{"input": "Makes sure the fast - path emits in order . [CODESPLIT] protected final void fastPathOrderedEmit ( U value , boolean delayError , Disposable disposable ) { final Observer < ? super V > observer = downstream ; final SimplePlainQueue < U > q = queue ; if ( wip . get ( ) == 0 && wip . compareAndSet ( 0 , 1 ) ) { if ( q . isEmpty ( ) ) { accept ( observer , value ) ; if ( leave ( - 1 ) == 0 ) { return ; } } else { q . offer ( value ) ; } } else { q . offer ( value ) ; if ( ! enter ( ) ) { return ; } } QueueDrainHelper . drainLoop ( q , observer , delayError , disposable , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends a termination notification . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / amb . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code amb } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > amb ( Iterable < ? extends ObservableSource < ? extends T > > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableAmb < T > ( null , sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mirrors the one ObservableSource in an array of several ObservableSources that first either emits an item or sends a termination notification . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / amb . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code ambArray } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > ambArray ( ObservableSource < ? extends T > ... sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; int len = sources . length ; if ( len == 0 ) { return empty ( ) ; } if ( len == 1 ) { return ( Observable < T > ) wrap ( sources [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new ObservableAmb < T > ( sources , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates elements of each ObservableSource provided via an Iterable sequence into a single sequence of elements without interleaving them . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concat . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concat ( Iterable < ? extends ObservableSource < ? extends T > > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return fromIterable ( sources ) . concatMapDelayError ( ( Function ) Functions . identity ( ) , bufferSize ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items emitted by each of the ObservableSources emitted by the source ObservableSource one after the other without interleaving them . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concat . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concat } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concat ( ObservableSource < ? extends ObservableSource < ? extends T > > sources , int prefetch ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMap ( sources , Functions . identity ( ) , prefetch , ErrorMode . IMMEDIATE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a variable number of ObservableSource sources . <p > Note : named this way because of overload conflict with concat ( ObservableSource&lt ; ObservableSource&gt ; ) <p > <img width = 640 height = 290 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatArray . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatArray ( ObservableSource < ? extends T > ... sources ) { if ( sources . length == 0 ) { return empty ( ) ; } else if ( sources . length == 1 ) { return wrap ( ( ObservableSource < T > ) sources [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new ObservableConcatMap ( fromArray ( sources ) , Functions . identity ( ) , bufferSize ( ) , ErrorMode . BOUNDARY ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a variable number of ObservableSource sources and delays errors from any of them till all terminate . <p > <img width = 640 height = 290 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatArray . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatArrayDelayError ( ObservableSource < ? extends T > ... sources ) { if ( sources . length == 0 ) { return empty ( ) ; } else if ( sources . length == 1 ) { return ( Observable < T > ) wrap ( sources [ 0 ] ) ; } return concatDelayError ( fromArray ( sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates an array of ObservableSources eagerly into a single stream of values . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatArrayEager . png alt = > <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source ObservableSources . The operator buffers the values emitted by these ObservableSources and then drains them in order each one after the previous one completes . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatArrayEager ( ObservableSource < ? extends T > ... sources ) { return concatArrayEager ( bufferSize ( ) , bufferSize ( ) , sources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates an array of ObservableSources eagerly into a single stream of values . <p > <img width = 640 height = 495 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatArrayEager . nn . png alt = > <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source ObservableSources . The operator buffers the values emitted by these ObservableSources and then drains them in order each one after the previous one completes . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatArrayEager ( int maxConcurrency , int prefetch , ObservableSource < ? extends T > ... sources ) { return fromArray ( sources ) . concatMapEagerDelayError ( ( Function ) Functions . identity ( ) , maxConcurrency , prefetch , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates an array of { [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatArrayEagerDelayError ( int maxConcurrency , int prefetch , ObservableSource < ? extends T > ... sources ) { return fromArray ( sources ) . concatMapEagerDelayError ( ( Function ) Functions . identity ( ) , maxConcurrency , prefetch , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the ObservableSource sequence of ObservableSources into a single sequence by subscribing to each inner ObservableSource one after the other one at a time and delays any errors till the all inner and the outer ObservableSources terminate . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatDelayError . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatDelayError ( ObservableSource < ? extends ObservableSource < ? extends T > > sources ) { return concatDelayError ( sources , bufferSize ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the ObservableSource sequence of ObservableSources into a single sequence by subscribing to each inner ObservableSource one after the other one at a time and delays any errors till the all inner and the outer ObservableSources terminate . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatDelayError . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatDelayError ( ObservableSource < ? extends ObservableSource < ? extends T > > sources , int prefetch , boolean tillTheEnd ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMap ( sources , Functions . identity ( ) , prefetch , tillTheEnd ? ErrorMode . END : ErrorMode . BOUNDARY ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates an ObservableSource sequence of ObservableSources eagerly into a single stream of values . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the emitted source ObservableSources as they are observed . The operator buffers the values emitted by these ObservableSources and then drains them in order each one after the previous one completes . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatEager . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatEager ( ObservableSource < ? extends ObservableSource < ? extends T > > sources , int maxConcurrency , int prefetch ) { return wrap ( sources ) . concatMapEager ( ( Function ) Functions . identity ( ) , maxConcurrency , prefetch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a sequence of ObservableSources eagerly into a single stream of values . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source ObservableSources . The operator buffers the values emitted by these ObservableSources and then drains them in order each one after the previous one completes . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatEager . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > concatEager ( Iterable < ? extends ObservableSource < ? extends T > > sources , int maxConcurrency , int prefetch ) { return fromIterable ( sources ) . concatMapEagerDelayError ( ( Function ) Functions . identity ( ) , maxConcurrency , prefetch , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits no items to the { @link Observer } and immediately invokes its { @link Observer#onComplete onComplete } method . <p > <img width = 640 height = 190 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / empty . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code empty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Observable < T > empty ( ) { return RxJavaPlugins . onAssembly ( ( Observable < T > ) ObservableEmpty . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that invokes an { @link Observer } s { @link Observer#onError onError } method when the Observer subscribes to it . <p > <img width = 640 height = 220 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / error . supplier . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code error } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > error ( Callable < ? extends Throwable > errorSupplier ) { ObjectHelper . requireNonNull ( errorSupplier , \"errorSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableError < T > ( errorSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an Array into an ObservableSource that emits the items in the Array . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / from . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromArray } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ NonNull public static < T > Observable < T > fromArray ( T ... items ) { ObjectHelper . requireNonNull ( items , \"items is null\" ) ; if ( items . length == 0 ) { return empty ( ) ; } else if ( items . length == 1 ) { return just ( items [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new ObservableFromArray < T > ( items ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an { @link Iterable } sequence into an ObservableSource that emits the items in the sequence . <p > <img width = 640 height = 186 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / fromIterable . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromIterable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > fromIterable ( Iterable < ? extends T > source ) { ObjectHelper . requireNonNull ( source , \"source is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableFromIterable < T > ( source ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an arbitrary Reactive - Streams Publisher into an Observable . <p > <img width = 640 height = 344 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / fromPublisher . o . png alt = > <p > The { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > fromPublisher ( Publisher < ? extends T > publisher ) { ObjectHelper . requireNonNull ( publisher , \"publisher is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableFromPublisher < T > ( publisher ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a cold synchronous and stateless generator of values . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / generate . 2 . png alt = > <p > Note that the { @link Emitter#onNext } { @link Emitter#onError } and { @link Emitter#onComplete } methods provided to the function via the { @link Emitter } instance should be called synchronously never concurrently and only while the function body is executing . Calling them from multiple threads or outside the function call is not supported and leads to an undefined behavior . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code generate } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > generate ( final Consumer < Emitter < T > > generator ) { ObjectHelper . requireNonNull ( generator , \"generator is null\" ) ; return generate ( Functions . < Object > nullSupplier ( ) , ObservableInternalHelper . simpleGenerator ( generator ) , Functions . < Object > emptyConsumer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a cold synchronous and stateful generator of values . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / generate . 2 . png alt = > <p > Note that the { @link Emitter#onNext } { @link Emitter#onError } and { @link Emitter#onComplete } methods provided to the function via the { @link Emitter } instance should be called synchronously never concurrently and only while the function body is executing . Calling them from multiple threads or outside the function call is not supported and leads to an undefined behavior . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code generate } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , S > Observable < T > generate ( Callable < S > initialState , BiFunction < S , Emitter < T > , S > generator ) { return generate ( initialState , generator , Functions . emptyConsumer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits a { @code 0L } after the { @code initialDelay } and ever increasing numbers after each { @code period } of time thereafter on a specified { @link Scheduler } . <p > <img width = 640 height = 200 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timer . ps . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Observable < Long > interval ( long initialDelay , long period , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableInterval ( Math . max ( 0L , initialDelay ) , Math . max ( 0L , period ) , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits a sequential number every specified interval of time . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / interval . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code interval } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public static Observable < Long > interval ( long period , TimeUnit unit ) { return interval ( period , period , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits a sequential number every specified interval of time on a specified Scheduler . <p > <img width = 640 height = 200 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / interval . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Observable < Long > interval ( long period , TimeUnit unit , Scheduler scheduler ) { return interval ( period , period , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals a range of long values the first after some initial delay and the rest periodically after . <p > The sequence completes immediately after the last value ( start + count - 1 ) has been reached . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / intervalRange . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public static Observable < Long > intervalRange ( long start , long count , long initialDelay , long period , TimeUnit unit ) { return intervalRange ( start , count , initialDelay , period , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals a range of long values the first after some initial delay and the rest periodically after . <p > The sequence completes immediately after the last value ( start + count - 1 ) has been reached . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / intervalRange . s . png alt = > * <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > you provide the { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Observable < Long > intervalRange ( long start , long count , long initialDelay , long period , TimeUnit unit , Scheduler scheduler ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } if ( count == 0L ) { return Observable . < Long > empty ( ) . delay ( initialDelay , unit , scheduler ) ; } long end = start + ( count - 1 ) ; if ( start > 0 && end < 0 ) { throw new IllegalArgumentException ( \"Overflow! start + count is bigger than Long.MAX_VALUE\" ) ; } ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableIntervalRange ( start , end , Math . max ( 0L , initialDelay ) , Math . max ( 0L , period ) , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that signals the given ( constant reference ) item and then completes . <p > <img width = 640 height = 290 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / just . item . png alt = > <p > Note that the item is taken and re - emitted as is and not computed by any means by { @code just } . Use { @link #fromCallable ( Callable ) } to generate a single item on demand ( when { @code Observer } s subscribe to it ) . <p > See the multi - parameter overloads of { @code just } to emit more than one ( constant reference ) items one after the other . Use { @link #fromArray ( Object ... ) } to emit an arbitrary number of items that are known upfront . <p > To emit the items of an { @link Iterable } sequence ( such as a { @link java . util . List } ) use { @link #fromIterable ( Iterable ) } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code just } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > just ( T item ) { ObjectHelper . requireNonNull ( item , \"item is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableJust < T > ( item ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an Iterable of ObservableSources into one ObservableSource without any transformation while limiting the number of concurrent subscriptions to these ObservableSources . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > You can combine the items emitted by multiple ObservableSources so that they appear as a single ObservableSource by using the { @code merge } method . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code merge } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If any of the source { @code ObservableSource } s signal a { @code Throwable } via { @code onError } the resulting { @code Observable } terminates with that { @code Throwable } and all other source { @code ObservableSource } s are disposed . If more than one { @code ObservableSource } signals an error the resulting { @code Observable } may terminate with the first one s error or depending on the concurrency of the sources may terminate with a { @code CompositeException } containing two or more of the various error signals . { @code Throwable } s that didn t make into the composite will be sent ( individually ) to the global error handler via { @link RxJavaPlugins#onError ( Throwable ) } method as { @code UndeliverableException } errors . Similarly { @code Throwable } s signaled by source ( s ) after the returned { @code Observable } has been disposed or terminated with a ( composite ) error will be sent to the same global error handler . Use { @link #mergeDelayError ( Iterable int int ) } to merge sources and terminate only when all source { @code ObservableSource } s have completed or failed with an error . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > merge ( Iterable < ? extends ObservableSource < ? extends T > > sources , int maxConcurrency , int bufferSize ) { return fromIterable ( sources ) . flatMap ( ( Function ) Functions . identity ( ) , false , maxConcurrency , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an Iterable of ObservableSources into one ObservableSource without any transformation while limiting the number of concurrent subscriptions to these ObservableSources . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > You can combine the items emitted by multiple ObservableSources so that they appear as a single ObservableSource by using the { @code merge } method . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeArray } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If any of the source { @code ObservableSource } s signal a { @code Throwable } via { @code onError } the resulting { @code Observable } terminates with that { @code Throwable } and all other source { @code ObservableSource } s are disposed . If more than one { @code ObservableSource } signals an error the resulting { @code Observable } may terminate with the first one s error or depending on the concurrency of the sources may terminate with a { @code CompositeException } containing two or more of the various error signals . { @code Throwable } s that didn t make into the composite will be sent ( individually ) to the global error handler via { @link RxJavaPlugins#onError ( Throwable ) } method as { @code UndeliverableException } errors . Similarly { @code Throwable } s signaled by source ( s ) after the returned { @code Observable } has been disposed or terminated with a ( composite ) error will be sent to the same global error handler . Use { @link #mergeArrayDelayError ( int int ObservableSource ... ) } to merge sources and terminate only when all source { @code ObservableSource } s have completed or failed with an error . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > mergeArray ( int maxConcurrency , int bufferSize , ObservableSource < ? extends T > ... sources ) { return fromArray ( sources ) . flatMap ( ( Function ) Functions . identity ( ) , false , maxConcurrency , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an ObservableSource that emits ObservableSources into a single ObservableSource that emits the items emitted by those ObservableSources without any transformation . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . oo . png alt = > <p > You can combine the items emitted by multiple ObservableSources so that they appear as a single ObservableSource by using the { @code merge } method . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code merge } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If any of the source { @code ObservableSource } s signal a { @code Throwable } via { @code onError } the resulting { @code Observable } terminates with that { @code Throwable } and all other source { @code ObservableSource } s are disposed . If more than one { @code ObservableSource } signals an error the resulting { @code Observable } may terminate with the first one s error or depending on the concurrency of the sources may terminate with a { @code CompositeException } containing two or more of the various error signals . { @code Throwable } s that didn t make into the composite will be sent ( individually ) to the global error handler via { @link RxJavaPlugins#onError ( Throwable ) } method as { @code UndeliverableException } errors . Similarly { @code Throwable } s signaled by source ( s ) after the returned { @code Observable } has been disposed or terminated with a ( composite ) error will be sent to the same global error handler . Use { @link #mergeDelayError ( ObservableSource ) } to merge sources and terminate only when all source { @code ObservableSource } s have completed or failed with an error . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public static < T > Observable < T > merge ( ObservableSource < ? extends ObservableSource < ? extends T > > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableFlatMap ( sources , Functions . identity ( ) , false , Integer . MAX_VALUE , bufferSize ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an Array of ObservableSources into one ObservableSource without any transformation . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . io . png alt = > <p > You can combine items emitted by multiple ObservableSources so that they appear as a single ObservableSource by using the { @code merge } method . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeArray } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If any of the source { @code ObservableSource } s signal a { @code Throwable } via { @code onError } the resulting { @code Observable } terminates with that { @code Throwable } and all other source { @code ObservableSource } s are disposed . If more than one { @code ObservableSource } signals an error the resulting { @code Observable } may terminate with the first one s error or depending on the concurrency of the sources may terminate with a { @code CompositeException } containing two or more of the various error signals . { @code Throwable } s that didn t make into the composite will be sent ( individually ) to the global error handler via { @link RxJavaPlugins#onError ( Throwable ) } method as { @code UndeliverableException } errors . Similarly { @code Throwable } s signaled by source ( s ) after the returned { @code Observable } has been disposed or terminated with a ( composite ) error will be sent to the same global error handler . Use { @link #mergeArrayDelayError ( ObservableSource ... ) } to merge sources and terminate only when all source { @code ObservableSource } s have completed or failed with an error . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > mergeArray ( ObservableSource < ? extends T > ... sources ) { return fromArray ( sources ) . flatMap ( ( Function ) Functions . identity ( ) , sources . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens three ObservableSources into one ObservableSource in a way that allows an Observer to receive all successfully emitted items from all of the source ObservableSources without being interrupted by an error notification from one of them . <p > This behaves like { @link #merge ( ObservableSource ObservableSource ObservableSource ) } except that if any of the merged ObservableSources notify of an error via { @link Observer#onError onError } { @code mergeDelayError } will refrain from propagating that error notification until all of the merged ObservableSources have finished emitting items . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeDelayError . png alt = > <p > Even if multiple merged ObservableSources send { @code onError } notifications { @code mergeDelayError } will only invoke the { @code onError } method of its Observers once . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > mergeDelayError ( ObservableSource < ? extends T > source1 , ObservableSource < ? extends T > source2 , ObservableSource < ? extends T > source3 ) { ObjectHelper . requireNonNull ( source1 , \"source1 is null\" ) ; ObjectHelper . requireNonNull ( source2 , \"source2 is null\" ) ; ObjectHelper . requireNonNull ( source3 , \"source3 is null\" ) ; return fromArray ( source1 , source2 , source3 ) . flatMap ( ( Function ) Functions . identity ( ) , true , 3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that never sends any items or notifications to an { @link Observer } . <p > <img width = 640 height = 185 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / never . png alt = > <p > This ObservableSource is useful primarily for testing purposes . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code never } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Observable < T > never ( ) { return RxJavaPlugins . onAssembly ( ( Observable < T > ) ObservableNever . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits a sequence of Integers within a specified range . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / range . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code range } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static Observable < Integer > range ( final int start , final int count ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } if ( count == 0 ) { return empty ( ) ; } if ( count == 1 ) { return just ( start ) ; } if ( ( long ) start + ( count - 1 ) > Integer . MAX_VALUE ) { throw new IllegalArgumentException ( \"Integer overflow\" ) ; } return RxJavaPlugins . onAssembly ( new ObservableRange ( start , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits a sequence of Longs within a specified range . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / rangeLong . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code rangeLong } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static Observable < Long > rangeLong ( long start , long count ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } if ( count == 0 ) { return empty ( ) ; } if ( count == 1 ) { return just ( start ) ; } long end = start + ( count - 1 ) ; if ( start > 0 && end < 0 ) { throw new IllegalArgumentException ( \"Overflow! start + count is bigger than Long.MAX_VALUE\" ) ; } return RxJavaPlugins . onAssembly ( new ObservableRangeLong ( start , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two ObservableSource sequences are the same by comparing the items emitted by each ObservableSource pairwise based on the results of a specified equality function . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( ObservableSource < ? extends T > source1 , ObservableSource < ? extends T > source2 , BiPredicate < ? super T , ? super T > isEqual ) { return sequenceEqual ( source1 , source2 , isEqual , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two ObservableSource sequences are the same by comparing the items emitted by each ObservableSource pairwise based on the results of a specified equality function . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( ObservableSource < ? extends T > source1 , ObservableSource < ? extends T > source2 , BiPredicate < ? super T , ? super T > isEqual , int bufferSize ) { ObjectHelper . requireNonNull ( source1 , \"source1 is null\" ) ; ObjectHelper . requireNonNull ( source2 , \"source2 is null\" ) ; ObjectHelper . requireNonNull ( isEqual , \"isEqual is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSequenceEqualSingle < T > ( source1 , source2 , isEqual , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two ObservableSource sequences are the same by comparing the items emitted by each ObservableSource pairwise . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( ObservableSource < ? extends T > source1 , ObservableSource < ? extends T > source2 , int bufferSize ) { return sequenceEqual ( source1 , source2 , ObjectHelper . equalsPredicate ( ) , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an ObservableSource that emits ObservableSources into an ObservableSource that emits the items emitted by the most recently emitted of those ObservableSources . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchDo . png alt = > <p > { @code switchOnNext } subscribes to an ObservableSource that emits ObservableSources . Each time it observes one of these emitted ObservableSources the ObservableSource returned by { @code switchOnNext } begins emitting the items emitted by that ObservableSource . When a new ObservableSource is emitted { @code switchOnNext } stops emitting items from the earlier - emitted ObservableSource and begins emitting items from the new one . <p > The resulting ObservableSource completes if both the outer ObservableSource and the last inner ObservableSource if any complete . If the outer ObservableSource signals an onError the inner ObservableSource is disposed and the error delivered in - sequence . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchOnNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > switchOnNext ( ObservableSource < ? extends ObservableSource < ? extends T > > sources , int bufferSize ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMap ( sources , Functions . identity ( ) , bufferSize , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an ObservableSource that emits ObservableSources into an ObservableSource that emits the items emitted by the most recently emitted of those ObservableSources and delays any exception until all ObservableSources terminate . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchOnNextDelayError . png alt = > <p > { @code switchOnNext } subscribes to an ObservableSource that emits ObservableSources . Each time it observes one of these emitted ObservableSources the ObservableSource returned by { @code switchOnNext } begins emitting the items emitted by that ObservableSource . When a new ObservableSource is emitted { @code switchOnNext } stops emitting items from the earlier - emitted ObservableSource and begins emitting items from the new one . <p > The resulting ObservableSource completes if both the main ObservableSource and the last inner ObservableSource if any complete . If the main ObservableSource signals an onError the termination of the last inner ObservableSource will emit that error as is or wrapped into a CompositeException along with the other possible errors the former inner ObservableSources signalled . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchOnNextDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > switchOnNextDelayError ( ObservableSource < ? extends ObservableSource < ? extends T > > sources , int prefetch ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMap ( sources , Functions . identity ( ) , prefetch , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an Observable by wrapping an ObservableSource <em > which has to be implemented according to the Reactive - Streams - based Observable specification by handling disposal correctly ; no safeguards are provided by the Observable itself< / em > . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > unsafeCreate ( ObservableSource < T > onSubscribe ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; if ( onSubscribe instanceof Observable ) { throw new IllegalArgumentException ( \"unsafeCreate(Observable) should be upgraded\" ) ; } return RxJavaPlugins . onAssembly ( new ObservableFromUnsafeSource < T > ( onSubscribe ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs an ObservableSource that creates a dependent resource object which is disposed of when the downstream calls dispose () . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / using . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code using } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , D > Observable < T > using ( Callable < ? extends D > resourceSupplier , Function < ? super D , ? extends ObservableSource < ? extends T > > sourceSupplier , Consumer < ? super D > disposer ) { return using ( resourceSupplier , sourceSupplier , disposer , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs an ObservableSource that creates a dependent resource object which is disposed of just before termination if you have set { @code disposeEagerly } to { @code true } and a dispose () call does not occur before termination . Otherwise resource disposal will occur on a dispose () call . Eager disposal is particularly appropriate for a synchronous ObservableSource that reuses resources . { @code disposeAction } will only be called once per subscription . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / using . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code using } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , D > Observable < T > using ( Callable < ? extends D > resourceSupplier , Function < ? super D , ? extends ObservableSource < ? extends T > > sourceSupplier , Consumer < ? super D > disposer , boolean eager ) { ObjectHelper . requireNonNull ( resourceSupplier , \"resourceSupplier is null\" ) ; ObjectHelper . requireNonNull ( sourceSupplier , \"sourceSupplier is null\" ) ; ObjectHelper . requireNonNull ( disposer , \"disposer is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableUsing < T , D > ( resourceSupplier , sourceSupplier , disposer , eager ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps an ObservableSource into an Observable if not already an Observable . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Observable < T > wrap ( ObservableSource < T > source ) { ObjectHelper . requireNonNull ( source , \"source is null\" ) ; if ( source instanceof Observable ) { return RxJavaPlugins . onAssembly ( ( Observable < T > ) source ) ; } return RxJavaPlugins . onAssembly ( new ObservableFromUnsafeSource < T > ( source ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the results of a specified combiner function applied to combinations of items emitted in sequence by an Iterable of other ObservableSources . <p > { @code zip } applies this function in strict sequence so the first item emitted by the new ObservableSource will be the result of the function applied to the first item emitted by each of the source ObservableSources ; the second item emitted by the new ObservableSource will be the result of the function applied to the second item emitted by each of those ObservableSources ; and so forth . <p > The resulting { @code ObservableSource<R > } returned from { @code zip } will invoke { @code onNext } as many times as the number of { @code onNext } invocations of the source ObservableSource that emits the fewest items . <p > The operator subscribes to its sources in order they are specified and completes eagerly if one of the sources is shorter than the rest while disposing the other sources . Therefore it is possible those other sources will never be able to run to completion ( and thus not calling { @code doOnComplete () } ) . This can also happen if the sources are exactly the same length ; if source A completes and B has been consumed and is about to complete the operator detects A won t be sending further values and it will dispose B immediately . For example : <pre > <code > zip ( Arrays . asList ( range ( 1 5 ) . doOnComplete ( action1 ) range ( 6 5 ) . doOnComplete ( action2 )) ( a ) - &gt ; a ) < / code > < / pre > { @code action1 } will be called but { @code action2 } won t . <br > To work around this termination property use { @link #doOnDispose ( Action ) } as well or use { @code using () } to do cleanup in case of completion or a dispose () call . <p > Note on method signature : since Java doesn t allow creating a generic array with { @code new T [] } the implementation of this operator has to create an { @code Object [] } instead . Unfortunately a { @code Function<Integer [] R > } passed to the method would trigger a { @code ClassCastException } . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , R > Observable < R > zip ( Iterable < ? extends ObservableSource < ? extends T > > sources , Function < ? super Object [ ] , ? extends R > zipper ) { ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableZip < T , R > ( null , sources , zipper , bufferSize ( ) , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the results of a specified combiner function applied to combinations of <i > n< / i > items emitted in sequence by the <i > n< / i > ObservableSources emitted by a specified ObservableSource . <p > { @code zip } applies this function in strict sequence so the first item emitted by the new ObservableSource will be the result of the function applied to the first item emitted by each of the ObservableSources emitted by the source ObservableSource ; the second item emitted by the new ObservableSource will be the result of the function applied to the second item emitted by each of those ObservableSources ; and so forth . <p > The resulting { @code ObservableSource<R > } returned from { @code zip } will invoke { @code onNext } as many times as the number of { @code onNext } invocations of the source ObservableSource that emits the fewest items . <p > The operator subscribes to its sources in order they are specified and completes eagerly if one of the sources is shorter than the rest while disposing the other sources . Therefore it is possible those other sources will never be able to run to completion ( and thus not calling { @code doOnComplete () } ) . This can also happen if the sources are exactly the same length ; if source A completes and B has been consumed and is about to complete the operator detects A won t be sending further values and it will dispose B immediately . For example : <pre > <code > zip ( just ( range ( 1 5 ) . doOnComplete ( action1 ) range ( 6 5 ) . doOnComplete ( action2 )) ( a ) - &gt ; a ) < / code > < / pre > { @code action1 } will be called but { @code action2 } won t . <br > To work around this termination property use { @link #doOnDispose ( Action ) } as well or use { @code using () } to do cleanup in case of completion or a dispose () call . <p > Note on method signature : since Java doesn t allow creating a generic array with { @code new T [] } the implementation of this operator has to create an { @code Object [] } instead . Unfortunately a { @code Function<Integer [] R > } passed to the method would trigger a { @code ClassCastException } . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , R > Observable < R > zip ( ObservableSource < ? extends ObservableSource < ? extends T > > sources , final Function < ? super Object [ ] , ? extends R > zipper ) { ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableToList ( sources , 16 ) . flatMap ( ObservableInternalHelper . zipIterable ( zipper ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the results of a specified combiner function applied to combinations of items emitted in sequence by an array of other ObservableSources . <p > { @code zip } applies this function in strict sequence so the first item emitted by the new ObservableSource will be the result of the function applied to the first item emitted by each of the source ObservableSources ; the second item emitted by the new ObservableSource will be the result of the function applied to the second item emitted by each of those ObservableSources ; and so forth . <p > The resulting { @code ObservableSource<R > } returned from { @code zip } will invoke { @code onNext } as many times as the number of { @code onNext } invocations of the source ObservableSource that emits the fewest items . <p > The operator subscribes to its sources in order they are specified and completes eagerly if one of the sources is shorter than the rest while disposing the other sources . Therefore it is possible those other sources will never be able to run to completion ( and thus not calling { @code doOnComplete () } ) . This can also happen if the sources are exactly the same length ; if source A completes and B has been consumed and is about to complete the operator detects A won t be sending further values and it will dispose B immediately . For example : <pre > <code > zip ( new ObservableSource [] { range ( 1 5 ) . doOnComplete ( action1 ) range ( 6 5 ) . doOnComplete ( action2 ) } ( a ) - &gt ; a ) < / code > < / pre > { @code action1 } will be called but { @code action2 } won t . <br > To work around this termination property use { @link #doOnDispose ( Action ) } as well or use { @code using () } to do cleanup in case of completion or a dispose () call . <p > Note on method signature : since Java doesn t allow creating a generic array with { @code new T [] } the implementation of this operator has to create an { @code Object [] } instead . Unfortunately a { @code Function<Integer [] R > } passed to the method would trigger a { @code ClassCastException } . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , R > Observable < R > zipArray ( Function < ? super Object [ ] , ? extends R > zipper , boolean delayError , int bufferSize , ObservableSource < ? extends T > ... sources ) { if ( sources . length == 0 ) { return empty ( ) ; } ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableZip < T , R > ( sources , null , zipper , bufferSize , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean that indicates whether all of the items emitted by the source ObservableSource satisfy a condition . <p > <img width = 640 height = 264 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / all . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code all } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > all ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableAllSingle < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mirrors the ObservableSource ( current or provided ) that first either emits an item or sends a termination notification . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / ambWith . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code ambWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > ambWith ( ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return ambArray ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits { @code true } if any item emitted by the source ObservableSource satisfies a specified condition otherwise { @code false } . <em > Note : < / em > this always emits { @code false } if the source ObservableSource is empty . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / any . 2 . png alt = > <p > In Rx . Net this is the { @code any } Observer but we renamed it in RxJava to better match Java naming idioms . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code any } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > any ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableAnySingle < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first item emitted by this { @code Observable } or throws { @code NoSuchElementException } if it emits no items . <p > <img width = 640 height = 412 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / blockingFirst . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingFirst } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingFirst ( ) { BlockingFirstObserver < T > observer = new BlockingFirstObserver < T > ( ) ; subscribe ( observer ) ; T v = observer . blockingGet ( ) ; if ( v != null ) { return v ; } throw new NoSuchElementException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes the upstream { @code Observable } in a blocking fashion and invokes the given { @code Consumer } with each upstream item on the <em > current thread< / em > until the upstream terminates . <p > <img width = 640 height = 330 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / blockingForEach . o . png alt = > <p > <em > Note : < / em > the method will only return if the upstream terminates or the current thread is interrupted . <p > This method executes the { @code Consumer } on the current thread while { @link #subscribe ( Consumer ) } executes the consumer on the original caller thread of the sequence . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingForEach } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingForEach ( Consumer < ? super T > onNext ) { Iterator < T > it = blockingIterable ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { try { onNext . accept ( it . next ( ) ) ; } catch ( Throwable e ) { Exceptions . throwIfFatal ( e ) ; ( ( Disposable ) it ) . dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts this { @code Observable } into an { @link Iterable } . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / blockingIterable . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingIterable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Iterable < T > blockingIterable ( int bufferSize ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return new BlockingObservableIterable < T > ( this , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last item emitted by this { @code Observable } or throws { @code NoSuchElementException } if this { @code Observable } emits no items . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / blockingLast . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingLast } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingLast ( ) { BlockingLastObserver < T > observer = new BlockingLastObserver < T > ( ) ; subscribe ( observer ) ; T v = observer . blockingGet ( ) ; if ( v != null ) { return v ; } throw new NoSuchElementException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @link Iterable } that always returns the item most recently emitted by this { @code Observable } . <p > <img width = 640 height = 426 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / blockingMostRecent . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingMostRecent } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Iterable < T > blockingMostRecent ( T initialValue ) { return new BlockingObservableMostRecent < T > ( this , initialValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this { @code Observable } completes after emitting a single item return that item otherwise throw a { @code NoSuchElementException } . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / blockingSingle . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingSingle } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingSingle ( ) { T v = singleElement ( ) . blockingGet ( ) ; if ( v == null ) { throw new NoSuchElementException ( ) ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this { @code Observable } completes after emitting a single item return that item ; if it emits more than one item throw an { @code IllegalArgumentException } ; if it emits no items return a default value . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / blockingSingleDefault . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingSingle } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingSingle ( T defaultItem ) { return single ( defaultItem ) . blockingGet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Future } representing the only value emitted by this { @code Observable } . <p > <img width = 640 height = 312 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / toFuture . o . png alt = > <p > If the { @link Observable } emits more than one item { @link java . util . concurrent . Future } will receive an { @link java . lang . IndexOutOfBoundsException } . If the { @link Observable } is empty { @link java . util . concurrent . Future } will receive an { @link java . util . NoSuchElementException } . The { @code Observable } source has to terminate in order for the returned { @code Future } to terminate as well . <p > If the { @code Observable } may emit more than one item use { @code Observable . toList () . toFuture () } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toFuture } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Future < T > toFuture ( ) { return subscribeWith ( new FutureObserver < T > ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given callbacks <strong > on the current thread< / strong > . <p > <img width = 640 height = 393 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / blockingSubscribe . o . 1 . png alt = > <p > If the { [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingSubscribe ( Consumer < ? super T > onNext ) { ObservableBlockingSubscribe . subscribe ( this , onNext , Functions . ON_ERROR_MISSING , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given callbacks <strong > on the current thread< / strong > . <p > <img width = 640 height = 396 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / blockingSubscribe . o . 2 . png alt = > <p > Note that calling this method will block the caller thread until the upstream terminates normally or with an error . Therefore calling this method from special threads such as the Android Main Thread or the Swing Event Dispatch Thread is not recommended . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingSubscribe ( Consumer < ? super T > onNext , Consumer < ? super Throwable > onError ) { ObservableBlockingSubscribe . subscribe ( this , onNext , onError , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given callbacks <strong > on the current thread< / strong > . <p > <img width = 640 height = 394 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / blockingSubscribe . o . png alt = > <p > Note that calling this method will block the caller thread until the upstream terminates normally or with an error . Therefore calling this method from special threads such as the Android Main Thread or the Swing Event Dispatch Thread is not recommended . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingSubscribe ( Consumer < ? super T > onNext , Consumer < ? super Throwable > onError , Action onComplete ) { ObservableBlockingSubscribe . subscribe ( this , onNext , onError , onComplete ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the { [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingSubscribe ( Observer < ? super T > observer ) { ObservableBlockingSubscribe . subscribe ( this , observer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping buffers each containing { @code count } items . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer3 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < List < T > > buffer ( int count ) { return buffer ( count , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits buffers every { @code skip } items each containing { @code count } items . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer4 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < List < T > > buffer ( int count , int skip ) { return buffer ( count , skip , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits buffers every { @code skip } items each containing { @code count } items . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer4 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U extends Collection < ? super T > > Observable < U > buffer ( int count , int skip , Callable < U > bufferSupplier ) { ObjectHelper . verifyPositive ( count , \"count\" ) ; ObjectHelper . verifyPositive ( skip , \"skip\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableBuffer < T , U > ( this , count , skip , bufferSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping buffers each containing { @code count } items . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer3 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U extends Collection < ? super T > > Observable < U > buffer ( int count , Callable < U > bufferSupplier ) { return buffer ( count , count , bufferSupplier ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource starts a new buffer periodically as determined by the { @code timeskip } argument . It emits each buffer after a fixed timespan specified by the { @code timespan } argument . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer7 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < List < T > > buffer ( long timespan , long timeskip , TimeUnit unit ) { return buffer ( timespan , timeskip , unit , Schedulers . computation ( ) , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource starts a new buffer periodically as determined by the { @code timeskip } argument and on the specified { @code scheduler } . It emits each buffer after a fixed timespan specified by the { @code timespan } argument . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer7 . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final < U extends Collection < ? super T > > Observable < U > buffer ( long timespan , long timeskip , TimeUnit unit , Scheduler scheduler , Callable < U > bufferSupplier ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableBufferTimed < T , U > ( this , timespan , timeskip , unit , scheduler , bufferSupplier , Integer . MAX_VALUE , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping buffers each of a fixed duration specified by the { @code timespan } argument or a maximum size specified by the { @code count } argument ( whichever is reached first ) . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer6 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < List < T > > buffer ( long timespan , TimeUnit unit , int count ) { return buffer ( timespan , unit , Schedulers . computation ( ) , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping buffers each of a fixed duration specified by the { @code timespan } argument as measured on the specified { @code scheduler } or a maximum size specified by the { @code count } argument ( whichever is reached first ) . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer6 . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < List < T > > buffer ( long timespan , TimeUnit unit , Scheduler scheduler , int count ) { return buffer ( timespan , unit , scheduler , count , ArrayListSupplier . < T > asCallable ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping buffers each of a fixed duration specified by the { @code timespan } argument as measured on the specified { @code scheduler } or a maximum size specified by the { @code count } argument ( whichever is reached first ) . When the source ObservableSource completes the resulting ObservableSource emits the current buffer and propagates the notification from the source ObservableSource . Note that if the source ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer6 . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final < U extends Collection < ? super T > > Observable < U > buffer ( long timespan , TimeUnit unit , Scheduler scheduler , int count , Callable < U > bufferSupplier , boolean restartTimerOnMaxSize ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; ObjectHelper . verifyPositive ( count , \"count\" ) ; return RxJavaPlugins . onAssembly ( new ObservableBufferTimed < T , U > ( this , timespan , timespan , unit , scheduler , bufferSupplier , count , restartTimerOnMaxSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits buffers that it creates when the specified { @code openingIndicator } ObservableSource emits an item and closes when the ObservableSource returned from { @code closingIndicator } emits an item . If any of the source ObservableSource { @code openingIndicator } or { @code closingIndicator } issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 470 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < TOpening , TClosing > Observable < List < T > > buffer ( ObservableSource < ? extends TOpening > openingIndicator , Function < ? super TOpening , ? extends ObservableSource < ? extends TClosing > > closingIndicator ) { return buffer ( openingIndicator , closingIndicator , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits buffers that it creates when the specified { @code openingIndicator } ObservableSource emits an item and closes when the ObservableSource returned from { @code closingIndicator } emits an item . If any of the source ObservableSource { @code openingIndicator } or { @code closingIndicator } issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 470 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < TOpening , TClosing , U extends Collection < ? super T > > Observable < U > buffer ( ObservableSource < ? extends TOpening > openingIndicator , Function < ? super TOpening , ? extends ObservableSource < ? extends TClosing > > closingIndicator , Callable < U > bufferSupplier ) { ObjectHelper . requireNonNull ( openingIndicator , \"openingIndicator is null\" ) ; ObjectHelper . requireNonNull ( closingIndicator , \"closingIndicator is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableBufferBoundary < T , U , TOpening , TClosing > ( this , openingIndicator , closingIndicator , bufferSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits non - overlapping buffered items from the source ObservableSource each time the specified boundary ObservableSource emits an item . <p > <img width = 640 height = 395 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer8 . png alt = > <p > Completion of either the source or the boundary ObservableSource causes the returned ObservableSource to emit the latest buffer and complete . If either the source ObservableSource or the boundary ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Observable < List < T > > buffer ( ObservableSource < B > boundary ) { return buffer ( boundary , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits non - overlapping buffered items from the source ObservableSource each time the specified boundary ObservableSource emits an item . <p > <img width = 640 height = 395 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer8 . png alt = > <p > Completion of either the source or the boundary ObservableSource causes the returned ObservableSource to emit the latest buffer and complete . If either the source ObservableSource or the boundary ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Observable < List < T > > buffer ( ObservableSource < B > boundary , final int initialCapacity ) { ObjectHelper . verifyPositive ( initialCapacity , \"initialCapacity\" ) ; return buffer ( boundary , Functions . < T > createArrayList ( initialCapacity ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits non - overlapping buffered items from the source ObservableSource each time the specified boundary ObservableSource emits an item . <p > <img width = 640 height = 395 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer8 . png alt = > <p > Completion of either the source or the boundary ObservableSource causes the returned ObservableSource to emit the latest buffer and complete . If either the source ObservableSource or the boundary ObservableSource issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B , U extends Collection < ? super T > > Observable < U > buffer ( ObservableSource < B > boundary , Callable < U > bufferSupplier ) { ObjectHelper . requireNonNull ( boundary , \"boundary is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableBufferExactBoundary < T , U , B > ( this , boundary , bufferSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits buffers of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping buffers . It emits the current buffer and replaces it with a new buffer whenever the ObservableSource produced by the specified { @code boundarySupplier } emits an item . <p > <img width = 640 height = 395 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer1 . png alt = > <p > If either the source { @code ObservableSource } or the boundary { @code ObservableSource } issues an { @code onError } notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Observable < List < T > > buffer ( Callable < ? extends ObservableSource < B > > boundarySupplier ) { return buffer ( boundarySupplier , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that subscribes to this ObservableSource lazily caches all of its events and replays them in the same order as received to all the downstream subscribers . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / cacheWithInitialCapacity . o . png alt = > <p > This is useful when you want an ObservableSource to cache responses and you can t control the subscribe / dispose behavior of all the { @link Observer } s . <p > The operator subscribes only when the first downstream subscriber subscribes and maintains a single subscription towards this ObservableSource . In contrast the operator family of { @link #replay () } that return a { @link ConnectableObservable } require an explicit call to { @link ConnectableObservable#connect () } . <p > <em > Note : < / em > You sacrifice the ability to dispose the origin when you use the { @code cache } Observer so be careful not to use this Observer on ObservableSources that emit an infinite or very large number of items that will use up memory . A possible workaround is to apply takeUntil with a predicate or another source before ( and perhaps after ) the application of cache () . <pre > <code > AtomicBoolean shouldStop = new AtomicBoolean () ; [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > cacheWithInitialCapacity ( int initialCapacity ) { ObjectHelper . verifyPositive ( initialCapacity , \"initialCapacity\" ) ; return RxJavaPlugins . onAssembly ( new ObservableCache < T > ( this , initialCapacity ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects items emitted by the finite source ObservableSource into a single mutable data structure and returns a Single that emits this structure . <p > <img width = 640 height = 330 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / collect . 2 . png alt = > <p > This is a simplified version of { @code reduce } that does not need to return the state on each pass . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulator object to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code collect } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Single < U > collect ( Callable < ? extends U > initialValueSupplier , BiConsumer < ? super U , ? super T > collector ) { ObjectHelper . requireNonNull ( initialValueSupplier , \"initialValueSupplier is null\" ) ; ObjectHelper . requireNonNull ( collector , \"collector is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableCollectSingle < T , U > ( this , initialValueSupplier , collector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects items emitted by the finite source ObservableSource into a single mutable data structure and returns a Single that emits this structure . <p > <img width = 640 height = 330 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / collectInto . o . png alt = > <p > This is a simplified version of { @code reduce } that does not need to return the state on each pass . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulator object to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code collectInto } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Single < U > collectInto ( final U initialValue , BiConsumer < ? super U , ? super T > collector ) { ObjectHelper . requireNonNull ( initialValue , \"initialValue is null\" ) ; return collect ( Functions . justCallable ( initialValue ) , collector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform an ObservableSource by applying a particular Transformer function to it . <p > This method operates on the ObservableSource itself whereas { @link #lift } operates on the ObservableSource s Observers . <p > If the operator you are creating is designed to act on the individual items emitted by a source ObservableSource use { @link #lift } . If your operator is designed to transform the source ObservableSource as a whole ( for instance by applying a particular set of existing RxJava operators to it ) use { @code compose } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code compose } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > compose ( ObservableTransformer < ? super T , ? extends R > composer ) { return wrap ( ( ( ObservableTransformer < T , R > ) ObjectHelper . requireNonNull ( composer , \"composer is null\" ) ) . apply ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new Observable that emits items resulting from applying a function that you supply to each item emitted by the source ObservableSource where that function returns an ObservableSource and then emitting the items that result from concatenating those resulting ObservableSources . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMap . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMap ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper ) { return concatMap ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new Observable that emits items resulting from applying a function that you supply to each item emitted by the source ObservableSource where that function returns an ObservableSource and then emitting the items that result from concatenating those resulting ObservableSources . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMap . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMap ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; if ( this instanceof ScalarCallable ) { @ SuppressWarnings ( \"unchecked\" ) T v = ( ( ScalarCallable < T > ) this ) . call ( ) ; if ( v == null ) { return empty ( ) ; } return ObservableScalarXMap . scalarXMap ( v , mapper ) ; } return RxJavaPlugins . onAssembly ( new ObservableConcatMap < T , R > ( this , mapper , prefetch , ErrorMode . IMMEDIATE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each of the items into an ObservableSource subscribes to them one after the other one at a time and emits their values in order while delaying any error from either this or any of the inner ObservableSources till all of them terminate . <p > <img width = 640 height = 347 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapDelayError . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatMapDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapDelayError ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper ) { return concatMapDelayError ( mapper , bufferSize ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a sequence of values into ObservableSources and concatenates these ObservableSources eagerly into a single ObservableSource . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source ObservableSources . The operator buffers the values emitted by these ObservableSources and then drains them in order each one after the previous one completes . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapEager . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapEager ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper ) { return concatMapEager ( mapper , Integer . MAX_VALUE , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a sequence of values into ObservableSources and concatenates these ObservableSources eagerly into a single ObservableSource . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source ObservableSources . The operator buffers the values emitted by these ObservableSources and then drains them in order each one after the previous one completes . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapEager . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapEager ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper , int maxConcurrency , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapEager < T , R > ( this , mapper , ErrorMode . IMMEDIATE , maxConcurrency , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a sequence of values into ObservableSources and concatenates these ObservableSources eagerly into a single ObservableSource . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source ObservableSources . The operator buffers the values emitted by these ObservableSources and then drains them in order each one after the previous one completes . <p > <img width = 640 height = 390 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapEagerDelayError . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapEagerDelayError ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper , int maxConcurrency , int prefetch , boolean tillTheEnd ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapEager < T , R > ( this , mapper , tillTheEnd ? ErrorMode . END : ErrorMode . BOUNDARY , maxConcurrency , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Observable into CompletableSources subscribes to them one at a time in order and waits until the upstream and all CompletableSources complete . <p > <img width = 640 height = 505 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapCompletable . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable concatMapCompletable ( Function < ? super T , ? extends CompletableSource > mapper ) { return concatMapCompletable ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Observable into CompletableSources subscribes to them one at a time in order and waits until the upstream and all CompletableSources complete . <p > <img width = 640 height = 505 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapCompletable . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatMapCompletable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > <p > History : 2 . 1 . 6 - experimental @param mapper a function that when applied to an item emitted by the source ObservableSource returns a CompletableSource [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable concatMapCompletable ( Function < ? super T , ? extends CompletableSource > mapper , int capacityHint ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( capacityHint , \"capacityHint\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapCompletable < T > ( this , mapper , ErrorMode . IMMEDIATE , capacityHint ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable concatMapCompletableDelayError ( Function < ? super T , ? extends CompletableSource > mapper ) { return concatMapCompletableDelayError ( mapper , true , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable concatMapCompletableDelayError ( Function < ? super T , ? extends CompletableSource > mapper , boolean tillTheEnd , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapCompletable < T > ( this , mapper , tillTheEnd ? ErrorMode . END : ErrorMode . BOUNDARY , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that concatenate each item emitted by the source ObservableSource with the values in an Iterable corresponding to that item that is generated by a selector . <p > <img width = 640 height = 275 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapIterable . o . png alt = > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < U > concatMapIterable ( final Function < ? super T , ? extends Iterable < ? extends U > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableFlattenIterable < T , U > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that concatenate each item emitted by the source ObservableSource with the values in an Iterable corresponding to that item that is generated by a selector . <p > <img width = 640 height = 275 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concatMapIterable . o . png alt = > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < U > concatMapIterable ( final Function < ? super T , ? extends Iterable < ? extends U > > mapper , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return concatMap ( ObservableInternalHelper . flatMapIntoIterable ( mapper ) , prefetch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapMaybe ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { return concatMapMaybe ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapMaybe ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapMaybe < T , R > ( this , mapper , ErrorMode . IMMEDIATE , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapMaybeDelayError ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { return concatMapMaybeDelayError ( mapper , true , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapMaybeDelayError ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper , boolean tillTheEnd , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapMaybe < T , R > ( this , mapper , tillTheEnd ? ErrorMode . END : ErrorMode . BOUNDARY , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapSingle ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper ) { return concatMapSingle ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapSingle ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapSingle < T , R > ( this , mapper , ErrorMode . IMMEDIATE , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapSingleDelayError ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper , boolean tillTheEnd ) { return concatMapSingleDelayError ( mapper , tillTheEnd , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > concatMapSingleDelayError ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper , boolean tillTheEnd , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatMapSingle < T , R > ( this , mapper , tillTheEnd ? ErrorMode . END : ErrorMode . BOUNDARY , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items emitted from the current ObservableSource then the next one after the other without interleaving them . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concat . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > concatWith ( ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return concat ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > concatWith ( @ NonNull SingleSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatWithSingle < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > concatWith ( @ NonNull MaybeSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatWithMaybe < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > concatWith ( @ NonNull CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableConcatWithCompletable < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean that indicates whether the source ObservableSource emitted a specified item . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / contains . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code contains } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > contains ( final Object element ) { ObjectHelper . requireNonNull ( element , \"element is null\" ) ; return any ( Functions . equalsWith ( element ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource except that it drops items emitted by the source ObservableSource that are followed by another item within a computed debounce duration . <p > <img width = 640 height = 425 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / debounce . f . png alt = > <p > The delivery of the item happens on the thread of the first { @code onNext } or { @code onComplete } signal of the generated { @code ObservableSource } sequence which if takes too long a newer item may arrive from the upstream causing the generated sequence to get disposed which may also interrupt any downstream blocking operation ( yielding an { @code InterruptedException } ) . It is recommended processing items that may take long time to be moved to another thread via { @link #observeOn } applied after { @code debounce } itself . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code debounce } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < T > debounce ( Function < ? super T , ? extends ObservableSource < U > > debounceSelector ) { ObjectHelper . requireNonNull ( debounceSelector , \"debounceSelector is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDebounce < T , U > ( this , debounceSelector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource except that it drops items emitted by the source ObservableSource that are followed by newer items before a timeout value expires . The timer resets on each emission . <p > <em > Note : < / em > If items keep being emitted by the source ObservableSource faster than the timeout then no items will be emitted by the resulting ObservableSource . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / debounce . png alt = > <p > Delivery of the item after the grace period happens on the { @code computation } { @code Scheduler } s { @code Worker } which if takes too long a newer item may arrive from the upstream causing the { @code Worker } s task to get disposed which may also interrupt any downstream blocking operation ( yielding an { @code InterruptedException } ) . It is recommended processing items that may take long time to be moved to another thread via { @link #observeOn } applied after { @code debounce } itself . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code debounce } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > debounce ( long timeout , TimeUnit unit ) { return debounce ( timeout , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource except that it drops items emitted by the source ObservableSource that are followed by newer items before a timeout value expires on a specified Scheduler . The timer resets on each emission . <p > <em > Note : < / em > If items keep being emitted by the source ObservableSource faster than the timeout then no items will be emitted by the resulting ObservableSource . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / debounce . s . png alt = > <p > Delivery of the item after the grace period happens on the given { @code Scheduler } s { @code Worker } which if takes too long a newer item may arrive from the upstream causing the { @code Worker } s task to get disposed which may also interrupt any downstream blocking operation ( yielding an { @code InterruptedException } ) . It is recommended processing items that may take long time to be moved to another thread via { @link #observeOn } applied after { @code debounce } itself . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > debounce ( long timeout , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDebounceTimed < T > ( this , timeout , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items emitted by the source ObservableSource or a specified default item if the source ObservableSource is empty . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / defaultIfEmpty . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code defaultIfEmpty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > defaultIfEmpty ( T defaultItem ) { ObjectHelper . requireNonNull ( defaultItem , \"defaultItem is null\" ) ; return switchIfEmpty ( just ( defaultItem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that delays the emissions of the source ObservableSource via another ObservableSource on a per - item basis . <p > <img width = 640 height = 450 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . o . png alt = > <p > <em > Note : < / em > the resulting ObservableSource will immediately propagate any { @code onError } notification from the source ObservableSource . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code delay } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < T > delay ( final Function < ? super T , ? extends ObservableSource < U > > itemDelay ) { ObjectHelper . requireNonNull ( itemDelay , \"itemDelay is null\" ) ; return flatMap ( ObservableInternalHelper . itemDelay ( itemDelay ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items emitted by the source ObservableSource shifted forward in time by a specified delay . Error notifications from the source ObservableSource are not delayed . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > delay ( long delay , TimeUnit unit , Scheduler scheduler ) { return delay ( delay , unit , scheduler , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items emitted by the source ObservableSource shifted forward in time by a specified delay . If { @code delayError } is true error notifications will also be delayed . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > delay ( long delay , TimeUnit unit , Scheduler scheduler , boolean delayError ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDelay < T > ( this , delay , unit , scheduler , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that delays the subscription to and emissions from the source ObservableSource via another ObservableSource on a per - item basis . <p > <img width = 640 height = 450 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . oo . png alt = > <p > <em > Note : < / em > the resulting ObservableSource will immediately propagate any { @code onError } notification from the source ObservableSource . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code delay } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Observable < T > delay ( ObservableSource < U > subscriptionDelay , Function < ? super T , ? extends ObservableSource < V > > itemDelay ) { return delaySubscription ( subscriptionDelay ) . delay ( itemDelay ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that delays the subscription to this Observable until the other Observable emits an element or completes normally . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delaySubscription . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < T > delaySubscription ( ObservableSource < U > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDelaySubscriptionOther < T , U > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that delays the subscription to the source ObservableSource by a given amount of time both waiting and subscribing on a given Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delaySubscription . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > delaySubscription ( long delay , TimeUnit unit , Scheduler scheduler ) { return delaySubscription ( timer ( delay , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that reverses the effect of { @link #materialize materialize } by transforming the { @link Notification } objects emitted by the source ObservableSource into the items or notifications they represent . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / dematerialize . png alt = > <p > When the upstream signals an { @link Notification#createOnError ( Throwable ) onError } or { @link Notification#createOnComplete () onComplete } item the returned Observable disposes of the flow and terminates with that type of terminal event : <pre > <code > Observable . just ( createOnNext ( 1 ) createOnComplete () createOnNext ( 2 )) . doOnDispose (( ) - &gt ; System . out . println ( Disposed! )) ; . dematerialize () . test () . assertResult ( 1 ) ; < / code > < / pre > If the upstream signals { @code onError } or { @code onComplete } directly the flow is terminated with the same event . <pre > <code > Observable . just ( createOnNext ( 1 ) createOnNext ( 2 )) . dematerialize () . test () . assertResult ( 1 2 ) ; < / code > < / pre > If this behavior is not desired the completion can be suppressed by applying { @link #concatWith ( ObservableSource ) } with a { @link #never () } source . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code dematerialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ Deprecated @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public final < T2 > Observable < T2 > dematerialize ( ) { return RxJavaPlugins . onAssembly ( new ObservableDematerialize ( this , Functions . identity ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that reverses the effect of { @link #materialize materialize } by transforming the { @link Notification } objects extracted from the source items via a selector function into their respective { @code Observer } signal types . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / dematerialize . png alt = > <p > The intended use of the { @code selector } function is to perform a type - safe identity mapping ( see example ) on a source that is already of type { @code Notification<T > } . The Java language doesn t allow limiting instance methods to a certain generic argument shape therefore a function is used to ensure the conversion remains type safe . <p > When the upstream signals an { @link Notification#createOnError ( Throwable ) onError } or { @link Notification#createOnComplete () onComplete } item the returned Observable disposes of the flow and terminates with that type of terminal event : <pre > <code > Observable . just ( createOnNext ( 1 ) createOnComplete () createOnNext ( 2 )) . doOnDispose (( ) - &gt ; System . out . println ( Disposed! )) ; . dematerialize ( notification - &gt ; notification ) . test () . assertResult ( 1 ) ; < / code > < / pre > If the upstream signals { @code onError } or { @code onComplete } directly the flow is terminated with the same event . <pre > <code > Observable . just ( createOnNext ( 1 ) createOnNext ( 2 )) . dematerialize ( notification - &gt ; notification ) . test () . assertResult ( 1 2 ) ; < / code > < / pre > If this behavior is not desired the completion can be suppressed by applying { @link #concatWith ( ObservableSource ) } with a { @link #never () } source . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code dematerialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ Experimental @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > dematerialize ( Function < ? super T , Notification < R > > selector ) { ObjectHelper . requireNonNull ( selector , \"selector is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDematerialize < T , R > ( this , selector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits all items emitted by the source ObservableSource that are distinct based on { @link Object#equals ( Object ) } comparison . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinct . png alt = > <p > It is recommended the elements class { @code T } in the flow overrides the default { @code Object . equals () } and { @link Object#hashCode () } to provide meaningful comparison between items as the default Java implementation only considers reference equivalence . <p > By default { @code distinct () } uses an internal { @link java . util . HashSet } per Observer to remember previously seen items and uses { @link java . util . Set#add ( Object ) } returning { @code false } as the indicator for duplicates . <p > Note that this internal { @code HashSet } may grow unbounded as items won t be removed from it by the operator . Therefore using very long or infinite upstream ( with very distinct elements ) may lead to { @code OutOfMemoryError } . <p > Customizing the retention policy can happen only by providing a custom { @link java . util . Collection } implementation to the { @link #distinct ( Function Callable ) } overload . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinct } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > distinct ( ) { return distinct ( Functions . identity ( ) , Functions . createHashSet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits all items emitted by the source ObservableSource that are distinct according to a key selector function and based on { @link Object#equals ( Object ) } comparison of the objects returned by the key selector function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinct . key . png alt = > <p > It is recommended the keys class { @code K } overrides the default { @code Object . equals () } and { @link Object#hashCode () } to provide meaningful comparison between the key objects as the default Java implementation only considers reference equivalence . <p > By default { @code distinct () } uses an internal { @link java . util . HashSet } per Observer to remember previously seen keys and uses { @link java . util . Set#add ( Object ) } returning { @code false } as the indicator for duplicates . <p > Note that this internal { @code HashSet } may grow unbounded as keys won t be removed from it by the operator . Therefore using very long or infinite upstream ( with very distinct keys ) may lead to { @code OutOfMemoryError } . <p > Customizing the retention policy can happen only by providing a custom { @link java . util . Collection } implementation to the { @link #distinct ( Function Callable ) } overload . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinct } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Observable < T > distinct ( Function < ? super T , K > keySelector ) { return distinct ( keySelector , Functions . createHashSet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits all items emitted by the source ObservableSource that are distinct according to a key selector function and based on { @link Object#equals ( Object ) } comparison of the objects returned by the key selector function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinct . key . png alt = > <p > It is recommended the keys class { @code K } overrides the default { @code Object . equals () } and { @link Object#hashCode () } to provide meaningful comparison between the key objects as the default Java implementation only considers reference equivalence . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinct } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Observable < T > distinct ( Function < ? super T , K > keySelector , Callable < ? extends Collection < ? super K > > collectionSupplier ) { ObjectHelper . requireNonNull ( keySelector , \"keySelector is null\" ) ; ObjectHelper . requireNonNull ( collectionSupplier , \"collectionSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDistinct < T , K > ( this , keySelector , collectionSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits all items emitted by the source ObservableSource that are distinct from their immediate predecessors based on { @link Object#equals ( Object ) } comparison . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinctUntilChanged . png alt = > <p > It is recommended the elements class { @code T } in the flow overrides the default { @code Object . equals () } to provide meaningful comparison between items as the default Java implementation only considers reference equivalence . Alternatively use the { @link #distinctUntilChanged ( BiPredicate ) } overload and provide a comparison function in case the class { @code T } can t be overridden with custom { @code equals () } or the comparison itself should happen on different terms or properties of the class { @code T } . <p > Note that the operator always retains the latest item from upstream regardless of the comparison result and uses it in the next comparison with the next upstream item . <p > Note that if element type { @code T } in the flow is mutable the comparison of the previous and current item may yield unexpected results if the items are mutated externally . Common cases are mutable { @code CharSequence } s or { @code List } s where the objects will actually have the same references when they are modified and { @code distinctUntilChanged } will evaluate subsequent items as same . To avoid such situation it is recommended that mutable data is converted to an immutable one for example using { @code map ( CharSequence :: toString ) } or { @code map ( list - > Collections . unmodifiableList ( new ArrayList< > ( list ))) } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinctUntilChanged } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > distinctUntilChanged ( ) { return distinctUntilChanged ( Functions . identity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits all items emitted by the source ObservableSource that are distinct from their immediate predecessors according to a key selector function and based on { @link Object#equals ( Object ) } comparison of those objects returned by the key selector function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinctUntilChanged . key . png alt = > <p > It is recommended the keys class { @code K } overrides the default { @code Object . equals () } to provide meaningful comparison between the key objects as the default Java implementation only considers reference equivalence . Alternatively use the { @link #distinctUntilChanged ( BiPredicate ) } overload and provide a comparison function in case the class { @code K } can t be overridden with custom { @code equals () } or the comparison itself should happen on different terms or properties of the item class { @code T } ( for which the keys can be derived via a similar selector ) . <p > Note that the operator always retains the latest key from upstream regardless of the comparison result and uses it in the next comparison with the next key derived from the next upstream item . <p > Note that if element type { @code T } in the flow is mutable the comparison of the previous and current item may yield unexpected results if the items are mutated externally . Common cases are mutable { @code CharSequence } s or { @code List } s where the objects will actually have the same references when they are modified and { @code distinctUntilChanged } will evaluate subsequent items as same . To avoid such situation it is recommended that mutable data is converted to an immutable one for example using { @code map ( CharSequence :: toString ) } or { @code map ( list - > Collections . unmodifiableList ( new ArrayList< > ( list ))) } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinctUntilChanged } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Observable < T > distinctUntilChanged ( Function < ? super T , K > keySelector ) { ObjectHelper . requireNonNull ( keySelector , \"keySelector is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDistinctUntilChanged < T , K > ( this , keySelector , ObjectHelper . equalsPredicate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits all items emitted by the source ObservableSource that are distinct from their immediate predecessors when compared with each other via the provided comparator function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinctUntilChanged . png alt = > <p > Note that the operator always retains the latest item from upstream regardless of the comparison result and uses it in the next comparison with the next upstream item . <p > Note that if element type { @code T } in the flow is mutable the comparison of the previous and current item may yield unexpected results if the items are mutated externally . Common cases are mutable { @code CharSequence } s or { @code List } s where the objects will actually have the same references when they are modified and { @code distinctUntilChanged } will evaluate subsequent items as same . To avoid such situation it is recommended that mutable data is converted to an immutable one for example using { @code map ( CharSequence :: toString ) } or { @code map ( list - > Collections . unmodifiableList ( new ArrayList< > ( list ))) } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinctUntilChanged } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > distinctUntilChanged ( BiPredicate < ? super T , ? super T > comparer ) { ObjectHelper . requireNonNull ( comparer , \"comparer is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDistinctUntilChanged < T , T > ( this , Functions . < T > identity ( ) , comparer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified consumer with the current item after this item has been emitted to the downstream . <p > Note that the { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doAfterNext ( Consumer < ? super T > onAfterNext ) { ObjectHelper . requireNonNull ( onAfterNext , \"onAfterNext is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDoAfterNext < T > ( this , onAfterNext ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an { @link Action } to be called when this ObservableSource invokes either { @link Observer#onComplete onComplete } or { @link Observer#onError onError } . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doAfterTerminate . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doAfterTerminate } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doAfterTerminate ( Action onFinally ) { ObjectHelper . requireNonNull ( onFinally , \"onFinally is null\" ) ; return doOnEach ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , onFinally ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified action after this Observable signals onError or onCompleted or gets disposed by the downstream . <p > In case of a race between a terminal event and a dispose call the provided { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doFinally ( Action onFinally ) { ObjectHelper . requireNonNull ( onFinally , \"onFinally is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDoFinally < T > ( this , onFinally ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the dispose { @code Action } if the downstream disposes the sequence . <p > The action is shared between subscriptions and thus may be called concurrently from multiple threads ; the action must be thread safe . <p > If the action throws a runtime exception that exception is rethrown by the { @code dispose () } call sometimes as a { @code CompositeException } if there were multiple exceptions along the way . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnDispose . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnDispose } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnDispose ( Action onDispose ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , onDispose ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source ObservableSource so that it invokes an action when it calls { @code onComplete } . <p > <img width = 640 height = 358 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnComplete . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnComplete } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnComplete ( Action onComplete ) { return doOnEach ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , onComplete , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the appropriate onXXX consumer ( shared between all subscribers ) whenever a signal with the same type passes through before forwarding them to downstream . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnEach . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnEach } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) private Observable < T > doOnEach ( Consumer < ? super T > onNext , Consumer < ? super Throwable > onError , Action onComplete , Action onAfterTerminate ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; ObjectHelper . requireNonNull ( onAfterTerminate , \"onAfterTerminate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDoOnEach < T > ( this , onNext , onError , onComplete , onAfterTerminate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source ObservableSource so that it invokes an action for each item it emits . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnEach . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnEach } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnEach ( final Consumer < ? super Notification < T > > onNotification ) { ObjectHelper . requireNonNull ( onNotification , \"onNotification is null\" ) ; return doOnEach ( Functions . notificationOnNext ( onNotification ) , Functions . notificationOnError ( onNotification ) , Functions . notificationOnComplete ( onNotification ) , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source ObservableSource so that it notifies an Observer for each item and terminal event it emits . <p > In case the { @code onError } of the supplied observer throws the downstream will receive a composite exception containing the original exception and the exception thrown by { @code onError } . If either the { @code onNext } or the { @code onComplete } method of the supplied observer throws the downstream will be terminated and will receive this thrown exception . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnEach . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnEach } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnEach ( final Observer < ? super T > observer ) { ObjectHelper . requireNonNull ( observer , \"observer is null\" ) ; return doOnEach ( ObservableInternalHelper . observerOnNext ( observer ) , ObservableInternalHelper . observerOnError ( observer ) , ObservableInternalHelper . observerOnComplete ( observer ) , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source ObservableSource so that it invokes an action if it calls { @code onError } . <p > In case the { @code onError } action throws the downstream will receive a composite exception containing the original exception and the exception thrown by { @code onError } . <p > <img width = 640 height = 355 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnError . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnError ( Consumer < ? super Throwable > onError ) { return doOnEach ( Functions . emptyConsumer ( ) , onError , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the appropriate onXXX method ( shared between all Observer ) for the lifecycle events of the sequence ( subscription disposal ) . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnLifecycle . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnLifecycle } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnLifecycle ( final Consumer < ? super Disposable > onSubscribe , final Action onDispose ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; ObjectHelper . requireNonNull ( onDispose , \"onDispose is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableDoOnLifecycle < T > ( this , onSubscribe , onDispose ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source ObservableSource so that it invokes an action when it calls { @code onNext } . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnNext . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnNext ( Consumer < ? super T > onNext ) { return doOnEach ( onNext , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source { @code ObservableSource } so that it invokes the given action when it is subscribed from its subscribers . Each subscription will result in an invocation of the given action except when the source { @code ObservableSource } is reference counted in which case the source { @code ObservableSource } will invoke the given action for the first subscription . <p > <img width = 640 height = 390 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnSubscribe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnSubscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnSubscribe ( Consumer < ? super Disposable > onSubscribe ) { return doOnLifecycle ( onSubscribe , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source ObservableSource so that it invokes an action when it calls { @code onComplete } or { @code onError } . <p > <img width = 640 height = 327 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnTerminate . o . png alt = > <p > This differs from { @code doAfterTerminate } in that this happens <em > before< / em > the { @code onComplete } or { @code onError } notification . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnTerminate } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > doOnTerminate ( final Action onTerminate ) { ObjectHelper . requireNonNull ( onTerminate , \"onTerminate is null\" ) ; return doOnEach ( Functions . emptyConsumer ( ) , Functions . actionConsumer ( onTerminate ) , onTerminate , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the single item at a specified index in a sequence of emissions from this Observable or completes if this Observable signals fewer elements than index . <p > <img width = 640 height = 363 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / elementAt . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code elementAt } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > elementAt ( long index ) { if ( index < 0 ) { throw new IndexOutOfBoundsException ( \"index >= 0 required but it was \" + index ) ; } return RxJavaPlugins . onAssembly ( new ObservableElementAtMaybe < T > ( this , index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the item found at a specified index in a sequence of emissions from this Observable or a default item if that index is out of range . <p > <img width = 640 height = 353 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / elementAtDefault . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code elementAt } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > elementAt ( long index , T defaultItem ) { if ( index < 0 ) { throw new IndexOutOfBoundsException ( \"index >= 0 required but it was \" + index ) ; } ObjectHelper . requireNonNull ( defaultItem , \"defaultItem is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableElementAtSingle < T > ( this , index , defaultItem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the item found at a specified index in a sequence of emissions from this Observable or signals a { @link NoSuchElementException } if this Observable signals fewer elements than index . <p > <img width = 640 height = 362 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / elementAtOrError . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code elementAtOrError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > elementAtOrError ( long index ) { if ( index < 0 ) { throw new IndexOutOfBoundsException ( \"index >= 0 required but it was \" + index ) ; } return RxJavaPlugins . onAssembly ( new ObservableElementAtSingle < T > ( this , index , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters items emitted by an ObservableSource by only emitting those that satisfy a specified predicate . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / filter . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code filter } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > filter ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableFilter < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits only the very first item emitted by the source ObservableSource or a default item if the source ObservableSource completes without emitting any items . <p > <img width = 640 height = 286 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / first . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code first } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > first ( T defaultItem ) { return elementAt ( 0L , defaultItem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items based on applying a function that you supply to each item emitted by the source ObservableSource where that function returns an ObservableSource and then merging those resulting ObservableSources and emitting the results of this merger . <p > <img width = 640 height = 356 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapDelayError . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMap ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper , boolean delayErrors ) { return flatMap ( mapper , delayErrors , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items based on applying a function that you supply to each item emitted by the source ObservableSource where that function returns an ObservableSource and then merging those resulting ObservableSources and emitting the results of this merger while limiting the maximum number of concurrent subscriptions to these ObservableSources . <p > <img width = 640 height = 441 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapMaxConcurrency . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMap ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper , boolean delayErrors , int maxConcurrency , int bufferSize ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; if ( this instanceof ScalarCallable ) { @ SuppressWarnings ( \"unchecked\" ) T v = ( ( ScalarCallable < T > ) this ) . call ( ) ; if ( v == null ) { return empty ( ) ; } return ObservableScalarXMap . scalarXMap ( v , mapper ) ; } return RxJavaPlugins . onAssembly ( new ObservableFlatMap < T , R > ( this , mapper , delayErrors , maxConcurrency , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that applies a function to each item emitted or notification raised by the source ObservableSource and then flattens the ObservableSources returned from these functions and emits the resulting items . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeMap . nce . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMap ( Function < ? super T , ? extends ObservableSource < ? extends R > > onNextMapper , Function < ? super Throwable , ? extends ObservableSource < ? extends R > > onErrorMapper , Callable < ? extends ObservableSource < ? extends R > > onCompleteSupplier ) { ObjectHelper . requireNonNull ( onNextMapper , \"onNextMapper is null\" ) ; ObjectHelper . requireNonNull ( onErrorMapper , \"onErrorMapper is null\" ) ; ObjectHelper . requireNonNull ( onCompleteSupplier , \"onCompleteSupplier is null\" ) ; return merge ( new ObservableMapNotification < T , R > ( this , onNextMapper , onErrorMapper , onCompleteSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the results of a specified function to the pair of values emitted by the source ObservableSource and a specified collection ObservableSource . <p > <img width = 640 height = 390 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeMap . r . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Observable < R > flatMap ( Function < ? super T , ? extends ObservableSource < ? extends U > > mapper , BiFunction < ? super T , ? super U , ? extends R > resultSelector ) { return flatMap ( mapper , resultSelector , false , bufferSize ( ) , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Observable into CompletableSources subscribes to them and waits until the upstream and all CompletableSources complete . <p > <img width = 640 height = 424 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapCompletable . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable flatMapCompletable ( Function < ? super T , ? extends CompletableSource > mapper ) { return flatMapCompletable ( mapper , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the results of applying a function to the pair of values from the source ObservableSource and an Iterable corresponding to that item that is generated by a selector . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapIterable . o . r . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMapIterable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Observable < V > flatMapIterable ( final Function < ? super T , ? extends Iterable < ? extends U > > mapper , BiFunction < ? super T , ? super U , ? extends V > resultSelector ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . requireNonNull ( resultSelector , \"resultSelector is null\" ) ; return flatMap ( ObservableInternalHelper . flatMapIntoIterable ( mapper ) , resultSelector , false , bufferSize ( ) , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Observable into MaybeSources subscribes to all of them and merges their onSuccess values in no particular order into a single Observable sequence . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapMaybe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMapMaybe ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { return flatMapMaybe ( mapper , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Observable into MaybeSources subscribes to them and merges their onSuccess values in no particular order into a single Observable sequence optionally delaying all errors . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapMaybe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMapMaybe ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper , boolean delayErrors ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableFlatMapMaybe < T , R > ( this , mapper , delayErrors ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Observable into SingleSources subscribes to all of them and merges their onSuccess values in no particular order into a single Observable sequence . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapSingle . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMapSingle ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper ) { return flatMapSingle ( mapper , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Observable into SingleSources subscribes to them and merges their onSuccess values in no particular order into a single Observable sequence optionally delaying all errors . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMapSingle . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMapSingle ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper , boolean delayErrors ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableFlatMapSingle < T , R > ( this , mapper , delayErrors ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the { @link ObservableSource } and receives notifications for each element and the terminal events until the onNext Predicate returns false . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code forEachWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable forEachWhile ( final Predicate < ? super T > onNext , Consumer < ? super Throwable > onError , final Action onComplete ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; ForEachWhileObserver < T > o = new ForEachWhileObserver < T > ( onNext , onError , onComplete ) ; subscribe ( o ) ; return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Groups the items emitted by an { @code ObservableSource } according to a specified criterion and emits these grouped items as { @link GroupedObservable } s . The emitted { @code GroupedObservableSource } allows only a single { @link Observer } during its lifetime and if this { @code Observer } calls dispose () before the source terminates the next emission by the source having the same key will trigger a new { @code GroupedObservableSource } emission . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / groupBy . png alt = > <p > <em > Note : < / em > A { @link GroupedObservable } will cache the items it is to emit until such time as it is subscribed to . For this reason in order to avoid memory leaks you should not simply ignore those { @code GroupedObservableSource } s that do not concern you . Instead you can signal to them that they may discard their buffers by applying an operator like { @link #ignoreElements } to them . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code groupBy } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Observable < GroupedObservable < K , T > > groupBy ( Function < ? super T , ? extends K > keySelector ) { return groupBy ( keySelector , ( Function ) Functions . identity ( ) , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Groups the items emitted by an { @code ObservableSource } according to a specified criterion and emits these grouped items as { @link GroupedObservable } s . The emitted { @code GroupedObservableSource } allows only a single { @link Observer } during its lifetime and if this { @code Observer } calls dispose () before the source terminates the next emission by the source having the same key will trigger a new { @code GroupedObservableSource } emission . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / groupBy . png alt = > <p > <em > Note : < / em > A { @link GroupedObservable } will cache the items it is to emit until such time as it is subscribed to . For this reason in order to avoid memory leaks you should not simply ignore those { @code GroupedObservableSource } s that do not concern you . Instead you can signal to them that they may discard their buffers by applying an operator like { @link #ignoreElements } to them . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code groupBy } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K , V > Observable < GroupedObservable < K , V > > groupBy ( Function < ? super T , ? extends K > keySelector , Function < ? super T , ? extends V > valueSelector ) { return groupBy ( keySelector , valueSelector , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Groups the items emitted by an { @code ObservableSource } according to a specified criterion and emits these grouped items as { @link GroupedObservable } s . The emitted { @code GroupedObservableSource } allows only a single { @link Observer } during its lifetime and if this { @code Observer } calls dispose () before the source terminates the next emission by the source having the same key will trigger a new { @code GroupedObservableSource } emission . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / groupBy . png alt = > <p > <em > Note : < / em > A { @link GroupedObservable } will cache the items it is to emit until such time as it is subscribed to . For this reason in order to avoid memory leaks you should not simply ignore those { @code GroupedObservableSource } s that do not concern you . Instead you can signal to them that they may discard their buffers by applying an operator like { @link #ignoreElements } to them . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code groupBy } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K , V > Observable < GroupedObservable < K , V > > groupBy ( Function < ? super T , ? extends K > keySelector , Function < ? super T , ? extends V > valueSelector , boolean delayError , int bufferSize ) { ObjectHelper . requireNonNull ( keySelector , \"keySelector is null\" ) ; ObjectHelper . requireNonNull ( valueSelector , \"valueSelector is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableGroupBy < T , K , V > ( this , keySelector , valueSelector , bufferSize , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides the identity of this Observable and its Disposable . <p > Allows hiding extra features such as { @link io . reactivex . subjects . Subject } s { @link Observer } methods or preventing certain identity - based optimizations ( fusion ) . <p > <img width = 640 height = 283 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / hide . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code hide } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > @return the new Observable instance [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > hide ( ) { return RxJavaPlugins . onAssembly ( new ObservableHide < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ignores all items emitted by the source ObservableSource and only calls { @code onComplete } or { @code onError } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / ignoreElements . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code ignoreElements } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable ignoreElements ( ) { return RxJavaPlugins . onAssembly ( new ObservableIgnoreElementsCompletable < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits { @code true } if the source ObservableSource is empty otherwise { @code false } . <p > In Rx . Net this is negated as the { @code any } Observer but we renamed this in RxJava to better match Java naming idioms . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / isEmpty . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code isEmpty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > isEmpty ( ) { return all ( Functions . alwaysFalse ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Correlates the items emitted by two ObservableSources based on overlapping durations . <p > There are no guarantees in what order the items get combined when multiple items from one or both source ObservableSources overlap . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / join_ . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code join } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < TRight , TLeftEnd , TRightEnd , R > Observable < R > join ( ObservableSource < ? extends TRight > other , Function < ? super T , ? extends ObservableSource < TLeftEnd > > leftEnd , Function < ? super TRight , ? extends ObservableSource < TRightEnd > > rightEnd , BiFunction < ? super T , ? super TRight , ? extends R > resultSelector ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; ObjectHelper . requireNonNull ( leftEnd , \"leftEnd is null\" ) ; ObjectHelper . requireNonNull ( rightEnd , \"rightEnd is null\" ) ; ObjectHelper . requireNonNull ( resultSelector , \"resultSelector is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableJoin < T , TRight , TLeftEnd , TRightEnd , R > ( this , other , leftEnd , rightEnd , resultSelector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the last item emitted by this Observable or completes if this Observable is empty . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / lastElement . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code lastElement } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > lastElement ( ) { return RxJavaPlugins . onAssembly ( new ObservableLastMaybe < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits only the last item emitted by this Observable or a default item if this Observable completes without emitting any items . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / last . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code last } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > last ( T defaultItem ) { ObjectHelper . requireNonNull ( defaultItem , \"defaultItem is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableLastSingle < T > ( this , defaultItem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits only the last item emitted by this Observable or signals a { @link NoSuchElementException } if this Observable is empty . <p > <img width = 640 height = 236 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / lastOrError . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code lastOrError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > lastOrError ( ) { return RxJavaPlugins . onAssembly ( new ObservableLastSingle < T > ( this , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that applies a specified function to each item emitted by the source ObservableSource and emits the results of these function applications . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / map . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code map } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > map ( Function < ? super T , ? extends R > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableMap < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that represents all of the emissions <em > and< / em > notifications from the source ObservableSource into emissions marked with their original types within { @link Notification } objects . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / materialize . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code materialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < Notification < T > > materialize ( ) { return RxJavaPlugins . onAssembly ( new ObservableMaterialize < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens this and another ObservableSource into a single ObservableSource without any transformation . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > You can combine items emitted by multiple ObservableSources so that they appear as a single ObservableSource by using the { @code mergeWith } method . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > mergeWith ( ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return merge ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the sequence of items of this Observable with the success value of the other SingleSource . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > The success value of the other { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > mergeWith ( @ NonNull SingleSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableMergeWithSingle < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the sequence of items of this Observable with the success value of the other MaybeSource or waits both to complete normally if the MaybeSource is empty . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > The success value of the other { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > mergeWith ( @ NonNull MaybeSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableMergeWithMaybe < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Relays the items of this Observable and completes only when the other CompletableSource completes as well . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > mergeWith ( @ NonNull CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableMergeWithCompletable < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies an ObservableSource to perform its emissions and notifications on a specified { @link Scheduler } asynchronously with an unbounded buffer with { @link Flowable#bufferSize () } island size . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > observeOn ( Scheduler scheduler ) { return observeOn ( scheduler , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies an ObservableSource to perform its emissions and notifications on a specified { @link Scheduler } asynchronously with an unbounded buffer of configurable island size and optionally delays onError notifications . <p > <img width = 640 height = 308 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / observeOn . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > <p > Island size indicates how large chunks the unbounded buffer allocates to store the excess elements waiting to be consumed on the other side of the asynchronous boundary . Values below 16 are not recommended in performance sensitive scenarios . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > observeOn ( Scheduler scheduler , boolean delayError , int bufferSize ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableObserveOn < T > ( this , scheduler , delayError , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs an ObservableSource to pass control to another ObservableSource rather than invoking { @link Observer#onError onError } if it encounters an error . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onErrorResumeNext . png alt = > <p > By default when an ObservableSource encounters an error that prevents it from emitting the expected item to its { @link Observer } the ObservableSource invokes its Observer s { @code onError } method and then quits without invoking any more of its Observer s methods . The { @code onErrorResumeNext } method changes this behavior . If you pass a function that returns an ObservableSource ( { @code resumeFunction } ) to { @code onErrorResumeNext } if the original ObservableSource encounters an error instead of invoking its Observer s { @code onError } method it will instead relinquish control to the ObservableSource returned from { @code resumeFunction } which will invoke the Observer s { @link Observer#onNext onNext } method if it is able to do so . In such a case because no ObservableSource necessarily invokes { @code onError } the Observer may never know that an error happened . <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorResumeNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > onErrorResumeNext ( Function < ? super Throwable , ? extends ObservableSource < ? extends T > > resumeFunction ) { ObjectHelper . requireNonNull ( resumeFunction , \"resumeFunction is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableOnErrorNext < T > ( this , resumeFunction , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs an ObservableSource to pass control to another ObservableSource rather than invoking { @link Observer#onError onError } if it encounters an error . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onErrorResumeNext . png alt = > <p > By default when an ObservableSource encounters an error that prevents it from emitting the expected item to its { @link Observer } the ObservableSource invokes its Observer s { @code onError } method and then quits without invoking any more of its Observer s methods . The { @code onErrorResumeNext } method changes this behavior . If you pass another ObservableSource ( { @code resumeSequence } ) to an ObservableSource s { @code onErrorResumeNext } method if the original ObservableSource encounters an error instead of invoking its Observer s { @code onError } method it will instead relinquish control to { @code resumeSequence } which will invoke the Observer s { @link Observer#onNext onNext } method if it is able to do so . In such a case because no ObservableSource necessarily invokes { @code onError } the Observer may never know that an error happened . <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorResumeNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > onErrorResumeNext ( final ObservableSource < ? extends T > next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return onErrorResumeNext ( Functions . justFunction ( next ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs an ObservableSource to emit an item ( returned by a specified function ) rather than invoking { @link Observer#onError onError } if it encounters an error . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onErrorReturn . o . png alt = > <p > By default when an ObservableSource encounters an error that prevents it from emitting the expected item to its { @link Observer } the ObservableSource invokes its Observer s { @code onError } method and then quits without invoking any more of its Observer s methods . The { @code onErrorReturn } method changes this behavior . If you pass a function ( { @code resumeFunction } ) to an ObservableSource s { @code onErrorReturn } method if the original ObservableSource encounters an error instead of invoking its Observer s { @code onError } method it will instead emit the return value of { @code resumeFunction } . <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorReturn } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > onErrorReturn ( Function < ? super Throwable , ? extends T > valueSupplier ) { ObjectHelper . requireNonNull ( valueSupplier , \"valueSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableOnErrorReturn < T > ( this , valueSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs an ObservableSource to pass control to another ObservableSource rather than invoking { @link Observer#onError onError } if it encounters an { @link java . lang . Exception } . <p > This differs from { @link #onErrorResumeNext } in that this one does not handle { @link java . lang . Throwable } or { @link java . lang . Error } but lets those continue through . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onExceptionResumeNextViaObservableSource . png alt = > <p > By default when an ObservableSource encounters an exception that prevents it from emitting the expected item to its { @link Observer } the ObservableSource invokes its Observer s { @code onError } method and then quits without invoking any more of its Observer s methods . The { @code onExceptionResumeNext } method changes this behavior . If you pass another ObservableSource ( { @code resumeSequence } ) to an ObservableSource s { @code onExceptionResumeNext } method if the original ObservableSource encounters an exception instead of invoking its Observer s { @code onError } method it will instead relinquish control to { @code resumeSequence } which will invoke the Observer s { @link Observer#onNext onNext } method if it is able to do so . In such a case because no ObservableSource necessarily invokes { @code onError } the Observer may never know that an exception happened . <p > You can use this to prevent exceptions from propagating or to supply fallback data should exceptions be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onExceptionResumeNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > onExceptionResumeNext ( final ObservableSource < ? extends T > next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableOnErrorNext < T > ( this , Functions . justFunction ( next ) , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Nulls out references to the upstream producer and downstream Observer if the sequence is terminated or downstream calls dispose () . <p > <img width = 640 height = 246 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onTerminateDetach . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > onTerminateDetach ( ) { return RxJavaPlugins . onAssembly ( new ObservableDetach < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the results of invoking a specified selector on items emitted by a { @link ConnectableObservable } that shares a single subscription to the underlying sequence . <p > <img width = 640 height = 647 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / publishFunction . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code publish } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > publish ( Function < ? super Observable < T > , ? extends ObservableSource < R > > selector ) { ObjectHelper . requireNonNull ( selector , \"selector is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservablePublishSelector < T , R > ( this , selector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that applies a specified accumulator function to the first item emitted by a source ObservableSource then feeds the result of that function along with the second item emitted by the source ObservableSource into the same function and so on until all items have been emitted by the finite source ObservableSource and emits the final result from the final call to your function as its sole item . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / reduce . 2 . png alt = > <p > This technique which is called reduce here is sometimes called aggregate fold accumulate compress or inject in other programming contexts . Groovy for instance has an { @code inject } method that does a similar operation on lists . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulator object to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code reduce } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > reduce ( BiFunction < T , T , T > reducer ) { ObjectHelper . requireNonNull ( reducer , \"reducer is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableReduceMaybe < T > ( this , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that applies a specified accumulator function to the first item emitted by a source ObservableSource and a specified seed value then feeds the result of that function along with the second item emitted by an ObservableSource into the same function and so on until all items have been emitted by the finite source ObservableSource emitting the final result from the final call to your function as its sole item . <p > <img width = 640 height = 325 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / reduceSeed . o . png alt = > <p > This technique which is called reduce here is sometimes called aggregate fold accumulate compress or inject in other programming contexts . Groovy for instance has an { @code inject } method that does a similar operation on lists . <p > Note that the { @code seed } is shared among all subscribers to the resulting ObservableSource and may cause problems if it is mutable . To make sure each subscriber gets its own value defer the application of this operator via { @link #defer ( Callable ) } : <pre > <code > ObservableSource&lt ; T&gt ; source = ... Single . defer (( ) - &gt ; source . reduce ( new ArrayList&lt ; &gt ; () ( list item ) - &gt ; list . add ( item ))) ; [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > reduce ( R seed , BiFunction < R , ? super T , R > reducer ) { ObjectHelper . requireNonNull ( seed , \"seed is null\" ) ; ObjectHelper . requireNonNull ( reducer , \"reducer is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableReduceSeedSingle < T , R > ( this , seed , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that applies a specified accumulator function to the first item emitted by a source ObservableSource and a seed value derived from calling a specified seedSupplier then feeds the result of that function along with the second item emitted by an ObservableSource into the same function and so on until all items have been emitted by the finite source ObservableSource emitting the final result from the final call to your function as its sole item . <p > <img width = 640 height = 325 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / reduceWith . o . png alt = > <p > This technique which is called reduce here is sometimes called aggregate fold accumulate compress or inject in other programming contexts . Groovy for instance has an { @code inject } method that does a similar operation on lists . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulator object to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code reduceWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > reduceWith ( Callable < R > seedSupplier , BiFunction < R , ? super T , R > reducer ) { ObjectHelper . requireNonNull ( seedSupplier , \"seedSupplier is null\" ) ; ObjectHelper . requireNonNull ( reducer , \"reducer is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableReduceWithSingle < T , R > ( this , seedSupplier , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that repeats the sequence of items emitted by the source ObservableSource indefinitely . <p > <img width = 640 height = 287 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeatInf . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeat } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > repeat ( ) { return repeat ( Long . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that repeats the sequence of items emitted by the source ObservableSource at most { @code count } times . <p > <img width = 640 height = 336 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeatCount . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeat } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > repeat ( long times ) { if ( times < 0 ) { throw new IllegalArgumentException ( \"times >= 0 required but it was \" + times ) ; } if ( times == 0 ) { return empty ( ) ; } return RxJavaPlugins . onAssembly ( new ObservableRepeat < T > ( this , times ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that repeats the sequence of items emitted by the source ObservableSource until the provided stop function returns true . <p > <img width = 640 height = 262 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeatUntil . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeatUntil } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > repeatUntil ( BooleanSupplier stop ) { ObjectHelper . requireNonNull ( stop , \"stop is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableRepeatUntil < T > ( this , stop ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the same values as the source ObservableSource with the exception of an { @code onComplete } . An { @code onComplete } notification from the source will result in the emission of a { @code void } item to the ObservableSource provided as an argument to the { @code notificationHandler } function . If that ObservableSource calls { @code onComplete } or { @code onError } then { @code repeatWhen } will call { @code onComplete } or { @code onError } on the child subscription . Otherwise this ObservableSource will resubscribe to the source ObservableSource . <p > <img width = 640 height = 430 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeatWhen . f . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeatWhen } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > repeatWhen ( final Function < ? super Observable < Object > , ? extends ObservableSource < ? > > handler ) { ObjectHelper . requireNonNull ( handler , \"handler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableRepeatWhen < T > ( this , handler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items that are the results of invoking a specified selector on the items emitted by a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource . <p > <img width = 640 height = 449 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . f . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > replay ( Function < ? super Observable < T > , ? extends ObservableSource < R > > selector ) { ObjectHelper . requireNonNull ( selector , \"selector is null\" ) ; return ObservableReplay . multicastSelector ( ObservableInternalHelper . replayCallable ( this ) , selector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items that are the results of invoking a specified selector on items emitted by a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource replaying no more than { @code bufferSize } items that were emitted within a specified time window . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 350 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . fnt . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final < R > Observable < R > replay ( Function < ? super Observable < T > , ? extends ObservableSource < R > > selector , int bufferSize , long time , TimeUnit unit ) { return replay ( selector , bufferSize , time , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items that are the results of invoking a specified selector on items emitted by a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource . <p > <img width = 640 height = 406 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . fs . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final < R > Observable < R > replay ( final Function < ? super Observable < T > , ? extends ObservableSource < R > > selector , final Scheduler scheduler ) { ObjectHelper . requireNonNull ( selector , \"selector is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return ObservableReplay . multicastSelector ( ObservableInternalHelper . replayCallable ( this ) , ObservableInternalHelper . replayFunction ( selector , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource that replays at most { @code bufferSize } items emitted by that ObservableSource . A Connectable ObservableSource resembles an ordinary ObservableSource except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . n . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final ConnectableObservable < T > replay ( final int bufferSize ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return ObservableReplay . create ( this , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource and replays at most { @code bufferSize } items that were emitted during a specified time window . A Connectable ObservableSource resembles an ordinary ObservableSource except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . nt . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final ConnectableObservable < T > replay ( int bufferSize , long time , TimeUnit unit ) { return replay ( bufferSize , time , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource and that replays a maximum of { @code bufferSize } items that are emitted within a specified time window . A Connectable ObservableSource resembles an ordinary ObservableSource except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . nts . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final ConnectableObservable < T > replay ( final int bufferSize , final long time , final TimeUnit unit , final Scheduler scheduler ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return ObservableReplay . create ( this , time , unit , scheduler , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource and replays at most { @code bufferSize } items emitted by that ObservableSource . A Connectable ObservableSource resembles an ordinary ObservableSource except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . ns . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final ConnectableObservable < T > replay ( final int bufferSize , final Scheduler scheduler ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return ObservableReplay . observeOn ( replay ( bufferSize ) , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableObservable } that shares a single subscription to the source ObservableSource that will replay all of its items and notifications to any future { @link Observer } on the given { @link Scheduler } . A Connectable ObservableSource resembles an ordinary ObservableSource except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . o . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final ConnectableObservable < T > replay ( final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return ObservableReplay . observeOn ( replay ( ) , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource resubscribing to it if it calls { @code onError } ( infinite retry count ) . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . png alt = > <p > If the source ObservableSource calls { @link Observer#onError } this method will resubscribe to the source ObservableSource rather than propagating the { @code onError } call . <p > Any and all items emitted by the source ObservableSource will be emitted by the resulting ObservableSource even those emitted during failed subscriptions . For example if an ObservableSource fails at first but emits { @code [ 1 2 ] } then succeeds the second time and emits { @code [ 1 2 3 4 5 ] } then the complete sequence of emissions and notifications would be { @code [ 1 2 1 2 3 4 5 onComplete ] } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > retry ( ) { return retry ( Long . MAX_VALUE , Functions . alwaysTrue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource resubscribing to it if it calls { @code onError } and the predicate returns true for that specific exception and retry count . <p > <img width = 640 height = 235 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . o . ne . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > retry ( BiPredicate < ? super Integer , ? super Throwable > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableRetryBiPredicate < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource resubscribing to it if it calls { @code onError } up to a specified number of retries . <p > <img width = 640 height = 325 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . o . n . png alt = > <p > If the source ObservableSource calls { @link Observer#onError } this method will resubscribe to the source ObservableSource for a maximum of { @code count } resubscriptions rather than propagating the { @code onError } call . <p > Any and all items emitted by the source ObservableSource will be emitted by the resulting ObservableSource even those emitted during failed subscriptions . For example if an ObservableSource fails at first but emits { @code [ 1 2 ] } then succeeds the second time and emits { @code [ 1 2 3 4 5 ] } then the complete sequence of emissions and notifications would be { @code [ 1 2 1 2 3 4 5 onComplete ] } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > retry ( long times ) { return retry ( times , Functions . alwaysTrue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retries at most times or until the predicate returns false whichever happens first . <p > <img width = 640 height = 269 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . o . nfe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > retry ( long times , Predicate < ? super Throwable > predicate ) { if ( times < 0 ) { throw new IllegalArgumentException ( \"times >= 0 required but it was \" + times ) ; } ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableRetryPredicate < T > ( this , times , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retries the current Observable if the predicate returns true . <p > <img width = 640 height = 248 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . o . e . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > retry ( Predicate < ? super Throwable > predicate ) { return retry ( Long . MAX_VALUE , predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the same values as the source ObservableSource with the exception of an { @code onError } . An { @code onError } notification from the source will result in the emission of a { @link Throwable } item to the ObservableSource provided as an argument to the { @code notificationHandler } function . If that ObservableSource calls { @code onComplete } or { @code onError } then { @code retry } will call { @code onComplete } or { @code onError } on the child subscription . Otherwise this ObservableSource will resubscribe to the source ObservableSource . <p > <img width = 640 height = 430 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retryWhen . f . png alt = > <p > Example : [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > retryWhen ( final Function < ? super Observable < Throwable > , ? extends ObservableSource < ? > > handler ) { ObjectHelper . requireNonNull ( handler , \"handler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableRetryWhen < T > ( this , handler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the most recently emitted item ( if any ) emitted by the source ObservableSource within periodic time intervals . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sample . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sample } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > sample ( long period , TimeUnit unit ) { return sample ( period , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the most recently emitted item ( if any ) emitted by the source ObservableSource within periodic time intervals where the intervals are defined on a particular Scheduler . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sample . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > sample ( long period , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSampleTimed < T > ( this , period , unit , scheduler , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that when the specified { @code sampler } ObservableSource emits an item or completes emits the most recently emitted item ( if any ) emitted by the source ObservableSource since the previous emission from the { @code sampler } ObservableSource . <p > <img width = 640 height = 289 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sample . o . nolast . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code sample } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < T > sample ( ObservableSource < U > sampler ) { ObjectHelper . requireNonNull ( sampler , \"sampler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSampleWithObservable < T > ( this , sampler , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that applies a specified accumulator function to the first item emitted by a source ObservableSource then feeds the result of that function along with the second item emitted by the source ObservableSource into the same function and so on until all items have been emitted by the source ObservableSource emitting the result of each of these iterations . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / scan . png alt = > <p > This sort of function is sometimes called an accumulator . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code scan } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > scan ( BiFunction < T , T , T > accumulator ) { ObjectHelper . requireNonNull ( accumulator , \"accumulator is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableScan < T > ( this , accumulator ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that applies a specified accumulator function to the first item emitted by a source ObservableSource and a seed value then feeds the result of that function along with the second item emitted by the source ObservableSource into the same function and so on until all items have been emitted by the source ObservableSource emitting the result of each of these iterations . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / scanSeed . png alt = > <p > This sort of function is sometimes called an accumulator . <p > Note that the ObservableSource that results from this method will emit { @code initialValue } as its first emitted item . <p > Note that the { @code initialValue } is shared among all subscribers to the resulting ObservableSource and may cause problems if it is mutable . To make sure each subscriber gets its own value defer the application of this operator via { @link #defer ( Callable ) } : <pre > <code > ObservableSource&lt ; T&gt ; source = ... Observable . defer (( ) - &gt ; source . scan ( new ArrayList&lt ; &gt ; () ( list item ) - &gt ; list . add ( item ))) ; [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > scan ( final R initialValue , BiFunction < R , ? super T , R > accumulator ) { ObjectHelper . requireNonNull ( initialValue , \"initialValue is null\" ) ; return scanWith ( Functions . justCallable ( initialValue ) , accumulator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that applies a specified accumulator function to the first item emitted by a source ObservableSource and a seed value then feeds the result of that function along with the second item emitted by the source ObservableSource into the same function and so on until all items have been emitted by the source ObservableSource emitting the result of each of these iterations . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / scanSeed . png alt = > <p > This sort of function is sometimes called an accumulator . <p > Note that the ObservableSource that results from this method will emit the value returned by the { @code seedSupplier } as its first item . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code scanWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > scanWith ( Callable < R > seedSupplier , BiFunction < R , ? super T , R > accumulator ) { ObjectHelper . requireNonNull ( seedSupplier , \"seedSupplier is null\" ) ; ObjectHelper . requireNonNull ( accumulator , \"accumulator is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableScanSeed < T , R > ( this , seedSupplier , accumulator ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forces an ObservableSource s emissions and notifications to be serialized and for it to obey <a href = http : // reactivex . io / documentation / contract . html > the ObservableSource contract< / a > in other ways . <p > It is possible for an ObservableSource to invoke its Observers methods asynchronously perhaps from different threads . This could make such an ObservableSource poorly - behaved in that it might try to invoke { @code onComplete } or { @code onError } before one of its { @code onNext } invocations or it might call { @code onNext } from two different threads concurrently . You can force such an ObservableSource to be well - behaved and sequential by applying the { @code serialize } method to it . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / synchronize . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code serialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > serialize ( ) { return RxJavaPlugins . onAssembly ( new ObservableSerialized < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that completes if this Observable is empty or emits the single item emitted by this Observable or signals an { @code IllegalArgumentException } if this Observable emits more than one item . <p > <img width = 640 height = 217 src = https : // raw . githubusercontent . com / wiki / ReactiveX / RxJava / images / rx - operators / singleElement . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code singleElement } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > singleElement ( ) { return RxJavaPlugins . onAssembly ( new ObservableSingleMaybe < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the single item emitted by this Observable if this Observable emits only a single item or a default item if the source ObservableSource emits no items . If the source ObservableSource emits more than one item an { @code IllegalArgumentException } is signalled instead . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / single . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code single } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > single ( T defaultItem ) { ObjectHelper . requireNonNull ( defaultItem , \"defaultItem is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSingleSingle < T > ( this , defaultItem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the single item emitted by this Observable if this Observable emits only a single item otherwise if this Observable completes without emitting any items or emits more than one item a { @link NoSuchElementException } or { @code IllegalArgumentException } will be signalled respectively . <p > <img width = 640 height = 228 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / singleOrError . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code singleOrError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > singleOrError ( ) { return RxJavaPlugins . onAssembly ( new ObservableSingleSingle < T > ( this , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that skips the first { @code count } items emitted by the source ObservableSource and emits the remainder . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skip . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code skip } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > skip ( long count ) { if ( count <= 0 ) { return RxJavaPlugins . onAssembly ( this ) ; } return RxJavaPlugins . onAssembly ( new ObservableSkip < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that skips values emitted by the source ObservableSource before a specified time window elapses . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skip . t . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code skip } does not operate on any particular scheduler but uses the current time from the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > skip ( long time , TimeUnit unit ) { return skipUntil ( timer ( time , unit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that skips values emitted by the source ObservableSource before a specified time window on a specified { @link Scheduler } elapses . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skip . ts . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use for the timed skipping< / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > skip ( long time , TimeUnit unit , Scheduler scheduler ) { return skipUntil ( timer ( time , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that drops a specified number of items from the end of the sequence emitted by the source ObservableSource . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipLast . png alt = > <p > This Observer accumulates a queue long enough to store the first { @code count } items . As more items are received items are taken from the front of the queue and emitted by the returned ObservableSource . This causes such items to be delayed . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code skipLast } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > skipLast ( int count ) { if ( count < 0 ) { throw new IndexOutOfBoundsException ( \"count >= 0 required but it was \" + count ) ; } if ( count == 0 ) { return RxJavaPlugins . onAssembly ( this ) ; } return RxJavaPlugins . onAssembly ( new ObservableSkipLast < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that drops items emitted by the source ObservableSource during a specified time window before the source completes . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipLast . t . png alt = > <p > Note : this action will cache the latest items arriving in the specified time window . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code skipLast } does not operate on any particular scheduler but uses the current time from the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . TRAMPOLINE ) public final Observable < T > skipLast ( long time , TimeUnit unit ) { return skipLast ( time , unit , Schedulers . trampoline ( ) , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that drops items emitted by the source ObservableSource during a specified time window ( defined on a specified scheduler ) before the source completes . <p > <img width = 640 height = 340 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipLast . ts . png alt = > <p > Note : this action will cache the latest items arriving in the specified time window . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use for tracking the current time< / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > skipLast ( long time , TimeUnit unit , Scheduler scheduler ) { return skipLast ( time , unit , scheduler , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that drops items emitted by the source ObservableSource during a specified time window ( defined on a specified scheduler ) before the source completes . <p > <img width = 640 height = 340 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipLast . ts . png alt = > <p > Note : this action will cache the latest items arriving in the specified time window . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > skipLast ( long time , TimeUnit unit , Scheduler scheduler , boolean delayError , int bufferSize ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; // the internal buffer holds pairs of (timestamp, value) so double the default buffer size int s = bufferSize << 1 ; return RxJavaPlugins . onAssembly ( new ObservableSkipLastTimed < T > ( this , time , unit , scheduler , s , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that skips items emitted by the source ObservableSource until a second ObservableSource emits an item . <p > <img width = 640 height = 375 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipUntil . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code skipUntil } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < T > skipUntil ( ObservableSource < U > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSkipUntil < T , U > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that skips all items emitted by the source ObservableSource as long as a specified condition holds true but emits all further source items as soon as the condition becomes false . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipWhile . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code skipWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > skipWhile ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSkipWhile < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the events emitted by source ObservableSource in a sorted order . Each item emitted by the ObservableSource must implement { @link Comparable } with respect to all other items in the sequence . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sorted . png alt = > <p > If any item emitted by this Observable does not implement { @link Comparable } with respect to all other items emitted by this Observable no items will be emitted and the sequence is terminated with a { @link ClassCastException } . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > sorted ( ) { return toList ( ) . toObservable ( ) . map ( Functions . listSorter ( Functions . < T > naturalComparator ( ) ) ) . flatMapIterable ( Functions . < List < T > > identity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the events emitted by source ObservableSource in a sorted order based on a specified comparison function . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > sorted ( Comparator < ? super T > sortFunction ) { ObjectHelper . requireNonNull ( sortFunction , \"sortFunction is null\" ) ; return toList ( ) . toObservable ( ) . map ( Functions . listSorter ( sortFunction ) ) . flatMapIterable ( Functions . < List < T > > identity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items in a specified { @link Iterable } before it begins to emit items emitted by the source ObservableSource . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / startWith . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code startWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > startWith ( Iterable < ? extends T > items ) { return concatArray ( fromIterable ( items ) , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items in a specified { @link ObservableSource } before it begins to emit items emitted by the source ObservableSource . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / startWith . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code startWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > startWith ( ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return concatArray ( other , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits a specified item before it begins to emit items emitted by the source ObservableSource . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / startWith . item . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code startWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > startWith ( T item ) { ObjectHelper . requireNonNull ( item , \"item is null\" ) ; return concatArray ( just ( item ) , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the specified items before it begins to emit items emitted by the source ObservableSource . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / startWithArray . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code startWithArray } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > startWithArray ( T ... items ) { Observable < T > fromArray = fromArray ( items ) ; if ( fromArray == empty ( ) ) { return RxJavaPlugins . onAssembly ( this ) ; } return concatArray ( fromArray , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to an ObservableSource and provides a callback to handle the items it emits . <p > If the Observable emits an error it is wrapped into an { @link io . reactivex . exceptions . OnErrorNotImplementedException OnErrorNotImplementedException } and routed to the RxJavaPlugins . onError handler . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( Consumer < ? super T > onNext ) { return subscribe ( onNext , Functions . ON_ERROR_MISSING , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to an ObservableSource and provides callbacks to handle the items it emits and any error notification it issues . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( Consumer < ? super T > onNext , Consumer < ? super Throwable > onError ) { return subscribe ( onNext , onError , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to an ObservableSource and provides callbacks to handle the items it emits and any error or completion notification it issues . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( Consumer < ? super T > onNext , Consumer < ? super Throwable > onError , Action onComplete , Consumer < ? super Disposable > onSubscribe ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; LambdaObserver < T > ls = new LambdaObserver < T > ( onNext , onError , onComplete , onSubscribe ) ; subscribe ( ls ) ; return ls ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously subscribes Observers to this ObservableSource on the specified { @link Scheduler } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / subscribeOn . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > subscribeOn ( Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSubscribeOn < T > ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items emitted by the source ObservableSource or the items of an alternate ObservableSource if the source ObservableSource is empty . <p > <img width = 640 height = 255 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchifempty . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchIfEmpty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > switchIfEmpty ( ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchIfEmpty < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new ObservableSource by applying a function that you supply to each item emitted by the source ObservableSource that returns an ObservableSource and then emitting the items emitted by the most recently emitted of these ObservableSources . <p > The resulting ObservableSource completes if both the upstream ObservableSource and the last inner ObservableSource if any complete . If the upstream ObservableSource signals an onError the inner ObservableSource is disposed and the error delivered in - sequence . <p > <img width = 640 height = 350 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchMap . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > switchMap ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper , int bufferSize ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; if ( this instanceof ScalarCallable ) { @ SuppressWarnings ( \"unchecked\" ) T v = ( ( ScalarCallable < T > ) this ) . call ( ) ; if ( v == null ) { return empty ( ) ; } return ObservableScalarXMap . scalarXMap ( v , mapper ) ; } return RxJavaPlugins . onAssembly ( new ObservableSwitchMap < T , R > ( this , mapper , bufferSize , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream values into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable switchMapCompletable ( @ NonNull Function < ? super T , ? extends CompletableSource > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMapCompletable < T > ( this , mapper , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream values into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable switchMapCompletableDelayError ( @ NonNull Function < ? super T , ? extends CompletableSource > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMapCompletable < T > ( this , mapper , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > switchMapMaybe ( @ NonNull Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMapMaybe < T , R > ( this , mapper , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > switchMapMaybeDelayError ( @ NonNull Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMapMaybe < T , R > ( this , mapper , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new ObservableSource by applying a function that you supply to each item emitted by the source ObservableSource that returns a SingleSource and then emitting the item emitted by the most recently emitted of these SingleSources . <p > The resulting ObservableSource completes if both the upstream ObservableSource and the last inner SingleSource if any complete . If the upstream ObservableSource signals an onError the inner SingleSource is disposed and the error delivered in - sequence . <p > <img width = 640 height = 531 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchMapSingle . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ NonNull public final < R > Observable < R > switchMapSingle ( @ NonNull Function < ? super T , ? extends SingleSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMapSingle < T , R > ( this , mapper , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new ObservableSource by applying a function that you supply to each item emitted by the source ObservableSource that returns a SingleSource and then emitting the item emitted by the most recently emitted of these SingleSources and delays any error until all SingleSources terminate . <p > The resulting ObservableSource completes if both the upstream ObservableSource and the last inner SingleSource if any complete . If the upstream ObservableSource signals an onError the termination of the last inner SingleSource will emit that error as is or wrapped into a CompositeException along with the other possible errors the former inner SingleSources signalled . <p > <img width = 640 height = 467 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchMapSingleDelayError . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ NonNull public final < R > Observable < R > switchMapSingleDelayError ( @ NonNull Function < ? super T , ? extends SingleSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableSwitchMapSingle < T , R > ( this , mapper , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new ObservableSource by applying a function that you supply to each item emitted by the source ObservableSource that returns an ObservableSource and then emitting the items emitted by the most recently emitted of these ObservableSources and delays any error until all ObservableSources terminate . <p > The resulting ObservableSource completes if both the upstream ObservableSource and the last inner ObservableSource if any complete . If the upstream ObservableSource signals an onError the termination of the last inner ObservableSource will emit that error as is or wrapped into a CompositeException along with the other possible errors the former inner ObservableSources signalled . <p > <img width = 640 height = 350 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchMap . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchMapDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > switchMapDelayError ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper ) { return switchMapDelayError ( mapper , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits only the first { @code count } items emitted by the source ObservableSource . If the source emits fewer than { @code count } items then all of its items are emitted . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / take . png alt = > <p > This method returns an ObservableSource that will invoke a subscribing { @link Observer } s { @link Observer#onNext onNext } function a maximum of { @code count } times before invoking { @link Observer#onComplete onComplete } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code take } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > take ( long count ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } return RxJavaPlugins . onAssembly ( new ObservableTake < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits those items emitted by source ObservableSource before a specified time runs out . <p > If time runs out before the { @code Observable } completes normally the { @code onComplete } event will be signaled on the default { @code computation } { @link Scheduler } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / take . t . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code take } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > take ( long time , TimeUnit unit ) { return takeUntil ( timer ( time , unit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits those items emitted by source ObservableSource before a specified time ( on a specified Scheduler ) runs out . <p > If time runs out before the { @code Observable } completes normally the { @code onComplete } event will be signaled on the provided { @link Scheduler } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / take . ts . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > take ( long time , TimeUnit unit , Scheduler scheduler ) { return takeUntil ( timer ( time , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits at most the last { @code count } items emitted by the source ObservableSource . If the source emits fewer than { @code count } items then all of its items are emitted . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeLast . n . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code takeLast } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > takeLast ( int count ) { if ( count < 0 ) { throw new IndexOutOfBoundsException ( \"count >= 0 required but it was \" + count ) ; } else if ( count == 0 ) { return RxJavaPlugins . onAssembly ( new ObservableIgnoreElements < T > ( this ) ) ; } else if ( count == 1 ) { return RxJavaPlugins . onAssembly ( new ObservableTakeLastOne < T > ( this ) ) ; } return RxJavaPlugins . onAssembly ( new ObservableTakeLast < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits at most a specified number of items from the source ObservableSource that were emitted in a specified window of time before the ObservableSource completed where the timing information is provided by a given Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeLast . tns . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use for tracking the current time< / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > takeLast ( long count , long time , TimeUnit unit , Scheduler scheduler , boolean delayError , int bufferSize ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; if ( count < 0 ) { throw new IndexOutOfBoundsException ( \"count >= 0 required but it was \" + count ) ; } return RxJavaPlugins . onAssembly ( new ObservableTakeLastTimed < T > ( this , count , time , unit , scheduler , bufferSize , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits the items emitted by the source Observable until a second ObservableSource emits an item . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeUntil . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code takeUntil } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Observable < T > takeUntil ( ObservableSource < U > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableTakeUntil < T , U > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items emitted by the source ObservableSource so long as each item satisfied a specified condition and then completes as soon as this condition is not satisfied . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeWhile . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code takeWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > takeWhile ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableTakeWhile < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits only the first item emitted by the source ObservableSource during sequential time windows of a specified duration . <p > This differs from { @link #throttleLast } in that this only tracks passage of time whereas { @link #throttleLast } ticks at scheduled intervals . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleFirst . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code throttleFirst } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > throttleFirst ( long windowDuration , TimeUnit unit ) { return throttleFirst ( windowDuration , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits only the first item emitted by the source ObservableSource during sequential time windows of a specified duration where the windows are managed by a specified Scheduler . <p > This differs from { @link #throttleLast } in that this only tracks passage of time whereas { @link #throttleLast } ticks at scheduled intervals . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleFirst . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > throttleFirst ( long skipDuration , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableThrottleFirstTimed < T > ( this , skipDuration , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits only the last item emitted by the source ObservableSource during sequential time windows of a specified duration . <p > This differs from { @link #throttleFirst } in that this ticks along at a scheduled interval whereas { @link #throttleFirst } does not tick it just tracks passage of time . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleLast . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code throttleLast } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > throttleLast ( long intervalDuration , TimeUnit unit ) { return sample ( intervalDuration , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits only the last item emitted by the source ObservableSource during sequential time windows of a specified duration where the duration is governed by a specified Scheduler . <p > This differs from { @link #throttleFirst } in that this ticks along at a scheduled interval whereas { @link #throttleFirst } does not tick it just tracks passage of time . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleLast . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > throttleLast ( long intervalDuration , TimeUnit unit , Scheduler scheduler ) { return sample ( intervalDuration , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource except that it drops items emitted by the source ObservableSource that are followed by newer items before a timeout value expires . The timer resets on each emission ( alias to { @link #debounce ( long TimeUnit Scheduler ) } ) . <p > <em > Note : < / em > If items keep being emitted by the source ObservableSource faster than the timeout then no items will be emitted by the resulting ObservableSource . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleWithTimeout . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code throttleWithTimeout } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > throttleWithTimeout ( long timeout , TimeUnit unit ) { return debounce ( timeout , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource except that it drops items emitted by the source ObservableSource that are followed by newer items before a timeout value expires on a specified Scheduler . The timer resets on each emission ( Alias to { @link #debounce ( long TimeUnit Scheduler ) } ) . <p > <em > Note : < / em > If items keep being emitted by the source ObservableSource faster than the timeout then no items will be emitted by the resulting ObservableSource . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleWithTimeout . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > throttleWithTimeout ( long timeout , TimeUnit unit , Scheduler scheduler ) { return debounce ( timeout , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits records of the time interval between consecutive items emitted by the source ObservableSource . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeInterval . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code timeInterval } does not operate on any particular scheduler but uses the current time from the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < Timed < T > > timeInterval ( ) { return timeInterval ( TimeUnit . MILLISECONDS , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits records of the time interval between consecutive items emitted by the source ObservableSource where this interval is computed on a specified Scheduler . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeInterval . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > The operator does not operate on any particular scheduler but uses the current time from the specified { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) // Supplied scheduler is only used for creating timestamps. public final Observable < Timed < T > > timeInterval ( TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableTimeInterval < T > ( this , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource but notifies observers of a { @code TimeoutException } if an item emitted by the source ObservableSource doesn t arrive within a window of time after the emission of the previous item where that period of time is measured by an ObservableSource that is a function of the previous item . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout3 . png alt = > <p > Note : The arrival of the first source item is never timed out . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code timeout } operates by default on the { @code immediate } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < V > Observable < T > timeout ( Function < ? super T , ? extends ObservableSource < V > > itemTimeoutIndicator ) { return timeout0 ( null , itemTimeoutIndicator , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource but that switches to a fallback ObservableSource if an item emitted by the source ObservableSource doesn t arrive within a window of time after the emission of the previous item where that period of time is measured by an ObservableSource that is a function of the previous item . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout4 . png alt = > <p > Note : The arrival of the first source item is never timed out . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code timeout } operates by default on the { @code immediate } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < V > Observable < T > timeout ( Function < ? super T , ? extends ObservableSource < V > > itemTimeoutIndicator , ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return timeout0 ( null , itemTimeoutIndicator , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource but applies a timeout policy for each emitted item . If the next item isn t emitted within the specified timeout duration starting from its predecessor the resulting ObservableSource terminates and notifies observers of a { @code TimeoutException } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 1 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code timeout } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > timeout ( long timeout , TimeUnit timeUnit ) { return timeout0 ( timeout , timeUnit , null , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource but applies a timeout policy for each emitted item . If the next item isn t emitted within the specified timeout duration starting from its predecessor the source ObservableSource is disposed and resulting ObservableSource begins instead to mirror a fallback ObservableSource . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code timeout } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < T > timeout ( long timeout , TimeUnit timeUnit , ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return timeout0 ( timeout , timeUnit , other , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource but applies a timeout policy for each emitted item using a specified Scheduler . If the next item isn t emitted within the specified timeout duration starting from its predecessor the source ObservableSource is disposed and resulting ObservableSource begins instead to mirror a fallback ObservableSource . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 2s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > timeout ( long timeout , TimeUnit timeUnit , Scheduler scheduler , ObservableSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return timeout0 ( timeout , timeUnit , other , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that mirrors the source ObservableSource but applies a timeout policy for each emitted item where this policy is governed on a specified Scheduler . If the next item isn t emitted within the specified timeout duration starting from its predecessor the resulting ObservableSource terminates and notifies observers of a { @code TimeoutException } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 1s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > timeout ( long timeout , TimeUnit timeUnit , Scheduler scheduler ) { return timeout0 ( timeout , timeUnit , null , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits each item emitted by the source ObservableSource wrapped in a { @link Timed } object whose timestamps are provided by a specified Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timestamp . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This operator does not operate on any particular scheduler but uses the current time from the specified { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) // Supplied scheduler is only used for creating timestamps. public final Observable < Timed < T > > timestamp ( Scheduler scheduler ) { return timestamp ( TimeUnit . MILLISECONDS , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits each item emitted by the source ObservableSource wrapped in a { @link Timed } object whose timestamps are provided by a specified Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timestamp . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This operator does not operate on any particular scheduler but uses the current time from the specified { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) // Supplied scheduler is only used for creating timestamps. public final Observable < Timed < T > > timestamp ( final TimeUnit unit , final Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return map ( Functions . < T > timestampWith ( unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a single item a list composed of all the items emitted by the finite source ObservableSource . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toList . 2 . png alt = > <p > Normally an ObservableSource that returns multiple items will do so by invoking its { @link Observer } s { @link Observer#onNext onNext } method for each such item . You can change this behavior instructing the ObservableSource to compose a list of all of these items and then to invoke the Observer s { @code onNext } function once passing it the entire list by calling the ObservableSource s { @code toList } method prior to calling its { @link #subscribe } method . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulated list to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toList } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < List < T > > toList ( final int capacityHint ) { ObjectHelper . verifyPositive ( capacityHint , \"capacityHint\" ) ; return RxJavaPlugins . onAssembly ( new ObservableToListSingle < T , List < T > > ( this , capacityHint ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a single item a list composed of all the items emitted by the finite source ObservableSource . <p > <img width = 640 height = 365 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toList . o . c . png alt = > <p > Normally an ObservableSource that returns multiple items will do so by invoking its { @link Observer } s { @link Observer#onNext onNext } method for each such item . You can change this behavior instructing the ObservableSource to compose a list of all of these items and then to invoke the Observer s { @code onNext } function once passing it the entire list by calling the ObservableSource s { @code toList } method prior to calling its { @link #subscribe } method . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulated collection to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toList } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U extends Collection < ? super T > > Single < U > toList ( Callable < U > collectionSupplier ) { ObjectHelper . requireNonNull ( collectionSupplier , \"collectionSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableToListSingle < T , U > ( this , collectionSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a single HashMap that contains an ArrayList of items emitted by the finite source ObservableSource keyed by a specified { @code keySelector } function . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toMultiMap . 2 . png alt = > <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulated map to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toMultimap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Single < Map < K , Collection < T > > > toMultimap ( Function < ? super T , ? extends K > keySelector ) { @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) Function < ? super T , ? extends T > valueSelector = ( Function ) Functions . identity ( ) ; Callable < Map < K , Collection < T > > > mapSupplier = HashMapSupplier . asCallable ( ) ; Function < K , List < T > > collectionFactory = ArrayListSupplier . asFunction ( ) ; return toMultimap ( keySelector , valueSelector , mapSupplier , collectionFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the current Observable into a Flowable by applying the specified backpressure strategy . <p > Marble diagrams for the various backpressure strategies are as follows : <ul > <li > { @link BackpressureStrategy#BUFFER } <p > <img width = 640 height = 274 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toFlowable . o . buffer . png alt = > < / li > <li > { @link BackpressureStrategy#DROP } <p > <img width = 640 height = 389 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toFlowable . o . drop . png alt = > < / li > <li > { @link BackpressureStrategy#LATEST } <p > <img width = 640 height = 296 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toFlowable . o . latest . png alt = > < / li > <li > { @link BackpressureStrategy#ERROR } <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toFlowable . o . error . png alt = > < / li > <li > { @link BackpressureStrategy#MISSING } <p > <img width = 640 height = 411 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toFlowable . o . missing . png alt = > < / li > < / ul > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator applies the chosen backpressure strategy of { @link BackpressureStrategy } enum . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toFlowable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > toFlowable ( BackpressureStrategy strategy ) { Flowable < T > f = new FlowableFromObservable < T > ( this ) ; switch ( strategy ) { case DROP : return f . onBackpressureDrop ( ) ; case LATEST : return f . onBackpressureLatest ( ) ; case MISSING : return f ; case ERROR : return RxJavaPlugins . onAssembly ( new FlowableOnBackpressureError < T > ( f ) ) ; default : return f . onBackpressureBuffer ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a list that contains the items emitted by the finite source ObservableSource in a sorted order . Each item emitted by the ObservableSource must implement { @link Comparable } with respect to all other items in the sequence . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < List < T > > toSortedList ( ) { return toSortedList ( Functions . naturalOrder ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source ObservableSource so that subscribers will dispose it on a specified { @link Scheduler } . <p > <img width = 640 height = 452 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / unsubscribeOn . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > unsubscribeOn ( Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableUnsubscribeOn < T > ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping windows each containing { @code count } items . When the source ObservableSource completes or encounters an error the resulting ObservableSource emits the current window and propagates the notification from the source ObservableSource . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window3 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < Observable < T > > window ( long count ) { return window ( count , count , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits windows every { @code skip } items each containing no more than { @code count } items . When the source ObservableSource completes or encounters an error the resulting ObservableSource emits the current window and propagates the notification from the source ObservableSource . <p > <img width = 640 height = 365 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window4 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < Observable < T > > window ( long count , long skip , int bufferSize ) { ObjectHelper . verifyPositive ( count , \"count\" ) ; ObjectHelper . verifyPositive ( skip , \"skip\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableWindow < T > ( this , count , skip , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource starts a new window periodically as determined by the { @code timeskip } argument . It emits each window after a fixed timespan specified by the { @code timespan } argument . When the source ObservableSource completes or ObservableSource completes or encounters an error the resulting ObservableSource emits the current window and propagates the notification from the source ObservableSource . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window7 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < Observable < T > > window ( long timespan , long timeskip , TimeUnit unit ) { return window ( timespan , timeskip , unit , Schedulers . computation ( ) , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource starts a new window periodically as determined by the { @code timeskip } argument . It emits each window after a fixed timespan specified by the { @code timespan } argument . When the source ObservableSource completes or ObservableSource completes or encounters an error the resulting ObservableSource emits the current window and propagates the notification from the source ObservableSource . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window7 . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < Observable < T > > window ( long timespan , long timeskip , TimeUnit unit , Scheduler scheduler , int bufferSize ) { ObjectHelper . verifyPositive ( timespan , \"timespan\" ) ; ObjectHelper . verifyPositive ( timeskip , \"timeskip\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableWindowTimed < T > ( this , timespan , timeskip , unit , scheduler , Long . MAX_VALUE , bufferSize , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping windows each of a fixed duration specified by the { @code timespan } argument . When the source ObservableSource completes or encounters an error the resulting ObservableSource emits the current window and propagates the notification from the source ObservableSource . <p > <img width = 640 height = 375 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window5 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Observable < Observable < T > > window ( long timespan , TimeUnit unit ) { return window ( timespan , unit , Schedulers . computation ( ) , Long . MAX_VALUE , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping windows each of a fixed duration specified by the { @code timespan } argument or a maximum size specified by the { @code count } argument ( whichever is reached first ) . When the source ObservableSource completes or encounters an error the resulting ObservableSource emits the current window and propagates the notification from the source ObservableSource . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window6 . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < Observable < T > > window ( long timespan , TimeUnit unit , Scheduler scheduler , long count ) { return window ( timespan , unit , scheduler , count , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping windows each of a fixed duration specified by the { @code timespan } argument or a maximum size specified by the { @code count } argument ( whichever is reached first ) . When the source ObservableSource completes or encounters an error the resulting ObservableSource emits the current window and propagates the notification from the source ObservableSource . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window6 . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < Observable < T > > window ( long timespan , TimeUnit unit , Scheduler scheduler , long count , boolean restart , int bufferSize ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . verifyPositive ( count , \"count\" ) ; return RxJavaPlugins . onAssembly ( new ObservableWindowTimed < T > ( this , timespan , timespan , unit , scheduler , count , bufferSize , restart ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits non - overlapping windows of items it collects from the source ObservableSource where the boundary of each window is determined by the items emitted from a specified boundary - governing ObservableSource . <p > <img width = 640 height = 475 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window8 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Observable < Observable < T > > window ( ObservableSource < B > boundary ) { return window ( boundary , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits windows that contain those items emitted by the source ObservableSource between the time when the { @code openingIndicator } ObservableSource emits an item and when the ObservableSource returned by { @code closingIndicator } emits an item . <p > <img width = 640 height = 550 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Observable < Observable < T > > window ( ObservableSource < U > openingIndicator , Function < ? super U , ? extends ObservableSource < V > > closingIndicator ) { return window ( openingIndicator , closingIndicator , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits windows that contain those items emitted by the source ObservableSource between the time when the { @code openingIndicator } ObservableSource emits an item and when the ObservableSource returned by { @code closingIndicator } emits an item . <p > <img width = 640 height = 550 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window2 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Observable < Observable < T > > window ( ObservableSource < U > openingIndicator , Function < ? super U , ? extends ObservableSource < V > > closingIndicator , int bufferSize ) { ObjectHelper . requireNonNull ( openingIndicator , \"openingIndicator is null\" ) ; ObjectHelper . requireNonNull ( closingIndicator , \"closingIndicator is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableWindowBoundarySelector < T , U , V > ( this , openingIndicator , closingIndicator , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits windows of items it collects from the source ObservableSource . The resulting ObservableSource emits connected non - overlapping windows . It emits the current window and opens a new one whenever the ObservableSource produced by the specified { @code closingIndicator } emits an item . <p > <img width = 640 height = 455 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window1 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Observable < Observable < T > > window ( Callable < ? extends ObservableSource < B > > boundary , int bufferSize ) { ObjectHelper . requireNonNull ( boundary , \"boundary is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new ObservableWindowBoundarySupplier < T , B > ( this , boundary , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items that are the result of applying a specified function to pairs of values one each from the source ObservableSource and a specified Iterable sequence . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / zip . i . png alt = > <p > Note that the { @code other } Iterable is evaluated as items are observed from the source ObservableSource ; it is not pre - consumed . This allows you to zip infinite streams on either side . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code zipWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Observable < R > zipWith ( Iterable < U > other , BiFunction < ? super T , ? super U , ? extends R > zipper ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableZipIterable < T , U , R > ( this , other , zipper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that emits items that are the result of applying a specified function to pairs of values one each from the source ObservableSource and another specified ObservableSource . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / zip . png alt = > <p > The operator subscribes to its sources in order they are specified and completes eagerly if one of the sources is shorter than the rest while disposing the other sources . Therefore it is possible those other sources will never be able to run to completion ( and thus not calling { @code doOnComplete () } ) . This can also happen if the sources are exactly the same length ; if source A completes and B has been consumed and is about to complete the operator detects A won t be sending further values and it will dispose B immediately . For example : <pre > <code > range ( 1 5 ) . doOnComplete ( action1 ) . zipWith ( range ( 6 5 ) . doOnComplete ( action2 ) ( a b ) - &gt ; a + b ) < / code > < / pre > { @code action1 } will be called but { @code action2 } won t . <br > To work around this termination property use { @link #doOnDispose ( Action ) } as well or use { @code using () } to do cleanup in case of completion or a dispose () call . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code zipWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Observable < R > zipWith ( ObservableSource < ? extends U > other , BiFunction < ? super T , ? super U , ? extends R > zipper ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return zip ( this , other , zipper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO fuse back to Observable [CODESPLIT] @ Override protected void subscribeActual ( MaybeObserver < ? super T > observer ) { source . subscribe ( new LastObserver < T > ( observer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { [CODESPLIT] @ NonNull @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public Observable < T > refCount ( ) { return RxJavaPlugins . onAssembly ( new ObservableRefCount < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the upstream { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > refCount ( int subscriberCount ) { return refCount ( subscriberCount , 0 , TimeUnit . NANOSECONDS , Schedulers . trampoline ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the upstream { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > refCount ( long timeout , TimeUnit unit , Scheduler scheduler ) { return refCount ( 1 , timeout , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the upstream { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Observable < T > refCount ( int subscriberCount , long timeout , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . verifyPositive ( subscriberCount , \"subscriberCount\" ) ; ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new ObservableRefCount < T > ( this , subscriberCount , timeout , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that automatically connects ( at most once ) to this ConnectableObservable when the specified number of Subscribers subscribe to it and calls the specified callback with the Subscription associated with the established connection . <p > <img width = 640 height = 348 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / autoConnect . o . png alt = > <p > The connection happens after the given number of subscriptions and happens at most once during the lifetime of the returned Observable . If this ConnectableObservable terminates the connection is never renewed no matter how Observers come and go . Use { @link #refCount () } to renew a connection or dispose an active connection when all { @code Observer } s have disposed their { @code Disposable } s . [CODESPLIT] @ NonNull public Observable < T > autoConnect ( int numberOfSubscribers , @ NonNull Consumer < ? super Disposable > connection ) { if ( numberOfSubscribers <= 0 ) { this . connect ( connection ) ; return RxJavaPlugins . onAssembly ( this ) ; } return RxJavaPlugins . onAssembly ( new ObservableAutoConnect < T > ( this , numberOfSubscribers , connection ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the number of subscribers and returns true if their number matches the parallelism level of this ParallelFlowable . [CODESPLIT] protected final boolean validate ( @ NonNull Subscriber < ? > [ ] subscribers ) { int p = parallelism ( ) ; if ( subscribers . length != p ) { Throwable iae = new IllegalArgumentException ( \"parallelism = \" + p + \", subscribers = \" + subscribers . length ) ; for ( Subscriber < ? > s : subscribers ) { EmptySubscription . error ( iae , s ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take a Publisher and prepare to consume it on multiple rails ( number of CPUs ) in a round - robin fashion . [CODESPLIT] @ CheckReturnValue public static < T > ParallelFlowable < T > from ( @ NonNull Publisher < ? extends T > source ) { return from ( source , Runtime . getRuntime ( ) . availableProcessors ( ) , Flowable . bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take a Publisher and prepare to consume it on parallelism number of rails in a round - robin fashion . [CODESPLIT] @ CheckReturnValue public static < T > ParallelFlowable < T > from ( @ NonNull Publisher < ? extends T > source , int parallelism ) { return from ( source , parallelism , Flowable . bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take a Publisher and prepare to consume it on parallelism number of rails possibly ordered and round - robin fashion and use custom prefetch amount and queue for dealing with the source Publisher s values . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > ParallelFlowable < T > from ( @ NonNull Publisher < ? extends T > source , int parallelism , int prefetch ) { ObjectHelper . requireNonNull ( source , \"source\" ) ; ObjectHelper . verifyPositive ( parallelism , \"parallelism\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ParallelFromPublisher < T > ( source , parallelism , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified converter function during assembly time and returns its resulting value . <p > This allows fluent conversion to any other type . <p > History : 2 . 1 . 7 - experimental [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > R as ( @ NonNull ParallelFlowableConverter < T , R > converter ) { return ObjectHelper . requireNonNull ( converter , \"converter is null\" ) . apply ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the source values on each rail to another value . <p > Note that the same mapper function may be called from multiple threads concurrently . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > map ( @ NonNull Function < ? super T , ? extends R > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper\" ) ; return RxJavaPlugins . onAssembly ( new ParallelMap < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the source values on each rail to another value and handles errors based on the given { [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > map ( @ NonNull Function < ? super T , ? extends R > mapper , @ NonNull ParallelFailureHandling errorHandler ) { ObjectHelper . requireNonNull ( mapper , \"mapper\" ) ; ObjectHelper . requireNonNull ( errorHandler , \"errorHandler is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelMapTry < T , R > ( this , mapper , errorHandler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters the source values on each rail . <p > Note that the same predicate may be called from multiple threads concurrently . [CODESPLIT] @ CheckReturnValue public final ParallelFlowable < T > filter ( @ NonNull Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate\" ) ; return RxJavaPlugins . onAssembly ( new ParallelFilter < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters the source values on each rail and handles errors based on the given { [CODESPLIT] @ CheckReturnValue public final ParallelFlowable < T > filter ( @ NonNull Predicate < ? super T > predicate , @ NonNull ParallelFailureHandling errorHandler ) { ObjectHelper . requireNonNull ( predicate , \"predicate\" ) ; ObjectHelper . requireNonNull ( errorHandler , \"errorHandler is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelFilterTry < T > ( this , predicate , errorHandler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies where each rail will observe its incoming values with no work - stealing and default prefetch amount . <p > This operator uses the default prefetch size returned by { @code Flowable . bufferSize () } . <p > The operator will call { @code Scheduler . createWorker () } as many times as this ParallelFlowable s parallelism level is . <p > No assumptions are made about the Scheduler s parallelism level if the Scheduler s parallelism level is lower than the ParallelFlowable s some rails may end up on the same thread / worker . <p > This operator doesn t require the Scheduler to be trampolining as it does its own built - in trampolining logic . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > runOn ( @ NonNull Scheduler scheduler ) { return runOn ( scheduler , Flowable . bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies where each rail will observe its incoming values with possibly work - stealing and a given prefetch amount . <p > This operator uses the default prefetch size returned by { @code Flowable . bufferSize () } . <p > The operator will call { @code Scheduler . createWorker () } as many times as this ParallelFlowable s parallelism level is . <p > No assumptions are made about the Scheduler s parallelism level if the Scheduler s parallelism level is lower than the ParallelFlowable s some rails may end up on the same thread / worker . <p > This operator doesn t require the Scheduler to be trampolining as it does its own built - in trampolining logic . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > runOn ( @ NonNull Scheduler scheduler , int prefetch ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ParallelRunOn < T > ( this , scheduler , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduces all values within a rail and across rails with a reducer function into a single sequential value . <p > Note that the same reducer function may be called from multiple threads concurrently . [CODESPLIT] @ CheckReturnValue @ NonNull public final Flowable < T > reduce ( @ NonNull BiFunction < T , T , T > reducer ) { ObjectHelper . requireNonNull ( reducer , \"reducer\" ) ; return RxJavaPlugins . onAssembly ( new ParallelReduceFull < T > ( this , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduces all values within a rail to a single value ( with a possibly different type ) via a reducer function that is initialized on each rail from an initialSupplier value . <p > Note that the same mapper function may be called from multiple threads concurrently . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > reduce ( @ NonNull Callable < R > initialSupplier , @ NonNull BiFunction < R , ? super T , R > reducer ) { ObjectHelper . requireNonNull ( initialSupplier , \"initialSupplier\" ) ; ObjectHelper . requireNonNull ( reducer , \"reducer\" ) ; return RxJavaPlugins . onAssembly ( new ParallelReduce < T , R > ( this , initialSupplier , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the values from each rail in a round - robin or same - order fashion and exposes it as a regular Publisher sequence running with a default prefetch value for the rails . <p > This operator uses the default prefetch size returned by { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ CheckReturnValue public final Flowable < T > sequential ( ) { return sequential ( Flowable . bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the values from each rail in a round - robin or same - order fashion and exposes it as a regular Publisher sequence running with a give prefetch value for the rails . <img width = 640 height = 602 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / parallelflowable . sequential . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ CheckReturnValue @ NonNull public final Flowable < T > sequential ( int prefetch ) { ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ParallelJoin < T > ( this , prefetch , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the values from each rail in a round - robin or same - order fashion and exposes it as a regular Flowable sequence running with a default prefetch value for the rails and delaying errors from all rails till all terminate . <p > This operator uses the default prefetch size returned by { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ CheckReturnValue @ NonNull public final Flowable < T > sequentialDelayError ( ) { return sequentialDelayError ( Flowable . bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the values from each rail in a round - robin or same - order fashion and exposes it as a regular Publisher sequence running with a give prefetch value for the rails and delaying errors from all rails till all terminate . <img width = 640 height = 602 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / parallelflowable . sequential . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ CheckReturnValue @ NonNull public final Flowable < T > sequentialDelayError ( int prefetch ) { ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ParallelJoin < T > ( this , prefetch , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the rails of this ParallelFlowable and returns a Publisher that sequentially picks the smallest next value from the rails . <p > This operator requires a finite source ParallelFlowable . [CODESPLIT] @ CheckReturnValue @ NonNull public final Flowable < T > sorted ( @ NonNull Comparator < ? super T > comparator ) { return sorted ( comparator , 16 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the rails according to the comparator and returns a full sorted list as a Publisher . <p > This operator requires a finite source ParallelFlowable . [CODESPLIT] @ CheckReturnValue @ NonNull public final Flowable < List < T > > toSortedList ( @ NonNull Comparator < ? super T > comparator ) { return toSortedList ( comparator , 16 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the rails according to the comparator and returns a full sorted list as a Publisher . <p > This operator requires a finite source ParallelFlowable . [CODESPLIT] @ CheckReturnValue @ NonNull public final Flowable < List < T > > toSortedList ( @ NonNull Comparator < ? super T > comparator , int capacityHint ) { ObjectHelper . requireNonNull ( comparator , \"comparator is null\" ) ; ObjectHelper . verifyPositive ( capacityHint , \"capacityHint\" ) ; int ch = capacityHint / parallelism ( ) + 1 ; ParallelFlowable < List < T > > railReduced = reduce ( Functions . < T > createArrayList ( ch ) , ListAddBiConsumer . < T > instance ( ) ) ; ParallelFlowable < List < T > > railSorted = railReduced . map ( new SorterFunction < T > ( comparator ) ) ; Flowable < List < T > > merged = railSorted . reduce ( new MergerBiFunction < T > ( comparator ) ) ; return RxJavaPlugins . onAssembly ( merged ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the specified consumer with the current element passing through any rail . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doOnNext ( @ NonNull Consumer < ? super T > onNext ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , onNext , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) , Functions . EMPTY_LONG_CONSUMER , Functions . EMPTY_ACTION ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the specified consumer with the current element passing through any rail and handles errors based on the given { [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doOnNext ( @ NonNull Consumer < ? super T > onNext , @ NonNull ParallelFailureHandling errorHandler ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( errorHandler , \"errorHandler is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelDoOnNextTry < T > ( this , onNext , errorHandler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the specified consumer with the current element passing through any rail after it has been delivered to downstream within the rail . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doAfterNext ( @ NonNull Consumer < ? super T > onAfterNext ) { ObjectHelper . requireNonNull ( onAfterNext , \"onAfterNext is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , Functions . emptyConsumer ( ) , onAfterNext , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) , Functions . EMPTY_LONG_CONSUMER , Functions . EMPTY_ACTION ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the specified consumer with the exception passing through any rail . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doOnError ( @ NonNull Consumer < Throwable > onError ) { ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , onError , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) , Functions . EMPTY_LONG_CONSUMER , Functions . EMPTY_ACTION ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the specified Action when a rail completes . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doOnComplete ( @ NonNull Action onComplete ) { ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , onComplete , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) , Functions . EMPTY_LONG_CONSUMER , Functions . EMPTY_ACTION ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the specified Action when a rail completes or signals an error . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doAfterTerminated ( @ NonNull Action onAfterTerminate ) { ObjectHelper . requireNonNull ( onAfterTerminate , \"onAfterTerminate is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , onAfterTerminate , Functions . emptyConsumer ( ) , Functions . EMPTY_LONG_CONSUMER , Functions . EMPTY_ACTION ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the specified callback when a rail receives a Subscription from its upstream . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doOnSubscribe ( @ NonNull Consumer < ? super Subscription > onSubscribe ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , onSubscribe , Functions . EMPTY_LONG_CONSUMER , Functions . EMPTY_ACTION ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the specified consumer with the request amount if any rail receives a request . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doOnRequest ( @ NonNull LongConsumer onRequest ) { ObjectHelper . requireNonNull ( onRequest , \"onRequest is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) , onRequest , Functions . EMPTY_ACTION ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the specified Action when a rail receives a cancellation . [CODESPLIT] @ CheckReturnValue @ NonNull public final ParallelFlowable < T > doOnCancel ( @ NonNull Action onCancel ) { ObjectHelper . requireNonNull ( onCancel , \"onCancel is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelPeek < T > ( this , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . emptyConsumer ( ) , Functions . EMPTY_LONG_CONSUMER , onCancel ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect the elements in each rail into a collection supplied via a collectionSupplier and collected into with a collector action emitting the collection at the end . [CODESPLIT] @ CheckReturnValue @ NonNull public final < C > ParallelFlowable < C > collect ( @ NonNull Callable < ? extends C > collectionSupplier , @ NonNull BiConsumer < ? super C , ? super T > collector ) { ObjectHelper . requireNonNull ( collectionSupplier , \"collectionSupplier is null\" ) ; ObjectHelper . requireNonNull ( collector , \"collector is null\" ) ; return RxJavaPlugins . onAssembly ( new ParallelCollect < T , C > ( this , collectionSupplier , collector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps multiple Publishers into a ParallelFlowable which runs them in parallel and unordered . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > ParallelFlowable < T > fromArray ( @ NonNull Publisher < T > ... publishers ) { if ( publishers . length == 0 ) { throw new IllegalArgumentException ( \"Zero publishers not supported\" ) ; } return RxJavaPlugins . onAssembly ( new ParallelFromArray < T > ( publishers ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a fluent transformation to a value via a converter function which receives this ParallelFlowable . [CODESPLIT] @ CheckReturnValue @ NonNull public final < U > U to ( @ NonNull Function < ? super ParallelFlowable < T > , U > converter ) { try { return ObjectHelper . requireNonNull ( converter , \"converter is null\" ) . apply ( this ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows composing operators in assembly time on top of this ParallelFlowable and returns another ParallelFlowable with composed features . [CODESPLIT] @ CheckReturnValue @ NonNull public final < U > ParallelFlowable < U > compose ( @ NonNull ParallelTransformer < T , U > composer ) { return RxJavaPlugins . onAssembly ( ObjectHelper . requireNonNull ( composer , \"composer is null\" ) . apply ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates and flattens Publishers on each rail optionally delaying errors . <p > It uses unbounded concurrency along with default inner prefetch . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > flatMap ( @ NonNull Function < ? super T , ? extends Publisher < ? extends R > > mapper , boolean delayError ) { return flatMap ( mapper , delayError , Integer . MAX_VALUE , Flowable . bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates and flattens Publishers on each rail optionally delaying errors having a total number of simultaneous subscriptions to the inner Publishers and using the given prefetch amount for the inner Publishers . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > flatMap ( @ NonNull Function < ? super T , ? extends Publisher < ? extends R > > mapper , boolean delayError , int maxConcurrency , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ParallelFlatMap < T , R > ( this , mapper , delayError , maxConcurrency , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates and concatenates Publishers on each rail signalling errors immediately and generating 2 publishers upfront . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > concatMap ( @ NonNull Function < ? super T , ? extends Publisher < ? extends R > > mapper ) { return concatMap ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates and concatenates Publishers on each rail signalling errors immediately and using the given prefetch amount for generating Publishers upfront . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > concatMap ( @ NonNull Function < ? super T , ? extends Publisher < ? extends R > > mapper , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ParallelConcatMap < T , R > ( this , mapper , prefetch , ErrorMode . IMMEDIATE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates and concatenates Publishers on each rail optionally delaying errors and generating 2 publishers upfront . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > concatMapDelayError ( @ NonNull Function < ? super T , ? extends Publisher < ? extends R > > mapper , boolean tillTheEnd ) { return concatMapDelayError ( mapper , 2 , tillTheEnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates and concatenates Publishers on each rail optionally delaying errors and using the given prefetch amount for generating Publishers upfront . [CODESPLIT] @ CheckReturnValue @ NonNull public final < R > ParallelFlowable < R > concatMapDelayError ( @ NonNull Function < ? super T , ? extends Publisher < ? extends R > > mapper , int prefetch , boolean tillTheEnd ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new ParallelConcatMap < T , R > ( this , mapper , prefetch , tillTheEnd ? ErrorMode . END : ErrorMode . BOUNDARY ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a connectable observable factory it multicasts over the generated ConnectableObservable via a selector function . [CODESPLIT] public static < U , R > Observable < R > multicastSelector ( final Callable < ? extends ConnectableObservable < U > > connectableFactory , final Function < ? super Observable < U > , ? extends ObservableSource < R > > selector ) { return RxJavaPlugins . onAssembly ( new MulticastReplay < R , U > ( connectableFactory , selector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Child Observers will observe the events of the ConnectableObservable on the specified scheduler . [CODESPLIT] public static < T > ConnectableObservable < T > observeOn ( final ConnectableObservable < T > co , final Scheduler scheduler ) { final Observable < T > observable = co . observeOn ( scheduler ) ; return RxJavaPlugins . onAssembly ( new Replay < T > ( co , observable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with an unbounded buffer . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > ConnectableObservable < T > createFrom ( ObservableSource < ? extends T > source ) { return create ( source , DEFAULT_UNBOUNDED_FACTORY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with a size bound buffer . [CODESPLIT] public static < T > ConnectableObservable < T > create ( ObservableSource < T > source , final int bufferSize ) { if ( bufferSize == Integer . MAX_VALUE ) { return createFrom ( source ) ; } return create ( source , new ReplayBufferSupplier < T > ( bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with a time bound buffer . [CODESPLIT] public static < T > ConnectableObservable < T > create ( ObservableSource < T > source , long maxAge , TimeUnit unit , Scheduler scheduler ) { return create ( source , maxAge , unit , scheduler , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with a size and time bound buffer . [CODESPLIT] public static < T > ConnectableObservable < T > create ( ObservableSource < T > source , final long maxAge , final TimeUnit unit , final Scheduler scheduler , final int bufferSize ) { return create ( source , new ScheduledReplaySupplier < T > ( bufferSize , maxAge , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a OperatorReplay instance to replay values of the given source observable . [CODESPLIT] static < T > ConnectableObservable < T > create ( ObservableSource < T > source , final BufferSupplier < T > bufferFactory ) { // the current connection to source needs to be shared between the operator and its onSubscribe call final AtomicReference < ReplayObserver < T > > curr = new AtomicReference < ReplayObserver < T > > ( ) ; ObservableSource < T > onSubscribe = new ReplaySource < T > ( curr , bufferFactory ) ; return RxJavaPlugins . onAssembly ( new ObservableReplay < T > ( onSubscribe , source , curr , bufferFactory ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the resource at the specified index and disposes the old resource . [CODESPLIT] public boolean setResource ( int index , Subscription resource ) { for ( ; ; ) { Subscription o = get ( index ) ; if ( o == SubscriptionHelper . CANCELLED ) { if ( resource != null ) { resource . cancel ( ) ; } return false ; } if ( compareAndSet ( index , o , resource ) ) { if ( o != null ) { o . cancel ( ) ; } return true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the resource at the specified index and returns the old resource . [CODESPLIT] public Subscription replaceResource ( int index , Subscription resource ) { for ( ; ; ) { Subscription o = get ( index ) ; if ( o == SubscriptionHelper . CANCELLED ) { if ( resource != null ) { resource . cancel ( ) ; } return null ; } if ( compareAndSet ( index , o , resource ) ) { return o ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an UnicastProcessor with the given internal buffer capacity hint . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > UnicastProcessor < T > create ( int capacityHint ) { return new UnicastProcessor < T > ( capacityHint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an UnicastProcessor with default internal buffer capacity hint and delay error flag . <p > History : 2 . 0 . 8 - experimental [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > UnicastProcessor < T > create ( boolean delayError ) { return new UnicastProcessor < T > ( bufferSize ( ) , null , delayError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an UnicastProcessor with the given internal buffer capacity hint and a callback for the case when the single Subscriber cancels its subscription . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > UnicastProcessor < T > create ( int capacityHint , Runnable onCancelled ) { ObjectHelper . requireNonNull ( onCancelled , \"onTerminate\" ) ; return new UnicastProcessor < T > ( capacityHint , onCancelled ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to subscribe to a possibly Callable source s mapped Publisher . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T , R > boolean tryScalarXMapSubscribe ( Publisher < T > source , Subscriber < ? super R > subscriber , Function < ? super T , ? extends Publisher < ? extends R > > mapper ) { if ( source instanceof Callable ) { T t ; try { t = ( ( Callable < T > ) source ) . call ( ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptySubscription . error ( ex , subscriber ) ; return true ; } if ( t == null ) { EmptySubscription . complete ( subscriber ) ; return true ; } Publisher < ? extends R > r ; try { r = ObjectHelper . requireNonNull ( mapper . apply ( t ) , \"The mapper returned a null Publisher\" ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptySubscription . error ( ex , subscriber ) ; return true ; } if ( r instanceof Callable ) { R u ; try { u = ( ( Callable < R > ) r ) . call ( ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptySubscription . error ( ex , subscriber ) ; return true ; } if ( u == null ) { EmptySubscription . complete ( subscriber ) ; return true ; } subscriber . onSubscribe ( new ScalarSubscription < R > ( subscriber , u ) ) ; } else { r . subscribe ( subscriber ) ; } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a scalar value into a Publisher and emits its values . [CODESPLIT] public static < T , U > Flowable < U > scalarXMap ( final T value , final Function < ? super T , ? extends Publisher < ? extends U > > mapper ) { return RxJavaPlugins . onAssembly ( new ScalarXMapFlowable < T , U > ( value , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Disposable by wrapping a Runnable that is executed exactly once when the Disposable is disposed . [CODESPLIT] @ NonNull public static Disposable fromRunnable ( @ NonNull Runnable run ) { ObjectHelper . requireNonNull ( run , \"run is null\" ) ; return new RunnableDisposable ( run ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Disposable by wrapping a Action that is executed exactly once when the Disposable is disposed . [CODESPLIT] @ NonNull public static Disposable fromAction ( @ NonNull Action run ) { ObjectHelper . requireNonNull ( run , \"run is null\" ) ; return new ActionDisposable ( run ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Disposable by wrapping a Future that is cancelled exactly once when the Disposable is disposed . [CODESPLIT] @ NonNull public static Disposable fromFuture ( @ NonNull Future < ? > future ) { ObjectHelper . requireNonNull ( future , \"future is null\" ) ; return fromFuture ( future , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Disposable by wrapping a Future that is cancelled exactly once when the Disposable is disposed . [CODESPLIT] @ NonNull public static Disposable fromFuture ( @ NonNull Future < ? > future , boolean allowInterrupt ) { ObjectHelper . requireNonNull ( future , \"future is null\" ) ; return new FutureDisposable ( future , allowInterrupt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Disposable by wrapping a Subscription that is cancelled exactly once when the Disposable is disposed . [CODESPLIT] @ NonNull public static Disposable fromSubscription ( @ NonNull Subscription subscription ) { ObjectHelper . requireNonNull ( subscription , \"subscription is null\" ) ; return new SubscriptionDisposable ( subscription ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Block until the first value arrives and return it otherwise return null for an empty source and rethrow any exception . [CODESPLIT] public final T blockingGet ( ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; await ( ) ; } catch ( InterruptedException ex ) { dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } } Throwable e = error ; if ( e != null ) { throw ExceptionHelper . wrapOrThrow ( e ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler initComputationScheduler ( @ NonNull Callable < Scheduler > defaultScheduler ) { ObjectHelper . requireNonNull ( defaultScheduler , \"Scheduler Callable can't be null\" ) ; Function < ? super Callable < Scheduler > , ? extends Scheduler > f = onInitComputationHandler ; if ( f == null ) { return callRequireNonNull ( defaultScheduler ) ; } return applyRequireNonNull ( f , defaultScheduler ) ; // JIT will skip this }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler initIoScheduler ( @ NonNull Callable < Scheduler > defaultScheduler ) { ObjectHelper . requireNonNull ( defaultScheduler , \"Scheduler Callable can't be null\" ) ; Function < ? super Callable < Scheduler > , ? extends Scheduler > f = onInitIoHandler ; if ( f == null ) { return callRequireNonNull ( defaultScheduler ) ; } return applyRequireNonNull ( f , defaultScheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler initNewThreadScheduler ( @ NonNull Callable < Scheduler > defaultScheduler ) { ObjectHelper . requireNonNull ( defaultScheduler , \"Scheduler Callable can't be null\" ) ; Function < ? super Callable < Scheduler > , ? extends Scheduler > f = onInitNewThreadHandler ; if ( f == null ) { return callRequireNonNull ( defaultScheduler ) ; } return applyRequireNonNull ( f , defaultScheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler initSingleScheduler ( @ NonNull Callable < Scheduler > defaultScheduler ) { ObjectHelper . requireNonNull ( defaultScheduler , \"Scheduler Callable can't be null\" ) ; Function < ? super Callable < Scheduler > , ? extends Scheduler > f = onInitSingleHandler ; if ( f == null ) { return callRequireNonNull ( defaultScheduler ) ; } return applyRequireNonNull ( f , defaultScheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler onComputationScheduler ( @ NonNull Scheduler defaultScheduler ) { Function < ? super Scheduler , ? extends Scheduler > f = onComputationHandler ; if ( f == null ) { return defaultScheduler ; } return apply ( f , defaultScheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when an undeliverable error occurs . <p > Undeliverable errors are those { @code Observer . onError () } invocations that are not allowed to happen on the given consumer type ( { @code Observer } { @code Subscriber } etc . ) due to protocol restrictions because the consumer has either disposed / cancelled its { @code Disposable } / { @code Subscription } or has already terminated with an { @code onError () } or { @code onComplete () } signal . <p > By default this global error handler prints the stacktrace via { @link Throwable#printStackTrace () } and calls { @link java . lang . Thread . UncaughtExceptionHandler#uncaughtException ( Thread Throwable ) } on the current thread . <p > Note that on some platforms the platform runtime terminates the current application with an error if such uncaught exceptions happen . In this case it is recommended the application installs a global error handler via the { @link #setErrorHandler ( Consumer ) } plugin method . [CODESPLIT] public static void onError ( @ NonNull Throwable error ) { Consumer < ? super Throwable > f = errorHandler ; if ( error == null ) { error = new NullPointerException ( \"onError called with null. Null values are generally not allowed in 2.x operators and sources.\" ) ; } else { if ( ! isBug ( error ) ) { error = new UndeliverableException ( error ) ; } } if ( f != null ) { try { f . accept ( error ) ; return ; } catch ( Throwable e ) { // Exceptions.throwIfFatal(e); TODO decide e . printStackTrace ( ) ; // NOPMD uncaught ( e ) ; } } error . printStackTrace ( ) ; // NOPMD uncaught ( error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler onIoScheduler ( @ NonNull Scheduler defaultScheduler ) { Function < ? super Scheduler , ? extends Scheduler > f = onIoHandler ; if ( f == null ) { return defaultScheduler ; } return apply ( f , defaultScheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler onNewThreadScheduler ( @ NonNull Scheduler defaultScheduler ) { Function < ? super Scheduler , ? extends Scheduler > f = onNewThreadHandler ; if ( f == null ) { return defaultScheduler ; } return apply ( f , defaultScheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when a task is scheduled . [CODESPLIT] @ NonNull public static Runnable onSchedule ( @ NonNull Runnable run ) { ObjectHelper . requireNonNull ( run , \"run is null\" ) ; Function < ? super Runnable , ? extends Runnable > f = onScheduleHandler ; if ( f == null ) { return run ; } return apply ( f , run ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Scheduler onSingleScheduler ( @ NonNull Scheduler defaultScheduler ) { Function < ? super Scheduler , ? extends Scheduler > f = onSingleHandler ; if ( f == null ) { return defaultScheduler ; } return apply ( f , defaultScheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all handlers and resets to default behavior . [CODESPLIT] public static void reset ( ) { setErrorHandler ( null ) ; setScheduleHandler ( null ) ; setComputationSchedulerHandler ( null ) ; setInitComputationSchedulerHandler ( null ) ; setIoSchedulerHandler ( null ) ; setInitIoSchedulerHandler ( null ) ; setSingleSchedulerHandler ( null ) ; setInitSingleSchedulerHandler ( null ) ; setNewThreadSchedulerHandler ( null ) ; setInitNewThreadSchedulerHandler ( null ) ; setOnFlowableAssembly ( null ) ; setOnFlowableSubscribe ( null ) ; setOnObservableAssembly ( null ) ; setOnObservableSubscribe ( null ) ; setOnSingleAssembly ( null ) ; setOnSingleSubscribe ( null ) ; setOnCompletableAssembly ( null ) ; setOnCompletableSubscribe ( null ) ; setOnConnectableFlowableAssembly ( null ) ; setOnConnectableObservableAssembly ( null ) ; setOnMaybeAssembly ( null ) ; setOnMaybeSubscribe ( null ) ; setOnParallelAssembly ( null ) ; setFailOnNonBlockingScheduler ( false ) ; setOnBeforeBlocking ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setComputationSchedulerHandler ( @ Nullable Function < ? super Scheduler , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onComputationHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setInitComputationSchedulerHandler ( @ Nullable Function < ? super Callable < Scheduler > , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onInitComputationHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setInitIoSchedulerHandler ( @ Nullable Function < ? super Callable < Scheduler > , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onInitIoHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setInitNewThreadSchedulerHandler ( @ Nullable Function < ? super Callable < Scheduler > , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onInitNewThreadHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setInitSingleSchedulerHandler ( @ Nullable Function < ? super Callable < Scheduler > , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onInitSingleHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setIoSchedulerHandler ( @ Nullable Function < ? super Scheduler , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onIoHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setNewThreadSchedulerHandler ( @ Nullable Function < ? super Scheduler , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onNewThreadHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setScheduleHandler ( @ Nullable Function < ? super Runnable , ? extends Runnable > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onScheduleHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setSingleSchedulerHandler ( @ Nullable Function < ? super Scheduler , ? extends Scheduler > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onSingleHandler = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setOnCompletableAssembly ( @ Nullable Function < ? super Completable , ? extends Completable > onCompletableAssembly ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onCompletableAssembly = onCompletableAssembly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] public static void setOnCompletableSubscribe ( @ Nullable BiFunction < ? super Completable , ? super CompletableObserver , ? extends CompletableObserver > onCompletableSubscribe ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onCompletableSubscribe = onCompletableSubscribe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnFlowableAssembly ( @ Nullable Function < ? super Flowable , ? extends Flowable > onFlowableAssembly ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onFlowableAssembly = onFlowableAssembly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnMaybeAssembly ( @ Nullable Function < ? super Maybe , ? extends Maybe > onMaybeAssembly ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onMaybeAssembly = onMaybeAssembly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnConnectableFlowableAssembly ( @ Nullable Function < ? super ConnectableFlowable , ? extends ConnectableFlowable > onConnectableFlowableAssembly ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onConnectableFlowableAssembly = onConnectableFlowableAssembly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnFlowableSubscribe ( @ Nullable BiFunction < ? super Flowable , ? super Subscriber , ? extends Subscriber > onFlowableSubscribe ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onFlowableSubscribe = onFlowableSubscribe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnMaybeSubscribe ( @ Nullable BiFunction < ? super Maybe , MaybeObserver , ? extends MaybeObserver > onMaybeSubscribe ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onMaybeSubscribe = onMaybeSubscribe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnObservableAssembly ( @ Nullable Function < ? super Observable , ? extends Observable > onObservableAssembly ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onObservableAssembly = onObservableAssembly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnConnectableObservableAssembly ( @ Nullable Function < ? super ConnectableObservable , ? extends ConnectableObservable > onConnectableObservableAssembly ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onConnectableObservableAssembly = onConnectableObservableAssembly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnObservableSubscribe ( @ Nullable BiFunction < ? super Observable , ? super Observer , ? extends Observer > onObservableSubscribe ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onObservableSubscribe = onObservableSubscribe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnSingleAssembly ( @ Nullable Function < ? super Single , ? extends Single > onSingleAssembly ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onSingleAssembly = onSingleAssembly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnSingleSubscribe ( @ Nullable BiFunction < ? super Single , ? super SingleObserver , ? extends SingleObserver > onSingleSubscribe ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } RxJavaPlugins . onSingleSubscribe = onSingleSubscribe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > Subscriber < ? super T > onSubscribe ( @ NonNull Flowable < T > source , @ NonNull Subscriber < ? super T > subscriber ) { BiFunction < ? super Flowable , ? super Subscriber , ? extends Subscriber > f = onFlowableSubscribe ; if ( f != null ) { return apply ( f , source , subscriber ) ; } return subscriber ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > Observer < ? super T > onSubscribe ( @ NonNull Observable < T > source , @ NonNull Observer < ? super T > observer ) { BiFunction < ? super Observable , ? super Observer , ? extends Observer > f = onObservableSubscribe ; if ( f != null ) { return apply ( f , source , observer ) ; } return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > SingleObserver < ? super T > onSubscribe ( @ NonNull Single < T > source , @ NonNull SingleObserver < ? super T > observer ) { BiFunction < ? super Single , ? super SingleObserver , ? extends SingleObserver > f = onSingleSubscribe ; if ( f != null ) { return apply ( f , source , observer ) ; } return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static CompletableObserver onSubscribe ( @ NonNull Completable source , @ NonNull CompletableObserver observer ) { BiFunction < ? super Completable , ? super CompletableObserver , ? extends CompletableObserver > f = onCompletableSubscribe ; if ( f != null ) { return apply ( f , source , observer ) ; } return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > MaybeObserver < ? super T > onSubscribe ( @ NonNull Maybe < T > source , @ NonNull MaybeObserver < ? super T > observer ) { BiFunction < ? super Maybe , ? super MaybeObserver , ? extends MaybeObserver > f = onMaybeSubscribe ; if ( f != null ) { return apply ( f , source , observer ) ; } return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > Maybe < T > onAssembly ( @ NonNull Maybe < T > source ) { Function < ? super Maybe , ? extends Maybe > f = onMaybeAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > Flowable < T > onAssembly ( @ NonNull Flowable < T > source ) { Function < ? super Flowable , ? extends Flowable > f = onFlowableAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > ConnectableFlowable < T > onAssembly ( @ NonNull ConnectableFlowable < T > source ) { Function < ? super ConnectableFlowable , ? extends ConnectableFlowable > f = onConnectableFlowableAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > Observable < T > onAssembly ( @ NonNull Observable < T > source ) { Function < ? super Observable , ? extends Observable > f = onObservableAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > ConnectableObservable < T > onAssembly ( @ NonNull ConnectableObservable < T > source ) { Function < ? super ConnectableObservable , ? extends ConnectableObservable > f = onConnectableObservableAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > Single < T > onAssembly ( @ NonNull Single < T > source ) { Function < ? super Single , ? extends Single > f = onSingleAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . [CODESPLIT] @ NonNull public static Completable onAssembly ( @ NonNull Completable source ) { Function < ? super Completable , ? extends Completable > f = onCompletableAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specific hook function . <p > History : 2 . 0 . 6 - experimental ; 2 . 1 - beta [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static void setOnParallelAssembly ( @ Nullable Function < ? super ParallelFlowable , ? extends ParallelFlowable > handler ) { if ( lockdown ) { throw new IllegalStateException ( \"Plugins can't be changed anymore\" ) ; } onParallelAssembly = handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the associated hook function . <p > History : 2 . 0 . 6 - experimental ; 2 . 1 - beta [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ NonNull public static < T > ParallelFlowable < T > onAssembly ( @ NonNull ParallelFlowable < T > source ) { Function < ? super ParallelFlowable , ? extends ParallelFlowable > f = onParallelAssembly ; if ( f != null ) { return apply ( f , source ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called before an operator attempts a blocking operation such as awaiting a condition or signal and should return true to indicate the operator should not block but throw an IllegalArgumentException . <p > History : 2 . 0 . 5 - experimental [CODESPLIT] public static boolean onBeforeBlocking ( ) { BooleanSupplier f = onBeforeBlocking ; if ( f != null ) { try { return f . getAsBoolean ( ) ; } catch ( Throwable ex ) { throw ExceptionHelper . wrapOrThrow ( ex ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of the default { [CODESPLIT] @ NonNull public static Scheduler createComputationScheduler ( @ NonNull ThreadFactory threadFactory ) { return new ComputationScheduler ( ObjectHelper . requireNonNull ( threadFactory , \"threadFactory is null\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the call to the function in try - catch and propagates thrown checked exceptions as RuntimeException . [CODESPLIT] @ NonNull static < T , R > R apply ( @ NonNull Function < T , R > f , @ NonNull T t ) { try { return f . apply ( t ) ; } catch ( Throwable ex ) { throw ExceptionHelper . wrapOrThrow ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the call to the function in try - catch and propagates thrown checked exceptions as RuntimeException . [CODESPLIT] @ NonNull static < T , U , R > R apply ( @ NonNull BiFunction < T , U , R > f , @ NonNull T t , @ NonNull U u ) { try { return f . apply ( t , u ) ; } catch ( Throwable ex ) { throw ExceptionHelper . wrapOrThrow ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the call to the Scheduler creation callable in try - catch and propagates thrown checked exceptions as RuntimeException and enforces that result is not null . [CODESPLIT] @ NonNull static Scheduler callRequireNonNull ( @ NonNull Callable < Scheduler > s ) { try { return ObjectHelper . requireNonNull ( s . call ( ) , \"Scheduler Callable result can't be null\" ) ; } catch ( Throwable ex ) { throw ExceptionHelper . wrapOrThrow ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the call to the Scheduler creation function in try - catch and propagates thrown checked exceptions as RuntimeException and enforces that result is not null . [CODESPLIT] @ NonNull static Scheduler applyRequireNonNull ( @ NonNull Function < ? super Callable < Scheduler > , ? extends Scheduler > f , Callable < Scheduler > s ) { return ObjectHelper . requireNonNull ( apply ( f , s ) , \"Scheduler Callable result can't be null\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs multiple MaybeSources and signals the events of the first one that signals ( disposing the rest ) . <p > <img width = 640 height = 519 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . amb . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > amb ( final Iterable < ? extends MaybeSource < ? extends T > > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeAmb < T > ( null , sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs multiple MaybeSources and signals the events of the first one that signals ( disposing the rest ) . <p > <img width = 640 height = 519 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . ambArray . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Maybe < T > ambArray ( final MaybeSource < ? extends T > ... sources ) { if ( sources . length == 0 ) { return empty ( ) ; } if ( sources . length == 1 ) { return wrap ( ( MaybeSource < T > ) sources [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new MaybeAmb < T > ( sources , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenate the single values in a non - overlapping fashion of the MaybeSource sources provided by a Publisher sequence . <p > <img width = 640 height = 416 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . concat . p . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concat ( Publisher < ? extends MaybeSource < ? extends T > > sources ) { return concat ( sources , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a variable number of MaybeSource sources and delays errors from any of them till all terminate . <p > <img width = 640 height = 425 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . concatArrayDelayError . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concatArrayDelayError ( MaybeSource < ? extends T > ... sources ) { if ( sources . length == 0 ) { return Flowable . empty ( ) ; } else if ( sources . length == 1 ) { return RxJavaPlugins . onAssembly ( new MaybeToFlowable < T > ( ( MaybeSource < T > ) sources [ 0 ] ) ) ; } return RxJavaPlugins . onAssembly ( new MaybeConcatArrayDelayError < T > ( sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a sequence of MaybeSource eagerly into a single stream of values . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source MaybeSources . The operator buffers the value emitted by these MaybeSources and then drains them in order each one after the previous one completes . <p > <img width = 640 height = 489 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . concatArrayEager . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concatArrayEager ( MaybeSource < ? extends T > ... sources ) { return Flowable . fromArray ( sources ) . concatMapEager ( ( Function ) MaybeToPublisher . instance ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a sequence of MaybeSources eagerly into a single stream of values . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source MaybeSources . The operator buffers the values emitted by these MaybeSources and then drains them in order each one after the previous one completes . <p > <img width = 640 height = 526 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . concatEager . i . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > Backpressure is honored towards the downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concatEager ( Iterable < ? extends MaybeSource < ? extends T > > sources ) { return Flowable . fromIterable ( sources ) . concatMapEager ( ( Function ) MaybeToPublisher . instance ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an API ( via a cold Maybe ) that bridges the reactive world with the callback - style world . <p > Example : <pre > <code > Maybe . &lt ; Event&gt ; create ( emitter - &gt ; { Callback listener = new Callback () { &#64 ; Override public void onEvent ( Event e ) { if ( e . isNothing () ) { emitter . onComplete () ; } else { emitter . onSuccess ( e ) ; } } [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > create ( MaybeOnSubscribe < T > onSubscribe ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeCreate < T > ( onSubscribe ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a Callable for each individual MaybeObserver to return the actual MaybeSource source to be subscribed to . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > defer ( final Callable < ? extends MaybeSource < ? extends T > > maybeSupplier ) { ObjectHelper . requireNonNull ( maybeSupplier , \"maybeSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeDefer < T > ( maybeSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a ( singleton ) Maybe instance that calls { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Maybe < T > empty ( ) { return RxJavaPlugins . onAssembly ( ( Maybe < T > ) MaybeEmpty . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that invokes a subscriber s { @link MaybeObserver#onError onError } method when the subscriber subscribes to it . <p > <img width = 640 height = 447 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . error . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code error } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > error ( Throwable exception ) { ObjectHelper . requireNonNull ( exception , \"exception is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeError < T > ( exception ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that invokes a { @link MaybeObserver } s { @link MaybeObserver#onError onError } method when the MaybeObserver subscribes to it . <p > <img width = 640 height = 190 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / error . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code error } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > error ( Callable < ? extends Throwable > supplier ) { ObjectHelper . requireNonNull ( supplier , \"errorSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeErrorCallable < T > ( supplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps a CompletableSource into a Maybe . [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > fromCompletable ( CompletableSource completableSource ) { ObjectHelper . requireNonNull ( completableSource , \"completableSource is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFromCompletable < T > ( completableSource ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps a SingleSource into a Maybe . [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > fromSingle ( SingleSource < T > singleSource ) { ObjectHelper . requireNonNull ( singleSource , \"singleSource is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFromSingle < T > ( singleSource ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Maybe } that invokes the given { @link Callable } for each individual { @link MaybeObserver } that subscribes and emits the resulting non - null item via { @code onSuccess } while considering a { @code null } result from the { @code Callable } as indication for valueless completion via { @code onComplete } . <p > This operator allows you to defer the execution of the given { @code Callable } until a { @code MaybeObserver } subscribes to the returned { @link Maybe } . In other terms this source operator evaluates the given { @code Callable } lazily . <p > Note that the { @code null } handling of this operator differs from the similar source operators in the other { @link io . reactivex base reactive classes } . Those operators signal a { @code NullPointerException } if the value returned by their { @code Callable } is { @code null } while this { @code fromCallable } considers it to indicate the returned { @code Maybe } is empty . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromCallable } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > Any non - fatal exception thrown by { @link Callable#call () } will be forwarded to { @code onError } except if the { @code MaybeObserver } disposed the subscription in the meantime . In this latter case the exception is forwarded to the global error handler via { @link io . reactivex . plugins . RxJavaPlugins#onError ( Throwable ) } wrapped into a { @link io . reactivex . exceptions . UndeliverableException UndeliverableException } . Fatal exceptions are rethrown and usually will end up in the executing thread s { @link java . lang . Thread . UncaughtExceptionHandler#uncaughtException ( Thread Throwable ) } handler . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > fromCallable ( @ NonNull final Callable < ? extends T > callable ) { ObjectHelper . requireNonNull ( callable , \"callable is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFromCallable < T > ( callable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link Future } into a Maybe treating a null result as an indication of emptiness . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / from . Future . png alt = > <p > You can convert any object that supports the { @link Future } interface into a Maybe that emits the return value of the { @link Future#get } method of that object by passing the object into the { @code from } method . <p > <em > Important note : < / em > This Maybe is blocking ; you cannot dispose it . <p > Unlike 1 . x disposing the Maybe won t cancel the future . If necessary one can use composition to achieve the cancellation effect : { @code futureMaybe . doOnDispose (( ) - > future . cancel ( true )) ; } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromFuture } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > fromFuture ( Future < ? extends T > future ) { ObjectHelper . requireNonNull ( future , \"future is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFromFuture < T > ( future , 0L , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link Future } into a Maybe with a timeout on the Future . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / from . Future . png alt = > <p > You can convert any object that supports the { @link Future } interface into a Maybe that emits the return value of the { @link Future#get } method of that object by passing the object into the { @code fromFuture } method . <p > Unlike 1 . x disposing the Maybe won t cancel the future . If necessary one can use composition to achieve the cancellation effect : { @code futureMaybe . doOnCancel (( ) - > future . cancel ( true )) ; } . <p > <em > Important note : < / em > This Maybe is blocking on the thread it gets subscribed on ; you cannot dispose it . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromFuture } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > fromFuture ( Future < ? extends T > future , long timeout , TimeUnit unit ) { ObjectHelper . requireNonNull ( future , \"future is null\" ) ; ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFromFuture < T > ( future , timeout , unit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe instance that runs the given Action for each subscriber and emits either its exception or simply completes . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > fromRunnable ( final Runnable run ) { ObjectHelper . requireNonNull ( run , \"run is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFromRunnable < T > ( run ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Maybe } that emits a specified item . <p > <img width = 640 height = 485 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . just . png alt = > <p > To convert any object into a { @code Maybe } that emits that object pass that object into the { @code just } method . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code just } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > just ( T item ) { ObjectHelper . requireNonNull ( item , \"item is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeJust < T > ( item ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges a Flowable sequence of MaybeSource instances into a single Flowable sequence running all MaybeSources at once . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > merge ( Publisher < ? extends MaybeSource < ? extends T > > sources ) { return merge ( sources , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an array of MaybeSources into one Flowable in a way that allows a Subscriber to receive all successfully emitted items from each of the source MaybeSources without being interrupted by an error notification from one of them . <p > This behaves like { @link #merge ( Publisher ) } except that if any of the merged MaybeSources notify of an error via { @link Subscriber#onError onError } { @code mergeDelayError } will refrain from propagating that error notification until all of the merged MaybeSources have finished emitting items . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeDelayError . png alt = > <p > Even if multiple merged MaybeSources send { @code onError } notifications { @code mergeDelayError } will only invoke the { @code onError } method of its Subscribers once . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeArrayDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > mergeArrayDelayError ( MaybeSource < ? extends T > ... sources ) { if ( sources . length == 0 ) { return Flowable . empty ( ) ; } return Flowable . fromArray ( sources ) . flatMap ( ( Function ) MaybeToPublisher . instance ( ) , true , sources . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an Iterable of MaybeSources into one Flowable in a way that allows a Subscriber to receive all successfully emitted items from each of the source MaybeSources without being interrupted by an error notification from one of them . <p > This behaves like { @link #merge ( Publisher ) } except that if any of the merged MaybeSources notify of an error via { @link Subscriber#onError onError } { @code mergeDelayError } will refrain from propagating that error notification until all of the merged MaybeSources have finished emitting items . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeDelayError . png alt = > <p > Even if multiple merged MaybeSources send { @code onError } notifications { @code mergeDelayError } will only invoke the { @code onError } method of its Subscribers once . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > mergeDelayError ( Iterable < ? extends MaybeSource < ? extends T > > sources ) { return Flowable . fromIterable ( sources ) . flatMap ( ( Function ) MaybeToPublisher . instance ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that never sends any items or notifications to a { @link MaybeObserver } . <p > <img width = 640 height = 185 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / never . png alt = > <p > This Maybe is useful primarily for testing purposes . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code never } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Maybe < T > never ( ) { return RxJavaPlugins . onAssembly ( ( Maybe < T > ) MaybeNever . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two MaybeSource sequences are the same by comparing the items emitted by each MaybeSource pairwise . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( MaybeSource < ? extends T > source1 , MaybeSource < ? extends T > source2 ) { return sequenceEqual ( source1 , source2 , ObjectHelper . equalsPredicate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two MaybeSources are the same by comparing the items emitted by each MaybeSource pairwise based on the results of a specified equality function . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( MaybeSource < ? extends T > source1 , MaybeSource < ? extends T > source2 , BiPredicate < ? super T , ? super T > isEqual ) { ObjectHelper . requireNonNull ( source1 , \"source1 is null\" ) ; ObjectHelper . requireNonNull ( source2 , \"source2 is null\" ) ; ObjectHelper . requireNonNull ( isEqual , \"isEqual is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeEqualSingle < T > ( source1 , source2 , isEqual ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits { @code 0L } after a specified delay . <p > <img width = 640 height = 200 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timer . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code timer } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public static Maybe < Long > timer ( long delay , TimeUnit unit ) { return timer ( delay , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits { @code 0L } after a specified delay on a specified Scheduler . <p > <img width = 640 height = 200 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timer . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Maybe < Long > timer ( long delay , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeTimer ( Math . max ( 0L , delay ) , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<strong > Advanced use only : < / strong > creates a Maybe instance without any safeguards by using a callback that is called with a MaybeObserver . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > unsafeCreate ( MaybeSource < T > onSubscribe ) { if ( onSubscribe instanceof Maybe ) { throw new IllegalArgumentException ( \"unsafeCreate(Maybe) should be upgraded\" ) ; } ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeUnsafeCreate < T > ( onSubscribe ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a Maybe that creates a dependent resource object which is disposed of when the upstream terminates or the downstream calls dispose () . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / using . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code using } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , D > Maybe < T > using ( Callable < ? extends D > resourceSupplier , Function < ? super D , ? extends MaybeSource < ? extends T > > sourceSupplier , Consumer < ? super D > resourceDisposer ) { return using ( resourceSupplier , sourceSupplier , resourceDisposer , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a Maybe that creates a dependent resource object which is disposed of just before termination if you have set { @code disposeEagerly } to { @code true } and a downstream dispose () does not occur before termination . Otherwise resource disposal will occur on call to dispose () . Eager disposal is particularly appropriate for a synchronous Maybe that reuses resources . { @code disposeAction } will only be called once per subscription . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / using . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code using } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , D > Maybe < T > using ( Callable < ? extends D > resourceSupplier , Function < ? super D , ? extends MaybeSource < ? extends T > > sourceSupplier , Consumer < ? super D > resourceDisposer , boolean eager ) { ObjectHelper . requireNonNull ( resourceSupplier , \"resourceSupplier is null\" ) ; ObjectHelper . requireNonNull ( sourceSupplier , \"sourceSupplier is null\" ) ; ObjectHelper . requireNonNull ( resourceDisposer , \"disposer is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeUsing < T , D > ( resourceSupplier , sourceSupplier , resourceDisposer , eager ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps a MaybeSource instance into a new Maybe instance if not already a Maybe instance . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Maybe < T > wrap ( MaybeSource < T > source ) { if ( source instanceof Maybe ) { return RxJavaPlugins . onAssembly ( ( Maybe < T > ) source ) ; } ObjectHelper . requireNonNull ( source , \"onSubscribe is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeUnsafeCreate < T > ( source ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the results of a specified combiner function applied to combinations of items emitted in sequence by an Iterable of other MaybeSources . <p > Note on method signature : since Java doesn t allow creating a generic array with { @code new T [] } the implementation of this operator has to create an { @code Object [] } instead . Unfortunately a { @code Function<Integer [] R > } passed to the method would trigger a { @code ClassCastException } . [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , R > Maybe < R > zip ( Iterable < ? extends MaybeSource < ? extends T > > sources , Function < ? super Object [ ] , ? extends R > zipper ) { ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeZipIterable < T , R > ( sources , zipper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the results of a specified combiner function applied to combinations of items emitted in sequence by an array of other MaybeSources . <p > Note on method signature : since Java doesn t allow creating a generic array with { @code new T [] } the implementation of this operator has to create an { @code Object [] } instead . Unfortunately a { @code Function<Integer [] R > } passed to the method would trigger a { @code ClassCastException } . [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , R > Maybe < R > zipArray ( Function < ? super Object [ ] , ? extends R > zipper , MaybeSource < ? extends T > ... sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; if ( sources . length == 0 ) { return empty ( ) ; } ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeZipArray < T , R > ( sources , zipper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mirrors the MaybeSource ( current or provided ) that first signals an event . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / amb . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code ambWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > ambWith ( MaybeSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return ambArray ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits in a blocking fashion until the current Maybe signals a success value ( which is returned ) null if completed or an exception ( which is propagated ) . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingGet ( ) { BlockingMultiObserver < T > observer = new BlockingMultiObserver < T > ( ) ; subscribe ( observer ) ; return observer . blockingGet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits in a blocking fashion until the current Maybe signals a success value ( which is returned ) defaultValue if completed or an exception ( which is propagated ) . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingGet ( T defaultValue ) { ObjectHelper . requireNonNull ( defaultValue , \"defaultValue is null\" ) ; BlockingMultiObserver < T > observer = new BlockingMultiObserver < T > ( ) ; subscribe ( observer ) ; return observer . blockingGet ( defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that subscribes to this Maybe lazily caches its event and replays it to all the downstream subscribers . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / cache . png alt = > <p > The operator subscribes only when the first downstream subscriber subscribes and maintains a single subscription towards this Maybe . <p > <em > Note : < / em > You sacrifice the ability to dispose the origin when you use the { @code cache } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code cache } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > cache ( ) { return RxJavaPlugins . onAssembly ( new MaybeCache < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a Maybe by applying a particular Transformer function to it . <p > This method operates on the Maybe itself whereas { @link #lift } operates on the Maybe s MaybeObservers . <p > If the operator you are creating is designed to act on the individual item emitted by a Maybe use { @link #lift } . If your operator is designed to transform the source Maybe as a whole ( for instance by applying a particular set of existing RxJava operators to it ) use { @code compose } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code compose } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Maybe < R > compose ( MaybeTransformer < ? super T , ? extends R > transformer ) { return wrap ( ( ( MaybeTransformer < T , R > ) ObjectHelper . requireNonNull ( transformer , \"transformer is null\" ) ) . apply ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that is based on applying a specified function to the item emitted by the source Maybe where that function returns a MaybeSource . <p > <img width = 640 height = 356 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . flatMap . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Maybe < R > concatMap ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFlatten < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items emitted from the current MaybeSource then the next one after the other without interleaving them . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concat . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > concatWith ( MaybeSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return concat ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean that indicates whether the source Maybe emitted a specified item . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / contains . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code contains } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > contains ( final Object item ) { ObjectHelper . requireNonNull ( item , \"item is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeContains < T > ( this , item ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that counts the total number of items emitted ( 0 or 1 ) by the source Maybe and emits this count as a 64 - bit Long . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / longCount . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code count } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Long > count ( ) { return RxJavaPlugins . onAssembly ( new MaybeCount < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that signals the events emitted by the source Maybe shifted forward in time by a specified delay . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code delay } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Maybe < T > delay ( long delay , TimeUnit unit ) { return delay ( delay , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that signals the events emitted by the source Maybe shifted forward in time by a specified delay running on the specified Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > you specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Maybe < T > delay ( long delay , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeDelay < T > ( this , Math . max ( 0L , delay ) , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that delays the subscription to this Maybe until the other Publisher emits an element or completes normally . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The { @code Publisher } source is consumed in an unbounded fashion ( without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Maybe < T > delaySubscription ( Publisher < U > subscriptionIndicator ) { ObjectHelper . requireNonNull ( subscriptionIndicator , \"subscriptionIndicator is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeDelaySubscriptionOtherPublisher < T , U > ( this , subscriptionIndicator ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that delays the subscription to the source Maybe by a given amount of time both waiting and subscribing on a given Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delaySubscription . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Maybe < T > delaySubscription ( long delay , TimeUnit unit , Scheduler scheduler ) { return delaySubscription ( Flowable . timer ( delay , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the shared consumer with the error sent via onError for each MaybeObserver that subscribes to the current Maybe . <p > <img width = 640 height = 358 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnError . m . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > doOnError ( Consumer < ? super Throwable > onError ) { return RxJavaPlugins . onAssembly ( new MaybePeek < T > ( this , Functions . emptyConsumer ( ) , // onSubscribe Functions . emptyConsumer ( ) , // onSuccess ObjectHelper . requireNonNull ( onError , \"onError is null\" ) , Functions . EMPTY_ACTION , // onComplete Functions . EMPTY_ACTION , // (onSuccess | onError | onComplete) Functions . EMPTY_ACTION // dispose ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the given onEvent callback with the ( success value null ) for an onSuccess ( null throwable ) for an onError or ( null null ) for an onComplete signal from this Maybe before delivering said signal to the downstream . <p > Exceptions thrown from the callback will override the event so the downstream receives the error instead of the original signal . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > doOnEvent ( BiConsumer < ? super T , ? super Throwable > onEvent ) { ObjectHelper . requireNonNull ( onEvent , \"onEvent is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeDoOnEvent < T > ( this , onEvent ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe instance that calls the given onTerminate callback just before this Maybe completes normally or with an exception . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnTerminate . png alt = > <p > This differs from { [CODESPLIT] @ Experimental @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > doOnTerminate ( final Action onTerminate ) { ObjectHelper . requireNonNull ( onTerminate , \"onTerminate is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeDoOnTerminate < T > ( this , onTerminate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the results of a specified function to the pair of values emitted by the source Maybe and a specified mapped MaybeSource . <p > <img width = 640 height = 390 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeMap . r . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Maybe < R > flatMap ( Function < ? super T , ? extends MaybeSource < ? extends U > > mapper , BiFunction < ? super T , ? super U , ? extends R > resultSelector ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . requireNonNull ( resultSelector , \"resultSelector is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFlatMapBiSelector < T , U , R > ( this , mapper , resultSelector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the success value of the upstream { @link Maybe } into an { @link Iterable } and emits its items as a { @link Flowable } sequence . <p > <img width = 640 height = 373 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flattenAsFlowable . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flattenAsFlowable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Flowable < U > flattenAsFlowable ( final Function < ? super T , ? extends Iterable < ? extends U > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeFlatMapIterableFlowable < T , U > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides the identity of this Maybe and its Disposable . <p > <img width = 640 height = 300 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . hide . png alt = > <p > Allows preventing certain identity - based optimizations ( fusion ) . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > hide ( ) { return RxJavaPlugins . onAssembly ( new MaybeHide < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ignores the item emitted by the source Maybe and only calls { @code onComplete } or { @code onError } . <p > <img width = 640 height = 389 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . ignoreElement . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code ignoreElement } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable ignoreElement ( ) { return RxJavaPlugins . onAssembly ( new MaybeIgnoreElementCompletable < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits { @code true } if the source Maybe is empty otherwise { @code false } . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / isEmpty . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code isEmpty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > isEmpty ( ) { return RxJavaPlugins . onAssembly ( new MaybeIsEmptySingle < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<strong > This method requires advanced knowledge about building operators please consider other standard composition methods first ; < / strong > Returns a { @code Maybe } which when subscribed to invokes the { @link MaybeOperator#apply ( MaybeObserver ) apply ( MaybeObserver ) } method of the provided { @link MaybeOperator } for each individual downstream { @link Maybe } and allows the insertion of a custom operator by accessing the downstream s { @link MaybeObserver } during this subscription phase and providing a new { @code MaybeObserver } containing the custom operator s intended business logic that will be used in the subscription process going further upstream . <p > Generally such a new { @code MaybeObserver } will wrap the downstream s { @code MaybeObserver } and forwards the { @code onSuccess } { @code onError } and { @code onComplete } events from the upstream directly or according to the emission pattern the custom operator s business logic requires . In addition such operator can intercept the flow control calls of { @code dispose } and { @code isDisposed } that would have traveled upstream and perform additional actions depending on the same business logic requirements . <p > Example : <pre > <code > // Step 1 : Create the consumer type that will be returned by the MaybeOperator . apply () : [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Maybe < R > lift ( final MaybeOperator < ? extends R , ? super T > lift ) { ObjectHelper . requireNonNull ( lift , \"lift is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeLift < T , R > ( this , lift ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that applies a specified function to the item emitted by the source Maybe and emits the result of this function application . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Maybe . map . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code map } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Maybe < R > map ( Function < ? super T , ? extends R > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeMap < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters the items emitted by a Maybe only emitting its success value if that is an instance of the supplied Class . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / ofClass . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code ofType } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Maybe < U > ofType ( final Class < U > clazz ) { ObjectHelper . requireNonNull ( clazz , \"clazz is null\" ) ; return filter ( Functions . isInstanceOf ( clazz ) ) . cast ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified converter function with the current Maybe instance during assembly time and returns its result . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code to } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > @param <R > the result type @param convert the function that is called with the current Maybe instance during assembly time that should return some value to be the result [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > R to ( Function < ? super Maybe < T > , R > convert ) { try { return ObjectHelper . requireNonNull ( convert , \"convert is null\" ) . apply ( this ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts this Maybe into an Observable instance composing disposal through . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > toObservable ( ) { if ( this instanceof FuseToObservable ) { return ( ( FuseToObservable < T > ) this ) . fuseToObservable ( ) ; } return RxJavaPlugins . onAssembly ( new MaybeToObservable < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts this Maybe into a Single instance composing disposal through and turning an empty Maybe into a signal of NoSuchElementException . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > toSingle ( ) { return RxJavaPlugins . onAssembly ( new MaybeToSingle < T > ( this , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe instance that if this Maybe emits an error it will emit an onComplete and swallow the throwable . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > onErrorComplete ( ) { return onErrorComplete ( Functions . alwaysTrue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Maybe to pass control to another { @link MaybeSource } rather than invoking { @link MaybeObserver#onError onError } if it encounters an error . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onErrorResumeNext . png alt = > <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorResumeNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > onErrorResumeNext ( final MaybeSource < ? extends T > next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return onErrorResumeNext ( Functions . justFunction ( next ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Maybe to pass control to another Maybe rather than invoking { @link MaybeObserver#onError onError } if it encounters an error . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onErrorResumeNext . png alt = > <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorResumeNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > onErrorResumeNext ( Function < ? super Throwable , ? extends MaybeSource < ? extends T > > resumeFunction ) { ObjectHelper . requireNonNull ( resumeFunction , \"resumeFunction is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeOnErrorNext < T > ( this , resumeFunction , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Maybe to emit an item ( returned by a specified function ) rather than invoking { @link MaybeObserver#onError onError } if it encounters an error . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onErrorReturn . png alt = > <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorReturn } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > onErrorReturn ( Function < ? super Throwable , ? extends T > valueSupplier ) { ObjectHelper . requireNonNull ( valueSupplier , \"valueSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeOnErrorReturn < T > ( this , valueSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Nulls out references to the upstream producer and downstream MaybeObserver if the sequence is terminated or downstream calls dispose () . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > onTerminateDetach ( ) { return RxJavaPlugins . onAssembly ( new MaybeDetach < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that repeats the sequence of items emitted by the source Maybe until the provided stop function returns true . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeat . on . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator honors downstream backpressure . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeatUntil } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > repeatUntil ( BooleanSupplier stop ) { return toFlowable ( ) . repeatUntil ( stop ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the same values as the source Publisher with the exception of an { @code onComplete } . An { @code onComplete } notification from the source will result in the emission of a { @code void } item to the Publisher provided as an argument to the { @code notificationHandler } function . If that Publisher calls { @code onComplete } or { @code onError } then { @code repeatWhen } will call { @code onComplete } or { @code onError } on the child subscription . Otherwise this Publisher will resubscribe to the source Publisher . <p > <img width = 640 height = 430 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeatWhen . f . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator <em > may< / em > throw an { @code IllegalStateException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeatWhen } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > repeatWhen ( final Function < ? super Flowable < Object > , ? extends Publisher < ? > > handler ) { return toFlowable ( ) . repeatWhen ( handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that mirrors the source Maybe resubscribing to it if it calls { @code onError } and the predicate returns true for that specific exception and retry count . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > retry ( BiPredicate < ? super Integer , ? super Throwable > predicate ) { return toFlowable ( ) . retry ( predicate ) . singleElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that mirrors the source Maybe resubscribing to it if it calls { @code onError } up to a specified number of retries . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . png alt = > <p > If the source Maybe calls { @link MaybeObserver#onError } this method will resubscribe to the source Maybe for a maximum of { @code count } resubscriptions rather than propagating the { @code onError } call . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > retry ( long count ) { return retry ( count , Functions . alwaysTrue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retries at most times or until the predicate returns false whichever happens first . [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > retry ( long times , Predicate < ? super Throwable > predicate ) { return toFlowable ( ) . retry ( times , predicate ) . singleElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the same values as the source Maybe with the exception of an { @code onError } . An { @code onError } notification from the source will result in the emission of a { @link Throwable } item to the Publisher provided as an argument to the { @code notificationHandler } function . If that Publisher calls { @code onComplete } or { @code onError } then { @code retry } will call { @code onComplete } or { @code onError } on the child subscription . Otherwise this Publisher will resubscribe to the source Publisher . <p > <img width = 640 height = 430 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retryWhen . f . png alt = > <p > Example : [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > retryWhen ( final Function < ? super Flowable < Throwable > , ? extends Publisher < ? > > handler ) { return toFlowable ( ) . retryWhen ( handler ) . singleElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to a Maybe and ignores { @code onSuccess } and { @code onComplete } emissions . <p > If the Maybe emits an error it is wrapped into an { @link io . reactivex . exceptions . OnErrorNotImplementedException OnErrorNotImplementedException } and routed to the RxJavaPlugins . onError handler . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( ) { return subscribe ( Functions . emptyConsumer ( ) , Functions . ON_ERROR_MISSING , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to a Maybe and provides callbacks to handle the items it emits and any error notification it issues . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( Consumer < ? super T > onSuccess , Consumer < ? super Throwable > onError ) { return subscribe ( onSuccess , onError , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the items emitted by the source Maybe or the items of an alternate MaybeSource if the current Maybe is empty . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchifempty . m . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchIfEmpty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > switchIfEmpty ( MaybeSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeSwitchIfEmpty < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the items emitted by the source Maybe or the item of an alternate SingleSource if the current Maybe is empty . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchifempty . m . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > switchIfEmpty ( SingleSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeSwitchIfEmptySingle < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the items emitted by the source Maybe until a second MaybeSource emits an item . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeUntil . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code takeUntil } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Maybe < T > takeUntil ( MaybeSource < U > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeTakeUntilMaybe < T , U > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that mirrors the source Maybe but applies a timeout policy for each emitted item . If the next item isn t emitted within the specified timeout duration starting from its predecessor the resulting Maybe terminates and notifies MaybeObservers of a { @code TimeoutException } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 1 . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code timeout } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Maybe < T > timeout ( long timeout , TimeUnit timeUnit ) { return timeout ( timeout , timeUnit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that mirrors the source Maybe but applies a timeout policy for each emitted item where this policy is governed on a specified Scheduler . If the next item isn t emitted within the specified timeout duration starting from its predecessor the resulting Maybe terminates and notifies MaybeObservers of a { @code TimeoutException } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 1s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Maybe < T > timeout ( long timeout , TimeUnit timeUnit , Scheduler scheduler ) { return timeout ( timer ( timeout , timeUnit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the current { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Maybe < T > timeout ( MaybeSource < U > timeoutIndicator ) { ObjectHelper . requireNonNull ( timeoutIndicator , \"timeoutIndicator is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeTimeoutMaybe < T , U > ( this , timeoutIndicator , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the current { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Maybe < T > timeout ( Publisher < U > timeoutIndicator ) { ObjectHelper . requireNonNull ( timeoutIndicator , \"timeoutIndicator is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeTimeoutPublisher < T , U > ( this , timeoutIndicator , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe which makes sure when a MaybeObserver disposes the Disposable that call is propagated up on the specified scheduler . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Maybe < T > unsubscribeOn ( final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeUnsubscribeOn < T > ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a OperatorPublish instance to publish values of the given source observable . [CODESPLIT] public static < T > ConnectableFlowable < T > create ( Flowable < T > source , final int bufferSize ) { // the current connection to source needs to be shared between the operator and its onSubscribe call final AtomicReference < PublishSubscriber < T > > curr = new AtomicReference < PublishSubscriber < T > > ( ) ; Publisher < T > onSubscribe = new FlowablePublisher < T > ( curr , bufferSize ) ; return RxJavaPlugins . onAssembly ( new FlowablePublish < T > ( onSubscribe , source , curr , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] public static < T > SingleObserver < T > create ( Observer < ? super T > downstream ) { return new SingleToObservableObserver < T > ( downstream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if the object is not null and returns it or throws a NullPointerException with the given message . [CODESPLIT] public static < T > T requireNonNull ( T object , String message ) { if ( object == null ) { throw new NullPointerException ( message ) ; } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a BiPredicate that compares its parameters via Objects . equals () . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > BiPredicate < T , T > equalsPredicate ( ) { return ( BiPredicate < T , T > ) EQUALS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emits the given exception if possible or adds it to the given error container to be emitted by a concurrent onNext if one is running . Undeliverable exceptions are sent to the RxJavaPlugins . onError . [CODESPLIT] public static void onError ( Subscriber < ? > subscriber , Throwable ex , AtomicInteger wip , AtomicThrowable error ) { if ( error . addThrowable ( ex ) ) { if ( wip . getAndIncrement ( ) == 0 ) { subscriber . onError ( error . terminate ( ) ) ; } } else { RxJavaPlugins . onError ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emits an onComplete signal or an onError signal with the given error or indicates the concurrently running onNext should do that . [CODESPLIT] public static void onComplete ( Subscriber < ? > subscriber , AtomicInteger wip , AtomicThrowable error ) { if ( wip . getAndIncrement ( ) == 0 ) { Throwable ex = error . terminate ( ) ; if ( ex != null ) { subscriber . onError ( ex ) ; } else { subscriber . onComplete ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emits the given exception if possible or adds it to the given error container to be emitted by a concurrent onNext if one is running . Undeliverable exceptions are sent to the RxJavaPlugins . onError . [CODESPLIT] public static void onError ( Observer < ? > observer , Throwable ex , AtomicInteger wip , AtomicThrowable error ) { if ( error . addThrowable ( ex ) ) { if ( wip . getAndIncrement ( ) == 0 ) { observer . onError ( error . terminate ( ) ) ; } } else { RxJavaPlugins . onError ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emits an onComplete signal or an onError signal with the given error or indicates the concurrently running onNext should do that . [CODESPLIT] public static void onComplete ( Observer < ? > observer , AtomicInteger wip , AtomicThrowable error ) { if ( wip . getAndIncrement ( ) == 0 ) { Throwable ex = error . terminate ( ) ; if ( ex != null ) { observer . onError ( ex ) ; } else { observer . onComplete ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an identity function that simply returns its argument . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > Function < T , T > identity ( ) { return ( Function < T , T > ) IDENTITY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Callable that returns the given value . [CODESPLIT] public static < T > Callable < T > justCallable ( T value ) { return new JustValue < Object , T > ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Function that ignores its parameter and returns the given value . [CODESPLIT] public static < T , U > Function < T , U > justFunction ( U value ) { return new JustValue < T , U > ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a function that cast the incoming values via a Class object . [CODESPLIT] public static < T , U > Function < T , U > castFunction ( Class < U > target ) { return new CastToClass < T , U > ( target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special handling for printing out a { @code CompositeException } . Loops through all inner exceptions and prints them out . [CODESPLIT] private void printStackTrace ( PrintStreamOrWriter s ) { StringBuilder b = new StringBuilder ( 128 ) ; b . append ( this ) . append ( ' ' ) ; for ( StackTraceElement myStackElement : getStackTrace ( ) ) { b . append ( \"\\tat \" ) . append ( myStackElement ) . append ( ' ' ) ; } int i = 1 ; for ( Throwable ex : exceptions ) { b . append ( \"  ComposedException \" ) . append ( i ) . append ( \" :\\n\" ) ; appendStackTrace ( b , ex , \"\\t\" ) ; i ++ ; } s . println ( b . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private [CODESPLIT] Throwable getRootCause ( Throwable e ) { Throwable root = e . getCause ( ) ; if ( root == null || e == root ) { return e ; } while ( true ) { Throwable cause = root . getCause ( ) ; if ( cause == null || cause == root ) { return root ; } root = cause ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an UnicastSubject with an internal buffer capacity hint 16 . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( ) { return new UnicastSubject < T > ( bufferSize ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an UnicastSubject with the given internal buffer capacity hint . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( int capacityHint ) { return new UnicastSubject < T > ( capacityHint , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an UnicastSubject with the given internal buffer capacity hint and a callback for the case when the single Subscriber cancels its subscription . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( int capacityHint , Runnable onTerminate ) { return new UnicastSubject < T > ( capacityHint , onTerminate , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an UnicastSubject with an internal buffer capacity hint 16 and given delay error flag . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( boolean delayError ) { return new UnicastSubject < T > ( bufferSize ( ) , delayError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to emit the item to all currently subscribed Subscribers if all of them has requested some value returns false otherwise . <p > This method should be called in a sequential manner just like the onXXX methods of the PublishProcessor . <p > Calling with null will terminate the PublishProcessor and a NullPointerException is signalled to the Subscribers . <p > History : 2 . 0 . 8 - experimental [CODESPLIT] public boolean offer ( T t ) { if ( t == null ) { onError ( new NullPointerException ( \"onNext called with null. Null values are generally not allowed in 2.x operators and sources.\" ) ) ; return true ; } PublishSubscription < T > [ ] array = subscribers . get ( ) ; for ( PublishSubscription < T > s : array ) { if ( s . isFull ( ) ) { return false ; } } for ( PublishSubscription < T > s : array ) { s . onNext ( t ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "final : fixed protocol steps to support fuseable and non - fuseable upstream [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public final void onSubscribe ( Disposable d ) { if ( DisposableHelper . validate ( this . upstream , d ) ) { this . upstream = d ; if ( d instanceof QueueDisposable ) { this . qd = ( QueueDisposable < T > ) d ; } if ( beforeDownstream ( ) ) { downstream . onSubscribe ( this ) ; afterDownstream ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------- [CODESPLIT] @ Override public void onError ( Throwable t ) { if ( done ) { RxJavaPlugins . onError ( t ) ; return ; } done = true ; downstream . onError ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rethrows the throwable if it is a fatal exception or calls { [CODESPLIT] protected final void fail ( Throwable t ) { Exceptions . throwIfFatal ( t ) ; upstream . dispose ( ) ; onError ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the upstream s QueueDisposable . requestFusion with the mode and saves the established mode in { [CODESPLIT] protected final int transitiveBoundaryFusion ( int mode ) { QueueDisposable < T > qd = this . qd ; if ( qd != null ) { if ( ( mode & BOUNDARY ) == 0 ) { int m = qd . requestFusion ( mode ) ; if ( m != NONE ) { sourceMode = m ; } return m ; } } return NONE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Block until the latch is counted down and return the error received or null if no error happened . [CODESPLIT] public Throwable blockingGetError ( ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; await ( ) ; } catch ( InterruptedException ex ) { dispose ( ) ; return ex ; } } return error ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Block until the latch is counted down and return the error received or when the wait is interrupted or times out null otherwise . [CODESPLIT] public Throwable blockingGetError ( long timeout , TimeUnit unit ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; if ( ! await ( timeout , unit ) ) { dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( new TimeoutException ( timeoutMessage ( timeout , unit ) ) ) ; } } catch ( InterruptedException ex ) { dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } } return error ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Block until the observer terminates and return true ; return false if the wait times out . [CODESPLIT] public boolean blockingAwait ( long timeout , TimeUnit unit ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; if ( ! await ( timeout , unit ) ) { dispose ( ) ; return false ; } } catch ( InterruptedException ex ) { dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } } Throwable ex = error ; if ( ex != null ) { throw ExceptionHelper . wrapOrThrow ( ex ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an unbounded ReplayProcessor with the specified initial buffer capacity . <p > Use this method to avoid excessive array reallocation while the internal buffer grows to accommodate new items . For example if you know that the buffer will hold 32k items you can ask the { @code ReplayProcessor } to preallocate its internal array with a capacity to hold that many items . Once the items start to arrive the internal array won t need to grow creating less garbage and no overhead due to frequent array - copying . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > ReplayProcessor < T > create ( int capacityHint ) { return new ReplayProcessor < T > ( new UnboundedReplayBuffer < T > ( capacityHint ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a size - bounded ReplayProcessor . <p > In this setting the { @code ReplayProcessor } holds at most { @code size } items in its internal buffer and discards the oldest item . <p > When { @code Subscriber } s subscribe to a terminated { @code ReplayProcessor } they are guaranteed to see at most { @code size } { @code onNext } events followed by a termination event . <p > If a { @code Subscriber } subscribes while the { @code ReplayProcessor } is active it will observe all items in the buffer at that point in time and each item observed afterwards even if the buffer evicts items due to the size constraint in the mean time . In other words once a { @code Subscriber } subscribes it will receive items without gaps in the sequence . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > ReplayProcessor < T > createWithSize ( int maxSize ) { return new ReplayProcessor < T > ( new SizeBoundReplayBuffer < T > ( maxSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * test [CODESPLIT] static < T > ReplayProcessor < T > createUnbounded ( ) { return new ReplayProcessor < T > ( new SizeBoundReplayBuffer < T > ( Integer . MAX_VALUE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a time - bounded ReplayProcessor . <p > In this setting the { @code ReplayProcessor } internally tags each observed item with a timestamp value supplied by the { @link Scheduler } and keeps only those whose age is less than the supplied time value converted to milliseconds . For example an item arrives at T = 0 and the max age is set to 5 ; at T&gt ; = 5 this first item is then evicted by any subsequent item or termination event leaving the buffer empty . <p > Once the processor is terminated { @code Subscriber } s subscribing to it will receive items that remained in the buffer after the terminal event regardless of their age . <p > If a { @code Subscriber } subscribes while the { @code ReplayProcessor } is active it will observe only those items from within the buffer that have an age less than the specified time and each item observed thereafter even if the buffer evicts items due to the time constraint in the mean time . In other words once a { @code Subscriber } subscribes it observes items without gaps in the sequence except for any outdated items at the beginning of the sequence . <p > Note that terminal notifications ( { @code onError } and { @code onComplete } ) trigger eviction as well . For example with a max age of 5 the first item is observed at T = 0 then an { @code onComplete } notification arrives at T = 10 . If a { @code Subscriber } subscribes at T = 11 it will find an empty { @code ReplayProcessor } with just an { @code onComplete } notification . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > ReplayProcessor < T > createWithTime ( long maxAge , TimeUnit unit , Scheduler scheduler ) { return new ReplayProcessor < T > ( new SizeAndTimeBoundReplayBuffer < T > ( Integer . MAX_VALUE , maxAge , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "final : fixed protocol steps to support fuseable and non - fuseable upstream [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public final void onSubscribe ( Subscription s ) { if ( SubscriptionHelper . validate ( this . upstream , s ) ) { this . upstream = s ; if ( s instanceof QueueSubscription ) { this . qs = ( QueueSubscription < T > ) s ; } if ( beforeDownstream ( ) ) { downstream . onSubscribe ( this ) ; afterDownstream ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rethrows the throwable if it is a fatal exception or calls { [CODESPLIT] protected final void fail ( Throwable t ) { Exceptions . throwIfFatal ( t ) ; upstream . cancel ( ) ; onError ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the upstream s QueueSubscription . requestFusion with the mode and saves the established mode in { [CODESPLIT] protected final int transitiveBoundaryFusion ( int mode ) { QueueSubscription < T > qs = this . qs ; if ( qs != null ) { if ( ( mode & BOUNDARY ) == 0 ) { int m = qs . requestFusion ( mode ) ; if ( m != NONE ) { sourceMode = m ; } return m ; } } return NONE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link BehaviorSubject } that emits the last item it observed and all subsequent items to each { @link Observer } that subscribes to it . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > BehaviorSubject < T > createDefault ( T defaultValue ) { return new BehaviorSubject < T > ( defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a single value the Subject currently has or null if no such value exists . <p > The method is thread - safe . [CODESPLIT] @ Nullable public T getValue ( ) { Object o = value . get ( ) ; if ( NotificationLite . isComplete ( o ) || NotificationLite . isError ( o ) ) { return null ; } return NotificationLite . getValue ( o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Object array containing snapshot all values of the Subject . <p > The method is thread - safe . [CODESPLIT] @ Deprecated public Object [ ] getValues ( ) { @ SuppressWarnings ( \"unchecked\" ) T [ ] a = ( T [ ] ) EMPTY_ARRAY ; T [ ] b = getValues ( a ) ; if ( b == EMPTY_ARRAY ) { return new Object [ 0 ] ; } return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a typed array containing a snapshot of all values of the Subject . <p > The method follows the conventions of Collection . toArray by setting the array element after the last value to null ( if the capacity permits ) . <p > The method is thread - safe . [CODESPLIT] @ Deprecated @ SuppressWarnings ( \"unchecked\" ) public T [ ] getValues ( T [ ] array ) { Object o = value . get ( ) ; if ( o == null || NotificationLite . isComplete ( o ) || NotificationLite . isError ( o ) ) { if ( array . length != 0 ) { array [ 0 ] = null ; } return array ; } T v = NotificationLite . getValue ( o ) ; if ( array . length != 0 ) { array [ 0 ] = v ; if ( array . length != 1 ) { array [ 1 ] = null ; } } else { array = ( T [ ] ) Array . newInstance ( array . getClass ( ) . getComponentType ( ) , 1 ) ; array [ 0 ] = v ; } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the subject has any value . <p > The method is thread - safe . [CODESPLIT] public boolean hasValue ( ) { Object o = value . get ( ) ; return o != null && ! NotificationLite . isComplete ( o ) && ! NotificationLite . isError ( o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drain the queue but give up with an error if there aren t enough requests . [CODESPLIT] public static < T , U > void drainMaxLoop ( SimplePlainQueue < T > q , Subscriber < ? super U > a , boolean delayError , Disposable dispose , QueueDrain < T , U > qd ) { int missed = 1 ; for ( ; ; ) { for ( ; ; ) { boolean d = qd . done ( ) ; T v = q . poll ( ) ; boolean empty = v == null ; if ( checkTerminated ( d , empty , a , delayError , q , qd ) ) { if ( dispose != null ) { dispose . dispose ( ) ; } return ; } if ( empty ) { break ; } long r = qd . requested ( ) ; if ( r != 0L ) { if ( qd . accept ( a , v ) ) { if ( r != Long . MAX_VALUE ) { qd . produced ( 1 ) ; } } } else { q . clear ( ) ; if ( dispose != null ) { dispose . dispose ( ) ; } a . onError ( new MissingBackpressureException ( \"Could not emit value due to lack of requests.\" ) ) ; return ; } } missed = qd . leave ( - missed ) ; if ( missed == 0 ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a queue : spsc - array if capacityHint is positive and spsc - linked - array if capacityHint is negative ; in both cases the capacity is the absolute value of prefetch . [CODESPLIT] public static < T > SimpleQueue < T > createQueue ( int capacityHint ) { if ( capacityHint < 0 ) { return new SpscLinkedArrayQueue < T > ( - capacityHint ) ; } return new SpscArrayQueue < T > ( capacityHint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests Long . MAX_VALUE if prefetch is negative or the exact amount if prefetch is positive . [CODESPLIT] public static void request ( Subscription s , int prefetch ) { s . request ( prefetch < 0 ? Long . MAX_VALUE : prefetch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accumulates requests ( not validated ) and handles the completed mode draining of the queue based on the requests . [CODESPLIT] public static < T > boolean postCompleteRequest ( long n , Subscriber < ? super T > actual , Queue < T > queue , AtomicLong state , BooleanSupplier isCancelled ) { for ( ; ; ) { long r = state . get ( ) ; // extract the current request amount long r0 = r & REQUESTED_MASK ; // preserve COMPLETED_MASK and calculate new requested amount long u = ( r & COMPLETED_MASK ) | BackpressureHelper . addCap ( r0 , n ) ; if ( state . compareAndSet ( r , u ) ) { // (complete, 0) -> (complete, n) transition then replay if ( r == COMPLETED_MASK ) { postCompleteDrain ( n | COMPLETED_MASK , actual , queue , state , isCancelled ) ; return true ; } // (active, r) -> (active, r + n) transition then continue with requesting from upstream return false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drains the queue based on the outstanding requests in post - completed mode ( only! ) . [CODESPLIT] static < T > boolean postCompleteDrain ( long n , Subscriber < ? super T > actual , Queue < T > queue , AtomicLong state , BooleanSupplier isCancelled ) { // TODO enable fast-path //        if (n == -1 || n == Long.MAX_VALUE) { //            for (;;) { //                if (isCancelled.getAsBoolean()) { //                    break; //                } // //                T v = queue.poll(); // //                if (v == null) { //                    actual.onComplete(); //                    break; //                } // //                actual.onNext(v); //            } // //            return true; //        } long e = n & COMPLETED_MASK ; for ( ; ; ) { while ( e != n ) { if ( isCancelled ( isCancelled ) ) { return true ; } T t = queue . poll ( ) ; if ( t == null ) { actual . onComplete ( ) ; return true ; } actual . onNext ( t ) ; e ++ ; } if ( isCancelled ( isCancelled ) ) { return true ; } if ( queue . isEmpty ( ) ) { actual . onComplete ( ) ; return true ; } n = state . get ( ) ; if ( n == e ) { n = state . addAndGet ( - ( e & REQUESTED_MASK ) ) ; if ( ( n & REQUESTED_MASK ) == 0L ) { return false ; } e = n & COMPLETED_MASK ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals the completion of the main sequence and switches to post - completion replay mode . [CODESPLIT] public static < T > void postComplete ( Subscriber < ? super T > actual , Queue < T > queue , AtomicLong state , BooleanSupplier isCancelled ) { if ( queue . isEmpty ( ) ) { actual . onComplete ( ) ; return ; } if ( postCompleteDrain ( state . get ( ) , actual , queue , state , isCancelled ) ) { return ; } for ( ; ; ) { long r = state . get ( ) ; if ( ( r & COMPLETED_MASK ) != 0L ) { return ; } long u = r | COMPLETED_MASK ; // (active, r) -> (complete, r) transition if ( state . compareAndSet ( r , u ) ) { // if the requested amount was non-zero, drain the queue if ( r != 0L ) { postCompleteDrain ( u , actual , queue , state , isCancelled ) ; } return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an unbounded replay subject . <p > The internal buffer is backed by an { @link ArrayList } and starts with an initial capacity of 16 . Once the number of items reaches this capacity it will grow as necessary ( usually by 50% ) . However as the number of items grows this causes frequent array reallocation and copying and may hurt performance and latency . This can be avoided with the { @link #create ( int ) } overload which takes an initial capacity parameter and can be tuned to reduce the array reallocation frequency as needed . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > ReplaySubject < T > create ( ) { return new ReplaySubject < T > ( new UnboundedReplayBuffer < T > ( 16 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a size - bounded replay subject . <p > In this setting the { @code ReplaySubject } holds at most { @code size } items in its internal buffer and discards the oldest item . <p > When observers subscribe to a terminated { @code ReplaySubject } they are guaranteed to see at most { @code size } { @code onNext } events followed by a termination event . <p > If an observer subscribes while the { @code ReplaySubject } is active it will observe all items in the buffer at that point in time and each item observed afterwards even if the buffer evicts items due to the size constraint in the mean time . In other words once an Observer subscribes it will receive items without gaps in the sequence . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > ReplaySubject < T > createWithSize ( int maxSize ) { return new ReplaySubject < T > ( new SizeBoundReplayBuffer < T > ( maxSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * test [CODESPLIT] static < T > ReplaySubject < T > createUnbounded ( ) { return new ReplaySubject < T > ( new SizeBoundReplayBuffer < T > ( Integer . MAX_VALUE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals the given value and an onComplete if the downstream is ready to receive the final value . [CODESPLIT] protected final void complete ( R n ) { long p = produced ; if ( p != 0 ) { BackpressureHelper . produced ( this , p ) ; } for ( ; ; ) { long r = get ( ) ; if ( ( r & COMPLETE_MASK ) != 0 ) { onDrop ( n ) ; return ; } if ( ( r & REQUEST_MASK ) != 0 ) { lazySet ( COMPLETE_MASK + 1 ) ; downstream . onNext ( n ) ; downstream . onComplete ( ) ; return ; } value = n ; if ( compareAndSet ( 0 , COMPLETE_MASK ) ) { return ; } value = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Object array containing snapshot all values of this processor . <p > The method is thread - safe . [CODESPLIT] @ Deprecated public Object [ ] getValues ( ) { T v = getValue ( ) ; return v != null ? new Object [ ] { v } : new Object [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a typed array containing a snapshot of all values of this processor . <p > The method follows the conventions of Collection . toArray by setting the array element after the last value to null ( if the capacity permits ) . <p > The method is thread - safe . [CODESPLIT] @ Deprecated public T [ ] getValues ( T [ ] array ) { T v = getValue ( ) ; if ( v == null ) { if ( array . length != 0 ) { array [ 0 ] = null ; } return array ; } if ( array . length == 0 ) { array = Arrays . copyOf ( array , 1 ) ; } array [ 0 ] = v ; if ( array . length != 1 ) { array [ 1 ] = null ; } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the contained value if this notification is an onNext signal null otherwise . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Nullable public T getValue ( ) { Object o = value ; if ( o != null && ! NotificationLite . isError ( o ) ) { return ( T ) value ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the container Throwable error if this notification is an onError signal null otherwise . [CODESPLIT] @ Nullable public Throwable getError ( ) { Object o = value ; if ( NotificationLite . isError ( o ) ) { return NotificationLite . getError ( o ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs an onNext notification containing the given value . [CODESPLIT] @ NonNull public static < T > Notification < T > createOnNext ( @ NonNull T value ) { ObjectHelper . requireNonNull ( value , \"value is null\" ) ; return new Notification < T > ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs an onError notification containing the error . [CODESPLIT] @ NonNull public static < T > Notification < T > createOnError ( @ NonNull Throwable error ) { ObjectHelper . requireNonNull ( error , \"error is null\" ) ; return new Notification < T > ( NotificationLite . error ( error ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the upstream Disposable is null and returns true otherwise disposes the next Disposable and if the upstream is not the shared disposed instance reports a ProtocolViolationException due to multiple subscribe attempts . [CODESPLIT] public static boolean validate ( Disposable upstream , Disposable next , Class < ? > observer ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; if ( upstream != null ) { next . dispose ( ) ; if ( upstream != DisposableHelper . DISPOSED ) { reportDoubleSubscription ( observer ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically updates the target upstream AtomicReference from null to the non - null next Disposable otherwise disposes next and reports a ProtocolViolationException if the AtomicReference doesn t contain the shared disposed indicator . [CODESPLIT] public static boolean setOnce ( AtomicReference < Disposable > upstream , Disposable next , Class < ? > observer ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; if ( ! upstream . compareAndSet ( null , next ) ) { next . dispose ( ) ; if ( upstream . get ( ) != DisposableHelper . DISPOSED ) { reportDoubleSubscription ( observer ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the upstream Subscription is null and returns true otherwise cancels the next Subscription and if the upstream is not the shared cancelled instance reports a ProtocolViolationException due to multiple subscribe attempts . [CODESPLIT] public static boolean validate ( Subscription upstream , Subscription next , Class < ? > subscriber ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; if ( upstream != null ) { next . cancel ( ) ; if ( upstream != SubscriptionHelper . CANCELLED ) { reportDoubleSubscription ( subscriber ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically updates the target upstream AtomicReference from null to the non - null next Subscription otherwise cancels next and reports a ProtocolViolationException if the AtomicReference doesn t contain the shared cancelled indicator . [CODESPLIT] public static boolean setOnce ( AtomicReference < Subscription > upstream , Subscription next , Class < ? > subscriber ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; if ( ! upstream . compareAndSet ( null , next ) ) { next . cancel ( ) ; if ( upstream . get ( ) != SubscriptionHelper . CANCELLED ) { reportDoubleSubscription ( subscriber ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically adds the consumer to the { [CODESPLIT] void add ( CacheSubscription < T > consumer ) { for ( ; ; ) { CacheSubscription < T > [ ] current = subscribers . get ( ) ; if ( current == TERMINATED ) { return ; } int n = current . length ; @ SuppressWarnings ( \"unchecked\" ) CacheSubscription < T > [ ] next = new CacheSubscription [ n + 1 ] ; System . arraycopy ( current , 0 , next , 0 , n ) ; next [ n ] = consumer ; if ( subscribers . compareAndSet ( current , next ) ) { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically removes the consumer from the { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) void remove ( CacheSubscription < T > consumer ) { for ( ; ; ) { CacheSubscription < T > [ ] current = subscribers . get ( ) ; int n = current . length ; if ( n == 0 ) { return ; } int j = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( current [ i ] == consumer ) { j = i ; break ; } } if ( j < 0 ) { return ; } CacheSubscription < T > [ ] next ; if ( n == 1 ) { next = EMPTY ; } else { next = new CacheSubscription [ n - 1 ] ; System . arraycopy ( current , 0 , next , 0 , j ) ; System . arraycopy ( current , j + 1 , next , j , n - j - 1 ) ; } if ( subscribers . compareAndSet ( current , next ) ) { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replays the contents of this cache to the given consumer based on its current state and number of items requested by it . [CODESPLIT] void replay ( CacheSubscription < T > consumer ) { // make sure there is only one replay going on at a time if ( consumer . getAndIncrement ( ) != 0 ) { return ; } // see if there were more replay request in the meantime int missed = 1 ; // read out state into locals upfront to avoid being re-read due to volatile reads long index = consumer . index ; int offset = consumer . offset ; Node < T > node = consumer . node ; AtomicLong requested = consumer . requested ; Subscriber < ? super T > downstream = consumer . downstream ; int capacity = capacityHint ; for ( ; ; ) { // first see if the source has terminated, read order matters! boolean sourceDone = done ; // and if the number of items is the same as this consumer has received boolean empty = size == index ; // if the source is done and we have all items so far, terminate the consumer if ( sourceDone && empty ) { // release the node object to avoid leaks through retained consumers consumer . node = null ; // if error is not null then the source failed Throwable ex = error ; if ( ex != null ) { downstream . onError ( ex ) ; } else { downstream . onComplete ( ) ; } return ; } // there are still items not sent to the consumer if ( ! empty ) { // see how many items the consumer has requested in total so far long consumerRequested = requested . get ( ) ; // MIN_VALUE indicates a cancelled consumer, we stop replaying if ( consumerRequested == Long . MIN_VALUE ) { // release the node object to avoid leaks through retained consumers consumer . node = null ; return ; } // if the consumer has requested more and there is more, we will emit an item if ( consumerRequested != index ) { // if the offset in the current node has reached the node capacity if ( offset == capacity ) { // switch to the subsequent node node = node . next ; // reset the in-node offset offset = 0 ; } // emit the cached item downstream . onNext ( node . values [ offset ] ) ; // move the node offset forward offset ++ ; // move the total consumed item count forward index ++ ; // retry for the next item/terminal event if any continue ; } } // commit the changed references back consumer . index = index ; consumer . offset = offset ; consumer . node = node ; // release the changes and see if there were more replay request in the meantime missed = consumer . addAndGet ( - missed ) ; if ( missed == 0 ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds two long values and caps the sum at Long . MAX_VALUE . [CODESPLIT] public static long addCap ( long a , long b ) { long u = a + b ; if ( u < 0L ) { return Long . MAX_VALUE ; } return u ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiplies two long values and caps the product at Long . MAX_VALUE . [CODESPLIT] public static long multiplyCap ( long a , long b ) { long u = a * b ; if ( ( ( a | b ) >>> 31 ) != 0 ) { if ( u / a != b ) { return Long . MAX_VALUE ; } } return u ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically adds the positive value n to the requested value in the AtomicLong and caps the result at Long . MAX_VALUE and returns the previous value . [CODESPLIT] public static long add ( AtomicLong requested , long n ) { for ( ; ; ) { long r = requested . get ( ) ; if ( r == Long . MAX_VALUE ) { return Long . MAX_VALUE ; } long u = addCap ( r , n ) ; if ( requested . compareAndSet ( r , u ) ) { return r ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically adds the positive value n to the requested value in the AtomicLong and caps the result at Long . MAX_VALUE and returns the previous value and considers Long . MIN_VALUE as a cancel indication ( no addition then ) . [CODESPLIT] public static long addCancel ( AtomicLong requested , long n ) { for ( ; ; ) { long r = requested . get ( ) ; if ( r == Long . MIN_VALUE ) { return Long . MIN_VALUE ; } if ( r == Long . MAX_VALUE ) { return Long . MAX_VALUE ; } long u = addCap ( r , n ) ; if ( requested . compareAndSet ( r , u ) ) { return r ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically subtract the given number ( positive not validated ) from the target field unless it contains Long . MAX_VALUE . [CODESPLIT] public static long produced ( AtomicLong requested , long n ) { for ( ; ; ) { long current = requested . get ( ) ; if ( current == Long . MAX_VALUE ) { return Long . MAX_VALUE ; } long update = current - n ; if ( update < 0L ) { RxJavaPlugins . onError ( new IllegalStateException ( \"More produced than requested: \" + update ) ) ; update = 0L ; } if ( requested . compareAndSet ( current , update ) ) { return update ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the Observer methods on the current thread . <p > [CODESPLIT] public static < T > void subscribe ( ObservableSource < ? extends T > o , Observer < ? super T > observer ) { final BlockingQueue < Object > queue = new LinkedBlockingQueue < Object > ( ) ; BlockingObserver < T > bs = new BlockingObserver < T > ( queue ) ; observer . onSubscribe ( bs ) ; o . subscribe ( bs ) ; for ( ; ; ) { if ( bs . isDisposed ( ) ) { break ; } Object v = queue . poll ( ) ; if ( v == null ) { try { v = queue . take ( ) ; } catch ( InterruptedException ex ) { bs . dispose ( ) ; observer . onError ( ex ) ; return ; } } if ( bs . isDisposed ( ) || o == BlockingObserver . TERMINATED || NotificationLite . acceptFull ( v , observer ) ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the source observable to a terminal event ignoring any values and rethrowing any exception . [CODESPLIT] public static < T > void subscribe ( ObservableSource < ? extends T > o ) { BlockingIgnoringReceiver callback = new BlockingIgnoringReceiver ( ) ; LambdaObserver < T > ls = new LambdaObserver < T > ( Functions . emptyConsumer ( ) , callback , callback , Functions . emptyConsumer ( ) ) ; o . subscribe ( ls ) ; BlockingHelper . awaitForComplete ( callback , ls ) ; Throwable e = callback . error ; if ( e != null ) { throw ExceptionHelper . wrapOrThrow ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given actions on the current thread . [CODESPLIT] public static < T > void subscribe ( ObservableSource < ? extends T > o , final Consumer < ? super T > onNext , final Consumer < ? super Throwable > onError , final Action onComplete ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; subscribe ( o , new LambdaObserver < T > ( onNext , onError , onComplete , Functions . emptyConsumer ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which completes only when all sources complete one after another . <p > <img width = 640 height = 283 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . concatArray . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable concatArray ( CompletableSource ... sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; if ( sources . length == 0 ) { return complete ( ) ; } else if ( sources . length == 1 ) { return wrap ( sources [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new CompletableConcatArray ( sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which completes only when all sources complete one after another . <p > <img width = 640 height = 303 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . concat . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable concat ( Iterable < ? extends CompletableSource > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableConcatIterable ( sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which completes only when all sources complete one after another . <p > <img width = 640 height = 237 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . concat . p . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public static Completable concat ( Publisher < ? extends CompletableSource > sources ) { return concat ( sources , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which completes only when all sources complete one after another . <p > <img width = 640 height = 237 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . concat . pn . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public static Completable concat ( Publisher < ? extends CompletableSource > sources , int prefetch ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new CompletableConcat ( sources , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an API ( via a cold Completable ) that bridges the reactive world with the callback - style world . <p > <img width = 640 height = 442 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . create . png alt = > <p > Example : <pre > <code > Completable . create ( emitter - &gt ; { Callback listener = new Callback () { &#64 ; Override public void onEvent ( Event e ) { emitter . onComplete () ; } [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable create ( CompletableOnSubscribe source ) { ObjectHelper . requireNonNull ( source , \"source is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableCreate ( source ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Completable instance that emits the given Throwable exception to subscribers . <p > <img width = 640 height = 462 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . error . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable error ( final Throwable error ) { ObjectHelper . requireNonNull ( error , \"error is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableError ( error ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that runs the given Action for each subscriber and emits either an unchecked exception or simply completes . <p > <img width = 640 height = 297 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . fromAction . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable fromAction ( final Action run ) { ObjectHelper . requireNonNull ( run , \"run is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableFromAction ( run ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which when subscribed executes the callable function ignores its normal result and emits onError or onComplete only . <p > <img width = 640 height = 286 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . fromCallable . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable fromCallable ( final Callable < ? > callable ) { ObjectHelper . requireNonNull ( callable , \"callable is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableFromCallable ( callable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that reacts to the termination of the given Future in a blocking fashion . <p > <img width = 640 height = 628 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . fromFuture . png alt = > <p > Note that if any of the observers to this Completable call dispose this Completable will cancel the future . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable fromFuture ( final Future < ? > future ) { ObjectHelper . requireNonNull ( future , \"future is null\" ) ; return fromAction ( Functions . futureAction ( future ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that when subscribed to subscribes to the { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Completable fromMaybe ( final MaybeSource < T > maybe ) { ObjectHelper . requireNonNull ( maybe , \"maybe is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeIgnoreElementCompletable < T > ( maybe ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that runs the given Runnable for each subscriber and emits either its exception or simply completes . <p > <img width = 640 height = 297 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . fromRunnable . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable fromRunnable ( final Runnable run ) { ObjectHelper . requireNonNull ( run , \"run is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableFromRunnable ( run ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that when subscribed to subscribes to the Single instance and emits a completion event if the single emits onSuccess or forwards any onError events . <p > <img width = 640 height = 356 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . fromSingle . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Completable fromSingle ( final SingleSource < T > single ) { ObjectHelper . requireNonNull ( single , \"single is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableFromSingle < T > ( single ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that subscribes to all sources at once and completes only when all source Completables complete or one of them emits an error . <p > <img width = 640 height = 270 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . mergeArray . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable mergeArray ( CompletableSource ... sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; if ( sources . length == 0 ) { return complete ( ) ; } else if ( sources . length == 1 ) { return wrap ( sources [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new CompletableMergeArray ( sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that subscribes to all sources at once and completes only when all source Completables complete or one of them emits an error . <p > <img width = 640 height = 311 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . merge . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable merge ( Iterable < ? extends CompletableSource > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableMergeIterable ( sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that subscribes to all sources at once and completes only when all source Completables complete or one of them emits an error . <p > <img width = 640 height = 336 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . merge . p . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) public static Completable merge ( Publisher < ? extends CompletableSource > sources ) { return merge0 ( sources , Integer . MAX_VALUE , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that keeps subscriptions to a limited number of sources at once and completes only when all source Completables complete or one of them emits an error . <p > <img width = 640 height = 269 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . merge . pn . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public static Completable merge ( Publisher < ? extends CompletableSource > sources , int maxConcurrency ) { return merge0 ( sources , maxConcurrency , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that subscribes to all Completables in the source sequence and delays any error emitted by either the sources observable or any of the inner Completables until all of them terminate in a way or another . <p > <img width = 640 height = 466 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . mergeDelayError . p . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) public static Completable mergeDelayError ( Publisher < ? extends CompletableSource > sources ) { return merge0 ( sources , Integer . MAX_VALUE , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that subscribes to a limited number of inner Completables at once in the source sequence and delays any error emitted by either the sources observable or any of the inner Completables until all of them terminate in a way or another . <p > <img width = 640 height = 440 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . mergeDelayError . pn . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public static Completable mergeDelayError ( Publisher < ? extends CompletableSource > sources , int maxConcurrency ) { return merge0 ( sources , maxConcurrency , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that never calls onError or onComplete . <p > <img width = 640 height = 512 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . never . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable never ( ) { return RxJavaPlugins . onAssembly ( CompletableNever . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that fires its onComplete event after the given delay elapsed . <p > <img width = 640 height = 413 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . timer . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public static Completable timer ( long delay , TimeUnit unit ) { return timer ( delay , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a NullPointerException instance and sets the given Throwable as its initial cause . [CODESPLIT] private static NullPointerException toNpe ( Throwable ex ) { NullPointerException npe = new NullPointerException ( \"Actually not, but can't pass out an exception otherwise...\" ) ; npe . initCause ( ex ) ; return npe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance which manages a resource along with a custom Completable instance while the subscription is active . <p > <img width = 640 height = 388 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . using . png alt = > <p > This overload disposes eagerly before the terminal event is emitted . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < R > Completable using ( Callable < R > resourceSupplier , Function < ? super R , ? extends CompletableSource > completableFunction , Consumer < ? super R > disposer ) { return using ( resourceSupplier , completableFunction , disposer , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the given CompletableSource into a Completable if not already Completable . <p > <img width = 640 height = 354 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . wrap . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static Completable wrap ( CompletableSource source ) { ObjectHelper . requireNonNull ( source , \"source is null\" ) ; if ( source instanceof Completable ) { return RxJavaPlugins . onAssembly ( ( Completable ) source ) ; } return RxJavaPlugins . onAssembly ( new CompletableFromUnsafeSource ( source ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that emits the a terminated event of either this Completable or the other Completable whichever fires first . <p > <img width = 640 height = 484 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . ambWith . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable ambWith ( CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return ambArray ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable which will subscribe to this Completable and once that is completed then will subscribe to the { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < T > Observable < T > andThen ( ObservableSource < T > next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableAndThenObservable < T > ( this , next ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable which will subscribe to this Completable and once that is completed then will subscribe to the { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < T > Flowable < T > andThen ( Publisher < T > next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableAndThenPublisher < T > ( this , next ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single which will subscribe to this Completable and once that is completed then will subscribe to the { @code next } SingleSource . An error event from this Completable will be propagated to the downstream subscriber and will result in skipping the subscription of the Single . <p > <img width = 640 height = 437 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . andThen . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code andThen } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < T > Single < T > andThen ( SingleSource < T > next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDelayWithCompletable < T > ( next , this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Maybe } which will subscribe to this Completable and once that is completed then will subscribe to the { @code next } MaybeSource . An error event from this Completable will be propagated to the downstream subscriber and will result in skipping the subscription of the Maybe . <p > <img width = 640 height = 280 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . andThen . m . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code andThen } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < T > Maybe < T > andThen ( MaybeSource < T > next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return RxJavaPlugins . onAssembly ( new MaybeDelayWithCompletable < T > ( next , this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that first runs this Completable and then the other completable . <p > <img width = 640 height = 437 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . andThen . c . png alt = > <p > This is an alias for { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable andThen ( CompletableSource next ) { ObjectHelper . requireNonNull ( next , \"next is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableAndThenCompletable ( this , next ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified converter function during assembly time and returns its resulting value . <p > <img width = 640 height = 751 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . as . png alt = > <p > This allows fluent conversion to any other type . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > R as ( @ NonNull CompletableConverter < ? extends R > converter ) { return ObjectHelper . requireNonNull ( converter , \"converter is null\" ) . apply ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to and awaits the termination of this Completable instance in a blocking manner and rethrows any exception emitted . <p > <img width = 640 height = 432 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . blockingAwait . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingAwait ( ) { BlockingMultiObserver < Void > observer = new BlockingMultiObserver < Void > ( ) ; subscribe ( observer ) ; observer . blockingGet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the given transformer function with this instance and returns the function s resulting Completable . <p > <img width = 640 height = 625 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . compose . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable compose ( CompletableTransformer transformer ) { return wrap ( ObjectHelper . requireNonNull ( transformer , \"transformer is null\" ) . apply ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates this Completable with another Completable . <p > <img width = 640 height = 317 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . concatWith . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable concatWith ( CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableAndThenCompletable ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which delays the emission of the completion event by the given time while running on the specified scheduler . <p > <img width = 640 height = 313 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . delay . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Completable delay ( long delay , TimeUnit unit , Scheduler scheduler ) { return delay ( delay , unit , scheduler , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which delays the emission of the completion event and optionally the error as well by the given time while running on the specified scheduler . <p > <img width = 640 height = 253 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . delay . sb . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Completable delay ( final long delay , final TimeUnit unit , final Scheduler scheduler , final boolean delayError ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableDelay ( this , delay , unit , scheduler , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time . <p > <img width = 640 height = 475 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . delaySubscription . t . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code delaySubscription } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ Experimental @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Completable delaySubscription ( long delay , TimeUnit unit ) { return delaySubscription ( delay , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time both waiting and subscribing on a given Scheduler . <p > <img width = 640 height = 420 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . delaySubscription . ts . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ Experimental @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Completable delaySubscription ( long delay , TimeUnit unit , Scheduler scheduler ) { return Completable . timer ( delay , unit , scheduler ) . andThen ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which calls the given onComplete callback if this Completable completes . <p > <img width = 640 height = 304 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . doOnComplete . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable doOnComplete ( Action onComplete ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , onComplete , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the shared { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable doOnDispose ( Action onDispose ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , onDispose ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which calls the given onError callback if this Completable emits an error . <p > <img width = 640 height = 304 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . doOnError . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable doOnError ( Consumer < ? super Throwable > onError ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , onError , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that calls the various callbacks on the specific lifecycle events . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) private Completable doOnLifecycle ( final Consumer < ? super Disposable > onSubscribe , final Consumer < ? super Throwable > onError , final Action onComplete , final Action onTerminate , final Action onAfterTerminate , final Action onDispose ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; ObjectHelper . requireNonNull ( onTerminate , \"onTerminate is null\" ) ; ObjectHelper . requireNonNull ( onAfterTerminate , \"onAfterTerminate is null\" ) ; ObjectHelper . requireNonNull ( onDispose , \"onDispose is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletablePeek ( this , onSubscribe , onError , onComplete , onTerminate , onAfterTerminate , onDispose ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that calls the given onSubscribe callback with the disposable that child subscribers receive on subscription . <p > <img width = 640 height = 304 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . doOnSubscribe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable doOnSubscribe ( Consumer < ? super Disposable > onSubscribe ) { return doOnLifecycle ( onSubscribe , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that calls the given onTerminate callback just before this Completable completes normally or with an exception . <p > <img width = 640 height = 304 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . doOnTerminate . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable doOnTerminate ( final Action onTerminate ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , onTerminate , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that calls the given onTerminate callback after this Completable completes normally or with an exception . <p > <img width = 640 height = 304 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . doAfterTerminate . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable doAfterTerminate ( final Action onAfterTerminate ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION , onAfterTerminate , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which emits the terminal events from the thread of the specified scheduler . <p > <img width = 640 height = 523 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . observeOn . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Completable observeOn ( final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableObserveOn ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that if this Completable emits an error and the predicate returns true it will emit an onComplete and swallow the throwable . <p > <img width = 640 height = 283 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . onErrorComplete . f . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable onErrorComplete ( final Predicate < ? super Throwable > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableOnErrorComplete ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that when encounters an error from this Completable calls the specified mapper function that returns another Completable instance for it and resumes the execution with it . <p > <img width = 640 height = 426 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . onErrorResumeNext . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable onErrorResumeNext ( final Function < ? super Throwable , ? extends CompletableSource > errorMapper ) { ObjectHelper . requireNonNull ( errorMapper , \"errorMapper is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableResumeNext ( this , errorMapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that subscribes repeatedly at most the given times to this Completable . <p > <img width = 640 height = 408 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . repeat . n . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable repeat ( long times ) { return fromPublisher ( toFlowable ( ) . repeat ( times ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that repeatedly subscribes to this Completable so long as the given stop supplier returns false . <p > <img width = 640 height = 381 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . repeatUntil . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable repeatUntil ( BooleanSupplier stop ) { return fromPublisher ( toFlowable ( ) . repeatUntil ( stop ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable instance that repeats when the Publisher returned by the handler emits an item or completes when this Publisher emits a completed event . <p > <img width = 640 height = 586 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . repeatWhen . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable repeatWhen ( Function < ? super Flowable < Object > , ? extends Publisher < ? > > handler ) { return fromPublisher ( toFlowable ( ) . repeatWhen ( handler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that retries this Completable in case of an error as long as the predicate returns true . <p > <img width = 640 height = 325 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . retry . ff . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable retry ( BiPredicate < ? super Integer , ? super Throwable > predicate ) { return fromPublisher ( toFlowable ( ) . retry ( predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that when this Completable emits an error retries at most the given number of times before giving up and emitting the last error . <p > <img width = 640 height = 451 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . retry . n . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable retry ( long times ) { return fromPublisher ( toFlowable ( ) . retry ( times ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that when this Completable emits an error retries at most times or until the predicate returns false whichever happens first and emitting the last error . <p > <img width = 640 height = 361 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . retry . nf . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable retry ( long times , Predicate < ? super Throwable > predicate ) { return fromPublisher ( toFlowable ( ) . retry ( times , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which given a Publisher and when this Completable emits an error delivers that error through a Flowable and the Publisher should signal a value indicating a retry in response or a terminal event indicating a termination . <p > <img width = 640 height = 586 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . retryWhen . png alt = > <p > Note that the inner { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable retryWhen ( Function < ? super Flowable < Throwable > , ? extends Publisher < ? > > handler ) { return fromPublisher ( toFlowable ( ) . retryWhen ( handler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable which first delivers the events of the other Observable then runs this CompletableConsumable . <p > <img width = 640 height = 289 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . startWith . o . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < T > Observable < T > startWith ( Observable < T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return other . concatWith ( this . < T > toObservable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to this CompletableConsumable and returns a Disposable which can be used to dispose the subscription . <p > <img width = 640 height = 352 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . subscribe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( ) { EmptyCompletableObserver observer = new EmptyCompletableObserver ( ) ; subscribe ( observer ) ; return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes a given CompletableObserver ( subclass ) to this Completable and returns the given CompletableObserver as is . <p > <img width = 640 height = 349 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . subscribeWith . png alt = > <p > Usage example : <pre > <code > Completable source = Completable . complete () . delay ( 1 TimeUnit . SECONDS ) ; CompositeDisposable composite = new CompositeDisposable () ; [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < E extends CompletableObserver > E subscribeWith ( E observer ) { subscribe ( observer ) ; return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable which subscribes the child subscriber on the specified scheduler making sure the subscription side - effects happen on that specific thread of the scheduler . <p > <img width = 640 height = 686 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . subscribeOn . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Completable subscribeOn ( final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableSubscribeOn ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Terminates the downstream if this or the other { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable takeUntil ( CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new CompletableTakeUntilCompletable ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that runs this Completable and emits a TimeoutException in case this Completable doesn t complete within the given time . <p > <img width = 640 height = 348 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . timeout . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Completable timeout ( long timeout , TimeUnit unit ) { return timeout0 ( timeout , unit , Schedulers . computation ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that runs this Completable and switches to the other Completable in case this Completable doesn t complete within the given time . <p > <img width = 640 height = 308 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . timeout . c . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Completable timeout ( long timeout , TimeUnit unit , CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return timeout0 ( timeout , unit , Schedulers . computation ( ) , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that runs this Completable and emits a TimeoutException in case this Completable doesn t complete within the given time while waiting on the specified Scheduler . <p > <img width = 640 height = 348 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . timeout . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Completable timeout ( long timeout , TimeUnit unit , Scheduler scheduler ) { return timeout0 ( timeout , unit , scheduler , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Completable that runs this Completable and switches to the other Completable in case this Completable doesn t complete within the given time while waiting on the specified scheduler . <p > <img width = 640 height = 308 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . timeout . sc . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Completable timeout ( long timeout , TimeUnit unit , Scheduler scheduler , CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return timeout0 ( timeout , unit , scheduler , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows fluent conversion to another type via a function callback . <p > <img width = 640 height = 751 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . to . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > U to ( Function < ? super Completable , U > converter ) { try { return ObjectHelper . requireNonNull ( converter , \"converter is null\" ) . apply ( this ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable which when subscribed to subscribes to this Completable and relays the terminal events to the subscriber . <p > <img width = 640 height = 585 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . toFlowable . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ SuppressWarnings ( \"unchecked\" ) @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < T > Flowable < T > toFlowable ( ) { if ( this instanceof FuseToFlowable ) { return ( ( FuseToFlowable < T > ) this ) . fuseToFlowable ( ) ; } return RxJavaPlugins . onAssembly ( new CompletableToFlowable < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts this Completable into a { @link Maybe } . <p > <img width = 640 height = 585 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Completable . toMaybe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toMaybe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SuppressWarnings ( \"unchecked\" ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < T > Maybe < T > toMaybe ( ) { if ( this instanceof FuseToMaybe ) { return ( ( FuseToMaybe < T > ) this ) . fuseToMaybe ( ) ; } return RxJavaPlugins . onAssembly ( new MaybeFromCompletable < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try subscribing to a { [CODESPLIT] static < T > boolean tryAsCompletable ( Object source , Function < ? super T , ? extends CompletableSource > mapper , CompletableObserver observer ) { if ( source instanceof Callable ) { @ SuppressWarnings ( \"unchecked\" ) Callable < T > call = ( Callable < T > ) source ; CompletableSource cs = null ; try { T item = call . call ( ) ; if ( item != null ) { cs = ObjectHelper . requireNonNull ( mapper . apply ( item ) , \"The mapper returned a null CompletableSource\" ) ; } } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptyDisposable . error ( ex , observer ) ; return true ; } if ( cs == null ) { EmptyDisposable . complete ( observer ) ; } else { cs . subscribe ( observer ) ; } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try subscribing to a { [CODESPLIT] static < T , R > boolean tryAsMaybe ( Object source , Function < ? super T , ? extends MaybeSource < ? extends R > > mapper , Observer < ? super R > observer ) { if ( source instanceof Callable ) { @ SuppressWarnings ( \"unchecked\" ) Callable < T > call = ( Callable < T > ) source ; MaybeSource < ? extends R > cs = null ; try { T item = call . call ( ) ; if ( item != null ) { cs = ObjectHelper . requireNonNull ( mapper . apply ( item ) , \"The mapper returned a null MaybeSource\" ) ; } } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptyDisposable . error ( ex , observer ) ; return true ; } if ( cs == null ) { EmptyDisposable . complete ( observer ) ; } else { cs . subscribe ( MaybeToObservable . create ( observer ) ) ; } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new element to this list . [CODESPLIT] public void add ( Object o ) { // if no value yet, create the first array if ( size == 0 ) { head = new Object [ capacityHint + 1 ] ; tail = head ; head [ 0 ] = o ; indexInTail = 1 ; size = 1 ; } else // if the tail is full, create a new tail and link if ( indexInTail == capacityHint ) { Object [ ] t = new Object [ capacityHint + 1 ] ; t [ 0 ] = o ; tail [ capacityHint ] = t ; tail = t ; indexInTail = 1 ; size ++ ; } else { tail [ indexInTail ] = o ; indexInTail ++ ; size ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the purge thread . [CODESPLIT] public static void shutdown ( ) { ScheduledExecutorService exec = PURGE_THREAD . getAndSet ( null ) ; if ( exec != null ) { exec . shutdownNow ( ) ; } POOLS . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a ScheduledExecutorService with the given factory . [CODESPLIT] public static ScheduledExecutorService create ( ThreadFactory factory ) { final ScheduledExecutorService exec = Executors . newScheduledThreadPool ( 1 , factory ) ; tryPutIntoPool ( PURGE_ENABLED , exec ) ; return exec ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically sets a new subscription . [CODESPLIT] public final void setSubscription ( Subscription s ) { if ( cancelled ) { s . cancel ( ) ; return ; } ObjectHelper . requireNonNull ( s , \"s is null\" ) ; if ( get ( ) == 0 && compareAndSet ( 0 , 1 ) ) { Subscription a = actual ; if ( a != null && cancelOnReplace ) { a . cancel ( ) ; } actual = s ; long r = requested ; if ( decrementAndGet ( ) != 0 ) { drainLoop ( ) ; } if ( r != 0L ) { s . request ( r ) ; } return ; } Subscription a = missedSubscription . getAndSet ( s ) ; if ( a != null && cancelOnReplace ) { a . cancel ( ) ; } drain ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops until all notifications in the queue has been processed . [CODESPLIT] void emitLoop ( ) { for ( ; ; ) { AppendOnlyLinkedArrayList < Object > q ; synchronized ( this ) { q = queue ; if ( q == null ) { emitting = false ; return ; } queue = null ; } q . forEachWhile ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO fuse back to Flowable [CODESPLIT] @ Override protected void subscribeActual ( SingleObserver < ? super T > observer ) { source . subscribe ( new LastSubscriber < T > ( observer , defaultItem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws a particular { @code Throwable } only if it belongs to a set of fatal error varieties . These varieties are as follows : <ul > <li > { @code VirtualMachineError } < / li > <li > { @code ThreadDeath } < / li > <li > { @code LinkageError } < / li > < / ul > This can be useful if you are writing an operator that calls user - supplied code and you want to notify subscribers of errors encountered in that code by calling their { @code onError } methods but only if the errors are not so catastrophic that such a call would be futile in which case you simply want to rethrow the error . [CODESPLIT] public static void throwIfFatal ( @ NonNull Throwable t ) { // values here derived from https://github.com/ReactiveX/RxJava/issues/748#issuecomment-32471495 if ( t instanceof VirtualMachineError ) { throw ( VirtualMachineError ) t ; } else if ( t instanceof ThreadDeath ) { throw ( ThreadDeath ) t ; } else if ( t instanceof LinkageError ) { throw ( LinkageError ) t ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the provided Throwable is an Error this method throws it otherwise returns a RuntimeException wrapping the error if that error is a checked exception . [CODESPLIT] public static RuntimeException wrapOrThrow ( Throwable error ) { if ( error instanceof Error ) { throw ( Error ) error ; } if ( error instanceof RuntimeException ) { return ( RuntimeException ) error ; } return new RuntimeException ( error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a flattened list of Throwables from tree - like CompositeException chain . [CODESPLIT] public static List < Throwable > flatten ( Throwable t ) { List < Throwable > list = new ArrayList < Throwable > ( ) ; ArrayDeque < Throwable > deque = new ArrayDeque < Throwable > ( ) ; deque . offer ( t ) ; while ( ! deque . isEmpty ( ) ) { Throwable e = deque . removeFirst ( ) ; if ( e instanceof CompositeException ) { CompositeException ce = ( CompositeException ) e ; List < Throwable > exceptions = ce . getExceptions ( ) ; for ( int i = exceptions . size ( ) - 1 ; i >= 0 ; i -- ) { deque . offerFirst ( exceptions . get ( i ) ) ; } } else { list . add ( e ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Workaround for Java 6 not supporting throwing a final Throwable from a catch block . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < E extends Throwable > Exception throwIfThrowable ( Throwable e ) throws E { if ( e instanceof Exception ) { return ( Exception ) e ; } throw ( E ) e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically adds the consumer to the { [CODESPLIT] void add ( CacheDisposable < T > consumer ) { for ( ; ; ) { CacheDisposable < T > [ ] current = observers . get ( ) ; if ( current == TERMINATED ) { return ; } int n = current . length ; @ SuppressWarnings ( \"unchecked\" ) CacheDisposable < T > [ ] next = new CacheDisposable [ n + 1 ] ; System . arraycopy ( current , 0 , next , 0 , n ) ; next [ n ] = consumer ; if ( observers . compareAndSet ( current , next ) ) { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically removes the consumer from the { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) void remove ( CacheDisposable < T > consumer ) { for ( ; ; ) { CacheDisposable < T > [ ] current = observers . get ( ) ; int n = current . length ; if ( n == 0 ) { return ; } int j = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( current [ i ] == consumer ) { j = i ; break ; } } if ( j < 0 ) { return ; } CacheDisposable < T > [ ] next ; if ( n == 1 ) { next = EMPTY ; } else { next = new CacheDisposable [ n - 1 ] ; System . arraycopy ( current , 0 , next , 0 , j ) ; System . arraycopy ( current , j + 1 , next , j , n - j - 1 ) ; } if ( observers . compareAndSet ( current , next ) ) { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replays the contents of this cache to the given consumer based on its current state and number of items requested by it . [CODESPLIT] void replay ( CacheDisposable < T > consumer ) { // make sure there is only one replay going on at a time if ( consumer . getAndIncrement ( ) != 0 ) { return ; } // see if there were more replay request in the meantime int missed = 1 ; // read out state into locals upfront to avoid being re-read due to volatile reads long index = consumer . index ; int offset = consumer . offset ; Node < T > node = consumer . node ; Observer < ? super T > downstream = consumer . downstream ; int capacity = capacityHint ; for ( ; ; ) { // if the consumer got disposed, clear the node and quit if ( consumer . disposed ) { consumer . node = null ; return ; } // first see if the source has terminated, read order matters! boolean sourceDone = done ; // and if the number of items is the same as this consumer has received boolean empty = size == index ; // if the source is done and we have all items so far, terminate the consumer if ( sourceDone && empty ) { // release the node object to avoid leaks through retained consumers consumer . node = null ; // if error is not null then the source failed Throwable ex = error ; if ( ex != null ) { downstream . onError ( ex ) ; } else { downstream . onComplete ( ) ; } return ; } // there are still items not sent to the consumer if ( ! empty ) { // if the offset in the current node has reached the node capacity if ( offset == capacity ) { // switch to the subsequent node node = node . next ; // reset the in-node offset offset = 0 ; } // emit the cached item downstream . onNext ( node . values [ offset ] ) ; // move the node offset forward offset ++ ; // move the total consumed item count forward index ++ ; // retry for the next item/terminal event if any continue ; } // commit the changed references back consumer . index = index ; consumer . offset = offset ; consumer . node = node ; // release the changes and see if there were more replay request in the meantime missed = consumer . addAndGet ( - missed ) ; if ( missed == 0 ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "flatMap [CODESPLIT] @ Benchmark public void oneStreamOfNthatMergesIn1 ( final InputMillion input ) throws InterruptedException { Flowable < Flowable < Integer >> os = Flowable . range ( 1 , input . size ) . map ( new Function < Integer , Flowable < Integer > > ( ) { @ Override public Flowable < Integer > apply ( Integer v ) { return Flowable . just ( v ) ; } } ) ; PerfSubscriber o = input . newLatchedObserver ( ) ; Flowable . merge ( os ) . subscribe ( o ) ; if ( input . size == 1 ) { while ( o . latch . getCount ( ) != 0 ) { } } else { o . latch . await ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a disposable to this container or disposes it if the container has been disposed . [CODESPLIT] @ Override public boolean add ( @ NonNull Disposable disposable ) { ObjectHelper . requireNonNull ( disposable , \"disposable is null\" ) ; if ( ! disposed ) { synchronized ( this ) { if ( ! disposed ) { OpenHashSet < Disposable > set = resources ; if ( set == null ) { set = new OpenHashSet < Disposable > ( ) ; resources = set ; } set . add ( disposable ) ; return true ; } } } disposable . dispose ( ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically adds the given array of Disposables to the container or disposes them all if the container has been disposed . [CODESPLIT] public boolean addAll ( @ NonNull Disposable ... disposables ) { ObjectHelper . requireNonNull ( disposables , \"disposables is null\" ) ; if ( ! disposed ) { synchronized ( this ) { if ( ! disposed ) { OpenHashSet < Disposable > set = resources ; if ( set == null ) { set = new OpenHashSet < Disposable > ( disposables . length + 1 ) ; resources = set ; } for ( Disposable d : disposables ) { ObjectHelper . requireNonNull ( d , \"A Disposable in the disposables array is null\" ) ; set . add ( d ) ; } return true ; } } } for ( Disposable d : disposables ) { d . dispose ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes and disposes the given disposable if it is part of this container . [CODESPLIT] @ Override public boolean remove ( @ NonNull Disposable disposable ) { if ( delete ( disposable ) ) { disposable . dispose ( ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes ( but does not dispose ) the given disposable if it is part of this container . [CODESPLIT] @ Override public boolean delete ( @ NonNull Disposable disposable ) { ObjectHelper . requireNonNull ( disposable , \"disposables is null\" ) ; if ( disposed ) { return false ; } synchronized ( this ) { if ( disposed ) { return false ; } OpenHashSet < Disposable > set = resources ; if ( set == null || ! set . remove ( disposable ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically clears the container then disposes all the previously contained Disposables . [CODESPLIT] public void clear ( ) { if ( disposed ) { return ; } OpenHashSet < Disposable > set ; synchronized ( this ) { if ( disposed ) { return ; } set = resources ; resources = null ; } dispose ( set ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of currently held Disposables . [CODESPLIT] public int size ( ) { if ( disposed ) { return 0 ; } synchronized ( this ) { if ( disposed ) { return 0 ; } OpenHashSet < Disposable > set = resources ; return set != null ? set . size ( ) : 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the Subscriber methods on the current thread . <p > [CODESPLIT] public static < T > void subscribe ( Publisher < ? extends T > o , Subscriber < ? super T > subscriber ) { final BlockingQueue < Object > queue = new LinkedBlockingQueue < Object > ( ) ; BlockingSubscriber < T > bs = new BlockingSubscriber < T > ( queue ) ; o . subscribe ( bs ) ; try { for ( ; ; ) { if ( bs . isCancelled ( ) ) { break ; } Object v = queue . poll ( ) ; if ( v == null ) { if ( bs . isCancelled ( ) ) { break ; } BlockingHelper . verifyNonBlocking ( ) ; v = queue . take ( ) ; } if ( bs . isCancelled ( ) ) { break ; } if ( v == BlockingSubscriber . TERMINATED || NotificationLite . acceptFull ( v , subscriber ) ) { break ; } } } catch ( InterruptedException e ) { bs . cancel ( ) ; subscriber . onError ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the source observable to a terminal event ignoring any values and rethrowing any exception . [CODESPLIT] public static < T > void subscribe ( Publisher < ? extends T > o ) { BlockingIgnoringReceiver callback = new BlockingIgnoringReceiver ( ) ; LambdaSubscriber < T > ls = new LambdaSubscriber < T > ( Functions . emptyConsumer ( ) , callback , callback , Functions . REQUEST_MAX ) ; o . subscribe ( ls ) ; BlockingHelper . awaitForComplete ( callback , ls ) ; Throwable e = callback . error ; if ( e != null ) { throw ExceptionHelper . wrapOrThrow ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given actions on the current thread . [CODESPLIT] public static < T > void subscribe ( Publisher < ? extends T > o , final Consumer < ? super T > onNext , final Consumer < ? super Throwable > onError , final Action onComplete ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; subscribe ( o , new LambdaSubscriber < T > ( onNext , onError , onComplete , Functions . REQUEST_MAX ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given actions on the current thread . [CODESPLIT] public static < T > void subscribe ( Publisher < ? extends T > o , final Consumer < ? super T > onNext , final Consumer < ? super Throwable > onError , final Action onComplete , int bufferSize ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"number > 0 required\" ) ; subscribe ( o , new BoundedSubscriber < T > ( onNext , onError , onComplete , Functions . boundedConsumer ( bufferSize ) , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a resource to this ResourceObserver . [CODESPLIT] public final void add ( @ NonNull Disposable resource ) { ObjectHelper . requireNonNull ( resource , \"resource is null\" ) ; resources . add ( resource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to subscribe to a possibly Callable source s mapped ObservableSource . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T , R > boolean tryScalarXMapSubscribe ( ObservableSource < T > source , Observer < ? super R > observer , Function < ? super T , ? extends ObservableSource < ? extends R > > mapper ) { if ( source instanceof Callable ) { T t ; try { t = ( ( Callable < T > ) source ) . call ( ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptyDisposable . error ( ex , observer ) ; return true ; } if ( t == null ) { EmptyDisposable . complete ( observer ) ; return true ; } ObservableSource < ? extends R > r ; try { r = ObjectHelper . requireNonNull ( mapper . apply ( t ) , \"The mapper returned a null ObservableSource\" ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptyDisposable . error ( ex , observer ) ; return true ; } if ( r instanceof Callable ) { R u ; try { u = ( ( Callable < R > ) r ) . call ( ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; EmptyDisposable . error ( ex , observer ) ; return true ; } if ( u == null ) { EmptyDisposable . complete ( observer ) ; return true ; } ScalarDisposable < R > sd = new ScalarDisposable < R > ( observer , u ) ; observer . onSubscribe ( sd ) ; sd . run ( ) ; } else { r . subscribe ( observer ) ; } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a scalar value into an Observable and emits its values . [CODESPLIT] public static < T , U > Observable < U > scalarXMap ( T value , Function < ? super T , ? extends ObservableSource < ? extends U > > mapper ) { return RxJavaPlugins . onAssembly ( new ScalarXMapObservable < T , U > ( value , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] public static < T > MaybeObserver < T > create ( Observer < ? super T > downstream ) { return new MaybeToObservableObserver < T > ( downstream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps an { [CODESPLIT] @ NonNull @ Experimental public static Scheduler from ( @ NonNull Executor executor , boolean interruptibleWorker ) { return new ExecutorScheduler ( executor , interruptibleWorker ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shuts down the standard Schedulers . <p > The operation is idempotent and thread - safe . [CODESPLIT] public static void shutdown ( ) { computation ( ) . shutdown ( ) ; io ( ) . shutdown ( ) ; newThread ( ) . shutdown ( ) ; single ( ) . shutdown ( ) ; trampoline ( ) . shutdown ( ) ; SchedulerPoolFactory . shutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a non - null value to the list . <p > Don t add null to the list! [CODESPLIT] public void add ( T value ) { final int c = capacity ; int o = offset ; if ( o == c ) { Object [ ] next = new Object [ c + 1 ] ; tail [ c ] = next ; tail = next ; o = 0 ; } tail [ o ] = value ; offset = o + 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops over all elements of the array until a null element is encountered or the given predicate returns true . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void forEachWhile ( NonThrowingPredicate < ? super T > consumer ) { Object [ ] a = head ; final int c = capacity ; while ( a != null ) { for ( int i = 0 ; i < c ; i ++ ) { Object o = a [ i ] ; if ( o == null ) { break ; } if ( consumer . test ( ( T ) o ) ) { return ; } } a = ( Object [ ] ) a [ c ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interprets the contents as NotificationLite objects and calls the appropriate Subscriber method . [CODESPLIT] public < U > boolean accept ( Subscriber < ? super U > subscriber ) { Object [ ] a = head ; final int c = capacity ; while ( a != null ) { for ( int i = 0 ; i < c ; i ++ ) { Object o = a [ i ] ; if ( o == null ) { break ; } if ( NotificationLite . acceptFull ( o , subscriber ) ) { return true ; } } a = ( Object [ ] ) a [ c ] ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interprets the contents as NotificationLite objects and calls the appropriate Observer method . [CODESPLIT] public < U > boolean accept ( Observer < ? super U > observer ) { Object [ ] a = head ; final int c = capacity ; while ( a != null ) { for ( int i = 0 ; i < c ; i ++ ) { Object o = a [ i ] ; if ( o == null ) { break ; } if ( NotificationLite . acceptFull ( o , observer ) ) { return true ; } } a = ( Object [ ] ) a [ c ] ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops over all elements of the array until a null element is encountered or the given predicate returns true . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < S > void forEachWhile ( S state , BiPredicate < ? super S , ? super T > consumer ) throws Exception { Object [ ] a = head ; final int c = capacity ; for ( ; ; ) { for ( int i = 0 ; i < c ; i ++ ) { Object o = a [ i ] ; if ( o == null ) { return ; } if ( consumer . test ( state , ( T ) o ) ) { return ; } } a = ( Object [ ] ) a [ c ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs multiple SingleSources and signals the events of the first one that signals ( disposing the rest ) . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . amb . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < T > amb ( final Iterable < ? extends SingleSource < ? extends T > > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleAmb < T > ( null , sources ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs multiple SingleSources and signals the events of the first one that signals ( disposing the rest ) . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . ambArray . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Single < T > ambArray ( final SingleSource < ? extends T > ... sources ) { if ( sources . length == 0 ) { return error ( SingleInternalHelper . < T > emptyThrower ( ) ) ; } if ( sources . length == 1 ) { return wrap ( ( SingleSource < T > ) sources [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new SingleAmb < T > ( sources , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenate the single values in a non - overlapping fashion of the SingleSources provided in an array . <p > <img width = 640 height = 319 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . concatArray . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public static < T > Flowable < T > concatArray ( SingleSource < ? extends T > ... sources ) { return RxJavaPlugins . onAssembly ( new FlowableConcatMap ( Flowable . fromArray ( sources ) , SingleInternalHelper . toFlowable ( ) , 2 , ErrorMode . BOUNDARY ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < T > defer ( final Callable < ? extends SingleSource < ? extends T > > singleSupplier ) { ObjectHelper . requireNonNull ( singleSupplier , \"singleSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDefer < T > ( singleSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals a Throwable returned by the callback function for each individual SingleObserver . <p > <img width = 640 height = 283 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . error . c . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < T > error ( final Callable < ? extends Throwable > errorSupplier ) { ObjectHelper . requireNonNull ( errorSupplier , \"errorSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleError < T > ( errorSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Single } that invokes passed function and emits its result for each new SingleObserver that subscribes . <p > Allows you to defer execution of passed function until SingleObserver subscribes to the { @link Single } . It makes passed function lazy . Result of the function invocation will be emitted by the { @link Single } . <p > <img width = 640 height = 467 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . fromCallable . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromCallable } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the { @link Callable } throws an exception the respective { @link Throwable } is delivered to the downstream via { @link SingleObserver#onError ( Throwable ) } except when the downstream has disposed this { @code Single } source . In this latter case the { @code Throwable } is delivered to the global error handler via { @link RxJavaPlugins#onError ( Throwable ) } as an { @link io . reactivex . exceptions . UndeliverableException UndeliverableException } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < T > fromCallable ( final Callable < ? extends T > callable ) { ObjectHelper . requireNonNull ( callable , \"callable is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleFromCallable < T > ( callable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link Future } into a { @code Single } . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . from . Future . png alt = > <p > You can convert any object that supports the { @link Future } interface into a Single that emits the return value of the { @link Future#get } method of that object by passing the object into the { @code from } method . <p > <em > Important note : < / em > This Single is blocking ; you cannot dispose it . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromFuture } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < T > fromFuture ( Future < ? extends T > future ) { return toSingle ( Flowable . < T > fromFuture ( future ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link Future } into a { @code Single } with a timeout on the Future . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . from . Future . png alt = > <p > You can convert any object that supports the { @link Future } interface into a { @code Single } that emits the return value of the { @link Future#get } method of that object by passing the object into the { @code from } method . <p > <em > Important note : < / em > This { @code Single } is blocking ; you cannot dispose it . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromFuture } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < T > fromFuture ( Future < ? extends T > future , long timeout , TimeUnit unit ) { return toSingle ( Flowable . < T > fromFuture ( future , timeout , unit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link Future } into a { @code Single } with a timeout on the Future . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . from . Future . png alt = > <p > You can convert any object that supports the { @link Future } interface into a { @code Single } that emits the return value of the { @link Future#get } method of that object by passing the object into the { @code from } method . <p > <em > Important note : < / em > This { @code Single } is blocking ; you cannot dispose it . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify the { @link Scheduler } where the blocking wait will happen . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static < T > Single < T > fromFuture ( Future < ? extends T > future , long timeout , TimeUnit unit , Scheduler scheduler ) { return toSingle ( Flowable . < T > fromFuture ( future , timeout , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens a { @code Single } that emits a { @code Single } into a single { @code Single } that emits the item emitted by the nested { @code Single } without any transformation . <p > <img width = 640 height = 412 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . merge . oo . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code merge } does not operate by default on a particular { @link Scheduler } . < / dd > <dd > The resulting { @code Single } emits the outer source s or the inner { @code SingleSource } s { @code Throwable } as is . Unlike the other { @code merge () } operators this operator won t and can t produce a { @code CompositeException } because there is only one possibility for the outer or the inner { @code SingleSource } to emit an { @code onError } signal . Therefore there is no need for a { @code mergeDelayError ( SingleSource<SingleSource<T >> ) } operator . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public static < T > Single < T > merge ( SingleSource < ? extends SingleSource < ? extends T > > source ) { ObjectHelper . requireNonNull ( source , \"source is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleFlatMap < SingleSource < ? extends T > , T > ( source , ( Function ) Functions . identity ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges a Flowable sequence of SingleSource instances into a single Flowable sequence running all SingleSources at once and delaying any error ( s ) until all sources succeed or fail . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public static < T > Flowable < T > mergeDelayError ( Publisher < ? extends SingleSource < ? extends T > > sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableFlatMapPublisher ( sources , SingleInternalHelper . toFlowable ( ) , true , Integer . MAX_VALUE , Flowable . bufferSize ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a singleton instance of a never - signalling Single ( only calls onSubscribe ) . <p > <img width = 640 height = 244 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . never . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Single < T > never ( ) { return RxJavaPlugins . onAssembly ( ( Single < T > ) SingleNever . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals success with 0L value after the given delay for each SingleObserver . <p > <img width = 640 height = 292 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . timer . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > you specify the { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Single < Long > timer ( final long delay , final TimeUnit unit , final Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleTimer ( delay , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<strong > Advanced use only : < / strong > creates a Single instance without any safeguards by using a callback that is called with a SingleObserver . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < T > unsafeCreate ( SingleSource < T > onSubscribe ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; if ( onSubscribe instanceof Single ) { throw new IllegalArgumentException ( \"unsafeCreate(Single) should be upgraded\" ) ; } return RxJavaPlugins . onAssembly ( new SingleFromUnsafeSource < T > ( onSubscribe ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows using and disposing a resource while running a SingleSource instance generated from that resource ( similar to a try - with - resources ) . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , U > Single < T > using ( Callable < U > resourceSupplier , Function < ? super U , ? extends SingleSource < ? extends T > > singleFunction , Consumer < ? super U > disposer ) { return using ( resourceSupplier , singleFunction , disposer , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified converter function during assembly time and returns its resulting value . <p > <img width = 640 height = 553 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . as . png alt = > <p > This allows fluent conversion to any other type . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > R as ( @ NonNull SingleConverter < T , ? extends R > converter ) { return ObjectHelper . requireNonNull ( converter , \"converter is null\" ) . apply ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides the identity of the current Single including the Disposable that is sent to the downstream via { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > hide ( ) { return RxJavaPlugins . onAssembly ( new SingleHide < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a Single by applying a particular Transformer function to it . <p > <img width = 640 height = 612 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . compose . png alt = > <p > This method operates on the Single itself whereas { @link #lift } operates on the Single s SingleObservers . <p > If the operator you are creating is designed to act on the individual item emitted by a Single use { @link #lift } . If your operator is designed to transform the source Single as a whole ( for instance by applying a particular set of existing RxJava operators to it ) use { @code compose } . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code compose } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > compose ( SingleTransformer < ? super T , ? extends R > transformer ) { return wrap ( ( ( SingleTransformer < T , R > ) ObjectHelper . requireNonNull ( transformer , \"transformer is null\" ) ) . apply ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the success value or exception from the current Single and replays it to late SingleObservers . <p > The returned Single subscribes to the current Single when the first SingleObserver subscribes . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code cache } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > cache ( ) { return RxJavaPlugins . onAssembly ( new SingleCache < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the item emitted by the source Single then the item emitted by the specified Single . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . concatWith . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { @code Flowable } honors the backpressure of the downstream consumer . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concatWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > concatWith ( SingleSource < ? extends T > other ) { return concat ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delays the emission of the success signal from the current Single by the specified amount . An error signal will not be delayed . <p > <img width = 640 height = 457 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . delay . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code delay } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Single < T > delay ( long time , TimeUnit unit ) { return delay ( time , unit , Schedulers . computation ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delays the emission of the success signal from the current Single by the specified amount . An error signal will not be delayed . <p > <img width = 640 height = 457 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . delay . s . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > you specify the { @link Scheduler } where the non - blocking wait and emission happens< / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Single < T > delay ( final long time , final TimeUnit unit , final Scheduler scheduler ) { return delay ( time , unit , scheduler , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delays the emission of the success or error signal from the current Single by the specified amount . <p > <img width = 640 height = 457 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . delay . se . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > you specify the { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Single < T > delay ( final long time , final TimeUnit unit , final Scheduler scheduler , boolean delayError ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDelay < T > ( this , time , unit , scheduler , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delays the actual subscription to the current Single until the given other CompletableSource completes . <p > If the delaying source signals an error that error is re - emitted and no subscription to the current Single happens . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > delaySubscription ( CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDelayWithCompletable < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delays the actual subscription to the current Single until the given time delay elapsed . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Single < T > delaySubscription ( long time , TimeUnit unit ) { return delaySubscription ( time , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delays the actual subscription to the current Single until the given time delay elapsed . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Single < T > delaySubscription ( long time , TimeUnit unit , Scheduler scheduler ) { return delaySubscription ( Observable . timer ( time , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) @ Experimental public final < R > Maybe < R > dematerialize ( Function < ? super T , Notification < R > > selector ) { ObjectHelper . requireNonNull ( selector , \"selector is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDematerialize < T , R > ( this , selector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified consumer with the success item after this item has been emitted to the downstream . <p > <img width = 640 height = 460 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . doAfterSuccess . png alt = > <p > Note that the { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doAfterSuccess ( Consumer < ? super T > onAfterSuccess ) { ObjectHelper . requireNonNull ( onAfterSuccess , \"onAfterSuccess is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoAfterSuccess < T > ( this , onAfterSuccess ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an { @link Action } to be called after this Single invokes either onSuccess or onError . <p > <img width = 640 height = 460 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . doAfterTerminate . png alt = > <p > Note that the { @code doAfterTerminate } action is shared between subscriptions and as such should be thread - safe . < / p > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doAfterTerminate ( Action onAfterTerminate ) { ObjectHelper . requireNonNull ( onAfterTerminate , \"onAfterTerminate is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoAfterTerminate < T > ( this , onAfterTerminate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified action after this Single signals onSuccess or onError or gets disposed by the downstream . <p > In case of a race between a terminal event and a dispose call the provided { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doFinally ( Action onFinally ) { ObjectHelper . requireNonNull ( onFinally , \"onFinally is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoFinally < T > ( this , onFinally ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the shared consumer with the Disposable sent through the onSubscribe for each SingleObserver that subscribes to the current Single . <p > <img width = 640 height = 347 src = https : // raw . githubusercontent . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . doOnSubscribe . png alt = > < / p > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doOnSubscribe ( final Consumer < ? super Disposable > onSubscribe ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoOnSubscribe < T > ( this , onSubscribe ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single instance that calls the given onTerminate callback just before this Single completes normally or with an exception . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnTerminate . png alt = > <p > This differs from { [CODESPLIT] @ Experimental @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doOnTerminate ( final Action onTerminate ) { ObjectHelper . requireNonNull ( onTerminate , \"onTerminate is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoOnTerminate < T > ( this , onTerminate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the shared consumer with the success value sent via onSuccess for each SingleObserver that subscribes to the current Single . <p > <img width = 640 height = 347 src = https : // raw . githubusercontent . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . doOnSuccess . 2 . png alt = > < / p > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doOnSuccess ( final Consumer < ? super T > onSuccess ) { ObjectHelper . requireNonNull ( onSuccess , \"onSuccess is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoOnSuccess < T > ( this , onSuccess ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the shared consumer with the error sent via onError for each SingleObserver that subscribes to the current Single . <p > <img width = 640 height = 349 src = https : // raw . githubusercontent . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . doOnError . 2 . png alt = > < / p > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doOnError ( final Consumer < ? super Throwable > onError ) { ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoOnError < T > ( this , onError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the shared { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > doOnDispose ( final Action onDispose ) { ObjectHelper . requireNonNull ( onDispose , \"onDispose is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleDoOnDispose < T > ( this , onDispose ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that is based on applying a specified function to the item emitted by the source Single where that function returns a SingleSource . <p > <img width = 640 height = 300 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . flatMap . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > flatMap ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleFlatMap < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that is based on applying a specified function to the item emitted by the source Single where that function returns a MaybeSource . <p > <img width = 640 height = 191 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . flatMapMaybe . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMapMaybe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Maybe < R > flatMapMaybe ( final Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleFlatMapMaybe < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Observable that is based on applying a specified function to the item emitted by the source Single where that function returns an ObservableSource . <p > <img width = 640 height = 300 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . flatMapObservable . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMapObservable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Observable < R > flatMapObservable ( Function < ? super T , ? extends ObservableSource < ? extends R > > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleFlatMapObservable < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<strong > This method requires advanced knowledge about building operators please consider other standard composition methods first ; < / strong > Returns a { @code Single } which when subscribed to invokes the { @link SingleOperator#apply ( SingleObserver ) apply ( SingleObserver ) } method of the provided { @link SingleOperator } for each individual downstream { @link Single } and allows the insertion of a custom operator by accessing the downstream s { @link SingleObserver } during this subscription phase and providing a new { @code SingleObserver } containing the custom operator s intended business logic that will be used in the subscription process going further upstream . <p > Generally such a new { @code SingleObserver } will wrap the downstream s { @code SingleObserver } and forwards the { @code onSuccess } and { @code onError } events from the upstream directly or according to the emission pattern the custom operator s business logic requires . In addition such operator can intercept the flow control calls of { @code dispose } and { @code isDisposed } that would have traveled upstream and perform additional actions depending on the same business logic requirements . <p > Example : <pre > <code > // Step 1 : Create the consumer type that will be returned by the SingleOperator . apply () : [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > lift ( final SingleOperator < ? extends R , ? super T > lift ) { ObjectHelper . requireNonNull ( lift , \"lift is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleLift < T , R > ( this , lift ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that applies a specified function to the item emitted by the source Single and emits the result of this function application . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . map . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code map } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > map ( Function < ? super T , ? extends R > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleMap < T , R > ( this , mapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the signal types of this Single into a { [CODESPLIT] @ Experimental @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Notification < T > > materialize ( ) { return RxJavaPlugins . onAssembly ( new SingleMaterialize < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals true if the current Single signals a success value that is Object - equals with the value provided . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > contains ( Object value ) { return contains ( value , ObjectHelper . equalsPredicate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens this and another Single into a single Flowable without any transformation . <p > <img width = 640 height = 415 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . mergeWith . png alt = > <p > You can combine items emitted by multiple Singles so that they appear as a single Flowable by using the { @code mergeWith } method . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { @code Flowable } honors the backpressure of the downstream consumer . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > mergeWith ( SingleSource < ? extends T > other ) { return merge ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies a Single to emit its item ( or notify of its error ) on a specified { @link Scheduler } asynchronously . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . observeOn . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > you specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Single < T > observeOn ( final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleObserveOn < T > ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Single to emit an item ( returned by a specified function ) rather than invoking { @link SingleObserver#onError onError } if it encounters an error . <p > <img width = 640 height = 451 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . onErrorReturn . png alt = > <p > By default when a Single encounters an error that prevents it from emitting the expected item to its subscriber the Single invokes its subscriber s { @link SingleObserver#onError } method and then quits without invoking any more of its subscriber s methods . The { @code onErrorReturn } method changes this behavior . If you pass a function ( { @code resumeFunction } ) to a Single s { @code onErrorReturn } method if the original Single encounters an error instead of invoking its subscriber s { @link SingleObserver#onError } method it will instead emit the return value of { @code resumeFunction } . <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorReturn } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > onErrorReturn ( final Function < Throwable , ? extends T > resumeFunction ) { ObjectHelper . requireNonNull ( resumeFunction , \"resumeFunction is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleOnErrorReturn < T > ( this , resumeFunction , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Nulls out references to the upstream producer and downstream SingleObserver if the sequence is terminated or downstream calls dispose () . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > onTerminateDetach ( ) { return RxJavaPlugins . onAssembly ( new SingleDetach < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repeatedly re - subscribes to the current Single and emits each success value . <p > <img width = 640 height = 457 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . repeat . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > repeat ( ) { return toFlowable ( ) . repeat ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repeatedly re - subscribes to the current Single indefinitely if it fails with an onError . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > retry ( ) { return toSingle ( toFlowable ( ) . retry ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - subscribe to the current Single if the given predicate returns true when the Single fails with an onError . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > retry ( BiPredicate < ? super Integer , ? super Throwable > predicate ) { return toSingle ( toFlowable ( ) . retry ( predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repeatedly re - subscribe at most times or until the predicate returns false whichever happens first if it fails with an onError . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > retry ( long times , Predicate < ? super Throwable > predicate ) { return toSingle ( toFlowable ( ) . retry ( times , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - subscribes to the current Single if and when the Publisher returned by the handler function signals a value . <p > If the Publisher signals an onComplete the resulting Single will signal a NoSuchElementException . <p > Note that the inner { @code Publisher } returned by the handler function should signal either { @code onNext } { @code onError } or { @code onComplete } in response to the received { @code Throwable } to indicate the operator should retry or terminate . If the upstream to the operator is asynchronous signalling onNext followed by onComplete immediately may result in the sequence to be completed immediately . Similarly if this inner { @code Publisher } signals { @code onError } or { @code onComplete } while the upstream is active the sequence is terminated with the same signal immediately . <p > The following example demonstrates how to retry an asynchronous source with a delay : <pre > <code > Single . timer ( 1 TimeUnit . SECONDS ) . doOnSubscribe ( s - &gt ; System . out . println ( subscribing )) . map ( v - &gt ; { throw new RuntimeException () ; } ) . retryWhen ( errors - &gt ; { AtomicInteger counter = new AtomicInteger () ; return errors . takeWhile ( e - &gt ; counter . getAndIncrement () ! = 3 ) . flatMap ( e - &gt ; { System . out . println ( delay retry by + counter . get () + second ( s ) ) ; return Flowable . timer ( counter . get () TimeUnit . SECONDS ) ; } ) ; } ) . blockingGet () ; < / code > < / pre > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retryWhen } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > retryWhen ( Function < ? super Flowable < Throwable > , ? extends Publisher < ? > > handler ) { return toSingle ( toFlowable ( ) . retryWhen ( handler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to a Single and provides a callback to handle the item it emits . <p > If the Single emits an error it is wrapped into an { @link io . reactivex . exceptions . OnErrorNotImplementedException OnErrorNotImplementedException } and routed to the RxJavaPlugins . onError handler . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( Consumer < ? super T > onSuccess ) { return subscribe ( onSuccess , Functions . ON_ERROR_MISSING ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to a Single and provides callbacks to handle the item it emits or any error notification it issues . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( final Consumer < ? super T > onSuccess , final Consumer < ? super Throwable > onError ) { ObjectHelper . requireNonNull ( onSuccess , \"onSuccess is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ConsumerSingleObserver < T > observer = new ConsumerSingleObserver < T > ( onSuccess , onError ) ; subscribe ( observer ) ; return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes a given SingleObserver ( subclass ) to this Single and returns the given SingleObserver as is . <p > Usage example : <pre > <code > Single&lt ; Integer&gt ; source = Single . just ( 1 ) ; CompositeDisposable composite = new CompositeDisposable () ; [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < E extends SingleObserver < ? super T > > E subscribeWith ( E observer ) { subscribe ( observer ) ; return observer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously subscribes subscribers to this Single on the specified { @link Scheduler } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . subscribeOn . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Single < T > subscribeOn ( final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleSubscribeOn < T > ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the item emitted by the source Single until a Completable terminates . Upon termination of { @code other } this will emit a { @link CancellationException } rather than go to { @link SingleObserver#onSuccess ( Object ) } . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeUntil . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code takeUntil } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > takeUntil ( final CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return takeUntil ( new CompletableToFlowable < T > ( other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals a TimeoutException if the current Single doesn t signal a success value within the specified timeout window . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Single < T > timeout ( long timeout , TimeUnit unit ) { return timeout0 ( timeout , unit , Schedulers . computation ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals a TimeoutException if the current Single doesn t signal a success value within the specified timeout window . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Single < T > timeout ( long timeout , TimeUnit unit , Scheduler scheduler ) { return timeout0 ( timeout , unit , scheduler , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Completable } that discards result of the { @link Single } and calls { @code onComplete } when this source { @link Single } calls { @code onSuccess } . Error terminal event is propagated . <p > <img width = 640 height = 436 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . toCompletable . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toCompletable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ Deprecated public final Completable toCompletable ( ) { return RxJavaPlugins . onAssembly ( new CompletableFromSingle < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Future } representing the single value emitted by this { @code Single } . <p > <img width = 640 height = 467 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / Single . toFuture . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toFuture } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Future < T > toFuture ( ) { return subscribeWith ( new FutureSingleObserver < T > ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single which makes sure when a SingleObserver disposes the Disposable that call is propagated up on the specified scheduler . <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Single < T > unsubscribeOn ( final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new SingleUnsubscribeOn < T > ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the result of applying a specified function to the pair of items emitted by the source Single and another specified Single . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Single . zip . png alt = > <dl > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code zipWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Single < R > zipWith ( SingleSource < U > other , BiFunction < ? super T , ? super U , ? extends R > zipper ) { return zip ( this , other , zipper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a fresh instance with the default Flowable . bufferSize () prefetch amount and no refCount - behavior . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > MulticastProcessor < T > create ( ) { return new MulticastProcessor < T > ( bufferSize ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a fresh instance with the default Flowable . bufferSize () prefetch amount and the optional refCount - behavior . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > MulticastProcessor < T > create ( boolean refCount ) { return new MulticastProcessor < T > ( bufferSize ( ) , refCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes this Processor by setting an upstream Subscription that ignores request amounts uses a fixed buffer and allows using the onXXX and offer methods afterwards . [CODESPLIT] public void start ( ) { if ( SubscriptionHelper . setOnce ( upstream , EmptySubscription . INSTANCE ) ) { queue = new SpscArrayQueue < T > ( bufferSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes this Processor by setting an upstream Subscription that ignores request amounts uses an unbounded buffer and allows using the onXXX and offer methods afterwards . [CODESPLIT] public void startUnbounded ( ) { if ( SubscriptionHelper . setOnce ( upstream , EmptySubscription . INSTANCE ) ) { queue = new SpscLinkedArrayQueue < T > ( bufferSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to offer an item into the internal queue and returns false if the queue is full . [CODESPLIT] public boolean offer ( T t ) { if ( once . get ( ) ) { return false ; } ObjectHelper . requireNonNull ( t , \"offer called with null. Null values are generally not allowed in 2.x operators and sources.\" ) ; if ( fusionMode == QueueSubscription . NONE ) { if ( queue . offer ( t ) ) { drain ( ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean offer ( final T e ) { if ( null == e ) { throw new NullPointerException ( \"Null is not a valid element\" ) ; } // local load of field to avoid repeated loads after volatile reads final AtomicReferenceArray < Object > buffer = producerBuffer ; final long index = lpProducerIndex ( ) ; final int mask = producerMask ; final int offset = calcWrappedOffset ( index , mask ) ; if ( index < producerLookAhead ) { return writeToQueue ( buffer , e , index , offset ) ; } else { final int lookAheadStep = producerLookAheadStep ; // go around the buffer or resize if full (unless we hit max capacity) int lookAheadElementOffset = calcWrappedOffset ( index + lookAheadStep , mask ) ; if ( null == lvElement ( buffer , lookAheadElementOffset ) ) { // LoadLoad producerLookAhead = index + lookAheadStep - 1 ; // joy, there's plenty of room return writeToQueue ( buffer , e , index , offset ) ; } else if ( null == lvElement ( buffer , calcWrappedOffset ( index + 1 , mask ) ) ) { // buffer is not full return writeToQueue ( buffer , e , index , offset ) ; } else { resize ( buffer , index , offset , e , mask ) ; // add a buffer and link old to new return true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Nullable @ SuppressWarnings ( \"unchecked\" ) @ Override public T poll ( ) { // local load of field to avoid repeated loads after volatile reads final AtomicReferenceArray < Object > buffer = consumerBuffer ; final long index = lpConsumerIndex ( ) ; final int mask = consumerMask ; final int offset = calcWrappedOffset ( index , mask ) ; final Object e = lvElement ( buffer , offset ) ; // LoadLoad boolean isNextBuffer = e == HAS_NEXT ; if ( null != e && ! isNextBuffer ) { soElement ( buffer , offset , null ) ; // StoreStore soConsumerIndex ( index + 1 ) ; // this ensures correctness on 32bit platforms return ( T ) e ; } else if ( isNextBuffer ) { return newBufferPoll ( lvNextBufferAndUnlink ( buffer , mask + 1 ) , index , mask ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Offer two elements at the same time . <p > Don t use the regular offer () with this at all! [CODESPLIT] @ Override public boolean offer ( T first , T second ) { final AtomicReferenceArray < Object > buffer = producerBuffer ; final long p = lvProducerIndex ( ) ; final int m = producerMask ; int pi = calcWrappedOffset ( p + 2 , m ) ; if ( null == lvElement ( buffer , pi ) ) { pi = calcWrappedOffset ( p , m ) ; soElement ( buffer , pi + 1 , second ) ; soElement ( buffer , pi , first ) ; soProducerIndex ( p + 2 ) ; } else { final int capacity = buffer . length ( ) ; final AtomicReferenceArray < Object > newBuffer = new AtomicReferenceArray < Object > ( capacity ) ; producerBuffer = newBuffer ; pi = calcWrappedOffset ( p , m ) ; soElement ( newBuffer , pi + 1 , second ) ; // StoreStore soElement ( newBuffer , pi , first ) ; soNext ( buffer , newBuffer ) ; soElement ( buffer , pi , HAS_NEXT ) ; // new buffer is visible after element is soProducerIndex ( p + 2 ) ; // this ensures correctness on 32bit platforms } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the currently contained Disposable or null if this container is empty . [CODESPLIT] @ Nullable public Disposable get ( ) { Disposable d = resource . get ( ) ; if ( d == DisposableHelper . DISPOSED ) { return Disposables . disposed ( ) ; } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a OperatorPublish instance to publish values of the given source observable . [CODESPLIT] public static < T > ConnectableObservable < T > create ( ObservableSource < T > source ) { // the current connection to source needs to be shared between the operator and its onSubscribe call final AtomicReference < PublishObserver < T > > curr = new AtomicReference < PublishObserver < T > > ( ) ; ObservableSource < T > onSubscribe = new PublishSource < T > ( curr ) ; return RxJavaPlugins . onAssembly ( new ObservablePublish < T > ( onSubscribe , source , curr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete the target with a single value or indicate there is a value available in fusion mode . [CODESPLIT] public final void complete ( T value ) { int state = get ( ) ; if ( ( state & ( FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED ) ) != 0 ) { return ; } Observer < ? super T > a = downstream ; if ( state == FUSED_EMPTY ) { this . value = value ; lazySet ( FUSED_READY ) ; a . onNext ( null ) ; } else { lazySet ( TERMINATED ) ; a . onNext ( value ) ; } if ( get ( ) != DISPOSED ) { a . onComplete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete the target with an error signal . [CODESPLIT] public final void error ( Throwable t ) { int state = get ( ) ; if ( ( state & ( FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED ) ) != 0 ) { RxJavaPlugins . onError ( t ) ; return ; } lazySet ( TERMINATED ) ; downstream . onError ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete the target without any value . [CODESPLIT] public final void complete ( ) { int state = get ( ) ; if ( ( state & ( FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED ) ) != 0 ) { return ; } lazySet ( TERMINATED ) ; downstream . onComplete ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items emitted by each of the Publishers emitted by the source Publisher one after the other without interleaving them . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concat . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . Both the outer and inner { @code Publisher } sources are expected to honor backpressure as well . If the outer violates this a { @code MissingBackpressureException } is signaled . If any of the inner { @code Publisher } s violates this it <em > may< / em > throw an { @code IllegalStateException } when an inner { @code Publisher } completes . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code concat } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concat ( Publisher < ? extends Publisher < ? extends T > > sources , int prefetch ) { return fromPublisher ( sources ) . concatMap ( ( Function ) Functions . identity ( ) , prefetch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a variable number of Publisher sources . <p > Note : named this way because of overload conflict with concat ( Publisher&lt ; Publisher&gt ; ) . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / concat . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concatArray ( Publisher < ? extends T > ... sources ) { if ( sources . length == 0 ) { return empty ( ) ; } else if ( sources . length == 1 ) { return fromPublisher ( sources [ 0 ] ) ; } return RxJavaPlugins . onAssembly ( new FlowableConcatArray < T > ( sources , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates an array of Publishers eagerly into a single stream of values . <p > <img width = 640 height = 406 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / Flowable . concatArrayEager . nn . png alt = > <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source Publishers . The operator buffers the values emitted by these Publishers and then drains them in order each one after the previous one completes . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) public static < T > Flowable < T > concatArrayEager ( int maxConcurrency , int prefetch , Publisher < ? extends T > ... sources ) { ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new FlowableConcatMapEager ( new FlowableFromArray ( sources ) , Functions . identity ( ) , maxConcurrency , prefetch , ErrorMode . IMMEDIATE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates an array of { [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public static < T > Flowable < T > concatArrayEagerDelayError ( int maxConcurrency , int prefetch , Publisher < ? extends T > ... sources ) { return fromArray ( sources ) . concatMapEagerDelayError ( ( Function ) Functions . identity ( ) , maxConcurrency , prefetch , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the Publisher sequence of Publishers into a single sequence by subscribing to each inner Publisher one after the other one at a time and delays any errors till the all inner and the outer Publishers terminate . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concatDelayError ( Publisher < ? extends Publisher < ? extends T > > sources ) { return concatDelayError ( sources , bufferSize ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the Publisher sequence of Publishers into a single sequence by subscribing to each inner Publisher one after the other one at a time and delays any errors till the all inner and the outer Publishers terminate . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > concatDelayError ( Publisher < ? extends Publisher < ? extends T > > sources , int prefetch , boolean tillTheEnd ) { return fromPublisher ( sources ) . concatMapDelayError ( ( Function ) Functions . identity ( ) , prefetch , tillTheEnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an API ( via a cold Flowable ) that bridges the reactive world with the callback - style generally non - backpressured world . <p > Example : <pre > <code > Flowable . &lt ; Event&gt ; create ( emitter - &gt ; { Callback listener = new Callback () { &#64 ; Override public void onEvent ( Event e ) { emitter . onNext ( e ) ; if ( e . isLast () ) { emitter . onComplete () ; } } [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > create ( FlowableOnSubscribe < T > source , BackpressureStrategy mode ) { ObjectHelper . requireNonNull ( source , \"source is null\" ) ; ObjectHelper . requireNonNull ( mode , \"mode is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableCreate < T > ( source , mode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits no items to the { @link Subscriber } and immediately invokes its { @link Subscriber#onComplete onComplete } method . <p > <img width = 640 height = 190 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / empty . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This source doesn t produce any elements and effectively ignores downstream backpressure . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code empty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Flowable < T > empty ( ) { return RxJavaPlugins . onAssembly ( ( Flowable < T > ) FlowableEmpty . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that invokes a { @link Subscriber } s { @link Subscriber#onError onError } method when the Subscriber subscribes to it . <p > <img width = 640 height = 190 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / error . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This source doesn t produce any elements and effectively ignores downstream backpressure . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code error } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > error ( Callable < ? extends Throwable > supplier ) { ObjectHelper . requireNonNull ( supplier , \"supplier is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableError < T > ( supplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an { @link Iterable } sequence into a Publisher that emits the items in the sequence . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / from . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and iterates the given { @code iterable } on demand ( i . e . when requested ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code fromIterable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > fromIterable ( Iterable < ? extends T > source ) { ObjectHelper . requireNonNull ( source , \"source is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableFromIterable < T > ( source ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a cold synchronous stateful and backpressure - aware generator of values . <p > Note that the { @link Emitter#onNext } { @link Emitter#onError } and { @link Emitter#onComplete } methods provided to the function via the { @link Emitter } instance should be called synchronously never concurrently and only while the function body is executing . Calling them from multiple threads or outside the function call is not supported and leads to an undefined behavior . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code generate } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , S > Flowable < T > generate ( Callable < S > initialState , BiFunction < S , Emitter < T > , S > generator ) { return generate ( initialState , generator , Functions . emptyConsumer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits a { @code 0L } after the { @code initialDelay } and ever - increasing numbers after each { @code period } of time thereafter on a specified { @link Scheduler } . <p > <img width = 640 height = 200 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timer . ps . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator generates values based on time and ignores downstream backpressure which may lead to { @code MissingBackpressureException } at some point in the chain . Consumers should consider applying one of the { @code onBackpressureXXX } operators as well . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Flowable < Long > interval ( long initialDelay , long period , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableInterval ( Math . max ( 0L , initialDelay ) , Math . max ( 0L , period ) , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits a sequential number every specified interval of time . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / interval . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator signals a { @code MissingBackpressureException } if the downstream is not ready to receive the next value . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code interval } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public static Flowable < Long > interval ( long period , TimeUnit unit ) { return interval ( period , period , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits a sequential number every specified interval of time on a specified Scheduler . <p > <img width = 640 height = 200 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / interval . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator generates values based on time and ignores downstream backpressure which may lead to { @code MissingBackpressureException } at some point in the chain . Consumers should consider applying one of the { @code onBackpressureXXX } operators as well . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Flowable < Long > interval ( long period , TimeUnit unit , Scheduler scheduler ) { return interval ( period , period , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals a range of long values the first after some initial delay and the rest periodically after . <p > The sequence completes immediately after the last value ( start + count - 1 ) has been reached . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator signals a { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public static Flowable < Long > intervalRange ( long start , long count , long initialDelay , long period , TimeUnit unit ) { return intervalRange ( start , count , initialDelay , period , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals a range of long values the first after some initial delay and the rest periodically after . <p > The sequence completes immediately after the last value ( start + count - 1 ) has been reached . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator signals a { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public static Flowable < Long > intervalRange ( long start , long count , long initialDelay , long period , TimeUnit unit , Scheduler scheduler ) { if ( count < 0L ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } if ( count == 0L ) { return Flowable . < Long > empty ( ) . delay ( initialDelay , unit , scheduler ) ; } long end = start + ( count - 1 ) ; if ( start > 0 && end < 0 ) { throw new IllegalArgumentException ( \"Overflow! start + count is bigger than Long.MAX_VALUE\" ) ; } ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableIntervalRange ( start , end , Math . max ( 0L , initialDelay ) , Math . max ( 0L , period ) , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that signals the given ( constant reference ) item and then completes . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / just . png alt = > <p > Note that the item is taken and re - emitted as is and not computed by any means by { @code just } . Use { @link #fromCallable ( Callable ) } to generate a single item on demand ( when { @code Subscriber } s subscribe to it ) . <p > See the multi - parameter overloads of { @code just } to emit more than one ( constant reference ) items one after the other . Use { @link #fromArray ( Object ... ) } to emit an arbitrary number of items that are known upfront . <p > To emit the items of an { @link Iterable } sequence ( such as a { @link java . util . List } ) use { @link #fromIterable ( Iterable ) } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code just } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > just ( T item ) { ObjectHelper . requireNonNull ( item , \"item is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableJust < T > ( item ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an Iterable of Publishers into one Publisher without any transformation while limiting the number of concurrent subscriptions to these Publishers . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > You can combine the items emitted by multiple Publishers so that they appear as a single Publisher by using the { @code merge } method . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The source { @code Publisher } s are expected to honor backpressure ; if violated the operator <em > may< / em > signal { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeArray } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If any of the source { @code Publisher } s signal a { @code Throwable } via { @code onError } the resulting { @code Flowable } terminates with that { @code Throwable } and all other source { @code Publisher } s are canceled . If more than one { @code Publisher } signals an error the resulting { @code Flowable } may terminate with the first one s error or depending on the concurrency of the sources may terminate with a { @code CompositeException } containing two or more of the various error signals . { @code Throwable } s that didn t make into the composite will be sent ( individually ) to the global error handler via { @link RxJavaPlugins#onError ( Throwable ) } method as { @code UndeliverableException } errors . Similarly { @code Throwable } s signaled by source ( s ) after the returned { @code Flowable } has been canceled or terminated with a ( composite ) error will be sent to the same global error handler . Use { @link #mergeArrayDelayError ( int int Publisher [] ) } to merge sources and terminate only when all source { @code Publisher } s have completed or failed with an error . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > mergeArray ( int maxConcurrency , int bufferSize , Publisher < ? extends T > ... sources ) { return fromArray ( sources ) . flatMap ( ( Function ) Functions . identity ( ) , false , maxConcurrency , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens four Publishers into a single Publisher without any transformation . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > You can combine items emitted by multiple Publishers so that they appear as a single Publisher by using the { @code merge } method . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The source { @code Publisher } s are expected to honor backpressure ; if violated the operator <em > may< / em > signal { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code merge } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If any of the source { @code Publisher } s signal a { @code Throwable } via { @code onError } the resulting { @code Flowable } terminates with that { @code Throwable } and all other source { @code Publisher } s are canceled . If more than one { @code Publisher } signals an error the resulting { @code Flowable } may terminate with the first one s error or depending on the concurrency of the sources may terminate with a { @code CompositeException } containing two or more of the various error signals . { @code Throwable } s that didn t make into the composite will be sent ( individually ) to the global error handler via { @link RxJavaPlugins#onError ( Throwable ) } method as { @code UndeliverableException } errors . Similarly { @code Throwable } s signaled by source ( s ) after the returned { @code Flowable } has been canceled or terminated with a ( composite ) error will be sent to the same global error handler . Use { @link #mergeDelayError ( Publisher Publisher Publisher Publisher ) } to merge sources and terminate only when all source { @code Publisher } s have completed or failed with an error . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > merge ( Publisher < ? extends T > source1 , Publisher < ? extends T > source2 , Publisher < ? extends T > source3 , Publisher < ? extends T > source4 ) { ObjectHelper . requireNonNull ( source1 , \"source1 is null\" ) ; ObjectHelper . requireNonNull ( source2 , \"source2 is null\" ) ; ObjectHelper . requireNonNull ( source3 , \"source3 is null\" ) ; ObjectHelper . requireNonNull ( source4 , \"source4 is null\" ) ; return fromArray ( source1 , source2 , source3 , source4 ) . flatMap ( ( Function ) Functions . identity ( ) , false , 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens an Iterable of Publishers into one Publisher in a way that allows a Subscriber to receive all successfully emitted items from each of the source Publishers without being interrupted by an error notification from one of them . <p > This behaves like { @link #merge ( Publisher ) } except that if any of the merged Publishers notify of an error via { @link Subscriber#onError onError } { @code mergeDelayError } will refrain from propagating that error notification until all of the merged Publishers have finished emitting items . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeDelayError . png alt = > <p > Even if multiple merged Publishers send { @code onError } notifications { @code mergeDelayError } will only invoke the { @code onError } method of its Subscribers once . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . All inner { @code Publisher } s are expected to honor backpressure ; if violated the operator <em > may< / em > signal { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > mergeDelayError ( Iterable < ? extends Publisher < ? extends T > > sources ) { return fromIterable ( sources ) . flatMap ( ( Function ) Functions . identity ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that never sends any items or notifications to a { @link Subscriber } . <p > <img width = 640 height = 185 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / never . png alt = > <p > This Publisher is useful primarily for testing purposes . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This source doesn t produce any elements and effectively ignores downstream backpressure . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code never } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ SuppressWarnings ( \"unchecked\" ) public static < T > Flowable < T > never ( ) { return RxJavaPlugins . onAssembly ( ( Flowable < T > ) FlowableNever . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits a sequence of Integers within a specified range . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / range . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and signals values on - demand ( i . e . when requested ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code range } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static Flowable < Integer > range ( int start , int count ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } else if ( count == 0 ) { return empty ( ) ; } else if ( count == 1 ) { return just ( start ) ; } else if ( ( long ) start + ( count - 1 ) > Integer . MAX_VALUE ) { throw new IllegalArgumentException ( \"Integer overflow\" ) ; } return RxJavaPlugins . onAssembly ( new FlowableRange ( start , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits a sequence of Longs within a specified range . <p > <img width = 640 height = 195 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / range . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and signals values on - demand ( i . e . when requested ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code rangeLong } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static Flowable < Long > rangeLong ( long start , long count ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } if ( count == 0 ) { return empty ( ) ; } if ( count == 1 ) { return just ( start ) ; } long end = start + ( count - 1 ) ; if ( start > 0 && end < 0 ) { throw new IllegalArgumentException ( \"Overflow! start + count is bigger than Long.MAX_VALUE\" ) ; } return RxJavaPlugins . onAssembly ( new FlowableRangeLong ( start , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two Publisher sequences are the same by comparing the items emitted by each Publisher pairwise based on the results of a specified equality function . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The source { @code Publisher } s are expected to honor backpressure ; if violated the operator signals a { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( Publisher < ? extends T > source1 , Publisher < ? extends T > source2 , BiPredicate < ? super T , ? super T > isEqual ) { return sequenceEqual ( source1 , source2 , isEqual , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two Publisher sequences are the same by comparing the items emitted by each Publisher pairwise based on the results of a specified equality function . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The source { @code Publisher } s are expected to honor backpressure ; if violated the operator signals a { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( Publisher < ? extends T > source1 , Publisher < ? extends T > source2 , BiPredicate < ? super T , ? super T > isEqual , int bufferSize ) { ObjectHelper . requireNonNull ( source1 , \"source1 is null\" ) ; ObjectHelper . requireNonNull ( source2 , \"source2 is null\" ) ; ObjectHelper . requireNonNull ( isEqual , \"isEqual is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new FlowableSequenceEqualSingle < T > ( source1 , source2 , isEqual , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean value that indicates whether two Publisher sequences are the same by comparing the items emitted by each Publisher pairwise . <p > <img width = 640 height = 385 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sequenceEqual . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator honors downstream backpressure and expects both of its sources to honor backpressure as well . If violated the operator will emit a MissingBackpressureException . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sequenceEqual } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Single < Boolean > sequenceEqual ( Publisher < ? extends T > source1 , Publisher < ? extends T > source2 , int bufferSize ) { return sequenceEqual ( source1 , source2 , ObjectHelper . equalsPredicate ( ) , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a Publisher that emits Publishers into a Publisher that emits the items emitted by the most recently emitted of those Publishers . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchDo . png alt = > <p > { @code switchOnNext } subscribes to a Publisher that emits Publishers . Each time it observes one of these emitted Publishers the Publisher returned by { @code switchOnNext } begins emitting the items emitted by that Publisher . When a new Publisher is emitted { @code switchOnNext } stops emitting items from the earlier - emitted Publisher and begins emitting items from the new one . <p > The resulting Publisher completes if both the outer Publisher and the last inner Publisher if any complete . If the outer Publisher signals an onError the inner Publisher is canceled and the error delivered in - sequence . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The outer { @code Publisher } is consumed in an unbounded manner ( i . e . without backpressure ) and the inner { @code Publisher } s are expected to honor backpressure but it is not enforced ; the operator won t signal a { @code MissingBackpressureException } but the violation <em > may< / em > lead to { @code OutOfMemoryError } due to internal buffer bloat . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchOnNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > switchOnNext ( Publisher < ? extends Publisher < ? extends T > > sources , int bufferSize ) { return fromPublisher ( sources ) . switchMap ( ( Function ) Functions . identity ( ) , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a Publisher that emits Publishers into a Publisher that emits the items emitted by the most recently emitted of those Publishers and delays any exception until all Publishers terminate . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchDo . png alt = > <p > { @code switchOnNext } subscribes to a Publisher that emits Publishers . Each time it observes one of these emitted Publishers the Publisher returned by { @code switchOnNext } begins emitting the items emitted by that Publisher . When a new Publisher is emitted { @code switchOnNext } stops emitting items from the earlier - emitted Publisher and begins emitting items from the new one . <p > The resulting Publisher completes if both the main Publisher and the last inner Publisher if any complete . If the main Publisher signals an onError the termination of the last inner Publisher will emit that error as is or wrapped into a CompositeException along with the other possible errors the former inner Publishers signaled . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The outer { @code Publisher } is consumed in an unbounded manner ( i . e . without backpressure ) and the inner { @code Publisher } s are expected to honor backpressure but it is not enforced ; the operator won t signal a { @code MissingBackpressureException } but the violation <em > may< / em > lead to { @code OutOfMemoryError } due to internal buffer bloat . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchOnNextDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > switchOnNextDelayError ( Publisher < ? extends Publisher < ? extends T > > sources , int prefetch ) { return fromPublisher ( sources ) . switchMapDelayError ( Functions . < Publisher < ? extends T > > identity ( ) , prefetch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits { @code 0L } after a specified delay and then completes . <p > <img width = 640 height = 200 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timer . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time . If the downstream needs a slower rate it should slow the timer or use something like { @link #onBackpressureDrop } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code timer } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public static Flowable < Long > timer ( long delay , TimeUnit unit ) { return timer ( delay , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Flowable by wrapping a Publisher <em > which has to be implemented according to the Reactive - Streams specification by handling backpressure and cancellation correctly ; no safeguards are provided by the Flowable itself< / em > . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator is a pass - through for backpressure and the behavior is determined by the provided Publisher implementation . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . NONE ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T > Flowable < T > unsafeCreate ( Publisher < T > onSubscribe ) { ObjectHelper . requireNonNull ( onSubscribe , \"onSubscribe is null\" ) ; if ( onSubscribe instanceof Flowable ) { throw new IllegalArgumentException ( \"unsafeCreate(Flowable) should be upgraded\" ) ; } return RxJavaPlugins . onAssembly ( new FlowableFromPublisher < T > ( onSubscribe ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a Publisher that creates a dependent resource object which is disposed of on cancellation . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / using . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator is a pass - through for backpressure and otherwise depends on the backpressure support of the Publisher returned by the { @code resourceFactory } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code using } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , D > Flowable < T > using ( Callable < ? extends D > resourceSupplier , Function < ? super D , ? extends Publisher < ? extends T > > sourceSupplier , Consumer < ? super D > resourceDisposer ) { return using ( resourceSupplier , sourceSupplier , resourceDisposer , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the results of a specified combiner function applied to combinations of items emitted in sequence by an Iterable of other Publishers . <p > { @code zip } applies this function in strict sequence so the first item emitted by the new Publisher will be the result of the function applied to the first item emitted by each of the source Publishers ; the second item emitted by the new Publisher will be the result of the function applied to the second item emitted by each of those Publishers ; and so forth . <p > The resulting { @code Publisher<R > } returned from { @code zip } will invoke { @code onNext } as many times as the number of { @code onNext } invocations of the source Publisher that emits the fewest items . <p > The operator subscribes to its sources in the order they are specified and completes eagerly if one of the sources is shorter than the rest while canceling the other sources . Therefore it is possible those other sources will never be able to run to completion ( and thus not calling { @code doOnComplete () } ) . This can also happen if the sources are exactly the same length ; if source A completes and B has been consumed and is about to complete the operator detects A won t be sending further values and it will cancel B immediately . For example : <pre > <code > zip ( Arrays . asList ( range ( 1 5 ) . doOnComplete ( action1 ) range ( 6 5 ) . doOnComplete ( action2 )) ( a ) - &gt ; a ) < / code > < / pre > { @code action1 } will be called but { @code action2 } won t . <br > To work around this termination property use { @link #doOnCancel ( Action ) } as well or use { @code using () } to do cleanup in case of completion or cancellation . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / zip . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator expects backpressure from the sources and honors backpressure from the downstream . ( I . e . zipping with { @link #interval ( long TimeUnit ) } may result in MissingBackpressureException use one of the { @code onBackpressureX } to handle similar backpressure - ignoring sources . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code zip } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , R > Flowable < R > zip ( Iterable < ? extends Publisher < ? extends T > > sources , Function < ? super Object [ ] , ? extends R > zipper ) { ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; ObjectHelper . requireNonNull ( sources , \"sources is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableZip < T , R > ( null , sources , zipper , bufferSize ( ) , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the results of a specified combiner function applied to combinations of <i > n< / i > items emitted in sequence by the <i > n< / i > Publishers emitted by a specified Publisher . <p > { @code zip } applies this function in strict sequence so the first item emitted by the new Publisher will be the result of the function applied to the first item emitted by each of the Publishers emitted by the source Publisher ; the second item emitted by the new Publisher will be the result of the function applied to the second item emitted by each of those Publishers ; and so forth . <p > The resulting { @code Publisher<R > } returned from { @code zip } will invoke { @code onNext } as many times as the number of { @code onNext } invocations of the source Publisher that emits the fewest items . <p > The operator subscribes to its sources in the order they are specified and completes eagerly if one of the sources is shorter than the rest while cancel the other sources . Therefore it is possible those other sources will never be able to run to completion ( and thus not calling { @code doOnComplete () } ) . This can also happen if the sources are exactly the same length ; if source A completes and B has been consumed and is about to complete the operator detects A won t be sending further values and it will cancel B immediately . For example : <pre > <code > zip ( just ( range ( 1 5 ) . doOnComplete ( action1 ) range ( 6 5 ) . doOnComplete ( action2 )) ( a ) - &gt ; a ) < / code > < / pre > { @code action1 } will be called but { @code action2 } won t . <br > To work around this termination property use { @link #doOnCancel ( Action ) } as well or use { @code using () } to do cleanup in case of completion or cancellation . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / zip . o . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator expects backpressure from the sources and honors backpressure from the downstream . ( I . e . zipping with { @link #interval ( long TimeUnit ) } may result in MissingBackpressureException use one of the { @code onBackpressureX } to handle similar backpressure - ignoring sources . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code zip } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" , \"cast\" } ) @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public static < T , R > Flowable < R > zip ( Publisher < ? extends Publisher < ? extends T > > sources , final Function < ? super Object [ ] , ? extends R > zipper ) { ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; return fromPublisher ( sources ) . toList ( ) . flatMapPublisher ( ( Function ) FlowableInternalHelper . < T , R > zipIterable ( zipper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified converter function during assembly time and returns its resulting value . <p > This allows fluent conversion to any other type . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The backpressure behavior depends on what happens in the { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > R as ( @ NonNull FlowableConverter < T , ? extends R > converter ) { return ObjectHelper . requireNonNull ( converter , \"converter is null\" ) . apply ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first item emitted by this { @code Flowable } or throws { @code NoSuchElementException } if it emits no items . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Flowable } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingFirst } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingFirst ( ) { BlockingFirstSubscriber < T > s = new BlockingFirstSubscriber < T > ( ) ; subscribe ( s ) ; T v = s . blockingGet ( ) ; if ( v != null ) { return v ; } throw new NoSuchElementException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts this { @code Flowable } into an { @link Iterable } . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / B . toIterable . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator expects the upstream to honor backpressure otherwise the returned Iterable s iterator will throw a { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingIterable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Iterable < T > blockingIterable ( ) { return blockingIterable ( bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts this { @code Flowable } into an { @link Iterable } . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / B . toIterable . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator expects the upstream to honor backpressure otherwise the returned Iterable s iterator will throw a { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingIterable } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Iterable < T > blockingIterable ( int bufferSize ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return new BlockingFlowableIterable < T > ( this , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last item emitted by this { @code Flowable } or throws { @code NoSuchElementException } if this { @code Flowable } emits no items . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / B . last . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Flowable } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingLast } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingLast ( ) { BlockingLastSubscriber < T > s = new BlockingLastSubscriber < T > ( ) ; subscribe ( s ) ; T v = s . blockingGet ( ) ; if ( v != null ) { return v ; } throw new NoSuchElementException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @link Iterable } that always returns the item most recently emitted by this { @code Flowable } . <p > <img width = 640 height = 490 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / B . mostRecent . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Flowable } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingMostRecent } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Iterable < T > blockingMostRecent ( T initialItem ) { return new BlockingFlowableMostRecent < T > ( this , initialItem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @link Iterable } that blocks until this { @code Flowable } emits another item then returns that item . <p > <img width = 640 height = 490 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / B . next . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Flowable } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Iterable < T > blockingNext ( ) { return new BlockingFlowableNext < T > ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this { @code Flowable } completes after emitting a single item return that item otherwise throw a { @code NoSuchElementException } . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / B . single . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Flowable } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingSingle } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingSingle ( ) { return singleOrError ( ) . blockingGet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this { @code Flowable } completes after emitting a single item return that item ; if it emits more than one item throw an { @code IllegalArgumentException } ; if it emits no items return a default value . <p > <img width = 640 height = 315 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / B . singleOrDefault . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Flowable } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code blockingSingle } does not operate by default on a particular { @link Scheduler } . < / dd > <dt > <b > Error handling : < / b > < / dt > <dd > If the source signals an error the operator wraps a checked { @link Exception } into { @link RuntimeException } and throws that . Otherwise { @code RuntimeException } s and { @link Error } s are rethrown as they are . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final T blockingSingle ( T defaultItem ) { return single ( defaultItem ) . blockingGet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Future } representing the only value emitted by this { @code Flowable } . <p > <img width = 640 height = 324 src = https : // github . com / ReactiveX / RxJava / wiki / images / rx - operators / Flowable . toFuture . png alt = > <p > If the { @link Flowable } emits more than one item { @link java . util . concurrent . Future } will receive an { @link java . lang . IndexOutOfBoundsException } . If the { @link Flowable } is empty { @link java . util . concurrent . Future } will receive a { @link java . util . NoSuchElementException } . The { @code Flowable } source has to terminate in order for the returned { @code Future } to terminate as well . <p > If the { @code Flowable } may emit more than one item use { @code Flowable . toList () . toFuture () } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Flowable } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toFuture } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Future < T > toFuture ( ) { return subscribeWith ( new FutureSubscriber < T > ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given callbacks <strong > on the current thread< / strong > . <p > If the Flowable emits an error it is wrapped into an { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingSubscribe ( Consumer < ? super T > onNext ) { FlowableBlockingSubscribe . subscribe ( this , onNext , Functions . ON_ERROR_MISSING , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the given callbacks <strong > on the current thread< / strong > . <p > Note that calling this method will block the caller thread until the upstream terminates normally or with an error . Therefore calling this method from special threads such as the Android Main Thread or the Swing Event Dispatch Thread is not recommended . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingSubscribe ( Consumer < ? super T > onNext , Consumer < ? super Throwable > onError , Action onComplete , int bufferSize ) { FlowableBlockingSubscribe . subscribe ( this , onNext , onError , onComplete , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the source and calls the { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final void blockingSubscribe ( Subscriber < ? super T > subscriber ) { FlowableBlockingSubscribe . subscribe ( this , subscriber ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping buffers each containing { @code count } items . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer3 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and expects the source { @code Publisher } to honor it as well although not enforced ; violation <em > may< / em > lead to { @code MissingBackpressureException } somewhere downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < List < T > > buffer ( int count ) { return buffer ( count , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits buffers every { @code skip } items each containing { @code count } items . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer4 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and expects the source { @code Publisher } to honor it as well although not enforced ; violation <em > may< / em > lead to { @code MissingBackpressureException } somewhere downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < List < T > > buffer ( int count , int skip ) { return buffer ( count , skip , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits buffers every { @code skip } items each containing { @code count } items . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer4 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and expects the source { @code Publisher } to honor it as well although not enforced ; violation <em > may< / em > lead to { @code MissingBackpressureException } somewhere downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U extends Collection < ? super T > > Flowable < U > buffer ( int count , int skip , Callable < U > bufferSupplier ) { ObjectHelper . verifyPositive ( count , \"count\" ) ; ObjectHelper . verifyPositive ( skip , \"skip\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableBuffer < T , U > ( this , count , skip , bufferSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping buffers each containing { @code count } items . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer3 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and expects the source { @code Publisher } to honor it as well although not enforced ; violation <em > may< / em > lead to { @code MissingBackpressureException } somewhere downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U extends Collection < ? super T > > Flowable < U > buffer ( int count , Callable < U > bufferSupplier ) { return buffer ( count , count , bufferSupplier ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher starts a new buffer periodically as determined by the { @code timeskip } argument . It emits each buffer after a fixed timespan specified by the { @code timespan } argument . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer7 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < List < T > > buffer ( long timespan , long timeskip , TimeUnit unit ) { return buffer ( timespan , timeskip , unit , Schedulers . computation ( ) , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher starts a new buffer periodically as determined by the { @code timeskip } argument and on the specified { @code scheduler } . It emits each buffer after a fixed timespan specified by the { @code timespan } argument . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer7 . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final < U extends Collection < ? super T > > Flowable < U > buffer ( long timespan , long timeskip , TimeUnit unit , Scheduler scheduler , Callable < U > bufferSupplier ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableBufferTimed < T , U > ( this , timespan , timeskip , unit , scheduler , bufferSupplier , Integer . MAX_VALUE , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping buffers each of a fixed duration specified by the { @code timespan } argument . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer5 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < List < T > > buffer ( long timespan , TimeUnit unit ) { return buffer ( timespan , unit , Schedulers . computation ( ) , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping buffers each of a fixed duration specified by the { @code timespan } argument as measured on the specified { @code scheduler } or a maximum size specified by the { @code count } argument ( whichever is reached first ) . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer6 . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < List < T > > buffer ( long timespan , TimeUnit unit , Scheduler scheduler , int count ) { return buffer ( timespan , unit , scheduler , count , ArrayListSupplier . < T > asCallable ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping buffers each of a fixed duration specified by the { @code timespan } argument as measured on the specified { @code scheduler } or a maximum size specified by the { @code count } argument ( whichever is reached first ) . When the source Publisher completes the resulting Publisher emits the current buffer and propagates the notification from the source Publisher . Note that if the source Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer6 . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final < U extends Collection < ? super T > > Flowable < U > buffer ( long timespan , TimeUnit unit , Scheduler scheduler , int count , Callable < U > bufferSupplier , boolean restartTimerOnMaxSize ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; ObjectHelper . verifyPositive ( count , \"count\" ) ; return RxJavaPlugins . onAssembly ( new FlowableBufferTimed < T , U > ( this , timespan , timespan , unit , scheduler , bufferSupplier , count , restartTimerOnMaxSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits buffers that it creates when the specified { @code openingIndicator } Publisher emits an item and closes when the Publisher returned from { @code closingIndicator } emits an item . If any of the source Publisher { @code openingIndicator } or { @code closingIndicator } issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 470 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer2 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it is instead controlled by the given Publishers and buffers data . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < TOpening , TClosing > Flowable < List < T > > buffer ( Flowable < ? extends TOpening > openingIndicator , Function < ? super TOpening , ? extends Publisher < ? extends TClosing > > closingIndicator ) { return buffer ( openingIndicator , closingIndicator , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits buffers of items it collects from the source Publisher . The resulting Publisher emits buffers that it creates when the specified { @code openingIndicator } Publisher emits an item and closes when the Publisher returned from { @code closingIndicator } emits an item . If any of the source Publisher { @code openingIndicator } or { @code closingIndicator } issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <p > <img width = 640 height = 470 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer2 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it is instead controlled by the given Publishers and buffers data . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < TOpening , TClosing , U extends Collection < ? super T > > Flowable < U > buffer ( Flowable < ? extends TOpening > openingIndicator , Function < ? super TOpening , ? extends Publisher < ? extends TClosing > > closingIndicator , Callable < U > bufferSupplier ) { ObjectHelper . requireNonNull ( openingIndicator , \"openingIndicator is null\" ) ; ObjectHelper . requireNonNull ( closingIndicator , \"closingIndicator is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableBufferBoundary < T , U , TOpening , TClosing > ( this , openingIndicator , closingIndicator , bufferSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits non - overlapping buffered items from the source Publisher each time the specified boundary Publisher emits an item . <p > <img width = 640 height = 395 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer8 . png alt = > <p > Completion of either the source or the boundary Publisher causes the returned Publisher to emit the latest buffer and complete . If either the source Publisher or the boundary Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it is instead controlled by the { @code Publisher } { @code boundary } and buffers data . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Flowable < List < T > > buffer ( Publisher < B > boundaryIndicator ) { return buffer ( boundaryIndicator , ArrayListSupplier . < T > asCallable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits non - overlapping buffered items from the source Publisher each time the specified boundary Publisher emits an item . <p > <img width = 640 height = 395 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer8 . png alt = > <p > Completion of either the source or the boundary Publisher causes the returned Publisher to emit the latest buffer and complete . If either the source Publisher or the boundary Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it is instead controlled by the { @code Publisher } { @code boundary } and buffers data . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Flowable < List < T > > buffer ( Publisher < B > boundaryIndicator , final int initialCapacity ) { ObjectHelper . verifyPositive ( initialCapacity , \"initialCapacity\" ) ; return buffer ( boundaryIndicator , Functions . < T > createArrayList ( initialCapacity ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits non - overlapping buffered items from the source Publisher each time the specified boundary Publisher emits an item . <p > <img width = 640 height = 395 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / buffer8 . png alt = > <p > Completion of either the source or the boundary Publisher causes the returned Publisher to emit the latest buffer and complete . If either the source Publisher or the boundary Publisher issues an onError notification the event is passed on immediately without first emitting the buffer it is in the process of assembling . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it is instead controlled by the { @code Publisher } { @code boundary } and buffers data . It requests { @code Long . MAX_VALUE } upstream and does not obey downstream requests . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code buffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B , U extends Collection < ? super T > > Flowable < U > buffer ( Publisher < B > boundaryIndicator , Callable < U > bufferSupplier ) { ObjectHelper . requireNonNull ( boundaryIndicator , \"boundaryIndicator is null\" ) ; ObjectHelper . requireNonNull ( bufferSupplier , \"bufferSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableBufferExactBoundary < T , U , B > ( this , boundaryIndicator , bufferSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that subscribes to this Publisher lazily caches all of its events and replays them in the same order as received to all the downstream subscribers . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / cache . png alt = > <p > This is useful when you want a Publisher to cache responses and you can t control the subscribe / cancel behavior of all the { @link Subscriber } s . <p > The operator subscribes only when the first downstream subscriber subscribes and maintains a single subscription towards this Publisher . In contrast the operator family of { @link #replay () } that return a { @link ConnectableFlowable } require an explicit call to { @link ConnectableFlowable#connect () } . <p > <em > Note : < / em > You sacrifice the ability to cancel the origin when you use the { @code cache } Subscriber so be careful not to use this Subscriber on Publishers that emit an infinite or very large number of items that will use up memory . A possible workaround is to apply takeUntil with a predicate or another source before ( and perhaps after ) the application of cache () . <pre > <code > AtomicBoolean shouldStop = new AtomicBoolean () ; [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > cache ( ) { return cacheWithInitialCapacity ( 16 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that subscribes to this Publisher lazily caches all of its events and replays them in the same order as received to all the downstream subscribers . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / cache . png alt = > <p > This is useful when you want a Publisher to cache responses and you can t control the subscribe / cancel behavior of all the { @link Subscriber } s . <p > The operator subscribes only when the first downstream subscriber subscribes and maintains a single subscription towards this Publisher . In contrast the operator family of { @link #replay () } that return a { @link ConnectableFlowable } require an explicit call to { @link ConnectableFlowable#connect () } . <p > <em > Note : < / em > You sacrifice the ability to cancel the origin when you use the { @code cache } Subscriber so be careful not to use this Subscriber on Publishers that emit an infinite or very large number of items that will use up memory . A possible workaround is to apply takeUntil with a predicate or another source before ( and perhaps after ) the application of cache () . <pre > <code > AtomicBoolean shouldStop = new AtomicBoolean () ; [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > cacheWithInitialCapacity ( int initialCapacity ) { ObjectHelper . verifyPositive ( initialCapacity , \"initialCapacity\" ) ; return RxJavaPlugins . onAssembly ( new FlowableCache < T > ( this , initialCapacity ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects items emitted by the finite source Publisher into a single mutable data structure and returns a Single that emits this structure . <p > <img width = 640 height = 330 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / collect . png alt = > <p > This is a simplified version of { @code reduce } that does not need to return the state on each pass . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulator object to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure because by intent it will receive all values and reduce them to a single { @code onNext } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code collect } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Single < U > collect ( Callable < ? extends U > initialItemSupplier , BiConsumer < ? super U , ? super T > collector ) { ObjectHelper . requireNonNull ( initialItemSupplier , \"initialItemSupplier is null\" ) ; ObjectHelper . requireNonNull ( collector , \"collector is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableCollectSingle < T , U > ( this , initialItemSupplier , collector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a Publisher by applying a particular Transformer function to it . <p > This method operates on the Publisher itself whereas { @link #lift } operates on the Publisher s Subscribers or Subscribers . <p > If the operator you are creating is designed to act on the individual items emitted by a source Publisher use { @link #lift } . If your operator is designed to transform the source Publisher as a whole ( for instance by applying a particular set of existing RxJava operators to it ) use { @code compose } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator itself doesn t interfere with the backpressure behavior which only depends on what kind of { @code Publisher } the transformer returns . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code compose } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > compose ( FlowableTransformer < ? super T , ? extends R > composer ) { return fromPublisher ( ( ( FlowableTransformer < T , R > ) ObjectHelper . requireNonNull ( composer , \"composer is null\" ) ) . apply ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public final Completable concatMapCompletable ( Function < ? super T , ? extends CompletableSource > mapper ) { return concatMapCompletable ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public final Completable concatMapCompletableDelayError ( Function < ? super T , ? extends CompletableSource > mapper , boolean tillTheEnd ) { return concatMapCompletableDelayError ( mapper , tillTheEnd , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . FULL ) public final Completable concatMapCompletableDelayError ( Function < ? super T , ? extends CompletableSource > mapper , boolean tillTheEnd , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new FlowableConcatMapCompletable < T > ( this , mapper , tillTheEnd ? ErrorMode . END : ErrorMode . BOUNDARY , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each of the items into a Publisher subscribes to them one after the other one at a time and emits their values in order while delaying any error from either this or any of the inner Publishers till all of them terminate . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > concatMapDelayError ( Function < ? super T , ? extends Publisher < ? extends R > > mapper ) { return concatMapDelayError ( mapper , 2 , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a sequence of values into Publishers and concatenates these Publishers eagerly into a single Publisher . <p > Eager concatenation means that once a subscriber subscribes this operator subscribes to all of the source Publishers . The operator buffers the values emitted by these Publishers and then drains them in order each one after the previous one completes . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > Backpressure is honored towards the downstream however due to the eagerness requirement sources are subscribed to in unbounded mode and their values are queued up in an unbounded buffer . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This method does not operate by default on a particular { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > concatMapEager ( Function < ? super T , ? extends Publisher < ? extends R > > mapper , int maxConcurrency , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new FlowableConcatMapEager < T , R > ( this , mapper , maxConcurrency , prefetch , ErrorMode . IMMEDIATE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that concatenate each item emitted by the source Publisher with the values in an Iterable corresponding to that item that is generated by a selector . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Flowable < U > concatMapIterable ( Function < ? super T , ? extends Iterable < ? extends U > > mapper ) { return concatMapIterable ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > concatMapMaybe ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { return concatMapMaybe ( mapper , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > concatMapSingle ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper , int prefetch ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( prefetch , \"prefetch\" ) ; return RxJavaPlugins . onAssembly ( new FlowableConcatMapSingle < T , R > ( this , mapper , ErrorMode . IMMEDIATE , prefetch ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream items into { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > concatMapSingleDelayError ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper ) { return concatMapSingleDelayError ( mapper , true , 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > concatWith ( @ NonNull SingleSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableConcatWithSingle < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > concatWith ( @ NonNull MaybeSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableConcatWithMaybe < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > concatWith ( @ NonNull CompletableSource other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableConcatWithCompletable < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a Boolean that indicates whether the source Publisher emitted a specified item . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / contains . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code contains } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > contains ( final Object item ) { ObjectHelper . requireNonNull ( item , \"item is null\" ) ; return any ( Functions . equalsWith ( item ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that counts the total number of items emitted by the source Publisher and emits this count as a 64 - bit Long . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / longCount . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code count } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Long > count ( ) { return RxJavaPlugins . onAssembly ( new FlowableCountSingle < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher except that it drops items emitted by the source Publisher that are followed by another item within a computed debounce duration . <p > <img width = 640 height = 425 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / debounce . f . png alt = > <p > The delivery of the item happens on the thread of the first { @code onNext } or { @code onComplete } signal of the generated { @code Publisher } sequence which if takes too long a newer item may arrive from the upstream causing the generated sequence to get cancelled which may also interrupt any downstream blocking operation ( yielding an { @code InterruptedException } ) . It is recommended processing items that may take long time to be moved to another thread via { @link #observeOn } applied after { @code debounce } itself . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses the { @code debounceSelector } to mark boundaries . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code debounce } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Flowable < T > debounce ( Function < ? super T , ? extends Publisher < U > > debounceIndicator ) { ObjectHelper . requireNonNull ( debounceIndicator , \"debounceIndicator is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDebounce < T , U > ( this , debounceIndicator ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher except that it drops items emitted by the source Publisher that are followed by newer items before a timeout value expires on a specified Scheduler . The timer resets on each emission . <p > <em > Note : < / em > If items keep being emitted by the source Publisher faster than the timeout then no items will be emitted by the resulting Publisher . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / debounce . s . png alt = > <p > Delivery of the item after the grace period happens on the given { @code Scheduler } s { @code Worker } which if takes too long a newer item may arrive from the upstream causing the { @code Worker } s task to get disposed which may also interrupt any downstream blocking operation ( yielding an { @code InterruptedException } ) . It is recommended processing items that may take long time to be moved to another thread via { @link #observeOn } applied after { @code debounce } itself . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > debounce ( long timeout , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDebounceTimed < T > ( this , timeout , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items emitted by the source Publisher shifted forward in time by a specified delay . If { @code delayError } is true error notifications will also be delayed . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with the backpressure behavior which is determined by the source { @code Publisher } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code delay } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < T > delay ( long delay , TimeUnit unit , boolean delayError ) { return delay ( delay , unit , Schedulers . computation ( ) , delayError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items emitted by the source Publisher shifted forward in time by a specified delay . Error notifications from the source Publisher are not delayed . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with the backpressure behavior which is determined by the source { @code Publisher } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > delay ( long delay , TimeUnit unit , Scheduler scheduler ) { return delay ( delay , unit , scheduler , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that delays the subscription to and emissions from the source Publisher via another Publisher on a per - item basis . <p > <img width = 640 height = 450 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / delay . oo . png alt = > <p > <em > Note : < / em > the resulting Publisher will immediately propagate any { @code onError } notification from the source Publisher . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with the backpressure behavior which is determined by the source { @code Publisher } . All of the other { @code Publisher } s supplied by the functions are consumed in an unbounded manner ( i . e . no backpressure applied to them ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code delay } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Flowable < T > delay ( Publisher < U > subscriptionIndicator , Function < ? super T , ? extends Publisher < V > > itemDelayIndicator ) { return delaySubscription ( subscriptionIndicator ) . delay ( itemDelayIndicator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that reverses the effect of { @link #materialize materialize } by transforming the { @link Notification } objects emitted by the source Publisher into the items or notifications they represent . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / dematerialize . png alt = > <p > When the upstream signals an { @link Notification#createOnError ( Throwable ) onError } or { @link Notification#createOnComplete () onComplete } item the returned Flowable cancels the flow and terminates with that type of terminal event : <pre > <code > Flowable . just ( createOnNext ( 1 ) createOnComplete () createOnNext ( 2 )) . doOnCancel (( ) - &gt ; System . out . println ( Cancelled! )) ; . dematerialize () . test () . assertResult ( 1 ) ; < / code > < / pre > If the upstream signals { @code onError } or { @code onComplete } directly the flow is terminated with the same event . <pre > <code > Flowable . just ( createOnNext ( 1 ) createOnNext ( 2 )) . dematerialize () . test () . assertResult ( 1 2 ) ; < / code > < / pre > If this behavior is not desired the completion can be suppressed by applying { @link #concatWith ( Publisher ) } with a { @link #never () } source . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code dematerialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ Deprecated @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public final < T2 > Flowable < T2 > dematerialize ( ) { return RxJavaPlugins . onAssembly ( new FlowableDematerialize ( this , Functions . identity ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that reverses the effect of { @link #materialize materialize } by transforming the { @link Notification } objects extracted from the source items via a selector function into their respective { @code Subscriber } signal types . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / dematerialize . png alt = > <p > The intended use of the { @code selector } function is to perform a type - safe identity mapping ( see example ) on a source that is already of type { @code Notification<T > } . The Java language doesn t allow limiting instance methods to a certain generic argument shape therefore a function is used to ensure the conversion remains type safe . <p > When the upstream signals an { @link Notification#createOnError ( Throwable ) onError } or { @link Notification#createOnComplete () onComplete } item the returned Flowable cancels of the flow and terminates with that type of terminal event : <pre > <code > Flowable . just ( createOnNext ( 1 ) createOnComplete () createOnNext ( 2 )) . doOnCancel (( ) - &gt ; System . out . println ( Canceled! )) ; . dematerialize ( notification - &gt ; notification ) . test () . assertResult ( 1 ) ; < / code > < / pre > If the upstream signals { @code onError } or { @code onComplete } directly the flow is terminated with the same event . <pre > <code > Flowable . just ( createOnNext ( 1 ) createOnNext ( 2 )) . dematerialize ( notification - &gt ; notification ) . test () . assertResult ( 1 2 ) ; < / code > < / pre > If this behavior is not desired the completion can be suppressed by applying { @link #concatWith ( Publisher ) } with a { @link #never () } source . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code dematerialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ Experimental @ CheckReturnValue @ NonNull @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) public final < R > Flowable < R > dematerialize ( Function < ? super T , Notification < R > > selector ) { ObjectHelper . requireNonNull ( selector , \"selector is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDematerialize < T , R > ( this , selector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits all items emitted by the source Publisher that are distinct based on { @link Object#equals ( Object ) } comparison . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinct . png alt = > <p > It is recommended the elements class { @code T } in the flow overrides the default { @code Object . equals () } and { @link Object#hashCode () } to provide a meaningful comparison between items as the default Java implementation only considers reference equivalence . <p > By default { @code distinct () } uses an internal { @link java . util . HashSet } per Subscriber to remember previously seen items and uses { @link java . util . Set#add ( Object ) } returning { @code false } as the indicator for duplicates . <p > Note that this internal { @code HashSet } may grow unbounded as items won t be removed from it by the operator . Therefore using very long or infinite upstream ( with very distinct elements ) may lead to { @code OutOfMemoryError } . <p > Customizing the retention policy can happen only by providing a custom { @link java . util . Collection } implementation to the { @link #distinct ( Function Callable ) } overload . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinct } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > distinct ( ) { return distinct ( ( Function ) Functions . identity ( ) , Functions . < T > createHashSet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits all items emitted by the source Publisher that are distinct according to a key selector function and based on { @link Object#equals ( Object ) } comparison of the objects returned by the key selector function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinct . key . png alt = > <p > It is recommended the keys class { @code K } overrides the default { @code Object . equals () } and { @link Object#hashCode () } to provide a meaningful comparison between the key objects as the default Java implementation only considers reference equivalence . <p > By default { @code distinct () } uses an internal { @link java . util . HashSet } per Subscriber to remember previously seen keys and uses { @link java . util . Set#add ( Object ) } returning { @code false } as the indicator for duplicates . <p > Note that this internal { @code HashSet } may grow unbounded as keys won t be removed from it by the operator . Therefore using very long or infinite upstream ( with very distinct keys ) may lead to { @code OutOfMemoryError } . <p > Customizing the retention policy can happen only by providing a custom { @link java . util . Collection } implementation to the { @link #distinct ( Function Callable ) } overload . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinct } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Flowable < T > distinct ( Function < ? super T , K > keySelector ) { return distinct ( keySelector , Functions . < K > createHashSet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits all items emitted by the source Publisher that are distinct according to a key selector function and based on { @link Object#equals ( Object ) } comparison of the objects returned by the key selector function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinct . key . png alt = > <p > It is recommended the keys class { @code K } overrides the default { @code Object . equals () } and { @link Object#hashCode () } to provide a meaningful comparison between the key objects as the default Java implementation only considers reference equivalence . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinct } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Flowable < T > distinct ( Function < ? super T , K > keySelector , Callable < ? extends Collection < ? super K > > collectionSupplier ) { ObjectHelper . requireNonNull ( keySelector , \"keySelector is null\" ) ; ObjectHelper . requireNonNull ( collectionSupplier , \"collectionSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDistinct < T , K > ( this , keySelector , collectionSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits all items emitted by the source Publisher that are distinct from their immediate predecessors based on { @link Object#equals ( Object ) } comparison . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinctUntilChanged . png alt = > <p > It is recommended the elements class { @code T } in the flow overrides the default { @code Object . equals () } to provide a meaningful comparison between items as the default Java implementation only considers reference equivalence . Alternatively use the { @link #distinctUntilChanged ( BiPredicate ) } overload and provide a comparison function in case the class { @code T } can t be overridden with custom { @code equals () } or the comparison itself should happen on different terms or properties of the class { @code T } . <p > Note that the operator always retains the latest item from upstream regardless of the comparison result and uses it in the next comparison with the next upstream item . <p > Note that if element type { @code T } in the flow is mutable the comparison of the previous and current item may yield unexpected results if the items are mutated externally . Common cases are mutable { @code CharSequence } s or { @code List } s where the objects will actually have the same references when they are modified and { @code distinctUntilChanged } will evaluate subsequent items as same . To avoid such situation it is recommended that mutable data is converted to an immutable one for example using { @code map ( CharSequence :: toString ) } or { @code map ( list - > Collections . unmodifiableList ( new ArrayList< > ( list ))) } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinctUntilChanged } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > distinctUntilChanged ( ) { return distinctUntilChanged ( Functions . identity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits all items emitted by the source Publisher that are distinct from their immediate predecessors according to a key selector function and based on { @link Object#equals ( Object ) } comparison of those objects returned by the key selector function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinctUntilChanged . key . png alt = > <p > It is recommended the keys class { @code K } overrides the default { @code Object . equals () } to provide a meaningful comparison between the key objects as the default Java implementation only considers reference equivalence . Alternatively use the { @link #distinctUntilChanged ( BiPredicate ) } overload and provide a comparison function in case the class { @code K } can t be overridden with custom { @code equals () } or the comparison itself should happen on different terms or properties of the item class { @code T } ( for which the keys can be derived via a similar selector ) . <p > Note that the operator always retains the latest key from upstream regardless of the comparison result and uses it in the next comparison with the next key derived from the next upstream item . <p > Note that if element type { @code T } in the flow is mutable the comparison of the previous and current item may yield unexpected results if the items are mutated externally . Common cases are mutable { @code CharSequence } s or { @code List } s where the objects will actually have the same references when they are modified and { @code distinctUntilChanged } will evaluate subsequent items as same . To avoid such situation it is recommended that mutable data is converted to an immutable one for example using { @code map ( CharSequence :: toString ) } or { @code map ( list - > Collections . unmodifiableList ( new ArrayList< > ( list ))) } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinctUntilChanged } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Flowable < T > distinctUntilChanged ( Function < ? super T , K > keySelector ) { ObjectHelper . requireNonNull ( keySelector , \"keySelector is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDistinctUntilChanged < T , K > ( this , keySelector , ObjectHelper . equalsPredicate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits all items emitted by the source Publisher that are distinct from their immediate predecessors when compared with each other via the provided comparator function . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / distinctUntilChanged . png alt = > <p > Note that the operator always retains the latest item from upstream regardless of the comparison result and uses it in the next comparison with the next upstream item . <p > Note that if element type { @code T } in the flow is mutable the comparison of the previous and current item may yield unexpected results if the items are mutated externally . Common cases are mutable { @code CharSequence } s or { @code List } s where the objects will actually have the same references when they are modified and { @code distinctUntilChanged } will evaluate subsequent items as same . To avoid such situation it is recommended that mutable data is converted to an immutable one for example using { @code map ( CharSequence :: toString ) } or { @code map ( list - > Collections . unmodifiableList ( new ArrayList< > ( list ))) } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code distinctUntilChanged } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > distinctUntilChanged ( BiPredicate < ? super T , ? super T > comparer ) { ObjectHelper . requireNonNull ( comparer , \"comparer is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDistinctUntilChanged < T , T > ( this , Functions . < T > identity ( ) , comparer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified action after this Flowable signals onError or onCompleted or gets canceled by the downstream . <p > In case of a race between a terminal event and a cancellation the provided { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doFinally ( Action onFinally ) { ObjectHelper . requireNonNull ( onFinally , \"onFinally is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDoFinally < T > ( this , onFinally ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified consumer with the current item after this item has been emitted to the downstream . <p > Note that the { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doAfterNext ( Consumer < ? super T > onAfterNext ) { ObjectHelper . requireNonNull ( onAfterNext , \"onAfterNext is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDoAfterNext < T > ( this , onAfterNext ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an { @link Action } to be called when this Publisher invokes either { @link Subscriber#onComplete onComplete } or { @link Subscriber#onError onError } . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / finallyDo . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doAfterTerminate } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doAfterTerminate ( Action onAfterTerminate ) { return doOnEach ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , onAfterTerminate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the cancel { @code Action } if the downstream cancels the sequence . <p > The action is shared between subscriptions and thus may be called concurrently from multiple threads ; the action must be thread - safe . <p > If the action throws a runtime exception that exception is rethrown by the { @code onCancel () } call sometimes as a { @code CompositeException } if there were multiple exceptions along the way . <p > Note that terminal events trigger the action unless the { @code Publisher } is subscribed to via { @code unsafeSubscribe () } . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnUnsubscribe . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > { @code doOnCancel } does not interact with backpressure requests or value delivery ; backpressure behavior is preserved between its upstream and its downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnCancel } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnCancel ( Action onCancel ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , Functions . EMPTY_LONG_CONSUMER , onCancel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source Publisher so that it invokes an action when it calls { @code onComplete } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnComplete . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnComplete } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnComplete ( Action onComplete ) { return doOnEach ( Functions . emptyConsumer ( ) , Functions . emptyConsumer ( ) , onComplete , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the appropriate onXXX consumer ( shared between all subscribers ) whenever a signal with the same type passes through before forwarding them to downstream . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnEach . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnEach } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) private Flowable < T > doOnEach ( Consumer < ? super T > onNext , Consumer < ? super Throwable > onError , Action onComplete , Action onAfterTerminate ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; ObjectHelper . requireNonNull ( onAfterTerminate , \"onAfterTerminate is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableDoOnEach < T > ( this , onNext , onError , onComplete , onAfterTerminate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source Publisher so that it invokes an action for each item it emits . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnEach . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnEach } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnEach ( final Consumer < ? super Notification < T > > onNotification ) { ObjectHelper . requireNonNull ( onNotification , \"onNotification is null\" ) ; return doOnEach ( Functions . notificationOnNext ( onNotification ) , Functions . notificationOnError ( onNotification ) , Functions . notificationOnComplete ( onNotification ) , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source Publisher so that it notifies a Subscriber for each item and terminal event it emits . <p > In case the { @code onError } of the supplied Subscriber throws the downstream will receive a composite exception containing the original exception and the exception thrown by { @code onError } . If either the { @code onNext } or the { @code onComplete } method of the supplied Subscriber throws the downstream will be terminated and will receive this thrown exception . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnEach . o . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnEach } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnEach ( final Subscriber < ? super T > subscriber ) { ObjectHelper . requireNonNull ( subscriber , \"subscriber is null\" ) ; return doOnEach ( FlowableInternalHelper . subscriberOnNext ( subscriber ) , FlowableInternalHelper . subscriberOnError ( subscriber ) , FlowableInternalHelper . subscriberOnComplete ( subscriber ) , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source Publisher so that it invokes an action if it calls { @code onError } . <p > In case the { @code onError } action throws the downstream will receive a composite exception containing the original exception and the exception thrown by { @code onError } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnError . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnError ( Consumer < ? super Throwable > onError ) { return doOnEach ( Functions . emptyConsumer ( ) , onError , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source Publisher so that it invokes an action when it calls { @code onNext } . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnNext . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnNext ( Consumer < ? super T > onNext ) { return doOnEach ( onNext , Functions . emptyConsumer ( ) , Functions . EMPTY_ACTION , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source { @code Publisher } so that it invokes the given action when it receives a request for more items . <p > <b > Note : < / b > This operator is for tracing the internal behavior of back - pressure request patterns and generally intended for debugging use . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnRequest } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnRequest ( LongConsumer onRequest ) { return doOnLifecycle ( Functions . emptyConsumer ( ) , onRequest , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source { @code Publisher } so that it invokes the given action when it is subscribed from its subscribers . Each subscription will result in an invocation of the given action except when the source { @code Publisher } is reference counted in which case the source { @code Publisher } will invoke the given action for the first subscription . <p > <img width = 640 height = 390 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnSubscribe . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnSubscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnSubscribe ( Consumer < ? super Subscription > onSubscribe ) { return doOnLifecycle ( onSubscribe , Functions . EMPTY_LONG_CONSUMER , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source Publisher so that it invokes an action when it calls { @code onComplete } or { @code onError } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / doOnTerminate . png alt = > <p > This differs from { @code doAfterTerminate } in that this happens <em > before< / em > the { @code onComplete } or { @code onError } notification . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code doOnTerminate } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > doOnTerminate ( final Action onTerminate ) { return doOnEach ( Functions . emptyConsumer ( ) , Functions . actionConsumer ( onTerminate ) , onTerminate , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the single item at a specified index in a sequence of emissions from this Flowable or completes if this Flowable sequence has fewer elements than index . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / elementAt . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code elementAt } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > elementAt ( long index ) { if ( index < 0 ) { throw new IndexOutOfBoundsException ( \"index >= 0 required but it was \" + index ) ; } return RxJavaPlugins . onAssembly ( new FlowableElementAtMaybe < T > ( this , index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the item found at a specified index in a sequence of emissions from this Flowable or signals a { @link NoSuchElementException } if this Flowable has fewer elements than index . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / elementAtOrDefault . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code elementAtOrError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > elementAtOrError ( long index ) { if ( index < 0 ) { throw new IndexOutOfBoundsException ( \"index >= 0 required but it was \" + index ) ; } return RxJavaPlugins . onAssembly ( new FlowableElementAtSingle < T > ( this , index , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters items emitted by a Publisher by only emitting those that satisfy a specified predicate . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / filter . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code filter } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > filter ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableFilter < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits only the very first item emitted by this Flowable or completes if this Flowable is empty . <p > <img width = 640 height = 237 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / firstElement . m . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code firstElement } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) // take may trigger UNBOUNDED_IN @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > firstElement ( ) { return elementAt ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits only the very first item emitted by this Flowable or a default item if this Flowable completes without emitting anything . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / first . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code first } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) // take may trigger UNBOUNDED_IN @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > first ( T defaultItem ) { return elementAt ( 0 , defaultItem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits only the very first item emitted by this Flowable or signals a { @link NoSuchElementException } if this Flowable is empty . <p > <img width = 640 height = 237 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / firstOrError . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code firstOrError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) // take may trigger UNBOUNDED_IN @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > firstOrError ( ) { return elementAtOrError ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits items based on applying a function that you supply to each item emitted by the source Publisher where that function returns a Publisher and then merging those resulting Publishers and emitting the results of this merger while limiting the maximum number of concurrent subscriptions to these Publishers . <! -- <p > -- > <! -- <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / flatMap . png alt = > -- > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The upstream Flowable is consumed in a bounded manner ( up to { @code maxConcurrency } outstanding request amount for items ) . The inner { @code Publisher } s are expected to honor backpressure ; if violated the operator <em > may< / em > signal { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > flatMap ( Function < ? super T , ? extends Publisher < ? extends R > > mapper , boolean delayErrors , int maxConcurrency , int bufferSize ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; if ( this instanceof ScalarCallable ) { @ SuppressWarnings ( \"unchecked\" ) T v = ( ( ScalarCallable < T > ) this ) . call ( ) ; if ( v == null ) { return empty ( ) ; } return FlowableScalarXMap . scalarXMap ( v , mapper ) ; } return RxJavaPlugins . onAssembly ( new FlowableFlatMap < T , R > ( this , mapper , delayErrors , maxConcurrency , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that applies a function to each item emitted or notification raised by the source Publisher and then flattens the Publishers returned from these functions and emits the resulting items . <p > <img width = 640 height = 410 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeMap . nce . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The upstream Flowable is consumed in a bounded manner ( up to { @link #bufferSize () } outstanding request amount for items ) . The inner { @code Publisher } s are expected to honor backpressure ; if violated the operator <em > may< / em > signal { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > flatMap ( Function < ? super T , ? extends Publisher < ? extends R > > onNextMapper , Function < ? super Throwable , ? extends Publisher < ? extends R > > onErrorMapper , Callable < ? extends Publisher < ? extends R > > onCompleteSupplier ) { ObjectHelper . requireNonNull ( onNextMapper , \"onNextMapper is null\" ) ; ObjectHelper . requireNonNull ( onErrorMapper , \"onErrorMapper is null\" ) ; ObjectHelper . requireNonNull ( onCompleteSupplier , \"onCompleteSupplier is null\" ) ; return merge ( new FlowableMapNotification < T , Publisher < ? extends R > > ( this , onNextMapper , onErrorMapper , onCompleteSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the results of a specified function to the pair of values emitted by the source Publisher and a specified collection Publisher while limiting the maximum number of concurrent subscriptions to these Publishers . <! -- <p > -- > <! -- <img width = 640 height = 390 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / mergeMap . r . png alt = > -- > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The upstream Flowable is consumed in a bounded manner ( up to { @code maxConcurrency } outstanding request amount for items ) . The inner { @code Publisher } s are expected to honor backpressure ; if violated the operator <em > may< / em > signal { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code flatMap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Flowable < R > flatMap ( final Function < ? super T , ? extends Publisher < ? extends U > > mapper , final BiFunction < ? super T , ? super U , ? extends R > combiner , boolean delayErrors , int maxConcurrency , int bufferSize ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . requireNonNull ( combiner , \"combiner is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return flatMap ( FlowableInternalHelper . flatMapWithCombiner ( mapper , combiner ) , delayErrors , maxConcurrency , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Flowable into CompletableSources subscribes to them and waits until the upstream and all CompletableSources complete . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the upstream in an unbounded manner . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable flatMapCompletable ( Function < ? super T , ? extends CompletableSource > mapper ) { return flatMapCompletable ( mapper , false , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Flowable into CompletableSources subscribes to them and waits until the upstream and all CompletableSources complete optionally delaying all errors . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > If { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable flatMapCompletable ( Function < ? super T , ? extends CompletableSource > mapper , boolean delayErrors , int maxConcurrency ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; return RxJavaPlugins . onAssembly ( new FlowableFlatMapCompletableCompletable < T > ( this , mapper , delayErrors , maxConcurrency ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Flowable into MaybeSources subscribes to all of them and merges their onSuccess values in no particular order into a single Flowable sequence . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the upstream in an unbounded manner . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > flatMapMaybe ( Function < ? super T , ? extends MaybeSource < ? extends R > > mapper ) { return flatMapMaybe ( mapper , false , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Flowable into SingleSources subscribes to all of them and merges their onSuccess values in no particular order into a single Flowable sequence . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the upstream in an unbounded manner . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > flatMapSingle ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper ) { return flatMapSingle ( mapper , false , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps each element of the upstream Flowable into SingleSources subscribes to at most { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > flatMapSingle ( Function < ? super T , ? extends SingleSource < ? extends R > > mapper , boolean delayErrors , int maxConcurrency ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; ObjectHelper . verifyPositive ( maxConcurrency , \"maxConcurrency\" ) ; return RxJavaPlugins . onAssembly ( new FlowableFlatMapSingle < T , R > ( this , mapper , delayErrors , maxConcurrency ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the { @link Publisher } and receives notifications for each element . <p > Alias to { @link #subscribe ( Consumer ) } <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code forEach } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . NONE ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable forEach ( Consumer < ? super T > onNext ) { return subscribe ( onNext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the { @link Publisher } and receives notifications for each element until the onNext Predicate returns false . <p > If the Flowable emits an error it is wrapped into an { @link io . reactivex . exceptions . OnErrorNotImplementedException OnErrorNotImplementedException } and routed to the RxJavaPlugins . onError handler . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code forEachWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . NONE ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable forEachWhile ( Predicate < ? super T > onNext ) { return forEachWhile ( onNext , Functions . ON_ERROR_MISSING , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the { @link Publisher } and receives notifications for each element and error events until the onNext Predicate returns false . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code forEachWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . NONE ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable forEachWhile ( Predicate < ? super T > onNext , Consumer < ? super Throwable > onError ) { return forEachWhile ( onNext , onError , Functions . EMPTY_ACTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the { @link Publisher } and receives notifications for each element and the terminal events until the onNext Predicate returns false . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code forEachWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . NONE ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable forEachWhile ( final Predicate < ? super T > onNext , final Consumer < ? super Throwable > onError , final Action onComplete ) { ObjectHelper . requireNonNull ( onNext , \"onNext is null\" ) ; ObjectHelper . requireNonNull ( onError , \"onError is null\" ) ; ObjectHelper . requireNonNull ( onComplete , \"onComplete is null\" ) ; ForEachWhileSubscriber < T > s = new ForEachWhileSubscriber < T > ( onNext , onError , onComplete ) ; subscribe ( s ) ; return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Groups the items emitted by a { @code Publisher } according to a specified criterion and emits these grouped items as { @link GroupedFlowable } s . The emitted { @code GroupedPublisher } allows only a single { @link Subscriber } during its lifetime and if this { @code Subscriber } cancels before the source terminates the next emission by the source having the same key will trigger a new { @code GroupedPublisher } emission . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / groupBy . png alt = > <p > <em > Note : < / em > A { @link GroupedFlowable } will cache the items it is to emit until such time as it is subscribed to . For this reason in order to avoid memory leaks you should not simply ignore those { @code GroupedPublisher } s that do not concern you . Instead you can signal to them that they may discard their buffers by applying an operator like { @link #ignoreElements } to them . <p > Note that the { @link GroupedFlowable } s should be subscribed to as soon as possible otherwise the unconsumed groups may starve other groups due to the internal backpressure coordination of the { @code groupBy } operator . Such hangs can be usually avoided by using { @link #flatMap ( Function int ) } or { @link #concatMapEager ( Function int int ) } and overriding the default maximum concurrency value to be greater or equal to the expected number of groups possibly using { @code Integer . MAX_VALUE } if the number of expected groups is unknown . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K > Flowable < GroupedFlowable < K , T > > groupBy ( Function < ? super T , ? extends K > keySelector ) { return groupBy ( keySelector , Functions . < T > identity ( ) , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Groups the items emitted by a { @code Publisher } according to a specified criterion and emits these grouped items as { @link GroupedFlowable } s . The emitted { @code GroupedPublisher } allows only a single { @link Subscriber } during its lifetime and if this { @code Subscriber } cancels before the source terminates the next emission by the source having the same key will trigger a new { @code GroupedPublisher } emission . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / groupBy . png alt = > <p > <em > Note : < / em > A { @link GroupedFlowable } will cache the items it is to emit until such time as it is subscribed to . For this reason in order to avoid memory leaks you should not simply ignore those { @code GroupedPublisher } s that do not concern you . Instead you can signal to them that they may discard their buffers by applying an operator like { @link #ignoreElements } to them . <p > Note that the { @link GroupedFlowable } s should be subscribed to as soon as possible otherwise the unconsumed groups may starve other groups due to the internal backpressure coordination of the { @code groupBy } operator . Such hangs can be usually avoided by using { @link #flatMap ( Function int ) } or { @link #concatMapEager ( Function int int ) } and overriding the default maximum concurrency value to be greater or equal to the expected number of groups possibly using { @code Integer . MAX_VALUE } if the number of expected groups is unknown . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K , V > Flowable < GroupedFlowable < K , V > > groupBy ( Function < ? super T , ? extends K > keySelector , Function < ? super T , ? extends V > valueSelector ) { return groupBy ( keySelector , valueSelector , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Groups the items emitted by a { @code Publisher } according to a specified criterion and emits these grouped items as { @link GroupedFlowable } s . The emitted { @code GroupedPublisher } allows only a single { @link Subscriber } during its lifetime and if this { @code Subscriber } cancels before the source terminates the next emission by the source having the same key will trigger a new { @code GroupedPublisher } emission . <p > <img width = 640 height = 360 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / groupBy . png alt = > <p > <em > Note : < / em > A { @link GroupedFlowable } will cache the items it is to emit until such time as it is subscribed to . For this reason in order to avoid memory leaks you should not simply ignore those { @code GroupedPublisher } s that do not concern you . Instead you can signal to them that they may discard their buffers by applying an operator like { @link #ignoreElements } to them . <p > Note that the { @link GroupedFlowable } s should be subscribed to as soon as possible otherwise the unconsumed groups may starve other groups due to the internal backpressure coordination of the { @code groupBy } operator . Such hangs can be usually avoided by using { @link #flatMap ( Function int ) } or { @link #concatMapEager ( Function int int ) } and overriding the default maximum concurrency value to be greater or equal to the expected number of groups possibly using { @code Integer . MAX_VALUE } if the number of expected groups is unknown . [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K , V > Flowable < GroupedFlowable < K , V > > groupBy ( Function < ? super T , ? extends K > keySelector , Function < ? super T , ? extends V > valueSelector , boolean delayError , int bufferSize ) { ObjectHelper . requireNonNull ( keySelector , \"keySelector is null\" ) ; ObjectHelper . requireNonNull ( valueSelector , \"valueSelector is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new FlowableGroupBy < T , K , V > ( this , keySelector , valueSelector , bufferSize , delayError , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hides the identity of this Flowable and its Subscription . <p > Allows hiding extra features such as { @link Processor } s { @link Subscriber } methods or preventing certain identity - based optimizations ( fusion ) . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator is a pass - through for backpressure the behavior is determined by the upstream s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code hide } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > @return the new Flowable instance [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > hide ( ) { return RxJavaPlugins . onAssembly ( new FlowableHide < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ignores all items emitted by the source Publisher and only calls { @code onComplete } or { @code onError } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / ignoreElements . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator ignores backpressure as it doesn t emit any elements and consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code ignoreElements } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable ignoreElements ( ) { return RxJavaPlugins . onAssembly ( new FlowableIgnoreElementsCompletable < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits { @code true } if the source Publisher is empty otherwise { @code false } . <p > In Rx . Net this is negated as the { @code any } Subscriber but we renamed this in RxJava to better match Java naming idioms . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / isEmpty . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code isEmpty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < Boolean > isEmpty ( ) { return all ( Functions . alwaysFalse ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that emits the last item emitted by this Flowable or completes if this Flowable is empty . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / last . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code lastElement } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > lastElement ( ) { return RxJavaPlugins . onAssembly ( new FlowableLastMaybe < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits only the last item emitted by this Flowable or signals a { @link NoSuchElementException } if this Flowable is empty . <p > <img width = 640 height = 236 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / lastOrError . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code lastOrError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > lastOrError ( ) { return RxJavaPlugins . onAssembly ( new FlowableLastSingle < T > ( this , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Limits both the number of upstream items ( after which the sequence completes ) and the total downstream request amount requested from the upstream to possibly prevent the creation of excess items by the upstream . <p > The operator requests at most the given { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ CheckReturnValue public final Flowable < T > limit ( long count ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } return RxJavaPlugins . onAssembly ( new FlowableLimit < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that represents all of the emissions <em > and< / em > notifications from the source Publisher into emissions marked with their original types within { @link Notification } objects . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / materialize . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and expects it from the source { @code Publisher } . If this expectation is violated the operator <em > may< / em > throw an { @code IllegalStateException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code materialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < Notification < T > > materialize ( ) { return RxJavaPlugins . onAssembly ( new FlowableMaterialize < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens this and another Publisher into a single Publisher without any transformation . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > You can combine items emitted by multiple Publishers so that they appear as a single Publisher by using the { @code mergeWith } method . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . This and the other { @code Publisher } s are expected to honor backpressure ; if violated the operator <em > may< / em > signal { @code MissingBackpressureException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code mergeWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > mergeWith ( Publisher < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return merge ( this , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the sequence of items of this Flowable with the success value of the other SingleSource . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > The success value of the other { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > mergeWith ( @ NonNull SingleSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableMergeWithSingle < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the sequence of items of this Flowable with the success value of the other MaybeSource or waits for both to complete normally if the MaybeSource is empty . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / merge . png alt = > <p > The success value of the other { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > mergeWith ( @ NonNull MaybeSource < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableMergeWithMaybe < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies a Publisher to perform its emissions and notifications on a specified { @link Scheduler } asynchronously with a bounded buffer of { @link #bufferSize () } slots . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > observeOn ( Scheduler scheduler ) { return observeOn ( scheduler , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Publisher that is emitting items faster than its Subscriber can consume them to buffer these items indefinitely until they can be emitted . <p > <img width = 640 height = 300 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / bp . obp . buffer . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . not applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onBackpressureBuffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > onBackpressureBuffer ( ) { return onBackpressureBuffer ( bufferSize ( ) , false , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Publisher that is emitting items faster than its Subscriber can consume them to buffer up to a given amount of items until they can be emitted . The resulting Publisher will signal a { @code BufferOverflowException } via { @code onError } as soon as the buffer s capacity is exceeded dropping all undelivered items and canceling the source . <p > <img width = 640 height = 300 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / bp . obp . buffer . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . not applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onBackpressureBuffer } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > onBackpressureBuffer ( int capacity ) { return onBackpressureBuffer ( capacity , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Publisher that is emitting items faster than its Subscriber can consume them to discard rather than emit those items that its Subscriber is not prepared to observe . <p > <img width = 640 height = 245 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / bp . obp . drop . png alt = > <p > If the downstream request count hits 0 then the Publisher will refrain from calling { @code onNext } until the Subscriber invokes { @code request ( n ) } again to increase the request count . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . not applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onBackpressureDrop } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > onBackpressureDrop ( ) { return RxJavaPlugins . onAssembly ( new FlowableOnBackpressureDrop < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Publisher that is emitting items faster than its Subscriber can consume them to discard rather than emit those items that its Subscriber is not prepared to observe . <p > <img width = 640 height = 245 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / bp . obp . drop . png alt = > <p > If the downstream request count hits 0 then the Publisher will refrain from calling { @code onNext } until the Subscriber invokes { @code request ( n ) } again to increase the request count . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . not applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onBackpressureDrop } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > onBackpressureDrop ( Consumer < ? super T > onDrop ) { ObjectHelper . requireNonNull ( onDrop , \"onDrop is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableOnBackpressureDrop < T > ( this , onDrop ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instructs a Publisher to pass control to another Publisher rather than invoking { @link Subscriber#onError onError } if it encounters an error . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / onErrorResumeNext . png alt = > <p > By default when a Publisher encounters an error that prevents it from emitting the expected item to its { @link Subscriber } the Publisher invokes its Subscriber s { @code onError } method and then quits without invoking any more of its Subscriber s methods . The { @code onErrorResumeNext } method changes this behavior . If you pass a function that returns a Publisher ( { @code resumeFunction } ) to { @code onErrorResumeNext } if the original Publisher encounters an error instead of invoking its Subscriber s { @code onError } method it will instead relinquish control to the Publisher returned from { @code resumeFunction } which will invoke the Subscriber s { @link Subscriber#onNext onNext } method if it is able to do so . In such a case because no Publisher necessarily invokes { @code onError } the Subscriber may never know that an error happened . <p > You can use this to prevent errors from propagating or to supply fallback data should errors be encountered . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . This and the resuming { @code Publisher } s are expected to honor backpressure as well . If any of them violate this expectation the operator <em > may< / em > throw an { @code IllegalStateException } when the source { @code Publisher } completes or a { @code MissingBackpressureException } is signaled somewhere downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code onErrorResumeNext } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > onErrorResumeNext ( Function < ? super Throwable , ? extends Publisher < ? extends T > > resumeFunction ) { ObjectHelper . requireNonNull ( resumeFunction , \"resumeFunction is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableOnErrorNext < T > ( this , resumeFunction , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Nulls out references to the upstream producer and downstream Subscriber if the sequence is terminated or downstream cancels . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > onTerminateDetach ( ) { return RxJavaPlugins . onAssembly ( new FlowableDetach < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parallelizes the flow by creating multiple rails ( equal to the number of CPUs ) and dispatches the upstream items to them in a round - robin fashion . <p > Note that the rails don t execute in parallel on their own and one needs to apply { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ CheckReturnValue public final ParallelFlowable < T > parallel ( ) { return ParallelFlowable . from ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parallelizes the flow by creating the specified number of rails and dispatches the upstream items to them in a round - robin fashion . <p > Note that the rails don t execute in parallel on their own and one needs to apply { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) @ CheckReturnValue public final ParallelFlowable < T > parallel ( int parallelism ) { ObjectHelper . verifyPositive ( parallelism , \"parallelism\" ) ; return ParallelFlowable . from ( this , parallelism ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableFlowable } which is a variety of Publisher that waits until its { @link ConnectableFlowable#connect connect } method is called before it begins emitting items to those { @link Subscriber } s that have subscribed to it . <p > <img width = 640 height = 510 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / publishConnect . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { @code ConnectableFlowable } honors backpressure for each of its { @code Subscriber } s and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator will signal a { @code MissingBackpressureException } to its { @code Subscriber } s and disconnect . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code publish } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final ConnectableFlowable < T > publish ( ) { return publish ( bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the results of invoking a specified selector on items emitted by a { @link ConnectableFlowable } that shares a single subscription to the underlying sequence . <p > <img width = 640 height = 510 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / publishConnect . f . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator expects the source { @code Publisher } to honor backpressure and if this expectation is violated the operator will signal a { @code MissingBackpressureException } through the { @code Publisher } provided to the function . Since the { @code Publisher } returned by the { @code selector } may be independent of the provided { @code Publisher } to the function the output s backpressure behavior is determined by this returned { @code Publisher } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code publish } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > publish ( Function < ? super Flowable < T > , ? extends Publisher < R > > selector ) { return publish ( selector , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableFlowable } which is a variety of Publisher that waits until its { @link ConnectableFlowable#connect connect } method is called before it begins emitting items to those { @link Subscriber } s that have subscribed to it . <p > <img width = 640 height = 510 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / publishConnect . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The returned { @code ConnectableFlowable } honors backpressure for each of its { @code Subscriber } s and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator will signal a { @code MissingBackpressureException } to its { @code Subscriber } s and disconnect . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code publish } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final ConnectableFlowable < T > publish ( int bufferSize ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return FlowablePublish . create ( this , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests { @code n } initially from the upstream and then 75% of { @code n } subsequently after 75% of { @code n } values have been emitted to the downstream . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > rebatchRequests ( int n ) { return observeOn ( ImmediateThinScheduler . INSTANCE , true , n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that applies a specified accumulator function to the first item emitted by a source Publisher then feeds the result of that function along with the second item emitted by the source Publisher into the same function and so on until all items have been emitted by the finite source Publisher and emits the final result from the final call to your function as its sole item . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / reduce . png alt = > <p > This technique which is called reduce here is sometimes called aggregate fold accumulate compress or inject in other programming contexts . Groovy for instance has an { @code inject } method that does a similar operation on lists . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulator object to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure of its downstream consumer and consumes the upstream source in unbounded mode . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code reduce } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > reduce ( BiFunction < T , T , T > reducer ) { ObjectHelper . requireNonNull ( reducer , \"reducer is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableReduceMaybe < T > ( this , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that applies a specified accumulator function to the first item emitted by a source Publisher and a specified seed value then feeds the result of that function along with the second item emitted by a Publisher into the same function and so on until all items have been emitted by the finite source Publisher emitting the final result from the final call to your function as its sole item . <p > <img width = 640 height = 325 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / reduceSeed . png alt = > <p > This technique which is called reduce here is sometimes called aggregate fold accumulate compress or inject in other programming contexts . Groovy for instance has an { @code inject } method that does a similar operation on lists . <p > Note that the { @code seed } is shared among all subscribers to the resulting Publisher and may cause problems if it is mutable . To make sure each subscriber gets its own value defer the application of this operator via { @link #defer ( Callable ) } : <pre > <code > Publisher&lt ; T&gt ; source = ... Single . defer (( ) - &gt ; source . reduce ( new ArrayList&lt ; &gt ; () ( list item ) - &gt ; list . add ( item ))) ; [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > reduce ( R seed , BiFunction < R , ? super T , R > reducer ) { ObjectHelper . requireNonNull ( seed , \"seed is null\" ) ; ObjectHelper . requireNonNull ( reducer , \"reducer is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableReduceSeedSingle < T , R > ( this , seed , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that applies a specified accumulator function to the first item emitted by a source Publisher and a seed value derived from calling a specified seedSupplier then feeds the result of that function along with the second item emitted by a Publisher into the same function and so on until all items have been emitted by the finite source Publisher emitting the final result from the final call to your function as its sole item . <p > <img width = 640 height = 325 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / reduceSeed . png alt = > <p > This technique which is called reduce here is sometimes called aggregate fold accumulate compress or inject in other programming contexts . Groovy for instance has an { @code inject } method that does a similar operation on lists . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulator object to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure of its downstream consumer and consumes the upstream source in unbounded mode . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code reduceWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Single < R > reduceWith ( Callable < R > seedSupplier , BiFunction < R , ? super T , R > reducer ) { ObjectHelper . requireNonNull ( seedSupplier , \"seedSupplier is null\" ) ; ObjectHelper . requireNonNull ( reducer , \"reducer is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableReduceWithSingle < T , R > ( this , seedSupplier , reducer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that repeats the sequence of items emitted by the source Publisher indefinitely . <p > <img width = 640 height = 309 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeat . o . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator <em > may< / em > throw an { @code IllegalStateException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeat } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > repeat ( ) { return repeat ( Long . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that repeats the sequence of items emitted by the source Publisher at most { @code count } times . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / repeat . on . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator <em > may< / em > throw an { @code IllegalStateException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code repeat } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > repeat ( long times ) { if ( times < 0 ) { throw new IllegalArgumentException ( \"times >= 0 required but it was \" + times ) ; } if ( times == 0 ) { return empty ( ) ; } return RxJavaPlugins . onAssembly ( new FlowableRepeat < T > ( this , times ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableFlowable } that shares a single subscription to the underlying Publisher that will replay all of its items and notifications to any future { @link Subscriber } . A Connectable Publisher resembles an ordinary Publisher except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator supports backpressure . Note that the upstream requests are determined by the child Subscriber which requests the largest amount : i . e . two child Subscribers with requests of 10 and 100 will request 100 elements from the underlying Publisher sequence . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final ConnectableFlowable < T > replay ( ) { return FlowableReplay . createFrom ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits items that are the results of invoking a specified selector on items emitted by a { @link ConnectableFlowable } that shares a single subscription to the source Publisher replaying no more than { @code bufferSize } items that were emitted within a specified time window . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . fnt . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator supports backpressure . Note that the upstream requests are determined by the child Subscriber which requests the largest amount : i . e . two child Subscribers with requests of 10 and 100 will request 100 elements from the underlying Publisher sequence . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final < R > Flowable < R > replay ( Function < ? super Flowable < T > , ? extends Publisher < R > > selector , int bufferSize , long time , TimeUnit unit ) { return replay ( selector , bufferSize , time , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits items that are the results of invoking a specified selector on items emitted by a { @link ConnectableFlowable } that shares a single subscription to the source Publisher . <p > <img width = 640 height = 445 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . fs . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator supports backpressure . Note that the upstream requests are determined by the child Subscriber which requests the largest amount : i . e . two child Subscribers with requests of 10 and 100 will request 100 elements from the underlying Publisher sequence . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final < R > Flowable < R > replay ( final Function < ? super Flowable < T > , ? extends Publisher < R > > selector , final Scheduler scheduler ) { ObjectHelper . requireNonNull ( selector , \"selector is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return FlowableReplay . multicastSelector ( FlowableInternalHelper . replayCallable ( this ) , FlowableInternalHelper . replayFunction ( selector , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableFlowable } that shares a single subscription to the source Publisher that replays at most { @code bufferSize } items emitted by that Publisher . A Connectable Publisher resembles an ordinary Publisher except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . n . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator supports backpressure . Note that the upstream requests are determined by the child Subscriber which requests the largest amount : i . e . two child Subscribers with requests of 10 and 100 will request 100 elements from the underlying Publisher sequence . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final ConnectableFlowable < T > replay ( final int bufferSize ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return FlowableReplay . create ( this , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableFlowable } that shares a single subscription to the source Publisher and replays at most { @code bufferSize } items that were emitted during a specified time window . A Connectable Publisher resembles an ordinary Publisher except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . nt . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator supports backpressure . Note that the upstream requests are determined by the child Subscriber which requests the largest amount : i . e . two child Subscribers with requests of 10 and 100 will request 100 elements from the underlying Publisher sequence . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code replay } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final ConnectableFlowable < T > replay ( int bufferSize , long time , TimeUnit unit ) { return replay ( bufferSize , time , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableFlowable } that shares a single subscription to the source Publisher and that replays a maximum of { @code bufferSize } items that are emitted within a specified time window . A Connectable Publisher resembles an ordinary Publisher except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . nts . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator supports backpressure . Note that the upstream requests are determined by the child Subscriber which requests the largest amount : i . e . two child Subscribers with requests of 10 and 100 will request 100 elements from the underlying Publisher sequence . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final ConnectableFlowable < T > replay ( final int bufferSize , final long time , final TimeUnit unit , final Scheduler scheduler ) { ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return FlowableReplay . create ( this , time , unit , scheduler , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ConnectableFlowable } that shares a single subscription to the source Publisher and replays at most { @code bufferSize } items emitted by that Publisher . A Connectable Publisher resembles an ordinary Publisher except that it does not begin emitting items when it is subscribed to but only when its { @code connect } method is called . <p > Note that due to concurrency requirements { @code replay ( bufferSize ) } may hold strong references to more than { @code bufferSize } source emissions . <p > <img width = 640 height = 515 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / replay . ns . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator supports backpressure . Note that the upstream requests are determined by the child Subscriber which requests the largest amount : i . e . two child Subscribers with requests of 10 and 100 will request 100 elements from the underlying Publisher sequence . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final ConnectableFlowable < T > replay ( final int bufferSize , final Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return FlowableReplay . observeOn ( replay ( bufferSize ) , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher resubscribing to it if it calls { @code onError } ( infinite retry count ) . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . png alt = > <p > If the source Publisher calls { @link Subscriber#onError } this method will resubscribe to the source Publisher rather than propagating the { @code onError } call . <p > Any and all items emitted by the source Publisher will be emitted by the resulting Publisher even those emitted during failed subscriptions . For example if a Publisher fails at first but emits { @code [ 1 2 ] } then succeeds the second time and emits { @code [ 1 2 3 4 5 ] } then the complete sequence of emissions and notifications would be { @code [ 1 2 1 2 3 4 5 onComplete ] } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator <em > may< / em > throw an { @code IllegalStateException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > retry ( ) { return retry ( Long . MAX_VALUE , Functions . alwaysTrue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher resubscribing to it if it calls { @code onError } up to a specified number of retries . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / retry . png alt = > <p > If the source Publisher calls { @link Subscriber#onError } this method will resubscribe to the source Publisher for a maximum of { @code count } resubscriptions rather than propagating the { @code onError } call . <p > Any and all items emitted by the source Publisher will be emitted by the resulting Publisher even those emitted during failed subscriptions . For example if a Publisher fails at first but emits { @code [ 1 2 ] } then succeeds the second time and emits { @code [ 1 2 3 4 5 ] } then the complete sequence of emissions and notifications would be { @code [ 1 2 1 2 3 4 5 onComplete ] } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator <em > may< / em > throw an { @code IllegalStateException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > retry ( long count ) { return retry ( count , Functions . alwaysTrue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retries the current Flowable if the predicate returns true . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator <em > may< / em > throw an { @code IllegalStateException } . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code retry } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > retry ( Predicate < ? super Throwable > predicate ) { return retry ( Long . MAX_VALUE , predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to the current Flowable and wraps the given Subscriber into a SafeSubscriber ( if not already a SafeSubscriber ) that deals with exceptions thrown by a misbehaving Subscriber ( that doesn t follow the Reactive - Streams specification ) . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator leaves the reactive world and the backpressure behavior depends on the Subscriber s behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final void safeSubscribe ( Subscriber < ? super T > s ) { ObjectHelper . requireNonNull ( s , \"s is null\" ) ; if ( s instanceof SafeSubscriber ) { subscribe ( ( SafeSubscriber < ? super T > ) s ) ; } else { subscribe ( new SafeSubscriber < T > ( s ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the most recently emitted item ( if any ) emitted by the source Publisher within periodic time intervals . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sample . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code sample } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < T > sample ( long period , TimeUnit unit ) { return sample ( period , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the most recently emitted item ( if any ) emitted by the source Publisher within periodic time intervals where the intervals are defined on a particular Scheduler . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sample . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > sample ( long period , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableSampleTimed < T > ( this , period , unit , scheduler , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that when the specified { @code sampler } Publisher emits an item or completes emits the most recently emitted item ( if any ) emitted by the source Publisher since the previous emission from the { @code sampler } Publisher . <p > <img width = 640 height = 289 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / sample . o . nolast . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses the emissions of the { @code sampler } Publisher to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code sample } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Flowable < T > sample ( Publisher < U > sampler ) { ObjectHelper . requireNonNull ( sampler , \"sampler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableSamplePublisher < T > ( this , sampler , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that applies a specified accumulator function to the first item emitted by a source Publisher and a seed value then feeds the result of that function along with the second item emitted by the source Publisher into the same function and so on until all items have been emitted by the source Publisher emitting the result of each of these iterations . <p > <img width = 640 height = 320 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / scanSeed . png alt = > <p > This sort of function is sometimes called an accumulator . <p > Note that the Publisher that results from this method will emit the value returned by the { @code seedSupplier } as its first item . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors downstream backpressure and expects the source { @code Publisher } to honor backpressure as well . Violating this expectation a { @code MissingBackpressureException } <em > may< / em > get signaled somewhere downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code scanWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > scanWith ( Callable < R > seedSupplier , BiFunction < R , ? super T , R > accumulator ) { ObjectHelper . requireNonNull ( seedSupplier , \"seedSupplier is null\" ) ; ObjectHelper . requireNonNull ( accumulator , \"accumulator is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableScanSeed < T , R > ( this , seedSupplier , accumulator ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forces a Publisher s emissions and notifications to be serialized and for it to obey <a href = http : // reactivex . io / documentation / contract . html > the Publisher contract< / a > in other ways . <p > It is possible for a Publisher to invoke its Subscribers methods asynchronously perhaps from different threads . This could make such a Publisher poorly - behaved in that it might try to invoke { @code onComplete } or { @code onError } before one of its { @code onNext } invocations or it might call { @code onNext } from two different threads concurrently . You can force such a Publisher to be well - behaved and sequential by applying the { @code serialize } method to it . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / synchronize . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code serialize } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > serialize ( ) { return RxJavaPlugins . onAssembly ( new FlowableSerialized < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @link Publisher } that multicasts ( and shares a single subscription to ) the original { @link Publisher } . As long as there is at least one { @link Subscriber } this { @link Publisher } will be subscribed and emitting data . When all subscribers have canceled it will cancel the source { @link Publisher } . <p > This is an alias for { @link #publish () } . { @link ConnectableFlowable#refCount () refCount () } . <p > <img width = 640 height = 510 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / publishRefCount . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure and expects the source { @code Publisher } to honor backpressure as well . If this expectation is violated the operator will signal a { @code MissingBackpressureException } to its { @code Subscriber } s . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code share } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > share ( ) { return publish ( ) . refCount ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Maybe that completes if this Flowable is empty signals one item if this Flowable signals exactly one item or signals an { @code IllegalArgumentException } if this Flowable signals more than one item . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / single . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code singleElement } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > singleElement ( ) { return RxJavaPlugins . onAssembly ( new FlowableSingleMaybe < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits the single item emitted by this Flowable if this Flowable emits only a single item otherwise if this Flowable completes without emitting any items a { @link NoSuchElementException } will be signaled and if this Flowable emits more than one item an { @code IllegalArgumentException } will be signaled . <p > <img width = 640 height = 205 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / singleOrError . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code singleOrError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < T > singleOrError ( ) { return RxJavaPlugins . onAssembly ( new FlowableSingleSingle < T > ( this , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that skips the first { @code count } items emitted by the source Publisher and emits the remainder . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skip . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code skip } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > skip ( long count ) { if ( count <= 0L ) { return RxJavaPlugins . onAssembly ( this ) ; } return RxJavaPlugins . onAssembly ( new FlowableSkip < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that skips values emitted by the source Publisher before a specified time window elapses . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skip . t . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t support backpressure as it uses time to skip an arbitrary number of elements and thus has to consume the source { @code Publisher } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code skip } does not operate on any particular scheduler but uses the current time from the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > skip ( long time , TimeUnit unit ) { return skipUntil ( timer ( time , unit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that skips values emitted by the source Publisher before a specified time window on a specified { @link Scheduler } elapses . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skip . ts . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t support backpressure as it uses time to skip an arbitrary number of elements and thus has to consume the source { @code Publisher } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use for the timed skipping< / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > skip ( long time , TimeUnit unit , Scheduler scheduler ) { return skipUntil ( timer ( time , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that drops a specified number of items from the end of the sequence emitted by the source Publisher . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipLast . png alt = > <p > This Subscriber accumulates a queue long enough to store the first { @code count } items . As more items are received items are taken from the front of the queue and emitted by the returned Publisher . This causes such items to be delayed . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code skipLast } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > skipLast ( int count ) { if ( count < 0 ) { throw new IndexOutOfBoundsException ( \"count >= 0 required but it was \" + count ) ; } if ( count == 0 ) { return RxJavaPlugins . onAssembly ( this ) ; } return RxJavaPlugins . onAssembly ( new FlowableSkipLast < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that drops items emitted by the source Publisher during a specified time window before the source completes . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipLast . t . png alt = > <p > Note : this action will cache the latest items arriving in the specified time window . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t support backpressure as it uses time to skip an arbitrary number of elements and thus has to consume the source { @code Publisher } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code skipLast } does not operate on any particular scheduler but uses the current time from the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > skipLast ( long time , TimeUnit unit ) { return skipLast ( time , unit , Schedulers . computation ( ) , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that drops items emitted by the source Publisher during a specified time window ( defined on a specified scheduler ) before the source completes . <p > <img width = 640 height = 340 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipLast . ts . png alt = > <p > Note : this action will cache the latest items arriving in the specified time window . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t support backpressure as it uses time to skip an arbitrary number of elements and thus has to consume the source { @code Publisher } in an unbounded manner ( i . e . no backpressure applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use for tracking the current time< / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > skipLast ( long time , TimeUnit unit , Scheduler scheduler ) { return skipLast ( time , unit , scheduler , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that skips all items emitted by the source Publisher as long as a specified condition holds true but emits all further source items as soon as the condition becomes false . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / skipWhile . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code skipWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > skipWhile ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableSkipWhile < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the events emitted by source Publisher in a sorted order . Each item emitted by the Publisher must implement { @link Comparable } with respect to all other items in the sequence . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > sorted ( ) { return toList ( ) . toFlowable ( ) . map ( Functions . listSorter ( Functions . < T > naturalComparator ( ) ) ) . flatMapIterable ( Functions . < List < T > > identity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the events emitted by source Publisher in a sorted order based on a specified comparison function . [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > sorted ( Comparator < ? super T > sortFunction ) { ObjectHelper . requireNonNull ( sortFunction , \"sortFunction\" ) ; return toList ( ) . toFlowable ( ) . map ( Functions . listSorter ( sortFunction ) ) . flatMapIterable ( Functions . < List < T > > identity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items in a specified { @link Iterable } before it begins to emit items emitted by the source Publisher . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / startWith . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The source { @code Publisher } is expected to honor backpressure as well . If it violates this rule it <em > may< / em > throw an { @code IllegalStateException } when the source { @code Publisher } completes . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code startWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > startWith ( Iterable < ? extends T > items ) { return concatArray ( fromIterable ( items ) , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the specified items before it begins to emit items emitted by the source Publisher . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / startWith . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The source { @code Publisher } is expected to honor backpressure as well . If it violates this rule it <em > may< / em > throw an { @code IllegalStateException } when the source { @code Publisher } completes . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code startWithArray } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > startWithArray ( T ... items ) { Flowable < T > fromArray = fromArray ( items ) ; if ( fromArray == empty ( ) ) { return RxJavaPlugins . onAssembly ( this ) ; } return concatArray ( fromArray , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to a Publisher and ignores { @code onNext } and { @code onComplete } emissions . <p > If the Flowable emits an error it is wrapped into an { @link io . reactivex . exceptions . OnErrorNotImplementedException OnErrorNotImplementedException } and routed to the RxJavaPlugins . onError handler . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( ) { return subscribe ( Functions . emptyConsumer ( ) , Functions . ON_ERROR_MISSING , Functions . EMPTY_ACTION , FlowableInternalHelper . RequestMax . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to a Publisher and provides a callback to handle the items it emits . <p > If the Flowable emits an error it is wrapped into an { @link io . reactivex . exceptions . OnErrorNotImplementedException OnErrorNotImplementedException } and routed to the RxJavaPlugins . onError handler . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code subscribe } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Disposable subscribe ( Consumer < ? super T > onNext ) { return subscribe ( onNext , Functions . ON_ERROR_MISSING , Functions . EMPTY_ACTION , FlowableInternalHelper . RequestMax . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Establish a connection between this Flowable and the given FlowableSubscriber and start streaming events based on the demand of the FlowableSubscriber . <p > This is a factory method and can be called multiple times each time starting a new { [CODESPLIT] @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final void subscribe ( FlowableSubscriber < ? super T > s ) { ObjectHelper . requireNonNull ( s , \"s is null\" ) ; try { Subscriber < ? super T > z = RxJavaPlugins . onSubscribe ( this , s ) ; ObjectHelper . requireNonNull ( z , \"The RxJavaPlugins.onSubscribe hook returned a null FlowableSubscriber. Please check the handler provided to RxJavaPlugins.setOnFlowableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins\" ) ; subscribeActual ( z ) ; } catch ( NullPointerException e ) { // NOPMD throw e ; } catch ( Throwable e ) { Exceptions . throwIfFatal ( e ) ; // can't call onError because no way to know if a Subscription has been set or not // can't call onSubscribe because the call might have set a Subscription already RxJavaPlugins . onError ( e ) ; NullPointerException npe = new NullPointerException ( \"Actually not, but can't throw other exceptions due to RS\" ) ; npe . initCause ( e ) ; throw npe ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes a given Subscriber ( subclass ) to this Flowable and returns the given Subscriber as is . <p > Usage example : <pre > <code > Flowable&lt ; Integer&gt ; source = Flowable . range ( 1 10 ) ; CompositeDisposable composite = new CompositeDisposable () ; [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < E extends Subscriber < ? super T > > E subscribeWith ( E subscriber ) { subscribe ( subscriber ) ; return subscriber ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously subscribes Subscribers to this Publisher on the specified { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > subscribeOn ( @ NonNull Scheduler scheduler , boolean requestOn ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableSubscribeOn < T > ( this , scheduler , requestOn ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items emitted by the source Publisher or the items of an alternate Publisher if the source Publisher is empty . <p > <img width = 640 height = 255 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchifempty . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > If the source { @code Publisher } is empty the alternate { @code Publisher } is expected to honor backpressure . If the source { @code Publisher } is non - empty it is expected to honor backpressure as instead . In either case if violated a { @code MissingBackpressureException } <em > may< / em > get signaled somewhere downstream . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchIfEmpty } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > switchIfEmpty ( Publisher < ? extends T > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableSwitchIfEmpty < T > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the upstream values into { [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Completable switchMapCompletable ( @ NonNull Function < ? super T , ? extends CompletableSource > mapper ) { ObjectHelper . requireNonNull ( mapper , \"mapper is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableSwitchMapCompletable < T > ( this , mapper , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new Publisher by applying a function that you supply to each item emitted by the source Publisher that returns a Publisher and then emitting the items emitted by the most recently emitted of these Publishers and delays any error until all Publishers terminate . <p > The resulting Publisher completes if both the upstream Publisher and the last inner Publisher if any complete . If the upstream Publisher signals an onError the termination of the last inner Publisher will emit that error as is or wrapped into a CompositeException along with the other possible errors the former inner Publishers signaled . <p > <img width = 640 height = 350 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / switchMap . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The outer { @code Publisher } is consumed in an unbounded manner ( i . e . without backpressure ) and the inner { @code Publisher } s are expected to honor backpressure but it is not enforced ; the operator won t signal a { @code MissingBackpressureException } but the violation <em > may< / em > lead to { @code OutOfMemoryError } due to internal buffer bloat . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code switchMapDelayError } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > switchMapDelayError ( Function < ? super T , ? extends Publisher < ? extends R > > mapper ) { return switchMapDelayError ( mapper , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits only the first { @code count } items emitted by the source Publisher . If the source emits fewer than { @code count } items then all of its items are emitted . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / take . png alt = > <p > This method returns a Publisher that will invoke a subscribing { @link Subscriber } s { @link Subscriber#onNext onNext } function a maximum of { @code count } times before invoking { @link Subscriber#onComplete onComplete } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior in case the first request is smaller than the { @code count } . Otherwise the source { @code Publisher } is consumed in an unbounded manner ( i . e . without applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code take } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) // may trigger UNBOUNDED_IN @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > take ( long count ) { if ( count < 0 ) { throw new IllegalArgumentException ( \"count >= 0 required but it was \" + count ) ; } return RxJavaPlugins . onAssembly ( new FlowableTake < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits those items emitted by source Publisher before a specified time runs out . <p > If time runs out before the { @code Flowable } completes normally the { @code onComplete } event will be signaled on the default { @code computation } { @link Scheduler } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / take . t . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code take } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < T > take ( long time , TimeUnit unit ) { return takeUntil ( timer ( time , unit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits those items emitted by source Publisher before a specified time ( on a specified Scheduler ) runs out . <p > If time runs out before the { @code Flowable } completes normally the { @code onComplete } event will be signaled on the provided { @link Scheduler } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / take . ts . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > take ( long time , TimeUnit unit , Scheduler scheduler ) { return takeUntil ( timer ( time , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits at most the last { @code count } items emitted by the source Publisher . If the source emits fewer than { @code count } items then all of its items are emitted . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeLast . n . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream if the { @code count } is non - zero ; ignores backpressure if the { @code count } is zero as it doesn t signal any values . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code takeLast } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > takeLast ( int count ) { if ( count < 0 ) { throw new IndexOutOfBoundsException ( \"count >= 0 required but it was \" + count ) ; } else if ( count == 0 ) { return RxJavaPlugins . onAssembly ( new FlowableIgnoreElements < T > ( this ) ) ; } else if ( count == 1 ) { return RxJavaPlugins . onAssembly ( new FlowableTakeLastOne < T > ( this ) ) ; } return RxJavaPlugins . onAssembly ( new FlowableTakeLast < T > ( this , count ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits at most a specified number of items from the source Publisher that were emitted in a specified window of time before the Publisher completed . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeLast . tn . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code takeLast } does not operate on any particular scheduler but uses the current time from the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > takeLast ( long count , long time , TimeUnit unit ) { return takeLast ( count , time , unit , Schedulers . computation ( ) , false , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits at most a specified number of items from the source Publisher that were emitted in a specified window of time before the Publisher completed where the timing information is provided by a given Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeLast . tns . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use for tracking the current time< / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > takeLast ( long count , long time , TimeUnit unit , Scheduler scheduler , boolean delayError , int bufferSize ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; if ( count < 0 ) { throw new IndexOutOfBoundsException ( \"count >= 0 required but it was \" + count ) ; } return RxJavaPlugins . onAssembly ( new FlowableTakeLastTimed < T > ( this , count , time , unit , scheduler , bufferSize , delayError ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items from the source Publisher that were emitted in a specified window of time before the Publisher completed where the timing information is provided by a specified Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeLast . ts . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . no backpressure is applied to it ) but note that this <em > may< / em > lead to { @code OutOfMemoryError } due to internal buffer bloat . Consider using { @link #takeLast ( long long TimeUnit Scheduler ) } in this case . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > takeLast ( long time , TimeUnit unit , Scheduler scheduler , boolean delayError , int bufferSize ) { return takeLast ( Long . MAX_VALUE , time , unit , scheduler , delayError , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits items emitted by the source Publisher checks the specified predicate for each item and then completes when the condition is satisfied . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeUntil . p . png alt = > <p > The difference between this operator and { @link #takeWhile ( Predicate ) } is that here the condition is evaluated <em > after< / em > the item is emitted . [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > takeUntil ( Predicate < ? super T > stopPredicate ) { ObjectHelper . requireNonNull ( stopPredicate , \"stopPredicate is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableTakeUntilPredicate < T > ( this , stopPredicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits the items emitted by the source Publisher until a second Publisher emits an item . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeUntil . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code takeUntil } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Flowable < T > takeUntil ( Publisher < U > other ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableTakeUntil < T , U > ( this , other ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits items emitted by the source Publisher so long as each item satisfied a specified condition and then completes as soon as this condition is not satisfied . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / takeWhile . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code takeWhile } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > takeWhile ( Predicate < ? super T > predicate ) { ObjectHelper . requireNonNull ( predicate , \"predicate is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableTakeWhile < T > ( this , predicate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits only the first item emitted by the source Publisher during sequential time windows of a specified duration . <p > This differs from { @link #throttleLast } in that this only tracks the passage of time whereas { @link #throttleLast } ticks at scheduled intervals . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleFirst . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code throttleFirst } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < T > throttleFirst ( long windowDuration , TimeUnit unit ) { return throttleFirst ( windowDuration , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits only the last item emitted by the source Publisher during sequential time windows of a specified duration . <p > This differs from { @link #throttleFirst } in that this ticks along at a scheduled interval whereas { @link #throttleFirst } does not tick it just tracks the passage of time . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleLast . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code throttleLast } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < T > throttleLast ( long intervalDuration , TimeUnit unit ) { return sample ( intervalDuration , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits only the last item emitted by the source Publisher during sequential time windows of a specified duration where the duration is governed by a specified Scheduler . <p > This differs from { @link #throttleFirst } in that this ticks along at a scheduled interval whereas { @link #throttleFirst } does not tick it just tracks the passage of time . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleLast . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > throttleLast ( long intervalDuration , TimeUnit unit , Scheduler scheduler ) { return sample ( intervalDuration , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher except that it drops items emitted by the source Publisher that are followed by newer items before a timeout value expires on a specified Scheduler . The timer resets on each emission ( alias to { @link #debounce ( long TimeUnit Scheduler ) } ) . <p > <em > Note : < / em > If items keep being emitted by the source Publisher faster than the timeout then no items will be emitted by the resulting Publisher . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / throttleWithTimeout . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > This operator does not support backpressure as it uses time to control data flow . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > throttleWithTimeout ( long timeout , TimeUnit unit , Scheduler scheduler ) { return debounce ( timeout , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits records of the time interval between consecutive items emitted by the source Publisher . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeInterval . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code timeInterval } does not operate on any particular scheduler but uses the current time from the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < Timed < T > > timeInterval ( TimeUnit unit ) { return timeInterval ( unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits records of the time interval between consecutive items emitted by the source Publisher where this interval is computed on a specified Scheduler . <p > <img width = 640 height = 315 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeInterval . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > The operator does not operate on any particular scheduler but uses the current time from the specified { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) // Supplied scheduler is only used for creating timestamps. public final Flowable < Timed < T > > timeInterval ( TimeUnit unit , Scheduler scheduler ) { ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableTimeInterval < T > ( this , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher but notifies Subscribers of a { @code TimeoutException } if an item emitted by the source Publisher doesn t arrive within a window of time after the emission of the previous item where that period of time is measured by a Publisher that is a function of the previous item . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout3 . png alt = > <p > Note : The arrival of the first source item is never timed out . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . The { @code Publisher } sources are expected to honor backpressure as well . If any of the source { @code Publisher } s violate this it <em > may< / em > throw an { @code IllegalStateException } when the source { @code Publisher } completes . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code timeout } operates by default on the { @code immediate } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < V > Flowable < T > timeout ( Function < ? super T , ? extends Publisher < V > > itemTimeoutIndicator ) { return timeout0 ( null , itemTimeoutIndicator , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher but applies a timeout policy for each emitted item . If the next item isn t emitted within the specified timeout duration starting from its predecessor the resulting Publisher terminates and notifies Subscribers of a { @code TimeoutException } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 1 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code timeout } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < T > timeout ( long timeout , TimeUnit timeUnit ) { return timeout0 ( timeout , timeUnit , null , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher but applies a timeout policy for each emitted item where this policy is governed by a specified Scheduler . If the next item isn t emitted within the specified timeout duration starting from its predecessor the resulting Publisher terminates and notifies Subscribers of a { @code TimeoutException } . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout . 1s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > timeout ( long timeout , TimeUnit timeUnit , Scheduler scheduler ) { return timeout0 ( timeout , timeUnit , null , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that mirrors the source Publisher but notifies Subscribers of a { @code TimeoutException } if either the first item emitted by the source Publisher or any subsequent item doesn t arrive within time windows defined by other Publishers . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timeout5 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream . Both this and the returned { @code Publisher } s are expected to honor backpressure as well . If any of then violates this rule it <em > may< / em > throw an { @code IllegalStateException } when the { @code Publisher } completes . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code timeout } does not operate by default on any { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Flowable < T > timeout ( Publisher < U > firstTimeoutIndicator , Function < ? super T , ? extends Publisher < V > > itemTimeoutIndicator ) { ObjectHelper . requireNonNull ( firstTimeoutIndicator , \"firstTimeoutIndicator is null\" ) ; return timeout0 ( firstTimeoutIndicator , itemTimeoutIndicator , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits each item emitted by the source Publisher wrapped in a { @link Timed } object whose timestamps are provided by a specified Scheduler . <p > <img width = 640 height = 310 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / timestamp . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This operator does not operate on any particular scheduler but uses the current time from the specified { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . NONE ) // Supplied scheduler is only used for creating timestamps. public final Flowable < Timed < T > > timestamp ( Scheduler scheduler ) { return timestamp ( TimeUnit . MILLISECONDS , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the specified converter function during assembly time and returns its resulting value . <p > This allows fluent conversion to any other type . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The backpressure behavior depends on what happens in the { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . SPECIAL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > R to ( Function < ? super Flowable < T > , R > converter ) { try { return ObjectHelper . requireNonNull ( converter , \"converter is null\" ) . apply ( this ) ; } catch ( Throwable ex ) { Exceptions . throwIfFatal ( ex ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a single item a list composed of all the items emitted by the finite upstream source Publisher . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toList . png alt = > <p > Normally a Publisher that returns multiple items will do so by invoking its { @link Subscriber } s { @link Subscriber#onNext onNext } method for each such item . You can change this behavior instructing the Publisher to compose a list of all of these items and then to invoke the Subscriber s { @code onNext } function once passing it the entire list by calling the Publisher s { @code toList } method prior to calling its { @link #subscribe } method . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulated list to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toList } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < List < T > > toList ( ) { return RxJavaPlugins . onAssembly ( new FlowableToListSingle < T , List < T > > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a single item a list composed of all the items emitted by the finite source Publisher . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toList . png alt = > <p > Normally a Publisher that returns multiple items will do so by invoking its { @link Subscriber } s { @link Subscriber#onNext onNext } method for each such item . You can change this behavior instructing the Publisher to compose a list of all of these items and then to invoke the Subscriber s { @code onNext } function once passing it the entire list by calling the Publisher s { @code toList } method prior to calling its { @link #subscribe } method . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulated list to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toList } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < List < T > > toList ( final int capacityHint ) { ObjectHelper . verifyPositive ( capacityHint , \"capacityHint\" ) ; return RxJavaPlugins . onAssembly ( new FlowableToListSingle < T , List < T > > ( this , Functions . < T > createArrayList ( capacityHint ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a single item a list composed of all the items emitted by the finite source Publisher . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toList . png alt = > <p > Normally a Publisher that returns multiple items will do so by invoking its { @link Subscriber } s { @link Subscriber#onNext onNext } method for each such item . You can change this behavior instructing the Publisher to compose a list of all of these items and then to invoke the Subscriber s { @code onNext } function once passing it the entire list by calling the Publisher s { @code toList } method prior to calling its { @link #subscribe } method . <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulated collection to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toList } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U extends Collection < ? super T > > Single < U > toList ( Callable < U > collectionSupplier ) { ObjectHelper . requireNonNull ( collectionSupplier , \"collectionSupplier is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableToListSingle < T , U > ( this , collectionSupplier ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a single Map returned by a specified { @code mapFactory } function that contains a custom collection of values extracted by a specified { @code valueSelector } function from items emitted by the finite source Publisher and keyed by the { @code keySelector } function . <p > <img width = 640 height = 305 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / toMultiMap . png alt = > <p > Note that this operator requires the upstream to signal { @code onComplete } for the accumulated map to be emitted . Sources that are infinite and never complete will never emit anything through this operator and an infinite source may lead to a fatal { @code OutOfMemoryError } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure from downstream and consumes the source { @code Publisher } in an unbounded manner ( i . e . without applying backpressure to it ) . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code toMultimap } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < K , V > Single < Map < K , Collection < V > > > toMultimap ( final Function < ? super T , ? extends K > keySelector , final Function < ? super T , ? extends V > valueSelector , final Callable < ? extends Map < K , Collection < V > > > mapSupplier , final Function < ? super K , ? extends Collection < ? super V > > collectionFactory ) { ObjectHelper . requireNonNull ( keySelector , \"keySelector is null\" ) ; ObjectHelper . requireNonNull ( valueSelector , \"valueSelector is null\" ) ; ObjectHelper . requireNonNull ( mapSupplier , \"mapSupplier is null\" ) ; ObjectHelper . requireNonNull ( collectionFactory , \"collectionFactory is null\" ) ; return collect ( mapSupplier , Functions . toMultimapKeyValueSelector ( keySelector , valueSelector , collectionFactory ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the current Flowable into a non - backpressured { [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Observable < T > toObservable ( ) { return RxJavaPlugins . onAssembly ( new ObservableFromPublisher < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Single that emits a list that contains the items emitted by the finite source Publisher in a sorted order . Each item emitted by the Publisher must implement { @link Comparable } with respect to all other items in the sequence . [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . UNBOUNDED_IN ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Single < List < T > > toSortedList ( ) { return toSortedList ( Functions . naturalComparator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the source Publisher so that subscribers will cancel it on a specified { @link Scheduler } . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator doesn t interfere with backpressure which is determined by the source { @code Publisher } s backpressure behavior . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < T > unsubscribeOn ( Scheduler scheduler ) { ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableUnsubscribeOn < T > ( this , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping windows each containing { @code count } items . When the source Publisher completes or encounters an error the resulting Publisher emits the current window and propagates the notification from the source Publisher . <p > <img width = 640 height = 400 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window3 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure of its inner and outer subscribers however the inner Publisher uses an unbounded buffer that may hold at most { @code count } elements . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < Flowable < T > > window ( long count ) { return window ( count , count , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits windows every { @code skip } items each containing no more than { @code count } items . When the source Publisher completes or encounters an error the resulting Publisher emits the current window and propagates the notification from the source Publisher . <p > <img width = 640 height = 365 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window4 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator honors backpressure of its inner and outer subscribers however the inner Publisher uses an unbounded buffer that may hold at most { @code count } elements . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < Flowable < T > > window ( long count , long skip , int bufferSize ) { ObjectHelper . verifyPositive ( skip , \"skip\" ) ; ObjectHelper . verifyPositive ( count , \"count\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new FlowableWindow < T > ( this , count , skip , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher starts a new window periodically as determined by the { @code timeskip } argument . It emits each window after a fixed timespan specified by the { @code timespan } argument . When the source Publisher completes or Publisher completes or encounters an error the resulting Publisher emits the current window and propagates the notification from the source Publisher . <p > <img width = 640 height = 335 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window7 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner . The returned { @code Publisher } doesn t support backpressure as it uses time to control the creation of windows . The returned inner { @code Publisher } s honor backpressure but have an unbounded inner buffer that <em > may< / em > lead to { @code OutOfMemoryError } if left unconsumed . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < Flowable < T > > window ( long timespan , long timeskip , TimeUnit unit ) { return window ( timespan , timeskip , unit , Schedulers . computation ( ) , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping windows each of a fixed duration as specified by the { @code timespan } argument or a maximum size as specified by the { @code count } argument ( whichever is reached first ) . When the source Publisher completes or encounters an error the resulting Publisher emits the current window and propagates the notification from the source Publisher . <p > <img width = 640 height = 370 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window6 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner . The returned { @code Publisher } doesn t support backpressure as it uses time to control the creation of windows . The returned inner { @code Publisher } s honor backpressure and may hold up to { @code count } elements at most . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } operates by default on the { @code computation } { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) public final Flowable < Flowable < T > > window ( long timespan , TimeUnit unit , long count ) { return window ( timespan , unit , Schedulers . computation ( ) , count , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping windows each of a fixed duration as specified by the { @code timespan } argument . When the source Publisher completes or encounters an error the resulting Publisher emits the current window and propagates the notification from the source Publisher . <p > <img width = 640 height = 375 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window5 . s . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner . The returned { @code Publisher } doesn t support backpressure as it uses time to control the creation of windows . The returned inner { @code Publisher } s honor backpressure but have an unbounded inner buffer that <em > may< / em > lead to { @code OutOfMemoryError } if left unconsumed . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > You specify which { @link Scheduler } this operator will use . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . CUSTOM ) public final Flowable < Flowable < T > > window ( long timespan , TimeUnit unit , Scheduler scheduler ) { return window ( timespan , unit , scheduler , Long . MAX_VALUE , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits windows that contain those items emitted by the source Publisher between the time when the { @code windowOpenings } Publisher emits an item and when the Publisher returned by { @code closingSelector } emits an item . <p > <img width = 640 height = 550 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window2 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The outer Publisher of this operator doesn t support backpressure because the emission of new inner Publishers are controlled by the { @code windowOpenings } Publisher . The inner Publishers honor backpressure and buffer everything until the associated closing Publisher signals or completes . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Flowable < Flowable < T > > window ( Publisher < U > openingIndicator , Function < ? super U , ? extends Publisher < V > > closingIndicator ) { return window ( openingIndicator , closingIndicator , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits windows that contain those items emitted by the source Publisher between the time when the { @code windowOpenings } Publisher emits an item and when the Publisher returned by { @code closingSelector } emits an item . <p > <img width = 640 height = 550 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window2 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The outer Publisher of this operator doesn t support backpressure because the emission of new inner Publishers are controlled by the { @code windowOpenings } Publisher . The inner Publishers honor backpressure and buffer everything until the associated closing Publisher signals or completes . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , V > Flowable < Flowable < T > > window ( Publisher < U > openingIndicator , Function < ? super U , ? extends Publisher < V > > closingIndicator , int bufferSize ) { ObjectHelper . requireNonNull ( openingIndicator , \"openingIndicator is null\" ) ; ObjectHelper . requireNonNull ( closingIndicator , \"closingIndicator is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new FlowableWindowBoundarySelector < T , U , V > ( this , openingIndicator , closingIndicator , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping windows . It emits the current window and opens a new one whenever the Publisher produced by the specified { @code closingSelector } emits an item . <p > <img width = 640 height = 455 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window1 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner . The returned { @code Publisher } doesn t support backpressure as it uses the { @code closingSelector } to control the creation of windows . The returned inner { @code Publisher } s honor backpressure but have an unbounded inner buffer that <em > may< / em > lead to { @code OutOfMemoryError } if left unconsumed . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Flowable < Flowable < T > > window ( Callable < ? extends Publisher < B > > boundaryIndicatorSupplier ) { return window ( boundaryIndicatorSupplier , bufferSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits windows of items it collects from the source Publisher . The resulting Publisher emits connected non - overlapping windows . It emits the current window and opens a new one whenever the Publisher produced by the specified { @code closingSelector } emits an item . <p > <img width = 640 height = 455 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / window1 . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator consumes the source { @code Publisher } in an unbounded manner . The returned { @code Publisher } doesn t support backpressure as it uses the { @code closingSelector } to control the creation of windows . The returned inner { @code Publisher } s honor backpressure but have an unbounded inner buffer that <em > may< / em > lead to { @code OutOfMemoryError } if left unconsumed . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > This version of { @code window } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . ERROR ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < B > Flowable < Flowable < T > > window ( Callable < ? extends Publisher < B > > boundaryIndicatorSupplier , int bufferSize ) { ObjectHelper . requireNonNull ( boundaryIndicatorSupplier , \"boundaryIndicatorSupplier is null\" ) ; ObjectHelper . verifyPositive ( bufferSize , \"bufferSize\" ) ; return RxJavaPlugins . onAssembly ( new FlowableWindowBoundarySupplier < T , B > ( this , boundaryIndicatorSupplier , bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits items that are the result of applying a specified function to pairs of values one each from the source Publisher and a specified Iterable sequence . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / zip . i . png alt = > <p > Note that the { @code other } Iterable is evaluated as items are observed from the source Publisher ; it is not pre - consumed . This allows you to zip infinite streams on either side . <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator expects backpressure from the sources and honors backpressure from the downstream . ( I . e . zipping with { @link #interval ( long TimeUnit ) } may result in MissingBackpressureException use one of the { @code onBackpressureX } to handle similar backpressure - ignoring sources . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code zipWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Flowable < R > zipWith ( Iterable < U > other , BiFunction < ? super T , ? super U , ? extends R > zipper ) { ObjectHelper . requireNonNull ( other , \"other is null\" ) ; ObjectHelper . requireNonNull ( zipper , \"zipper is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableZipIterable < T , U , R > ( this , other , zipper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that emits items that are the result of applying a specified function to pairs of values one each from the source Publisher and another specified Publisher . <p > The operator subscribes to its sources in the order they are specified and completes eagerly if one of the sources is shorter than the rest while canceling the other sources . Therefore it is possible those other sources will never be able to run to completion ( and thus not calling { @code doOnComplete () } ) . This can also happen if the sources are exactly the same length ; if source A completes and B has been consumed and is about to complete the operator detects A won t be sending further values and it will cancel B immediately . For example : <pre > <code > range ( 1 5 ) . doOnComplete ( action1 ) . zipWith ( range ( 6 5 ) . doOnComplete ( action2 ) ( a b ) - &gt ; a + b ) < / code > < / pre > { @code action1 } will be called but { @code action2 } won t . <br > To work around this termination property use { @link #doOnCancel ( Action ) } as well or use { @code using () } to do cleanup in case of completion or cancellation . <p > <img width = 640 height = 380 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / zip . png alt = > <dl > <dt > <b > Backpressure : < / b > < / dt > <dd > The operator expects backpressure from the sources and honors backpressure from the downstream . ( I . e . zipping with { @link #interval ( long TimeUnit ) } may result in MissingBackpressureException use one of the { @code onBackpressureX } to handle similar backpressure - ignoring sources . < / dd > <dt > <b > Scheduler : < / b > < / dt > <dd > { @code zipWith } does not operate by default on a particular { @link Scheduler } . < / dd > < / dl > [CODESPLIT] @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U , R > Flowable < R > zipWith ( Publisher < ? extends U > other , BiFunction < ? super T , ? super U , ? extends R > zipper , boolean delayError ) { return zip ( this , other , zipper , delayError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } <br > <p > IMPLEMENTATION NOTES : <br > Offer is allowed from multiple threads . <br > Offer allocates a new node and : <ol > <li > Swaps it atomically with current producer node ( only one producer wins ) <li > Sets the new node as the node following from the swapped producer node < / ol > This works because each producer is guaranteed to plant a new node and link the old node . No 2 producers can get the same producer node as part of XCHG guarantee . [CODESPLIT] @ Override public boolean offer ( final T e ) { if ( null == e ) { throw new NullPointerException ( \"Null is not a valid element\" ) ; } final LinkedQueueNode < T > nextNode = new LinkedQueueNode < T > ( e ) ; final LinkedQueueNode < T > prevProducerNode = xchgProducerNode ( nextNode ) ; // Should a producer thread get interrupted here the chain WILL be broken until that thread is resumed // and completes the store in prev.next. prevProducerNode . soNext ( nextNode ) ; // StoreStore return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } <br > <p > IMPLEMENTATION NOTES : <br > Poll is allowed from a SINGLE thread . <br > Poll reads the next node from the consumerNode and : <ol > <li > If it is null the queue is assumed empty ( though it might not be ) . <li > If it is not null set it as the consumer node and return it s now evacuated value . < / ol > This means the consumerNode . value is always null which is also the starting point for the queue . Because null values are not allowed to be offered this is the only node with it s value set to null at any one time . [CODESPLIT] @ Nullable @ Override public T poll ( ) { LinkedQueueNode < T > currConsumerNode = lpConsumerNode ( ) ; // don't load twice, it's alright LinkedQueueNode < T > nextNode = currConsumerNode . lvNext ( ) ; if ( nextNode != null ) { // we have to null out the value because we are going to hang on to the node final T nextValue = nextNode . getAndNullValue ( ) ; spConsumerNode ( nextNode ) ; return nextValue ; } else if ( currConsumerNode != lvProducerNode ( ) ) { // spin, we are no longer wait free while ( ( nextNode = currConsumerNode . lvNext ( ) ) == null ) { } // NOPMD // got the next node... // we have to null out the value because we are going to hang on to the node final T nextValue = nextNode . getAndNullValue ( ) ; spConsumerNode ( nextNode ) ; return nextValue ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the given runnable into a ScheduledRunnable and schedules it on the underlying ScheduledExecutorService . <p > If the schedule has been rejected the ScheduledRunnable . wasScheduled will return false . [CODESPLIT] @ NonNull public ScheduledRunnable scheduleActual ( final Runnable run , long delayTime , @ NonNull TimeUnit unit , @ Nullable DisposableContainer parent ) { Runnable decoratedRun = RxJavaPlugins . onSchedule ( run ) ; ScheduledRunnable sr = new ScheduledRunnable ( decoratedRun , parent ) ; if ( parent != null ) { if ( ! parent . add ( sr ) ) { return sr ; } } Future < ? > f ; try { if ( delayTime <= 0 ) { f = executor . submit ( ( Callable < Object > ) sr ) ; } else { f = executor . schedule ( ( Callable < Object > ) sr , delayTime , unit ) ; } sr . setFuture ( f ) ; } catch ( RejectedExecutionException ex ) { if ( parent != null ) { parent . remove ( sr ) ; } RxJavaPlugins . onError ( ex ) ; } return sr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait for the terminal signal . [CODESPLIT] public PerfAsyncConsumer await ( int count ) { if ( count <= 1000 ) { while ( getCount ( ) != 0 ) { } } else { try { await ( ) ; } catch ( InterruptedException ex ) { throw new RuntimeException ( ex ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completes this subscription by indicating the given value should be emitted when the first request arrives . <p > Make sure this is called exactly once . [CODESPLIT] public final void complete ( T v ) { int state = get ( ) ; for ( ; ; ) { if ( state == FUSED_EMPTY ) { value = v ; lazySet ( FUSED_READY ) ; Subscriber < ? super T > a = downstream ; a . onNext ( v ) ; if ( get ( ) != CANCELLED ) { a . onComplete ( ) ; } return ; } // if state is >= CANCELLED or bit zero is set (*_HAS_VALUE) case, return if ( ( state & ~ HAS_REQUEST_NO_VALUE ) != 0 ) { return ; } if ( state == HAS_REQUEST_NO_VALUE ) { lazySet ( HAS_REQUEST_HAS_VALUE ) ; Subscriber < ? super T > a = downstream ; a . onNext ( v ) ; if ( get ( ) != CANCELLED ) { a . onComplete ( ) ; } return ; } value = v ; if ( compareAndSet ( NO_REQUEST_NO_VALUE , NO_REQUEST_HAS_VALUE ) ) { return ; } state = get ( ) ; if ( state == CANCELLED ) { value = null ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link BehaviorProcessor } that emits the last item it observed and all subsequent items to each { @link Subscriber } that subscribes to it . [CODESPLIT] @ CheckReturnValue @ NonNull public static < T > BehaviorProcessor < T > createDefault ( T defaultValue ) { ObjectHelper . requireNonNull ( defaultValue , \"defaultValue is null\" ) ; return new BehaviorProcessor < T > ( defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to emit the item to all currently subscribed Subscribers if all of them has requested some value returns false otherwise . <p > This method should be called in a sequential manner just like the onXXX methods of the PublishProcessor . <p > Calling with null will terminate the PublishProcessor and a NullPointerException is signalled to the Subscribers . <p > History : 2 . 0 . 8 - experimental [CODESPLIT] public boolean offer ( T t ) { if ( t == null ) { onError ( new NullPointerException ( \"onNext called with null. Null values are generally not allowed in 2.x operators and sources.\" ) ) ; return true ; } BehaviorSubscription < T > [ ] array = subscribers . get ( ) ; for ( BehaviorSubscription < T > s : array ) { if ( s . isFull ( ) ) { return false ; } } Object o = NotificationLite . next ( t ) ; setCurrent ( o ) ; for ( BehaviorSubscription < T > bs : array ) { bs . emitNext ( o , index ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO fuse back to Flowable [CODESPLIT] @ Override protected void subscribeActual ( MaybeObserver < ? super T > observer ) { source . subscribe ( new LastSubscriber < T > ( observer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the { [CODESPLIT] public static void verifyNonBlocking ( ) { if ( RxJavaPlugins . isFailOnNonBlockingScheduler ( ) && ( Thread . currentThread ( ) instanceof NonBlockingThread || RxJavaPlugins . onBeforeBlocking ( ) ) ) { throw new IllegalStateException ( \"Attempt to block on a Scheduler \" + Thread . currentThread ( ) . getName ( ) + \" that doesn't support blocking operators as they may lead to deadlock\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { [CODESPLIT] @ NonNull @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) public Flowable < T > refCount ( ) { return RxJavaPlugins . onAssembly ( new FlowableRefCount < T > ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the upstream { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) public final Flowable < T > refCount ( int subscriberCount ) { return refCount ( subscriberCount , 0 , TimeUnit . NANOSECONDS , Schedulers . trampoline ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the upstream { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . COMPUTATION ) @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) public final Flowable < T > refCount ( long timeout , TimeUnit unit ) { return refCount ( 1 , timeout , unit , Schedulers . computation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the upstream { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) public final Flowable < T > refCount ( long timeout , TimeUnit unit , Scheduler scheduler ) { return refCount ( 1 , timeout , unit , scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the upstream { [CODESPLIT] @ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . CUSTOM ) @ BackpressureSupport ( BackpressureKind . PASS_THROUGH ) public final Flowable < T > refCount ( int subscriberCount , long timeout , TimeUnit unit , Scheduler scheduler ) { ObjectHelper . verifyPositive ( subscriberCount , \"subscriberCount\" ) ; ObjectHelper . requireNonNull ( unit , \"unit is null\" ) ; ObjectHelper . requireNonNull ( scheduler , \"scheduler is null\" ) ; return RxJavaPlugins . onAssembly ( new FlowableRefCount < T > ( this , subscriberCount , timeout , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Flowable that automatically connects ( at most once ) to this ConnectableFlowable when the specified number of Subscribers subscribe to it and calls the specified callback with the Subscription associated with the established connection . <p > <img width = 640 height = 392 src = https : // raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / autoConnect . f . png alt = > <p > The connection happens after the given number of subscriptions and happens at most once during the lifetime of the returned Flowable . If this ConnectableFlowable terminates the connection is never renewed no matter how Subscribers come and go . Use { @link #refCount () } to renew a connection or dispose an active connection when all { @code Subscriber } s have cancelled their { @code Subscription } s . [CODESPLIT] @ NonNull public Flowable < T > autoConnect ( int numberOfSubscribers , @ NonNull Consumer < ? super Disposable > connection ) { if ( numberOfSubscribers <= 0 ) { this . connect ( connection ) ; return RxJavaPlugins . onAssembly ( this ) ; } return RxJavaPlugins . onAssembly ( new FlowableAutoConnect < T > ( this , numberOfSubscribers , connection ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests from the upstream Subscription . [CODESPLIT] protected final void request ( long n ) { Subscription s = this . upstream ; if ( s != null ) { s . request ( n ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the resource at the specified index and disposes the old resource . [CODESPLIT] public boolean setResource ( int index , Disposable resource ) { for ( ; ; ) { Disposable o = get ( index ) ; if ( o == DisposableHelper . DISPOSED ) { resource . dispose ( ) ; return false ; } if ( compareAndSet ( index , o , resource ) ) { if ( o != null ) { o . dispose ( ) ; } return true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the resource at the specified index and returns the old resource . [CODESPLIT] public Disposable replaceResource ( int index , Disposable resource ) { for ( ; ; ) { Disposable o = get ( index ) ; if ( o == DisposableHelper . DISPOSED ) { resource . dispose ( ) ; return null ; } if ( compareAndSet ( index , o , resource ) ) { return o ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Block until the first value arrives and return it otherwise return null for an empty source and rethrow any exception . [CODESPLIT] public final T blockingGet ( ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; await ( ) ; } catch ( InterruptedException ex ) { Subscription s = this . upstream ; this . upstream = SubscriptionHelper . CANCELLED ; if ( s != null ) { s . cancel ( ) ; } throw ExceptionHelper . wrapOrThrow ( ex ) ; } } Throwable e = error ; if ( e != null ) { throw ExceptionHelper . wrapOrThrow ( e ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to add the given subscriber to the subscribers array atomically or returns false if the subject has terminated . [CODESPLIT] boolean add ( PublishDisposable < T > ps ) { for ( ; ; ) { PublishDisposable < T > [ ] a = subscribers . get ( ) ; if ( a == TERMINATED ) { return false ; } int n = a . length ; @ SuppressWarnings ( \"unchecked\" ) PublishDisposable < T > [ ] b = new PublishDisposable [ n + 1 ] ; System . arraycopy ( a , 0 , b , 0 , n ) ; b [ n ] = ps ; if ( subscribers . compareAndSet ( a , b ) ) { return true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically removes the given subscriber if it is subscribed to the subject . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) void remove ( PublishDisposable < T > ps ) { for ( ; ; ) { PublishDisposable < T > [ ] a = subscribers . get ( ) ; if ( a == TERMINATED || a == EMPTY ) { return ; } int n = a . length ; int j = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == ps ) { j = i ; break ; } } if ( j < 0 ) { return ; } PublishDisposable < T > [ ] b ; if ( n == 1 ) { b = EMPTY ; } else { b = new PublishDisposable [ n - 1 ] ; System . arraycopy ( a , 0 , b , 0 , j ) ; System . arraycopy ( a , j + 1 , b , j , n - j - 1 ) ; } if ( subscribers . compareAndSet ( a , b ) ) { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a connectable observable factory it multicasts over the generated ConnectableObservable via a selector function . [CODESPLIT] public static < U , R > Flowable < R > multicastSelector ( final Callable < ? extends ConnectableFlowable < U > > connectableFactory , final Function < ? super Flowable < U > , ? extends Publisher < R > > selector ) { return new MulticastFlowable < R , U > ( connectableFactory , selector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Child Subscribers will observe the events of the ConnectableObservable on the specified scheduler . [CODESPLIT] public static < T > ConnectableFlowable < T > observeOn ( final ConnectableFlowable < T > cf , final Scheduler scheduler ) { final Flowable < T > flowable = cf . observeOn ( scheduler ) ; return RxJavaPlugins . onAssembly ( new ConnectableFlowableReplay < T > ( cf , flowable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with an unbounded buffer . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > ConnectableFlowable < T > createFrom ( Flowable < ? extends T > source ) { return create ( source , DEFAULT_UNBOUNDED_FACTORY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with a size bound buffer . [CODESPLIT] public static < T > ConnectableFlowable < T > create ( Flowable < T > source , final int bufferSize ) { if ( bufferSize == Integer . MAX_VALUE ) { return createFrom ( source ) ; } return create ( source , new ReplayBufferTask < T > ( bufferSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with a time bound buffer . [CODESPLIT] public static < T > ConnectableFlowable < T > create ( Flowable < T > source , long maxAge , TimeUnit unit , Scheduler scheduler ) { return create ( source , maxAge , unit , scheduler , Integer . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a replaying ConnectableObservable with a size and time bound buffer . [CODESPLIT] public static < T > ConnectableFlowable < T > create ( Flowable < T > source , final long maxAge , final TimeUnit unit , final Scheduler scheduler , final int bufferSize ) { return create ( source , new ScheduledReplayBufferTask < T > ( bufferSize , maxAge , unit , scheduler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a OperatorReplay instance to replay values of the given source observable . [CODESPLIT] static < T > ConnectableFlowable < T > create ( Flowable < T > source , final Callable < ? extends ReplayBuffer < T > > bufferFactory ) { // the current connection to source needs to be shared between the operator and its onSubscribe call final AtomicReference < ReplaySubscriber < T > > curr = new AtomicReference < ReplaySubscriber < T > > ( ) ; Publisher < T > onSubscribe = new ReplayPublisher < T > ( curr , bufferFactory ) ; return RxJavaPlugins . onAssembly ( new FlowableReplay < T > ( onSubscribe , source , curr , bufferFactory ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance using { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static MoshiConverterFactory create ( Moshi moshi ) { if ( moshi == null ) throw new NullPointerException ( \"moshi == null\" ) ; return new MoshiConverterFactory ( moshi , false , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance which creates synchronous observables that { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static RxJava2CallAdapterFactory createWithScheduler ( Scheduler scheduler ) { if ( scheduler == null ) throw new NullPointerException ( \"scheduler == null\" ) ; return new RxJava2CallAdapterFactory ( scheduler , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance using { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static SimpleXmlConverterFactory createNonStrict ( Serializer serializer ) { if ( serializer == null ) throw new NullPointerException ( \"serializer == null\" ) ; return new SimpleXmlConverterFactory ( serializer , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the generic supertype for { [CODESPLIT] static Type getGenericSupertype ( Type context , Class < ? > rawType , Class < ? > toResolve ) { if ( toResolve == rawType ) return context ; // We skip searching through interfaces if unknown is an interface. if ( toResolve . isInterface ( ) ) { Class < ? > [ ] interfaces = rawType . getInterfaces ( ) ; for ( int i = 0 , length = interfaces . length ; i < length ; i ++ ) { if ( interfaces [ i ] == toResolve ) { return rawType . getGenericInterfaces ( ) [ i ] ; } else if ( toResolve . isAssignableFrom ( interfaces [ i ] ) ) { return getGenericSupertype ( rawType . getGenericInterfaces ( ) [ i ] , interfaces [ i ] , toResolve ) ; } } } // Check our supertypes. if ( ! rawType . isInterface ( ) ) { while ( rawType != Object . class ) { Class < ? > rawSupertype = rawType . getSuperclass ( ) ; if ( rawSupertype == toResolve ) { return rawType . getGenericSuperclass ( ) ; } else if ( toResolve . isAssignableFrom ( rawSupertype ) ) { return getGenericSupertype ( rawType . getGenericSuperclass ( ) , rawSupertype , toResolve ) ; } rawType = rawSupertype ; } } // We can't resolve this further. return toResolve ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes { [CODESPLIT] public static < T > Call < T > defer ( Callable < Call < T > > callable ) { return new DeferredCall <> ( callable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an implementation of the API endpoints defined by the { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) // Single-interface proxy creation guarded by parameter safety. public < T > T create ( final Class < T > service ) { Utils . validateServiceInterface ( service ) ; if ( validateEagerly ) { eagerlyValidateMethods ( service ) ; } return ( T ) Proxy . newProxyInstance ( service . getClassLoader ( ) , new Class < ? > [ ] { service } , new InvocationHandler ( ) { private final Platform platform = Platform . get ( ) ; private final Object [ ] emptyArgs = new Object [ 0 ] ; @ Override public @ Nullable Object invoke ( Object proxy , Method method , @ Nullable Object [ ] args ) throws Throwable { // If the method is a method from Object then defer to normal invocation. if ( method . getDeclaringClass ( ) == Object . class ) { return method . invoke ( this , args ) ; } if ( platform . isDefaultMethod ( method ) ) { return platform . invokeDefaultMethod ( method , service , proxy , args ) ; } return loadServiceMethod ( method ) . invoke ( args != null ? args : emptyArgs ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link CallAdapter } for { @code returnType } from the available { @linkplain #callAdapterFactories () factories } . [CODESPLIT] public CallAdapter < ? , ? > callAdapter ( Type returnType , Annotation [ ] annotations ) { return nextCallAdapter ( null , returnType , annotations ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link CallAdapter } for { @code returnType } from the available { @linkplain #callAdapterFactories () factories } except { @code skipPast } . [CODESPLIT] public CallAdapter < ? , ? > nextCallAdapter ( @ Nullable CallAdapter . Factory skipPast , Type returnType , Annotation [ ] annotations ) { checkNotNull ( returnType , \"returnType == null\" ) ; checkNotNull ( annotations , \"annotations == null\" ) ; int start = callAdapterFactories . indexOf ( skipPast ) + 1 ; for ( int i = start , count = callAdapterFactories . size ( ) ; i < count ; i ++ ) { CallAdapter < ? , ? > adapter = callAdapterFactories . get ( i ) . get ( returnType , annotations , this ) ; if ( adapter != null ) { return adapter ; } } StringBuilder builder = new StringBuilder ( \"Could not locate call adapter for \" ) . append ( returnType ) . append ( \".\\n\" ) ; if ( skipPast != null ) { builder . append ( \"  Skipped:\" ) ; for ( int i = 0 ; i < start ; i ++ ) { builder . append ( \"\\n   * \" ) . append ( callAdapterFactories . get ( i ) . getClass ( ) . getName ( ) ) ; } builder . append ( ' ' ) ; } builder . append ( \"  Tried:\" ) ; for ( int i = start , count = callAdapterFactories . size ( ) ; i < count ; i ++ ) { builder . append ( \"\\n   * \" ) . append ( callAdapterFactories . get ( i ) . getClass ( ) . getName ( ) ) ; } throw new IllegalArgumentException ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Converter } for { @code type } to { @link RequestBody } from the available { @linkplain #converterFactories () factories } . [CODESPLIT] public < T > Converter < T , RequestBody > requestBodyConverter ( Type type , Annotation [ ] parameterAnnotations , Annotation [ ] methodAnnotations ) { return nextRequestBodyConverter ( null , type , parameterAnnotations , methodAnnotations ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Converter } for { @code type } to { @link RequestBody } from the available { @linkplain #converterFactories () factories } except { @code skipPast } . [CODESPLIT] public < T > Converter < T , RequestBody > nextRequestBodyConverter ( @ Nullable Converter . Factory skipPast , Type type , Annotation [ ] parameterAnnotations , Annotation [ ] methodAnnotations ) { checkNotNull ( type , \"type == null\" ) ; checkNotNull ( parameterAnnotations , \"parameterAnnotations == null\" ) ; checkNotNull ( methodAnnotations , \"methodAnnotations == null\" ) ; int start = converterFactories . indexOf ( skipPast ) + 1 ; for ( int i = start , count = converterFactories . size ( ) ; i < count ; i ++ ) { Converter . Factory factory = converterFactories . get ( i ) ; Converter < ? , RequestBody > converter = factory . requestBodyConverter ( type , parameterAnnotations , methodAnnotations , this ) ; if ( converter != null ) { //noinspection unchecked return ( Converter < T , RequestBody > ) converter ; } } StringBuilder builder = new StringBuilder ( \"Could not locate RequestBody converter for \" ) . append ( type ) . append ( \".\\n\" ) ; if ( skipPast != null ) { builder . append ( \"  Skipped:\" ) ; for ( int i = 0 ; i < start ; i ++ ) { builder . append ( \"\\n   * \" ) . append ( converterFactories . get ( i ) . getClass ( ) . getName ( ) ) ; } builder . append ( ' ' ) ; } builder . append ( \"  Tried:\" ) ; for ( int i = start , count = converterFactories . size ( ) ; i < count ; i ++ ) { builder . append ( \"\\n   * \" ) . append ( converterFactories . get ( i ) . getClass ( ) . getName ( ) ) ; } throw new IllegalArgumentException ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Converter } for { @link ResponseBody } to { @code type } from the available { @linkplain #converterFactories () factories } . [CODESPLIT] public < T > Converter < ResponseBody , T > responseBodyConverter ( Type type , Annotation [ ] annotations ) { return nextResponseBodyConverter ( null , type , annotations ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link Converter } for { @link ResponseBody } to { @code type } from the available { @linkplain #converterFactories () factories } except { @code skipPast } . [CODESPLIT] public < T > Converter < ResponseBody , T > nextResponseBodyConverter ( @ Nullable Converter . Factory skipPast , Type type , Annotation [ ] annotations ) { checkNotNull ( type , \"type == null\" ) ; checkNotNull ( annotations , \"annotations == null\" ) ; int start = converterFactories . indexOf ( skipPast ) + 1 ; for ( int i = start , count = converterFactories . size ( ) ; i < count ; i ++ ) { Converter < ResponseBody , ? > converter = converterFactories . get ( i ) . responseBodyConverter ( type , annotations , this ) ; if ( converter != null ) { //noinspection unchecked return ( Converter < ResponseBody , T > ) converter ; } } StringBuilder builder = new StringBuilder ( \"Could not locate ResponseBody converter for \" ) . append ( type ) . append ( \".\\n\" ) ; if ( skipPast != null ) { builder . append ( \"  Skipped:\" ) ; for ( int i = 0 ; i < start ; i ++ ) { builder . append ( \"\\n   * \" ) . append ( converterFactories . get ( i ) . getClass ( ) . getName ( ) ) ; } builder . append ( ' ' ) ; } builder . append ( \"  Tried:\" ) ; for ( int i = start , count = converterFactories . size ( ) ; i < count ; i ++ ) { builder . append ( \"\\n   * \" ) . append ( converterFactories . get ( i ) . getClass ( ) . getName ( ) ) ; } throw new IllegalArgumentException ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { [CODESPLIT] public < T > Converter < T , String > stringConverter ( Type type , Annotation [ ] annotations ) { checkNotNull ( type , \"type == null\" ) ; checkNotNull ( annotations , \"annotations == null\" ) ; for ( int i = 0 , count = converterFactories . size ( ) ; i < count ; i ++ ) { Converter < ? , String > converter = converterFactories . get ( i ) . stringConverter ( type , annotations , this ) ; if ( converter != null ) { //noinspection unchecked return ( Converter < T , String > ) converter ; } } // Nothing matched. Resort to default converter which just calls toString(). //noinspection unchecked return ( Converter < T , String > ) BuiltInConverters . ToStringConverter . INSTANCE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance using { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static JaxbConverterFactory create ( JAXBContext context ) { if ( context == null ) throw new NullPointerException ( \"context == null\" ) ; return new JaxbConverterFactory ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance using { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static GsonConverterFactory create ( Gson gson ) { if ( gson == null ) throw new NullPointerException ( \"gson == null\" ) ; return new GsonConverterFactory ( gson ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance which creates synchronous observables that { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static RxJavaCallAdapterFactory createWithScheduler ( Scheduler scheduler ) { if ( scheduler == null ) throw new NullPointerException ( \"scheduler == null\" ) ; return new RxJavaCallAdapterFactory ( scheduler , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance using { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static JacksonConverterFactory create ( ObjectMapper mapper ) { if ( mapper == null ) throw new NullPointerException ( \"mapper == null\" ) ; return new JacksonConverterFactory ( mapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects the annotations on an interface method to construct a reusable service method that speaks HTTP . This requires potentially - expensive reflection so it is best to build each service method only once and reuse it . [CODESPLIT] static < ResponseT , ReturnT > HttpServiceMethod < ResponseT , ReturnT > parseAnnotations ( Retrofit retrofit , Method method , RequestFactory requestFactory ) { boolean isKotlinSuspendFunction = requestFactory . isKotlinSuspendFunction ; boolean continuationWantsResponse = false ; boolean continuationBodyNullable = false ; Annotation [ ] annotations = method . getAnnotations ( ) ; Type adapterType ; if ( isKotlinSuspendFunction ) { Type [ ] parameterTypes = method . getGenericParameterTypes ( ) ; Type responseType = Utils . getParameterLowerBound ( 0 , ( ParameterizedType ) parameterTypes [ parameterTypes . length - 1 ] ) ; if ( getRawType ( responseType ) == Response . class && responseType instanceof ParameterizedType ) { // Unwrap the actual body type from Response<T>. responseType = Utils . getParameterUpperBound ( 0 , ( ParameterizedType ) responseType ) ; continuationWantsResponse = true ; } else { // TODO figure out if type is nullable or not // Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class) // Find the entry for method // Determine if return type is nullable or not } adapterType = new Utils . ParameterizedTypeImpl ( null , Call . class , responseType ) ; annotations = SkipCallbackExecutorImpl . ensurePresent ( annotations ) ; } else { adapterType = method . getGenericReturnType ( ) ; } CallAdapter < ResponseT , ReturnT > callAdapter = createCallAdapter ( retrofit , method , adapterType , annotations ) ; Type responseType = callAdapter . responseType ( ) ; if ( responseType == okhttp3 . Response . class ) { throw methodError ( method , \"'\" + getRawType ( responseType ) . getName ( ) + \"' is not a valid response body type. Did you mean ResponseBody?\" ) ; } if ( responseType == Response . class ) { throw methodError ( method , \"Response must include generic type (e.g., Response<String>)\" ) ; } // TODO support Unit for Kotlin? if ( requestFactory . httpMethod . equals ( \"HEAD\" ) && ! Void . class . equals ( responseType ) ) { throw methodError ( method , \"HEAD method must use Void as response type.\" ) ; } Converter < ResponseBody , ResponseT > responseConverter = createResponseConverter ( retrofit , method , responseType ) ; okhttp3 . Call . Factory callFactory = retrofit . callFactory ; if ( ! isKotlinSuspendFunction ) { return new CallAdapted <> ( requestFactory , callFactory , responseConverter , callAdapter ) ; } else if ( continuationWantsResponse ) { //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object. return ( HttpServiceMethod < ResponseT , ReturnT > ) new SuspendForResponse <> ( requestFactory , callFactory , responseConverter , ( CallAdapter < ResponseT , Call < ResponseT > > ) callAdapter ) ; } else { //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object. return ( HttpServiceMethod < ResponseT , ReturnT > ) new SuspendForBody <> ( requestFactory , callFactory , responseConverter , ( CallAdapter < ResponseT , Call < ResponseT > > ) callAdapter , continuationBodyNullable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance with default behavior which uses { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public static NetworkBehavior create ( Random random ) { if ( random == null ) throw new NullPointerException ( \"random == null\" ) ; return new NetworkBehavior ( random ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the network round trip delay . [CODESPLIT] public void setDelay ( long amount , TimeUnit unit ) { if ( amount < 0 ) { throw new IllegalArgumentException ( \"Amount must be positive value.\" ) ; } this . delayMs = unit . toMillis ( amount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the error response factory to be used when an error is triggered . This factory may only return responses for which { [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) // Guarding public API nullability. public void setErrorFactory ( Callable < Response < ? > > errorFactory ) { if ( errorFactory == null ) { throw new NullPointerException ( \"errorFactory == null\" ) ; } this . errorFactory = errorFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The HTTP error to be used when an error is triggered . [CODESPLIT] public Response < ? > createErrorResponse ( ) { Response < ? > call ; try { call = errorFactory . call ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( \"Error factory threw an exception.\" , e ) ; } if ( call == null ) { throw new IllegalStateException ( \"Error factory returned null.\" ) ; } if ( call . isSuccessful ( ) ) { throw new IllegalStateException ( \"Error factory returned successful response.\" ) ; } return call ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the delay that should be used for delaying a response in accordance with configured behavior . [CODESPLIT] public long calculateDelay ( TimeUnit unit ) { float delta = variancePercent / 100f ; // e.g., 20 / 100f == 0.2f float lowerBound = 1f - delta ; // 0.2f --> 0.8f float upperBound = 1f + delta ; // 0.2f --> 1.2f float bound = upperBound - lowerBound ; // 1.2f - 0.8f == 0.4f float delayPercent = lowerBound + ( random . nextFloat ( ) * bound ) ; // 0.8 + (rnd * 0.4) long callDelayMs = ( long ) ( delayMs * delayPercent ) ; return MILLISECONDS . convert ( callDelayMs , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a synthetic successful response with { [CODESPLIT] public static < T > Response < T > success ( @ Nullable T body ) { return success ( body , new okhttp3 . Response . Builder ( ) // . code ( 200 ) . message ( \"OK\" ) . protocol ( Protocol . HTTP_1_1 ) . request ( new Request . Builder ( ) . url ( \"http://localhost/\" ) . build ( ) ) . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a successful response from { [CODESPLIT] public static < T > Response < T > success ( @ Nullable T body , okhttp3 . Response rawResponse ) { checkNotNull ( rawResponse , \"rawResponse == null\" ) ; if ( ! rawResponse . isSuccessful ( ) ) { throw new IllegalArgumentException ( \"rawResponse must be successful response\" ) ; } return new Response <> ( rawResponse , body , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a synthetic error response with an HTTP status code of { [CODESPLIT] public static < T > Response < T > error ( int code , ResponseBody body ) { if ( code < 400 ) throw new IllegalArgumentException ( \"code < 400: \" + code ) ; return error ( body , new okhttp3 . Response . Builder ( ) // . code ( code ) . message ( \"Response.error()\" ) . protocol ( Protocol . HTTP_1_1 ) . request ( new Request . Builder ( ) . url ( \"http://localhost/\" ) . build ( ) ) . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an error response from { [CODESPLIT] public static < T > Response < T > error ( ResponseBody body , okhttp3 . Response rawResponse ) { checkNotNull ( body , \"body == null\" ) ; checkNotNull ( rawResponse , \"rawResponse == null\" ) ; if ( rawResponse . isSuccessful ( ) ) { throw new IllegalArgumentException ( \"rawResponse should not be successful response\" ) ; } return new Response <> ( rawResponse , null , body ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理数字字母混合输出 如：windos2000 | linliangyi2005 [CODESPLIT] private boolean processMixLetter ( AnalyzeContext context ) { boolean needLock = false ; if ( this . start == - 1 ) { //当前的分词器尚未开始处理字符\r if ( CharacterUtil . CHAR_ARABIC == context . getCurrentCharType ( ) || CharacterUtil . CHAR_ENGLISH == context . getCurrentCharType ( ) ) { //记录起始指针的位置,标明分词器进入处理状态\r this . start = context . getCursor ( ) ; this . end = start ; } } else { //当前的分词器正在处理字符\t\t\t\r if ( CharacterUtil . CHAR_ARABIC == context . getCurrentCharType ( ) || CharacterUtil . CHAR_ENGLISH == context . getCurrentCharType ( ) ) { //记录下可能的结束位置\r this . end = context . getCursor ( ) ; } else if ( CharacterUtil . CHAR_USELESS == context . getCurrentCharType ( ) && this . isLetterConnector ( context . getCurrentChar ( ) ) ) { //记录下可能的结束位置\r this . end = context . getCursor ( ) ; } else { //遇到非Letter字符，输出词元\r Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , this . start , this . end - this . start + 1 , Lexeme . TYPE_LETTER ) ; context . addLexeme ( newLexeme ) ; this . start = - 1 ; this . end = - 1 ; } } //判断缓冲区是否已经读完\r if ( context . isBufferConsumed ( ) && ( this . start != - 1 && this . end != - 1 ) ) { //缓冲以读完，输出词元\r Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , this . start , this . end - this . start + 1 , Lexeme . TYPE_LETTER ) ; context . addLexeme ( newLexeme ) ; this . start = - 1 ; this . end = - 1 ; } //判断是否锁定缓冲区\r if ( this . start == - 1 && this . end == - 1 ) { //对缓冲区解锁\r needLock = false ; } else { needLock = true ; } return needLock ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "识别字符类型 [CODESPLIT] static int identifyCharType ( char input ) { if ( input >= ' ' && input <= ' ' ) { return CHAR_ARABIC ; } else if ( ( input >= ' ' && input <= ' ' ) || ( input >= ' ' && input <= ' ' ) ) { return CHAR_ENGLISH ; } else { Character . UnicodeBlock ub = Character . UnicodeBlock . of ( input ) ; if ( ub == Character . UnicodeBlock . CJK_UNIFIED_IDEOGRAPHS || ub == Character . UnicodeBlock . CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character . UnicodeBlock . CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A ) { //目前已知的中文字符UTF-8集合\r return CHAR_CHINESE ; } else if ( ub == Character . UnicodeBlock . HALFWIDTH_AND_FULLWIDTH_FORMS //全角数字字符和日韩字符\r //韩文字符集\r || ub == Character . UnicodeBlock . HANGUL_SYLLABLES || ub == Character . UnicodeBlock . HANGUL_JAMO || ub == Character . UnicodeBlock . HANGUL_COMPATIBILITY_JAMO //日文字符集\r || ub == Character . UnicodeBlock . HIRAGANA //平假名\r || ub == Character . UnicodeBlock . KATAKANA //片假名\r || ub == Character . UnicodeBlock . KATAKANA_PHONETIC_EXTENSIONS ) { return CHAR_OTHER_CJK ; } } //其他的不做处理的字符\r return CHAR_USELESS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "进行字符规格化（全角转半角，大写转小写处理） [CODESPLIT] static char regularize ( char input , boolean lowercase ) { if ( input == 12288 ) { input = ( char ) 32 ; } else if ( input > 65280 && input < 65375 ) { input = ( char ) ( input - 65248 ) ; } else if ( input >= ' ' && input <= ' ' && lowercase ) { input += 32 ; } return input ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "初始化词典，加载子分词器实现 [CODESPLIT] private List < ISegmenter > loadSegmenters ( ) { List < ISegmenter > segmenters = new ArrayList < ISegmenter > ( 4 ) ; //处理字母的子分词器\r segmenters . add ( new LetterSegmenter ( ) ) ; //处理中文数量词的子分词器\r segmenters . add ( new CN_QuantifierSegmenter ( ) ) ; //处理中文词的子分词器\r segmenters . add ( new CJKSegmenter ( ) ) ; return segmenters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分词，获取下一个词元 [CODESPLIT] public synchronized Lexeme next ( ) throws IOException { Lexeme l = null ; while ( ( l = context . getNextLexeme ( ) ) == null ) { /*\r\n\t\t\t * 从reader中读取数据，填充buffer\r\n\t\t\t * 如果reader是分次读入buffer的，那么buffer要  进行移位处理\r\n\t\t\t * 移位处理上次读入的但未处理的数据\r\n\t\t\t */ int available = context . fillBuffer ( this . input ) ; if ( available <= 0 ) { //reader已经读完\r context . reset ( ) ; return null ; } else { //初始化指针\r context . initCursor ( ) ; do { //遍历子分词器\r for ( ISegmenter segmenter : segmenters ) { segmenter . analyze ( context ) ; } //字符缓冲区接近读完，需要读入新的字符\r if ( context . needRefillBuffer ( ) ) { break ; } //向前移动指针\r } while ( context . moveCursor ( ) ) ; //重置子分词器，为下轮循环进行初始化\r for ( ISegmenter segmenter : segmenters ) { segmenter . reset ( ) ; } } //对分词进行歧义处理\r this . arbitrator . process ( context , configuration . isUseSmart ( ) ) ; //将分词结果输出到结果集，并处理未切分的单个CJK字符\r context . outputToResult ( ) ; //记录本次分词的缓冲区位移\r context . markBufferOffset ( ) ; } return l ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "重置分词器到初始状态 [CODESPLIT] public synchronized void reset ( Reader input ) { this . input = input ; context . reset ( ) ; for ( ISegmenter segmenter : segmenters ) { segmenter . reset ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分词歧义处理 * [CODESPLIT] void process ( AnalyzeContext context , boolean useSmart ) { QuickSortSet orgLexemes = context . getOrgLexemes ( ) ; Lexeme orgLexeme = orgLexemes . pollFirst ( ) ; LexemePath crossPath = new LexemePath ( ) ; while ( orgLexeme != null ) { if ( ! crossPath . addCrossLexeme ( orgLexeme ) ) { //找到与crossPath不相交的下一个crossPath\t\r if ( crossPath . size ( ) == 1 || ! useSmart ) { //crossPath没有歧义 或者 不做歧义处理\r //直接输出当前crossPath\r context . addLexemePath ( crossPath ) ; } else { //对当前的crossPath进行歧义处理\r QuickSortSet . Cell headCell = crossPath . getHead ( ) ; LexemePath judgeResult = this . judge ( headCell , crossPath . getPathLength ( ) ) ; //输出歧义处理结果judgeResult\r context . addLexemePath ( judgeResult ) ; } //把orgLexeme加入新的crossPath中\r crossPath = new LexemePath ( ) ; crossPath . addCrossLexeme ( orgLexeme ) ; } orgLexeme = orgLexemes . pollFirst ( ) ; } //处理最后的path\r if ( crossPath . size ( ) == 1 || ! useSmart ) { //crossPath没有歧义 或者 不做歧义处理\r //直接输出当前crossPath\r context . addLexemePath ( crossPath ) ; } else { //对当前的crossPath进行歧义处理\r QuickSortSet . Cell headCell = crossPath . getHead ( ) ; LexemePath judgeResult = this . judge ( headCell , crossPath . getPathLength ( ) ) ; //输出歧义处理结果judgeResult\r context . addLexemePath ( judgeResult ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "歧义识别 [CODESPLIT] private LexemePath judge ( QuickSortSet . Cell lexemeCell , int fullTextLength ) { //候选路径集合\r TreeSet < LexemePath > pathOptions = new TreeSet < LexemePath > ( ) ; //候选结果路径\r LexemePath option = new LexemePath ( ) ; //对crossPath进行一次遍历,同时返回本次遍历中有冲突的Lexeme栈\r Stack < QuickSortSet . Cell > lexemeStack = this . forwardPath ( lexemeCell , option ) ; //当前词元链并非最理想的，加入候选路径集合\r pathOptions . add ( option . copy ( ) ) ; //存在歧义词，处理\r QuickSortSet . Cell c = null ; while ( ! lexemeStack . isEmpty ( ) ) { c = lexemeStack . pop ( ) ; //回滚词元链\r this . backPath ( c . getLexeme ( ) , option ) ; //从歧义词位置开始，递归，生成可选方案\r this . forwardPath ( c , option ) ; pathOptions . add ( option . copy ( ) ) ; } //返回集合中的最优方案\r return pathOptions . first ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向前遍历，添加词元，构造一个无歧义词元组合 * [CODESPLIT] private Stack < QuickSortSet . Cell > forwardPath ( QuickSortSet . Cell lexemeCell , LexemePath option ) { //发生冲突的Lexeme栈\r Stack < QuickSortSet . Cell > conflictStack = new Stack < QuickSortSet . Cell > ( ) ; QuickSortSet . Cell c = lexemeCell ; //迭代遍历Lexeme链表\r while ( c != null && c . getLexeme ( ) != null ) { if ( ! option . addNotCrossLexeme ( c . getLexeme ( ) ) ) { //词元交叉，添加失败则加入lexemeStack栈\r conflictStack . push ( c ) ; } c = c . getNext ( ) ; } return conflictStack ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "回滚词元链，直到它能够接受指定的词元 * [CODESPLIT] private void backPath ( Lexeme l , LexemePath option ) { while ( option . checkCross ( l ) ) { option . removeTail ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "重载Analyzer接口，构造分词组件 [CODESPLIT] @ Override protected TokenStreamComponents createComponents ( String fieldName ) { Tokenizer _IKTokenizer = new IKTokenizer ( configuration ) ; return new TokenStreamComponents ( _IKTokenizer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据context的上下文情况，填充segmentBuff [CODESPLIT] int fillBuffer ( Reader reader ) throws IOException { int readCount = 0 ; if ( this . buffOffset == 0 ) { //首次读取reader\r readCount = reader . read ( segmentBuff ) ; } else { int offset = this . available - this . cursor ; if ( offset > 0 ) { //最近一次读取的>最近一次处理的，将未处理的字串拷贝到segmentBuff头部\r System . arraycopy ( this . segmentBuff , this . cursor , this . segmentBuff , 0 , offset ) ; readCount = offset ; } //继续读取reader ，以onceReadIn - onceAnalyzed为起始位置，继续填充segmentBuff剩余的部分\r readCount += reader . read ( this . segmentBuff , offset , BUFF_SIZE - offset ) ; } //记录最后一次从Reader中读入的可用字符长度\r this . available = readCount ; //重置当前指针\r this . cursor = 0 ; return readCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "初始化buff指针，处理第一个字符 [CODESPLIT] void initCursor ( ) { this . cursor = 0 ; this . segmentBuff [ this . cursor ] = CharacterUtil . regularize ( this . segmentBuff [ this . cursor ] , cfg . isEnableLowercase ( ) ) ; this . charTypes [ this . cursor ] = CharacterUtil . identifyCharType ( this . segmentBuff [ this . cursor ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "添加分词结果路径 路径起始位置 --- > 路径 映射表 [CODESPLIT] void addLexemePath ( LexemePath path ) { if ( path != null ) { this . pathMap . put ( path . getPathBegin ( ) , path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "推送分词结果到结果集合 1 . 从buff头部遍历到this . cursor已处理位置 2 . 将map中存在的分词结果推入results 3 . 将map中不存在的CJDK字符以单字方式推入results [CODESPLIT] void outputToResult ( ) { int index = 0 ; for ( ; index <= this . cursor ; ) { //跳过非CJK字符\r if ( CharacterUtil . CHAR_USELESS == this . charTypes [ index ] ) { index ++ ; continue ; } //从pathMap找出对应index位置的LexemePath\r LexemePath path = this . pathMap . get ( index ) ; if ( path != null ) { //输出LexemePath中的lexeme到results集合\r Lexeme l = path . pollFirst ( ) ; while ( l != null ) { this . results . add ( l ) ; //字典中无单字，但是词元冲突了，切分出相交词元的前一个词元中的单字\r int innerIndex = index + 1 ; for ( ; innerIndex < index + l . getLength ( ) ; innerIndex ++ ) { Lexeme innerL = path . peekFirst ( ) ; if ( innerL != null && innerIndex == innerL . getBegin ( ) ) { this . outputSingleCJK ( innerIndex - 1 ) ; } } //将index移至lexeme后\r index = l . getBegin ( ) + l . getLength ( ) ; l = path . pollFirst ( ) ; if ( l != null ) { //输出path内部，词元间遗漏的单字\r for ( ; index < l . getBegin ( ) ; index ++ ) { this . outputSingleCJK ( index ) ; } } } } else { //pathMap中找不到index对应的LexemePath\r //单字输出\r this . outputSingleCJK ( index ) ; index ++ ; } } //清空当前的Map\r this . pathMap . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对CJK字符进行单字输出 [CODESPLIT] private void outputSingleCJK ( int index ) { if ( CharacterUtil . CHAR_CHINESE == this . charTypes [ index ] ) { Lexeme singleCharLexeme = new Lexeme ( this . buffOffset , index , 1 , Lexeme . TYPE_CNCHAR ) ; this . results . add ( singleCharLexeme ) ; } else if ( CharacterUtil . CHAR_OTHER_CJK == this . charTypes [ index ] ) { Lexeme singleCharLexeme = new Lexeme ( this . buffOffset , index , 1 , Lexeme . TYPE_OTHER_CJK ) ; this . results . add ( singleCharLexeme ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回lexeme [CODESPLIT] Lexeme getNextLexeme ( ) { //从结果集取出，并移除第一个Lexme\r Lexeme result = this . results . pollFirst ( ) ; while ( result != null ) { //数量词合并\r this . compound ( result ) ; if ( Dictionary . getSingleton ( ) . isStopWord ( this . segmentBuff , result . getBegin ( ) , result . getLength ( ) ) ) { //是停止词继续取列表的下一个\r result = this . results . pollFirst ( ) ; } else { //不是停止词, 生成lexeme的词元文本,输出\r result . setLexemeText ( String . valueOf ( segmentBuff , result . getBegin ( ) , result . getLength ( ) ) ) ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "重置分词上下文状态 [CODESPLIT] void reset ( ) { this . buffLocker . clear ( ) ; this . orgLexemes = new QuickSortSet ( ) ; this . available = 0 ; this . buffOffset = 0 ; this . charTypes = new int [ BUFF_SIZE ] ; this . cursor = 0 ; this . results . clear ( ) ; this . segmentBuff = new char [ BUFF_SIZE ] ; this . pathMap . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "组合词元 [CODESPLIT] private void compound ( Lexeme result ) { if ( ! this . cfg . isUseSmart ( ) ) { return ; } //数量词合并处理\r if ( ! this . results . isEmpty ( ) ) { if ( Lexeme . TYPE_ARABIC == result . getLexemeType ( ) ) { Lexeme nextLexeme = this . results . peekFirst ( ) ; boolean appendOk = false ; if ( Lexeme . TYPE_CNUM == nextLexeme . getLexemeType ( ) ) { //合并英文数词+中文数词\r appendOk = result . append ( nextLexeme , Lexeme . TYPE_CNUM ) ; } else if ( Lexeme . TYPE_COUNT == nextLexeme . getLexemeType ( ) ) { //合并英文数词+中文量词\r appendOk = result . append ( nextLexeme , Lexeme . TYPE_CQUAN ) ; } if ( appendOk ) { //弹出\r this . results . pollFirst ( ) ; } } //可能存在第二轮合并\r if ( Lexeme . TYPE_CNUM == result . getLexemeType ( ) && ! this . results . isEmpty ( ) ) { Lexeme nextLexeme = this . results . peekFirst ( ) ; boolean appendOk = false ; if ( Lexeme . TYPE_COUNT == nextLexeme . getLexemeType ( ) ) { //合并中文数词+中文量词\r appendOk = result . append ( nextLexeme , Lexeme . TYPE_CQUAN ) ; } if ( appendOk ) { //弹出\r this . results . pollFirst ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向LexemePath追加相交的Lexeme [CODESPLIT] boolean addCrossLexeme ( Lexeme lexeme ) { if ( this . isEmpty ( ) ) { this . addLexeme ( lexeme ) ; this . pathBegin = lexeme . getBegin ( ) ; this . pathEnd = lexeme . getBegin ( ) + lexeme . getLength ( ) ; this . payloadLength += lexeme . getLength ( ) ; return true ; } else if ( this . checkCross ( lexeme ) ) { this . addLexeme ( lexeme ) ; if ( lexeme . getBegin ( ) + lexeme . getLength ( ) > this . pathEnd ) { this . pathEnd = lexeme . getBegin ( ) + lexeme . getLength ( ) ; } this . payloadLength = this . pathEnd - this . pathBegin ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向LexemePath追加不相交的Lexeme [CODESPLIT] boolean addNotCrossLexeme ( Lexeme lexeme ) { if ( this . isEmpty ( ) ) { this . addLexeme ( lexeme ) ; this . pathBegin = lexeme . getBegin ( ) ; this . pathEnd = lexeme . getBegin ( ) + lexeme . getLength ( ) ; this . payloadLength += lexeme . getLength ( ) ; return true ; } else if ( this . checkCross ( lexeme ) ) { return false ; } else { this . addLexeme ( lexeme ) ; this . payloadLength += lexeme . getLength ( ) ; Lexeme head = this . peekFirst ( ) ; this . pathBegin = head . getBegin ( ) ; Lexeme tail = this . peekLast ( ) ; this . pathEnd = tail . getBegin ( ) + tail . getLength ( ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "移除尾部的Lexeme [CODESPLIT] Lexeme removeTail ( ) { Lexeme tail = this . pollLast ( ) ; if ( this . isEmpty ( ) ) { this . pathBegin = - 1 ; this . pathEnd = - 1 ; this . payloadLength = 0 ; } else { this . payloadLength -= tail . getLength ( ) ; Lexeme newTail = this . peekLast ( ) ; this . pathEnd = newTail . getBegin ( ) + newTail . getLength ( ) ; } return tail ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检测词元位置交叉（有歧义的切分） [CODESPLIT] boolean checkCross ( Lexeme lexeme ) { return ( lexeme . getBegin ( ) >= this . pathBegin && lexeme . getBegin ( ) < this . pathEnd ) || ( this . pathBegin >= lexeme . getBegin ( ) && this . pathBegin < lexeme . getBegin ( ) + lexeme . getLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "X权重（词元长度积） [CODESPLIT] int getXWeight ( ) { int product = 1 ; Cell c = this . getHead ( ) ; while ( c != null && c . getLexeme ( ) != null ) { product *= c . getLexeme ( ) . getLength ( ) ; c = c . getNext ( ) ; } return product ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "词元位置权重 [CODESPLIT] int getPWeight ( ) { int pWeight = 0 ; int p = 0 ; Cell c = this . getHead ( ) ; while ( c != null && c . getLexeme ( ) != null ) { p ++ ; pWeight += p * c . getLexeme ( ) . getLength ( ) ; c = c . getNext ( ) ; } return pWeight ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "词典初始化 由于IK Analyzer的词典采用Dictionary类的静态方法进行词典初始化 只有当Dictionary类被实际调用时，才会开始载入词典， 这将延长首次分词操作的时间 该方法提供了一个在应用加载阶段就初始化字典的手段 [CODESPLIT] public static synchronized void initial ( Configuration cfg ) { if ( singleton == null ) { synchronized ( Dictionary . class ) { if ( singleton == null ) { singleton = new Dictionary ( cfg ) ; singleton . loadMainDict ( ) ; singleton . loadSurnameDict ( ) ; singleton . loadQuantifierDict ( ) ; singleton . loadSuffixDict ( ) ; singleton . loadPrepDict ( ) ; singleton . loadStopWordDict ( ) ; if ( cfg . isEnableRemoteDict ( ) ) { // 建立监控线程\r for ( String location : singleton . getRemoteExtDictionarys ( ) ) { // 10 秒是初始延迟可以修改的 60是间隔时间 单位秒\r pool . scheduleAtFixedRate ( new Monitor ( location ) , 10 , 60 , TimeUnit . SECONDS ) ; } for ( String location : singleton . getRemoteExtStopWordDictionarys ( ) ) { pool . scheduleAtFixedRate ( new Monitor ( location ) , 10 , 60 , TimeUnit . SECONDS ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "批量移除（屏蔽）词条 [CODESPLIT] public void disableWords ( Collection < String > words ) { if ( words != null ) { for ( String word : words ) { if ( word != null ) { // 批量屏蔽词条\r singleton . _MainDict . disableSegment ( word . trim ( ) . toCharArray ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检索匹配主词典 [CODESPLIT] public Hit matchInMainDict ( char [ ] charArray , int begin , int length ) { return singleton . _MainDict . match ( charArray , begin , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检索匹配量词词典 [CODESPLIT] public Hit matchInQuantifierDict ( char [ ] charArray , int begin , int length ) { return singleton . _QuantifierDict . match ( charArray , begin , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从已匹配的Hit中直接取出DictSegment，继续向下匹配 [CODESPLIT] public Hit matchWithHit ( char [ ] charArray , int currentIndex , Hit matchedHit ) { DictSegment ds = matchedHit . getMatchedDictSegment ( ) ; return ds . match ( charArray , currentIndex , 1 , matchedHit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断是否是停止词 [CODESPLIT] public boolean isStopWord ( char [ ] charArray , int begin , int length ) { return singleton . _StopWords . match ( charArray , begin , length ) . isMatch ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载主词典及扩展词典 [CODESPLIT] private void loadMainDict ( ) { // 建立一个主词典实例\r _MainDict = new DictSegment ( ( char ) 0 ) ; // 读取主词典文件\r Path file = PathUtils . get ( getDictRoot ( ) , Dictionary . PATH_DIC_MAIN ) ; loadDictFile ( _MainDict , file , false , \"Main Dict\" ) ; // 加载扩展词典\r this . loadExtDict ( ) ; // 加载远程自定义词库\r this . loadRemoteExtDict ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载用户配置的扩展词典到主词库表 [CODESPLIT] private void loadExtDict ( ) { // 加载扩展词典配置\r List < String > extDictFiles = getExtDictionarys ( ) ; if ( extDictFiles != null ) { for ( String extDictName : extDictFiles ) { // 读取扩展词典文件\r logger . info ( \"[Dict Loading] \" + extDictName ) ; Path file = PathUtils . get ( extDictName ) ; loadDictFile ( _MainDict , file , false , \"Extra Dict\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载远程扩展词典到主词库表 [CODESPLIT] private void loadRemoteExtDict ( ) { List < String > remoteExtDictFiles = getRemoteExtDictionarys ( ) ; for ( String location : remoteExtDictFiles ) { logger . info ( \"[Dict Loading] \" + location ) ; List < String > lists = getRemoteWords ( location ) ; // 如果找不到扩展的字典，则忽略\r if ( lists == null ) { logger . error ( \"[Dict Loading] \" + location + \"加载失败\");\r   continue ; } for ( String theWord : lists ) { if ( theWord != null && ! \"\" . equals ( theWord . trim ( ) ) ) { // 加载扩展词典数据到主内存词典中\r logger . info ( theWord ) ; _MainDict . fillSegment ( theWord . trim ( ) . toLowerCase ( ) . toCharArray ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从远程服务器上下载自定义词条 [CODESPLIT] private static List < String > getRemoteWordsUnprivileged ( String location ) { List < String > buffer = new ArrayList < String > ( ) ; RequestConfig rc = RequestConfig . custom ( ) . setConnectionRequestTimeout ( 10 * 1000 ) . setConnectTimeout ( 10 * 1000 ) . setSocketTimeout ( 60 * 1000 ) . build ( ) ; CloseableHttpClient httpclient = HttpClients . createDefault ( ) ; CloseableHttpResponse response ; BufferedReader in ; HttpGet get = new HttpGet ( location ) ; get . setConfig ( rc ) ; try { response = httpclient . execute ( get ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 200 ) { String charset = \"UTF-8\" ; // 获取编码，默认为utf-8\r HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { Header contentType = entity . getContentType ( ) ; if ( contentType != null && contentType . getValue ( ) != null ) { String typeValue = contentType . getValue ( ) ; if ( typeValue != null && typeValue . contains ( \"charset=\" ) ) { charset = typeValue . substring ( typeValue . lastIndexOf ( \"=\" ) + 1 ) ; } } if ( entity . getContentLength ( ) > 0 ) { in = new BufferedReader ( new InputStreamReader ( entity . getContent ( ) , charset ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) { buffer . add ( line ) ; } in . close ( ) ; response . close ( ) ; return buffer ; } } } response . close ( ) ; } catch ( IllegalStateException | IOException e ) { logger . error ( \"getRemoteWords {} error\" , e , location ) ; } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载用户扩展的停止词词典 [CODESPLIT] private void loadStopWordDict ( ) { // 建立主词典实例\r _StopWords = new DictSegment ( ( char ) 0 ) ; // 读取主词典文件\r Path file = PathUtils . get ( getDictRoot ( ) , Dictionary . PATH_DIC_STOP ) ; loadDictFile ( _StopWords , file , false , \"Main Stopwords\" ) ; // 加载扩展停止词典\r List < String > extStopWordDictFiles = getExtStopWordDictionarys ( ) ; if ( extStopWordDictFiles != null ) { for ( String extStopWordDictName : extStopWordDictFiles ) { logger . info ( \"[Dict Loading] \" + extStopWordDictName ) ; // 读取扩展词典文件\r file = PathUtils . get ( extStopWordDictName ) ; loadDictFile ( _StopWords , file , false , \"Extra Stopwords\" ) ; } } // 加载远程停用词典\r List < String > remoteExtStopWordDictFiles = getRemoteExtStopWordDictionarys ( ) ; for ( String location : remoteExtStopWordDictFiles ) { logger . info ( \"[Dict Loading] \" + location ) ; List < String > lists = getRemoteWords ( location ) ; // 如果找不到扩展的字典，则忽略\r if ( lists == null ) { logger . error ( \"[Dict Loading] \" + location + \"加载失败\");\r   continue ; } for ( String theWord : lists ) { if ( theWord != null && ! \"\" . equals ( theWord . trim ( ) ) ) { // 加载远程词典数据到主内存中\r logger . info ( theWord ) ; _StopWords . fillSegment ( theWord . trim ( ) . toLowerCase ( ) . toCharArray ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载量词词典 [CODESPLIT] private void loadQuantifierDict ( ) { // 建立一个量词典实例\r _QuantifierDict = new DictSegment ( ( char ) 0 ) ; // 读取量词词典文件\r Path file = PathUtils . get ( getDictRoot ( ) , Dictionary . PATH_DIC_QUANTIFIER ) ; loadDictFile ( _QuantifierDict , file , false , \"Quantifier\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void analyze ( AnalyzeContext context ) { if ( CharacterUtil . CHAR_USELESS != context . getCurrentCharType ( ) ) { //优先处理tmpHits中的hit\r if ( ! this . tmpHits . isEmpty ( ) ) { //处理词段队列\r Hit [ ] tmpArray = this . tmpHits . toArray ( new Hit [ this . tmpHits . size ( ) ] ) ; for ( Hit hit : tmpArray ) { hit = Dictionary . getSingleton ( ) . matchWithHit ( context . getSegmentBuff ( ) , context . getCursor ( ) , hit ) ; if ( hit . isMatch ( ) ) { //输出当前的词\r Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , hit . getBegin ( ) , context . getCursor ( ) - hit . getBegin ( ) + 1 , Lexeme . TYPE_CNWORD ) ; context . addLexeme ( newLexeme ) ; if ( ! hit . isPrefix ( ) ) { //不是词前缀，hit不需要继续匹配，移除\r this . tmpHits . remove ( hit ) ; } } else if ( hit . isUnmatch ( ) ) { //hit不是词，移除\r this . tmpHits . remove ( hit ) ; } } } //*********************************\r //再对当前指针位置的字符进行单字匹配\r Hit singleCharHit = Dictionary . getSingleton ( ) . matchInMainDict ( context . getSegmentBuff ( ) , context . getCursor ( ) , 1 ) ; if ( singleCharHit . isMatch ( ) ) { //首字成词\r //输出当前的词\r Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , context . getCursor ( ) , 1 , Lexeme . TYPE_CNWORD ) ; context . addLexeme ( newLexeme ) ; //同时也是词前缀\r if ( singleCharHit . isPrefix ( ) ) { //前缀匹配则放入hit列表\r this . tmpHits . add ( singleCharHit ) ; } } else if ( singleCharHit . isPrefix ( ) ) { //首字为词前缀\r //前缀匹配则放入hit列表\r this . tmpHits . add ( singleCharHit ) ; } } else { //遇到CHAR_USELESS字符\r //清空队列\r this . tmpHits . clear ( ) ; } //判断缓冲区是否已经读完\r if ( context . isBufferConsumed ( ) ) { //清空队列\r this . tmpHits . clear ( ) ; } //判断是否锁定缓冲区\r if ( this . tmpHits . size ( ) == 0 ) { context . unlockBuffer ( SEGMENTER_NAME ) ; } else { context . lockBuffer ( SEGMENTER_NAME ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "监控流程： ①向词库服务器发送Head请求 ②从响应中获取Last - Modify、ETags字段值，判断是否变化 ③如果未变化，休眠1min，返回第①步 ④如果有变化，重新加载词典 ⑤休眠1min，返回第①步 [CODESPLIT] public void runUnprivileged ( ) { //超时设置 RequestConfig rc = RequestConfig . custom ( ) . setConnectionRequestTimeout ( 10 * 1000 ) . setConnectTimeout ( 10 * 1000 ) . setSocketTimeout ( 15 * 1000 ) . build ( ) ; HttpHead head = new HttpHead ( location ) ; head . setConfig ( rc ) ; //设置请求头 if ( last_modified != null ) { head . setHeader ( \"If-Modified-Since\" , last_modified ) ; } if ( eTags != null ) { head . setHeader ( \"If-None-Match\" , eTags ) ; } CloseableHttpResponse response = null ; try { response = httpclient . execute ( head ) ; //返回200 才做操作 if ( response . getStatusLine ( ) . getStatusCode ( ) == 200 ) { if ( ( ( response . getLastHeader ( \"Last-Modified\" ) != null ) && ! response . getLastHeader ( \"Last-Modified\" ) . getValue ( ) . equalsIgnoreCase ( last_modified ) ) || ( ( response . getLastHeader ( \"ETag\" ) != null ) && ! response . getLastHeader ( \"ETag\" ) . getValue ( ) . equalsIgnoreCase ( eTags ) ) ) { // 远程词库有更新,需要重新加载词典，并修改last_modified,eTags Dictionary . getSingleton ( ) . reLoadMainDict ( ) ; last_modified = response . getLastHeader ( \"Last-Modified\" ) == null ? null : response . getLastHeader ( \"Last-Modified\" ) . getValue ( ) ; eTags = response . getLastHeader ( \"ETag\" ) == null ? null : response . getLastHeader ( \"ETag\" ) . getValue ( ) ; } } else if ( response . getStatusLine ( ) . getStatusCode ( ) == 304 ) { //没有修改，不做操作 //noop } else { logger . info ( \"remote_ext_dict {} return bad code {}\" , location , response . getStatusLine ( ) . getStatusCode ( ) ) ; } } catch ( Exception e ) { logger . error ( \"remote_ext_dict {} error!\" , e , location ) ; } finally { try { if ( response != null ) { response . close ( ) ; } } catch ( IOException e ) { logger . error ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向链表集合添加词元 [CODESPLIT] boolean addLexeme ( Lexeme lexeme ) { Cell newCell = new Cell ( lexeme ) ; if ( this . size == 0 ) { this . head = newCell ; this . tail = newCell ; this . size ++ ; return true ; } else { if ( this . tail . compareTo ( newCell ) == 0 ) { //词元与尾部词元相同，不放入集合\r return false ; } else if ( this . tail . compareTo ( newCell ) < 0 ) { //词元接入链表尾部\r this . tail . next = newCell ; newCell . prev = this . tail ; this . tail = newCell ; this . size ++ ; return true ; } else if ( this . head . compareTo ( newCell ) > 0 ) { //词元接入链表头部\r this . head . prev = newCell ; newCell . next = this . head ; this . head = newCell ; this . size ++ ; return true ; } else { //从尾部上逆\r Cell index = this . tail ; while ( index != null && index . compareTo ( newCell ) > 0 ) { index = index . prev ; } if ( index . compareTo ( newCell ) == 0 ) { //词元与集合中的词元重复，不放入集合\r return false ; } else if ( index . compareTo ( newCell ) < 0 ) { //词元插入链表中的某个位置\r newCell . prev = index ; newCell . next = index . next ; index . next . prev = newCell ; index . next = newCell ; this . size ++ ; return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取出链表集合的第一个元素 [CODESPLIT] Lexeme pollFirst ( ) { if ( this . size == 1 ) { Lexeme first = this . head . lexeme ; this . head = null ; this . tail = null ; this . size -- ; return first ; } else if ( this . size > 1 ) { Lexeme first = this . head . lexeme ; this . head = this . head . next ; this . size -- ; return first ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取出链表集合的最后一个元素 [CODESPLIT] Lexeme pollLast ( ) { if ( this . size == 1 ) { Lexeme last = this . head . lexeme ; this . head = null ; this . tail = null ; this . size -- ; return last ; } else if ( this . size > 1 ) { Lexeme last = this . tail . lexeme ; this . tail = this . tail . prev ; this . size -- ; return last ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分词 [CODESPLIT] public void analyze ( AnalyzeContext context ) { //处理中文数词\r this . processCNumber ( context ) ; //处理中文量词\r this . processCount ( context ) ; //判断是否锁定缓冲区\r if ( this . nStart == - 1 && this . nEnd == - 1 && countHits . isEmpty ( ) ) { //对缓冲区解锁\r context . unlockBuffer ( SEGMENTER_NAME ) ; } else { context . lockBuffer ( SEGMENTER_NAME ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理中文量词 [CODESPLIT] private void processCount ( AnalyzeContext context ) { // 判断是否需要启动量词扫描\r if ( ! this . needCountScan ( context ) ) { return ; } if ( CharacterUtil . CHAR_CHINESE == context . getCurrentCharType ( ) ) { //优先处理countHits中的hit\r if ( ! this . countHits . isEmpty ( ) ) { //处理词段队列\r Hit [ ] tmpArray = this . countHits . toArray ( new Hit [ this . countHits . size ( ) ] ) ; for ( Hit hit : tmpArray ) { hit = Dictionary . getSingleton ( ) . matchWithHit ( context . getSegmentBuff ( ) , context . getCursor ( ) , hit ) ; if ( hit . isMatch ( ) ) { //输出当前的词\r Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , hit . getBegin ( ) , context . getCursor ( ) - hit . getBegin ( ) + 1 , Lexeme . TYPE_COUNT ) ; context . addLexeme ( newLexeme ) ; if ( ! hit . isPrefix ( ) ) { //不是词前缀，hit不需要继续匹配，移除\r this . countHits . remove ( hit ) ; } } else if ( hit . isUnmatch ( ) ) { //hit不是词，移除\r this . countHits . remove ( hit ) ; } } } //*********************************\r //对当前指针位置的字符进行单字匹配\r Hit singleCharHit = Dictionary . getSingleton ( ) . matchInQuantifierDict ( context . getSegmentBuff ( ) , context . getCursor ( ) , 1 ) ; if ( singleCharHit . isMatch ( ) ) { //首字成量词词\r //输出当前的词\r Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , context . getCursor ( ) , 1 , Lexeme . TYPE_COUNT ) ; context . addLexeme ( newLexeme ) ; //同时也是词前缀\r if ( singleCharHit . isPrefix ( ) ) { //前缀匹配则放入hit列表\r this . countHits . add ( singleCharHit ) ; } } else if ( singleCharHit . isPrefix ( ) ) { //首字为量词前缀\r //前缀匹配则放入hit列表\r this . countHits . add ( singleCharHit ) ; } } else { //输入的不是中文字符\r //清空未成形的量词\r this . countHits . clear ( ) ; } //缓冲区数据已经读完，还有尚未输出的量词\r if ( context . isBufferConsumed ( ) ) { //清空未成形的量词\r this . countHits . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断是否需要扫描量词 [CODESPLIT] private boolean needCountScan ( AnalyzeContext context ) { if ( ( nStart != - 1 && nEnd != - 1 ) || ! countHits . isEmpty ( ) ) { //正在处理中文数词,或者正在处理量词\r return true ; } else { //找到一个相邻的数词\r if ( ! context . getOrgLexemes ( ) . isEmpty ( ) ) { Lexeme l = context . getOrgLexemes ( ) . peekLast ( ) ; if ( ( Lexeme . TYPE_CNUM == l . getLexemeType ( ) || Lexeme . TYPE_ARABIC == l . getLexemeType ( ) ) && ( l . getBegin ( ) + l . getLength ( ) == context . getCursor ( ) ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "添加数词词元到结果集 [CODESPLIT] private void outputNumLexeme ( AnalyzeContext context ) { if ( nStart > - 1 && nEnd > - 1 ) { //输出数词\r Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , nStart , nEnd - nStart + 1 , Lexeme . TYPE_CNUM ) ; context . addLexeme ( newLexeme ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "匹配词段 [CODESPLIT] Hit match ( char [ ] charArray , int begin , int length ) { return this . match ( charArray , begin , length , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载填充词典片段 [CODESPLIT] private synchronized void fillSegment ( char [ ] charArray , int begin , int length , int enabled ) { //获取字典表中的汉字对象 Character beginChar = Character . valueOf ( charArray [ begin ] ) ; Character keyChar = charMap . get ( beginChar ) ; //字典中没有该字，则将其添加入字典 if ( keyChar == null ) { charMap . put ( beginChar , beginChar ) ; keyChar = beginChar ; } //搜索当前节点的存储，查询对应keyChar的keyChar，如果没有则创建 DictSegment ds = lookforSegment ( keyChar , enabled ) ; if ( ds != null ) { //处理keyChar对应的segment if ( length > 1 ) { //词元还没有完全加入词典树 ds . fillSegment ( charArray , begin + 1 , length - 1 , enabled ) ; } else if ( length == 1 ) { //已经是词元的最后一个char,设置当前节点状态为enabled， //enabled=1表明一个完整的词，enabled=0表示从词典中屏蔽当前词 ds . nodeState = enabled ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查找本节点下对应的keyChar的segment * [CODESPLIT] private DictSegment lookforSegment ( Character keyChar , int create ) { DictSegment ds = null ; if ( this . storeSize <= ARRAY_LENGTH_LIMIT ) { //获取数组容器，如果数组未创建则创建数组 DictSegment [ ] segmentArray = getChildrenArray ( ) ; //搜寻数组 DictSegment keySegment = new DictSegment ( keyChar ) ; int position = Arrays . binarySearch ( segmentArray , 0 , this . storeSize , keySegment ) ; if ( position >= 0 ) { ds = segmentArray [ position ] ; } //遍历数组后没有找到对应的segment if ( ds == null && create == 1 ) { ds = keySegment ; if ( this . storeSize < ARRAY_LENGTH_LIMIT ) { //数组容量未满，使用数组存储 segmentArray [ this . storeSize ] = ds ; //segment数目+1 this . storeSize ++ ; Arrays . sort ( segmentArray , 0 , this . storeSize ) ; } else { //数组容量已满，切换Map存储 //获取Map容器，如果Map未创建,则创建Map Map < Character , DictSegment > segmentMap = getChildrenMap ( ) ; //将数组中的segment迁移到Map中 migrate ( segmentArray , segmentMap ) ; //存储新的segment segmentMap . put ( keyChar , ds ) ; //segment数目+1 ，  必须在释放数组前执行storeSize++ ， 确保极端情况下，不会取到空的数组 this . storeSize ++ ; //释放当前的数组引用 this . childrenArray = null ; } } } else { //获取Map容器，如果Map未创建,则创建Map Map < Character , DictSegment > segmentMap = getChildrenMap ( ) ; //搜索Map ds = ( DictSegment ) segmentMap . get ( keyChar ) ; if ( ds == null && create == 1 ) { //构造新的segment ds = new DictSegment ( keyChar ) ; segmentMap . put ( keyChar , ds ) ; //当前节点存储segment数目+1 this . storeSize ++ ; } } return ds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取Map容器 线程同步方法 [CODESPLIT] private Map < Character , DictSegment > getChildrenMap ( ) { synchronized ( this ) { if ( this . childrenMap == null ) { this . childrenMap = new ConcurrentHashMap < Character , DictSegment > ( ARRAY_LENGTH_LIMIT * 2 , 0.8f ) ; } } return this . childrenMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将数组中的segment迁移到Map中 [CODESPLIT] private void migrate ( DictSegment [ ] segmentArray , Map < Character , DictSegment > segmentMap ) { for ( DictSegment segment : segmentArray ) { if ( segment != null ) { segmentMap . put ( segment . nodeChar , segment ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 词元在排序集合中的比较算法 [CODESPLIT] public int compareTo ( Lexeme other ) { //起始位置优先\r if ( this . begin < other . getBegin ( ) ) { return - 1 ; } else if ( this . begin == other . getBegin ( ) ) { //词元长度优先\r if ( this . length > other . getLength ( ) ) { return - 1 ; } else if ( this . length == other . getLength ( ) ) { return 0 ; } else { //this.length < other.getLength()\r return 1 ; } } else { //this.begin > other.getBegin()\r return 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取词元类型标示字符串 [CODESPLIT] public String getLexemeTypeString ( ) { switch ( lexemeType ) { case TYPE_ENGLISH : return \"ENGLISH\" ; case TYPE_ARABIC : return \"ARABIC\" ; case TYPE_LETTER : return \"LETTER\" ; case TYPE_CNWORD : return \"CN_WORD\" ; case TYPE_CNCHAR : return \"CN_CHAR\" ; case TYPE_OTHER_CJK : return \"OTHER_CJK\" ; case TYPE_COUNT : return \"COUNT\" ; case TYPE_CNUM : return \"TYPE_CNUM\" ; case TYPE_CQUAN : return \"TYPE_CQUAN\" ; default : return \"UNKONW\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "合并两个相邻的词元 [CODESPLIT] public boolean append ( Lexeme l , int lexemeType ) { if ( l != null && this . getEndPosition ( ) == l . getBeginPosition ( ) ) { this . length += l . getLength ( ) ; this . lexemeType = lexemeType ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter } used for converting the OAuth 2 . 0 Error parameters to an { @link OAuth2Error } . [CODESPLIT] public final void setErrorConverter ( Converter < Map < String , String > , OAuth2Error > errorConverter ) { Assert . notNull ( errorConverter , \"errorConverter cannot be null\" ) ; this . errorConverter = errorConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter } used for converting the { @link OAuth2Error } to a { @code Map } representation of the OAuth 2 . 0 Error parameters . [CODESPLIT] public final void setErrorParametersConverter ( Converter < OAuth2Error , Map < String , String > > errorParametersConverter ) { Assert . notNull ( errorParametersConverter , \"errorParametersConverter cannot be null\" ) ; this . errorParametersConverter = errorParametersConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the { @link CsrfToken } [CODESPLIT] public void logout ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) { this . csrfTokenRepository . saveToken ( null , request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the maximum acceptable clock skew . The default is 60 seconds . The clock skew is used when validating the { @link JwtClaimNames#EXP exp } and { @link JwtClaimNames#IAT iat } claims . [CODESPLIT] public final void setClockSkew ( Duration clockSkew ) { Assert . notNull ( clockSkew , \"clockSkew cannot be null\" ) ; Assert . isTrue ( clockSkew . getSeconds ( ) >= 0 , \"clockSkew must be >= 0\" ) ; this . clockSkew = clockSkew ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter Converter&lt ; Jwt Collection&lt ; GrantedAuthority&gt ; &gt ; } to use . Defaults to { @link JwtGrantedAuthoritiesConverter } . [CODESPLIT] public void setJwtGrantedAuthoritiesConverter ( Converter < Jwt , Collection < GrantedAuthority > > jwtGrantedAuthoritiesConverter ) { Assert . notNull ( jwtGrantedAuthoritiesConverter , \"jwtGrantedAuthoritiesConverter cannot be null\" ) ; this . jwtGrantedAuthoritiesConverter = jwtGrantedAuthoritiesConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set to override the default HTTP port to HTTPS port mappings of 80 : 443 and 8080 : 8443 . In a Spring XML ApplicationContext a definition would look something like this : [CODESPLIT] public void setPortMappings ( Map < String , String > newMappings ) { Assert . notNull ( newMappings , \"A valid list of HTTPS port mappings must be provided\" ) ; this . httpsPortMappings . clear ( ) ; for ( Map . Entry < String , String > entry : newMappings . entrySet ( ) ) { Integer httpPort = Integer . valueOf ( entry . getKey ( ) ) ; Integer httpsPort = Integer . valueOf ( entry . getValue ( ) ) ; if ( ( httpPort . intValue ( ) < 1 ) || ( httpPort . intValue ( ) > 65535 ) || ( httpsPort . intValue ( ) < 1 ) || ( httpsPort . intValue ( ) > 65535 ) ) { throw new IllegalArgumentException ( \"one or both ports out of legal range: \" + httpPort + \", \" + httpsPort ) ; } this . httpsPortMappings . put ( httpPort , httpsPort ) ; } if ( this . httpsPortMappings . size ( ) < 1 ) { throw new IllegalArgumentException ( \"must map at least one port\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a directory for the user and a series of sub - directories . The root directory is the parent for the user directory . The sub - directories are confidential and shared . The ROLE_USER will be given read and write access to shared . [CODESPLIT] private void createSampleData ( String username , String password ) { Assert . notNull ( documentDao , \"DocumentDao required\" ) ; Assert . hasText ( username , \"Username required\" ) ; Authentication auth = new UsernamePasswordAuthenticationToken ( username , password ) ; try { // Set the SecurityContextHolder ThreadLocal so any subclasses // automatically know which user is operating SecurityContextHolder . getContext ( ) . setAuthentication ( auth ) ; // Create the home directory first Directory home = new Directory ( username , Directory . ROOT_DIRECTORY ) ; documentDao . create ( home ) ; addPermission ( documentDao , home , username , LEVEL_GRANT_ADMIN ) ; addPermission ( documentDao , home , \"ROLE_USER\" , LEVEL_GRANT_READ ) ; createFiles ( documentDao , home ) ; // Now create the confidential directory Directory confid = new Directory ( \"confidential\" , home ) ; documentDao . create ( confid ) ; addPermission ( documentDao , confid , \"ROLE_USER\" , LEVEL_NEGATE_READ ) ; createFiles ( documentDao , confid ) ; // Now create the shared directory Directory shared = new Directory ( \"shared\" , home ) ; documentDao . create ( shared ) ; addPermission ( documentDao , shared , \"ROLE_USER\" , LEVEL_GRANT_READ ) ; addPermission ( documentDao , shared , \"ROLE_USER\" , LEVEL_GRANT_WRITE ) ; createFiles ( documentDao , shared ) ; } finally { // Clear the SecurityContextHolder ThreadLocal so future calls are // guaranteed to be clean SecurityContextHolder . clearContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the algorithm to use . See <a href = https : // docs . oracle . com / javase / 8 / docs / technotes / guides / security / StandardNames . html#SecretKeyFactory > SecretKeyFactory Algorithms< / a > [CODESPLIT] public void setAlgorithm ( SecretKeyFactoryAlgorithm secretKeyFactoryAlgorithm ) { if ( secretKeyFactoryAlgorithm == null ) { throw new IllegalArgumentException ( \"secretKeyFactoryAlgorithm cannot be null\" ) ; } String algorithmName = secretKeyFactoryAlgorithm . name ( ) ; try { SecretKeyFactory . getInstance ( algorithmName ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( \"Invalid algorithm '\" + algorithmName + \"'.\" , e ) ; } this . algorithm = algorithmName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the callback passed to the handle method is an instance of PasswordCallback the JaasPasswordCallbackHandler will call callback . setPassword ( authentication . getCredentials () . toString () ) . [CODESPLIT] public void handle ( Callback callback , Authentication auth ) throws IOException , UnsupportedCallbackException { if ( callback instanceof PasswordCallback ) { PasswordCallback pc = ( PasswordCallback ) callback ; pc . setPassword ( auth . getCredentials ( ) . toString ( ) . toCharArray ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a save way of obtaining the HttpMethod from a String . If the method is invalid returns null . [CODESPLIT] private static HttpMethod valueOf ( String method ) { try { return HttpMethod . valueOf ( method ) ; } catch ( IllegalArgumentException e ) { } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void doFilter ( ServletRequest req , ServletResponse res , FilterChain chain ) throws IOException , ServletException { HttpServletRequest request = ( HttpServletRequest ) req ; HttpServletResponse response = ( HttpServletResponse ) res ; if ( requiresLogout ( request , response ) ) { Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Logging out user '\" + auth + \"' and transferring to logout destination\" ) ; } this . handler . logout ( request , response , auth ) ; logoutSuccessHandler . onLogoutSuccess ( request , response , auth ) ; return ; } chain . doFilter ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the LdapUserDetails containing the user s information [CODESPLIT] @ Override public DirContextOperations searchForUser ( String username ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Searching for user '\" + username + \"', with user search \" + this ) ; } SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate ( contextSource ) ; template . setSearchControls ( searchControls ) ; try { return template . searchForSingleEntry ( searchBase , searchFilter , new String [ ] { username } ) ; } catch ( IncorrectResultSizeDataAccessException notFound ) { if ( notFound . getActualSize ( ) == 0 ) { throw new UsernameNotFoundException ( \"User \" + username + \" not found in directory.\" ) ; } // Search should never return multiple results if properly configured, so just // rethrow throw notFound ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public String beginConsumption ( HttpServletRequest req , String identityUrl , String returnToUrl , String realm ) throws OpenIDConsumerException { List < DiscoveryInformation > discoveries ; try { discoveries = consumerManager . discover ( identityUrl ) ; } catch ( DiscoveryException e ) { throw new OpenIDConsumerException ( \"Error during discovery\" , e ) ; } DiscoveryInformation information = consumerManager . associate ( discoveries ) ; req . getSession ( ) . setAttribute ( DISCOVERY_INFO_KEY , information ) ; AuthRequest authReq ; try { authReq = consumerManager . authenticate ( information , returnToUrl , realm ) ; logger . debug ( \"Looking up attribute fetch list for identifier: \" + identityUrl ) ; List < OpenIDAttribute > attributesToFetch = attributesToFetchFactory . createAttributeList ( identityUrl ) ; if ( ! attributesToFetch . isEmpty ( ) ) { req . getSession ( ) . setAttribute ( ATTRIBUTE_LIST_KEY , attributesToFetch ) ; FetchRequest fetchRequest = FetchRequest . createFetchRequest ( ) ; for ( OpenIDAttribute attr : attributesToFetch ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Adding attribute \" + attr . getType ( ) + \" to fetch request\" ) ; } fetchRequest . addAttribute ( attr . getName ( ) , attr . getType ( ) , attr . isRequired ( ) , attr . getCount ( ) ) ; } authReq . addExtension ( fetchRequest ) ; } } catch ( MessageException e ) { throw new OpenIDConsumerException ( \"Error processing ConsumerManager authentication\" , e ) ; } catch ( ConsumerException e ) { throw new OpenIDConsumerException ( \"Error processing ConsumerManager authentication\" , e ) ; } return authReq . getDestinationUrl ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the rawPass using a MessageDigest . If a salt is specified it will be merged with the password before encoding . [CODESPLIT] public String encode ( CharSequence rawPassword ) { String salt = PREFIX + this . saltGenerator . generateKey ( ) + SUFFIX ; return digest ( salt , rawPassword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a previously encoded password and compares it with a rawpassword after mixing in the salt and encoding that value [CODESPLIT] public boolean matches ( CharSequence rawPassword , String encodedPassword ) { String salt = extractSalt ( encodedPassword ) ; String rawPasswordEncoded = digest ( salt , rawPassword ) ; return PasswordEncoderUtils . equals ( encodedPassword . toString ( ) , rawPasswordEncoded ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform version checks with specific min Spring Version [CODESPLIT] private static void performVersionChecks ( String minSpringVersion ) { if ( minSpringVersion == null ) { return ; } // Check Spring Compatibility String springVersion = SpringVersion . getVersion ( ) ; String version = getVersion ( ) ; if ( disableChecks ( springVersion , version ) ) { return ; } logger . info ( \"You are running with Spring Security Core \" + version ) ; if ( new ComparableVersion ( springVersion ) . compareTo ( new ComparableVersion ( minSpringVersion ) ) < 0 ) { logger . warn ( \"**** You are advised to use Spring \" + minSpringVersion + \" or later with this version. You are running: \" + springVersion ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable if springVersion and springSecurityVersion are the same to allow working with Uber Jars . [CODESPLIT] private static boolean disableChecks ( String springVersion , String springSecurityVersion ) { if ( springVersion == null || springVersion . equals ( springSecurityVersion ) ) { return true ; } return Boolean . getBoolean ( DISABLE_CHECKS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the spring version or null if it cannot be found . [CODESPLIT] private static String getSpringVersion ( ) { Properties properties = new Properties ( ) ; try { properties . load ( SpringSecurityCoreVersion . class . getClassLoader ( ) . getResourceAsStream ( \"META-INF/spring-security.versions\" ) ) ; } catch ( IOException | NullPointerException e ) { return null ; } return properties . getProperty ( \"org.springframework:spring-core\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to load the client registration id from the current { [CODESPLIT] private Mono < String > clientRegistrationId ( Mono < Authentication > authentication ) { return authentication . filter ( t -> this . defaultOAuth2AuthorizedClient && t instanceof OAuth2AuthenticationToken ) . cast ( OAuth2AuthenticationToken . class ) . map ( OAuth2AuthenticationToken :: getAuthorizedClientRegistrationId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through all <code > AfterInvocationProvider< / code > s and ensures each can support the presented class . <p > If one or more providers cannot support the presented class <code > false< / code > is returned . [CODESPLIT] public boolean supports ( Class < ? > clazz ) { for ( AfterInvocationProvider provider : providers ) { if ( ! provider . supports ( clazz ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut for invoking { @link #authenticationUserDetailsService ( AuthenticationUserDetailsService ) } with a { @link UserDetailsByNameServiceWrapper } . [CODESPLIT] public X509Configurer < H > userDetailsService ( UserDetailsService userDetailsService ) { UserDetailsByNameServiceWrapper < PreAuthenticatedAuthenticationToken > authenticationUserDetailsService = new UserDetailsByNameServiceWrapper <> ( ) ; authenticationUserDetailsService . setUserDetailsService ( userDetailsService ) ; return authenticationUserDetailsService ( authenticationUserDetailsService ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the regex to extract the principal from the certificate . If not specified the default expression from { @link SubjectDnX509PrincipalExtractor } is used . [CODESPLIT] public X509Configurer < H > subjectPrincipalRegex ( String subjectPrincipalRegex ) { SubjectDnX509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor ( ) ; principalExtractor . setSubjectDnRegex ( subjectPrincipalRegex ) ; this . x509PrincipalExtractor = principalExtractor ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public final O build ( ) throws Exception { if ( this . building . compareAndSet ( false , true ) ) { this . object = doBuild ( ) ; return this . object ; } throw new AlreadyBuiltException ( \"This object has already been built\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public final Collection < ConfigAttribute > getAttributes ( Object object ) { if ( object instanceof MethodInvocation ) { MethodInvocation mi = ( MethodInvocation ) object ; Object target = mi . getThis ( ) ; Class < ? > targetClass = null ; if ( target != null ) { targetClass = target instanceof Class < ? > ? ( Class < ? > ) target : AopProxyUtils . ultimateTargetClass ( target ) ; } Collection < ConfigAttribute > attrs = getAttributes ( mi . getMethod ( ) , targetClass ) ; if ( attrs != null && ! attrs . isEmpty ( ) ) { return attrs ; } if ( target != null && ! ( target instanceof Class < ? > ) ) { attrs = getAttributes ( mi . getMethod ( ) , target . getClass ( ) ) ; } return attrs ; } throw new IllegalArgumentException ( \"Object must be a non-null MethodInvocation\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a non - null and mutable map of { [CODESPLIT] private Map < String , OAuth2AuthorizationRequest > getAuthorizationRequests ( HttpServletRequest request ) { HttpSession session = request . getSession ( false ) ; Map < String , OAuth2AuthorizationRequest > authorizationRequests = session == null ? null : ( Map < String , OAuth2AuthorizationRequest > ) session . getAttribute ( this . sessionAttributeName ) ; if ( authorizationRequests == null ) { return new HashMap <> ( ) ; } return authorizationRequests ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void logIfNeeded ( boolean granted , AccessControlEntry ace ) { Assert . notNull ( ace , \"AccessControlEntry required\" ) ; if ( ace instanceof AuditableAccessControlEntry ) { AuditableAccessControlEntry auditableAce = ( AuditableAccessControlEntry ) ace ; if ( granted && auditableAce . isAuditSuccess ( ) ) { System . out . println ( \"GRANTED due to ACE: \" + ace ) ; } else if ( ! granted && auditableAce . isAuditFailure ( ) ) { System . out . println ( \"DENIED due to ACE: \" + ace ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up OpenID attribute exchange for OpenID s matching the specified pattern . [CODESPLIT] public AttributeExchangeConfigurer attributeExchange ( String identifierPattern ) { AttributeExchangeConfigurer attributeExchangeConfigurer = new AttributeExchangeConfigurer ( identifierPattern ) ; this . attributeExchangeConfigurers . add ( attributeExchangeConfigurer ) ; return attributeExchangeConfigurer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] private OpenIDConsumer getConsumer ( ) throws ConsumerException { if ( this . openIDConsumer == null ) { this . openIDConsumer = new OpenID4JavaConsumer ( getConsumerManager ( ) , attributesToFetchFactory ( ) ) ; } return this . openIDConsumer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an { @link RegexBasedAxFetchListFactory } using the attributes populated by { @link AttributeExchangeConfigurer } [CODESPLIT] private AxFetchListFactory attributesToFetchFactory ( ) { Map < String , List < OpenIDAttribute > > identityToAttrs = new HashMap < String , List < OpenIDAttribute > > ( ) ; for ( AttributeExchangeConfigurer conf : this . attributeExchangeConfigurers ) { identityToAttrs . put ( conf . identifier , conf . getAttributes ( ) ) ; } return new RegexBasedAxFetchListFactory ( identityToAttrs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link AuthenticationUserDetailsService } that was configured or defaults to { @link UserDetailsByNameServiceWrapper } that uses a { @link UserDetailsService } looked up using { @link HttpSecurity#getSharedObject ( Class ) } [CODESPLIT] private AuthenticationUserDetailsService < OpenIDAuthenticationToken > getAuthenticationUserDetailsService ( H http ) { if ( this . authenticationUserDetailsService != null ) { return this . authenticationUserDetailsService ; } return new UserDetailsByNameServiceWrapper <> ( http . getSharedObject ( UserDetailsService . class ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If available initializes the { @link DefaultLoginPageGeneratingFilter } shared object . [CODESPLIT] private void initDefaultLoginFilter ( H http ) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http . getSharedObject ( DefaultLoginPageGeneratingFilter . class ) ; if ( loginPageGeneratingFilter != null && ! isCustomLoginPage ( ) ) { loginPageGeneratingFilter . setOpenIdEnabled ( true ) ; loginPageGeneratingFilter . setOpenIDauthenticationUrl ( getLoginProcessingUrl ( ) ) ; String loginPageUrl = loginPageGeneratingFilter . getLoginPageUrl ( ) ; if ( loginPageUrl == null ) { loginPageGeneratingFilter . setLoginPageUrl ( getLoginPage ( ) ) ; loginPageGeneratingFilter . setFailureUrl ( getFailureUrl ( ) ) ; } loginPageGeneratingFilter . setOpenIDusernameParameter ( OpenIDAuthenticationFilter . DEFAULT_CLAIMED_IDENTITY_FIELD ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows restricting access based upon the { @link HttpServletRequest } using [CODESPLIT] public ExpressionUrlAuthorizationConfigurer < HttpSecurity > . ExpressionInterceptUrlRegistry authorizeRequests ( ) throws Exception { ApplicationContext context = getContext ( ) ; return getOrApply ( new ExpressionUrlAuthorizationConfigurer <> ( context ) ) . getRegistry ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds CSRF support . This is activated by default when using { @link WebSecurityConfigurerAdapter } s default constructor . You can disable it using : [CODESPLIT] public CsrfConfigurer < HttpSecurity > csrf ( ) throws Exception { ApplicationContext context = getContext ( ) ; return getOrApply ( new CsrfConfigurer <> ( context ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures OAuth 2 . 0 Client support . [CODESPLIT] public OAuth2ClientConfigurer < HttpSecurity > oauth2Client ( ) throws Exception { OAuth2ClientConfigurer < HttpSecurity > configurer = getOrApply ( new OAuth2ClientConfigurer <> ( ) ) ; this . postProcess ( configurer ) ; return configurer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures OAuth 2 . 0 Resource Server support . [CODESPLIT] public OAuth2ResourceServerConfigurer < HttpSecurity > oauth2ResourceServer ( ) throws Exception { OAuth2ResourceServerConfigurer < HttpSecurity > configurer = getOrApply ( new OAuth2ResourceServerConfigurer <> ( getContext ( ) ) ) ; this . postProcess ( configurer ) ; return configurer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures channel security . In order for this configuration to be useful at least one mapping to a required channel must be provided . [CODESPLIT] public ChannelSecurityConfigurer < HttpSecurity > . ChannelRequestMatcherRegistry requiresChannel ( ) throws Exception { ApplicationContext context = getContext ( ) ; return getOrApply ( new ChannelSecurityConfigurer <> ( context ) ) . getRegistry ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public HttpSecurity addFilterAfter ( Filter filter , Class < ? extends Filter > afterFilter ) { comparator . registerAfter ( filter . getClass ( ) , afterFilter ) ; return addFilter ( filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public HttpSecurity addFilterBefore ( Filter filter , Class < ? extends Filter > beforeFilter ) { comparator . registerBefore ( filter . getClass ( ) , beforeFilter ) ; return addFilter ( filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public HttpSecurity addFilter ( Filter filter ) { Class < ? extends Filter > filterClass = filter . getClass ( ) ; if ( ! comparator . isRegistered ( filterClass ) ) { throw new IllegalArgumentException ( \"The Filter class \" + filterClass . getName ( ) + \" does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.\" ) ; } this . filters . add ( filter ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the Filter at the location of the specified Filter class . For example if you want the filter CustomFilter to be registered in the same position as { @link UsernamePasswordAuthenticationFilter } you can invoke : [CODESPLIT] public HttpSecurity addFilterAt ( Filter filter , Class < ? extends Filter > atFilter ) { this . comparator . registerAt ( filter . getClass ( ) , atFilter ) ; return addFilter ( filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows configuring the { @link HttpSecurity } to only be invoked when matching the provided Spring MVC pattern . If more advanced configuration is necessary consider using { @link #requestMatchers () } or { @link #requestMatcher ( RequestMatcher ) } . [CODESPLIT] public HttpSecurity mvcMatcher ( String mvcPattern ) { HandlerMappingIntrospector introspector = new HandlerMappingIntrospector ( getContext ( ) ) ; return requestMatcher ( new MvcRequestMatcher ( introspector , mvcPattern ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the { @link SecurityConfigurer } has already been specified get the original otherwise apply the new { @link SecurityConfigurerAdapter } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private < C extends SecurityConfigurerAdapter < DefaultSecurityFilterChain , HttpSecurity > > C getOrApply ( C configurer ) throws Exception { C existingConfig = ( C ) getConfigurer ( configurer . getClass ( ) ) ; if ( existingConfig != null ) { return existingConfig ; } return apply ( configurer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link List } of { @link PathPatternParserServerWebExchangeMatcher } instances . [CODESPLIT] public T pathMatchers ( HttpMethod method , String ... antPatterns ) { return matcher ( ServerWebExchangeMatchers . pathMatchers ( method , antPatterns ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an LDAP compare operation of the value of an attribute for a particular directory entry . [CODESPLIT] public boolean compare ( final String dn , final String attributeName , final Object value ) { final String comparisonFilter = \"(\" + attributeName + \"={0})\" ; class LdapCompareCallback implements ContextExecutor { public Object executeWithContext ( DirContext ctx ) throws NamingException { SearchControls ctls = new SearchControls ( ) ; ctls . setReturningAttributes ( NO_ATTRS ) ; ctls . setSearchScope ( SearchControls . OBJECT_SCOPE ) ; NamingEnumeration < SearchResult > results = ctx . search ( dn , comparisonFilter , new Object [ ] { value } , ctls ) ; Boolean match = Boolean . valueOf ( results . hasMore ( ) ) ; LdapUtils . closeEnumeration ( results ) ; return match ; } } Boolean matches = ( Boolean ) executeReadOnly ( new LdapCompareCallback ( ) ) ; return matches . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Composes an object from the attributes of the given DN . [CODESPLIT] public DirContextOperations retrieveEntry ( final String dn , final String [ ] attributesToRetrieve ) { return ( DirContextOperations ) executeReadOnly ( new ContextExecutor ( ) { public Object executeWithContext ( DirContext ctx ) throws NamingException { Attributes attrs = ctx . getAttributes ( dn , attributesToRetrieve ) ; // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx)); return new DirContextAdapter ( attrs , new DistinguishedName ( dn ) , new DistinguishedName ( ctx . getNameInNamespace ( ) ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search using the supplied filter and returns the union of the values of the named attribute found in all entries matched by the search . Note that one directory entry may have several values for the attribute . Intended for role searches and similar scenarios . [CODESPLIT] public Set < String > searchForSingleAttributeValues ( final String base , final String filter , final Object [ ] params , final String attributeName ) { String [ ] attributeNames = new String [ ] { attributeName } ; Set < Map < String , List < String > > > multipleAttributeValues = searchForMultipleAttributeValues ( base , filter , params , attributeNames ) ; Set < String > result = new HashSet <> ( ) ; for ( Map < String , List < String > > map : multipleAttributeValues ) { List < String > values = map . get ( attributeName ) ; if ( values != null ) { result . addAll ( values ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search using the supplied filter and returns the values of each named attribute found in all entries matched by the search . Note that one directory entry may have several values for the attribute . Intended for role searches and similar scenarios . [CODESPLIT] public Set < Map < String , List < String > > > searchForMultipleAttributeValues ( final String base , final String filter , final Object [ ] params , final String [ ] attributeNames ) { // Escape the params acording to RFC2254 Object [ ] encodedParams = new String [ params . length ] ; for ( int i = 0 ; i < params . length ; i ++ ) { encodedParams [ i ] = LdapEncoder . filterEncode ( params [ i ] . toString ( ) ) ; } String formattedFilter = MessageFormat . format ( filter , encodedParams ) ; logger . debug ( \"Using filter: \" + formattedFilter ) ; final HashSet < Map < String , List < String > > > set = new HashSet < Map < String , List < String > > > ( ) ; ContextMapper roleMapper = new ContextMapper ( ) { public Object mapFromContext ( Object ctx ) { DirContextAdapter adapter = ( DirContextAdapter ) ctx ; Map < String , List < String > > record = new HashMap < String , List < String > > ( ) ; if ( attributeNames == null || attributeNames . length == 0 ) { try { for ( NamingEnumeration ae = adapter . getAttributes ( ) . getAll ( ) ; ae . hasMore ( ) ; ) { Attribute attr = ( Attribute ) ae . next ( ) ; extractStringAttributeValues ( adapter , record , attr . getID ( ) ) ; } } catch ( NamingException x ) { org . springframework . ldap . support . LdapUtils . convertLdapException ( x ) ; } } else { for ( String attributeName : attributeNames ) { extractStringAttributeValues ( adapter , record , attributeName ) ; } } record . put ( DN_KEY , Arrays . asList ( getAdapterDN ( adapter ) ) ) ; set . add ( record ) ; return null ; } } ; SearchControls ctls = new SearchControls ( ) ; ctls . setSearchScope ( searchControls . getSearchScope ( ) ) ; ctls . setReturningAttributes ( attributeNames != null && attributeNames . length > 0 ? attributeNames : null ) ; search ( base , formattedFilter , ctls , roleMapper ) ; return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts String values for a specified attribute name and places them in the map representing the ldap record If a value is not of type String it will derive it s value from the { @link Object#toString () } [CODESPLIT] private void extractStringAttributeValues ( DirContextAdapter adapter , Map < String , List < String > > record , String attributeName ) { Object [ ] values = adapter . getObjectAttributes ( attributeName ) ; if ( values == null || values . length == 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"No attribute value found for '\" + attributeName + \"'\" ) ; } return ; } List < String > svalues = new ArrayList <> ( ) ; for ( Object o : values ) { if ( o != null ) { if ( String . class . isAssignableFrom ( o . getClass ( ) ) ) { svalues . add ( ( String ) o ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Attribute:\" + attributeName + \" contains a non string value of type[\" + o . getClass ( ) + \"]\" ) ; } svalues . add ( o . toString ( ) ) ; } } } record . put ( attributeName , svalues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search with the requirement that the search shall return a single directory entry and uses the supplied mapper to create the object from that entry . <p > Ignores <tt > PartialResultException< / tt > if thrown for compatibility with Active Directory ( see { @link LdapTemplate#setIgnorePartialResultException ( boolean ) } ) . [CODESPLIT] public DirContextOperations searchForSingleEntry ( final String base , final String filter , final Object [ ] params ) { return ( DirContextOperations ) executeReadOnly ( new ContextExecutor ( ) { public Object executeWithContext ( DirContext ctx ) throws NamingException { return searchForSingleEntryInternal ( ctx , searchControls , base , filter , params ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method extracted to avoid code duplication in AD search . [CODESPLIT] public static DirContextOperations searchForSingleEntryInternal ( DirContext ctx , SearchControls searchControls , String base , String filter , Object [ ] params ) throws NamingException { final DistinguishedName ctxBaseDn = new DistinguishedName ( ctx . getNameInNamespace ( ) ) ; final DistinguishedName searchBaseDn = new DistinguishedName ( base ) ; final NamingEnumeration < SearchResult > resultsEnum = ctx . search ( searchBaseDn , filter , params , buildControls ( searchControls ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Searching for entry under DN '\" + ctxBaseDn + \"', base = '\" + searchBaseDn + \"', filter = '\" + filter + \"'\" ) ; } Set < DirContextOperations > results = new HashSet <> ( ) ; try { while ( resultsEnum . hasMore ( ) ) { SearchResult searchResult = resultsEnum . next ( ) ; DirContextAdapter dca = ( DirContextAdapter ) searchResult . getObject ( ) ; Assert . notNull ( dca , \"No object returned by search, DirContext is not correctly configured\" ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Found DN: \" + dca . getDn ( ) ) ; } results . add ( dca ) ; } } catch ( PartialResultException e ) { LdapUtils . closeEnumeration ( resultsEnum ) ; logger . info ( \"Ignoring PartialResultException\" ) ; } if ( results . size ( ) == 0 ) { throw new IncorrectResultSizeDataAccessException ( 1 , 0 ) ; } if ( results . size ( ) > 1 ) { throw new IncorrectResultSizeDataAccessException ( 1 , results . size ( ) ) ; } return results . iterator ( ) . next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We need to make sure the search controls has the return object flag set to true in order for the search to return DirContextAdapter instances . [CODESPLIT] private static SearchControls buildControls ( SearchControls originalControls ) { return new SearchControls ( originalControls . getSearchScope ( ) , originalControls . getCountLimit ( ) , originalControls . getTimeLimit ( ) , originalControls . getReturningAttributes ( ) , RETURN_OBJECT , originalControls . getDerefLinkFlag ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] private String computeRepeatingSql ( String repeatingSql , int requiredRepetitions ) { assert requiredRepetitions > 0 : \"requiredRepetitions must be > 0\" ; final String startSql = selectClause ; final String endSql = orderByClause ; StringBuilder sqlStringBldr = new StringBuilder ( startSql . length ( ) + endSql . length ( ) + requiredRepetitions * ( repeatingSql . length ( ) + 4 ) ) ; sqlStringBldr . append ( startSql ) ; for ( int i = 1 ; i <= requiredRepetitions ; i ++ ) { sqlStringBldr . append ( repeatingSql ) ; if ( i != requiredRepetitions ) { sqlStringBldr . append ( \" or \" ) ; } } sqlStringBldr . append ( endSql ) ; return sqlStringBldr . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates the primary key IDs specified in findNow adding AclImpl instances with StubAclParents to the acls Map . [CODESPLIT] private void lookupPrimaryKeys ( final Map < Serializable , Acl > acls , final Set < Long > findNow , final List < Sid > sids ) { Assert . notNull ( acls , \"ACLs are required\" ) ; Assert . notEmpty ( findNow , \"Items to find now required\" ) ; String sql = computeRepeatingSql ( lookupPrimaryKeysWhereClause , findNow . size ( ) ) ; Set < Long > parentsToLookup = jdbcTemplate . query ( sql , new PreparedStatementSetter ( ) { public void setValues ( PreparedStatement ps ) throws SQLException { int i = 0 ; for ( Long toFind : findNow ) { i ++ ; ps . setLong ( i , toFind ) ; } } } , new ProcessResultSet ( acls , sids ) ) ; // Lookup the parents, now that our JdbcTemplate has released the database // connection (SEC-547) if ( parentsToLookup . size ( ) > 0 ) { lookupPrimaryKeys ( acls , parentsToLookup , sids ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main method . <p > WARNING : This implementation completely disregards the sids argument! Every item in the cache is expected to contain all SIDs . If you have serious performance needs ( e . g . a very large number of SIDs per object identity ) you ll probably want to develop a custom { @link LookupStrategy } implementation instead . <p > The implementation works in batch sizes specified by { @link #batchSize } . [CODESPLIT] public final Map < ObjectIdentity , Acl > readAclsById ( List < ObjectIdentity > objects , List < Sid > sids ) { Assert . isTrue ( batchSize >= 1 , \"BatchSize must be >= 1\" ) ; Assert . notEmpty ( objects , \"Objects to lookup required\" ) ; // Map<ObjectIdentity,Acl> Map < ObjectIdentity , Acl > result = new HashMap <> ( ) ; // contains // FULLY // loaded // Acl // objects Set < ObjectIdentity > currentBatchToLoad = new HashSet <> ( ) ; for ( int i = 0 ; i < objects . size ( ) ; i ++ ) { final ObjectIdentity oid = objects . get ( i ) ; boolean aclFound = false ; // Check we don't already have this ACL in the results if ( result . containsKey ( oid ) ) { aclFound = true ; } // Check cache for the present ACL entry if ( ! aclFound ) { Acl acl = aclCache . getFromCache ( oid ) ; // Ensure any cached element supports all the requested SIDs // (they should always, as our base impl doesn't filter on SID) if ( acl != null ) { if ( acl . isSidLoaded ( sids ) ) { result . put ( acl . getObjectIdentity ( ) , acl ) ; aclFound = true ; } else { throw new IllegalStateException ( \"Error: SID-filtered element detected when implementation does not perform SID filtering \" + \"- have you added something to the cache manually?\" ) ; } } } // Load the ACL from the database if ( ! aclFound ) { currentBatchToLoad . add ( oid ) ; } // Is it time to load from JDBC the currentBatchToLoad? if ( ( currentBatchToLoad . size ( ) == this . batchSize ) || ( ( i + 1 ) == objects . size ( ) ) ) { if ( currentBatchToLoad . size ( ) > 0 ) { Map < ObjectIdentity , Acl > loadedBatch = lookupObjectIdentities ( currentBatchToLoad , sids ) ; // Add loaded batch (all elements 100% initialized) to results result . putAll ( loadedBatch ) ; // Add the loaded batch to the cache for ( Acl loadedAcl : loadedBatch . values ( ) ) { aclCache . putInCache ( ( AclImpl ) loadedAcl ) ; } currentBatchToLoad . clear ( ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up a batch of <code > ObjectIdentity< / code > s directly from the database . <p > The caller is responsible for optimization issues such as selecting the identities to lookup ensuring the cache doesn t contain them already and adding the returned elements to the cache etc . <p > This subclass is required to return fully valid <code > Acl< / code > s including properly - configured parent ACLs . [CODESPLIT] private Map < ObjectIdentity , Acl > lookupObjectIdentities ( final Collection < ObjectIdentity > objectIdentities , List < Sid > sids ) { Assert . notEmpty ( objectIdentities , \"Must provide identities to lookup\" ) ; final Map < Serializable , Acl > acls = new HashMap <> ( ) ; // contains // Acls // with // StubAclParents // Make the \"acls\" map contain all requested objectIdentities // (including markers to each parent in the hierarchy) String sql = computeRepeatingSql ( lookupObjectIdentitiesWhereClause , objectIdentities . size ( ) ) ; Set < Long > parentsToLookup = jdbcTemplate . query ( sql , new PreparedStatementSetter ( ) { public void setValues ( PreparedStatement ps ) throws SQLException { int i = 0 ; for ( ObjectIdentity oid : objectIdentities ) { // Determine prepared statement values for this iteration String type = oid . getType ( ) ; // No need to check for nulls, as guaranteed non-null by // ObjectIdentity.getIdentifier() interface contract String identifier = oid . getIdentifier ( ) . toString ( ) ; // Inject values ps . setString ( ( 2 * i ) + 1 , identifier ) ; ps . setString ( ( 2 * i ) + 2 , type ) ; i ++ ; } } } , new ProcessResultSet ( acls , sids ) ) ; // Lookup the parents, now that our JdbcTemplate has released the database // connection (SEC-547) if ( parentsToLookup . size ( ) > 0 ) { lookupPrimaryKeys ( acls , parentsToLookup , sids ) ; } // Finally, convert our \"acls\" containing StubAclParents into true Acls Map < ObjectIdentity , Acl > resultMap = new HashMap <> ( ) ; for ( Acl inputAcl : acls . values ( ) ) { Assert . isInstanceOf ( AclImpl . class , inputAcl , \"Map should have contained an AclImpl\" ) ; Assert . isInstanceOf ( Long . class , ( ( AclImpl ) inputAcl ) . getId ( ) , \"Acl.getId() must be Long\" ) ; Acl result = convert ( acls , ( Long ) ( ( AclImpl ) inputAcl ) . getId ( ) ) ; resultMap . put ( result . getObjectIdentity ( ) , result ) ; } return resultMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The final phase of converting the <code > Map< / code > of <code > AclImpl< / code > instances which contain <code > StubAclParent< / code > s into proper valid <code > AclImpl< / code > s with correct ACL parents . [CODESPLIT] private AclImpl convert ( Map < Serializable , Acl > inputMap , Long currentIdentity ) { Assert . notEmpty ( inputMap , \"InputMap required\" ) ; Assert . notNull ( currentIdentity , \"CurrentIdentity required\" ) ; // Retrieve this Acl from the InputMap Acl uncastAcl = inputMap . get ( currentIdentity ) ; Assert . isInstanceOf ( AclImpl . class , uncastAcl , \"The inputMap contained a non-AclImpl\" ) ; AclImpl inputAcl = ( AclImpl ) uncastAcl ; Acl parent = inputAcl . getParentAcl ( ) ; if ( ( parent != null ) && parent instanceof StubAclParent ) { // Lookup the parent StubAclParent stubAclParent = ( StubAclParent ) parent ; parent = convert ( inputMap , stubAclParent . getId ( ) ) ; } // Now we have the parent (if there is one), create the true AclImpl AclImpl result = new AclImpl ( inputAcl . getObjectIdentity ( ) , ( Long ) inputAcl . getId ( ) , aclAuthorizationStrategy , grantingStrategy , parent , null , inputAcl . isEntriesInheriting ( ) , inputAcl . getOwner ( ) ) ; // Copy the \"aces\" from the input to the destination // Obtain the \"aces\" from the input ACL List < AccessControlEntryImpl > aces = readAces ( inputAcl ) ; // Create a list in which to store the \"aces\" for the \"result\" AclImpl instance List < AccessControlEntryImpl > acesNew = new ArrayList <> ( ) ; // Iterate over the \"aces\" input and replace each nested // AccessControlEntryImpl.getAcl() with the new \"result\" AclImpl instance // This ensures StubAclParent instances are removed, as per SEC-951 for ( AccessControlEntryImpl ace : aces ) { setAclOnAce ( ace , result ) ; acesNew . add ( ace ) ; } // Finally, now that the \"aces\" have been converted to have the \"result\" AclImpl // instance, modify the \"result\" AclImpl instance setAces ( result , acesNew ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a particular implementation of { @link Sid } depending on the arguments . [CODESPLIT] protected Sid createSid ( boolean isPrincipal , String sid ) { if ( isPrincipal ) { return new PrincipalSid ( sid ) ; } else { return new GrantedAuthoritySid ( sid ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the list of user roles based on the current user s JEE roles . The { @link javax . servlet . http . HttpServletRequest#isUserInRole ( String ) } method is called for each of the values in the { @code j2eeMappableRoles } set to determine if that role should be assigned to the user . [CODESPLIT] protected Collection < String > getUserRoles ( HttpServletRequest request ) { ArrayList < String > j2eeUserRolesList = new ArrayList <> ( ) ; for ( String role : j2eeMappableRoles ) { if ( request . isUserInRole ( role ) ) { j2eeUserRolesList . add ( role ) ; } } return j2eeUserRolesList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the authentication details object . [CODESPLIT] public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails buildDetails ( HttpServletRequest context ) { Collection < String > j2eeUserRoles = getUserRoles ( context ) ; Collection < ? extends GrantedAuthority > userGas = j2eeUserRoles2GrantedAuthoritiesMapper . getGrantedAuthorities ( j2eeUserRoles ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"J2EE roles [\" + j2eeUserRoles + \"] mapped to Granted Authorities: [\" + userGas + \"]\" ) ; } PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails result = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails ( context , userGas ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the factory that provides an { @link OAuth2TokenValidator } which is used by the { @link JwtDecoder } . The default is { @link OidcIdTokenValidator } . [CODESPLIT] public final void setJwtValidatorFactory ( Function < ClientRegistration , OAuth2TokenValidator < Jwt > > jwtValidatorFactory ) { Assert . notNull ( jwtValidatorFactory , \"jwtValidatorFactory cannot be null\" ) ; this . jwtValidatorFactory = jwtValidatorFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the resolver that provides the expected { @link JwsAlgorithm JWS algorithm } used for the signature or MAC on the { @link OidcIdToken ID Token } . The default resolves to { @link SignatureAlgorithm#RS256 RS256 } for all { @link ClientRegistration clients } . [CODESPLIT] public final void setJwsAlgorithmResolver ( Function < ClientRegistration , JwsAlgorithm > jwsAlgorithmResolver ) { Assert . notNull ( jwsAlgorithmResolver , \"jwsAlgorithmResolver cannot be null\" ) ; this . jwsAlgorithmResolver = jwsAlgorithmResolver ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will be called if no url attribute is supplied . [CODESPLIT] private RootBeanDefinition createEmbeddedServer ( Element element , ParserContext parserContext ) { Object source = parserContext . extractSource ( element ) ; String suffix = element . getAttribute ( ATT_ROOT_SUFFIX ) ; if ( ! StringUtils . hasText ( suffix ) ) { suffix = OPT_DEFAULT_ROOT_SUFFIX ; } String port = element . getAttribute ( ATT_PORT ) ; if ( ! StringUtils . hasText ( port ) ) { port = getDefaultPort ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Using default port of \" + port ) ; } } String url = \"ldap://127.0.0.1:\" + port + \"/\" + suffix ; BeanDefinitionBuilder contextSource = BeanDefinitionBuilder . rootBeanDefinition ( CONTEXT_SOURCE_CLASS ) ; contextSource . addConstructorArgValue ( url ) ; contextSource . addPropertyValue ( \"userDn\" , \"uid=admin,ou=system\" ) ; contextSource . addPropertyValue ( \"password\" , \"secret\" ) ; RootBeanDefinition apacheContainer = new RootBeanDefinition ( \"org.springframework.security.ldap.server.ApacheDSContainer\" , null , null ) ; apacheContainer . setSource ( source ) ; apacheContainer . getConstructorArgumentValues ( ) . addGenericArgumentValue ( suffix ) ; String ldifs = element . getAttribute ( ATT_LDIF_FILE ) ; if ( ! StringUtils . hasText ( ldifs ) ) { ldifs = OPT_DEFAULT_LDIF_FILE ; } apacheContainer . getConstructorArgumentValues ( ) . addGenericArgumentValue ( ldifs ) ; apacheContainer . getPropertyValues ( ) . addPropertyValue ( \"port\" , port ) ; logger . info ( \"Embedded LDAP server bean definition created for URL: \" + url ) ; if ( parserContext . getRegistry ( ) . containsBeanDefinition ( BeanIds . EMBEDDED_APACHE_DS ) ) { parserContext . getReaderContext ( ) . error ( \"Only one embedded server bean is allowed per application context\" , element ) ; } parserContext . getRegistry ( ) . registerBeanDefinition ( BeanIds . EMBEDDED_APACHE_DS , apacheContainer ) ; return ( RootBeanDefinition ) contextSource . getBeanDefinition ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Mono < Void > writeHttpHeaders ( ServerWebExchange exchange ) { return isSecure ( exchange ) ? delegate . writeHttpHeaders ( exchange ) : Mono . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the servlet - api integration filter if required [CODESPLIT] private void createServletApiFilter ( BeanReference authenticationManager ) { final String ATT_SERVLET_API_PROVISION = \"servlet-api-provision\" ; final String DEF_SERVLET_API_PROVISION = \"true\" ; String provideServletApi = httpElt . getAttribute ( ATT_SERVLET_API_PROVISION ) ; if ( ! StringUtils . hasText ( provideServletApi ) ) { provideServletApi = DEF_SERVLET_API_PROVISION ; } if ( \"true\" . equals ( provideServletApi ) ) { servApiFilter = GrantedAuthorityDefaultsParserUtils . registerWithDefaultRolePrefix ( pc , SecurityContextHolderAwareRequestFilterBeanFactory . class ) ; servApiFilter . getPropertyValues ( ) . add ( \"authenticationManager\" , authenticationManager ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the jaas - api integration filter if required [CODESPLIT] private void createJaasApiFilter ( ) { final String ATT_JAAS_API_PROVISION = \"jaas-api-provision\" ; final String DEF_JAAS_API_PROVISION = \"false\" ; String provideJaasApi = httpElt . getAttribute ( ATT_JAAS_API_PROVISION ) ; if ( ! StringUtils . hasText ( provideJaasApi ) ) { provideJaasApi = DEF_JAAS_API_PROVISION ; } if ( \"true\" . equals ( provideJaasApi ) ) { jaasApiFilter = new RootBeanDefinition ( JaasApiIntegrationFilter . class ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the intercept - url elements to obtain the map used by channel security . This will be empty unless the <tt > requires - channel< / tt > attribute has been used on a URL path . [CODESPLIT] private ManagedMap < BeanMetadataElement , BeanDefinition > parseInterceptUrlsForChannelSecurity ( ) { ManagedMap < BeanMetadataElement , BeanDefinition > channelRequestMap = new ManagedMap <> ( ) ; for ( Element urlElt : interceptUrls ) { String path = urlElt . getAttribute ( ATT_PATH_PATTERN ) ; String method = urlElt . getAttribute ( ATT_HTTP_METHOD ) ; String matcherRef = urlElt . getAttribute ( ATT_REQUEST_MATCHER_REF ) ; boolean hasMatcherRef = StringUtils . hasText ( matcherRef ) ; if ( ! hasMatcherRef && ! StringUtils . hasText ( path ) ) { pc . getReaderContext ( ) . error ( \"pattern attribute cannot be empty or null\" , urlElt ) ; } String requiredChannel = urlElt . getAttribute ( ATT_REQUIRES_CHANNEL ) ; if ( StringUtils . hasText ( requiredChannel ) ) { BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference ( matcherRef ) : matcherType . createMatcher ( pc , path , method ) ; RootBeanDefinition channelAttributes = new RootBeanDefinition ( ChannelAttributeFactory . class ) ; channelAttributes . getConstructorArgumentValues ( ) . addGenericArgumentValue ( requiredChannel ) ; channelAttributes . setFactoryMethodName ( \"createChannelAttributes\" ) ; channelRequestMap . put ( matcher , channelAttributes ) ; } } return channelRequestMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void writeHeaders ( HttpServletRequest request , HttpServletResponse response ) { if ( this . requestMatcher . matches ( request ) ) { if ( ! response . containsHeader ( HSTS_HEADER_NAME ) ) { response . setHeader ( HSTS_HEADER_NAME , this . hstsHeaderValue ) ; } } else if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( \"Not injecting HSTS header since it did not match the requestMatcher \" + this . requestMatcher ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String [ ] selectImports ( AnnotationMetadata importingClassMetadata ) { boolean webmvcPresent = ClassUtils . isPresent ( \"org.springframework.web.servlet.DispatcherServlet\" , getClass ( ) . getClassLoader ( ) ) ; return webmvcPresent ? new String [ ] { \"org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration\" } : new String [ ] { } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked on the server - side . <p > The transmitted principal and credentials will be used to create an unauthenticated { @code Authentication } instance for processing by the { @code AuthenticationManager } . [CODESPLIT] public Object invoke ( Object targetObject ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { if ( principal != null ) { Authentication request = createAuthenticationRequest ( principal , credentials ) ; request . setAuthenticated ( false ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( request ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Set SecurityContextHolder to contain: \" + request ) ; } } try { return super . invoke ( targetObject ) ; } finally { SecurityContextHolder . clearContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Cleared SecurityContextHolder.\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the web . xml file using the configured <tt > ResourceLoader< / tt > and parses the role - name elements from it using these as the set of <tt > mappableAttributes< / tt > . [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Resource webXml = resourceLoader . getResource ( \"/WEB-INF/web.xml\" ) ; Document doc = getDocument ( webXml . getInputStream ( ) ) ; NodeList webApp = doc . getElementsByTagName ( \"web-app\" ) ; if ( webApp . getLength ( ) != 1 ) { throw new IllegalArgumentException ( \"Failed to find 'web-app' element in resource\" + webXml ) ; } NodeList securityRoles = ( ( Element ) webApp . item ( 0 ) ) . getElementsByTagName ( \"security-role\" ) ; ArrayList < String > roleNames = new ArrayList <> ( ) ; for ( int i = 0 ; i < securityRoles . getLength ( ) ; i ++ ) { Element secRoleElt = ( Element ) securityRoles . item ( i ) ; NodeList roles = secRoleElt . getElementsByTagName ( \"role-name\" ) ; if ( roles . getLength ( ) > 0 ) { String roleName = ( ( Element ) roles . item ( 0 ) ) . getTextContent ( ) . trim ( ) ; roleNames . add ( roleName ) ; logger . info ( \"Retrieved role-name '\" + roleName + \"' from web.xml\" ) ; } else { logger . info ( \"No security-role elements found in \" + webXml ) ; } } mappableAttributes = Collections . unmodifiableSet ( new HashSet <> ( roleNames ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public List < Sid > getSids ( Authentication authentication ) { Collection < ? extends GrantedAuthority > authorities = roleHierarchy . getReachableGrantedAuthorities ( authentication . getAuthorities ( ) ) ; List < Sid > sids = new ArrayList <> ( authorities . size ( ) + 1 ) ; sids . add ( new PrincipalSid ( authentication ) ) ; for ( GrantedAuthority authority : authorities ) { sids . add ( new GrantedAuthoritySid ( authority ) ) ; } return sids ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a TypeResolverBuilder that performs whitelisting . [CODESPLIT] private static TypeResolverBuilder < ? extends TypeResolverBuilder > createWhitelistedDefaultTyping ( ) { TypeResolverBuilder < ? extends TypeResolverBuilder > result = new WhitelistTypeResolverBuilder ( ObjectMapper . DefaultTyping . NON_FINAL ) ; result = result . init ( JsonTypeInfo . Id . CLASS , null ) ; result = result . inclusion ( JsonTypeInfo . As . PROPERTY ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public final void onStartup ( ServletContext servletContext ) throws ServletException { beforeSpringSecurityFilterChain ( servletContext ) ; if ( this . configurationClasses != null ) { AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext ( ) ; rootAppContext . register ( this . configurationClasses ) ; servletContext . addListener ( new ContextLoaderListener ( rootAppContext ) ) ; } if ( enableHttpSessionEventPublisher ( ) ) { servletContext . addListener ( \"org.springframework.security.web.session.HttpSessionEventPublisher\" ) ; } servletContext . setSessionTrackingModes ( getSessionTrackingModes ( ) ) ; insertSpringSecurityFilterChain ( servletContext ) ; afterSpringSecurityFilterChain ( servletContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the springSecurityFilterChain [CODESPLIT] private void insertSpringSecurityFilterChain ( ServletContext servletContext ) { String filterName = DEFAULT_FILTER_NAME ; DelegatingFilterProxy springSecurityFilterChain = new DelegatingFilterProxy ( filterName ) ; String contextAttribute = getWebApplicationContextAttribute ( ) ; if ( contextAttribute != null ) { springSecurityFilterChain . setContextAttribute ( contextAttribute ) ; } registerFilter ( servletContext , true , filterName , springSecurityFilterChain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the provided { @link Filter } s using default generated names { @link #getSecurityDispatcherTypes () } and { @link #isAsyncSecuritySupported () } . [CODESPLIT] private void registerFilters ( ServletContext servletContext , boolean insertBeforeOtherFilters , Filter ... filters ) { Assert . notEmpty ( filters , \"filters cannot be null or empty\" ) ; for ( Filter filter : filters ) { if ( filter == null ) { throw new IllegalArgumentException ( \"filters cannot contain null values. Got \" + Arrays . asList ( filters ) ) ; } String filterName = Conventions . getVariableName ( filter ) ; registerFilter ( servletContext , insertBeforeOtherFilters , filterName , filter ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the provided filter using the { @link #isAsyncSecuritySupported () } and { @link #getSecurityDispatcherTypes () } . [CODESPLIT] private final void registerFilter ( ServletContext servletContext , boolean insertBeforeOtherFilters , String filterName , Filter filter ) { Dynamic registration = servletContext . addFilter ( filterName , filter ) ; if ( registration == null ) { throw new IllegalStateException ( \"Duplicate Filter registration for '\" + filterName + \"'. Check to ensure the Filter is only configured once.\" ) ; } registration . setAsyncSupported ( isAsyncSecuritySupported ( ) ) ; EnumSet < DispatcherType > dispatcherTypes = getSecurityDispatcherTypes ( ) ; registration . addMappingForUrlPatterns ( dispatcherTypes , ! insertBeforeOtherFilters , \"/*\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link DelegatingFilterProxy#getContextAttribute () } or null if the parent { @link ApplicationContext } should be used . The default behavior is to use the parent { @link ApplicationContext } . [CODESPLIT] private String getWebApplicationContextAttribute ( ) { String dispatcherServletName = getDispatcherWebApplicationContextSuffix ( ) ; if ( dispatcherServletName == null ) { return null ; } return SERVLET_CONTEXT_PREFIX + dispatcherServletName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { [CODESPLIT] protected EnumSet < DispatcherType > getSecurityDispatcherTypes ( ) { return EnumSet . of ( DispatcherType . REQUEST , DispatcherType . ERROR , DispatcherType . ASYNC ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the token data for the supplied series identifier . [CODESPLIT] public PersistentRememberMeToken getTokenForSeries ( String seriesId ) { try { return getJdbcTemplate ( ) . queryForObject ( tokensBySeriesSql , new RowMapper < PersistentRememberMeToken > ( ) { public PersistentRememberMeToken mapRow ( ResultSet rs , int rowNum ) throws SQLException { return new PersistentRememberMeToken ( rs . getString ( 1 ) , rs . getString ( 2 ) , rs . getString ( 3 ) , rs . getTimestamp ( 4 ) ) ; } } , seriesId ) ; } catch ( EmptyResultDataAccessException zeroResults ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Querying token for series '\" + seriesId + \"' returned no results.\" , zeroResults ) ; } } catch ( IncorrectResultSizeDataAccessException moreThanOne ) { logger . error ( \"Querying token for series '\" + seriesId + \"' returned more than one value. Series\" + \" should be unique\" ) ; } catch ( DataAccessException e ) { logger . error ( \"Failed to load token for series \" + seriesId , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the public static fields of type { @link Permission } for a give class . <p > These permissions will be registered under the name of the field . See { @link BasePermission } for an example . [CODESPLIT] protected void registerPublicPermissions ( Class < ? extends Permission > clazz ) { Assert . notNull ( clazz , \"Class required\" ) ; Field [ ] fields = clazz . getFields ( ) ; for ( Field field : fields ) { try { Object fieldValue = field . get ( null ) ; if ( Permission . class . isAssignableFrom ( fieldValue . getClass ( ) ) ) { // Found a Permission static field Permission perm = ( Permission ) fieldValue ; String permissionName = field . getName ( ) ; registerPermission ( perm , permissionName ) ; } } catch ( Exception ignore ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract any <a href = https : // tools . ietf . org / html / rfc6750#section - 1 . 2 target = _blank > Bearer Token< / a > from the request and attempt an authentication . [CODESPLIT] @ Override protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain filterChain ) throws ServletException , IOException { final boolean debug = this . logger . isDebugEnabled ( ) ; String token ; try { token = this . bearerTokenResolver . resolve ( request ) ; } catch ( OAuth2AuthenticationException invalid ) { this . authenticationEntryPoint . commence ( request , response , invalid ) ; return ; } if ( token == null ) { filterChain . doFilter ( request , response ) ; return ; } BearerTokenAuthenticationToken authenticationRequest = new BearerTokenAuthenticationToken ( token ) ; authenticationRequest . setDetails ( this . authenticationDetailsSource . buildDetails ( request ) ) ; try { AuthenticationManager authenticationManager = this . authenticationManagerResolver . resolve ( request ) ; Authentication authenticationResult = authenticationManager . authenticate ( authenticationRequest ) ; SecurityContext context = SecurityContextHolder . createEmptyContext ( ) ; context . setAuthentication ( authenticationResult ) ; SecurityContextHolder . setContext ( context ) ; filterChain . doFilter ( request , response ) ; } catch ( AuthenticationException failed ) { SecurityContextHolder . clearContext ( ) ; if ( debug ) { this . logger . debug ( \"Authentication request for failed: \" + failed ) ; } this . authenticationEntryPoint . commence ( request , response , failed ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the given list of string attributes one - to - one to Spring Security GrantedAuthorities . [CODESPLIT] public List < GrantedAuthority > getGrantedAuthorities ( Collection < String > attributes ) { List < GrantedAuthority > result = new ArrayList <> ( attributes . size ( ) ) ; for ( String attribute : attributes ) { result . add ( getGrantedAuthority ( attribute ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the given role one - on - one to a Spring Security GrantedAuthority optionally doing case conversion and / or adding a prefix . [CODESPLIT] private GrantedAuthority getGrantedAuthority ( String attribute ) { if ( isConvertAttributeToLowerCase ( ) ) { attribute = attribute . toLowerCase ( Locale . getDefault ( ) ) ; } else if ( isConvertAttributeToUpperCase ( ) ) { attribute = attribute . toUpperCase ( Locale . getDefault ( ) ) ; } if ( isAddPrefixIfAlreadyExisting ( ) || ! attribute . startsWith ( getAttributePrefix ( ) ) ) { return new SimpleGrantedAuthority ( getAttributePrefix ( ) + attribute ) ; } else { return new SimpleGrantedAuthority ( attribute ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If available initializes the { @link DefaultLoginPageGeneratingFilter } shared object . [CODESPLIT] private void initDefaultLoginFilter ( H http ) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http . getSharedObject ( DefaultLoginPageGeneratingFilter . class ) ; if ( loginPageGeneratingFilter != null && ! isCustomLoginPage ( ) ) { loginPageGeneratingFilter . setFormLoginEnabled ( true ) ; loginPageGeneratingFilter . setUsernameParameter ( getUsernameParameter ( ) ) ; loginPageGeneratingFilter . setPasswordParameter ( getPasswordParameter ( ) ) ; loginPageGeneratingFilter . setLoginPageUrl ( getLoginPage ( ) ) ; loginPageGeneratingFilter . setFailureUrl ( getFailureUrl ( ) ) ; loginPageGeneratingFilter . setAuthenticationUrl ( getLoginProcessingUrl ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OAuth2TokenValidatorResult validate ( Jwt token ) { Assert . notNull ( token , \"token cannot be null\" ) ; String tokenIssuer = token . getClaimAsString ( JwtClaimNames . ISS ) ; if ( this . issuer . equals ( tokenIssuer ) ) { return OAuth2TokenValidatorResult . success ( ) ; } else { return OAuth2TokenValidatorResult . failure ( INVALID_ISSUER ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setting this attribute will inject the provided invalidSessionStrategy into the { [CODESPLIT] public SessionManagementConfigurer < H > invalidSessionStrategy ( InvalidSessionStrategy invalidSessionStrategy ) { Assert . notNull ( invalidSessionStrategy , \"invalidSessionStrategy\" ) ; this . invalidSessionStrategy = invalidSessionStrategy ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows specifying the { [CODESPLIT] public SessionManagementConfigurer < H > sessionCreationPolicy ( SessionCreationPolicy sessionCreationPolicy ) { Assert . notNull ( sessionCreationPolicy , \"sessionCreationPolicy cannot be null\" ) ; this . sessionPolicy = sessionCreationPolicy ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link InvalidSessionStrategy } to use . If null and { @link #invalidSessionUrl } is not null defaults to { @link SimpleRedirectInvalidSessionStrategy } . [CODESPLIT] InvalidSessionStrategy getInvalidSessionStrategy ( ) { if ( this . invalidSessionStrategy != null ) { return this . invalidSessionStrategy ; } if ( this . invalidSessionUrl != null ) { this . invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy ( this . invalidSessionUrl ) ; } if ( this . invalidSessionUrl == null ) { return null ; } if ( this . invalidSessionStrategy == null ) { this . invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy ( this . invalidSessionUrl ) ; } return this . invalidSessionStrategy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] SessionCreationPolicy getSessionCreationPolicy ( ) { if ( this . sessionPolicy != null ) { return this . sessionPolicy ; } SessionCreationPolicy sessionPolicy = getBuilder ( ) . getSharedObject ( SessionCreationPolicy . class ) ; return sessionPolicy == null ? SessionCreationPolicy . IF_REQUIRED : sessionPolicy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the { [CODESPLIT] private boolean isAllowSessionCreation ( ) { SessionCreationPolicy sessionPolicy = getSessionCreationPolicy ( ) ; return SessionCreationPolicy . ALWAYS == sessionPolicy || SessionCreationPolicy . IF_REQUIRED == sessionPolicy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the customized { @link SessionAuthenticationStrategy } if { @link #sessionAuthenticationStrategy ( SessionAuthenticationStrategy ) } was specified . Otherwise creates a default { @link SessionAuthenticationStrategy } . [CODESPLIT] private SessionAuthenticationStrategy getSessionAuthenticationStrategy ( H http ) { if ( this . sessionAuthenticationStrategy != null ) { return this . sessionAuthenticationStrategy ; } List < SessionAuthenticationStrategy > delegateStrategies = this . sessionAuthenticationStrategies ; SessionAuthenticationStrategy defaultSessionAuthenticationStrategy ; if ( this . providedSessionAuthenticationStrategy == null ) { // If the user did not provide a SessionAuthenticationStrategy // then default to sessionFixationAuthenticationStrategy defaultSessionAuthenticationStrategy = postProcess ( this . sessionFixationAuthenticationStrategy ) ; } else { defaultSessionAuthenticationStrategy = this . providedSessionAuthenticationStrategy ; } if ( isConcurrentSessionControlEnabled ( ) ) { SessionRegistry sessionRegistry = getSessionRegistry ( http ) ; ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlStrategy = new ConcurrentSessionControlAuthenticationStrategy ( sessionRegistry ) ; concurrentSessionControlStrategy . setMaximumSessions ( this . maximumSessions ) ; concurrentSessionControlStrategy . setExceptionIfMaximumExceeded ( this . maxSessionsPreventsLogin ) ; concurrentSessionControlStrategy = postProcess ( concurrentSessionControlStrategy ) ; RegisterSessionAuthenticationStrategy registerSessionStrategy = new RegisterSessionAuthenticationStrategy ( sessionRegistry ) ; registerSessionStrategy = postProcess ( registerSessionStrategy ) ; delegateStrategies . addAll ( Arrays . asList ( concurrentSessionControlStrategy , defaultSessionAuthenticationStrategy , registerSessionStrategy ) ) ; } else { delegateStrategies . add ( defaultSessionAuthenticationStrategy ) ; } this . sessionAuthenticationStrategy = postProcess ( new CompositeSessionAuthenticationStrategy ( delegateStrategies ) ) ; return this . sessionAuthenticationStrategy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . hasLength ( this . service , \"service cannot be empty.\" ) ; Assert . hasLength ( this . artifactParameter , \"artifactParameter cannot be empty.\" ) ; Assert . hasLength ( this . serviceParameter , \"serviceParameter cannot be empty.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the { [CODESPLIT] public void doFilter ( ServletRequest req , ServletResponse res , FilterChain chain ) throws IOException , ServletException { HttpServletRequest request = ( HttpServletRequest ) req ; HttpServletResponse response = ( HttpServletResponse ) res ; if ( ! requiresAuthentication ( request , response ) ) { chain . doFilter ( request , response ) ; return ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Request is to process authentication\" ) ; } Authentication authResult ; try { authResult = attemptAuthentication ( request , response ) ; if ( authResult == null ) { // return immediately as subclass has indicated that it hasn't completed // authentication return ; } sessionStrategy . onAuthentication ( authResult , request , response ) ; } catch ( InternalAuthenticationServiceException failed ) { logger . error ( \"An internal error occurred while trying to authenticate the user.\" , failed ) ; unsuccessfulAuthentication ( request , response , failed ) ; return ; } catch ( AuthenticationException failed ) { // Authentication failed unsuccessfulAuthentication ( request , response , failed ) ; return ; } // Authentication success if ( continueChainBeforeSuccessfulAuthentication ) { chain . doFilter ( request , response ) ; } successfulAuthentication ( request , response , chain , authResult ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default behaviour for successful authentication . <ol > <li > Sets the successful <tt > Authentication< / tt > object on the { @link SecurityContextHolder } < / li > <li > Informs the configured <tt > RememberMeServices< / tt > of the successful login< / li > <li > Fires an { @link InteractiveAuthenticationSuccessEvent } via the configured <tt > ApplicationEventPublisher< / tt > < / li > <li > Delegates additional behaviour to the { @link AuthenticationSuccessHandler } . < / li > < / ol > [CODESPLIT] protected void successfulAuthentication ( HttpServletRequest request , HttpServletResponse response , FilterChain chain , Authentication authResult ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Authentication success. Updating SecurityContextHolder to contain: \" + authResult ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authResult ) ; rememberMeServices . loginSuccess ( request , response , authResult ) ; // Fire event if ( this . eventPublisher != null ) { eventPublisher . publishEvent ( new InteractiveAuthenticationSuccessEvent ( authResult , this . getClass ( ) ) ) ; } successHandler . onAuthenticationSuccess ( request , response , authResult ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default behaviour for unsuccessful authentication . <ol > <li > Clears the { [CODESPLIT] protected void unsuccessfulAuthentication ( HttpServletRequest request , HttpServletResponse response , AuthenticationException failed ) throws IOException , ServletException { SecurityContextHolder . clearContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Authentication request failed: \" + failed . toString ( ) , failed ) ; logger . debug ( \"Updated SecurityContextHolder to contain null Authentication\" ) ; logger . debug ( \"Delegating to authentication failure handler \" + failureHandler ) ; } rememberMeServices . loginFail ( request , response ) ; failureHandler . onAuthenticationFailure ( request , response , failed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the AccessDeniedHandler on the { @link CsrfFilter } [CODESPLIT] void initAccessDeniedHandler ( BeanDefinition invalidSessionStrategy , BeanMetadataElement defaultDeniedHandler ) { BeanMetadataElement accessDeniedHandler = createAccessDeniedHandler ( invalidSessionStrategy , defaultDeniedHandler ) ; this . csrfFilter . getPropertyValues ( ) . addPropertyValue ( \"accessDeniedHandler\" , accessDeniedHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link AccessDeniedHandler } from the result of { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } and { @link #getInvalidSessionStrategy ( HttpSecurityBuilder ) } . If { @link #getInvalidSessionStrategy ( HttpSecurityBuilder ) } is non - null then a { @link DelegatingAccessDeniedHandler } is used in combination with { @link InvalidSessionAccessDeniedHandler } and the { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } . Otherwise only { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } is used . [CODESPLIT] private BeanMetadataElement createAccessDeniedHandler ( BeanDefinition invalidSessionStrategy , BeanMetadataElement defaultDeniedHandler ) { if ( invalidSessionStrategy == null ) { return defaultDeniedHandler ; } ManagedMap < Class < ? extends AccessDeniedException > , BeanDefinition > handlers = new ManagedMap < Class < ? extends AccessDeniedException > , BeanDefinition > ( ) ; BeanDefinitionBuilder invalidSessionHandlerBldr = BeanDefinitionBuilder . rootBeanDefinition ( InvalidSessionAccessDeniedHandler . class ) ; invalidSessionHandlerBldr . addConstructorArgValue ( invalidSessionStrategy ) ; handlers . put ( MissingCsrfTokenException . class , invalidSessionHandlerBldr . getBeanDefinition ( ) ) ; BeanDefinitionBuilder deniedBldr = BeanDefinitionBuilder . rootBeanDefinition ( DelegatingAccessDeniedHandler . class ) ; deniedBldr . addConstructorArgValue ( handlers ) ; deniedBldr . addConstructorArgValue ( defaultDeniedHandler ) ; return deniedBldr . getBeanDefinition ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a SecretKey . [CODESPLIT] public static SecretKey newSecretKey ( String algorithm , String password ) { return newSecretKey ( algorithm , new PBEKeySpec ( password . toCharArray ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a SecretKey . [CODESPLIT] public static SecretKey newSecretKey ( String algorithm , PBEKeySpec keySpec ) { try { SecretKeyFactory factory = SecretKeyFactory . getInstance ( algorithm ) ; return factory . generateSecret ( keySpec ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( \"Not a valid encryption algorithm\" , e ) ; } catch ( InvalidKeySpecException e ) { throw new IllegalArgumentException ( \"Not a valid secret key\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a new Cipher . [CODESPLIT] public static Cipher newCipher ( String algorithm ) { try { return Cipher . getInstance ( algorithm ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( \"Not a valid encryption algorithm\" , e ) ; } catch ( NoSuchPaddingException e ) { throw new IllegalStateException ( \"Should not happen\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the Cipher for use . [CODESPLIT] public static < T extends AlgorithmParameterSpec > T getParameterSpec ( Cipher cipher , Class < T > parameterSpecClass ) { try { return cipher . getParameters ( ) . getParameterSpec ( parameterSpecClass ) ; } catch ( InvalidParameterSpecException e ) { throw new IllegalArgumentException ( \"Unable to access parameter\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the Cipher for use . [CODESPLIT] public static void initCipher ( Cipher cipher , int mode , SecretKey secretKey ) { initCipher ( cipher , mode , secretKey , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the Cipher for use . [CODESPLIT] public static void initCipher ( Cipher cipher , int mode , SecretKey secretKey , byte [ ] salt , int iterationCount ) { initCipher ( cipher , mode , secretKey , new PBEParameterSpec ( salt , iterationCount ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the Cipher for use . [CODESPLIT] public static void initCipher ( Cipher cipher , int mode , SecretKey secretKey , AlgorithmParameterSpec parameterSpec ) { try { if ( parameterSpec != null ) { cipher . init ( mode , secretKey , parameterSpec ) ; } else { cipher . init ( mode , secretKey ) ; } } catch ( InvalidKeyException e ) { throw new IllegalArgumentException ( \"Unable to initialize due to invalid secret key\" , e ) ; } catch ( InvalidAlgorithmParameterException e ) { throw new IllegalStateException ( \"Unable to initialize due to invalid decryption parameter spec\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the Cipher to perform encryption or decryption ( depending on the initialized mode ) . [CODESPLIT] public static byte [ ] doFinal ( Cipher cipher , byte [ ] input ) { try { return cipher . doFinal ( input ) ; } catch ( IllegalBlockSizeException e ) { throw new IllegalStateException ( \"Unable to invoke Cipher due to illegal block size\" , e ) ; } catch ( BadPaddingException e ) { throw new IllegalStateException ( \"Unable to invoke Cipher due to bad padding\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether all required properties have been set . [CODESPLIT] @ Override public void afterPropertiesSet ( ) { try { super . afterPropertiesSet ( ) ; } catch ( ServletException e ) { // convert to RuntimeException for passivity on afterPropertiesSet signature throw new RuntimeException ( e ) ; } Assert . notNull ( authenticationManager , \"An AuthenticationManager must be set\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to authenticate a pre - authenticated user with Spring Security if the user has not yet been authenticated . [CODESPLIT] public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Checking secure context token: \" + SecurityContextHolder . getContext ( ) . getAuthentication ( ) ) ; } if ( requiresAuthentication ( ( HttpServletRequest ) request ) ) { doAuthenticate ( ( HttpServletRequest ) request , ( HttpServletResponse ) response ) ; } chain . doFilter ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the current principal has changed . The default implementation tries [CODESPLIT] protected boolean principalChanged ( HttpServletRequest request , Authentication currentAuthentication ) { Object principal = getPreAuthenticatedPrincipal ( request ) ; if ( ( principal instanceof String ) && currentAuthentication . getName ( ) . equals ( principal ) ) { return false ; } if ( principal != null && principal . equals ( currentAuthentication . getPrincipal ( ) ) ) { return false ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Pre-authenticated principal has changed to \" + principal + \" and will be reauthenticated\" ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do the actual authentication for a pre - authenticated user . [CODESPLIT] private void doAuthenticate ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { Authentication authResult ; Object principal = getPreAuthenticatedPrincipal ( request ) ; Object credentials = getPreAuthenticatedCredentials ( request ) ; if ( principal == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"No pre-authenticated principal found in request\" ) ; } return ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"preAuthenticatedPrincipal = \" + principal + \", trying to authenticate\" ) ; } try { PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken ( principal , credentials ) ; authRequest . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; authResult = authenticationManager . authenticate ( authRequest ) ; successfulAuthentication ( request , response , authResult ) ; } catch ( AuthenticationException failed ) { unsuccessfulAuthentication ( request , response , failed ) ; if ( ! continueFilterChainOnUnsuccessfulAuthentication ) { throw failed ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the <code > Authentication< / code > instance returned by the authentication manager into the secure context . [CODESPLIT] protected void successfulAuthentication ( HttpServletRequest request , HttpServletResponse response , Authentication authResult ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Authentication success: \" + authResult ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authResult ) ; // Fire event if ( this . eventPublisher != null ) { eventPublisher . publishEvent ( new InteractiveAuthenticationSuccessEvent ( authResult , this . getClass ( ) ) ) ; } if ( authenticationSuccessHandler != null ) { authenticationSuccessHandler . onAuthenticationSuccess ( request , response , authResult ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures the authentication object in the secure context is set to null when authentication fails . <p > Caches the failure exception as a request attribute [CODESPLIT] protected void unsuccessfulAuthentication ( HttpServletRequest request , HttpServletResponse response , AuthenticationException failed ) throws IOException , ServletException { SecurityContextHolder . clearContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Cleared security context due to exception\" , failed ) ; } request . setAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION , failed ) ; if ( authenticationFailureHandler != null ) { authenticationFailureHandler . onAuthenticationFailure ( request , response , failed ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes sure { [CODESPLIT] @ Override public final void sendError ( int sc , String msg ) throws IOException { doOnResponseCommitted ( ) ; super . sendError ( sc , msg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the contentLengthToWrite to the total contentWritten size and checks to see if the response should be written . [CODESPLIT] private void checkContentLength ( long contentLengthToWrite ) { this . contentWritten += contentLengthToWrite ; boolean isBodyFullyWritten = this . contentLength > 0 && this . contentWritten >= this . contentLength ; int bufferSize = getBufferSize ( ) ; boolean requiresFlush = bufferSize > 0 && this . contentWritten >= bufferSize ; if ( isBodyFullyWritten || requiresFlush ) { doOnResponseCommitted ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delay the lookup of the { @link ExpressionParser } to prevent SEC - 2136 [CODESPLIT] private ExpressionParser getParser ( ) { if ( this . parser != null ) { return this . parser ; } synchronized ( parserLock ) { this . parser = handler . getExpressionParser ( ) ; this . handler = null ; } return this . parser ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Determines which HTTP methods should be allowed . The default is to allow DELETE GET HEAD OPTIONS PATCH POST and PUT . < / p > [CODESPLIT] public void setAllowedHttpMethods ( Collection < String > allowedHttpMethods ) { if ( allowedHttpMethods == null ) { throw new IllegalArgumentException ( \"allowedHttpMethods cannot be null\" ) ; } if ( allowedHttpMethods == ALLOW_ANY_HTTP_METHOD ) { this . allowedHttpMethods = ALLOW_ANY_HTTP_METHOD ; } else { this . allowedHttpMethods = new HashSet <> ( allowedHttpMethods ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Determines if a percent % that is URL encoded %25 should be allowed in the path or not . The default is not to allow this behavior because it is a frequent source of security exploits . < / p > <p > For example this can lead to exploits that involve double URL encoding that lead to bypassing security constraints . < / p > [CODESPLIT] public void setAllowUrlEncodedPercent ( boolean allowUrlEncodedPercent ) { if ( allowUrlEncodedPercent ) { this . encodedUrlBlacklist . remove ( ENCODED_PERCENT ) ; this . decodedUrlBlacklist . remove ( PERCENT ) ; } else { this . encodedUrlBlacklist . add ( ENCODED_PERCENT ) ; this . decodedUrlBlacklist . add ( PERCENT ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a mapping of the supplied authorities based on the case - conversion and prefix settings . The mapping will be one - to - one unless duplicates are produced during the conversion . If a default authority has been set this will also be assigned to each mapping . [CODESPLIT] public Set < GrantedAuthority > mapAuthorities ( Collection < ? extends GrantedAuthority > authorities ) { HashSet < GrantedAuthority > mapped = new HashSet <> ( authorities . size ( ) ) ; for ( GrantedAuthority authority : authorities ) { mapped . add ( mapAuthority ( authority . getAuthority ( ) ) ) ; } if ( defaultAuthority != null ) { mapped . add ( defaultAuthority ) ; } return mapped ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies where users will go after authenticating successfully if they have not visited a secured page prior to authenticating or { @code alwaysUse } is true . This is a shortcut for calling { @link #successHandler ( AuthenticationSuccessHandler ) } . [CODESPLIT] public final T defaultSuccessUrl ( String defaultSuccessUrl , boolean alwaysUse ) { SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler ( ) ; handler . setDefaultTargetUrl ( defaultSuccessUrl ) ; handler . setAlwaysUseDefaultTargetUrl ( alwaysUse ) ; this . defaultSuccessHandler = handler ; return successHandler ( handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the URL to validate the credentials . [CODESPLIT] public T loginProcessingUrl ( String loginProcessingUrl ) { this . loginProcessingUrl = loginProcessingUrl ; authFilter . setRequiresAuthenticationRequestMatcher ( createLoginProcessingUrlMatcher ( loginProcessingUrl ) ) ; return getSelf ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The URL to send users if authentication fails . This is a shortcut for invoking { @link #failureHandler ( AuthenticationFailureHandler ) } . The default is / login?error . [CODESPLIT] public final T failureUrl ( String authenticationFailureUrl ) { T result = failureHandler ( new SimpleUrlAuthenticationFailureHandler ( authenticationFailureUrl ) ) ; this . failureUrl = authenticationFailureUrl ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Specifies the URL to send users to if login is required . If used with { @link WebSecurityConfigurerAdapter } a default login page will be generated when this attribute is not specified . < / p > [CODESPLIT] protected T loginPage ( String loginPage ) { setLoginPage ( loginPage ) ; updateAuthenticationDefaults ( ) ; this . customLoginPage = true ; return getSelf ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the default values for authentication . [CODESPLIT] protected final void updateAuthenticationDefaults ( ) { if ( loginProcessingUrl == null ) { loginProcessingUrl ( loginPage ) ; } if ( failureHandler == null ) { failureUrl ( loginPage + \"?error\" ) ; } final LogoutConfigurer < B > logoutConfigurer = getBuilder ( ) . getConfigurer ( LogoutConfigurer . class ) ; if ( logoutConfigurer != null && ! logoutConfigurer . isCustomLogoutSuccess ( ) ) { logoutConfigurer . logoutSuccessUrl ( loginPage + \"?logout\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the default values for access . [CODESPLIT] protected final void updateAccessDefaults ( B http ) { if ( permitAll ) { PermitAllSupport . permitAll ( http , loginPage , loginProcessingUrl , failureUrl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the repository of client registrations . [CODESPLIT] public OAuth2LoginConfigurer < B > clientRegistrationRepository ( ClientRegistrationRepository clientRegistrationRepository ) { Assert . notNull ( clientRegistrationRepository , \"clientRegistrationRepository cannot be null\" ) ; this . getBuilder ( ) . setSharedObject ( ClientRegistrationRepository . class , clientRegistrationRepository ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the repository for authorized client ( s ) . [CODESPLIT] public OAuth2LoginConfigurer < B > authorizedClientRepository ( OAuth2AuthorizedClientRepository authorizedClientRepository ) { Assert . notNull ( authorizedClientRepository , \"authorizedClientRepository cannot be null\" ) ; this . getBuilder ( ) . setSharedObject ( OAuth2AuthorizedClientRepository . class , authorizedClientRepository ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the service for authorized client ( s ) . [CODESPLIT] public OAuth2LoginConfigurer < B > authorizedClientService ( OAuth2AuthorizedClientService authorizedClientService ) { Assert . notNull ( authorizedClientService , \"authorizedClientService cannot be null\" ) ; this . authorizedClientRepository ( new AuthenticatedPrincipalOAuth2AuthorizedClientRepository ( authorizedClientService ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows registering multiple { @link RequestMatcher } instances to a collection of { @link ConfigAttribute } instances [CODESPLIT] private void interceptUrl ( Iterable < ? extends RequestMatcher > requestMatchers , Collection < ConfigAttribute > configAttributes ) { for ( RequestMatcher requestMatcher : requestMatchers ) { REGISTRY . addMapping ( new AbstractConfigAttributeRequestMatcherRegistry . UrlMapping ( requestMatcher , configAttributes ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OAuth2TokenValidatorResult validate ( Jwt jwt ) { Assert . notNull ( jwt , \"jwt cannot be null\" ) ; Instant expiry = jwt . getExpiresAt ( ) ; if ( expiry != null ) { if ( Instant . now ( this . clock ) . minus ( clockSkew ) . isAfter ( expiry ) ) { OAuth2Error error = new OAuth2Error ( OAuth2ErrorCodes . INVALID_REQUEST , String . format ( \"Jwt expired at %s\" , jwt . getExpiresAt ( ) ) , \"https://tools.ietf.org/html/rfc6750#section-3.1\" ) ; return OAuth2TokenValidatorResult . failure ( error ) ; } } Instant notBefore = jwt . getNotBefore ( ) ; if ( notBefore != null ) { if ( Instant . now ( this . clock ) . plus ( clockSkew ) . isBefore ( notBefore ) ) { OAuth2Error error = new OAuth2Error ( OAuth2ErrorCodes . INVALID_REQUEST , String . format ( \"Jwt used before %s\" , jwt . getNotBefore ( ) ) , \"https://tools.ietf.org/html/rfc6750#section-3.1\" ) ; return OAuth2TokenValidatorResult . failure ( error ) ; } } return OAuth2TokenValidatorResult . success ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register escalate and configure the AspectJ auto proxy creator based on the value of the [CODESPLIT] public void registerBeanDefinitions ( AnnotationMetadata importingClassMetadata , BeanDefinitionRegistry registry ) { BeanDefinition interceptor = registry . getBeanDefinition ( \"methodSecurityInterceptor\" ) ; BeanDefinitionBuilder aspect = BeanDefinitionBuilder . rootBeanDefinition ( \"org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect\" ) ; aspect . setFactoryMethod ( \"aspectOf\" ) ; aspect . setRole ( BeanDefinition . ROLE_INFRASTRUCTURE ) ; aspect . addPropertyValue ( \"securityInterceptor\" , interceptor ) ; registry . registerBeanDefinition ( \"annotationSecurityAspect$0\" , aspect . getBeanDefinition ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public UserDetails mapUserFromContext ( DirContextOperations ctx , String username , Collection < ? extends GrantedAuthority > authorities ) { String dn = ctx . getNameInNamespace ( ) ; this . logger . debug ( \"Mapping user details from context with DN: \" + dn ) ; LdapUserDetailsImpl . Essence essence = new LdapUserDetailsImpl . Essence ( ) ; essence . setDn ( dn ) ; Object passwordValue = ctx . getObjectAttribute ( this . passwordAttributeName ) ; if ( passwordValue != null ) { essence . setPassword ( mapPassword ( passwordValue ) ) ; } essence . setUsername ( username ) ; // Map the roles for ( int i = 0 ; ( this . roleAttributes != null ) && ( i < this . roleAttributes . length ) ; i ++ ) { String [ ] rolesForAttribute = ctx . getStringAttributes ( this . roleAttributes [ i ] ) ; if ( rolesForAttribute == null ) { this . logger . debug ( \"Couldn't read role attribute '\" + this . roleAttributes [ i ] + \"' for user \" + dn ) ; continue ; } for ( String role : rolesForAttribute ) { GrantedAuthority authority = createAuthority ( role ) ; if ( authority != null ) { essence . addAuthority ( authority ) ; } } } // Add the supplied authorities for ( GrantedAuthority authority : authorities ) { essence . addAuthority ( authority ) ; } // Check for PPolicy data PasswordPolicyResponseControl ppolicy = ( PasswordPolicyResponseControl ) ctx . getObjectAttribute ( PasswordPolicyControl . OID ) ; if ( ppolicy != null ) { essence . setTimeBeforeExpiration ( ppolicy . getTimeBeforeExpiration ( ) ) ; essence . setGraceLoginsRemaining ( ppolicy . getGraceLoginsRemaining ( ) ) ; } return essence . createUserDetails ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extension point to allow customized creation of the user s password from the attribute stored in the directory . [CODESPLIT] protected String mapPassword ( Object passwordValue ) { if ( ! ( passwordValue instanceof String ) ) { // Assume it's binary passwordValue = new String ( ( byte [ ] ) passwordValue ) ; } return ( String ) passwordValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a GrantedAuthority from a role attribute . Override to customize authority object creation . <p > The default implementation converts string attributes to roles making use of the <tt > rolePrefix< / tt > and <tt > convertToUpperCase< / tt > properties . Non - String attributes are ignored . < / p > [CODESPLIT] protected GrantedAuthority createAuthority ( Object role ) { if ( role instanceof String ) { if ( this . convertToUpperCase ) { role = ( ( String ) role ) . toUpperCase ( ) ; } return new SimpleGrantedAuthority ( this . rolePrefix + role ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this { @link Jwt } Validator [CODESPLIT] public void setJwtValidator ( OAuth2TokenValidator < Jwt > jwtValidator ) { Assert . notNull ( jwtValidator , \"jwtValidator cannot be null\" ) ; this . jwtValidator = jwtValidator ; this . delegate . setJwtValidator ( jwtValidator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link RestOperations } used when requesting the JSON Web Key ( JWK ) Set . [CODESPLIT] public final void setRestOperations ( RestOperations restOperations ) { Assert . notNull ( restOperations , \"restOperations cannot be null\" ) ; this . jwtDecoderBuilder = this . jwtDecoderBuilder . restOperations ( restOperations ) ; this . delegate = makeDelegate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolve the argument to inject into the controller parameter . @param parameter the method parameter . @param mavContainer the model and view container . @param webRequest the web request . @param binderFactory the web data binder factory . [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , ModelAndViewContainer mavContainer , NativeWebRequest webRequest , WebDataBinderFactory binderFactory ) throws Exception { SecurityContext securityContext = SecurityContextHolder . getContext ( ) ; if ( securityContext == null ) { return null ; } Object securityContextResult = securityContext ; CurrentSecurityContext securityContextAnnotation = findMethodAnnotation ( CurrentSecurityContext . class , parameter ) ; String expressionToParse = securityContextAnnotation . expression ( ) ; if ( StringUtils . hasLength ( expressionToParse ) ) { StandardEvaluationContext context = new StandardEvaluationContext ( ) ; context . setRootObject ( securityContext ) ; context . setVariable ( \"this\" , securityContext ) ; Expression expression = this . parser . parseExpression ( expressionToParse ) ; securityContextResult = expression . getValue ( context ) ; } if ( securityContextResult != null && ! parameter . getParameterType ( ) . isAssignableFrom ( securityContextResult . getClass ( ) ) ) { if ( securityContextAnnotation . errorOnInvalidType ( ) ) { throw new ClassCastException ( securityContextResult + \" is not assignable to \" + parameter . getParameterType ( ) ) ; } else { return null ; } } return securityContextResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the specified { @link Annotation } on the specified { @link MethodParameter } . [CODESPLIT] private < T extends Annotation > T findMethodAnnotation ( Class < T > annotationClass , MethodParameter parameter ) { T annotation = parameter . getParameterAnnotation ( annotationClass ) ; if ( annotation != null ) { return annotation ; } Annotation [ ] annotationsToSearch = parameter . getParameterAnnotations ( ) ; for ( Annotation toSearch : annotationsToSearch ) { annotation = AnnotationUtils . findAnnotation ( toSearch . annotationType ( ) , annotationClass ) ; if ( annotation != null ) { return annotation ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , ModelAndViewContainer mavContainer , NativeWebRequest webRequest , WebDataBinderFactory binderFactory ) throws Exception { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication == null ) { return null ; } Object principal = authentication . getPrincipal ( ) ; AuthenticationPrincipal authPrincipal = findMethodAnnotation ( AuthenticationPrincipal . class , parameter ) ; String expressionToParse = authPrincipal . expression ( ) ; if ( StringUtils . hasLength ( expressionToParse ) ) { StandardEvaluationContext context = new StandardEvaluationContext ( ) ; context . setRootObject ( principal ) ; context . setVariable ( \"this\" , principal ) ; context . setBeanResolver ( beanResolver ) ; Expression expression = this . parser . parseExpression ( expressionToParse ) ; principal = expression . getValue ( context ) ; } if ( principal != null && ! parameter . getParameterType ( ) . isAssignableFrom ( principal . getClass ( ) ) ) { if ( authPrincipal . errorOnInvalidType ( ) ) { throw new ClassCastException ( principal + \" is not assignable to \" + parameter . getParameterType ( ) ) ; } else { return null ; } } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create a { [CODESPLIT] public static OAuth2TokenValidator < Jwt > createDefaultWithIssuer ( String issuer ) { List < OAuth2TokenValidator < Jwt >> validators = new ArrayList <> ( ) ; validators . add ( new JwtTimestampValidator ( ) ) ; validators . add ( new JwtIssuerValidator ( issuer ) ) ; return new DelegatingOAuth2TokenValidator <> ( validators ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void postProcessBeanFactory ( ConfigurableListableBeanFactory beanFactory ) throws BeansException { if ( hasUserDefinedConversionService ( beanFactory ) ) { return ; } Converter < String , RSAPrivateKey > pkcs8 = pkcs8 ( ) ; Converter < String , RSAPublicKey > x509 = x509 ( ) ; ConversionService service = beanFactory . getConversionService ( ) ; if ( service instanceof ConverterRegistry ) { ConverterRegistry registry = ( ConverterRegistry ) service ; registry . addConverter ( String . class , RSAPrivateKey . class , pkcs8 ) ; registry . addConverter ( String . class , RSAPublicKey . class , x509 ) ; } else { beanFactory . addPropertyEditorRegistrar ( registry -> { registry . registerCustomEditor ( RSAPublicKey . class , new ConverterPropertyEditorAdapter <> ( x509 ) ) ; registry . registerCustomEditor ( RSAPrivateKey . class , new ConverterPropertyEditorAdapter <> ( pkcs8 ) ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Template implementation which locates the Spring Security cookie decodes it into a delimited array of tokens and submits it to subclasses for processing via the <tt > processAutoLoginCookie< / tt > method . <p > The returned username is then used to load the UserDetails object for the user which in turn is used to create a valid authentication token . [CODESPLIT] @ Override public final Authentication autoLogin ( HttpServletRequest request , HttpServletResponse response ) { String rememberMeCookie = extractRememberMeCookie ( request ) ; if ( rememberMeCookie == null ) { return null ; } logger . debug ( \"Remember-me cookie detected\" ) ; if ( rememberMeCookie . length ( ) == 0 ) { logger . debug ( \"Cookie was empty\" ) ; cancelCookie ( request , response ) ; return null ; } UserDetails user = null ; try { String [ ] cookieTokens = decodeCookie ( rememberMeCookie ) ; user = processAutoLoginCookie ( cookieTokens , request , response ) ; userDetailsChecker . check ( user ) ; logger . debug ( \"Remember-me cookie accepted\" ) ; return createSuccessfulAuthentication ( request , user ) ; } catch ( CookieTheftException cte ) { cancelCookie ( request , response ) ; throw cte ; } catch ( UsernameNotFoundException noUser ) { logger . debug ( \"Remember-me login was valid but corresponding user not found.\" , noUser ) ; } catch ( InvalidCookieException invalidCookie ) { logger . debug ( \"Invalid remember-me cookie: \" + invalidCookie . getMessage ( ) ) ; } catch ( AccountStatusException statusInvalid ) { logger . debug ( \"Invalid UserDetails: \" + statusInvalid . getMessage ( ) ) ; } catch ( RememberMeAuthenticationException e ) { logger . debug ( e . getMessage ( ) ) ; } cancelCookie ( request , response ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates the Spring Security remember me cookie in the request and returns its value . The cookie is searched for by name and also by matching the context path to the cookie path . [CODESPLIT] protected String extractRememberMeCookie ( HttpServletRequest request ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( ( cookies == null ) || ( cookies . length == 0 ) ) { return null ; } for ( Cookie cookie : cookies ) { if ( cookieName . equals ( cookie . getName ( ) ) ) { return cookie . getValue ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the final <tt > Authentication< / tt > object returned from the <tt > autoLogin< / tt > method . <p > By default it will create a <tt > RememberMeAuthenticationToken< / tt > instance . [CODESPLIT] protected Authentication createSuccessfulAuthentication ( HttpServletRequest request , UserDetails user ) { RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken ( key , user , authoritiesMapper . mapAuthorities ( user . getAuthorities ( ) ) ) ; auth . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; return auth ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the cookie and splits it into a set of token strings using the : delimiter . [CODESPLIT] protected String [ ] decodeCookie ( String cookieValue ) throws InvalidCookieException { for ( int j = 0 ; j < cookieValue . length ( ) % 4 ; j ++ ) { cookieValue = cookieValue + \"=\" ; } try { Base64 . getDecoder ( ) . decode ( cookieValue . getBytes ( ) ) ; } catch ( IllegalArgumentException e ) { throw new InvalidCookieException ( \"Cookie token was not Base64 encoded; value was '\" + cookieValue + \"'\" ) ; } String cookieAsPlainText = new String ( Base64 . getDecoder ( ) . decode ( cookieValue . getBytes ( ) ) ) ; String [ ] tokens = StringUtils . delimitedListToStringArray ( cookieAsPlainText , DELIMITER ) ; for ( int i = 0 ; i < tokens . length ; i ++ ) { try { tokens [ i ] = URLDecoder . decode ( tokens [ i ] , StandardCharsets . UTF_8 . toString ( ) ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( e . getMessage ( ) , e ) ; } } return tokens ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inverse operation of decodeCookie . [CODESPLIT] protected String encodeCookie ( String [ ] cookieTokens ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < cookieTokens . length ; i ++ ) { try { sb . append ( URLEncoder . encode ( cookieTokens [ i ] , StandardCharsets . UTF_8 . toString ( ) ) ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( e . getMessage ( ) , e ) ; } if ( i < cookieTokens . length - 1 ) { sb . append ( DELIMITER ) ; } } String value = sb . toString ( ) ; sb = new StringBuilder ( new String ( Base64 . getEncoder ( ) . encode ( value . getBytes ( ) ) ) ) ; while ( sb . charAt ( sb . length ( ) - 1 ) == ' ' ) { sb . deleteCharAt ( sb . length ( ) - 1 ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public final void loginSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication successfulAuthentication ) { if ( ! rememberMeRequested ( request , parameter ) ) { logger . debug ( \"Remember-me login not requested.\" ) ; return ; } onLoginSuccess ( request , response , successfulAuthentication ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows customization of whether a remember - me login has been requested . The default is to return true if <tt > alwaysRemember< / tt > is set or the configured parameter name has been included in the request and is set to the value true . [CODESPLIT] protected boolean rememberMeRequested ( HttpServletRequest request , String parameter ) { if ( alwaysRemember ) { return true ; } String paramValue = request . getParameter ( parameter ) ; if ( paramValue != null ) { if ( paramValue . equalsIgnoreCase ( \"true\" ) || paramValue . equalsIgnoreCase ( \"on\" ) || paramValue . equalsIgnoreCase ( \"yes\" ) || paramValue . equals ( \"1\" ) ) { return true ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Did not send remember-me cookie (principal did not set parameter '\" + parameter + \"')\" ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a cancel cookie ( with maxAge = 0 ) on the response to disable persistent logins . [CODESPLIT] protected void cancelCookie ( HttpServletRequest request , HttpServletResponse response ) { logger . debug ( \"Cancelling cookie\" ) ; Cookie cookie = new Cookie ( cookieName , null ) ; cookie . setMaxAge ( 0 ) ; cookie . setPath ( getCookiePath ( request ) ) ; if ( cookieDomain != null ) { cookie . setDomain ( cookieDomain ) ; } response . addCookie ( cookie ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the cookie on the response . [CODESPLIT] protected void setCookie ( String [ ] tokens , int maxAge , HttpServletRequest request , HttpServletResponse response ) { String cookieValue = encodeCookie ( tokens ) ; Cookie cookie = new Cookie ( cookieName , cookieValue ) ; cookie . setMaxAge ( maxAge ) ; cookie . setPath ( getCookiePath ( request ) ) ; if ( cookieDomain != null ) { cookie . setDomain ( cookieDomain ) ; } if ( maxAge < 1 ) { cookie . setVersion ( 1 ) ; } if ( useSecureCookie == null ) { cookie . setSecure ( request . isSecure ( ) ) ; } else { cookie . setSecure ( useSecureCookie ) ; } cookie . setHttpOnly ( true ) ; response . addCookie ( cookie ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of { [CODESPLIT] @ Override public void logout ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Logout of user \" + ( authentication == null ? \"Unknown\" : authentication . getName ( ) ) ) ; } cancelCookie ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a { @link Converter } for converting a PEM - encoded PKCS#8 RSA Private Key into a { @link RSAPrivateKey } . [CODESPLIT] public static Converter < InputStream , RSAPrivateKey > pkcs8 ( ) { KeyFactory keyFactory = rsaFactory ( ) ; return source -> { List < String > lines = readAllLines ( source ) ; Assert . isTrue ( ! lines . isEmpty ( ) && lines . get ( 0 ) . startsWith ( PKCS8_PEM_HEADER ) , \"Key is not in PEM-encoded PKCS#8 format, \" + \"please check that the header begins with -----\" + PKCS8_PEM_HEADER + \"-----\" ) ; String base64Encoded = lines . stream ( ) . filter ( RsaKeyConverters :: isNotPkcs8Wrapper ) . collect ( Collectors . joining ( ) ) ; byte [ ] pkcs8 = Base64 . getDecoder ( ) . decode ( base64Encoded ) ; try { return ( RSAPrivateKey ) keyFactory . generatePrivate ( new PKCS8EncodedKeySpec ( pkcs8 ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a { @link Converter } for converting a PEM - encoded X . 509 RSA Public Key into a { @link RSAPublicKey } . [CODESPLIT] public static Converter < InputStream , RSAPublicKey > x509 ( ) { KeyFactory keyFactory = rsaFactory ( ) ; return source -> { List < String > lines = readAllLines ( source ) ; Assert . isTrue ( ! lines . isEmpty ( ) && lines . get ( 0 ) . startsWith ( X509_PEM_HEADER ) , \"Key is not in PEM-encoded X.509 format, \" + \"please check that the header begins with -----\" + X509_PEM_HEADER + \"-----\" ) ; String base64Encoded = lines . stream ( ) . filter ( RsaKeyConverters :: isNotX509Wrapper ) . collect ( Collectors . joining ( ) ) ; byte [ ] x509 = Base64 . getDecoder ( ) . decode ( base64Encoded ) ; try { return ( RSAPublicKey ) keyFactory . generatePublic ( new X509EncodedKeySpec ( x509 ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Mono < Void > writeHttpHeaders ( ServerWebExchange exchange ) { HttpHeaders headers = exchange . getResponse ( ) . getHeaders ( ) ; boolean containsOneHeaderToAdd = Collections . disjoint ( headers . keySet ( ) , this . headersToAdd . keySet ( ) ) ; if ( containsOneHeaderToAdd ) { this . headersToAdd . forEach ( ( name , values ) -> { headers . put ( name , values ) ; } ) ; } return Mono . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the SQL <tt > usersByUsernameQuery< / tt > and returns a list of UserDetails objects . There should normally only be one matching user . [CODESPLIT] protected List < UserDetails > loadUsersByUsername ( String username ) { return getJdbcTemplate ( ) . query ( this . usersByUsernameQuery , new String [ ] { username } , new RowMapper < UserDetails > ( ) { @ Override public UserDetails mapRow ( ResultSet rs , int rowNum ) throws SQLException { String username = rs . getString ( 1 ) ; String password = rs . getString ( 2 ) ; boolean enabled = rs . getBoolean ( 3 ) ; return new User ( username , password , enabled , true , true , true , AuthorityUtils . NO_AUTHORITIES ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads authorities by executing the SQL from <tt > authoritiesByUsernameQuery< / tt > . [CODESPLIT] protected List < GrantedAuthority > loadUserAuthorities ( String username ) { return getJdbcTemplate ( ) . query ( this . authoritiesByUsernameQuery , new String [ ] { username } , new RowMapper < GrantedAuthority > ( ) { @ Override public GrantedAuthority mapRow ( ResultSet rs , int rowNum ) throws SQLException { String roleName = JdbcDaoImpl . this . rolePrefix + rs . getString ( 2 ) ; return new SimpleGrantedAuthority ( roleName ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads authorities by executing the SQL from <tt > groupAuthoritiesByUsernameQuery< / tt > . [CODESPLIT] protected List < GrantedAuthority > loadGroupAuthorities ( String username ) { return getJdbcTemplate ( ) . query ( this . groupAuthoritiesByUsernameQuery , new String [ ] { username } , new RowMapper < GrantedAuthority > ( ) { @ Override public GrantedAuthority mapRow ( ResultSet rs , int rowNum ) throws SQLException { String roleName = getRolePrefix ( ) + rs . getString ( 3 ) ; return new SimpleGrantedAuthority ( roleName ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Can be overridden to customize the creation of the final UserDetailsObject which is returned by the <tt > loadUserByUsername< / tt > method . [CODESPLIT] protected UserDetails createUserDetails ( String username , UserDetails userFromUserQuery , List < GrantedAuthority > combinedAuthorities ) { String returnUsername = userFromUserQuery . getUsername ( ) ; if ( ! this . usernameBasedPrimaryKey ) { returnUsername = username ; } return new User ( returnUsername , userFromUserQuery . getPassword ( ) , userFromUserQuery . isEnabled ( ) , userFromUserQuery . isAccountNonExpired ( ) , userFromUserQuery . isCredentialsNonExpired ( ) , userFromUserQuery . isAccountNonLocked ( ) , combinedAuthorities ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) throws SessionAuthenticationException { boolean containsToken = this . csrfTokenRepository . loadToken ( request ) != null ; if ( containsToken ) { this . csrfTokenRepository . saveToken ( null , request , response ) ; CsrfToken newToken = this . csrfTokenRepository . generateToken ( request ) ; this . csrfTokenRepository . saveToken ( newToken , request , response ) ; request . setAttribute ( CsrfToken . class . getName ( ) , newToken ) ; request . setAttribute ( newToken . getParameterName ( ) , newToken ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This concrete implementation simply polls all configured { @link AccessDecisionVoter } s and grants access if any <code > AccessDecisionVoter< / code > voted affirmatively . Denies access only if there was a deny vote AND no affirmative votes . <p > If every <code > AccessDecisionVoter< / code > abstained from voting the decision will be based on the { @link #isAllowIfAllAbstainDecisions () } property ( defaults to false ) . < / p > [CODESPLIT] public void decide ( Authentication authentication , Object object , Collection < ConfigAttribute > configAttributes ) throws AccessDeniedException { int deny = 0 ; for ( AccessDecisionVoter voter : getDecisionVoters ( ) ) { int result = voter . vote ( authentication , object , configAttributes ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Voter: \" + voter + \", returned: \" + result ) ; } switch ( result ) { case AccessDecisionVoter . ACCESS_GRANTED : return ; case AccessDecisionVoter . ACCESS_DENIED : deny ++ ; break ; default : break ; } } if ( deny > 0 ) { throw new AccessDeniedException ( messages . getMessage ( \"AbstractAccessDecisionManager.accessDenied\" , \"Access is denied\" ) ) ; } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void handle ( HttpServletRequest request , HttpServletResponse response , AccessDeniedException accessDeniedException ) throws IOException , ServletException { if ( ! response . isCommitted ( ) ) { if ( errorPage != null ) { // Put exception into request scope (perhaps of use to a view) request . setAttribute ( WebAttributes . ACCESS_DENIED_403 , accessDeniedException ) ; // Set the 403 status code. response . setStatus ( HttpStatus . FORBIDDEN . value ( ) ) ; // forward to error page. RequestDispatcher dispatcher = request . getRequestDispatcher ( errorPage ) ; dispatcher . forward ( request , response ) ; } else { response . sendError ( HttpStatus . FORBIDDEN . value ( ) , HttpStatus . FORBIDDEN . getReasonPhrase ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The error page to use . Must begin with a / and is interpreted relative to the current context root . [CODESPLIT] public void setErrorPage ( String errorPage ) { if ( ( errorPage != null ) && ! errorPage . startsWith ( \"/\" ) ) { throw new IllegalArgumentException ( \"errorPage must begin with '/'\" ) ; } this . errorPage = errorPage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolve the argument to inject into the controller parameter . [CODESPLIT] @ Override public Mono < Object > resolveArgument ( MethodParameter parameter , BindingContext bindingContext , ServerWebExchange exchange ) { ReactiveAdapter adapter = getAdapterRegistry ( ) . getAdapter ( parameter . getParameterType ( ) ) ; Mono < SecurityContext > reactiveSecurityContext = ReactiveSecurityContextHolder . getContext ( ) ; if ( reactiveSecurityContext == null ) { return null ; } return reactiveSecurityContext . flatMap ( a -> { Object p = resolveSecurityContext ( parameter , a ) ; Mono < Object > o = Mono . justOrEmpty ( p ) ; return adapter == null ? o : Mono . just ( adapter . fromPublisher ( o ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolve the expression from { [CODESPLIT] private Object resolveSecurityContext ( MethodParameter parameter , SecurityContext securityContext ) { CurrentSecurityContext securityContextAnnotation = findMethodAnnotation ( CurrentSecurityContext . class , parameter ) ; Object securityContextResult = securityContext ; String expressionToParse = securityContextAnnotation . expression ( ) ; if ( StringUtils . hasLength ( expressionToParse ) ) { StandardEvaluationContext context = new StandardEvaluationContext ( ) ; context . setRootObject ( securityContext ) ; context . setVariable ( \"this\" , securityContext ) ; context . setBeanResolver ( beanResolver ) ; Expression expression = this . parser . parseExpression ( expressionToParse ) ; securityContextResult = expression . getValue ( context ) ; } if ( isInvalidType ( parameter , securityContextResult ) ) { if ( securityContextAnnotation . errorOnInvalidType ( ) ) { throw new ClassCastException ( securityContextResult + \" is not assignable to \" + parameter . getParameterType ( ) ) ; } else { return null ; } } return securityContextResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If present removes the artifactParameterName and the corresponding value from the query String . [CODESPLIT] private String getQueryString ( final HttpServletRequest request , final Pattern artifactPattern ) { final String query = request . getQueryString ( ) ; if ( query == null ) { return null ; } final String result = artifactPattern . matcher ( query ) . replaceFirst ( \"\" ) ; if ( result . length ( ) == 0 ) { return null ; } // strip off the trailing & only if the artifact was the first query param return result . startsWith ( \"&\" ) ? result . substring ( 1 ) : result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Pattern } that can be passed into the constructor . This allows the { @link Pattern } to be reused for every instance of { @link DefaultServiceAuthenticationDetails } . [CODESPLIT] static Pattern createArtifactPattern ( String artifactParameterName ) { Assert . hasLength ( artifactParameterName , \"artifactParameterName is expected to have a length\" ) ; return Pattern . compile ( \"&?\" + Pattern . quote ( artifactParameterName ) + \"=[^&]*\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the port from the casServiceURL ensuring to return the proper value if the default port is being used . [CODESPLIT] private static int getServicePort ( URL casServiceUrl ) { int port = casServiceUrl . getPort ( ) ; if ( port == - 1 ) { port = casServiceUrl . getDefaultPort ( ) ; } return port ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the principals of the logged in user in this case the distinguished name . [CODESPLIT] public String getPrincipal ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication == null ) { log . warn ( \"No Authentication object set in SecurityContext - returning empty String as Principal\" ) ; return \"\" ; } Object principal = authentication . getPrincipal ( ) ; if ( principal instanceof LdapUserDetails ) { LdapUserDetails details = ( LdapUserDetails ) principal ; return details . getDn ( ) ; } else if ( authentication instanceof AnonymousAuthenticationToken ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Anonymous Authentication, returning empty String as Principal\" ) ; } return \"\" ; } else { throw new IllegalArgumentException ( \"The principal property of the authentication object\" + \"needs to be an LdapUserDetails.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , ModelAndViewContainer mavContainer , NativeWebRequest webRequest , WebDataBinderFactory binderFactory ) throws Exception { CsrfToken token = ( CsrfToken ) webRequest . getAttribute ( CsrfToken . class . getName ( ) , NativeWebRequest . SCOPE_REQUEST ) ; return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void onApplicationEvent ( AbstractAuthenticationEvent event ) { if ( ! logInteractiveAuthenticationSuccessEvents && event instanceof InteractiveAuthenticationSuccessEvent ) { return ; } if ( logger . isWarnEnabled ( ) ) { final StringBuilder builder = new StringBuilder ( ) ; builder . append ( \"Authentication event \" ) ; builder . append ( ClassUtils . getShortName ( event . getClass ( ) ) ) ; builder . append ( \": \" ) ; builder . append ( event . getAuthentication ( ) . getName ( ) ) ; builder . append ( \"; details: \" ) ; builder . append ( event . getAuthentication ( ) . getDetails ( ) ) ; if ( event instanceof AbstractAuthenticationFailureEvent ) { builder . append ( \"; exception: \" ) ; builder . append ( ( ( AbstractAuthenticationFailureEvent ) event ) . getException ( ) . getMessage ( ) ) ; } logger . warn ( builder . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the default MethodInterceptor which is a MethodSecurityInterceptor using the following methods to construct it . <ul > <li > { @link #accessDecisionManager () } < / li > <li > { @link #afterInvocationManager () } < / li > <li > { @link #authenticationManager () } < / li > <li > { @link #methodSecurityMetadataSource () } < / li > <li > { @link #runAsManager () } < / li > [CODESPLIT] @ Bean public MethodInterceptor methodSecurityInterceptor ( ) throws Exception { this . methodSecurityInterceptor = isAspectJ ( ) ? new AspectJMethodSecurityInterceptor ( ) : new MethodSecurityInterceptor ( ) ; methodSecurityInterceptor . setAccessDecisionManager ( accessDecisionManager ( ) ) ; methodSecurityInterceptor . setAfterInvocationManager ( afterInvocationManager ( ) ) ; methodSecurityInterceptor . setSecurityMetadataSource ( methodSecurityMetadataSource ( ) ) ; RunAsManager runAsManager = runAsManager ( ) ; if ( runAsManager != null ) { methodSecurityInterceptor . setRunAsManager ( runAsManager ) ; } return this . methodSecurityInterceptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void afterSingletonsInstantiated ( ) { try { initializeMethodSecurityInterceptor ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } PermissionEvaluator permissionEvaluator = getSingleBeanOrNull ( PermissionEvaluator . class ) ; if ( permissionEvaluator != null ) { this . defaultMethodExpressionHandler . setPermissionEvaluator ( permissionEvaluator ) ; } RoleHierarchy roleHierarchy = getSingleBeanOrNull ( RoleHierarchy . class ) ; if ( roleHierarchy != null ) { this . defaultMethodExpressionHandler . setRoleHierarchy ( roleHierarchy ) ; } AuthenticationTrustResolver trustResolver = getSingleBeanOrNull ( AuthenticationTrustResolver . class ) ; if ( trustResolver != null ) { this . defaultMethodExpressionHandler . setTrustResolver ( trustResolver ) ; } GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull ( GrantedAuthorityDefaults . class ) ; if ( grantedAuthorityDefaults != null ) { this . defaultMethodExpressionHandler . setDefaultRolePrefix ( grantedAuthorityDefaults . getRolePrefix ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provide a custom { @link AfterInvocationManager } for the default implementation of { @link #methodSecurityInterceptor () } . The default is null if pre post is not enabled . Otherwise it returns a { @link AfterInvocationProviderManager } . [CODESPLIT] protected AfterInvocationManager afterInvocationManager ( ) { if ( prePostEnabled ( ) ) { AfterInvocationProviderManager invocationProviderManager = new AfterInvocationProviderManager ( ) ; ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice ( getExpressionHandler ( ) ) ; PostInvocationAdviceProvider postInvocationAdviceProvider = new PostInvocationAdviceProvider ( postAdvice ) ; List < AfterInvocationProvider > afterInvocationProviders = new ArrayList <> ( ) ; afterInvocationProviders . add ( postInvocationAdviceProvider ) ; invocationProviderManager . setProviders ( afterInvocationProviders ) ; return invocationProviderManager ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows subclasses to provide a custom { @link AccessDecisionManager } . The default is a { @link AffirmativeBased } with the following voters : [CODESPLIT] protected AccessDecisionManager accessDecisionManager ( ) { List < AccessDecisionVoter < ? extends Object > > decisionVoters = new ArrayList < AccessDecisionVoter < ? extends Object > > ( ) ; ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice ( ) ; expressionAdvice . setExpressionHandler ( getExpressionHandler ( ) ) ; if ( prePostEnabled ( ) ) { decisionVoters . add ( new PreInvocationAuthorizationAdviceVoter ( expressionAdvice ) ) ; } if ( jsr250Enabled ( ) ) { decisionVoters . add ( new Jsr250Voter ( ) ) ; } RoleVoter roleVoter = new RoleVoter ( ) ; GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull ( GrantedAuthorityDefaults . class ) ; if ( grantedAuthorityDefaults != null ) { roleVoter . setRolePrefix ( grantedAuthorityDefaults . getRolePrefix ( ) ) ; } decisionVoters . add ( roleVoter ) ; decisionVoters . add ( new AuthenticatedVoter ( ) ) ; return new AffirmativeBased ( decisionVoters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows providing a custom { @link AuthenticationManager } . The default is to use any authentication mechanisms registered by { @link #configure ( AuthenticationManagerBuilder ) } . If { @link #configure ( AuthenticationManagerBuilder ) } was not overridden then an { @link AuthenticationManager } is attempted to be autowired by type . [CODESPLIT] protected AuthenticationManager authenticationManager ( ) throws Exception { if ( authenticationManager == null ) { DefaultAuthenticationEventPublisher eventPublisher = objectPostProcessor . postProcess ( new DefaultAuthenticationEventPublisher ( ) ) ; auth = new AuthenticationManagerBuilder ( objectPostProcessor ) ; auth . authenticationEventPublisher ( eventPublisher ) ; configure ( auth ) ; if ( disableAuthenticationRegistry ) { authenticationManager = getAuthenticationConfiguration ( ) . getAuthenticationManager ( ) ; } else { authenticationManager = auth . build ( ) ; } } return authenticationManager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides the default { @link MethodSecurityMetadataSource } that will be used . It creates a { @link DelegatingMethodSecurityMetadataSource } based upon { @link #customMethodSecurityMetadataSource () } and the attributes on { @link EnableGlobalMethodSecurity } . [CODESPLIT] @ Bean public MethodSecurityMetadataSource methodSecurityMetadataSource ( ) { List < MethodSecurityMetadataSource > sources = new ArrayList <> ( ) ; ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory ( getExpressionHandler ( ) ) ; MethodSecurityMetadataSource customMethodSecurityMetadataSource = customMethodSecurityMetadataSource ( ) ; if ( customMethodSecurityMetadataSource != null ) { sources . add ( customMethodSecurityMetadataSource ) ; } boolean hasCustom = customMethodSecurityMetadataSource != null ; boolean isPrePostEnabled = prePostEnabled ( ) ; boolean isSecuredEnabled = securedEnabled ( ) ; boolean isJsr250Enabled = jsr250Enabled ( ) ; if ( ! isPrePostEnabled && ! isSecuredEnabled && ! isJsr250Enabled && ! hasCustom ) { throw new IllegalStateException ( \"In the composition of all global method configuration, \" + \"no annotation support was actually activated\" ) ; } if ( isPrePostEnabled ) { sources . add ( new PrePostAnnotationSecurityMetadataSource ( attributeFactory ) ) ; } if ( isSecuredEnabled ) { sources . add ( new SecuredAnnotationSecurityMetadataSource ( ) ) ; } if ( isJsr250Enabled ) { GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull ( GrantedAuthorityDefaults . class ) ; Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource = this . context . getBean ( Jsr250MethodSecurityMetadataSource . class ) ; if ( grantedAuthorityDefaults != null ) { jsr250MethodSecurityMetadataSource . setDefaultRolePrefix ( grantedAuthorityDefaults . getRolePrefix ( ) ) ; } sources . add ( jsr250MethodSecurityMetadataSource ) ; } return new DelegatingMethodSecurityMetadataSource ( sources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link PreInvocationAuthorizationAdvice } to be used . The default is { @link ExpressionBasedPreInvocationAdvice } . [CODESPLIT] @ Bean public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice ( ) { ExpressionBasedPreInvocationAdvice preInvocationAdvice = new ExpressionBasedPreInvocationAdvice ( ) ; preInvocationAdvice . setExpressionHandler ( getExpressionHandler ( ) ) ; return preInvocationAdvice ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the attributes from { [CODESPLIT] public final void setImportMetadata ( AnnotationMetadata importMetadata ) { Map < String , Object > annotationAttributes = importMetadata . getAnnotationAttributes ( EnableGlobalMethodSecurity . class . getName ( ) ) ; enableMethodSecurity = AnnotationAttributes . fromMap ( annotationAttributes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public AppConfigurationEntry [ ] getAppConfigurationEntry ( String name ) { AppConfigurationEntry [ ] mappedResult = this . mappedConfigurations . get ( name ) ; return mappedResult == null ? this . defaultConfiguration : mappedResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String resolve ( HttpServletRequest request ) { String authorizationHeaderToken = resolveFromAuthorizationHeader ( request ) ; String parameterToken = resolveFromRequestParameters ( request ) ; if ( authorizationHeaderToken != null ) { if ( parameterToken != null ) { BearerTokenError error = new BearerTokenError ( BearerTokenErrorCodes . INVALID_REQUEST , HttpStatus . BAD_REQUEST , \"Found multiple bearer tokens in the request\" , \"https://tools.ietf.org/html/rfc6750#section-3.1\" ) ; throw new OAuth2AuthenticationException ( error ) ; } return authorizationHeaderToken ; } else if ( parameterToken != null && isParameterTokenSupportedForRequest ( request ) ) { return parameterToken ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a { @link MappedJwtClaimSetConverter } overriding individual claim converters with the provided { @link Map } of { @link Converter } s . [CODESPLIT] public static MappedJwtClaimSetConverter withDefaults ( Map < String , Converter < Object , ? > > claimConverters ) { Assert . notNull ( claimConverters , \"claimConverters cannot be null\" ) ; Map < String , Converter < Object , ? > > claimNameToConverter = new HashMap <> ( ) ; claimNameToConverter . put ( JwtClaimNames . AUD , AUDIENCE_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . EXP , TEMPORAL_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . IAT , TEMPORAL_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . ISS , ISSUER_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . JTI , STRING_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . NBF , TEMPORAL_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . SUB , STRING_CONVERTER ) ; claimNameToConverter . putAll ( claimConverters ) ; return new MappedJwtClaimSetConverter ( claimNameToConverter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Map < String , Object > convert ( Map < String , Object > claims ) { Assert . notNull ( claims , \"claims cannot be null\" ) ; Map < String , Object > mappedClaims = new HashMap <> ( claims ) ; for ( Map . Entry < String , Converter < Object , ? > > entry : this . claimConverters . entrySet ( ) ) { String claimName = entry . getKey ( ) ; Converter < Object , ? > converter = entry . getValue ( ) ; if ( converter != null ) { Object claim = claims . get ( claimName ) ; Object mappedClaim = converter . convert ( claim ) ; mappedClaims . compute ( claimName , ( key , value ) -> mappedClaim ) ; } } Instant issuedAt = ( Instant ) mappedClaims . get ( JwtClaimNames . IAT ) ; Instant expiresAt = ( Instant ) mappedClaims . get ( JwtClaimNames . EXP ) ; if ( issuedAt == null && expiresAt != null ) { mappedClaims . put ( JwtClaimNames . IAT , expiresAt . minusSeconds ( 1 ) ) ; } return mappedClaims ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the configured pattern ( and HTTP - Method ) match those of the supplied request . [CODESPLIT] @ Override public boolean matches ( HttpServletRequest request ) { if ( this . httpMethod != null && StringUtils . hasText ( request . getMethod ( ) ) && this . httpMethod != valueOf ( request . getMethod ( ) ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Request '\" + request . getMethod ( ) + \" \" + getRequestPath ( request ) + \"'\" + \" doesn't match '\" + this . httpMethod + \" \" + this . pattern + \"'\" ) ; } return false ; } if ( this . pattern . equals ( MATCH_ALL ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Request '\" + getRequestPath ( request ) + \"' matched by universal pattern '/**'\" ) ; } return true ; } String url = getRequestPath ( request ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Checking match of request : '\" + url + \"'; against '\" + this . pattern + \"'\" ) ; } return this . matcher . matches ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that is actually called by the filter chain . Simply delegates to the { @link #invoke ( FilterInvocation ) } method . [CODESPLIT] public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { FilterInvocation fi = new FilterInvocation ( request , response , chain ) ; invoke ( fi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the map of exception types ( by name ) to URLs . [CODESPLIT] public void setExceptionMappings ( Map < ? , ? > failureUrlMap ) { this . failureUrlMap . clear ( ) ; for ( Map . Entry < ? , ? > entry : failureUrlMap . entrySet ( ) ) { Object exception = entry . getKey ( ) ; Object url = entry . getValue ( ) ; Assert . isInstanceOf ( String . class , exception , \"Exception key must be a String (the exception classname).\" ) ; Assert . isInstanceOf ( String . class , url , \"URL must be a String\" ) ; Assert . isTrue ( UrlUtils . isValidRedirectUrl ( ( String ) url ) , ( ) -> \"Not a valid redirect URL: \" + url ) ; this . failureUrlMap . put ( ( String ) exception , ( String ) url ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { [CODESPLIT] public ServerHttpSecurity addFilterAfter ( WebFilter webFilter , SecurityWebFiltersOrder order ) { this . webFilters . add ( new OrderedWebFilter ( webFilter , order . getOrder ( ) + 1 ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the { [CODESPLIT] public SecurityWebFilterChain build ( ) { if ( this . built != null ) { throw new IllegalStateException ( \"This has already been built with the following stacktrace. \" + buildToString ( ) ) ; } this . built = new RuntimeException ( \"First Build Invocation\" ) . fillInStackTrace ( ) ; if ( this . headers != null ) { this . headers . configure ( this ) ; } WebFilter securityContextRepositoryWebFilter = securityContextRepositoryWebFilter ( ) ; if ( securityContextRepositoryWebFilter != null ) { this . webFilters . add ( securityContextRepositoryWebFilter ) ; } if ( this . httpsRedirectSpec != null ) { this . httpsRedirectSpec . configure ( this ) ; } if ( this . x509 != null ) { this . x509 . configure ( this ) ; } if ( this . csrf != null ) { this . csrf . configure ( this ) ; } if ( this . cors != null ) { this . cors . configure ( this ) ; } if ( this . httpBasic != null ) { this . httpBasic . authenticationManager ( this . authenticationManager ) ; this . httpBasic . configure ( this ) ; } if ( this . formLogin != null ) { this . formLogin . authenticationManager ( this . authenticationManager ) ; if ( this . securityContextRepository != null ) { this . formLogin . securityContextRepository ( this . securityContextRepository ) ; } this . formLogin . configure ( this ) ; } if ( this . oauth2Login != null ) { this . oauth2Login . configure ( this ) ; } if ( this . resourceServer != null ) { this . resourceServer . configure ( this ) ; } if ( this . client != null ) { this . client . configure ( this ) ; } if ( this . anonymous != null ) { this . anonymous . configure ( this ) ; } this . loginPage . configure ( this ) ; if ( this . logout != null ) { this . logout . configure ( this ) ; } this . requestCache . configure ( this ) ; this . addFilterAt ( new SecurityContextServerWebExchangeWebFilter ( ) , SecurityWebFiltersOrder . SECURITY_CONTEXT_SERVER_WEB_EXCHANGE ) ; if ( this . authorizeExchange != null ) { ServerAuthenticationEntryPoint authenticationEntryPoint = getAuthenticationEntryPoint ( ) ; ExceptionTranslationWebFilter exceptionTranslationWebFilter = new ExceptionTranslationWebFilter ( ) ; if ( authenticationEntryPoint != null ) { exceptionTranslationWebFilter . setAuthenticationEntryPoint ( authenticationEntryPoint ) ; } ServerAccessDeniedHandler accessDeniedHandler = getAccessDeniedHandler ( ) ; if ( accessDeniedHandler != null ) { exceptionTranslationWebFilter . setAccessDeniedHandler ( accessDeniedHandler ) ; } this . addFilterAt ( exceptionTranslationWebFilter , SecurityWebFiltersOrder . EXCEPTION_TRANSLATION ) ; this . authorizeExchange . configure ( this ) ; } AnnotationAwareOrderComparator . sort ( this . webFilters ) ; List < WebFilter > sortedWebFilters = new ArrayList <> ( ) ; this . webFilters . forEach ( f -> { if ( f instanceof OrderedWebFilter ) { f = ( ( OrderedWebFilter ) f ) . webFilter ; } sortedWebFilters . add ( f ) ; } ) ; sortedWebFilters . add ( 0 , new ServerWebExchangeReactorContextWebFilter ( ) ) ; return new MatcherSecurityWebFilterChain ( getSecurityMatcher ( ) , sortedWebFilters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requires the request to be passed in . [CODESPLIT] public void logout ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) { Assert . notNull ( request , \"HttpServletRequest required\" ) ; if ( invalidateHttpSession ) { HttpSession session = request . getSession ( false ) ; if ( session != null ) { logger . debug ( \"Invalidating session: \" + session . getId ( ) ) ; session . invalidate ( ) ; } } if ( clearAuthentication ) { SecurityContext context = SecurityContextHolder . getContext ( ) ; context . setAuthentication ( null ) ; } SecurityContextHolder . clearContext ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of { @link ServerLogoutSuccessHandler#onLogoutSuccess ( WebFilterExchange Authentication ) } . Sets the status on the { @link WebFilterExchange } . [CODESPLIT] @ Override public Mono < Void > onLogoutSuccess ( WebFilterExchange exchange , Authentication authentication ) { return Mono . fromRunnable ( ( ) -> exchange . getExchange ( ) . getResponse ( ) . setStatusCode ( this . httpStatusToReturn ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the required properties are set . In addition if { [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . hasLength ( this . loginContextName , \"loginContextName cannot be null or empty\" ) ; Assert . notEmpty ( this . authorityGranters , \"authorityGranters cannot be null or empty\" ) ; if ( ObjectUtils . isEmpty ( this . callbackHandlers ) ) { setCallbackHandlers ( new JaasAuthenticationCallbackHandler [ ] { new JaasNameCallbackHandler ( ) , new JaasPasswordCallbackHandler ( ) } ) ; } Assert . notNull ( this . loginExceptionResolver , \"loginExceptionResolver cannot be null\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to login the user given the Authentication objects principal and credential [CODESPLIT] public Authentication authenticate ( Authentication auth ) throws AuthenticationException { if ( ! ( auth instanceof UsernamePasswordAuthenticationToken ) ) { return null ; } UsernamePasswordAuthenticationToken request = ( UsernamePasswordAuthenticationToken ) auth ; Set < GrantedAuthority > authorities ; try { // Create the LoginContext object, and pass our InternallCallbackHandler LoginContext loginContext = createLoginContext ( new InternalCallbackHandler ( auth ) ) ; // Attempt to login the user, the LoginContext will call our // InternalCallbackHandler at this point. loginContext . login ( ) ; // Create a set to hold the authorities, and add any that have already been // applied. authorities = new HashSet <> ( ) ; // Get the subject principals and pass them to each of the AuthorityGranters Set < Principal > principals = loginContext . getSubject ( ) . getPrincipals ( ) ; for ( Principal principal : principals ) { for ( AuthorityGranter granter : this . authorityGranters ) { Set < String > roles = granter . grant ( principal ) ; // If the granter doesn't wish to grant any authorities, it should // return null. if ( ( roles != null ) && ! roles . isEmpty ( ) ) { for ( String role : roles ) { authorities . add ( new JaasGrantedAuthority ( role , principal ) ) ; } } } } // Convert the authorities set back to an array and apply it to the token. JaasAuthenticationToken result = new JaasAuthenticationToken ( request . getPrincipal ( ) , request . getCredentials ( ) , new ArrayList <> ( authorities ) , loginContext ) ; // Publish the success event publishSuccessEvent ( result ) ; // we're done, return the token. return result ; } catch ( LoginException loginException ) { AuthenticationException ase = this . loginExceptionResolver . resolveException ( loginException ) ; publishFailureEvent ( request , ase ) ; throw ase ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the logout by getting the security contexts for the destroyed session and invoking { @code LoginContext . logout () } for any which contain a { @code JaasAuthenticationToken } . [CODESPLIT] protected void handleLogout ( SessionDestroyedEvent event ) { List < SecurityContext > contexts = event . getSecurityContexts ( ) ; if ( contexts . isEmpty ( ) ) { this . log . debug ( \"The destroyed session has no SecurityContexts\" ) ; return ; } for ( SecurityContext context : contexts ) { Authentication auth = context . getAuthentication ( ) ; if ( ( auth != null ) && ( auth instanceof JaasAuthenticationToken ) ) { JaasAuthenticationToken token = ( JaasAuthenticationToken ) auth ; try { LoginContext loginContext = token . getLoginContext ( ) ; boolean debug = this . log . isDebugEnabled ( ) ; if ( loginContext != null ) { if ( debug ) { this . log . debug ( \"Logging principal: [\" + token . getPrincipal ( ) + \"] out of LoginContext\" ) ; } loginContext . logout ( ) ; } else if ( debug ) { this . log . debug ( \"Cannot logout principal: [\" + token . getPrincipal ( ) + \"] from LoginContext. \" + \"The LoginContext is unavailable\" ) ; } } catch ( LoginException e ) { this . log . warn ( \"Error error logging out of LoginContext\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Publishes the { @link JaasAuthenticationFailedEvent } . Can be overridden by subclasses for different functionality [CODESPLIT] protected void publishFailureEvent ( UsernamePasswordAuthenticationToken token , AuthenticationException ase ) { if ( this . applicationEventPublisher != null ) { this . applicationEventPublisher . publishEvent ( new JaasAuthenticationFailedEvent ( token , ase ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for creating a { @link DelegatingSecurityContextRunnable } . [CODESPLIT] public static Runnable create ( Runnable delegate , SecurityContext securityContext ) { Assert . notNull ( delegate , \"delegate cannot be  null\" ) ; return securityContext == null ? new DelegatingSecurityContextRunnable ( delegate ) : new DelegatingSecurityContextRunnable ( delegate , securityContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public Collection < ConfigAttribute > getAllConfigAttributes ( ) { Set < ConfigAttribute > allAttributes = new HashSet <> ( ) ; for ( Map . Entry < RequestMatcher , Collection < ConfigAttribute > > entry : requestMap . entrySet ( ) ) { allAttributes . addAll ( entry . getValue ( ) ) ; } return allAttributes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set all authorities for this user from String values . It will create the necessary { @link GrantedAuthority } objects . [CODESPLIT] public void setAuthoritiesAsString ( List < String > authoritiesAsStrings ) { setAuthorities ( new ArrayList <> ( authoritiesAsStrings . size ( ) ) ) ; for ( String authority : authoritiesAsStrings ) { addAuthority ( new SimpleGrantedAuthority ( authority ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the provided value as a Bearer token in a header with the name of { [CODESPLIT] public static Consumer < HttpHeaders > bearerToken ( String bearerTokenValue ) { Assert . hasText ( bearerTokenValue , \"bearerTokenValue cannot be null\" ) ; return headers -> headers . set ( HttpHeaders . AUTHORIZATION , \"Bearer \" + bearerTokenValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a Spring LDAP - compliant Provider URL string i . e . a space - separated list of LDAP servers with their base DNs . As the base DN must be identical for all servers it needs to be supplied only once . [CODESPLIT] private static String buildProviderUrl ( List < String > urls , String baseDn ) { Assert . notNull ( baseDn , \"The Base DN for the LDAP server must not be null.\" ) ; Assert . notEmpty ( urls , \"At least one LDAP server URL must be provided.\" ) ; String trimmedBaseDn = baseDn . trim ( ) ; StringBuilder providerUrl = new StringBuilder ( ) ; for ( String serverUrl : urls ) { String trimmedUrl = serverUrl . trim ( ) ; if ( \"\" . equals ( trimmedUrl ) ) { continue ; } providerUrl . append ( trimmedUrl ) ; if ( ! trimmedUrl . endsWith ( \"/\" ) ) { providerUrl . append ( \"/\" ) ; } providerUrl . append ( trimmedBaseDn ) ; providerUrl . append ( \" \" ) ; } return providerUrl . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the user authority list from the values of the { [CODESPLIT] @ Override protected Collection < ? extends GrantedAuthority > loadUserAuthorities ( DirContextOperations userData , String username , String password ) { String [ ] groups = userData . getStringAttributes ( \"memberOf\" ) ; if ( groups == null ) { logger . debug ( \"No values for 'memberOf' attribute.\" ) ; return AuthorityUtils . NO_AUTHORITIES ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"'memberOf' attribute values: \" + Arrays . asList ( groups ) ) ; } ArrayList < GrantedAuthority > authorities = new ArrayList <> ( groups . length ) ; for ( String group : groups ) { authorities . add ( new SimpleGrantedAuthority ( new DistinguishedName ( group ) . removeLast ( ) . getValue ( ) ) ) ; } return authorities ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows a custom environment properties to be used to create initial LDAP context . [CODESPLIT] public void setContextEnvironmentProperties ( Map < String , Object > environment ) { Assert . notEmpty ( environment , \"environment must not be empty\" ) ; this . contextEnvironmentProperties = new Hashtable <> ( environment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the state parameter from the { [CODESPLIT] private String getStateParameter ( ServerWebExchange exchange ) { Assert . notNull ( exchange , \"exchange cannot be null\" ) ; return exchange . getRequest ( ) . getQueryParams ( ) . getFirst ( OAuth2ParameterNames . STATE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the current request matches the <code > DefaultSavedRequest< / code > . <p > All URL arguments are considered but not cookies locales headers or parameters . [CODESPLIT] public boolean doesRequestMatch ( HttpServletRequest request , PortResolver portResolver ) { if ( ! propertyEquals ( \"pathInfo\" , this . pathInfo , request . getPathInfo ( ) ) ) { return false ; } if ( ! propertyEquals ( \"queryString\" , this . queryString , request . getQueryString ( ) ) ) { return false ; } if ( ! propertyEquals ( \"requestURI\" , this . requestURI , request . getRequestURI ( ) ) ) { return false ; } if ( ! \"GET\" . equals ( request . getMethod ( ) ) && \"GET\" . equals ( method ) ) { // A save GET should not match an incoming non-GET method return false ; } if ( ! propertyEquals ( \"serverPort\" , Integer . valueOf ( this . serverPort ) , Integer . valueOf ( portResolver . getServerPort ( request ) ) ) ) { return false ; } if ( ! propertyEquals ( \"requestURL\" , this . requestURL , request . getRequestURL ( ) . toString ( ) ) ) { return false ; } if ( ! propertyEquals ( \"scheme\" , this . scheme , request . getScheme ( ) ) ) { return false ; } if ( ! propertyEquals ( \"serverName\" , this . serverName , request . getServerName ( ) ) ) { return false ; } if ( ! propertyEquals ( \"contextPath\" , this . contextPath , request . getContextPath ( ) ) ) { return false ; } return propertyEquals ( \"servletPath\" , this . servletPath , request . getServletPath ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates the URL that the user agent used for this request . [CODESPLIT] @ Override public String getRedirectUrl ( ) { return UrlUtils . buildFullRequestUrl ( scheme , serverName , serverPort , requestURI , queryString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the following { @link Converter } for manipulating the JWT s claim set [CODESPLIT] public void setClaimSetConverter ( Converter < Map < String , Object > , Map < String , Object > > claimSetConverter ) { Assert . notNull ( claimSetConverter , \"claimSetConverter cannot be null\" ) ; this . claimSetConverter = claimSetConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter } used for converting the { @link OAuth2UserRequest } to a { @link RequestEntity } representation of the UserInfo Request . [CODESPLIT] public final void setRequestEntityConverter ( Converter < OAuth2UserRequest , RequestEntity < ? > > requestEntityConverter ) { Assert . notNull ( requestEntityConverter , \"requestEntityConverter cannot be null\" ) ; this . requestEntityConverter = requestEntityConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , ModelAndViewContainer mavContainer , NativeWebRequest webRequest , WebDataBinderFactory binderFactory ) throws Exception { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication == null ) { return null ; } Object principal = authentication . getPrincipal ( ) ; if ( principal != null && ! parameter . getParameterType ( ) . isAssignableFrom ( principal . getClass ( ) ) ) { AuthenticationPrincipal authPrincipal = findMethodAnnotation ( AuthenticationPrincipal . class , parameter ) ; if ( authPrincipal . errorOnInvalidType ( ) ) { throw new ClassCastException ( principal + \" is not assignable to \" + parameter . getParameterType ( ) ) ; } else { return null ; } } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link JwtDecoder } using the provided <a href = https : // openid . net / specs / openid - connect - core - 1_0 . html#IssuerIdentifier > Issuer< / a > by making an <a href = https : // openid . net / specs / openid - connect - discovery - 1_0 . html#ProviderConfigurationRequest > OpenID Provider Configuration Request< / a > and using the values in the <a href = https : // openid . net / specs / openid - connect - discovery - 1_0 . html#ProviderConfigurationResponse > OpenID Provider Configuration Response< / a > to initialize the { @link JwtDecoder } . [CODESPLIT] public static JwtDecoder fromOidcIssuerLocation ( String oidcIssuerLocation ) { Map < String , Object > openidConfiguration = getOpenidConfiguration ( oidcIssuerLocation ) ; String metadataIssuer = \"(unavailable)\" ; if ( openidConfiguration . containsKey ( \"issuer\" ) ) { metadataIssuer = openidConfiguration . get ( \"issuer\" ) . toString ( ) ; } if ( ! oidcIssuerLocation . equals ( metadataIssuer ) ) { throw new IllegalStateException ( \"The Issuer \\\"\" + metadataIssuer + \"\\\" provided in the OpenID Configuration \" + \"did not match the requested issuer \\\"\" + oidcIssuerLocation + \"\\\"\" ) ; } OAuth2TokenValidator < Jwt > jwtValidator = JwtValidators . createDefaultWithIssuer ( oidcIssuerLocation ) ; NimbusJwtDecoder jwtDecoder = withJwkSetUri ( openidConfiguration . get ( \"jwks_uri\" ) . toString ( ) ) . build ( ) ; jwtDecoder . setJwtValidator ( jwtValidator ) ; return jwtDecoder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The aim of this method is to build the list of filters which have been defined by the namespace elements and attributes within the &lt ; http&gt ; configuration along with any custom - filter s linked to user - defined filter beans . <p > By the end of this method the default <tt > FilterChainProxy< / tt > bean should have been registered and will have the map of filter chains defined with the universal match pattern mapped to the list of beans which have been parsed here . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) @ Override public BeanDefinition parse ( Element element , ParserContext pc ) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition ( element . getTagName ( ) , pc . extractSource ( element ) ) ; pc . pushContainingComponent ( compositeDef ) ; registerFilterChainProxyIfNecessary ( pc , pc . extractSource ( element ) ) ; // Obtain the filter chains and add the new chain to it BeanDefinition listFactoryBean = pc . getRegistry ( ) . getBeanDefinition ( BeanIds . FILTER_CHAINS ) ; List < BeanReference > filterChains = ( List < BeanReference > ) listFactoryBean . getPropertyValues ( ) . getPropertyValue ( \"sourceList\" ) . getValue ( ) ; filterChains . add ( createFilterChain ( element , pc ) ) ; pc . popAndRegisterContainingComponent ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { [CODESPLIT] private BeanReference createFilterChain ( Element element , ParserContext pc ) { boolean secured = ! OPT_SECURITY_NONE . equals ( element . getAttribute ( ATT_SECURED ) ) ; if ( ! secured ) { if ( ! StringUtils . hasText ( element . getAttribute ( ATT_PATH_PATTERN ) ) && ! StringUtils . hasText ( ATT_REQUEST_MATCHER_REF ) ) { pc . getReaderContext ( ) . error ( \"The '\" + ATT_SECURED + \"' attribute must be used in combination with\" + \" the '\" + ATT_PATH_PATTERN + \"' or '\" + ATT_REQUEST_MATCHER_REF + \"' attributes.\" , pc . extractSource ( element ) ) ; } for ( int n = 0 ; n < element . getChildNodes ( ) . getLength ( ) ; n ++ ) { if ( element . getChildNodes ( ) . item ( n ) instanceof Element ) { pc . getReaderContext ( ) . error ( \"If you are using <http> to define an unsecured pattern, \" + \"it cannot contain child elements.\" , pc . extractSource ( element ) ) ; } } return createSecurityFilterChainBean ( element , pc , Collections . emptyList ( ) ) ; } final BeanReference portMapper = createPortMapper ( element , pc ) ; final BeanReference portResolver = createPortResolver ( portMapper , pc ) ; ManagedList < BeanReference > authenticationProviders = new ManagedList <> ( ) ; BeanReference authenticationManager = createAuthenticationManager ( element , pc , authenticationProviders ) ; boolean forceAutoConfig = isDefaultHttpConfig ( element ) ; HttpConfigurationBuilder httpBldr = new HttpConfigurationBuilder ( element , forceAutoConfig , pc , portMapper , portResolver , authenticationManager ) ; AuthenticationConfigBuilder authBldr = new AuthenticationConfigBuilder ( element , forceAutoConfig , pc , httpBldr . getSessionCreationPolicy ( ) , httpBldr . getRequestCache ( ) , authenticationManager , httpBldr . getSessionStrategy ( ) , portMapper , portResolver , httpBldr . getCsrfLogoutHandler ( ) ) ; httpBldr . setLogoutHandlers ( authBldr . getLogoutHandlers ( ) ) ; httpBldr . setEntryPoint ( authBldr . getEntryPointBean ( ) ) ; httpBldr . setAccessDeniedHandler ( authBldr . getAccessDeniedHandlerBean ( ) ) ; authenticationProviders . addAll ( authBldr . getProviders ( ) ) ; List < OrderDecorator > unorderedFilterChain = new ArrayList <> ( ) ; unorderedFilterChain . addAll ( httpBldr . getFilters ( ) ) ; unorderedFilterChain . addAll ( authBldr . getFilters ( ) ) ; unorderedFilterChain . addAll ( buildCustomFilterList ( element , pc ) ) ; Collections . sort ( unorderedFilterChain , new OrderComparator ( ) ) ; checkFilterChainOrder ( unorderedFilterChain , pc , pc . extractSource ( element ) ) ; // The list of filter beans List < BeanMetadataElement > filterChain = new ManagedList <> ( ) ; for ( OrderDecorator od : unorderedFilterChain ) { filterChain . add ( od . bean ) ; } return createSecurityFilterChainBean ( element , pc , filterChain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the internal AuthenticationManager bean which uses either the externally registered ( global ) one as a parent or the bean specified by authentication - manager - ref . [CODESPLIT] private BeanReference createAuthenticationManager ( Element element , ParserContext pc , ManagedList < BeanReference > authenticationProviders ) { String parentMgrRef = element . getAttribute ( ATT_AUTHENTICATION_MANAGER_REF ) ; BeanDefinitionBuilder authManager = BeanDefinitionBuilder . rootBeanDefinition ( ProviderManager . class ) ; authManager . addConstructorArgValue ( authenticationProviders ) ; if ( StringUtils . hasText ( parentMgrRef ) ) { RuntimeBeanReference parentAuthManager = new RuntimeBeanReference ( parentMgrRef ) ; authManager . addConstructorArgValue ( parentAuthManager ) ; RootBeanDefinition clearCredentials = new RootBeanDefinition ( ClearCredentialsMethodInvokingFactoryBean . class ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( \"targetObject\" , parentAuthManager ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( \"targetMethod\" , \"isEraseCredentialsAfterAuthentication\" ) ; authManager . addPropertyValue ( \"eraseCredentialsAfterAuthentication\" , clearCredentials ) ; } else { RootBeanDefinition amfb = new RootBeanDefinition ( AuthenticationManagerFactoryBean . class ) ; amfb . setRole ( BeanDefinition . ROLE_INFRASTRUCTURE ) ; String amfbId = pc . getReaderContext ( ) . generateBeanName ( amfb ) ; pc . registerBeanComponent ( new BeanComponentDefinition ( amfb , amfbId ) ) ; RootBeanDefinition clearCredentials = new RootBeanDefinition ( MethodInvokingFactoryBean . class ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( \"targetObject\" , new RuntimeBeanReference ( amfbId ) ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( \"targetMethod\" , \"isEraseCredentialsAfterAuthentication\" ) ; authManager . addConstructorArgValue ( new RuntimeBeanReference ( amfbId ) ) ; authManager . addPropertyValue ( \"eraseCredentialsAfterAuthentication\" , clearCredentials ) ; } authManager . getRawBeanDefinition ( ) . setSource ( pc . extractSource ( element ) ) ; BeanDefinition authMgrBean = authManager . getBeanDefinition ( ) ; String id = pc . getReaderContext ( ) . generateBeanName ( authMgrBean ) ; pc . registerBeanComponent ( new BeanComponentDefinition ( authMgrBean , id ) ) ; return new RuntimeBeanReference ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OAuth2TokenValidatorResult validate ( T token ) { Collection < OAuth2Error > errors = new ArrayList <> ( ) ; for ( OAuth2TokenValidator < T > validator : this . tokenValidators ) { errors . addAll ( validator . validate ( token ) . getErrors ( ) ) ; } return OAuth2TokenValidatorResult . failure ( errors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the base class { @link AbstractAuthorizeTag#authorize () } method to decide if the body of the tag should be skipped or not . [CODESPLIT] public int doStartTag ( ) throws JspException { try { authorized = super . authorize ( ) ; if ( ! authorized && TagLibConfig . isUiSecurityDisabled ( ) ) { pageContext . getOut ( ) . write ( TagLibConfig . getSecuredUiPrefix ( ) ) ; } if ( var != null ) { pageContext . setAttribute ( var , authorized , PageContext . PAGE_SCOPE ) ; } return TagLibConfig . evalOrSkip ( authorized ) ; } catch ( IOException e ) { throw new JspException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default processing of the end tag returning EVAL_PAGE . [CODESPLIT] public int doEndTag ( ) throws JspException { try { if ( ! authorized && TagLibConfig . isUiSecurityDisabled ( ) ) { pageContext . getOut ( ) . write ( TagLibConfig . getSecuredUiSuffix ( ) ) ; } } catch ( IOException e ) { throw new JspException ( e ) ; } return EVAL_PAGE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates the users that have been added . [CODESPLIT] @ Override protected void initUserDetailsService ( ) throws Exception { for ( UserDetailsBuilder userBuilder : userBuilders ) { getUserDetailsService ( ) . createUser ( userBuilder . build ( ) ) ; } for ( UserDetails userDetails : this . users ) { getUserDetailsService ( ) . createUser ( userDetails ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows adding a user to the { @link UserDetailsManager } that is being created . This method can be invoked multiple times to add multiple users . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public final C withUser ( User . UserBuilder userBuilder ) { this . users . add ( userBuilder . build ( ) ) ; return ( C ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows adding a user to the { @link UserDetailsManager } that is being created . This method can be invoked multiple times to add multiple users . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public final UserDetailsBuilder withUser ( String username ) { UserDetailsBuilder userBuilder = new UserDetailsBuilder ( ( C ) this ) ; userBuilder . username ( username ) ; this . userBuilders . add ( userBuilder ) ; return userBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default { [CODESPLIT] private SecurityWebFilterChain springSecurityFilterChain ( ServerHttpSecurity http ) { http . authorizeExchange ( ) . anyExchange ( ) . authenticated ( ) ; if ( isOAuth2Present && OAuth2ClasspathGuard . shouldConfigure ( this . context ) ) { OAuth2ClasspathGuard . configure ( this . context , http ) ; } else { http . httpBasic ( ) . and ( ) . formLogin ( ) ; } SecurityWebFilterChain result = http . build ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the value of an XML attribute which represents a redirect URL . If not empty or starting with $ ( potential placeholder ) or starting with # ( potential SpEL ) / or http it will raise an error . [CODESPLIT] static void validateHttpRedirect ( String url , ParserContext pc , Object source ) { if ( ! StringUtils . hasText ( url ) || UrlUtils . isValidRedirectUrl ( url ) || url . startsWith ( \"$\" ) || url . startsWith ( \"#\" ) ) { return ; } pc . getReaderContext ( ) . warning ( url + \" is not a valid redirect URL (must start with '/' or http(s))\" , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the <code > response< / code > portion of a Digest authentication header . Both the server and user agent should compute the <code > response< / code > independently . Provided as a static method to simplify the coding of user agents . [CODESPLIT] static String generateDigest ( boolean passwordAlreadyEncoded , String username , String realm , String password , String httpMethod , String uri , String qop , String nonce , String nc , String cnonce ) throws IllegalArgumentException { String a1Md5 ; String a2 = httpMethod + \":\" + uri ; String a2Md5 = md5Hex ( a2 ) ; if ( passwordAlreadyEncoded ) { a1Md5 = password ; } else { a1Md5 = DigestAuthUtils . encodePasswordInA1Format ( username , realm , password ) ; } String digest ; if ( qop == null ) { // as per RFC 2069 compliant clients (also reaffirmed by RFC 2617) digest = a1Md5 + \":\" + nonce + \":\" + a2Md5 ; } else if ( \"auth\" . equals ( qop ) ) { // As per RFC 2617 compliant clients digest = a1Md5 + \":\" + nonce + \":\" + nc + \":\" + cnonce + \":\" + qop + \":\" + a2Md5 ; } else { throw new IllegalArgumentException ( \"This method does not support a qop: '\" + qop + \"'\" ) ; } return md5Hex ( digest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an array of <code > String< / code > s and for each element removes any instances of <code > removeCharacter< / code > and splits the element based on the <code > delimiter< / code > . A <code > Map< / code > is then generated with the left of the delimiter providing the key and the right of the delimiter providing the value . <p > Will trim both the key and value before adding to the <code > Map< / code > . < / p > [CODESPLIT] static Map < String , String > splitEachArrayElementAndCreateMap ( String [ ] array , String delimiter , String removeCharacters ) { if ( ( array == null ) || ( array . length == 0 ) ) { return null ; } Map < String , String > map = new HashMap <> ( ) ; for ( String s : array ) { String postRemove ; if ( removeCharacters == null ) { postRemove = s ; } else { postRemove = StringUtils . replace ( s , removeCharacters , \"\" ) ; } String [ ] splitThisArrayElement = split ( postRemove , delimiter ) ; if ( splitThisArrayElement == null ) { continue ; } map . put ( splitThisArrayElement [ 0 ] . trim ( ) , splitThisArrayElement [ 1 ] . trim ( ) ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a <code > String< / code > at the first instance of the delimiter . <p > Does not include the delimiter in the response . < / p > [CODESPLIT] static String [ ] split ( String toSplit , String delimiter ) { Assert . hasLength ( toSplit , \"Cannot split a null or empty string\" ) ; Assert . hasLength ( delimiter , \"Cannot use a null or empty delimiter to split a string\" ) ; if ( delimiter . length ( ) != 1 ) { throw new IllegalArgumentException ( \"Delimiter can only be one character in length\" ) ; } int offset = toSplit . indexOf ( delimiter ) ; if ( offset < 0 ) { return null ; } String beforeDelimiter = toSplit . substring ( 0 , offset ) ; String afterDelimiter = toSplit . substring ( offset + 1 ) ; return new String [ ] { beforeDelimiter , afterDelimiter } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . notNull ( getSecureObjectClass ( ) , \"Subclass must provide a non-null response to getSecureObjectClass()\" ) ; Assert . notNull ( this . messages , \"A message source must be set\" ) ; Assert . notNull ( this . authenticationManager , \"An AuthenticationManager is required\" ) ; Assert . notNull ( this . accessDecisionManager , \"An AccessDecisionManager is required\" ) ; Assert . notNull ( this . runAsManager , \"A RunAsManager is required\" ) ; Assert . notNull ( this . obtainSecurityMetadataSource ( ) , \"An SecurityMetadataSource is required\" ) ; Assert . isTrue ( this . obtainSecurityMetadataSource ( ) . supports ( getSecureObjectClass ( ) ) , ( ) -> \"SecurityMetadataSource does not support secure object class: \" + getSecureObjectClass ( ) ) ; Assert . isTrue ( this . runAsManager . supports ( getSecureObjectClass ( ) ) , ( ) -> \"RunAsManager does not support secure object class: \" + getSecureObjectClass ( ) ) ; Assert . isTrue ( this . accessDecisionManager . supports ( getSecureObjectClass ( ) ) , ( ) -> \"AccessDecisionManager does not support secure object class: \" + getSecureObjectClass ( ) ) ; if ( this . afterInvocationManager != null ) { Assert . isTrue ( this . afterInvocationManager . supports ( getSecureObjectClass ( ) ) , ( ) -> \"AfterInvocationManager does not support secure object class: \" + getSecureObjectClass ( ) ) ; } if ( this . validateConfigAttributes ) { Collection < ConfigAttribute > attributeDefs = this . obtainSecurityMetadataSource ( ) . getAllConfigAttributes ( ) ; if ( attributeDefs == null ) { logger . warn ( \"Could not validate configuration attributes as the SecurityMetadataSource did not return \" + \"any attributes from getAllConfigAttributes()\" ) ; return ; } Set < ConfigAttribute > unsupportedAttrs = new HashSet <> ( ) ; for ( ConfigAttribute attr : attributeDefs ) { if ( ! this . runAsManager . supports ( attr ) && ! this . accessDecisionManager . supports ( attr ) && ( ( this . afterInvocationManager == null ) || ! this . afterInvocationManager . supports ( attr ) ) ) { unsupportedAttrs . add ( attr ) ; } } if ( unsupportedAttrs . size ( ) != 0 ) { throw new IllegalArgumentException ( \"Unsupported configuration attributes: \" + unsupportedAttrs ) ; } logger . debug ( \"Validated configuration attributes\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans up the work of the <tt > AbstractSecurityInterceptor< / tt > after the secure object invocation has been completed . This method should be invoked after the secure object invocation and before afterInvocation regardless of the secure object invocation returning successfully ( i . e . it should be done in a finally block ) . [CODESPLIT] protected void finallyInvocation ( InterceptorStatusToken token ) { if ( token != null && token . isContextHolderRefreshRequired ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Reverting to original Authentication: \" + token . getSecurityContext ( ) . getAuthentication ( ) ) ; } SecurityContextHolder . setContext ( token . getSecurityContext ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completes the work of the <tt > AbstractSecurityInterceptor< / tt > after the secure object invocation has been completed . [CODESPLIT] protected Object afterInvocation ( InterceptorStatusToken token , Object returnedObject ) { if ( token == null ) { // public object return returnedObject ; } finallyInvocation ( token ) ; // continue to clean in this method for passivity if ( afterInvocationManager != null ) { // Attempt after invocation handling try { returnedObject = afterInvocationManager . decide ( token . getSecurityContext ( ) . getAuthentication ( ) , token . getSecureObject ( ) , token . getAttributes ( ) , returnedObject ) ; } catch ( AccessDeniedException accessDeniedException ) { AuthorizationFailureEvent event = new AuthorizationFailureEvent ( token . getSecureObject ( ) , token . getAttributes ( ) , token . getSecurityContext ( ) . getAuthentication ( ) , accessDeniedException ) ; publishEvent ( event ) ; throw accessDeniedException ; } } return returnedObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the current authentication token and passes it to the AuthenticationManager if { @link org . springframework . security . core . Authentication#isAuthenticated () } returns false or the property <tt > alwaysReauthenticate< / tt > has been set to true . [CODESPLIT] private Authentication authenticateIfRequired ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication . isAuthenticated ( ) && ! alwaysReauthenticate ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Previously Authenticated: \" + authentication ) ; } return authentication ; } authentication = authenticationManager . authenticate ( authentication ) ; // We don't authenticated.setAuthentication(true), because each provider should do // that if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Successfully Authenticated: \" + authentication ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authentication ) ; return authentication ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method which generates an exception containing the passed reason and publishes an event to the application context . <p > Always throws an exception . [CODESPLIT] private void credentialsNotFound ( String reason , Object secureObject , Collection < ConfigAttribute > configAttribs ) { AuthenticationCredentialsNotFoundException exception = new AuthenticationCredentialsNotFoundException ( reason ) ; AuthenticationCredentialsNotFoundEvent event = new AuthenticationCredentialsNotFoundEvent ( secureObject , configAttribs , exception ) ; publishEvent ( event ) ; throw exception ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains a user details service for use in RememberMeServices etc . Will return a caching version if available so should not be used for beans which need to separate the two . [CODESPLIT] private UserDetailsService getUserDetailsService ( ) { Map < String , ? > beans = getBeansOfType ( CachingUserDetailsService . class ) ; if ( beans . size ( ) == 0 ) { beans = getBeansOfType ( UserDetailsService . class ) ; } if ( beans . size ( ) == 0 ) { throw new ApplicationContextException ( \"No UserDetailsService registered.\" ) ; } else if ( beans . size ( ) > 1 ) { throw new ApplicationContextException ( \"More than one UserDetailsService registered. Please \" + \"use a specific Id reference in <remember-me/> <openid-login/> or <x509 /> elements.\" ) ; } return ( UserDetailsService ) beans . values ( ) . toArray ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and adds additional PKCE parameters for use in the OAuth 2 . 0 Authorization and Access Token Requests [CODESPLIT] private void addPkceParameters ( Map < String , Object > attributes , Map < String , Object > additionalParameters ) { String codeVerifier = this . codeVerifierGenerator . generateKey ( ) ; attributes . put ( PkceParameterNames . CODE_VERIFIER , codeVerifier ) ; try { String codeChallenge = createCodeChallenge ( codeVerifier ) ; additionalParameters . put ( PkceParameterNames . CODE_CHALLENGE , codeChallenge ) ; additionalParameters . put ( PkceParameterNames . CODE_CHALLENGE_METHOD , \"S256\" ) ; } catch ( NoSuchAlgorithmException e ) { additionalParameters . put ( PkceParameterNames . CODE_CHALLENGE , codeVerifier ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override protected final void successfulAuthentication ( HttpServletRequest request , HttpServletResponse response , FilterChain chain , Authentication authResult ) throws IOException , ServletException { boolean continueFilterChain = proxyTicketRequest ( serviceTicketRequest ( request , response ) , request ) ; if ( ! continueFilterChain ) { super . successfulAuthentication ( request , response , chain , authResult ) ; return ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Authentication success. Updating SecurityContextHolder to contain: \" + authResult ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authResult ) ; // Fire event if ( this . eventPublisher != null ) { eventPublisher . publishEvent ( new InteractiveAuthenticationSuccessEvent ( authResult , this . getClass ( ) ) ) ; } chain . doFilter ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overridden to provide proxying capabilities . [CODESPLIT] protected boolean requiresAuthentication ( final HttpServletRequest request , final HttpServletResponse response ) { final boolean serviceTicketRequest = serviceTicketRequest ( request , response ) ; final boolean result = serviceTicketRequest || proxyReceptorRequest ( request ) || ( proxyTicketRequest ( serviceTicketRequest , request ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"requiresAuthentication = \" + result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if the request is elgible to process a service ticket . This method exists for readability . [CODESPLIT] private boolean serviceTicketRequest ( final HttpServletRequest request , final HttpServletResponse response ) { boolean result = super . requiresAuthentication ( request , response ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"serviceTicketRequest = \" + result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if the request is elgible to process a proxy ticket . [CODESPLIT] private boolean proxyTicketRequest ( final boolean serviceTicketRequest , final HttpServletRequest request ) { if ( serviceTicketRequest ) { return false ; } final boolean result = authenticateAllArtifacts && obtainArtifact ( request ) != null && ! authenticated ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"proxyTicketRequest = \" + result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if a user is already authenticated . [CODESPLIT] private boolean authenticated ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; return authentication != null && authentication . isAuthenticated ( ) && ! ( authentication instanceof AnonymousAuthenticationToken ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if the request is elgible to be processed as the proxy receptor . [CODESPLIT] private boolean proxyReceptorRequest ( final HttpServletRequest request ) { final boolean result = proxyReceptorConfigured ( ) && proxyReceptorMatcher . matches ( request ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"proxyReceptorRequest = \" + result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the { @link CasAuthenticationFilter } is configured to handle the proxy receptor requests . [CODESPLIT] private boolean proxyReceptorConfigured ( ) { final boolean result = this . proxyGrantingTicketStorage != null && proxyReceptorMatcher != null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"proxyReceptorConfigured = \" + result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the SQL <tt > usersByUsernameQuery< / tt > and returns a list of UserDetails objects . There should normally only be one matching user . [CODESPLIT] protected List < UserDetails > loadUsersByUsername ( String username ) { return getJdbcTemplate ( ) . query ( getUsersByUsernameQuery ( ) , new String [ ] { username } , ( rs , rowNum ) -> { String userName = rs . getString ( 1 ) ; String password = rs . getString ( 2 ) ; boolean enabled = rs . getBoolean ( 3 ) ; boolean accLocked = false ; boolean accExpired = false ; boolean credsExpired = false ; if ( rs . getMetaData ( ) . getColumnCount ( ) > 3 ) { //NOTE: acc_locked, acc_expired and creds_expired are also to be loaded accLocked = rs . getBoolean ( 4 ) ; accExpired = rs . getBoolean ( 5 ) ; credsExpired = rs . getBoolean ( 6 ) ; } return new User ( userName , password , enabled , ! accExpired , ! credsExpired , ! accLocked , AuthorityUtils . NO_AUTHORITIES ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a unique { [CODESPLIT] public static WebApplicationContext findRequiredWebApplicationContext ( ServletContext servletContext ) { WebApplicationContext wac = _findWebApplicationContext ( servletContext ) ; if ( wac == null ) { throw new IllegalStateException ( \"No WebApplicationContext found: no ContextLoaderListener registered?\" ) ; } return wac ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy of { [CODESPLIT] private static WebApplicationContext _findWebApplicationContext ( ServletContext sc ) { WebApplicationContext wac = getWebApplicationContext ( sc ) ; if ( wac == null ) { Enumeration < String > attrNames = sc . getAttributeNames ( ) ; while ( attrNames . hasMoreElements ( ) ) { String attrName = attrNames . nextElement ( ) ; Object attrValue = sc . getAttribute ( attrName ) ; if ( attrValue instanceof WebApplicationContext ) { if ( wac != null ) { throw new IllegalStateException ( \"No unique WebApplicationContext found: more than one \" + \"DispatcherServlet registered with publishContext=true?\" ) ; } wac = ( WebApplicationContext ) attrValue ; } } } return wac ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses a { [CODESPLIT] public StandardEvaluationContext createEvaluationContextInternal ( Authentication auth , MethodInvocation mi ) { return new MethodSecurityEvaluationContext ( auth , mi , getParameterNameDiscoverer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the root object for expression evaluation . [CODESPLIT] protected MethodSecurityExpressionOperations createSecurityExpressionRoot ( Authentication authentication , MethodInvocation invocation ) { MethodSecurityExpressionRoot root = new MethodSecurityExpressionRoot ( authentication ) ; root . setThis ( invocation . getThis ( ) ) ; root . setPermissionEvaluator ( getPermissionEvaluator ( ) ) ; root . setTrustResolver ( getTrustResolver ( ) ) ; root . setRoleHierarchy ( getRoleHierarchy ( ) ) ; root . setDefaultRolePrefix ( getDefaultRolePrefix ( ) ) ; return root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters the { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Object filter ( Object filterTarget , Expression filterExpression , EvaluationContext ctx ) { MethodSecurityExpressionOperations rootObject = ( MethodSecurityExpressionOperations ) ctx . getRootObject ( ) . getValue ( ) ; final boolean debug = logger . isDebugEnabled ( ) ; List retainList ; if ( debug ) { logger . debug ( \"Filtering with expression: \" + filterExpression . getExpressionString ( ) ) ; } if ( filterTarget instanceof Collection ) { Collection collection = ( Collection ) filterTarget ; retainList = new ArrayList ( collection . size ( ) ) ; if ( debug ) { logger . debug ( \"Filtering collection with \" + collection . size ( ) + \" elements\" ) ; } if ( permissionCacheOptimizer != null ) { permissionCacheOptimizer . cachePermissionsFor ( rootObject . getAuthentication ( ) , collection ) ; } for ( Object filterObject : ( Collection ) filterTarget ) { rootObject . setFilterObject ( filterObject ) ; if ( ExpressionUtils . evaluateAsBoolean ( filterExpression , ctx ) ) { retainList . add ( filterObject ) ; } } if ( debug ) { logger . debug ( \"Retaining elements: \" + retainList ) ; } collection . clear ( ) ; collection . addAll ( retainList ) ; return filterTarget ; } if ( filterTarget . getClass ( ) . isArray ( ) ) { Object [ ] array = ( Object [ ] ) filterTarget ; retainList = new ArrayList ( array . length ) ; if ( debug ) { logger . debug ( \"Filtering array with \" + array . length + \" elements\" ) ; } if ( permissionCacheOptimizer != null ) { permissionCacheOptimizer . cachePermissionsFor ( rootObject . getAuthentication ( ) , Arrays . asList ( array ) ) ; } for ( Object o : array ) { rootObject . setFilterObject ( o ) ; if ( ExpressionUtils . evaluateAsBoolean ( filterExpression , ctx ) ) { retainList . add ( o ) ; } } if ( debug ) { logger . debug ( \"Retaining elements: \" + retainList ) ; } Object [ ] filtered = ( Object [ ] ) Array . newInstance ( filterTarget . getClass ( ) . getComponentType ( ) , retainList . size ( ) ) ; for ( int i = 0 ; i < retainList . size ( ) ; i ++ ) { filtered [ i ] = retainList . get ( i ) ; } return filtered ; } if ( filterTarget instanceof Stream ) { final Stream < ? > original = ( Stream < ? > ) filterTarget ; return original . filter ( filterObject -> { rootObject . setFilterObject ( filterObject ) ; return ExpressionUtils . evaluateAsBoolean ( filterExpression , ctx ) ; } ) . onClose ( original :: close ) ; } throw new IllegalArgumentException ( \"Filter target must be a collection, array, or stream type, but was \" + filterTarget ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the cached JWK set from the configured URL . [CODESPLIT] private Mono < JWKSet > getJWKSet ( ) { return this . webClient . get ( ) . uri ( this . jwkSetURL ) . retrieve ( ) . bodyToMono ( String . class ) . map ( this :: parse ) . doOnNext ( jwkSet -> this . cachedJWKSet . set ( Mono . just ( jwkSet ) ) ) . cache ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first specified key ID ( kid ) for a JWK matcher . [CODESPLIT] protected static String getFirstSpecifiedKeyID ( final JWKMatcher jwkMatcher ) { Set < String > keyIDs = jwkMatcher . getKeyIDs ( ) ; if ( keyIDs == null || keyIDs . isEmpty ( ) ) { return null ; } for ( String id : keyIDs ) { if ( id != null ) { return id ; } } return null ; // No kid in matcher }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Redirects the response to the supplied URL . <p > If <tt > contextRelative< / tt > is set the redirect value will be the value after the request context path . Note that this will result in the loss of protocol information ( HTTP or HTTPS ) so will cause problems if a redirect is being performed to change to HTTPS for example . [CODESPLIT] public void sendRedirect ( HttpServletRequest request , HttpServletResponse response , String url ) throws IOException { String redirectUrl = calculateRedirectUrl ( request . getContextPath ( ) , url ) ; redirectUrl = response . encodeRedirectURL ( redirectUrl ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Redirecting to '\" + redirectUrl + \"'\" ) ; } response . sendRedirect ( redirectUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Authentication authenticate ( final Authentication authentication ) throws AuthenticationException { if ( ! supports ( authentication . getClass ( ) ) ) { return null ; } if ( authentication instanceof OpenIDAuthenticationToken ) { OpenIDAuthenticationToken response = ( OpenIDAuthenticationToken ) authentication ; OpenIDAuthenticationStatus status = response . getStatus ( ) ; // handle the various possibilities if ( status == OpenIDAuthenticationStatus . SUCCESS ) { // Lookup user details UserDetails userDetails = this . userDetailsService . loadUserDetails ( response ) ; return createSuccessfulAuthentication ( userDetails , response ) ; } else if ( status == OpenIDAuthenticationStatus . CANCELLED ) { throw new AuthenticationCancelledException ( \"Log in cancelled\" ) ; } else if ( status == OpenIDAuthenticationStatus . ERROR ) { throw new AuthenticationServiceException ( \"Error message from server: \" + response . getMessage ( ) ) ; } else if ( status == OpenIDAuthenticationStatus . FAILURE ) { throw new BadCredentialsException ( \"Log in failed - identity could not be verified\" ) ; } else if ( status == OpenIDAuthenticationStatus . SETUP_NEEDED ) { throw new AuthenticationServiceException ( \"The server responded setup was needed, which shouldn't happen\" ) ; } else { throw new AuthenticationServiceException ( \"Unrecognized return value \" + status . toString ( ) ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the creation of the final <tt > Authentication< / tt > object which will be returned by the provider . <p > The default implementation just creates a new OpenIDAuthenticationToken from the original but with the UserDetails as the principal and including the authorities loaded by the UserDetailsService . [CODESPLIT] protected Authentication createSuccessfulAuthentication ( UserDetails userDetails , OpenIDAuthenticationToken auth ) { return new OpenIDAuthenticationToken ( userDetails , this . authoritiesMapper . mapAuthorities ( userDetails . getAuthorities ( ) ) , auth . getIdentityUrl ( ) , auth . getAttributes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Votes according to JSR 250 . <p > If no JSR - 250 attributes are found it will abstain otherwise it will grant or deny access based on the attributes that are found . [CODESPLIT] public int vote ( Authentication authentication , Object object , Collection < ConfigAttribute > definition ) { boolean jsr250AttributeFound = false ; for ( ConfigAttribute attribute : definition ) { if ( Jsr250SecurityConfig . PERMIT_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_GRANTED ; } if ( Jsr250SecurityConfig . DENY_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_DENIED ; } if ( supports ( attribute ) ) { jsr250AttributeFound = true ; // Attempt to find a matching granted authority for ( GrantedAuthority authority : authentication . getAuthorities ( ) ) { if ( attribute . getAttribute ( ) . equals ( authority . getAuthority ( ) ) ) { return ACCESS_GRANTED ; } } } } return jsr250AttributeFound ? ACCESS_DENIED : ACCESS_ABSTAIN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public void afterPropertiesSet ( ) { super . afterPropertiesSet ( ) ; if ( consumer == null ) { try { consumer = new OpenID4JavaConsumer ( ) ; } catch ( ConsumerException e ) { throw new IllegalArgumentException ( \"Failed to initialize OpenID\" , e ) ; } } if ( returnToUrlParameters . isEmpty ( ) && getRememberMeServices ( ) instanceof AbstractRememberMeServices ) { returnToUrlParameters = new HashSet <> ( ) ; returnToUrlParameters . add ( ( ( AbstractRememberMeServices ) getRememberMeServices ( ) ) . getParameter ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authentication has two phases . <ol > <li > The initial submission of the claimed OpenID . A redirect to the URL returned from the consumer will be performed and null will be returned . < / li > <li > The redirection from the OpenID server to the return_to URL once it has authenticated the user< / li > < / ol > [CODESPLIT] @ Override public Authentication attemptAuthentication ( HttpServletRequest request , HttpServletResponse response ) throws AuthenticationException , IOException { OpenIDAuthenticationToken token ; String identity = request . getParameter ( \"openid.identity\" ) ; if ( ! StringUtils . hasText ( identity ) ) { String claimedIdentity = obtainUsername ( request ) ; try { String returnToUrl = buildReturnToUrl ( request ) ; String realm = lookupRealm ( returnToUrl ) ; String openIdUrl = consumer . beginConsumption ( request , claimedIdentity , returnToUrl , realm ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"return_to is '\" + returnToUrl + \"', realm is '\" + realm + \"'\" ) ; logger . debug ( \"Redirecting to \" + openIdUrl ) ; } response . sendRedirect ( openIdUrl ) ; // Indicate to parent class that authentication is continuing. return null ; } catch ( OpenIDConsumerException e ) { logger . debug ( \"Failed to consume claimedIdentity: \" + claimedIdentity , e ) ; throw new AuthenticationServiceException ( \"Unable to process claimed identity '\" + claimedIdentity + \"'\" ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Supplied OpenID identity is \" + identity ) ; } try { token = consumer . endConsumption ( request ) ; } catch ( OpenIDConsumerException oice ) { throw new AuthenticationServiceException ( \"Consumer error\" , oice ) ; } token . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; // delegate to the authentication provider Authentication authentication = this . getAuthenticationManager ( ) . authenticate ( token ) ; return authentication ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the <tt > return_to< / tt > URL that will be sent to the OpenID service provider . By default returns the URL of the current request . [CODESPLIT] protected String buildReturnToUrl ( HttpServletRequest request ) { StringBuffer sb = request . getRequestURL ( ) ; Iterator < String > iterator = returnToUrlParameters . iterator ( ) ; boolean isFirst = true ; while ( iterator . hasNext ( ) ) { String name = iterator . next ( ) ; // Assume for simplicity that there is only one value String value = request . getParameter ( name ) ; if ( value == null ) { continue ; } if ( isFirst ) { sb . append ( \"?\" ) ; isFirst = false ; } sb . append ( utf8UrlEncode ( name ) ) . append ( \"=\" ) . append ( utf8UrlEncode ( value ) ) ; if ( iterator . hasNext ( ) ) { sb . append ( \"&\" ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the <tt > claimedIdentityFieldName< / tt > from the submitted request . [CODESPLIT] protected String obtainUsername ( HttpServletRequest req ) { String claimedIdentity = req . getParameter ( claimedIdentityFieldName ) ; if ( ! StringUtils . hasText ( claimedIdentity ) ) { logger . error ( \"No claimed identity supplied in authentication request\" ) ; return \"\" ; } return claimedIdentity . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs URL encoding with UTF - 8 [CODESPLIT] private String utf8UrlEncode ( String value ) { try { return URLEncoder . encode ( value , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { Error err = new AssertionError ( \"The Java platform guarantees UTF-8 support, but it seemingly is not present.\" ) ; err . initCause ( e ) ; throw err ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public UserDetails getUserFromCache ( String username ) { Cache . ValueWrapper element = username != null ? cache . get ( username ) : null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Cache hit: \" + ( element != null ) + \"; username: \" + username ) ; } if ( element == null ) { return null ; } else { return ( UserDetails ) element . get ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the current active <code > Authentication< / code > [CODESPLIT] private Authentication getAuthentication ( ) { Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( ! trustResolver . isAnonymous ( auth ) ) { return auth ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the principal s name as obtained from the <code > SecurityContextHolder< / code > . Properly handles both <code > String< / code > - based and <code > UserDetails< / code > - based principals . [CODESPLIT] @ Override public String getRemoteUser ( ) { Authentication auth = getAuthentication ( ) ; if ( ( auth == null ) || ( auth . getPrincipal ( ) == null ) ) { return null ; } if ( auth . getPrincipal ( ) instanceof UserDetails ) { return ( ( UserDetails ) auth . getPrincipal ( ) ) . getUsername ( ) ; } return auth . getPrincipal ( ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > Authentication< / code > ( which is a subclass of <code > Principal< / code > ) or <code > null< / code > if unavailable . [CODESPLIT] @ Override public Principal getUserPrincipal ( ) { Authentication auth = getAuthentication ( ) ; if ( ( auth == null ) || ( auth . getPrincipal ( ) == null ) ) { return null ; } return auth ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link LdapAuthoritiesPopulator } and defaults to { @link DefaultLdapAuthoritiesPopulator } [CODESPLIT] private LdapAuthoritiesPopulator getLdapAuthoritiesPopulator ( ) { if ( ldapAuthoritiesPopulator != null ) { return ldapAuthoritiesPopulator ; } DefaultLdapAuthoritiesPopulator defaultAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator ( contextSource , groupSearchBase ) ; defaultAuthoritiesPopulator . setGroupRoleAttribute ( groupRoleAttribute ) ; defaultAuthoritiesPopulator . setGroupSearchFilter ( groupSearchFilter ) ; defaultAuthoritiesPopulator . setRolePrefix ( this . rolePrefix ) ; this . ldapAuthoritiesPopulator = defaultAuthoritiesPopulator ; return defaultAuthoritiesPopulator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link GrantedAuthoritiesMapper } and defaults to { @link SimpleAuthorityMapper } . [CODESPLIT] protected GrantedAuthoritiesMapper getAuthoritiesMapper ( ) throws Exception { if ( authoritiesMapper != null ) { return authoritiesMapper ; } SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper ( ) ; simpleAuthorityMapper . setPrefix ( this . rolePrefix ) ; simpleAuthorityMapper . afterPropertiesSet ( ) ; this . authoritiesMapper = simpleAuthorityMapper ; return simpleAuthorityMapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link LdapAuthenticator } to use [CODESPLIT] private LdapAuthenticator createLdapAuthenticator ( BaseLdapPathContextSource contextSource ) { AbstractLdapAuthenticator ldapAuthenticator = passwordEncoder == null ? createBindAuthenticator ( contextSource ) : createPasswordCompareAuthenticator ( contextSource ) ; LdapUserSearch userSearch = createUserSearch ( ) ; if ( userSearch != null ) { ldapAuthenticator . setUserSearch ( userSearch ) ; } if ( userDnPatterns != null && userDnPatterns . length > 0 ) { ldapAuthenticator . setUserDnPatterns ( userDnPatterns ) ; } return postProcess ( ldapAuthenticator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link PasswordComparisonAuthenticator } [CODESPLIT] private PasswordComparisonAuthenticator createPasswordCompareAuthenticator ( BaseLdapPathContextSource contextSource ) { PasswordComparisonAuthenticator ldapAuthenticator = new PasswordComparisonAuthenticator ( contextSource ) ; if ( passwordAttribute != null ) { ldapAuthenticator . setPasswordAttributeName ( passwordAttribute ) ; } ldapAuthenticator . setPasswordEncoder ( passwordEncoder ) ; return ldapAuthenticator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the { @link org . springframework . security . crypto . password . PasswordEncoder } to be used when authenticating with password comparison . [CODESPLIT] public LdapAuthenticationProviderConfigurer < B > passwordEncoder ( final org . springframework . security . crypto . password . PasswordEncoder passwordEncoder ) { Assert . notNull ( passwordEncoder , \"passwordEncoder must not be null.\" ) ; this . passwordEncoder = passwordEncoder ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter } used for converting the { @link OAuth2ClientCredentialsGrantRequest } to a { @link RequestEntity } representation of the OAuth 2 . 0 Access Token Request . [CODESPLIT] public void setRequestEntityConverter ( Converter < OAuth2ClientCredentialsGrantRequest , RequestEntity < ? > > requestEntityConverter ) { Assert . notNull ( requestEntityConverter , \"requestEntityConverter cannot be null\" ) ; this . requestEntityConverter = requestEntityConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Mono < Void > onLogoutSuccess ( WebFilterExchange exchange , Authentication authentication ) { return Mono . just ( authentication ) . filter ( OAuth2AuthenticationToken . class :: isInstance ) . filter ( token -> authentication . getPrincipal ( ) instanceof OidcUser ) . map ( OAuth2AuthenticationToken . class :: cast ) . flatMap ( this :: endSessionEndpoint ) . map ( endSessionEndpoint -> endpointUri ( endSessionEndpoint , authentication ) ) . switchIfEmpty ( this . serverLogoutSuccessHandler . onLogoutSuccess ( exchange , authentication ) . then ( Mono . empty ( ) ) ) . flatMap ( endpointUri -> this . redirectStrategy . sendRedirect ( exchange . getExchange ( ) , endpointUri ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void commence ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { String queryString = request . getQueryString ( ) ; String redirectUrl = request . getRequestURI ( ) + ( ( queryString == null ) ? \"\" : ( \"?\" + queryString ) ) ; Integer currentPort = Integer . valueOf ( portResolver . getServerPort ( request ) ) ; Integer redirectPort = getMappedPort ( currentPort ) ; if ( redirectPort != null ) { boolean includePort = redirectPort . intValue ( ) != standardPort ; redirectUrl = scheme + request . getServerName ( ) + ( ( includePort ) ? ( \":\" + redirectPort ) : \"\" ) + redirectUrl ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Redirecting to: \" + redirectUrl ) ; } redirectStrategy . sendRedirect ( request , response , redirectUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter } used for converting the OAuth 2 . 0 Access Token Response parameters to an { @link OAuth2AccessTokenResponse } . [CODESPLIT] public final void setTokenResponseConverter ( Converter < Map < String , String > , OAuth2AccessTokenResponse > tokenResponseConverter ) { Assert . notNull ( tokenResponseConverter , \"tokenResponseConverter cannot be null\" ) ; this . tokenResponseConverter = tokenResponseConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter } used for converting the { @link OAuth2AccessTokenResponse } to a { @code Map } representation of the OAuth 2 . 0 Access Token Response parameters . [CODESPLIT] public final void setTokenResponseParametersConverter ( Converter < OAuth2AccessTokenResponse , Map < String , String > > tokenResponseParametersConverter ) { Assert . notNull ( tokenResponseParametersConverter , \"tokenResponseParametersConverter cannot be null\" ) ; this . tokenResponseParametersConverter = tokenResponseParametersConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a list of Granted Authorities based on the current user s WebSphere groups . [CODESPLIT] private Collection < ? extends GrantedAuthority > getWebSphereGroupsBasedGrantedAuthorities ( ) { List < String > webSphereGroups = wasHelper . getGroupsForCurrentUser ( ) ; Collection < ? extends GrantedAuthority > userGas = webSphereGroups2GrantedAuthoritiesMapper . getGrantedAuthorities ( webSphereGroups ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"WebSphere groups: \" + webSphereGroups + \" mapped to Granted Authorities: \" + userGas ) ; } return userGas ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of PasswordPolicyResponseControl if the passed control is a response control of this type . Attributes of the result are filled with the correct values ( e . g . error code ) . [CODESPLIT] public Control getControlInstance ( Control ctl ) { if ( ctl . getID ( ) . equals ( PasswordPolicyControl . OID ) ) { return new PasswordPolicyResponseControl ( ctl . getEncodedValue ( ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . notNull ( this . authenticationUserDetailsService , \"An authenticationUserDetailsService must be set\" ) ; Assert . notNull ( this . ticketValidator , \"A ticketValidator must be set\" ) ; Assert . notNull ( this . statelessTicketCache , \"A statelessTicketCache must be set\" ) ; Assert . hasText ( this . key , \"A Key is required so CasAuthenticationProvider can identify tokens it previously authenticated\" ) ; Assert . notNull ( this . messages , \"A message source must be set\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the serviceUrl . If the { @link Authentication#getDetails () } is an instance of { @link ServiceAuthenticationDetails } then { @link ServiceAuthenticationDetails#getServiceUrl () } is used . Otherwise the { @link ServiceProperties#getService () } is used . [CODESPLIT] private String getServiceUrl ( Authentication authentication ) { String serviceUrl ; if ( authentication . getDetails ( ) instanceof ServiceAuthenticationDetails ) { serviceUrl = ( ( ServiceAuthenticationDetails ) authentication . getDetails ( ) ) . getServiceUrl ( ) ; } else if ( serviceProperties == null ) { throw new IllegalStateException ( \"serviceProperties cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails.\" ) ; } else if ( serviceProperties . getService ( ) == null ) { throw new IllegalStateException ( \"serviceProperties.getService() cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails.\" ) ; } else { serviceUrl = serviceProperties . getService ( ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"serviceUrl = \" + serviceUrl ) ; } return serviceUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Template method for retrieving the UserDetails based on the assertion . Default is to call configured userDetailsService and pass the username . Deployers can override this method and retrieve the user based on any criteria they desire . [CODESPLIT] protected UserDetails loadUserByAssertion ( final Assertion assertion ) { final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken ( assertion , \"\" ) ; return this . authenticationUserDetailsService . loadUserDetails ( token ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the repository of client registrations . [CODESPLIT] public OAuth2ClientConfigurer < B > clientRegistrationRepository ( ClientRegistrationRepository clientRegistrationRepository ) { Assert . notNull ( clientRegistrationRepository , \"clientRegistrationRepository cannot be null\" ) ; this . getBuilder ( ) . setSharedObject ( ClientRegistrationRepository . class , clientRegistrationRepository ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the repository for authorized client ( s ) . [CODESPLIT] public OAuth2ClientConfigurer < B > authorizedClientRepository ( OAuth2AuthorizedClientRepository authorizedClientRepository ) { Assert . notNull ( authorizedClientRepository , \"authorizedClientRepository cannot be null\" ) ; this . getBuilder ( ) . setSharedObject ( OAuth2AuthorizedClientRepository . class , authorizedClientRepository ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the service for authorized client ( s ) . [CODESPLIT] public OAuth2ClientConfigurer < B > authorizedClientService ( OAuth2AuthorizedClientService authorizedClientService ) { Assert . notNull ( authorizedClientService , \"authorizedClientService cannot be null\" ) ; this . authorizedClientRepository ( new AuthenticatedPrincipalOAuth2AuthorizedClientRepository ( authorizedClientService ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get s the URL ( i . e . http : // localhost : 123456 ) [CODESPLIT] private String getUrl ( ) { MockWebServer mockWebServer = getSource ( ) ; if ( ! this . started ) { intializeMockWebServer ( mockWebServer ) ; } String url = mockWebServer . url ( \"\" ) . url ( ) . toExternalForm ( ) ; return url . substring ( 0 , url . length ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the WebSphere user name . [CODESPLIT] protected Object getPreAuthenticatedPrincipal ( HttpServletRequest httpRequest ) { Object principal = wasHelper . getCurrentUserName ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"PreAuthenticated WebSphere principal: \" + principal ) ; } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of { [CODESPLIT] public UserDetails loadUserByUsername ( String id ) throws UsernameNotFoundException { UserDetails user = registeredUsers . get ( id ) ; if ( user == null ) { throw new UsernameNotFoundException ( id ) ; } return user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of { [CODESPLIT] public UserDetails loadUserDetails ( OpenIDAuthenticationToken token ) { String id = token . getIdentityUrl ( ) ; CustomUserDetails user = registeredUsers . get ( id ) ; if ( user != null ) { return user ; } String email = null ; String firstName = null ; String lastName = null ; String fullName = null ; List < OpenIDAttribute > attributes = token . getAttributes ( ) ; for ( OpenIDAttribute attribute : attributes ) { if ( attribute . getName ( ) . equals ( \"email\" ) ) { email = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( \"firstname\" ) ) { firstName = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( \"lastname\" ) ) { lastName = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( \"fullname\" ) ) { fullName = attribute . getValues ( ) . get ( 0 ) ; } } if ( fullName == null ) { StringBuilder fullNameBldr = new StringBuilder ( ) ; if ( firstName != null ) { fullNameBldr . append ( firstName ) ; } if ( lastName != null ) { fullNameBldr . append ( \" \" ) . append ( lastName ) ; } fullName = fullNameBldr . toString ( ) ; } user = new CustomUserDetails ( id , DEFAULT_AUTHORITIES ) ; user . setEmail ( email ) ; user . setName ( fullName ) ; registeredUsers . put ( id , user ) ; user = new CustomUserDetails ( id , DEFAULT_AUTHORITIES ) ; user . setEmail ( email ) ; user . setName ( fullName ) ; user . setNewUser ( true ) ; return user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides defaults for the { [CODESPLIT] public Consumer < WebClient . RequestHeadersSpec < ? > > defaultRequest ( ) { return spec -> { spec . attributes ( attrs -> { populateDefaultRequestResponse ( attrs ) ; populateDefaultAuthentication ( attrs ) ; populateDefaultOAuth2AuthorizedClient ( attrs ) ; } ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the { @link ClientRequest#attributes () } to include the { @link OAuth2AuthorizedClient } to be used for providing the Bearer Token . [CODESPLIT] public static Consumer < Map < String , Object > > oauth2AuthorizedClient ( OAuth2AuthorizedClient authorizedClient ) { return attributes -> { if ( authorizedClient == null ) { attributes . remove ( OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME ) ; } else { attributes . put ( OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME , authorizedClient ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the { @link ClientRequest#attributes () } to include the { @link ClientRegistration#getRegistrationId () } to be used to look up the { @link OAuth2AuthorizedClient } . [CODESPLIT] public static Consumer < Map < String , Object > > clientRegistrationId ( String clientRegistrationId ) { return attributes -> attributes . put ( CLIENT_REGISTRATION_ID_ATTR_NAME , clientRegistrationId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the { @link ClientRequest#attributes () } to include the { @link Authentication } used to look up and save the { @link OAuth2AuthorizedClient } . The value is defaulted in { @link ServletOAuth2AuthorizedClientExchangeFilterFunction#defaultRequest () } [CODESPLIT] public static Consumer < Map < String , Object > > authentication ( Authentication authentication ) { return attributes -> attributes . put ( AUTHENTICATION_ATTR_NAME , authentication ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the { @link ClientRequest#attributes () } to include the { @link HttpServletRequest } used to look up and save the { @link OAuth2AuthorizedClient } . The value is defaulted in { @link ServletOAuth2AuthorizedClientExchangeFilterFunction#defaultRequest () } [CODESPLIT] public static Consumer < Map < String , Object > > httpServletRequest ( HttpServletRequest request ) { return attributes -> attributes . put ( HTTP_SERVLET_REQUEST_ATTR_NAME , request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the { @link ClientRequest#attributes () } to include the { @link HttpServletResponse } used to save the { @link OAuth2AuthorizedClient } . The value is defaulted in { @link ServletOAuth2AuthorizedClientExchangeFilterFunction#defaultRequest () } [CODESPLIT] public static Consumer < Map < String , Object > > httpServletResponse ( HttpServletResponse response ) { return attributes -> attributes . put ( HTTP_SERVLET_RESPONSE_ATTR_NAME , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether the user has the given permission ( s ) on the domain object using the ACL configuration . If the domain object is null returns false ( this can always be overridden using a null check in the expression itself ) . [CODESPLIT] public boolean hasPermission ( Authentication authentication , Object domainObject , Object permission ) { if ( domainObject == null ) { return false ; } ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy . getObjectIdentity ( domainObject ) ; return checkPermission ( authentication , objectIdentity , permission ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override protected UserDetails processAutoLoginCookie ( String [ ] cookieTokens , HttpServletRequest request , HttpServletResponse response ) { if ( cookieTokens . length != 3 ) { throw new InvalidCookieException ( \"Cookie token did not contain 3\" + \" tokens, but contained '\" + Arrays . asList ( cookieTokens ) + \"'\" ) ; } long tokenExpiryTime ; try { tokenExpiryTime = new Long ( cookieTokens [ 1 ] ) . longValue ( ) ; } catch ( NumberFormatException nfe ) { throw new InvalidCookieException ( \"Cookie token[1] did not contain a valid number (contained '\" + cookieTokens [ 1 ] + \"')\" ) ; } if ( isTokenExpired ( tokenExpiryTime ) ) { throw new InvalidCookieException ( \"Cookie token[1] has expired (expired on '\" + new Date ( tokenExpiryTime ) + \"'; current time is '\" + new Date ( ) + \"')\" ) ; } // Check the user exists. // Defer lookup until after expiry time checked, to possibly avoid expensive // database call. UserDetails userDetails = getUserDetailsService ( ) . loadUserByUsername ( cookieTokens [ 0 ] ) ; // Check signature of token matches remaining details. // Must do this after user lookup, as we need the DAO-derived password. // If efficiency was a major issue, just add in a UserCache implementation, // but recall that this method is usually only called once per HttpSession - if // the token is valid, // it will cause SecurityContextHolder population, whilst if invalid, will cause // the cookie to be cancelled. String expectedTokenSignature = makeTokenSignature ( tokenExpiryTime , userDetails . getUsername ( ) , userDetails . getPassword ( ) ) ; if ( ! equals ( expectedTokenSignature , cookieTokens [ 2 ] ) ) { throw new InvalidCookieException ( \"Cookie token[2] contained signature '\" + cookieTokens [ 2 ] + \"' but expected '\" + expectedTokenSignature + \"'\" ) ; } return userDetails ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the digital signature to be put in the cookie . Default value is MD5 ( username : tokenExpiryTime : password : key ) [CODESPLIT] protected String makeTokenSignature ( long tokenExpiryTime , String username , String password ) { String data = username + \":\" + tokenExpiryTime + \":\" + password + \":\" + getKey ( ) ; MessageDigest digest ; try { digest = MessageDigest . getInstance ( \"MD5\" ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( \"No MD5 algorithm available!\" ) ; } return new String ( Hex . encode ( digest . digest ( data . getBytes ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the individual byte arrays into one array . [CODESPLIT] public static byte [ ] concatenate ( byte [ ] ... arrays ) { int length = 0 ; for ( byte [ ] array : arrays ) { length += array . length ; } byte [ ] newArray = new byte [ length ] ; int destPos = 0 ; for ( byte [ ] array : arrays ) { System . arraycopy ( array , 0 , newArray , destPos , array . length ) ; destPos += array . length ; } return newArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract a sub array of bytes out of the byte array . [CODESPLIT] public static byte [ ] subArray ( byte [ ] array , int beginIndex , int endIndex ) { int length = endIndex - beginIndex ; byte [ ] subarray = new byte [ length ] ; System . arraycopy ( array , beginIndex , subarray , 0 , length ) ; return subarray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the given array of attributes to Spring Security GrantedAuthorities . [CODESPLIT] public List < GrantedAuthority > getGrantedAuthorities ( Collection < String > attributes ) { ArrayList < GrantedAuthority > gaList = new ArrayList <> ( ) ; for ( String attribute : attributes ) { Collection < GrantedAuthority > c = attributes2grantedAuthoritiesMap . get ( attribute ) ; if ( c != null ) { gaList . addAll ( c ) ; } } gaList . trimToSize ( ) ; return gaList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Preprocess the given map to convert all the values to GrantedAuthority collections [CODESPLIT] private Map < String , Collection < GrantedAuthority > > preProcessMap ( Map < ? , ? > orgMap ) { Map < String , Collection < GrantedAuthority > > result = new HashMap < String , Collection < GrantedAuthority > > ( orgMap . size ( ) ) ; for ( Map . Entry < ? , ? > entry : orgMap . entrySet ( ) ) { Assert . isInstanceOf ( String . class , entry . getKey ( ) , \"attributes2grantedAuthoritiesMap contains non-String objects as keys\" ) ; result . put ( ( String ) entry . getKey ( ) , getGrantedAuthorityCollection ( entry . getValue ( ) ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given value to a collection of Granted Authorities [CODESPLIT] private Collection < GrantedAuthority > getGrantedAuthorityCollection ( Object value ) { Collection < GrantedAuthority > result = new ArrayList <> ( ) ; addGrantedAuthorityCollection ( result , value ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given value to a collection of Granted Authorities adding the result to the given result collection . [CODESPLIT] private void addGrantedAuthorityCollection ( Collection < GrantedAuthority > result , Object value ) { if ( value == null ) { return ; } if ( value instanceof Collection < ? > ) { addGrantedAuthorityCollection ( result , ( Collection < ? > ) value ) ; } else if ( value instanceof Object [ ] ) { addGrantedAuthorityCollection ( result , ( Object [ ] ) value ) ; } else if ( value instanceof String ) { addGrantedAuthorityCollection ( result , ( String ) value ) ; } else if ( value instanceof GrantedAuthority ) { result . add ( ( GrantedAuthority ) value ) ; } else { throw new IllegalArgumentException ( \"Invalid object type: \" + value . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the J2EE user name . [CODESPLIT] protected Object getPreAuthenticatedPrincipal ( HttpServletRequest httpRequest ) { Object principal = httpRequest . getUserPrincipal ( ) == null ? null : httpRequest . getUserPrincipal ( ) . getName ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"PreAuthenticated J2EE principal: \" + principal ) ; } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Similar to { @link #build () } and { @link #getObject () } but checks the state to determine if { @link #build () } needs to be called first . [CODESPLIT] public O getOrBuild ( ) { if ( isUnbuilt ( ) ) { try { return build ( ) ; } catch ( Exception e ) { logger . debug ( \"Failed to perform build. Returning null\" , e ) ; return null ; } } else { return getObject ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a { @link SecurityConfigurerAdapter } to this { @link SecurityBuilder } and invokes { @link SecurityConfigurerAdapter#setBuilder ( SecurityBuilder ) } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < C extends SecurityConfigurerAdapter < O , B > > C apply ( C configurer ) throws Exception { configurer . addObjectPostProcessor ( objectPostProcessor ) ; configurer . setBuilder ( ( B ) this ) ; add ( configurer ) ; return configurer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a { @link SecurityConfigurer } to this { @link SecurityBuilder } overriding any { @link SecurityConfigurer } of the exact same class . Note that object hierarchies are not considered . [CODESPLIT] public < C extends SecurityConfigurer < O , B > > C apply ( C configurer ) throws Exception { add ( configurer ) ; return configurer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets an object that is shared by multiple { @link SecurityConfigurer } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < C > void setSharedObject ( Class < C > sharedType , C object ) { this . sharedObjects . put ( sharedType , object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a shared Object . Note that object heirarchies are not considered . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < C > C getSharedObject ( Class < C > sharedType ) { return ( C ) this . sharedObjects . get ( sharedType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds { @link SecurityConfigurer } ensuring that it is allowed and invoking { @link SecurityConfigurer#init ( SecurityBuilder ) } immediately if necessary . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private < C extends SecurityConfigurer < O , B > > void add ( C configurer ) throws Exception { Assert . notNull ( configurer , \"configurer cannot be null\" ) ; Class < ? extends SecurityConfigurer < O , B > > clazz = ( Class < ? extends SecurityConfigurer < O , B > > ) configurer . getClass ( ) ; synchronized ( configurers ) { if ( buildState . isConfigured ( ) ) { throw new IllegalStateException ( \"Cannot apply \" + configurer + \" to already built object\" ) ; } List < SecurityConfigurer < O , B > > configs = allowConfigurersOfSameType ? this . configurers . get ( clazz ) : null ; if ( configs == null ) { configs = new ArrayList < SecurityConfigurer < O , B > > ( 1 ) ; } configs . add ( configurer ) ; this . configurers . put ( clazz , configs ) ; if ( buildState . isInitializing ( ) ) { this . configurersAddedInInitializing . add ( configurer ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets all the { @link SecurityConfigurer } instances by its class name or an empty List if not found . Note that object hierarchies are not considered . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < C extends SecurityConfigurer < O , B > > List < C > getConfigurers ( Class < C > clazz ) { List < C > configs = ( List < C > ) this . configurers . get ( clazz ) ; if ( configs == null ) { return new ArrayList <> ( ) ; } return new ArrayList <> ( configs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all the { @link SecurityConfigurer } instances by its class name or an empty List if not found . Note that object hierarchies are not considered . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < C extends SecurityConfigurer < O , B > > List < C > removeConfigurers ( Class < C > clazz ) { List < C > configs = ( List < C > ) this . configurers . remove ( clazz ) ; if ( configs == null ) { return new ArrayList <> ( ) ; } return new ArrayList <> ( configs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes and returns the { @link SecurityConfigurer } by its class name or <code > null< / code > if not found . Note that object hierarchies are not considered . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < C extends SecurityConfigurer < O , B > > C removeConfigurer ( Class < C > clazz ) { List < SecurityConfigurer < O , B > > configs = this . configurers . remove ( clazz ) ; if ( configs == null ) { return null ; } if ( configs . size ( ) != 1 ) { throw new IllegalStateException ( \"Only one configurer expected for type \" + clazz + \", but got \" + configs ) ; } return ( C ) configs . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public O objectPostProcessor ( ObjectPostProcessor < Object > objectPostProcessor ) { Assert . notNull ( objectPostProcessor , \"objectPostProcessor cannot be null\" ) ; this . objectPostProcessor = objectPostProcessor ; return ( O ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the build using the { @link SecurityConfigurer } s that have been applied using the following steps : [CODESPLIT] @ Override protected final O doBuild ( ) throws Exception { synchronized ( configurers ) { buildState = BuildState . INITIALIZING ; beforeInit ( ) ; init ( ) ; buildState = BuildState . CONFIGURING ; beforeConfigure ( ) ; configure ( ) ; buildState = BuildState . BUILDING ; O result = performBuild ( ) ; buildState = BuildState . BUILT ; return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] protected Object getDomainObjectInstance ( MethodInvocation invocation ) { Object [ ] args ; Class < ? > [ ] params ; params = invocation . getMethod ( ) . getParameterTypes ( ) ; args = invocation . getArguments ( ) ; for ( int i = 0 ; i < params . length ; i ++ ) { if ( processDomainObjectClass . isAssignableFrom ( params [ i ] ) ) { return args [ i ] ; } } throw new AuthorizationServiceException ( \"MethodInvocation: \" + invocation + \" did not provide any argument of type: \" + processDomainObjectClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . isTrue ( StringUtils . hasText ( loginFormUrl ) && UrlUtils . isValidRedirectUrl ( loginFormUrl ) , \"loginFormUrl must be specified and must be a valid redirect URL\" ) ; if ( useForward && UrlUtils . isAbsoluteUrl ( loginFormUrl ) ) { throw new IllegalArgumentException ( \"useForward must be false if using an absolute loginFormURL\" ) ; } Assert . notNull ( portMapper , \"portMapper must be specified\" ) ; Assert . notNull ( portResolver , \"portResolver must be specified\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the redirect ( or forward ) to the login form URL . [CODESPLIT] public void commence ( HttpServletRequest request , HttpServletResponse response , AuthenticationException authException ) throws IOException , ServletException { String redirectUrl = null ; if ( useForward ) { if ( forceHttps && \"http\" . equals ( request . getScheme ( ) ) ) { // First redirect the current request to HTTPS. // When that request is received, the forward to the login page will be // used. redirectUrl = buildHttpsRedirectUrlForRequest ( request ) ; } if ( redirectUrl == null ) { String loginForm = determineUrlToUseForThisRequest ( request , response , authException ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Server side forward to: \" + loginForm ) ; } RequestDispatcher dispatcher = request . getRequestDispatcher ( loginForm ) ; dispatcher . forward ( request , response ) ; return ; } } else { // redirect to login page. Use https if forceHttps true redirectUrl = buildRedirectUrlToLoginPage ( request , response , authException ) ; } redirectStrategy . sendRedirect ( request , response , redirectUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a URL to redirect the supplied request to HTTPS . Used to redirect the current request to HTTPS before doing a forward to the login page . [CODESPLIT] protected String buildHttpsRedirectUrlForRequest ( HttpServletRequest request ) throws IOException , ServletException { int serverPort = portResolver . getServerPort ( request ) ; Integer httpsPort = portMapper . lookupHttpsPort ( Integer . valueOf ( serverPort ) ) ; if ( httpsPort != null ) { RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder ( ) ; urlBuilder . setScheme ( \"https\" ) ; urlBuilder . setServerName ( request . getServerName ( ) ) ; urlBuilder . setPort ( httpsPort . intValue ( ) ) ; urlBuilder . setContextPath ( request . getContextPath ( ) ) ; urlBuilder . setServletPath ( request . getServletPath ( ) ) ; urlBuilder . setPathInfo ( request . getPathInfo ( ) ) ; urlBuilder . setQuery ( request . getQueryString ( ) ) ; return urlBuilder . getUrl ( ) ; } // Fall through to server-side forward with warning message logger . warn ( \"Unable to redirect to HTTPS as no port mapping found for HTTP port \" + serverPort ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that is suitable for user with traditional AspectJ - code aspects . [CODESPLIT] public Object invoke ( JoinPoint jp , AspectJCallback advisorProceed ) { InterceptorStatusToken token = super . beforeInvocation ( new MethodInvocationAdapter ( jp ) ) ; Object result ; try { result = advisorProceed . proceedWithObject ( ) ; } finally { super . finallyInvocation ( token ) ; } return super . afterInvocation ( token , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the default { @link AccessDecisionVoter } instances used if an { @link AccessDecisionManager } was not specified . [CODESPLIT] @ Override @ SuppressWarnings ( \"rawtypes\" ) final List < AccessDecisionVoter < ? extends Object > > getDecisionVoters ( H http ) { List < AccessDecisionVoter < ? extends Object > > decisionVoters = new ArrayList < AccessDecisionVoter < ? extends Object > > ( ) ; decisionVoters . add ( new RoleVoter ( ) ) ; decisionVoters . add ( new AuthenticatedVoter ( ) ) ; return decisionVoters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a String for specifying a user requires a role . [CODESPLIT] private static String hasRole ( String role ) { Assert . isTrue ( ! role . startsWith ( \"ROLE_\" ) , ( ) -> role + \" should not start with ROLE_ since ROLE_ is automatically prepended when using hasRole. Consider using hasAuthority or access instead.\" ) ; return \"ROLE_\" + role ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a String for specifying that a user requires one of many roles . [CODESPLIT] private static String [ ] hasAnyRole ( String ... roles ) { for ( int i = 0 ; i < roles . length ; i ++ ) { roles [ i ] = \"ROLE_\" + roles [ i ] ; } return roles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the regular expression which will by used to extract the user name from the certificate s Subject DN . <p > It should contain a single group ; for example the default expression CN = ( . * ? ) ( ? : |$ ) matches the common name field . So CN = Jimi Hendrix OU = ... will give a user name of Jimi Hendrix . <p > The matches are case insensitive . So emailAddress = ( . ? ) will match EMAILADDRESS = jimi@hendrix . org CN = ... giving a user name jimi@hendrix . org [CODESPLIT] public void setSubjectDnRegex ( String subjectDnRegex ) { Assert . hasText ( subjectDnRegex , \"Regular expression may not be null or empty\" ) ; subjectDnPattern = Pattern . compile ( subjectDnRegex , Pattern . CASE_INSENSITIVE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Mono < MatchResult > matches ( ServerWebExchange exchange ) { return Mono . defer ( ( ) -> { Map < String , Object > variables = new HashMap <> ( ) ; return Flux . fromIterable ( matchers ) . flatMap ( matcher -> matcher . matches ( exchange ) ) . doOnNext ( matchResult -> variables . putAll ( matchResult . getVariables ( ) ) ) . all ( MatchResult :: isMatch ) . flatMap ( allMatch -> allMatch ? MatchResult . match ( variables ) : MatchResult . notMatch ( ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates the presented cookie data in the token repository using the series id . If the data compares successfully with that in the persistent store a new token is generated and stored with the same series . The corresponding cookie value is set on the response . [CODESPLIT] protected UserDetails processAutoLoginCookie ( String [ ] cookieTokens , HttpServletRequest request , HttpServletResponse response ) { if ( cookieTokens . length != 2 ) { throw new InvalidCookieException ( \"Cookie token did not contain \" + 2 + \" tokens, but contained '\" + Arrays . asList ( cookieTokens ) + \"'\" ) ; } final String presentedSeries = cookieTokens [ 0 ] ; final String presentedToken = cookieTokens [ 1 ] ; PersistentRememberMeToken token = tokenRepository . getTokenForSeries ( presentedSeries ) ; if ( token == null ) { // No series match, so we can't authenticate using this cookie throw new RememberMeAuthenticationException ( \"No persistent token found for series id: \" + presentedSeries ) ; } // We have a match for this user/series combination if ( ! presentedToken . equals ( token . getTokenValue ( ) ) ) { // Token doesn't match series value. Delete all logins for this user and throw // an exception to warn them. tokenRepository . removeUserTokens ( token . getUsername ( ) ) ; throw new CookieTheftException ( messages . getMessage ( \"PersistentTokenBasedRememberMeServices.cookieStolen\" , \"Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.\" ) ) ; } if ( token . getDate ( ) . getTime ( ) + getTokenValiditySeconds ( ) * 1000L < System . currentTimeMillis ( ) ) { throw new RememberMeAuthenticationException ( \"Remember-me login has expired\" ) ; } // Token also matches, so login is valid. Update the token value, keeping the // *same* series number. if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Refreshing persistent login token for user '\" + token . getUsername ( ) + \"', series '\" + token . getSeries ( ) + \"'\" ) ; } PersistentRememberMeToken newToken = new PersistentRememberMeToken ( token . getUsername ( ) , token . getSeries ( ) , generateTokenData ( ) , new Date ( ) ) ; try { tokenRepository . updateToken ( newToken . getSeries ( ) , newToken . getTokenValue ( ) , newToken . getDate ( ) ) ; addCookie ( newToken , request , response ) ; } catch ( Exception e ) { logger . error ( \"Failed to update token: \" , e ) ; throw new RememberMeAuthenticationException ( \"Autologin failed due to data access problem\" ) ; } return getUserDetailsService ( ) . loadUserByUsername ( token . getUsername ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new persistent login token with a new series number stores the data in the persistent token repository and adds the corresponding cookie to the response . [CODESPLIT] protected void onLoginSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication successfulAuthentication ) { String username = successfulAuthentication . getName ( ) ; logger . debug ( \"Creating new persistent login for user \" + username ) ; PersistentRememberMeToken persistentToken = new PersistentRememberMeToken ( username , generateSeriesData ( ) , generateTokenData ( ) , new Date ( ) ) ; try { tokenRepository . createNewToken ( persistentToken ) ; addCookie ( persistentToken , request , response ) ; } catch ( Exception e ) { logger . error ( \"Failed to save persistent token \" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . notNull ( this . userDetailsService , \"userDetailsService must be specified\" ) ; Assert . isTrue ( this . successHandler != null || this . targetUrl != null , \"You must set either a successHandler or the targetUrl\" ) ; if ( this . targetUrl != null ) { Assert . isNull ( this . successHandler , \"You cannot set both successHandler and targetUrl\" ) ; this . successHandler = new SimpleUrlAuthenticationSuccessHandler ( this . targetUrl ) ; } if ( this . failureHandler == null ) { this . failureHandler = this . switchFailureUrl == null ? new SimpleUrlAuthenticationFailureHandler ( ) : new SimpleUrlAuthenticationFailureHandler ( this . switchFailureUrl ) ; } else { Assert . isNull ( this . switchFailureUrl , \"You cannot set both a switchFailureUrl and a failureHandler\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to switch to another user . If the user does not exist or is not active return null . [CODESPLIT] protected Authentication attemptSwitchUser ( HttpServletRequest request ) throws AuthenticationException { UsernamePasswordAuthenticationToken targetUserRequest ; String username = request . getParameter ( this . usernameParameter ) ; if ( username == null ) { username = \"\" ; } if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( \"Attempt to switch to user [\" + username + \"]\" ) ; } UserDetails targetUser = this . userDetailsService . loadUserByUsername ( username ) ; this . userDetailsChecker . check ( targetUser ) ; // OK, create the switch user token targetUserRequest = createSwitchUserToken ( request , targetUser ) ; if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( \"Switch User Token [\" + targetUserRequest + \"]\" ) ; } // publish event if ( this . eventPublisher != null ) { this . eventPublisher . publishEvent ( new AuthenticationSwitchUserEvent ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) , targetUser ) ) ; } return targetUserRequest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to exit from an already switched user . [CODESPLIT] protected Authentication attemptExitUser ( HttpServletRequest request ) throws AuthenticationCredentialsNotFoundException { // need to check to see if the current user has a SwitchUserGrantedAuthority Authentication current = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( null == current ) { throw new AuthenticationCredentialsNotFoundException ( this . messages . getMessage ( \"SwitchUserFilter.noCurrentUser\" , \"No current user associated with this request\" ) ) ; } // check to see if the current user did actual switch to another user // if so, get the original source user so we can switch back Authentication original = getSourceAuthentication ( current ) ; if ( original == null ) { this . logger . debug ( \"Could not find original user Authentication object!\" ) ; throw new AuthenticationCredentialsNotFoundException ( this . messages . getMessage ( \"SwitchUserFilter.noOriginalAuthentication\" , \"Could not find original Authentication object\" ) ) ; } // get the source user details UserDetails originalUser = null ; Object obj = original . getPrincipal ( ) ; if ( ( obj != null ) && obj instanceof UserDetails ) { originalUser = ( UserDetails ) obj ; } // publish event if ( this . eventPublisher != null ) { this . eventPublisher . publishEvent ( new AuthenticationSwitchUserEvent ( current , originalUser ) ) ; } return original ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a switch user token that contains an additional <tt > GrantedAuthority< / tt > that contains the original <code > Authentication< / code > object . [CODESPLIT] private UsernamePasswordAuthenticationToken createSwitchUserToken ( HttpServletRequest request , UserDetails targetUser ) { UsernamePasswordAuthenticationToken targetUserRequest ; // grant an additional authority that contains the original Authentication object // which will be used to 'exit' from the current switched user. Authentication currentAuth ; try { // SEC-1763. Check first if we are already switched. currentAuth = attemptExitUser ( request ) ; } catch ( AuthenticationCredentialsNotFoundException e ) { currentAuth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; } GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority ( this . switchAuthorityRole , currentAuth ) ; // get the original authorities Collection < ? extends GrantedAuthority > orig = targetUser . getAuthorities ( ) ; // Allow subclasses to change the authorities to be granted if ( this . switchUserAuthorityChanger != null ) { orig = this . switchUserAuthorityChanger . modifyGrantedAuthorities ( targetUser , currentAuth , orig ) ; } // add the new switch user authority List < GrantedAuthority > newAuths = new ArrayList <> ( orig ) ; newAuths . add ( switchAuthority ) ; // create the new authentication token targetUserRequest = new UsernamePasswordAuthenticationToken ( targetUser , targetUser . getPassword ( ) , newAuths ) ; // set details targetUserRequest . setDetails ( this . authenticationDetailsSource . buildDetails ( request ) ) ; return targetUserRequest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the original <code > Authentication< / code > object from the current user s granted authorities . A successfully switched user should have a <code > SwitchUserGrantedAuthority< / code > that contains the original source user <code > Authentication< / code > object . [CODESPLIT] private Authentication getSourceAuthentication ( Authentication current ) { Authentication original = null ; // iterate over granted authorities and find the 'switch user' authority Collection < ? extends GrantedAuthority > authorities = current . getAuthorities ( ) ; for ( GrantedAuthority auth : authorities ) { // check for switch user type of authority if ( auth instanceof SwitchUserGrantedAuthority ) { original = ( ( SwitchUserGrantedAuthority ) auth ) . getSource ( ) ; this . logger . debug ( \"Found original switch user granted authority [\" + original + \"]\" ) ; } } return original ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the URL to respond to exit user processing . [CODESPLIT] public void setExitUserUrl ( String exitUserUrl ) { Assert . isTrue ( UrlUtils . isValidRedirectUrl ( exitUserUrl ) , \"exitUserUrl cannot be empty and must be a valid redirect URL\" ) ; this . exitUserMatcher = createMatcher ( exitUserUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the URL to respond to switch user processing . This is a shortcut for { @link #setSwitchUserMatcher ( RequestMatcher ) } [CODESPLIT] public void setSwitchUserUrl ( String switchUserUrl ) { Assert . isTrue ( UrlUtils . isValidRedirectUrl ( switchUserUrl ) , \"switchUserUrl cannot be empty and must be a valid redirect URL\" ) ; this . switchUserMatcher = createMatcher ( switchUserUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the URL to which a user should be redirected if the switch fails . For example this might happen because the account they are attempting to switch to is invalid ( the user doesn t exist account is locked etc ) . <p > If not set an error message will be written to the response . <p > Use { @link #setFailureHandler ( AuthenticationFailureHandler ) failureHandler } instead if you need more customized behaviour . [CODESPLIT] public void setSwitchFailureUrl ( String switchFailureUrl ) { Assert . isTrue ( UrlUtils . isValidRedirectUrl ( switchFailureUrl ) , \"switchFailureUrl must be a valid redirect URL\" ) ; this . switchFailureUrl = switchFailureUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The public index page used for unauthenticated users . [CODESPLIT] @ RequestMapping ( value = \"/hello.htm\" , method = RequestMethod . GET ) public ModelAndView displayPublicIndex ( ) { Contact rnd = contactManager . getRandomContact ( ) ; return new ModelAndView ( \"hello\" , \"contact\" , rnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The index page for an authenticated user . <p > This controller displays a list of all the contacts for which the current user has read or admin permissions . It makes a call to { [CODESPLIT] @ RequestMapping ( value = \"/secure/index.htm\" , method = RequestMethod . GET ) public ModelAndView displayUserContacts ( ) { List < Contact > myContactsList = contactManager . getAll ( ) ; Map < Contact , Boolean > hasDelete = new HashMap <> ( myContactsList . size ( ) ) ; Map < Contact , Boolean > hasAdmin = new HashMap <> ( myContactsList . size ( ) ) ; Authentication user = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; for ( Contact contact : myContactsList ) { hasDelete . put ( contact , Boolean . valueOf ( permissionEvaluator . hasPermission ( user , contact , HAS_DELETE ) ) ) ; hasAdmin . put ( contact , Boolean . valueOf ( permissionEvaluator . hasPermission ( user , contact , HAS_ADMIN ) ) ) ; } Map < String , Object > model = new HashMap <> ( ) ; model . put ( \"contacts\" , myContactsList ) ; model . put ( \"hasDeletePermission\" , hasDelete ) ; model . put ( \"hasAdminPermission\" , hasAdmin ) ; return new ModelAndView ( \"index\" , \"model\" , model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes path parameters from each path segment in the supplied path and truncates sequences of multiple / characters to a single / . [CODESPLIT] private String strip ( String path ) { if ( path == null ) { return null ; } int scIndex = path . indexOf ( ' ' ) ; if ( scIndex < 0 ) { int doubleSlashIndex = path . indexOf ( \"//\" ) ; if ( doubleSlashIndex < 0 ) { // Most likely case, no parameters in any segment and no '//', so no // stripping required return path ; } } StringTokenizer st = new StringTokenizer ( path , \"/\" ) ; StringBuilder stripped = new StringBuilder ( path . length ( ) ) ; if ( path . charAt ( 0 ) == ' ' ) { stripped . append ( ' ' ) ; } while ( st . hasMoreTokens ( ) ) { String segment = st . nextToken ( ) ; scIndex = segment . indexOf ( ' ' ) ; if ( scIndex >= 0 ) { segment = segment . substring ( 0 , scIndex ) ; } stripped . append ( segment ) . append ( ' ' ) ; } // Remove the trailing slash if the original path didn't have one if ( path . charAt ( path . length ( ) - 1 ) != ' ' ) { stripped . deleteCharAt ( stripped . length ( ) - 1 ) ; } return stripped . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the Spring Security Filter Chain [CODESPLIT] @ Bean ( name = AbstractSecurityWebApplicationInitializer . DEFAULT_FILTER_NAME ) public Filter springSecurityFilterChain ( ) throws Exception { boolean hasConfigurers = webSecurityConfigurers != null && ! webSecurityConfigurers . isEmpty ( ) ; if ( ! hasConfigurers ) { WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor . postProcess ( new WebSecurityConfigurerAdapter ( ) { } ) ; webSecurity . apply ( adapter ) ; } return webSecurity . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @code <SecurityConfigurer<FilterChainProxy WebSecurityBuilder > } instances used to create the web configuration . [CODESPLIT] @ Autowired ( required = false ) public void setFilterChainProxySecurityConfigurer ( ObjectPostProcessor < Object > objectPostProcessor , @ Value ( \"#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}\" ) List < SecurityConfigurer < Filter , WebSecurity > > webSecurityConfigurers ) throws Exception { webSecurity = objectPostProcessor . postProcess ( new WebSecurity ( objectPostProcessor ) ) ; if ( debugEnabled != null ) { webSecurity . debug ( debugEnabled ) ; } Collections . sort ( webSecurityConfigurers , AnnotationAwareOrderComparator . INSTANCE ) ; Integer previousOrder = null ; Object previousConfig = null ; for ( SecurityConfigurer < Filter , WebSecurity > config : webSecurityConfigurers ) { Integer order = AnnotationAwareOrderComparator . lookupOrder ( config ) ; if ( previousOrder != null && previousOrder . equals ( order ) ) { throw new IllegalStateException ( \"@Order on WebSecurityConfigurers must be unique. Order of \" + order + \" was already used on \" + previousConfig + \", so it cannot be used on \" + config + \" too.\" ) ; } previousOrder = order ; previousConfig = config ; } for ( SecurityConfigurer < Filter , WebSecurity > webSecurityConfigurer : webSecurityConfigurers ) { webSecurity . apply ( webSecurityConfigurer ) ; } this . webSecurityConfigurers = webSecurityConfigurers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setImportMetadata ( AnnotationMetadata importMetadata ) { Map < String , Object > enableWebSecurityAttrMap = importMetadata . getAnnotationAttributes ( EnableWebSecurity . class . getName ( ) ) ; AnnotationAttributes enableWebSecurityAttrs = AnnotationAttributes . fromMap ( enableWebSecurityAttrMap ) ; debugEnabled = enableWebSecurityAttrs . getBoolean ( \"debug\" ) ; if ( webSecurity != null ) { webSecurity . debug ( debugEnabled ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link MessageSecurityMetadataSource } that uses { @link MessageMatcher } mapped to Spring Expressions . Each entry is considered in order and only the first match is used . [CODESPLIT] public static MessageSecurityMetadataSource createExpressionMessageMetadataSource ( LinkedHashMap < MessageMatcher < ? > , String > matcherToExpression , SecurityExpressionHandler < Message < Object > > handler ) { LinkedHashMap < MessageMatcher < ? > , Collection < ConfigAttribute > > matcherToAttrs = new LinkedHashMap < MessageMatcher < ? > , Collection < ConfigAttribute > > ( ) ; for ( Map . Entry < MessageMatcher < ? > , String > entry : matcherToExpression . entrySet ( ) ) { MessageMatcher < ? > matcher = entry . getKey ( ) ; String rawExpression = entry . getValue ( ) ; Expression expression = handler . getExpressionParser ( ) . parseExpression ( rawExpression ) ; ConfigAttribute attribute = new MessageExpressionConfigAttribute ( expression ) ; matcherToAttrs . put ( matcher , Arrays . asList ( attribute ) ) ; } return new DefaultMessageSecurityMetadataSource ( matcherToAttrs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode and validate the JWT from its compact claims representation format [CODESPLIT] @ Override public Jwt decode ( String token ) throws JwtException { JWT jwt = parse ( token ) ; if ( jwt instanceof SignedJWT ) { Jwt createdJwt = createJwt ( token , jwt ) ; return validateJwt ( createdJwt ) ; } throw new JwtException ( \"Unsupported algorithm of \" + jwt . getHeader ( ) . getAlgorithm ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void onAuthenticationFailure ( HttpServletRequest request , HttpServletResponse response , AuthenticationException exception ) throws IOException , ServletException { for ( Map . Entry < Class < ? extends AuthenticationException > , AuthenticationFailureHandler > entry : handlers . entrySet ( ) ) { Class < ? extends AuthenticationException > handlerMappedExceptionClass = entry . getKey ( ) ; if ( handlerMappedExceptionClass . isAssignableFrom ( exception . getClass ( ) ) ) { AuthenticationFailureHandler handler = entry . getValue ( ) ; handler . onAuthenticationFailure ( request , response , exception ) ; return ; } } defaultHandler . onAuthenticationFailure ( request , response , exception ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through all <code > AccessDecisionVoter< / code > s and ensures each can support the presented class . <p > If one or more voters cannot support the presented class <code > false< / code > is returned . [CODESPLIT] public boolean supports ( Class < ? > clazz ) { for ( AccessDecisionVoter voter : this . decisionVoters ) { if ( ! voter . supports ( clazz ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Mono < Map < String , Object > > introspect ( String token ) { return Mono . just ( token ) . flatMap ( this :: makeRequest ) . flatMap ( this :: adaptToNimbusResponse ) . map ( this :: parseNimbusResponse ) . map ( this :: castToNimbusSuccess ) . doOnNext ( response -> validate ( token , response ) ) . map ( this :: convertClaimsSet ) . onErrorMap ( e -> ! ( e instanceof OAuth2IntrospectionException ) , this :: onError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an authorization decision by considering all &lt ; authorize&gt ; tag attributes . The following are valid combinations of attributes : <ul > <li > access< / li > <li > url method< / li > < / ul > The above combinations are mutually exclusive and evaluated in the given order . [CODESPLIT] public boolean authorize ( ) throws IOException { boolean isAuthorized ; if ( StringUtils . hasText ( getAccess ( ) ) ) { isAuthorized = authorizeUsingAccessExpression ( ) ; } else if ( StringUtils . hasText ( getUrl ( ) ) ) { isAuthorized = authorizeUsingUrlCheck ( ) ; } else { isAuthorized = false ; } return isAuthorized ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an authorization decision based on a Spring EL expression . See the Expression - Based Access Control chapter in Spring Security for details on what expressions can be used . [CODESPLIT] public boolean authorizeUsingAccessExpression ( ) throws IOException { if ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) == null ) { return false ; } SecurityExpressionHandler < FilterInvocation > handler = getExpressionHandler ( ) ; Expression accessExpression ; try { accessExpression = handler . getExpressionParser ( ) . parseExpression ( getAccess ( ) ) ; } catch ( ParseException e ) { IOException ioException = new IOException ( ) ; ioException . initCause ( e ) ; throw ioException ; } return ExpressionUtils . evaluateAsBoolean ( accessExpression , createExpressionEvaluationContext ( handler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows the { [CODESPLIT] protected EvaluationContext createExpressionEvaluationContext ( SecurityExpressionHandler < FilterInvocation > handler ) { FilterInvocation f = new FilterInvocation ( getRequest ( ) , getResponse ( ) , new FilterChain ( ) { public void doFilter ( ServletRequest request , ServletResponse response ) throws IOException , ServletException { throw new UnsupportedOperationException ( ) ; } } ) ; return handler . createEvaluationContext ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) , f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an authorization decision based on the URL and HTTP method attributes . True is returned if the user is allowed to access the given URL as defined . [CODESPLIT] public boolean authorizeUsingUrlCheck ( ) throws IOException { String contextPath = ( ( HttpServletRequest ) getRequest ( ) ) . getContextPath ( ) ; Authentication currentUser = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; return getPrivilegeEvaluator ( ) . isAllowed ( contextPath , getUrl ( ) , getMethod ( ) , currentUser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ------------- Private helper methods ----------------- [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) private SecurityExpressionHandler < FilterInvocation > getExpressionHandler ( ) throws IOException { ApplicationContext appContext = SecurityWebApplicationContextUtils . findRequiredWebApplicationContext ( getServletContext ( ) ) ; Map < String , SecurityExpressionHandler > handlers = appContext . getBeansOfType ( SecurityExpressionHandler . class ) ; for ( SecurityExpressionHandler h : handlers . values ( ) ) { if ( FilterInvocation . class . equals ( GenericTypeResolver . resolveTypeArgument ( h . getClass ( ) , SecurityExpressionHandler . class ) ) ) { return h ; } } throw new IOException ( \"No visible WebSecurityExpressionHandler instance could be found in the application \" + \"context. There must be at least one in order to support expressions in JSP 'authorize' tags.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method construct { [CODESPLIT] @ Override public UsernamePasswordAuthenticationToken deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException , JsonProcessingException { UsernamePasswordAuthenticationToken token = null ; ObjectMapper mapper = ( ObjectMapper ) jp . getCodec ( ) ; JsonNode jsonNode = mapper . readTree ( jp ) ; Boolean authenticated = readJsonNode ( jsonNode , \"authenticated\" ) . asBoolean ( ) ; JsonNode principalNode = readJsonNode ( jsonNode , \"principal\" ) ; Object principal = null ; if ( principalNode . isObject ( ) ) { principal = mapper . readValue ( principalNode . traverse ( mapper ) , Object . class ) ; } else { principal = principalNode . asText ( ) ; } JsonNode credentialsNode = readJsonNode ( jsonNode , \"credentials\" ) ; Object credentials ; if ( credentialsNode . isNull ( ) || credentialsNode . isMissingNode ( ) ) { credentials = null ; } else { credentials = credentialsNode . asText ( ) ; } List < GrantedAuthority > authorities = mapper . readValue ( readJsonNode ( jsonNode , \"authorities\" ) . traverse ( mapper ) , new TypeReference < List < GrantedAuthority > > ( ) { } ) ; if ( authenticated ) { token = new UsernamePasswordAuthenticationToken ( principal , credentials , authorities ) ; } else { token = new UsernamePasswordAuthenticationToken ( principal , credentials ) ; } JsonNode detailsNode = readJsonNode ( jsonNode , \"details\" ) ; if ( detailsNode . isNull ( ) || detailsNode . isMissingNode ( ) ) { token . setDetails ( null ) ; } else { token . setDetails ( detailsNode ) ; } return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If available initializes the { @link DefaultLoginPageGeneratingFilter } shared object . [CODESPLIT] private void initDefaultLoginFilter ( H http ) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http . getSharedObject ( DefaultLoginPageGeneratingFilter . class ) ; if ( loginPageGeneratingFilter != null ) { loginPageGeneratingFilter . setRememberMeParameter ( getRememberMeParameter ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] private RememberMeServices getRememberMeServices ( H http , String key ) throws Exception { if ( this . rememberMeServices != null ) { if ( this . rememberMeServices instanceof LogoutHandler && this . logoutHandler == null ) { this . logoutHandler = ( LogoutHandler ) this . rememberMeServices ; } return this . rememberMeServices ; } AbstractRememberMeServices tokenRememberMeServices = createRememberMeServices ( http , key ) ; tokenRememberMeServices . setParameter ( this . rememberMeParameter ) ; tokenRememberMeServices . setCookieName ( this . rememberMeCookieName ) ; if ( this . rememberMeCookieDomain != null ) { tokenRememberMeServices . setCookieDomain ( this . rememberMeCookieDomain ) ; } if ( this . tokenValiditySeconds != null ) { tokenRememberMeServices . setTokenValiditySeconds ( this . tokenValiditySeconds ) ; } if ( this . useSecureCookie != null ) { tokenRememberMeServices . setUseSecureCookie ( this . useSecureCookie ) ; } if ( this . alwaysRemember != null ) { tokenRememberMeServices . setAlwaysRemember ( this . alwaysRemember ) ; } tokenRememberMeServices . afterPropertiesSet ( ) ; this . logoutHandler = tokenRememberMeServices ; this . rememberMeServices = tokenRememberMeServices ; return tokenRememberMeServices ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link RememberMeServices } to use when none is provided . The result is either { @link PersistentTokenRepository } ( if a { @link PersistentTokenRepository } is specified else { @link TokenBasedRememberMeServices } . [CODESPLIT] private AbstractRememberMeServices createRememberMeServices ( H http , String key ) throws Exception { return this . tokenRepository == null ? createTokenBasedRememberMeServices ( http , key ) : createPersistentRememberMeServices ( http , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link TokenBasedRememberMeServices } [CODESPLIT] private AbstractRememberMeServices createTokenBasedRememberMeServices ( H http , String key ) { UserDetailsService userDetailsService = getUserDetailsService ( http ) ; return new TokenBasedRememberMeServices ( key , userDetailsService ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link PersistentTokenBasedRememberMeServices } [CODESPLIT] private AbstractRememberMeServices createPersistentRememberMeServices ( H http , String key ) { UserDetailsService userDetailsService = getUserDetailsService ( http ) ; return new PersistentTokenBasedRememberMeServices ( key , userDetailsService , this . tokenRepository ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link UserDetailsService } to use . Either the explicitly configure { @link UserDetailsService } from { @link #userDetailsService ( UserDetailsService ) } or a shared object from { @link HttpSecurity#getSharedObject ( Class ) } . [CODESPLIT] private UserDetailsService getUserDetailsService ( H http ) { if ( this . userDetailsService == null ) { this . userDetailsService = http . getSharedObject ( UserDetailsService . class ) ; } if ( this . userDetailsService == null ) { throw new IllegalStateException ( \"userDetailsService cannot be null. Invoke \" + RememberMeConfigurer . class . getSimpleName ( ) + \"#userDetailsService(UserDetailsService) or see its javadoc for alternative approaches.\" ) ; } return this . userDetailsService ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the strategy used for converting from a { [CODESPLIT] @ Deprecated public void setAuthenticationConverter ( Function < ServerWebExchange , Mono < Authentication > > authenticationConverter ) { Assert . notNull ( authenticationConverter , \"authenticationConverter cannot be null\" ) ; setServerAuthenticationConverter ( authenticationConverter :: apply ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . notNull ( mutableAclService , \"mutableAclService required\" ) ; Assert . notNull ( template , \"dataSource required\" ) ; Assert . notNull ( tt , \"platformTransactionManager required\" ) ; // Set a user account that will initially own all the created data Authentication authRequest = new UsernamePasswordAuthenticationToken ( \"rod\" , \"koala\" , AuthorityUtils . createAuthorityList ( \"ROLE_IGNORED\" ) ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( authRequest ) ; try { template . execute ( \"DROP TABLE CONTACTS\" ) ; template . execute ( \"DROP TABLE AUTHORITIES\" ) ; template . execute ( \"DROP TABLE USERS\" ) ; template . execute ( \"DROP TABLE ACL_ENTRY\" ) ; template . execute ( \"DROP TABLE ACL_OBJECT_IDENTITY\" ) ; template . execute ( \"DROP TABLE ACL_CLASS\" ) ; template . execute ( \"DROP TABLE ACL_SID\" ) ; } catch ( Exception e ) { System . out . println ( \"Failed to drop tables: \" + e . getMessage ( ) ) ; } template . execute ( \"CREATE TABLE ACL_SID(\" + \"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,\" + \"PRINCIPAL BOOLEAN NOT NULL,\" + \"SID VARCHAR_IGNORECASE(100) NOT NULL,\" + \"CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));\" ) ; template . execute ( \"CREATE TABLE ACL_CLASS(\" + \"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,\" + \"CLASS VARCHAR_IGNORECASE(100) NOT NULL,\" + \"CLASS_ID_TYPE VARCHAR_IGNORECASE(100),\" + \"CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));\" ) ; template . execute ( \"CREATE TABLE ACL_OBJECT_IDENTITY(\" + \"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,\" + \"OBJECT_ID_CLASS BIGINT NOT NULL,\" + \"OBJECT_ID_IDENTITY VARCHAR_IGNORECASE(36) NOT NULL,\" + \"PARENT_OBJECT BIGINT,\" + \"OWNER_SID BIGINT,\" + \"ENTRIES_INHERITING BOOLEAN NOT NULL,\" + \"CONSTRAINT UNIQUE_UK_3 UNIQUE(OBJECT_ID_CLASS,OBJECT_ID_IDENTITY),\" + \"CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID),\" + \"CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID),\" + \"CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));\" ) ; template . execute ( \"CREATE TABLE ACL_ENTRY(\" + \"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,\" + \"ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL,\" + \"MASK INTEGER NOT NULL,GRANTING BOOLEAN NOT NULL,AUDIT_SUCCESS BOOLEAN NOT NULL,\" + \"AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER),\" + \"CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID),\" + \"CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));\" ) ; template . execute ( \"CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL);\" ) ; template . execute ( \"CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));\" ) ; template . execute ( \"CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);\" ) ; template . execute ( \"CREATE TABLE CONTACTS(ID BIGINT NOT NULL PRIMARY KEY, CONTACT_NAME VARCHAR_IGNORECASE(50) NOT NULL, EMAIL VARCHAR_IGNORECASE(50) NOT NULL)\" ) ; /*\n\t\t * Passwords encoded using MD5, NOT in Base64 format, with null as salt Encoded\n\t\t * password for rod is \"koala\" Encoded password for dianne is \"emu\" Encoded\n\t\t * password for scott is \"wombat\" Encoded password for peter is \"opal\" (but user\n\t\t * is disabled) Encoded password for bill is \"wombat\" Encoded password for bob is\n\t\t * \"wombat\" Encoded password for jane is \"wombat\"\n\t\t */ template . execute ( \"INSERT INTO USERS VALUES('rod','$2a$10$75pBjapg4Nl8Pzd.3JRnUe7PDJmk9qBGwNEJDAlA3V.dEJxcDKn5O',TRUE);\" ) ; template . execute ( \"INSERT INTO USERS VALUES('dianne','$2a$04$bCMEyxrdF/7sgfUiUJ6Ose2vh9DAMaVBldS1Bw2fhi1jgutZrr9zm',TRUE);\" ) ; template . execute ( \"INSERT INTO USERS VALUES('scott','$2a$06$eChwvzAu3TSexnC3ynw4LOSw1qiEbtNItNeYv5uI40w1i3paoSfLu',TRUE);\" ) ; template . execute ( \"INSERT INTO USERS VALUES('peter','$2a$04$8.H8bCMROLF4CIgd7IpeQ.tcBXLP5w8iplO0n.kCIkISwrIgX28Ii',FALSE);\" ) ; template . execute ( \"INSERT INTO USERS VALUES('bill','$2a$04$8.H8bCMROLF4CIgd7IpeQ.3khQlPVNWbp8kzSQqidQHGFurim7P8O',TRUE);\" ) ; template . execute ( \"INSERT INTO USERS VALUES('bob','$2a$06$zMgxlMf01SfYNcdx7n4NpeFlAGU8apCETz/i2C7VlYWu6IcNyn4Ay',TRUE);\" ) ; template . execute ( \"INSERT INTO USERS VALUES('jane','$2a$05$ZrdS7yMhCZ1J.AAidXZhCOxdjD8LO/dhlv4FJzkXA6xh9gdEbBT/u',TRUE);\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('rod','ROLE_SUPERVISOR');\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');\" ) ; template . execute ( \"INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (1, 'John Smith', 'john@somewhere.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (2, 'Michael Citizen', 'michael@xyz.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (3, 'Joe Bloggs', 'joe@demo.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (4, 'Karen Sutherland', 'karen@sutherland.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (5, 'Mitchell Howard', 'mitchell@abcdef.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (6, 'Rose Costas', 'rose@xyz.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (7, 'Amanda Smith', 'amanda@abcdef.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (8, 'Cindy Smith', 'cindy@smith.com');\" ) ; template . execute ( \"INSERT INTO contacts VALUES (9, 'Jonathan Citizen', 'jonathan@xyz.com');\" ) ; for ( int i = 10 ; i < createEntities ; i ++ ) { String [ ] person = selectPerson ( ) ; template . execute ( \"INSERT INTO contacts VALUES (\" + i + \", '\" + person [ 2 ] + \"', '\" + person [ 0 ] . toLowerCase ( ) + \"@\" + person [ 1 ] . toLowerCase ( ) + \".com');\" ) ; } // Create acl_object_identity rows (and also acl_class rows as needed for ( int i = 1 ; i < createEntities ; i ++ ) { final ObjectIdentity objectIdentity = new ObjectIdentityImpl ( Contact . class , Long . valueOf ( i ) ) ; tt . execute ( new TransactionCallback < Object > ( ) { public Object doInTransaction ( TransactionStatus arg0 ) { mutableAclService . createAcl ( objectIdentity ) ; return null ; } } ) ; } // Now grant some permissions grantPermissions ( 1 , \"rod\" , BasePermission . ADMINISTRATION ) ; grantPermissions ( 2 , \"rod\" , BasePermission . READ ) ; grantPermissions ( 3 , \"rod\" , BasePermission . READ ) ; grantPermissions ( 3 , \"rod\" , BasePermission . WRITE ) ; grantPermissions ( 3 , \"rod\" , BasePermission . DELETE ) ; grantPermissions ( 4 , \"rod\" , BasePermission . ADMINISTRATION ) ; grantPermissions ( 4 , \"dianne\" , BasePermission . ADMINISTRATION ) ; grantPermissions ( 4 , \"scott\" , BasePermission . READ ) ; grantPermissions ( 5 , \"dianne\" , BasePermission . ADMINISTRATION ) ; grantPermissions ( 5 , \"dianne\" , BasePermission . READ ) ; grantPermissions ( 6 , \"dianne\" , BasePermission . READ ) ; grantPermissions ( 6 , \"dianne\" , BasePermission . WRITE ) ; grantPermissions ( 6 , \"dianne\" , BasePermission . DELETE ) ; grantPermissions ( 6 , \"scott\" , BasePermission . READ ) ; grantPermissions ( 7 , \"scott\" , BasePermission . ADMINISTRATION ) ; grantPermissions ( 8 , \"dianne\" , BasePermission . ADMINISTRATION ) ; grantPermissions ( 8 , \"dianne\" , BasePermission . READ ) ; grantPermissions ( 8 , \"scott\" , BasePermission . READ ) ; grantPermissions ( 9 , \"scott\" , BasePermission . ADMINISTRATION ) ; grantPermissions ( 9 , \"scott\" , BasePermission . READ ) ; grantPermissions ( 9 , \"scott\" , BasePermission . WRITE ) ; grantPermissions ( 9 , \"scott\" , BasePermission . DELETE ) ; // Now expressly change the owner of the first ten contacts // We have to do this last, because \"rod\" owns all of them (doing it sooner would // prevent ACL updates) // Note that ownership has no impact on permissions - they're separate (ownership // only allows ACl editing) changeOwner ( 5 , \"dianne\" ) ; changeOwner ( 6 , \"dianne\" ) ; changeOwner ( 7 , \"scott\" ) ; changeOwner ( 8 , \"dianne\" ) ; changeOwner ( 9 , \"scott\" ) ; String [ ] users = { \"bill\" , \"bob\" , \"jane\" } ; // don't want to mess around with // consistent sample data Permission [ ] permissions = { BasePermission . ADMINISTRATION , BasePermission . READ , BasePermission . DELETE } ; for ( int i = 10 ; i < createEntities ; i ++ ) { String user = users [ rnd . nextInt ( users . length ) ] ; Permission permission = permissions [ rnd . nextInt ( permissions . length ) ] ; grantPermissions ( i , user , permission ) ; String user2 = users [ rnd . nextInt ( users . length ) ] ; Permission permission2 = permissions [ rnd . nextInt ( permissions . length ) ] ; grantPermissions ( i , user2 , permission2 ) ; } SecurityContextHolder . clearContext ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies roles to use map from the { @link HttpServletRequest } to the { @link UserDetails } . If { @link HttpServletRequest#isUserInRole ( String ) } returns true the role is added to the { @link UserDetails } . This method is the equivalent of invoking { @link #mappableAuthorities ( Set ) } . Multiple invocations of { @link #mappableAuthorities ( String ... ) } will override previous invocations . [CODESPLIT] public JeeConfigurer < H > mappableAuthorities ( String ... mappableRoles ) { this . mappableRoles . clear ( ) ; for ( String role : mappableRoles ) { this . mappableRoles . add ( role ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates a { @link PreAuthenticatedAuthenticationProvider } into { @link HttpSecurity#authenticationProvider ( org . springframework . security . authentication . AuthenticationProvider ) } and a { @link Http403ForbiddenEntryPoint } into { @link HttpSecurityBuilder#setSharedObject ( Class Object ) } [CODESPLIT] @ Override public void init ( H http ) throws Exception { PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider ( ) ; authenticationProvider . setPreAuthenticatedUserDetailsService ( getUserDetailsService ( ) ) ; authenticationProvider = postProcess ( authenticationProvider ) ; // @formatter:off http . authenticationProvider ( authenticationProvider ) . setSharedObject ( AuthenticationEntryPoint . class , new Http403ForbiddenEntryPoint ( ) ) ; // @formatter:on }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] private J2eePreAuthenticatedProcessingFilter getFilter ( AuthenticationManager authenticationManager ) { if ( j2eePreAuthenticatedProcessingFilter == null ) { j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter ( ) ; j2eePreAuthenticatedProcessingFilter . setAuthenticationManager ( authenticationManager ) ; j2eePreAuthenticatedProcessingFilter . setAuthenticationDetailsSource ( createWebAuthenticationDetailsSource ( ) ) ; j2eePreAuthenticatedProcessingFilter = postProcess ( j2eePreAuthenticatedProcessingFilter ) ; } return j2eePreAuthenticatedProcessingFilter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource } to set on the { @link J2eePreAuthenticatedProcessingFilter } . It is populated with a { @link SimpleMappableAttributesRetriever } . [CODESPLIT] private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource createWebAuthenticationDetailsSource ( ) { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource detailsSource = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource ( ) ; SimpleMappableAttributesRetriever rolesRetriever = new SimpleMappableAttributesRetriever ( ) ; rolesRetriever . setMappableAttributes ( mappableRoles ) ; detailsSource . setMappableRolesRetriever ( rolesRetriever ) ; detailsSource = postProcess ( detailsSource ) ; return detailsSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void writeHeaders ( HttpServletRequest request , HttpServletResponse response ) { if ( this . requestMatcher . matches ( request ) ) { this . delegateHeaderWriter . writeHeaders ( request , response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { @link HeaderWriter } instance [CODESPLIT] public HeadersConfigurer < H > addHeaderWriter ( HeaderWriter headerWriter ) { Assert . notNull ( headerWriter , \"headerWriter cannot be null\" ) ; this . headerWriters . add ( headerWriter ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears all of the default headers from the response . After doing so one can add headers back . For example if you only want to use Spring Security s cache control you can use the following : [CODESPLIT] public HeadersConfigurer < H > defaultsDisabled ( ) { contentTypeOptions . disable ( ) ; xssProtection . disable ( ) ; cacheControl . disable ( ) ; hsts . disable ( ) ; frameOptions . disable ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link HeaderWriter } [CODESPLIT] private HeaderWriterFilter createHeaderWriterFilter ( ) { List < HeaderWriter > writers = getHeaderWriters ( ) ; if ( writers . isEmpty ( ) ) { throw new IllegalStateException ( \"Headers security is enabled, but no headers will be added. Either add headers or disable headers security\" ) ; } HeaderWriterFilter headersFilter = new HeaderWriterFilter ( writers ) ; headersFilter = postProcess ( headersFilter ) ; return headersFilter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link HeaderWriter } instances and possibly initializes with the defaults . [CODESPLIT] private List < HeaderWriter > getHeaderWriters ( ) { List < HeaderWriter > writers = new ArrayList <> ( ) ; addIfNotNull ( writers , contentTypeOptions . writer ) ; addIfNotNull ( writers , xssProtection . writer ) ; addIfNotNull ( writers , cacheControl . writer ) ; addIfNotNull ( writers , hsts . writer ) ; addIfNotNull ( writers , frameOptions . writer ) ; addIfNotNull ( writers , hpkp . writer ) ; addIfNotNull ( writers , contentSecurityPolicy . writer ) ; addIfNotNull ( writers , referrerPolicy . writer ) ; addIfNotNull ( writers , featurePolicy . writer ) ; writers . addAll ( headerWriters ) ; return writers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a { [CODESPLIT] public void registerAfter ( Class < ? extends Filter > filter , Class < ? extends Filter > afterFilter ) { Integer position = getOrder ( afterFilter ) ; if ( position == null ) { throw new IllegalArgumentException ( \"Cannot register after unregistered Filter \" + afterFilter ) ; } put ( filter , position + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a { [CODESPLIT] public void registerAt ( Class < ? extends Filter > filter , Class < ? extends Filter > atFilter ) { Integer position = getOrder ( atFilter ) ; if ( position == null ) { throw new IllegalArgumentException ( \"Cannot register after unregistered Filter \" + atFilter ) ; } put ( filter , position ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a { [CODESPLIT] public void registerBefore ( Class < ? extends Filter > filter , Class < ? extends Filter > beforeFilter ) { Integer position = getOrder ( beforeFilter ) ; if ( position == null ) { throw new IllegalArgumentException ( \"Cannot register after unregistered Filter \" + beforeFilter ) ; } put ( filter , position - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the order of a particular { @link Filter } class taking into consideration superclasses . [CODESPLIT] private Integer getOrder ( Class < ? > clazz ) { while ( clazz != null ) { Integer result = filterToOrder . get ( clazz . getName ( ) ) ; if ( result != null ) { return result ; } clazz = clazz . getSuperclass ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the authorities [CODESPLIT] @ Override public Collection < GrantedAuthority > convert ( Jwt jwt ) { return getScopes ( jwt ) . stream ( ) . map ( authority -> SCOPE_AUTHORITY_PREFIX + authority ) . map ( SimpleGrantedAuthority :: new ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the scopes from a { [CODESPLIT] private Collection < String > getScopes ( Jwt jwt ) { for ( String attributeName : WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES ) { Object scopes = jwt . getClaims ( ) . get ( attributeName ) ; if ( scopes instanceof String ) { if ( StringUtils . hasText ( ( String ) scopes ) ) { return Arrays . asList ( ( ( String ) scopes ) . split ( \" \" ) ) ; } else { return Collections . emptyList ( ) ; } } else if ( scopes instanceof Collection ) { return ( Collection < String > ) scopes ; } } return Collections . emptyList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows providing a parent { @link AuthenticationManager } that will be tried if this { @link AuthenticationManager } was unable to attempt to authenticate the provided { @link Authentication } . [CODESPLIT] public AuthenticationManagerBuilder parentAuthenticationManager ( AuthenticationManager authenticationManager ) { if ( authenticationManager instanceof ProviderManager ) { eraseCredentials ( ( ( ProviderManager ) authenticationManager ) . isEraseCredentialsAfterAuthentication ( ) ) ; } this . parentAuthenticationManager = authenticationManager ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add authentication based upon the custom { @link UserDetailsService } that is passed in . It then returns a { @link DaoAuthenticationConfigurer } to allow customization of the authentication . [CODESPLIT] public < T extends UserDetailsService > DaoAuthenticationConfigurer < AuthenticationManagerBuilder , T > userDetailsService ( T userDetailsService ) throws Exception { this . defaultUserDetailsService = userDetailsService ; return apply ( new DaoAuthenticationConfigurer <> ( userDetailsService ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Captures the { @link UserDetailsService } from any { @link UserDetailsAwareConfigurer } . [CODESPLIT] private < C extends UserDetailsAwareConfigurer < AuthenticationManagerBuilder , ? extends UserDetailsService > > C apply ( C configurer ) throws Exception { this . defaultUserDetailsService = configurer . getUserDetailsService ( ) ; return ( C ) super . apply ( configurer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a new token [CODESPLIT] @ Override public CsrfToken generateToken ( HttpServletRequest request ) { return wrap ( request , this . delegate . generateToken ( request ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does nothing if the { [CODESPLIT] @ Override public void saveToken ( CsrfToken token , HttpServletRequest request , HttpServletResponse response ) { if ( token == null ) { this . delegate . saveToken ( token , request , response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays the permission admin page for a particular contact . [CODESPLIT] @ RequestMapping ( value = \"/secure/adminPermission.htm\" , method = RequestMethod . GET ) public ModelAndView displayAdminPage ( @ RequestParam ( \"contactId\" ) int contactId ) { Contact contact = contactManager . getById ( Long . valueOf ( contactId ) ) ; Acl acl = aclService . readAclById ( new ObjectIdentityImpl ( contact ) ) ; Map < String , Object > model = new HashMap <> ( ) ; model . put ( \"contact\" , contact ) ; model . put ( \"acl\" , acl ) ; return new ModelAndView ( \"adminPermission\" , \"model\" , model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Displays the add permission page for a contact . [CODESPLIT] @ RequestMapping ( value = \"/secure/addPermission.htm\" , method = RequestMethod . GET ) public ModelAndView displayAddPermissionPageForContact ( @ RequestParam ( \"contactId\" ) long contactId ) { Contact contact = contactManager . getById ( contactId ) ; AddPermission addPermission = new AddPermission ( ) ; addPermission . setContact ( contact ) ; Map < String , Object > model = new HashMap <> ( ) ; model . put ( \"addPermission\" , addPermission ) ; model . put ( \"recipients\" , listRecipients ( ) ) ; model . put ( \"permissions\" , listPermissions ( ) ) ; return new ModelAndView ( \"addPermission\" , model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles submission of the add permission form . [CODESPLIT] @ RequestMapping ( value = \"/secure/addPermission.htm\" , method = RequestMethod . POST ) public String addPermission ( AddPermission addPermission , BindingResult result , ModelMap model ) { addPermissionValidator . validate ( addPermission , result ) ; if ( result . hasErrors ( ) ) { model . put ( \"recipients\" , listRecipients ( ) ) ; model . put ( \"permissions\" , listPermissions ( ) ) ; return \"addPermission\" ; } PrincipalSid sid = new PrincipalSid ( addPermission . getRecipient ( ) ) ; Permission permission = permissionFactory . buildFromMask ( addPermission . getPermission ( ) ) ; try { contactManager . addPermission ( addPermission . getContact ( ) , sid , permission ) ; } catch ( DataAccessException existingPermission ) { existingPermission . printStackTrace ( ) ; result . rejectValue ( \"recipient\" , \"err.recipientExistsForContact\" , \"Addition failure.\" ) ; model . put ( \"recipients\" , listRecipients ( ) ) ; model . put ( \"permissions\" , listPermissions ( ) ) ; return \"addPermission\" ; } return \"redirect:/secure/index.htm\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes a permission [CODESPLIT] @ RequestMapping ( value = \"/secure/deletePermission.htm\" ) public ModelAndView deletePermission ( @ RequestParam ( \"contactId\" ) long contactId , @ RequestParam ( \"sid\" ) String sid , @ RequestParam ( \"permission\" ) int mask ) { Contact contact = contactManager . getById ( contactId ) ; Sid sidObject = new PrincipalSid ( sid ) ; Permission permission = permissionFactory . buildFromMask ( mask ) ; contactManager . deletePermission ( contact , sidObject , permission ) ; Map < String , Object > model = new HashMap <> ( ) ; model . put ( \"contact\" , contact ) ; model . put ( \"sid\" , sidObject ) ; model . put ( \"permission\" , permission ) ; return new ModelAndView ( \"deletePermission\" , \"model\" , model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prefixes role with defaultRolePrefix if defaultRolePrefix is non - null and if role does not already start with defaultRolePrefix . [CODESPLIT] private static String getRoleWithDefaultPrefix ( String defaultRolePrefix , String role ) { if ( role == null ) { return role ; } if ( defaultRolePrefix == null || defaultRolePrefix . length ( ) == 0 ) { return role ; } if ( role . startsWith ( defaultRolePrefix ) ) { return role ; } return defaultRolePrefix + role ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . notNull ( this . securityMetadataSource , \"securityMetadataSource must be specified\" ) ; Assert . notNull ( this . channelDecisionManager , \"channelDecisionManager must be specified\" ) ; Collection < ConfigAttribute > attrDefs = this . securityMetadataSource . getAllConfigAttributes ( ) ; if ( attrDefs == null ) { if ( this . logger . isWarnEnabled ( ) ) { this . logger . warn ( \"Could not validate configuration attributes as the FilterInvocationSecurityMetadataSource did \" + \"not return any attributes\" ) ; } return ; } Set < ConfigAttribute > unsupportedAttributes = new HashSet <> ( ) ; for ( ConfigAttribute attr : attrDefs ) { if ( ! this . channelDecisionManager . supports ( attr ) ) { unsupportedAttributes . add ( attr ) ; } } if ( unsupportedAttributes . size ( ) == 0 ) { if ( this . logger . isInfoEnabled ( ) ) { this . logger . info ( \"Validated configuration attributes\" ) ; } } else { throw new IllegalArgumentException ( \"Unsupported configuration attributes: \" + unsupportedAttributes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @link Builder } initialized with the authorization code . [CODESPLIT] public static Builder success ( String code ) { Assert . hasText ( code , \"code cannot be empty\" ) ; return new Builder ( ) . code ( code ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @link Builder } initialized with the error code . [CODESPLIT] public static Builder error ( String errorCode ) { Assert . hasText ( errorCode , \"errorCode cannot be empty\" ) ; return new Builder ( ) . errorCode ( errorCode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Mono < MatchResult > matches ( ServerWebExchange exchange ) { return matcher . matches ( exchange ) . flatMap ( m -> m . isMatch ( ) ? MatchResult . notMatch ( ) : MatchResult . match ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ReactiveUserDetailsServiceResourceFactoryBean with the location of a Resource that is a Properties file in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static ReactiveUserDetailsServiceResourceFactoryBean fromResourceLocation ( String resourceLocation ) { ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean ( ) ; result . setResourceLocation ( resourceLocation ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ReactiveUserDetailsServiceResourceFactoryBean with a Resource that is a Properties file in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static ReactiveUserDetailsServiceResourceFactoryBean fromResource ( Resource propertiesResource ) { ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean ( ) ; result . setResource ( propertiesResource ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ReactiveUserDetailsServiceResourceFactoryBean with a String that is in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static ReactiveUserDetailsServiceResourceFactoryBean fromString ( String users ) { ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean ( ) ; result . setResource ( new InMemoryResource ( users ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will create { @link User } object . It will ensure successful object creation even if password key is null in serialized json because credentials may be removed from the { @link User } by invoking { @link User#eraseCredentials () } . In that case there won t be any password key in serialized json . [CODESPLIT] @ Override public User deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException , JsonProcessingException { ObjectMapper mapper = ( ObjectMapper ) jp . getCodec ( ) ; JsonNode jsonNode = mapper . readTree ( jp ) ; Set < GrantedAuthority > authorities = mapper . convertValue ( jsonNode . get ( \"authorities\" ) , new TypeReference < Set < SimpleGrantedAuthority > > ( ) { } ) ; JsonNode password = readJsonNode ( jsonNode , \"password\" ) ; User result = new User ( readJsonNode ( jsonNode , \"username\" ) . asText ( ) , password . asText ( \"\" ) , readJsonNode ( jsonNode , \"enabled\" ) . asBoolean ( ) , readJsonNode ( jsonNode , \"accountNonExpired\" ) . asBoolean ( ) , readJsonNode ( jsonNode , \"credentialsNonExpired\" ) . asBoolean ( ) , readJsonNode ( jsonNode , \"accountNonLocked\" ) . asBoolean ( ) , authorities ) ; if ( password . asText ( null ) == null ) { result . eraseCredentials ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the default { [CODESPLIT] private AccessDecisionManager createDefaultAccessDecisionManager ( H http ) { AffirmativeBased result = new AffirmativeBased ( getDecisionVoters ( http ) ) ; return postProcess ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If currently null creates a default { @link AccessDecisionManager } using { @link #createDefaultAccessDecisionManager ( HttpSecurityBuilder ) } . Otherwise returns the { @link AccessDecisionManager } . [CODESPLIT] private AccessDecisionManager getAccessDecisionManager ( H http ) { if ( accessDecisionManager == null ) { accessDecisionManager = createDefaultAccessDecisionManager ( http ) ; } return accessDecisionManager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link FilterSecurityInterceptor } [CODESPLIT] private FilterSecurityInterceptor createFilterSecurityInterceptor ( H http , FilterInvocationSecurityMetadataSource metadataSource , AuthenticationManager authenticationManager ) throws Exception { FilterSecurityInterceptor securityInterceptor = new FilterSecurityInterceptor ( ) ; securityInterceptor . setSecurityMetadataSource ( metadataSource ) ; securityInterceptor . setAccessDecisionManager ( getAccessDecisionManager ( http ) ) ; securityInterceptor . setAuthenticationManager ( authenticationManager ) ; securityInterceptor . afterPropertiesSet ( ) ; return securityInterceptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a UserDetailsResourceFactoryBean with the location of a Resource that is a Properties file in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static UserDetailsResourceFactoryBean fromResourceLocation ( String resourceLocation ) { UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean ( ) ; result . setResourceLocation ( resourceLocation ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a UserDetailsResourceFactoryBean with a Resource that is a Properties file in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static UserDetailsResourceFactoryBean fromResource ( Resource propertiesResource ) { UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean ( ) ; result . setResource ( propertiesResource ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a UserDetailsResourceFactoryBean with a resource from the provided String [CODESPLIT] public static UserDetailsResourceFactoryBean fromString ( String users ) { InMemoryResource resource = new InMemoryResource ( users ) ; return fromResource ( resource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Creates a new instance with the specified pattern { @code SimpMessageType . SUBSCRIBE } and { @link PathMatcher } . [CODESPLIT] public static SimpDestinationMessageMatcher createSubscribeMatcher ( String pattern , PathMatcher matcher ) { return new SimpDestinationMessageMatcher ( pattern , SimpMessageType . SUBSCRIBE , matcher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Creates a new instance with the specified pattern { @code SimpMessageType . MESSAGE } and { @link PathMatcher } . [CODESPLIT] public static SimpDestinationMessageMatcher createMessageMatcher ( String pattern , PathMatcher matcher ) { return new SimpDestinationMessageMatcher ( pattern , SimpMessageType . MESSAGE , matcher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the values for a specific attribute [CODESPLIT] public List < String > getAttributeValues ( String name ) { List < String > result = null ; if ( attributes != null ) { result = attributes . get ( name ) ; } if ( result == null ) { result = Collections . emptyList ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first attribute value for a specified attribute [CODESPLIT] public String getFirstAttributeValue ( String name ) { List < String > result = getAttributeValues ( name ) ; if ( result . isEmpty ( ) ) { return null ; } else { return result . get ( 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the callback passed to the handle method is an instance of NameCallback the JaasNameCallbackHandler will call callback . setName ( authentication . getPrincipal () . toString () ) . [CODESPLIT] public void handle ( Callback callback , Authentication authentication ) throws IOException , UnsupportedCallbackException { if ( callback instanceof NameCallback ) { NameCallback ncb = ( NameCallback ) callback ; String username ; Object principal = authentication . getPrincipal ( ) ; if ( principal instanceof UserDetails ) { username = ( ( UserDetails ) principal ) . getUsername ( ) ; } else { username = principal . toString ( ) ; } ncb . setName ( username ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the bytes of the String in UTF - 8 encoded form . [CODESPLIT] public static byte [ ] encode ( CharSequence string ) { try { ByteBuffer bytes = CHARSET . newEncoder ( ) . encode ( CharBuffer . wrap ( string ) ) ; byte [ ] bytesCopy = new byte [ bytes . limit ( ) ] ; System . arraycopy ( bytes . array ( ) , 0 , bytesCopy , 0 , bytes . limit ( ) ) ; return bytesCopy ; } catch ( CharacterCodingException e ) { throw new IllegalArgumentException ( \"Encoding failed\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode the bytes in UTF - 8 form into a String . [CODESPLIT] public static String decode ( byte [ ] bytes ) { try { return CHARSET . newDecoder ( ) . decode ( ByteBuffer . wrap ( bytes ) ) . toString ( ) ; } catch ( CharacterCodingException e ) { throw new IllegalArgumentException ( \"Decoding failed\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public CasAuthenticationToken getByTicketId ( final String serviceTicket ) { final Cache . ValueWrapper element = serviceTicket != null ? cache . get ( serviceTicket ) : null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Cache hit: \" + ( element != null ) + \"; service ticket: \" + serviceTicket ) ; } return element == null ? null : ( CasAuthenticationToken ) element . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String [ ] getParameterNames ( Method method ) { Method originalMethod = BridgeMethodResolver . findBridgedMethod ( method ) ; String [ ] paramNames = lookupParameterNames ( METHOD_METHODPARAM_FACTORY , originalMethod ) ; if ( paramNames != null ) { return paramNames ; } Class < ? > declaringClass = method . getDeclaringClass ( ) ; Class < ? > [ ] interfaces = declaringClass . getInterfaces ( ) ; for ( Class < ? > intrfc : interfaces ) { Method intrfcMethod = ReflectionUtils . findMethod ( intrfc , method . getName ( ) , method . getParameterTypes ( ) ) ; if ( intrfcMethod != null ) { return lookupParameterNames ( METHOD_METHODPARAM_FACTORY , intrfcMethod ) ; } } return paramNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the parameter names or null if not found . [CODESPLIT] private < T extends AccessibleObject > String [ ] lookupParameterNames ( ParameterNameFactory < T > parameterNameFactory , T t ) { Annotation [ ] [ ] parameterAnnotations = parameterNameFactory . findParameterAnnotations ( t ) ; int parameterCount = parameterAnnotations . length ; String [ ] paramNames = new String [ parameterCount ] ; boolean found = false ; for ( int i = 0 ; i < parameterCount ; i ++ ) { Annotation [ ] annotations = parameterAnnotations [ i ] ; String parameterName = findParameterName ( annotations ) ; if ( parameterName != null ) { found = true ; paramNames [ i ] = parameterName ; } } return found ? paramNames : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the parameter name from the provided { @link Annotation } s or null if it could not find it . The search is done by looking at the value property of the { @link #annotationClassesToUse } . [CODESPLIT] private String findParameterName ( Annotation [ ] parameterAnnotations ) { for ( Annotation paramAnnotation : parameterAnnotations ) { if ( annotationClassesToUse . contains ( paramAnnotation . annotationType ( ) . getName ( ) ) ) { return ( String ) AnnotationUtils . getValue ( paramAnnotation , \"value\" ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the submission of the contact form creating a new instance if the username and email are valid . [CODESPLIT] @ RequestMapping ( value = \"/secure/add.htm\" , method = RequestMethod . POST ) public String addContact ( WebContact form , BindingResult result ) { validator . validate ( form , result ) ; if ( result . hasErrors ( ) ) { return \"add\" ; } Contact contact = new Contact ( form . getName ( ) , form . getEmail ( ) ) ; contactManager . create ( contact ) ; return \"redirect:/secure/index.htm\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void writeHeaders ( HttpServletRequest request , HttpServletResponse response ) { if ( requestMatcher . matches ( request ) ) { if ( ! pins . isEmpty ( ) ) { String headerName = reportOnly ? HPKP_RO_HEADER_NAME : HPKP_HEADER_NAME ; if ( ! response . containsHeader ( headerName ) ) { response . setHeader ( headerName , hpkpHeaderValue ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Not injecting HPKP header since there aren't any pins\" ) ; } } else if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Not injecting HPKP header since it wasn't a secure connection\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the value for the pin - directive of the Public - Key - Pins header . < / p > [CODESPLIT] public void setPins ( Map < String , String > pins ) { Assert . notNull ( pins , \"pins cannot be null\" ) ; this . pins = pins ; updateHpkpHeaderValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Adds a list of SHA256 hashed pins for the pin - directive of the Public - Key - Pins header . < / p > [CODESPLIT] public void addSha256Pins ( String ... pins ) { for ( String pin : pins ) { Assert . notNull ( pin , \"pin cannot be null\" ) ; this . pins . put ( pin , \"sha256\" ) ; } updateHpkpHeaderValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the URI to which the browser should report pin validation failures . < / p > [CODESPLIT] public void setReportUri ( String reportUri ) { try { this . reportUri = new URI ( reportUri ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } updateHpkpHeaderValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will walk the method inheritance tree to find the most specific declaration applicable . [CODESPLIT] @ Override protected Collection < ConfigAttribute > findAttributes ( Method method , Class < ? > targetClass ) { if ( targetClass == null ) { return null ; } return findAttributesSpecifiedAgainst ( method , targetClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add configuration attributes for a secure method . Method names can end or start with <code > * < / code > for matching multiple methods . [CODESPLIT] private void addSecureMethod ( String name , List < ConfigAttribute > attr ) { int lastDotIndex = name . lastIndexOf ( \".\" ) ; if ( lastDotIndex == - 1 ) { throw new IllegalArgumentException ( \"'\" + name + \"' is not a valid method name: format is FQN.methodName\" ) ; } String methodName = name . substring ( lastDotIndex + 1 ) ; Assert . hasText ( methodName , ( ) -> \"Method not found for '\" + name + \"'\" ) ; String typeName = name . substring ( 0 , lastDotIndex ) ; Class < ? > type = ClassUtils . resolveClassName ( typeName , this . beanClassLoader ) ; addSecureMethod ( type , methodName , attr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add configuration attributes for a secure method . Mapped method names can end or start with <code > * < / code > for matching multiple methods . [CODESPLIT] public void addSecureMethod ( Class < ? > javaType , String mappedName , List < ConfigAttribute > attr ) { String name = javaType . getName ( ) + ' ' + mappedName ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Request to add secure method [\" + name + \"] with attributes [\" + attr + \"]\" ) ; } Method [ ] methods = javaType . getMethods ( ) ; List < Method > matchingMethods = new ArrayList <> ( ) ; for ( Method m : methods ) { if ( m . getName ( ) . equals ( mappedName ) || isMatch ( m . getName ( ) , mappedName ) ) { matchingMethods . add ( m ) ; } } if ( matchingMethods . isEmpty ( ) ) { throw new IllegalArgumentException ( \"Couldn't find method '\" + mappedName + \"' on '\" + javaType + \"'\" ) ; } // register all matching methods for ( Method method : matchingMethods ) { RegisteredMethod registeredMethod = new RegisteredMethod ( method , javaType ) ; String regMethodName = ( String ) this . nameMap . get ( registeredMethod ) ; if ( ( regMethodName == null ) || ( ! regMethodName . equals ( name ) && ( regMethodName . length ( ) <= name . length ( ) ) ) ) { // no already registered method name, or more specific // method name specification now -> (re-)register method if ( regMethodName != null ) { logger . debug ( \"Replacing attributes for secure method [\" + method + \"]: current name [\" + name + \"] is more specific than [\" + regMethodName + \"]\" ) ; } this . nameMap . put ( registeredMethod , name ) ; addSecureMethod ( registeredMethod , attr ) ; } else { logger . debug ( \"Keeping attributes for secure method [\" + method + \"]: current name [\" + name + \"] is not more specific than [\" + regMethodName + \"]\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds configuration attributes for a specific method for example where the method has been matched using a pointcut expression . If a match already exists in the map for the method then the existing match will be retained so that if this method is called for a more general pointcut it will not override a more specific one which has already been added . <p > This method should only be called during initialization of the { [CODESPLIT] public void addSecureMethod ( Class < ? > javaType , Method method , List < ConfigAttribute > attr ) { RegisteredMethod key = new RegisteredMethod ( method , javaType ) ; if ( methodMap . containsKey ( key ) ) { logger . debug ( \"Method [\" + method + \"] is already registered with attributes [\" + methodMap . get ( key ) + \"]\" ) ; return ; } methodMap . put ( key , attr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add configuration attributes for a secure method . [CODESPLIT] private void addSecureMethod ( RegisteredMethod method , List < ConfigAttribute > attr ) { Assert . notNull ( method , \"RegisteredMethod required\" ) ; Assert . notNull ( attr , \"Configuration attribute required\" ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( \"Adding secure method [\" + method + \"] with attributes [\" + attr + \"]\" ) ; } this . methodMap . put ( method , attr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the configuration attributes explicitly defined against this bean . [CODESPLIT] @ Override public Collection < ConfigAttribute > getAllConfigAttributes ( ) { Set < ConfigAttribute > allAttributes = new HashSet <> ( ) ; for ( List < ConfigAttribute > attributeList : methodMap . values ( ) ) { allAttributes . addAll ( attributeList ) ; } return allAttributes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return if the given method name matches the mapped name . The default implementation checks for xxx and xxx matches . [CODESPLIT] private boolean isMatch ( String methodName , String mappedName ) { return ( mappedName . endsWith ( \"*\" ) && methodName . startsWith ( mappedName . substring ( 0 , mappedName . length ( ) - 1 ) ) ) || ( mappedName . startsWith ( \"*\" ) && methodName . endsWith ( mappedName . substring ( 1 , mappedName . length ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link PortMapper } to use . If { @link #portMapper ( PortMapper ) } was not invoked builds a { @link PortMapperImpl } using the port mappings specified with { @link #http ( int ) } . [CODESPLIT] private PortMapper getPortMapper ( ) { if ( portMapper == null ) { PortMapperImpl portMapper = new PortMapperImpl ( ) ; portMapper . setPortMappings ( httpsPortMappings ) ; this . portMapper = portMapper ; } return portMapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void saveToken ( CsrfToken token , HttpServletRequest request , HttpServletResponse response ) { if ( token == null ) { HttpSession session = request . getSession ( false ) ; if ( session != null ) { session . removeAttribute ( this . sessionAttributeName ) ; } } else { HttpSession session = request . getSession ( ) ; session . setAttribute ( this . sessionAttributeName , token ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public CsrfToken loadToken ( HttpServletRequest request ) { HttpSession session = request . getSession ( false ) ; if ( session == null ) { return null ; } return ( CsrfToken ) session . getAttribute ( this . sessionAttributeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ReactiveJwtDecoder } using the provided <a href = https : // openid . net / specs / openid - connect - core - 1_0 . html#IssuerIdentifier > Issuer< / a > by making an <a href = https : // openid . net / specs / openid - connect - discovery - 1_0 . html#ProviderConfigurationRequest > OpenID Provider Configuration Request< / a > and using the values in the <a href = https : // openid . net / specs / openid - connect - discovery - 1_0 . html#ProviderConfigurationResponse > OpenID Provider Configuration Response< / a > to initialize the { @link ReactiveJwtDecoder } . [CODESPLIT] public static ReactiveJwtDecoder fromOidcIssuerLocation ( String oidcIssuerLocation ) { Map < String , Object > openidConfiguration = getOpenidConfiguration ( oidcIssuerLocation ) ; String metadataIssuer = \"(unavailable)\" ; if ( openidConfiguration . containsKey ( \"issuer\" ) ) { metadataIssuer = openidConfiguration . get ( \"issuer\" ) . toString ( ) ; } if ( ! oidcIssuerLocation . equals ( metadataIssuer ) ) { throw new IllegalStateException ( \"The Issuer \\\"\" + metadataIssuer + \"\\\" provided in the OpenID Configuration \" + \"did not match the requested issuer \\\"\" + oidcIssuerLocation + \"\\\"\" ) ; } OAuth2TokenValidator < Jwt > jwtValidator = JwtValidators . createDefaultWithIssuer ( oidcIssuerLocation ) ; NimbusReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder ( openidConfiguration . get ( \"jwks_uri\" ) . toString ( ) ) ; jwtDecoder . setJwtValidator ( jwtValidator ) ; return jwtDecoder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Mono < MatchResult > matches ( ServerWebExchange exchange ) { return Flux . fromIterable ( matchers ) . flatMap ( m -> m . matches ( exchange ) ) . filter ( m -> m . isMatch ( ) ) . next ( ) . switchIfEmpty ( MatchResult . notMatch ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of { @link AuthorityReactiveAuthorizationManager } with the provided authority . [CODESPLIT] public static < T > AuthorityReactiveAuthorizationManager < T > hasAuthority ( String authority ) { Assert . notNull ( authority , \"authority cannot be null\" ) ; return new AuthorityReactiveAuthorizationManager <> ( authority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of { @link AuthorityReactiveAuthorizationManager } with the provided authorities . [CODESPLIT] public static < T > AuthorityReactiveAuthorizationManager < T > hasAnyAuthority ( String ... authorities ) { Assert . notNull ( authorities , \"authorities cannot be null\" ) ; for ( String authority : authorities ) { Assert . notNull ( authority , \"authority cannot be null\" ) ; } return new AuthorityReactiveAuthorizationManager <> ( authorities ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of { @link AuthorityReactiveAuthorizationManager } with the provided authority . [CODESPLIT] public static < T > AuthorityReactiveAuthorizationManager < T > hasRole ( String role ) { Assert . notNull ( role , \"role cannot be null\" ) ; return hasAuthority ( \"ROLE_\" + role ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of { @link AuthorityReactiveAuthorizationManager } with the provided authorities . [CODESPLIT] public static < T > AuthorityReactiveAuthorizationManager < T > hasAnyRole ( String ... roles ) { Assert . notNull ( roles , \"roles cannot be null\" ) ; for ( String role : roles ) { Assert . notNull ( role , \"role cannot be null\" ) ; } return hasAnyAuthority ( Stream . of ( roles ) . map ( r -> \"ROLE_\" + r ) . toArray ( String [ ] :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the security context for the current request ( if available ) and returns it . <p > If the session is null the context object is null or the context object stored in the session is not an instance of { [CODESPLIT] public SecurityContext loadContext ( HttpRequestResponseHolder requestResponseHolder ) { HttpServletRequest request = requestResponseHolder . getRequest ( ) ; HttpServletResponse response = requestResponseHolder . getResponse ( ) ; HttpSession httpSession = request . getSession ( false ) ; SecurityContext context = readSecurityContextFromSession ( httpSession ) ; if ( context == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"No SecurityContext was available from the HttpSession: \" + httpSession + \". \" + \"A new one will be created.\" ) ; } context = generateNewContext ( ) ; } SaveToSessionResponseWrapper wrappedResponse = new SaveToSessionResponseWrapper ( response , request , httpSession != null , context ) ; requestResponseHolder . setResponse ( wrappedResponse ) ; requestResponseHolder . setRequest ( new SaveToSessionRequestWrapper ( request , wrappedResponse ) ) ; return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps any request . [CODESPLIT] public C anyRequest ( ) { Assert . state ( ! this . anyRequestConfigured , \"Can't configure anyRequest after itself\" ) ; C configurer = requestMatchers ( ANY_REQUEST ) ; this . anyRequestConfigured = true ; return configurer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link List } of { @link org . springframework . security . web . util . matcher . AntPathRequestMatcher } instances that do not care which { @link HttpMethod } is used . [CODESPLIT] public C antMatchers ( String ... antPatterns ) { Assert . state ( ! this . anyRequestConfigured , \"Can't configure antMatchers after anyRequest\" ) ; return chainRequestMatchers ( RequestMatchers . antMatchers ( antPatterns ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link MvcRequestMatcher } instances for the method and patterns passed in [CODESPLIT] protected final List < MvcRequestMatcher > createMvcMatchers ( HttpMethod method , String ... mvcPatterns ) { Assert . state ( ! this . anyRequestConfigured , \"Can't configure mvcMatchers after anyRequest\" ) ; ObjectPostProcessor < Object > opp = this . context . getBean ( ObjectPostProcessor . class ) ; if ( ! this . context . containsBean ( HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME ) ) { throw new NoSuchBeanDefinitionException ( \"A Bean named \" + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME + \" of type \" + HandlerMappingIntrospector . class . getName ( ) + \" is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext.\" ) ; } HandlerMappingIntrospector introspector = this . context . getBean ( HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME , HandlerMappingIntrospector . class ) ; List < MvcRequestMatcher > matchers = new ArrayList <> ( mvcPatterns . length ) ; for ( String mvcPattern : mvcPatterns ) { MvcRequestMatcher matcher = new MvcRequestMatcher ( introspector , mvcPattern ) ; opp . postProcess ( matcher ) ; if ( method != null ) { matcher . setMethod ( method ) ; } matchers . add ( matcher ) ; } return matchers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link List } of { @link org . springframework . security . web . util . matcher . RegexRequestMatcher } instances . [CODESPLIT] public C regexMatchers ( HttpMethod method , String ... regexPatterns ) { Assert . state ( ! this . anyRequestConfigured , \"Can't configure regexMatchers after anyRequest\" ) ; return chainRequestMatchers ( RequestMatchers . regexMatchers ( method , regexPatterns ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates a list of { @link RequestMatcher } instances with the { @link AbstractConfigAttributeRequestMatcherRegistry } [CODESPLIT] public C requestMatchers ( RequestMatcher ... requestMatchers ) { Assert . state ( ! this . anyRequestConfigured , \"Can't configure requestMatchers after anyRequest\" ) ; return chainRequestMatchers ( Arrays . asList ( requestMatchers ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , Message < ? > message ) throws Exception { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication == null ) { return null ; } Object principal = authentication . getPrincipal ( ) ; AuthenticationPrincipal authPrincipal = findMethodAnnotation ( AuthenticationPrincipal . class , parameter ) ; String expressionToParse = authPrincipal . expression ( ) ; if ( StringUtils . hasLength ( expressionToParse ) ) { StandardEvaluationContext context = new StandardEvaluationContext ( ) ; context . setRootObject ( principal ) ; context . setVariable ( \"this\" , principal ) ; Expression expression = this . parser . parseExpression ( expressionToParse ) ; principal = expression . getValue ( context ) ; } if ( principal != null && ! parameter . getParameterType ( ) . isAssignableFrom ( principal . getClass ( ) ) ) { if ( authPrincipal . errorOnInvalidType ( ) ) { throw new ClassCastException ( principal + \" is not assignable to \" + parameter . getParameterType ( ) ) ; } else { return null ; } } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a LoginContext using the Configuration that was specified in { [CODESPLIT] @ Override protected LoginContext createLoginContext ( CallbackHandler handler ) throws LoginException { return new LoginContext ( getLoginContextName ( ) , null , handler , getConfiguration ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public DirContextOperations authenticate ( Authentication authentication ) { DirContextOperations user = null ; Assert . isInstanceOf ( UsernamePasswordAuthenticationToken . class , authentication , \"Can only process UsernamePasswordAuthenticationToken objects\" ) ; String username = authentication . getName ( ) ; String password = ( String ) authentication . getCredentials ( ) ; if ( ! StringUtils . hasLength ( password ) ) { logger . debug ( \"Rejecting empty password for user \" + username ) ; throw new BadCredentialsException ( messages . getMessage ( \"BindAuthenticator.emptyPassword\" , \"Empty Password\" ) ) ; } // If DN patterns are configured, try authenticating with them directly for ( String dn : getUserDns ( username ) ) { user = bindWithDn ( dn , username , password ) ; if ( user != null ) { break ; } } // Otherwise use the configured search object to find the user and authenticate // with the returned DN. if ( user == null && getUserSearch ( ) != null ) { DirContextOperations userFromSearch = getUserSearch ( ) . searchForUser ( username ) ; user = bindWithDn ( userFromSearch . getDn ( ) . toString ( ) , username , password , userFromSearch . getAttributes ( ) ) ; } if ( user == null ) { throw new BadCredentialsException ( messages . getMessage ( \"BindAuthenticator.badCredentials\" , \"Bad credentials\" ) ) ; } return user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows subclasses to inspect the exception thrown by an attempt to bind with a particular DN . The default implementation just reports the failure to the debug logger . [CODESPLIT] protected void handleBindException ( String userDn , String username , Throwable cause ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Failed to bind as \" + userDn + \": \" + cause ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link RequestEntity } used for the UserInfo Request . [CODESPLIT] @ Override public RequestEntity < ? > convert ( OAuth2UserRequest userRequest ) { ClientRegistration clientRegistration = userRequest . getClientRegistration ( ) ; HttpMethod httpMethod = HttpMethod . GET ; if ( AuthenticationMethod . FORM . equals ( clientRegistration . getProviderDetails ( ) . getUserInfoEndpoint ( ) . getAuthenticationMethod ( ) ) ) { httpMethod = HttpMethod . POST ; } HttpHeaders headers = new HttpHeaders ( ) ; headers . setAccept ( Collections . singletonList ( MediaType . APPLICATION_JSON ) ) ; URI uri = UriComponentsBuilder . fromUriString ( clientRegistration . getProviderDetails ( ) . getUserInfoEndpoint ( ) . getUri ( ) ) . build ( ) . toUri ( ) ; RequestEntity < ? > request ; if ( HttpMethod . POST . equals ( httpMethod ) ) { headers . setContentType ( DEFAULT_CONTENT_TYPE ) ; MultiValueMap < String , String > formParameters = new LinkedMultiValueMap <> ( ) ; formParameters . add ( OAuth2ParameterNames . ACCESS_TOKEN , userRequest . getAccessToken ( ) . getTokenValue ( ) ) ; request = new RequestEntity <> ( formParameters , headers , httpMethod , uri ) ; } else { headers . setBearerAuth ( userRequest . getAccessToken ( ) . getTokenValue ( ) ) ; request = new RequestEntity <> ( headers , httpMethod , uri ) ; } return request ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain filterChain ) throws ServletException , IOException { request . setAttribute ( HttpServletResponse . class . getName ( ) , response ) ; CsrfToken csrfToken = this . tokenRepository . loadToken ( request ) ; final boolean missingToken = csrfToken == null ; if ( missingToken ) { csrfToken = this . tokenRepository . generateToken ( request ) ; this . tokenRepository . saveToken ( csrfToken , request , response ) ; } request . setAttribute ( CsrfToken . class . getName ( ) , csrfToken ) ; request . setAttribute ( csrfToken . getParameterName ( ) , csrfToken ) ; if ( ! this . requireCsrfProtectionMatcher . matches ( request ) ) { filterChain . doFilter ( request , response ) ; return ; } String actualToken = request . getHeader ( csrfToken . getHeaderName ( ) ) ; if ( actualToken == null ) { actualToken = request . getParameter ( csrfToken . getParameterName ( ) ) ; } if ( ! csrfToken . getToken ( ) . equals ( actualToken ) ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( \"Invalid CSRF token found for \" + UrlUtils . buildFullRequestUrl ( request ) ) ; } if ( missingToken ) { this . accessDeniedHandler . handle ( request , response , new MissingCsrfTokenException ( actualToken ) ) ; } else { this . accessDeniedHandler . handle ( request , response , new InvalidCsrfTokenException ( csrfToken , actualToken ) ) ; } return ; } filterChain . doFilter ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) throws SessionAuthenticationException { for ( SessionAuthenticationStrategy delegate : this . delegateStrategies ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( \"Delegating to \" + delegate ) ; } delegate . onAuthentication ( authentication , request , response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds list of possible DNs for the user worked out from the <tt > userDnPatterns< / tt > property . [CODESPLIT] protected List < String > getUserDns ( String username ) { if ( userDnFormat == null ) { return Collections . emptyList ( ) ; } List < String > userDns = new ArrayList <> ( userDnFormat . length ) ; String [ ] args = new String [ ] { LdapEncoder . nameEncode ( username ) } ; synchronized ( userDnFormat ) { for ( MessageFormat formatter : userDnFormat ) { userDns . add ( formatter . format ( args ) ) ; } } return userDns ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the pattern which will be used to supply a DN for the user . The pattern should be the name relative to the root DN . The pattern argument { 0 } will contain the username . An example would be cn = { 0 } ou = people . [CODESPLIT] public void setUserDnPatterns ( String [ ] dnPattern ) { Assert . notNull ( dnPattern , \"The array of DN patterns cannot be set to null\" ) ; // this.userDnPattern = dnPattern; userDnFormat = new MessageFormat [ dnPattern . length ] ; for ( int i = 0 ; i < dnPattern . length ; i ++ ) { userDnFormat [ i ] = new MessageFormat ( dnPattern [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void onApplicationEvent ( AbstractAuthorizationEvent event ) { if ( event instanceof AuthenticationCredentialsNotFoundEvent ) { AuthenticationCredentialsNotFoundEvent authEvent = ( AuthenticationCredentialsNotFoundEvent ) event ; if ( logger . isWarnEnabled ( ) ) { logger . warn ( \"Security interception failed due to: \" + authEvent . getCredentialsNotFoundException ( ) + \"; secure object: \" + authEvent . getSource ( ) + \"; configuration attributes: \" + authEvent . getConfigAttributes ( ) ) ; } } if ( event instanceof AuthorizationFailureEvent ) { AuthorizationFailureEvent authEvent = ( AuthorizationFailureEvent ) event ; if ( logger . isWarnEnabled ( ) ) { logger . warn ( \"Security authorization failed due to: \" + authEvent . getAccessDeniedException ( ) + \"; authenticated principal: \" + authEvent . getAuthentication ( ) + \"; secure object: \" + authEvent . getSource ( ) + \"; configuration attributes: \" + authEvent . getConfigAttributes ( ) ) ; } } if ( event instanceof AuthorizedEvent ) { AuthorizedEvent authEvent = ( AuthorizedEvent ) event ; if ( logger . isInfoEnabled ( ) ) { logger . info ( \"Security authorized for authenticated principal: \" + authEvent . getAuthentication ( ) + \"; secure object: \" + authEvent . getSource ( ) + \"; configuration attributes: \" + authEvent . getConfigAttributes ( ) ) ; } } if ( event instanceof PublicInvocationEvent ) { PublicInvocationEvent authEvent = ( PublicInvocationEvent ) event ; if ( logger . isInfoEnabled ( ) ) { logger . info ( \"Security interception not required for public secure object: \" + authEvent . getSource ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the mapping of { @link RequestMatcher } to { @link Collection } of { @link ConfigAttribute } instances [CODESPLIT] final LinkedHashMap < RequestMatcher , Collection < ConfigAttribute > > createRequestMap ( ) { if ( unmappedMatchers != null ) { throw new IllegalStateException ( \"An incomplete mapping was found for \" + unmappedMatchers + \". Try completing it with something like requestUrls().<something>.hasRole('USER')\" ) ; } LinkedHashMap < RequestMatcher , Collection < ConfigAttribute > > requestMap = new LinkedHashMap < RequestMatcher , Collection < ConfigAttribute > > ( ) ; for ( UrlMapping mapping : getUrlMappings ( ) ) { RequestMatcher matcher = mapping . getRequestMatcher ( ) ; Collection < ConfigAttribute > configAttrs = mapping . getConfigAttrs ( ) ; requestMap . put ( matcher , configAttrs ) ; } return requestMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of { [CODESPLIT] public void onLogoutSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) throws IOException , ServletException { response . setStatus ( this . httpStatusToReturn . value ( ) ) ; response . getWriter ( ) . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether the user represented by the supplied <tt > Authentication< / tt > object is allowed to invoke the supplied URI . [CODESPLIT] public boolean isAllowed ( String uri , Authentication authentication ) { return isAllowed ( null , uri , null , authentication ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether the user represented by the supplied <tt > Authentication< / tt > object is allowed to invoke the supplied URI with the given . <p > Note the default implementation of <tt > FilterInvocationSecurityMetadataSource< / tt > disregards the <code > contextPath< / code > when evaluating which secure object metadata applies to a given request URI so generally the <code > contextPath< / code > is unimportant unless you are using a custom <code > FilterInvocationSecurityMetadataSource< / code > . [CODESPLIT] public boolean isAllowed ( String contextPath , String uri , String method , Authentication authentication ) { Assert . notNull ( uri , \"uri parameter is required\" ) ; FilterInvocation fi = new FilterInvocation ( contextPath , uri , method ) ; Collection < ConfigAttribute > attrs = securityInterceptor . obtainSecurityMetadataSource ( ) . getAttributes ( fi ) ; if ( attrs == null ) { if ( securityInterceptor . isRejectPublicInvocations ( ) ) { return false ; } return true ; } if ( authentication == null ) { return false ; } try { securityInterceptor . getAccessDecisionManager ( ) . decide ( authentication , fi , attrs ) ; } catch ( AccessDeniedException unauthorized ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( fi . toString ( ) + \" denied for \" + authentication . toString ( ) , unauthorized ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Map < String , String > extractUriTemplateVariables ( HttpServletRequest request ) { MatchableHandlerMapping mapping = getMapping ( request ) ; if ( mapping == null ) { return this . defaultMatcher . extractUriTemplateVariables ( request ) ; } RequestMatchResult result = mapping . match ( request , this . pattern ) ; return result == null ? Collections . < String , String > emptyMap ( ) : result . extractUriTemplateVariables ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the target URL . It allows for the host to change based upon the cas . service . host system property . If the property is not set the default is localhost : 8443 . [CODESPLIT] @ Override public void init ( ) throws ServletException { super . init ( ) ; String casServiceHost = System . getProperty ( \"cas.service.host\" , \"localhost:8443\" ) ; targetUrl = \"https://\" + casServiceHost + \"/cas-sample/secure/\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public long getDateHeader ( String name ) { String value = getHeader ( name ) ; if ( value == null ) { return - 1L ; } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat . parseDate ( value , formats ) ; if ( result != - 1L ) { return result ; } throw new IllegalArgumentException ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the parameter is available from the wrapped request then the request has been forwarded / included to a URL with parameters either supplementing or overriding the saved request values . <p > In this case the value from the wrapped request should be used . <p > If the value from the wrapped request is null an attempt will be made to retrieve the parameter from the saved request . [CODESPLIT] @ Override public String getParameter ( String name ) { String value = super . getParameter ( name ) ; if ( value != null ) { return value ; } String [ ] values = savedRequest . getParameterValues ( name ) ; if ( values == null || values . length == 0 ) { return null ; } return values [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read and returns the variable named by { @code principalEnvironmentVariable } from the request . [CODESPLIT] protected Object getPreAuthenticatedPrincipal ( HttpServletRequest request ) { String principal = ( String ) request . getAttribute ( principalEnvironmentVariable ) ; if ( principal == null && exceptionIfVariableMissing ) { throw new PreAuthenticatedCredentialsNotFoundException ( principalEnvironmentVariable + \" variable not found in request.\" ) ; } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In addition to the steps from the superclass the sessionRegistry will be updated with the new session information . [CODESPLIT] public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) { sessionRegistry . registerNewSession ( request . getSession ( ) . getId ( ) , authentication . getPrincipal ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method should be used to enforce security on a <code > MethodInvocation< / code > . [CODESPLIT] public Object invoke ( MethodInvocation mi ) throws Throwable { InterceptorStatusToken token = super . beforeInvocation ( mi ) ; Object result ; try { result = mi . proceed ( ) ; } finally { super . finallyInvocation ( token ) ; } return super . afterInvocation ( token , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a public method . [CODESPLIT] @ Transactional ( readOnly = true ) public Contact getRandomContact ( ) { logger . debug ( \"Returning random contact\" ) ; Random rnd = new Random ( ) ; List < Contact > contacts = contactDao . findAll ( ) ; int getNumber = rnd . nextInt ( contacts . size ( ) ) ; return contacts . get ( getNumber ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void evictFromCache ( Serializable pk ) { Assert . notNull ( pk , \"Primary key (identifier) required\" ) ; MutableAcl acl = getFromCache ( pk ) ; if ( acl != null ) { cache . remove ( acl . getId ( ) ) ; cache . remove ( acl . getObjectIdentity ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs post processing of an object . The default is to delegate to the { @link ObjectPostProcessor } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected < T > T postProcess ( T object ) { return ( T ) this . objectPostProcessor . postProcess ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the parent class { [CODESPLIT] public void onAuthenticationSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) throws IOException , ServletException { handle ( request , response , authentication ) ; clearAuthenticationAttributes ( request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes temporary authentication - related data which may have been stored in the session during the authentication process . [CODESPLIT] protected final void clearAuthenticationAttributes ( HttpServletRequest request ) { HttpSession session = request . getSession ( false ) ; if ( session == null ) { return ; } session . removeAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to locate the specified field on the class . [CODESPLIT] public static Field getField ( Class < ? > clazz , String fieldName ) throws IllegalStateException { Assert . notNull ( clazz , \"Class required\" ) ; Assert . hasText ( fieldName , \"Field name required\" ) ; try { return clazz . getDeclaredField ( fieldName ) ; } catch ( NoSuchFieldException nsf ) { // Try superclass if ( clazz . getSuperclass ( ) != null ) { return getField ( clazz . getSuperclass ( ) , fieldName ) ; } throw new IllegalStateException ( \"Could not locate field '\" + fieldName + \"' on class \" + clazz ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of a ( nested ) field on a bean . Intended for testing . [CODESPLIT] public static Object getFieldValue ( Object bean , String fieldName ) throws IllegalAccessException { Assert . notNull ( bean , \"Bean cannot be null\" ) ; Assert . hasText ( fieldName , \"Field name required\" ) ; String [ ] nestedFields = StringUtils . tokenizeToStringArray ( fieldName , \".\" ) ; Class < ? > componentClass = bean . getClass ( ) ; Object value = bean ; for ( String nestedField : nestedFields ) { Field field = getField ( componentClass , nestedField ) ; field . setAccessible ( true ) ; value = field . get ( value ) ; if ( value != null ) { componentClass = value . getClass ( ) ; } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . hasLength ( this . loginUrl , \"loginUrl must be specified\" ) ; Assert . notNull ( this . serviceProperties , \"serviceProperties must be specified\" ) ; Assert . notNull ( this . serviceProperties . getService ( ) , \"serviceProperties.getService() cannot be null.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a new Service Url . The default implementation relies on the CAS client to do the bulk of the work . [CODESPLIT] protected String createServiceUrl ( final HttpServletRequest request , final HttpServletResponse response ) { return CommonUtils . constructServiceUrl ( null , response , this . serviceProperties . getService ( ) , null , this . serviceProperties . getArtifactParameter ( ) , this . encodeServiceUrlWithSessionId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs the Url for Redirection to the CAS server . Default implementation relies on the CAS client to do the bulk of the work . [CODESPLIT] protected String createRedirectUrl ( final String serviceUrl ) { return CommonUtils . constructRedirectUrl ( this . loginUrl , this . serviceProperties . getServiceParameter ( ) , serviceUrl , this . serviceProperties . isSendRenew ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the role hierarchy and pre - calculate for every role the set of all reachable roles i . e . all roles lower in the hierarchy of every given role . Pre - calculation is done for performance reasons ( reachable roles can then be calculated in O ( 1 ) time ) . During pre - calculation cycles in role hierarchy are detected and will cause a <tt > CycleInRoleHierarchyException< / tt > to be thrown . [CODESPLIT] public void setHierarchy ( String roleHierarchyStringRepresentation ) { this . roleHierarchyStringRepresentation = roleHierarchyStringRepresentation ; logger . debug ( \"setHierarchy() - The following role hierarchy was set: \" + roleHierarchyStringRepresentation ) ; buildRolesReachableInOneStepMap ( ) ; buildRolesReachableInOneOrMoreStepsMap ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SEC - 863 [CODESPLIT] private void addReachableRoles ( Set < GrantedAuthority > reachableRoles , GrantedAuthority authority ) { for ( GrantedAuthority testAuthority : reachableRoles ) { String testKey = testAuthority . getAuthority ( ) ; if ( ( testKey != null ) && ( testKey . equals ( authority . getAuthority ( ) ) ) ) { return ; } } reachableRoles . add ( authority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SEC - 863 [CODESPLIT] private Set < GrantedAuthority > getRolesReachableInOneOrMoreSteps ( GrantedAuthority authority ) { if ( authority . getAuthority ( ) == null ) { return null ; } for ( GrantedAuthority testAuthority : this . rolesReachableInOneOrMoreStepsMap . keySet ( ) ) { String testKey = testAuthority . getAuthority ( ) ; if ( ( testKey != null ) && ( testKey . equals ( authority . getAuthority ( ) ) ) ) { return this . rolesReachableInOneOrMoreStepsMap . get ( testAuthority ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse input and build the map for the roles reachable in one step : the higher role will become a key that references a set of the reachable lower roles . [CODESPLIT] private void buildRolesReachableInOneStepMap ( ) { this . rolesReachableInOneStepMap = new HashMap < GrantedAuthority , Set < GrantedAuthority > > ( ) ; try ( BufferedReader bufferedReader = new BufferedReader ( new StringReader ( this . roleHierarchyStringRepresentation ) ) ) { for ( String readLine ; ( readLine = bufferedReader . readLine ( ) ) != null ; ) { String [ ] roles = readLine . split ( \" > \" ) ; for ( int i = 1 ; i < roles . length ; i ++ ) { GrantedAuthority higherRole = new SimpleGrantedAuthority ( roles [ i - 1 ] . replaceAll ( \"^\\\\s+|\\\\s+$\" , \"\" ) ) ; GrantedAuthority lowerRole = new SimpleGrantedAuthority ( roles [ i ] . replaceAll ( \"^\\\\s+|\\\\s+$\" , \"\" ) ) ; Set < GrantedAuthority > rolesReachableInOneStepSet ; if ( ! this . rolesReachableInOneStepMap . containsKey ( higherRole ) ) { rolesReachableInOneStepSet = new HashSet < GrantedAuthority > ( ) ; this . rolesReachableInOneStepMap . put ( higherRole , rolesReachableInOneStepSet ) ; } else { rolesReachableInOneStepSet = this . rolesReachableInOneStepMap . get ( higherRole ) ; } addReachableRoles ( rolesReachableInOneStepSet , lowerRole ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"buildRolesReachableInOneStepMap() - From role \" + higherRole + \" one can reach role \" + lowerRole + \" in one step.\" ) ; } } } } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For every higher role from rolesReachableInOneStepMap store all roles that are reachable from it in the map of roles reachable in one or more steps . ( Or throw a CycleInRoleHierarchyException if a cycle in the role hierarchy definition is detected ) [CODESPLIT] private void buildRolesReachableInOneOrMoreStepsMap ( ) { this . rolesReachableInOneOrMoreStepsMap = new HashMap <> ( ) ; // iterate over all higher roles from rolesReachableInOneStepMap for ( GrantedAuthority role : this . rolesReachableInOneStepMap . keySet ( ) ) { Set < GrantedAuthority > rolesToVisitSet = new HashSet <> ( ) ; if ( this . rolesReachableInOneStepMap . containsKey ( role ) ) { rolesToVisitSet . addAll ( this . rolesReachableInOneStepMap . get ( role ) ) ; } Set < GrantedAuthority > visitedRolesSet = new HashSet <> ( ) ; while ( ! rolesToVisitSet . isEmpty ( ) ) { // take a role from the rolesToVisit set GrantedAuthority aRole = rolesToVisitSet . iterator ( ) . next ( ) ; rolesToVisitSet . remove ( aRole ) ; addReachableRoles ( visitedRolesSet , aRole ) ; if ( this . rolesReachableInOneStepMap . containsKey ( aRole ) ) { Set < GrantedAuthority > newReachableRoles = this . rolesReachableInOneStepMap . get ( aRole ) ; // definition of a cycle: you can reach the role you are starting from if ( rolesToVisitSet . contains ( role ) || visitedRolesSet . contains ( role ) ) { throw new CycleInRoleHierarchyException ( ) ; } else { // no cycle rolesToVisitSet . addAll ( newReachableRoles ) ; } } } this . rolesReachableInOneOrMoreStepsMap . put ( role , visitedRolesSet ) ; logger . debug ( \"buildRolesReachableInOneOrMoreStepsMap() - From role \" + role + \" one can reach \" + visitedRolesSet + \" in one or more steps.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "internal helpers [CODESPLIT] private byte [ ] iv ( byte [ ] encrypted ) { return this . ivGenerator != NULL_IV_GENERATOR ? subArray ( encrypted , 0 , this . ivGenerator . getKeyLength ( ) ) : NULL_IV_GENERATOR . generateKey ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { @link LogoutHandler } . The { @link SecurityContextLogoutHandler } is added as the last { @link LogoutHandler } by default . [CODESPLIT] public LogoutConfigurer < H > addLogoutHandler ( LogoutHandler logoutHandler ) { Assert . notNull ( logoutHandler , \"logoutHandler cannot be null\" ) ; this . logoutHandlers . add ( logoutHandler ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link LogoutSuccessHandler } to use . If this is specified { @link #logoutSuccessUrl ( String ) } is ignored . [CODESPLIT] public LogoutConfigurer < H > logoutSuccessHandler ( LogoutSuccessHandler logoutSuccessHandler ) { this . logoutSuccessUrl = null ; this . customLogoutSuccess = true ; this . logoutSuccessHandler = logoutSuccessHandler ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a default { @link LogoutSuccessHandler } to be used which prefers being invoked for the provided { @link RequestMatcher } . If no { @link LogoutSuccessHandler } is specified a { @link SimpleUrlLogoutSuccessHandler } will be used . If any default { @link LogoutSuccessHandler } instances are configured then a { @link DelegatingLogoutSuccessHandler } will be used that defaults to a { @link SimpleUrlLogoutSuccessHandler } . [CODESPLIT] public LogoutConfigurer < H > defaultLogoutSuccessHandlerFor ( LogoutSuccessHandler handler , RequestMatcher preferredMatcher ) { Assert . notNull ( handler , \"handler cannot be null\" ) ; Assert . notNull ( preferredMatcher , \"preferredMatcher cannot be null\" ) ; this . defaultLogoutSuccessHandlerMappings . put ( preferredMatcher , handler ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link LogoutSuccessHandler } if not null otherwise creates a new { @link SimpleUrlLogoutSuccessHandler } using the { @link #logoutSuccessUrl ( String ) } . [CODESPLIT] private LogoutSuccessHandler getLogoutSuccessHandler ( ) { LogoutSuccessHandler handler = this . logoutSuccessHandler ; if ( handler == null ) { handler = createDefaultSuccessHandler ( ) ; } return handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link LogoutFilter } using the { @link LogoutHandler } instances the { @link #logoutSuccessHandler ( LogoutSuccessHandler ) } and the { @link #logoutUrl ( String ) } . [CODESPLIT] private LogoutFilter createLogoutFilter ( H http ) throws Exception { logoutHandlers . add ( contextLogoutHandler ) ; LogoutHandler [ ] handlers = logoutHandlers . toArray ( new LogoutHandler [ logoutHandlers . size ( ) ] ) ; LogoutFilter result = new LogoutFilter ( getLogoutSuccessHandler ( ) , handlers ) ; result . setLogoutRequestMatcher ( getLogoutRequestMatcher ( http ) ) ; result = postProcess ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public Collection < ConfigAttribute > getAttributes ( Method method , Class < ? > targetClass ) { DefaultCacheKey cacheKey = new DefaultCacheKey ( method , targetClass ) ; synchronized ( attributeCache ) { Collection < ConfigAttribute > cached = attributeCache . get ( cacheKey ) ; // Check for canonical value indicating there is no config attribute, if ( cached != null ) { return cached ; } // No cached value, so query the sources to find a result Collection < ConfigAttribute > attributes = null ; for ( MethodSecurityMetadataSource s : methodSecurityMetadataSources ) { attributes = s . getAttributes ( method , targetClass ) ; if ( attributes != null && ! attributes . isEmpty ( ) ) { break ; } } // Put it in the cache. if ( attributes == null || attributes . isEmpty ( ) ) { this . attributeCache . put ( cacheKey , NULL_CONFIG_ATTRIBUTE ) ; return NULL_CONFIG_ATTRIBUTE ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Caching method [\" + cacheKey + \"] with attributes \" + attributes ) ; } this . attributeCache . put ( cacheKey , attributes ) ; return attributes ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] private byte [ ] combineHashAndSalt ( byte [ ] hash , byte [ ] salt ) { if ( salt == null ) { return hash ; } byte [ ] hashAndSalt = new byte [ hash . length + salt . length ] ; System . arraycopy ( hash , 0 , hashAndSalt , 0 , hash . length ) ; System . arraycopy ( salt , 0 , hashAndSalt , hash . length , salt . length ) ; return hashAndSalt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the hash of password ( and salt bytes if supplied ) and returns a base64 encoded concatenation of the hash and salt prefixed with { SHA } ( or { SSHA } if salt was used ) . [CODESPLIT] public String encode ( CharSequence rawPass ) { byte [ ] salt = this . saltGenerator . generateKey ( ) ; return encode ( rawPass , salt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the validity of an unencoded password against an encoded one in the form { SSHA } sQuQF8vj8Eg2Y1hPdh3bkQhCKQBgjhQI . [CODESPLIT] public boolean matches ( CharSequence rawPassword , String encodedPassword ) { return matches ( rawPassword == null ? null : rawPassword . toString ( ) , encodedPassword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the hash prefix or null if there isn t one . [CODESPLIT] private String extractPrefix ( String encPass ) { if ( ! encPass . startsWith ( \"{\" ) ) { return null ; } int secondBrace = encPass . lastIndexOf ( ' ' ) ; if ( secondBrace < 0 ) { throw new IllegalArgumentException ( \"Couldn't find closing brace for SHA prefix\" ) ; } return encPass . substring ( 0 , secondBrace + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Demonstrates that { @link HttpServletRequest#authenticate ( HttpServletResponse ) } will send the user to the log in page configured within Spring Security if the user is not already authenticated . [CODESPLIT] @ RequestMapping ( \"/authenticate\" ) public String authenticate ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { boolean authenticate = request . authenticate ( response ) ; return authenticate ? \"index\" : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Demonstrates that you can authenticate with Spring Security using { @link HttpServletRequest#login ( String String ) } . [CODESPLIT] @ RequestMapping ( value = \"/login\" , method = RequestMethod . POST ) public String login ( HttpServletRequest request , HttpServletResponse response , @ ModelAttribute LoginForm loginForm , BindingResult result ) throws ServletException { try { request . login ( loginForm . getUsername ( ) , loginForm . getPassword ( ) ) ; } catch ( ServletException authenticationFailed ) { result . rejectValue ( null , \"authentication.failed\" , authenticationFailed . getMessage ( ) ) ; return \"login\" ; } return \"redirect:/\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Demonstrates that invoking { [CODESPLIT] @ RequestMapping ( \"/logout\" ) public String logout ( HttpServletRequest request , HttpServletResponse response , RedirectAttributes redirect ) throws ServletException { request . logout ( ) ; return \"redirect:/\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Demonstrates Spring Security with { [CODESPLIT] @ RequestMapping ( \"/async\" ) public void asynch ( HttpServletRequest request , HttpServletResponse response ) { final AsyncContext async = request . startAsync ( ) ; async . start ( new Runnable ( ) { public void run ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; try { final HttpServletResponse asyncResponse = ( HttpServletResponse ) async . getResponse ( ) ; asyncResponse . setStatus ( HttpServletResponse . SC_OK ) ; asyncResponse . getWriter ( ) . write ( String . valueOf ( authentication ) ) ; async . complete ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Always returns a 403 error code to the client . [CODESPLIT] public void commence ( HttpServletRequest request , HttpServletResponse response , AuthenticationException arg2 ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Pre-authenticated entry point called. Rejecting access\" ) ; } response . sendError ( HttpServletResponse . SC_FORBIDDEN , \"Access Denied\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Object decide ( Authentication authentication , Object object , Collection < ConfigAttribute > config , Object returnedObject ) throws AccessDeniedException { if ( returnedObject == null ) { logger . debug ( \"Return object is null, skipping\" ) ; return null ; } for ( ConfigAttribute attr : config ) { if ( ! this . supports ( attr ) ) { continue ; } // Need to process the Collection for this invocation Filterer filterer ; if ( returnedObject instanceof Collection ) { filterer = new CollectionFilterer ( ( Collection ) returnedObject ) ; } else if ( returnedObject . getClass ( ) . isArray ( ) ) { filterer = new ArrayFilterer ( ( Object [ ] ) returnedObject ) ; } else { throw new AuthorizationServiceException ( \"A Collection or an array (or null) was required as the \" + \"returnedObject, but the returnedObject was: \" + returnedObject ) ; } // Locate unauthorised Collection elements for ( Object domainObject : filterer ) { // Ignore nulls or entries which aren't instances of the configured domain // object class if ( domainObject == null || ! getProcessDomainObjectClass ( ) . isAssignableFrom ( domainObject . getClass ( ) ) ) { continue ; } if ( ! hasPermission ( authentication , domainObject ) ) { filterer . remove ( domainObject ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Principal is NOT authorised for element: \" + domainObject ) ; } } } return filterer . getFilteredObject ( ) ; } return returnedObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether a path is normalized ( doesn t contain path traversal sequences like . / / .. / or / . ) [CODESPLIT] private boolean isNormalized ( String path ) { if ( path == null ) { return true ; } for ( int j = path . length ( ) ; j > 0 ; ) { int i = path . lastIndexOf ( ' ' , j - 1 ) ; int gap = j - i ; if ( gap == 2 && path . charAt ( i + 1 ) == ' ' ) { // \".\", \"/./\" or \"/.\" return false ; } else if ( gap == 3 && path . charAt ( i + 1 ) == ' ' && path . charAt ( i + 2 ) == ' ' ) { return false ; } j = i ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the filter list for possible errors and logs them [CODESPLIT] private void checkFilterStack ( List < Filter > filters ) { checkForDuplicates ( SecurityContextPersistenceFilter . class , filters ) ; checkForDuplicates ( UsernamePasswordAuthenticationFilter . class , filters ) ; checkForDuplicates ( SessionManagementFilter . class , filters ) ; checkForDuplicates ( BasicAuthenticationFilter . class , filters ) ; checkForDuplicates ( SecurityContextHolderAwareRequestFilter . class , filters ) ; checkForDuplicates ( JaasApiIntegrationFilter . class , filters ) ; checkForDuplicates ( ExceptionTranslationFilter . class , filters ) ; checkForDuplicates ( FilterSecurityInterceptor . class , filters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks for the common error of having a login page URL protected by the security interceptor [CODESPLIT] private void checkLoginPageIsntProtected ( FilterChainProxy fcp , List < Filter > filterStack ) { ExceptionTranslationFilter etf = getFilter ( ExceptionTranslationFilter . class , filterStack ) ; if ( etf == null || ! ( etf . getAuthenticationEntryPoint ( ) instanceof LoginUrlAuthenticationEntryPoint ) ) { return ; } String loginPage = ( ( LoginUrlAuthenticationEntryPoint ) etf . getAuthenticationEntryPoint ( ) ) . getLoginFormUrl ( ) ; logger . info ( \"Checking whether login URL '\" + loginPage + \"' is accessible with your configuration\" ) ; FilterInvocation loginRequest = new FilterInvocation ( loginPage , \"POST\" ) ; List < Filter > filters = null ; try { filters = fcp . getFilters ( loginPage ) ; } catch ( Exception e ) { // May happen legitimately if a filter-chain request matcher requires more // request data than that provided // by the dummy request used when creating the filter invocation. logger . info ( \"Failed to obtain filter chain information for the login page. Unable to complete check.\" ) ; } if ( filters == null || filters . isEmpty ( ) ) { logger . debug ( \"Filter chain is empty for the login page\" ) ; return ; } if ( getFilter ( DefaultLoginPageGeneratingFilter . class , filters ) != null ) { logger . debug ( \"Default generated login page is in use\" ) ; return ; } FilterSecurityInterceptor fsi = getFilter ( FilterSecurityInterceptor . class , filters ) ; FilterInvocationSecurityMetadataSource fids = fsi . getSecurityMetadataSource ( ) ; Collection < ConfigAttribute > attributes = fids . getAttributes ( loginRequest ) ; if ( attributes == null ) { logger . debug ( \"No access attributes defined for login page URL\" ) ; if ( fsi . isRejectPublicInvocations ( ) ) { logger . warn ( \"FilterSecurityInterceptor is configured to reject public invocations.\" + \" Your login page may not be accessible.\" ) ; } return ; } AnonymousAuthenticationFilter anonPF = getFilter ( AnonymousAuthenticationFilter . class , filters ) ; if ( anonPF == null ) { logger . warn ( \"The login page is being protected by the filter chain, but you don't appear to have\" + \" anonymous authentication enabled. This is almost certainly an error.\" ) ; return ; } // Simulate an anonymous access with the supplied attributes. AnonymousAuthenticationToken token = new AnonymousAuthenticationToken ( \"key\" , anonPF . getPrincipal ( ) , anonPF . getAuthorities ( ) ) ; try { fsi . getAccessDecisionManager ( ) . decide ( token , loginRequest , attributes ) ; } catch ( AccessDeniedException e ) { logger . warn ( \"Anonymous access to the login page doesn't appear to be enabled. This is almost certainly \" + \"an error. Please check your configuration allows unauthenticated access to the configured \" + \"login page. (Simulated access was rejected: \" + e + \")\" ) ; } catch ( Exception e ) { // May happen legitimately if a filter-chain request matcher requires more // request data than that provided // by the dummy request used when creating the filter invocation. See SEC-1878 logger . info ( \"Unable to check access to the login page to determine if anonymous access is allowed. This might be an error, but can happen under normal circumstances.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a <code > ThrowableCauseExtractor< / code > for the specified type . <i > Can be used in subclasses overriding { @link #initExtractorMap () } . < / i > [CODESPLIT] protected final void registerExtractor ( Class < ? extends Throwable > throwableType , ThrowableCauseExtractor extractor ) { Assert . notNull ( extractor , \"Invalid extractor: null\" ) ; this . extractorMap . put ( throwableType , extractor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array containing the classes for which extractors are registered . The order of the classes is the order in which comparisons will occur for resolving a matching extractor . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) final Class < ? extends Throwable > [ ] getRegisteredTypes ( ) { Set < Class < ? extends Throwable > > typeList = this . extractorMap . keySet ( ) ; return typeList . toArray ( new Class [ typeList . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines the cause chain of the provided <code > Throwable< / code > . The returned array contains all throwables extracted from the stacktrace using the registered { @link ThrowableCauseExtractor extractors } . The elements of the array are ordered : The first element is the passed in throwable itself . The following elements appear in their order downward the stacktrace . <p > Note : If no { @link ThrowableCauseExtractor } is registered for this instance then the returned array will always only contain the passed in throwable . [CODESPLIT] public final Throwable [ ] determineCauseChain ( Throwable throwable ) { if ( throwable == null ) { throw new IllegalArgumentException ( \"Invalid throwable: null\" ) ; } List < Throwable > chain = new ArrayList <> ( ) ; Throwable currentThrowable = throwable ; while ( currentThrowable != null ) { chain . add ( currentThrowable ) ; currentThrowable = extractCause ( currentThrowable ) ; } return chain . toArray ( new Throwable [ chain . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the cause of the given throwable using an appropriate extractor . [CODESPLIT] private Throwable extractCause ( Throwable throwable ) { for ( Map . Entry < Class < ? extends Throwable > , ThrowableCauseExtractor > entry : extractorMap . entrySet ( ) ) { Class < ? extends Throwable > throwableType = entry . getKey ( ) ; if ( throwableType . isInstance ( throwable ) ) { ThrowableCauseExtractor extractor = entry . getValue ( ) ; return extractor . extractCause ( throwable ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first throwable from the passed in array that is assignable to the provided type . A returned instance is safe to be cast to the specified type . <p > If the passed in array is null or empty this method returns <code > null< / code > . [CODESPLIT] public final Throwable getFirstThrowableOfType ( Class < ? extends Throwable > throwableType , Throwable [ ] chain ) { if ( chain != null ) { for ( Throwable t : chain ) { if ( ( t != null ) && throwableType . isInstance ( t ) ) { return t ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies that the provided throwable is a valid subclass of the provided type ( or of the type itself ) . If <code > expectdBaseType< / code > is <code > null< / code > no check will be performed . <p > Can be used for verification purposes in implementations of { @link ThrowableCauseExtractor extractors } . [CODESPLIT] public static void verifyThrowableHierarchy ( Throwable throwable , Class < ? extends Throwable > expectedBaseType ) { if ( expectedBaseType == null ) { return ; } if ( throwable == null ) { throw new IllegalArgumentException ( \"Invalid throwable: null\" ) ; } Class < ? extends Throwable > throwableType = throwable . getClass ( ) ; if ( ! expectedBaseType . isAssignableFrom ( throwableType ) ) { throw new IllegalArgumentException ( \"Invalid type: '\" + throwableType . getName ( ) + \"'. Has to be a subclass of '\" + expectedBaseType . getName ( ) + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the imports to use if the { [CODESPLIT] private String [ ] getProxyImports ( ) { List < String > result = new ArrayList <> ( ) ; result . add ( AutoProxyRegistrar . class . getName ( ) ) ; result . add ( ReactiveMethodSecurityConfiguration . class . getName ( ) ) ; return result . toArray ( new String [ result . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the default AccessDecisionManager . Adds the special JSR 250 voter jsr - 250 is enabled and an expression voter if expression - based access control is enabled . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) private String registerAccessManager ( ParserContext pc , boolean jsr250Enabled , BeanDefinition expressionVoter ) { BeanDefinitionBuilder accessMgrBuilder = BeanDefinitionBuilder . rootBeanDefinition ( AffirmativeBased . class ) ; ManagedList voters = new ManagedList ( 4 ) ; if ( expressionVoter != null ) { voters . add ( expressionVoter ) ; } voters . add ( new RootBeanDefinition ( RoleVoter . class ) ) ; voters . add ( new RootBeanDefinition ( AuthenticatedVoter . class ) ) ; if ( jsr250Enabled ) { voters . add ( new RootBeanDefinition ( Jsr250Voter . class ) ) ; } accessMgrBuilder . addConstructorArgValue ( voters ) ; BeanDefinition accessManager = accessMgrBuilder . getBeanDefinition ( ) ; String id = pc . getReaderContext ( ) . generateBeanName ( accessManager ) ; pc . registerBeanComponent ( new BeanComponentDefinition ( accessManager , id ) ) ; return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the policy directive ( s ) to be used in the response header . [CODESPLIT] public void setPolicyDirectives ( String policyDirectives ) { Assert . hasLength ( policyDirectives , \"policyDirectives must not be null or empty\" ) ; this . policyDirectives = policyDirectives ; this . delegate = createDelegate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter } used for converting the { @link OAuth2AuthorizationCodeGrantRequest } to a { @link RequestEntity } representation of the OAuth 2 . 0 Access Token Request . [CODESPLIT] public void setRequestEntityConverter ( Converter < OAuth2AuthorizationCodeGrantRequest , RequestEntity < ? > > requestEntityConverter ) { Assert . notNull ( requestEntityConverter , \"requestEntityConverter cannot be null\" ) ; this . requestEntityConverter = requestEntityConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets additional exception to event mappings . These are automatically merged with the default exception to event mappings that <code > ProviderManager< / code > defines . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public void setAdditionalExceptionMappings ( Properties additionalExceptionMappings ) { Assert . notNull ( additionalExceptionMappings , \"The exceptionMappings object must not be null\" ) ; for ( Object exceptionClass : additionalExceptionMappings . keySet ( ) ) { String eventClass = ( String ) additionalExceptionMappings . get ( exceptionClass ) ; try { Class < ? > clazz = getClass ( ) . getClassLoader ( ) . loadClass ( eventClass ) ; Assert . isAssignable ( AbstractAuthenticationFailureEvent . class , clazz ) ; addMapping ( ( String ) exceptionClass , ( Class < ? extends AbstractAuthenticationFailureEvent > ) clazz ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( \"Failed to load authentication event class \" + eventClass ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the { @link ClientRequest#attributes () } to include the { @link OAuth2AuthorizedClient } to be used for providing the Bearer Token . Example usage : [CODESPLIT] public static Consumer < Map < String , Object > > serverWebExchange ( ServerWebExchange serverWebExchange ) { return attributes -> attributes . put ( SERVER_WEB_EXCHANGE_ATTR_NAME , serverWebExchange ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the HttpSessionEvent by publishing a { @link HttpSessionCreatedEvent } to the application appContext . [CODESPLIT] public void sessionCreated ( HttpSessionEvent event ) { HttpSessionCreatedEvent e = new HttpSessionCreatedEvent ( event . getSession ( ) ) ; Log log = LogFactory . getLog ( LOGGER_NAME ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Publishing event: \" + e ) ; } getContext ( event . getSession ( ) . getServletContext ( ) ) . publishEvent ( e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the HttpSessionEvent by publishing a { @link HttpSessionDestroyedEvent } to the application appContext . [CODESPLIT] public void sessionDestroyed ( HttpSessionEvent event ) { HttpSessionDestroyedEvent e = new HttpSessionDestroyedEvent ( event . getSession ( ) ) ; Log log = LogFactory . getLog ( LOGGER_NAME ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Publishing event: \" + e ) ; } getContext ( event . getSession ( ) . getServletContext ( ) ) . publishEvent ( e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of GrantedAuthority objects to a Set . [CODESPLIT] public static Set < String > authorityListToSet ( Collection < ? extends GrantedAuthority > userAuthorities ) { Assert . notNull ( userAuthorities , \"userAuthorities cannot be null\" ) ; Set < String > set = new HashSet <> ( userAuthorities . size ( ) ) ; for ( GrantedAuthority authority : userAuthorities ) { set . add ( authority . getAuthority ( ) ) ; } return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constant time comparison to prevent against timing attacks . [CODESPLIT] private boolean matches ( byte [ ] expected , byte [ ] actual ) { if ( expected . length != actual . length ) { return false ; } int result = 0 ; for ( int i = 0 ; i < expected . length ; i ++ ) { result |= expected [ i ] ^ actual [ i ] ; } return result == 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link RequestEntity } used for the Access Token Request . [CODESPLIT] @ Override public RequestEntity < ? > convert ( OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest ) { ClientRegistration clientRegistration = authorizationCodeGrantRequest . getClientRegistration ( ) ; HttpHeaders headers = OAuth2AuthorizationGrantRequestEntityUtils . getTokenRequestHeaders ( clientRegistration ) ; MultiValueMap < String , String > formParameters = this . buildFormParameters ( authorizationCodeGrantRequest ) ; URI uri = UriComponentsBuilder . fromUriString ( clientRegistration . getProviderDetails ( ) . getTokenUri ( ) ) . build ( ) . toUri ( ) ; return new RequestEntity <> ( formParameters , headers , HttpMethod . POST , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link MultiValueMap } of the form parameters used for the Access Token Request body . [CODESPLIT] private MultiValueMap < String , String > buildFormParameters ( OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest ) { ClientRegistration clientRegistration = authorizationCodeGrantRequest . getClientRegistration ( ) ; OAuth2AuthorizationExchange authorizationExchange = authorizationCodeGrantRequest . getAuthorizationExchange ( ) ; MultiValueMap < String , String > formParameters = new LinkedMultiValueMap <> ( ) ; formParameters . add ( OAuth2ParameterNames . GRANT_TYPE , authorizationCodeGrantRequest . getGrantType ( ) . getValue ( ) ) ; formParameters . add ( OAuth2ParameterNames . CODE , authorizationExchange . getAuthorizationResponse ( ) . getCode ( ) ) ; String redirectUri = authorizationExchange . getAuthorizationRequest ( ) . getRedirectUri ( ) ; String codeVerifier = authorizationExchange . getAuthorizationRequest ( ) . getAttribute ( PkceParameterNames . CODE_VERIFIER ) ; if ( redirectUri != null ) { formParameters . add ( OAuth2ParameterNames . REDIRECT_URI , redirectUri ) ; } if ( ! ClientAuthenticationMethod . BASIC . equals ( clientRegistration . getClientAuthenticationMethod ( ) ) ) { formParameters . add ( OAuth2ParameterNames . CLIENT_ID , clientRegistration . getClientId ( ) ) ; } if ( ClientAuthenticationMethod . POST . equals ( clientRegistration . getClientAuthenticationMethod ( ) ) ) { formParameters . add ( OAuth2ParameterNames . CLIENT_SECRET , clientRegistration . getClientSecret ( ) ) ; } if ( codeVerifier != null ) { formParameters . add ( PkceParameterNames . CODE_VERIFIER , codeVerifier ) ; } return formParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the base { @code URI } used for authorization requests . [CODESPLIT] public ImplicitGrantConfigurer < B > authorizationRequestBaseUri ( String authorizationRequestBaseUri ) { Assert . hasText ( authorizationRequestBaseUri , \"authorizationRequestBaseUri cannot be empty\" ) ; this . authorizationRequestBaseUri = authorizationRequestBaseUri ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the repository of client registrations . [CODESPLIT] public ImplicitGrantConfigurer < B > clientRegistrationRepository ( ClientRegistrationRepository clientRegistrationRepository ) { Assert . notNull ( clientRegistrationRepository , \"clientRegistrationRepository cannot be null\" ) ; this . getBuilder ( ) . setSharedObject ( ClientRegistrationRepository . class , clientRegistrationRepository ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the redirect or forward to the { [CODESPLIT] public void onAuthenticationFailure ( HttpServletRequest request , HttpServletResponse response , AuthenticationException exception ) throws IOException , ServletException { if ( defaultFailureUrl == null ) { logger . debug ( \"No failure URL set, sending 401 Unauthorized error\" ) ; response . sendError ( HttpStatus . UNAUTHORIZED . value ( ) , HttpStatus . UNAUTHORIZED . getReasonPhrase ( ) ) ; } else { saveException ( request , exception ) ; if ( forwardToDestination ) { logger . debug ( \"Forwarding to \" + defaultFailureUrl ) ; request . getRequestDispatcher ( defaultFailureUrl ) . forward ( request , response ) ; } else { logger . debug ( \"Redirecting to \" + defaultFailureUrl ) ; redirectStrategy . sendRedirect ( request , response , defaultFailureUrl ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Caches the { [CODESPLIT] protected final void saveException ( HttpServletRequest request , AuthenticationException exception ) { if ( forwardToDestination ) { request . setAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION , exception ) ; } else { HttpSession session = request . getSession ( false ) ; if ( session != null || allowSessionCreation ) { request . getSession ( ) . setAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION , exception ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The URL which will be used as the failure destination . [CODESPLIT] public void setDefaultFailureUrl ( String defaultFailureUrl ) { Assert . isTrue ( UrlUtils . isValidRedirectUrl ( defaultFailureUrl ) , ( ) -> \"'\" + defaultFailureUrl + \"' is not a valid redirect URL\" ) ; this . defaultFailureUrl = defaultFailureUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate the given PreAuthenticatedAuthenticationToken . <p > If the principal contained in the authentication object is null the request will be ignored to allow other providers to authenticate it . [CODESPLIT] public Authentication authenticate ( Authentication authentication ) throws AuthenticationException { if ( ! supports ( authentication . getClass ( ) ) ) { return null ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"PreAuthenticated authentication request: \" + authentication ) ; } if ( authentication . getPrincipal ( ) == null ) { logger . debug ( \"No pre-authenticated principal found in request.\" ) ; if ( throwExceptionWhenTokenRejected ) { throw new BadCredentialsException ( \"No pre-authenticated principal found in request.\" ) ; } return null ; } if ( authentication . getCredentials ( ) == null ) { logger . debug ( \"No pre-authenticated credentials found in request.\" ) ; if ( throwExceptionWhenTokenRejected ) { throw new BadCredentialsException ( \"No pre-authenticated credentials found in request.\" ) ; } return null ; } UserDetails ud = preAuthenticatedUserDetailsService . loadUserDetails ( ( PreAuthenticatedAuthenticationToken ) authentication ) ; userDetailsChecker . check ( ud ) ; PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken ( ud , authentication . getCredentials ( ) , ud . getAuthorities ( ) ) ; result . setDetails ( authentication . getDetails ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a Function used to resolve a Map of the hidden inputs where the key is the name of the input and the value is the value of the input . Typically this is used to resolve the CSRF token . [CODESPLIT] public void setResolveHiddenInputs ( Function < HttpServletRequest , Map < String , String > > resolveHiddenInputs ) { Assert . notNull ( resolveHiddenInputs , \"resolveHiddenInputs cannot be null\" ) ; this . resolveHiddenInputs = resolveHiddenInputs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Introspect and validate the opaque <a href = https : // tools . ietf . org / html / rfc6750#section - 1 . 2 target = _blank > Bearer Token< / a > . [CODESPLIT] @ Override public Authentication authenticate ( Authentication authentication ) throws AuthenticationException { if ( ! ( authentication instanceof BearerTokenAuthenticationToken ) ) { return null ; } BearerTokenAuthenticationToken bearer = ( BearerTokenAuthenticationToken ) authentication ; Map < String , Object > claims ; try { claims = this . introspectionClient . introspect ( bearer . getToken ( ) ) ; } catch ( OAuth2IntrospectionException failed ) { OAuth2Error invalidToken = invalidToken ( failed . getMessage ( ) ) ; throw new OAuth2AuthenticationException ( invalidToken ) ; } AbstractAuthenticationToken result = convert ( bearer . getToken ( ) , claims ) ; result . setDetails ( bearer . getDetails ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a UserDetails object based on the user name contained in the given token and the GrantedAuthorities as returned by the GrantedAuthoritiesContainer implementation as returned by the token . getDetails () method . [CODESPLIT] public final UserDetails loadUserDetails ( PreAuthenticatedAuthenticationToken token ) throws AuthenticationException { Assert . notNull ( token . getDetails ( ) , \"token.getDetails() cannot be null\" ) ; Assert . isInstanceOf ( GrantedAuthoritiesContainer . class , token . getDetails ( ) ) ; Collection < ? extends GrantedAuthority > authorities = ( ( GrantedAuthoritiesContainer ) token . getDetails ( ) ) . getGrantedAuthorities ( ) ; return createUserDetails ( token , authorities ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the final <tt > UserDetails< / tt > object . Can be overridden to customize the contents . [CODESPLIT] protected UserDetails createUserDetails ( Authentication token , Collection < ? extends GrantedAuthority > authorities ) { return new User ( token . getName ( ) , \"N/A\" , true , true , true , true , authorities ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a failure { @link OAuth2TokenValidatorResult } with the provided detail [CODESPLIT] public static OAuth2TokenValidatorResult failure ( Collection < OAuth2Error > errors ) { if ( errors . isEmpty ( ) ) { return NO_ERRORS ; } return new OAuth2TokenValidatorResult ( errors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link RequestCache } to use . If one is defined using { @link #requestCache ( org . springframework . security . web . savedrequest . RequestCache ) } then it is used . Otherwise an attempt to find a { @link RequestCache } shared object is made . If that fails an { @link HttpSessionRequestCache } is used [CODESPLIT] private RequestCache getRequestCache ( H http ) { RequestCache result = http . getSharedObject ( RequestCache . class ) ; if ( result != null ) { return result ; } result = getBeanOrNull ( RequestCache . class ) ; if ( result != null ) { return result ; } HttpSessionRequestCache defaultCache = new HttpSessionRequestCache ( ) ; defaultCache . setRequestMatcher ( createDefaultSavedRequestMatcher ( http ) ) ; return defaultCache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public static String buildFullRequestUrl ( HttpServletRequest r ) { return buildFullRequestUrl ( r . getScheme ( ) , r . getServerName ( ) , r . getServerPort ( ) , r . getRequestURI ( ) , r . getQueryString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the full URL the client used to make the request . <p > Note that the server port will not be shown if it is the default server port for HTTP or HTTPS ( 80 and 443 respectively ) . [CODESPLIT] public static String buildFullRequestUrl ( String scheme , String serverName , int serverPort , String requestURI , String queryString ) { scheme = scheme . toLowerCase ( ) ; StringBuilder url = new StringBuilder ( ) ; url . append ( scheme ) . append ( \"://\" ) . append ( serverName ) ; // Only add port if not default if ( \"http\" . equals ( scheme ) ) { if ( serverPort != 80 ) { url . append ( \":\" ) . append ( serverPort ) ; } } else if ( \"https\" . equals ( scheme ) ) { if ( serverPort != 443 ) { url . append ( \":\" ) . append ( serverPort ) ; } } // Use the requestURI as it is encoded (RFC 3986) and hence suitable for // redirects. url . append ( requestURI ) ; if ( queryString != null ) { url . append ( \"?\" ) . append ( queryString ) ; } return url . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the web application - specific fragment of the request URL . <p > Under normal spec conditions [CODESPLIT] public static String buildRequestUrl ( HttpServletRequest r ) { return buildRequestUrl ( r . getServletPath ( ) , r . getRequestURI ( ) , r . getContextPath ( ) , r . getPathInfo ( ) , r . getQueryString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the web application - specific fragment of the URL . [CODESPLIT] private static String buildRequestUrl ( String servletPath , String requestURI , String contextPath , String pathInfo , String queryString ) { StringBuilder url = new StringBuilder ( ) ; if ( servletPath != null ) { url . append ( servletPath ) ; if ( pathInfo != null ) { url . append ( pathInfo ) ; } } else { url . append ( requestURI . substring ( contextPath . length ( ) ) ) ; } if ( queryString != null ) { url . append ( \"?\" ) . append ( queryString ) ; } return url . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides if a URL is absolute based on whether it contains a valid scheme name as defined in RFC 1738 . [CODESPLIT] public static boolean isAbsoluteUrl ( String url ) { if ( url == null ) { return false ; } final Pattern ABSOLUTE_URL = Pattern . compile ( \"\\\\A[a-z0-9.+-]+://.*\" , Pattern . CASE_INSENSITIVE ) ; return ABSOLUTE_URL . matcher ( url ) . matches ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through the patterns stored in the map and returns the list of attributes defined for the first match . If no match is found returns an empty list . [CODESPLIT] public List < OpenIDAttribute > createAttributeList ( String identifier ) { for ( Map . Entry < Pattern , List < OpenIDAttribute > > entry : idToAttributes . entrySet ( ) ) { if ( entry . getKey ( ) . matcher ( identifier ) . matches ( ) ) { return entry . getValue ( ) ; } } return Collections . emptyList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . hasLength ( key , \"key must have length\" ) ; Assert . notNull ( principal , \"Anonymous authentication principal must be set\" ) ; Assert . notNull ( authorities , \"Anonymous authorities must be set\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a representation of the active bits in the presented mask with each active bit being denoted by the passed character . <p > Inactive bits will be denoted by character { @link Permission#RESERVED_OFF } . [CODESPLIT] public static String printBinary ( int mask , char code ) { Assert . doesNotContain ( Character . toString ( code ) , Character . toString ( Permission . RESERVED_ON ) , ( ) -> Permission . RESERVED_ON + \" is a reserved character code\" ) ; Assert . doesNotContain ( Character . toString ( code ) , Character . toString ( Permission . RESERVED_OFF ) , ( ) -> Permission . RESERVED_OFF + \" is a reserved character code\" ) ; return printBinary ( mask , Permission . RESERVED_ON , Permission . RESERVED_OFF ) . replace ( Permission . RESERVED_ON , code ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the raw type from the database into the right Java type . For most applications the raw type will be Long for some applications it could be String . [CODESPLIT] Serializable identifierFrom ( Serializable identifier , ResultSet resultSet ) throws SQLException { if ( isString ( identifier ) && hasValidClassIdType ( resultSet ) && canConvertFromStringTo ( classIdTypeFrom ( resultSet ) ) ) { identifier = convertFromStringTo ( ( String ) identifier , classIdTypeFrom ( resultSet ) ) ; } else { // Assume it should be a Long type identifier = convertToLong ( identifier ) ; } return identifier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to a { [CODESPLIT] private Long convertToLong ( Serializable identifier ) { Long idAsLong ; if ( canConvertFromStringTo ( Long . class ) ) { idAsLong = conversionService . convert ( identifier , Long . class ) ; } else { idAsLong = Long . valueOf ( identifier . toString ( ) ) ; } return idAsLong ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > <b > WARNING : < / b > This method is considered unsafe for production and is only intended for sample applications . < / p > <p > Creates a user and automatically encodes the provided password using { @code PasswordEncoderFactories . createDelegatingPasswordEncoder () } . For example : < / p > [CODESPLIT] @ Deprecated public static UserBuilder withDefaultPasswordEncoder ( ) { logger . warn ( \"User.withDefaultPasswordEncoder() is considered unsafe for production and is only intended for sample applications.\" ) ; PasswordEncoder encoder = PasswordEncoderFactories . createDelegatingPasswordEncoder ( ) ; return builder ( ) . passwordEncoder ( encoder :: encode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ClientRegistration . Builder } using the provided <a href = https : // openid . net / specs / openid - connect - core - 1_0 . html#IssuerIdentifier > Issuer< / a > by making an <a href = https : // openid . net / specs / openid - connect - discovery - 1_0 . html#ProviderConfigurationRequest > OpenID Provider Configuration Request< / a > and using the values in the <a href = https : // openid . net / specs / openid - connect - discovery - 1_0 . html#ProviderConfigurationResponse > OpenID Provider Configuration Response< / a > to initialize the { @link ClientRegistration . Builder } . [CODESPLIT] public static ClientRegistration . Builder fromOidcIssuerLocation ( String issuer ) { String openidConfiguration = getOpenidConfiguration ( issuer ) ; OIDCProviderMetadata metadata = parse ( openidConfiguration ) ; String metadataIssuer = metadata . getIssuer ( ) . getValue ( ) ; if ( ! issuer . equals ( metadataIssuer ) ) { throw new IllegalStateException ( \"The Issuer \\\"\" + metadataIssuer + \"\\\" provided in the OpenID Configuration did not match the requested issuer \\\"\" + issuer + \"\\\"\" ) ; } String name = URI . create ( issuer ) . getHost ( ) ; ClientAuthenticationMethod method = getClientAuthenticationMethod ( issuer , metadata . getTokenEndpointAuthMethods ( ) ) ; List < GrantType > grantTypes = metadata . getGrantTypes ( ) ; // If null, the default includes authorization_code if ( grantTypes != null && ! grantTypes . contains ( GrantType . AUTHORIZATION_CODE ) ) { throw new IllegalArgumentException ( \"Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \\\"\" + issuer + \"\\\" returned a configuration of \" + grantTypes ) ; } List < String > scopes = getScopes ( metadata ) ; Map < String , Object > configurationMetadata = new LinkedHashMap <> ( metadata . toJSONObject ( ) ) ; return ClientRegistration . withRegistrationId ( name ) . userNameAttributeName ( IdTokenClaimNames . SUB ) . scope ( scopes ) . authorizationGrantType ( AuthorizationGrantType . AUTHORIZATION_CODE ) . clientAuthenticationMethod ( method ) . redirectUriTemplate ( \"{baseUrl}/{action}/oauth2/code/{registrationId}\" ) . authorizationUri ( metadata . getAuthorizationEndpointURI ( ) . toASCIIString ( ) ) . jwkSetUri ( metadata . getJWKSetURI ( ) . toASCIIString ( ) ) . providerConfigurationMetadata ( configurationMetadata ) . userInfoUri ( metadata . getUserInfoEndpointURI ( ) . toASCIIString ( ) ) . tokenUri ( metadata . getTokenEndpointURI ( ) . toASCIIString ( ) ) . clientName ( issuer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public Authentication buildRunAs ( Authentication authentication , Object object , Collection < ConfigAttribute > config ) { return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the { @link CsrfToken } [CODESPLIT] @ Override public Mono < Void > logout ( WebFilterExchange exchange , Authentication authentication ) { return this . csrfTokenRepository . saveToken ( exchange . getExchange ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut to specify the { @link AccessDeniedHandler } to be used is a specific error page [CODESPLIT] public ExceptionHandlingConfigurer < H > accessDeniedPage ( String accessDeniedUrl ) { AccessDeniedHandlerImpl accessDeniedHandler = new AccessDeniedHandlerImpl ( ) ; accessDeniedHandler . setErrorPage ( accessDeniedUrl ) ; return accessDeniedHandler ( accessDeniedHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a default { @link AccessDeniedHandler } to be used which prefers being invoked for the provided { @link RequestMatcher } . If only a single default { @link AccessDeniedHandler } is specified it will be what is used for the default { @link AccessDeniedHandler } . If multiple default { @link AccessDeniedHandler } instances are configured then a { @link RequestMatcherDelegatingAccessDeniedHandler } will be used . [CODESPLIT] public ExceptionHandlingConfigurer < H > defaultAccessDeniedHandlerFor ( AccessDeniedHandler deniedHandler , RequestMatcher preferredMatcher ) { this . defaultDeniedHandlerMappings . put ( preferredMatcher , deniedHandler ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a default { @link AuthenticationEntryPoint } to be used which prefers being invoked for the provided { @link RequestMatcher } . If only a single default { @link AuthenticationEntryPoint } is specified it will be what is used for the default { @link AuthenticationEntryPoint } . If multiple default { @link AuthenticationEntryPoint } instances are configured then a { @link DelegatingAuthenticationEntryPoint } will be used . [CODESPLIT] public ExceptionHandlingConfigurer < H > defaultAuthenticationEntryPointFor ( AuthenticationEntryPoint entryPoint , RequestMatcher preferredMatcher ) { this . defaultEntryPointMappings . put ( preferredMatcher , entryPoint ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] AccessDeniedHandler getAccessDeniedHandler ( H http ) { AccessDeniedHandler deniedHandler = this . accessDeniedHandler ; if ( deniedHandler == null ) { deniedHandler = createDefaultDeniedHandler ( http ) ; } return deniedHandler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] AuthenticationEntryPoint getAuthenticationEntryPoint ( H http ) { AuthenticationEntryPoint entryPoint = this . authenticationEntryPoint ; if ( entryPoint == null ) { entryPoint = createDefaultEntryPoint ( http ) ; } return entryPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link RequestCache } to use . If one is defined using { @link #requestCache ( org . springframework . security . web . savedrequest . RequestCache ) } then it is used . Otherwise an attempt to find a { @link RequestCache } shared object is made . If that fails an { @link HttpSessionRequestCache } is used [CODESPLIT] private RequestCache getRequestCache ( H http ) { RequestCache result = http . getSharedObject ( RequestCache . class ) ; if ( result != null ) { return result ; } return new HttpSessionRequestCache ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the supplied { @link Map } of role name to implied role name ( s ) to a string representation understood by { @link RoleHierarchyImpl#setHierarchy ( String ) } . The map key is the role name and the map value is a { @link List } of implied role name ( s ) . [CODESPLIT] public static String roleHierarchyFromMap ( Map < String , List < String > > roleHierarchyMap ) { Assert . notEmpty ( roleHierarchyMap , \"roleHierarchyMap cannot be empty\" ) ; StringWriter roleHierarchyBuffer = new StringWriter ( ) ; PrintWriter roleHierarchyWriter = new PrintWriter ( roleHierarchyBuffer ) ; for ( Map . Entry < String , List < String > > roleHierarchyEntry : roleHierarchyMap . entrySet ( ) ) { String role = roleHierarchyEntry . getKey ( ) ; List < String > impliedRoles = roleHierarchyEntry . getValue ( ) ; Assert . hasLength ( role , \"role name must be supplied\" ) ; Assert . notEmpty ( impliedRoles , \"implied role name(s) cannot be empty\" ) ; for ( String impliedRole : impliedRoles ) { String roleMapping = role + \" > \" + impliedRole ; roleHierarchyWriter . println ( roleMapping ) ; } } return roleHierarchyBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public MutableAcl createAcl ( ObjectIdentity objectIdentity ) throws AlreadyExistsException { Assert . notNull ( objectIdentity , \"Object Identity required\" ) ; // Check this object identity hasn't already been persisted if ( retrieveObjectIdentityPrimaryKey ( objectIdentity ) != null ) { throw new AlreadyExistsException ( \"Object identity '\" + objectIdentity + \"' already exists\" ) ; } // Need to retrieve the current principal, in order to know who \"owns\" this ACL // (can be changed later on) Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; PrincipalSid sid = new PrincipalSid ( auth ) ; // Create the acl_object_identity row createObjectIdentity ( objectIdentity , sid ) ; // Retrieve the ACL via superclass (ensures cache registration, proper retrieval // etc) Acl acl = readAclById ( objectIdentity ) ; Assert . isInstanceOf ( MutableAcl . class , acl , \"MutableAcl should be been returned\" ) ; return ( MutableAcl ) acl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new row in acl_entry for every ACE defined in the passed MutableAcl object . [CODESPLIT] protected void createEntries ( final MutableAcl acl ) { if ( acl . getEntries ( ) . isEmpty ( ) ) { return ; } jdbcOperations . batchUpdate ( insertEntry , new BatchPreparedStatementSetter ( ) { public int getBatchSize ( ) { return acl . getEntries ( ) . size ( ) ; } public void setValues ( PreparedStatement stmt , int i ) throws SQLException { AccessControlEntry entry_ = acl . getEntries ( ) . get ( i ) ; Assert . isTrue ( entry_ instanceof AccessControlEntryImpl , \"Unknown ACE class\" ) ; AccessControlEntryImpl entry = ( AccessControlEntryImpl ) entry_ ; stmt . setLong ( 1 , ( ( Long ) acl . getId ( ) ) . longValue ( ) ) ; stmt . setInt ( 2 , i ) ; stmt . setLong ( 3 , createOrRetrieveSidPrimaryKey ( entry . getSid ( ) , true ) . longValue ( ) ) ; stmt . setInt ( 4 , entry . getPermission ( ) . getMask ( ) ) ; stmt . setBoolean ( 5 , entry . isGranting ( ) ) ; stmt . setBoolean ( 6 , entry . isAuditSuccess ( ) ) ; stmt . setBoolean ( 7 , entry . isAuditFailure ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an entry in the acl_object_identity table for the passed ObjectIdentity . The Sid is also necessary as acl_object_identity has defined the sid column as non - null . [CODESPLIT] protected void createObjectIdentity ( ObjectIdentity object , Sid owner ) { Long sidId = createOrRetrieveSidPrimaryKey ( owner , true ) ; Long classId = createOrRetrieveClassPrimaryKey ( object . getType ( ) , true , object . getIdentifier ( ) . getClass ( ) ) ; jdbcOperations . update ( insertObjectIdentity , classId , object . getIdentifier ( ) . toString ( ) , sidId , Boolean . TRUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the primary key from { @code acl_class } creating a new row if needed and the { @code allowCreate } property is { @code true } . [CODESPLIT] protected Long createOrRetrieveClassPrimaryKey ( String type , boolean allowCreate , Class idType ) { List < Long > classIds = jdbcOperations . queryForList ( selectClassPrimaryKey , new Object [ ] { type } , Long . class ) ; if ( ! classIds . isEmpty ( ) ) { return classIds . get ( 0 ) ; } if ( allowCreate ) { if ( ! isAclClassIdSupported ( ) ) { jdbcOperations . update ( insertClass , type ) ; } else { jdbcOperations . update ( insertClass , type , idType . getCanonicalName ( ) ) ; } Assert . isTrue ( TransactionSynchronizationManager . isSynchronizationActive ( ) , \"Transaction must be running\" ) ; return jdbcOperations . queryForObject ( classIdentityQuery , Long . class ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the primary key from acl_sid creating a new row if needed and the allowCreate property is true . [CODESPLIT] protected Long createOrRetrieveSidPrimaryKey ( Sid sid , boolean allowCreate ) { Assert . notNull ( sid , \"Sid required\" ) ; String sidName ; boolean sidIsPrincipal = true ; if ( sid instanceof PrincipalSid ) { sidName = ( ( PrincipalSid ) sid ) . getPrincipal ( ) ; } else if ( sid instanceof GrantedAuthoritySid ) { sidName = ( ( GrantedAuthoritySid ) sid ) . getGrantedAuthority ( ) ; sidIsPrincipal = false ; } else { throw new IllegalArgumentException ( \"Unsupported implementation of Sid\" ) ; } return createOrRetrieveSidPrimaryKey ( sidName , sidIsPrincipal , allowCreate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the primary key from acl_sid creating a new row if needed and the allowCreate property is true . [CODESPLIT] protected Long createOrRetrieveSidPrimaryKey ( String sidName , boolean sidIsPrincipal , boolean allowCreate ) { List < Long > sidIds = jdbcOperations . queryForList ( selectSidPrimaryKey , new Object [ ] { Boolean . valueOf ( sidIsPrincipal ) , sidName } , Long . class ) ; if ( ! sidIds . isEmpty ( ) ) { return sidIds . get ( 0 ) ; } if ( allowCreate ) { jdbcOperations . update ( insertSid , Boolean . valueOf ( sidIsPrincipal ) , sidName ) ; Assert . isTrue ( TransactionSynchronizationManager . isSynchronizationActive ( ) , \"Transaction must be running\" ) ; return jdbcOperations . queryForObject ( sidIdentityQuery , Long . class ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the primary key from the acl_object_identity table for the passed ObjectIdentity . Unlike some other methods in this implementation this method will NOT create a row ( use { @link #createObjectIdentity ( ObjectIdentity Sid ) } instead ) . [CODESPLIT] protected Long retrieveObjectIdentityPrimaryKey ( ObjectIdentity oid ) { try { return jdbcOperations . queryForObject ( selectObjectIdentityPrimaryKey , Long . class , oid . getType ( ) , oid . getIdentifier ( ) . toString ( ) ) ; } catch ( DataAccessException notFound ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation will simply delete all ACEs in the database and recreate them on each invocation of this method . A more comprehensive implementation might use dirty state checking or more likely use ORM capabilities for create update and delete operations of { [CODESPLIT] public MutableAcl updateAcl ( MutableAcl acl ) throws NotFoundException { Assert . notNull ( acl . getId ( ) , \"Object Identity doesn't provide an identifier\" ) ; // Delete this ACL's ACEs in the acl_entry table deleteEntries ( retrieveObjectIdentityPrimaryKey ( acl . getObjectIdentity ( ) ) ) ; // Create this ACL's ACEs in the acl_entry table createEntries ( acl ) ; // Change the mutable columns in acl_object_identity updateObjectIdentity ( acl ) ; // Clear the cache, including children clearCacheIncludingChildren ( acl . getObjectIdentity ( ) ) ; // Retrieve the ACL via superclass (ensures cache registration, proper retrieval // etc) return ( MutableAcl ) super . readAclById ( acl . getObjectIdentity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing acl_object_identity row with new information presented in the passed MutableAcl object . Also will create an acl_sid entry if needed for the Sid that owns the MutableAcl . [CODESPLIT] protected void updateObjectIdentity ( MutableAcl acl ) { Long parentId = null ; if ( acl . getParentAcl ( ) != null ) { Assert . isInstanceOf ( ObjectIdentityImpl . class , acl . getParentAcl ( ) . getObjectIdentity ( ) , \"Implementation only supports ObjectIdentityImpl\" ) ; ObjectIdentityImpl oii = ( ObjectIdentityImpl ) acl . getParentAcl ( ) . getObjectIdentity ( ) ; parentId = retrieveObjectIdentityPrimaryKey ( oii ) ; } Assert . notNull ( acl . getOwner ( ) , \"Owner is required in this implementation\" ) ; Long ownerSid = createOrRetrieveSidPrimaryKey ( acl . getOwner ( ) , true ) ; int count = jdbcOperations . update ( updateObjectIdentity , parentId , ownerSid , Boolean . valueOf ( acl . isEntriesInheriting ( ) ) , acl . getId ( ) ) ; if ( count != 1 ) { throw new NotFoundException ( \"Unable to locate ACL to update\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the current request provided the configuration properties allow it . [CODESPLIT] public void saveRequest ( HttpServletRequest request , HttpServletResponse response ) { if ( requestMatcher . matches ( request ) ) { DefaultSavedRequest savedRequest = new DefaultSavedRequest ( request , portResolver ) ; if ( createSessionAllowed || request . getSession ( false ) != null ) { // Store the HTTP request itself. Used by // AbstractAuthenticationProcessingFilter // for redirection after successful authentication (SEC-29) request . getSession ( ) . setAttribute ( this . sessionAttrName , savedRequest ) ; logger . debug ( \"DefaultSavedRequest added to Session: \" + savedRequest ) ; } } else { logger . debug ( \"Request not saved as configured RequestMatcher did not match\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link DelegatingSecurityContextCallable } and with the given { @link Callable } and { @link SecurityContext } but if the securityContext is null will defaults to the current { @link SecurityContext } on the { @link SecurityContextHolder } [CODESPLIT] public static < V > Callable < V > create ( Callable < V > delegate , SecurityContext securityContext ) { return securityContext == null ? new DelegatingSecurityContextCallable <> ( delegate ) : new DelegatingSecurityContextCallable <> ( delegate , securityContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the { @link LogoutHandler } s used when integrating with { @link HttpServletRequest } with Servlet 3 APIs . Specifically it will be used when { @link HttpServletRequest#logout () } is invoked in order to log the user out . So long as the { @link LogoutHandler } s do not commit the { @link HttpServletResponse } ( expected ) then the user is in charge of handling the response . < / p > <p > If the value is null ( default ) the default container behavior will be retained when invoking { @link HttpServletRequest#logout () } . < / p > [CODESPLIT] public void setLogoutHandlers ( List < LogoutHandler > logoutHandlers ) { this . logoutHandler = CollectionUtils . isEmpty ( logoutHandlers ) ? null : new CompositeLogoutHandler ( logoutHandlers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a matcher that matches on the specific method and any of the provided patterns . [CODESPLIT] public static ServerWebExchangeMatcher pathMatchers ( HttpMethod method , String ... patterns ) { List < ServerWebExchangeMatcher > matchers = new ArrayList <> ( patterns . length ) ; for ( String pattern : patterns ) { matchers . add ( new PathPatternParserServerWebExchangeMatcher ( pattern , method ) ) ; } return new OrServerWebExchangeMatcher ( matchers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches any exchange [CODESPLIT] public static ServerWebExchangeMatcher anyExchange ( ) { // we don't use a lambda to ensure a unique equals and hashcode // which otherwise can cause problems with adding multiple entries to an ordered LinkedHashMap return new ServerWebExchangeMatcher ( ) { @ Override public Mono < MatchResult > matches ( ServerWebExchange exchange ) { return ServerWebExchangeMatcher . MatchResult . match ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a standard password - based bytes encryptor using 256 bit AES encryption with Galois Counter Mode ( GCM ) . Derives the secret key using PKCS #5 s PBKDF2 ( Password - Based Key Derivation Function #2 ) . Salts the password to prevent dictionary attacks against the key . The provided salt is expected to be hex - encoded ; it should be random and at least 8 bytes in length . Also applies a random 16 byte initialization vector to ensure each encrypted message will be unique . Requires Java 6 . [CODESPLIT] public static BytesEncryptor stronger ( CharSequence password , CharSequence salt ) { return new AesBytesEncryptor ( password . toString ( ) , salt , KeyGenerators . secureRandom ( 16 ) , CipherAlgorithm . GCM ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a standard password - based bytes encryptor using 256 bit AES encryption . Derives the secret key using PKCS #5 s PBKDF2 ( Password - Based Key Derivation Function #2 ) . Salts the password to prevent dictionary attacks against the key . The provided salt is expected to be hex - encoded ; it should be random and at least 8 bytes in length . Also applies a random 16 byte initialization vector to ensure each encrypted message will be unique . Requires Java 6 . [CODESPLIT] public static BytesEncryptor standard ( CharSequence password , CharSequence salt ) { return new AesBytesEncryptor ( password . toString ( ) , salt , KeyGenerators . secureRandom ( 16 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a text encryptor that uses stronger password - based encryption . Encrypted text is hex - encoded . [CODESPLIT] public static TextEncryptor delux ( CharSequence password , CharSequence salt ) { return new HexEncodingTextEncryptor ( stronger ( password , salt ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a text encryptor that uses standard password - based encryption . Encrypted text is hex - encoded . [CODESPLIT] public static TextEncryptor text ( CharSequence password , CharSequence salt ) { return new HexEncodingTextEncryptor ( standard ( password , salt ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an encryptor for queryable text strings that uses standard password - based encryption . Uses a 16 - byte all - zero initialization vector so encrypting the same data results in the same encryption result . This is done to allow encrypted data to be queried against . Encrypted text is hex - encoded . [CODESPLIT] public static TextEncryptor queryableText ( CharSequence password , CharSequence salt ) { return new HexEncodingTextEncryptor ( new AesBytesEncryptor ( password . toString ( ) , salt ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the { @link SecurityExpressionHandler } to be used . If this is null then a { @link DefaultWebSecurityExpressionHandler } will be used . [CODESPLIT] public WebSecurity expressionHandler ( SecurityExpressionHandler < FilterInvocation > expressionHandler ) { Assert . notNull ( expressionHandler , \"expressionHandler cannot be null\" ) ; this . expressionHandler = expressionHandler ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator ( ) { if ( privilegeEvaluator != null ) { return privilegeEvaluator ; } return filterSecurityInterceptor == null ? null : new DefaultWebInvocationPrivilegeEvaluator ( filterSecurityInterceptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This concrete implementation polls all configured { @link AccessDecisionVoter } s for each { @link ConfigAttribute } and grants access if <b > only< / b > grant ( or abstain ) votes were received . <p > Other voting implementations usually pass the entire list of <tt > ConfigAttribute< / tt > s to the <code > AccessDecisionVoter< / code > . This implementation differs in that each <code > AccessDecisionVoter< / code > knows only about a single <code > ConfigAttribute< / code > at a time . <p > If every <code > AccessDecisionVoter< / code > abstained from voting the decision will be based on the { @link #isAllowIfAllAbstainDecisions () } property ( defaults to false ) . [CODESPLIT] public void decide ( Authentication authentication , Object object , Collection < ConfigAttribute > attributes ) throws AccessDeniedException { int grant = 0 ; List < ConfigAttribute > singleAttributeList = new ArrayList <> ( 1 ) ; singleAttributeList . add ( null ) ; for ( ConfigAttribute attribute : attributes ) { singleAttributeList . set ( 0 , attribute ) ; for ( AccessDecisionVoter voter : getDecisionVoters ( ) ) { int result = voter . vote ( authentication , object , singleAttributeList ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Voter: \" + voter + \", returned: \" + result ) ; } switch ( result ) { case AccessDecisionVoter . ACCESS_GRANTED : grant ++ ; break ; case AccessDecisionVoter . ACCESS_DENIED : throw new AccessDeniedException ( messages . getMessage ( \"AbstractAccessDecisionManager.accessDenied\" , \"Access is denied\" ) ) ; default : break ; } } } // To get this far, there were no deny votes if ( grant > 0 ) { return ; } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link DelegatingPasswordEncoder } with default mappings . Additional mappings may be added and the encoding will be updated to conform with best practices . However due to the nature of { @link DelegatingPasswordEncoder } the updates should not impact users . The mappings current are : [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) public static PasswordEncoder createDelegatingPasswordEncoder ( ) { String encodingId = \"bcrypt\" ; Map < String , PasswordEncoder > encoders = new HashMap <> ( ) ; encoders . put ( encodingId , new BCryptPasswordEncoder ( ) ) ; encoders . put ( \"ldap\" , new org . springframework . security . crypto . password . LdapShaPasswordEncoder ( ) ) ; encoders . put ( \"MD4\" , new org . springframework . security . crypto . password . Md4PasswordEncoder ( ) ) ; encoders . put ( \"MD5\" , new org . springframework . security . crypto . password . MessageDigestPasswordEncoder ( \"MD5\" ) ) ; encoders . put ( \"noop\" , org . springframework . security . crypto . password . NoOpPasswordEncoder . getInstance ( ) ) ; encoders . put ( \"pbkdf2\" , new Pbkdf2PasswordEncoder ( ) ) ; encoders . put ( \"scrypt\" , new SCryptPasswordEncoder ( ) ) ; encoders . put ( \"SHA-1\" , new org . springframework . security . crypto . password . MessageDigestPasswordEncoder ( \"SHA-1\" ) ) ; encoders . put ( \"SHA-256\" , new org . springframework . security . crypto . password . MessageDigestPasswordEncoder ( \"SHA-256\" ) ) ; encoders . put ( \"sha256\" , new org . springframework . security . crypto . password . StandardPasswordEncoder ( ) ) ; return new DelegatingPasswordEncoder ( encodingId , encoders ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect error details from the provided parameters and format according to RFC 6750 specifically { @code error } { @code error_description } { @code error_uri } and { @scope scope } . [CODESPLIT] @ Override public void handle ( HttpServletRequest request , HttpServletResponse response , AccessDeniedException accessDeniedException ) throws IOException , ServletException { Map < String , String > parameters = new LinkedHashMap <> ( ) ; if ( this . realmName != null ) { parameters . put ( \"realm\" , this . realmName ) ; } if ( request . getUserPrincipal ( ) instanceof AbstractOAuth2TokenAuthenticationToken ) { AbstractOAuth2TokenAuthenticationToken token = ( AbstractOAuth2TokenAuthenticationToken ) request . getUserPrincipal ( ) ; String scope = getScope ( token ) ; parameters . put ( \"error\" , BearerTokenErrorCodes . INSUFFICIENT_SCOPE ) ; parameters . put ( \"error_description\" , String . format ( \"The token provided has insufficient scope [%s] for this request\" , scope ) ) ; parameters . put ( \"error_uri\" , \"https://tools.ietf.org/html/rfc6750#section-3.1\" ) ; if ( StringUtils . hasText ( scope ) ) { parameters . put ( \"scope\" , scope ) ; } } String wwwAuthenticate = computeWWWAuthenticateHeaderValue ( parameters ) ; response . addHeader ( HttpHeaders . WWW_AUTHENTICATE , wwwAuthenticate ) ; response . setStatus ( HttpStatus . FORBIDDEN . value ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the X - Frame - Options header value overwritting any previous value . [CODESPLIT] public void writeHeaders ( HttpServletRequest request , HttpServletResponse response ) { if ( XFrameOptionsMode . ALLOW_FROM . equals ( frameOptionsMode ) ) { String allowFromValue = this . allowFromStrategy . getAllowFromValue ( request ) ; if ( XFrameOptionsMode . DENY . getMode ( ) . equals ( allowFromValue ) ) { if ( ! response . containsHeader ( XFRAME_OPTIONS_HEADER ) ) { response . setHeader ( XFRAME_OPTIONS_HEADER , XFrameOptionsMode . DENY . getMode ( ) ) ; } } else if ( allowFromValue != null ) { if ( ! response . containsHeader ( XFRAME_OPTIONS_HEADER ) ) { response . setHeader ( XFRAME_OPTIONS_HEADER , XFrameOptionsMode . ALLOW_FROM . getMode ( ) + \" \" + allowFromValue ) ; } } } else { response . setHeader ( XFRAME_OPTIONS_HEADER , frameOptionsMode . getMode ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Attempts to obtain and run as a JAAS <code > Subject< / code > using { @link #obtainSubject ( ServletRequest ) } . < / p > [CODESPLIT] public final void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws ServletException , IOException { Subject subject = obtainSubject ( request ) ; if ( subject == null && createEmptySubject ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Subject returned was null and createEmtpySubject is true; creating new empty subject to run as.\" ) ; } subject = new Subject ( ) ; } if ( subject == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Subject is null continue running with no Subject.\" ) ; } chain . doFilter ( request , response ) ; return ; } final PrivilegedExceptionAction < Object > continueChain = new PrivilegedExceptionAction < Object > ( ) { public Object run ( ) throws IOException , ServletException { chain . doFilter ( request , response ) ; return null ; } } ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Running as Subject \" + subject ) ; } try { Subject . doAs ( subject , continueChain ) ; } catch ( PrivilegedActionException e ) { throw new ServletException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Obtains the <code > Subject< / code > to run as or <code > null< / code > if no <code > Subject< / code > is available . < / p > <p > The default implementation attempts to obtain the <code > Subject< / code > from the <code > SecurityContext< / code > s <code > Authentication< / code > . If it is of type <code > JaasAuthenticationToken< / code > and is authenticated the <code > Subject< / code > is returned from it . Otherwise <code > null< / code > is returned . < / p > [CODESPLIT] protected Subject obtainSubject ( ServletRequest request ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Attempting to obtainSubject using authentication : \" + authentication ) ; } if ( authentication == null ) { return null ; } if ( ! authentication . isAuthenticated ( ) ) { return null ; } if ( ! ( authentication instanceof JaasAuthenticationToken ) ) { return null ; } JaasAuthenticationToken token = ( JaasAuthenticationToken ) authentication ; LoginContext loginContext = token . getLoginContext ( ) ; if ( loginContext == null ) { return null ; } return loginContext . getSubject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the { @link CsrfTokenRepository } to use . The default is an { @link HttpSessionCsrfTokenRepository } wrapped by { @link LazyCsrfTokenRepository } . [CODESPLIT] public CsrfConfigurer < H > csrfTokenRepository ( CsrfTokenRepository csrfTokenRepository ) { Assert . notNull ( csrfTokenRepository , \"csrfTokenRepository cannot be null\" ) ; this . csrfTokenRepository = csrfTokenRepository ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the { @link RequestMatcher } to use for determining when CSRF should be applied . The default is to ignore GET HEAD TRACE OPTIONS and process all other requests . [CODESPLIT] public CsrfConfigurer < H > requireCsrfProtectionMatcher ( RequestMatcher requireCsrfProtectionMatcher ) { Assert . notNull ( requireCsrfProtectionMatcher , \"requireCsrfProtectionMatcher cannot be null\" ) ; this . requireCsrfProtectionMatcher = requireCsrfProtectionMatcher ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Allows specifying { @link HttpServletRequest } that should not use CSRF Protection even if they match the { @link #requireCsrfProtectionMatcher ( RequestMatcher ) } . < / p > [CODESPLIT] public CsrfConfigurer < H > ignoringAntMatchers ( String ... antPatterns ) { return new IgnoreCsrfProtectionRegistry ( this . context ) . antMatchers ( antPatterns ) . and ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Allows specifying { @link HttpServletRequest } s that should not use CSRF Protection even if they match the { @link #requireCsrfProtectionMatcher ( RequestMatcher ) } . < / p > [CODESPLIT] public CsrfConfigurer < H > ignoringRequestMatchers ( RequestMatcher ... requestMatchers ) { return new IgnoreCsrfProtectionRegistry ( this . context ) . requestMatchers ( requestMatchers ) . and ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the final { @link RequestMatcher } to use by combining the { @link #requireCsrfProtectionMatcher ( RequestMatcher ) } and any { @link #ignore () } . [CODESPLIT] private RequestMatcher getRequireCsrfProtectionMatcher ( ) { if ( this . ignoredCsrfProtectionMatchers . isEmpty ( ) ) { return this . requireCsrfProtectionMatcher ; } return new AndRequestMatcher ( this . requireCsrfProtectionMatcher , new NegatedRequestMatcher ( new OrRequestMatcher ( this . ignoredCsrfProtectionMatchers ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the default { @link AccessDeniedHandler } from the { @link ExceptionHandlingConfigurer#getAccessDeniedHandler () } or create a { @link AccessDeniedHandlerImpl } if not available . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private AccessDeniedHandler getDefaultAccessDeniedHandler ( H http ) { ExceptionHandlingConfigurer < H > exceptionConfig = http . getConfigurer ( ExceptionHandlingConfigurer . class ) ; AccessDeniedHandler handler = null ; if ( exceptionConfig != null ) { handler = exceptionConfig . getAccessDeniedHandler ( ) ; } if ( handler == null ) { handler = new AccessDeniedHandlerImpl ( ) ; } return handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the default { @link InvalidSessionStrategy } from the { @link SessionManagementConfigurer#getInvalidSessionStrategy () } or null if not available . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private InvalidSessionStrategy getInvalidSessionStrategy ( H http ) { SessionManagementConfigurer < H > sessionManagement = http . getConfigurer ( SessionManagementConfigurer . class ) ; if ( sessionManagement == null ) { return null ; } return sessionManagement . getInvalidSessionStrategy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link AccessDeniedHandler } from the result of { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } and { @link #getInvalidSessionStrategy ( HttpSecurityBuilder ) } . If { @link #getInvalidSessionStrategy ( HttpSecurityBuilder ) } is non - null then a { @link DelegatingAccessDeniedHandler } is used in combination with { @link InvalidSessionAccessDeniedHandler } and the { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } . Otherwise only { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } is used . [CODESPLIT] private AccessDeniedHandler createAccessDeniedHandler ( H http ) { InvalidSessionStrategy invalidSessionStrategy = getInvalidSessionStrategy ( http ) ; AccessDeniedHandler defaultAccessDeniedHandler = getDefaultAccessDeniedHandler ( http ) ; if ( invalidSessionStrategy == null ) { return defaultAccessDeniedHandler ; } InvalidSessionAccessDeniedHandler invalidSessionDeniedHandler = new InvalidSessionAccessDeniedHandler ( invalidSessionStrategy ) ; LinkedHashMap < Class < ? extends AccessDeniedException > , AccessDeniedHandler > handlers = new LinkedHashMap < Class < ? extends AccessDeniedException > , AccessDeniedHandler > ( ) ; handlers . put ( MissingCsrfTokenException . class , invalidSessionDeniedHandler ) ; return new DelegatingAccessDeniedHandler ( handlers , defaultAccessDeniedHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the configured { [CODESPLIT] protected void handle ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) throws IOException , ServletException { String targetUrl = determineTargetUrl ( request , response , authentication ) ; if ( response . isCommitted ( ) ) { logger . debug ( \"Response has already been committed. Unable to redirect to \" + targetUrl ) ; return ; } redirectStrategy . sendRedirect ( request , response , targetUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the target URL according to the logic defined in the main class Javadoc [CODESPLIT] protected String determineTargetUrl ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) { return determineTargetUrl ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the target URL according to the logic defined in the main class Javadoc . [CODESPLIT] protected String determineTargetUrl ( HttpServletRequest request , HttpServletResponse response ) { if ( isAlwaysUseDefaultTargetUrl ( ) ) { return defaultTargetUrl ; } // Check for the parameter and use that if available String targetUrl = null ; if ( targetUrlParameter != null ) { targetUrl = request . getParameter ( targetUrlParameter ) ; if ( StringUtils . hasText ( targetUrl ) ) { logger . debug ( \"Found targetUrlParameter in request: \" + targetUrl ) ; return targetUrl ; } } if ( useReferer && ! StringUtils . hasLength ( targetUrl ) ) { targetUrl = request . getHeader ( \"Referer\" ) ; logger . debug ( \"Using Referer header: \" + targetUrl ) ; } if ( ! StringUtils . hasText ( targetUrl ) ) { targetUrl = defaultTargetUrl ; logger . debug ( \"Using default Url: \" + targetUrl ) ; } return targetUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supplies the default target Url that will be used if no saved request is found in the session or the { @code alwaysUseDefaultTargetUrl } property is set to true . If not set defaults to { @code / } . It will be treated as relative to the web - app s context path and should include the leading <code > / < / code > . Alternatively inclusion of a scheme name ( such as http : // or https : // ) as the prefix will denote a fully - qualified URL and this is also supported . [CODESPLIT] public void setDefaultTargetUrl ( String defaultTargetUrl ) { Assert . isTrue ( UrlUtils . isValidRedirectUrl ( defaultTargetUrl ) , \"defaultTarget must start with '/' or with 'http(s)'\" ) ; this . defaultTargetUrl = defaultTargetUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this property is set the current request will be checked for this a parameter with this name and the value used as the target URL if present . [CODESPLIT] public void setTargetUrlParameter ( String targetUrlParameter ) { if ( targetUrlParameter != null ) { Assert . hasText ( targetUrlParameter , \"targetUrlParameter cannot be empty\" ) ; } this . targetUrlParameter = targetUrlParameter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes recursive SQL as needed to build a full Directory hierarchy of objects [CODESPLIT] private Directory getDirectoryWithImmediateParentPopulated ( final Long id ) { return getJdbcTemplate ( ) . queryForObject ( SELECT_FROM_DIRECTORY_SINGLE , new Object [ ] { id } , new RowMapper < Directory > ( ) { public Directory mapRow ( ResultSet rs , int rowNumber ) throws SQLException { Long parentDirectoryId = new Long ( rs . getLong ( \"parent_directory_id\" ) ) ; Directory parentDirectory = Directory . ROOT_DIRECTORY ; if ( parentDirectoryId != null && ! parentDirectoryId . equals ( new Long ( - 1 ) ) ) { // Need to go and lookup the parent, so do that first parentDirectory = getDirectoryWithImmediateParentPopulated ( parentDirectoryId ) ; } Directory directory = new Directory ( rs . getString ( \"directory_name\" ) , parentDirectory ) ; FieldUtils . setProtectedFieldValue ( \"id\" , directory , new Long ( rs . getLong ( \"id\" ) ) ) ; return directory ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read and returns the header named by { @code principalRequestHeader } from the request . [CODESPLIT] protected Object getPreAuthenticatedPrincipal ( HttpServletRequest request ) { String principal = request . getHeader ( principalRequestHeader ) ; if ( principal == null && exceptionIfHeaderMissing ) { throw new PreAuthenticatedCredentialsNotFoundException ( principalRequestHeader + \" header not found in request.\" ) ; } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void invokeContactManager ( Authentication authentication , int nrOfCalls ) { StopWatch stopWatch = new StopWatch ( nrOfCalls + \" ContactManager call(s)\" ) ; Map < String , ContactManager > contactServices = this . beanFactory . getBeansOfType ( ContactManager . class , true , true ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( authentication ) ; for ( Map . Entry < String , ContactManager > entry : contactServices . entrySet ( ) ) { String beanName = entry . getKey ( ) ; ContactManager remoteContactManager = entry . getValue ( ) ; Object object = this . beanFactory . getBean ( \"&\" + beanName ) ; try { System . out . println ( \"Trying to find setUsername(String) method on: \" + object . getClass ( ) . getName ( ) ) ; Method method = object . getClass ( ) . getMethod ( \"setUsername\" , new Class [ ] { String . class } ) ; System . out . println ( \"Found; Trying to setUsername(String) to \" + authentication . getPrincipal ( ) ) ; method . invoke ( object , authentication . getPrincipal ( ) ) ; } catch ( NoSuchMethodException ignored ) { System . out . println ( \"This client proxy factory does not have a setUsername(String) method\" ) ; } catch ( IllegalAccessException ignored ) { ignored . printStackTrace ( ) ; } catch ( InvocationTargetException ignored ) { ignored . printStackTrace ( ) ; } try { System . out . println ( \"Trying to find setPassword(String) method on: \" + object . getClass ( ) . getName ( ) ) ; Method method = object . getClass ( ) . getMethod ( \"setPassword\" , new Class [ ] { String . class } ) ; method . invoke ( object , authentication . getCredentials ( ) ) ; System . out . println ( \"Found; Trying to setPassword(String) to \" + authentication . getCredentials ( ) ) ; } catch ( NoSuchMethodException ignored ) { System . out . println ( \"This client proxy factory does not have a setPassword(String) method\" ) ; } catch ( IllegalAccessException ignored ) { } catch ( InvocationTargetException ignored ) { } System . out . println ( \"Calling ContactManager '\" + beanName + \"'\" ) ; stopWatch . start ( beanName ) ; List < Contact > contacts = null ; for ( int i = 0 ; i < nrOfCalls ; i ++ ) { contacts = remoteContactManager . getAll ( ) ; } stopWatch . stop ( ) ; if ( contacts . size ( ) != 0 ) { for ( Contact contact : contacts ) { System . out . println ( \"Contact: \" + contact ) ; } } else { System . out . println ( \"No contacts found which this user has permission to\" ) ; } System . out . println ( ) ; System . out . println ( stopWatch . prettyPrint ( ) ) ; } SecurityContextHolder . clearContext ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assembles the Distinguished Name that should be used the given username . [CODESPLIT] public DistinguishedName buildDn ( String username ) { DistinguishedName dn = new DistinguishedName ( userDnBase ) ; dn . add ( usernameAttribute , username ) ; return dn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @link Builder } initialized with the values from the provided { @code authorizationRequest } . [CODESPLIT] public static Builder from ( OAuth2AuthorizationRequest authorizationRequest ) { Assert . notNull ( authorizationRequest , \"authorizationRequest cannot be null\" ) ; return new Builder ( authorizationRequest . getGrantType ( ) ) . authorizationUri ( authorizationRequest . getAuthorizationUri ( ) ) . clientId ( authorizationRequest . getClientId ( ) ) . redirectUri ( authorizationRequest . getRedirectUri ( ) ) . scopes ( authorizationRequest . getScopes ( ) ) . state ( authorizationRequest . getState ( ) ) . additionalParameters ( authorizationRequest . getAdditionalParameters ( ) ) . attributes ( authorizationRequest . getAttributes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Map < String , Object > introspect ( String token ) { TokenIntrospectionSuccessResponse response = Optional . of ( token ) . map ( this :: buildRequest ) . map ( this :: makeRequest ) . map ( this :: adaptToNimbusResponse ) . map ( this :: parseNimbusResponse ) . map ( this :: castToNimbusSuccess ) // relying solely on the authorization server to validate this token (not checking 'exp', for example) . filter ( TokenIntrospectionSuccessResponse :: isActive ) . orElseThrow ( ( ) -> new OAuth2IntrospectionException ( \"Provided token [\" + token + \"] isn't active\" ) ) ; return convertClaimsSet ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @link HttpSecurity } or returns the current instance [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) protected final HttpSecurity getHttp ( ) throws Exception { if ( http != null ) { return http ; } DefaultAuthenticationEventPublisher eventPublisher = objectPostProcessor . postProcess ( new DefaultAuthenticationEventPublisher ( ) ) ; localConfigureAuthenticationBldr . authenticationEventPublisher ( eventPublisher ) ; AuthenticationManager authenticationManager = authenticationManager ( ) ; authenticationBuilder . parentAuthenticationManager ( authenticationManager ) ; authenticationBuilder . authenticationEventPublisher ( eventPublisher ) ; Map < Class < ? extends Object > , Object > sharedObjects = createSharedObjects ( ) ; http = new HttpSecurity ( objectPostProcessor , authenticationBuilder , sharedObjects ) ; if ( ! disableDefaults ) { // @formatter:off http . csrf ( ) . and ( ) . addFilter ( new WebAsyncManagerIntegrationFilter ( ) ) . exceptionHandling ( ) . and ( ) . headers ( ) . and ( ) . sessionManagement ( ) . and ( ) . securityContext ( ) . and ( ) . requestCache ( ) . and ( ) . anonymous ( ) . and ( ) . servletApi ( ) . and ( ) . apply ( new DefaultLoginPageConfigurer <> ( ) ) . and ( ) . logout ( ) ; // @formatter:on ClassLoader classLoader = this . context . getClassLoader ( ) ; List < AbstractHttpConfigurer > defaultHttpConfigurers = SpringFactoriesLoader . loadFactories ( AbstractHttpConfigurer . class , classLoader ) ; for ( AbstractHttpConfigurer configurer : defaultHttpConfigurers ) { http . apply ( configurer ) ; } } configure ( http ) ; return http ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link AuthenticationManager } to use . The default strategy is if { @link #configure ( AuthenticationManagerBuilder ) } method is overridden to use the { @link AuthenticationManagerBuilder } that was passed in . Otherwise autowire the { @link AuthenticationManager } by type . [CODESPLIT] protected AuthenticationManager authenticationManager ( ) throws Exception { if ( ! authenticationManagerInitialized ) { configure ( localConfigureAuthenticationBldr ) ; if ( disableLocalConfigureAuthenticationBldr ) { authenticationManager = authenticationConfiguration . getAuthenticationManager ( ) ; } else { authenticationManager = localConfigureAuthenticationBldr . build ( ) ; } authenticationManagerInitialized = true ; } return authenticationManager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override this method to expose a { @link UserDetailsService } created from { @link #configure ( AuthenticationManagerBuilder ) } as a bean . In general only the following override should be done of this method : [CODESPLIT] public UserDetailsService userDetailsServiceBean ( ) throws Exception { AuthenticationManagerBuilder globalAuthBuilder = context . getBean ( AuthenticationManagerBuilder . class ) ; return new UserDetailsServiceDelegator ( Arrays . asList ( localConfigureAuthenticationBldr , globalAuthBuilder ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows modifying and accessing the { @link UserDetailsService } from { @link #userDetailsServiceBean () } without interacting with the { @link ApplicationContext } . Developers should override this method when changing the instance of { @link #userDetailsServiceBean () } . [CODESPLIT] protected UserDetailsService userDetailsService ( ) { AuthenticationManagerBuilder globalAuthBuilder = context . getBean ( AuthenticationManagerBuilder . class ) ; return new UserDetailsServiceDelegator ( Arrays . asList ( localConfigureAuthenticationBldr , globalAuthBuilder ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the shared objects [CODESPLIT] private Map < Class < ? extends Object > , Object > createSharedObjects ( ) { Map < Class < ? extends Object > , Object > sharedObjects = new HashMap < Class < ? extends Object > , Object > ( ) ; sharedObjects . putAll ( localConfigureAuthenticationBldr . getSharedObjects ( ) ) ; sharedObjects . put ( UserDetailsService . class , userDetailsService ( ) ) ; sharedObjects . put ( ApplicationContext . class , context ) ; sharedObjects . put ( ContentNegotiationStrategy . class , contentNegotiationStrategy ) ; sharedObjects . put ( AuthenticationTrustResolver . class , trustResolver ) ; return sharedObjects ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public void afterPropertiesSet ( ) throws Exception { // the superclass is not called because it does additional checks that are // non-passive Assert . hasLength ( getLoginContextName ( ) , ( ) -> \"loginContextName must be set on \" + getClass ( ) ) ; Assert . notNull ( this . loginConfig , ( ) -> \"loginConfig must be set on \" + getClass ( ) ) ; configureJaas ( this . loginConfig ) ; Assert . notNull ( Configuration . getConfiguration ( ) , \"As per https://java.sun.com/j2se/1.5.0/docs/api/javax/security/auth/login/Configuration.html \" + \"\\\"If a Configuration object was set via the Configuration.setConfiguration method, then that object is \" + \"returned. Otherwise, a default Configuration object is returned\\\". Your JRE returned null to \" + \"Configuration.getConfiguration().\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops through the login . config . url . 1 login . config . url . 2 properties looking for the login configuration . If it is not set it will be set to the last available login . config . url . X property . [CODESPLIT] private void configureJaasUsingLoop ( ) throws IOException { String loginConfigUrl = convertLoginConfigToUrl ( ) ; boolean alreadySet = false ; int n = 1 ; final String prefix = \"login.config.url.\" ; String existing ; while ( ( existing = Security . getProperty ( prefix + n ) ) != null ) { alreadySet = existing . equals ( loginConfigUrl ) ; if ( alreadySet ) { break ; } n ++ ; } if ( ! alreadySet ) { String key = prefix + n ; log . debug ( \"Setting security property [\" + key + \"] to: \" + loginConfigUrl ) ; Security . setProperty ( key , loginConfigUrl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Publishes the { @link JaasAuthenticationFailedEvent } . Can be overridden by subclasses for different functionality [CODESPLIT] @ Override protected void publishFailureEvent ( UsernamePasswordAuthenticationToken token , AuthenticationException ase ) { // exists for passivity (the superclass does a null check before publishing) getApplicationEventPublisher ( ) . publishEvent ( new JaasAuthenticationFailedEvent ( token , ase ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the internal template methods to create { @code StandardEvaluationContext } and { @code SecurityExpressionRoot } objects . [CODESPLIT] public final EvaluationContext createEvaluationContext ( Authentication authentication , T invocation ) { SecurityExpressionOperations root = createSecurityExpressionRoot ( authentication , invocation ) ; StandardEvaluationContext ctx = createEvaluationContextInternal ( authentication , invocation ) ; ctx . setBeanResolver ( br ) ; ctx . setRootObject ( root ) ; return ctx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String resolveServiceEntry ( String serviceType , String domain ) { return resolveServiceEntry ( serviceType , domain , this . ctxFactory . getCtx ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String resolveServiceIpAddress ( String serviceType , String domain ) { DirContext ctx = this . ctxFactory . getCtx ( ) ; String hostname = resolveServiceEntry ( serviceType , domain , ctx ) ; return resolveIpAddress ( hostname , ctx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolveServiceIpAddress () . [CODESPLIT] private String resolveIpAddress ( String hostname , DirContext ctx ) { try { Attribute dnsRecord = lookup ( hostname , ctx , \"A\" ) ; // There should be only one A record, therefore it is save to return // only the first. return dnsRecord . get ( ) . toString ( ) ; } catch ( NamingException e ) { throw new DnsLookupException ( \"DNS lookup failed for: \" + hostname , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolveServiceIpAddress () . [CODESPLIT] private String resolveServiceEntry ( String serviceType , String domain , DirContext ctx ) { String result = null ; try { String query = new StringBuilder ( \"_\" ) . append ( serviceType ) . append ( \"._tcp.\" ) . append ( domain ) . toString ( ) ; Attribute dnsRecord = lookup ( query , ctx , \"SRV\" ) ; // There are maybe more records defined, we will return the one // with the highest priority (lowest number) and the highest weight // (highest number) int highestPriority = - 1 ; int highestWeight = - 1 ; for ( NamingEnumeration < ? > recordEnum = dnsRecord . getAll ( ) ; recordEnum . hasMoreElements ( ) ; ) { String [ ] record = recordEnum . next ( ) . toString ( ) . split ( \" \" ) ; if ( record . length != 4 ) { throw new DnsLookupException ( \"Wrong service record for query \" + query + \": [\" + Arrays . toString ( record ) + \"]\" ) ; } int priority = Integer . parseInt ( record [ 0 ] ) ; int weight = Integer . parseInt ( record [ 1 ] ) ; // we have a new highest Priority, so forget also the highest weight if ( priority < highestPriority || highestPriority == - 1 ) { highestPriority = priority ; highestWeight = weight ; result = record [ 3 ] . trim ( ) ; } // same priority, but higher weight if ( priority == highestPriority && weight > highestWeight ) { highestWeight = weight ; result = record [ 3 ] . trim ( ) ; } } } catch ( NamingException e ) { throw new DnsLookupException ( \"DNS lookup failed for service \" + serviceType + \" at \" + domain , e ) ; } // remove the \".\" at the end if ( result . endsWith ( \".\" ) ) { result = result . substring ( 0 , result . length ( ) - 1 ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called every time a HTTP invocation is made . <p > Simply allows the parent to setup the connection and then adds an <code > Authorization< / code > HTTP header property that will be used for BASIC authentication . < / p > <p > The <code > SecurityContextHolder< / code > is used to obtain the relevant principal and credentials . < / p > [CODESPLIT] protected void prepareConnection ( HttpURLConnection con , int contentLength ) throws IOException { super . prepareConnection ( con , contentLength ) ; Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( ( auth != null ) && ( auth . getName ( ) != null ) && ( auth . getCredentials ( ) != null ) && ! trustResolver . isAnonymous ( auth ) ) { String base64 = auth . getName ( ) + \":\" + auth . getCredentials ( ) . toString ( ) ; con . setRequestProperty ( \"Authorization\" , \"Basic \" + new String ( Base64 . getEncoder ( ) . encode ( base64 . getBytes ( ) ) ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived: \" + auth . toString ( ) ) ; } } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Unable to set BASIC authentication header as SecurityContext did not provide \" + \"valid Authentication: \" + auth ) ; } } doPrepareConnection ( con , contentLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] public static Mono < SecurityContext > getContext ( ) { return Mono . subscriberContext ( ) . filter ( c -> c . hasKey ( SECURITY_CONTEXT_KEY ) ) . flatMap ( c -> c . < Mono < SecurityContext > > get ( SECURITY_CONTEXT_KEY ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T postProcess ( T object ) { if ( object == null ) { return null ; } T result = null ; try { result = ( T ) this . autowireBeanFactory . initializeBean ( object , object . toString ( ) ) ; } catch ( RuntimeException e ) { Class < ? > type = object . getClass ( ) ; throw new RuntimeException ( \"Could not postProcess \" + object + \" of type \" + type , e ) ; } this . autowireBeanFactory . autowireBean ( object ) ; if ( result instanceof DisposableBean ) { this . disposableBeans . add ( ( DisposableBean ) result ) ; } if ( result instanceof SmartInitializingSingleton ) { this . smartSingletons . add ( ( SmartInitializingSingleton ) result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void destroy ( ) throws Exception { for ( DisposableBean disposable : this . disposableBeans ) { try { disposable . destroy ( ) ; } catch ( Exception error ) { this . logger . error ( error ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void setAsText ( String s ) throws IllegalArgumentException { if ( StringUtils . hasText ( s ) ) { String [ ] tokens = StringUtils . commaDelimitedListToStringArray ( s ) ; UserAttribute userAttrib = new UserAttribute ( ) ; List < String > authoritiesAsStrings = new ArrayList <> ( ) ; for ( int i = 0 ; i < tokens . length ; i ++ ) { String currentToken = tokens [ i ] . trim ( ) ; if ( i == 0 ) { userAttrib . setPassword ( currentToken ) ; } else { if ( currentToken . toLowerCase ( ) . equals ( \"enabled\" ) ) { userAttrib . setEnabled ( true ) ; } else if ( currentToken . toLowerCase ( ) . equals ( \"disabled\" ) ) { userAttrib . setEnabled ( false ) ; } else { authoritiesAsStrings . add ( currentToken ) ; } } } userAttrib . setAuthoritiesAsString ( authoritiesAsStrings ) ; if ( userAttrib . isValid ( ) ) { setValue ( userAttrib ) ; } else { setValue ( null ) ; } } else { setValue ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link OAuth2UserService } used when requesting the user info resource . [CODESPLIT] public final void setOauth2UserService ( OAuth2UserService < OAuth2UserRequest , OAuth2User > oauth2UserService ) { Assert . notNull ( oauth2UserService , \"oauth2UserService cannot be null\" ) ; this . oauth2UserService = oauth2UserService ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a specified date to HTTP format . If local format is not <code > null< / code > it s used instead . [CODESPLIT] public static String formatDate ( long value , DateFormat threadLocalformat ) { String cachedDate = null ; Long longValue = Long . valueOf ( value ) ; try { cachedDate = formatCache . get ( longValue ) ; } catch ( Exception ignored ) { } if ( cachedDate != null ) { return cachedDate ; } String newDate ; Date dateValue = new Date ( value ) ; if ( threadLocalformat != null ) { newDate = threadLocalformat . format ( dateValue ) ; synchronized ( formatCache ) { updateCache ( formatCache , longValue , newDate ) ; } } else { synchronized ( formatCache ) { newDate = format . format ( dateValue ) ; updateCache ( formatCache , longValue , newDate ) ; } } return newDate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current date in HTTP format . [CODESPLIT] public static String getCurrentDate ( ) { long now = System . currentTimeMillis ( ) ; if ( ( now - currentDateGenerated ) > 1000 ) { synchronized ( format ) { if ( ( now - currentDateGenerated ) > 1000 ) { currentDateGenerated = now ; currentDate = format . format ( new Date ( now ) ) ; } } } return currentDate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses date with given formatters . [CODESPLIT] private static Long internalParseDate ( String value , DateFormat [ ] formats ) { Date date = null ; for ( int i = 0 ; ( date == null ) && ( i < formats . length ) ; i ++ ) { try { date = formats [ i ] . parse ( value ) ; } catch ( ParseException ignored ) { } } if ( date == null ) { return null ; } return new Long ( date . getTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to parse the given date as an HTTP date . If local format list is not <code > null< / code > it s used instead . [CODESPLIT] public static long parseDate ( String value , DateFormat [ ] threadLocalformats ) { Long cachedDate = null ; try { cachedDate = ( Long ) parseCache . get ( value ) ; } catch ( Exception ignored ) { } if ( cachedDate != null ) { return cachedDate . longValue ( ) ; } Long date ; if ( threadLocalformats != null ) { date = internalParseDate ( value , threadLocalformats ) ; synchronized ( parseCache ) { updateCache ( parseCache , value , date ) ; } } else { synchronized ( parseCache ) { date = internalParseDate ( value , formats ) ; updateCache ( parseCache , value , date ) ; } } if ( date == null ) { return ( - 1L ) ; } else { return date . longValue ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates cache . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static void updateCache ( HashMap cache , Object key , Object value ) { if ( value == null ) { return ; } if ( cache . size ( ) > 1000 ) { cache . clear ( ) ; } cache . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a <code > MethodInvocation< / code > for specified <code > methodName< / code > on the passed object using the <code > args< / code > to locate the method . [CODESPLIT] public static MethodInvocation create ( Object object , String methodName , Object ... args ) { Assert . notNull ( object , \"Object required\" ) ; Class < ? > [ ] classArgs = null ; if ( args != null ) { classArgs = new Class < ? > [ args . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) { classArgs [ i ] = args [ i ] . getClass ( ) ; } } // Determine the type that declares the requested method, taking into account // proxies Class < ? > target = AopUtils . getTargetClass ( object ) ; if ( object instanceof Advised ) { Advised a = ( Advised ) object ; if ( ! a . isProxyTargetClass ( ) ) { Class < ? > [ ] possibleInterfaces = a . getProxiedInterfaces ( ) ; for ( Class < ? > possibleInterface : possibleInterfaces ) { try { possibleInterface . getMethod ( methodName , classArgs ) ; // to get here means no exception happened target = possibleInterface ; break ; } catch ( Exception ignored ) { // try the next one } } } } return createFromClass ( object , target , methodName , classArgs , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a <code > MethodInvocation< / code > for the specified <code > methodName< / code > on the passed class . [CODESPLIT] public static MethodInvocation createFromClass ( Class < ? > clazz , String methodName ) { MethodInvocation mi = createFromClass ( null , clazz , methodName , null , null ) ; if ( mi == null ) { for ( Method m : clazz . getDeclaredMethods ( ) ) { if ( m . getName ( ) . equals ( methodName ) ) { if ( mi != null ) { throw new IllegalArgumentException ( \"The class \" + clazz + \" has more than one method named\" + \" '\" + methodName + \"'\" ) ; } mi = new SimpleMethodInvocation ( null , m ) ; } } } return mi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a <code > MethodInvocation< / code > for specified <code > methodName< / code > on the passed class using the <code > args< / code > to locate the method . [CODESPLIT] public static MethodInvocation createFromClass ( Object targetObject , Class < ? > clazz , String methodName , Class < ? > [ ] classArgs , Object [ ] args ) { Assert . notNull ( clazz , \"Class required\" ) ; Assert . hasText ( methodName , \"MethodName required\" ) ; Method method ; try { method = clazz . getMethod ( methodName , classArgs ) ; } catch ( NoSuchMethodException e ) { return null ; } return new SimpleMethodInvocation ( targetObject , method , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public Authentication attemptAuthentication ( HttpServletRequest request , HttpServletResponse response ) throws AuthenticationException { if ( postOnly && ! request . getMethod ( ) . equals ( \"POST\" ) ) { throw new AuthenticationServiceException ( \"Authentication method not supported: \" + request . getMethod ( ) ) ; } String username = obtainUsername ( request ) ; String password = obtainPassword ( request ) ; if ( username == null ) { username = \"\" ; } if ( password == null ) { password = \"\" ; } username = username . trim ( ) ; UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken ( username , password ) ; // Allow subclasses to set the \"details\" property setDetails ( request , authRequest ) ; return this . getAuthenticationManager ( ) . authenticate ( authRequest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provided so that subclasses may configure what is put into the authentication request s details property . [CODESPLIT] protected void setDetails ( HttpServletRequest request , UsernamePasswordAuthenticationToken authRequest ) { authRequest . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link List } of { @link SimpDestinationMessageMatcher } instances . [CODESPLIT] public Constraint simpTypeMatchers ( SimpMessageType ... typesToMatch ) { MessageMatcher < ? > [ ] typeMatchers = new MessageMatcher < ? > [ typesToMatch . length ] ; for ( int i = 0 ; i < typesToMatch . length ; i ++ ) { SimpMessageType typeToMatch = typesToMatch [ i ] ; typeMatchers [ i ] = new SimpMessageTypeMatcher ( typeToMatch ) ; } return matchers ( typeMatchers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link List } of { @link SimpDestinationMessageMatcher } instances . If no destination is found on the Message then the Matcher returns false . [CODESPLIT] private Constraint simpDestMatchers ( SimpMessageType type , String ... patterns ) { List < MatcherBuilder > matchers = new ArrayList <> ( patterns . length ) ; for ( String pattern : patterns ) { matchers . add ( new PathMatcherMessageMatcherBuilder ( pattern , type ) ) ; } return new Constraint ( matchers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The { @link PathMatcher } to be used with the { @link MessageSecurityMetadataSourceRegistry#simpDestMatchers ( String ... ) } . The default is to use the default constructor of { @link AntPathMatcher } . [CODESPLIT] public MessageSecurityMetadataSourceRegistry simpDestPathMatcher ( PathMatcher pathMatcher ) { Assert . notNull ( pathMatcher , \"pathMatcher cannot be null\" ) ; this . pathMatcher . setPathMatcher ( pathMatcher ) ; this . defaultPathMatcher = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link List } of { @link MessageMatcher } instances to a security expression . [CODESPLIT] public Constraint matchers ( MessageMatcher < ? > ... matchers ) { List < MatcherBuilder > builders = new ArrayList <> ( matchers . length ) ; for ( MessageMatcher < ? > matcher : matchers ) { builders . add ( new PreBuiltMatcherBuilder ( matcher ) ) ; } return new Constraint ( builders ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The { @link SecurityExpressionHandler } to be used . The default is to use { @link DefaultMessageSecurityExpressionHandler } . [CODESPLIT] public MessageSecurityMetadataSourceRegistry expressionHandler ( SecurityExpressionHandler < Message < Object > > expressionHandler ) { Assert . notNull ( expressionHandler , \"expressionHandler cannot be null\" ) ; this . expressionHandler = expressionHandler ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows subclasses to create creating a { @link MessageSecurityMetadataSource } . [CODESPLIT] protected MessageSecurityMetadataSource createMetadataSource ( ) { LinkedHashMap < MessageMatcher < ? > , String > matcherToExpression = new LinkedHashMap < MessageMatcher < ? > , String > ( ) ; for ( Map . Entry < MatcherBuilder , String > entry : this . matcherToExpression . entrySet ( ) ) { matcherToExpression . put ( entry . getKey ( ) . build ( ) , entry . getValue ( ) ) ; } return ExpressionBasedMessageSecurityMetadataSourceFactory . createExpressionMessageMetadataSource ( matcherToExpression , expressionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a successful { @link Authentication } object . <p > Protected so subclasses can override . < / p > <p > Subclasses will usually store the original credentials the user supplied ( not salted or encoded passwords ) in the returned <code > Authentication< / code > object . < / p > [CODESPLIT] protected Authentication createSuccessAuthentication ( Object principal , Authentication authentication , UserDetails user ) { // Ensure we return the original credentials the user supplied, // so subsequent attempts are successful even with encoded passwords. // Also ensure we return the original getDetails(), so that future // authentication events after cache expiry contain the details UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken ( principal , authentication . getCredentials ( ) , authoritiesMapper . mapAuthorities ( user . getAuthorities ( ) ) ) ; result . setDetails ( authentication . getDetails ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows easily changing the realm but leaving the remaining defaults in place . If { @link #authenticationEntryPoint ( AuthenticationEntryPoint ) } has been invoked invoking this method will result in an error . [CODESPLIT] public HttpBasicConfigurer < B > realmName ( String realmName ) throws Exception { this . basicAuthEntryPoint . setRealmName ( realmName ) ; this . basicAuthEntryPoint . afterPropertiesSet ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates the { @link DataSource } to be used . This is the only required attribute . [CODESPLIT] public JdbcUserDetailsManagerConfigurer < B > dataSource ( DataSource dataSource ) throws Exception { this . dataSource = dataSource ; getUserDetailsService ( ) . setDataSource ( dataSource ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An SQL statement to query user s group authorities given a username . For example : [CODESPLIT] public JdbcUserDetailsManagerConfigurer < B > groupAuthoritiesByUsername ( String query ) throws Exception { JdbcUserDetailsManager userDetailsService = getUserDetailsService ( ) ; userDetailsService . setEnableGroups ( true ) ; userDetailsService . setGroupAuthoritiesByUsernameQuery ( query ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The keyStore must not be null and must be a valid file . Will set the keyStore file on the underlying { [CODESPLIT] public void setKeyStoreFile ( File keyStoreFile ) { Assert . notNull ( keyStoreFile , \"The keyStoreFile must not be null.\" ) ; Assert . isTrue ( keyStoreFile . isFile ( ) , \"The keyStoreFile must be a file.\" ) ; this . keyStoreFile = keyStoreFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) protected void additionalAuthenticationChecks ( UserDetails userDetails , UsernamePasswordAuthenticationToken authentication ) throws AuthenticationException { if ( authentication . getCredentials ( ) == null ) { logger . debug ( \"Authentication failed: no credentials provided\" ) ; throw new BadCredentialsException ( messages . getMessage ( \"AbstractUserDetailsAuthenticationProvider.badCredentials\" , \"Bad credentials\" ) ) ; } String presentedPassword = authentication . getCredentials ( ) . toString ( ) ; if ( ! passwordEncoder . matches ( presentedPassword , userDetails . getPassword ( ) ) ) { logger . debug ( \"Authentication failed: password does not match stored value\" ) ; throw new BadCredentialsException ( messages . getMessage ( \"AbstractUserDetailsAuthenticationProvider.badCredentials\" , \"Bad credentials\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the PasswordEncoder instance to be used to encode and validate passwords . If not set the password will be compared using { @link PasswordEncoderFactories#createDelegatingPasswordEncoder () } [CODESPLIT] public void setPasswordEncoder ( PasswordEncoder passwordEncoder ) { Assert . notNull ( passwordEncoder , \"passwordEncoder cannot be null\" ) ; this . passwordEncoder = passwordEncoder ; this . userNotFoundEncodedPassword = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate the <code > Subject< / code > ( phase two ) by adding the Spring Security <code > Authentication< / code > to the <code > Subject< / code > s principals . [CODESPLIT] public boolean commit ( ) throws LoginException { if ( authen == null ) { return false ; } subject . getPrincipals ( ) . add ( authen ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize this <code > LoginModule< / code > . Ignores the callback handler since the code establishing the <code > LoginContext< / code > likely won t provide one that understands Spring Security . Also ignores the <code > sharedState< / code > and <code > options< / code > parameters since none are recognized . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void initialize ( Subject subject , CallbackHandler callbackHandler , Map sharedState , Map options ) { this . subject = subject ; if ( options != null ) { ignoreMissingAuthentication = \"true\" . equals ( options . get ( \"ignoreMissingAuthentication\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate the <code > Subject< / code > ( phase one ) by extracting the Spring Security <code > Authentication< / code > from the current <code > SecurityContext< / code > . [CODESPLIT] public boolean login ( ) throws LoginException { authen = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authen == null ) { String msg = \"Login cannot complete, authentication not found in security context\" ; if ( ignoreMissingAuthentication ) { log . warn ( msg ) ; return false ; } else { throw new LoginException ( msg ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log out the <code > Subject< / code > . [CODESPLIT] public boolean logout ( ) throws LoginException { if ( authen == null ) { return false ; } subject . getPrincipals ( ) . remove ( authen ) ; authen = null ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a UserDetailsManagerResourceFactoryBean with the location of a Resource that is a Properties file in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static UserDetailsManagerResourceFactoryBean fromResourceLocation ( String resourceLocation ) { UserDetailsManagerResourceFactoryBean result = new UserDetailsManagerResourceFactoryBean ( ) ; result . setResourceLocation ( resourceLocation ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a UserDetailsManagerResourceFactoryBean with a Resource that is a Properties file in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static UserDetailsManagerResourceFactoryBean fromResource ( Resource resource ) { UserDetailsManagerResourceFactoryBean result = new UserDetailsManagerResourceFactoryBean ( ) ; result . setResource ( resource ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a UserDetailsManagerResourceFactoryBean with a String that is in the format defined in { @link UserDetailsResourceFactoryBean } . [CODESPLIT] public static UserDetailsManagerResourceFactoryBean fromString ( String users ) { UserDetailsManagerResourceFactoryBean result = new UserDetailsManagerResourceFactoryBean ( ) ; result . setResource ( new InMemoryResource ( users ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] @ Override public void deleteAce ( int aceIndex ) throws NotFoundException { aclAuthorizationStrategy . securityCheck ( this , AclAuthorizationStrategy . CHANGE_GENERAL ) ; verifyAceIndexExists ( aceIndex ) ; synchronized ( aces ) { this . aces . remove ( aceIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegates to the { @link PermissionGrantingStrategy } . [CODESPLIT] @ Override public boolean isGranted ( List < Permission > permission , List < Sid > sids , boolean administrativeMode ) throws NotFoundException , UnloadedSidException { Assert . notEmpty ( permission , \"Permissions required\" ) ; Assert . notEmpty ( sids , \"SIDs required\" ) ; if ( ! this . isSidLoaded ( sids ) ) { throw new UnloadedSidException ( \"ACL was not loaded for one or more SID\" ) ; } return permissionGrantingStrategy . isGranted ( this , permission , sids , administrativeMode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See { [CODESPLIT] private < A extends Annotation > A findAnnotation ( Method method , Class < ? > targetClass , Class < A > annotationClass ) { // The method may be on an interface, but we need attributes from the target // class. // If the target class is null, the method will be unchanged. Method specificMethod = ClassUtils . getMostSpecificMethod ( method , targetClass ) ; A annotation = AnnotationUtils . findAnnotation ( specificMethod , annotationClass ) ; if ( annotation != null ) { logger . debug ( annotation + \" found on specific method: \" + specificMethod ) ; return annotation ; } // Check the original (e.g. interface) method if ( specificMethod != method ) { annotation = AnnotationUtils . findAnnotation ( method , annotationClass ) ; if ( annotation != null ) { logger . debug ( annotation + \" found on: \" + method ) ; return annotation ; } } // Check the class-level (note declaringClass, not targetClass, which may not // actually implement the method) annotation = AnnotationUtils . findAnnotation ( specificMethod . getDeclaringClass ( ) , annotationClass ) ; if ( annotation != null ) { logger . debug ( annotation + \" found on: \" + specificMethod . getDeclaringClass ( ) . getName ( ) ) ; return annotation ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the security name for the given subject . [CODESPLIT] private static String getSecurityName ( final Subject subject ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Determining Websphere security name for subject \" + subject ) ; } String userSecurityName = null ; if ( subject != null ) { // SEC-803 Object credential = subject . getPublicCredentials ( getWSCredentialClass ( ) ) . iterator ( ) . next ( ) ; if ( credential != null ) { userSecurityName = ( String ) invokeMethod ( getSecurityNameMethod ( ) , credential ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Websphere security name is \" + userSecurityName + \" for subject \" + subject ) ; } return userSecurityName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the WebSphere group names for the given security name . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static List < String > getWebSphereGroups ( final String securityName ) { Context ic = null ; try { // TODO: Cache UserRegistry object ic = new InitialContext ( ) ; Object objRef = ic . lookup ( USER_REGISTRY ) ; Object userReg = invokeMethod ( getNarrowMethod ( ) , null , objRef , Class . forName ( \"com.ibm.websphere.security.UserRegistry\" ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Determining WebSphere groups for user \" + securityName + \" using WebSphere UserRegistry \" + userReg ) ; } final Collection groups = ( Collection ) invokeMethod ( getGroupsForUserMethod ( ) , userReg , new Object [ ] { securityName } ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Groups for user \" + securityName + \": \" + groups . toString ( ) ) ; } return new ArrayList ( groups ) ; } catch ( Exception e ) { logger . error ( \"Exception occured while looking up groups for user\" , e ) ; throw new RuntimeException ( \"Exception occured while looking up groups for user\" , e ) ; } finally { try { if ( ic != null ) { ic . close ( ) ; } } catch ( NamingException e ) { logger . debug ( \"Exception occured while closing context\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the password for the current user . The username is obtained from the security context . [CODESPLIT] public void changePassword ( final String oldPassword , final String newPassword ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; Assert . notNull ( authentication , \"No authentication object found in security context. Can't change current user's password!\" ) ; String username = authentication . getName ( ) ; logger . debug ( \"Changing password for user '\" + username ) ; DistinguishedName userDn = usernameMapper . buildDn ( username ) ; if ( usePasswordModifyExtensionOperation ) { changePasswordUsingExtensionOperation ( userDn , oldPassword , newPassword ) ; } else { changePasswordUsingAttributeModification ( userDn , oldPassword , newPassword ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a DN from a group name . [CODESPLIT] protected DistinguishedName buildGroupDn ( String group ) { DistinguishedName dn = new DistinguishedName ( groupSearchBase ) ; dn . add ( groupRoleAttributeName , group . toLowerCase ( ) ) ; return dn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the name of the multi - valued attribute which holds the DNs of users who are members of a group . <p > Usually this will be <tt > uniquemember< / tt > ( the default value ) or <tt > member< / tt > . < / p > [CODESPLIT] public void setGroupMemberAttributeName ( String groupMemberAttributeName ) { Assert . hasText ( groupMemberAttributeName , \"groupMemberAttributeName should have text\" ) ; this . groupMemberAttributeName = groupMemberAttributeName ; this . groupSearchFilter = \"(\" + groupMemberAttributeName + \"={0})\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public List < ObjectIdentity > findChildren ( ObjectIdentity parentIdentity ) { Object [ ] args = { parentIdentity . getIdentifier ( ) . toString ( ) , parentIdentity . getType ( ) } ; List < ObjectIdentity > objects = jdbcOperations . query ( findChildrenSql , args , new RowMapper < ObjectIdentity > ( ) { public ObjectIdentity mapRow ( ResultSet rs , int rowNum ) throws SQLException { String javaType = rs . getString ( \"class\" ) ; Serializable identifier = ( Serializable ) rs . getObject ( \"obj_id\" ) ; identifier = aclClassIdUtils . identifierFrom ( identifier , rs ) ; return new ObjectIdentityImpl ( javaType , identifier ) ; } } ) ; if ( objects . size ( ) == 0 ) { return null ; } return objects ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public Object decide ( Authentication authentication , Object object , Collection < ConfigAttribute > config , Object returnedObject ) throws AccessDeniedException { if ( returnedObject == null ) { // AclManager interface contract prohibits nulls // As they have permission to null/nothing, grant access logger . debug ( \"Return object is null, skipping\" ) ; return null ; } if ( ! getProcessDomainObjectClass ( ) . isAssignableFrom ( returnedObject . getClass ( ) ) ) { logger . debug ( \"Return object is not applicable for this provider, skipping\" ) ; return returnedObject ; } for ( ConfigAttribute attr : config ) { if ( ! this . supports ( attr ) ) { continue ; } // Need to make an access decision on this invocation if ( hasPermission ( authentication , returnedObject ) ) { return returnedObject ; } logger . debug ( \"Denying access\" ) ; throw new AccessDeniedException ( messages . getMessage ( \"AclEntryAfterInvocationProvider.noPermission\" , new Object [ ] { authentication . getName ( ) , returnedObject } , \"Authentication {0} has NO permissions to the domain object {1}\" ) ) ; } return returnedObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In addition to the steps from the superclass the sessionRegistry will be updated with the new session information . [CODESPLIT] public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) { final List < SessionInformation > sessions = sessionRegistry . getAllSessions ( authentication . getPrincipal ( ) , false ) ; int sessionCount = sessions . size ( ) ; int allowedSessions = getMaximumSessionsForThisUser ( authentication ) ; if ( sessionCount < allowedSessions ) { // They haven't got too many login sessions running at present return ; } if ( allowedSessions == - 1 ) { // We permit unlimited logins return ; } if ( sessionCount == allowedSessions ) { HttpSession session = request . getSession ( false ) ; if ( session != null ) { // Only permit it though if this request is associated with one of the // already registered sessions for ( SessionInformation si : sessions ) { if ( si . getSessionId ( ) . equals ( session . getId ( ) ) ) { return ; } } } // If the session is null, a new one will be created by the parent class, // exceeding the allowed number } allowableSessionsExceeded ( sessions , allowedSessions , sessionRegistry ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows subclasses to customise behaviour when too many sessions are detected . [CODESPLIT] protected void allowableSessionsExceeded ( List < SessionInformation > sessions , int allowableSessions , SessionRegistry registry ) throws SessionAuthenticationException { if ( exceptionIfMaximumExceeded || ( sessions == null ) ) { throw new SessionAuthenticationException ( messages . getMessage ( \"ConcurrentSessionControlAuthenticationStrategy.exceededAllowed\" , new Object [ ] { Integer . valueOf ( allowableSessions ) } , \"Maximum sessions of {0} for this principal exceeded\" ) ) ; } // Determine least recently used session, and mark it for invalidation SessionInformation leastRecentlyUsed = null ; for ( SessionInformation session : sessions ) { if ( ( leastRecentlyUsed == null ) || session . getLastRequest ( ) . before ( leastRecentlyUsed . getLastRequest ( ) ) ) { leastRecentlyUsed = session ; } } leastRecentlyUsed . expireNow ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect error details from the provided parameters and format according to RFC 6750 specifically { @code error } { @code error_description } { @code error_uri } and { @scope scope } . [CODESPLIT] @ Override public void commence ( HttpServletRequest request , HttpServletResponse response , AuthenticationException authException ) throws IOException , ServletException { HttpStatus status = HttpStatus . UNAUTHORIZED ; Map < String , String > parameters = new LinkedHashMap <> ( ) ; if ( this . realmName != null ) { parameters . put ( \"realm\" , this . realmName ) ; } if ( authException instanceof OAuth2AuthenticationException ) { OAuth2Error error = ( ( OAuth2AuthenticationException ) authException ) . getError ( ) ; parameters . put ( \"error\" , error . getErrorCode ( ) ) ; if ( StringUtils . hasText ( error . getDescription ( ) ) ) { parameters . put ( \"error_description\" , error . getDescription ( ) ) ; } if ( StringUtils . hasText ( error . getUri ( ) ) ) { parameters . put ( \"error_uri\" , error . getUri ( ) ) ; } if ( error instanceof BearerTokenError ) { BearerTokenError bearerTokenError = ( BearerTokenError ) error ; if ( StringUtils . hasText ( bearerTokenError . getScope ( ) ) ) { parameters . put ( \"scope\" , bearerTokenError . getScope ( ) ) ; } status = ( ( BearerTokenError ) error ) . getHttpStatus ( ) ; } } String wwwAuthenticate = computeWWWAuthenticateHeaderValue ( parameters ) ; response . addHeader ( HttpHeaders . WWW_AUTHENTICATE , wwwAuthenticate ) ; response . setStatus ( status . value ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode and validate the <a href = https : // tools . ietf . org / html / rfc6750#section - 1 . 2 target = _blank > Bearer Token< / a > . [CODESPLIT] @ Override public Authentication authenticate ( Authentication authentication ) throws AuthenticationException { BearerTokenAuthenticationToken bearer = ( BearerTokenAuthenticationToken ) authentication ; Jwt jwt ; try { jwt = this . jwtDecoder . decode ( bearer . getToken ( ) ) ; } catch ( JwtException failed ) { OAuth2Error invalidToken = invalidToken ( failed . getMessage ( ) ) ; throw new OAuth2AuthenticationException ( invalidToken , invalidToken . getDescription ( ) , failed ) ; } AbstractAuthenticationToken token = this . jwtAuthenticationConverter . convert ( jwt ) ; token . setDetails ( bearer . getDetails ( ) ) ; return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link MultiValueMap } of the form parameters used for the Access Token Request body . [CODESPLIT] private MultiValueMap < String , String > buildFormParameters ( OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest ) { ClientRegistration clientRegistration = clientCredentialsGrantRequest . getClientRegistration ( ) ; MultiValueMap < String , String > formParameters = new LinkedMultiValueMap <> ( ) ; formParameters . add ( OAuth2ParameterNames . GRANT_TYPE , clientCredentialsGrantRequest . getGrantType ( ) . getValue ( ) ) ; if ( ! CollectionUtils . isEmpty ( clientRegistration . getScopes ( ) ) ) { formParameters . add ( OAuth2ParameterNames . SCOPE , StringUtils . collectionToDelimitedString ( clientRegistration . getScopes ( ) , \" \" ) ) ; } if ( ClientAuthenticationMethod . POST . equals ( clientRegistration . getClientAuthenticationMethod ( ) ) ) { formParameters . add ( OAuth2ParameterNames . CLIENT_ID , clientRegistration . getClientId ( ) ) ; formParameters . add ( OAuth2ParameterNames . CLIENT_SECRET , clientRegistration . getClientSecret ( ) ) ; } return formParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to authenticate the passed { @link Authentication } object . <p > The list of { @link AuthenticationProvider } s will be successively tried until an <code > AuthenticationProvider< / code > indicates it is capable of authenticating the type of <code > Authentication< / code > object passed . Authentication will then be attempted with that <code > AuthenticationProvider< / code > . <p > If more than one <code > AuthenticationProvider< / code > supports the passed <code > Authentication< / code > object the first one able to successfully authenticate the <code > Authentication< / code > object determines the <code > result< / code > overriding any possible <code > AuthenticationException< / code > thrown by earlier supporting <code > AuthenticationProvider< / code > s . On successful authentication no subsequent <code > AuthenticationProvider< / code > s will be tried . If authentication was not successful by any supporting <code > AuthenticationProvider< / code > the last thrown <code > AuthenticationException< / code > will be rethrown . [CODESPLIT] public Authentication authenticate ( Authentication authentication ) throws AuthenticationException { Class < ? extends Authentication > toTest = authentication . getClass ( ) ; AuthenticationException lastException = null ; AuthenticationException parentException = null ; Authentication result = null ; Authentication parentResult = null ; boolean debug = logger . isDebugEnabled ( ) ; for ( AuthenticationProvider provider : getProviders ( ) ) { if ( ! provider . supports ( toTest ) ) { continue ; } if ( debug ) { logger . debug ( \"Authentication attempt using \" + provider . getClass ( ) . getName ( ) ) ; } try { result = provider . authenticate ( authentication ) ; if ( result != null ) { copyDetails ( authentication , result ) ; break ; } } catch ( AccountStatusException e ) { prepareException ( e , authentication ) ; // SEC-546: Avoid polling additional providers if auth failure is due to // invalid account status throw e ; } catch ( InternalAuthenticationServiceException e ) { prepareException ( e , authentication ) ; throw e ; } catch ( AuthenticationException e ) { lastException = e ; } } if ( result == null && parent != null ) { // Allow the parent to try. try { result = parentResult = parent . authenticate ( authentication ) ; } catch ( ProviderNotFoundException e ) { // ignore as we will throw below if no other exception occurred prior to // calling parent and the parent // may throw ProviderNotFound even though a provider in the child already // handled the request } catch ( AuthenticationException e ) { lastException = parentException = e ; } } if ( result != null ) { if ( eraseCredentialsAfterAuthentication && ( result instanceof CredentialsContainer ) ) { // Authentication is complete. Remove credentials and other secret data // from authentication ( ( CredentialsContainer ) result ) . eraseCredentials ( ) ; } // If the parent AuthenticationManager was attempted and successful than it will publish an AuthenticationSuccessEvent // This check prevents a duplicate AuthenticationSuccessEvent if the parent AuthenticationManager already published it if ( parentResult == null ) { eventPublisher . publishAuthenticationSuccess ( result ) ; } return result ; } // Parent was null, or didn't authenticate (or throw an exception). if ( lastException == null ) { lastException = new ProviderNotFoundException ( messages . getMessage ( \"ProviderManager.providerNotFound\" , new Object [ ] { toTest . getName ( ) } , \"No AuthenticationProvider found for {0}\" ) ) ; } // If the parent AuthenticationManager was attempted and failed than it will publish an AbstractAuthenticationFailureEvent // This check prevents a duplicate AbstractAuthenticationFailureEvent if the parent AuthenticationManager already published it if ( parentException == null ) { prepareException ( lastException , authentication ) ; } throw lastException ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the authentication details from a source Authentication object to a destination one provided the latter does not already have one set . [CODESPLIT] private void copyDetails ( Authentication source , Authentication dest ) { if ( ( dest instanceof AbstractAuthenticationToken ) && ( dest . getDetails ( ) == null ) ) { AbstractAuthenticationToken token = ( AbstractAuthenticationToken ) dest ; token . setDetails ( source . getDetails ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when a user is newly authenticated . <p > If a session already exists and matches the session Id from the client a new session will be created and the session attributes copied to it ( if { [CODESPLIT] public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) { boolean hadSessionAlready = request . getSession ( false ) != null ; if ( ! hadSessionAlready && ! alwaysCreateSession ) { // Session fixation isn't a problem if there's no session return ; } // Create new session if necessary HttpSession session = request . getSession ( ) ; if ( hadSessionAlready && request . isRequestedSessionIdValid ( ) ) { String originalSessionId ; String newSessionId ; Object mutex = WebUtils . getSessionMutex ( session ) ; synchronized ( mutex ) { // We need to migrate to a new session originalSessionId = session . getId ( ) ; session = applySessionFixation ( request ) ; newSessionId = session . getId ( ) ; } if ( originalSessionId . equals ( newSessionId ) ) { logger . warn ( \"Your servlet container did not change the session ID when a new session was created. You will\" + \" not be adequately protected against session-fixation attacks\" ) ; } onSessionChange ( originalSessionId , session , authentication ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the session has been changed and the old attributes have been migrated to the new session . Only called if a session existed to start with . Allows subclasses to plug in additional behaviour . * <p > The default implementation of this method publishes a { @link SessionFixationProtectionEvent } to notify the application that the session ID has changed . If you override this method and still wish these events to be published you should call { @code super . onSessionChange () } within your overriding method . [CODESPLIT] protected void onSessionChange ( String originalSessionId , HttpSession newSession , Authentication auth ) { applicationEventPublisher . publishEvent ( new SessionFixationProtectionEvent ( auth , originalSessionId , newSession . getId ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the <tt > RoleHierarchy< / tt > to obtain the complete set of user authorities . [CODESPLIT] @ Override Collection < ? extends GrantedAuthority > extractAuthorities ( Authentication authentication ) { return roleHierarchy . getReachableGrantedAuthorities ( authentication . getAuthorities ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first filter chain matching the supplied URL . [CODESPLIT] private List < Filter > getFilters ( HttpServletRequest request ) { for ( SecurityFilterChain chain : filterChains ) { if ( chain . matches ( request ) ) { return chain . getFilters ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method mainly for testing . [CODESPLIT] public List < Filter > getFilters ( String url ) { return getFilters ( firewall . getFirewalledRequest ( ( new FilterInvocation ( url , \"GET\" ) . getRequest ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public int doStartTag ( ) throws JspException { if ( ( null == hasPermission ) || \"\" . equals ( hasPermission ) ) { return skipBody ( ) ; } initializeIfRequired ( ) ; if ( domainObject == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"domainObject resolved to null, so including tag body\" ) ; } // Of course they have access to a null object! return evalBody ( ) ; } Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"SecurityContextHolder did not return a non-null Authentication object, so skipping tag body\" ) ; } return skipBody ( ) ; } List < Object > requiredPermissions = parseHasPermission ( hasPermission ) ; for ( Object requiredPermission : requiredPermissions ) { if ( ! permissionEvaluator . hasPermission ( authentication , domainObject , requiredPermission ) ) { return skipBody ( ) ; } } return evalBody ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows test cases to override where application context obtained from . [CODESPLIT] protected ApplicationContext getContext ( PageContext pageContext ) { ServletContext servletContext = pageContext . getServletContext ( ) ; return SecurityWebApplicationContextUtils . findRequiredWebApplicationContext ( servletContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the final { @code Authentication } object which will be returned from the { @code authenticate } method . [CODESPLIT] protected Authentication createSuccessfulAuthentication ( UsernamePasswordAuthenticationToken authentication , UserDetails user ) { Object password = this . useAuthenticationRequestCredentials ? authentication . getCredentials ( ) : user . getPassword ( ) ; UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken ( user , password , this . authoritiesMapper . mapAuthorities ( user . getAuthorities ( ) ) ) ; result . setDetails ( authentication . getDetails ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public void securityCheck ( Acl acl , int changeType ) { if ( ( SecurityContextHolder . getContext ( ) == null ) || ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) == null ) || ! SecurityContextHolder . getContext ( ) . getAuthentication ( ) . isAuthenticated ( ) ) { throw new AccessDeniedException ( \"Authenticated principal required to operate with ACLs\" ) ; } Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; // Check if authorized by virtue of ACL ownership Sid currentUser = createCurrentUser ( authentication ) ; if ( currentUser . equals ( acl . getOwner ( ) ) && ( ( changeType == CHANGE_GENERAL ) || ( changeType == CHANGE_OWNERSHIP ) ) ) { return ; } // Not authorized by ACL ownership; try via adminstrative permissions GrantedAuthority requiredAuthority ; if ( changeType == CHANGE_AUDITING ) { requiredAuthority = this . gaModifyAuditing ; } else if ( changeType == CHANGE_GENERAL ) { requiredAuthority = this . gaGeneralChanges ; } else if ( changeType == CHANGE_OWNERSHIP ) { requiredAuthority = this . gaTakeOwnership ; } else { throw new IllegalArgumentException ( \"Unknown change type\" ) ; } // Iterate this principal's authorities to determine right Set < String > authorities = AuthorityUtils . authorityListToSet ( authentication . getAuthorities ( ) ) ; if ( authorities . contains ( requiredAuthority . getAuthority ( ) ) ) { return ; } // Try to get permission via ACEs within the ACL List < Sid > sids = sidRetrievalStrategy . getSids ( authentication ) ; if ( acl . isGranted ( Arrays . asList ( BasePermission . ADMINISTRATION ) , sids , false ) ) { return ; } throw new AccessDeniedException ( \"Principal does not have required ACL permissions to perform requested operation\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register escalate and configure the AspectJ auto proxy creator based on the value of the [CODESPLIT] public void registerBeanDefinitions ( AnnotationMetadata importingClassMetadata , BeanDefinitionRegistry registry ) { BeanDefinitionBuilder advisor = BeanDefinitionBuilder . rootBeanDefinition ( MethodSecurityMetadataSourceAdvisor . class ) ; advisor . setRole ( BeanDefinition . ROLE_INFRASTRUCTURE ) ; advisor . addConstructorArgValue ( \"methodSecurityInterceptor\" ) ; advisor . addConstructorArgReference ( \"methodSecurityMetadataSource\" ) ; advisor . addConstructorArgValue ( \"methodSecurityMetadataSource\" ) ; MultiValueMap < String , Object > attributes = importingClassMetadata . getAllAnnotationAttributes ( EnableGlobalMethodSecurity . class . getName ( ) ) ; Integer order = ( Integer ) attributes . getFirst ( \"order\" ) ; if ( order != null ) { advisor . addPropertyValue ( \"order\" , order ) ; } registry . registerBeanDefinition ( \"metaDataSourceAdvisor\" , advisor . getBeanDefinition ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================== [CODESPLIT] public static void closeContext ( Context ctx ) { if ( ctx instanceof DirContextAdapter ) { return ; } try { if ( ctx != null ) { ctx . close ( ) ; } } catch ( NamingException e ) { logger . error ( \"Failed to close context.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the part of a DN relative to a supplied base context . <p > If the DN is cn = bob ou = people dc = springframework dc = org and the base context name is ou = people dc = springframework dc = org it would return cn = bob . < / p > [CODESPLIT] public static String getRelativeName ( String fullDn , Context baseCtx ) throws NamingException { String baseDn = baseCtx . getNameInNamespace ( ) ; if ( baseDn . length ( ) == 0 ) { return fullDn ; } DistinguishedName base = new DistinguishedName ( baseDn ) ; DistinguishedName full = new DistinguishedName ( fullDn ) ; if ( base . equals ( full ) ) { return \"\" ; } Assert . isTrue ( full . startsWith ( base ) , \"Full DN does not start with base DN\" ) ; full . removeFirst ( base ) ; return full . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the full dn of a name by prepending the name of the context it is relative to . If the name already contains the base name it is returned unaltered . [CODESPLIT] public static DistinguishedName getFullDn ( DistinguishedName dn , Context baseCtx ) throws NamingException { DistinguishedName baseDn = new DistinguishedName ( baseCtx . getNameInNamespace ( ) ) ; if ( dn . contains ( baseDn ) ) { return dn ; } baseDn . append ( dn ) ; return baseDn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link Converter Converter&lt ; Jwt Flux&lt ; GrantedAuthority&gt ; &gt ; } to use . Defaults to a reactive { @link JwtGrantedAuthoritiesConverter } . [CODESPLIT] public void setJwtGrantedAuthoritiesConverter ( Converter < Jwt , Flux < GrantedAuthority > > jwtGrantedAuthoritiesConverter ) { Assert . notNull ( jwtGrantedAuthoritiesConverter , \"jwtGrantedAuthoritiesConverter cannot be null\" ) ; this . jwtGrantedAuthoritiesConverter = jwtGrantedAuthoritiesConverter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Mono < Void > filter ( ServerWebExchange exchange , WebFilterChain chain ) { return Mono . just ( exchange ) . filter ( this :: isInsecure ) . flatMap ( this . requiresHttpsRedirectMatcher :: matches ) . filter ( matchResult -> matchResult . isMatch ( ) ) . switchIfEmpty ( chain . filter ( exchange ) . then ( Mono . empty ( ) ) ) . map ( matchResult -> createRedirectUri ( exchange ) ) . flatMap ( uri -> this . redirectStrategy . sendRedirect ( exchange , uri ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set session attributes . [CODESPLIT] public MockMvcRequestSpecification sessionAttrs ( Map < String , Object > sessionAttributes ) { notNull ( sessionAttributes , \"sessionAttributes\" ) ; parameterUpdater . updateParameters ( convert ( cfg . getMockMvcParamConfig ( ) . sessionAttributesUpdateStrategy ( ) ) , sessionAttributes , this . sessionAttributes ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a session attribute . [CODESPLIT] public MockMvcRequestSpecification sessionAttr ( String name , Object value ) { notNull ( name , \"Session attribute name\" ) ; parameterUpdater . updateZeroToManyParameters ( convert ( cfg . getMockMvcParamConfig ( ) . sessionAttributesUpdateStrategy ( ) ) , sessionAttributes , name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable Cross - site request forgery ( csrf ) support when using form authentication by including the csrf value of the input field with the specified name . For example if the login page looks like this : <pre > &lt ; html&gt ; &lt ; head&gt ; &lt ; title&gt ; Login&lt ; / title&gt ; &lt ; / head&gt ; &lt ; body&gt ; &lt ; form action = &quot ; j_spring_security_check_with_csrf&quot ; method = &quot ; POST&quot ; &gt ; &lt ; table&gt ; &lt ; tr&gt ; &lt ; td&gt ; User : &amp ; nbsp ; &lt ; / td&gt ; &lt ; td&gt ; &lt ; input type = &quot ; text&quot ; name = &quot ; j_username&quot ; &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; tr&gt ; &lt ; td&gt ; Password : &lt ; / td&gt ; &lt ; td&gt ; &lt ; input type = &quot ; password&quot ; name = &quot ; j_password&quot ; &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; tr&gt ; &lt ; td colspan = &quot ; 2&quot ; &gt ; &lt ; input name = &quot ; submit&quot ; type = &quot ; submit&quot ; / &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; / table&gt ; &lt ; input type = &quot ; hidden&quot ; name = &quot ; _csrf&quot ; value = &quot ; 8adf2ea1 - b246 - 40aa - 8e13 - a85fb7914341&quot ; / &gt ; &lt ; / form&gt ; &lt ; / body&gt ; &lt ; / html&gt ; < / pre > The csrf field name is called <code > _csrf< / code > . <p / > <b > Important : < / b > When enabling csrf support then REST Assured <b > must always< / b > make an additional request to the server in order to be able to include in the csrf value which will slow down the tests . [CODESPLIT] public FormAuthConfig withCsrfFieldName ( String fieldName ) { notNull ( fieldName , \"CSRF field name\" ) ; if ( autoDetectCsrfFieldName ) { throw new IllegalStateException ( \"Cannot defined a CSRF field name since the CSRF field name has been marked as auto-detected.\" ) ; } return new FormAuthConfig ( formAction , userInputTagName , passwordInputTagName , logDetail , logConfig , fieldName , false , sendCsrfTokenAsFormParam , additionalInputFieldNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include additional field when using form authentication by including input field value with the specified name . For example if the login page looks like this : <pre > &lt ; html&gt ; &lt ; head&gt ; &lt ; title&gt ; Login&lt ; / title&gt ; &lt ; / head&gt ; &lt ; body&gt ; &lt ; form action = &quot ; j_spring_security_check_with_csrf&quot ; method = &quot ; POST&quot ; &gt ; &lt ; table&gt ; &lt ; tr&gt ; &lt ; td&gt ; User : &amp ; nbsp ; &lt ; / td&gt ; &lt ; td&gt ; &lt ; input type = &quot ; text&quot ; name = &quot ; j_username&quot ; &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; tr&gt ; &lt ; td&gt ; Password : &lt ; / td&gt ; &lt ; td&gt ; &lt ; input type = &quot ; password&quot ; name = &quot ; j_password&quot ; &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; tr&gt ; &lt ; td colspan = &quot ; 2&quot ; &gt ; &lt ; input name = &quot ; submit&quot ; type = &quot ; submit&quot ; / &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; / table&gt ; &lt ; input type = &quot ; hidden&quot ; name = &quot ; something&quot ; value = &quot ; 8adf2ea1 - b246 - 40aa - 8e13 - a85fb7914341&quot ; / &gt ; &lt ; / form&gt ; &lt ; / body&gt ; &lt ; / html&gt ; < / pre > and you d like to include the field named <code > something< / code > as an additional form parameter in the request you can do like this : [CODESPLIT] public FormAuthConfig withAdditionalField ( String fieldName ) { notNull ( fieldName , \"Additional field name\" ) ; List < String > list = new ArrayList < String > ( additionalInputFieldNames ) ; list . add ( fieldName ) ; return new FormAuthConfig ( formAction , userInputTagName , passwordInputTagName , logDetail , logConfig , csrfFieldName , autoDetectCsrfFieldName , sendCsrfTokenAsFormParam , list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include multiple additional fields when using form authentication by including input field values with the specified name . This is the same as { @link #withAdditionalField ( String ) } but for multiple fields . [CODESPLIT] public FormAuthConfig withAdditionalFields ( String firstFieldName , String secondFieldName , String ... additionalFieldNames ) { notNull ( firstFieldName , \"First additional field name\" ) ; notNull ( secondFieldName , \"Second additional field name\" ) ; List < String > list = new ArrayList < String > ( additionalInputFieldNames ) ; list . add ( firstFieldName ) ; list . add ( secondFieldName ) ; if ( additionalFieldNames != null && additionalFieldNames . length > 0 ) { list . addAll ( Arrays . asList ( additionalFieldNames ) ) ; } return new FormAuthConfig ( formAction , userInputTagName , passwordInputTagName , logDetail , logConfig , csrfFieldName , autoDetectCsrfFieldName , sendCsrfTokenAsFormParam , list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable Cross - site request forgery ( csrf ) support when using form authentication by automatically trying to find the name and value of the csrf input field . For example if the login page looks like this : <pre > &lt ; html&gt ; &lt ; head&gt ; &lt ; title&gt ; Login&lt ; / title&gt ; &lt ; / head&gt ; &lt ; body&gt ; &lt ; form action = &quot ; j_spring_security_check_with_csrf&quot ; method = &quot ; POST&quot ; &gt ; &lt ; table&gt ; &lt ; tr&gt ; &lt ; td&gt ; User : &amp ; nbsp ; &lt ; / td&gt ; &lt ; td&gt ; &lt ; input type = &quot ; text&quot ; name = &quot ; j_username&quot ; &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; tr&gt ; &lt ; td&gt ; Password : &lt ; / td&gt ; &lt ; td&gt ; &lt ; input type = &quot ; password&quot ; name = &quot ; j_password&quot ; &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; tr&gt ; &lt ; td colspan = &quot ; 2&quot ; &gt ; &lt ; input name = &quot ; submit&quot ; type = &quot ; submit&quot ; / &gt ; &lt ; / td&gt ; &lt ; / tr&gt ; &lt ; / table&gt ; &lt ; input type = &quot ; hidden&quot ; name = &quot ; _csrf&quot ; value = &quot ; 8adf2ea1 - b246 - 40aa - 8e13 - a85fb7914341&quot ; / &gt ; &lt ; / form&gt ; &lt ; / body&gt ; &lt ; / html&gt ; < / pre > The csrf field name is called <code > _csrf< / code > and REST Assured will autodetect its name since the field name is the only <code > hidden< / code > field on this page . If auto - detection fails you can consider using { @link #withCsrfFieldName ( String ) } . <p / > <b > Important : < / b > When enabling csrf support then REST Assured <b > must always< / b > make an additional request to the server in order to be able to include in the csrf value which will slow down the tests . [CODESPLIT] public FormAuthConfig withAutoDetectionOfCsrf ( ) { if ( hasCsrfFieldName ( ) ) { throw new IllegalStateException ( format ( \"Cannot use auto-detection of CSRF field name since a CSRF field name was already defined as '%s'\" , csrfFieldName ) ) ; } return new FormAuthConfig ( formAction , userInputTagName , passwordInputTagName , logDetail , logConfig , csrfFieldName , true , sendCsrfTokenAsFormParam , additionalInputFieldNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables logging with the supplied log detail of the request made to authenticate using form authentication using the specified { @link LogConfig } . Both the request and the response is logged . [CODESPLIT] public FormAuthConfig withLoggingEnabled ( LogDetail logDetail , LogConfig logConfig ) { notNull ( logDetail , LogDetail . class ) ; notNull ( logConfig , LogConfig . class ) ; return new FormAuthConfig ( formAction , userInputTagName , passwordInputTagName , logDetail , logConfig , csrfFieldName , autoDetectCsrfFieldName , sendCsrfTokenAsFormParam , additionalInputFieldNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use preemptive http basic authentication . This means that the authentication details are sent in the request header regardless if the server has challenged for authentication or not . [CODESPLIT] public AuthenticationScheme basic ( String userName , String password ) { final PreemptiveBasicAuthScheme preemptiveBasicAuthScheme = new PreemptiveBasicAuthScheme ( ) ; preemptiveBasicAuthScheme . setUserName ( userName ) ; preemptiveBasicAuthScheme . setPassword ( password ) ; return preemptiveBasicAuthScheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add default filters that will be applied to each request . [CODESPLIT] public static void filters ( List < Filter > filters ) { Validate . notNull ( filters , \"Filter list cannot be null\" ) ; RestAssured . filters . addAll ( filters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add default filters to apply to each request . [CODESPLIT] public static void filters ( Filter filter , Filter ... additionalFilters ) { Validate . notNull ( filter , \"Filter cannot be null\" ) ; RestAssured . filters . add ( filter ) ; if ( additionalFilters != null ) { Collections . addAll ( RestAssured . filters , additionalFilters ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the default filters to apply to each request . [CODESPLIT] public static void replaceFiltersWith ( List < Filter > filters ) { Validate . notNull ( filters , \"Filter list cannot be null\" ) ; RestAssured . filters . clear ( ) ; filters ( filters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the default filters to apply to each request . [CODESPLIT] public static void replaceFiltersWith ( Filter filter , Filter ... additionalFilters ) { Validate . notNull ( filter , \"Filter cannot be null\" ) ; RestAssured . filters . clear ( ) ; filters ( filter , additionalFilters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a object mapper that ll be used when serializing and deserializing Java objects to and from it s document representation ( XML JSON etc ) . [CODESPLIT] public static void objectMapper ( ObjectMapper objectMapper ) { Validate . notNull ( objectMapper , \"Default object mapper cannot be null\" ) ; config = config ( ) . objectMapperConfig ( ObjectMapperConfig . objectMapperConfig ( ) . defaultObjectMapper ( objectMapper ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a list of arguments that can be used to create parts of the path in a body / content expression . This is useful in situations where you have e . g . pre - defined variables that constitutes the key . For example : <pre > String someSubPath = else ; int index = 1 ; when () . get () . then () . body ( something . %s [ %d ] withArgs ( someSubPath index ) equalTo ( some value )) . .. < / pre > <p / > or if you have complex root paths and don t wish to duplicate the path for small variations : <pre > get ( / x ) . then () . assertThat () . root ( filters . filterConfig [ %d ] . filterConfigGroups . find { it . name == Gold } . includes ) . body ( withArgs ( 0 ) hasItem ( first )) . body ( withArgs ( 1 ) hasItem ( second )) . .. < / pre > <p / > The key and arguments follows the standard <a href = http : // download . oracle . com / javase / 1 5 . 0 / docs / api / java / util / Formatter . html#syntax > formatting syntax< / a > of Java . [CODESPLIT] public static List < Argument > withArgs ( Object firstArgument , Object ... additionalArguments ) { Validate . notNull ( firstArgument , \"You need to supply at least one argument\" ) ; final List < Argument > arguments = new LinkedList < Argument > ( ) ; arguments . add ( Argument . arg ( firstArgument ) ) ; if ( additionalArguments != null && additionalArguments . length > 0 ) { for ( Object additionalArgument : additionalArguments ) { arguments . add ( Argument . arg ( additionalArgument ) ) ; } } return Collections . unmodifiableList ( arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a GET request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response get ( String path , Object ... pathParams ) { return given ( ) . get ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a GET request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response get ( String path , Map < String , ? > pathParams ) { return given ( ) . get ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a POST request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response post ( String path , Object ... pathParams ) { return given ( ) . post ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a POST request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response post ( String path , Map < String , ? > pathParams ) { return given ( ) . post ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a PUT request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response put ( String path , Object ... pathParams ) { return given ( ) . put ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a DELETE request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response delete ( String path , Object ... pathParams ) { return given ( ) . delete ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a DELETE request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response delete ( String path , Map < String , ? > pathParams ) { return given ( ) . delete ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a HEAD request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response head ( String path , Object ... pathParams ) { return given ( ) . head ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a HEAD request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response head ( String path , Map < String , ? > pathParams ) { return given ( ) . head ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a PATCH request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response patch ( String path , Object ... pathParams ) { return given ( ) . patch ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a PATCH request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response patch ( String path , Map < String , ? > pathParams ) { return given ( ) . patch ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a OPTIONS request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response options ( String path , Object ... pathParams ) { return given ( ) . options ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a OPTIONS request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static Response options ( String path , Map < String , ? > pathParams ) { return given ( ) . options ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a request to a <code > uri< / code > . [CODESPLIT] public static Response request ( Method method , URI uri ) { return given ( ) . request ( method , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a request to a <code > url< / code > . [CODESPLIT] public static Response request ( Method method , URL url ) { return given ( ) . request ( method , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a custom HTTP request to a <code > uri< / code > . [CODESPLIT] public static Response request ( String method , URI uri ) { return given ( ) . request ( method , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a custom HTTP request to a <code > url< / code > . [CODESPLIT] public static Response request ( String method , URL url ) { return given ( ) . request ( method , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a http basic authentication scheme . [CODESPLIT] public static AuthenticationScheme basic ( String userName , String password ) { final BasicAuthScheme scheme = new BasicAuthScheme ( ) ; scheme . setUserName ( userName ) ; scheme . setPassword ( password ) ; return scheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a NTLM authentication scheme . [CODESPLIT] public static AuthenticationScheme ntlm ( String userName , String password , String workstation , String domain ) { final NTLMAuthScheme scheme = new NTLMAuthScheme ( ) ; scheme . setUserName ( userName ) ; scheme . setPassword ( password ) ; scheme . setWorkstation ( workstation ) ; scheme . setDomain ( domain ) ; return scheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use form authentication . Rest Assured will try to parse the response login page and determine and try find the action username and password input field automatically . <p > Note that the request will be much faster if you also supply a form auth configuration . < / p > [CODESPLIT] public static AuthenticationScheme form ( String userName , String password ) { return form ( userName , password , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use form authentication with the supplied configuration . [CODESPLIT] public static AuthenticationScheme form ( String userName , String password , FormAuthConfig config ) { if ( userName == null ) { throw new IllegalArgumentException ( \"Username cannot be null\" ) ; } if ( password == null ) { throw new IllegalArgumentException ( \"Password cannot be null\" ) ; } final FormAuthScheme scheme = new FormAuthScheme ( ) ; scheme . setUserName ( userName ) ; scheme . setPassword ( password ) ; scheme . setConfig ( config ) ; return scheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a certificate to be used for SSL authentication . See { @link java . lang . Class#getResource ( String ) } for how to get a URL from a resource on the classpath . <p > Uses SSL settings defined in { @link SSLConfig } . < / p > [CODESPLIT] public static AuthenticationScheme certificate ( String certURL , String password ) { SSLConfig sslConfig = config ( ) . getSSLConfig ( ) ; return certificate ( certURL , password , CertificateAuthSettings . certAuthSettings ( ) . keyStoreType ( sslConfig . getKeyStoreType ( ) ) . trustStore ( sslConfig . getTrustStore ( ) ) . keyStore ( sslConfig . getKeyStore ( ) ) . trustStoreType ( sslConfig . getTrustStoreType ( ) ) . x509HostnameVerifier ( sslConfig . getX509HostnameVerifier ( ) ) . port ( sslConfig . getPort ( ) ) . sslSocketFactory ( sslConfig . getSSLSocketFactory ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a certificate to be used for SSL authentication . See { @link Class#getResource ( String ) } for how to get a URL from a resource on the classpath . <p / > [CODESPLIT] public static AuthenticationScheme certificate ( String certURL , String password , CertificateAuthSettings certificateAuthSettings ) { return certificate ( certURL , password , \"\" , \"\" , certificateAuthSettings ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a certificate to be used for SSL authentication . See { @link Class#getResource ( String ) } for how to get a URL from a resource on the classpath . <p / > [CODESPLIT] public static AuthenticationScheme certificate ( String trustStorePath , String trustStorePassword , String keyStorePath , String keyStorePassword , CertificateAuthSettings certificateAuthSettings ) { AssertParameter . notNull ( keyStorePath , \"Keystore path\" ) ; AssertParameter . notNull ( keyStorePassword , \"Keystore password\" ) ; AssertParameter . notNull ( trustStorePath , \"Trust store path\" ) ; AssertParameter . notNull ( trustStorePassword , \"Keystore password\" ) ; AssertParameter . notNull ( certificateAuthSettings , CertificateAuthSettings . class ) ; final CertAuthScheme scheme = new CertAuthScheme ( ) ; scheme . setPathToKeyStore ( keyStorePath ) ; scheme . setKeyStorePassword ( keyStorePassword ) ; scheme . setKeystoreType ( certificateAuthSettings . getKeyStoreType ( ) ) ; scheme . setKeyStore ( certificateAuthSettings . getKeyStore ( ) ) ; scheme . setPort ( certificateAuthSettings . getPort ( ) ) ; scheme . setTrustStore ( certificateAuthSettings . getTrustStore ( ) ) ; scheme . setTrustStoreType ( certificateAuthSettings . getTrustStoreType ( ) ) ; scheme . setPathToTrustStore ( trustStorePath ) ; scheme . setTrustStorePassword ( trustStorePassword ) ; scheme . setX509HostnameVerifier ( certificateAuthSettings . getX509HostnameVerifier ( ) ) ; scheme . setSslSocketFactory ( certificateAuthSettings . getSSLSocketFactory ( ) ) ; return scheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Excerpt from the HttpBuilder docs : <br > OAuth sign the request . Note that this currently does not wait for a WWW - Authenticate challenge before sending the the OAuth header . All requests to all domains will be signed for this instance . This assumes you ve already generated an accessToken and secretToken for the site you re targeting . For More information on how to achieve this see the <a href = https : // github . com / mttkay / signpost / blob / master / docs / GettingStarted . md#using - signpost > Signpost documentation< / a > . [CODESPLIT] public static AuthenticationScheme oauth ( String consumerKey , String consumerSecret , String accessToken , String secretToken , OAuthSignature signature ) { OAuthScheme scheme = new OAuthScheme ( ) ; scheme . setConsumerKey ( consumerKey ) ; scheme . setConsumerSecret ( consumerSecret ) ; scheme . setAccessToken ( accessToken ) ; scheme . setSecretToken ( secretToken ) ; scheme . setSignature ( signature ) ; return scheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OAuth sign the request . Note that this currently does not wait for a WWW - Authenticate challenge before sending the the OAuth header . All requests to all domains will be signed for this instance . [CODESPLIT] public static AuthenticationScheme oauth2 ( String accessToken ) { PreemptiveOAuth2HeaderScheme myScheme = new PreemptiveOAuth2HeaderScheme ( ) ; myScheme . setAccessToken ( accessToken ) ; return myScheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OAuth sign the request . Note that this currently does not wait for a WWW - Authenticate challenge before sending the the OAuth header . All requests to all domains will be signed for this instance . [CODESPLIT] public static AuthenticationScheme oauth2 ( String accessToken , OAuthSignature signature ) { OAuth2Scheme scheme = new OAuth2Scheme ( ) ; scheme . setAccessToken ( accessToken ) ; scheme . setSignature ( signature ) ; return scheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the { [CODESPLIT] public static void reset ( ) { baseURI = DEFAULT_URI ; port = UNDEFINED_PORT ; basePath = DEFAULT_PATH ; authentication = DEFAULT_AUTH ; rootPath = DEFAULT_BODY_ROOT_PATH ; filters = new LinkedList < Filter > ( ) ; requestSpecification = null ; responseSpecification = null ; urlEncodingEnabled = DEFAULT_URL_ENCODING_ENABLED ; RESPONSE_PARSER_REGISTRAR = new ResponseParserRegistrar ( ) ; defaultParser = null ; config = new RestAssuredConfig ( ) ; sessionId = DEFAULT_SESSION_ID_VALUE ; proxy = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use relaxed HTTP validation with a specific protocol . This means that you ll trust all hosts regardless if the SSL certificate is invalid . By using this method you don t need to specify a keystore ( see { @link #keyStore ( String String ) } or trust store ( see { @link #trustStore ( java . security . KeyStore ) } . <p > This is just a shortcut for : < / p > <pre > RestAssured . config = RestAssured . config () . sslConfig ( sslConfig () . relaxedHTTPSValidation ( &lt ; protocol&gt ; )) ; < / pre > [CODESPLIT] public static void useRelaxedHTTPSValidation ( String protocol ) { config = RestAssured . config ( ) . sslConfig ( SSLConfig . sslConfig ( ) . relaxedHTTPSValidation ( protocol ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable logging of both the request and the response if REST Assureds test validation fails with the specified log detail . <p / > <p > This is just a shortcut for : < / p > <pre > RestAssured . config = RestAssured . config () . logConfig ( logConfig () . enableLoggingOfRequestAndResponseIfValidationFails ( logDetail )) ; < / pre > [CODESPLIT] public static void enableLoggingOfRequestAndResponseIfValidationFails ( LogDetail logDetail ) { LogConfig logConfig = LogConfig . logConfig ( ) . enableLoggingOfRequestAndResponseIfValidationFails ( logDetail ) ; config = RestAssured . config ( ) . logConfig ( logConfig ) ; // Update request specification if already defined otherwise it'll override the configs. // Note that request spec also influence response spec when it comes to logging if validation fails due to the way filters work if ( requestSpecification != null && requestSpecification instanceof RequestSpecificationImpl ) { RestAssuredConfig restAssuredConfig = ( ( RequestSpecificationImpl ) requestSpecification ) . getConfig ( ) ; if ( restAssuredConfig == null ) { restAssuredConfig = config ; } else { LogConfig logConfigForRequestSpec = restAssuredConfig . getLogConfig ( ) . enableLoggingOfRequestAndResponseIfValidationFails ( logDetail ) ; restAssuredConfig = restAssuredConfig . logConfig ( logConfigForRequestSpec ) ; } requestSpecification . config ( restAssuredConfig ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply a keystore for all requests <pre > given () . keyStore ( / truststore_javanet . jks test1234 ) . .. < / pre > < / p > <p > Note that this is just a shortcut for : < / p > <pre > RestAssured . config = RestAssured . config () . sslConfig ( sslConfig () . keyStore ( pathToJks password )) ; < / pre > [CODESPLIT] public static void keyStore ( String pathToJks , String password ) { Validate . notEmpty ( password , \"Password cannot be empty\" ) ; applyKeyStore ( pathToJks , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The following documentation is taken from <a href = HTTP Builder > https : // github . com / jgritman / httpbuilder / wiki / SSL< / a > : <p > <h1 > SSL Configuration< / h1 > <p / > SSL should for the most part just work . There are a few situations where it is not completely intuitive . You can follow the example below or see HttpClient s SSLSocketFactory documentation for more information . <p / > <h1 > SSLPeerUnverifiedException< / h1 > <p / > If you can t connect to an SSL website it is likely because the certificate chain is not trusted . This is an Apache HttpClient issue but explained here for convenience . To correct the untrusted certificate you need to import a certificate into an SSL truststore . <p / > First export a certificate from the website using your browser . For example if you go to https : // dev . java . net in Firefox you will probably get a warning in your browser . Choose Add Exception Get Certificate View Details tab . Choose a certificate in the chain and export it as a PEM file . You can view the details of the exported certificate like so : <pre > $ keytool - printcert - file EquifaxSecureGlobaleBusinessCA - 1 . crt Owner : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Issuer : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Serial number : 1 Valid from : Mon Jun 21 00 : 00 : 00 EDT 1999 until : Sun Jun 21 00 : 00 : 00 EDT 2020 Certificate fingerprints : MD5 : 8F : 5D : 77 : 06 : 27 : C4 : 98 : 3C : 5B : 93 : 78 : E7 : D7 : 7D : 9B : CC SHA1 : 7E : 78 : 4A : 10 : 1C : 82 : 65 : CC : 2D : E1 : F1 : 6D : 47 : B4 : 40 : CA : D9 : 0A : 19 : 45 Signature algorithm name : MD5withRSA Version : 3 .... < / pre > Now import that into a Java keystore file : <pre > $ keytool - importcert - alias equifax - ca - file EquifaxSecureGlobaleBusinessCA - 1 . crt - keystore truststore_javanet . jks - storepass test1234 Owner : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Issuer : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Serial number : 1 Valid from : Mon Jun 21 00 : 00 : 00 EDT 1999 until : Sun Jun 21 00 : 00 : 00 EDT 2020 Certificate fingerprints : MD5 : 8F : 5D : 77 : 06 : 27 : C4 : 98 : 3C : 5B : 93 : 78 : E7 : D7 : 7D : 9B : CC SHA1 : 7E : 78 : 4A : 10 : 1C : 82 : 65 : CC : 2D : E1 : F1 : 6D : 47 : B4 : 40 : CA : D9 : 0A : 19 : 45 Signature algorithm name : MD5withRSA Version : 3 ... Trust this certificate? [ no ] : yes Certificate was added to keystore < / pre > Now you want to use this truststore in your client : <pre > RestAssured . trustSture ( / truststore_javanet . jks test1234 ) ; < / pre > or <pre > given () . trustStore ( / truststore_javanet . jks test1234 ) . .. < / pre > < / p > <p > Note that this is just a shortcut for : < / p > <pre > RestAssured . config = RestAssured . config () . sslConfig ( sslConfig () . trustStore ( pathToJks password )) ; < / pre > [CODESPLIT] public static void trustStore ( String pathToJks , String password ) { Validate . notEmpty ( password , \"Password cannot be empty\" ) ; applyTrustStore ( pathToJks , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a trust store that ll be used for HTTPS requests . A trust store is a { @link java . security . KeyStore } that has been loaded with the password . If you wish that REST Assured loads the KeyStore store and applies the password ( thus making it a trust store ) please see some of the <code > keystore< / code > methods such as { @link #keyStore ( java . io . File String ) } . [CODESPLIT] public static void trustStore ( KeyStore truststore ) { Validate . notNull ( truststore , \"Truststore cannot be null\" ) ; config = config ( ) . sslConfig ( SSLConfig . sslConfig ( ) . trustStore ( truststore ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use a keystore located on the file - system . See { @link #keyStore ( String String ) } for more details . * <p > Note that this is just a shortcut for : < / p > <pre > RestAssured . config = RestAssured . config () . sslConfig ( sslConfig () . keyStore ( pathToJks password )) ; < / pre > [CODESPLIT] public static void keyStore ( File pathToJks , String password ) { Validate . notNull ( pathToJks , \"Path to JKS on the file system cannot be null\" ) ; applyKeyStore ( pathToJks , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use a trust store located on the file - system . See { @link #trustStore ( String String ) } for more details . * <p > Note that this is just a shortcut for : < / p > <pre > RestAssured . config = RestAssured . config () . sslConfig ( sslConfig () . trustStore ( pathToJks password )) ; < / pre > [CODESPLIT] public static void trustStore ( File pathToJks , String password ) { Validate . notNull ( pathToJks , \"Path to JKS on the file system cannot be null\" ) ; applyTrustStore ( pathToJks , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instruct REST Assured to connect to a proxy on the specified host on port <code > 8888< / code > . [CODESPLIT] public static void proxy ( String host ) { if ( UriValidator . isUri ( host ) ) { try { proxy ( new URI ( host ) ) ; } catch ( URISyntaxException e ) { throw new RuntimeException ( \"Internal error in REST Assured when constructing URI for Proxy.\" , e ) ; } } else { proxy ( host ( host ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instruct REST Assured to connect to a proxy on the specified port on localhost with a specific scheme . [CODESPLIT] public static void proxy ( String host , int port , String scheme ) { proxy ( new ProxySpecification ( host , port , scheme ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instruct REST Assured to connect to a proxy using a URI . [CODESPLIT] public static void proxy ( URI uri ) { if ( uri == null ) { throw new IllegalArgumentException ( \"Proxy URI cannot be null\" ) ; } proxy ( new ProxySpecification ( uri . getHost ( ) , uri . getPort ( ) , uri . getScheme ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the response to the print stream [CODESPLIT] public static String print ( ResponseOptions responseOptions , ResponseBody responseBody , PrintStream stream , LogDetail logDetail , boolean shouldPrettyPrint ) { final StringBuilder builder = new StringBuilder ( ) ; if ( logDetail == ALL || logDetail == STATUS ) { builder . append ( responseOptions . statusLine ( ) ) ; } if ( logDetail == ALL || logDetail == HEADERS ) { final Headers headers = responseOptions . headers ( ) ; if ( headers . exist ( ) ) { appendNewLineIfAll ( logDetail , builder ) . append ( toString ( headers ) ) ; } } else if ( logDetail == COOKIES ) { final Cookies cookies = responseOptions . detailedCookies ( ) ; if ( cookies . exist ( ) ) { appendNewLineIfAll ( logDetail , builder ) . append ( cookies . toString ( ) ) ; } } if ( logDetail == ALL || logDetail == BODY ) { String responseBodyToAppend ; if ( shouldPrettyPrint ) { responseBodyToAppend = new Prettifier ( ) . getPrettifiedBodyIfPossible ( responseOptions , responseBody ) ; } else { responseBodyToAppend = responseBody . asString ( ) ; } if ( logDetail == ALL && ! isBlank ( responseBodyToAppend ) ) { builder . append ( SystemUtils . LINE_SEPARATOR ) . append ( SystemUtils . LINE_SEPARATOR ) ; } builder . append ( responseBodyToAppend ) ; } String response = builder . toString ( ) ; stream . println ( response ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the redirect config . [CODESPLIT] public RestAssuredConfig redirect ( RedirectConfig redirectConfig ) { notNull ( redirectConfig , \"Redirect config\" ) ; return new RestAssuredConfig ( redirectConfig , conf ( HttpClientConfig . class ) , conf ( LogConfig . class ) , conf ( EncoderConfig . class ) , conf ( DecoderConfig . class ) , conf ( SessionConfig . class ) , conf ( ObjectMapperConfig . class ) , conf ( ConnectionConfig . class ) , conf ( JsonConfig . class ) , conf ( XmlConfig . class ) , conf ( SSLConfig . class ) , conf ( MatcherConfig . class ) , conf ( HeaderConfig . class ) , conf ( MultiPartConfig . class ) , conf ( ParamConfig . class ) , conf ( OAuthConfig . class ) , conf ( FailureConfig . class ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public EncoderConfig defaultCharsetForContentType ( String charset , String contentType ) { notNull ( charset , \"Charset\" ) ; notNull ( contentType , \"ContentType\" ) ; Map < String , String > map = new HashMap < String , String > ( contentTypeToDefaultCharset ) ; map . put ( trim ( contentType ) . toLowerCase ( ) , trim ( charset ) ) ; return new EncoderConfig ( charset , defaultQueryParameterCharset , shouldAppendDefaultContentCharsetToContentTypeIfUndefined , contentEncoders , map , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public EncoderConfig defaultCharsetForContentType ( Charset charset , ContentType contentType ) { notNull ( charset , \"Charset\" ) ; return defaultCharsetForContentType ( charset . toString ( ) , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public EncoderConfig defaultCharsetForContentType ( Charset charset , String contentType ) { notNull ( charset , \"Charset\" ) ; return defaultCharsetForContentType ( charset . toString ( ) , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset for the body / content in the request specification [CODESPLIT] public EncoderConfig defaultContentCharset ( Charset charset ) { String charsetAsString = notNull ( charset , Charset . class ) . toString ( ) ; return new EncoderConfig ( charsetAsString , defaultQueryParameterCharset , shouldAppendDefaultContentCharsetToContentTypeIfUndefined , contentEncoders , contentTypeToDefaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset for query parameters [CODESPLIT] public EncoderConfig defaultQueryParameterCharset ( String charset ) { return new EncoderConfig ( defaultContentCharset , charset , shouldAppendDefaultContentCharsetToContentTypeIfUndefined , contentEncoders , contentTypeToDefaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tells whether REST Assured should automatically append the content charset to the content - type header if not defined explicitly . <p > Note that this does not affect multipart form data . < / p > <p > Default is <code > true< / code > . < / p > [CODESPLIT] public EncoderConfig appendDefaultContentCharsetToContentTypeIfUndefined ( boolean shouldAddDefaultContentCharsetToContentTypeIfMissing ) { return new EncoderConfig ( defaultContentCharset , defaultQueryParameterCharset , shouldAddDefaultContentCharsetToContentTypeIfMissing , contentEncoders , contentTypeToDefaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the content ( body ) of the request specified with the given <code > contentType< / code > with the same encoder used by the supplied <code > encoder< / code > . This is useful only if REST Assured picks the wrong encoder ( or can t recognize it ) for the given content - type . [CODESPLIT] public EncoderConfig encodeContentTypeAs ( String contentType , ContentType encoder ) { notNull ( contentType , \"Content-Type to encode\" ) ; notNull ( encoder , ContentType . class ) ; Map < String , ContentType > newMap = new HashMap < String , ContentType > ( contentEncoders ) ; newMap . put ( contentType , encoder ) ; return new EncoderConfig ( defaultContentCharset , defaultQueryParameterCharset , shouldAppendDefaultContentCharsetToContentTypeIfUndefined , newMap , contentTypeToDefaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object mapper configuration that uses the specified object mapper as default . [CODESPLIT] public ObjectMapperConfig defaultObjectMapperType ( ObjectMapperType defaultObjectMapperType ) { return new ObjectMapperConfig ( defaultObjectMapper , defaultObjectMapperType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , jaxbObjectMapperFactory , johnzonObjectMapperFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a custom Gson object mapper factory . [CODESPLIT] public ObjectMapperConfig gsonObjectMapperFactory ( GsonObjectMapperFactory gsonObjectMapperFactory ) { return new ObjectMapperConfig ( defaultObjectMapper , defaultObjectMapperType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , jaxbObjectMapperFactory , johnzonObjectMapperFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a custom Jackson 1 . 0 object mapper factory . [CODESPLIT] public ObjectMapperConfig jackson1ObjectMapperFactory ( Jackson1ObjectMapperFactory jackson1ObjectMapperFactory ) { return new ObjectMapperConfig ( defaultObjectMapper , defaultObjectMapperType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , jaxbObjectMapperFactory , johnzonObjectMapperFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a custom Jackson 1 . 0 object mapper factory . [CODESPLIT] public ObjectMapperConfig jackson2ObjectMapperFactory ( Jackson2ObjectMapperFactory jackson2ObjectMapperFactory ) { return new ObjectMapperConfig ( defaultObjectMapper , defaultObjectMapperType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , jaxbObjectMapperFactory , johnzonObjectMapperFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a custom JAXB object mapper factory . [CODESPLIT] public ObjectMapperConfig jaxbObjectMapperFactory ( JAXBObjectMapperFactory jaxbObjectMapperFactory ) { return new ObjectMapperConfig ( defaultObjectMapper , defaultObjectMapperType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , jaxbObjectMapperFactory , johnzonObjectMapperFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Log config . [CODESPLIT] public RestAssuredMockMvcConfig logConfig ( LogConfig logConfig ) { notNull ( logConfig , \"Log config\" ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the session config . [CODESPLIT] public RestAssuredMockMvcConfig sessionConfig ( SessionConfig sessionConfig ) { notNull ( sessionConfig , \"Session config\" ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the object mapper config . [CODESPLIT] public RestAssuredMockMvcConfig objectMapperConfig ( ObjectMapperConfig objectMapperConfig ) { notNull ( objectMapperConfig , \"Object mapper config\" ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Json config . [CODESPLIT] public RestAssuredMockMvcConfig jsonConfig ( JsonConfig jsonConfig ) { notNull ( jsonConfig , \"JsonConfig\" ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Xml config . [CODESPLIT] public RestAssuredMockMvcConfig xmlConfig ( XmlConfig xmlConfig ) { notNull ( xmlConfig , \"XmlConfig\" ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the encoder config [CODESPLIT] public RestAssuredMockMvcConfig encoderConfig ( EncoderConfig encoderConfig ) { notNull ( encoderConfig , \"EncoderConfig\" ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the header config [CODESPLIT] public RestAssuredMockMvcConfig headerConfig ( HeaderConfig headerConfig ) { notNull ( headerConfig , \"HeaderConfig\" ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the async config [CODESPLIT] public RestAssuredMockMvcConfig asyncConfig ( AsyncConfig asyncConfig ) { notNull ( asyncConfig , AsyncConfig . class ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the MockMVC config [CODESPLIT] public RestAssuredMockMvcConfig mockMvcConfig ( MockMvcConfig mockMvcConfig ) { notNull ( mockMvcConfig , MockMvcConfig . class ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the multi - part config [CODESPLIT] public RestAssuredMockMvcConfig multiPartConfig ( MultiPartConfig multiPartConfig ) { notNull ( multiPartConfig , MultiPartConfig . class ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the parameter config [CODESPLIT] public RestAssuredMockMvcConfig paramConfig ( MockMvcParamConfig paramConfig ) { notNull ( paramConfig , MultiPartConfig . class ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the matcher config [CODESPLIT] public RestAssuredMockMvcConfig matcherConfig ( MatcherConfig matcherConfig ) { notNull ( matcherConfig , MatcherConfig . class ) ; return new RestAssuredMockMvcConfig ( logConfig , encoderConfig , decoderConfig , sessionConfig , objectMapperConfig , jsonConfig , xmlConfig , headerConfig , asyncConfig , multiPartConfig , mockMvcConfig , paramConfig , matcherConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode / unescape a portion of a URL to use with the query part ensure { @code plusAsBlank } is true . [CODESPLIT] public static String urlDecode ( final String content , final Charset charset , final boolean plusAsBlank ) { if ( content == null ) { return null ; } final ByteBuffer bb = ByteBuffer . allocate ( content . length ( ) ) ; final CharBuffer cb = CharBuffer . wrap ( content ) ; while ( cb . hasRemaining ( ) ) { final char c = cb . get ( ) ; if ( c == ' ' && cb . remaining ( ) >= 2 ) { final char uc = cb . get ( ) ; final char lc = cb . get ( ) ; final int u = Character . digit ( uc , 16 ) ; final int l = Character . digit ( lc , 16 ) ; if ( u != - 1 && l != - 1 ) { bb . put ( ( byte ) ( ( u << 4 ) + l ) ) ; } else { bb . put ( ( byte ) ' ' ) ; bb . put ( ( byte ) uc ) ; bb . put ( ( byte ) lc ) ; } } else if ( plusAsBlank && c == ' ' ) { bb . put ( ( byte ) ' ' ) ; } else { bb . put ( ( byte ) c ) ; } } bb . flip ( ) ; return charset . decode ( bb ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * If body expectations are defined we need to return a new Response otherwise the stream has been closed due to the logging . [CODESPLIT] private Response cloneResponseIfNeeded ( Response response , byte [ ] responseAsString ) { if ( responseAsString != null && response instanceof RestAssuredResponseImpl && ! ( ( RestAssuredResponseImpl ) response ) . getHasExpectations ( ) ) { final Response build = new ResponseBuilder ( ) . clone ( response ) . setBody ( responseAsString ) . build ( ) ; ( ( RestAssuredResponseImpl ) build ) . setHasExpectations ( true ) ; return build ; } return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure the CertificateAuthSettings to use strict host name verification ( this is the default behavior ) . [CODESPLIT] public CertificateAuthSettings strictHostnames ( ) { return new CertificateAuthSettings ( keystoreType , trustStoreType , port , trustStore , keyStore , STRICT_HOSTNAME_VERIFIER , sslSocketFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure the CertificateAuthSettings to allow all host names . [CODESPLIT] public CertificateAuthSettings allowAllHostnames ( ) { return new CertificateAuthSettings ( keystoreType , trustStoreType , port , trustStore , keyStore , ALLOW_ALL_HOSTNAME_VERIFIER , sslSocketFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure the CertificateAuthSettings to use the provided { @link X509HostnameVerifier } instance . [CODESPLIT] public CertificateAuthSettings x509HostnameVerifier ( X509HostnameVerifier x509HostnameVerifier ) { return new CertificateAuthSettings ( keystoreType , trustStoreType , port , trustStore , keyStore , x509HostnameVerifier , sslSocketFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify features that will be used when parsing XML . [CODESPLIT] public XmlPathConfig features ( Map < String , Boolean > features ) { Validate . notNull ( features , \"Features cannot be null\" ) ; return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultDeserializer , charset , features , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value of a feature flag . [CODESPLIT] public XmlPathConfig feature ( String uri , boolean enabled ) { Validate . notEmpty ( uri , \"URI cannot be empty\" ) ; Map < String , Boolean > newFeatures = new HashMap < String , Boolean > ( features ) ; newFeatures . put ( uri , enabled ) ; return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultDeserializer , charset , newFeatures , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify properties that will be used when parsing XML . [CODESPLIT] public XmlPathConfig properties ( Map < String , Object > properties ) { Validate . notNull ( properties , \"Properties cannot be null\" ) ; return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultDeserializer , charset , features , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value of a property . [CODESPLIT] public XmlPathConfig property ( String name , Object value ) { Validate . notEmpty ( name , \"Name cannot be empty\" ) ; Map < String , Object > newProperties = new HashMap < String , Object > ( properties ) ; newProperties . put ( name , value ) ; return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultDeserializer , charset , features , declaredNamespaces , newProperties , validating , namespaceAware , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disables external DTD loading . <p > This is a shortcut for doing : <br > <pre > setFeature ( http : // apache . org / xml / features / nonvalidating / load - external - dtd false ) ; < / pre > < / p > [CODESPLIT] public XmlPathConfig disableLoadingOfExternalDtd ( ) { Map < String , Boolean > newFeatures = new HashMap < String , Boolean > ( features ) ; newFeatures . put ( \"http://apache.org/xml/features/nonvalidating/load-external-dtd\" , false ) ; newFeatures . put ( \"http://apache.org/xml/features/disallow-doctype-decl\" , false ) ; return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultDeserializer , charset , newFeatures , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an json path configuration that uses the specified object de - serializer as default . [CODESPLIT] public XmlPathConfig defaultObjectDeserializer ( XmlPathObjectDeserializer defaultObjectDeserializer ) { return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultObjectDeserializer , charset , features , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify declared namespaces that will be used when parsing XML . [CODESPLIT] public XmlPathConfig declareNamespaces ( Map < String , String > namespacesToDeclare ) { return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultDeserializer , charset , features , namespacesToDeclare , properties , validating , namespaceAware , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declares a namespace . [CODESPLIT] public XmlPathConfig declaredNamespace ( String prefix , String namespaceURI ) { Validate . notEmpty ( prefix , \"Prefix cannot be empty\" ) ; Validate . notEmpty ( namespaceURI , \"Namespace URI cannot be empty\" ) ; Map < String , String > updatedNamespaces = new HashMap < String , String > ( declaredNamespaces ) ; updatedNamespaces . put ( prefix , namespaceURI ) ; return new XmlPathConfig ( jaxbObjectMapperFactory , defaultParserType , defaultDeserializer , charset , features , updatedNamespaces , properties , validating , true , allowDocTypeDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Convenience method to perform an HTTP GET . It will use the HTTPBuilder s { @link #getHandler () registered response handlers } to handle success or failure status codes . By default the <code > success< / code > response handler will attempt to parse the data and simply return the parsed object . < / p > <p > <p > <strong > Note : < / strong > If using the { @link #defaultSuccessHandler ( HttpResponseDecorator Object ) default <code > success< / code > response handler } be sure to read the caveat regarding streaming response data . < / p > [CODESPLIT] public Object get ( Map < String , ? > args ) throws ClientProtocolException , IOException , URISyntaxException { return this . get ( args , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Convenience method to perform an HTTP GET . The response closure will be called only on a successful response . < / p > <p > <p > A failed response ( i . e . any HTTP status code > 399 ) will be handled by the registered failure handler . The { @link #defaultFailureHandler ( HttpResponseDecorator ) default failure handler } throws an { @link HttpResponseException } . < / p > [CODESPLIT] public Object get ( Map < String , ? > args , Closure responseClosure ) throws ClientProtocolException , IOException , URISyntaxException { RequestConfigDelegate delegate = new RequestConfigDelegate ( new HttpGet ( ) , this . defaultContentType , this . defaultRequestHeaders , this . defaultResponseHandlers ) ; delegate . setPropertiesFromMap ( args ) ; if ( responseClosure != null ) delegate . getResponse ( ) . put ( Status . SUCCESS , responseClosure ) ; return this . doRequest ( delegate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Convenience method to perform an HTTP POST . It will use the HTTPBuilder s { @link #getHandler () registered response handlers } to handle success or failure status codes . By default the <code > success< / code > response handler will attempt to parse the data and simply return the parsed object . < / p > <p > <p > <strong > Note : < / strong > If using the { @link #defaultSuccessHandler ( HttpResponseDecorator Object ) default <code > success< / code > response handler } be sure to read the caveat regarding streaming response data . < / p > [CODESPLIT] public Object post ( Map < String , ? > args ) throws ClientProtocolException , URISyntaxException , IOException { return this . post ( args , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Convenience method to perform an HTTP PATCH . It will use the HTTPBuilder s { @link #getHandler () registered response handlers } to handle success or failure status codes . By default the <code > success< / code > response handler will attempt to parse the data and simply return the parsed object . < / p > <p > <p > <strong > Note : < / strong > If using the { @link #defaultSuccessHandler ( HttpResponseDecorator Object ) default <code > success< / code > response handler } be sure to read the caveat regarding streaming response data . < / p > [CODESPLIT] public Object patch ( Map < String , ? > args ) throws ClientProtocolException , URISyntaxException , IOException { return this . patch ( args , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Convenience method to perform an HTTP form PATCH . The response closure will be called only on a successful response . < / p > <p > <p > A failed response ( i . e . any HTTP status code > 399 ) will be handled by the registered failure handler . The { @link #defaultFailureHandler ( HttpResponseDecorator ) default failure handler } throws an { @link HttpResponseException } . < / p > <p > <p > The request body ( specified by a <code > body< / code > named parameter ) will be converted to a url - encoded form string unless a different <code > requestContentType< / code > named parameter is passed to this method . ( See { @link EncoderRegistry#encodeForm ( Map ) } . ) < / p > [CODESPLIT] public Object patch ( Map < String , ? > args , Closure responseClosure ) throws URISyntaxException , ClientProtocolException , IOException { RequestConfigDelegate delegate = new RequestConfigDelegate ( new HttpPatch ( ) , this . defaultContentType , this . defaultRequestHeaders , this . defaultResponseHandlers ) ; /* by default assume the request body will be URLEncoded, but allow\n             the 'requestContentType' named argument to override this if it is\n             given */ delegate . setRequestContentType ( ContentType . URLENC . toString ( ) ) ; delegate . setPropertiesFromMap ( args ) ; if ( responseClosure != null ) { delegate . getResponse ( ) . put ( Status . SUCCESS . toString ( ) , responseClosure ) ; delegate . getResponse ( ) . put ( Status . FAILURE . toString ( ) , responseClosure ) ; } return this . doRequest ( delegate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an HTTP request to the default URI and parse using the default content - type . [CODESPLIT] public Object request ( String method , boolean hasBody , Closure configClosure ) throws ClientProtocolException , IOException { return this . doRequest ( this . defaultURI . toURI ( ) , method , this . defaultContentType , hasBody , configClosure ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a request for the given HTTP method and content - type with additional options configured in the <code > configClosure< / code > . See { @link RequestConfigDelegate } for options . [CODESPLIT] public Object request ( Object uri , String method , Object contentType , boolean hasBody , Closure configClosure ) throws ClientProtocolException , IOException , URISyntaxException { return this . doRequest ( URIBuilder . convertToURI ( uri ) , method , contentType , hasBody , configClosure ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] protected Object doRequest ( URI uri , String method , Object contentType , boolean hasBody , Closure configClosure ) throws IOException { HttpRequestBase reqMethod = HttpRequestFactory . createHttpRequest ( uri , method , hasBody ) ; RequestConfigDelegate delegate = new RequestConfigDelegate ( reqMethod , contentType , this . defaultRequestHeaders , this . defaultResponseHandlers ) ; configClosure . setDelegate ( delegate ) ; configClosure . setResolveStrategy ( Closure . DELEGATE_FIRST ) ; configClosure . call ( reqMethod ) ; return this . doRequest ( delegate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the response data based on the given content - type . If the given content - type is { @link ContentType#ANY } the <code > content - type< / code > header from the response will be used to determine how to parse the response . [CODESPLIT] protected Object parseResponse ( HttpResponse resp , Object contentType ) throws IOException { // For HEAD or OPTIONS requests, there should be no response entity. if ( resp . getEntity ( ) == null ) { log . debug ( \"Response contains no entity.  Parsed data is null.\" ) ; return null ; } // first, start with the _given_ content-type String responseContentType = contentType . toString ( ) ; // if the given content-type is ANY (\"*/*\") then use the response content-type try { if ( ContentType . ANY . toString ( ) . equals ( responseContentType ) ) responseContentType = HttpResponseContentTypeFinder . findContentType ( resp ) ; } catch ( RuntimeException ex ) { /* if for whatever reason we can't determine the content-type, but\n                * still want to attempt to parse the data, use the BINARY\n                * content-type so that the response will be buffered into a\n                * ByteArrayInputStream. */ responseContentType = ContentType . BINARY . toString ( ) ; } Object parsedData = null ; log . debug ( \"Parsing response as: \" + responseContentType ) ; parsedData = resp . getEntity ( ) . getContent ( ) ; if ( parsedData == null ) log . debug ( \"Parser returned null!\" ) ; else log . debug ( \"Parsed data to instance of: \" + parsedData . getClass ( ) ) ; return parsedData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates default response handlers for { @link Status#SUCCESS success } and { @link Status#FAILURE failure } status codes . This is used to populate the handler map when a new HTTPBuilder instance is created . [CODESPLIT] protected Map < Object , Closure > buildDefaultResponseHandlers ( ) { Map < Object , Closure > map = new StringHashMap < Closure > ( ) ; map . put ( Status . SUCCESS , new MethodClosure ( this , \"defaultSuccessHandler\" ) ) ; map . put ( Status . FAILURE , new MethodClosure ( this , \"defaultFailureHandler\" ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > This is the default <code > response . success< / code > handler . It will be executed if the response is not handled by a status - code - specific handler ( i . e . <code > response . 200 = { .. } < / code > ) and no generic success handler is given ( i . e . <code > response . success = { .. } < / code > . ) This handler simply returns the parsed data from the response body . In most cases you will probably want to define a <code > response . success = { ... } < / code > handler from the request closure which will replace the response handler defined by this method . < / p > <p > <p > In practice a user - supplied response handler closure is <i > designed< / i > to handle streaming content so it can be read directly from the response stream without buffering which will be much more efficient . Therefore it is recommended that request method variants be used which explicitly accept a response handler closure in these cases . < / p > [CODESPLIT] protected Object defaultSuccessHandler ( HttpResponseDecorator resp , Object parsedData ) throws ResponseParseException { try { //If response is streaming, buffer it in a byte array: if ( parsedData instanceof InputStream ) { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; DefaultGroovyMethods . leftShift ( buffer , ( InputStream ) parsedData ) ; parsedData = new ByteArrayInputStream ( buffer . toByteArray ( ) ) ; } else if ( parsedData instanceof Reader ) { StringWriter buffer = new StringWriter ( ) ; DefaultGroovyMethods . leftShift ( buffer , ( Reader ) parsedData ) ; parsedData = new StringReader ( buffer . toString ( ) ) ; } else if ( parsedData instanceof Closeable ) log . debug ( \"Parsed data is streaming, but will be accessible after \" + \"the network connection is closed.  Use at your own risk!\" ) ; return parsedData ; } catch ( IOException ex ) { throw new ResponseParseException ( resp , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default URI used for requests that do not explicitly take a <code > uri< / code > param . [CODESPLIT] public void setUri ( Object uri ) throws URISyntaxException { this . defaultURI = new URIBuilder ( URIBuilder . convertToURI ( uri ) , urlEncodingEnabled , encoderConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default headers to add to all requests made by this builder instance . These values will replace any previously set default headers . [CODESPLIT] public void setHeaders ( Map < ? , ? > headers ) { this . defaultRequestHeaders . clear ( ) ; if ( headers == null ) return ; for ( Object key : headers . keySet ( ) ) { Object val = headers . get ( key ) ; if ( val == null ) continue ; this . defaultRequestHeaders . put ( key . toString ( ) , val . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default HTTP proxy to be used for all requests . [CODESPLIT] public void setProxy ( String host , int port , String scheme ) { getClient ( ) . getParams ( ) . setParameter ( ConnRoutePNames . DEFAULT_PROXY , new HttpHost ( host , port , scheme ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the control name of this multi - part . [CODESPLIT] public MultiPartSpecBuilder controlName ( String controlName ) { Validate . notEmpty ( controlName , \"Control name cannot be empty\" ) ; this . controlName = controlName ; this . isControlNameExplicit = true ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a header to this multipart specification . [CODESPLIT] public MultiPartSpecBuilder header ( String name , String value ) { Validate . notEmpty ( name , \"Header name cannot be empty\" ) ; Validate . notEmpty ( value , \"Header value cannot be empty\" ) ; // Replace previous header if exists final Set < String > headerNames = headers . keySet ( ) ; final String trimmedName = name . trim ( ) ; for ( String headerName : headerNames ) { if ( headerName . equalsIgnoreCase ( trimmedName ) ) { headers . remove ( headerName ) ; } } // Put the name header in the header list headers . put ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the headers for this multipart specification ( replaces previous headers ) [CODESPLIT] public MultiPartSpecBuilder headers ( Map < String , String > headers ) { if ( headers == null ) { this . headers = new HashMap < String , String > ( ) ; } else { this . headers = new HashMap < String , String > ( headers ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the charset for this charset . [CODESPLIT] public MultiPartSpecBuilder charset ( String charset ) { Validate . notEmpty ( charset , \"Charset cannot be empty\" ) ; if ( content instanceof byte [ ] || content instanceof InputStream ) { throw new IllegalArgumentException ( \"Cannot specify charset input streams or byte arrays.\" ) ; } this . charset = charset ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the charset for this charset . [CODESPLIT] public MultiPartSpecBuilder charset ( Charset charset ) { Validate . notNull ( charset , \"Charset cannot be null\" ) ; this . charset = charset . toString ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation adds a { @link GZIPEncoding } and { @link DeflateEncoding } handler to the registry . Override this method to provide a different set of defaults . [CODESPLIT] protected Map < String , ContentEncoding > getDefaultEncoders ( ) { Map < String , ContentEncoding > map = new HashMap < String , ContentEncoding > ( ) ; map . put ( Type . GZIP . toString ( ) , new GZIPEncoding ( ) ) ; map . put ( Type . DEFLATE . toString ( ) , new DeflateEncoding ( useNoWrapForInflateDecoding ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the request and response interceptors to the { @link HttpClient } which will provide transparent decoding of the given content - encoding types . This method is called by HTTPBuilder and probably should not need be modified by sub - classes . [CODESPLIT] void setInterceptors ( final AbstractHttpClient client , Object ... encodings ) { // remove any encoding interceptors that are already set client . removeRequestInterceptorByClass ( ContentEncoding . RequestInterceptor . class ) ; client . removeResponseInterceptorByClass ( ContentEncoding . ResponseInterceptor . class ) ; for ( Object encName : encodings ) { ContentEncoding enc = availableEncoders . get ( encName . toString ( ) ) ; if ( enc == null ) continue ; client . addRequestInterceptor ( enc . getRequestInterceptor ( ) ) ; client . addResponseInterceptor ( enc . getResponseInterceptor ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set authentication credentials to be used for the current { @link HTTPBuilder#getUri () default host } . This method name is a bit of a misnomer since these credentials will actually work for digest authentication as well . [CODESPLIT] public void basic ( String user , String pass ) { URI uri = ( ( URIBuilder ) builder . getUri ( ) ) . toURI ( ) ; if ( uri == null ) throw new IllegalStateException ( \"a default URI must be set\" ) ; this . basic ( uri . getHost ( ) , uri . getPort ( ) , user , pass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set authentication credentials to be used for the given host and port . [CODESPLIT] public void basic ( String host , int port , String user , String pass ) { builder . getClient ( ) . getCredentialsProvider ( ) . setCredentials ( new AuthScope ( host , port ) , new UsernamePasswordCredentials ( user , pass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set NTLM authentication credentials to be used for the current { @link HTTPBuilder#getUri () default host } . [CODESPLIT] public void ntlm ( String user , String pass , String workstation , String domain ) { URI uri = ( ( URIBuilder ) builder . getUri ( ) ) . toURI ( ) ; if ( uri == null ) throw new IllegalStateException ( \"a default URI must be set\" ) ; this . ntlm ( uri . getHost ( ) , uri . getPort ( ) , user , pass , workstation , domain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set NTLM authentication credentials to be used for the given host and port . [CODESPLIT] public void ntlm ( String host , int port , String user , String pass , String workstation , String domain ) { builder . getClient ( ) . getCredentialsProvider ( ) . setCredentials ( new AuthScope ( host , port ) , new NTCredentials ( user , pass , workstation , domain ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a certificate to be used for SSL authentication . See { @link Class#getResource ( String ) } for how to get a URL from a resource on the classpath . [CODESPLIT] public void certificate ( Object keyStorePath , String keyStorePassword , String keyStoreType , KeyStore keyStore , Object trustStorePath , String trustStorePassword , String trustStoreType , KeyStore trustStore , int port , X509HostnameVerifier hostnameVerifier , SSLSocketFactory sslConnectionSocketFactory ) { TrustAndKeystoreSpecImpl spec = new TrustAndKeystoreSpecImpl ( ) ; URI uri = ( ( URIBuilder ) builder . getUri ( ) ) . toURI ( ) ; if ( uri == null ) throw new IllegalStateException ( \"a default URI must be set\" ) ; spec . setKeyStoreType ( keyStoreType ) ; spec . setKeyStorePassword ( keyStorePassword ) ; spec . setKeyStorePath ( keyStorePath ) ; spec . setKeyStore ( keyStore ) ; spec . setTrustStoreType ( trustStoreType ) ; spec . setTrustStorePassword ( trustStorePassword ) ; spec . setTrustStorePath ( trustStorePath ) ; spec . setTrustStore ( trustStore ) ; spec . setPort ( port ) ; spec . setX509HostnameVerifier ( hostnameVerifier ) ; spec . setFactory ( sslConnectionSocketFactory ) ; int portSpecifiedInUri = uri . getPort ( ) ; spec . apply ( builder , portSpecifiedInUri == UNDEFINED_PORT ? DEFAULT_HTTPS_PORT : portSpecifiedInUri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< / p > OAuth sign all requests . Note that this currently does <strong > not< / strong > wait for a <code > WWW - Authenticate< / code > challenge before sending the the OAuth header . All requests to all domains will be signed for this instance . < / p > <p / > <p > This assumes you ve already generated an <code > accessToken< / code > and <code > secretToken< / code > for the site you re targeting . For More information on how to achieve this see the <a href = https : // github . com / scribejava / scribejava / wiki / Getting - Started > Scribe documentation< / a > . < / p > [CODESPLIT] public void oauth ( String consumerKey , String consumerSecret , String accessToken , String secretToken ) { this . builder . client . removeRequestInterceptorByClass ( OAuthSigner . class ) ; if ( consumerKey != null ) { this . builder . client . addRequestInterceptor ( new OAuthSigner ( consumerKey , consumerSecret , accessToken , secretToken , OAuthSignature . HEADER , raOAuthConfig . shouldAddEmptyAccessOAuthTokenToBaseString ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< / p > OAuth2 sign all requests . Note that this currently does <strong > not< / strong > wait for a <code > WWW - Authenticate< / code > challenge before sending the the OAuth header . All requests to all domains will be signed for this instance . < / p > <p / > <p > This assumes you ve already generated an <code > accessToken< / code > for the site you re targeting . For More information on how to achieve this see the <a href = https : // github . com / scribejava / scribejava / wiki / Getting - Started > Scribe documentation< / a > . < / p > [CODESPLIT] public void oauth2 ( String accessToken ) { this . builder . client . removeRequestInterceptorByClass ( OAuthSigner . class ) ; if ( accessToken != null ) { this . builder . client . addRequestInterceptor ( new OAuthSigner ( accessToken , OAuthSignature . HEADER ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get the content - type string from the response ( no charset ) . [CODESPLIT] public static String findContentType ( HttpResponse resp ) { Header contentTypeHeader = resp . getFirstHeader ( HttpHeaders . CONTENT_TYPE ) ; if ( contentTypeHeader == null ) throw new IllegalArgumentException ( \"Response does not have a content-type header\" ) ; try { return contentTypeHeader . getValue ( ) ; } catch ( RuntimeException ex ) { // NPE or OOB Exceptions throw new IllegalArgumentException ( \"Could not parse content-type from response\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An alternative way to create a Headers object from the constructor . [CODESPLIT] public static Headers headers ( Header header , Header ... additionalHeaders ) { notNull ( header , \"Header\" ) ; final List < Header > headerList = new LinkedList < Header > ( ) ; headerList . add ( header ) ; if ( additionalHeaders != null ) { Collections . addAll ( headerList , additionalHeaders ) ; } return new Headers ( headerList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is usually the entry - point of the API if you need to specify parameters or a body in the request . For example : <p / > <pre > given () . param ( x y ) . when () . get ( / something ) . then () . statusCode ( 200 ) . body ( x . y notNullValue () ) ; < / pre > Note that this method is the same as { @link #with () } but with another syntax . [CODESPLIT] public static MockMvcRequestSpecification given ( ) { return new MockMvcRequestSpecificationImpl ( mockMvcFactory , config , resultHandlers , requestPostProcessors , basePath , requestSpecification , responseSpecification , authentication ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset all static configurations to their default values . [CODESPLIT] public static void reset ( ) { mockMvcFactory = null ; config = null ; basePath = \"/\" ; resultHandlers . clear ( ) ; requestPostProcessors . clear ( ) ; responseSpecification = null ; requestSpecification = null ; authentication = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a GET request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse get ( String path , Object ... pathParams ) { return given ( ) . get ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a GET request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse get ( String path , Map < String , ? > pathParams ) { return given ( ) . get ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a POST request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse post ( String path , Object ... pathParams ) { return given ( ) . post ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a POST request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse post ( String path , Map < String , ? > pathParams ) { return given ( ) . post ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a PUT request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse put ( String path , Object ... pathParams ) { return given ( ) . put ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a DELETE request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse delete ( String path , Object ... pathParams ) { return given ( ) . delete ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a DELETE request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse delete ( String path , Map < String , ? > pathParams ) { return given ( ) . delete ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a HEAD request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse head ( String path , Object ... pathParams ) { return given ( ) . head ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a HEAD request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse head ( String path , Map < String , ? > pathParams ) { return given ( ) . head ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a PATCH request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse patch ( String path , Object ... pathParams ) { return given ( ) . patch ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a PATCH request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse patch ( String path , Map < String , ? > pathParams ) { return given ( ) . patch ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a OPTIONS request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse options ( String path , Object ... pathParams ) { return given ( ) . options ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a OPTIONS request to a <code > path< / code > . Normally the path doesn t have to be fully - qualified e . g . you don t need to specify the path as <tt > http : // localhost : 8080 / path< / tt > . In this case it s enough to use <tt > / path< / tt > . [CODESPLIT] public static MockMvcResponse options ( String path , Map < String , ? > pathParams ) { return given ( ) . options ( path , pathParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a request to a <code > uri< / code > . [CODESPLIT] public static MockMvcResponse request ( Method method , URI uri ) { return given ( ) . request ( method , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a request to a <code > url< / code > . [CODESPLIT] public static MockMvcResponse request ( Method method , URL url ) { return given ( ) . request ( method , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a custom HTTP request to a <code > uri< / code > . [CODESPLIT] public static MockMvcResponse request ( String method , URI uri ) { return given ( ) . request ( method , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a custom HTTP request to a <code > url< / code > . [CODESPLIT] public static MockMvcResponse request ( String method , URL url ) { return given ( ) . request ( method , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate using the given principal . Used as : <pre > RestAssured . authentication = principal ( myPrincipal ) ; < / pre > or in a { @link MockMvcRequestSpecBuilder } : <pre > MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder () . setAuth ( principal ( myPrincipal )) . .. < / pre > [CODESPLIT] public static MockMvcAuthenticationScheme principal ( final Principal principal ) { return new MockMvcAuthenticationScheme ( ) { public void authenticate ( MockMvcRequestSpecification mockMvcRequestSpecification ) { mockMvcRequestSpecification . auth ( ) . principal ( principal ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate using the given principal . Used as : <pre > RestAssured . authentication = principal ( myPrincipal ) ; < / pre > or in a { @link MockMvcRequestSpecBuilder } : <pre > MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder () . setAuth ( principal ( myPrincipal )) . .. < / pre > [CODESPLIT] public static MockMvcAuthenticationScheme principal ( final Object principal ) { return new MockMvcAuthenticationScheme ( ) { public void authenticate ( MockMvcRequestSpecification mockMvcRequestSpecification ) { mockMvcRequestSpecification . auth ( ) . principal ( principal ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate using the given principal and credentials . Used as : <pre > RestAssured . authentication = principalWithCredentials ( myPrincipal myCredentials ) ; < / pre > or in a { @link MockMvcRequestSpecBuilder } : <pre > MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder () . setAuth ( principalWithCredentials ( myPrincipal myCredentials )) . .. < / pre > [CODESPLIT] public static MockMvcAuthenticationScheme principalWithCredentials ( final Object principal , final Object credentials , final String ... authorities ) { return new MockMvcAuthenticationScheme ( ) { public void authenticate ( MockMvcRequestSpecification mockMvcRequestSpecification ) { mockMvcRequestSpecification . auth ( ) . principalWithCredentials ( principal , credentials , authorities ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate using the supplied authentication instance ( <code > org . springframework . security . core . Authentication< / code > from Spring Security ) . Used as : <pre > RestAssured . authentication = authentication ( myAuth ) ; < / pre > or in a { @link MockMvcRequestSpecBuilder } : <pre > MockMvcRequestSpecification req = new MockMvcRequestSpecBuilder () . setAuth ( authentication ( myAuth )) . .. < / pre > [CODESPLIT] public static MockMvcAuthenticationScheme authentication ( final Object authentication ) { return new MockMvcAuthenticationScheme ( ) { public void authenticate ( MockMvcRequestSpecification mockMvcRequestSpecification ) { mockMvcRequestSpecification . auth ( ) . authentication ( authentication ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate using a { @link RequestPostProcessor } . This is mainly useful when you have added the <code > spring - security - test< / code > artifact to classpath . This allows you to do for example : <pre > RestAssured . authentication = with ( user ( username ) . password ( password )) ; < / pre > where <code > user< / code > is statically imported from <code > org . springframework . security . test . web . servlet . request . SecurityMockMvcRequestPostProcessors< / code > . [CODESPLIT] public static MockMvcAuthenticationScheme with ( final RequestPostProcessor requestPostProcessor , final RequestPostProcessor ... additionalRequestPostProcessor ) { return new MockMvcAuthenticationScheme ( ) { public void authenticate ( MockMvcRequestSpecification mockMvcRequestSpecification ) { mockMvcRequestSpecification . auth ( ) . with ( requestPostProcessor , additionalRequestPostProcessor ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable logging of both the request and the response if REST Assureds test validation fails with the specified log detail . <p / > <p > This is just a shortcut for : < / p > <pre > RestAssured . config = new RestAssuredMockMvcConfig () . logConfig ( logConfig () . enableLoggingOfRequestAndResponseIfValidationFails ( logDetail )) ; < / pre > [CODESPLIT] public static void enableLoggingOfRequestAndResponseIfValidationFails ( LogDetail logDetail ) { config = config == null ? new RestAssuredMockMvcConfig ( ) : config ; config = config . logConfig ( logConfig ( ) . enableLoggingOfRequestAndResponseIfValidationFails ( logDetail ) ) ; // Update request specification if already defined otherwise it'll override the configs. // Note that request spec also influence response spec when it comes to logging if validation fails due to the way filters work if ( requestSpecification != null && requestSpecification instanceof MockMvcRequestSpecificationImpl ) { RestAssuredMockMvcConfig restAssuredConfig = ( ( MockMvcRequestSpecificationImpl ) requestSpecification ) . getRestAssuredMockMvcConfig ( ) ; if ( restAssuredConfig == null ) { restAssuredConfig = config ; } else { LogConfig logConfigForRequestSpec = restAssuredConfig . getLogConfig ( ) . enableLoggingOfRequestAndResponseIfValidationFails ( logDetail ) ; restAssuredConfig = restAssuredConfig . logConfig ( logConfigForRequestSpec ) ; } requestSpecification . config ( restAssuredConfig ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id playerId : my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( userId equalToPath ( playerId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < MockMvcResponse > equalToPath ( final String path ) { return new ResponseAwareMatcher < MockMvcResponse > ( ) { public Matcher < ? > matcher ( MockMvcResponse response ) { return equalTo ( response . path ( path ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href endsWithPath ( userId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < MockMvcResponse > endsWithPath ( final String path ) { return new ResponseAwareMatcher < MockMvcResponse > ( ) { public Matcher < ? > matcher ( MockMvcResponse response ) { return endsWith ( response . < String > path ( path ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id baseUri : http : // localhost : 8080 href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href startsWithPath ( baseUri )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < MockMvcResponse > startsWithPath ( final String path ) { return new ResponseAwareMatcher < MockMvcResponse > ( ) { public Matcher < ? > matcher ( MockMvcResponse response ) { return startsWith ( response . < String > path ( path ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href containsPath ( userId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < MockMvcResponse > containsPath ( final String path ) { return new ResponseAwareMatcher < MockMvcResponse > ( ) { public Matcher < ? > matcher ( MockMvcResponse response ) { return containsString ( response . < String > path ( path ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the content type of the response [CODESPLIT] public ResponseBuilder setContentType ( String contentType ) { notNull ( contentType , \"Content type\" ) ; restAssuredResponse . setContentType ( contentType ) ; setHeader ( CONTENT_TYPE , contentType ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the content type of the response [CODESPLIT] public ResponseBuilder setContentType ( ContentType contentType ) { notNull ( contentType , ContentType . class ) ; return setContentType ( contentType . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a specific header [CODESPLIT] public ResponseBuilder setHeader ( String name , String value ) { notNull ( name , \"Header name\" ) ; notNull ( value , \"Header value\" ) ; List < Header > newHeaders = new ArrayList < Header > ( restAssuredResponse . headers ( ) . asList ( ) ) ; newHeaders . add ( new Header ( name , value ) ) ; restAssuredResponse . setResponseHeaders ( new Headers ( newHeaders ) ) ; if ( trim ( name ) . equalsIgnoreCase ( CONTENT_TYPE ) ) { restAssuredResponse . setContentType ( value ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the actual response [CODESPLIT] public Response build ( ) { final int statusCode = restAssuredResponse . statusCode ( ) ; if ( statusCode < 100 || statusCode >= 600 ) { throw new IllegalArgumentException ( format ( \"Status code must be greater than 100 and less than 600, was %d.\" , statusCode ) ) ; } if ( StringUtils . isBlank ( restAssuredResponse . statusLine ( ) ) ) { restAssuredResponse . setStatusLine ( restAssuredResponse . statusCode ( ) ) ; } restAssuredResponse . setRpr ( new ResponseParserRegistrar ( ) ) ; return restAssuredResponse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether value of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher value ( Matcher < ? super String > valueMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"value\" , valueMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether comment of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher comment ( Matcher < ? super String > commentMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"comment\" , commentMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether expiry date of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher expiryDate ( Matcher < ? super Date > expiryDateMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"expiryDate\" , expiryDateMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether domain of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher domain ( Matcher < ? super String > domainMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"domain\" , domainMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether path of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher path ( Matcher < ? super String > pathMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"path\" , pathMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether secured property of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher secured ( Matcher < ? super Boolean > securedMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"secured\" , securedMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether http - only property of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher httpOnly ( Matcher < ? super Boolean > httpOnlyMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"httpOnly\" , httpOnlyMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether version of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher version ( Matcher < ? super Integer > versionMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"version\" , versionMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies whether max age of cookie satisfies specified matcher . [CODESPLIT] public DetailedCookieMatcher maxAge ( Matcher < ? super Integer > maxAgeMatcher ) { return new DetailedCookieMatcher ( and ( Matchers . hasProperty ( \"maxAge\" , maxAgeMatcher ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expect that a response header matches the supplied header name and hamcrest matcher . [CODESPLIT] public ResponseSpecBuilder expectHeader ( String headerName , Matcher < String > expectedValueMatcher ) { spec . header ( headerName , expectedValueMatcher ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expect that a response header matches the supplied name and value . [CODESPLIT] public ResponseSpecBuilder expectHeader ( String headerName , String expectedValue ) { spec . header ( headerName , expectedValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expect that a response cookie matches the supplied cookie name and hamcrest matcher . <p > E . g . <tt > cookieName1 = cookieValue1< / tt > < / p > [CODESPLIT] public ResponseSpecBuilder expectCookie ( String cookieName , Matcher < String > expectedValueMatcher ) { spec . cookie ( cookieName , expectedValueMatcher ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expect that a detailed response cookie matches the supplied cookie name and hamcrest matcher ( see { @link DetailedCookieMatcher } . <p > E . g . expect that the response of the GET request to / something contain cookie <tt > cookieName1 = cookieValue1< / tt > <pre > expectCookie ( cookieName1 detailedCookie () . value ( cookieValue1 ) . secured ( true )) ; < / pre > < / p > <p / > <p > You can also expect several cookies : <pre > expectCookie ( cookieName1 detailedCookie () . value ( cookieValue1 ) . secured ( true )) . expectCookie ( cookieName2 detailedCookie () . value ( cookieValue2 ) . secured ( false )) ; < / pre > < / p > [CODESPLIT] public ResponseSpecBuilder expectCookie ( String cookieName , DetailedCookieMatcher detailedCookieMatcher ) { spec . cookie ( cookieName , detailedCookieMatcher ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expect that a response cookie matches the supplied name and value . [CODESPLIT] public ResponseSpecBuilder expectCookie ( String cookieName , String expectedValue ) { spec . cookie ( cookieName , expectedValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that the response time matches the supplied <code > matcher< / code > and time unit . [CODESPLIT] public ResponseSpecBuilder expectResponseTime ( Matcher < Long > matcher , TimeUnit timeUnit ) { spec . time ( matcher , timeUnit ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the root path of the response body so that you don t need to write the entire path for each expectation . The same as { @link #rootPath ( String ) } but also provides a way to defined arguments . [CODESPLIT] public ResponseSpecBuilder rootPath ( String rootPath , List < Argument > arguments ) { spec . root ( rootPath , arguments ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append the given path to the root path with arguments supplied of the response body so that you don t need to write the entire path for each expectation . This is mainly useful when you have parts of the path defined in variables . E . g . instead of writing : <p / > <pre > String namePath = name ; expect () . root ( x . y ) . body ( age is ( .. )) . body ( gender is ( .. )) . body ( namePath + first is ( .. )) . body ( namePath + last is ( .. )) . when () . get ( .. ) ; < / pre > <p / > you can use a append root and do : <pre > String namePath = name ; expect () . root ( x . y ) . body ( age is ( .. )) . body ( gender is ( .. )) . appendRoot ( %s withArgs ( namePath )) . body ( first is ( .. )) . body ( last is ( .. )) . when () . get ( .. ) ; < / pre > [CODESPLIT] public ResponseSpecBuilder appendRootPath ( String pathToAppend , List < Argument > arguments ) { spec . appendRootPath ( pathToAppend , arguments ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expect that the JSON or XML response content conforms to one or more Hamcrest matchers . <br > <h3 > JSON example< / h3 > <p / > Assume that a GET request to / lotto returns a JSON response containing : <pre > { lotto : { lottoId : 5 winning - numbers : [ 2 45 34 23 7 5 3 ] winners : [ { winnerId : 23 numbers : [ 2 45 34 23 3 5 ] } { winnerId : 54 numbers : [ 52 3 12 11 18 22 ] } ] }} < / pre > <p / > You can verify that the lottoId is equal to 5 like this : <pre > ResponseSpecBuilder builder = new ResponseSpecBuilder () ; builder . expectBody ( lotto . lottoId equalTo ( 5 )) ; < / pre > [CODESPLIT] public ResponseSpecBuilder expectBody ( String path , Matcher < ? > matcher ) { spec . body ( path , matcher ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as { @link #expectBody ( String org . hamcrest . Matcher ) } expect that you can pass arguments to the path . This is useful in situations where you have e . g . pre - defined variables that constitutes the path : <pre > String someSubPath = else ; int index = 1 ; expect () . body ( something . %s [ %d ] withArgs ( someSubPath index ) equalTo ( some value )) . .. < / pre > <p / > or if you have complex root paths and don t wish to duplicate the path for small variations : <pre > expect () . root ( filters . filterConfig [ %d ] . filterConfigGroups . find { it . name == Gold } . includes ) . body ( withArgs ( 0 ) hasItem ( first )) . body ( withArgs ( 1 ) hasItem ( second )) . .. < / pre > <p / > The path and arguments follows the standard <a href = http : // download . oracle . com / javase / 1 5 . 0 / docs / api / java / util / Formatter . html#syntax > formatting syntax< / a > of Java . <p > Note that <code > withArgs< / code > can be statically imported from the <code > io . restassured . RestAssured< / code > class . < / p > [CODESPLIT] public ResponseSpecBuilder expectBody ( String path , List < Argument > arguments , Matcher < ? > matcher ) { spec . body ( path , arguments , matcher ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge this builder with settings from another specification . Note that the supplied specification can overwrite data in the current specification . The following settings are overwritten : <ul > <li > Content type< / li > <li > Root path< / <li > Status code< / li > <li > Status line< / li > < / ul > The following settings are merged : <ul > <li > Response body expectations< / li > <li > Cookies< / li > <li > Headers< / li > < / ul > [CODESPLIT] public ResponseSpecBuilder addResponseSpecification ( ResponseSpecification specification ) { if ( ! ( specification instanceof ResponseSpecificationImpl ) ) { throw new IllegalArgumentException ( \"specification must be of type \" + ResponseSpecificationImpl . class . getClass ( ) + \".\" ) ; } ResponseSpecificationImpl rs = ( ResponseSpecificationImpl ) specification ; SpecificationMerger . merge ( ( ResponseSpecificationImpl ) spec , rs ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enabled logging with the specified log detail . Set a { @link LogConfig } to configure the print stream and pretty printing options . [CODESPLIT] public ResponseSpecBuilder log ( LogDetail logDetail ) { notNull ( logDetail , LogDetail . class ) ; spec . logDetail ( logDetail ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a content - type to be parsed using a predefined parser . E . g . let s say you want parse content - type <tt > application / vnd . uoml + xml< / tt > with the XML parser to be able to verify the response using the XML dot notations : <pre > expect () . body ( document . child equalsTo ( something )) .. < / pre > Since <tt > application / vnd . uoml + xml< / tt > is not registered to be processed by the XML parser by default you need to explicitly tell REST Assured to use this parser before making the request : <pre > expect () . parser ( application / vnd . uoml + xml Parser . XML ) . when () . .. ; < / pre > <p / > You can also specify by default by using : <pre > RestAssured . registerParser ( application / vnd . uoml + xml Parser . XML ) ; < / pre > [CODESPLIT] public ResponseSpecBuilder registerParser ( String contentType , Parser parser ) { spec . parser ( contentType , parser ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Hamcrest matcher that validates that a JSON document conforms to the JSON schema provided to this method . [CODESPLIT] public static JsonSchemaValidator matchesJsonSchema ( String schema ) { return new JsonSchemaValidatorFactory < String > ( ) { @ Override JsonNode createSchemaInstance ( String input ) throws IOException { return JsonLoader . fromString ( input ) ; } } . create ( schema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Hamcrest matcher that validates that a JSON document conforms to the JSON schema provided to this method . [CODESPLIT] public static JsonSchemaValidator matchesJsonSchemaInClasspath ( String pathToSchemaInClasspath ) { return matchesJsonSchema ( Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( pathToSchemaInClasspath ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Hamcrest matcher that validates that a JSON document conforms to the JSON schema provided to this method . [CODESPLIT] public static JsonSchemaValidator matchesJsonSchema ( Reader schema ) { return new JsonSchemaValidatorFactory < Reader > ( ) { @ Override JsonNode createSchemaInstance ( Reader input ) throws IOException { return JsonLoader . fromReader ( input ) ; } } . create ( schema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Hamcrest matcher that validates that a JSON document conforms to the JSON schema provided to this method . [CODESPLIT] public static JsonSchemaValidator matchesJsonSchema ( File file ) { return new JsonSchemaValidatorFactory < File > ( ) { @ Override JsonNode createSchemaInstance ( File input ) throws IOException { return JsonLoader . fromFile ( input ) ; } } . create ( file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compose this { @link ResponseAwareMatcher } with another { @link ResponseAwareMatcher } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T extends ResponseBody < T > & ResponseOptions < T > > ResponseAwareMatcher < T > and ( final ResponseAwareMatcher < T > matcher1 , final ResponseAwareMatcher < T > matcher2 ) { return and ( matcher1 , matcher2 , new ResponseAwareMatcher [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compose this { @link ResponseAwareMatcher } with another { @link ResponseAwareMatcher } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T extends ResponseBody < T > & ResponseOptions < T > > ResponseAwareMatcher < T > and ( final ResponseAwareMatcher < T > matcher1 , final ResponseAwareMatcher < T > matcher2 , final ResponseAwareMatcher < T > ... additionalMatchers ) { return response -> { Matcher < ? > [ ] matchers = toHamcrestMatchers ( response , matcher1 , matcher2 , additionalMatchers ) ; return allOf ( ( Matcher < ? super Object > [ ] ) matchers ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compose this { @link ResponseAwareMatcher } with another { @link ResponseAwareMatcher } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T extends ResponseBody < T > & ResponseOptions < T > > ResponseAwareMatcher < T > or ( final ResponseAwareMatcher < T > matcher1 , final ResponseAwareMatcher < T > matcher2 , final ResponseAwareMatcher < T > ... additionalMatchers ) { return response -> { Matcher < ? > [ ] matchers = toHamcrestMatchers ( response , matcher1 , matcher2 , additionalMatchers ) ; return anyOf ( ( Matcher < ? super Object > [ ] ) matchers ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a single entity with the supplied name . If there are several entities match the <code > entityName< / code > then the last one is returned . [CODESPLIT] public T get ( String entityName ) { notNull ( entityName , \"Entity name\" ) ; List < T > copyOfEntities = reverse ( ) ; for ( T entity : copyOfEntities ) { if ( entity . getName ( ) . equalsIgnoreCase ( entityName ) ) { return entity ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a single entity value with the supplied name . If there are several headers match the <code > headerName< / code > then the last one is returned . [CODESPLIT] public String getValue ( String entityName ) { notNull ( entityName , \"Entity name\" ) ; final T entity = get ( entityName ) ; if ( entity == null ) { return null ; } return entity . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all entities with the supplied name . If there s only one entity matching the <code > entityName< / code > then a list with only that entity is returned . [CODESPLIT] public List < T > getList ( String entityName ) { notNull ( entityName , \"Entity name\" ) ; final List < T > entityList = new ArrayList < T > ( ) ; for ( T entity : entities ) { if ( entity . getName ( ) . equalsIgnoreCase ( entityName ) ) { entityList . add ( entity ) ; } } return Collections . unmodifiableList ( entityList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all entity values of the entity with supplied name . If there s only one header matching the <code > entity name< / code > then a list with only that header value is returned . [CODESPLIT] public List < String > getValues ( String entityName ) { final List < T > list = getList ( entityName ) ; final List < String > stringList = new LinkedList < String > ( ) ; for ( T entity : list ) { stringList . add ( entity . getValue ( ) ) ; } return Collections . unmodifiableList ( stringList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the hostname for of the proxy . Will use port { @value #DEFAULT_PORT } and scheme { @value #DEFAULT_SCHEME } . [CODESPLIT] public static ProxySpecification host ( String host ) { return new ProxySpecification ( host , DEFAULT_PORT , DEFAULT_SCHEME , DEFAULT_USERNAME , DEFAULT_PASSWORD ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify preemptive basic authentication for the proxy . Will use hostname { @value #DEFAULT_HOST } port { @value #DEFAULT_PORT } and scheme { @value #DEFAULT_SCHEME } . [CODESPLIT] public static ProxySpecification auth ( String username , String password ) { AssertParameter . notNull ( username , \"username\" ) ; AssertParameter . notNull ( password , \"password\" ) ; return new ProxySpecification ( DEFAULT_HOST , DEFAULT_PORT , DEFAULT_SCHEME , username , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the hostname of the proxy . [CODESPLIT] public ProxySpecification withHost ( String host ) { return new ProxySpecification ( host , port , scheme , username , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify ( preemptive ) basic authentication for the proxy [CODESPLIT] public ProxySpecification withAuth ( String username , String password ) { AssertParameter . notNull ( username , \"username\" ) ; AssertParameter . notNull ( password , \"password\" ) ; return new ProxySpecification ( host , port , scheme , username , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies if JsonPath should use floats and doubles or BigDecimals to represent Json numbers . [CODESPLIT] public JsonPathConfig numberReturnType ( NumberReturnType numberReturnType ) { return new JsonPathConfig ( numberReturnType , defaultParserType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , johnzonObjectMapperFactory , defaultDeserializer , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an json path configuration that uses the specified parser type as default . [CODESPLIT] public JsonPathConfig defaultParserType ( JsonParserType defaultParserType ) { return new JsonPathConfig ( numberReturnType , defaultParserType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , johnzonObjectMapperFactory , defaultDeserializer , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an json path configuration that uses the specified object de - serializer as default . [CODESPLIT] public JsonPathConfig defaultObjectDeserializer ( JsonPathObjectDeserializer defaultObjectDeserializer ) { return new JsonPathConfig ( numberReturnType , null , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , johnzonObjectMapperFactory , defaultObjectDeserializer , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a custom Gson object mapper factory . [CODESPLIT] public JsonPathConfig gsonObjectMapperFactory ( GsonObjectMapperFactory gsonObjectMapperFactory ) { return new JsonPathConfig ( numberReturnType , defaultParserType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , johnzonObjectMapperFactory , defaultDeserializer , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a custom Jackson 1 . 0 object mapper factory . [CODESPLIT] public JsonPathConfig jackson1ObjectMapperFactory ( Jackson1ObjectMapperFactory jackson1ObjectMapperFactory ) { return new JsonPathConfig ( numberReturnType , defaultParserType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , johnzonObjectMapperFactory , defaultDeserializer , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a custom Jackson 1 . 0 object mapper factory . [CODESPLIT] public JsonPathConfig jackson2ObjectMapperFactory ( Jackson2ObjectMapperFactory jackson2ObjectMapperFactory ) { return new JsonPathConfig ( numberReturnType , defaultParserType , gsonObjectMapperFactory , jackson1ObjectMapperFactory , jackson2ObjectMapperFactory , johnzonObjectMapperFactory , defaultDeserializer , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the <code > potentialUri< / code > is a URI . [CODESPLIT] public static boolean isUri ( String potentialUri ) { if ( StringUtils . isBlank ( potentialUri ) ) { return false ; } try { URI uri = new URI ( potentialUri ) ; return uri . getScheme ( ) != null && uri . getHost ( ) != null ; } catch ( URISyntaxException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a new default stream to the print to . [CODESPLIT] public LogConfig defaultStream ( PrintStream printStream ) { return new LogConfig ( printStream , true , logDetailIfValidationFails , urlEncodeRequestUri , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable logging of both the request and the response if REST Assureds test validation fails with the specified log detail [CODESPLIT] public LogConfig enableLoggingOfRequestAndResponseIfValidationFails ( LogDetail logDetail ) { return new LogConfig ( defaultPrintStream , prettyPrintingEnabled , logDetail , urlEncodeRequestUri , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO Extract content - type from headers and apply charset if needed! [CODESPLIT] public static String findContentType ( Headers headers , List < Object > multiParts , SpecificationConfig config ) { String requestContentType = headers . getValue ( CONTENT_TYPE ) ; if ( StringUtils . isBlank ( requestContentType ) && ! multiParts . isEmpty ( ) ) { requestContentType = \"multipart/\" + config . getMultiPartConfig ( ) . defaultSubtype ( ) ; } EncoderConfig encoderConfig = config . getEncoderConfig ( ) ; if ( requestContentType != null && encoderConfig . shouldAppendDefaultContentCharsetToContentTypeIfUndefined ( ) && ! StringUtils . containsIgnoreCase ( requestContentType , CHARSET ) ) { // Append default charset to request content type requestContentType += \"; charset=\" ; if ( encoderConfig . hasDefaultCharsetForContentType ( requestContentType ) ) { requestContentType += encoderConfig . defaultCharsetForContentType ( requestContentType ) ; } else { requestContentType += encoderConfig . defaultContentCharset ( ) ; } } return requestContentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the HttpRequest class that represents this request type . [CODESPLIT] static HttpRequestBase createHttpRequest ( URI uri , String httpMethod , boolean hasBody ) { String method = notNull ( upperCase ( trimToNull ( httpMethod ) ) , \"Http method\" ) ; Class < ? extends HttpRequestBase > type = HTTP_METHOD_TO_HTTP_REQUEST_TYPE . get ( method ) ; final HttpRequestBase httpRequest ; // If we are sending HTTP method that does not allow body (like GET) then HTTP library prevents // us from including it, however we chose to allow deviations from standard if user wants so, // so it needs custom handling - hence the second condition below. // Otherwise we should use standard implementation found in the map if ( type == null || ( ! ( type . isInstance ( HttpEntityEnclosingRequest . class ) ) && hasBody ) ) { httpRequest = new CustomHttpMethod ( method , uri ) ; } else { try { httpRequest = type . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } httpRequest . setURI ( uri ) ; } return httpRequest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new { @link MockMvcFactory } with the supplied controllers or mock mvc configureres [CODESPLIT] public static MockMvcFactory of ( Object [ ] controllerOrMockMvcConfigurers ) { List < Object > controllers = new ArrayList < Object > ( ) ; List < MockMvcConfigurer > configurers = new ArrayList < MockMvcConfigurer > ( ) ; for ( Object object : controllerOrMockMvcConfigurers ) { if ( object instanceof MockMvcConfigurer ) { configurers . add ( ( MockMvcConfigurer ) object ) ; } else { controllers . add ( object ) ; } } StandaloneMockMvcBuilder mockMvc = MockMvcBuilders . standaloneSetup ( controllers . toArray ( ) ) ; if ( ! configurers . isEmpty ( ) ) { for ( MockMvcConfigurer configurer : configurers ) { mockMvc . apply ( configurer ) ; } } return new MockMvcFactory ( mockMvc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define headers that should be overwritten instead of merged adding headers or using request specifications . Note that by default all headers are merged except the { @value #ACCEPT_HEADER_NAME } and { @value #CONTENT_TYPE_HEADER_NAME } headers . For example if the header with name <code > header1< / code > is <i > not< / i > marked as overwritable ( default ) and you do the following : <pre > given () . header ( header1 value1 ) . header ( header1 value2 ) . .. < / pre > <p / > Then <code > header1< / code > will be sent twice in the request : <pre > header1 : value1 header1 : value2 < / pre > <p / > If you configure <code > header1< / code > to be overwritable by doing : <pre > given () . config ( RestAssured . config () . headerConfig ( headerConfig () . overwriteHeadersWithName ( header1 )) . header ( header1 value1 ) . header ( header1 value2 ) . ... < / pre > then <code > header1< / code > will only be sent once : <pre > header1 : value2 < / pre > [CODESPLIT] public HeaderConfig overwriteHeadersWithName ( String headerName , String ... additionalHeaderNames ) { notNull ( headerName , \"Header name\" ) ; Map < String , Boolean > map = newHashMapReturningFalseByDefault ( headerName ) ; if ( additionalHeaderNames != null && additionalHeaderNames . length > 0 ) { for ( String additionalHeaderName : additionalHeaderNames ) { map . put ( additionalHeaderName . toUpperCase ( ) , true ) ; } } return new HeaderConfig ( map , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default control name to use if not defined explicitly in multi - part request . <p > Default is { @value #DEFAULT_CONTROL_NAME } < / p > [CODESPLIT] public MultiPartConfig defaultControlName ( String defaultControlName ) { return new MultiPartConfig ( defaultControlName , defaultFileName , defaultSubtype , defaultBoundary , defaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default filename to use if not defined explicitly in multi - part request . <p > Default is { @value #DEFAULT_FILE_NAME } < / p > [CODESPLIT] public MultiPartConfig defaultFileName ( String defaultFileName ) { return new MultiPartConfig ( defaultControlName , defaultFileName , defaultSubtype , defaultBoundary , defaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default subtype to use if not defined explicitly in when making the multi - part request . This will control how the Content - Type will be constructed for multipart requests when using REST Assured when no Content - Type header has been explicitly defined . For example if subtype is set to mixed then the Content - Type header will be multipart / mixed if not specified explicitly . <p > Default is { @value #DEFAULT_SUBTYPE } < / p > [CODESPLIT] public MultiPartConfig defaultSubtype ( String defaultSubtype ) { return new MultiPartConfig ( defaultControlName , defaultFileName , defaultSubtype , defaultBoundary , defaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify an explicit default multipart boundary to use when sending multi - part data . [CODESPLIT] public MultiPartConfig defaultBoundary ( String defaultBoundary ) { return new MultiPartConfig ( defaultControlName , defaultFileName , defaultSubtype , defaultBoundary , defaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a default charset to use for multi - parts ( default is US - ASCII ) . This affects the encoding of the multipart body ( such as the control name ) but <i > not< / i > the actual <i > content< / i > ( such as the a JSON or String document ) . <p > <b > NOTE : < / b > This setting is <i > only< / i > taken into account if { @link HttpClientConfig#httpMultipartMode ( HttpMultipartMode ) } is set to something other than { @link HttpMultipartMode#STRICT } ( which is the default ) . So if you want this setting to apply you also need to explicitly change the multipart mode for example : [CODESPLIT] public MultiPartConfig defaultCharset ( String defaultCharset ) { return new MultiPartConfig ( defaultControlName , defaultFileName , defaultSubtype , defaultBoundary , defaultCharset , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a default charset to use for multi - parts ( default is US - ASCII ) . This affects the encoding of the multipart body ( such as the control name ) but <i > not< / i > the actual <i > content< / i > ( such as the a JSON or String document ) . <p > <b > NOTE : < / b > This setting is <i > only< / i > taken into account if { @link HttpClientConfig#httpMultipartMode ( HttpMultipartMode ) } is set to something other than { @link HttpMultipartMode#STRICT } ( which is the default ) . So if you want this setting to apply you also need to explicitly change the multipart mode for example : [CODESPLIT] public MultiPartConfig defaultCharset ( Charset defaultCharset ) { String charsetAsString = AssertParameter . notNull ( defaultCharset , Charset . class ) . toString ( ) ; return new MultiPartConfig ( defaultControlName , defaultFileName , defaultSubtype , defaultBoundary , charsetAsString , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper . This works for the POST PATCH and PUT methods only . Trying to do this for the other http methods will cause an exception to be thrown . <p > Note that { @link #setBody ( Object ObjectMapper ) } are the same except for the syntactic difference . < / p > [CODESPLIT] public MockMvcRequestSpecBuilder setBody ( Object object , ObjectMapper mapper ) { spec . body ( object , mapper ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper type . This works for the POST PATCH and PUT methods only . Trying to do this for the other http methods will cause an exception to be thrown . <p > Example of use : <pre > Message message = new Message () ; message . setMessage ( My beautiful message ) ; [CODESPLIT] public MockMvcRequestSpecBuilder setBody ( Object object , ObjectMapperType mapperType ) { spec . body ( object , mapperType ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a session attribute . [CODESPLIT] MockMvcRequestSpecBuilder addSessionAttr ( String name , Object value ) { spec . sessionAttr ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add request attribute [CODESPLIT] public MockMvcRequestSpecBuilder addAttribute ( String attributeName , Object attributeValue ) { spec . attribute ( attributeName , attributeValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a header to be sent with the request [CODESPLIT] public MockMvcRequestSpecBuilder addHeader ( String headerName , String headerValue ) { spec . header ( headerName , headerValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a file to upload to the server using multi - part form data uploading with a specific control name . It will use the content - type <tt > application / octet - stream< / tt > . If this is not what you want please use an overloaded method . [CODESPLIT] public MockMvcRequestSpecBuilder addMultiPart ( String controlName , File file ) { spec . multiPart ( controlName , file ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a byte - array to upload to the server using multi - part form data . It will use the content - type <tt > application / octet - stream< / tt > . If this is not what you want please use an overloaded method . [CODESPLIT] public MockMvcRequestSpecBuilder addMultiPart ( String controlName , String fileName , byte [ ] bytes ) { spec . multiPart ( controlName , fileName , bytes ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a string to send to the server using multi - part form data . It will use the content - type <tt > text / plain< / tt > . If this is not what you want please use an overloaded method . [CODESPLIT] public MockMvcRequestSpecBuilder addMultiPart ( String controlName , String contentBody ) { spec . multiPart ( controlName , contentBody ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a string to send to the server using multi - part form data with a specific mime - type . [CODESPLIT] public MockMvcRequestSpecBuilder addMultiPart ( String controlName , String contentBody , String mimeType ) { spec . multiPart ( controlName , mimeType ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the session id name and value for this request . It ll override the default session id name from the configuration ( by default this is { @value SessionConfig#DEFAULT_SESSION_ID_NAME } ) . You can configure the default session id name by using : <pre > RestAssuredMockMvc . config = newConfig () . sessionConfig ( new SessionConfig () . sessionIdName ( &lt ; sessionIdName&gt ; )) ; < / pre > and then you can use the { @link MockMvcRequestSpecBuilder#setSessionId ( String ) } method to set the session id value without specifying the name for each request . [CODESPLIT] public MockMvcRequestSpecBuilder setSessionId ( String sessionIdName , String sessionIdValue ) { spec . sessionId ( sessionIdName , sessionIdValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize with a { @link WebApplicationContext } that will be used to create the { @link MockMvc } instance . <p / > Note that this will override the any { @link MockMvc } instances configured by other setters . [CODESPLIT] public MockMvcRequestSpecBuilder setWebAppContextSetup ( WebApplicationContext context , MockMvcConfigurer ... mockMvcConfigurers ) { spec . webAppContextSetup ( context , mockMvcConfigurers ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a result handler [CODESPLIT] public MockMvcRequestSpecBuilder addResultHandlers ( ResultHandler resultHandler , ResultHandler ... additionalResultHandlers ) { spec . resultHandlers ( resultHandler , additionalResultHandlers ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enabled logging with the specified log detail . Set a { @link LogConfig } to configure the print stream and pretty printing options . [CODESPLIT] public MockMvcRequestSpecBuilder log ( LogDetail logDetail ) { notNull ( logDetail , LogDetail . class ) ; LogConfig logConfig = spec . getRestAssuredMockMvcConfig ( ) . getLogConfig ( ) ; PrintStream printStream = logConfig . defaultStream ( ) ; boolean prettyPrintingEnabled = logConfig . isPrettyPrintingEnabled ( ) ; boolean shouldUrlEncodeRequestUri = logConfig . shouldUrlEncodeRequestUri ( ) ; spec . setRequestLoggingFilter ( new RequestLoggingFilter ( logDetail , prettyPrintingEnabled , printStream , shouldUrlEncodeRequestUri ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a http client parameter . [CODESPLIT] public < T > HttpClientConfig setParam ( String parameterName , T parameterValue ) { notNull ( parameterName , \"Parameter name\" ) ; final Map < String , Object > newParams = new HashMap < String , Object > ( httpClientParams ) ; newParams . put ( parameterName , parameterValue ) ; return new HttpClientConfig ( httpClientFactory , newParams , httpMultipartMode , shouldReuseHttpClientInstance , NO_HTTP_CLIENT , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the currently configured parameters with the ones supplied by <code > httpClientParams< / code > . This method is the same as { @link #setParams ( java . util . Map ) } . [CODESPLIT] public HttpClientConfig withParams ( Map < String , ? > httpClientParams ) { return new HttpClientConfig ( httpClientFactory , httpClientParams , httpMultipartMode , shouldReuseHttpClientInstance , NO_HTTP_CLIENT , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the given parameters to an already configured number of parameters . [CODESPLIT] public HttpClientConfig addParams ( Map < String , ? > httpClientParams ) { notNull ( httpClientParams , \"httpClientParams\" ) ; final Map < String , Object > newParams = new HashMap < String , Object > ( this . httpClientParams ) ; newParams . putAll ( httpClientParams ) ; return new HttpClientConfig ( httpClientFactory , newParams , httpMultipartMode , shouldReuseHttpClientInstance , NO_HTTP_CLIENT , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the http client factory that Rest Assured should use when making request . For each request REST Assured will invoke the factory to get the a the HttpClient instance . [CODESPLIT] public HttpClientConfig httpClientFactory ( HttpClientFactory httpClientFactory ) { return new HttpClientConfig ( httpClientFactory , httpClientParams , httpMultipartMode , shouldReuseHttpClientInstance , NO_HTTP_CLIENT , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the HTTP Multipart mode when sending multi - part data . [CODESPLIT] public HttpClientConfig httpMultipartMode ( HttpMultipartMode httpMultipartMode ) { return new HttpClientConfig ( httpClientFactory , httpClientParams , httpMultipartMode , shouldReuseHttpClientInstance , httpClient , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a boolean . [CODESPLIT] public < T > T get ( String path ) { final JSONAssertion jsonAssertion = createJsonAssertion ( path , params ) ; final Object json = jsonParser . parseWith ( createConfigurableJsonSlurper ( ) ) ; return ( T ) jsonAssertion . getResult ( json , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as an int . [CODESPLIT] public int getInt ( String path ) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get ( path ) ; if ( value instanceof Integer ) { return ( Integer ) value ; } else if ( value instanceof Short ) { return ( ( Short ) value ) . intValue ( ) ; } else if ( value instanceof Long ) { return ( ( Long ) value ) . intValue ( ) ; } else { return ObjectConverter . convertObjectTo ( value , Integer . class ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a byte . [CODESPLIT] public byte getByte ( String path ) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get ( path ) ; if ( value instanceof Byte ) { return ( Byte ) value ; } else if ( value instanceof Long ) { return ( ( Long ) value ) . byteValue ( ) ; } else if ( value instanceof Integer ) { return ( ( Integer ) value ) . byteValue ( ) ; } else { return ObjectConverter . convertObjectTo ( value , Byte . class ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a short . [CODESPLIT] public short getShort ( String path ) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get ( path ) ; if ( value instanceof Short ) { return ( Short ) value ; } else if ( value instanceof Long ) { return ( ( Long ) value ) . shortValue ( ) ; } else if ( value instanceof Integer ) { return ( ( Integer ) value ) . shortValue ( ) ; } else { return ObjectConverter . convertObjectTo ( value , Short . class ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a float . [CODESPLIT] public float getFloat ( String path ) { final Object value = get ( path ) ; //Groovy will always return a Double for floating point values. if ( value instanceof Double ) { return ( ( Double ) value ) . floatValue ( ) ; } else { return ObjectConverter . convertObjectTo ( value , Float . class ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a double . [CODESPLIT] public double getDouble ( String path ) { final Object value = get ( path ) ; if ( value instanceof Double ) { return ( Double ) value ; } return ObjectConverter . convertObjectTo ( value , Double . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a long . [CODESPLIT] public long getLong ( String path ) { //The type returned from Groovy depends on the input, so we need to handle different numerical types. Object value = get ( path ) ; if ( value instanceof Long ) { return ( Long ) value ; } else if ( value instanceof Short ) { return ( ( Short ) value ) . longValue ( ) ; } else if ( value instanceof Integer ) { return ( ( Integer ) value ) . longValue ( ) ; } else { return ObjectConverter . convertObjectTo ( value , Long . class ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a list . [CODESPLIT] public < T > List < T > getList ( String path , Class < T > genericType ) { if ( genericType == null ) { throw new IllegalArgumentException ( \"Generic type cannot be null\" ) ; } final List < T > original = get ( path ) ; final List < T > newList = new LinkedList < T > ( ) ; if ( original != null ) { for ( T t : original ) { T e ; if ( t instanceof Map && ! genericType . isAssignableFrom ( Map . class ) ) { // TODO Avoid double parsing String str = objectToString ( t ) ; //noinspection unchecked e = ( T ) jsonStringToObject ( str , genericType ) ; } else { e = ObjectConverter . convertObjectTo ( t , genericType ) ; } newList . add ( e ) ; } } return Collections . unmodifiableList ( newList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an Object path expression as a map . [CODESPLIT] public < K , V > Map < K , V > getMap ( String path ) { return get ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of a Object path expression as a java Object . E . g . given the following Object document : <pre > { store : { book : [ { category : reference author : Nigel Rees title : Sayings of the Century price : 8 . 95 } { category : fiction author : Evelyn Waugh title : Sword of Honour price : 12 . 99 } { category : fiction author : Herman Melville title : Moby Dick isbn : 0 - 553 - 21311 - 3 price : 8 . 99 } { category : fiction author : J . R . R . Tolkien title : The Lord of the Rings isbn : 0 - 395 - 19395 - 8 price : 22 . 99 } ] bicycle : { color : red price : 19 . 95 } } } < / pre > And a Java object like this : <p / > <pre > public class Book { private String category ; private String author ; private String title ; private String isbn ; private float price ; [CODESPLIT] public < T > T getObject ( String path , Class < T > objectType ) { Object object = getJsonObject ( path ) ; if ( object == null ) { return null ; } else if ( object instanceof List || object instanceof Map ) { // TODO Avoid double parsing object = objectToString ( object ) ; } else { return ObjectConverter . convertObjectTo ( object , objectType ) ; } if ( ! ( object instanceof String ) ) { throw new IllegalStateException ( \"Internal error: Json object was not an instance of String, please report to the REST Assured mailing-list.\" ) ; } return ( T ) jsonStringToObject ( ( String ) object , objectType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of a Object path expression as a java Object with generic type . E . g . given the following Object document : <pre > { store : { book : [ { category : reference author : Nigel Rees title : Sayings of the Century price : 8 . 95 } { category : fiction author : Evelyn Waugh title : Sword of Honour price : 12 . 99 } { category : fiction author : Herman Melville title : Moby Dick isbn : 0 - 553 - 21311 - 3 price : 8 . 99 } { category : fiction author : J . R . R . Tolkien title : The Lord of the Rings isbn : 0 - 395 - 19395 - 8 price : 22 . 99 } ] bicycle : { color : red price : 19 . 95 } } } < / pre > And you want to get a book as a <code > Map&lt ; String Object&gt ; < / code > : <p / > Then <pre > Map&lt ; String Object&gt ; book = from ( Object ) . getObject ( store . book [ 2 ] new TypeRef&lt ; Map&lt ; String Object&gt ; &gt ; () {} ) ; < / pre > <p / > maps the second book to a Book instance . [CODESPLIT] public < T > T getObject ( String path , TypeRef < T > typeRef ) { AssertParameter . notNull ( \"objectType\" , \"Type ref\" ) ; return getObject ( path , typeRef . getTypeAsClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a parameter for the expression . Example : <pre > String name = System . console () . readLine () ; List&lt ; Map&gt ; books = with ( Object ) . param ( name name ) . get ( store . book . findAll { book - > book . author == name } ) ; < / pre > [CODESPLIT] public JsonPath param ( String key , Object value ) { JsonPath newP = new JsonPath ( this , config ) ; if ( newP . params == null ) { newP . params = new HashMap < String , Object > ( ) ; } newP . params . put ( key , value ) ; return newP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get and print the JSON as a prettified string . <p > Note that the content is not guaranteed to be looking exactly like the it does at the source . This is because once you peek the content has been downloaded and transformed into another data structure ( used by JsonPath ) and the JSON is rendered from this data structure . < / p > [CODESPLIT] public String prettyPrint ( ) { final String pretty = prettify ( ) ; System . out . println ( pretty ) ; return pretty ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify features that will be used when parsing XML . [CODESPLIT] public XmlConfig features ( Map < String , Boolean > features ) { return new XmlConfig ( features , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify properties that will be used when parsing XML . [CODESPLIT] public XmlConfig properties ( Map < String , Object > properties ) { return new XmlConfig ( features , declaredNamespaces , this . properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value of a feature flag . [CODESPLIT] public XmlConfig feature ( String uri , boolean enabled ) { Validate . notEmpty ( uri , \"URI cannot be empty\" ) ; Map < String , Boolean > newFeatures = new HashMap < String , Boolean > ( features ) ; newFeatures . put ( uri , enabled ) ; return new XmlConfig ( newFeatures , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value of a property . [CODESPLIT] public XmlConfig property ( String name , Object value ) { Validate . notEmpty ( name , \"Name cannot be empty\" ) ; Map < String , Object > newProperties = new HashMap < String , Object > ( properties ) ; newProperties . put ( name , value ) ; return new XmlConfig ( features , declaredNamespaces , newProperties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify declared namespaces that will be used when parsing XML . Will also set { @link #namespaceAware ( boolean ) } to <code > true< / code > of namespaces are not empty . <p > Note that you cannot use this to add namespaces for the { @link org . hamcrest . xml . HasXPath } matcher . This has to be done by providing a { @link javax . xml . namespace . NamespaceContext } to the matcher instance . < / p > [CODESPLIT] public XmlConfig declareNamespaces ( Map < String , String > namespacesToDeclare ) { final boolean shouldBeNamespaceAware = namespacesToDeclare == null ? namespaceAware : ! namespacesToDeclare . isEmpty ( ) ; return new XmlConfig ( features , namespacesToDeclare , properties , validating , shouldBeNamespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declares a namespace and also sets { @link #namespaceAware ( boolean ) } to <code > true< / code > . <p / > <p > Note that you cannot use this to add namespaces for the { @link org . hamcrest . xml . HasXPath } matcher . This has to be done by providing a { @link javax . xml . namespace . NamespaceContext } to the matcher instance . < / p > [CODESPLIT] public XmlConfig declareNamespace ( String prefix , String namespaceURI ) { Validate . notEmpty ( prefix , \"Prefix cannot be empty\" ) ; Validate . notEmpty ( namespaceURI , \"Namespace URI cannot be empty\" ) ; Map < String , String > updatedNamespaces = new HashMap < String , String > ( declaredNamespaces ) ; updatedNamespaces . put ( prefix , namespaceURI ) ; return new XmlConfig ( features , updatedNamespaces , properties , validating , true , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disables external DTD loading . <p > This is a shortcut for doing : <br > <pre > setFeature ( http : // apache . org / xml / features / nonvalidating / load - external - dtd false ) ; < / pre > < / p > [CODESPLIT] public XmlConfig disableLoadingOfExternalDtd ( ) { Map < String , Boolean > newFeatures = new HashMap < String , Boolean > ( features ) ; newFeatures . put ( \"http://apache.org/xml/features/nonvalidating/load-external-dtd\" , false ) ; return new XmlConfig ( newFeatures , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure if XmlPath should validate documents as they are parsed ( default is { @value #DEFAULT_VALIDATING } ) . Note that this is only applicable when { @link XmlPath . CompatibilityMode } is equal to { @link XmlPath . CompatibilityMode#XML } . [CODESPLIT] public XmlConfig validating ( boolean isValidating ) { return new XmlConfig ( features , declaredNamespaces , properties , isValidating , namespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure whether or not REST Assured should be aware of namespaces when parsing XML ( default is { @value #DEFAULT_NAMESPACE_AWARE } ) . Note that this is only applicable when { @link XmlPath . CompatibilityMode } is equal to { @link XmlPath . CompatibilityMode#XML } . [CODESPLIT] public XmlConfig namespaceAware ( boolean shouldBeAwareOfNamespaces ) { return new XmlConfig ( features , declaredNamespaces , properties , validating , shouldBeAwareOfNamespaces , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure if XmlPath should provide support for DOCTYPE declarations ( default is { @value #DEFAULT_ALLOW_DOC_TYPE_DECLARATION } ) . Note that this is only applicable when { @link XmlPath . CompatibilityMode } is equal to { @link XmlPath . CompatibilityMode#XML } . [CODESPLIT] public XmlConfig allowDocTypeDeclaration ( boolean allowDocTypeDeclaration ) { return new XmlConfig ( features , declaredNamespaces , properties , validating , namespaceAware , allowDocTypeDeclaration , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public DecoderConfig defaultCharsetForContentType ( String charset , String contentType ) { notNull ( charset , \"Charset\" ) ; notNull ( contentType , \"ContentType\" ) ; Map < String , String > map = new HashMap < String , String > ( contentTypeToDefaultCharset ) ; map . put ( trim ( contentType ) . toLowerCase ( ) , trim ( charset ) ) ; return new DecoderConfig ( charset , useNoWrapForInflateDecoding , true , contentDecoders , map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public DecoderConfig defaultCharsetForContentType ( Charset charset , String contentType ) { notNull ( charset , \"Charset\" ) ; return defaultCharsetForContentType ( charset . toString ( ) , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset to use for the specific content - type if it s not specified in the content - type header explicitly [CODESPLIT] public DecoderConfig defaultCharsetForContentType ( Charset charset , ContentType contentType ) { notNull ( charset , \"Charset\" ) ; return defaultCharsetForContentType ( charset . toString ( ) , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset of the content in the response that s assumed if no charset is explicitly specified in the response . [CODESPLIT] @ SuppressWarnings ( \"UnusedDeclaration\" ) public DecoderConfig defaultContentCharset ( String charset ) { return new DecoderConfig ( charset , useNoWrapForInflateDecoding , true , contentDecoders , contentTypeToDefaultCharset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the default charset of the content in the response that s assumed if no charset is explicitly specified in the response . [CODESPLIT] @ SuppressWarnings ( \"UnusedDeclaration\" ) public DecoderConfig defaultContentCharset ( Charset charset ) { String charsetAsString = notNull ( charset , Charset . class ) . toString ( ) ; return new DecoderConfig ( charsetAsString , useNoWrapForInflateDecoding , true , contentDecoders , contentTypeToDefaultCharset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the content decoders that will be presented to the server when making a request ( using the <code > Accept - Encoding< / code > header ) . If the server supports any of these encodings then REST Assured will automatically perform decoding of the response accordingly . <p > By default { @link ContentDecoder#GZIP } and { @link ContentDecoder#DEFLATE } are used . < / p > [CODESPLIT] public DecoderConfig contentDecoders ( ContentDecoder contentDecoder , ContentDecoder ... additionalContentDecoders ) { return new DecoderConfig ( defaultContentCharset , useNoWrapForInflateDecoding , true , contentTypeToDefaultCharset , merge ( contentDecoder , additionalContentDecoders ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public < T > T get ( String path ) { AssertParameter . notNull ( path , \"path\" ) ; return getFromPath ( path , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a list . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public < T > List < T > getList ( String path , Class < T > genericType ) { return getAsList ( path , genericType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a map . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public < K , V > Map < K , V > getMap ( String path , Class < K > keyType , Class < V > valueType ) { final Map < K , V > originalMap = get ( path ) ; final Map < K , V > newMap = new HashMap < K , V > ( ) ; for ( Entry < K , V > entry : originalMap . entrySet ( ) ) { final K key = entry . getKey ( ) == null ? null : convertObjectTo ( entry . getKey ( ) , keyType ) ; final V value = entry . getValue ( ) == null ? null : convertObjectTo ( entry . getValue ( ) , valueType ) ; newMap . put ( key , value ) ; } return Collections . unmodifiableMap ( newMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an XML document as a Java Object . [CODESPLIT] public < T > T getObject ( String path , Class < T > objectType ) { Object object = getFromPath ( path , false ) ; return getObjectAsType ( object , objectType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as an int . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public int getInt ( String path ) { final Object object = get ( path ) ; return convertObjectTo ( object , Integer . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a boolean . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public boolean getBoolean ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Boolean . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a char . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public char getChar ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Character . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a byte . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public byte getByte ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Byte . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a short . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public short getShort ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Short . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a float . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public float getFloat ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Float . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a double . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public double getDouble ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Double . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a long . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public long getLong ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , Long . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a string . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public String getString ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , String . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the result of an XML path expression as a UUID . For syntax details please refer to <a href = http : // www . groovy - lang . org / processing - xml . html#_manipulating_xml > this< / a > url . [CODESPLIT] public UUID getUUID ( String path ) { Object object = get ( path ) ; return convertObjectTo ( object , UUID . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a parameter for the expression . Example : <pre > String type = System . console () . readLine () ; List&lt ; Map&gt ; books = with ( Object ) . param ( type type ) . get ( shopping . category . findAll { it . @type == type } ) ; < / pre > [CODESPLIT] public XmlPath param ( String key , Object value ) { XmlPath newP = new XmlPath ( this , getXmlPathConfig ( ) ) ; if ( newP . params == null ) { newP . params = new HashMap < String , Object > ( ) ; } newP . params . put ( key , value ) ; return newP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peeks into the XML / HTML that XmlPath will parse by printing it to the console . You can continue working with XmlPath afterwards . This is mainly for debug purposes . If you want to return a prettified version of the content see { @link #prettify () } . If you want to return a prettified version of the content and also print it to the console use { @link #prettyPrint () } . <p / > <p > Note that the content is not guaranteed to be looking exactly like the it does at the source . This is because once you peek the content has been downloaded and transformed into another data structure ( used by XmlPath ) and the XML is rendered from this data structure . < / p > [CODESPLIT] public XmlPath peek ( ) { final GPathResult result = lazyXmlParser . invoke ( ) ; final String render = XmlRenderer . render ( result ) ; System . out . println ( render ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peeks into the XML / HTML that XmlPath will parse by printing it to the console in a prettified manner . You can continue working with XmlPath afterwards . This is mainly for debug purposes . If you want to return a prettified version of the content see { @link #prettify () } . If you want to return a prettified version of the content and also print it to the console use { @link #prettyPrint () } . <p / > <p > Note that the content is not guaranteed to be looking exactly like the it does at the source . This is because once you peek the content has been downloaded and transformed into another data structure ( used by XmlPath ) and the XML is rendered from this data structure . < / p > [CODESPLIT] public XmlPath prettyPeek ( ) { final GPathResult result = lazyXmlParser . invoke ( ) ; final String prettify = XmlPrettifier . prettify ( result ) ; System . out . println ( prettify ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper . This works for the POST PATCH and PUT methods only . Trying to do this for the other http methods will cause an exception to be thrown . [CODESPLIT] public RequestSpecBuilder setBody ( Object object , ObjectMapper mapper ) { spec . body ( object , mapper ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify an Object request content that will automatically be serialized to JSON or XML and sent with the request using a specific object mapper type . This works for the POST PATCH and PUT methods only . Trying to do this for the other http methods will cause an exception to be thrown . <p > Example of use : <pre > Message message = new Message () ; message . setMessage ( My beautiful message ) ; [CODESPLIT] public RequestSpecBuilder setBody ( Object object , ObjectMapperType mapperType ) { spec . body ( object , mapperType ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a cookie to be sent with the request . [CODESPLIT] public RequestSpecBuilder addCookie ( String key , Object value , Object ... cookieNameValuePairs ) { spec . cookie ( key , value , cookieNameValuePairs ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a parameter to be sent with the request . [CODESPLIT] public RequestSpecBuilder addParam ( String parameterName , Object ... parameterValues ) { spec . param ( parameterName , parameterValues ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a multi - value parameter to be sent with the request . [CODESPLIT] public RequestSpecBuilder addParam ( String parameterName , Collection < ? > parameterValues ) { spec . param ( parameterName , parameterValues ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a query parameter to be sent with the request . This method is the same as { @link #addParam ( String java . util . Collection ) } for all HTTP methods except POST where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addQueryParam ( String parameterName , Collection < ? > parameterValues ) { spec . queryParam ( parameterName , parameterValues ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a query parameter to be sent with the request . This method is the same as { @link #addParam ( String Object ... ) } ) } for all HTTP methods except POST where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addQueryParam ( String parameterName , Object ... parameterValues ) { spec . queryParam ( parameterName , parameterValues ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a form parameter to be sent with the request . This method is the same as { @link #addParam ( String java . util . Collection ) } for all HTTP methods except PUT where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addFormParam ( String parameterName , Collection < ? > parameterValues ) { spec . formParam ( parameterName , parameterValues ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a form parameter to be sent with the request . This method is the same as { @link #addParam ( String Object ... ) } ) } for all HTTP methods except PUT where this method can be used to differentiate between form and query params . [CODESPLIT] public RequestSpecBuilder addFormParam ( String parameterName , Object ... parameterValues ) { spec . formParam ( parameterName , parameterValues ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a path parameter . Path parameters are used to improve readability of the request path . E . g . instead of writing : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / + myItem . getItemNumber () + / buy / + 2 ) ; < / pre > you can write : <pre > given () . pathParam ( itemNumber myItem . getItemNumber () ) . pathParam ( amount 2 ) . expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } ) ; < / pre > <p / > which improves readability and allows the path to be reusable in many tests . Another alternative is to use : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } myItem . getItemNumber () 2 ) ; < / pre > [CODESPLIT] public RequestSpecBuilder addPathParam ( String parameterName , Object parameterValue ) { spec . pathParam ( parameterName , parameterValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify multiple path parameter name - value pairs . Path parameters are used to improve readability of the request path . E . g . instead of writing : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / + myItem . getItemNumber () + / buy / + 2 ) ; < / pre > you can write : <pre > given () . pathParam ( itemNumber myItem . getItemNumber () amount 2 ) . expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } ) ; < / pre > <p / > which improves readability and allows the path to be reusable in many tests . Another alternative is to use : <pre > expect () . statusCode ( 200 ) . when () . get ( / item / { itemNumber } / buy / { amount } myItem . getItemNumber () 2 ) ; < / pre > [CODESPLIT] public RequestSpecBuilder addPathParams ( String firstParameterName , Object firstParameterValue , Object ... parameterNameValuePairs ) { spec . pathParams ( firstParameterName , firstParameterValue , parameterNameValuePairs ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a keystore . <pre > RestAssured . keyStore ( / truststore_javanet . jks test1234 ) ; < / pre > or <pre > given () . keyStore ( / truststore_javanet . jks test1234 ) . .. < / pre > < / p > [CODESPLIT] public RequestSpecBuilder setKeyStore ( String pathToJks , String password ) { spec . keyStore ( pathToJks , password ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The following documentation is taken from <a href = HTTP Builder > https : // github . com / jgritman / httpbuilder / wiki / SSL< / a > : <p > <h1 > SSL Configuration< / h1 > <p / > SSL should for the most part just work . There are a few situations where it is not completely intuitive . You can follow the example below or see HttpClient s SSLSocketFactory documentation for more information . <p / > <h1 > SSLPeerUnverifiedException< / h1 > <p / > If you can t connect to an SSL website it is likely because the certificate chain is not trusted . This is an Apache HttpClient issue but explained here for convenience . To correct the untrusted certificate you need to import a certificate into an SSL truststore . <p / > First export a certificate from the website using your browser . For example if you go to https : // dev . java . net in Firefox you will probably get a warning in your browser . Choose Add Exception Get Certificate View Details tab . Choose a certificate in the chain and export it as a PEM file . You can view the details of the exported certificate like so : <pre > $ keytool - printcert - file EquifaxSecureGlobaleBusinessCA - 1 . crt Owner : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Issuer : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Serial number : 1 Valid from : Mon Jun 21 00 : 00 : 00 EDT 1999 until : Sun Jun 21 00 : 00 : 00 EDT 2020 Certificate fingerprints : MD5 : 8F : 5D : 77 : 06 : 27 : C4 : 98 : 3C : 5B : 93 : 78 : E7 : D7 : 7D : 9B : CC SHA1 : 7E : 78 : 4A : 10 : 1C : 82 : 65 : CC : 2D : E1 : F1 : 6D : 47 : B4 : 40 : CA : D9 : 0A : 19 : 45 Signature algorithm name : MD5withRSA Version : 3 .... < / pre > Now import that into a Java keystore file : <pre > $ keytool - importcert - alias equifax - ca - file EquifaxSecureGlobaleBusinessCA - 1 . crt - keystore truststore_javanet . jks - storepass test1234 Owner : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Issuer : CN = Equifax Secure Global eBusiness CA - 1 O = Equifax Secure Inc . C = US Serial number : 1 Valid from : Mon Jun 21 00 : 00 : 00 EDT 1999 until : Sun Jun 21 00 : 00 : 00 EDT 2020 Certificate fingerprints : MD5 : 8F : 5D : 77 : 06 : 27 : C4 : 98 : 3C : 5B : 93 : 78 : E7 : D7 : 7D : 9B : CC SHA1 : 7E : 78 : 4A : 10 : 1C : 82 : 65 : CC : 2D : E1 : F1 : 6D : 47 : B4 : 40 : CA : D9 : 0A : 19 : 45 Signature algorithm name : MD5withRSA Version : 3 ... Trust this certificate? [ no ] : yes Certificate was added to keystore < / pre > Now you want to use this truststore in your client : <pre > RestAssured . trustStore ( / truststore_javanet . jks test1234 ) ; < / pre > or <pre > given () . trustStore ( / truststore_javanet . jks test1234 ) . .. < / pre > < / p > [CODESPLIT] public RequestSpecBuilder setTrustStore ( String pathToJks , String password ) { spec . trustStore ( pathToJks , password ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a header to be sent with the request e . g : [CODESPLIT] public RequestSpecBuilder addHeader ( String headerName , String headerValue ) { spec . header ( headerName , headerValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify an inputstream to upload to the server using multi - part form data . It will use the content - type <tt > application / octet - stream< / tt > . If this is not what you want please use an overloaded method . [CODESPLIT] public RequestSpecBuilder addMultiPart ( String controlName , String fileName , InputStream stream ) { spec . multiPart ( controlName , fileName , stream ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a string to send to the server using multi - part form data . It will use the content - type <tt > text / plain< / tt > . If this is not what you want please use an overloaded method . [CODESPLIT] public RequestSpecBuilder addMultiPart ( String controlName , String contentBody ) { spec . multiPart ( controlName , contentBody ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the session id name and value for this request . It ll override the default session id name from the configuration ( by default this is { @value SessionConfig#DEFAULT_SESSION_ID_NAME } ) . You can configure the default session id name by using : <pre > RestAssured . config = newConfig () . sessionConfig ( new SessionConfig () . sessionIdName ( &lt ; sessionIdName&gt ; )) ; < / pre > and then you can use the { @link RequestSpecBuilder#setSessionId ( String ) } method to set the session id value without specifying the name for each request . [CODESPLIT] public RequestSpecBuilder setSessionId ( String sessionIdName , String sessionIdValue ) { spec . sessionId ( sessionIdName , sessionIdValue ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge this builder with settings from another specification . Note that the supplied specification can overwrite data in the current specification . The following settings are overwritten : <ul > <li > Port< / li > <li > Authentication scheme< / <li > Content type< / li > <li > Request body< / li > < / ul > The following settings are merged : <ul > <li > Parameters< / li > <li > Cookies< / li > <li > Headers< / li > <li > Filters< / li > < / ul > [CODESPLIT] public RequestSpecBuilder addRequestSpecification ( RequestSpecification specification ) { if ( ! ( specification instanceof RequestSpecificationImpl ) ) { throw new IllegalArgumentException ( \"Specification must be of type \" + RequestSpecificationImpl . class . getClass ( ) + \".\" ) ; } RequestSpecificationImpl rs = ( RequestSpecificationImpl ) specification ; SpecificationMerger . merge ( ( RequestSpecificationImpl ) spec , rs ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enabled logging with the specified log detail . Set a { @link LogConfig } to configure the print stream and pretty printing options . [CODESPLIT] public RequestSpecBuilder log ( LogDetail logDetail ) { notNull ( logDetail , LogDetail . class ) ; RestAssuredConfig restAssuredConfig = spec . getConfig ( ) ; LogConfig logConfig ; if ( restAssuredConfig == null ) { logConfig = new RestAssuredConfig ( ) . getLogConfig ( ) ; } else { logConfig = restAssuredConfig . getLogConfig ( ) ; } PrintStream printStream = logConfig . defaultStream ( ) ; boolean prettyPrintingEnabled = logConfig . isPrettyPrintingEnabled ( ) ; boolean shouldUrlEncodeRequestUri = logConfig . shouldUrlEncodeRequestUri ( ) ; spec . filter ( new RequestLoggingFilter ( logDetail , prettyPrintingEnabled , printStream , shouldUrlEncodeRequestUri ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instruct REST Assured to connect to a proxy on the specified port on localhost with a specific scheme . [CODESPLIT] public RequestSpecBuilder setProxy ( String host , int port , String scheme ) { spec . proxy ( host , port , scheme ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set form parameter update strategy to the given value . [CODESPLIT] public MockMvcParamConfig formParamsUpdateStrategy ( UpdateStrategy updateStrategy ) { return new MockMvcParamConfig ( queryParamsUpdateStrategy , updateStrategy , requestParameterUpdateStrategy , attributeUpdateStrategy , sessionUpdateStrategy , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id playerId : my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( userId equalToPath ( playerId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > equalToPath ( final String path ) { return response -> equalTo ( response . path ( path ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href endsWithPath ( userId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > endsWithPath ( final String path ) { return response -> endsWith ( response . < String > path ( path ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id baseUri : http : // localhost : 8080 href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href startsWithPath ( baseUri )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > startsWithPath ( final String path ) { return response -> startsWith ( response . < String > path ( path ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResponseAwareMatcher } that extracts the given path from the response and wraps it in a { @link org . hamcrest . Matchers#equalTo ( Object ) } matcher . This is useful if you have a resource that e . g . returns the given JSON : <pre > { userId : my - id href : http : // localhost : 8080 / my - id } < / pre > you can then test it like this : <pre > get ( / x ) . then () . body ( href containsPath ( userId )) ; < / pre > [CODESPLIT] public static ResponseAwareMatcher < Response > containsPath ( final String path ) { return response -> containsString ( response . < String > path ( path ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new logging filter without using the new operator . Will make the DSL look nicer . [CODESPLIT] public static Filter logResponseToIfMatches ( PrintStream stream , Matcher < Integer > matcher ) { return new ResponseLoggingFilter ( stream , matcher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use a keystore located on the file - system . See { @link #keyStore ( String String ) } for more details . [CODESPLIT] public SSLConfig keyStore ( File pathToJks , String password ) { Validate . notNull ( pathToJks , \"Path to JKS on the file system cannot be null\" ) ; Validate . notEmpty ( password , \"Password cannot be empty\" ) ; return new SSLConfig ( pathToJks , pathToTrustStore , password , trustStorePassword , keyStoreType , trustStoreType , port , keyStore , trustStore , x509HostnameVerifier , sslSocketFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the user default keystore stored in &lt ; user . home&gt ; / . keystore [CODESPLIT] public SSLConfig keyStore ( String password ) { Validate . notEmpty ( password , \"Password cannot be empty\" ) ; return keyStore ( System . getProperty ( \"user.home\" ) + File . separatorChar + \".keystore\" , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The certificate type will use { @link java . security . KeyStore#getDefaultType () } by default . [CODESPLIT] public SSLConfig keystoreType ( String keystoreType ) { return new SSLConfig ( pathToKeyStore , pathToTrustStore , keyStorePassword , trustStorePassword , keystoreType , trustStoreType , port , keyStore , trustStore , x509HostnameVerifier , sslSocketFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use relaxed HTTP validation . This means that you ll trust all hosts regardless if the SSL certificate is invalid . By using this method you don t need to specify a keystore ( see { @link #keyStore ( String String ) } or trust store ( see { @link #trustStore ( java . security . KeyStore ) } . [CODESPLIT] public SSLConfig relaxedHTTPSValidation ( String protocol ) { AssertParameter . notNull ( protocol , \"Protocol\" ) ; SSLContext sslContext ; try { sslContext = SSLContext . getInstance ( protocol ) ; } catch ( NoSuchAlgorithmException e ) { return SafeExceptionRethrower . safeRethrow ( e ) ; } // Set up a TrustManager that trusts everything try { sslContext . init ( null , new TrustManager [ ] { new X509TrustManager ( ) { public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } public void checkClientTrusted ( X509Certificate [ ] certs , String authType ) { } public void checkServerTrusted ( X509Certificate [ ] certs , String authType ) { } } } , new SecureRandom ( ) ) ; } catch ( KeyManagementException e ) { return SafeExceptionRethrower . safeRethrow ( e ) ; } SSLSocketFactory sf = new SSLSocketFactory ( sslContext , ALLOW_ALL_HOSTNAME_VERIFIER ) ; return sslSocketFactory ( sf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a { @link org . apache . http . conn . ssl . SSLSocketFactory } . This will override settings from trust store as well as keystore and password . [CODESPLIT] public SSLConfig sslSocketFactory ( SSLSocketFactory sslSocketFactory ) { AssertParameter . notNull ( sslSocketFactory , SSLSocketFactory . class ) ; return new SSLConfig ( pathToKeyStore , pathToTrustStore , keyStorePassword , trustStorePassword , keyStoreType , trustStoreType , port , keyStore , trustStore , x509HostnameVerifier , sslSocketFactory , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a single cookie with the supplied name . If there are several cookies match the <code > cookieName< / code > then the first one is returned . [CODESPLIT] public Cookie get ( String cookieName ) { AssertParameter . notNull ( cookieName , \"Cookie name\" ) ; return cookies . get ( cookieName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a single cookie <i > value< / i > with the supplied name . If there are several cookies matching the <code > cookieName< / code > then the first one is returned . [CODESPLIT] public String getValue ( String cookieName ) { AssertParameter . notNull ( cookieName , \"Cookie name\" ) ; return cookies . getValue ( cookieName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An alternative way to create a Cookies object from the constructor . [CODESPLIT] public static Cookies cookies ( Cookie cookie , Cookie ... additionalCookies ) { AssertParameter . notNull ( cookie , \"Cookie\" ) ; final List < Cookie > cookieList = new LinkedList < Cookie > ( ) ; cookieList . add ( cookie ) ; Collections . addAll ( cookieList , additionalCookies ) ; return new Cookies ( cookieList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a provider which looks up objects in JNDI using the given name . Example usage : [CODESPLIT] public static < T > Provider < T > fromJndi ( Class < T > type , String name ) { return new JndiProvider < T > ( type , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There may be multiple child injectors blacklisting a certain key so only remove the source that s relevant . [CODESPLIT] private void cleanUpForCollectedState ( Set < KeyAndSource > keysAndSources ) { synchronized ( lock ) { for ( KeyAndSource keyAndSource : keysAndSources ) { Multiset < Object > set = backingMap . get ( keyAndSource . key ) ; if ( set != null ) { set . remove ( keyAndSource . source ) ; if ( set . isEmpty ( ) ) { backingMap . remove ( keyAndSource . key ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indexes bindings by type . [CODESPLIT] void index ( ) { for ( Binding < ? > binding : state . getExplicitBindingsThisLevel ( ) . values ( ) ) { bindingsMultimap . put ( binding . getKey ( ) . getTypeLiteral ( ) , binding ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the binding for { [CODESPLIT] @ Override public < T > BindingImpl < T > getBinding ( Key < T > key ) { Errors errors = new Errors ( checkNotNull ( key , \"key\" ) ) ; try { BindingImpl < T > result = getBindingOrThrow ( key , errors , JitLimitation . EXISTING_JIT ) ; errors . throwConfigurationExceptionIfErrorsExist ( ) ; return result ; } catch ( ErrorsException e ) { throw new ConfigurationException ( errors . merge ( e . getErrors ( ) ) . getMessages ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a binding implementation . First it check to see if the parent has a binding . If the parent has a binding and the binding is scoped it will use that binding . Otherwise this checks for an explicit binding . If no explicit binding is found it looks for a just - in - time binding . [CODESPLIT] < T > BindingImpl < T > getBindingOrThrow ( Key < T > key , Errors errors , JitLimitation jitType ) throws ErrorsException { // Check explicit bindings, i.e. bindings created by modules. BindingImpl < T > binding = state . getExplicitBinding ( key ) ; if ( binding != null ) { return binding ; } // Look for an on-demand binding. return getJustInTimeBinding ( key , errors , jitType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a just - in - time binding for { @code key } creating it if necessary . [CODESPLIT] private < T > BindingImpl < T > getJustInTimeBinding ( Key < T > key , Errors errors , JitLimitation jitType ) throws ErrorsException { boolean jitOverride = isProvider ( key ) || isTypeLiteral ( key ) || isMembersInjector ( key ) ; synchronized ( state . lock ( ) ) { // first try to find a JIT binding that we've already created for ( InjectorImpl injector = this ; injector != null ; injector = injector . parent ) { @ SuppressWarnings ( \"unchecked\" ) // we only store bindings that match their key BindingImpl < T > binding = ( BindingImpl < T > ) injector . jitBindings . get ( key ) ; if ( binding != null ) { // If we found a JIT binding and we don't allow them, // fail.  (But allow bindings created through TypeConverters.) if ( options . jitDisabled && jitType == JitLimitation . NO_JIT && ! jitOverride && ! ( binding instanceof ConvertedConstantBindingImpl ) ) { throw errors . jitDisabled ( key ) . toException ( ) ; } else { return binding ; } } } // If we previously failed creating this JIT binding and our Errors has // already recorded an error, then just directly throw that error. // We need to do this because it's possible we already cleaned up the // entry in jitBindings (during cleanup), and we may be trying // to create it again (in the case of a recursive JIT binding). // We need both of these guards for different reasons // failedJitBindings.contains: We want to continue processing if we've never //   failed before, so that our initial error message contains //   as much useful information as possible about what errors exist. // errors.hasErrors: If we haven't already failed, then it's OK to //   continue processing, to make sure the ultimate error message //   is the correct one. // See: ImplicitBindingsTest#testRecursiveJitBindingsCleanupCorrectly // for where this guard compes into play. if ( failedJitBindings . contains ( key ) && errors . hasErrors ( ) ) { throw errors . toException ( ) ; } return createJustInTimeBindingRecursive ( key , errors , options . jitDisabled , jitType ) ; } // end synchronized(state.lock()) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the key type is MembersInjector ( but not a subclass of MembersInjector ) . [CODESPLIT] private static boolean isMembersInjector ( Key < ? > key ) { return key . getTypeLiteral ( ) . getRawType ( ) . equals ( MembersInjector . class ) && key . getAnnotationType ( ) == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a synthetic binding to { [CODESPLIT] private < T > BindingImpl < Provider < T > > createProviderBinding ( Key < Provider < T > > key , Errors errors ) throws ErrorsException { Key < T > providedKey = getProvidedKey ( key , errors ) ; BindingImpl < T > delegate = getBindingOrThrow ( providedKey , errors , JitLimitation . NO_JIT ) ; return new ProviderBindingImpl < T > ( this , key , delegate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a constant string binding to the required type . [CODESPLIT] private < T > BindingImpl < T > convertConstantStringBinding ( Key < T > key , Errors errors ) throws ErrorsException { // Find a constant string binding. Key < String > stringKey = key . ofType ( STRING_TYPE ) ; BindingImpl < String > stringBinding = state . getExplicitBinding ( stringKey ) ; if ( stringBinding == null || ! stringBinding . isConstant ( ) ) { return null ; } // We can't call getProvider().get() because this InstanceBinding may not have been inintialized // yet (because we may have been called during InternalInjectorCreator.initializeStatically and // instance binding validation hasn't happened yet.) @ SuppressWarnings ( \"unchecked\" ) String stringValue = ( ( InstanceBinding < String > ) stringBinding ) . getInstance ( ) ; Object source = stringBinding . getSource ( ) ; // Find a matching type converter. TypeLiteral < T > type = key . getTypeLiteral ( ) ; TypeConverterBinding typeConverterBinding = state . getConverter ( stringValue , type , errors , source ) ; if ( typeConverterBinding == null ) { // No converter can handle the given type. return null ; } // Try to convert the string. A failed conversion results in an error. try { @ SuppressWarnings ( \"unchecked\" ) // This cast is safe because we double check below. T converted = ( T ) typeConverterBinding . getTypeConverter ( ) . convert ( stringValue , type ) ; if ( converted == null ) { throw errors . converterReturnedNull ( stringValue , source , type , typeConverterBinding ) . toException ( ) ; } if ( ! type . getRawType ( ) . isInstance ( converted ) ) { throw errors . conversionTypeError ( stringValue , source , type , typeConverterBinding , converted ) . toException ( ) ; } return new ConvertedConstantBindingImpl < T > ( this , key , converted , stringBinding , typeConverterBinding ) ; } catch ( ErrorsException e ) { throw e ; } catch ( RuntimeException e ) { throw errors . conversionError ( stringValue , source , type , typeConverterBinding , e ) . toException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through the binding s dependencies to clean up any stray bindings that were leftover from a failed JIT binding . This is required because the bindings are eagerly & optimistically added to allow circular dependency support so dependencies may pass where they should have failed . [CODESPLIT] private boolean cleanup ( BindingImpl < ? > binding , Set < Key > encountered ) { boolean bindingFailed = false ; Set < Dependency < ? > > deps = getInternalDependencies ( binding ) ; for ( Dependency dep : deps ) { Key < ? > depKey = dep . getKey ( ) ; InjectionPoint ip = dep . getInjectionPoint ( ) ; if ( encountered . add ( depKey ) ) { // only check if we haven't looked at this key yet BindingImpl depBinding = jitBindings . get ( depKey ) ; if ( depBinding != null ) { // if the binding still exists, validate boolean failed = cleanup ( depBinding , encountered ) ; // if children fail, we fail if ( depBinding instanceof ConstructorBindingImpl ) { ConstructorBindingImpl ctorBinding = ( ConstructorBindingImpl ) depBinding ; ip = ctorBinding . getInternalConstructor ( ) ; if ( ! ctorBinding . isInitialized ( ) ) { failed = true ; } } if ( failed ) { removeFailedJitBinding ( depBinding , ip ) ; bindingFailed = true ; } } else if ( state . getExplicitBinding ( depKey ) == null ) { // ignore keys if they were explicitly bound, but if neither JIT // nor explicit, it's also invalid & should let parent know. bindingFailed = true ; } } } return bindingFailed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans up any state that may have been cached when constructing the JIT binding . [CODESPLIT] private void removeFailedJitBinding ( Binding < ? > binding , InjectionPoint ip ) { failedJitBindings . add ( binding . getKey ( ) ) ; jitBindings . remove ( binding . getKey ( ) ) ; membersInjectorStore . remove ( binding . getKey ( ) . getTypeLiteral ( ) ) ; provisionListenerStore . remove ( binding ) ; if ( ip != null ) { constructors . remove ( ip ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safely gets the dependencies of possibly not initialized bindings . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private Set < Dependency < ? > > getInternalDependencies ( BindingImpl < ? > binding ) { if ( binding instanceof ConstructorBindingImpl ) { return ( ( ConstructorBindingImpl ) binding ) . getInternalDependencies ( ) ; } else if ( binding instanceof HasDependencies ) { return ( ( HasDependencies ) binding ) . getDependencies ( ) ; } else { return ImmutableSet . of ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a binding for an injectable type with the given scope . Looks for a scope on the type if none is specified . [CODESPLIT] < T > BindingImpl < T > createUninitializedBinding ( Key < T > key , Scoping scoping , Object source , Errors errors , boolean jitBinding ) throws ErrorsException { Class < ? > rawType = key . getTypeLiteral ( ) . getRawType ( ) ; ImplementedBy implementedBy = rawType . getAnnotation ( ImplementedBy . class ) ; // Don't try to inject arrays or enums annotated with @ImplementedBy. if ( rawType . isArray ( ) || ( rawType . isEnum ( ) && implementedBy != null ) ) { throw errors . missingImplementationWithHint ( key , this ) . toException ( ) ; } // Handle TypeLiteral<T> by binding the inner type if ( rawType == TypeLiteral . class ) { @ SuppressWarnings ( \"unchecked\" ) // we have to fudge the inner type as Object BindingImpl < T > binding = ( BindingImpl < T > ) createTypeLiteralBinding ( ( Key < TypeLiteral < Object > > ) key , errors ) ; return binding ; } // Handle @ImplementedBy if ( implementedBy != null ) { Annotations . checkForMisplacedScopeAnnotations ( rawType , source , errors ) ; return createImplementedByBinding ( key , scoping , implementedBy , errors ) ; } // Handle @ProvidedBy. ProvidedBy providedBy = rawType . getAnnotation ( ProvidedBy . class ) ; if ( providedBy != null ) { Annotations . checkForMisplacedScopeAnnotations ( rawType , source , errors ) ; return createProvidedByBinding ( key , scoping , providedBy , errors ) ; } return ConstructorBindingImpl . create ( this , key , null , /* use default constructor */ source , scoping , errors , jitBinding && options . jitDisabled , options . atInjectRequired ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a binding for a { [CODESPLIT] private < T > BindingImpl < TypeLiteral < T > > createTypeLiteralBinding ( Key < TypeLiteral < T > > key , Errors errors ) throws ErrorsException { Type typeLiteralType = key . getTypeLiteral ( ) . getType ( ) ; if ( ! ( typeLiteralType instanceof ParameterizedType ) ) { throw errors . cannotInjectRawTypeLiteral ( ) . toException ( ) ; } ParameterizedType parameterizedType = ( ParameterizedType ) typeLiteralType ; Type innerType = parameterizedType . getActualTypeArguments ( ) [ 0 ] ; // this is unforunate. We don't support building TypeLiterals for type variable like 'T'. If // this proves problematic, we can probably fix TypeLiteral to support type variables if ( ! ( innerType instanceof Class ) && ! ( innerType instanceof GenericArrayType ) && ! ( innerType instanceof ParameterizedType ) ) { throw errors . cannotInjectTypeLiteralOf ( innerType ) . toException ( ) ; } @ SuppressWarnings ( \"unchecked\" ) // by definition, innerType == T, so this is safe TypeLiteral < T > value = ( TypeLiteral < T > ) TypeLiteral . get ( innerType ) ; InternalFactory < TypeLiteral < T > > factory = new ConstantFactory < TypeLiteral < T > > ( Initializables . of ( value ) ) ; return new InstanceBindingImpl < TypeLiteral < T > > ( this , key , SourceProvider . UNKNOWN_SOURCE , factory , ImmutableSet . < InjectionPoint > of ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a binding for a type annotated with [CODESPLIT] < T > BindingImpl < T > createProvidedByBinding ( Key < T > key , Scoping scoping , ProvidedBy providedBy , Errors errors ) throws ErrorsException { Class < ? > rawType = key . getTypeLiteral ( ) . getRawType ( ) ; Class < ? extends javax . inject . Provider < ? > > providerType = providedBy . value ( ) ; // Make sure it's not the same type. TODO: Can we check for deeper loops? if ( providerType == rawType ) { throw errors . recursiveProviderType ( ) . toException ( ) ; } // Assume the provider provides an appropriate type. We double check at runtime. @ SuppressWarnings ( \"unchecked\" ) Key < ? extends Provider < T > > providerKey = ( Key < ? extends Provider < T > > ) Key . get ( providerType ) ; ProvidedByInternalFactory < T > internalFactory = new ProvidedByInternalFactory < T > ( rawType , providerType , providerKey ) ; Object source = rawType ; BindingImpl < T > binding = LinkedProviderBindingImpl . createWithInitializer ( this , key , source , Scoping . < T > scope ( key , this , internalFactory , source , scoping ) , scoping , providerKey , internalFactory ) ; internalFactory . setProvisionListenerCallback ( provisionListenerStore . get ( binding ) ) ; return binding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a binding for a type annotated with [CODESPLIT] private < T > BindingImpl < T > createImplementedByBinding ( Key < T > key , Scoping scoping , ImplementedBy implementedBy , Errors errors ) throws ErrorsException { Class < ? > rawType = key . getTypeLiteral ( ) . getRawType ( ) ; Class < ? > implementationType = implementedBy . value ( ) ; // Make sure it's not the same type. TODO: Can we check for deeper cycles? if ( implementationType == rawType ) { throw errors . recursiveImplementationType ( ) . toException ( ) ; } // Make sure implementationType extends type. if ( ! rawType . isAssignableFrom ( implementationType ) ) { throw errors . notASubtype ( implementationType , rawType ) . toException ( ) ; } @ SuppressWarnings ( \"unchecked\" ) // After the preceding check, this cast is safe. Class < ? extends T > subclass = ( Class < ? extends T > ) implementationType ; // Look up the target binding. final Key < ? extends T > targetKey = Key . get ( subclass ) ; Object source = rawType ; FactoryProxy < T > factory = new FactoryProxy <> ( this , key , targetKey , source ) ; factory . notify ( errors ) ; // causes the factory to initialize itself internally return new LinkedBindingImpl < T > ( this , key , source , Scoping . < T > scope ( key , this , factory , source , scoping ) , scoping , targetKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to create a just - in - time binding for { [CODESPLIT] private < T > BindingImpl < T > createJustInTimeBindingRecursive ( Key < T > key , Errors errors , boolean jitDisabled , JitLimitation jitType ) throws ErrorsException { // ask the parent to create the JIT binding if ( parent != null ) { if ( jitType == JitLimitation . NEW_OR_EXISTING_JIT && jitDisabled && ! parent . options . jitDisabled ) { // If the binding would be forbidden here but allowed in a parent, report an error instead throw errors . jitDisabledInParent ( key ) . toException ( ) ; } try { return parent . createJustInTimeBindingRecursive ( key , new Errors ( ) , jitDisabled , parent . options . jitDisabled ? JitLimitation . NO_JIT : jitType ) ; } catch ( ErrorsException ignored ) { } } // Retrieve the sources before checking for blacklisting to guard against sources becoming null // due to a full GC happening after calling state.isBlacklisted and // state.getSourcesForBlacklistedKey. // TODO(user): Consolidate these two APIs. Set < Object > sources = state . getSourcesForBlacklistedKey ( key ) ; if ( state . isBlacklisted ( key ) ) { throw errors . childBindingAlreadySet ( key , sources ) . toException ( ) ; } key = MoreTypes . canonicalizeKey ( key ) ; // before storing the key long-term, canonicalize it. BindingImpl < T > binding = createJustInTimeBinding ( key , errors , jitDisabled , jitType ) ; state . parent ( ) . blacklist ( key , state , binding . getSource ( ) ) ; jitBindings . put ( key , binding ) ; return binding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new just - in - time binding created by resolving { @code key } . The strategies used to create just - in - time bindings are : [CODESPLIT] private < T > BindingImpl < T > createJustInTimeBinding ( Key < T > key , Errors errors , boolean jitDisabled , JitLimitation jitType ) throws ErrorsException { int numErrorsBefore = errors . size ( ) ; // Retrieve the sources before checking for blacklisting to guard against sources becoming null // due to a full GC happening after calling state.isBlacklisted and // state.getSourcesForBlacklistedKey. // TODO(user): Consolidate these two APIs. Set < Object > sources = state . getSourcesForBlacklistedKey ( key ) ; if ( state . isBlacklisted ( key ) ) { throw errors . childBindingAlreadySet ( key , sources ) . toException ( ) ; } // Handle cases where T is a Provider<?>. if ( isProvider ( key ) ) { // These casts are safe. We know T extends Provider<X> and that given Key<Provider<X>>, // createProviderBinding() will return BindingImpl<Provider<X>>. @ SuppressWarnings ( { \"unchecked\" , \"cast\" } ) BindingImpl < T > binding = ( BindingImpl < T > ) createProviderBinding ( ( Key ) key , errors ) ; return binding ; } // Handle cases where T is a MembersInjector<?> if ( isMembersInjector ( key ) ) { // These casts are safe. T extends MembersInjector<X> and that given Key<MembersInjector<X>>, // createMembersInjectorBinding() will return BindingImpl<MembersInjector<X>>. @ SuppressWarnings ( { \"unchecked\" , \"cast\" } ) BindingImpl < T > binding = ( BindingImpl < T > ) createMembersInjectorBinding ( ( Key ) key , errors ) ; return binding ; } // Try to convert a constant string binding to the requested type. BindingImpl < T > convertedBinding = convertConstantStringBinding ( key , errors ) ; if ( convertedBinding != null ) { return convertedBinding ; } if ( ! isTypeLiteral ( key ) && jitDisabled && jitType != JitLimitation . NEW_OR_EXISTING_JIT ) { throw errors . jitDisabled ( key ) . toException ( ) ; } // If the key has an annotation... if ( key . getAnnotationType ( ) != null ) { // Look for a binding without annotation attributes or return null. if ( key . hasAttributes ( ) && ! options . exactBindingAnnotationsRequired ) { try { Errors ignored = new Errors ( ) ; return getBindingOrThrow ( key . withoutAttributes ( ) , ignored , JitLimitation . NO_JIT ) ; } catch ( ErrorsException ignored ) { // throw with a more appropriate message below } } throw errors . missingImplementationWithHint ( key , this ) . toException ( ) ; } Object source = key . getTypeLiteral ( ) . getRawType ( ) ; BindingImpl < T > binding = createUninitializedBinding ( key , Scoping . UNSCOPED , source , errors , true ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; initializeJitBinding ( binding , errors ) ; return binding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns parameter injectors or { [CODESPLIT] SingleParameterInjector < ? > [ ] getParametersInjectors ( List < Dependency < ? > > parameters , Errors errors ) throws ErrorsException { if ( parameters . isEmpty ( ) ) { return null ; } int numErrorsBefore = errors . size ( ) ; SingleParameterInjector < ? > [ ] result = new SingleParameterInjector < ? > [ parameters . size ( ) ] ; int i = 0 ; for ( Dependency < ? > parameter : parameters ) { try { result [ i ++ ] = createParameterInjector ( parameter , errors . withSource ( parameter ) ) ; } catch ( ErrorsException rethrownBelow ) { // rethrown below } } errors . throwIfNewErrors ( numErrorsBefore ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up thread local context and { @link InternalContext#enter () enters } it or creates a new context if necessary . [CODESPLIT] InternalContext enterContext ( ) { Object [ ] reference = localContext . get ( ) ; if ( reference == null ) { reference = new Object [ 1 ] ; localContext . set ( reference ) ; } InternalContext ctx = ( InternalContext ) reference [ 0 ] ; if ( ctx == null ) { reference [ 0 ] = ctx = new InternalContext ( options , reference ) ; } else { ctx . enter ( ) ; } return ctx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of parameter values . [CODESPLIT] static Object [ ] getAll ( InternalContext context , SingleParameterInjector < ? > [ ] parameterInjectors ) throws InternalProvisionException { if ( parameterInjectors == null ) { return NO_ARGUMENTS ; } int size = parameterInjectors . length ; Object [ ] parameters = new Object [ size ] ; // optimization: use manual for/each to save allocating an iterator here for ( int i = 0 ; i < size ; i ++ ) { parameters [ i ] = parameterInjectors [ i ] . inject ( context ) ; } return parameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the label for a node . This is a string of HTML that defines a table with a heading at the top and ( in the case of { [CODESPLIT] protected String getNodeLabel ( GraphvizNode node ) { String cellborder = node . getStyle ( ) == NodeStyle . INVISIBLE ? \"1\" : \"0\" ; StringBuilder html = new StringBuilder ( ) ; html . append ( \"<\" ) ; html . append ( \"<table cellspacing=\\\"0\\\" cellpadding=\\\"5\\\" cellborder=\\\"\" ) ; html . append ( cellborder ) . append ( \"\\\" border=\\\"0\\\">\" ) ; html . append ( \"<tr>\" ) . append ( \"<td align=\\\"left\\\" port=\\\"header\\\" \" ) ; html . append ( \"bgcolor=\\\"\" + node . getHeaderBackgroundColor ( ) + \"\\\">\" ) ; String subtitle = Joiner . on ( \"<br align=\\\"left\\\"/>\" ) . join ( node . getSubtitles ( ) ) ; if ( subtitle . length ( ) != 0 ) { html . append ( \"<font color=\\\"\" ) . append ( node . getHeaderTextColor ( ) ) ; html . append ( \"\\\" point-size=\\\"10\\\">\" ) ; html . append ( subtitle ) . append ( \"<br align=\\\"left\\\"/>\" ) . append ( \"</font>\" ) ; } html . append ( \"<font color=\\\"\" + node . getHeaderTextColor ( ) + \"\\\">\" ) ; html . append ( htmlEscape ( node . getTitle ( ) ) ) . append ( \"<br align=\\\"left\\\"/>\" ) ; html . append ( \"</font>\" ) . append ( \"</td>\" ) . append ( \"</tr>\" ) ; for ( Map . Entry < String , String > field : node . getFields ( ) . entrySet ( ) ) { html . append ( \"<tr>\" ) ; html . append ( \"<td align=\\\"left\\\" port=\\\"\" ) . append ( htmlEscape ( field . getKey ( ) ) ) . append ( \"\\\">\" ) ; html . append ( htmlEscape ( field . getValue ( ) ) ) ; html . append ( \"</td>\" ) . append ( \"</tr>\" ) ; } html . append ( \"</table>\" ) ; html . append ( \">\" ) ; return html . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new multibinder that collects instances of the key s type in a { @link Set } that is itself bound with the annotation ( if any ) of the key . [CODESPLIT] public static < T > Multibinder < T > newSetBinder ( Binder binder , Key < T > key ) { return new Multibinder < T > ( newRealSetBinder ( binder . skipSources ( Multibinder . class ) , key ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new multibinder that collects instances of { [CODESPLIT] public static < T > Multibinder < T > newSetBinder ( Binder binder , Class < T > type , Class < ? extends Annotation > annotationType ) { return newSetBinder ( binder , Key . get ( type , annotationType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See the factory configuration examples at { [CODESPLIT] public < T > FactoryModuleBuilder implement ( Class < T > source , Class < ? extends T > target ) { return implement ( source , TypeLiteral . get ( target ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See the factory configuration examples at { [CODESPLIT] public < F > Module build ( Class < F > factoryInterface ) { return build ( TypeLiteral . get ( factoryInterface ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See the factory configuration examples at { [CODESPLIT] public < F > Module build ( TypeLiteral < F > factoryInterface ) { return build ( Key . get ( factoryInterface ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Injector is a special case because we allow both parent and child injectors to both have a binding for that key . [CODESPLIT] private static void bindInjector ( InjectorImpl injector ) { Key < Injector > key = Key . get ( Injector . class ) ; InjectorFactory injectorFactory = new InjectorFactory ( injector ) ; injector . state . putBinding ( key , new ProviderInstanceBindingImpl < Injector > ( injector , key , SourceProvider . UNKNOWN_SOURCE , injectorFactory , Scoping . UNSCOPED , injectorFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Logger is a special case because it knows the injection point of the injected member . It s the only binding that does this . [CODESPLIT] private static void bindLogger ( InjectorImpl injector ) { Key < Logger > key = Key . get ( Logger . class ) ; LoggerFactory loggerFactory = new LoggerFactory ( ) ; injector . state . putBinding ( key , new ProviderInstanceBindingImpl < Logger > ( injector , key , SourceProvider . UNKNOWN_SOURCE , loggerFactory , Scoping . UNSCOPED , loggerFactory , ImmutableSet . < InjectionPoint > of ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This metohd is necessary to create a Dependency<T > with proper generic type information [CODESPLIT] private < T > Dependency < T > newDependency ( Key < T > key , boolean allowsNull , int parameterIndex ) { return new Dependency < T > ( this , key , allowsNull , parameterIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new injection point for the specified constructor . If the declaring type of { @code constructor } is parameterized ( such as { @code List<T > } ) prefer the overload that includes a type literal . [CODESPLIT] public static < T > InjectionPoint forConstructor ( Constructor < T > constructor ) { return new InjectionPoint ( TypeLiteral . get ( constructor . getDeclaringClass ( ) ) , constructor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new injection point for the specified constructor of { @code type } . [CODESPLIT] public static < T > InjectionPoint forConstructor ( Constructor < T > constructor , TypeLiteral < ? extends T > type ) { if ( type . getRawType ( ) != constructor . getDeclaringClass ( ) ) { new Errors ( type ) . constructorNotDefinedByType ( constructor , type ) . throwConfigurationExceptionIfErrorsExist ( ) ; } return new InjectionPoint ( type , constructor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new injection point for the injectable constructor of { @code type } . [CODESPLIT] public static InjectionPoint forConstructorOf ( TypeLiteral < ? > type ) { Class < ? > rawType = getRawType ( type . getType ( ) ) ; Errors errors = new Errors ( rawType ) ; Constructor < ? > injectableConstructor = null ; for ( Constructor < ? > constructor : rawType . getDeclaredConstructors ( ) ) { boolean optional ; Inject guiceInject = constructor . getAnnotation ( Inject . class ) ; if ( guiceInject == null ) { javax . inject . Inject javaxInject = constructor . getAnnotation ( javax . inject . Inject . class ) ; if ( javaxInject == null ) { continue ; } optional = false ; } else { optional = guiceInject . optional ( ) ; } if ( optional ) { errors . optionalConstructor ( constructor ) ; } if ( injectableConstructor != null ) { errors . tooManyConstructors ( rawType ) ; } injectableConstructor = constructor ; checkForMisplacedBindingAnnotations ( injectableConstructor , errors ) ; } errors . throwConfigurationExceptionIfErrorsExist ( ) ; if ( injectableConstructor != null ) { return new InjectionPoint ( type , injectableConstructor ) ; } // If no annotated constructor is found, look for a no-arg constructor instead. try { Constructor < ? > noArgConstructor = rawType . getDeclaredConstructor ( ) ; // Disallow private constructors on non-private classes (unless they have @Inject) if ( Modifier . isPrivate ( noArgConstructor . getModifiers ( ) ) && ! Modifier . isPrivate ( rawType . getModifiers ( ) ) ) { errors . missingConstructor ( rawType ) ; throw new ConfigurationException ( errors . getMessages ( ) ) ; } checkForMisplacedBindingAnnotations ( noArgConstructor , errors ) ; return new InjectionPoint ( type , noArgConstructor ) ; } catch ( NoSuchMethodException e ) { errors . missingConstructor ( rawType ) ; throw new ConfigurationException ( errors . getMessages ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new injection point for the specified method of { @code type } . This is useful for extensions that need to build dependency graphs from arbitrary methods . [CODESPLIT] public static < T > InjectionPoint forMethod ( Method method , TypeLiteral < T > type ) { return new InjectionPoint ( type , method , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all static method and field injection points on { @code type } . [CODESPLIT] public static Set < InjectionPoint > forStaticMethodsAndFields ( TypeLiteral < ? > type ) { Errors errors = new Errors ( ) ; Set < InjectionPoint > result ; if ( type . getRawType ( ) . isInterface ( ) ) { errors . staticInjectionOnInterface ( type . getRawType ( ) ) ; result = null ; } else { result = getInjectionPoints ( type , true , errors ) ; } if ( errors . hasErrors ( ) ) { throw new ConfigurationException ( errors . getMessages ( ) ) . withPartialValue ( result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all instance method and field injection points on { @code type } . [CODESPLIT] public static Set < InjectionPoint > forInstanceMethodsAndFields ( TypeLiteral < ? > type ) { Errors errors = new Errors ( ) ; Set < InjectionPoint > result = getInjectionPoints ( type , false , errors ) ; if ( errors . hasErrors ( ) ) { throw new ConfigurationException ( errors . getMessages ( ) ) . withPartialValue ( result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the binding annotation is in the wrong place . [CODESPLIT] private static boolean checkForMisplacedBindingAnnotations ( Member member , Errors errors ) { Annotation misplacedBindingAnnotation = Annotations . findBindingAnnotation ( errors , member , ( ( AnnotatedElement ) member ) . getAnnotations ( ) ) ; if ( misplacedBindingAnnotation == null ) { return false ; } // don't warn about misplaced binding annotations on methods when there's a field with the same // name. In Scala, fields always get accessor methods (that we need to ignore). See bug 242. if ( member instanceof Method ) { try { if ( member . getDeclaringClass ( ) . getDeclaredField ( member . getName ( ) ) != null ) { return false ; } } catch ( NoSuchFieldException ignore ) { } } errors . misplacedBindingAnnotation ( member , misplacedBindingAnnotation ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an ordered immutable set of injection points for the given type . Members in superclasses come before members in subclasses . Within a class fields come before methods . Overridden methods are filtered out . The order of fields / methods within a class is consistent but undefined . [CODESPLIT] private static Set < InjectionPoint > getInjectionPoints ( final TypeLiteral < ? > type , boolean statics , Errors errors ) { InjectableMembers injectableMembers = new InjectableMembers ( ) ; OverrideIndex overrideIndex = null ; List < TypeLiteral < ? > > hierarchy = hierarchyFor ( type ) ; int topIndex = hierarchy . size ( ) - 1 ; for ( int i = topIndex ; i >= 0 ; i -- ) { if ( overrideIndex != null && i < topIndex ) { // Knowing the position within the hierarchy helps us make optimizations. if ( i == 0 ) { overrideIndex . position = Position . BOTTOM ; } else { overrideIndex . position = Position . MIDDLE ; } } TypeLiteral < ? > current = hierarchy . get ( i ) ; for ( Field field : getDeclaredFields ( current ) ) { if ( Modifier . isStatic ( field . getModifiers ( ) ) == statics ) { Annotation atInject = getAtInject ( field ) ; if ( atInject != null ) { InjectableField injectableField = new InjectableField ( current , field , atInject ) ; if ( injectableField . jsr330 && Modifier . isFinal ( field . getModifiers ( ) ) ) { errors . cannotInjectFinalField ( field ) ; } injectableMembers . add ( injectableField ) ; } } } for ( Method method : getDeclaredMethods ( current ) ) { if ( isEligibleForInjection ( method , statics ) ) { Annotation atInject = getAtInject ( method ) ; if ( atInject != null ) { InjectableMethod injectableMethod = new InjectableMethod ( current , method , atInject ) ; if ( checkForMisplacedBindingAnnotations ( method , errors ) || ! isValidMethod ( injectableMethod , errors ) ) { if ( overrideIndex != null ) { boolean removed = overrideIndex . removeIfOverriddenBy ( method , false , injectableMethod ) ; if ( removed ) { logger . log ( Level . WARNING , \"Method: {0} is not a valid injectable method (\" + \"because it either has misplaced binding annotations \" + \"or specifies type parameters) but is overriding a method that is \" + \"valid. Because it is not valid, the method will not be injected. \" + \"To fix this, make the method a valid injectable method.\" , method ) ; } } continue ; } if ( statics ) { injectableMembers . add ( injectableMethod ) ; } else { if ( overrideIndex == null ) { /*\n                 * Creating the override index lazily means that the first type in the hierarchy\n                 * with injectable methods (not necessarily the top most type) will be treated as\n                 * the TOP position and will enjoy the same optimizations (no checks for overridden\n                 * methods, etc.).\n                 */ overrideIndex = new OverrideIndex ( injectableMembers ) ; } else { // Forcibly remove the overridden method, otherwise we'll inject // it twice. overrideIndex . removeIfOverriddenBy ( method , true , injectableMethod ) ; } overrideIndex . add ( injectableMethod ) ; } } else { if ( overrideIndex != null ) { boolean removed = overrideIndex . removeIfOverriddenBy ( method , false , null ) ; if ( removed ) { logger . log ( Level . WARNING , \"Method: {0} is not annotated with @Inject but \" + \"is overriding a method that is annotated with @javax.inject.Inject.\" + \"Because it is not annotated with @Inject, the method will not be \" + \"injected. To fix this, annotate the method with @Inject.\" , method ) ; } } } } } } if ( injectableMembers . isEmpty ( ) ) { return Collections . emptySet ( ) ; } ImmutableSet . Builder < InjectionPoint > builder = ImmutableSet . builder ( ) ; for ( InjectableMember im = injectableMembers . head ; im != null ; im = im . next ) { try { builder . add ( im . toInjectionPoint ( ) ) ; } catch ( ConfigurationException ignorable ) { if ( ! im . optional ) { errors . merge ( ignorable . getErrorMessages ( ) ) ; } } } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the method is eligible to be injected . This is different than { @link #isValidMethod } because ineligibility will not drop a method from being injected if a superclass was eligible & valid . Bridge & synthetic methods are excluded from eligibility for two reasons : [CODESPLIT] private static boolean isEligibleForInjection ( Method method , boolean statics ) { return Modifier . isStatic ( method . getModifiers ( ) ) == statics && ! method . isBridge ( ) && ! method . isSynthetic ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if a overrides b . Assumes signatures of a and b are the same and a s declaring class is a subclass of b s declaring class . [CODESPLIT] private static boolean overrides ( Method a , Method b ) { // See JLS section 8.4.8.1 int modifiers = b . getModifiers ( ) ; if ( Modifier . isPublic ( modifiers ) || Modifier . isProtected ( modifiers ) ) { return true ; } if ( Modifier . isPrivate ( modifiers ) ) { return false ; } // b must be package-private return a . getDeclaringClass ( ) . getPackage ( ) . equals ( b . getDeclaringClass ( ) . getPackage ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the actual members injector . [CODESPLIT] public void initializeDelegate ( MembersInjector < T > delegate ) { checkState ( this . delegate == null , \"delegate already initialized\" ) ; this . delegate = checkNotNull ( delegate , \"delegate\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the looked up members injector . The result is not valid until this lookup has been initialized which usually happens when the injector is created . The members injector will throw an { [CODESPLIT] public MembersInjector < T > getMembersInjector ( ) { return new MembersInjector < T > ( ) { @ Override public void injectMembers ( T instance ) { MembersInjector < T > local = delegate ; if ( local == null ) { throw new IllegalStateException ( \"This MembersInjector cannot be used until the Injector has been created.\" ) ; } local . injectMembers ( instance ) ; } @ Override public String toString ( ) { return \"MembersInjector<\" + type + \">\" ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link CheckedProvider } which always provides { @code instance } . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P of ( TypeLiteral < P > providerType , @ Nullable T instance ) { return generateProvider ( providerType , Optional . fromNullable ( instance ) , new ReturningHandler < T > ( instance ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link CheckedProvider } which always provides { @code instance } . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P of ( Class < P > providerType , @ Nullable T instance ) { return of ( TypeLiteral . get ( providerType ) , instance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link CheckedProvider } which always throws exceptions . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P throwing ( TypeLiteral < P > providerType , Class < ? extends Throwable > throwable ) { // TODO(eatnumber1): Understand why TypeLiteral#getRawType returns a Class<? super T> rather // than a Class<T> and remove this unsafe cast. Class < P > providerRaw = ( Class ) providerType . getRawType ( ) ; checkThrowable ( providerRaw , throwable ) ; return generateProvider ( providerType , Optional . < T > absent ( ) , ThrowingHandler . forClass ( throwable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link CheckedProvider } which always throws exceptions . [CODESPLIT] public static < T , P extends CheckedProvider < ? super T > > P throwing ( Class < P > providerType , Class < ? extends Throwable > throwable ) { return throwing ( TypeLiteral . get ( providerType ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the type from super class s type parameter in { [CODESPLIT] static Type getSuperclassTypeParameter ( Class < ? > subclass ) { Type superclass = subclass . getGenericSuperclass ( ) ; if ( superclass instanceof Class ) { throw new RuntimeException ( \"Missing type parameter.\" ) ; } ParameterizedType parameterized = ( ParameterizedType ) superclass ; return canonicalize ( parameterized . getActualTypeArguments ( ) [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the type of this type s provider . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) final TypeLiteral < Provider < T > > providerType ( ) { // This cast is safe and wouldn't generate a warning if Type had a type // parameter. return ( TypeLiteral < Provider < T > > ) get ( Types . providerOf ( getType ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets type literal for the given { [CODESPLIT] public static < T > TypeLiteral < T > get ( Class < T > type ) { return new TypeLiteral < T > ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an immutable list of the resolved types . [CODESPLIT] private List < TypeLiteral < ? > > resolveAll ( Type [ ] types ) { TypeLiteral < ? > [ ] result = new TypeLiteral < ? > [ types . length ] ; for ( int t = 0 ; t < types . length ; t ++ ) { result [ t ] = resolve ( types [ t ] ) ; } return ImmutableList . copyOf ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the generic form of { @code supertype } . For example if this is { @code ArrayList<String > } this returns { @code Iterable<String > } given the input { @code Iterable . class } . [CODESPLIT] public TypeLiteral < ? > getSupertype ( Class < ? > supertype ) { checkArgument ( supertype . isAssignableFrom ( rawType ) , \"%s is not a supertype of %s\" , supertype , this . type ) ; return resolve ( MoreTypes . getGenericSupertype ( type , rawType , supertype ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the resolved generic type of { @code field } . [CODESPLIT] public TypeLiteral < ? > getFieldType ( Field field ) { checkArgument ( field . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , \"%s is not defined by a supertype of %s\" , field , type ) ; return resolve ( field . getGenericType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the resolved generic parameter types of { @code methodOrConstructor } . [CODESPLIT] public List < TypeLiteral < ? > > getParameterTypes ( Member methodOrConstructor ) { Type [ ] genericParameterTypes ; if ( methodOrConstructor instanceof Method ) { Method method = ( Method ) methodOrConstructor ; checkArgument ( method . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , \"%s is not defined by a supertype of %s\" , method , type ) ; genericParameterTypes = method . getGenericParameterTypes ( ) ; } else if ( methodOrConstructor instanceof Constructor ) { Constructor < ? > constructor = ( Constructor < ? > ) methodOrConstructor ; checkArgument ( constructor . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , \"%s does not construct a supertype of %s\" , constructor , type ) ; genericParameterTypes = constructor . getGenericParameterTypes ( ) ; } else { throw new IllegalArgumentException ( \"Not a method or a constructor: \" + methodOrConstructor ) ; } return resolveAll ( genericParameterTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the resolved generic exception types thrown by { @code constructor } . [CODESPLIT] public List < TypeLiteral < ? > > getExceptionTypes ( Member methodOrConstructor ) { Type [ ] genericExceptionTypes ; if ( methodOrConstructor instanceof Method ) { Method method = ( Method ) methodOrConstructor ; checkArgument ( method . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , \"%s is not defined by a supertype of %s\" , method , type ) ; genericExceptionTypes = method . getGenericExceptionTypes ( ) ; } else if ( methodOrConstructor instanceof Constructor ) { Constructor < ? > constructor = ( Constructor < ? > ) methodOrConstructor ; checkArgument ( constructor . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , \"%s does not construct a supertype of %s\" , constructor , type ) ; genericExceptionTypes = constructor . getGenericExceptionTypes ( ) ; } else { throw new IllegalArgumentException ( \"Not a method or a constructor: \" + methodOrConstructor ) ; } return resolveAll ( genericExceptionTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the resolved generic return type of { @code method } . [CODESPLIT] public TypeLiteral < ? > getReturnType ( Method method ) { checkArgument ( method . getDeclaringClass ( ) . isAssignableFrom ( rawType ) , \"%s is not defined by a supertype of %s\" , method , type ) ; return resolve ( method . getGenericReturnType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a key that doesn t hold any references to parent classes . This is necessary for anonymous keys so ensure we don t hold a ref to the containing module ( or class ) forever . [CODESPLIT] public static < T > Key < T > canonicalizeKey ( Key < T > key ) { // If we know this isn't a subclass, return as-is. // Otherwise, recreate the key to avoid the subclass if ( key . getClass ( ) == Key . class ) { return key ; } else if ( key . getAnnotation ( ) != null ) { return Key . get ( key . getTypeLiteral ( ) , key . getAnnotation ( ) ) ; } else if ( key . getAnnotationType ( ) != null ) { return Key . get ( key . getTypeLiteral ( ) , key . getAnnotationType ( ) ) ; } else { return Key . get ( key . getTypeLiteral ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an type that s appropriate for use in a key . [CODESPLIT] public static < T > TypeLiteral < T > canonicalizeForKey ( TypeLiteral < T > typeLiteral ) { Type type = typeLiteral . getType ( ) ; if ( ! isFullySpecified ( type ) ) { Errors errors = new Errors ( ) . keyNotFullySpecified ( typeLiteral ) ; throw new ConfigurationException ( errors . getMessages ( ) ) ; } if ( typeLiteral . getRawType ( ) == javax . inject . Provider . class ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; // the following casts are generally unsafe, but com.google.inject.Provider extends // javax.inject.Provider and is covariant @ SuppressWarnings ( \"unchecked\" ) TypeLiteral < T > guiceProviderType = ( TypeLiteral < T > ) TypeLiteral . get ( Types . providerOf ( parameterizedType . getActualTypeArguments ( ) [ 0 ] ) ) ; return guiceProviderType ; } @ SuppressWarnings ( \"unchecked\" ) TypeLiteral < T > wrappedPrimitives = ( TypeLiteral < T > ) PRIMITIVE_TO_WRAPPER . get ( typeLiteral ) ; if ( wrappedPrimitives != null ) { return wrappedPrimitives ; } // If we know this isn't a subclass, return as-is. if ( typeLiteral . getClass ( ) == TypeLiteral . class ) { return typeLiteral ; } // recreate the TypeLiteral to avoid anonymous TypeLiterals from holding refs to their // surrounding classes. @ SuppressWarnings ( \"unchecked\" ) TypeLiteral < T > recreated = ( TypeLiteral < T > ) TypeLiteral . get ( typeLiteral . getType ( ) ) ; return recreated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if { [CODESPLIT] private static boolean isFullySpecified ( Type type ) { if ( type instanceof Class ) { return true ; } else if ( type instanceof CompositeType ) { return ( ( CompositeType ) type ) . isFullySpecified ( ) ; } else if ( type instanceof TypeVariable ) { return false ; } else { return ( ( CompositeType ) canonicalize ( type ) ) . isFullySpecified ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a type that is functionally equal but not necessarily equal according to { [CODESPLIT] public static Type canonicalize ( Type type ) { if ( type instanceof Class ) { Class < ? > c = ( Class < ? > ) type ; return c . isArray ( ) ? new GenericArrayTypeImpl ( canonicalize ( c . getComponentType ( ) ) ) : c ; } else if ( type instanceof CompositeType ) { return type ; } else if ( type instanceof ParameterizedType ) { ParameterizedType p = ( ParameterizedType ) type ; return new ParameterizedTypeImpl ( p . getOwnerType ( ) , p . getRawType ( ) , p . getActualTypeArguments ( ) ) ; } else if ( type instanceof GenericArrayType ) { GenericArrayType g = ( GenericArrayType ) type ; return new GenericArrayTypeImpl ( g . getGenericComponentType ( ) ) ; } else if ( type instanceof WildcardType ) { WildcardType w = ( WildcardType ) type ; return new WildcardTypeImpl ( w . getUpperBounds ( ) , w . getLowerBounds ( ) ) ; } else { // type is either serializable as-is or unsupported return type ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the declaring class of { [CODESPLIT] private static Class < ? > declaringClassOf ( TypeVariable typeVariable ) { GenericDeclaration genericDeclaration = typeVariable . getGenericDeclaration ( ) ; return genericDeclaration instanceof Class ? ( Class < ? > ) genericDeclaration : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Introspects the injector and collects all instances of bound { @code List<ServletDefinition > } into a master list . [CODESPLIT] private ServletDefinition [ ] collectServletDefinitions ( Injector injector ) { List < ServletDefinition > servletDefinitions = Lists . newArrayList ( ) ; for ( Binding < ServletDefinition > entry : injector . findBindingsByType ( SERVLET_DEFS ) ) { servletDefinitions . add ( entry . getProvider ( ) . get ( ) ) ; } // Copy to a fixed size array for speed. return servletDefinitions . toArray ( new ServletDefinition [ servletDefinitions . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs default converters for primitives enums and class literals . [CODESPLIT] static void prepareBuiltInConverters ( InjectorImpl injector ) { // Configure type converters. convertToPrimitiveType ( injector , int . class , Integer . class ) ; convertToPrimitiveType ( injector , long . class , Long . class ) ; convertToPrimitiveType ( injector , boolean . class , Boolean . class ) ; convertToPrimitiveType ( injector , byte . class , Byte . class ) ; convertToPrimitiveType ( injector , short . class , Short . class ) ; convertToPrimitiveType ( injector , float . class , Float . class ) ; convertToPrimitiveType ( injector , double . class , Double . class ) ; convertToClass ( injector , Character . class , new TypeConverter ( ) { @ Override public Object convert ( String value , TypeLiteral < ? > toType ) { value = value . trim ( ) ; if ( value . length ( ) != 1 ) { throw new RuntimeException ( \"Length != 1.\" ) ; } return value . charAt ( 0 ) ; } @ Override public String toString ( ) { return \"TypeConverter<Character>\" ; } } ) ; convertToClasses ( injector , Matchers . subclassesOf ( Enum . class ) , new TypeConverter ( ) { @ Override @ SuppressWarnings ( \"unchecked\" ) public Object convert ( String value , TypeLiteral < ? > toType ) { return Enum . valueOf ( ( Class ) toType . getRawType ( ) , value ) ; } @ Override public String toString ( ) { return \"TypeConverter<E extends Enum<E>>\" ; } } ) ; internalConvertToTypes ( injector , new AbstractMatcher < TypeLiteral < ? > > ( ) { @ Override public boolean matches ( TypeLiteral < ? > typeLiteral ) { return typeLiteral . getRawType ( ) == Class . class ; } @ Override public String toString ( ) { return \"Class<?>\" ; } } , new TypeConverter ( ) { @ Override @ SuppressWarnings ( \"unchecked\" ) public Object convert ( String value , TypeLiteral < ? > toType ) { try { return Class . forName ( value ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e . getMessage ( ) ) ; } } @ Override public String toString ( ) { return \"TypeConverter<Class<?>>\" ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to canonicalize null references to the system class loader . May return null if for some reason the system loader is unavailable . [CODESPLIT] private static ClassLoader canonicalize ( ClassLoader classLoader ) { return classLoader != null ? classLoader : SystemBridgeHolder . SYSTEM_BRIDGE . getParent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a FastClass proxy for invoking the given member or { @code null } if access rules disallow it . [CODESPLIT] public static net . sf . cglib . reflect . FastClass newFastClassForMember ( Member member ) { return newFastClassForMember ( member . getDeclaringClass ( ) , member ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a FastClass proxy for invoking the given member or { @code null } if access rules disallow it . [CODESPLIT] public static net . sf . cglib . reflect . FastClass newFastClassForMember ( Class < ? > type , Member member ) { if ( ! new net . sf . cglib . core . VisibilityPredicate ( type , false ) . evaluate ( member ) ) { // the member cannot be indexed by fast class.  Bail out. return null ; } boolean publiclyCallable = isPubliclyCallable ( member ) ; if ( ! publiclyCallable && ! hasSameVersionOfCglib ( type . getClassLoader ( ) ) ) { // The type is in a classloader with a different version of cglib and is not publicly visible // (so we can't use the bridge classloader to work around).  Bail out. return null ; } net . sf . cglib . reflect . FastClass . Generator generator = new net . sf . cglib . reflect . FastClass . Generator ( ) ; if ( publiclyCallable ) { // Use the bridge classloader if we can generator . setClassLoader ( getClassLoader ( type ) ) ; } generator . setType ( type ) ; generator . setNamingPolicy ( FASTCLASS_NAMING_POLICY ) ; if ( logger . isLoggable ( Level . FINE ) ) { logger . fine ( \"Loading \" + type + \" FastClass with \" + generator . getClassLoader ( ) ) ; } return generator . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the types classloader has the same version of cglib that BytecodeGen has . This only returns false in strange OSGI situations but it prevents us from using FastClass for non public members . [CODESPLIT] private static boolean hasSameVersionOfCglib ( ClassLoader classLoader ) { Class < ? > fc = net . sf . cglib . reflect . FastClass . class ; try { return classLoader . loadClass ( fc . getName ( ) ) == fc ; } catch ( ClassNotFoundException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the member can be called by a fast class generated in a different classloader . [CODESPLIT] private static boolean isPubliclyCallable ( Member member ) { if ( ! Modifier . isPublic ( member . getModifiers ( ) ) ) { return false ; } Class < ? > [ ] parameterTypes ; if ( member instanceof Constructor ) { parameterTypes = ( ( Constructor ) member ) . getParameterTypes ( ) ; } else { Method method = ( Method ) member ; if ( ! Modifier . isPublic ( method . getReturnType ( ) . getModifiers ( ) ) ) { return false ; } parameterTypes = method . getParameterTypes ( ) ; } for ( Class < ? > type : parameterTypes ) { if ( ! Modifier . isPublic ( type . getModifiers ( ) ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ProviderMethod } . [CODESPLIT] static < T > ProviderMethod < T > create ( Key < T > key , Method method , Object instance , ImmutableSet < Dependency < ? > > dependencies , Class < ? extends Annotation > scopeAnnotation , boolean skipFastClassGeneration , Annotation annotation ) { int modifiers = method . getModifiers ( ) ; /*if[AOP]*/ if ( ! skipFastClassGeneration ) { try { net . sf . cglib . reflect . FastClass fc = BytecodeGen . newFastClassForMember ( method ) ; if ( fc != null ) { return new FastClassProviderMethod < T > ( key , fc , method , instance , dependencies , scopeAnnotation , annotation ) ; } } catch ( net . sf . cglib . core . CodeGenerationException e ) { /* fall-through */ } } /*end[AOP]*/ if ( ! Modifier . isPublic ( modifiers ) || ! Modifier . isPublic ( method . getDeclaringClass ( ) . getModifiers ( ) ) ) { method . setAccessible ( true ) ; } return new ReflectionProviderMethod < T > ( key , method , instance , dependencies , scopeAnnotation , annotation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Guice { [CODESPLIT] public Object getValue ( Injector injector ) { if ( null == provider ) { synchronized ( this ) { if ( null == provider ) { provider = isProvider ? injector . getProvider ( getBindingForType ( getProvidedType ( type ) ) ) : injector . getProvider ( getPrimaryBindingKey ( ) ) ; } } } return isProvider ? provider : provider . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace annotation instances with annotation types this is only appropriate for testing if a key is bound and not for injecting . [CODESPLIT] public Key < ? > fixAnnotations ( Key < ? > key ) { return key . getAnnotation ( ) == null ? key : Key . get ( key . getTypeLiteral ( ) , key . getAnnotation ( ) . annotationType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the unique binding annotation from the specified list or { @code null } if there are none . [CODESPLIT] private Annotation getBindingAnnotation ( Annotation [ ] annotations ) { Annotation bindingAnnotation = null ; for ( Annotation annotation : annotations ) { if ( Annotations . isBindingAnnotation ( annotation . annotationType ( ) ) ) { checkArgument ( bindingAnnotation == null , \"Parameter has multiple binding annotations: %s and %s\" , bindingAnnotation , annotation ) ; bindingAnnotation = annotation ; } } return bindingAnnotation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an instance for member injection when that step is performed . [CODESPLIT] < T > Initializable < T > requestInjection ( InjectorImpl injector , T instance , Binding < T > binding , Object source , Set < InjectionPoint > injectionPoints ) { checkNotNull ( source ) ; Preconditions . checkState ( ! validationStarted , \"Member injection could not be requested after validation is started\" ) ; ProvisionListenerStackCallback < T > provisionCallback = binding == null ? null : injector . provisionListenerStore . get ( binding ) ; // short circuit if the object has no injections or listeners. if ( instance == null || ( injectionPoints . isEmpty ( ) && ! injector . membersInjectorStore . hasTypeListeners ( ) && provisionCallback == null ) ) { return Initializables . of ( instance ) ; } if ( initializablesCache . containsKey ( instance ) ) { @ SuppressWarnings ( \"unchecked\" ) // Map from T to InjectableReference<T> Initializable < T > cached = ( Initializable < T > ) initializablesCache . get ( instance ) ; return cached ; } InjectableReference < T > injectableReference = new InjectableReference < T > ( injector , instance , binding == null ? null : binding . getKey ( ) , provisionCallback , source , cycleDetectingLockFactory . create ( instance . getClass ( ) ) ) ; initializablesCache . put ( instance , injectableReference ) ; pendingInjections . add ( injectableReference ) ; return injectableReference ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares member injectors for all injected instances . This prompts Guice to do static analysis on the injected instances . [CODESPLIT] void validateOustandingInjections ( Errors errors ) { validationStarted = true ; initializablesCache . clear ( ) ; for ( InjectableReference < ? > reference : pendingInjections ) { try { reference . validate ( errors ) ; } catch ( ErrorsException e ) { errors . merge ( e . getErrors ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs creation - time injections on all objects that require it . Whenever fulfilling an injection depends on another object that requires injection we inject it first . If the two instances are codependent ( directly or transitively ) ordering of injection is arbitrary . [CODESPLIT] void injectAll ( final Errors errors ) { Preconditions . checkState ( validationStarted , \"Validation should be done before injection\" ) ; for ( InjectableReference < ? > reference : pendingInjections ) { try { reference . get ( ) ; } catch ( InternalProvisionException ipe ) { errors . merge ( ipe ) ; } } pendingInjections . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance of T constructed using this constructor with the supplied arguments . [CODESPLIT] public T newInstance ( Object [ ] args ) throws Throwable { constructor . setAccessible ( true ) ; try { return constructor . newInstance ( args ) ; } catch ( InvocationTargetException e ) { throw e . getCause ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Introspects the injector and collects all instances of bound { @code List<FilterDefinition > } into a master list . [CODESPLIT] private FilterDefinition [ ] collectFilterDefinitions ( Injector injector ) { List < FilterDefinition > filterDefinitions = Lists . newArrayList ( ) ; for ( Binding < FilterDefinition > entry : injector . findBindingsByType ( FILTER_DEFS ) ) { filterDefinitions . add ( entry . getProvider ( ) . get ( ) ) ; } // Copy to a fixed-size array for speed of iteration. return filterDefinitions . toArray ( new FilterDefinition [ filterDefinitions . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to create an proxy that dispatches either to the guice - servlet pipeline or the regular pipeline based on uri - path match . This proxy also provides minimal forwarding support . [CODESPLIT] @ SuppressWarnings ( { \"JavaDoc\" , \"deprecation\" } ) private ServletRequest withDispatcher ( ServletRequest servletRequest , final ManagedServletPipeline servletPipeline ) { // don't wrap the request if there are no servlets mapped. This prevents us from inserting our // wrapper unless it's actually going to be used. This is necessary for compatibility for apps // that downcast their HttpServletRequests to a concrete implementation. if ( ! servletPipeline . hasServletsMapped ( ) ) { return servletRequest ; } HttpServletRequest request = ( HttpServletRequest ) servletRequest ; //noinspection OverlyComplexAnonymousInnerClass return new HttpServletRequestWrapper ( request ) { @ Override public RequestDispatcher getRequestDispatcher ( String path ) { final RequestDispatcher dispatcher = servletPipeline . getRequestDispatcher ( path ) ; return ( null != dispatcher ) ? dispatcher : super . getRequestDispatcher ( path ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transitively resolves aliases . Given aliases ( X to Y ) and ( Y to Z ) it will return mappings ( X to Z ) and ( Y to Z ) . [CODESPLIT] private Map < NodeId , NodeId > resolveAliases ( Iterable < Alias > aliases ) { Map < NodeId , NodeId > resolved = Maps . newHashMap ( ) ; SetMultimap < NodeId , NodeId > inverse = HashMultimap . create ( ) ; for ( Alias alias : aliases ) { NodeId from = alias . getFromId ( ) ; NodeId to = alias . getToId ( ) ; if ( resolved . containsKey ( to ) ) { to = resolved . get ( to ) ; } resolved . put ( from , to ) ; inverse . put ( to , from ) ; Set < NodeId > prev = inverse . get ( from ) ; if ( prev != null ) { for ( NodeId id : prev ) { resolved . remove ( id ) ; inverse . remove ( from , id ) ; resolved . put ( id , to ) ; inverse . put ( to , id ) ; } } } return resolved ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this scope is a singleton that should be loaded eagerly in { [CODESPLIT] public boolean isEagerSingleton ( Stage stage ) { if ( this == EAGER_SINGLETON ) { return true ; } if ( stage == Stage . PRODUCTION ) { return this == SINGLETON_ANNOTATION || this == SINGLETON_INSTANCE ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes an internal factory . [CODESPLIT] static < T > InternalFactory < ? extends T > scope ( Key < T > key , InjectorImpl injector , InternalFactory < ? extends T > creator , Object source , Scoping scoping ) { if ( scoping . isNoScope ( ) ) { return creator ; } Scope scope = scoping . getScopeInstance ( ) ; // NOTE: SingletonScope relies on the fact that we are passing a // ProviderToInternalFactoryAdapter here.  If you change the type make sure to update // SingletonScope as well. Provider < T > scoped = scope . scope ( key , new ProviderToInternalFactoryAdapter < T > ( injector , creator ) ) ; return new InternalFactoryToProviderAdapter < T > ( scoped , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces annotation scopes with instance scopes using the Injector s annotation - to - instance map . If the scope annotation has no corresponding instance an error will be added and unscoped will be retuned . [CODESPLIT] static Scoping makeInjectable ( Scoping scoping , InjectorImpl injector , Errors errors ) { Class < ? extends Annotation > scopeAnnotation = scoping . getScopeAnnotation ( ) ; if ( scopeAnnotation == null ) { return scoping ; } ScopeBinding scope = injector . state . getScopeBinding ( scopeAnnotation ) ; if ( scope != null ) { return forInstance ( scope . getScope ( ) ) ; } errors . scopeNotFound ( scopeAnnotation ) ; return UNSCOPED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes a path by unescaping all safe percent encoded characters . [CODESPLIT] static String normalizePath ( String path ) { StringBuilder sb = new StringBuilder ( path . length ( ) ) ; int queryStart = path . indexOf ( ' ' ) ; String query = null ; if ( queryStart != - 1 ) { query = path . substring ( queryStart ) ; path = path . substring ( 0 , queryStart ) ; } // Normalize the path.  we need to decode path segments, normalize and rejoin in order to // 1. decode and normalize safe percent escaped characters.  e.g. %70 -> 'p' // 2. decode and interpret dangerous character sequences. e.g. /%2E/ -> '/./' -> '/' // 3. preserve dangerous encoded characters. e.g. '/%2F/' -> '///' -> '/%2F' List < String > segments = new ArrayList <> ( ) ; for ( String segment : SLASH_SPLITTER . split ( path ) ) { // This decodes all non-special characters from the path segment.  so if someone passes // /%2E/foo we will normalize it to /./foo and then /foo String normalized = UrlEscapers . urlPathSegmentEscaper ( ) . escape ( lenientDecode ( segment , UTF_8 , false ) ) ; if ( \".\" . equals ( normalized ) ) { // skip } else if ( \"..\" . equals ( normalized ) ) { if ( segments . size ( ) > 1 ) { segments . remove ( segments . size ( ) - 1 ) ; } } else { segments . add ( normalized ) ; } } SLASH_JOINER . appendTo ( sb , segments ) ; if ( query != null ) { sb . append ( query ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Percent - decodes a US - ASCII string into a Unicode string . The specified encoding is used to determine what characters are represented by any consecutive sequences of the form %<i > XX< / i > . This is the lenient kind of decoding that will simply ignore and copy as - is any %XX sequence that is invalid ( for example %HH ) . [CODESPLIT] private static String lenientDecode ( String string , Charset encoding , boolean decodePlus ) { checkNotNull ( string ) ; checkNotNull ( encoding ) ; if ( decodePlus ) { string = string . replace ( ' ' , ' ' ) ; } int firstPercentPos = string . indexOf ( ' ' ) ; if ( firstPercentPos < 0 ) { return string ; } ByteAccumulator accumulator = new ByteAccumulator ( string . length ( ) , encoding ) ; StringBuilder builder = new StringBuilder ( string . length ( ) ) ; if ( firstPercentPos > 0 ) { builder . append ( string , 0 , firstPercentPos ) ; } for ( int srcPos = firstPercentPos ; srcPos < string . length ( ) ; srcPos ++ ) { char c = string . charAt ( srcPos ) ; if ( c < 0x80 ) { // ASCII boolean processed = false ; if ( c == ' ' && string . length ( ) >= srcPos + 3 ) { String hex = string . substring ( srcPos + 1 , srcPos + 3 ) ; try { int encoded = Integer . parseInt ( hex , 16 ) ; if ( encoded >= 0 ) { accumulator . append ( ( byte ) encoded ) ; srcPos += 2 ; processed = true ; } } catch ( NumberFormatException ignore ) { // Expected case (badly formatted % group) } } if ( ! processed ) { if ( accumulator . isEmpty ( ) ) { // We're not accumulating elements of a multibyte encoded // char, so just toss it right into the result string. builder . append ( c ) ; } else { accumulator . append ( ( byte ) c ) ; } } } else { // Non-ASCII // A non-ASCII char marks the end of a multi-char encoding sequence, // if one is in progress. accumulator . dumpTo ( builder ) ; builder . append ( c ) ; } } accumulator . dumpTo ( builder ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We tolerate duplicate bindings if one exposes the other or if the two bindings are considered duplicates ( see { @link Bindings#areDuplicates ( BindingImpl BindingImpl ) } . [CODESPLIT] private boolean isOkayDuplicate ( BindingImpl < ? > original , BindingImpl < ? > binding , State state ) { if ( original instanceof ExposedBindingImpl ) { ExposedBindingImpl exposed = ( ExposedBindingImpl ) original ; InjectorImpl exposedFrom = ( InjectorImpl ) exposed . getPrivateElements ( ) . getInjector ( ) ; return ( exposedFrom == binding . getInjector ( ) ) ; } else { original = ( BindingImpl < ? > ) state . getExplicitBindingsThisLevel ( ) . get ( binding . getKey ( ) ) ; // If no original at this level, the original was on a parent, and we don't // allow deduplication between parents & children. if ( original == null ) { return false ; } else { return original . equals ( binding ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates an Annotation for the annotation class . Requires that the annotation is all optionals . [CODESPLIT] public static < T extends Annotation > T generateAnnotation ( Class < T > annotationType ) { Preconditions . checkState ( isAllDefaultMethods ( annotationType ) , \"%s is not all default methods\" , annotationType ) ; return ( T ) cache . getUnchecked ( annotationType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements { [CODESPLIT] private static boolean annotationEquals ( Class < ? extends Annotation > type , Map < String , Object > members , Object other ) throws Exception { if ( ! type . isInstance ( other ) ) { return false ; } for ( Method method : type . getDeclaredMethods ( ) ) { String name = method . getName ( ) ; if ( ! Arrays . deepEquals ( new Object [ ] { method . invoke ( other ) } , new Object [ ] { members . get ( name ) } ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements { [CODESPLIT] private static int annotationHashCode ( Class < ? extends Annotation > type , Map < String , Object > members ) throws Exception { int result = 0 ; for ( Method method : type . getDeclaredMethods ( ) ) { String name = method . getName ( ) ; Object value = members . get ( name ) ; result += ( 127 * name . hashCode ( ) ) ^ ( Arrays . deepHashCode ( new Object [ ] { value } ) - 31 ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements { [CODESPLIT] private static String annotationToString ( Class < ? extends Annotation > type , Map < String , Object > members ) throws Exception { StringBuilder sb = new StringBuilder ( ) . append ( \"@\" ) . append ( type . getName ( ) ) . append ( \"(\" ) ; JOINER . appendTo ( sb , Maps . transformValues ( members , arg -> { String s = Arrays . deepToString ( new Object [ ] { arg } ) ; return s . substring ( 1 , s . length ( ) - 1 ) ; // cut off brackets } ) ) ; return sb . append ( \")\" ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given annotation is retained at runtime . [CODESPLIT] public static boolean isRetainedAtRuntime ( Class < ? extends Annotation > annotationType ) { Retention retention = annotationType . getAnnotation ( Retention . class ) ; return retention != null && retention . value ( ) == RetentionPolicy . RUNTIME ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the scope annotation on { [CODESPLIT] public static Class < ? extends Annotation > findScopeAnnotation ( Errors errors , Class < ? > implementation ) { return findScopeAnnotation ( errors , implementation . getAnnotations ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the scoping annotation or null if there isn t one . [CODESPLIT] public static Class < ? extends Annotation > findScopeAnnotation ( Errors errors , Annotation [ ] annotations ) { Class < ? extends Annotation > found = null ; for ( Annotation annotation : annotations ) { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; if ( isScopeAnnotation ( annotationType ) ) { if ( found != null ) { errors . duplicateScopeAnnotations ( found , annotationType ) ; } else { found = annotationType ; } } } return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an error if there is a misplaced annotations on { [CODESPLIT] public static void checkForMisplacedScopeAnnotations ( Class < ? > type , Object source , Errors errors ) { if ( Classes . isConcrete ( type ) ) { return ; } Class < ? extends Annotation > scopeAnnotation = findScopeAnnotation ( errors , type ) ; if ( scopeAnnotation != null // We let Dagger Components through to aid migrations. && ! containsComponentAnnotation ( type . getAnnotations ( ) ) ) { errors . withSource ( type ) . scopeAnnotationOnAbstractType ( scopeAnnotation , type , source ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for the given type member and annotations . [CODESPLIT] public static Key < ? > getKey ( TypeLiteral < ? > type , Member member , Annotation [ ] annotations , Errors errors ) throws ErrorsException { int numErrorsBefore = errors . size ( ) ; Annotation found = findBindingAnnotation ( errors , member , annotations ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; return found == null ? Key . get ( type ) : Key . get ( type , found ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the binding annotation on { [CODESPLIT] public static Annotation findBindingAnnotation ( Errors errors , Member member , Annotation [ ] annotations ) { Annotation found = null ; for ( Annotation annotation : annotations ) { Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; if ( isBindingAnnotation ( annotationType ) ) { if ( found != null ) { errors . duplicateBindingAnnotations ( member , found . annotationType ( ) , annotationType ) ; } else { found = annotation ; } } } return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the annotation is an instance of { [CODESPLIT] public static Annotation canonicalizeIfNamed ( Annotation annotation ) { if ( annotation instanceof javax . inject . Named ) { return Names . named ( ( ( javax . inject . Named ) annotation ) . value ( ) ) ; } else { return annotation ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the annotation is the class { [CODESPLIT] public static Class < ? extends Annotation > canonicalizeIfNamed ( Class < ? extends Annotation > annotationType ) { if ( annotationType == javax . inject . Named . class ) { return Named . class ; } else { return annotationType ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name the binding should use . This is based on the annotation . If the annotation has an instance and is not a marker annotation we ask the annotation for its toString . If it was a marker annotation or just an annotation type we use the annotation s name . Otherwise the name is the empty string . [CODESPLIT] public static String nameOf ( Key < ? > key ) { Annotation annotation = key . getAnnotation ( ) ; Class < ? extends Annotation > annotationType = key . getAnnotationType ( ) ; if ( annotation != null && ! isMarker ( annotationType ) ) { return key . getAnnotation ( ) . toString ( ) ; } else if ( key . getAnnotationType ( ) != null ) { return \"@\" + key . getAnnotationType ( ) . getName ( ) ; } else { return \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the actual provider . [CODESPLIT] public void initializeDelegate ( Provider < T > delegate ) { checkState ( this . delegate == null , \"delegate already initialized\" ) ; this . delegate = checkNotNull ( delegate , \"delegate\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the looked up provider . The result is not valid until this lookup has been initialized which usually happens when the injector is created . The provider will throw an { [CODESPLIT] public Provider < T > getProvider ( ) { return new ProviderWithDependencies < T > ( ) { @ Override public T get ( ) { Provider < T > local = delegate ; if ( local == null ) { throw new IllegalStateException ( \"This Provider cannot be used until the Injector has been created.\" ) ; } return local . get ( ) ; } @ Override public Set < Dependency < ? > > getDependencies ( ) { // We depend on Provider<T>, not T directly.  This is an important distinction // for dependency analysis tools that short-circuit on providers. Key < ? > providerKey = getKey ( ) . ofType ( Types . providerOf ( getKey ( ) . getTypeLiteral ( ) . getType ( ) ) ) ; return ImmutableSet . < Dependency < ? > > of ( Dependency . get ( providerKey ) ) ; } @ Override public String toString ( ) { return \"Provider<\" + getKey ( ) . getTypeLiteral ( ) + \">\" ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public static Class < ? extends Member > memberType ( Member member ) { checkNotNull ( member , \"member\" ) ; if ( member instanceof Field ) { return Field . class ; } else if ( member instanceof Method ) { return Method . class ; } else if ( member instanceof Constructor ) { return Constructor . class ; } else { throw new IllegalArgumentException ( \"Unsupported implementation class for Member, \" + member . getClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType ) { return new MapBinder < K , V > ( newMapRealBinder ( binder . skipSources ( MapBinder . class ) , keyType , valueType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , Class < K > keyType , Class < V > valueType ) { return newMapBinder ( binder , TypeLiteral . get ( keyType ) , TypeLiteral . get ( valueType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > MapBinder < K , V > newMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType , Annotation annotation ) { return new MapBinder < K , V > ( newRealMapBinder ( binder . skipSources ( MapBinder . class ) , keyType , valueType , annotation ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a binding for T . Multiple calls to this are safe and will be collapsed as duplicate bindings . [CODESPLIT] private void addDirectTypeBinding ( Binder binder ) { binder . bind ( bindingSelection . getDirectKey ( ) ) . toProvider ( new RealDirectTypeProvider < T > ( bindingSelection ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new complete constructor injector with injection listeners registered . [CODESPLIT] public ConstructorInjector < ? > get ( InjectionPoint constructorInjector , Errors errors ) throws ErrorsException { return cache . get ( constructorInjector , errors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given class has a scope annotation . [CODESPLIT] private static boolean hasScope ( Class < ? extends Interceptor > interceptorClass ) { for ( Annotation annotation : interceptorClass . getAnnotations ( ) ) { if ( Annotations . isScopeAnnotation ( annotation . annotationType ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new mapbinder that collects entries of { [CODESPLIT] public static < K , V > RealMapBinder < K , V > newRealMapBinder ( Binder binder , TypeLiteral < K > keyType , TypeLiteral < V > valueType , Annotation annotation ) { binder = binder . skipSources ( RealMapBinder . class ) ; return newRealMapBinder ( binder , keyType , valueType , Key . get ( mapOf ( keyType , valueType ) , annotation ) , RealMultibinder . newRealSetBinder ( binder , Key . get ( entryOfProviderOf ( keyType , valueType ) , annotation ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "provider map <K V > is safely a Map<K javax . inject . Provider<V >>> [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) static < K , V > TypeLiteral < Map < K , javax . inject . Provider < V > > > mapOfJavaxProviderOf ( TypeLiteral < K > keyType , TypeLiteral < V > valueType ) { return ( TypeLiteral < Map < K , javax . inject . Provider < V > > > ) TypeLiteral . get ( Types . mapOf ( keyType . getType ( ) , newParameterizedType ( javax . inject . Provider . class , valueType . getType ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a Key<T > will return a Key<Provider<T >> [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static < T > Key < Provider < T > > getKeyOfProvider ( Key < T > valueKey ) { return ( Key < Provider < T > > ) valueKey . ofType ( Types . providerOf ( valueKey . getTypeLiteral ( ) . getType ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "since it s an easy way to group a type and an optional annotation type or instance . [CODESPLIT] static < K , V > RealMapBinder < K , V > newRealMapBinder ( Binder binder , TypeLiteral < K > keyType , Key < V > valueTypeAndAnnotation ) { binder = binder . skipSources ( RealMapBinder . class ) ; TypeLiteral < V > valueType = valueTypeAndAnnotation . getTypeLiteral ( ) ; return newRealMapBinder ( binder , keyType , valueType , valueTypeAndAnnotation . ofType ( mapOf ( keyType , valueType ) ) , RealMultibinder . newRealSetBinder ( binder , valueTypeAndAnnotation . ofType ( entryOfProviderOf ( keyType , valueType ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a binding to the map for the given key . [CODESPLIT] Key < V > getKeyForNewValue ( K key ) { checkNotNull ( key , \"key\" ) ; checkConfiguration ( ! bindingSelection . isInitialized ( ) , \"MapBinder was already initialized\" ) ; RealMultibinder < Map . Entry < K , Provider < V > > > entrySetBinder = bindingSelection . getEntrySetBinder ( ) ; Key < V > valueKey = Key . get ( bindingSelection . getValueType ( ) , new RealElement ( entrySetBinder . getSetName ( ) , MAPBINDER , bindingSelection . getKeyType ( ) . toString ( ) ) ) ; entrySetBinder . addBinding ( ) . toProvider ( new ProviderMapEntry < K , V > ( key , valueKey ) ) ; return valueKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns some metadata if the method is annotated { @code @Finder } or null . [CODESPLIT] public static DynamicFinder from ( Method method ) { return method . isAnnotationPresent ( Finder . class ) ? new DynamicFinder ( method ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] static void onNullInjectedIntoNonNullableDependency ( Object source , Dependency < ? > dependency ) throws InternalProvisionException { // Hack to allow null parameters to @Provides methods, for backwards compatibility. if ( dependency . getInjectionPoint ( ) . getMember ( ) instanceof Method ) { Method annotated = ( Method ) dependency . getInjectionPoint ( ) . getMember ( ) ; if ( annotated . isAnnotationPresent ( Provides . class ) ) { switch ( InternalFlags . getNullableProvidesOption ( ) ) { case ERROR : break ; // break out & let the below exception happen case IGNORE : return ; // user doesn't care about injecting nulls to non-@Nullables. case WARN : // Warn only once, otherwise we spam logs too much. if ( warnedDependencies . add ( dependency ) ) { logger . log ( Level . WARNING , \"Guice injected null into {0} (a {1}), please mark it @Nullable.\" + \" Use -Dguice_check_nullable_provides_params=ERROR to turn this into an\" + \" error.\" , new Object [ ] { Messages . formatParameter ( dependency ) , Messages . convert ( dependency . getKey ( ) ) } ) ; } return ; } } } Object formattedDependency = ( dependency . getParameterIndex ( ) != - 1 ) ? Messages . formatParameter ( dependency ) : StackTraceElements . forMember ( dependency . getInjectionPoint ( ) . getMember ( ) ) ; throw InternalProvisionException . create ( \"null returned by binding at %s%n but %s is not @Nullable\" , source , formattedDependency ) . addSource ( source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepends the given { @code source } to the stack of binding sources for the errors reported in this exception . [CODESPLIT] InternalProvisionException addSource ( Object source ) { if ( source == SourceProvider . UNKNOWN_SOURCE ) { return this ; } int sz = sourcesToPrepend . size ( ) ; if ( sz > 0 && sourcesToPrepend . get ( sz - 1 ) == source ) { // This is for when there are two identical sources added in a row.  This behavior is copied // from Errors.withSource where it can happen when an constructor/provider method throws an // exception return this ; } sourcesToPrepend . add ( source ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct an instance . Returns { [CODESPLIT] Object construct ( final InternalContext context , Dependency < ? > dependency , /* @Nullable */ ProvisionListenerStackCallback < T > provisionCallback ) throws InternalProvisionException { final ConstructionContext < T > constructionContext = context . getConstructionContext ( this ) ; // We have a circular reference between constructors. Return a proxy. if ( constructionContext . isConstructing ( ) ) { // TODO (crazybob): if we can't proxy this object, can we proxy the other object? return constructionContext . createProxy ( context . getInjectorOptions ( ) , dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) ) ; } // If we're re-entering this factory while injecting fields or methods, // return the same instance. This prevents infinite loops. T t = constructionContext . getCurrentReference ( ) ; if ( t != null ) { if ( context . getInjectorOptions ( ) . disableCircularProxies ) { throw InternalProvisionException . circularDependenciesDisabled ( dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) ) ; } else { return t ; } } constructionContext . startConstruction ( ) ; try { // Optimization: Don't go through the callback stack if we have no listeners. if ( provisionCallback == null ) { return provision ( context , constructionContext ) ; } else { return provisionCallback . provision ( context , new ProvisionCallback < T > ( ) { @ Override public T call ( ) throws InternalProvisionException { return provision ( context , constructionContext ) ; } } ) ; } } finally { constructionContext . finishConstruction ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provisions a new T . [CODESPLIT] private T provision ( InternalContext context , ConstructionContext < T > constructionContext ) throws InternalProvisionException { try { T t ; try { Object [ ] parameters = SingleParameterInjector . getAll ( context , parameterInjectors ) ; t = constructionProxy . newInstance ( parameters ) ; constructionContext . setProxyDelegates ( t ) ; } finally { constructionContext . finishConstruction ( ) ; } // Store reference. If an injector re-enters this factory, they'll get the same reference. constructionContext . setCurrentReference ( t ) ; MembersInjectorImpl < T > localMembersInjector = membersInjector ; localMembersInjector . injectMembers ( t , context , false ) ; localMembersInjector . notifyListeners ( t ) ; return t ; } catch ( InvocationTargetException userException ) { Throwable cause = userException . getCause ( ) != null ? userException . getCause ( ) : userException ; throw InternalProvisionException . errorInjectingConstructor ( cause ) . addSource ( constructionProxy . getInjectionPoint ( ) ) ; } finally { constructionContext . removeCurrentReference ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the binding to a copy with the specified annotation on the bound key [CODESPLIT] protected BindingImpl < T > annotatedWithInternal ( Class < ? extends Annotation > annotationType ) { checkNotNull ( annotationType , \"annotationType\" ) ; checkNotAnnotated ( ) ; return setBinding ( binding . withKey ( Key . get ( this . binding . getKey ( ) . getTypeLiteral ( ) , annotationType ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the binding to a copy with the specified annotation on the bound key [CODESPLIT] protected BindingImpl < T > annotatedWithInternal ( Annotation annotation ) { checkNotNull ( annotation , \"annotation\" ) ; checkNotAnnotated ( ) ; return setBinding ( binding . withKey ( Key . get ( this . binding . getKey ( ) . getTypeLiteral ( ) , annotation ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When serialized we eagerly convert sources to strings . This hurts our formatting but it guarantees that the receiving end will be able to read the message . [CODESPLIT] private Object writeReplace ( ) throws ObjectStreamException { Object [ ] sourcesAsStrings = sources . toArray ( ) ; for ( int i = 0 ; i < sourcesAsStrings . length ; i ++ ) { sourcesAsStrings [ i ] = Errors . convert ( sourcesAsStrings [ i ] ) . toString ( ) ; } return new Message ( ImmutableList . copyOf ( sourcesAsStrings ) , message , cause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a module which creates bindings for provider methods from the given module . [CODESPLIT] static Module forModule ( Module module ) { // avoid infinite recursion, since installing a module always installs itself if ( module instanceof CheckedProviderMethodsModule ) { return Modules . EMPTY_MODULE ; } return new CheckedProviderMethodsModule ( module ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the collection is immutable . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public Collection < AssistedMethod > getAssistedMethods ( ) { return ( Collection < AssistedMethod > ) ( Collection < ? > ) assistDataByMethod . values ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the ConfigurationException is due to an error of TypeLiteral not being fully specified . [CODESPLIT] private boolean isTypeNotSpecified ( TypeLiteral < ? > typeLiteral , ConfigurationException ce ) { Collection < Message > messages = ce . getErrorMessages ( ) ; if ( messages . size ( ) == 1 ) { Message msg = Iterables . getOnlyElement ( new Errors ( ) . keyNotFullySpecified ( typeLiteral ) . getMessages ( ) ) ; return msg . getMessage ( ) . equals ( Iterables . getOnlyElement ( messages ) . getMessage ( ) ) ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a constructor suitable for the method . If the implementation contained any constructors marked with { [CODESPLIT] private < T > InjectionPoint findMatchingConstructorInjectionPoint ( Method method , Key < ? > returnType , TypeLiteral < T > implementation , List < Key < ? > > paramList ) throws ErrorsException { Errors errors = new Errors ( method ) ; if ( returnType . getTypeLiteral ( ) . equals ( implementation ) ) { errors = errors . withSource ( implementation ) ; } else { errors = errors . withSource ( returnType ) . withSource ( implementation ) ; } Class < ? > rawType = implementation . getRawType ( ) ; if ( Modifier . isInterface ( rawType . getModifiers ( ) ) ) { errors . addMessage ( \"%s is an interface, not a concrete class.  Unable to create AssistedInject factory.\" , implementation ) ; throw errors . toException ( ) ; } else if ( Modifier . isAbstract ( rawType . getModifiers ( ) ) ) { errors . addMessage ( \"%s is abstract, not a concrete class.  Unable to create AssistedInject factory.\" , implementation ) ; throw errors . toException ( ) ; } else if ( Classes . isInnerClass ( rawType ) ) { errors . cannotInjectInnerClass ( rawType ) ; throw errors . toException ( ) ; } Constructor < ? > matchingConstructor = null ; boolean anyAssistedInjectConstructors = false ; // Look for AssistedInject constructors... for ( Constructor < ? > constructor : rawType . getDeclaredConstructors ( ) ) { if ( constructor . isAnnotationPresent ( AssistedInject . class ) ) { anyAssistedInjectConstructors = true ; if ( constructorHasMatchingParams ( implementation , constructor , paramList , errors ) ) { if ( matchingConstructor != null ) { errors . addMessage ( \"%s has more than one constructor annotated with @AssistedInject\" + \" that matches the parameters in method %s.  Unable to create \" + \"AssistedInject factory.\" , implementation , method ) ; throw errors . toException ( ) ; } else { matchingConstructor = constructor ; } } } } if ( ! anyAssistedInjectConstructors ) { // If none existed, use @Inject. try { return InjectionPoint . forConstructorOf ( implementation ) ; } catch ( ConfigurationException e ) { errors . merge ( e . getErrorMessages ( ) ) ; throw errors . toException ( ) ; } } else { // Otherwise, use it or fail with a good error message. if ( matchingConstructor != null ) { // safe because we got the constructor from this implementation. @ SuppressWarnings ( \"unchecked\" ) InjectionPoint ip = InjectionPoint . forConstructor ( ( Constructor < ? super T > ) matchingConstructor , implementation ) ; return ip ; } else { errors . addMessage ( \"%s has @AssistedInject constructors, but none of them match the\" + \" parameters in method %s.  Unable to create AssistedInject factory.\" , implementation , method ) ; throw errors . toException ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matching logic for constructors annotated with AssistedInject . This returns true if and only if all [CODESPLIT] private boolean constructorHasMatchingParams ( TypeLiteral < ? > type , Constructor < ? > constructor , List < Key < ? > > paramList , Errors errors ) throws ErrorsException { List < TypeLiteral < ? > > params = type . getParameterTypes ( constructor ) ; Annotation [ ] [ ] paramAnnotations = constructor . getParameterAnnotations ( ) ; int p = 0 ; List < Key < ? > > constructorKeys = Lists . newArrayList ( ) ; for ( TypeLiteral < ? > param : params ) { Key < ? > paramKey = Annotations . getKey ( param , constructor , paramAnnotations [ p ++ ] , errors ) ; constructorKeys . add ( paramKey ) ; } // Require that every key exist in the constructor to match up exactly. for ( Key < ? > key : paramList ) { // If it didn't exist in the constructor set, we can't use it. if ( ! constructorKeys . remove ( key ) ) { return false ; } } // If any keys remain and their annotation is Assisted, we can't use it. for ( Key < ? > key : constructorKeys ) { if ( key . getAnnotationType ( ) == Assisted . class ) { return false ; } } // All @Assisted params match up to the method's parameters. return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates all dependencies required by the implementation and constructor . [CODESPLIT] private Set < Dependency < ? > > getDependencies ( InjectionPoint ctorPoint , TypeLiteral < ? > implementation ) { ImmutableSet . Builder < Dependency < ? > > builder = ImmutableSet . builder ( ) ; builder . addAll ( ctorPoint . getDependencies ( ) ) ; if ( ! implementation . getRawType ( ) . isInterface ( ) ) { for ( InjectionPoint ip : InjectionPoint . forInstanceMethodsAndFields ( implementation ) ) { builder . addAll ( ip . getDependencies ( ) ) ; } } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all non - assisted dependencies . [CODESPLIT] private Set < Dependency < ? > > removeAssistedDeps ( Set < Dependency < ? > > deps ) { ImmutableSet . Builder < Dependency < ? > > builder = ImmutableSet . builder ( ) ; for ( Dependency < ? > dep : deps ) { Class < ? > annotationType = dep . getKey ( ) . getAnnotationType ( ) ; if ( annotationType == null || ! annotationType . equals ( Assisted . class ) ) { builder . add ( dep ) ; } } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if all dependencies are suitable for the optimized version of AssistedInject . The optimized version caches the binding & uses a ThreadLocal Provider so can only be applied if the assisted bindings are immediately provided . This looks for hints that the values may be lazily retrieved by looking for injections of Injector or a Provider for the assisted values . [CODESPLIT] private boolean isValidForOptimizedAssistedInject ( Set < Dependency < ? > > dependencies , Class < ? > implementation , TypeLiteral < ? > factoryType ) { Set < Dependency < ? > > badDeps = null ; // optimization: create lazily for ( Dependency < ? > dep : dependencies ) { if ( isInjectorOrAssistedProvider ( dep ) ) { if ( badDeps == null ) { badDeps = Sets . newHashSet ( ) ; } badDeps . add ( dep ) ; } } if ( badDeps != null && ! badDeps . isEmpty ( ) ) { logger . log ( Level . WARNING , \"AssistedInject factory {0} will be slow \" + \"because {1} has assisted Provider dependencies or injects the Injector. \" + \"Stop injecting @Assisted Provider<T> (instead use @Assisted T) \" + \"or Injector to speed things up. (It will be a ~6500% speed bump!)  \" + \"The exact offending deps are: {2}\" , new Object [ ] { factoryType , implementation , badDeps } ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the dependency is for { [CODESPLIT] private boolean isInjectorOrAssistedProvider ( Dependency < ? > dependency ) { Class < ? > annotationType = dependency . getKey ( ) . getAnnotationType ( ) ; if ( annotationType != null && annotationType . equals ( Assisted . class ) ) { // If it's assisted.. if ( dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) . equals ( Provider . class ) ) { // And a Provider... return true ; } } else if ( dependency . getKey ( ) . getTypeLiteral ( ) . getRawType ( ) . equals ( Injector . class ) ) { // If it's the Injector... return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "At injector - creation time we initialize the invocation handler . At this time we make sure all factory methods will be able to build the target types . [CODESPLIT] @ Inject @ Toolable void initialize ( Injector injector ) { if ( this . injector != null ) { throw new ConfigurationException ( ImmutableList . of ( new Message ( FactoryProvider2 . class , \"Factories.create() factories may only be used in one Injector!\" ) ) ) ; } this . injector = injector ; for ( Map . Entry < Method , AssistData > entry : assistDataByMethod . entrySet ( ) ) { Method method = entry . getKey ( ) ; AssistData data = entry . getValue ( ) ; Object [ ] args ; if ( ! data . optimized ) { args = new Object [ method . getParameterTypes ( ) . length ] ; Arrays . fill ( args , \"dummy object for validating Factories\" ) ; } else { args = null ; // won't be used -- instead will bind to data.providers. } getBindingFromNewInjector ( method , args , data ) ; // throws if the binding isn't properly configured } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a child injector that binds the args and returns the binding for the method s result . [CODESPLIT] public Binding < ? > getBindingFromNewInjector ( final Method method , final Object [ ] args , final AssistData data ) { checkState ( injector != null , \"Factories.create() factories cannot be used until they're initialized by Guice.\" ) ; final Key < ? > returnType = data . returnType ; // We ignore any pre-existing binding annotation. final Key < ? > returnKey = Key . get ( returnType . getTypeLiteral ( ) , RETURN_ANNOTATION ) ; Module assistedModule = new AbstractModule ( ) { @ Override @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) // raw keys are necessary for the args array and return value protected void configure ( ) { Binder binder = binder ( ) . withSource ( method ) ; int p = 0 ; if ( ! data . optimized ) { for ( Key < ? > paramKey : data . paramTypes ) { // Wrap in a Provider to cover null, and to prevent Guice from injecting the // parameter binder . bind ( ( Key ) paramKey ) . toProvider ( Providers . of ( args [ p ++ ] ) ) ; } } else { for ( Key < ? > paramKey : data . paramTypes ) { // Bind to our ThreadLocalProviders. binder . bind ( ( Key ) paramKey ) . toProvider ( data . providers . get ( p ++ ) ) ; } } Constructor constructor = data . constructor ; // Constructor *should* always be non-null here, // but if it isn't, we'll end up throwing a fairly good error // message for the user. if ( constructor != null ) { binder . bind ( returnKey ) . toConstructor ( constructor , ( TypeLiteral ) data . implementationType ) . in ( Scopes . NO_SCOPE ) ; // make sure we erase any scope on the implementation type } } } ; Injector forCreate = injector . createChildInjector ( assistedModule ) ; Binding < ? > binding = forCreate . getBinding ( returnKey ) ; // If we have providers cached in data, cache the binding for future optimizations. if ( data . optimized ) { data . cachedBinding = binding ; } return binding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When a factory method is invoked we create a child injector that binds all parameters then use that to get an instance of the return type . [CODESPLIT] @ Override public Object invoke ( Object proxy , final Method method , final Object [ ] args ) throws Throwable { // If we setup a method handle earlier for this method, call it. // This is necessary for default methods that java8 creates, so we // can call the default method implementation (and not our proxied version of it). if ( methodHandleByMethod . containsKey ( method ) ) { return methodHandleByMethod . get ( method ) . invokeWithArguments ( args ) ; } if ( method . getDeclaringClass ( ) . equals ( Object . class ) ) { if ( \"equals\" . equals ( method . getName ( ) ) ) { return proxy == args [ 0 ] ; } else if ( \"hashCode\" . equals ( method . getName ( ) ) ) { return System . identityHashCode ( proxy ) ; } else { return method . invoke ( this , args ) ; } } AssistData data = assistDataByMethod . get ( method ) ; checkState ( data != null , \"No data for method: %s\" , method ) ; Provider < ? > provider ; if ( data . cachedBinding != null ) { // Try to get optimized form... provider = data . cachedBinding . getProvider ( ) ; } else { provider = getBindingFromNewInjector ( method , args , data ) . getProvider ( ) ; } try { int p = 0 ; for ( ThreadLocalProvider tlp : data . providers ) { tlp . set ( args [ p ++ ] ) ; } return provider . get ( ) ; } catch ( ProvisionException e ) { // if this is an exception declared by the factory method, throw it as-is if ( e . getErrorMessages ( ) . size ( ) == 1 ) { Message onlyError = getOnlyElement ( e . getErrorMessages ( ) ) ; Throwable cause = onlyError . getCause ( ) ; if ( cause != null && canRethrow ( method , cause ) ) { throw cause ; } } throw e ; } finally { for ( ThreadLocalProvider tlp : data . providers ) { tlp . remove ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if { [CODESPLIT] static boolean canRethrow ( Method invoked , Throwable thrown ) { if ( thrown instanceof Error || thrown instanceof RuntimeException ) { return true ; } for ( Class < ? > declared : invoked . getExceptionTypes ( ) ) { if ( declared . isInstance ( thrown ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws a ConfigurationException with an NullPointerExceptions as the cause if the given reference is { [CODESPLIT] static < T > T checkNotNull ( T reference , String name ) { if ( reference != null ) { return reference ; } NullPointerException npe = new NullPointerException ( name ) ; throw new ConfigurationException ( ImmutableSet . of ( new Message ( npe . toString ( ) , npe ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws a ConfigurationException with a formatted { [CODESPLIT] static void checkConfiguration ( boolean condition , String format , Object ... args ) { if ( condition ) { return ; } throw new ConfigurationException ( ImmutableSet . of ( new Message ( Errors . format ( format , args ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance that uses { [CODESPLIT] public Errors withSource ( Object source ) { return source == this . source || source == SourceProvider . UNKNOWN_SOURCE ? this : new Errors ( this , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Within guice s core allow for better missing binding messages [CODESPLIT] < T > Errors missingImplementationWithHint ( Key < T > key , Injector injector ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( format ( \"No implementation for %s was bound.\" , key ) ) ; // Keys which have similar strings as the desired key List < String > possibleMatches = new ArrayList <> ( ) ; // Check for other keys that may have the same type, // but not the same annotation TypeLiteral < T > type = key . getTypeLiteral ( ) ; List < Binding < T > > sameTypes = injector . findBindingsByType ( type ) ; if ( ! sameTypes . isEmpty ( ) ) { sb . append ( format ( \"%n  Did you mean?\" ) ) ; int howMany = Math . min ( sameTypes . size ( ) , MAX_MATCHING_TYPES_REPORTED ) ; for ( int i = 0 ; i < howMany ; ++ i ) { // TODO: Look into a better way to prioritize suggestions. For example, possbily // use levenshtein distance of the given annotation vs actual annotation. sb . append ( format ( \"%n    * %s\" , sameTypes . get ( i ) . getKey ( ) ) ) ; } int remaining = sameTypes . size ( ) - MAX_MATCHING_TYPES_REPORTED ; if ( remaining > 0 ) { String plural = ( remaining == 1 ) ? \"\" : \"s\" ; sb . append ( format ( \"%n    %d more binding%s with other annotations.\" , remaining , plural ) ) ; } } else { // For now, do a simple substring search for possibilities. This can help spot // issues when there are generics being used (such as a wrapper class) and the // user has forgotten they need to bind based on the wrapper, not the underlying // class. In the future, consider doing a strict in-depth type search. // TODO: Look into a better way to prioritize suggestions. For example, possbily // use levenshtein distance of the type literal strings. String want = type . toString ( ) ; Map < Key < ? > , Binding < ? > > bindingMap = injector . getAllBindings ( ) ; for ( Key < ? > bindingKey : bindingMap . keySet ( ) ) { String have = bindingKey . getTypeLiteral ( ) . toString ( ) ; if ( have . contains ( want ) || want . contains ( have ) ) { Formatter fmt = new Formatter ( ) ; Messages . formatSource ( fmt , bindingMap . get ( bindingKey ) . getSource ( ) ) ; String match = String . format ( \"%s bound%s\" , convert ( bindingKey ) , fmt . toString ( ) ) ; possibleMatches . add ( match ) ; // TODO: Consider a check that if there are more than some number of results, // don't suggest any. if ( possibleMatches . size ( ) > MAX_RELATED_TYPES_REPORTED ) { // Early exit if we have found more than we need. break ; } } } if ( ( possibleMatches . size ( ) > 0 ) && ( possibleMatches . size ( ) <= MAX_RELATED_TYPES_REPORTED ) ) { sb . append ( format ( \"%n  Did you mean?\" ) ) ; for ( String possibleMatch : possibleMatches ) { sb . append ( format ( \"%n    %s\" , possibleMatch ) ) ; } } } // If where are no possibilities to suggest, then handle the case of missing // annotations on simple types. This is usually a bad idea. if ( sameTypes . isEmpty ( ) && possibleMatches . isEmpty ( ) && key . getAnnotation ( ) == null && COMMON_AMBIGUOUS_TYPES . contains ( key . getTypeLiteral ( ) . getRawType ( ) ) ) { // We don't recommend using such simple types without annotations. sb . append ( format ( \"%nThe key seems very generic, did you forget an annotation?\" ) ) ; } return addMessage ( sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO ( lukes ) : inline into callers [CODESPLIT] public static String format ( String messageFormat , Object ... arguments ) { return Messages . format ( messageFormat , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO ( lukes ) : inline in callers . There are some callers outside of guice so this is difficult [CODESPLIT] public static Object convert ( Object o , ElementSource source ) { return Messages . convert ( o , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of newSetBinder . [CODESPLIT] public static < T > RealMultibinder < T > newRealSetBinder ( Binder binder , Key < T > key ) { binder = binder . skipSources ( RealMultibinder . class ) ; RealMultibinder < T > result = new RealMultibinder <> ( binder , key ) ; binder . install ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new entry to the set and returns the key for it . [CODESPLIT] Key < T > getKeyForNewItem ( ) { checkConfiguration ( ! bindingSelection . isInitialized ( ) , \"Multibinder was already initialized\" ) ; return Key . get ( bindingSelection . getElementTypeLiteral ( ) , new RealElement ( bindingSelection . getSetName ( ) , MULTIBINDER , \"\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates over the remaining filter definitions . Returns the first applicable filter or null if none apply . [CODESPLIT] private Filter findNextFilter ( HttpServletRequest request ) { while ( ++ index < filterDefinitions . length ) { Filter filter = filterDefinitions [ index ] . getFilterIfMatching ( request ) ; if ( filter != null ) { return filter ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the inject annotation is on the constructor . [CODESPLIT] private static boolean hasAtInject ( Constructor cxtor ) { return cxtor . isAnnotationPresent ( Inject . class ) || cxtor . isAnnotationPresent ( javax . inject . Inject . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an injection point that can be used to clean up the constructor store . [CODESPLIT] InjectionPoint getInternalConstructor ( ) { if ( factory . constructorInjector != null ) { return factory . constructorInjector . getConstructionProxy ( ) . getInjectionPoint ( ) ; } else { return constructorInjectionPoint ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set of dependencies that can be iterated over to clean up stray JIT bindings . [CODESPLIT] Set < Dependency < ? > > getInternalDependencies ( ) { ImmutableSet . Builder < InjectionPoint > builder = ImmutableSet . builder ( ) ; if ( factory . constructorInjector == null ) { builder . add ( constructorInjectionPoint ) ; // If the below throws, it's OK -- we just ignore those dependencies, because no one // could have used them anyway. try { builder . addAll ( InjectionPoint . forInstanceMethodsAndFields ( constructorInjectionPoint . getDeclaringType ( ) ) ) ; } catch ( ConfigurationException ignored ) { } } else { builder . add ( getConstructor ( ) ) . addAll ( getInjectableMembers ( ) ) ; } return Dependency . forInjectionPoints ( builder . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * if [ AOP ] [CODESPLIT] @ Override public Map < Method , List < org . aopalliance . intercept . MethodInterceptor > > getMethodInterceptors ( ) { checkState ( factory . constructorInjector != null , \"Binding is not ready\" ) ; return factory . constructorInjector . getConstructionProxy ( ) . getMethodInterceptors ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * end [ AOP ] [CODESPLIT] @ Override public Set < Dependency < ? > > getDependencies ( ) { return Dependency . forInjectionPoints ( new ImmutableSet . Builder < InjectionPoint > ( ) . add ( getConstructor ( ) ) . addAll ( getInjectableMembers ( ) ) . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the instance methods and fields of { @code instance } that will be injected to fulfill this request . [CODESPLIT] public Set < InjectionPoint > getInjectionPoints ( ) throws ConfigurationException { return InjectionPoint . forInstanceMethodsAndFields ( instance != null ? TypeLiteral . get ( instance . getClass ( ) ) : type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the system option indicated by the specified key ; runs as a privileged action . [CODESPLIT] private static < T extends Enum < T > > T getSystemOption ( final String name , T defaultValue ) { return getSystemOption ( name , defaultValue , defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the system option indicated by the specified key ; runs as a privileged action . [CODESPLIT] private static < T extends Enum < T > > T getSystemOption ( final String name , T defaultValue , T secureValue ) { Class < T > enumType = defaultValue . getDeclaringClass ( ) ; String value = null ; try { value = AccessController . doPrivileged ( new PrivilegedAction < String > ( ) { @ Override public String run ( ) { return System . getProperty ( name ) ; } } ) ; return ( value != null && value . length ( ) > 0 ) ? Enum . valueOf ( enumType , value ) : defaultValue ; } catch ( SecurityException e ) { return secureValue ; } catch ( IllegalArgumentException e ) { logger . warning ( value + \" is not a valid flag value for \" + name + \". \" + \" Values must be one of \" + Arrays . asList ( enumType . getEnumConstants ( ) ) ) ; return defaultValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a name for a Guice source object . This will typically be either a { [CODESPLIT] @ Override public String getSourceName ( Object source ) { if ( source instanceof ElementSource ) { source = ( ( ElementSource ) source ) . getDeclaringSource ( ) ; } if ( source instanceof Method ) { source = StackTraceElements . forMember ( ( Method ) source ) ; } if ( source instanceof StackTraceElement ) { return getFileString ( ( StackTraceElement ) source ) ; } return stripPackages ( source . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new parameterized type applying { @code typeArguments } to { @code rawType } . The returned type does not have an owner type . [CODESPLIT] public static ParameterizedType newParameterizedType ( Type rawType , Type ... typeArguments ) { return newParameterizedTypeWithOwner ( null , rawType , typeArguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new parameterized type applying { @code typeArguments } to { @code rawType } and enclosed by { @code ownerType } . [CODESPLIT] public static ParameterizedType newParameterizedTypeWithOwner ( Type ownerType , Type rawType , Type ... typeArguments ) { return new ParameterizedTypeImpl ( ownerType , rawType , typeArguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a type modelling a { @link Map } whose keys are of type { @code keyType } and whose values are of type { @code valueType } . [CODESPLIT] public static ParameterizedType mapOf ( Type keyType , Type valueType ) { return newParameterizedType ( Map . class , keyType , valueType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a type modelling a { @link javax . inject . Provider } that provides elements of type { @code elementType } . [CODESPLIT] public static Type javaxProviderOf ( Type type ) { return Types . newParameterizedType ( javax . inject . Provider . class , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a module which creates bindings methods in the module that match the scanner . [CODESPLIT] public static Module forModule ( Object module , ModuleAnnotatedMethodScanner scanner ) { return forObject ( module , false , scanner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the annotation that is claimed by the scanner or null if there is none . [CODESPLIT] private Annotation getAnnotation ( Binder binder , Method method ) { if ( method . isBridge ( ) || method . isSynthetic ( ) ) { return null ; } Annotation annotation = null ; for ( Class < ? extends Annotation > annotationClass : scanner . annotationClasses ( ) ) { Annotation foundAnnotation = method . getAnnotation ( annotationClass ) ; if ( foundAnnotation != null ) { if ( annotation != null ) { binder . addError ( \"More than one annotation claimed by %s on method %s.\" + \" Methods can only have one annotation claimed per scanner.\" , scanner , method ) ; return null ; } annotation = foundAnnotation ; } } return annotation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a constant binding to { [CODESPLIT] public static void bindProperties ( Binder binder , Map < String , String > properties ) { binder = binder . skipSources ( Names . class ) ; for ( Map . Entry < String , String > entry : properties . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; binder . bind ( Key . get ( String . class , new NamedImpl ( key ) ) ) . toInstance ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a constant binding to { [CODESPLIT] public static void bindProperties ( Binder binder , Properties properties ) { binder = binder . skipSources ( Names . class ) ; // use enumeration to include the default properties for ( Enumeration < ? > e = properties . propertyNames ( ) ; e . hasMoreElements ( ) ; ) { String propertyName = ( String ) e . nextElement ( ) ; String value = properties . getProperty ( propertyName ) ; binder . bind ( Key . get ( String . class , new NamedImpl ( propertyName ) ) ) . toInstance ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an injector for the given set of modules in a given development stage . [CODESPLIT] public static Injector createInjector ( Stage stage , Module ... modules ) { return createInjector ( stage , Arrays . asList ( modules ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an injector for the given set of modules in a given development stage . [CODESPLIT] public static Injector createInjector ( Stage stage , Iterable < ? extends Module > modules ) { return new InternalInjectorCreator ( ) . stage ( stage ) . addModules ( modules ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the position of { @link com . google . inject . Module#configure configure ( Binder ) } method call in the { @link #getStackTrace stack trace } for modules that their classes returned by { @link #getModuleClassNames } . For example if the stack trace looks like the following : [CODESPLIT] public List < Integer > getModuleConfigurePositionsInStackTrace ( ) { int size = moduleSource . size ( ) ; Integer [ ] positions = new Integer [ size ] ; int chunkSize = partialCallStack . length ; positions [ 0 ] = chunkSize - 1 ; ModuleSource current = moduleSource ; for ( int cursor = 1 ; cursor < size ; cursor ++ ) { chunkSize = current . getPartialCallStackSize ( ) ; positions [ cursor ] = positions [ cursor - 1 ] + chunkSize ; current = current . getParent ( ) ; } return ImmutableList . < Integer > copyOf ( positions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the sequence of method calls that ends at one of { [CODESPLIT] public StackTraceElement [ ] getStackTrace ( ) { int modulesCallStackSize = moduleSource . getStackTraceSize ( ) ; int chunkSize = partialCallStack . length ; int size = moduleSource . getStackTraceSize ( ) + chunkSize ; StackTraceElement [ ] callStack = new StackTraceElement [ size ] ; System . arraycopy ( StackTraceElements . convertToStackTraceElement ( partialCallStack ) , 0 , callStack , 0 , chunkSize ) ; System . arraycopy ( moduleSource . getStackTrace ( ) , 0 , callStack , chunkSize , modulesCallStackSize ) ; return callStack ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the line number associated with the given member . [CODESPLIT] public Integer getLineNumber ( Member member ) { Preconditions . checkArgument ( type == member . getDeclaringClass ( ) , \"Member %s belongs to %s, not %s\" , member , member . getDeclaringClass ( ) , type ) ; return lines . get ( memberKey ( member ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the specified lookups either immediately or when the injector is created . [CODESPLIT] void initialize ( Errors errors ) { injector . lookups = injector ; new LookupProcessor ( errors ) . process ( injector , lookups ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the given callable in a contextual callable that continues the HTTP request in another thread . This acts as a way of transporting request context data from the request processing thread to to worker threads . [CODESPLIT] @ Deprecated public static < T > Callable < T > continueRequest ( Callable < T > callable , Map < Key < ? > , Object > seedMap ) { return wrap ( callable , continueRequest ( seedMap ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the given callable in a contextual callable that transfers the request to another thread . This acts as a way of transporting request context data from the current thread to a future thread . [CODESPLIT] public static < T > Callable < T > transferRequest ( Callable < T > callable ) { return wrap ( callable , transferRequest ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scopes the given callable inside a request scope . This is not the same as the HTTP request scope but is used if no HTTP request scope is in progress . In this way keys can be scoped as @RequestScoped and exist in non - HTTP requests ( for example : RPC requests ) as well as in HTTP request threads . [CODESPLIT] public static < T > Callable < T > scopeRequest ( Callable < T > callable , Map < Key < ? > , Object > seedMap ) { return wrap ( callable , scopeRequest ( seedMap ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the key and object ensuring the value matches the key type and canonicalizing null objects to the null sentinel . [CODESPLIT] private static Object validateAndCanonicalizeValue ( Key < ? > key , Object object ) { if ( object == null || object == NullObject . INSTANCE ) { return NullObject . INSTANCE ; } if ( ! key . getTypeLiteral ( ) . getRawType ( ) . isInstance ( object ) ) { throw new IllegalArgumentException ( \"Value[\" + object + \"] of type[\" + object . getClass ( ) . getName ( ) + \"] is not compatible with key[\" + key + \"]\" ) ; } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new complete members injector with injection listeners registered . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) // the MembersInjector type always agrees with the passed type public < T > MembersInjectorImpl < T > get ( TypeLiteral < T > key , Errors errors ) throws ErrorsException { return ( MembersInjectorImpl < T > ) cache . get ( key , errors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new members injector and attaches both injection listeners and method aspects . [CODESPLIT] private < T > MembersInjectorImpl < T > createWithListeners ( TypeLiteral < T > type , Errors errors ) throws ErrorsException { int numErrorsBefore = errors . size ( ) ; Set < InjectionPoint > injectionPoints ; try { injectionPoints = InjectionPoint . forInstanceMethodsAndFields ( type ) ; } catch ( ConfigurationException e ) { errors . merge ( e . getErrorMessages ( ) ) ; injectionPoints = e . getPartialValue ( ) ; } ImmutableList < SingleMemberInjector > injectors = getInjectors ( injectionPoints , errors ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; EncounterImpl < T > encounter = new EncounterImpl <> ( errors , injector . lookups ) ; Set < TypeListener > alreadySeenListeners = Sets . newHashSet ( ) ; for ( TypeListenerBinding binding : typeListenerBindings ) { TypeListener typeListener = binding . getListener ( ) ; if ( ! alreadySeenListeners . contains ( typeListener ) && binding . getTypeMatcher ( ) . matches ( type ) ) { alreadySeenListeners . add ( typeListener ) ; try { typeListener . hear ( type , encounter ) ; } catch ( RuntimeException e ) { errors . errorNotifyingTypeListener ( binding , type , e ) ; } } } encounter . invalidate ( ) ; errors . throwIfNewErrors ( numErrorsBefore ) ; return new MembersInjectorImpl < T > ( injector , type , encounter , injectors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the injectors for the specified injection points . [CODESPLIT] ImmutableList < SingleMemberInjector > getInjectors ( Set < InjectionPoint > injectionPoints , Errors errors ) { List < SingleMemberInjector > injectors = Lists . newArrayList ( ) ; for ( InjectionPoint injectionPoint : injectionPoints ) { try { Errors errorsForMember = injectionPoint . isOptional ( ) ? new Errors ( injectionPoint ) : errors . withSource ( injectionPoint ) ; SingleMemberInjector injector = injectionPoint . getMember ( ) instanceof Field ? new SingleFieldInjector ( this . injector , injectionPoint , errorsForMember ) : new SingleMethodInjector ( this . injector , injectionPoint , errorsForMember ) ; injectors . add ( injector ) ; } catch ( ErrorsException ignoredForNow ) { // ignored for now } } return ImmutableList . copyOf ( injectors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "VisibleForTesting [CODESPLIT] @ Inject static void setPipeline ( FilterPipeline pipeline ) { // This can happen if you create many injectors and they all have their own // servlet module. This is legal, caveat a small warning. if ( GuiceFilter . pipeline instanceof ManagedFilterPipeline ) { LOGGER . warning ( MULTIPLE_INJECTORS_WARNING ) ; } // We overwrite the default pipeline GuiceFilter . pipeline = pipeline ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type and an annotation strategy . [CODESPLIT] static < T > Key < T > get ( Class < T > type , AnnotationStrategy annotationStrategy ) { return new Key < T > ( type , annotationStrategy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type . [CODESPLIT] public static < T > Key < T > get ( Class < T > type ) { return new Key < T > ( type , NullAnnotationStrategy . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type and an annotation type . [CODESPLIT] public static < T > Key < T > get ( Class < T > type , Class < ? extends Annotation > annotationType ) { return new Key < T > ( type , strategyFor ( annotationType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type and an annotation . [CODESPLIT] public static < T > Key < T > get ( Class < T > type , Annotation annotation ) { return new Key < T > ( type , strategyFor ( annotation ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type and an annotation type . [CODESPLIT] public static Key < ? > get ( Type type , Class < ? extends Annotation > annotationType ) { return new Key < Object > ( type , strategyFor ( annotationType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type and an annotation . [CODESPLIT] public static Key < ? > get ( Type type , Annotation annotation ) { return new Key < Object > ( type , strategyFor ( annotation ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type . [CODESPLIT] public static < T > Key < T > get ( TypeLiteral < T > typeLiteral ) { return new Key < T > ( typeLiteral , NullAnnotationStrategy . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type and an annotation type . [CODESPLIT] public static < T > Key < T > get ( TypeLiteral < T > typeLiteral , Class < ? extends Annotation > annotationType ) { return new Key < T > ( typeLiteral , strategyFor ( annotationType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key for an injection type and an annotation . [CODESPLIT] public static < T > Key < T > get ( TypeLiteral < T > typeLiteral , Annotation annotation ) { return new Key < T > ( typeLiteral , strategyFor ( annotation ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new key of the specified type with the same annotation as this key . [CODESPLIT] public < T > Key < T > ofType ( Class < T > type ) { return new Key < T > ( type , annotationStrategy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new key of the specified type with the same annotation as this key . [CODESPLIT] public < T > Key < T > ofType ( TypeLiteral < T > type ) { return new Key < T > ( type , annotationStrategy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the strategy for an annotation . [CODESPLIT] static AnnotationStrategy strategyFor ( Annotation annotation ) { checkNotNull ( annotation , \"annotation\" ) ; Class < ? extends Annotation > annotationType = annotation . annotationType ( ) ; ensureRetainedAtRuntime ( annotationType ) ; ensureIsBindingAnnotation ( annotationType ) ; if ( Annotations . isMarker ( annotationType ) ) { return new AnnotationTypeStrategy ( annotationType , annotation ) ; } return new AnnotationInstanceStrategy ( Annotations . canonicalizeIfNamed ( annotation ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the strategy for an annotation type . [CODESPLIT] static AnnotationStrategy strategyFor ( Class < ? extends Annotation > annotationType ) { annotationType = Annotations . canonicalizeIfNamed ( annotationType ) ; if ( isAllDefaultMethods ( annotationType ) ) { return strategyFor ( generateAnnotation ( annotationType ) ) ; } checkNotNull ( annotationType , \"annotation type\" ) ; ensureRetainedAtRuntime ( annotationType ) ; ensureIsBindingAnnotation ( annotationType ) ; return new AnnotationTypeStrategy ( annotationType , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records the elements executed by { [CODESPLIT] public static List < Element > getElements ( Module ... modules ) { return getElements ( Stage . DEVELOPMENT , Arrays . asList ( modules ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records the elements executed by { [CODESPLIT] public static List < Element > getElements ( Iterable < ? extends Module > modules ) { return getElements ( Stage . DEVELOPMENT , modules ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records the elements executed by { [CODESPLIT] public static List < Element > getElements ( Stage stage , Iterable < ? extends Module > modules ) { RecordingBinder binder = new RecordingBinder ( stage ) ; for ( Module module : modules ) { binder . install ( module ) ; } binder . scanForAnnotatedMethods ( ) ; for ( RecordingBinder child : binder . privateBinders ) { child . scanForAnnotatedMethods ( ) ; } // Free the memory consumed by the stack trace elements cache StackTraceElements . clearCache ( ) ; return Collections . unmodifiableList ( binder . elements ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes stacktrace elements related to AOP internal mechanics from the throwable s stack trace and any causes it may have . [CODESPLIT] private void pruneStacktrace ( Throwable throwable ) { for ( Throwable t = throwable ; t != null ; t = t . getCause ( ) ) { StackTraceElement [ ] stackTrace = t . getStackTrace ( ) ; List < StackTraceElement > pruned = Lists . newArrayList ( ) ; for ( StackTraceElement element : stackTrace ) { String className = element . getClassName ( ) ; if ( ! AOP_INTERNAL_CLASSES . contains ( className ) && ! className . contains ( \"$EnhancerByGuice$\" ) ) { pruned . add ( element ) ; } } t . setStackTrace ( pruned . toArray ( new StackTraceElement [ pruned . size ( ) ] ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) // the ProvisionListenerStackCallback type always agrees with the passed type public < T > ProvisionListenerStackCallback < T > get ( Binding < T > binding ) { // Never notify any listeners for internal bindings. if ( ! INTERNAL_BINDINGS . contains ( binding . getKey ( ) ) ) { ProvisionListenerStackCallback < T > callback = ( ProvisionListenerStackCallback < T > ) cache . getUnchecked ( new KeyBinding ( binding . getKey ( ) , binding ) ) ; return callback . hasListeners ( ) ? callback : null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { [CODESPLIT] private < T > ProvisionListenerStackCallback < T > create ( Binding < T > binding ) { List < ProvisionListener > listeners = null ; for ( ProvisionListenerBinding provisionBinding : listenerBindings ) { if ( provisionBinding . getBindingMatcher ( ) . matches ( binding ) ) { if ( listeners == null ) { listeners = Lists . newArrayList ( ) ; } listeners . addAll ( provisionBinding . getListeners ( ) ) ; } } if ( listeners == null || listeners . isEmpty ( ) ) { // Optimization: don't bother constructing the callback if there are // no listeners. return ProvisionListenerStackCallback . emptyListener ( ) ; } return new ProvisionListenerStackCallback < T > ( binding , listeners ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string describing where this dependency was bound . If the binding was just - in - time there is no valid binding source so this describes the class in question . [CODESPLIT] public String getBindingSource ( ) { if ( source instanceof Class ) { return StackTraceElements . forType ( ( Class ) source ) . toString ( ) ; } else if ( source instanceof Member ) { return StackTraceElements . forMember ( ( Member ) source ) . toString ( ) ; } else { return source . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * if [ AOP ] [CODESPLIT] ImmutableList < MethodAspect > getAspects ( ) { return aspects == null ? ImmutableList . < MethodAspect > of ( ) : ImmutableList . copyOf ( aspects ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * end [ AOP ] [CODESPLIT] ImmutableSet < MembersInjector < ? super T > > getMembersInjectors ( ) { return membersInjectors == null ? ImmutableSet . < MembersInjector < ? super T > > of ( ) : ImmutableSet . copyOf ( membersInjectors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepends the list of sources to the given { [CODESPLIT] static Message mergeSources ( List < Object > sources , Message message ) { List < Object > messageSources = message . getSources ( ) ; // It is possible that the end of getSources() and the beginning of message.getSources() are // equivalent, in this case we should drop the repeated source when joining the lists.  The // most likely scenario where this would happen is when a scoped binding throws an exception, // due to the fact that InternalFactoryToProviderAdapter applies the binding source when // merging errors. if ( ! sources . isEmpty ( ) && ! messageSources . isEmpty ( ) && Objects . equal ( messageSources . get ( 0 ) , sources . get ( sources . size ( ) - 1 ) ) ) { messageSources = messageSources . subList ( 1 , messageSources . size ( ) ) ; } return new Message ( ImmutableList . builder ( ) . addAll ( sources ) . addAll ( messageSources ) . build ( ) , message . getMessage ( ) , message . getCause ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls { [CODESPLIT] public static String format ( String messageFormat , Object ... arguments ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { arguments [ i ] = convert ( arguments [ i ] ) ; } return String . format ( messageFormat , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the formatted message for an exception with the specified messages . [CODESPLIT] public static String formatMessages ( String heading , Collection < Message > errorMessages ) { Formatter fmt = new Formatter ( ) . format ( heading ) . format ( \":%n%n\" ) ; int index = 1 ; boolean displayCauses = getOnlyCause ( errorMessages ) == null ; Map < Equivalence . Wrapper < Throwable > , Integer > causes = Maps . newHashMap ( ) ; for ( Message errorMessage : errorMessages ) { int thisIdx = index ++ ; fmt . format ( \"%s) %s%n\" , thisIdx , errorMessage . getMessage ( ) ) ; List < Object > dependencies = errorMessage . getSources ( ) ; for ( int i = dependencies . size ( ) - 1 ; i >= 0 ; i -- ) { Object source = dependencies . get ( i ) ; formatSource ( fmt , source ) ; } Throwable cause = errorMessage . getCause ( ) ; if ( displayCauses && cause != null ) { Equivalence . Wrapper < Throwable > causeEquivalence = ThrowableEquivalence . INSTANCE . wrap ( cause ) ; if ( ! causes . containsKey ( causeEquivalence ) ) { causes . put ( causeEquivalence , thisIdx ) ; fmt . format ( \"Caused by: %s\" , Throwables . getStackTraceAsString ( cause ) ) ; } else { int causeIdx = causes . get ( causeEquivalence ) ; fmt . format ( \"Caused by: %s (same stack trace as error #%s)\" , cause . getClass ( ) . getName ( ) , causeIdx ) ; } } fmt . format ( \"%n\" ) ; } if ( errorMessages . size ( ) == 1 ) { fmt . format ( \"1 error\" ) ; } else { fmt . format ( \"%s errors\" , errorMessages . size ( ) ) ; } return fmt . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Message without a cause . [CODESPLIT] public static Message create ( String messageFormat , Object ... arguments ) { return create ( null , messageFormat , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Message with the given cause . [CODESPLIT] public static Message create ( Throwable cause , String messageFormat , Object ... arguments ) { return create ( cause , ImmutableList . of ( ) , messageFormat , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Message with the given cause and a binding source stack . [CODESPLIT] public static Message create ( Throwable cause , List < Object > sources , String messageFormat , Object ... arguments ) { String message = format ( messageFormat , arguments ) ; return new Message ( sources , message , cause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats an object in a user friendly way . [CODESPLIT] static Object convert ( Object o ) { ElementSource source = null ; if ( o instanceof ElementSource ) { source = ( ElementSource ) o ; o = source . getDeclaringSource ( ) ; } return convert ( o , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the cause throwable if there is exactly one cause in { [CODESPLIT] public static Throwable getOnlyCause ( Collection < Message > messages ) { Throwable onlyCause = null ; for ( Message message : messages ) { Throwable messageCause = message . getCause ( ) ; if ( messageCause == null ) { continue ; } if ( onlyCause != null && ! ThrowableEquivalence . INSTANCE . equivalent ( onlyCause , messageCause ) ) { return null ; } onlyCause = messageCause ; } return onlyCause ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the class names of modules in this module source . The first element ( index 0 ) is filled by this object { [CODESPLIT] List < String > getModuleClassNames ( ) { ImmutableList . Builder < String > classNames = ImmutableList . builder ( ) ; ModuleSource current = this ; while ( current != null ) { String className = current . moduleClassName ; classNames . add ( className ) ; current = current . parent ; } return classNames . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the full call stack that ends just before the module { [CODESPLIT] StackTraceElement [ ] getStackTrace ( ) { int stackTraceSize = getStackTraceSize ( ) ; StackTraceElement [ ] callStack = new StackTraceElement [ stackTraceSize ] ; int cursor = 0 ; ModuleSource current = this ; while ( current != null ) { StackTraceElement [ ] chunk = StackTraceElements . convertToStackTraceElement ( current . partialCallStack ) ; int chunkSize = chunk . length ; System . arraycopy ( chunk , 0 , callStack , cursor , chunkSize ) ; current = current . parent ; cursor = cursor + chunkSize ; } return callStack ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an injector defined by { @code modules } and immediately uses it to create an instance of { @code type } . The modules can be of any type and must contain { @code @Provides } methods . [CODESPLIT] public static < T > T inject ( Class < T > type , Object ... modules ) { Key key = new Key ( type , null ) ; MiniGuice miniGuice = new MiniGuice ( ) ; for ( Object module : modules ) { miniGuice . install ( module ) ; } miniGuice . requireKey ( key , \"root injection\" ) ; miniGuice . addJitBindings ( ) ; miniGuice . addProviderBindings ( ) ; miniGuice . eagerlyLoadSingletons ( ) ; Provider < ? > provider = miniGuice . bindings . get ( key ) ; return type . cast ( provider . get ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the className should be skipped . [CODESPLIT] private boolean shouldBeSkipped ( String className ) { return ( parent != null && parent . shouldBeSkipped ( className ) ) || classNamesToSkip . contains ( className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the class names as Strings [CODESPLIT] private static List < String > asStrings ( Class ... classes ) { List < String > strings = Lists . newArrayList ( ) ; for ( Class c : classes ) { strings . add ( c . getName ( ) ) ; } return strings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the calling line of code . The selected line is the nearest to the top of the stack that is not skipped . [CODESPLIT] public StackTraceElement get ( StackTraceElement [ ] stackTraceElements ) { Preconditions . checkNotNull ( stackTraceElements , \"The stack trace elements cannot be null.\" ) ; for ( final StackTraceElement element : stackTraceElements ) { String className = element . getClassName ( ) ; if ( ! shouldBeSkipped ( className ) ) { return element ; } } throw new AssertionError ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the non - skipped module class name . [CODESPLIT] public Object getFromClassNames ( List < String > moduleClassNames ) { Preconditions . checkNotNull ( moduleClassNames , \"The list of module class names cannot be null.\" ) ; for ( final String moduleClassName : moduleClassNames ) { if ( ! shouldBeSkipped ( moduleClassName ) ) { return new StackTraceElement ( moduleClassName , \"configure\" , null , - 1 ) ; } } return UNKNOWN_SOURCE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers all the bindings of an Injector with the platform MBean server . Consider using the name of your root { [CODESPLIT] public static void manage ( String domain , Injector injector ) { manage ( ManagementFactory . getPlatformMBeanServer ( ) , domain , injector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers all the bindings of an Injector with the given MBean server . Consider using the name of your root { [CODESPLIT] public static void manage ( MBeanServer server , String domain , Injector injector ) { // Register each binding independently. for ( Binding < ? > binding : injector . getBindings ( ) . values ( ) ) { // Construct the name manually so we can ensure proper ordering of the // key/value pairs. StringBuilder name = new StringBuilder ( ) ; name . append ( domain ) . append ( \":\" ) ; Key < ? > key = binding . getKey ( ) ; name . append ( \"type=\" ) . append ( quote ( key . getTypeLiteral ( ) . toString ( ) ) ) ; Annotation annotation = key . getAnnotation ( ) ; if ( annotation != null ) { name . append ( \",annotation=\" ) . append ( quote ( annotation . toString ( ) ) ) ; } else { Class < ? extends Annotation > annotationType = key . getAnnotationType ( ) ; if ( annotationType != null ) { name . append ( \",annotation=\" ) . append ( quote ( \"@\" + annotationType . getName ( ) ) ) ; } } try { server . registerMBean ( new ManagedBinding ( binding ) , new ObjectName ( name . toString ( ) ) ) ; } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( \"Bad object name: \" + name , e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run with no arguments for usage instructions . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { if ( args . length != 1 ) { System . err . println ( \"Usage: java -Dcom.sun.management.jmxremote \" + Manager . class . getName ( ) + \" [module class name]\" ) ; System . err . println ( \"Then run 'jconsole' to connect.\" ) ; System . exit ( 1 ) ; } Module module = ( Module ) Class . forName ( args [ 0 ] ) . newInstance ( ) ; Injector injector = Guice . createInjector ( module ) ; manage ( args [ 0 ] , injector ) ; System . out . println ( \"Press Ctrl+C to exit...\" ) ; // Sleep forever. Thread . sleep ( Long . MAX_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns encoded in - memory version of { [CODESPLIT] public static InMemoryStackTraceElement [ ] convertToInMemoryStackTraceElement ( StackTraceElement [ ] stackTraceElements ) { if ( stackTraceElements . length == 0 ) { return EMPTY_INMEMORY_STACK_TRACE ; } InMemoryStackTraceElement [ ] inMemoryStackTraceElements = new InMemoryStackTraceElement [ stackTraceElements . length ] ; for ( int i = 0 ; i < stackTraceElements . length ; i ++ ) { inMemoryStackTraceElements [ i ] = weakIntern ( new InMemoryStackTraceElement ( stackTraceElements [ i ] ) ) ; } return inMemoryStackTraceElements ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes in - memory stack trace elements to regular { [CODESPLIT] public static StackTraceElement [ ] convertToStackTraceElement ( InMemoryStackTraceElement [ ] inMemoryStackTraceElements ) { if ( inMemoryStackTraceElements . length == 0 ) { return EMPTY_STACK_TRACE ; } StackTraceElement [ ] stackTraceElements = new StackTraceElement [ inMemoryStackTraceElements . length ] ; for ( int i = 0 ; i < inMemoryStackTraceElements . length ; i ++ ) { String declaringClass = inMemoryStackTraceElements [ i ] . getClassName ( ) ; String methodName = inMemoryStackTraceElements [ i ] . getMethodName ( ) ; int lineNumber = inMemoryStackTraceElements [ i ] . getLineNumber ( ) ; stackTraceElements [ i ] = new StackTraceElement ( declaringClass , methodName , UNKNOWN_SOURCE , lineNumber ) ; } return stackTraceElements ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the new current dependency & adds it to the state . [CODESPLIT] Dependency < ? > pushDependency ( Dependency < ? > dependency , Object source ) { Dependency < ? > previous = this . dependency ; this . dependency = dependency ; doPushState ( dependency , source ) ; return previous ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds to the state without setting the dependency . [CODESPLIT] void pushState ( com . google . inject . Key < ? > key , Object source ) { doPushState ( key , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current dependency chain ( all the state stored in the dependencyStack ) . [CODESPLIT] java . util . List < com . google . inject . spi . DependencyAndSource > getDependencyChain ( ) { com . google . common . collect . ImmutableList . Builder < com . google . inject . spi . DependencyAndSource > builder = com . google . common . collect . ImmutableList . builder ( ) ; for ( int i = 0 ; i < dependencyStackSize ; i += 2 ) { Object evenEntry = dependencyStack [ i ] ; Dependency < ? > dependency ; if ( evenEntry instanceof com . google . inject . Key ) { dependency = Dependency . get ( ( com . google . inject . Key < ? > ) evenEntry ) ; } else { dependency = ( Dependency < ? > ) evenEntry ; } builder . add ( new com . google . inject . spi . DependencyAndSource ( dependency , dependencyStack [ i + 1 ] ) ) ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an initializable for an instance that requires no initialization . [CODESPLIT] static < T > Initializable < T > of ( final T instance ) { return new Initializable < T > ( ) { @ Override public T get ( ) { return instance ; } @ Override public String toString ( ) { return String . valueOf ( instance ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility that delegates to the actual service method of the servlet wrapped with a contextual request ( i . e . with correctly computed path info ) . [CODESPLIT] void doService ( final ServletRequest servletRequest , ServletResponse servletResponse ) throws ServletException , IOException { HttpServletRequest request = new HttpServletRequestWrapper ( ( HttpServletRequest ) servletRequest ) { private boolean pathComputed ; private String path ; private boolean pathInfoComputed ; private String pathInfo ; @ Override public String getPathInfo ( ) { if ( ! isPathInfoComputed ( ) ) { String servletPath = getServletPath ( ) ; int servletPathLength = servletPath . length ( ) ; String requestUri = getRequestURI ( ) ; pathInfo = requestUri . substring ( getContextPath ( ) . length ( ) ) . replaceAll ( \"[/]{2,}\" , \"/\" ) ; // See: https://github.com/google/guice/issues/372 if ( pathInfo . startsWith ( servletPath ) ) { pathInfo = pathInfo . substring ( servletPathLength ) ; // Corner case: when servlet path & request path match exactly (without trailing '/'), // then pathinfo is null. if ( pathInfo . isEmpty ( ) && servletPathLength > 0 ) { pathInfo = null ; } else { try { pathInfo = new URI ( pathInfo ) . getPath ( ) ; } catch ( URISyntaxException e ) { // ugh, just leave it alone then } } } else { pathInfo = null ; // we know nothing additional about the URI. } pathInfoComputed = true ; } return pathInfo ; } // NOTE(dhanji): These two are a bit of a hack to help ensure that request dispatcher-sent // requests don't use the same path info that was memoized for the original request. // NOTE(iqshum): I don't think this is possible, since the dispatcher-sent request would // perform its own wrapping. private boolean isPathInfoComputed ( ) { return pathInfoComputed && servletRequest . getAttribute ( REQUEST_DISPATCHER_REQUEST ) == null ; } private boolean isPathComputed ( ) { return pathComputed && servletRequest . getAttribute ( REQUEST_DISPATCHER_REQUEST ) == null ; } @ Override public String getServletPath ( ) { return computePath ( ) ; } @ Override public String getPathTranslated ( ) { final String info = getPathInfo ( ) ; return ( null == info ) ? null : getRealPath ( info ) ; } // Memoizer pattern. private String computePath ( ) { if ( ! isPathComputed ( ) ) { String servletPath = super . getServletPath ( ) ; path = patternMatcher . extractPath ( servletPath ) ; pathComputed = true ; if ( null == path ) { path = servletPath ; } } return path ; } } ; doServiceImpl ( request , ( HttpServletResponse ) servletResponse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provisions a new instance . Subclasses should override this to catch exceptions & rethrow as ErrorsExceptions . [CODESPLIT] protected T provision ( Provider < ? extends T > provider , Dependency < ? > dependency , ConstructionContext < T > constructionContext ) throws InternalProvisionException { T t = provider . get ( ) ; if ( t == null && ! dependency . isNullable ( ) ) { InternalProvisionException . onNullInjectedIntoNonNullableDependency ( source , dependency ) ; } constructionContext . setProxyDelegates ( t ) ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dispatch events . [CODESPLIT] public void onEvent ( ConnectionEventType type , String remoteAddr , Connection conn ) { List < ConnectionEventProcessor > processorList = this . processors . get ( type ) ; if ( processorList != null ) { for ( ConnectionEventProcessor processor : processorList ) { processor . onEvent ( remoteAddr , conn ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add event processor . [CODESPLIT] public void addConnectionEventProcessor ( ConnectionEventType type , ConnectionEventProcessor processor ) { List < ConnectionEventProcessor > processorList = this . processors . get ( type ) ; if ( processorList == null ) { this . processors . putIfAbsent ( type , new ArrayList < ConnectionEventProcessor > ( 1 ) ) ; processorList = this . processors . get ( type ) ; } processorList . add ( processor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the result of a future task [CODESPLIT] public static < T > T getFutureTaskResult ( RunStateRecordedFutureTask < T > task , Logger logger ) { T t = null ; if ( null != task ) { try { t = task . getAfterRun ( ) ; } catch ( InterruptedException e ) { logger . error ( \"Future task interrupted!\" , e ) ; } catch ( ExecutionException e ) { logger . error ( \"Future task execute failed!\" , e ) ; } catch ( FutureTaskNotRunYetException e ) { logger . error ( \"Future task has not run yet!\" , e ) ; } catch ( FutureTaskNotCompleted e ) { logger . error ( \"Future task has not completed!\" , e ) ; } } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "launder the throwable [CODESPLIT] public static void launderThrowable ( Throwable t ) { if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error ) t ; } else { throw new IllegalStateException ( \"Not unchecked!\" , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register processor to process command that has the command code of cmdCode . [CODESPLIT] public void registerProcessor ( CommandCode cmdCode , RemotingProcessor < ? > processor ) { if ( this . cmd2processors . containsKey ( cmdCode ) ) { logger . warn ( \"Processor for cmd={} is already registered, the processor is {}, and changed to {}\" , cmdCode , cmd2processors . get ( cmdCode ) . getClass ( ) . getName ( ) , processor . getClass ( ) . getName ( ) ) ; } this . cmd2processors . put ( cmdCode , processor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the default processor to process command with no specific processor registered . [CODESPLIT] public void registerDefaultProcessor ( RemotingProcessor < ? > processor ) { if ( this . defaultProcessor == null ) { this . defaultProcessor = processor ; } else { throw new IllegalStateException ( \"The defaultProcessor has already been registered: \" + this . defaultProcessor . getClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the specific processor with command code of cmdCode if registered otherwise the default processor is returned . [CODESPLIT] public RemotingProcessor < ? > getProcessor ( CommandCode cmdCode ) { RemotingProcessor < ? > processor = this . cmd2processors . get ( cmdCode ) ; if ( processor != null ) { return processor ; } return this . defaultProcessor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "try get from cache [CODESPLIT] private Url tryGet ( String url ) { SoftReference < Url > softRef = Url . parsedUrls . get ( url ) ; return ( null == softRef ) ? null : softRef . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "decode the protocol code [CODESPLIT] protected ProtocolCode decodeProtocolCode ( ByteBuf in ) { if ( in . readableBytes ( ) >= protocolCodeLength ) { byte [ ] protocolCodeBytes = new byte [ protocolCodeLength ] ; in . readBytes ( protocolCodeBytes ) ; return ProtocolCode . fromBytes ( protocolCodeBytes ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all connections of all poolKey . [CODESPLIT] @ Override public Map < String , List < Connection > > getAll ( ) { Map < String , List < Connection > > allConnections = new HashMap < String , List < Connection > > ( ) ; Iterator < Map . Entry < String , RunStateRecordedFutureTask < ConnectionPool > > > iterator = this . getConnPools ( ) . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Map . Entry < String , RunStateRecordedFutureTask < ConnectionPool > > entry = iterator . next ( ) ; ConnectionPool pool = FutureTaskUtil . getFutureTaskResult ( entry . getValue ( ) , logger ) ; if ( null != pool ) { allConnections . put ( entry . getKey ( ) , pool . getAll ( ) ) ; } } return allConnections ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warning! This is weakly consistent implementation to prevent lock the whole { @link ConcurrentHashMap } . [CODESPLIT] @ Override public void removeAll ( ) { if ( null == this . connTasks || this . connTasks . isEmpty ( ) ) { return ; } if ( null != this . connTasks && ! this . connTasks . isEmpty ( ) ) { Iterator < String > iter = this . connTasks . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String poolKey = iter . next ( ) ; this . removeTask ( poolKey ) ; iter . remove ( ) ; } logger . warn ( \"All connection pool and connections have been removed!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in case of cache pollution and connection leak to do schedule scan [CODESPLIT] @ Override public void scan ( ) { if ( null != this . connTasks && ! this . connTasks . isEmpty ( ) ) { Iterator < String > iter = this . connTasks . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String poolKey = iter . next ( ) ; ConnectionPool pool = this . getConnectionPool ( this . connTasks . get ( poolKey ) ) ; if ( null != pool ) { pool . scan ( ) ; if ( pool . isEmpty ( ) ) { if ( ( System . currentTimeMillis ( ) - pool . getLastAccessTimestamp ( ) ) > DEFAULT_EXPIRE_TIME ) { iter . remove ( ) ; logger . warn ( \"Remove expired pool task of poolKey {} which is empty.\" , poolKey ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If no task cached create one and initialize the connections . [CODESPLIT] @ Override public Connection getAndCreateIfAbsent ( Url url ) throws InterruptedException , RemotingException { // get and create a connection pool with initialized connections. ConnectionPool pool = this . getConnectionPoolAndCreateIfAbsent ( url . getUniqueKey ( ) , new ConnectionPoolCall ( url ) ) ; if ( null != pool ) { return pool . get ( ) ; } else { logger . error ( \"[NOTIFYME] bug detected! pool here must not be null!\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If no task cached create one and initialize the connections . If task cached check whether the number of connections adequate if not then heal it . [CODESPLIT] @ Override public void createConnectionAndHealIfNeed ( Url url ) throws InterruptedException , RemotingException { // get and create a connection pool with initialized connections. ConnectionPool pool = this . getConnectionPoolAndCreateIfAbsent ( url . getUniqueKey ( ) , new ConnectionPoolCall ( url ) ) ; if ( null != pool ) { healIfNeed ( pool , url ) ; } else { logger . error ( \"[NOTIFYME] bug detected! pool here must not be null!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the mapping instance of { @link ConnectionPool } with the specified poolKey or create one if there is none mapping in connTasks . [CODESPLIT] private ConnectionPool getConnectionPoolAndCreateIfAbsent ( String poolKey , Callable < ConnectionPool > callable ) throws RemotingException , InterruptedException { RunStateRecordedFutureTask < ConnectionPool > initialTask = null ; ConnectionPool pool = null ; int retry = DEFAULT_RETRY_TIMES ; int timesOfResultNull = 0 ; int timesOfInterrupt = 0 ; for ( int i = 0 ; ( i < retry ) && ( pool == null ) ; ++ i ) { initialTask = this . connTasks . get ( poolKey ) ; if ( null == initialTask ) { initialTask = new RunStateRecordedFutureTask < ConnectionPool > ( callable ) ; initialTask = this . connTasks . putIfAbsent ( poolKey , initialTask ) ; if ( null == initialTask ) { initialTask = this . connTasks . get ( poolKey ) ; initialTask . run ( ) ; } } try { pool = initialTask . get ( ) ; if ( null == pool ) { if ( i + 1 < retry ) { timesOfResultNull ++ ; continue ; } this . connTasks . remove ( poolKey ) ; String errMsg = \"Get future task result null for poolKey [\" + poolKey + \"] after [\" + ( timesOfResultNull + 1 ) + \"] times try.\" ; throw new RemotingException ( errMsg ) ; } } catch ( InterruptedException e ) { if ( i + 1 < retry ) { timesOfInterrupt ++ ; continue ; // retry if interrupted } this . connTasks . remove ( poolKey ) ; logger . warn ( \"Future task of poolKey {} interrupted {} times. InterruptedException thrown and stop retry.\" , poolKey , ( timesOfInterrupt + 1 ) , e ) ; throw e ; } catch ( ExecutionException e ) { // DO NOT retry if ExecutionException occurred this . connTasks . remove ( poolKey ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof RemotingException ) { throw ( RemotingException ) cause ; } else { FutureTaskUtil . launderThrowable ( cause ) ; } } } return pool ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove task and remove all connections [CODESPLIT] private void removeTask ( String poolKey ) { RunStateRecordedFutureTask < ConnectionPool > task = this . connTasks . remove ( poolKey ) ; if ( null != task ) { ConnectionPool pool = FutureTaskUtil . getFutureTaskResult ( task , logger ) ; if ( null != pool ) { pool . removeAllAndTryClose ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "execute heal connection tasks if the actual number of connections in pool is less than expected [CODESPLIT] private void healIfNeed ( ConnectionPool pool , Url url ) throws RemotingException , InterruptedException { String poolKey = url . getUniqueKey ( ) ; // only when async creating connections done // and the actual size of connections less than expected, the healing task can be run. if ( pool . isAsyncCreationDone ( ) && pool . size ( ) < url . getConnNum ( ) ) { FutureTask < Integer > task = this . healTasks . get ( poolKey ) ; if ( null == task ) { task = new FutureTask < Integer > ( new HealConnectionCall ( url , pool ) ) ; task = this . healTasks . putIfAbsent ( poolKey , task ) ; if ( null == task ) { task = this . healTasks . get ( poolKey ) ; task . run ( ) ; } } try { int numAfterHeal = task . get ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"[NOTIFYME] - conn num after heal {}, expected {}, warmup {}\" , numAfterHeal , url . getConnNum ( ) , url . isConnWarmup ( ) ) ; } } catch ( InterruptedException e ) { this . healTasks . remove ( poolKey ) ; throw e ; } catch ( ExecutionException e ) { this . healTasks . remove ( poolKey ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof RemotingException ) { throw ( RemotingException ) cause ; } else { FutureTaskUtil . launderThrowable ( cause ) ; } } // heal task is one-off, remove from cache directly after run this . healTasks . remove ( poolKey ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "do create connections [CODESPLIT] private void doCreate ( final Url url , final ConnectionPool pool , final String taskName , final int syncCreateNumWhenNotWarmup ) throws RemotingException { final int actualNum = pool . size ( ) ; final int expectNum = url . getConnNum ( ) ; if ( actualNum < expectNum ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"actual num {}, expect num {}, task name {}\" , actualNum , expectNum , taskName ) ; } if ( url . isConnWarmup ( ) ) { for ( int i = actualNum ; i < expectNum ; ++ i ) { Connection connection = create ( url ) ; pool . add ( connection ) ; } } else { if ( syncCreateNumWhenNotWarmup < 0 || syncCreateNumWhenNotWarmup > url . getConnNum ( ) ) { throw new IllegalArgumentException ( \"sync create number when not warmup should be [0,\" + url . getConnNum ( ) + \"]\" ) ; } // create connection in sync way if ( syncCreateNumWhenNotWarmup > 0 ) { for ( int i = 0 ; i < syncCreateNumWhenNotWarmup ; ++ i ) { Connection connection = create ( url ) ; pool . add ( connection ) ; } if ( syncCreateNumWhenNotWarmup == url . getConnNum ( ) ) { return ; } } // initialize executor in lazy way initializeExecutor ( ) ; pool . markAsyncCreationStart ( ) ; // mark the start of async try { this . asyncCreateConnectionExecutor . execute ( new Runnable ( ) { @ Override public void run ( ) { try { for ( int i = pool . size ( ) ; i < url . getConnNum ( ) ; ++ i ) { Connection conn = null ; try { conn = create ( url ) ; } catch ( RemotingException e ) { logger . error ( \"Exception occurred in async create connection thread for {}, taskName {}\" , url . getUniqueKey ( ) , taskName , e ) ; } pool . add ( conn ) ; } } finally { pool . markAsyncCreationDone ( ) ; // mark the end of async } } } ) ; } catch ( RejectedExecutionException e ) { pool . markAsyncCreationDone ( ) ; // mark the end of async when reject throw e ; } } // end of NOT warm up } // end of if }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize executor [CODESPLIT] private void initializeExecutor ( ) { if ( ! this . executorInitialized ) { this . executorInitialized = true ; this . asyncCreateConnectionExecutor = new ThreadPoolExecutor ( minPoolSize , maxPoolSize , keepAliveTime , TimeUnit . SECONDS , new ArrayBlockingQueue < Runnable > ( queueSize ) , new NamedThreadFactory ( \"Bolt-conn-warmup-executor\" , true ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdown . <p > Notice : <br > <li > Rpc client can not be used any more after shutdown . <li > If you need you should destroy it and instantiate another one . [CODESPLIT] public void shutdown ( ) { this . connectionManager . removeAll ( ) ; logger . warn ( \"Close all connections from client side!\" ) ; this . taskScanner . shutdown ( ) ; logger . warn ( \"Rpc client shutdown!\" ) ; if ( reconnectManager != null ) { reconnectManager . stop ( ) ; } if ( connectionMonitor != null ) { connectionMonitor . destroy ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One way invocation using a string address address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2 <br > <p > Notice : <br > <ol > <li > <b > DO NOT modify the request object concurrently when this method is called . < / b > < / li > <li > When do invocation use the string address to find a available connection if none then create one . < / li > <ul > <li > You can use { @link RpcConfigs#CONNECT_TIMEOUT_KEY } to specify connection timeout time unit is milliseconds e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTTIMEOUT = 3000 ] <li > You can use { @link RpcConfigs#CONNECTION_NUM_KEY } to specify connection number for each ip and port e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONNUM = 30 ] <li > You can use { @link RpcConfigs#CONNECTION_WARMUP_KEY } to specify whether need warmup all connections for the first time you call this method e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONWARMUP = false ] < / ul > <li > You should use { @link #closeConnection ( String addr ) } to close it if you want . < / ol > [CODESPLIT] public void oneway ( final String addr , final Object request ) throws RemotingException , InterruptedException { this . rpcRemoting . oneway ( addr , request , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One way invocation using a { @link Connection } <br > <p > Notice : <br > <b > DO NOT modify the request object concurrently when this method is called . < / b > [CODESPLIT] public void oneway ( final Connection conn , final Object request ) throws RemotingException { this . rpcRemoting . oneway ( conn , request , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Oneway invocation with a { @link InvokeContext } common api notice please see { @link #oneway ( Connection Object ) } [CODESPLIT] public void oneway ( final Connection conn , final Object request , final InvokeContext invokeContext ) throws RemotingException { this . rpcRemoting . oneway ( conn , request , invokeContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous invocation using a string address address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2 <br > <p > Notice : <br > <ol > <li > <b > DO NOT modify the request object concurrently when this method is called . < / b > < / li > <li > When do invocation use the string address to find a available connection if none then create one . < / li > <ul > <li > You can use { @link RpcConfigs#CONNECT_TIMEOUT_KEY } to specify connection timeout time unit is milliseconds e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTTIMEOUT = 3000 ] <li > You can use { @link RpcConfigs#CONNECTION_NUM_KEY } to specify connection number for each ip and port e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONNUM = 30 ] <li > You can use { @link RpcConfigs#CONNECTION_WARMUP_KEY } to specify whether need warmup all connections for the first time you call this method e . g [ 127 . 0 . 0 . 1 : 12200?_CONNECTIONWARMUP = false ] < / ul > <li > You should use { @link #closeConnection ( String addr ) } to close it if you want . < / ol > [CODESPLIT] public Object invokeSync ( final String addr , final Object request , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . rpcRemoting . invokeSync ( addr , request , null , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous invocation with a { @link InvokeContext } common api notice please see { @link #invokeSync ( String Object int ) } [CODESPLIT] public Object invokeSync ( final String addr , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . rpcRemoting . invokeSync ( addr , request , invokeContext , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous invocation using a parsed { @link Url } <br > <p > Notice : <br > <ol > <li > <b > DO NOT modify the request object concurrently when this method is called . < / b > < / li > <li > When do invocation use the parsed { @link Url } to find a available connection if none then create one . < / li > <ul > <li > You can use { @link Url#setConnectTimeout } to specify connection timeout time unit is milliseconds . <li > You can use { @link Url#setConnNum } to specify connection number for each ip and port . <li > You can use { @link Url#setConnWarmup } to specify whether need warmup all connections for the first time you call this method . < / ul > <li > You should use { @link #closeConnection ( Url url ) } to close it if you want . < / ol > [CODESPLIT] public Object invokeSync ( final Url url , final Object request , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . invokeSync ( url , request , null , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous invocation with a { @link InvokeContext } common api notice please see { @link #invokeSync ( Url Object int ) } [CODESPLIT] public Object invokeSync ( final Url url , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . rpcRemoting . invokeSync ( url , request , invokeContext , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous invocation using a { @link Connection } <br > <p > Notice : <br > <b > DO NOT modify the request object concurrently when this method is called . < / b > [CODESPLIT] public Object invokeSync ( final Connection conn , final Object request , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . rpcRemoting . invokeSync ( conn , request , null , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous invocation with a { @link InvokeContext } common api notice please see { @link #invokeSync ( Connection Object int ) } [CODESPLIT] public Object invokeSync ( final Connection conn , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { return this . rpcRemoting . invokeSync ( conn , request , invokeContext , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Future invocation using a { @link Connection } <br > You can get result use the returned { @link RpcResponseFuture } . <p > Notice : <br > <b > DO NOT modify the request object concurrently when this method is called . < / b > [CODESPLIT] public RpcResponseFuture invokeWithFuture ( final Connection conn , final Object request , int timeoutMillis ) throws RemotingException { return this . rpcRemoting . invokeWithFuture ( conn , request , null , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback invocation with a { @link InvokeContext } common api notice please see { @link #invokeWithCallback ( Url Object InvokeCallback int ) } [CODESPLIT] public void invokeWithCallback ( final Url url , final Object request , final InvokeContext invokeContext , final InvokeCallback invokeCallback , final int timeoutMillis ) throws RemotingException , InterruptedException { this . rpcRemoting . invokeWithCallback ( url , request , invokeContext , invokeCallback , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback invocation using a { @link Connection } <br > You can specify an implementation of { @link InvokeCallback } to get the result . <p > Notice : <br > <b > DO NOT modify the request object concurrently when this method is called . < / b > [CODESPLIT] public void invokeWithCallback ( final Connection conn , final Object request , final InvokeCallback invokeCallback , final int timeoutMillis ) throws RemotingException { this . rpcRemoting . invokeWithCallback ( conn , request , null , invokeCallback , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback invocation with a { @link InvokeContext } common api notice please see { @link #invokeWithCallback ( Connection Object InvokeCallback int ) } [CODESPLIT] public void invokeWithCallback ( final Connection conn , final Object request , final InvokeContext invokeContext , final InvokeCallback invokeCallback , final int timeoutMillis ) throws RemotingException { this . rpcRemoting . invokeWithCallback ( conn , request , invokeContext , invokeCallback , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a stand alone connection using ip and port . <br > <p > Notice : <br > <li > Each time you call this method will create a new connection . <li > Bolt will not control this connection . <li > You should use { @link #closeStandaloneConnection } to close it . [CODESPLIT] public Connection createStandaloneConnection ( String ip , int port , int connectTimeout ) throws RemotingException { return this . connectionManager . create ( ip , port , connectTimeout ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a stand alone connection using address address format example - 127 . 0 . 0 . 1 : 12200 <br > <p > Notice : <br > <ol > <li > Each time you can this method will create a new connection . <li > Bolt will not control this connection . <li > You should use { @link #closeStandaloneConnection } to close it . < / ol > [CODESPLIT] public Connection createStandaloneConnection ( String addr , int connectTimeout ) throws RemotingException { return this . connectionManager . create ( addr , connectTimeout ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a connection using address address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2 <br > <p > Notice : <br > <ol > <li > Get a connection if none then create . < / li > <ul > <li > You can use { [CODESPLIT] public Connection getConnection ( String addr , int connectTimeout ) throws RemotingException , InterruptedException { Url url = this . addressParser . parse ( addr ) ; return this . getConnection ( url , connectTimeout ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a connection using a { @link Url } . <br > <p > Notice : <ol > <li > Get a connection if none then create . <li > Bolt will control this connection in { @link com . alipay . remoting . ConnectionPool } <li > You should use { @link #closeConnection ( Url url ) } to close it . < / ol > [CODESPLIT] public Connection getConnection ( Url url , int connectTimeout ) throws RemotingException , InterruptedException { url . setConnectTimeout ( connectTimeout ) ; return this . connectionManager . getAndCreateIfAbsent ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check connection the address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2 [CODESPLIT] public boolean checkConnection ( String addr ) { Url url = this . addressParser . parse ( addr ) ; Connection conn = this . connectionManager . get ( url . getUniqueKey ( ) ) ; try { this . connectionManager . check ( conn ) ; } catch ( Exception e ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close all connections of a address [CODESPLIT] public void closeConnection ( String addr ) { Url url = this . addressParser . parse ( addr ) ; this . connectionManager . remove ( url . getUniqueKey ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable heart beat for a certain connection . If this address not connected then do nothing . <p > Notice : this method takes no effect on a stand alone connection . [CODESPLIT] public void enableConnHeartbeat ( String addr ) { Url url = this . addressParser . parse ( addr ) ; this . enableConnHeartbeat ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable heart beat for a certain connection . If this { @link Url } not connected then do nothing . <p > Notice : this method takes no effect on a stand alone connection . [CODESPLIT] public void enableConnHeartbeat ( Url url ) { if ( null != url ) { this . connectionManager . enableHeartbeat ( this . connectionManager . get ( url . getUniqueKey ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable heart beat for a certain connection . If this addr not connected then do nothing . <p > Notice : this method takes no effect on a stand alone connection . [CODESPLIT] public void disableConnHeartbeat ( String addr ) { Url url = this . addressParser . parse ( addr ) ; this . disableConnHeartbeat ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable heart beat for a certain connection . If this { @link Url } not connected then do nothing . <p > Notice : this method takes no effect on a stand alone connection . [CODESPLIT] public void disableConnHeartbeat ( Url url ) { if ( null != url ) { this . connectionManager . disableHeartbeat ( this . connectionManager . get ( url . getUniqueKey ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialization . [CODESPLIT] private void init ( ) { this . channel . attr ( HEARTBEAT_COUNT ) . set ( new Integer ( 0 ) ) ; this . channel . attr ( PROTOCOL ) . set ( this . protocolCode ) ; this . channel . attr ( VERSION ) . set ( this . version ) ; this . channel . attr ( HEARTBEAT_SWITCH ) . set ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do something when closing . [CODESPLIT] public void onClose ( ) { Iterator < Entry < Integer , InvokeFuture > > iter = invokeFutureMap . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Entry < Integer , InvokeFuture > entry = iter . next ( ) ; iter . remove ( ) ; InvokeFuture future = entry . getValue ( ) ; if ( future != null ) { future . putResponse ( future . createConnectionClosedResponse ( this . getRemoteAddress ( ) ) ) ; future . cancelTimeout ( ) ; future . tryAsyncExecuteInvokeCallbackAbnormally ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the connection . [CODESPLIT] public void close ( ) { if ( closed . compareAndSet ( false , true ) ) { try { if ( this . getChannel ( ) != null ) { this . getChannel ( ) . close ( ) . addListener ( new ChannelFutureListener ( ) { @ Override public void operationComplete ( ChannelFuture future ) throws Exception { if ( logger . isInfoEnabled ( ) ) { logger . info ( \"Close the connection to remote address={}, result={}, cause={}\" , RemotingUtil . parseRemoteAddress ( Connection . this . getChannel ( ) ) , future . isSuccess ( ) , future . cause ( ) ) ; } } } ) ; } } catch ( Exception e ) { logger . warn ( \"Exception caught when closing connection {}\" , RemotingUtil . parseRemoteAddress ( Connection . this . getChannel ( ) ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set attribute if key absent . [CODESPLIT] public Object setAttributeIfAbsent ( String key , Object value ) { return attributes . putIfAbsent ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method has been modified to check the size of decoded msgs which is represented by the local variable { @code RecyclableArrayList out } . If has decoded more than one msg then construct an array list to submit all decoded msgs to the pipeline . [CODESPLIT] @ Override public void channelRead ( ChannelHandlerContext ctx , Object msg ) throws Exception { if ( msg instanceof ByteBuf ) { RecyclableArrayList out = RecyclableArrayList . newInstance ( ) ; try { ByteBuf data = ( ByteBuf ) msg ; first = cumulation == null ; if ( first ) { cumulation = data ; } else { cumulation = cumulator . cumulate ( ctx . alloc ( ) , cumulation , data ) ; } callDecode ( ctx , cumulation , out ) ; } catch ( DecoderException e ) { throw e ; } catch ( Throwable t ) { throw new DecoderException ( t ) ; } finally { if ( cumulation != null && ! cumulation . isReadable ( ) ) { numReads = 0 ; cumulation . release ( ) ; cumulation = null ; } else if ( ++ numReads >= discardAfterReads ) { // We did enough reads already try to discard some bytes so we not risk to see a OOME. // See https://github.com/netty/netty/issues/4275 numReads = 0 ; discardSomeReadBytes ( ) ; } int size = out . size ( ) ; if ( size == 0 ) { decodeWasNull = true ; } else if ( size == 1 ) { ctx . fireChannelRead ( out . get ( 0 ) ) ; } else { ArrayList < Object > ret = new ArrayList < Object > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { ret . add ( out . get ( i ) ) ; } ctx . fireChannelRead ( ret ) ; } out . recycle ( ) ; } } else { ctx . fireChannelRead ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called once data should be decoded from the given { @link ByteBuf } . This method will call { @link #decode ( ChannelHandlerContext ByteBuf List ) } as long as decoding should take place . [CODESPLIT] protected void callDecode ( ChannelHandlerContext ctx , ByteBuf in , List < Object > out ) { try { while ( in . isReadable ( ) ) { int outSize = out . size ( ) ; int oldInputLength = in . readableBytes ( ) ; decode ( ctx , in , out ) ; // Check if this handler was removed before continuing the loop. // If it was removed, it is not safe to continue to operate on the buffer. // // See https://github.com/netty/netty/issues/1664 if ( ctx . isRemoved ( ) ) { break ; } if ( outSize == out . size ( ) ) { if ( oldInputLength == in . readableBytes ( ) ) { break ; } else { continue ; } } if ( oldInputLength == in . readableBytes ( ) ) { throw new DecoderException ( StringUtil . simpleClassName ( getClass ( ) ) + \".decode() did not read anything but decoded a message.\" ) ; } if ( isSingleDecode ( ) ) { break ; } } } catch ( DecoderException e ) { throw e ; } catch ( Throwable cause ) { throw new DecoderException ( cause ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Help register single - interest user processor . [CODESPLIT] public static void registerUserProcessor ( UserProcessor < ? > processor , ConcurrentHashMap < String , UserProcessor < ? > > userProcessors ) { if ( null == processor ) { throw new RuntimeException ( \"User processor should not be null!\" ) ; } if ( processor instanceof MultiInterestUserProcessor ) { registerUserProcessor ( ( MultiInterestUserProcessor ) processor , userProcessors ) ; } else { if ( StringUtils . isBlank ( processor . interest ( ) ) ) { throw new RuntimeException ( \"Processor interest should not be blank!\" ) ; } UserProcessor < ? > preProcessor = userProcessors . putIfAbsent ( processor . interest ( ) , processor ) ; if ( preProcessor != null ) { String errMsg = \"Processor with interest key [\" + processor . interest ( ) + \"] has already been registered to rpc server, can not register again!\" ; throw new RuntimeException ( errMsg ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Help register multi - interest user processor . [CODESPLIT] private static void registerUserProcessor ( MultiInterestUserProcessor < ? > processor , ConcurrentHashMap < String , UserProcessor < ? > > userProcessors ) { if ( null == processor . multiInterest ( ) || processor . multiInterest ( ) . isEmpty ( ) ) { throw new RuntimeException ( \"Processor interest should not be blank!\" ) ; } for ( String interest : processor . multiInterest ( ) ) { UserProcessor < ? > preProcessor = userProcessors . putIfAbsent ( interest , processor ) ; if ( preProcessor != null ) { String errMsg = \"Processor with interest key [\" + interest + \"] has already been registered to rpc server, can not register again!\" ; throw new RuntimeException ( errMsg ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send response using remoting context if necessary . <br > If request type is oneway no need to send any response nor exception . [CODESPLIT] public void sendResponseIfNecessary ( final RemotingContext ctx , byte type , final RemotingCommand response ) { final int id = response . getId ( ) ; if ( type != RpcCommandType . REQUEST_ONEWAY ) { RemotingCommand serializedResponse = response ; try { response . serialize ( ) ; } catch ( SerializationException e ) { String errMsg = \"SerializationException occurred when sendResponseIfNecessary in RpcRequestProcessor, id=\" + id ; logger . error ( errMsg , e ) ; serializedResponse = this . getCommandFactory ( ) . createExceptionResponse ( id , ResponseStatus . SERVER_SERIAL_EXCEPTION , e ) ; try { serializedResponse . serialize ( ) ; // serialize again for exception response } catch ( SerializationException e1 ) { // should not happen logger . error ( \"serialize SerializationException response failed!\" ) ; } } catch ( Throwable t ) { String errMsg = \"Serialize RpcResponseCommand failed when sendResponseIfNecessary in RpcRequestProcessor, id=\" + id ; logger . error ( errMsg , t ) ; serializedResponse = this . getCommandFactory ( ) . createExceptionResponse ( id , t , errMsg ) ; } ctx . writeAndFlush ( serializedResponse ) . addListener ( new ChannelFutureListener ( ) { @ Override public void operationComplete ( ChannelFuture future ) throws Exception { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Rpc response sent! requestId=\" + id + \". The address is \" + RemotingUtil . parseRemoteAddress ( ctx . getChannelContext ( ) . channel ( ) ) ) ; } if ( ! future . isSuccess ( ) ) { logger . error ( \"Rpc response send failed! id=\" + id + \". The address is \" + RemotingUtil . parseRemoteAddress ( ctx . getChannelContext ( ) . channel ( ) ) , future . cause ( ) ) ; } } } ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Oneway rpc request received, do not send response, id=\" + id + \", the address is \" + RemotingUtil . parseRemoteAddress ( ctx . getChannelContext ( ) . channel ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dispatch request command to user processor [CODESPLIT] private void dispatchToUserProcessor ( RemotingContext ctx , RpcRequestCommand cmd ) { final int id = cmd . getId ( ) ; final byte type = cmd . getType ( ) ; // processor here must not be null, for it have been checked before UserProcessor processor = ctx . getUserProcessor ( cmd . getRequestClass ( ) ) ; if ( processor instanceof AsyncUserProcessor ) { try { processor . handleRequest ( processor . preHandleRequest ( ctx , cmd . getRequestObject ( ) ) , new RpcAsyncContext ( ctx , cmd , this ) , cmd . getRequestObject ( ) ) ; } catch ( RejectedExecutionException e ) { logger . warn ( \"RejectedExecutionException occurred when do ASYNC process in RpcRequestProcessor\" ) ; sendResponseIfNecessary ( ctx , type , this . getCommandFactory ( ) . createExceptionResponse ( id , ResponseStatus . SERVER_THREADPOOL_BUSY ) ) ; } catch ( Throwable t ) { String errMsg = \"AYSNC process rpc request failed in RpcRequestProcessor, id=\" + id ; logger . error ( errMsg , t ) ; sendResponseIfNecessary ( ctx , type , this . getCommandFactory ( ) . createExceptionResponse ( id , t , errMsg ) ) ; } } else { try { Object responseObject = processor . handleRequest ( processor . preHandleRequest ( ctx , cmd . getRequestObject ( ) ) , cmd . getRequestObject ( ) ) ; sendResponseIfNecessary ( ctx , type , this . getCommandFactory ( ) . createResponse ( responseObject , cmd ) ) ; } catch ( RejectedExecutionException e ) { logger . warn ( \"RejectedExecutionException occurred when do SYNC process in RpcRequestProcessor\" ) ; sendResponseIfNecessary ( ctx , type , this . getCommandFactory ( ) . createExceptionResponse ( id , ResponseStatus . SERVER_THREADPOOL_BUSY ) ) ; } catch ( Throwable t ) { String errMsg = \"SYNC process rpc request failed in RpcRequestProcessor, id=\" + id ; logger . error ( errMsg , t ) ; sendResponseIfNecessary ( ctx , type , this . getCommandFactory ( ) . createExceptionResponse ( id , t , errMsg ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deserialize request command [CODESPLIT] private boolean deserializeRequestCommand ( RemotingContext ctx , RpcRequestCommand cmd , int level ) { boolean result ; try { cmd . deserialize ( level ) ; result = true ; } catch ( DeserializationException e ) { logger . error ( \"DeserializationException occurred when process in RpcRequestProcessor, id={}, deserializeLevel={}\" , cmd . getId ( ) , RpcDeserializeLevel . valueOf ( level ) , e ) ; sendResponseIfNecessary ( ctx , cmd . getType ( ) , this . getCommandFactory ( ) . createExceptionResponse ( cmd . getId ( ) , ResponseStatus . SERVER_DESERIAL_EXCEPTION , e ) ) ; result = false ; } catch ( Throwable t ) { String errMsg = \"Deserialize RpcRequestCommand failed in RpcRequestProcessor, id=\" + cmd . getId ( ) + \", deserializeLevel=\" + level ; logger . error ( errMsg , t ) ; sendResponseIfNecessary ( ctx , cmd . getType ( ) , this . getCommandFactory ( ) . createExceptionResponse ( cmd . getId ( ) , t , errMsg ) ) ; result = false ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pre process remoting context initial some useful infos and pass to biz [CODESPLIT] private void preProcessRemotingContext ( RemotingContext ctx , RpcRequestCommand cmd , long currentTimestamp ) { ctx . setArriveTimestamp ( cmd . getArriveTime ( ) ) ; ctx . setTimeout ( cmd . getTimeout ( ) ) ; ctx . setRpcCommandType ( cmd . getType ( ) ) ; ctx . getInvokeContext ( ) . putIfAbsent ( InvokeContext . BOLT_PROCESS_WAIT_TIME , currentTimestamp - cmd . getArriveTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "print some log when request timeout and discarded in io thread . [CODESPLIT] private void timeoutLog ( final RpcRequestCommand cmd , long currentTimestamp , RemotingContext ctx ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"request id [{}] currenTimestamp [{}] - arriveTime [{}] = server cost [{}] >= timeout value [{}].\" , cmd . getId ( ) , currentTimestamp , cmd . getArriveTime ( ) , ( currentTimestamp - cmd . getArriveTime ( ) ) , cmd . getTimeout ( ) ) ; } String remoteAddr = \"UNKNOWN\" ; if ( null != ctx ) { ChannelHandlerContext channelCtx = ctx . getChannelContext ( ) ; Channel channel = channelCtx . channel ( ) ; if ( null != channel ) { remoteAddr = RemotingUtil . parseRemoteAddress ( channel ) ; } } logger . warn ( \"Rpc request id[{}], from remoteAddr[{}] stop process, total wait time in queue is [{}], client timeout setting is [{}].\" , cmd . getId ( ) , remoteAddr , ( currentTimestamp - cmd . getArriveTime ( ) ) , cmd . getTimeout ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "print some debug log when receive request [CODESPLIT] private void debugLog ( RemotingContext ctx , RpcRequestCommand cmd , long currentTimestamp ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Rpc request received! requestId={}, from {}\" , cmd . getId ( ) , RemotingUtil . parseRemoteAddress ( ctx . getChannelContext ( ) . channel ( ) ) ) ; logger . debug ( \"request id {} currenTimestamp {} - arriveTime {} = server cost {} < timeout {}.\" , cmd . getId ( ) , currentTimestamp , cmd . getArriveTime ( ) , ( currentTimestamp - cmd . getArriveTime ( ) ) , cmd . getTimeout ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the remoting command with its own executor or with the defaultExecutor if its own if null . [CODESPLIT] @ Override public void process ( RemotingContext ctx , T msg , ExecutorService defaultExecutor ) throws Exception { ProcessTask task = new ProcessTask ( ctx , msg ) ; if ( this . getExecutor ( ) != null ) { this . getExecutor ( ) . execute ( task ) ; } else { defaultExecutor . execute ( task ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous invocation [CODESPLIT] protected RemotingCommand invokeSync ( final Connection conn , final RemotingCommand request , final int timeoutMillis ) throws RemotingException , InterruptedException { final InvokeFuture future = createInvokeFuture ( request , request . getInvokeContext ( ) ) ; conn . addInvokeFuture ( future ) ; final int requestId = request . getId ( ) ; try { conn . getChannel ( ) . writeAndFlush ( request ) . addListener ( new ChannelFutureListener ( ) { @ Override public void operationComplete ( ChannelFuture f ) throws Exception { if ( ! f . isSuccess ( ) ) { conn . removeInvokeFuture ( requestId ) ; future . putResponse ( commandFactory . createSendFailedResponse ( conn . getRemoteAddress ( ) , f . cause ( ) ) ) ; logger . error ( \"Invoke send failed, id={}\" , requestId , f . cause ( ) ) ; } } } ) ; } catch ( Exception e ) { conn . removeInvokeFuture ( requestId ) ; future . putResponse ( commandFactory . createSendFailedResponse ( conn . getRemoteAddress ( ) , e ) ) ; logger . error ( \"Exception caught when sending invocation, id={}\" , requestId , e ) ; } RemotingCommand response = future . waitResponse ( timeoutMillis ) ; if ( response == null ) { conn . removeInvokeFuture ( requestId ) ; response = this . commandFactory . createTimeoutResponse ( conn . getRemoteAddress ( ) ) ; logger . warn ( \"Wait response, request id={} timeout!\" , requestId ) ; } return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invocation with callback . [CODESPLIT] protected void invokeWithCallback ( final Connection conn , final RemotingCommand request , final InvokeCallback invokeCallback , final int timeoutMillis ) { final InvokeFuture future = createInvokeFuture ( conn , request , request . getInvokeContext ( ) , invokeCallback ) ; conn . addInvokeFuture ( future ) ; final int requestId = request . getId ( ) ; try { Timeout timeout = TimerHolder . getTimer ( ) . newTimeout ( new TimerTask ( ) { @ Override public void run ( Timeout timeout ) throws Exception { InvokeFuture future = conn . removeInvokeFuture ( requestId ) ; if ( future != null ) { future . putResponse ( commandFactory . createTimeoutResponse ( conn . getRemoteAddress ( ) ) ) ; future . tryAsyncExecuteInvokeCallbackAbnormally ( ) ; } } } , timeoutMillis , TimeUnit . MILLISECONDS ) ; future . addTimeout ( timeout ) ; conn . getChannel ( ) . writeAndFlush ( request ) . addListener ( new ChannelFutureListener ( ) { @ Override public void operationComplete ( ChannelFuture cf ) throws Exception { if ( ! cf . isSuccess ( ) ) { InvokeFuture f = conn . removeInvokeFuture ( requestId ) ; if ( f != null ) { f . cancelTimeout ( ) ; f . putResponse ( commandFactory . createSendFailedResponse ( conn . getRemoteAddress ( ) , cf . cause ( ) ) ) ; f . tryAsyncExecuteInvokeCallbackAbnormally ( ) ; } logger . error ( \"Invoke send failed. The address is {}\" , RemotingUtil . parseRemoteAddress ( conn . getChannel ( ) ) , cf . cause ( ) ) ; } } } ) ; } catch ( Exception e ) { InvokeFuture f = conn . removeInvokeFuture ( requestId ) ; if ( f != null ) { f . cancelTimeout ( ) ; f . putResponse ( commandFactory . createSendFailedResponse ( conn . getRemoteAddress ( ) , e ) ) ; f . tryAsyncExecuteInvokeCallbackAbnormally ( ) ; } logger . error ( \"Exception caught when sending invocation. The address is {}\" , RemotingUtil . parseRemoteAddress ( conn . getChannel ( ) ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Oneway invocation . [CODESPLIT] protected void oneway ( final Connection conn , final RemotingCommand request ) { try { conn . getChannel ( ) . writeAndFlush ( request ) . addListener ( new ChannelFutureListener ( ) { @ Override public void operationComplete ( ChannelFuture f ) throws Exception { if ( ! f . isSuccess ( ) ) { logger . error ( \"Invoke send failed. The address is {}\" , RemotingUtil . parseRemoteAddress ( conn . getChannel ( ) ) , f . cause ( ) ) ; } } } ) ; } catch ( Exception e ) { if ( null == conn ) { logger . error ( \"Conn is null\" ) ; } else { logger . error ( \"Exception caught when sending invocation. The address is {}\" , RemotingUtil . parseRemoteAddress ( conn . getChannel ( ) ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create an instance of { @link ProtocolSwitch } according to byte value [CODESPLIT] public static ProtocolSwitch create ( int value ) { ProtocolSwitch status = new ProtocolSwitch ( ) ; status . setBs ( toBitSet ( value ) ) ; return status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create an instance of { @link ProtocolSwitch } according to switch index [CODESPLIT] public static ProtocolSwitch create ( int [ ] index ) { ProtocolSwitch status = new ProtocolSwitch ( ) ; for ( int i = 0 ; i < index . length ; ++ i ) { status . turnOn ( index [ i ] ) ; } return status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "from bit set to byte [CODESPLIT] public static byte toByte ( BitSet bs ) { int value = 0 ; for ( int i = 0 ; i < bs . length ( ) ; ++ i ) { if ( bs . get ( i ) ) { value += 1 << i ; } } if ( bs . length ( ) > 7 ) { throw new IllegalArgumentException ( \"The byte value \" + value + \" generated according to bit set \" + bs + \" is out of range, should be limited between [\" + Byte . MIN_VALUE + \"] to [\" + Byte . MAX_VALUE + \"]\" ) ; } return ( byte ) value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "from byte to bit set [CODESPLIT] public static BitSet toBitSet ( int value ) { if ( value > Byte . MAX_VALUE || value < Byte . MIN_VALUE ) { throw new IllegalArgumentException ( \"The value \" + value + \" is out of byte range, should be limited between [\" + Byte . MIN_VALUE + \"] to [\" + Byte . MAX_VALUE + \"]\" ) ; } BitSet bs = new BitSet ( ) ; int index = 0 ; while ( value != 0 ) { if ( value % 2 != 0 ) { bs . set ( index ) ; } ++ index ; value = ( byte ) ( value >> 1 ) ; } return bs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get connection and set init invokeContext if invokeContext not { @code null } [CODESPLIT] protected Connection getConnectionAndInitInvokeContext ( Url url , InvokeContext invokeContext ) throws RemotingException , InterruptedException { long start = System . currentTimeMillis ( ) ; Connection conn ; try { conn = this . connectionManager . getAndCreateIfAbsent ( url ) ; } finally { if ( null != invokeContext ) { invokeContext . putIfAbsent ( InvokeContext . CLIENT_CONN_CREATETIME , ( System . currentTimeMillis ( ) - start ) ) ; } } return conn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add reconnect task [CODESPLIT] public void addReconnectTask ( Url url ) { ReconnectTask task = new ReconnectTask ( ) ; task . url = url ; tasks . add ( task ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stop reconnect thread [CODESPLIT] public void stop ( ) { if ( ! this . started ) { return ; } this . started = false ; healConnectionThreads . interrupt ( ) ; this . tasks . clear ( ) ; this . canceled . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Oneway rpc invocation . <br > Notice! DO NOT modify the request object concurrently when this method is called . [CODESPLIT] public void oneway ( final String addr , final Object request , final InvokeContext invokeContext ) throws RemotingException , InterruptedException { Url url = this . addressParser . parse ( addr ) ; this . oneway ( url , request , invokeContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Oneway rpc invocation . <br > Notice! DO NOT modify the request object concurrently when this method is called . [CODESPLIT] public void oneway ( final Connection conn , final Object request , final InvokeContext invokeContext ) throws RemotingException { RequestCommand requestCommand = ( RequestCommand ) toRemotingCommand ( request , conn , invokeContext , - 1 ) ; requestCommand . setType ( RpcCommandType . REQUEST_ONEWAY ) ; preProcessInvokeContext ( invokeContext , requestCommand , conn ) ; super . oneway ( conn , requestCommand ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous rpc invocation . <br > Notice! DO NOT modify the request object concurrently when this method is called . [CODESPLIT] public Object invokeSync ( final String addr , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { Url url = this . addressParser . parse ( addr ) ; return this . invokeSync ( url , request , invokeContext , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous rpc invocation . <br > Notice! DO NOT modify the request object concurrently when this method is called . [CODESPLIT] public Object invokeSync ( final Connection conn , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { RemotingCommand requestCommand = toRemotingCommand ( request , conn , invokeContext , timeoutMillis ) ; preProcessInvokeContext ( invokeContext , requestCommand , conn ) ; ResponseCommand responseCommand = ( ResponseCommand ) super . invokeSync ( conn , requestCommand , timeoutMillis ) ; responseCommand . setInvokeContext ( invokeContext ) ; Object responseObject = RpcResponseResolver . resolveResponseObject ( responseCommand , RemotingUtil . parseRemoteAddress ( conn . getChannel ( ) ) ) ; return responseObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rpc invocation with future returned . <br > Notice! DO NOT modify the request object concurrently when this method is called . [CODESPLIT] public RpcResponseFuture invokeWithFuture ( final Connection conn , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException { RemotingCommand requestCommand = toRemotingCommand ( request , conn , invokeContext , timeoutMillis ) ; preProcessInvokeContext ( invokeContext , requestCommand , conn ) ; InvokeFuture future = super . invokeWithFuture ( conn , requestCommand , timeoutMillis ) ; return new RpcResponseFuture ( RemotingUtil . parseRemoteAddress ( conn . getChannel ( ) ) , future ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rpc invocation with callback . <br > Notice! DO NOT modify the request object concurrently when this method is called . [CODESPLIT] public void invokeWithCallback ( String addr , Object request , final InvokeContext invokeContext , InvokeCallback invokeCallback , int timeoutMillis ) throws RemotingException , InterruptedException { Url url = this . addressParser . parse ( addr ) ; this . invokeWithCallback ( url , request , invokeContext , invokeCallback , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rpc invocation with callback . <br > Notice! DO NOT modify the request object concurrently when this method is called . [CODESPLIT] public void invokeWithCallback ( final Connection conn , final Object request , final InvokeContext invokeContext , final InvokeCallback invokeCallback , final int timeoutMillis ) throws RemotingException { RemotingCommand requestCommand = toRemotingCommand ( request , conn , invokeContext , timeoutMillis ) ; preProcessInvokeContext ( invokeContext , requestCommand , conn ) ; super . invokeWithCallback ( conn , requestCommand , invokeCallback , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert application request object to remoting request command . [CODESPLIT] protected RemotingCommand toRemotingCommand ( Object request , Connection conn , InvokeContext invokeContext , int timeoutMillis ) throws SerializationException { RpcRequestCommand command = this . getCommandFactory ( ) . createRequestCommand ( request ) ; if ( null != invokeContext ) { // set client custom serializer for request command if not null Object clientCustomSerializer = invokeContext . get ( InvokeContext . BOLT_CUSTOM_SERIALIZER ) ; if ( null != clientCustomSerializer ) { try { command . setSerializer ( ( Byte ) clientCustomSerializer ) ; } catch ( ClassCastException e ) { throw new IllegalArgumentException ( \"Illegal custom serializer [\" + clientCustomSerializer + \"], the type of value should be [byte], but now is [\" + clientCustomSerializer . getClass ( ) . getName ( ) + \"].\" ) ; } } // enable crc by default, user can disable by set invoke context `false` for key `InvokeContext.BOLT_CRC_SWITCH` Boolean crcSwitch = invokeContext . get ( InvokeContext . BOLT_CRC_SWITCH , ProtocolSwitch . CRC_SWITCH_DEFAULT_VALUE ) ; if ( null != crcSwitch && crcSwitch ) { command . setProtocolSwitch ( ProtocolSwitch . create ( new int [ ] { ProtocolSwitch . CRC_SWITCH_INDEX } ) ) ; } } else { // enable crc by default, if there is no invoke context. command . setProtocolSwitch ( ProtocolSwitch . create ( new int [ ] { ProtocolSwitch . CRC_SWITCH_INDEX } ) ) ; } command . setTimeout ( timeoutMillis ) ; command . setRequestClass ( request . getClass ( ) . getName ( ) ) ; command . setInvokeContext ( invokeContext ) ; command . serialize ( ) ; logDebugInfo ( command ) ; return command ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter connections to monitor [CODESPLIT] @ Override public Map < String , List < Connection > > filter ( List < Connection > connections ) { List < Connection > serviceOnConnections = new ArrayList < Connection > ( ) ; List < Connection > serviceOffConnections = new ArrayList < Connection > ( ) ; Map < String , List < Connection > > filteredConnections = new ConcurrentHashMap < String , List < Connection > > ( ) ; for ( Connection connection : connections ) { String serviceStatus = ( String ) connection . getAttribute ( Configs . CONN_SERVICE_STATUS ) ; if ( serviceStatus != null ) { if ( connection . isInvokeFutureMapFinish ( ) && ! freshSelectConnections . containsValue ( connection ) ) { serviceOffConnections . add ( connection ) ; } } else { serviceOnConnections . add ( connection ) ; } } filteredConnections . put ( Configs . CONN_SERVICE_STATUS_ON , serviceOnConnections ) ; filteredConnections . put ( Configs . CONN_SERVICE_STATUS_OFF , serviceOffConnections ) ; return filteredConnections ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Monitor connections and close connections with status is off [CODESPLIT] @ Override public void monitor ( Map < String , RunStateRecordedFutureTask < ConnectionPool > > connPools ) { try { if ( null != connPools && ! connPools . isEmpty ( ) ) { Iterator < Map . Entry < String , RunStateRecordedFutureTask < ConnectionPool > > > iter = connPools . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry < String , RunStateRecordedFutureTask < ConnectionPool > > entry = iter . next ( ) ; String poolKey = entry . getKey ( ) ; ConnectionPool pool = FutureTaskUtil . getFutureTaskResult ( entry . getValue ( ) , logger ) ; List < Connection > connections = pool . getAll ( ) ; Map < String , List < Connection > > filteredConnectons = this . filter ( connections ) ; List < Connection > serviceOnConnections = filteredConnectons . get ( Configs . CONN_SERVICE_STATUS_ON ) ; List < Connection > serviceOffConnections = filteredConnectons . get ( Configs . CONN_SERVICE_STATUS_OFF ) ; if ( serviceOnConnections . size ( ) > CONNECTION_THRESHOLD ) { Connection freshSelectConnect = serviceOnConnections . get ( random . nextInt ( serviceOnConnections . size ( ) ) ) ; freshSelectConnect . setAttribute ( Configs . CONN_SERVICE_STATUS , Configs . CONN_SERVICE_STATUS_OFF ) ; Connection lastSelectConnect = freshSelectConnections . remove ( poolKey ) ; freshSelectConnections . put ( poolKey , freshSelectConnect ) ; closeFreshSelectConnections ( lastSelectConnect , serviceOffConnections ) ; } else { if ( freshSelectConnections . containsKey ( poolKey ) ) { Connection lastSelectConnect = freshSelectConnections . remove ( poolKey ) ; closeFreshSelectConnections ( lastSelectConnect , serviceOffConnections ) ; } if ( logger . isInfoEnabled ( ) ) { logger . info ( \"the size of serviceOnConnections [{}] reached CONNECTION_THRESHOLD [{}].\" , serviceOnConnections . size ( ) , CONNECTION_THRESHOLD ) ; } } for ( Connection offConn : serviceOffConnections ) { if ( offConn . isFine ( ) ) { offConn . close ( ) ; } } } } } catch ( Exception e ) { logger . error ( \"ScheduledDisconnectStrategy monitor error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "close the connection of the fresh select connections [CODESPLIT] private void closeFreshSelectConnections ( Connection lastSelectConnect , List < Connection > serviceOffConnections ) throws InterruptedException { if ( null != lastSelectConnect ) { if ( lastSelectConnect . isInvokeFutureMapFinish ( ) ) { serviceOffConnections . add ( lastSelectConnect ) ; } else { Thread . sleep ( RETRY_DETECT_PERIOD ) ; if ( lastSelectConnect . isInvokeFutureMapFinish ( ) ) { serviceOffConnections . add ( lastSelectConnect ) ; } else { if ( logger . isInfoEnabled ( ) ) { logger . info ( \"Address={} won't close at this schedule turn\" , RemotingUtil . parseRemoteAddress ( lastSelectConnect . getChannel ( ) ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Handle the request ( s ) . [CODESPLIT] private void handle ( final RemotingContext ctx , final Object msg ) { try { if ( msg instanceof List ) { final Runnable handleTask = new Runnable ( ) { @ Override public void run ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Batch message! size={}\" , ( ( List < ? > ) msg ) . size ( ) ) ; } for ( final Object m : ( List < ? > ) msg ) { RpcCommandHandler . this . process ( ctx , m ) ; } } } ; if ( RpcConfigManager . dispatch_msg_list_in_default_executor ( ) ) { // If msg is list ,then the batch submission to biz threadpool can save io thread. // See com.alipay.remoting.decoder.ProtocolDecoder processorManager . getDefaultExecutor ( ) . execute ( handleTask ) ; } else { handleTask . run ( ) ; } } else { process ( ctx , msg ) ; } } catch ( final Throwable t ) { processException ( ctx , msg , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Return error command if necessary . [CODESPLIT] private void processExceptionForSingleCommand ( RemotingContext ctx , Object msg , Throwable t ) { final int id = ( ( RpcCommand ) msg ) . getId ( ) ; final String emsg = \"Exception caught when processing \" + ( ( msg instanceof RequestCommand ) ? \"request, id=\" : \"response, id=\" ) ; logger . warn ( emsg + id , t ) ; if ( msg instanceof RequestCommand ) { final RequestCommand cmd = ( RequestCommand ) msg ; if ( cmd . getType ( ) != RpcCommandType . REQUEST_ONEWAY ) { if ( t instanceof RejectedExecutionException ) { final ResponseCommand response = this . commandFactory . createExceptionResponse ( id , ResponseStatus . SERVER_THREADPOOL_BUSY ) ; // RejectedExecutionException here assures no response has been sent back // Other exceptions should be processed where exception was caught, because here we don't known whether ack had been sent back. ctx . getChannelContext ( ) . writeAndFlush ( response ) . addListener ( new ChannelFutureListener ( ) { @ Override public void operationComplete ( ChannelFuture future ) throws Exception { if ( future . isSuccess ( ) ) { if ( logger . isInfoEnabled ( ) ) { logger . info ( \"Write back exception response done, requestId={}, status={}\" , id , response . getResponseStatus ( ) ) ; } } else { logger . error ( \"Write back exception response failed, requestId={}\" , id , future . cause ( ) ) ; } } } ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "~~~ public helper methods to retrieve system property [CODESPLIT] public static boolean getBool ( String key , String defaultValue ) { return Boolean . parseBoolean ( System . getProperty ( key , defaultValue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize according to mask . <ol > <li > If mask < = { @link RpcDeserializeLevel#DESERIALIZE_CLAZZ } only deserialize clazz - only one part . < / li > <li > If mask < = { @link RpcDeserializeLevel#DESERIALIZE_HEADER } deserialize clazz and header - two parts . < / li > <li > If mask < = { @link RpcDeserializeLevel#DESERIALIZE_ALL } deserialize clazz header and content - all three parts . < / li > < / ol > [CODESPLIT] public void deserialize ( long mask ) throws DeserializationException { if ( mask <= RpcDeserializeLevel . DESERIALIZE_CLAZZ ) { this . deserializeClazz ( ) ; } else if ( mask <= RpcDeserializeLevel . DESERIALIZE_HEADER ) { this . deserializeClazz ( ) ; this . deserializeHeader ( this . getInvokeContext ( ) ) ; } else if ( mask <= RpcDeserializeLevel . DESERIALIZE_ALL ) { this . deserialize ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Getter method for property <tt > customSerializer< / tt > . [CODESPLIT] public CustomSerializer getCustomSerializer ( ) { if ( this . customSerializer != null ) { return customSerializer ; } if ( this . requestClass != null ) { this . customSerializer = CustomSerializerManager . getCustomSerializer ( this . requestClass ) ; } if ( this . customSerializer == null ) { this . customSerializer = CustomSerializerManager . getCustomSerializer ( this . getCmdCode ( ) ) ; } return this . customSerializer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setter method for property <tt > listener< / tt > . [CODESPLIT] public void setConnectionEventListener ( ConnectionEventListener listener ) { if ( listener != null ) { this . eventListener = listener ; if ( this . eventExecutor == null ) { this . eventExecutor = new ConnectionEventExecutor ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "print info log [CODESPLIT] private void infoLog ( String format , String addr ) { if ( logger . isInfoEnabled ( ) ) { if ( StringUtils . isNotEmpty ( addr ) ) { logger . info ( format , addr ) ; } else { logger . info ( format , \"UNKNOWN-ADDR\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "whether this request already timeout [CODESPLIT] public boolean isRequestTimeout ( ) { if ( this . timeout > 0 && ( this . rpcCommandType != RpcCommandType . REQUEST_ONEWAY ) && ( System . currentTimeMillis ( ) - this . arriveTimestamp ) > this . timeout ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get user processor for class name . [CODESPLIT] public UserProcessor < ? > getUserProcessor ( String className ) { return StringUtils . isBlank ( className ) ? null : this . userProcessors . get ( className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get one connection randomly [CODESPLIT] private Connection randomGet ( List < Connection > conns ) { if ( null == conns || conns . isEmpty ( ) ) { return null ; } int size = conns . size ( ) ; int tries = 0 ; Connection result = null ; while ( ( result == null || ! result . isFine ( ) ) && tries ++ < MAX_TIMES ) { result = conns . get ( this . random . nextInt ( size ) ) ; } if ( result != null && ! result . isFine ( ) ) { result = null ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Getter method for property <tt > customSerializer< / tt > . [CODESPLIT] public CustomSerializer getCustomSerializer ( ) { if ( this . customSerializer != null ) { return customSerializer ; } if ( this . responseClass != null ) { this . customSerializer = CustomSerializerManager . getCustomSerializer ( this . responseClass ) ; } if ( this . customSerializer == null ) { this . customSerializer = CustomSerializerManager . getCustomSerializer ( this . getCmdCode ( ) ) ; } return this . customSerializer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T get ( String key ) { return ( T ) this . context . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get and use default if not found [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T get ( String key , T defaultIfNotFound ) { return this . context . get ( key ) != null ? ( T ) this . context . get ( key ) : defaultIfNotFound ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get property value according to property key [CODESPLIT] public String getProperty ( String key ) { if ( properties == null ) { return null ; } return properties . getProperty ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute CRC32 code for byte [] . [CODESPLIT] public static final int crc32 ( byte [ ] array , int offset , int length ) { CRC32 crc32 = CRC_32_THREAD_LOCAL . get ( ) ; crc32 . update ( array , offset , length ) ; int ret = ( int ) crc32 . getValue ( ) ; crc32 . reset ( ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyze the response command and generate the response object . [CODESPLIT] public static Object resolveResponseObject ( ResponseCommand responseCommand , String addr ) throws RemotingException { preProcess ( responseCommand , addr ) ; if ( responseCommand . getResponseStatus ( ) == ResponseStatus . SUCCESS ) { return toResponseObject ( responseCommand ) ; } else { String msg = String . format ( \"Rpc invocation exception: %s, the address is %s, id=%s\" , responseCommand . getResponseStatus ( ) , addr , responseCommand . getId ( ) ) ; logger . warn ( msg ) ; if ( responseCommand . getCause ( ) != null ) { throw new InvokeException ( msg , responseCommand . getCause ( ) ) ; } else { throw new InvokeException ( msg + \", please check the server log for more.\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert remoting response command to application response object . [CODESPLIT] private static Object toResponseObject ( ResponseCommand responseCommand ) throws CodecException { RpcResponseCommand response = ( RpcResponseCommand ) responseCommand ; response . deserialize ( ) ; return response . getResponseObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert remoting response command to throwable if it is a throwable otherwise return null . [CODESPLIT] private static Throwable toThrowable ( ResponseCommand responseCommand ) throws CodecException { RpcResponseCommand resp = ( RpcResponseCommand ) responseCommand ; resp . deserialize ( ) ; Object ex = resp . getResponseObject ( ) ; if ( ex != null && ex instanceof Throwable ) { return ( Throwable ) ex ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detail your error msg with the error msg returned from response command [CODESPLIT] private static String detailErrMsg ( String clientErrMsg , ResponseCommand responseCommand ) { RpcResponseCommand resp = ( RpcResponseCommand ) responseCommand ; if ( StringUtils . isNotBlank ( resp . getErrorMsg ( ) ) ) { return String . format ( \"%s, ServerErrorMsg:%s\" , clientErrMsg , resp . getErrorMsg ( ) ) ; } else { return String . format ( \"%s, ServerErrorMsg:null\" , clientErrMsg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create server exception using error msg and fill the stack trace using the stack trace of throwable . [CODESPLIT] private RpcServerException createServerException ( Throwable t , String errMsg ) { String formattedErrMsg = String . format ( \"[Server]OriginErrorMsg: %s: %s. AdditionalErrorMsg: %s\" , t . getClass ( ) . getName ( ) , t . getMessage ( ) , errMsg ) ; RpcServerException e = new RpcServerException ( formattedErrMsg ) ; e . setStackTrace ( t . getStackTrace ( ) ) ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "print trace log [CODESPLIT] public static void printConnectionTraceLog ( Logger logger , String traceId , InvokeContext invokeContext ) { String sourceIp = invokeContext . get ( InvokeContext . CLIENT_LOCAL_IP ) ; Integer sourcePort = invokeContext . get ( InvokeContext . CLIENT_LOCAL_PORT ) ; String targetIp = invokeContext . get ( InvokeContext . CLIENT_REMOTE_IP ) ; Integer targetPort = invokeContext . get ( InvokeContext . CLIENT_REMOTE_PORT ) ; StringBuilder logMsg = new StringBuilder ( ) ; logMsg . append ( traceId ) . append ( \",\" ) ; logMsg . append ( sourceIp ) . append ( \",\" ) ; logMsg . append ( sourcePort ) . append ( \",\" ) ; logMsg . append ( targetIp ) . append ( \",\" ) ; logMsg . append ( targetPort ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( logMsg . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the right event loop according to current platform and system property fallback to NIO when epoll not enabled . [CODESPLIT] public static EventLoopGroup newEventLoopGroup ( int nThreads , ThreadFactory threadFactory ) { return epollEnabled ? new EpollEventLoopGroup ( nThreads , threadFactory ) : new NioEventLoopGroup ( nThreads , threadFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use { [CODESPLIT] public static void enableTriggeredMode ( ServerBootstrap serverBootstrap ) { if ( epollEnabled ) { if ( ConfigManager . netty_epoll_lt_enabled ( ) ) { serverBootstrap . childOption ( EpollChannelOption . EPOLL_MODE , EpollMode . LEVEL_TRIGGERED ) ; } else { serverBootstrap . childOption ( EpollChannelOption . EPOLL_MODE , EpollMode . EDGE_TRIGGERED ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start! [CODESPLIT] public void start ( ) { scheduledService . scheduleWithFixedDelay ( new Runnable ( ) { @ Override public void run ( ) { for ( Scannable scanned : scanList ) { try { scanned . scan ( ) ; } catch ( Throwable t ) { logger . error ( \"Exception caught when scannings.\" , t ) ; } } } } , 10000 , 10000 , TimeUnit . MILLISECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the remote address of the channel . [CODESPLIT] public static String parseRemoteAddress ( final Channel channel ) { if ( null == channel ) { return StringUtils . EMPTY ; } final SocketAddress remote = channel . remoteAddress ( ) ; return doParse ( remote != null ? remote . toString ( ) . trim ( ) : StringUtils . EMPTY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the local address of the channel . [CODESPLIT] public static String parseLocalAddress ( final Channel channel ) { if ( null == channel ) { return StringUtils . EMPTY ; } final SocketAddress local = channel . localAddress ( ) ; return doParse ( local != null ? local . toString ( ) . trim ( ) : StringUtils . EMPTY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the remote host ip of the channel . [CODESPLIT] public static String parseRemoteIP ( final Channel channel ) { if ( null == channel ) { return StringUtils . EMPTY ; } final InetSocketAddress remote = ( InetSocketAddress ) channel . remoteAddress ( ) ; if ( remote != null ) { return remote . getAddress ( ) . getHostAddress ( ) ; } return StringUtils . EMPTY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the remote hostname of the channel . [CODESPLIT] public static String parseRemoteHostName ( final Channel channel ) { if ( null == channel ) { return StringUtils . EMPTY ; } final InetSocketAddress remote = ( InetSocketAddress ) channel . remoteAddress ( ) ; if ( remote != null ) { return remote . getAddress ( ) . getHostName ( ) ; } return StringUtils . EMPTY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the local host ip of the channel . [CODESPLIT] public static String parseLocalIP ( final Channel channel ) { if ( null == channel ) { return StringUtils . EMPTY ; } final InetSocketAddress local = ( InetSocketAddress ) channel . localAddress ( ) ; if ( local != null ) { return local . getAddress ( ) . getHostAddress ( ) ; } return StringUtils . EMPTY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the remote host port of the channel . [CODESPLIT] public static int parseRemotePort ( final Channel channel ) { if ( null == channel ) { return - 1 ; } final InetSocketAddress remote = ( InetSocketAddress ) channel . remoteAddress ( ) ; if ( remote != null ) { return remote . getPort ( ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the local host port of the channel . [CODESPLIT] public static int parseLocalPort ( final Channel channel ) { if ( null == channel ) { return - 1 ; } final InetSocketAddress local = ( InetSocketAddress ) channel . localAddress ( ) ; if ( local != null ) { return local . getPort ( ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the socket address omit the leading / if present . [CODESPLIT] public static String parseSocketAddressToString ( SocketAddress socketAddress ) { if ( socketAddress != null ) { return doParse ( socketAddress . toString ( ) . trim ( ) ) ; } return StringUtils . EMPTY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the host ip of socket address . [CODESPLIT] public static String parseSocketAddressToHostIp ( SocketAddress socketAddress ) { final InetSocketAddress addrs = ( InetSocketAddress ) socketAddress ; if ( addrs != null ) { InetAddress addr = addrs . getAddress ( ) ; if ( null != addr ) { return addr . getHostAddress ( ) ; } } return StringUtils . EMPTY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<ol > <li > if an address starts with a / skip it . <li > if an address contains a / substring it . < / ol > [CODESPLIT] private static String doParse ( String addr ) { if ( StringUtils . isBlank ( addr ) ) { return StringUtils . EMPTY ; } if ( addr . charAt ( 0 ) == ' ' ) { return addr . substring ( 1 ) ; } else { int len = addr . length ( ) ; for ( int i = 1 ; i < len ; ++ i ) { if ( addr . charAt ( i ) == ' ' ) { return addr . substring ( i + 1 ) ; } } return addr ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a connection [CODESPLIT] public void add ( Connection connection ) { markAccess ( ) ; if ( null == connection ) { return ; } boolean res = this . conns . addIfAbsent ( connection ) ; if ( res ) { connection . increaseRef ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "removeAndTryClose a connection [CODESPLIT] public void removeAndTryClose ( Connection connection ) { if ( null == connection ) { return ; } boolean res = this . conns . remove ( connection ) ; if ( res ) { connection . decreaseRef ( ) ; } if ( connection . noRef ( ) ) { connection . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a connection [CODESPLIT] public Connection get ( ) { markAccess ( ) ; if ( null != this . conns ) { List < Connection > snapshot = new ArrayList < Connection > ( this . conns ) ; if ( snapshot . size ( ) > 0 ) { return this . strategy . select ( snapshot ) ; } else { return null ; } } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register custom serializer for class name . [CODESPLIT] public static void registerCustomSerializer ( String className , CustomSerializer serializer ) { CustomSerializer prevSerializer = classCustomSerializer . putIfAbsent ( className , serializer ) ; if ( prevSerializer != null ) { throw new RuntimeException ( \"CustomSerializer has been registered for class: \" + className + \", the custom serializer is: \" + prevSerializer . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the custom serializer for class name . [CODESPLIT] public static CustomSerializer getCustomSerializer ( String className ) { if ( ! classCustomSerializer . isEmpty ( ) ) { return classCustomSerializer . get ( className ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register custom serializer for command code . [CODESPLIT] public static void registerCustomSerializer ( CommandCode code , CustomSerializer serializer ) { CustomSerializer prevSerializer = commandCustomSerializer . putIfAbsent ( code , serializer ) ; if ( prevSerializer != null ) { throw new RuntimeException ( \"CustomSerializer has been registered for command code: \" + code + \", the custom serializer is: \" + prevSerializer . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the custom serializer for command code . [CODESPLIT] public static CustomSerializer getCustomSerializer ( CommandCode code ) { if ( ! commandCustomSerializer . isEmpty ( ) ) { return commandCustomSerializer . get ( code ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start schedule task [CODESPLIT] public void start ( ) { /** initial delay to execute schedule task, unit: ms */ long initialDelay = ConfigManager . conn_monitor_initial_delay ( ) ; /** period of schedule task, unit: ms*/ long period = ConfigManager . conn_monitor_period ( ) ; this . executor = new ScheduledThreadPoolExecutor ( 1 , new NamedThreadFactory ( \"ConnectionMonitorThread\" , true ) , new ThreadPoolExecutor . AbortPolicy ( ) ) ; MonitorTask monitorTask = new MonitorTask ( ) ; this . executor . scheduleAtFixedRate ( monitorTask , initialDelay , period , TimeUnit . MILLISECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notice : only { @link GlobalSwitch#SERVER_MANAGE_CONNECTION_SWITCH } switch on will close all connections . [CODESPLIT] @ Override protected boolean doStop ( ) { if ( null != this . channelFuture ) { this . channelFuture . channel ( ) . close ( ) ; } if ( this . switches ( ) . isOn ( GlobalSwitch . SERVER_SYNC_STOP ) ) { this . bossGroup . shutdownGracefully ( ) . awaitUninterruptibly ( ) ; } else { this . bossGroup . shutdownGracefully ( ) ; } if ( this . switches ( ) . isOn ( GlobalSwitch . SERVER_MANAGE_CONNECTION_SWITCH ) && null != this . connectionManager ) { this . connectionManager . removeAll ( ) ; logger . warn ( \"Close all connections from server side!\" ) ; } logger . warn ( \"Rpc Server stopped!\" ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One way invocation with a { @link InvokeContext } common api notice please see { @link #oneway ( String Object ) } [CODESPLIT] public void oneway ( final String addr , final Object request , final InvokeContext invokeContext ) throws RemotingException , InterruptedException { check ( ) ; this . rpcRemoting . oneway ( addr , request , invokeContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One way invocation using a parsed { @link Url } <br > <p > Notice : <br > <ol > <li > <b > DO NOT modify the request object concurrently when this method is called . < / b > < / li > <li > When do invocation use the parsed { @link Url } to find a available client connection if none then throw exception< / li > < / ol > [CODESPLIT] public void oneway ( final Url url , final Object request ) throws RemotingException , InterruptedException { check ( ) ; this . rpcRemoting . oneway ( url , request , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One way invocation with a { @link InvokeContext } common api notice please see { @link #oneway ( Url Object ) } [CODESPLIT] public void oneway ( final Url url , final Object request , final InvokeContext invokeContext ) throws RemotingException , InterruptedException { check ( ) ; this . rpcRemoting . oneway ( url , request , invokeContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Future invocation using a string address address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2 <br > You can get result use the returned { @link RpcResponseFuture } . <p > Notice : <br > <ol > <li > <b > DO NOT modify the request object concurrently when this method is called . < / b > < / li > <li > When do invocation use the string address to find a available client connection if none then throw exception< / li > <li > Unlike rpc client address arguments takes no effect here for rpc server will not create connection . < / li > < / ol > [CODESPLIT] public RpcResponseFuture invokeWithFuture ( final String addr , final Object request , final int timeoutMillis ) throws RemotingException , InterruptedException { check ( ) ; return this . rpcRemoting . invokeWithFuture ( addr , request , null , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Future invocation with a { @link InvokeContext } common api notice please see { @link #invokeWithFuture ( String Object int ) } [CODESPLIT] public RpcResponseFuture invokeWithFuture ( final String addr , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { check ( ) ; return this . rpcRemoting . invokeWithFuture ( addr , request , invokeContext , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Future invocation using a parsed { @link Url } <br > You can get result use the returned { @link RpcResponseFuture } . <p > Notice : <br > <ol > <li > <b > DO NOT modify the request object concurrently when this method is called . < / b > < / li > <li > When do invocation use the parsed { @link Url } to find a available client connection if none then throw exception< / li > < / ol > [CODESPLIT] public RpcResponseFuture invokeWithFuture ( final Url url , final Object request , final int timeoutMillis ) throws RemotingException , InterruptedException { check ( ) ; return this . rpcRemoting . invokeWithFuture ( url , request , null , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Future invocation with a { @link InvokeContext } common api notice please see { @link #invokeWithFuture ( Url Object int ) } [CODESPLIT] public RpcResponseFuture invokeWithFuture ( final Url url , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException , InterruptedException { check ( ) ; return this . rpcRemoting . invokeWithFuture ( url , request , invokeContext , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Future invocation with a { @link InvokeContext } common api notice please see { @link #invokeWithFuture ( Connection Object int ) } [CODESPLIT] public RpcResponseFuture invokeWithFuture ( final Connection conn , final Object request , final InvokeContext invokeContext , final int timeoutMillis ) throws RemotingException { return this . rpcRemoting . invokeWithFuture ( conn , request , invokeContext , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback invocation using a string address address format example - 127 . 0 . 0 . 1 : 12200?key1 = value1&key2 = value2 <br > You can specify an implementation of { @link InvokeCallback } to get the result . <p > Notice : <br > <ol > <li > <b > DO NOT modify the request object concurrently when this method is called . < / b > < / li > <li > When do invocation use the string address to find a available client connection if none then throw exception< / li > <li > Unlike rpc client address arguments takes no effect here for rpc server will not create connection . < / li > < / ol > [CODESPLIT] public void invokeWithCallback ( final String addr , final Object request , final InvokeCallback invokeCallback , final int timeoutMillis ) throws RemotingException , InterruptedException { check ( ) ; this . rpcRemoting . invokeWithCallback ( addr , request , null , invokeCallback , timeoutMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check whether a client address connected [CODESPLIT] public boolean isConnected ( String remoteAddr ) { Url url = this . rpcRemoting . addressParser . parse ( remoteAddr ) ; return this . isConnected ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check whether a { @link Url } connected [CODESPLIT] public boolean isConnected ( Url url ) { Connection conn = this . rpcRemoting . connectionManager . get ( url . getUniqueKey ( ) ) ; if ( null != conn ) { return conn . isFine ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init netty write buffer water mark [CODESPLIT] private void initWriteBufferWaterMark ( ) { int lowWaterMark = this . netty_buffer_low_watermark ( ) ; int highWaterMark = this . netty_buffer_high_watermark ( ) ; if ( lowWaterMark > highWaterMark ) { throw new IllegalArgumentException ( String . format ( \"[server side] bolt netty high water mark {%s} should not be smaller than low water mark {%s} bytes)\" , highWaterMark , lowWaterMark ) ) ; } else { logger . warn ( \"[server side] bolt netty low water mark is {} bytes, high water mark is {} bytes\" , lowWaterMark , highWaterMark ) ; } this . bootstrap . childOption ( ChannelOption . WRITE_BUFFER_WATER_MARK , new WriteBufferWaterMark ( lowWaterMark , highWaterMark ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the provided BytebBuffer contains a valid utf8 encoded string . <p > Using the algorithm Flexible and Economical UTF - 8 Decoder by Björn Höhrmann ( http : // bjoern . hoehrmann . de / utf - 8 / decoder / dfa / ) [CODESPLIT] public static boolean isValidUTF8 ( ByteBuffer data , int off ) { int len = data . remaining ( ) ; if ( len < off ) { return false ; } int state = 0 ; for ( int i = off ; i < len ; ++ i ) { state = utf8d [ 256 + ( state << 4 ) + utf8d [ ( 0xff & data . get ( i ) ) ] ] ; if ( state == 1 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a frame with a specific opcode [CODESPLIT] public static FramedataImpl1 get ( Opcode opcode ) { if ( opcode == null ) { throw new IllegalArgumentException ( \"Supplied opcode cannot be null\" ) ; } switch ( opcode ) { case PING : return new PingFrame ( ) ; case PONG : return new PongFrame ( ) ; case TEXT : return new TextFrame ( ) ; case BINARY : return new BinaryFrame ( ) ; case CLOSING : return new CloseFrame ( ) ; case CONTINUOUS : return new ContinuousFrame ( ) ; default : throw new IllegalArgumentException ( \"Supplied opcode is invalid\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the whole outQueue has been flushed [CODESPLIT] public static boolean batch ( WebSocketImpl ws , ByteChannel sockchannel ) throws IOException { if ( ws == null ) { return false ; } ByteBuffer buffer = ws . outQueue . peek ( ) ; WrappedByteChannel c = null ; if ( buffer == null ) { if ( sockchannel instanceof WrappedByteChannel ) { c = ( WrappedByteChannel ) sockchannel ; if ( c . isNeedWrite ( ) ) { c . writeMore ( ) ; } } } else { do { // FIXME writing as much as possible is unfair!! /*int written = */ sockchannel . write ( buffer ) ; if ( buffer . remaining ( ) > 0 ) { return false ; } else { ws . outQueue . poll ( ) ; // Buffer finished. Remove it. buffer = ws . outQueue . peek ( ) ; } } while ( buffer != null ) ; } if ( ws . outQueue . isEmpty ( ) && ws . isFlushAndClose ( ) && ws . getDraft ( ) != null && ws . getDraft ( ) . getRole ( ) != null && ws . getDraft ( ) . getRole ( ) == Role . SERVER ) { // ws . closeConnection ( ) ; } return c == null || ! ( ( WrappedByteChannel ) sockchannel ) . isNeedWrite ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the close code for this close frame [CODESPLIT] public void setCode ( int code ) { this . code = code ; // CloseFrame.TLS_ERROR is not allowed to be transfered over the wire if ( code == CloseFrame . TLS_ERROR ) { this . code = CloseFrame . NOCODE ; this . reason = \"\" ; } updatePayload ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the payload to valid utf8 [CODESPLIT] private void validateUtf8 ( ByteBuffer payload , int mark ) throws InvalidDataException { try { payload . position ( payload . position ( ) + 2 ) ; reason = Charsetfunctions . stringUtf8 ( payload ) ; } catch ( IllegalArgumentException e ) { throw new InvalidDataException ( CloseFrame . NO_UTF8 ) ; } finally { payload . position ( mark ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the payload to represent the close code and the reason [CODESPLIT] private void updatePayload ( ) { byte [ ] by = Charsetfunctions . utf8Bytes ( reason ) ; ByteBuffer buf = ByteBuffer . allocate ( 4 ) ; buf . putInt ( code ) ; buf . position ( 2 ) ; ByteBuffer pay = ByteBuffer . allocate ( 2 + by . length ) ; pay . put ( buf ) ; pay . put ( by ) ; pay . rewind ( ) ; super . setPayload ( pay ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the requested protocol is part of this draft [CODESPLIT] private HandshakeState containsRequestedProtocol ( String requestedProtocol ) { for ( IProtocol knownProtocol : knownProtocols ) { if ( knownProtocol . acceptProvidedProtocol ( requestedProtocol ) ) { protocol = knownProtocol ; log . trace ( \"acceptHandshake - Matching protocol found: {}\" , protocol ) ; return HandshakeState . MATCHED ; } } return HandshakeState . NOT_MATCHED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translate the buffer depending when it has an extended payload length ( 126 or 127 ) [CODESPLIT] private TranslatedPayloadMetaData translateSingleFramePayloadLength ( ByteBuffer buffer , Opcode optcode , int oldPayloadlength , int maxpacketsize , int oldRealpacketsize ) throws InvalidFrameException , IncompleteException , LimitExceededException { int payloadlength = oldPayloadlength , realpacketsize = oldRealpacketsize ; if ( optcode == Opcode . PING || optcode == Opcode . PONG || optcode == Opcode . CLOSING ) { log . trace ( \"Invalid frame: more than 125 octets\" ) ; throw new InvalidFrameException ( \"more than 125 octets\" ) ; } if ( payloadlength == 126 ) { realpacketsize += 2 ; // additional length bytes translateSingleFrameCheckPacketSize ( maxpacketsize , realpacketsize ) ; byte [ ] sizebytes = new byte [ 3 ] ; sizebytes [ 1 ] = buffer . get ( /*1 + 1*/ ) ; sizebytes [ 2 ] = buffer . get ( /*1 + 2*/ ) ; payloadlength = new BigInteger ( sizebytes ) . intValue ( ) ; } else { realpacketsize += 8 ; // additional length bytes translateSingleFrameCheckPacketSize ( maxpacketsize , realpacketsize ) ; byte [ ] bytes = new byte [ 8 ] ; for ( int i = 0 ; i < 8 ; i ++ ) { bytes [ i ] = buffer . get ( /*1 + i*/ ) ; } long length = new BigInteger ( bytes ) . longValue ( ) ; translateSingleFrameCheckLengthLimit ( length ) ; payloadlength = ( int ) length ; } return new TranslatedPayloadMetaData ( payloadlength , realpacketsize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the frame size exceeds the allowed limit [CODESPLIT] private void translateSingleFrameCheckLengthLimit ( long length ) throws LimitExceededException { if ( length > Integer . MAX_VALUE ) { log . trace ( \"Limit exedeed: Payloadsize is to big...\" ) ; throw new LimitExceededException ( \"Payloadsize is to big...\" ) ; } if ( length > maxFrameSize ) { log . trace ( \"Payload limit reached. Allowed: {} Current: {}\" , maxFrameSize , length ) ; throw new LimitExceededException ( \"Payload limit reached.\" , maxFrameSize ) ; } if ( length < 0 ) { log . trace ( \"Limit underflow: Payloadsize is to little...\" ) ; throw new LimitExceededException ( \"Payloadsize is to little...\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the max packet size is smaller than the real packet size [CODESPLIT] private void translateSingleFrameCheckPacketSize ( int maxpacketsize , int realpacketsize ) throws IncompleteException { if ( maxpacketsize < realpacketsize ) { log . trace ( \"Incomplete frame: maxpacketsize < realpacketsize\" ) ; throw new IncompleteException ( realpacketsize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a final key from a input string [CODESPLIT] private String generateFinalKey ( String in ) { String seckey = in . trim ( ) ; String acc = seckey + \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\" ; MessageDigest sh1 ; try { sh1 = MessageDigest . getInstance ( \"SHA1\" ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( e ) ; } return Base64 . encodeBytes ( sh1 . digest ( acc . getBytes ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the frame if it is a continuous frame or the fin bit is not set [CODESPLIT] private void processFrameContinuousAndNonFin ( WebSocketImpl webSocketImpl , Framedata frame , Opcode curop ) throws InvalidDataException { if ( curop != Opcode . CONTINUOUS ) { processFrameIsNotFin ( frame ) ; } else if ( frame . isFin ( ) ) { processFrameIsFin ( webSocketImpl , frame ) ; } else if ( currentContinuousFrame == null ) { log . error ( \"Protocol error: Continuous frame sequence was not started.\" ) ; throw new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , \"Continuous frame sequence was not started.\" ) ; } //Check if the whole payload is valid utf8, when the opcode indicates a text if ( curop == Opcode . TEXT && ! Charsetfunctions . isValidUTF8 ( frame . getPayloadData ( ) ) ) { log . error ( \"Protocol error: Payload is not UTF8\" ) ; throw new InvalidDataException ( CloseFrame . NO_UTF8 ) ; } //Checking if the current continuous frame contains a correct payload with the other frames combined if ( curop == Opcode . CONTINUOUS && currentContinuousFrame != null ) { addToBufferList ( frame . getPayloadData ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the frame if it is a binary frame [CODESPLIT] private void processFrameBinary ( WebSocketImpl webSocketImpl , Framedata frame ) { try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , frame . getPayloadData ( ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the runtime exception to the specific WebSocketImpl [CODESPLIT] private void logRuntimeException ( WebSocketImpl webSocketImpl , RuntimeException e ) { log . error ( \"Runtime exception during onWebsocketMessage\" , e ) ; webSocketImpl . getWebSocketListener ( ) . onWebsocketError ( webSocketImpl , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the frame if it is a text frame [CODESPLIT] private void processFrameText ( WebSocketImpl webSocketImpl , Framedata frame ) throws InvalidDataException { try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , Charsetfunctions . stringUtf8 ( frame . getPayloadData ( ) ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the frame if it is the last frame [CODESPLIT] private void processFrameIsFin ( WebSocketImpl webSocketImpl , Framedata frame ) throws InvalidDataException { if ( currentContinuousFrame == null ) { log . trace ( \"Protocol error: Previous continuous frame sequence not completed.\" ) ; throw new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , \"Continuous frame sequence was not started.\" ) ; } addToBufferList ( frame . getPayloadData ( ) ) ; checkBufferLimit ( ) ; if ( currentContinuousFrame . getOpcode ( ) == Opcode . TEXT ) { ( ( FramedataImpl1 ) currentContinuousFrame ) . setPayload ( getPayloadFromByteBufferList ( ) ) ; ( ( FramedataImpl1 ) currentContinuousFrame ) . isValid ( ) ; try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , Charsetfunctions . stringUtf8 ( currentContinuousFrame . getPayloadData ( ) ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; } } else if ( currentContinuousFrame . getOpcode ( ) == Opcode . BINARY ) { ( ( FramedataImpl1 ) currentContinuousFrame ) . setPayload ( getPayloadFromByteBufferList ( ) ) ; ( ( FramedataImpl1 ) currentContinuousFrame ) . isValid ( ) ; try { webSocketImpl . getWebSocketListener ( ) . onWebsocketMessage ( webSocketImpl , currentContinuousFrame . getPayloadData ( ) ) ; } catch ( RuntimeException e ) { logRuntimeException ( webSocketImpl , e ) ; } } currentContinuousFrame = null ; clearBufferList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the frame if it is not the last frame [CODESPLIT] private void processFrameIsNotFin ( Framedata frame ) throws InvalidDataException { if ( currentContinuousFrame != null ) { log . trace ( \"Protocol error: Previous continuous frame sequence not completed.\" ) ; throw new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , \"Previous continuous frame sequence not completed.\" ) ; } currentContinuousFrame = frame ; addToBufferList ( frame . getPayloadData ( ) ) ; checkBufferLimit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the frame if it is a closing frame [CODESPLIT] private void processFrameClosing ( WebSocketImpl webSocketImpl , Framedata frame ) { int code = CloseFrame . NOCODE ; String reason = \"\" ; if ( frame instanceof CloseFrame ) { CloseFrame cf = ( CloseFrame ) frame ; code = cf . getCloseCode ( ) ; reason = cf . getMessage ( ) ; } if ( webSocketImpl . getReadyState ( ) == ReadyState . CLOSING ) { // complete the close handshake by disconnecting webSocketImpl . closeConnection ( code , reason , true ) ; } else { // echo close handshake if ( getCloseHandshakeType ( ) == CloseHandshakeType . TWOWAY ) webSocketImpl . close ( code , reason , true ) ; else webSocketImpl . flushAndClose ( code , reason , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the current size of the buffer and throw an exception if the size is bigger than the max allowed frame size [CODESPLIT] private void checkBufferLimit ( ) throws LimitExceededException { long totalSize = getByteBufferListSize ( ) ; if ( totalSize > maxFrameSize ) { clearBufferList ( ) ; log . trace ( \"Payload limit reached. Allowed: {} Current: {}\" , maxFrameSize , totalSize ) ; throw new LimitExceededException ( maxFrameSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to generate a full bytebuffer out of all the fragmented frame payload [CODESPLIT] private ByteBuffer getPayloadFromByteBufferList ( ) throws LimitExceededException { long totalSize = 0 ; ByteBuffer resultingByteBuffer ; synchronized ( byteBufferList ) { for ( ByteBuffer buffer : byteBufferList ) { totalSize += buffer . limit ( ) ; } checkBufferLimit ( ) ; resultingByteBuffer = ByteBuffer . allocate ( ( int ) totalSize ) ; for ( ByteBuffer buffer : byteBufferList ) { resultingByteBuffer . put ( buffer ) ; } } resultingByteBuffer . flip ( ) ; return resultingByteBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current size of the resulting bytebuffer in the bytebuffer list [CODESPLIT] private long getByteBufferListSize ( ) { long totalSize = 0 ; synchronized ( byteBufferList ) { for ( ByteBuffer buffer : byteBufferList ) { totalSize += buffer . limit ( ) ; } } return totalSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements the handshake protocol between two peers required for the establishment of the SSL / TLS connection . During the handshake encryption configuration information - such as the list of available cipher suites - will be exchanged and if the handshake is successful will lead to an established SSL / TLS session . <p > <p / > A typical handshake will usually contain the following steps : <p > <ul > <li > 1 . wrap : ClientHello< / li > <li > 2 . unwrap : ServerHello / Cert / ServerHelloDone< / li > <li > 3 . wrap : ClientKeyExchange< / li > <li > 4 . wrap : ChangeCipherSpec< / li > <li > 5 . wrap : Finished< / li > <li > 6 . unwrap : ChangeCipherSpec< / li > <li > 7 . unwrap : Finished< / li > < / ul > <p / > Handshake is also used during the end of the session in order to properly close the connection between the two peers . A proper connection close will typically include the one peer sending a CLOSE message to another and then wait for the other s CLOSE message to close the transport link . The other peer from his perspective would read a CLOSE message from his peer and then enter the handshake procedure to send his own CLOSE message as well . [CODESPLIT] private boolean doHandshake ( ) throws IOException { SSLEngineResult result ; HandshakeStatus handshakeStatus ; // NioSslPeer's fields myAppData and peerAppData are supposed to be large enough to hold all message data the peer // will send and expects to receive from the other peer respectively. Since the messages to be exchanged will usually be less // than 16KB long the capacity of these fields should also be smaller. Here we initialize these two local buffers // to be used for the handshake, while keeping client's buffers at the same size. int appBufferSize = engine . getSession ( ) . getApplicationBufferSize ( ) ; myAppData = ByteBuffer . allocate ( appBufferSize ) ; peerAppData = ByteBuffer . allocate ( appBufferSize ) ; myNetData . clear ( ) ; peerNetData . clear ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; boolean handshakeComplete = false ; while ( ! handshakeComplete ) { switch ( handshakeStatus ) { case FINISHED : handshakeComplete = ! this . peerNetData . hasRemaining ( ) ; if ( handshakeComplete ) return true ; socketChannel . write ( this . peerNetData ) ; break ; case NEED_UNWRAP : if ( socketChannel . read ( peerNetData ) < 0 ) { if ( engine . isInboundDone ( ) && engine . isOutboundDone ( ) ) { return false ; } try { engine . closeInbound ( ) ; } catch ( SSLException e ) { //Ignore, cant do anything against this exception } engine . closeOutbound ( ) ; // After closeOutbound the engine will be set to WRAP state, in order to try to send a close message to the client. handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } peerNetData . flip ( ) ; try { result = engine . unwrap ( peerNetData , peerAppData ) ; peerNetData . compact ( ) ; handshakeStatus = result . getHandshakeStatus ( ) ; } catch ( SSLException sslException ) { engine . closeOutbound ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } switch ( result . getStatus ( ) ) { case OK : break ; case BUFFER_OVERFLOW : // Will occur when peerAppData's capacity is smaller than the data derived from peerNetData's unwrap. peerAppData = enlargeApplicationBuffer ( peerAppData ) ; break ; case BUFFER_UNDERFLOW : // Will occur either when no data was read from the peer or when the peerNetData buffer was too small to hold all peer's data. peerNetData = handleBufferUnderflow ( peerNetData ) ; break ; case CLOSED : if ( engine . isOutboundDone ( ) ) { return false ; } else { engine . closeOutbound ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } default : throw new IllegalStateException ( \"Invalid SSL status: \" + result . getStatus ( ) ) ; } break ; case NEED_WRAP : myNetData . clear ( ) ; try { result = engine . wrap ( myAppData , myNetData ) ; handshakeStatus = result . getHandshakeStatus ( ) ; } catch ( SSLException sslException ) { engine . closeOutbound ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; break ; } switch ( result . getStatus ( ) ) { case OK : myNetData . flip ( ) ; while ( myNetData . hasRemaining ( ) ) { socketChannel . write ( myNetData ) ; } break ; case BUFFER_OVERFLOW : // Will occur if there is not enough space in myNetData buffer to write all the data that would be generated by the method wrap. // Since myNetData is set to session's packet size we should not get to this point because SSLEngine is supposed // to produce messages smaller or equal to that, but a general handling would be the following: myNetData = enlargePacketBuffer ( myNetData ) ; break ; case BUFFER_UNDERFLOW : throw new SSLException ( \"Buffer underflow occured after a wrap. I don't think we should ever get here.\" ) ; case CLOSED : try { myNetData . flip ( ) ; while ( myNetData . hasRemaining ( ) ) { socketChannel . write ( myNetData ) ; } // At this point the handshake status will probably be NEED_UNWRAP so we make sure that peerNetData is clear to read. peerNetData . clear ( ) ; } catch ( Exception e ) { handshakeStatus = engine . getHandshakeStatus ( ) ; } break ; default : throw new IllegalStateException ( \"Invalid SSL status: \" + result . getStatus ( ) ) ; } break ; case NEED_TASK : Runnable task ; while ( ( task = engine . getDelegatedTask ( ) ) != null ) { executor . execute ( task ) ; } handshakeStatus = engine . getHandshakeStatus ( ) ; break ; case NOT_HANDSHAKING : break ; default : throw new IllegalStateException ( \"Invalid SSL status: \" + handshakeStatus ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares <code > sessionProposedCapacity<code > with buffer s capacity . If buffer s capacity is smaller returns a buffer with the proposed capacity . If it s equal or larger returns a buffer with capacity twice the size of the initial one . [CODESPLIT] private ByteBuffer enlargeBuffer ( ByteBuffer buffer , int sessionProposedCapacity ) { if ( sessionProposedCapacity > buffer . capacity ( ) ) { buffer = ByteBuffer . allocate ( sessionProposedCapacity ) ; } else { buffer = ByteBuffer . allocate ( buffer . capacity ( ) * 2 ) ; } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles { @link SSLEngineResult . Status#BUFFER_UNDERFLOW } . Will check if the buffer is already filled and if there is no space problem will return the same buffer so the client tries to read again . If the buffer is already filled will try to enlarge the buffer either to session s proposed size or to a larger capacity . A buffer underflow can happen only after an unwrap so the buffer will always be a peerNetData buffer . [CODESPLIT] private ByteBuffer handleBufferUnderflow ( ByteBuffer buffer ) { if ( engine . getSession ( ) . getPacketBufferSize ( ) < buffer . limit ( ) ) { return buffer ; } else { ByteBuffer replaceBuffer = enlargePacketBuffer ( buffer ) ; buffer . flip ( ) ; replaceBuffer . put ( buffer ) ; return replaceBuffer ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checking the handshake for the role as server [CODESPLIT] private static HandshakeBuilder translateHandshakeHttpServer ( String [ ] firstLineTokens , String line ) throws InvalidHandshakeException { // translating/parsing the request from the CLIENT if ( ! \"GET\" . equalsIgnoreCase ( firstLineTokens [ 0 ] ) ) { throw new InvalidHandshakeException ( String . format ( \"Invalid request method received: %s Status line: %s\" , firstLineTokens [ 0 ] , line ) ) ; } if ( ! \"HTTP/1.1\" . equalsIgnoreCase ( firstLineTokens [ 2 ] ) ) { throw new InvalidHandshakeException ( String . format ( \"Invalid status line received: %s Status line: %s\" , firstLineTokens [ 2 ] , line ) ) ; } ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client ( ) ; clienthandshake . setResourceDescriptor ( firstLineTokens [ 1 ] ) ; return clienthandshake ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checking the handshake for the role as client [CODESPLIT] private static HandshakeBuilder translateHandshakeHttpClient ( String [ ] firstLineTokens , String line ) throws InvalidHandshakeException { // translating/parsing the response from the SERVER if ( ! \"101\" . equals ( firstLineTokens [ 1 ] ) ) { throw new InvalidHandshakeException ( String . format ( \"Invalid status code received: %s Status line: %s\" , firstLineTokens [ 1 ] , line ) ) ; } if ( ! \"HTTP/1.1\" . equalsIgnoreCase ( firstLineTokens [ 0 ] ) ) { throw new InvalidHandshakeException ( String . format ( \"Invalid status line received: %s Status line: %s\" , firstLineTokens [ 0 ] , line ) ) ; } HandshakeBuilder handshake = new HandshakeImpl1Server ( ) ; ServerHandshakeBuilder serverhandshake = ( ServerHandshakeBuilder ) handshake ; serverhandshake . setHttpStatus ( Short . parseShort ( firstLineTokens [ 1 ] ) ) ; serverhandshake . setHttpStatusMessage ( firstLineTokens [ 2 ] ) ; return handshake ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to decode the provided ByteBuffer [CODESPLIT] public void decode ( ByteBuffer socketBuffer ) { assert ( socketBuffer . hasRemaining ( ) ) ; log . trace ( \"process({}): ({})\" , socketBuffer . remaining ( ) , ( socketBuffer . remaining ( ) > 1000 ? \"too big to display\" : new String ( socketBuffer . array ( ) , socketBuffer . position ( ) , socketBuffer . remaining ( ) ) ) ) ; if ( readyState != ReadyState . NOT_YET_CONNECTED ) { if ( readyState == ReadyState . OPEN ) { decodeFrames ( socketBuffer ) ; } } else { if ( decodeHandshake ( socketBuffer ) && ( ! isClosing ( ) && ! isClosed ( ) ) ) { assert ( tmpHandshakeBytes . hasRemaining ( ) != socketBuffer . hasRemaining ( ) || ! socketBuffer . hasRemaining ( ) ) ; // the buffers will never have remaining bytes at the same time if ( socketBuffer . hasRemaining ( ) ) { decodeFrames ( socketBuffer ) ; } else if ( tmpHandshakeBytes . hasRemaining ( ) ) { decodeFrames ( tmpHandshakeBytes ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the handshake phase has is completed . In case of a broken handshake this will be never the case . [CODESPLIT] private boolean decodeHandshake ( ByteBuffer socketBufferNew ) { ByteBuffer socketBuffer ; if ( tmpHandshakeBytes . capacity ( ) == 0 ) { socketBuffer = socketBufferNew ; } else { if ( tmpHandshakeBytes . remaining ( ) < socketBufferNew . remaining ( ) ) { ByteBuffer buf = ByteBuffer . allocate ( tmpHandshakeBytes . capacity ( ) + socketBufferNew . remaining ( ) ) ; tmpHandshakeBytes . flip ( ) ; buf . put ( tmpHandshakeBytes ) ; tmpHandshakeBytes = buf ; } tmpHandshakeBytes . put ( socketBufferNew ) ; tmpHandshakeBytes . flip ( ) ; socketBuffer = tmpHandshakeBytes ; } socketBuffer . mark ( ) ; try { HandshakeState handshakestate ; try { if ( role == Role . SERVER ) { if ( draft == null ) { for ( Draft d : knownDrafts ) { d = d . copyInstance ( ) ; try { d . setParseMode ( role ) ; socketBuffer . reset ( ) ; Handshakedata tmphandshake = d . translateHandshake ( socketBuffer ) ; if ( ! ( tmphandshake instanceof ClientHandshake ) ) { log . trace ( \"Closing due to wrong handshake\" ) ; closeConnectionDueToWrongHandshake ( new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , \"wrong http function\" ) ) ; return false ; } ClientHandshake handshake = ( ClientHandshake ) tmphandshake ; handshakestate = d . acceptHandshakeAsServer ( handshake ) ; if ( handshakestate == HandshakeState . MATCHED ) { resourceDescriptor = handshake . getResourceDescriptor ( ) ; ServerHandshakeBuilder response ; try { response = wsl . onWebsocketHandshakeReceivedAsServer ( this , d , handshake ) ; } catch ( InvalidDataException e ) { log . trace ( \"Closing due to wrong handshake. Possible handshake rejection\" , e ) ; closeConnectionDueToWrongHandshake ( e ) ; return false ; } catch ( RuntimeException e ) { log . error ( \"Closing due to internal server error\" , e ) ; wsl . onWebsocketError ( this , e ) ; closeConnectionDueToInternalServerError ( e ) ; return false ; } write ( d . createHandshake ( d . postProcessHandshakeResponseAsServer ( handshake , response ) ) ) ; draft = d ; open ( handshake ) ; return true ; } } catch ( InvalidHandshakeException e ) { // go on with an other draft } } if ( draft == null ) { log . trace ( \"Closing due to protocol error: no draft matches\" ) ; closeConnectionDueToWrongHandshake ( new InvalidDataException ( CloseFrame . PROTOCOL_ERROR , \"no draft matches\" ) ) ; } return false ; } else { // special case for multiple step handshakes Handshakedata tmphandshake = draft . translateHandshake ( socketBuffer ) ; if ( ! ( tmphandshake instanceof ClientHandshake ) ) { log . trace ( \"Closing due to protocol error: wrong http function\" ) ; flushAndClose ( CloseFrame . PROTOCOL_ERROR , \"wrong http function\" , false ) ; return false ; } ClientHandshake handshake = ( ClientHandshake ) tmphandshake ; handshakestate = draft . acceptHandshakeAsServer ( handshake ) ; if ( handshakestate == HandshakeState . MATCHED ) { open ( handshake ) ; return true ; } else { log . trace ( \"Closing due to protocol error: the handshake did finally not match\" ) ; close ( CloseFrame . PROTOCOL_ERROR , \"the handshake did finally not match\" ) ; } return false ; } } else if ( role == Role . CLIENT ) { draft . setParseMode ( role ) ; Handshakedata tmphandshake = draft . translateHandshake ( socketBuffer ) ; if ( ! ( tmphandshake instanceof ServerHandshake ) ) { log . trace ( \"Closing due to protocol error: wrong http function\" ) ; flushAndClose ( CloseFrame . PROTOCOL_ERROR , \"wrong http function\" , false ) ; return false ; } ServerHandshake handshake = ( ServerHandshake ) tmphandshake ; handshakestate = draft . acceptHandshakeAsClient ( handshakerequest , handshake ) ; if ( handshakestate == HandshakeState . MATCHED ) { try { wsl . onWebsocketHandshakeReceivedAsClient ( this , handshakerequest , handshake ) ; } catch ( InvalidDataException e ) { log . trace ( \"Closing due to invalid data exception. Possible handshake rejection\" , e ) ; flushAndClose ( e . getCloseCode ( ) , e . getMessage ( ) , false ) ; return false ; } catch ( RuntimeException e ) { log . error ( \"Closing since client was never connected\" , e ) ; wsl . onWebsocketError ( this , e ) ; flushAndClose ( CloseFrame . NEVER_CONNECTED , e . getMessage ( ) , false ) ; return false ; } open ( handshake ) ; return true ; } else { log . trace ( \"Closing due to protocol error: draft {} refuses handshake\" , draft ) ; close ( CloseFrame . PROTOCOL_ERROR , \"draft \" + draft + \" refuses handshake\" ) ; } } } catch ( InvalidHandshakeException e ) { log . trace ( \"Closing due to invalid handshake\" , e ) ; close ( e ) ; } } catch ( IncompleteHandshakeException e ) { if ( tmpHandshakeBytes . capacity ( ) == 0 ) { socketBuffer . reset ( ) ; int newsize = e . getPreferredSize ( ) ; if ( newsize == 0 ) { newsize = socketBuffer . capacity ( ) + 16 ; } else { assert ( e . getPreferredSize ( ) >= socketBuffer . remaining ( ) ) ; } tmpHandshakeBytes = ByteBuffer . allocate ( newsize ) ; tmpHandshakeBytes . put ( socketBufferNew ) ; // tmpHandshakeBytes.flip(); } else { tmpHandshakeBytes . position ( tmpHandshakeBytes . limit ( ) ) ; tmpHandshakeBytes . limit ( tmpHandshakeBytes . capacity ( ) ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the connection if the received handshake was not correct [CODESPLIT] private void closeConnectionDueToWrongHandshake ( InvalidDataException exception ) { write ( generateHttpResponseDueToError ( 404 ) ) ; flushAndClose ( exception . getCloseCode ( ) , exception . getMessage ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the connection if there was a server error by a RuntimeException [CODESPLIT] private void closeConnectionDueToInternalServerError ( RuntimeException exception ) { write ( generateHttpResponseDueToError ( 500 ) ) ; flushAndClose ( CloseFrame . NEVER_CONNECTED , exception . getMessage ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a simple response for the corresponding endpoint to indicate some error [CODESPLIT] private ByteBuffer generateHttpResponseDueToError ( int errorCode ) { String errorCodeDescription ; switch ( errorCode ) { case 404 : errorCodeDescription = \"404 WebSocket Upgrade Failure\" ; break ; case 500 : default : errorCodeDescription = \"500 Internal Server Error\" ; } return ByteBuffer . wrap ( Charsetfunctions . asciiBytes ( \"HTTP/1.1 \" + errorCodeDescription + \"\\r\\nContent-Type: text/html\\nServer: TooTallNate Java-WebSocket\\r\\nContent-Length: \" + ( 48 + errorCodeDescription . length ( ) ) + \"\\r\\n\\r\\n<html><head></head><body><h1>\" + errorCodeDescription + \"</h1></body></html>\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will close the connection immediately without a proper close handshake . The code and the message therefore won t be transfered over the wire also they will be forwarded to onClose / onWebsocketClose . [CODESPLIT] public synchronized void closeConnection ( int code , String message , boolean remote ) { if ( readyState == ReadyState . CLOSED ) { return ; } //Methods like eot() call this method without calling onClose(). Due to that reason we have to adjust the ReadyState manually if ( readyState == ReadyState . OPEN ) { if ( code == CloseFrame . ABNORMAL_CLOSE ) { readyState = ReadyState . CLOSING ; } } if ( key != null ) { // key.attach( null ); //see issue #114 key . cancel ( ) ; } if ( channel != null ) { try { channel . close ( ) ; } catch ( IOException e ) { if ( e . getMessage ( ) . equals ( \"Broken pipe\" ) ) { log . trace ( \"Caught IOException: Broken pipe during closeConnection()\" , e ) ; } else { log . error ( \"Exception during channel.close()\" , e ) ; wsl . onWebsocketError ( this , e ) ; } } } try { this . wsl . onWebsocketClose ( this , code , message , remote ) ; } catch ( RuntimeException e ) { wsl . onWebsocketError ( this , e ) ; } if ( draft != null ) draft . reset ( ) ; handshakerequest = null ; readyState = ReadyState . CLOSED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send Text data to the other end . [CODESPLIT] @ Override public void send ( String text ) { if ( text == null ) throw new IllegalArgumentException ( \"Cannot send 'null' data to a WebSocketImpl.\" ) ; send ( draft . createFrames ( text , role == Role . CLIENT ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send Binary data ( plain bytes ) to the other end . [CODESPLIT] @ Override public void send ( ByteBuffer bytes ) { if ( bytes == null ) throw new IllegalArgumentException ( \"Cannot send 'null' data to a WebSocketImpl.\" ) ; send ( draft . createFrames ( bytes , role == Role . CLIENT ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a list of bytebuffer ( frames in binary form ) into the outgoing queue [CODESPLIT] private void write ( List < ByteBuffer > bufs ) { synchronized ( synchronizeWriteObject ) { for ( ByteBuffer b : bufs ) { write ( b ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset everything relevant to allow a reconnect [CODESPLIT] private void reset ( ) { Thread current = Thread . currentThread ( ) ; if ( current == writeThread || current == connectReadThread ) { throw new IllegalStateException ( \"You cannot initialize a reconnect out of the websocket thread. Use reconnect in another thread to insure a successful cleanup.\" ) ; } try { closeBlocking ( ) ; if ( writeThread != null ) { this . writeThread . interrupt ( ) ; this . writeThread = null ; } if ( connectReadThread != null ) { this . connectReadThread . interrupt ( ) ; this . connectReadThread = null ; } this . draft . reset ( ) ; if ( this . socket != null ) { this . socket . close ( ) ; this . socket = null ; } } catch ( Exception e ) { onError ( e ) ; engine . closeConnection ( CloseFrame . ABNORMAL_CLOSE , e . getMessage ( ) ) ; return ; } connectLatch = new CountDownLatch ( 1 ) ; closeLatch = new CountDownLatch ( 1 ) ; this . engine = new WebSocketImpl ( this , this . draft ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiates the websocket connection . This method does not block . [CODESPLIT] public void connect ( ) { if ( connectReadThread != null ) throw new IllegalStateException ( \"WebSocketClient objects are not reuseable\" ) ; connectReadThread = new Thread ( this ) ; connectReadThread . setName ( \"WebSocketConnectReadThread-\" + connectReadThread . getId ( ) ) ; connectReadThread . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as <code > connect< / code > but blocks with a timeout until the websocket connected or failed to do so . <br > [CODESPLIT] public boolean connectBlocking ( long timeout , TimeUnit timeUnit ) throws InterruptedException { connect ( ) ; return connectLatch . await ( timeout , timeUnit ) && engine . isOpen ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the specified port [CODESPLIT] private int getPort ( ) { int port = uri . getPort ( ) ; if ( port == - 1 ) { String scheme = uri . getScheme ( ) ; if ( \"wss\" . equals ( scheme ) ) { return WebSocketImpl . DEFAULT_WSS_PORT ; } else if ( \"ws\" . equals ( scheme ) ) { return WebSocketImpl . DEFAULT_PORT ; } else { throw new IllegalArgumentException ( \"unknown scheme: \" + scheme ) ; } } return port ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and send the handshake to the other endpoint [CODESPLIT] private void sendHandshake ( ) throws InvalidHandshakeException { String path ; String part1 = uri . getRawPath ( ) ; String part2 = uri . getRawQuery ( ) ; if ( part1 == null || part1 . length ( ) == 0 ) path = \"/\" ; else path = part1 ; if ( part2 != null ) path += ' ' + part2 ; int port = getPort ( ) ; String host = uri . getHost ( ) + ( ( port != WebSocketImpl . DEFAULT_PORT && port != WebSocketImpl . DEFAULT_WSS_PORT ) ? \":\" + port : \"\" ) ; HandshakeImpl1Client handshake = new HandshakeImpl1Client ( ) ; handshake . setResourceDescriptor ( path ) ; handshake . put ( \"Host\" , host ) ; if ( headers != null ) { for ( Map . Entry < String , String > kv : headers . entrySet ( ) ) { handshake . put ( kv . getKey ( ) , kv . getValue ( ) ) ; } } engine . startHandshake ( handshake ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls subclass implementation of <var > onOpen< / var > . [CODESPLIT] @ Override public final void onWebsocketOpen ( WebSocket conn , Handshakedata handshake ) { startConnectionLostTimer ( ) ; onOpen ( ( ServerHandshake ) handshake ) ; connectLatch . countDown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls subclass implementation of <var > onClose< / var > . [CODESPLIT] @ Override public final void onWebsocketClose ( WebSocket conn , int code , String reason , boolean remote ) { stopConnectionLostTimer ( ) ; if ( writeThread != null ) writeThread . interrupt ( ) ; onClose ( code , reason , remote ) ; connectLatch . countDown ( ) ; closeLatch . countDown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setter for the interval checking for lost connections A value lower or equal 0 results in the check to be deactivated [CODESPLIT] public void setConnectionLostTimeout ( int connectionLostTimeout ) { synchronized ( syncConnectionLost ) { this . connectionLostTimeout = TimeUnit . SECONDS . toNanos ( connectionLostTimeout ) ; if ( this . connectionLostTimeout <= 0 ) { log . trace ( \"Connection lost timer stopped\" ) ; cancelConnectionLostTimer ( ) ; return ; } if ( this . websocketRunning ) { log . trace ( \"Connection lost timer restarted\" ) ; //Reset all the pings try { ArrayList < WebSocket > connections = new ArrayList < WebSocket > ( getConnections ( ) ) ; WebSocketImpl webSocketImpl ; for ( WebSocket conn : connections ) { if ( conn instanceof WebSocketImpl ) { webSocketImpl = ( WebSocketImpl ) conn ; webSocketImpl . updateLastPong ( ) ; } } } catch ( Exception e ) { log . error ( \"Exception during connection lost restart\" , e ) ; } restartConnectionLostTimer ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop the connection lost timer [CODESPLIT] protected void stopConnectionLostTimer ( ) { synchronized ( syncConnectionLost ) { if ( connectionLostCheckerService != null || connectionLostCheckerFuture != null ) { this . websocketRunning = false ; log . trace ( \"Connection lost timer stopped\" ) ; cancelConnectionLostTimer ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the connection lost timer [CODESPLIT] protected void startConnectionLostTimer ( ) { synchronized ( syncConnectionLost ) { if ( this . connectionLostTimeout <= 0 ) { log . trace ( \"Connection lost timer deactivated\" ) ; return ; } log . trace ( \"Connection lost timer started\" ) ; this . websocketRunning = true ; restartConnectionLostTimer ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This methods allows the reset of the connection lost timer in case of a changed parameter [CODESPLIT] private void restartConnectionLostTimer ( ) { cancelConnectionLostTimer ( ) ; connectionLostCheckerService = Executors . newSingleThreadScheduledExecutor ( new NamedThreadFactory ( \"connectionLostChecker\" ) ) ; Runnable connectionLostChecker = new Runnable ( ) { /**\n\t\t\t * Keep the connections in a separate list to not cause deadlocks\n\t\t\t */ private ArrayList < WebSocket > connections = new ArrayList < WebSocket > ( ) ; @ Override public void run ( ) { connections . clear ( ) ; try { connections . addAll ( getConnections ( ) ) ; long minimumPongTime = ( long ) ( System . nanoTime ( ) - ( connectionLostTimeout * 1.5 ) ) ; for ( WebSocket conn : connections ) { executeConnectionLostDetection ( conn , minimumPongTime ) ; } } catch ( Exception e ) { //Ignore this exception } connections . clear ( ) ; } } ; connectionLostCheckerFuture = connectionLostCheckerService . scheduleAtFixedRate ( connectionLostChecker , connectionLostTimeout , connectionLostTimeout , TimeUnit . NANOSECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a ping to the endpoint or close the connection since the other endpoint did not respond with a ping [CODESPLIT] private void executeConnectionLostDetection ( WebSocket webSocket , long minimumPongTime ) { if ( ! ( webSocket instanceof WebSocketImpl ) ) { return ; } WebSocketImpl webSocketImpl = ( WebSocketImpl ) webSocket ; if ( webSocketImpl . getLastPong ( ) < minimumPongTime ) { log . trace ( \"Closing connection due to no pong received: {}\" , webSocketImpl ) ; webSocketImpl . closeConnection ( CloseFrame . ABNORMAL_CLOSE , \"The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection\" ) ; } else { if ( webSocketImpl . isOpen ( ) ) { webSocketImpl . sendPing ( ) ; } else { log . trace ( \"Trying to ping a non open connection: {}\" , webSocketImpl ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancel any running timer for the connection lost detection [CODESPLIT] private void cancelConnectionLostTimer ( ) { if ( connectionLostCheckerService != null ) { connectionLostCheckerService . shutdownNow ( ) ; connectionLostCheckerService = null ; } if ( connectionLostCheckerFuture != null ) { connectionLostCheckerFuture . cancel ( false ) ; connectionLostCheckerFuture = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Keystore with certificate created like so ( in JKS format ) : [CODESPLIT] public static void main ( String [ ] args ) throws Exception { ChatServer chatserver = new ChatServer ( 8887 ) ; // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store String STORETYPE = \"JKS\" ; String KEYSTORE = \"keystore.jks\" ; String STOREPASSWORD = \"storepassword\" ; String KEYPASSWORD = \"keypassword\" ; KeyStore ks = KeyStore . getInstance ( STORETYPE ) ; File kf = new File ( KEYSTORE ) ; ks . load ( new FileInputStream ( kf ) , STOREPASSWORD . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( \"SunX509\" ) ; kmf . init ( ks , KEYPASSWORD . toCharArray ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( \"SunX509\" ) ; tmf . init ( ks ) ; SSLContext sslContext = null ; sslContext = SSLContext . getInstance ( \"TLS\" ) ; sslContext . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , null ) ; chatserver . setWebSocketFactory ( new DefaultSSLWebSocketServerFactory ( sslContext ) ) ; chatserver . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This default implementation does not do anything . Go ahead and overwrite it . [CODESPLIT] @ Override public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer ( WebSocket conn , Draft draft , ClientHandshake request ) throws InvalidDataException { return new HandshakeImpl1Server ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This default implementation will send a pong in response to the received ping . The pong frame will have the same payload as the ping frame . [CODESPLIT] @ Override public void onWebsocketPing ( WebSocket conn , Framedata f ) { conn . sendFrame ( new PongFrame ( ( PingFrame ) f ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Keystore with certificate created like so ( in JKS format ) : [CODESPLIT] public static void main ( String [ ] args ) throws Exception { ChatServer chatserver = new ChatServer ( 8887 ) ; // Firefox does allow multible ssl connection only via port 443 //tested on FF16 // load up the key store String STORETYPE = \"JKS\" ; String KEYSTORE = \"keystore.jks\" ; String STOREPASSWORD = \"storepassword\" ; String KEYPASSWORD = \"keypassword\" ; KeyStore ks = KeyStore . getInstance ( STORETYPE ) ; File kf = new File ( KEYSTORE ) ; ks . load ( new FileInputStream ( kf ) , STOREPASSWORD . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( \"SunX509\" ) ; kmf . init ( ks , KEYPASSWORD . toCharArray ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( \"SunX509\" ) ; tmf . init ( ks ) ; SSLContext sslContext = SSLContext . getInstance ( \"TLS\" ) ; sslContext . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , null ) ; //Lets remove some ciphers and protocols SSLEngine engine = sslContext . createSSLEngine ( ) ; List < String > ciphers = new ArrayList < String > ( Arrays . asList ( engine . getEnabledCipherSuites ( ) ) ) ; ciphers . remove ( \"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\" ) ; List < String > protocols = new ArrayList < String > ( Arrays . asList ( engine . getEnabledProtocols ( ) ) ) ; protocols . remove ( \"SSLv3\" ) ; CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory ( sslContext , protocols . toArray ( new String [ ] { } ) , ciphers . toArray ( new String [ ] { } ) ) ; // Different example just using specific ciphers and protocols /*\n        String[] enabledProtocols = {\"TLSv1.2\"};\n\t\tString[] enabledCipherSuites = {\"TLS_RSA_WITH_AES_128_CBC_SHA\", \"TLS_RSA_WITH_AES_256_CBC_SHA\"};\n        CustomSSLWebSocketServerFactory factory = new CustomSSLWebSocketServerFactory(sslContext, enabledProtocols,enabledCipherSuites);\n        */ chatserver . setWebSocketFactory ( factory ) ; chatserver . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will do whatever necessary to process the sslengine handshake . Thats why it s called both from the { [CODESPLIT] private synchronized void processHandshake ( ) throws IOException { if ( sslEngine . getHandshakeStatus ( ) == HandshakeStatus . NOT_HANDSHAKING ) return ; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking. if ( ! tasks . isEmpty ( ) ) { Iterator < Future < ? > > it = tasks . iterator ( ) ; while ( it . hasNext ( ) ) { Future < ? > f = it . next ( ) ; if ( f . isDone ( ) ) { it . remove ( ) ; } else { if ( isBlocking ( ) ) consumeFutureUninterruptible ( f ) ; return ; } } } if ( sslEngine . getHandshakeStatus ( ) == SSLEngineResult . HandshakeStatus . NEED_UNWRAP ) { if ( ! isBlocking ( ) || readEngineResult . getStatus ( ) == Status . BUFFER_UNDERFLOW ) { inCrypt . compact ( ) ; int read = socketChannel . read ( inCrypt ) ; if ( read == - 1 ) { throw new IOException ( \"connection closed unexpectedly by peer\" ) ; } inCrypt . flip ( ) ; } inData . compact ( ) ; unwrap ( ) ; if ( readEngineResult . getHandshakeStatus ( ) == HandshakeStatus . FINISHED ) { createBuffers ( sslEngine . getSession ( ) ) ; return ; } } consumeDelegatedTasks ( ) ; if ( tasks . isEmpty ( ) || sslEngine . getHandshakeStatus ( ) == SSLEngineResult . HandshakeStatus . NEED_WRAP ) { socketChannel . write ( wrap ( emptybuffer ) ) ; if ( writeEngineResult . getHandshakeStatus ( ) == HandshakeStatus . FINISHED ) { createBuffers ( sslEngine . getSession ( ) ) ; return ; } } assert ( sslEngine . getHandshakeStatus ( ) != HandshakeStatus . NOT_HANDSHAKING ) ; // this function could only leave NOT_HANDSHAKING after createBuffers was called unless #190 occurs which means that nio wrap/unwrap never return HandshakeStatus.FINISHED bufferallocations = 1 ; // look at variable declaration why this line exists and #190. Without this line buffers would not be be recreated when #190 AND a rehandshake occur. }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "performs the unwrap operation by unwrapping from { [CODESPLIT] private synchronized ByteBuffer unwrap ( ) throws SSLException { int rem ; //There are some ssl test suites, which get around the selector.select() call, which cause an infinite unwrap and 100% cpu usage (see #459 and #458) if ( readEngineResult . getStatus ( ) == SSLEngineResult . Status . CLOSED && sslEngine . getHandshakeStatus ( ) == HandshakeStatus . NOT_HANDSHAKING ) { try { close ( ) ; } catch ( IOException e ) { //Not really interesting } } do { rem = inData . remaining ( ) ; readEngineResult = sslEngine . unwrap ( inCrypt , inData ) ; } while ( readEngineResult . getStatus ( ) == SSLEngineResult . Status . OK && ( rem != inData . remaining ( ) || sslEngine . getHandshakeStatus ( ) == HandshakeStatus . NEED_UNWRAP ) ) ; inData . flip ( ) ; return inData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Blocks when in blocking mode until at least one byte has been decoded . <br > When not in blocking mode 0 may be returned . [CODESPLIT] public int read ( ByteBuffer dst ) throws IOException { while ( true ) { if ( ! dst . hasRemaining ( ) ) return 0 ; if ( ! isHandShakeComplete ( ) ) { if ( isBlocking ( ) ) { while ( ! isHandShakeComplete ( ) ) { processHandshake ( ) ; } } else { processHandshake ( ) ; if ( ! isHandShakeComplete ( ) ) { return 0 ; } } } // assert ( bufferallocations > 1 ); //see #190 //if( bufferallocations <= 1 ) { //\tcreateBuffers( sslEngine.getSession() ); //} /* 1. When \"dst\" is smaller than \"inData\" readRemaining will fill \"dst\" with data decoded in a previous read call.\n\t\t * 2. When \"inCrypt\" contains more data than \"inData\" has remaining space, unwrap has to be called on more time(readRemaining)\n\t\t */ int purged = readRemaining ( dst ) ; if ( purged != 0 ) return purged ; /* We only continue when we really need more data from the network.\n\t\t * Thats the case if inData is empty or inCrypt holds to less data than necessary for decryption\n\t\t */ assert ( inData . position ( ) == 0 ) ; inData . clear ( ) ; if ( ! inCrypt . hasRemaining ( ) ) inCrypt . clear ( ) ; else inCrypt . compact ( ) ; if ( isBlocking ( ) || readEngineResult . getStatus ( ) == Status . BUFFER_UNDERFLOW ) if ( socketChannel . read ( inCrypt ) == - 1 ) { return - 1 ; } inCrypt . flip ( ) ; unwrap ( ) ; int transfered = transfereTo ( inData , dst ) ; if ( transfered == 0 && isBlocking ( ) ) { continue ; } return transfered ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] private int readRemaining ( ByteBuffer dst ) throws SSLException { if ( inData . hasRemaining ( ) ) { return transfereTo ( inData , dst ) ; } if ( ! inData . hasRemaining ( ) ) inData . clear ( ) ; // test if some bytes left from last read (e.g. BUFFER_UNDERFLOW) if ( inCrypt . hasRemaining ( ) ) { unwrap ( ) ; int amount = transfereTo ( inData , dst ) ; if ( readEngineResult . getStatus ( ) == SSLEngineResult . Status . CLOSED ) { return - 1 ; } if ( amount > 0 ) return amount ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes all connected clients sockets then closes the underlying ServerSocketChannel effectively killing the server socket selectorthread freeing the port the server was bound to and stops all internal workerthreads . [CODESPLIT] public void stop ( int timeout ) throws InterruptedException { if ( ! isclosed . compareAndSet ( false , true ) ) { // this also makes sure that no further connections will be added to this.connections return ; } List < WebSocket > socketsToClose ; // copy the connections in a list (prevent callback deadlocks) synchronized ( connections ) { socketsToClose = new ArrayList < WebSocket > ( connections ) ; } for ( WebSocket ws : socketsToClose ) { ws . close ( CloseFrame . GOING_AWAY ) ; } wsf . close ( ) ; synchronized ( this ) { if ( selectorthread != null && selector != null ) { selector . wakeup ( ) ; selectorthread . join ( timeout ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the port number that this server listens on . [CODESPLIT] public int getPort ( ) { int port = getAddress ( ) . getPort ( ) ; if ( port == 0 && server != null ) { port = server . socket ( ) . getLocalPort ( ) ; } return port ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runnable IMPLEMENTATION ///////////////////////////////////////////////// [CODESPLIT] public void run ( ) { if ( ! doEnsureSingleThread ( ) ) { return ; } if ( ! doSetupSelectorAndServerThread ( ) ) { return ; } try { int iShutdownCount = 5 ; int selectTimeout = 0 ; while ( ! selectorthread . isInterrupted ( ) && iShutdownCount != 0 ) { SelectionKey key = null ; WebSocketImpl conn = null ; try { if ( isclosed . get ( ) ) { selectTimeout = 5 ; } int keyCount = selector . select ( selectTimeout ) ; if ( keyCount == 0 && isclosed . get ( ) ) { iShutdownCount -- ; } Set < SelectionKey > keys = selector . selectedKeys ( ) ; Iterator < SelectionKey > i = keys . iterator ( ) ; while ( i . hasNext ( ) ) { key = i . next ( ) ; conn = null ; if ( ! key . isValid ( ) ) { continue ; } if ( key . isAcceptable ( ) ) { doAccept ( key , i ) ; continue ; } if ( key . isReadable ( ) && ! doRead ( key , i ) ) { continue ; } if ( key . isWritable ( ) ) { doWrite ( key ) ; } } doAdditionalRead ( ) ; } catch ( CancelledKeyException e ) { // an other thread may cancel the key } catch ( ClosedByInterruptException e ) { return ; // do the same stuff as when InterruptedException is thrown } catch ( IOException ex ) { if ( key != null ) key . cancel ( ) ; handleIOException ( key , conn , ex ) ; } catch ( InterruptedException e ) { // FIXME controlled shutdown (e.g. take care of buffermanagement) Thread . currentThread ( ) . interrupt ( ) ; } } } catch ( RuntimeException e ) { // should hopefully never occur handleFatal ( null , e ) ; } finally { doServerShutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do an additional read [CODESPLIT] private void doAdditionalRead ( ) throws InterruptedException , IOException { WebSocketImpl conn ; while ( ! iqueue . isEmpty ( ) ) { conn = iqueue . remove ( 0 ) ; WrappedByteChannel c = ( ( WrappedByteChannel ) conn . getChannel ( ) ) ; ByteBuffer buf = takeBuffer ( ) ; try { if ( SocketChannelIOHelper . readMore ( buf , conn , c ) ) iqueue . add ( conn ) ; if ( buf . hasRemaining ( ) ) { conn . inQueue . put ( buf ) ; queue ( conn ) ; } else { pushBuffer ( buf ) ; } } catch ( IOException e ) { pushBuffer ( buf ) ; throw e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a accept operation [CODESPLIT] private void doAccept ( SelectionKey key , Iterator < SelectionKey > i ) throws IOException , InterruptedException { if ( ! onConnect ( key ) ) { key . cancel ( ) ; return ; } SocketChannel channel = server . accept ( ) ; if ( channel == null ) { return ; } channel . configureBlocking ( false ) ; Socket socket = channel . socket ( ) ; socket . setTcpNoDelay ( isTcpNoDelay ( ) ) ; socket . setKeepAlive ( true ) ; WebSocketImpl w = wsf . createWebSocket ( this , drafts ) ; w . setSelectionKey ( channel . register ( selector , SelectionKey . OP_READ , w ) ) ; try { w . setChannel ( wsf . wrapChannel ( channel , w . getSelectionKey ( ) ) ) ; i . remove ( ) ; allocateBuffers ( w ) ; } catch ( IOException ex ) { if ( w . getSelectionKey ( ) != null ) w . getSelectionKey ( ) . cancel ( ) ; handleIOException ( w . getSelectionKey ( ) , null , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a read operation [CODESPLIT] private boolean doRead ( SelectionKey key , Iterator < SelectionKey > i ) throws InterruptedException , IOException { WebSocketImpl conn = ( WebSocketImpl ) key . attachment ( ) ; ByteBuffer buf = takeBuffer ( ) ; if ( conn . getChannel ( ) == null ) { key . cancel ( ) ; handleIOException ( key , conn , new IOException ( ) ) ; return false ; } try { if ( SocketChannelIOHelper . read ( buf , conn , conn . getChannel ( ) ) ) { if ( buf . hasRemaining ( ) ) { conn . inQueue . put ( buf ) ; queue ( conn ) ; i . remove ( ) ; if ( conn . getChannel ( ) instanceof WrappedByteChannel && ( ( WrappedByteChannel ) conn . getChannel ( ) ) . isNeedRead ( ) ) { iqueue . add ( conn ) ; } } else { pushBuffer ( buf ) ; } } else { pushBuffer ( buf ) ; } } catch ( IOException e ) { pushBuffer ( buf ) ; throw e ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a write operation [CODESPLIT] private void doWrite ( SelectionKey key ) throws IOException { WebSocketImpl conn = ( WebSocketImpl ) key . attachment ( ) ; if ( SocketChannelIOHelper . batch ( conn , conn . getChannel ( ) ) ) { if ( key . isValid ( ) ) { key . interestOps ( SelectionKey . OP_READ ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup the selector thread as well as basic server settings [CODESPLIT] private boolean doSetupSelectorAndServerThread ( ) { selectorthread . setName ( \"WebSocketSelector-\" + selectorthread . getId ( ) ) ; try { server = ServerSocketChannel . open ( ) ; server . configureBlocking ( false ) ; ServerSocket socket = server . socket ( ) ; socket . setReceiveBufferSize ( WebSocketImpl . RCVBUF ) ; socket . setReuseAddress ( isReuseAddr ( ) ) ; socket . bind ( address ) ; selector = Selector . open ( ) ; server . register ( selector , server . validOps ( ) ) ; startConnectionLostTimer ( ) ; for ( WebSocketWorker ex : decoders ) { ex . start ( ) ; } onStart ( ) ; } catch ( IOException ex ) { handleFatal ( null , ex ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The websocket server can only be started once [CODESPLIT] private boolean doEnsureSingleThread ( ) { synchronized ( this ) { if ( selectorthread != null ) throw new IllegalStateException ( getClass ( ) . getName ( ) + \" can only be started once.\" ) ; selectorthread = Thread . currentThread ( ) ; if ( isclosed . get ( ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean up everything after a shutdown [CODESPLIT] private void doServerShutdown ( ) { stopConnectionLostTimer ( ) ; if ( decoders != null ) { for ( WebSocketWorker w : decoders ) { w . interrupt ( ) ; } } if ( selector != null ) { try { selector . close ( ) ; } catch ( IOException e ) { log . error ( \"IOException during selector.close\" , e ) ; onError ( null , e ) ; } } if ( server != null ) { try { server . close ( ) ; } catch ( IOException e ) { log . error ( \"IOException during server.close\" , e ) ; onError ( null , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized <p > { [CODESPLIT] protected boolean removeConnection ( WebSocket ws ) { boolean removed = false ; synchronized ( connections ) { if ( this . connections . contains ( ws ) ) { removed = this . connections . remove ( ws ) ; } else { //Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512 log . trace ( \"Removing connection which is not in the connections collection! Possible no handshake recieved! {}\" , ws ) ; } } if ( isclosed . get ( ) && connections . isEmpty ( ) ) { selectorthread . interrupt ( ) ; } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Getter to return the socket used by this specific connection [CODESPLIT] private Socket getSocket ( WebSocket conn ) { WebSocketImpl impl = ( WebSocketImpl ) conn ; return ( ( SocketChannel ) impl . getSelectionKey ( ) . channel ( ) ) . socket ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a byte array to a specific collection of websocket connections [CODESPLIT] public void broadcast ( byte [ ] data , Collection < WebSocket > clients ) { if ( data == null || clients == null ) { throw new IllegalArgumentException ( ) ; } broadcast ( ByteBuffer . wrap ( data ) , clients ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a text to a specific collection of websocket connections [CODESPLIT] public void broadcast ( String text , Collection < WebSocket > clients ) { if ( text == null || clients == null ) { throw new IllegalArgumentException ( ) ; } doBroadcast ( text , clients ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private method to cache all the frames to improve memory footprint and conversion time [CODESPLIT] private void doBroadcast ( Object data , Collection < WebSocket > clients ) { String sData = null ; if ( data instanceof String ) { sData = ( String ) data ; } ByteBuffer bData = null ; if ( data instanceof ByteBuffer ) { bData = ( ByteBuffer ) data ; } if ( sData == null && bData == null ) { return ; } Map < Draft , List < Framedata > > draftFrames = new HashMap < Draft , List < Framedata > > ( ) ; for ( WebSocket client : clients ) { if ( client != null ) { Draft draft = client . getDraft ( ) ; fillFrames ( draft , draftFrames , sData , bData ) ; try { client . sendFrame ( draftFrames . get ( draft ) ) ; } catch ( WebsocketNotConnectedException e ) { //Ignore this exception in this case } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fills the draftFrames with new data for the broadcast [CODESPLIT] private void fillFrames ( Draft draft , Map < Draft , List < Framedata > > draftFrames , String sData , ByteBuffer bData ) { if ( ! draftFrames . containsKey ( draft ) ) { List < Framedata > frames = null ; if ( sData != null ) { frames = draft . createFrames ( sData , false ) ; } if ( bData != null ) { frames = draft . createFrames ( bData , false ) ; } if ( frames != null ) { draftFrames . put ( draft , frames ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transfer from one ByteBuffer to another ByteBuffer [CODESPLIT] public static int transferByteBuffer ( ByteBuffer source , ByteBuffer dest ) { if ( source == null || dest == null ) { throw new IllegalArgumentException ( ) ; } int fremain = source . remaining ( ) ; int toremain = dest . remaining ( ) ; if ( fremain > toremain ) { int limit = Math . min ( fremain , toremain ) ; source . limit ( limit ) ; dest . put ( source ) ; return limit ; } else { dest . put ( source ) ; return fremain ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Keystore with certificate created like so ( in JKS format ) : [CODESPLIT] public static void main ( String [ ] args ) throws Exception { WebSocketChatClient chatclient = new WebSocketChatClient ( new URI ( \"wss://localhost:8887\" ) ) ; // load up the key store String STORETYPE = \"JKS\" ; String KEYSTORE = \"keystore.jks\" ; String STOREPASSWORD = \"storepassword\" ; String KEYPASSWORD = \"keypassword\" ; KeyStore ks = KeyStore . getInstance ( STORETYPE ) ; File kf = new File ( KEYSTORE ) ; ks . load ( new FileInputStream ( kf ) , STOREPASSWORD . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( \"SunX509\" ) ; kmf . init ( ks , KEYPASSWORD . toCharArray ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( \"SunX509\" ) ; tmf . init ( ks ) ; SSLContext sslContext = null ; sslContext = SSLContext . getInstance ( \"TLS\" ) ; sslContext . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , null ) ; // sslContext.init( null, null, null ); // will use java's default key and trust store which is sufficient unless you deal with self-signed certificates SSLSocketFactory factory = sslContext . getSocketFactory ( ) ; // (SSLSocketFactory) SSLSocketFactory.getDefault(); chatclient . setSocketFactory ( factory ) ; chatclient . connectBlocking ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; while ( true ) { String line = reader . readLine ( ) ; if ( line . equals ( \"close\" ) ) { chatclient . closeBlocking ( ) ; } else if ( line . equals ( \"open\" ) ) { chatclient . reconnect ( ) ; } else { chatclient . send ( line ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialise JPA entity manager factories . [CODESPLIT] public JPAApi start ( ) { jpaConfig . persistenceUnits ( ) . forEach ( persistenceUnit -> emfs . put ( persistenceUnit . name , Persistence . createEntityManagerFactory ( persistenceUnit . unitName ) ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a newly created EntityManager for the specified persistence unit name . [CODESPLIT] public EntityManager em ( String name ) { EntityManagerFactory emf = emfs . get ( name ) ; if ( emf == null ) { return null ; } return emf . createEntityManager ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a block of code with a newly created EntityManager for the default Persistence Unit . [CODESPLIT] public void withTransaction ( Consumer < EntityManager > block ) { withTransaction ( em -> { block . accept ( em ) ; return null ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a block of code with a newly created EntityManager for the named Persistence Unit . [CODESPLIT] public < T > T withTransaction ( String name , Function < EntityManager , T > block ) { return withTransaction ( name , false , block ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a block of code with a newly created EntityManager for the named Persistence Unit . [CODESPLIT] public < T > T withTransaction ( String name , boolean readOnly , Function < EntityManager , T > block ) { EntityManager entityManager = null ; EntityTransaction tx = null ; try { entityManager = em ( name ) ; if ( entityManager == null ) { throw new RuntimeException ( \"Could not create JPA entity manager for '\" + name + \"'\" ) ; } if ( entityManagerContext != null ) { entityManagerContext . push ( entityManager , true ) ; } if ( ! readOnly ) { tx = entityManager . getTransaction ( ) ; tx . begin ( ) ; } T result = block . apply ( entityManager ) ; if ( tx != null ) { if ( tx . getRollbackOnly ( ) ) { tx . rollback ( ) ; } else { tx . commit ( ) ; } } return result ; } catch ( Throwable t ) { if ( tx != null ) { try { if ( tx . isActive ( ) ) { tx . rollback ( ) ; } } catch ( Exception e ) { logger . error ( \"Could not rollback transaction\" , e ) ; } } throw t ; } finally { if ( entityManager != null ) { if ( entityManagerContext != null ) { entityManagerContext . pop ( true ) ; } entityManager . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a block of code with a newly created EntityManager for the named Persistence Unit . [CODESPLIT] public void withTransaction ( String name , boolean readOnly , Consumer < EntityManager > block ) { withTransaction ( name , readOnly , em -> { block . accept ( em ) ; return null ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a block of code in a JPA transaction . [CODESPLIT] @ Deprecated public < T > T withTransaction ( Supplier < T > block ) { return withTransaction ( \"default\" , false , block ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a block of code in a JPA transaction . [CODESPLIT] @ Deprecated public void withTransaction ( final Runnable block ) { try { withTransaction ( ( ) -> { block . run ( ) ; return null ; } ) ; } catch ( Throwable t ) { throw new RuntimeException ( \"JPA transaction failed\" , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a block of code in a JPA transaction . [CODESPLIT] @ Deprecated public < T > T withTransaction ( String name , boolean readOnly , Supplier < T > block ) { return withTransaction ( name , readOnly , entityManager -> { return block . get ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the varargs to a scala buffer takes care of wrapping varargs into a intermediate list if necessary [CODESPLIT] private static Seq < Object > convertArgsToScalaBuffer ( final Object ... args ) { return scala . collection . JavaConverters . asScalaBufferConverter ( wrapArgsToListIfNeeded ( args ) ) . asScala ( ) . toList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps arguments passed into a list if necessary . [CODESPLIT] @ SafeVarargs private static < T > List < T > wrapArgsToListIfNeeded ( final T ... args ) { List < T > out ; if ( args != null && args . length == 1 && args [ 0 ] instanceof List ) { out = ( List < T > ) args [ 0 ] ; } else { out = Arrays . asList ( args ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates a message . [CODESPLIT] public String get ( play . api . i18n . Lang lang , String key , Object ... args ) { Seq < Object > scalaArgs = convertArgsToScalaBuffer ( args ) ; return messages . apply ( key , scalaArgs , lang ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates the first defined message . [CODESPLIT] public String get ( play . api . i18n . Lang lang , List < String > keys , Object ... args ) { Buffer < String > keyArgs = scala . collection . JavaConverters . asScalaBufferConverter ( keys ) . asScala ( ) ; Seq < Object > scalaArgs = convertArgsToScalaBuffer ( args ) ; return messages . apply ( keyArgs . toSeq ( ) , scalaArgs , lang ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a message key is defined . [CODESPLIT] public Boolean isDefinedAt ( play . api . i18n . Lang lang , String key ) { return messages . isDefinedAt ( key , lang ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a messages context appropriate for the given candidates . [CODESPLIT] public Messages preferred ( Collection < Lang > candidates ) { Seq < Lang > cs = Scala . asScala ( candidates ) ; play . api . i18n . Messages msgs = messages . preferred ( ( Seq ) cs ) ; return new MessagesImpl ( new Lang ( msgs . lang ( ) ) , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a messages context appropriate for the given request . [CODESPLIT] public Messages preferred ( Http . RequestHeader request ) { play . api . i18n . Messages msgs = messages . preferred ( request ) ; return new MessagesImpl ( new Lang ( msgs . lang ( ) ) , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a Result and a Lang return a new Result with the lang cookie set to the given Lang . [CODESPLIT] public Result setLang ( Result result , Lang lang ) { return messages . setLang ( result . asScala ( ) , lang ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add additional configuration . [CODESPLIT] public final Self configure ( Config conf ) { return newBuilder ( delegate . configure ( new play . api . Configuration ( conf ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add additional configuration . [CODESPLIT] public final Self configure ( Map < String , Object > conf ) { return configure ( ConfigFactory . parseMap ( conf ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add additional configuration . [CODESPLIT] public final Self configure ( String key , Object value ) { return configure ( ImmutableMap . of ( key , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add bindings from guiceable modules . [CODESPLIT] public final Self bindings ( GuiceableModule ... modules ) { return newBuilder ( delegate . bindings ( Scala . varargs ( modules ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add bindings from Play modules . [CODESPLIT] public final Self bindings ( play . api . inject . Module ... modules ) { return bindings ( Guiceable . modules ( modules ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add Play bindings . [CODESPLIT] public final Self bindings ( play . api . inject . Binding < ? > ... bindings ) { return bindings ( Guiceable . bindings ( bindings ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override bindings using guiceable modules . [CODESPLIT] public final Self overrides ( GuiceableModule ... modules ) { return newBuilder ( delegate . overrides ( Scala . varargs ( modules ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override bindings using Play modules . [CODESPLIT] public final Self overrides ( play . api . inject . Module ... modules ) { return overrides ( Guiceable . modules ( modules ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override bindings using Play bindings . [CODESPLIT] public final Self overrides ( play . api . inject . Binding < ? > ... bindings ) { return overrides ( Guiceable . bindings ( bindings ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable modules by class . [CODESPLIT] public final Self disable ( Class < ? > ... moduleClasses ) { return newBuilder ( delegate . disable ( Scala . toSeq ( moduleClasses ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes this action with the given HTTP context and returns the result . [CODESPLIT] @ Deprecated // TODO: When you remove this method make call(Request) below abstract public CompletionStage < Result > call ( Context ctx ) { return call ( ctx . args != null && ! ctx . args . isEmpty ( ) ? ctx . request ( ) . addAttr ( CTX_ARGS , ctx . args ) : ctx . request ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes this action with the given HTTP request and returns the result . [CODESPLIT] public CompletionStage < Result > call ( Request req ) { // TODO: Make this method abstract after removing call(Context) return Context . safeCurrent ( ) . map ( threadLocalCtx -> { // A previous action did explicitly set a context onto the thread local (via // Http.Context.current.set(...)) // Let's use that context so the user doesn't loose data he/she set onto that ctx // (args,...) Context newCtx = threadLocalCtx . withRequest ( req . removeAttr ( CTX_ARGS ) ) ; Context . setCurrent ( newCtx ) ; return call ( newCtx ) ; } ) . orElseGet ( ( ) -> { // A previous action did not set a context explicitly, we simply create a new one to // pass on the request Context ctx = new Context ( req . removeAttr ( CTX_ARGS ) , contextComponents ) ; ctx . args = req . attrs ( ) . getOptional ( CTX_ARGS ) . orElse ( new HashMap <> ( ) ) ; return call ( ctx ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a file relative to the application root path . This method returns an Optional using empty if the file was not found . [CODESPLIT] public Optional < File > getExistingFile ( String relativePath ) { return OptionConverters . toJava ( env . getExistingFile ( relativePath ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure the scope for this binding . [CODESPLIT] public < A extends Annotation > Binding < T > in ( final Class < A > scope ) { return underlying . in ( scope ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a tuple of A B [CODESPLIT] public static < A , B > Tuple < A , B > Tuple ( A a , B b ) { return new Tuple < A , B > ( a , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a tuple of A B C D E [CODESPLIT] public static < A , B , C , D , E > Tuple5 < A , B , C , D , E > Tuple5 ( A a , B b , C c , D d , E e ) { return new Tuple5 < A , B , C , D , E > ( a , b , c , d , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the execution context to an executor preparing it first . [CODESPLIT] private static Executor toExecutor ( ExecutionContext ec ) { ExecutionContext prepared = ec . prepare ( ) ; if ( prepared instanceof Executor ) { return ( Executor ) prepared ; } else { return prepared :: execute ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the specified Set - Cookie HTTP header value into a { @link Cookie } . [CODESPLIT] public Cookie decode ( String header ) { if ( header == null ) { throw new NullPointerException ( \"header\" ) ; } final int headerLen = header . length ( ) ; if ( headerLen == 0 ) { return null ; } CookieBuilder cookieBuilder = null ; loop : for ( int i = 0 ; ; ) { // Skip spaces and separators. for ( ; ; ) { if ( i == headerLen ) { break loop ; } char c = header . charAt ( i ) ; if ( c == ' ' ) { // Having multiple cookies in a single Set-Cookie header is // deprecated, modern browsers only parse the first one break loop ; } else if ( c == ' ' || c == ' ' || c == 0x0b || c == ' ' || c == ' ' || c == ' ' || c == ' ' ) { i ++ ; continue ; } break ; } int nameBegin = i ; int nameEnd = i ; int valueBegin = - 1 ; int valueEnd = - 1 ; if ( i != headerLen ) { keyValLoop : for ( ; ; ) { char curChar = header . charAt ( i ) ; if ( curChar == ' ' ) { // NAME; (no value till ';') nameEnd = i ; valueBegin = valueEnd = - 1 ; break keyValLoop ; } else if ( curChar == ' ' ) { // NAME=VALUE nameEnd = i ; i ++ ; if ( i == headerLen ) { // NAME= (empty value, i.e. nothing after '=') valueBegin = valueEnd = 0 ; break keyValLoop ; } valueBegin = i ; // NAME=VALUE; int semiPos = header . indexOf ( ' ' , i ) ; valueEnd = i = semiPos > 0 ? semiPos : headerLen ; break keyValLoop ; } else { i ++ ; } if ( i == headerLen ) { // NAME (no value till the end of string) nameEnd = headerLen ; valueBegin = valueEnd = - 1 ; break ; } } } if ( valueEnd > 0 && header . charAt ( valueEnd - 1 ) == ' ' ) { // old multiple cookies separator, skipping it valueEnd -- ; } if ( cookieBuilder == null ) { // cookie name-value pair DefaultCookie cookie = initCookie ( header , nameBegin , nameEnd , valueBegin , valueEnd ) ; if ( cookie == null ) { return null ; } cookieBuilder = new CookieBuilder ( cookie ) ; } else { // cookie attribute String attrValue = valueBegin == - 1 ? null : header . substring ( valueBegin , valueEnd ) ; cookieBuilder . appendAttribute ( header , nameBegin , nameEnd , attrValue ) ; } } return cookieBuilder . cookie ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new instance that also skips { @code moreClassesToSkip } . [CODESPLIT] public SourceProvider plusSkippedClasses ( Class ... moreClassesToSkip ) { Set < String > toSkip = new HashSet < String > ( classNamesToSkip ) ; toSkip . addAll ( asStrings ( moreClassesToSkip ) ) ; return new SourceProvider ( toSkip ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the class names as Strings [CODESPLIT] private static List < String > asStrings ( Class ... classes ) { List < String > strings = new ArrayList < String > ( ) ; for ( Class c : classes ) { strings . add ( c . getName ( ) ) ; } return strings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the calling line of code . The selected line is the nearest to the top of the stack that is not skipped . [CODESPLIT] public StackTraceElement get ( ) { for ( final StackTraceElement element : new Throwable ( ) . getStackTrace ( ) ) { String className = element . getClassName ( ) ; if ( ! classNamesToSkip . contains ( className ) ) { return element ; } } throw new AssertionError ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a default JPA configuration with the given name and unit name . [CODESPLIT] public static JPAConfig of ( String name , String unitName ) { return new DefaultJPAConfig ( new JPAConfig . PersistenceUnit ( name , unitName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a default JPA configuration with the given names and unit names . [CODESPLIT] public static JPAConfig of ( String n1 , String u1 , String n2 , String u2 ) { return new DefaultJPAConfig ( new JPAConfig . PersistenceUnit ( n1 , u1 ) , new JPAConfig . PersistenceUnit ( n2 , u2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a default JPA configuration from a map of names to unit names . [CODESPLIT] public static JPAConfig from ( Map < String , String > map ) { ImmutableSet . Builder < JPAConfig . PersistenceUnit > persistenceUnits = new ImmutableSet . Builder < JPAConfig . PersistenceUnit > ( ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { persistenceUnits . add ( new JPAConfig . PersistenceUnit ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } return new DefaultJPAConfig ( persistenceUnits . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces a Flow of escaped ByteString from a series of String elements . Calls out to Comet . flow internally . [CODESPLIT] public static Flow < String , ByteString , NotUsed > string ( String callbackName ) { return Flow . of ( String . class ) . map ( str -> { return ByteString . fromString ( \"'\" + StringEscapeUtils . escapeEcmaScript ( str ) + \"'\" ) ; } ) . via ( flow ( callbackName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces a flow of ByteString using Json . stringify from a Flow of JsonNode . Calls out to Comet . flow internally . [CODESPLIT] public static Flow < JsonNode , ByteString , NotUsed > json ( String callbackName ) { return Flow . of ( JsonNode . class ) . map ( json -> { return ByteString . fromString ( Json . stringify ( json ) ) ; } ) . via ( flow ( callbackName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces a flow of ByteString with a prepended block and a script wrapper . [CODESPLIT] public static Flow < ByteString , ByteString , NotUsed > flow ( String callbackName ) { ByteString cb = ByteString . fromString ( callbackName ) ; return Flow . of ( ByteString . class ) . map ( ( msg ) - > { return formatted ( cb , msg )  ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the content type of the passed in request using the given validator . [CODESPLIT] public static < A > Accumulator < ByteString , F . Either < Result , A > > validateContentType ( HttpErrorHandler errorHandler , Http . RequestHeader request , String errorMessage , Function < String , Boolean > validate , Function < Http . RequestHeader , Accumulator < ByteString , F . Either < Result , A > > > parser ) { if ( request . contentType ( ) . map ( validate ) . orElse ( false ) ) { return parser . apply ( request ) ; } else { CompletionStage < Result > result = errorHandler . onClientError ( request , Status $ . MODULE $ . UNSUPPORTED_MEDIA_TYPE ( ) , errorMessage ) ; return Accumulator . done ( result . thenApply ( F . Either :: Left ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a logger instance . [CODESPLIT] public static ALogger of ( String name ) { return new ALogger ( play . api . Logger . apply ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a logger instance . [CODESPLIT] public static ALogger of ( Class < ? > clazz ) { return new ALogger ( play . api . Logger . apply ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the TRACE level . [CODESPLIT] @ Deprecated public static void trace ( String message , Object ... args ) { logger . trace ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the TRACE level . [CODESPLIT] @ Deprecated public static void trace ( String message , Supplier < ? > ... args ) { logger . trace ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the TRACE level . [CODESPLIT] @ Deprecated public static void trace ( String message , Throwable error ) { logger . trace ( message , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the DEBUG level . [CODESPLIT] @ Deprecated public static void debug ( String message , Object ... args ) { logger . debug ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the DEBUG level . [CODESPLIT] @ Deprecated public static void debug ( String message , Supplier < ? > ... args ) { logger . debug ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the DEBUG level . [CODESPLIT] @ Deprecated public static void debug ( String message , Throwable error ) { logger . debug ( message , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the INFO level . [CODESPLIT] @ Deprecated public static void info ( String message , Object ... args ) { logger . info ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the INFO level . [CODESPLIT] @ Deprecated public static void info ( String message , Supplier < ? > ... args ) { logger . info ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the INFO level . [CODESPLIT] @ Deprecated public static void info ( String message , Throwable error ) { logger . info ( message , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the WARN level . [CODESPLIT] @ Deprecated public static void warn ( String message , Object ... args ) { logger . warn ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the WARN level . [CODESPLIT] @ Deprecated public static void warn ( String message , Supplier < ? > ... args ) { logger . warn ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the WARN level . [CODESPLIT] @ Deprecated public static void warn ( String message , Throwable error ) { logger . warn ( message , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the ERROR level . [CODESPLIT] @ Deprecated public static void error ( String message , Object ... args ) { logger . error ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the ERROR level . [CODESPLIT] @ Deprecated public static void error ( String message , Supplier < ? > args ) { logger . error ( message , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with the ERROR level . [CODESPLIT] @ Deprecated public static void error ( String message , Throwable error ) { logger . error ( message , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds validator as a singleton . [CODESPLIT] public < T extends ConstraintValidator < ? , ? > > MappedConstraintValidatorFactory addConstraintValidator ( Class < T > key , T constraintValidator ) { validators . put ( key , ( ) -> constraintValidator ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "need to do so . [CODESPLIT] private < T extends ConstraintValidator < ? , ? > > T newInstance ( Class < T > key ) { try { return key . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( InstantiationException | RuntimeException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#clients - show - action [CODESPLIT] public Result show ( Long id ) { Client client = clientService . findById ( id ) ; return ok ( views . html . Client . show ( client ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#range - request [CODESPLIT] public Result video ( Http . Request request , Long videoId ) { File videoFile = getVideoFile ( videoId ) ; return RangeResults . ofFile ( request , videoFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an accessible method ( that is one that can be invoked via reflection ) that implements the specified Method . If no such method can be found return { @code null } . [CODESPLIT] public static Method getAccessibleMethod ( Method method ) { if ( ! MemberUtils . isAccessible ( method ) ) { return null ; } // If the declaring class is public, we are done final Class < ? > cls = method . getDeclaringClass ( ) ; if ( Modifier . isPublic ( cls . getModifiers ( ) ) ) { return method ; } final String methodName = method . getName ( ) ; final Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; // Check the implemented interfaces and subinterfaces method = getAccessibleMethodFromInterfaceNest ( cls , methodName , parameterTypes ) ; // Check the superclass chain if ( method == null ) { method = getAccessibleMethodFromSuperclass ( cls , methodName , parameterTypes ) ; } return method ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an accessible method ( that is one that can be invoked via reflection ) by scanning through the superclasses . If no such method can be found return { @code null } . [CODESPLIT] private static Method getAccessibleMethodFromSuperclass ( final Class < ? > cls , final String methodName , final Class < ? > ... parameterTypes ) { Class < ? > parentClass = cls . getSuperclass ( ) ; while ( parentClass != null ) { if ( Modifier . isPublic ( parentClass . getModifiers ( ) ) ) { try { return parentClass . getMethod ( methodName , parameterTypes ) ; } catch ( final NoSuchMethodException e ) { return null ; } } parentClass = parentClass . getSuperclass ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds an accessible method that matches the given name and has compatible parameters . Compatible parameters mean that every method parameter is assignable from the given parameters . In other words it finds a method with the given name that will take the parameters given . [CODESPLIT] public static Method getMatchingAccessibleMethod ( final Class < ? > cls , final String methodName , final Class < ? > ... parameterTypes ) { try { final Method method = cls . getMethod ( methodName , parameterTypes ) ; MemberUtils . setAccessibleWorkaround ( method ) ; return method ; } catch ( final NoSuchMethodException e ) { // NOPMD - Swallow the exception } // search through all methods Method bestMatch = null ; final Method [ ] methods = cls . getMethods ( ) ; for ( final Method method : methods ) { // compare name and parameters if ( method . getName ( ) . equals ( methodName ) && MemberUtils . isMatchingMethod ( method , parameterTypes ) ) { // get accessible version of method final Method accessibleMethod = getAccessibleMethod ( method ) ; if ( accessibleMethod != null && ( bestMatch == null || MemberUtils . compareMethodFit ( accessibleMethod , bestMatch , parameterTypes ) < 0 ) ) { bestMatch = accessibleMethod ; } } } if ( bestMatch != null ) { MemberUtils . setAccessibleWorkaround ( bestMatch ) ; } if ( bestMatch != null && bestMatch . isVarArgs ( ) && bestMatch . getParameterTypes ( ) . length > 0 && parameterTypes . length > 0 ) { final Class < ? > [ ] methodParameterTypes = bestMatch . getParameterTypes ( ) ; final Class < ? > methodParameterComponentType = methodParameterTypes [ methodParameterTypes . length - 1 ] . getComponentType ( ) ; final String methodParameterComponentTypeName = ClassUtils . primitiveToWrapper ( methodParameterComponentType ) . getName ( ) ; final String parameterTypeName = parameterTypes [ parameterTypes . length - 1 ] . getName ( ) ; final String parameterTypeSuperClassName = parameterTypes [ parameterTypes . length - 1 ] . getSuperclass ( ) . getName ( ) ; if ( ! methodParameterComponentTypeName . equals ( parameterTypeName ) && ! methodParameterComponentTypeName . equals ( parameterTypeSuperClassName ) ) { return null ; } } return bestMatch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when a client error occurs that is an error in the 4xx series . [CODESPLIT] @ Override public CompletionStage < Result > onClientError ( RequestHeader request , int statusCode , String message ) { if ( statusCode == 400 ) { return onBadRequest ( request , message ) ; } else if ( statusCode == 403 ) { return onForbidden ( request , message ) ; } else if ( statusCode == 404 ) { return onNotFound ( request , message ) ; } else if ( statusCode >= 400 && statusCode < 500 ) { return onOtherClientError ( request , statusCode , message ) ; } else { throw new IllegalArgumentException ( \"onClientError invoked with non client error status code \" + statusCode + \": \" + message ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when a client makes a bad request . [CODESPLIT] protected CompletionStage < Result > onBadRequest ( RequestHeader request , String message ) { return CompletableFuture . completedFuture ( Results . badRequest ( views . html . defaultpages . badRequest . render ( request . method ( ) , request . uri ( ) , message , request . asScala ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when a client makes a request that was forbidden . [CODESPLIT] protected CompletionStage < Result > onForbidden ( RequestHeader request , String message ) { return CompletableFuture . completedFuture ( Results . forbidden ( views . html . defaultpages . unauthorized . render ( request . asScala ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when a handler or resource is not found . [CODESPLIT] protected CompletionStage < Result > onNotFound ( RequestHeader request , String message ) { if ( environment . isProd ( ) ) { return CompletableFuture . completedFuture ( Results . notFound ( views . html . defaultpages . notFound . render ( request . method ( ) , request . uri ( ) , request . asScala ( ) ) ) ) ; } else { return CompletableFuture . completedFuture ( Results . notFound ( views . html . defaultpages . devNotFound . render ( request . method ( ) , request . uri ( ) , Some . apply ( routes . get ( ) ) , request . asScala ( ) ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when a server error occurs . [CODESPLIT] @ Override public CompletionStage < Result > onServerError ( RequestHeader request , Throwable exception ) { try { UsefulException usefulException = throwableToUsefulException ( exception ) ; logServerError ( request , usefulException ) ; switch ( environment . mode ( ) ) { case PROD : return onProdServerError ( request , usefulException ) ; default : return onDevServerError ( request , usefulException ) ; } } catch ( Exception e ) { logger . error ( \"Error while handling error\" , e ) ; return CompletableFuture . completedFuture ( Results . internalServerError ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Responsible for logging server errors . [CODESPLIT] protected void logServerError ( RequestHeader request , UsefulException usefulException ) { logger . error ( String . format ( \"\\n\\n! @%s - Internal server error, for (%s) [%s] ->\\n\" , usefulException . id , request . method ( ) , request . uri ( ) ) , usefulException ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given exception to an exception that Play can report more information about . [CODESPLIT] protected final UsefulException throwableToUsefulException ( final Throwable throwable ) { return HttpErrorHandlerExceptions . throwableToUsefulException ( sourceMapper . sourceMapper ( ) , environment . isProd ( ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked in dev mode when a server error occurs . Note that this method is where the URL set by play . editor is used . [CODESPLIT] protected CompletionStage < Result > onDevServerError ( RequestHeader request , UsefulException exception ) { return CompletableFuture . completedFuture ( Results . internalServerError ( views . html . defaultpages . devError . render ( playEditor , exception , request . asScala ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked in prod mode when a server error occurs . [CODESPLIT] protected CompletionStage < Result > onProdServerError ( RequestHeader request , UsefulException exception ) { return CompletableFuture . completedFuture ( Results . internalServerError ( views . html . defaultpages . error . render ( exception , request . asScala ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a BuildDocHandler that serves documentation from the given files which could either be directories or jar files . The baseDir array must be the same length as the files array and the corresponding entry in there for jar files is used as a base directory to use resources from in the jar . [CODESPLIT] public static BuildDocHandler fromResources ( File [ ] files , String [ ] baseDirs ) throws IOException { assert ( files . length == baseDirs . length ) ; FileRepository [ ] repositories = new FileRepository [ files . length ] ; List < JarFile > jarFiles = new ArrayList <> ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { File file = files [ i ] ; String baseDir = baseDirs [ i ] ; if ( file . isDirectory ( ) ) { repositories [ i ] = new FilesystemRepository ( file ) ; } else { // Assume it's a jar file JarFile jarFile = new JarFile ( file ) ; jarFiles . add ( jarFile ) ; repositories [ i ] = new JarRepository ( jarFile , Option . apply ( baseDir ) ) ; } } return new DocumentationHandler ( new AggregateFileRepository ( repositories ) , ( ) -> { for ( JarFile jarFile : jarFiles ) { jarFile . close ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an BuildDocHandler that serves documentation from a given directory by wrapping a FilesystemRepository . [CODESPLIT] public static BuildDocHandler fromDirectory ( File directory ) { FileRepository repo = new FilesystemRepository ( directory ) ; return new DocumentationHandler ( repo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an BuildDocHandler that serves the manual from a given directory by wrapping a FilesystemRepository and the API docs from a given JAR file by wrapping a JarRepository [CODESPLIT] public static BuildDocHandler fromDirectoryAndJar ( File directory , JarFile jarFile , String base ) { return fromDirectoryAndJar ( directory , jarFile , base , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an BuildDocHandler that serves the manual from a given directory by wrapping a FilesystemRepository and the API docs from a given JAR file by wrapping a JarRepository . [CODESPLIT] public static BuildDocHandler fromDirectoryAndJar ( File directory , JarFile jarFile , String base , boolean fallbackToJar ) { FileRepository fileRepo = new FilesystemRepository ( directory ) ; FileRepository jarRepo = new JarRepository ( jarFile , Option . apply ( base ) ) ; FileRepository manualRepo ; if ( fallbackToJar ) { manualRepo = new AggregateFileRepository ( new FileRepository [ ] { fileRepo , jarRepo } ) ; } else { manualRepo = fileRepo ; } return new DocumentationHandler ( manualRepo , jarRepo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an BuildDocHandler that serves documentation from a given JAR file by wrapping a JarRepository . [CODESPLIT] public static BuildDocHandler fromJar ( JarFile jarFile , String base ) { FileRepository repo = new JarRepository ( jarFile , Option . apply ( base ) ) ; return new DocumentationHandler ( repo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "###insert : import static net . logstash . logback . marker . Markers . append ; [CODESPLIT] private Marker requestMarker ( Http . Request request ) { return append ( \"host\" , request . host ( ) ) . and ( append ( \"path\" , request . path ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#logging - log - info - with - async - request - context [CODESPLIT] public CompletionStage < Result > asyncIndex ( Http . Request request ) { return CompletableFuture . supplyAsync ( ( ) -> { logger . info ( requestMarker ( request ) , \"Rendering asyncIndex()\" ) ; return ok ( \"foo\" ) ; } , httpExecutionContext . current ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes the data . [CODESPLIT] public CompletionStage < ByteString > consumeData ( Materializer mat ) { return dataStream ( ) . runFold ( ByteString . empty ( ) , ByteString :: concat , mat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an entity from the given content . [CODESPLIT] public static final HttpEntity fromContent ( Content content , String charset ) { String body ; if ( content instanceof Xml ) { // See https://github.com/playframework/playframework/issues/2770 body = content . body ( ) . trim ( ) ; } else { body = content . body ( ) ; } return new Strict ( ByteString . fromString ( body , charset ) , Optional . of ( content . contentType ( ) + \"; charset=\" + charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an entity from the given String . [CODESPLIT] public static final HttpEntity fromString ( String content , String charset ) { return new Strict ( ByteString . fromString ( content , charset ) , Optional . of ( \"text/plain; charset=\" + charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given source of ByteStrings to a chunked entity . [CODESPLIT] public static final HttpEntity chunked ( Source < ByteString , ? > data , Optional < String > contentType ) { return new Chunked ( data . map ( HttpChunk . Chunk :: new ) , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#bind [CODESPLIT] @ Override public Optional < AgeRange > bind ( String key , Map < String , String [ ] > data ) { try { from = Integer . valueOf ( data . get ( \"from\" ) [ 0 ] ) ; to = Integer . valueOf ( data . get ( \"to\" ) [ 0 ] ) ; return Optional . of ( this ) ; } catch ( Exception e ) { // no parameter match return None return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#bind [CODESPLIT] @ Override public String javascriptUnbind ( ) { return new StringBuilder ( ) . append ( \"from=\" ) . append ( from ) . append ( \";to=\" ) . append ( to ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a simple result . [CODESPLIT] public static Result status ( int status , Content content , String charset ) { if ( content == null ) { throw new NullPointerException ( \"Null content\" ) ; } return new Result ( status , HttpEntity . fromContent ( content , charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a simple result . [CODESPLIT] public static Result status ( int status , String content , String charset ) { if ( content == null ) { throw new NullPointerException ( \"Null content\" ) ; } return new Result ( status , HttpEntity . fromString ( content , charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a simple result with json content and UTF8 encoding . [CODESPLIT] public static Result status ( int status , JsonNode content ) { return status ( status , content , JsonEncoding . UTF8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a simple result with json content . [CODESPLIT] public static Result status ( int status , JsonNode content , JsonEncoding encoding ) { if ( content == null ) { throw new NullPointerException ( \"Null content\" ) ; } return status ( status ) . sendJson ( content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a simple result with byte - array content . [CODESPLIT] public static Result status ( int status , byte [ ] content ) { if ( content == null ) { throw new NullPointerException ( \"Null content\" ) ; } return new Result ( status , new HttpEntity . Strict ( ByteString . fromArray ( content ) , Optional . empty ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a chunked result . [CODESPLIT] public static Result status ( int status , InputStream content , long contentLength ) { return status ( status ) . sendInputStream ( content , contentLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a result with file contents . [CODESPLIT] public static Result status ( int status , File content ) { return status ( status , content , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a result . [CODESPLIT] public static Result status ( int status , File content , String fileName ) { return status ( status , content , fileName , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a result . [CODESPLIT] public static Result status ( int status , File content , String fileName , FileMimeTypes fileMimeTypes ) { return status ( status ) . sendFile ( content , fileName , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a result with path contents . [CODESPLIT] public static Result status ( int status , Path content ) { return status ( status , content , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a result with path contents . [CODESPLIT] public static Result status ( int status , Path content , FileMimeTypes fileMimeTypes ) { return status ( status ) . sendPath ( content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a result . [CODESPLIT] public static Result status ( int status , Path content , String fileName ) { return status ( status , content , fileName , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 200 OK result . [CODESPLIT] public static Result ok ( String content , String charset ) { return status ( OK , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 200 OK result . [CODESPLIT] public static Result ok ( JsonNode content , JsonEncoding encoding ) { return status ( OK , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 200 OK result . [CODESPLIT] public static Result ok ( File content , boolean inline ) { return ok ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 200 OK result . [CODESPLIT] public static Result ok ( File content , String filename ) { return ok ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 200 OK result . [CODESPLIT] public static Result ok ( Path content , FileMimeTypes fileMimeTypes ) { return status ( OK , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 200 OK result . [CODESPLIT] public static Result ok ( Path content , boolean inline ) { return ok ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 200 OK result . [CODESPLIT] public static Result ok ( Path content , String filename ) { return ok ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 201 Created result . [CODESPLIT] public static Result created ( Content content , String charset ) { return status ( CREATED , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 201 Created result . [CODESPLIT] public static Result created ( JsonNode content , JsonEncoding encoding ) { return status ( CREATED , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 201 Created result . [CODESPLIT] public static Result created ( File content , boolean inline ) { return created ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 201 Created result . [CODESPLIT] public static Result created ( File content , String filename ) { return created ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 201 Created result . [CODESPLIT] public static Result created ( Path content , boolean inline ) { return created ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 201 Created result . [CODESPLIT] public static Result created ( Path content , String filename ) { return created ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 201 Created result . [CODESPLIT] public static Result created ( Path content , boolean inline , String filename , FileMimeTypes fileMimeTypes ) { return status ( CREATED , content , inline , filename , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 400 Bad Request result . [CODESPLIT] public static Result badRequest ( Content content , String charset ) { return status ( BAD_REQUEST , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 400 Bad Request result . [CODESPLIT] public static Result badRequest ( JsonNode content , JsonEncoding encoding ) { return status ( BAD_REQUEST , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 400 Bad Request result . [CODESPLIT] public static Result badRequest ( File content , FileMimeTypes fileMimeTypes ) { return status ( BAD_REQUEST , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 400 Bad Request result . [CODESPLIT] public static Result badRequest ( File content , boolean inline ) { return badRequest ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 400 Bad Request result . [CODESPLIT] public static Result badRequest ( File content , String filename ) { return badRequest ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 400 Bad Request result . [CODESPLIT] public static Result badRequest ( Path content , boolean inline ) { return badRequest ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 400 Bad Request result . [CODESPLIT] public static Result badRequest ( Path content , String filename ) { return badRequest ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 401 Unauthorized result . [CODESPLIT] public static Result unauthorized ( Content content , String charset ) { return status ( UNAUTHORIZED , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 401 Unauthorized result . [CODESPLIT] public static Result unauthorized ( JsonNode content , JsonEncoding encoding ) { return status ( UNAUTHORIZED , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 401 Unauthorized result . [CODESPLIT] public static Result unauthorized ( File content , FileMimeTypes fileMimeTypes ) { return status ( UNAUTHORIZED , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 401 Unauthorized result . [CODESPLIT] public static Result unauthorized ( File content , boolean inline ) { return unauthorized ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 401 Unauthorized result . [CODESPLIT] public static Result unauthorized ( File content , String filename ) { return unauthorized ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 401 Unauthorized result . [CODESPLIT] public static Result unauthorized ( Path content , boolean inline ) { return unauthorized ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 401 Unauthorized result . [CODESPLIT] public static Result unauthorized ( Path content , String filename ) { return unauthorized ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 402 Payment Required result . [CODESPLIT] public static Result paymentRequired ( String content , String charset ) { return status ( PAYMENT_REQUIRED , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 402 Payment Required result . [CODESPLIT] public static Result paymentRequired ( JsonNode content , JsonEncoding encoding ) { return status ( PAYMENT_REQUIRED , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 402 Payment Required result . [CODESPLIT] public static Result paymentRequired ( File content , FileMimeTypes fileMimeTypes ) { return status ( PAYMENT_REQUIRED , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 402 Payment Required result . [CODESPLIT] public static Result paymentRequired ( File content , boolean inline ) { return paymentRequired ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 402 Payment Required result . [CODESPLIT] public static Result paymentRequired ( File content , String filename ) { return paymentRequired ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 402 Payment Required result . [CODESPLIT] public static Result paymentRequired ( Path content , boolean inline ) { return paymentRequired ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 402 Payment Required result . [CODESPLIT] public static Result paymentRequired ( Path content , String filename ) { return paymentRequired ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 403 Forbidden result . [CODESPLIT] public static Result forbidden ( Content content , String charset ) { return status ( FORBIDDEN , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 403 Forbidden result . [CODESPLIT] public static Result forbidden ( JsonNode content , JsonEncoding encoding ) { return status ( FORBIDDEN , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 403 Forbidden result . [CODESPLIT] public static Result forbidden ( File content , boolean inline ) { return forbidden ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 403 Forbidden result . [CODESPLIT] public static Result forbidden ( File content , String filename ) { return forbidden ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 403 Forbidden result . [CODESPLIT] public static Result forbidden ( File content , boolean inline , String filename , FileMimeTypes fileMimeTypes ) { return status ( FORBIDDEN , content , inline , filename , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 403 Forbidden result . [CODESPLIT] public static Result forbidden ( Path content , boolean inline ) { return forbidden ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 403 Forbidden result . [CODESPLIT] public static Result forbidden ( Path content , String filename ) { return forbidden ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 404 Not Found result . [CODESPLIT] public static Result notFound ( Content content , String charset ) { return status ( NOT_FOUND , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 404 Not Found result . [CODESPLIT] public static Result notFound ( JsonNode content , JsonEncoding encoding ) { return status ( NOT_FOUND , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 404 Not Found result . [CODESPLIT] public static Result notFound ( File content , boolean inline ) { return notFound ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 404 Not Found result . [CODESPLIT] public static Result notFound ( File content , String filename ) { return notFound ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 404 Not Found result . [CODESPLIT] public static Result notFound ( Path content , boolean inline ) { return notFound ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 404 Not Found result . [CODESPLIT] public static Result notFound ( Path content , String filename ) { return notFound ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 404 Not Found result . [CODESPLIT] public static Result notFound ( Path content , String filename , FileMimeTypes fileMimeTypes ) { return status ( NOT_FOUND , content , filename , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 406 Not Acceptable result . [CODESPLIT] public static Result notAcceptable ( Content content , String charset ) { return status ( NOT_ACCEPTABLE , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 406 Not Acceptable result . [CODESPLIT] public static Result notAcceptable ( JsonNode content , JsonEncoding encoding ) { return status ( NOT_ACCEPTABLE , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 406 Not Acceptable result . [CODESPLIT] public static Result notAcceptable ( File content , FileMimeTypes fileMimeTypes ) { return status ( NOT_ACCEPTABLE , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 406 Not Acceptable result . [CODESPLIT] public static Result notAcceptable ( File content , boolean inline ) { return notAcceptable ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 406 Not Acceptable result . [CODESPLIT] public static Result notAcceptable ( File content , String filename ) { return notAcceptable ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 406 Not Acceptable result . [CODESPLIT] public static Result notAcceptable ( Path content , boolean inline ) { return notAcceptable ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 406 Not Acceptable result . [CODESPLIT] public static Result notAcceptable ( Path content , String filename ) { return notAcceptable ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 415 Unsupported Media Type result . [CODESPLIT] public static Result unsupportedMediaType ( String content , String charset ) { return status ( UNSUPPORTED_MEDIA_TYPE , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 415 Unsupported Media Type result . [CODESPLIT] public static Result unsupportedMediaType ( JsonNode content , JsonEncoding encoding ) { return status ( UNSUPPORTED_MEDIA_TYPE , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 415 Unsupported Media Type result . [CODESPLIT] public static Result unsupportedMediaType ( File content , FileMimeTypes fileMimeTypes ) { return status ( UNSUPPORTED_MEDIA_TYPE , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 415 Unsupported Media Type result . [CODESPLIT] public static Result unsupportedMediaType ( File content , boolean inline ) { return unsupportedMediaType ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 415 Unsupported Media Type result . [CODESPLIT] public static Result unsupportedMediaType ( File content , String filename ) { return unsupportedMediaType ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 415 Unsupported Media Type result . [CODESPLIT] public static Result unsupportedMediaType ( Path content , boolean inline ) { return unsupportedMediaType ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 415 Unsupported Media Type result . [CODESPLIT] public static Result unsupportedMediaType ( Path content , String filename ) { return unsupportedMediaType ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 428 Precondition Required result . [CODESPLIT] public static Result preconditionRequired ( Content content , String charset ) { return status ( PRECONDITION_REQUIRED , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 428 Precondition Required result . [CODESPLIT] public static Result preconditionRequired ( JsonNode content , JsonEncoding encoding ) { return status ( PRECONDITION_REQUIRED , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 428 Precondition Required result . [CODESPLIT] public static Result preconditionRequired ( File content , FileMimeTypes fileMimeTypes ) { return status ( PRECONDITION_REQUIRED , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 428 Precondition Required result . [CODESPLIT] public static Result preconditionRequired ( File content , boolean inline ) { return preconditionRequired ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 428 Precondition Required result . [CODESPLIT] public static Result preconditionRequired ( File content , String filename ) { return preconditionRequired ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 428 Precondition Required result . [CODESPLIT] public static Result preconditionRequired ( Path content , boolean inline ) { return preconditionRequired ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 428 Precondition Required result . [CODESPLIT] public static Result preconditionRequired ( Path content , String filename ) { return preconditionRequired ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 429 Too Many Requests result . [CODESPLIT] public static Result tooManyRequests ( Content content , String charset ) { return status ( TOO_MANY_REQUESTS , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 429 Too Many Requests result . [CODESPLIT] public static Result tooManyRequests ( JsonNode content , JsonEncoding encoding ) { return status ( TOO_MANY_REQUESTS , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 429 Too Many Requests result . [CODESPLIT] public static Result tooManyRequests ( File content , boolean inline ) { return tooManyRequests ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 429 Too Many Requests result . [CODESPLIT] public static Result tooManyRequests ( File content , String filename ) { return tooManyRequests ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 429 Too Many Requests result . [CODESPLIT] public static Result tooManyRequests ( File content , String filename , FileMimeTypes fileMimeTypes ) { return status ( TOO_MANY_REQUESTS , content , filename , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 429 Too Many Requests result . [CODESPLIT] public static Result tooManyRequests ( Path content , boolean inline ) { return tooManyRequests ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 429 Too Many Requests result . [CODESPLIT] public static Result tooManyRequests ( Path content , String filename ) { return tooManyRequests ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 431 Request Header Fields Too Large result . [CODESPLIT] public static Result requestHeaderFieldsTooLarge ( Content content , String charset ) { return status ( REQUEST_HEADER_FIELDS_TOO_LARGE , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 431 Request Header Fields Too Large result . [CODESPLIT] public static Result requestHeaderFieldsTooLarge ( JsonNode content , JsonEncoding encoding ) { return status ( REQUEST_HEADER_FIELDS_TOO_LARGE , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 431 Request Header Fields Too Large result . [CODESPLIT] public static Result requestHeaderFieldsTooLarge ( File content , boolean inline ) { return requestHeaderFieldsTooLarge ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 431 Request Header Fields Too Large result . [CODESPLIT] public static Result requestHeaderFieldsTooLarge ( File content , String filename ) { return requestHeaderFieldsTooLarge ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 431 Request Header Fields Too Large result . [CODESPLIT] public static Result requestHeaderFieldsTooLarge ( Path content , boolean inline ) { return requestHeaderFieldsTooLarge ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 431 Request Header Fields Too Large result . [CODESPLIT] public static Result requestHeaderFieldsTooLarge ( Path content , boolean inline , FileMimeTypes fileMimeTypes ) { return status ( REQUEST_HEADER_FIELDS_TOO_LARGE , content , inline , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 431 Request Header Fields Too Large result . [CODESPLIT] public static Result requestHeaderFieldsTooLarge ( Path content , String filename ) { return requestHeaderFieldsTooLarge ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 500 Internal Server Error result . [CODESPLIT] public static Result internalServerError ( String content , String charset ) { return status ( INTERNAL_SERVER_ERROR , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 500 Internal Server Error result . [CODESPLIT] public static Result internalServerError ( JsonNode content , JsonEncoding encoding ) { return status ( INTERNAL_SERVER_ERROR , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 500 Internal Server Error result . [CODESPLIT] public static Result internalServerError ( File content , FileMimeTypes fileMimeTypes ) { return status ( INTERNAL_SERVER_ERROR , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 500 Internal Server Error result . [CODESPLIT] public static Result internalServerError ( File content , boolean inline ) { return internalServerError ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 500 Internal Server Error result . [CODESPLIT] public static Result internalServerError ( File content , String filename ) { return internalServerError ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 500 Internal Server Error result . [CODESPLIT] public static Result internalServerError ( Path content , boolean inline ) { return internalServerError ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 500 Internal Server Error result . [CODESPLIT] public static Result internalServerError ( Path content , String filename ) { return internalServerError ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 511 Network Authentication Required result . [CODESPLIT] public static Result networkAuthenticationRequired ( Content content , String charset ) { return status ( NETWORK_AUTHENTICATION_REQUIRED , content , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 511 Network Authentication Required result . [CODESPLIT] public static Result networkAuthenticationRequired ( JsonNode content , JsonEncoding encoding ) { return status ( NETWORK_AUTHENTICATION_REQUIRED , content , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 511 Network Authentication Required result . [CODESPLIT] public static Result networkAuthenticationRequired ( File content , FileMimeTypes fileMimeTypes ) { return status ( NETWORK_AUTHENTICATION_REQUIRED , content , fileMimeTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 511 Network Authentication Required result . [CODESPLIT] public static Result networkAuthenticationRequired ( File content , boolean inline ) { return networkAuthenticationRequired ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 511 Network Authentication Required result . [CODESPLIT] public static Result networkAuthenticationRequired ( File content , String filename ) { return networkAuthenticationRequired ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 511 Network Authentication Required result . [CODESPLIT] public static Result networkAuthenticationRequired ( Path content , boolean inline ) { return networkAuthenticationRequired ( content , inline , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 511 Network Authentication Required result . [CODESPLIT] public static Result networkAuthenticationRequired ( Path content , String filename ) { return networkAuthenticationRequired ( content , filename , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 301 Moved Permanently result . [CODESPLIT] public static Result movedPermanently ( String url ) { return new Result ( MOVED_PERMANENTLY , Collections . singletonMap ( LOCATION , url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 301 Moved Permanently result . [CODESPLIT] public static Result movedPermanently ( Call call ) { return new Result ( MOVED_PERMANENTLY , Collections . singletonMap ( LOCATION , call . path ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 302 Found result . [CODESPLIT] public static Result found ( String url ) { return new Result ( FOUND , Collections . singletonMap ( LOCATION , url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 302 Found result . [CODESPLIT] public static Result found ( Call call ) { return new Result ( FOUND , Collections . singletonMap ( LOCATION , call . path ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 303 See Other result . [CODESPLIT] public static Result seeOther ( String url ) { return new Result ( SEE_OTHER , Collections . singletonMap ( LOCATION , url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 303 See Other result . [CODESPLIT] public static Result redirect ( String url ) { return new Result ( SEE_OTHER , Collections . singletonMap ( LOCATION , url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 303 See Other result . [CODESPLIT] public static Result redirect ( Call call ) { return new Result ( SEE_OTHER , Collections . singletonMap ( LOCATION , call . path ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 307 Temporary Redirect result . [CODESPLIT] public static Result temporaryRedirect ( String url ) { return new Result ( TEMPORARY_REDIRECT , Collections . singletonMap ( LOCATION , url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 307 Temporary Redirect result . [CODESPLIT] public static Result temporaryRedirect ( Call call ) { return new Result ( TEMPORARY_REDIRECT , Collections . singletonMap ( LOCATION , call . path ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 308 Permanent Redirect result . [CODESPLIT] public static Result permanentRedirect ( String url ) { return new Result ( PERMANENT_REDIRECT , Collections . singletonMap ( LOCATION , url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 308 Permanent Redirect result . [CODESPLIT] public static Result permanentRedirect ( Call call ) { return new Result ( PERMANENT_REDIRECT , Collections . singletonMap ( LOCATION , call . path ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#bind [CODESPLIT] @ Override public User bind ( String key , String id ) { // findById meant to be lightweight operation User user = findById ( Long . valueOf ( id ) ) ; if ( user == null ) { throw new IllegalArgumentException ( \"User with id \" + id + \" not found\" ) ; } return user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "designed to be lightweight operation [CODESPLIT] private User findById ( Long id ) { if ( id > 3 ) return null ; User user = new User ( ) ; user . id = id ; user . name = \"User \" + String . valueOf ( id ) ; return user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select a preferred language given the list of candidates . [CODESPLIT] public Lang preferred ( Collection < Lang > candidates ) { return new Lang ( langs . preferred ( ( scala . collection . immutable . Seq ) Scala . asScala ( candidates ) . toSeq ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a unique identifier to the URL . [CODESPLIT] public Call unique ( ) { return new play . api . mvc . Call ( method ( ) , this . uniquify ( this . url ( ) ) , fragment ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new Call with the given fragment . [CODESPLIT] public Call withFragment ( String fragment ) { return new play . api . mvc . Call ( method ( ) , url ( ) , fragment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform this call to an absolute URL . [CODESPLIT] public String absoluteURL ( Http . Request request ) { return absoluteURL ( request . secure ( ) , request . host ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform this call to an WebSocket URL . [CODESPLIT] public String webSocketURL ( Http . Request request ) { return webSocketURL ( request . secure ( ) , request . host ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Scala function wrapper for ConnectionRunnable . [CODESPLIT] AbstractFunction1 < Connection , BoxedUnit > connectionFunction ( final ConnectionRunnable block ) { return new AbstractFunction1 < Connection , BoxedUnit > ( ) { public BoxedUnit apply ( Connection connection ) { try { block . run ( connection ) ; return BoxedUnit . UNIT ; } catch ( java . sql . SQLException e ) { throw new RuntimeException ( \"Connection runnable failed\" , e ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Scala function wrapper for ConnectionCallable . [CODESPLIT] < A > AbstractFunction1 < Connection , A > connectionFunction ( final ConnectionCallable < A > block ) { return new AbstractFunction1 < Connection , A > ( ) { public A apply ( Connection connection ) { try { return block . call ( connection ) ; } catch ( java . sql . SQLException e ) { throw new RuntimeException ( \"Connection callable failed\" , e ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#show - page - action [CODESPLIT] public Result show ( String page ) { String content = Page . getContentOf ( page ) ; return ok ( content ) . as ( \"text/html\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a server for the given router . [CODESPLIT] public static Server forRouter ( Function < BuiltInComponents , Router > block ) { return forRouter ( Mode . TEST , 0 , block ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a server for the given router . [CODESPLIT] public static Server forRouter ( Mode mode , Function < BuiltInComponents , Router > block ) { return forRouter ( mode , 0 , block ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a server for the router returned by the given block . [CODESPLIT] public static Server forRouter ( Mode mode , int port , Function < BuiltInComponents , Router > block ) { return new Builder ( ) . mode ( mode ) . http ( port ) . build ( block ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#javascript - router - resource [CODESPLIT] public Result javascriptRoutes2 ( Http . Request request ) { return ok ( // #javascript-router-resource-custom-method JavaScriptReverseRouter . create ( \"jsRoutes\" , \"myAjaxMethod\" , request . host ( ) , routes . javascript . Users . list ( ) , routes . javascript . Users . get ( ) ) // #javascript-router-resource-custom-method ) . as ( Http . MimeTypes . JAVASCRIPT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an object to JsonNode . [CODESPLIT] public static JsonNode toJson ( final Object data ) { try { return mapper ( ) . valueToTree ( data ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a JsonNode to a Java value [CODESPLIT] public static < A > A fromJson ( JsonNode json , Class < A > clazz ) { try { return mapper ( ) . treeToValue ( json , clazz ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a String representing a json and return it as a JsonNode . [CODESPLIT] public static JsonNode parse ( String src ) { try { return mapper ( ) . readTree ( src ) ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a InputStream representing a json and return it as a JsonNode . [CODESPLIT] public static JsonNode parse ( java . io . InputStream src ) { try { return mapper ( ) . readTree ( src ) ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signs the given String using the given key . <br > [CODESPLIT] @ Override public String sign ( String message , byte [ ] key ) { return signer . sign ( message , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a JavaScript reverse router . [CODESPLIT] public static JavaScript create ( String name , String ajaxMethod , String host , JavaScriptReverseRoute ... routes ) { return play . api . routing . JavaScriptReverseRouter . apply ( name , Scala . Option ( ajaxMethod ) , host , Scala . varargs ( routes ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a JavaScript reverse router . [CODESPLIT] @ Deprecated public static JavaScript create ( String name , String ajaxMethod , JavaScriptReverseRoute ... routes ) { return create ( name , ajaxMethod , play . mvc . Http . Context . current ( ) . request ( ) . host ( ) , routes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a JavaScript reverse router . [CODESPLIT] @ Deprecated public static JavaScript create ( String name , JavaScriptReverseRoute ... routes ) { return create ( name , \"jQuery.ajax\" , routes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array whose entries do not contain container annotations anymore but the indirectly present annotation ( s ) a container annotation was wrapping instead . An annotation is considered a container annotation if its indirectly present annotation ( s ) are annotated with { @link Repeatable } . Annotations inside the given array which don t meet the above definition of a container annotations will be returned untouched . [CODESPLIT] public static < A extends Annotation > Annotation [ ] unwrapContainerAnnotations ( final A [ ] annotations ) { final List < Annotation > unwrappedAnnotations = new LinkedList <> ( ) ; for ( final Annotation maybeContainerAnnotation : annotations ) { final List < Annotation > indirectlyPresentAnnotations = getIndirectlyPresentAnnotations ( maybeContainerAnnotation ) ; if ( ! indirectlyPresentAnnotations . isEmpty ( ) ) { unwrappedAnnotations . addAll ( indirectlyPresentAnnotations ) ; } else { unwrappedAnnotations . add ( maybeContainerAnnotation ) ; // was not a container annotation } } return unwrappedAnnotations . toArray ( new Annotation [ unwrappedAnnotations . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the return type of an existing { @code value () } method of the passed annotation is an { @code Annotation [] } array and the annotations inside that { @code Annotation [] } array are annotated with the { @link Repeatable } annotation the annotations of that array will be returned . If the passed annotation does not have a { @code value () } method or the above criteria are not met an empty list will be returned instead . [CODESPLIT] public static < A extends Annotation > List < Annotation > getIndirectlyPresentAnnotations ( final A maybeContainerAnnotation ) { try { final Method method = maybeContainerAnnotation . annotationType ( ) . getMethod ( \"value\" ) ; final Object o = method . invoke ( maybeContainerAnnotation ) ; if ( Annotation [ ] . class . isAssignableFrom ( o . getClass ( ) ) ) { final Annotation [ ] indirectAnnotations = ( Annotation [ ] ) o ; if ( indirectAnnotations . length > 0 && indirectAnnotations [ 0 ] . annotationType ( ) . isAnnotationPresent ( Repeatable . class ) ) { return Arrays . asList ( indirectAnnotations ) ; } } } catch ( final NoSuchMethodException e ) { // That's ok, this just wasn't a container annotation -> continue } catch ( final SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } return Collections . emptyList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a path to targetPath that s relative to the given startPath . [CODESPLIT] public static String relative ( String startPath , String targetPath ) { // If the start and target path's are the same then link to the current directory if ( startPath . equals ( targetPath ) ) { return CURRENT_DIR ; } String [ ] start = toSegments ( canonical ( startPath ) ) ; String [ ] target = toSegments ( canonical ( targetPath ) ) ; // If start path has no trailing separator (a \"file\" path), then drop file segment if ( ! startPath . endsWith ( SEPARATOR ) ) start = Arrays . copyOfRange ( start , 0 , start . length - 1 ) ; // If target path has no trailing separator, then drop file segment, but keep a reference to add // it later String targetFile = \"\" ; if ( ! targetPath . endsWith ( SEPARATOR ) ) { targetFile = target [ target . length - 1 ] ; target = Arrays . copyOfRange ( target , 0 , target . length - 1 ) ; } // Work out how much of the filepath is shared by start and path. String [ ] common = commonPrefix ( start , target ) ; String [ ] parents = toParentDirs ( start . length - common . length ) ; int relativeStartIdx = common . length ; String [ ] relativeDirs = Arrays . copyOfRange ( target , relativeStartIdx , target . length ) ; String [ ] relativePath = Arrays . copyOf ( parents , parents . length + relativeDirs . length ) ; System . arraycopy ( relativeDirs , 0 , relativePath , parents . length , relativeDirs . length ) ; // If this is not a sibling reference append a trailing / to path String trailingSep = \"\" ; if ( relativePath . length > 0 ) trailingSep = SEPARATOR ; return Arrays . stream ( relativePath ) . collect ( Collectors . joining ( SEPARATOR ) ) + trailingSep + targetFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a canonical path that does not contain parent directories current directories or superfluous directory separators . [CODESPLIT] public static String canonical ( String url ) { String [ ] urlPath = toSegments ( url ) ; Stack < String > canonical = new Stack <> ( ) ; for ( String comp : urlPath ) { if ( comp . isEmpty ( ) || comp . equals ( CURRENT_DIR ) ) continue ; if ( ! comp . equals ( PARENT_DIR ) || ( ! canonical . empty ( ) && canonical . peek ( ) . equals ( PARENT_DIR ) ) ) canonical . push ( comp ) ; else canonical . pop ( ) ; } String prefixSep = url . startsWith ( SEPARATOR ) ? SEPARATOR : \"\" ; String trailingSep = url . endsWith ( SEPARATOR ) ? SEPARATOR : \"\" ; return prefixSep + canonical . stream ( ) . collect ( Collectors . joining ( SEPARATOR ) ) + trailingSep ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#hello - world - hello - correct - action [CODESPLIT] public Result hello ( String name ) { // ###replace:    return ok(views.html.hello.render(name)); return ok ( javaguide . hello . html . helloName . render ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a set of constraints to human - readable values . Does not guarantee the order of the returned constraints . [CODESPLIT] public static List < Tuple < String , List < Object > > > displayableConstraint ( Set < ConstraintDescriptor < ? > > constraints ) { return constraints . parallelStream ( ) . filter ( c -> c . getAnnotation ( ) . annotationType ( ) . isAnnotationPresent ( Display . class ) ) . map ( c -> displayableConstraint ( c ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a set of constraints to human - readable values in guaranteed order . Only constraints that have an annotation that intersect with the { @code orderedAnnotations } parameter will be considered . The order of the returned constraints corresponds to the order of the { @code orderedAnnotations parameter } . [CODESPLIT] public static List < Tuple < String , List < Object > > > displayableConstraint ( Set < ConstraintDescriptor < ? > > constraints , Annotation [ ] orderedAnnotations ) { final List < Annotation > constraintAnnot = constraints . stream ( ) . map ( c -> c . getAnnotation ( ) ) . collect ( Collectors . < Annotation > toList ( ) ) ; return Stream . of ( orderedAnnotations ) . filter ( constraintAnnot :: contains ) // only use annotations for which we actually have a constraint . filter ( a -> a . annotationType ( ) . isAnnotationPresent ( Display . class ) ) . map ( a -> displayableConstraint ( constraints . parallelStream ( ) . filter ( c -> c . getAnnotation ( ) . equals ( a ) ) . findFirst ( ) . get ( ) ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a constraint to a human - readable value . [CODESPLIT] public static Tuple < String , List < Object > > displayableConstraint ( ConstraintDescriptor < ? > constraint ) { final Display displayAnnotation = constraint . getAnnotation ( ) . annotationType ( ) . getAnnotation ( Display . class ) ; return Tuple ( displayAnnotation . name ( ) , Collections . unmodifiableList ( Stream . of ( displayAnnotation . attributes ( ) ) . map ( attr -> constraint . getAttributes ( ) . get ( attr ) ) . collect ( Collectors . toList ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#jpa - withTransaction - function [CODESPLIT] public CompletionStage < Long > runningWithTransaction ( ) { return CompletableFuture . supplyAsync ( ( ) -> { // lambda is an instance of Function<EntityManager, Long> return jpaApi . withTransaction ( entityManager -> { Query query = entityManager . createNativeQuery ( \"select max(age) from people\" ) ; return ( Long ) query . getSingleResult ( ) ; } ) ; } , executionContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#jpa - withTransaction - consumer [CODESPLIT] public CompletionStage < Void > runningWithRunnable ( ) { // lambda is an instance of Consumer<EntityManager> return CompletableFuture . runAsync ( ( ) -> { jpaApi . withTransaction ( entityManager -> { Query query = entityManager . createNativeQuery ( \"update people set active = 1 where age > 18\" ) ; query . executeUpdate ( ) ; } ) ; } , executionContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a CompletionStage that returns either the input stage or a futures . [CODESPLIT] @ Override public < A > CompletionStage < A > timeout ( final CompletionStage < A > stage , final long amount , final TimeUnit unit ) { requireNonNull ( stage , \"Null stage\" ) ; requireNonNull ( unit , \"Null unit\" ) ; FiniteDuration duration = FiniteDuration . apply ( amount , unit ) ; return toJava ( delegate . timeout ( duration , Scala . asScalaWithFuture ( ( ) -> stage ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An alias for futures ( stage delay unit ) that uses a java . time . Duration . [CODESPLIT] @ Override public < A > CompletionStage < A > timeout ( final CompletionStage < A > stage , final Duration duration ) { requireNonNull ( stage , \"Null stage\" ) ; requireNonNull ( duration , \"Null duration\" ) ; FiniteDuration finiteDuration = FiniteDuration . apply ( duration . toMillis ( ) , TimeUnit . MILLISECONDS ) ; return toJava ( delegate . timeout ( finiteDuration , Scala . asScalaWithFuture ( ( ) -> stage ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a CompletionStage which after a delay will be redeemed with the result of a given supplier . The supplier will be called after the delay . [CODESPLIT] @ Override public < A > CompletionStage < A > delayed ( final Callable < CompletionStage < A > > callable , long amount , TimeUnit unit ) { requireNonNull ( callable , \"Null callable\" ) ; requireNonNull ( amount , \"Null amount\" ) ; requireNonNull ( unit , \"Null unit\" ) ; FiniteDuration duration = FiniteDuration . apply ( amount , unit ) ; return toJava ( delegate . delayed ( duration , Scala . asScalaWithFuture ( callable ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a CompletionStage which after a delay will be redeemed with the result of a given supplier . The supplier will be called after the delay . [CODESPLIT] @ Override public < A > CompletionStage < A > delayed ( final Callable < CompletionStage < A > > callable , Duration duration ) { requireNonNull ( callable , \"Null callable\" ) ; requireNonNull ( duration , \"Null duration\" ) ; FiniteDuration finiteDuration = FiniteDuration . apply ( duration . toMillis ( ) , TimeUnit . MILLISECONDS ) ; return toJava ( delegate . delayed ( finiteDuration , Scala . asScalaWithFuture ( callable ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if an array of Classes can be assigned to another array of Classes . [CODESPLIT] public static boolean isAssignable ( Class < ? > [ ] classArray , Class < ? > [ ] toClassArray , boolean autoboxing ) { if ( arrayGetLength ( classArray ) != arrayGetLength ( toClassArray ) ) { return false ; } if ( classArray == null ) { classArray = EMPTY_CLASS_ARRAY ; } if ( toClassArray == null ) { toClassArray = EMPTY_CLASS_ARRAY ; } for ( int i = 0 ; i < classArray . length ; i ++ ) { if ( isAssignable ( classArray [ i ] , toClassArray [ i ] , autoboxing ) == false ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a CRON expression . [CODESPLIT] public static Date parseCRONExpression ( String cron ) { try { return new CronExpression ( cron ) . getNextValidTimeAfter ( new Date ( ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Invalid CRON pattern : \" + cron , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the number of milliseconds between the next valid date and the one after . [CODESPLIT] public static long cronInterval ( String cron , Date date ) { try { return new CronExpression ( cron ) . getNextInterval ( date ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Invalid CRON pattern : \" + cron , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates WS client manually from configuration internally creating a new instance of AsyncHttpClient and managing its own thread pool . [CODESPLIT] public static AhcWSClient create ( AhcWSClientConfig config , AhcHttpCache cache , Materializer materializer ) { final StandaloneAhcWSClient client = StandaloneAhcWSClient . create ( config , cache , materializer ) ; return new AhcWSClient ( client , materializer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#inject [CODESPLIT] @ Test public void createNewRoutingDsl ( ) { play . mvc . BodyParser . Default bodyParser = app . injector ( ) . instanceOf ( play . mvc . BodyParser . Default . class ) ; JavaContextComponents javaContextComponents = app . injector ( ) . instanceOf ( JavaContextComponents . class ) ; // #new-routing-dsl RoutingDsl routingDsl = new RoutingDsl ( bodyParser , javaContextComponents ) ; // #new-routing-dsl Router router = routingDsl . GET ( \"/hello/:to\" ) . routingTo ( ( request , to ) -> ok ( \"Hello \" + to ) ) . build ( ) ; assertThat ( makeRequest ( router , \"GET\" , \"/hello/world\" ) , equalTo ( \"Hello world\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a builder to use for loading the given context . [CODESPLIT] public GuiceApplicationBuilder builder ( ApplicationLoader . Context context ) { return initialBuilder . in ( context . environment ( ) ) . loadConfig ( context . initialConfig ( ) ) . overrides ( overrides ( context ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify some bindings that should be used as overrides when loading an application using this context . The default implementation of this method provides bindings that most applications should include . [CODESPLIT] protected GuiceableModule [ ] overrides ( ApplicationLoader . Context context ) { scala . collection . Seq < GuiceableModule > seq = play . api . inject . guice . GuiceApplicationLoader $ . MODULE $ . defaultOverrides ( context . asScala ( ) ) ; return Scala . asArray ( GuiceableModule . class , seq ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 501 NOT_IMPLEMENTED simple result . [CODESPLIT] public static Result TODO ( Request request ) { return status ( NOT_IMPLEMENTED , views . html . defaultpages . todo . render ( request . asScala ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a new value into the current session . [CODESPLIT] @ Deprecated public static void session ( String key , String value ) { session ( ) . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a new value into the flash scope . [CODESPLIT] @ Deprecated public static void flash ( String key , String value ) { flash ( ) . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#pass - arg - action - index [CODESPLIT] @ With ( PassArgAction . class ) public static Result passArgIndex ( Http . Request request ) { User user = request . attrs ( ) . get ( Attrs . USER ) ; return ok ( Json . toJson ( user ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qualify this binding key with the given instance of an annotation . [CODESPLIT] public < A extends Annotation > BindingKey < T > qualifiedWith ( final A instance ) { return underlying . qualifiedWith ( instance ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qualify this binding key with the given annotation . [CODESPLIT] public < A extends Annotation > BindingKey < T > qualifiedWith ( final Class < A > annotation ) { return underlying . qualifiedWith ( annotation ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind this binding key to the given implementation class . [CODESPLIT] public Binding < T > to ( final Class < ? extends T > implementation ) { return underlying . to ( implementation ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind this binding key to the given provider instance . [CODESPLIT] public Binding < T > to ( final Provider < ? extends T > provider ) { return underlying . to ( provider ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind this binding key to the given instance . [CODESPLIT] public < A extends T > Binding < T > to ( final Supplier < A > instance ) { return underlying . to ( new FromJavaSupplier <> ( instance ) ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind this binding key to another binding key . [CODESPLIT] public Binding < T > to ( final BindingKey < ? extends T > key ) { return underlying . to ( key . asScala ( ) ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind this binding key to the given provider class . [CODESPLIT] public < P extends Provider < ? extends T > > Binding < T > toProvider ( final Class < P > provider ) { return underlying . toProvider ( provider ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a configured { [CODESPLIT] public static Caffeine < Object , Object > from ( Config config ) { CaffeineParser parser = new CaffeineParser ( config ) ; config . entrySet ( ) . stream ( ) . map ( Map . Entry :: getKey ) . forEach ( parser :: parse ) ; return parser . cacheBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Lang value from a code ( such as fr or en - US ) . [CODESPLIT] public static Lang forCode ( String code ) { try { return new Lang ( play . api . i18n . Lang . apply ( code ) ) ; } catch ( Exception e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve Lang availables from the application configuration . [CODESPLIT] public static List < Lang > availables ( Application app ) { play . api . i18n . Langs langs = app . injector ( ) . instanceOf ( play . api . i18n . Langs . class ) ; List < play . api . i18n . Lang > availableLangs = Scala . asJava ( langs . availables ( ) ) ; return availableLangs . stream ( ) . map ( Lang :: new ) . collect ( toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Guess the preferred lang in the langs set passed as argument . The first Lang that matches an available Lang wins otherwise returns the first Lang available in this application . [CODESPLIT] public static Lang preferred ( Application app , List < Lang > availableLangs ) { play . api . i18n . Langs langs = app . injector ( ) . instanceOf ( play . api . i18n . Langs . class ) ; Stream < Lang > stream = availableLangs . stream ( ) ; List < play . api . i18n . Lang > langSeq = stream . map ( l -> new play . api . i18n . Lang ( l . toLocale ( ) ) ) . collect ( toList ( ) ) ; return new Lang ( langs . preferred ( Scala . toSeq ( langSeq ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an evolutions reader that reads evolution files from a classloader . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader fromClassLoader ( ClassLoader classLoader ) { return fromClassLoader ( classLoader , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an evolutions reader that reads evolution files from a classloader . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader fromClassLoader ( ClassLoader classLoader , String prefix ) { return new play . api . db . evolutions . ClassLoaderEvolutionsReader ( classLoader , prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an evolutions reader based on a simple map of database names to evolutions . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader fromMap ( Map < String , List < Evolution > > evolutions ) { return new SimpleEvolutionsReader ( evolutions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an evolutions reader for the default database from a list of evolutions . [CODESPLIT] public static play . api . db . evolutions . EvolutionsReader forDefault ( Evolution ... evolutions ) { Map < String , List < Evolution > > map = new HashMap < String , List < Evolution > > ( ) ; map . put ( \"default\" , Arrays . asList ( evolutions ) ) ; return fromMap ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply evolutions for the given database . [CODESPLIT] public static void applyEvolutions ( Database database , play . api . db . evolutions . EvolutionsReader reader , boolean autocommit , String schema ) { DatabaseEvolutions evolutions = new DatabaseEvolutions ( database . asScala ( ) , schema ) ; evolutions . evolve ( evolutions . scripts ( reader ) , autocommit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply evolutions for the given database . [CODESPLIT] public static void applyEvolutions ( Database database , play . api . db . evolutions . EvolutionsReader reader , String schema ) { applyEvolutions ( database , reader , true , schema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleanup evolutions for the given database . [CODESPLIT] public static void cleanupEvolutions ( Database database , boolean autocommit , String schema ) { DatabaseEvolutions evolutions = new DatabaseEvolutions ( database . asScala ( ) , schema ) ; evolutions . evolve ( evolutions . resetScripts ( ) , autocommit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the initial configuration loader . Overrides the default or any previously configured values . [CODESPLIT] public GuiceApplicationBuilder withConfigLoader ( Function < Environment , Config > load ) { return newBuilder ( delegate . loadConfig ( func ( ( play . api . Environment env ) -> new play . api . Configuration ( load . apply ( new Environment ( env ) ) ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the module loader . Overrides the default or any previously configured values . [CODESPLIT] public GuiceApplicationBuilder withModuleLoader ( BiFunction < Environment , Config , List < GuiceableModule > > loader ) { return newBuilder ( delegate . load ( func ( ( play . api . Environment env , play . api . Configuration conf ) -> Scala . toSeq ( loader . apply ( new Environment ( env ) , conf . underlying ( ) ) ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the module loader with the given guiceable modules . [CODESPLIT] public GuiceApplicationBuilder load ( GuiceableModule ... modules ) { return newBuilder ( delegate . load ( Scala . varargs ( modules ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the module loader with the given Guice modules . [CODESPLIT] public GuiceApplicationBuilder load ( com . google . inject . Module ... modules ) { return load ( Guiceable . modules ( modules ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the module loader with the given Play modules . [CODESPLIT] public GuiceApplicationBuilder load ( play . api . inject . Module ... modules ) { return load ( Guiceable . modules ( modules ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the module loader with the given Play bindings . [CODESPLIT] public GuiceApplicationBuilder load ( play . api . inject . Binding < ? > ... bindings ) { return load ( Guiceable . bindings ( bindings ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of Self creation for GuiceBuilder . [CODESPLIT] protected GuiceApplicationBuilder newBuilder ( play . api . inject . guice . GuiceApplicationBuilder builder ) { return new GuiceApplicationBuilder ( builder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the specified cookie into a Cookie header value . [CODESPLIT] public String encode ( Cookie cookie ) { if ( cookie == null ) { throw new NullPointerException ( \"cookie\" ) ; } StringBuilder buf = new StringBuilder ( ) ; encode ( buf , cookie ) ; return stripTrailingSeparator ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the specified cookies into a single Cookie header value . [CODESPLIT] public String encode ( Cookie ... cookies ) { if ( cookies == null ) { throw new NullPointerException ( \"cookies\" ) ; } if ( cookies . length == 0 ) { return null ; } StringBuilder buf = new StringBuilder ( ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encode ( buf , c ) ; } return stripTrailingSeparatorOrNull ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the specified cookies into a single Cookie header value . [CODESPLIT] public String encode ( Iterable < ? extends Cookie > cookies ) { if ( cookies == null ) { throw new NullPointerException ( \"cookies\" ) ; } Iterator < ? extends Cookie > cookiesIt = cookies . iterator ( ) ; if ( ! cookiesIt . hasNext ( ) ) { return null ; } StringBuilder buf = new StringBuilder ( ) ; while ( cookiesIt . hasNext ( ) ) { Cookie c = cookiesIt . next ( ) ; if ( c == null ) { break ; } encode ( buf , c ) ; } return stripTrailingSeparatorOrNull ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default EntityManager for this thread . [CODESPLIT] public EntityManager em ( ) { Deque < EntityManager > ems = this . emStack ( true ) ; if ( ems . isEmpty ( ) ) { Http . Context . safeCurrent ( ) . map ( ctx -> { throw new RuntimeException ( \"No EntityManager found in the context. Try to annotate your action method with @play.db.jpa.Transactional\" ) ; } ) . orElseGet ( ( ) -> { throw new RuntimeException ( \"No EntityManager bound to this thread. Try wrapping this call in JPAApi.withTransaction, or ensure that the HTTP context is setup on this thread.\" ) ; } ) ; } return ems . peekFirst ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the EntityManager stack . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Deque < EntityManager > emStack ( boolean threadLocalFallback ) { return Http . Context . safeCurrent ( ) . map ( context -> { Object emsObject = context . args . get ( CURRENT_ENTITY_MANAGER ) ; if ( emsObject != null ) { return ( Deque < EntityManager > ) emsObject ; } else { Deque < EntityManager > ems = new ArrayDeque <> ( ) ; context . args . put ( CURRENT_ENTITY_MANAGER , ems ) ; return ems ; } } ) . orElseGet ( ( ) -> { // Not a web request if ( threadLocalFallback ) { return this . get ( ) ; } else { throw new RuntimeException ( \"No Http.Context is present. If you want to invoke this method outside of a HTTP request, you need to wrap the call with JPA.withTransaction instead.\" ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes or pops the EntityManager stack depending on the value of the em argument . If em is null then the current EntityManager is popped . If em is non - null then em is pushed onto the stack and becomes the current EntityManager . [CODESPLIT] void pushOrPopEm ( EntityManager em , boolean threadLocalFallback ) { Deque < EntityManager > ems = this . emStack ( threadLocalFallback ) ; if ( em != null ) { ems . push ( em ) ; } else { if ( ems . isEmpty ( ) ) { throw new IllegalStateException ( \"Tried to remove the EntityManager, but none was set.\" ) ; } ems . pop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#person - class [CODESPLIT] @ Test public void fromJson ( ) { // #from-json // parse the JSON as a JsonNode JsonNode json = Json . parse ( \"{\\\"firstName\\\":\\\"Foo\\\", \\\"lastName\\\":\\\"Bar\\\", \\\"age\\\":13}\" ) ; // read the JsonNode as a Person Person person = Json . fromJson ( json , Person . class ) ; // #from-json assertThat ( person . firstName , equalTo ( \"Foo\" ) ) ; assertThat ( person . lastName , equalTo ( \"Bar\" ) ) ; assertThat ( person . age , equalTo ( 13 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#xml - hello [CODESPLIT] public Result sayHello ( Http . Request request ) { Document dom = request . body ( ) . asXml ( ) ; if ( dom == null ) { return badRequest ( \"Expecting Xml data\" ) ; } else { String name = XPath . selectText ( \"//name\" , dom ) ; if ( name == null ) { return badRequest ( \"Missing parameter [name]\" ) ; } else { return ok ( \"Hello \" + name ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#xml - hello - bodyparser [CODESPLIT] @ BodyParser . Of ( BodyParser . Xml . class ) public Result sayHelloBP ( Http . Request request ) { Document dom = request . body ( ) . asXml ( ) ; if ( dom == null ) { return badRequest ( \"Expecting Xml data\" ) ; } else { String name = XPath . selectText ( \"//name\" , dom ) ; if ( name == null ) { return badRequest ( \"Missing parameter [name]\" ) ; } else { return ok ( \"Hello \" + name ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bypass the given flow using the given splitter function . [CODESPLIT] public static < In , FlowIn , Out > Flow < In , Out , ? > bypassWith ( Function < In , F . Either < FlowIn , Out > > splitter , Flow < FlowIn , Out , ? > flow ) { return bypassWith ( Flow . < In > create ( ) . map ( splitter :: apply ) , play . api . libs . streams . AkkaStreams . onlyFirstCanFinishMerge ( 2 ) , flow ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Using the given splitter flow allow messages to bypass a flow . [CODESPLIT] public static < In , FlowIn , Out > Flow < In , Out , ? > bypassWith ( Flow < In , F . Either < FlowIn , Out > , ? > splitter , Graph < UniformFanInShape < Out , Out > , ? > mergeStrategy , Flow < FlowIn , Out , ? > flow ) { return splitter . via ( Flow . fromGraph ( GraphDSL . < FlowShape < F . Either < FlowIn , Out > , Out > > create ( builder -> { // Eager cancel must be true so that if the flow cancels, that will be propagated // upstream. // However, that means the bypasser must block cancel, since when this flow // finishes, the merge // will result in a cancel flowing up through the bypasser, which could lead to // dropped messages. // Using scaladsl here because of https://github.com/akka/akka/issues/18384 UniformFanOutShape < F . Either < FlowIn , Out > , F . Either < FlowIn , Out > > broadcast = builder . add ( Broadcast . create ( 2 , true ) ) ; UniformFanInShape < Out , Out > merge = builder . add ( mergeStrategy ) ; Flow < F . Either < FlowIn , Out > , FlowIn , ? > collectIn = Flow . < F . Either < FlowIn , Out > > create ( ) . collect ( Scala . partialFunction ( x -> { if ( x . left . isPresent ( ) ) { return x . left . get ( ) ; } else { throw Scala . noMatch ( ) ; } } ) ) ; Flow < F . Either < FlowIn , Out > , Out , ? > collectOut = Flow . < F . Either < FlowIn , Out > > create ( ) . collect ( Scala . partialFunction ( x -> { if ( x . right . isPresent ( ) ) { return x . right . get ( ) ; } else { throw Scala . noMatch ( ) ; } } ) ) ; Flow < F . Either < FlowIn , Out > , F . Either < FlowIn , Out > , ? > blockCancel = play . api . libs . streams . AkkaStreams . < F . Either < FlowIn , Out > > ignoreAfterCancellation ( ) . asJava ( ) ; // Normal flow builder . from ( broadcast . out ( 0 ) ) . via ( builder . add ( collectIn ) ) . via ( builder . add ( flow ) ) . toInlet ( merge . in ( 0 ) ) ; // Bypass flow, need to ignore downstream finish builder . from ( broadcast . out ( 1 ) ) . via ( builder . add ( blockCancel ) ) . via ( builder . add ( collectOut ) ) . toInlet ( merge . in ( 1 ) ) ; return new FlowShape <> ( broadcast . in ( ) , merge . out ( ) ) ; } ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a flow that is handled by an actor . [CODESPLIT] public static < In , Out > Flow < In , Out , ? > actorRef ( Function < ActorRef , Props > props , int bufferSize , OverflowStrategy overflowStrategy , ActorRefFactory factory , Materializer mat ) { return play . api . libs . streams . ActorFlow . < In , Out > actorRef ( new AbstractFunction1 < ActorRef , Props > ( ) { @ Override public Props apply ( ActorRef v1 ) { return props . apply ( v1 ) ; } } , bufferSize , overflowStrategy , factory , mat ) . asJava ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds request data to this form - that is handles form submission . [CODESPLIT] @ Deprecated public Form < T > bindFromRequest ( String ... allowedFields ) { return bind ( play . mvc . Controller . ctx ( ) . messages ( ) . lang ( ) , play . mvc . Controller . request ( ) . attrs ( ) , requestData ( play . mvc . Controller . request ( ) ) , requestFileData ( play . mvc . Controller . request ( ) ) , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds request data to this form - that is handles form submission . [CODESPLIT] public Form < T > bindFromRequest ( Http . Request request , String ... allowedFields ) { return bind ( this . messagesApi . preferred ( request ) . lang ( ) , request . attrs ( ) , requestData ( request ) , requestFileData ( request ) , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds request data to this form - that is handles form submission . [CODESPLIT] @ Deprecated public Form < T > bindFromRequest ( Map < String , String [ ] > requestData , String ... allowedFields ) { return bindFromRequestData ( ctxLang ( ) , ctxRequestAttrs ( ) , requestData , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds request data to this form - that is handles form submission . [CODESPLIT] public Form < T > bindFromRequestData ( Lang lang , TypedMap attrs , Map < String , String [ ] > requestData , String ... allowedFields ) { return bindFromRequestData ( lang , attrs , requestData , Collections . emptyMap ( ) , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds Json data to this form - that is handles form submission . [CODESPLIT] @ Deprecated public Form < T > bind ( JsonNode data , String ... allowedFields ) { return bind ( ctxLang ( ) , ctxRequestAttrs ( ) , data , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds Json data to this form - that is handles form submission . [CODESPLIT] public Form < T > bind ( Lang lang , TypedMap attrs , JsonNode data , String ... allowedFields ) { return bind ( lang , attrs , play . libs . Scala . asJava ( play . api . data . FormUtils . fromJson ( \"\" , play . api . libs . json . Json . parse ( play . libs . Json . stringify ( data ) ) ) ) , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When dealing with @ValidateWith or @ValidatePayloadWith annotations and message parameter is not used in the annotation extract the message from validator s getErrorMessageKey () method [CODESPLIT] protected String getMessageForConstraintViolation ( ConstraintViolation < Object > violation ) { String errorMessage = violation . getMessage ( ) ; Annotation annotation = violation . getConstraintDescriptor ( ) . getAnnotation ( ) ; if ( annotation instanceof Constraints . ValidateWith ) { Constraints . ValidateWith validateWithAnnotation = ( Constraints . ValidateWith ) annotation ; if ( violation . getMessage ( ) . equals ( Constraints . ValidateWithValidator . defaultMessage ) ) { Constraints . ValidateWithValidator validateWithValidator = new Constraints . ValidateWithValidator ( ) ; validateWithValidator . initialize ( validateWithAnnotation ) ; Tuple < String , Object [ ] > errorMessageKey = validateWithValidator . getErrorMessageKey ( ) ; if ( errorMessageKey != null && errorMessageKey . _1 != null ) { errorMessage = errorMessageKey . _1 ; } } } if ( annotation instanceof Constraints . ValidatePayloadWith ) { Constraints . ValidatePayloadWith validatePayloadWithAnnotation = ( Constraints . ValidatePayloadWith ) annotation ; if ( violation . getMessage ( ) . equals ( Constraints . ValidatePayloadWithValidator . defaultMessage ) ) { Constraints . ValidatePayloadWithValidator validatePayloadWithValidator = new Constraints . ValidatePayloadWithValidator ( ) ; validatePayloadWithValidator . initialize ( validatePayloadWithAnnotation ) ; Tuple < String , Object [ ] > errorMessageKey = validatePayloadWithValidator . getErrorMessageKey ( ) ; if ( errorMessageKey != null && errorMessageKey . _1 != null ) { errorMessage = errorMessageKey . _1 ; } } } return errorMessage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds data to this form - that is handles form submission . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Deprecated public Form < T > bind ( Map < String , String > data , String ... allowedFields ) { return bind ( ctxLang ( ) , ctxRequestAttrs ( ) , data , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds data to this form - that is handles form submission . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Form < T > bind ( Lang lang , TypedMap attrs , Map < String , String > data , String ... allowedFields ) { return bind ( lang , attrs , data , Collections . emptyMap ( ) , allowedFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds data to this form - that is handles form submission . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Form < T > bind ( Lang lang , TypedMap attrs , Map < String , String > data , Map < String , Http . MultipartFormData . FilePart < ? > > files , String ... allowedFields ) { final DataBinder dataBinder = dataBinder ( allowedFields ) ; final Map < String , Object > objectDataFinal = getObjectData ( data , files ) ; final Set < ConstraintViolation < Object > > validationErrors = runValidation ( lang , attrs , dataBinder , objectDataFinal ) ; final BindingResult result = dataBinder . getBindingResult ( ) ; validationErrors . forEach ( violation -> addConstraintViolationToBindingResult ( violation , result ) ) ; boolean hasAnyError = result . hasErrors ( ) || result . getGlobalErrorCount ( ) > 0 ; if ( hasAnyError ) { final List < ValidationError > errors = getFieldErrorsAsValidationErrors ( lang , result ) ; final List < ValidationError > globalErrors = globalErrorsAsValidationErrors ( result ) ; errors . addAll ( globalErrors ) ; return new Form <> ( rootName , backedType , data , files , errors , Optional . ofNullable ( ( T ) result . getTarget ( ) ) , groups , messagesApi , formatters , this . validatorFactory , config , lang , directFieldAccess ) ; } return new Form <> ( rootName , backedType , data , files , errors , Optional . ofNullable ( ( T ) result . getTarget ( ) ) , groups , messagesApi , formatters , this . validatorFactory , config , lang , directFieldAccess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the error arguments . [CODESPLIT] private List < Object > convertErrorArguments ( Object [ ] arguments ) { if ( arguments == null ) { return Collections . emptyList ( ) ; } List < Object > converted = Arrays . stream ( arguments ) . filter ( arg -> ! ( arg instanceof org . springframework . context . support . DefaultMessageSourceResolvable ) ) . collect ( Collectors . toList ( ) ) ; return Collections . unmodifiableList ( converted ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates this form with an existing value used for edit forms . [CODESPLIT] public Form < T > fill ( T value ) { if ( value == null ) { throw new RuntimeException ( \"Cannot fill a form with a null value\" ) ; } return new Form <> ( rootName , backedType , new HashMap <> ( ) , new HashMap <> ( ) , new ArrayList <> ( ) , Optional . ofNullable ( value ) , groups , messagesApi , formatters , validatorFactory , config , lang , directFieldAccess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all global errors - errors without a key . [CODESPLIT] public List < ValidationError > globalErrors ( ) { return Collections . unmodifiableList ( errors . stream ( ) . filter ( error -> error . key ( ) . isEmpty ( ) ) . collect ( Collectors . toList ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the form errors serialized as Json using the given Lang . [CODESPLIT] public JsonNode errorsAsJson ( Lang lang ) { Map < String , List < String > > allMessages = new HashMap <> ( ) ; errors . forEach ( error -> { if ( error != null ) { final List < String > messages = new ArrayList <> ( ) ; if ( messagesApi != null && lang != null ) { final List < String > reversedMessages = new ArrayList <> ( error . messages ( ) ) ; Collections . reverse ( reversedMessages ) ; messages . add ( messagesApi . get ( lang , reversedMessages , translateMsgArg ( error . arguments ( ) , messagesApi , lang ) ) ) ; } else { messages . add ( error . message ( ) ) ; } allMessages . put ( error . key ( ) , messages ) ; } } ) ; return play . libs . Json . toJson ( allMessages ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the concrete value only if the submission was a success . If the form is invalid because of validation errors this method will throw an exception . If you want to retrieve the value even when the form is invalid use { @link #value () } instead . [CODESPLIT] public T get ( Lang lang ) { if ( ! errors . isEmpty ( ) ) { throw new IllegalStateException ( \"Error(s) binding form: \" + errorsAsJson ( lang ) ) ; } return value . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a field . [CODESPLIT] public Field field ( final String key , final Lang lang ) { // Value String fieldValue = null ; Http . MultipartFormData . FilePart file = null ; if ( rawData . containsKey ( key ) ) { fieldValue = rawData . get ( key ) ; } else if ( files . containsKey ( key ) ) { file = files . get ( key ) ; } else { if ( value . isPresent ( ) ) { BeanWrapper beanWrapper = new BeanWrapperImpl ( value . get ( ) ) ; beanWrapper . setAutoGrowNestedPaths ( true ) ; String objectKey = key ; if ( rootName != null && key . startsWith ( rootName + \".\" ) ) { objectKey = key . substring ( rootName . length ( ) + 1 ) ; } if ( beanWrapper . isReadableProperty ( objectKey ) ) { Object oValue = beanWrapper . getPropertyValue ( objectKey ) ; if ( oValue != null ) { if ( oValue instanceof Http . MultipartFormData . FilePart < ? > ) { file = ( Http . MultipartFormData . FilePart < ? > ) oValue ; } else { if ( formatters != null ) { final String objectKeyFinal = objectKey ; fieldValue = withRequestLocale ( lang , ( ) -> formatters . print ( beanWrapper . getPropertyTypeDescriptor ( objectKeyFinal ) , oValue ) ) ; } else { fieldValue = oValue . toString ( ) ; } } } } } } // Format Tuple < String , List < Object > > format = null ; BeanWrapper beanWrapper = new BeanWrapperImpl ( blankInstance ( ) ) ; beanWrapper . setAutoGrowNestedPaths ( true ) ; try { for ( Annotation a : beanWrapper . getPropertyTypeDescriptor ( key ) . getAnnotations ( ) ) { Class < ? > annotationType = a . annotationType ( ) ; if ( annotationType . isAnnotationPresent ( play . data . Form . Display . class ) ) { play . data . Form . Display d = annotationType . getAnnotation ( play . data . Form . Display . class ) ; if ( d . name ( ) . startsWith ( \"format.\" ) ) { List < Object > attributes = new ArrayList <> ( ) ; for ( String attr : d . attributes ( ) ) { Object attrValue = null ; try { attrValue = a . getClass ( ) . getDeclaredMethod ( attr ) . invoke ( a ) ; } catch ( Exception e ) { // do nothing } attributes . add ( attrValue ) ; } format = Tuple ( d . name ( ) , Collections . unmodifiableList ( attributes ) ) ; } } } } catch ( NullPointerException e ) { // do nothing } // Constraints List < Tuple < String , List < Object > > > constraints = new ArrayList <> ( ) ; Class < ? > classType = backedType ; String leafKey = key ; if ( rootName != null && leafKey . startsWith ( rootName + \".\" ) ) { leafKey = leafKey . substring ( rootName . length ( ) + 1 ) ; } int p = leafKey . lastIndexOf ( ' ' ) ; if ( p > 0 ) { classType = beanWrapper . getPropertyType ( leafKey . substring ( 0 , p ) ) ; leafKey = leafKey . substring ( p + 1 ) ; } if ( classType != null && this . validatorFactory != null ) { BeanDescriptor beanDescriptor = this . validatorFactory . getValidator ( ) . getConstraintsForClass ( classType ) ; if ( beanDescriptor != null ) { PropertyDescriptor property = beanDescriptor . getConstraintsForProperty ( leafKey ) ; if ( property != null ) { Annotation [ ] orderedAnnotations = null ; for ( Class < ? > c = classType ; c != null ; c = c . getSuperclass ( ) ) { // we also check the fields of all superclasses java . lang . reflect . Field field = null ; try { field = c . getDeclaredField ( leafKey ) ; } catch ( NoSuchFieldException | SecurityException e ) { continue ; } // getDeclaredAnnotations also looks for private fields; also it provides the // annotations in a guaranteed order orderedAnnotations = AnnotationUtils . unwrapContainerAnnotations ( field . getDeclaredAnnotations ( ) ) ; break ; } constraints = Constraints . displayableConstraint ( property . findConstraints ( ) . unorderedAndMatchingGroups ( groups != null ? groups : new Class [ ] { Default . class } ) . getConstraintDescriptors ( ) , orderedAnnotations ) ; } } } return new Field ( this , key , constraints , format , errors ( key ) , fieldValue , file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A copy of this form with the given lang set which is used for formatting when retrieving a field ( via { [CODESPLIT] public Form < T > withLang ( Lang lang ) { return new Form < T > ( this . rootName , this . backedType , this . rawData , this . files , this . errors , this . value , this . groups , this . messagesApi , this . formatters , this . validatorFactory , this . config , lang , this . directFieldAccess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the locale of the current request ( if there is one ) into Spring s LocaleContextHolder . [CODESPLIT] private static < T > T withRequestLocale ( Lang lang , Supplier < T > code ) { try { LocaleContextHolder . setLocale ( lang != null ? lang . toLocale ( ) : null ) ; } catch ( Exception e ) { // Just continue (Maybe there is no context or some internal error in LocaleContextHolder). // System default locale will be used. } try { return code . get ( ) ; } finally { LocaleContextHolder . resetLocaleContext ( ) ; // Clean up ThreadLocal } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the concrete value only if the submission was a success . If the form is invalid because of validation errors or you try to access a file field this method will return null . If you want to retrieve the value even when the form is invalid use { @link #value ( String ) } instead . If you want to retrieve a file field use { @link #file ( String ) } instead . [CODESPLIT] public String get ( String key ) { try { return ( String ) get ( ) . getData ( ) . get ( asNormalKey ( key ) ) ; } catch ( Exception e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the concrete value only if the submission was a success . If the form is invalid because of validation errors or you try to access a non - file field this method will return null . If you want to retrieve the value even when the form is invalid use { @link #value ( String ) } instead . If you want to retrieve a non - file field use { @link #get ( String ) } instead . [CODESPLIT] public < A > Http . MultipartFormData . FilePart < A > file ( String key ) { try { return ( Http . MultipartFormData . FilePart < A > ) get ( ) . getData ( ) . get ( asNormalKey ( key ) ) ; } catch ( Exception e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the concrete value [CODESPLIT] public Optional < Object > value ( String key ) { return super . value ( ) . map ( v -> v . getData ( ) . get ( asNormalKey ( key ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fills the form with existing data . [CODESPLIT] public DynamicForm fill ( Map < String , Object > value ) { Form < Dynamic > form = super . fill ( new Dynamic ( value ) ) ; return new DynamicForm ( form . rawData ( ) , form . files ( ) , form . errors ( ) , form . value ( ) , messagesApi , formatters , validatorFactory , config , lang ( ) . orElse ( null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- tools [CODESPLIT] static String asDynamicKey ( String key ) { if ( key . isEmpty ( ) || MATCHES_DATA . matcher ( key ) . matches ( ) ) { return key ; } else { return \"data[\" + key + \"]\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses this string as instance of the given class . [CODESPLIT] public < T > T parse ( String text , Class < T > clazz ) { return conversion . convert ( text , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses this string as instance of a specific field [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T parse ( Field field , String text ) { return ( T ) conversion . convert ( text , new TypeDescriptor ( field ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the display string for any value . [CODESPLIT] public < T > String print ( T t ) { if ( t == null ) { return \"\" ; } if ( conversion . canConvert ( t . getClass ( ) , String . class ) ) { return conversion . convert ( t , String . class ) ; } else { return t . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the display string for any value for a specific field . [CODESPLIT] public < T > String print ( Field field , T t ) { return print ( new TypeDescriptor ( field ) , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the display string for any value for a specific type . [CODESPLIT] public < T > String print ( TypeDescriptor desc , T t ) { if ( t == null ) { return \"\" ; } if ( desc != null && conversion . canConvert ( desc , TypeDescriptor . valueOf ( String . class ) ) ) { return ( String ) conversion . convert ( t , desc , TypeDescriptor . valueOf ( String . class ) ) ; } else if ( conversion . canConvert ( t . getClass ( ) , String . class ) ) { return conversion . convert ( t , String . class ) ; } else { return t . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converter for String - > Optional and Optional - > String [CODESPLIT] private Formatters registerOptional ( ) { conversion . addConverter ( new GenericConverter ( ) { public Object convert ( Object source , TypeDescriptor sourceType , TypeDescriptor targetType ) { if ( sourceType . getObjectType ( ) . equals ( String . class ) ) { // From String to Optional Object element = conversion . convert ( source , sourceType , targetType . elementTypeDescriptor ( source ) ) ; return Optional . ofNullable ( element ) ; } else if ( targetType . getObjectType ( ) . equals ( String . class ) ) { // From Optional to String if ( source == null ) return \"\" ; Optional < ? > opt = ( Optional ) source ; return opt . map ( o -> conversion . convert ( source , sourceType . getElementTypeDescriptor ( ) , targetType ) ) . orElse ( \"\" ) ; } return null ; } public Set < GenericConverter . ConvertiblePair > getConvertibleTypes ( ) { Set < ConvertiblePair > result = new HashSet <> ( ) ; result . add ( new ConvertiblePair ( Optional . class , String . class ) ) ; result . add ( new ConvertiblePair ( String . class , Optional . class ) ) ; return result ; } } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a simple formatter . [CODESPLIT] public < T > Formatters register ( final Class < T > clazz , final SimpleFormatter < T > formatter ) { conversion . addFormatterForFieldType ( clazz , new org . springframework . format . Formatter < T > ( ) { public T parse ( String text , Locale locale ) throws java . text . ParseException { return formatter . parse ( text , locale ) ; } public String print ( T t , Locale locale ) { return formatter . print ( t , locale ) ; } public String toString ( ) { return formatter . toString ( ) ; } } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers an annotation - based formatter . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < A extends Annotation , T > Formatters register ( final Class < T > clazz , final AnnotationFormatter < A , T > formatter ) { final Class < ? extends Annotation > annotationType = ( Class < ? extends Annotation > ) GenericTypeResolver . resolveTypeArguments ( formatter . getClass ( ) , AnnotationFormatter . class ) [ 0 ] ; conversion . addConverter ( new ConditionalGenericConverter ( ) { public Set < GenericConverter . ConvertiblePair > getConvertibleTypes ( ) { Set < GenericConverter . ConvertiblePair > types = new HashSet <> ( ) ; types . add ( new GenericConverter . ConvertiblePair ( clazz , String . class ) ) ; return types ; } public boolean matches ( TypeDescriptor sourceType , TypeDescriptor targetType ) { return ( sourceType . getAnnotation ( annotationType ) != null ) ; } public Object convert ( Object source , TypeDescriptor sourceType , TypeDescriptor targetType ) { final A a = ( A ) sourceType . getAnnotation ( annotationType ) ; Locale locale = LocaleContextHolder . getLocale ( ) ; try { return formatter . print ( a , ( T ) source , locale ) ; } catch ( Exception ex ) { throw new ConversionFailedException ( sourceType , targetType , source , ex ) ; } } public String toString ( ) { return \"@\" + annotationType . getName ( ) + \" \" + clazz . getName ( ) + \" -> \" + String . class . getName ( ) + \": \" + formatter ; } } ) ; conversion . addConverter ( new ConditionalGenericConverter ( ) { public Set < GenericConverter . ConvertiblePair > getConvertibleTypes ( ) { Set < GenericConverter . ConvertiblePair > types = new HashSet <> ( ) ; types . add ( new GenericConverter . ConvertiblePair ( String . class , clazz ) ) ; return types ; } public boolean matches ( TypeDescriptor sourceType , TypeDescriptor targetType ) { return ( targetType . getAnnotation ( annotationType ) != null ) ; } public Object convert ( Object source , TypeDescriptor sourceType , TypeDescriptor targetType ) { final A a = ( A ) targetType . getAnnotation ( annotationType ) ; Locale locale = LocaleContextHolder . getLocale ( ) ; try { return formatter . parse ( a , ( String ) source , locale ) ; } catch ( Exception ex ) { throw new ConversionFailedException ( sourceType , targetType , source , ex ) ; } } public String toString ( ) { return String . class . getName ( ) + \" -> @\" + annotationType . getName ( ) + \" \" + clazz . getName ( ) + \": \" + formatter ; } } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the specified cookie into a Set - Cookie header value . [CODESPLIT] public String encode ( Cookie cookie ) { if ( cookie == null ) { throw new NullPointerException ( \"cookie\" ) ; } final String name = cookie . name ( ) ; final String value = cookie . value ( ) != null ? cookie . value ( ) : \"\" ; validateCookie ( name , value ) ; StringBuilder buf = new StringBuilder ( ) ; if ( cookie . wrap ( ) ) { addQuoted ( buf , name , value ) ; } else { add ( buf , name , value ) ; } if ( cookie . maxAge ( ) != Integer . MIN_VALUE ) { add ( buf , CookieHeaderNames . MAX_AGE , cookie . maxAge ( ) ) ; Date expires = cookie . maxAge ( ) <= 0 ? new Date ( 0 ) // Set expires to the Unix epoch : new Date ( cookie . maxAge ( ) * 1000L + System . currentTimeMillis ( ) ) ; add ( buf , CookieHeaderNames . EXPIRES , HttpHeaderDateFormat . get ( ) . format ( expires ) ) ; } if ( cookie . sameSite ( ) != null ) { add ( buf , CookieHeaderNames . SAMESITE , cookie . sameSite ( ) ) ; } if ( cookie . path ( ) != null ) { add ( buf , CookieHeaderNames . PATH , cookie . path ( ) ) ; } if ( cookie . domain ( ) != null ) { add ( buf , CookieHeaderNames . DOMAIN , cookie . domain ( ) ) ; } if ( cookie . isSecure ( ) ) { add ( buf , CookieHeaderNames . SECURE ) ; } if ( cookie . isHttpOnly ( ) ) { add ( buf , CookieHeaderNames . HTTPONLY ) ; } return stripTrailingSeparator ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch encodes cookies into Set - Cookie header values . [CODESPLIT] public List < String > encode ( Cookie ... cookies ) { if ( cookies == null ) { throw new NullPointerException ( \"cookies\" ) ; } if ( cookies . length == 0 ) { return Collections . emptyList ( ) ; } List < String > encoded = new ArrayList < String > ( cookies . length ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encoded . add ( encode ( c ) ) ; } return encoded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch encodes cookies into Set - Cookie header values . [CODESPLIT] public List < String > encode ( Collection < ? extends Cookie > cookies ) { if ( cookies == null ) { throw new NullPointerException ( \"cookies\" ) ; } if ( cookies . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < String > encoded = new ArrayList < String > ( cookies . size ( ) ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encoded . add ( encode ( c ) ) ; } return encoded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch encodes cookies into Set - Cookie header values . [CODESPLIT] public List < String > encode ( Iterable < ? extends Cookie > cookies ) { if ( cookies == null ) { throw new NullPointerException ( \"cookies\" ) ; } if ( cookies . iterator ( ) . hasNext ( ) ) { return Collections . emptyList ( ) ; } List < String > encoded = new ArrayList < String > ( ) ; for ( Cookie c : cookies ) { if ( c == null ) { break ; } encoded . add ( encode ( c ) ) ; } return encoded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the specified Set - Cookie HTTP header value into a { @link Cookie } . [CODESPLIT] public Set < Cookie > decode ( String header ) { if ( header == null ) { throw new NullPointerException ( \"header\" ) ; } final int headerLen = header . length ( ) ; if ( headerLen == 0 ) { return Collections . emptySet ( ) ; } Set < Cookie > cookies = new TreeSet < Cookie > ( ) ; int i = 0 ; boolean rfc2965Style = false ; if ( header . regionMatches ( true , 0 , RFC2965_VERSION , 0 , RFC2965_VERSION . length ( ) ) ) { // RFC 2965 style cookie, move to after version value i = header . indexOf ( ' ' ) + 1 ; rfc2965Style = true ; } loop : for ( ; ; ) { // Skip spaces and separators. for ( ; ; ) { if ( i == headerLen ) { break loop ; } char c = header . charAt ( i ) ; if ( c == ' ' || c == ' ' || c == 0x0b || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' ) { i ++ ; continue ; } break ; } int nameBegin = i ; int nameEnd = i ; int valueBegin = - 1 ; int valueEnd = - 1 ; if ( i != headerLen ) { keyValLoop : for ( ; ; ) { char curChar = header . charAt ( i ) ; if ( curChar == ' ' ) { // NAME; (no value till ';') nameEnd = i ; valueBegin = valueEnd = - 1 ; break keyValLoop ; } else if ( curChar == ' ' ) { // NAME=VALUE nameEnd = i ; i ++ ; if ( i == headerLen ) { // NAME= (empty value, i.e. nothing after '=') valueBegin = valueEnd = 0 ; break keyValLoop ; } valueBegin = i ; // NAME=VALUE; int semiPos = header . indexOf ( ' ' , i ) ; valueEnd = i = semiPos > 0 ? semiPos : headerLen ; break keyValLoop ; } else { i ++ ; } if ( i == headerLen ) { // NAME (no value till the end of string) nameEnd = headerLen ; valueBegin = valueEnd = - 1 ; break ; } } } if ( rfc2965Style && ( header . regionMatches ( nameBegin , RFC2965_PATH , 0 , RFC2965_PATH . length ( ) ) || header . regionMatches ( nameBegin , RFC2965_DOMAIN , 0 , RFC2965_DOMAIN . length ( ) ) || header . regionMatches ( nameBegin , RFC2965_PORT , 0 , RFC2965_PORT . length ( ) ) ) ) { // skip obsolete RFC2965 fields continue ; } DefaultCookie cookie = initCookie ( header , nameBegin , nameEnd , valueBegin , valueEnd ) ; if ( cookie != null ) { cookies . add ( cookie ) ; } } return cookies ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofStream ( Http . Request request , InputStream stream ) { return JavaRangeResult . ofStream ( stream , rangeHeader ( request ) , null , Optional . empty ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofStream ( InputStream stream , long contentLength ) { return ofStream ( Http . Context . current ( ) . request ( ) , stream , contentLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofPath ( Http . Request request , Path path ) { return ofPath ( request , path , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofPath ( Http . Request request , Path path , FileMimeTypes fileMimeTypes ) { return JavaRangeResult . ofPath ( path , rangeHeader ( request ) , fileMimeTypes . forFileName ( path . toFile ( ) . getName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofPath ( Path path , String fileName ) { return ofPath ( Http . Context . current ( ) . request ( ) , path , fileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the path as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofPath ( Http . Request request , Path path , String fileName , FileMimeTypes fileMimeTypes ) { return JavaRangeResult . ofPath ( path , rangeHeader ( request ) , fileName , fileMimeTypes . forFileName ( fileName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the file as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofFile ( File file , String fileName ) { return ofFile ( Http . Context . current ( ) . request ( ) , file , fileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the file as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofFile ( Http . Request request , File file , String fileName ) { return ofFile ( request , file , fileName , StaticFileMimeTypes . fileMimeTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the file as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofFile ( Http . Request request , File file , String fileName , FileMimeTypes fileMimeTypes ) { return JavaRangeResult . ofFile ( file , rangeHeader ( request ) , fileName , fileMimeTypes . forFileName ( fileName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] @ Deprecated public static Result ofSource ( Long entityLength , Source < ByteString , ? > source , String fileName , String contentType ) { return ofSource ( Http . Context . current ( ) . request ( ) , entityLength , source , fileName , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stream as a result considering Range header . If the header is present and it is satisfiable then a Result containing just the requested part will be returned . If the header is not present or is unsatisfiable then a regular Result will be returned . [CODESPLIT] public static Result ofSource ( Http . Request request , Long entityLength , Source < ByteString , ? > source , String fileName , String contentType ) { return JavaRangeResult . ofSource ( entityLength , source , rangeHeader ( request ) , Optional . ofNullable ( fileName ) , Optional . ofNullable ( contentType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select all nodes that are selected by this XPath expression . If multiple nodes match multiple nodes will be returned . Nodes will be returned in document - order [CODESPLIT] public static NodeList selectNodes ( String path , Object node ) { return selectNodes ( path , node , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a Java List to Scala Seq . [CODESPLIT] public static < T > scala . collection . immutable . Seq < T > toSeq ( java . util . List < T > list ) { return scala . collection . JavaConverters . asScalaBufferConverter ( list ) . asScala ( ) . toList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a Java Array to Scala Seq . [CODESPLIT] public static < T > scala . collection . immutable . Seq < T > toSeq ( T [ ] array ) { return toSeq ( java . util . Arrays . asList ( array ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a Java varargs to Scala varargs . [CODESPLIT] @ SafeVarargs public static < T > scala . collection . immutable . Seq < T > varargs ( T ... array ) { return toSeq ( array ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acceptor for JSON WebSockets . [CODESPLIT] public static < In , Out > MappedWebSocketAcceptor < In , Out > json ( Class < In > in ) { return new MappedWebSocketAcceptor <> ( Scala . partialFunction ( message -> { try { if ( message instanceof Message . Binary ) { return F . Either . Left ( play . libs . Json . mapper ( ) . readValue ( ( ( Message . Binary ) message ) . data ( ) . iterator ( ) . asInputStream ( ) , in ) ) ; } else if ( message instanceof Message . Text ) { return F . Either . Left ( play . libs . Json . mapper ( ) . readValue ( ( ( Message . Text ) message ) . data ( ) , in ) ) ; } } catch ( Exception e ) { return F . Either . Right ( new Message . Close ( CloseCodes . Unacceptable ( ) , e . getMessage ( ) ) ) ; } throw Scala . noMatch ( ) ; } ) , outMessage -> { try { return new Message . Text ( play . libs . Json . mapper ( ) . writeValueAsString ( outMessage ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper to create handlers for WebSockets . [CODESPLIT] private static < In , Out > WebSocket acceptOrResult ( PartialFunction < Message , F . Either < In , Message > > inMapper , Function < Http . RequestHeader , CompletionStage < F . Either < Result , Flow < In , Out , ? > > > > f , Function < Out , Message > outMapper ) { return new WebSocket ( ) { @ Override public CompletionStage < F . Either < Result , Flow < Message , Message , ? > > > apply ( Http . RequestHeader request ) { return f . apply ( request ) . thenApply ( resultOrFlow -> { if ( resultOrFlow . left . isPresent ( ) ) { return F . Either . Left ( resultOrFlow . left . get ( ) ) ; } else { Flow < Message , Message , ? > flow = AkkaStreams . bypassWith ( Flow . < Message > create ( ) . collect ( inMapper ) , play . api . libs . streams . AkkaStreams . onlyFirstCanFinishMerge ( 2 ) , resultOrFlow . right . get ( ) . map ( outMapper :: apply ) ) ; return F . Either . Right ( flow ) ; } } ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether a { @link Member } is accessible . [CODESPLIT] static boolean isAccessible ( final Member m ) { return m != null && Modifier . isPublic ( m . getModifiers ( ) ) && ! m . isSynthetic ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "XXX Default access superclass workaround . [CODESPLIT] static boolean setAccessibleWorkaround ( final AccessibleObject o ) { if ( o == null || o . isAccessible ( ) ) { return false ; } final Member m = ( Member ) o ; if ( ! o . isAccessible ( ) && Modifier . isPublic ( m . getModifiers ( ) ) && isPackageAccess ( m . getDeclaringClass ( ) . getModifiers ( ) ) ) { try { o . setAccessible ( true ) ; return true ; } catch ( final SecurityException e ) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the relative fitness of two Constructors in terms of how well they match a set of runtime parameter types such that a list ordered by the results of the comparison would return the best match first ( least ) . [CODESPLIT] static int compareConstructorFit ( final Constructor < ? > left , final Constructor < ? > right , final Class < ? > [ ] actual ) { return compareParameterTypes ( Executable . of ( left ) , Executable . of ( right ) , actual ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the relative fitness of two Methods in terms of how well they match a set of runtime parameter types such that a list ordered by the results of the comparison would return the best match first ( least ) . [CODESPLIT] static int compareMethodFit ( final Method left , final Method right , final Class < ? > [ ] actual ) { return compareParameterTypes ( Executable . of ( left ) , Executable . of ( right ) , actual ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the relative fitness of two Executables in terms of how well they match a set of runtime parameter types such that a list ordered by the results of the comparison would return the best match first ( least ) . [CODESPLIT] private static int compareParameterTypes ( final Executable left , final Executable right , final Class < ? > [ ] actual ) { final float leftCost = getTotalTransformationCost ( actual , left ) ; final float rightCost = getTotalTransformationCost ( actual , right ) ; return leftCost < rightCost ? - 1 : rightCost < leftCost ? 1 : 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the number of steps required to promote a primitive number to another type . [CODESPLIT] private static float getPrimitivePromotionCost ( final Class < ? > srcClass , final Class < ? > destClass ) { float cost = 0.0f ; Class < ? > cls = srcClass ; if ( ! cls . isPrimitive ( ) ) { // slight unwrapping penalty cost += 0.1f ; cls = ClassUtils . wrapperToPrimitive ( cls ) ; } for ( int i = 0 ; cls != destClass && i < ORDERED_PRIMITIVE_TYPES . length ; i ++ ) { if ( cls == ORDERED_PRIMITIVE_TYPES [ i ] ) { cost += 0.1f ; if ( i < ORDERED_PRIMITIVE_TYPES . length - 1 ) { cls = ORDERED_PRIMITIVE_TYPES [ i + 1 ] ; } } } return cost ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the sum of the object transformation cost for each class in the source argument list . [CODESPLIT] private static float getTotalTransformationCost ( final Class < ? > [ ] srcArgs , final Executable executable ) { final Class < ? > [ ] destArgs = executable . getParameterTypes ( ) ; final boolean isVarArgs = executable . isVarArgs ( ) ; // \"source\" and \"destination\" are the actual and declared args respectively. float totalCost = 0.0f ; final long normalArgsLen = isVarArgs ? destArgs . length - 1 : destArgs . length ; if ( srcArgs . length < normalArgsLen ) { return Float . MAX_VALUE ; } for ( int i = 0 ; i < normalArgsLen ; i ++ ) { totalCost += getObjectTransformationCost ( srcArgs [ i ] , destArgs [ i ] ) ; } if ( isVarArgs ) { // When isVarArgs is true, srcArgs and dstArgs may differ in length. // There are two special cases to consider: final boolean noVarArgsPassed = srcArgs . length < destArgs . length ; final boolean explicitArrayForVarags = srcArgs . length == destArgs . length && srcArgs [ srcArgs . length - 1 ] . isArray ( ) ; final float varArgsCost = 0.001f ; final Class < ? > destClass = destArgs [ destArgs . length - 1 ] . getComponentType ( ) ; if ( noVarArgsPassed ) { // When no varargs passed, the best match is the most generic matching type, not the most // specific. totalCost += getObjectTransformationCost ( destClass , Object . class ) + varArgsCost ; } else if ( explicitArrayForVarags ) { final Class < ? > sourceClass = srcArgs [ srcArgs . length - 1 ] . getComponentType ( ) ; totalCost += getObjectTransformationCost ( sourceClass , destClass ) + varArgsCost ; } else { // This is typical varargs case. for ( int i = destArgs . length - 1 ; i < srcArgs . length ; i ++ ) { final Class < ? > srcClass = srcArgs [ i ] ; totalCost += getObjectTransformationCost ( srcClass , destClass ) + varArgsCost ; } } } return totalCost ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the number of steps required needed to turn the source class into the destination class . This represents the number of steps in the object hierarchy graph . [CODESPLIT] private static float getObjectTransformationCost ( Class < ? > srcClass , final Class < ? > destClass ) { if ( destClass . isPrimitive ( ) ) { return getPrimitivePromotionCost ( srcClass , destClass ) ; } float cost = 0.0f ; while ( srcClass != null && ! destClass . equals ( srcClass ) ) { if ( destClass . isInterface ( ) && ClassUtils . isAssignable ( srcClass , destClass ) ) { // slight penalty for interface match. // we still want an exact match to override an interface match, // but // an interface match should override anything where we have to // get a superclass. cost += 0.25f ; break ; } cost ++ ; srcClass = srcClass . getSuperclass ( ) ; } /*\n     * If the destination class is null, we've traveled all the way up to\n     * an Object match. We'll penalize this by adding 1.5 to the cost.\n     */ if ( srcClass == null ) { cost += 1.5f ; } return cost ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "#explicit - messages - api [CODESPLIT] private MessagesApi explicitMessagesApi ( ) { return new play . i18n . MessagesApi ( new play . api . i18n . DefaultMessagesApi ( Collections . singletonMap ( Lang . defaultLang ( ) . code ( ) , Collections . singletonMap ( \"foo\" , \"bar\" ) ) , new play . api . i18n . DefaultLangs ( ) . asJava ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the message at the given key . [CODESPLIT] public String at ( String key , Object ... args ) { return messagesApi . get ( lang , key , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the message at the first defined key . [CODESPLIT] public String at ( List < String > keys , Object ... args ) { return messagesApi . get ( lang , keys , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a pooled database with the given configuration . [CODESPLIT] public static Database createFrom ( String name , String driver , String url , Map < String , ? extends Object > config ) { ImmutableMap . Builder < String , Object > dbConfig = new ImmutableMap . Builder < String , Object > ( ) ; dbConfig . put ( \"driver\" , driver ) ; dbConfig . put ( \"url\" , url ) ; dbConfig . putAll ( config ) ; return new DefaultDatabase ( name , dbConfig . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a pooled database with the given configuration . [CODESPLIT] public static Database createFrom ( String name , String driver , String url ) { return createFrom ( name , driver , url , ImmutableMap . < String , Object > of ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a pooled database named default with the given configuration . [CODESPLIT] public static Database createFrom ( String driver , String url , Map < String , ? extends Object > config ) { return createFrom ( \"default\" , driver , url , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name , String url , Map < String , ? extends Object > config ) { return createFrom ( name , \"org.h2.Driver\" , url , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name , Map < String , String > urlOptions , Map < String , ? extends Object > config ) { StringBuilder urlExtra = new StringBuilder ( ) ; for ( Map . Entry < String , String > option : urlOptions . entrySet ( ) ) { urlExtra . append ( ' ' ) . append ( option . getKey ( ) ) . append ( ' ' ) . append ( option . getValue ( ) ) ; } String url = \"jdbc:h2:mem:\" + name + urlExtra ; return inMemory ( name , url , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name , Map < String , ? extends Object > config ) { return inMemory ( name , \"jdbc:h2:mem:\" + name , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an in - memory H2 database . [CODESPLIT] public static Database inMemory ( String name ) { return inMemory ( name , ImmutableMap . < String , Object > of ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an in - memory H2 database with name default and with extra configuration provided by the given entries . [CODESPLIT] public static Database inMemoryWith ( String k1 , Object v1 ) { return inMemory ( ImmutableMap . of ( k1 , v1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an in - memory H2 database with name default and with extra configuration provided by the given entries . [CODESPLIT] public static Database inMemoryWith ( String k1 , Object v1 , String k2 , Object v2 , String k3 , Object v3 ) { return inMemory ( ImmutableMap . of ( k1 , v1 , k2 , v2 , k3 , v3 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create a new <code > BeanMap< / code > . For finer control over the generated instance use a new instance of <code > BeanMap . Generator< / code > instead of this static method . [CODESPLIT] public static BeanMap create ( Object bean ) { Generator gen = new Generator ( ) ; gen . setBean ( bean ) ; return gen . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : optimize [CODESPLIT] public Set entrySet ( ) { HashMap copy = new HashMap ( ) ; for ( Iterator it = keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Object key = it . next ( ) ; copy . put ( key , get ( key ) ) ; } return Collections . unmodifiableMap ( copy ) . entrySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new ParallelSorter object for a set of arrays . You may sort the arrays multiple times via the same ParallelSorter object . [CODESPLIT] public static ParallelSorter create ( Object [ ] arrays ) { Generator gen = new Generator ( ) ; gen . setArrays ( arrays ) ; return gen . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort the arrays using the quicksort algorithm . [CODESPLIT] public void quickSort ( int index , int lo , int hi , Comparator cmp ) { chooseComparer ( index , cmp ) ; super . quickSort ( lo , hi - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort the arrays using an in - place merge sort . [CODESPLIT] public void mergeSort ( int index , int lo , int hi , Comparator cmp ) { chooseComparer ( index , cmp ) ; super . mergeSort ( lo , hi - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : support constructor indices ( <init > ) [CODESPLIT] private void emitIndexBySignature ( List methods ) { CodeEmitter e = begin_method ( Constants . ACC_PUBLIC , SIGNATURE_GET_INDEX , null ) ; List signatures = CollectionUtils . transform ( methods , new Transformer ( ) { public Object transform ( Object obj ) { return ReflectUtils . getSignature ( ( Method ) obj ) . toString ( ) ; } } ) ; e . load_arg ( 0 ) ; e . invoke_virtual ( Constants . TYPE_OBJECT , TO_STRING ) ; signatureSwitchHelper ( e , signatures ) ; e . end_method ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO [CODESPLIT] private void emitIndexByClassArray ( List methods ) { CodeEmitter e = begin_method ( Constants . ACC_PUBLIC , METHOD_GET_INDEX , null ) ; if ( methods . size ( ) > TOO_MANY_METHODS ) { // hack for big classes List signatures = CollectionUtils . transform ( methods , new Transformer ( ) { public Object transform ( Object obj ) { String s = ReflectUtils . getSignature ( ( Method ) obj ) . toString ( ) ; return s . substring ( 0 , s . lastIndexOf ( ' ' ) + 1 ) ; } } ) ; e . load_args ( ) ; e . invoke_static ( FAST_CLASS , GET_SIGNATURE_WITHOUT_RETURN_TYPE ) ; signatureSwitchHelper ( e , signatures ) ; } else { e . load_args ( ) ; List info = CollectionUtils . transform ( methods , MethodInfoTransformer . getInstance ( ) ) ; EmitUtils . method_switch ( e , info , new GetIndexCallback ( e , info ) ) ; } e . end_method ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create an interface mixin . For finer control over the generated instance use a new instance of <code > Mixin< / code > instead of this static method . TODO [CODESPLIT] public static Mixin create ( Object [ ] delegates ) { Generator gen = new Generator ( ) ; gen . setDelegates ( delegates ) ; return gen . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create an interface mixin . For finer control over the generated instance use a new instance of <code > Mixin< / code > instead of this static method . TODO [CODESPLIT] public static Mixin create ( Class [ ] interfaces , Object [ ] delegates ) { Generator gen = new Generator ( ) ; gen . setClasses ( interfaces ) ; gen . setDelegates ( delegates ) ; return gen . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create a bean mixin . For finer control over the generated instance use a new instance of <code > Mixin< / code > instead of this static method . TODO [CODESPLIT] public static Mixin createBean ( ClassLoader loader , Object [ ] beans ) { Generator gen = new Generator ( ) ; gen . setStyle ( STYLE_BEANS ) ; gen . setDelegates ( beans ) ; gen . setClassLoader ( loader ) ; return gen . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private static Route route ( Object [ ] delegates ) { Object key = ClassesKey . create ( delegates ) ; Route route = ( Route ) ROUTE_CACHE . get ( key ) ; if ( route == null ) { ROUTE_CACHE . put ( key , route = new Route ( delegates ) ) ; } return route ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For internal use by { [CODESPLIT] public static MethodProxy create ( Class c1 , Class c2 , String desc , String name1 , String name2 ) { MethodProxy proxy = new MethodProxy ( ) ; proxy . sig1 = new Signature ( name1 , desc ) ; proxy . sig2 = new Signature ( name2 , desc ) ; proxy . createInfo = new CreateInfo ( c1 , c2 ) ; return proxy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the <code > MethodProxy< / code > used when intercepting the method matching the given signature . [CODESPLIT] public static MethodProxy find ( Class type , Signature sig ) { try { Method m = type . getDeclaredMethod ( MethodInterceptorGenerator . FIND_PROXY_NAME , MethodInterceptorGenerator . FIND_PROXY_TYPES ) ; return ( MethodProxy ) m . invoke ( null , new Object [ ] { sig } ) ; } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( \"Class \" + type + \" does not use a MethodInterceptor\" ) ; } catch ( IllegalAccessException e ) { throw new CodeGenerationException ( e ) ; } catch ( InvocationTargetException e ) { throw new CodeGenerationException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke the original method on a different object of the same type . [CODESPLIT] public Object invoke ( Object obj , Object [ ] args ) throws Throwable { try { init ( ) ; FastClassInfo fci = fastClassInfo ; return fci . f1 . invoke ( fci . i1 , obj , args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } catch ( IllegalArgumentException e ) { if ( fastClassInfo . i1 < 0 ) throw new IllegalArgumentException ( \"Protected method: \" + sig1 ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke the original ( super ) method on the specified object . [CODESPLIT] public Object invokeSuper ( Object obj , Object [ ] args ) throws Throwable { try { init ( ) ; FastClassInfo fci = fastClassInfo ; return fci . f2 . invoke ( fci . i2 , obj , args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Casts from one primitive numeric type to another [CODESPLIT] public void cast_numeric ( Type from , Type to ) { if ( from != to ) { if ( from == Type . DOUBLE_TYPE ) { if ( to == Type . FLOAT_TYPE ) { mv . visitInsn ( Constants . D2F ) ; } else if ( to == Type . LONG_TYPE ) { mv . visitInsn ( Constants . D2L ) ; } else { mv . visitInsn ( Constants . D2I ) ; cast_numeric ( Type . INT_TYPE , to ) ; } } else if ( from == Type . FLOAT_TYPE ) { if ( to == Type . DOUBLE_TYPE ) { mv . visitInsn ( Constants . F2D ) ; } else if ( to == Type . LONG_TYPE ) { mv . visitInsn ( Constants . F2L ) ; } else { mv . visitInsn ( Constants . F2I ) ; cast_numeric ( Type . INT_TYPE , to ) ; } } else if ( from == Type . LONG_TYPE ) { if ( to == Type . DOUBLE_TYPE ) { mv . visitInsn ( Constants . L2D ) ; } else if ( to == Type . FLOAT_TYPE ) { mv . visitInsn ( Constants . L2F ) ; } else { mv . visitInsn ( Constants . L2I ) ; cast_numeric ( Type . INT_TYPE , to ) ; } } else { if ( to == Type . BYTE_TYPE ) { mv . visitInsn ( Constants . I2B ) ; } else if ( to == Type . CHAR_TYPE ) { mv . visitInsn ( Constants . I2C ) ; } else if ( to == Type . DOUBLE_TYPE ) { mv . visitInsn ( Constants . I2D ) ; } else if ( to == Type . FLOAT_TYPE ) { mv . visitInsn ( Constants . I2F ) ; } else if ( to == Type . LONG_TYPE ) { mv . visitInsn ( Constants . I2L ) ; } else if ( to == Type . SHORT_TYPE ) { mv . visitInsn ( Constants . I2S ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes the specified argument of the current method onto the stack . [CODESPLIT] public void load_arg ( int index ) { load_local ( state . argumentTypes [ index ] , state . localOffset + skipArgs ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "zero - based ( see load_this ) [CODESPLIT] public void load_args ( int fromArg , int count ) { int pos = state . localOffset + skipArgs ( fromArg ) ; for ( int i = 0 ; i < count ; i ++ ) { Type t = state . argumentTypes [ fromArg + i ] ; load_local ( t , pos ) ; pos += t . getSize ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package - protected for EmitUtils try to fix [CODESPLIT] void emit_field ( int opcode , Type ctype , String name , Type ftype ) { mv . visitFieldInsn ( opcode , ctype . getInternalName ( ) , name , ftype . getDescriptor ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the argument is a primitive class replaces the primitive value on the top of the stack with the wrapped ( Object ) equivalent . For example char - > Character . If the class is Void a null is pushed onto the stack instead . [CODESPLIT] public void box ( Type type ) { if ( TypeUtils . isPrimitive ( type ) ) { if ( type == Type . VOID_TYPE ) { aconst_null ( ) ; } else { Type boxed = TypeUtils . getBoxedType ( type ) ; new_instance ( boxed ) ; if ( type . getSize ( ) == 2 ) { // Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o dup_x2 ( ) ; dup_x2 ( ) ; pop ( ) ; } else { // p -> po -> opo -> oop -> o dup_x1 ( ) ; swap ( ) ; } invoke_constructor ( boxed , new Signature ( Constants . CONSTRUCTOR_NAME , Type . VOID_TYPE , new Type [ ] { type } ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the argument is a primitive class replaces the object on the top of the stack with the unwrapped ( primitive ) equivalent . For example Character - > char . [CODESPLIT] public void unbox ( Type type ) { Type t = Constants . TYPE_NUMBER ; Signature sig = null ; switch ( type . getSort ( ) ) { case Type . VOID : return ; case Type . CHAR : t = Constants . TYPE_CHARACTER ; sig = CHAR_VALUE ; break ; case Type . BOOLEAN : t = Constants . TYPE_BOOLEAN ; sig = BOOLEAN_VALUE ; break ; case Type . DOUBLE : sig = DOUBLE_VALUE ; break ; case Type . FLOAT : sig = FLOAT_VALUE ; break ; case Type . LONG : sig = LONG_VALUE ; break ; case Type . INT : case Type . SHORT : case Type . BYTE : sig = INT_VALUE ; } if ( sig == null ) { checkcast ( type ) ; } else { checkcast ( t ) ; invoke_virtual ( t , sig ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocates and fills an Object [] array with the arguments to the current method . Primitive values are inserted as their boxed ( Object ) equivalents . [CODESPLIT] public void create_arg_array ( ) { /* generates:\n           Object[] args = new Object[]{ arg1, new Integer(arg2) };\n         */ push ( state . argumentTypes . length ) ; newarray ( ) ; for ( int i = 0 ; i < state . argumentTypes . length ; i ++ ) { dup ( ) ; push ( i ) ; load_arg ( i ) ; box ( state . argumentTypes [ i ] ) ; aastore ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes a zero onto the stack if the argument is a primitive class or a null otherwise . [CODESPLIT] public void zero_or_null ( Type type ) { if ( TypeUtils . isPrimitive ( type ) ) { switch ( type . getSort ( ) ) { case Type . DOUBLE : push ( 0d ) ; break ; case Type . LONG : push ( 0L ) ; break ; case Type . FLOAT : push ( 0f ) ; break ; case Type . VOID : aconst_null ( ) ; default : push ( 0 ) ; } } else { aconst_null ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unboxes the object on the top of the stack . If the object is null the unboxed primitive value becomes zero . [CODESPLIT] public void unbox_or_zero ( Type type ) { if ( TypeUtils . isPrimitive ( type ) ) { if ( type != Type . VOID_TYPE ) { Label nonNull = make_label ( ) ; Label end = make_label ( ) ; dup ( ) ; ifnonnull ( nonNull ) ; pop ( ) ; zero_or_null ( type ) ; goTo ( end ) ; mark ( nonNull ) ; unbox ( type ) ; mark ( end ) ; } } else { checkcast ( type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process an array on the stack . Assumes the top item on the stack is an array of the specified type . For each element in the array puts the element on the stack and triggers the callback . [CODESPLIT] public static void process_array ( CodeEmitter e , Type type , ProcessArrayCallback callback ) { Type componentType = TypeUtils . getComponentType ( type ) ; Local array = e . make_local ( ) ; Local loopvar = e . make_local ( Type . INT_TYPE ) ; Label loopbody = e . make_label ( ) ; Label checkloop = e . make_label ( ) ; e . store_local ( array ) ; e . push ( 0 ) ; e . store_local ( loopvar ) ; e . goTo ( checkloop ) ; e . mark ( loopbody ) ; e . load_local ( array ) ; e . load_local ( loopvar ) ; e . array_load ( componentType ) ; callback . processElement ( componentType ) ; e . iinc ( loopvar , 1 ) ; e . mark ( checkloop ) ; e . load_local ( loopvar ) ; e . load_local ( array ) ; e . arraylength ( ) ; e . if_icmp ( e . LT , loopbody ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Branches to the specified label if the top two items on the stack are not equal . The items must both be of the specified class . Equality is determined by comparing primitive values directly and by invoking the <code > equals< / code > method for Objects . Arrays are recursively processed in the same manner . [CODESPLIT] public static void not_equals ( final CodeEmitter e , Type type , final Label notEquals , final CustomizerRegistry registry ) { ( new ProcessArrayCallback ( ) { public void processElement ( Type type ) { not_equals_helper ( e , type , notEquals , registry , this ) ; } } ) . processElement ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If both objects on the top of the stack are non - null does nothing . If one is null or both are null both are popped off and execution branches to the respective label . [CODESPLIT] private static void nullcmp ( CodeEmitter e , Label oneNull , Label bothNull ) { e . dup2 ( ) ; Label nonNull = e . make_label ( ) ; Label oneNullHelper = e . make_label ( ) ; Label end = e . make_label ( ) ; e . ifnonnull ( nonNull ) ; e . ifnonnull ( oneNullHelper ) ; e . pop2 ( ) ; e . goTo ( bothNull ) ; e . mark ( nonNull ) ; e . ifnull ( oneNullHelper ) ; e . goTo ( end ) ; e . mark ( oneNullHelper ) ; e . pop2 ( ) ; e . goTo ( oneNull ) ; e . mark ( end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * generates : } catch ( RuntimeException e ) { throw e ; } catch ( Error e ) { throw e ; } catch ( <DeclaredException > e ) { throw e ; } catch ( Throwable e ) { throw new <Wrapper > ( e ) ; } [CODESPLIT] public static void wrap_undeclared_throwable ( CodeEmitter e , Block handler , Type [ ] exceptions , Type wrapper ) { Set set = ( exceptions == null ) ? Collections . EMPTY_SET : new HashSet ( Arrays . asList ( exceptions ) ) ; if ( set . contains ( Constants . TYPE_THROWABLE ) ) return ; boolean needThrow = exceptions != null ; if ( ! set . contains ( Constants . TYPE_RUNTIME_EXCEPTION ) ) { e . catch_exception ( handler , Constants . TYPE_RUNTIME_EXCEPTION ) ; needThrow = true ; } if ( ! set . contains ( Constants . TYPE_ERROR ) ) { e . catch_exception ( handler , Constants . TYPE_ERROR ) ; needThrow = true ; } if ( exceptions != null ) { for ( int i = 0 ; i < exceptions . length ; i ++ ) { e . catch_exception ( handler , exceptions [ i ] ) ; } } if ( needThrow ) { e . athrow ( ) ; } // e -> eo -> oeo -> ooe -> o e . catch_exception ( handler , Constants . TYPE_THROWABLE ) ; e . new_instance ( wrapper ) ; e . dup_x1 ( ) ; e . swap ( ) ; e . invoke_constructor ( wrapper , CSTRUCT_THROWABLE ) ; e . athrow ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all bridge methods that are being called with invokespecial & returns them . [CODESPLIT] public Map /*<Signature, Signature>*/ resolveAll ( ) { Map resolved = new HashMap ( ) ; for ( Iterator entryIter = declToBridge . entrySet ( ) . iterator ( ) ; entryIter . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) entryIter . next ( ) ; Class owner = ( Class ) entry . getKey ( ) ; Set bridges = ( Set ) entry . getValue ( ) ; try { InputStream is = classLoader . getResourceAsStream ( owner . getName ( ) . replace ( ' ' , ' ' ) + \".class\" ) ; if ( is == null ) { return resolved ; } try { new ClassReader ( is ) . accept ( new BridgedFinder ( bridges , resolved ) , ClassReader . SKIP_FRAMES | ClassReader . SKIP_DEBUG ) ; } finally { is . close ( ) ; } } catch ( IOException ignored ) { } } return resolved ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the class which the generated class will extend . As a convenience if the supplied superclass is actually an interface <code > setInterfaces< / code > will be called with the appropriate argument instead . A non - interface argument must not be declared as final and must have an accessible constructor . [CODESPLIT] public void setSuperclass ( Class superclass ) { if ( superclass != null && superclass . isInterface ( ) ) { setInterfaces ( new Class [ ] { superclass } ) ; } else if ( superclass != null && superclass . equals ( Object . class ) ) { // affects choice of ClassLoader this . superclass = null ; } else { this . superclass = superclass ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the array of callbacks to use . Ignored if you use { [CODESPLIT] public void setCallbacks ( Callback [ ] callbacks ) { if ( callbacks != null && callbacks . length == 0 ) { throw new IllegalArgumentException ( \"Array cannot be empty\" ) ; } this . callbacks = callbacks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the array of callback types to use . This may be used instead of { [CODESPLIT] public void setCallbackTypes ( Class [ ] callbackTypes ) { if ( callbackTypes != null && callbackTypes . length == 0 ) { throw new IllegalArgumentException ( \"Array cannot be empty\" ) ; } this . callbackTypes = CallbackInfo . determineTypes ( callbackTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a new class if necessary and uses the specified callbacks ( if any ) to create a new object instance . Uses the constructor of the superclass matching the <code > argumentTypes< / code > parameter with the given arguments . [CODESPLIT] public Object create ( Class [ ] argumentTypes , Object [ ] arguments ) { classOnly = false ; if ( argumentTypes == null || arguments == null || argumentTypes . length != arguments . length ) { throw new IllegalArgumentException ( \"Arguments must be non-null and of equal length\" ) ; } this . argumentTypes = argumentTypes ; this . arguments = arguments ; return createHelper ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all of the methods that will be extended by an Enhancer - generated class using the specified superclass and interfaces . This can be useful in building a list of Callback objects . The methods are added to the end of the given list . Due to the subclassing nature of the classes generated by Enhancer the methods are guaranteed to be non - static non - final and non - private . Each method signature will only occur once even if it occurs in multiple classes . [CODESPLIT] public static void getMethods ( Class superclass , Class [ ] interfaces , List methods ) { getMethods ( superclass , interfaces , methods , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter the list of constructors from the superclass . The constructors which remain will be included in the generated class . The default implementation is to filter out all private constructors but subclasses may extend Enhancer to override this behavior . [CODESPLIT] protected void filterConstructors ( Class sc , List constructors ) { CollectionUtils . filter ( constructors , new VisibilityPredicate ( sc , true ) ) ; if ( constructors . size ( ) == 0 ) throw new IllegalArgumentException ( \"No visible constructors in \" + sc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a class was generated using <code > Enhancer< / code > . [CODESPLIT] public static boolean isEnhanced ( Class type ) { try { getCallbacksSetter ( type , SET_THREAD_CALLBACKS_NAME ) ; return true ; } catch ( NoSuchMethodException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a proxy instance and assigns callback values . Implementation detail : java . lang . reflect instances are not cached so this method should not be used on a hot path . This method is used when { @link #setUseCache ( boolean ) } is set to { @code false } . [CODESPLIT] private Object createUsingReflection ( Class type ) { setThreadCallbacks ( type , callbacks ) ; try { if ( argumentTypes != null ) { return ReflectUtils . newInstance ( type , argumentTypes , arguments ) ; } else { return ReflectUtils . newInstance ( type ) ; } } finally { // clear thread callbacks to allow them to be gc'd setThreadCallbacks ( type , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create an intercepted object . For finer control over the generated instance use a new instance of <code > Enhancer< / code > instead of this static method . [CODESPLIT] public static Object create ( Class type , Callback callback ) { Enhancer e = new Enhancer ( ) ; e . setSuperclass ( type ) ; e . setCallback ( callback ) ; return e . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create an intercepted object . For finer control over the generated instance use a new instance of <code > Enhancer< / code > instead of this static method . [CODESPLIT] public static Object create ( Class superclass , Class interfaces [ ] , Callback callback ) { Enhancer e = new Enhancer ( ) ; e . setSuperclass ( superclass ) ; e . setInterfaces ( interfaces ) ; e . setCallback ( callback ) ; return e . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create an intercepted object . For finer control over the generated instance use a new instance of <code > Enhancer< / code > instead of this static method . [CODESPLIT] public static Object create ( Class superclass , Class [ ] interfaces , CallbackFilter filter , Callback [ ] callbacks ) { Enhancer e = new Enhancer ( ) ; e . setSuperclass ( superclass ) ; e . setInterfaces ( interfaces ) ; e . setCallbackFilter ( filter ) ; e . setCallbacks ( callbacks ) ; return e . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the class which the generated class will extend . The class must not be declared as final and must have a non - private no - argument constructor . [CODESPLIT] public void setSuperclass ( Class superclass ) { if ( superclass != null && superclass . equals ( Object . class ) ) { superclass = null ; } this . superclass = superclass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to avoid JVM hashcode implementation incompatibilities [CODESPLIT] private void getField ( String [ ] names ) throws Exception { final CodeEmitter e = begin_method ( Constants . ACC_PUBLIC , PROVIDER_GET , null ) ; e . load_this ( ) ; e . load_arg ( 0 ) ; EmitUtils . string_switch ( e , names , Constants . SWITCH_STYLE_HASH , new ObjectSwitchCallback ( ) { public void processCase ( Object key , Label end ) { Type type = ( Type ) fields . get ( key ) ; e . getfield ( ( String ) key ) ; e . box ( type ) ; e . return_value ( ) ; } public void processDefault ( ) { e . throw_exception ( ILLEGAL_ARGUMENT_EXCEPTION , \"Unknown field name\" ) ; } } ) ; e . end_method ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a method signature to the interface . The method modifiers are ignored since interface methods are by definition abstract and public . [CODESPLIT] public void add ( Method method ) { add ( ReflectUtils . getSignature ( method ) , ReflectUtils . getExceptionTypes ( method ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all the public methods in the specified class . Methods from superclasses are included except for methods declared in the base Object class ( e . g . <code > getClass< / code > <code > equals< / code > <code > hashCode< / code > ) . [CODESPLIT] public void add ( Class clazz ) { Method [ ] methods = clazz . getMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method m = methods [ i ] ; if ( ! m . getDeclaringClass ( ) . getName ( ) . equals ( \"java.lang.Object\" ) ) { add ( m ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If bit 31 is set then this method results in an infinite loop . [CODESPLIT] public int cardinality ( ) { int w = value ; int c = 0 ; while ( w != 0 ) { c += T [ w & 255 ] ; w >>= 8 ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the default naming policy . [CODESPLIT] public void setNamingPolicy ( NamingPolicy namingPolicy ) { if ( namingPolicy == null ) namingPolicy = DefaultNamingPolicy . INSTANCE ; this . namingPolicy = namingPolicy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the strategy to use to create the bytecode from this generator . By default an instance of { [CODESPLIT] public void setStrategy ( GeneratorStrategy strategy ) { if ( strategy == null ) strategy = DefaultGeneratorStrategy . INSTANCE ; this . strategy = strategy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads entry to the cache . If entry is missing put { [CODESPLIT] protected V createEntry ( final K key , KK cacheKey , Object v ) { FutureTask < V > task ; boolean creator = false ; if ( v != null ) { // Another thread is already loading an instance task = ( FutureTask < V > ) v ; } else { task = new FutureTask < V > ( new Callable < V > ( ) { public V call ( ) throws Exception { return loader . apply ( key ) ; } } ) ; Object prevTask = map . putIfAbsent ( cacheKey , task ) ; if ( prevTask == null ) { // creator does the load creator = true ; task . run ( ) ; } else if ( prevTask instanceof FutureTask ) { task = ( FutureTask < V > ) prevTask ; } else { return ( V ) prevTask ; } } V result ; try { result = task . get ( ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( \"Interrupted while loading cache item\" , e ) ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof RuntimeException ) { throw ( ( RuntimeException ) cause ) ; } throw new IllegalStateException ( \"Unable to load cache item\" , cause ) ; } if ( creator ) { map . put ( cacheKey , result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used by MethodInterceptorGenerated generated code [CODESPLIT] public static Method [ ] findMethods ( String [ ] namesAndDescriptors , Method [ ] methods ) { Map map = new HashMap ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method method = methods [ i ] ; map . put ( method . getName ( ) + Type . getMethodDescriptor ( method ) , method ) ; } Method [ ] result = new Method [ namesAndDescriptors . length / 2 ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = ( Method ) map . get ( namesAndDescriptors [ i * 2 ] + namesAndDescriptors [ i * 2 + 1 ] ) ; if ( result [ i ] == null ) { // TODO: error? } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves subpath in safer way . For some reason if child starts with a separator it gets resolved as a full path ignoring the base . This method acts different . [CODESPLIT] public static Path resolve ( final Path base , String child ) { if ( StringUtil . startsWithChar ( child , File . separatorChar ) ) { child = child . substring ( 1 ) ; } return base . resolve ( child ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads path content . [CODESPLIT] public static String readString ( final Path path ) throws IOException { try ( BufferedReader reader = Files . newBufferedReader ( path , StandardCharsets . UTF_8 ) ) { StringWriter writer = new StringWriter ( ) ; // flush & close not needed for StringWriter-instance StreamUtil . copy ( reader , writer ) ; return writer . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets request host name . [CODESPLIT] public HttpRequest host ( final String host ) { this . host = host ; if ( headers . contains ( HEADER_HOST ) ) { headerOverwrite ( HEADER_HOST , host ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the destination ( method host port ... ) at once . [CODESPLIT] public HttpRequest set ( String destination ) { destination = destination . trim ( ) ; // http method, optional int ndx = destination . indexOf ( ' ' ) ; if ( ndx != - 1 ) { String method = destination . substring ( 0 , ndx ) . toUpperCase ( ) ; try { HttpMethod httpMethod = HttpMethod . valueOf ( method ) ; this . method = httpMethod . name ( ) ; destination = destination . substring ( ndx + 1 ) ; } catch ( IllegalArgumentException ignore ) { // unknown http method } } // protocol ndx = destination . indexOf ( \"://\" ) ; if ( ndx != - 1 ) { protocol = destination . substring ( 0 , ndx ) ; destination = destination . substring ( ndx + 3 ) ; } // host ndx = destination . indexOf ( ' ' ) ; if ( ndx == - 1 ) { ndx = destination . length ( ) ; } if ( ndx != 0 ) { String hostToSet = destination . substring ( 0 , ndx ) ; destination = destination . substring ( ndx ) ; // port ndx = hostToSet . indexOf ( ' ' ) ; if ( ndx == - 1 ) { port = Defaults . DEFAULT_PORT ; } else { port = Integer . parseInt ( hostToSet . substring ( ndx + 1 ) ) ; hostToSet = hostToSet . substring ( 0 , ndx ) ; } host ( hostToSet ) ; } // path + query path ( destination ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic request builder usually used when method is a variable . Otherwise use one of the other static request builder methods . [CODESPLIT] public static HttpRequest create ( final String method , final String destination ) { return new HttpRequest ( ) . method ( method . toUpperCase ( ) ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a CONNECT request . [CODESPLIT] public static HttpRequest connect ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . CONNECT ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a GET request . [CODESPLIT] public static HttpRequest get ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . GET ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a POST request . [CODESPLIT] public static HttpRequest post ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . POST ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a PUT request . [CODESPLIT] public static HttpRequest put ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . PUT ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a PATCH request . [CODESPLIT] public static HttpRequest patch ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . PATCH ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a DELETE request . [CODESPLIT] public static HttpRequest delete ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . DELETE ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a HEAD request . [CODESPLIT] public static HttpRequest head ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . HEAD ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a TRACE request . [CODESPLIT] public static HttpRequest trace ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . TRACE ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds an OPTIONS request . [CODESPLIT] public static HttpRequest options ( final String destination ) { return new HttpRequest ( ) . method ( HttpMethod . OPTIONS ) . set ( destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets request path . Query string is allowed . Adds a slash if path doesn t start with one . Query will be stripped out from the path . Previous query is discarded . [CODESPLIT] public HttpRequest path ( String path ) { // this must be the only place that sets the path if ( ! path . startsWith ( StringPool . SLASH ) ) { path = StringPool . SLASH + path ; } int ndx = path . indexOf ( ' ' ) ; if ( ndx != - 1 ) { String queryString = path . substring ( ndx + 1 ) ; path = path . substring ( 0 , ndx ) ; query = HttpUtil . parseQuery ( queryString , true ) ; } else { query = HttpMultiMap . newCaseInsensitiveMap ( ) ; } this . path = path ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets cookies to the request . [CODESPLIT] public HttpRequest cookies ( final Cookie ... cookies ) { if ( cookies . length == 0 ) { return this ; } StringBuilder cookieString = new StringBuilder ( ) ; boolean first = true ; for ( Cookie cookie : cookies ) { Integer maxAge = cookie . getMaxAge ( ) ; if ( maxAge != null && maxAge . intValue ( ) == 0 ) { continue ; } if ( ! first ) { cookieString . append ( \"; \" ) ; } first = false ; cookieString . append ( cookie . getName ( ) ) ; cookieString . append ( ' ' ) ; cookieString . append ( cookie . getValue ( ) ) ; } headerOverwrite ( \"cookie\" , cookieString . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds query parameter . [CODESPLIT] public HttpRequest query ( final String name , final String value ) { query . add ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds many query parameters at once . Although it accepts objects each value will be converted to string . [CODESPLIT] public HttpRequest query ( final String name1 , final Object value1 , final Object ... parameters ) { query ( name1 , value1 == null ? null : value1 . toString ( ) ) ; for ( int i = 0 ; i < parameters . length ; i += 2 ) { String name = parameters [ i ] . toString ( ) ; String value = parameters [ i + 1 ] . toString ( ) ; query . add ( name , value ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all parameters from the provided map . [CODESPLIT] public HttpRequest query ( final Map < String , String > queryMap ) { for ( Map . Entry < String , String > entry : queryMap . entrySet ( ) ) { query . add ( entry . getKey ( ) , entry . getValue ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets query from provided query string . Previous query values are discarded . [CODESPLIT] public HttpRequest queryString ( final String queryString , final boolean decode ) { this . query = HttpUtil . parseQuery ( queryString , decode ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates query string . All values are URL encoded . [CODESPLIT] public String queryString ( ) { if ( query == null ) { return StringPool . EMPTY ; } return HttpUtil . buildQuery ( query , queryEncoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns full URL path . Simply concatenates { [CODESPLIT] public String url ( ) { StringBuilder url = new StringBuilder ( ) ; url . append ( hostUrl ( ) ) ; if ( path != null ) { url . append ( path ) ; } String queryString = queryString ( ) ; if ( StringUtil . isNotBlank ( queryString ) ) { url . append ( ' ' ) ; url . append ( queryString ) ; } return url . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns just host url without path and query . [CODESPLIT] public String hostUrl ( ) { StringBand url = new StringBand ( 8 ) ; if ( protocol != null ) { url . append ( protocol ) ; url . append ( \"://\" ) ; } if ( host != null ) { url . append ( host ) ; } if ( port != Defaults . DEFAULT_PORT ) { url . append ( ' ' ) ; url . append ( port ) ; } return url . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables basic authentication by adding required header . [CODESPLIT] public HttpRequest basicAuthentication ( final String username , final String password ) { if ( username != null && password != null ) { String data = username . concat ( StringPool . COLON ) . concat ( password ) ; String base64 = Base64 . encodeToString ( data ) ; headerOverwrite ( HEADER_AUTHORIZATION , \"Basic \" + base64 ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets Host header from current host and port . [CODESPLIT] public HttpRequest setHostHeader ( ) { String hostPort = this . host ; if ( port != Defaults . DEFAULT_PORT ) { hostPort += StringPool . COLON + port ; } headerOverwrite ( HEADER_HOST , hostPort ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a new { [CODESPLIT] public HttpRequest open ( final HttpConnectionProvider httpConnectionProvider ) { if ( this . httpConnection != null ) { throw new HttpException ( \"Connection already opened\" ) ; } try { this . httpConnectionProvider = httpConnectionProvider ; this . httpConnection = httpConnectionProvider . createHttpConnection ( this ) ; } catch ( IOException ioex ) { throw new HttpException ( \"Can't connect to: \" + url ( ) , ioex ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assignees provided { [CODESPLIT] public HttpRequest open ( final HttpConnection httpConnection ) { if ( this . httpConnection != null ) { throw new HttpException ( \"Connection already opened\" ) ; } this . httpConnection = httpConnection ; this . httpConnectionProvider = null ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Continues using the same keep - alive connection . Don t use any variant of <code > open () < / code > when continuing the communication! First it checks if Connection header exist in the response and if it is equal to Keep - Alive value . Then it checks the Keep - Alive headers max parameter . If its value is positive then the existing { @link jodd . http . HttpConnection } from the request will be reused . If max value is 1 connection will be sent with Connection : Close header indicating its the last request . When new connection is created the same { @link jodd . http . HttpConnectionProvider } that was used for creating initial connection is used for opening the new connection . [CODESPLIT] public HttpRequest keepAlive ( final HttpResponse httpResponse , final boolean doContinue ) { boolean keepAlive = httpResponse . isConnectionPersistent ( ) ; if ( keepAlive ) { HttpConnection previousConnection = httpResponse . getHttpRequest ( ) . httpConnection ; if ( previousConnection != null ) { // keep using the connection! this . httpConnection = previousConnection ; this . httpConnectionProvider = httpResponse . getHttpRequest ( ) . connectionProvider ( ) ; } //keepAlive = true; (already set) } else { // close previous connection httpResponse . close ( ) ; // force keep-alive on new request keepAlive = true ; } // if we don't want to continue with this persistent session, mark this connection as closed if ( ! doContinue ) { keepAlive = false ; } connectionKeepAlive ( keepAlive ) ; // if connection is not opened, open it using previous connection provider if ( httpConnection == null ) { open ( httpResponse . getHttpRequest ( ) . connectionProvider ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public HttpResponse send ( ) { if ( ! followRedirects ) { return _send ( ) ; } int redirects = this . maxRedirects ; while ( redirects > 0 ) { redirects -- ; final HttpResponse httpResponse = _send ( ) ; final int statusCode = httpResponse . statusCode ( ) ; if ( HttpStatus . isRedirect ( statusCode ) ) { _reset ( ) ; set ( httpResponse . location ( ) ) ; continue ; } return httpResponse ; } throw new HttpException ( \"Max number of redirects exceeded: \" + this . maxRedirects ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the request buffer . [CODESPLIT] @ Override protected Buffer buffer ( final boolean fullRequest ) { // INITIALIZATION // host port if ( header ( HEADER_HOST ) == null ) { setHostHeader ( ) ; } // form Buffer formBuffer = formBuffer ( ) ; // query string String queryString = queryString ( ) ; // user-agent if ( header ( \"User-Agent\" ) == null ) { header ( \"User-Agent\" , Defaults . userAgent ) ; } // POST method requires Content-Type to be set if ( method . equals ( \"POST\" ) && ( contentLength ( ) == null ) ) { contentLength ( 0 ) ; } // BUILD OUT Buffer request = new Buffer ( ) ; request . append ( method ) . append ( SPACE ) . append ( path ) ; if ( query != null && ! query . isEmpty ( ) ) { request . append ( ' ' ) ; request . append ( queryString ) ; } request . append ( SPACE ) . append ( httpVersion ) . append ( CRLF ) ; populateHeaderAndBody ( request , formBuffer , fullRequest ) ; return request ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Syntax sugar . [CODESPLIT] public < R > R sendAndReceive ( final Function < HttpResponse , R > responseHandler ) { return responseHandler . apply ( send ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { @link Session } with or without custom { @link Properties } . [CODESPLIT] protected Session createSession ( Properties properties ) { if ( properties == null ) { properties = System . getProperties ( ) ; } this . session = Session . getInstance ( properties ) ; return session ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies properties from given set . If { @link Session } is already created exception will be thrown . [CODESPLIT] public T set ( final Properties properties ) throws MailException { checkSessionNotSet ( ) ; this . properties . putAll ( properties ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets property for the { @link Session } . If { @link Session } is already created an exception will be thrown . [CODESPLIT] public T set ( final String name , final String value ) { checkSessionNotSet ( ) ; properties . setProperty ( name , value ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add new error message to the { [CODESPLIT] public void addError ( final String message ) { if ( config . collectErrors ) { if ( errors == null ) { errors = new ArrayList <> ( ) ; } errors . add ( message ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the range between start and end from the Handler list that begins with the given element . [CODESPLIT] static Handler removeRange ( final Handler firstHandler , final Label start , final Label end ) { if ( firstHandler == null ) { return null ; } else { firstHandler . nextHandler = removeRange ( firstHandler . nextHandler , start , end ) ; } int handlerStart = firstHandler . startPc . bytecodeOffset ; int handlerEnd = firstHandler . endPc . bytecodeOffset ; int rangeStart = start . bytecodeOffset ; int rangeEnd = end == null ? Integer . MAX_VALUE : end . bytecodeOffset ; // Return early if [handlerStart,handlerEnd[ and [rangeStart,rangeEnd[ don't intersect. if ( rangeStart >= handlerEnd || rangeEnd <= handlerStart ) { return firstHandler ; } if ( rangeStart <= handlerStart ) { if ( rangeEnd >= handlerEnd ) { // If [handlerStart,handlerEnd[ is included in [rangeStart,rangeEnd[, remove firstHandler. return firstHandler . nextHandler ; } else { // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [rangeEnd,handlerEnd[ return new Handler ( firstHandler , end , firstHandler . endPc ) ; } } else if ( rangeEnd >= handlerEnd ) { // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [handlerStart,rangeStart[ return new Handler ( firstHandler , firstHandler . startPc , start ) ; } else { // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = //     [handlerStart,rangeStart[ + [rangeEnd,handerEnd[ firstHandler . nextHandler = new Handler ( firstHandler , end , firstHandler . endPc ) ; return new Handler ( firstHandler , firstHandler . startPc , start ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of elements of the Handler list that begins with the given element . [CODESPLIT] static int getExceptionTableLength ( final Handler firstHandler ) { int length = 0 ; Handler handler = firstHandler ; while ( handler != null ) { length ++ ; handler = handler . nextHandler ; } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the JVMS exception_table corresponding to the Handler list that begins with the given element . <i > This includes the exception_table_length field . < / i > [CODESPLIT] static void putExceptionTable ( final Handler firstHandler , final ByteVector output ) { output . putShort ( getExceptionTableLength ( firstHandler ) ) ; Handler handler = firstHandler ; while ( handler != null ) { output . putShort ( handler . startPc . bytecodeOffset ) . putShort ( handler . endPc . bytecodeOffset ) . putShort ( handler . handlerPc . bytecodeOffset ) . putShort ( handler . catchType ) ; handler = handler . nextHandler ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all interceptors . [CODESPLIT] protected void collectActionInterceptors ( ) { final Collection < ? extends ActionInterceptor > interceptorValues = interceptorsManager . getAllInterceptors ( ) ; interceptors = new ArrayList <> ( ) ; interceptors . addAll ( interceptorValues ) ; interceptors . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all filters . [CODESPLIT] protected void collectActionFilters ( ) { final Collection < ? extends ActionFilter > filterValues = filtersManager . getAllFilters ( ) ; filters = new ArrayList <> ( ) ; filters . addAll ( filterValues ) ; filters . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all action results . [CODESPLIT] protected void collectActionResults ( ) { final Collection < ActionResult > resultsValues = resultsManager . getAllActionResults ( ) ; results = new ArrayList <> ( ) ; results . addAll ( resultsValues ) ; results . sort ( Comparator . comparing ( a -> a . getClass ( ) . getSimpleName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all action runtime configurations . [CODESPLIT] protected void collectActionRuntimes ( ) { actions = actionsManager . getAllActionRuntimes ( ) ; actions . sort ( Comparator . comparing ( ActionRuntime :: getActionPath ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves nested property name to the very last indexed property . If forced <code > null< / code > or non - existing properties will be created . [CODESPLIT] protected void resolveNestedProperties ( final BeanProperty bp ) { String name = bp . name ; int dotNdx ; while ( ( dotNdx = indexOfDot ( name ) ) != - 1 ) { bp . last = false ; bp . setName ( name . substring ( 0 , dotNdx ) ) ; bp . updateBean ( getIndexProperty ( bp ) ) ; name = name . substring ( dotNdx + 1 ) ; } bp . last = true ; bp . setName ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- simple property [CODESPLIT] @ Override public boolean hasSimpleProperty ( final Object bean , final String property ) { return hasSimpleProperty ( new BeanProperty ( this , bean , property ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a value of simple property . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) protected void setSimpleProperty ( final BeanProperty bp , final Object value ) { Setter setter = bp . getSetter ( isDeclared ) ; // try: setter if ( setter != null ) { invokeSetter ( setter , bp , value ) ; return ; } // try: put(\"property\", value) if ( bp . isMap ( ) ) { ( ( Map ) bp . bean ) . put ( bp . name , value ) ; return ; } if ( isSilent ) { return ; } throw new BeanException ( \"Simple property not found: \" + bp . name , bp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- indexed property [CODESPLIT] protected boolean hasIndexProperty ( final BeanProperty bp ) { if ( bp . bean == null ) { return false ; } String indexString = extractIndex ( bp ) ; if ( indexString == null ) { return hasSimpleProperty ( bp ) ; } Object resultBean = getSimpleProperty ( bp ) ; if ( resultBean == null ) { return false ; } // try: property[index] if ( resultBean . getClass ( ) . isArray ( ) ) { int index = parseInt ( indexString , bp ) ; return ( index >= 0 ) && ( index < Array . getLength ( resultBean ) ) ; } // try: list.get(index) if ( resultBean instanceof List ) { int index = parseInt ( indexString , bp ) ; return ( index >= 0 ) && ( index < ( ( List ) resultBean ) . size ( ) ) ; } if ( resultBean instanceof Map ) { return ( ( Map ) resultBean ) . containsKey ( indexString ) ; } // failed return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get non - nested property value : either simple or indexed property . If forced missing bean will be created if possible . [CODESPLIT] protected Object getIndexProperty ( final BeanProperty bp ) { bp . indexString = extractIndex ( bp ) ; Object value = _getIndexProperty ( bp ) ; bp . indexString = null ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets indexed or regular properties ( no nested! ) . [CODESPLIT] protected void setIndexProperty ( final BeanProperty bp , final Object value ) { bp . indexString = extractIndex ( bp ) ; _setIndexProperty ( bp , value ) ; bp . indexString = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- SET [CODESPLIT] @ Override public void setProperty ( final Object bean , final String name , final Object value ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! isSilent ) { resolveNestedProperties ( beanProperty ) ; setIndexProperty ( beanProperty , value ) ; } else { try { resolveNestedProperties ( beanProperty ) ; setIndexProperty ( beanProperty , value ) ; } catch ( Exception ignore ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns value of bean s property . [CODESPLIT] @ Override public < T > T getProperty ( final Object bean , final String name ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! isSilent ) { resolveNestedProperties ( beanProperty ) ; return ( T ) getIndexProperty ( beanProperty ) ; } else { try { resolveNestedProperties ( beanProperty ) ; return ( T ) getIndexProperty ( beanProperty ) ; } catch ( Exception ignore ) { return null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- HAS [CODESPLIT] @ Override public boolean hasProperty ( final Object bean , final String name ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! resolveExistingNestedProperties ( beanProperty ) ) { return false ; } return hasIndexProperty ( beanProperty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- type [CODESPLIT] @ Override public Class < ? > getPropertyType ( final Object bean , final String name ) { BeanProperty beanProperty = new BeanProperty ( this , bean , name ) ; if ( ! resolveExistingNestedProperties ( beanProperty ) ) { return null ; } hasIndexProperty ( beanProperty ) ; return extractType ( beanProperty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the first name of this reference . [CODESPLIT] @ Override public String extractThisReference ( final String propertyName ) { int ndx = StringUtil . indexOfChars ( propertyName , INDEX_CHARS ) ; if ( ndx == - 1 ) { return propertyName ; } return propertyName . substring ( 0 , ndx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns buffered writer . Buffer will be created if not already used . [CODESPLIT] @ Override public PrintWriter getWriter ( ) { if ( writer == null ) { writer = new FastCharArrayWriter ( ) ; printWriter = new PrintWriter ( writer ) ; } return printWriter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the builder so it can be used again . Not everything is reset : object references and column alias type is not . [CODESPLIT] protected void resetSoft ( ) { columnCount = 0 ; paramCount = 0 ; hintCount = 0 ; if ( tableRefs != null ) { tableRefs . clear ( ) ; } //\t\tobjectRefs = null; if ( columnData != null ) { columnData . clear ( ) ; } if ( parameters != null ) { parameters . clear ( ) ; } if ( hints != null ) { hints . clear ( ) ; } //columnAliasType = defaultColumnAliasType; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves object reference . [CODESPLIT] public void setObjectReference ( final String name , final Object object ) { if ( objectRefs == null ) { objectRefs = new HashMap <> ( ) ; } objectRefs . put ( name , object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns object reference . [CODESPLIT] public Object getObjectReference ( final String name ) { if ( objectRefs == null ) { return null ; } return objectRefs . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for object reference and throws an exception if reference doesn t exist . [CODESPLIT] public Object lookupObject ( final String ref ) { Object value = getObjectReference ( ref ) ; if ( value == null ) { throw new DbSqlBuilderException ( \"Invalid object reference: \" + ref ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns entity descriptor for provided table reference . [CODESPLIT] public DbEntityDescriptor getTableDescriptor ( final String tableRef ) { if ( tableRefs == null ) { return null ; } TableRefData t = tableRefs . get ( tableRef ) ; return t == null ? null : t . desc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds entity descriptor of a table that contains provided column reference . [CODESPLIT] public DbEntityDescriptor findTableDescriptorByColumnRef ( final String columnRef ) { for ( Map . Entry < String , TableRefData > entry : tableRefs . entrySet ( ) ) { DbEntityDescriptor ded = entry . getValue ( ) . desc ; if ( ded . findByPropertyName ( columnRef ) != null ) { return ded ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns table alias for provided table reference . [CODESPLIT] public String getTableAlias ( final String tableRef ) { if ( tableRefs == null ) { return null ; } TableRefData t = tableRefs . get ( tableRef ) ; return t == null ? null : t . alias ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers table reference for provided entity . [CODESPLIT] public void registerTableReference ( final String tableReference , final DbEntityDescriptor ded , final String tableAlias ) { if ( tableRefs == null ) { tableRefs = new HashMap <> ( ) ; } TableRefData t = new TableRefData ( ded , tableAlias ) ; if ( tableRefs . put ( tableReference , t ) != null ) { throw new DbSqlBuilderException ( \"Duplicated table reference: \" + tableReference ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds query parameter . [CODESPLIT] public void addParameter ( final String name , final Object value , final DbEntityColumnDescriptor dec ) { if ( parameters == null ) { parameters = new HashMap <> ( ) ; } parameters . put ( name , new ParameterValue ( value , dec ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for entity name and throws exception if entity name not found . [CODESPLIT] protected DbEntityDescriptor lookupName ( final String entityName ) { DbEntityDescriptor ded = entityManager . lookupName ( entityName ) ; if ( ded == null ) { throw new DbSqlBuilderException ( \"Entity name not registered: \" + entityName ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for table reference and throws an exception if table reference not found . [CODESPLIT] protected DbEntityDescriptor lookupTableRef ( final String tableRef ) { DbEntityDescriptor ded = getTableDescriptor ( tableRef ) ; if ( ded == null ) { throw new DbSqlBuilderException ( \"Table reference not used in this query: \" + tableRef ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines parameter with name and its value . [CODESPLIT] protected void defineParameter ( final StringBuilder query , String name , final Object value ) { if ( name == null ) { name = getNextParameterName ( ) ; } query . append ( ' ' ) . append ( name ) ; addParameter ( name , value , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a hint . [CODESPLIT] public void registerHint ( final String hint ) { if ( hints == null ) { hints = new ArrayList <> ( hintCount ) ; } hints . add ( hint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects circular dependencies and pushes value as current type context . [CODESPLIT] @ Override public final boolean serialize ( final JsonContext jsonContext , final T value ) { if ( jsonContext . pushValue ( value ) ) { // prevent circular dependencies return false ; } serializeValue ( jsonContext , value ) ; jsonContext . popValue ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- inject [CODESPLIT] @ Override public void inject ( final ActionRequest actionRequest , final Targets targets ) { final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; instancesInjector . inject ( actionRequest , targets ) ; if ( injectAttributes ) { injectAttributes ( servletRequest , targets ) ; } if ( injectParameters ) { injectParameters ( servletRequest , targets ) ; injectUploadedFiles ( servletRequest , targets ) ; } actionPathMacroInjector . inject ( actionRequest , targets ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects request attributes . [CODESPLIT] protected void injectAttributes ( final HttpServletRequest servletRequest , final Targets targets ) { final Enumeration < String > attributeNames = servletRequest . getAttributeNames ( ) ; while ( attributeNames . hasMoreElements ( ) ) { final String attrName = attributeNames . nextElement ( ) ; targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( attrName ) ; if ( name != null ) { final Object attrValue = servletRequest . getAttribute ( attrName ) ; target . writeValue ( name , attrValue , true ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject request parameters . [CODESPLIT] protected void injectParameters ( final HttpServletRequest servletRequest , final Targets targets ) { final boolean encode = encodeGetParams && servletRequest . getMethod ( ) . equals ( \"GET\" ) ; final Enumeration < String > paramNames = servletRequest . getParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { final String paramName = paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( paramName ) ; if ( name != null ) { String [ ] paramValues = servletRequest . getParameterValues ( paramName ) ; paramValues = ServletUtil . prepareParameters ( paramValues , treatEmptyParamsAsNull , ignoreEmptyRequestParams ) ; if ( paramValues != null ) { if ( encode ) { for ( int j = 0 ; j < paramValues . length ; j ++ ) { final String p = paramValues [ j ] ; if ( p != null ) { final String encoding = madvocEncoding . getEncoding ( ) ; paramValues [ j ] = StringUtil . convertCharset ( p , StringPool . ISO_8859_1 , encoding ) ; } } } final Object value = ( paramValues . length != 1 ? paramValues : paramValues [ 0 ] ) ; target . writeValue ( name , value , true ) ; } } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject uploaded files from multipart request parameters . [CODESPLIT] protected void injectUploadedFiles ( final HttpServletRequest servletRequest , final Targets targets ) { if ( ! ( servletRequest instanceof MultipartRequestWrapper ) ) { return ; } final MultipartRequestWrapper multipartRequest = ( MultipartRequestWrapper ) servletRequest ; if ( ! multipartRequest . isMultipart ( ) ) { return ; } final Enumeration < String > paramNames = multipartRequest . getFileParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { final String paramName = paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } targets . forEachTargetAndIn ( this , ( target , in ) -> { final String name = in . matchedName ( paramName ) ; if ( name != null ) { final FileUpload [ ] paramValues = multipartRequest . getFiles ( paramName ) ; if ( ignoreInvalidUploadFiles ) { for ( int j = 0 ; j < paramValues . length ; j ++ ) { final FileUpload paramValue = paramValues [ j ] ; if ( ( ! paramValue . isValid ( ) ) || ( ! paramValue . isUploaded ( ) ) ) { paramValues [ j ] = null ; } } } final Object value = ( paramValues . length == 1 ? paramValues [ 0 ] : paramValues ) ; target . writeValue ( name , value , true ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- outject [CODESPLIT] @ Override public void outject ( final ActionRequest actionRequest , final Targets targets ) { final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; targets . forEachTargetAndOut ( this , ( target , out ) -> { final Object value = target . readValue ( out ) ; servletRequest . setAttribute ( out . name ( ) , value ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts property name to column name . [CODESPLIT] public String convertPropertyNameToColumnName ( final String propertyName ) { StringBuilder tableName = new StringBuilder ( propertyName . length ( ) * 2 ) ; if ( splitCamelCase ) { String convertedTableName = Format . fromCamelCase ( propertyName , separatorChar ) ; tableName . append ( convertedTableName ) ; } else { tableName . append ( propertyName ) ; } if ( ! changeCase ) { return tableName . toString ( ) ; } return uppercase ? toUppercase ( tableName ) . toString ( ) : toLowercase ( tableName ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts column name to property name . [CODESPLIT] public String convertColumnNameToPropertyName ( final String columnName ) { StringBuilder propertyName = new StringBuilder ( columnName . length ( ) ) ; int len = columnName . length ( ) ; if ( splitCamelCase ) { boolean toUpper = false ; for ( int i = 0 ; i < len ; i ++ ) { char c = columnName . charAt ( i ) ; if ( c == separatorChar ) { toUpper = true ; continue ; } if ( toUpper ) { propertyName . append ( Character . toUpperCase ( c ) ) ; toUpper = false ; } else { propertyName . append ( Character . toLowerCase ( c ) ) ; } } return propertyName . toString ( ) ; } return columnName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies column naming strategy to given column name hint . Returns full column name . [CODESPLIT] public String applyToColumnName ( final String columnName ) { String propertyName = convertColumnNameToPropertyName ( columnName ) ; return convertPropertyNameToColumnName ( propertyName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected boolean [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final boolean [ ] target = new boolean [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Boolean > booleanArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final boolean convertedValue = convertType ( element ) ; booleanArrayList . add ( Boolean . valueOf ( convertedValue ) ) ; } final boolean [ ] array = new boolean [ booleanArrayList . size ( ) ] ; for ( int i = 0 ; i < booleanArrayList . size ( ) ; i ++ ) { final Boolean b = booleanArrayList . get ( i ) ; array [ i ] = b . booleanValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores value in database . Value is casted to sql type . [CODESPLIT] public void storeValue ( final PreparedStatement st , final int index , final Object value , final int dbSqlType ) throws SQLException { T t = TypeConverterManager . get ( ) . convertType ( value , sqlType ) ; set ( st , index , t , dbSqlType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Once when value is read from result set prepare it to match destination type . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) protected < E > E prepareGetValue ( final T t , final Class < E > destinationType ) { if ( t == null ) { return null ; } if ( destinationType == null ) { return ( E ) t ; } return TypeConverterManager . get ( ) . convertType ( t , destinationType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all action wrappers . Returns a copy in new set . [CODESPLIT] protected Set < T > getAll ( ) { final Set < T > set = new HashSet <> ( wrappers . size ( ) ) ; set . addAll ( wrappers . values ( ) ) ; return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves single wrapper . Creates new wrapper instance if not already registered . Does not expand the wrappers . [CODESPLIT] public T resolve ( final Class < ? extends T > wrapperClass ) { String wrapperClassName = wrapperClass . getName ( ) ; T wrapper = lookup ( wrapperClassName ) ; if ( wrapper == null ) { wrapper = createWrapper ( wrapperClass ) ; initializeWrapper ( wrapper ) ; wrappers . put ( wrapperClassName , wrapper ) ; } return wrapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves wrappers . Unregistered wrappers will be registered . Returned array may be different size than size of provided array due to { [CODESPLIT] public T [ ] resolveAll ( Class < ? extends T > [ ] wrapperClasses ) { if ( wrapperClasses == null ) { return null ; } wrapperClasses = expand ( wrapperClasses ) ; T [ ] result = createArray ( wrapperClasses . length ) ; for ( int i = 0 ; i < wrapperClasses . length ; i ++ ) { result [ i ] = resolve ( wrapperClasses [ i ] ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces all { [CODESPLIT] protected Class < ? extends T > [ ] expand ( final Class < ? extends T > [ ] actionWrappers ) { if ( actionWrappers == null ) { return null ; } List < Class < ? extends T > > list = new ArrayList <> ( actionWrappers . length ) ; list . addAll ( Arrays . asList ( actionWrappers ) ) ; int i = 0 ; while ( i < list . size ( ) ) { Class < ? extends T > wrapperClass = list . get ( i ) ; if ( wrapperClass == null ) { continue ; } if ( ClassUtil . isTypeOf ( wrapperClass , BaseActionWrapperStack . class ) ) { BaseActionWrapperStack stack = ( BaseActionWrapperStack ) resolve ( wrapperClass ) ; list . remove ( i ) ; Class < ? extends T > [ ] stackWrappers = stack . getWrappers ( ) ; if ( stackWrappers != null ) { list . addAll ( i , Arrays . asList ( stackWrappers ) ) ; } i -- ; //continue; } i ++ ; } return list . toArray ( new Class [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new wrapper . [CODESPLIT] protected < R extends T > R createWrapper ( final Class < R > wrapperClass ) { try { return ClassUtil . newInstance ( wrapperClass ) ; } catch ( Exception ex ) { throw new MadvocException ( \"Invalid Madvoc wrapper: \" + wrapperClass , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates a filename to a base path using normal command line style rules . <p > The effect is equivalent to resultant directory after changing directory to the first argument followed by changing directory to the second argument . <p > The first argument is the base path the second is the path to concatenate . The returned path is always normalized via { @link #normalize ( String ) } thus <code > .. < / code > is handled . <p > If <code > pathToAdd< / code > is absolute ( has an absolute prefix ) then it will be normalized and returned . Otherwise the paths will be joined normalized and returned . <p > The output will be the same on both Unix and Windows except for the separator character . <pre > { @code / foo / + bar -- > / foo / bar / foo + bar -- > / foo / bar / foo + / bar -- > / bar / foo + C : / bar -- > C : / bar / foo + C : bar -- > C : bar ( * ) / foo / a / + .. / bar -- > foo / bar / foo / + .. / .. / bar -- > null / foo / + / bar -- > / bar / foo / .. + / bar -- > / bar / foo + bar / c . txt -- > / foo / bar / c . txt / foo / c . txt + bar -- > / foo / c . txt / bar ( ! ) } < / pre > ( * ) Note that the Windows relative drive prefix is unreliable when used with this method . ( ! ) Note that the first parameter must be a path . If it ends with a name then the name will be built into the concatenated path . If this might be a problem use { @link #getFullPath ( String ) } on the base path argument . [CODESPLIT] public static String concat ( final String basePath , final String fullFilenameToAdd ) { return doConcat ( basePath , fullFilenameToAdd , SYSTEM_SEPARATOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts all separators to the system separator . [CODESPLIT] public static String separatorsToSystem ( final String path ) { if ( path == null ) { return null ; } if ( SYSTEM_SEPARATOR == WINDOWS_SEPARATOR ) { return separatorsToWindows ( path ) ; } else { return separatorsToUnix ( path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the index of the last directory separator character . <p > This method will handle a file in either Unix or Windows format . The position of the last forward or backslash is returned . <p > The output will be the same irrespective of the machine that the code is running on . [CODESPLIT] public static int indexOfLastSeparator ( final String filename ) { if ( filename == null ) { return - 1 ; } int lastUnixPos = filename . lastIndexOf ( UNIX_SEPARATOR ) ; int lastWindowsPos = filename . lastIndexOf ( WINDOWS_SEPARATOR ) ; return Math . max ( lastUnixPos , lastWindowsPos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the work of getting the path . [CODESPLIT] private static String doGetPath ( final String filename , final int separatorAdd ) { if ( filename == null ) { return null ; } int prefix = getPrefixLength ( filename ) ; if ( prefix < 0 ) { return null ; } int index = indexOfLastSeparator ( filename ) ; int endIndex = index + separatorAdd ; if ( prefix >= filename . length ( ) || index < 0 || prefix >= endIndex ) { return StringPool . EMPTY ; } return filename . substring ( prefix , endIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits filename into a array of four Strings containing prefix path basename and extension . Path will contain ending separator . [CODESPLIT] public static String [ ] split ( final String filename ) { String prefix = getPrefix ( filename ) ; if ( prefix == null ) { prefix = StringPool . EMPTY ; } int lastSeparatorIndex = indexOfLastSeparator ( filename ) ; int lastExtensionIndex = indexOfExtension ( filename ) ; String path ; String baseName ; String extension ; if ( lastSeparatorIndex == - 1 ) { path = StringPool . EMPTY ; if ( lastExtensionIndex == - 1 ) { baseName = filename . substring ( prefix . length ( ) ) ; extension = StringPool . EMPTY ; } else { baseName = filename . substring ( prefix . length ( ) , lastExtensionIndex ) ; extension = filename . substring ( lastExtensionIndex + 1 ) ; } } else { path = filename . substring ( prefix . length ( ) , lastSeparatorIndex + 1 ) ; if ( lastExtensionIndex == - 1 ) { baseName = filename . substring ( prefix . length ( ) + path . length ( ) ) ; extension = StringPool . EMPTY ; } else { baseName = filename . substring ( prefix . length ( ) + path . length ( ) , lastExtensionIndex ) ; extension = filename . substring ( lastExtensionIndex + 1 ) ; } } return new String [ ] { prefix , path , baseName , extension } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve <code > ~< / code > in the path . [CODESPLIT] public static String resolveHome ( final String path ) { if ( path . length ( ) == 1 ) { if ( path . charAt ( 0 ) == ' ' ) { return SystemUtil . info ( ) . getHomeDir ( ) ; } return path ; } if ( path . length ( ) >= 2 ) { if ( ( path . charAt ( 0 ) == ' ' ) && ( path . charAt ( 1 ) == File . separatorChar ) ) { return SystemUtil . info ( ) . getHomeDir ( ) + path . substring ( 1 ) ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates relative path of target path on base path . [CODESPLIT] public static String relativePath ( final String targetPath , final String basePath ) { return new File ( basePath ) . toPath ( ) . relativize ( new File ( targetPath ) . toPath ( ) ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- visitor [CODESPLIT] @ Override public void visit ( final String name , final Object value ) { elements . put ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers additional Madvoc components after the registration of default components . [CODESPLIT] public WebApp registerComponent ( final Class < ? > madvocComponent ) { Objects . requireNonNull ( madvocComponent ) ; madvocComponents . add ( ClassConsumer . of ( madvocComponent ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers Madvoc component <i > instance< / i > . Use with caution as injection of components registered after this will fail . [CODESPLIT] public WebApp registerComponent ( final Object madvocComponent ) { Objects . requireNonNull ( madvocComponent ) ; madvocComponentInstances . add ( madvocComponent ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures the action configurations . [CODESPLIT] public < A extends ActionConfig > WebApp withActionConfig ( final Class < A > actionConfigType , final Consumer < A > actionConfigConsumer ) { withRegisteredComponent ( ActionConfigManager . class , acm -> acm . with ( actionConfigType , actionConfigConsumer ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures a component . While the signature is the same as for { [CODESPLIT] public < T > WebApp withRegisteredComponent ( final Class < T > madvocComponent , final Consumer < T > componentConsumer ) { if ( componentConfigs == null ) { // component is already configured final T component = madvocContainer . lookupComponent ( madvocComponent ) ; if ( component == null ) { throw new MadvocException ( \"Component not found: \" + madvocComponent . getName ( ) ) ; } componentConsumer . accept ( component ) ; } else { componentConfigs . add ( madvocContainer -> { final T component = madvocContainer . lookupComponent ( madvocComponent ) ; if ( component == null ) { throw new MadvocException ( \"Component not found: \" + madvocComponent . getName ( ) ) ; } componentConsumer . accept ( component ) ; } ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes and starts web application . [CODESPLIT] public WebApp start ( ) { log = LoggerFactory . getLogger ( WebApp . class ) ; log . debug ( \"Initializing Madvoc WebApp\" ) ; //// params & props for ( final Map < String , Object > params : paramsList ) { madvocContainer . defineParams ( params ) ; } for ( final Props props : propsList ) { madvocContainer . defineParams ( props ) ; } propsList = null ; //// components registerMadvocComponents ( ) ; madvocComponents . forEach ( madvocComponent -> madvocContainer . registerComponent ( madvocComponent . type ( ) , madvocComponent . consumer ( ) ) ) ; madvocComponents = null ; madvocComponentInstances . forEach ( madvocContainer :: registerComponentInstance ) ; madvocComponentInstances = null ; configureDefaults ( ) ; //// listeners madvocContainer . fireEvent ( Init . class ) ; //// component configuration componentConfigs . accept ( madvocContainer ) ; componentConfigs = null ; initialized ( ) ; madvocContainer . fireEvent ( Start . class ) ; if ( ! madvocRouterConsumers . isEmpty ( ) ) { final MadvocRouter madvocRouter = MadvocRouter . create ( ) ; madvocContainer . registerComponentInstance ( madvocRouter ) ; madvocRouterConsumers . accept ( madvocRouter ) ; } madvocRouterConsumers = null ; started ( ) ; madvocContainer . fireEvent ( Ready . class ) ; ready ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure defaults . [CODESPLIT] protected void configureDefaults ( ) { final ActionConfigManager actionConfigManager = madvocContainer . lookupComponent ( ActionConfigManager . class ) ; actionConfigManager . registerAnnotation ( Action . class ) ; actionConfigManager . registerAnnotation ( RestAction . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers default Madvoc components . [CODESPLIT] protected void registerMadvocComponents ( ) { if ( madvocContainer == null ) { throw new MadvocException ( \"Madvoc WebApp not initialized.\" ) ; } log . debug ( \"Registering Madvoc WebApp components\" ) ; madvocContainer . registerComponent ( MadvocEncoding . class ) ; madvocContainer . registerComponentInstance ( new ServletContextProvider ( servletContext ) ) ; madvocContainer . registerComponent ( ActionConfigManager . class ) ; madvocContainer . registerComponent ( ActionMethodParamNameResolver . class ) ; madvocContainer . registerComponent ( ActionMethodParser . class ) ; madvocContainer . registerComponent ( ActionPathRewriter . class ) ; madvocContainer . registerComponent ( ActionsManager . class ) ; madvocContainer . registerComponent ( ContextInjectorComponent . class ) ; madvocContainer . registerComponent ( InterceptorsManager . class ) ; madvocContainer . registerComponent ( FiltersManager . class ) ; madvocContainer . registerComponent ( MadvocController . class ) ; madvocContainer . registerComponent ( RootPackages . class ) ; madvocContainer . registerComponent ( ResultsManager . class ) ; madvocContainer . registerComponent ( ResultMapper . class ) ; madvocContainer . registerComponent ( ScopeResolver . class ) ; madvocContainer . registerComponent ( ScopeDataInspector . class ) ; madvocContainer . registerComponent ( AsyncActionExecutor . class ) ; madvocContainer . registerComponent ( FileUploader . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify excluded jars . [CODESPLIT] public ClassScanner excludeJars ( final String ... excludedJars ) { for ( final String excludedJar : excludedJars ) { rulesJars . exclude ( excludedJar ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify included jars . [CODESPLIT] public ClassScanner includeJars ( final String ... includedJars ) { for ( final String includedJar : includedJars ) { rulesJars . include ( includedJar ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets included set of names that will be considered during configuration . [CODESPLIT] public ClassScanner includeEntries ( final String ... includedEntries ) { for ( final String includedEntry : includedEntries ) { rulesEntries . include ( includedEntry ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets excluded names that narrows included set of packages . [CODESPLIT] public ClassScanner excludeEntries ( final String ... excludedEntries ) { for ( final String excludedEntry : excludedEntries ) { rulesEntries . exclude ( excludedEntry ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if some JAR file has to be accepted . [CODESPLIT] protected boolean acceptJar ( final File jarFile ) { String path = jarFile . getAbsolutePath ( ) ; path = FileNameUtil . separatorsToUnix ( path ) ; return rulesJars . match ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans classes inside single JAR archive . Archive is scanned as a zip file . [CODESPLIT] protected void scanJarFile ( final File file ) { final ZipFile zipFile ; try { zipFile = new ZipFile ( file ) ; } catch ( IOException ioex ) { if ( ! ignoreException ) { throw new FindFileException ( \"Invalid zip: \" + file . getName ( ) , ioex ) ; } return ; } final Enumeration entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { final ZipEntry zipEntry = ( ZipEntry ) entries . nextElement ( ) ; final String zipEntryName = zipEntry . getName ( ) ; try { if ( StringUtil . endsWithIgnoreCase ( zipEntryName , CLASS_FILE_EXT ) ) { final String entryName = prepareEntryName ( zipEntryName , true ) ; final ClassPathEntry classPathEntry = new ClassPathEntry ( entryName , zipFile , zipEntry ) ; try { scanEntry ( classPathEntry ) ; } finally { classPathEntry . closeInputStream ( ) ; } } else if ( includeResources ) { final String entryName = prepareEntryName ( zipEntryName , false ) ; final ClassPathEntry classPathEntry = new ClassPathEntry ( entryName , zipFile , zipEntry ) ; try { scanEntry ( classPathEntry ) ; } finally { classPathEntry . closeInputStream ( ) ; } } } catch ( RuntimeException rex ) { if ( ! ignoreException ) { ZipUtil . close ( zipFile ) ; throw rex ; } } } ZipUtil . close ( zipFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans single classpath directory . [CODESPLIT] protected void scanClassPath ( final File root ) { String rootPath = root . getAbsolutePath ( ) ; if ( ! rootPath . endsWith ( File . separator ) ) { rootPath += File . separatorChar ; } final FindFile ff = FindFile . create ( ) . includeDirs ( false ) . recursive ( true ) . searchPath ( rootPath ) ; File file ; while ( ( file = ff . nextFile ( ) ) != null ) { final String filePath = file . getAbsolutePath ( ) ; try { if ( StringUtil . endsWithIgnoreCase ( filePath , CLASS_FILE_EXT ) ) { scanClassFile ( filePath , rootPath , file , true ) ; } else if ( includeResources ) { scanClassFile ( filePath , rootPath , file , false ) ; } } catch ( RuntimeException rex ) { if ( ! ignoreException ) { throw rex ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares resource and class names . For classes it strips . class from the end and converts all ( back ) slashes to dots . For resources it replaces all backslashes to slashes . [CODESPLIT] protected String prepareEntryName ( final String name , final boolean isClass ) { String entryName = name ; if ( isClass ) { entryName = name . substring ( 0 , name . length ( ) - 6 ) ; // 6 == \".class\".length() entryName = StringUtil . replaceChar ( entryName , ' ' , ' ' ) ; entryName = StringUtil . replaceChar ( entryName , ' ' , ' ' ) ; } else { entryName = ' ' + StringUtil . replaceChar ( entryName , ' ' , ' ' ) ; } return entryName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If entry name is { [CODESPLIT] protected void scanEntry ( final ClassPathEntry classPathEntry ) { if ( ! acceptEntry ( classPathEntry . name ( ) ) ) { return ; } try { onEntry ( classPathEntry ) ; } catch ( Exception ex ) { throw new FindFileException ( \"Scan entry error: \" + classPathEntry , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns type signature bytes used for searching in class file . [CODESPLIT] public static byte [ ] bytecodeSignatureOfType ( final Class type ) { final String name = ' ' + type . getName ( ) . replace ( ' ' , ' ' ) + ' ' ; return name . getBytes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans URLs . If ( #ignoreExceptions } is set exceptions per one URL will be ignored and loops continues . [CODESPLIT] public ClassScanner scan ( final URL ... urls ) { for ( final URL url : urls ) { final File file = FileUtil . toContainerFile ( url ) ; if ( file == null ) { if ( ! ignoreException ) { throw new FindFileException ( \"URL is not a valid file: \" + url ) ; } } else { filesToScan . add ( file ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans provided paths . [CODESPLIT] public ClassScanner scan ( final String ... paths ) { for ( final String path : paths ) { filesToScan . add ( new File ( path ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts with the scanner . [CODESPLIT] public void start ( ) { if ( detectEntriesMode ) { rulesEntries . detectMode ( ) ; } filesToScan . forEach ( file -> { final String path = file . getAbsolutePath ( ) ; if ( StringUtil . endsWithIgnoreCase ( path , JAR_FILE_EXT ) ) { if ( ! acceptJar ( file ) ) { return ; } scanJarFile ( file ) ; } else if ( file . isDirectory ( ) ) { scanClassPath ( file ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns String characters in most performing way . If possible the inner <code > char [] < / code > will be returned . If not <code > toCharArray () < / code > will be called . Returns <code > null< / code > when argument is <code > null< / code > . [CODESPLIT] public static char [ ] getChars ( final String string ) { if ( string == null ) { return null ; } if ( ! HAS_UNSAFE || ! JoddCore . unsafeUsageEnabled ) { return string . toCharArray ( ) ; } return UnsafeInternal . unsafeGetChars ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public DbJtxTransaction requestTransaction ( final JtxTransactionMode mode , final Object scope ) { return ( DbJtxTransaction ) super . requestTransaction ( mode , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds new transaction instance . [CODESPLIT] @ Override protected JtxTransaction createNewTransaction ( final JtxTransactionMode tm , final Object scope , final boolean active ) { return new DbJtxTransaction ( this , tm , scope , active ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups the scope instance of given scope annotation . If instance does not exist it will be created cached and returned . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < S extends MadvocScope > S defaultOrScopeType ( final Class < S > scopeClass ) { if ( scopeClass == null ) { return ( S ) getOrInitScope ( RequestScope . class ) ; } return ( S ) getOrInitScope ( scopeClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs search for the scope class and returns it s instance . [CODESPLIT] protected MadvocScope getOrInitScope ( final Class < ? extends MadvocScope > madvocScopeType ) { for ( final MadvocScope s : allScopes ) { if ( s . getClass ( ) . equals ( madvocScopeType ) ) { return s ; } } // new scope detected final MadvocScope newScope ; try { newScope = madpc . createBean ( madvocScopeType ) ; } catch ( Exception ex ) { throw new MadvocException ( \"Unable to create scope: \" + madvocScopeType , ex ) ; } allScopes . add ( newScope ) ; return newScope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a given scope and consumes it . [CODESPLIT] public void forScope ( final Class < ? extends MadvocScope > scopeType , final Consumer < MadvocScope > madvocScopeConsumer ) { final MadvocScope scope = getOrInitScope ( scopeType ) ; madvocScopeConsumer . accept ( scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses { @link Message } and extracts all data for the received message . [CODESPLIT] protected void parseMessage ( final Message msg , final boolean envelope ) throws MessagingException , IOException { // flags flags ( msg . getFlags ( ) ) ; // message number messageNumber ( msg . getMessageNumber ( ) ) ; if ( msg instanceof MimeMessage ) { messageId ( ( ( MimeMessage ) msg ) . getMessageID ( ) ) ; } // single from final Address [ ] addresses = msg . getFrom ( ) ; if ( addresses != null && addresses . length > 0 ) { from ( addresses [ 0 ] ) ; } // reply-to replyTo ( msg . getReplyTo ( ) ) ; // recipients to ( msg . getRecipients ( Message . RecipientType . TO ) ) ; cc ( msg . getRecipients ( Message . RecipientType . CC ) ) ; // no BCC because this will always be empty // subject subject ( msg . getSubject ( ) ) ; // dates receivedDate ( msg . getReceivedDate ( ) ) ; sentDate ( msg . getSentDate ( ) ) ; // headers headers ( msg . getAllHeaders ( ) ) ; // content if ( ! envelope ) { processPart ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process part of the received message . All parts are simply added to the { @link ReceivedEmail } i . e . hierarchy is not saved . [CODESPLIT] protected void processPart ( final Part part ) throws MessagingException , IOException { final Object content = part . getContent ( ) ; if ( content instanceof String ) { addStringContent ( part , ( String ) content ) ; } else if ( content instanceof Multipart ) { processMultipart ( ( Multipart ) content ) ; } else if ( content instanceof InputStream ) { addAttachment ( part , ( InputStream ) content , attachmentStorage ) ; } else if ( content instanceof MimeMessage ) { final MimeMessage mimeMessage = ( MimeMessage ) content ; attachedMessage ( new ReceivedEmail ( mimeMessage , false , attachmentStorage ) ) ; } else { addAttachment ( part , part . getInputStream ( ) , attachmentStorage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the { @link Multipart } . [CODESPLIT] private void processMultipart ( final Multipart mp ) throws MessagingException , IOException { final int count = mp . getCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { final Part innerPart = mp . getBodyPart ( i ) ; processPart ( innerPart ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds String content as either { @link EmailAttachment } or as { @link EmailMessage } . [CODESPLIT] private void addStringContent ( final Part part , final String content ) throws MessagingException , UnsupportedEncodingException { final String contentType = part . getContentType ( ) ; final String encoding = EmailUtil . extractEncoding ( contentType , StringPool . US_ASCII ) ; final String disposition = part . getDisposition ( ) ; if ( disposition != null && disposition . equalsIgnoreCase ( Part . ATTACHMENT ) ) { addAttachment ( part , content . getBytes ( encoding ) ) ; } else { final String mimeType = EmailUtil . extractMimeType ( contentType ) ; message ( content , mimeType , encoding ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Content - ID of this { @link Part } . Returns { @code null } if none present . [CODESPLIT] protected static String parseContentId ( final Part part ) throws MessagingException { if ( part instanceof MimePart ) { final MimePart mp = ( MimePart ) part ; return mp . getContentID ( ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if the { @link Part } is inline . [CODESPLIT] protected static boolean parseInline ( final Part part ) throws MessagingException { if ( part instanceof MimePart ) { final String dispositionId = part . getDisposition ( ) ; return dispositionId != null && dispositionId . equalsIgnoreCase ( \"inline\" ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds received attachment . [CODESPLIT] private ReceivedEmail addAttachment ( final Part part , final InputStream content , final File attachmentStorage ) throws MessagingException , IOException { final EmailAttachmentBuilder builder = addAttachmentInfo ( part ) ; builder . content ( content , part . getContentType ( ) ) ; if ( attachmentStorage != null ) { String name = messageId + \"-\" + ( this . attachments ( ) . size ( ) + 1 ) ; return storeAttachment ( builder . buildFileDataSource ( name , attachmentStorage ) ) ; } return storeAttachment ( builder . buildByteArrayDataSource ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds received attachment . [CODESPLIT] private ReceivedEmail addAttachment ( final Part part , final byte [ ] content ) throws MessagingException { final EmailAttachmentBuilder builder = addAttachmentInfo ( part ) ; builder . content ( content , part . getContentType ( ) ) ; final EmailAttachment < ByteArrayDataSource > attachment = builder . buildByteArrayDataSource ( ) ; attachment . setSize ( content . length ) ; return storeAttachment ( attachment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link EmailAttachmentBuilder } from { @link Part } and sets Content ID inline and name . [CODESPLIT] private static EmailAttachmentBuilder addAttachmentInfo ( final Part part ) throws MessagingException { final String fileName = EmailUtil . resolveFileName ( part ) ; final String contentId = parseContentId ( part ) ; final boolean isInline = parseInline ( part ) ; return new EmailAttachmentBuilder ( ) . name ( fileName ) . contentId ( contentId ) . inline ( isInline ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a raw byte array into a BASE64 <code > char [] < / code > . [CODESPLIT] public static char [ ] encodeToChar ( final byte [ ] arr , final boolean lineSeparator ) { int len = arr != null ? arr . length : 0 ; if ( len == 0 ) { return new char [ 0 ] ; } int evenlen = ( len / 3 ) * 3 ; int cnt = ( ( len - 1 ) / 3 + 1 ) << 2 ; int destLen = cnt + ( lineSeparator ? ( cnt - 1 ) / 76 << 1 : 0 ) ; char [ ] dest = new char [ destLen ] ; for ( int s = 0 , d = 0 , cc = 0 ; s < evenlen ; ) { int i = ( arr [ s ++ ] & 0xff ) << 16 | ( arr [ s ++ ] & 0xff ) << 8 | ( arr [ s ++ ] & 0xff ) ; dest [ d ++ ] = CHARS [ ( i >>> 18 ) & 0x3f ] ; dest [ d ++ ] = CHARS [ ( i >>> 12 ) & 0x3f ] ; dest [ d ++ ] = CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ d ++ ] = CHARS [ i & 0x3f ] ; if ( lineSeparator && ( ++ cc == 19 ) && ( d < ( destLen - 2 ) ) ) { dest [ d ++ ] = ' ' ; dest [ d ++ ] = ' ' ; cc = 0 ; } } int left = len - evenlen ; // 0 - 2. if ( left > 0 ) { int i = ( ( arr [ evenlen ] & 0xff ) << 10 ) | ( left == 2 ? ( ( arr [ len - 1 ] & 0xff ) << 2 ) : 0 ) ; dest [ destLen - 4 ] = CHARS [ i >> 12 ] ; dest [ destLen - 3 ] = CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ destLen - 2 ] = left == 2 ? CHARS [ i & 0x3f ] : ' ' ; dest [ destLen - 1 ] = ' ' ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes a BASE64 encoded char array . [CODESPLIT] public static byte [ ] decode ( final char [ ] arr ) { int length = arr . length ; if ( length == 0 ) { return new byte [ 0 ] ; } int sndx = 0 , endx = length - 1 ; int pad = arr [ endx ] == ' ' ? ( arr [ endx - 1 ] == ' ' ? 2 : 1 ) : 0 ; int cnt = endx - sndx + 1 ; int sepCnt = length > 76 ? ( arr [ 76 ] == ' ' ? cnt / 78 : 0 ) << 1 : 0 ; int len = ( ( cnt - sepCnt ) * 6 >> 3 ) - pad ; byte [ ] dest = new byte [ len ] ; int d = 0 ; for ( int cc = 0 , eLen = ( len / 3 ) * 3 ; d < eLen ; ) { int i = INV [ arr [ sndx ++ ] ] << 18 | INV [ arr [ sndx ++ ] ] << 12 | INV [ arr [ sndx ++ ] ] << 6 | INV [ arr [ sndx ++ ] ] ; dest [ d ++ ] = ( byte ) ( i >> 16 ) ; dest [ d ++ ] = ( byte ) ( i >> 8 ) ; dest [ d ++ ] = ( byte ) i ; if ( sepCnt > 0 && ++ cc == 19 ) { sndx += 2 ; cc = 0 ; } } if ( d < len ) { int i = 0 ; for ( int j = 0 ; sndx <= endx - pad ; j ++ ) { i |= INV [ arr [ sndx ++ ] ] << ( 18 - j * 6 ) ; } for ( int r = 16 ; d < len ; r -= 8 ) { dest [ d ++ ] = ( byte ) ( i >> r ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a raw byte array into a BASE64 <code > char [] < / code > . [CODESPLIT] public static byte [ ] encodeToByte ( final byte [ ] arr , final boolean lineSep ) { int len = arr != null ? arr . length : 0 ; if ( len == 0 ) { return new byte [ 0 ] ; } int evenlen = ( len / 3 ) * 3 ; int cnt = ( ( len - 1 ) / 3 + 1 ) << 2 ; int destlen = cnt + ( lineSep ? ( cnt - 1 ) / 76 << 1 : 0 ) ; byte [ ] dest = new byte [ destlen ] ; for ( int s = 0 , d = 0 , cc = 0 ; s < evenlen ; ) { int i = ( arr [ s ++ ] & 0xff ) << 16 | ( arr [ s ++ ] & 0xff ) << 8 | ( arr [ s ++ ] & 0xff ) ; dest [ d ++ ] = ( byte ) CHARS [ ( i >>> 18 ) & 0x3f ] ; dest [ d ++ ] = ( byte ) CHARS [ ( i >>> 12 ) & 0x3f ] ; dest [ d ++ ] = ( byte ) CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ d ++ ] = ( byte ) CHARS [ i & 0x3f ] ; if ( lineSep && ++ cc == 19 && d < destlen - 2 ) { dest [ d ++ ] = ' ' ; dest [ d ++ ] = ' ' ; cc = 0 ; } } int left = len - evenlen ; if ( left > 0 ) { int i = ( ( arr [ evenlen ] & 0xff ) << 10 ) | ( left == 2 ? ( ( arr [ len - 1 ] & 0xff ) << 2 ) : 0 ) ; dest [ destlen - 4 ] = ( byte ) CHARS [ i >> 12 ] ; dest [ destlen - 3 ] = ( byte ) CHARS [ ( i >>> 6 ) & 0x3f ] ; dest [ destlen - 2 ] = left == 2 ? ( byte ) CHARS [ i & 0x3f ] : ( byte ) ' ' ; dest [ destlen - 1 ] = ' ' ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- string [CODESPLIT] public static String encodeToString ( final String s ) { return new String ( encodeToChar ( StringUtil . getBytes ( s ) , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates new CSRF token and puts it in the session . Returns generated token value . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static String prepareCsrfToken ( final HttpSession session , final int timeToLive ) { Set < Token > tokenSet = ( Set < Token > ) session . getAttribute ( CSRF_TOKEN_SET ) ; if ( tokenSet == null ) { tokenSet = new HashSet <> ( ) ; session . setAttribute ( CSRF_TOKEN_SET , tokenSet ) ; } String value ; boolean unique ; do { value = RandomString . get ( ) . randomAlphaNumeric ( 32 ) ; assureSize ( tokenSet ) ; unique = tokenSet . add ( new Token ( value , timeToLive ) ) ; } while ( ! unique ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes expired tokens if token set is full . [CODESPLIT] protected static void assureSize ( final Set < Token > tokenSet ) { if ( tokenSet . size ( ) < maxTokensPerSession ) { return ; } long validUntilMin = Long . MAX_VALUE ; Token tokenToRemove = null ; Iterator < Token > iterator = tokenSet . iterator ( ) ; while ( iterator . hasNext ( ) ) { Token token = iterator . next ( ) ; if ( token . isExpired ( ) ) { iterator . remove ( ) ; continue ; } if ( token . validUntil < validUntilMin ) { validUntilMin = token . validUntil ; tokenToRemove = token ; } } if ( ( tokenToRemove != null ) && ( tokenSet . size ( ) >= maxTokensPerSession ) ) { tokenSet . remove ( tokenToRemove ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static boolean checkCsrfToken ( final HttpServletRequest request , final String tokenName ) { String tokenValue = request . getParameter ( tokenName ) ; return checkCsrfToken ( request . getSession ( ) , tokenValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks token value . C [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static boolean checkCsrfToken ( final HttpSession session , final String tokenValue ) { Set < Token > tokenSet = ( Set < Token > ) session . getAttribute ( CSRF_TOKEN_SET ) ; if ( ( tokenSet == null ) && ( tokenValue == null ) ) { return true ; } if ( ( tokenSet == null ) || ( tokenValue == null ) ) { return false ; } boolean found = false ; Iterator < Token > it = tokenSet . iterator ( ) ; while ( it . hasNext ( ) ) { Token t = it . next ( ) ; if ( t . isExpired ( ) ) { it . remove ( ) ; continue ; } if ( t . getValue ( ) . equals ( tokenValue ) ) { it . remove ( ) ; found = true ; } } return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates <code > BeanCopy< / code > with given <code > Map< / code > as a source . [CODESPLIT] public static BeanCopy fromMap ( final Map source ) { BeanCopy beanCopy = new BeanCopy ( source ) ; beanCopy . isSourceMap = true ; return beanCopy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines source detects a map . [CODESPLIT] public static BeanCopy from ( final Object source ) { BeanCopy beanCopy = new BeanCopy ( source ) ; beanCopy . isSourceMap = source instanceof Map ; return beanCopy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the copying . [CODESPLIT] public void copy ( ) { beanUtil = new BeanUtilBean ( ) . declared ( declared ) . forced ( forced ) . silent ( true ) ; visit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies single property to the destination . Exceptions are ignored so copying continues if destination does not have some of the sources properties . [CODESPLIT] @ Override protected boolean visitProperty ( String name , final Object value ) { if ( isTargetMap ) { name = LEFT_SQ_BRACKET + name + RIGHT_SQ_BRACKET ; } beanUtil . setProperty ( destination , name , value ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses content using Lagarto and { [CODESPLIT] @ Override protected final char [ ] parse ( final char [ ] content , final HttpServletRequest request ) { LagartoParsingProcessor lpp = createParsingProcessor ( ) ; if ( lpp == null ) { return content ; } lpp . init ( content ) ; return lpp . parse ( request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves and registers table references . [CODESPLIT] @ Override public void init ( final TemplateData templateData ) { super . init ( templateData ) ; if ( entity != null ) { ded = lookupType ( entity ) ; } else { Object object = templateData . getObjectReference ( entityName ) ; if ( object != null ) { ded = lookupType ( resolveClass ( object ) ) ; } else { ded = lookupName ( entityName ) ; } } String tableReference = this . tableReference ; if ( tableReference == null ) { tableReference = tableAlias ; } if ( tableReference == null ) { tableReference = entityName ; } if ( tableReference == null ) { tableReference = ded . getEntityName ( ) ; } templateData . registerTableReference ( tableReference , ded , tableAlias ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves and registers scope from a scope type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < S extends Scope > S resolveScope ( final Class < S > scopeType ) { S scope = ( S ) scopes . get ( scopeType ) ; if ( scope == null ) { try { scope = newInternalInstance ( scopeType , ( PetiteContainer ) this ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Invalid Petite scope: \" + scopeType . getName ( ) , ex ) ; } registerScope ( scopeType , scope ) ; scopes . put ( scopeType , scope ) ; } return scope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new instance of given type . In the first try it tries to use constructor with a { [CODESPLIT] private < T > T newInternalInstance ( final Class < T > type , final PetiteContainer petiteContainer ) throws Exception { T t = null ; // first try ctor(PetiteContainer) try { Constructor < T > ctor = type . getConstructor ( PetiteContainer . class ) ; t = ctor . newInstance ( petiteContainer ) ; } catch ( NoSuchMethodException nsmex ) { // ignore } // if first try failed, try default ctor if ( t == null ) { return ClassUtil . newInstance ( type ) ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new scope . It is not necessary to manually register scopes since they become registered on first scope resolving . However it is possible to pre - register some scopes or to <i > replace< / i > one scope type with another . Replacing may be important for testing purposes when using container - depended scopes . [CODESPLIT] public void registerScope ( final Class < ? extends Scope > scopeType , final Scope scope ) { scopes . put ( scopeType , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for { [CODESPLIT] public BeanDefinition lookupBeanDefinition ( final String name ) { BeanDefinition beanDefinition = beans . get ( name ) ; // try alt bean names if ( beanDefinition == null ) { if ( petiteConfig . isUseAltBeanNames ( ) ) { beanDefinition = beansAlt . get ( name ) ; } } return beanDefinition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for first founded { [CODESPLIT] protected BeanDefinition lookupBeanDefinitions ( final BeanReferences beanReferences ) { final int total = beanReferences . size ( ) ; for ( int i = 0 ; i < total ; i ++ ) { final String name = beanReferences . name ( i ) ; BeanDefinition beanDefinition = lookupBeanDefinition ( name ) ; if ( beanDefinition != null ) { return beanDefinition ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for existing { [CODESPLIT] protected BeanDefinition lookupExistingBeanDefinition ( final String name ) { BeanDefinition beanDefinition = lookupBeanDefinition ( name ) ; if ( beanDefinition == null ) { throw new PetiteException ( \"Bean not found: \" + name ) ; } return beanDefinition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] protected < T > BeanDefinition createBeanDefinitionForRegistration ( final String name , final Class < T > type , final Scope scope , final WiringMode wiringMode , final Consumer < T > consumer ) { return new BeanDefinition <> ( name , type , scope , wiringMode , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] protected < T > BeanDefinition createBeandDefinitionForExternalBeans ( final Class < T > type , final WiringMode wiringMode ) { final String name = resolveBeanName ( type ) ; return new BeanDefinition <> ( name , type , null , wiringMode , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a bean using provided class that is annotated . [CODESPLIT] public BeanDefinition registerPetiteBean ( final Class type ) { return registerPetiteBean ( type , null , null , null , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a bean using provided class that is annotated . [CODESPLIT] public < T > BeanDefinition < T > registerPetiteBean ( final Class < T > type , final Consumer < T > consumer ) { return registerPetiteBean ( type , null , null , null , false , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers or defines a bean . [CODESPLIT] public < T > BeanDefinition < T > registerPetiteBean ( final Class < T > type , String name , Class < ? extends Scope > scopeType , WiringMode wiringMode , final boolean define , final Consumer < T > consumer ) { if ( name == null ) { name = resolveBeanName ( type ) ; } if ( wiringMode == null ) { wiringMode = annotationResolver . resolveBeanWiringMode ( type ) ; } if ( wiringMode == WiringMode . DEFAULT ) { wiringMode = petiteConfig . getDefaultWiringMode ( ) ; } if ( scopeType == null ) { scopeType = annotationResolver . resolveBeanScopeType ( type ) ; } if ( scopeType == null ) { scopeType = SingletonScope . class ; } // remove existing bean BeanDefinition existing = removeBean ( name ) ; if ( existing != null ) { if ( petiteConfig . getDetectDuplicatedBeanNames ( ) ) { throw new PetiteException ( \"Duplicated bean name detected while registering class '\" + type . getName ( ) + \"'. Petite bean class '\" + existing . type . getName ( ) + \"' is already registered with the name: \" + name ) ; } } // check if type is valid if ( type . isInterface ( ) ) { throw new PetiteException ( \"PetiteBean can not be an interface: \" + type . getName ( ) ) ; } // registration if ( log . isDebugEnabled ( ) ) { log . info ( \"Petite bean: [\" + name + \"] --> \" + type . getName ( ) + \" @ \" + scopeType . getSimpleName ( ) + \":\" + wiringMode . toString ( ) ) ; } // register Scope scope = resolveScope ( scopeType ) ; BeanDefinition < T > beanDefinition = createBeanDefinitionForRegistration ( name , type , scope , wiringMode , consumer ) ; registerBean ( name , beanDefinition ) ; // providers ProviderDefinition [ ] providerDefinitions = petiteResolvers . resolveProviderDefinitions ( type , name ) ; if ( providerDefinitions != null ) { for ( ProviderDefinition providerDefinition : providerDefinitions ) { providers . put ( providerDefinition . name , providerDefinition ) ; } } // define if ( define ) { beanDefinition . ctor = petiteResolvers . resolveCtorInjectionPoint ( beanDefinition . type ( ) ) ; beanDefinition . properties = PropertyInjectionPoint . EMPTY ; beanDefinition . methods = MethodInjectionPoint . EMPTY ; beanDefinition . initMethods = InitMethodPoint . EMPTY ; beanDefinition . destroyMethods = DestroyMethodPoint . EMPTY ; } // return return beanDefinition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers bean definition by putting it in the beans map . If bean does not have petite name explicitly defined alternative bean names will be registered . [CODESPLIT] protected void registerBean ( final String name , final BeanDefinition beanDefinition ) { beans . put ( name , beanDefinition ) ; if ( ! petiteConfig . isUseAltBeanNames ( ) ) { return ; } Class type = beanDefinition . type ( ) ; if ( annotationResolver . beanHasAnnotationName ( type ) ) { return ; } Class [ ] interfaces = ClassUtil . resolveAllInterfaces ( type ) ; for ( Class anInterface : interfaces ) { String altName = annotationResolver . resolveBeanName ( anInterface , petiteConfig . getUseFullTypeNames ( ) ) ; if ( name . equals ( altName ) ) { continue ; } if ( beans . containsKey ( altName ) ) { continue ; } if ( beansAlt . containsKey ( altName ) ) { BeanDefinition existing = beansAlt . get ( altName ) ; if ( existing != null ) { beansAlt . put ( altName , null ) ; // store null as value to mark that alt name is duplicate } } else { beansAlt . put ( altName , beanDefinition ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all petite beans of provided type . Bean name is not resolved from a type! Instead all beans are iterated and only beans with equal types are removed . [CODESPLIT] public void removeBean ( final Class type ) { // collect bean names Set < String > beanNames = new HashSet <> ( ) ; for ( BeanDefinition def : beans . values ( ) ) { if ( def . type . equals ( type ) ) { beanNames . add ( def . name ) ; } } // remove collected bean names for ( String beanName : beanNames ) { removeBean ( beanName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes bean and returns definition of removed bean . All resolvers references are deleted too . Returns bean definition of removed bean or <code > null< / code > . [CODESPLIT] public BeanDefinition removeBean ( final String name ) { BeanDefinition bd = beans . remove ( name ) ; if ( bd == null ) { return null ; } bd . scopeRemove ( ) ; return bd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves bean names for give type . [CODESPLIT] protected String [ ] resolveBeanNamesForType ( final Class type ) { String [ ] beanNames = beanCollections . get ( type ) ; if ( beanNames != null ) { return beanNames ; } ArrayList < String > list = new ArrayList <> ( ) ; for ( Map . Entry < String , BeanDefinition > entry : beans . entrySet ( ) ) { BeanDefinition beanDefinition = entry . getValue ( ) ; if ( ClassUtil . isTypeOf ( beanDefinition . type , type ) ) { String beanName = entry . getKey ( ) ; list . add ( beanName ) ; } } if ( list . isEmpty ( ) ) { beanNames = StringPool . EMPTY_ARRAY ; } else { beanNames = list . toArray ( new String [ 0 ] ) ; } beanCollections . put ( type , beanNames ) ; return beanNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers constructor injection point . [CODESPLIT] public void registerPetiteCtorInjectionPoint ( final String beanName , final Class [ ] paramTypes , final String [ ] references ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; Constructor constructor = null ; if ( paramTypes == null ) { CtorDescriptor [ ] ctors = cd . getAllCtorDescriptors ( ) ; if ( ctors != null && ctors . length > 0 ) { if ( ctors . length > 1 ) { throw new PetiteException ( ctors . length + \" suitable constructor found as injection point for: \" + beanDefinition . type . getName ( ) ) ; } constructor = ctors [ 0 ] . getConstructor ( ) ; } } else { CtorDescriptor ctorDescriptor = cd . getCtorDescriptor ( paramTypes , true ) ; if ( ctorDescriptor != null ) { constructor = ctorDescriptor . getConstructor ( ) ; } } if ( constructor == null ) { throw new PetiteException ( \"Constructor not found: \" + beanDefinition . type . getName ( ) ) ; } BeanReferences [ ] ref = referencesResolver . resolveReferenceFromValues ( constructor , references ) ; beanDefinition . ctor = new CtorInjectionPoint ( constructor , ref ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers property injection point . [CODESPLIT] public void registerPetitePropertyInjectionPoint ( final String beanName , final String property , final String reference ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; PropertyDescriptor propertyDescriptor = cd . getPropertyDescriptor ( property , true ) ; if ( propertyDescriptor == null ) { throw new PetiteException ( \"Property not found: \" + beanDefinition . type . getName ( ) + ' ' + property ) ; } BeanReferences ref = referencesResolver . resolveReferenceFromValue ( propertyDescriptor , reference ) ; PropertyInjectionPoint pip = new PropertyInjectionPoint ( propertyDescriptor , ref ) ; beanDefinition . addPropertyInjectionPoint ( pip ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers set injection point . [CODESPLIT] public void registerPetiteSetInjectionPoint ( final String beanName , final String property ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; PropertyDescriptor propertyDescriptor = cd . getPropertyDescriptor ( property , true ) ; if ( propertyDescriptor == null ) { throw new PetiteException ( \"Property not found: \" + beanDefinition . type . getName ( ) + ' ' + property ) ; } SetInjectionPoint sip = new SetInjectionPoint ( propertyDescriptor ) ; beanDefinition . addSetInjectionPoint ( sip ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers method injection point . [CODESPLIT] public void registerPetiteMethodInjectionPoint ( final String beanName , final String methodName , final Class [ ] arguments , final String [ ] references ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; Method method = null ; if ( arguments == null ) { MethodDescriptor [ ] methods = cd . getAllMethodDescriptors ( methodName ) ; if ( methods != null && methods . length > 0 ) { if ( methods . length > 1 ) { throw new PetiteException ( methods . length + \" suitable methods found as injection points for: \" + beanDefinition . type . getName ( ) + ' ' + methodName ) ; } method = methods [ 0 ] . getMethod ( ) ; } } else { MethodDescriptor md = cd . getMethodDescriptor ( methodName , arguments , true ) ; if ( md != null ) { method = md . getMethod ( ) ; } } if ( method == null ) { throw new PetiteException ( \"Method not found: \" + beanDefinition . type . getName ( ) + ' ' + methodName ) ; } BeanReferences [ ] ref = referencesResolver . resolveReferenceFromValues ( method , references ) ; MethodInjectionPoint mip = new MethodInjectionPoint ( method , ref ) ; beanDefinition . addMethodInjectionPoint ( mip ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers init method . [CODESPLIT] public void registerPetiteInitMethods ( final String beanName , final InitMethodInvocationStrategy invocationStrategy , String ... initMethodNames ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; if ( initMethodNames == null ) { initMethodNames = StringPool . EMPTY_ARRAY ; } int total = initMethodNames . length ; InitMethodPoint [ ] initMethodPoints = new InitMethodPoint [ total ] ; int i ; for ( i = 0 ; i < initMethodNames . length ; i ++ ) { MethodDescriptor md = cd . getMethodDescriptor ( initMethodNames [ i ] , ClassUtil . EMPTY_CLASS_ARRAY , true ) ; if ( md == null ) { throw new PetiteException ( \"Init method not found: \" + beanDefinition . type . getName ( ) + ' ' + initMethodNames [ i ] ) ; } initMethodPoints [ i ] = new InitMethodPoint ( md . getMethod ( ) , i , invocationStrategy ) ; } beanDefinition . addInitMethodPoints ( initMethodPoints ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers destroy method . [CODESPLIT] public void registerPetiteDestroyMethods ( final String beanName , String ... destroyMethodNames ) { BeanDefinition beanDefinition = lookupExistingBeanDefinition ( beanName ) ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanDefinition . type ) ; if ( destroyMethodNames == null ) { destroyMethodNames = StringPool . EMPTY_ARRAY ; } int total = destroyMethodNames . length ; DestroyMethodPoint [ ] destroyMethodPoints = new DestroyMethodPoint [ total ] ; int i ; for ( i = 0 ; i < destroyMethodNames . length ; i ++ ) { MethodDescriptor md = cd . getMethodDescriptor ( destroyMethodNames [ i ] , ClassUtil . EMPTY_CLASS_ARRAY , true ) ; if ( md == null ) { throw new PetiteException ( \"Destroy method not found: \" + beanDefinition . type . getName ( ) + ' ' + destroyMethodNames [ i ] ) ; } destroyMethodPoints [ i ] = new DestroyMethodPoint ( md . getMethod ( ) ) ; } beanDefinition . addDestroyMethodPoints ( destroyMethodPoints ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers instance method provider . [CODESPLIT] public void registerPetiteProvider ( final String providerName , final String beanName , final String methodName , final Class [ ] arguments ) { BeanDefinition beanDefinition = lookupBeanDefinition ( beanName ) ; if ( beanDefinition == null ) { throw new PetiteException ( \"Bean not found: \" + beanName ) ; } Class beanType = beanDefinition . type ; ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( beanType ) ; MethodDescriptor md = cd . getMethodDescriptor ( methodName , arguments , true ) ; if ( md == null ) { throw new PetiteException ( \"Provider method not found: \" + methodName ) ; } ProviderDefinition providerDefinition = new ProviderDefinition ( providerName , beanName , md . getMethod ( ) ) ; providers . put ( providerName , providerDefinition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers static method provider . [CODESPLIT] public void registerPetiteProvider ( final String providerName , final Class type , final String staticMethodName , final Class [ ] arguments ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; MethodDescriptor md = cd . getMethodDescriptor ( staticMethodName , arguments , true ) ; if ( md == null ) { throw new PetiteException ( \"Provider method not found: \" + staticMethodName ) ; } ProviderDefinition providerDefinition = new ProviderDefinition ( providerName , md . getMethod ( ) ) ; providers . put ( providerName , providerDefinition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates all beans . Iteration occurs over the { [CODESPLIT] public void forEachBean ( final Consumer < BeanDefinition > beanDefinitionConsumer ) { final Set < String > names = beanNames ( ) ; for ( String beanName : names ) { BeanDefinition beanDefinition = lookupBeanDefinition ( beanName ) ; if ( beanDefinition != null ) { beanDefinitionConsumer . accept ( beanDefinition ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates all beans that are of given type . [CODESPLIT] public void forEachBeanType ( final Class type , final Consumer < String > beanNameConsumer ) { forEachBean ( bd -> { if ( ClassUtil . isTypeOf ( bd . type , type ) ) { beanNameConsumer . accept ( bd . name ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines many parameters at once . [CODESPLIT] public void defineParameters ( final Map < ? , ? > properties ) { for ( Map . Entry < ? , ? > entry : properties . entrySet ( ) ) { defineParameter ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines many parameters at once from { [CODESPLIT] public void defineParameters ( final Props props ) { Map < ? , ? > map = new HashMap <> ( ) ; props . extractProps ( map ) ; defineParameters ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value in the current classloader copy of this variable . If the variable has no value for the current classloader it is first initialized to the value returned by an invocation of the initialValue () method . [CODESPLIT] public synchronized T get ( ) { ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( contextClassLoader != null ) { T value = weakMap . get ( contextClassLoader ) ; if ( ( value == null ) && ! weakMap . containsKey ( contextClassLoader ) ) { value = initialValue ( ) ; weakMap . put ( contextClassLoader , value ) ; } return value ; } if ( ! initialized ) { value = initialValue ( ) ; initialized = true ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the current classloaders s copy of this variable to the specified value . Most subclasses will have no need to override this method relying solely on the initialValue () method to set the values of classloader - locals . [CODESPLIT] public synchronized void set ( final T value ) { ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( contextClassLoader != null ) { weakMap . put ( contextClassLoader , value ) ; return ; } this . value = value ; this . initialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Float get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Float . valueOf ( rs . getFloat ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Float value , final int dbSqlType ) throws SQLException { st . setFloat ( index , value . floatValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Date get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getDate ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Date value , final int dbSqlType ) throws SQLException { st . setDate ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Measure action invocation time . [CODESPLIT] @ Override public Object intercept ( final ActionRequest actionRequest ) throws Exception { printBefore ( actionRequest ) ; long startTime = System . currentTimeMillis ( ) ; Object result = null ; try { result = actionRequest . invoke ( ) ; } catch ( Exception ex ) { result = \"<exception>\" ; throw ex ; } catch ( Throwable th ) { result = \"<throwable>\" ; throw new Exception ( th ) ; } finally { long executionTime = System . currentTimeMillis ( ) - startTime ; printAfter ( actionRequest , executionTime , result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints out the message . User can override this method and modify the way the message is printed . [CODESPLIT] protected void printBefore ( final ActionRequest request ) { StringBuilder message = new StringBuilder ( prefixIn ) ; message . append ( request . getActionPath ( ) ) . append ( \"   [\" ) . append ( request . getActionRuntime ( ) . createActionString ( ) ) . append ( ' ' ) ; out ( message . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints out the message . User can override this method and modify the way the message is printed . [CODESPLIT] protected void printAfter ( final ActionRequest request , final long executionTime , final Object result ) { StringBuilder message = new StringBuilder ( prefixOut ) ; String resultString = StringUtil . toSafeString ( result ) ; if ( resultString . length ( ) > 70 ) { resultString = resultString . substring ( 0 , 70 ) ; resultString += \"...\" ; } message . append ( request . getActionPath ( ) ) . append ( \"  (\" ) . append ( resultString ) . append ( \") in \" ) . append ( executionTime ) . append ( \"ms.\" ) ; out ( message . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves Java version from current version . [CODESPLIT] public static int resolveJavaVersion ( final int version ) { final int javaVersionNumber = SystemUtil . info ( ) . getJavaVersionNumber ( ) ; final int platformVersion = javaVersionNumber - 8 + 52 ; return version > platformVersion ? version : platformVersion ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes int value in an optimal way . [CODESPLIT] public static void pushInt ( final MethodVisitor mv , final int value ) { if ( value <= 5 ) { mv . visitInsn ( ICONST_0 + value ) ; } else if ( value <= Byte . MAX_VALUE ) { mv . visitIntInsn ( BIPUSH , value ) ; } else { mv . visitIntInsn ( SIPUSH , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates argument index . [CODESPLIT] public static void checkArgumentIndex ( final MethodInfo methodInfo , final int argIndex ) { if ( ( argIndex < 1 ) || ( argIndex > methodInfo . getArgumentsCount ( ) ) ) { throw new ProxettaException ( \"Invalid argument index: \" + argIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds advice field name . [CODESPLIT] public static String adviceFieldName ( final String name , final int index ) { return ProxettaNames . fieldPrefix + name + ProxettaNames . fieldDivider + index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds advice method name . [CODESPLIT] public static String adviceMethodName ( final String name , final int index ) { return ProxettaNames . methodPrefix + name + ProxettaNames . methodDivider + index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- load [CODESPLIT] public static void loadMethodArgumentClass ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { TypeInfo argument = methodInfo . getArgument ( index ) ; loadClass ( mv , argument . getOpcode ( ) , argument . getRawName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads all method arguments before INVOKESPECIAL call . [CODESPLIT] public static void loadSpecialMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { mv . visitVarInsn ( ALOAD , 0 ) ; for ( int i = 1 ; i <= methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads all method arguments before INVOKESTATIC call . [CODESPLIT] public static void loadStaticMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { for ( int i = 0 ; i < methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads all method arguments before INVOKEVIRTUAL call . [CODESPLIT] public static void loadVirtualMethodArguments ( final MethodVisitor mv , final MethodInfo methodInfo ) { for ( int i = 1 ; i <= methodInfo . getArgumentsCount ( ) ; i ++ ) { loadMethodArgument ( mv , methodInfo , i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads one argument . Index is 1 - based . No conversion occurs . [CODESPLIT] public static void loadMethodArgument ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { int offset = methodInfo . getArgumentOffset ( index ) ; int type = methodInfo . getArgument ( index ) . getOpcode ( ) ; switch ( type ) { case ' ' : break ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : mv . visitVarInsn ( ILOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( LLOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( FLOAD , offset ) ; break ; case ' ' : mv . visitVarInsn ( DLOAD , offset ) ; break ; default : mv . visitVarInsn ( ALOAD , offset ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores one argument . Index is 1 - based . No conversion occurs . [CODESPLIT] public static void storeMethodArgument ( final MethodVisitor mv , final MethodInfo methodInfo , final int index ) { int offset = methodInfo . getArgumentOffset ( index ) ; int type = methodInfo . getArgument ( index ) . getOpcode ( ) ; switch ( type ) { case ' ' : break ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : mv . visitVarInsn ( ISTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( LSTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( FSTORE , offset ) ; break ; case ' ' : mv . visitVarInsn ( DSTORE , offset ) ; break ; default : mv . visitVarInsn ( ASTORE , offset ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if opcode is xSTORE . [CODESPLIT] public static boolean isStoreOpcode ( final int opcode ) { return ( opcode == ISTORE ) || ( opcode == LSTORE ) || ( opcode == FSTORE ) || ( opcode == DSTORE ) || ( opcode == ASTORE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits return opcodes . [CODESPLIT] public static void visitReturn ( final MethodVisitor mv , final MethodInfo methodInfo , final boolean isLast ) { switch ( methodInfo . getReturnType ( ) . getOpcode ( ) ) { case ' ' : if ( isLast ) { mv . visitInsn ( POP ) ; } mv . visitInsn ( RETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . byteValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . charValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . shortValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . intValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . booleanValue ( mv ) ; } mv . visitInsn ( IRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( LCONST_0 ) ; mv . visitInsn ( LRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . longValue ( mv ) ; } mv . visitInsn ( LRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( FCONST_0 ) ; mv . visitInsn ( FRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . floatValue ( mv ) ; } mv . visitInsn ( FRETURN ) ; break ; case ' ' : if ( isLast ) { mv . visitInsn ( DUP ) ; Label label = new Label ( ) ; mv . visitJumpInsn ( IFNONNULL , label ) ; mv . visitInsn ( POP ) ; mv . visitInsn ( DCONST_0 ) ; mv . visitInsn ( DRETURN ) ; mv . visitLabel ( label ) ; AsmUtil . doubleValue ( mv ) ; } mv . visitInsn ( DRETURN ) ; break ; default : mv . visitInsn ( ARETURN ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares return value . [CODESPLIT] public static void prepareReturnValue ( final MethodVisitor mv , final MethodInfo methodInfo , int varOffset ) { varOffset += methodInfo . getAllArgumentsSize ( ) ; switch ( methodInfo . getReturnType ( ) . getOpcode ( ) ) { case ' ' : mv . visitInsn ( ACONST_NULL ) ; break ; case ' ' : AsmUtil . valueOfByte ( mv ) ; break ; case ' ' : AsmUtil . valueOfCharacter ( mv ) ; break ; case ' ' : AsmUtil . valueOfShort ( mv ) ; break ; case ' ' : AsmUtil . valueOfInteger ( mv ) ; break ; case ' ' : AsmUtil . valueOfBoolean ( mv ) ; break ; case ' ' : AsmUtil . valueOfLong ( mv ) ; break ; case ' ' : AsmUtil . valueOfFloat ( mv ) ; break ; case ' ' : AsmUtil . valueOfDouble ( mv ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates unique key for method signatures map . [CODESPLIT] public static String createMethodSignaturesKey ( final int access , final String methodName , final String description , final String className ) { return new StringBand ( 7 ) . append ( access ) . append ( COLON ) . append ( description ) . append ( StringPool . UNDERSCORE ) . append ( className ) . append ( StringPool . HASH ) . append ( methodName ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits non - array element value for annotation . Returns <code > true< / code > if value is successfully processed . [CODESPLIT] public static void visitElementValue ( final MethodVisitor mv , final Object elementValue , final boolean boxPrimitives ) { if ( elementValue instanceof String ) { // string mv . visitLdcInsn ( elementValue ) ; return ; } if ( elementValue instanceof Type ) { // class mv . visitLdcInsn ( elementValue ) ; return ; } if ( elementValue instanceof Class ) { mv . visitLdcInsn ( Type . getType ( ( Class ) elementValue ) ) ; return ; } // primitives if ( elementValue instanceof Integer ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfInteger ( mv ) ; } return ; } if ( elementValue instanceof Long ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfLong ( mv ) ; } return ; } if ( elementValue instanceof Short ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfShort ( mv ) ; } return ; } if ( elementValue instanceof Byte ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfByte ( mv ) ; } return ; } if ( elementValue instanceof Float ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfFloat ( mv ) ; } return ; } if ( elementValue instanceof Double ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfDouble ( mv ) ; } return ; } if ( elementValue instanceof Character ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfCharacter ( mv ) ; } return ; } if ( elementValue instanceof Boolean ) { mv . visitLdcInsn ( elementValue ) ; if ( boxPrimitives ) { AsmUtil . valueOfBoolean ( mv ) ; } return ; } // enum Class elementValueClass = elementValue . getClass ( ) ; Class enumClass = ClassUtil . findEnum ( elementValueClass ) ; if ( enumClass != null ) { try { String typeRef = AsmUtil . typeToTyperef ( enumClass ) ; String typeSignature = AsmUtil . typeToSignature ( enumClass ) ; // invoke Method nameMethod = elementValue . getClass ( ) . getMethod ( \"name\" ) ; String name = ( String ) nameMethod . invoke ( elementValue ) ; mv . visitFieldInsn ( GETSTATIC , typeSignature , name , typeRef ) ; return ; } catch ( Exception ignore ) { } } throw new ProxettaException ( \"Unsupported annotation type: \" + elementValue . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new array . [CODESPLIT] public static void newArray ( final MethodVisitor mv , final Class componentType ) { if ( componentType == int . class ) { mv . visitIntInsn ( NEWARRAY , T_INT ) ; return ; } if ( componentType == long . class ) { mv . visitIntInsn ( NEWARRAY , T_LONG ) ; return ; } if ( componentType == float . class ) { mv . visitIntInsn ( NEWARRAY , T_FLOAT ) ; return ; } if ( componentType == double . class ) { mv . visitIntInsn ( NEWARRAY , T_DOUBLE ) ; return ; } if ( componentType == byte . class ) { mv . visitIntInsn ( NEWARRAY , T_BYTE ) ; return ; } if ( componentType == short . class ) { mv . visitIntInsn ( NEWARRAY , T_SHORT ) ; return ; } if ( componentType == boolean . class ) { mv . visitIntInsn ( NEWARRAY , T_BOOLEAN ) ; return ; } if ( componentType == char . class ) { mv . visitIntInsn ( NEWARRAY , T_CHAR ) ; return ; } mv . visitTypeInsn ( ANEWARRAY , AsmUtil . typeToSignature ( componentType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores element on stack into an array . [CODESPLIT] public static void storeIntoArray ( final MethodVisitor mv , final Class componentType ) { if ( componentType == int . class ) { mv . visitInsn ( IASTORE ) ; return ; } if ( componentType == long . class ) { mv . visitInsn ( LASTORE ) ; return ; } if ( componentType == float . class ) { mv . visitInsn ( FASTORE ) ; return ; } if ( componentType == double . class ) { mv . visitInsn ( DASTORE ) ; return ; } if ( componentType == byte . class ) { mv . visitInsn ( BASTORE ) ; return ; } if ( componentType == short . class ) { mv . visitInsn ( SASTORE ) ; return ; } if ( componentType == boolean . class ) { mv . visitInsn ( BASTORE ) ; return ; } if ( componentType == char . class ) { mv . visitInsn ( CASTORE ) ; return ; } mv . visitInsn ( AASTORE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- detect advice macros [CODESPLIT] public static boolean isInvokeMethod ( final String name , final String desc ) { if ( name . equals ( \"invoke\" ) ) { if ( desc . equals ( \"()Ljava/lang/Object;\" ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups the decorator for given decorator path . Returns { [CODESPLIT] public char [ ] lookupDecoratorContent ( final String path ) { if ( contentMap != null ) { final char [ ] data = contentMap . get ( path ) ; if ( data != null ) { return data ; } final File file = filesMap . get ( path ) ; if ( file != null ) { try { return FileUtil . readChars ( file ) ; } catch ( IOException e ) { throw new DecoraException ( \"Unable to read Decrator files\" , e ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves decorator path based on request and action path . If decorator is not found returns <code > null< / code > . By default applies decorator on all * . html pages . [CODESPLIT] public String resolveDecorator ( final HttpServletRequest request , final String actionPath ) { if ( actionPath . endsWith ( \".html\" ) ) { return DEFAULT_DECORATOR ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : should this always return lowercase or always uppercase? [CODESPLIT] public static String extractMimeType ( final String contentType ) { final int ndx = contentType . indexOf ( ' ' ) ; final String mime ; if ( ndx != - 1 ) { mime = contentType . substring ( 0 , ndx ) ; } else { mime = contentType ; } return mime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : should this always return lowercase or always uppercase? [CODESPLIT] public static String extractEncoding ( final String contentType ) { int ndx = contentType . indexOf ( ' ' ) ; final String charset = ndx != - 1 ? contentType . substring ( ndx + 1 ) : StringPool . EMPTY ; String encoding = null ; ndx = charset . indexOf ( ATTR_CHARSET ) ; if ( ndx != - 1 ) { ndx += ATTR_CHARSET . length ( ) ; final int len = charset . length ( ) ; if ( charset . charAt ( ndx ) == ' ' ) { ndx ++ ; } final int start = ndx ; while ( ndx < len ) { final char c = charset . charAt ( ndx ) ; if ( ( c == ' ' ) || ( CharUtil . isWhitespace ( c ) ) || ( c == ' ' ) ) { break ; } ndx ++ ; } encoding = charset . substring ( start , ndx ) ; } return encoding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts encoding from a given content type . [CODESPLIT] public static String extractEncoding ( final String contentType , String defaultEncoding ) { String encoding = extractEncoding ( contentType ) ; if ( encoding == null ) { if ( defaultEncoding == null ) { defaultEncoding = JoddCore . encoding ; } encoding = defaultEncoding ; } return encoding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Correctly resolves file name from the message part . Thanx to : Flavio Pompermaier [CODESPLIT] public static String resolveFileName ( final Part part ) throws MessagingException { if ( ! ( part instanceof MimeBodyPart ) ) { return part . getFileName ( ) ; } final String contentType = part . getContentType ( ) ; String ret ; try { ret = MimeUtility . decodeText ( part . getFileName ( ) ) ; } catch ( final Exception ex ) { // String[] contentId = part.getHeader(\"Content-ID\"); // if (contentId != null && contentId.length > 0) { final String contentId = ( ( MimeBodyPart ) part ) . getContentID ( ) ; if ( contentId != null ) { ret = contentId + contentTypeForFileName ( contentType ) ; } else { ret = defaultFileName ( contentType ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether flags is a empty flags [CODESPLIT] public static boolean isEmptyFlags ( Flags flags ) { if ( flags == null ) return true ; Flags . Flag [ ] systemFlags = flags . getSystemFlags ( ) ; if ( systemFlags != null && systemFlags . length > 0 ) { return false ; } String [ ] userFlags = flags . getUserFlags ( ) ; if ( userFlags != null && userFlags . length > 0 ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected char [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final char [ ] target = new char [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Character > charArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final char convertedValue = convertType ( element ) ; charArrayList . add ( Character . valueOf ( convertedValue ) ) ; } final char [ ] array = new char [ charArrayList . size ( ) ] ; for ( int i = 0 ; i < charArrayList . size ( ) ; i ++ ) { final Character c = charArrayList . get ( i ) ; array [ i ] = c . charValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final CharSequence charSequence = ( CharSequence ) value ; final char [ ] result = new char [ charSequence . length ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = charSequence . charAt ( i ) ; } return result ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if a request is multi - part request . [CODESPLIT] public static boolean isMultipartRequest ( final HttpServletRequest request ) { String type = request . getHeader ( HEADER_CONTENT_TYPE ) ; return ( type != null ) && type . startsWith ( TYPE_MULTIPART_FORM_DATA ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the Authorization header and retrieves the user s name from it . Returns <code > null< / code > if the header is not present . [CODESPLIT] public static String resolveAuthUsername ( final HttpServletRequest request ) { String header = request . getHeader ( HEADER_AUTHORIZATION ) ; if ( header == null ) { return null ; } if ( ! header . contains ( \"Basic \" ) ) { return null ; } final String encoded = header . substring ( header . indexOf ( ' ' ) + 1 ) ; final String decoded = new String ( Base64 . decode ( encoded ) ) ; return decoded . substring ( 0 , decoded . indexOf ( ' ' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Bearer token . [CODESPLIT] public static String resolveAuthBearerToken ( final HttpServletRequest request ) { String header = request . getHeader ( HEADER_AUTHORIZATION ) ; if ( header == null ) { return null ; } int ndx = header . indexOf ( \"Bearer \" ) ; if ( ndx == - 1 ) { return null ; } return header . substring ( ndx + 7 ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends correct headers to require basic authentication for the given realm . [CODESPLIT] public static void requireAuthentication ( final HttpServletResponse resp , final String realm ) throws IOException { resp . setHeader ( WWW_AUTHENTICATE , \"Basic realm=\\\"\" + realm + ' ' ) ; resp . sendError ( HttpServletResponse . SC_UNAUTHORIZED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares response for file download with provided mime type . [CODESPLIT] public static void prepareDownload ( final HttpServletResponse response , final File file , final String mimeType ) { if ( ! file . exists ( ) ) { throw new IllegalArgumentException ( \"File not found: \" + file ) ; } if ( file . length ( ) > Integer . MAX_VALUE ) { throw new IllegalArgumentException ( \"File too big: \" + file ) ; } prepareResponse ( response , file . getAbsolutePath ( ) , mimeType , ( int ) file . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares response for various provided data . [CODESPLIT] public static void prepareResponse ( final HttpServletResponse response , final String fileName , String mimeType , final int fileSize ) { if ( ( mimeType == null ) && ( fileName != null ) ) { String extension = FileNameUtil . getExtension ( fileName ) ; mimeType = MimeTypes . getMimeType ( extension ) ; } if ( mimeType != null ) { response . setContentType ( mimeType ) ; } if ( fileSize >= 0 ) { response . setContentLength ( fileSize ) ; } // support internationalization // See https://tools.ietf.org/html/rfc6266#section-5 for more information. if ( fileName != null ) { String name = FileNameUtil . getName ( fileName ) ; String encodedFileName = URLCoder . encode ( name ) ; response . setHeader ( CONTENT_DISPOSITION , \"attachment;filename=\\\"\" + name + \"\\\";filename*=utf8''\" + encodedFileName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all cookies from client that matches provided name . [CODESPLIT] public static Cookie [ ] getAllCookies ( final HttpServletRequest request , final String cookieName ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies == null ) { return null ; } ArrayList < Cookie > list = new ArrayList <> ( cookies . length ) ; for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( cookieName ) ) { list . add ( cookie ) ; } } if ( list . isEmpty ( ) ) { return null ; } return list . toArray ( new Cookie [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads HTTP request body using the request reader . Once body is read it cannot be read again! [CODESPLIT] public static String readRequestBodyFromReader ( final HttpServletRequest request ) throws IOException { BufferedReader buff = request . getReader ( ) ; StringWriter out = new StringWriter ( ) ; StreamUtil . copy ( buff , out ) ; return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads HTTP request body using the request stream . Once body is read it cannot be read again! [CODESPLIT] public static String readRequestBodyFromStream ( final HttpServletRequest request ) throws IOException { String charEncoding = request . getCharacterEncoding ( ) ; if ( charEncoding == null ) { charEncoding = JoddCore . encoding ; } CharArrayWriter charArrayWriter = new CharArrayWriter ( ) ; BufferedReader bufferedReader = null ; try { InputStream inputStream = request . getInputStream ( ) ; if ( inputStream != null ) { bufferedReader = new BufferedReader ( new InputStreamReader ( inputStream , charEncoding ) ) ; StreamUtil . copy ( bufferedReader , charArrayWriter ) ; } else { return StringPool . EMPTY ; } } finally { StreamUtil . close ( bufferedReader ) ; } return charArrayWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns correct context path as by Servlet definition . Different application servers return all variants : null / . <p > The context path always comes first in a request URI . The path starts with a / character but does not end with a / character . For servlets in the default ( root ) context this method returns . [CODESPLIT] public static String getContextPath ( final HttpServletRequest request ) { String contextPath = request . getContextPath ( ) ; if ( contextPath == null || contextPath . equals ( StringPool . SLASH ) ) { contextPath = StringPool . EMPTY ; } return contextPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns correct context path as by Servlet definition . Different application servers return all variants : null / . <p > The context path always comes first in a request URI . The path starts with a / character but does not end with a / character . For servlets in the default ( root ) context this method returns . [CODESPLIT] public static String getContextPath ( final ServletContext servletContext ) { String contextPath = servletContext . getContextPath ( ) ; if ( contextPath == null || contextPath . equals ( StringPool . SLASH ) ) { contextPath = StringPool . EMPTY ; } return contextPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores context path in server context and request scope . [CODESPLIT] public static void storeContextPath ( final PageContext pageContext , final String contextPathVariableName ) { String ctxPath = getContextPath ( pageContext ) ; HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; request . setAttribute ( contextPathVariableName , ctxPath ) ; ServletContext servletContext = pageContext . getServletContext ( ) ; servletContext . setAttribute ( contextPathVariableName , ctxPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores context path in page context and request scope . [CODESPLIT] public static void storeContextPath ( final ServletContext servletContext , final String contextPathVariableName ) { String ctxPath = getContextPath ( servletContext ) ; servletContext . setAttribute ( contextPathVariableName , ctxPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns non - <code > null< / code > attribute value . Scopes are examined in the following order : request session application . [CODESPLIT] public static Object attribute ( final HttpServletRequest request , final String name ) { Object value = request . getAttribute ( name ) ; if ( value != null ) { return value ; } value = request . getSession ( ) . getAttribute ( name ) ; if ( value != null ) { return value ; } return request . getServletContext ( ) . getAttribute ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns value of property / attribute . The following value sets are looked up : <ul > <li > page context attributes< / li > <li > request attributes< / li > <li > request parameters ( multi - part request detected ) < / li > <li > session attributes< / li > <li > context attributes< / li > < / ul > [CODESPLIT] public static Object value ( final PageContext pageContext , final String name ) { Object value = pageContext . getAttribute ( name ) ; if ( value != null ) { return value ; } return value ( ( HttpServletRequest ) pageContext . getRequest ( ) , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns value of property / attribute . The following value sets are looked up : <ul > <li > request attributes< / li > <li > request parameters ( multi - part request detected ) < / li > <li > session attributes< / li > <li > context attributes< / li > < / ul > [CODESPLIT] public static Object value ( final HttpServletRequest request , final String name ) { Object value = request . getAttribute ( name ) ; if ( value != null ) { return value ; } if ( isMultipartRequest ( request ) ) { try { MultipartRequest multipartRequest = MultipartRequest . getInstance ( request ) ; value = multipartRequest . getParameter ( name ) ; } catch ( IOException ignore ) { } } else { String [ ] params = request . getParameterValues ( name ) ; if ( params != null ) { if ( params . length == 1 ) { value = params [ 0 ] ; } else { value = params ; } } } if ( value != null ) { return value ; } value = request . getSession ( ) . getAttribute ( name ) ; if ( value != null ) { return value ; } return request . getServletContext ( ) . getAttribute ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets scope attribute . [CODESPLIT] public static void setScopeAttribute ( final String name , final Object value , final String scope , final PageContext pageContext ) { HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; String scopeValue = scope != null ? scope . toLowerCase ( ) : SCOPE_PAGE ; if ( scopeValue . equals ( SCOPE_PAGE ) ) { pageContext . setAttribute ( name , value ) ; } else if ( scopeValue . equals ( SCOPE_REQUEST ) ) { request . setAttribute ( name , value ) ; } else if ( scopeValue . equals ( SCOPE_SESSION ) ) { request . getSession ( ) . setAttribute ( name , value ) ; } else if ( scopeValue . equals ( SCOPE_APPLICATION ) ) { request . getServletContext ( ) . setAttribute ( name , value ) ; } else { throw new IllegalArgumentException ( \"Invalid scope: \" + scope ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes scope attribute . [CODESPLIT] public static void removeScopeAttribute ( final String name , final String scope , final PageContext pageContext ) { HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; String scopeValue = scope != null ? scope . toLowerCase ( ) : SCOPE_PAGE ; if ( scopeValue . equals ( SCOPE_PAGE ) ) { pageContext . removeAttribute ( name ) ; } else if ( scopeValue . equals ( SCOPE_REQUEST ) ) { request . removeAttribute ( name ) ; } else if ( scopeValue . equals ( SCOPE_SESSION ) ) { request . getSession ( ) . removeAttribute ( name ) ; } else if ( scopeValue . equals ( SCOPE_APPLICATION ) ) { request . getServletContext ( ) . removeAttribute ( name ) ; } else { throw new IllegalArgumentException ( \"Invalid scope: \" + scope ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if current URL is absolute <code > false< / code > otherwise . [CODESPLIT] public static boolean isAbsoluteUrl ( final String url ) { if ( url == null ) { // a null URL is not absolute return false ; } int colonPos ; // fast simple check first if ( ( colonPos = url . indexOf ( ' ' ) ) == - 1 ) { return false ; } // if we DO have a colon, make sure that every character // leading up to it is a valid scheme character for ( int i = 0 ; i < colonPos ; i ++ ) { if ( VALID_SCHEME_CHARS . indexOf ( url . charAt ( i ) ) == - 1 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips a servlet session ID from <code > url< / code > . The session ID is encoded as a URL path parameter beginning with jsessionid = . We thus remove anything we find between ; jsessionid = ( inclusive ) and either EOS or a subsequent ; ( exclusive ) . [CODESPLIT] public static String stripSessionId ( final String url ) { StringBuilder u = new StringBuilder ( url ) ; int sessionStart ; while ( ( sessionStart = u . toString ( ) . indexOf ( \";jsessionid=\" ) ) != - 1 ) { int sessionEnd = u . toString ( ) . indexOf ( ' ' , sessionStart + 1 ) ; if ( sessionEnd == - 1 ) { sessionEnd = u . toString ( ) . indexOf ( ' ' , sessionStart + 1 ) ; } if ( sessionEnd == - 1 ) { sessionEnd = u . length ( ) ; } u . delete ( sessionStart , sessionEnd ) ; } return u . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns HTTP request parameter as String or String [] . [CODESPLIT] public static Object getRequestParameter ( final ServletRequest request , final String name ) { String [ ] values = request . getParameterValues ( name ) ; if ( values == null ) { return null ; } if ( values . length == 1 ) { return values [ 0 ] ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if some parameter is in GET parameters . [CODESPLIT] public boolean isGetParameter ( final HttpServletRequest request , String name ) { name = URLCoder . encodeQueryParam ( name ) + ' ' ; String query = request . getQueryString ( ) ; String [ ] nameValuePairs = StringUtil . splitc ( query , ' ' ) ; for ( String nameValuePair : nameValuePairs ) { if ( nameValuePair . startsWith ( name ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares parameters for further processing . [CODESPLIT] public static String [ ] prepareParameters ( final String [ ] paramValues , final boolean treatEmptyParamsAsNull , final boolean ignoreEmptyRequestParams ) { if ( treatEmptyParamsAsNull || ignoreEmptyRequestParams ) { int emptyCount = 0 ; int total = paramValues . length ; for ( int i = 0 ; i < paramValues . length ; i ++ ) { String paramValue = paramValues [ i ] ; if ( paramValue == null ) { emptyCount ++ ; continue ; } if ( paramValue . length ( ) == 0 ) { emptyCount ++ ; if ( treatEmptyParamsAsNull ) { paramValue = null ; } } paramValues [ i ] = paramValue ; } if ( ( ignoreEmptyRequestParams ) && ( emptyCount == total ) ) { return null ; } } return paramValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public static boolean isJsonRequest ( HttpServletRequest servletRequest ) { final String contentType = servletRequest . getContentType ( ) ; if ( contentType == null ) { return false ; } return contentType . equals ( MimeTypes . MIME_APPLICATION_JSON ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all request parameters to attributes . [CODESPLIT] public static void copyParamsToAttributes ( final HttpServletRequest servletRequest , final boolean treatEmptyParamsAsNull , final boolean ignoreEmptyRequestParams ) { Enumeration paramNames = servletRequest . getParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { String paramName = ( String ) paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } String [ ] paramValues = servletRequest . getParameterValues ( paramName ) ; paramValues = prepareParameters ( paramValues , treatEmptyParamsAsNull , ignoreEmptyRequestParams ) ; if ( paramValues == null ) { continue ; } servletRequest . setAttribute ( paramName , paramValues . length == 1 ? paramValues [ 0 ] : paramValues ) ; } // multipart if ( ! ( servletRequest instanceof MultipartRequestWrapper ) ) { return ; } MultipartRequestWrapper multipartRequest = ( MultipartRequestWrapper ) servletRequest ; if ( ! multipartRequest . isMultipart ( ) ) { return ; } paramNames = multipartRequest . getFileParameterNames ( ) ; while ( paramNames . hasMoreElements ( ) ) { String paramName = ( String ) paramNames . nextElement ( ) ; if ( servletRequest . getAttribute ( paramName ) != null ) { continue ; } FileUpload [ ] paramValues = multipartRequest . getFiles ( paramName ) ; servletRequest . setAttribute ( paramName , paramValues . length == 1 ? paramValues [ 0 ] : paramValues ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes tag body . [CODESPLIT] public static void invokeBody ( final JspFragment body ) throws JspException { if ( body == null ) { return ; } try { body . invoke ( null ) ; } catch ( IOException ioex ) { throw new JspException ( \"Tag body failed\" , ioex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders tag body to char array . [CODESPLIT] public static char [ ] renderBody ( final JspFragment body ) throws JspException { FastCharArrayWriter writer = new FastCharArrayWriter ( ) ; invokeBody ( body , writer ) ; return writer . toCharArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders tag body to string . [CODESPLIT] public static String renderBodyToString ( final JspFragment body ) throws JspException { char [ ] result = renderBody ( body ) ; return new String ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets scope attribute . [CODESPLIT] public static void setScopeAttribute ( final String name , final Object value , final String scope , final PageContext pageContext ) throws JspException { try { ServletUtil . setScopeAttribute ( name , value , scope , pageContext ) ; } catch ( UncheckedException uex ) { throw new JspException ( uex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes scope attribute . [CODESPLIT] public static void removeScopeAttribute ( final String name , final String scope , final PageContext pageContext ) throws JspException { try { ServletUtil . removeScopeAttribute ( name , scope , pageContext ) ; } catch ( UncheckedException uex ) { throw new JspException ( uex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes init methods . [CODESPLIT] public void invokeInitMethods ( final InitMethodInvocationStrategy invocationStrategy ) { for ( final InitMethodPoint initMethod : beanDefinition . initMethodPoints ( ) ) { if ( invocationStrategy != initMethod . invocationStrategy ) { continue ; } try { initMethod . method . invoke ( bean ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Invalid init method: \" + initMethod , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls destroy methods on given BeanData . Destroy methods are called without any order . [CODESPLIT] public void callDestroyMethods ( ) { for ( final DestroyMethodPoint destroyMethodPoint : beanDefinition . destroyMethodPoints ( ) ) { try { destroyMethodPoint . method . invoke ( bean ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Invalid destroy method: \" + destroyMethodPoint . method , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance . [CODESPLIT] public Object newBeanInstance ( ) { if ( beanDefinition . ctor == CtorInjectionPoint . EMPTY ) { throw new PetiteException ( \"No constructor (annotated, single or default) founded as injection point for: \" + beanDefinition . type . getName ( ) ) ; } int paramNo = beanDefinition . ctor . references . length ; Object [ ] args = new Object [ paramNo ] ; // wiring if ( beanDefinition . wiringMode != WiringMode . NONE ) { for ( int i = 0 ; i < paramNo ; i ++ ) { args [ i ] = pc . getBean ( beanDefinition . ctor . references [ i ] ) ; if ( args [ i ] == null ) { if ( ( beanDefinition . wiringMode == WiringMode . STRICT ) ) { throw new PetiteException ( \"Wiring constructor failed. References '\" + beanDefinition . ctor . references [ i ] + \"' not found for constructor: \" + beanDefinition . ctor . constructor ) ; } } } } // create instance final Object bean ; try { bean = beanDefinition . ctor . constructor . newInstance ( args ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Failed to create new bean instance '\" + beanDefinition . type . getName ( ) + \"' using constructor: \" + beanDefinition . ctor . constructor , ex ) ; } return bean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects all parameters . [CODESPLIT] public void injectParams ( final ParamManager paramManager , final boolean implicitParamInjection ) { if ( beanDefinition . name == null ) { return ; } if ( implicitParamInjection ) { // implicit final int len = beanDefinition . name . length ( ) + 1 ; for ( final String param : beanDefinition . params ) { final Object value = paramManager . get ( param ) ; final String destination = param . substring ( len ) ; try { BeanUtil . declared . setProperty ( bean , destination , value ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Unable to set parameter: '\" + param + \"' to bean: \" + beanDefinition . name , ex ) ; } } } // explicit for ( final ValueInjectionPoint pip : beanDefinition . values ) { final String value = paramManager . parseKeyTemplate ( pip . valueTemplate ) ; try { BeanUtil . declared . setProperty ( bean , pip . property , value ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Unable to set value for: '\" + pip . valueTemplate + \"' to bean: \" + beanDefinition . name , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rewrites action path . [CODESPLIT] @ SuppressWarnings ( { \"UnusedDeclaration\" } ) public String rewrite ( final HttpServletRequest servletRequest , final String actionPath , final String httpMethod ) { return actionPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- configure [CODESPLIT] @ Override public void configure ( final HasSubstring annotation ) { this . substring = annotation . value ( ) ; this . ignoreCase = annotation . ignoreCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- valid [CODESPLIT] @ Override public boolean isValid ( final ValidationConstraintContext vcc , final Object value ) { return validate ( value , substring , ignoreCase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds new header value . If existing value exist it will be removed so the store the new key value . [CODESPLIT] public void addHeader ( final String name , final String value ) { List < String > valuesList = super . getAll ( name ) ; if ( valuesList . isEmpty ( ) ) { super . add ( name , value ) ; return ; } super . remove ( name ) ; valuesList . add ( value ) ; super . addAll ( name , valuesList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- configure [CODESPLIT] @ Override public void configure ( final Length annotation ) { this . min = annotation . min ( ) ; this . max = annotation . max ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- valid [CODESPLIT] @ Override public boolean isValid ( final ValidationConstraintContext vcc , final Object value ) { return validate ( value , min , max ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts key - value pair into the map with respect of appending duplicate properties [CODESPLIT] protected void put ( final String profile , final Map < String , PropsEntry > map , final String key , final String value , final boolean append ) { String realValue = value ; if ( append || appendDuplicateProps ) { PropsEntry pv = map . get ( key ) ; if ( pv != null ) { realValue = pv . value + APPEND_SEPARATOR + realValue ; } } PropsEntry propsEntry = new PropsEntry ( key , realValue , profile , this ) ; // update position pointers if ( first == null ) { first = propsEntry ; } else { last . next = propsEntry ; } last = propsEntry ; // add to the map map . put ( key , propsEntry ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds base property . [CODESPLIT] public void putBaseProperty ( final String key , final String value , final boolean append ) { put ( null , baseProperties , key , value , append ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Counts profile properties . Note : this method is not that easy on execution . [CODESPLIT] public int countProfileProperties ( ) { final HashSet < String > profileKeys = new HashSet <> ( ) ; for ( final Map < String , PropsEntry > map : profileProperties . values ( ) ) { for ( final String key : map . keySet ( ) ) { if ( ! baseProperties . containsKey ( key ) ) { profileKeys . add ( key ) ; } } } return profileKeys . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds profile property . [CODESPLIT] public void putProfileProperty ( final String key , final String value , final String profile , final boolean append ) { Map < String , PropsEntry > map = profileProperties . computeIfAbsent ( profile , k -> new HashMap <> ( ) ) ; put ( profile , map , key , value , append ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns profile property . [CODESPLIT] public PropsEntry getProfileProperty ( final String profile , final String key ) { final Map < String , PropsEntry > profileMap = profileProperties . get ( profile ) ; if ( profileMap == null ) { return null ; } return profileMap . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup props value through profiles and base properties . Returns { [CODESPLIT] protected String lookupValue ( final String key , final String ... profiles ) { if ( profiles != null ) { for ( String profile : profiles ) { if ( profile == null ) { continue ; } while ( true ) { final Map < String , PropsEntry > profileMap = this . profileProperties . get ( profile ) ; if ( profileMap != null ) { final PropsEntry value = profileMap . get ( key ) ; if ( value != null ) { return value . getValue ( profiles ) ; } } // go back with profile final int ndx = profile . lastIndexOf ( ' ' ) ; if ( ndx == - 1 ) { break ; } profile = profile . substring ( 0 , ndx ) ; } } } final PropsEntry value = getBaseProperty ( key ) ; if ( value == null ) { return null ; } return value . getValue ( profiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves all macros in this props set . Called on property lookup . [CODESPLIT] public String resolveMacros ( String value , final String ... profiles ) { // create string template parser that will be used internally StringTemplateParser stringTemplateParser = new StringTemplateParser ( ) ; stringTemplateParser . setResolveEscapes ( false ) ; if ( ! ignoreMissingMacros ) { stringTemplateParser . setReplaceMissingKey ( false ) ; } else { stringTemplateParser . setReplaceMissingKey ( true ) ; stringTemplateParser . setMissingKeyReplacement ( StringPool . EMPTY ) ; } final Function < String , String > macroResolver = macroName -> { String [ ] lookupProfiles = profiles ; int leftIndex = macroName . indexOf ( ' ' ) ; if ( leftIndex != - 1 ) { int rightIndex = macroName . indexOf ( ' ' ) ; String profiles1 = macroName . substring ( leftIndex + 1 , rightIndex ) ; macroName = macroName . substring ( 0 , leftIndex ) . concat ( macroName . substring ( rightIndex + 1 ) ) ; lookupProfiles = StringUtil . splitc ( profiles1 , ' ' ) ; StringUtil . trimAll ( lookupProfiles ) ; } return lookupValue ( macroName , lookupProfiles ) ; } ; // start parsing int loopCount = 0 ; while ( loopCount ++ < MAX_INNER_MACROS ) { final String newValue = stringTemplateParser . parse ( value , macroResolver ) ; if ( newValue . equals ( value ) ) { break ; } if ( skipEmptyProps ) { if ( newValue . length ( ) == 0 ) { return null ; } } value = newValue ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts props to target map . This is all - in - one method that does many things at once . [CODESPLIT] public Map extract ( Map target , final String [ ] profiles , final String [ ] wildcardPatterns , String prefix ) { if ( target == null ) { target = new HashMap ( ) ; } // make sure prefix ends with a dot if ( prefix != null ) { if ( ! StringUtil . endsWithChar ( prefix , ' ' ) ) { prefix += StringPool . DOT ; } } if ( profiles != null ) { for ( String profile : profiles ) { while ( true ) { final Map < String , PropsEntry > map = this . profileProperties . get ( profile ) ; if ( map != null ) { extractMap ( target , map , profiles , wildcardPatterns , prefix ) ; } final int ndx = profile . lastIndexOf ( ' ' ) ; if ( ndx == - 1 ) { break ; } profile = profile . substring ( 0 , ndx ) ; } } } extractMap ( target , this . baseProperties , profiles , wildcardPatterns , prefix ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cycically extract a word of key material . [CODESPLIT] private static int streamtoword ( byte [ ] data , int [ ] offp ) { int i ; int word = 0 ; int off = offp [ 0 ] ; for ( i = 0 ; i < 4 ; i ++ ) { word = ( word << 8 ) | ( data [ off ] & 0xff ) ; off = ( off + 1 ) % data . length ; } offp [ 0 ] = off ; return word ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hash a password using the OpenBSD bcrypt scheme . [CODESPLIT] public static String hashpw ( String password , String salt ) { BCrypt B ; String real_salt ; byte [ ] passwordb , saltb , hashed ; char minor = ( char ) 0 ; int rounds , off ; StringBuffer rs = new StringBuffer ( ) ; if ( salt . charAt ( 0 ) != ' ' || salt . charAt ( 1 ) != ' ' ) { throw new IllegalArgumentException ( \"Invalid salt version\" ) ; } if ( salt . charAt ( 2 ) == ' ' ) { off = 3 ; } else { minor = salt . charAt ( 2 ) ; if ( minor != ' ' || salt . charAt ( 3 ) != ' ' ) { throw new IllegalArgumentException ( \"Invalid salt revision\" ) ; } off = 4 ; } // Extract number of rounds if ( salt . charAt ( off + 2 ) > ' ' ) { throw new IllegalArgumentException ( \"Missing salt rounds\" ) ; } rounds = Integer . parseInt ( salt . substring ( off , off + 2 ) ) ; real_salt = salt . substring ( off + 3 , off + 25 ) ; try { passwordb = ( password + ( minor >= ' ' ? \"\\000\" : \"\" ) ) . getBytes ( \"UTF-8\" ) ; } catch ( UnsupportedEncodingException uee ) { throw new AssertionError ( \"UTF-8 is not supported\" ) ; } saltb = decode_base64 ( real_salt , BCRYPT_SALT_LEN ) ; B = new BCrypt ( ) ; hashed = B . crypt_raw ( passwordb , saltb , rounds , ( int [ ] ) bf_crypt_ciphertext . clone ( ) ) ; rs . append ( \"$2\" ) ; if ( minor >= ' ' ) { rs . append ( minor ) ; } rs . append ( ' ' ) ; if ( rounds < 10 ) { rs . append ( ' ' ) ; } if ( rounds > 30 ) { throw new IllegalArgumentException ( \"rounds exceeds maximum (30)\" ) ; } rs . append ( rounds ) . append ( ' ' ) . append ( encode_base64 ( saltb , saltb . length ) ) . append ( encode_base64 ( hashed , bf_crypt_ciphertext . length * 4 - 1 ) ) ; return rs . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that a plaintext password matches a previously hashed one . [CODESPLIT] public static boolean checkpw ( String plaintext , String hashed ) { byte [ ] hashed_bytes ; byte [ ] try_bytes ; try { String try_pw = hashpw ( plaintext , hashed ) ; hashed_bytes = hashed . getBytes ( \"UTF-8\" ) ; try_bytes = try_pw . getBytes ( \"UTF-8\" ) ; } catch ( UnsupportedEncodingException uee ) { return false ; } if ( hashed_bytes . length != try_bytes . length ) { return false ; } byte ret = 0 ; for ( int i = 0 ; i < try_bytes . length ; i ++ ) { ret |= hashed_bytes [ i ] ^ try_bytes [ i ] ; } return ret == 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data header from the input stream . When there is no more headers ( i . e . end of stream reached ) returns <code > null< / code > [CODESPLIT] public FileUploadHeader readDataHeader ( final String encoding ) throws IOException { String dataHeader = readDataHeaderString ( encoding ) ; if ( dataHeader != null ) { lastHeader = new FileUploadHeader ( dataHeader ) ; } else { lastHeader = null ; } return lastHeader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies bytes from this stream to some output until boundary is reached . Returns number of copied bytes . It will throw an exception for any irregular behaviour . [CODESPLIT] public int copyAll ( final OutputStream out ) throws IOException { int count = 0 ; while ( true ) { byte b = readByte ( ) ; if ( isBoundary ( b ) ) { break ; } out . write ( b ) ; count ++ ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies max or less number of bytes to output stream . Useful for determining if uploaded file is larger then expected . [CODESPLIT] public int copyMax ( final OutputStream out , final int maxBytes ) throws IOException { int count = 0 ; while ( true ) { byte b = readByte ( ) ; if ( isBoundary ( b ) ) { break ; } out . write ( b ) ; count ++ ; if ( count == maxBytes ) { return count ; } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses action class and method and creates { [CODESPLIT] public ActionDefinition parseActionDefinition ( final Class < ? > actionClass , final Method actionMethod ) { final ActionAnnotationValues annotationValues = detectActionAnnotationValues ( actionMethod ) ; final ActionConfig actionConfig = resolveActionConfig ( annotationValues ) ; final String [ ] packageActionNames = readPackageActionPath ( actionClass ) ; final String [ ] classActionNames = readClassActionPath ( actionClass ) ; final String [ ] methodActionNames = readMethodActionPath ( actionMethod . getName ( ) , annotationValues , actionConfig ) ; final String method = readMethodHttpMethod ( actionMethod ) ; final ActionNames actionNames = new ActionNames ( packageActionNames , classActionNames , methodActionNames , method ) ; final ActionNamingStrategy namingStrategy ; try { namingStrategy = ClassUtil . newInstance ( actionConfig . getNamingStrategy ( ) ) ; contextInjectorComponent . injectContext ( namingStrategy ) ; } catch ( Exception ex ) { throw new MadvocException ( ex ) ; } return namingStrategy . buildActionDef ( actionClass , actionMethod , actionNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses java action method annotation and returns its action runtime . [CODESPLIT] public ActionRuntime parse ( final Class < ? > actionClass , final Method actionMethod , ActionDefinition actionDefinition ) { final ActionAnnotationValues annotationValues = detectActionAnnotationValues ( actionMethod ) ; final ActionConfig actionConfig = resolveActionConfig ( annotationValues ) ; // interceptors ActionInterceptor [ ] actionInterceptors = parseActionInterceptors ( actionClass , actionMethod , actionConfig ) ; // filters ActionFilter [ ] actionFilters = parseActionFilters ( actionClass , actionMethod , actionConfig ) ; // build action definition when not provided if ( actionDefinition == null ) { actionDefinition = parseActionDefinition ( actionClass , actionMethod ) ; } detectAndRegisterAlias ( annotationValues , actionDefinition ) ; final boolean async = parseMethodAsyncFlag ( actionMethod ) ; final boolean auth = parseMethodAuthFlag ( actionMethod ) ; final Class < ? extends ActionResult > actionResult = parseActionResult ( actionMethod ) ; final Class < ? extends ActionResult > defaultActionResult = actionConfig . getActionResult ( ) ; return createActionRuntime ( null , actionClass , actionMethod , actionResult , defaultActionResult , actionFilters , actionInterceptors , actionDefinition , async , auth ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves action config . [CODESPLIT] protected ActionConfig resolveActionConfig ( final ActionAnnotationValues annotationValues ) { final Class < ? extends Annotation > annotationType ; if ( annotationValues == null ) { annotationType = Action . class ; } else { annotationType = annotationValues . annotationType ( ) ; } return actionConfigManager . lookup ( annotationType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects if alias is defined in annotation and registers it if so . [CODESPLIT] protected void detectAndRegisterAlias ( final ActionAnnotationValues annotationValues , final ActionDefinition actionDefinition ) { final String alias = parseMethodAlias ( annotationValues ) ; if ( alias != null ) { String aliasPath = StringUtil . cutToIndexOf ( actionDefinition . actionPath ( ) , StringPool . HASH ) ; actionsManager . registerPathAlias ( alias , aliasPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads class or method annotation for action interceptors . [CODESPLIT] protected Class < ? extends ActionInterceptor > [ ] readActionInterceptors ( final AnnotatedElement actionClassOrMethod ) { Class < ? extends ActionInterceptor > [ ] result = null ; InterceptedBy interceptedBy = actionClassOrMethod . getAnnotation ( InterceptedBy . class ) ; if ( interceptedBy != null ) { result = interceptedBy . value ( ) ; if ( result . length == 0 ) { result = null ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads class or method annotation for action filters . [CODESPLIT] protected Class < ? extends ActionFilter > [ ] readActionFilters ( final AnnotatedElement actionClassOrMethod ) { Class < ? extends ActionFilter > [ ] result = null ; FilteredBy filteredBy = actionClassOrMethod . getAnnotation ( FilteredBy . class ) ; if ( filteredBy != null ) { result = filteredBy . value ( ) ; if ( result . length == 0 ) { result = null ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads action path for package . If annotation is not set on package - level class package will be used for package action path part . [CODESPLIT] protected String [ ] readPackageActionPath ( final Class actionClass ) { Package actionPackage = actionClass . getPackage ( ) ; final String actionPackageName = actionPackage . getName ( ) ; // 1 - read annotations first String packageActionPathFromAnnotation ; mainloop : while ( true ) { MadvocAction madvocActionAnnotation = actionPackage . getAnnotation ( MadvocAction . class ) ; packageActionPathFromAnnotation = madvocActionAnnotation != null ? madvocActionAnnotation . value ( ) . trim ( ) : null ; if ( StringUtil . isEmpty ( packageActionPathFromAnnotation ) ) { packageActionPathFromAnnotation = null ; } if ( packageActionPathFromAnnotation == null ) { // next package String newPackage = actionPackage . getName ( ) ; actionPackage = null ; while ( actionPackage == null ) { final int ndx = newPackage . lastIndexOf ( ' ' ) ; if ( ndx == - 1 ) { // end of hierarchy, nothing found break mainloop ; } newPackage = newPackage . substring ( 0 , ndx ) ; actionPackage = Packages . of ( actionClass . getClassLoader ( ) , newPackage ) ; } } else { // annotation found, register root rootPackages . addRootPackage ( actionPackage . getName ( ) , packageActionPathFromAnnotation ) ; break ; } } // 2 - read root package String packagePath = rootPackages . findPackagePathForActionPackage ( actionPackageName ) ; if ( packagePath == null ) { return ArraysUtil . array ( null , null ) ; } return ArraysUtil . array ( StringUtil . stripChar ( packagePath , ' ' ) , StringUtil . surround ( packagePath , StringPool . SLASH ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads action path from class . If the class is annotated with { [CODESPLIT] protected String [ ] readClassActionPath ( final Class actionClass ) { // read class annotation MadvocAction madvocActionAnnotation = ( ( Class < ? > ) actionClass ) . getAnnotation ( MadvocAction . class ) ; String classActionPath = madvocActionAnnotation != null ? madvocActionAnnotation . value ( ) . trim ( ) : null ; if ( StringUtil . isEmpty ( classActionPath ) ) { classActionPath = null ; } String actionClassName = actionClass . getSimpleName ( ) ; actionClassName = StringUtil . uncapitalize ( actionClassName ) ; actionClassName = MadvocUtil . stripLastCamelWord ( actionClassName ) ; // removes 'Action' from the class name if ( classActionPath == null ) { classActionPath = actionClassName ; } return ArraysUtil . array ( actionClassName , classActionPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads action path from the action method . [CODESPLIT] protected String [ ] readMethodActionPath ( final String methodName , final ActionAnnotationValues annotationValues , final ActionConfig actionConfig ) { // read annotation String methodActionPath = annotationValues != null ? annotationValues . value ( ) : null ; if ( methodActionPath == null ) { methodActionPath = methodName ; } else { if ( methodActionPath . equals ( Action . NONE ) ) { return ArraysUtil . array ( null , null ) ; } } // check for defaults for ( String path : actionConfig . getActionMethodNames ( ) ) { if ( methodActionPath . equals ( path ) ) { methodActionPath = null ; break ; } } return ArraysUtil . array ( methodName , methodActionPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads method s alias value . [CODESPLIT] protected String parseMethodAlias ( final ActionAnnotationValues annotationValues ) { String alias = null ; if ( annotationValues != null ) { alias = annotationValues . alias ( ) ; } return alias ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads method s http method or { [CODESPLIT] private String readMethodHttpMethod ( final Method actionMethod ) { for ( Class < ? extends Annotation > methodAnnotation : METHOD_ANNOTATIONS ) { if ( actionMethod . getAnnotation ( methodAnnotation ) != null ) { return methodAnnotation . getSimpleName ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new instance of action runtime configuration . Initialize caches . [CODESPLIT] public ActionRuntime createActionRuntime ( final ActionHandler actionHandler , final Class actionClass , final Method actionClassMethod , final Class < ? extends ActionResult > actionResult , final Class < ? extends ActionResult > defaultActionResult , final ActionFilter [ ] filters , final ActionInterceptor [ ] interceptors , final ActionDefinition actionDefinition , final boolean async , final boolean auth ) { if ( actionHandler != null ) { return new ActionRuntime ( actionHandler , actionClass , actionClassMethod , filters , interceptors , actionDefinition , NoneActionResult . class , NoneActionResult . class , async , auth , null , null ) ; } final ScopeData scopeData = scopeDataInspector . inspectClassScopes ( actionClass ) ; // find ins and outs final Class [ ] paramTypes = actionClassMethod . getParameterTypes ( ) ; final MethodParam [ ] params = new MethodParam [ paramTypes . length ] ; final Annotation [ ] [ ] paramAnns = actionClassMethod . getParameterAnnotations ( ) ; String [ ] methodParamNames = null ; // for all elements: action and method arguments... for ( int ndx = 0 ; ndx < paramTypes . length ; ndx ++ ) { Class paramType = paramTypes [ ndx ] ; // lazy init to postpone bytecode usage, when method has no arguments if ( methodParamNames == null ) { methodParamNames = actionMethodParamNameResolver . resolveParamNames ( actionClassMethod ) ; } final String paramName = methodParamNames [ ndx ] ; final Annotation [ ] parameterAnnotations = paramAnns [ ndx ] ; final ScopeData paramsScopeData = scopeDataInspector . inspectMethodParameterScopes ( paramName , paramType , parameterAnnotations ) ; MapperFunction mapperFunction = null ; for ( final Annotation annotation : parameterAnnotations ) { if ( annotation instanceof Mapper ) { mapperFunction = MapperFunctionInstances . get ( ) . lookup ( ( ( Mapper ) annotation ) . value ( ) ) ; break ; } } params [ ndx ] = new MethodParam ( paramTypes [ ndx ] , paramName , scopeDataInspector . detectAnnotationType ( parameterAnnotations ) , paramsScopeData , mapperFunction ) ; } return new ActionRuntime ( null , actionClass , actionClassMethod , filters , interceptors , actionDefinition , actionResult , defaultActionResult , async , auth , scopeData , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Time get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getTime ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Time value , final int dbSqlType ) throws SQLException { st . setTime ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo move to BufferResponseWrapper ? [CODESPLIT] @ Override protected void preResponseCommit ( ) { long lastModified = lastModifiedData . getLastModified ( ) ; long ifModifiedSince = request . getDateHeader ( \"If-Modified-Since\" ) ; if ( lastModified > - 1 && ! response . containsHeader ( \"Last-Modified\" ) ) { if ( ifModifiedSince < ( lastModified / 1000 * 1000 ) ) { response . setDateHeader ( \"Last-Modified\" , lastModified ) ; } else { response . reset ( ) ; response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Boolean< / code > . [CODESPLIT] public Boolean toBoolean ( final Object value ) { final TypeConverter < Boolean > tc = TypeConverterManager . get ( ) . lookup ( Boolean . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Boolean< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Boolean toBoolean ( final Object value , final Boolean defaultValue ) { final Boolean result = toBoolean ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > boolean< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public boolean toBooleanValue ( final Object value , final boolean defaultValue ) { final Boolean result = toBoolean ( value ) ; if ( result == null ) { return defaultValue ; } return result . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Integer< / code > . [CODESPLIT] public Integer toInteger ( final Object value ) { final TypeConverter < Integer > tc = TypeConverterManager . get ( ) . lookup ( Integer . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Integer< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Integer toInteger ( final Object value , final Integer defaultValue ) { final Integer result = toInteger ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > int< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public int toIntValue ( final Object value , final int defaultValue ) { final Integer result = toInteger ( value ) ; if ( result == null ) { return defaultValue ; } return result . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Long< / code > . [CODESPLIT] public Long toLong ( final Object value ) { final TypeConverter < Long > tc = TypeConverterManager . get ( ) . lookup ( Long . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Long< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Long toLong ( final Object value , final Long defaultValue ) { final Long result = toLong ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > long< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public long toLongValue ( final Object value , final long defaultValue ) { final Long result = toLong ( value ) ; if ( result == null ) { return defaultValue ; } return result . longValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Float< / code > . [CODESPLIT] public Float toFloat ( final Object value ) { final TypeConverter < Float > tc = TypeConverterManager . get ( ) . lookup ( Float . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Float< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Float toFloat ( final Object value , final Float defaultValue ) { final Float result = toFloat ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > float< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public float toFloatValue ( final Object value , final float defaultValue ) { final Float result = toFloat ( value ) ; if ( result == null ) { return defaultValue ; } return result . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Double< / code > . [CODESPLIT] public Double toDouble ( final Object value ) { final TypeConverter < Double > tc = TypeConverterManager . get ( ) . lookup ( Double . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Double< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Double toDouble ( final Object value , final Double defaultValue ) { final Double result = toDouble ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > double< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public double toDoubleValue ( final Object value , final double defaultValue ) { final Double result = toDouble ( value ) ; if ( result == null ) { return defaultValue ; } return result . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Short< / code > . [CODESPLIT] public Short toShort ( final Object value ) { final TypeConverter < Short > tc = TypeConverterManager . get ( ) . lookup ( Short . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Short< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Short toShort ( final Object value , final Short defaultValue ) { final Short result = toShort ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > short< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public short toShortValue ( final Object value , final short defaultValue ) { final Short result = toShort ( value ) ; if ( result == null ) { return defaultValue ; } return result . shortValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Character< / code > . [CODESPLIT] public Character toCharacter ( final Object value ) { final TypeConverter < Character > tc = TypeConverterManager . get ( ) . lookup ( Character . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Character< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Character toCharacter ( final Object value , final Character defaultValue ) { final Character result = toCharacter ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > char< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public char toCharValue ( final Object value , final char defaultValue ) { final Character result = toCharacter ( value ) ; if ( result == null ) { return defaultValue ; } return result . charValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Byte< / code > . [CODESPLIT] public Byte toByte ( final Object value ) { final TypeConverter < Byte > tc = TypeConverterManager . get ( ) . lookup ( Byte . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Byte< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public Byte toByte ( final Object value , final Byte defaultValue ) { final Byte result = toByte ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > byte< / code > . Returns default value when conversion result is <code > null< / code > . [CODESPLIT] public byte toByteValue ( final Object value , final byte defaultValue ) { final Byte result = toByte ( value ) ; if ( result == null ) { return defaultValue ; } return result . byteValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > long [] < / code > . [CODESPLIT] public long [ ] toLongArray ( final Object value ) { final TypeConverter < long [ ] > tc = TypeConverterManager . get ( ) . lookup ( long [ ] . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > String [] < / code > . [CODESPLIT] public String [ ] toStringArray ( final Object value ) { final TypeConverter < String [ ] > tc = TypeConverterManager . get ( ) . lookup ( String [ ] . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > Class< / code > . [CODESPLIT] public Class toClass ( final Object value ) { final TypeConverter < Class > tc = TypeConverterManager . get ( ) . lookup ( Class . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > BigInteger< / code > . [CODESPLIT] public BigInteger toBigInteger ( final Object value ) { final TypeConverter < BigInteger > tc = TypeConverterManager . get ( ) . lookup ( BigInteger . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > BigInteger< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public BigInteger toBigInteger ( final Object value , final BigInteger defaultValue ) { final BigInteger result = toBigInteger ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > BigDecimal< / code > . [CODESPLIT] public BigDecimal toBigDecimal ( final Object value ) { final TypeConverter < BigDecimal > tc = TypeConverterManager . get ( ) . lookup ( BigDecimal . class ) ; return tc . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to <code > BigDecimal< / code > . Returns default value when conversion result is <code > null< / code > [CODESPLIT] public BigDecimal toBigDecimal ( final Object value , final BigDecimal defaultValue ) { final BigDecimal result = toBigDecimal ( value ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- configure [CODESPLIT] @ Override public void configure ( final Range annotation ) { this . min = annotation . min ( ) ; this . max = annotation . max ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures { [CODESPLIT] public void configure ( ) { long elapsed = System . currentTimeMillis ( ) ; final ClassScanner classScanner = new ClassScanner ( ) ; classScanner . detectEntriesMode ( true ) ; classScanner . scanDefaultClasspath ( ) ; classScannerConsumers . accept ( classScanner ) ; registerAsConsumer ( classScanner ) ; try { classScanner . start ( ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Scan classpath error\" , ex ) ; } elapsed = System . currentTimeMillis ( ) - elapsed ; log . info ( \"Petite configured in \" + elapsed + \" ms. Total beans: \" + container . beansCount ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a class consumer that registers only those annotated with { [CODESPLIT] public void registerAsConsumer ( final ClassScanner classScanner ) { classScanner . registerEntryConsumer ( classPathEntry -> { if ( ! classPathEntry . isTypeSignatureInUse ( PETITE_BEAN_ANNOTATION_BYTES ) ) { return ; } final Class < ? > beanClass ; try { beanClass = classPathEntry . loadClass ( ) ; } catch ( ClassNotFoundException cnfex ) { throw new PetiteException ( \"Unable to load class: \" + cnfex , cnfex ) ; } if ( beanClass == null ) { return ; } final PetiteBean petiteBean = beanClass . getAnnotation ( PetiteBean . class ) ; if ( petiteBean == null ) { return ; } container . registerPetiteBean ( beanClass , null , null , null , false , null ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies advice on given target class and returns proxy instance . [CODESPLIT] public static < T > T applyAdvice ( final Class < T > targetClass ) { Class adviceClass = cache . get ( targetClass ) ; if ( adviceClass == null ) { // advice not yet created adviceClass = PROXY_PROXETTA . proxy ( ) . setTarget ( targetClass ) . define ( ) ; cache . put ( targetClass , adviceClass ) ; } // create new advice instance and injects target instance to it try { Object advice = ClassUtil . newInstance ( adviceClass ) ; Field field = adviceClass . getField ( \"$___target$0\" ) ; field . set ( advice , targetClass ) ; return ( T ) advice ; } catch ( Exception ex ) { throw new ProxettaException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects target into proxy . [CODESPLIT] public static void injectTargetIntoProxy ( final Object proxy , final Object target ) { Class proxyClass = proxy . getClass ( ) ; try { Field field = proxyClass . getField ( \"$___target$0\" ) ; field . set ( proxy , target ) ; } catch ( Exception ex ) { throw new ProxettaException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an annotation of the field . [CODESPLIT] public AnnotationVisitor visitAnnotation ( final String descriptor , final boolean visible ) { if ( fv != null ) { return fv . visitAnnotation ( descriptor , visible ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves real name from JSON name . [CODESPLIT] public String resolveRealName ( final String jsonName ) { if ( jsonNames == null ) { return jsonName ; } int jsonIndex = ArraysUtil . indexOf ( jsonNames , jsonName ) ; if ( jsonIndex == - 1 ) { return jsonName ; } return realNames [ jsonIndex ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves JSON name from real name . [CODESPLIT] public String resolveJsonName ( final String realName ) { if ( realNames == null ) { return realName ; } int realIndex = ArraysUtil . indexOf ( realNames , realName ) ; if ( realIndex == - 1 ) { return realName ; } return jsonNames [ realIndex ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all includes for given type . Returns an empty array when no includes are defined . [CODESPLIT] public TypeData lookupTypeData ( final Class type ) { TypeData typeData = typeDataMap . get ( type ) ; if ( typeData == null ) { if ( serializationSubclassAware ) { typeData = findSubclassTypeData ( type ) ; } if ( typeData == null ) { typeData = scanClassForAnnotations ( type ) ; typeDataMap . put ( type , typeData ) ; } } return typeData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups type data and creates one if missing . [CODESPLIT] protected TypeData _lookupTypeData ( final Class type ) { TypeData typeData = typeDataMap . get ( type ) ; if ( typeData == null ) { typeData = scanClassForAnnotations ( type ) ; typeDataMap . put ( type , typeData ) ; } return typeData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds type data of first annotated superclass or interface . [CODESPLIT] protected TypeData findSubclassTypeData ( final Class type ) { final Class < ? extends Annotation > defaultAnnotation = jsonAnnotation ; if ( type . getAnnotation ( defaultAnnotation ) != null ) { // current type has annotation, don't find anything, let type data be created return null ; } ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; // lookup superclasses Class [ ] superClasses = cd . getAllSuperclasses ( ) ; for ( Class superClass : superClasses ) { if ( superClass . getAnnotation ( defaultAnnotation ) != null ) { // annotated subclass founded! return _lookupTypeData ( superClass ) ; } } Class [ ] interfaces = cd . getAllInterfaces ( ) ; for ( Class interfaze : interfaces ) { if ( interfaze . getAnnotation ( defaultAnnotation ) != null ) { // annotated subclass founded! return _lookupTypeData ( interfaze ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns different name of a property if set by annotation . [CODESPLIT] public String resolveJsonName ( final Class type , final String name ) { TypeData typeData = lookupTypeData ( type ) ; return typeData . resolveJsonName ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns real property name for given JSON property . [CODESPLIT] public String resolveRealName ( final Class type , final String jsonName ) { TypeData typeData = lookupTypeData ( type ) ; return typeData . resolveRealName ( jsonName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans class for annotations and returns { [CODESPLIT] private TypeData scanClassForAnnotations ( final Class type ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; PropertyDescriptor [ ] pds = cd . getAllPropertyDescriptors ( ) ; ArrayList < String > includedList = new ArrayList <> ( ) ; ArrayList < String > excludedList = new ArrayList <> ( ) ; ArrayList < String > jsonNames = new ArrayList <> ( ) ; ArrayList < String > realNames = new ArrayList <> ( ) ; AnnotationParser annotationParser = JSONAnnotationValues . parserFor ( jsonAnnotation ) ; for ( PropertyDescriptor pd : pds ) { JSONAnnotationValues data = null ; { MethodDescriptor md = pd . getReadMethodDescriptor ( ) ; if ( md != null ) { Method method = md . getMethod ( ) ; data = JSONAnnotationValues . of ( annotationParser , method ) ; } } if ( data == null ) { MethodDescriptor md = pd . getWriteMethodDescriptor ( ) ; if ( md != null ) { Method method = md . getMethod ( ) ; data = JSONAnnotationValues . of ( annotationParser , method ) ; } } if ( data == null ) { FieldDescriptor fd = pd . getFieldDescriptor ( ) ; if ( fd != null ) { Field field = fd . getField ( ) ; data = JSONAnnotationValues . of ( annotationParser , field ) ; } } if ( data != null ) { // annotation found String propertyName = pd . getName ( ) ; String newPropertyName = data . name ( ) ; if ( newPropertyName != null ) { realNames . add ( propertyName ) ; jsonNames . add ( newPropertyName ) ; propertyName = newPropertyName ; } if ( data . include ( ) ) { includedList . add ( propertyName ) ; } else { excludedList . add ( propertyName ) ; } } } String [ ] reals = null ; if ( ! realNames . isEmpty ( ) ) { reals = realNames . toArray ( new String [ 0 ] ) ; } String [ ] jsons = null ; if ( ! jsonNames . isEmpty ( ) ) { jsons = jsonNames . toArray ( new String [ 0 ] ) ; } // type JSONAnnotationValues data = JSONAnnotationValues . of ( annotationParser , type ) ; return new TypeData ( includedList , excludedList , data != null && data . strict ( ) , jsons , reals ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- process [CODESPLIT] protected boolean matchFileExtension ( ) throws IOException { String fileNameExtension = FileNameUtil . getExtension ( getHeader ( ) . getFileName ( ) ) ; for ( String fileExtension : fileExtensions ) { if ( fileNameExtension . equalsIgnoreCase ( fileExtension ) ) { if ( ! allowFileExtensions ) { // extension matched and it is not allowed if ( breakOnError ) { throw new IOException ( \"Upload filename extension not allowed: \" + fileNameExtension ) ; } size = input . skipToBoundary ( ) ; return false ; } return true ; // extension matched and it is allowed. } } if ( allowFileExtensions ) { // extension is not one of the allowed ones. if ( breakOnError ) { throw new IOException ( \"Upload filename extension not allowed: \" + fileNameExtension ) ; } size = input . skipToBoundary ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the content of file upload item . [CODESPLIT] @ Override public byte [ ] getFileContent ( ) throws IOException { if ( data != null ) { return data ; } if ( tempFile != null ) { return FileUtil . readBytes ( tempFile ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the BootstrapMethods bootstrap_methods array binary content and add them as entries of the SymbolTable . [CODESPLIT] private void copyBootstrapMethods ( final ClassReader classReader , final char [ ] charBuffer ) { // Find attributOffset of the 'bootstrap_methods' array. byte [ ] inputBytes = classReader . b ; int currentAttributeOffset = classReader . getFirstAttributeOffset ( ) ; for ( int i = classReader . readUnsignedShort ( currentAttributeOffset - 2 ) ; i > 0 ; -- i ) { String attributeName = classReader . readUTF8 ( currentAttributeOffset , charBuffer ) ; if ( Constants . BOOTSTRAP_METHODS . equals ( attributeName ) ) { bootstrapMethodCount = classReader . readUnsignedShort ( currentAttributeOffset + 6 ) ; break ; } currentAttributeOffset += 6 + classReader . readInt ( currentAttributeOffset + 2 ) ; } if ( bootstrapMethodCount > 0 ) { // Compute the offset and the length of the BootstrapMethods 'bootstrap_methods' array. int bootstrapMethodsOffset = currentAttributeOffset + 8 ; int bootstrapMethodsLength = classReader . readInt ( currentAttributeOffset + 2 ) - 2 ; bootstrapMethods = new ByteVector ( bootstrapMethodsLength ) ; bootstrapMethods . putByteArray ( inputBytes , bootstrapMethodsOffset , bootstrapMethodsLength ) ; // Add each bootstrap method in the symbol table entries. int currentOffset = bootstrapMethodsOffset ; for ( int i = 0 ; i < bootstrapMethodCount ; i ++ ) { int offset = currentOffset - bootstrapMethodsOffset ; int bootstrapMethodRef = classReader . readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; int numBootstrapArguments = classReader . readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; int hashCode = classReader . readConst ( bootstrapMethodRef , charBuffer ) . hashCode ( ) ; while ( numBootstrapArguments -- > 0 ) { int bootstrapArgument = classReader . readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; hashCode ^= classReader . readConst ( bootstrapArgument , charBuffer ) . hashCode ( ) ; } add ( new Entry ( i , Symbol . BOOTSTRAP_METHOD_TAG , offset , hashCode & 0x7FFFFFFF ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the major version and the name of the class to which this symbol table belongs . Also adds the class name to the constant pool . [CODESPLIT] int setMajorVersionAndClassName ( final int majorVersion , final String className ) { this . majorVersion = majorVersion ; this . className = className ; return addConstantClass ( className ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts this symbol table s constant_pool array in the given ByteVector preceded by the constant_pool_count value . [CODESPLIT] void putConstantPool ( final ByteVector output ) { output . putShort ( constantPoolCount ) . putByteArray ( constantPool . data , 0 , constantPool . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts this symbol table s BootstrapMethods attribute in the given ByteVector . This includes the 6 attribute header bytes and the num_bootstrap_methods value . [CODESPLIT] void putBootstrapMethods ( final ByteVector output ) { if ( bootstrapMethods != null ) { output . putShort ( addConstantUtf8 ( Constants . BOOTSTRAP_METHODS ) ) . putInt ( bootstrapMethods . length + 2 ) . putShort ( bootstrapMethodCount ) . putByteArray ( bootstrapMethods . data , 0 , bootstrapMethods . length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the given entry in the { @link #entries } hash set . This method does <i > not< / i > check whether { @link #entries } already contains a similar entry or not . { @link #entries } is resized if necessary to avoid hash collisions ( multiple entries needing to be stored at the same { @link #entries } array index ) as much as possible with reasonable memory usage . [CODESPLIT] private Entry put ( final Entry entry ) { if ( entryCount > ( entries . length * 3 ) / 4 ) { int currentCapacity = entries . length ; int newCapacity = currentCapacity * 2 + 1 ; Entry [ ] newEntries = new Entry [ newCapacity ] ; for ( int i = currentCapacity - 1 ; i >= 0 ; -- i ) { Entry currentEntry = entries [ i ] ; while ( currentEntry != null ) { int newCurrentEntryIndex = currentEntry . hashCode % newCapacity ; Entry nextEntry = currentEntry . next ; currentEntry . next = newEntries [ newCurrentEntryIndex ] ; newEntries [ newCurrentEntryIndex ] = currentEntry ; currentEntry = nextEntry ; } } entries = newEntries ; } entryCount ++ ; int index = entry . hashCode % entries . length ; entry . next = entries [ index ] ; return entries [ index ] = entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given entry in the { @link #entries } hash set . This method does <i > not< / i > check whether { @link #entries } already contains a similar entry or not and does <i > not< / i > resize { @link #entries } if necessary . [CODESPLIT] private void add ( final Entry entry ) { entryCount ++ ; int index = entry . hashCode % entries . length ; entry . next = entries [ index ] ; entries [ index ] = entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Fieldref_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] Symbol addConstantFieldref ( final String owner , final String name , final String descriptor ) { return addConstantMemberReference ( Symbol . CONSTANT_FIELDREF_TAG , owner , name , descriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] Symbol addConstantMethodref ( final String owner , final String name , final String descriptor , final boolean isInterface ) { int tag = isInterface ? Symbol . CONSTANT_INTERFACE_METHODREF_TAG : Symbol . CONSTANT_METHODREF_TAG ; return addConstantMemberReference ( tag , owner , name , descriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Fieldref_info CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] private Entry addConstantMemberReference ( final int tag , final String owner , final String name , final String descriptor ) { int hashCode = hash ( tag , owner , name , descriptor ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == tag && entry . hashCode == hashCode && entry . owner . equals ( owner ) && entry . name . equals ( name ) && entry . value . equals ( descriptor ) ) { return entry ; } entry = entry . next ; } constantPool . put122 ( tag , addConstantClass ( owner ) . index , addConstantNameAndType ( name , descriptor ) ) ; return put ( new Entry ( constantPoolCount ++ , tag , owner , name , descriptor , 0 , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_Fieldref_info CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantMemberReference ( final int index , final int tag , final String owner , final String name , final String descriptor ) { add ( new Entry ( index , tag , owner , name , descriptor , 0 , hash ( tag , owner , name , descriptor ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] private Symbol addConstantIntegerOrFloat ( final int tag , final int value ) { int hashCode = hash ( tag , value ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == tag && entry . hashCode == hashCode && entry . data == value ) { return entry ; } entry = entry . next ; } constantPool . putByte ( tag ) . putInt ( value ) ; return put ( new Entry ( constantPoolCount ++ , tag , value , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantIntegerOrFloat ( final int index , final int tag , final int value ) { add ( new Entry ( index , tag , value , hash ( tag , value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] private Symbol addConstantLongOrDouble ( final int tag , final long value ) { int hashCode = hash ( tag , value ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == tag && entry . hashCode == hashCode && entry . data == value ) { return entry ; } entry = entry . next ; } int index = constantPoolCount ; constantPool . putByte ( tag ) . putLong ( value ) ; constantPoolCount += 2 ; return put ( new Entry ( index , tag , value , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantLongOrDouble ( final int index , final int tag , final long value ) { add ( new Entry ( index , tag , value , hash ( tag , value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_NameAndType_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] int addConstantNameAndType ( final String name , final String descriptor ) { final int tag = Symbol . CONSTANT_NAME_AND_TYPE_TAG ; int hashCode = hash ( tag , name , descriptor ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == tag && entry . hashCode == hashCode && entry . name . equals ( name ) && entry . value . equals ( descriptor ) ) { return entry . index ; } entry = entry . next ; } constantPool . put122 ( tag , addConstantUtf8 ( name ) , addConstantUtf8 ( descriptor ) ) ; return put ( new Entry ( constantPoolCount ++ , tag , name , descriptor , hashCode ) ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_NameAndType_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantNameAndType ( final int index , final String name , final String descriptor ) { final int tag = Symbol . CONSTANT_NAME_AND_TYPE_TAG ; add ( new Entry ( index , tag , name , descriptor , hash ( tag , name , descriptor ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Utf8_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] int addConstantUtf8 ( final String value ) { int hashCode = hash ( Symbol . CONSTANT_UTF8_TAG , value ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == Symbol . CONSTANT_UTF8_TAG && entry . hashCode == hashCode && entry . value . equals ( value ) ) { return entry . index ; } entry = entry . next ; } constantPool . putByte ( Symbol . CONSTANT_UTF8_TAG ) . putUTF8 ( value ) ; return put ( new Entry ( constantPoolCount ++ , Symbol . CONSTANT_UTF8_TAG , value , hashCode ) ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_String_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantUtf8 ( final int index , final String value ) { add ( new Entry ( index , Symbol . CONSTANT_UTF8_TAG , value , hash ( Symbol . CONSTANT_UTF8_TAG , value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_MethodHandle_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] Symbol addConstantMethodHandle ( final int referenceKind , final String owner , final String name , final String descriptor , final boolean isInterface ) { final int tag = Symbol . CONSTANT_METHOD_HANDLE_TAG ; // Note that we don't need to include isInterface in the hash computation, because it is // redundant with owner (we can't have the same owner with different isInterface values). int hashCode = hash ( tag , owner , name , descriptor , referenceKind ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == tag && entry . hashCode == hashCode && entry . data == referenceKind && entry . owner . equals ( owner ) && entry . name . equals ( name ) && entry . value . equals ( descriptor ) ) { return entry ; } entry = entry . next ; } if ( referenceKind <= Opcodes . H_PUTSTATIC ) { constantPool . put112 ( tag , referenceKind , addConstantFieldref ( owner , name , descriptor ) . index ) ; } else { constantPool . put112 ( tag , referenceKind , addConstantMethodref ( owner , name , descriptor , isInterface ) . index ) ; } return put ( new Entry ( constantPoolCount ++ , tag , owner , name , descriptor , referenceKind , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_MethodHandle_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantMethodHandle ( final int index , final int referenceKind , final String owner , final String name , final String descriptor ) { final int tag = Symbol . CONSTANT_METHOD_HANDLE_TAG ; int hashCode = hash ( tag , owner , name , descriptor , referenceKind ) ; add ( new Entry ( index , tag , owner , name , descriptor , referenceKind , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Dynamic_info to the constant pool of this symbol table . Also adds the related bootstrap method to the BootstrapMethods of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] Symbol addConstantDynamic ( final String name , final String descriptor , final Handle bootstrapMethodHandle , final Object ... bootstrapMethodArguments ) { Symbol bootstrapMethod = addBootstrapMethod ( bootstrapMethodHandle , bootstrapMethodArguments ) ; return addConstantDynamicOrInvokeDynamicReference ( Symbol . CONSTANT_DYNAMIC_TAG , name , descriptor , bootstrapMethod . index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_InvokeDynamic_info to the constant pool of this symbol table . Also adds the related bootstrap method to the BootstrapMethods of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] Symbol addConstantInvokeDynamic ( final String name , final String descriptor , final Handle bootstrapMethodHandle , final Object ... bootstrapMethodArguments ) { Symbol bootstrapMethod = addBootstrapMethod ( bootstrapMethodHandle , bootstrapMethodArguments ) ; return addConstantDynamicOrInvokeDynamicReference ( Symbol . CONSTANT_INVOKE_DYNAMIC_TAG , name , descriptor , bootstrapMethod . index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Dynamic or a CONSTANT_InvokeDynamic_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] private Symbol addConstantDynamicOrInvokeDynamicReference ( final int tag , final String name , final String descriptor , final int bootstrapMethodIndex ) { int hashCode = hash ( tag , name , descriptor , bootstrapMethodIndex ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == tag && entry . hashCode == hashCode && entry . data == bootstrapMethodIndex && entry . name . equals ( name ) && entry . value . equals ( descriptor ) ) { return entry ; } entry = entry . next ; } constantPool . put122 ( tag , bootstrapMethodIndex , addConstantNameAndType ( name , descriptor ) ) ; return put ( new Entry ( constantPoolCount ++ , tag , null , name , descriptor , bootstrapMethodIndex , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_Dynamic_info or CONSTANT_InvokeDynamic_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantDynamicOrInvokeDynamicReference ( final int tag , final int index , final String name , final String descriptor , final int bootstrapMethodIndex ) { int hashCode = hash ( tag , name , descriptor , bootstrapMethodIndex ) ; add ( new Entry ( index , tag , null , name , descriptor , bootstrapMethodIndex , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CONSTANT_Class_info CONSTANT_String_info CONSTANT_MethodType_info CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table . Does nothing if the constant pool already contains a similar item . [CODESPLIT] private Symbol addConstantUtf8Reference ( final int tag , final String value ) { int hashCode = hash ( tag , value ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == tag && entry . hashCode == hashCode && entry . value . equals ( value ) ) { return entry ; } entry = entry . next ; } constantPool . put12 ( tag , addConstantUtf8 ( value ) ) ; return put ( new Entry ( constantPoolCount ++ , tag , value , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CONSTANT_Class_info CONSTANT_String_info CONSTANT_MethodType_info CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table . [CODESPLIT] private void addConstantUtf8Reference ( final int index , final int tag , final String value ) { add ( new Entry ( index , tag , value , hash ( tag , value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a bootstrap method to the BootstrapMethods attribute of this symbol table . Does nothing if the BootstrapMethods already contains a similar bootstrap method . [CODESPLIT] Symbol addBootstrapMethod ( final Handle bootstrapMethodHandle , final Object ... bootstrapMethodArguments ) { ByteVector bootstrapMethodsAttribute = bootstrapMethods ; if ( bootstrapMethodsAttribute == null ) { bootstrapMethodsAttribute = bootstrapMethods = new ByteVector ( ) ; } // The bootstrap method arguments can be Constant_Dynamic values, which reference other // bootstrap methods. We must therefore add the bootstrap method arguments to the constant pool // and BootstrapMethods attribute first, so that the BootstrapMethods attribute is not modified // while adding the given bootstrap method to it, in the rest of this method. for ( Object bootstrapMethodArgument : bootstrapMethodArguments ) { addConstant ( bootstrapMethodArgument ) ; } // Write the bootstrap method in the BootstrapMethods table. This is necessary to be able to // compare it with existing ones, and will be reverted below if there is already a similar // bootstrap method. int bootstrapMethodOffset = bootstrapMethodsAttribute . length ; bootstrapMethodsAttribute . putShort ( addConstantMethodHandle ( bootstrapMethodHandle . getTag ( ) , bootstrapMethodHandle . getOwner ( ) , bootstrapMethodHandle . getName ( ) , bootstrapMethodHandle . getDesc ( ) , bootstrapMethodHandle . isInterface ( ) ) . index ) ; int numBootstrapArguments = bootstrapMethodArguments . length ; bootstrapMethodsAttribute . putShort ( numBootstrapArguments ) ; for ( Object bootstrapMethodArgument : bootstrapMethodArguments ) { bootstrapMethodsAttribute . putShort ( addConstant ( bootstrapMethodArgument ) . index ) ; } // Compute the length and the hash code of the bootstrap method. int bootstrapMethodlength = bootstrapMethodsAttribute . length - bootstrapMethodOffset ; int hashCode = bootstrapMethodHandle . hashCode ( ) ; for ( Object bootstrapMethodArgument : bootstrapMethodArguments ) { hashCode ^= bootstrapMethodArgument . hashCode ( ) ; } hashCode &= 0x7FFFFFFF ; // Add the bootstrap method to the symbol table or revert the above changes. return addBootstrapMethod ( bootstrapMethodOffset , bootstrapMethodlength , hashCode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a bootstrap method to the BootstrapMethods attribute of this symbol table . Does nothing if the BootstrapMethods already contains a similar bootstrap method ( more precisely reverts the content of { @link #bootstrapMethods } to remove the last duplicate bootstrap method ) . [CODESPLIT] private Symbol addBootstrapMethod ( final int offset , final int length , final int hashCode ) { final byte [ ] bootstrapMethodsData = bootstrapMethods . data ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == Symbol . BOOTSTRAP_METHOD_TAG && entry . hashCode == hashCode ) { int otherOffset = ( int ) entry . data ; boolean isSameBootstrapMethod = true ; for ( int i = 0 ; i < length ; ++ i ) { if ( bootstrapMethodsData [ offset + i ] != bootstrapMethodsData [ otherOffset + i ] ) { isSameBootstrapMethod = false ; break ; } } if ( isSameBootstrapMethod ) { bootstrapMethods . length = offset ; // Revert to old position. return entry ; } } entry = entry . next ; } return put ( new Entry ( bootstrapMethodCount ++ , Symbol . BOOTSTRAP_METHOD_TAG , offset , hashCode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a merged type in the type table of this symbol table . Does nothing if the type table already contains a similar type . [CODESPLIT] int addMergedType ( final int typeTableIndex1 , final int typeTableIndex2 ) { // TODO sort the arguments? The merge result should be independent of their order. long data = typeTableIndex1 | ( ( ( long ) typeTableIndex2 ) << 32 ) ; int hashCode = hash ( Symbol . MERGED_TYPE_TAG , typeTableIndex1 + typeTableIndex2 ) ; Entry entry = get ( hashCode ) ; while ( entry != null ) { if ( entry . tag == Symbol . MERGED_TYPE_TAG && entry . hashCode == hashCode && entry . data == data ) { return entry . info ; } entry = entry . next ; } String type1 = typeTable [ typeTableIndex1 ] . value ; String type2 = typeTable [ typeTableIndex2 ] . value ; int commonSuperTypeIndex = addType ( classWriter . getCommonSuperClass ( type1 , type2 ) ) ; put ( new Entry ( typeCount , Symbol . MERGED_TYPE_TAG , data , hashCode ) ) . info = commonSuperTypeIndex ; return commonSuperTypeIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given type Symbol to { @link #typeTable } . [CODESPLIT] private int addTypeInternal ( final Entry entry ) { if ( typeTable == null ) { typeTable = new Entry [ 16 ] ; } if ( typeCount == typeTable . length ) { Entry [ ] newTypeTable = new Entry [ 2 * typeTable . length ] ; System . arraycopy ( typeTable , 0 , newTypeTable , 0 , typeTable . length ) ; typeTable = newTypeTable ; } typeTable [ typeCount ++ ] = entry ; return put ( entry ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected float [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final float [ ] target = new float [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Float > floatArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final float convertedValue = convertType ( element ) ; floatArrayList . add ( Float . valueOf ( convertedValue ) ) ; } final float [ ] array = new float [ floatArrayList . size ( ) ] ; for ( int i = 0 ; i < floatArrayList . size ( ) ; i ++ ) { final Float f = floatArrayList . get ( i ) ; array [ i ] = f . floatValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates hash value of the input string . [CODESPLIT] private int hash ( final String name ) { int h = 0 ; for ( int i = name . length ( ) - 1 ; i >= 0 ; i -- ) { char c = name . charAt ( i ) ; if ( ! caseSensitive ) { if ( c >= ' ' && c <= ' ' ) { c += 32 ; } } h = 31 * h + c ; } if ( h > 0 ) { return h ; } if ( h == Integer . MIN_VALUE ) { return Integer . MAX_VALUE ; } return - h ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if two names are the same . [CODESPLIT] private boolean eq ( final String name1 , final String name2 ) { int nameLen = name1 . length ( ) ; if ( nameLen != name2 . length ( ) ) { return false ; } for ( int i = nameLen - 1 ; i >= 0 ; i -- ) { char c1 = name1 . charAt ( i ) ; char c2 = name2 . charAt ( i ) ; if ( c1 != c2 ) { if ( caseSensitive ) { return false ; } if ( c1 >= ' ' && c1 <= ' ' ) { c1 += 32 ; } if ( c2 >= ' ' && c2 <= ' ' ) { c2 += 32 ; } if ( c1 != c2 ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the map . [CODESPLIT] public HttpMultiMap < V > clear ( ) { for ( int i = 0 ; i < entries . length ; i ++ ) { entries [ i ] = null ; } head . before = head . after = head ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- set / add [CODESPLIT] private HttpMultiMap < V > _set ( final Iterable < Map . Entry < String , V > > map ) { clear ( ) ; for ( Map . Entry < String , V > entry : map ) { add ( entry . getKey ( ) , entry . getValue ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- remove [CODESPLIT] public HttpMultiMap < V > remove ( final String name ) { int h = hash ( name ) ; int i = index ( h ) ; _remove ( h , i , name ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first value from the map associated with the name . Returns <code > null< / code > if name does not exist or if associated value is <code > null< / code > . [CODESPLIT] public V get ( final String name ) { Map . Entry < String , V > entry = getEntry ( name ) ; if ( entry == null ) { return null ; } return entry . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns first entry for given name . Returns <code > null< / code > if entry does not exist . [CODESPLIT] public Map . Entry < String , V > getEntry ( final String name ) { int h = hash ( name ) ; int i = index ( h ) ; MapEntry < V > e = entries [ i ] ; while ( e != null ) { if ( e . hash == h && eq ( name , e . key ) ) { return e ; } e = e . next ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all values associated with the name . [CODESPLIT] public List < V > getAll ( final String name ) { LinkedList < V > values = new LinkedList <> ( ) ; int h = hash ( name ) ; int i = index ( h ) ; MapEntry < V > e = entries [ i ] ; while ( e != null ) { if ( e . hash == h && eq ( name , e . key ) ) { values . addFirst ( e . getValue ( ) ) ; } e = e . next ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns iterator of all entries . [CODESPLIT] @ Override public Iterator < Map . Entry < String , V > > iterator ( ) { final MapEntry [ ] e = { head . after } ; return new Iterator < Map . Entry < String , V > > ( ) { @ Override public boolean hasNext ( ) { return e [ 0 ] != head ; } @ Override @ SuppressWarnings ( \"unchecked\" ) public Map . Entry < String , V > next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( \"No next() entry in the iteration\" ) ; } MapEntry < V > next = e [ 0 ] ; e [ 0 ] = e [ 0 ] . after ; return next ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the entries of this map . Case sensitivity does not influence the returned list it always contains all of the values . [CODESPLIT] public List < Map . Entry < String , V > > entries ( ) { List < Map . Entry < String , V > > all = new LinkedList <> ( ) ; MapEntry < V > e = head . after ; while ( e != head ) { all . add ( e ) ; e = e . after ; } return all ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grows the buffer . [CODESPLIT] private void grow ( final int minCapacity ) { final int oldCapacity = buffer . length ; int newCapacity = oldCapacity << 1 ; if ( newCapacity - minCapacity < 0 ) { // special case, min capacity is larger then a grow newCapacity = minCapacity + 512 ; } buffer = Arrays . copyOf ( buffer , newCapacity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends single { [CODESPLIT] @ Override public FastCharBuffer append ( final char element ) { if ( offset - buffer . length >= 0 ) { grow ( offset ) ; } buffer [ offset ++ ] = element ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastCharBuffer append ( final FastCharBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends character sequence to buffer . [CODESPLIT] @ Override public FastCharBuffer append ( final CharSequence csq , final int start , final int end ) { for ( int i = start ; i < end ; i ++ ) { append ( csq . charAt ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies target method annotations . [CODESPLIT] @ Override public AnnotationVisitor visitAnnotation ( final String desc , final boolean visible ) { AnnotationVisitor destAnn = methodVisitor . visitAnnotation ( desc , visible ) ; // [A4] return new AnnotationVisitorAdapter ( destAnn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finally builds proxy methods if applied to current method . [CODESPLIT] @ Override public void visitEnd ( ) { createFirstChainDelegate_Continue ( tmd ) ; for ( int p = 0 ; p < tmd . proxyData . length ; p ++ ) { tmd . selectCurrentProxy ( p ) ; createProxyMethod ( tmd ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts creation of first chain delegate . [CODESPLIT] protected void createFirstChainDelegate_Start ( ) { // check invalid access flags int access = msign . getAccessFlags ( ) ; if ( ! wd . allowFinalMethods ) { if ( ( access & AsmUtil . ACC_FINAL ) != 0 ) { // detect final throw new ProxettaException ( \"Unable to create proxy for final method: \" + msign + \". Remove final modifier or change the pointcut definition.\" ) ; } } // create proxy methods tmd = new TargetMethodData ( msign , aspectList ) ; access &= ~ ACC_NATIVE ; access &= ~ ACC_ABSTRACT ; methodVisitor = wd . dest . visitMethod ( access , tmd . msign . getMethodName ( ) , tmd . msign . getDescription ( ) , tmd . msign . getAsmMethodSignature ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Continues the creation of the very first method in calling chain that simply delegates invocation to the first proxy method . This method mirrors the target method . [CODESPLIT] protected void createFirstChainDelegate_Continue ( final TargetMethodData tmd ) { methodVisitor . visitCode ( ) ; if ( tmd . msign . isStatic ) { loadStaticMethodArguments ( methodVisitor , tmd . msign ) ; methodVisitor . visitMethodInsn ( INVOKESTATIC , wd . thisReference , tmd . firstMethodName ( ) , tmd . msign . getDescription ( ) , false ) ; } else { loadSpecialMethodArguments ( methodVisitor , tmd . msign ) ; methodVisitor . visitMethodInsn ( INVOKESPECIAL , wd . thisReference , tmd . firstMethodName ( ) , tmd . msign . getDescription ( ) , false ) ; } visitReturn ( methodVisitor , tmd . msign , false ) ; methodVisitor . visitMaxs ( 0 , 0 ) ; methodVisitor . visitEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates proxy methods over target method For each matched proxy new proxy method is created by taking advice bytecode and replaces usages of { [CODESPLIT] public void createProxyMethod ( final TargetMethodData td ) { final ProxyAspectData aspectData = td . getProxyData ( ) ; int access = td . msign . getAccessFlags ( ) ; access &= ~ ACC_NATIVE ; access &= ~ ACC_ABSTRACT ; access = ProxettaAsmUtil . makePrivateFinalAccess ( access ) ; final MethodVisitor mv = wd . dest . visitMethod ( access , td . methodName ( ) , td . msign . getDescription ( ) , null , null ) ; mv . visitCode ( ) ; //*** VISIT ADVICE - called for each aspect and each method aspectData . getAdviceClassReader ( ) . accept ( new EmptyClassVisitor ( ) { @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { if ( ! name . equals ( ProxettaNames . executeMethodName ) ) { return null ; } return new HistoryMethodAdapter ( mv ) { @ Override public void visitFieldInsn ( final int opcode , String owner , String name , final String desc ) { if ( owner . equals ( aspectData . adviceReference ) ) { owner = wd . thisReference ; // [F5] name = adviceFieldName ( name , aspectData . aspectIndex ) ; } super . visitFieldInsn ( opcode , owner , name , desc ) ; } @ Override public void visitVarInsn ( final int opcode , int var ) { var += ( var == 0 ? 0 : td . msign . getAllArgumentsSize ( ) ) ; if ( proxyInfoRequested ) { proxyInfoRequested = false ; if ( opcode == ASTORE ) { ProxyTargetReplacement . info ( mv , td . msign , var ) ; } } super . visitVarInsn ( opcode , var ) ; // [F1] } @ Override public void visitIincInsn ( int var , final int increment ) { var += ( var == 0 ? 0 : td . msign . getAllArgumentsSize ( ) ) ; super . visitIincInsn ( var , increment ) ; // [F1] } @ Override public void visitInsn ( final int opcode ) { if ( opcode == ARETURN ) { visitReturn ( mv , td . msign , true ) ; return ; } if ( traceNext ) { if ( ( opcode == POP ) || ( opcode == POP2 ) ) { // [F3] - invoke invoked without assignment return ; } } super . visitInsn ( opcode ) ; } @ SuppressWarnings ( { \"ParameterNameDiffersFromOverriddenParameter\" } ) @ Override public void visitMethodInsn ( final int opcode , String string , String mname , final String mdesc , final boolean isInterface ) { if ( ( opcode == INVOKEVIRTUAL ) || ( opcode == INVOKEINTERFACE ) || ( opcode == INVOKESPECIAL ) ) { if ( string . equals ( aspectData . adviceReference ) ) { string = wd . thisReference ; mname = adviceMethodName ( mname , aspectData . aspectIndex ) ; } } else if ( opcode == INVOKESTATIC ) { if ( string . equals ( aspectData . adviceReference ) ) { string = wd . thisReference ; mname = adviceMethodName ( mname , aspectData . aspectIndex ) ; } else if ( string . endsWith ( ' ' + TARGET_CLASS_NAME ) ) { if ( isInvokeMethod ( mname , mdesc ) ) { // [R7] if ( td . isLastMethodInChain ( ) ) { // last proxy method just calls super target method if ( ! wd . isWrapper ( ) ) { // PROXY loadSpecialMethodArguments ( mv , td . msign ) ; mv . visitMethodInsn ( INVOKESPECIAL , wd . superReference , td . msign . getMethodName ( ) , td . msign . getDescription ( ) , isInterface ) ; } else { // WRAPPER mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitFieldInsn ( GETFIELD , wd . thisReference , wd . wrapperRef , wd . wrapperType ) ; loadVirtualMethodArguments ( mv , td . msign ) ; if ( wd . wrapInterface ) { mv . visitMethodInsn ( INVOKEINTERFACE , wd . wrapperType . substring ( 1 , wd . wrapperType . length ( ) - 1 ) , td . msign . getMethodName ( ) , td . msign . getDescription ( ) , true ) ; } else { mv . visitMethodInsn ( INVOKEVIRTUAL , wd . wrapperType . substring ( 1 , wd . wrapperType . length ( ) - 1 ) , td . msign . getMethodName ( ) , td . msign . getDescription ( ) , isInterface ) ; } } prepareReturnValue ( mv , td . msign , aspectData . maxLocalVarOffset ) ; // [F4] traceNext = true ; } else { // calls next proxy method loadSpecialMethodArguments ( mv , td . msign ) ; mv . visitMethodInsn ( INVOKESPECIAL , wd . thisReference , td . nextMethodName ( ) , td . msign . getDescription ( ) , isInterface ) ; visitReturn ( mv , td . msign , false ) ; } return ; } if ( isArgumentsCountMethod ( mname , mdesc ) ) { // [R2] ProxyTargetReplacement . argumentsCount ( mv , td . msign ) ; return ; } if ( isArgumentTypeMethod ( mname , mdesc ) ) { // [R3] int argIndex = this . getArgumentIndex ( ) ; ProxyTargetReplacement . argumentType ( mv , td . msign , argIndex ) ; return ; } if ( isArgumentMethod ( mname , mdesc ) ) { // [R4] int argIndex = this . getArgumentIndex ( ) ; ProxyTargetReplacement . argument ( mv , td . msign , argIndex ) ; return ; } if ( isSetArgumentMethod ( mname , mdesc ) ) { // [R5] int argIndex = this . getArgumentIndex ( ) ; checkArgumentIndex ( td . msign , argIndex ) ; mv . visitInsn ( POP ) ; storeMethodArgumentFromObject ( mv , td . msign , argIndex ) ; return ; } if ( isCreateArgumentsArrayMethod ( mname , mdesc ) ) { // [R6] ProxyTargetReplacement . createArgumentsArray ( mv , td . msign ) ; return ; } if ( isCreateArgumentsClassArrayMethod ( mname , mdesc ) ) { // [R11] ProxyTargetReplacement . createArgumentsClassArray ( mv , td . msign ) ; return ; } if ( isTargetMethod ( mname , mdesc ) ) { // [R9.1] mv . visitVarInsn ( ALOAD , 0 ) ; return ; } if ( isTargetClassMethod ( mname , mdesc ) ) { // [R9] ProxyTargetReplacement . targetClass ( mv , td . msign ) ; //ProxyTargetReplacement.targetClass(mv, wd.superReference); return ; } if ( isTargetMethodNameMethod ( mname , mdesc ) ) { // [R10] ProxyTargetReplacement . targetMethodName ( mv , td . msign ) ; return ; } if ( isTargetMethodSignatureMethod ( mname , mdesc ) ) { ProxyTargetReplacement . targetMethodSignature ( mv , td . msign ) ; return ; } if ( isTargetMethodDescriptionMethod ( mname , mdesc ) ) { ProxyTargetReplacement . targetMethodDescription ( mv , td . msign ) ; return ; } if ( isInfoMethod ( mname , mdesc ) ) { // we are NOT replacing info() here! First, we need to figure out // what is the operand for the very next ASTORE instructions // since we need to create an object and store it in this // register - and reuse it, in replacement code. //ProxyTargetReplacement.info(mv, td.msign); proxyInfoRequested = true ; return ; } if ( isReturnTypeMethod ( mname , mdesc ) ) { // [R11] ProxyTargetReplacement . returnType ( mv , td . msign ) ; return ; } if ( isReturnValueMethod ( mname , mdesc ) ) { castToReturnType ( mv , td . msign ) ; return ; } if ( isTargetMethodAnnotationMethod ( mname , mdesc ) ) { String [ ] args = getLastTwoStringArguments ( ) ; // pop current two args mv . visitInsn ( POP ) ; mv . visitInsn ( POP ) ; ProxyTargetReplacement . targetMethodAnnotation ( mv , td . msign , args ) ; return ; } if ( isTargetClassAnnotationMethod ( mname , mdesc ) ) { String [ ] args = getLastTwoStringArguments ( ) ; // pop current two args mv . visitInsn ( POP ) ; mv . visitInsn ( POP ) ; ProxyTargetReplacement . targetClassAnnotation ( mv , td . msign . getClassInfo ( ) , args ) ; return ; } } } super . visitMethodInsn ( opcode , string , mname , mdesc , isInterface ) ; } } ; } } , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses input dot - separated string that represents a path . [CODESPLIT] public static Path parse ( final String path ) { return path == null ? new Path ( ) : new Path ( StringUtil . splitc ( path , ' ' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push element to the path . [CODESPLIT] public Path push ( final CharSequence field ) { _push ( field ) ; if ( altPath != null ) { altPath . push ( field ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Alternative way for registering Joy listeners . Sometimes servlet container does not allow adding new listener from already added listener . This method therefore registers the listener <i > before< / i > container actually called the callback methods . [CODESPLIT] public static void registerInServletContext ( final ServletContext servletContext , final Class < ? extends JoyContextListener > joyContextListenerClass ) { try { final JoyContextListener joyContextListener = ClassUtil . newInstance ( joyContextListenerClass ) ; joyContextListener . createJoyAndInitServletContext ( servletContext ) ; } catch ( Exception e ) { throw new JoyException ( e ) ; } servletContext . addListener ( joyContextListenerClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] protected JoddJoy createJoy ( ) { final JoddJoy joy = JoddJoy . get ( ) ; if ( SystemUtil . info ( ) . isAtLeastJavaVersion ( 9 ) ) { joy . withScanner ( joyScanner -> joyScanner . scanClasspathOf ( this . getClass ( ) ) ) ; } return joy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures servlet context . [CODESPLIT] private void configureServletContext ( final ServletContext servletContext ) { servletContext . addListener ( jodd . servlet . RequestContextListener . class ) ; if ( decoraEnabled ) { final FilterRegistration filter = servletContext . addFilter ( \"decora\" , jodd . decora . DecoraServletFilter . class ) ; filter . addMappingForUrlPatterns ( null , true , contextPath ) ; } final FilterRegistration filter = servletContext . addFilter ( \"madvoc\" , jodd . madvoc . MadvocServletFilter . class ) ; filter . addMappingForUrlPatterns ( madvocDispatcherTypes , true , contextPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- integer [CODESPLIT] public int getInteger ( final int index ) { try { return statement . getInt ( index ) ; } catch ( SQLException sex ) { throw newGetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- boolean [CODESPLIT] public boolean getBoolean ( final int index ) { try { return statement . getBoolean ( index ) ; } catch ( SQLException sex ) { throw newGetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- byte [CODESPLIT] public byte getByte ( final int index ) { try { return statement . getByte ( index ) ; } catch ( SQLException sex ) { throw newGetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- doublw [CODESPLIT] public double getDouble ( final int index ) { try { return statement . getDouble ( index ) ; } catch ( SQLException sex ) { throw newGetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- float [CODESPLIT] public float getFloat ( final int index ) { try { return statement . getFloat ( index ) ; } catch ( SQLException sex ) { throw newGetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- string [CODESPLIT] public String getString ( final int index ) { try { return statement . getString ( index ) ; } catch ( SQLException sex ) { throw newGetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- long [CODESPLIT] public long getLong ( final int index ) { try { return statement . getLong ( index ) ; } catch ( SQLException sex ) { throw newGetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads method name and appends it . Creates object for next call and returns that value . If next object is unsupported it will return null ; [CODESPLIT] public Object execute ( ) { String methodName = targetMethodName ( ) ; Class returnType = returnType ( ) ; Object next = pathref . continueWith ( this , methodName , returnType ) ; return ProxyTarget . returnValue ( next ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects fields and returns map of { [CODESPLIT] private Map < String , FieldDescriptor > inspectFields ( ) { if ( classDescriptor . isSystemClass ( ) ) { return emptyFields ( ) ; } final boolean scanAccessible = classDescriptor . isScanAccessible ( ) ; final Class type = classDescriptor . getType ( ) ; final Field [ ] fields = scanAccessible ? ClassUtil . getAccessibleFields ( type ) : ClassUtil . getSupportedFields ( type ) ; final HashMap < String , FieldDescriptor > map = new HashMap <> ( fields . length ) ; for ( final Field field : fields ) { final String fieldName = field . getName ( ) ; if ( fieldName . equals ( \"serialVersionUID\" ) ) { continue ; } map . put ( fieldName , createFieldDescriptor ( field ) ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all fields of this collection . Returns empty array if no fields exist . Initialized lazy . [CODESPLIT] public FieldDescriptor [ ] getAllFieldDescriptors ( ) { if ( allFields == null ) { FieldDescriptor [ ] allFields = new FieldDescriptor [ fieldsMap . size ( ) ] ; int index = 0 ; for ( FieldDescriptor fieldDescriptor : fieldsMap . values ( ) ) { allFields [ index ] = fieldDescriptor ; index ++ ; } Arrays . sort ( allFields , Comparator . comparing ( fd -> fd . getField ( ) . getName ( ) ) ) ; this . allFields = allFields ; } return allFields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Blob get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getBlob ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Blob value , final int dbSqlType ) throws SQLException { st . setBlob ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies proxetta on bean class before bean registration . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override protected < T > BeanDefinition < T > createBeanDefinitionForRegistration ( final String name , Class < T > type , final Scope scope , final WiringMode wiringMode , final Consumer < T > consumer ) { if ( proxetta != null ) { final Class originalType = type ; final ProxettaFactory builder = proxetta . proxy ( ) ; builder . setTarget ( type ) ; type = builder . define ( ) ; return new ProxettaBeanDefinition ( name , type , scope , wiringMode , originalType , proxetta . getAspects ( new ProxyAspect [ 0 ] ) , consumer ) ; } return super . createBeanDefinitionForRegistration ( name , type , scope , wiringMode , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converter JTX transaction mode to DB transaction mode . [CODESPLIT] public static DbTransactionMode convertToDbMode ( final JtxTransactionMode txMode ) { final int isolation ; switch ( txMode . getIsolationLevel ( ) ) { case ISOLATION_DEFAULT : isolation = DbTransactionMode . ISOLATION_DEFAULT ; break ; case ISOLATION_NONE : isolation = DbTransactionMode . ISOLATION_NONE ; break ; case ISOLATION_READ_COMMITTED : isolation = DbTransactionMode . ISOLATION_READ_COMMITTED ; break ; case ISOLATION_READ_UNCOMMITTED : isolation = DbTransactionMode . ISOLATION_READ_UNCOMMITTED ; break ; case ISOLATION_REPEATABLE_READ : isolation = DbTransactionMode . ISOLATION_REPEATABLE_READ ; break ; case ISOLATION_SERIALIZABLE : isolation = DbTransactionMode . ISOLATION_SERIALIZABLE ; break ; default : throw new IllegalArgumentException ( ) ; } return new DbTransactionMode ( isolation , txMode . isReadOnly ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Character get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { if ( TypesUtil . isIntegerType ( dbSqlType ) ) { return Character . valueOf ( ( char ) rs . getInt ( index ) ) ; } String s = rs . getString ( index ) ; if ( s == null ) { return null ; } if ( s . length ( ) > 1 ) { throw new DbSqlException ( \"Char column size too long, should be 1\" ) ; } return Character . valueOf ( s . charAt ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Character value , final int dbSqlType ) throws SQLException { if ( TypesUtil . isIntegerType ( dbSqlType ) ) { st . setInt ( index , value . charValue ( ) ) ; return ; } st . setString ( index , value . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads property value and { [CODESPLIT] @ Override protected final void onSerializableProperty ( String propertyName , final PropertyDescriptor propertyDescriptor ) { final Object value ; if ( propertyDescriptor == null ) { // metadata - classname value = source . getClass ( ) . getName ( ) ; } else { value = readProperty ( source , propertyDescriptor ) ; if ( ( value == null ) && jsonContext . isExcludeNulls ( ) ) { return ; } // change name for properties propertyName = typeData . resolveJsonName ( propertyName ) ; } onSerializableProperty ( propertyName , propertyDescriptor == null ? null : propertyDescriptor . getType ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked on serializable properties that have passed all the rules . Property type is <code > null< / code > for metadata class name property . [CODESPLIT] protected void onSerializableProperty ( final String propertyName , final Class propertyType , final Object value ) { jsonContext . pushName ( propertyName , count > 0 ) ; jsonContext . serialize ( value ) ; if ( jsonContext . isNamePopped ( ) ) { count ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads property using property descriptor . [CODESPLIT] private Object readProperty ( final Object source , final PropertyDescriptor propertyDescriptor ) { Getter getter = propertyDescriptor . getGetter ( declared ) ; if ( getter != null ) { try { return getter . invokeGetter ( source ) ; } catch ( Exception ex ) { throw new JsonException ( ex ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if first argument contains provided element . It works for strings collections maps and arrays . s [CODESPLIT] public static boolean containsElement ( final Object obj , final Object element ) { if ( obj == null ) { return false ; } if ( obj instanceof String ) { if ( element == null ) { return false ; } return ( ( String ) obj ) . contains ( element . toString ( ) ) ; } if ( obj instanceof Collection ) { return ( ( Collection ) obj ) . contains ( element ) ; } if ( obj instanceof Map ) { return ( ( Map ) obj ) . values ( ) . contains ( element ) ; } if ( obj instanceof Iterator ) { Iterator iter = ( Iterator ) obj ; while ( iter . hasNext ( ) ) { Object o = iter . next ( ) ; if ( equals ( o , element ) ) { return true ; } } return false ; } if ( obj instanceof Enumeration ) { Enumeration enumeration = ( Enumeration ) obj ; while ( enumeration . hasMoreElements ( ) ) { Object o = enumeration . nextElement ( ) ; if ( equals ( o , element ) ) { return true ; } } return false ; } if ( obj . getClass ( ) . isArray ( ) ) { int len = Array . getLength ( obj ) ; for ( int i = 0 ; i < len ; i ++ ) { Object o = Array . get ( obj , i ) ; if ( equals ( o , element ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates EML string from given { @link Email } . [CODESPLIT] public String compose ( final Email email ) { if ( getSession ( ) == null ) { createSession ( getProperties ( ) ) ; } final OutputStreamTransport ost = new OutputStreamTransport ( getSession ( ) ) ; final SendMailSession sendMailSession = new SendMailSession ( getSession ( ) , ost ) ; sendMailSession . sendMail ( email ) ; return ost . getEml ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates EML string from given { @link ReceivedEmail } . [CODESPLIT] public String compose ( final ReceivedEmail receivedEmail ) { Message msg = receivedEmail . originalMessage ( ) ; final ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; try { msg . writeTo ( outputStream ) ; } catch ( IOException | MessagingException e ) { throw new MailException ( e ) ; } return outputStream . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastDoubleBuffer append ( final FastDoubleBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rehashes the contents of this map into a new <code > IntHashMap< / code > instance with a larger capacity . This method is called automatically when the number of keys in this map exceeds its capacity and load factor . [CODESPLIT] private void rehash ( ) { int oldCapacity = table . length ; Entry [ ] oldMap = table ; int newCapacity = ( oldCapacity << 1 ) + 1 ; Entry [ ] newMap = new Entry [ newCapacity ] ; modCount ++ ; threshold = ( int ) ( newCapacity * loadFactor ) ; table = newMap ; for ( int i = oldCapacity ; i -- > 0 ; ) { for ( Entry old = oldMap [ i ] ; old != null ; ) { Entry e = old ; old = old . next ; int index = ( e . key & 0x7FFFFFFF ) % newCapacity ; e . next = newMap [ index ] ; newMap [ index ] = e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified key in this map . If the map previously contained a mapping for this key the old value is replaced . [CODESPLIT] public Object put ( final int key , final Object value ) { // makes sure the key is not already in the IntHashMap. Entry [ ] tab = table ; int index = ( key & 0x7FFFFFFF ) % tab . length ; for ( Entry e = tab [ index ] ; e != null ; e = e . next ) { if ( e . key == key ) { Object old = e . value ; e . value = value ; return old ; } } modCount ++ ; if ( count >= threshold ) { // rehash the table if the threshold is exceeded rehash ( ) ; tab = table ; index = ( key & 0x7FFFFFFF ) % tab . length ; } // creates the new entry. tab [ index ] = new Entry ( key , value , tab [ index ] ) ; count ++ ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all of the mappings from the specified map to this one . These mappings replace any mappings that this map had for any of the keys currently in the specified Map . [CODESPLIT] @ Override public void putAll ( final Map t ) { for ( Object o : t . entrySet ( ) ) { Map . Entry e = ( Map . Entry ) o ; put ( e . getKey ( ) , e . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all mappings from this map . [CODESPLIT] @ Override public void clear ( ) { Entry [ ] tab = table ; modCount ++ ; for ( int index = tab . length ; -- index >= 0 ; ) { tab [ index ] = null ; } count = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastLongBuffer append ( final FastLongBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] public long [ ] toArray ( final int start , final int len ) { final long [ ] array = new long [ len ] ; if ( len == 0 ) { return array ; } System . arraycopy ( buffer , start , array , 0 , len ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends string content to buffer . [CODESPLIT] public Buffer append ( final String string ) { ensureLast ( ) ; try { byte [ ] bytes = string . getBytes ( StringPool . ISO_8859_1 ) ; last . append ( bytes ) ; size += bytes . length ; } catch ( UnsupportedEncodingException ignore ) { } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends { [CODESPLIT] public Buffer append ( final Uploadable uploadable ) { list . add ( uploadable ) ; size += uploadable . getSize ( ) ; last = null ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends other buffer to this one . [CODESPLIT] public Buffer append ( final Buffer buffer ) { if ( buffer . list . isEmpty ( ) ) { // nothing to append return buffer ; } list . addAll ( buffer . list ) ; last = buffer . last ; size += buffer . size ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes content to the writer . [CODESPLIT] public void writeTo ( final Writer writer ) throws IOException { for ( Object o : list ) { if ( o instanceof FastByteBuffer ) { FastByteBuffer fastByteBuffer = ( FastByteBuffer ) o ; byte [ ] array = fastByteBuffer . toArray ( ) ; writer . write ( new String ( array , StringPool . ISO_8859_1 ) ) ; } else if ( o instanceof Uploadable ) { Uploadable uploadable = ( Uploadable ) o ; InputStream inputStream = uploadable . openInputStream ( ) ; try { StreamUtil . copy ( inputStream , writer , StringPool . ISO_8859_1 ) ; } finally { StreamUtil . close ( inputStream ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes content to the output stream . [CODESPLIT] public void writeTo ( final OutputStream out ) throws IOException { for ( Object o : list ) { if ( o instanceof FastByteBuffer ) { FastByteBuffer fastByteBuffer = ( FastByteBuffer ) o ; out . write ( fastByteBuffer . toArray ( ) ) ; } else if ( o instanceof Uploadable ) { Uploadable uploadable = ( Uploadable ) o ; InputStream inputStream = uploadable . openInputStream ( ) ; try { StreamUtil . copy ( inputStream , out ) ; } finally { StreamUtil . close ( inputStream ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes content to the output stream using progress listener to track the sending progress . [CODESPLIT] public void writeTo ( final OutputStream out , final HttpProgressListener progressListener ) throws IOException { // start final int size = size ( ) ; final int callbackSize = progressListener . callbackSize ( size ) ; int count = 0 ; // total count int step = 0 ; // step is offset in current chunk progressListener . transferred ( count ) ; // loop for ( Object o : list ) { if ( o instanceof FastByteBuffer ) { FastByteBuffer fastByteBuffer = ( FastByteBuffer ) o ; byte [ ] bytes = fastByteBuffer . toArray ( ) ; int offset = 0 ; while ( offset < bytes . length ) { // calc the remaining sending chunk size int chunk = callbackSize - step ; // check if this chunk size fits the bytes array if ( offset + chunk > bytes . length ) { chunk = bytes . length - offset ; } // writes the chunk out . write ( bytes , offset , chunk ) ; offset += chunk ; step += chunk ; count += chunk ; // listener if ( step >= callbackSize ) { progressListener . transferred ( count ) ; step -= callbackSize ; } } } else if ( o instanceof Uploadable ) { Uploadable uploadable = ( Uploadable ) o ; InputStream inputStream = uploadable . openInputStream ( ) ; int remaining = uploadable . getSize ( ) ; try { while ( remaining > 0 ) { // calc the remaining sending chunk size int chunk = callbackSize - step ; // check if this chunk size fits the remaining size if ( chunk > remaining ) { chunk = remaining ; } // writes remaining chunk StreamUtil . copy ( inputStream , out , chunk ) ; remaining -= chunk ; step += chunk ; count += chunk ; // listener if ( step >= callbackSize ) { progressListener . transferred ( count ) ; step -= callbackSize ; } } } finally { StreamUtil . close ( inputStream ) ; } } } // end if ( step != 0 ) { progressListener . transferred ( count ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- private [CODESPLIT] private static String encode ( final CharSequence text , final char [ ] [ ] buff , final int bufflen ) { int len ; if ( ( text == null ) || ( ( len = text . length ( ) ) == 0 ) ) { return StringPool . EMPTY ; } StringBuilder buffer = new StringBuilder ( len + ( len >> 2 ) ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = text . charAt ( i ) ; if ( c < bufflen ) { buffer . append ( buff [ c ] ) ; } else { buffer . append ( c ) ; } } return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the string value with the specified key . [CODESPLIT] public String getString ( final String key ) { CharSequence cs = ( CharSequence ) map . get ( key ) ; return cs == null ? null : cs . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the integer value with the specified key . [CODESPLIT] public Integer getInteger ( final String key ) { Number number = ( Number ) map . get ( key ) ; if ( number == null ) { return null ; } if ( number instanceof Integer ) { return ( Integer ) number ; } return number . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the long value with the specified key . [CODESPLIT] public Long getLong ( final String key ) { Number number = ( Number ) map . get ( key ) ; if ( number == null ) { return null ; } if ( number instanceof Long ) { return ( Long ) number ; } return number . longValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the double value with the specified key . [CODESPLIT] public Double getDouble ( final String key ) { Number number = ( Number ) map . get ( key ) ; if ( number == null ) { return null ; } if ( number instanceof Double ) { return ( Double ) number ; } return number . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the float value with the specified key . [CODESPLIT] public Float getFloat ( final String key ) { Number number = ( Number ) map . get ( key ) ; if ( number == null ) { return null ; } if ( number instanceof Float ) { return ( Float ) number ; } return number . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { [CODESPLIT] public JsonObject getJsonObject ( final String key ) { Object val = map . get ( key ) ; if ( val instanceof Map ) { val = new JsonObject ( ( Map ) val ) ; } return ( JsonObject ) val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { [CODESPLIT] public JsonArray getJsonArray ( final String key ) { Object val = map . get ( key ) ; if ( val instanceof List ) { val = new JsonArray ( ( List ) val ) ; } return ( JsonArray ) val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the binary value with the specified key . <p > JSON itself has no notion of a binary . This extension complies to the RFC - 7493 . THe byte array is Base64 encoded binary . [CODESPLIT] public byte [ ] getBinary ( final String key ) { String encoded = ( String ) map . get ( key ) ; return encoded == null ? null : Base64 . getDecoder ( ) . decode ( encoded ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value with the specified key as an object . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T getValue ( final String key ) { T val = ( T ) map . get ( key ) ; if ( val instanceof Map ) { return ( T ) new JsonObject ( ( Map ) val ) ; } if ( val instanceof List ) { return ( T ) new JsonArray ( ( List ) val ) ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public String getString ( final String key , final String def ) { String val = getString ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public Integer getInteger ( final String key , final Integer def ) { Integer val = getInteger ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public Long getLong ( final String key , final Long def ) { Long val = getLong ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public Double getDouble ( final String key , final Double def ) { Double val = getDouble ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public Float getFloat ( final String key , final Float def ) { Float val = getFloat ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public Boolean getBoolean ( final String key , final Boolean def ) { Boolean val = getBoolean ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public JsonObject getJsonObject ( final String key , final JsonObject def ) { JsonObject val = getJsonObject ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public JsonArray getJsonArray ( final String key , final JsonArray def ) { JsonArray val = getJsonArray ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public byte [ ] getBinary ( final String key , final byte [ ] def ) { byte [ ] val = getBinary ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { [CODESPLIT] public < T > T getValue ( final String key , final T def ) { T val = getValue ( key ) ; if ( val == null ) { if ( map . containsKey ( key ) ) { return null ; } return def ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts an Enum into the JSON object with the specified key . <p > JSON has no concept of encoding Enums so the Enum will be converted to a String using the { [CODESPLIT] public JsonObject put ( final String key , final Enum value ) { Objects . requireNonNull ( key ) ; map . put ( key , value == null ? null : value . name ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts an { [CODESPLIT] public JsonObject put ( final String key , final CharSequence value ) { Objects . requireNonNull ( key ) ; map . put ( key , value == null ? null : value . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a string into the JSON object with the specified key . [CODESPLIT] public JsonObject put ( final String key , final String value ) { Objects . requireNonNull ( key ) ; map . put ( key , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a { [CODESPLIT] public JsonObject putNull ( final String key ) { Objects . requireNonNull ( key ) ; map . put ( key , null ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a { [CODESPLIT] public JsonObject put ( final String key , final byte [ ] value ) { Objects . requireNonNull ( key ) ; map . put ( key , value == null ? null : Base64 . getEncoder ( ) . encodeToString ( value ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns array of all { @link Folder } s as { @code String } s . You can use these names in { @link #useFolder ( String ) } method . [CODESPLIT] public String [ ] getAllFolders ( ) { final Folder [ ] folders ; try { folders = getService ( ) . getDefaultFolder ( ) . list ( \"*\" ) ; } catch ( final MessagingException msgexc ) { throw new MailException ( \"Failed to connect to folder\" , msgexc ) ; } final String [ ] folderNames = new String [ folders . length ] ; for ( int i = 0 ; i < folders . length ; i ++ ) { final Folder folder = folders [ i ] ; folderNames [ i ] = folder . getFullName ( ) ; } return folderNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens new folder and closes previously opened folder . [CODESPLIT] public void useFolder ( final String folderName ) { closeFolderIfOpened ( folder ) ; try { this . folderName = folderName ; this . folder = getService ( ) . getFolder ( folderName ) ; try { folder . open ( Folder . READ_WRITE ) ; } catch ( final MailException ignore ) { folder . open ( Folder . READ_ONLY ) ; } } catch ( final MessagingException msgexc ) { throw new MailException ( \"Failed to connect to folder: \" + folderName , msgexc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Just returns a folder w / o opening . [CODESPLIT] public Folder getFolder ( final String folder ) { try { return getService ( ) . getFolder ( folder ) ; } catch ( MessagingException e ) { throw new MailException ( \"Folder not found: \" + folder , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receives all emails that matches given { @link EmailFilter } . Messages are not modified . However servers may set SEEN flag anyway so we force messages to remain unseen . [CODESPLIT] public ReceivedEmail [ ] receiveEmail ( final EmailFilter filter ) { return receiveMessages ( filter , null , null , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receives all emails that matches given { @link EmailFilter } and mark them as seen ( ie read ) . [CODESPLIT] public ReceivedEmail [ ] receiveEmailAndMarkSeen ( final EmailFilter filter ) { final Flags flagsToSet = new Flags ( ) ; flagsToSet . add ( Flags . Flag . SEEN ) ; return receiveMessages ( filter , flagsToSet , null , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receives all emails that matches given { @link EmailFilter } and mark all messages as seen and deleted . [CODESPLIT] public ReceivedEmail [ ] receiveEmailAndDelete ( final EmailFilter filter ) { final Flags flags = new Flags ( ) ; flags . add ( Flags . Flag . SEEN ) ; flags . add ( Flags . Flag . DELETED ) ; return receiveMessages ( filter , flags , null , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main email receiving method . [CODESPLIT] ReceivedEmail [ ] receiveMessages ( final EmailFilter filter , final Flags flagsToSet , final Flags flagsToUnset , final boolean envelope , final Consumer < Message [ ] > processedMessageConsumer ) { useAndOpenFolderIfNotSet ( ) ; final Message [ ] messages ; try { if ( filter == null ) { messages = folder . getMessages ( ) ; } else { messages = folder . search ( filter . getSearchTerm ( ) ) ; } if ( messages . length == 0 ) { return ReceivedEmail . EMPTY_ARRAY ; } if ( envelope ) { final FetchProfile fetchProfile = new FetchProfile ( ) ; fetchProfile . add ( FetchProfile . Item . ENVELOPE ) ; fetchProfile . add ( FetchProfile . Item . FLAGS ) ; folder . fetch ( messages , fetchProfile ) ; } // process messages final ReceivedEmail [ ] emails = new ReceivedEmail [ messages . length ] ; for ( int i = 0 ; i < messages . length ; i ++ ) { final Message msg = messages [ i ] ; // we need to parse message BEFORE flags are set! emails [ i ] = new ReceivedEmail ( msg , envelope , attachmentStorage ) ; if ( ! EmailUtil . isEmptyFlags ( flagsToSet ) ) { emails [ i ] . flags ( flagsToSet ) ; msg . setFlags ( flagsToSet , true ) ; } if ( ! EmailUtil . isEmptyFlags ( flagsToUnset ) ) { emails [ i ] . flags ( ) . remove ( flagsToUnset ) ; msg . setFlags ( flagsToUnset , false ) ; } if ( EmailUtil . isEmptyFlags ( flagsToSet ) && ! emails [ i ] . isSeen ( ) ) { msg . setFlag ( Flags . Flag . SEEN , false ) ; } } if ( processedMessageConsumer != null ) { processedMessageConsumer . accept ( messages ) ; } // if messages were marked to be deleted, we need to expunge the folder if ( ! EmailUtil . isEmptyFlags ( flagsToSet ) ) { if ( flagsToSet . contains ( Flags . Flag . DELETED ) ) { folder . expunge ( ) ; } } return emails ; } catch ( final MessagingException msgexc ) { throw new MailException ( \"Failed to fetch messages\" , msgexc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the email flags on the server . [CODESPLIT] public void updateEmailFlags ( final ReceivedEmail receivedEmail ) { useAndOpenFolderIfNotSet ( ) ; try { folder . setFlags ( new int [ ] { receivedEmail . messageNumber ( ) } , receivedEmail . flags ( ) , true ) ; } catch ( MessagingException mex ) { throw new MailException ( \"Failed to fetch messages\" , mex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes folder if opened and expunge deleted messages . [CODESPLIT] protected void closeFolderIfOpened ( final Folder folder ) { if ( folder != null ) { try { folder . close ( true ) ; } catch ( final MessagingException ignore ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup for named parameter . [CODESPLIT] DbQueryNamedParameter lookupNamedParameter ( final String name ) { DbQueryNamedParameter p = rootNP ; while ( p != null ) { if ( p . equalsName ( name ) ) { return p ; } p = p . next ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of batch parameter . Returns <code > 0< / code > if parameter does not exist . [CODESPLIT] protected int getBatchParameterSize ( final String name ) { if ( batchParams == null ) { return 0 ; } Integer size = batchParams . get ( name ) ; if ( size == null ) { return 0 ; } return size . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- parser [CODESPLIT] void parseSql ( final String sqlString ) { rootNP = null ; final int stringLength = sqlString . length ( ) ; final StringBuilder pureSql = new StringBuilder ( stringLength ) ; boolean inQuote = false ; int index = 0 ; int paramCount = 0 ; while ( index < stringLength ) { char c = sqlString . charAt ( index ) ; if ( inQuote ) { if ( c == ' ' ) { inQuote = false ; } } else if ( c == ' ' ) { inQuote = true ; } else if ( c == ' ' && index + 1 < stringLength && sqlString . charAt ( index + 1 ) == ' ' ) { // don't treat '::foo' sequence as named parameter; skip this // chunk int right = StringUtil . indexOfChars ( sqlString , SQL_SEPARATORS , index + 2 ) ; if ( right < 0 ) { right = stringLength ; } pureSql . append ( sqlString . substring ( index , right ) ) ; index = right ; continue ; } else if ( c == ' ' ) { int right = StringUtil . indexOfChars ( sqlString , SQL_SEPARATORS , index + 1 ) ; boolean batch = false ; if ( right < 0 ) { right = stringLength ; } else { if ( sqlString . charAt ( right ) == ' ' ) { batch = true ; } } String param = sqlString . substring ( index + 1 , right ) ; if ( ! batch ) { paramCount ++ ; storeNamedParameter ( param , paramCount ) ; pureSql . append ( ' ' ) ; } else { // read batch size right ++ ; int numStart = right ; while ( right < stringLength ) { if ( ! CharUtil . isDigit ( sqlString . charAt ( right ) ) ) { break ; } right ++ ; } String numberValue = sqlString . substring ( numStart , right ) ; int batchSize ; try { batchSize = Integer . parseInt ( numberValue ) ; } catch ( NumberFormatException nfex ) { throw new DbSqlException ( \"Batch size is not an integer: \" + numberValue , nfex ) ; } saveBatchParameter ( param , batchSize ) ; // create batch parameters for ( int i = 1 ; i <= batchSize ; i ++ ) { if ( i != 1 ) { pureSql . append ( ' ' ) ; } paramCount ++ ; storeNamedParameter ( param + ' ' + i , paramCount ) ; pureSql . append ( ' ' ) ; } } index = right ; continue ; } else if ( c == ' ' ) { // either an ordinal or positional parameter if ( ( index < stringLength - 1 ) && ( Character . isDigit ( sqlString . charAt ( index + 1 ) ) ) ) { // positional parameter int right = StringUtil . indexOfChars ( sqlString , SQL_SEPARATORS , index + 1 ) ; if ( right < 0 ) { right = stringLength ; } String param = sqlString . substring ( index + 1 , right ) ; try { Integer . parseInt ( param ) ; } catch ( NumberFormatException nfex ) { throw new DbSqlException ( \"Positional parameter is not an integer: \" + param , nfex ) ; } paramCount ++ ; storeNamedParameter ( param , paramCount ) ; pureSql . append ( ' ' ) ; index = right ; continue ; } paramCount ++ ; // ordinal param } pureSql . append ( c ) ; index ++ ; } this . prepared = ( paramCount != 0 ) ; this . sql = pureSql . toString ( ) ; if ( this . sql . startsWith ( \"{\" ) ) { this . callable = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates alias . [CODESPLIT] protected String alias ( final String target ) { return StringPool . LEFT_CHEV . concat ( target ) . concat ( StringPool . RIGHT_CHEV ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates alias from target object and target method name . If classname contains a $ sign everything will be stripped after it ( to get the real name if action class is proxified ) . [CODESPLIT] protected String alias ( final Object target , final String targetMethodName ) { String targetClassName = target . getClass ( ) . getName ( ) ; targetClassName = StringUtil . cutToIndexOf ( targetClassName , ' ' ) ; return ' ' + targetClassName + ' ' + targetMethodName + ' ' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates action . Profiles are reset after the invocation . [CODESPLIT] protected boolean validateAction ( final String ... profiles ) { prepareValidator ( ) ; vtor . useProfiles ( profiles ) ; vtor . validate ( this ) ; vtor . resetProfiles ( ) ; List < Violation > violations = vtor . getViolations ( ) ; return violations == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds action violation . [CODESPLIT] protected void addViolation ( final String name , final Object invalidValue ) { prepareValidator ( ) ; vtor . addViolation ( new Violation ( name , this , invalidValue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if tag name is a void tag . [CODESPLIT] public boolean isVoidTag ( final CharSequence tagName ) { for ( String html5VoidTag : HTML5_VOID_TAGS ) { if ( CharSequenceUtil . equalsToLowercase ( tagName , html5VoidTag ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines mime type by providing real mime type or just extension! [CODESPLIT] public RawData as ( final String mimeOrExtension ) { if ( mimeOrExtension . contains ( StringPool . SLASH ) ) { this . mimeType = mimeOrExtension ; } else { this . mimeType = MimeTypes . getMimeType ( mimeOrExtension ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines download file name and mime type from the name extension . [CODESPLIT] public RawData downloadableAs ( final String downloadFileName ) { this . downloadFileName = downloadFileName ; this . mimeType = MimeTypes . getMimeType ( FileNameUtil . getExtension ( downloadFileName ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines class input stream as a target . [CODESPLIT] protected T setTarget ( final InputStream target ) { assertTargetIsNotDefined ( ) ; targetInputStream = target ; targetClass = null ; targetClassName = null ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines class name as a target . Class will not be loaded by classloader! [CODESPLIT] protected T setTarget ( final String targetName ) { assertTargetIsNotDefined ( ) ; try { targetInputStream = ClassLoaderUtil . getClassAsStream ( targetName ) ; if ( targetInputStream == null ) { throw new ProxettaException ( \"Target class not found: \" + targetName ) ; } targetClassName = targetName ; targetClass = null ; } catch ( IOException ioex ) { StreamUtil . close ( targetInputStream ) ; throw new ProxettaException ( \"Unable to get stream class name: \" + targetName , ioex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines class as a target . [CODESPLIT] public T setTarget ( final Class target ) { assertTargetIsNotDefined ( ) ; try { targetInputStream = ClassLoaderUtil . getClassAsStream ( target ) ; if ( targetInputStream == null ) { throw new ProxettaException ( \"Target class not found: \" + target . getName ( ) ) ; } targetClass = target ; targetClassName = target . getName ( ) ; } catch ( IOException ioex ) { StreamUtil . close ( targetInputStream ) ; throw new ProxettaException ( \"Unable to stream class: \" + target . getName ( ) , ioex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns new suffix or <code > null< / code > if suffix is not in use . [CODESPLIT] protected String resolveClassNameSuffix ( ) { String classNameSuffix = proxetta . getClassNameSuffix ( ) ; if ( classNameSuffix == null ) { return null ; } if ( ! proxetta . isVariableClassName ( ) ) { return classNameSuffix ; } suffixCounter ++ ; return classNameSuffix + suffixCounter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the target and creates destination class . [CODESPLIT] protected void process ( ) { if ( targetInputStream == null ) { throw new ProxettaException ( \"Target missing: \" + targetClassName ) ; } // create class reader final ClassReader classReader ; try { classReader = new ClassReader ( targetInputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( \"Error reading class input stream\" , ioex ) ; } // reads information final TargetClassInfoReader targetClassInfoReader = new TargetClassInfoReader ( proxetta . getClassLoader ( ) ) ; classReader . accept ( targetClassInfoReader , 0 ) ; this . destClassWriter = new ClassWriter ( ClassWriter . COMPUTE_MAXS | ClassWriter . COMPUTE_FRAMES ) ; // create proxy if ( log . isDebugEnabled ( ) ) { log . debug ( \"processing: \" + classReader . getClassName ( ) ) ; } WorkData wd = process ( classReader , targetClassInfoReader ) ; // store important data proxyApplied = wd . proxyApplied ; proxyClassName = wd . thisReference . replace ( ' ' , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns byte array of created class . [CODESPLIT] public byte [ ] create ( ) { process ( ) ; byte [ ] result = toByteArray ( ) ; dumpClassInDebugFolder ( result ) ; if ( ( ! proxetta . isForced ( ) ) && ( ! isProxyApplied ( ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Proxy not applied: \" + StringUtil . toSafeString ( targetClassName ) ) ; } return null ; } if ( log . isDebugEnabled ( ) ) { log . debug ( \"Proxy created \" + StringUtil . toSafeString ( targetClassName ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines class . [CODESPLIT] public Class define ( ) { process ( ) ; if ( ( ! proxetta . isForced ( ) ) && ( ! isProxyApplied ( ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Proxy not applied: \" + StringUtil . toSafeString ( targetClassName ) ) ; } if ( targetClass != null ) { return targetClass ; } if ( targetClassName != null ) { try { return ClassLoaderUtil . loadClass ( targetClassName ) ; } catch ( ClassNotFoundException cnfex ) { throw new ProxettaException ( cnfex ) ; } } } if ( log . isDebugEnabled ( ) ) { log . debug ( \"Proxy created: \" + StringUtil . toSafeString ( targetClassName ) ) ; } try { ClassLoader classLoader = proxetta . getClassLoader ( ) ; if ( classLoader == null ) { classLoader = ClassLoaderUtil . getDefaultClassLoader ( ) ; if ( ( classLoader == null ) && ( targetClass != null ) ) { classLoader = targetClass . getClassLoader ( ) ; } } final byte [ ] bytes = toByteArray ( ) ; dumpClassInDebugFolder ( bytes ) ; return DefineClass . of ( getProxyClassName ( ) , bytes , classLoader ) ; } catch ( Exception ex ) { throw new ProxettaException ( \"Class definition failed\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new instance of created class . Assumes default no - arg constructor . [CODESPLIT] public Object newInstance ( ) { Class type = define ( ) ; try { return ClassUtil . newInstance ( type ) ; } catch ( Exception ex ) { throw new ProxettaException ( \"Invalid Proxetta class\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes created class content to output folder for debugging purposes . [CODESPLIT] protected void dumpClassInDebugFolder ( final byte [ ] bytes ) { File debugFolder = proxetta . getDebugFolder ( ) ; if ( debugFolder == null ) { return ; } if ( ! debugFolder . exists ( ) || ! debugFolder . isDirectory ( ) ) { log . warn ( \"Invalid debug folder: \" + debugFolder ) ; } String fileName = proxyClassName ; if ( fileName == null ) { fileName = \"proxetta-\" + System . currentTimeMillis ( ) ; } fileName += \".class\" ; File file = new File ( debugFolder , fileName ) ; try { FileUtil . writeBytes ( file , bytes ) ; } catch ( IOException ioex ) { log . warn ( \"Error writing class as \" + file , ioex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the FROM address by providing personal name and address . [CODESPLIT] public T from ( final String personalName , final String from ) { return from ( new EmailAddress ( personalName , from ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends TO address . [CODESPLIT] public T to ( final EmailAddress to ) { this . to = ArraysUtil . append ( this . to , to ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends TO address by personal name and email address . [CODESPLIT] public T to ( final String personalName , final String to ) { return to ( new EmailAddress ( personalName , to ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends REPLY - TO address . [CODESPLIT] public T replyTo ( final EmailAddress replyTo ) { this . replyTo = ArraysUtil . append ( this . replyTo , replyTo ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends REPLY - TO address . [CODESPLIT] public T replyTo ( final String personalName , final String replyTo ) { return replyTo ( new EmailAddress ( personalName , replyTo ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends REPLY - TO addresses . [CODESPLIT] public T replyTo ( final EmailAddress ... replyTo ) { this . replyTo = ArraysUtil . join ( this . replyTo , valueOrEmptyArray ( replyTo ) ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends CC address . [CODESPLIT] public T cc ( final EmailAddress to ) { this . cc = ArraysUtil . append ( this . cc , to ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends CC address . [CODESPLIT] public T cc ( final String personalName , final String cc ) { return cc ( new EmailAddress ( personalName , cc ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends CC addresses . [CODESPLIT] public T cc ( final EmailAddress ... ccs ) { this . cc = ArraysUtil . join ( this . cc , valueOrEmptyArray ( ccs ) ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets message subject with specified encoding to override default platform encoding . If the subject contains non US - ASCII characters it will be encoded using the specified charset . If the subject contains only US - ASCII characters no encoding is done and it is used as - is . The application must ensure that the subject does not contain any line breaks . See { @link javax . mail . internet . MimeMessage#setSubject ( String String ) } . [CODESPLIT] public T subject ( final String subject , final String encoding ) { subject ( subject ) ; this . subjectEncoding = encoding ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { @link EmailMessage } . [CODESPLIT] public T message ( final String text , final String mimeType , final String encoding ) { return message ( new EmailMessage ( text , mimeType , encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds plain message text . [CODESPLIT] public T textMessage ( final String text , final String encoding ) { return message ( new EmailMessage ( text , MimeTypes . MIME_TEXT_PLAIN , encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds HTML message . [CODESPLIT] public T htmlMessage ( final String html , final String encoding ) { return message ( new EmailMessage ( html , MimeTypes . MIME_TEXT_HTML , encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets header value . [CODESPLIT] public T header ( final String name , final String value ) { headers . put ( name , value ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets headers . [CODESPLIT] public T headers ( final Map < String , String > headersToSet ) { headers . putAll ( headersToSet ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets headers . [CODESPLIT] public T headers ( final Enumeration < Header > headersToSet ) { while ( headersToSet . hasMoreElements ( ) ) { final Header header = headersToSet . nextElement ( ) ; header ( header . getName ( ) , header . getValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds { @link EmailAttachment } s . [CODESPLIT] protected T storeAttachments ( final List < EmailAttachment < ? extends DataSource > > attachments ) { this . attachments . addAll ( attachments ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds { @link EmailAttachment } s . [CODESPLIT] public T attachments ( final List < EmailAttachment < ? extends DataSource > > attachments ) { for ( final EmailAttachment < ? > attachment : attachments ) { attachment ( attachment ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds { @link EmailAttachment } . Content ID will be set to { @code null } . [CODESPLIT] public T attachment ( final EmailAttachment < ? extends DataSource > attachment ) { attachment . setContentId ( null ) ; return storeAttachment ( attachment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attaches the embedded attachment : Content ID will be set if missing from attachment s file name . [CODESPLIT] public T embeddedAttachment ( final EmailAttachmentBuilder builder ) { builder . setContentIdFromNameIfMissing ( ) ; // https://github.com/oblac/jodd/issues/546 // https://github.com/oblac/jodd/issues/404#issuecomment-297011351 // content disposition will be set to \"inline\" builder . inline ( true ) ; return embeddedAttachment ( builder . buildByteArrayDataSource ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Embed { @link EmailAttachment } to last message . No header is changed . [CODESPLIT] public T embeddedAttachment ( final EmailAttachment < ? extends DataSource > attachment ) { storeAttachment ( attachment ) ; final List < EmailMessage > messages = messages ( ) ; final int size = messages . size ( ) ; if ( size > 1 ) { // Add to last message final int lastMessagePos = size - 1 ; final EmailMessage lastMessage = messages . get ( lastMessagePos ) ; attachment . setEmbeddedMessage ( lastMessage ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- helper [CODESPLIT] protected EmailAddress [ ] valueOrEmptyArray ( EmailAddress [ ] arr ) { if ( arr == null ) { arr = EmailAddress . EMPTY_ARRAY ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns system property . If key is not available returns the default value . [CODESPLIT] public static String get ( final String name , final String defaultValue ) { Objects . requireNonNull ( name ) ; String value = null ; try { if ( System . getSecurityManager ( ) == null ) { value = System . getProperty ( name ) ; } else { value = AccessController . doPrivileged ( ( PrivilegedAction < String > ) ( ) -> System . getProperty ( name ) ) ; } } catch ( Exception ignore ) { } if ( value == null ) { return defaultValue ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns system property as boolean . [CODESPLIT] public static boolean getBoolean ( final String name , final boolean defaultValue ) { String value = get ( name ) ; if ( value == null ) { return defaultValue ; } value = value . trim ( ) . toLowerCase ( ) ; switch ( value ) { case \"true\" : case \"yes\" : case \"1\" : case \"on\" : return true ; case \"false\" : case \"no\" : case \"0\" : case \"off\" : return false ; default : return defaultValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns system property as an int . [CODESPLIT] public static long getInt ( final String name , final int defaultValue ) { String value = get ( name ) ; if ( value == null ) { return defaultValue ; } value = value . trim ( ) . toLowerCase ( ) ; try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException nfex ) { return defaultValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns system property as a long . [CODESPLIT] public static long getLong ( final String name , final long defaultValue ) { String value = get ( name ) ; if ( value == null ) { return defaultValue ; } value = value . trim ( ) . toLowerCase ( ) ; try { return Long . parseLong ( value ) ; } catch ( NumberFormatException nfex ) { return defaultValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes parsing on { [CODESPLIT] public Jerry parse ( final char [ ] content ) { Document doc = domBuilder . parse ( content ) ; return new Jerry ( domBuilder , doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes parsing on { [CODESPLIT] public Jerry parse ( String content ) { if ( content == null ) { content = StringPool . EMPTY ; } Document doc = domBuilder . parse ( content ) ; return new Jerry ( domBuilder , doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends single { [CODESPLIT] public void append ( final float element ) { if ( offset - buffer . length >= 0 ) { grow ( offset ) ; } buffer [ offset ++ ] = element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends { [CODESPLIT] public FastFloatBuffer append ( final float [ ] array , final int off , final int len ) { if ( offset + len - buffer . length > 0 ) { grow ( offset + len ) ; } System . arraycopy ( array , off , buffer , offset , len ) ; offset += len ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastFloatBuffer append ( final FastFloatBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if type name equals param type . [CODESPLIT] boolean isEqualTypeName ( final Type argumentType , final Class paramType ) { String s = argumentType . getClassName ( ) ; if ( s . endsWith ( ARRAY ) ) { // arrays detected String prefix = s . substring ( 0 , s . length ( ) - 2 ) ; String bytecodeSymbol = primitives . get ( prefix ) ; if ( bytecodeSymbol != null ) { s = ' ' + bytecodeSymbol ; } else { s = \"[L\" + prefix + ' ' ; } } return s . equals ( paramType . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns method parameters once when method is parsed . If method has no parameters an empty array is returned . [CODESPLIT] MethodParameter [ ] getResolvedParameters ( ) { if ( paramExtractor == null ) { return MethodParameter . EMPTY_ARRAY ; } if ( ! paramExtractor . debugInfoPresent ) { throw new ParamoException ( \"Parameter names not available for method: \" + declaringClass . getName ( ) + ' ' + methodName ) ; } return paramExtractor . getMethodParameters ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes key and a value . [CODESPLIT] protected int serializeKeyValue ( final JsonContext jsonContext , final Path currentPath , final Object key , final Object value , int count ) { if ( ( value == null ) && jsonContext . isExcludeNulls ( ) ) { return count ; } if ( key != null ) { currentPath . push ( key . toString ( ) ) ; } else { currentPath . push ( StringPool . NULL ) ; } // check if we should include the field boolean include = true ; if ( value != null ) { // + all collections are not serialized by default include = jsonContext . matchIgnoredPropertyTypes ( value . getClass ( ) , false , include ) ; // + path queries: excludes/includes include = jsonContext . matchPathToQueries ( include ) ; } // done if ( ! include ) { currentPath . pop ( ) ; return count ; } if ( key == null ) { jsonContext . pushName ( null , count > 0 ) ; } else { jsonContext . pushName ( key . toString ( ) , count > 0 ) ; } jsonContext . serialize ( value ) ; if ( jsonContext . isNamePopped ( ) ) { count ++ ; } currentPath . pop ( ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups value as an alias and if not found as a default alias . [CODESPLIT] protected String lookupAlias ( final String alias ) { String value = actionsManager . lookupPathAlias ( alias ) ; if ( value == null ) { ActionRuntime cfg = actionsManager . lookup ( alias ) ; if ( cfg != null ) { value = cfg . getActionPath ( ) ; } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns resolved alias result value or passed on if alias doesn t exist . [CODESPLIT] protected String resolveAlias ( final String value ) { final StringBuilder result = new StringBuilder ( value . length ( ) ) ; int i = 0 ; int len = value . length ( ) ; while ( i < len ) { int ndx = value . indexOf ( ' ' , i ) ; if ( ndx == - 1 ) { // alias markers not found if ( i == 0 ) { // try whole string as an alias String alias = lookupAlias ( value ) ; return ( alias != null ? alias : value ) ; } else { result . append ( value . substring ( i ) ) ; } break ; } // alias marked found result . append ( value . substring ( i , ndx ) ) ; ndx ++ ; int ndx2 = value . indexOf ( ' ' , ndx ) ; String aliasName = ( ndx2 == - 1 ? value . substring ( ndx ) : value . substring ( ndx , ndx2 ) ) ; // process alias String alias = lookupAlias ( aliasName ) ; if ( alias != null ) { result . append ( alias ) ; } else { // alias not found if ( log . isWarnEnabled ( ) ) { log . warn ( \"Alias not found: \" + aliasName ) ; } } i = ndx2 + 1 ; } // fix prefix '//' - may happened when aliases are used i = 0 ; len = result . length ( ) ; while ( i < len ) { if ( result . charAt ( i ) != ' ' ) { break ; } i ++ ; } if ( i > 1 ) { return result . substring ( i - 1 , len ) ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves result path . [CODESPLIT] public ResultPath resolveResultPath ( String path , String value ) { boolean absolutePath = false ; if ( value != null ) { // [*] resolve alias in value value = resolveAlias ( value ) ; // [*] absolute paths if ( StringUtil . startsWithChar ( value , ' ' ) ) { absolutePath = true ; int dotNdx = value . indexOf ( \"..\" ) ; if ( dotNdx != - 1 ) { path = value . substring ( 0 , dotNdx ) ; value = value . substring ( dotNdx + 2 ) ; } else { path = value ; value = null ; } } else { // [*] resolve # in value and path int i = 0 ; while ( i < value . length ( ) ) { if ( value . charAt ( i ) != ' ' ) { break ; } int dotNdx = MadvocUtil . lastIndexOfSlashDot ( path ) ; if ( dotNdx != - 1 ) { // dot found path = path . substring ( 0 , dotNdx ) ; } i ++ ; } if ( i > 0 ) { // remove # from value value = value . substring ( i ) ; // [*] update path and value if ( StringUtil . startsWithChar ( value , ' ' ) ) { value = value . substring ( 1 ) ; } else { int dotNdx = value . indexOf ( \"..\" ) ; if ( dotNdx != - 1 ) { path += ' ' + value . substring ( 0 , dotNdx ) ; value = value . substring ( dotNdx + 2 ) ; } else { if ( value . length ( ) > 0 ) { if ( StringUtil . endsWithChar ( path , ' ' ) ) { path += value ; } else { path += ' ' + value ; } } value = null ; } } } } } if ( ! absolutePath ) { if ( resultPathPrefix != null ) { path = resultPathPrefix + path ; } } return new ResultPath ( path , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves result path as a string when parts are not important and when only full string matters . Additional alias resolving on full path is done . [CODESPLIT] public String resolveResultPathString ( final String path , final String value ) { final ResultPath resultPath = resolveResultPath ( path , value ) ; final String result = resultPath . pathValue ( ) ; return resolveAlias ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates last dot after the last slash or just slash . [CODESPLIT] public static int lastIndexOfSlashDot ( final String str ) { int slashNdx = str . lastIndexOf ( ' ' ) ; int dotNdx = StringUtil . lastIndexOf ( str , ' ' , str . length ( ) , slashNdx ) ; if ( dotNdx == - 1 ) { if ( slashNdx == - 1 ) { return - 1 ; } slashNdx ++ ; if ( slashNdx < str . length ( ) - 1 ) { dotNdx = slashNdx ; } else { dotNdx = - 1 ; } } return dotNdx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates last index of dot after the optional last slash . [CODESPLIT] public static int lastIndexOfDotAfterSlash ( final String str ) { int slashNdx = str . lastIndexOf ( ' ' ) ; slashNdx ++ ; return StringUtil . lastIndexOf ( str , ' ' , str . length ( ) , slashNdx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates first dot after the last slash . [CODESPLIT] public static int indexOfDotAfterSlash ( final String str ) { int slashNdx = str . lastIndexOf ( ' ' ) ; if ( slashNdx == - 1 ) { slashNdx = 0 ; } return str . indexOf ( ' ' , slashNdx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes last CamelWord [CODESPLIT] public static String stripLastCamelWord ( String name ) { int ndx = name . length ( ) - 1 ; while ( ndx >= 0 ) { if ( CharUtil . isUppercaseAlpha ( name . charAt ( ndx ) ) ) { break ; } ndx -- ; } if ( ndx >= 0 ) { name = name . substring ( 0 , ndx ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns matched name or <code > null< / code > if name is not matched . <p > Matches if attribute name matches the required field name . If the match is positive injection is performed on the field . <p > Parameter name matches field name if param name starts with field name and has either . or [ after the field name . <p > Returns real property name once when name is matched . [CODESPLIT] public String matchedName ( final String value ) { // match if ( ! value . startsWith ( name ) ) { return null ; } final int requiredLen = name . length ( ) ; if ( value . length ( ) >= requiredLen + 1 ) { final char c = value . charAt ( requiredLen ) ; if ( ( c != ' ' ) && ( c != ' ' ) ) { return null ; } } // get param if ( targetName == null ) { return value ; } return targetName + value . substring ( name . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the { [CODESPLIT] public String encode ( final SimTok simTok ) { final String json = JsonSerializer . create ( ) . deep ( true ) . serialize ( simTok ) ; final String p1 = Base64 . encodeToString ( \"JoddSimTok\" + SALT_ROUNDS ) ; final String p2 = Base64 . encodeToString ( json ) ; final String salt = BCrypt . gensalt ( SALT_ROUNDS ) ; final String p3 = BCrypt . hashpw ( p1 + \".\" + p2 + \".\" + SECRET , salt ) ; return p1 + \".\" + p2 + \".\" + p3 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the String to the { [CODESPLIT] public SimTok decode ( final String token ) { final int ndx = token . indexOf ( ' ' ) ; final String p1 = token . substring ( 0 , ndx ) ; final int ndx2 = token . indexOf ( ' ' , ndx + 1 ) ; final String p2 = token . substring ( ndx + 1 , ndx2 ) ; final String p3 = token . substring ( ndx2 + 1 ) ; if ( ! BCrypt . checkpw ( p1 + \".\" + p2 + \".\" + SECRET , p3 ) ) { return null ; } final String p2Decoded = Base64 . decodeToString ( p2 ) ; return JsonParser . create ( ) . parse ( p2Decoded , SimTok . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves table name from a type . If type is annotated table name will be read from annotation value . If this value is empty or if type is not annotated table name will be set to wildcard pattern * ( to match all tables ) . [CODESPLIT] public static String resolveTableName ( final Class < ? > type , final TableNamingStrategy tableNamingStrategy ) { String tableName = null ; final DbTable dbTable = type . getAnnotation ( DbTable . class ) ; if ( dbTable != null ) { tableName = dbTable . value ( ) . trim ( ) ; } if ( ( tableName == null ) || ( tableName . length ( ) == 0 ) ) { tableName = tableNamingStrategy . convertEntityNameToTableName ( type ) ; } else { if ( ! tableNamingStrategy . isStrictAnnotationNames ( ) ) { tableName = tableNamingStrategy . applyToTableName ( tableName ) ; } } return quoteIfRequired ( tableName , tableNamingStrategy . isAlwaysQuoteNames ( ) , tableNamingStrategy . getQuoteChar ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves schema name from a type . Uses default schema name if not specified . [CODESPLIT] public static String resolveSchemaName ( final Class < ? > type , final String defaultSchemaName ) { String schemaName = null ; final DbTable dbTable = type . getAnnotation ( DbTable . class ) ; if ( dbTable != null ) { schemaName = dbTable . schema ( ) . trim ( ) ; } if ( ( schemaName == null ) || ( schemaName . length ( ) == 0 ) ) { schemaName = defaultSchemaName ; } return schemaName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if class is annotated with <code > DbTable< / code > annotation . [CODESPLIT] public static boolean resolveIsAnnotated ( final Class < ? > type ) { DbTable dbTable = type . getAnnotation ( DbTable . class ) ; return dbTable != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves column descriptor from property . If property is annotated value will be read from annotation . If property is not annotated then property will be ignored if entity is annotated . Otherwise column name is generated from the property name . [CODESPLIT] public static DbEntityColumnDescriptor resolveColumnDescriptors ( final DbEntityDescriptor dbEntityDescriptor , final PropertyDescriptor property , final boolean isAnnotated , final ColumnNamingStrategy columnNamingStrategy ) { String columnName = null ; boolean isId = false ; Class < ? extends SqlType > sqlTypeClass = null ; // read ID annotation DbId dbId = null ; if ( property . getFieldDescriptor ( ) != null ) { dbId = property . getFieldDescriptor ( ) . getField ( ) . getAnnotation ( DbId . class ) ; } if ( dbId == null && property . getReadMethodDescriptor ( ) != null ) { dbId = property . getReadMethodDescriptor ( ) . getMethod ( ) . getAnnotation ( DbId . class ) ; } if ( dbId == null && property . getWriteMethodDescriptor ( ) != null ) { dbId = property . getWriteMethodDescriptor ( ) . getMethod ( ) . getAnnotation ( DbId . class ) ; } if ( dbId != null ) { columnName = dbId . value ( ) . trim ( ) ; sqlTypeClass = dbId . sqlType ( ) ; isId = true ; } else { DbColumn dbColumn = null ; if ( property . getFieldDescriptor ( ) != null ) { dbColumn = property . getFieldDescriptor ( ) . getField ( ) . getAnnotation ( DbColumn . class ) ; } if ( dbColumn == null && property . getReadMethodDescriptor ( ) != null ) { dbColumn = property . getReadMethodDescriptor ( ) . getMethod ( ) . getAnnotation ( DbColumn . class ) ; } if ( dbColumn == null && property . getWriteMethodDescriptor ( ) != null ) { dbColumn = property . getWriteMethodDescriptor ( ) . getMethod ( ) . getAnnotation ( DbColumn . class ) ; } if ( dbColumn != null ) { columnName = dbColumn . value ( ) . trim ( ) ; sqlTypeClass = dbColumn . sqlType ( ) ; } else { if ( isAnnotated ) { return null ; } } } if ( StringUtil . isEmpty ( columnName ) ) { // default annotation value columnName = columnNamingStrategy . convertPropertyNameToColumnName ( property . getName ( ) ) ; } else { if ( ! columnNamingStrategy . isStrictAnnotationNames ( ) ) { columnName = columnNamingStrategy . applyToColumnName ( columnName ) ; } } if ( sqlTypeClass == SqlType . class ) { sqlTypeClass = null ; } return new DbEntityColumnDescriptor ( dbEntityDescriptor , quoteIfRequired ( columnName , columnNamingStrategy . isAlwaysQuoteNames ( ) , columnNamingStrategy . getQuoteChar ( ) ) , property . getName ( ) , property . getType ( ) , isId , sqlTypeClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves mapped types from { [CODESPLIT] public static Class [ ] resolveMappedTypes ( final Class type ) { DbMapTo dbMapTo = ( DbMapTo ) type . getAnnotation ( DbMapTo . class ) ; if ( dbMapTo == null ) { return null ; } return dbMapTo . value ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- privates [CODESPLIT] private static String quoteIfRequired ( final String name , final boolean alwaysQuoteNames , final char quoteChar ) { if ( StringUtil . detectQuoteChar ( name ) != 0 ) { return name ; // already quoted } if ( alwaysQuoteNames && quoteChar != 0 ) { return quoteChar + name + quoteChar ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the cipher using the key and the tweak value . [CODESPLIT] public void init ( final long [ ] key , final long [ ] tweak ) { final int newNw = key . length ; // only create new arrays if the value of N{w} changes (different key size) if ( nw != newNw ) { nw = newNw ; switch ( nw ) { case WORDS_4 : pi = PI4 ; rpi = RPI4 ; r = R4 ; break ; case WORDS_8 : pi = PI8 ; rpi = RPI8 ; r = R8 ; break ; case WORDS_16 : pi = PI16 ; rpi = RPI16 ; r = R16 ; break ; default : throw new RuntimeException ( \"Invalid threefish key\" ) ; } this . k = new long [ nw + 1 ] ; // instantiation of these fields here for performance reasons vd = new long [ nw ] ; // v is the intermediate value v{d} at round d ed = new long [ nw ] ; // ed is the value of e{d} at round d fd = new long [ nw ] ; // fd is the value of f{d} at round d ksd = new long [ nw ] ; // ksd is the value of k{s} at round d } System . arraycopy ( key , 0 , this . k , 0 , key . length ) ; long knw = EXTENDED_KEY_SCHEDULE_CONST ; for ( int i = 0 ; i < nw ; i ++ ) { knw ^= this . k [ i ] ; } this . k [ nw ] = knw ; // set tweak values t [ 0 ] = tweak [ 0 ] ; t [ 1 ] = tweak [ 1 ] ; t [ 2 ] = t [ 0 ] ^ t [ 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the E ( K T P ) function . The K and T values should be set previously using the init () method . This version is the 64 bit implementation of Threefish . [CODESPLIT] public void blockEncrypt ( final long [ ] p , final long [ ] c ) { // initial value = plain System . arraycopy ( p , 0 , vd , 0 , nw ) ; for ( int d = 0 ; d < nr ; d ++ ) { // do the rounds // calculate e{d,i} if ( d % SUBKEY_INTERVAL == 0 ) { final int s = d / SUBKEY_INTERVAL ; keySchedule ( s ) ; for ( int i = 0 ; i < nw ; i ++ ) { ed [ i ] = vd [ i ] + ksd [ i ] ; } } else { System . arraycopy ( vd , 0 , ed , 0 , nw ) ; } for ( int j = 0 ; j < nw / 2 ; j ++ ) { x [ 0 ] = ed [ j * 2 ] ; x [ 1 ] = ed [ j * 2 + 1 ] ; mix ( j , d ) ; fd [ j * 2 ] = y [ 0 ] ; fd [ j * 2 + 1 ] = y [ 1 ] ; } for ( int i = 0 ; i < nw ; i ++ ) { vd [ i ] = fd [ pi [ i ] ] ; } } // do the last keyschedule keySchedule ( nr / SUBKEY_INTERVAL ) ; for ( int i = 0 ; i < nw ; i ++ ) { c [ i ] = vd [ i ] + ksd [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the MIX function . [CODESPLIT] private void mix ( final int j , final int d ) { y [ 0 ] = x [ 0 ] + x [ 1 ] ; final long rotl = r [ d % DEPTH_OF_D_IN_R ] [ j ] ; // java left rotation for a long y [ 1 ] = ( x [ 1 ] << rotl ) | ( x [ 1 ] >>> ( Long . SIZE - rotl ) ) ; y [ 1 ] ^= y [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the D ( K T C ) function . The K and T values should be set previously using the init () method . This version is the 64 bit implementation of Threefish . [CODESPLIT] public void blockDecrypt ( final long [ ] c , final long [ ] p ) { // initial value = plain System . arraycopy ( c , 0 , vd , 0 , nw ) ; for ( int d = nr ; d > 0 ; d -- ) { // do the rounds // calculate e{d,i} if ( d % SUBKEY_INTERVAL == 0 ) { final int s = d / SUBKEY_INTERVAL ; keySchedule ( s ) ; // calculate same keys for ( int i = 0 ; i < nw ; i ++ ) { fd [ i ] = vd [ i ] - ksd [ i ] ; } } else { System . arraycopy ( vd , 0 , fd , 0 , nw ) ; } for ( int i = 0 ; i < nw ; i ++ ) { ed [ i ] = fd [ rpi [ i ] ] ; } for ( int j = 0 ; j < nw / 2 ; j ++ ) { y [ 0 ] = ed [ j * 2 ] ; y [ 1 ] = ed [ j * 2 + 1 ] ; demix ( j , d - 1 ) ; vd [ j * 2 ] = x [ 0 ] ; vd [ j * 2 + 1 ] = x [ 1 ] ; } } // do the first keyschedule keySchedule ( 0 ) ; for ( int i = 0 ; i < nw ; i ++ ) { p [ i ] = vd [ i ] - ksd [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the un - MIX function . [CODESPLIT] private void demix ( final int j , final int d ) { y [ 1 ] ^= y [ 0 ] ; final long rotr = r [ d % DEPTH_OF_D_IN_R ] [ j ] ; // NOTE performance: darn, creation on stack! // right shift x [ 1 ] = ( y [ 1 ] << ( Long . SIZE - rotr ) ) | ( y [ 1 ] >>> rotr ) ; x [ 0 ] = y [ 0 ] - x [ 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the subkeys . [CODESPLIT] private void keySchedule ( final int s ) { for ( int i = 0 ; i < nw ; i ++ ) { // just put in the main key first ksd [ i ] = k [ ( s + i ) % ( nw + 1 ) ] ; // don't add anything for i = 0,...,Nw - 4 if ( i == nw - 3 ) { // second to last ksd [ i ] += t [ s % TWEAK_VALUES ] ; } else if ( i == nw - 2 ) { // first to last ksd [ i ] += t [ ( s + 1 ) % TWEAK_VALUES ] ; } else if ( i == nw - 1 ) { // last ksd [ i ] += s ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes cipher in a simple way . [CODESPLIT] public void init ( final String keyMessage , final long tweak1 , final long tweak2 ) { long [ ] tweak = new long [ ] { tweak1 , tweak2 } ; byte [ ] key = new byte [ blockSize / Byte . SIZE ] ; byte [ ] keyData = StringUtil . getBytes ( keyMessage ) ; System . arraycopy ( keyData , 0 , key , 0 , key . length < keyData . length ? key . length : keyData . length ) ; init ( bytesToLongs ( key ) , tweak ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encrypts a block . [CODESPLIT] @ Override public byte [ ] encryptBlock ( final byte [ ] content , final int offset ) { long [ ] contentBlock = bytesToLongs ( content , offset , blockSizeInBytes ) ; long [ ] encryptedBlock = new long [ blockSize / Long . SIZE ] ; blockEncrypt ( contentBlock , encryptedBlock ) ; return longsToBytes ( encryptedBlock ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts segment of byte array into long array . [CODESPLIT] protected static long [ ] bytesToLongs ( final byte [ ] ba , final int offset , final int size ) { long [ ] result = new long [ size >> 3 ] ; int i8 = offset ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = Bits . getLong ( ba , i8 ) ; i8 += 8 ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts char digit into integer value . Accepts numeric chars ( 0 - 9 ) as well as letter ( A - z ) . [CODESPLIT] public static int parseDigit ( final char digit ) { if ( ( digit >= ' ' ) && ( digit <= ' ' ) ) { return digit - ' ' ; } if ( CharUtil . isLowercaseAlpha ( digit ) ) { return 10 + digit - ' ' ; } return 10 + digit - ' ' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter initialization . [CODESPLIT] @ Override public void init ( final FilterConfig filterConfig ) throws ServletException { final ServletContext servletContext = filterConfig . getServletContext ( ) ; madvoc = Madvoc . get ( servletContext ) ; if ( madvoc != null ) { log = LoggerFactory . getLogger ( this . getClass ( ) ) ; madvocController = madvoc . webapp ( ) . madvocContainer ( ) . requestComponent ( MadvocController . class ) ; return ; } final WebApp webApp = WebApp . get ( servletContext ) ; if ( webApp != null ) { log = LoggerFactory . getLogger ( this . getClass ( ) ) ; madvocController = webApp . madvocContainer ( ) . requestComponent ( MadvocController . class ) ; return ; } throw new ServletException ( \"Neither Madvoc or WebApp found! Use MadvocContextListener to create Madvoc or \" + \"WebApp#withServletContext() to make it available.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds { [CODESPLIT] @ Override public void doFilter ( final ServletRequest req , final ServletResponse res , final FilterChain chain ) throws IOException , ServletException { HttpServletRequest request = ( HttpServletRequest ) req ; HttpServletResponse response = ( HttpServletResponse ) res ; String actionPath = DispatcherUtil . getServletPath ( request ) ; try { MadvocResponseWrapper madvocResponse = new MadvocResponseWrapper ( response ) ; actionPath = madvocController . invoke ( actionPath , request , madvocResponse ) ; } catch ( Exception ex ) { log . error ( \"Invoking action path failed: \" + actionPath , ex ) ; throw new ServletException ( ex ) ; } if ( actionPath != null ) { // action path is not consumed boolean pathProcessed = processUnhandledPath ( actionPath , req , res ) ; if ( ! pathProcessed ) { chain . doFilter ( request , response ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses email address . Returns { [CODESPLIT] public ParsedAddress parse ( String email ) { email = email . trim ( ) ; // match all final Matcher mailboxMatcher = MAILBOX_PATTERN ( ) . matcher ( email ) ; final boolean mailboxMatcherMatches = mailboxMatcher . matches ( ) ; final String [ ] mailboxMatcherParts = mailboxMatcherMatches ? _calcMatcherParts ( mailboxMatcher ) : null ; final Matcher returnPathMatcher = RETURN_PATH_PATTERN ( ) . matcher ( email ) ; final boolean returnPathMatches = returnPathMatcher . matches ( ) ; // extract String personalName = null ; String localPart = null ; String domain = null ; InternetAddress internetAddress = null ; String returnPathAddress = null ; if ( mailboxMatcherMatches ) { personalName = mailboxMatcherParts [ 0 ] ; localPart = mailboxMatcherParts [ 1 ] ; domain = mailboxMatcherParts [ 2 ] ; internetAddress = pullFromGroups ( mailboxMatcher ) ; } if ( returnPathMatches ) { if ( internetAddress != null ) { returnPathAddress = internetAddress . getAddress ( ) ; } else { returnPathAddress = StringPool . EMPTY ; } } return new ParsedAddress ( mailboxMatcherMatches , personalName , localPart , domain , internetAddress , returnPathMatches , returnPathAddress ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenient shortcut of { [CODESPLIT] public InternetAddress parseToInternetAddress ( final String email ) { final ParsedAddress parsedAddress = parse ( email ) ; if ( ! parsedAddress . isValid ( ) ) { return null ; } return parsedAddress . getInternetAddress ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenient shortcut of { [CODESPLIT] public EmailAddress parseToEmailAddress ( final String email ) { final ParsedAddress parsedAddress = parse ( email ) ; if ( ! parsedAddress . isValid ( ) ) { return null ; } return new EmailAddress ( parsedAddress . getPersonalName ( ) , parsedAddress . getLocalPart ( ) + ' ' + parsedAddress . getDomain ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds all regexp patterns . [CODESPLIT] private void buildPatterns ( ) { // http://tools.ietf.org/html/rfc2822 // RFC 2822 2.2.2 Structured Header Field Bodies final String CRLF = \"\\\\r\\\\n\" ; final String WSP = \"[ \\\\t]\" ; final String FWSP = \"(?:\" + WSP + \"*\" + CRLF + \")?\" + WSP + \"+\" ; // RFC 2822 3.2.1 Primitive tokens final String D_QUOTE = \"\\\\\\\"\" ; final String NO_WS_CTL = \"\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F\" ; final String ASCII_TEXT = \"[\\\\x01-\\\\x09\\\\x0B\\\\x0C\\\\x0E-\\\\x7F]\" ; // RFC 2822 3.2.2 Quoted characters final String QUOTED_PAIR = \"(?:\\\\\\\\\" + ASCII_TEXT + \")\" ; // RFC 2822 3.2.3 CFWS specification final String C_TEXT = \"[\" + NO_WS_CTL + \"\\\\!-\\\\'\\\\*-\\\\[\\\\]-\\\\~]\" ; final String C_CONTENT = C_TEXT + \"|\" + QUOTED_PAIR ; // + \"|\" + comment; final String COMMENT = \"\\\\((?:(?:\" + FWSP + \")?\" + C_CONTENT + \")*(?:\" + FWSP + \")?\\\\)\" ; final String CFWS = \"(?:(?:\" + FWSP + \")?\" + COMMENT + \")*(?:(?:(?:\" + FWSP + \")?\" + COMMENT + \")|(?:\" + FWSP + \"))\" ; // RFC 2822 3.2.4 Atom final String A_TEXT = \"[a-zA-Z0-9\\\\!\\\\#-\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^-\\\\`\\\\{-\\\\~\" + ( ALLOW_DOT_IN_ATEXT ? \"\\\\.\" : \"\" ) + ( ALLOW_SQUARE_BRACKETS_IN_ATEXT ? \"\\\\[\\\\]\" : \"\" ) + \"]\" ; final String REGULAR_A_TEXT = \"[a-zA-Z0-9\\\\!\\\\#-\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^-\\\\`\\\\{-\\\\~]\" ; final String ATOM = \"(?:\" + CFWS + \")?\" + A_TEXT + \"+\" + \"(?:\" + CFWS + \")?\" ; final String DOT_ATOM_TEXT = REGULAR_A_TEXT + \"+\" + \"(?:\" + \"\\\\.\" + REGULAR_A_TEXT + \"+)*\" ; final String CAP_DOT_ATOM_NO_CFWS = \"(?:\" + CFWS + \")?(\" + DOT_ATOM_TEXT + \")(?:\" + CFWS + \")?\" ; final String CAP_DOT_ATOM_TRAILING_CFWS = \"(?:\" + CFWS + \")?(\" + DOT_ATOM_TEXT + \")(\" + CFWS + \")?\" ; // RFC 2822 3.2.5 Quoted strings final String Q_TEXT = \"[\" + NO_WS_CTL + \"\\\\!\\\\#-\\\\[\\\\]-\\\\~]\" ; final String LOCAL_PART_Q_TEXT = \"[\" + NO_WS_CTL + ( ALLOW_PARENS_IN_LOCALPART ? \"\\\\!\\\\#-\\\\[\\\\]-\\\\~]\" : \"\\\\!\\\\#-\\\\'\\\\*-\\\\[\\\\]-\\\\~]\" ) ; final String Q_CONTENT = \"(?:\" + Q_TEXT + \"|\" + QUOTED_PAIR + \")\" ; final String LOCAL_PART_Q_CONTENT = \"(?>\" + LOCAL_PART_Q_TEXT + \"|\" + QUOTED_PAIR + \")\" ; final String QUOTED_STRING_WOCFWS = D_QUOTE + \"(?>(?:\" + FWSP + \")?\" + Q_CONTENT + \")*(?:\" + FWSP + \")?\" + D_QUOTE ; final String QUOTED_STRING = \"(?:\" + CFWS + \")?\" + QUOTED_STRING_WOCFWS + \"(?:\" + CFWS + \")?\" ; final String LOCAL_PART_QUOTED_STRING = \"(?:\" + CFWS + \")?(\" + D_QUOTE + \"(?:(?:\" + FWSP + \")?\" + LOCAL_PART_Q_CONTENT + \")*(?:\" + FWSP + \")?\" + D_QUOTE + \")(?:\" + CFWS + \")?\" ; // RFC 2822 3.2.6 Miscellaneous tokens final String WORD = \"(?:(?:\" + ATOM + \")|(?:\" + QUOTED_STRING + \"))\" ; // by 2822: phrase = 1*word / obs-phrase // implemented here as: phrase = word (FWS word)* // so that aaaa can't be four words, which can cause tons of recursive backtracking final String PHRASE = WORD + \"(?:(?:\" + FWSP + \")\" + WORD + \")*\" ; // RFC 1035 tokens for domain names final String LETTER = \"[a-zA-Z]\" ; final String LET_DIG = \"[a-zA-Z0-9]\" ; final String LET_DIG_HYP = \"[a-zA-Z0-9-]\" ; final String RFC_LABEL = LET_DIG + \"(?:\" + LET_DIG_HYP + \"{0,61}\" + LET_DIG + \")?\" ; final String RFC_1035_DOMAIN_NAME = RFC_LABEL + \"(?:\\\\.\" + RFC_LABEL + \")*\\\\.\" + LETTER + \"{2,6}\" ; // RFC 2822 3.4 Address specification final String D_TEXT = \"[\" + NO_WS_CTL + \"\\\\!-Z\\\\^-\\\\~]\" ; final String D_CONTENT = D_TEXT + \"|\" + QUOTED_PAIR ; final String CAP_DOMAIN_LITERAL_NO_CFWS = \"(?:\" + CFWS + \")?\" + \"(\\\\[\" + \"(?:(?:\" + FWSP + \")?(?:\" + D_CONTENT + \")+)*(?:\" + FWSP + \")?\\\\])\" + \"(?:\" + CFWS + \")?\" ; final String CAP_DOMAIN_LITERAL_TRAILING_CFWS = \"(?:\" + CFWS + \")?\" + \"(\\\\[\" + \"(?:(?:\" + FWSP + \")?(?:\" + D_CONTENT + \")+)*(?:\" + FWSP + \")?\\\\])\" + \"(\" + CFWS + \")?\" ; final String RFC_2822_DOMAIN = \"(?:\" + CAP_DOT_ATOM_NO_CFWS + \"|\" + CAP_DOMAIN_LITERAL_NO_CFWS + \")\" ; final String CAP_CFWSR_FC2822_DOMAIN = \"(?:\" + CAP_DOT_ATOM_TRAILING_CFWS + \"|\" + CAP_DOMAIN_LITERAL_TRAILING_CFWS + \")\" ; final String DOMAIN = ALLOW_DOMAIN_LITERALS ? RFC_2822_DOMAIN : \"(?:\" + CFWS + \")?(\" + RFC_1035_DOMAIN_NAME + \")(?:\" + CFWS + \")?\" ; final String CAP_CFWS_DOMAIN = ALLOW_DOMAIN_LITERALS ? CAP_CFWSR_FC2822_DOMAIN : \"(?:\" + CFWS + \")?(\" + RFC_1035_DOMAIN_NAME + \")(\" + CFWS + \")?\" ; final String LOCAL_PART = \"(\" + CAP_DOT_ATOM_NO_CFWS + \"|\" + LOCAL_PART_QUOTED_STRING + \")\" ; // uniqueAddrSpec exists so we can have a duplicate tree that has a capturing group // instead of a non-capturing group for the trailing CFWS after the domain token // that we wouldn't want if it was inside // an angleAddr. The matching should be otherwise identical. final String ADDR_SPEC = LOCAL_PART + \"@\" + DOMAIN ; final String UNIQUE_ADDR_SPEC = LOCAL_PART + \"@\" + CAP_CFWS_DOMAIN ; final String ANGLE_ADDR = \"(?:\" + CFWS + \")?<\" + ADDR_SPEC + \">(\" + CFWS + \")?\" ; final String NAME_ADDR = \"(\" + PHRASE + \")??(\" + ANGLE_ADDR + \")\" ; final String MAIL_BOX = ( ALLOW_QUOTED_IDENTIFIERS ? \"(\" + NAME_ADDR + \")|\" : \"\" ) + \"(\" + UNIQUE_ADDR_SPEC + \")\" ; final String RETURN_PATH = \"(?:(?:\" + CFWS + \")?<((?:\" + CFWS + \")?|\" + ADDR_SPEC + \")>(?:\" + CFWS + \")?)\" ; //private static final String mailboxList = \"(?:(?:\" + mailbox + \")(?:,(?:\" + mailbox + \"))*)\"; //private static final String groupPostfix = \"(?:\" + CFWS + \"|(?:\" + mailboxList + \")\" + \")?;(?:\" + CFWS + \")?\"; //private static final String groupPrefix = phrase + \":\"; //private static final String group = groupPrefix + groupPostfix; //private static final String address = \"(?:(?:\" + mailbox + \")|(?:\" + group + \"))\" // Java regex pattern for 2822 _MAILBOX_PATTERN = Pattern . compile ( MAIL_BOX ) ; _ADDR_SPEC_PATTERN = Pattern . compile ( ADDR_SPEC ) ; //final Pattern MAILBOX_LIST_PATTERN = Pattern.compile(mailboxList); _COMMENT_PATTERN = Pattern . compile ( COMMENT ) ; _QUOTED_STRING_WO_CFWS_PATTERN = Pattern . compile ( QUOTED_STRING_WOCFWS ) ; _RETURN_PATH_PATTERN = Pattern . compile ( RETURN_PATH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- utilities [CODESPLIT] private InternetAddress pullFromGroups ( final Matcher m ) { InternetAddress currentInternetAddress ; final String [ ] parts = _calcMatcherParts ( m ) ; if ( parts [ 1 ] == null || parts [ 2 ] == null ) { return null ; } // if for some reason you want to require that the result be re-parsable by // InternetAddress, you // could uncomment the appropriate stuff below, but note that not all the utility // functions use pullFromGroups; some call getMatcherParts directly. try { //currentInternetAddress = new InternetAddress(parts[0] + \" <\" + parts[1] + \"@\" + //                                 parts[2]+ \">\", true); // so it parses it OK, but since javamail doesn't extract too well // we make sure that the consistent parts // are correct currentInternetAddress = new InternetAddress ( ) ; currentInternetAddress . setPersonal ( parts [ 0 ] ) ; currentInternetAddress . setAddress ( parts [ 1 ] + \"@\" + parts [ 2 ] ) ; } catch ( final UnsupportedEncodingException uee ) { currentInternetAddress = null ; } return currentInternetAddress ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a string extract the first matched comment token as defined in 2822 trimmed ; return null on all errors or non - findings . <p > Note for future improvement : if COMMENT_PATTERN could handle nested comments then this should be able to as well but if this method were to be used to find the CFWS personal name ( see boolean option ) then such a nested comment would probably not be the one you were looking for? [CODESPLIT] private String getFirstComment ( final String text ) { if ( text == null ) { return null ; // important } final Matcher m = _COMMENT_PATTERN . matcher ( text ) ; if ( ! m . find ( ) ) { return null ; } return m . group ( ) . trim ( ) ; // must trim }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the string starts and ends with start and end char remove them otherwise return the string as it was passed in . [CODESPLIT] private static String removeAnyBounding ( final char s , final char e , final String str ) { if ( str == null || str . length ( ) < 2 ) { return str ; } if ( str . startsWith ( String . valueOf ( s ) ) && str . endsWith ( String . valueOf ( e ) ) ) { return str . substring ( 1 , str . length ( ) - 1 ) ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps action class and returns <code > MethRef< / code > object ( proxified target ) so user can choose the method . [CODESPLIT] protected < T > Methref < T > wrapTargetToMethref ( final Class < T > target ) { return Methref . on ( target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns path value . [CODESPLIT] public String path ( ) { if ( methref != null ) { final String methodName = methref . ref ( ) ; return target . getName ( ) + ' ' + methodName ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compresses a file into zlib archive . [CODESPLIT] public static File zlib ( final File file ) throws IOException { if ( file . isDirectory ( ) ) { throw new IOException ( \"Can't zlib folder\" ) ; } FileInputStream fis = new FileInputStream ( file ) ; Deflater deflater = new Deflater ( Deflater . BEST_COMPRESSION ) ; String zlibFileName = file . getAbsolutePath ( ) + ZLIB_EXT ; DeflaterOutputStream dos = new DeflaterOutputStream ( new FileOutputStream ( zlibFileName ) , deflater ) ; try { StreamUtil . copy ( fis , dos ) ; } finally { StreamUtil . close ( dos ) ; StreamUtil . close ( fis ) ; } return new File ( zlibFileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compresses a file into gzip archive . [CODESPLIT] public static File gzip ( final File file ) throws IOException { if ( file . isDirectory ( ) ) { throw new IOException ( \"Can't gzip folder\" ) ; } FileInputStream fis = new FileInputStream ( file ) ; String gzipName = file . getAbsolutePath ( ) + GZIP_EXT ; GZIPOutputStream gzos = new GZIPOutputStream ( new FileOutputStream ( gzipName ) ) ; try { StreamUtil . copy ( fis , gzos ) ; } finally { StreamUtil . close ( gzos ) ; StreamUtil . close ( fis ) ; } return new File ( gzipName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decompress gzip archive . [CODESPLIT] public static File ungzip ( final File file ) throws IOException { String outFileName = FileNameUtil . removeExtension ( file . getAbsolutePath ( ) ) ; File out = new File ( outFileName ) ; out . createNewFile ( ) ; FileOutputStream fos = new FileOutputStream ( out ) ; GZIPInputStream gzis = new GZIPInputStream ( new FileInputStream ( file ) ) ; try { StreamUtil . copy ( gzis , fos ) ; } finally { StreamUtil . close ( fos ) ; StreamUtil . close ( gzis ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zips a file or a folder . If adding a folder all its content will be added . [CODESPLIT] public static File zip ( final File file ) throws IOException { String zipFile = file . getAbsolutePath ( ) + ZIP_EXT ; return ZipBuilder . createZipFile ( zipFile ) . add ( file ) . recursive ( ) . save ( ) . toZipFile ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists zip content . [CODESPLIT] public static List < String > listZip ( final File zipFile ) throws IOException { List < String > entries = new ArrayList <> ( ) ; ZipFile zip = new ZipFile ( zipFile ) ; Enumeration zipEntries = zip . entries ( ) ; while ( zipEntries . hasMoreElements ( ) ) { ZipEntry entry = ( ZipEntry ) zipEntries . nextElement ( ) ; String entryName = entry . getName ( ) ; entries . add ( entryName ) ; } return Collections . unmodifiableList ( entries ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts zip file content to the target directory . [CODESPLIT] public static void unzip ( final String zipFile , final String destDir , final String ... patterns ) throws IOException { unzip ( new File ( zipFile ) , new File ( destDir ) , patterns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds single entry to ZIP output stream . [CODESPLIT] public static void addToZip ( final ZipOutputStream zos , final File file , String path , final String comment , final boolean recursive ) throws IOException { if ( ! file . exists ( ) ) { throw new FileNotFoundException ( file . toString ( ) ) ; } if ( path == null ) { path = file . getName ( ) ; } while ( path . length ( ) != 0 && path . charAt ( 0 ) == ' ' ) { path = path . substring ( 1 ) ; } boolean isDir = file . isDirectory ( ) ; if ( isDir ) { // add folder record if ( ! StringUtil . endsWithChar ( path , ' ' ) ) { path += ' ' ; } } ZipEntry zipEntry = new ZipEntry ( path ) ; zipEntry . setTime ( file . lastModified ( ) ) ; if ( comment != null ) { zipEntry . setComment ( comment ) ; } if ( isDir ) { zipEntry . setSize ( 0 ) ; zipEntry . setCrc ( 0 ) ; } zos . putNextEntry ( zipEntry ) ; if ( ! isDir ) { InputStream is = new FileInputStream ( file ) ; try { StreamUtil . copy ( is , zos ) ; } finally { StreamUtil . close ( is ) ; } } zos . closeEntry ( ) ; // continue adding if ( recursive && file . isDirectory ( ) ) { boolean noRelativePath = StringUtil . isEmpty ( path ) ; final File [ ] children = file . listFiles ( ) ; if ( children != null && children . length != 0 ) { for ( File child : children ) { String childRelativePath = ( noRelativePath ? StringPool . EMPTY : path ) + child . getName ( ) ; addToZip ( zos , child , childRelativePath , comment , recursive ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds byte content into the zip as a file . [CODESPLIT] public static void addToZip ( final ZipOutputStream zos , final byte [ ] content , String path , final String comment ) throws IOException { while ( path . length ( ) != 0 && path . charAt ( 0 ) == ' ' ) { path = path . substring ( 1 ) ; } if ( StringUtil . endsWithChar ( path , ' ' ) ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } ZipEntry zipEntry = new ZipEntry ( path ) ; zipEntry . setTime ( System . currentTimeMillis ( ) ) ; if ( comment != null ) { zipEntry . setComment ( comment ) ; } zos . putNextEntry ( zipEntry ) ; InputStream is = new ByteArrayInputStream ( content ) ; try { StreamUtil . copy ( is , zos ) ; } finally { StreamUtil . close ( is ) ; } zos . closeEntry ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns field descriptor . [CODESPLIT] public FieldDescriptor getFieldDescriptor ( final String name , final boolean declared ) { final FieldDescriptor fieldDescriptor = getFields ( ) . getFieldDescriptor ( name ) ; if ( fieldDescriptor != null ) { if ( ! fieldDescriptor . matchDeclared ( declared ) ) { return null ; } } return fieldDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public MethodDescriptor getMethodDescriptor ( final String name , final boolean declared ) { final MethodDescriptor methodDescriptor = getMethods ( ) . getMethodDescriptor ( name ) ; if ( ( methodDescriptor != null ) && methodDescriptor . matchDeclared ( declared ) ) { return methodDescriptor ; } return methodDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns property descriptor . Declared flag is matched on both read and write methods . [CODESPLIT] public PropertyDescriptor getPropertyDescriptor ( final String name , final boolean declared ) { PropertyDescriptor propertyDescriptor = getProperties ( ) . getPropertyDescriptor ( name ) ; if ( ( propertyDescriptor != null ) && propertyDescriptor . matchDeclared ( declared ) ) { return propertyDescriptor ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the default ctor or <code > null< / code > if not found . [CODESPLIT] public CtorDescriptor getDefaultCtorDescriptor ( final boolean declared ) { CtorDescriptor defaultCtor = getCtors ( ) . getDefaultCtor ( ) ; if ( ( defaultCtor != null ) && defaultCtor . matchDeclared ( declared ) ) { return defaultCtor ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the constructor identified by arguments or <code > null< / code > if not found . [CODESPLIT] public CtorDescriptor getCtorDescriptor ( final Class [ ] args , final boolean declared ) { CtorDescriptor ctorDescriptor = getCtors ( ) . getCtorDescriptor ( args ) ; if ( ( ctorDescriptor != null ) && ctorDescriptor . matchDeclared ( declared ) ) { return ctorDescriptor ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets bundle name for provided servlet request . [CODESPLIT] public static void setRequestBundleName ( final ServletRequest request , final String bundleName ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Bundle name for this request: \" + bundleName ) ; } request . setAttribute ( REQUEST_BUNDLE_NAME_ATTR , bundleName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves Locale to HTTP session . [CODESPLIT] public static void setSessionLocale ( final HttpSession session , final String localeCode ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Locale stored to session: \" + localeCode ) ; } Locale locale = Locale . forLanguageTag ( localeCode ) ; session . setAttribute ( SESSION_LOCALE_ATTR , locale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns current locale from session . s [CODESPLIT] public static Locale getSessionLocale ( final HttpSession session ) { Locale locale = ( Locale ) session . getAttribute ( SESSION_LOCALE_ATTR ) ; return locale == null ? MESSAGE_RESOLVER . getFallbackLocale ( ) : locale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { [CODESPLIT] @ Override public void contextInitialized ( final ServletContextEvent servletContextEvent ) { ServletContext servletContext = servletContextEvent . getServletContext ( ) ; madvoc = new Madvoc ( ) ; madvoc . configureWith ( servletContext ) ; madvoc . startWebApplication ( servletContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of param keys that belongs to provided bean . Optionally resolves the value of returned parameters . [CODESPLIT] public String [ ] filterParametersForBeanName ( String beanName , final boolean resolveReferenceParams ) { beanName = beanName + ' ' ; List < String > list = new ArrayList <> ( ) ; for ( Map . Entry < String , Object > entry : params . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( ! key . startsWith ( beanName ) ) { continue ; } list . add ( key ) ; if ( ! resolveReferenceParams ) { continue ; } // resolve all references String value = PropertiesUtil . resolveProperty ( params , key ) ; entry . setValue ( value ) ; } if ( list . isEmpty ( ) ) { return StringPool . EMPTY_ARRAY ; } else { return list . toArray ( new String [ 0 ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------------------------------- [CODESPLIT] @ Override public void visit ( final String name , final Object value ) { // Case of an element_value with a const_value_index, class_info_index or array_index field. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. ++ numElementValuePairs ; if ( useNamedValues ) { annotation . putShort ( symbolTable . addConstantUtf8 ( name ) ) ; } if ( value instanceof String ) { annotation . put12 ( ' ' , symbolTable . addConstantUtf8 ( ( String ) value ) ) ; } else if ( value instanceof Byte ) { annotation . put12 ( ' ' , symbolTable . addConstantInteger ( ( ( Byte ) value ) . byteValue ( ) ) . index ) ; } else if ( value instanceof Boolean ) { int booleanValue = ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ; annotation . put12 ( ' ' , symbolTable . addConstantInteger ( booleanValue ) . index ) ; } else if ( value instanceof Character ) { annotation . put12 ( ' ' , symbolTable . addConstantInteger ( ( ( Character ) value ) . charValue ( ) ) . index ) ; } else if ( value instanceof Short ) { annotation . put12 ( ' ' , symbolTable . addConstantInteger ( ( ( Short ) value ) . shortValue ( ) ) . index ) ; } else if ( value instanceof Type ) { annotation . put12 ( ' ' , symbolTable . addConstantUtf8 ( ( ( Type ) value ) . getDescriptor ( ) ) ) ; } else if ( value instanceof byte [ ] ) { byte [ ] byteArray = ( byte [ ] ) value ; annotation . put12 ( ' [ ' , byteArray . length ) ; for ( byte byteValue : byteArray ) { annotation . put12 ( ' ' , symbolTable . addConstantInteger ( byteValue ) . index ) ; } } else if ( value instanceof boolean [ ] ) { boolean [ ] booleanArray = ( boolean [ ] ) value ; annotation . put12 ( ' [ ' , booleanArray . length ) ; for ( boolean booleanValue : booleanArray ) { annotation . put12 ( ' Z ' , symbolTable . addConstantInteger ( booleanValue ? 1 : 0 ) . index ) ; } } else if ( value instanceof short [ ] ) { short [ ] shortArray = ( short [ ] ) value ; annotation . put12 ( ' [ ' , shortArray . length ) ; for ( short shortValue : shortArray ) { annotation . put12 ( ' S ' , symbolTable . addConstantInteger ( shortValue ) . index ) ; } } else if ( value instanceof char [ ] ) { char [ ] charArray = ( char [ ] ) value ; annotation . put12 ( ' [ ' , charArray . length ) ; for ( char charValue : charArray ) { annotation . put12 ( ' ' , symbolTable . addConstantInteger ( charValue ) . index ) ; } } else if ( value instanceof int [ ] ) { int [ ] intArray = ( int [ ] ) value ; annotation . put12 ( ' [ ' , intArray . length ) ; for ( int intValue : intArray ) { annotation . put12 ( ' I ' , symbolTable . addConstantInteger ( intValue ) . index ) ; } } else if ( value instanceof long [ ] ) { long [ ] longArray = ( long [ ] ) value ; annotation . put12 ( ' [ ' , longArray . length ) ; for ( long longValue : longArray ) { annotation . put12 ( ' J ' , symbolTable . addConstantLong ( longValue ) . index ) ; } } else if ( value instanceof float [ ] ) { float [ ] floatArray = ( float [ ] ) value ; annotation . put12 ( ' [ ' , floatArray . length ) ; for ( float floatValue : floatArray ) { annotation . put12 ( ' ' , symbolTable . addConstantFloat ( floatValue ) . index ) ; } } else if ( value instanceof double [ ] ) { double [ ] doubleArray = ( double [ ] ) value ; annotation . put12 ( ' [ ' , doubleArray . length ) ; for ( double doubleValue : doubleArray ) { annotation . put12 ( ' ' , symbolTable . addConstantDouble ( doubleValue ) . index ) ; } } else { Symbol symbol = symbolTable . addConstant ( value ) ; annotation . put12 ( \".s.IFJDCS\" . charAt ( symbol . tag ) , symbol . index ) ; } } @ Override public void visitEnum ( final String name , final String descriptor , final String value ) { // Case of an element_value with an enum_const_value field. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. ++ numElementValuePairs ; if ( useNamedValues ) { annotation . putShort ( symbolTable . addConstantUtf8 ( name ) ) ; } annotation . put12 ( ' ' , symbolTable . addConstantUtf8 ( descriptor ) ) . putShort ( symbolTable . addConstantUtf8 ( value ) ) ; } @ Override public AnnotationVisitor visitAnnotation  ( final String name , final String descriptor ) { // Case of an element_value with an annotation_value field. // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. ++ numElementValuePairs ; if ( useNamedValues ) { annotation . putShort ( symbolTable . addConstantUtf8 ( name ) ) ; } // Write tag and type_index, and reserve 2 bytes for num_element_value_pairs. annotation . put12 ( ' ' , symbolTable . addConstantUtf8 ( descriptor ) ) . putShort ( 0 ) ; return new AnnotationWriter ( symbolTable , annotation , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of a Runtime [ In ] Visible [ Type ] Annotations attribute containing this annotation and all its <i > predecessors< / i > ( see { @link #previousAnnotation } . Also adds the attribute name to the constant pool of the class ( if not null ) . [CODESPLIT] int computeAnnotationsSize ( final String attributeName ) { if ( attributeName != null ) { symbolTable . addConstantUtf8 ( attributeName ) ; } // The attribute_name_index, attribute_length and num_annotations fields use 8 bytes. int attributeSize = 8 ; AnnotationWriter annotationWriter = this ; while ( annotationWriter != null ) { attributeSize += annotationWriter . annotation . length ; annotationWriter = annotationWriter . previousAnnotation ; } return attributeSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a Runtime [ In ] Visible [ Type ] Annotations attribute containing this annotations and all its <i > predecessors< / i > ( see { @link #previousAnnotation } in the given ByteVector . Annotations are put in the same order they have been visited . [CODESPLIT] void putAnnotations ( final int attributeNameIndex , final ByteVector output ) { int attributeLength = 2 ; // For num_annotations. int numAnnotations = 0 ; AnnotationWriter annotationWriter = this ; AnnotationWriter firstAnnotation = null ; while ( annotationWriter != null ) { // In case the user forgot to call visitEnd(). annotationWriter . visitEnd ( ) ; attributeLength += annotationWriter . annotation . length ; numAnnotations ++ ; firstAnnotation = annotationWriter ; annotationWriter = annotationWriter . previousAnnotation ; } output . putShort ( attributeNameIndex ) ; output . putInt ( attributeLength ) ; output . putShort ( numAnnotations ) ; annotationWriter = firstAnnotation ; while ( annotationWriter != null ) { output . putByteArray ( annotationWriter . annotation . data , 0 , annotationWriter . annotation . length ) ; annotationWriter = annotationWriter . nextAnnotation ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of a Runtime [ In ] VisibleParameterAnnotations attribute containing all the annotation lists from the given AnnotationWriter sub - array . Also adds the attribute name to the constant pool of the class . [CODESPLIT] static int computeParameterAnnotationsSize ( final String attributeName , final AnnotationWriter [ ] annotationWriters , final int annotableParameterCount ) { // Note: attributeName is added to the constant pool by the call to computeAnnotationsSize // below. This assumes that there is at least one non-null element in the annotationWriters // sub-array (which is ensured by the lazy instantiation of this array in MethodWriter). // The attribute_name_index, attribute_length and num_parameters fields use 7 bytes, and each // element of the parameter_annotations array uses 2 bytes for its num_annotations field. int attributeSize = 7 + 2 * annotableParameterCount ; for ( int i = 0 ; i < annotableParameterCount ; ++ i ) { AnnotationWriter annotationWriter = annotationWriters [ i ] ; attributeSize += annotationWriter == null ? 0 : annotationWriter . computeAnnotationsSize ( attributeName ) - 8 ; } return attributeSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a Runtime [ In ] VisibleParameterAnnotations attribute containing all the annotation lists from the given AnnotationWriter sub - array in the given ByteVector . [CODESPLIT] static void putParameterAnnotations ( final int attributeNameIndex , final AnnotationWriter [ ] annotationWriters , final int annotableParameterCount , final ByteVector output ) { // The num_parameters field uses 1 byte, and each element of the parameter_annotations array // uses 2 bytes for its num_annotations field. int attributeLength = 1 + 2 * annotableParameterCount ; for ( int i = 0 ; i < annotableParameterCount ; ++ i ) { AnnotationWriter annotationWriter = annotationWriters [ i ] ; attributeLength += annotationWriter == null ? 0 : annotationWriter . computeAnnotationsSize ( null ) - 8 ; } output . putShort ( attributeNameIndex ) ; output . putInt ( attributeLength ) ; output . putByte ( annotableParameterCount ) ; for ( int i = 0 ; i < annotableParameterCount ; ++ i ) { AnnotationWriter annotationWriter = annotationWriters [ i ] ; AnnotationWriter firstAnnotation = null ; int numAnnotations = 0 ; while ( annotationWriter != null ) { // In case user the forgot to call visitEnd(). annotationWriter . visitEnd ( ) ; numAnnotations ++ ; firstAnnotation = annotationWriter ; annotationWriter = annotationWriter . previousAnnotation ; } output . putShort ( numAnnotations ) ; annotationWriter = firstAnnotation ; while ( annotationWriter != null ) { output . putByteArray ( annotationWriter . annotation . data , 0 , annotationWriter . annotation . length ) ; annotationWriter = annotationWriter . nextAnnotation ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables profiles to iterate . [CODESPLIT] public PropsEntries profile ( final String ... profiles ) { if ( profiles == null ) { return this ; } for ( String profile : profiles ) { addProfiles ( profile ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a long from a byte buffer in little endian byte order . [CODESPLIT] public static long getLongLittleEndian ( final byte [ ] buf , final int offset ) { return ( ( long ) buf [ offset + 7 ] << 56 ) // no mask needed | ( ( buf [ offset + 6 ] & 0xff L ) << 48 ) | ( ( buf [ offset + 5 ] & 0xff L ) << 40 ) | ( ( buf [ offset + 4 ] & 0xff L ) << 32 ) | ( ( buf [ offset + 3 ] & 0xff L ) << 24 ) | ( ( buf [ offset + 2 ] & 0xff L ) << 16 ) | ( ( buf [ offset + 1 ] & 0xff L ) << 8 ) | ( ( buf [ offset ] & 0xff L ) ) ; // no shift needed }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the MurmurHash3_x64_128 hash . [CODESPLIT] public static HashValue murmurhash3_x64_128 ( final byte [ ] key , final int offset , final int len , final int seed ) { // The original algorithm does have a 32 bit unsigned seed. // We have to mask to match the behavior of the unsigned types and prevent sign extension. long h1 = seed & 0x00000000FFFFFFFF  L ; long h2 = seed & 0x00000000FFFFFFFF  L ; final long c1 = 0x87c37b91114253d5  L ; final long c2 = 0x4cf5ad432745937f  L ; int roundedEnd = offset + ( len & 0xFFFFFFF0 ) ; // round down to 16 byte block for ( int i = offset ; i < roundedEnd ; i += 16 ) { long k1 = getLongLittleEndian ( key , i ) ; long k2 = getLongLittleEndian ( key , i + 8 ) ; k1 *= c1 ; k1 = Long . rotateLeft ( k1 , 31 ) ; k1 *= c2 ; h1 ^= k1 ; h1 = Long . rotateLeft ( h1 , 27 ) ; h1 += h2 ; h1 = h1 * 5 + 0x52dce729 ; k2 *= c2 ; k2 = Long . rotateLeft ( k2 , 33 ) ; k2 *= c1 ; h2 ^= k2 ; h2 = Long . rotateLeft ( h2 , 31 ) ; h2 += h1 ; h2 = h2 * 5 + 0x38495ab5 ; } long k1 = 0 ; long k2 = 0 ; switch ( len & 15 ) { case 15 : k2 = ( key [ roundedEnd + 14 ] & 0xff L ) << 48 ; case 14 : k2 |= ( key [ roundedEnd + 13 ] & 0xff L ) << 40 ; case 13 : k2 |= ( key [ roundedEnd + 12 ] & 0xff L ) << 32 ; case 12 : k2 |= ( key [ roundedEnd + 11 ] & 0xff L ) << 24 ; case 11 : k2 |= ( key [ roundedEnd + 10 ] & 0xff L ) << 16 ; case 10 : k2 |= ( key [ roundedEnd + 9 ] & 0xff L ) << 8 ; case 9 : k2 |= ( key [ roundedEnd + 8 ] & 0xff L ) ; k2 *= c2 ; k2 = Long . rotateLeft ( k2 , 33 ) ; k2 *= c1 ; h2 ^= k2 ; case 8 : k1 = ( ( long ) key [ roundedEnd + 7 ] ) << 56 ; case 7 : k1 |= ( key [ roundedEnd + 6 ] & 0xff L ) << 48 ; case 6 : k1 |= ( key [ roundedEnd + 5 ] & 0xff L ) << 40 ; case 5 : k1 |= ( key [ roundedEnd + 4 ] & 0xff L ) << 32 ; case 4 : k1 |= ( key [ roundedEnd + 3 ] & 0xff L ) << 24 ; case 3 : k1 |= ( key [ roundedEnd + 2 ] & 0xff L ) << 16 ; case 2 : k1 |= ( key [ roundedEnd + 1 ] & 0xff L ) << 8 ; case 1 : k1 |= ( key [ roundedEnd ] & 0xff L ) ; k1 *= c1 ; k1 = Long . rotateLeft ( k1 , 31 ) ; k1 *= c2 ; h1 ^= k1 ; } //---------- // finalization h1 ^= len ; h2 ^= len ; h1 += h2 ; h2 += h1 ; h1 = fmix64 ( h1 ) ; h2 = fmix64 ( h2 ) ; h1 += h2 ; h2 += h1 ; return new HashValue ( h1 , h2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the given input stream and returns its content as a byte array . [CODESPLIT] private static byte [ ] readStream ( final InputStream inputStream , final boolean close ) throws IOException { if ( inputStream == null ) { throw new IOException ( \"Class not found\" ) ; } try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; byte [ ] data = new byte [ INPUT_STREAM_DATA_CHUNK_SIZE ] ; int bytesRead ; while ( ( bytesRead = inputStream . read ( data , 0 , data . length ) ) != - 1 ) { outputStream . write ( data , 0 , bytesRead ) ; } outputStream . flush ( ) ; return outputStream . toByteArray ( ) ; } finally { if ( close ) { inputStream . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the internal names of the implemented interfaces ( see { @link Type#getInternalName () } ) . [CODESPLIT] public String [ ] getInterfaces ( ) { // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each). int currentOffset = header + 6 ; int interfacesCount = readUnsignedShort ( currentOffset ) ; String [ ] interfaces = new String [ interfacesCount ] ; if ( interfacesCount > 0 ) { char [ ] charBuffer = new char [ maxStringLength ] ; for ( int i = 0 ; i < interfacesCount ; ++ i ) { currentOffset += 2 ; interfaces [ i ] = readClass ( currentOffset , charBuffer ) ; } } return interfaces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this { @link ClassReader } . [CODESPLIT] public void accept ( final ClassVisitor classVisitor , final Attribute [ ] attributePrototypes , final int parsingOptions ) { Context context = new Context ( ) ; context . attributePrototypes = attributePrototypes ; context . parsingOptions = parsingOptions ; context . charBuffer = new char [ maxStringLength ] ; // Read the access_flags, this_class, super_class, interface_count and interfaces fields. char [ ] charBuffer = context . charBuffer ; int currentOffset = header ; int accessFlags = readUnsignedShort ( currentOffset ) ; String thisClass = readClass ( currentOffset + 2 , charBuffer ) ; String superClass = readClass ( currentOffset + 4 , charBuffer ) ; String [ ] interfaces = new String [ readUnsignedShort ( currentOffset + 6 ) ] ; currentOffset += 8 ; for ( int i = 0 ; i < interfaces . length ; ++ i ) { interfaces [ i ] = readClass ( currentOffset , charBuffer ) ; currentOffset += 2 ; } // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS). // Attribute offsets exclude the attribute_name_index and attribute_length fields. // - The offset of the InnerClasses attribute, or 0. int innerClassesOffset = 0 ; // - The offset of the EnclosingMethod attribute, or 0. int enclosingMethodOffset = 0 ; // - The string corresponding to the Signature attribute, or null. String signature = null ; // - The string corresponding to the SourceFile attribute, or null. String sourceFile = null ; // - The string corresponding to the SourceDebugExtension attribute, or null. String sourceDebugExtension = null ; // - The offset of the RuntimeVisibleAnnotations attribute, or 0. int runtimeVisibleAnnotationsOffset = 0 ; // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. int runtimeInvisibleAnnotationsOffset = 0 ; // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. int runtimeVisibleTypeAnnotationsOffset = 0 ; // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. int runtimeInvisibleTypeAnnotationsOffset = 0 ; // - The offset of the Module attribute, or 0. int moduleOffset = 0 ; // - The offset of the ModulePackages attribute, or 0. int modulePackagesOffset = 0 ; // - The string corresponding to the ModuleMainClass attribute, or null. String moduleMainClass = null ; // - The string corresponding to the NestHost attribute, or null. String nestHostClass = null ; // - The offset of the NestMembers attribute, or 0. int nestMembersOffset = 0 ; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). //   This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null ; int currentAttributeOffset = getFirstAttributeOffset ( ) ; for ( int i = readUnsignedShort ( currentAttributeOffset - 2 ) ; i > 0 ; -- i ) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8 ( currentAttributeOffset , charBuffer ) ; int attributeLength = readInt ( currentAttributeOffset + 2 ) ; currentAttributeOffset += 6 ; // The tests are sorted in decreasing frequency order (based on frequencies observed on // typical classes). if ( Constants . SOURCE_FILE . equals ( attributeName ) ) { sourceFile = readUTF8 ( currentAttributeOffset , charBuffer ) ; } else if ( Constants . INNER_CLASSES . equals ( attributeName ) ) { innerClassesOffset = currentAttributeOffset ; } else if ( Constants . ENCLOSING_METHOD . equals ( attributeName ) ) { enclosingMethodOffset = currentAttributeOffset ; } else if ( Constants . NEST_HOST . equals ( attributeName ) ) { nestHostClass = readClass ( currentAttributeOffset , charBuffer ) ; } else if ( Constants . NEST_MEMBERS . equals ( attributeName ) ) { nestMembersOffset = currentAttributeOffset ; } else if ( Constants . SIGNATURE . equals ( attributeName ) ) { signature = readUTF8 ( currentAttributeOffset , charBuffer ) ; } else if ( Constants . RUNTIME_VISIBLE_ANNOTATIONS . equals ( attributeName ) ) { runtimeVisibleAnnotationsOffset = currentAttributeOffset ; } else if ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset ; } else if ( Constants . DEPRECATED . equals ( attributeName ) ) { accessFlags |= Opcodes . ACC_DEPRECATED ; } else if ( Constants . SYNTHETIC . equals ( attributeName ) ) { accessFlags |= Opcodes . ACC_SYNTHETIC ; } else if ( Constants . SOURCE_DEBUG_EXTENSION . equals ( attributeName ) ) { sourceDebugExtension = readUtf ( currentAttributeOffset , attributeLength , new char [ attributeLength ] ) ; } else if ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS . equals ( attributeName ) ) { runtimeInvisibleAnnotationsOffset = currentAttributeOffset ; } else if ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset ; } else if ( Constants . MODULE . equals ( attributeName ) ) { moduleOffset = currentAttributeOffset ; } else if ( Constants . MODULE_MAIN_CLASS . equals ( attributeName ) ) { moduleMainClass = readClass ( currentAttributeOffset , charBuffer ) ; } else if ( Constants . MODULE_PACKAGES . equals ( attributeName ) ) { modulePackagesOffset = currentAttributeOffset ; } else if ( ! Constants . BOOTSTRAP_METHODS . equals ( attributeName ) ) { // The BootstrapMethods attribute is read in the constructor. Attribute attribute = readAttribute ( attributePrototypes , attributeName , currentAttributeOffset , attributeLength , charBuffer , - 1 , null ) ; attribute . nextAttribute = attributes ; attributes = attribute ; } currentAttributeOffset += attributeLength ; } // Visit the class declaration. The minor_version and major_version fields start 6 bytes before // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition). classVisitor . visit ( readInt ( cpInfoOffsets [ 1 ] - 7 ) , accessFlags , thisClass , signature , superClass , interfaces ) ; // Visit the SourceFile and SourceDebugExtenstion attributes. if ( ( parsingOptions & SKIP_DEBUG ) == 0 && ( sourceFile != null || sourceDebugExtension != null ) ) { classVisitor . visitSource ( sourceFile , sourceDebugExtension ) ; } // Visit the Module, ModulePackages and ModuleMainClass attributes. if ( moduleOffset != 0 ) { readModuleAttributes ( classVisitor , context , moduleOffset , modulePackagesOffset , moduleMainClass ) ; } // Visit the NestHost attribute. if ( nestHostClass != null ) { classVisitor . visitNestHost ( nestHostClass ) ; } // Visit the EnclosingMethod attribute. if ( enclosingMethodOffset != 0 ) { String className = readClass ( enclosingMethodOffset , charBuffer ) ; int methodIndex = readUnsignedShort ( enclosingMethodOffset + 2 ) ; String name = methodIndex == 0 ? null : readUTF8 ( cpInfoOffsets [ methodIndex ] , charBuffer ) ; String type = methodIndex == 0 ? null : readUTF8 ( cpInfoOffsets [ methodIndex ] + 2 , charBuffer ) ; classVisitor . visitOuterClass ( className , name , type ) ; } // Visit the RuntimeVisibleAnnotations attribute. if ( runtimeVisibleAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeVisibleAnnotationsOffset ) ; int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( classVisitor . visitAnnotation ( annotationDescriptor , /* visible = */ true ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeInvisibleAnnotations attribute. if ( runtimeInvisibleAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeInvisibleAnnotationsOffset ) ; int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( classVisitor . visitAnnotation ( annotationDescriptor , /* visible = */ false ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeVisibleTypeAnnotations attribute. if ( runtimeVisibleTypeAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeVisibleTypeAnnotationsOffset ) ; int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget ( context , currentAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( classVisitor . visitTypeAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ true ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeInvisibleTypeAnnotations attribute. if ( runtimeInvisibleTypeAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeInvisibleTypeAnnotationsOffset ) ; int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget ( context , currentAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( classVisitor . visitTypeAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ false ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the non standard attributes. while ( attributes != null ) { // Copy and reset the nextAttribute field so that it can also be used in ClassWriter. Attribute nextAttribute = attributes . nextAttribute ; attributes . nextAttribute = null ; classVisitor . visitAttribute ( attributes ) ; attributes = nextAttribute ; } // Visit the NestedMembers attribute. if ( nestMembersOffset != 0 ) { int numberOfNestMembers = readUnsignedShort ( nestMembersOffset ) ; int currentNestMemberOffset = nestMembersOffset + 2 ; while ( numberOfNestMembers -- > 0 ) { classVisitor . visitNestMember ( readClass ( currentNestMemberOffset , charBuffer ) ) ; currentNestMemberOffset += 2 ; } } // Visit the InnerClasses attribute. if ( innerClassesOffset != 0 ) { int numberOfClasses = readUnsignedShort ( innerClassesOffset ) ; int currentClassesOffset = innerClassesOffset + 2 ; while ( numberOfClasses -- > 0 ) { classVisitor . visitInnerClass ( readClass ( currentClassesOffset , charBuffer ) , readClass ( currentClassesOffset + 2 , charBuffer ) , readUTF8 ( currentClassesOffset + 4 , charBuffer ) , readUnsignedShort ( currentClassesOffset + 6 ) ) ; currentClassesOffset += 8 ; } } // Visit the fields and methods. int fieldsCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( fieldsCount -- > 0 ) { currentOffset = readField ( classVisitor , context , currentOffset ) ; } int methodsCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( methodsCount -- > 0 ) { currentOffset = readMethod ( classVisitor , context , currentOffset ) ; } // Visit the end of the class. classVisitor . visitEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the Module ModulePackages and ModuleMainClass attributes and visit them . [CODESPLIT] private void readModuleAttributes ( final ClassVisitor classVisitor , final Context context , final int moduleOffset , final int modulePackagesOffset , final String moduleMainClass ) { char [ ] buffer = context . charBuffer ; // Read the module_name_index, module_flags and module_version_index fields and visit them. int currentOffset = moduleOffset ; String moduleName = readModule ( currentOffset , buffer ) ; int moduleFlags = readUnsignedShort ( currentOffset + 2 ) ; String moduleVersion = readUTF8 ( currentOffset + 4 , buffer ) ; currentOffset += 6 ; ModuleVisitor moduleVisitor = classVisitor . visitModule ( moduleName , moduleFlags , moduleVersion ) ; if ( moduleVisitor == null ) { return ; } // Visit the ModuleMainClass attribute. if ( moduleMainClass != null ) { moduleVisitor . visitMainClass ( moduleMainClass ) ; } // Visit the ModulePackages attribute. if ( modulePackagesOffset != 0 ) { int packageCount = readUnsignedShort ( modulePackagesOffset ) ; int currentPackageOffset = modulePackagesOffset + 2 ; while ( packageCount -- > 0 ) { moduleVisitor . visitPackage ( readPackage ( currentPackageOffset , buffer ) ) ; currentPackageOffset += 2 ; } } // Read the 'requires_count' and 'requires' fields. int requiresCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( requiresCount -- > 0 ) { // Read the requires_index, requires_flags and requires_version fields and visit them. String requires = readModule ( currentOffset , buffer ) ; int requiresFlags = readUnsignedShort ( currentOffset + 2 ) ; String requiresVersion = readUTF8 ( currentOffset + 4 , buffer ) ; currentOffset += 6 ; moduleVisitor . visitRequire ( requires , requiresFlags , requiresVersion ) ; } // Read the 'exports_count' and 'exports' fields. int exportsCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( exportsCount -- > 0 ) { // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields // and visit them. String exports = readPackage ( currentOffset , buffer ) ; int exportsFlags = readUnsignedShort ( currentOffset + 2 ) ; int exportsToCount = readUnsignedShort ( currentOffset + 4 ) ; currentOffset += 6 ; String [ ] exportsTo = null ; if ( exportsToCount != 0 ) { exportsTo = new String [ exportsToCount ] ; for ( int i = 0 ; i < exportsToCount ; ++ i ) { exportsTo [ i ] = readModule ( currentOffset , buffer ) ; currentOffset += 2 ; } } moduleVisitor . visitExport ( exports , exportsFlags , exportsTo ) ; } // Reads the 'opens_count' and 'opens' fields. int opensCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( opensCount -- > 0 ) { // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them. String opens = readPackage ( currentOffset , buffer ) ; int opensFlags = readUnsignedShort ( currentOffset + 2 ) ; int opensToCount = readUnsignedShort ( currentOffset + 4 ) ; currentOffset += 6 ; String [ ] opensTo = null ; if ( opensToCount != 0 ) { opensTo = new String [ opensToCount ] ; for ( int i = 0 ; i < opensToCount ; ++ i ) { opensTo [ i ] = readModule ( currentOffset , buffer ) ; currentOffset += 2 ; } } moduleVisitor . visitOpen ( opens , opensFlags , opensTo ) ; } // Read the 'uses_count' and 'uses' fields. int usesCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( usesCount -- > 0 ) { moduleVisitor . visitUse ( readClass ( currentOffset , buffer ) ) ; currentOffset += 2 ; } // Read the  'provides_count' and 'provides' fields. int providesCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( providesCount -- > 0 ) { // Read the provides_index, provides_with_count and provides_with_index fields and visit them. String provides = readClass ( currentOffset , buffer ) ; int providesWithCount = readUnsignedShort ( currentOffset + 2 ) ; currentOffset += 4 ; String [ ] providesWith = new String [ providesWithCount ] ; for ( int i = 0 ; i < providesWithCount ; ++ i ) { providesWith [ i ] = readClass ( currentOffset , buffer ) ; currentOffset += 2 ; } moduleVisitor . visitProvide ( provides , providesWith ) ; } // Visit the end of the module attributes. moduleVisitor . visitEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JVMS field_info structure and makes the given visitor visit it . [CODESPLIT] private int readField ( final ClassVisitor classVisitor , final Context context , final int fieldInfoOffset ) { char [ ] charBuffer = context . charBuffer ; // Read the access_flags, name_index and descriptor_index fields. int currentOffset = fieldInfoOffset ; int accessFlags = readUnsignedShort ( currentOffset ) ; String name = readUTF8 ( currentOffset + 2 , charBuffer ) ; String descriptor = readUTF8 ( currentOffset + 4 , charBuffer ) ; currentOffset += 6 ; // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS). // Attribute offsets exclude the attribute_name_index and attribute_length fields. // - The value corresponding to the ConstantValue attribute, or null. Object constantValue = null ; // - The string corresponding to the Signature attribute, or null. String signature = null ; // - The offset of the RuntimeVisibleAnnotations attribute, or 0. int runtimeVisibleAnnotationsOffset = 0 ; // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. int runtimeInvisibleAnnotationsOffset = 0 ; // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. int runtimeVisibleTypeAnnotationsOffset = 0 ; // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. int runtimeInvisibleTypeAnnotationsOffset = 0 ; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). //   This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null ; int attributesCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( attributesCount -- > 0 ) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8 ( currentOffset , charBuffer ) ; int attributeLength = readInt ( currentOffset + 2 ) ; currentOffset += 6 ; // The tests are sorted in decreasing frequency order (based on frequencies observed on // typical classes). if ( Constants . CONSTANT_VALUE . equals ( attributeName ) ) { int constantvalueIndex = readUnsignedShort ( currentOffset ) ; constantValue = constantvalueIndex == 0 ? null : readConst ( constantvalueIndex , charBuffer ) ; } else if ( Constants . SIGNATURE . equals ( attributeName ) ) { signature = readUTF8 ( currentOffset , charBuffer ) ; } else if ( Constants . DEPRECATED . equals ( attributeName ) ) { accessFlags |= Opcodes . ACC_DEPRECATED ; } else if ( Constants . SYNTHETIC . equals ( attributeName ) ) { accessFlags |= Opcodes . ACC_SYNTHETIC ; } else if ( Constants . RUNTIME_VISIBLE_ANNOTATIONS . equals ( attributeName ) ) { runtimeVisibleAnnotationsOffset = currentOffset ; } else if ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { runtimeVisibleTypeAnnotationsOffset = currentOffset ; } else if ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS . equals ( attributeName ) ) { runtimeInvisibleAnnotationsOffset = currentOffset ; } else if ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { runtimeInvisibleTypeAnnotationsOffset = currentOffset ; } else { Attribute attribute = readAttribute ( context . attributePrototypes , attributeName , currentOffset , attributeLength , charBuffer , - 1 , null ) ; attribute . nextAttribute = attributes ; attributes = attribute ; } currentOffset += attributeLength ; } // Visit the field declaration. FieldVisitor fieldVisitor = classVisitor . visitField ( accessFlags , name , descriptor , signature , constantValue ) ; if ( fieldVisitor == null ) { return currentOffset ; } // Visit the RuntimeVisibleAnnotations attribute. if ( runtimeVisibleAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeVisibleAnnotationsOffset ) ; int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( fieldVisitor . visitAnnotation ( annotationDescriptor , /* visible = */ true ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeInvisibleAnnotations attribute. if ( runtimeInvisibleAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeInvisibleAnnotationsOffset ) ; int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( fieldVisitor . visitAnnotation ( annotationDescriptor , /* visible = */ false ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeVisibleTypeAnnotations attribute. if ( runtimeVisibleTypeAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeVisibleTypeAnnotationsOffset ) ; int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget ( context , currentAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( fieldVisitor . visitTypeAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ true ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeInvisibleTypeAnnotations attribute. if ( runtimeInvisibleTypeAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeInvisibleTypeAnnotationsOffset ) ; int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget ( context , currentAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( fieldVisitor . visitTypeAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ false ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the non standard attributes. while ( attributes != null ) { // Copy and reset the nextAttribute field so that it can also be used in FieldWriter. Attribute nextAttribute = attributes . nextAttribute ; attributes . nextAttribute = null ; fieldVisitor . visitAttribute ( attributes ) ; attributes = nextAttribute ; } // Visit the end of the field. fieldVisitor . visitEnd ( ) ; return currentOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JVMS method_info structure and makes the given visitor visit it . [CODESPLIT] private int readMethod ( final ClassVisitor classVisitor , final Context context , final int methodInfoOffset ) { char [ ] charBuffer = context . charBuffer ; // Read the access_flags, name_index and descriptor_index fields. int currentOffset = methodInfoOffset ; context . currentMethodAccessFlags = readUnsignedShort ( currentOffset ) ; context . currentMethodName = readUTF8 ( currentOffset + 2 , charBuffer ) ; context . currentMethodDescriptor = readUTF8 ( currentOffset + 4 , charBuffer ) ; currentOffset += 6 ; // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS). // Attribute offsets exclude the attribute_name_index and attribute_length fields. // - The offset of the Code attribute, or 0. int codeOffset = 0 ; // - The offset of the Exceptions attribute, or 0. int exceptionsOffset = 0 ; // - The strings corresponding to the Exceptions attribute, or null. String [ ] exceptions = null ; // - Whether the method has a Synthetic attribute. boolean synthetic = false ; // - The constant pool index contained in the Signature attribute, or 0. int signatureIndex = 0 ; // - The offset of the RuntimeVisibleAnnotations attribute, or 0. int runtimeVisibleAnnotationsOffset = 0 ; // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. int runtimeInvisibleAnnotationsOffset = 0 ; // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0. int runtimeVisibleParameterAnnotationsOffset = 0 ; // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0. int runtimeInvisibleParameterAnnotationsOffset = 0 ; // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. int runtimeVisibleTypeAnnotationsOffset = 0 ; // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. int runtimeInvisibleTypeAnnotationsOffset = 0 ; // - The offset of the AnnotationDefault attribute, or 0. int annotationDefaultOffset = 0 ; // - The offset of the MethodParameters attribute, or 0. int methodParametersOffset = 0 ; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). //   This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null ; int attributesCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( attributesCount -- > 0 ) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8 ( currentOffset , charBuffer ) ; int attributeLength = readInt ( currentOffset + 2 ) ; currentOffset += 6 ; // The tests are sorted in decreasing frequency order (based on frequencies observed on // typical classes). if ( Constants . CODE . equals ( attributeName ) ) { if ( ( context . parsingOptions & SKIP_CODE ) == 0 ) { codeOffset = currentOffset ; } } else if ( Constants . EXCEPTIONS . equals ( attributeName ) ) { exceptionsOffset = currentOffset ; exceptions = new String [ readUnsignedShort ( exceptionsOffset ) ] ; int currentExceptionOffset = exceptionsOffset + 2 ; for ( int i = 0 ; i < exceptions . length ; ++ i ) { exceptions [ i ] = readClass ( currentExceptionOffset , charBuffer ) ; currentExceptionOffset += 2 ; } } else if ( Constants . SIGNATURE . equals ( attributeName ) ) { signatureIndex = readUnsignedShort ( currentOffset ) ; } else if ( Constants . DEPRECATED . equals ( attributeName ) ) { context . currentMethodAccessFlags |= Opcodes . ACC_DEPRECATED ; } else if ( Constants . RUNTIME_VISIBLE_ANNOTATIONS . equals ( attributeName ) ) { runtimeVisibleAnnotationsOffset = currentOffset ; } else if ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { runtimeVisibleTypeAnnotationsOffset = currentOffset ; } else if ( Constants . ANNOTATION_DEFAULT . equals ( attributeName ) ) { annotationDefaultOffset = currentOffset ; } else if ( Constants . SYNTHETIC . equals ( attributeName ) ) { synthetic = true ; context . currentMethodAccessFlags |= Opcodes . ACC_SYNTHETIC ; } else if ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS . equals ( attributeName ) ) { runtimeInvisibleAnnotationsOffset = currentOffset ; } else if ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { runtimeInvisibleTypeAnnotationsOffset = currentOffset ; } else if ( Constants . RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS . equals ( attributeName ) ) { runtimeVisibleParameterAnnotationsOffset = currentOffset ; } else if ( Constants . RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS . equals ( attributeName ) ) { runtimeInvisibleParameterAnnotationsOffset = currentOffset ; } else if ( Constants . METHOD_PARAMETERS . equals ( attributeName ) ) { methodParametersOffset = currentOffset ; } else { Attribute attribute = readAttribute ( context . attributePrototypes , attributeName , currentOffset , attributeLength , charBuffer , - 1 , null ) ; attribute . nextAttribute = attributes ; attributes = attribute ; } currentOffset += attributeLength ; } // Visit the method declaration. MethodVisitor methodVisitor = classVisitor . visitMethod ( context . currentMethodAccessFlags , context . currentMethodName , context . currentMethodDescriptor , signatureIndex == 0 ? null : readUtf ( signatureIndex , charBuffer ) , exceptions ) ; if ( methodVisitor == null ) { return currentOffset ; } // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method // adapter between the reader and the writer. In this case, it might be possible to copy // the method attributes directly into the writer. If so, return early without visiting // the content of these attributes. if ( methodVisitor instanceof MethodWriter ) { MethodWriter methodWriter = ( MethodWriter ) methodVisitor ; if ( methodWriter . canCopyMethodAttributes ( this , methodInfoOffset , currentOffset - methodInfoOffset , synthetic , ( context . currentMethodAccessFlags & Opcodes . ACC_DEPRECATED ) != 0 , readUnsignedShort ( methodInfoOffset + 4 ) , signatureIndex , exceptionsOffset ) ) { return currentOffset ; } } // Visit the MethodParameters attribute. if ( methodParametersOffset != 0 ) { int parametersCount = readByte ( methodParametersOffset ) ; int currentParameterOffset = methodParametersOffset + 1 ; while ( parametersCount -- > 0 ) { // Read the name_index and access_flags fields and visit them. methodVisitor . visitParameter ( readUTF8 ( currentParameterOffset , charBuffer ) , readUnsignedShort ( currentParameterOffset + 2 ) ) ; currentParameterOffset += 4 ; } } // Visit the AnnotationDefault attribute. if ( annotationDefaultOffset != 0 ) { AnnotationVisitor annotationVisitor = methodVisitor . visitAnnotationDefault ( ) ; readElementValue ( annotationVisitor , annotationDefaultOffset , null , charBuffer ) ; if ( annotationVisitor != null ) { annotationVisitor . visitEnd ( ) ; } } // Visit the RuntimeVisibleAnnotations attribute. if ( runtimeVisibleAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeVisibleAnnotationsOffset ) ; int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( methodVisitor . visitAnnotation ( annotationDescriptor , /* visible = */ true ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeInvisibleAnnotations attribute. if ( runtimeInvisibleAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeInvisibleAnnotationsOffset ) ; int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( methodVisitor . visitAnnotation ( annotationDescriptor , /* visible = */ false ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeVisibleTypeAnnotations attribute. if ( runtimeVisibleTypeAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeVisibleTypeAnnotationsOffset ) ; int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget ( context , currentAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( methodVisitor . visitTypeAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ true ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeInvisibleTypeAnnotations attribute. if ( runtimeInvisibleTypeAnnotationsOffset != 0 ) { int numAnnotations = readUnsignedShort ( runtimeInvisibleTypeAnnotationsOffset ) ; int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2 ; while ( numAnnotations -- > 0 ) { // Parse the target_type, target_info and target_path fields. currentAnnotationOffset = readTypeAnnotationTarget ( context , currentAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentAnnotationOffset = readElementValues ( methodVisitor . visitTypeAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ false ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } } // Visit the RuntimeVisibleParameterAnnotations attribute. if ( runtimeVisibleParameterAnnotationsOffset != 0 ) { readParameterAnnotations ( methodVisitor , context , runtimeVisibleParameterAnnotationsOffset , /* visible = */ true ) ; } // Visit the RuntimeInvisibleParameterAnnotations attribute. if ( runtimeInvisibleParameterAnnotationsOffset != 0 ) { readParameterAnnotations ( methodVisitor , context , runtimeInvisibleParameterAnnotationsOffset , /* visible = */ false ) ; } // Visit the non standard attributes. while ( attributes != null ) { // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. Attribute nextAttribute = attributes . nextAttribute ; attributes . nextAttribute = null ; methodVisitor . visitAttribute ( attributes ) ; attributes = nextAttribute ; } // Visit the Code attribute. if ( codeOffset != 0 ) { methodVisitor . visitCode ( ) ; readCode ( methodVisitor , context , codeOffset ) ; } // Visit the end of the method. methodVisitor . visitEnd ( ) ; return currentOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JVMS Code attribute and makes the given visitor visit it . [CODESPLIT] private void readCode ( final MethodVisitor methodVisitor , final Context context , final int codeOffset ) { int currentOffset = codeOffset ; // Read the max_stack, max_locals and code_length fields. final byte [ ] classFileBuffer = b ; final char [ ] charBuffer = context . charBuffer ; final int maxStack = readUnsignedShort ( currentOffset ) ; final int maxLocals = readUnsignedShort ( currentOffset + 2 ) ; final int codeLength = readInt ( currentOffset + 4 ) ; currentOffset += 8 ; // Read the bytecode 'code' array to create a label for each referenced instruction. final int bytecodeStartOffset = currentOffset ; final int bytecodeEndOffset = currentOffset + codeLength ; final Label [ ] labels = context . currentMethodLabels = new Label [ codeLength + 1 ] ; while ( currentOffset < bytecodeEndOffset ) { final int bytecodeOffset = currentOffset - bytecodeStartOffset ; final int opcode = classFileBuffer [ currentOffset ] & 0xFF ; switch ( opcode ) { case Constants . NOP : case Constants . ACONST_NULL : case Constants . ICONST_M1 : case Constants . ICONST_0 : case Constants . ICONST_1 : case Constants . ICONST_2 : case Constants . ICONST_3 : case Constants . ICONST_4 : case Constants . ICONST_5 : case Constants . LCONST_0 : case Constants . LCONST_1 : case Constants . FCONST_0 : case Constants . FCONST_1 : case Constants . FCONST_2 : case Constants . DCONST_0 : case Constants . DCONST_1 : case Constants . IALOAD : case Constants . LALOAD : case Constants . FALOAD : case Constants . DALOAD : case Constants . AALOAD : case Constants . BALOAD : case Constants . CALOAD : case Constants . SALOAD : case Constants . IASTORE : case Constants . LASTORE : case Constants . FASTORE : case Constants . DASTORE : case Constants . AASTORE : case Constants . BASTORE : case Constants . CASTORE : case Constants . SASTORE : case Constants . POP : case Constants . POP2 : case Constants . DUP : case Constants . DUP_X1 : case Constants . DUP_X2 : case Constants . DUP2 : case Constants . DUP2_X1 : case Constants . DUP2_X2 : case Constants . SWAP : case Constants . IADD : case Constants . LADD : case Constants . FADD : case Constants . DADD : case Constants . ISUB : case Constants . LSUB : case Constants . FSUB : case Constants . DSUB : case Constants . IMUL : case Constants . LMUL : case Constants . FMUL : case Constants . DMUL : case Constants . IDIV : case Constants . LDIV : case Constants . FDIV : case Constants . DDIV : case Constants . IREM : case Constants . LREM : case Constants . FREM : case Constants . DREM : case Constants . INEG : case Constants . LNEG : case Constants . FNEG : case Constants . DNEG : case Constants . ISHL : case Constants . LSHL : case Constants . ISHR : case Constants . LSHR : case Constants . IUSHR : case Constants . LUSHR : case Constants . IAND : case Constants . LAND : case Constants . IOR : case Constants . LOR : case Constants . IXOR : case Constants . LXOR : case Constants . I2L : case Constants . I2F : case Constants . I2D : case Constants . L2I : case Constants . L2F : case Constants . L2D : case Constants . F2I : case Constants . F2L : case Constants . F2D : case Constants . D2I : case Constants . D2L : case Constants . D2F : case Constants . I2B : case Constants . I2C : case Constants . I2S : case Constants . LCMP : case Constants . FCMPL : case Constants . FCMPG : case Constants . DCMPL : case Constants . DCMPG : case Constants . IRETURN : case Constants . LRETURN : case Constants . FRETURN : case Constants . DRETURN : case Constants . ARETURN : case Constants . RETURN : case Constants . ARRAYLENGTH : case Constants . ATHROW : case Constants . MONITORENTER : case Constants . MONITOREXIT : case Constants . ILOAD_0 : case Constants . ILOAD_1 : case Constants . ILOAD_2 : case Constants . ILOAD_3 : case Constants . LLOAD_0 : case Constants . LLOAD_1 : case Constants . LLOAD_2 : case Constants . LLOAD_3 : case Constants . FLOAD_0 : case Constants . FLOAD_1 : case Constants . FLOAD_2 : case Constants . FLOAD_3 : case Constants . DLOAD_0 : case Constants . DLOAD_1 : case Constants . DLOAD_2 : case Constants . DLOAD_3 : case Constants . ALOAD_0 : case Constants . ALOAD_1 : case Constants . ALOAD_2 : case Constants . ALOAD_3 : case Constants . ISTORE_0 : case Constants . ISTORE_1 : case Constants . ISTORE_2 : case Constants . ISTORE_3 : case Constants . LSTORE_0 : case Constants . LSTORE_1 : case Constants . LSTORE_2 : case Constants . LSTORE_3 : case Constants . FSTORE_0 : case Constants . FSTORE_1 : case Constants . FSTORE_2 : case Constants . FSTORE_3 : case Constants . DSTORE_0 : case Constants . DSTORE_1 : case Constants . DSTORE_2 : case Constants . DSTORE_3 : case Constants . ASTORE_0 : case Constants . ASTORE_1 : case Constants . ASTORE_2 : case Constants . ASTORE_3 : currentOffset += 1 ; break ; case Constants . IFEQ : case Constants . IFNE : case Constants . IFLT : case Constants . IFGE : case Constants . IFGT : case Constants . IFLE : case Constants . IF_ICMPEQ : case Constants . IF_ICMPNE : case Constants . IF_ICMPLT : case Constants . IF_ICMPGE : case Constants . IF_ICMPGT : case Constants . IF_ICMPLE : case Constants . IF_ACMPEQ : case Constants . IF_ACMPNE : case Constants . GOTO : case Constants . JSR : case Constants . IFNULL : case Constants . IFNONNULL : createLabel ( bytecodeOffset + readShort ( currentOffset + 1 ) , labels ) ; currentOffset += 3 ; break ; case Constants . ASM_IFEQ : case Constants . ASM_IFNE : case Constants . ASM_IFLT : case Constants . ASM_IFGE : case Constants . ASM_IFGT : case Constants . ASM_IFLE : case Constants . ASM_IF_ICMPEQ : case Constants . ASM_IF_ICMPNE : case Constants . ASM_IF_ICMPLT : case Constants . ASM_IF_ICMPGE : case Constants . ASM_IF_ICMPGT : case Constants . ASM_IF_ICMPLE : case Constants . ASM_IF_ACMPEQ : case Constants . ASM_IF_ACMPNE : case Constants . ASM_GOTO : case Constants . ASM_JSR : case Constants . ASM_IFNULL : case Constants . ASM_IFNONNULL : createLabel ( bytecodeOffset + readUnsignedShort ( currentOffset + 1 ) , labels ) ; currentOffset += 3 ; break ; case Constants . GOTO_W : case Constants . JSR_W : case Constants . ASM_GOTO_W : createLabel ( bytecodeOffset + readInt ( currentOffset + 1 ) , labels ) ; currentOffset += 5 ; break ; case Constants . WIDE : switch ( classFileBuffer [ currentOffset + 1 ] & 0xFF ) { case Constants . ILOAD : case Constants . FLOAD : case Constants . ALOAD : case Constants . LLOAD : case Constants . DLOAD : case Constants . ISTORE : case Constants . FSTORE : case Constants . ASTORE : case Constants . LSTORE : case Constants . DSTORE : case Constants . RET : currentOffset += 4 ; break ; case Constants . IINC : currentOffset += 6 ; break ; default : throw new IllegalArgumentException ( ) ; } break ; case Constants . TABLESWITCH : // Skip 0 to 3 padding bytes. currentOffset += 4 - ( bytecodeOffset & 3 ) ; // Read the default label and the number of table entries. createLabel ( bytecodeOffset + readInt ( currentOffset ) , labels ) ; int numTableEntries = readInt ( currentOffset + 8 ) - readInt ( currentOffset + 4 ) + 1 ; currentOffset += 12 ; // Read the table labels. while ( numTableEntries -- > 0 ) { createLabel ( bytecodeOffset + readInt ( currentOffset ) , labels ) ; currentOffset += 4 ; } break ; case Constants . LOOKUPSWITCH : // Skip 0 to 3 padding bytes. currentOffset += 4 - ( bytecodeOffset & 3 ) ; // Read the default label and the number of switch cases. createLabel ( bytecodeOffset + readInt ( currentOffset ) , labels ) ; int numSwitchCases = readInt ( currentOffset + 4 ) ; currentOffset += 8 ; // Read the switch labels. while ( numSwitchCases -- > 0 ) { createLabel ( bytecodeOffset + readInt ( currentOffset + 4 ) , labels ) ; currentOffset += 8 ; } break ; case Constants . ILOAD : case Constants . LLOAD : case Constants . FLOAD : case Constants . DLOAD : case Constants . ALOAD : case Constants . ISTORE : case Constants . LSTORE : case Constants . FSTORE : case Constants . DSTORE : case Constants . ASTORE : case Constants . RET : case Constants . BIPUSH : case Constants . NEWARRAY : case Constants . LDC : currentOffset += 2 ; break ; case Constants . SIPUSH : case Constants . LDC_W : case Constants . LDC2_W : case Constants . GETSTATIC : case Constants . PUTSTATIC : case Constants . GETFIELD : case Constants . PUTFIELD : case Constants . INVOKEVIRTUAL : case Constants . INVOKESPECIAL : case Constants . INVOKESTATIC : case Constants . NEW : case Constants . ANEWARRAY : case Constants . CHECKCAST : case Constants . INSTANCEOF : case Constants . IINC : currentOffset += 3 ; break ; case Constants . INVOKEINTERFACE : case Constants . INVOKEDYNAMIC : currentOffset += 5 ; break ; case Constants . MULTIANEWARRAY : currentOffset += 4 ; break ; default : throw new IllegalArgumentException ( ) ; } } // Read the 'exception_table_length' and 'exception_table' field to create a label for each // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks. int exceptionTableLength = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( exceptionTableLength -- > 0 ) { Label start = createLabel ( readUnsignedShort ( currentOffset ) , labels ) ; Label end = createLabel ( readUnsignedShort ( currentOffset + 2 ) , labels ) ; Label handler = createLabel ( readUnsignedShort ( currentOffset + 4 ) , labels ) ; String catchType = readUTF8 ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 6 ) ] , charBuffer ) ; currentOffset += 8 ; methodVisitor . visitTryCatchBlock ( start , end , handler , catchType ) ; } // Read the Code attributes to create a label for each referenced instruction (the variables // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the // attribute_name_index and attribute_length fields. // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0. // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is // updated after each stack_map_frame is read. int stackMapFrameOffset = 0 ; // - The end offset of the StackMap[Table] attribute, or 0. int stackMapTableEndOffset = 0 ; // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not. boolean compressedFrames = true ; // - The offset of the LocalVariableTable attribute, or 0. int localVariableTableOffset = 0 ; // - The offset of the LocalVariableTypeTable attribute, or 0. int localVariableTypeTableOffset = 0 ; // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations // attribute, or null. int [ ] visibleTypeAnnotationOffsets = null ; // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations // attribute, or null. int [ ] invisibleTypeAnnotationOffsets = null ; // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). //   This list in the <i>reverse order</i> or their order in the ClassFile structure. Attribute attributes = null ; int attributesCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( attributesCount -- > 0 ) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8 ( currentOffset , charBuffer ) ; int attributeLength = readInt ( currentOffset + 2 ) ; currentOffset += 6 ; if ( Constants . LOCAL_VARIABLE_TABLE . equals ( attributeName ) ) { if ( ( context . parsingOptions & SKIP_DEBUG ) == 0 ) { localVariableTableOffset = currentOffset ; // Parse the attribute to find the corresponding (debug only) labels. int currentLocalVariableTableOffset = currentOffset ; int localVariableTableLength = readUnsignedShort ( currentLocalVariableTableOffset ) ; currentLocalVariableTableOffset += 2 ; while ( localVariableTableLength -- > 0 ) { int startPc = readUnsignedShort ( currentLocalVariableTableOffset ) ; createDebugLabel ( startPc , labels ) ; int length = readUnsignedShort ( currentLocalVariableTableOffset + 2 ) ; createDebugLabel ( startPc + length , labels ) ; // Skip the name_index, descriptor_index and index fields (2 bytes each). currentLocalVariableTableOffset += 10 ; } } } else if ( Constants . LOCAL_VARIABLE_TYPE_TABLE . equals ( attributeName ) ) { localVariableTypeTableOffset = currentOffset ; // Here we do not extract the labels corresponding to the attribute content. We assume they // are the same or a subset of those of the LocalVariableTable attribute. } else if ( Constants . LINE_NUMBER_TABLE . equals ( attributeName ) ) { if ( ( context . parsingOptions & SKIP_DEBUG ) == 0 ) { // Parse the attribute to find the corresponding (debug only) labels. int currentLineNumberTableOffset = currentOffset ; int lineNumberTableLength = readUnsignedShort ( currentLineNumberTableOffset ) ; currentLineNumberTableOffset += 2 ; while ( lineNumberTableLength -- > 0 ) { int startPc = readUnsignedShort ( currentLineNumberTableOffset ) ; int lineNumber = readUnsignedShort ( currentLineNumberTableOffset + 2 ) ; currentLineNumberTableOffset += 4 ; createDebugLabel ( startPc , labels ) ; labels [ startPc ] . addLineNumber ( lineNumber ) ; } } } else if ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { visibleTypeAnnotationOffsets = readTypeAnnotations ( methodVisitor , context , currentOffset , /* visible = */ true ) ; // Here we do not extract the labels corresponding to the attribute content. This would // require a full parsing of the attribute, which would need to be repeated when parsing // the bytecode instructions (see below). Instead, the content of the attribute is read one // type annotation at a time (i.e. after a type annotation has been visited, the next type // annotation is read), and the labels it contains are also extracted one annotation at a // time. This assumes that type annotations are ordered by increasing bytecode offset. } else if ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS . equals ( attributeName ) ) { invisibleTypeAnnotationOffsets = readTypeAnnotations ( methodVisitor , context , currentOffset , /* visible = */ false ) ; // Same comment as above for the RuntimeVisibleTypeAnnotations attribute. } else if ( Constants . STACK_MAP_TABLE . equals ( attributeName ) ) { if ( ( context . parsingOptions & SKIP_FRAMES ) == 0 ) { stackMapFrameOffset = currentOffset + 2 ; stackMapTableEndOffset = currentOffset + attributeLength ; } // Here we do not extract the labels corresponding to the attribute content. This would // require a full parsing of the attribute, which would need to be repeated when parsing // the bytecode instructions (see below). Instead, the content of the attribute is read one // frame at a time (i.e. after a frame has been visited, the next frame is read), and the // labels it contains are also extracted one frame at a time. Thanks to the ordering of // frames, having only a \"one frame lookahead\" is not a problem, i.e. it is not possible to // see an offset smaller than the offset of the current instruction and for which no Label // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map // table without a full decoding (see below). } else if ( \"StackMap\" . equals ( attributeName ) ) { if ( ( context . parsingOptions & SKIP_FRAMES ) == 0 ) { stackMapFrameOffset = currentOffset + 2 ; stackMapTableEndOffset = currentOffset + attributeLength ; compressedFrames = false ; } // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute, // although this is not guaranteed by the attribute format. This allows an incremental // extraction of the labels corresponding to this attribute (see the comment above for the // StackMapTable attribute). } else { Attribute attribute = readAttribute ( context . attributePrototypes , attributeName , currentOffset , attributeLength , charBuffer , codeOffset , labels ) ; attribute . nextAttribute = attributes ; attributes = attribute ; } currentOffset += attributeLength ; } // Initialize the context fields related to stack map frames, and generate the first // (implicit) stack map frame, if needed. final boolean expandFrames = ( context . parsingOptions & EXPAND_FRAMES ) != 0 ; if ( stackMapFrameOffset != 0 ) { // The bytecode offset of the first explicit frame is not offset_delta + 1 but only // offset_delta. Setting the implicit frame offset to -1 allows us to use of the // \"offset_delta + 1\" rule in all cases. context . currentFrameOffset = - 1 ; context . currentFrameType = 0 ; context . currentFrameLocalCount = 0 ; context . currentFrameLocalCountDelta = 0 ; context . currentFrameLocalTypes = new Object [ maxLocals ] ; context . currentFrameStackCount = 0 ; context . currentFrameStackTypes = new Object [ maxStack ] ; if ( expandFrames ) { computeImplicitFrame ( context ) ; } // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the // stack map table, we look for 3 consecutive bytes that \"look like\" an UNINITIALIZED type // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset). // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare, // and the only consequence will be the creation of an unneeded label. This is better than // creating a label for each NEW instruction, and faster than fully decoding the whole stack // map table. for ( int offset = stackMapFrameOffset ; offset < stackMapTableEndOffset - 2 ; ++ offset ) { if ( classFileBuffer [ offset ] == Frame . ITEM_UNINITIALIZED ) { int potentialBytecodeOffset = readUnsignedShort ( offset + 1 ) ; if ( potentialBytecodeOffset >= 0 && potentialBytecodeOffset < codeLength && ( classFileBuffer [ bytecodeStartOffset + potentialBytecodeOffset ] & 0xFF ) == Opcodes . NEW ) { createLabel ( potentialBytecodeOffset , labels ) ; } } } } if ( expandFrames && ( context . parsingOptions & EXPAND_ASM_INSNS ) != 0 ) { // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method // does not currently have any frame. These inserted frames must be computed by simulating the // effect of the bytecode instructions, one by one, starting from the implicit first frame. // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is // computed in MethodWriter). methodVisitor . visitFrame ( Opcodes . F_NEW , maxLocals , null , 0 , null ) ; } // Visit the bytecode instructions. First, introduce state variables for the incremental parsing // of the type annotations. // Index of the next runtime visible type annotation to read (in the // visibleTypeAnnotationOffsets array). int currentVisibleTypeAnnotationIndex = 0 ; // The bytecode offset of the next runtime visible type annotation to read, or -1. int currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset ( visibleTypeAnnotationOffsets , 0 ) ; // Index of the next runtime invisible type annotation to read (in the // invisibleTypeAnnotationOffsets array). int currentInvisibleTypeAnnotationIndex = 0 ; // The bytecode offset of the next runtime invisible type annotation to read, or -1. int currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset ( invisibleTypeAnnotationOffsets , 0 ) ; // Whether a F_INSERT stack map frame must be inserted before the current instruction. boolean insertFrame = false ; // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific // instructions). final int wideJumpOpcodeDelta = ( context . parsingOptions & EXPAND_ASM_INSNS ) == 0 ? Constants . WIDE_JUMP_OPCODE_DELTA : 0 ; currentOffset = bytecodeStartOffset ; while ( currentOffset < bytecodeEndOffset ) { final int currentBytecodeOffset = currentOffset - bytecodeStartOffset ; // Visit the label and the line number(s) for this bytecode offset, if any. Label currentLabel = labels [ currentBytecodeOffset ] ; if ( currentLabel != null ) { currentLabel . accept ( methodVisitor , ( context . parsingOptions & SKIP_DEBUG ) == 0 ) ; } // Visit the stack map frame for this bytecode offset, if any. while ( stackMapFrameOffset != 0 && ( context . currentFrameOffset == currentBytecodeOffset || context . currentFrameOffset == - 1 ) ) { // If there is a stack map frame for this offset, make methodVisitor visit it, and read the // next stack map frame if there is one. if ( context . currentFrameOffset != - 1 ) { if ( ! compressedFrames || expandFrames ) { methodVisitor . visitFrame ( Opcodes . F_NEW , context . currentFrameLocalCount , context . currentFrameLocalTypes , context . currentFrameStackCount , context . currentFrameStackTypes ) ; } else { methodVisitor . visitFrame ( context . currentFrameType , context . currentFrameLocalCountDelta , context . currentFrameLocalTypes , context . currentFrameStackCount , context . currentFrameStackTypes ) ; } // Since there is already a stack map frame for this bytecode offset, there is no need to // insert a new one. insertFrame = false ; } if ( stackMapFrameOffset < stackMapTableEndOffset ) { stackMapFrameOffset = readStackMapFrame ( stackMapFrameOffset , compressedFrames , expandFrames , context ) ; } else { stackMapFrameOffset = 0 ; } } // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to // true during the previous iteration. The actual frame content is computed in MethodWriter. if ( insertFrame ) { if ( ( context . parsingOptions & EXPAND_FRAMES ) != 0 ) { methodVisitor . visitFrame ( Constants . F_INSERT , 0 , null , 0 , null ) ; } insertFrame = false ; } // Visit the instruction at this bytecode offset. int opcode = classFileBuffer [ currentOffset ] & 0xFF ; switch ( opcode ) { case Constants . NOP : case Constants . ACONST_NULL : case Constants . ICONST_M1 : case Constants . ICONST_0 : case Constants . ICONST_1 : case Constants . ICONST_2 : case Constants . ICONST_3 : case Constants . ICONST_4 : case Constants . ICONST_5 : case Constants . LCONST_0 : case Constants . LCONST_1 : case Constants . FCONST_0 : case Constants . FCONST_1 : case Constants . FCONST_2 : case Constants . DCONST_0 : case Constants . DCONST_1 : case Constants . IALOAD : case Constants . LALOAD : case Constants . FALOAD : case Constants . DALOAD : case Constants . AALOAD : case Constants . BALOAD : case Constants . CALOAD : case Constants . SALOAD : case Constants . IASTORE : case Constants . LASTORE : case Constants . FASTORE : case Constants . DASTORE : case Constants . AASTORE : case Constants . BASTORE : case Constants . CASTORE : case Constants . SASTORE : case Constants . POP : case Constants . POP2 : case Constants . DUP : case Constants . DUP_X1 : case Constants . DUP_X2 : case Constants . DUP2 : case Constants . DUP2_X1 : case Constants . DUP2_X2 : case Constants . SWAP : case Constants . IADD : case Constants . LADD : case Constants . FADD : case Constants . DADD : case Constants . ISUB : case Constants . LSUB : case Constants . FSUB : case Constants . DSUB : case Constants . IMUL : case Constants . LMUL : case Constants . FMUL : case Constants . DMUL : case Constants . IDIV : case Constants . LDIV : case Constants . FDIV : case Constants . DDIV : case Constants . IREM : case Constants . LREM : case Constants . FREM : case Constants . DREM : case Constants . INEG : case Constants . LNEG : case Constants . FNEG : case Constants . DNEG : case Constants . ISHL : case Constants . LSHL : case Constants . ISHR : case Constants . LSHR : case Constants . IUSHR : case Constants . LUSHR : case Constants . IAND : case Constants . LAND : case Constants . IOR : case Constants . LOR : case Constants . IXOR : case Constants . LXOR : case Constants . I2L : case Constants . I2F : case Constants . I2D : case Constants . L2I : case Constants . L2F : case Constants . L2D : case Constants . F2I : case Constants . F2L : case Constants . F2D : case Constants . D2I : case Constants . D2L : case Constants . D2F : case Constants . I2B : case Constants . I2C : case Constants . I2S : case Constants . LCMP : case Constants . FCMPL : case Constants . FCMPG : case Constants . DCMPL : case Constants . DCMPG : case Constants . IRETURN : case Constants . LRETURN : case Constants . FRETURN : case Constants . DRETURN : case Constants . ARETURN : case Constants . RETURN : case Constants . ARRAYLENGTH : case Constants . ATHROW : case Constants . MONITORENTER : case Constants . MONITOREXIT : methodVisitor . visitInsn ( opcode ) ; currentOffset += 1 ; break ; case Constants . ILOAD_0 : case Constants . ILOAD_1 : case Constants . ILOAD_2 : case Constants . ILOAD_3 : case Constants . LLOAD_0 : case Constants . LLOAD_1 : case Constants . LLOAD_2 : case Constants . LLOAD_3 : case Constants . FLOAD_0 : case Constants . FLOAD_1 : case Constants . FLOAD_2 : case Constants . FLOAD_3 : case Constants . DLOAD_0 : case Constants . DLOAD_1 : case Constants . DLOAD_2 : case Constants . DLOAD_3 : case Constants . ALOAD_0 : case Constants . ALOAD_1 : case Constants . ALOAD_2 : case Constants . ALOAD_3 : opcode -= Constants . ILOAD_0 ; methodVisitor . visitVarInsn ( Opcodes . ILOAD + ( opcode >> 2 ) , opcode & 0x3 ) ; currentOffset += 1 ; break ; case Constants . ISTORE_0 : case Constants . ISTORE_1 : case Constants . ISTORE_2 : case Constants . ISTORE_3 : case Constants . LSTORE_0 : case Constants . LSTORE_1 : case Constants . LSTORE_2 : case Constants . LSTORE_3 : case Constants . FSTORE_0 : case Constants . FSTORE_1 : case Constants . FSTORE_2 : case Constants . FSTORE_3 : case Constants . DSTORE_0 : case Constants . DSTORE_1 : case Constants . DSTORE_2 : case Constants . DSTORE_3 : case Constants . ASTORE_0 : case Constants . ASTORE_1 : case Constants . ASTORE_2 : case Constants . ASTORE_3 : opcode -= Constants . ISTORE_0 ; methodVisitor . visitVarInsn ( Opcodes . ISTORE + ( opcode >> 2 ) , opcode & 0x3 ) ; currentOffset += 1 ; break ; case Constants . IFEQ : case Constants . IFNE : case Constants . IFLT : case Constants . IFGE : case Constants . IFGT : case Constants . IFLE : case Constants . IF_ICMPEQ : case Constants . IF_ICMPNE : case Constants . IF_ICMPLT : case Constants . IF_ICMPGE : case Constants . IF_ICMPGT : case Constants . IF_ICMPLE : case Constants . IF_ACMPEQ : case Constants . IF_ACMPNE : case Constants . GOTO : case Constants . JSR : case Constants . IFNULL : case Constants . IFNONNULL : methodVisitor . visitJumpInsn ( opcode , labels [ currentBytecodeOffset + readShort ( currentOffset + 1 ) ] ) ; currentOffset += 3 ; break ; case Constants . GOTO_W : case Constants . JSR_W : methodVisitor . visitJumpInsn ( opcode - wideJumpOpcodeDelta , labels [ currentBytecodeOffset + readInt ( currentOffset + 1 ) ] ) ; currentOffset += 5 ; break ; case Constants . ASM_IFEQ : case Constants . ASM_IFNE : case Constants . ASM_IFLT : case Constants . ASM_IFGE : case Constants . ASM_IFGT : case Constants . ASM_IFLE : case Constants . ASM_IF_ICMPEQ : case Constants . ASM_IF_ICMPNE : case Constants . ASM_IF_ICMPLT : case Constants . ASM_IF_ICMPGE : case Constants . ASM_IF_ICMPGT : case Constants . ASM_IF_ICMPLE : case Constants . ASM_IF_ACMPEQ : case Constants . ASM_IF_ACMPNE : case Constants . ASM_GOTO : case Constants . ASM_JSR : case Constants . ASM_IFNULL : case Constants . ASM_IFNONNULL : { // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx <l> with IFNOTxxx <L> GOTO_W <l> L:..., // where IFNOTxxx is the \"opposite\" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and // where <L> designates the instruction just after the GOTO_W. // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL. opcode = opcode < Constants . ASM_IFNULL ? opcode - Constants . ASM_OPCODE_DELTA : opcode - Constants . ASM_IFNULL_OPCODE_DELTA ; Label target = labels [ currentBytecodeOffset + readUnsignedShort ( currentOffset + 1 ) ] ; if ( opcode == Opcodes . GOTO || opcode == Opcodes . JSR ) { // Replace GOTO with GOTO_W and JSR with JSR_W. methodVisitor . visitJumpInsn ( opcode + Constants . WIDE_JUMP_OPCODE_DELTA , target ) ; } else { // Compute the \"opposite\" of opcode. This can be done by flipping the least // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ // (with a pre and post offset by 1). opcode = opcode < Opcodes . GOTO ? ( ( opcode + 1 ) ^ 1 ) - 1 : opcode ^ 1 ; Label endif = createLabel ( currentBytecodeOffset + 3 , labels ) ; methodVisitor . visitJumpInsn ( opcode , endif ) ; methodVisitor . visitJumpInsn ( Constants . GOTO_W , target ) ; // endif designates the instruction just after GOTO_W, and is visited as part of the // next instruction. Since it is a jump target, we need to insert a frame here. insertFrame = true ; } currentOffset += 3 ; break ; } case Constants . ASM_GOTO_W : { // Replace ASM_GOTO_W with GOTO_W. methodVisitor . visitJumpInsn ( Constants . GOTO_W , labels [ currentBytecodeOffset + readInt ( currentOffset + 1 ) ] ) ; // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns // IFNOTxxx <L> ASM_GOTO_W <l> L:..., see MethodWriter), so we need to insert a frame // here. insertFrame = true ; currentOffset += 5 ; break ; } case Constants . WIDE : opcode = classFileBuffer [ currentOffset + 1 ] & 0xFF ; if ( opcode == Opcodes . IINC ) { methodVisitor . visitIincInsn ( readUnsignedShort ( currentOffset + 2 ) , readShort ( currentOffset + 4 ) ) ; currentOffset += 6 ; } else { methodVisitor . visitVarInsn ( opcode , readUnsignedShort ( currentOffset + 2 ) ) ; currentOffset += 4 ; } break ; case Constants . TABLESWITCH : { // Skip 0 to 3 padding bytes. currentOffset += 4 - ( currentBytecodeOffset & 3 ) ; // Read the instruction. Label defaultLabel = labels [ currentBytecodeOffset + readInt ( currentOffset ) ] ; int low = readInt ( currentOffset + 4 ) ; int high = readInt ( currentOffset + 8 ) ; currentOffset += 12 ; Label [ ] table = new Label [ high - low + 1 ] ; for ( int i = 0 ; i < table . length ; ++ i ) { table [ i ] = labels [ currentBytecodeOffset + readInt ( currentOffset ) ] ; currentOffset += 4 ; } methodVisitor . visitTableSwitchInsn ( low , high , defaultLabel , table ) ; break ; } case Constants . LOOKUPSWITCH : { // Skip 0 to 3 padding bytes. currentOffset += 4 - ( currentBytecodeOffset & 3 ) ; // Read the instruction. Label defaultLabel = labels [ currentBytecodeOffset + readInt ( currentOffset ) ] ; int numPairs = readInt ( currentOffset + 4 ) ; currentOffset += 8 ; int [ ] keys = new int [ numPairs ] ; Label [ ] values = new Label [ numPairs ] ; for ( int i = 0 ; i < numPairs ; ++ i ) { keys [ i ] = readInt ( currentOffset ) ; values [ i ] = labels [ currentBytecodeOffset + readInt ( currentOffset + 4 ) ] ; currentOffset += 8 ; } methodVisitor . visitLookupSwitchInsn ( defaultLabel , keys , values ) ; break ; } case Constants . ILOAD : case Constants . LLOAD : case Constants . FLOAD : case Constants . DLOAD : case Constants . ALOAD : case Constants . ISTORE : case Constants . LSTORE : case Constants . FSTORE : case Constants . DSTORE : case Constants . ASTORE : case Constants . RET : methodVisitor . visitVarInsn ( opcode , classFileBuffer [ currentOffset + 1 ] & 0xFF ) ; currentOffset += 2 ; break ; case Constants . BIPUSH : case Constants . NEWARRAY : methodVisitor . visitIntInsn ( opcode , classFileBuffer [ currentOffset + 1 ] ) ; currentOffset += 2 ; break ; case Constants . SIPUSH : methodVisitor . visitIntInsn ( opcode , readShort ( currentOffset + 1 ) ) ; currentOffset += 3 ; break ; case Constants . LDC : methodVisitor . visitLdcInsn ( readConst ( classFileBuffer [ currentOffset + 1 ] & 0xFF , charBuffer ) ) ; currentOffset += 2 ; break ; case Constants . LDC_W : case Constants . LDC2_W : methodVisitor . visitLdcInsn ( readConst ( readUnsignedShort ( currentOffset + 1 ) , charBuffer ) ) ; currentOffset += 3 ; break ; case Constants . GETSTATIC : case Constants . PUTSTATIC : case Constants . GETFIELD : case Constants . PUTFIELD : case Constants . INVOKEVIRTUAL : case Constants . INVOKESPECIAL : case Constants . INVOKESTATIC : case Constants . INVOKEINTERFACE : { int cpInfoOffset = cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ; int nameAndTypeCpInfoOffset = cpInfoOffsets [ readUnsignedShort ( cpInfoOffset + 2 ) ] ; String owner = readClass ( cpInfoOffset , charBuffer ) ; String name = readUTF8 ( nameAndTypeCpInfoOffset , charBuffer ) ; String descriptor = readUTF8 ( nameAndTypeCpInfoOffset + 2 , charBuffer ) ; if ( opcode < Opcodes . INVOKEVIRTUAL ) { methodVisitor . visitFieldInsn ( opcode , owner , name , descriptor ) ; } else { boolean isInterface = classFileBuffer [ cpInfoOffset - 1 ] == Symbol . CONSTANT_INTERFACE_METHODREF_TAG ; methodVisitor . visitMethodInsn ( opcode , owner , name , descriptor , isInterface ) ; } if ( opcode == Opcodes . INVOKEINTERFACE ) { currentOffset += 5 ; } else { currentOffset += 3 ; } break ; } case Constants . INVOKEDYNAMIC : { int cpInfoOffset = cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ; int nameAndTypeCpInfoOffset = cpInfoOffsets [ readUnsignedShort ( cpInfoOffset + 2 ) ] ; String name = readUTF8 ( nameAndTypeCpInfoOffset , charBuffer ) ; String descriptor = readUTF8 ( nameAndTypeCpInfoOffset + 2 , charBuffer ) ; int bootstrapMethodOffset = bootstrapMethodOffsets [ readUnsignedShort ( cpInfoOffset ) ] ; Handle handle = ( Handle ) readConst ( readUnsignedShort ( bootstrapMethodOffset ) , charBuffer ) ; Object [ ] bootstrapMethodArguments = new Object [ readUnsignedShort ( bootstrapMethodOffset + 2 ) ] ; bootstrapMethodOffset += 4 ; for ( int i = 0 ; i < bootstrapMethodArguments . length ; i ++ ) { bootstrapMethodArguments [ i ] = readConst ( readUnsignedShort ( bootstrapMethodOffset ) , charBuffer ) ; bootstrapMethodOffset += 2 ; } methodVisitor . visitInvokeDynamicInsn ( name , descriptor , handle , bootstrapMethodArguments ) ; currentOffset += 5 ; break ; } case Constants . NEW : case Constants . ANEWARRAY : case Constants . CHECKCAST : case Constants . INSTANCEOF : methodVisitor . visitTypeInsn ( opcode , readClass ( currentOffset + 1 , charBuffer ) ) ; currentOffset += 3 ; break ; case Constants . IINC : methodVisitor . visitIincInsn ( classFileBuffer [ currentOffset + 1 ] & 0xFF , classFileBuffer [ currentOffset + 2 ] ) ; currentOffset += 3 ; break ; case Constants . MULTIANEWARRAY : methodVisitor . visitMultiANewArrayInsn ( readClass ( currentOffset + 1 , charBuffer ) , classFileBuffer [ currentOffset + 3 ] & 0xFF ) ; currentOffset += 4 ; break ; default : throw new AssertionError ( ) ; } // Visit the runtime visible instruction annotations, if any. while ( visibleTypeAnnotationOffsets != null && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets . length && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset ) { if ( currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset ) { // Parse the target_type, target_info and target_path fields. int currentAnnotationOffset = readTypeAnnotationTarget ( context , visibleTypeAnnotationOffsets [ currentVisibleTypeAnnotationIndex ] ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues ( methodVisitor . visitInsnAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ true ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset ( visibleTypeAnnotationOffsets , ++ currentVisibleTypeAnnotationIndex ) ; } // Visit the runtime invisible instruction annotations, if any. while ( invisibleTypeAnnotationOffsets != null && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets . length && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset ) { if ( currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset ) { // Parse the target_type, target_info and target_path fields. int currentAnnotationOffset = readTypeAnnotationTarget ( context , invisibleTypeAnnotationOffsets [ currentInvisibleTypeAnnotationIndex ] ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentAnnotationOffset , charBuffer ) ; currentAnnotationOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues ( methodVisitor . visitInsnAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , annotationDescriptor , /* visible = */ false ) , currentAnnotationOffset , /* named = */ true , charBuffer ) ; } currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset ( invisibleTypeAnnotationOffsets , ++ currentInvisibleTypeAnnotationIndex ) ; } } if ( labels [ codeLength ] != null ) { methodVisitor . visitLabel ( labels [ codeLength ] ) ; } // Visit LocalVariableTable and LocalVariableTypeTable attributes. if ( localVariableTableOffset != 0 && ( context . parsingOptions & SKIP_DEBUG ) == 0 ) { // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable. int [ ] typeTable = null ; if ( localVariableTypeTableOffset != 0 ) { typeTable = new int [ readUnsignedShort ( localVariableTypeTableOffset ) * 3 ] ; currentOffset = localVariableTypeTableOffset + 2 ; int typeTableIndex = typeTable . length ; while ( typeTableIndex > 0 ) { // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'. typeTable [ -- typeTableIndex ] = currentOffset + 6 ; typeTable [ -- typeTableIndex ] = readUnsignedShort ( currentOffset + 8 ) ; typeTable [ -- typeTableIndex ] = readUnsignedShort ( currentOffset ) ; currentOffset += 10 ; } } int localVariableTableLength = readUnsignedShort ( localVariableTableOffset ) ; currentOffset = localVariableTableOffset + 2 ; while ( localVariableTableLength -- > 0 ) { int startPc = readUnsignedShort ( currentOffset ) ; int length = readUnsignedShort ( currentOffset + 2 ) ; String name = readUTF8 ( currentOffset + 4 , charBuffer ) ; String descriptor = readUTF8 ( currentOffset + 6 , charBuffer ) ; int index = readUnsignedShort ( currentOffset + 8 ) ; currentOffset += 10 ; String signature = null ; if ( typeTable != null ) { for ( int i = 0 ; i < typeTable . length ; i += 3 ) { if ( typeTable [ i ] == startPc && typeTable [ i + 1 ] == index ) { signature = readUTF8 ( typeTable [ i + 2 ] , charBuffer ) ; break ; } } } methodVisitor . visitLocalVariable ( name , descriptor , signature , labels [ startPc ] , labels [ startPc + length ] , index ) ; } } // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute. if ( visibleTypeAnnotationOffsets != null ) { for ( int typeAnnotationOffset : visibleTypeAnnotationOffsets ) { int targetType = readByte ( typeAnnotationOffset ) ; if ( targetType == TypeReference . LOCAL_VARIABLE || targetType == TypeReference . RESOURCE_VARIABLE ) { // Parse the target_type, target_info and target_path fields. currentOffset = readTypeAnnotationTarget ( context , typeAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentOffset , charBuffer ) ; currentOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues ( methodVisitor . visitLocalVariableAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , context . currentLocalVariableAnnotationRangeStarts , context . currentLocalVariableAnnotationRangeEnds , context . currentLocalVariableAnnotationRangeIndices , annotationDescriptor , /* visible = */ true ) , currentOffset , /* named = */ true , charBuffer ) ; } } } // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute. if ( invisibleTypeAnnotationOffsets != null ) { for ( int typeAnnotationOffset : invisibleTypeAnnotationOffsets ) { int targetType = readByte ( typeAnnotationOffset ) ; if ( targetType == TypeReference . LOCAL_VARIABLE || targetType == TypeReference . RESOURCE_VARIABLE ) { // Parse the target_type, target_info and target_path fields. currentOffset = readTypeAnnotationTarget ( context , typeAnnotationOffset ) ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentOffset , charBuffer ) ; currentOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. readElementValues ( methodVisitor . visitLocalVariableAnnotation ( context . currentTypeAnnotationTarget , context . currentTypeAnnotationTargetPath , context . currentLocalVariableAnnotationRangeStarts , context . currentLocalVariableAnnotationRangeEnds , context . currentLocalVariableAnnotationRangeIndices , annotationDescriptor , /* visible = */ false ) , currentOffset , /* named = */ true , charBuffer ) ; } } } // Visit the non standard attributes. while ( attributes != null ) { // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. Attribute nextAttribute = attributes . nextAttribute ; attributes . nextAttribute = null ; methodVisitor . visitAttribute ( attributes ) ; attributes = nextAttribute ; } // Visit the max stack and max locals values. methodVisitor . visitMaxs ( maxStack , maxLocals ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the label corresponding to the given bytecode offset . The default implementation of this method creates a label for the given offset if it has not been already created . [CODESPLIT] protected Label readLabel ( final int bytecodeOffset , final Label [ ] labels ) { if ( labels [ bytecodeOffset ] == null ) { labels [ bytecodeOffset ] = new Label ( ) ; } return labels [ bytecodeOffset ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a label without the { @link Label#FLAG_DEBUG_ONLY } flag set for the given bytecode offset . The label is created with a call to { @link #readLabel } and its { @link Label#FLAG_DEBUG_ONLY } flag is cleared . [CODESPLIT] private Label createLabel ( final int bytecodeOffset , final Label [ ] labels ) { Label label = readLabel ( bytecodeOffset , labels ) ; label . flags &= ~ Label . FLAG_DEBUG_ONLY ; return label ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a label with the { @link Label#FLAG_DEBUG_ONLY } flag set if there is no already existing label for the given bytecode offset ( otherwise does nothing ) . The label is created with a call to { @link #readLabel } . [CODESPLIT] private void createDebugLabel ( final int bytecodeOffset , final Label [ ] labels ) { if ( labels [ bytecodeOffset ] == null ) { readLabel ( bytecodeOffset , labels ) . flags |= Label . FLAG_DEBUG_ONLY ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a Runtime [ In ] VisibleTypeAnnotations attribute to find the offset of each type_annotation entry it contains to find the corresponding labels and to visit the try catch block annotations . [CODESPLIT] private int [ ] readTypeAnnotations ( final MethodVisitor methodVisitor , final Context context , final int runtimeTypeAnnotationsOffset , final boolean visible ) { char [ ] charBuffer = context . charBuffer ; int currentOffset = runtimeTypeAnnotationsOffset ; // Read the num_annotations field and create an array to store the type_annotation offsets. int [ ] typeAnnotationsOffsets = new int [ readUnsignedShort ( currentOffset ) ] ; currentOffset += 2 ; // Parse the 'annotations' array field. for ( int i = 0 ; i < typeAnnotationsOffsets . length ; ++ i ) { typeAnnotationsOffsets [ i ] = currentOffset ; // Parse the type_annotation's target_type and the target_info fields. The size of the // target_info field depends on the value of target_type. int targetType = readInt ( currentOffset ) ; switch ( targetType >>> 24 ) { case TypeReference . LOCAL_VARIABLE : case TypeReference . RESOURCE_VARIABLE : // A localvar_target has a variable size, which depends on the value of their table_length // field. It also references bytecode offsets, for which we need labels. int tableLength = readUnsignedShort ( currentOffset + 1 ) ; currentOffset += 3 ; while ( tableLength -- > 0 ) { int startPc = readUnsignedShort ( currentOffset ) ; int length = readUnsignedShort ( currentOffset + 2 ) ; // Skip the index field (2 bytes). currentOffset += 6 ; createLabel ( startPc , context . currentMethodLabels ) ; createLabel ( startPc + length , context . currentMethodLabels ) ; } break ; case TypeReference . CAST : case TypeReference . CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT : case TypeReference . METHOD_INVOCATION_TYPE_ARGUMENT : case TypeReference . CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT : case TypeReference . METHOD_REFERENCE_TYPE_ARGUMENT : currentOffset += 4 ; break ; case TypeReference . CLASS_EXTENDS : case TypeReference . CLASS_TYPE_PARAMETER_BOUND : case TypeReference . METHOD_TYPE_PARAMETER_BOUND : case TypeReference . THROWS : case TypeReference . EXCEPTION_PARAMETER : case TypeReference . INSTANCEOF : case TypeReference . NEW : case TypeReference . CONSTRUCTOR_REFERENCE : case TypeReference . METHOD_REFERENCE : currentOffset += 3 ; break ; case TypeReference . CLASS_TYPE_PARAMETER : case TypeReference . METHOD_TYPE_PARAMETER : case TypeReference . METHOD_FORMAL_PARAMETER : case TypeReference . FIELD : case TypeReference . METHOD_RETURN : case TypeReference . METHOD_RECEIVER : default : // TypeReference type which can't be used in Code attribute, or which is unknown. throw new IllegalArgumentException ( ) ; } // Parse the rest of the type_annotation structure, starting with the target_path structure // (whose size depends on its path_length field). int pathLength = readByte ( currentOffset ) ; if ( ( targetType >>> 24 ) == TypeReference . EXCEPTION_PARAMETER ) { // Parse the target_path structure and create a corresponding TypePath. TypePath path = pathLength == 0 ? null : new TypePath ( b , currentOffset ) ; currentOffset += 1 + 2 * pathLength ; // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentOffset , charBuffer ) ; currentOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentOffset = readElementValues ( methodVisitor . visitTryCatchAnnotation ( targetType & 0xFFFFFF00 , path , annotationDescriptor , visible ) , currentOffset , /* named = */ true , charBuffer ) ; } else { // We don't want to visit the other target_type annotations, so we just skip them (which // requires some parsing because the element_value_pairs array has a variable size). First, // skip the target_path structure: currentOffset += 3 + 2 * pathLength ; // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them // with a null AnnotationVisitor). currentOffset = readElementValues ( /* annotationVisitor = */ null , currentOffset , /* named = */ true , charBuffer ) ; } } return typeAnnotationsOffsets ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the bytecode offset corresponding to the specified JVMS type_annotation structure or - 1 if there is no such type_annotation of if it does not have a bytecode offset . [CODESPLIT] private int getTypeAnnotationBytecodeOffset ( final int [ ] typeAnnotationOffsets , final int typeAnnotationIndex ) { if ( typeAnnotationOffsets == null || typeAnnotationIndex >= typeAnnotationOffsets . length || readByte ( typeAnnotationOffsets [ typeAnnotationIndex ] ) < TypeReference . INSTANCEOF ) { return - 1 ; } return readUnsignedShort ( typeAnnotationOffsets [ typeAnnotationIndex ] + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the header of a JVMS type_annotation structure to extract its target_type target_info and target_path ( the result is stored in the given context ) and returns the start offset of the rest of the type_annotation structure . [CODESPLIT] private int readTypeAnnotationTarget ( final Context context , final int typeAnnotationOffset ) { int currentOffset = typeAnnotationOffset ; // Parse and store the target_type structure. int targetType = readInt ( typeAnnotationOffset ) ; switch ( targetType >>> 24 ) { case TypeReference . CLASS_TYPE_PARAMETER : case TypeReference . METHOD_TYPE_PARAMETER : case TypeReference . METHOD_FORMAL_PARAMETER : targetType &= 0xFFFF0000 ; currentOffset += 2 ; break ; case TypeReference . FIELD : case TypeReference . METHOD_RETURN : case TypeReference . METHOD_RECEIVER : targetType &= 0xFF000000 ; currentOffset += 1 ; break ; case TypeReference . LOCAL_VARIABLE : case TypeReference . RESOURCE_VARIABLE : targetType &= 0xFF000000 ; int tableLength = readUnsignedShort ( currentOffset + 1 ) ; currentOffset += 3 ; context . currentLocalVariableAnnotationRangeStarts = new Label [ tableLength ] ; context . currentLocalVariableAnnotationRangeEnds = new Label [ tableLength ] ; context . currentLocalVariableAnnotationRangeIndices = new int [ tableLength ] ; for ( int i = 0 ; i < tableLength ; ++ i ) { int startPc = readUnsignedShort ( currentOffset ) ; int length = readUnsignedShort ( currentOffset + 2 ) ; int index = readUnsignedShort ( currentOffset + 4 ) ; currentOffset += 6 ; context . currentLocalVariableAnnotationRangeStarts [ i ] = createLabel ( startPc , context . currentMethodLabels ) ; context . currentLocalVariableAnnotationRangeEnds [ i ] = createLabel ( startPc + length , context . currentMethodLabels ) ; context . currentLocalVariableAnnotationRangeIndices [ i ] = index ; } break ; case TypeReference . CAST : case TypeReference . CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT : case TypeReference . METHOD_INVOCATION_TYPE_ARGUMENT : case TypeReference . CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT : case TypeReference . METHOD_REFERENCE_TYPE_ARGUMENT : targetType &= 0xFF0000FF ; currentOffset += 4 ; break ; case TypeReference . CLASS_EXTENDS : case TypeReference . CLASS_TYPE_PARAMETER_BOUND : case TypeReference . METHOD_TYPE_PARAMETER_BOUND : case TypeReference . THROWS : case TypeReference . EXCEPTION_PARAMETER : targetType &= 0xFFFFFF00 ; currentOffset += 3 ; break ; case TypeReference . INSTANCEOF : case TypeReference . NEW : case TypeReference . CONSTRUCTOR_REFERENCE : case TypeReference . METHOD_REFERENCE : targetType &= 0xFF000000 ; currentOffset += 3 ; break ; default : throw new IllegalArgumentException ( ) ; } context . currentTypeAnnotationTarget = targetType ; // Parse and store the target_path structure. int pathLength = readByte ( currentOffset ) ; context . currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath ( b , currentOffset ) ; // Return the start offset of the rest of the type_annotation structure. return currentOffset + 1 + 2 * pathLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a Runtime [ In ] VisibleParameterAnnotations attribute and makes the given visitor visit it . [CODESPLIT] private void readParameterAnnotations ( final MethodVisitor methodVisitor , final Context context , final int runtimeParameterAnnotationsOffset , final boolean visible ) { int currentOffset = runtimeParameterAnnotationsOffset ; int numParameters = b [ currentOffset ++ ] & 0xFF ; methodVisitor . visitAnnotableParameterCount ( numParameters , visible ) ; char [ ] charBuffer = context . charBuffer ; for ( int i = 0 ; i < numParameters ; ++ i ) { int numAnnotations = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( numAnnotations -- > 0 ) { // Parse the type_index field. String annotationDescriptor = readUTF8 ( currentOffset , charBuffer ) ; currentOffset += 2 ; // Parse num_element_value_pairs and element_value_pairs and visit these values. currentOffset = readElementValues ( methodVisitor . visitParameterAnnotation ( i , annotationDescriptor , visible ) , currentOffset , /* named = */ true , charBuffer ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the element values of a JVMS annotation structure and makes the given visitor visit them . This method can also be used to read the values of the JVMS array_value field of an annotation s element_value . [CODESPLIT] private int readElementValues ( final AnnotationVisitor annotationVisitor , final int annotationOffset , final boolean named , final char [ ] charBuffer ) { int currentOffset = annotationOffset ; // Read the num_element_value_pairs field (or num_values field for an array_value). int numElementValuePairs = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; if ( named ) { // Parse the element_value_pairs array. while ( numElementValuePairs -- > 0 ) { String elementName = readUTF8 ( currentOffset , charBuffer ) ; currentOffset = readElementValue ( annotationVisitor , currentOffset + 2 , elementName , charBuffer ) ; } } else { // Parse the array_value array. while ( numElementValuePairs -- > 0 ) { currentOffset = readElementValue ( annotationVisitor , currentOffset , /* named = */ null , charBuffer ) ; } } if ( annotationVisitor != null ) { annotationVisitor . visitEnd ( ) ; } return currentOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JVMS element_value structure and makes the given visitor visit it . [CODESPLIT] private int readElementValue ( final AnnotationVisitor annotationVisitor , final int elementValueOffset , final String elementName , final char [ ] charBuffer ) { int currentOffset = elementValueOffset ; if ( annotationVisitor == null ) { switch ( b [ currentOffset ] & 0xFF ) { case ' ' : // enum_const_value return currentOffset + 5 ; case ' ' : // annotation_value return readElementValues ( null , currentOffset + 3 , /* named = */ true , charBuffer ) ; case ' ' : // array_value return readElementValues ( null , currentOffset + 1 , /* named = */ false , charBuffer ) ; default : return currentOffset + 3 ; } } switch ( b [ currentOffset ++ ] & 0xFF ) { case ' ' : // const_value_index, CONSTANT_Integer annotationVisitor . visit ( elementName , ( byte ) readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset ) ] ) ) ; currentOffset += 2 ; break ; case ' ' : // const_value_index, CONSTANT_Integer annotationVisitor . visit ( elementName , ( char ) readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset ) ] ) ) ; currentOffset += 2 ; break ; case ' ' : // const_value_index, CONSTANT_Double case ' ' : // const_value_index, CONSTANT_Float case ' ' : // const_value_index, CONSTANT_Integer case ' ' : // const_value_index, CONSTANT_Long annotationVisitor . visit ( elementName , readConst ( readUnsignedShort ( currentOffset ) , charBuffer ) ) ; currentOffset += 2 ; break ; case ' ' : // const_value_index, CONSTANT_Integer annotationVisitor . visit ( elementName , ( short ) readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset ) ] ) ) ; currentOffset += 2 ; break ; case ' ' : // const_value_index, CONSTANT_Integer annotationVisitor . visit ( elementName , readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset ) ] ) == 0 ? Boolean . FALSE : Boolean . TRUE ) ; currentOffset += 2 ; break ; case ' ' : // const_value_index, CONSTANT_Utf8 annotationVisitor . visit ( elementName , readUTF8 ( currentOffset , charBuffer ) ) ; currentOffset += 2 ; break ; case ' ' : // enum_const_value annotationVisitor . visitEnum ( elementName , readUTF8 ( currentOffset , charBuffer ) , readUTF8 ( currentOffset + 2 , charBuffer ) ) ; currentOffset += 4 ; break ; case ' ' : // class_info annotationVisitor . visit ( elementName , Type . getType ( readUTF8 ( currentOffset , charBuffer ) ) ) ; currentOffset += 2 ; break ; case ' ' : // annotation_value currentOffset = readElementValues ( annotationVisitor . visitAnnotation ( elementName , readUTF8 ( currentOffset , charBuffer ) ) , currentOffset + 2 , true , charBuffer ) ; break ; case ' ' : // array_value int numValues = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; if ( numValues == 0 ) { return readElementValues ( annotationVisitor . visitArray ( elementName ) , currentOffset - 2 , /* named = */ false , charBuffer ) ; } switch ( b [ currentOffset ] & 0xFF ) { case ' ' : byte [ ] byteValues = new byte [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { byteValues [ i ] = ( byte ) readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , byteValues ) ; break ; case ' ' : boolean [ ] booleanValues = new boolean [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { booleanValues [ i ] = readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) != 0 ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , booleanValues ) ; break ; case ' ' : short [ ] shortValues = new short [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { shortValues [ i ] = ( short ) readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , shortValues ) ; break ; case ' ' : char [ ] charValues = new char [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { charValues [ i ] = ( char ) readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , charValues ) ; break ; case ' ' : int [ ] intValues = new int [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { intValues [ i ] = readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , intValues ) ; break ; case ' ' : long [ ] longValues = new long [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { longValues [ i ] = readLong ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , longValues ) ; break ; case ' ' : float [ ] floatValues = new float [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { floatValues [ i ] = Float . intBitsToFloat ( readInt ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) ) ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , floatValues ) ; break ; case ' ' : double [ ] doubleValues = new double [ numValues ] ; for ( int i = 0 ; i < numValues ; i ++ ) { doubleValues [ i ] = Double . longBitsToDouble ( readLong ( cpInfoOffsets [ readUnsignedShort ( currentOffset + 1 ) ] ) ) ; currentOffset += 3 ; } annotationVisitor . visit ( elementName , doubleValues ) ; break ; default : currentOffset = readElementValues ( annotationVisitor . visitArray ( elementName ) , currentOffset - 2 , /* named = */ false , charBuffer ) ; break ; } break ; default : throw new IllegalArgumentException ( ) ; } return currentOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the implicit frame of the method currently being parsed ( as defined in the given { @link Context } ) and stores it in the given context . [CODESPLIT] private void computeImplicitFrame ( final Context context ) { String methodDescriptor = context . currentMethodDescriptor ; Object [ ] locals = context . currentFrameLocalTypes ; int numLocal = 0 ; if ( ( context . currentMethodAccessFlags & Opcodes . ACC_STATIC ) == 0 ) { if ( \"<init>\" . equals ( context . currentMethodName ) ) { locals [ numLocal ++ ] = Opcodes . UNINITIALIZED_THIS ; } else { locals [ numLocal ++ ] = readClass ( header + 2 , context . charBuffer ) ; } } // Parse the method descriptor, one argument type descriptor at each iteration. Start by // skipping the first method descriptor character, which is always '('. int currentMethodDescritorOffset = 1 ; while ( true ) { int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset ; switch ( methodDescriptor . charAt ( currentMethodDescritorOffset ++ ) ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : locals [ numLocal ++ ] = Opcodes . INTEGER ; break ; case ' ' : locals [ numLocal ++ ] = Opcodes . FLOAT ; break ; case ' ' : locals [ numLocal ++ ] = Opcodes . LONG ; break ; case ' ' : locals [ numLocal ++ ] = Opcodes . DOUBLE ; break ; case ' ' : while ( methodDescriptor . charAt ( currentMethodDescritorOffset ) == ' ' ) { ++ currentMethodDescritorOffset ; } if ( methodDescriptor . charAt ( currentMethodDescritorOffset ) == ' ' ) { ++ currentMethodDescritorOffset ; while ( methodDescriptor . charAt ( currentMethodDescritorOffset ) != ' ' ) { ++ currentMethodDescritorOffset ; } } locals [ numLocal ++ ] = methodDescriptor . substring ( currentArgumentDescriptorStartOffset , ++ currentMethodDescritorOffset ) ; break ; case ' ' : while ( methodDescriptor . charAt ( currentMethodDescritorOffset ) != ' ' ) { ++ currentMethodDescritorOffset ; } locals [ numLocal ++ ] = methodDescriptor . substring ( currentArgumentDescriptorStartOffset + 1 , currentMethodDescritorOffset ++ ) ; break ; default : context . currentFrameLocalCount = numLocal ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JVMS stack_map_frame structure and stores the result in the given { @link Context } object . This method can also be used to read a full_frame structure excluding its frame_type field ( this is used to parse the legacy StackMap attributes ) . [CODESPLIT] private int readStackMapFrame ( final int stackMapFrameOffset , final boolean compressed , final boolean expand , final Context context ) { int currentOffset = stackMapFrameOffset ; final char [ ] charBuffer = context . charBuffer ; final Label [ ] labels = context . currentMethodLabels ; int frameType ; if ( compressed ) { // Read the frame_type field. frameType = b [ currentOffset ++ ] & 0xFF ; } else { frameType = Frame . FULL_FRAME ; context . currentFrameOffset = - 1 ; } int offsetDelta ; context . currentFrameLocalCountDelta = 0 ; if ( frameType < Frame . SAME_LOCALS_1_STACK_ITEM_FRAME ) { offsetDelta = frameType ; context . currentFrameType = Opcodes . F_SAME ; context . currentFrameStackCount = 0 ; } else if ( frameType < Frame . RESERVED ) { offsetDelta = frameType - Frame . SAME_LOCALS_1_STACK_ITEM_FRAME ; currentOffset = readVerificationTypeInfo ( currentOffset , context . currentFrameStackTypes , 0 , charBuffer , labels ) ; context . currentFrameType = Opcodes . F_SAME1 ; context . currentFrameStackCount = 1 ; } else if ( frameType >= Frame . SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED ) { offsetDelta = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; if ( frameType == Frame . SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED ) { currentOffset = readVerificationTypeInfo ( currentOffset , context . currentFrameStackTypes , 0 , charBuffer , labels ) ; context . currentFrameType = Opcodes . F_SAME1 ; context . currentFrameStackCount = 1 ; } else if ( frameType >= Frame . CHOP_FRAME && frameType < Frame . SAME_FRAME_EXTENDED ) { context . currentFrameType = Opcodes . F_CHOP ; context . currentFrameLocalCountDelta = Frame . SAME_FRAME_EXTENDED - frameType ; context . currentFrameLocalCount -= context . currentFrameLocalCountDelta ; context . currentFrameStackCount = 0 ; } else if ( frameType == Frame . SAME_FRAME_EXTENDED ) { context . currentFrameType = Opcodes . F_SAME ; context . currentFrameStackCount = 0 ; } else if ( frameType < Frame . FULL_FRAME ) { int local = expand ? context . currentFrameLocalCount : 0 ; for ( int k = frameType - Frame . SAME_FRAME_EXTENDED ; k > 0 ; k -- ) { currentOffset = readVerificationTypeInfo ( currentOffset , context . currentFrameLocalTypes , local ++ , charBuffer , labels ) ; } context . currentFrameType = Opcodes . F_APPEND ; context . currentFrameLocalCountDelta = frameType - Frame . SAME_FRAME_EXTENDED ; context . currentFrameLocalCount += context . currentFrameLocalCountDelta ; context . currentFrameStackCount = 0 ; } else { final int numberOfLocals = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; context . currentFrameType = Opcodes . F_FULL ; context . currentFrameLocalCountDelta = numberOfLocals ; context . currentFrameLocalCount = numberOfLocals ; for ( int local = 0 ; local < numberOfLocals ; ++ local ) { currentOffset = readVerificationTypeInfo ( currentOffset , context . currentFrameLocalTypes , local , charBuffer , labels ) ; } final int numberOfStackItems = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; context . currentFrameStackCount = numberOfStackItems ; for ( int stack = 0 ; stack < numberOfStackItems ; ++ stack ) { currentOffset = readVerificationTypeInfo ( currentOffset , context . currentFrameStackTypes , stack , charBuffer , labels ) ; } } } else { throw new IllegalArgumentException ( ) ; } context . currentFrameOffset += offsetDelta + 1 ; createLabel ( context . currentFrameOffset , labels ) ; return currentOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JVMS verification_type_info structure and stores it at the given index in the given array . [CODESPLIT] private int readVerificationTypeInfo ( final int verificationTypeInfoOffset , final Object [ ] frame , final int index , final char [ ] charBuffer , final Label [ ] labels ) { int currentOffset = verificationTypeInfoOffset ; int tag = b [ currentOffset ++ ] & 0xFF ; switch ( tag ) { case Frame . ITEM_TOP : frame [ index ] = Opcodes . TOP ; break ; case Frame . ITEM_INTEGER : frame [ index ] = Opcodes . INTEGER ; break ; case Frame . ITEM_FLOAT : frame [ index ] = Opcodes . FLOAT ; break ; case Frame . ITEM_DOUBLE : frame [ index ] = Opcodes . DOUBLE ; break ; case Frame . ITEM_LONG : frame [ index ] = Opcodes . LONG ; break ; case Frame . ITEM_NULL : frame [ index ] = Opcodes . NULL ; break ; case Frame . ITEM_UNINITIALIZED_THIS : frame [ index ] = Opcodes . UNINITIALIZED_THIS ; break ; case Frame . ITEM_OBJECT : frame [ index ] = readClass ( currentOffset , charBuffer ) ; currentOffset += 2 ; break ; case Frame . ITEM_UNINITIALIZED : frame [ index ] = createLabel ( readUnsignedShort ( currentOffset ) , labels ) ; currentOffset += 2 ; break ; default : throw new IllegalArgumentException ( ) ; } return currentOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the offset in { @link #b } of the first ClassFile s attributes array field entry . [CODESPLIT] final int getFirstAttributeOffset ( ) { // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes // each), as well as the interfaces array field (2 bytes per interface). int currentOffset = header + 8 + readUnsignedShort ( header + 6 ) * 2 ; // Read the fields_count field. int fieldsCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; // Skip the 'fields' array field. while ( fieldsCount -- > 0 ) { // Invariant: currentOffset is the offset of a field_info structure. // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the // attributes_count field. int attributesCount = readUnsignedShort ( currentOffset + 6 ) ; currentOffset += 8 ; // Skip the 'attributes' array field. while ( attributesCount -- > 0 ) { // Invariant: currentOffset is the offset of an attribute_info structure. // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip // this many bytes, plus 6 for the attribute_name_index and attribute_length fields // (yielding the total size of the attribute_info structure). currentOffset += 6 + readInt ( currentOffset + 2 ) ; } } // Skip the methods_count and 'methods' fields, using the same method as above. int methodsCount = readUnsignedShort ( currentOffset ) ; currentOffset += 2 ; while ( methodsCount -- > 0 ) { int attributesCount = readUnsignedShort ( currentOffset + 6 ) ; currentOffset += 8 ; while ( attributesCount -- > 0 ) { currentOffset += 6 + readInt ( currentOffset + 2 ) ; } } // Skip the ClassFile's attributes_count field. return currentOffset + 2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the BootstrapMethods attribute to compute the offset of each bootstrap method . [CODESPLIT] private int [ ] readBootstrapMethodsAttribute ( final int maxStringLength ) { char [ ] charBuffer = new char [ maxStringLength ] ; int currentAttributeOffset = getFirstAttributeOffset ( ) ; int [ ] currentBootstrapMethodOffsets = null ; for ( int i = readUnsignedShort ( currentAttributeOffset - 2 ) ; i > 0 ; -- i ) { // Read the attribute_info's attribute_name and attribute_length fields. String attributeName = readUTF8 ( currentAttributeOffset , charBuffer ) ; int attributeLength = readInt ( currentAttributeOffset + 2 ) ; currentAttributeOffset += 6 ; if ( Constants . BOOTSTRAP_METHODS . equals ( attributeName ) ) { // Read the num_bootstrap_methods field and create an array of this size. currentBootstrapMethodOffsets = new int [ readUnsignedShort ( currentAttributeOffset ) ] ; // Compute and store the offset of each 'bootstrap_methods' array field entry. int currentBootstrapMethodOffset = currentAttributeOffset + 2 ; for ( int j = 0 ; j < currentBootstrapMethodOffsets . length ; ++ j ) { currentBootstrapMethodOffsets [ j ] = currentBootstrapMethodOffset ; // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each), // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2). currentBootstrapMethodOffset += 4 + readUnsignedShort ( currentBootstrapMethodOffset + 2 ) * 2 ; } return currentBootstrapMethodOffsets ; } currentAttributeOffset += attributeLength ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a non standard JVMS attribute structure in { @link #b } . [CODESPLIT] private Attribute readAttribute ( final Attribute [ ] attributePrototypes , final String type , final int offset , final int length , final char [ ] charBuffer , final int codeAttributeOffset , final Label [ ] labels ) { for ( Attribute attributePrototype : attributePrototypes ) { if ( attributePrototype . type . equals ( type ) ) { return attributePrototype . read ( this , offset , length , charBuffer , codeAttributeOffset , labels ) ; } } return new Attribute ( type ) . read ( this , offset , length , null , - 1 , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a signed int value in { @link #b } . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public int readInt ( final int offset ) { byte [ ] classFileBuffer = b ; return ( ( classFileBuffer [ offset ] & 0xFF ) << 24 ) | ( ( classFileBuffer [ offset + 1 ] & 0xFF ) << 16 ) | ( ( classFileBuffer [ offset + 2 ] & 0xFF ) << 8 ) | ( classFileBuffer [ offset + 3 ] & 0xFF ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a signed long value in { @link #b } . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public long readLong ( final int offset ) { long l1 = readInt ( offset ) ; long l0 = readInt ( offset + 4 ) & 0xFFFFFFFF  L ; return ( l1 << 32 ) | l0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DontCheck ( AbbreviationAsWordInName ) : can t be renamed ( for backward binary compatibility ) . [CODESPLIT] public String readUTF8 ( final int offset , final char [ ] charBuffer ) { int constantPoolEntryIndex = readUnsignedShort ( offset ) ; if ( offset == 0 || constantPoolEntryIndex == 0 ) { return null ; } return readUtf ( constantPoolEntryIndex , charBuffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a CONSTANT_Utf8 constant pool entry in { @link #b } . [CODESPLIT] final String readUtf ( final int constantPoolEntryIndex , final char [ ] charBuffer ) { String value = constantUtf8Values [ constantPoolEntryIndex ] ; if ( value != null ) { return value ; } int cpInfoOffset = cpInfoOffsets [ constantPoolEntryIndex ] ; return constantUtf8Values [ constantPoolEntryIndex ] = readUtf ( cpInfoOffset + 2 , readUnsignedShort ( cpInfoOffset ) , charBuffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads an UTF8 string in { @link #b } . [CODESPLIT] private String readUtf ( final int utfOffset , final int utfLength , final char [ ] charBuffer ) { int currentOffset = utfOffset ; int endOffset = currentOffset + utfLength ; int strLength = 0 ; byte [ ] classFileBuffer = b ; while ( currentOffset < endOffset ) { int currentByte = classFileBuffer [ currentOffset ++ ] ; if ( ( currentByte & 0x80 ) == 0 ) { charBuffer [ strLength ++ ] = ( char ) ( currentByte & 0x7F ) ; } else if ( ( currentByte & 0xE0 ) == 0xC0 ) { charBuffer [ strLength ++ ] = ( char ) ( ( ( currentByte & 0x1F ) << 6 ) + ( classFileBuffer [ currentOffset ++ ] & 0x3F ) ) ; } else { charBuffer [ strLength ++ ] = ( char ) ( ( ( currentByte & 0xF ) << 12 ) + ( ( classFileBuffer [ currentOffset ++ ] & 0x3F ) << 6 ) + ( classFileBuffer [ currentOffset ++ ] & 0x3F ) ) ; } } return new String ( charBuffer , 0 , strLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a CONSTANT_Dynamic constant pool entry in { @link #b } . [CODESPLIT] private ConstantDynamic readConstantDynamic ( final int constantPoolEntryIndex , final char [ ] charBuffer ) { ConstantDynamic constantDynamic = constantDynamicValues [ constantPoolEntryIndex ] ; if ( constantDynamic != null ) { return constantDynamic ; } int cpInfoOffset = cpInfoOffsets [ constantPoolEntryIndex ] ; int nameAndTypeCpInfoOffset = cpInfoOffsets [ readUnsignedShort ( cpInfoOffset + 2 ) ] ; String name = readUTF8 ( nameAndTypeCpInfoOffset , charBuffer ) ; String descriptor = readUTF8 ( nameAndTypeCpInfoOffset + 2 , charBuffer ) ; int bootstrapMethodOffset = bootstrapMethodOffsets [ readUnsignedShort ( cpInfoOffset ) ] ; Handle handle = ( Handle ) readConst ( readUnsignedShort ( bootstrapMethodOffset ) , charBuffer ) ; Object [ ] bootstrapMethodArguments = new Object [ readUnsignedShort ( bootstrapMethodOffset + 2 ) ] ; bootstrapMethodOffset += 4 ; for ( int i = 0 ; i < bootstrapMethodArguments . length ; i ++ ) { bootstrapMethodArguments [ i ] = readConst ( readUnsignedShort ( bootstrapMethodOffset ) , charBuffer ) ; bootstrapMethodOffset += 2 ; } return constantDynamicValues [ constantPoolEntryIndex ] = new ConstantDynamic ( name , descriptor , handle , bootstrapMethodArguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a numeric or string constant pool entry in { @link #b } . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public Object readConst ( final int constantPoolEntryIndex , final char [ ] charBuffer ) { int cpInfoOffset = cpInfoOffsets [ constantPoolEntryIndex ] ; switch ( b [ cpInfoOffset - 1 ] ) { case Symbol . CONSTANT_INTEGER_TAG : return readInt ( cpInfoOffset ) ; case Symbol . CONSTANT_FLOAT_TAG : return Float . intBitsToFloat ( readInt ( cpInfoOffset ) ) ; case Symbol . CONSTANT_LONG_TAG : return readLong ( cpInfoOffset ) ; case Symbol . CONSTANT_DOUBLE_TAG : return Double . longBitsToDouble ( readLong ( cpInfoOffset ) ) ; case Symbol . CONSTANT_CLASS_TAG : return Type . getObjectType ( readUTF8 ( cpInfoOffset , charBuffer ) ) ; case Symbol . CONSTANT_STRING_TAG : return readUTF8 ( cpInfoOffset , charBuffer ) ; case Symbol . CONSTANT_METHOD_TYPE_TAG : return Type . getMethodType ( readUTF8 ( cpInfoOffset , charBuffer ) ) ; case Symbol . CONSTANT_METHOD_HANDLE_TAG : int referenceKind = readByte ( cpInfoOffset ) ; int referenceCpInfoOffset = cpInfoOffsets [ readUnsignedShort ( cpInfoOffset + 1 ) ] ; int nameAndTypeCpInfoOffset = cpInfoOffsets [ readUnsignedShort ( referenceCpInfoOffset + 2 ) ] ; String owner = readClass ( referenceCpInfoOffset , charBuffer ) ; String name = readUTF8 ( nameAndTypeCpInfoOffset , charBuffer ) ; String descriptor = readUTF8 ( nameAndTypeCpInfoOffset + 2 , charBuffer ) ; boolean isInterface = b [ referenceCpInfoOffset - 1 ] == Symbol . CONSTANT_INTERFACE_METHODREF_TAG ; return new Handle ( referenceKind , owner , name , descriptor , isInterface ) ; case Symbol . CONSTANT_DYNAMIC_TAG : return readConstantDynamic ( constantPoolEntryIndex , charBuffer ) ; default : throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Clob get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getClob ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Clob value , final int dbSqlType ) throws SQLException { st . setClob ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets content type . If charset is missing current value is reset . If passed value is <code > null< / code > content type will be reset as never set . [CODESPLIT] @ Override public void setContentType ( final String type ) { if ( type == null ) { mimeType = null ; characterEncoding = null ; return ; } ContentTypeHeaderResolver contentTypeResolver = new ContentTypeHeaderResolver ( type ) ; mimeType = contentTypeResolver . getMimeType ( ) ; characterEncoding = contentTypeResolver . getEncoding ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns content type and optionally charset . Returns <code > null< / code > when mime type is not set . [CODESPLIT] @ Override public String getContentType ( ) { String contentType = mimeType ; if ( mimeType != null && characterEncoding != null ) { contentType += \";charset=\" + characterEncoding ; } return contentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getString ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final String value , final int dbSqlType ) throws SQLException { st . setString ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects all declared constructors of a target type . [CODESPLIT] protected CtorDescriptor [ ] inspectConstructors ( ) { Class type = classDescriptor . getType ( ) ; Constructor [ ] ctors = type . getDeclaredConstructors ( ) ; CtorDescriptor [ ] allCtors = new CtorDescriptor [ ctors . length ] ; for ( int i = 0 ; i < ctors . length ; i ++ ) { Constructor ctor = ctors [ i ] ; CtorDescriptor ctorDescriptor = createCtorDescriptor ( ctor ) ; allCtors [ i ] = ctorDescriptor ; if ( ctorDescriptor . isDefault ( ) ) { defaultCtor = ctorDescriptor ; } } return allCtors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds constructor description that matches given argument types . [CODESPLIT] public CtorDescriptor getCtorDescriptor ( final Class ... args ) { ctors : for ( CtorDescriptor ctorDescriptor : allCtors ) { Class [ ] arg = ctorDescriptor . getParameters ( ) ; if ( arg . length != args . length ) { continue ; } for ( int j = 0 ; j < arg . length ; j ++ ) { if ( arg [ j ] != args [ j ] ) { continue ctors ; } } return ctorDescriptor ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns instance map from http request . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected Map < String , TransientBeanData > getRequestMap ( final HttpServletRequest servletRequest ) { return ( Map < String , TransientBeanData > ) servletRequest . getAttribute ( ATTR_NAME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates instance map and stores it in the request . [CODESPLIT] protected Map < String , TransientBeanData > createRequestMap ( final HttpServletRequest servletRequest ) { Map < String , TransientBeanData > map = new HashMap <> ( ) ; servletRequest . setAttribute ( ATTR_NAME , map ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns request from current thread . [CODESPLIT] protected HttpServletRequest getCurrentHttpRequest ( ) { HttpServletRequest request = RequestContextListener . getRequest ( ) ; if ( request == null ) { throw new PetiteException ( \"No HTTP request bound to the current thread. Is RequestContextListener registered?\" ) ; } return request ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected long [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final long [ ] target = new long [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Long > longArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final long convertedValue = convertType ( element ) ; longArrayList . add ( Long . valueOf ( convertedValue ) ) ; } final long [ ] array = new long [ longArrayList . size ( ) ] ; for ( int i = 0 ; i < longArrayList . size ( ) ; i ++ ) { final Long l = longArrayList . get ( i ) ; array [ i ] = l . longValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts array value to array . [CODESPLIT] protected long [ ] convertArrayToArray ( final Object value ) { final Class valueComponentType = value . getClass ( ) . getComponentType ( ) ; final long [ ] result ; if ( valueComponentType . isPrimitive ( ) ) { result = convertPrimitiveArrayToArray ( value , valueComponentType ) ; } else { // convert object array to target array final Object [ ] array = ( Object [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts primitive array to target array . [CODESPLIT] protected long [ ] convertPrimitiveArrayToArray ( final Object value , final Class primitiveComponentType ) { long [ ] result = null ; if ( primitiveComponentType == long . class ) { return ( long [ ] ) value ; } if ( primitiveComponentType == int . class ) { final int [ ] array = ( int [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = array [ i ] ; } } else if ( primitiveComponentType == float . class ) { final float [ ] array = ( float [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = ( long ) array [ i ] ; } } else if ( primitiveComponentType == double . class ) { final double [ ] array = ( double [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = ( long ) array [ i ] ; } } else if ( primitiveComponentType == short . class ) { final short [ ] array = ( short [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = array [ i ] ; } } else if ( primitiveComponentType == byte . class ) { final byte [ ] array = ( byte [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = array [ i ] ; } } else if ( primitiveComponentType == char . class ) { final char [ ] array = ( char [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = array [ i ] ; } } else if ( primitiveComponentType == boolean . class ) { final boolean [ ] array = ( boolean [ ] ) value ; result = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = array [ i ] ? 1 : 0 ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes Decora filter . Loads manager and parser from init parameters . [CODESPLIT] @ Override public void init ( final FilterConfig filterConfig ) throws ServletException { // final String decoraManagerClass = filterConfig . getInitParameter ( PARAM_DECORA_MANAGER ) ; if ( decoraManagerClass != null ) { try { final Class decoraManagerType = ClassLoaderUtil . loadClass ( decoraManagerClass ) ; decoraManager = ( DecoraManager ) ClassUtil . newInstance ( decoraManagerType ) ; } catch ( Exception ex ) { log . error ( \"Unable to load Decora manager class: \" + decoraManagerClass , ex ) ; throw new ServletException ( ex ) ; } } else { decoraManager = createDecoraManager ( ) ; } // final String decoraParserClass = filterConfig . getInitParameter ( PARAM_DECORA_PARSER ) ; if ( decoraParserClass != null ) { try { final Class decoraParserType = ClassLoaderUtil . loadClass ( decoraParserClass ) ; decoraParser = ( DecoraParser ) ClassUtil . newInstance ( decoraParserType ) ; } catch ( Exception ex ) { log . error ( \"Unable to load Decora parser class: \" + decoraParserClass , ex ) ; throw new ServletException ( ex ) ; } } else { decoraParser = createDecoraParser ( ) ; } // final String decoraCache = filterConfig . getInitParameter ( PARAM_DECORA_CACHE ) ; if ( decoraCache != null ) { cached = Converter . get ( ) . toBoolean ( decoraCache , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers file consumer [CODESPLIT] public FindFile onFile ( final Consumer < File > fileConsumer ) { if ( consumers == null ) { consumers = Consumers . of ( fileConsumer ) ; } else { consumers . add ( fileConsumer ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the search path . If provided path contains { [CODESPLIT] public FindFile searchPath ( final String searchPath ) { if ( searchPath . indexOf ( File . pathSeparatorChar ) != - 1 ) { String [ ] paths = StringUtil . split ( searchPath , File . pathSeparator ) ; for ( String path : paths ) { addPath ( new File ( path ) ) ; } } else { addPath ( new File ( searchPath ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the search path . Throws an exception if URI is invalid . [CODESPLIT] public FindFile searchPath ( final URI searchPath ) { File file ; try { file = new File ( searchPath ) ; } catch ( Exception ex ) { throw new FindFileException ( \"URI error: \" + searchPath , ex ) ; } addPath ( file ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the search path . Throws an exception if URL is invalid . [CODESPLIT] public FindFile searchPath ( final URL searchPath ) { File file = FileUtil . toContainerFile ( searchPath ) ; if ( file == null ) { throw new FindFileException ( \"URL error: \" + searchPath ) ; } addPath ( file ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines include patterns . [CODESPLIT] public FindFile include ( final String ... patterns ) { for ( String pattern : patterns ) { rules . include ( pattern ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines exclude patterns . [CODESPLIT] public FindFile exclude ( final String ... patterns ) { for ( String pattern : patterns ) { rules . exclude ( pattern ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if file is accepted based on include and exclude rules . Called on each file entry ( file or directory ) and returns <code > true< / code > if file passes search criteria . File is matched using { [CODESPLIT] protected boolean acceptFile ( final File file ) { String matchingFilePath = getMatchingFilePath ( file ) ; if ( rules . match ( matchingFilePath ) ) { if ( consumers != null ) { consumers . accept ( file ) ; } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves file path depending on { [CODESPLIT] protected String getMatchingFilePath ( final File file ) { String path = null ; switch ( matchType ) { case FULL_PATH : path = file . getAbsolutePath ( ) ; break ; case RELATIVE_PATH : path = file . getAbsolutePath ( ) ; path = path . substring ( rootPath . length ( ) ) ; break ; case NAME : path = file . getName ( ) ; } path = FileNameUtil . separatorsToUnix ( path ) ; return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds existing search path to the file list . Non existing files are ignored . If path is a folder it will be scanned for all files . [CODESPLIT] protected void addPath ( final File path ) { if ( ! path . exists ( ) ) { return ; } if ( pathList == null ) { pathList = new LinkedList <> ( ) ; } pathList . add ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the search so it can be run again with very same parameters ( and sorting options ) . [CODESPLIT] public void reset ( ) { pathList = pathListOriginal ; pathListOriginal = null ; todoFiles = null ; lastFile = null ; rules . reset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the next file . Returns founded file that matches search configuration or <code > null< / code > if no more files can be found . [CODESPLIT] public File nextFile ( ) { if ( todoFiles == null ) { init ( ) ; } while ( true ) { // iterate files if ( ! todoFiles . isEmpty ( ) ) { FilesIterator filesIterator = todoFiles . getLast ( ) ; File nextFile = filesIterator . next ( ) ; if ( nextFile == null ) { todoFiles . removeLast ( ) ; continue ; } if ( nextFile . isDirectory ( ) ) { if ( ! walking ) { todoFolders . add ( nextFile ) ; continue ; } // walking if ( recursive ) { todoFiles . add ( new FilesIterator ( nextFile ) ) ; } if ( includeDirs ) { if ( acceptFile ( nextFile ) ) { lastFile = nextFile ; return nextFile ; } } continue ; } lastFile = nextFile ; return nextFile ; } // process folders File folder ; boolean initialDir = false ; if ( todoFolders . isEmpty ( ) ) { if ( pathList . isEmpty ( ) ) { // the end return null ; } folder = pathList . removeFirst ( ) ; rootFile = folder ; rootPath = rootFile . getAbsolutePath ( ) ; initialDir = true ; } else { folder = todoFolders . removeFirst ( ) ; } if ( ( initialDir ) || ( recursive ) ) { todoFiles . add ( new FilesIterator ( folder ) ) ; } if ( ( ! initialDir ) && ( includeDirs ) ) { if ( acceptFile ( folder ) ) { lastFile = folder ; return folder ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all files and returns list of founded files . [CODESPLIT] public List < File > findAll ( ) { List < File > allFiles = new ArrayList <> ( ) ; File file ; while ( ( file = nextFile ( ) ) != null ) { allFiles . add ( file ) ; } return allFiles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes file walking . Separates input files and folders . [CODESPLIT] protected void init ( ) { rules . detectMode ( ) ; todoFiles = new LinkedList <> ( ) ; todoFolders = new LinkedList <> ( ) ; if ( pathList == null ) { pathList = new LinkedList <> ( ) ; return ; } if ( pathListOriginal == null ) { pathListOriginal = ( LinkedList < File > ) pathList . clone ( ) ; } String [ ] files = new String [ pathList . size ( ) ] ; int index = 0 ; Iterator < File > iterator = pathList . iterator ( ) ; while ( iterator . hasNext ( ) ) { File file = iterator . next ( ) ; if ( file . isFile ( ) ) { files [ index ++ ] = file . getAbsolutePath ( ) ; iterator . remove ( ) ; } } if ( index != 0 ) { FilesIterator filesIterator = new FilesIterator ( files ) ; todoFiles . add ( filesIterator ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns file walking iterator . [CODESPLIT] @ Override public Iterator < File > iterator ( ) { return new Iterator < File > ( ) { private File nextFile ; @ Override public boolean hasNext ( ) { nextFile = nextFile ( ) ; return nextFile != null ; } @ Override public File next ( ) { if ( nextFile == null ) { throw new NoSuchElementException ( ) ; } return nextFile ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public byte [ ] get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getBytes ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final byte [ ] value , final int dbSqlType ) throws SQLException { st . setBytes ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves bean s auto - wire flag from the annotation . Returns default auto - wire if annotation doesn t exist . [CODESPLIT] public WiringMode resolveBeanWiringMode ( final Class type ) { PetiteBean petiteBean = ( ( Class < ? > ) type ) . getAnnotation ( PetiteBean . class ) ; return petiteBean != null ? petiteBean . wiring ( ) : WiringMode . DEFAULT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves bean s scope type from the annotation . Returns <code > null< / code > if annotation doesn t exist . [CODESPLIT] public Class < ? extends Scope > resolveBeanScopeType ( final Class type ) { PetiteBean petiteBean = ( ( Class < ? > ) type ) . getAnnotation ( PetiteBean . class ) ; return petiteBean != null ? petiteBean . scope ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves bean s name from bean annotation or type name . May be used for resolving bean name of base type during registration of bean subclass . [CODESPLIT] public String resolveBeanName ( final Class type , final boolean useLongTypeName ) { PetiteBean petiteBean = ( ( Class < ? > ) type ) . getAnnotation ( PetiteBean . class ) ; String name = null ; if ( petiteBean != null ) { name = petiteBean . value ( ) . trim ( ) ; } if ( ( name == null ) || ( name . length ( ) == 0 ) ) { if ( useLongTypeName ) { name = type . getName ( ) ; } else { name = StringUtil . uncapitalize ( type . getSimpleName ( ) ) ; } } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if bean has name defined by Petite annotation . [CODESPLIT] public boolean beanHasAnnotationName ( final Class type ) { PetiteBean petiteBean = ( ( Class < ? > ) type ) . getAnnotation ( PetiteBean . class ) ; if ( petiteBean == null ) { return false ; } String name = petiteBean . value ( ) . trim ( ) ; return ! name . isEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a writer . [CODESPLIT] public PrintWriter getWriter ( ) { if ( outWriter == null ) { if ( outStream != null ) { throw new IllegalStateException ( \"Can't call getWriter() after getOutputStream()\" ) ; } bufferedWriter = new FastCharArrayWriter ( ) ; outWriter = new PrintWriter ( bufferedWriter ) { @ Override public void close ( ) { // do not close the print writer after rendering // since it will remove reference to bufferedWriter } } ; } return outWriter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a servlet output stream . [CODESPLIT] public ServletOutputStream getOutputStream ( ) { if ( outStream == null ) { if ( outWriter != null ) { throw new IllegalStateException ( \"Can't call getOutputStream() after getWriter()\" ) ; } bufferOutputStream = new FastByteArrayServletOutputStream ( ) ; outStream = bufferOutputStream ; } return outStream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link Type } corresponding to the given class . [CODESPLIT] public static Type getType ( final Class < ? > clazz ) { if ( clazz . isPrimitive ( ) ) { if ( clazz == Integer . TYPE ) { return INT_TYPE ; } else if ( clazz == Void . TYPE ) { return VOID_TYPE ; } else if ( clazz == Boolean . TYPE ) { return BOOLEAN_TYPE ; } else if ( clazz == Byte . TYPE ) { return BYTE_TYPE ; } else if ( clazz == Character . TYPE ) { return CHAR_TYPE ; } else if ( clazz == Short . TYPE ) { return SHORT_TYPE ; } else if ( clazz == Double . TYPE ) { return DOUBLE_TYPE ; } else if ( clazz == Float . TYPE ) { return FLOAT_TYPE ; } else if ( clazz == Long . TYPE ) { return LONG_TYPE ; } else { throw new AssertionError ( ) ; } } else { return getType ( getDescriptor ( clazz ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link Type } corresponding to the given internal name . [CODESPLIT] public static Type getObjectType ( final String internalName ) { return new Type ( internalName . charAt ( 0 ) == ' ' ? ARRAY : INTERNAL , internalName , 0 , internalName . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the method { @link Type } corresponding to the given argument and return types . [CODESPLIT] public static Type getMethodType ( final Type returnType , final Type ... argumentTypes ) { return getType ( getMethodDescriptor ( returnType , argumentTypes ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link Type } values corresponding to the argument types of the given method descriptor . [CODESPLIT] public static Type [ ] getArgumentTypes ( final String methodDescriptor ) { // First step: compute the number of argument types in methodDescriptor. int numArgumentTypes = 0 ; // Skip the first character, which is always a '('. int currentOffset = 1 ; // Parse the argument types, one at a each loop iteration. while ( methodDescriptor . charAt ( currentOffset ) != ' ' ) { while ( methodDescriptor . charAt ( currentOffset ) == ' ' ) { currentOffset ++ ; } if ( methodDescriptor . charAt ( currentOffset ++ ) == ' ' ) { // Skip the argument descriptor content. currentOffset = methodDescriptor . indexOf ( ' ' , currentOffset ) + 1 ; } ++ numArgumentTypes ; } // Second step: create a Type instance for each argument type. Type [ ] argumentTypes = new Type [ numArgumentTypes ] ; // Skip the first character, which is always a '('. currentOffset = 1 ; // Parse and create the argument types, one at each loop iteration. int currentArgumentTypeIndex = 0 ; while ( methodDescriptor . charAt ( currentOffset ) != ' ' ) { final int currentArgumentTypeOffset = currentOffset ; while ( methodDescriptor . charAt ( currentOffset ) == ' ' ) { currentOffset ++ ; } if ( methodDescriptor . charAt ( currentOffset ++ ) == ' ' ) { // Skip the argument descriptor content. currentOffset = methodDescriptor . indexOf ( ' ' , currentOffset ) + 1 ; } argumentTypes [ currentArgumentTypeIndex ++ ] = getTypeInternal ( methodDescriptor , currentArgumentTypeOffset , currentOffset ) ; } return argumentTypes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link Type } corresponding to the return type of the given method descriptor . [CODESPLIT] public static Type getReturnType ( final String methodDescriptor ) { // Skip the first character, which is always a '('. int currentOffset = 1 ; // Skip the argument types, one at a each loop iteration. while ( methodDescriptor . charAt ( currentOffset ) != ' ' ) { while ( methodDescriptor . charAt ( currentOffset ) == ' ' ) { currentOffset ++ ; } if ( methodDescriptor . charAt ( currentOffset ++ ) == ' ' ) { // Skip the argument descriptor content. currentOffset = methodDescriptor . indexOf ( ' ' , currentOffset ) + 1 ; } } return getTypeInternal ( methodDescriptor , currentOffset + 1 , methodDescriptor . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link Type } corresponding to the given field or method descriptor . [CODESPLIT] private static Type getTypeInternal ( final String descriptorBuffer , final int descriptorBegin , final int descriptorEnd ) { switch ( descriptorBuffer . charAt ( descriptorBegin ) ) { case ' ' : return VOID_TYPE ; case ' ' : return BOOLEAN_TYPE ; case ' ' : return CHAR_TYPE ; case ' ' : return BYTE_TYPE ; case ' ' : return SHORT_TYPE ; case ' ' : return INT_TYPE ; case ' ' : return FLOAT_TYPE ; case ' ' : return LONG_TYPE ; case ' ' : return DOUBLE_TYPE ; case ' ' : return new Type ( ARRAY , descriptorBuffer , descriptorBegin , descriptorEnd ) ; case ' ' : return new Type ( OBJECT , descriptorBuffer , descriptorBegin + 1 , descriptorEnd - 1 ) ; case ' ' : return new Type ( METHOD , descriptorBuffer , descriptorBegin , descriptorEnd ) ; default : throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the binary name of the class corresponding to this type . This method must not be used on method types . [CODESPLIT] public String getClassName ( ) { switch ( sort ) { case VOID : return \"void\" ; case BOOLEAN : return \"boolean\" ; case CHAR : return \"char\" ; case BYTE : return \"byte\" ; case SHORT : return \"short\" ; case INT : return \"int\" ; case FLOAT : return \"float\" ; case LONG : return \"long\" ; case DOUBLE : return \"double\" ; case ARRAY : StringBuilder stringBuilder = new StringBuilder ( getElementType ( ) . getClassName ( ) ) ; for ( int i = getDimensions ( ) ; i > 0 ; -- i ) { stringBuilder . append ( \"[]\" ) ; } return stringBuilder . toString ( ) ; case OBJECT : case INTERNAL : return valueBuffer . substring ( valueBegin , valueEnd ) . replace ( ' ' , ' ' ) ; default : throw new AssertionError ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the descriptor corresponding to the given constructor . [CODESPLIT] public static String getConstructorDescriptor ( final Constructor < ? > constructor ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( ' ' ) ; Class < ? > [ ] parameters = constructor . getParameterTypes ( ) ; for ( Class < ? > parameter : parameters ) { appendDescriptor ( parameter , stringBuilder ) ; } return stringBuilder . append ( \")V\" ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the descriptor corresponding to the given argument and return types . [CODESPLIT] public static String getMethodDescriptor ( final Type returnType , final Type ... argumentTypes ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( ' ' ) ; for ( Type argumentType : argumentTypes ) { argumentType . appendDescriptor ( stringBuilder ) ; } stringBuilder . append ( ' ' ) ; returnType . appendDescriptor ( stringBuilder ) ; return stringBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the descriptor corresponding to the given method . [CODESPLIT] public static String getMethodDescriptor ( final Method method ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( ' ' ) ; Class < ? > [ ] parameters = method . getParameterTypes ( ) ; for ( Class < ? > parameter : parameters ) { appendDescriptor ( parameter , stringBuilder ) ; } stringBuilder . append ( ' ' ) ; appendDescriptor ( method . getReturnType ( ) , stringBuilder ) ; return stringBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the descriptor corresponding to this type to the given string buffer . [CODESPLIT] private void appendDescriptor ( final StringBuilder stringBuilder ) { if ( sort == OBJECT ) { stringBuilder . append ( valueBuffer , valueBegin - 1 , valueEnd + 1 ) ; } else if ( sort == INTERNAL ) { stringBuilder . append ( ' ' ) . append ( valueBuffer , valueBegin , valueEnd ) . append ( ' ' ) ; } else { stringBuilder . append ( valueBuffer , valueBegin , valueEnd ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of values of this type . This method must not be used for method types . [CODESPLIT] public int getSize ( ) { switch ( sort ) { case VOID : return 0 ; case BOOLEAN : case CHAR : case BYTE : case SHORT : case INT : case FLOAT : case ARRAY : case OBJECT : case INTERNAL : return 1 ; case LONG : case DOUBLE : return 2 ; default : throw new AssertionError ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the size of the arguments and of the return value of a method . [CODESPLIT] public static int getArgumentsAndReturnSizes ( final String methodDescriptor ) { int argumentsSize = 1 ; // Skip the first character, which is always a '('. int currentOffset = 1 ; int currentChar = methodDescriptor . charAt ( currentOffset ) ; // Parse the argument types and compute their size, one at a each loop iteration. while ( currentChar != ' ' ) { if ( currentChar == ' ' || currentChar == ' ' ) { currentOffset ++ ; argumentsSize += 2 ; } else { while ( methodDescriptor . charAt ( currentOffset ) == ' ' ) { currentOffset ++ ; } if ( methodDescriptor . charAt ( currentOffset ++ ) == ' ' ) { // Skip the argument descriptor content. currentOffset = methodDescriptor . indexOf ( ' ' , currentOffset ) + 1 ; } argumentsSize += 1 ; } currentChar = methodDescriptor . charAt ( currentOffset ) ; } currentChar = methodDescriptor . charAt ( currentOffset + 1 ) ; if ( currentChar == ' ' ) { return argumentsSize << 2 ; } else { int returnSize = ( currentChar == ' ' || currentChar == ' ' ) ? 2 : 1 ; return argumentsSize << 2 | returnSize ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a JVM instruction opcode adapted to this { @link Type } . This method must not be used for method types . [CODESPLIT] public int getOpcode ( final int opcode ) { if ( opcode == Opcodes . IALOAD || opcode == Opcodes . IASTORE ) { switch ( sort ) { case BOOLEAN : case BYTE : return opcode + ( Opcodes . BALOAD - Opcodes . IALOAD ) ; case CHAR : return opcode + ( Opcodes . CALOAD - Opcodes . IALOAD ) ; case SHORT : return opcode + ( Opcodes . SALOAD - Opcodes . IALOAD ) ; case INT : return opcode ; case FLOAT : return opcode + ( Opcodes . FALOAD - Opcodes . IALOAD ) ; case LONG : return opcode + ( Opcodes . LALOAD - Opcodes . IALOAD ) ; case DOUBLE : return opcode + ( Opcodes . DALOAD - Opcodes . IALOAD ) ; case ARRAY : case OBJECT : case INTERNAL : return opcode + ( Opcodes . AALOAD - Opcodes . IALOAD ) ; case METHOD : case VOID : throw new UnsupportedOperationException ( ) ; default : throw new AssertionError ( ) ; } } else { switch ( sort ) { case VOID : if ( opcode != Opcodes . IRETURN ) { throw new UnsupportedOperationException ( ) ; } return Opcodes . RETURN ; case BOOLEAN : case BYTE : case CHAR : case SHORT : case INT : return opcode ; case FLOAT : return opcode + ( Opcodes . FRETURN - Opcodes . IRETURN ) ; case LONG : return opcode + ( Opcodes . LRETURN - Opcodes . IRETURN ) ; case DOUBLE : return opcode + ( Opcodes . DRETURN - Opcodes . IRETURN ) ; case ARRAY : case OBJECT : case INTERNAL : if ( opcode != Opcodes . ILOAD && opcode != Opcodes . ISTORE && opcode != Opcodes . IRETURN ) { throw new UnsupportedOperationException ( ) ; } return opcode + ( Opcodes . ARETURN - Opcodes . IRETURN ) ; case METHOD : throw new UnsupportedOperationException ( ) ; default : throw new AssertionError ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modify the transaction associated with the target object such that the only possible outcome of the transaction is to roll back the transaction . [CODESPLIT] public void setRollbackOnly ( final Throwable th ) { if ( ! isNoTransaction ( ) ) { if ( ( status != STATUS_MARKED_ROLLBACK ) && ( status != STATUS_ACTIVE ) ) { throw new JtxException ( \"TNo active TX that can be marked as rollback only\" ) ; } } rollbackCause = th ; status = STATUS_MARKED_ROLLBACK ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs either commit or rollback on all transaction resources . [CODESPLIT] protected void commitOrRollback ( boolean doCommit ) { if ( log . isDebugEnabled ( ) ) { if ( doCommit ) { log . debug ( \"Commit JTX\" ) ; } else { log . debug ( \"Rollback JTX\" ) ; } } boolean forcedRollback = false ; if ( ! isNoTransaction ( ) ) { if ( isRollbackOnly ( ) ) { if ( doCommit ) { doCommit = false ; forcedRollback = true ; } } else if ( ! isActive ( ) ) { if ( isCompleted ( ) ) { throw new JtxException ( \"TX is already completed, commit or rollback should be called once per TX\" ) ; } throw new JtxException ( \"No active TX to \" + ( doCommit ? \"commit\" : \"rollback\" ) ) ; } } if ( doCommit ) { commitAllResources ( ) ; } else { rollbackAllResources ( forcedRollback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commits all attached resources . On successful commit resource will be closed and detached from this transaction . On exception resource remains attached to transaction . <p > All resources will be committed even if commit fails on some in that process . If there was at least one failed commit its exception will be re - thrown after finishing committing all resources and transaction will be marked as rollback only . [CODESPLIT] protected void commitAllResources ( ) throws JtxException { status = STATUS_COMMITTING ; Exception lastException = null ; Iterator < JtxResource > it = resources . iterator ( ) ; while ( it . hasNext ( ) ) { JtxResource resource = it . next ( ) ; try { resource . commitTransaction ( ) ; it . remove ( ) ; } catch ( Exception ex ) { lastException = ex ; } } if ( lastException != null ) { setRollbackOnly ( lastException ) ; throw new JtxException ( \"Commit failed: one or more TX resources couldn't commit a TX\" , lastException ) ; } txManager . removeTransaction ( this ) ; status = STATUS_COMMITTED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rollbacks all attached resources . Resource will be closed . and detached from this transaction . If exception occurs it will be rethrown at the end . [CODESPLIT] protected void rollbackAllResources ( final boolean wasForced ) { status = STATUS_ROLLING_BACK ; Exception lastException = null ; Iterator < JtxResource > it = resources . iterator ( ) ; while ( it . hasNext ( ) ) { JtxResource resource = it . next ( ) ; try { resource . rollbackTransaction ( ) ; } catch ( Exception ex ) { lastException = ex ; } finally { it . remove ( ) ; } } txManager . removeTransaction ( this ) ; status = STATUS_ROLLEDBACK ; if ( lastException != null ) { status = STATUS_UNKNOWN ; throw new JtxException ( \"Rollback failed: one or more TX resources couldn't rollback a TX\" , lastException ) ; } if ( wasForced ) { throw new JtxException ( \"TX rolled back because it has been marked as rollback-only\" , rollbackCause ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests a resource . If resource is not found it will be created and new transaction will be started on it . [CODESPLIT] public < E > E requestResource ( final Class < E > resourceType ) { if ( isCompleted ( ) ) { throw new JtxException ( \"TX is already completed, resource are not available after commit or rollback\" ) ; } if ( isRollbackOnly ( ) ) { throw new JtxException ( \"TX is marked as rollback only, resource are not available\" , rollbackCause ) ; } if ( ! isNoTransaction ( ) && ! isActive ( ) ) { throw new JtxException ( \"Resources are not available since TX is not active\" ) ; } checkTimeout ( ) ; E resource = lookupResource ( resourceType ) ; if ( resource == null ) { int maxResources = txManager . getMaxResourcesPerTransaction ( ) ; if ( ( maxResources != - 1 ) && ( resources . size ( ) >= maxResources ) ) { throw new JtxException ( \"TX already has attached max. number of resources\" ) ; } JtxResourceManager < E > resourceManager = txManager . lookupResourceManager ( resourceType ) ; resource = resourceManager . beginTransaction ( mode , isActive ( ) ) ; resources . add ( new JtxResource <> ( this , resourceManager , resource ) ) ; } return resource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for open resource . Returns <code > null< / code > if resource not found . Only open resources can be found . [CODESPLIT] protected < E > E lookupResource ( final Class < E > resourceType ) { for ( JtxResource jtxResource : resources ) { if ( jtxResource . isSameTypeAsResource ( resourceType ) ) { //noinspection unchecked return ( E ) jtxResource . getResource ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores name to temporary stack . Used when name s value may or may not be serialized ( e . g . it may be excluded ) in that case we do not need to write the name . [CODESPLIT] public void pushName ( final String name , final boolean withComma ) { pushedName = name ; pushedComma = withComma ; isPushed = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes stored name to JSON string . Cleans storage . [CODESPLIT] protected void popName ( ) { if ( isPushed ) { if ( pushedComma ) { writeComma ( ) ; } String name = pushedName ; pushedName = null ; isPushed = false ; writeName ( name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes object s property name : string and a colon . [CODESPLIT] public void writeName ( final String name ) { if ( name != null ) { writeString ( name ) ; } else { write ( NULL ) ; } write ( ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a quoted and escaped value to the output . [CODESPLIT] public void writeString ( final String value ) { popName ( ) ; write ( StringPool . QUOTE ) ; int len = value . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = value . charAt ( i ) ; switch ( c ) { case ' ' : write ( \"\\\\\\\"\" ) ; break ; case ' ' : write ( \"\\\\\\\\\" ) ; break ; case ' ' : if ( strictStringEncoding ) { write ( \"\\\\/\" ) ; } else { write ( c ) ; } break ; case ' ' : write ( \"\\\\b\" ) ; break ; case ' ' : write ( \"\\\\f\" ) ; break ; case ' ' : write ( \"\\\\n\" ) ; break ; case ' ' : write ( \"\\\\r\" ) ; break ; case ' ' : write ( \"\\\\t\" ) ; break ; default : if ( Character . isISOControl ( c ) ) { unicode ( c ) ; } else { write ( c ) ; } } } write ( StringPool . QUOTE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes unicode representation of a character . [CODESPLIT] protected void unicode ( final char c ) { write ( \"\\\\u\" ) ; int n = c ; for ( int i = 0 ; i < 4 ; ++ i ) { int digit = ( n & 0xf000 ) >> 12 ; char hex = CharUtil . int2hex ( digit ) ; write ( hex ) ; n <<= 4 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends char sequence to the buffer . Used for numbers nulls booleans etc . [CODESPLIT] public void write ( final CharSequence charSequence ) { popName ( ) ; try { out . append ( charSequence ) ; } catch ( IOException ioex ) { throw new JsonException ( ioex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets parsing error log level as a name . [CODESPLIT] public LagartoDomBuilderConfig setParsingErrorLogLevelName ( String logLevel ) { logLevel = logLevel . trim ( ) . toUpperCase ( ) ; parsingErrorLogLevel = Logger . Level . valueOf ( logLevel ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- util methods [CODESPLIT] protected static StringBuilder toUppercase ( final StringBuilder string ) { final int strLen = string . length ( ) ; for ( int i = 0 ; i < strLen ; i ++ ) { char c = string . charAt ( i ) ; char uppercaseChar = Character . toUpperCase ( c ) ; if ( c != uppercaseChar ) { string . setCharAt ( i , uppercaseChar ) ; } } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if provided tag matches decorator tag . [CODESPLIT] public boolean isMatchedTag ( final Tag tag ) { if ( ! tag . nameEquals ( name ) ) { return false ; } if ( id != null ) { CharSequence tagId = tag . getId ( ) ; if ( tagId == null ) { return false ; } if ( ! CharSequenceUtil . equals ( id , tagId ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts defining region by setting the start index and reset region length to zero . [CODESPLIT] public void startRegion ( final int start , final int tagLen , final int deepLevel ) { this . regionStart = start + tagLen ; this . regionLength = 0 ; this . regionTagStart = start ; this . deepLevel = deepLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if region of this Decora tag is inside of region of provided Decora tag . [CODESPLIT] public boolean isInsideOtherTagRegion ( final DecoraTag decoraTag ) { return ( regionStart > decoraTag . getRegionStart ( ) ) && ( regionStart < decoraTag . getRegionStart ( ) + decoraTag . getRegionLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if attribute is containing some value . [CODESPLIT] public boolean isContaining ( final String include ) { if ( value == null ) { return false ; } if ( splits == null ) { splits = StringUtil . splitc ( value , ' ' ) ; } for ( String s : splits ) { if ( s . equals ( include ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers pseudo function . [CODESPLIT] public static void registerPseudoFunction ( final Class < ? extends PseudoFunction > pseudoFunctionType ) { PseudoFunction pseudoFunction ; try { pseudoFunction = ClassUtil . newInstance ( pseudoFunctionType ) ; } catch ( Exception ex ) { throw new CSSellyException ( ex ) ; } PSEUDO_FUNCTION_MAP . put ( pseudoFunction . getPseudoFunctionName ( ) , pseudoFunction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups pseudo function for given pseudo function name . [CODESPLIT] public static PseudoFunction < ? > lookupPseudoFunction ( final String pseudoFunctionName ) { PseudoFunction pseudoFunction = PSEUDO_FUNCTION_MAP . get ( pseudoFunctionName ) ; if ( pseudoFunction == null ) { throw new CSSellyException ( \"Unsupported pseudo function: \" + pseudoFunctionName ) ; } return pseudoFunction ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accepts node within selected results . Invoked after results are matched . [CODESPLIT] @ Override public boolean accept ( final List < Node > currentResults , final Node node , final int index ) { return pseudoFunction . match ( currentResults , node , index , parsedExpression ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates destination subclass header from current target class . Destination name is created from targets by adding a suffix and optionally a number . Destination extends the target . [CODESPLIT] @ Override public void visit ( final int version , int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { wd . init ( name , superName , this . suffix , this . reqProxyClassName ) ; // change access of destination access &= ~ AsmUtil . ACC_ABSTRACT ; // write destination class final int v = ProxettaAsmUtil . resolveJavaVersion ( version ) ; wd . dest . visit ( v , access , wd . thisReference , signature , wd . superName , null ) ; wd . proxyAspects = new ProxyAspectData [ aspects . length ] ; for ( int i = 0 ; i < aspects . length ; i ++ ) { wd . proxyAspects [ i ] = new ProxyAspectData ( wd , aspects [ i ] , i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates proxified methods and constructors . Destination proxy will have all constructors as a target class using { [CODESPLIT] @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { final MethodSignatureVisitor msign = targetClassInfo . lookupMethodSignatureVisitor ( access , name , desc , wd . superReference ) ; if ( msign == null ) { return null ; } if ( msign . isFinal && ! wd . allowFinalMethods ) { return null ; } // destination constructors [A1] if ( name . equals ( INIT ) ) { MethodVisitor mv = wd . dest . visitMethod ( access , name , desc , msign . getAsmMethodSignature ( ) , null ) ; return new ProxettaCtorBuilder ( mv , msign , wd ) ; } // ignore destination static block if ( name . equals ( CLINIT ) ) { return null ; } return applyProxy ( msign ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all destination type annotations to the target . [CODESPLIT] @ Override public AnnotationVisitor visitAnnotation ( final String desc , final boolean visible ) { AnnotationVisitor destAnn = wd . dest . visitAnnotation ( desc , visible ) ; // [A3] return new AnnotationVisitorAdapter ( destAnn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates static initialization block that simply calls all advice static init methods in correct order . [CODESPLIT] protected void makeStaticInitBlock ( ) { if ( wd . adviceClinits != null ) { MethodVisitor mv = wd . dest . visitMethod ( AsmUtil . ACC_STATIC , CLINIT , DESC_VOID , null , null ) ; mv . visitCode ( ) ; for ( String name : wd . adviceClinits ) { mv . visitMethodInsn ( INVOKESTATIC , wd . thisReference , name , DESC_VOID , false ) ; } mv . visitInsn ( RETURN ) ; mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates init method that simply calls all advice constructor methods in correct order . This created init method is called from each destination s constructor . [CODESPLIT] protected void makeProxyConstructor ( ) { MethodVisitor mv = wd . dest . visitMethod ( AsmUtil . ACC_PRIVATE | AsmUtil . ACC_FINAL , ProxettaNames . initMethodName , DESC_VOID , null , null ) ; mv . visitCode ( ) ; if ( wd . adviceInits != null ) { for ( String name : wd . adviceInits ) { mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitMethodInsn ( INVOKESPECIAL , wd . thisReference , name , DESC_VOID , false ) ; } } mv . visitInsn ( RETURN ) ; mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for all public super methods that are not overridden . [CODESPLIT] protected void processSuperMethods ( ) { for ( ClassReader cr : targetClassInfo . superClassReaders ) { cr . accept ( new EmptyClassVisitor ( ) { String declaredClassName ; @ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { declaredClassName = name ; } @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { if ( name . equals ( INIT ) || name . equals ( CLINIT ) ) { return null ; } MethodSignatureVisitor msign = targetClassInfo . lookupMethodSignatureVisitor ( access , name , desc , declaredClassName ) ; if ( msign == null ) { return null ; } return applyProxy ( msign ) ; } } , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if proxy should be applied on method and return proxy method builder if so . Otherwise returns <code > null< / code > . [CODESPLIT] protected ProxettaMethodBuilder applyProxy ( final MethodSignatureVisitor msign ) { List < ProxyAspectData > aspectList = matchMethodPointcuts ( msign ) ; if ( aspectList == null ) { // no pointcuts on this method, return return null ; } int access = msign . getAccessFlags ( ) ; if ( ( access & ACC_ABSTRACT ) != 0 ) { throw new ProxettaException ( \"Unable to process abstract method: \" + msign ) ; } wd . proxyApplied = true ; return new ProxettaMethodBuilder ( msign , wd , aspectList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches pointcuts on method . If no pointcut found returns <code > null< / code > . [CODESPLIT] protected List < ProxyAspectData > matchMethodPointcuts ( final MethodSignatureVisitor msign ) { List < ProxyAspectData > aspectList = null ; for ( ProxyAspectData aspectData : wd . proxyAspects ) { if ( aspectData . apply ( msign ) ) { if ( aspectList == null ) { aspectList = new ArrayList <> ( wd . proxyAspects . length ) ; } aspectList . add ( aspectData ) ; } } return aspectList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds index of given element in inclusive index range . Returns negative value if element is not found . [CODESPLIT] public int find ( int low , int high ) { while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( mid ) ; if ( delta < 0 ) { low = mid + 1 ; } else if ( delta > 0 ) { high = mid - 1 ; } else { return mid ; } } // not found return - ( low + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds very first index of given element in inclusive index range . Returns negative value if element is not found . [CODESPLIT] public int findFirst ( int low , int high ) { int ndx = - 1 ; while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( mid ) ; if ( delta < 0 ) { low = mid + 1 ; } else { if ( delta == 0 ) { ndx = mid ; } high = mid - 1 ; } } if ( ndx == - 1 ) { return - ( low + 1 ) ; } return ndx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds very last index of given element in inclusive index range . Returns negative value if element is not found . [CODESPLIT] public int findLast ( int low , int high ) { int ndx = - 1 ; while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( mid ) ; if ( delta > 0 ) { high = mid - 1 ; } else { if ( delta == 0 ) { ndx = mid ; } low = mid + 1 ; } } if ( ndx == - 1 ) { return - ( low + 1 ) ; } return ndx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- internal [CODESPLIT] protected void startSequence ( final String value ) { if ( prefix == null ) { prefix = new StringBuilder ( ) ; prefix . append ( \"\\u001B[\" ) ; } else { prefix . append ( StringPool . SEMICOLON ) ; } prefix . append ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns chalked string . [CODESPLIT] public String on ( final String string ) { if ( ! enabled ) { return string ; } final StringBuilder sb = new StringBuilder ( ) ; if ( prefix != null ) { sb . append ( prefix ) . append ( \"m\" ) ; } sb . append ( string ) ; if ( suffix != null ) { sb . append ( suffix ) . append ( \"m\" ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------------------------------- [CODESPLIT] @ Override public final void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { this . version = version ; this . accessFlags = access ; this . thisClass = symbolTable . setMajorVersionAndClassName ( version & 0xFFFF , name ) ; if ( signature != null ) { this . signatureIndex = symbolTable . addConstantUtf8 ( signature ) ; } this . superClass = superName == null ? 0 : symbolTable . addConstantClass ( superName ) . index ; if ( interfaces != null && interfaces . length > 0 ) { interfaceCount = interfaces . length ; this . interfaces = new int [ interfaceCount ] ; for ( int i = 0 ; i < interfaceCount ; ++ i ) { this . interfaces [ i ] = symbolTable . addConstantClass ( interfaces [ i ] ) . index ; } } if ( compute == MethodWriter . COMPUTE_MAX_STACK_AND_LOCAL && ( version & 0xFFFF ) >= Opcodes . V1_7 ) { compute = MethodWriter . COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the content of the class file that was built by this ClassWriter . [CODESPLIT] public byte [ ] toByteArray ( ) throws ClassTooLargeException , MethodTooLargeException { // First step: compute the size in bytes of the ClassFile structure. // The magic field uses 4 bytes, 10 mandatory fields (minor_version, major_version, // constant_pool_count, access_flags, this_class, super_class, interfaces_count, fields_count, // methods_count and attributes_count) use 2 bytes each, and each interface uses 2 bytes too. int size = 24 + 2 * interfaceCount ; int fieldsCount = 0 ; FieldWriter fieldWriter = firstField ; while ( fieldWriter != null ) { ++ fieldsCount ; size += fieldWriter . computeFieldInfoSize ( ) ; fieldWriter = ( FieldWriter ) fieldWriter . fv ; } int methodsCount = 0 ; MethodWriter methodWriter = firstMethod ; while ( methodWriter != null ) { ++ methodsCount ; size += methodWriter . computeMethodInfoSize ( ) ; methodWriter = ( MethodWriter ) methodWriter . mv ; } // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. int attributesCount = 0 ; if ( innerClasses != null ) { ++ attributesCount ; size += 8 + innerClasses . length ; symbolTable . addConstantUtf8 ( Constants . INNER_CLASSES ) ; } if ( enclosingClassIndex != 0 ) { ++ attributesCount ; size += 10 ; symbolTable . addConstantUtf8 ( Constants . ENCLOSING_METHOD ) ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && ( version & 0xFFFF ) < Opcodes . V1_5 ) { ++ attributesCount ; size += 6 ; symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ; } if ( signatureIndex != 0 ) { ++ attributesCount ; size += 8 ; symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ; } if ( sourceFileIndex != 0 ) { ++ attributesCount ; size += 8 ; symbolTable . addConstantUtf8 ( Constants . SOURCE_FILE ) ; } if ( debugExtension != null ) { ++ attributesCount ; size += 6 + debugExtension . length ; symbolTable . addConstantUtf8 ( Constants . SOURCE_DEBUG_EXTENSION ) ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { ++ attributesCount ; size += 6 ; symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ; } if ( lastRuntimeVisibleAnnotation != null ) { ++ attributesCount ; size += lastRuntimeVisibleAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_ANNOTATIONS ) ; } if ( lastRuntimeInvisibleAnnotation != null ) { ++ attributesCount ; size += lastRuntimeInvisibleAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS ) ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { ++ attributesCount ; size += lastRuntimeVisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { ++ attributesCount ; size += lastRuntimeInvisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) ; } if ( symbolTable . computeBootstrapMethodsSize ( ) > 0 ) { ++ attributesCount ; size += symbolTable . computeBootstrapMethodsSize ( ) ; } if ( moduleWriter != null ) { attributesCount += moduleWriter . getAttributeCount ( ) ; size += moduleWriter . computeAttributesSize ( ) ; } if ( nestHostClassIndex != 0 ) { ++ attributesCount ; size += 8 ; symbolTable . addConstantUtf8 ( Constants . NEST_HOST ) ; } if ( nestMemberClasses != null ) { ++ attributesCount ; size += 8 + nestMemberClasses . length ; symbolTable . addConstantUtf8 ( Constants . NEST_MEMBERS ) ; } if ( firstAttribute != null ) { attributesCount += firstAttribute . getAttributeCount ( ) ; size += firstAttribute . computeAttributesSize ( symbolTable ) ; } // IMPORTANT: this must be the last part of the ClassFile size computation, because the previous // statements can add attribute names to the constant pool, thereby changing its size! size += symbolTable . getConstantPoolLength ( ) ; int constantPoolCount = symbolTable . getConstantPoolCount ( ) ; if ( constantPoolCount > 0xFFFF ) { throw new ClassTooLargeException ( symbolTable . getClassName ( ) , constantPoolCount ) ; } // Second step: allocate a ByteVector of the correct size (in order to avoid any array copy in // dynamic resizes) and fill it with the ClassFile content. ByteVector result = new ByteVector ( size ) ; result . putInt ( 0xCAFEBABE ) . putInt ( version ) ; symbolTable . putConstantPool ( result ) ; int mask = ( version & 0xFFFF ) < Opcodes . V1_5 ? Opcodes . ACC_SYNTHETIC : 0 ; result . putShort ( accessFlags & ~ mask ) . putShort ( thisClass ) . putShort ( superClass ) ; result . putShort ( interfaceCount ) ; for ( int i = 0 ; i < interfaceCount ; ++ i ) { result . putShort ( interfaces [ i ] ) ; } result . putShort ( fieldsCount ) ; fieldWriter = firstField ; while ( fieldWriter != null ) { fieldWriter . putFieldInfo ( result ) ; fieldWriter = ( FieldWriter ) fieldWriter . fv ; } result . putShort ( methodsCount ) ; boolean hasFrames = false ; boolean hasAsmInstructions = false ; methodWriter = firstMethod ; while ( methodWriter != null ) { hasFrames |= methodWriter . hasFrames ( ) ; hasAsmInstructions |= methodWriter . hasAsmInstructions ( ) ; methodWriter . putMethodInfo ( result ) ; methodWriter = ( MethodWriter ) methodWriter . mv ; } // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. result . putShort ( attributesCount ) ; if ( innerClasses != null ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . INNER_CLASSES ) ) . putInt ( innerClasses . length + 2 ) . putShort ( numberOfInnerClasses ) . putByteArray ( innerClasses . data , 0 , innerClasses . length ) ; } if ( enclosingClassIndex != 0 ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . ENCLOSING_METHOD ) ) . putInt ( 4 ) . putShort ( enclosingClassIndex ) . putShort ( enclosingMethodIndex ) ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && ( version & 0xFFFF ) < Opcodes . V1_5 ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ) . putInt ( 0 ) ; } if ( signatureIndex != 0 ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ) . putInt ( 2 ) . putShort ( signatureIndex ) ; } if ( sourceFileIndex != 0 ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . SOURCE_FILE ) ) . putInt ( 2 ) . putShort ( sourceFileIndex ) ; } if ( debugExtension != null ) { int length = debugExtension . length ; result . putShort ( symbolTable . addConstantUtf8 ( Constants . SOURCE_DEBUG_EXTENSION ) ) . putInt ( length ) . putByteArray ( debugExtension . data , 0 , length ) ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ) . putInt ( 0 ) ; } if ( lastRuntimeVisibleAnnotation != null ) { lastRuntimeVisibleAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_ANNOTATIONS ) , result ) ; } if ( lastRuntimeInvisibleAnnotation != null ) { lastRuntimeInvisibleAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS ) , result ) ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { lastRuntimeVisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) , result ) ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { lastRuntimeInvisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) , result ) ; } symbolTable . putBootstrapMethods ( result ) ; if ( moduleWriter != null ) { moduleWriter . putAttributes ( result ) ; } if ( nestHostClassIndex != 0 ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . NEST_HOST ) ) . putInt ( 2 ) . putShort ( nestHostClassIndex ) ; } if ( nestMemberClasses != null ) { result . putShort ( symbolTable . addConstantUtf8 ( Constants . NEST_MEMBERS ) ) . putInt ( nestMemberClasses . length + 2 ) . putShort ( numberOfNestMemberClasses ) . putByteArray ( nestMemberClasses . data , 0 , nestMemberClasses . length ) ; } if ( firstAttribute != null ) { firstAttribute . putAttributes ( symbolTable , result ) ; } // Third step: replace the ASM specific instructions, if any. if ( hasAsmInstructions ) { return replaceAsmInstructions ( result . data , hasFrames ) ; } else { return result . data ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the equivalent of the given class file with the ASM specific instructions replaced with standard ones . This is done with a ClassReader - &gt ; ClassWriter round trip . [CODESPLIT] private byte [ ] replaceAsmInstructions ( final byte [ ] classFile , final boolean hasFrames ) { final Attribute [ ] attributes = getAttributePrototypes ( ) ; firstField = null ; lastField = null ; firstMethod = null ; lastMethod = null ; lastRuntimeVisibleAnnotation = null ; lastRuntimeInvisibleAnnotation = null ; lastRuntimeVisibleTypeAnnotation = null ; lastRuntimeInvisibleTypeAnnotation = null ; moduleWriter = null ; nestHostClassIndex = 0 ; numberOfNestMemberClasses = 0 ; nestMemberClasses = null ; firstAttribute = null ; compute = hasFrames ? MethodWriter . COMPUTE_INSERTED_FRAMES : MethodWriter . COMPUTE_NOTHING ; new ClassReader ( classFile , 0 , /* checkClassVersion = */ false ) . accept ( this , attributes , ( hasFrames ? ClassReader . EXPAND_FRAMES : 0 ) | ClassReader . EXPAND_ASM_INSNS ) ; return toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the prototypes of the attributes used by this class its fields and its methods . [CODESPLIT] private Attribute [ ] getAttributePrototypes ( ) { Attribute . Set attributePrototypes = new Attribute . Set ( ) ; attributePrototypes . addAttributes ( firstAttribute ) ; FieldWriter fieldWriter = firstField ; while ( fieldWriter != null ) { fieldWriter . collectAttributePrototypes ( attributePrototypes ) ; fieldWriter = ( FieldWriter ) fieldWriter . fv ; } MethodWriter methodWriter = firstMethod ; while ( methodWriter != null ) { methodWriter . collectAttributePrototypes ( attributePrototypes ) ; methodWriter = ( MethodWriter ) methodWriter . mv ; } return attributePrototypes . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a handle to the constant pool of the class being build . Does nothing if the constant pool already contains a similar item . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public int newHandle ( final int tag , final String owner , final String name , final String descriptor , final boolean isInterface ) { return symbolTable . addConstantMethodHandle ( tag , owner , name , descriptor , isInterface ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a dynamic constant reference to the constant pool of the class being build . Does nothing if the constant pool already contains a similar item . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public int newConstantDynamic ( final String name , final String descriptor , final Handle bootstrapMethodHandle , final Object ... bootstrapMethodArguments ) { return symbolTable . addConstantDynamic ( name , descriptor , bootstrapMethodHandle , bootstrapMethodArguments ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an invokedynamic reference to the constant pool of the class being build . Does nothing if the constant pool already contains a similar item . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public int newInvokeDynamic ( final String name , final String descriptor , final Handle bootstrapMethodHandle , final Object ... bootstrapMethodArguments ) { return symbolTable . addConstantInvokeDynamic ( name , descriptor , bootstrapMethodHandle , bootstrapMethodArguments ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a field reference to the constant pool of the class being build . Does nothing if the constant pool already contains a similar item . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public int newField ( final String owner , final String name , final String descriptor ) { return symbolTable . addConstantFieldref ( owner , name , descriptor ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a method reference to the constant pool of the class being build . Does nothing if the constant pool already contains a similar item . <i > This method is intended for { @link Attribute } sub classes and is normally not needed by class generators or adapters . < / i > [CODESPLIT] public int newMethod ( final String owner , final String name , final String descriptor , final boolean isInterface ) { return symbolTable . addConstantMethodref ( owner , name , descriptor , isInterface ) . index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the common super type of the two given types . The default implementation of this method <i > loads< / i > the two given classes and uses the java . lang . Class methods to find the common super class . It can be overridden to compute this common super type in other ways in particular without actually loading any class or to take into account the class that is currently being generated by this ClassWriter which can of course not be loaded since it is under construction . [CODESPLIT] protected String getCommonSuperClass ( final String type1 , final String type2 ) { ClassLoader classLoader = getClassLoader ( ) ; Class < ? > class1 ; try { class1 = Class . forName ( type1 . replace ( ' ' , ' ' ) , false , classLoader ) ; } catch ( ClassNotFoundException e ) { throw new TypeNotPresentException ( type1 , e ) ; } Class < ? > class2 ; try { class2 = Class . forName ( type2 . replace ( ' ' , ' ' ) , false , classLoader ) ; } catch ( ClassNotFoundException e ) { throw new TypeNotPresentException ( type2 , e ) ; } if ( class1 . isAssignableFrom ( class2 ) ) { return type1 ; } if ( class2 . isAssignableFrom ( class1 ) ) { return type2 ; } if ( class1 . isInterface ( ) || class2 . isInterface ( ) ) { return \"java/lang/Object\" ; } else { do { class1 = class1 . getSuperclass ( ) ; } while ( ! class1 . isAssignableFrom ( class2 ) ) ; return class1 . getName ( ) . replace ( ' ' , ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers default set of SQL types . [CODESPLIT] public void registerDefaults ( ) { register ( Integer . class , IntegerSqlType . class ) ; register ( int . class , IntegerSqlType . class ) ; register ( MutableInteger . class , IntegerSqlType . class ) ; register ( Float . class , FloatSqlType . class ) ; register ( float . class , FloatSqlType . class ) ; register ( MutableFloat . class , FloatSqlType . class ) ; register ( Double . class , DoubleSqlType . class ) ; register ( double . class , DoubleSqlType . class ) ; register ( MutableDouble . class , DoubleSqlType . class ) ; register ( Byte . class , ByteSqlType . class ) ; register ( byte . class , ByteSqlType . class ) ; register ( MutableByte . class , ByteSqlType . class ) ; register ( Boolean . class , BooleanSqlType . class ) ; register ( boolean . class , BooleanSqlType . class ) ; register ( MutableBoolean . class , BooleanSqlType . class ) ; register ( Long . class , LongSqlType . class ) ; register ( long . class , LongSqlType . class ) ; register ( MutableLong . class , LongSqlType . class ) ; register ( Short . class , ShortSqlType . class ) ; register ( short . class , ShortSqlType . class ) ; register ( MutableShort . class , ShortSqlType . class ) ; register ( Character . class , CharacterSqlType . class ) ; register ( char . class , CharacterSqlType . class ) ; register ( BigDecimal . class , BigDecimalSqlType . class ) ; register ( BigInteger . class , BigIntegerSqlType . class ) ; register ( String . class , StringSqlType . class ) ; register ( LocalDateTime . class , LocalDateTimeSqlType . class ) ; register ( LocalDate . class , LocalDateSqlType . class ) ; register ( LocalTime . class , LocalTimeSqlType . class ) ; register ( Date . class , SqlDateSqlType . class ) ; register ( Timestamp . class , TimestampSqlType . class ) ; register ( Time . class , TimeSqlType . class ) ; register ( java . util . Date . class , DateSqlType . class ) ; register ( JulianDate . class , JulianDateSqlType . class ) ; register ( byte [ ] . class , ByteArraySqlType . class ) ; register ( URL . class , URLSqlType . class ) ; register ( Blob . class , BlobSqlType . class ) ; register ( Clob . class , ClobSqlType . class ) ; register ( Array . class , SqlArraySqlType . class ) ; register ( Ref . class , SqlRefSqlType . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers sql type for provided type . [CODESPLIT] public void register ( final Class type , final Class < ? extends SqlType > sqlTypeClass ) { types . put ( type , lookupSqlType ( sqlTypeClass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves SQL type for provided type . All subclasses and interfaces are examined for matching sql type . [CODESPLIT] public SqlType lookup ( final Class clazz ) { SqlType sqlType ; for ( Class x = clazz ; x != null ; x = x . getSuperclass ( ) ) { sqlType = types . get ( clazz ) ; if ( sqlType != null ) { return sqlType ; } Class [ ] interfaces = x . getInterfaces ( ) ; for ( Class i : interfaces ) { sqlType = types . get ( i ) ; if ( sqlType != null ) { return sqlType ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns sql type instance . Instances are stored for better performances . [CODESPLIT] public SqlType lookupSqlType ( final Class < ? extends SqlType > sqlTypeClass ) { SqlType sqlType = sqlTypes . get ( sqlTypeClass ) ; if ( sqlType == null ) { try { sqlType = ClassUtil . newInstance ( sqlTypeClass ) ; } catch ( Exception ex ) { throw new DbSqlException ( \"SQL type not found: \" + sqlTypeClass . getSimpleName ( ) , ex ) ; } sqlTypes . put ( sqlTypeClass , sqlType ) ; } return sqlType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SOCKS4 proxy . [CODESPLIT] public static ProxyInfo socks4Proxy ( final String proxyAddress , final int proxyPort , final String proxyUser ) { return new ProxyInfo ( ProxyType . SOCKS4 , proxyAddress , proxyPort , proxyUser , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SOCKS5 proxy . [CODESPLIT] public static ProxyInfo socks5Proxy ( final String proxyAddress , final int proxyPort , final String proxyUser , final String proxyPassword ) { return new ProxyInfo ( ProxyType . SOCKS5 , proxyAddress , proxyPort , proxyUser , proxyPassword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates HTTP proxy . [CODESPLIT] public static ProxyInfo httpProxy ( final String proxyAddress , final int proxyPort , final String proxyUser , final String proxyPassword ) { return new ProxyInfo ( ProxyType . HTTP , proxyAddress , proxyPort , proxyUser , proxyPassword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns total number of transactions associated with current thread . [CODESPLIT] public int totalThreadTransactions ( ) { ArrayList < JtxTransaction > txList = txStack . get ( ) ; if ( txList == null ) { return 0 ; } return txList . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns total number of transactions of the specified status associated with current thread . [CODESPLIT] public int totalThreadTransactionsWithStatus ( final JtxStatus status ) { ArrayList < JtxTransaction > txlist = txStack . get ( ) ; if ( txlist == null ) { return 0 ; } int count = 0 ; for ( JtxTransaction tx : txlist ) { if ( tx . getStatus ( ) == status ) { count ++ ; } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if provided transaction is associated with current thread . [CODESPLIT] public boolean isAssociatedWithThread ( final JtxTransaction tx ) { ArrayList < JtxTransaction > txList = txStack . get ( ) ; if ( txList == null ) { return false ; } return txList . contains ( tx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes transaction association with current thread . Transaction should be properly handled ( committed or rolledback ) before removing from current thread . Also removes thread list from this thread . [CODESPLIT] protected boolean removeTransaction ( final JtxTransaction tx ) { ArrayList < JtxTransaction > txList = txStack . get ( ) ; if ( txList == null ) { return false ; } boolean removed = txList . remove ( tx ) ; if ( removed ) { totalTransactions -- ; } if ( txList . isEmpty ( ) ) { txStack . remove ( ) ; } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns last transaction associated with current thread or <code > null< / code > when thread has no associated transactions created by this transaction manager . [CODESPLIT] public JtxTransaction getTransaction ( ) { ArrayList < JtxTransaction > txlist = txStack . get ( ) ; if ( txlist == null ) { return null ; } if ( txlist . isEmpty ( ) ) { return null ; } return txlist . get ( txlist . size ( ) - 1 ) ; // get last }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associate transaction to current thread . [CODESPLIT] protected void associateTransaction ( final JtxTransaction tx ) { totalTransactions ++ ; ArrayList < JtxTransaction > txList = txStack . get ( ) ; if ( txList == null ) { txList = new ArrayList <> ( ) ; txStack . set ( txList ) ; } txList . add ( tx ) ; // add last }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { [CODESPLIT] protected JtxTransaction createNewTransaction ( final JtxTransactionMode tm , final Object scope , final boolean active ) { return new JtxTransaction ( this , tm , scope , active ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests transaction with specified { [CODESPLIT] public JtxTransaction requestTransaction ( final JtxTransactionMode mode , final Object scope ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Requesting TX \" + mode . toString ( ) ) ; } JtxTransaction currentTx = getTransaction ( ) ; if ( ! isNewTxScope ( currentTx , scope ) ) { return currentTx ; } switch ( mode . getPropagationBehavior ( ) ) { case PROPAGATION_REQUIRED : return propRequired ( currentTx , mode , scope ) ; case PROPAGATION_SUPPORTS : return propSupports ( currentTx , mode , scope ) ; case PROPAGATION_MANDATORY : return propMandatory ( currentTx , mode , scope ) ; case PROPAGATION_REQUIRES_NEW : return propRequiresNew ( currentTx , mode , scope ) ; case PROPAGATION_NOT_SUPPORTED : return propNotSupported ( currentTx , mode , scope ) ; case PROPAGATION_NEVER : return propNever ( currentTx , mode , scope ) ; } throw new JtxException ( \"Invalid TX propagation value: \" + mode . getPropagationBehavior ( ) . value ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if scope is specified and it is different then of existing transaction . [CODESPLIT] protected boolean isNewTxScope ( final JtxTransaction currentTx , final Object destScope ) { if ( ignoreScope ) { return true ; } if ( currentTx == null ) { return true ; } if ( destScope == null ) { return true ; } if ( currentTx . getScope ( ) == null ) { return true ; } return ! destScope . equals ( currentTx . getScope ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if propagation of a transaction is possible due to source and destination transaction modes . [CODESPLIT] protected void continueTx ( final JtxTransaction sourceTx , final JtxTransactionMode destMode ) { if ( ! validateExistingTransaction ) { return ; } JtxTransactionMode sourceMode = sourceTx . getTransactionMode ( ) ; JtxIsolationLevel destIsolationLevel = destMode . getIsolationLevel ( ) ; if ( destIsolationLevel != ISOLATION_DEFAULT ) { JtxIsolationLevel currentIsolationLevel = sourceMode . getIsolationLevel ( ) ; if ( currentIsolationLevel != destIsolationLevel ) { throw new JtxException ( \"Participating TX specifies isolation level: \" + destIsolationLevel + \" which is incompatible with existing TX: \" + currentIsolationLevel ) ; } } if ( ( ! destMode . isReadOnly ( ) ) && ( sourceMode . isReadOnly ( ) ) ) { throw new JtxException ( \"Participating TX is not marked as read-only, but existing TX is\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagation : REQUIRED <pre > { [CODESPLIT] protected JtxTransaction propRequired ( JtxTransaction currentTx , final JtxTransactionMode mode , final Object scope ) { if ( ( currentTx == null ) || ( currentTx . isNoTransaction ( ) ) ) { currentTx = createNewTransaction ( mode , scope , true ) ; } else { continueTx ( currentTx , mode ) ; } return currentTx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagation : REQUIRES_NEW <pre > { [CODESPLIT] @ SuppressWarnings ( { \"UnusedDeclaration\" } ) protected JtxTransaction propRequiresNew ( final JtxTransaction currentTx , final JtxTransactionMode mode , final Object scope ) { return createNewTransaction ( mode , scope , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagation : SUPPORTS <pre > { [CODESPLIT] protected JtxTransaction propSupports ( JtxTransaction currentTx , final JtxTransactionMode mode , final Object scope ) { if ( ( currentTx != null ) && ( ! currentTx . isNoTransaction ( ) ) ) { continueTx ( currentTx , mode ) ; } if ( currentTx == null ) { currentTx = createNewTransaction ( mode , scope , false ) ; } return currentTx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagation : MANDATORY <pre > { [CODESPLIT] @ SuppressWarnings ( { \"UnusedDeclaration\" } ) protected JtxTransaction propMandatory ( final JtxTransaction currentTx , final JtxTransactionMode mode , final Object scope ) { if ( ( currentTx == null ) || ( currentTx . isNoTransaction ( ) ) ) { throw new JtxException ( \"No existing TX found for TX marked with propagation 'mandatory'\" ) ; } continueTx ( currentTx , mode ) ; return currentTx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagation : NOT_SUPPORTED <pre > { [CODESPLIT] protected JtxTransaction propNotSupported ( final JtxTransaction currentTx , final JtxTransactionMode mode , final Object scope ) { if ( currentTx == null ) { return createNewTransaction ( mode , scope , false ) ; } if ( currentTx . isNoTransaction ( ) ) { return currentTx ; } return createNewTransaction ( mode , scope , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagation : NEVER <pre > { [CODESPLIT] protected JtxTransaction propNever ( JtxTransaction currentTx , final JtxTransactionMode mode , final Object scope ) { if ( ( currentTx != null ) && ( ! currentTx . isNoTransaction ( ) ) ) { throw new JtxException ( \"Existing TX found for TX marked with propagation 'never'\" ) ; } if ( currentTx == null ) { currentTx = createNewTransaction ( mode , scope , false ) ; } return currentTx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new { [CODESPLIT] public void registerResourceManager ( final JtxResourceManager resourceManager ) { if ( ( oneResourceManager ) && ( ! resourceManagers . isEmpty ( ) ) ) { throw new JtxException ( \"TX manager allows only one resource manager\" ) ; } this . resourceManagers . put ( resourceManager . getResourceType ( ) , resourceManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups resource manager for provided type . Throws an exception if provider doesn t exists . [CODESPLIT] protected < E > JtxResourceManager < E > lookupResourceManager ( final Class < E > resourceType ) { //noinspection unchecked JtxResourceManager < E > resourceManager = this . resourceManagers . get ( resourceType ) ; if ( resourceManager == null ) { throw new JtxException ( \"No registered resource manager for resource type: \" + resourceType . getSimpleName ( ) ) ; } return resourceManager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes transaction manager . All registered { [CODESPLIT] public void close ( ) { this . resourceManagers . forEachValue ( resourceManager -> { try { resourceManager . close ( ) ; } catch ( Exception ex ) { // ignore } } ) ; resourceManagers . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates proxy object . [CODESPLIT] protected C createProxyObject ( Class < C > target ) { target = ProxettaUtil . resolveTargetClass ( target ) ; Class proxyClass = cache . get ( target ) ; if ( proxyClass == null ) { proxyClass = proxetta . defineProxy ( target ) ; cache . put ( target , proxyClass ) ; } C proxy ; try { proxy = ( C ) ClassUtil . newInstance ( proxyClass ) ; } catch ( Exception ex ) { throw new PathrefException ( ex ) ; } return proxy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends method name to existing path . [CODESPLIT] protected void append ( final String methodName ) { if ( path . length ( ) != 0 ) { path += StringPool . DOT ; } if ( methodName . startsWith ( StringPool . LEFT_SQ_BRACKET ) ) { path = StringUtil . substring ( path , 0 , - 1 ) ; } path += methodName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static factory of next target . It handles special cases of maps sets and lists . In case target can not be proxified ( like for Java classes ) it returns <code > null< / code > . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T continueWith ( final Object currentInstance , final String methodName , final Class < T > target ) { Class currentClass = currentInstance . getClass ( ) ; Method method ; try { method = currentClass . getDeclaredMethod ( methodName ) ; } catch ( NoSuchMethodException e ) { throw new PathrefException ( \"Not a getter: \" + methodName , e ) ; } if ( ! ClassUtil . isBeanPropertyGetter ( method ) ) { throw new PathrefException ( \"Not a getter: \" + methodName ) ; } String getterName = ClassUtil . getBeanPropertyGetterName ( method ) ; append ( getterName ) ; if ( ClassUtil . isTypeOf ( target , List . class ) ) { final Class componentType = ClassUtil . getComponentType ( method . getGenericReturnType ( ) , currentClass , 0 ) ; if ( componentType == null ) { throw new PathrefException ( \"Unknown component name for: \" + methodName ) ; } return ( T ) new ArrayList ( ) { @ Override public Object get ( final int index ) { if ( index >= 0 ) { append ( \"[\" + index + \"]\" ) ; } return new Pathref <> ( componentType , Pathref . this ) . to ( ) ; } } ; } try { return new Pathref <> ( target , this ) . to ( ) ; } catch ( Exception ex ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- Apache Commons Codec - Base64 [CODESPLIT] @ Benchmark public String encode_Apache_Base64 ( ) { return org . apache . commons . codec . binary . Base64 . encodeBase64String ( to_be_encoded ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the text to the left and pads with spaces until the size is reached . [CODESPLIT] public static String alignLeftAndPad ( final String text , final int size ) { int textLength = text . length ( ) ; if ( textLength > size ) { return text . substring ( 0 , size ) ; } final StringBuilder sb = new StringBuilder ( size ) ; sb . append ( text ) ; while ( textLength ++ < size ) { sb . append ( ' ' ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats byte size to human readable bytecount . https : // stackoverflow . com / questions / 3758606 / how - to - convert - byte - size - into - human - readable - format - in - java / 3758880#3758880 [CODESPLIT] public static String humanReadableByteCount ( final long bytes , final boolean useSi ) { final int unit = useSi ? 1000 : 1024 ; if ( bytes < unit ) return bytes + \" B\" ; final int exp = ( int ) ( Math . log ( bytes ) / Math . log ( unit ) ) ; final String pre = ( useSi ? \"kMGTPE\" : \"KMGTPE\" ) . charAt ( exp - 1 ) + ( useSi ? \"\" : \"i\" ) ; return String . format ( \"%.1f %sB\" , bytes / Math . pow ( unit , exp ) , pre ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts object into pretty string . All arrays are iterated . [CODESPLIT] public static String toPrettyString ( final Object value ) { if ( value == null ) { return StringPool . NULL ; } final Class < ? > type = value . getClass ( ) ; if ( type . isArray ( ) ) { final Class componentType = type . getComponentType ( ) ; if ( componentType . isPrimitive ( ) ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( ' ' ) ; if ( componentType == int . class ) { sb . append ( ArraysUtil . toString ( ( int [ ] ) value ) ) ; } else if ( componentType == long . class ) { sb . append ( ArraysUtil . toString ( ( long [ ] ) value ) ) ; } else if ( componentType == double . class ) { sb . append ( ArraysUtil . toString ( ( double [ ] ) value ) ) ; } else if ( componentType == float . class ) { sb . append ( ArraysUtil . toString ( ( float [ ] ) value ) ) ; } else if ( componentType == boolean . class ) { sb . append ( ArraysUtil . toString ( ( boolean [ ] ) value ) ) ; } else if ( componentType == short . class ) { sb . append ( ArraysUtil . toString ( ( short [ ] ) value ) ) ; } else if ( componentType == byte . class ) { sb . append ( ArraysUtil . toString ( ( byte [ ] ) value ) ) ; } else { throw new IllegalArgumentException ( ) ; } sb . append ( ' ' ) ; return sb . toString ( ) ; } else { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( ' ' ) ; final Object [ ] array = ( Object [ ] ) value ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( i > 0 ) { sb . append ( ' ' ) ; } sb . append ( toPrettyString ( array [ i ] ) ) ; } sb . append ( ' ' ) ; return sb . toString ( ) ; } } else if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final StringBuilder sb = new StringBuilder ( ) ; sb . append ( ' ' ) ; int i = 0 ; for ( final Object o : iterable ) { if ( i > 0 ) { sb . append ( ' ' ) ; } sb . append ( toPrettyString ( o ) ) ; i ++ ; } sb . append ( ' ' ) ; return sb . toString ( ) ; } return value . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes CamelCase string to lower case words separated by provided separator character . The following translations are applied : <ul > <li > Every upper case letter in the CamelCase name is translated into two characters a separator and the lower case equivalent of the target character with three exceptions . <ol > <li > For contiguous sequences of upper case letters characters after the first character are replaced only by their lower case equivalent and are not preceded by a separator ( <code > theFOO< / code > to <code > the_foo< / code > ) . <li > An upper case character in the first position of the CamelCase name is not preceded by a separator character and is translated only to its lower case equivalent . ( <code > Foo< / code > to <code > foo< / code > and not <code > _foo< / code > ) <li > An upper case character in the CamelCase name that is already preceded by a separator character is translated only to its lower case equivalent and is not preceded by an additional separator . ( <code > user_Name< / code > to <code > user_name< / code > and not <code > user__name< / code > . < / ol > <li > If the CamelCase name starts with a separator then that separator is not included in the translated name unless the CamelCase name is just one character in length i . e . it is the separator character . This applies only to the first character of the CamelCase name . < / ul > [CODESPLIT] public static String fromCamelCase ( final String input , final char separator ) { final int length = input . length ( ) ; final StringBuilder result = new StringBuilder ( length * 2 ) ; int resultLength = 0 ; boolean prevTranslated = false ; for ( int i = 0 ; i < length ; i ++ ) { char c = input . charAt ( i ) ; if ( i > 0 || c != separator ) { // skip first starting separator if ( Character . isUpperCase ( c ) ) { if ( ! prevTranslated && resultLength > 0 && result . charAt ( resultLength - 1 ) != separator ) { result . append ( separator ) ; resultLength ++ ; } c = Character . toLowerCase ( c ) ; prevTranslated = true ; } else { prevTranslated = false ; } result . append ( c ) ; resultLength ++ ; } } return resultLength > 0 ? result . toString ( ) : input ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts separated string value to CamelCase . [CODESPLIT] public static String toCamelCase ( final String input , final boolean firstCharUppercase , final char separator ) { final int length = input . length ( ) ; final StringBuilder sb = new StringBuilder ( length ) ; boolean upperCase = firstCharUppercase ; for ( int i = 0 ; i < length ; i ++ ) { final char ch = input . charAt ( i ) ; if ( ch == separator ) { upperCase = true ; } else if ( upperCase ) { sb . append ( Character . toUpperCase ( ch ) ) ; upperCase = false ; } else { sb . append ( ch ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats provided string as paragraph . [CODESPLIT] public static String formatParagraph ( final String src , final int len , final boolean breakOnWhitespace ) { StringBuilder str = new StringBuilder ( ) ; int total = src . length ( ) ; int from = 0 ; while ( from < total ) { int to = from + len ; if ( to >= total ) { to = total ; } else if ( breakOnWhitespace ) { int ndx = StringUtil . lastIndexOfWhitespace ( src , to - 1 , from ) ; if ( ndx != - 1 ) { to = ndx + 1 ; } } int cutFrom = StringUtil . indexOfNonWhitespace ( src , from , to ) ; if ( cutFrom != - 1 ) { int cutTo = StringUtil . lastIndexOfNonWhitespace ( src , to - 1 , from ) + 1 ; str . append ( src , cutFrom , cutTo ) ; } str . append ( ' ' ) ; from = to ; } return str . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts all tabs on a line to spaces according to the provided tab width . This is not a simple tab to spaces replacement since the resulting indentation remains the same . [CODESPLIT] public static String convertTabsToSpaces ( final String line , final int tabWidth ) { int tab_index , tab_size ; int last_tab_index = 0 ; int added_chars = 0 ; if ( tabWidth == 0 ) { return StringUtil . remove ( line , ' ' ) ; } StringBuilder result = new StringBuilder ( ) ; while ( ( tab_index = line . indexOf ( ' ' , last_tab_index ) ) != - 1 ) { tab_size = tabWidth - ( ( tab_index + added_chars ) % tabWidth ) ; if ( tab_size == 0 ) { tab_size = tabWidth ; } added_chars += tab_size - 1 ; result . append ( line , last_tab_index , tab_index ) ; result . append ( StringUtil . repeat ( ' ' , tab_size ) ) ; last_tab_index = tab_index + 1 ; } if ( last_tab_index == 0 ) { return line ; } result . append ( line . substring ( last_tab_index ) ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escapes a string using java rules . [CODESPLIT] public static String escapeJava ( final String string ) { int strLen = string . length ( ) ; StringBuilder sb = new StringBuilder ( strLen ) ; for ( int i = 0 ; i < strLen ; i ++ ) { char c = string . charAt ( i ) ; switch ( c ) { case ' ' : sb . append ( \"\\\\b\" ) ; break ; case ' ' : sb . append ( \"\\\\t\" ) ; break ; case ' ' : sb . append ( \"\\\\n\" ) ; break ; case ' ' : sb . append ( \"\\\\f\" ) ; break ; case ' ' : sb . append ( \"\\\\r\" ) ; break ; case ' ' : sb . append ( \"\\\\\\\"\" ) ; break ; case ' ' : sb . append ( \"\\\\\\\\\" ) ; break ; default : if ( ( c < 32 ) || ( c > 127 ) ) { String hex = Integer . toHexString ( c ) ; sb . append ( \"\\\\u\" ) ; for ( int k = hex . length ( ) ; k < 4 ; k ++ ) { sb . append ( ' ' ) ; } sb . append ( hex ) ; } else { sb . append ( c ) ; } } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unescapes a string using java rules . [CODESPLIT] public static String unescapeJava ( final String str ) { char [ ] chars = str . toCharArray ( ) ; StringBuilder sb = new StringBuilder ( str . length ( ) ) ; for ( int i = 0 ; i < chars . length ; i ++ ) { char c = chars [ i ] ; if ( c != ' ' ) { sb . append ( c ) ; continue ; } i ++ ; c = chars [ i ] ; switch ( c ) { case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : char hex = ( char ) Integer . parseInt ( new String ( chars , i + 1 , 4 ) , 16 ) ; sb . append ( hex ) ; i += 4 ; break ; default : throw new IllegalArgumentException ( \"Invalid escaping character: \" + c ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut for checking the annotation on annotated element and returning either the values or { [CODESPLIT] public static TransactionAnnotationValues of ( final AnnotationParser annotationParser , final AnnotatedElement annotatedElement ) { if ( ! annotationParser . hasAnnotationOn ( annotatedElement ) ) { return null ; } return new TransactionAnnotationValues ( annotationParser . of ( annotatedElement ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- core [CODESPLIT] protected Object lookupMixingScopedBean ( final BeanDefinition def , final BeanReferences refNames ) { final boolean mixing = petiteConfig . wireScopedProxy || petiteConfig . detectMixedScopes ; Object value = null ; if ( mixing ) { final BeanDefinition refBeanDefinition = lookupBeanDefinitions ( refNames ) ; if ( refBeanDefinition != null ) { value = scopedProxyManager . lookupValue ( PetiteContainer . this , def , refBeanDefinition ) ; } } if ( value == null ) { value = PetiteContainer . this . getBean ( refNames ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Petite bean instance . Bean name will be resolved from provided type . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public < T > T getBean ( final Class < T > type ) { String name = resolveBeanName ( type ) ; return ( T ) getBean ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Petite bean instance named as one of the provided names . Returns { [CODESPLIT] protected Object getBean ( final BeanReferences beanReferences ) { final int total = beanReferences . size ( ) ; for ( int i = 0 ; i < total ; i ++ ) { String name = beanReferences . name ( i ) ; if ( name != null ) { Object bean = getBean ( name ) ; if ( bean != null ) { return bean ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Petite bean instance . Petite container will find the bean in corresponding scope and all its dependencies either by constructor or property injection . When using constructor injection cyclic dependencies can not be prevented but at least they are detected . [CODESPLIT] public < T > T getBean ( final String name ) { // Lookup for registered bean definition. BeanDefinition def = lookupBeanDefinition ( name ) ; if ( def == null ) { // try provider ProviderDefinition providerDefinition = providers . get ( name ) ; if ( providerDefinition != null ) { return ( T ) invokeProvider ( providerDefinition ) ; } return null ; } // Find the bean in its scope Object bean = def . scopeLookup ( ) ; if ( bean == null ) { // Create new bean in the scope initBeanDefinition ( def ) ; final BeanData beanData = new BeanData ( this , def ) ; registerBeanAndWireAndInjectParamsAndInvokeInitMethods ( beanData ) ; bean = beanData . bean ( ) ; } return ( T ) bean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves and initializes bean definition . May be called multiple times . [CODESPLIT] protected void initBeanDefinition ( final BeanDefinition def ) { // init methods if ( def . initMethods == null ) { def . initMethods = petiteResolvers . resolveInitMethodPoint ( def . type ) ; } // destroy methods if ( def . destroyMethods == null ) { def . destroyMethods = petiteResolvers . resolveDestroyMethodPoint ( def . type ) ; } // properties if ( def . properties == null ) { def . properties = petiteResolvers . resolvePropertyInjectionPoint ( def . type , def . wiringMode == WiringMode . AUTOWIRE ) ; } // methods if ( def . methods == null ) { def . methods = petiteResolvers . resolveMethodInjectionPoint ( def . type ) ; } // ctors if ( def . ctor == null ) { def . ctor = petiteResolvers . resolveCtorInjectionPoint ( def . type ) ; } // values if ( def . values == null ) { def . values = paramManager . resolveParamInjectionPoints ( def . type ) ; } // sets if ( def . sets == null ) { def . sets = petiteResolvers . resolveSetInjectionPoint ( def . type , def . wiringMode == WiringMode . AUTOWIRE ) ; } // params if ( def . params == null ) { def . params = paramManager . filterParametersForBeanName ( def . name , petiteConfig . getResolveReferenceParameters ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wires bean injects parameters and invokes init methods . Such a loooong name : ) [CODESPLIT] protected void registerBeanAndWireAndInjectParamsAndInvokeInitMethods ( final BeanData beanData ) { initBeanDefinition ( beanData . definition ( ) ) ; beanData . scopeRegister ( ) ; beanData . invokeInitMethods ( InitMethodInvocationStrategy . POST_CONSTRUCT ) ; beanData . wireBean ( ) ; beanData . invokeInitMethods ( InitMethodInvocationStrategy . POST_DEFINE ) ; beanData . injectParams ( paramManager , petiteConfig . isImplicitParamInjection ( ) ) ; beanData . invokeInitMethods ( InitMethodInvocationStrategy . POST_INITIALIZE ) ; beanData . invokeConsumerIfRegistered ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wires provided bean with the container and optionally invokes init methods . Bean is <b > not< / b > registered withing container . [CODESPLIT] public void wire ( final Object bean , final WiringMode wiringMode ) { final WiringMode finalWiringMode = petiteConfig . resolveWiringMode ( wiringMode ) ; final BeanDefinition def = externalsCache . get ( bean . getClass ( ) , ( ) -> { final BeanDefinition beanDefinition = createBeandDefinitionForExternalBeans ( bean . getClass ( ) , finalWiringMode ) ; initBeanDefinition ( beanDefinition ) ; return beanDefinition ; } ) ; registerBeanAndWireAndInjectParamsAndInvokeInitMethods ( new BeanData ( this , def , bean ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the method of some bean with the container when its parameters requires to be injected into . The bean is <b > not< / b > registered within container . [CODESPLIT] public < T > T invokeMethod ( final Object bean , final Method method ) { final WiringMode wiringMode = petiteConfig . resolveWiringMode ( null ) ; final BeanDefinition def = externalsCache . get ( bean . getClass ( ) , ( ) -> { final BeanDefinition beanDefinition = createBeandDefinitionForExternalBeans ( bean . getClass ( ) , wiringMode ) ; initBeanDefinition ( beanDefinition ) ; return beanDefinition ; } ) ; final BeanData beanData = new BeanData ( this , def , bean ) ; for ( MethodInjectionPoint methodInjectionPoint : def . methods ) { if ( methodInjectionPoint . method . equals ( method ) ) { return ( T ) beanData . invokeMethodInjectionPoint ( methodInjectionPoint ) ; } } try { return ( T ) method . invoke ( bean ) ; } catch ( Exception e ) { throw new PetiteException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and wires a bean within the container and optionally invokes init methods . However bean is <b > not< / b > registered . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public < E > E createBean ( final Class < E > type , final WiringMode wiringMode ) { final WiringMode finalWiringMode = petiteConfig . resolveWiringMode ( wiringMode ) ; final BeanDefinition def = externalsCache . get ( type , ( ) -> { final BeanDefinition beanDefinition = createBeandDefinitionForExternalBeans ( type , finalWiringMode ) ; initBeanDefinition ( beanDefinition ) ; return beanDefinition ; } ) ; final BeanData < E > beanData = new BeanData ( this , def ) ; registerBeanAndWireAndInjectParamsAndInvokeInitMethods ( beanData ) ; return beanData . bean ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes provider to get a bean . [CODESPLIT] protected Object invokeProvider ( final ProviderDefinition provider ) { if ( provider . method != null ) { final Object bean ; if ( provider . beanName != null ) { // instance factory method bean = getBean ( provider . beanName ) ; } else { // static factory method bean = null ; } try { return provider . method . invoke ( bean ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Invalid provider method: \" + provider . method . getName ( ) , ex ) ; } } throw new PetiteException ( \"Invalid provider\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds object instance to the container as singleton bean . [CODESPLIT] public void addBean ( final String name , final Object bean , WiringMode wiringMode ) { wiringMode = petiteConfig . resolveWiringMode ( wiringMode ) ; registerPetiteBean ( bean . getClass ( ) , name , SingletonScope . class , wiringMode , false , null ) ; BeanDefinition def = lookupExistingBeanDefinition ( name ) ; registerBeanAndWireAndInjectParamsAndInvokeInitMethods ( new BeanData ( this , def , bean ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets petite bean property . [CODESPLIT] public void setBeanProperty ( final String name , final Object value ) { Object bean = null ; int ndx = name . length ( ) ; while ( true ) { ndx = name . lastIndexOf ( ' ' , ndx ) ; if ( ndx == - 1 ) { break ; } String beanName = name . substring ( 0 , ndx ) ; bean = getBean ( beanName ) ; if ( bean != null ) { break ; } ndx -- ; } if ( bean == null ) { throw new PetiteException ( \"Invalid bean property: \" + name ) ; } try { BeanUtil . declared . setProperty ( bean , name . substring ( ndx + 1 ) , value ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Invalid bean property: \" + name , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns petite bean property value . [CODESPLIT] public Object getBeanProperty ( final String name ) { int ndx = name . indexOf ( ' ' ) ; if ( ndx == - 1 ) { throw new PetiteException ( \"Only bean name is specified, missing property name: \" + name ) ; } String beanName = name . substring ( 0 , ndx ) ; Object bean = getBean ( beanName ) ; if ( bean == null ) { throw new PetiteException ( \"Bean doesn't exist: \" + name ) ; } try { return BeanUtil . declared . getProperty ( bean , name . substring ( ndx + 1 ) ) ; } catch ( Exception ex ) { throw new PetiteException ( \"Invalid bean property: \" + name , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdowns container . After container is down it can t be used anymore . [CODESPLIT] public void shutdown ( ) { scopes . forEachValue ( Scope :: shutdown ) ; externalsCache . clear ( ) ; beans . clear ( ) ; beansAlt . clear ( ) ; scopes . clear ( ) ; providers . clear ( ) ; beanCollections . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- properties [CODESPLIT] @ Override protected Properties createSessionProperties ( ) { final Properties props = super . createSessionProperties ( ) ; props . setProperty ( MAIL_TRANSPORT_PROTOCOL , PROTOCOL_SMTP ) ; props . setProperty ( MAIL_HOST , host ) ; props . setProperty ( MAIL_SMTP_HOST , host ) ; props . setProperty ( MAIL_SMTP_PORT , String . valueOf ( port ) ) ; if ( authenticator != null ) { props . setProperty ( MAIL_SMTP_AUTH , TRUE ) ; } if ( timeout > 0 ) { final String timeoutValue = String . valueOf ( timeout ) ; props . put ( MAIL_SMTP_CONNECTIONTIMEOUT , timeoutValue ) ; props . put ( MAIL_SMTP_TIMEOUT , timeoutValue ) ; props . put ( MAIL_SMTP_WRITETIMEOUT , timeoutValue ) ; } return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public SendMailSession createSession ( ) { final Session session = Session . getInstance ( createSessionProperties ( ) , authenticator ) ; final Transport mailTransport ; try { mailTransport = getTransport ( session ) ; } catch ( final NoSuchProviderException nspex ) { throw new MailException ( nspex ) ; } return new SendMailSession ( session , mailTransport ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- lifecycle [CODESPLIT] @ Override public void start ( ) { initLogger ( ) ; final String resourceName = StringUtil . replaceChar ( JoyPaths . class . getName ( ) , ' ' , ' ' ) + \".class\" ; URL url = ClassLoaderUtil . getResourceUrl ( resourceName ) ; if ( url == null ) { throw new JoyException ( \"Failed to resolve app dir, missing: \" + resourceName ) ; } final String protocol = url . getProtocol ( ) ; if ( ! protocol . equals ( \"file\" ) ) { try { url = new URL ( url . getFile ( ) ) ; } catch ( MalformedURLException ignore ) { } } appDir = url . getFile ( ) ; final int ndx = appDir . indexOf ( \"WEB-INF\" ) ; appDir = ( ndx > 0 ) ? appDir . substring ( 0 , ndx ) : SystemUtil . info ( ) . getWorkingDir ( ) ; System . setProperty ( APP_DIR , appDir ) ; log . info ( \"Application folder: \" + appDir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts Jodd logging level to JDK . [CODESPLIT] private java . util . logging . Level jodd2jdk ( final Level level ) { switch ( level ) { case TRACE : return java . util . logging . Level . FINER ; case DEBUG : return java . util . logging . Level . FINE ; case INFO : return java . util . logging . Level . INFO ; case WARN : return java . util . logging . Level . WARNING ; case ERROR : return java . util . logging . Level . SEVERE ; default : throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Double get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Double . valueOf ( rs . getDouble ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Double value , final int dbSqlType ) throws SQLException { st . setDouble ( index , value . doubleValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves method parameters from a method or constructor . Returns an empty array when target does not contain any parameter . No caching is involved in this process i . e . class bytecode is examined every time this method is called . [CODESPLIT] public static MethodParameter [ ] resolveParameters ( final AccessibleObject methodOrCtor ) { Class [ ] paramTypes ; Class declaringClass ; String name ; if ( methodOrCtor instanceof Method ) { Method method = ( Method ) methodOrCtor ; paramTypes = method . getParameterTypes ( ) ; name = method . getName ( ) ; declaringClass = method . getDeclaringClass ( ) ; } else { Constructor constructor = ( Constructor ) methodOrCtor ; paramTypes = constructor . getParameterTypes ( ) ; declaringClass = constructor . getDeclaringClass ( ) ; name = CTOR_METHOD ; } if ( paramTypes . length == 0 ) { return MethodParameter . EMPTY_ARRAY ; } InputStream stream ; try { stream = ClassLoaderUtil . getClassAsStream ( declaringClass ) ; } catch ( IOException ioex ) { throw new ParamoException ( \"Failed to read class bytes: \" + declaringClass . getName ( ) , ioex ) ; } if ( stream == null ) { throw new ParamoException ( \"Class not found: \" + declaringClass ) ; } try { ClassReader reader = new ClassReader ( stream ) ; MethodFinder visitor = new MethodFinder ( declaringClass , name , paramTypes ) ; reader . accept ( visitor , 0 ) ; return visitor . getResolvedParameters ( ) ; } catch ( IOException ioex ) { throw new ParamoException ( ioex ) ; } finally { StreamUtil . close ( stream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs smart form population . [CODESPLIT] @ Override public int doAfterBody ( ) throws JspException { BodyContent body = getBodyContent ( ) ; JspWriter out = body . getEnclosingWriter ( ) ; String bodytext = populateForm ( body . getString ( ) , name -> value ( name , pageContext ) ) ; try { out . print ( bodytext ) ; } catch ( IOException ioex ) { throw new JspException ( ioex ) ; } return SKIP_BODY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the property value with replaced macros . [CODESPLIT] public String getValue ( final String ... profiles ) { if ( hasMacro ) { return propsData . resolveMacros ( value , profiles ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts with DOM building . Creates root { [CODESPLIT] @ Override public void start ( ) { log . debug ( \"DomTree builder started\" ) ; if ( rootNode == null ) { rootNode = new Document ( domBuilder . config ) ; } parentNode = rootNode ; enabled = true ; if ( domBuilder . config . isEnabledVoidTags ( ) ) { htmlVoidRules = new HtmlVoidRules ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finishes the tree building . Closes unclosed tags . [CODESPLIT] @ Override public void end ( ) { if ( parentNode != rootNode ) { Node thisNode = parentNode ; while ( thisNode != rootNode ) { if ( domBuilder . config . isImpliedEndTags ( ) ) { if ( implRules . implicitlyCloseTagOnEOF ( thisNode . getNodeName ( ) ) ) { thisNode = thisNode . getParentNode ( ) ; continue ; } } error ( \"Unclosed tag closed: <\" + thisNode . getNodeName ( ) + \">\" ) ; thisNode = thisNode . getParentNode ( ) ; } } // remove whitespaces if ( domBuilder . config . isIgnoreWhitespacesBetweenTags ( ) ) { removeLastChildNodeIfEmptyText ( parentNode , true ) ; } // foster if ( domBuilder . config . isUseFosterRules ( ) ) { HtmlFosterRules fosterRules = new HtmlFosterRules ( ) ; fosterRules . fixFosterElements ( rootNode ) ; } // elapsed rootNode . end ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"LagartoDom tree created in \" + rootNode . getElapsedTime ( ) + \" ms\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new element with correct configuration . [CODESPLIT] protected Element createElementNode ( final Tag tag ) { boolean hasVoidTags = htmlVoidRules != null ; boolean isVoid = false ; boolean selfClosed = false ; if ( hasVoidTags ) { isVoid = htmlVoidRules . isVoidTag ( tag . getName ( ) ) ; // HTML and XHTML if ( isVoid ) { // it's void tag, lookup the flag selfClosed = domBuilder . config . isSelfCloseVoidTags ( ) ; } } else { // XML, no voids, lookup the flag selfClosed = domBuilder . config . isSelfCloseVoidTags ( ) ; } return new Element ( rootNode , tag , isVoid , selfClosed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits tags . [CODESPLIT] @ Override public void tag ( final Tag tag ) { if ( ! enabled ) { return ; } TagType tagType = tag . getType ( ) ; Element node ; switch ( tagType ) { case START : if ( domBuilder . config . isIgnoreWhitespacesBetweenTags ( ) ) { removeLastChildNodeIfEmptyText ( parentNode , false ) ; } node = createElementNode ( tag ) ; if ( domBuilder . config . isImpliedEndTags ( ) ) { while ( true ) { String parentNodeName = parentNode . getNodeName ( ) ; if ( ! implRules . implicitlyCloseParentTagOnNewTag ( parentNodeName , node . getNodeName ( ) ) ) { break ; } parentNode = parentNode . getParentNode ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Implicitly closed tag <\" + node . getNodeName ( ) + \"> \" ) ; } } } parentNode . addChild ( node ) ; if ( ! node . isVoidElement ( ) ) { parentNode = node ; } break ; case END : if ( domBuilder . config . isIgnoreWhitespacesBetweenTags ( ) ) { removeLastChildNodeIfEmptyText ( parentNode , true ) ; } String tagName = tag . getName ( ) . toString ( ) ; Node matchingParent = findMatchingParentOpenTag ( tagName ) ; if ( matchingParent == parentNode ) { // regular situation parentNode = parentNode . getParentNode ( ) ; break ; } if ( matchingParent == null ) { // matching open tag not found, remove it error ( \"Orphan closed tag ignored: </\" + tagName + \"> \" + tag . getTagPosition ( ) ) ; break ; } // try to close it implicitly if ( domBuilder . config . isImpliedEndTags ( ) ) { boolean fixed = false ; while ( implRules . implicitlyCloseParentTagOnTagEnd ( parentNode . getNodeName ( ) , tagName ) ) { parentNode = parentNode . getParentNode ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Implicitly closed tag <\" + tagName + \">\" ) ; } if ( parentNode == matchingParent ) { parentNode = matchingParent . parentNode ; fixed = true ; break ; } } if ( fixed ) { break ; } } // matching tag found, but it is not a regular situation // therefore close all unclosed tags in between fixUnclosedTagsUpToMatchingParent ( tag , matchingParent ) ; break ; case SELF_CLOSING : if ( domBuilder . config . isIgnoreWhitespacesBetweenTags ( ) ) { removeLastChildNodeIfEmptyText ( parentNode , false ) ; } node = createElementNode ( tag ) ; parentNode . addChild ( node ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes last child node if contains just empty text . [CODESPLIT] protected void removeLastChildNodeIfEmptyText ( final Node parentNode , final boolean closedTag ) { if ( parentNode == null ) { return ; } Node lastChild = parentNode . getLastChild ( ) ; if ( lastChild == null ) { return ; } if ( lastChild . getNodeType ( ) != Node . NodeType . TEXT ) { return ; } if ( closedTag ) { if ( parentNode . getChildNodesCount ( ) == 1 ) { return ; } } Text text = ( Text ) lastChild ; if ( text . isBlank ( ) ) { lastChild . detachFromParent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds matching parent open tag or <code > null< / code > if not found . [CODESPLIT] protected Node findMatchingParentOpenTag ( String tagName ) { Node parent = parentNode ; if ( ! rootNode . config . isCaseSensitive ( ) ) { tagName = tagName . toLowerCase ( ) ; } while ( parent != null ) { String parentNodeName = parent . getNodeName ( ) ; if ( parentNodeName != null ) { if ( ! rootNode . config . isCaseSensitive ( ) ) { parentNodeName = parentNodeName . toLowerCase ( ) ; } } if ( tagName . equals ( parentNodeName ) ) { return parent ; } parent = parent . getParentNode ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fixes all unclosed tags up to matching parent . Missing end tags will be added just before parent tag is closed making the whole inner content as its tag body . <p > Tags that can be closed implicitly are checked and closed . <p > There is optional check for detecting orphan tags inside the table or lists . If set tags can be closed beyond the border of the table and the list and it is reported as orphan tag . <p > This is just a generic solutions closest to the rules . [CODESPLIT] protected void fixUnclosedTagsUpToMatchingParent ( final Tag tag , final Node matchingParent ) { if ( domBuilder . config . isUnclosedTagAsOrphanCheck ( ) ) { Node thisNode = parentNode ; if ( ! CharSequenceUtil . equalsIgnoreCase ( tag . getName ( ) , \"table\" ) ) { // check if there is table or list between this node // and matching parent while ( thisNode != matchingParent ) { String thisNodeName = thisNode . getNodeName ( ) . toLowerCase ( ) ; if ( thisNodeName . equals ( \"table\" ) || thisNodeName . equals ( \"ul\" ) || thisNodeName . equals ( \"ol\" ) ) { String positionString = tag . getPosition ( ) ; if ( positionString == null ) { positionString = StringPool . EMPTY ; } error ( \"Orphan closed tag ignored: </\" + tag . getName ( ) + \"> \" + positionString ) ; return ; } thisNode = thisNode . getParentNode ( ) ; } } } while ( true ) { if ( parentNode == matchingParent ) { parentNode = parentNode . getParentNode ( ) ; break ; } Node parentParentNode = parentNode . getParentNode ( ) ; if ( domBuilder . config . isImpliedEndTags ( ) ) { if ( implRules . implicitlyCloseParentTagOnNewTag ( parentParentNode . getNodeName ( ) , parentNode . getNodeName ( ) ) ) { // break the tree: detach this node and append it after parent parentNode . detachFromParent ( ) ; parentParentNode . getParentNode ( ) . addChild ( parentNode ) ; } } // debug message error ( \"Unclosed tag closed: <\" + parentNode . getNodeName ( ) + \">\" ) ; // continue looping parentNode = parentParentNode ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- tree [CODESPLIT] @ Override public void script ( final Tag tag , final CharSequence body ) { if ( ! enabled ) { return ; } Element node = createElementNode ( tag ) ; parentNode . addChild ( node ) ; if ( body . length ( ) != 0 ) { Node text = new Text ( rootNode , body . toString ( ) ) ; node . addChild ( text ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- error [CODESPLIT] @ Override public void error ( final String message ) { rootNode . addError ( message ) ; log . log ( domBuilder . config . getParsingErrorLogLevel ( ) , message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns argument index from the history . <b > Must< / b > POP value from the stack after the execution . [CODESPLIT] protected int getArgumentIndex ( ) { if ( ! isPrevious ) { throw new ProxettaException ( \"Unexpected previous instruction type used for setting argument index\" ) ; } int argIndex ; switch ( opcode ) { case ICONST_0 : argIndex = 0 ; break ; case ICONST_1 : argIndex = 1 ; break ; case ICONST_2 : argIndex = 2 ; break ; case ICONST_3 : argIndex = 3 ; break ; case ICONST_4 : argIndex = 4 ; break ; case ICONST_5 : argIndex = 5 ; break ; case BIPUSH : case SIPUSH : argIndex = operand ; break ; default : throw new ProxettaException ( \"Unexpected previous instruction used for setting argument index\" ) ; } return argIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- visitors [CODESPLIT] @ Override public void visitInsn ( final int opcode ) { this . opcode = opcode ; isPrevious = true ; traceNext = false ; super . visitInsn ( opcode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void argumentsCount ( final MethodVisitor mv , final MethodInfo methodInfo ) { int argsCount = methodInfo . getArgumentsCount ( ) ; pushInt ( mv , argsCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void argumentType ( final MethodVisitor mv , final MethodInfo methodInfo , final int argIndex ) { checkArgumentIndex ( methodInfo , argIndex ) ; mv . visitInsn ( POP ) ; loadMethodArgumentClass ( mv , methodInfo , argIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void argument ( final MethodVisitor mv , final MethodInfo methodInfo , final int argIndex ) { checkArgumentIndex ( methodInfo , argIndex ) ; mv . visitInsn ( POP ) ; loadMethodArgumentAsObject ( mv , methodInfo , argIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void createArgumentsArray ( final MethodVisitor mv , final MethodInfo methodInfo ) { int argsCount = methodInfo . getArgumentsCount ( ) ; pushInt ( mv , argsCount ) ; mv . visitTypeInsn ( ANEWARRAY , AsmUtil . SIGNATURE_JAVA_LANG_OBJECT ) ; for ( int i = 0 ; i < argsCount ; i ++ ) { mv . visitInsn ( DUP ) ; pushInt ( mv , i ) ; loadMethodArgumentAsObject ( mv , methodInfo , i + 1 ) ; mv . visitInsn ( AASTORE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void createArgumentsClassArray ( final MethodVisitor mv , final MethodInfo methodInfo ) { int argsCount = methodInfo . getArgumentsCount ( ) ; pushInt ( mv , argsCount ) ; mv . visitTypeInsn ( ANEWARRAY , AsmUtil . SIGNATURE_JAVA_LANG_CLASS ) ; for ( int i = 0 ; i < argsCount ; i ++ ) { mv . visitInsn ( DUP ) ; pushInt ( mv , i ) ; loadMethodArgumentClass ( mv , methodInfo , i + 1 ) ; mv . visitInsn ( AASTORE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void returnType ( final MethodVisitor mv , final MethodInfo methodInfo ) { ProxettaAsmUtil . loadClass ( mv , methodInfo . getReturnType ( ) . getOpcode ( ) , methodInfo . getReturnType ( ) . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void targetClass ( final MethodVisitor mv , final MethodInfo methodInfo ) { ClassInfo classInfo = methodInfo . getClassInfo ( ) ; mv . visitLdcInsn ( Type . getType ( ' ' + classInfo . getReference ( ) + ' ' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void info ( final MethodVisitor mv , final MethodInfo methodInfo , final int argsOff ) { mv . visitTypeInsn ( Opcodes . NEW , PROXY_TARGET_INFO ) ; mv . visitInsn ( DUP ) ; mv . visitMethodInsn ( Opcodes . INVOKESPECIAL , PROXY_TARGET_INFO , \"<init>\" , \"()V\" , false ) ; //\t\tint argsOff = methodInfo.getAllArgumentsSize(); //\t\targsOff++; mv . visitVarInsn ( Opcodes . ASTORE , argsOff ) ; // argument count mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; argumentsCount ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"argumentCount\" , \"I\" ) ; // arguments class mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; createArgumentsClassArray ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"argumentsClasses\" , \"[Ljava/lang/Class;\" ) ; // arguments mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; createArgumentsArray ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"arguments\" , \"[Ljava/lang/Object;\" ) ; // return type mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; returnType ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"returnType\" , AsmUtil . L_SIGNATURE_JAVA_LANG_CLASS ) ; // target method name mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; targetMethodName ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"targetMethodName\" , AsmUtil . L_SIGNATURE_JAVA_LANG_STRING ) ; // target method name mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; targetMethodDescription ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"targetMethodDescription\" , AsmUtil . L_SIGNATURE_JAVA_LANG_STRING ) ; // target method name mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; targetMethodSignature ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"targetMethodSignature\" , AsmUtil . L_SIGNATURE_JAVA_LANG_STRING ) ; // target class mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; targetClass ( mv , methodInfo ) ; mv . visitFieldInsn ( Opcodes . PUTFIELD , PROXY_TARGET_INFO , \"targetClass\" , AsmUtil . L_SIGNATURE_JAVA_LANG_CLASS ) ; // the end mv . visitVarInsn ( Opcodes . ALOAD , argsOff ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void targetMethodAnnotation ( final MethodVisitor mv , final MethodInfo methodInfo , final String [ ] args ) { AnnotationInfo [ ] anns = methodInfo . getAnnotations ( ) ; if ( anns != null ) { targetAnnotation ( mv , anns , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits replacement code for { [CODESPLIT] public static void targetClassAnnotation ( final MethodVisitor mv , final ClassInfo classInfo , final String [ ] args ) { AnnotationInfo [ ] anns = classInfo . getAnnotations ( ) ; if ( anns != null ) { targetAnnotation ( mv , anns , args ) ; } else { mv . visitInsn ( Opcodes . ACONST_NULL ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the query string . [CODESPLIT] public String getQueryString ( ) { if ( sqlTemplate == null ) { return toString ( ) ; } if ( parameterValues == null ) { return sqlTemplate ; } final StringBuilder sb = new StringBuilder ( ) ; int qMarkCount = 0 ; final StringTokenizer tok = new StringTokenizer ( sqlTemplate + ' ' , \"?\" ) ; while ( tok . hasMoreTokens ( ) ) { final String oneChunk = tok . nextToken ( ) ; sb . append ( oneChunk ) ; try { Object value = null ; if ( parameterValues . size ( ) > 1 + qMarkCount ) { value = parameterValues . get ( 1 + qMarkCount ) ; qMarkCount ++ ; } else { if ( ! tok . hasMoreTokens ( ) ) { value = \"\" ; } } if ( value == null ) { value = \"?\" ; } sb . append ( value ) ; } catch ( Throwable th ) { sb . append ( \"--- Building query failed: \" ) . append ( th . toString ( ) ) ; } } return sb . toString ( ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves the parameter value <code > obj< / code > for the specified <code > position< / code > for use in logging output . [CODESPLIT] protected void saveQueryParamValue ( final int position , final Object obj ) { final String strValue ; if ( obj instanceof String || obj instanceof Date ) { strValue = \"'\" + obj + ' ' ; // if we have a String or Date, include '' in the saved value } else if ( obj instanceof LocalDateTime || obj instanceof LocalDate || obj instanceof LocalTime ) { strValue = \"'\" + Converter . get ( ) . toString ( obj ) + ' ' ; // time as string with ' } else if ( obj == null ) { strValue = \"<null>\" ; // convert null to the string null } else { strValue = Converter . get ( ) . toString ( obj ) ; // all other objects (includes all Numbers, arrays, etc) } // if we are setting a position larger than current size of parameterValues, // first make it larger if ( parameterValues == null ) { parameterValues = new ArrayList <> ( ) ; } while ( position >= parameterValues . size ( ) ) { parameterValues . add ( null ) ; } parameterValues . set ( position , strValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns correct action class name . Detects Proxetta classes . [CODESPLIT] protected String getActionClassName ( final Object action ) { Class clazz = action . getClass ( ) ; clazz = ProxettaUtil . resolveTargetClass ( clazz ) ; return clazz . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates TO . [CODESPLIT] protected int calculateTo ( final int from , final int count , final int size ) { int to = size ; if ( count != - 1 ) { to = from + count ; if ( to > size ) { to = size ; } } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates collection . [CODESPLIT] protected void iterateCollection ( final Collection collection , final int from , final int count , final PageContext pageContext ) throws JspException { JspFragment body = getJspBody ( ) ; Iterator iter = collection . iterator ( ) ; int i = 0 ; int to = calculateTo ( from , count , collection . size ( ) ) ; while ( i < to ) { Object item = iter . next ( ) ; if ( i >= from ) { if ( status != null ) { iteratorStatus . next ( ! iter . hasNext ( ) ) ; } TagUtil . setScopeAttribute ( var , item , scope , pageContext ) ; TagUtil . invokeBody ( body ) ; } i ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates arrays . [CODESPLIT] protected void iterateArray ( final Object [ ] array , final int from , final int count , final PageContext pageContext ) throws JspException { JspFragment body = getJspBody ( ) ; int len = array . length ; int to = calculateTo ( from , count , len ) ; int last = to - 1 ; for ( int i = from ; i < to ; i ++ ) { Object item = array [ i ] ; if ( status != null ) { iteratorStatus . next ( i == last ) ; } TagUtil . setScopeAttribute ( var , item , scope , pageContext ) ; TagUtil . invokeBody ( body ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins entity array using provided string hints . [CODESPLIT] public Object [ ] join ( final Object [ ] data , final String [ ] hints ) { if ( hints == null ) { return data ; } // build context Map < String , Object > context = new HashMap <> ( hints . length ) ; for ( int i = 0 ; i < hints . length ; i ++ ) { hints [ i ] = hints [ i ] . trim ( ) ; String hint = hints [ i ] ; if ( hint . indexOf ( ' ' ) == - 1 ) { context . put ( hint , data [ i ] ) ; } } // no joining hints found if ( context . size ( ) == data . length ) { return data ; } // joining Object [ ] result = new Object [ context . size ( ) ] ; int count = 0 ; for ( int i = 0 ; i < hints . length ; i ++ ) { String hint = hints [ i ] ; int ndx = hint . indexOf ( ' ' ) ; if ( ndx != - 1 ) { String key = hint . substring ( 0 , ndx ) ; Object value = context . get ( key ) ; if ( value == null ) { throw new DbOomException ( \"Hint value missing: \" + key ) ; } // don't merge nulls if ( data [ i ] == null ) { continue ; } String hintPropertyName = hint . substring ( ndx + 1 ) ; Class hintPropertyType = BeanUtil . pojo . getPropertyType ( value , hintPropertyName ) ; if ( hintPropertyType != null ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( hintPropertyType ) ; if ( cd . isCollection ( ) ) { // add element to collection try { Collection collection = BeanUtil . declared . getProperty ( value , hintPropertyName ) ; if ( collection == null ) { collection = ( Collection ) ClassUtil . newInstance ( hintPropertyType ) ; BeanUtil . declaredSilent . setProperty ( value , hintPropertyName , collection ) ; } collection . add ( data [ i ] ) ; } catch ( Exception ex ) { throw new DbOomException ( ex ) ; } } else if ( cd . isArray ( ) ) { // add element to array try { Object [ ] array = BeanUtil . declared . getProperty ( value , hintPropertyName ) ; if ( array == null ) { array = ( Object [ ] ) Array . newInstance ( hintPropertyType . getComponentType ( ) , 1 ) ; BeanUtil . declaredSilent . setProperty ( value , hintPropertyName , array ) ; array [ 0 ] = data [ i ] ; } else { Object [ ] newArray = ArraysUtil . append ( array , data [ i ] ) ; if ( newArray != array ) { BeanUtil . declaredSilent . setProperty ( value , hintPropertyName , newArray ) ; } } } catch ( Exception ex ) { throw new DbOomException ( ex ) ; } } else { // set value BeanUtil . declaredSilent . setProperty ( value , hintPropertyName , data [ i ] ) ; } } else { // special case - the property probably contains the collection in the way int lastNdx = hintPropertyName . lastIndexOf ( ' ' ) ; String name = hintPropertyName . substring ( 0 , lastNdx ) ; Object target = resolveValueInSpecialCase ( value , name ) ; if ( target != null ) { String targetSimpleName = hintPropertyName . substring ( lastNdx + 1 ) ; BeanUtil . declaredForcedSilent . setProperty ( target , targetSimpleName , data [ i ] ) ; } } } else { result [ count ] = data [ i ] ; count ++ ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces all occurrences of a certain pattern in a string with a replacement string . This is the fastest replace function known to author . [CODESPLIT] public static String replace ( final String s , final String sub , final String with ) { if ( sub . isEmpty ( ) ) { return s ; } int c = 0 ; int i = s . indexOf ( sub , c ) ; if ( i == - 1 ) { return s ; } int length = s . length ( ) ; StringBuilder sb = new StringBuilder ( length + with . length ( ) ) ; do { sb . append ( s , c , i ) ; sb . append ( with ) ; c = i + sub . length ( ) ; } while ( ( i = s . indexOf ( sub , c ) ) != - 1 ) ; if ( c < length ) { sb . append ( s , c , length ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces all occurrences of a character in a string . [CODESPLIT] public static String replaceChar ( final String s , final char sub , final char with ) { int startIndex = s . indexOf ( sub ) ; if ( startIndex == - 1 ) { return s ; } char [ ] str = s . toCharArray ( ) ; for ( int i = startIndex ; i < str . length ; i ++ ) { if ( str [ i ] == sub ) { str [ i ] = with ; } } return new String ( str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces all occurrences of a characters in a string . [CODESPLIT] public static String replaceChars ( final String s , final char [ ] sub , final char [ ] with ) { char [ ] str = s . toCharArray ( ) ; for ( int i = 0 ; i < str . length ; i ++ ) { char c = str [ i ] ; for ( int j = 0 ; j < sub . length ; j ++ ) { if ( c == sub [ j ] ) { str [ i ] = with [ j ] ; break ; } } } return new String ( str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the very first occurrence of a substring with supplied string . [CODESPLIT] public static String replaceFirst ( final String s , final String sub , final String with ) { int i = s . indexOf ( sub ) ; if ( i == - 1 ) { return s ; } return s . substring ( 0 , i ) + with + s . substring ( i + sub . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the very first occurrence of a character in a string . [CODESPLIT] public static String replaceFirst ( final String s , final char sub , final char with ) { int index = s . indexOf ( sub ) ; if ( index == - 1 ) { return s ; } char [ ] str = s . toCharArray ( ) ; str [ index ] = with ; return new String ( str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the very last occurrence of a substring with supplied string . [CODESPLIT] public static String replaceLast ( final String s , final String sub , final String with ) { int i = s . lastIndexOf ( sub ) ; if ( i == - 1 ) { return s ; } return s . substring ( 0 , i ) + with + s . substring ( i + sub . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the very last occurrence of a character in a string . [CODESPLIT] public static String replaceLast ( final String s , final char sub , final char with ) { int index = s . lastIndexOf ( sub ) ; if ( index == - 1 ) { return s ; } char [ ] str = s . toCharArray ( ) ; str [ index ] = with ; return new String ( str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all substring occurrences from the string . [CODESPLIT] public static String remove ( final String s , final String sub ) { int c = 0 ; int sublen = sub . length ( ) ; if ( sublen == 0 ) { return s ; } int i = s . indexOf ( sub , c ) ; if ( i == - 1 ) { return s ; } StringBuilder sb = new StringBuilder ( s . length ( ) ) ; do { sb . append ( s , c , i ) ; c = i + sublen ; } while ( ( i = s . indexOf ( sub , c ) ) != - 1 ) ; if ( c < s . length ( ) ) { sb . append ( s , c , s . length ( ) ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a single character from string . [CODESPLIT] public static String remove ( final String string , final char ch ) { int stringLen = string . length ( ) ; char [ ] result = new char [ stringLen ] ; int offset = 0 ; for ( int i = 0 ; i < stringLen ; i ++ ) { char c = string . charAt ( i ) ; if ( c == ch ) { continue ; } result [ offset ] = c ; offset ++ ; } if ( offset == stringLen ) { return string ; // no changes } return new String ( result , 0 , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if string array contains empty strings . [CODESPLIT] public static boolean isAllEmpty ( final String ... strings ) { for ( String string : strings ) { if ( ! isEmpty ( string ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if string array contains just blank strings . [CODESPLIT] public static boolean isAllBlank ( final String ... strings ) { for ( String string : strings ) { if ( ! isBlank ( string ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if string contains only white spaces . [CODESPLIT] public static boolean containsOnlyWhitespaces ( final CharSequence string ) { int size = string . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { char c = string . charAt ( i ) ; if ( ! CharUtil . isWhitespace ( c ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if string contains only digits . [CODESPLIT] public static boolean containsOnlyDigits ( final CharSequence string ) { int size = string . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { char c = string . charAt ( i ) ; if ( ! CharUtil . isDigit ( c ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array object to array of strings where every element of input array is converted to a string . If input is not an array the result will still be an array with one element . [CODESPLIT] public static String [ ] toStringArray ( final Object value ) { if ( value == null ) { return new String [ 0 ] ; } Class < ? > type = value . getClass ( ) ; if ( ! type . isArray ( ) ) { return new String [ ] { value . toString ( ) } ; } Class componentType = type . getComponentType ( ) ; if ( componentType . isPrimitive ( ) ) { if ( componentType == int . class ) { return ArraysUtil . toStringArray ( ( int [ ] ) value ) ; } else if ( componentType == long . class ) { return ArraysUtil . toStringArray ( ( long [ ] ) value ) ; } else if ( componentType == double . class ) { return ArraysUtil . toStringArray ( ( double [ ] ) value ) ; } else if ( componentType == float . class ) { return ArraysUtil . toStringArray ( ( float [ ] ) value ) ; } else if ( componentType == boolean . class ) { return ArraysUtil . toStringArray ( ( boolean [ ] ) value ) ; } else if ( componentType == short . class ) { return ArraysUtil . toStringArray ( ( short [ ] ) value ) ; } else if ( componentType == byte . class ) { return ArraysUtil . toStringArray ( ( byte [ ] ) value ) ; } else { throw new IllegalArgumentException ( ) ; } } else { return ArraysUtil . toStringArray ( ( Object [ ] ) value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method for changing the first character case . [CODESPLIT] private static String changeFirstCharacterCase ( final boolean capitalize , final String string ) { int strLen = string . length ( ) ; if ( strLen == 0 ) { return string ; } char ch = string . charAt ( 0 ) ; char modifiedCh ; if ( capitalize ) { modifiedCh = Character . toUpperCase ( ch ) ; } else { modifiedCh = Character . toLowerCase ( ch ) ; } if ( modifiedCh == ch ) { // no change, return unchanged string return string ; } char [ ] chars = string . toCharArray ( ) ; chars [ 0 ] = modifiedCh ; return new String ( chars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a title - cased string from given input . [CODESPLIT] public static String title ( final String string ) { char [ ] chars = string . toCharArray ( ) ; boolean wasWhitespace = true ; for ( int i = 0 ; i < chars . length ; i ++ ) { char c = chars [ i ] ; if ( CharUtil . isWhitespace ( c ) ) { wasWhitespace = true ; } else { if ( wasWhitespace ) { chars [ i ] = Character . toUpperCase ( c ) ; } else { chars [ i ] = Character . toLowerCase ( c ) ; } wasWhitespace = false ; } } return new String ( chars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new string that is a substring of this string . The substring begins at the specified <code > fromIndex< / code > and extends to the character at index <code > toIndex - 1< / code > . However index values can be negative and then the real index will be calculated from the strings end . This allows to specify e . g . <code > substring ( 1 - 1 ) < / code > to cut one character from both ends of the string . If <code > fromIndex< / code > is negative and <code > toIndex< / code > is 0 it will return last characters of the string . Also this method will never throw an exception if index is out of range . [CODESPLIT] public static String substring ( final String string , int fromIndex , int toIndex ) { int len = string . length ( ) ; if ( fromIndex < 0 ) { fromIndex = len + fromIndex ; if ( toIndex == 0 ) { toIndex = len ; } } if ( toIndex < 0 ) { toIndex = len + toIndex ; } // safe net if ( fromIndex < 0 ) { fromIndex = 0 ; } if ( toIndex > len ) { toIndex = len ; } if ( fromIndex >= toIndex ) { return StringPool . EMPTY ; } return string . substring ( fromIndex , toIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if substring exist at given offset in a string . [CODESPLIT] public static boolean isSubstringAt ( final String string , final String substring , final int offset ) { int len = substring . length ( ) ; int max = offset + len ; if ( max > string . length ( ) ) { return false ; } int ndx = 0 ; for ( int i = offset ; i < max ; i ++ , ndx ++ ) { if ( string . charAt ( i ) != substring . charAt ( ndx ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a string in several parts ( tokens ) that are separated by delimiter . Delimiter is <b > always< / b > surrounded by two strings! If there is no content between two delimiters empty string will be returned for that token . Therefore the length of the returned array will always be : #delimiters + 1 . <p > Method is much much faster then regexp <code > String . split () < / code > and a bit faster then <code > StringTokenizer< / code > . [CODESPLIT] public static String [ ] split ( final String src , final String delimiter ) { int maxparts = ( src . length ( ) / delimiter . length ( ) ) + 2 ; // one more for the last int [ ] positions = new int [ maxparts ] ; int dellen = delimiter . length ( ) ; int i , j = 0 ; int count = 0 ; positions [ 0 ] = - dellen ; while ( ( i = src . indexOf ( delimiter , j ) ) != - 1 ) { count ++ ; positions [ count ] = i ; j = i + dellen ; } count ++ ; positions [ count ] = src . length ( ) ; String [ ] result = new String [ count ] ; for ( i = 0 ; i < count ; i ++ ) { result [ i ] = src . substring ( positions [ i ] + dellen , positions [ i + 1 ] ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a string in several parts ( tokens ) that are separated by delimiter characters . Delimiter may contains any number of character and it is always surrounded by two strings . [CODESPLIT] public static String [ ] splitc ( final String src , final String d ) { if ( ( d . length ( ) == 0 ) || ( src . length ( ) == 0 ) ) { return new String [ ] { src } ; } return splitc ( src , d . toCharArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compress multiple occurrences of given char into one appearance . [CODESPLIT] public static String compressChars ( final String s , final char c ) { int len = s . length ( ) ; StringBuilder sb = new StringBuilder ( len ) ; boolean wasChar = false ; for ( int i = 0 ; i < len ; i ++ ) { char c1 = s . charAt ( i ) ; if ( c1 == c ) { if ( wasChar ) { continue ; } wasChar = true ; } else { wasChar = false ; } sb . append ( c1 ) ; } if ( sb . length ( ) == len ) { return s ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence of a character in the given source but within limited range ( start end ] . [CODESPLIT] public static int indexOf ( final String src , final char c , int startIndex , int endIndex ) { if ( startIndex < 0 ) { startIndex = 0 ; } int srclen = src . length ( ) ; if ( endIndex > srclen ) { endIndex = srclen ; } for ( int i = startIndex ; i < endIndex ; i ++ ) { if ( src . charAt ( i ) == c ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence of a character in the given source but within limited range ( start end ] . [CODESPLIT] public static int indexOfIgnoreCase ( final String src , char c , int startIndex , int endIndex ) { if ( startIndex < 0 ) { startIndex = 0 ; } int srclen = src . length ( ) ; if ( endIndex > srclen ) { endIndex = srclen ; } c = Character . toLowerCase ( c ) ; for ( int i = startIndex ; i < endIndex ; i ++ ) { if ( Character . toLowerCase ( src . charAt ( i ) ) == c ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds first index of a substring in the given source string with ignored case . [CODESPLIT] public static int indexOfIgnoreCase ( final String src , final String subS ) { return indexOfIgnoreCase ( src , subS , 0 , src . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds last index of a substring in the given source string with ignored case . [CODESPLIT] public static int lastIndexOfIgnoreCase ( final String s , final String subS ) { return lastIndexOfIgnoreCase ( s , subS , s . length ( ) , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds last index of a substring in the given source string with ignored case . [CODESPLIT] public static int lastIndexOfIgnoreCase ( final String src , final String subS , final int startIndex ) { return lastIndexOfIgnoreCase ( src , subS , startIndex , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds last index of a substring in the given source string in specified range [ end start ] See { @link #indexOf ( String String int int ) } for details about the speed . [CODESPLIT] public static int lastIndexOf ( final String src , final String sub , int startIndex , int endIndex ) { int sublen = sub . length ( ) ; int srclen = src . length ( ) ; if ( sublen == 0 ) { return startIndex > srclen ? srclen : ( startIndex < - 1 ? - 1 : startIndex ) ; } int total = srclen - sublen ; if ( total < 0 ) { return - 1 ; } if ( startIndex >= total ) { startIndex = total ; } if ( endIndex < 0 ) { endIndex = 0 ; } char c = sub . charAt ( 0 ) ; mainloop : for ( int i = startIndex ; i >= endIndex ; i -- ) { if ( src . charAt ( i ) != c ) { continue ; } int j = 1 ; int k = i + 1 ; while ( j < sublen ) { if ( sub . charAt ( j ) != src . charAt ( k ) ) { continue mainloop ; } j ++ ; k ++ ; } return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds last index of a character in the given source string in specified range [ end start ] [CODESPLIT] public static int lastIndexOf ( final String src , final char c , int startIndex , int endIndex ) { int total = src . length ( ) - 1 ; if ( total < 0 ) { return - 1 ; } if ( startIndex >= total ) { startIndex = total ; } if ( endIndex < 0 ) { endIndex = 0 ; } for ( int i = startIndex ; i >= endIndex ; i -- ) { if ( src . charAt ( i ) == c ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if this string starts with the specified prefix with ignored case and with the specified prefix beginning a specified index . [CODESPLIT] public static boolean startsWithIgnoreCase ( final String src , final String subS , final int startIndex ) { String sub = subS . toLowerCase ( ) ; int sublen = sub . length ( ) ; if ( startIndex + sublen > src . length ( ) ) { return false ; } int j = 0 ; int i = startIndex ; while ( j < sublen ) { char source = Character . toLowerCase ( src . charAt ( i ) ) ; if ( sub . charAt ( j ) != source ) { return false ; } j ++ ; i ++ ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns if string ends with provided character . [CODESPLIT] public static boolean endsWithChar ( final String s , final char c ) { if ( s . length ( ) == 0 ) { return false ; } return s . charAt ( s . length ( ) - 1 ) == c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count substring occurrences in a source string ignoring case . [CODESPLIT] public static int countIgnoreCase ( final String source , final String sub ) { int count = 0 ; int j = 0 ; int sublen = sub . length ( ) ; if ( sublen == 0 ) { return 0 ; } while ( true ) { int i = indexOfIgnoreCase ( source , sub , j ) ; if ( i == - 1 ) { break ; } count ++ ; j = i + sublen ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the very last index of a substring from the specified array . It returns an int [ 2 ] where int [ 0 ] represents the substring index and int [ 1 ] represents position where substring was found . Returns <code > null< / code > if noting found . [CODESPLIT] public static int [ ] lastIndexOfIgnoreCase ( final String s , final String ... arr ) { return lastIndexOfIgnoreCase ( s , arr , s . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two string arrays . [CODESPLIT] public static boolean equalsIgnoreCase ( final String [ ] as , final String [ ] as1 ) { if ( as . length != as1 . length ) { return false ; } for ( int i = 0 ; i < as . length ; i ++ ) { if ( ! as [ i ] . equalsIgnoreCase ( as1 [ i ] ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces many substring at once . Order of string array is important . [CODESPLIT] public static String replace ( final String s , final String [ ] sub , final String [ ] with ) { if ( ( sub . length != with . length ) || ( sub . length == 0 ) ) { return s ; } int start = 0 ; StringBuilder buf = new StringBuilder ( s . length ( ) ) ; while ( true ) { int [ ] res = indexOf ( s , sub , start ) ; if ( res == null ) { break ; } int end = res [ 1 ] ; buf . append ( s , start , end ) ; buf . append ( with [ res [ 0 ] ] ) ; start = end + sub [ res [ 0 ] ] . length ( ) ; } buf . append ( s . substring ( start ) ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces many substring at once . Order of string array is important . [CODESPLIT] public static String replaceIgnoreCase ( final String s , final String [ ] sub , final String [ ] with ) { if ( ( sub . length != with . length ) || ( sub . length == 0 ) ) { return s ; } int start = 0 ; StringBuilder buf = new StringBuilder ( s . length ( ) ) ; while ( true ) { int [ ] res = indexOfIgnoreCase ( s , sub , start ) ; if ( res == null ) { break ; } int end = res [ 1 ] ; buf . append ( s , start , end ) ; buf . append ( with [ res [ 0 ] ] ) ; start = end + sub [ 0 ] . length ( ) ; } buf . append ( s . substring ( start ) ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares string with at least one from the provided array . If at least one equal string is found returns its index . Otherwise <code > - 1< / code > is returned . [CODESPLIT] public static int equalsOne ( final String src , final String ... dest ) { for ( int i = 0 ; i < dest . length ; i ++ ) { if ( src . equals ( dest [ i ] ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares string with at least one from the provided array ignoring case . If at least one equal string is found it returns its index . Otherwise <code > - 1< / code > is returned . [CODESPLIT] public static int equalsOneIgnoreCase ( final String src , final String ... dest ) { for ( int i = 0 ; i < dest . length ; i ++ ) { if ( src . equalsIgnoreCase ( dest [ i ] ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if string starts with at least one string from the provided array . If at least one string is matched it returns its index . Otherwise <code > - 1< / code > is returned . [CODESPLIT] public static int startsWithOne ( final String src , final String ... dest ) { for ( int i = 0 ; i < dest . length ; i ++ ) { String m = dest [ i ] ; if ( m == null ) { continue ; } if ( src . startsWith ( m ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if string starts with at least one string from the provided array . If at least one string is matched it returns its index . Otherwise <code > - 1< / code > is returned . [CODESPLIT] public static int startsWithOneIgnoreCase ( final String src , final String ... dest ) { for ( int i = 0 ; i < dest . length ; i ++ ) { String m = dest [ i ] ; if ( m == null ) { continue ; } if ( startsWithIgnoreCase ( src , m ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if string ends with at least one string from the provided array . If at least one string is matched it returns its index . Otherwise <code > - 1< / code > is returned . [CODESPLIT] public static int endsWithOne ( final String src , final String ... dest ) { for ( int i = 0 ; i < dest . length ; i ++ ) { String m = dest [ i ] ; if ( m == null ) { continue ; } if ( src . endsWith ( m ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if string ends with at least one string from the provided array . If at least one string is matched it returns its index . Otherwise <code > - 1< / code > is returned . [CODESPLIT] public static int endsWithOneIgnoreCase ( final String src , final String ... dest ) { for ( int i = 0 ; i < dest . length ; i ++ ) { String m = dest [ i ] ; if ( m == null ) { continue ; } if ( endsWithIgnoreCase ( src , m ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns first index of a whitespace character starting from specified index offset . [CODESPLIT] public static int indexOfWhitespace ( final String string , final int startindex , final int endindex ) { for ( int i = startindex ; i < endindex ; i ++ ) { if ( CharUtil . isWhitespace ( string . charAt ( i ) ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips leading char if string starts with one . [CODESPLIT] public static String stripLeadingChar ( final String string , final char c ) { if ( string . length ( ) > 0 ) { if ( string . charAt ( 0 ) == c ) { return string . substring ( 1 ) ; } } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips trailing char if string ends with one . [CODESPLIT] public static String stripTrailingChar ( final String string , final char c ) { if ( string . length ( ) > 0 ) { if ( string . charAt ( string . length ( ) - 1 ) == c ) { return string . substring ( 0 , string . length ( ) - 1 ) ; } } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips leading and trailing char from given string . [CODESPLIT] public static String stripChar ( final String string , final char c ) { if ( string . length ( ) == 0 ) { return string ; } if ( string . length ( ) == 1 ) { if ( string . charAt ( 0 ) == c ) { return StringPool . EMPTY ; } return string ; } int left = 0 ; int right = string . length ( ) ; if ( string . charAt ( left ) == c ) { left ++ ; } if ( string . charAt ( right - 1 ) == c ) { right -- ; } return string . substring ( left , right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips everything up to the first appearance of given char . Character IS included in the returned string . [CODESPLIT] public static String stripToChar ( final String string , final char c ) { int ndx = string . indexOf ( c ) ; if ( ndx == - 1 ) { return string ; } return string . substring ( ndx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips everything from the first appearance of given char . Character IS NOT included in the returned string . [CODESPLIT] public static String stripFromChar ( final String string , final char c ) { int ndx = string . indexOf ( c ) ; if ( ndx == - 1 ) { return string ; } return string . substring ( 0 , ndx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trims array of strings . <code > null< / code > array elements are ignored . [CODESPLIT] public static void trimAll ( final String ... strings ) { for ( int i = 0 ; i < strings . length ; i ++ ) { String string = strings [ i ] ; if ( string != null ) { strings [ i ] = string . trim ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trims array of strings where empty strings are set to <code > null< / code > . <code > null< / code > elements of the array are ignored . [CODESPLIT] public static void trimDownAll ( final String ... strings ) { for ( int i = 0 ; i < strings . length ; i ++ ) { String string = strings [ i ] ; if ( string != null ) { strings [ i ] = trimDown ( string ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trims string and sets to <code > null< / code > if trimmed string is empty . [CODESPLIT] public static String trimDown ( String string ) { string = string . trim ( ) ; if ( string . length ( ) == 0 ) { string = null ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Crops all elements of string array . [CODESPLIT] public static void cropAll ( final String ... strings ) { for ( int i = 0 ; i < strings . length ; i ++ ) { String string = strings [ i ] ; if ( string != null ) { string = crop ( strings [ i ] ) ; } strings [ i ] = string ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trim whitespaces from the left . [CODESPLIT] public static String trimLeft ( final String src ) { int len = src . length ( ) ; int st = 0 ; while ( ( st < len ) && ( CharUtil . isWhitespace ( src . charAt ( st ) ) ) ) { st ++ ; } return st > 0 ? src . substring ( st ) : src ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trim whitespaces from the right . [CODESPLIT] public static String trimRight ( final String src ) { int len = src . length ( ) ; int count = len ; while ( ( len > 0 ) && ( CharUtil . isWhitespace ( src . charAt ( len - 1 ) ) ) ) { len -- ; } return ( len < count ) ? src . substring ( 0 , len ) : src ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns indexes of the first region without escaping character . [CODESPLIT] public static int [ ] indexOfRegion ( final String string , final String leftBoundary , final String rightBoundary , final int offset ) { int ndx = offset ; int [ ] res = new int [ 4 ] ; ndx = string . indexOf ( leftBoundary , ndx ) ; if ( ndx == - 1 ) { return null ; } res [ 0 ] = ndx ; ndx += leftBoundary . length ( ) ; res [ 1 ] = ndx ; ndx = string . indexOf ( rightBoundary , ndx ) ; if ( ndx == - 1 ) { return null ; } res [ 2 ] = ndx ; res [ 3 ] = ndx + rightBoundary . length ( ) ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns indexes of the first string region . Region is defined by its left and right boundary . Return value is an array of the following indexes : <ul > <li > start of left boundary index< / li > <li > region start index i . e . end of left boundary< / li > <li > region end index i . e . start of right boundary< / li > <li > end of right boundary index< / li > < / ul > <p > Escape character may be used to prefix boundaries so they can be ignored . Double escaped region will be found and first index of the result will be decreased to include one escape character . If region is not founded <code > null< / code > is returned . [CODESPLIT] public static int [ ] indexOfRegion ( final String string , final String leftBoundary , final String rightBoundary , final char escape , final int offset ) { int ndx = offset ; int [ ] res = new int [ 4 ] ; while ( true ) { ndx = string . indexOf ( leftBoundary , ndx ) ; if ( ndx == - 1 ) { return null ; } int leftBoundaryLen = leftBoundary . length ( ) ; if ( ndx > 0 ) { if ( string . charAt ( ndx - 1 ) == escape ) { // check previous char boolean cont = true ; if ( ndx > 1 ) { if ( string . charAt ( ndx - 2 ) == escape ) { // check double escapes ndx -- ; leftBoundaryLen ++ ; cont = false ; } } if ( cont ) { ndx += leftBoundaryLen ; continue ; } } } res [ 0 ] = ndx ; ndx += leftBoundaryLen ; res [ 1 ] = ndx ; while ( true ) { // find right boundary ndx = string . indexOf ( rightBoundary , ndx ) ; if ( ndx == - 1 ) { return null ; } if ( ndx > 0 ) { if ( string . charAt ( ndx - 1 ) == escape ) { ndx += rightBoundary . length ( ) ; continue ; } } res [ 2 ] = ndx ; res [ 3 ] = ndx + rightBoundary . length ( ) ; return res ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins an collection of objects into one string with separator . [CODESPLIT] public static String join ( final Collection collection , final char separator ) { if ( collection == null ) { return null ; } if ( collection . size ( ) == 0 ) { return StringPool . EMPTY ; } final StringBuilder sb = new StringBuilder ( collection . size ( ) * 16 ) ; final Iterator it = collection . iterator ( ) ; for ( int i = 0 ; i < collection . size ( ) ; i ++ ) { if ( i > 0 ) { sb . append ( separator ) ; } sb . append ( it . next ( ) ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins an array of objects into one string with separator . [CODESPLIT] public static String join ( final Object [ ] array , final String separator ) { if ( array == null ) { return null ; } if ( array . length == 0 ) { return StringPool . EMPTY ; } if ( array . length == 1 ) { return String . valueOf ( array [ 0 ] ) ; } final StringBuilder sb = new StringBuilder ( array . length * 16 ) ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( i > 0 ) { sb . append ( separator ) ; } sb . append ( array [ i ] ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts string charset . If charset names are the same the same string is returned . [CODESPLIT] public static String convertCharset ( final String source , final String srcCharsetName , final String newCharsetName ) { if ( srcCharsetName . equals ( newCharsetName ) ) { return source ; } return StringUtil . newString ( StringUtil . getBytes ( source , srcCharsetName ) , newCharsetName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safely compares provided char with char on given location . [CODESPLIT] public static boolean isCharAtEqual ( final String string , final int index , final char charToCompare ) { if ( ( index < 0 ) || ( index >= string . length ( ) ) ) { return false ; } return string . charAt ( index ) == charToCompare ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Surrounds the string with provided prefix and suffix if such missing from string . [CODESPLIT] public static String surround ( String string , final String prefix , final String suffix ) { if ( ! string . startsWith ( prefix ) ) { string = prefix + string ; } if ( ! string . endsWith ( suffix ) ) { string += suffix ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts prefix if doesn t exist . [CODESPLIT] public static String prefix ( String string , final String prefix ) { if ( ! string . startsWith ( prefix ) ) { string = prefix + string ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends suffix if doesn t exist . [CODESPLIT] public static String suffix ( String string , final String suffix ) { if ( ! string . endsWith ( suffix ) ) { string += suffix ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts the string from beginning to the first index of provided substring . [CODESPLIT] public static String cutToIndexOf ( String string , final String substring ) { int i = string . indexOf ( substring ) ; if ( i != - 1 ) { string = string . substring ( 0 , i ) ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts the string from the first index of provided substring to the end . [CODESPLIT] public static String cutFromIndexOf ( String string , final String substring ) { int i = string . indexOf ( substring ) ; if ( i != - 1 ) { string = string . substring ( i ) ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts prefix if exists . [CODESPLIT] public static String cutPrefix ( String string , final String prefix ) { if ( string . startsWith ( prefix ) ) { string = string . substring ( prefix . length ( ) ) ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts sufix if exists . [CODESPLIT] public static String cutSuffix ( String string , final String suffix ) { if ( string . endsWith ( suffix ) ) { string = string . substring ( 0 , string . length ( ) - suffix . length ( ) ) ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes surrounding prefix and suffixes . [CODESPLIT] public static String cutSurrounding ( final String string , final String prefix , final String suffix ) { int start = 0 ; int end = string . length ( ) ; if ( string . startsWith ( prefix ) ) { start = prefix . length ( ) ; } if ( string . endsWith ( suffix ) ) { end -= suffix . length ( ) ; } if ( end <= start ) { return StringPool . EMPTY ; } return string . substring ( start , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts a string between two other strings . If either of left and right is missing nothing will be cut and <code > null< / code > is returned . If indexes of left or right strings are wrong empty string is returned . [CODESPLIT] public static String cutBetween ( final String string , final String left , final String right ) { int leftNdx = string . indexOf ( left ) ; if ( leftNdx == - 1 ) { return null ; } int rightNdx = string . indexOf ( right ) ; if ( rightNdx == - 1 ) { return null ; } leftNdx += left . length ( ) ; if ( leftNdx >= rightNdx ) { return StringPool . EMPTY ; } return string . substring ( leftNdx , rightNdx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if character at provided index position is escaped by escape character . [CODESPLIT] public static boolean isCharAtEscaped ( final String src , int ndx , final char escapeChar ) { if ( ndx == 0 ) { return false ; } ndx -- ; return src . charAt ( ndx ) == escapeChar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a string on provided offset . [CODESPLIT] public static String insert ( final String src , final String insert , int offset ) { if ( offset < 0 ) { offset = 0 ; } if ( offset > src . length ( ) ) { offset = src . length ( ) ; } StringBuilder sb = new StringBuilder ( src ) ; sb . insert ( offset , insert ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new string that contains the provided string a number of times . [CODESPLIT] public static String repeat ( final String source , int count ) { StringBand result = new StringBand ( count ) ; while ( count > 0 ) { result . append ( source ) ; count -- ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverse a string . [CODESPLIT] public static String reverse ( final String s ) { StringBuilder result = new StringBuilder ( s . length ( ) ) ; for ( int i = s . length ( ) - 1 ; i >= 0 ; i -- ) { result . append ( s . charAt ( i ) ) ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns max common prefix of two strings . [CODESPLIT] public static String maxCommonPrefix ( final String one , final String two ) { final int minLength = Math . min ( one . length ( ) , two . length ( ) ) ; final StringBuilder sb = new StringBuilder ( minLength ) ; for ( int pos = 0 ; pos < minLength ; pos ++ ) { final char currentChar = one . charAt ( pos ) ; if ( currentChar != two . charAt ( pos ) ) { break ; } sb . append ( currentChar ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds common prefix for several strings . Returns an empty string if arguments do not have a common prefix . [CODESPLIT] public static String findCommonPrefix ( final String ... strings ) { StringBuilder prefix = new StringBuilder ( ) ; int index = 0 ; char c = 0 ; loop : while ( true ) { for ( int i = 0 ; i < strings . length ; i ++ ) { String s = strings [ i ] ; if ( index == s . length ( ) ) { break loop ; } if ( i == 0 ) { c = s . charAt ( index ) ; } else { if ( s . charAt ( index ) != c ) { break loop ; } } } index ++ ; prefix . append ( c ) ; } return prefix . length ( ) == 0 ? StringPool . EMPTY : prefix . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shorten string to given length . [CODESPLIT] public static String shorten ( String s , int length , final String suffix ) { length -= suffix . length ( ) ; if ( s . length ( ) > length ) { for ( int j = length ; j >= 0 ; j -- ) { if ( CharUtil . isWhitespace ( s . charAt ( j ) ) ) { length = j ; break ; } } String temp = s . substring ( 0 , length ) ; s = temp . concat ( suffix ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts all of the characters in the string to upper case based on the locale . [CODESPLIT] public static String toUpperCase ( final String s , Locale locale ) { if ( s == null ) { return null ; } StringBuilder sb = null ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c > 127 ) { // found non-ascii char, fallback to the slow unicode detection if ( locale == null ) { locale = Locale . getDefault ( ) ; } return s . toUpperCase ( locale ) ; } if ( ( c >= ' ' ) && ( c <= ' ' ) ) { if ( sb == null ) { sb = new StringBuilder ( s ) ; } sb . setCharAt ( i , ( char ) ( c - 32 ) ) ; } } if ( sb == null ) { return s ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes starting and ending single or double quotes . [CODESPLIT] public static String removeQuotes ( final String string ) { if ( ( startsWithChar ( string , ' ' ) && endsWithChar ( string , ' ' ) ) || ( startsWithChar ( string , ' ' ) && endsWithChar ( string , ' ' ) ) || ( startsWithChar ( string , ' ' ) && endsWithChar ( string , ' ' ) ) ) { return substring ( string , 1 , - 1 ) ; } return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts bytes to hex string . [CODESPLIT] public static String toHexString ( final byte [ ] bytes ) { char [ ] chars = new char [ bytes . length * 2 ] ; int i = 0 ; for ( byte b : bytes ) { chars [ i ++ ] = CharUtil . int2hex ( ( b & 0xF0 ) >> 4 ) ; chars [ i ++ ] = CharUtil . int2hex ( b & 0x0F ) ; } return new String ( chars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes function on a string if not { [CODESPLIT] public static String ifNotNull ( final String input , final Function < String , String > stringFunction ) { if ( input == null ) { return StringPool . EMPTY ; } return stringFunction . apply ( input ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns String bytes using Jodds default encoding . [CODESPLIT] public static byte [ ] getBytes ( final String string ) { try { return string . getBytes ( JoddCore . encoding ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects quote character or return 0 . [CODESPLIT] public static char detectQuoteChar ( final String str ) { if ( str . length ( ) < 2 ) { return 0 ; } final char c = str . charAt ( 0 ) ; if ( c != str . charAt ( str . length ( ) - 1 ) ) { return 0 ; } if ( c == ' ' || c == ' ' || c == ' ' ) { return c ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Redirects to the given location . Provided path is parsed action is used as a value context . [CODESPLIT] @ Override public void render ( final ActionRequest actionRequest , final Object resultValue ) { final PermRedirect redirectResult ; if ( resultValue == null ) { redirectResult = PermRedirect . to ( StringPool . SLASH ) ; } else { if ( resultValue instanceof String ) { redirectResult = PermRedirect . to ( ( String ) resultValue ) ; } else { redirectResult = ( PermRedirect ) resultValue ; } } final String resultBasePath = actionRequest . getActionRuntime ( ) . getResultBasePath ( ) ; final String redirectValue = redirectResult . path ( ) ; final String resultPath ; if ( redirectValue . startsWith ( \"http://\" ) || redirectValue . startsWith ( \"https://\" ) ) { resultPath = redirectValue ; } else { resultPath = resultMapper . resolveResultPathString ( resultBasePath , redirectValue ) ; } final HttpServletRequest request = actionRequest . getHttpServletRequest ( ) ; final HttpServletResponse response = actionRequest . getHttpServletResponse ( ) ; String path = beanTemplateParser . parseWithBean ( resultPath , actionRequest . getAction ( ) ) ; DispatcherUtil . redirectPermanent ( request , response , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastIntBuffer append ( final FastIntBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a primitive value of the annotation . [CODESPLIT] public void visit ( final String name , final Object value ) { if ( av != null ) { av . visit ( name , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an enumeration value of the annotation . [CODESPLIT] public void visitEnum ( final String name , final String descriptor , final String value ) { if ( av != null ) { av . visitEnum ( name , descriptor , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a nested annotation value of the annotation . [CODESPLIT] public AnnotationVisitor visitAnnotation ( final String name , final String descriptor ) { if ( av != null ) { return av . visitAnnotation ( name , descriptor ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups { [CODESPLIT] public < E > DbEntityDescriptor < E > lookupType ( final Class < E > type ) { String typeName = type . getName ( ) ; if ( StringUtil . startsWithOne ( typeName , primitiveEntitiesPrefixes ) != - 1 ) { return null ; } DbEntityDescriptor < E > ded = descriptorsMap . get ( type ) ; if ( ded == null ) { ded = registerType ( type ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers just type and entity names . Enough for most usages . [CODESPLIT] public < E > DbEntityDescriptor < E > registerType ( final Class < E > type ) { DbEntityDescriptor < E > ded = createDbEntityDescriptor ( type ) ; DbEntityDescriptor < E > existing = descriptorsMap . put ( type , ded ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Register \" + type . getName ( ) + \" as \" + ded . getTableName ( ) ) ; } if ( existing != null ) { if ( ded . getType ( ) == type ) { return ded ; } throw new DbOomException ( \"Type already registered: \" + existing . getType ( ) ) ; } existing = entityNamesMap . put ( ded . getEntityName ( ) , ded ) ; if ( existing != null ) { throw new DbOomException ( \"Name '\" + ded . getEntityName ( ) + \"' already mapped to an entity: \" + existing . getType ( ) ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers entity . { [CODESPLIT] public < E > DbEntityDescriptor < E > registerEntity ( final Class < E > type ) { DbEntityDescriptor < E > ded = registerType ( type ) ; DbEntityDescriptor existing = tableNamesMap . put ( ded . getTableName ( ) , ded ) ; if ( existing != null ) { if ( ded . getType ( ) == type ) { return ded ; } throw new DbOomException ( \"Entity registration failed! Table '\" + ded . getTableName ( ) + \"' already mapped to an entity: \" + existing . getType ( ) ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers entity . Existing entity will be removed if exist so no exception will be thrown . [CODESPLIT] public < E > DbEntityDescriptor < E > registerEntity ( final Class < E > type , final boolean force ) { if ( force ) { removeEntity ( type ) ; } return registerEntity ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes entity and returns removed descriptor . [CODESPLIT] public < E > DbEntityDescriptor < E > removeEntity ( final Class < E > type ) { DbEntityDescriptor < E > ded = descriptorsMap . remove ( type ) ; if ( ded == null ) { ded = createDbEntityDescriptor ( type ) ; } entityNamesMap . remove ( ded . getEntityName ( ) ) ; tableNamesMap . remove ( ded . getTableName ( ) ) ; return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] protected < E > DbEntityDescriptor < E > createDbEntityDescriptor ( final Class < E > type ) { final String schemaName = dbOomConfig . getSchemaName ( ) ; final TableNamingStrategy tableNames = dbOomConfig . getTableNames ( ) ; final ColumnNamingStrategy columnNames = dbOomConfig . getColumnNames ( ) ; return new DbEntityDescriptor <> ( type , schemaName , tableNames , columnNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new entity instances . [CODESPLIT] public < E > E createEntityInstance ( final Class < E > type ) { try { return ClassUtil . newInstance ( type ) ; } catch ( Exception ex ) { throw new DbOomException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines the interface of the resulting class . [CODESPLIT] public WrapperProxettaFactory setTargetInterface ( final Class targetInterface ) { if ( ! targetInterface . isInterface ( ) ) { throw new ProxettaException ( \"Not an interface: \" + targetInterface . getName ( ) ) ; } this . targetInterface = targetInterface ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected WorkData process ( final ClassReader cr , final TargetClassInfoReader targetClassInfoReader ) { final ProxettaWrapperClassBuilder pcb = new ProxettaWrapperClassBuilder ( targetClassOrInterface , targetInterface , targetFieldName , destClassWriter , proxetta . getAspects ( new ProxyAspect [ 0 ] ) , resolveClassNameSuffix ( ) , requestedProxyClassName , targetClassInfoReader , createTargetInDefaultCtor ) ; cr . accept ( pcb , 0 ) ; return pcb . getWorkData ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects target into wrapper . [CODESPLIT] public void injectTargetIntoWrapper ( final Object target , final Object wrapper ) { ProxettaUtil . injectTargetIntoWrapper ( target , wrapper , targetFieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for annotated properties . Caches all annotated properties on the first action class scan . [CODESPLIT] protected PropertyDescriptor [ ] lookupAnnotatedProperties ( final Class type ) { PropertyDescriptor [ ] properties = annotatedProperties . get ( type ) ; if ( properties != null ) { return properties ; } ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; PropertyDescriptor [ ] allProperties = cd . getAllPropertyDescriptors ( ) ; List < PropertyDescriptor > list = new ArrayList <> ( ) ; for ( PropertyDescriptor propertyDescriptor : allProperties ) { Annotation ann = null ; if ( propertyDescriptor . getFieldDescriptor ( ) != null ) { ann = propertyDescriptor . getFieldDescriptor ( ) . getField ( ) . getAnnotation ( annotations ) ; } if ( ann == null && propertyDescriptor . getWriteMethodDescriptor ( ) != null ) { ann = propertyDescriptor . getWriteMethodDescriptor ( ) . getMethod ( ) . getAnnotation ( annotations ) ; } if ( ann == null && propertyDescriptor . getReadMethodDescriptor ( ) != null ) { ann = propertyDescriptor . getReadMethodDescriptor ( ) . getMethod ( ) . getAnnotation ( annotations ) ; } if ( ann != null ) { list . add ( propertyDescriptor ) ; } } if ( list . isEmpty ( ) ) { properties = EMPTY ; } else { properties = list . toArray ( new PropertyDescriptor [ 0 ] ) ; } annotatedProperties . put ( type , properties ) ; return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects database and configure DbOom engine . [CODESPLIT] public DbServer detectDatabaseAndConfigureDbOom ( final ConnectionProvider cp , final DbOomConfig dbOomConfig ) { cp . init ( ) ; final Connection connection = cp . getConnection ( ) ; final DbServer dbServer = detectDatabase ( connection ) ; cp . closeConnection ( connection ) ; dbServer . accept ( dbOomConfig ) ; return dbServer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects database and returns { [CODESPLIT] public DbServer detectDatabase ( final Connection connection ) { final String dbName ; final int dbMajorVersion ; final String version ; try { log . info ( \"Detecting database...\" ) ; DatabaseMetaData databaseMetaData = connection . getMetaData ( ) ; dbName = databaseMetaData . getDatabaseProductName ( ) ; dbMajorVersion = databaseMetaData . getDatabaseMajorVersion ( ) ; final int dbMinorVersion = databaseMetaData . getDatabaseMinorVersion ( ) ; version = dbMajorVersion + \".\" + dbMinorVersion ; log . info ( \"Database: \" + dbName + \" v\" + dbMajorVersion + \".\" + dbMinorVersion ) ; } catch ( SQLException sex ) { String msg = sex . getMessage ( ) ; if ( msg . contains ( \"explicitly set for database: DB2\" ) ) { return new Db2DbServer ( ) ; } throw new DbSqlException ( sex ) ; } if ( dbName . equals ( \"Apache Derby\" ) ) { return new DerbyDbServer ( version ) ; } if ( dbName . startsWith ( \"DB2/\" ) ) { return new Db2DbServer ( version ) ; } if ( dbName . equals ( \"HSQL Database Engine\" ) ) { return new HsqlDbServer ( version ) ; } if ( dbName . equals ( \"Informix Dynamic Server\" ) ) { return new InformixDbServer ( version ) ; } if ( dbName . startsWith ( \"Microsoft SQL Server\" ) ) { return new SqlServerDbServer ( version ) ; } if ( dbName . equals ( \"MySQL\" ) ) { return new MySqlDbServer ( version ) ; } if ( dbName . equals ( \"Oracle\" ) ) { return new OracleDbServer ( version ) ; } if ( dbName . equals ( \"PostgreSQL\" ) ) { return new PostgreSqlDbServer ( version ) ; } if ( dbName . equals ( \"Sybase SQL Server\" ) ) { return new SybaseDbServer ( version ) ; } if ( dbName . equals ( \"ASE\" ) && ( dbMajorVersion == 15 ) ) { return new SybaseDbServer ( version ) ; } if ( dbName . equals ( \"SQLite\" ) ) { return new SQLiteDbServer ( version ) ; } return new GenericDbServer ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes this output stream causing any buffered data to be flushed and any further output data to throw an IOException . [CODESPLIT] @ Override public void close ( ) throws IOException { if ( closed ) { return ; } if ( gzipstream != null ) { flushToGZip ( ) ; gzipstream . close ( ) ; gzipstream = null ; } else { if ( bufferCount > 0 ) { output . write ( buffer , 0 , bufferCount ) ; bufferCount = 0 ; } } output . close ( ) ; closed = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the specified byte to our output stream . [CODESPLIT] @ Override public void write ( final int b ) throws IOException { if ( closed ) { throw new IOException ( \"Cannot write to a closed output stream\" ) ; } if ( bufferCount >= buffer . length ) { flushToGZip ( ) ; } buffer [ bufferCount ++ ] = ( byte ) b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes <code > len< / code > bytes from the specified byte array starting at the specified offset to our output stream . [CODESPLIT] @ Override public void write ( final byte [ ] b , final int off , final int len ) throws IOException { if ( closed ) { throw new IOException ( \"Cannot write to a closed output stream\" ) ; } if ( len == 0 ) { return ; } // Can we write into buffer ? if ( len <= ( buffer . length - bufferCount ) ) { System . arraycopy ( b , off , buffer , bufferCount , len ) ; bufferCount += len ; return ; } // There is not enough space in buffer. Flush it ... flushToGZip ( ) ; // ... and try again. Note, that bufferCount = 0 here ! if ( len <= ( buffer . length - bufferCount ) ) { System . arraycopy ( b , off , buffer , bufferCount , len ) ; bufferCount += len ; return ; } // write direct to gzip writeToGZip ( b , off , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes byte array to gzip output stream . Creates new <code > GZIPOutputStream< / code > if not created yet . Also sets the Content - Encoding header . [CODESPLIT] public void writeToGZip ( final byte [ ] b , final int off , final int len ) throws IOException { if ( gzipstream == null ) { gzipstream = new GZIPOutputStream ( output ) ; response . setHeader ( \"Content-Encoding\" , \"gzip\" ) ; } gzipstream . write ( b , off , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters requests to remove URL - based session identifiers . [CODESPLIT] @ Override public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws IOException , ServletException { HttpServletRequest httpRequest = ( HttpServletRequest ) request ; HttpServletResponse httpResponse = ( HttpServletResponse ) response ; if ( isRequestedSessionIdFromURL ( httpRequest ) ) { HttpSession session = httpRequest . getSession ( false ) ; if ( session != null ) { session . invalidate ( ) ; // clear session if session id in URL } } // wrap response to remove URL encoding HttpServletResponseWrapper wrappedResponse = new HttpServletResponseWrapper ( httpResponse ) { @ Override public String encodeRedirectUrl ( final String url ) { return url ; } @ Override public String encodeRedirectURL ( final String url ) { return url ; } @ Override public String encodeUrl ( final String url ) { return url ; } @ Override public String encodeURL ( final String url ) { return url ; } } ; chain . doFilter ( request , wrappedResponse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects if session ID exist in the URL . It works more reliable than <code > servletRequest . isRequestedSessionIdFromURL () < / code > . [CODESPLIT] protected boolean isRequestedSessionIdFromURL ( final HttpServletRequest servletRequest ) { if ( servletRequest . isRequestedSessionIdFromURL ( ) ) { return true ; } HttpSession session = servletRequest . getSession ( false ) ; if ( session != null ) { String sessionId = session . getId ( ) ; StringBuffer requestUri = servletRequest . getRequestURL ( ) ; return requestUri . indexOf ( sessionId ) != - 1 ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns encoded attachment name . [CODESPLIT] public String getEncodedName ( ) { if ( name == null ) { return null ; } try { return MimeUtility . encodeText ( name ) ; } catch ( final UnsupportedEncodingException ueex ) { throw new MailException ( ueex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns byte content of the attachment . [CODESPLIT] public byte [ ] toByteArray ( ) { final FastByteArrayOutputStream out ; if ( size != - 1 ) { out = new FastByteArrayOutputStream ( size ) ; } else { out = new FastByteArrayOutputStream ( ) ; } writeToStream ( out ) ; return out . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves attachment to a file . [CODESPLIT] public void writeToFile ( final File destination ) { InputStream input = null ; final OutputStream output ; try { input = getDataSource ( ) . getInputStream ( ) ; output = new FileOutputStream ( destination ) ; StreamUtil . copy ( input , output ) ; } catch ( final IOException ioex ) { throw new MailException ( ioex ) ; } finally { StreamUtil . close ( input ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves attachment to the output stream . [CODESPLIT] public void writeToStream ( final OutputStream out ) { InputStream input = null ; try { input = getDataSource ( ) . getInputStream ( ) ; StreamUtil . copy ( input , out ) ; } catch ( final IOException ioex ) { throw new MailException ( ioex ) ; } finally { StreamUtil . close ( input ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BigDecimal get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getBigDecimal ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final BigDecimal value , final int dbSqlType ) throws SQLException { st . setBigDecimal ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked on INVOKEVIRTUAL INVOKESPECIAL INVOKESTATIC INVOKEINTERFACE or INVOKEDYNAMIC . [CODESPLIT] @ Override public void visitMethodInsn ( final int opcode , String owner , String name , String desc , final boolean isInterface ) { // replace NEW.<init> if ( ( newInvokeReplacer != null ) && ( opcode == INVOKESPECIAL ) ) { String exOwner = owner ; owner = newInvokeReplacer . getOwner ( ) ; name = newInvokeReplacer . getMethodName ( ) ; desc = changeReturnType ( desc , ' ' + exOwner + ' ' ) ; super . visitMethodInsn ( INVOKESTATIC , owner , name , desc , isInterface ) ; newInvokeReplacer = null ; return ; } InvokeInfo invokeInfo = new InvokeInfo ( owner , name , desc ) ; // [*] // creating FooClone.<init>; inside the FOO constructor // replace the very first invokespecial <init> call (SUB.<init>) // to targets subclass with target (FOO.<init>). if ( methodInfo . getMethodName ( ) . equals ( INIT ) ) { if ( ( ! firstSuperCtorInitCalled ) && ( opcode == INVOKESPECIAL ) && name . equals ( INIT ) && owner . equals ( wd . nextSupername ) ) { firstSuperCtorInitCalled = true ; owner = wd . superReference ; super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; return ; } } // detection of super calls if ( ( opcode == INVOKESPECIAL ) && ( owner . equals ( wd . nextSupername ) && ( ! name . equals ( INIT ) ) ) ) { throw new ProxettaException ( \"Super call detected in class \" + methodInfo . getClassname ( ) + \" method: \" + methodInfo . getSignature ( ) + \"\\nProxetta can't handle super calls due to VM limitations.\" ) ; } InvokeReplacer ir = null ; // find first matching aspect for ( InvokeAspect aspect : aspects ) { ir = aspect . pointcut ( invokeInfo ) ; if ( ir != null ) { break ; } } if ( ir == null || ir . isNone ( ) ) { if ( ProxettaAsmUtil . isCreateArgumentsArrayMethod ( name , desc ) ) { ProxyTargetReplacement . createArgumentsArray ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( ProxettaAsmUtil . isCreateArgumentsClassArrayMethod ( name , desc ) ) { ProxyTargetReplacement . createArgumentsClassArray ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( ProxettaAsmUtil . isArgumentsCountMethod ( name , desc ) ) { ProxyTargetReplacement . argumentsCount ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( ProxettaAsmUtil . isTargetMethodNameMethod ( name , desc ) ) { ProxyTargetReplacement . targetMethodName ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( ProxettaAsmUtil . isTargetMethodDescriptionMethod ( name , desc ) ) { ProxyTargetReplacement . targetMethodDescription ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( ProxettaAsmUtil . isTargetMethodSignatureMethod ( name , desc ) ) { ProxyTargetReplacement . targetMethodSignature ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( ProxettaAsmUtil . isReturnTypeMethod ( name , desc ) ) { ProxyTargetReplacement . returnType ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( ProxettaAsmUtil . isTargetClassMethod ( name , desc ) ) { ProxyTargetReplacement . targetClass ( mv , methodInfo ) ; wd . proxyApplied = true ; return ; } if ( isArgumentTypeMethod ( name , desc ) ) { int argIndex = this . getArgumentIndex ( ) ; ProxyTargetReplacement . argumentType ( mv , methodInfo , argIndex ) ; wd . proxyApplied = true ; return ; } if ( isArgumentMethod ( name , desc ) ) { int argIndex = this . getArgumentIndex ( ) ; ProxyTargetReplacement . argument ( mv , methodInfo , argIndex ) ; wd . proxyApplied = true ; return ; } if ( isInfoMethod ( name , desc ) ) { proxyInfoRequested = true ; // we are NOT calling the replacement here, as we would expect. // NO, we need to wait for the very next ASTORE method so we // can read the index and use it for replacement method!!! //ProxyTargetReplacement.info(mv, methodInfo); wd . proxyApplied = true ; return ; } if ( isTargetMethodAnnotationMethod ( name , desc ) ) { String [ ] args = getLastTwoStringArguments ( ) ; // pop current two args mv . visitInsn ( POP ) ; mv . visitInsn ( POP ) ; ProxyTargetReplacement . targetMethodAnnotation ( mv , methodInfo , args ) ; wd . proxyApplied = true ; return ; } if ( isTargetClassAnnotationMethod ( name , desc ) ) { String [ ] args = getLastTwoStringArguments ( ) ; // pop current two args mv . visitInsn ( POP ) ; mv . visitInsn ( POP ) ; ProxyTargetReplacement . targetClassAnnotation ( mv , methodInfo . getClassInfo ( ) , args ) ; wd . proxyApplied = true ; return ; } super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; return ; } wd . proxyApplied = true ; String exOwner = owner ; owner = ir . getOwner ( ) ; name = ir . getMethodName ( ) ; switch ( opcode ) { case INVOKEINTERFACE : desc = prependArgument ( desc , AsmUtil . L_SIGNATURE_JAVA_LANG_OBJECT ) ; break ; case INVOKEVIRTUAL : desc = prependArgument ( desc , AsmUtil . L_SIGNATURE_JAVA_LANG_OBJECT ) ; break ; case INVOKESTATIC : break ; default : throw new ProxettaException ( \"Unsupported opcode: \" + opcode ) ; } // additional arguments if ( ir . isPassOwnerName ( ) ) { desc = appendArgument ( desc , AsmUtil . L_SIGNATURE_JAVA_LANG_STRING ) ; super . visitLdcInsn ( exOwner ) ; } if ( ir . isPassMethodName ( ) ) { desc = appendArgument ( desc , AsmUtil . L_SIGNATURE_JAVA_LANG_STRING ) ; super . visitLdcInsn ( methodInfo . getMethodName ( ) ) ; } if ( ir . isPassMethodSignature ( ) ) { desc = appendArgument ( desc , AsmUtil . L_SIGNATURE_JAVA_LANG_STRING ) ; super . visitLdcInsn ( methodInfo . getSignature ( ) ) ; } if ( ir . isPassTargetClass ( ) ) { desc = appendArgument ( desc , AsmUtil . L_SIGNATURE_JAVA_LANG_CLASS ) ; super . mv . visitLdcInsn ( Type . getType ( ' ' + wd . superReference + ' ' ) ) ; } if ( ir . isPassThis ( ) ) { desc = appendArgument ( desc , AsmUtil . L_SIGNATURE_JAVA_LANG_OBJECT ) ; super . mv . visitVarInsn ( ALOAD , 0 ) ; } super . visitMethodInsn ( INVOKESTATIC , owner , name , desc , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends argument to the existing description . [CODESPLIT] protected static String appendArgument ( final String desc , final String type ) { int ndx = desc . indexOf ( ' ' ) ; return desc . substring ( 0 , ndx ) + type + desc . substring ( ndx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepends argument to the existing description . [CODESPLIT] protected static String prependArgument ( final String desc , final String type ) { int ndx = desc . indexOf ( ' ' ) ; ndx ++ ; return desc . substring ( 0 , ndx ) + type + desc . substring ( ndx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes return type . [CODESPLIT] protected static String changeReturnType ( final String desc , final String type ) { int ndx = desc . indexOf ( ' ' ) ; return desc . substring ( 0 , ndx + 1 ) + type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans unnecessary whitespaces . [CODESPLIT] @ Override public void text ( final CharSequence text ) { if ( ! strip ) { super . text ( text ) ; return ; } int textLength = text . length ( ) ; char [ ] dest = new char [ textLength ] ; int ndx = 0 ; boolean regularChar = true ; for ( int i = 0 ; i < textLength ; i ++ ) { char c = text . charAt ( i ) ; if ( CharUtil . isWhitespace ( c ) ) { if ( regularChar ) { regularChar = false ; c = ' ' ; } else { continue ; } } else { regularChar = true ; } dest [ ndx ] = c ; ndx ++ ; } if ( regularChar || ( ndx != 1 ) ) { super . text ( CharBuffer . wrap ( dest , 0 , ndx ) ) ; strippedCharsCount += textLength - ndx ; } else { strippedCharsCount += textLength ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers default set of converters . [CODESPLIT] public void registerDefaults ( ) { register ( String . class , new StringConverter ( ) ) ; register ( String [ ] . class , new StringArrayConverter ( this ) ) ; IntegerConverter integerConverter = new IntegerConverter ( ) ; register ( Integer . class , integerConverter ) ; register ( int . class , integerConverter ) ; register ( MutableInteger . class , new MutableIntegerConverter ( this ) ) ; ShortConverter shortConverter = new ShortConverter ( ) ; register ( Short . class , shortConverter ) ; register ( short . class , shortConverter ) ; register ( MutableShort . class , new MutableShortConverter ( this ) ) ; LongConverter longConverter = new LongConverter ( ) ; register ( Long . class , longConverter ) ; register ( long . class , longConverter ) ; register ( MutableLong . class , new MutableLongConverter ( this ) ) ; ByteConverter byteConverter = new ByteConverter ( ) ; register ( Byte . class , byteConverter ) ; register ( byte . class , byteConverter ) ; register ( MutableByte . class , new MutableByteConverter ( this ) ) ; FloatConverter floatConverter = new FloatConverter ( ) ; register ( Float . class , floatConverter ) ; register ( float . class , floatConverter ) ; register ( MutableFloat . class , new MutableFloatConverter ( this ) ) ; DoubleConverter doubleConverter = new DoubleConverter ( ) ; register ( Double . class , doubleConverter ) ; register ( double . class , doubleConverter ) ; register ( MutableDouble . class , new MutableDoubleConverter ( this ) ) ; BooleanConverter booleanConverter = new BooleanConverter ( ) ; register ( Boolean . class , booleanConverter ) ; register ( boolean . class , booleanConverter ) ; CharacterConverter characterConverter = new CharacterConverter ( ) ; register ( Character . class , characterConverter ) ; register ( char . class , characterConverter ) ; register ( byte [ ] . class , new ByteArrayConverter ( this ) ) ; register ( short [ ] . class , new ShortArrayConverter ( this ) ) ; register ( int [ ] . class , new IntegerArrayConverter ( this ) ) ; register ( long [ ] . class , new LongArrayConverter ( this ) ) ; register ( float [ ] . class , new FloatArrayConverter ( this ) ) ; register ( double [ ] . class , new DoubleArrayConverter ( this ) ) ; register ( boolean [ ] . class , new BooleanArrayConverter ( this ) ) ; register ( char [ ] . class , new CharacterArrayConverter ( this ) ) ; // we don't really need these, but converters will be cached and not created every time register ( Integer [ ] . class , new ArrayConverter < Integer > ( this , Integer . class ) { @ Override protected Integer [ ] createArray ( final int length ) { return new Integer [ length ] ; } } ) ; register ( Long [ ] . class , new ArrayConverter < Long > ( this , Long . class ) { @ Override protected Long [ ] createArray ( final int length ) { return new Long [ length ] ; } } ) ; register ( Byte [ ] . class , new ArrayConverter < Byte > ( this , Byte . class ) { @ Override protected Byte [ ] createArray ( final int length ) { return new Byte [ length ] ; } } ) ; register ( Short [ ] . class , new ArrayConverter < Short > ( this , Short . class ) { @ Override protected Short [ ] createArray ( final int length ) { return new Short [ length ] ; } } ) ; register ( Float [ ] . class , new ArrayConverter < Float > ( this , Float . class ) { @ Override protected Float [ ] createArray ( final int length ) { return new Float [ length ] ; } } ) ; register ( Double [ ] . class , new ArrayConverter < Double > ( this , Double . class ) { @ Override protected Double [ ] createArray ( final int length ) { return new Double [ length ] ; } } ) ; register ( Boolean [ ] . class , new ArrayConverter < Boolean > ( this , Boolean . class ) { @ Override protected Boolean [ ] createArray ( final int length ) { return new Boolean [ length ] ; } } ) ; register ( Character [ ] . class , new ArrayConverter < Character > ( this , Character . class ) { @ Override protected Character [ ] createArray ( final int length ) { return new Character [ length ] ; } } ) ; register ( MutableInteger [ ] . class , new ArrayConverter <> ( this , MutableInteger . class ) ) ; register ( MutableLong [ ] . class , new ArrayConverter <> ( this , MutableLong . class ) ) ; register ( MutableByte [ ] . class , new ArrayConverter <> ( this , MutableByte . class ) ) ; register ( MutableShort [ ] . class , new ArrayConverter <> ( this , MutableShort . class ) ) ; register ( MutableFloat [ ] . class , new ArrayConverter <> ( this , MutableFloat . class ) ) ; register ( MutableDouble [ ] . class , new ArrayConverter <> ( this , MutableDouble . class ) ) ; register ( BigDecimal . class , new BigDecimalConverter ( ) ) ; register ( BigInteger . class , new BigIntegerConverter ( ) ) ; register ( BigDecimal [ ] . class , new ArrayConverter <> ( this , BigDecimal . class ) ) ; register ( BigInteger [ ] . class , new ArrayConverter <> ( this , BigInteger . class ) ) ; register ( java . util . Date . class , new DateConverter ( ) ) ; register ( java . sql . Date . class , new SqlDateConverter ( ) ) ; register ( Time . class , new SqlTimeConverter ( ) ) ; register ( Timestamp . class , new SqlTimestampConverter ( ) ) ; register ( Calendar . class , new CalendarConverter ( ) ) ; //\t\tregister(GregorianCalendar.class, new CalendarConverter()); register ( LocalDateTime . class , new LocalDateTimeConverter ( ) ) ; register ( LocalDate . class , new LocalDateConverter ( ) ) ; register ( LocalTime . class , new LocalTimeConverter ( ) ) ; register ( File . class , new FileConverter ( ) ) ; register ( FileUpload . class , new FileUploadConverter ( ) ) ; register ( Class . class , new ClassConverter ( ) ) ; register ( Class [ ] . class , new ClassArrayConverter ( this ) ) ; register ( URI . class , new URIConverter ( ) ) ; register ( URL . class , new URLConverter ( ) ) ; register ( Locale . class , new LocaleConverter ( ) ) ; register ( TimeZone . class , new TimeZoneConverter ( ) ) ; register ( UUID . class , new UUIDConverter ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a converter for specified type . User must register converter for all super - classes as well . [CODESPLIT] public < T > void register ( final Class < T > type , final TypeConverter < T > typeConverter ) { converters . put ( type , typeConverter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves converter for provided type . Only registered types are matched therefore subclasses must be also registered . [CODESPLIT] public < T > TypeConverter < T > lookup ( final Class < T > type ) { return converters . get ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an object to destination type . If type is registered it s { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public < T > T convertType ( final Object value , final Class < T > destinationType ) { if ( destinationType == Object . class ) { // no conversion :) return ( T ) value ; } final TypeConverter converter = lookup ( destinationType ) ; if ( converter != null ) { return ( T ) converter . convert ( value ) ; } // no converter if ( value == null ) { return null ; } // check same instances if ( ClassUtil . isInstanceOf ( value , destinationType ) ) { return ( T ) value ; } // handle destination arrays if ( destinationType . isArray ( ) ) { ArrayConverter < T > arrayConverter = new ArrayConverter ( this , destinationType . getComponentType ( ) ) ; return ( T ) arrayConverter . convert ( value ) ; } // handle enums if ( destinationType . isEnum ( ) ) { Object [ ] enums = destinationType . getEnumConstants ( ) ; String valStr = value . toString ( ) ; for ( Object e : enums ) { if ( e . toString ( ) . equals ( valStr ) ) { return ( T ) e ; } } } // collection if ( ClassUtil . isTypeOf ( destinationType , Collection . class ) ) { // component type is unknown because of Java's type-erasure CollectionConverter < T > collectionConverter = new CollectionConverter ( this , destinationType , Object . class ) ; return ( T ) collectionConverter . convert ( value ) ; } // fail throw new TypeConversionException ( \"Conversion failed of input type: \" + value . getClass ( ) + \" into: \" + destinationType . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special case of { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < C extends Collection < T > , T > C convertToCollection ( final Object value , final Class < ? extends Collection > destinationType , final Class < T > componentType ) { if ( value == null ) { return null ; } // check same instances if ( ClassUtil . isInstanceOf ( value , destinationType ) ) { return ( C ) value ; } final CollectionConverter collectionConverter ; if ( componentType == null ) { collectionConverter = new CollectionConverter ( destinationType , Object . class ) ; } else { collectionConverter = new CollectionConverter ( destinationType , componentType ) ; } return ( C ) collectionConverter . convert ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects nodes using CSS3 selector query . [CODESPLIT] public List < Node > select ( final String query ) { Collection < List < CssSelector >> selectorsCollection = CSSelly . parse ( query ) ; return select ( selectorsCollection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selected nodes using pre - parsed CSS selectors . Take in consideration collection type for results grouping order . [CODESPLIT] public List < Node > select ( final Collection < List < CssSelector > > selectorsCollection ) { List < Node > results = new ArrayList <> ( ) ; for ( List < CssSelector > selectors : selectorsCollection ) { processSelectors ( results , selectors ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process selectors and keep adding results . [CODESPLIT] protected void processSelectors ( final List < Node > results , final List < CssSelector > selectors ) { List < Node > selectedNodes = select ( rootNode , selectors ) ; for ( Node selectedNode : selectedNodes ) { if ( ! results . contains ( selectedNode ) ) { results . add ( selectedNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects nodes using CSS3 selector query and returns the very first one . [CODESPLIT] public Node selectFirst ( final String query ) { List < Node > selectedNodes = select ( query ) ; if ( selectedNodes . isEmpty ( ) ) { return null ; } return selectedNodes . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects nodes using { [CODESPLIT] public List < Node > select ( final NodeFilter nodeFilter ) { List < Node > nodes = new ArrayList <> ( ) ; walk ( rootNode , nodeFilter , nodes ) ; return nodes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects nodes using { [CODESPLIT] public Node selectFirst ( final NodeFilter nodeFilter ) { List < Node > selectedNodes = select ( nodeFilter ) ; if ( selectedNodes . isEmpty ( ) ) { return null ; } return selectedNodes . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- internal [CODESPLIT] protected void walk ( final Node rootNode , final NodeFilter nodeFilter , final List < Node > result ) { int childCount = rootNode . getChildNodesCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { Node node = rootNode . getChild ( i ) ; if ( nodeFilter . accept ( node ) ) { result . add ( node ) ; } walk ( node , nodeFilter , result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walks over the child notes maintaining the tree order and not using recursion . [CODESPLIT] protected void walkDescendantsIteratively ( final LinkedList < Node > nodes , final CssSelector cssSelector , final List < Node > result ) { while ( ! nodes . isEmpty ( ) ) { Node node = nodes . removeFirst ( ) ; selectAndAdd ( node , cssSelector , result ) ; // append children in walking order to be processed right after this node int childCount = node . getChildNodesCount ( ) ; for ( int i = childCount - 1 ; i >= 0 ; i -- ) { nodes . addFirst ( node . getChild ( i ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds nodes in the tree that matches single selector . [CODESPLIT] protected void walk ( final Node rootNode , final CssSelector cssSelector , final List < Node > result ) { // previous combinator determines the behavior CssSelector previousCssSelector = cssSelector . getPrevCssSelector ( ) ; Combinator combinator = previousCssSelector != null ? previousCssSelector . getCombinator ( ) : Combinator . DESCENDANT ; switch ( combinator ) { case DESCENDANT : LinkedList < Node > nodes = new LinkedList <> ( ) ; int childCount = rootNode . getChildNodesCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { nodes . add ( rootNode . getChild ( i ) ) ; // recursive //\t\t\t\t\tselectAndAdd(node, cssSelector, result); //\t\t\t\t\twalk(node, cssSelector, result); } walkDescendantsIteratively ( nodes , cssSelector , result ) ; break ; case CHILD : childCount = rootNode . getChildNodesCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { Node node = rootNode . getChild ( i ) ; selectAndAdd ( node , cssSelector , result ) ; } break ; case ADJACENT_SIBLING : Node node = rootNode . getNextSiblingElement ( ) ; if ( node != null ) { selectAndAdd ( node , cssSelector , result ) ; } break ; case GENERAL_SIBLING : node = rootNode ; while ( true ) { node = node . getNextSiblingElement ( ) ; if ( node == null ) { break ; } selectAndAdd ( node , cssSelector , result ) ; } break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects single node for single selector and appends it to the results . [CODESPLIT] protected void selectAndAdd ( final Node node , final CssSelector cssSelector , final List < Node > result ) { // ignore all nodes that are not elements if ( node . getNodeType ( ) != Node . NodeType . ELEMENT ) { return ; } boolean matched = cssSelector . accept ( node ) ; if ( matched ) { // check for duplicates if ( result . contains ( node ) ) { return ; } // no duplicate found, add it to the results result . add ( node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter nodes . [CODESPLIT] protected boolean filter ( final List < Node > currentResults , final Node node , final CssSelector cssSelector , final int index ) { return cssSelector . accept ( currentResults , node , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpacks the compressed character translation table . [CODESPLIT] private static char [ ] zzUnpackCMap ( final String packed ) { char [ ] map = new char [ 0x110000 ] ; int i = 0 ; /* index in packed string  */ int j = 0 ; /* index in unpacked array */ while ( i < 128 ) { int count = packed . charAt ( i ++ ) ; char value = packed . charAt ( i ++ ) ; do map [ j ++ ] = value ; while ( -- count > 0 ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refills the input buffer . [CODESPLIT] private boolean zzRefill ( ) { if ( zzBuffer == null ) { zzBuffer = zzChars ; zzEndRead += zzChars . length ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resumes scanning until the next regular expression is matched the end of input is encountered or an I / O - Error occurs . [CODESPLIT] public int yylex ( ) throws java . io . IOException { int zzInput ; int zzAction ; // cached fields: int zzCurrentPosL ; int zzMarkedPosL ; int zzEndReadL = zzEndRead ; char [ ] zzBufferL = zzBuffer ; char [ ] zzCMapL = ZZ_CMAP ; int [ ] zzTransL = ZZ_TRANS ; int [ ] zzRowMapL = ZZ_ROWMAP ; int [ ] zzAttrL = ZZ_ATTRIBUTE ; while ( true ) { zzMarkedPosL = zzMarkedPos ; yychar += zzMarkedPosL - zzStartRead ; zzAction = - 1 ; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL ; zzState = ZZ_LEXSTATE [ zzLexicalState ] ; // set up zzAction for empty match case: int zzAttributes = zzAttrL [ zzState ] ; if ( ( zzAttributes & 1 ) == 1 ) { zzAction = zzState ; } zzForAction : { while ( true ) { if ( zzCurrentPosL < zzEndReadL ) { zzInput = Character . codePointAt ( zzBufferL , zzCurrentPosL , zzEndReadL ) ; zzCurrentPosL += Character . charCount ( zzInput ) ; } else if ( zzAtEOF ) { zzInput = YYEOF ; break zzForAction ; } else { // store back cached positions zzCurrentPos = zzCurrentPosL ; zzMarkedPos = zzMarkedPosL ; boolean eof = zzRefill ( ) ; // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos ; zzMarkedPosL = zzMarkedPos ; zzBufferL = zzBuffer ; zzEndReadL = zzEndRead ; if ( eof ) { zzInput = YYEOF ; break zzForAction ; } else { zzInput = Character . codePointAt ( zzBufferL , zzCurrentPosL , zzEndReadL ) ; zzCurrentPosL += Character . charCount ( zzInput ) ; } } int zzNext = zzTransL [ zzRowMapL [ zzState ] + zzCMapL [ zzInput ] ] ; if ( zzNext == - 1 ) break zzForAction ; zzState = zzNext ; zzAttributes = zzAttrL [ zzState ] ; if ( ( zzAttributes & 1 ) == 1 ) { zzAction = zzState ; zzMarkedPosL = zzCurrentPosL ; if ( ( zzAttributes & 8 ) == 8 ) break zzForAction ; } } } // store back cached position zzMarkedPos = zzMarkedPosL ; if ( zzInput == YYEOF && zzStartRead == zzCurrentPos ) { zzAtEOF = true ; zzDoEOF ( ) ; { return 0 ; } } else { switch ( zzAction < 0 ? zzAction : ZZ_ACTION [ zzAction ] ) { case 1 : { cssSelector . setCombinator ( Combinator . DESCENDANT ) ; stateReset ( ) ; } case 20 : break ; case 2 : { cssSelector = new CssSelector ( yytext ( ) ) ; selectors . add ( cssSelector ) ; stateSelector ( ) ; } case 21 : break ; case 3 : { cssSelector = new CssSelector ( ) ; selectors . add ( cssSelector ) ; yypushback ( 1 ) ; stateSelector ( ) ; } case 22 : break ; case 4 : { /* ignore whitespaces */ } case 23 : break ; case 5 : { cssSelector = new CssSelector ( ) ; selectors . add ( cssSelector ) ; stateSelector ( ) ; } case 24 : break ; case 6 : { throw new CSSellyException ( \"Illegal character <\" + yytext ( ) + \">.\" , yystate ( ) , line ( ) , column ( ) ) ; } case 25 : break ; case 7 : { yypushback ( 1 ) ; stateCombinator ( ) ; } case 26 : break ; case 8 : { stateAttr ( ) ; } case 27 : break ; case 9 : { cssSelector . addAttributeSelector ( yytext ( ) ) ; } case 28 : break ; case 10 : { stateSelector ( ) ; } case 29 : break ; case 11 : { throw new CSSellyException ( \"Invalid combinator <\" + yytext ( ) + \">.\" , yystate ( ) , line ( ) , column ( ) ) ; } case 30 : break ; case 12 : { cssSelector . setCombinator ( Combinator . GENERAL_SIBLING ) ; stateReset ( ) ; } case 31 : break ; case 13 : { cssSelector . setCombinator ( Combinator . CHILD ) ; stateReset ( ) ; } case 32 : break ; case 14 : { cssSelector . setCombinator ( Combinator . ADJACENT_SIBLING ) ; stateReset ( ) ; } case 33 : break ; case 15 : { cssSelector . addPseudoFunctionSelector ( pseudoFnName , yytext ( 0 , 1 ) ) ; stateSelector ( ) ; } case 34 : break ; case 16 : { cssSelector . addClassSelector ( yytext ( 1 ) ) ; } case 35 : break ; case 17 : { cssSelector . addIdSelector ( yytext ( 1 ) ) ; } case 36 : break ; case 18 : { cssSelector . addPseudoClassSelector ( yytext ( yycharat ( 1 ) == ' ' ? 2 : 1 ) ) ; } case 37 : break ; case 19 : { pseudoFnName = yytext ( yycharat ( 1 ) == ' ' ? 2 : 1 , 1 ) ; statePseudoFn ( ) ; } case 38 : break ; default : zzScanError ( ZZ_NO_MATCH ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the pagination with given { @link jodd . joy . page . PageRequest } . [CODESPLIT] public < T > PageData < T > page ( PageRequest pageRequest , final String sql , final Map params , final String [ ] sortColumns , final Class [ ] target ) { if ( pageRequest == null ) { pageRequest = getDefaultPageRequest ( ) ; } // check sort String sortColumName = null ; boolean ascending = true ; int sort = pageRequest . getSort ( ) ; if ( sort != 0 ) { ascending = sort > 0 ; if ( ! ascending ) { sort = - sort ; } int index = sort - 1 ; if ( index >= sortColumns . length ) { index = 1 ; } sortColumName = sortColumns [ index ] ; } // page int page = pageRequest . getPage ( ) ; int pageSize = pageRequest . getSize ( ) ; PageData < T > pageData = page ( sql , params , page , pageSize , sortColumName , ascending , target ) ; // fix the out-of-bounds if ( pageData . getItems ( ) . isEmpty ( ) && pageData . currentPage != 0 ) { if ( pageData . currentPage != page ) { // out of bounds int newPage = pageData . getCurrentPage ( ) ; pageData = page ( sql , params , newPage , pageSize , sortColumName , ascending , target ) ; } } return pageData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pages given page . [CODESPLIT] protected < T > PageData < T > page ( String sql , final Map params , final int page , final int pageSize , final String sortColumnName , final boolean ascending , final Class [ ] target ) { if ( sortColumnName != null ) { sql = buildOrderSql ( sql , sortColumnName , ascending ) ; } int from = ( page - 1 ) * pageSize ; String pageSql = buildPageSql ( sql , from , pageSize ) ; DbSqlBuilder dbsql = sql ( pageSql ) ; DbOomQuery query = query ( dbsql ) ; query . setMaxRows ( pageSize ) ; query . setFetchSize ( pageSize ) ; query . setMap ( params ) ; List < T > list = query . list ( pageSize , target ) ; query . close ( ) ; String countSql = buildCountSql ( sql ) ; dbsql = sql ( countSql ) ; query = query ( dbsql ) ; query . setMap ( params ) ; long count = query . executeCount ( ) ; query . close ( ) ; return new PageData <> ( page , ( int ) count , pageSize , list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the first select from the sql query . [CODESPLIT] protected String removeSelect ( String sql ) { int ndx = StringUtil . indexOfIgnoreCase ( sql , \"select\" ) ; if ( ndx != - 1 ) { sql = sql . substring ( ndx + 6 ) ; // select.length() } return sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the first part of the sql up to the relevant from . Tries to detect sub - queries in the select part . [CODESPLIT] protected String removeToFrom ( String sql ) { int from = 0 ; int fromCount = 1 ; int selectCount = 0 ; int lastNdx = 0 ; while ( true ) { int ndx = StringUtil . indexOfIgnoreCase ( sql , \"from\" , from ) ; if ( ndx == - 1 ) { break ; } // count selects in left part String left = sql . substring ( lastNdx , ndx ) ; selectCount += StringUtil . countIgnoreCase ( left , \"select\" ) ; if ( fromCount >= selectCount ) { sql = sql . substring ( ndx ) ; break ; } // find next 'from' lastNdx = ndx ; from = ndx + 4 ; fromCount ++ ; } return sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes everything from last order by . [CODESPLIT] protected String removeLastOrderBy ( String sql ) { int ndx = StringUtil . lastIndexOfIgnoreCase ( sql , \"order by\" ) ; if ( ndx != - 1 ) { int ndx2 = sql . lastIndexOf ( sql , ' ' ) ; if ( ndx > ndx2 ) { sql = sql . substring ( 0 , ndx ) ; } } return sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes HTML text . Assumes that all character references are properly closed with semi - colon . [CODESPLIT] public static String decode ( final String html ) { int ndx = html . indexOf ( ' ' ) ; if ( ndx == - 1 ) { return html ; } StringBuilder result = new StringBuilder ( html . length ( ) ) ; int lastIndex = 0 ; int len = html . length ( ) ; mainloop : while ( ndx != - 1 ) { result . append ( html . substring ( lastIndex , ndx ) ) ; lastIndex = ndx ; while ( html . charAt ( lastIndex ) != ' ' ) { lastIndex ++ ; if ( lastIndex == len ) { lastIndex = ndx ; break mainloop ; } } if ( html . charAt ( ndx + 1 ) == ' ' ) { // decimal/hex char c = html . charAt ( ndx + 2 ) ; int radix ; if ( ( c == ' ' ) || ( c == ' ' ) ) { radix = 16 ; ndx += 3 ; } else { radix = 10 ; ndx += 2 ; } String number = html . substring ( ndx , lastIndex ) ; int i = Integer . parseInt ( number , radix ) ; result . append ( ( char ) i ) ; lastIndex ++ ; } else { // token String encodeToken = html . substring ( ndx + 1 , lastIndex ) ; char [ ] replacement = ENTITY_MAP . get ( encodeToken ) ; if ( replacement == null ) { result . append ( ' ' ) ; lastIndex = ndx + 1 ; } else { result . append ( replacement ) ; lastIndex ++ ; } } ndx = html . indexOf ( ' ' , lastIndex ) ; } result . append ( html . substring ( lastIndex ) ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects the longest character reference name on given position in char array . [CODESPLIT] public static String detectName ( final char [ ] input , int ndx ) { final Ptr ptr = new Ptr ( ) ; int firstIndex = 0 ; int lastIndex = ENTITY_NAMES . length - 1 ; int len = input . length ; char [ ] lastName = null ; final BinarySearchBase binarySearch = new BinarySearchBase ( ) { @ Override protected int compare ( final int index ) { char [ ] name = ENTITY_NAMES [ index ] ; if ( ptr . offset >= name . length ) { return - 1 ; } return name [ ptr . offset ] - ptr . c ; } } ; while ( true ) { ptr . c = input [ ndx ] ; if ( ! CharUtil . isAlphaOrDigit ( ptr . c ) ) { return lastName != null ? new String ( lastName ) : null ; } firstIndex = binarySearch . findFirst ( firstIndex , lastIndex ) ; if ( firstIndex < 0 ) { return lastName != null ? new String ( lastName ) : null ; } char [ ] element = ENTITY_NAMES [ firstIndex ] ; if ( element . length == ptr . offset + 1 ) { // total match, remember position, continue for finding the longer name lastName = ENTITY_NAMES [ firstIndex ] ; } lastIndex = binarySearch . findLast ( firstIndex , lastIndex ) ; if ( firstIndex == lastIndex ) { // only one element found, check the rest for ( int i = ptr . offset ; i < element . length ; i ++ ) { if ( element [ i ] != input [ ndx ] ) { return lastName != null ? new String ( lastName ) : null ; } ndx ++ ; } return new String ( element ) ; } ptr . offset ++ ; ndx ++ ; if ( ndx == len ) { return lastName != null ? new String ( lastName ) : null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- define [CODESPLIT] @ Override protected void defineParameter ( final StringBuilder query , final String name , final Object value , DbEntityColumnDescriptor dec ) { if ( dec == null ) { dec = templateData . lastColumnDec ; } super . defineParameter ( query , name , value , dec ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends ORDER BY keyword . [CODESPLIT] @ Override protected String buildOrderSql ( String sql , final String column , final boolean ascending ) { sql += \" order by \" + column ; if ( ! ascending ) { sql += \" desc\" ; } return sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds page sql using LIMIT keyword after the SELECT . [CODESPLIT] @ Override protected String buildPageSql ( String sql , final int from , final int pageSize ) { sql = removeSelect ( sql ) ; return \"select LIMIT \" + from + ' ' + pageSize + sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds count sql using COUNT ( * ) . [CODESPLIT] @ Override protected String buildCountSql ( String sql ) { sql = removeToFrom ( sql ) ; sql = removeLastOrderBy ( sql ) ; return \"select count(*) \" + sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves list of all columns and properties . [CODESPLIT] private void resolveColumnsAndProperties ( final Class type ) { PropertyDescriptor [ ] allProperties = ClassIntrospector . get ( ) . lookup ( type ) . getAllPropertyDescriptors ( ) ; List < DbEntityColumnDescriptor > decList = new ArrayList <> ( allProperties . length ) ; int idcount = 0 ; HashSet < String > names = new HashSet <> ( allProperties . length ) ; for ( PropertyDescriptor propertyDescriptor : allProperties ) { DbEntityColumnDescriptor dec = DbMetaUtil . resolveColumnDescriptors ( this , propertyDescriptor , isAnnotated , columnNamingStrategy ) ; if ( dec != null ) { if ( ! names . add ( dec . getColumnName ( ) ) ) { throw new DbOomException ( \"Duplicate column name: \" + dec . getColumnName ( ) ) ; } decList . add ( dec ) ; if ( dec . isId ) { idcount ++ ; } } } if ( decList . isEmpty ( ) ) { throw new DbOomException ( \"No column mappings in entity: \" + type ) ; } columnDescriptors = decList . toArray ( new DbEntityColumnDescriptor [ 0 ] ) ; Arrays . sort ( columnDescriptors ) ; // extract ids from sorted list if ( idcount > 0 ) { idColumnDescriptors = new DbEntityColumnDescriptor [ idcount ] ; idcount = 0 ; for ( DbEntityColumnDescriptor dec : columnDescriptors ) { if ( dec . isId ) { idColumnDescriptors [ idcount ++ ] = dec ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds column descriptor by column name . Case is ignored . [CODESPLIT] public DbEntityColumnDescriptor findByColumnName ( final String columnName ) { if ( columnName == null ) { return null ; } init ( ) ; for ( DbEntityColumnDescriptor columnDescriptor : columnDescriptors ) { if ( columnDescriptor . columnName . equalsIgnoreCase ( columnName ) ) { return columnDescriptor ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds column descriptor by property name . [CODESPLIT] public DbEntityColumnDescriptor findByPropertyName ( final String propertyName ) { if ( propertyName == null ) { return null ; } init ( ) ; for ( DbEntityColumnDescriptor columnDescriptor : columnDescriptors ) { if ( columnDescriptor . propertyName . equals ( propertyName ) ) { return columnDescriptor ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns property name for specified column name . [CODESPLIT] public String getPropertyName ( final String columnName ) { DbEntityColumnDescriptor dec = findByColumnName ( columnName ) ; return dec == null ? null : dec . propertyName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns column name for specified property name .. [CODESPLIT] public String getColumnName ( final String propertyName ) { DbEntityColumnDescriptor dec = findByPropertyName ( propertyName ) ; return dec == null ? null : dec . columnName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns ID value for given entity instance . [CODESPLIT] public Object getIdValue ( final E object ) { final String propertyName = getIdPropertyName ( ) ; return BeanUtil . declared . getProperty ( object , propertyName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets ID value for given entity . [CODESPLIT] public void setIdValue ( final E object , final Object value ) { final String propertyName = getIdPropertyName ( ) ; BeanUtil . declared . setProperty ( object , propertyName , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns unique key for this entity . Returned key is built from entity class and id value . [CODESPLIT] public String getKeyValue ( final E object ) { Object idValue = getIdValue ( object ) ; String idValueString = idValue == null ? StringPool . NULL : idValue . toString ( ) ; return type . getName ( ) . concat ( StringPool . COLON ) . concat ( idValueString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends a string . [CODESPLIT] public StringBand append ( String s ) { if ( s == null ) { s = StringPool . NULL ; } if ( index >= array . length ) { expandCapacity ( ) ; } array [ index ++ ] = s ; length += s . length ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the new index . [CODESPLIT] public void setIndex ( final int newIndex ) { if ( newIndex < 0 ) { throw new ArrayIndexOutOfBoundsException ( newIndex ) ; } if ( newIndex > array . length ) { String [ ] newArray = new String [ newIndex ] ; System . arraycopy ( array , 0 , newArray , 0 , index ) ; array = newArray ; } if ( newIndex > index ) { for ( int i = index ; i < newIndex ; i ++ ) { array [ i ] = StringPool . EMPTY ; } } else if ( newIndex < index ) { for ( int i = newIndex ; i < index ; i ++ ) { array [ i ] = null ; } } index = newIndex ; length = calculateLength ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns char at given position . This method is <b > not< / b > fast as it calculates the right string array element and the offset! [CODESPLIT] public char charAt ( final int pos ) { int len = 0 ; for ( int i = 0 ; i < index ; i ++ ) { int newlen = len + array [ i ] . length ( ) ; if ( pos < newlen ) { return array [ i ] . charAt ( pos - len ) ; } len = newlen ; } throw new IllegalArgumentException ( \"Invalid char index\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands internal string array by multiplying its size by 2 . [CODESPLIT] protected void expandCapacity ( ) { String [ ] newArray = new String [ array . length << 1 ] ; System . arraycopy ( array , 0 , newArray , 0 , index ) ; array = newArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates string length . [CODESPLIT] protected int calculateLength ( ) { int len = 0 ; for ( int i = 0 ; i < index ; i ++ ) { len += array [ i ] . length ( ) ; } return len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns scoped proxy bean if injection scopes are mixed on some injection point . May return <code > null< / code > if mixing scopes is not detected . [CODESPLIT] public Object lookupValue ( final PetiteContainer petiteContainer , final BeanDefinition targetBeanDefinition , final BeanDefinition refBeanDefinition ) { Scope targetScope = targetBeanDefinition . scope ; Scope refBeanScope = refBeanDefinition . scope ; boolean detectMixedScopes = petiteContainer . config ( ) . isDetectMixedScopes ( ) ; boolean wireScopedProxy = petiteContainer . config ( ) . isWireScopedProxy ( ) ; // when target scope is null then all beans can be injected into it // similar to prototype scope if ( targetScope != null && ! targetScope . accept ( refBeanScope ) ) { if ( ! wireScopedProxy ) { if ( detectMixedScopes ) { throw new PetiteException ( createMixingMessage ( targetBeanDefinition , refBeanDefinition ) ) ; } return null ; } if ( detectMixedScopes ) { if ( log . isWarnEnabled ( ) ) { log . warn ( createMixingMessage ( targetBeanDefinition , refBeanDefinition ) ) ; } } else { if ( log . isDebugEnabled ( ) ) { log . debug ( createMixingMessage ( targetBeanDefinition , refBeanDefinition ) ) ; } } String scopedProxyBeanName = refBeanDefinition . name ; Object proxy = proxies . get ( scopedProxyBeanName ) ; if ( proxy == null ) { proxy = createScopedProxyBean ( petiteContainer , refBeanDefinition ) ; proxies . put ( scopedProxyBeanName , proxy ) ; } return proxy ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates mixed scope message . [CODESPLIT] protected String createMixingMessage ( final BeanDefinition targetBeanDefinition , final BeanDefinition refBeanDefinition ) { return \"Scopes mixing detected: \" + refBeanDefinition . name + \"@\" + refBeanDefinition . scope . getClass ( ) . getSimpleName ( ) + \" -> \" + targetBeanDefinition . name + \"@\" + targetBeanDefinition . scope . getClass ( ) . getSimpleName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates scoped proxy bean for given bean definition . [CODESPLIT] protected Object createScopedProxyBean ( final PetiteContainer petiteContainer , final BeanDefinition refBeanDefinition ) { Class beanType = refBeanDefinition . type ; Class proxyClass = proxyClasses . get ( beanType ) ; if ( proxyClass == null ) { // create proxy class only once if ( refBeanDefinition instanceof ProxettaBeanDefinition ) { // special case, double proxy! ProxettaBeanDefinition pbd = ( ProxettaBeanDefinition ) refBeanDefinition ; ProxyProxetta proxetta = Proxetta . proxyProxetta ( ) . withAspects ( ArraysUtil . insert ( pbd . proxyAspects , aspect , 0 ) ) ; proxetta . setClassNameSuffix ( \"$ScopedProxy\" ) ; proxetta . setVariableClassName ( true ) ; ProxyProxettaFactory builder = proxetta . proxy ( ) . setTarget ( pbd . originalTarget ) ; proxyClass = builder . define ( ) ; proxyClasses . put ( beanType , proxyClass ) ; } else { ProxyProxetta proxetta = Proxetta . proxyProxetta ( ) . withAspect ( aspect ) ; proxetta . setClassNameSuffix ( \"$ScopedProxy\" ) ; proxetta . setVariableClassName ( true ) ; ProxyProxettaFactory builder = proxetta . proxy ( ) . setTarget ( beanType ) ; proxyClass = builder . define ( ) ; proxyClasses . put ( beanType , proxyClass ) ; } } Object proxy ; try { proxy = ClassUtil . newInstance ( proxyClass ) ; Field field = proxyClass . getField ( \"$__petiteContainer$0\" ) ; field . set ( proxy , petiteContainer ) ; field = proxyClass . getField ( \"$__name$0\" ) ; field . set ( proxy , refBeanDefinition . name ) ; } catch ( Exception ex ) { throw new PetiteException ( ex ) ; } return proxy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares step value . If step is 0 it will be set to + 1 or - 1 depending on start and end value . <p > If autoDirection flag is <code > true< / code > then it is assumed that step is positive and that direction ( step sign ) should be detected from start and end value . <p > If checkDirection flag is <code > true< / code > than it checks loop direction ( step sign ) based on start and end value . Throws an exception if direction is invalid . If autoDirection is set direction checking is skipped . [CODESPLIT] protected void prepareStepDirection ( final boolean autoDirection , final boolean checkDirection ) { if ( step == 0 ) { step = ( start <= end ) ? 1 : - 1 ; return ; } if ( autoDirection ) { if ( step < 0 ) { throw new IllegalArgumentException ( \"Step value can't be negative: \" + step ) ; } if ( start > end ) { step = - step ; } return ; } if ( checkDirection ) { if ( start < end ) { if ( step < 0 ) { throw new IllegalArgumentException ( \"Negative step value for increasing loop\" ) ; } return ; } if ( start > end ) { if ( step > 0 ) { throw new IllegalArgumentException ( \"Positive step value for decreasing loop\" ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops body . [CODESPLIT] protected void loopBody ( ) throws JspException { JspFragment body = getJspBody ( ) ; if ( body == null ) { return ; } LoopIterator loopIterator = new LoopIterator ( start , end , step , modulus ) ; if ( status != null ) { getJspContext ( ) . setAttribute ( status , loopIterator ) ; } while ( loopIterator . next ( ) ) { TagUtil . invokeBody ( body ) ; } if ( status != null ) { getJspContext ( ) . removeAttribute ( status ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes dir watcher by reading all files from watched folder . [CODESPLIT] protected void init ( ) { File [ ] filesArray = dir . listFiles ( ) ; filesCount = 0 ; if ( filesArray != null ) { filesCount = filesArray . length ; for ( File file : filesArray ) { if ( ! acceptFile ( file ) ) { continue ; } map . put ( file , new MutableLong ( file . lastModified ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accepts if a file is going to be watched . [CODESPLIT] protected boolean acceptFile ( final File file ) { if ( ! file . isFile ( ) ) { return false ; // ignore non-files } String fileName = file . getName ( ) ; if ( ignoreDotFiles ) { if ( fileName . startsWith ( StringPool . DOT ) ) { return false ; // ignore hidden files } } if ( patterns == null ) { return true ; } return Wildcard . matchOne ( fileName , patterns ) != - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables usage of provided watch file . [CODESPLIT] public DirWatcher useWatchFile ( final String name ) { watchFile = new File ( dir , name ) ; if ( ! watchFile . isFile ( ) || ! watchFile . exists ( ) ) { try { FileUtil . touch ( watchFile ) ; } catch ( IOException ioex ) { throw new DirWatcherException ( \"Invalid watch file: \" + name , ioex ) ; } } watchFileLastAccessTime = watchFile . lastModified ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the watcher . [CODESPLIT] public void start ( final long pollingInterval ) { if ( timer == null ) { if ( ! startBlank ) { init ( ) ; } timer = new Timer ( true ) ; timer . schedule ( new WatchTask ( ) , 0 , pollingInterval ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers listeners on file change . [CODESPLIT] protected void onChange ( final DirWatcherEvent . Type type , final File file ) { listeners . accept ( new DirWatcherEvent ( type , file ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an enumeration to this composite . [CODESPLIT] public void add ( final Enumeration < T > enumeration ) { if ( allEnumerations . contains ( enumeration ) ) { throw new IllegalArgumentException ( \"Duplicate enumeration\" ) ; } allEnumerations . add ( enumeration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if composite has more elements . [CODESPLIT] public boolean hasMoreElements ( ) { if ( currentEnumeration == - 1 ) { currentEnumeration = 0 ; } for ( int i = currentEnumeration ; i < allEnumerations . size ( ) ; i ++ ) { Enumeration enumeration = allEnumerations . get ( i ) ; if ( enumeration . hasMoreElements ( ) ) { currentEnumeration = i ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected double [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final double [ ] target = new double [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Double > doubleArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final double convertedValue = convertType ( element ) ; doubleArrayList . add ( Double . valueOf ( convertedValue ) ) ; } final double [ ] array = new double [ doubleArrayList . size ( ) ] ; for ( int i = 0 ; i < doubleArrayList . size ( ) ; i ++ ) { final Double d = doubleArrayList . get ( i ) ; array [ i ] = d . doubleValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of the field_info JVMS structure generated by this FieldWriter . Also adds the names of the attributes of this field in the constant pool . [CODESPLIT] int computeFieldInfoSize ( ) { // The access_flags, name_index, descriptor_index and attributes_count fields use 8 bytes. int size = 8 ; // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. if ( constantValueIndex != 0 ) { // ConstantValue attributes always use 8 bytes. symbolTable . addConstantUtf8 ( Constants . CONSTANT_VALUE ) ; size += 8 ; } // Before Java 1.5, synthetic fields are represented with a Synthetic attribute. if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && symbolTable . getMajorVersion ( ) < Opcodes . V1_5 ) { // Synthetic attributes always use 6 bytes. symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ; size += 6 ; } if ( signatureIndex != 0 ) { // Signature attributes always use 8 bytes. symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ; size += 8 ; } // ACC_DEPRECATED is ASM specific, the ClassFile format uses a Deprecated attribute instead. if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { // Deprecated attributes always use 6 bytes. symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ; size += 6 ; } if ( lastRuntimeVisibleAnnotation != null ) { size += lastRuntimeVisibleAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_ANNOTATIONS ) ; } if ( lastRuntimeInvisibleAnnotation != null ) { size += lastRuntimeInvisibleAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS ) ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { size += lastRuntimeVisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { size += lastRuntimeInvisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) ; } if ( firstAttribute != null ) { size += firstAttribute . computeAttributesSize ( symbolTable ) ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the content of the field_info JVMS structure generated by this FieldWriter into the given ByteVector . [CODESPLIT] void putFieldInfo ( final ByteVector output ) { boolean useSyntheticAttribute = symbolTable . getMajorVersion ( ) < Opcodes . V1_5 ; // Put the access_flags, name_index and descriptor_index fields. int mask = useSyntheticAttribute ? Opcodes . ACC_SYNTHETIC : 0 ; output . putShort ( accessFlags & ~ mask ) . putShort ( nameIndex ) . putShort ( descriptorIndex ) ; // Compute and put the attributes_count field. // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. int attributesCount = 0 ; if ( constantValueIndex != 0 ) { ++ attributesCount ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { ++ attributesCount ; } if ( signatureIndex != 0 ) { ++ attributesCount ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { ++ attributesCount ; } if ( lastRuntimeVisibleAnnotation != null ) { ++ attributesCount ; } if ( lastRuntimeInvisibleAnnotation != null ) { ++ attributesCount ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { ++ attributesCount ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { ++ attributesCount ; } if ( firstAttribute != null ) { attributesCount += firstAttribute . getAttributeCount ( ) ; } output . putShort ( attributesCount ) ; // Put the field_info attributes. // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. if ( constantValueIndex != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . CONSTANT_VALUE ) ) . putInt ( 2 ) . putShort ( constantValueIndex ) ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ) . putInt ( 0 ) ; } if ( signatureIndex != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ) . putInt ( 2 ) . putShort ( signatureIndex ) ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ) . putInt ( 0 ) ; } if ( lastRuntimeVisibleAnnotation != null ) { lastRuntimeVisibleAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_ANNOTATIONS ) , output ) ; } if ( lastRuntimeInvisibleAnnotation != null ) { lastRuntimeInvisibleAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS ) , output ) ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { lastRuntimeVisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) , output ) ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { lastRuntimeInvisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) , output ) ; } if ( firstAttribute != null ) { firstAttribute . putAttributes ( symbolTable , output ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches conditional comment expression with current mode . Returns <code > true< / code > it conditional comment expression is positive otherwise returns <code > false< / code > . [CODESPLIT] public boolean match ( final float ieVersion , String expression ) { expression = StringUtil . removeChars ( expression , \"()\" ) ; expression = expression . substring ( 3 ) ; String [ ] andChunks = StringUtil . splitc ( expression , ' ' ) ; boolean valid = true ; for ( String andChunk : andChunks ) { String [ ] orChunks = StringUtil . splitc ( andChunk , ' ' ) ; boolean innerValid = false ; for ( String orChunk : orChunks ) { orChunk = orChunk . trim ( ) ; if ( orChunk . startsWith ( \"IE \" ) ) { String value = orChunk . substring ( 3 ) ; float number = Float . parseFloat ( value ) ; if ( versionToCompare ( ieVersion , number ) == number ) { innerValid = true ; break ; } continue ; } if ( orChunk . startsWith ( \"!IE \" ) ) { String value = orChunk . substring ( 4 ) ; float number = Float . parseFloat ( value ) ; if ( versionToCompare ( ieVersion , number ) != number ) { innerValid = true ; break ; } continue ; } if ( orChunk . startsWith ( \"lt IE \" ) ) { String value = orChunk . substring ( 6 ) ; float number = Float . parseFloat ( value ) ; if ( ieVersion < number ) { innerValid = true ; break ; } continue ; } if ( orChunk . startsWith ( \"lte IE \" ) ) { String value = orChunk . substring ( 7 ) ; float number = Float . parseFloat ( value ) ; if ( versionToCompare ( ieVersion , number ) <= number ) { innerValid = true ; break ; } continue ; } if ( orChunk . startsWith ( \"gt IE \" ) ) { String value = orChunk . substring ( 6 ) ; float number = Float . parseFloat ( value ) ; if ( versionToCompare ( ieVersion , number ) > number ) { innerValid = true ; break ; } continue ; } if ( orChunk . startsWith ( \"gte IE \" ) ) { String value = orChunk . substring ( 7 ) ; float number = Float . parseFloat ( value ) ; if ( ieVersion >= number ) { innerValid = true ; break ; } continue ; } } valid = valid && innerValid ; } return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastByteBuffer append ( final FastByteBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a common target over a value with known scope data . [CODESPLIT] public static Target ofValue ( final Object value , final ScopeData scopeData ) { return new Target ( value , null , scopeData , null , VALUE_INSTANCE_CREATOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a common target over a method param . [CODESPLIT] public static Target ofMethodParam ( final MethodParam methodParam , final Object object ) { return new Target ( object , methodParam . type ( ) , methodParam . scopeData ( ) , methodParam . mapperFunction ( ) , VALUE_INSTANCE_CREATOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a common target over a method param . [CODESPLIT] public static Target ofMethodParam ( final MethodParam methodParam , final Function < Class , Object > valueInstanceCreator ) { return new Target ( null , methodParam . type ( ) , methodParam . scopeData ( ) , methodParam . mapperFunction ( ) , valueInstanceCreator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes value to this target . Depending on a flag writing the value can be completely silent when no exception is thrown and with top performances . Otherwise an exception is thrown on a failure . [CODESPLIT] public void writeValue ( final InjectionPoint injectionPoint , final Object propertyValue , final boolean silent ) { writeValue ( injectionPoint . targetName ( ) , propertyValue , silent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorates page content with decorator template and outputs the result . [CODESPLIT] public void decorate ( final Writer writer , final char [ ] pageContent , final char [ ] decoraContent ) throws IOException { DecoraTag [ ] decoraTags = parseDecorator ( decoraContent ) ; parsePage ( pageContent , decoraTags ) ; writeDecoratedPage ( writer , decoraContent , pageContent , decoraTags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses decorator file and collects { [CODESPLIT] protected DecoraTag [ ] parseDecorator ( final char [ ] decoraContent ) { LagartoParser lagartoParser = new LagartoParser ( decoraContent ) ; lagartoParser . getConfig ( ) . setEnableRawTextModes ( false ) ; DecoratorTagVisitor visitor = new DecoratorTagVisitor ( ) ; lagartoParser . parse ( visitor ) ; return visitor . getDecoraTags ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses target page and extracts Decora regions for replacements . [CODESPLIT] protected void parsePage ( final char [ ] pageContent , final DecoraTag [ ] decoraTags ) { LagartoParser lagartoParser = new LagartoParser ( pageContent ) ; PageRegionExtractor writer = new PageRegionExtractor ( decoraTags ) ; lagartoParser . parse ( writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes decorated content . [CODESPLIT] protected void writeDecoratedPage ( final Writer out , final char [ ] decoratorContent , final char [ ] pageContent , final DecoraTag [ ] decoraTags ) throws IOException { int ndx = 0 ; for ( DecoraTag decoraTag : decoraTags ) { // [1] just copy content before the Decora tag int decoratorLen = decoraTag . getStartIndex ( ) - ndx ; if ( decoratorLen <= 0 ) { continue ; } out . write ( decoratorContent , ndx , decoratorLen ) ; ndx = decoraTag . getEndIndex ( ) ; // [2] now write region at the place of Decora tag int regionLen = decoraTag . getRegionLength ( ) ; if ( regionLen == 0 ) { if ( decoraTag . hasDefaultValue ( ) ) { out . write ( decoratorContent , decoraTag . getDefaultValueStart ( ) , decoraTag . getDefaultValueLength ( ) ) ; } } else { writeRegion ( out , pageContent , decoraTag , decoraTags ) ; } } // write remaining content out . write ( decoratorContent , ndx , decoratorContent . length - ndx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes region to output but extracts all inner regions . [CODESPLIT] protected void writeRegion ( final Writer out , final char [ ] pageContent , final DecoraTag decoraTag , final DecoraTag [ ] decoraTags ) throws IOException { int regionStart = decoraTag . getRegionStart ( ) ; int regionLen = decoraTag . getRegionLength ( ) ; int regionEnd = regionStart + regionLen ; for ( DecoraTag innerDecoraTag : decoraTags ) { if ( decoraTag == innerDecoraTag ) { continue ; } if ( decoraTag . isRegionUndefined ( ) ) { continue ; } if ( innerDecoraTag . isInsideOtherTagRegion ( decoraTag ) ) { // write everything from region start to the inner Decora tag out . write ( pageContent , regionStart , innerDecoraTag . getRegionTagStart ( ) - regionStart ) ; regionStart = innerDecoraTag . getRegionTagEnd ( ) ; } } // write remaining content of the region out . write ( pageContent , regionStart , regionEnd - regionStart ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if text content is blank . [CODESPLIT] public boolean isBlank ( ) { if ( blank == null ) { blank = Boolean . valueOf ( StringUtil . isBlank ( nodeValue ) ) ; } return blank . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts HTTP tunnel . Method ends when the tunnel is stopped . [CODESPLIT] public void start ( ) throws IOException { serverSocket = new ServerSocket ( listenPort , socketBacklog ) ; serverSocket . setReuseAddress ( true ) ; executorService = Executors . newFixedThreadPool ( threadPoolSize ) ; running = true ; while ( running ) { Socket socket = serverSocket . accept ( ) ; socket . setKeepAlive ( false ) ; executorService . execute ( onSocketConnection ( socket ) ) ; } executorService . shutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected int [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final int [ ] target = new int [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final FastIntBuffer fastIntBuffer = new FastIntBuffer ( ) ; for ( final Object element : iterable ) { final int convertedValue = convertType ( element ) ; fastIntBuffer . append ( convertedValue ) ; } return fastIntBuffer . toArray ( ) ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a process and returns the process output and exit code . [CODESPLIT] public static ProcessResult run ( final Process process ) throws InterruptedException { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final StreamGobbler outputGobbler = new StreamGobbler ( process . getInputStream ( ) , baos , OUTPUT_PREFIX ) ; final StreamGobbler errorGobbler = new StreamGobbler ( process . getErrorStream ( ) , baos , ERROR_PREFIX ) ; outputGobbler . start ( ) ; errorGobbler . start ( ) ; final int result = process . waitFor ( ) ; outputGobbler . waitFor ( ) ; errorGobbler . waitFor ( ) ; return new ProcessResult ( result , baos . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns email store . [CODESPLIT] @ Override protected IMAPSSLStore getStore ( final Session session ) { SimpleAuthenticator simpleAuthenticator = ( SimpleAuthenticator ) authenticator ; final URLName url ; if ( simpleAuthenticator == null ) { url = new URLName ( PROTOCOL_IMAP , host , port , StringPool . EMPTY , null , null ) ; } else { final PasswordAuthentication pa = simpleAuthenticator . getPasswordAuthentication ( ) ; url = new URLName ( PROTOCOL_IMAP , host , port , StringPool . EMPTY , pa . getUserName ( ) , pa . getPassword ( ) ) ; } return new IMAPSSLStore ( session , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if path matches the query . [CODESPLIT] public boolean matches ( final Path path ) { int exprNdx = 0 ; int pathNdx = 0 ; int pathLen = path . length ( ) ; int exprLen = expression . length ; while ( pathNdx < pathLen ) { CharSequence current = path . get ( pathNdx ) ; if ( exprNdx < exprLen && expression [ exprNdx ] . equals ( STAR ) ) { exprNdx ++ ; } else if ( exprNdx < exprLen && expression [ exprNdx ] . contentEquals ( current ) ) { pathNdx ++ ; exprNdx ++ ; } else if ( exprNdx - 1 >= 0 && expression [ exprNdx - 1 ] . equals ( STAR ) ) { pathNdx ++ ; } else { return false ; } } if ( exprNdx > 0 && expression [ exprNdx - 1 ] . equals ( STAR ) ) { return pathNdx >= pathLen && exprNdx >= exprLen ; } else { return pathLen != 0 && pathNdx >= pathLen && ( included || exprNdx >= exprLen ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a ServletOutputStream to write the content associated with this Response . [CODESPLIT] public ServletOutputStream createOutputStream ( ) throws IOException { GzipResponseStream gzstream = new GzipResponseStream ( origResponse ) ; gzstream . setBuffer ( threshold ) ; return gzstream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes validation on inner context . Always returns <code > true< / code > since inner context violations will be appended to provided validator . [CODESPLIT] @ Override public boolean isValid ( final ValidationConstraintContext vcc , final Object value ) { if ( value == null ) { return true ; } vcc . validateWithin ( targetValidationContext , value ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public URL get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getURL ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final URL value , final int dbSqlType ) throws SQLException { st . setURL ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- process [CODESPLIT] @ Override public void process ( final StringBuilder out ) { final DbEntityDescriptor ded ; if ( tableRef != null ) { ded = lookupTableRef ( tableRef ) ; final String tableName = resolveTable ( tableRef , ded ) ; out . append ( tableName ) ; } else { ded = findColumnRef ( columnRef ) ; } if ( onlyId ) { if ( tableRef != null ) { out . append ( ' ' ) ; } out . append ( ded . getIdColumnName ( ) ) ; } else if ( columnRef != null ) { DbEntityColumnDescriptor dec = ded . findByPropertyName ( columnRef ) ; templateData . lastColumnDec = dec ; if ( dec == null ) { throw new DbSqlBuilderException ( \"Invalid column reference: [\" + tableRef + ' ' + columnRef + \"]\" ) ; } if ( tableRef != null ) { out . append ( ' ' ) ; } out . append ( dec . getColumnNameForQuery ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Counts actual real hints . [CODESPLIT] @ Override public void init ( final TemplateData templateData ) { super . init ( templateData ) ; if ( hint != null ) { templateData . incrementHintsCount ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends alias . [CODESPLIT] protected void appendAlias ( final StringBuilder query , final DbEntityDescriptor ded , final DbEntityColumnDescriptor dec ) { final ColumnAliasType columnAliasType = templateData . getColumnAliasType ( ) ; if ( columnAliasType == null || columnAliasType == ColumnAliasType . TABLE_REFERENCE ) { final String tableName = ded . getTableName ( ) ; final String columnName = dec . getColumnNameForQuery ( ) ; templateData . registerColumnDataForTableRef ( tableRef , tableName ) ; query . append ( tableRef ) . append ( columnAliasSeparator ) . append ( columnName ) ; } else if ( columnAliasType == ColumnAliasType . COLUMN_CODE ) { final String tableName = ded . getTableName ( ) ; final String columnName = dec . getColumnName ( ) ; final String code = templateData . registerColumnDataForColumnCode ( tableName , columnName ) ; query . append ( code ) ; } else if ( columnAliasType == ColumnAliasType . TABLE_NAME ) { final String tableName = ded . getTableNameForQuery ( ) ; final String columnName = dec . getColumnNameForQuery ( ) ; query . append ( tableName ) . append ( columnAliasSeparator ) . append ( columnName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simply appends column name with optional table reference and alias . [CODESPLIT] protected void appendColumnName ( final StringBuilder query , final DbEntityDescriptor ded , final DbEntityColumnDescriptor dec ) { query . append ( resolveTable ( tableRef , ded ) ) . append ( ' ' ) . append ( dec . getColumnName ( ) ) ; if ( templateData . getColumnAliasType ( ) != null ) { // create column aliases query . append ( AS ) ; switch ( templateData . getColumnAliasType ( ) ) { case TABLE_NAME : { final String tableName = ded . getTableNameForQuery ( ) ; query . append ( tableName ) . append ( columnAliasSeparator ) . append ( dec . getColumnNameForQuery ( ) ) ; break ; } case TABLE_REFERENCE : { final String tableName = ded . getTableName ( ) ; templateData . registerColumnDataForTableRef ( tableRef , tableName ) ; query . append ( tableRef ) . append ( columnAliasSeparator ) . append ( dec . getColumnNameForQuery ( ) ) ; break ; } case COLUMN_CODE : { final String tableName = ded . getTableName ( ) ; final String code = templateData . registerColumnDataForColumnCode ( tableName , dec . getColumnName ( ) ) ; query . append ( code ) ; break ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a rule . Duplicates are not allowed and will be ignored . [CODESPLIT] protected void addRule ( final D ruleDefinition , final boolean include ) { if ( rules == null ) { rules = new ArrayList <> ( ) ; } if ( include ) { includesCount ++ ; } else { excludesCount ++ ; } Rule < R > newRule = new Rule <> ( makeRule ( ruleDefinition ) , include ) ; if ( rules . contains ( newRule ) ) { return ; } rules . add ( newRule ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches value against the set of rules using provided white / black list mode . [CODESPLIT] public boolean match ( final V value , final boolean blacklist ) { if ( rules == null ) { return blacklist ; } boolean include = blacklist ; if ( include ) { include = processExcludes ( value , true ) ; include = processIncludes ( value , include ) ; } else { include = processIncludes ( value , false ) ; include = processExcludes ( value , include ) ; } return include ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies rules on given flag . Flag is only changed if at least one rule matched . Otherwise the same value is returned . This way you can chain several rules and have the rule engine change the flag only when a rule is matched . [CODESPLIT] public boolean apply ( final V value , final boolean blacklist , boolean flag ) { if ( rules == null ) { return flag ; } if ( blacklist ) { flag = processExcludes ( value , flag ) ; flag = processIncludes ( value , flag ) ; } else { flag = processIncludes ( value , flag ) ; flag = processExcludes ( value , flag ) ; } return flag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process includes rules . [CODESPLIT] protected boolean processIncludes ( final V value , boolean include ) { if ( includesCount > 0 ) { if ( ! include ) { for ( Rule < R > rule : rules ) { if ( ! rule . include ) { continue ; } if ( inExRuleMatcher . accept ( value , rule . value , true ) ) { include = true ; break ; } } } } return include ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process excludes rules . [CODESPLIT] protected boolean processExcludes ( final V value , boolean include ) { if ( excludesCount > 0 ) { if ( include ) { for ( Rule < R > rule : rules ) { if ( rule . include ) { continue ; } if ( inExRuleMatcher . accept ( value , rule . value , false ) ) { include = false ; break ; } } } } return include ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches value against single rule . By default performs <code > equals< / code > on value against the rule . [CODESPLIT] @ Override public boolean accept ( final V value , final R rule , final boolean include ) { return value . equals ( rule ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns pseudo - class name from simple class name . [CODESPLIT] public String getPseudoClassName ( ) { String name = getClass ( ) . getSimpleName ( ) . toLowerCase ( ) ; name = name . replace ( ' ' , ' ' ) ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an Object to sorted list . Object is inserted at correct place found using binary search . If the same item exist it will be put to the end of the range . <p > This method breaks original list contract since objects are not added at the list end but in sorted manner . [CODESPLIT] @ Override public boolean add ( final E o ) { int idx = 0 ; if ( ! isEmpty ( ) ) { idx = findInsertionPoint ( o ) ; } super . add ( idx , o ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all of the elements in the given collection to this list . [CODESPLIT] @ Override public boolean addAll ( final Collection < ? extends E > c ) { Iterator < ? extends E > i = c . iterator ( ) ; boolean changed = false ; while ( i . hasNext ( ) ) { boolean ret = add ( i . next ( ) ) ; if ( ! changed ) { changed = ret ; } } return changed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conducts a binary search to find the index where Object should be inserted . [CODESPLIT] protected int findInsertionPoint ( final E o , int low , int high ) { while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( get ( mid ) , o ) ; if ( delta > 0 ) { high = mid - 1 ; } else { low = mid + 1 ; } } return low ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts Jodd logging level to JDK . [CODESPLIT] private org . apache . logging . log4j . Level jodd2log4j2 ( final Logger . Level level ) { switch ( level ) { case TRACE : return org . apache . logging . log4j . Level . TRACE ; case DEBUG : return org . apache . logging . log4j . Level . DEBUG ; case INFO : return org . apache . logging . log4j . Level . INFO ; case WARN : return org . apache . logging . log4j . Level . WARN ; case ERROR : return org . apache . logging . log4j . Level . ERROR ; default : throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- match [CODESPLIT] public boolean accept ( final Node node ) { if ( ! node . hasAttribute ( name ) ) { return false ; } if ( value == null ) { // just detect if attribute exist return true ; } String nodeValue = node . getAttribute ( name ) ; if ( nodeValue == null ) { return false ; } return match . compare ( nodeValue , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers action configuration for given annotation . New { [CODESPLIT] public void registerAnnotation ( final Class < ? extends Annotation > annotationType ) { final ActionConfiguredBy actionConfiguredBy = annotationType . getAnnotation ( ActionConfiguredBy . class ) ; if ( actionConfiguredBy == null ) { throw new MadvocException ( \"Action annotation is missing it's \" + ActionConfiguredBy . class . getSimpleName ( ) + \" configuration.\" ) ; } bindAnnotationConfig ( annotationType , actionConfiguredBy . value ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds action annotation and the action config . This can overwrite the default annotation configuration of an annotation . [CODESPLIT] public void bindAnnotationConfig ( final Class < ? extends Annotation > annotationType , final Class < ? extends ActionConfig > actionConfigClass ) { final ActionConfig actionConfig = registerNewActionConfiguration ( actionConfigClass ) ; actionConfigs . put ( annotationType , actionConfig ) ; for ( final AnnotationParser annotationParser : annotationParsers ) { if ( annotationType . equals ( annotationParser . getAnnotationType ( ) ) ) { // parser already exists return ; } } annotationParsers = ArraysUtil . append ( annotationParsers , new AnnotationParser ( annotationType , Action . class ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers action configuration for given type . [CODESPLIT] protected ActionConfig registerNewActionConfiguration ( final Class < ? extends ActionConfig > actionConfigClass ) { final ActionConfig newActionConfig = createActionConfig ( actionConfigClass ) ; actionConfigs . put ( actionConfigClass , newActionConfig ) ; return newActionConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup for the action configuration . Typically the input argument is either the action type or annotation type . [CODESPLIT] public ActionConfig lookup ( final Class actionTypeOrAnnotationType ) { final ActionConfig actionConfig = actionConfigs . get ( actionTypeOrAnnotationType ) ; if ( actionConfig == null ) { throw new MadvocException ( \"ActionConfiguration not registered:\" + actionTypeOrAnnotationType . getName ( ) ) ; } return actionConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch some action config and consumes it . [CODESPLIT] public < T extends ActionConfig > void with ( final Class < T > actionConfigType , final Consumer < T > actionConfigConsumer ) { final T actionConfig = ( T ) lookup ( actionConfigType ) ; actionConfigConsumer . accept ( actionConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public boolean hasActionAnnotationOn ( final AnnotatedElement annotatedElement ) { for ( final AnnotationParser annotationParser : annotationParsers ) { if ( annotationParser . hasAnnotationOn ( annotatedElement ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setups the system email properties . [CODESPLIT] protected static void setupSystemMailProperties ( ) { System . setProperty ( \"mail.mime.encodefilename\" , Boolean . valueOf ( Defaults . mailMimeEncodefilename ) . toString ( ) ) ; System . setProperty ( \"mail.mime.decodefilename\" , Boolean . valueOf ( Defaults . mailMimeDecodefilename ) . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates provided context and value withing this constraint content . [CODESPLIT] public void validateWithin ( final ValidationContext vctx , final Object value ) { vtor . validate ( vctx , value , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if provided element is one of the table - related elements . [CODESPLIT] protected boolean isOneOfTableElements ( final Element element ) { String elementName = element . getNodeName ( ) . toLowerCase ( ) ; return StringUtil . equalsOne ( elementName , TABLE_ELEMENTS ) != - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if given node is a table element . [CODESPLIT] protected boolean isTableElement ( final Node node ) { if ( node . getNodeType ( ) != Node . NodeType . ELEMENT ) { return false ; } String elementName = node . getNodeName ( ) . toLowerCase ( ) ; return elementName . equals ( \"table\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if parent node is one of the table elements . [CODESPLIT] protected boolean isParentNodeOneOfFosterTableElements ( final Node parentNode ) { if ( parentNode == null ) { return false ; } if ( parentNode . getNodeName ( ) == null ) { return false ; } String nodeName = parentNode . getNodeName ( ) . toLowerCase ( ) ; return StringUtil . equalsOne ( nodeName , FOSTER_TABLE_ELEMENTS ) != - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the last table in stack of open elements . [CODESPLIT] protected Element findLastTable ( final Node node ) { Node tableNode = node ; while ( tableNode != null ) { if ( tableNode . getNodeType ( ) == Node . NodeType . ELEMENT ) { String tableNodeName = tableNode . getNodeName ( ) . toLowerCase ( ) ; if ( tableNodeName . equals ( \"table\" ) ) { break ; } } tableNode = tableNode . getParentNode ( ) ; } return ( Element ) tableNode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds foster elements . Returns <code > true< / code > if there was no change in DOM tree of the parent element . Otherwise returns <code > false< / code > meaning that parent will scan its childs again . [CODESPLIT] protected boolean findFosterNodes ( final Node node ) { boolean isTable = false ; if ( ! lastTables . isEmpty ( ) ) { // if inside table if ( node . getNodeType ( ) == Node . NodeType . TEXT ) { String value = node . getNodeValue ( ) ; if ( ! StringUtil . isBlank ( value ) ) { if ( isParentNodeOneOfFosterTableElements ( node . getParentNode ( ) ) ) { fosterTexts . add ( ( Text ) node ) ; } } } } if ( node . getNodeType ( ) == Node . NodeType . ELEMENT ) { Element element = ( Element ) node ; isTable = isTableElement ( node ) ; if ( isTable ) { // if node is a table, add it to the stack-of-last-tables lastTables . add ( element ) ; } else { // otherwise... // ...if inside the table if ( ! lastTables . isEmpty ( ) ) { // check this and parent Node parentNode = node . getParentNode ( ) ; if ( isParentNodeOneOfFosterTableElements ( parentNode ) && ! isOneOfTableElements ( element ) ) { String elementNodeName = element . getNodeName ( ) . toLowerCase ( ) ; if ( elementNodeName . equals ( \"form\" ) ) { if ( element . getChildNodesCount ( ) > 0 ) { // if form element, take all its child nodes // and add after the from element Node [ ] formChildNodes = element . getChildNodes ( ) ; parentNode . insertAfter ( formChildNodes , element ) ; return false ; } else { // empty form element, leave it where it is return true ; } } if ( elementNodeName . equals ( \"input\" ) ) { String inputType = element . getAttribute ( \"type\" ) ; if ( inputType . equals ( \"hidden\" ) ) { // input hidden elements remains as they are return true ; } } // foster element found, remember it to process it later fosterElements . add ( element ) ; } } else { // ...if not inside the table, just keep going } } } allchilds : while ( true ) { int childs = node . getChildNodesCount ( ) ; for ( int i = 0 ; i < childs ; i ++ ) { Node childNode = node . getChild ( i ) ; boolean done = findFosterNodes ( childNode ) ; if ( ! done ) { continue allchilds ; } } break ; } if ( isTable ) { // remove last element int size = lastTables . size ( ) ; if ( size > 0 ) { lastTables . remove ( size - 1 ) ; // no array copy occurs when the last element is removed } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the fix for elements . [CODESPLIT] protected void fixElements ( ) { for ( Element fosterElement : fosterElements ) { // find parent table Element lastTable = findLastTable ( fosterElement ) ; Node fosterElementParent = fosterElement . getParentNode ( ) ; // filter our foster element Node [ ] fosterChilds = fosterElement . getChildNodes ( ) ; for ( Node fosterChild : fosterChilds ) { if ( fosterChild . getNodeType ( ) == Node . NodeType . ELEMENT ) { if ( isOneOfTableElements ( ( Element ) fosterChild ) ) { // move all child table elements outside // the foster element fosterChild . detachFromParent ( ) ; fosterElementParent . insertBefore ( fosterChild , fosterElement ) ; } } } // finally, move foster element above the table fosterElement . detachFromParent ( ) ; lastTable . getParentNode ( ) . insertBefore ( fosterElement , lastTable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prune only expired objects <code > LinkedHashMap< / code > will take care of LRU if needed . [CODESPLIT] @ Override protected int pruneCache ( ) { if ( ! isPruneExpiredActive ( ) ) { return 0 ; } int count = 0 ; Iterator < CacheObject < K , V > > values = cacheMap . values ( ) . iterator ( ) ; while ( values . hasNext ( ) ) { CacheObject < K , V > co = values . next ( ) ; if ( co . isExpired ( ) ) { values . remove ( ) ; onRemove ( co . key , co . cachedObject ) ; count ++ ; } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new session destroy callback if not already registered . [CODESPLIT] protected Map < String , BeanData > registerSessionBeans ( final HttpSession httpSession ) { SessionBeans sessionBeans = new SessionBeans ( ) ; httpSession . setAttribute ( SESSION_BEANS_NAME , sessionBeans ) ; return sessionBeans . getBeanMap ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns instance map from http session . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected Map < String , BeanData > getSessionMap ( final HttpSession session ) { SessionBeans sessionBeans = ( SessionBeans ) session . getAttribute ( SESSION_BEANS_NAME ) ; if ( sessionBeans == null ) { return null ; } return sessionBeans . getBeanMap ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns request from current thread . [CODESPLIT] protected HttpSession getCurrentHttpSession ( ) { HttpServletRequest request = RequestContextListener . getRequest ( ) ; if ( request == null ) { throw new PetiteException ( \"No HTTP request bound to the current thread. Is RequestContextListener registered?\" ) ; } return request . getSession ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Work data initialization . [CODESPLIT] public void init ( String name , final String superName , final String suffix , final String reqProxyClassName ) { int lastSlash = name . lastIndexOf ( ' ' ) ; this . targetPackage = lastSlash == - 1 ? StringPool . EMPTY : name . substring ( 0 , lastSlash ) . replace ( ' ' , ' ' ) ; this . targetClassname = name . substring ( lastSlash + 1 ) ; this . nextSupername = superName ; this . superName = name ; // create proxy name if ( reqProxyClassName != null ) { if ( reqProxyClassName . startsWith ( DOT ) ) { name = name . substring ( 0 , lastSlash ) + ' ' + reqProxyClassName . substring ( 1 ) ; } else if ( reqProxyClassName . endsWith ( DOT ) ) { name = reqProxyClassName . replace ( ' ' , ' ' ) + this . targetClassname ; } else { name = reqProxyClassName . replace ( ' ' , ' ' ) ; } } // add optional suffix if ( suffix != null ) { name += suffix ; } this . thisReference = name ; this . superReference = this . superName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves used static initialization blocks ( clinit ) of advices . [CODESPLIT] void addAdviceClinitMethod ( final String name ) { if ( adviceClinits == null ) { adviceClinits = new ArrayList <> ( ) ; } adviceClinits . add ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves used constructors of advices . [CODESPLIT] void addAdviceInitMethod ( final String name ) { if ( adviceInits == null ) { adviceInits = new ArrayList <> ( ) ; } adviceInits . add ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Byte get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Byte . valueOf ( rs . getByte ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Byte value , final int dbSqlType ) throws SQLException { st . setByte ( index , value . byteValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process links . Returns bundle link if this is the first resource of the same type . Otherwise returns <code > null< / code > indicating that collection is going on and the original link should be removed . [CODESPLIT] public String processLink ( final String src ) { if ( newAction ) { if ( bundleId == null ) { bundleId = bundlesManager . registerNewBundleId ( ) ; bundleId += ' ' + bundleContentType ; } sources . add ( src ) ; } if ( firstScriptTag ) { // this is the first tag, change the url to point to the bundle firstScriptTag = false ; return buildStaplerUrl ( ) ; } else { // ignore all other script tags return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called on end of parsing . [CODESPLIT] public void end ( ) { if ( newAction ) { bundleId = bundlesManager . registerBundle ( contextPath , actionPath , bundleId , bundleContentType , sources ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces bundle marker with calculated bundle id . Used for <code > RESOURCE_ONLY< / code > strategy . [CODESPLIT] public char [ ] replaceBundleId ( final char [ ] content ) { if ( strategy == ACTION_MANAGED || bundleId == null ) { return content ; } int index = ArraysUtil . indexOf ( content , bundleIdMark ) ; if ( index == - 1 ) { return content ; } char [ ] bundleIdChars = bundleId . toCharArray ( ) ; char [ ] result = new char [ content . length - bundleIdMark . length + bundleIdChars . length ] ; System . arraycopy ( content , 0 , result , 0 , index ) ; System . arraycopy ( bundleIdChars , 0 , result , index , bundleIdChars . length ) ; System . arraycopy ( content , index + bundleIdMark . length , result , index + bundleIdChars . length , content . length - bundleIdMark . length - index ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert Java Properties to Jodd Props format . [CODESPLIT] public static void convert ( final Writer writer , final Properties properties ) throws IOException { convert ( writer , properties , Collections . emptyMap ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert Java Properties to Jodd Props format . [CODESPLIT] public static void convert ( final Writer writer , final Properties properties , final Map < String , Properties > profiles ) throws IOException { final PropertiesToProps toProps = new PropertiesToProps ( ) ; toProps . convertToWriter ( writer , properties , profiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties . [CODESPLIT] public void parse ( final String in ) { ParseState state = ParseState . TEXT ; ParseState stateOnEscape = null ; boolean insideSection = false ; String currentSection = null ; String key = null ; Operator operator = Operator . ASSIGN ; final StringBuilder sb = new StringBuilder ( ) ; final int len = in . length ( ) ; int ndx = 0 ; while ( ndx < len ) { final char c = in . charAt ( ndx ) ; ndx ++ ; if ( state == ParseState . COMMENT ) { // comment, skip to the end of the line if ( c == ' ' ) { if ( ( ndx < len ) && ( in . charAt ( ndx ) == ' ' ) ) { ndx ++ ; } state = ParseState . TEXT ; } else if ( c == ' ' ) { state = ParseState . TEXT ; } } else if ( state == ParseState . ESCAPE ) { state = stateOnEscape ; //ParseState.VALUE; switch ( c ) { case ' ' : if ( ( ndx < len ) && ( in . charAt ( ndx ) == ' ' ) ) { ndx ++ ; } case ' ' : // need to go 1 step back in order to escape // the current line ending in the follow-up state ndx -- ; state = ParseState . ESCAPE_NEWLINE ; break ; // encode UTF character case ' ' : int value = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { final char hexChar = in . charAt ( ndx ++ ) ; if ( CharUtil . isDigit ( hexChar ) ) { value = ( value << 4 ) + hexChar - ' ' ; } else if ( hexChar >= ' ' && hexChar <= ' ' ) { value = ( value << 4 ) + 10 + hexChar - ' ' ; } else if ( hexChar >= ' ' && hexChar <= ' ' ) { value = ( value << 4 ) + 10 + hexChar - ' ' ; } else { throw new IllegalArgumentException ( \"Malformed \\\\uXXXX encoding.\" ) ; } } sb . append ( ( char ) value ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; case ' ' : sb . append ( ' ' ) ; break ; default : sb . append ( c ) ; } } else if ( state == ParseState . TEXT ) { switch ( c ) { case ' ' : // escape char, take the next char as is stateOnEscape = state ; state = ParseState . ESCAPE ; break ; // start section case ' ' : if ( sb . length ( ) > 0 ) { if ( StringUtil . isNotBlank ( sb ) ) { sb . append ( c ) ; // previous string is not blank, hence it's not the section break ; } } sb . setLength ( 0 ) ; insideSection = true ; break ; // end section case ' ' : if ( insideSection ) { currentSection = sb . toString ( ) . trim ( ) ; sb . setLength ( 0 ) ; insideSection = false ; if ( currentSection . length ( ) == 0 ) { currentSection = null ; } } else { sb . append ( c ) ; } break ; case ' ' : case ' ' : state = ParseState . COMMENT ; break ; // copy operator case ' ' : if ( ndx == len || in . charAt ( ndx ) != ' ' ) { sb . append ( c ) ; break ; } operator = Operator . COPY ; //ndx++; continue ; // assignment operator case ' ' : if ( ndx == len || in . charAt ( ndx ) != ' ' ) { sb . append ( c ) ; break ; } operator = Operator . QUICK_APPEND ; //ndx++; continue ; case ' ' : case ' ' : if ( key == null ) { key = sb . toString ( ) . trim ( ) ; sb . setLength ( 0 ) ; } else { sb . append ( c ) ; } state = ParseState . VALUE ; break ; case ' ' : case ' ' : add ( currentSection , key , sb , true , operator ) ; sb . setLength ( 0 ) ; key = null ; operator = Operator . ASSIGN ; break ; case ' ' : case ' ' : // ignore whitespaces break ; default : sb . append ( c ) ; } } else { switch ( c ) { case ' ' : // escape char, take the next char as is stateOnEscape = state ; state = ParseState . ESCAPE ; break ; case ' ' : if ( ( ndx < len ) && ( in . charAt ( ndx ) == ' ' ) ) { ndx ++ ; } case ' ' : if ( state == ParseState . ESCAPE_NEWLINE ) { sb . append ( escapeNewLineValue ) ; if ( ! ignorePrefixWhitespacesOnNewLine ) { state = ParseState . VALUE ; } } else { add ( currentSection , key , sb , true , operator ) ; sb . setLength ( 0 ) ; key = null ; operator = Operator . ASSIGN ; // end of value, continue to text state = ParseState . TEXT ; } break ; case ' ' : case ' ' : if ( state == ParseState . ESCAPE_NEWLINE ) { break ; } default : sb . append ( c ) ; state = ParseState . VALUE ; if ( multilineValues ) { if ( sb . length ( ) == 3 ) { // check for ''' beginning if ( sb . toString ( ) . equals ( \"'''\" ) ) { sb . setLength ( 0 ) ; int endIndex = in . indexOf ( \"'''\" , ndx ) ; if ( endIndex == - 1 ) { endIndex = in . length ( ) ; } sb . append ( in , ndx , endIndex ) ; // append add ( currentSection , key , sb , false , operator ) ; sb . setLength ( 0 ) ; key = null ; operator = Operator . ASSIGN ; // end of value, continue to text state = ParseState . TEXT ; ndx = endIndex + 3 ; } } } } } } if ( key != null ) { add ( currentSection , key , sb , true , operator ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds accumulated value to key and current section . [CODESPLIT] protected void add ( final String section , final String key , final StringBuilder value , final boolean trim , final Operator operator ) { // ignore lines without : or = if ( key == null ) { return ; } String fullKey = key ; if ( section != null ) { if ( fullKey . length ( ) != 0 ) { fullKey = section + ' ' + fullKey ; } else { fullKey = section ; } } String v = value . toString ( ) ; if ( trim ) { if ( valueTrimLeft && valueTrimRight ) { v = v . trim ( ) ; } else if ( valueTrimLeft ) { v = StringUtil . trimLeft ( v ) ; } else { v = StringUtil . trimRight ( v ) ; } } if ( v . length ( ) == 0 && skipEmptyProps ) { return ; } extractProfilesAndAdd ( fullKey , v , operator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts profiles from the key name and adds key - value to them . [CODESPLIT] protected void extractProfilesAndAdd ( final String key , final String value , final Operator operator ) { String fullKey = key ; int ndx = fullKey . indexOf ( PROFILE_LEFT ) ; if ( ndx == - 1 ) { justAdd ( fullKey , value , null , operator ) ; return ; } // extract profiles ArrayList < String > keyProfiles = new ArrayList <> ( ) ; while ( true ) { ndx = fullKey . indexOf ( PROFILE_LEFT ) ; if ( ndx == - 1 ) { break ; } final int len = fullKey . length ( ) ; int ndx2 = fullKey . indexOf ( PROFILE_RIGHT , ndx + 1 ) ; if ( ndx2 == - 1 ) { ndx2 = len ; } // remember profile final String profile = fullKey . substring ( ndx + 1 , ndx2 ) ; keyProfiles . add ( profile ) ; // extract profile from key ndx2 ++ ; final String right = ( ndx2 == len ) ? StringPool . EMPTY : fullKey . substring ( ndx2 ) ; fullKey = fullKey . substring ( 0 , ndx ) + right ; } if ( fullKey . startsWith ( StringPool . DOT ) ) { // check for special case when only profile is defined in section fullKey = fullKey . substring ( 1 ) ; } // add value to extracted profiles justAdd ( fullKey , value , keyProfiles , operator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Core key - value addition . [CODESPLIT] protected void justAdd ( final String key , final String value , final ArrayList < String > keyProfiles , final Operator operator ) { if ( operator == Operator . COPY ) { HashMap < String , Object > target = new HashMap <> ( ) ; String [ ] profiles = null ; if ( keyProfiles != null ) { profiles = keyProfiles . toArray ( new String [ 0 ] ) ; } String [ ] sources = StringUtil . splitc ( value , ' ' ) ; for ( String source : sources ) { source = source . trim ( ) ; // try to extract profile for parsing String [ ] lookupProfiles = profiles ; String lookupProfilesString = null ; int leftIndex = source . indexOf ( ' ' ) ; if ( leftIndex != - 1 ) { int rightIndex = source . indexOf ( ' ' ) ; lookupProfilesString = source . substring ( leftIndex + 1 , rightIndex ) ; source = source . substring ( 0 , leftIndex ) . concat ( source . substring ( rightIndex + 1 ) ) ; lookupProfiles = StringUtil . splitc ( lookupProfilesString , ' ' ) ; StringUtil . trimAll ( lookupProfiles ) ; } String [ ] wildcards = new String [ ] { source + \".*\" } ; propsData . extract ( target , lookupProfiles , wildcards , null ) ; for ( Map . Entry < String , Object > entry : target . entrySet ( ) ) { String entryKey = entry . getKey ( ) ; String suffix = entryKey . substring ( source . length ( ) ) ; String newKey = key + suffix ; String newValue = \"${\" + entryKey ; if ( lookupProfilesString != null ) { newValue += \"<\" + lookupProfilesString + \">\" ; } newValue += \"}\" ; if ( profiles == null ) { propsData . putBaseProperty ( newKey , newValue , false ) ; } else { for ( final String p : profiles ) { propsData . putProfileProperty ( newKey , newValue , p , false ) ; } } } } return ; } boolean append = operator == Operator . QUICK_APPEND ; if ( keyProfiles == null ) { propsData . putBaseProperty ( key , value , append ) ; return ; } for ( final String p : keyProfiles ) { propsData . putProfileProperty ( key , value , p , append ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares value of two same instances . [CODESPLIT] @ Override public int compareTo ( final MutableShort other ) { return value < other . value ? - 1 : ( value == other . value ? 0 : 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts bytecode - like description to java class name that can be loaded with a classloader . Uses less - known feature of class loaders for loading array classes . [CODESPLIT] public static String typedesc2ClassName ( final String desc ) { String className = desc ; switch ( desc . charAt ( 0 ) ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : if ( desc . length ( ) != 1 ) { throw new IllegalArgumentException ( INVALID_BASE_TYPE + desc ) ; } break ; case ' ' : className = className . substring ( 1 , className . length ( ) - 1 ) ; break ; case ' ' : // uses less-known feature of class loaders for loading array types // using bytecode-like signatures. className = className . replace ( ' ' , ' ' ) ; break ; default : throw new IllegalArgumentException ( INVALID_TYPE_DESCRIPTION + desc ) ; } return className ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts type reference to java - name . [CODESPLIT] public static String typeref2Name ( final String desc ) { if ( desc . charAt ( 0 ) != TYPE_REFERENCE ) { throw new IllegalArgumentException ( INVALID_TYPE_DESCRIPTION + desc ) ; } String name = desc . substring ( 1 , desc . length ( ) - 1 ) ; return name . replace ( ' ' , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns java - like signature of a bytecode - like description . Only first description is parsed . [CODESPLIT] public static String typedescToSignature ( final String desc , final MutableInteger from ) { int fromIndex = from . get ( ) ; from . value ++ ; // default usage for most cases switch ( desc . charAt ( fromIndex ) ) { case ' ' : return \"byte\" ; case ' ' : return \"char\" ; case ' ' : return \"double\" ; case ' ' : return \"float\" ; case ' ' : return \"int\" ; case ' ' : return \"long\" ; case ' ' : return \"short\" ; case ' ' : return \"boolean\" ; case ' ' : return \"void\" ; case ' ' : int index = desc . indexOf ( ' ' , fromIndex ) ; if ( index < 0 ) { throw new IllegalArgumentException ( INVALID_TYPE_DESCRIPTION + desc ) ; } from . set ( index + 1 ) ; String str = desc . substring ( fromIndex + 1 , index ) ; return str . replace ( ' ' , ' ' ) ; case ' ' : return desc . substring ( from . value ) ; case ' ' : StringBuilder brackets = new StringBuilder ( ) ; int n = fromIndex ; while ( desc . charAt ( n ) == ' ' ) { // count opening brackets brackets . append ( \"[]\" ) ; n ++ ; } from . value = n ; String type = typedescToSignature ( desc , from ) ; // the rest of the string denotes a `<field_type>' return type + brackets ; default : if ( from . value == 0 ) { throw new IllegalArgumentException ( INVALID_TYPE_DESCRIPTION + desc ) ; } // generics! return desc . substring ( from . value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts type to byteccode type ref . [CODESPLIT] public static String typeToTyperef ( final Class type ) { if ( ! type . isArray ( ) ) { if ( ! type . isPrimitive ( ) ) { return ' ' + typeToSignature ( type ) + ' ' ; } if ( type == int . class ) { return \"I\" ; } if ( type == long . class ) { return \"J\" ; } if ( type == boolean . class ) { return \"Z\" ; } if ( type == double . class ) { return \"D\" ; } if ( type == float . class ) { return \"F\" ; } if ( type == short . class ) { return \"S\" ; } if ( type == void . class ) { return \"V\" ; } if ( type == byte . class ) { return \"B\" ; } if ( type == char . class ) { return \"C\" ; } } return type . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Integer< / code > object to an <code > int< / code > . [CODESPLIT] public static void intValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_INTEGER ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_INTEGER , \"intValue\" , \"()I\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Long< / code > object to a <code > long< / code > . [CODESPLIT] public static void longValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_LONG ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_LONG , \"longValue\" , \"()J\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Float< / code > object to a <code > float< / code > . [CODESPLIT] public static void floatValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_FLOAT ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_FLOAT , \"floatValue\" , \"()F\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Double< / code > object to a <code > double< / code > . [CODESPLIT] public static void doubleValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_DOUBLE ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_DOUBLE , \"doubleValue\" , \"()D\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Byte< / code > object to a <code > byte< / code > . [CODESPLIT] public static void byteValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_BYTE ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_BYTE , \"byteValue\" , \"()B\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Short< / code > object to a <code > short< / code > . [CODESPLIT] public static void shortValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_SHORT ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_SHORT , \"shortValue\" , \"()S\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Boolean< / code > object to a <code > boolean< / code > . [CODESPLIT] public static void booleanValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_BOOLEAN ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_BOOLEAN , \"booleanValue\" , \"()Z\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Character< / code > object to a <code > char< / code > . [CODESPLIT] public static void charValue ( final MethodVisitor mv ) { mv . visitTypeInsn ( CHECKCAST , SIGNATURE_JAVA_LANG_CHARACTER ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , SIGNATURE_JAVA_LANG_CHARACTER , \"charValue\" , \"()C\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers additional consumers . [CODESPLIT] public Consumers < T > addAll ( final Consumer < T > ... consumers ) { Collections . addAll ( consumerList , consumers ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes all registered consumers . The are executed sequentially in order of registration . If { [CODESPLIT] @ Override public void accept ( final T t ) { if ( parallel ) { consumerList . parallelStream ( ) . forEach ( consumer -> consumer . accept ( t ) ) ; } else { consumerList . forEach ( consumer -> consumer . accept ( t ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new collection of target component type . Default implementation uses reflection to create an collection of target type . Override it for better performances . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected Collection < T > createCollection ( final int length ) { if ( collectionType . isInterface ( ) ) { if ( collectionType == List . class ) { if ( length > 0 ) { return new ArrayList <> ( length ) ; } else { return new ArrayList <> ( ) ; } } if ( collectionType == Set . class ) { if ( length > 0 ) { return new HashSet <> ( length ) ; } else { return new HashSet <> ( ) ; } } throw new TypeConversionException ( \"Unknown collection: \" + collectionType . getName ( ) ) ; } if ( length > 0 ) { try { Constructor < Collection < T >> ctor = ( Constructor < Collection < T > > ) collectionType . getConstructor ( int . class ) ; return ctor . newInstance ( Integer . valueOf ( length ) ) ; } catch ( Exception ex ) { // ignore exception } } try { return collectionType . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( Exception ex ) { throw new TypeConversionException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a collection with single element . [CODESPLIT] protected Collection < T > convertToSingleElementCollection ( final Object value ) { Collection < T > collection = createCollection ( 0 ) ; //noinspection unchecked collection . add ( ( T ) value ) ; return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - collection value to collection . [CODESPLIT] protected Collection < T > convertValueToCollection ( Object value ) { if ( value instanceof Iterable ) { Iterable iterable = ( Iterable ) value ; Collection < T > collection = createCollection ( 0 ) ; for ( Object element : iterable ) { collection . add ( convertType ( element ) ) ; } return collection ; } if ( value instanceof CharSequence ) { value = CsvUtil . toStringArray ( value . toString ( ) ) ; } Class type = value . getClass ( ) ; if ( type . isArray ( ) ) { // convert arrays Class componentType = type . getComponentType ( ) ; if ( componentType . isPrimitive ( ) ) { return convertPrimitiveArrayToCollection ( value , componentType ) ; } else { Object [ ] array = ( Object [ ] ) value ; Collection < T > result = createCollection ( array . length ) ; for ( Object a : array ) { result . add ( convertType ( a ) ) ; } return result ; } } // everything else: return convertToSingleElementCollection ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts collection value to target collection . Each element is converted to target component type . [CODESPLIT] protected Collection < T > convertCollectionToCollection ( final Collection value ) { Collection < T > collection = createCollection ( value . size ( ) ) ; for ( Object v : value ) { collection . add ( convertType ( v ) ) ; } return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts primitive array to target collection . [CODESPLIT] @ SuppressWarnings ( \"AutoBoxing\" ) protected Collection < T > convertPrimitiveArrayToCollection ( final Object value , final Class primitiveComponentType ) { Collection < T > result = null ; if ( primitiveComponentType == int . class ) { int [ ] array = ( int [ ] ) value ; result = createCollection ( array . length ) ; for ( int a : array ) { result . add ( convertType ( a ) ) ; } } else if ( primitiveComponentType == long . class ) { long [ ] array = ( long [ ] ) value ; result = createCollection ( array . length ) ; for ( long a : array ) { result . add ( convertType ( a ) ) ; } } else if ( primitiveComponentType == float . class ) { float [ ] array = ( float [ ] ) value ; result = createCollection ( array . length ) ; for ( float a : array ) { result . add ( convertType ( a ) ) ; } } else if ( primitiveComponentType == double . class ) { double [ ] array = ( double [ ] ) value ; result = createCollection ( array . length ) ; for ( double a : array ) { result . add ( convertType ( a ) ) ; } } else if ( primitiveComponentType == short . class ) { short [ ] array = ( short [ ] ) value ; result = createCollection ( array . length ) ; for ( short a : array ) { result . add ( convertType ( a ) ) ; } } else if ( primitiveComponentType == byte . class ) { byte [ ] array = ( byte [ ] ) value ; result = createCollection ( array . length ) ; for ( byte a : array ) { result . add ( convertType ( a ) ) ; } } else if ( primitiveComponentType == char . class ) { char [ ] array = ( char [ ] ) value ; result = createCollection ( array . length ) ; for ( char a : array ) { result . add ( convertType ( a ) ) ; } } else if ( primitiveComponentType == boolean . class ) { boolean [ ] array = ( boolean [ ] ) value ; result = createCollection ( array . length ) ; for ( boolean a : array ) { result . add ( convertType ( a ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected WorkData process ( final ClassReader cr , final TargetClassInfoReader targetClassInfoReader ) { ProxettaClassBuilder pcb = new ProxettaClassBuilder ( destClassWriter , proxetta . getAspects ( new ProxyAspect [ 0 ] ) , resolveClassNameSuffix ( ) , requestedProxyClassName , targetClassInfoReader ) ; cr . accept ( pcb , 0 ) ; return pcb . getWorkData ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a source line number corresponding to this label . [CODESPLIT] final void addLineNumber ( final int lineNumber ) { if ( this . lineNumber == 0 ) { this . lineNumber = ( short ) lineNumber ; } else { if ( otherLineNumbers == null ) { otherLineNumbers = new int [ LINE_NUMBERS_CAPACITY_INCREMENT ] ; } int otherLineNumberIndex = ++ otherLineNumbers [ 0 ] ; if ( otherLineNumberIndex >= otherLineNumbers . length ) { int [ ] newLineNumbers = new int [ otherLineNumbers . length + LINE_NUMBERS_CAPACITY_INCREMENT ] ; System . arraycopy ( otherLineNumbers , 0 , newLineNumbers , 0 , otherLineNumbers . length ) ; otherLineNumbers = newLineNumbers ; } otherLineNumbers [ otherLineNumberIndex ] = lineNumber ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes the given visitor visit this label and its source line numbers if applicable . [CODESPLIT] final void accept ( final MethodVisitor methodVisitor , final boolean visitLineNumbers ) { methodVisitor . visitLabel ( this ) ; if ( visitLineNumbers && lineNumber != 0 ) { methodVisitor . visitLineNumber ( lineNumber & 0xFFFF , this ) ; if ( otherLineNumbers != null ) { for ( int i = 1 ; i <= otherLineNumbers [ 0 ] ; ++ i ) { methodVisitor . visitLineNumber ( otherLineNumbers [ i ] , this ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a reference to this label in the bytecode of a method . If the bytecode offset of the label is known the relative bytecode offset between the label and the instruction referencing it is computed and written directly . Otherwise a null relative offset is written and a new forward reference is declared for this label . [CODESPLIT] final void put ( final ByteVector code , final int sourceInsnBytecodeOffset , final boolean wideReference ) { if ( ( flags & FLAG_RESOLVED ) == 0 ) { if ( wideReference ) { addForwardReference ( sourceInsnBytecodeOffset , FORWARD_REFERENCE_TYPE_WIDE , code . length ) ; code . putInt ( - 1 ) ; } else { addForwardReference ( sourceInsnBytecodeOffset , FORWARD_REFERENCE_TYPE_SHORT , code . length ) ; code . putShort ( - 1 ) ; } } else { if ( wideReference ) { code . putInt ( bytecodeOffset - sourceInsnBytecodeOffset ) ; } else { code . putShort ( bytecodeOffset - sourceInsnBytecodeOffset ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a forward reference to this label . This method must be called only for a true forward reference i . e . only if this label is not resolved yet . For backward references the relative bytecode offset of the reference can be and must be computed and stored directly . [CODESPLIT] private void addForwardReference ( final int sourceInsnBytecodeOffset , final int referenceType , final int referenceHandle ) { if ( forwardReferences == null ) { forwardReferences = new int [ FORWARD_REFERENCES_CAPACITY_INCREMENT ] ; } int lastElementIndex = forwardReferences [ 0 ] ; if ( lastElementIndex + 2 >= forwardReferences . length ) { int [ ] newValues = new int [ forwardReferences . length + FORWARD_REFERENCES_CAPACITY_INCREMENT ] ; System . arraycopy ( forwardReferences , 0 , newValues , 0 , forwardReferences . length ) ; forwardReferences = newValues ; } forwardReferences [ ++ lastElementIndex ] = sourceInsnBytecodeOffset ; forwardReferences [ ++ lastElementIndex ] = referenceType | referenceHandle ; forwardReferences [ 0 ] = lastElementIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the bytecode offset of this label to the given value and resolves the forward references to this label if any . This method must be called when this label is added to the bytecode of the method i . e . when its bytecode offset becomes known . This method fills in the blanks that where left in the bytecode by each forward reference previously added to this label . [CODESPLIT] final boolean resolve ( final byte [ ] code , final int bytecodeOffset ) { this . flags |= FLAG_RESOLVED ; this . bytecodeOffset = bytecodeOffset ; if ( forwardReferences == null ) { return false ; } boolean hasAsmInstructions = false ; for ( int i = forwardReferences [ 0 ] ; i > 0 ; i -= 2 ) { final int sourceInsnBytecodeOffset = forwardReferences [ i - 1 ] ; final int reference = forwardReferences [ i ] ; final int relativeOffset = bytecodeOffset - sourceInsnBytecodeOffset ; int handle = reference & FORWARD_REFERENCE_HANDLE_MASK ; if ( ( reference & FORWARD_REFERENCE_TYPE_MASK ) == FORWARD_REFERENCE_TYPE_SHORT ) { if ( relativeOffset < Short . MIN_VALUE || relativeOffset > Short . MAX_VALUE ) { // Change the opcode of the jump instruction, in order to be able to find it later in // ClassReader. These ASM specific opcodes are similar to jump instruction opcodes, except // that the 2 bytes offset is unsigned (and can therefore represent values from 0 to // 65535, which is sufficient since the size of a method is limited to 65535 bytes). int opcode = code [ sourceInsnBytecodeOffset ] & 0xFF ; if ( opcode < Opcodes . IFNULL ) { // Change IFEQ ... JSR to ASM_IFEQ ... ASM_JSR. code [ sourceInsnBytecodeOffset ] = ( byte ) ( opcode + Constants . ASM_OPCODE_DELTA ) ; } else { // Change IFNULL and IFNONNULL to ASM_IFNULL and ASM_IFNONNULL. code [ sourceInsnBytecodeOffset ] = ( byte ) ( opcode + Constants . ASM_IFNULL_OPCODE_DELTA ) ; } hasAsmInstructions = true ; } code [ handle ++ ] = ( byte ) ( relativeOffset >>> 8 ) ; code [ handle ] = ( byte ) relativeOffset ; } else { code [ handle ++ ] = ( byte ) ( relativeOffset >>> 24 ) ; code [ handle ++ ] = ( byte ) ( relativeOffset >>> 16 ) ; code [ handle ++ ] = ( byte ) ( relativeOffset >>> 8 ) ; code [ handle ] = ( byte ) relativeOffset ; } } return hasAsmInstructions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the basic blocks that belong to the subroutine starting with the basic block corresponding to this label and marks these blocks as belonging to this subroutine . This method follows the control flow graph to find all the blocks that are reachable from the current basic block WITHOUT following any jsr target . [CODESPLIT] final void markSubroutine ( final short subroutineId ) { // Data flow algorithm: put this basic block in a list of blocks to process (which are blocks // belonging to subroutine subroutineId) and, while there are blocks to process, remove one from // the list, mark it as belonging to the subroutine, and add its successor basic blocks in the // control flow graph to the list of blocks to process (if not already done). Label listOfBlocksToProcess = this ; listOfBlocksToProcess . nextListElement = EMPTY_LIST ; while ( listOfBlocksToProcess != EMPTY_LIST ) { // Remove a basic block from the list of blocks to process. Label basicBlock = listOfBlocksToProcess ; listOfBlocksToProcess = listOfBlocksToProcess . nextListElement ; basicBlock . nextListElement = null ; // If it is not already marked as belonging to a subroutine, mark it as belonging to // subroutineId and add its successors to the list of blocks to process (unless already done). if ( basicBlock . subroutineId == 0 ) { basicBlock . subroutineId = subroutineId ; listOfBlocksToProcess = basicBlock . pushSuccessors ( listOfBlocksToProcess ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the basic blocks that end a subroutine starting with the basic block corresponding to this label and for each one of them adds an outgoing edge to the basic block following the given subroutine call . In other words completes the control flow graph by adding the edges corresponding to the return from this subroutine when called from the given caller basic block . [CODESPLIT] final void addSubroutineRetSuccessors ( final Label subroutineCaller ) { // Data flow algorithm: put this basic block in a list blocks to process (which are blocks // belonging to a subroutine starting with this label) and, while there are blocks to process, // remove one from the list, put it in a list of blocks that have been processed, add a return // edge to the successor of subroutineCaller if applicable, and add its successor basic blocks // in the control flow graph to the list of blocks to process (if not already done). Label listOfProcessedBlocks = EMPTY_LIST ; Label listOfBlocksToProcess = this ; listOfBlocksToProcess . nextListElement = EMPTY_LIST ; while ( listOfBlocksToProcess != EMPTY_LIST ) { // Move a basic block from the list of blocks to process to the list of processed blocks. Label basicBlock = listOfBlocksToProcess ; listOfBlocksToProcess = basicBlock . nextListElement ; basicBlock . nextListElement = listOfProcessedBlocks ; listOfProcessedBlocks = basicBlock ; // Add an edge from this block to the successor of the caller basic block, if this block is // the end of a subroutine and if this block and subroutineCaller do not belong to the same // subroutine. if ( ( basicBlock . flags & FLAG_SUBROUTINE_END ) != 0 && basicBlock . subroutineId != subroutineCaller . subroutineId ) { basicBlock . outgoingEdges = new Edge ( basicBlock . outputStackSize , // By construction, the first outgoing edge of a basic block that ends with a jsr // instruction leads to the jsr continuation block, i.e. where execution continues // when ret is called (see {@link #FLAG_SUBROUTINE_CALLER}). subroutineCaller . outgoingEdges . successor , basicBlock . outgoingEdges ) ; } // Add its successors to the list of blocks to process. Note that {@link #pushSuccessors} does // not push basic blocks which are already in a list. Here this means either in the list of // blocks to process, or in the list of already processed blocks. This second list is // important to make sure we don't reprocess an already processed block. listOfBlocksToProcess = basicBlock . pushSuccessors ( listOfBlocksToProcess ) ; } // Reset the {@link #nextListElement} of all the basic blocks that have been processed to null, // so that this method can be called again with a different subroutine or subroutine caller. while ( listOfProcessedBlocks != EMPTY_LIST ) { Label newListOfProcessedBlocks = listOfProcessedBlocks . nextListElement ; listOfProcessedBlocks . nextListElement = null ; listOfProcessedBlocks = newListOfProcessedBlocks ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the successors of this label in the method s control flow graph ( except those corresponding to a jsr target and those already in a list of labels ) to the given list of blocks to process and returns the new list . [CODESPLIT] private Label pushSuccessors ( final Label listOfLabelsToProcess ) { Label newListOfLabelsToProcess = listOfLabelsToProcess ; Edge outgoingEdge = outgoingEdges ; while ( outgoingEdge != null ) { // By construction, the second outgoing edge of a basic block that ends with a jsr instruction // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). boolean isJsrTarget = ( flags & Label . FLAG_SUBROUTINE_CALLER ) != 0 && outgoingEdge == outgoingEdges . nextEdge ; if ( ! isJsrTarget && outgoingEdge . successor . nextListElement == null ) { // Add this successor to the list of blocks to process, if it does not already belong to a // list of labels. outgoingEdge . successor . nextListElement = newListOfLabelsToProcess ; newListOfLabelsToProcess = outgoingEdge . successor ; } outgoingEdge = outgoingEdge . nextEdge ; } return newListOfLabelsToProcess ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare digits at certain position in two strings . The longest run of digits wins . That aside the greatest value wins . [CODESPLIT] protected int [ ] compareDigits ( final String str1 , int ndx1 , final String str2 , int ndx2 ) { // iterate all digits in the first string int zeroCount1 = 0 ; while ( charAt ( str1 , ndx1 ) == ' ' ) { zeroCount1 ++ ; ndx1 ++ ; } int len1 = 0 ; while ( true ) { final char char1 = charAt ( str1 , ndx1 ) ; final boolean isDigitChar1 = CharUtil . isDigit ( char1 ) ; if ( ! isDigitChar1 ) { break ; } len1 ++ ; ndx1 ++ ; } // iterate all digits in the second string and compare with the first int zeroCount2 = 0 ; while ( charAt ( str2 , ndx2 ) == ' ' ) { zeroCount2 ++ ; ndx2 ++ ; } int len2 = 0 ; int ndx1_new = ndx1 - len1 ; int equalNumbers = 0 ; while ( true ) { final char char2 = charAt ( str2 , ndx2 ) ; final boolean isDigitChar2 = CharUtil . isDigit ( char2 ) ; if ( ! isDigitChar2 ) { break ; } if ( equalNumbers == 0 && ( ndx1_new < ndx1 ) ) { equalNumbers = charAt ( str1 , ndx1_new ++ ) - char2 ; } len2 ++ ; ndx2 ++ ; } // compare if ( len1 != len2 ) { // numbers are not equals size return new int [ ] { len1 - len2 } ; } if ( equalNumbers != 0 ) { return new int [ ] { equalNumbers } ; } // numbers are equal, but number of zeros is different return new int [ ] { 0 , zeroCount1 - zeroCount2 , ndx1 , ndx2 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fixes accent char . [CODESPLIT] private char fixAccent ( final char c ) { for ( int i = 0 ; i < ACCENT_CHARS . length ; i += 2 ) { final char accentChar = ACCENT_CHARS [ i ] ; if ( accentChar == c ) { return ACCENT_CHARS [ i + 1 ] ; } } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safe { [CODESPLIT] private static char charAt ( final String string , final int ndx ) { if ( ndx >= string . length ( ) ) { return 0 ; } return string . charAt ( ndx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a byte into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] public ByteVector putByte ( final int byteValue ) { int currentLength = length ; if ( currentLength + 1 > data . length ) { enlarge ( 1 ) ; } data [ currentLength ++ ] = ( byte ) byteValue ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts two bytes into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] final ByteVector put11 ( final int byteValue1 , final int byteValue2 ) { int currentLength = length ; if ( currentLength + 2 > data . length ) { enlarge ( 2 ) ; } byte [ ] currentData = data ; currentData [ currentLength ++ ] = ( byte ) byteValue1 ; currentData [ currentLength ++ ] = ( byte ) byteValue2 ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a short into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] public ByteVector putShort ( final int shortValue ) { int currentLength = length ; if ( currentLength + 2 > data . length ) { enlarge ( 2 ) ; } byte [ ] currentData = data ; currentData [ currentLength ++ ] = ( byte ) ( shortValue >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) shortValue ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a byte and a short into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] final ByteVector put12 ( final int byteValue , final int shortValue ) { int currentLength = length ; if ( currentLength + 3 > data . length ) { enlarge ( 3 ) ; } byte [ ] currentData = data ; currentData [ currentLength ++ ] = ( byte ) byteValue ; currentData [ currentLength ++ ] = ( byte ) ( shortValue >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) shortValue ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts two bytes and a short into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] final ByteVector put112 ( final int byteValue1 , final int byteValue2 , final int shortValue ) { int currentLength = length ; if ( currentLength + 4 > data . length ) { enlarge ( 4 ) ; } byte [ ] currentData = data ; currentData [ currentLength ++ ] = ( byte ) byteValue1 ; currentData [ currentLength ++ ] = ( byte ) byteValue2 ; currentData [ currentLength ++ ] = ( byte ) ( shortValue >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) shortValue ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts an int into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] public ByteVector putInt ( final int intValue ) { int currentLength = length ; if ( currentLength + 4 > data . length ) { enlarge ( 4 ) ; } byte [ ] currentData = data ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 24 ) ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 16 ) ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) intValue ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts one byte and two shorts into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] final ByteVector put122 ( final int byteValue , final int shortValue1 , final int shortValue2 ) { int currentLength = length ; if ( currentLength + 5 > data . length ) { enlarge ( 5 ) ; } byte [ ] currentData = data ; currentData [ currentLength ++ ] = ( byte ) byteValue ; currentData [ currentLength ++ ] = ( byte ) ( shortValue1 >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) shortValue1 ; currentData [ currentLength ++ ] = ( byte ) ( shortValue2 >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) shortValue2 ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a long into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] public ByteVector putLong ( final long longValue ) { int currentLength = length ; if ( currentLength + 8 > data . length ) { enlarge ( 8 ) ; } byte [ ] currentData = data ; int intValue = ( int ) ( longValue >>> 32 ) ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 24 ) ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 16 ) ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) intValue ; intValue = ( int ) longValue ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 24 ) ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 16 ) ; currentData [ currentLength ++ ] = ( byte ) ( intValue >>> 8 ) ; currentData [ currentLength ++ ] = ( byte ) intValue ; length = currentLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts an array of bytes into this byte vector . The byte vector is automatically enlarged if necessary . [CODESPLIT] public ByteVector putByteArray ( final byte [ ] byteArrayValue , final int byteOffset , final int byteLength ) { if ( length + byteLength > data . length ) { enlarge ( byteLength ) ; } if ( byteArrayValue != null ) { System . arraycopy ( byteArrayValue , byteOffset , data , length , byteLength ) ; } length += byteLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enlarges this byte vector so that it can receive size more bytes . [CODESPLIT] private void enlarge ( final int size ) { int doubleCapacity = 2 * data . length ; int minimalCapacity = length + size ; byte [ ] newData = new byte [ doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity ] ; System . arraycopy ( data , 0 , newData , 0 , length ) ; data = newData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to authenticate user via HTTP session . Returns the token if user is authenticated . Returned token may be rotated . [CODESPLIT] protected T authenticateUserViaHttpSession ( final ActionRequest actionRequest ) { final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; final UserSession < T > userSession = UserSession . get ( servletRequest ) ; if ( userSession == null ) { return null ; } final T authToken = userSession . getAuthToken ( ) ; if ( authToken == null ) { return null ; } // granted final T newAuthToken = userAuth ( ) . rotateToken ( authToken ) ; if ( newAuthToken != authToken ) { final UserSession < T > newUserSesion = new UserSession <> ( newAuthToken , userAuth ( ) . tokenValue ( newAuthToken ) ) ; newUserSesion . start ( servletRequest , actionRequest . getHttpServletResponse ( ) ) ; } return newAuthToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to authenticate user via token . Returns the token if user is authenticated . Returned token may be rotated . [CODESPLIT] protected T authenticateUserViaToken ( final ActionRequest actionRequest ) { final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; // then try the auth token final String token = ServletUtil . resolveAuthBearerToken ( servletRequest ) ; if ( token == null ) { return null ; } final T authToken = userAuth ( ) . validateToken ( token ) ; if ( authToken == null ) { return null ; } // granted final T newAuthToken = userAuth ( ) . rotateToken ( authToken ) ; actionRequest . getHttpServletResponse ( ) . setHeader ( \"Authentication\" , \"Bearer: \" + userAuth ( ) . tokenValue ( newAuthToken ) ) ; return newAuthToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tires to authenticate user via the basic authentication . Returns the token if user is authenticated . [CODESPLIT] protected T authenticateUserViaBasicAuth ( final ActionRequest actionRequest ) { final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; final String username = ServletUtil . resolveAuthUsername ( servletRequest ) ; if ( username == null ) { return null ; } final String password = ServletUtil . resolveAuthPassword ( servletRequest ) ; final T authToken = userAuth ( ) . login ( username , password ) ; if ( authToken == null ) { return null ; } return authToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Ref get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getRef ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Ref value , final int dbSqlType ) throws SQLException { st . setRef ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates indexedTextName ( collection [ * ] ) if applicable . [CODESPLIT] private String calcIndexKey ( final String key ) { String indexedKey = null ; if ( key . indexOf ( ' ' ) != - 1 ) { int i = - 1 ; indexedKey = key ; while ( ( i = indexedKey . indexOf ( ' ' , i + 1 ) ) != - 1 ) { int j = indexedKey . indexOf ( ' ' , i ) ; String a = indexedKey . substring ( 0 , i ) ; String b = indexedKey . substring ( j ) ; indexedKey = a + \"[*\" + b ; } } return indexedKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds messages in the provided bundle . If message not found all parent bundles will be examined until the root bundle . At the end if still no success all default bundles will be examined . Returns <code > null< / code > if key is not found . [CODESPLIT] public String findMessage ( String bundleName , final Locale locale , final String key ) { String indexedKey = calcIndexKey ( key ) ; // hierarchy String name = bundleName ; while ( true ) { String msg = getMessage ( name , locale , key , indexedKey ) ; if ( msg != null ) { return msg ; } if ( bundleName == null || bundleName . length ( ) == 0 ) { break ; } int ndx = bundleName . lastIndexOf ( ' ' ) ; if ( ndx == - 1 ) { bundleName = null ; name = fallbackBundlename ; } else { bundleName = bundleName . substring ( 0 , ndx ) ; name = bundleName + ' ' + fallbackBundlename ; } } // default bundles for ( String bname : defaultBundles ) { String msg = getMessage ( bname , locale , key , indexedKey ) ; if ( msg != null ) { return msg ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds message in default bundles only starting from fallback bundlename . [CODESPLIT] public String findDefaultMessage ( final Locale locale , final String key ) { String indexedKey = calcIndexKey ( key ) ; String msg = getMessage ( fallbackBundlename , locale , key , indexedKey ) ; if ( msg != null ) { return msg ; } for ( String bname : defaultBundles ) { msg = getMessage ( bname , locale , key , indexedKey ) ; if ( msg != null ) { return msg ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the message from the named resource bundle . Performs the failback only when bundle name or locale are not specified ( i . e . are <code > null< / code > ) . [CODESPLIT] public String getMessage ( final String bundleName , final Locale locale , final String key ) { ResourceBundle bundle = findResourceBundle ( bundleName , locale ) ; if ( bundle == null ) { return null ; } /*\t\t//jdk6:\n\t\tif (bundle.containsKey(key) == false) {\n\t\t\treturn null;\n\t\t}\n*/ try { return bundle . getString ( key ) ; } catch ( MissingResourceException mrex ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds resource bundle by it s name . Missed and founded resource bundles are cached for better performances . Returns <code > null< / code > if resource bundle is missing . [CODESPLIT] public ResourceBundle findResourceBundle ( String bundleName , Locale locale ) { if ( bundleName == null ) { bundleName = fallbackBundlename ; } if ( locale == null ) { locale = fallbackLocale ; } if ( ! cacheResourceBundles ) { try { return getBundle ( bundleName , locale , ClassLoaderUtil . getDefaultClassLoader ( ) ) ; } catch ( MissingResourceException ignore ) { return null ; } } String key = bundleName + ' ' + locale . toLanguageTag ( ) ; try { if ( ! misses . contains ( key ) ) { ResourceBundle bundle = notmisses . get ( key ) ; if ( bundle == null ) { bundle = getBundle ( bundleName , locale , ClassLoaderUtil . getDefaultClassLoader ( ) ) ; notmisses . put ( key , bundle ) ; } return bundle ; } } catch ( MissingResourceException ignore ) { misses . add ( key ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns specified bundle . Invoked every time if cache is disabled . Input arguments are always valid . [CODESPLIT] protected ResourceBundle getBundle ( final String bundleName , final Locale locale , final ClassLoader classLoader ) { return ResourceBundle . getBundle ( bundleName , locale , classLoader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns array s element at given index . [CODESPLIT] protected K get ( final K [ ] array , final int index ) { return ( K ) Array . get ( array , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if entity is persistent . [CODESPLIT] protected < E > boolean isPersistent ( final DbEntityDescriptor < E > ded , final E entity ) { final Object key = ded . getIdValue ( entity ) ; if ( key == null ) { return false ; } if ( key instanceof Number ) { final long value = ( ( Number ) key ) . longValue ( ) ; if ( value == 0 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets new ID value for entity . [CODESPLIT] protected < E , ID > void setEntityId ( final DbEntityDescriptor < E > ded , final E entity , final ID newIdValue ) { ded . setIdValue ( entity , newIdValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves or updates entity . If ID is not <code > null< / code > entity will be updated . Otherwise entity will be inserted into the database . [CODESPLIT] public < E > E store ( final E entity ) { final Class type = entity . getClass ( ) ; final DbEntityDescriptor ded = dbOom . entityManager ( ) . lookupType ( type ) ; if ( ded == null ) { throw new DbOomException ( \"Not an entity: \" + type ) ; } if ( ! isPersistent ( ded , entity ) ) { final DbQuery q ; if ( dbOom . config ( ) . isKeysGeneratedByDatabase ( ) ) { q = query ( dbOom . entities ( ) . insert ( entity ) ) ; q . setGeneratedKey ( ) ; q . executeUpdate ( ) ; final Object nextId = q . getGeneratedKey ( ) ; setEntityId ( ded , entity , nextId ) ; } else { final Object nextId = generateNextId ( ded ) ; setEntityId ( ded , entity , nextId ) ; q = query ( dbOom . entities ( ) . insert ( entity ) ) ; q . executeUpdate ( ) ; } q . close ( ) ; } else { query ( dbOom . entities ( ) . updateAll ( entity ) ) . autoClose ( ) . executeUpdate ( ) ; } return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simply inserts object into the database . [CODESPLIT] public void save ( final Object entity ) { final DbQuery q = query ( dbOom . entities ( ) . insert ( entity ) ) ; q . autoClose ( ) . executeUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates single entity . [CODESPLIT] public void update ( final Object entity ) { query ( dbOom . entities ( ) . updateAll ( entity ) ) . autoClose ( ) . executeUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates single property in database and in the bean . [CODESPLIT] public < E > E updateProperty ( final E entity , final String name , final Object newValue ) { query ( dbOom . entities ( ) . updateColumn ( entity , name , newValue ) ) . autoClose ( ) . executeUpdate ( ) ; BeanUtil . declared . setProperty ( entity , name , newValue ) ; return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates property in the database by storing the current property value . [CODESPLIT] public < E > E updateProperty ( final E entity , final String name ) { Object value = BeanUtil . declared . getProperty ( entity , name ) ; query ( dbOom . entities ( ) . updateColumn ( entity , name , value ) ) . autoClose ( ) . executeUpdate ( ) ; return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds single entity by its id . [CODESPLIT] public < E , ID > E findById ( final Class < E > entityType , final ID id ) { return query ( dbOom . entities ( ) . findById ( entityType , id ) ) . autoClose ( ) . find ( entityType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds single entity by matching property . [CODESPLIT] public < E > E findOneByProperty ( final Class < E > entityType , final String name , final Object value ) { return query ( dbOom . entities ( ) . findByColumn ( entityType , name , value ) ) . autoClose ( ) . find ( entityType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds one entity for given criteria . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public < E > E findOne ( final Object criteria ) { return ( E ) query ( dbOom . entities ( ) . find ( criteria ) ) . autoClose ( ) . find ( criteria . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds list of entities matching given criteria . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public < E > List < E > find ( final Object criteria ) { return query ( dbOom . entities ( ) . find ( criteria ) ) . autoClose ( ) . list ( criteria . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds list of entities matching given criteria . [CODESPLIT] public < E > List < E > find ( final Class < E > entityType , final Object criteria ) { return query ( dbOom . entities ( ) . find ( entityType , criteria ) ) . autoClose ( ) . list ( entityType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deleted single entity by its id . [CODESPLIT] public < ID > void deleteById ( final Class entityType , final ID id ) { query ( dbOom . entities ( ) . deleteById ( entityType , id ) ) . autoClose ( ) . executeUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete single object by its id . Resets ID value . [CODESPLIT] public void deleteById ( final Object entity ) { if ( entity != null ) { int result = query ( dbOom . entities ( ) . deleteById ( entity ) ) . autoClose ( ) . executeUpdate ( ) ; if ( result != 0 ) { // now reset the ID value Class type = entity . getClass ( ) ; DbEntityDescriptor ded = dbOom . entityManager ( ) . lookupType ( type ) ; setEntityId ( ded , entity , 0 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Counts number of all entities . [CODESPLIT] public long count ( final Class entityType ) { return query ( dbOom . entities ( ) . count ( entityType ) ) . autoClose ( ) . executeCount ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increases a property . [CODESPLIT] public < ID > void increaseProperty ( final Class entityType , final ID id , final String name , final Number delta ) { query ( dbOom . entities ( ) . increaseColumn ( entityType , id , name , delta , true ) ) . autoClose ( ) . executeUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decreases a property . [CODESPLIT] public < ID > void decreaseProperty ( final Class entityType , final ID id , final String name , final Number delta ) { query ( dbOom . entities ( ) . increaseColumn ( entityType , id , name , delta , false ) ) . autoClose ( ) . executeUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds related entity . [CODESPLIT] public < E > List < E > findRelated ( final Class < E > target , final Object source ) { return query ( dbOom . entities ( ) . findForeign ( target , source ) ) . autoClose ( ) . list ( target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List all entities . [CODESPLIT] public < E > List < E > listAll ( final Class < E > target ) { return query ( dbOom . entities ( ) . from ( target ) ) . autoClose ( ) . list ( target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if parent node tag can be closed implicitly . [CODESPLIT] public boolean implicitlyCloseParentTagOnNewTag ( String parentNodeName , String nodeName ) { if ( parentNodeName == null ) { return false ; } parentNodeName = parentNodeName . toLowerCase ( ) ; nodeName = nodeName . toLowerCase ( ) ; for ( int i = 0 ; i < IMPLIED_ON_START . length ; i += 2 ) { if ( StringUtil . equalsOne ( parentNodeName , IMPLIED_ON_START [ i ] ) != - 1 ) { if ( StringUtil . equalsOne ( nodeName , IMPLIED_ON_START [ i + 1 ] ) != - 1 ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if current end tag ( node name ) closes the parent tag . [CODESPLIT] public boolean implicitlyCloseParentTagOnTagEnd ( String parentNodeName , String nodeName ) { if ( parentNodeName == null ) { return false ; } parentNodeName = parentNodeName . toLowerCase ( ) ; nodeName = nodeName . toLowerCase ( ) ; for ( int i = 0 ; i < IMPLIED_ON_END . length ; i += 2 ) { if ( StringUtil . equalsOne ( nodeName , IMPLIED_ON_END [ i ] ) != - 1 ) { if ( StringUtil . equalsOne ( parentNodeName , IMPLIED_ON_END [ i + 1 ] ) != - 1 ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if tag should be closed on EOF . [CODESPLIT] public boolean implicitlyCloseTagOnEOF ( String nodeName ) { if ( nodeName == null ) { return false ; } nodeName = nodeName . toLowerCase ( ) ; return StringUtil . equalsOne ( nodeName , CLOSED_ON_EOF ) != - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all attributes from the request as well as clears entries in this map . [CODESPLIT] @ Override public void clear ( ) { entries = null ; Iterator < String > keys = getAttributeNames ( ) ; while ( keys . hasNext ( ) ) { removeAttribute ( keys . next ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Set of attributes from the http request . [CODESPLIT] @ Override public Set < Entry < String , Object > > entrySet ( ) { if ( entries == null ) { entries = new HashSet <> ( ) ; Iterator < String > iterator = getAttributeNames ( ) ; while ( iterator . hasNext ( ) ) { final String key = iterator . next ( ) ; final Object value = getAttribute ( key ) ; entries . add ( new Entry < String , Object > ( ) { @ Override public boolean equals ( final Object obj ) { if ( obj == null ) { return false ; } if ( this . getClass ( ) != obj . getClass ( ) ) { return false ; } Entry entry = ( Entry ) obj ; return ( ( key == null ) ? ( entry . getKey ( ) == null ) : key . equals ( entry . getKey ( ) ) ) && ( ( value == null ) ? ( entry . getValue ( ) == null ) : value . equals ( entry . getValue ( ) ) ) ; } @ Override public int hashCode ( ) { return ( ( key == null ) ? 0 : key . hashCode ( ) ) ^ ( ( value == null ) ? 0 : value . hashCode ( ) ) ; } @ Override public String getKey ( ) { return key ; } @ Override public Object getValue ( ) { return value ; } @ Override public Object setValue ( final Object obj ) { setAttribute ( key , obj ) ; return value ; } } ) ; } } return entries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an attribute in the request . [CODESPLIT] @ Override public Object put ( final String key , final Object value ) { entries = null ; Object previous = get ( key ) ; setAttribute ( key , value ) ; return previous ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified request attribute . [CODESPLIT] @ Override public Object remove ( final Object key ) { entries = null ; Object value = get ( key ) ; removeAttribute ( key . toString ( ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns current stack trace in form of array of stack trace elements . First stack trace element is removed . Since an exception is thrown internally this method is slow . [CODESPLIT] @ SuppressWarnings ( { \"ThrowCaughtLocally\" } ) public static StackTraceElement [ ] getCurrentStackTrace ( ) { StackTraceElement [ ] ste = new Exception ( ) . getStackTrace ( ) ; if ( ste . length > 1 ) { StackTraceElement [ ] result = new StackTraceElement [ ste . length - 1 ] ; System . arraycopy ( ste , 1 , result , 0 , ste . length - 1 ) ; return result ; } else { return ste ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns stack trace filtered by class names . [CODESPLIT] public static StackTraceElement [ ] getStackTrace ( final Throwable t , final String [ ] allow , final String [ ] deny ) { StackTraceElement [ ] st = t . getStackTrace ( ) ; ArrayList < StackTraceElement > result = new ArrayList <> ( st . length ) ; elementLoop : for ( StackTraceElement element : st ) { String className = element . getClassName ( ) ; if ( allow != null ) { boolean validElemenet = false ; for ( String filter : allow ) { if ( className . contains ( filter ) ) { validElemenet = true ; break ; } } if ( ! validElemenet ) { continue ; } } if ( deny != null ) { for ( String filter : deny ) { if ( className . contains ( filter ) ) { continue elementLoop ; } } } result . add ( element ) ; } st = new StackTraceElement [ result . size ( ) ] ; return result . toArray ( st ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns stack trace chain filtered by class names . [CODESPLIT] public static StackTraceElement [ ] [ ] getStackTraceChain ( Throwable t , final String [ ] allow , final String [ ] deny ) { ArrayList < StackTraceElement [ ] > result = new ArrayList <> ( ) ; while ( t != null ) { StackTraceElement [ ] stack = getStackTrace ( t , allow , deny ) ; result . add ( stack ) ; t = t . getCause ( ) ; } StackTraceElement [ ] [ ] allStacks = new StackTraceElement [ result . size ( ) ] [  ] ; for ( int i = 0 ; i < allStacks . length ; i ++ ) { allStacks [ i ] = result . get ( i ) ; } return allStacks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns exception chain starting from top up to root cause . [CODESPLIT] public static Throwable [ ] getExceptionChain ( Throwable throwable ) { ArrayList < Throwable > list = new ArrayList <> ( ) ; list . add ( throwable ) ; while ( ( throwable = throwable . getCause ( ) ) != null ) { list . add ( throwable ) ; } Throwable [ ] result = new Throwable [ list . size ( ) ] ; return list . toArray ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints stack trace into a String . [CODESPLIT] public static String exceptionStackTraceToString ( final Throwable t ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw , true ) ; t . printStackTrace ( pw ) ; StreamUtil . close ( pw ) ; StreamUtil . close ( sw ) ; return sw . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints full exception stack trace from top to root cause into a String . [CODESPLIT] public static String exceptionChainToString ( Throwable t ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw , true ) ; while ( t != null ) { t . printStackTrace ( pw ) ; t = t . getCause ( ) ; } StreamUtil . close ( pw ) ; StreamUtil . close ( sw ) ; return sw . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a message for the given base message and its cause . [CODESPLIT] public static String buildMessage ( final String message , Throwable cause ) { if ( cause != null ) { cause = getRootCause ( cause ) ; StringBuilder buf = new StringBuilder ( ) ; if ( message != null ) { buf . append ( message ) . append ( \"; \" ) ; } buf . append ( \"<--- \" ) . append ( cause ) ; return buf . toString ( ) ; } else { return message ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Introspects the <code > Throwable< / code > to obtain the root cause . <p > This method walks through the exception chain to the last element root of the tree and returns that exception . If no root cause found returns provided throwable . [CODESPLIT] public static Throwable getRootCause ( final Throwable throwable ) { Throwable cause = throwable . getCause ( ) ; if ( cause == null ) { return throwable ; } Throwable t = throwable ; // defend against (malicious?) circularity for ( int i = 0 ; i < 1000 ; i ++ ) { cause = t . getCause ( ) ; if ( cause == null ) { return t ; } t = cause ; } return throwable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds throwing cause in exception stack . Returns throwable object if cause class is matched . Otherwise returns <code > null< / code > . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static < T extends Throwable > T findCause ( Throwable throwable , final Class < T > cause ) { while ( throwable != null ) { if ( throwable . getClass ( ) . equals ( cause ) ) { return ( T ) throwable ; } throwable = throwable . getCause ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rolls up SQL exceptions by taking each proceeding exception and making it a child of the previous using the <code > setNextException< / code > method of SQLException . [CODESPLIT] public static SQLException rollupSqlExceptions ( final Collection < SQLException > exceptions ) { SQLException parent = null ; for ( SQLException exception : exceptions ) { if ( parent != null ) { exception . setNextException ( parent ) ; } parent = exception ; } return parent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > non - null< / code > message for a throwable . [CODESPLIT] public static String message ( final Throwable throwable ) { String message = throwable . getMessage ( ) ; if ( StringUtil . isBlank ( message ) ) { message = throwable . toString ( ) ; } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps exception to { [CODESPLIT] public static RuntimeException wrapToRuntimeException ( final Throwable throwable ) { if ( throwable instanceof RuntimeException ) { return ( RuntimeException ) throwable ; } return new RuntimeException ( throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unwraps invocation and undeclared exceptions to real cause . [CODESPLIT] public static Throwable unwrapThrowable ( final Throwable wrappedThrowable ) { Throwable unwrapped = wrappedThrowable ; while ( true ) { if ( unwrapped instanceof InvocationTargetException ) { unwrapped = ( ( InvocationTargetException ) unwrapped ) . getTargetException ( ) ; } else if ( unwrapped instanceof UndeclaredThrowableException ) { unwrapped = ( ( UndeclaredThrowableException ) unwrapped ) . getUndeclaredThrowable ( ) ; } else { return unwrapped ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut for checking the annotation on annotated element and returning either the values or { [CODESPLIT] public static JSONAnnotationValues of ( final AnnotationParser annotationParser , final AnnotatedElement annotatedElement ) { if ( ! annotationParser . hasAnnotationOn ( annotatedElement ) ) { return null ; } return new JSONAnnotationValues ( annotationParser . of ( annotatedElement ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses class name that matches madvoc - related names . [CODESPLIT] protected void registerAsConsumer ( final ClassScanner classScanner ) { classScanner . registerEntryConsumer ( classPathEntry -> { final String entryName = classPathEntry . name ( ) ; if ( entryName . endsWith ( actionClassSuffix ) ) { try { acceptActionClass ( classPathEntry . loadClass ( ) ) ; } catch ( Exception ex ) { log . debug ( \"Invalid Madvoc action, ignoring: \" + entryName ) ; } } else if ( classPathEntry . isTypeSignatureInUse ( MADVOC_COMPONENT_ANNOTATION ) ) { try { acceptMadvocComponentClass ( classPathEntry . loadClass ( ) ) ; } catch ( Exception ex ) { log . debug ( \"Invalid Madvoc component ignoring: {}\" + entryName ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if class should be examined for Madvoc annotations . Array anonymous primitive interfaces and so on should be ignored . Sometimes checking may fail due to e . g . <code > NoClassDefFoundError< / code > ; we should continue searching anyway . [CODESPLIT] protected boolean checkClass ( final Class clazz ) { try { if ( clazz . isAnonymousClass ( ) ) { return false ; } if ( clazz . isArray ( ) || clazz . isEnum ( ) ) { return false ; } if ( clazz . isInterface ( ) ) { return false ; } if ( clazz . isLocalClass ( ) ) { return false ; } if ( ( clazz . isMemberClass ( ) ^ Modifier . isStatic ( clazz . getModifiers ( ) ) ) ) { return false ; } if ( clazz . isPrimitive ( ) ) { return false ; } int modifiers = clazz . getModifiers ( ) ; if ( Modifier . isAbstract ( modifiers ) ) { return false ; } return true ; } catch ( Throwable ignore ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds action runtime configuration on founded action class . Action classes are annotated with { [CODESPLIT] @ SuppressWarnings ( \"NonConstantStringShouldBeStringBuffer\" ) protected void acceptActionClass ( final Class < ? > actionClass ) { if ( actionClass == null ) { return ; } if ( ! checkClass ( actionClass ) ) { return ; } if ( actionClass . getAnnotation ( MadvocAction . class ) == null ) { return ; } ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( actionClass ) ; MethodDescriptor [ ] allMethodDescriptors = cd . getAllMethodDescriptors ( ) ; for ( MethodDescriptor methodDescriptor : allMethodDescriptors ) { if ( ! methodDescriptor . isPublic ( ) ) { continue ; } // just public methods final Method method = methodDescriptor . getMethod ( ) ; final boolean hasAnnotation = actionConfigManager . hasActionAnnotationOn ( method ) ; if ( ! hasAnnotation ) { continue ; } webappConfigurations . add ( ( ) -> actionsManager . registerAction ( actionClass , method , null ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new Madvoc component . [CODESPLIT] protected void acceptMadvocComponentClass ( final Class componentClass ) { if ( componentClass == null ) { return ; } if ( ! checkClass ( componentClass ) ) { return ; } madvocComponents . add ( ( ) -> madvocContainer . registerComponent ( componentClass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns default class loader . By default it is { [CODESPLIT] public static ClassLoader getDefaultClassLoader ( ) { ClassLoader cl = getContextClassLoader ( ) ; if ( cl == null ) { Class callerClass = ClassUtil . getCallerClass ( 2 ) ; cl = callerClass . getClassLoader ( ) ; } return cl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns system class loader . [CODESPLIT] public static ClassLoader getSystemClassLoader ( ) { if ( System . getSecurityManager ( ) == null ) { return ClassLoader . getSystemClassLoader ( ) ; } else { return AccessController . doPrivileged ( ( PrivilegedAction < ClassLoader > ) ClassLoader :: getSystemClassLoader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns classpath item manifest or <code > null< / code > if not found . [CODESPLIT] public static Manifest getClasspathItemManifest ( final File classpathItem ) { Manifest manifest = null ; if ( classpathItem . isFile ( ) ) { FileInputStream fis = null ; try { fis = new FileInputStream ( classpathItem ) ; JarFile jar = new JarFile ( classpathItem ) ; manifest = jar . getManifest ( ) ; } catch ( IOException ignore ) { } finally { StreamUtil . close ( fis ) ; } } else { File metaDir = new File ( classpathItem , \"META-INF\" ) ; File manifestFile = null ; if ( metaDir . isDirectory ( ) ) { for ( String m : MANIFESTS ) { File mFile = new File ( metaDir , m ) ; if ( mFile . isFile ( ) ) { manifestFile = mFile ; break ; } } } if ( manifestFile != null ) { FileInputStream fis = null ; try { fis = new FileInputStream ( manifestFile ) ; manifest = new Manifest ( fis ) ; } catch ( IOException ignore ) { } finally { StreamUtil . close ( fis ) ; } } } return manifest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns base folder for classpath item . If item is a ( jar ) file its parent is returned . If item is a directory its name is returned . [CODESPLIT] public static String getClasspathItemBaseDir ( final File classpathItem ) { String base ; if ( classpathItem . isFile ( ) ) { base = classpathItem . getParent ( ) ; } else { base = classpathItem . toString ( ) ; } return base ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns default class path from all available <code > URLClassLoader< / code > in classloader hierarchy . The following is added to the classpath list : <ul > <li > file URLs from <code > URLClassLoader< / code > ( other URL protocols are ignored ) < / li > <li > inner entries from containing <b > manifest< / b > files ( if exist ) < / li > <li > bootstrap classpath is ignored< / li > < / ul > [CODESPLIT] public static File [ ] getDefaultClasspath ( ClassLoader classLoader ) { Set < File > classpaths = new TreeSet <> ( ) ; while ( classLoader != null ) { URL [ ] urls = ClassPathURLs . of ( classLoader , null ) ; if ( urls != null ) { for ( URL u : urls ) { File f = FileUtil . toContainerFile ( u ) ; if ( ( f != null ) && f . exists ( ) ) { try { f = f . getCanonicalFile ( ) ; boolean newElement = classpaths . add ( f ) ; if ( newElement ) { addInnerClasspathItems ( classpaths , f ) ; } } catch ( IOException ignore ) { } } } } classLoader = classLoader . getParent ( ) ; } File [ ] result = new File [ classpaths . size ( ) ] ; return classpaths . toArray ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves given resource as URL . Resource is always absolute and may starts with a slash character . <p > Resource will be loaded using class loaders in the following order : <ul > <li > { [CODESPLIT] public static URL getResourceUrl ( String resourceName , final ClassLoader classLoader ) { if ( resourceName . startsWith ( \"/\" ) ) { resourceName = resourceName . substring ( 1 ) ; } URL resourceUrl ; // try #1 - using provided class loader if ( classLoader != null ) { resourceUrl = classLoader . getResource ( resourceName ) ; if ( resourceUrl != null ) { return resourceUrl ; } } // try #2 - using thread class loader ClassLoader currentThreadClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( ( currentThreadClassLoader != null ) && ( currentThreadClassLoader != classLoader ) ) { resourceUrl = currentThreadClassLoader . getResource ( resourceName ) ; if ( resourceUrl != null ) { return resourceUrl ; } } // try #3 - using caller classloader, similar as Class.forName() Class callerClass = ClassUtil . getCallerClass ( 2 ) ; ClassLoader callerClassLoader = callerClass . getClassLoader ( ) ; if ( ( callerClassLoader != classLoader ) && ( callerClassLoader != currentThreadClassLoader ) ) { resourceUrl = callerClassLoader . getResource ( resourceName ) ; if ( resourceUrl != null ) { return resourceUrl ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a resource of the specified name for reading . [CODESPLIT] public static InputStream getResourceAsStream ( final String resourceName , final ClassLoader callingClass ) throws IOException { URL url = getResourceUrl ( resourceName , callingClass ) ; if ( url != null ) { return url . openStream ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a resource of the specified name for reading . Controls caching that is important when the same jar is reloaded using custom classloader . [CODESPLIT] public static InputStream getResourceAsStream ( final String resourceName , final ClassLoader callingClass , final boolean useCache ) throws IOException { URL url = getResourceUrl ( resourceName , callingClass ) ; if ( url != null ) { URLConnection urlConnection = url . openConnection ( ) ; urlConnection . setUseCaches ( useCache ) ; return urlConnection . getInputStream ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a class of the specified name for reading using class classloader . [CODESPLIT] public static InputStream getClassAsStream ( final Class clazz ) throws IOException { return getResourceAsStream ( ClassUtil . convertClassNameToFileName ( clazz ) , clazz . getClassLoader ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a class of the specified name for reading using provided class loader . [CODESPLIT] public static InputStream getClassAsStream ( final String className , final ClassLoader classLoader ) throws IOException { return getResourceAsStream ( ClassUtil . convertClassNameToFileName ( className ) , classLoader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a class using default class loader strategy . [CODESPLIT] public static Class loadClass ( final String className ) throws ClassNotFoundException { return ClassLoaderStrategy . get ( ) . loadClass ( className , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a class using default class loader strategy . [CODESPLIT] public static Class loadClass ( final String className , final ClassLoader classLoader ) throws ClassNotFoundException { return ClassLoaderStrategy . get ( ) . loadClass ( className , classLoader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new child to the tree . [CODESPLIT] public RouteChunk add ( final String newValue ) { RouteChunk routeChunk = new RouteChunk ( routes , this , newValue ) ; if ( children == null ) { children = new RouteChunk [ ] { routeChunk } ; } else { children = ArraysUtil . append ( children , routeChunk ) ; } return routeChunk ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds existing chunk or creates a new one if does not exist . [CODESPLIT] public RouteChunk findOrCreateChild ( final String value ) { if ( children != null ) { for ( RouteChunk child : children ) { if ( child . get ( ) . equals ( value ) ) { return child ; } } } return add ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public boolean match ( final String value ) { if ( pathMacros == null ) { return this . value . equals ( value ) ; } return pathMacros . match ( value ) != - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns new or existing instance of <code > MultipartRequest< / code > . [CODESPLIT] public static MultipartRequest getInstance ( final HttpServletRequest request , final FileUploadFactory fileUploadFactory , final String encoding ) throws IOException { MultipartRequest mreq = ( MultipartRequest ) request . getAttribute ( MREQ_ATTR_NAME ) ; if ( mreq == null ) { mreq = new MultipartRequest ( request , fileUploadFactory , encoding ) ; request . setAttribute ( MREQ_ATTR_NAME , mreq ) ; } if ( ! mreq . isParsed ( ) ) { mreq . parseRequest ( ) ; } return mreq ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if request if multi - part and parse it . If request is not multi - part it copies all parameters to make usage the same in both cases . [CODESPLIT] public void parseRequest ( ) throws IOException { if ( ServletUtil . isMultipartRequest ( request ) ) { parseRequestStream ( request . getInputStream ( ) , characterEncoding ) ; } else { Enumeration names = request . getParameterNames ( ) ; while ( names . hasMoreElements ( ) ) { String paramName = ( String ) names . nextElement ( ) ; String [ ] values = request . getParameterValues ( paramName ) ; putParameters ( paramName , values ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts object to destination type . Invoked before the value is set into destination . Throws <code > TypeConversionException< / code > if conversion fails . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected Object convertType ( final Object value , final Class type ) { return typeConverterManager . convertType ( value , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converter to collection . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected Object convertToCollection ( final Object value , final Class destinationType , final Class componentType ) { return typeConverterManager . convertToCollection ( value , destinationType , componentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes setter but first converts type to match the setter type . [CODESPLIT] protected Object invokeSetter ( final Setter setter , final BeanProperty bp , Object value ) { try { final MapperFunction setterMapperFunction = setter . getMapperFunction ( ) ; if ( setterMapperFunction != null ) { value = setterMapperFunction . apply ( value ) ; } final Class type = setter . getSetterRawType ( ) ; if ( ClassUtil . isTypeOf ( type , Collection . class ) ) { Class componentType = setter . getSetterRawComponentType ( ) ; value = convertToCollection ( value , type , componentType ) ; } else { // no collections value = convertType ( value , type ) ; } setter . invokeSetter ( bp . bean , value ) ; } catch ( Exception ex ) { if ( isSilent ) { return null ; } throw new BeanException ( \"Setter failed: \" + setter , ex ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the element of an array forced . If value is <code > null< / code > it will be instantiated . If not the last part of indexed bean property array will be expanded to the index if necessary . [CODESPLIT] protected Object arrayForcedGet ( final BeanProperty bp , Object array , final int index ) { Class componentType = array . getClass ( ) . getComponentType ( ) ; if ( ! bp . last ) { array = ensureArraySize ( bp , array , componentType , index ) ; } Object value = Array . get ( array , index ) ; if ( value == null ) { try { //noinspection unchecked value = ClassUtil . newInstance ( componentType ) ; } catch ( Exception ex ) { if ( isSilent ) { return null ; } throw new BeanException ( \"Invalid array element: \" + bp . name + ' ' + index + ' ' , bp , ex ) ; } Array . set ( array , index , value ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the array element forced . If index is greater then arrays length array will be expanded to the index . If speed is critical it is better to allocate an array with proper size before using this method . [CODESPLIT] protected void arrayForcedSet ( final BeanProperty bp , Object array , final int index , Object value ) { Class componentType = array . getClass ( ) . getComponentType ( ) ; array = ensureArraySize ( bp , array , componentType , index ) ; value = convertType ( value , componentType ) ; Array . set ( array , index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the very first next dot . Ignores dots between index brackets . Returns <code > - 1< / code > when dot is not found . [CODESPLIT] protected int indexOfDot ( final String name ) { int ndx = 0 ; int len = name . length ( ) ; boolean insideBracket = false ; while ( ndx < len ) { char c = name . charAt ( ndx ) ; if ( insideBracket ) { if ( c == ' ' ) { insideBracket = false ; } } else { if ( c == ' ' ) { return ndx ; } if ( c == ' ' ) { insideBracket = true ; } } ndx ++ ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract index string from non - nested property name . If index is found it is stripped from bean property name . If no index is found it returns <code > null< / code > . [CODESPLIT] protected String extractIndex ( final BeanProperty bp ) { bp . index = null ; String name = bp . name ; int lastNdx = name . length ( ) - 1 ; if ( lastNdx < 0 ) { return null ; } if ( name . charAt ( lastNdx ) == ' ' ) { int leftBracketNdx = name . lastIndexOf ( ' ' ) ; if ( leftBracketNdx != - 1 ) { bp . setName ( name . substring ( 0 , leftBracketNdx ) ) ; bp . index = name . substring ( leftBracketNdx + 1 , lastNdx ) ; return bp . index ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new instance for current property name through its setter . It uses default constructor! [CODESPLIT] protected Object createBeanProperty ( final BeanProperty bp ) { Setter setter = bp . getSetter ( true ) ; if ( setter == null ) { return null ; } Class type = setter . getSetterRawType ( ) ; Object newInstance ; try { newInstance = ClassUtil . newInstance ( type ) ; } catch ( Exception ex ) { if ( isSilent ) { return null ; } throw new BeanException ( \"Invalid property: \" + bp . name , bp , ex ) ; } newInstance = invokeSetter ( setter , bp , newInstance ) ; return newInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts generic component type of a property . Returns <code > Object . class< / code > when property does not have component . [CODESPLIT] protected Class extractGenericComponentType ( final Getter getter ) { Class componentType = null ; if ( getter != null ) { componentType = getter . getGetterRawComponentType ( ) ; } if ( componentType == null ) { componentType = Object . class ; } return componentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <b > Map< / b > index to key type . If conversion fails original value will be returned . [CODESPLIT] protected Object convertIndexToMapKey ( final Getter getter , final Object index ) { Class indexType = null ; if ( getter != null ) { indexType = getter . getGetterRawKeyComponentType ( ) ; } // check if set if ( indexType == null ) { indexType = Object . class ; // marker for no generic type } if ( indexType == Object . class ) { return index ; } try { return convertType ( index , indexType ) ; } catch ( Exception ignore ) { return index ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts type of current property . [CODESPLIT] protected Class extractType ( final BeanProperty bp ) { Getter getter = bp . getGetter ( isDeclared ) ; if ( getter != null ) { if ( bp . index != null ) { Class type = getter . getGetterRawComponentType ( ) ; return type == null ? Object . class : type ; } return getter . getGetterRawType ( ) ; } return null ; // this should not happens }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the user session from the HTTP session . Returns { [CODESPLIT] public static UserSession get ( final HttpServletRequest httpServletRequest ) { final HttpSession httpSession = httpServletRequest . getSession ( false ) ; if ( httpSession == null ) { return null ; } return ( UserSession ) httpSession . getAttribute ( AUTH_SESSION_NAME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the user session by removing it from the http session and invalidating the cookie . [CODESPLIT] public static void stop ( final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) { final HttpSession httpSession = servletRequest . getSession ( false ) ; if ( httpSession != null ) { httpSession . removeAttribute ( AUTH_SESSION_NAME ) ; } final Cookie cookie = ServletUtil . getCookie ( servletRequest , AUTH_COOKIE_NAME ) ; if ( cookie == null ) { return ; } cookie . setMaxAge ( 0 ) ; cookie . setPath ( \"/\" ) ; servletResponse . addCookie ( cookie ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts new user session . [CODESPLIT] public void start ( final HttpServletRequest httpServletRequest , final HttpServletResponse httpServletResponse ) { final HttpSession httpSession = httpServletRequest . getSession ( true ) ; httpSession . setAttribute ( AUTH_SESSION_NAME , this ) ; final Cookie cookie = new Cookie ( AUTH_COOKIE_NAME , authTokenValue ) ; //cookie.setDomain(SSORealm.SSO_DOMAIN); cookie . setMaxAge ( cookieMaxAge ) ; cookie . setPath ( \"/\" ) ; httpServletResponse . addCookie ( cookie ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts local date to Date . [CODESPLIT] public static Date toDate ( final LocalDate localDate ) { return Date . from ( localDate . atStartOfDay ( ZoneId . systemDefault ( ) ) . toInstant ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts local date time to Calendar . [CODESPLIT] public static Calendar toCalendar ( final LocalDateTime localDateTime ) { return GregorianCalendar . from ( ZonedDateTime . of ( localDateTime , ZoneId . systemDefault ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats time to HTTP date / time format . Note that number of milliseconds is lost . [CODESPLIT] public static String formatHttpDate ( final long millis ) { final Date date = new Date ( millis ) ; return HTTP_DATE_FORMAT . format ( date ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the HTTP date / time format . Returns <code > - 1< / code > if given string is invalid . [CODESPLIT] public static long parseHttpTime ( final String time ) { if ( time == null ) { return - 1 ; } try { return TimeUtil . HTTP_DATE_FORMAT . parse ( time ) . getTime ( ) ; } catch ( ParseException e ) { return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates new class . [CODESPLIT] public Class defineProxy ( final Class target ) { ProxyProxettaFactory builder = proxetta . proxy ( ) ; builder . setTarget ( target ) ; return builder . define ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds validation checks . [CODESPLIT] public void add ( final Check check ) { String name = check . getName ( ) ; List < Check > list = map . computeIfAbsent ( name , k -> new ArrayList <> ( ) ) ; list . add ( check ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve validation context for provided target class . [CODESPLIT] public static ValidationContext resolveFor ( final Class < ? > target ) { ValidationContext vc = new ValidationContext ( ) ; vc . addClassChecks ( target ) ; return vc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses class annotations and adds all checks . [CODESPLIT] public void addClassChecks ( final Class target ) { final List < Check > list = cache . get ( target , ( ) -> { final List < Check > newList = new ArrayList <> ( ) ; final ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( target ) ; final PropertyDescriptor [ ] allProperties = cd . getAllPropertyDescriptors ( ) ; for ( PropertyDescriptor propertyDescriptor : allProperties ) { collectPropertyAnnotationChecks ( newList , propertyDescriptor ) ; } return newList ; } ) ; addAll ( list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all annotations of provided properties . [CODESPLIT] protected void collectPropertyAnnotationChecks ( final List < Check > annChecks , final PropertyDescriptor propertyDescriptor ) { FieldDescriptor fd = propertyDescriptor . getFieldDescriptor ( ) ; if ( fd != null ) { Annotation [ ] annotations = fd . getField ( ) . getAnnotations ( ) ; collectAnnotationChecks ( annChecks , propertyDescriptor . getType ( ) , propertyDescriptor . getName ( ) , annotations ) ; } MethodDescriptor md = propertyDescriptor . getReadMethodDescriptor ( ) ; if ( md != null ) { Annotation [ ] annotations = md . getMethod ( ) . getAnnotations ( ) ; collectAnnotationChecks ( annChecks , propertyDescriptor . getType ( ) , propertyDescriptor . getName ( ) , annotations ) ; } md = propertyDescriptor . getWriteMethodDescriptor ( ) ; if ( md != null ) { Annotation [ ] annotations = md . getMethod ( ) . getAnnotations ( ) ; collectAnnotationChecks ( annChecks , propertyDescriptor . getType ( ) , propertyDescriptor . getName ( ) , annotations ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect annotations for some target . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) protected void collectAnnotationChecks ( final List < Check > annChecks , final Class targetType , final String targetName , final Annotation [ ] annotations ) { for ( Annotation annotation : annotations ) { Constraint c = annotation . annotationType ( ) . getAnnotation ( Constraint . class ) ; Class < ? extends ValidationConstraint > constraintClass ; if ( c == null ) { // if constraint is not available, try lookup String constraintClassName = annotation . annotationType ( ) . getName ( ) + \"Constraint\" ; try { constraintClass = ClassLoaderUtil . loadClass ( constraintClassName , this . getClass ( ) . getClassLoader ( ) ) ; } catch ( ClassNotFoundException ingore ) { continue ; } } else { constraintClass = c . value ( ) ; } ValidationConstraint vc ; try { vc = newConstraint ( constraintClass , targetType ) ; } catch ( Exception ex ) { throw new VtorException ( \"Invalid constraint: \" + constraintClass . getClass ( ) . getName ( ) , ex ) ; } vc . configure ( annotation ) ; Check check = new Check ( targetName , vc ) ; copyDefaultCheckProperties ( check , annotation ) ; annChecks . add ( check ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new constraint . The following rules are used : <ul > <li > use default constructor if exist . < / li > <li > otherwise use constructor with ValidationContext parameter . < / li > < / ul > [CODESPLIT] protected < V extends ValidationConstraint > V newConstraint ( final Class < V > constraint , final Class targetType ) throws Exception { Constructor < V > ctor ; try { ctor = constraint . getConstructor ( ) ; return ctor . newInstance ( ) ; } catch ( NoSuchMethodException ignore ) { ctor = constraint . getConstructor ( ValidationContext . class ) ; return ctor . newInstance ( resolveFor ( targetType ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies default properties from annotation to the check . [CODESPLIT] protected void copyDefaultCheckProperties ( final Check destCheck , final Annotation annotation ) { Integer severity = ( Integer ) ClassUtil . readAnnotationValue ( annotation , ANN_SEVERITY ) ; destCheck . setSeverity ( severity . intValue ( ) ) ; String [ ] profiles = ( String [ ] ) ClassUtil . readAnnotationValue ( annotation , ANN_PROFILES ) ; destCheck . setProfiles ( profiles ) ; String message = ( String ) ClassUtil . readAnnotationValue ( annotation , ANN_MESSAGE ) ; destCheck . setMessage ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public static < T > CompletableFuture < T > failAfter ( final long duration ) { final CompletableFuture < T > promise = new CompletableFuture <> ( ) ; SCHEDULER . schedule ( ( ) -> { final TimeoutException ex = new TimeoutException ( \"Timeout after \" + duration ) ; return promise . completeExceptionally ( ex ) ; } , duration , MILLISECONDS ) ; return promise ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Array get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getArray ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Array value , final int dbSqlType ) throws SQLException { st . setArray ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes single URI component . [CODESPLIT] private static String encodeUriComponent ( final String source , final String encoding , final URIPart uriPart ) { if ( source == null ) { return null ; } byte [ ] bytes = encodeBytes ( StringUtil . getBytes ( source , encoding ) , uriPart ) ; char [ ] chars = new char [ bytes . length ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { chars [ i ] = ( char ) bytes [ i ] ; } return new String ( chars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes byte array using allowed characters from { [CODESPLIT] private static byte [ ] encodeBytes ( final byte [ ] source , final URIPart uriPart ) { ByteArrayOutputStream bos = new ByteArrayOutputStream ( source . length ) ; for ( byte b : source ) { if ( b < 0 ) { b += 256 ; } if ( uriPart . isValid ( ( char ) b ) ) { bos . write ( b ) ; } else { bos . write ( ' ' ) ; char hex1 = Character . toUpperCase ( Character . forDigit ( ( b >> 4 ) & 0xF , 16 ) ) ; char hex2 = Character . toUpperCase ( Character . forDigit ( b & 0xF , 16 ) ) ; bos . write ( hex1 ) ; bos . write ( hex2 ) ; } } return bos . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes string using default RFCP rules . [CODESPLIT] public static String encode ( final String string , final String encoding ) { return encodeUriComponent ( string , encoding , URIPart . UNRESERVED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given URI scheme with the given encoding . [CODESPLIT] public static String encodeScheme ( final String scheme , final String encoding ) { return encodeUriComponent ( scheme , encoding , URIPart . SCHEME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given URI host with the given encoding . [CODESPLIT] public static String encodeHost ( final String host , final String encoding ) { return encodeUriComponent ( host , encoding , URIPart . HOST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given URI port with the given encoding . [CODESPLIT] public static String encodePort ( final String port , final String encoding ) { return encodeUriComponent ( port , encoding , URIPart . PORT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given URI path with the given encoding . [CODESPLIT] public static String encodePath ( final String path , final String encoding ) { return encodeUriComponent ( path , encoding , URIPart . PATH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given URI query with the given encoding . [CODESPLIT] public static String encodeQuery ( final String query , final String encoding ) { return encodeUriComponent ( query , encoding , URIPart . QUERY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given URI query parameter with the given encoding . [CODESPLIT] public static String encodeQueryParam ( final String queryParam , final String encoding ) { return encodeUriComponent ( queryParam , encoding , URIPart . QUERY_PARAM ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given URI fragment with the given encoding . [CODESPLIT] public static String encodeFragment ( final String fragment , final String encoding ) { return encodeUriComponent ( fragment , encoding , URIPart . FRAGMENT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given source URI into an encoded String . All various URI components are encoded according to their respective valid character sets . <p > This method does <b > not< / b > attempt to encode = and { [CODESPLIT] public static String encodeUri ( final String uri , final String encoding ) { Matcher m = URI_PATTERN . matcher ( uri ) ; if ( m . matches ( ) ) { String scheme = m . group ( 2 ) ; String authority = m . group ( 3 ) ; String userinfo = m . group ( 5 ) ; String host = m . group ( 6 ) ; String port = m . group ( 8 ) ; String path = m . group ( 9 ) ; String query = m . group ( 11 ) ; String fragment = m . group ( 13 ) ; return encodeUriComponents ( scheme , authority , userinfo , host , port , path , query , fragment , encoding ) ; } throw new IllegalArgumentException ( \"Invalid URI: \" + uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given HTTP URI into an encoded String . All various URI components are encoded according to their respective valid character sets . <p > This method does <b > not< / b > support fragments ( { [CODESPLIT] public static String encodeHttpUrl ( final String httpUrl , final String encoding ) { Matcher m = HTTP_URL_PATTERN . matcher ( httpUrl ) ; if ( m . matches ( ) ) { String scheme = m . group ( 1 ) ; String authority = m . group ( 2 ) ; String userinfo = m . group ( 4 ) ; String host = m . group ( 5 ) ; String portString = m . group ( 7 ) ; String path = m . group ( 8 ) ; String query = m . group ( 10 ) ; return encodeUriComponents ( scheme , authority , userinfo , host , portString , path , query , null , encoding ) ; } throw new IllegalArgumentException ( \"Invalid HTTP URL: \" + httpUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates URL builder with given path that can be optionally encoded . Since most of the time path is valid and does not require to be encoded use this method to gain some performance . When encoding flag is turned off provided path is used without processing . <p > The purpose of builder is to help with query parameters . All other URI parts should be set previously or after the URL is built . [CODESPLIT] public static Builder build ( final String path , final boolean encodePath ) { return new Builder ( path , encodePath , JoddCore . encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects all properties of target type . [CODESPLIT] protected HashMap < String , PropertyDescriptor > inspectProperties ( ) { boolean scanAccessible = classDescriptor . isScanAccessible ( ) ; Class type = classDescriptor . getType ( ) ; HashMap < String , PropertyDescriptor > map = new HashMap <> ( ) ; Method [ ] methods = scanAccessible ? ClassUtil . getAccessibleMethods ( type ) : ClassUtil . getSupportedMethods ( type ) ; for ( int iteration = 0 ; iteration < 2 ; iteration ++ ) { // first find the getters, and then the setters! for ( Method method : methods ) { if ( Modifier . isStatic ( method . getModifiers ( ) ) ) { continue ; // ignore static methods } boolean add = false ; boolean issetter = false ; String propertyName ; if ( iteration == 0 ) { propertyName = ClassUtil . getBeanPropertyGetterName ( method ) ; if ( propertyName != null ) { add = true ; issetter = false ; } } else { propertyName = ClassUtil . getBeanPropertySetterName ( method ) ; if ( propertyName != null ) { add = true ; issetter = true ; } } if ( add ) { MethodDescriptor methodDescriptor = classDescriptor . getMethodDescriptor ( method . getName ( ) , method . getParameterTypes ( ) , true ) ; addProperty ( map , propertyName , methodDescriptor , issetter ) ; } } } if ( classDescriptor . isIncludeFieldsAsProperties ( ) ) { FieldDescriptor [ ] fieldDescriptors = classDescriptor . getAllFieldDescriptors ( ) ; String [ ] prefix = classDescriptor . getPropertyFieldPrefix ( ) ; for ( FieldDescriptor fieldDescriptor : fieldDescriptors ) { Field field = fieldDescriptor . getField ( ) ; if ( Modifier . isStatic ( field . getModifiers ( ) ) ) { continue ; // ignore static fields } String name = field . getName ( ) ; if ( prefix != null ) { for ( String p : prefix ) { if ( ! name . startsWith ( p ) ) { continue ; } name = name . substring ( p . length ( ) ) ; break ; } } if ( ! map . containsKey ( name ) ) { // add missing field as a potential property map . put ( name , createPropertyDescriptor ( name , fieldDescriptor ) ) ; } } } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a setter and / or getter method to the property . If property is already defined the new updated definition will be created . [CODESPLIT] protected void addProperty ( final HashMap < String , PropertyDescriptor > map , final String name , final MethodDescriptor methodDescriptor , final boolean isSetter ) { MethodDescriptor setterMethod = isSetter ? methodDescriptor : null ; MethodDescriptor getterMethod = isSetter ? null : methodDescriptor ; PropertyDescriptor existing = map . get ( name ) ; if ( existing == null ) { // new property, just add it PropertyDescriptor propertyDescriptor = createPropertyDescriptor ( name , getterMethod , setterMethod ) ; map . put ( name , propertyDescriptor ) ; return ; } // property exist if ( ! isSetter ) { // use existing setter setterMethod = existing . getWriteMethodDescriptor ( ) ; // check existing MethodDescriptor existingMethodDescriptor = existing . getReadMethodDescriptor ( ) ; if ( existingMethodDescriptor != null ) { // check for special case of double get/is // getter with the same name already exist String methodName = methodDescriptor . getMethod ( ) . getName ( ) ; String existingMethodName = existingMethodDescriptor . getMethod ( ) . getName ( ) ; if ( existingMethodName . startsWith ( METHOD_IS_PREFIX ) && methodName . startsWith ( METHOD_GET_PREFIX ) ) { // ignore getter when ister exist return ; } } } else { // setter // use existing getter getterMethod = existing . getReadMethodDescriptor ( ) ; if ( getterMethod != null ) { Class returnType = getterMethod . getMethod ( ) . getReturnType ( ) ; if ( setterMethod != null ) { Class parameterType = setterMethod . getMethod ( ) . getParameterTypes ( ) [ 0 ] ; if ( returnType != parameterType ) { // getter's type is different then setter's return ; } } } } PropertyDescriptor propertyDescriptor = createPropertyDescriptor ( name , getterMethod , setterMethod ) ; map . put ( name , propertyDescriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { [CODESPLIT] protected PropertyDescriptor createPropertyDescriptor ( final String name , final MethodDescriptor getterMethod , final MethodDescriptor setterMethod ) { return new PropertyDescriptor ( classDescriptor , name , getterMethod , setterMethod ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new field - only { [CODESPLIT] protected PropertyDescriptor createPropertyDescriptor ( final String name , final FieldDescriptor fieldDescriptor ) { return new PropertyDescriptor ( classDescriptor , name , fieldDescriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all property descriptors . Properties are sorted by name . [CODESPLIT] public PropertyDescriptor [ ] getAllPropertyDescriptors ( ) { if ( allProperties == null ) { PropertyDescriptor [ ] allProperties = new PropertyDescriptor [ propertyDescriptors . size ( ) ] ; int index = 0 ; for ( PropertyDescriptor propertyDescriptor : propertyDescriptors . values ( ) ) { allProperties [ index ] = propertyDescriptor ; index ++ ; } Arrays . sort ( allProperties , new Comparator < PropertyDescriptor > ( ) { @ Override public int compare ( final PropertyDescriptor pd1 , final PropertyDescriptor pd2 ) { return pd1 . getName ( ) . compareTo ( pd2 . getName ( ) ) ; } } ) ; this . allProperties = allProperties ; } return allProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses location header to return the next location or returns { [CODESPLIT] public String location ( ) { String location = header ( \"location\" ) ; if ( location == null ) { return null ; } if ( location . startsWith ( StringPool . SLASH ) ) { location = getHttpRequest ( ) . hostUrl ( ) + location ; } return location ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns list of valid cookies sent from server . If no cookie found returns an empty array . Invalid cookies are ignored . [CODESPLIT] public Cookie [ ] cookies ( ) { List < String > newCookies = headers ( \"set-cookie\" ) ; if ( newCookies == null ) { return new Cookie [ 0 ] ; } List < Cookie > cookieList = new ArrayList <> ( newCookies . size ( ) ) ; for ( String cookieValue : newCookies ) { try { Cookie cookie = new Cookie ( cookieValue ) ; cookieList . add ( cookie ) ; } catch ( Exception ex ) { // ignore } } return cookieList . toArray ( new Cookie [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unzips GZip - ed body content removes the content - encoding header and sets the new content - length value . [CODESPLIT] public HttpResponse unzip ( ) { String contentEncoding = contentEncoding ( ) ; if ( contentEncoding != null && contentEncoding ( ) . equals ( \"gzip\" ) ) { if ( body != null ) { headerRemove ( HEADER_CONTENT_ENCODING ) ; try { ByteArrayInputStream in = new ByteArrayInputStream ( body . getBytes ( StringPool . ISO_8859_1 ) ) ; GZIPInputStream gzipInputStream = new GZIPInputStream ( in ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; StreamUtil . copy ( gzipInputStream , out ) ; body ( out . toString ( StringPool . ISO_8859_1 ) ) ; } catch ( IOException ioex ) { throw new HttpException ( ioex ) ; } } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates response { [CODESPLIT] @ Override protected Buffer buffer ( final boolean fullResponse ) { // form Buffer formBuffer = formBuffer ( ) ; // response Buffer response = new Buffer ( ) ; response . append ( httpVersion ) . append ( SPACE ) . append ( statusCode ) . append ( SPACE ) . append ( statusPhrase ) . append ( CRLF ) ; populateHeaderAndBody ( response , formBuffer , fullResponse ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads response input stream and returns { [CODESPLIT] public static HttpResponse readFrom ( final InputStream in ) { InputStreamReader inputStreamReader ; try { inputStreamReader = new InputStreamReader ( in , StringPool . ISO_8859_1 ) ; } catch ( UnsupportedEncodingException unee ) { throw new HttpException ( unee ) ; } BufferedReader reader = new BufferedReader ( inputStreamReader ) ; HttpResponse httpResponse = new HttpResponse ( ) ; // the first line String line ; try { line = reader . readLine ( ) ; } catch ( IOException ioex ) { throw new HttpException ( ioex ) ; } if ( line != null ) { line = line . trim ( ) ; int ndx = line . indexOf ( ' ' ) ; int ndx2 ; if ( ndx > - 1 ) { httpResponse . httpVersion ( line . substring ( 0 , ndx ) ) ; ndx2 = line . indexOf ( ' ' , ndx + 1 ) ; } else { httpResponse . httpVersion ( HTTP_1_1 ) ; ndx2 = - 1 ; ndx = 0 ; } if ( ndx2 == - 1 ) { ndx2 = line . length ( ) ; } try { httpResponse . statusCode ( Integer . parseInt ( line . substring ( ndx , ndx2 ) . trim ( ) ) ) ; } catch ( NumberFormatException nfex ) { httpResponse . statusCode ( - 1 ) ; } httpResponse . statusPhrase ( line . substring ( ndx2 ) . trim ( ) ) ; } httpResponse . readHeaders ( reader ) ; httpResponse . readBody ( reader ) ; return httpResponse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes requests connection if it was open . Should be called when using keep - alive connections . Otherwise connection will be already closed . [CODESPLIT] public HttpResponse close ( ) { HttpConnection httpConnection = httpRequest . httpConnection ; if ( httpConnection != null ) { httpConnection . close ( ) ; httpRequest . httpConnection = null ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines allowed referenced scopes that can be injected into the thread - local scoped bean . [CODESPLIT] @ Override public boolean accept ( final Scope referenceScope ) { Class < ? extends Scope > refScopeType = referenceScope . getClass ( ) ; if ( refScopeType == ProtoScope . class ) { return true ; } if ( refScopeType == SingletonScope . class ) { return true ; } if ( refScopeType == ThreadLocalScope . class ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- lifecycle [CODESPLIT] @ Override public void start ( ) { initLogger ( ) ; log . info ( \"MADVOC start  ----------\" ) ; webApp = webAppSupplier == null ? new PetiteWebApp ( joyPetiteSupplier . get ( ) . getPetiteContainer ( ) ) : webAppSupplier . get ( ) ; webApp . withRegisteredComponent ( ActionConfigManager . class , acm -> { acm . bindAnnotationConfig ( Action . class , JoyActionConfig . class ) ; acm . bindAnnotationConfig ( RestAction . class , JoyRestActionConfig . class ) ; } ) ; if ( servletContext != null ) { webApp . bindServletContext ( servletContext ) ; } final Props allProps = joyPropsSupplier . get ( ) . getProps ( ) ; webApp . withParams ( allProps . innerMap ( beanNamePrefix ( ) ) ) ; webApp . registerComponent ( new ProxettaSupplier ( joyProxettaSupplier . get ( ) . getProxetta ( ) ) ) ; webApp . registerComponent ( ProxettaAwareActionsManager . class ) ; // Automagic Madvoc configurator will scan and register ALL! // This way we reduce the startup time and have only one scanning. // Scanning happens in the INIT phase. final AutomagicMadvocConfigurator automagicMadvocConfigurator = new AutomagicMadvocConfigurator ( joyScannerSupplier . get ( ) . getClassScanner ( ) ) { @ Override protected String createInfoMessage ( ) { return \"Scanning completed in \" + elapsed + \"ms.\" ; } } ; webApp . registerComponent ( automagicMadvocConfigurator ) ; webAppConsumers . accept ( webApp ) ; webApp . start ( ) ; log . info ( \"MADVOC OK!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints routes to console . [CODESPLIT] protected void printRoutes ( final int width ) { final ActionsManager actionsManager = webApp . madvocContainer ( ) . lookupComponent ( ActionsManager . class ) ; final List < ActionRuntime > actions = actionsManager . getAllActionRuntimes ( ) ; final Map < String , String > aliases = actionsManager . getAllAliases ( ) ; if ( actions . isEmpty ( ) ) { return ; } final Print print = new Print ( ) ; print . line ( \"Routes\" , width ) ; actions . stream ( ) . sorted ( Comparator . comparing ( actionRuntime -> actionRuntime . getActionPath ( ) + ' ' + actionRuntime . getActionMethod ( ) ) ) . forEach ( ar -> { final String actionMethod = ar . getActionMethod ( ) ; print . out ( Chalk256 . chalk ( ) . yellow ( ) , actionMethod == null ? \"*\" : actionMethod , 7 ) ; print . space ( ) ; final String signature = ClassUtil . getShortClassName ( ProxettaUtil . resolveTargetClass ( ar . getActionClass ( ) ) , 2 ) + ' ' + ar . getActionClassMethod ( ) . getName ( ) ; print . outLeftRightNewLine ( Chalk256 . chalk ( ) . green ( ) , ar . getActionPath ( ) , Chalk256 . chalk ( ) . blue ( ) , signature , width - 7 - 1 ) ; } ) ; if ( ! aliases . isEmpty ( ) ) { print . line ( \"Aliases\" , width ) ; actions . stream ( ) . sorted ( Comparator . comparing ( actionRuntime -> actionRuntime . getActionPath ( ) + ' ' + actionRuntime . getActionMethod ( ) ) ) . forEach ( ar -> { final String actionPath = ar . getActionPath ( ) ; for ( final Map . Entry < String , String > entry : aliases . entrySet ( ) ) { if ( entry . getValue ( ) . equals ( actionPath ) ) { print . space ( 8 ) ; print . outLeftRightNewLine ( Chalk256 . chalk ( ) . green ( ) , entry . getValue ( ) , Chalk256 . chalk ( ) . blue ( ) , entry . getKey ( ) , width - 8 ) ; } } } ) ; } print . line ( width ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encrypts complete content block by block . [CODESPLIT] public byte [ ] encrypt ( final byte [ ] content ) { FastByteBuffer fbb = new FastByteBuffer ( ) ; int length = content . length + 1 ; int blockCount = length / blockSizeInBytes ; int remaining = length ; int offset = 0 ; for ( int i = 0 ; i < blockCount ; i ++ ) { if ( remaining == blockSizeInBytes ) { break ; } byte [ ] encrypted = encryptBlock ( content , offset ) ; fbb . append ( encrypted ) ; offset += blockSizeInBytes ; remaining -= blockSizeInBytes ; } if ( remaining != 0 ) { // process remaining bytes byte [ ] block = new byte [ blockSizeInBytes ] ; System . arraycopy ( content , offset , block , 0 , remaining - 1 ) ; block [ remaining - 1 ] = TERMINATOR ; byte [ ] encrypted = encryptBlock ( block , 0 ) ; fbb . append ( encrypted ) ; } return fbb . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decrypts the whole content block by block . [CODESPLIT] public byte [ ] decrypt ( final byte [ ] encryptedContent ) { FastByteBuffer fbb = new FastByteBuffer ( ) ; int length = encryptedContent . length ; int blockCount = length / blockSizeInBytes ; int offset = 0 ; for ( int i = 0 ; i < blockCount - 1 ; i ++ ) { byte [ ] decrypted = decryptBlock ( encryptedContent , offset ) ; fbb . append ( decrypted ) ; offset += blockSizeInBytes ; } // process last block byte [ ] decrypted = decryptBlock ( encryptedContent , offset ) ; // find terminator int ndx = blockSizeInBytes - 1 ; while ( ndx >= 0 ) { if ( decrypted [ ndx ] == TERMINATOR ) { break ; } ndx -- ; } fbb . append ( decrypted , 0 , ndx ) ; return fbb . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts map to target type . [CODESPLIT] public Object map2bean ( final Map map , Class targetType ) { Object target = null ; // create targets type String className = ( String ) map . get ( classMetadataName ) ; if ( className == null ) { if ( targetType == null ) { // nothing to do, no information about target type found target = map ; } } else { checkClassName ( jsonParser . classnameWhitelist , className ) ; try { targetType = ClassLoaderUtil . loadClass ( className ) ; } catch ( ClassNotFoundException cnfex ) { throw new JsonException ( cnfex ) ; } } if ( target == null ) { target = jsonParser . newObjectInstance ( targetType ) ; } ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( target . getClass ( ) ) ; boolean targetIsMap = target instanceof Map ; for ( Object key : map . keySet ( ) ) { String keyName = key . toString ( ) ; if ( classMetadataName != null ) { if ( keyName . equals ( classMetadataName ) ) { continue ; } } PropertyDescriptor pd = cd . getPropertyDescriptor ( keyName , declared ) ; if ( ! targetIsMap && pd == null ) { // target property does not exist, continue continue ; } // value is one of JSON basic types, like Number, Map, List... Object value = map . get ( key ) ; Class propertyType = pd == null ? null : pd . getType ( ) ; Class componentType = pd == null ? null : pd . resolveComponentType ( true ) ; if ( value != null ) { if ( value instanceof List ) { if ( componentType != null && componentType != String . class ) { value = generifyList ( ( List ) value , componentType ) ; } } else if ( value instanceof Map ) { // if the value we want to inject is a Map... if ( ! ClassUtil . isTypeOf ( propertyType , Map . class ) ) { // ... and if target is NOT a map value = map2bean ( ( Map ) value , propertyType ) ; } else { // target is also a Map, but we might need to generify it Class keyType = pd == null ? null : pd . resolveKeyType ( true ) ; if ( keyType != String . class || componentType != String . class ) { // generify value = generifyMap ( ( Map ) value , keyType , componentType ) ; } } } } if ( targetIsMap ) { ( ( Map ) target ) . put ( keyName , value ) ; } else { try { setValue ( target , pd , value ) ; } catch ( Exception ignore ) { ignore . printStackTrace ( ) ; } } } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts type of all list elements to match the component type . [CODESPLIT] private Object generifyList ( final List list , final Class componentType ) { for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Object element = list . get ( i ) ; if ( element != null ) { if ( element instanceof Map ) { Object bean = map2bean ( ( Map ) element , componentType ) ; list . set ( i , bean ) ; } else { Object value = convert ( element , componentType ) ; list . set ( i , value ) ; } } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the property value . [CODESPLIT] private void setValue ( final Object target , final PropertyDescriptor pd , Object value ) throws InvocationTargetException , IllegalAccessException { Class propertyType ; Setter setter = pd . getSetter ( true ) ; if ( setter != null ) { if ( value != null ) { propertyType = setter . getSetterRawType ( ) ; value = jsonParser . convertType ( value , propertyType ) ; } setter . invokeSetter ( target , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change map elements to match key and value types . [CODESPLIT] protected < K , V > Map < K , V > generifyMap ( final Map < Object , Object > map , final Class < K > keyType , final Class < V > valueType ) { if ( keyType == String . class ) { // only value type is changed, we can make value replacements for ( Map . Entry < Object , Object > entry : map . entrySet ( ) ) { Object value = entry . getValue ( ) ; Object newValue = convert ( value , valueType ) ; if ( value != newValue ) { entry . setValue ( newValue ) ; } } return ( Map < K , V > ) map ; } // key is changed too, we need a new map Map < K , V > newMap = new HashMap <> ( map . size ( ) ) ; for ( Map . Entry < Object , Object > entry : map . entrySet ( ) ) { Object key = entry . getKey ( ) ; Object newKey = convert ( key , keyType ) ; Object value = entry . getValue ( ) ; Object newValue = convert ( value , valueType ) ; newMap . put ( ( K ) newKey , ( V ) newValue ) ; } return newMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads method name and stores it in local variable . For methods that return <code > String< / code > returns the method name otherwise returns <code > null< / code > . [CODESPLIT] public Object execute ( ) { methodName = targetMethodName ( ) ; Class returnType = returnType ( ) ; if ( returnType == String . class ) { return ProxyTarget . returnValue ( targetMethodName ( ) ) ; } return ProxyTarget . returnValue ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected short [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final short [ ] target = new short [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Short > shortArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final short convertedValue = convertType ( element ) ; shortArrayList . add ( Short . valueOf ( convertedValue ) ) ; } final short [ ] array = new short [ shortArrayList . size ( ) ] ; for ( int i = 0 ; i < shortArrayList . size ( ) ; i ++ ) { final Short s = shortArrayList . get ( i ) ; array [ i ] = s . shortValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two column descriptors . Identity columns should be the first on the list . Each group then will be sorted by column name . [CODESPLIT] @ Override public int compareTo ( final Object o ) { DbEntityColumnDescriptor that = ( DbEntityColumnDescriptor ) o ; if ( this . isId != that . isId ) { return this . isId ? - 1 : 1 ; // IDs should be the first in the array } return this . columnName . compareTo ( that . columnName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds default header to all requests . [CODESPLIT] public HttpBrowser setDefaultHeader ( final String name , final String value ) { defaultHeaders . addHeader ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends new request as a browser . Before sending all browser cookies are added to the request . After sending the cookies are read from the response . Moreover status codes 301 and 302 are automatically handled . Returns very last response . [CODESPLIT] public HttpResponse sendRequest ( HttpRequest httpRequest ) { elapsedTime = System . currentTimeMillis ( ) ; // send request httpRequest . followRedirects ( false ) ; while ( true ) { this . httpRequest = httpRequest ; HttpResponse previousResponse = this . httpResponse ; this . httpResponse = null ; addDefaultHeaders ( httpRequest ) ; addCookies ( httpRequest ) ; // send request if ( catchTransportExceptions ) { try { this . httpResponse = _sendRequest ( httpRequest , previousResponse ) ; } catch ( HttpException httpException ) { httpResponse = new HttpResponse ( ) ; httpResponse . assignHttpRequest ( httpRequest ) ; httpResponse . statusCode ( 503 ) ; httpResponse . statusPhrase ( \"Service unavailable. \" + ExceptionUtil . message ( httpException ) ) ; } } else { this . httpResponse = _sendRequest ( httpRequest , previousResponse ) ; } readCookies ( httpResponse ) ; int statusCode = httpResponse . statusCode ( ) ; // 301: moved permanently if ( statusCode == 301 ) { String newPath = httpResponse . location ( ) ; if ( newPath == null ) { break ; } httpRequest = HttpRequest . get ( newPath ) ; continue ; } // 302: redirect, 303: see other if ( statusCode == 302 || statusCode == 303 ) { String newPath = httpResponse . location ( ) ; if ( newPath == null ) { break ; } httpRequest = HttpRequest . get ( newPath ) ; continue ; } // 307: temporary redirect, 308: permanent redirect if ( statusCode == 307 || statusCode == 308 ) { String newPath = httpResponse . location ( ) ; if ( newPath == null ) { break ; } String originalMethod = httpRequest . method ( ) ; httpRequest = new HttpRequest ( ) . method ( originalMethod ) . set ( newPath ) ; continue ; } break ; } elapsedTime = System . currentTimeMillis ( ) - elapsedTime ; return this . httpResponse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens connection and sends a response . [CODESPLIT] protected HttpResponse _sendRequest ( final HttpRequest httpRequest , final HttpResponse previouseResponse ) { if ( ! keepAlive ) { httpRequest . open ( httpConnectionProvider ) ; } else { // keeping alive if ( previouseResponse == null ) { httpRequest . open ( httpConnectionProvider ) . connectionKeepAlive ( true ) ; } else { httpRequest . keepAlive ( previouseResponse , true ) ; } } return httpRequest . send ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add default headers to the request . If request already has a header set default header will be ignored . [CODESPLIT] protected void addDefaultHeaders ( final HttpRequest httpRequest ) { for ( Map . Entry < String , String > entry : defaultHeaders . entries ( ) ) { String name = entry . getKey ( ) ; if ( ! httpRequest . headers . contains ( name ) ) { httpRequest . headers . add ( name , entry . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads cookies from response and adds to cookies list . [CODESPLIT] protected void readCookies ( final HttpResponse httpResponse ) { Cookie [ ] newCookies = httpResponse . cookies ( ) ; for ( Cookie cookie : newCookies ) { cookies . add ( cookie . getName ( ) , cookie ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add cookies to the request . [CODESPLIT] protected void addCookies ( final HttpRequest httpRequest ) { // prepare all cookies List < Cookie > cookiesList = new ArrayList <> ( ) ; if ( ! cookies . isEmpty ( ) ) { for ( Map . Entry < String , Cookie > cookieEntry : cookies ) { cookiesList . add ( cookieEntry . getValue ( ) ) ; } httpRequest . cookies ( cookiesList . toArray ( new Cookie [ 0 ] ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares message and sends it . Returns Message ID of sent email . [CODESPLIT] public String sendMail ( final Email email ) { try { final MimeMessage msg = createMessage ( email ) ; getService ( ) . sendMessage ( msg , msg . getAllRecipients ( ) ) ; return msg . getMessageID ( ) ; } catch ( final MessagingException msgexc ) { throw new MailException ( \"Failed to send email: \" + email , msgexc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { @link MimeMessage } from an { @link Email } . [CODESPLIT] protected MimeMessage createMessage ( final Email email ) throws MessagingException { final Email clone = email . clone ( ) ; final MimeMessage newMsg = new MimeMessage ( getSession ( ) ) ; setPeople ( clone , newMsg ) ; setSubject ( clone , newMsg ) ; setSentDate ( clone , newMsg ) ; setHeaders ( clone , newMsg ) ; addBodyData ( clone , newMsg ) ; return newMsg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets subject in msgToSet from subject in emailWithData . [CODESPLIT] private void setSubject ( final Email emailWithData , final MimeMessage msgToSet ) throws MessagingException { if ( emailWithData . subjectEncoding ( ) != null ) { msgToSet . setSubject ( emailWithData . subject ( ) , emailWithData . subjectEncoding ( ) ) ; } else { msgToSet . setSubject ( emailWithData . subject ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets sent date in msgToSet with sent date from emailWithData . [CODESPLIT] private void setSentDate ( final Email emailWithData , final MimeMessage msgToSet ) throws MessagingException { Date date = emailWithData . sentDate ( ) ; if ( date == null ) { date = new Date ( ) ; } msgToSet . setSentDate ( date ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets headers in msgToSet with headers from emailWithData . [CODESPLIT] private void setHeaders ( final Email emailWithData , final MimeMessage msgToSet ) throws MessagingException { final Map < String , String > headers = emailWithData . headers ( ) ; if ( headers != null ) { for ( final Map . Entry < String , String > entry : headers . entrySet ( ) ) { msgToSet . setHeader ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets FROM REPLY - TO and recipients . [CODESPLIT] private void setPeople ( final Email emailWithData , final MimeMessage msgToSet ) throws MessagingException { msgToSet . setFrom ( emailWithData . from ( ) . toInternetAddress ( ) ) ; msgToSet . setReplyTo ( EmailAddress . convert ( emailWithData . replyTo ( ) ) ) ; setRecipients ( emailWithData , msgToSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets TO CC and BCC in msgToSet with TO CC and BCC from emailWithData . [CODESPLIT] private void setRecipients ( final Email emailWithData , final MimeMessage msgToSet ) throws MessagingException { // TO final InternetAddress [ ] to = EmailAddress . convert ( emailWithData . to ( ) ) ; if ( to . length > 0 ) { msgToSet . setRecipients ( RecipientType . TO , to ) ; } // CC final InternetAddress [ ] cc = EmailAddress . convert ( emailWithData . cc ( ) ) ; if ( cc . length > 0 ) { msgToSet . setRecipients ( RecipientType . CC , cc ) ; } // BCC final InternetAddress [ ] bcc = EmailAddress . convert ( emailWithData . bcc ( ) ) ; if ( bcc . length > 0 ) { msgToSet . setRecipients ( RecipientType . BCC , bcc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds message data and attachments . [CODESPLIT] private void addBodyData ( final Email emailWithData , final MimeMessage msgToSet ) throws MessagingException { final List < EmailMessage > messages = emailWithData . messages ( ) ; final int totalMessages = messages . size ( ) ; // Need to use new list since filterEmbeddedAttachments(List) removes attachments from the source List final List < EmailAttachment < ? extends DataSource > > attachments = new ArrayList <> ( emailWithData . attachments ( ) ) ; if ( attachments . isEmpty ( ) && totalMessages == 1 ) { // special case: no attachments and just one content setContent ( messages . get ( 0 ) , msgToSet ) ; } else { final MimeMultipart multipart = new MimeMultipart ( ) ; final MimeMultipart msgMultipart = new MimeMultipart ( ALTERNATIVE ) ; multipart . addBodyPart ( getBaseBodyPart ( msgMultipart ) ) ; for ( final EmailMessage emailMessage : messages ) { msgMultipart . addBodyPart ( getBodyPart ( emailMessage , attachments ) ) ; } addAnyAttachments ( attachments , multipart ) ; msgToSet . setContent ( multipart ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns new { @link MimeBodyPart } with content set as msgMultipart . [CODESPLIT] private MimeBodyPart getBaseBodyPart ( final MimeMultipart msgMultipart ) throws MessagingException { final MimeBodyPart bodyPart = new MimeBodyPart ( ) ; bodyPart . setContent ( msgMultipart ) ; return bodyPart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets emailWithData content into msgToSet . [CODESPLIT] private void setContent ( final EmailMessage emailWithData , final Part partToSet ) throws MessagingException { partToSet . setContent ( emailWithData . getContent ( ) , emailWithData . getMimeType ( ) + CHARSET + emailWithData . getEncoding ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates attachment body part . Handles regular and inline attachments . [CODESPLIT] protected MimeBodyPart createAttachmentBodyPart ( final EmailAttachment < ? extends DataSource > attachment ) throws MessagingException { final MimeBodyPart part = new MimeBodyPart ( ) ; final String attachmentName = attachment . getEncodedName ( ) ; if ( attachmentName != null ) { part . setFileName ( attachmentName ) ; } part . setDataHandler ( new DataHandler ( attachment . getDataSource ( ) ) ) ; if ( attachment . getContentId ( ) != null ) { part . setContentID ( StringPool . LEFT_CHEV + attachment . getContentId ( ) + StringPool . RIGHT_CHEV ) ; } if ( attachment . isInline ( ) ) { part . setDisposition ( INLINE ) ; } return part ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters out the { @link List } of embedded { @link EmailAttachment } s for given { @link EmailMessage } . This will remove the embedded attachments from the { @link List } and return them in a new { @link List } . [CODESPLIT] protected List < EmailAttachment < ? extends DataSource > > filterEmbeddedAttachments ( final List < EmailAttachment < ? extends DataSource > > attachments , final EmailMessage emailMessage ) { final List < EmailAttachment < ? extends DataSource > > embeddedAttachments = new ArrayList <> ( ) ; if ( attachments == null || attachments . isEmpty ( ) || emailMessage == null ) { return embeddedAttachments ; } final Iterator < EmailAttachment < ? extends DataSource > > iterator = attachments . iterator ( ) ; while ( iterator . hasNext ( ) ) { final EmailAttachment < ? extends DataSource > emailAttachment = iterator . next ( ) ; if ( emailAttachment . isEmbeddedInto ( emailMessage ) ) { embeddedAttachments . add ( emailAttachment ) ; iterator . remove ( ) ; } } return embeddedAttachments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds { @link List } of { @link EmailAttachment } s to multipart . [CODESPLIT] private void addAnyAttachments ( final List < EmailAttachment < ? extends DataSource > > attachments , final MimeMultipart multipart ) throws MessagingException { for ( final EmailAttachment < ? extends DataSource > attachment : attachments ) { final MimeBodyPart bodyPart = createAttachmentBodyPart ( attachment ) ; multipart . addBodyPart ( bodyPart ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares value of two same instances . [CODESPLIT] @ Override public int compareTo ( final MutableInteger other ) { return value < other . value ? - 1 : ( value == other . value ? 0 : 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets value of data field or <code > null< / code > if field not found . [CODESPLIT] private String getDataFieldValue ( final String dataHeader , final String fieldName ) { String value = null ; String token = String . valueOf ( ( new StringBuffer ( String . valueOf ( fieldName ) ) ) . append ( ' ' ) . append ( ' ' ) ) ; int pos = dataHeader . indexOf ( token ) ; if ( pos > 0 ) { int start = pos + token . length ( ) ; int end = dataHeader . indexOf ( ' ' , start ) ; if ( ( start > 0 ) && ( end > 0 ) ) { value = dataHeader . substring ( start , end ) ; } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips content type information from requests data header . [CODESPLIT] private String getContentType ( final String dataHeader ) { String token = \"Content-Type:\" ; int start = dataHeader . indexOf ( token ) ; if ( start == - 1 ) { return StringPool . EMPTY ; } start += token . length ( ) ; return dataHeader . substring ( start ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores result set . [CODESPLIT] protected void saveResultSet ( final ResultSet rs ) { if ( resultSets == null ) { resultSets = new HashSet <> ( ) ; } resultSets . add ( rs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes session . When not specified ( i . e . is <code > null< / code > ) session is fetched from session provider . [CODESPLIT] protected void initSession ( final DbSession session ) { if ( session != null ) { this . session = session ; return ; } final DbSessionProvider dbSessionProvider = dbOom . sessionProvider ( ) ; this . session = dbSessionProvider . getDbSession ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs JDBC initialization of the query . Obtains connection parses the SQL query string and creates statements . Initialization is performed only once when switching to initialized state . [CODESPLIT] @ SuppressWarnings ( \"MagicConstant\" ) protected void initializeJdbc ( ) { // connection if ( connection == null ) { initSession ( session ) ; connection = session . getConnection ( ) ; } this . query = new DbQueryParser ( sqlString ) ; // callable statement if ( query . callable ) { try { if ( debug ) { if ( holdability != QueryHoldability . DEFAULT ) { callableStatement = new LoggableCallableStatement ( connection . prepareCall ( query . sql , type . value ( ) , concurrencyType . value ( ) , holdability . value ( ) ) , query . sql ) ; } else { callableStatement = new LoggableCallableStatement ( connection . prepareCall ( query . sql , type . value ( ) , concurrencyType . value ( ) ) , query . sql ) ; } } else { if ( holdability != QueryHoldability . DEFAULT ) { callableStatement = connection . prepareCall ( query . sql , type . value ( ) , concurrencyType . value ( ) , holdability . value ( ) ) ; } else { callableStatement = connection . prepareCall ( query . sql , type . value ( ) , concurrencyType . value ( ) ) ; } } } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Error creating callable statement\" , sex ) ; } preparedStatement = callableStatement ; statement = callableStatement ; return ; } // prepared statement if ( query . prepared || forcePreparedStatement ) { try { if ( debug ) { if ( generatedColumns != null ) { if ( generatedColumns . length == 0 ) { preparedStatement = new LoggablePreparedStatement ( connection . prepareStatement ( query . sql , Statement . RETURN_GENERATED_KEYS ) , query . sql ) ; } else { preparedStatement = new LoggablePreparedStatement ( connection . prepareStatement ( query . sql , generatedColumns ) , query . sql ) ; } } else { if ( holdability != QueryHoldability . DEFAULT ) { preparedStatement = new LoggablePreparedStatement ( connection . prepareStatement ( query . sql , type . value ( ) , concurrencyType . value ( ) , holdability . value ( ) ) , query . sql ) ; } else { preparedStatement = new LoggablePreparedStatement ( connection . prepareStatement ( query . sql , type . value ( ) , concurrencyType . value ( ) ) , query . sql ) ; } } } else { if ( generatedColumns != null ) { if ( generatedColumns . length == 0 ) { preparedStatement = connection . prepareStatement ( query . sql , Statement . RETURN_GENERATED_KEYS ) ; } else { preparedStatement = connection . prepareStatement ( query . sql , generatedColumns ) ; } } else { if ( holdability != QueryHoldability . DEFAULT ) { preparedStatement = connection . prepareStatement ( query . sql , type . value ( ) , concurrencyType . value ( ) , holdability . value ( ) ) ; } else { preparedStatement = connection . prepareStatement ( query . sql , type . value ( ) , concurrencyType . value ( ) ) ; } } } } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Error creating prepared statement\" , sex ) ; } statement = preparedStatement ; return ; } // statement try { if ( holdability != QueryHoldability . DEFAULT ) { statement = connection . createStatement ( type . value ( ) , concurrencyType . value ( ) , holdability . value ( ) ) ; } else { statement = connection . createStatement ( type . value ( ) , concurrencyType . value ( ) ) ; } } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Error creating statement\" , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes all result sets opened by this query . Query remains active . Returns <code > SQLException< / code > ( stacked with all exceptions ) or <code > null< / code > . [CODESPLIT] private SQLException closeQueryResultSets ( ) { SQLException sqlException = null ; if ( resultSets != null ) { for ( final ResultSet rs : resultSets ) { try { rs . close ( ) ; } catch ( SQLException sex ) { if ( sqlException == null ) { sqlException = sex ; } else { sqlException . setNextException ( sex ) ; } } finally { totalOpenResultSetCount -- ; } } resultSets . clear ( ) ; resultSets = null ; } return sqlException ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes all result sets created by this query . Query remains active . [CODESPLIT] public Q closeAllResultSets ( ) { final SQLException sex = closeQueryResultSets ( ) ; if ( sex != null ) { throw new DbSqlException ( \"Close associated ResultSets error\" , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes all assigned result sets and then closes the query . Query becomes closed . [CODESPLIT] protected SQLException closeQuery ( ) { SQLException sqlException = closeQueryResultSets ( ) ; if ( statement != null ) { try { statement . close ( ) ; } catch ( SQLException sex ) { if ( sqlException == null ) { sqlException = sex ; } else { sqlException . setNextException ( sex ) ; } } statement = null ; } query = null ; queryState = CLOSED ; return sqlException ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the query and all created results sets and detaches itself from the session . [CODESPLIT] @ Override @ SuppressWarnings ( { \"ClassReferencesSubclass\" } ) public void close ( ) { final SQLException sqlException = closeQuery ( ) ; connection = null ; if ( this . session != null ) { this . session . detachQuery ( this ) ; } if ( sqlException != null ) { throw new DbSqlException ( \"Close query error\" , sqlException ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes single result set that was created by this query . It is not necessary to close result sets explicitly since { [CODESPLIT] public void closeResultSet ( final ResultSet rs ) { if ( rs == null ) { return ; } if ( ! resultSets . remove ( rs ) ) { throw new DbSqlException ( this , \"ResultSet is not created by this query\" ) ; } try { rs . close ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Close result set error\" , sex ) ; } finally { totalOpenResultSetCount -- ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed . The number of rows specified affects only result sets created using this statement . If the value specified is zero then the hint is ignored . The default value is zero . [CODESPLIT] public Q setFetchSize ( final int rows ) { checkNotClosed ( ) ; this . fetchSize = rows ; if ( statement != null ) { try { statement . setFetchSize ( fetchSize ) ; } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Unable to set fetch size: \" + fetchSize , sex ) ; } } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the limit for the maximum number of rows that any ResultSet object can contain to the given number . If the limit is exceeded the excess rows are silently dropped . Zero means there is no limit . [CODESPLIT] public Q setMaxRows ( final int maxRows ) { checkNotClosed ( ) ; this . maxRows = maxRows ; if ( statement != null ) { try { statement . setMaxRows ( maxRows ) ; } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Unable to set max rows: \" + maxRows , sex ) ; } } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the query . If this method is invoked at least once the query or all created ResultSets must be explicitly closed at the end of query usage . This can be done explicitly by calling { [CODESPLIT] public ResultSet execute ( ) { start = System . currentTimeMillis ( ) ; init ( ) ; ResultSet rs = null ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Executing statement: \" + getQueryString ( ) ) ; } try { if ( preparedStatement == null ) { rs = statement . executeQuery ( query . sql ) ; } else { rs = preparedStatement . executeQuery ( ) ; } rs . setFetchSize ( fetchSize ) ; } catch ( SQLException sex ) { DbUtil . close ( rs ) ; throw new DbSqlException ( this , \"Query execution failed\" , sex ) ; } saveResultSet ( rs ) ; totalOpenResultSetCount ++ ; elapsed = System . currentTimeMillis ( ) - start ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"execution time: \" + elapsed + \"ms\" ) ; } return rs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes UPDATE INSERT or DELETE queries and optionally closes the query . [CODESPLIT] protected int executeUpdate ( final boolean closeQuery ) { start = System . currentTimeMillis ( ) ; init ( ) ; final int result ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Executing update: \" + getQueryString ( ) ) ; } try { if ( preparedStatement == null ) { if ( generatedColumns != null ) { if ( generatedColumns . length == 0 ) { result = statement . executeUpdate ( query . sql , Statement . RETURN_GENERATED_KEYS ) ; } else { result = statement . executeUpdate ( query . sql , generatedColumns ) ; } } else { result = statement . executeUpdate ( query . sql ) ; } } else { result = preparedStatement . executeUpdate ( ) ; } } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Query execution failed\" , sex ) ; } if ( closeQuery ) { close ( ) ; } elapsed = System . currentTimeMillis ( ) - start ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"execution time: \" + elapsed + \"ms\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes count queries and optionally closes query afterwards . [CODESPLIT] protected long executeCount ( final boolean close ) { start = System . currentTimeMillis ( ) ; init ( ) ; ResultSet rs = null ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Executing prepared count: \" + getQueryString ( ) ) ; } try { if ( preparedStatement == null ) { rs = statement . executeQuery ( query . sql ) ; } else { rs = preparedStatement . executeQuery ( ) ; } final long firstLong = DbUtil . getFirstLong ( rs ) ; elapsed = System . currentTimeMillis ( ) - start ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"execution time: \" + elapsed + \"ms\" ) ; } return firstLong ; } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Count query failed\" , sex ) ; } finally { DbUtil . close ( rs ) ; if ( close ) { close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < T > List < T > list ( final QueryMapper < T > queryMapper ) { final ResultSet resultSet = execute ( ) ; final List < T > list = new ArrayList <> ( ) ; try { while ( resultSet . next ( ) ) { final T t = queryMapper . process ( resultSet ) ; if ( t == null ) { break ; } list . add ( t ) ; } } catch ( SQLException sex ) { throw new DbSqlException ( sex ) ; } finally { DbUtil . close ( resultSet ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < T > T find ( final QueryMapper < T > queryMapper ) { final ResultSet resultSet = execute ( ) ; try { if ( resultSet . next ( ) ) { return queryMapper . process ( resultSet ) ; } } catch ( SQLException sex ) { throw new DbSqlException ( sex ) ; } finally { DbUtil . close ( resultSet ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < T > Set < T > listSet ( final QueryMapper < T > queryMapper ) { final ResultSet resultSet = execute ( ) ; final Set < T > set = new HashSet <> ( ) ; try { while ( resultSet . next ( ) ) { final T t = queryMapper . process ( resultSet ) ; if ( t == null ) { break ; } set . add ( t ) ; } } catch ( SQLException sex ) { throw new DbSqlException ( sex ) ; } finally { DbUtil . close ( resultSet ) ; } return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns generated columns . [CODESPLIT] public ResultSet getGeneratedColumns ( ) { checkInitialized ( ) ; if ( generatedColumns == null ) { throw new DbSqlException ( this , \"No column is specified as auto-generated\" ) ; } final ResultSet rs ; try { rs = statement . getGeneratedKeys ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( this , \"No generated keys\" , sex ) ; } saveResultSet ( rs ) ; totalOpenResultSetCount ++ ; return rs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns generated key i . e . first generated column as <code > long< / code > . [CODESPLIT] public long getGeneratedKey ( ) { checkInitialized ( ) ; final ResultSet rs = getGeneratedColumns ( ) ; try { return DbUtil . getFirstLong ( rs ) ; } catch ( SQLException sex ) { throw new DbSqlException ( this , \"No generated key as long\" , sex ) ; } finally { DbUtil . close ( rs ) ; resultSets . remove ( rs ) ; totalOpenResultSetCount -- ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns query SQL string . For prepared statements returned sql string with quick - and - dirty replaced values . [CODESPLIT] public String getQueryString ( ) { if ( debug ) { if ( ( callableStatement != null ) ) { if ( preparedStatement instanceof LoggableCallableStatement ) { return ( ( LoggableCallableStatement ) callableStatement ) . getQueryString ( ) ; } } if ( preparedStatement != null ) { if ( preparedStatement instanceof LoggablePreparedStatement ) { return ( ( LoggablePreparedStatement ) preparedStatement ) . getQueryString ( ) ; } } } if ( query != null ) { return query . sql ; } return sqlString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new address by specifying one of the following : <ul > <li > { @code foo@bar . com - only email address . } < / li > <li > { @code Jenny Doe &lt ; foo@bar . com&gt ; - first part of the string is personal name and the other part is email surrounded with < and > . } < / li > < / ul > [CODESPLIT] public static EmailAddress of ( String address ) { address = address . trim ( ) ; if ( ! StringUtil . endsWithChar ( address , ' ' ) ) { return new EmailAddress ( null , address ) ; } final int ndx = address . lastIndexOf ( ' ' ) ; if ( ndx == - 1 ) { return new EmailAddress ( null , address ) ; } String email = address . substring ( ndx + 1 , address . length ( ) - 1 ) ; String personalName = address . substring ( 0 , ndx ) . trim ( ) ; return new EmailAddress ( personalName , email ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { @link InternetAddress } from current data . [CODESPLIT] public InternetAddress toInternetAddress ( ) throws AddressException { try { return new InternetAddress ( email , personalName , JoddCore . encoding ) ; } catch ( final UnsupportedEncodingException ueex ) { throw new AddressException ( ueex . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts array of { @link Address } to { @link EmailAddress } . [CODESPLIT] public static EmailAddress [ ] of ( final Address ... addresses ) { if ( addresses == null ) { return EmailAddress . EMPTY_ARRAY ; } if ( addresses . length == 0 ) { return EmailAddress . EMPTY_ARRAY ; } final EmailAddress [ ] res = new EmailAddress [ addresses . length ] ; for ( int i = 0 ; i < addresses . length ; i ++ ) { res [ i ] = EmailAddress . of ( addresses [ i ] ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert from array of { @link EmailAddress } to array of { @link InternetAddress } . [CODESPLIT] public static InternetAddress [ ] convert ( final EmailAddress [ ] addresses ) throws MessagingException { if ( addresses == null ) { return new InternetAddress [ 0 ] ; } final int numRecipients = addresses . length ; final InternetAddress [ ] address = new InternetAddress [ numRecipients ] ; for ( int i = 0 ; i < numRecipients ; i ++ ) { address [ i ] = addresses [ i ] . toInternetAddress ( ) ; } return address ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a proxy of given target and the aspect . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T proxyOf ( final T target , final Class < ? extends Aspect > aspectClass ) { final Aspect aspect ; try { aspect = ClassUtil . newInstance ( aspectClass , target ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Can't create new instance of aspect class\" , e ) ; } return ( T ) newProxyInstance ( target . getClass ( ) . getClassLoader ( ) , aspect , target . getClass ( ) . getInterfaces ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a proxy from given { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T proxyOf ( final Aspect aspect ) { final Object target = aspect . getTarget ( ) ; return ( T ) newProxyInstance ( target . getClass ( ) . getClassLoader ( ) , aspect , target . getClass ( ) . getInterfaces ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses string template and replaces macros with resolved values . [CODESPLIT] public String parse ( String template , final Function < String , String > macroResolver ) { StringBuilder result = new StringBuilder ( template . length ( ) ) ; int i = 0 ; int len = template . length ( ) ; // strict flag means that start and end tag are not necessary boolean strict ; if ( macroPrefix == null ) { // when prefix is not specified, make it equals to macro start // so we can use the same code macroPrefix = macroStart ; strict = true ; } else { strict = false ; } final int prefixLen = macroPrefix . length ( ) ; final int startLen = macroStart . length ( ) ; final int endLen = macroEnd . length ( ) ; while ( i < len ) { int ndx = template . indexOf ( macroPrefix , i ) ; if ( ndx == - 1 ) { result . append ( i == 0 ? template : template . substring ( i ) ) ; break ; } // check escaped int j = ndx - 1 ; boolean escape = false ; int count = 0 ; while ( ( j >= 0 ) && ( template . charAt ( j ) == escapeChar ) ) { escape = ! escape ; if ( escape ) { count ++ ; } j -- ; } if ( resolveEscapes ) { result . append ( template . substring ( i , ndx - count ) ) ; } else { result . append ( template . substring ( i , ndx ) ) ; } if ( escape ) { result . append ( macroPrefix ) ; i = ndx + prefixLen ; continue ; } // macro started, detect strict format boolean detectedStrictFormat = strict ; if ( ! detectedStrictFormat ) { if ( StringUtil . isSubstringAt ( template , macroStart , ndx ) ) { detectedStrictFormat = true ; } } int ndx1 ; int ndx2 ; if ( ! detectedStrictFormat ) { // not strict format: $foo ndx += prefixLen ; ndx1 = ndx ; ndx2 = ndx ; while ( ( ndx2 < len ) && CharUtil . isPropertyNameChar ( template . charAt ( ndx2 ) ) ) { ndx2 ++ ; } if ( ndx2 == len ) { ndx2 -- ; } while ( ( ndx2 > ndx ) && ! CharUtil . isAlphaOrDigit ( template . charAt ( ndx2 ) ) ) { ndx2 -- ; } ndx2 ++ ; if ( ndx2 == ndx1 + 1 ) { // no value, hence no macro result . append ( macroPrefix ) ; i = ndx1 ; continue ; } } else { // strict format: ${foo} // find macros end ndx += startLen ; ndx2 = template . indexOf ( macroEnd , ndx ) ; if ( ndx2 == - 1 ) { throw new IllegalArgumentException ( \"Invalid template, unclosed macro at: \" + ( ndx - startLen ) ) ; } // detect inner macros, there is no escaping ndx1 = ndx ; while ( ndx1 < ndx2 ) { int n = StringUtil . indexOf ( template , macroStart , ndx1 , ndx2 ) ; if ( n == - 1 ) { break ; } ndx1 = n + startLen ; } } final String name = template . substring ( ndx1 , ndx2 ) ; // find value and append Object value ; if ( missingKeyReplacement != null || ! replaceMissingKey ) { try { value = macroResolver . apply ( name ) ; } catch ( Exception ignore ) { value = null ; } if ( value == null ) { if ( replaceMissingKey ) { value = missingKeyReplacement ; } else { if ( detectedStrictFormat ) { value = template . substring ( ndx1 - startLen , ndx2 + endLen ) ; } else { value = template . substring ( ndx1 - 1 , ndx2 ) ; } } } } else { value = macroResolver . apply ( name ) ; if ( value == null ) { value = StringPool . EMPTY ; } } if ( ndx == ndx1 ) { String stringValue = value . toString ( ) ; if ( parseValues ) { if ( stringValue . contains ( macroStart ) ) { stringValue = parse ( stringValue , macroResolver ) ; } } result . append ( stringValue ) ; i = ndx2 ; if ( detectedStrictFormat ) { i += endLen ; } } else { // inner macro template = template . substring ( 0 , ndx1 - startLen ) + value . toString ( ) + template . substring ( ndx2 + endLen ) ; len = template . length ( ) ; i = ndx - startLen ; } } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapt the specified <code > Iterator< / code > to the <code > Enumeration< / code > interface . [CODESPLIT] public static < E > Enumeration < E > asEnumeration ( final Iterator < E > iter ) { return new Enumeration < E > ( ) { @ Override public boolean hasMoreElements ( ) { return iter . hasNext ( ) ; } @ Override public E nextElement ( ) { return iter . next ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapt the specified <code > Enumeration< / code > to the <code > Iterator< / code > interface . [CODESPLIT] public static < E > Iterator < E > asIterator ( final Enumeration < E > e ) { return new Iterator < E > ( ) { @ Override public boolean hasNext ( ) { return e . hasMoreElements ( ) ; } @ Override public E next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } return e . nextElement ( ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection containing all elements of the iterator . [CODESPLIT] public static < T > Collection < T > collectionOf ( final Iterator < ? extends T > iterator ) { final List < T > list = new ArrayList <> ( ) ; while ( iterator . hasNext ( ) ) { list . add ( iterator . next ( ) ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts iterator to a stream . [CODESPLIT] public static < T > Stream < T > streamOf ( final Iterator < T > iterator ) { return StreamSupport . stream ( ( ( Iterable < T > ) ( ) -> iterator ) . spliterator ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps an iterator as a stream . [CODESPLIT] public static < T > Stream < T > parallelStreamOf ( final Iterator < T > iterator ) { return StreamSupport . stream ( ( ( Iterable < T > ) ( ) -> iterator ) . spliterator ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps an iterator as a stream . [CODESPLIT] public static < T > Stream < T > parallelStreamOf ( final Iterable < T > iterable ) { return StreamSupport . stream ( iterable . spliterator ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public DbSession getDbSession ( ) { log . debug ( \"Requesting thread session\" ) ; final DbSession session = ThreadDbSessionHolder . get ( ) ; if ( session == null ) { throw new DbSqlException ( \"No DbSession associated with current thread.\" + \"It seems that ThreadDbSessionHolder is not used.\" ) ; } return session ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two objects starting with first comparator ; if they are equals proceeds to the next comparator and so on . [CODESPLIT] @ Override public int compare ( final T o1 , final T o2 ) { for ( Comparator < T > comparator : comparators ) { int result = comparator . compare ( o1 , o2 ) ; if ( result != 0 ) { return result ; } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- add content [CODESPLIT] public AddContentToZip add ( final String content ) { return new AddContentToZip ( StringUtil . getBytes ( content , StringPool . UTF_8 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- folder [CODESPLIT] public ZipBuilder addFolder ( final String folderName ) throws IOException { ZipUtil . addFolderToZip ( zos , folderName , null ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies default wiring mode . [CODESPLIT] public PetiteConfig setDefaultWiringMode ( final WiringMode defaultWiringMode ) { if ( ( defaultWiringMode == null ) || ( defaultWiringMode == WiringMode . DEFAULT ) ) { throw new PetiteException ( \"Invalid default wiring mode: \" + defaultWiringMode ) ; } this . defaultWiringMode = defaultWiringMode ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves wiring mode by checking if default and <code > null< / code > values . [CODESPLIT] protected WiringMode resolveWiringMode ( WiringMode wiringMode ) { if ( ( wiringMode == null ) || ( wiringMode == WiringMode . DEFAULT ) ) { wiringMode = defaultWiringMode ; } return wiringMode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints error message if level is enabled . [CODESPLIT] protected void print ( final Level level , final String message , final Throwable throwable ) { if ( ! isEnabled ( level ) ) { return ; } StringBuilder msg = new StringBuilder ( ) . append ( slf . getElapsedTime ( ) ) . append ( ' ' ) . append ( ' ' ) . append ( level ) . append ( ' ' ) . append ( ' ' ) . append ( getCallerClass ( ) ) . append ( ' ' ) . append ( ' ' ) . append ( ' ' ) . append ( message ) ; System . out . println ( msg . toString ( ) ) ; if ( throwable != null ) { throwable . printStackTrace ( System . out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns called class . [CODESPLIT] protected String getCallerClass ( ) { Exception exception = new Exception ( ) ; StackTraceElement [ ] stackTrace = exception . getStackTrace ( ) ; for ( StackTraceElement stackTraceElement : stackTrace ) { String className = stackTraceElement . getClassName ( ) ; if ( className . equals ( SimpleLoggerProvider . class . getName ( ) ) ) { continue ; } if ( className . equals ( SimpleLogger . class . getName ( ) ) ) { continue ; } if ( className . equals ( Logger . class . getName ( ) ) ) { continue ; } return shortenClassName ( className ) + ' ' + stackTraceElement . getMethodName ( ) + ' ' + stackTraceElement . getLineNumber ( ) ; } return \"N/A\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns shorten class name . [CODESPLIT] protected String shortenClassName ( final String className ) { int lastDotIndex = className . lastIndexOf ( ' ' ) ; if ( lastDotIndex == - 1 ) { return className ; } StringBuilder shortClassName = new StringBuilder ( className . length ( ) ) ; int start = 0 ; while ( true ) { shortClassName . append ( className . charAt ( start ) ) ; int next = className . indexOf ( ' ' , start ) ; if ( next == lastDotIndex ) { break ; } start = next + 1 ; shortClassName . append ( ' ' ) ; } shortClassName . append ( className . substring ( lastDotIndex ) ) ; return shortClassName . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines custom { [CODESPLIT] public JsonSerializer withSerializer ( final String pathString , final TypeJsonSerializer typeJsonSerializer ) { if ( pathSerializersMap == null ) { pathSerializersMap = new HashMap <> ( ) ; } pathSerializersMap . put ( Path . parse ( pathString ) , typeJsonSerializer ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines custom { [CODESPLIT] public JsonSerializer withSerializer ( final Class type , final TypeJsonSerializer typeJsonSerializer ) { if ( typeSerializersMap == null ) { typeSerializersMap = new TypeJsonSerializerMap ( TypeJsonSerializerMap . get ( ) ) ; } typeSerializersMap . register ( type , typeJsonSerializer ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds excludes with optional parent including . When parents are included for each exclude query its parent will be included . For example exclude of aaa . bb . ccc would include it s parent : aaa . bb . [CODESPLIT] public JsonSerializer exclude ( final boolean includeParent , final String ... excludes ) { for ( String exclude : excludes ) { if ( includeParent ) { int dotIndex = exclude . lastIndexOf ( ' ' ) ; if ( dotIndex != - 1 ) { PathQuery pathQuery = new PathQuery ( exclude . substring ( 0 , dotIndex ) , true ) ; rules . include ( pathQuery ) ; } } PathQuery pathQuery = new PathQuery ( exclude , false ) ; rules . exclude ( pathQuery ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Excludes type names . You can disable serialization of properties that are of some type . For example you can disable properties of <code > InputStream< / code > . You can use wildcards to describe type names . [CODESPLIT] public JsonSerializer excludeTypes ( final String ... typeNames ) { if ( excludedTypeNames == null ) { excludedTypeNames = typeNames ; } else { excludedTypeNames = ArraysUtil . join ( excludedTypeNames , typeNames ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Excludes types . Supports interfaces and subclasses as well . [CODESPLIT] public JsonSerializer excludeTypes ( final Class ... types ) { if ( excludedTypes == null ) { excludedTypes = types ; } else { excludedTypes = ArraysUtil . join ( excludedTypes , types ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes object into provided appendable . [CODESPLIT] public void serialize ( final Object source , final Appendable target ) { JsonContext jsonContext = createJsonContext ( target ) ; jsonContext . serialize ( source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes object into source . [CODESPLIT] public String serialize ( final Object source ) { FastCharBuffer fastCharBuffer = new FastCharBuffer ( ) ; serialize ( source , fastCharBuffer ) ; return fastCharBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes the object but returns the { [CODESPLIT] public CharSequence serializeToCharSequence ( final Object source ) { FastCharBuffer fastCharBuffer = new FastCharBuffer ( ) ; serialize ( source , fastCharBuffer ) ; return fastCharBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create object copy using serialization mechanism . [CODESPLIT] public static < T extends Serializable > T cloneViaSerialization ( final T obj ) throws IOException , ClassNotFoundException { FastByteArrayOutputStream bos = new FastByteArrayOutputStream ( ) ; ObjectOutputStream out = null ; ObjectInputStream in = null ; Object objCopy = null ; try { out = new ObjectOutputStream ( bos ) ; out . writeObject ( obj ) ; out . flush ( ) ; byte [ ] bytes = bos . toByteArray ( ) ; in = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; objCopy = in . readObject ( ) ; } finally { StreamUtil . close ( out ) ; StreamUtil . close ( in ) ; } return ( T ) objCopy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes serializable object to a file . Existing file will be overwritten . [CODESPLIT] public static void writeObject ( final File dest , final Object object ) throws IOException { FileOutputStream fos = null ; BufferedOutputStream bos = null ; ObjectOutputStream oos = null ; try { fos = new FileOutputStream ( dest ) ; bos = new BufferedOutputStream ( fos ) ; oos = new ObjectOutputStream ( bos ) ; oos . writeObject ( object ) ; } finally { StreamUtil . close ( oos ) ; StreamUtil . close ( bos ) ; StreamUtil . close ( fos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads serialized object from the file . [CODESPLIT] public static Object readObject ( final File source ) throws IOException , ClassNotFoundException { Object result = null ; FileInputStream fis = null ; BufferedInputStream bis = null ; ObjectInputStream ois = null ; try { fis = new FileInputStream ( source ) ; bis = new BufferedInputStream ( fis ) ; ois = new ObjectInputStream ( bis ) ; result = ois . readObject ( ) ; } finally { StreamUtil . close ( ois ) ; StreamUtil . close ( bis ) ; StreamUtil . close ( fis ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize an object to byte array . [CODESPLIT] public static byte [ ] objectToByteArray ( final Object obj ) throws IOException { FastByteArrayOutputStream bos = new FastByteArrayOutputStream ( ) ; ObjectOutputStream oos = null ; try { oos = new ObjectOutputStream ( bos ) ; oos . writeObject ( obj ) ; } finally { StreamUtil . close ( oos ) ; } return bos . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "De - serialize an object from byte array . [CODESPLIT] public static Object byteArrayToObject ( final byte [ ] data ) throws IOException , ClassNotFoundException { Object retObj = null ; ByteArrayInputStream bais = new ByteArrayInputStream ( data ) ; ObjectInputStream ois = null ; try { ois = new ObjectInputStream ( bais ) ; retObj = ois . readObject ( ) ; } finally { StreamUtil . close ( ois ) ; } return retObj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Class [ ] resolveTables ( ) { List < Class > classes = new ArrayList <> ( tableNames . length ) ; String lastTableName = null ; resultColumns . clear ( ) ; for ( int i = 0 ; i < tableNames . length ; i ++ ) { String tableName = tableNames [ i ] ; String columnName = columnNames [ i ] ; if ( tableName == null ) { // maybe JDBC driver does not support it throw new DbOomException ( dbOomQuery , \"Table name missing in meta-data\" ) ; } if ( ( ! tableName . equals ( lastTableName ) ) || ( resultColumns . contains ( columnName ) ) ) { resultColumns . clear ( ) ; lastTableName = tableName ; DbEntityDescriptor ded = dbEntityManager . lookupTableName ( tableName ) ; if ( ded == null ) { throw new DbOomException ( dbOomQuery , \"Table name not registered: \" + tableName ) ; } classes . add ( ded . getType ( ) ) ; } resultColumns . add ( columnName ) ; } return classes . toArray ( new Class [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves { [CODESPLIT] protected DbEntityDescriptor [ ] resolveDbEntityDescriptors ( final Class [ ] types ) { if ( cachedDbEntityDescriptors == null ) { DbEntityDescriptor [ ] descs = new DbEntityDescriptor [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { Class type = types [ i ] ; if ( type != null ) { descs [ i ] = dbEntityManager . lookupType ( type ) ; } } cachedDbEntityDescriptors = descs ; } return cachedDbEntityDescriptors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates table names for all specified types . Since this is usually done once per result set these names are cached . Type name will be <code > null< / code > for simple names i . e . for all those types that returns <code > null< / code > when used by { [CODESPLIT] protected String [ ] resolveTypesTableNames ( final Class [ ] types ) { if ( types != cachedUsedTypes ) { cachedTypesTableNames = createTypesTableNames ( types ) ; cachedUsedTypes = types ; } return cachedTypesTableNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolved mapped type names for each type . [CODESPLIT] protected String [ ] [ ] resolveMappedTypesTableNames ( final Class [ ] types ) { if ( cachedMappedNames == null ) { String [ ] [ ] names = new String [ types . length ] [  ] ; for ( int i = 0 ; i < types . length ; i ++ ) { Class type = types [ i ] ; if ( type != null ) { DbEntityDescriptor ded = cachedDbEntityDescriptors [ i ] ; if ( ded != null ) { Class [ ] mappedTypes = ded . getMappedTypes ( ) ; if ( mappedTypes != null ) { names [ i ] = createTypesTableNames ( mappedTypes ) ; } } } } cachedMappedNames = names ; } return cachedMappedNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates table names for given types . [CODESPLIT] protected String [ ] createTypesTableNames ( final Class [ ] types ) { String [ ] names = new String [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { if ( types [ i ] == null ) { names [ i ] = null ; continue ; } DbEntityDescriptor ded = dbEntityManager . lookupType ( types [ i ] ) ; if ( ded != null ) { String tableName = ded . getTableName ( ) ; tableName = tableName . toUpperCase ( ) ; names [ i ] = tableName ; } } return names ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads column value from result set . Since this method may be called more then once for the same column it caches column values . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) protected Object readColumnValue ( final int colNdx , final Class destinationType , final Class < ? extends SqlType > sqlTypeClass , final int columnDbSqlType ) { if ( colNdx != cachedColumnNdx ) { try { SqlType sqlType ; if ( sqlTypeClass != null ) { sqlType = SqlTypeManager . get ( ) . lookupSqlType ( sqlTypeClass ) ; } else { sqlType = SqlTypeManager . get ( ) . lookup ( destinationType ) ; } if ( sqlType != null ) { cachedColumnValue = sqlType . readValue ( resultSet , colNdx + 1 , destinationType , columnDbSqlType ) ; } else { cachedColumnValue = resultSet . getObject ( colNdx + 1 ) ; cachedColumnValue = TypeConverterManager . get ( ) . convertType ( cachedColumnValue , destinationType ) ; } } catch ( SQLException sex ) { throw new DbOomException ( dbOomQuery , \"Invalid value for column #\" + ( colNdx + 1 ) , sex ) ; } cachedColumnNdx = colNdx ; } return cachedColumnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object [ ] parseObjects ( final Class ... types ) { resultColumns . clear ( ) ; int totalTypes = types . length ; Object [ ] result = new Object [ totalTypes ] ; boolean [ ] resultUsage = new boolean [ totalTypes ] ; DbEntityDescriptor [ ] dbEntityDescriptors = resolveDbEntityDescriptors ( types ) ; String [ ] typesTableNames = resolveTypesTableNames ( types ) ; String [ ] [ ] mappedNames = resolveMappedTypesTableNames ( types ) ; int currentResult = 0 ; cachedColumnNdx = - 1 ; int colNdx = 0 ; while ( colNdx < totalColumns ) { // no more types for mapping? if ( currentResult >= totalTypes ) { break ; } // skip columns that doesn't map Class currentType = types [ currentResult ] ; if ( currentType == null ) { colNdx ++ ; currentResult ++ ; resultColumns . clear ( ) ; continue ; } String columnName = columnNames [ colNdx ] ; int columnDbSqlType = columnDbSqlTypes [ colNdx ] ; String tableName = tableNames [ colNdx ] ; String resultTableName = typesTableNames [ currentResult ] ; if ( resultTableName == null ) { // match: simple type result [ currentResult ] = readColumnValue ( colNdx , currentType , null , columnDbSqlType ) ; resultUsage [ currentResult ] = true ; colNdx ++ ; currentResult ++ ; resultColumns . clear ( ) ; continue ; } // match table boolean tableMatched = false ; if ( tableName == null ) { tableMatched = true ; } else if ( resultTableName . equals ( tableName ) ) { tableMatched = true ; } else { String [ ] mapped = mappedNames [ currentResult ] ; if ( mapped != null ) { for ( String m : mapped ) { if ( m . equals ( tableName ) ) { tableMatched = true ; break ; } } } } if ( tableMatched ) { if ( ! resultColumns . contains ( columnName ) ) { //DbEntityDescriptor ded = dbEntityManager.lookupType(currentType); DbEntityDescriptor ded = dbEntityDescriptors [ currentResult ] ; DbEntityColumnDescriptor dec = ded . findByColumnName ( columnName ) ; String propertyName = ( dec == null ? null : dec . getPropertyName ( ) ) ; // check if a property that matches column name exist if ( propertyName != null ) { // if current entity instance does not exist (i.e. we are at the first column // of some entity), create the instance and store it if ( result [ currentResult ] == null ) { result [ currentResult ] = dbEntityManager . createEntityInstance ( currentType ) ; } /*\n\t\t\t\t\t\tboolean success = value != null ?\n\t\t\t\t\t\t\t\t\t\tBeanUtil.setDeclaredPropertySilent(result[currentResult], propertyName, value) :\n\t\t\t\t\t\t\t\t\t\tBeanUtil.hasDeclaredProperty(result[currentResult], propertyName);\n*/ Class type = BeanUtil . declared . getPropertyType ( result [ currentResult ] , propertyName ) ; if ( type != null ) { // match: entity dec . updateDbSqlType ( columnDbSqlType ) ; // updates column db sql type information for the entity!!! Class < ? extends SqlType > sqlTypeClass = dec . getSqlTypeClass ( ) ; Object value = readColumnValue ( colNdx , type , sqlTypeClass , columnDbSqlType ) ; if ( value != null ) { // inject column value into existing entity BeanUtil . declared . setProperty ( result [ currentResult ] , propertyName , value ) ; resultUsage [ currentResult ] = true ; } colNdx ++ ; resultColumns . add ( columnName ) ; continue ; } } } } // go to next type, i.e. result currentResult ++ ; resultColumns . clear ( ) ; } resultColumns . clear ( ) ; for ( int i = 0 ; i < resultUsage . length ; i ++ ) { if ( ! resultUsage [ i ] ) { result [ i ] = null ; } } if ( cacheEntities ) { cacheResultSetEntities ( result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Caches returned entities . Replaces new instances with existing ones . [CODESPLIT] protected void cacheResultSetEntities ( final Object [ ] result ) { if ( entitiesCache == null ) { entitiesCache = new HashMap <> ( ) ; } for ( int i = 0 ; i < result . length ; i ++ ) { Object object = result [ i ] ; if ( object == null ) { continue ; } DbEntityDescriptor ded = cachedDbEntityDescriptors [ i ] ; if ( ded == null ) { // not a type, continue continue ; } // calculate key Object key ; if ( ded . hasIdColumn ( ) ) { //noinspection unchecked key = ded . getKeyValue ( object ) ; } else { key = object ; } Object cachedObject = entitiesCache . get ( key ) ; if ( cachedObject == null ) { // object is not in the cache, add it entitiesCache . put ( key , object ) ; } else { // object is in the cache, replace it result [ i ] = cachedObject ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves all providers in the class [CODESPLIT] public ProviderDefinition [ ] resolve ( final Class type , final String name ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; MethodDescriptor [ ] methods = cd . getAllMethodDescriptors ( ) ; List < ProviderDefinition > list = new ArrayList <> ( ) ; for ( MethodDescriptor methodDescriptor : methods ) { Method method = methodDescriptor . getMethod ( ) ; PetiteProvider petiteProvider = method . getAnnotation ( PetiteProvider . class ) ; if ( petiteProvider == null ) { continue ; } String providerName = petiteProvider . value ( ) ; if ( StringUtil . isBlank ( providerName ) ) { // default provider name providerName = method . getName ( ) ; if ( providerName . endsWith ( \"Provider\" ) ) { providerName = StringUtil . substring ( providerName , 0 , - 8 ) ; } } ProviderDefinition providerDefinition ; if ( Modifier . isStatic ( method . getModifiers ( ) ) ) { providerDefinition = new ProviderDefinition ( providerName , method ) ; } else { providerDefinition = new ProviderDefinition ( providerName , name , method ) ; } list . add ( providerDefinition ) ; } ProviderDefinition [ ] providers ; if ( list . isEmpty ( ) ) { providers = ProviderDefinition . EMPTY ; } else { providers = list . toArray ( new ProviderDefinition [ 0 ] ) ; } return providers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts entity ( type ) name to table name . [CODESPLIT] public String convertEntityNameToTableName ( String entityName ) { int ndx = entityName . indexOf ( entityNameTerminator ) ; if ( ndx != - 1 ) { entityName = entityName . substring ( 0 , ndx ) ; } StringBuilder tableName = new StringBuilder ( entityName . length ( ) * 2 ) ; if ( prefix != null ) { tableName . append ( prefix ) ; } if ( splitCamelCase ) { String convertedTableName = Format . fromCamelCase ( entityName , separatorChar ) ; tableName . append ( convertedTableName ) ; } else { tableName . append ( entityName ) ; } if ( suffix != null ) { tableName . append ( suffix ) ; } if ( ! changeCase ) { return tableName . toString ( ) ; } return uppercase ? toUppercase ( tableName ) . toString ( ) : toLowercase ( tableName ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts table name to entity ( type ) name . [CODESPLIT] public String convertTableNameToEntityName ( final String tableName ) { StringBuilder className = new StringBuilder ( tableName . length ( ) ) ; int len = tableName . length ( ) ; int i = 0 ; if ( prefix != null ) { if ( tableName . startsWith ( prefix ) ) { i = prefix . length ( ) ; } } if ( suffix != null ) { if ( tableName . endsWith ( suffix ) ) { len -= suffix . length ( ) ; } } if ( splitCamelCase ) { boolean toUpper = true ; for ( ; i < len ; i ++ ) { char c = tableName . charAt ( i ) ; if ( c == separatorChar ) { toUpper = true ; continue ; } if ( toUpper ) { className . append ( Character . toUpperCase ( c ) ) ; toUpper = false ; } else { className . append ( Character . toLowerCase ( c ) ) ; } } return className . toString ( ) ; } return tableName . substring ( i , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies table naming strategy to given table name hint . Returns full table name . [CODESPLIT] public String applyToTableName ( final String tableName ) { String entityName = convertTableNameToEntityName ( tableName ) ; return convertEntityNameToTableName ( entityName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public synchronized void init ( ) { if ( initialised ) { return ; } if ( log . isInfoEnabled ( ) ) { log . info ( \"Core connection pool initialization\" ) ; } try { Class . forName ( driver ) ; } catch ( ClassNotFoundException cnfex ) { throw new DbSqlException ( \"Database driver not found: \" + driver , cnfex ) ; } if ( minConnections > maxConnections ) { minConnections = maxConnections ; } availableConnections = new ArrayList <> ( maxConnections ) ; busyConnections = new ArrayList <> ( maxConnections ) ; for ( int i = 0 ; i < minConnections ; i ++ ) { try { Connection conn = DriverManager . getConnection ( url , user , password ) ; availableConnections . add ( new ConnectionData ( conn ) ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"No database connection\" , sex ) ; } } initialised = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public synchronized Connection getConnection ( ) { if ( availableConnections == null ) { throw new DbSqlException ( \"Connection pool is not initialized\" ) ; } if ( ! availableConnections . isEmpty ( ) ) { int lastIndex = availableConnections . size ( ) - 1 ; ConnectionData existingConnection = availableConnections . get ( lastIndex ) ; availableConnections . remove ( lastIndex ) ; // If conn on available list is closed (e.g., it timed out), then remove it from available list // and repeat the process of obtaining a conn. Also wake up threads that were waiting for a // conn because maxConnection limit was reached. long now = System . currentTimeMillis ( ) ; boolean isValid = isConnectionValid ( existingConnection , now ) ; if ( ! isValid ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Pooled connection not valid, resetting\" ) ; } notifyAll ( ) ; // freed up a spot for anybody waiting return getConnection ( ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Returning valid pooled connection\" ) ; } busyConnections . add ( existingConnection ) ; existingConnection . lastUsed = now ; return existingConnection . connection ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( \"No more available connections\" ) ; } // no available connections if ( ( ( availableConnections . size ( ) + busyConnections . size ( ) ) < maxConnections ) && ! connectionPending ) { makeBackgroundConnection ( ) ; } else if ( ! waitIfBusy ) { throw new DbSqlException ( \"Connection limit reached: \" + maxConnections ) ; } // wait for either a new conn to be established (if you called makeBackgroundConnection) or for // an existing conn to be freed up. try { wait ( ) ; } catch ( InterruptedException ie ) { // ignore } // someone freed up a conn, so try again. return getConnection ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if existing connection is valid and available . It may happens that if connection is not used for a while it becomes inactive although not technically closed . [CODESPLIT] private boolean isConnectionValid ( final ConnectionData connectionData , final long now ) { if ( ! validateConnection ) { return true ; } if ( now < connectionData . lastUsed + validationTimeout ) { return true ; } Connection conn = connectionData . connection ; if ( validationQuery == null ) { try { return ! conn . isClosed ( ) ; } catch ( SQLException sex ) { return false ; } } boolean valid = true ; Statement st = null ; try { st = conn . createStatement ( ) ; st . execute ( validationQuery ) ; } catch ( SQLException sex ) { valid = false ; } finally { if ( st != null ) { try { st . close ( ) ; } catch ( SQLException ignore ) { } } } return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close all the connections . Use with caution : be sure no connections are in use before calling . Note that you are not <i > required< / i > to call this when done with a ConnectionPool since connections are guaranteed to be closed when garbage collected . But this method gives more control regarding when the connections are closed . [CODESPLIT] @ Override public synchronized void close ( ) { if ( log . isInfoEnabled ( ) ) { log . info ( \"Core connection pool shutdown\" ) ; } closeConnections ( availableConnections ) ; availableConnections = new ArrayList <> ( maxConnections ) ; closeConnections ( busyConnections ) ; busyConnections = new ArrayList <> ( maxConnections ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the view by dispatching to the target JSP . [CODESPLIT] @ Override protected void renderView ( final ActionRequest actionRequest , final String target ) throws Exception { HttpServletRequest request = actionRequest . getHttpServletRequest ( ) ; HttpServletResponse response = actionRequest . getHttpServletResponse ( ) ; RequestDispatcher dispatcher = request . getRequestDispatcher ( target ) ; if ( dispatcher == null ) { response . sendError ( SC_NOT_FOUND , \"Result not found: \" + target ) ; // should never happened return ; } // If we're included, then include the view, otherwise do forward. // This allow the page to, for example, set content type. if ( DispatcherUtil . isPageIncluded ( request , response ) ) { dispatcher . include ( request , response ) ; } else { dispatcher . forward ( request , response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates target using path with various extensions appended . [CODESPLIT] @ Override protected String locateTarget ( final ActionRequest actionRequest , String path ) { String target ; if ( path . endsWith ( StringPool . SLASH ) ) { path = path + defaultViewPageName ; } for ( final String ext : defaultViewExtensions ) { target = path + ext ; if ( targetExists ( actionRequest , target ) ) { return target ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if target exists . [CODESPLIT] protected boolean targetExists ( final ActionRequest actionRequest , final String target ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"target check: \" + target ) ; } final ServletContext servletContext = actionRequest . getHttpServletRequest ( ) . getServletContext ( ) ; try { return servletContext . getResource ( target ) != null ; } catch ( MalformedURLException ignore ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns buffered writer if buffering is enabled otherwise returns the original writer . [CODESPLIT] @ Override public PrintWriter getWriter ( ) throws IOException { preResponseCommit ( ) ; if ( buffer == null ) { return getResponse ( ) . getWriter ( ) ; } return buffer . getWriter ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns buffered output stream if buffering is enabled otherwise returns the original stream . [CODESPLIT] @ Override public ServletOutputStream getOutputStream ( ) throws IOException { preResponseCommit ( ) ; if ( buffer == null ) { return getResponse ( ) . getOutputStream ( ) ; } return buffer . getOutputStream ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns buffered content as chars no matter if stream or writer is used . Returns <code > null< / code > if buffering was not enabled . [CODESPLIT] public char [ ] getBufferContentAsChars ( ) { if ( buffer == null ) { return null ; } if ( ! buffer . isUsingStream ( ) ) { return buffer . toCharArray ( ) ; } byte [ ] content = buffer . toByteArray ( ) ; String encoding = getContentTypeEncoding ( ) ; if ( encoding == null ) { // assume default encoding return CharUtil . toCharArray ( content ) ; } else { return CharUtil . toCharArray ( content , encoding ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes content to original output stream using either output stream or writer depending on how the content was buffered . It is assumed that provided content is a modified wrapped content . [CODESPLIT] public void writeContentToResponse ( final char [ ] content ) throws IOException { if ( buffer == null ) { return ; } if ( buffer . isUsingStream ( ) ) { ServletOutputStream outputStream = getResponse ( ) . getOutputStream ( ) ; String encoding = getContentTypeEncoding ( ) ; if ( encoding == null ) { outputStream . write ( CharUtil . toByteArray ( content ) ) ; } else { outputStream . write ( CharUtil . toByteArray ( content , encoding ) ) ; } outputStream . flush ( ) ; } else { Writer out = getResponse ( ) . getWriter ( ) ; out . write ( content ) ; out . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes ( unmodified ) buffered content using either output stream or writer . May be used for writing the unmodified response . Of course you may { [CODESPLIT] public void writeContentToResponse ( ) throws IOException { if ( buffer == null ) { return ; } if ( buffer . isUsingStream ( ) ) { ServletOutputStream outputStream = getResponse ( ) . getOutputStream ( ) ; outputStream . write ( buffer . toByteArray ( ) ) ; outputStream . flush ( ) ; } else { Writer out = getResponse ( ) . getWriter ( ) ; out . write ( buffer . toCharArray ( ) ) ; out . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the content type and enables or disables buffering . [CODESPLIT] @ Override public void setContentType ( final String type ) { super . setContentType ( type ) ; contentTypeResolver = new ContentTypeHeaderResolver ( type ) ; if ( bufferContentType ( type , contentTypeResolver . getMimeType ( ) , contentTypeResolver . getEncoding ( ) ) ) { enableBuffering ( ) ; } else { disableBuffering ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prevents setting content - length if buffering enabled . [CODESPLIT] @ Override public void setHeader ( final String name , final String value ) { String lowerName = name . toLowerCase ( ) ; if ( lowerName . equals ( CONTENT_TYPE ) ) { setContentType ( value ) ; } else if ( buffer == null || ! lowerName . equals ( CONTENT_LENGTH ) ) { super . setHeader ( name , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prevents setting content - length if buffering enabled . [CODESPLIT] @ Override public void setIntHeader ( final String name , final int value ) { if ( buffer == null || ! name . equalsIgnoreCase ( CONTENT_LENGTH ) ) { super . setIntHeader ( name , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends string to the buffer . [CODESPLIT] public void print ( final String string ) throws IOException { if ( isBufferStreamBased ( ) ) { String encoding = getContentTypeEncoding ( ) ; byte [ ] bytes ; if ( encoding == null ) { bytes = string . getBytes ( ) ; } else { bytes = string . getBytes ( encoding ) ; } buffer . getOutputStream ( ) . write ( bytes ) ; return ; } // make sure at least writer is initialized buffer . getWriter ( ) . write ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate user and start user session . [CODESPLIT] protected JsonResult login ( ) { T authToken ; authToken = loginViaBasicAuth ( servletRequest ) ; if ( authToken == null ) { authToken = loginViaRequestParams ( servletRequest ) ; } if ( authToken == null ) { log . warn ( \"Login failed.\" ) ; return JsonResult . of ( HttpStatus . error401 ( ) . unauthorized ( \"Login failed.\" ) ) ; } log . info ( \"login OK!\" ) ; final UserSession < T > userSession = new UserSession <> ( authToken , userAuth . tokenValue ( authToken ) ) ; userSession . start ( servletRequest , servletResponse ) ; // return token return tokenAsJson ( authToken ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the JSON payload that carries on the token value . [CODESPLIT] protected JsonResult tokenAsJson ( final T authToken ) { final JsonObject jsonObject = new JsonObject ( ) ; jsonObject . put ( \"token\" , userAuth . tokenValue ( authToken ) ) ; return JsonResult . of ( jsonObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to login user with form data . Returns session object otherwise returns <code > null< / code > . [CODESPLIT] protected T loginViaRequestParams ( final HttpServletRequest servletRequest ) { final String username = servletRequest . getParameter ( PARAM_USERNAME ) . trim ( ) ; if ( StringUtil . isEmpty ( username ) ) { return null ; } final String password = servletRequest . getParameter ( PARAM_PASSWORD ) . trim ( ) ; return userAuth . login ( username , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to login user with basic authentication . [CODESPLIT] protected T loginViaBasicAuth ( final HttpServletRequest servletRequest ) { final String username = ServletUtil . resolveAuthUsername ( servletRequest ) ; if ( username == null ) { return null ; } final String password = ServletUtil . resolveAuthPassword ( servletRequest ) ; return userAuth . login ( username , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logout hook . [CODESPLIT] protected JsonResult logout ( ) { log . debug ( \"logout user\" ) ; UserSession . stop ( servletRequest , servletResponse ) ; return JsonResult . of ( HttpStatus . ok ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- utils [CODESPLIT] private static < V > Set < V > set ( final int size , final V [ ] array ) { int index = 0 ; final Set < V > set = new HashSet <> ( ) ; for ( final V v : array ) { set . add ( v ) ; index ++ ; if ( index == size ) { break ; } } return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simple factory for { [CODESPLIT] public static File file ( String fileName ) { fileName = StringUtil . replace ( fileName , USER_HOME , SystemUtil . info ( ) . getHomeDir ( ) ) ; return new File ( fileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts { [CODESPLIT] public static File toFile ( final URL url ) { String fileName = toFileName ( url ) ; if ( fileName == null ) { return null ; } return file ( fileName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts { @link File } { @link URL } s to file name . Accepts only { @link URL } s with file protocol . Otherwise for other schemes returns { @code null } . [CODESPLIT] public static String toFileName ( final URL url ) { if ( ( url == null ) || ! ( url . getProtocol ( ) . equals ( FILE_PROTOCOL ) ) ) { return null ; } String filename = url . getFile ( ) . replace ( ' ' , File . separatorChar ) ; return URLDecoder . decode ( filename , encoding ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a file of either a folder or a containing archive . [CODESPLIT] public static File toContainerFile ( final URL url ) { String protocol = url . getProtocol ( ) ; if ( protocol . equals ( FILE_PROTOCOL ) ) { return toFile ( url ) ; } String path = url . getPath ( ) ; return new File ( URI . create ( path . substring ( ZERO , path . lastIndexOf ( \"!/\" ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates all directories at once . [CODESPLIT] public static File mkdirs ( final File dirs ) throws IOException { if ( dirs . exists ( ) ) { checkIsDirectory ( dirs ) ; return dirs ; } return checkCreateDirectory ( dirs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates single directory . [CODESPLIT] public static File mkdir ( final File dir ) throws IOException { if ( dir . exists ( ) ) { checkIsDirectory ( dir ) ; return dir ; } return checkCreateDirectory ( dir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements the Unix touch utility . It creates a new { [CODESPLIT] public static void touch ( final File file ) throws IOException { if ( ! file . exists ( ) ) { StreamUtil . close ( new FileOutputStream ( file , false ) ) ; } file . setLastModified ( System . currentTimeMillis ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies a { @link File } to another { @link File } . [CODESPLIT] public static void copyFile ( final File srcFile , final File destFile ) throws IOException { checkFileCopy ( srcFile , destFile ) ; _copyFile ( srcFile , destFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal file copy when most of the pre - checking has passed . [CODESPLIT] private static void _copyFile ( final File srcFile , final File destFile ) throws IOException { if ( destFile . exists ( ) ) { if ( destFile . isDirectory ( ) ) { throw new IOException ( \"Destination '\" + destFile + \"' is a directory\" ) ; } } // do copy file FileInputStream input = null ; FileOutputStream output = null ; try { input = new FileInputStream ( srcFile ) ; output = new FileOutputStream ( destFile , false ) ; StreamUtil . copy ( input , output ) ; } finally { StreamUtil . close ( output ) ; StreamUtil . close ( input ) ; } // done if ( srcFile . length ( ) != destFile . length ( ) ) { throw new IOException ( \"Copy file failed of '\" + srcFile + \"' to '\" + destFile + \"' due to different sizes\" ) ; } destFile . setLastModified ( srcFile . lastModified ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies a { [CODESPLIT] public static File copyFileToDir ( final File srcFile , final File destDir ) throws IOException { checkExistsAndDirectory ( destDir ) ; File destFile = file ( destDir , srcFile . getName ( ) ) ; copyFile ( srcFile , destFile ) ; return destFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies directory with specified copy params . [CODESPLIT] public static void copyDir ( final File srcDir , final File destDir ) throws IOException { checkDirCopy ( srcDir , destDir ) ; _copyDirectory ( srcDir , destDir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves a { @link File } . [CODESPLIT] private static void _moveFile ( final File srcFile , final File destFile ) throws IOException { if ( destFile . exists ( ) ) { checkIsFile ( destFile ) ; destFile . delete ( ) ; } final boolean rename = srcFile . renameTo ( destFile ) ; if ( ! rename ) { _copyFile ( srcFile , destFile ) ; srcFile . delete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves a file to a directory . [CODESPLIT] public static File moveFileToDir ( final File srcFile , final File destDir ) throws IOException { checkExistsAndDirectory ( destDir ) ; return moveFile ( srcFile , file ( destDir , srcFile . getName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves a directory . [CODESPLIT] private static void _moveDirectory ( final File srcDest , File destDir ) throws IOException { if ( destDir . exists ( ) ) { checkIsDirectory ( destDir ) ; destDir = file ( destDir , destDir . getName ( ) ) ; destDir . mkdir ( ) ; } final boolean rename = srcDest . renameTo ( destDir ) ; if ( ! rename ) { _copyDirectory ( srcDest , destDir ) ; deleteDir ( srcDest ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans a directory without deleting it . [CODESPLIT] public static void cleanDir ( final File destDir ) throws IOException { checkExists ( destDir ) ; checkIsDirectory ( destDir ) ; File [ ] files = destDir . listFiles ( ) ; if ( files == null ) { throw new IOException ( \"Failed to list contents of: \" + destDir ) ; } IOException exception = null ; for ( File file : files ) { try { if ( file . isDirectory ( ) ) { deleteDir ( file ) ; } else { file . delete ( ) ; } } catch ( IOException ioex ) { exception = ioex ; continue ; } } if ( exception != null ) { throw exception ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads UTF file content as char array . [CODESPLIT] public static char [ ] readUTFChars ( final File file ) throws IOException { checkExists ( file ) ; checkIsFile ( file ) ; UnicodeInputStream in = unicodeInputStreamOf ( file ) ; try { return StreamUtil . readChars ( in , detectEncoding ( in ) ) ; } finally { StreamUtil . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads file content as char array . [CODESPLIT] public static char [ ] readChars ( final File file , final String encoding ) throws IOException { checkExists ( file ) ; checkIsFile ( file ) ; InputStream in = streamOf ( file , encoding ) ; try { return StreamUtil . readChars ( in , encoding ) ; } finally { StreamUtil . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write characters . append = false [CODESPLIT] public static void writeChars ( final File dest , final char [ ] data , final String encoding ) throws IOException { outChars ( dest , data , encoding , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes characters to { @link File } destination . [CODESPLIT] protected static void outChars ( final File dest , final char [ ] data , final String encoding , final boolean append ) throws IOException { if ( dest . exists ( ) ) { checkIsFile ( dest ) ; } Writer out = new BufferedWriter ( StreamUtil . outputStreamWriterOf ( new FileOutputStream ( dest , append ) , encoding ) ) ; try { out . write ( data ) ; } finally { StreamUtil . close ( out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects optional BOM and reads UTF { @link String } from a { @link File } . If BOM is missing UTF - 8 is assumed . [CODESPLIT] public static String readUTFString ( final File file ) throws IOException { UnicodeInputStream in = unicodeInputStreamOf ( file ) ; try { return StreamUtil . copy ( in , detectEncoding ( in ) ) . toString ( ) ; } finally { StreamUtil . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects optional BOM and reads UTF { @link String } from an { @link InputStream } . If BOM is missing UTF - 8 is assumed . [CODESPLIT] public static String readUTFString ( final InputStream inputStream ) throws IOException { UnicodeInputStream in = null ; try { in = new UnicodeInputStream ( inputStream , null ) ; return StreamUtil . copy ( in , detectEncoding ( in ) ) . toString ( ) ; } finally { StreamUtil . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads { @link File } content as { @link String } encoded in provided encoding . For UTF encoded files detects optional BOM characters . [CODESPLIT] public static String readString ( final File file , final String encoding ) throws IOException { checkExists ( file ) ; checkIsFile ( file ) ; InputStream in = streamOf ( file , encoding ) ; try { return StreamUtil . copy ( in , encoding ) . toString ( ) ; } finally { StreamUtil . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes String . append = false [CODESPLIT] public static void writeString ( final File dest , final String data , final String encoding ) throws IOException { outString ( dest , data , encoding , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends String . append = true [CODESPLIT] public static void appendString ( final File dest , final String data , final String encoding ) throws IOException { outString ( dest , data , encoding , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data using encoding to { @link File } . [CODESPLIT] protected static void outString ( final File dest , final String data , final String encoding , final boolean append ) throws IOException { if ( dest . exists ( ) ) { checkIsFile ( dest ) ; } FileOutputStream out = null ; try { out = new FileOutputStream ( dest , append ) ; out . write ( data . getBytes ( encoding ) ) ; } finally { StreamUtil . close ( out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write { @link InputStream } in to { @link FileOutputStream } . [CODESPLIT] public static void writeStream ( final FileOutputStream out , final InputStream in ) throws IOException { try { StreamUtil . copy ( in , out ) ; } finally { StreamUtil . close ( out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads lines from source { @link File } with specified encoding and returns lines as { @link String } s in array . [CODESPLIT] public static String [ ] readLines ( final File file , final String encoding ) throws IOException { checkExists ( file ) ; checkIsFile ( file ) ; List < String > list = new ArrayList <> ( ) ; InputStream in = streamOf ( file , encoding ) ; try { BufferedReader br = new BufferedReader ( StreamUtil . inputStreamReadeOf ( in , encoding ) ) ; String strLine ; while ( ( strLine = br . readLine ( ) ) != null ) { list . add ( strLine ) ; } } finally { StreamUtil . close ( in ) ; } return list . toArray ( new String [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read file and returns byte array with contents . [CODESPLIT] public static byte [ ] readBytes ( final File file , final int count ) throws IOException { checkExists ( file ) ; checkIsFile ( file ) ; long numToRead = file . length ( ) ; if ( numToRead >= Integer . MAX_VALUE ) { throw new IOException ( \"File is larger then max array size\" ) ; } if ( count > NEGATIVE_ONE && count < numToRead ) { numToRead = count ; } byte [ ] bytes = new byte [ ( int ) numToRead ] ; RandomAccessFile randomAccessFile = new RandomAccessFile ( file , \"r\" ) ; randomAccessFile . readFully ( bytes ) ; randomAccessFile . close ( ) ; return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write bytes . append = false [CODESPLIT] public static void writeBytes ( final File dest , final byte [ ] data , final int off , final int len ) throws IOException { outBytes ( dest , data , off , len , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends bytes . append = true [CODESPLIT] public static void appendBytes ( final File dest , final byte [ ] data , final int off , final int len ) throws IOException { outBytes ( dest , data , off , len , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to { @link File } destination . [CODESPLIT] protected static void outBytes ( final File dest , final byte [ ] data , final int off , final int len , final boolean append ) throws IOException { if ( dest . exists ( ) ) { checkIsFile ( dest ) ; } FileOutputStream out = null ; try { out = new FileOutputStream ( dest , append ) ; out . write ( data , off , len ) ; } finally { StreamUtil . close ( out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- equals content [CODESPLIT] public static boolean compare ( final String file1 , final String file2 ) throws IOException { return compare ( file ( file1 ) , file ( file2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare the contents of two { [CODESPLIT] public static boolean compare ( final File one , final File two ) throws IOException { boolean file1Exists = one . exists ( ) ; if ( file1Exists != two . exists ( ) ) { return false ; } if ( ! file1Exists ) { return true ; } if ( ( ! one . isFile ( ) ) || ( ! two . isFile ( ) ) ) { throw new IOException ( \"Only files can be compared\" ) ; } if ( one . length ( ) != two . length ( ) ) { return false ; } if ( equals ( one , two ) ) { return true ; } InputStream input1 = null ; InputStream input2 = null ; try { input1 = new FileInputStream ( one ) ; input2 = new FileInputStream ( two ) ; return StreamUtil . compare ( input1 , input2 ) ; } finally { StreamUtil . close ( input1 ) ; StreamUtil . close ( input2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses { @link File#lastModified () } for reference . [CODESPLIT] public static boolean isNewer ( final File file , final File reference ) { checkReferenceExists ( reference ) ; return isNewer ( file , reference . lastModified ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses { @link File#lastModified () } for reference . [CODESPLIT] public static boolean isOlder ( final File file , final File reference ) { checkReferenceExists ( reference ) ; return isOlder ( file , reference . lastModified ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Smart copy . If source is a directory copy it to destination . Otherwise if destination is directory copy source file to it . Otherwise try to copy source file to destination file . [CODESPLIT] public static void copy ( final File src , final File dest ) throws IOException { if ( src . isDirectory ( ) ) { copyDir ( src , dest ) ; return ; } if ( dest . isDirectory ( ) ) { copyFileToDir ( src , dest ) ; return ; } copyFile ( src , dest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Smart move . If source is a directory move it to destination . Otherwise if destination is directory move source { @link File } to it . Otherwise try to move source { @link File } to destination { @link File } . [CODESPLIT] public static void move ( final File src , final File dest ) throws IOException { if ( src . isDirectory ( ) ) { moveDir ( src , dest ) ; return ; } if ( dest . isDirectory ( ) ) { moveFileToDir ( src , dest ) ; return ; } moveFile ( src , dest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Smart delete of destination file or directory . [CODESPLIT] public static void delete ( final File dest ) throws IOException { if ( dest . isDirectory ( ) ) { deleteDir ( dest ) ; return ; } deleteFile ( dest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if one { @link File } is an ancestor of second one . [CODESPLIT] public static boolean isAncestor ( final File ancestor , final File file , final boolean strict ) { File parent = strict ? getParentFile ( file ) : file ; while ( true ) { if ( parent == null ) { return false ; } if ( parent . equals ( ancestor ) ) { return true ; } parent = getParentFile ( parent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns parent for the file . The method correctly processes . and .. in { @link File } names . The name remains relative if was relative before . Returns { @code null } if the { @link File } has no parent . [CODESPLIT] public static File getParentFile ( final File file ) { int skipCount = ZERO ; File parentFile = file ; while ( true ) { parentFile = parentFile . getParentFile ( ) ; if ( parentFile == null ) { return null ; } if ( StringPool . DOT . equals ( parentFile . getName ( ) ) ) { continue ; } if ( StringPool . DOTDOT . equals ( parentFile . getName ( ) ) ) { skipCount ++ ; continue ; } if ( skipCount > ZERO ) { skipCount -- ; continue ; } return parentFile ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if file and its ancestors are acceptable by using { @link FileFilter#accept ( File ) } . [CODESPLIT] public static boolean isFilePathAcceptable ( File file , final FileFilter fileFilter ) { do { if ( fileFilter != null && ! fileFilter . accept ( file ) ) { return false ; } file = file . getParentFile ( ) ; } while ( file != null ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates temporary directory . [CODESPLIT] public static File createTempDirectory ( final String prefix , final String suffix , final File tempDir ) throws IOException { File file = createTempFile ( prefix , suffix , tempDir ) ; file . delete ( ) ; file . mkdir ( ) ; return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates temporary { @link File } . [CODESPLIT] public static File createTempFile ( final String prefix , final String suffix , final File tempDir , final boolean create ) throws IOException { File file = createTempFile ( prefix , suffix , tempDir ) ; file . delete ( ) ; if ( create ) { file . createNewFile ( ) ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates temporary { @link File } . Wraps Java method and repeats creation several times if something fails . [CODESPLIT] public static File createTempFile ( final String prefix , final String suffix , final File tempDir ) throws IOException { int exceptionsCount = ZERO ; while ( true ) { try { return File . createTempFile ( prefix , suffix , tempDir ) . getCanonicalFile ( ) ; } catch ( IOException ioex ) { // fixes java.io.WinNTFileSystem.createFileExclusively access denied if ( ++ exceptionsCount >= 50 ) { throw ioex ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the start of the file for ASCII control characters [CODESPLIT] public static boolean isBinary ( final File file ) throws IOException { byte [ ] bytes = readBytes ( file , 128 ) ; for ( byte b : bytes ) { if ( b < 32 && b != 9 && b != 10 && b != 13 ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns either new { @link FileInputStream } or new { @link UnicodeInputStream } . [CODESPLIT] private static InputStream streamOf ( final File file , final String encoding ) throws IOException { InputStream in = new FileInputStream ( file ) ; if ( encoding . startsWith ( \"UTF\" ) ) { in = unicodeInputStreamOf ( in , encoding ) ; } return in ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect encoding on { @link UnicodeInputStream } by using { @link UnicodeInputStream#getDetectedEncoding () } . [CODESPLIT] private static String detectEncoding ( final UnicodeInputStream in ) { String encoding = in . getDetectedEncoding ( ) ; if ( encoding == null ) { encoding = StringPool . UTF_8 ; } return encoding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if { @link File } exists . Throws IllegalArgumentException if not . [CODESPLIT] private static void checkReferenceExists ( final File file ) throws IllegalArgumentException { try { checkExists ( file ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( \"Reference file not found: \" + file ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if directory can be created . Throws IOException if it cannot . <p > This actually creates directory ( and its ancestors ) ( as per { @link File#mkdirs () } } ) . [CODESPLIT] private static File checkCreateDirectory ( final File dir ) throws IOException { if ( ! dir . mkdirs ( ) ) { throw new IOException ( MSG_CANT_CREATE + dir ) ; } return dir ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that srcDir exists that it is a directory and if srcDir and destDir are not equal . [CODESPLIT] private static void checkDirCopy ( final File srcDir , final File destDir ) throws IOException { checkExists ( srcDir ) ; checkIsDirectory ( srcDir ) ; if ( equals ( srcDir , destDir ) ) { throw new IOException ( \"Source '\" + srcDir + \"' and destination '\" + destDir + \"' are equal\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that file copy can occur . [CODESPLIT] private static void checkFileCopy ( final File srcFile , final File destFile ) throws IOException { checkExists ( srcFile ) ; checkIsFile ( srcFile ) ; if ( equals ( srcFile , destFile ) ) { throw new IOException ( \"Files '\" + srcFile + \"' and '\" + destFile + \"' are equal\" ) ; } File destParent = destFile . getParentFile ( ) ; if ( destParent != null && ! destParent . exists ( ) ) { checkCreateDirectory ( destParent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastBooleanBuffer append ( final FastBooleanBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the usage line . [CODESPLIT] public void printUsage ( final String commandName ) { final StringBuilder usage = new StringBuilder ( commandName ) ; for ( final Option option : options ) { if ( option . shortName != null ) { usage . append ( \" [-\" ) . append ( option . shortName ) . append ( \"]\" ) ; } else if ( option . longName != null ) { usage . append ( \" [--\" ) . append ( option . longName ) . append ( \"]\" ) ; } } for ( final Param param : params ) { usage . append ( \" \" ) . append ( param . label ) ; } System . out . println ( usage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves action method for given action class ane method name . [CODESPLIT] public Method resolveActionMethod ( final Class < ? > actionClass , final String methodName ) { MethodDescriptor methodDescriptor = ClassIntrospector . get ( ) . lookup ( actionClass ) . getMethodDescriptor ( methodName , false ) ; if ( methodDescriptor == null ) { throw new MadvocException ( \"Public method not found: \" + actionClass . getSimpleName ( ) + \"#\" + methodName ) ; } return methodDescriptor . getMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers action with provided action class and method name . [CODESPLIT] public ActionRuntime registerAction ( final Class actionClass , final String actionMethodName , final ActionDefinition actionDefinition ) { Method actionMethod = resolveActionMethod ( actionClass , actionMethodName ) ; return registerAction ( actionClass , actionMethod , actionDefinition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registration main point . Does two things : <ul > <li > { [CODESPLIT] public ActionRuntime registerAction ( final Class actionClass , final Method actionMethod , final ActionDefinition actionDefinition ) { final ActionRuntime actionRuntime = actionMethodParser . parse ( actionClass , actionMethod , actionDefinition ) ; if ( actionRuntime == null ) { return null ; } return registerActionRuntime ( actionRuntime ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers manually created { [CODESPLIT] public ActionRuntime registerActionRuntime ( final ActionRuntime actionRuntime ) { final String actionPath = actionRuntime . getActionPath ( ) ; final String method = actionRuntime . getActionMethod ( ) ; log . debug ( ( ) -> \"Madvoc action: \" + ifNotNull ( method , m -> m + \" \" ) + actionRuntime . getActionPath ( ) + \" => \" + actionRuntime . createActionString ( ) ) ; final RouteChunk routeChunk = routes . registerPath ( method , actionPath ) ; if ( routeChunk . value ( ) != null ) { // existing chunk if ( detectDuplicatePathsEnabled ) { throw new MadvocException ( \"Duplicate action path for [\" + actionRuntime + \"] occupied by: [\" + routeChunk . value ( ) + \"]\" ) ; } } else { actionsCount ++ ; } routeChunk . bind ( actionRuntime ) ; // finally runtimes . put ( actionRuntime . createActionString ( ) , actionRuntime ) ; // async check if ( actionRuntime . isAsync ( ) ) { asyncMode = true ; } return actionRuntime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- look - up [CODESPLIT] public ActionRuntime lookup ( final String method , final String [ ] actionPath ) { return routes . lookup ( method , actionPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new path alias . [CODESPLIT] public void registerPathAlias ( final String alias , final String path ) { final String existing = pathAliases . put ( alias , path ) ; if ( existing != null ) { throw new MadvocException ( \"Duplicated alias detected: [\" + alias + \"] for paths: \" + path + \", \" + existing ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates to next value at the beginning of the loop . [CODESPLIT] public boolean next ( ) { if ( ! looping ) { return false ; } if ( last ) { return false ; } if ( count == 0 ) { value = start ; first = true ; } else { value += step ; first = false ; } count ++ ; last = isLastIteration ( value + step ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static constructor that creates a char sequence by making a copy of provided char array . [CODESPLIT] public static CharArraySequence from ( final char [ ] value , final int offset , final int len ) { final char [ ] buffer = new char [ value . length ] ; System . arraycopy ( value , offset , buffer , 0 , len ) ; return new CharArraySequence ( buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastShortBuffer append ( final FastShortBuffer buff ) { if ( buff . offset == 0 ) { return this ; } append ( buff . buffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up for method in target object and invokes it using reflection . [CODESPLIT] public Object execute ( ) throws Exception { String methodName = ProxyTarget . targetMethodName ( ) ; Class [ ] argTypes = ProxyTarget . createArgumentsClassArray ( ) ; Object [ ] args = ProxyTarget . createArgumentsArray ( ) ; // lookup method on target object class (and not #targetClass!() Class type = _target . getClass ( ) ; Method method = type . getMethod ( methodName , argTypes ) ; // remember context classloader ClassLoader contextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Object result ; try { // change class loader Thread . currentThread ( ) . setContextClassLoader ( type . getClassLoader ( ) ) ; // invoke result = method . invoke ( _target , args ) ; } finally { // return context classloader Thread . currentThread ( ) . setContextClassLoader ( contextClassLoader ) ; } return ProxyTarget . returnValue ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines class and it s classloader to scan . This is not required in Java8 and would not hurt anything if called . However for Java9 you should pass <i > any< / i > user - application class so Jodd can figure out the real class path to scan . [CODESPLIT] @ Override public JoyScanner scanClasspathOf ( final Class applicationClass ) { requireNotStarted ( classScanner ) ; appClasses . add ( applicationClass ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shortcut for { [CODESPLIT] @ Override public JoyScanner scanClasspathOf ( final Object applicationObject ) { requireNotStarted ( classScanner ) ; return scanClasspathOf ( applicationObject . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures scanner class finder . Works for all three scanners : Petite DbOom and Madvoc . All scanners by default include all jars but exclude all entries . [CODESPLIT] @ Override public void start ( ) { initLogger ( ) ; log . info ( \"SCANNER start ----------\" ) ; classScanner = new ClassScanner ( ) { @ Override protected void scanJarFile ( final File file ) { log . debug ( \"Scanning jar: \" + file ) ; super . scanJarFile ( file ) ; } @ Override protected void scanClassPath ( final File root ) { log . debug ( \"Scanning path: \" + root ) ; super . scanClassPath ( root ) ; } } ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Scan entries: \" + Converter . get ( ) . toString ( includedEntries ) ) ; log . debug ( \"Scan jars: \" + Converter . get ( ) . toString ( includedJars ) ) ; log . debug ( \"Scan exclude jars: \" + Converter . get ( ) . toString ( excludedJars ) ) ; log . debug ( \"Scan ignore exception: \" + ignoreExceptions ) ; } classScanner . excludeCommonEntries ( ) ; classScanner . excludeCommonJars ( ) ; classScanner . excludeJars ( excludedJars . toArray ( new String [ 0 ] ) ) ; if ( includedEntries . isEmpty ( ) && includedJars . isEmpty ( ) ) { // nothing was explicitly included classScanner . excludeAllEntries ( false ) ; } else { // something was included by user classScanner . excludeAllEntries ( true ) ; includedEntries . add ( \"jodd.*\" ) ; } classScanner . detectEntriesMode ( true ) . includeEntries ( includedEntries . toArray ( new String [ 0 ] ) ) . includeJars ( includedJars . toArray ( new String [ 0 ] ) ) . ignoreException ( ignoreExceptions ) . scanDefaultClasspath ( ) ; appClasses . forEach ( clazz -> classScanner . scan ( ClassPathURLs . of ( null , clazz ) ) ) ; log . info ( \"SCANNER OK!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- javascripts [CODESPLIT] @ Override public void script ( final Tag tag , final CharSequence body ) { if ( ! insideConditionalComment ) { String src = Util . toString ( tag . getAttributeValue ( \"src\" ) ) ; if ( src == null ) { super . script ( tag , body ) ; return ; } if ( jsBundleAction . acceptLink ( src ) ) { String link = jsBundleAction . processLink ( src ) ; if ( link != null ) { tag . setAttributeValue ( \"src\" , link ) ; super . script ( tag , body ) ; } return ; } } super . script ( tag , body ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- conditional comments [CODESPLIT] @ Override public void condComment ( final CharSequence expression , final boolean isStartingTag , final boolean isHidden , final boolean isHiddenEndTag ) { insideConditionalComment = isStartingTag ; super . condComment ( expression , isStartingTag , isHidden , isHiddenEndTag ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Post process final content . Required for <code > RESOURCE_ONLY< / code > strategy . [CODESPLIT] public char [ ] postProcess ( char [ ] content ) { content = jsBundleAction . replaceBundleId ( content ) ; content = cssBundleAction . replaceBundleId ( content ) ; return content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps checked exceptions in a <code > UncheckedException< / code > . Unchecked exceptions are not wrapped . [CODESPLIT] public static < V > V callAndWrapException ( final Callable < V > callable ) { try { return callable . call ( ) ; } catch ( IOException ioex ) { throw new UncheckedIOException ( ioex ) ; } catch ( RuntimeException rtex ) { throw rtex ; } catch ( Exception t ) { throw new UncheckedException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps checked exceptions in a <code > UncheckedException< / code > . Unchecked exceptions are not wrapped . [CODESPLIT] public static void runAndWrapException ( final CallableVoid callable ) { try { callable . call ( ) ; } catch ( IOException ioex ) { throw new UncheckedIOException ( ioex ) ; } catch ( RuntimeException rtex ) { throw rtex ; } catch ( Exception t ) { throw new UncheckedException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a character in some range and returns its index . Returns <code > - 1< / code > if character is not found . [CODESPLIT] protected final int find ( final char target , int from , final int end ) { while ( from < end ) { if ( input [ from ] == target ) { break ; } from ++ ; } return ( from == end ) ? - 1 : from ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds character buffer in some range and returns its index . Returns <code > - 1< / code > if character is not found . [CODESPLIT] protected final int find ( final char [ ] target , int from , final int end ) { while ( from < end ) { if ( match ( target , from ) ) { break ; } from ++ ; } return ( from == end ) ? - 1 : from ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches char buffer with content on given location . [CODESPLIT] protected final boolean match ( final char [ ] target , final int ndx ) { if ( ndx + target . length >= total ) { return false ; } int j = ndx ; for ( int i = 0 ; i < target . length ; i ++ , j ++ ) { if ( input [ j ] != target [ i ] ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches char buffer given in uppercase with content at current location that will be converted to upper case to make case - insensitive matching . [CODESPLIT] public final boolean matchUpperCase ( final char [ ] uppercaseTarget ) { if ( ndx + uppercaseTarget . length > total ) { return false ; } int j = ndx ; for ( int i = 0 ; i < uppercaseTarget . length ; i ++ , j ++ ) { final char c = CharUtil . toUpperAscii ( input [ j ] ) ; if ( c != uppercaseTarget [ i ] ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates char sub - sequence from the input . [CODESPLIT] protected final CharSequence charSequence ( final int from , final int to ) { if ( from == to ) { return CharArraySequence . EMPTY ; } return CharArraySequence . of ( input , from , to - from ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates { [CODESPLIT] protected Position position ( final int position ) { int line ; int offset ; int lastNewLineOffset ; if ( position > lastOffset ) { line = 1 ; offset = 0 ; lastNewLineOffset = 0 ; } else { line = lastLine ; offset = lastOffset ; lastNewLineOffset = lastLastNewLineOffset ; } while ( offset < position ) { final char c = input [ offset ] ; if ( c == ' ' ) { line ++ ; lastNewLineOffset = offset + 1 ; } offset ++ ; } lastOffset = offset ; lastLine = line ; lastLastNewLineOffset = lastNewLineOffset ; return new Position ( position , line , position - lastNewLineOffset + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests for transaction and returns non - null value <b > only< / b > when new transaction is created! When <code > null< / code > is returned transaction may be get by { @link #getCurrentTransaction () } . [CODESPLIT] public JtxTransaction maybeRequestTransaction ( final JtxTransactionMode txMode , final Object scope ) { if ( txMode == null ) { return null ; } JtxTransaction currentTx = txManager . getTransaction ( ) ; JtxTransaction requestedTx = txManager . requestTransaction ( txMode , scope ) ; if ( currentTx == requestedTx ) { return null ; } return requestedTx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commits transaction if created in the same level where this method is invoked . Returns <code > true< / code > if transaction was actually committed or <code > false< / code > if transaction was not created on this level . [CODESPLIT] public boolean maybeCommitTransaction ( final JtxTransaction tx ) { if ( tx == null ) { return false ; } log . debug ( \"commit tx\" ) ; tx . commit ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rollbacks transaction if created in the same scope where this method is invoked . If not current transaction is marked for rollback . Returns <code > true< / code > if transaction was actually roll backed . [CODESPLIT] public boolean markOrRollbackTransaction ( JtxTransaction tx , final Throwable cause ) { if ( tx == null ) { tx = getCurrentTransaction ( ) ; if ( tx == null ) { return false ; } log . debug ( \"set rollback only tx\" ) ; tx . setRollbackOnly ( cause ) ; return false ; } log . debug ( \"rollback tx\" ) ; tx . rollback ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns urls for the classloader . [CODESPLIT] public static URL [ ] of ( ClassLoader classLoader , Class clazz ) { if ( clazz == null ) { clazz = ClassPathURLs . class ; } if ( classLoader == null ) { classLoader = clazz . getClassLoader ( ) ; } final Set < URL > urls = new LinkedHashSet <> ( ) ; while ( classLoader != null ) { if ( classLoader instanceof URLClassLoader ) { URLClassLoader urlClassLoader = ( URLClassLoader ) classLoader ; URL [ ] allURLS = urlClassLoader . getURLs ( ) ; Collections . addAll ( urls , allURLS ) ; break ; } URL classUrl = classModuleUrl ( classLoader , clazz ) ; if ( classUrl != null ) { urls . add ( classUrl ) ; } classUrl = classModuleUrl ( classLoader , ClassPathURLs . class ) ; if ( classUrl != null ) { urls . add ( classUrl ) ; } ModuleDescriptor moduleDescriptor = clazz . getModule ( ) . getDescriptor ( ) ; if ( moduleDescriptor != null ) { moduleDescriptor . requires ( ) . forEach ( req -> { ModuleLayer . boot ( ) . findModule ( req . name ( ) ) . ifPresent ( mod -> { ClassLoader moduleClassLoader = mod . getClassLoader ( ) ; if ( moduleClassLoader != null ) { URL url = moduleClassLoader . getResource ( MANIFEST ) ; if ( url != null ) { url = fixManifestUrl ( url ) ; urls . add ( url ) ; } } } ) ; } ) ; } classLoader = classLoader . getParent ( ) ; } return urls . toArray ( new URL [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- Apache Commons Codec - Base32 [CODESPLIT] @ Benchmark public String encode_Apache_Base32 ( ) { return new org . apache . commons . codec . binary . Base32 ( false ) . encodeAsString ( to_be_encoded ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends BCC address . [CODESPLIT] public Email bcc ( final EmailAddress to ) { this . bcc = ArraysUtil . append ( this . bcc , to ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends BCC address . [CODESPLIT] public Email bcc ( final String personalName , final String bcc ) { return bcc ( new EmailAddress ( personalName , bcc ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends one or more BCC addresses . [CODESPLIT] public Email bcc ( final EmailAddress ... bccs ) { this . bcc = ArraysUtil . join ( this . bcc , valueOrEmptyArray ( bccs ) ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FileUpload create ( final MultipartRequestInputStream input ) { return new AdaptiveFileUpload ( input , memoryThreshold , uploadPath , maxFileSize , breakOnError , fileExtensions , allowFileExtensions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers default set of { [CODESPLIT] public void registerDefaults ( ) { // main map . put ( Object . class , new ObjectJsonSerializer ( ) ) ; map . put ( Map . class , new MapJsonSerializer ( ) ) ; map . put ( Iterable . class , new IterableJsonSerializer ( ) ) ; map . put ( JsonObject . class , new JsonObjectSerializer ( ) ) ; map . put ( JsonArray . class , new JsonArraySerializer ( ) ) ; // arrays map . put ( int [ ] . class , new IntArrayJsonSerializer ( ) ) ; map . put ( long [ ] . class , new LongArrayJsonSerializer ( ) ) ; map . put ( double [ ] . class , new DoubleArrayJsonSerializer ( ) ) ; map . put ( float [ ] . class , new FloatArrayJsonSerializer ( ) ) ; map . put ( boolean [ ] . class , new BooleanArrayJsonSerializer ( ) ) ; map . put ( byte [ ] . class , new ByteArrayJsonSerializer ( ) ) ; map . put ( Integer [ ] . class , new ArraysJsonSerializer < Integer > ( ) { @ Override protected int getLength ( final Integer [ ] array ) { return array . length ; } @ Override protected Integer get ( final Integer [ ] array , final int index ) { return array [ index ] ; } } ) ; map . put ( Long [ ] . class , new ArraysJsonSerializer < Long > ( ) { @ Override protected int getLength ( final Long [ ] array ) { return array . length ; } @ Override protected Long get ( final Long [ ] array , final int index ) { return array [ index ] ; } } ) ; map . put ( Arrays . class , new ArraysJsonSerializer ( ) ) ; // strings TypeJsonSerializer jsonSerializer = new CharSequenceJsonSerializer ( ) ; map . put ( String . class , jsonSerializer ) ; map . put ( StringBuilder . class , jsonSerializer ) ; map . put ( CharSequence . class , jsonSerializer ) ; // number jsonSerializer = new NumberJsonSerializer ( ) ; map . put ( Number . class , jsonSerializer ) ; map . put ( Integer . class , jsonSerializer ) ; map . put ( int . class , jsonSerializer ) ; map . put ( Long . class , jsonSerializer ) ; map . put ( long . class , jsonSerializer ) ; DoubleJsonSerializer doubleJsonSerializer = new DoubleJsonSerializer ( ) ; map . put ( Double . class , doubleJsonSerializer ) ; map . put ( double . class , doubleJsonSerializer ) ; FloatJsonSerializer floatJsonSerializer = new FloatJsonSerializer ( ) ; map . put ( Float . class , floatJsonSerializer ) ; map . put ( float . class , floatJsonSerializer ) ; map . put ( BigInteger . class , jsonSerializer ) ; map . put ( BigDecimal . class , jsonSerializer ) ; // other map . put ( Boolean . class , new BooleanJsonSerializer ( ) ) ; map . put ( boolean . class , new BooleanJsonSerializer ( ) ) ; map . put ( Date . class , new DateJsonSerializer ( ) ) ; map . put ( Calendar . class , new CalendarJsonSerializer ( ) ) ; map . put ( JulianDate . class , new JulianDateSerializer ( ) ) ; map . put ( LocalDateTime . class , new LocalDateTimeSerializer ( ) ) ; map . put ( LocalDate . class , new LocalDateSerializer ( ) ) ; map . put ( LocalTime . class , new LocalTimeSerializer ( ) ) ; map . put ( Enum . class , new EnumJsonSerializer ( ) ) ; map . put ( File . class , new FileJsonSerializer ( FileJsonSerializer . Type . PATH ) ) ; //map.putUnsafe();(Collection.class, new CollectionJsonSerializer()); jsonSerializer = new CharacterJsonSerializer ( ) ; map . put ( Character . class , jsonSerializer ) ; map . put ( char . class , jsonSerializer ) ; map . put ( UUID . class , new UUIDJsonSerializer ( ) ) ; map . put ( Class . class , new ClassJsonSerializer ( ) ) ; // clear cache cache . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new serializer . [CODESPLIT] public void register ( final Class type , final TypeJsonSerializer typeJsonSerializer ) { map . put ( type , typeJsonSerializer ) ; cache . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get type serializer from map . First the current map is used . If element is missing default map will be used if exist . [CODESPLIT] protected TypeJsonSerializer lookupSerializer ( final Class type ) { TypeJsonSerializer tjs = map . get ( type ) ; if ( tjs == null ) { if ( defaultSerializerMap != null ) { tjs = defaultSerializerMap . map . get ( type ) ; } } return tjs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- load and extract [CODESPLIT] protected void putFile ( final String name , final FileUpload value ) { if ( requestFiles == null ) { requestFiles = new HashMap <> ( ) ; } FileUpload [ ] fileUploads = requestFiles . get ( name ) ; if ( fileUploads != null ) { fileUploads = ArraysUtil . append ( fileUploads , value ) ; } else { fileUploads = new FileUpload [ ] { value } ; } requestFiles . put ( name , fileUploads ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts uploaded files and parameters from the request data . [CODESPLIT] public void parseRequestStream ( final InputStream inputStream , final String encoding ) throws IOException { setParsed ( ) ; MultipartRequestInputStream input = new MultipartRequestInputStream ( inputStream ) ; input . readBoundary ( ) ; while ( true ) { FileUploadHeader header = input . readDataHeader ( encoding ) ; if ( header == null ) { break ; } if ( header . isFile ) { String fileName = header . fileName ; if ( fileName . length ( ) > 0 ) { if ( header . contentType . indexOf ( \"application/x-macbinary\" ) > 0 ) { input . skipBytes ( 128 ) ; } } FileUpload newFile = fileUploadFactory . create ( input ) ; newFile . processStream ( ) ; if ( fileName . length ( ) == 0 ) { // file was specified, but no name was provided, therefore it was not uploaded if ( newFile . getSize ( ) == 0 ) { newFile . size = - 1 ; } } putFile ( header . formFieldName , newFile ) ; } else { // no file, therefore it is regular form parameter. FastByteArrayOutputStream fbos = new FastByteArrayOutputStream ( ) ; input . copyAll ( fbos ) ; String value = encoding != null ? new String ( fbos . toByteArray ( ) , encoding ) : new String ( fbos . toByteArray ( ) ) ; putParameter ( header . formFieldName , value ) ; } input . skipBytes ( 1 ) ; input . mark ( 1 ) ; // read byte, but may be end of stream int nextByte = input . read ( ) ; if ( nextByte == - 1 || nextByte == ' ' ) { input . reset ( ) ; break ; } input . reset ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns single value of a parameter . If parameter name is used for more then one parameter only the first one will be returned . [CODESPLIT] public String getParameter ( final String paramName ) { if ( requestParameters == null ) { return null ; } String [ ] values = requestParameters . get ( paramName ) ; if ( ( values != null ) && ( values . length > 0 ) ) { return values [ 0 ] ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all values all of the values the given request parameter has . [CODESPLIT] public String [ ] getParameterValues ( final String paramName ) { if ( requestParameters == null ) { return null ; } return requestParameters . get ( paramName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns uploaded file . [CODESPLIT] public FileUpload getFile ( final String paramName ) { if ( requestFiles == null ) { return null ; } FileUpload [ ] values = requestFiles . get ( paramName ) ; if ( ( values != null ) && ( values . length > 0 ) ) { return values [ 0 ] ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all uploaded files the given request parameter has . [CODESPLIT] public FileUpload [ ] getFiles ( final String paramName ) { if ( requestFiles == null ) { return null ; } return requestFiles . get ( paramName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Place this filter into service . [CODESPLIT] @ Override public void init ( final FilterConfig filterConfig ) { this . filterConfig = filterConfig ; this . encoding = filterConfig . getInitParameter ( \"encoding\" ) ; if ( this . encoding == null ) { this . encoding = JoddCore . encoding ; } this . ignore = Converter . get ( ) . toBooleanValue ( filterConfig . getInitParameter ( \"ignore\" ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses template and returns generated sql builder . [CODESPLIT] public void parse ( final DbSqlBuilder sqlBuilder , final String template ) { int length = template . length ( ) ; int last = 0 ; while ( true ) { int mark = template . indexOf ( ' ' , last ) ; if ( mark == - 1 ) { if ( last < length ) { sqlBuilder . appendRaw ( template . substring ( last ) ) ; } break ; } int escapesCount = countEscapes ( template , mark ) ; // check if escaped if ( escapesCount > 0 ) { boolean isEscaped = escapesCount % 2 != 0 ; int escapesToAdd = escapesCount >> 1 ; sqlBuilder . appendRaw ( template . substring ( last , mark - escapesCount + escapesToAdd ) + ' ' ) ; if ( isEscaped ) { last = mark + 1 ; continue ; } } else { sqlBuilder . appendRaw ( template . substring ( last , mark ) ) ; } int end ; if ( template . startsWith ( MACRO_TABLE , mark ) ) { mark += MACRO_TABLE . length ( ) ; end = findMacroEnd ( template , mark ) ; onTable ( sqlBuilder , template . substring ( mark , end ) ) ; } else if ( template . startsWith ( MACRO_COLUMN , mark ) ) { mark += MACRO_COLUMN . length ( ) ; end = findMacroEnd ( template , mark ) ; onColumn ( sqlBuilder , template . substring ( mark , end ) ) ; } else if ( template . startsWith ( MACRO_MATCH , mark ) ) { mark += MACRO_MATCH . length ( ) ; end = findMacroEnd ( template , mark ) ; onMatch ( sqlBuilder , template . substring ( mark , end ) ) ; } else if ( template . startsWith ( MACRO_VALUE , mark ) ) { mark += MACRO_VALUE . length ( ) ; end = findMacroEnd ( template , mark ) ; onValue ( sqlBuilder , template . substring ( mark , end ) ) ; } else { mark ++ ; // reference found end = mark ; // find macro end while ( end < length ) { if ( ! isReferenceChar ( template , end ) ) { break ; } end ++ ; } onReference ( sqlBuilder , template . substring ( mark , end ) ) ; end -- ; } end ++ ; last = end ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds macros end . [CODESPLIT] protected int findMacroEnd ( final String template , final int fromIndex ) { int endIndex = template . indexOf ( ' ' , fromIndex ) ; if ( endIndex == - 1 ) { throw new DbSqlBuilderException ( \"Template syntax error, some macros are not closed. Error at: '...\" + template . substring ( fromIndex ) ) ; } return endIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count escapes to the left . [CODESPLIT] protected int countEscapes ( final String template , int macroIndex ) { macroIndex -- ; int escapeCount = 0 ; while ( macroIndex >= 0 ) { if ( template . charAt ( macroIndex ) != ESCAPE_CHARACTER ) { break ; } escapeCount ++ ; macroIndex -- ; } return escapeCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- handlers [CODESPLIT] protected void onTable ( final DbSqlBuilder sqlBuilder , final String allTables ) { String [ ] tables = StringUtil . split ( allTables , StringPool . COMMA ) ; for ( String table : tables ) { sqlBuilder . table ( table ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a query string from given query map . [CODESPLIT] public static String buildQuery ( final HttpMultiMap < ? > queryMap , final String encoding ) { if ( queryMap . isEmpty ( ) ) { return StringPool . EMPTY ; } int queryMapSize = queryMap . size ( ) ; StringBand query = new StringBand ( queryMapSize * 4 ) ; int count = 0 ; for ( Map . Entry < String , ? > entry : queryMap ) { String key = entry . getKey ( ) ; key = URLCoder . encodeQueryParam ( key , encoding ) ; Object value = entry . getValue ( ) ; if ( value == null ) { if ( count != 0 ) { query . append ( ' ' ) ; } query . append ( key ) ; count ++ ; } else { if ( count != 0 ) { query . append ( ' ' ) ; } query . append ( key ) ; count ++ ; query . append ( ' ' ) ; String valueString = URLCoder . encodeQueryParam ( value . toString ( ) , encoding ) ; query . append ( valueString ) ; } } return query . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses query from give query string . Values are optionally decoded . [CODESPLIT] public static HttpMultiMap < String > parseQuery ( final String query , final boolean decode ) { final HttpMultiMap < String > queryMap = HttpMultiMap . newCaseInsensitiveMap ( ) ; if ( StringUtil . isBlank ( query ) ) { return queryMap ; } int lastNdx = 0 ; while ( lastNdx < query . length ( ) ) { int ndx = query . indexOf ( ' ' , lastNdx ) ; if ( ndx == - 1 ) { ndx = query . length ( ) ; } final String paramAndValue = query . substring ( lastNdx , ndx ) ; ndx = paramAndValue . indexOf ( ' ' ) ; if ( ndx == - 1 ) { queryMap . add ( paramAndValue , null ) ; } else { String name = paramAndValue . substring ( 0 , ndx ) ; if ( decode ) { name = URLDecoder . decodeQuery ( name ) ; } String value = paramAndValue . substring ( ndx + 1 ) ; if ( decode ) { value = URLDecoder . decodeQuery ( value ) ; } queryMap . add ( name , value ) ; } lastNdx += paramAndValue . length ( ) + 1 ; } return queryMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes nice header names . [CODESPLIT] public static String prepareHeaderParameterName ( final String headerName ) { // special cases if ( headerName . equals ( \"etag\" ) ) { return HttpBase . HEADER_ETAG ; } if ( headerName . equals ( \"www-authenticate\" ) ) { return \"WWW-Authenticate\" ; } char [ ] name = headerName . toCharArray ( ) ; boolean capitalize = true ; for ( int i = 0 ; i < name . length ; i ++ ) { char c = name [ i ] ; if ( c == ' ' ) { capitalize = true ; continue ; } if ( capitalize ) { name [ i ] = Character . toUpperCase ( c ) ; capitalize = false ; } else { name [ i ] = Character . toLowerCase ( c ) ; } } return new String ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts media - type from value of Content Type header . [CODESPLIT] public static String extractMediaType ( final String contentType ) { int index = contentType . indexOf ( ' ' ) ; if ( index == - 1 ) { return contentType ; } return contentType . substring ( 0 , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts header parameter . Returns <code > null< / code > if parameter not found . [CODESPLIT] public static String extractHeaderParameter ( final String header , final String parameter , final char separator ) { int index = 0 ; while ( true ) { index = header . indexOf ( separator , index ) ; if ( index == - 1 ) { return null ; } index ++ ; // skip whitespaces while ( index < header . length ( ) && header . charAt ( index ) == ' ' ) { index ++ ; } int eqNdx = header . indexOf ( ' ' , index ) ; if ( eqNdx == - 1 ) { return null ; } String paramName = header . substring ( index , eqNdx ) ; eqNdx ++ ; if ( ! paramName . equalsIgnoreCase ( parameter ) ) { index = eqNdx ; continue ; } int endIndex = header . indexOf ( ' ' , eqNdx ) ; if ( endIndex == - 1 ) { return header . substring ( eqNdx ) ; } else { return header . substring ( eqNdx , endIndex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets prepared statement object using target SQL type . Here Jodd makes conversion and not JDBC driver . See : http : // www . tutorialspoint . com / jdbc / jdbc - data - types . htm [CODESPLIT] public static void setPreparedStatementObject ( final PreparedStatement preparedStatement , final int index , final Object value , final int targetSqlType ) throws SQLException { if ( value == null ) { preparedStatement . setNull ( index , Types . NULL ) ; return ; } switch ( targetSqlType ) { case Types . VARCHAR : case Types . LONGVARCHAR : case Types . CHAR : preparedStatement . setString ( index , Converter . get ( ) . toString ( value ) ) ; break ; case Types . INTEGER : case Types . SMALLINT : case Types . TINYINT : preparedStatement . setInt ( index , Converter . get ( ) . toIntValue ( value ) ) ; break ; case Types . BIGINT : preparedStatement . setLong ( index , Converter . get ( ) . toLongValue ( value ) ) ; break ; case Types . BOOLEAN : case Types . BIT : preparedStatement . setBoolean ( index , Converter . get ( ) . toBooleanValue ( value ) ) ; break ; case Types . DATE : preparedStatement . setDate ( index , TypeConverterManager . get ( ) . convertType ( value , java . sql . Date . class ) ) ; break ; case Types . NUMERIC : case Types . DECIMAL : preparedStatement . setBigDecimal ( index , Converter . get ( ) . toBigDecimal ( value ) ) ; break ; case Types . DOUBLE : preparedStatement . setDouble ( index , Converter . get ( ) . toDoubleValue ( value ) ) ; break ; case Types . REAL : case Types . FLOAT : preparedStatement . setFloat ( index , Converter . get ( ) . toFloatValue ( value ) ) ; break ; case Types . TIME : preparedStatement . setTime ( index , TypeConverterManager . get ( ) . convertType ( value , java . sql . Time . class ) ) ; break ; case Types . TIMESTAMP : preparedStatement . setTimestamp ( index , TypeConverterManager . get ( ) . convertType ( value , Timestamp . class ) ) ; break ; case Types . BINARY : case Types . VARBINARY : preparedStatement . setBytes ( index , TypeConverterManager . get ( ) . convertType ( value , byte [ ] . class ) ) ; break ; default : if ( targetSqlType != SqlType . DB_SQLTYPE_NOT_AVAILABLE ) { preparedStatement . setObject ( index , value , targetSqlType ) ; } else { preparedStatement . setObject ( index , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean init ( final String actionPath , final String [ ] separators ) { String prefix = separators [ 0 ] ; String split = separators [ 1 ] ; String suffix = separators [ 2 ] ; macrosCount = StringUtil . count ( actionPath , prefix ) ; if ( macrosCount == 0 ) { return false ; } names = new String [ macrosCount ] ; patterns = new String [ macrosCount ] ; fixed = new String [ macrosCount + 1 ] ; int offset = 0 ; int i = 0 ; while ( true ) { int [ ] ndx = StringUtil . indexOfRegion ( actionPath , prefix , suffix , offset ) ; if ( ndx == null ) { break ; } fixed [ i ] = actionPath . substring ( offset , ndx [ 0 ] ) ; String name = actionPath . substring ( ndx [ 1 ] , ndx [ 2 ] ) ; // name:pattern String pattern = null ; int colonNdx = name . indexOf ( split ) ; if ( colonNdx != - 1 ) { pattern = name . substring ( colonNdx + 1 ) . trim ( ) ; name = name . substring ( 0 , colonNdx ) . trim ( ) ; } this . patterns [ i ] = pattern ; this . names [ i ] = name ; // iterate offset = ndx [ 3 ] ; i ++ ; } if ( offset < actionPath . length ( ) ) { fixed [ i ] = actionPath . substring ( offset ) ; } else { fixed [ i ] = StringPool . EMPTY ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int match ( final String actionPath ) { String [ ] values = process ( actionPath , true ) ; if ( values == null ) { return - 1 ; } int macroChars = 0 ; for ( String value : values ) { if ( value != null ) { macroChars += value . length ( ) ; } } return actionPath . length ( ) - macroChars ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process action path in two modes : matching mode and extracting mode . [CODESPLIT] private String [ ] process ( final String actionPath , final boolean match ) { // first check the first fixed as a prefix if ( match && ! actionPath . startsWith ( fixed [ 0 ] ) ) { return null ; } String [ ] values = new String [ macrosCount ] ; int offset = fixed [ 0 ] . length ( ) ; int i = 0 ; while ( i < macrosCount ) { int nexti = i ; // defines next fixed string to match String nextFixed ; while ( true ) { nexti ++ ; if ( nexti > macrosCount ) { nextFixed = null ; // match to the end of line break ; } nextFixed = fixed [ nexti ] ; if ( nextFixed . length ( ) != 0 ) { break ; } // next fixed is an empty string, so skip the next macro. } // find next fixed string int ndx ; if ( nextFixed != null ) { ndx = actionPath . indexOf ( nextFixed , offset ) ; } else { ndx = actionPath . length ( ) ; } if ( ndx == - 1 ) { return null ; } String macroValue = actionPath . substring ( offset , ndx ) ; values [ i ] = macroValue ; if ( match && patterns [ i ] != null ) { if ( ! matchValue ( i , macroValue ) ) { return null ; } } if ( nextFixed == null ) { offset = ndx ; break ; } // iterate int nextFixedLength = nextFixed . length ( ) ; offset = ndx + nextFixedLength ; i = nexti ; } if ( offset != actionPath . length ( ) ) { // action path is not consumed fully during this matching return null ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders node to appendable . [CODESPLIT] public String toHtml ( final Node node , final Appendable appendable ) { NodeVisitor renderer = createRenderer ( appendable ) ; node . visit ( renderer ) ; return appendable . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders node children to appendable . [CODESPLIT] public String toInnerHtml ( final Node node , final Appendable appendable ) { NodeVisitor renderer = createRenderer ( appendable ) ; node . visitChildren ( renderer ) ; return appendable . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > null< / code > for excluded HTTP headers . [CODESPLIT] @ Override public String getHeader ( final String header ) { if ( isExcluded ( header ) ) { return null ; } return super . getHeader ( header ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void put ( final K key , final V object , final long timeout ) { Objects . requireNonNull ( object ) ; final long stamp = lock . writeLock ( ) ; try { CacheObject < K , V > co = new CacheObject <> ( key , object , timeout ) ; if ( timeout != 0 ) { existCustomTimeout = true ; } if ( isReallyFull ( key ) ) { pruneCache ( ) ; } cacheMap . put ( key , co ) ; } finally { lock . unlockWrite ( stamp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public V get ( final K key ) { long stamp = lock . readLock ( ) ; try { CacheObject < K , V > co = cacheMap . get ( key ) ; if ( co == null ) { missCount ++ ; return null ; } if ( co . isExpired ( ) ) { final long newStamp = lock . tryConvertToWriteLock ( stamp ) ; if ( newStamp != 0L ) { stamp = newStamp ; // lock is upgraded to write lock } else { // manually upgrade lock to write lock lock . unlockRead ( stamp ) ; stamp = lock . writeLock ( ) ; } CacheObject < K , V > removedCo = cacheMap . remove ( key ) ; if ( removedCo != null ) { onRemove ( removedCo . key , removedCo . cachedObject ) ; } missCount ++ ; return null ; } hitCount ++ ; return co . getObject ( ) ; } finally { lock . unlock ( stamp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public V remove ( final K key ) { V removedValue = null ; final long stamp = lock . writeLock ( ) ; try { CacheObject < K , V > co = cacheMap . remove ( key ) ; if ( co != null ) { onRemove ( co . key , co . cachedObject ) ; removedValue = co . cachedObject ; } } finally { lock . unlockWrite ( stamp ) ; } return removedValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void clear ( ) { final long stamp = lock . writeLock ( ) ; try { cacheMap . clear ( ) ; } finally { lock . unlockWrite ( stamp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Map < K , V > snapshot ( ) { final long stamp = lock . writeLock ( ) ; try { Map < K , V > map = new HashMap <> ( cacheMap . size ( ) ) ; cacheMap . forEach ( ( key , cacheValue ) -> map . put ( key , cacheValue . getObject ( ) ) ) ; return map ; } finally { lock . unlockWrite ( stamp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures Madvoc by reading context init parameters . [CODESPLIT] public void configureWith ( final ServletContext servletContext ) { webAppClassName = servletContext . getInitParameter ( PARAM_MADVOC_WEBAPP ) ; paramsFiles = Converter . get ( ) . toStringArray ( servletContext . getInitParameter ( PARAM_MADVOC_PARAMS ) ) ; madvocConfiguratorClassName = servletContext . getInitParameter ( PARAM_MADVOC_CONFIGURATOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and starts new <code > Madvoc< / code > web application . <code > Madvoc< / code > instance is stored in servlet context . Important : <code > servletContext< / code > may be <code > null< / code > when web application is run out from container . [CODESPLIT] @ SuppressWarnings ( \"InstanceofCatchParameter\" ) public WebApp startWebApplication ( final ServletContext servletContext ) { try { WebApp webApp = _start ( servletContext ) ; log . info ( \"Madvoc is up and running.\" ) ; return webApp ; } catch ( Exception ex ) { if ( log != null ) { log . error ( \"Madvoc startup failure.\" , ex ) ; } else { ex . printStackTrace ( ) ; } if ( ex instanceof MadvocException ) { throw ( MadvocException ) ex ; } throw new MadvocException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops <em > Madvoc< / em > web application . [CODESPLIT] public void stopWebApplication ( ) { log . info ( \"Madvoc shutting down...\" ) ; if ( servletContext != null ) { servletContext . removeAttribute ( MADVOC_ATTR ) ; } webapp . shutdown ( ) ; webapp = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] protected WebApp createWebApplication ( ) { if ( ( webAppClassName == null ) && ( webAppClass == null ) ) { return new WebApp ( ) ; } final WebApp webApp ; try { if ( webAppClassName != null ) { webAppClass = ClassLoaderUtil . loadClass ( webAppClassName ) ; } webApp = ( WebApp ) ClassUtil . newInstance ( webAppClass ) ; } catch ( Exception ex ) { throw new MadvocException ( \"Unable to load Madvoc web application class: \" + webAppClassName , ex ) ; } return webApp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads Madvoc parameters . New { [CODESPLIT] protected Props loadMadvocParams ( final String [ ] patterns ) { if ( log . isInfoEnabled ( ) ) { log . info ( \"Loading Madvoc parameters from: \" + Converter . get ( ) . toString ( patterns ) ) ; } try { return new Props ( ) . loadFromClasspath ( patterns ) ; } catch ( Exception ex ) { throw new MadvocException ( \"Unable to load Madvoc parameters from: \" + Converter . get ( ) . toString ( patterns ) + \".properties': \" + ex . toString ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads Madvoc component that will be used for configuring the user actions . If class name is <code > null< / code > default { [CODESPLIT] protected void resolveMadvocConfigClass ( ) { if ( ( madvocConfiguratorClassName == null ) && ( madvocConfiguratorClass == null ) ) { return ; } try { if ( madvocConfiguratorClassName != null ) { madvocConfiguratorClass = ClassLoaderUtil . loadClass ( madvocConfiguratorClassName ) ; } log . info ( \"Configuring Madvoc using: \" + madvocConfiguratorClass . getName ( ) ) ; } catch ( Exception ex ) { throw new MadvocException ( \"Unable to load Madvoc configurator class: \" + madvocConfiguratorClassName , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a class from byte array into the specified class loader . Warning : this is a <b > hack< / b > ! [CODESPLIT] public static Class of ( final String className , final byte [ ] classData , ClassLoader classLoader ) { if ( classLoader == null ) { classLoader = ClassLoaderUtil . getDefaultClassLoader ( ) ; } try { final Method defineClassMethod = ClassLoader . class . getDeclaredMethod ( \"defineClass\" , String . class , byte [ ] . class , int . class , int . class ) ; defineClassMethod . setAccessible ( true ) ; return ( Class ) defineClassMethod . invoke ( classLoader , className , classData , 0 , classData . length ) ; } catch ( Throwable th ) { throw new RuntimeException ( \"Define class failed: \" + className , th ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets JSON parser so it can be reused . [CODESPLIT] protected void reset ( ) { this . ndx = 0 ; this . textLen = 0 ; this . path = new Path ( ) ; this . notFirstObject = false ; if ( useAltPaths ) { path . altPath = new Path ( ) ; } if ( classMetadataName != null ) { mapToBean = createMapToBean ( classMetadataName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines how JSON parser works . In non - lazy mode the whole JSON is parsed as it is . In the lazy mode not everything is parsed but some things are left lazy . This way we gain performance especially on partial usage of the whole JSON . However be aware that parser holds the input memory until the returned objects are disposed . [CODESPLIT] public JsonParser lazy ( final boolean lazy ) { this . lazy = lazy ; this . mapSupplier = lazy ? LAZYMAP_SUPPLIER : HASHMAP_SUPPLIER ; this . listSupplier = lazy ? LAZYLIST_SUPPLIER : ARRAYLIST_SUPPLIER ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a class to given path . For arrays append <code > values< / code > to the path to specify component type ( if not specified by generics ) . [CODESPLIT] public JsonParser map ( final String path , final Class target ) { if ( path == null ) { rootType = target ; return this ; } if ( mappings == null ) { mappings = new HashMap <> ( ) ; } mappings . put ( Path . parse ( path ) , target ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces type with mapped type for current path . [CODESPLIT] protected Class replaceWithMappedTypeForPath ( final Class target ) { if ( mappings == null ) { return target ; } Class newType ; // first try alt paths Path altPath = path . getAltPath ( ) ; if ( altPath != null ) { if ( ! altPath . equals ( path ) ) { newType = mappings . get ( altPath ) ; if ( newType != null ) { return newType ; } } } // now check regular paths newType = mappings . get ( path ) ; if ( newType != null ) { return newType ; } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines { [CODESPLIT] public JsonParser withValueConverter ( final String path , final ValueConverter valueConverter ) { if ( convs == null ) { convs = new HashMap <> ( ) ; } convs . put ( Path . parse ( path ) , valueConverter ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { [CODESPLIT] public JsonParser allowClass ( final String classPattern ) { if ( super . classnameWhitelist == null ) { super . classnameWhitelist = new ArrayList <> ( ) ; } classnameWhitelist . add ( classPattern ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses input JSON as given type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T parse ( final String input , final Class < T > targetType ) { rootType = targetType ; return _parse ( UnsafeUtil . getChars ( input ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses input JSON to a list with specified component type . [CODESPLIT] public < T > List < T > parseAsList ( final String string , final Class < T > componentType ) { return new JsonParser ( ) . map ( JsonParser . VALUES , componentType ) . parse ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses input JSON to a list with specified key and value types . [CODESPLIT] public < K , V > Map < K , V > parseAsMap ( final String string , final Class < K > keyType , final Class < V > valueType ) { return new JsonParser ( ) . map ( JsonParser . KEYS , keyType ) . map ( JsonParser . VALUES , valueType ) . parse ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses input JSON as given type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T parse ( final char [ ] input , final Class < T > targetType ) { rootType = targetType ; return _parse ( input ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a JSON value . [CODESPLIT] protected Object parseValue ( final Class targetType , final Class keyType , final Class componentType ) { final ValueConverter valueConverter ; final char c = input [ ndx ] ; switch ( c ) { case ' ' : if ( ! looseMode ) { break ; } case ' ' : ndx ++ ; Object string = parseStringContent ( c ) ; valueConverter = lookupValueConverter ( ) ; if ( valueConverter != null ) { return valueConverter . convert ( string ) ; } if ( targetType != null && targetType != String . class ) { string = convertType ( string , targetType ) ; } return string ; case ' ' : ndx ++ ; if ( lazy ) { if ( notFirstObject ) { final Object value = new ObjectParser ( this , targetType , keyType , componentType ) ; skipObject ( ) ; return value ; } else { notFirstObject = true ; } } return parseObjectContent ( targetType , keyType , componentType ) ; case ' ' : ndx ++ ; return parseArrayContent ( targetType , componentType ) ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : Object number = parseNumber ( ) ; valueConverter = lookupValueConverter ( ) ; if ( valueConverter != null ) { return valueConverter . convert ( number ) ; } if ( targetType != null ) { number = convertType ( number , targetType ) ; } return number ; case ' ' : ndx ++ ; if ( match ( N_ULL ) ) { valueConverter = lookupValueConverter ( ) ; if ( valueConverter != null ) { return valueConverter . convert ( null ) ; } return null ; } break ; case ' ' : ndx ++ ; if ( match ( T_RUE ) ) { Object value = Boolean . TRUE ; valueConverter = lookupValueConverter ( ) ; if ( valueConverter != null ) { return valueConverter . convert ( value ) ; } if ( targetType != null ) { value = convertType ( value , targetType ) ; } return value ; } break ; case ' ' : ndx ++ ; if ( match ( F_ALSE ) ) { Object value = Boolean . FALSE ; valueConverter = lookupValueConverter ( ) ; if ( valueConverter != null ) { return valueConverter . convert ( value ) ; } if ( targetType != null ) { value = convertType ( value , targetType ) ; } return value ; } break ; } if ( looseMode ) { // try to parse unquoted string Object string = parseUnquotedStringContent ( ) ; valueConverter = lookupValueConverter ( ) ; if ( valueConverter != null ) { return valueConverter . convert ( string ) ; } if ( targetType != null && targetType != String . class ) { string = convertType ( string , targetType ) ; } return string ; } syntaxError ( \"Invalid char: \" + input [ ndx ] ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves lazy value during the parsing runtime . [CODESPLIT] private Object resolveLazyValue ( Object value ) { if ( value instanceof Supplier ) { value = ( ( Supplier ) value ) . get ( ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips over complete object . It is not parsed just skipped . It will be parsed later but only if required . [CODESPLIT] private void skipObject ( ) { int bracketCount = 1 ; boolean insideString = false ; while ( ndx < total ) { final char c = input [ ndx ] ; if ( insideString ) { if ( c == ' ' && notPrecededByEvenNumberOfBackslashes ( ) ) { insideString = false ; } } else if ( c == ' ' ) { insideString = true ; } else if ( c == ' ' ) { bracketCount ++ ; } else if ( c == ' ' ) { bracketCount -- ; if ( bracketCount == 0 ) { ndx ++ ; return ; } } ndx ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a string . [CODESPLIT] protected String parseString ( ) { char quote = ' ' ; if ( looseMode ) { quote = consumeOneOf ( ' ' , ' ' ) ; if ( quote == 0 ) { return parseUnquotedStringContent ( ) ; } } else { consume ( quote ) ; } return parseStringContent ( quote ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses string content once when starting quote has been consumed . [CODESPLIT] protected String parseStringContent ( final char quote ) { final int startNdx = ndx ; // roll-out until the end of the string or the escape char while ( true ) { final char c = input [ ndx ] ; if ( c == quote ) { // no escapes found, just use existing string ndx ++ ; return new String ( input , startNdx , ndx - 1 - startNdx ) ; } if ( c == ' ' ) { break ; } ndx ++ ; } // escapes found, proceed differently textLen = ndx - startNdx ; growEmpty ( ) ; //\t\tfor (int i = startNdx, j = 0; j < textLen; i++, j++) { //\t\t\ttext[j] = input[i]; //\t\t} System . arraycopy ( input , startNdx , text , 0 , textLen ) ; // escape char, process everything until the end while ( true ) { char c = input [ ndx ] ; if ( c == quote ) { // done ndx ++ ; final String str = new String ( text , 0 , textLen ) ; textLen = 0 ; return str ; } if ( c == ' ' ) { // escape char found ndx ++ ; c = input [ ndx ] ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : ndx ++ ; c = parseUnicode ( ) ; break ; default : if ( looseMode ) { if ( c != ' ' ) { c = ' ' ; ndx -- ; } } else { syntaxError ( \"Invalid escape char: \" + c ) ; } } } text [ textLen ] = c ; textLen ++ ; growAndCopy ( ) ; ndx ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grows text array when { [CODESPLIT] protected void growAndCopy ( ) { if ( textLen == text . length ) { int newSize = text . length << 1 ; char [ ] newText = new char [ newSize ] ; if ( textLen > 0 ) { System . arraycopy ( text , 0 , newText , 0 , textLen ) ; } text = newText ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses 4 characters and returns unicode character . [CODESPLIT] protected char parseUnicode ( ) { int i0 = CharUtil . hex2int ( input [ ndx ++ ] ) ; int i1 = CharUtil . hex2int ( input [ ndx ++ ] ) ; int i2 = CharUtil . hex2int ( input [ ndx ++ ] ) ; int i3 = CharUtil . hex2int ( input [ ndx ] ) ; return ( char ) ( ( i0 << 12 ) + ( i1 << 8 ) + ( i2 << 4 ) + i3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses un - quoted string content . [CODESPLIT] protected String parseUnquotedStringContent ( ) { final int startNdx = ndx ; while ( true ) { final char c = input [ ndx ] ; if ( c <= ' ' || CharUtil . equalsOne ( c , UNQUOTED_DELIMETERS ) ) { final int currentNdx = ndx ; // done skipWhiteSpaces ( ) ; return new String ( input , startNdx , currentNdx - startNdx ) ; } ndx ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses JSON numbers . [CODESPLIT] protected Number parseNumber ( ) { final int startIndex = ndx ; char c = input [ ndx ] ; boolean isDouble = false ; boolean isExp = false ; if ( c == ' ' ) { ndx ++ ; } while ( true ) { if ( isEOF ( ) ) { break ; } c = input [ ndx ] ; if ( c >= ' ' && c <= ' ' ) { ndx ++ ; continue ; } if ( c <= 32 ) { // white space break ; } if ( c == ' ' || c == ' ' || c == ' ' ) { // delimiter break ; } if ( c == ' ' ) { isDouble = true ; } else if ( c == ' ' || c == ' ' ) { isExp = true ; } ndx ++ ; } final String value = new String ( input , startIndex , ndx - startIndex ) ; if ( isDouble ) { return Double . valueOf ( value ) ; } long longNumber ; if ( isExp ) { longNumber = Double . valueOf ( value ) . longValue ( ) ; } else { if ( value . length ( ) >= 19 ) { // if string is 19 chars and longer, it can be over the limit BigInteger bigInteger = new BigInteger ( value ) ; if ( isGreaterThanLong ( bigInteger ) ) { return bigInteger ; } longNumber = bigInteger . longValue ( ) ; } else { longNumber = Long . parseLong ( value ) ; } } if ( ( longNumber >= Integer . MIN_VALUE ) && ( longNumber <= Integer . MAX_VALUE ) ) { return ( int ) longNumber ; } return longNumber ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses arrays once when open bracket has been consumed . [CODESPLIT] protected Object parseArrayContent ( Class targetType , Class componentType ) { // detect special case if ( targetType == Object . class ) { targetType = List . class ; } // continue targetType = replaceWithMappedTypeForPath ( targetType ) ; if ( componentType == null && targetType != null && targetType . isArray ( ) ) { componentType = targetType . getComponentType ( ) ; } path . push ( VALUES ) ; componentType = replaceWithMappedTypeForPath ( componentType ) ; Collection < Object > target = newArrayInstance ( targetType ) ; boolean koma = false ; mainloop : while ( true ) { skipWhiteSpaces ( ) ; char c = input [ ndx ] ; if ( c == ' ' ) { if ( koma ) { syntaxError ( \"Trailing comma\" ) ; } ndx ++ ; path . pop ( ) ; return target ; } Object value = parseValue ( componentType , null , null ) ; target . add ( value ) ; skipWhiteSpaces ( ) ; c = input [ ndx ] ; switch ( c ) { case ' ' : ndx ++ ; break mainloop ; case ' ' : ndx ++ ; koma = true ; break ; default : syntaxError ( \"Invalid char: expected ] or ,\" ) ; } } path . pop ( ) ; if ( targetType != null ) { return convertType ( target , targetType ) ; } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses object once when open bracket has been consumed . [CODESPLIT] protected Object parseObjectContent ( Class targetType , Class valueKeyType , Class valueType ) { // detect special case if ( targetType == Object . class ) { targetType = Map . class ; } // continue targetType = replaceWithMappedTypeForPath ( targetType ) ; Object target ; boolean isTargetTypeMap = true ; boolean isTargetRealTypeMap = true ; ClassDescriptor targetTypeClassDescriptor = null ; TypeData typeData = null ; if ( targetType != null ) { targetTypeClassDescriptor = ClassIntrospector . get ( ) . lookup ( targetType ) ; // find if the target is really a map // because when classMetadataName != null we are forcing // map usage locally in this method isTargetRealTypeMap = targetTypeClassDescriptor . isMap ( ) ; typeData = jsonAnnotationManager . lookupTypeData ( targetType ) ; } if ( isTargetRealTypeMap ) { // resolve keys only for real maps path . push ( KEYS ) ; valueKeyType = replaceWithMappedTypeForPath ( valueKeyType ) ; path . pop ( ) ; } if ( classMetadataName == null ) { // create instance of target type, no 'class' information target = newObjectInstance ( targetType ) ; isTargetTypeMap = isTargetRealTypeMap ; } else { // all beans will be created first as a map target = mapSupplier . get ( ) ; } boolean koma = false ; mainloop : while ( true ) { skipWhiteSpaces ( ) ; char c = input [ ndx ] ; if ( c == ' ' ) { if ( koma ) { syntaxError ( \"Trailing comma\" ) ; } ndx ++ ; break ; } koma = false ; String key = parseString ( ) ; String keyOriginal = key ; skipWhiteSpaces ( ) ; consume ( ' ' ) ; skipWhiteSpaces ( ) ; // read the type of the simple property PropertyDescriptor pd = null ; Class propertyType = null ; Class keyType = null ; Class componentType = null ; // resolve simple property if ( ! isTargetRealTypeMap ) { // replace key with real property value key = jsonAnnotationManager . resolveRealName ( targetType , key ) ; } if ( ! isTargetTypeMap ) { pd = targetTypeClassDescriptor . getPropertyDescriptor ( key , true ) ; if ( pd != null ) { propertyType = pd . getType ( ) ; keyType = pd . resolveKeyType ( true ) ; componentType = pd . resolveComponentType ( true ) ; } } Object value ; if ( ! isTargetTypeMap ) { // *** inject into bean path . push ( key ) ; value = parseValue ( propertyType , keyType , componentType ) ; path . pop ( ) ; if ( typeData . rules . match ( keyOriginal , ! typeData . strict ) ) { if ( pd != null ) { if ( lazy ) { // need to resolve lazy value before injecting objects into it value = resolveLazyValue ( value ) ; } // only inject values if target property exist injectValueIntoObject ( target , pd , value ) ; } } } else { Object keyValue = key ; if ( valueKeyType != null ) { keyValue = convertType ( key , valueKeyType ) ; } // *** add to map if ( isTargetRealTypeMap ) { path . push ( VALUES , key ) ; valueType = replaceWithMappedTypeForPath ( valueType ) ; } else { path . push ( key ) ; } value = parseValue ( valueType , null , null ) ; path . pop ( ) ; ( ( Map ) target ) . put ( keyValue , value ) ; } skipWhiteSpaces ( ) ; c = input [ ndx ] ; switch ( c ) { case ' ' : ndx ++ ; break mainloop ; case ' ' : ndx ++ ; koma = true ; break ; default : syntaxError ( \"Invalid char: expected } or ,\" ) ; } } // done // convert Map to target type if ( classMetadataName != null ) { target = mapToBean . map2bean ( ( Map ) target , targetType ) ; } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes one of the allowed char at current position . If char is different return <code > 0< / code > . If matched returns matched char . [CODESPLIT] protected char consumeOneOf ( final char c1 , final char c2 ) { char c = input [ ndx ] ; if ( ( c != c1 ) && ( c != c2 ) ) { return 0 ; } ndx ++ ; return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches char buffer with content on given location . [CODESPLIT] protected final boolean match ( final char [ ] target ) { for ( char c : target ) { if ( input [ ndx ] != c ) { return false ; } ndx ++ ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws { [CODESPLIT] protected void syntaxError ( final String message ) { String left = \"...\" ; String right = \"...\" ; int offset = 10 ; int from = ndx - offset ; if ( from < 0 ) { from = 0 ; left = StringPool . EMPTY ; } int to = ndx + offset ; if ( to > input . length ) { to = input . length ; right = StringPool . EMPTY ; } final CharSequence str = CharArraySequence . of ( input , from , to - from ) ; throw new JsonException ( \"Syntax error! \" + message + \"\\n\" + \"offset: \" + ndx + \" near: \\\"\" + left + str + right + \"\\\"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void visit ( final int version , int access , final String name , final String signature , final String superName , String [ ] interfaces ) { wd . init ( name , superName , this . suffix , this . reqProxyClassName ) ; // no superclass wd . superName = AsmUtil . SIGNATURE_JAVA_LANG_OBJECT ; // change access of destination access &= ~ AsmUtil . ACC_ABSTRACT ; access &= ~ AsmUtil . ACC_INTERFACE ; // write destination class if ( targetClassOrInterface . isInterface ( ) ) { // target is interface wd . wrapInterface = true ; interfaces = new String [ ] { targetClassOrInterface . getName ( ) . replace ( ' ' , ' ' ) } ; } else { // target is class wd . wrapInterface = false ; if ( targetInterface != null ) { // interface provided interfaces = new String [ ] { targetInterface . getName ( ) . replace ( ' ' , ' ' ) } ; } else { // no interface provided, use all //interfaces = null; } } final int v = ProxettaAsmUtil . resolveJavaVersion ( version ) ; wd . dest . visit ( v , access , wd . thisReference , signature , wd . superName , interfaces ) ; wd . proxyAspects = new ProxyAspectData [ aspects . length ] ; for ( int i = 0 ; i < aspects . length ; i ++ ) { wd . proxyAspects [ i ] = new ProxyAspectData ( wd , aspects [ i ] , i ) ; } // create new field wrapper field and store it's reference into work-data wd . wrapperRef = targetFieldName ; wd . wrapperType = ' ' + name + ' ' ; if ( createTargetInDefaultCtor ) { // create private, final field final FieldVisitor fv = wd . dest . visitField ( AsmUtil . ACC_PRIVATE | AsmUtil . ACC_FINAL , wd . wrapperRef , wd . wrapperType , null , null ) ; fv . visitEnd ( ) ; createEmptyCtorThatCreatesTarget ( ) ; } else { // create public, non-final field final FieldVisitor fv = wd . dest . visitField ( AsmUtil . ACC_PUBLIC , wd . wrapperRef , wd . wrapperType , null , null ) ; fv . visitEnd ( ) ; createEmptyCtor ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Created empty default constructor . [CODESPLIT] protected void createEmptyCtor ( ) { final MethodVisitor mv = wd . dest . visitMethod ( AsmUtil . ACC_PUBLIC , INIT , \"()V\" , null , null ) ; mv . visitCode ( ) ; mv . visitVarInsn ( Opcodes . ALOAD , 0 ) ; mv . visitMethodInsn ( Opcodes . INVOKESPECIAL , AsmUtil . SIGNATURE_JAVA_LANG_OBJECT , INIT , \"()V\" , false ) ; mv . visitInsn ( Opcodes . RETURN ) ; mv . visitMaxs ( 1 , 1 ) ; mv . visitEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { MethodSignatureVisitor msign = targetClassInfo . lookupMethodSignatureVisitor ( access , name , desc , wd . superReference ) ; if ( msign == null ) { return null ; } // ignore all destination constructors if ( name . equals ( INIT ) ) { return null ; } // ignore all destination static block if ( name . equals ( CLINIT ) ) { return null ; } // skip all static methods if ( Modifier . isStatic ( access ) ) { return null ; } return applyProxy ( msign ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates simple method wrapper without proxy . [CODESPLIT] protected void createSimpleMethodWrapper ( final MethodSignatureVisitor msign ) { int access = msign . getAccessFlags ( ) ; access &= ~ ACC_ABSTRACT ; access &= ~ ACC_NATIVE ; MethodVisitor mv = wd . dest . visitMethod ( access , msign . getMethodName ( ) , msign . getDescription ( ) , msign . getAsmMethodSignature ( ) , msign . getExceptions ( ) ) ; mv . visitCode ( ) ; mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitFieldInsn ( GETFIELD , wd . thisReference , wd . wrapperRef , wd . wrapperType ) ; loadVirtualMethodArguments ( mv , msign ) ; if ( wd . wrapInterface ) { mv . visitMethodInsn ( INVOKEINTERFACE , wd . wrapperType . substring ( 1 , wd . wrapperType . length ( ) - 1 ) , msign . getMethodName ( ) , msign . getDescription ( ) , true ) ; } else { mv . visitMethodInsn ( INVOKEVIRTUAL , wd . wrapperType . substring ( 1 , wd . wrapperType . length ( ) - 1 ) , msign . getMethodName ( ) , msign . getDescription ( ) , false ) ; } ProxettaAsmUtil . prepareReturnValue ( mv , msign , 0 ) ; visitReturn ( mv , msign , true ) ; mv . visitMaxs ( 0 , 0 ) ; mv . visitEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- method - info signature [CODESPLIT] @ Override public String getSignature ( ) { if ( signature == null ) { String decl = getDeclaration ( ) ; int ndx = decl . indexOf ( ' ' ) ; ndx ++ ; String retType = decl . substring ( ndx ) ; StringBuilder methodDeclaration = new StringBuilder ( 50 ) ; methodDeclaration . append ( retType ) . append ( ' ' ) . append ( methodName ) . append ( decl , 0 , ndx ) ; String exceptionsAsString = getExceptionsAsString ( ) ; if ( exceptionsAsString != null ) { methodDeclaration . append ( \" throws \" ) . append ( exceptionsAsString ) ; } signature = methodDeclaration . toString ( ) ; } return signature ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves raw type name using the generics information from the class or method information . [CODESPLIT] private String resolveRawTypeName ( String typeName ) { if ( typeName == null ) { return null ; } boolean isArray = typeName . startsWith ( StringPool . LEFT_SQ_BRACKET ) ; if ( isArray ) { typeName = typeName . substring ( 1 ) ; } String rawTypeName ; if ( generics . containsKey ( typeName ) ) { rawTypeName = generics . get ( typeName ) ; } else { rawTypeName = declaredTypeGeneric . getOrDefault ( typeName , typeName ) ; } if ( isArray ) { rawTypeName = ' ' + rawTypeName ; } return rawTypeName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves reference from given values . Returns bean reference of given value or defaults if given name is blank . [CODESPLIT] public BeanReferences resolveReferenceFromValue ( final PropertyDescriptor propertyDescriptor , final String refName ) { BeanReferences references ; if ( refName == null || refName . isEmpty ( ) ) { references = buildDefaultReference ( propertyDescriptor ) ; } else { references = BeanReferences . of ( refName ) ; } references = references . removeDuplicateNames ( ) ; return references ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes given parameters references and returns reference set for given method or constructor . [CODESPLIT] public BeanReferences [ ] resolveReferenceFromValues ( final Executable methodOrCtor , final String ... parameterReferences ) { BeanReferences [ ] references = convertRefToReferences ( parameterReferences ) ; if ( references == null || references . length == 0 ) { references = buildDefaultReferences ( methodOrCtor ) ; } if ( methodOrCtor . getParameterTypes ( ) . length != references . length ) { throw new PetiteException ( \"Different number of method parameters and references for: \" + methodOrCtor . getDeclaringClass ( ) . getName ( ) + ' ' + methodOrCtor . getName ( ) ) ; } removeAllDuplicateNames ( references ) ; return references ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts references for given property . Returns { [CODESPLIT] public BeanReferences readReferenceFromAnnotation ( final PropertyDescriptor propertyDescriptor ) { final MethodDescriptor writeMethodDescriptor = propertyDescriptor . getWriteMethodDescriptor ( ) ; final FieldDescriptor fieldDescriptor = propertyDescriptor . getFieldDescriptor ( ) ; PetiteInject ref = null ; if ( writeMethodDescriptor != null ) { ref = writeMethodDescriptor . getMethod ( ) . getAnnotation ( PetiteInject . class ) ; } if ( ref == null && fieldDescriptor != null ) { ref = fieldDescriptor . getField ( ) . getAnnotation ( PetiteInject . class ) ; } if ( ref == null ) { return null ; } BeanReferences reference = null ; String name = ref . value ( ) . trim ( ) ; if ( name . length ( ) != 0 ) { reference = BeanReferences . of ( name ) ; } reference = updateReferencesWithDefaultsIfNeeded ( propertyDescriptor , reference ) ; reference = reference . removeDuplicateNames ( ) ; return reference ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts references from method or constructor annotation . [CODESPLIT] public BeanReferences [ ] readAllReferencesFromAnnotation ( final Executable methodOrCtor ) { PetiteInject petiteInject = methodOrCtor . getAnnotation ( PetiteInject . class ) ; final Parameter [ ] parameters = methodOrCtor . getParameters ( ) ; BeanReferences [ ] references ; final boolean hasAnnotationOnMethodOrCtor ; if ( petiteInject != null ) { references = convertAnnValueToReferences ( petiteInject . value ( ) ) ; hasAnnotationOnMethodOrCtor = true ; } else { references = new BeanReferences [ parameters . length ] ; hasAnnotationOnMethodOrCtor = false ; } int parametersWithAnnotationCount = 0 ; for ( int i = 0 ; i < parameters . length ; i ++ ) { Parameter parameter = parameters [ i ] ; petiteInject = parameter . getAnnotation ( PetiteInject . class ) ; if ( petiteInject == null ) { // no annotation on argument continue ; } // there is annotation on argument, override values String annotationValue = readAnnotationValue ( petiteInject ) ; if ( annotationValue != null ) { references [ i ] = BeanReferences . of ( annotationValue ) ; } parametersWithAnnotationCount ++ ; } if ( ! hasAnnotationOnMethodOrCtor ) { if ( parametersWithAnnotationCount == 0 ) { return null ; } if ( parametersWithAnnotationCount != parameters . length ) { throw new PetiteException ( \"All arguments must be annotated with PetiteInject\" ) ; } } references = updateReferencesWithDefaultsIfNeeded ( methodOrCtor , references ) ; removeAllDuplicateNames ( references ) ; return references ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads annotation value and returns { [CODESPLIT] private String readAnnotationValue ( final PetiteInject annotation ) { String value = annotation . value ( ) . trim ( ) ; if ( value . isEmpty ( ) ) { return null ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds default method references . [CODESPLIT] private BeanReferences [ ] buildDefaultReferences ( final Executable methodOrCtor ) { final boolean useParamo = petiteConfig . getUseParamo ( ) ; final PetiteReferenceType [ ] lookupReferences = petiteConfig . getLookupReferences ( ) ; MethodParameter [ ] methodParameters = null ; if ( useParamo ) { methodParameters = Paramo . resolveParameters ( methodOrCtor ) ; } final Class [ ] paramTypes = methodOrCtor . getParameterTypes ( ) ; final BeanReferences [ ] references = new BeanReferences [ paramTypes . length ] ; for ( int j = 0 ; j < paramTypes . length ; j ++ ) { String [ ] ref = new String [ lookupReferences . length ] ; references [ j ] = BeanReferences . of ( ref ) ; for ( int i = 0 ; i < ref . length ; i ++ ) { switch ( lookupReferences [ i ] ) { case NAME : ref [ i ] = methodParameters != null ? methodParameters [ j ] . getName ( ) : null ; break ; case TYPE_SHORT_NAME : ref [ i ] = StringUtil . uncapitalize ( paramTypes [ j ] . getSimpleName ( ) ) ; break ; case TYPE_FULL_NAME : ref [ i ] = paramTypes [ j ] . getName ( ) ; break ; } } } return references ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds default field references . [CODESPLIT] public BeanReferences buildDefaultReference ( final PropertyDescriptor propertyDescriptor ) { final PetiteReferenceType [ ] lookupReferences = petiteConfig . getLookupReferences ( ) ; final String [ ] references = new String [ lookupReferences . length ] ; for ( int i = 0 ; i < references . length ; i ++ ) { switch ( lookupReferences [ i ] ) { case NAME : references [ i ] = propertyDescriptor . getName ( ) ; break ; case TYPE_SHORT_NAME : references [ i ] = StringUtil . uncapitalize ( propertyDescriptor . getType ( ) . getSimpleName ( ) ) ; break ; case TYPE_FULL_NAME : references [ i ] = propertyDescriptor . getType ( ) . getName ( ) ; break ; } } return BeanReferences . of ( references ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes duplicate names from bean references . [CODESPLIT] private void removeAllDuplicateNames ( final BeanReferences [ ] allBeanReferences ) { for ( int i = 0 ; i < allBeanReferences . length ; i ++ ) { BeanReferences references = allBeanReferences [ i ] ; allBeanReferences [ i ] = references . removeDuplicateNames ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts single string array to an array of bean references . [CODESPLIT] private BeanReferences [ ] convertRefToReferences ( final String [ ] references ) { if ( references == null ) { return null ; } BeanReferences [ ] ref = new BeanReferences [ references . length ] ; for ( int i = 0 ; i < references . length ; i ++ ) { ref [ i ] = BeanReferences . of ( references [ i ] ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts comma - separated string into array of Bean references . [CODESPLIT] private BeanReferences [ ] convertAnnValueToReferences ( String value ) { if ( value == null ) { return null ; } value = value . trim ( ) ; if ( value . length ( ) == 0 ) { return null ; } String [ ] refNames = Converter . get ( ) . toStringArray ( value ) ; BeanReferences [ ] references = new BeanReferences [ refNames . length ] ; for ( int i = 0 ; i < refNames . length ; i ++ ) { references [ i ] = BeanReferences . of ( refNames [ i ] . trim ( ) ) ; } return references ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs JOY in standalone mode with only backend . [CODESPLIT] public void runJoy ( final Consumer < JoddJoyRuntime > consumer ) { final JoddJoy joddJoy = new JoddJoy ( ) ; final JoddJoyRuntime joyRuntime = joddJoy . startOnlyBackend ( ) ; joddJoy . withDb ( joyDb -> setJtxManager ( joyRuntime . getJtxManager ( ) ) ) ; final JtxTransaction tx = startRwTx ( ) ; final Print print = new Print ( ) ; try { print . line ( \"START\" , 80 ) ; print . newLine ( ) ; consumer . accept ( joyRuntime ) ; print . newLine ( ) ; print . line ( \"END\" , 80 ) ; if ( tx != null ) { tx . commit ( ) ; } } catch ( Throwable throwable ) { throwable . printStackTrace ( ) ; if ( tx != null ) { tx . rollback ( ) ; } } joddJoy . stop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts new read / write transaction in PROPAGATION_REQUIRED mode . [CODESPLIT] private JtxTransaction startRwTx ( ) { if ( jtxManager == null ) { return null ; } return jtxManager . requestTransaction ( new JtxTransactionMode ( JtxPropagationBehavior . PROPAGATION_REQUIRED , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns method from an object matched by name . This may be considered as a slow operation since methods are matched one by one . Returns only accessible methods . Only first method is matched . [CODESPLIT] public static Method findMethod ( final Class c , final String methodName ) { return findDeclaredMethod ( c , methodName , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds constructor with given parameter types . First matched ctor is returned . [CODESPLIT] public static < T > Constructor < T > findConstructor ( final Class < T > clazz , final Class < ? > ... parameterTypes ) { final Constructor < ? > [ ] constructors = clazz . getConstructors ( ) ; Class < ? > [ ] pts ; for ( Constructor < ? > constructor : constructors ) { pts = constructor . getParameterTypes ( ) ; if ( isAllAssignableFrom ( pts , parameterTypes ) ) { return ( Constructor < T > ) constructor ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public static boolean isAllAssignableFrom ( final Class < ? > [ ] typesTarget , final Class < ? > [ ] typesFrom ) { if ( typesTarget . length == typesFrom . length ) { for ( int i = 0 ; i < typesTarget . length ; i ++ ) { if ( ! typesTarget [ i ] . isAssignableFrom ( typesFrom [ i ] ) ) { return false ; } } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns classes from array of objects . It accepts { [CODESPLIT] public static Class [ ] getClasses ( final Object ... objects ) { if ( objects . length == 0 ) { return EMPTY_CLASS_ARRAY ; } Class [ ] result = new Class [ objects . length ] ; for ( int i = 0 ; i < objects . length ; i ++ ) { if ( objects [ i ] != null ) { result [ i ] = objects [ i ] . getClass ( ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safe version of <code > isAssignableFrom< / code > method that returns <code > false< / code > if one of the arguments is <code > null< / code > . [CODESPLIT] public static boolean isTypeOf ( final Class < ? > lookupClass , final Class < ? > targetClass ) { if ( targetClass == null || lookupClass == null ) { return false ; } return targetClass . isAssignableFrom ( lookupClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safe version of <code > isInstance< / code > returns <code > false< / code > if any of the arguments is <code > null< / code > . [CODESPLIT] public static boolean isInstanceOf ( final Object object , final Class target ) { if ( object == null || target == null ) { return false ; } return target . isInstance ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves all interfaces of a type . No duplicates are returned . Direct interfaces are prior the interfaces of subclasses in the returned array . [CODESPLIT] public static Class [ ] resolveAllInterfaces ( final Class type ) { Set < Class > bag = new LinkedHashSet <> ( ) ; _resolveAllInterfaces ( type , bag ) ; return bag . toArray ( new Class [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves all super classes from top ( direct subclass ) to down . <code > Object< / code > class is not included in the list . [CODESPLIT] public static Class [ ] resolveAllSuperclasses ( Class type ) { List < Class > list = new ArrayList <> ( ) ; while ( true ) { type = type . getSuperclass ( ) ; if ( ( type == null ) || ( type == Object . class ) ) { break ; } list . add ( type ) ; } return list . toArray ( new Class [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns array of all methods that are accessible from given class upto limit ( usually <code > Object . class< / code > ) . Abstract methods are ignored . [CODESPLIT] public static Method [ ] getAccessibleMethods ( Class clazz , final Class limit ) { Package topPackage = clazz . getPackage ( ) ; List < Method > methodList = new ArrayList <> ( ) ; int topPackageHash = topPackage == null ? 0 : topPackage . hashCode ( ) ; boolean top = true ; do { if ( clazz == null ) { break ; } Method [ ] declaredMethods = clazz . getDeclaredMethods ( ) ; for ( Method method : declaredMethods ) { if ( Modifier . isVolatile ( method . getModifiers ( ) ) ) { continue ; } //\t\t\t\tif (Modifier.isAbstract(method.getModifiers())) { //\t\t\t\t\tcontinue; //\t\t\t\t} if ( top ) { // add all top declared methods methodList . add ( method ) ; continue ; } int modifier = method . getModifiers ( ) ; if ( Modifier . isPrivate ( modifier ) ) { continue ; // ignore super private methods } if ( Modifier . isAbstract ( modifier ) ) { // ignore super abstract methods continue ; } if ( Modifier . isPublic ( modifier ) ) { addMethodIfNotExist ( methodList , method ) ; // add super public methods continue ; } if ( Modifier . isProtected ( modifier ) ) { addMethodIfNotExist ( methodList , method ) ; // add super protected methods continue ; } // add super default methods from the same package Package pckg = method . getDeclaringClass ( ) . getPackage ( ) ; int pckgHash = pckg == null ? 0 : pckg . hashCode ( ) ; if ( pckgHash == topPackageHash ) { addMethodIfNotExist ( methodList , method ) ; } } top = false ; } while ( ( clazz = clazz . getSuperclass ( ) ) != limit ) ; Method [ ] methods = new Method [ methodList . size ( ) ] ; for ( int i = 0 ; i < methods . length ; i ++ ) { methods [ i ] = methodList . get ( i ) ; } return methods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > Method< / code > array of the methods to which instances of the specified respond except for those methods defined in the class specified by limit or any of its superclasses . Note that limit is usually used to eliminate them methods defined by <code > java . lang . Object< / code > . If limit is <code > null< / code > then all methods are returned . [CODESPLIT] public static Method [ ] getSupportedMethods ( final Class clazz , final Class limit ) { final ArrayList < Method > supportedMethods = new ArrayList <> ( ) ; for ( Class c = clazz ; c != limit && c != null ; c = c . getSuperclass ( ) ) { final Method [ ] methods = c . getDeclaredMethods ( ) ; for ( final Method method : methods ) { boolean found = false ; for ( final Method supportedMethod : supportedMethods ) { if ( compareSignatures ( method , supportedMethod ) ) { found = true ; break ; } } if ( ! found ) { supportedMethods . add ( method ) ; } } } return supportedMethods . toArray ( new Method [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares method declarations : signature and return types . [CODESPLIT] public static boolean compareDeclarations ( final Method first , final Method second ) { if ( first . getReturnType ( ) != second . getReturnType ( ) ) { return false ; } return compareSignatures ( first , second ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares method signatures : names and parameters . [CODESPLIT] public static boolean compareSignatures ( final Method first , final Method second ) { if ( ! first . getName ( ) . equals ( second . getName ( ) ) ) { return false ; } return compareParameters ( first . getParameterTypes ( ) , second . getParameterTypes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares classes usually method or ctor parameters . [CODESPLIT] public static boolean compareParameters ( final Class [ ] first , final Class [ ] second ) { if ( first . length != second . length ) { return false ; } for ( int i = 0 ; i < first . length ; i ++ ) { if ( first [ i ] != second [ i ] ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Suppress access check against a reflection object . SecurityException is silently ignored . Checks first if the object is already accessible . [CODESPLIT] public static void forceAccess ( final AccessibleObject accObject ) { try { if ( System . getSecurityManager ( ) == null ) accObject . setAccessible ( true ) ; else { AccessController . doPrivileged ( ( PrivilegedAction ) ( ) -> { accObject . setAccessible ( true ) ; return null ; } ) ; } } catch ( SecurityException sex ) { // ignore } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if class member is public and if its declaring class is also public . [CODESPLIT] public static boolean isPublicPublic ( final Member member ) { if ( Modifier . isPublic ( member . getModifiers ( ) ) ) { if ( Modifier . isPublic ( member . getDeclaringClass ( ) . getModifiers ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new instance of given class with given optional arguments . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T newInstance ( final Class < T > clazz , final Object ... params ) throws InstantiationException , IllegalAccessException , InvocationTargetException , NoSuchMethodException { if ( params . length == 0 ) { return newInstance ( clazz ) ; } final Class < ? > [ ] paramTypes = getClasses ( params ) ; final Constructor < ? > constructor = findConstructor ( clazz , paramTypes ) ; if ( constructor == null ) { throw new InstantiationException ( \"No constructor matched parameter types.\" ) ; } return ( T ) constructor . newInstance ( params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new instances including for common mutable classes that do not have a default constructor . more user - friendly . It examines if class is a map list String Character Boolean or a Number . Immutable instances are cached and not created again . Arrays are also created with no elements . Note that this bunch of <code > if< / code > blocks is faster then using a <code > HashMap< / code > . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T newInstance ( final Class < T > type ) throws IllegalAccessException , InstantiationException , NoSuchMethodException , InvocationTargetException { if ( type . isPrimitive ( ) ) { if ( type == int . class ) { return ( T ) Integer . valueOf ( 0 ) ; } if ( type == long . class ) { return ( T ) Long . valueOf ( 0 ) ; } if ( type == boolean . class ) { return ( T ) Boolean . FALSE ; } if ( type == float . class ) { return ( T ) Float . valueOf ( 0 ) ; } if ( type == double . class ) { return ( T ) Double . valueOf ( 0 ) ; } if ( type == byte . class ) { return ( T ) Byte . valueOf ( ( byte ) 0 ) ; } if ( type == short . class ) { return ( T ) Short . valueOf ( ( short ) 0 ) ; } if ( type == char . class ) { return ( T ) Character . valueOf ( ( char ) 0 ) ; } throw new IllegalArgumentException ( \"Invalid primitive: \" + type ) ; } if ( type . getName ( ) . startsWith ( \"java.\" ) ) { if ( type == Integer . class ) { return ( T ) Integer . valueOf ( 0 ) ; } if ( type == String . class ) { return ( T ) StringPool . EMPTY ; } if ( type == Long . class ) { return ( T ) Long . valueOf ( 0 ) ; } if ( type == Boolean . class ) { return ( T ) Boolean . FALSE ; } if ( type == Float . class ) { return ( T ) Float . valueOf ( 0 ) ; } if ( type == Double . class ) { return ( T ) Double . valueOf ( 0 ) ; } if ( type == Map . class ) { return ( T ) new HashMap ( ) ; } if ( type == List . class ) { return ( T ) new ArrayList ( ) ; } if ( type == Set . class ) { return ( T ) new HashSet ( ) ; } if ( type == Collection . class ) { return ( T ) new ArrayList ( ) ; } if ( type == Byte . class ) { return ( T ) Byte . valueOf ( ( byte ) 0 ) ; } if ( type == Short . class ) { return ( T ) Short . valueOf ( ( short ) 0 ) ; } if ( type == Character . class ) { return ( T ) Character . valueOf ( ( char ) 0 ) ; } } if ( type . isEnum ( ) ) { return type . getEnumConstants ( ) [ 0 ] ; } if ( type . isArray ( ) ) { return ( T ) Array . newInstance ( type . getComponentType ( ) , 0 ) ; } Constructor < T > declaredConstructor = type . getDeclaredConstructor ( ) ; forceAccess ( declaredConstructor ) ; return declaredConstructor . newInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the first member is accessible from second one . [CODESPLIT] public static boolean isAssignableFrom ( final Member member1 , final Member member2 ) { return member1 . getDeclaringClass ( ) . isAssignableFrom ( member2 . getDeclaringClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all superclasses . [CODESPLIT] public static Class [ ] getSuperclasses ( final Class type ) { int i = 0 ; for ( Class x = type . getSuperclass ( ) ; x != null ; x = x . getSuperclass ( ) ) { i ++ ; } Class [ ] result = new Class [ i ] ; i = 0 ; for ( Class x = type . getSuperclass ( ) ; x != null ; x = x . getSuperclass ( ) ) { result [ i ] = x ; i ++ ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if method is a bean property . [CODESPLIT] public static boolean isBeanProperty ( final Method method ) { if ( isObjectMethod ( method ) ) { return false ; } String methodName = method . getName ( ) ; Class returnType = method . getReturnType ( ) ; Class [ ] paramTypes = method . getParameterTypes ( ) ; if ( methodName . startsWith ( METHOD_GET_PREFIX ) ) { // getter method must starts with 'get' and it is not getClass() if ( ( returnType != null ) && ( paramTypes . length == 0 ) ) { // getter must have a return type and no arguments return true ; } } else if ( methodName . startsWith ( METHOD_IS_PREFIX ) ) { // ister must starts with 'is' if ( ( returnType != null ) && ( paramTypes . length == 0 ) ) { // ister must have return type and no arguments return true ; } } else if ( methodName . startsWith ( METHOD_SET_PREFIX ) ) { // setter must start with a 'set' if ( paramTypes . length == 1 ) { // setter must have just one argument return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns property name from a getter method . Returns <code > null< / code > if method is not a real getter . [CODESPLIT] public static String getBeanPropertyGetterName ( final Method method ) { int prefixLength = getBeanPropertyGetterPrefixLength ( method ) ; if ( prefixLength == 0 ) { return null ; } String methodName = method . getName ( ) . substring ( prefixLength ) ; return StringUtil . decapitalize ( methodName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns beans property setter name or <code > null< / code > if method is not a real setter . [CODESPLIT] public static String getBeanPropertySetterName ( final Method method ) { int prefixLength = getBeanPropertySetterPrefixLength ( method ) ; if ( prefixLength == 0 ) { return null ; } String methodName = method . getName ( ) . substring ( prefixLength ) ; return StringUtil . decapitalize ( methodName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns single component type for given type and implementation . Index is used when type consist of many components . If negative index will be calculated from the end of the returned array . Returns <code > null< / code > if component type does not exist or if index is out of bounds . <p > [CODESPLIT] public static Class getComponentType ( final Type type , final Class implClass , int index ) { Class [ ] componentTypes = getComponentTypes ( type , implClass ) ; if ( componentTypes == null ) { return null ; } if ( index < 0 ) { index += componentTypes . length ; } if ( index >= componentTypes . length ) { return null ; } return componentTypes [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all component types of the given type . For example the following types all have the component - type MyClass : <ul > <li > MyClass [] < / li > <li > List&lt ; MyClass&gt ; < / li > <li > Foo&lt ; ? extends MyClass&gt ; < / li > <li > Bar&lt ; ? super MyClass&gt ; < / li > <li > &lt ; T extends MyClass&gt ; T [] < / li > < / ul > [CODESPLIT] public static Class [ ] getComponentTypes ( final Type type , final Class implClass ) { if ( type instanceof Class ) { Class clazz = ( Class ) type ; if ( clazz . isArray ( ) ) { return new Class [ ] { clazz . getComponentType ( ) } ; } } else if ( type instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) type ; Type [ ] generics = pt . getActualTypeArguments ( ) ; if ( generics . length == 0 ) { return null ; } Class [ ] types = new Class [ generics . length ] ; for ( int i = 0 ; i < generics . length ; i ++ ) { types [ i ] = getRawType ( generics [ i ] , implClass ) ; } return types ; } else if ( type instanceof GenericArrayType ) { GenericArrayType gat = ( GenericArrayType ) type ; Class rawType = getRawType ( gat . getGenericComponentType ( ) , implClass ) ; if ( rawType == null ) { return null ; } return new Class [ ] { rawType } ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts <code > Type< / code > to a <code > String< / code > . Supports successor interfaces : <ul > <li > <code > java . lang . Class< / code > - represents usual class< / li > <li > <code > java . lang . reflect . ParameterizedType< / code > - class with generic parameter ( e . g . <code > List< / code > ) < / li > <li > <code > java . lang . reflect . TypeVariable< / code > - generic type literal ( e . g . <code > List< / code > <code > T< / code > - type variable ) < / li > <li > <code > java . lang . reflect . WildcardType< / code > - wildcard type ( <code > List&lt ; ? extends Number&gt ; < / code > <code > ? extends Number< / code > - wildcard type ) < / li > <li > <code > java . lang . reflect . GenericArrayType< / code > - type for generic array ( e . g . <code > T [] < / code > <code > T< / code > - array type ) < / li > < / ul > [CODESPLIT] public static String typeToString ( final Type type ) { StringBuilder sb = new StringBuilder ( ) ; typeToString ( sb , type , new HashSet < Type > ( ) ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads annotation value . Returns <code > null< / code > on error ( e . g . when value name not found ) . [CODESPLIT] public static Object readAnnotationValue ( final Annotation annotation , final String name ) { try { Method method = annotation . annotationType ( ) . getDeclaredMethod ( name ) ; return method . invoke ( annotation ) ; } catch ( Exception ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emulates <code > Reflection . getCallerClass< / code > using standard API . This implementation uses custom <code > SecurityManager< / code > and it is the fastest . Other implementations are : <ul > <li > <code > new Throwable () . getStackTrace () [ callStackDepth ] < / code > < / li > <li > <code > Thread . currentThread () . getStackTrace () [ callStackDepth ] < / code > ( the slowest ) < / li > < / ul > <p > In case when usage of <code > SecurityManager< / code > is not allowed this method fails back to the second implementation . <p > Note that original <code > Reflection . getCallerClass< / code > is way faster then any emulation . [CODESPLIT] public static Class getCallerClass ( int framesToSkip ) { if ( SECURITY_MANAGER != null ) { return SECURITY_MANAGER . getCallerClass ( framesToSkip ) ; } StackTraceElement [ ] stackTraceElements = new Throwable ( ) . getStackTrace ( ) ; if ( framesToSkip >= 2 ) { framesToSkip += 4 ; } String className = stackTraceElements [ framesToSkip ] . getClassName ( ) ; try { return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException cnfex ) { throw new UnsupportedOperationException ( className + \" not found.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Smart variant of { [CODESPLIT] public static Class getCallerClass ( ) { String className = null ; StackTraceElement [ ] stackTraceElements = new Throwable ( ) . getStackTrace ( ) ; for ( StackTraceElement stackTraceElement : stackTraceElements ) { className = stackTraceElement . getClassName ( ) ; String methodName = stackTraceElement . getMethodName ( ) ; if ( methodName . equals ( \"loadClass\" ) ) { if ( className . contains ( ClassLoaderStrategy . class . getSimpleName ( ) ) ) { continue ; } if ( className . equals ( ClassLoaderUtil . class . getName ( ) ) ) { continue ; } } else if ( methodName . equals ( \"getCallerClass\" ) ) { continue ; } break ; } try { return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException cnfex ) { throw new UnsupportedOperationException ( className + \" not found.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > enum< / code > class or <code > null< / code > if class is not an enum . [CODESPLIT] public static Class findEnum ( Class target ) { if ( target . isPrimitive ( ) ) { return null ; } while ( target != Object . class ) { if ( target . isEnum ( ) ) { return target ; } target = target . getSuperclass ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the class of the immediate subclass of the given parent class for the given object instance ; or null if such immediate subclass cannot be uniquely identified for the given object instance . [CODESPLIT] public static Class < ? > childClassOf ( final Class < ? > parentClass , final Object instance ) { if ( instance == null || instance == Object . class ) { return null ; } if ( parentClass != null ) { if ( parentClass . isInterface ( ) ) { return null ; } } Class < ? > childClass = instance . getClass ( ) ; while ( true ) { Class < ? > parent = childClass . getSuperclass ( ) ; if ( parent == parentClass ) { return childClass ; } if ( parent == null ) { return null ; } childClass = parent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the jar file from which the given class is loaded ; or null if no such jar file can be located . [CODESPLIT] public static JarFile jarFileOf ( final Class < ? > klass ) { URL url = klass . getResource ( \"/\" + klass . getName ( ) . replace ( ' ' , ' ' ) + \".class\" ) ; if ( url == null ) { return null ; } String s = url . getFile ( ) ; int beginIndex = s . indexOf ( \"file:\" ) + \"file:\" . length ( ) ; int endIndex = s . indexOf ( \".jar!\" ) ; if ( endIndex == - 1 ) { return null ; } endIndex += \".jar\" . length ( ) ; String f = s . substring ( beginIndex , endIndex ) ; // decode URL string - it may contain encoded chars (e.g. whitespaces) which are not supported for file-instances f = URLDecoder . decode ( f , \"UTF-8\" ) ; File file = new File ( f ) ; try { return file . exists ( ) ? new JarFile ( file ) : null ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves class file name from class name by replacing dot s with / separator and adding class extension at the end . If array component type is returned . [CODESPLIT] public static String convertClassNameToFileName ( Class clazz ) { if ( clazz . isArray ( ) ) { clazz = clazz . getComponentType ( ) ; } return convertClassNameToFileName ( clazz . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public static boolean isKotlinClass ( final Class type ) { final Annotation [ ] annotations = type . getAnnotations ( ) ; for ( Annotation annotation : annotations ) { if ( annotation . annotationType ( ) . getName ( ) . equals ( \"kotlin.Metadata\" ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if type is some integer - like type : INTEGER SMALLINT TINYINT BIT . [CODESPLIT] public static boolean isIntegerType ( final int type ) { return ( type == Types . INTEGER ) || ( type == Types . SMALLINT ) || ( type == Types . TINYINT ) || ( type == Types . BIT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a thread to sleep without throwing an InterruptedException . [CODESPLIT] public static void sleep ( final long ms ) { try { Thread . sleep ( ms ) ; } catch ( InterruptedException iex ) { Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a thread to sleep forever . [CODESPLIT] public static void sleep ( ) { try { Thread . sleep ( Long . MAX_VALUE ) ; } catch ( InterruptedException iex ) { Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for a object for synchronization purposes . [CODESPLIT] public static void wait ( final Object obj ) { synchronized ( obj ) { try { obj . wait ( ) ; } catch ( InterruptedException inex ) { Thread . currentThread ( ) . interrupt ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- join [CODESPLIT] public static void join ( final Thread thread ) { try { thread . join ( ) ; } catch ( InterruptedException inex ) { Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new daemon thread factory . [CODESPLIT] public static ThreadFactory daemonThreadFactory ( final String name , final int priority ) { return new ThreadFactory ( ) { private AtomicInteger count = new AtomicInteger ( ) ; @ Override public Thread newThread ( final Runnable r ) { Thread thread = new Thread ( r ) ; thread . setName ( name + ' ' + count . incrementAndGet ( ) ) ; thread . setDaemon ( true ) ; thread . setPriority ( priority ) ; return thread ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value . Value will be computed on first call . [CODESPLIT] @ Override public T get ( ) { if ( ! initialized ) { synchronized ( this ) { if ( ! initialized ) { final T t = supplier . get ( ) ; value = t ; initialized = true ; supplier = null ; return t ; } } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a parameter of this method . [CODESPLIT] public void visitParameter ( final String name , final int access ) { if ( api < Opcodes . ASM5 ) { throw new UnsupportedOperationException ( REQUIRES_ASM5 ) ; } if ( mv != null ) { mv . visitParameter ( name , access ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an annotation of this method . [CODESPLIT] public AnnotationVisitor visitAnnotation ( final String descriptor , final boolean visible ) { if ( mv != null ) { return mv . visitAnnotation ( descriptor , visible ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an annotation on a type in the method signature . [CODESPLIT] public AnnotationVisitor visitTypeAnnotation ( final int typeRef , final TypePath typePath , final String descriptor , final boolean visible ) { if ( api < Opcodes . ASM5 ) { throw new UnsupportedOperationException ( REQUIRES_ASM5 ) ; } if ( mv != null ) { return mv . visitTypeAnnotation ( typeRef , typePath , descriptor , visible ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an annotation of a parameter this method . [CODESPLIT] public AnnotationVisitor visitParameterAnnotation ( final int parameter , final String descriptor , final boolean visible ) { if ( mv != null ) { return mv . visitParameterAnnotation ( parameter , descriptor , visible ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits the current state of the local variables and operand stack elements . This method must ( * ) be called <i > just before< / i > any instruction <b > i< / b > that follows an unconditional branch instruction such as GOTO or THROW that is the target of a jump instruction or that starts an exception handler block . The visited types must describe the values of the local variables and of the operand stack elements <i > just before< / i > <b > i< / b > is executed . <br > <br > ( * ) this is mandatory only for classes whose version is greater than or equal to { @link Opcodes#V1_6 } . <br > <br > The frames of a method must be given either in expanded form or in compressed form ( all frames must use the same format i . e . you must not mix expanded and compressed frames within a single method ) : [CODESPLIT] public void visitFrame ( final int type , final int numLocal , final Object [ ] local , final int numStack , final Object [ ] stack ) { if ( mv != null ) { mv . visitFrame ( type , numLocal , local , numStack , stack ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a field instruction . A field instruction is an instruction that loads or stores the value of a field of an object . [CODESPLIT] public void visitFieldInsn ( final int opcode , final String owner , final String name , final String descriptor ) { if ( mv != null ) { mv . visitFieldInsn ( opcode , owner , name , descriptor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a method instruction . A method instruction is an instruction that invokes a method . [CODESPLIT] public void visitMethodInsn ( final int opcode , final String owner , final String name , final String descriptor , final boolean isInterface ) { if ( api < Opcodes . ASM5 ) { if ( isInterface != ( opcode == Opcodes . INVOKEINTERFACE ) ) { throw new IllegalArgumentException ( \"INVOKESPECIAL/STATIC on interfaces requires ASM5\" ) ; } visitMethodInsn ( opcode , owner , name , descriptor ) ; return ; } if ( mv != null ) { mv . visitMethodInsn ( opcode , owner , name , descriptor , isInterface ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an invokedynamic instruction . [CODESPLIT] public void visitInvokeDynamicInsn ( final String name , final String descriptor , final Handle bootstrapMethodHandle , final Object ... bootstrapMethodArguments ) { if ( api < Opcodes . ASM5 ) { throw new UnsupportedOperationException ( REQUIRES_ASM5 ) ; } if ( mv != null ) { mv . visitInvokeDynamicInsn ( name , descriptor , bootstrapMethodHandle , bootstrapMethodArguments ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a jump instruction . A jump instruction is an instruction that may jump to another instruction . [CODESPLIT] public void visitJumpInsn ( final int opcode , final Label label ) { if ( mv != null ) { mv . visitJumpInsn ( opcode , label ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a MULTIANEWARRAY instruction . [CODESPLIT] public void visitMultiANewArrayInsn ( final String descriptor , final int numDimensions ) { if ( mv != null ) { mv . visitMultiANewArrayInsn ( descriptor , numDimensions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a try catch block . [CODESPLIT] public void visitTryCatchBlock ( final Label start , final Label end , final Label handler , final String type ) { if ( mv != null ) { mv . visitTryCatchBlock ( start , end , handler , type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an annotation on a local variable type . [CODESPLIT] public AnnotationVisitor visitLocalVariableAnnotation ( final int typeRef , final TypePath typePath , final Label [ ] start , final Label [ ] end , final int [ ] index , final String descriptor , final boolean visible ) { if ( api < Opcodes . ASM5 ) { throw new UnsupportedOperationException ( REQUIRES_ASM5 ) ; } if ( mv != null ) { return mv . visitLocalVariableAnnotation ( typeRef , typePath , start , end , index , descriptor , visible ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert Java Properties to Jodd Props format [CODESPLIT] void convertToWriter ( final Writer writer , final Properties properties , final Map < String , Properties > profiles ) throws IOException { final BufferedWriter bw = getBufferedWriter ( writer ) ; writeBaseAndProfileProperties ( bw , properties , profiles ) ; writeProfilePropertiesThatAreNotInTheBase ( bw , properties , profiles ) ; bw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from input stream into byte array and stores file size . [CODESPLIT] @ Override public void processStream ( ) throws IOException { FastByteArrayOutputStream out = new FastByteArrayOutputStream ( ) ; size = 0 ; if ( maxFileSize == - 1 ) { size += input . copyAll ( out ) ; } else { size += input . copyMax ( out , maxFileSize + 1 ) ; // one more byte to detect larger files if ( size > maxFileSize ) { fileTooBig = true ; valid = false ; input . skipToBoundary ( ) ; return ; } } data = out . toByteArray ( ) ; size = data . length ; valid = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if there is { [CODESPLIT] @ Override public boolean hasNext ( ) { if ( hasNext == null ) { hasNext = Boolean . valueOf ( moveToNext ( ) ) ; } return hasNext . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns next mapped object . [CODESPLIT] @ Override public T next ( ) { if ( hasNext == null ) { hasNext = Boolean . valueOf ( moveToNext ( ) ) ; } if ( hasNext == false ) { throw new NoSuchElementException ( ) ; } if ( ! entityAwareMode ) { hasNext = null ; return newElement ; } count ++ ; T result = previousElement ; previousElement = newElement ; hasNext = null ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves to next element . [CODESPLIT] private boolean moveToNext ( ) { if ( last ) { // last has been set to true, so no more rows to iterate - close everything if ( closeOnEnd ) { query . close ( ) ; } else { query . closeResultSet ( resultSetMapper . getResultSet ( ) ) ; } return false ; } while ( true ) { if ( ! resultSetMapper . next ( ) ) { // no more rows, no more parsing, previousElement is the last one to iterate last = true ; return entityAwareMode ; } // parse row Object [ ] objects = resultSetMapper . parseObjects ( types ) ; Object row = query . resolveRowResults ( objects ) ; newElement = ( T ) row ; if ( entityAwareMode ) { if ( count == 0 && previousElement == null ) { previousElement = newElement ; continue ; } if ( previousElement != null && newElement != null ) { boolean equals ; if ( newElement . getClass ( ) . isArray ( ) ) { equals = Arrays . equals ( ( Object [ ] ) previousElement , ( Object [ ] ) newElement ) ; } else { equals = previousElement . equals ( newElement ) ; } if ( equals ) { continue ; } } } break ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins arrays . Component type is resolved from the array argument . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static < T > T [ ] join ( T [ ] ... arrays ) { Class < T > componentType = ( Class < T > ) arrays . getClass ( ) . getComponentType ( ) . getComponentType ( ) ; return join ( componentType , arrays ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins arrays using provided component type . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static < T > T [ ] join ( Class < T > componentType , T [ ] [ ] arrays ) { if ( arrays . length == 1 ) { return arrays [ 0 ] ; } int length = 0 ; for ( T [ ] array : arrays ) { length += array . length ; } T [ ] result = ( T [ ] ) Array . newInstance ( componentType , length ) ; length = 0 ; for ( T [ ] array : arrays ) { System . arraycopy ( array , 0 , result , length , array . length ) ; length += array . length ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join <code > double< / code > arrays . [CODESPLIT] public static double [ ] join ( double [ ] ... arrays ) { if ( arrays . length == 0 ) { return new double [ 0 ] ; } if ( arrays . length == 1 ) { return arrays [ 0 ] ; } int length = 0 ; for ( double [ ] array : arrays ) { length += array . length ; } double [ ] result = new double [ length ] ; length = 0 ; for ( double [ ] array : arrays ) { System . arraycopy ( array , 0 , result , length , array . length ) ; length += array . length ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resizes an array . [CODESPLIT] public static < T > T [ ] resize ( T [ ] buffer , int newSize ) { Class < T > componentType = ( Class < T > ) buffer . getClass ( ) . getComponentType ( ) ; T [ ] temp = ( T [ ] ) Array . newInstance ( componentType , newSize ) ; System . arraycopy ( buffer , 0 , temp , 0 , buffer . length >= newSize ? newSize : buffer . length ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resizes a <code > String< / code > array . [CODESPLIT] public static String [ ] resize ( String [ ] buffer , int newSize ) { String [ ] temp = new String [ newSize ] ; System . arraycopy ( buffer , 0 , temp , 0 , buffer . length >= newSize ? newSize : buffer . length ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends an element to array . [CODESPLIT] public static < T > T [ ] append ( T [ ] buffer , T newElement ) { T [ ] t = resize ( buffer , buffer . length + 1 ) ; t [ buffer . length ] = newElement ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes sub - array . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static < T > T [ ] remove ( T [ ] buffer , int offset , int length , Class < T > componentType ) { int len2 = buffer . length - length ; T [ ] temp = ( T [ ] ) Array . newInstance ( componentType , len2 ) ; System . arraycopy ( buffer , 0 , temp , 0 , offset ) ; System . arraycopy ( buffer , offset + length , temp , offset , len2 - offset ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes sub - array from <code > boolean< / code > array . [CODESPLIT] public static boolean [ ] remove ( boolean [ ] buffer , int offset , int length ) { int len2 = buffer . length - length ; boolean [ ] temp = new boolean [ len2 ] ; System . arraycopy ( buffer , 0 , temp , 0 , offset ) ; System . arraycopy ( buffer , offset + length , temp , offset , len2 - offset ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns subarray . [CODESPLIT] public static < T > T [ ] subarray ( T [ ] buffer , int offset , int length ) { Class < T > componentType = ( Class < T > ) buffer . getClass ( ) . getComponentType ( ) ; return subarray ( buffer , offset , length , componentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns subarray . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static < T > T [ ] subarray ( T [ ] buffer , int offset , int length , Class < T > componentType ) { T [ ] temp = ( T [ ] ) Array . newInstance ( componentType , length ) ; System . arraycopy ( buffer , offset , temp , 0 , length ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns subarray . [CODESPLIT] public static String [ ] subarray ( String [ ] buffer , int offset , int length ) { String [ ] temp = new String [ length ] ; System . arraycopy ( buffer , offset , temp , 0 , length ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts one array into another <code > String< / code > array . [CODESPLIT] public static String [ ] insert ( String [ ] dest , String [ ] src , int offset ) { String [ ] temp = new String [ dest . length + src . length ] ; System . arraycopy ( dest , 0 , temp , 0 , offset ) ; System . arraycopy ( src , 0 , temp , offset , src . length ) ; System . arraycopy ( dest , offset , temp , src . length + offset , dest . length - offset ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts one array into another at given offset . [CODESPLIT] public static < T > T [ ] insertAt ( T [ ] dest , T [ ] src , int offset ) { Class < T > componentType = ( Class < T > ) dest . getClass ( ) . getComponentType ( ) ; return insertAt ( dest , src , offset , componentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts one array into another at given offset . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public static < T > T [ ] insertAt ( T [ ] dest , T [ ] src , int offset , Class componentType ) { T [ ] temp = ( T [ ] ) Array . newInstance ( componentType , dest . length + src . length - 1 ) ; System . arraycopy ( dest , 0 , temp , 0 , offset ) ; System . arraycopy ( src , 0 , temp , offset , src . length ) ; System . arraycopy ( dest , offset + 1 , temp , src . length + offset , dest . length - offset - 1 ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static byte [ ] values ( Byte [ ] array ) { byte [ ] dest = new byte [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Byte v = array [ i ] ; if ( v != null ) { dest [ i ] = v . byteValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Byte [ ] valuesOf ( byte [ ] array ) { Byte [ ] dest = new Byte [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Byte . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static char [ ] values ( Character [ ] array ) { char [ ] dest = new char [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Character v = array [ i ] ; if ( v != null ) { dest [ i ] = v . charValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Character [ ] valuesOf ( char [ ] array ) { Character [ ] dest = new Character [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Character . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static short [ ] values ( Short [ ] array ) { short [ ] dest = new short [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Short v = array [ i ] ; if ( v != null ) { dest [ i ] = v . shortValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Short [ ] valuesOf ( short [ ] array ) { Short [ ] dest = new Short [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Short . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static int [ ] values ( Integer [ ] array ) { int [ ] dest = new int [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Integer v = array [ i ] ; if ( v != null ) { dest [ i ] = v . intValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Integer [ ] valuesOf ( int [ ] array ) { Integer [ ] dest = new Integer [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Integer . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static long [ ] values ( Long [ ] array ) { long [ ] dest = new long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Long v = array [ i ] ; if ( v != null ) { dest [ i ] = v . longValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Long [ ] valuesOf ( long [ ] array ) { Long [ ] dest = new Long [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Long . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static float [ ] values ( Float [ ] array ) { float [ ] dest = new float [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Float v = array [ i ] ; if ( v != null ) { dest [ i ] = v . floatValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Float [ ] valuesOf ( float [ ] array ) { Float [ ] dest = new Float [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Float . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static double [ ] values ( Double [ ] array ) { double [ ] dest = new double [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Double v = array [ i ] ; if ( v != null ) { dest [ i ] = v . doubleValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Double [ ] valuesOf ( double [ ] array ) { Double [ ] dest = new Double [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Double . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to primitive array . [CODESPLIT] public static boolean [ ] values ( Boolean [ ] array ) { boolean [ ] dest = new boolean [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { Boolean v = array [ i ] ; if ( v != null ) { dest [ i ] = v . booleanValue ( ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to object array . [CODESPLIT] public static Boolean [ ] valuesOf ( boolean [ ] array ) { Boolean [ ] dest = new Boolean [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { dest [ i ] = Boolean . valueOf ( array [ i ] ) ; } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence in an array from specified given position and upto given length . [CODESPLIT] public static int indexOf ( byte [ ] array , byte value , int startIndex , int endIndex ) { for ( int i = startIndex ; i < endIndex ; i ++ ) { if ( array [ i ] == value ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence of an element in an array . [CODESPLIT] public static int indexOf ( char [ ] array , char value ) { for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == value ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence of value in <code > float< / code > array . [CODESPLIT] public static int indexOf ( float [ ] array , float value ) { for ( int i = 0 ; i < array . length ; i ++ ) { if ( Float . compare ( array [ i ] , value ) == 0 ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence in <code > float< / code > array from specified given position and upto given length . [CODESPLIT] public static int indexOf ( float [ ] array , float value , int startIndex , int endIndex ) { for ( int i = startIndex ; i < endIndex ; i ++ ) { if ( Float . compare ( array [ i ] , value ) == 0 ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence of value in <code > double< / code > array . [CODESPLIT] public static int indexOf ( double [ ] array , double value ) { for ( int i = 0 ; i < array . length ; i ++ ) { if ( Double . compare ( array [ i ] , value ) == 0 ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence in <code > double< / code > array from specified given position and upto given length . [CODESPLIT] public static int indexOf ( double [ ] array , double value , int startIndex , int endIndex ) { for ( int i = startIndex ; i < endIndex ; i ++ ) { if ( Double . compare ( array [ i ] , value ) == 0 ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence in an array . [CODESPLIT] public static int indexOf ( Object [ ] array , Object value ) { for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] . equals ( value ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence in an array from specified given position . [CODESPLIT] public static int indexOf ( byte [ ] array , byte [ ] sub , int startIndex ) { return indexOf ( array , sub , startIndex , array . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence in an array from specified given position and upto given length . [CODESPLIT] public static int indexOf ( double [ ] array , double [ ] sub , int startIndex , int endIndex ) { int sublen = sub . length ; if ( sublen == 0 ) { return startIndex ; } int total = endIndex - sublen + 1 ; double c = sub [ 0 ] ; mainloop : for ( int i = startIndex ; i < total ; i ++ ) { if ( Double . compare ( array [ i ] , c ) != 0 ) { continue ; } int j = 1 ; int k = i + 1 ; while ( j < sublen ) { if ( Double . compare ( sub [ j ] , array [ k ] ) != 0 ) { continue mainloop ; } j ++ ; k ++ ; } return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array to string array . [CODESPLIT] public static String [ ] toStringArray ( Object [ ] array ) { if ( array == null ) { return null ; } String [ ] result = new String [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = StringUtil . toString ( array [ i ] ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array to string array . [CODESPLIT] public static String [ ] toStringArray ( String [ ] array ) { if ( array == null ) { return null ; } String [ ] result = new String [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = String . valueOf ( array [ i ] ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables XHTML mode . [CODESPLIT] public LagartoDOMBuilder enableXhtmlMode ( ) { config . ignoreWhitespacesBetweenTags = false ; // collect all whitespaces config . setCaseSensitive ( true ) ; // XHTML is case sensitive config . setEnableRawTextModes ( false ) ; // all tags are parsed in the same way config . enabledVoidTags = true ; // list of void tags config . selfCloseVoidTags = true ; // self close void tags config . impliedEndTags = false ; // no implied tag ends config . setEnableConditionalComments ( false ) ; // don't enable IE conditional comments config . setParseXmlTags ( false ) ; // enable XML mode in parsing return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates DOM tree from provided content . [CODESPLIT] @ Override public Document parse ( final char [ ] content ) { LagartoParser lagartoParser = new LagartoParser ( content ) ; return doParse ( lagartoParser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the content using provided lagarto parser . [CODESPLIT] protected Document doParse ( final LagartoParser lagartoParser ) { lagartoParser . setConfig ( config ) ; LagartoDOMBuilderTagVisitor domBuilderTagVisitor = new LagartoDOMBuilderTagVisitor ( this ) ; lagartoParser . parse ( domBuilderTagVisitor ) ; return domBuilderTagVisitor . getDocument ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------------------------------- [CODESPLIT] @ Override public void visitParameter ( final String name , final int access ) { if ( parameters == null ) { parameters = new ByteVector ( ) ; } ++ parametersCount ; parameters . putShort ( ( name == null ) ? 0 : symbolTable . addConstantUtf8 ( name ) ) . putShort ( access ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes all the stack map frames of the method from scratch . [CODESPLIT] private void computeAllFrames ( ) { // Complete the control flow graph with exception handler blocks. Handler handler = firstHandler ; while ( handler != null ) { String catchTypeDescriptor = handler . catchTypeDescriptor == null ? \"java/lang/Throwable\" : handler . catchTypeDescriptor ; int catchType = Frame . getAbstractTypeFromInternalName ( symbolTable , catchTypeDescriptor ) ; // Mark handlerBlock as an exception handler. Label handlerBlock = handler . handlerPc . getCanonicalInstance ( ) ; handlerBlock . flags |= Label . FLAG_JUMP_TARGET ; // Add handlerBlock as a successor of all the basic blocks in the exception handler range. Label handlerRangeBlock = handler . startPc . getCanonicalInstance ( ) ; Label handlerRangeEnd = handler . endPc . getCanonicalInstance ( ) ; while ( handlerRangeBlock != handlerRangeEnd ) { handlerRangeBlock . outgoingEdges = new Edge ( catchType , handlerBlock , handlerRangeBlock . outgoingEdges ) ; handlerRangeBlock = handlerRangeBlock . nextBasicBlock ; } handler = handler . nextHandler ; } // Create and visit the first (implicit) frame. Frame firstFrame = firstBasicBlock . frame ; firstFrame . setInputFrameFromDescriptor ( symbolTable , accessFlags , descriptor , this . maxLocals ) ; firstFrame . accept ( this ) ; // Fix point algorithm: add the first basic block to a list of blocks to process (i.e. blocks // whose stack map frame has changed) and, while there are blocks to process, remove one from // the list and update the stack map frames of its successor blocks in the control flow graph // (which might change them, in which case these blocks must be processed too, and are thus // added to the list of blocks to process). Also compute the maximum stack size of the method, // as a by-product. Label listOfBlocksToProcess = firstBasicBlock ; listOfBlocksToProcess . nextListElement = Label . EMPTY_LIST ; int maxStackSize = 0 ; while ( listOfBlocksToProcess != Label . EMPTY_LIST ) { // Remove a basic block from the list of blocks to process. Label basicBlock = listOfBlocksToProcess ; listOfBlocksToProcess = listOfBlocksToProcess . nextListElement ; basicBlock . nextListElement = null ; // By definition, basicBlock is reachable. basicBlock . flags |= Label . FLAG_REACHABLE ; // Update the (absolute) maximum stack size. int maxBlockStackSize = basicBlock . frame . getInputStackSize ( ) + basicBlock . outputStackMax ; if ( maxBlockStackSize > maxStackSize ) { maxStackSize = maxBlockStackSize ; } // Update the successor blocks of basicBlock in the control flow graph. Edge outgoingEdge = basicBlock . outgoingEdges ; while ( outgoingEdge != null ) { Label successorBlock = outgoingEdge . successor . getCanonicalInstance ( ) ; boolean successorBlockChanged = basicBlock . frame . merge ( symbolTable , successorBlock . frame , outgoingEdge . info ) ; if ( successorBlockChanged && successorBlock . nextListElement == null ) { // If successorBlock has changed it must be processed. Thus, if it is not already in the // list of blocks to process, add it to this list. successorBlock . nextListElement = listOfBlocksToProcess ; listOfBlocksToProcess = successorBlock ; } outgoingEdge = outgoingEdge . nextEdge ; } } // Loop over all the basic blocks and visit the stack map frames that must be stored in the // StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from // exception handler ranges. Label basicBlock = firstBasicBlock ; while ( basicBlock != null ) { if ( ( basicBlock . flags & ( Label . FLAG_JUMP_TARGET | Label . FLAG_REACHABLE ) ) == ( Label . FLAG_JUMP_TARGET | Label . FLAG_REACHABLE ) ) { basicBlock . frame . accept ( this ) ; } if ( ( basicBlock . flags & Label . FLAG_REACHABLE ) == 0 ) { // Find the start and end bytecode offsets of this unreachable block. Label nextBasicBlock = basicBlock . nextBasicBlock ; int startOffset = basicBlock . bytecodeOffset ; int endOffset = ( nextBasicBlock == null ? code . length : nextBasicBlock . bytecodeOffset ) - 1 ; if ( endOffset >= startOffset ) { // Replace its instructions with NOP ... NOP ATHROW. for ( int i = startOffset ; i < endOffset ; ++ i ) { code . data [ i ] = Opcodes . NOP ; } code . data [ endOffset ] = ( byte ) Opcodes . ATHROW ; // Emit a frame for this unreachable block, with no local and a Throwable on the stack // (so that the ATHROW could consume this Throwable if it were reachable). int frameIndex = visitFrameStart ( startOffset , /* numLocal = */ 0 , /* numStack = */ 1 ) ; currentFrame [ frameIndex ] = Frame . getAbstractTypeFromInternalName ( symbolTable , \"java/lang/Throwable\" ) ; visitFrameEnd ( ) ; // Remove this unreachable basic block from the exception handler ranges. firstHandler = Handler . removeRange ( firstHandler , basicBlock , nextBasicBlock ) ; // The maximum stack size is now at least one, because of the Throwable declared above. maxStackSize = Math . max ( maxStackSize , 1 ) ; } } basicBlock = basicBlock . nextBasicBlock ; } this . maxStack = maxStackSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the maximum stack size of the method . [CODESPLIT] private void computeMaxStackAndLocal ( ) { // Complete the control flow graph with exception handler blocks. Handler handler = firstHandler ; while ( handler != null ) { Label handlerBlock = handler . handlerPc ; Label handlerRangeBlock = handler . startPc ; Label handlerRangeEnd = handler . endPc ; // Add handlerBlock as a successor of all the basic blocks in the exception handler range. while ( handlerRangeBlock != handlerRangeEnd ) { if ( ( handlerRangeBlock . flags & Label . FLAG_SUBROUTINE_CALLER ) == 0 ) { handlerRangeBlock . outgoingEdges = new Edge ( Edge . EXCEPTION , handlerBlock , handlerRangeBlock . outgoingEdges ) ; } else { // If handlerRangeBlock is a JSR block, add handlerBlock after the first two outgoing // edges to preserve the hypothesis about JSR block successors order (see // {@link #visitJumpInsn}). handlerRangeBlock . outgoingEdges . nextEdge . nextEdge = new Edge ( Edge . EXCEPTION , handlerBlock , handlerRangeBlock . outgoingEdges . nextEdge . nextEdge ) ; } handlerRangeBlock = handlerRangeBlock . nextBasicBlock ; } handler = handler . nextHandler ; } // Complete the control flow graph with the successor blocks of subroutines, if needed. if ( hasSubroutines ) { // First step: find the subroutines. This step determines, for each basic block, to which // subroutine(s) it belongs. Start with the main \"subroutine\": short numSubroutines = 1 ; firstBasicBlock . markSubroutine ( numSubroutines ) ; // Then, mark the subroutines called by the main subroutine, then the subroutines called by // those called by the main subroutine, etc. for ( short currentSubroutine = 1 ; currentSubroutine <= numSubroutines ; ++ currentSubroutine ) { Label basicBlock = firstBasicBlock ; while ( basicBlock != null ) { if ( ( basicBlock . flags & Label . FLAG_SUBROUTINE_CALLER ) != 0 && basicBlock . subroutineId == currentSubroutine ) { Label jsrTarget = basicBlock . outgoingEdges . nextEdge . successor ; if ( jsrTarget . subroutineId == 0 ) { // If this subroutine has not been marked yet, find its basic blocks. jsrTarget . markSubroutine ( ++ numSubroutines ) ; } } basicBlock = basicBlock . nextBasicBlock ; } } // Second step: find the successors in the control flow graph of each subroutine basic block // 'r' ending with a RET instruction. These successors are the virtual successors of the basic // blocks ending with JSR instructions (see {@link #visitJumpInsn)} that can reach 'r'. Label basicBlock = firstBasicBlock ; while ( basicBlock != null ) { if ( ( basicBlock . flags & Label . FLAG_SUBROUTINE_CALLER ) != 0 ) { // By construction, jsr targets are stored in the second outgoing edge of basic blocks // that ends with a jsr instruction (see {@link #FLAG_SUBROUTINE_CALLER}). Label subroutine = basicBlock . outgoingEdges . nextEdge . successor ; subroutine . addSubroutineRetSuccessors ( basicBlock ) ; } basicBlock = basicBlock . nextBasicBlock ; } } // Data flow algorithm: put the first basic block in a list of blocks to process (i.e. blocks // whose input stack size has changed) and, while there are blocks to process, remove one // from the list, update the input stack size of its successor blocks in the control flow // graph, and add these blocks to the list of blocks to process (if not already done). Label listOfBlocksToProcess = firstBasicBlock ; listOfBlocksToProcess . nextListElement = Label . EMPTY_LIST ; int maxStackSize = maxStack ; while ( listOfBlocksToProcess != Label . EMPTY_LIST ) { // Remove a basic block from the list of blocks to process. Note that we don't reset // basicBlock.nextListElement to null on purpose, to make sure we don't reprocess already // processed basic blocks. Label basicBlock = listOfBlocksToProcess ; listOfBlocksToProcess = listOfBlocksToProcess . nextListElement ; // Compute the (absolute) input stack size and maximum stack size of this block. int inputStackTop = basicBlock . inputStackSize ; int maxBlockStackSize = inputStackTop + basicBlock . outputStackMax ; // Update the absolute maximum stack size of the method. if ( maxBlockStackSize > maxStackSize ) { maxStackSize = maxBlockStackSize ; } // Update the input stack size of the successor blocks of basicBlock in the control flow // graph, and add these blocks to the list of blocks to process, if not already done. Edge outgoingEdge = basicBlock . outgoingEdges ; if ( ( basicBlock . flags & Label . FLAG_SUBROUTINE_CALLER ) != 0 ) { // Ignore the first outgoing edge of the basic blocks ending with a jsr: these are virtual // edges which lead to the instruction just after the jsr, and do not correspond to a // possible execution path (see {@link #visitJumpInsn} and // {@link Label#FLAG_SUBROUTINE_CALLER}). outgoingEdge = outgoingEdge . nextEdge ; } while ( outgoingEdge != null ) { Label successorBlock = outgoingEdge . successor ; if ( successorBlock . nextListElement == null ) { successorBlock . inputStackSize = ( short ) ( outgoingEdge . info == Edge . EXCEPTION ? 1 : inputStackTop + outgoingEdge . info ) ; successorBlock . nextListElement = listOfBlocksToProcess ; listOfBlocksToProcess = successorBlock ; } outgoingEdge = outgoingEdge . nextEdge ; } } this . maxStack = maxStackSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a successor to { @link #currentBasicBlock } in the control flow graph . [CODESPLIT] private void addSuccessorToCurrentBasicBlock ( final int info , final Label successor ) { currentBasicBlock . outgoingEdges = new Edge ( info , successor , currentBasicBlock . outgoingEdges ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ends the current basic block . This method must be used in the case where the current basic block does not have any successor . [CODESPLIT] private void endCurrentBasicBlockWithNoSuccessor ( ) { if ( compute == COMPUTE_ALL_FRAMES ) { Label nextBasicBlock = new Label ( ) ; nextBasicBlock . frame = new Frame ( nextBasicBlock ) ; nextBasicBlock . resolve ( code . data , code . length ) ; lastBasicBlock . nextBasicBlock = nextBasicBlock ; lastBasicBlock = nextBasicBlock ; currentBasicBlock = null ; } else if ( compute == COMPUTE_MAX_STACK_AND_LOCAL ) { currentBasicBlock . outputStackMax = ( short ) maxRelativeStackSize ; currentBasicBlock = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the visit of a new stack map frame stored in { @link #currentFrame } . [CODESPLIT] int visitFrameStart ( final int offset , final int numLocal , final int numStack ) { int frameLength = 3 + numLocal + numStack ; if ( currentFrame == null || currentFrame . length < frameLength ) { currentFrame = new int [ frameLength ] ; } currentFrame [ 0 ] = offset ; currentFrame [ 1 ] = numLocal ; currentFrame [ 2 ] = numStack ; return 3 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ends the visit of { [CODESPLIT] void visitFrameEnd ( ) { if ( previousFrame != null ) { if ( stackMapTableEntries == null ) { stackMapTableEntries = new ByteVector ( ) ; } putFrame ( ) ; ++ stackMapTableNumberOfEntries ; } previousFrame = currentFrame ; currentFrame = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compresses and writes { [CODESPLIT] private void putFrame ( ) { final int numLocal = currentFrame [ 1 ] ; final int numStack = currentFrame [ 2 ] ; if ( symbolTable . getMajorVersion ( ) < Opcodes . V1_6 ) { // Generate a StackMap attribute entry, which are always uncompressed. stackMapTableEntries . putShort ( currentFrame [ 0 ] ) . putShort ( numLocal ) ; putAbstractTypes ( 3 , 3 + numLocal ) ; stackMapTableEntries . putShort ( numStack ) ; putAbstractTypes ( 3 + numLocal , 3 + numLocal + numStack ) ; return ; } final int offsetDelta = stackMapTableNumberOfEntries == 0 ? currentFrame [ 0 ] : currentFrame [ 0 ] - previousFrame [ 0 ] - 1 ; final int previousNumlocal = previousFrame [ 1 ] ; final int numLocalDelta = numLocal - previousNumlocal ; int type = Frame . FULL_FRAME ; if ( numStack == 0 ) { switch ( numLocalDelta ) { case - 3 : case - 2 : case - 1 : type = Frame . CHOP_FRAME ; break ; case 0 : type = offsetDelta < 64 ? Frame . SAME_FRAME : Frame . SAME_FRAME_EXTENDED ; break ; case 1 : case 2 : case 3 : type = Frame . APPEND_FRAME ; break ; default : // Keep the FULL_FRAME type. break ; } } else if ( numLocalDelta == 0 && numStack == 1 ) { type = offsetDelta < 63 ? Frame . SAME_LOCALS_1_STACK_ITEM_FRAME : Frame . SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED ; } if ( type != Frame . FULL_FRAME ) { // Verify if locals are the same as in the previous frame. int frameIndex = 3 ; for ( int i = 0 ; i < previousNumlocal && i < numLocal ; i ++ ) { if ( currentFrame [ frameIndex ] != previousFrame [ frameIndex ] ) { type = Frame . FULL_FRAME ; break ; } frameIndex ++ ; } } switch ( type ) { case Frame . SAME_FRAME : stackMapTableEntries . putByte ( offsetDelta ) ; break ; case Frame . SAME_LOCALS_1_STACK_ITEM_FRAME : stackMapTableEntries . putByte ( Frame . SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta ) ; putAbstractTypes ( 3 + numLocal , 4 + numLocal ) ; break ; case Frame . SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED : stackMapTableEntries . putByte ( Frame . SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED ) . putShort ( offsetDelta ) ; putAbstractTypes ( 3 + numLocal , 4 + numLocal ) ; break ; case Frame . SAME_FRAME_EXTENDED : stackMapTableEntries . putByte ( Frame . SAME_FRAME_EXTENDED ) . putShort ( offsetDelta ) ; break ; case Frame . CHOP_FRAME : stackMapTableEntries . putByte ( Frame . SAME_FRAME_EXTENDED + numLocalDelta ) . putShort ( offsetDelta ) ; break ; case Frame . APPEND_FRAME : stackMapTableEntries . putByte ( Frame . SAME_FRAME_EXTENDED + numLocalDelta ) . putShort ( offsetDelta ) ; putAbstractTypes ( 3 + previousNumlocal , 3 + numLocal ) ; break ; case Frame . FULL_FRAME : default : stackMapTableEntries . putByte ( Frame . FULL_FRAME ) . putShort ( offsetDelta ) . putShort ( numLocal ) ; putAbstractTypes ( 3 , 3 + numLocal ) ; stackMapTableEntries . putShort ( numStack ) ; putAbstractTypes ( 3 + numLocal , 3 + numLocal + numStack ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts some abstract types of { @link #currentFrame } in { @link #stackMapTableEntries } using the JVMS verification_type_info format used in StackMapTable attributes . [CODESPLIT] private void putAbstractTypes ( final int start , final int end ) { for ( int i = start ; i < end ; ++ i ) { Frame . putAbstractType ( symbolTable , currentFrame [ i ] , stackMapTableEntries ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the given public API frame element type in { @link #stackMapTableEntries } using the JVMS verification_type_info format used in StackMapTable attributes . [CODESPLIT] private void putFrameType ( final Object type ) { if ( type instanceof Integer ) { stackMapTableEntries . putByte ( ( ( Integer ) type ) . intValue ( ) ) ; } else if ( type instanceof String ) { stackMapTableEntries . putByte ( Frame . ITEM_OBJECT ) . putShort ( symbolTable . addConstantClass ( ( String ) type ) . index ) ; } else { stackMapTableEntries . putByte ( Frame . ITEM_UNINITIALIZED ) . putShort ( ( ( Label ) type ) . bytecodeOffset ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the attributes of this method can be copied from the attributes of the given method ( assuming there is no method visitor between the given ClassReader and this MethodWriter ) . This method should only be called just after this MethodWriter has been created and before any content is visited . It returns true if the attributes corresponding to the constructor arguments ( at most a Signature an Exception a Deprecated and a Synthetic attribute ) are the same as the corresponding attributes in the given method . [CODESPLIT] boolean canCopyMethodAttributes ( final ClassReader source , final int methodInfoOffset , final int methodInfoLength , final boolean hasSyntheticAttribute , final boolean hasDeprecatedAttribute , final int descriptorIndex , final int signatureIndex , final int exceptionsOffset ) { // If the method descriptor has changed, with more locals than the max_locals field of the // original Code attribute, if any, then the original method attributes can't be copied. A // conservative check on the descriptor changes alone ensures this (being more precise is not // worth the additional complexity, because these cases should be rare -- if a transform changes // a method descriptor, most of the time it needs to change the method's code too). if ( source != symbolTable . getSource ( ) || descriptorIndex != this . descriptorIndex || signatureIndex != this . signatureIndex || hasDeprecatedAttribute != ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) ) { return false ; } boolean needSyntheticAttribute = symbolTable . getMajorVersion ( ) < Opcodes . V1_5 && ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 ; if ( hasSyntheticAttribute != needSyntheticAttribute ) { return false ; } if ( exceptionsOffset == 0 ) { if ( numberOfExceptions != 0 ) { return false ; } } else if ( source . readUnsignedShort ( exceptionsOffset ) == numberOfExceptions ) { int currentExceptionOffset = exceptionsOffset + 2 ; for ( int i = 0 ; i < numberOfExceptions ; ++ i ) { if ( source . readUnsignedShort ( currentExceptionOffset ) != exceptionIndexTable [ i ] ) { return false ; } currentExceptionOffset += 2 ; } } // Don't copy the attributes yet, instead store their location in the source class reader so // they can be copied later, in {@link #putMethodInfo}. Note that we skip the 6 header bytes // of the method_info JVMS structure. this . sourceOffset = methodInfoOffset + 6 ; this . sourceLength = methodInfoLength - 6 ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of the method_info JVMS structure generated by this MethodWriter . Also add the names of the attributes of this method in the constant pool . [CODESPLIT] int computeMethodInfoSize ( ) { // If this method_info must be copied from an existing one, the size computation is trivial. if ( sourceOffset != 0 ) { // sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index. return 6 + sourceLength ; } // 2 bytes each for access_flags, name_index, descriptor_index and attributes_count. int size = 8 ; // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. if ( code . length > 0 ) { if ( code . length > 65535 ) { throw new MethodTooLargeException ( symbolTable . getClassName ( ) , name , descriptor , code . length ) ; } symbolTable . addConstantUtf8 ( Constants . CODE ) ; // The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack, // max_locals, code_length and attributes_count, plus the bytecode and the exception table. size += 16 + code . length + Handler . getExceptionTableSize ( firstHandler ) ; if ( stackMapTableEntries != null ) { boolean useStackMapTable = symbolTable . getMajorVersion ( ) >= Opcodes . V1_6 ; symbolTable . addConstantUtf8 ( useStackMapTable ? Constants . STACK_MAP_TABLE : \"StackMap\" ) ; // 6 header bytes and 2 bytes for number_of_entries. size += 8 + stackMapTableEntries . length ; } if ( lineNumberTable != null ) { symbolTable . addConstantUtf8 ( Constants . LINE_NUMBER_TABLE ) ; // 6 header bytes and 2 bytes for line_number_table_length. size += 8 + lineNumberTable . length ; } if ( localVariableTable != null ) { symbolTable . addConstantUtf8 ( Constants . LOCAL_VARIABLE_TABLE ) ; // 6 header bytes and 2 bytes for local_variable_table_length. size += 8 + localVariableTable . length ; } if ( localVariableTypeTable != null ) { symbolTable . addConstantUtf8 ( Constants . LOCAL_VARIABLE_TYPE_TABLE ) ; // 6 header bytes and 2 bytes for local_variable_type_table_length. size += 8 + localVariableTypeTable . length ; } if ( lastCodeRuntimeVisibleTypeAnnotation != null ) { size += lastCodeRuntimeVisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) ; } if ( lastCodeRuntimeInvisibleTypeAnnotation != null ) { size += lastCodeRuntimeInvisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) ; } if ( firstCodeAttribute != null ) { size += firstCodeAttribute . computeAttributesSize ( symbolTable , code . data , code . length , maxStack , maxLocals ) ; } } if ( numberOfExceptions > 0 ) { symbolTable . addConstantUtf8 ( Constants . EXCEPTIONS ) ; size += 8 + 2 * numberOfExceptions ; } boolean useSyntheticAttribute = symbolTable . getMajorVersion ( ) < Opcodes . V1_5 ; if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ; size += 6 ; } if ( signatureIndex != 0 ) { symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ; size += 8 ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ; size += 6 ; } if ( lastRuntimeVisibleAnnotation != null ) { size += lastRuntimeVisibleAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_ANNOTATIONS ) ; } if ( lastRuntimeInvisibleAnnotation != null ) { size += lastRuntimeInvisibleAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS ) ; } if ( lastRuntimeVisibleParameterAnnotations != null ) { size += AnnotationWriter . computeParameterAnnotationsSize ( Constants . RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS , lastRuntimeVisibleParameterAnnotations , visibleAnnotableParameterCount == 0 ? lastRuntimeVisibleParameterAnnotations . length : visibleAnnotableParameterCount ) ; } if ( lastRuntimeInvisibleParameterAnnotations != null ) { size += AnnotationWriter . computeParameterAnnotationsSize ( Constants . RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS , lastRuntimeInvisibleParameterAnnotations , invisibleAnnotableParameterCount == 0 ? lastRuntimeInvisibleParameterAnnotations . length : invisibleAnnotableParameterCount ) ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { size += lastRuntimeVisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { size += lastRuntimeInvisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) ; } if ( defaultValue != null ) { symbolTable . addConstantUtf8 ( Constants . ANNOTATION_DEFAULT ) ; size += 6 + defaultValue . length ; } if ( parameters != null ) { symbolTable . addConstantUtf8 ( Constants . METHOD_PARAMETERS ) ; // 6 header bytes and 1 byte for parameters_count. size += 7 + parameters . length ; } if ( firstAttribute != null ) { size += firstAttribute . computeAttributesSize ( symbolTable ) ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the content of the method_info JVMS structure generated by this MethodWriter into the given ByteVector . [CODESPLIT] void putMethodInfo ( final ByteVector output ) { boolean useSyntheticAttribute = symbolTable . getMajorVersion ( ) < Opcodes . V1_5 ; int mask = useSyntheticAttribute ? Opcodes . ACC_SYNTHETIC : 0 ; output . putShort ( accessFlags & ~ mask ) . putShort ( nameIndex ) . putShort ( descriptorIndex ) ; // If this method_info must be copied from an existing one, copy it now and return early. if ( sourceOffset != 0 ) { output . putByteArray ( symbolTable . getSource ( ) . b , sourceOffset , sourceLength ) ; return ; } // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. int attributeCount = 0 ; if ( code . length > 0 ) { ++ attributeCount ; } if ( numberOfExceptions > 0 ) { ++ attributeCount ; } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { ++ attributeCount ; } if ( signatureIndex != 0 ) { ++ attributeCount ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { ++ attributeCount ; } if ( lastRuntimeVisibleAnnotation != null ) { ++ attributeCount ; } if ( lastRuntimeInvisibleAnnotation != null ) { ++ attributeCount ; } if ( lastRuntimeVisibleParameterAnnotations != null ) { ++ attributeCount ; } if ( lastRuntimeInvisibleParameterAnnotations != null ) { ++ attributeCount ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { ++ attributeCount ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { ++ attributeCount ; } if ( defaultValue != null ) { ++ attributeCount ; } if ( parameters != null ) { ++ attributeCount ; } if ( firstAttribute != null ) { attributeCount += firstAttribute . getAttributeCount ( ) ; } // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. output . putShort ( attributeCount ) ; if ( code . length > 0 ) { // 2, 2, 4 and 2 bytes respectively for max_stack, max_locals, code_length and // attributes_count, plus the bytecode and the exception table. int size = 10 + code . length + Handler . getExceptionTableSize ( firstHandler ) ; int codeAttributeCount = 0 ; if ( stackMapTableEntries != null ) { // 6 header bytes and 2 bytes for number_of_entries. size += 8 + stackMapTableEntries . length ; ++ codeAttributeCount ; } if ( lineNumberTable != null ) { // 6 header bytes and 2 bytes for line_number_table_length. size += 8 + lineNumberTable . length ; ++ codeAttributeCount ; } if ( localVariableTable != null ) { // 6 header bytes and 2 bytes for local_variable_table_length. size += 8 + localVariableTable . length ; ++ codeAttributeCount ; } if ( localVariableTypeTable != null ) { // 6 header bytes and 2 bytes for local_variable_type_table_length. size += 8 + localVariableTypeTable . length ; ++ codeAttributeCount ; } if ( lastCodeRuntimeVisibleTypeAnnotation != null ) { size += lastCodeRuntimeVisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) ; ++ codeAttributeCount ; } if ( lastCodeRuntimeInvisibleTypeAnnotation != null ) { size += lastCodeRuntimeInvisibleTypeAnnotation . computeAnnotationsSize ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) ; ++ codeAttributeCount ; } if ( firstCodeAttribute != null ) { size += firstCodeAttribute . computeAttributesSize ( symbolTable , code . data , code . length , maxStack , maxLocals ) ; codeAttributeCount += firstCodeAttribute . getAttributeCount ( ) ; } output . putShort ( symbolTable . addConstantUtf8 ( Constants . CODE ) ) . putInt ( size ) . putShort ( maxStack ) . putShort ( maxLocals ) . putInt ( code . length ) . putByteArray ( code . data , 0 , code . length ) ; Handler . putExceptionTable ( firstHandler , output ) ; output . putShort ( codeAttributeCount ) ; if ( stackMapTableEntries != null ) { boolean useStackMapTable = symbolTable . getMajorVersion ( ) >= Opcodes . V1_6 ; output . putShort ( symbolTable . addConstantUtf8 ( useStackMapTable ? Constants . STACK_MAP_TABLE : \"StackMap\" ) ) . putInt ( 2 + stackMapTableEntries . length ) . putShort ( stackMapTableNumberOfEntries ) . putByteArray ( stackMapTableEntries . data , 0 , stackMapTableEntries . length ) ; } if ( lineNumberTable != null ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . LINE_NUMBER_TABLE ) ) . putInt ( 2 + lineNumberTable . length ) . putShort ( lineNumberTableLength ) . putByteArray ( lineNumberTable . data , 0 , lineNumberTable . length ) ; } if ( localVariableTable != null ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . LOCAL_VARIABLE_TABLE ) ) . putInt ( 2 + localVariableTable . length ) . putShort ( localVariableTableLength ) . putByteArray ( localVariableTable . data , 0 , localVariableTable . length ) ; } if ( localVariableTypeTable != null ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . LOCAL_VARIABLE_TYPE_TABLE ) ) . putInt ( 2 + localVariableTypeTable . length ) . putShort ( localVariableTypeTableLength ) . putByteArray ( localVariableTypeTable . data , 0 , localVariableTypeTable . length ) ; } if ( lastCodeRuntimeVisibleTypeAnnotation != null ) { lastCodeRuntimeVisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) , output ) ; } if ( lastCodeRuntimeInvisibleTypeAnnotation != null ) { lastCodeRuntimeInvisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) , output ) ; } if ( firstCodeAttribute != null ) { firstCodeAttribute . putAttributes ( symbolTable , code . data , code . length , maxStack , maxLocals , output ) ; } } if ( numberOfExceptions > 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . EXCEPTIONS ) ) . putInt ( 2 + 2 * numberOfExceptions ) . putShort ( numberOfExceptions ) ; for ( int exceptionIndex : exceptionIndexTable ) { output . putShort ( exceptionIndex ) ; } } if ( ( accessFlags & Opcodes . ACC_SYNTHETIC ) != 0 && useSyntheticAttribute ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . SYNTHETIC ) ) . putInt ( 0 ) ; } if ( signatureIndex != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . SIGNATURE ) ) . putInt ( 2 ) . putShort ( signatureIndex ) ; } if ( ( accessFlags & Opcodes . ACC_DEPRECATED ) != 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . DEPRECATED ) ) . putInt ( 0 ) ; } if ( lastRuntimeVisibleAnnotation != null ) { lastRuntimeVisibleAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_ANNOTATIONS ) , output ) ; } if ( lastRuntimeInvisibleAnnotation != null ) { lastRuntimeInvisibleAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_ANNOTATIONS ) , output ) ; } if ( lastRuntimeVisibleParameterAnnotations != null ) { AnnotationWriter . putParameterAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS ) , lastRuntimeVisibleParameterAnnotations , visibleAnnotableParameterCount == 0 ? lastRuntimeVisibleParameterAnnotations . length : visibleAnnotableParameterCount , output ) ; } if ( lastRuntimeInvisibleParameterAnnotations != null ) { AnnotationWriter . putParameterAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS ) , lastRuntimeInvisibleParameterAnnotations , invisibleAnnotableParameterCount == 0 ? lastRuntimeInvisibleParameterAnnotations . length : invisibleAnnotableParameterCount , output ) ; } if ( lastRuntimeVisibleTypeAnnotation != null ) { lastRuntimeVisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_VISIBLE_TYPE_ANNOTATIONS ) , output ) ; } if ( lastRuntimeInvisibleTypeAnnotation != null ) { lastRuntimeInvisibleTypeAnnotation . putAnnotations ( symbolTable . addConstantUtf8 ( Constants . RUNTIME_INVISIBLE_TYPE_ANNOTATIONS ) , output ) ; } if ( defaultValue != null ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . ANNOTATION_DEFAULT ) ) . putInt ( defaultValue . length ) . putByteArray ( defaultValue . data , 0 , defaultValue . length ) ; } if ( parameters != null ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . METHOD_PARAMETERS ) ) . putInt ( 1 + parameters . length ) . putByte ( parametersCount ) . putByteArray ( parameters . data , 0 , parameters . length ) ; } if ( firstAttribute != null ) { firstAttribute . putAttributes ( symbolTable , output ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects the attributes of this method into the given set of attribute prototypes . [CODESPLIT] final void collectAttributePrototypes ( final Attribute . Set attributePrototypes ) { attributePrototypes . addAttributes ( firstAttribute ) ; attributePrototypes . addAttributes ( firstCodeAttribute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected WorkData process ( final ClassReader cr , final TargetClassInfoReader targetClassInfoReader ) { InvokeClassBuilder icb = new InvokeClassBuilder ( destClassWriter , proxetta . getAspects ( new InvokeAspect [ 0 ] ) , resolveClassNameSuffix ( ) , requestedProxyClassName , targetClassInfoReader ) ; cr . accept ( icb , 0 ) ; return icb . getWorkData ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject context into target . [CODESPLIT] public void injectContext ( final Object targetObject ) { final Class targetType = targetObject . getClass ( ) ; final ScopeData scopeData = scopeDataInspector . inspectClassScopesWithCache ( targetType ) ; final Targets targets = new Targets ( targetObject , scopeData ) ; // inject no context scopeResolver . forEachScope ( madvocScope -> madvocScope . inject ( targets ) ) ; // inject special case scopeResolver . forScope ( ParamsScope . class , scope -> scope . inject ( targets ) ) ; // inject servlet context final ServletContext servletContext = madvocController . getApplicationContext ( ) ; if ( servletContext != null ) { scopeResolver . forEachScope ( madvocScope -> madvocScope . inject ( servletContext , targets ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses selector string . Returns <code > null< / code > if no selector can be parsed . [CODESPLIT] public List < CssSelector > parse ( ) { try { lexer . yylex ( ) ; if ( lexer . selectors . isEmpty ( ) ) { return null ; } // fixes last combinator CssSelector last = lexer . selectors . get ( lexer . selectors . size ( ) - 1 ) ; if ( last . getCombinator ( ) == Combinator . DESCENDANT ) { last . setCombinator ( null ) ; } // set previous css selector CssSelector prevCssSelector = null ; for ( CssSelector cssSelector : lexer . selectors ) { if ( prevCssSelector != null ) { cssSelector . setPrevCssSelector ( prevCssSelector ) ; } prevCssSelector = cssSelector ; } return lexer . selectors ; } catch ( IOException ioex ) { throw new CSSellyException ( ioex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses string of selectors ( separated with <b > < / b > ) . Returns list of { [CODESPLIT] public static List < List < CssSelector > > parse ( final String query ) { String [ ] singleQueries = StringUtil . splitc ( query , ' ' ) ; List < List < CssSelector > > selectors = new ArrayList <> ( singleQueries . length ) ; for ( String singleQuery : singleQueries ) { selectors . add ( new CSSelly ( singleQuery ) . parse ( ) ) ; } return selectors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers pseudo class . [CODESPLIT] public static void registerPseudoClass ( final Class < ? extends PseudoClass > pseudoClassType ) { PseudoClass pseudoClass ; try { pseudoClass = ClassUtil . newInstance ( pseudoClassType ) ; } catch ( Exception ex ) { throw new CSSellyException ( ex ) ; } PSEUDO_CLASS_MAP . put ( pseudoClass . getPseudoClassName ( ) , pseudoClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups pseudo class for given pseudo class name . [CODESPLIT] public static PseudoClass lookupPseudoClass ( final String pseudoClassName ) { PseudoClass pseudoClass = PSEUDO_CLASS_MAP . get ( pseudoClassName ) ; if ( pseudoClass == null ) { throw new CSSellyException ( \"Unsupported pseudo class: \" + pseudoClassName ) ; } return pseudoClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accepts node within selected results . Invoked after results are matched . [CODESPLIT] @ Override public boolean accept ( final List < Node > currentResults , final Node node , final int index ) { return pseudoClass . match ( currentResults , node , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes an action asynchronously by submitting it to the thread pool . [CODESPLIT] public void invoke ( final ActionRequest actionRequest ) { if ( executorService == null ) { throw new MadvocException ( \"No action is marked as async!\" ) ; } final HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; log . debug ( ( ) -> \"Async call to: \" + actionRequest ) ; final AsyncContext asyncContext = servletRequest . startAsync ( ) ; executorService . submit ( ( ) -> { try { actionRequest . invoke ( ) ; } catch ( Exception ex ) { log . error ( \"Invoking async action path failed: \" , ExceptionUtil . unwrapThrowable ( ex ) ) ; } finally { asyncContext . complete ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes silently the closable object . If it is { [CODESPLIT] public static void close ( final Closeable closeable ) { if ( closeable != null ) { if ( closeable instanceof Flushable ) { try { ( ( Flushable ) closeable ) . flush ( ) ; } catch ( IOException ignored ) { } } try { closeable . close ( ) ; } catch ( IOException ignored ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies specified number of characters from { @link Reader } to { @link Writer } using buffer . { @link Reader } and { @link Writer } don t have to be wrapped to buffered since copying is already optimized . [CODESPLIT] public static int copy ( final Reader input , final Writer output , final int count ) throws IOException { if ( count == ALL ) { return copy ( input , output ) ; } int numToRead = count ; char [ ] buffer = new char [ numToRead ] ; int totalRead = ZERO ; int read ; while ( numToRead > ZERO ) { read = input . read ( buffer , ZERO , bufferSize ( numToRead ) ) ; if ( read == NEGATIVE_ONE ) { break ; } output . write ( buffer , ZERO , read ) ; numToRead = numToRead - read ; totalRead = totalRead + read ; } output . flush ( ) ; return totalRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies specified number of bytes from { @link InputStream } to { @link OutputStream } using buffer . { @link InputStream } and { @link OutputStream } don t have to be wrapped to buffered since copying is already optimized . [CODESPLIT] public static int copy ( final InputStream input , final OutputStream output , final int count ) throws IOException { if ( count == ALL ) { return copy ( input , output ) ; } int numToRead = count ; byte [ ] buffer = new byte [ numToRead ] ; int totalRead = ZERO ; int read ; while ( numToRead > ZERO ) { read = input . read ( buffer , ZERO , bufferSize ( numToRead ) ) ; if ( read == NEGATIVE_ONE ) { break ; } output . write ( buffer , ZERO , read ) ; numToRead = numToRead - read ; totalRead = totalRead + read ; } output . flush ( ) ; return totalRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all available bytes from { @link InputStream } as a byte array . Uses { @link InputStream#available () } to determine the size of input stream . This is the fastest method for reading { @link InputStream } to byte array but depends on { @link InputStream } implementation of { @link InputStream#available () } . [CODESPLIT] public static byte [ ] readAvailableBytes ( final InputStream input ) throws IOException { int numToRead = input . available ( ) ; byte [ ] buffer = new byte [ numToRead ] ; int totalRead = ZERO ; int read ; while ( ( totalRead < numToRead ) && ( read = input . read ( buffer , totalRead , numToRead - totalRead ) ) >= ZERO ) { totalRead = totalRead + read ; } if ( totalRead < numToRead ) { throw new IOException ( \"Failed to completely read InputStream\" ) ; } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies { @link Reader } to { @link OutputStream } using buffer and specified encoding . [CODESPLIT] public static < T extends OutputStream > T copy ( final Reader input , final T output , final String encoding , final int count ) throws IOException { try ( Writer out = outputStreamWriterOf ( output , encoding ) ) { copy ( input , out , count ) ; return output ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies { @link InputStream } to a new { @link FastByteArrayOutputStream } using buffer and specified encoding . [CODESPLIT] public static FastByteArrayOutputStream copyToOutputStream ( final InputStream input , final int count ) throws IOException { try ( FastByteArrayOutputStream output = createFastByteArrayOutputStream ( ) ) { copy ( input , output , count ) ; return output ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies { @link Reader } to a new { @link FastByteArrayOutputStream } using buffer and specified encoding . [CODESPLIT] public static FastByteArrayOutputStream copyToOutputStream ( final Reader input , final String encoding , final int count ) throws IOException { try ( FastByteArrayOutputStream output = createFastByteArrayOutputStream ( ) ) { copy ( input , output , encoding , count ) ; return output ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies { @link InputStream } to a new { @link FastCharArrayWriter } using buffer and specified encoding . [CODESPLIT] public static FastCharArrayWriter copy ( final InputStream input , final String encoding , final int count ) throws IOException { try ( FastCharArrayWriter output = createFastCharArrayWriter ( ) ) { copy ( input , output , encoding , count ) ; return output ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies { @link Reader } to a new { @link FastCharArrayWriter } using buffer and specified encoding . [CODESPLIT] public static FastCharArrayWriter copy ( final Reader input , final int count ) throws IOException { try ( FastCharArrayWriter output = createFastCharArrayWriter ( ) ) { copy ( input , output , count ) ; return output ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns new { @link InputStreamReader } using specified { @link InputStream } and encoding . [CODESPLIT] public static InputStreamReader inputStreamReadeOf ( final InputStream input , final String encoding ) throws UnsupportedEncodingException { return new InputStreamReader ( input , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns new { @link OutputStreamWriter } using specified { @link OutputStream } and encoding . [CODESPLIT] public static OutputStreamWriter outputStreamWriterOf ( final OutputStream output , final String encoding ) throws UnsupportedEncodingException { return new OutputStreamWriter ( output , encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all bean property names . [CODESPLIT] protected String [ ] getAllBeanPropertyNames ( final Class type , final boolean declared ) { ClassDescriptor classDescriptor = ClassIntrospector . get ( ) . lookup ( type ) ; PropertyDescriptor [ ] propertyDescriptors = classDescriptor . getAllPropertyDescriptors ( ) ; ArrayList < String > names = new ArrayList <> ( propertyDescriptors . length ) ; for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { MethodDescriptor getter = propertyDescriptor . getReadMethodDescriptor ( ) ; if ( getter != null ) { if ( getter . matchDeclared ( declared ) ) { names . add ( propertyDescriptor . getName ( ) ) ; } } else if ( includeFields ) { FieldDescriptor field = propertyDescriptor . getFieldDescriptor ( ) ; if ( field != null ) { if ( field . matchDeclared ( declared ) ) { names . add ( field . getName ( ) ) ; } } } } return names . toArray ( new String [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of bean properties . If bean is a <code > Map< / code > all its keys will be returned . [CODESPLIT] protected String [ ] resolveProperties ( final Object bean , final boolean declared ) { String [ ] properties ; if ( bean instanceof Map ) { Set keys = ( ( Map ) bean ) . keySet ( ) ; properties = new String [ keys . size ( ) ] ; int ndx = 0 ; for ( Object key : keys ) { properties [ ndx ] = key . toString ( ) ; ndx ++ ; } } else { properties = getAllBeanPropertyNames ( bean . getClass ( ) , declared ) ; } return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts visiting properties . [CODESPLIT] public void visit ( ) { String [ ] properties = resolveProperties ( source , declared ) ; for ( String name : properties ) { if ( name == null ) { continue ; } if ( ! rules . match ( name , blacklist ) ) { continue ; } Object value ; String propertyName = name ; if ( isSourceMap ) { propertyName = LEFT_SQ_BRACKET + name + RIGHT_SQ_BRACKET ; } if ( declared ) { value = BeanUtil . declared . getProperty ( source , propertyName ) ; } else { value = BeanUtil . pojo . getProperty ( source , propertyName ) ; } if ( value == null && ignoreNullValues ) { continue ; } if ( value instanceof String && StringUtil . isEmpty ( ( String ) value ) ) { continue ; } visitProperty ( name , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares property name to the rules . [CODESPLIT] @ Override public boolean accept ( final String propertyName , final String rule , final boolean include ) { return propertyName . equals ( rule ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public ClassDescriptor lookup ( final Class type ) { return cache . get ( type , ( ) -> new ClassDescriptor ( type , scanAccessible , enhancedProperties , includeFieldsAsProperties , propertyFieldPrefix ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve method injection points in given class . [CODESPLIT] public MethodInjectionPoint [ ] resolve ( final Class type ) { // lookup methods ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; List < MethodInjectionPoint > list = new ArrayList <> ( ) ; MethodDescriptor [ ] allMethods = cd . getAllMethodDescriptors ( ) ; for ( MethodDescriptor methodDescriptor : allMethods ) { Method method = methodDescriptor . getMethod ( ) ; if ( ClassUtil . isBeanPropertySetter ( method ) ) { // ignore setters continue ; } if ( method . getParameterTypes ( ) . length == 0 ) { // ignore methods with no argument continue ; } BeanReferences [ ] references = referencesResolver . readAllReferencesFromAnnotation ( method ) ; if ( references != null ) { MethodInjectionPoint methodInjectionPoint = new MethodInjectionPoint ( method , references ) ; list . add ( methodInjectionPoint ) ; } } final MethodInjectionPoint [ ] methodInjectionPoints ; if ( list . isEmpty ( ) ) { methodInjectionPoints = MethodInjectionPoint . EMPTY ; } else { methodInjectionPoints = list . toArray ( new MethodInjectionPoint [ 0 ] ) ; } return methodInjectionPoints ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads filter config parameters and set into destination target . [CODESPLIT] protected void readFilterConfigParameters ( final FilterConfig filterConfig , final Object target , final String ... parameters ) { for ( String parameter : parameters ) { String value = filterConfig . getInitParameter ( parameter ) ; if ( value != null ) { BeanUtil . declared . setProperty ( target , parameter , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] protected HtmlStaplerBundlesManager createBundleManager ( final ServletContext servletContext , final Strategy strategy ) { String webRoot = servletContext . getRealPath ( StringPool . EMPTY ) ; String contextPath = ServletUtil . getContextPath ( servletContext ) ; return new HtmlStaplerBundlesManager ( contextPath , webRoot , strategy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Outputs bundle file to the response . [CODESPLIT] protected void sendBundleFile ( final HttpServletResponse resp , final File bundleFile ) throws IOException { OutputStream out = resp . getOutputStream ( ) ; FileInputStream fileInputStream = new FileInputStream ( bundleFile ) ; try { StreamUtil . copy ( fileInputStream , out ) ; } finally { StreamUtil . close ( fileInputStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures { [CODESPLIT] public void configure ( ) { long elapsed = System . currentTimeMillis ( ) ; final ClassScanner classScanner = new ClassScanner ( ) ; classScanner . detectEntriesMode ( true ) ; classScanner . scanDefaultClasspath ( ) ; classScannerConsumers . accept ( classScanner ) ; registerAsConsumer ( classScanner ) ; try { classScanner . start ( ) ; } catch ( Exception ex ) { throw new DbOomException ( \"Scan classpath error\" , ex ) ; } elapsed = System . currentTimeMillis ( ) - elapsed ; if ( log . isInfoEnabled ( ) ) { log . info ( \"DbEntityManager configured in \" + elapsed + \"ms. Total entities: \" + dbEntityManager . getTotalNames ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a class consumer that registers only those annotated with { [CODESPLIT] public void registerAsConsumer ( final ClassScanner classScanner ) { classScanner . registerEntryConsumer ( classPathEntry -> { if ( ! classPathEntry . isTypeSignatureInUse ( DB_TABLE_ANNOTATION_BYTES ) ) { return ; } final Class < ? > beanClass ; try { beanClass = classPathEntry . loadClass ( ) ; } catch ( ClassNotFoundException cnfex ) { throw new DbOomException ( \"Entry class not found: \" + classPathEntry . name ( ) , cnfex ) ; } if ( beanClass == null ) { return ; } final DbTable dbTable = beanClass . getAnnotation ( DbTable . class ) ; if ( dbTable == null ) { return ; } if ( registerAsEntities ) { dbEntityManager . registerEntity ( beanClass ) ; } else { dbEntityManager . registerType ( beanClass ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the number of random characters that will be appended to the { [CODESPLIT] public void setRandomDigestChars ( final int randomDigestChars ) { this . randomDigestChars = randomDigestChars ; if ( randomDigestChars == 0 ) { uniqueDigestKey = null ; } else { uniqueDigestKey = new RandomString ( ) . randomAlphaNumeric ( randomDigestChars ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates bundle file in bundleFolder / staplerPath . Only file object is created not the file content . [CODESPLIT] protected File createBundleFile ( final String bundleId ) { File folder = new File ( bundleFolder , staplerPath ) ; if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } return new File ( folder , bundleId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for bundle file . [CODESPLIT] public File lookupBundleFile ( String bundleId ) { if ( ( mirrors != null ) && ( ! mirrors . isEmpty ( ) ) ) { String realBundleId = mirrors . remove ( bundleId ) ; if ( realBundleId != null ) { bundleId = realBundleId ; } } return createBundleFile ( bundleId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates gzipped version of bundle file . If gzip file does not exist it will be created . [CODESPLIT] public File lookupGzipBundleFile ( final File file ) throws IOException { String path = file . getPath ( ) + ZipUtil . GZIP_EXT ; File gzipFile = new File ( path ) ; if ( ! gzipFile . exists ( ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"gzip bundle to \" + path ) ; } ZipUtil . gzip ( file ) ; } return gzipFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new bundle that consist of provided list of source paths . Returns the real bundle id as provided one is just a temporary bundle id . [CODESPLIT] public synchronized String registerBundle ( final String contextPath , final String actionPath , final String tempBundleId , final String bundleContentType , final List < String > sources ) { if ( tempBundleId == null || sources . isEmpty ( ) ) { if ( strategy == Strategy . ACTION_MANAGED ) { // page does not include any resource source file actionBundles . put ( actionPath , StringPool . EMPTY ) ; } return null ; } // create unique digest from the collected sources String [ ] sourcesArray = sources . toArray ( new String [ 0 ] ) ; for ( int i = 0 , sourcesArrayLength = sourcesArray . length ; i < sourcesArrayLength ; i ++ ) { sourcesArray [ i ] = sourcesArray [ i ] . trim ( ) . toLowerCase ( ) ; } if ( sortResources ) { Arrays . sort ( sourcesArray ) ; } StringBand sb = new StringBand ( sourcesArray . length ) ; for ( String src : sourcesArray ) { sb . append ( src ) ; } String sourcesString = sb . toString ( ) ; String bundleId = createDigest ( sourcesString ) ; bundleId += ' ' + bundleContentType ; // bundle appears for the first time, create the bundle if ( strategy == Strategy . ACTION_MANAGED ) { actionBundles . put ( actionPath , bundleId ) ; mirrors . put ( tempBundleId , bundleId ) ; } try { createBundle ( contextPath , actionPath , bundleId , sources ) ; } catch ( IOException ioex ) { throw new HtmlStaplerException ( \"Can't create bundle\" , ioex ) ; } return bundleId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates digest i . e . bundle id from given string . Returned digest must be filename safe for all platforms . [CODESPLIT] protected String createDigest ( final String source ) { final DigestEngine digestEngine = DigestEngine . sha256 ( ) ; final byte [ ] bytes = digestEngine . digest ( CharUtil . toSimpleByteArray ( source ) ) ; String digest = Base32 . encode ( bytes ) ; if ( uniqueDigestKey != null ) { digest += uniqueDigestKey ; } return digest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates bundle file by loading resource files content . If bundle file already exist it will not be recreated! [CODESPLIT] protected void createBundle ( final String contextPath , final String actionPath , final String bundleId , final List < String > sources ) throws IOException { final File bundleFile = createBundleFile ( bundleId ) ; if ( bundleFile . exists ( ) ) { return ; } StringBand sb = new StringBand ( sources . size ( ) * 2 ) ; for ( String src : sources ) { if ( sb . length ( ) != 0 ) { sb . append ( StringPool . NEWLINE ) ; } String content ; if ( isExternalResource ( src ) ) { content = downloadString ( src ) ; } else { if ( ! downloadLocal ) { // load local resource from file system String localFile = webRoot ; if ( src . startsWith ( contextPath + ' ' ) ) { src = src . substring ( contextPath . length ( ) ) ; } if ( src . startsWith ( StringPool . SLASH ) ) { // absolute path localFile += src ; } else { // relative path localFile += ' ' + FileNameUtil . getPathNoEndSeparator ( actionPath ) + ' ' + src ; } // trim link parameters, if any int qmndx = localFile . indexOf ( ' ' ) ; if ( qmndx != - 1 ) { localFile = localFile . substring ( 0 , qmndx ) ; } try { content = FileUtil . readString ( localFile ) ; } catch ( IOException ioex ) { if ( notFoundExceptionEnabled ) { throw ioex ; } if ( log . isWarnEnabled ( ) ) { log . warn ( ioex . getMessage ( ) ) ; } content = null ; } } else { // download local resource String localUrl = localAddressAndPort ; if ( src . startsWith ( StringPool . SLASH ) ) { localUrl += contextPath + src ; } else { localUrl += contextPath + FileNameUtil . getPath ( actionPath ) + ' ' + src ; } content = downloadString ( localUrl ) ; } if ( content != null ) { if ( isCssResource ( src ) ) { content = fixCssRelativeUrls ( content , src ) ; } } } if ( content != null ) { content = onResourceContent ( content ) ; sb . append ( content ) ; } } FileUtil . writeString ( bundleFile , sb . toString ( ) ) ; if ( log . isInfoEnabled ( ) ) { log . info ( \"Bundle created: \" + bundleId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears all settings and removes all created bundle files from file system . [CODESPLIT] public synchronized void reset ( ) { if ( strategy == Strategy . ACTION_MANAGED ) { actionBundles . clear ( ) ; mirrors . clear ( ) ; } final FindFile ff = new FindFile ( ) ; ff . includeDirs ( false ) ; ff . searchPath ( new File ( bundleFolder , staplerPath ) ) ; File f ; int count = 0 ; while ( ( f = ff . nextFile ( ) ) != null ) { f . delete ( ) ; count ++ ; } if ( log . isInfoEnabled ( ) ) { log . info ( \"reset: \" + count + \" bundle files deleted.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the content with all relative URLs fixed . [CODESPLIT] protected String fixCssRelativeUrls ( final String content , final String src ) { final String path = FileNameUtil . getPath ( src ) ; final Matcher matcher = CSS_URL_PATTERN . matcher ( content ) ; final StringBuilder sb = new StringBuilder ( content . length ( ) ) ; int start = 0 ; while ( matcher . find ( ) ) { sb . append ( content , start , matcher . start ( ) ) ; final String matchedUrl = StringUtil . removeChars ( matcher . group ( 1 ) , \"'\\\"\" ) ; final String url ; if ( matchedUrl . startsWith ( \"https://\" ) || matchedUrl . startsWith ( \"http://\" ) || matchedUrl . startsWith ( \"data:\" ) ) { url = \"url('\" + matchedUrl + \"')\" ; } else { url = fixRelativeUrl ( matchedUrl , path ) ; } sb . append ( url ) ; start = matcher . end ( ) ; } sb . append ( content . substring ( start ) ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given URL ( optionally quoted ) produces CSS URL where relative paths are fixed and prefixed with offsetPath . [CODESPLIT] protected String fixRelativeUrl ( final String url , final String offsetPath ) { final StringBuilder res = new StringBuilder ( ) ; res . append ( \"url('\" ) ; if ( ! url . startsWith ( StringPool . SLASH ) ) { res . append ( \"../\" ) . append ( offsetPath ) ; } res . append ( url ) . append ( \"')\" ) ; return res . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates UPDATE query that updates all non - null values of an entity that is matched by id . [CODESPLIT] public DbSqlBuilder update ( final Object entity ) { String tableRef = createTableRefName ( entity ) ; if ( ! dbOomConfig . isUpdateAcceptsTableAlias ( ) ) { tableRef = null ; } return sql ( ) . $ ( UPDATE ) . table ( entity , tableRef ) . set ( tableRef , entity ) . $ ( WHERE ) . matchIds ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates UPDATE query that updates all values of an entity that is matched by id . [CODESPLIT] public DbSqlBuilder updateAll ( final Object entity ) { String tableRef = createTableRefName ( entity ) ; if ( ! dbOomConfig . isUpdateAcceptsTableAlias ( ) ) { tableRef = null ; } return sql ( ) . $ ( UPDATE ) . table ( entity , tableRef ) . setAll ( tableRef , entity ) . $ ( WHERE ) . matchIds ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates UPDATE query for single column of an entity that is matched by id . [CODESPLIT] public DbSqlBuilder updateColumn ( final Object entity , final String columnRef , final Object value ) { String tableRef = createTableRefName ( entity ) ; if ( ! dbOomConfig . isUpdateAcceptsTableAlias ( ) ) { tableRef = null ; } return sql ( ) . $ ( UPDATE ) . table ( entity , tableRef ) . $ ( SET ) . ref ( null , columnRef ) . $ ( EQUALS ) . columnValue ( value ) . $ ( WHERE ) . matchIds ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads property value and updates the DB . [CODESPLIT] public DbSqlBuilder updateColumn ( final Object entity , final String columnRef ) { final Object value = BeanUtil . pojo . getProperty ( entity , columnRef ) ; return updateColumn ( entity , columnRef , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates DELETE query that deletes entity matched by non - null values . [CODESPLIT] public DbSqlBuilder delete ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( DELETE_FROM ) . table ( entity , null , tableRef ) . $ ( WHERE ) . match ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates DELETE query that deletes entity matched by all values . [CODESPLIT] public DbSqlBuilder deleteByAll ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( DELETE_FROM ) . table ( entity , null , tableRef ) . $ ( WHERE ) . matchAll ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates DELETE query that deletes entity by ID . [CODESPLIT] public DbSqlBuilder deleteById ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( DELETE_FROM ) . table ( entity , null , tableRef ) . $ ( WHERE ) . matchIds ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates DELETE query that deletes entity by ID . [CODESPLIT] public DbSqlBuilder deleteById ( final Object entityType , final Object id ) { final String tableRef = createTableRefName ( entityType ) ; return sql ( ) . $ ( DELETE_FROM ) . table ( entityType , null , tableRef ) . $ ( WHERE ) . refId ( tableRef ) . $ ( EQUALS ) . columnValue ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT criteria for the entity matched by non - null values . [CODESPLIT] public DbSqlBuilder find ( final Class target , final Object matchEntity ) { final String tableRef = createTableRefName ( target ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( target , tableRef ) . $ ( WHERE ) . match ( tableRef , matchEntity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT criteria for the entity matched by non - null values . [CODESPLIT] public DbSqlBuilder find ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( entity , tableRef ) . $ ( WHERE ) . match ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT criteria for the entity matched by all values . [CODESPLIT] public DbSqlBuilder findByAll ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( entity , tableRef ) . $ ( WHERE ) . matchAll ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT criteria for the entity matched by column name [CODESPLIT] public DbSqlBuilder findByColumn ( final Class entity , final String column , final Object value ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( entity , tableRef ) . $ ( WHERE ) . ref ( tableRef , column ) . $ ( EQUALS ) . columnValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT criteria for the entity matched by foreign key . Foreign key is created by concatenating foreign table name and column name . [CODESPLIT] public DbSqlBuilder findForeign ( final Class entity , final Object value ) { final String tableRef = createTableRefName ( entity ) ; final DbEntityDescriptor dedFk = entityManager . lookupType ( value . getClass ( ) ) ; final String tableName = dbOomConfig . getTableNames ( ) . convertTableNameToEntityName ( dedFk . getTableName ( ) ) ; final String columnName = dbOomConfig . getColumnNames ( ) . convertColumnNameToPropertyName ( dedFk . getIdColumnName ( ) ) ; final String fkColumn = uncapitalize ( tableName ) + capitalize ( columnName ) ; final Object idValue = BeanUtil . pojo . getProperty ( value , dedFk . getIdPropertyName ( ) ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( entity , tableRef ) . $ ( WHERE ) . ref ( tableRef , fkColumn ) . $ ( EQUALS ) . columnValue ( idValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all records for given type . [CODESPLIT] public DbSqlBuilder findAll ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( entity , tableRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT criteria for the entity matched by id . [CODESPLIT] public DbSqlBuilder findById ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( entity , tableRef ) . $ ( WHERE ) . matchIds ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT criteria for the entity matched by id . [CODESPLIT] public DbSqlBuilder findById ( final Object entityType , final Object id ) { final String tableRef = createTableRefName ( entityType ) ; return sql ( ) . $ ( SELECT ) . column ( tableRef ) . $ ( FROM ) . table ( entityType , tableRef ) . $ ( WHERE ) . refId ( tableRef ) . $ ( EQUALS ) . columnValue ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT COUNT criteria for the entity matched by non - null values . [CODESPLIT] public DbSqlBuilder count ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( SELECT_COUNT_1_FROM ) . table ( entity , tableRef ) . $ ( WHERE ) . match ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT COUNT all query . [CODESPLIT] public DbSqlBuilder count ( final Class entityType ) { final String tableRef = createTableRefName ( entityType ) ; return sql ( ) . $ ( SELECT_COUNT_1_FROM ) . table ( entityType , tableRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates SELECT COUNT criteria for the entity matched by all values . [CODESPLIT] public DbSqlBuilder countAll ( final Object entity ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( SELECT_COUNT_1_FROM ) . table ( entity , tableRef ) . $ ( WHERE ) . matchAll ( tableRef , entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates UPDATE that increases / decreases column by some delta value . [CODESPLIT] public DbSqlBuilder increaseColumn ( final Class entity , final Object id , final String columnRef , final Number delta , final boolean increase ) { final String tableRef = createTableRefName ( entity ) ; return sql ( ) . $ ( UPDATE ) . table ( entity , null , tableRef ) . $ ( SET ) . ref ( null , columnRef ) . $ ( EQUALS ) . ref ( null , columnRef ) . $ ( increase ? StringPool . PLUS : StringPool . DASH ) . columnValue ( delta ) . $ ( WHERE ) . refId ( tableRef ) . $ ( EQUALS ) . columnValue ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates table reference name from entity type . Always appends an underscore to reference name in order to circumvent SQL compatibility issues when entity class name equals to a reserved word . [CODESPLIT] protected static String createTableRefName ( final Object entity ) { Class type = entity . getClass ( ) ; type = ( type == Class . class ? ( Class ) entity : type ) ; return ( type . getSimpleName ( ) + ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns session from JTX transaction manager and started transaction . [CODESPLIT] @ Override public DbSession getDbSession ( ) { log . debug ( \"Requesting db TX manager session\" ) ; final DbJtxTransaction jtx = ( DbJtxTransaction ) jtxTxManager . getTransaction ( ) ; if ( jtx == null ) { throw new DbSqlException ( \"No transaction is in progress and DbSession can't be provided. \" + \"It seems that transaction manager is not used to begin a transaction.\" ) ; } return jtx . requestResource ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves method name of method reference . Argument is used so { [CODESPLIT] public String ref ( final Object dummy ) { if ( dummy != null ) { if ( dummy instanceof String ) { return ( String ) dummy ; } throw new MethrefException ( \"Target method not collected\" ) ; } return ref ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns name of method reference . Target { [CODESPLIT] public String ref ( ) { if ( instance == null ) { return null ; } try { Field f = instance . getClass ( ) . getDeclaredField ( \"$__methodName$0\" ) ; f . setAccessible ( true ) ; Object name = f . get ( instance ) ; if ( name == null ) { throw new MethrefException ( \"Target method not collected\" ) ; } return name . toString ( ) ; } catch ( Exception ex ) { if ( ex instanceof MethrefException ) { throw ( ( MethrefException ) ex ) ; } throw new MethrefException ( \"Methref field not found\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers actions and applies proxetta on actions that are not already registered . We need to define { [CODESPLIT] @ Override public synchronized ActionRuntime registerAction ( Class actionClass , final Method actionMethod , ActionDefinition actionDefinition ) { if ( proxettaSupplier == null ) { return super . registerAction ( actionClass , actionMethod , actionDefinition ) ; } if ( actionDefinition == null ) { actionDefinition = actionMethodParser . parseActionDefinition ( actionClass , actionMethod ) ; } // create proxy for action class if not already created Class existing = proxyActionClasses . get ( actionClass ) ; if ( existing == null ) { final Proxetta proxetta = proxettaSupplier . get ( ) ; existing = proxetta . proxy ( ) . setTarget ( actionClass ) . define ( ) ; proxyActionClasses . put ( actionClass , existing ) ; } actionClass = existing ; return super . registerAction ( actionClass , actionMethod , actionDefinition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an array with single element . [CODESPLIT] protected T [ ] convertToSingleElementArray ( final Object value ) { T [ ] singleElementArray = createArray ( 1 ) ; singleElementArray [ 0 ] = convertType ( value ) ; return singleElementArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various collection types and iterates them to make conversion and to create target array . [CODESPLIT] protected T [ ] convertValueToArray ( final Object value ) { if ( value instanceof Collection ) { Collection collection = ( Collection ) value ; T [ ] target = createArray ( collection . size ( ) ) ; int i = 0 ; for ( Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { Iterable iterable = ( Iterable ) value ; List < T > list = new ArrayList <> ( ) ; for ( Object element : iterable ) { list . add ( convertType ( element ) ) ; } T [ ] target = createArray ( list . size ( ) ) ; return list . toArray ( target ) ; } if ( value instanceof CharSequence ) { String [ ] strings = convertStringToArray ( value . toString ( ) ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts primitive array to target array . [CODESPLIT] @ SuppressWarnings ( \"AutoBoxing\" ) protected T [ ] convertPrimitiveArrayToArray ( final Object value , final Class primitiveComponentType ) { T [ ] result = null ; if ( primitiveComponentType == int . class ) { int [ ] array = ( int [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } else if ( primitiveComponentType == long . class ) { long [ ] array = ( long [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } else if ( primitiveComponentType == float . class ) { float [ ] array = ( float [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } else if ( primitiveComponentType == double . class ) { double [ ] array = ( double [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } else if ( primitiveComponentType == short . class ) { short [ ] array = ( short [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } else if ( primitiveComponentType == byte . class ) { byte [ ] array = ( byte [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } else if ( primitiveComponentType == char . class ) { char [ ] array = ( char [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } else if ( primitiveComponentType == boolean . class ) { boolean [ ] array = ( boolean [ ] ) value ; result = createArray ( array . length ) ; for ( int i = 0 ; i < array . length ; i ++ ) { result [ i ] = convertType ( array [ i ] ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses signature for generic information and returns a map where key is generic name and value is raw type . Returns an empty map if signature does not define any generics . [CODESPLIT] public Map < String , String > parseSignatureForGenerics ( final String signature , final boolean isInterface ) { if ( signature == null ) { return Collections . emptyMap ( ) ; } final Map < String , String > genericsMap = new HashMap <> ( ) ; SignatureReader sr = new SignatureReader ( signature ) ; StringBuilder sb = new StringBuilder ( ) ; TraceSignatureVisitor v = new TraceSignatureVisitor ( sb , isInterface ) { String genericName ; @ Override public void visitFormalTypeParameter ( final String name ) { genericName = name ; super . visitFormalTypeParameter ( name ) ; } @ Override public void visitClassType ( final String name ) { if ( genericName != null ) { genericsMap . put ( genericName , ' ' + name + ' ' ) ; genericName = null ; } super . visitClassType ( name ) ; } } ; sr . accept ( v ) ; return genericsMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves all collections for given type . [CODESPLIT] public SetInjectionPoint [ ] resolve ( final Class type , final boolean autowire ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; List < SetInjectionPoint > list = new ArrayList <> ( ) ; PropertyDescriptor [ ] allProperties = cd . getAllPropertyDescriptors ( ) ; for ( PropertyDescriptor propertyDescriptor : allProperties ) { if ( propertyDescriptor . isGetterOnly ( ) ) { continue ; } Class propertyType = propertyDescriptor . getType ( ) ; if ( ! ClassUtil . isTypeOf ( propertyType , Collection . class ) ) { continue ; } MethodDescriptor writeMethodDescriptor = propertyDescriptor . getWriteMethodDescriptor ( ) ; FieldDescriptor fieldDescriptor = propertyDescriptor . getFieldDescriptor ( ) ; PetiteInject ref = null ; if ( writeMethodDescriptor != null ) { ref = writeMethodDescriptor . getMethod ( ) . getAnnotation ( PetiteInject . class ) ; } if ( ref == null && fieldDescriptor != null ) { ref = fieldDescriptor . getField ( ) . getAnnotation ( PetiteInject . class ) ; } if ( ( ! autowire ) && ( ref == null ) ) { continue ; } list . add ( new SetInjectionPoint ( propertyDescriptor ) ) ; } SetInjectionPoint [ ] fields ; if ( list . isEmpty ( ) ) { fields = SetInjectionPoint . EMPTY ; } else { fields = list . toArray ( new SetInjectionPoint [ 0 ] ) ; } return fields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if object has been already processed during the serialization . Used to prevent circular dependencies . Objects are matched by identity . [CODESPLIT] public boolean pushValue ( final Object value ) { for ( int i = 0 ; i < bagSize ; i ++ ) { JsonValueContext valueContext = bag . get ( i ) ; if ( valueContext . getValue ( ) == value ) { return true ; } } if ( bagSize == bag . size ( ) ) { lastValueContext = new JsonValueContext ( value ) ; bag . add ( lastValueContext ) ; } else { lastValueContext = bag . get ( bagSize ) ; lastValueContext . reuse ( value ) ; } bagSize ++ ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void pushName ( final String name , final boolean withComma ) { JsonValueContext valueContext = peekValueContext ( ) ; if ( valueContext != null ) { valueContext . setPropertyName ( name ) ; } super . pushName ( name , withComma ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeComma ( ) { JsonValueContext valueContext = peekValueContext ( ) ; if ( valueContext != null ) { valueContext . incrementIndex ( ) ; } super . writeComma ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes the object using { [CODESPLIT] public boolean serialize ( final Object object ) { if ( object == null ) { write ( NULL ) ; return true ; } TypeJsonSerializer typeJsonSerializer = null ; // callback if ( serializerResolver != null ) { typeJsonSerializer = serializerResolver . apply ( object ) ; } if ( typeJsonSerializer == null ) { // + read paths map if ( jsonSerializer . pathSerializersMap != null ) { typeJsonSerializer = jsonSerializer . pathSerializersMap . get ( path ) ; } final Class type = object . getClass ( ) ; // + read local types map if ( jsonSerializer . typeSerializersMap != null ) { typeJsonSerializer = jsonSerializer . typeSerializersMap . lookup ( type ) ; } // + globals if ( typeJsonSerializer == null ) { typeJsonSerializer = TypeJsonSerializerMap . get ( ) . lookup ( type ) ; } } return typeJsonSerializer . serialize ( this , object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches property types that are ignored by default . [CODESPLIT] public boolean matchIgnoredPropertyTypes ( final Class propertyType , final boolean excludeMaps , final boolean include ) { if ( ! include ) { return false ; } if ( propertyType != null ) { if ( ! jsonSerializer . deep ) { ClassDescriptor propertyTypeClassDescriptor = ClassIntrospector . get ( ) . lookup ( propertyType ) ; if ( propertyTypeClassDescriptor . isArray ( ) ) { return false ; } if ( propertyTypeClassDescriptor . isCollection ( ) ) { return false ; } if ( excludeMaps ) { if ( propertyTypeClassDescriptor . isMap ( ) ) { return false ; } } } // still not excluded, continue with excluded types and type names // + excluded types if ( jsonSerializer . excludedTypes != null ) { for ( Class excludedType : jsonSerializer . excludedTypes ) { if ( ClassUtil . isTypeOf ( propertyType , excludedType ) ) { return false ; } } } // + exclude type names final String propertyTypeName = propertyType . getName ( ) ; if ( jsonSerializer . excludedTypeNames != null ) { for ( String excludedTypeName : jsonSerializer . excludedTypeNames ) { if ( Wildcard . match ( propertyTypeName , excludedTypeName ) ) { return false ; } } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes current session and all allocated resources . All attached queries are closed . If a transaction is still active exception occurs . Database connection is returned to the { [CODESPLIT] public void closeSession ( ) { log . debug ( \"Closing db session\" ) ; SQLException sqlException = null ; if ( queries != null ) { for ( DbQueryBase query : queries ) { SQLException sex = query . closeQuery ( ) ; if ( sex != null ) { if ( sqlException == null ) { sqlException = sex ; } else { sqlException . setNextException ( sex ) ; } } } } if ( connection != null ) { if ( txActive ) { throw new DbSqlException ( \"TX was not closed before closing the session\" ) ; } connectionProvider . closeConnection ( connection ) ; connection = null ; } queries = null ; if ( sqlException != null ) { throw new DbSqlException ( \"Closing DbSession failed\" , sqlException ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens connection in auto - commit mode if already not opened . [CODESPLIT] protected void openConnectionForQuery ( ) { if ( connection == null ) { connection = connectionProvider . getConnection ( ) ; txActive = false ; // txAction should already be false try { connection . setAutoCommit ( true ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"Failed to open non-TX connection\" , sex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a transaction . [CODESPLIT] protected void openTx ( ) { if ( connection == null ) { connection = connectionProvider . getConnection ( ) ; } txActive = true ; try { connection . setAutoCommit ( false ) ; if ( txMode . getIsolation ( ) != DbTransactionMode . ISOLATION_DEFAULT ) { connection . setTransactionIsolation ( txMode . getIsolation ( ) ) ; } connection . setReadOnly ( txMode . isReadOnly ( ) ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"Open TX failed\" , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes current transaction . [CODESPLIT] protected void closeTx ( ) { txActive = false ; try { connection . setAutoCommit ( true ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"Close TX failed\" , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commit the current transaction writing any unflushed changes to the database . Transaction mode is closed . [CODESPLIT] public void commitTransaction ( ) { log . debug ( \"Committing transaction\" ) ; assertTxIsActive ( ) ; try { connection . commit ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"Commit TX failed\" , sex ) ; } finally { closeTx ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Roll back the current transaction . Transaction mode is closed . [CODESPLIT] public void rollbackTransaction ( ) { log . debug ( \"Rolling-back transaction\" ) ; assertTxIsActive ( ) ; try { connection . rollback ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"Rollback TX failed\" , sex ) ; } finally { closeTx ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces action path macros in the path . If one of the provided paths is <code > null< / code > it will not be replaced - so to emphasize the problem . [CODESPLIT] protected String replaceActionNameMacros ( String path , final ActionNames actionNames ) { final String packageName = actionNames . packageName ( ) ; final String className = actionNames . className ( ) ; final String methodName = actionNames . methodName ( ) ; final String httpMethod = actionNames . httpMethod ( ) ; if ( packageName != null ) { path = StringUtil . replace ( path , PACKAGE_MACRO , packageName ) ; } if ( className != null ) { path = StringUtil . replace ( path , CLASS_MACRO , className ) ; } if ( methodName != null ) { path = StringUtil . replace ( path , METHOD_MACRO , methodName ) ; } if ( httpMethod != null ) { path = StringUtil . replace ( path , HTTPMETHOD_MACRO , httpMethod ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Single point of { [CODESPLIT] protected ActionDefinition createActionDef ( String path , String httpMethod , String resultBasePath , final ActionNames actionNames ) { path = replaceActionNameMacros ( path , actionNames ) ; if ( httpMethod != null ) { httpMethod = replaceActionNameMacros ( httpMethod , actionNames ) ; } if ( resultBasePath != null ) { resultBasePath = replaceActionNameMacros ( resultBasePath , actionNames ) ; } return new ActionDefinition ( path , httpMethod , resultBasePath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] protected boolean isAbsolutePath ( final String path ) { if ( path == null ) { return false ; } return path . startsWith ( StringPool . SLASH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create properties from the file . [CODESPLIT] public static Properties createFromFile ( final File file ) throws IOException { Properties prop = new Properties ( ) ; loadFromFile ( prop , file ) ; return prop ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties from the file . Properties are appended to the existing properties object . [CODESPLIT] public static void loadFromFile ( final Properties p , final String fileName ) throws IOException { loadFromFile ( p , new File ( fileName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties from the file . Properties are appended to the existing properties object . [CODESPLIT] public static void loadFromFile ( final Properties p , final File file ) throws IOException { FileInputStream fis = null ; try { fis = new FileInputStream ( file ) ; p . load ( fis ) ; } finally { StreamUtil . close ( fis ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes properties to a file . [CODESPLIT] public static void writeToFile ( final Properties p , final String fileName ) throws IOException { writeToFile ( p , new File ( fileName ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes properties to a file . [CODESPLIT] public static void writeToFile ( final Properties p , final String fileName , final String header ) throws IOException { writeToFile ( p , new File ( fileName ) , header ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes properties to a file . [CODESPLIT] public static void writeToFile ( final Properties p , final File file ) throws IOException { writeToFile ( p , file , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes properties to a file . [CODESPLIT] public static void writeToFile ( final Properties p , final File file , final String header ) throws IOException { FileOutputStream fos = null ; try { fos = new FileOutputStream ( file ) ; p . store ( fos , header ) ; } finally { StreamUtil . close ( fos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates properties from string . [CODESPLIT] public static Properties createFromString ( final String data ) throws IOException { Properties p = new Properties ( ) ; loadFromString ( p , data ) ; return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties from string . [CODESPLIT] public static void loadFromString ( final Properties p , final String data ) throws IOException { try ( ByteArrayInputStream is = new ByteArrayInputStream ( data . getBytes ( StringPool . ISO_8859_1 ) ) ) { p . load ( is ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Properties object from the original one by copying those properties that have specified first part of the key name . Prefix may be optionally stripped during this process . [CODESPLIT] public static Properties subset ( final Properties p , String prefix , final boolean stripPrefix ) { if ( StringUtil . isBlank ( prefix ) ) { return p ; } if ( ! prefix . endsWith ( StringPool . DOT ) ) { prefix += ' ' ; } Properties result = new Properties ( ) ; int baseLen = prefix . length ( ) ; for ( Object o : p . keySet ( ) ) { String key = ( String ) o ; if ( key . startsWith ( prefix ) ) { result . setProperty ( stripPrefix ? key . substring ( baseLen ) : key , p . getProperty ( key ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates properties from classpath . [CODESPLIT] public static Properties createFromClasspath ( final String ... rootTemplate ) { Properties p = new Properties ( ) ; return loadFromClasspath ( p , rootTemplate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties from classpath file ( s ) . Properties are specified using wildcards . [CODESPLIT] public static Properties loadFromClasspath ( final Properties p , final String ... rootTemplate ) { ClassScanner . create ( ) . registerEntryConsumer ( entryData -> UncheckedException . runAndWrapException ( ( ) -> p . load ( entryData . openInputStream ( ) ) ) ) . includeResources ( true ) . ignoreException ( true ) . excludeAllEntries ( true ) . includeEntries ( rootTemplate ) . scanDefaultClasspath ( ) ; return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns String property from a map . If key is not found or if value is not a String returns <code > null< / code > . Mimics <code > Property . getProperty< / code > but on map . [CODESPLIT] public static String getProperty ( final Map map , final String key ) { return getProperty ( map , key , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns String property from a map . [CODESPLIT] public static String getProperty ( final Map map , final String key , final String defaultValue ) { Object val = map . get ( key ) ; return ( val instanceof String ) ? ( String ) val : defaultValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves all variables . [CODESPLIT] public static void resolveAllVariables ( final Properties prop ) { for ( Object o : prop . keySet ( ) ) { String key = ( String ) o ; String value = resolveProperty ( prop , key ) ; prop . setProperty ( key , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns property with resolved variables . [CODESPLIT] public static String resolveProperty ( final Map map , final String key ) { String value = getProperty ( map , key ) ; if ( value == null ) { return null ; } value = stp . parse ( value , macroName -> getProperty ( map , macroName ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves tx scope from scope pattern . [CODESPLIT] public String resolveScope ( final Class type , final String methodName ) { if ( scopePattern == null ) { return null ; } String ctx = scopePattern ; ctx = StringUtil . replace ( ctx , JTXCTX_PATTERN_CLASS , type . getName ( ) ) ; ctx = StringUtil . replace ( ctx , JTXCTX_PATTERN_METHOD , methodName ) ; return ctx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads transaction mode from method annotation . Annotations are cached for better performances . [CODESPLIT] public synchronized JtxTransactionMode getTxMode ( final Class type , final String methodName , final Class [ ] methodArgTypes , final String unique ) { String signature = type . getName ( ) + ' ' + methodName + ' ' + unique ; JtxTransactionMode txMode = txmap . get ( signature ) ; if ( txMode == null ) { if ( ! txmap . containsKey ( signature ) ) { final Method m ; try { m = type . getMethod ( methodName , methodArgTypes ) ; } catch ( NoSuchMethodException nsmex ) { throw new ProxettaException ( nsmex ) ; } final TransactionAnnotationValues txAnn = readTransactionAnnotation ( m ) ; if ( txAnn != null ) { txMode = new JtxTransactionMode ( txAnn . propagation ( ) , txAnn . isolation ( ) , txAnn . readOnly ( ) , txAnn . timeout ( ) ) ; } else { txMode = defaultTransactionMode ; } txmap . put ( signature , txMode ) ; } } return txMode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new TX annotations . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public void registerAnnotations ( final Class < ? extends Annotation > [ ] annotations ) { this . annotations = annotations ; this . annotationParsers = new AnnotationParser [ annotations . length ] ; for ( int i = 0 ; i < annotations . length ; i ++ ) { annotationParsers [ i ] = TransactionAnnotationValues . parserFor ( annotations [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds TX annotation . [CODESPLIT] protected TransactionAnnotationValues readTransactionAnnotation ( final Method method ) { for ( AnnotationParser annotationParser : annotationParsers ) { TransactionAnnotationValues tad = TransactionAnnotationValues . of ( annotationParser , method ) ; if ( tad != null ) { return tad ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- attributes [CODESPLIT] public void addIdSelector ( String id ) { id = unescape ( id ) ; selectors . add ( new AttributeSelector ( ID , EQUALS , id ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accepts single node . [CODESPLIT] @ Override public boolean accept ( final Node node ) { // match element name with node name if ( ! matchElement ( node ) ) { return false ; } // match attributes int totalSelectors = selectorsCount ( ) ; for ( int i = 0 ; i < totalSelectors ; i ++ ) { Selector selector = getSelector ( i ) ; // just attr name existence switch ( selector . getType ( ) ) { case ATTRIBUTE : if ( ! ( ( AttributeSelector ) selector ) . accept ( node ) ) { return false ; } break ; case PSEUDO_CLASS : if ( ! ( ( PseudoClassSelector ) selector ) . accept ( node ) ) { return false ; } break ; case PSEUDO_FUNCTION : if ( ! ( ( PseudoFunctionSelector ) selector ) . accept ( node ) ) { return false ; } break ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches element to css selector . All non - element types are ignored . [CODESPLIT] protected boolean matchElement ( final Node node ) { if ( node . getNodeType ( ) != Node . NodeType . ELEMENT ) { return false ; } String element = getElement ( ) ; String nodeName = node . getNodeName ( ) ; return element . equals ( StringPool . STAR ) || element . equals ( nodeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accepts node within current results . [CODESPLIT] public boolean accept ( final List < Node > currentResults , final Node node , final int index ) { // match attributes int totalSelectors = selectorsCount ( ) ; for ( int i = 0 ; i < totalSelectors ; i ++ ) { Selector selector = getSelector ( i ) ; // just attr name existence switch ( selector . getType ( ) ) { case PSEUDO_FUNCTION : if ( ! ( ( PseudoFunctionSelector ) selector ) . accept ( currentResults , node , index ) ) { return false ; } break ; case PSEUDO_CLASS : if ( ! ( ( PseudoClassSelector ) selector ) . accept ( currentResults , node , index ) ) { return false ; } break ; default : } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unescapes CSS string by removing all backslash characters from it . [CODESPLIT] protected String unescape ( final String value ) { if ( value . indexOf ( ' ' ) == - 1 ) { return value ; } return StringUtil . remove ( value , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a set of java core packages . [CODESPLIT] private String [ ] buildJrePackages ( final int javaVersionNumber ) { final ArrayList < String > packages = new ArrayList <> ( ) ; switch ( javaVersionNumber ) { case 9 : case 8 : case 7 : case 6 : case 5 : // in Java1.5, the apache stuff moved packages . add ( \"com.sun.org.apache\" ) ; // fall through... case 4 : if ( javaVersionNumber == 4 ) { packages . add ( \"org.apache.crimson\" ) ; packages . add ( \"org.apache.xalan\" ) ; packages . add ( \"org.apache.xml\" ) ; packages . add ( \"org.apache.xpath\" ) ; } packages . add ( \"org.ietf.jgss\" ) ; packages . add ( \"org.w3c.dom\" ) ; packages . add ( \"org.xml.sax\" ) ; // fall through... case 3 : packages . add ( \"org.omg\" ) ; packages . add ( \"com.sun.corba\" ) ; packages . add ( \"com.sun.jndi\" ) ; packages . add ( \"com.sun.media\" ) ; packages . add ( \"com.sun.naming\" ) ; packages . add ( \"com.sun.org.omg\" ) ; packages . add ( \"com.sun.rmi\" ) ; packages . add ( \"sunw.io\" ) ; packages . add ( \"sunw.util\" ) ; // fall through... case 2 : packages . add ( \"com.sun.java\" ) ; packages . add ( \"com.sun.image\" ) ; // fall through... case 1 : default : // core stuff packages . add ( \"sun\" ) ; packages . add ( \"java\" ) ; packages . add ( \"javax\" ) ; break ; } return packages . toArray ( new String [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- java checks [CODESPLIT] private int detectJavaVersionNumber ( ) { String javaVersion = JAVA_VERSION ; final int lastDashNdx = javaVersion . lastIndexOf ( ' ' ) ; if ( lastDashNdx != - 1 ) { javaVersion = javaVersion . substring ( 0 , lastDashNdx ) ; } if ( javaVersion . startsWith ( \"1.\" ) ) { // up to java 8 final int index = javaVersion . indexOf ( ' ' , 2 ) ; return Integer . parseInt ( javaVersion . substring ( 2 , index ) ) ; } else { final int index = javaVersion . indexOf ( ' ' ) ; return Integer . parseInt ( index == - 1 ? javaVersion : javaVersion . substring ( 0 , index ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all non - final values to the empty cloned object . Cache - related values are not copied . [CODESPLIT] protected < T extends Node > T cloneTo ( final T dest ) { //\t\tdest.nodeValue = nodeValue;\t\t// already  in clone implementations! dest . parentNode = parentNode ; if ( attributes != null ) { dest . attributes = new ArrayList <> ( attributes . size ( ) ) ; for ( int i = 0 , attributesSize = attributes . size ( ) ; i < attributesSize ; i ++ ) { Attribute attr = attributes . get ( i ) ; dest . attributes . add ( attr . clone ( ) ) ; } } if ( childNodes != null ) { dest . childNodes = new ArrayList <> ( childNodes . size ( ) ) ; for ( int i = 0 , childNodesSize = childNodes . size ( ) ; i < childNodesSize ; i ++ ) { Node child = childNodes . get ( i ) ; Node childClone = child . clone ( ) ; childClone . parentNode = dest ; // fix parent! dest . childNodes . add ( childClone ) ; } } return dest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes this node from DOM tree . [CODESPLIT] public void detachFromParent ( ) { if ( parentNode == null ) { return ; } if ( parentNode . childNodes != null ) { parentNode . childNodes . remove ( siblingIndex ) ; parentNode . reindexChildren ( ) ; } parentNode = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends child node . Don t use this node in the loop since it might be slow due to { [CODESPLIT] public void addChild ( final Node node ) { node . detachFromParent ( ) ; node . parentNode = this ; initChildNodes ( node ) ; childNodes . add ( node ) ; reindexChildrenOnAdd ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends several child nodes at once . Reindex is done only once after all children are added . [CODESPLIT] public void addChild ( final Node ... nodes ) { if ( nodes . length == 0 ) { return ; // nothing to add } for ( Node node : nodes ) { node . detachFromParent ( ) ; node . parentNode = this ; initChildNodes ( node ) ; childNodes . add ( node ) ; } reindexChildrenOnAdd ( nodes . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts node at given index . [CODESPLIT] public void insertChild ( final Node node , final int index ) { node . detachFromParent ( ) ; node . parentNode = this ; try { initChildNodes ( node ) ; childNodes . add ( index , node ) ; } catch ( IndexOutOfBoundsException ignore ) { throw new LagartoDOMException ( \"Invalid node index: \" + index ) ; } reindexChildren ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts node before provided node . [CODESPLIT] public void insertBefore ( final Node newChild , final Node refChild ) { int siblingIndex = refChild . getSiblingIndex ( ) ; refChild . parentNode . insertChild ( newChild , siblingIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts several child nodes before provided node . [CODESPLIT] public void insertBefore ( final Node [ ] newChilds , final Node refChild ) { if ( newChilds . length == 0 ) { return ; } int siblingIndex = refChild . getSiblingIndex ( ) ; refChild . parentNode . insertChild ( newChilds , siblingIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts node after provided node . [CODESPLIT] public void insertAfter ( final Node newChild , final Node refChild ) { int siblingIndex = refChild . getSiblingIndex ( ) + 1 ; if ( siblingIndex == refChild . parentNode . getChildNodesCount ( ) ) { refChild . parentNode . addChild ( newChild ) ; } else { refChild . parentNode . insertChild ( newChild , siblingIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts several child nodes after referent node . [CODESPLIT] public void insertAfter ( final Node [ ] newChilds , final Node refChild ) { if ( newChilds . length == 0 ) { return ; } int siblingIndex = refChild . getSiblingIndex ( ) + 1 ; if ( siblingIndex == refChild . parentNode . getChildNodesCount ( ) ) { refChild . parentNode . addChild ( newChilds ) ; } else { refChild . parentNode . insertChild ( newChilds , siblingIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes child node at given index . Returns removed node or <code > null< / code > if index is invalid . [CODESPLIT] public Node removeChild ( final int index ) { if ( childNodes == null ) { return null ; } Node node ; try { node = childNodes . get ( index ) ; } catch ( IndexOutOfBoundsException ignore ) { return null ; } node . detachFromParent ( ) ; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all child nodes . Each child node will be detached from this parent . [CODESPLIT] public void removeAllChilds ( ) { List < Node > removedNodes = childNodes ; childNodes = null ; childElementNodes = null ; childElementNodesCount = 0 ; if ( removedNodes != null ) { for ( int i = 0 , removedNodesSize = removedNodes . size ( ) ; i < removedNodesSize ; i ++ ) { Node removedNode = removedNodes . get ( i ) ; removedNode . detachFromParent ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns attribute at given index or <code > null< / code > if index not found . [CODESPLIT] public Attribute getAttribute ( final int index ) { if ( attributes == null ) { return null ; } if ( ( index < 0 ) || ( index >= attributes . size ( ) ) ) { return null ; } return attributes . get ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if node contains an attribute . [CODESPLIT] public boolean hasAttribute ( String name ) { if ( attributes == null ) { return false ; } if ( ! ownerDocument . config . isCaseSensitive ( ) ) { name = name . toLowerCase ( ) ; } for ( int i = 0 , attributesSize = attributes . size ( ) ; i < attributesSize ; i ++ ) { Attribute attr = attributes . get ( i ) ; if ( attr . getName ( ) . equals ( name ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns attribute value . Returns <code > null< / code > when attribute doesn t exist or when attribute exist but doesn t specify a value . [CODESPLIT] public String getAttribute ( final String name ) { Attribute attribute = getAttributeInstance ( name ) ; if ( attribute == null ) { return null ; } return attribute . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets attribute value . Value may be <code > null< / code > . [CODESPLIT] public void setAttribute ( String name , final String value ) { initAttributes ( ) ; String rawAttributeName = name ; if ( ! ownerDocument . config . isCaseSensitive ( ) ) { name = name . toLowerCase ( ) ; } // search if attribute with the same name exist for ( int i = 0 , attributesSize = attributes . size ( ) ; i < attributesSize ; i ++ ) { Attribute attr = attributes . get ( i ) ; if ( attr . getName ( ) . equals ( name ) ) { attr . setValue ( value ) ; return ; } } attributes . add ( new Attribute ( rawAttributeName , name , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if attribute containing some word . [CODESPLIT] public boolean isAttributeContaining ( final String name , final String word ) { Attribute attr = getAttributeInstance ( name ) ; if ( attr == null ) { return false ; } return attr . isContaining ( word ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first child node with given node name . [CODESPLIT] public Node findChildNodeWithName ( final String name ) { if ( childNodes == null ) { return null ; } for ( final Node childNode : childNodes ) { if ( childNode . getNodeName ( ) . equals ( name ) ) { return childNode ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters child nodes . [CODESPLIT] public Node [ ] filterChildNodes ( final Predicate < Node > nodePredicate ) { if ( childNodes == null ) { return new Node [ 0 ] ; } return childNodes . stream ( ) . filter ( nodePredicate ) . toArray ( Node [ ] :: new ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a child node at given index or <code > null< / code > if child doesn t exist for that index . [CODESPLIT] public Node getChild ( final int index ) { if ( childNodes == null ) { return null ; } if ( ( index < 0 ) || ( index >= childNodes . size ( ) ) ) { return null ; } return childNodes . get ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a child node with given hierarchy . Just a shortcut for successive calls of { [CODESPLIT] public Node getChild ( final int ... indexes ) { Node node = this ; for ( int index : indexes ) { node = node . getChild ( index ) ; } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a child element node at given index . If index is out of bounds <code > null< / code > is returned . [CODESPLIT] public Element getChildElement ( final int index ) { initChildElementNodes ( ) ; if ( ( index < 0 ) || ( index >= childElementNodes . length ) ) { return null ; } return childElementNodes [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns first child or <code > null< / code > if no children exist . [CODESPLIT] public Node getFirstChild ( ) { if ( childNodes == null ) { return null ; } if ( childNodes . isEmpty ( ) ) { return null ; } return childNodes . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns last child or <code > null< / code > if no children exist . [CODESPLIT] public Node getLastChild ( ) { if ( childNodes == null ) { return null ; } if ( childNodes . isEmpty ( ) ) { return null ; } return childNodes . get ( getChildNodesCount ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns last child <b > element< / b > with given name or <code > null< / code > if no such child node exist . [CODESPLIT] public Element getLastChildElement ( final String elementName ) { if ( childNodes == null ) { return null ; } int from = childNodes . size ( ) - 1 ; for ( int i = from ; i >= 0 ; i -- ) { Node child = childNodes . get ( i ) ; if ( child . getNodeType ( ) == NodeType . ELEMENT && elementName . equals ( child . getNodeName ( ) ) ) { child . initSiblingNames ( ) ; return ( Element ) child ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the health of child nodes . Useful during complex tree manipulation to check if everything is OK . Not optimized for speed should be used just for testing purposes . [CODESPLIT] public boolean check ( ) { if ( childNodes == null ) { return true ; } // children int siblingElementIndex = 0 ; for ( int i = 0 , childNodesSize = childNodes . size ( ) ; i < childNodesSize ; i ++ ) { Node childNode = childNodes . get ( i ) ; if ( childNode . siblingIndex != i ) { return false ; } if ( childNode . getNodeType ( ) == NodeType . ELEMENT ) { if ( childNode . siblingElementIndex != siblingElementIndex ) { return false ; } siblingElementIndex ++ ; } } if ( childElementNodesCount != siblingElementIndex ) { return false ; } // child element nodes if ( childElementNodes != null ) { if ( childElementNodes . length != childElementNodesCount ) { return false ; } int childCount = getChildNodesCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { Node child = getChild ( i ) ; if ( child . siblingElementIndex >= 0 ) { if ( childElementNodes [ child . siblingElementIndex ] != child ) { return false ; } } } } // sibling names if ( siblingNameIndex != - 1 ) { List < Node > siblings = parentNode . childNodes ; int index = 0 ; for ( int i = 0 , siblingsSize = siblings . size ( ) ; i < siblingsSize ; i ++ ) { Node sibling = siblings . get ( i ) ; if ( sibling . siblingNameIndex == - 1 && nodeType == NodeType . ELEMENT && nodeName . equals ( sibling . getNodeName ( ) ) ) { if ( sibling . siblingNameIndex != index ++ ) { return false ; } } } } // process children for ( Node childNode : childNodes ) { if ( ! childNode . check ( ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reindex children nodes . Must be called on every children addition / removal . Iterates { [CODESPLIT] protected void reindexChildren ( ) { int siblingElementIndex = 0 ; for ( int i = 0 , childNodesSize = childNodes . size ( ) ; i < childNodesSize ; i ++ ) { Node childNode = childNodes . get ( i ) ; childNode . siblingIndex = i ; childNode . siblingNameIndex = - 1 ; // reset sibling name info if ( childNode . getNodeType ( ) == NodeType . ELEMENT ) { childNode . siblingElementIndex = siblingElementIndex ; siblingElementIndex ++ ; } } childElementNodesCount = siblingElementIndex ; childElementNodes = null ; // reset child element nodes }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes list of child elements . [CODESPLIT] protected void initChildElementNodes ( ) { if ( childElementNodes == null ) { childElementNodes = new Element [ childElementNodesCount ] ; int childCount = getChildNodesCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { Node child = getChild ( i ) ; if ( child . siblingElementIndex >= 0 ) { childElementNodes [ child . siblingElementIndex ] = ( Element ) child ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes siblings elements of the same name . [CODESPLIT] protected void initSiblingNames ( ) { if ( siblingNameIndex == - 1 ) { List < Node > siblings = parentNode . childNodes ; int index = 0 ; for ( int i = 0 , siblingsSize = siblings . size ( ) ; i < siblingsSize ; i ++ ) { Node sibling = siblings . get ( i ) ; if ( sibling . siblingNameIndex == - 1 && nodeType == NodeType . ELEMENT && nodeName . equals ( sibling . getNodeName ( ) ) ) { sibling . siblingNameIndex = index ++ ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes child nodes list when needed . Also fix owner document for new node if needed . [CODESPLIT] protected void initChildNodes ( final Node newNode ) { if ( childNodes == null ) { childNodes = new ArrayList <> ( ) ; } if ( ownerDocument != null ) { if ( newNode . ownerDocument != ownerDocument ) { changeOwnerDocument ( newNode , ownerDocument ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes owner document for given node and all its children . [CODESPLIT] protected void changeOwnerDocument ( final Node node , final Document ownerDocument ) { node . ownerDocument = ownerDocument ; int childCount = node . getChildNodesCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { Node child = node . getChild ( i ) ; changeOwnerDocument ( child , ownerDocument ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this node s next sibling of <b > any< / b > type or <code > null< / code > if this is the last sibling . [CODESPLIT] public Node getNextSibling ( ) { List < Node > siblings = parentNode . childNodes ; int index = siblingIndex + 1 ; if ( index >= siblings . size ( ) ) { return null ; } return siblings . get ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this node s next <b > element< / b > . [CODESPLIT] public Node getNextSiblingElement ( ) { parentNode . initChildElementNodes ( ) ; if ( siblingElementIndex == - 1 ) { int max = parentNode . getChildNodesCount ( ) ; for ( int i = siblingIndex ; i < max ; i ++ ) { Node sibling = parentNode . childNodes . get ( i ) ; if ( sibling . getNodeType ( ) == NodeType . ELEMENT ) { return sibling ; } } return null ; } int index = siblingElementIndex + 1 ; if ( index >= parentNode . childElementNodesCount ) { return null ; } return parentNode . childElementNodes [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this node s next <b > element< / b > with the same name . [CODESPLIT] public Node getNextSiblingName ( ) { if ( nodeName == null ) { return null ; } initSiblingNames ( ) ; int index = siblingNameIndex + 1 ; int max = parentNode . getChildNodesCount ( ) ; for ( int i = siblingIndex + 1 ; i < max ; i ++ ) { Node sibling = parentNode . childNodes . get ( i ) ; if ( ( index == sibling . siblingNameIndex ) && nodeName . equals ( sibling . getNodeName ( ) ) ) { return sibling ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this node s previous sibling of <b > any< / b > type or <code > null< / code > if this is the first sibling . [CODESPLIT] public Node getPreviousSibling ( ) { List < Node > siblings = parentNode . childNodes ; int index = siblingIndex - 1 ; if ( index < 0 ) { return null ; } return siblings . get ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this node s previous sibling of <b > element< / b > type or <code > null< / code > if this is the first sibling . [CODESPLIT] public Node getPreviousSiblingElement ( ) { parentNode . initChildElementNodes ( ) ; if ( siblingElementIndex == - 1 ) { for ( int i = siblingIndex - 1 ; i >= 0 ; i -- ) { Node sibling = parentNode . childNodes . get ( i ) ; if ( sibling . getNodeType ( ) == NodeType . ELEMENT ) { return sibling ; } } return null ; } int index = siblingElementIndex - 1 ; if ( index < 0 ) { return null ; } return parentNode . childElementNodes [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this node s previous sibling element with the same name . [CODESPLIT] public Node getPreviousSiblingName ( ) { if ( nodeName == null ) { return null ; } initSiblingNames ( ) ; int index = siblingNameIndex - 1 ; for ( int i = siblingIndex ; i >= 0 ; i -- ) { Node sibling = parentNode . childNodes . get ( i ) ; if ( ( index == sibling . siblingNameIndex ) && nodeName . equals ( sibling . getNodeName ( ) ) ) { return sibling ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the text content of this node and its descendants . [CODESPLIT] public String getTextContent ( ) { StringBuilder sb = new StringBuilder ( getChildNodesCount ( ) + 1 ) ; appendTextContent ( sb ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the text content to an <code > Appendable< / code > ( <code > StringBuilder< / code > <code > CharBuffer< / code > ... ) . This way we can reuse the <code > Appendable< / code > instance during the creation of text content and have better performances . [CODESPLIT] public void appendTextContent ( final Appendable appendable ) { if ( nodeValue != null ) { if ( ( nodeType == NodeType . TEXT ) || ( nodeType == NodeType . CDATA ) ) { try { appendable . append ( nodeValue ) ; } catch ( IOException ioex ) { throw new LagartoDOMException ( ioex ) ; } } } if ( childNodes != null ) { for ( int i = 0 , childNodesSize = childNodes . size ( ) ; i < childNodesSize ; i ++ ) { Node childNode = childNodes . get ( i ) ; childNode . appendTextContent ( appendable ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates HTML . [CODESPLIT] public String getHtml ( ) { LagartoDomBuilderConfig lagartoDomBuilderConfig ; if ( ownerDocument == null ) { lagartoDomBuilderConfig = ( ( Document ) this ) . getConfig ( ) ; } else { lagartoDomBuilderConfig = ownerDocument . getConfig ( ) ; } LagartoHtmlRenderer lagartoHtmlRenderer = lagartoDomBuilderConfig . getLagartoHtmlRenderer ( ) ; return lagartoHtmlRenderer . toHtml ( this , new StringBuilder ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates inner HTML . [CODESPLIT] public String getInnerHtml ( ) { LagartoDomBuilderConfig lagartoDomBuilderConfig ; if ( ownerDocument == null ) { lagartoDomBuilderConfig = ( ( Document ) this ) . getConfig ( ) ; } else { lagartoDomBuilderConfig = ownerDocument . getConfig ( ) ; } LagartoHtmlRenderer lagartoHtmlRenderer = lagartoDomBuilderConfig . getLagartoHtmlRenderer ( ) ; return lagartoHtmlRenderer . toInnerHtml ( this , new StringBuilder ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits children nodes . [CODESPLIT] protected void visitChildren ( final NodeVisitor nodeVisitor ) { if ( childNodes != null ) { for ( int i = 0 , childNodesSize = childNodes . size ( ) ; i < childNodesSize ; i ++ ) { Node childNode = childNodes . get ( i ) ; childNode . visit ( nodeVisitor ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns CSS path to this node from document root . [CODESPLIT] public String getCssPath ( ) { StringBuilder path = new StringBuilder ( ) ; Node node = this ; while ( node != null ) { String nodeName = node . getNodeName ( ) ; if ( nodeName != null ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( ' ' ) . append ( nodeName ) ; String id = node . getAttribute ( \"id\" ) ; if ( id != null ) { sb . append ( ' ' ) . append ( id ) ; } path . insert ( 0 , sb ) ; } node = node . getParentNode ( ) ; } if ( path . charAt ( 0 ) == ' ' ) { return path . substring ( 1 ) ; } return path . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle Decora tags . [CODESPLIT] protected void onDecoraTag ( final Tag tag ) { String tagName = tag . getName ( ) . toString ( ) ; if ( tag . getType ( ) == TagType . SELF_CLOSING ) { checkNestedDecoraTags ( ) ; decoraTagName = tagName . substring ( 7 ) ; decoraTagStart = tag . getTagPosition ( ) ; decoraTagEnd = tag . getTagPosition ( ) + tag . getTagLength ( ) ; defineDecoraTag ( ) ; return ; } if ( tag . getType ( ) == TagType . START ) { checkNestedDecoraTags ( ) ; decoraTagName = tagName . substring ( 7 ) ; decoraTagStart = tag . getTagPosition ( ) ; decoraTagDefaultValueStart = tag . getTagPosition ( ) + tag . getTagLength ( ) ; return ; } // closed tag type decoraTagEnd = tag . getTagPosition ( ) + tag . getTagLength ( ) ; decoraTagDefaultValueEnd = tag . getTagPosition ( ) ; defineDecoraTag ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle open and empty ID attribute tags . [CODESPLIT] protected void onIdAttrStart ( final Tag tag ) { String id = tag . getId ( ) . toString ( ) . substring ( 7 ) ; String tagName ; String idName ; int dashIndex = id . indexOf ( ' ' ) ; if ( dashIndex == - 1 ) { tagName = id ; idName = null ; } else { tagName = id . substring ( 0 , dashIndex ) ; idName = id . substring ( dashIndex + 1 ) ; } if ( tag . getType ( ) == TagType . SELF_CLOSING ) { checkNestedDecoraTags ( ) ; decoraTagName = tagName ; decoraIdName = idName ; decoraTagStart = tag . getTagPosition ( ) ; decoraTagEnd = tag . getTagPosition ( ) + tag . getTagLength ( ) ; defineDecoraTag ( ) ; return ; } if ( tag . getType ( ) == TagType . START ) { checkNestedDecoraTags ( ) ; decoraTagName = tagName ; decoraIdName = idName ; decoraTagStart = tag . getTagPosition ( ) ; decoraTagDefaultValueStart = tag . getTagPosition ( ) + tag . getTagLength ( ) ; closingTagName = tag . getName ( ) . toString ( ) ; closingTagDeepLevel = tag . getDeepLevel ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines Decora tag position inside decorator content . Resets current Decora tag tracking . [CODESPLIT] protected void defineDecoraTag ( ) { DecoraTag decoraTag = decoraTagDefaultValueStart == 0 ? new DecoraTag ( decoraTagName , decoraIdName , decoraTagStart , decoraTagEnd ) : new DecoraTag ( decoraTagName , decoraIdName , decoraTagStart , decoraTagEnd , decoraTagDefaultValueStart , decoraTagDefaultValueEnd - decoraTagDefaultValueStart ) ; decoraTags . add ( decoraTag ) ; decoraTagName = null ; decoraIdName = null ; closingTagName = null ; decoraTagDefaultValueStart = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a proxy aspect . [CODESPLIT] @ Override public JoyProxetta addProxyAspect ( final ProxyAspect proxyAspect ) { requireNotStarted ( proxetta ) ; this . proxyAspects . add ( proxyAspect ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates Proxetta with all aspects . The following aspects are created : <ul > <li > Transaction proxy - applied on all classes that contains public top - level methods annotated with <code > [CODESPLIT] @ Override public void start ( ) { initLogger ( ) ; log . info ( \"PROXETTA start ----------\" ) ; final ProxyAspect [ ] proxyAspectsArray = this . proxyAspects . toArray ( new ProxyAspect [ 0 ] ) ; log . debug ( \"Total proxy aspects: \" + proxyAspectsArray . length ) ; //\t\tproxetta = Proxetta.wrapperProxetta().setCreateTargetInDefaultCtor(true).withAspects(proxyAspectsArray); proxetta = Proxetta . proxyProxetta ( ) . withAspects ( proxyAspectsArray ) ; log . info ( \"PROXETTA OK!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- benchmark [CODESPLIT] @ Benchmark public Object map ( ) { final FastCharBuffer sb = new FastCharBuffer ( ) ; for ( final int index : indexes ) { sb . append ( map . get ( TYPES [ index ] ) ) ; } return sb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timestamp get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return rs . getTimestamp ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Timestamp value , final int dbSqlType ) throws SQLException { st . setTimestamp ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the corresponding MIME type to the given extension . If no MIME type was found it returns <code > application / octet - stream< / code > type . [CODESPLIT] public static String getMimeType ( final String ext ) { String mimeType = lookupMimeType ( ext ) ; if ( mimeType == null ) { mimeType = MIME_APPLICATION_OCTET_STREAM ; } return mimeType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all extensions that belong to given mime type ( s ) . If wildcard mode is on provided mime type is wildcard pattern . [CODESPLIT] public static String [ ] findExtensionsByMimeTypes ( String mimeType , final boolean useWildcard ) { final ArrayList < String > extensions = new ArrayList <> ( ) ; mimeType = mimeType . toLowerCase ( ) ; final String [ ] mimeTypes = StringUtil . splitc ( mimeType , \", \" ) ; for ( final Map . Entry < String , String > entry : MIME_TYPE_MAP . entrySet ( ) ) { final String entryExtension = entry . getKey ( ) ; final String entryMimeType = entry . getValue ( ) . toLowerCase ( ) ; final int matchResult = useWildcard ? Wildcard . matchOne ( entryMimeType , mimeTypes ) : StringUtil . equalsOne ( entryMimeType , mimeTypes ) ; if ( matchResult != - 1 ) { extensions . add ( entryExtension ) ; } } if ( extensions . isEmpty ( ) ) { return StringPool . EMPTY_ARRAY ; } return extensions . toArray ( new String [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Boolean get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Boolean . valueOf ( rs . getBoolean ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Boolean value , final int dbSqlType ) throws SQLException { st . setBoolean ( index , value . booleanValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds root package and its path mapping . Duplicate root packages are ignored if mapping path is equals otherwise exception is thrown . [CODESPLIT] public void addRootPackage ( final String rootPackage , String mapping ) { if ( packages == null ) { packages = new String [ 0 ] ; } if ( mappings == null ) { mappings = new String [ 0 ] ; } // fix mapping if ( mapping . length ( ) > 0 ) { // mapping must start with the slash if ( ! mapping . startsWith ( StringPool . SLASH ) ) { mapping = StringPool . SLASH + mapping ; } // mapping must NOT end with the slash if ( mapping . endsWith ( StringPool . SLASH ) ) { mapping = StringUtil . substring ( mapping , 0 , - 1 ) ; } } // detect duplicates for ( int i = 0 ; i < packages . length ; i ++ ) { if ( packages [ i ] . equals ( rootPackage ) ) { if ( mappings [ i ] . equals ( mapping ) ) { // both package and the mappings are the same return ; } throw new MadvocException ( \"Different mappings for the same root package: \" + rootPackage ) ; } } packages = ArraysUtil . append ( packages , rootPackage ) ; mappings = ArraysUtil . append ( mappings , mapping ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets root package to package of given class . [CODESPLIT] public void addRootPackageOf ( final Class actionClass , final String mapping ) { addRootPackage ( actionClass . getPackage ( ) . getName ( ) , mapping ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds closest root package for the given action path . [CODESPLIT] public String findRootPackageForActionPath ( final String actionPath ) { if ( mappings == null ) { return null ; } int ndx = - 1 ; int delta = Integer . MAX_VALUE ; for ( int i = 0 ; i < mappings . length ; i ++ ) { String mapping = mappings [ i ] ; boolean found = false ; if ( actionPath . equals ( mapping ) ) { found = true ; } else { mapping += StringPool . SLASH ; if ( actionPath . startsWith ( mapping ) ) { found = true ; } } if ( found ) { int distance = actionPath . length ( ) - mapping . length ( ) ; if ( distance < delta ) { ndx = i ; delta = distance ; } } } if ( ndx == - 1 ) { return null ; } return packages [ ndx ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds mapping for given action class . Returns <code > null< / code > if no mapping is found . If there is more then one matching root package the closest one will be returned . [CODESPLIT] public String findPackagePathForActionPackage ( final String actionPackage ) { if ( packages == null ) { return null ; } if ( packagePaths == null ) { packagePaths = new HashMap <> ( ) ; } String packagePath = packagePaths . get ( actionPackage ) ; if ( packagePath != null ) { return packagePath ; } int ndx = - 1 ; int delta = Integer . MAX_VALUE ; for ( int i = 0 ; i < packages . length ; i ++ ) { String rootPackage = packages [ i ] ; if ( rootPackage . equals ( actionPackage ) ) { // exact match ndx = i ; delta = 0 ; break ; } rootPackage += ' ' ; if ( actionPackage . startsWith ( rootPackage ) ) { // found, action package contains root package int distanceFromTheRoot = actionPackage . length ( ) - rootPackage . length ( ) ; if ( distanceFromTheRoot < delta ) { ndx = i ; delta = distanceFromTheRoot ; } } } if ( ndx == - 1 ) { return null ; } String packageActionPath = delta == 0 ? StringPool . EMPTY : StringUtil . substring ( actionPackage , - delta - 1 , 0 ) ; packageActionPath = packageActionPath . replace ( ' ' , ' ' ) ; String result = mappings [ ndx ] + packageActionPath ; packagePaths . put ( actionPackage , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public DbSession beginTransaction ( final JtxTransactionMode jtxMode , final boolean active ) { DbSession session = new DbSession ( connectionProvider ) ; if ( active ) { log . debug ( \"begin jtx\" ) ; session . beginTransaction ( JtxDbUtil . convertToDbMode ( jtxMode ) ) ; } return session ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void commitTransaction ( final DbSession resource ) { if ( resource . isTransactionActive ( ) ) { log . debug ( \"commit jtx\" ) ; resource . commitTransaction ( ) ; } resource . closeSession ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void rollbackTransaction ( final DbSession resource ) { try { if ( resource . isTransactionActive ( ) ) { log . debug ( \"rollback tx\" ) ; resource . rollbackTransaction ( ) ; } } catch ( Exception ex ) { throw new JtxException ( ex ) ; } finally { resource . closeSession ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns JSON violations string . Contains javascript array with elements that contain : <ul > <li > name - violation name< / li > <li > msg - message code i . e . constraint class name< / li > < / ul > [CODESPLIT] public static String createViolationsJsonString ( final HttpServletRequest request , final List < Violation > violations ) { if ( violations == null ) { return StringPool . EMPTY ; } StringBuilder sb = new StringBuilder ( ) . append ( ' ' ) ; for ( int i = 0 , violationsSize = violations . size ( ) ; i < violationsSize ; i ++ ) { Violation violation = violations . get ( i ) ; if ( i != 0 ) { sb . append ( ' ' ) ; } sb . append ( ' ' ) ; sb . append ( \"\\\"name\\\":\\\"\" ) . append ( violation . getName ( ) ) . append ( ' ' ) . append ( ' ' ) ; sb . append ( \"\\\"msg\\\":\\\"\" ) . append ( resolveValidationMessage ( request , violation ) ) . append ( ' ' ) ; sb . append ( ' ' ) ; } sb . append ( ' ' ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares validation messages . Key is either validation constraint class name or violation name . [CODESPLIT] public static String resolveValidationMessage ( final HttpServletRequest request , final Violation violation ) { ValidationConstraint vc = violation . getConstraint ( ) ; String key = vc != null ? vc . getClass ( ) . getName ( ) : violation . getName ( ) ; String msg = LocalizationUtil . findMessage ( request , key ) ; if ( msg != null ) { return beanTemplateParser . parseWithBean ( msg , violation ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes later duplicated references in an array . Returns new instance of BeanReferences if there was changes otherwise returns the same instance . [CODESPLIT] public BeanReferences removeDuplicateNames ( ) { if ( names . length < 2 ) { return this ; } int nullCount = 0 ; for ( int i = 1 ; i < names . length ; i ++ ) { String thisRef = names [ i ] ; if ( thisRef == null ) { nullCount ++ ; continue ; } for ( int j = 0 ; j < i ; j ++ ) { if ( names [ j ] == null ) { continue ; } if ( thisRef . equals ( names [ j ] ) ) { names [ i ] = null ; break ; } } } if ( nullCount == 0 ) { return this ; } String [ ] newRefs = new String [ names . length - nullCount ] ; int ndx = 0 ; for ( String name : names ) { if ( name == null ) { continue ; } newRefs [ ndx ] = name ; ndx ++ ; } return new BeanReferences ( newRefs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds props files or patterns . [CODESPLIT] @ Override public JoyProps addPropsFile ( final String namePattern ) { requireNotStarted ( props ) ; this . propsNamePatterns . add ( namePattern ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and loads application props . It first loads system properties ( registered as <code > sys . * < / code > ) and then environment properties ( registered as <code > env . * < / code > ) . Finally props files are read from the classpath . All properties are loaded using <p > If props have been already loaded does nothing . [CODESPLIT] @ Override public void start ( ) { initLogger ( ) ; log . info ( \"PROPS start ----------\" ) ; props = createProps ( ) ; props . loadSystemProperties ( \"sys\" ) ; props . loadEnvironment ( \"env\" ) ; log . debug ( \"Loaded sys&env props: \" + props . countTotalProperties ( ) + \" properties.\" ) ; props . setActiveProfiles ( propsProfiles . toArray ( new String [ 0 ] ) ) ; // prepare patterns final String [ ] patterns = new String [ propsNamePatterns . size ( ) + 1 ] ; patterns [ 0 ] = \"/\" + nameSupplier . get ( ) + \"*.prop*\" ; for ( int i = 0 ; i < propsNamePatterns . size ( ) ; i ++ ) { patterns [ i + 1 ] = propsNamePatterns . get ( i ) ; } log . debug ( \"Loading props from classpath...\" ) ; final long startTime = System . currentTimeMillis ( ) ; props . loadFromClasspath ( patterns ) ; log . debug ( \"Props scanning completed in \" + ( System . currentTimeMillis ( ) - startTime ) + \"ms.\" ) ; log . debug ( \"Total properties: \" + props . countTotalProperties ( ) ) ; log . info ( \"PROPS OK!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { [CODESPLIT] protected Props createProps ( ) { final Props props = new Props ( ) ; props . setSkipEmptyProps ( true ) ; props . setIgnoreMissingMacros ( true ) ; return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates all targets . [CODESPLIT] public void forEachTarget ( final Consumer < Target > targetConsumer ) { for ( final Target target : targets ) { targetConsumer . accept ( target ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates all targets and for each target iterates all IN injection points of given scope . [CODESPLIT] public void forEachTargetAndIn ( final MadvocScope scope , final BiConsumer < Target , InjectionPoint > biConsumer ) { for ( final Target target : targets ) { final ScopeData scopeData = target . scopeData ( ) ; if ( scopeData . in ( ) == null ) { continue ; } for ( final InjectionPoint in : scopeData . in ( ) ) { if ( in . scope ( ) != scope ) { continue ; } biConsumer . accept ( target , in ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates all targets and for each target iterates all OUT injection points of given scope . [CODESPLIT] public void forEachTargetAndOut ( final MadvocScope scope , final BiConsumer < Target , InjectionPoint > biConsumer ) { for ( final Target target : targets ) { final ScopeData scopeData = target . scopeData ( ) ; if ( scopeData . out ( ) == null ) { continue ; } for ( final InjectionPoint out : scopeData . out ( ) ) { if ( out . scope ( ) != scope ) { continue ; } biConsumer . accept ( target , out ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all parameters from target into an array . [CODESPLIT] public Object [ ] extractParametersValues ( ) { final Object [ ] values = new Object [ targets . length - 1 ] ; for ( int i = 1 ; i < targets . length ; i ++ ) { values [ i - 1 ] = targets [ i ] . value ( ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins action and parameters into one single array of Targets . [CODESPLIT] protected Target [ ] makeTargets ( final Target actionTarget , final MethodParam [ ] methodParams ) { if ( methodParams == null ) { // action does not have method parameters, so there is just one target return new Target [ ] { actionTarget } ; } // action has method arguments, so there is more then one target final Target [ ] target = new Target [ methodParams . length + 1 ] ; target [ 0 ] = actionTarget ; final Object action = actionTarget . value ( ) ; for ( int i = 0 ; i < methodParams . length ; i ++ ) { final MethodParam methodParam = methodParams [ i ] ; final Class paramType = methodParam . type ( ) ; final Target paramTarget ; if ( methodParam . annotationType ( ) == null ) { // parameter is NOT annotated, create new value for the target // the class itself will be a base class, and should be scanned final ScopeData newScopeData = methodParam . scopeData ( ) . inspector ( ) . inspectClassScopesWithCache ( paramType ) ; paramTarget = Target . ofValue ( createActionMethodArgument ( paramType , action ) , newScopeData ) ; } else if ( methodParam . annotationType ( ) == Out . class ) { // parameter is annotated with *only* OUT annotation // create the output value now AND to save the type paramTarget = Target . ofMethodParam ( methodParam , createActionMethodArgument ( paramType , action ) ) ; } else { // parameter is annotated with any IN annotation // create target with NO value, as the value will be created later paramTarget = Target . ofMethodParam ( methodParam , type -> createActionMethodArgument ( type , action ) ) ; } target [ i + 1 ] = paramTarget ; } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates action method arguments . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"NullArgumentToVariableArgMethod\" } ) protected Object createActionMethodArgument ( final Class type , final Object action ) { try { if ( type . getEnclosingClass ( ) == null || Modifier . isStatic ( type . getModifiers ( ) ) ) { // regular or static class return ClassUtil . newInstance ( type ) ; } else { // member class Constructor ctor = type . getDeclaredConstructor ( type . getDeclaringClass ( ) ) ; ctor . setAccessible ( true ) ; return ctor . newInstance ( action ) ; } } catch ( Exception ex ) { throw new MadvocException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores session in map and broadcasts event to registered listeners . [CODESPLIT] @ Override public void sessionCreated ( final HttpSessionEvent httpSessionEvent ) { HttpSession session = httpSessionEvent . getSession ( ) ; sessionMap . putIfAbsent ( session . getId ( ) , session ) ; for ( HttpSessionListener listener : listeners ) { listener . sessionCreated ( httpSessionEvent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes session from a map and broadcasts event to registered listeners . [CODESPLIT] @ Override public void sessionDestroyed ( final HttpSessionEvent httpSessionEvent ) { HttpSession session = httpSessionEvent . getSession ( ) ; sessionMap . remove ( session . getId ( ) ) ; for ( HttpSessionListener listener : listeners ) { listener . sessionDestroyed ( httpSessionEvent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the string at position { [CODESPLIT] public String getString ( final int pos ) { CharSequence cs = ( CharSequence ) list . get ( pos ) ; return cs == null ? null : cs . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the integer at position { [CODESPLIT] public Integer getInteger ( final int pos ) { Number number = ( Number ) list . get ( pos ) ; if ( number == null ) { return null ; } if ( number instanceof Integer ) { // avoid unnecessary unbox/box return ( Integer ) number ; } return number . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the long at position { [CODESPLIT] public Long getLong ( final int pos ) { Number number = ( Number ) list . get ( pos ) ; if ( number == null ) { return null ; } if ( number instanceof Long ) { // avoids unnecessary unbox/box return ( Long ) number ; } return number . longValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the double at position { [CODESPLIT] public Double getDouble ( final int pos ) { Number number = ( Number ) list . get ( pos ) ; if ( number == null ) { return null ; } if ( number instanceof Double ) { // avoids unnecessary unbox/box return ( Double ) number ; } return number . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Float at position { [CODESPLIT] public Float getFloat ( final int pos ) { Number number = ( Number ) list . get ( pos ) ; if ( number == null ) { return null ; } if ( number instanceof Float ) { // avoids unnecessary unbox/box return ( Float ) number ; } return number . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retruns the JsonObject at position { [CODESPLIT] public JsonObject getJsonObject ( final int pos ) { Object val = list . get ( pos ) ; if ( val instanceof Map ) { val = new JsonObject ( ( Map ) val ) ; } return ( JsonObject ) val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the JsonArray at position { [CODESPLIT] public JsonArray getJsonArray ( final int pos ) { Object val = list . get ( pos ) ; if ( val instanceof List ) { val = new JsonArray ( ( List ) val ) ; } return ( JsonArray ) val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the byte [] at position { [CODESPLIT] public byte [ ] getBinary ( final int pos ) { String val = ( String ) list . get ( pos ) ; if ( val == null ) { return null ; } return Base64 . getDecoder ( ) . decode ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the object value at position { [CODESPLIT] public Object getValue ( final int pos ) { Object val = list . get ( pos ) ; if ( val instanceof Map ) { val = new JsonObject ( ( Map ) val ) ; } else if ( val instanceof List ) { val = new JsonArray ( ( List ) val ) ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an enum to the JSON array . <p > JSON has no concept of encoding Enums so the Enum will be converted to a String using the { [CODESPLIT] public JsonArray add ( final Enum value ) { if ( value == null ) { list . add ( null ) ; } else { list . add ( value . name ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an object to the JSON array . [CODESPLIT] public JsonArray add ( Object value ) { Objects . requireNonNull ( value ) ; value = JsonObject . resolveValue ( value ) ; list . add ( value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends all of the elements in the specified array to the end of this JSON array . [CODESPLIT] public JsonArray addAll ( final JsonArray array ) { Objects . requireNonNull ( array ) ; list . addAll ( array . list ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the value at the specified position in the JSON array . [CODESPLIT] public Object remove ( final int pos ) { Object removed = list . remove ( pos ) ; if ( removed instanceof Map ) { return new JsonObject ( ( Map ) removed ) ; } if ( removed instanceof ArrayList ) { return new JsonArray ( ( List ) removed ) ; } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dispatches to the template location created from result value and JSP extension . Does its forward via a <code > RequestDispatcher< / code > . If the dispatch fails a 404 error will be sent back in the http response . [CODESPLIT] @ Override public void render ( final ActionRequest actionRequest , final Object resultValue ) throws Exception { final PathResult pathResult ; if ( resultValue == null ) { pathResult = resultOf ( StringPool . EMPTY ) ; } else { if ( resultValue instanceof String ) { pathResult = resultOf ( resultValue ) ; } else { pathResult = ( PathResult ) resultValue ; } } final String resultBasePath = actionRequest . getActionRuntime ( ) . getResultBasePath ( ) ; final String path = pathResult != null ? pathResult . path ( ) : StringPool . EMPTY ; final String actionAndResultPath = resultBasePath + ( pathResult != null ? ' ' + path : StringPool . EMPTY ) ; String target = targetCache . get ( actionAndResultPath ) ; if ( target == null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"new target: \" + actionAndResultPath ) ; } target = resolveTarget ( actionRequest , path ) ; if ( target == null ) { targetNotFound ( actionRequest , actionAndResultPath ) ; return ; } if ( log . isDebugEnabled ( ) ) { log . debug ( \"target found: \" + target ) ; } // store target in cache targetCache . put ( actionAndResultPath , target ) ; } // the target exists, continue renderView ( actionRequest , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates the target file from action path and the result value . [CODESPLIT] protected String resolveTarget ( final ActionRequest actionRequest , final String resultValue ) { String resultBasePath = actionRequest . getActionRuntime ( ) . getResultBasePath ( ) ; ResultPath resultPath = resultMapper . resolveResultPath ( resultBasePath , resultValue ) ; String actionPath = resultPath . path ( ) ; String path = actionPath ; String value = resultPath . value ( ) ; if ( StringUtil . isEmpty ( value ) ) { value = null ; } String target ; while ( true ) { // variant #1: with value if ( value != null ) { if ( path == null ) { // only value remains int lastSlashNdx = actionPath . lastIndexOf ( ' ' ) ; if ( lastSlashNdx != - 1 ) { target = actionPath . substring ( 0 , lastSlashNdx + 1 ) + value ; } else { target = ' ' + value ; } } else { target = path + ' ' + value ; } target = locateTarget ( actionRequest , target ) ; if ( target != null ) { break ; } } if ( path != null ) { // variant #2: without value target = locateTarget ( actionRequest , path ) ; if ( target != null ) { break ; } } // continue if ( path == null ) { // path not found return null ; } int dotNdx = MadvocUtil . lastIndexOfDotAfterSlash ( path ) ; if ( dotNdx == - 1 ) { path = null ; } else { path = path . substring ( 0 , dotNdx ) ; } } return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when target not found . By default sends 404 to the response . [CODESPLIT] protected void targetNotFound ( final ActionRequest actionRequest , final String actionAndResultPath ) throws IOException { final HttpServletResponse response = actionRequest . getHttpServletResponse ( ) ; if ( ! response . isCommitted ( ) ) { response . sendError ( SC_NOT_FOUND , \"Result not found: \" + actionAndResultPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Redirects to the given location . Provided path is parsed action is used as a value context . [CODESPLIT] @ Override public void render ( final ActionRequest actionRequest , final Object resultValue ) throws Exception { final Redirect redirectResult ; if ( resultValue == null ) { redirectResult = Redirect . to ( StringPool . EMPTY ) ; } else { if ( resultValue instanceof String ) { redirectResult = Redirect . to ( ( String ) resultValue ) ; } else { redirectResult = ( Redirect ) resultValue ; } } final String resultBasePath = actionRequest . getActionRuntime ( ) . getResultBasePath ( ) ; final String redirectPath = redirectResult . path ( ) ; final String resultPath ; if ( redirectPath . startsWith ( \"http://\" ) || redirectPath . startsWith ( \"https://\" ) ) { resultPath = redirectPath ; } else { resultPath = resultMapper . resolveResultPathString ( resultBasePath , redirectPath ) ; } HttpServletRequest request = actionRequest . getHttpServletRequest ( ) ; HttpServletResponse response = actionRequest . getHttpServletResponse ( ) ; String path = resultPath ; path = beanTemplateParser . parseWithBean ( path , actionRequest . getAction ( ) ) ; DispatcherUtil . redirect ( request , response , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- input [CODESPLIT] private void processInputStartTag ( final Tag tag ) { // INPUT CharSequence tagType = tag . getAttributeValue ( TYPE ) ; if ( tagType == null ) { return ; } CharSequence nameSequence = tag . getAttributeValue ( NAME ) ; if ( nameSequence == null ) { return ; } String name = nameSequence . toString ( ) ; Object valueObject = resolver . value ( name ) ; if ( valueObject == null ) { return ; } String tagTypeName = tagType . toString ( ) . toLowerCase ( ) ; if ( tagTypeName . equals ( TEXT ) || tagTypeName . equals ( HIDDEN ) || tagTypeName . equals ( IMAGE ) || tagTypeName . equals ( PASSWORD ) ) { String value = valueToString ( name , valueObject ) ; if ( value == null ) { return ; } tag . setAttribute ( VALUE , value ) ; } else if ( tagTypeName . equals ( CHECKBOX ) ) { CharSequence tagValue = tag . getAttributeValue ( VALUE ) ; if ( tagValue == null ) { tagValue = TRUE ; } tagValue = tagValue . toString ( ) ; if ( valueObject . getClass ( ) . isArray ( ) ) { // checkbox group String [ ] vs = StringUtil . toStringArray ( valueObject ) ; for ( String vsk : vs ) { if ( ( vsk != null ) && ( vsk . contentEquals ( tagValue ) ) ) { tag . setAttribute ( CHECKED , null ) ; } } } else if ( tagValue . equals ( valueObject . toString ( ) ) ) { tag . setAttribute ( CHECKED , null ) ; } } else if ( tagType . equals ( RADIO ) ) { CharSequence tagValue = tag . getAttributeValue ( VALUE ) ; if ( tagValue != null ) { tagValue = tagValue . toString ( ) ; if ( tagValue . equals ( valueObject . toString ( ) ) ) { tag . setAttribute ( CHECKED , null ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts value to a string . [CODESPLIT] protected String valueToString ( final String name , final Object valueObject ) { if ( ! valueObject . getClass ( ) . isArray ( ) ) { return valueObject . toString ( ) ; } // array String [ ] array = ( String [ ] ) valueObject ; if ( valueNameIndexes == null ) { valueNameIndexes = new HashMap <> ( ) ; } MutableInteger index = valueNameIndexes . get ( name ) ; if ( index == null ) { index = new MutableInteger ( 0 ) ; valueNameIndexes . put ( name , index ) ; } if ( index . value >= array . length ) { return null ; } String result = array [ index . value ] ; index . value ++ ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures an interceptor . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T extends ActionInterceptor > MadvocRouter interceptor ( final Class < T > actionInterceptorClass ) { interceptorsManager . resolve ( actionInterceptorClass ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures an interceptor . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T extends ActionInterceptor > MadvocRouter interceptor ( final Class < T > actionInterceptorClass , final Consumer < T > interceptorConsumer ) { T interceptor = ( T ) interceptorsManager . resolve ( actionInterceptorClass ) ; interceptorConsumer . accept ( interceptor ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns action filter instance for further configuration . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T extends ActionFilter > MadvocRouter filter ( final Class < T > actionFilterClass ) { filtersManager . resolve ( actionFilterClass ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if node matches the pseudoclass within current results . [CODESPLIT] public boolean match ( final List < Node > currentResults , final Node node , final int index , final E expression ) { return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns pseudo - function name . [CODESPLIT] public String getPseudoFunctionName ( ) { String name = getClass ( ) . getSimpleName ( ) . toLowerCase ( ) ; name = name . replace ( ' ' , ' ' ) ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns action string in form actionClass#actionMethod . [CODESPLIT] public String createActionString ( ) { if ( actionHandler != null ) { return actionHandler . getClass ( ) . getName ( ) ; } String className = actionClass . getName ( ) ; final int ndx = className . indexOf ( \"$$\" ) ; if ( ndx != - 1 ) { className = className . substring ( 0 , ndx ) ; } return className + ' ' + actionClassMethod . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Integer get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Integer . valueOf ( rs . getInt ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Integer value , final int dbSqlType ) throws SQLException { st . setInt ( index , value . intValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves all properties for given type . [CODESPLIT] public PropertyInjectionPoint [ ] resolve ( Class type , final boolean autowire ) { final List < PropertyInjectionPoint > list = new ArrayList <> ( ) ; final Set < String > usedPropertyNames = new HashSet <> ( ) ; // lookup fields while ( type != Object . class ) { final ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; final PropertyDescriptor [ ] allPropertyDescriptors = cd . getAllPropertyDescriptors ( ) ; for ( PropertyDescriptor propertyDescriptor : allPropertyDescriptors ) { if ( propertyDescriptor . isGetterOnly ( ) ) { continue ; } if ( usedPropertyNames . contains ( propertyDescriptor . getName ( ) ) ) { continue ; } Class propertyType = propertyDescriptor . getType ( ) ; if ( ClassUtil . isTypeOf ( propertyType , Collection . class ) ) { continue ; } BeanReferences reference = referencesResolver . readReferenceFromAnnotation ( propertyDescriptor ) ; if ( reference == null ) { if ( ! autowire ) { continue ; } else { reference = referencesResolver . buildDefaultReference ( propertyDescriptor ) ; } } list . add ( new PropertyInjectionPoint ( propertyDescriptor , reference ) ) ; usedPropertyNames . add ( propertyDescriptor . getName ( ) ) ; } // go to the supertype type = type . getSuperclass ( ) ; } final PropertyInjectionPoint [ ] fields ; if ( list . isEmpty ( ) ) { fields = PropertyInjectionPoint . EMPTY ; } else { fields = list . toArray ( new PropertyInjectionPoint [ 0 ] ) ; } return fields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to the SOCKS4 proxy and returns proxified socket . [CODESPLIT] private Socket createSocks4ProxySocket ( final String host , final int port ) { Socket socket = null ; final String proxyHost = proxy . getProxyAddress ( ) ; final int proxyPort = proxy . getProxyPort ( ) ; final String user = proxy . getProxyUsername ( ) ; try { socket = Sockets . connect ( proxyHost , proxyPort , connectionTimeout ) ; final InputStream in = socket . getInputStream ( ) ; final OutputStream out = socket . getOutputStream ( ) ; socket . setTcpNoDelay ( true ) ; byte [ ] buf = new byte [ 1024 ] ; // 1) CONNECT int index = 0 ; buf [ index ++ ] = 4 ; buf [ index ++ ] = 1 ; buf [ index ++ ] = ( byte ) ( port >>> 8 ) ; buf [ index ++ ] = ( byte ) ( port & 0xff ) ; InetAddress addr = InetAddress . getByName ( host ) ; byte [ ] byteAddress = addr . getAddress ( ) ; for ( byte byteAddres : byteAddress ) { buf [ index ++ ] = byteAddres ; } if ( user != null ) { System . arraycopy ( user . getBytes ( ) , 0 , buf , index , user . length ( ) ) ; index += user . length ( ) ; } buf [ index ++ ] = 0 ; out . write ( buf , 0 , index ) ; // 2) RESPONSE int len = 6 ; int s = 0 ; while ( s < len ) { int i = in . read ( buf , s , len - s ) ; if ( i <= 0 ) { throw new HttpException ( ProxyInfo . ProxyType . SOCKS4 , \"stream is closed\" ) ; } s += i ; } if ( buf [ 0 ] != 0 ) { throw new HttpException ( ProxyInfo . ProxyType . SOCKS4 , \"proxy returned VN \" + buf [ 0 ] ) ; } if ( buf [ 1 ] != 90 ) { try { socket . close ( ) ; } catch ( Exception ignore ) { } throw new HttpException ( ProxyInfo . ProxyType . SOCKS4 , \"proxy returned CD \" + buf [ 1 ] ) ; } byte [ ] temp = new byte [ 2 ] ; in . read ( temp , 0 , 2 ) ; return socket ; } catch ( RuntimeException rtex ) { closeSocket ( socket ) ; throw rtex ; } catch ( Exception ex ) { closeSocket ( socket ) ; throw new HttpException ( ProxyInfo . ProxyType . SOCKS4 , ex . toString ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a { @link #type } attribute . This method must return a <i > new< / i > { @link Attribute } object of type { @link #type } corresponding to the length bytes starting at offset in the given ClassReader . [CODESPLIT] protected Attribute read ( final ClassReader classReader , final int offset , final int length , final char [ ] charBuffer , final int codeAttributeOffset , final Label [ ] labels ) { Attribute attribute = new Attribute ( type ) ; attribute . content = new byte [ length ] ; System . arraycopy ( classReader . b , offset , attribute . content , 0 , length ) ; return attribute ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the byte array form of the content of this attribute . The 6 header bytes ( attribute_name_index and attribute_length ) must <i > not< / i > be added in the returned ByteVector . [CODESPLIT] protected ByteVector write ( final ClassWriter classWriter , final byte [ ] code , final int codeLength , final int maxStack , final int maxLocals ) { return new ByteVector ( content ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of attributes of the attribute list that begins with this attribute . [CODESPLIT] final int getAttributeCount ( ) { int count = 0 ; Attribute attribute = this ; while ( attribute != null ) { count += 1 ; attribute = attribute . nextAttribute ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the total size in bytes of all the attributes in the attribute list that begins with this attribute . This size includes the 6 header bytes ( attribute_name_index and attribute_length ) per attribute . Also adds the attribute type names to the constant pool . [CODESPLIT] final int computeAttributesSize ( final SymbolTable symbolTable ) { final byte [ ] code = null ; final int codeLength = 0 ; final int maxStack = - 1 ; final int maxLocals = - 1 ; return computeAttributesSize ( symbolTable , code , codeLength , maxStack , maxLocals ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the total size in bytes of all the attributes in the attribute list that begins with this attribute . This size includes the 6 header bytes ( attribute_name_index and attribute_length ) per attribute . Also adds the attribute type names to the constant pool . [CODESPLIT] final int computeAttributesSize ( final SymbolTable symbolTable , final byte [ ] code , final int codeLength , final int maxStack , final int maxLocals ) { final ClassWriter classWriter = symbolTable . classWriter ; int size = 0 ; Attribute attribute = this ; while ( attribute != null ) { symbolTable . addConstantUtf8 ( attribute . type ) ; size += 6 + attribute . write ( classWriter , code , codeLength , maxStack , maxLocals ) . length ; attribute = attribute . nextAttribute ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts all the attributes of the attribute list that begins with this attribute in the given byte vector . This includes the 6 header bytes ( attribute_name_index and attribute_length ) per attribute . [CODESPLIT] final void putAttributes ( final SymbolTable symbolTable , final ByteVector output ) { final byte [ ] code = null ; final int codeLength = 0 ; final int maxStack = - 1 ; final int maxLocals = - 1 ; putAttributes ( symbolTable , code , codeLength , maxStack , maxLocals , output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts all the attributes of the attribute list that begins with this attribute in the given byte vector . This includes the 6 header bytes ( attribute_name_index and attribute_length ) per attribute . [CODESPLIT] final void putAttributes ( final SymbolTable symbolTable , final byte [ ] code , final int codeLength , final int maxStack , final int maxLocals , final ByteVector output ) { final ClassWriter classWriter = symbolTable . classWriter ; Attribute attribute = this ; while ( attribute != null ) { ByteVector attributeContent = attribute . write ( classWriter , code , codeLength , maxStack , maxLocals ) ; // Put attribute_name_index and attribute_length. output . putShort ( symbolTable . addConstantUtf8 ( attribute . type ) ) . putInt ( attributeContent . length ) ; output . putByteArray ( attributeContent . data , 0 , attributeContent . length ) ; attribute = attribute . nextAttribute ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all action results as new set . [CODESPLIT] public Set < ActionResult > getAllActionResults ( ) { final Set < ActionResult > set = new HashSet <> ( allResults . size ( ) ) ; allResults . forEachValue ( set :: add ) ; return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers new action result instance . If action result of the same class is already registered registration will be skipped . If result for the same result type or same target class exist it will be replaced! However default Jodd results will <i > never< / i > replace other results . After the registration results are initialized . [CODESPLIT] protected ActionResult register ( final ActionResult result ) { Class < ? extends ActionResult > actionResultClass = result . getClass ( ) ; // check existing ActionResult existingResult = allResults . get ( actionResultClass ) ; if ( existingResult != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"ActionResult already registered: \" + actionResultClass ) ; } return existingResult ; } allResults . put ( actionResultClass , result ) ; // + init initializeResult ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for action result and { [CODESPLIT] private ActionResult lookupAndRegisterIfMissing ( final Class < ? extends ActionResult > actionResultClass ) { ActionResult actionResult = allResults . get ( actionResultClass ) ; if ( actionResult == null ) { actionResult = register ( actionResultClass ) ; } return actionResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for { [CODESPLIT] public ActionResult lookup ( final ActionRequest actionRequest , final Object resultObject ) { ActionResult actionResultHandler = null ; // + read @RenderWith value on method { final ActionRuntime actionRuntime = actionRequest . getActionRuntime ( ) ; final Class < ? extends ActionResult > actionResultClass = actionRuntime . getActionResult ( ) ; if ( actionResultClass != null ) { actionResultHandler = lookupAndRegisterIfMissing ( actionResultClass ) ; } } // + use @RenderWith value on resulting object if exist if ( actionResultHandler == null && resultObject != null ) { final RenderWith renderWith = resultObject . getClass ( ) . getAnnotation ( RenderWith . class ) ; if ( renderWith != null ) { actionResultHandler = lookupAndRegisterIfMissing ( renderWith . value ( ) ) ; } else if ( resultObject instanceof ActionResult ) { // special case - returned value is already the ActionResult actionResultHandler = ( ActionResult ) resultObject ; } } // + use action configuration if ( actionResultHandler == null ) { final ActionRuntime actionRuntime = actionRequest . getActionRuntime ( ) ; final Class < ? extends ActionResult > actionResultClass = actionRuntime . getDefaultActionResult ( ) ; if ( actionResultClass != null ) { actionResultHandler = lookupAndRegisterIfMissing ( actionResultClass ) ; } } if ( actionResultHandler == null ) { throw new MadvocException ( \"ActionResult not found for: \" + resultObject ) ; } // set action result object into action request! actionRequest . bindActionResult ( resultObject ) ; return actionResultHandler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { [CODESPLIT] protected ActionResult createResult ( final Class < ? extends ActionResult > actionResultClass ) { try { return ClassUtil . newInstance ( actionResultClass ) ; } catch ( Exception ex ) { throw new MadvocException ( \"Invalid Madvoc result: \" + actionResultClass , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match if one character equals to any of the given character . [CODESPLIT] public static boolean equalsOne ( final char c , final CharSequence match ) { for ( int i = 0 ; i < match . length ( ) ; i ++ ) { char aMatch = match . charAt ( i ) ; if ( c == aMatch ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds index of the first character in given charsequence the matches any from the given set of characters . [CODESPLIT] public static int findFirstEqual ( final CharSequence source , final int index , final CharSequence match ) { for ( int i = index ; i < source . length ( ) ; i ++ ) { if ( equalsOne ( source . charAt ( i ) , match ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds index of the first character in given array the matches any from the given set of characters . [CODESPLIT] public static int findFirstEqual ( final char [ ] source , final int index , final char match ) { for ( int i = index ; i < source . length ; i ++ ) { if ( source [ i ] == match ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds several arguments . [CODESPLIT] public CommandLine args ( final String ... arguments ) { if ( arguments != null && arguments . length > 0 ) { Collections . addAll ( cmdLine , arguments ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets environment variable . [CODESPLIT] public CommandLine env ( final String key , final String value ) { if ( env == null ) { env = new HashMap <> ( ) ; } env . put ( key , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs command and returns process result . [CODESPLIT] public ProcessRunner . ProcessResult run ( ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; out = err = baos ; try { baos . write ( StringUtil . join ( cmdLine , ' ' ) . getBytes ( ) ) ; baos . write ( StringPool . BYTES_NEW_LINE ) ; } catch ( IOException ignore ) { } ProcessBuilder processBuilder = new ProcessBuilder ( ) ; processBuilder . command ( cmdLine ) ; if ( cleanEnvironment ) { processBuilder . environment ( ) . clear ( ) ; } if ( env != null ) { processBuilder . environment ( ) . putAll ( env ) ; } processBuilder . directory ( workingDirectory ) ; Process process = null ; try { process = processBuilder . start ( ) ; } catch ( IOException ioex ) { return writeException ( baos , ioex ) ; } StreamGobbler outputGobbler = new StreamGobbler ( process . getInputStream ( ) , out , outPrefix ) ; StreamGobbler errorGobbler = new StreamGobbler ( process . getErrorStream ( ) , err , errPrefix ) ; outputGobbler . start ( ) ; errorGobbler . start ( ) ; int result ; try { result = process . waitFor ( ) ; } catch ( InterruptedException iex ) { return writeException ( baos , iex ) ; } outputGobbler . waitFor ( ) ; errorGobbler . waitFor ( ) ; return new ProcessRunner . ProcessResult ( result , baos . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke the listener based on type . Not very OOP but works . [CODESPLIT] public static void invoke ( final Object listener , final Class listenerType ) { if ( listenerType == Init . class ) { ( ( Init ) listener ) . init ( ) ; return ; } if ( listenerType == Start . class ) { ( ( Start ) listener ) . start ( ) ; return ; } if ( listenerType == Ready . class ) { ( ( Ready ) listener ) . ready ( ) ; return ; } if ( listenerType == Stop . class ) { ( ( Stop ) listener ) . stop ( ) ; return ; } throw new MadvocException ( \"Invalid listener\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets this frame to the value of the given frame . [CODESPLIT] final void copyFrom ( final Frame frame ) { inputLocals = frame . inputLocals ; inputStack = frame . inputStack ; outputStackStart = 0 ; outputLocals = frame . outputLocals ; outputStack = frame . outputStack ; outputStackTop = frame . outputStackTop ; initializationCount = frame . initializationCount ; initializations = frame . initializations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the abstract type corresponding to the given public API frame element type . [CODESPLIT] static int getAbstractTypeFromApiFormat ( final SymbolTable symbolTable , final Object type ) { if ( type instanceof Integer ) { return CONSTANT_KIND | ( ( Integer ) type ) . intValue ( ) ; } else if ( type instanceof String ) { String descriptor = Type . getObjectType ( ( String ) type ) . getDescriptor ( ) ; return getAbstractTypeFromDescriptor ( symbolTable , descriptor , 0 ) ; } else { return UNINITIALIZED_KIND | symbolTable . addUninitializedType ( \"\" , ( ( Label ) type ) . bytecodeOffset ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the abstract type corresponding to the given type descriptor . [CODESPLIT] private static int getAbstractTypeFromDescriptor ( final SymbolTable symbolTable , final String buffer , final int offset ) { String internalName ; switch ( buffer . charAt ( offset ) ) { case ' ' : return 0 ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : return INTEGER ; case ' ' : return FLOAT ; case ' ' : return LONG ; case ' ' : return DOUBLE ; case ' ' : internalName = buffer . substring ( offset + 1 , buffer . length ( ) - 1 ) ; return REFERENCE_KIND | symbolTable . addType ( internalName ) ; case ' ' : int elementDescriptorOffset = offset + 1 ; while ( buffer . charAt ( elementDescriptorOffset ) == ' ' ) { ++ elementDescriptorOffset ; } int typeValue ; switch ( buffer . charAt ( elementDescriptorOffset ) ) { case ' ' : typeValue = BOOLEAN ; break ; case ' ' : typeValue = CHAR ; break ; case ' ' : typeValue = BYTE ; break ; case ' ' : typeValue = SHORT ; break ; case ' ' : typeValue = INTEGER ; break ; case ' ' : typeValue = FLOAT ; break ; case ' ' : typeValue = LONG ; break ; case ' ' : typeValue = DOUBLE ; break ; case ' ' : internalName = buffer . substring ( elementDescriptorOffset + 1 , buffer . length ( ) - 1 ) ; typeValue = REFERENCE_KIND | symbolTable . addType ( internalName ) ; break ; default : throw new IllegalArgumentException ( ) ; } return ( ( elementDescriptorOffset - offset ) << DIM_SHIFT ) | typeValue ; default : throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the input frame from the given method description . This method is used to initialize the first frame of a method which is implicit ( i . e . not stored explicitly in the StackMapTable attribute ) . [CODESPLIT] final void setInputFrameFromDescriptor ( final SymbolTable symbolTable , final int access , final String descriptor , final int maxLocals ) { inputLocals = new int [ maxLocals ] ; inputStack = new int [ 0 ] ; int inputLocalIndex = 0 ; if ( ( access & Opcodes . ACC_STATIC ) == 0 ) { if ( ( access & Constants . ACC_CONSTRUCTOR ) == 0 ) { inputLocals [ inputLocalIndex ++ ] = REFERENCE_KIND | symbolTable . addType ( symbolTable . getClassName ( ) ) ; } else { inputLocals [ inputLocalIndex ++ ] = UNINITIALIZED_THIS ; } } for ( Type argumentType : Type . getArgumentTypes ( descriptor ) ) { int abstractType = getAbstractTypeFromDescriptor ( symbolTable , argumentType . getDescriptor ( ) , 0 ) ; inputLocals [ inputLocalIndex ++ ] = abstractType ; if ( abstractType == LONG || abstractType == DOUBLE ) { inputLocals [ inputLocalIndex ++ ] = TOP ; } } while ( inputLocalIndex < maxLocals ) { inputLocals [ inputLocalIndex ++ ] = TOP ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the input frame from the given public API frame description . [CODESPLIT] final void setInputFrameFromApiFormat ( final SymbolTable symbolTable , final int numLocal , final Object [ ] local , final int numStack , final Object [ ] stack ) { int inputLocalIndex = 0 ; for ( int i = 0 ; i < numLocal ; ++ i ) { inputLocals [ inputLocalIndex ++ ] = getAbstractTypeFromApiFormat ( symbolTable , local [ i ] ) ; if ( local [ i ] == Opcodes . LONG || local [ i ] == Opcodes . DOUBLE ) { inputLocals [ inputLocalIndex ++ ] = TOP ; } } while ( inputLocalIndex < inputLocals . length ) { inputLocals [ inputLocalIndex ++ ] = TOP ; } int numStackTop = 0 ; for ( int i = 0 ; i < numStack ; ++ i ) { if ( stack [ i ] == Opcodes . LONG || stack [ i ] == Opcodes . DOUBLE ) { ++ numStackTop ; } } inputStack = new int [ numStack + numStackTop ] ; int inputStackIndex = 0 ; for ( int i = 0 ; i < numStack ; ++ i ) { inputStack [ inputStackIndex ++ ] = getAbstractTypeFromApiFormat ( symbolTable , stack [ i ] ) ; if ( stack [ i ] == Opcodes . LONG || stack [ i ] == Opcodes . DOUBLE ) { inputStack [ inputStackIndex ++ ] = TOP ; } } outputStackTop = 0 ; initializationCount = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the abstract type stored at the given local variable index in the output frame . [CODESPLIT] private int getLocal ( final int localIndex ) { if ( outputLocals == null || localIndex >= outputLocals . length ) { // If this local has never been assigned in this basic block, it is still equal to its value // in the input frame. return LOCAL_KIND | localIndex ; } else { int abstractType = outputLocals [ localIndex ] ; if ( abstractType == 0 ) { // If this local has never been assigned in this basic block, so it is still equal to its // value in the input frame. abstractType = outputLocals [ localIndex ] = LOCAL_KIND | localIndex ; } return abstractType ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the abstract type stored at the given local variable index in the output frame . [CODESPLIT] private void setLocal ( final int localIndex , final int abstractType ) { // Create and/or resize the output local variables array if necessary. if ( outputLocals == null ) { outputLocals = new int [ 10 ] ; } int outputLocalsLength = outputLocals . length ; if ( localIndex >= outputLocalsLength ) { int [ ] newOutputLocals = new int [ Math . max ( localIndex + 1 , 2 * outputLocalsLength ) ] ; System . arraycopy ( outputLocals , 0 , newOutputLocals , 0 , outputLocalsLength ) ; outputLocals = newOutputLocals ; } // Set the local variable. outputLocals [ localIndex ] = abstractType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes the given abstract type on the output frame stack . [CODESPLIT] private void push ( final int abstractType ) { // Create and/or resize the output stack array if necessary. if ( outputStack == null ) { outputStack = new int [ 10 ] ; } int outputStackLength = outputStack . length ; if ( outputStackTop >= outputStackLength ) { int [ ] newOutputStack = new int [ Math . max ( outputStackTop + 1 , 2 * outputStackLength ) ] ; System . arraycopy ( outputStack , 0 , newOutputStack , 0 , outputStackLength ) ; outputStack = newOutputStack ; } // Pushes the abstract type on the output stack. outputStack [ outputStackTop ++ ] = abstractType ; // Updates the maximum size reached by the output stack, if needed (note that this size is // relative to the input stack size, which is not known yet). short outputStackSize = ( short ) ( outputStackStart + outputStackTop ) ; if ( outputStackSize > owner . outputStackMax ) { owner . outputStackMax = outputStackSize ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes the abstract type corresponding to the given descriptor on the output frame stack . [CODESPLIT] private void push ( final SymbolTable symbolTable , final String descriptor ) { int typeDescriptorOffset = descriptor . charAt ( 0 ) == ' ' ? descriptor . indexOf ( ' ' ) + 1 : 0 ; int abstractType = getAbstractTypeFromDescriptor ( symbolTable , descriptor , typeDescriptorOffset ) ; if ( abstractType != 0 ) { push ( abstractType ) ; if ( abstractType == LONG || abstractType == DOUBLE ) { push ( TOP ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops the given number of abstract types from the output frame stack . [CODESPLIT] private void pop ( final int elements ) { if ( outputStackTop >= elements ) { outputStackTop -= elements ; } else { // If the number of elements to be popped is greater than the number of elements in the output // stack, clear it, and pop the remaining elements from the input stack. outputStackStart -= elements - outputStackTop ; outputStackTop = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops as many abstract types from the output frame stack as described by the given descriptor . [CODESPLIT] private void pop ( final String descriptor ) { char firstDescriptorChar = descriptor . charAt ( 0 ) ; if ( firstDescriptorChar == ' ' ) { pop ( ( Type . getArgumentsAndReturnSizes ( descriptor ) >> 2 ) - 1 ) ; } else if ( firstDescriptorChar == ' ' || firstDescriptorChar == ' ' ) { pop ( 2 ) ; } else { pop ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an abstract type to the list of types on which a constructor is invoked in the basic block . [CODESPLIT] private void addInitializedType ( final int abstractType ) { // Create and/or resize the initializations array if necessary. if ( initializations == null ) { initializations = new int [ 2 ] ; } int initializationsLength = initializations . length ; if ( initializationCount >= initializationsLength ) { int [ ] newInitializations = new int [ Math . max ( initializationCount + 1 , 2 * initializationsLength ) ] ; System . arraycopy ( initializations , 0 , newInitializations , 0 , initializationsLength ) ; initializations = newInitializations ; } // Store the abstract type. initializations [ initializationCount ++ ] = abstractType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the initialized abstract type corresponding to the given abstract type . [CODESPLIT] private int getInitializedType ( final SymbolTable symbolTable , final int abstractType ) { if ( abstractType == UNINITIALIZED_THIS || ( abstractType & ( DIM_MASK | KIND_MASK ) ) == UNINITIALIZED_KIND ) { for ( int i = 0 ; i < initializationCount ; ++ i ) { int initializedType = initializations [ i ] ; int dim = initializedType & DIM_MASK ; int kind = initializedType & KIND_MASK ; int value = initializedType & VALUE_MASK ; if ( kind == LOCAL_KIND ) { initializedType = dim + inputLocals [ value ] ; } else if ( kind == STACK_KIND ) { initializedType = dim + inputStack [ inputStack . length - value ] ; } if ( abstractType == initializedType ) { if ( abstractType == UNINITIALIZED_THIS ) { return REFERENCE_KIND | symbolTable . addType ( symbolTable . getClassName ( ) ) ; } else { return REFERENCE_KIND | symbolTable . addType ( symbolTable . getType ( abstractType & VALUE_MASK ) . value ) ; } } } } return abstractType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simulates the action of the given instruction on the output stack frame . [CODESPLIT] void execute ( final int opcode , final int arg , final Symbol argSymbol , final SymbolTable symbolTable ) { // Abstract types popped from the stack or read from local variables. int abstractType1 ; int abstractType2 ; int abstractType3 ; int abstractType4 ; switch ( opcode ) { case Opcodes . NOP : case Opcodes . INEG : case Opcodes . LNEG : case Opcodes . FNEG : case Opcodes . DNEG : case Opcodes . I2B : case Opcodes . I2C : case Opcodes . I2S : case Opcodes . GOTO : case Opcodes . RETURN : break ; case Opcodes . ACONST_NULL : push ( NULL ) ; break ; case Opcodes . ICONST_M1 : case Opcodes . ICONST_0 : case Opcodes . ICONST_1 : case Opcodes . ICONST_2 : case Opcodes . ICONST_3 : case Opcodes . ICONST_4 : case Opcodes . ICONST_5 : case Opcodes . BIPUSH : case Opcodes . SIPUSH : case Opcodes . ILOAD : push ( INTEGER ) ; break ; case Opcodes . LCONST_0 : case Opcodes . LCONST_1 : case Opcodes . LLOAD : push ( LONG ) ; push ( TOP ) ; break ; case Opcodes . FCONST_0 : case Opcodes . FCONST_1 : case Opcodes . FCONST_2 : case Opcodes . FLOAD : push ( FLOAT ) ; break ; case Opcodes . DCONST_0 : case Opcodes . DCONST_1 : case Opcodes . DLOAD : push ( DOUBLE ) ; push ( TOP ) ; break ; case Opcodes . LDC : switch ( argSymbol . tag ) { case Symbol . CONSTANT_INTEGER_TAG : push ( INTEGER ) ; break ; case Symbol . CONSTANT_LONG_TAG : push ( LONG ) ; push ( TOP ) ; break ; case Symbol . CONSTANT_FLOAT_TAG : push ( FLOAT ) ; break ; case Symbol . CONSTANT_DOUBLE_TAG : push ( DOUBLE ) ; push ( TOP ) ; break ; case Symbol . CONSTANT_CLASS_TAG : push ( REFERENCE_KIND | symbolTable . addType ( \"java/lang/Class\" ) ) ; break ; case Symbol . CONSTANT_STRING_TAG : push ( REFERENCE_KIND | symbolTable . addType ( \"java/lang/String\" ) ) ; break ; case Symbol . CONSTANT_METHOD_TYPE_TAG : push ( REFERENCE_KIND | symbolTable . addType ( \"java/lang/invoke/MethodType\" ) ) ; break ; case Symbol . CONSTANT_METHOD_HANDLE_TAG : push ( REFERENCE_KIND | symbolTable . addType ( \"java/lang/invoke/MethodHandle\" ) ) ; break ; case Symbol . CONSTANT_DYNAMIC_TAG : push ( symbolTable , argSymbol . value ) ; break ; default : throw new AssertionError ( ) ; } break ; case Opcodes . ALOAD : push ( getLocal ( arg ) ) ; break ; case Opcodes . LALOAD : case Opcodes . D2L : pop ( 2 ) ; push ( LONG ) ; push ( TOP ) ; break ; case Opcodes . DALOAD : case Opcodes . L2D : pop ( 2 ) ; push ( DOUBLE ) ; push ( TOP ) ; break ; case Opcodes . AALOAD : pop ( 1 ) ; abstractType1 = pop ( ) ; push ( abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1 ) ; break ; case Opcodes . ISTORE : case Opcodes . FSTORE : case Opcodes . ASTORE : abstractType1 = pop ( ) ; setLocal ( arg , abstractType1 ) ; if ( arg > 0 ) { int previousLocalType = getLocal ( arg - 1 ) ; if ( previousLocalType == LONG || previousLocalType == DOUBLE ) { setLocal ( arg - 1 , TOP ) ; } else if ( ( previousLocalType & KIND_MASK ) == LOCAL_KIND || ( previousLocalType & KIND_MASK ) == STACK_KIND ) { // The type of the previous local variable is not known yet, but if it later appears // to be LONG or DOUBLE, we should then use TOP instead. setLocal ( arg - 1 , previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG ) ; } } break ; case Opcodes . LSTORE : case Opcodes . DSTORE : pop ( 1 ) ; abstractType1 = pop ( ) ; setLocal ( arg , abstractType1 ) ; setLocal ( arg + 1 , TOP ) ; if ( arg > 0 ) { int previousLocalType = getLocal ( arg - 1 ) ; if ( previousLocalType == LONG || previousLocalType == DOUBLE ) { setLocal ( arg - 1 , TOP ) ; } else if ( ( previousLocalType & KIND_MASK ) == LOCAL_KIND || ( previousLocalType & KIND_MASK ) == STACK_KIND ) { // The type of the previous local variable is not known yet, but if it later appears // to be LONG or DOUBLE, we should then use TOP instead. setLocal ( arg - 1 , previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG ) ; } } break ; case Opcodes . IASTORE : case Opcodes . BASTORE : case Opcodes . CASTORE : case Opcodes . SASTORE : case Opcodes . FASTORE : case Opcodes . AASTORE : pop ( 3 ) ; break ; case Opcodes . LASTORE : case Opcodes . DASTORE : pop ( 4 ) ; break ; case Opcodes . POP : case Opcodes . IFEQ : case Opcodes . IFNE : case Opcodes . IFLT : case Opcodes . IFGE : case Opcodes . IFGT : case Opcodes . IFLE : case Opcodes . IRETURN : case Opcodes . FRETURN : case Opcodes . ARETURN : case Opcodes . TABLESWITCH : case Opcodes . LOOKUPSWITCH : case Opcodes . ATHROW : case Opcodes . MONITORENTER : case Opcodes . MONITOREXIT : case Opcodes . IFNULL : case Opcodes . IFNONNULL : pop ( 1 ) ; break ; case Opcodes . POP2 : case Opcodes . IF_ICMPEQ : case Opcodes . IF_ICMPNE : case Opcodes . IF_ICMPLT : case Opcodes . IF_ICMPGE : case Opcodes . IF_ICMPGT : case Opcodes . IF_ICMPLE : case Opcodes . IF_ACMPEQ : case Opcodes . IF_ACMPNE : case Opcodes . LRETURN : case Opcodes . DRETURN : pop ( 2 ) ; break ; case Opcodes . DUP : abstractType1 = pop ( ) ; push ( abstractType1 ) ; push ( abstractType1 ) ; break ; case Opcodes . DUP_X1 : abstractType1 = pop ( ) ; abstractType2 = pop ( ) ; push ( abstractType1 ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; break ; case Opcodes . DUP_X2 : abstractType1 = pop ( ) ; abstractType2 = pop ( ) ; abstractType3 = pop ( ) ; push ( abstractType1 ) ; push ( abstractType3 ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; break ; case Opcodes . DUP2 : abstractType1 = pop ( ) ; abstractType2 = pop ( ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; break ; case Opcodes . DUP2_X1 : abstractType1 = pop ( ) ; abstractType2 = pop ( ) ; abstractType3 = pop ( ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; push ( abstractType3 ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; break ; case Opcodes . DUP2_X2 : abstractType1 = pop ( ) ; abstractType2 = pop ( ) ; abstractType3 = pop ( ) ; abstractType4 = pop ( ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; push ( abstractType4 ) ; push ( abstractType3 ) ; push ( abstractType2 ) ; push ( abstractType1 ) ; break ; case Opcodes . SWAP : abstractType1 = pop ( ) ; abstractType2 = pop ( ) ; push ( abstractType1 ) ; push ( abstractType2 ) ; break ; case Opcodes . IALOAD : case Opcodes . BALOAD : case Opcodes . CALOAD : case Opcodes . SALOAD : case Opcodes . IADD : case Opcodes . ISUB : case Opcodes . IMUL : case Opcodes . IDIV : case Opcodes . IREM : case Opcodes . IAND : case Opcodes . IOR : case Opcodes . IXOR : case Opcodes . ISHL : case Opcodes . ISHR : case Opcodes . IUSHR : case Opcodes . L2I : case Opcodes . D2I : case Opcodes . FCMPL : case Opcodes . FCMPG : pop ( 2 ) ; push ( INTEGER ) ; break ; case Opcodes . LADD : case Opcodes . LSUB : case Opcodes . LMUL : case Opcodes . LDIV : case Opcodes . LREM : case Opcodes . LAND : case Opcodes . LOR : case Opcodes . LXOR : pop ( 4 ) ; push ( LONG ) ; push ( TOP ) ; break ; case Opcodes . FALOAD : case Opcodes . FADD : case Opcodes . FSUB : case Opcodes . FMUL : case Opcodes . FDIV : case Opcodes . FREM : case Opcodes . L2F : case Opcodes . D2F : pop ( 2 ) ; push ( FLOAT ) ; break ; case Opcodes . DADD : case Opcodes . DSUB : case Opcodes . DMUL : case Opcodes . DDIV : case Opcodes . DREM : pop ( 4 ) ; push ( DOUBLE ) ; push ( TOP ) ; break ; case Opcodes . LSHL : case Opcodes . LSHR : case Opcodes . LUSHR : pop ( 3 ) ; push ( LONG ) ; push ( TOP ) ; break ; case Opcodes . IINC : setLocal ( arg , INTEGER ) ; break ; case Opcodes . I2L : case Opcodes . F2L : pop ( 1 ) ; push ( LONG ) ; push ( TOP ) ; break ; case Opcodes . I2F : pop ( 1 ) ; push ( FLOAT ) ; break ; case Opcodes . I2D : case Opcodes . F2D : pop ( 1 ) ; push ( DOUBLE ) ; push ( TOP ) ; break ; case Opcodes . F2I : case Opcodes . ARRAYLENGTH : case Opcodes . INSTANCEOF : pop ( 1 ) ; push ( INTEGER ) ; break ; case Opcodes . LCMP : case Opcodes . DCMPL : case Opcodes . DCMPG : pop ( 4 ) ; push ( INTEGER ) ; break ; case Opcodes . JSR : case Opcodes . RET : throw new IllegalArgumentException ( \"JSR/RET are not supported with computeFrames option\" ) ; case Opcodes . GETSTATIC : push ( symbolTable , argSymbol . value ) ; break ; case Opcodes . PUTSTATIC : pop ( argSymbol . value ) ; break ; case Opcodes . GETFIELD : pop ( 1 ) ; push ( symbolTable , argSymbol . value ) ; break ; case Opcodes . PUTFIELD : pop ( argSymbol . value ) ; pop ( ) ; break ; case Opcodes . INVOKEVIRTUAL : case Opcodes . INVOKESPECIAL : case Opcodes . INVOKESTATIC : case Opcodes . INVOKEINTERFACE : pop ( argSymbol . value ) ; if ( opcode != Opcodes . INVOKESTATIC ) { abstractType1 = pop ( ) ; if ( opcode == Opcodes . INVOKESPECIAL && argSymbol . name . charAt ( 0 ) == ' ' ) { addInitializedType ( abstractType1 ) ; } } push ( symbolTable , argSymbol . value ) ; break ; case Opcodes . INVOKEDYNAMIC : pop ( argSymbol . value ) ; push ( symbolTable , argSymbol . value ) ; break ; case Opcodes . NEW : push ( UNINITIALIZED_KIND | symbolTable . addUninitializedType ( argSymbol . value , arg ) ) ; break ; case Opcodes . NEWARRAY : pop ( ) ; switch ( arg ) { case Opcodes . T_BOOLEAN : push ( ARRAY_OF | BOOLEAN ) ; break ; case Opcodes . T_CHAR : push ( ARRAY_OF | CHAR ) ; break ; case Opcodes . T_BYTE : push ( ARRAY_OF | BYTE ) ; break ; case Opcodes . T_SHORT : push ( ARRAY_OF | SHORT ) ; break ; case Opcodes . T_INT : push ( ARRAY_OF | INTEGER ) ; break ; case Opcodes . T_FLOAT : push ( ARRAY_OF | FLOAT ) ; break ; case Opcodes . T_DOUBLE : push ( ARRAY_OF | DOUBLE ) ; break ; case Opcodes . T_LONG : push ( ARRAY_OF | LONG ) ; break ; default : throw new IllegalArgumentException ( ) ; } break ; case Opcodes . ANEWARRAY : String arrayElementType = argSymbol . value ; pop ( ) ; if ( arrayElementType . charAt ( 0 ) == ' ' ) { push ( symbolTable , ' ' + arrayElementType ) ; } else { push ( ARRAY_OF | REFERENCE_KIND | symbolTable . addType ( arrayElementType ) ) ; } break ; case Opcodes . CHECKCAST : String castType = argSymbol . value ; pop ( ) ; if ( castType . charAt ( 0 ) == ' ' ) { push ( symbolTable , castType ) ; } else { push ( REFERENCE_KIND | symbolTable . addType ( castType ) ) ; } break ; case Opcodes . MULTIANEWARRAY : pop ( arg ) ; push ( symbolTable , argSymbol . value ) ; break ; default : throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the type at the given index in the given abstract type array with the given type . Returns { @literal true } if the type array has been modified by this operation . [CODESPLIT] private static boolean merge ( final SymbolTable symbolTable , final int sourceType , final int [ ] dstTypes , final int dstIndex ) { int dstType = dstTypes [ dstIndex ] ; if ( dstType == sourceType ) { // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change. return false ; } int srcType = sourceType ; if ( ( sourceType & ~ DIM_MASK ) == NULL ) { if ( dstType == NULL ) { return false ; } srcType = NULL ; } if ( dstType == 0 ) { // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType. dstTypes [ dstIndex ] = srcType ; return true ; } int mergedType ; if ( ( dstType & DIM_MASK ) != 0 || ( dstType & KIND_MASK ) == REFERENCE_KIND ) { // If dstType is a reference type of any array dimension. if ( srcType == NULL ) { // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change. return false ; } else if ( ( srcType & ( DIM_MASK | KIND_MASK ) ) == ( dstType & ( DIM_MASK | KIND_MASK ) ) ) { // If srcType has the same array dimension and the same kind as dstType. if ( ( dstType & KIND_MASK ) == REFERENCE_KIND ) { // If srcType and dstType are reference types with the same array dimension, // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType. mergedType = ( srcType & DIM_MASK ) | REFERENCE_KIND | symbolTable . addMergedType ( srcType & VALUE_MASK , dstType & VALUE_MASK ) ; } else { // If srcType and dstType are array types of equal dimension but different element types, // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object. int mergedDim = ELEMENT_OF + ( srcType & DIM_MASK ) ; mergedType = mergedDim | REFERENCE_KIND | symbolTable . addType ( \"java/lang/Object\" ) ; } } else if ( ( srcType & DIM_MASK ) != 0 || ( srcType & KIND_MASK ) == REFERENCE_KIND ) { // If srcType is any other reference or array type, // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type // with a non reference element type (and similarly for dstDim). int srcDim = srcType & DIM_MASK ; if ( srcDim != 0 && ( srcType & KIND_MASK ) != REFERENCE_KIND ) { srcDim = ELEMENT_OF + srcDim ; } int dstDim = dstType & DIM_MASK ; if ( dstDim != 0 && ( dstType & KIND_MASK ) != REFERENCE_KIND ) { dstDim = ELEMENT_OF + dstDim ; } mergedType = Math . min ( srcDim , dstDim ) | REFERENCE_KIND | symbolTable . addType ( \"java/lang/Object\" ) ; } else { // If srcType is any other type, merge(srcType, dstType) = TOP. mergedType = TOP ; } } else if ( dstType == NULL ) { // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a // an array type or a reference type. mergedType = ( srcType & DIM_MASK ) != 0 || ( srcType & KIND_MASK ) == REFERENCE_KIND ? srcType : TOP ; } else { // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType. mergedType = TOP ; } if ( mergedType != dstType ) { dstTypes [ dstIndex ] = mergedType ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes the given { @link MethodWriter } visit the input frame of this { @link Frame } . The visit is done with the { @link MethodWriter#visitFrameStart } { @link MethodWriter#visitAbstractType } and { @link MethodWriter#visitFrameEnd } methods . [CODESPLIT] final void accept ( final MethodWriter methodWriter ) { // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and // all trailing TOP types. int [ ] localTypes = inputLocals ; int numLocal = 0 ; int numTrailingTop = 0 ; int i = 0 ; while ( i < localTypes . length ) { int localType = localTypes [ i ] ; i += ( localType == LONG || localType == DOUBLE ) ? 2 : 1 ; if ( localType == TOP ) { numTrailingTop ++ ; } else { numLocal += numTrailingTop + 1 ; numTrailingTop = 0 ; } } // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE. int [ ] stackTypes = inputStack ; int numStack = 0 ; i = 0 ; while ( i < stackTypes . length ) { int stackType = stackTypes [ i ] ; i += ( stackType == LONG || stackType == DOUBLE ) ? 2 : 1 ; numStack ++ ; } // Visit the frame and its content. int frameIndex = methodWriter . visitFrameStart ( owner . bytecodeOffset , numLocal , numStack ) ; i = 0 ; while ( numLocal -- > 0 ) { int localType = localTypes [ i ] ; i += ( localType == LONG || localType == DOUBLE ) ? 2 : 1 ; methodWriter . visitAbstractType ( frameIndex ++ , localType ) ; } i = 0 ; while ( numStack -- > 0 ) { int stackType = stackTypes [ i ] ; i += ( stackType == LONG || stackType == DOUBLE ) ? 2 : 1 ; methodWriter . visitAbstractType ( frameIndex ++ , stackType ) ; } methodWriter . visitFrameEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put the given abstract type in the given ByteVector using the JVMS verification_type_info format used in StackMapTable attributes . [CODESPLIT] static void putAbstractType ( final SymbolTable symbolTable , final int abstractType , final ByteVector output ) { int arrayDimensions = ( abstractType & Frame . DIM_MASK ) >> DIM_SHIFT ; if ( arrayDimensions == 0 ) { int typeValue = abstractType & VALUE_MASK ; switch ( abstractType & KIND_MASK ) { case CONSTANT_KIND : output . putByte ( typeValue ) ; break ; case REFERENCE_KIND : output . putByte ( ITEM_OBJECT ) . putShort ( symbolTable . addConstantClass ( symbolTable . getType ( typeValue ) . value ) . index ) ; break ; case UNINITIALIZED_KIND : output . putByte ( ITEM_UNINITIALIZED ) . putShort ( ( int ) symbolTable . getType ( typeValue ) . data ) ; break ; default : throw new AssertionError ( ) ; } } else { // Case of an array type, we need to build its descriptor first. StringBuilder typeDescriptor = new StringBuilder ( ) ; while ( arrayDimensions -- > 0 ) { typeDescriptor . append ( ' ' ) ; } if ( ( abstractType & KIND_MASK ) == REFERENCE_KIND ) { typeDescriptor . append ( ' ' ) . append ( symbolTable . getType ( abstractType & VALUE_MASK ) . value ) . append ( ' ' ) ; } else { switch ( abstractType & VALUE_MASK ) { case Frame . ITEM_ASM_BOOLEAN : typeDescriptor . append ( ' ' ) ; break ; case Frame . ITEM_ASM_BYTE : typeDescriptor . append ( ' ' ) ; break ; case Frame . ITEM_ASM_CHAR : typeDescriptor . append ( ' ' ) ; break ; case Frame . ITEM_ASM_SHORT : typeDescriptor . append ( ' ' ) ; break ; case Frame . ITEM_INTEGER : typeDescriptor . append ( ' ' ) ; break ; case Frame . ITEM_FLOAT : typeDescriptor . append ( ' ' ) ; break ; case Frame . ITEM_LONG : typeDescriptor . append ( ' ' ) ; break ; case Frame . ITEM_DOUBLE : typeDescriptor . append ( ' ' ) ; break ; default : throw new AssertionError ( ) ; } } output . putByte ( ITEM_OBJECT ) . putShort ( symbolTable . addConstantClass ( typeDescriptor . toString ( ) ) . index ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prunes expired elements from the cache . Returns the number of removed objects . [CODESPLIT] @ Override protected int pruneCache ( ) { int count = 0 ; Iterator < CacheObject < K , V > > values = cacheMap . values ( ) . iterator ( ) ; while ( values . hasNext ( ) ) { CacheObject co = values . next ( ) ; if ( co . isExpired ( ) ) { values . remove ( ) ; count ++ ; } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Schedules prune . [CODESPLIT] public void schedulePrune ( final long delay ) { if ( pruneTimer != null ) { pruneTimer . cancel ( ) ; } pruneTimer = new Timer ( ) ; pruneTimer . schedule ( new TimerTask ( ) { @ Override public void run ( ) { prune ( ) ; } } , delay , delay ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visit the module corresponding to the class . [CODESPLIT] public ModuleVisitor visitModule ( final String name , final int access , final String version ) { if ( api < Opcodes . ASM6 ) { throw new UnsupportedOperationException ( \"This feature requires ASM6\" ) ; } if ( cv != null ) { return cv . visitModule ( name , access , version ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits the nest host class of the class . A nest is a set of classes of the same package that share access to their private members . One of these classes called the host lists the other members of the nest which in turn should link to the host of their nest . This method must be called only once and only if the visited class is a non - host member of a nest . A class is implicitly its own nest so it s invalid to call this method with the visited class name as argument . [CODESPLIT] public void visitNestHost ( final String nestHost ) { if ( api < Opcodes . ASM7 ) { throw new UnsupportedOperationException ( \"This feature requires ASM7\" ) ; } if ( cv != null ) { cv . visitNestHost ( nestHost ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits the enclosing class of the class . This method must be called only if the class has an enclosing class . [CODESPLIT] public void visitOuterClass ( final String owner , final String name , final String descriptor ) { if ( cv != null ) { cv . visitOuterClass ( owner , name , descriptor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits an annotation of the class . [CODESPLIT] public AnnotationVisitor visitAnnotation ( final String descriptor , final boolean visible ) { if ( cv != null ) { return cv . visitAnnotation ( descriptor , visible ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a member of the nest . A nest is a set of classes of the same package that share access to their private members . One of these classes called the host lists the other members of the nest which in turn should link to the host of their nest . This method must be called only if the visited class is the host of a nest . A nest host is implicitly a member of its own nest so it s invalid to call this method with the visited class name as argument . [CODESPLIT] public void visitNestMember ( final String nestMember ) { if ( api < Opcodes . ASM7 ) { throw new UnsupportedOperationException ( \"This feature requires ASM7\" ) ; } if ( cv != null ) { cv . visitNestMember ( nestMember ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits information about an inner class . This inner class is not necessarily a member of the class being visited . [CODESPLIT] public void visitInnerClass ( final String name , final String outerName , final String innerName , final int access ) { if ( cv != null ) { cv . visitInnerClass ( name , outerName , innerName , access ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a field of the class . [CODESPLIT] public FieldVisitor visitField ( final int access , final String name , final String descriptor , final String signature , final Object value ) { if ( cv != null ) { return cv . visitField ( access , name , descriptor , signature , value ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- provider [CODESPLIT] @ Override public synchronized void init ( ) { try { Class . forName ( driverClass ) ; } catch ( ClassNotFoundException cnfex ) { throw new DbSqlException ( \"JDBC driver not found: \" + driverClass , cnfex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns existing thread session or new one if already not exist . If session doesn t exist it will be created using default connection provider . [CODESPLIT] public static DbThreadSession getThreadSession ( ) { DbThreadSession session = ( DbThreadSession ) ThreadDbSessionHolder . get ( ) ; if ( session == null ) { session = new DbThreadSession ( ) ; } return session ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes thread session . [CODESPLIT] public static void closeThreadSession ( ) { DbThreadSession session = ( DbThreadSession ) ThreadDbSessionHolder . get ( ) ; if ( session != null ) { session . closeSession ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates execution array that will invoke all filters actions and results in correct order . [CODESPLIT] protected ActionWrapper [ ] createExecutionArray ( ) { int totalInterceptors = ( this . actionRuntime . getInterceptors ( ) != null ? this . actionRuntime . getInterceptors ( ) . length : 0 ) ; int totalFilters = ( this . actionRuntime . getFilters ( ) != null ? this . actionRuntime . getFilters ( ) . length : 0 ) ; ActionWrapper [ ] executionArray = new ActionWrapper [ totalFilters + 1 + totalInterceptors + 1 ] ; // filters int index = 0 ; if ( totalFilters > 0 ) { System . arraycopy ( actionRuntime . getFilters ( ) , 0 , executionArray , index , totalFilters ) ; index += totalFilters ; } // result is executed AFTER the action AND interceptors executionArray [ index ++ ] = actionRequest -> { Object actionResult = actionRequest . invoke ( ) ; ActionRequest . this . madvocController . render ( ActionRequest . this , actionResult ) ; return actionResult ; } ; // interceptors if ( totalInterceptors > 0 ) { System . arraycopy ( actionRuntime . getInterceptors ( ) , 0 , executionArray , index , totalInterceptors ) ; index += totalInterceptors ; } // action executionArray [ index ] = actionRequest -> { actionResult = invokeActionMethod ( ) ; return actionResult ; } ; return executionArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes action method after starting all interceptors . After method invocation all interceptors will finish in opposite order . [CODESPLIT] protected Object invokeActionMethod ( ) throws Exception { if ( actionRuntime . isActionHandlerDefined ( ) ) { actionRuntime . getActionHandler ( ) . handle ( this ) ; return null ; } final Object [ ] params = targets . extractParametersValues ( ) ; try { return actionRuntime . getActionClassMethod ( ) . invoke ( action , params ) ; } catch ( InvocationTargetException itex ) { throw wrapToException ( unwrapThrowable ( itex ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads request body only once and returns it to user . [CODESPLIT] public String readRequestBody ( ) { if ( requestBody == null ) { try { requestBody = ServletUtil . readRequestBodyFromStream ( getHttpServletRequest ( ) ) ; } catch ( IOException ioex ) { requestBody = StringPool . EMPTY ; } } return requestBody ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the first item index of requested page . [CODESPLIT] public static int calcFirstItemIndexOfPage ( int page , final int pageSize , final int total ) { if ( total == 0 ) { return 0 ; } if ( page < 1 ) { page = 1 ; } int first = ( page - 1 ) * pageSize ; if ( first >= total ) { first = ( ( total - 1 ) / pageSize ) * pageSize ; // first item on the last page } return first ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates first item index of the page . [CODESPLIT] public static int calcFirstItemIndexOfPage ( final PageRequest pageRequest , final int total ) { return calcFirstItemIndexOfPage ( pageRequest . getPage ( ) , pageRequest . getSize ( ) , total ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses int value or throws <code > CSSellyException< / code > on failure . [CODESPLIT] protected int parseInt ( final String value ) { try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException nfex ) { throw new CSSellyException ( nfex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches expression with the value . [CODESPLIT] public boolean match ( final int value ) { if ( a == 0 ) { return value == b ; } if ( a > 0 ) { if ( value < b ) { return false ; } return ( value - b ) % a == 0 ; } if ( value > b ) { return false ; } return ( b - value ) % ( - a ) == 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts char array into byte array by replacing each character with two bytes . [CODESPLIT] public static byte [ ] toRawByteArray ( final char [ ] carr ) { byte [ ] barr = new byte [ carr . length << 1 ] ; for ( int i = 0 , bpos = 0 ; i < carr . length ; i ++ ) { char c = carr [ i ] ; barr [ bpos ++ ] = ( byte ) ( ( c & 0xFF00 ) >> 8 ) ; barr [ bpos ++ ] = ( byte ) ( c & 0x00FF ) ; } return barr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds index of the first character in given array the differs from the given set of characters . [CODESPLIT] public static int findFirstDiff ( final char [ ] source , final int index , final char [ ] match ) { for ( int i = index ; i < source . length ; i ++ ) { if ( ! equalsOne ( source [ i ] , match ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders node name . [CODESPLIT] protected String resolveNodeName ( final Node node ) { switch ( tagCase ) { case DEFAULT : return node . getNodeName ( ) ; case RAW : return node . getNodeRawName ( ) ; case LOWERCASE : return node . getNodeRawName ( ) . toLowerCase ( ) ; case UPPERCASE : return node . getNodeRawName ( ) . toUpperCase ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders attribute name . [CODESPLIT] protected String resolveAttributeName ( final Node node , final Attribute attribute ) { switch ( attributeCase ) { case DEFAULT : return attribute . getName ( ) ; case RAW : return attribute . getRawName ( ) ; case LOWERCASE : return attribute . getRawName ( ) . toLowerCase ( ) ; case UPPERCASE : return attribute . getRawName ( ) . toUpperCase ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders attribute . [CODESPLIT] protected void renderAttribute ( final Node node , final Attribute attribute , final Appendable appendable ) throws IOException { String name = resolveAttributeName ( node , attribute ) ; String value = attribute . getValue ( ) ; appendable . append ( name ) ; if ( value != null ) { appendable . append ( ' ' ) ; appendable . append ( ' ' ) ; appendable . append ( HtmlEncoder . attributeDoubleQuoted ( value ) ) ; appendable . append ( ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads props from the file . Assumes UTF8 encoding unless the file ends with . properties than it uses ISO 8859 - 1 . [CODESPLIT] public Props load ( final File file ) throws IOException { final String extension = FileNameUtil . getExtension ( file . getAbsolutePath ( ) ) ; final String data ; if ( extension . equalsIgnoreCase ( \"properties\" ) ) { data = FileUtil . readString ( file , StringPool . ISO_8859_1 ) ; } else { data = FileUtil . readString ( file ) ; } parse ( data ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties from the file in provided encoding . [CODESPLIT] public Props load ( final File file , final String encoding ) throws IOException { parse ( FileUtil . readString ( file , encoding ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties from input stream . Stream is not closed at the end . [CODESPLIT] public Props load ( final InputStream in ) throws IOException { final Writer out = new FastCharArrayWriter ( ) ; StreamUtil . copy ( in , out ) ; parse ( out . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads base properties from the provided java properties . Null values are ignored . [CODESPLIT] public Props load ( final Map < ? , ? > p ) { for ( final Map . Entry < ? , ? > entry : p . entrySet ( ) ) { final String name = entry . getKey ( ) . toString ( ) ; final Object value = entry . getValue ( ) ; if ( value == null ) { continue ; } data . putBaseProperty ( name , value . toString ( ) , false ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads base properties from java Map using provided prefix . Null values are ignored . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Props load ( final Map < ? , ? > map , final String prefix ) { String realPrefix = prefix ; realPrefix += ' ' ; for ( final Map . Entry entry : map . entrySet ( ) ) { final String name = entry . getKey ( ) . toString ( ) ; final Object value = entry . getValue ( ) ; if ( value == null ) { continue ; } data . putBaseProperty ( realPrefix + name , value . toString ( ) , false ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads system properties with given prefix . If prefix is <code > null< / code > it will not be ignored . [CODESPLIT] public Props loadSystemProperties ( final String prefix ) { final Properties environmentProperties = System . getProperties ( ) ; load ( environmentProperties , prefix ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads environment properties with given prefix . If prefix is <code > null< / code > it will not be used . [CODESPLIT] public Props loadEnvironment ( final String prefix ) { final Map < String , String > environmentMap = System . getenv ( ) ; load ( environmentMap , prefix ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads props and properties from the classpath . [CODESPLIT] public Props loadFromClasspath ( final String ... patterns ) { ClassScanner . create ( ) . registerEntryConsumer ( entryData -> { String usedEncoding = JoddCore . encoding ; if ( StringUtil . endsWithIgnoreCase ( entryData . name ( ) , \".properties\" ) ) { usedEncoding = StringPool . ISO_8859_1 ; } final String encoding = usedEncoding ; UncheckedException . runAndWrapException ( ( ) -> load ( entryData . openInputStream ( ) , encoding ) ) ; } ) . includeResources ( true ) . ignoreException ( true ) . excludeCommonJars ( ) . excludeAllEntries ( true ) . includeEntries ( patterns ) . scanDefaultClasspath ( ) . start ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns value of property using active profiles or default value if not found . [CODESPLIT] public String getValueOrDefault ( final String key , final String defaultValue ) { initialize ( ) ; final String value = data . lookupValue ( key , activeProfiles ) ; if ( value == null ) { return defaultValue ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns double value of given property or { [CODESPLIT] public Double getDoubleValue ( final String key ) { final String value = getValue ( key ) ; if ( value == null ) { return null ; } return Double . valueOf ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > string< / code > value of given profiles . If key is not found under listed profiles base properties will be searched . Returns <code > null< / code > if property doesn t exist . [CODESPLIT] public String getValue ( final String key , final String ... profiles ) { initialize ( ) ; return data . lookupValue ( key , profiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets value on some profile . [CODESPLIT] public void setValue ( final String key , final String value , final String profile ) { if ( profile == null ) { data . putBaseProperty ( key , value , false ) ; } else { data . putProfileProperty ( key , value , profile , false ) ; } initialized = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts props belonging to active profiles . [CODESPLIT] public void extractProps ( final Map target ) { initialize ( ) ; data . extract ( target , activeProfiles , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract props of given profiles . [CODESPLIT] public void extractProps ( final Map target , final String ... profiles ) { initialize ( ) ; data . extract ( target , profiles , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts subset of properties that matches given wildcards . [CODESPLIT] public void extractSubProps ( final Map target , final String ... wildcardPatterns ) { initialize ( ) ; data . extract ( target , activeProfiles , wildcardPatterns , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns inner map from the props with given prefix . Keys in returned map will not have the prefix . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Map < String , Object > innerMap ( final String prefix ) { initialize ( ) ; return data . extract ( null , activeProfiles , null , prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds child map to the props on given prefix . [CODESPLIT] public void addInnerMap ( String prefix , final Map < ? , ? > map , final String profile ) { if ( ! StringUtil . endsWithChar ( prefix , ' ' ) ) { prefix += StringPool . DOT ; } for ( Map . Entry < ? , ? > entry : map . entrySet ( ) ) { String key = entry . getKey ( ) . toString ( ) ; key = prefix + key ; setValue ( key , entry . getValue ( ) . toString ( ) , profile ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves active profiles from special property . This property can be only a base property! If default active property is not defined nothing happens . Otherwise it will replace currently active profiles . [CODESPLIT] protected void resolveActiveProfiles ( ) { if ( activeProfilesProp == null ) { activeProfiles = null ; return ; } final PropsEntry pv = data . getBaseProperty ( activeProfilesProp ) ; if ( pv == null ) { // no active profile set as the property, exit return ; } final String value = pv . getValue ( ) ; if ( StringUtil . isBlank ( value ) ) { activeProfiles = null ; return ; } activeProfiles = StringUtil . splitc ( value , ' ' ) ; StringUtil . trimAll ( activeProfiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all profiles names . [CODESPLIT] public String [ ] getAllProfiles ( ) { String [ ] profiles = new String [ data . profileProperties . size ( ) ] ; int index = 0 ; for ( String profileName : data . profileProperties . keySet ( ) ) { profiles [ index ] = profileName ; index ++ ; } return profiles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the profiles that define certain prop s key name . Key name is given as a wildcard or it can be matched fully . [CODESPLIT] public String [ ] getProfilesFor ( final String propKeyNameWildcard ) { HashSet < String > profiles = new HashSet <> ( ) ; profile : for ( Map . Entry < String , Map < String , PropsEntry > > entries : data . profileProperties . entrySet ( ) ) { String profileName = entries . getKey ( ) ; Map < String , PropsEntry > value = entries . getValue ( ) ; for ( String propKeyName : value . keySet ( ) ) { if ( Wildcard . equalsOrMatch ( propKeyName , propKeyNameWildcard ) ) { profiles . add ( profileName ) ; continue profile ; } } } return profiles . toArray ( new String [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds property injection point . [CODESPLIT] protected void addPropertyInjectionPoint ( final PropertyInjectionPoint pip ) { if ( properties == null ) { properties = new PropertyInjectionPoint [ 1 ] ; properties [ 0 ] = pip ; } else { properties = ArraysUtil . append ( properties , pip ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds set injection point . [CODESPLIT] protected void addSetInjectionPoint ( final SetInjectionPoint sip ) { if ( sets == null ) { sets = new SetInjectionPoint [ 1 ] ; sets [ 0 ] = sip ; } else { sets = ArraysUtil . append ( sets , sip ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds method injection point . [CODESPLIT] protected void addMethodInjectionPoint ( final MethodInjectionPoint mip ) { if ( methods == null ) { methods = new MethodInjectionPoint [ 1 ] ; methods [ 0 ] = mip ; } else { methods = ArraysUtil . append ( methods , mip ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds init methods . [CODESPLIT] protected void addInitMethodPoints ( final InitMethodPoint [ ] methods ) { if ( initMethods == null ) { initMethods = methods ; } else { initMethods = ArraysUtil . join ( initMethods , methods ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds destroy methods . [CODESPLIT] protected void addDestroyMethodPoints ( final DestroyMethodPoint [ ] methods ) { if ( destroyMethods == null ) { destroyMethods = methods ; } else { destroyMethods = ArraysUtil . join ( destroyMethods , methods ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns target class if proxetta applied on given class . If not returns given class as result . [CODESPLIT] public static Class resolveTargetClass ( final Class proxy ) { final String name = proxy . getName ( ) ; if ( name . endsWith ( ProxettaNames . proxyClassNameSuffix ) ) { return proxy . getSuperclass ( ) ; } if ( name . endsWith ( ProxettaNames . wrapperClassNameSuffix ) ) { return getTargetWrapperType ( proxy ) ; } return proxy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects some target instance into { [CODESPLIT] public static void injectTargetIntoWrapper ( final Object target , final Object wrapper , final String targetFieldName ) { try { final Field field = wrapper . getClass ( ) . getField ( targetFieldName ) ; field . setAccessible ( true ) ; field . set ( wrapper , target ) ; } catch ( Exception ex ) { throw new ProxettaException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects target instance into proxy using default target field name . [CODESPLIT] public static void injectTargetIntoWrapper ( final Object target , final Object wrapper ) { injectTargetIntoWrapper ( target , wrapper , ProxettaNames . wrapperTargetFieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns wrapper target type . [CODESPLIT] public static Class getTargetWrapperType ( final Class wrapperClass ) { try { final Field field = wrapperClass . getDeclaredField ( ProxettaNames . wrapperTargetFieldName ) ; return field . getType ( ) ; } catch ( NoSuchFieldException nsfex ) { throw new ProxettaException ( nsfex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prunes expired and if cache is still full the LFU element ( s ) from the cache . On LFU removal access count is normalized to value which had removed object . Returns the number of removed objects . [CODESPLIT] @ Override protected int pruneCache ( ) { int count = 0 ; CacheObject < K , V > comin = null ; // remove expired items and find cached object with minimal access count Iterator < CacheObject < K , V > > values = cacheMap . values ( ) . iterator ( ) ; while ( values . hasNext ( ) ) { CacheObject < K , V > co = values . next ( ) ; if ( co . isExpired ( ) ) { values . remove ( ) ; onRemove ( co . key , co . cachedObject ) ; count ++ ; continue ; } if ( comin == null ) { comin = co ; } else { if ( co . accessCount < comin . accessCount ) { comin = co ; } } } if ( ! isFull ( ) ) { return count ; } // decrease access count to all cached objects if ( comin != null ) { long minAccessCount = comin . accessCount ; values = cacheMap . values ( ) . iterator ( ) ; while ( values . hasNext ( ) ) { CacheObject < K , V > co = values . next ( ) ; co . accessCount -= minAccessCount ; if ( co . accessCount <= 0 ) { values . remove ( ) ; onRemove ( co . key , co . cachedObject ) ; count ++ ; } } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates property field . Field is being searched also in all superclasses of current class . [CODESPLIT] protected FieldDescriptor findField ( final String fieldName ) { FieldDescriptor fieldDescriptor = classDescriptor . getFieldDescriptor ( fieldName , true ) ; if ( fieldDescriptor != null ) { return fieldDescriptor ; } // field descriptor not found in this class // try to locate it in the superclasses Class [ ] superclasses = classDescriptor . getAllSuperclasses ( ) ; for ( Class superclass : superclasses ) { ClassDescriptor classDescriptor = ClassIntrospector . get ( ) . lookup ( superclass ) ; fieldDescriptor = classDescriptor . getFieldDescriptor ( fieldName , true ) ; if ( fieldDescriptor != null ) { return fieldDescriptor ; } } // nothing found return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns property type . Raw types are detected . [CODESPLIT] public Class getType ( ) { if ( type == null ) { if ( fieldDescriptor != null ) { type = fieldDescriptor . getRawType ( ) ; } else if ( readMethodDescriptor != null ) { type = getGetter ( true ) . getGetterRawType ( ) ; //type = readMethodDescriptor.getGetterRawType(); } else if ( writeMethodDescriptor != null ) { type = getSetter ( true ) . getSetterRawType ( ) ; //type = writeMethodDescriptor.getSetterRawType(); } } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public Getter getGetter ( final boolean declared ) { if ( getters == null ) { getters = new Getter [ ] { createGetter ( false ) , createGetter ( true ) , } ; } return getters [ declared ? 1 : 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] protected Getter createGetter ( final boolean declared ) { if ( readMethodDescriptor != null ) { if ( readMethodDescriptor . matchDeclared ( declared ) ) { return Getter . of ( readMethodDescriptor ) ; } } if ( fieldDescriptor != null ) { if ( fieldDescriptor . matchDeclared ( declared ) ) { return Getter . of ( fieldDescriptor ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public Setter getSetter ( final boolean declared ) { if ( setters == null ) { setters = new Setter [ ] { createSetter ( false ) , createSetter ( true ) , } ; } return setters [ declared ? 1 : 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] protected Setter createSetter ( final boolean declared ) { if ( writeMethodDescriptor != null ) { if ( writeMethodDescriptor . matchDeclared ( declared ) ) { return Setter . of ( writeMethodDescriptor ) ; } } if ( fieldDescriptor != null ) { if ( fieldDescriptor . matchDeclared ( declared ) ) { return Setter . of ( fieldDescriptor ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves key type for given property descriptor . [CODESPLIT] public Class resolveKeyType ( final boolean declared ) { Class keyType = null ; Getter getter = getGetter ( declared ) ; if ( getter != null ) { keyType = getter . getGetterRawKeyComponentType ( ) ; } if ( keyType == null ) { FieldDescriptor fieldDescriptor = getFieldDescriptor ( ) ; if ( fieldDescriptor != null ) { keyType = fieldDescriptor . getRawKeyComponentType ( ) ; } } return keyType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves component type for given property descriptor . [CODESPLIT] public Class resolveComponentType ( final boolean declared ) { Class componentType = null ; Getter getter = getGetter ( declared ) ; if ( getter != null ) { componentType = getter . getGetterRawComponentType ( ) ; } if ( componentType == null ) { FieldDescriptor fieldDescriptor = getFieldDescriptor ( ) ; if ( fieldDescriptor != null ) { componentType = fieldDescriptor . getRawComponentType ( ) ; } } return componentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- util [CODESPLIT] protected String nosep ( final String in ) { if ( in . endsWith ( File . separator ) ) { return in . substring ( 0 , in . length ( ) - 1 ) ; } return in ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates JSON result from given object . The object will be serialized to JSON . [CODESPLIT] public static JsonResult of ( final Object object ) { final String json = JsonSerializer . create ( ) . deep ( true ) . serialize ( object ) ; return new JsonResult ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a JSON response from an exception . Response body will have information about the exception and response status will be set to 500 . [CODESPLIT] public static JsonResult of ( final Exception exception ) { final HashMap < String , Object > errorMap = new HashMap <> ( ) ; errorMap . put ( \"message\" , ExceptionUtil . message ( exception ) ) ; errorMap . put ( \"error\" , exception . getClass ( ) . getName ( ) ) ; errorMap . put ( \"cause\" , exception . getCause ( ) != null ? exception . getCause ( ) . getClass ( ) . getName ( ) : null ) ; final ArrayList < String > details = new ArrayList <> ( ) ; final StackTraceElement [ ] ste = ExceptionUtil . getStackTrace ( exception , null , null ) ; for ( StackTraceElement stackTraceElement : ste ) { details . add ( stackTraceElement . toString ( ) ) ; } errorMap . put ( \"details\" , details ) ; final String json = JsonSerializer . create ( ) . deep ( true ) . serialize ( errorMap ) ; return new JsonResult ( json ) . status ( HttpStatus . error500 ( ) . internalError ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves HTTP method name from method name . If method name or first camel - case word of a method equals to a HTTP method it will be used as that HTTP methods . [CODESPLIT] protected String resolveHttpMethodFromMethodName ( final String methodName ) { int i = 0 ; while ( i < methodName . length ( ) ) { if ( CharUtil . isUppercaseAlpha ( methodName . charAt ( i ) ) ) { break ; } i ++ ; } final String name = methodName . substring ( 0 , i ) . toUpperCase ( ) ; for ( final HttpMethod httpMethod : HttpMethod . values ( ) ) { if ( httpMethod . equalsName ( name ) ) { return httpMethod . name ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if two strings are equals or if they { [CODESPLIT] public static boolean equalsOrMatch ( final CharSequence string , final CharSequence pattern ) { if ( string . equals ( pattern ) ) { return true ; } return match ( string , pattern , 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal matching recursive function . [CODESPLIT] private static boolean match ( final CharSequence string , final CharSequence pattern , int sNdx , int pNdx ) { int pLen = pattern . length ( ) ; if ( pLen == 1 ) { if ( pattern . charAt ( 0 ) == ' ' ) { // speed-up return true ; } } int sLen = string . length ( ) ; boolean nextIsNotWildcard = false ; while ( true ) { // check if end of string and/or pattern occurred if ( ( sNdx >= sLen ) ) { // end of string still may have pending '*' in pattern while ( ( pNdx < pLen ) && ( pattern . charAt ( pNdx ) == ' ' ) ) { pNdx ++ ; } return pNdx >= pLen ; } if ( pNdx >= pLen ) { // end of pattern, but not end of the string return false ; } char p = pattern . charAt ( pNdx ) ; // pattern char // perform logic if ( ! nextIsNotWildcard ) { if ( p == ' ' ) { pNdx ++ ; nextIsNotWildcard = true ; continue ; } if ( p == ' ' ) { sNdx ++ ; pNdx ++ ; continue ; } if ( p == ' ' ) { char pNext = 0 ; // next pattern char if ( pNdx + 1 < pLen ) { pNext = pattern . charAt ( pNdx + 1 ) ; } if ( pNext == ' ' ) { // double '*' have the same effect as one '*' pNdx ++ ; continue ; } int i ; pNdx ++ ; // find recursively if there is any substring from the end of the // line that matches the rest of the pattern !!! for ( i = string . length ( ) ; i >= sNdx ; i -- ) { if ( match ( string , pattern , i , pNdx ) ) { return true ; } } return false ; } } else { nextIsNotWildcard = false ; } // check if pattern char and string char are equals if ( p != string . charAt ( sNdx ) ) { return false ; } // everything matches for now, continue sNdx ++ ; pNdx ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches string to at least one pattern . Returns index of matched pattern or <code > - 1< / code > otherwise . [CODESPLIT] public static int matchOne ( final String src , final String ... patterns ) { for ( int i = 0 ; i < patterns . length ; i ++ ) { if ( match ( src , patterns [ i ] ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches path against pattern using * ? and ** wildcards . Both path and the pattern are tokenized on path separators ( both \\ and / ) . ** represents deep tree wildcard as in Ant . [CODESPLIT] public static boolean matchPath ( final String path , final String pattern ) { String [ ] pathElements = StringUtil . splitc ( path , PATH_SEPARATORS ) ; String [ ] patternElements = StringUtil . splitc ( pattern , PATH_SEPARATORS ) ; return matchTokens ( pathElements , patternElements ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if class or resource name matches at least one package rule from the list . [CODESPLIT] protected boolean isMatchingRules ( final String name , final String ... rules ) { for ( String rule : rules ) { if ( Wildcard . equalsOrMatch ( name , rule ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves loading rules . [CODESPLIT] protected Loading resolveLoading ( final boolean parentFirstStrategy , final String className ) { boolean withParent = true ; boolean withLoader = true ; if ( parentFirstStrategy ) { if ( isMatchingRules ( className , loaderOnlyRules ) ) { withParent = false ; } else if ( isMatchingRules ( className , parentOnlyRules ) ) { withLoader = false ; } } else { if ( isMatchingRules ( className , parentOnlyRules ) ) { withLoader = false ; } else if ( isMatchingRules ( className , loaderOnlyRules ) ) { withParent = false ; } } return new Loading ( withParent , withLoader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves resources . [CODESPLIT] protected Loading resolveResourceLoading ( final boolean parentFirstStrategy , String resourceName ) { if ( matchResourcesAsPackages ) { resourceName = StringUtil . replaceChar ( resourceName , ' ' , ' ' ) ; } return resolveLoading ( parentFirstStrategy , resourceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads class using parent - first or parent - last strategy . [CODESPLIT] @ Override protected synchronized Class < ? > loadClass ( final String className , final boolean resolve ) throws ClassNotFoundException { // check first if the class has already been loaded Class < ? > c = findLoadedClass ( className ) ; if ( c != null ) { if ( resolve ) { resolveClass ( c ) ; } return c ; } // class not loaded yet Loading loading = resolveLoading ( parentFirst , className ) ; if ( parentFirst ) { // PARENT FIRST if ( loading . withParent ) { try { c = parentClassLoader . loadClass ( className ) ; } catch ( ClassNotFoundException ignore ) { } } if ( c == null ) { if ( loading . withLoader ) { c = this . findClass ( className ) ; } else { throw new ClassNotFoundException ( \"Class not found: \" + className ) ; } } } else { // THIS FIRST if ( loading . withLoader ) { try { c = this . findClass ( className ) ; } catch ( ClassNotFoundException ignore ) { } } if ( c == null ) { if ( loading . withParent ) { c = parentClassLoader . loadClass ( className ) ; } else { throw new ClassNotFoundException ( \"Class not found: \" + className ) ; } } } if ( resolve ) { resolveClass ( c ) ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a resource using parent - first or parent - last strategy . [CODESPLIT] @ Override public URL getResource ( final String resourceName ) { URL url = null ; Loading loading = resolveResourceLoading ( parentFirst , resourceName ) ; if ( parentFirst ) { // PARENT FIRST if ( loading . withParent ) { url = parentClassLoader . getResource ( resourceName ) ; } if ( url == null ) { if ( loading . withLoader ) { url = this . findResource ( resourceName ) ; } } } else { // THIS FIRST if ( loading . withLoader ) { url = this . findResource ( resourceName ) ; } if ( url == null ) { if ( loading . withParent ) { url = parentClassLoader . getResource ( resourceName ) ; } } } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for gobbler to end . [CODESPLIT] public void waitFor ( ) { try { synchronized ( lock ) { if ( ! end ) { lock . wait ( ) ; } } } catch ( InterruptedException ignore ) { Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans annotation and returns type of Madvoc annotations . [CODESPLIT] public Class < ? extends Annotation > detectAnnotationType ( final Annotation [ ] annotations ) { for ( final Annotation annotation : annotations ) { if ( annotation instanceof In ) { return annotation . annotationType ( ) ; } else if ( annotation instanceof Out ) { return annotation . annotationType ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects { [CODESPLIT] public ScopeData inspectMethodParameterScopes ( final String name , final Class type , final Annotation [ ] annotations ) { In in = null ; Out out = null ; for ( final Annotation annotation : annotations ) { if ( annotation instanceof In ) { in = ( In ) annotation ; } else if ( annotation instanceof Out ) { out = ( Out ) annotation ; } } final Class < ? extends MadvocScope > scope = resolveScopeClassFromAnnotations ( annotations ) ; int count = 0 ; InjectionPoint [ ] ins = null ; InjectionPoint [ ] outs = null ; if ( in != null ) { final InjectionPoint scopeDataIn = buildInjectionPoint ( in . value ( ) , name , type , scope ) ; if ( scopeDataIn != null ) { count ++ ; ins = new InjectionPoint [ ] { scopeDataIn } ; } } if ( out != null ) { final InjectionPoint scopeDataOut = buildInjectionPoint ( out . value ( ) , name , type , scope ) ; if ( scopeDataOut != null ) { count ++ ; outs = new InjectionPoint [ ] { scopeDataOut } ; } } if ( count == 0 ) { return NO_SCOPE_DATA ; } return new ScopeData ( this , ins , outs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds injection point . [CODESPLIT] protected InjectionPoint buildInjectionPoint ( final String annotationValue , final String propertyName , final Class propertyType , final Class < ? extends MadvocScope > scope ) { final String value = annotationValue . trim ( ) ; final String name , targetName ; if ( StringUtil . isNotBlank ( value ) ) { name = value ; targetName = propertyName ; } else { name = propertyName ; targetName = null ; } return new InjectionPoint ( propertyType , name , targetName , scopeResolver . defaultOrScopeType ( scope ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects { [CODESPLIT] public ScopeData inspectClassScopes ( final Class actionClass ) { ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( actionClass ) ; PropertyDescriptor [ ] allProperties = cd . getAllPropertyDescriptors ( ) ; List < InjectionPoint > listIn = new ArrayList <> ( allProperties . length ) ; List < InjectionPoint > listOut = new ArrayList <> ( allProperties . length ) ; for ( PropertyDescriptor pd : allProperties ) { // collect annotations Class < ? extends MadvocScope > scope = null ; In in = null ; Out out = null ; if ( pd . getFieldDescriptor ( ) != null ) { Field field = pd . getFieldDescriptor ( ) . getField ( ) ; in = field . getAnnotation ( In . class ) ; out = field . getAnnotation ( Out . class ) ; scope = resolveScopeClassFromAnnotations ( field . getAnnotations ( ) ) ; } if ( pd . getWriteMethodDescriptor ( ) != null ) { Method method = pd . getWriteMethodDescriptor ( ) . getMethod ( ) ; if ( in == null ) { in = method . getAnnotation ( In . class ) ; } if ( out == null ) { out = method . getAnnotation ( Out . class ) ; } if ( scope == null ) { scope = resolveScopeClassFromAnnotations ( method . getAnnotations ( ) ) ; } } if ( pd . getReadMethodDescriptor ( ) != null ) { Method method = pd . getReadMethodDescriptor ( ) . getMethod ( ) ; if ( in == null ) { in = method . getAnnotation ( In . class ) ; } if ( out == null ) { out = method . getAnnotation ( Out . class ) ; } if ( scope == null ) { scope = resolveScopeClassFromAnnotations ( method . getAnnotations ( ) ) ; } } // inspect all final InjectionPoint ii = in == null ? null : buildInjectionPoint ( in . value ( ) , pd . getName ( ) , pd . getType ( ) , scope ) ; if ( ii != null ) { listIn . add ( ii ) ; } final InjectionPoint oi = out == null ? null : buildInjectionPoint ( out . value ( ) , pd . getName ( ) , pd . getType ( ) , scope ) ; if ( oi != null ) { listOut . add ( oi ) ; } } if ( ( listIn . isEmpty ( ) ) && ( listOut . isEmpty ( ) ) ) { return NO_SCOPE_DATA ; } InjectionPoint [ ] in = null ; InjectionPoint [ ] out = null ; if ( ! listIn . isEmpty ( ) ) { in = listIn . toArray ( new InjectionPoint [ 0 ] ) ; } if ( ! listOut . isEmpty ( ) ) { out = listOut . toArray ( new InjectionPoint [ 0 ] ) ; } return new ScopeData ( this , in , out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a type . [CODESPLIT] public void visit ( ) { ClassDescriptor classDescriptor = ClassIntrospector . get ( ) . lookup ( type ) ; if ( classMetadataName != null ) { // process first 'meta' fields 'class' onProperty ( classMetadataName , null , false ) ; } PropertyDescriptor [ ] propertyDescriptors = classDescriptor . getAllPropertyDescriptors ( ) ; for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { Getter getter = propertyDescriptor . getGetter ( declared ) ; if ( getter != null ) { String propertyName = propertyDescriptor . getName ( ) ; boolean isTransient = false ; // check for transient flag FieldDescriptor fieldDescriptor = propertyDescriptor . getFieldDescriptor ( ) ; if ( fieldDescriptor != null ) { isTransient = Modifier . isTransient ( fieldDescriptor . getField ( ) . getModifiers ( ) ) ; } onProperty ( propertyName , propertyDescriptor , isTransient ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked on each property . Properties are getting matched against the rules . If property passes all the rules it will be processed in { [CODESPLIT] protected void onProperty ( String propertyName , final PropertyDescriptor propertyDescriptor , final boolean isTransient ) { Class propertyType = propertyDescriptor == null ? null : propertyDescriptor . getType ( ) ; Path currentPath = jsonContext . path ; currentPath . push ( propertyName ) ; // change name for properties if ( propertyType != null ) { propertyName = typeData . resolveJsonName ( propertyName ) ; } // determine if name should be included/excluded boolean include = ! typeData . strict ; // + don't include transient fields if ( isTransient ) { include = false ; } // + all collections are not serialized by default include = jsonContext . matchIgnoredPropertyTypes ( propertyType , true , include ) ; // + annotations include = typeData . rules . apply ( propertyName , true , include ) ; // + path queries: excludes/includes include = jsonContext . matchPathToQueries ( include ) ; // done if ( ! include ) { currentPath . pop ( ) ; return ; } onSerializableProperty ( propertyName , propertyDescriptor ) ; currentPath . pop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns urls for the classloader [CODESPLIT] public static URL [ ] of ( ClassLoader classLoader , Class clazz ) { if ( clazz == null ) { clazz = ClassPathURLs . class ; } if ( classLoader == null ) { classLoader = clazz . getClassLoader ( ) ; } final Set < URL > urls = new LinkedHashSet <> ( ) ; while ( classLoader != null ) { if ( classLoader instanceof URLClassLoader ) { final URLClassLoader urlClassLoader = ( URLClassLoader ) classLoader ; return urlClassLoader . getURLs ( ) ; } final URL url = classModuleUrl ( classLoader , clazz ) ; if ( url != null ) { urls . add ( url ) ; } classLoader = classLoader . getParent ( ) ; } return urls . toArray ( new URL [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets new bean instance . [CODESPLIT] private void setBean ( final Object bean ) { this . bean = bean ; this . cd = ( bean == null ? null : introspector . lookup ( bean . getClass ( ) ) ) ; this . first = false ; this . updateProperty = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the bean . Detects special case of suppliers . [CODESPLIT] public void updateBean ( final Object bean ) { this . setBean ( bean ) ; if ( this . cd != null && this . cd . isSupplier ( ) ) { final Object newBean = ( ( Supplier ) this . bean ) . get ( ) ; setBean ( newBean ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads property descriptor if property was updated . [CODESPLIT] private void loadPropertyDescriptor ( ) { if ( updateProperty ) { if ( cd == null ) { propertyDescriptor = null ; } else { propertyDescriptor = cd . getPropertyDescriptor ( name , true ) ; } updateProperty = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns getter . [CODESPLIT] public Getter getGetter ( final boolean declared ) { loadPropertyDescriptor ( ) ; return propertyDescriptor != null ? propertyDescriptor . getGetter ( declared ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns setter . [CODESPLIT] public Setter getSetter ( final boolean declared ) { loadPropertyDescriptor ( ) ; return propertyDescriptor != null ? propertyDescriptor . getSetter ( declared ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the DbOom by connecting to the database . Database will be detected and DbOom will be configured to match it . [CODESPLIT] public DbOom connect ( ) { connectionProvider . init ( ) ; final DbDetector dbDetector = new DbDetector ( ) ; dbDetector . detectDatabaseAndConfigureDbOom ( connectionProvider , dbOomConfig ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an iterator to this composite . [CODESPLIT] public void add ( final Iterator < T > iterator ) { if ( allIterators . contains ( iterator ) ) { throw new IllegalArgumentException ( \"Duplicate iterator\" ) ; } allIterators . add ( iterator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if next element is available . [CODESPLIT] @ Override public boolean hasNext ( ) { if ( currentIterator == - 1 ) { currentIterator = 0 ; } for ( int i = currentIterator ; i < allIterators . size ( ) ; i ++ ) { Iterator iterator = allIterators . get ( i ) ; if ( iterator . hasNext ( ) ) { currentIterator = i ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects if there was a <code > null< / code > reading and returns <code > null< / code > if it was . Result set returns default value ( e . g . 0 ) for many getters therefore it detects if it was a null reading or it is a real value . [CODESPLIT] @ Override public < E > E readValue ( final ResultSet rs , final int index , final Class < E > destinationType , final int dbSqlType ) throws SQLException { T t = get ( rs , index , dbSqlType ) ; if ( ( t == null ) || ( rs . wasNull ( ) ) ) { return null ; } return prepareGetValue ( t , destinationType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects <code > null< / code > before storing the value into the database . [CODESPLIT] @ Override public void storeValue ( final PreparedStatement st , final int index , final Object value , final int dbSqlType ) throws SQLException { if ( value == null ) { st . setNull ( index , dbSqlType ) ; return ; } super . storeValue ( st , index , value , dbSqlType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the Joy . Returns the { [CODESPLIT] public JoddJoyRuntime start ( final ServletContext servletContext ) { LoggerProvider loggerProvider = null ; if ( loggerProviderSupplier != null ) { loggerProvider = loggerProviderSupplier . get ( ) ; } if ( loggerProvider == null ) { loggerProvider = SimpleLogger . PROVIDER ; } LoggerFactory . setLoggerProvider ( loggerProvider ) ; log = LoggerFactory . getLogger ( JoddJoy . class ) ; printLogo ( ) ; log . info ( \"Ah, Joy!\" ) ; log . info ( \"Logging using: \" + loggerProvider . getClass ( ) . getSimpleName ( ) ) ; joyPropsConsumers . accept ( joyProps ) ; joyProxettaConsumers . accept ( joyProxetta ) ; joyDbConsumers . accept ( joyDb ) ; joyPetiteConsumers . accept ( joyPetite ) ; try { joyPaths . start ( ) ; joyProps . start ( ) ; joyProxetta . start ( ) ; joyScanner . start ( ) ; joyPetite . start ( ) ; joyPetite . getPetiteContainer ( ) . addBean ( appName + \".core\" , this ) ; joyPetite . getPetiteContainer ( ) . addBean ( appName + \".scanner\" , joyScanner ) ; joyDb . start ( ) ; joyMadvoc . setServletContext ( servletContext ) ; joyMadvoc . start ( ) ; runJoyInitBeans ( ) ; // cleanup things we will not use joyScanner . stop ( ) ; } catch ( Exception ex ) { if ( log != null ) { log . error ( ex . toString ( ) , ex ) ; } else { System . out . println ( ex . toString ( ) ) ; ex . printStackTrace ( ) ; } stop ( ) ; throw ex ; } joyPetite . printBeans ( 100 ) ; joyDb . printEntities ( 100 ) ; joyMadvoc . printRoutes ( 100 ) ; System . out . println ( Chalk256 . chalk ( ) . yellow ( ) . on ( \"Joy\" ) + \" is up. Enjoy!\" ) ; log . info ( \"Joy is up. Enjoy!\" ) ; if ( joyDb . isDatabaseEnabled ( ) ) { return new JoddJoyRuntime ( appName , joyPaths . getAppDir ( ) , joyProps . getProps ( ) , joyProxetta . getProxetta ( ) , joyPetite . getPetiteContainer ( ) , joyMadvoc . getWebApp ( ) , joyDb . isDatabaseEnabled ( ) , joyDb . getConnectionProvider ( ) , joyDb . getJtxManager ( ) ) ; } else { return new JoddJoyRuntime ( appName , joyPaths . getAppDir ( ) , joyProps . getProps ( ) , joyProxetta . getProxetta ( ) , joyPetite . getPetiteContainer ( ) , joyMadvoc . getWebApp ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a logo . [CODESPLIT] private void printLogo ( ) { System . out . println ( Chalk256 . chalk ( ) . yellow ( ) . on ( Jodd . JODD ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the Joy . [CODESPLIT] public void stop ( ) { joyProps . stop ( ) ; try { joyDb . stop ( ) ; joyPetite . stop ( ) ; } catch ( Exception ignore ) { } if ( log != null ) { log . info ( \"Joy is down. Bye, bye!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new connection from current { @link jodd . http . HttpRequest request } . [CODESPLIT] @ Override public HttpConnection createHttpConnection ( final HttpRequest httpRequest ) throws IOException { final SocketHttpConnection httpConnection ; final boolean https = httpRequest . protocol ( ) . equalsIgnoreCase ( \"https\" ) ; if ( https ) { SSLSocket sslSocket = createSSLSocket ( httpRequest . host ( ) , httpRequest . port ( ) , httpRequest . connectionTimeout ( ) , httpRequest . trustAllCertificates ( ) , httpRequest . verifyHttpsHost ( ) ) ; httpConnection = new SocketHttpSecureConnection ( sslSocket ) ; } else { Socket socket = createSocket ( httpRequest . host ( ) , httpRequest . port ( ) , httpRequest . connectionTimeout ( ) ) ; httpConnection = new SocketHttpConnection ( socket ) ; } // prepare connection config httpConnection . setTimeout ( httpRequest . timeout ( ) ) ; try { // additional socket initialization httpConnection . init ( ) ; } catch ( Throwable throwable ) { // @wjw_add httpConnection . close ( ) ; throw new HttpException ( throwable ) ; } return httpConnection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a socket using socket factory . [CODESPLIT] protected Socket createSocket ( final String host , final int port , final int connectionTimeout ) throws IOException { final SocketFactory socketFactory = getSocketFactory ( proxy , false , false , connectionTimeout ) ; if ( connectionTimeout < 0 ) { return socketFactory . createSocket ( host , port ) ; } else { // creates unconnected socket Socket socket = socketFactory . createSocket ( ) ; socket . connect ( new InetSocketAddress ( host , port ) , connectionTimeout ) ; return socket ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a SSL socket . Enables default secure enabled protocols if specified . [CODESPLIT] protected SSLSocket createSSLSocket ( final String host , final int port , final int connectionTimeout , final boolean trustAll , final boolean verifyHttpsHost ) throws IOException { final SocketFactory socketFactory = getSocketFactory ( proxy , true , trustAll , connectionTimeout ) ; final Socket socket ; if ( connectionTimeout < 0 ) { socket = socketFactory . createSocket ( host , port ) ; } else { // creates unconnected socket // unfortunately, this does not work always //\t\t\tsslSocket = (SSLSocket) socketFactory.createSocket(); //\t\t\tsslSocket.connect(new InetSocketAddress(host, port), connectionTimeout); // // Note: SSLSocketFactory has several create() methods. // Those that take arguments all connect immediately // and have no options for specifying a connection timeout. // // So, we have to create a socket and connect it (with a // connection timeout), then have the SSLSocketFactory wrap // the already-connected socket. // socket = Sockets . connect ( host , port , connectionTimeout ) ; //sock.setSoTimeout(readTimeout); //socket.connect(new InetSocketAddress(host, port), connectionTimeout); // continue to wrap this plain socket with ssl socket... } // wrap plain socket in an SSL socket SSLSocket sslSocket ; if ( socket instanceof SSLSocket ) { sslSocket = ( SSLSocket ) socket ; } else { if ( socketFactory instanceof SSLSocketFactory ) { sslSocket = ( SSLSocket ) ( ( SSLSocketFactory ) socketFactory ) . createSocket ( socket , host , port , true ) ; } else { sslSocket = ( SSLSocket ) ( getDefaultSSLSocketFactory ( trustAll ) ) . createSocket ( socket , host , port , true ) ; } } // sslSocket is now ready if ( secureEnabledProtocols != null ) { final String [ ] values = StringUtil . splitc ( secureEnabledProtocols , ' ' ) ; StringUtil . trimAll ( values ) ; sslSocket . setEnabledProtocols ( values ) ; } // set SSL parameters to allow host name verifier if ( verifyHttpsHost ) { final SSLParameters sslParams = new SSLParameters ( ) ; sslParams . setEndpointIdentificationAlgorithm ( \"HTTPS\" ) ; sslSocket . setSSLParameters ( sslParams ) ; } return sslSocket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns default SSL socket factory allowing setting trust managers . [CODESPLIT] protected SSLSocketFactory getDefaultSSLSocketFactory ( final boolean trustAllCertificates ) throws IOException { if ( trustAllCertificates ) { try { SSLContext sc = SSLContext . getInstance ( sslProtocol ) ; sc . init ( null , TrustManagers . TRUST_ALL_CERTS , new java . security . SecureRandom ( ) ) ; return sc . getSocketFactory ( ) ; } catch ( NoSuchAlgorithmException | KeyManagementException e ) { throw new IOException ( e ) ; } } else { return ( SSLSocketFactory ) SSLSocketFactory . getDefault ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns socket factory based on proxy type and SSL requirements . [CODESPLIT] protected SocketFactory getSocketFactory ( final ProxyInfo proxy , final boolean ssl , final boolean trustAllCertificates , final int connectionTimeout ) throws IOException { switch ( proxy . getProxyType ( ) ) { case NONE : if ( ssl ) { return getDefaultSSLSocketFactory ( trustAllCertificates ) ; } else { return SocketFactory . getDefault ( ) ; } case HTTP : return new HTTPProxySocketFactory ( proxy , connectionTimeout ) ; case SOCKS4 : return new Socks4ProxySocketFactory ( proxy , connectionTimeout ) ; case SOCKS5 : return new Socks5ProxySocketFactory ( proxy , connectionTimeout ) ; default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates random string whose length is the number of characters specified . Characters are chosen from the set of characters specified . [CODESPLIT] public String random ( int count , final char [ ] chars ) { if ( count == 0 ) { return StringPool . EMPTY ; } final char [ ] result = new char [ count ] ; while ( count -- > 0 ) { result [ count ] = chars [ rnd . nextInt ( chars . length ) ] ; } return new String ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates random string whose length is the number of characters specified . Characters are chosen from the provided range . [CODESPLIT] public String random ( int count , final char start , final char end ) { if ( count == 0 ) { return StringPool . EMPTY ; } final char [ ] result = new char [ count ] ; final int len = end - start + 1 ; while ( count -- > 0 ) { result [ count ] = ( char ) ( rnd . nextInt ( len ) + start ) ; } return new String ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates random string whose length is the number of characters specified . Characters are chosen from the multiple sets defined by range pairs . All ranges must be in acceding order . [CODESPLIT] public String randomRanges ( int count , final char ... ranges ) { if ( count == 0 ) { return StringPool . EMPTY ; } int i = 0 ; int len = 0 ; final int [ ] lens = new int [ ranges . length ] ; while ( i < ranges . length ) { int gap = ranges [ i + 1 ] - ranges [ i ] + 1 ; len += gap ; lens [ i ] = len ; i += 2 ; } final char [ ] result = new char [ count ] ; while ( count -- > 0 ) { char c = 0 ; int r = rnd . nextInt ( len ) ; for ( i = 0 ; i < ranges . length ; i += 2 ) { if ( r < lens [ i ] ) { r += ranges [ i ] ; if ( i != 0 ) { r -= lens [ i - 2 ] ; } c = ( char ) r ; break ; } } result [ count ] = c ; } return new String ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses EML with provided EML content . [CODESPLIT] public ReceivedEmail parse ( final String emlContent , final String charset ) throws UnsupportedEncodingException , MessagingException { final byte [ ] bytes = emlContent . getBytes ( charset ) ; return parse ( bytes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses EML with provided EML content . [CODESPLIT] public ReceivedEmail parse ( final String emlContent ) throws MessagingException { try { return parse ( emlContent , JoddCore . encoding ) ; } catch ( final UnsupportedEncodingException ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts EML parsing with provided EML { @link File } . [CODESPLIT] public ReceivedEmail parse ( final File emlFile ) throws FileNotFoundException , MessagingException { final FileInputStream fileInputStream = new FileInputStream ( emlFile ) ; try { return parse ( fileInputStream ) ; } finally { StreamUtil . close ( fileInputStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the EML content . If { @link Session } is not created default one will be used . [CODESPLIT] protected ReceivedEmail parse ( final InputStream emlContentInputStream ) throws MessagingException { if ( getSession ( ) == null ) { createSession ( getProperties ( ) ) ; } try { final MimeMessage message = new MimeMessage ( getSession ( ) , emlContentInputStream ) ; return new ReceivedEmail ( message , false , null ) ; } finally { StreamUtil . close ( emlContentInputStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new type for JSON array objects . It returns a collection . Later the collection will be converted into the target type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected Collection < Object > newArrayInstance ( final Class targetType ) { if ( targetType == null || targetType == List . class || targetType == Collection . class || targetType . isArray ( ) ) { return listSupplier . get ( ) ; } if ( targetType == Set . class ) { return new HashSet <> ( ) ; } try { return ( Collection < Object > ) targetType . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { throw new JsonException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new object or a <code > HashMap< / code > if type is not specified . [CODESPLIT] protected Object newObjectInstance ( final Class targetType ) { if ( targetType == null || targetType == Map . class ) { return mapSupplier . get ( ) ; } final ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( targetType ) ; final CtorDescriptor ctorDescriptor = cd . getDefaultCtorDescriptor ( true ) ; if ( ctorDescriptor == null ) { throw new JsonException ( \"Default ctor not found for: \" + targetType . getName ( ) ) ; } try { //\t\t\treturn ClassUtil.newInstance(targetType); return ctorDescriptor . getConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { throw new JsonException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects value into the targets property . [CODESPLIT] protected void injectValueIntoObject ( final Object target , final PropertyDescriptor pd , final Object value ) { Object convertedValue = value ; if ( value != null ) { Class targetClass = pd . getType ( ) ; convertedValue = convertType ( value , targetClass ) ; } try { Setter setter = pd . getSetter ( true ) ; if ( setter != null ) { setter . invokeSetter ( target , convertedValue ) ; } } catch ( Exception ex ) { throw new JsonException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts type of the given value . [CODESPLIT] protected Object convertType ( final Object value , final Class targetType ) { final Class valueClass = value . getClass ( ) ; if ( valueClass == targetType ) { return value ; } try { return TypeConverterManager . get ( ) . convertType ( value , targetType ) ; } catch ( Exception ex ) { if ( ! strictTypes ) { return null ; } throw new JsonException ( \"Type conversion failed\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visit an implementation of a service . [CODESPLIT] public void visitProvide ( final String service , final String ... providers ) { if ( mv != null ) { mv . visitProvide ( service , providers ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Short get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Short . valueOf ( rs . getShort ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Short value , final int dbSqlType ) throws SQLException { st . setShort ( index , value . shortValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- header [CODESPLIT] @ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { wd . init ( name , superName , suffix , reqProxyClassName ) ; // write destination class final int v = ProxettaAsmUtil . resolveJavaVersion ( version ) ; super . visit ( v , access , wd . thisReference , signature , wd . superName , interfaces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates default implementation of the type cache . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < A > TypeCache < A > createDefault ( ) { return ( TypeCache < A > ) Defaults . implementation . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add values to the map . [CODESPLIT] public T put ( final Class < ? > type , final T value ) { return map . put ( type , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns existing value or add default supplied one . Use this method instead of { [CODESPLIT] public T get ( final Class < ? > key , final Supplier < T > valueSupplier ) { return map . computeIfAbsent ( key , aClass -> valueSupplier . get ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Long get ( final ResultSet rs , final int index , final int dbSqlType ) throws SQLException { return Long . valueOf ( rs . getLong ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void set ( final PreparedStatement st , final int index , final Long value , final int dbSqlType ) throws SQLException { st . setLong ( index , value . longValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects types methods and return map of { [CODESPLIT] protected HashMap < String , MethodDescriptor [ ] > inspectMethods ( ) { boolean scanAccessible = classDescriptor . isScanAccessible ( ) ; if ( classDescriptor . isSystemClass ( ) ) { scanAccessible = false ; } final Class type = classDescriptor . getType ( ) ; final Method [ ] methods = scanAccessible ? ClassUtil . getAccessibleMethods ( type ) : ClassUtil . getSupportedMethods ( type ) ; final HashMap < String , MethodDescriptor [ ] > map = new HashMap <> ( methods . length ) ; for ( final Method method : methods ) { final String methodName = method . getName ( ) ; MethodDescriptor [ ] mds = map . get ( methodName ) ; if ( mds == null ) { mds = new MethodDescriptor [ 1 ] ; } else { mds = ArraysUtil . resize ( mds , mds . length + 1 ) ; } map . put ( methodName , mds ) ; mds [ mds . length - 1 ] = createMethodDescriptor ( method ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a method that matches given name and parameter types . Returns <code > null< / code > if method is not found . [CODESPLIT] public MethodDescriptor getMethodDescriptor ( final String name , final Class [ ] paramTypes ) { final MethodDescriptor [ ] methodDescriptors = methodsMap . get ( name ) ; if ( methodDescriptors == null ) { return null ; } for ( MethodDescriptor methodDescriptor : methodDescriptors ) { final Method m = methodDescriptor . getMethod ( ) ; if ( ClassUtil . compareParameters ( m . getParameterTypes ( ) , paramTypes ) ) { return methodDescriptor ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns method descriptor for given name . If more then one methods with the same name exists one method will be returned ( not determined which one ) . Returns <code > null< / code > if no method exist in this collection by given name . [CODESPLIT] public MethodDescriptor getMethodDescriptor ( final String name ) { final MethodDescriptor [ ] methodDescriptors = methodsMap . get ( name ) ; if ( methodDescriptors == null ) { return null ; } if ( methodDescriptors . length != 1 ) { throw new IllegalArgumentException ( \"Method name not unique: \" + name ) ; } return methodDescriptors [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all methods . Cached . Lazy . [CODESPLIT] public MethodDescriptor [ ] getAllMethodDescriptors ( ) { if ( allMethods == null ) { final List < MethodDescriptor > allMethodsList = new ArrayList <> ( ) ; for ( MethodDescriptor [ ] methodDescriptors : methodsMap . values ( ) ) { Collections . addAll ( allMethodsList , methodDescriptors ) ; } final MethodDescriptor [ ] allMethods = allMethodsList . toArray ( new MethodDescriptor [ 0 ] ) ; Arrays . sort ( allMethods , Comparator . comparing ( md -> md . getMethod ( ) . getName ( ) ) ) ; this . allMethods = allMethods ; } return allMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves IP address from a hostname . [CODESPLIT] public static String resolveIpAddress ( final String hostname ) { try { InetAddress netAddress ; if ( hostname == null || hostname . equalsIgnoreCase ( LOCAL_HOST ) ) { netAddress = InetAddress . getLocalHost ( ) ; } else { netAddress = Inet4Address . getByName ( hostname ) ; } return netAddress . getHostAddress ( ) ; } catch ( UnknownHostException ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns IP address as integer . [CODESPLIT] public static int getIpAsInt ( final String ipAddress ) { int ipIntValue = 0 ; String [ ] tokens = StringUtil . splitc ( ipAddress , ' ' ) ; for ( String token : tokens ) { if ( ipIntValue > 0 ) { ipIntValue <<= 8 ; } ipIntValue += Integer . parseInt ( token ) ; } return ipIntValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks given string against IP address v4 format . [CODESPLIT] public static boolean validateAgaintIPAdressV4Format ( final String input ) { if ( input == null ) { return false ; } int hitDots = 0 ; char [ ] data = input . toCharArray ( ) ; for ( int i = 0 ; i < data . length ; i ++ ) { char c = data [ i ] ; int b = 0 ; do { if ( c < ' ' || c > ' ' ) { return false ; } b = ( b * 10 + c ) - 48 ; if ( ++ i >= data . length ) { break ; } c = data [ i ] ; } while ( c != ' ' ) ; if ( b > 255 ) { return false ; } hitDots ++ ; } return hitDots == 4 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves host name from IP address bytes . [CODESPLIT] public static String resolveHostName ( final byte [ ] ip ) { try { InetAddress address = InetAddress . getByAddress ( ip ) ; return address . getHostName ( ) ; } catch ( UnknownHostException ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downloads resource as byte array . [CODESPLIT] public static byte [ ] downloadBytes ( final String url ) throws IOException { try ( InputStream inputStream = new URL ( url ) . openStream ( ) ) { return StreamUtil . readBytes ( inputStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downloads resource as String . [CODESPLIT] public static String downloadString ( final String url , final String encoding ) throws IOException { try ( InputStream inputStream = new URL ( url ) . openStream ( ) ) { return new String ( StreamUtil . readChars ( inputStream , encoding ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downloads resource to a file potentially very efficiently . [CODESPLIT] public static void downloadFile ( final String url , final File file ) throws IOException { try ( InputStream inputStream = new URL ( url ) . openStream ( ) ; ReadableByteChannel rbc = Channels . newChannel ( inputStream ) ; FileChannel fileChannel = FileChannel . open ( file . toPath ( ) , StandardOpenOption . CREATE , StandardOpenOption . TRUNCATE_EXISTING , StandardOpenOption . WRITE ) ) { fileChannel . transferFrom ( rbc , 0 , Long . MAX_VALUE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the response and parse it using Lagarto parser . It first calls { [CODESPLIT] @ Override public void doFilter ( final ServletRequest servletRequest , final ServletResponse servletResponse , final FilterChain filterChain ) throws IOException , ServletException { HttpServletRequest request = ( HttpServletRequest ) servletRequest ; HttpServletResponse response = ( HttpServletResponse ) servletResponse ; String actionPath = DispatcherUtil . getServletPath ( request ) ; if ( processActionPath ( request , response , actionPath ) ) { return ; } if ( ! acceptActionPath ( request , actionPath ) ) { filterChain . doFilter ( servletRequest , servletResponse ) ; return ; } BufferResponseWrapper wrapper = new BufferResponseWrapper ( response ) ; filterChain . doFilter ( servletRequest , wrapper ) ; // reset servlet response content length AFTER the chain, since // servlet container may set it and we are changing the content. servletResponse . setContentLength ( - 1 ) ; char [ ] content = wrapper . getBufferContentAsChars ( ) ; if ( ( content != null ) && ( content . length != 0 ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Lagarto is about to parse: \" + actionPath ) ; } try { content = parse ( content , request ) ; } catch ( Exception ex ) { log . error ( \"Error parsing\" , ex ) ; throw new ServletException ( ex ) ; } wrapper . writeContentToResponse ( content ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accepts action path for further parsing . By default only <code > * . htm ( l ) < / code > requests are passed through and those without any extension . [CODESPLIT] protected boolean acceptActionPath ( final HttpServletRequest request , final String actionPath ) { String extension = FileNameUtil . getExtension ( actionPath ) ; if ( extension . length ( ) == 0 ) { return true ; } if ( extension . equals ( \"html\" ) || extension . equals ( \"htm\" ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { [CODESPLIT] @ Override public void render ( final ActionRequest actionRequest , final Object resultValue ) { final Chain chainResult ; if ( resultValue == null ) { chainResult = Chain . to ( StringPool . EMPTY ) ; } else { if ( resultValue instanceof String ) { chainResult = Chain . to ( ( String ) resultValue ) ; } else { chainResult = ( Chain ) resultValue ; } } final String resultBasePath = actionRequest . getActionRuntime ( ) . getResultBasePath ( ) ; final String resultPath = resultMapper . resolveResultPathString ( resultBasePath , chainResult . path ( ) ) ; actionRequest . setNextActionPath ( resultPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object intercept ( final ActionRequest actionRequest ) throws Exception { HttpServletRequest servletRequest = actionRequest . getHttpServletRequest ( ) ; // detect multipart request if ( ServletUtil . isMultipartRequest ( servletRequest ) ) { servletRequest = new MultipartRequestWrapper ( servletRequest , fileUploader . get ( ) , madvocEncoding . getEncoding ( ) ) ; actionRequest . bind ( servletRequest ) ; } // do it inject ( actionRequest ) ; final Object result = actionRequest . invoke ( ) ; outject ( actionRequest ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs injection . [CODESPLIT] protected void inject ( final ActionRequest actionRequest ) { final Targets targets = actionRequest . getTargets ( ) ; final ServletContext servletContext = actionRequest . getHttpServletRequest ( ) . getServletContext ( ) ; scopeResolver . forEachScope ( madvocScope -> madvocScope . inject ( servletContext , targets ) ) ; scopeResolver . forEachScope ( madvocScope -> madvocScope . inject ( actionRequest , targets ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs outjection . [CODESPLIT] protected void outject ( final ActionRequest actionRequest ) { final Targets targets = actionRequest . getTargets ( ) ; scopeResolver . forEachScope ( madvocScope -> madvocScope . outject ( actionRequest , targets ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a socket . [CODESPLIT] public static Socket connect ( final String hostname , final int port ) throws IOException { final Socket socket = new Socket ( ) ; socket . connect ( new InetSocketAddress ( hostname , port ) ) ; return socket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a socket with a timeout . [CODESPLIT] public static Socket connect ( final String hostname , final int port , final int connectionTimeout ) throws IOException { final Socket socket = new Socket ( ) ; if ( connectionTimeout <= 0 ) { socket . connect ( new InetSocketAddress ( hostname , port ) ) ; } else { socket . connect ( new InetSocketAddress ( hostname , port ) , connectionTimeout ) ; } return socket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares classname for loading respecting the arrays . Returns <code > null< / code > if class name is not an array . [CODESPLIT] public static String prepareArrayClassnameForLoading ( String className ) { int bracketCount = StringUtil . count ( className , ' ' ) ; if ( bracketCount == 0 ) { // not an array return null ; } String brackets = StringUtil . repeat ( ' ' , bracketCount ) ; int bracketIndex = className . indexOf ( ' ' ) ; className = className . substring ( 0 , bracketIndex ) ; int primitiveNdx = getPrimitiveClassNameIndex ( className ) ; if ( primitiveNdx >= 0 ) { className = String . valueOf ( PRIMITIVE_BYTECODE_NAME [ primitiveNdx ] ) ; return brackets + className ; } else { return brackets + ' ' + className + ' ' ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects if provided class name is a primitive type . Returns > = 0 number if so . [CODESPLIT] private static int getPrimitiveClassNameIndex ( final String className ) { int dotIndex = className . indexOf ( ' ' ) ; if ( dotIndex != - 1 ) { return - 1 ; } return Arrays . binarySearch ( PRIMITIVE_TYPE_NAMES , className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads class by name . [CODESPLIT] @ Override public Class loadClass ( final String className , final ClassLoader classLoader ) throws ClassNotFoundException { String arrayClassName = prepareArrayClassnameForLoading ( className ) ; if ( ( className . indexOf ( ' ' ) == - 1 ) && ( arrayClassName == null ) ) { // maybe a primitive int primitiveNdx = getPrimitiveClassNameIndex ( className ) ; if ( primitiveNdx >= 0 ) { return PRIMITIVE_TYPES [ primitiveNdx ] ; } } // try #1 - using provided class loader if ( classLoader != null ) { Class klass = loadClass ( className , arrayClassName , classLoader ) ; if ( klass != null ) { return klass ; } } // try #2 - using thread class loader ClassLoader currentThreadClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( ( currentThreadClassLoader != null ) && ( currentThreadClassLoader != classLoader ) ) { Class klass = loadClass ( className , arrayClassName , currentThreadClassLoader ) ; if ( klass != null ) { return klass ; } } // try #3 - using caller classloader, similar as Class.forName() //Class callerClass = ReflectUtil.getCallerClass(2); Class callerClass = ClassUtil . getCallerClass ( ) ; ClassLoader callerClassLoader = callerClass . getClassLoader ( ) ; if ( ( callerClassLoader != classLoader ) && ( callerClassLoader != currentThreadClassLoader ) ) { Class klass = loadClass ( className , arrayClassName , callerClassLoader ) ; if ( klass != null ) { return klass ; } } // try #4 - everything failed, try alternative array loader if ( arrayClassName != null ) { try { return loadArrayClassByComponentType ( className , classLoader ) ; } catch ( ClassNotFoundException ignore ) { } } throw new ClassNotFoundException ( \"Class not found: \" + className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a class using provided class loader . If class is an array it will be first loaded using the <code > Class . forName< / code > ! We must use this since for JDK { [CODESPLIT] protected Class loadClass ( final String className , final String arrayClassName , final ClassLoader classLoader ) { if ( arrayClassName != null ) { try { if ( loadArrayClassByComponentTypes ) { return loadArrayClassByComponentType ( className , classLoader ) ; } else { return Class . forName ( arrayClassName , true , classLoader ) ; } } catch ( ClassNotFoundException ignore ) { } } try { return classLoader . loadClass ( className ) ; } catch ( ClassNotFoundException ignore ) { } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads array class using component type . [CODESPLIT] protected Class loadArrayClassByComponentType ( final String className , final ClassLoader classLoader ) throws ClassNotFoundException { int ndx = className . indexOf ( ' ' ) ; int multi = StringUtil . count ( className , ' ' ) ; String componentTypeName = className . substring ( 0 , ndx ) ; Class componentType = loadClass ( componentTypeName , classLoader ) ; if ( multi == 1 ) { return Array . newInstance ( componentType , 0 ) . getClass ( ) ; } int [ ] multiSizes ; if ( multi == 2 ) { multiSizes = new int [ ] { 0 , 0 } ; } else if ( multi == 3 ) { multiSizes = new int [ ] { 0 , 0 , 0 } ; } else { multiSizes = ( int [ ] ) Array . newInstance ( int . class , multi ) ; } return Array . newInstance ( componentType , multiSizes ) . getClass ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate all beans and invokes registered destroy methods . [CODESPLIT] @ Override public void shutdown ( ) { for ( final BeanData beanData : instances . values ( ) ) { beanData . callDestroyMethods ( ) ; } instances . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates binary search wrapper over an array . [CODESPLIT] public static < T extends Comparable > BinarySearch < T > forArray ( final T [ ] array ) { return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { \"unchecked\" } ) protected int compare ( final int index , final T element ) { return array [ index ] . compareTo ( element ) ; } @ Override protected int getLastIndex ( ) { return array . length - 1 ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates binary search wrapper over an array with given comparator . [CODESPLIT] public static < T > BinarySearch < T > forArray ( final T [ ] array , final Comparator < T > comparator ) { return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { \"unchecked\" } ) protected int compare ( final int index , final T element ) { return comparator . compare ( array [ index ] , element ) ; } @ Override protected int getLastIndex ( ) { return array . length - 1 ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds index of given element in inclusive index range . Returns negative value if element is not found . [CODESPLIT] public int find ( final E element , int low , int high ) { while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( mid , element ) ; if ( delta < 0 ) { low = mid + 1 ; } else if ( delta > 0 ) { high = mid - 1 ; } else { return mid ; } } // not found return - ( low + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines excluded property names . [CODESPLIT] public T exclude ( final String ... excludes ) { for ( String ex : excludes ) { rules . exclude ( ex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines included property names . [CODESPLIT] public T include ( final String ... includes ) { for ( String in : includes ) { rules . include ( in ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines included property names as public properties of given template class . Sets to black list mode . [CODESPLIT] public T includeAs ( final Class template ) { blacklist = false ; String [ ] properties = getAllBeanPropertyNames ( template , false ) ; include ( properties ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the tag with the index of first < . Resets all tag data . [CODESPLIT] public void start ( final int startIndex ) { this . tagStartIndex = startIndex ; this . name = null ; this . idNdx = - 1 ; this . attributesCount = 0 ; this . tagLength = 0 ; this . modified = false ; this . type = TagType . START ; this . rawTag = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- match [CODESPLIT] @ Override public boolean nameEquals ( final CharSequence charSequence ) { return caseSensitive ? CharSequenceUtil . equals ( name , charSequence ) : CharSequenceUtil . equalsIgnoreCase ( name , charSequence ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- util [CODESPLIT] private void ensureLength ( ) { if ( attributesCount + 1 >= attrNames . length ) { attrNames = ArraysUtil . resize ( attrNames , attributesCount * 2 ) ; attrValues = ArraysUtil . resize ( attrValues , attributesCount * 2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- output [CODESPLIT] private void appendTo ( final Appendable out ) { try { out . append ( type . getStartString ( ) ) ; out . append ( name ) ; if ( attributesCount > 0 ) { for ( int i = 0 ; i < attributesCount ; i ++ ) { out . append ( ' ' ) ; out . append ( attrNames [ i ] ) ; final CharSequence value = attrValues [ i ] ; if ( value != null ) { out . append ( ' ' ) . append ( ' ' ) ; out . append ( HtmlEncoder . attributeDoubleQuoted ( value ) ) ; out . append ( ' ' ) ; } } } out . append ( type . getEndString ( ) ) ; } catch ( IOException ioex ) { throw new LagartoException ( ioex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers component using its { @link #resolveBaseComponentName ( Class ) base name } . Previously defined component will be removed . [CODESPLIT] public void registerComponent ( final Class component ) { String name = resolveBaseComponentName ( component ) ; registerComponent ( name , component ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers Madvoc component with given name . [CODESPLIT] public < T > void registerComponent ( final String name , final Class < T > component , final Consumer < T > consumer ) { log . debug ( ( ) -> \"Madvoc WebApp component: [\" + name + \"] --> \" + component . getName ( ) ) ; madpc . removeBean ( name ) ; madpc . registerPetiteBean ( component , name , null , null , false , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers component instance using its { @link #resolveBaseComponentName ( Class ) base name } . Previously defined component will be removed . [CODESPLIT] public void registerComponentInstance ( final Object componentInstance ) { Class component = componentInstance . getClass ( ) ; String name = resolveBaseComponentName ( component ) ; registerComponentInstance ( name , componentInstance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers component instance and wires it with internal container . Warning : in this moment we can not guarantee that all other components are registered replaced or configuration is update ; therefore DO NOT USE injection unless you are absolutely sure it works . [CODESPLIT] public void registerComponentInstance ( final String name , final Object componentInstance ) { log . debug ( ( ) -> \"Madvoc WebApp component: [\" + name + \"] --> \" + componentInstance . getClass ( ) . getName ( ) ) ; madpc . removeBean ( name ) ; madpc . addBean ( name , componentInstance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires the Madvoc event . Warning : since event handlers may register more handlers we must collect first the list of components that matches the type and then to execute . [CODESPLIT] public void fireEvent ( final Class listenerType ) { final Set < String > existing = new HashSet <> ( ) ; while ( true ) { MutableInteger newCount = MutableInteger . of ( 0 ) ; madpc . forEachBeanType ( listenerType , name -> { if ( existing . add ( name ) ) { // name not found, fire! newCount . value ++ ; Object listener = lookupComponent ( name ) ; if ( listener != null ) { MadvocComponentLifecycle . invoke ( listener , listenerType ) ; } } } ) ; if ( newCount . value == 0 ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns registered component or { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public < T > T lookupComponent ( final Class < T > component ) { String name = resolveBaseComponentName ( component ) ; return ( T ) madpc . getBean ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns existing component . Throws an exception if component is not registered . [CODESPLIT] public < T > T requestComponent ( final Class < T > component ) { T existingComponent = lookupComponent ( component ) ; if ( existingComponent == null ) { throw new MadvocException ( \"Madvoc component not found: \" + component . getName ( ) ) ; } return existingComponent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns existing component . Throws an exception if component is not registered . [CODESPLIT] public < T > T requestComponent ( final String componentName ) { T existingComponent = ( T ) lookupComponent ( componentName ) ; if ( existingComponent == null ) { throw new MadvocException ( \"Madvoc component not found: \" + componentName ) ; } return existingComponent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the name of the last base non - abstract subclass for provided component . It iterates all subclasses up to the <code > Object< / cde > and declares the last non - abstract class as base component . Component name will be resolved from the founded base component . [CODESPLIT] private String resolveBaseComponentName ( Class component ) { Class lastComponent = component ; while ( true ) { Class superClass = component . getSuperclass ( ) ; if ( superClass . equals ( Object . class ) ) { break ; } component = superClass ; if ( ! Modifier . isAbstract ( component . getModifiers ( ) ) ) { lastComponent = component ; } } return madpc . resolveBeanName ( lastComponent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the query after initialization . Besides default work it checks if sql generator is used and if so generator hints and query parameters will be used for this query . Note regarding hints : since hints can be added manually generators hints will be ignored if there exists some manually set hints . [CODESPLIT] @ Override protected void prepareQuery ( ) { super . prepareQuery ( ) ; if ( sqlgen == null ) { return ; } if ( hints == null ) { String [ ] joinHints = sqlgen . getJoinHints ( ) ; if ( joinHints != null ) { withHints ( joinHints ) ; } } // insert parameters Map < String , ParameterValue > parameters = sqlgen . getQueryParameters ( ) ; if ( parameters == null ) { return ; } for ( Map . Entry < String , ParameterValue > entry : parameters . entrySet ( ) ) { String paramName = entry . getKey ( ) ; ParameterValue param = entry . getValue ( ) ; DbEntityColumnDescriptor dec = param . getColumnDescriptor ( ) ; if ( dec == null ) { setObject ( paramName , param . getValue ( ) ) ; } else { resolveColumnDbSqlType ( connection , dec ) ; setObject ( paramName , param . getValue ( ) , dec . getSqlTypeClass ( ) , dec . getDbSqlType ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves column db sql type and populates it in column descriptor if missing . [CODESPLIT] protected void resolveColumnDbSqlType ( final Connection connection , final DbEntityColumnDescriptor dec ) { if ( dec . dbSqlType != SqlType . DB_SQLTYPE_UNKNOWN ) { return ; } ResultSet rs = null ; DbEntityDescriptor ded = dec . getDbEntityDescriptor ( ) ; try { DatabaseMetaData dmd = connection . getMetaData ( ) ; rs = dmd . getColumns ( null , ded . getSchemaName ( ) , ded . getTableName ( ) , dec . getColumnName ( ) ) ; if ( rs . next ( ) ) { dec . dbSqlType = rs . getInt ( \"DATA_TYPE\" ) ; } else { dec . dbSqlType = SqlType . DB_SQLTYPE_NOT_AVAILABLE ; if ( log . isWarnEnabled ( ) ) { log . warn ( \"Column SQL type not available: \" + ded . toString ( ) + ' ' + dec . getColumnName ( ) ) ; } } } catch ( SQLException sex ) { dec . dbSqlType = SqlType . DB_SQLTYPE_NOT_AVAILABLE ; if ( log . isWarnEnabled ( ) ) { log . warn ( \"Column SQL type not resolved: \" + ded . toString ( ) + ' ' + dec . getColumnName ( ) , sex ) ; } } finally { DbUtil . close ( rs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pre - process SQL before using it . If string starts with a non - ascii char or it has no spaces it will be loaded from the query map . [CODESPLIT] protected String preprocessSql ( String sqlString ) { // detects callable statement if ( sqlString . charAt ( 0 ) == ' ' ) { return sqlString ; } // quickly detect if SQL string is a key if ( ! CharUtil . isAlpha ( sqlString . charAt ( 0 ) ) ) { sqlString = sqlString . substring ( 1 ) ; } else if ( sqlString . indexOf ( ' ' ) != - 1 ) { return sqlString ; } final String sqlFromMap = dbOom . queryMap ( ) . getQuery ( sqlString ) ; if ( sqlFromMap != null ) { sqlString = sqlFromMap . trim ( ) ; } return sqlString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares a row ( array of rows mapped object ) using hints . Returns either single object or objects array . [CODESPLIT] protected Object resolveRowResults ( Object [ ] row ) { if ( hintResolver == null ) { hintResolver = new JoinHintResolver ( ) ; } row = hintResolver . join ( row , hints ) ; return row . length == 1 ? row [ 0 ] : row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory for result sets mapper . [CODESPLIT] protected ResultSetMapper createResultSetMapper ( final ResultSet resultSet ) { final Map < String , ColumnData > columnAliases = sqlgen != null ? sqlgen . getColumnData ( ) : null ; return new DefaultResultSetMapper ( dbOom , resultSet , columnAliases , cacheEntities , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds generated key column of given type . [CODESPLIT] public < T > T findGeneratedKey ( final Class < T > type ) { return find ( new Class [ ] { type } , false , getGeneratedColumns ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates entity with generated column values from executed query . [CODESPLIT] public void populateGeneratedKeys ( final Object entity ) { final String [ ] generatedColumns = getGeneratedColumnNames ( ) ; if ( generatedColumns == null ) { return ; } DbEntityDescriptor ded = dbOom . entityManager ( ) . lookupType ( entity . getClass ( ) ) ; // prepare key types Class [ ] keyTypes = new Class [ generatedColumns . length ] ; String [ ] properties = new String [ generatedColumns . length ] ; for ( int i = 0 ; i < generatedColumns . length ; i ++ ) { String column = generatedColumns [ i ] ; DbEntityColumnDescriptor decd = ded . findByColumnName ( column ) ; if ( decd != null ) { keyTypes [ i ] = decd . getPropertyType ( ) ; properties [ i ] = decd . getPropertyName ( ) ; } } final Object keyValues = findGeneratedColumns ( keyTypes ) ; if ( ! keyValues . getClass ( ) . isArray ( ) ) { BeanUtil . declared . setProperty ( entity , properties [ 0 ] , keyValues ) ; } else { for ( int i = 0 ; i < properties . length ; i ++ ) { BeanUtil . declared . setProperty ( entity , properties [ i ] , ( ( Object [ ] ) keyValues ) [ i ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires interceptor from Petite container . [CODESPLIT] @ Override protected < R extends ActionInterceptor > R createWrapper ( final Class < R > wrapperClass ) { return petiteContainer . createBean ( wrapperClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the current parameter values immediately . <p > In general parameter values remain in force for repeated use of a statement . Setting a parameter value automatically clears its previous value . However in some cases it is useful to immediately release the resources used by the current parameter values ; this can be done by calling the method <code > clearParameters< / code > . [CODESPLIT] public Q clearParameters ( ) { init ( ) ; if ( preparedStatement == null ) { return _this ( ) ; } try { preparedStatement . clearParameters ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- null [CODESPLIT] public Q setNull ( final int index , final int type ) { initPrepared ( ) ; try { preparedStatement . setNull ( index , type ) ; } catch ( SQLException sex ) { throw new DbSqlException ( this , \"Failed to set null to parameter: \" + index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- int [CODESPLIT] public Q setInteger ( final int index , final int value ) { initPrepared ( ) ; try { preparedStatement . setInt ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Integer [CODESPLIT] public Q setInteger ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . INTEGER ) ; } else { setInteger ( index , value . intValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Boolean [CODESPLIT] public Q setBoolean ( final int index , final Boolean value ) { if ( value == null ) { setNull ( index , Types . BOOLEAN ) ; } else { setBoolean ( index , value . booleanValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Long [CODESPLIT] public Q setLong ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . BIGINT ) ; } else { setLong ( index , value . longValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Byte [CODESPLIT] public Q setByte ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . SMALLINT ) ; } else { setByte ( index , value . byteValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- double [CODESPLIT] public Q setDouble ( final int index , final double value ) { initPrepared ( ) ; try { preparedStatement . setDouble ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Double [CODESPLIT] public Q setDouble ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . DOUBLE ) ; } else { setDouble ( index , value . doubleValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Float [CODESPLIT] public Q setFloat ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . FLOAT ) ; } else { setFloat ( index , value . floatValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Short [CODESPLIT] public Q setShort ( final int index , final Number value ) { if ( value == null ) { setNull ( index , Types . SMALLINT ) ; } else { setShort ( index , value . shortValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- string [CODESPLIT] public Q setString ( final int index , final String value ) { initPrepared ( ) ; try { preparedStatement . setString ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- date [CODESPLIT] public Q setDate ( final int index , final Date value ) { initPrepared ( ) ; try { preparedStatement . setDate ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- time [CODESPLIT] public Q setTime ( final int index , final Time value ) { initPrepared ( ) ; try { preparedStatement . setTime ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- timestamp [CODESPLIT] public Q setTimestamp ( final int index , final Timestamp value ) { initPrepared ( ) ; try { preparedStatement . setTimestamp ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- big decimal [CODESPLIT] public Q setBigDecimal ( final int index , final BigDecimal value ) { initPrepared ( ) ; try { preparedStatement . setBigDecimal ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- big integer [CODESPLIT] public Q setBigInteger ( final int index , final BigInteger value ) { if ( value == null ) { setNull ( index , Types . NUMERIC ) ; } else { setLong ( index , value . longValue ( ) ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- URL [CODESPLIT] public Q setURL ( final int index , final URL value ) { initPrepared ( ) ; try { preparedStatement . setURL ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- BLOB [CODESPLIT] public Q setBlob ( final int index , final Blob value ) { initPrepared ( ) ; try { preparedStatement . setBlob ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- CLOB [CODESPLIT] public Q setClob ( final int index , final Clob value ) { initPrepared ( ) ; try { preparedStatement . setClob ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Array [CODESPLIT] public Q setArray ( final int index , final Array value ) { initPrepared ( ) ; try { preparedStatement . setArray ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- Ref [CODESPLIT] public Q setRef ( final int index , final Ref value ) { initPrepared ( ) ; try { preparedStatement . setRef ( index , value ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- ascii streams [CODESPLIT] public Q setAsciiStream ( final int index , final InputStream stream ) { initPrepared ( ) ; try { preparedStatement . setAsciiStream ( index , stream , stream . available ( ) ) ; } catch ( IOException | SQLException ioex ) { throwSetParamError ( index , ioex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets bean parameters from bean . Non - existing bean properties are ignored . [CODESPLIT] public Q setBean ( final String beanName , final Object bean ) { if ( bean == null ) { return _this ( ) ; } init ( ) ; final String beanNamePrefix = beanName + ' ' ; query . forEachNamedParameter ( p -> { final String paramName = p . name ; if ( paramName . startsWith ( beanNamePrefix ) ) { final String propertyName = paramName . substring ( beanNamePrefix . length ( ) ) ; if ( BeanUtil . declared . hasRootProperty ( bean , propertyName ) ) { final Object value = BeanUtil . declared . getProperty ( bean , propertyName ) ; setObject ( paramName , value ) ; } } } ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets properties from the map . [CODESPLIT] public Q setMap ( final Map parameters ) { if ( parameters == null ) { return _this ( ) ; } init ( ) ; query . forEachNamedParameter ( p -> { final String paramName = p . name ; setObject ( paramName , parameters . get ( paramName ) ) ; } ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the designated parameter with the given object . This method is like the method <code > setObject< / code > above except that it assumes a scale of zero . [CODESPLIT] public Q setObject ( final int index , final Object object , final int targetSqlType ) { initPrepared ( ) ; try { preparedStatement . setObject ( index , object , targetSqlType ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the designated parameter with the given object . This method is like the method <code > setObject< / code > above except that it assumes a scale of zero . [CODESPLIT] public Q setObject ( final String param , final Object object , final int targetSqlType ) { initPrepared ( ) ; final int [ ] positions = query . getNamedParameterIndices ( param ) ; try { for ( final int position : positions ) { preparedStatement . setObject ( position , object , targetSqlType ) ; } } catch ( SQLException sex ) { throwSetParamError ( param , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the designated parameter with the given object . This method is like the method <code > setObject< / code > above except that it assumes a scale of zero . [CODESPLIT] void setObject ( final int index , final Object object , final int targetSqlType , final int scale ) { initPrepared ( ) ; try { preparedStatement . setObject ( index , object , targetSqlType , scale ) ; } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets object parameter in an advanced way . <p > First it checks if object is <code > null< / code > and invokes <code > setNull< / code > if so . If object is not <code > null< / code > it tries to resolve { [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) public Q setObject ( final int index , final Object value , final Class < ? extends SqlType > sqlTypeClass , final int dbSqlType ) { init ( ) ; if ( value == null ) { setNull ( index , Types . NULL ) ; return _this ( ) ; } final SqlType sqlType ; if ( sqlTypeClass != null ) { sqlType = SqlTypeManager . get ( ) . lookupSqlType ( sqlTypeClass ) ; } else { sqlType = SqlTypeManager . get ( ) . lookup ( value . getClass ( ) ) ; } try { if ( ( sqlType != null ) && ( dbSqlType != SqlType . DB_SQLTYPE_NOT_AVAILABLE ) ) { sqlType . storeValue ( preparedStatement , index , value , dbSqlType ) ; } else { DbUtil . setPreparedStatementObject ( preparedStatement , index , value , dbSqlType ) ; } } catch ( SQLException sex ) { throwSetParamError ( index , sex ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets an array of objects parameters in given order . [CODESPLIT] public Q setObjects ( final Object ... objects ) { int index = 1 ; for ( final Object object : objects ) { setObject ( index ++ , object ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets sql parameters from two arrays : names and values . [CODESPLIT] public Q setObjects ( final String [ ] names , final Object [ ] values ) { init ( ) ; if ( names . length != values . length ) { throw new DbSqlException ( this , \"Different number of parameter names and values\" ) ; } for ( int i = 0 ; i < names . length ; i ++ ) { setObject ( names [ i ] , values [ i ] ) ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets batch parameters with given array of values . [CODESPLIT] public Q setBatch ( final String name , final int [ ] array , int startingIndex ) { init ( ) ; final int batchSize = query . getBatchParameterSize ( name ) ; for ( int i = 1 ; i <= batchSize ; i ++ ) { final String paramName = name + ' ' + i ; if ( startingIndex < array . length ) { setInteger ( paramName , array [ startingIndex ] ) ; } else { setNull ( paramName , Types . INTEGER ) ; } startingIndex ++ ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets batch parameters with given array of values . [CODESPLIT] public Q setBatch ( final String name , final Object [ ] array , int startingIndex ) { init ( ) ; final int batchSize = query . getBatchParameterSize ( name ) ; for ( int i = 1 ; i <= batchSize ; i ++ ) { final String paramName = name + ' ' + i ; if ( startingIndex < array . length ) { setObject ( paramName , array [ startingIndex ] ) ; } else { setObject ( paramName , null ) ; } startingIndex ++ ; } return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends chunk to previous one and maintains the double - linked list of the previous chunk . Current surrounding connections of this chunk will be cut - off . [CODESPLIT] public void insertChunkAfter ( final SqlChunk previous ) { SqlChunk next = previous . nextChunk ; previous . nextChunk = this ; this . previousChunk = previous ; if ( next != null ) { next . previousChunk = this ; this . nextChunk = next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for entity name and throws exception if entity name not found . [CODESPLIT] protected DbEntityDescriptor lookupName ( final String entityName ) { DbEntityDescriptor ded = dbEntityManager . lookupName ( entityName ) ; if ( ded == null ) { throw new DbSqlBuilderException ( \"Entity name not registered: \" + entityName ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for entity name and throws an exception if entity type is invalid . [CODESPLIT] protected DbEntityDescriptor lookupType ( final Class entity ) { final DbEntityDescriptor ded = dbEntityManager . lookupType ( entity ) ; if ( ded == null ) { throw new DbSqlBuilderException ( \"Invalid or not-persistent entity: \" + entity . getName ( ) ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a table that contains given column . [CODESPLIT] protected DbEntityDescriptor findColumnRef ( final String columnRef ) { DbEntityDescriptor ded = templateData . findTableDescriptorByColumnRef ( columnRef ) ; if ( ded == null ) { throw new DbSqlBuilderException ( \"Invalid column reference: [\" + columnRef + \"]\" ) ; } return ded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves table name or alias that will be used in the query . [CODESPLIT] protected String resolveTable ( final String tableRef , final DbEntityDescriptor ded ) { String tableAlias = templateData . getTableAlias ( tableRef ) ; if ( tableAlias != null ) { return tableAlias ; } return ded . getTableNameForQuery ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines parameter with name and its value . [CODESPLIT] protected void defineParameter ( final StringBuilder query , String name , final Object value , final DbEntityColumnDescriptor dec ) { if ( name == null ) { name = templateData . getNextParameterName ( ) ; } query . append ( ' ' ) . append ( name ) ; templateData . addParameter ( name , value , dec ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves object to a class . [CODESPLIT] protected static Class resolveClass ( final Object object ) { Class type = object . getClass ( ) ; return type == Class . class ? ( Class ) object : type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if a value is considered empty i . e . not existing . [CODESPLIT] protected boolean isEmptyColumnValue ( final DbEntityColumnDescriptor dec , final Object value ) { if ( value == null ) { return true ; } // special case for ID column if ( dec . isId ( ) && value instanceof Number ) { final double d = ( ( Number ) value ) . doubleValue ( ) ; if ( d == 0.0d ) { return true ; } } // special case for primitives if ( dec . getPropertyType ( ) . isPrimitive ( ) ) { if ( char . class == dec . getPropertyType ( ) ) { final Character c = ( ( Character ) value ) ; if ( ' ' == c . charValue ( ) ) { return true ; } } else { final double d = ( ( Number ) value ) . doubleValue ( ) ; if ( d == 0 ) { return true ; } } } // special case for strings if ( value instanceof CharSequence ) { if ( StringUtil . isBlank ( ( CharSequence ) value ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends missing space if the output doesn t end with whitespace . [CODESPLIT] protected void appendMissingSpace ( final StringBuilder out ) { int len = out . length ( ) ; if ( len == 0 ) { return ; } len -- ; if ( ! CharUtil . isWhitespace ( out . charAt ( len ) ) ) { out . append ( ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- valid [CODESPLIT] public boolean isValid ( final ValidationConstraintContext vcc , final Object value ) { return validate ( vcc . getTarget ( ) , value , fieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- get / free [CODESPLIT] @ Override public Connection getConnection ( ) { PooledConnection pconn ; try { pconn = cpds . getPooledConnection ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"Invalid pooled connection\" , sex ) ; } try { return pconn . getConnection ( ) ; } catch ( SQLException sex ) { throw new DbSqlException ( \"Invalid pooled connection\" , sex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an enumeration of the parameter names for uploaded files [CODESPLIT] public Enumeration < String > getFileParameterNames ( ) { if ( mreq == null ) { return null ; } return Collections . enumeration ( mreq . getFileParameterNames ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a { @link FileUpload } array for the given input field name . [CODESPLIT] public FileUpload [ ] getFiles ( final String fieldName ) { if ( mreq == null ) { return null ; } return mreq . getFiles ( fieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares value of two same instances . [CODESPLIT] @ Override public int compareTo ( final MutableLong other ) { return value < other . value ? - 1 : ( value == other . value ? 0 : 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include page which path is relative to the current HTTP request . [CODESPLIT] public static boolean include ( final ServletRequest request , final ServletResponse response , final String page ) throws IOException , ServletException { RequestDispatcher dispatcher = request . getRequestDispatcher ( page ) ; if ( dispatcher != null ) { dispatcher . include ( request , response ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include named resource . [CODESPLIT] public static boolean includeNamed ( final HttpServletRequest request , final ServletResponse response , final String resource ) throws IOException , ServletException { return includeNamed ( request . getServletContext ( ) , request , response , resource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include named resource . [CODESPLIT] public static boolean includeNamed ( final ServletContext context , final ServletRequest request , final ServletResponse response , final String page ) throws IOException , ServletException { RequestDispatcher dispatcher = context . getNamedDispatcher ( page ) ; if ( dispatcher != null ) { dispatcher . include ( request , response ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include page which path relative to the root of the ServletContext . [CODESPLIT] public static boolean includeAbsolute ( final HttpServletRequest request , final HttpServletResponse response , final String page ) throws IOException , ServletException { return includeAbsolute ( request . getServletContext ( ) , request , response , page ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include page which path relative to the root of the ServletContext . [CODESPLIT] public static boolean includeAbsolute ( final ServletContext context , final ServletRequest request , final HttpServletResponse response , final String page ) throws IOException , ServletException { RequestDispatcher dispatcher = context . getRequestDispatcher ( page ) ; if ( dispatcher != null ) { dispatcher . include ( request , response ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forward to page path relative to the root of the ServletContext . [CODESPLIT] public static boolean forwardAbsolute ( final HttpServletRequest request , final ServletResponse response , final String page ) throws IOException , ServletException { return forwardAbsolute ( request . getServletContext ( ) , request , response , page ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forward to page path relative to the root of the ServletContext . [CODESPLIT] public static boolean forwardAbsolute ( final ServletContext context , final ServletRequest request , final ServletResponse response , final String resource ) throws IOException , ServletException { RequestDispatcher dispatcher = context . getRequestDispatcher ( resource ) ; if ( dispatcher != null ) { dispatcher . forward ( request , response ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs redirection ( 302 ) to specified url . [CODESPLIT] public static void redirect ( final HttpServletRequest request , final HttpServletResponse response , String url ) throws IOException { if ( url . startsWith ( StringPool . SLASH ) ) { url = ServletUtil . getContextPath ( request ) + url ; } response . sendRedirect ( response . encodeRedirectURL ( url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs permanent redirection ( 301 ) to specified url . [CODESPLIT] public static void redirectPermanent ( final HttpServletRequest request , final HttpServletResponse response , String url ) { if ( url . startsWith ( StringPool . SLASH ) ) { url = ServletUtil . getContextPath ( request ) + url ; } response . setStatus ( HttpServletResponse . SC_MOVED_PERMANENTLY ) ; response . setHeader ( \"Location\" , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns full URL : uri + query string including the context path . [CODESPLIT] public static String getFullUrl ( final HttpServletRequest request ) { String url = request . getRequestURI ( ) ; String query = request . getQueryString ( ) ; if ( ( query != null ) && ( query . length ( ) != 0 ) ) { url += ' ' + query ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns url without context path convenient for request dispatcher . [CODESPLIT] public static String getUrl ( final HttpServletRequest request ) { String servletPath = request . getServletPath ( ) ; String query = request . getQueryString ( ) ; if ( ( query != null ) && ( query . length ( ) != 0 ) ) { servletPath += ' ' + query ; } return servletPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if current page is included . [CODESPLIT] public static boolean isPageIncluded ( final HttpServletRequest request , final HttpServletResponse response ) { return ( response . isCommitted ( ) || ( getIncludeServletPath ( request ) != null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the base ( top - level ) uri . [CODESPLIT] public static String getBaseRequestUri ( final HttpServletRequest request ) { String result = getForwardRequestUri ( request ) ; if ( result == null ) { result = request . getRequestURI ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get current request uri . [CODESPLIT] public static String getRequestUri ( final HttpServletRequest request ) { String result = getIncludeRequestUri ( request ) ; if ( result == null ) { result = request . getRequestURI ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns method parameter names . [CODESPLIT] public String [ ] resolveParamNames ( final Method actionClassMethod ) { MethodParameter [ ] methodParameters = Paramo . resolveParameters ( actionClassMethod ) ; String [ ] names = new String [ methodParameters . length ] ; for ( int i = 0 ; i < methodParameters . length ; i ++ ) { names [ i ] = methodParameters [ i ] . getName ( ) ; } return names ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds { [CODESPLIT] public PathMacros buildActionPathMacros ( final String actionPath ) { if ( actionPath . isEmpty ( ) ) { return null ; } PathMacros pathMacros = createPathMacroInstance ( ) ; if ( ! pathMacros . init ( actionPath , actionsManager . getPathMacroSeparators ( ) ) ) { return null ; } return pathMacros ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new <code > PathMacro< / code > instance . [CODESPLIT] private PathMacros createPathMacroInstance ( ) { try { return ClassUtil . newInstance ( actionsManager . getPathMacroClass ( ) ) ; } catch ( Exception ex ) { throw new MadvocException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and initializes Petite container . It will be auto - magically configured by scanning the classpath . [CODESPLIT] @ Override public void start ( ) { initLogger ( ) ; log . info ( \"PETITE start  ----------\" ) ; petiteContainer = createPetiteContainer ( ) ; if ( externalsCache ) { petiteContainer . setExternalsCache ( TypeCache . createDefault ( ) ) ; } log . info ( \"Web application? \" + isWebApplication ) ; if ( ! isWebApplication ) { // make session scope to act as singleton scope // if this is not a web application (and http session is not available). petiteContainer . registerScope ( SessionScope . class , new SingletonScope ( petiteContainer ) ) ; } // load parameters from properties files petiteContainer . defineParameters ( joyPropsSupplier . get ( ) . getProps ( ) ) ; // automagic configuration if ( autoConfiguration ) { final AutomagicPetiteConfigurator automagicPetiteConfigurator = new AutomagicPetiteConfigurator ( petiteContainer ) ; automagicPetiteConfigurator . registerAsConsumer ( joyScannerSupplier . get ( ) . getClassScanner ( ) ) ; } petiteContainerConsumers . accept ( this . petiteContainer ) ; log . info ( \"PETITE OK!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops Petite container . [CODESPLIT] @ Override public void stop ( ) { if ( log != null ) { log . info ( \"PETITE stop\" ) ; } if ( petiteContainer != null ) { petiteContainer . shutdown ( ) ; } petiteContainer = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- print [CODESPLIT] public void printBeans ( final int width ) { final Print print = new Print ( ) ; print . line ( \"Beans\" , width ) ; final List < BeanDefinition > beanDefinitionList = new ArrayList <> ( ) ; final String appName = appNameSupplier . get ( ) ; final String prefix = appName + \".\" ; petiteContainer . forEachBean ( beanDefinitionList :: add ) ; beanDefinitionList . stream ( ) . sorted ( ( bd1 , bd2 ) -> { if ( bd1 . name ( ) . startsWith ( prefix ) ) { if ( bd2 . name ( ) . startsWith ( prefix ) ) { return bd1 . name ( ) . compareTo ( bd2 . name ( ) ) ; } return 1 ; } if ( bd2 . name ( ) . startsWith ( prefix ) ) { if ( bd1 . name ( ) . startsWith ( prefix ) ) { return bd1 . name ( ) . compareTo ( bd2 . name ( ) ) ; } return - 1 ; } return bd1 . name ( ) . compareTo ( bd2 . name ( ) ) ; } ) . forEach ( beanDefinition -> { print . out ( Chalk256 . chalk ( ) . yellow ( ) , scopeName ( beanDefinition ) , 10 ) ; print . space ( ) ; print . outLeftRightNewLine ( Chalk256 . chalk ( ) . green ( ) , beanDefinition . name ( ) , Chalk256 . chalk ( ) . blue ( ) , ClassUtil . getShortClassName ( beanDefinition . type ( ) , 2 ) , width - 10 - 1 ) ; } ) ; print . line ( width ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets this CurrentFrame to the input stack map frame of the next current instruction i . e . the instruction just after the given one . It is assumed that the value of this object when this method is called is the stack map frame status just before the given instruction is executed . [CODESPLIT] @ Override void execute ( final int opcode , final int arg , final Symbol symbolArg , final SymbolTable symbolTable ) { super . execute ( opcode , arg , symbolArg , symbolTable ) ; Frame successor = new Frame ( null ) ; merge ( symbolTable , successor , 0 ) ; copyFrom ( successor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for SUBJECT field . [CODESPLIT] public EmailFilter subject ( final String subject ) { final SearchTerm subjectTerm = new SubjectTerm ( subject ) ; concat ( subjectTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for message id . [CODESPLIT] public EmailFilter messageId ( final String messageId ) { final SearchTerm msgIdTerm = new MessageIDTerm ( messageId ) ; concat ( msgIdTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for FROM field . [CODESPLIT] public EmailFilter from ( final String fromAddress ) { final SearchTerm fromTerm = new FromStringTerm ( fromAddress ) ; concat ( fromTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for TO field . [CODESPLIT] public EmailFilter to ( final String toAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . TO , toAddress ) ; concat ( toTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for CC field . [CODESPLIT] public EmailFilter cc ( final String ccAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . CC , ccAddress ) ; concat ( toTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for BCC field . [CODESPLIT] public EmailFilter bcc ( final String bccAddress ) { final SearchTerm toTerm = new RecipientStringTerm ( RecipientType . BCC , bccAddress ) ; concat ( toTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for many flags at once . [CODESPLIT] public EmailFilter flags ( final Flags flags , final boolean value ) { final SearchTerm flagTerm = new FlagTerm ( flags , value ) ; concat ( flagTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for single flag . [CODESPLIT] public EmailFilter flag ( final Flag flag , final boolean value ) { final Flags flags = new Flags ( ) ; flags . add ( flag ) ; return flags ( flags , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for received date . [CODESPLIT] public EmailFilter receivedDate ( final Operator operator , final long milliseconds ) { final SearchTerm term = new ReceivedDateTerm ( operator . value , new Date ( milliseconds ) ) ; concat ( term ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for sent date . [CODESPLIT] public EmailFilter sentDate ( final Operator operator , final long milliseconds ) { final SearchTerm term = new SentDateTerm ( operator . value , new Date ( milliseconds ) ) ; concat ( term ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter on a message body . All parts of the message that are of MIME type text / * are searched . [CODESPLIT] public EmailFilter text ( final String pattern ) { final SearchTerm term = new BodyTerm ( pattern ) ; concat ( term ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for { @link Header } . [CODESPLIT] public EmailFilter header ( final String headerName , final String pattern ) { final SearchTerm term = new HeaderTerm ( headerName , pattern ) ; concat ( term ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines filter for message size . [CODESPLIT] public EmailFilter size ( final Operator comparison , final int size ) { final SearchTerm term = new SizeTerm ( comparison . value , size ) ; concat ( term ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines AND group of filters . [CODESPLIT] public EmailFilter and ( final EmailFilter ... emailFilters ) { final SearchTerm [ ] searchTerms = new SearchTerm [ emailFilters . length ] ; for ( int i = 0 ; i < emailFilters . length ; i ++ ) { searchTerms [ i ] = emailFilters [ i ] . searchTerm ; } concat ( new AndTerm ( searchTerms ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines OR group of filters . [CODESPLIT] public EmailFilter or ( final EmailFilter ... emailFilters ) { final SearchTerm [ ] searchTerms = new SearchTerm [ emailFilters . length ] ; for ( int i = 0 ; i < emailFilters . length ; i ++ ) { searchTerms [ i ] = emailFilters [ i ] . searchTerm ; } concat ( new OrTerm ( searchTerms ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends single filter as NOT . [CODESPLIT] public EmailFilter not ( final EmailFilter emailFilter ) { final SearchTerm searchTerm = new NotTerm ( emailFilter . searchTerm ) ; concat ( searchTerm ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates last search term with new one . [CODESPLIT] protected void concat ( SearchTerm searchTerm ) { if ( nextIsNot ) { searchTerm = new NotTerm ( searchTerm ) ; nextIsNot = false ; } if ( operatorAnd ) { and ( searchTerm ) ; } else { or ( searchTerm ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets { @link AndTerm } as searchTerm . [CODESPLIT] protected void and ( final SearchTerm searchTerm ) { if ( this . searchTerm == null ) { this . searchTerm = searchTerm ; return ; } this . searchTerm = new AndTerm ( this . searchTerm , searchTerm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets { @link OrTerm } searchTerm . [CODESPLIT] protected void or ( final SearchTerm searchTerm ) { if ( this . searchTerm == null ) { this . searchTerm = searchTerm ; return ; } this . searchTerm = new OrTerm ( this . searchTerm , searchTerm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode an array of binary bytes into a Base32 string . [CODESPLIT] public static String encode ( final byte [ ] bytes ) { StringBuilder base32 = new StringBuilder ( ( bytes . length * 8 + 4 ) / 5 ) ; int currByte , digit , i = 0 ; while ( i < bytes . length ) { // STEP 0; insert new 5 bits, leave 3 bits currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ currByte >> 3 ] ) ; digit = ( currByte & 7 ) << 2 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 3: insert 2 new bits, then 5 bits, leave 1 bit currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 6 ) ] ) ; base32 . append ( CHARS [ ( currByte >> 1 ) & 31 ] ) ; digit = ( currByte & 1 ) << 4 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 1: insert 4 new bits, leave 4 bit currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 4 ) ] ) ; digit = ( currByte & 15 ) << 1 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 4: insert 1 new bit, then 5 bits, leave 2 bits currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 7 ) ] ) ; base32 . append ( CHARS [ ( currByte >> 2 ) & 31 ] ) ; digit = ( currByte & 3 ) << 3 ; if ( i >= bytes . length ) { base32 . append ( CHARS [ digit ] ) ; break ; } // STEP 2: insert 3 new bits, then 5 bits, leave 0 bit currByte = bytes [ i ++ ] & 255 ; base32 . append ( CHARS [ digit | ( currByte >> 5 ) ] ) ; base32 . append ( CHARS [ currByte & 31 ] ) ; } return base32 . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode a Base32 string into an array of binary bytes . [CODESPLIT] public static byte [ ] decode ( final String base32 ) throws IllegalArgumentException { switch ( base32 . length ( ) % 8 ) { case 1 : case 3 : case 6 : throw new IllegalArgumentException ( ERR_CANONICAL_LEN ) ; } byte [ ] bytes = new byte [ base32 . length ( ) * 5 / 8 ] ; int offset = 0 , i = 0 , lookup ; byte nextByte , digit ; while ( i < base32 . length ( ) ) { lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 0: leave 5 bits nextByte = ( byte ) ( digit << 3 ) ; lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 5: insert 3 bits, leave 2 bits bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 2 ) ) ; nextByte = ( byte ) ( ( digit & 3 ) << 6 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 2: leave 7 bits nextByte |= ( byte ) ( digit << 1 ) ; lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 7: insert 1 bit, leave 4 bits bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 4 ) ) ; nextByte = ( byte ) ( ( digit & 15 ) << 4 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 4: insert 4 bits, leave 1 bit bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 1 ) ) ; nextByte = ( byte ) ( ( digit & 1 ) << 7 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 1: leave 6 bits nextByte |= ( byte ) ( digit << 2 ) ; lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 6: insert 2 bits, leave 3 bits bytes [ offset ++ ] = ( byte ) ( nextByte | ( digit >> 3 ) ) ; nextByte = ( byte ) ( ( digit & 7 ) << 5 ) ; if ( i >= base32 . length ( ) ) { if ( nextByte != ( byte ) 0 ) { throw new IllegalArgumentException ( ERR_CANONICAL_END ) ; } break ; } lookup = base32 . charAt ( i ++ ) - ' ' ; if ( lookup < 0 || lookup >= LOOKUP . length ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } digit = LOOKUP [ lookup ] ; if ( digit == - 1 ) { throw new IllegalArgumentException ( ERR_INVALID_CHARS ) ; } // STEP n = 3: insert 5 bits, leave 0 bit bytes [ offset ++ ] = ( byte ) ( nextByte | digit ) ; } return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts non - array value to array . Detects various types and collections iterates them to make conversion and to create target array . [CODESPLIT] protected byte [ ] convertValueToArray ( final Object value ) { if ( value instanceof Blob ) { final Blob blob = ( Blob ) value ; try { final long length = blob . length ( ) ; if ( length > Integer . MAX_VALUE ) { throw new TypeConversionException ( \"Blob is too big.\" ) ; } return blob . getBytes ( 1 , ( int ) length ) ; } catch ( SQLException sex ) { throw new TypeConversionException ( value , sex ) ; } } if ( value instanceof File ) { try { return FileUtil . readBytes ( ( File ) value ) ; } catch ( IOException ioex ) { throw new TypeConversionException ( value , ioex ) ; } } if ( value instanceof Collection ) { final Collection collection = ( Collection ) value ; final byte [ ] target = new byte [ collection . size ( ) ] ; int i = 0 ; for ( final Object element : collection ) { target [ i ] = convertType ( element ) ; i ++ ; } return target ; } if ( value instanceof Iterable ) { final Iterable iterable = ( Iterable ) value ; final ArrayList < Byte > byteArrayList = new ArrayList <> ( ) ; for ( final Object element : iterable ) { final byte convertedValue = convertType ( element ) ; byteArrayList . add ( Byte . valueOf ( convertedValue ) ) ; } final byte [ ] array = new byte [ byteArrayList . size ( ) ] ; for ( int i = 0 ; i < byteArrayList . size ( ) ; i ++ ) { final Byte b = byteArrayList . get ( i ) ; array [ i ] = b . byteValue ( ) ; } return array ; } if ( value instanceof CharSequence ) { final String [ ] strings = StringUtil . splitc ( value . toString ( ) , ArrayConverter . NUMBER_DELIMITERS ) ; return convertArrayToArray ( strings ) ; } // everything else: return convertToSingleElementArray ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If browser supports gzip sets the Content - Encoding response header and invoke resource with a wrapped response that collects all the output . Extracts the output and write it into a gzipped byte array . Finally write that array to the client s output stream . <p > If browser does not support gzip invokes resource normally . [CODESPLIT] @ Override public void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws ServletException , IOException { HttpServletRequest req = ( HttpServletRequest ) request ; HttpServletResponse res = ( HttpServletResponse ) response ; if ( ( threshold == 0 ) || ( ! ServletUtil . isGzipSupported ( req ) ) || ( ! isGzipEligible ( req ) ) ) { chain . doFilter ( request , response ) ; return ; } GzipResponseWrapper wrappedResponse = new GzipResponseWrapper ( res ) ; wrappedResponse . setCompressionThreshold ( threshold ) ; try { chain . doFilter ( request , wrappedResponse ) ; } finally { wrappedResponse . finishResponse ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter initialization . [CODESPLIT] @ Override public void init ( final FilterConfig config ) { try { wildcards = Converter . get ( ) . toBooleanValue ( config . getInitParameter ( \"wildcards\" ) , false ) ; } catch ( TypeConversionException ignore ) { wildcards = false ; } // min size try { threshold = Converter . get ( ) . toIntValue ( config . getInitParameter ( \"threshold\" ) , 0 ) ; } catch ( TypeConversionException ignore ) { threshold = 0 ; } // match string String uriMatch = config . getInitParameter ( \"match\" ) ; if ( ( uriMatch != null ) && ( ! uriMatch . equals ( StringPool . STAR ) ) ) { matches = StringUtil . splitc ( uriMatch , ' ' ) ; for ( int i = 0 ; i < matches . length ; i ++ ) { matches [ i ] = matches [ i ] . trim ( ) ; } } // exclude string String uriExclude = config . getInitParameter ( \"exclude\" ) ; if ( uriExclude != null ) { excludes = StringUtil . splitc ( uriExclude , ' ' ) ; for ( int i = 0 ; i < excludes . length ; i ++ ) { excludes [ i ] = excludes [ i ] . trim ( ) ; } } // request parameter name requestParameterName = config . getInitParameter ( \"requestParameterName\" ) ; if ( requestParameterName == null ) { requestParameterName = \"gzip\" ; } requestParameterName = requestParameterName . trim ( ) ; // allowed extensions String urlExtensions = config . getInitParameter ( \"extensions\" ) ; if ( urlExtensions != null ) { if ( urlExtensions . equals ( StringPool . STAR ) ) { extensions = null ; } else { extensions = StringUtil . splitc ( urlExtensions , \", \" ) ; } } else { extensions = new String [ ] { \"html\" , \"htm\" , \"js\" , \"css\" } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if request is eligible for GZipping . [CODESPLIT] protected boolean isGzipEligible ( final HttpServletRequest request ) { // request parameter name if ( requestParameterName . length ( ) != 0 ) { String forceGzipString = request . getParameter ( requestParameterName ) ; if ( forceGzipString != null ) { return Converter . get ( ) . toBooleanValue ( forceGzipString , false ) ; } } // extract uri String uri = request . getRequestURI ( ) ; if ( uri == null ) { return false ; } uri = uri . toLowerCase ( ) ; boolean result = false ; // check uri if ( matches == null ) { // match == * if ( extensions == null ) { // extensions == * return true ; } // extension String extension = FileNameUtil . getExtension ( uri ) ; if ( extension . length ( ) > 0 ) { extension = extension . toLowerCase ( ) ; if ( StringUtil . equalsOne ( extension , extensions ) != - 1 ) { result = true ; } } } else { if ( wildcards ) { result = Wildcard . matchPathOne ( uri , matches ) != - 1 ; } else { for ( String match : matches ) { if ( uri . contains ( match ) ) { result = true ; break ; } } } } if ( ( result ) && ( excludes != null ) ) { if ( wildcards ) { if ( Wildcard . matchPathOne ( uri , excludes ) != - 1 ) { result = false ; } } else { for ( String exclude : excludes ) { if ( uri . contains ( exclude ) ) { result = false ; // excludes founded break ; } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds new { [CODESPLIT] public void addViolation ( final Violation v ) { if ( v == null ) { return ; } if ( violations == null ) { violations = new ArrayList <> ( ) ; } violations . add ( v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate object using context from the annotations . [CODESPLIT] public List < Violation > validate ( final Object target ) { return validate ( ValidationContext . resolveFor ( target . getClass ( ) ) , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs validation of provided validation context and appends violations . [CODESPLIT] public List < Violation > validate ( final ValidationContext ctx , final Object target , final String targetName ) { for ( Map . Entry < String , List < Check > > entry : ctx . map . entrySet ( ) ) { String name = entry . getKey ( ) ; Object value = BeanUtil . declaredSilent . getProperty ( target , name ) ; String valueName = targetName != null ? ( targetName + ' ' + name ) : name ; // move up ValidationConstraintContext vcc = new ValidationConstraintContext ( this , target , valueName ) ; for ( Check check : entry . getValue ( ) ) { String [ ] checkProfiles = check . getProfiles ( ) ; if ( ! matchProfiles ( checkProfiles ) ) { continue ; } if ( check . getSeverity ( ) < severity ) { continue ; } ValidationConstraint constraint = check . getConstraint ( ) ; if ( ! constraint . isValid ( vcc , value ) ) { addViolation ( new Violation ( valueName , target , value , check ) ) ; } } } return getViolations ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables single profile . [CODESPLIT] public void useProfile ( final String profile ) { if ( profile == null ) { return ; } if ( this . enabledProfiles == null ) { this . enabledProfiles = new HashSet <> ( ) ; } this . enabledProfiles . add ( profile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables list of profiles . [CODESPLIT] public void useProfiles ( final String ... enabledProfiles ) { if ( enabledProfiles == null ) { return ; } if ( this . enabledProfiles == null ) { this . enabledProfiles = new HashSet <> ( ) ; } Collections . addAll ( this . enabledProfiles , enabledProfiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if any of checks profiles is among enabled profiles . [CODESPLIT] protected boolean matchProfiles ( final String [ ] checkProfiles ) { // test for all profiles if ( ( checkProfiles != null ) && ( checkProfiles . length == 1 ) && checkProfiles [ 0 ] . equals ( ALL_PROFILES ) ) { return true ; } if ( enabledProfiles == null || enabledProfiles . isEmpty ( ) ) { if ( validateAllProfilesByDefault ) { return true ; // all profiles are considered as enabled } // only default profile is enabled if ( ( checkProfiles == null ) || ( checkProfiles . length == 0 ) ) { return true ; } for ( String profile : checkProfiles ) { if ( StringUtil . isEmpty ( profile ) ) { return true ; // default profile } if ( profile . equals ( DEFAULT_PROFILE ) ) { return true ; } } return false ; } // there are enabled profiles if ( ( checkProfiles == null ) || ( checkProfiles . length == 0 ) ) { return enabledProfiles . contains ( DEFAULT_PROFILE ) ; } boolean result = false ; for ( String profile : checkProfiles ) { boolean b = true ; boolean must = false ; if ( StringUtil . isEmpty ( profile ) ) { profile = DEFAULT_PROFILE ; } else if ( profile . charAt ( 0 ) == ' ' ) { profile = profile . substring ( 1 ) ; b = false ; } else if ( profile . charAt ( 0 ) == ' ' ) { profile = profile . substring ( 1 ) ; must = true ; } if ( enabledProfiles . contains ( profile ) ) { if ( ! b ) { return false ; } result = true ; } else { if ( must ) { return false ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses request body into the target type . [CODESPLIT] protected Object parseRequestBody ( final String body , final Class targetType ) { return JsonParser . create ( ) . parse ( body , targetType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to milliseconds . [CODESPLIT] public long toMilliseconds ( ) { double then = ( fraction - JD_1970 . fraction ) * MILLIS_IN_DAY ; then += ( integer - JD_1970 . integer ) * MILLIS_IN_DAY ; then += then > 0 ? 1.0e-6 : - 1.0e-6 ; return ( long ) then ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a JD to current instance . [CODESPLIT] public JulianDate add ( final JulianDate jds ) { int i = this . integer + jds . integer ; double f = this . fraction + jds . fraction ; return new JulianDate ( i , f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtracts a JD from current instance . [CODESPLIT] public JulianDate sub ( final JulianDate jds ) { int i = this . integer - jds . integer ; double f = this . fraction - jds . fraction ; return new JulianDate ( i , f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets integer and fractional part with normalization . Normalization means that if double is out of range values will be correctly fixed . [CODESPLIT] private void set ( final int i , double f ) { integer = i ; int fi = ( int ) f ; f -= fi ; integer += fi ; if ( f < 0 ) { f += 1 ; integer -- ; } this . fraction = f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns span between two days . Returned value may be positive ( when this date is after the provided one ) or negative ( when comparing to future date ) . [CODESPLIT] public int daysSpan ( final JulianDate otherDate ) { int now = getJulianDayNumber ( ) ; int then = otherDate . getJulianDayNumber ( ) ; return now - then ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- fg codes [CODESPLIT] public Chalk256 standard ( final int index ) { startSequence ( FG_CODES [ index ( index , 0 , 8 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Colors with red - green - blue value in the range 0 to 6 . [CODESPLIT] public Chalk256 rgb ( final int r , final int b , final int g ) { startSequence ( FG_CODES [ index ( 36 * r + 6 * g + b , 16 , 232 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- bg codes [CODESPLIT] public Chalk256 bgStandard ( final int index ) { startSequence ( BG_CODES [ index ( index , 0 , 8 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Colors with red - green - blue value in the range 0 to 6 . [CODESPLIT] public Chalk256 bgRgb ( final int r , final int b , final int g ) { startSequence ( BG_CODES [ index ( 36 * r + 6 * g + b , 16 , 232 ) ] ) ; endSequence ( RESET ) ; return _this ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- bgcolors [CODESPLIT] private int index ( int index , final int from , final int to ) { index += from ; if ( ( index < from ) || ( index >= to ) ) { throw new IllegalArgumentException ( \"Color index not in range: [0, \" + ( to - from ) + \"]\" ) ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes parser . [CODESPLIT] @ Override protected void initialize ( final char [ ] input ) { super . initialize ( input ) ; this . tag = new ParsedTag ( ) ; this . doctype = new ParsedDoctype ( ) ; this . text = new char [ 1024 ] ; this . textLen = 0 ; this . parsingTime = - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses content and callback provided { [CODESPLIT] public void parse ( final TagVisitor visitor ) { tag . init ( config . caseSensitive ) ; this . parsingTime = System . currentTimeMillis ( ) ; this . visitor = visitor ; visitor . start ( ) ; parsing = true ; while ( parsing ) { state . parse ( ) ; } emitText ( ) ; visitor . end ( ) ; this . parsingTime = System . currentTimeMillis ( ) - parsingTime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emits a comment . Also checks for conditional comments! [CODESPLIT] protected void emitComment ( final int from , final int to ) { if ( config . enableConditionalComments ) { // CC: downlevel-hidden starting if ( match ( CC_IF , from ) ) { int endBracketNdx = find ( ' ' , from + 3 , to ) ; CharSequence expression = charSequence ( from + 1 , endBracketNdx ) ; ndx = endBracketNdx + 1 ; char c = input [ ndx ] ; if ( c != ' ' ) { errorInvalidToken ( ) ; } visitor . condComment ( expression , true , true , false ) ; state = DATA_STATE ; return ; } if ( to > CC_ENDIF2 . length && match ( CC_ENDIF2 , to - CC_ENDIF2 . length ) ) { // CC: downlevel-hidden ending visitor . condComment ( _ENDIF , false , true , true ) ; state = DATA_STATE ; return ; } } CharSequence comment = charSequence ( from , to ) ; visitor . comment ( comment ) ; commentStart = - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares error message and reports it to the visitor . [CODESPLIT] protected void _error ( String message ) { if ( config . calculatePosition ) { Position currentPosition = position ( ndx ) ; message = message . concat ( StringPool . SPACE ) . concat ( currentPosition . toString ( ) ) ; } else { message = message . concat ( \" [@\" ) . concat ( Integer . toString ( ndx ) ) . concat ( StringPool . RIGHT_SQ_BRACKET ) ; } visitor . error ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- util [CODESPLIT] private boolean isAppropriateTagName ( final char [ ] lowerCaseNameToMatch , final int from , final int to ) { final int len = to - from ; if ( len != lowerCaseNameToMatch . length ) { return false ; } for ( int i = from , k = 0 ; i < to ; i ++ , k ++ ) { char c = input [ i ] ; c = CharUtil . toLowerAscii ( c ) ; if ( c != lowerCaseNameToMatch [ k ] ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a salted PBKDF2 hash of the password . [CODESPLIT] public String createHash ( final char [ ] password ) { // Generate a random salt SecureRandom random = new SecureRandom ( ) ; byte [ ] salt = new byte [ saltBytes ] ; random . nextBytes ( salt ) ; // Hash the password byte [ ] hash = pbkdf2 ( password , salt , pbkdf2Iterations , hashBytes ) ; // format iterations:salt:hash return pbkdf2Iterations + \":\" + StringUtil . toHexString ( salt ) + \":\" + StringUtil . toHexString ( hash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the PBKDF2 hash of a password . [CODESPLIT] private static byte [ ] pbkdf2 ( final char [ ] password , final byte [ ] salt , final int iterations , final int bytes ) { PBEKeySpec spec = new PBEKeySpec ( password , salt , iterations , bytes * 8 ) ; try { SecretKeyFactory skf = SecretKeyFactory . getInstance ( PBKDF2_ALGORITHM ) ; return skf . generateSecret ( spec ) . getEncoded ( ) ; } catch ( NoSuchAlgorithmException ignore ) { return null ; } catch ( InvalidKeySpecException e ) { throw new IllegalArgumentException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a string of hexadecimal characters into a byte array . [CODESPLIT] private static byte [ ] fromHex ( final String hex ) { final byte [ ] binary = new byte [ hex . length ( ) / 2 ] ; for ( int i = 0 ; i < binary . length ; i ++ ) { binary [ i ] = ( byte ) Integer . parseInt ( hex . substring ( 2 * i , 2 * i + 2 ) , 16 ) ; } return binary ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves provider definition defined in a bean . [CODESPLIT] public ProviderDefinition [ ] resolveProviderDefinitions ( final Class type , final String name ) { return providerResolver . resolve ( type , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets file name . [CODESPLIT] public EmailAttachmentBuilder name ( final String name ) { if ( name != null && ! name . trim ( ) . isEmpty ( ) ) { this . name = name ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link DataSource } . Common { @link DataSource } s include { @link ByteArrayDataSource } and { @link FileDataSource } . [CODESPLIT] public < T extends DataSource > EmailAttachmentBuilder content ( final T dataSource ) { this . dataSource = dataSource ; name ( dataSource . getName ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { @link ByteArrayDataSource } and then calls { @link #content ( DataSource ) } . [CODESPLIT] public EmailAttachmentBuilder content ( final InputStream inputStream , final String contentType ) throws IOException { return content ( new ByteArrayDataSource ( inputStream , resolveContentType ( contentType ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new { @link ByteArrayDataSource } and then calls { @link #content ( DataSource ) } . [CODESPLIT] public EmailAttachmentBuilder content ( final byte [ ] bytes , final String contentType ) { return content ( new ByteArrayDataSource ( bytes , resolveContentType ( contentType ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link EmailAttachment } . [CODESPLIT] public EmailAttachment < ByteArrayDataSource > buildByteArrayDataSource ( ) throws MailException { try { final ByteArrayDataSource bads ; if ( dataSource instanceof ByteArrayDataSource ) { bads = ( ByteArrayDataSource ) dataSource ; } else { bads = new ByteArrayDataSource ( dataSource . getInputStream ( ) , dataSource . getContentType ( ) ) ; } checkDataSource ( ) ; return new EmailAttachment <> ( name , contentId , isInline , bads ) . setEmbeddedMessage ( targetMessage ) ; } catch ( final IOException ioexc ) { throw new MailException ( ioexc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link EmailAttachment } . [CODESPLIT] public EmailAttachment < FileDataSource > buildFileDataSource ( final String messageId , final File attachmentStorage ) throws MailException { try { final FileDataSource fds ; if ( dataSource instanceof FileDataSource ) { fds = ( FileDataSource ) dataSource ; } else { final File file = new File ( attachmentStorage , messageId ) ; FileUtil . writeStream ( file , dataSource . getInputStream ( ) ) ; fds = new FileDataSource ( file ) ; } checkDataSource ( ) ; return new EmailAttachment <> ( name , contentId , isInline , fds ) . setEmbeddedMessage ( targetMessage ) ; } catch ( final IOException ioexc ) { throw new MailException ( ioexc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set content ID if it is missing . [CODESPLIT] protected EmailAttachmentBuilder setContentIdFromNameIfMissing ( ) { if ( contentId == null ) { if ( name != null ) { contentId ( FileNameUtil . getName ( name ) ) ; } else { contentId ( NO_NAME ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves content type from all data . [CODESPLIT] protected String resolveContentType ( final String contentType ) { if ( contentType != null ) { return contentType ; } if ( name == null ) { return MimeTypes . MIME_APPLICATION_OCTET_STREAM ; } final String extension = FileNameUtil . getExtension ( name ) ; return MimeTypes . getMimeType ( extension ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes the given visitor visit the signature of this { @link SignatureReader } . This signature is the one specified in the constructor ( see { @link #SignatureReader } ) . This method is intended to be called on a { @link SignatureReader } that was created using a <i > ClassSignature< / i > ( such as the <code > signature< / code > parameter of the { @link org . objectweb . asm . ClassVisitor#visit } method ) or a <i > MethodSignature< / i > ( such as the <code > signature< / code > parameter of the { @link org . objectweb . asm . ClassVisitor#visitMethod } method ) . [CODESPLIT] public void accept ( final SignatureVisitor signatureVistor ) { String signature = this . signatureValue ; int length = signature . length ( ) ; int offset ; // Current offset in the parsed signature (parsed from left to right). char currentChar ; // The signature character at 'offset', or just before. // If the signature starts with '<', it starts with TypeParameters, i.e. a formal type parameter // identifier, followed by one or more pair ':',ReferenceTypeSignature (for its class bound and // interface bounds). if ( signature . charAt ( 0 ) == ' ' ) { // Invariant: offset points to the second character of a formal type parameter name at the // beginning of each iteration of the loop below. offset = 2 ; do { // The formal type parameter name is everything between offset - 1 and the first ':'. int classBoundStartOffset = signature . indexOf ( ' ' , offset ) ; signatureVistor . visitFormalTypeParameter ( signature . substring ( offset - 1 , classBoundStartOffset ) ) ; // If the character after the ':' class bound marker is not the start of a // ReferenceTypeSignature, it means the class bound is empty (which is a valid case). offset = classBoundStartOffset + 1 ; currentChar = signature . charAt ( offset ) ; if ( currentChar == ' ' || currentChar == ' ' || currentChar == ' ' ) { offset = parseType ( signature , offset , signatureVistor . visitClassBound ( ) ) ; } // While the character after the class bound or after the last parsed interface bound // is ':', we need to parse another interface bound. while ( ( currentChar = signature . charAt ( offset ++ ) ) == ' ' ) { offset = parseType ( signature , offset , signatureVistor . visitInterfaceBound ( ) ) ; } // At this point a TypeParameter has been fully parsed, and we need to parse the next one // (note that currentChar is now the first character of the next TypeParameter, and that // offset points to the second character), unless the character just after this // TypeParameter signals the end of the TypeParameters. } while ( currentChar != ' ' ) ; } else { offset = 0 ; } // If the (optional) TypeParameters is followed by '(' this means we are parsing a // MethodSignature, which has JavaTypeSignature type inside parentheses, followed by a Result // type and optional ThrowsSignature types. if ( signature . charAt ( offset ) == ' ' ) { offset ++ ; while ( signature . charAt ( offset ) != ' ' ) { offset = parseType ( signature , offset , signatureVistor . visitParameterType ( ) ) ; } // Use offset + 1 to skip ')'. offset = parseType ( signature , offset + 1 , signatureVistor . visitReturnType ( ) ) ; while ( offset < length ) { // Use offset + 1 to skip the first character of a ThrowsSignature, i.e. '^'. offset = parseType ( signature , offset + 1 , signatureVistor . visitExceptionType ( ) ) ; } } else { // Otherwise we are parsing a ClassSignature (by hypothesis on the method input), which has // one or more ClassTypeSignature for the super class and the implemented interfaces. offset = parseType ( signature , offset , signatureVistor . visitSuperclass ( ) ) ; while ( offset < length ) { offset = parseType ( signature , offset , signatureVistor . visitInterface ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a JavaTypeSignature and makes the given visitor visit it . [CODESPLIT] private static int parseType ( final String signature , final int startOffset , final SignatureVisitor signatureVisitor ) { int offset = startOffset ; // Current offset in the parsed signature. char currentChar = signature . charAt ( offset ++ ) ; // The signature character at 'offset'. // Switch based on the first character of the JavaTypeSignature, which indicates its kind. switch ( currentChar ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : // Case of a BaseType or a VoidDescriptor. signatureVisitor . visitBaseType ( currentChar ) ; return offset ; case ' ' : // Case of an ArrayTypeSignature, a '[' followed by a JavaTypeSignature. return parseType ( signature , offset , signatureVisitor . visitArrayType ( ) ) ; case ' ' : // Case of TypeVariableSignature, an identifier between 'T' and ';'. int endOffset = signature . indexOf ( ' ' , offset ) ; signatureVisitor . visitTypeVariable ( signature . substring ( offset , endOffset ) ) ; return endOffset + 1 ; case ' ' : // Case of a ClassTypeSignature, which ends with ';'. // These signatures have a main class type followed by zero or more inner class types // (separated by '.'). Each can have type arguments, inside '<' and '>'. int start = offset ; // The start offset of the currently parsed main or inner class name. boolean visited = false ; // Whether the currently parsed class name has been visited. boolean inner = false ; // Whether we are currently parsing an inner class type. // Parses the signature, one character at a time. while ( true ) { currentChar = signature . charAt ( offset ++ ) ; if ( currentChar == ' ' || currentChar == ' ' ) { // If a '.' or ';' is encountered, this means we have fully parsed the main class name // or an inner class name. This name may already have been visited it is was followed by // type arguments between '<' and '>'. If not, we need to visit it here. if ( ! visited ) { String name = signature . substring ( start , offset - 1 ) ; if ( inner ) { signatureVisitor . visitInnerClassType ( name ) ; } else { signatureVisitor . visitClassType ( name ) ; } } // If we reached the end of the ClassTypeSignature return, otherwise start the parsing // of a new class name, which is necessarily an inner class name. if ( currentChar == ' ' ) { signatureVisitor . visitEnd ( ) ; break ; } start = offset ; visited = false ; inner = true ; } else if ( currentChar == ' ' ) { // If a '<' is encountered, this means we have fully parsed the main class name or an // inner class name, and that we now need to parse TypeArguments. First, we need to // visit the parsed class name. String name = signature . substring ( start , offset - 1 ) ; if ( inner ) { signatureVisitor . visitInnerClassType ( name ) ; } else { signatureVisitor . visitClassType ( name ) ; } visited = true ; // Now, parse the TypeArgument(s), one at a time. while ( ( currentChar = signature . charAt ( offset ) ) != ' ' ) { switch ( currentChar ) { case ' ' : // Unbounded TypeArgument. ++ offset ; signatureVisitor . visitTypeArgument ( ) ; break ; case ' ' : case ' ' : // Extends or Super TypeArgument. Use offset + 1 to skip the '+' or '-'. offset = parseType ( signature , offset + 1 , signatureVisitor . visitTypeArgument ( currentChar ) ) ; break ; default : // Instanceof TypeArgument. The '=' is implicit. offset = parseType ( signature , offset , signatureVisitor . visitTypeArgument ( ' ' ) ) ; break ; } } } } return offset ; default : throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of the Module ModulePackages and ModuleMainClass attributes generated by this ModuleWriter . Also add the names of these attributes in the constant pool . [CODESPLIT] int computeAttributesSize ( ) { symbolTable . addConstantUtf8 ( Constants . MODULE ) ; // 6 attribute header bytes, 6 bytes for name, flags and version, and 5 * 2 bytes for counts. int size = 22 + requires . length + exports . length + opens . length + usesIndex . length + provides . length ; if ( packageCount > 0 ) { symbolTable . addConstantUtf8 ( Constants . MODULE_PACKAGES ) ; // 6 attribute header bytes, and 2 bytes for package_count. size += 8 + packageIndex . length ; } if ( mainClassIndex > 0 ) { symbolTable . addConstantUtf8 ( Constants . MODULE_MAIN_CLASS ) ; // 6 attribute header bytes, and 2 bytes for main_class_index. size += 8 ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the Module ModulePackages and ModuleMainClass attributes generated by this ModuleWriter in the given ByteVector . [CODESPLIT] void putAttributes ( final ByteVector output ) { // 6 bytes for name, flags and version, and 5 * 2 bytes for counts. int moduleAttributeLength = 16 + requires . length + exports . length + opens . length + usesIndex . length + provides . length ; output . putShort ( symbolTable . addConstantUtf8 ( Constants . MODULE ) ) . putInt ( moduleAttributeLength ) . putShort ( moduleNameIndex ) . putShort ( moduleFlags ) . putShort ( moduleVersionIndex ) . putShort ( requiresCount ) . putByteArray ( requires . data , 0 , requires . length ) . putShort ( exportsCount ) . putByteArray ( exports . data , 0 , exports . length ) . putShort ( opensCount ) . putByteArray ( opens . data , 0 , opens . length ) . putShort ( usesCount ) . putByteArray ( usesIndex . data , 0 , usesIndex . length ) . putShort ( providesCount ) . putByteArray ( provides . data , 0 , provides . length ) ; if ( packageCount > 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . MODULE_PACKAGES ) ) . putInt ( 2 + packageIndex . length ) . putShort ( packageCount ) . putByteArray ( packageIndex . data , 0 , packageIndex . length ) ; } if ( mainClassIndex > 0 ) { output . putShort ( symbolTable . addConstantUtf8 ( Constants . MODULE_MAIN_CLASS ) ) . putInt ( 2 ) . putShort ( mainClassIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes URL elements . This method may be used for all parts of URL except for the query parts since it does not decode the + character . [CODESPLIT] public static String decode ( final String source , final String encoding ) { return decode ( source , encoding , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes query name or value . [CODESPLIT] public static String decodeQuery ( final String source , final String encoding ) { return decode ( source , encoding , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes database . First creates connection pool . and transaction manager . Then Jodds DbEntityManager is configured . It is also configured automagically by scanning the class path for entities . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public void start ( ) { initLogger ( ) ; if ( ! databaseEnabled ) { log . info ( \"DB not enabled.\" ) ; return ; } log . info ( \"DB start ----------\" ) ; final PetiteContainer petiteContainer = joyPetiteSupplier . get ( ) . getPetiteContainer ( ) ; // connection pool connectionProvider = createConnectionProviderIfNotSupplied ( ) ; petiteContainer . addBean ( beanNamePrefix ( ) + \"pool\" , connectionProvider ) ; if ( connectionProvider instanceof CoreConnectionPool ) { final CoreConnectionPool pool = ( CoreConnectionPool ) connectionProvider ; if ( pool . getDriver ( ) == null ) { databaseEnabled = false ; log . warn ( \"DB configuration not set (\" + beanNamePrefix ( ) + \"pool.*). DB will be disabled.\" ) ; return ; } } connectionProvider . init ( ) ; checkConnectionProvider ( ) ; // transactions manager jtxManager = createJtxTransactionManager ( connectionProvider ) ; jtxManager . setValidateExistingTransaction ( true ) ; final AnnotationTxAdviceManager annTxAdviceManager = new AnnotationTxAdviceManager ( new LeanJtxWorker ( jtxManager ) , jtxScopePattern ) ; AnnotationTxAdviceSupport . manager = annTxAdviceManager ; // create proxy joyProxettaSupplier . get ( ) . getProxetta ( ) . withAspect ( createTxProxyAspects ( annTxAdviceManager . getAnnotations ( ) ) ) ; final DbSessionProvider sessionProvider = new DbJtxSessionProvider ( jtxManager ) ; // querymap final long startTime = System . currentTimeMillis ( ) ; final QueryMap queryMap = new DbPropsQueryMap ( ) ; log . debug ( \"Queries loaded in \" + ( System . currentTimeMillis ( ) - startTime ) + \"ms.\" ) ; log . debug ( \"Total queries: \" + queryMap . size ( ) ) ; // dboom dbOom = DbOom . create ( ) . withConnectionProvider ( connectionProvider ) . withSessionProvider ( sessionProvider ) . withQueryMap ( queryMap ) . get ( ) ; dbOom . connect ( ) ; final DbEntityManager dbEntityManager = dbOom . entityManager ( ) ; dbEntityManager . reset ( ) ; petiteContainer . addBean ( beanNamePrefix ( ) + \"query\" , dbOom . queryConfig ( ) ) ; petiteContainer . addBean ( beanNamePrefix ( ) + \"oom\" , dbOom . config ( ) ) ; // automatic configuration if ( autoConfiguration ) { final AutomagicDbOomConfigurator automagicDbOomConfigurator = new AutomagicDbOomConfigurator ( dbEntityManager , true ) ; automagicDbOomConfigurator . registerAsConsumer ( joyScannerSupplier . get ( ) . getClassScanner ( ) ) ; } dbEntityManagerConsumers . accept ( dbEntityManager ) ; log . info ( \"DB OK!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if connection provider can return a connection . [CODESPLIT] protected void checkConnectionProvider ( ) { final Connection connection = connectionProvider . getConnection ( ) ; try { final DatabaseMetaData databaseMetaData = connection . getMetaData ( ) ; String name = databaseMetaData . getDatabaseProductName ( ) ; String version = databaseMetaData . getDatabaseProductVersion ( ) ; if ( log . isInfoEnabled ( ) ) { log . info ( \"Connected to database: \" + name + \" v\" + version ) ; } } catch ( SQLException sex ) { log . error ( \"DB connection failed: \" , sex ) ; } finally { connectionProvider . closeConnection ( connection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- print [CODESPLIT] public void printEntities ( final int width ) { if ( ! databaseEnabled ) { return ; } final List < DbEntityDescriptor > list = new ArrayList <> ( ) ; dbOom . entityManager ( ) . forEachEntity ( list :: add ) ; if ( list . isEmpty ( ) ) { return ; } final Print print = new Print ( ) ; print . line ( \"Entities\" , width ) ; list . stream ( ) . sorted ( Comparator . comparing ( DbEntityDescriptor :: getEntityName ) ) . forEach ( ded -> print . outLeftRightNewLine ( Chalk256 . chalk ( ) . yellow ( ) , ded . getTableName ( ) , Chalk256 . chalk ( ) . blue ( ) , ClassUtil . getShortClassName ( ded . getType ( ) , 2 ) , width ) ) ; print . line ( width ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns method signature for some method . If signature is not found returns <code > null< / code > . Founded signatures means that those method can be proxyfied . [CODESPLIT] public MethodSignatureVisitor lookupMethodSignatureVisitor ( final int access , final String name , final String desc , final String className ) { String key = ProxettaAsmUtil . createMethodSignaturesKey ( access , name , desc , className ) ; return methodSignatures . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- visits [CODESPLIT] @ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { final int lastSlash = name . lastIndexOf ( ' ' ) ; this . thisReference = name ; this . superName = superName ; this . nextSupername = superName ; this . targetPackage = lastSlash == - 1 ? StringPool . EMPTY : name . substring ( 0 , lastSlash ) . replace ( ' ' , ' ' ) ; this . targetClassname = name . substring ( lastSlash + 1 ) ; this . isTargetInterface = ( access & AsmUtil . ACC_INTERFACE ) != 0 ; if ( this . isTargetInterface ) { nextInterfaces = new HashSet <> ( ) ; if ( interfaces != null ) { Collections . addAll ( nextInterfaces , interfaces ) ; } } generics = new GenericsReader ( ) . parseSignatureForGenerics ( signature , isTargetInterface ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores method signature for target method . [CODESPLIT] @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { //\t\tif ((access & AsmUtil.ACC_FINAL) != 0) { //\t\t\treturn null;\t// skip finals //\t\t} MethodSignatureVisitor msign = createMethodSignature ( access , name , desc , signature , exceptions , thisReference , this . generics ) ; String key = ProxettaAsmUtil . createMethodSignaturesKey ( access , name , desc , thisReference ) ; methodSignatures . put ( key , msign ) ; allMethodSignatures . add ( msign . getCleanSignature ( ) ) ; return new MethodAnnotationReader ( msign ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores signatures for all super public methods not already overridden by target class . All this methods will be accepted for proxyfication . [CODESPLIT] @ Override public void visitEnd ( ) { // prepare class annotations if ( classAnnotations != null ) { annotations = classAnnotations . toArray ( new AnnotationInfo [ 0 ] ) ; classAnnotations = null ; } List < String > superList = new ArrayList <> ( ) ; Set < String > allInterfaces = new HashSet <> ( ) ; if ( nextInterfaces != null ) { allInterfaces . addAll ( nextInterfaces ) ; } // check all public super methods that are not overridden in superclass while ( nextSupername != null ) { InputStream inputStream = null ; ClassReader cr ; try { inputStream = ClassLoaderUtil . getClassAsStream ( nextSupername , classLoader ) ; cr = new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( \"Unable to inspect super class: \" + nextSupername , ioex ) ; } finally { StreamUtil . close ( inputStream ) ; } superList . add ( nextSupername ) ; superClassReaders . add ( cr ) ; // remember the super class reader cr . accept ( new SuperClassVisitor ( ) , 0 ) ; if ( cr . getInterfaces ( ) != null ) { Collections . addAll ( allInterfaces , cr . getInterfaces ( ) ) ; } } superClasses = superList . toArray ( new String [ 0 ] ) ; // check all interface methods that are not overridden in super-interface Set < String > todoInterfaces = new HashSet <> ( allInterfaces ) ; Set < String > newCollectedInterfaces = new HashSet <> ( ) ; while ( true ) { for ( String next : todoInterfaces ) { InputStream inputStream = null ; ClassReader cr ; try { inputStream = ClassLoaderUtil . getClassAsStream ( next , classLoader ) ; cr = new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( \"Unable to inspect super interface: \" + next , ioex ) ; } finally { StreamUtil . close ( inputStream ) ; } superClassReaders . add ( cr ) ; // remember the super class reader cr . accept ( new SuperClassVisitor ( ) , 0 ) ; if ( cr . getInterfaces ( ) != null ) { for ( String newInterface : cr . getInterfaces ( ) ) { if ( ! allInterfaces . contains ( newInterface ) && ! todoInterfaces . contains ( newInterface ) ) { // new interface found newCollectedInterfaces . add ( newInterface ) ; } } } } // perform collection allInterfaces . addAll ( todoInterfaces ) ; if ( newCollectedInterfaces . isEmpty ( ) ) { // no new interface found break ; } todoInterfaces . clear ( ) ; todoInterfaces . addAll ( newCollectedInterfaces ) ; newCollectedInterfaces . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates method signature from method name . [CODESPLIT] protected MethodSignatureVisitor createMethodSignature ( final int access , final String methodName , final String description , final String signature , final String [ ] exceptions , final String classname , final Map < String , String > declaredTypeGenerics ) { MethodSignatureVisitor v = new MethodSignatureVisitor ( methodName , access , classname , description , exceptions , signature , declaredTypeGenerics , this ) ; new SignatureReader ( signature != null ? signature : description ) . accept ( v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse fields as csv string [CODESPLIT] public static String toCsvString ( final Object ... elements ) { StringBuilder line = new StringBuilder ( ) ; int last = elements . length - 1 ; for ( int i = 0 ; i < elements . length ; i ++ ) { if ( elements [ i ] == null ) { if ( i != last ) { line . append ( FIELD_SEPARATOR ) ; } continue ; } String field = elements [ i ] . toString ( ) ; // check for special cases int ndx = field . indexOf ( FIELD_SEPARATOR ) ; if ( ndx == - 1 ) { ndx = field . indexOf ( FIELD_QUOTE ) ; } if ( ndx == - 1 ) { if ( field . startsWith ( StringPool . SPACE ) || field . endsWith ( StringPool . SPACE ) ) { ndx = 1 ; } } if ( ndx == - 1 ) { ndx = StringUtil . indexOfChars ( field , SPECIAL_CHARS ) ; } // add field if ( ndx != - 1 ) { line . append ( FIELD_QUOTE ) ; } field = StringUtil . replace ( field , StringPool . QUOTE , DOUBLE_QUOTE ) ; line . append ( field ) ; if ( ndx != - 1 ) { line . append ( FIELD_QUOTE ) ; } // last if ( i != last ) { line . append ( FIELD_SEPARATOR ) ; } } return line . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts CSV line to string array . [CODESPLIT] public static String [ ] toStringArray ( final String line ) { List < String > row = new ArrayList <> ( ) ; boolean inQuotedField = false ; int fieldStart = 0 ; final int len = line . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = line . charAt ( i ) ; if ( c == FIELD_SEPARATOR ) { if ( ! inQuotedField ) { // ignore we are quoting addField ( row , line , fieldStart , i , inQuotedField ) ; fieldStart = i + 1 ; } } else if ( c == FIELD_QUOTE ) { if ( inQuotedField ) { if ( i + 1 == len || line . charAt ( i + 1 ) == FIELD_SEPARATOR ) { // we are already quoting - peek to see if this is the end of the field addField ( row , line , fieldStart , i , inQuotedField ) ; fieldStart = i + 2 ; i ++ ; // and skip the comma inQuotedField = false ; } } else if ( fieldStart == i ) { inQuotedField = true ; // this is a beginning of a quote fieldStart ++ ; // move field start } } } // add last field - but only if string was not empty if ( len > 0 && fieldStart <= len ) { addField ( row , line , fieldStart , len , inQuotedField ) ; } return row . toArray ( new String [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves constructor injection point from type . Looks for single annotated constructor . If no annotated constructors found the total number of constructors will be checked . If there is only one constructor that one will be used as injection point . If more constructors exist the default one will be used as injection point . Otherwise exception is thrown . [CODESPLIT] public CtorInjectionPoint resolve ( final Class type , final boolean useAnnotation ) { // lookup methods ClassDescriptor cd = ClassIntrospector . get ( ) . lookup ( type ) ; CtorDescriptor [ ] allCtors = cd . getAllCtorDescriptors ( ) ; Constructor foundedCtor = null ; Constructor defaultCtor = null ; BeanReferences [ ] references = null ; for ( CtorDescriptor ctorDescriptor : allCtors ) { Constructor < ? > ctor = ctorDescriptor . getConstructor ( ) ; Class < ? > [ ] paramTypes = ctor . getParameterTypes ( ) ; if ( paramTypes . length == 0 ) { defaultCtor = ctor ; // detects default ctors } if ( ! useAnnotation ) { continue ; } BeanReferences [ ] ctorReferences = referencesResolver . readAllReferencesFromAnnotation ( ctor ) ; if ( ctorReferences == null ) { continue ; } if ( foundedCtor != null ) { throw new PetiteException ( \"Two or more constructors are annotated as injection points in the bean: \" + type . getName ( ) ) ; } foundedCtor = ctor ; references = ctorReferences ; } if ( foundedCtor == null ) { // there is no annotated constructor if ( allCtors . length == 1 ) { foundedCtor = allCtors [ 0 ] . getConstructor ( ) ; } else { foundedCtor = defaultCtor ; } if ( foundedCtor == null ) { // no matching ctor found // still this is not an error if bean is already instantiated. return CtorInjectionPoint . EMPTY ; } references = referencesResolver . readAllReferencesFromAnnotation ( foundedCtor ) ; if ( references == null ) { references = new BeanReferences [ 0 ] ; } } return new CtorInjectionPoint ( foundedCtor , references ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates advice s class reader . [CODESPLIT] private ClassReader createAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { InputStream inputStream = null ; try { inputStream = ClassLoaderUtil . getClassAsStream ( advice ) ; return new ClassReader ( inputStream ) ; } catch ( IOException ioex ) { throw new ProxettaException ( ioex ) ; } finally { StreamUtil . close ( inputStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns class reader for advice . [CODESPLIT] private ClassReader getCachedAdviceClassReader ( final Class < ? extends ProxyAdvice > advice ) { if ( adviceClassReaderCache == null ) { adviceClassReaderCache = TypeCache . createDefault ( ) ; } ClassReader adviceReader = adviceClassReaderCache . get ( advice ) ; if ( adviceReader == null ) { adviceReader = createAdviceClassReader ( advice ) ; adviceClassReaderCache . put ( advice , adviceReader ) ; } return adviceReader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse advice class to gather some advice data . Should be called before any advice use . Must be called only * once * per advice . [CODESPLIT] private void readAdviceData ( ) { if ( ready ) { return ; } adviceClassReader . accept ( new EmptyClassVisitor ( ) { /**\n\t\t\t * Stores advice reference.\n\t\t\t */ @ Override public void visit ( final int version , final int access , final String name , final String signature , final String superName , final String [ ] interfaces ) { adviceReference = name ; super . visit ( version , access , name , signature , superName , interfaces ) ; } /**\n\t\t\t * Prevents advice to have inner classes.\n\t\t\t */ @ Override public void visitInnerClass ( final String name , final String outerName , final String innerName , final int access ) { if ( outerName . equals ( adviceReference ) ) { throw new ProxettaException ( \"Proxetta doesn't allow inner classes in/for advice: \" + advice . getName ( ) ) ; } super . visitInnerClass ( name , outerName , innerName , access ) ; } /**\n\t\t\t * Clones advices fields to destination.\n\t\t\t */ @ Override public FieldVisitor visitField ( final int access , final String name , final String desc , final String signature , final Object value ) { wd . dest . visitField ( access , adviceFieldName ( name , aspectIndex ) , desc , signature , value ) ; // [A5] return super . visitField ( access , name , desc , signature , value ) ; } /**\n\t\t\t * Copies advices methods to destination.\n\t\t\t */ @ Override public MethodVisitor visitMethod ( int access , String name , final String desc , final String signature , final String [ ] exceptions ) { if ( name . equals ( CLINIT ) ) { // [A6] if ( ! desc . equals ( DESC_VOID ) ) { throw new ProxettaException ( \"Invalid static initialization block description for advice: \" + advice . getName ( ) ) ; } name = ProxettaNames . clinitMethodName + ProxettaNames . methodDivider + aspectIndex ; access |= AsmUtil . ACC_PRIVATE | AsmUtil . ACC_FINAL ; wd . addAdviceClinitMethod ( name ) ; return new MethodAdapter ( wd . dest . visitMethod ( access , name , desc , signature , exceptions ) ) { @ Override public void visitLocalVariable ( final String name , final String desc , final String signature , final Label start , final Label end , final int index ) { } @ Override public void visitLineNumber ( final int line , final Label start ) { } @ Override public void visitMethodInsn ( final int opcode , String owner , String name , final String desc , final boolean isInterface ) { if ( opcode == INVOKESTATIC ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; } @ Override public void visitFieldInsn ( final int opcode , String owner , String name , final String desc ) { // [F6] if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; // [F5] name = adviceFieldName ( name , aspectIndex ) ; } super . visitFieldInsn ( opcode , owner , name , desc ) ; } } ; } else if ( name . equals ( INIT ) ) { // [A7] if ( ! desc . equals ( DESC_VOID ) ) { throw new ProxettaException ( \"Advices can have only default constructors. Invalid advice: \" + advice . getName ( ) ) ; } name = ProxettaNames . initMethodName + ProxettaNames . methodDivider + aspectIndex ; access = ProxettaAsmUtil . makePrivateFinalAccess ( access ) ; wd . addAdviceInitMethod ( name ) ; return new MethodAdapter ( wd . dest . visitMethod ( access , name , desc , signature , exceptions ) ) { @ Override public void visitLocalVariable ( final String name , final String desc , final String signature , final Label start , final Label end , final int index ) { } @ Override public void visitLineNumber ( final int line , final Label start ) { } int state ; // used to detect and to ignore the first super call() @ Override public void visitVarInsn ( final int opcode , final int var ) { // [F7] if ( ( state == 0 ) && ( opcode == ALOAD ) && ( var == 0 ) ) { state ++ ; return ; } super . visitVarInsn ( opcode , var ) ; } @ Override public void visitMethodInsn ( final int opcode , String owner , String name , final String desc , final boolean isInterface ) { if ( ( state == 1 ) && ( opcode == INVOKESPECIAL ) ) { state ++ ; return ; } if ( ( opcode == INVOKEVIRTUAL ) || ( opcode == INVOKEINTERFACE ) ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } else if ( opcode == INVOKESTATIC ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; } @ Override public void visitFieldInsn ( final int opcode , String owner , String name , final String desc ) { // [F7] if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; // [F5] name = adviceFieldName ( name , aspectIndex ) ; } super . visitFieldInsn ( opcode , owner , name , desc ) ; } } ; } else // other methods if ( ! name . equals ( ProxettaNames . executeMethodName ) ) { name = adviceMethodName ( name , aspectIndex ) ; return new MethodAdapter ( wd . dest . visitMethod ( access , name , desc , signature , exceptions ) ) { @ Override public void visitLocalVariable ( final String name , final String desc , final String signature , final Label start , final Label end , final int index ) { } @ Override public void visitLineNumber ( final int line , final Label start ) { } @ Override public void visitMethodInsn ( final int opcode , String owner , String name , final String desc , final boolean isInterface ) { if ( ( opcode == INVOKEVIRTUAL ) || ( opcode == INVOKEINTERFACE ) ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } else if ( opcode == INVOKESTATIC || opcode == INVOKESPECIAL ) { if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceMethodName ( name , aspectIndex ) ; } } super . visitMethodInsn ( opcode , owner , name , desc , isInterface ) ; } @ Override public void visitFieldInsn ( final int opcode , String owner , String name , final String desc ) { // replace field references if ( owner . equals ( adviceReference ) ) { owner = wd . thisReference ; name = adviceFieldName ( name , aspectIndex ) ; } super . visitFieldInsn ( opcode , owner , name , desc ) ; } } ; } // Parse EXECUTE method, just to gather some info, real parsing will come later //return new MethodAdapter(new EmptyMethodVisitor()) {\t\t// toask may we replace this with the following code? return new EmptyMethodVisitor ( ) { @ Override public void visitVarInsn ( final int opcode , final int var ) { if ( isStoreOpcode ( opcode ) ) { if ( var > maxLocalVarOffset ) { maxLocalVarOffset = var ; // find max local var offset } } super . visitVarInsn ( opcode , var ) ; } } ; //\t\t\t\t\treturn super.visitMethod(access, name, desc, signature, exceptions); } } , 0 ) ; maxLocalVarOffset += 2 ; // increment offset by 2 because var on last index may be a dword value ready = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Symmetrically encrypts the string . [CODESPLIT] public String encrypt ( final String str ) { try { byte [ ] utf8 = StringUtil . getBytes ( str ) ; // encode the string into bytes using utf-8 byte [ ] enc = ecipher . doFinal ( utf8 ) ; // encrypt return Base64 . encodeToString ( enc ) ; // encode bytes to base64 to get a string } catch ( Throwable ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Symmetrically decrypts the string . [CODESPLIT] public String decrypt ( String str ) { try { str = StringUtil . replaceChar ( str , ' ' , ' ' ) ; // replace spaces with chars. byte [ ] dec = Base64 . decode ( str ) ; // decode base64 to get bytes byte [ ] utf8 = dcipher . doFinal ( dec ) ; // decrypt return new String ( utf8 , UTF_8 ) ; // decode using utf-8 } catch ( Throwable ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets { [CODESPLIT] public static void setLoggerProvider ( final LoggerProvider loggerProvider ) { LoggerFactory . loggerProvider = loggerProvider :: createLogger ; if ( loggers != null ) { loggers . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns logger for given name . Repeated calls to this method with the same argument should return the very same instance of the logger . [CODESPLIT] public static Logger getLogger ( final String name ) { if ( loggers == null ) { return loggerProvider . apply ( name ) ; } return loggers . computeIfAbsent ( name , loggerProvider ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the cookie name and checks for validity . [CODESPLIT] private void setName ( final String name ) { if ( name . contains ( \";\" ) || name . contains ( \",\" ) || name . startsWith ( \"$\" ) ) { throw new IllegalArgumentException ( \"Invalid cookie name:\" + name ) ; } for ( int n = 0 ; n < name . length ( ) ; n ++ ) { char c = name . charAt ( n ) ; if ( c <= 0x20 || c >= 0x7f ) { throw new IllegalArgumentException ( \"Invalid cookie name:\" + name ) ; } } this . name = name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes action registered to provided action path Provides action chaining by invoking the next action request . Returns <code > null< / code > if action path is consumed and has been invoked by this controller ; otherwise the action path string is returned ( it might be different than original one provided in arguments ) . On first invoke initializes the action runtime before further proceeding . [CODESPLIT] public String invoke ( String actionPath , final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) throws Exception { final String originalActionPath = actionPath ; boolean characterEncodingSet = false ; while ( actionPath != null ) { // build action path final String httpMethod = servletRequest . getMethod ( ) . toUpperCase ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Action path: \" + httpMethod + \" \" + actionPath ) ; } actionPath = actionPathRewriter . rewrite ( servletRequest , actionPath , httpMethod ) ; String [ ] actionPathChunks = MadvocUtil . splitPathToChunks ( actionPath ) ; // resolve action runtime ActionRuntime actionRuntime = actionsManager . lookup ( httpMethod , actionPathChunks ) ; if ( actionRuntime == null ) { // special case! if ( actionPath . endsWith ( welcomeFile ) ) { actionPath = actionPath . substring ( 0 , actionPath . length ( ) - ( welcomeFile . length ( ) - 1 ) ) ; actionPathChunks = MadvocUtil . splitPathToChunks ( actionPath ) ; actionRuntime = actionsManager . lookup ( httpMethod , actionPathChunks ) ; } if ( actionRuntime == null ) { return originalActionPath ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( \"Invoke action for '\" + actionPath + \"' using \" + actionRuntime . createActionString ( ) ) ; } // set character encoding if ( ! characterEncodingSet && applyCharacterEncoding ) { final String encoding = madvocEncoding . getEncoding ( ) ; if ( encoding != null ) { servletRequest . setCharacterEncoding ( encoding ) ; servletResponse . setCharacterEncoding ( encoding ) ; } characterEncodingSet = true ; } // create action object final Object action ; if ( actionRuntime . isActionHandlerDefined ( ) ) { action = actionRuntime . getActionHandler ( ) ; } else { action = createAction ( actionRuntime . getActionClass ( ) ) ; } final ActionRequest actionRequest = createActionRequest ( actionPath , actionPathChunks , actionRuntime , action , servletRequest , servletResponse ) ; // invoke and render if ( actionRuntime . isAsync ( ) ) { asyncActionExecutor . invoke ( actionRequest ) ; } else { actionRequest . invoke ( ) ; } actionPath = actionRequest . getNextActionPath ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes a result after the action invocation . <p > Results may be objects that specify which action result will be used to render the result . <p > Result value may consist of two parts : type and value . Result type is optional and if exists it is separated by semi - colon from the value . If type is not specified then the default result type if still not defined . Result type defines which { @link ActionResult } should be used for rendering the value . <p > Result value is first checked against aliased values . Then it is resolved and then passed to the founded { @link ActionResult } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void render ( final ActionRequest actionRequest , final Object resultObject ) throws Exception { final ActionResult actionResult = resultsManager . lookup ( actionRequest , resultObject ) ; if ( actionResult == null ) { throw new MadvocException ( \"Action result not found\" ) ; } if ( preventCaching ) { ServletUtil . preventCaching ( actionRequest . getHttpServletResponse ( ) ) ; } log . debug ( ( ) -> \"Result type: \" + actionResult . getClass ( ) . getSimpleName ( ) ) ; actionResult . render ( actionRequest , actionRequest . getActionResult ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new action object from { [CODESPLIT] protected Object createAction ( final Class actionClass ) { try { return ClassUtil . newInstance ( actionClass ) ; } catch ( Exception ex ) { throw new MadvocException ( \"Invalid Madvoc action\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new action request . [CODESPLIT] protected ActionRequest createActionRequest ( final String actionPath , final String [ ] actionPathChunks , final ActionRuntime actionRuntime , final Object action , final HttpServletRequest servletRequest , final HttpServletResponse servletResponse ) { return new ActionRequest ( this , actionPath , actionPathChunks , actionRuntime , action , servletRequest , servletResponse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires filter from Petite container . [CODESPLIT] @ Override protected < R extends ActionFilter > R createWrapper ( final Class < R > wrapperClass ) { return petiteContainer . createBean ( wrapperClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if bean is destroyable . [CODESPLIT] protected boolean isBeanDestroyable ( final BeanData beanData ) { DestroyMethodPoint [ ] dmp = beanData . definition ( ) . destroyMethodPoints ( ) ; return dmp != null && dmp . length != 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if bean data is destroyable ( has destroy methods ) and registers it for later { [CODESPLIT] protected void registerDestroyableBeans ( final BeanData beanData ) { if ( ! isBeanDestroyable ( beanData ) ) { return ; } if ( destroyableBeans == null ) { destroyableBeans = new ArrayList <> ( ) ; } destroyableBeans . add ( beanData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes destroyable bean from the list and calls it destroy methods . If bean is not destroyable does nothing . Bean gets destroyed only once . [CODESPLIT] protected void destroyBean ( final BeanData beanData ) { if ( destroyableBeans == null ) { return ; } if ( ! isBeanDestroyable ( beanData ) ) { return ; } if ( destroyableBeans . remove ( beanData ) ) { beanData . callDestroyMethods ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdowns the scope and calls all collected destroyable beans . [CODESPLIT] @ Override public void shutdown ( ) { if ( destroyableBeans == null ) { return ; } for ( final BeanData destroyableBean : destroyableBeans ) { destroyableBean . callDestroyMethods ( ) ; } destroyableBeans . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link MailSession } { @link Properties } . [CODESPLIT] protected Properties createSessionProperties ( ) { final Properties props = new Properties ( ) ; props . putAll ( customProperties ) ; if ( debugMode ) { props . put ( MAIL_DEBUG , \"true\" ) ; } if ( ! strictAddress ) { props . put ( MAIL_MIME_ADDRESS_STRICT , \"false\" ) ; } return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receives the emails as specified by the builder . [CODESPLIT] public ReceivedEmail [ ] get ( ) { if ( fromFolder != null ) { session . useFolder ( fromFolder ) ; } return session . receiveMessages ( filter , flagsToSet , flagsToUnset , envelopeOnly , messages -> { if ( targetFolder != null ) { try { session . folder . copyMessages ( messages , session . getFolder ( targetFolder ) ) ; } catch ( MessagingException e ) { throw new MailException ( \"Copying messages failed\" ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Duplicate the underlying { @link ByteBuffer } s and wrap them for thread local access . [CODESPLIT] public UnsafeBuffer [ ] duplicateTermBuffers ( ) { final UnsafeBuffer [ ] buffers = new UnsafeBuffer [ PARTITION_COUNT ] ; for ( int i = 0 ; i < PARTITION_COUNT ; i ++ ) { buffers [ i ] = new UnsafeBuffer ( termBuffers [ i ] . duplicate ( ) . order ( ByteOrder . LITTLE_ENDIAN ) ) ; } return buffers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch the clustered service container and await a shutdown signal . [CODESPLIT] public static void main ( final String [ ] args ) { loadPropertiesFiles ( args ) ; try ( ClusteredServiceContainer container = launch ( ) ) { container . context ( ) . shutdownSignalBarrier ( ) . await ( ) ; System . out . println ( \"Shutdown ClusteredServiceContainer...\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a per { @link io . aeron . driver . PublicationImage } indicator . [CODESPLIT] public static AtomicCounter allocate ( final MutableDirectBuffer tempBuffer , final String name , final CountersManager countersManager , final long registrationId , final int sessionId , final int streamId , final String channel ) { final int counterId = StreamCounter . allocateCounterId ( tempBuffer , name , PER_IMAGE_TYPE_ID , countersManager , registrationId , sessionId , streamId , channel ) ; return new AtomicCounter ( countersManager . valuesBuffer ( ) , counterId , countersManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run loop for the rate reporter [CODESPLIT] public void run ( ) { do { LockSupport . parkNanos ( parkNs ) ; final long currentTotalMessages = totalMessages ; final long currentTotalBytes = totalBytes ; final long currentTimestamp = System . nanoTime ( ) ; final long timeSpanNs = currentTimestamp - lastTimestamp ; final double messagesPerSec = ( ( currentTotalMessages - lastTotalMessages ) * ( double ) reportIntervalNs ) / ( double ) timeSpanNs ; final double bytesPerSec = ( ( currentTotalBytes - lastTotalBytes ) * ( double ) reportIntervalNs ) / ( double ) timeSpanNs ; reportingFunc . onReport ( messagesPerSec , bytesPerSec , currentTotalMessages , currentTotalBytes ) ; lastTotalBytes = currentTotalBytes ; lastTotalMessages = currentTotalMessages ; lastTimestamp = currentTimestamp ; } while ( ! halt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a reusable parametrised { @link FragmentHandler } that calls into a { @link RateReporter } . [CODESPLIT] public static FragmentHandler rateReporterHandler ( final RateReporter reporter ) { return ( buffer , offset , length , header ) -> reporter . onMessage ( 1 , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic error handler that just prints message to stdout . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static void printError ( final String channel , final int streamId , final int sessionId , final String message , final HeaderFlyweight cause ) { System . out . println ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the rates to stdout [CODESPLIT] public static void printRate ( final double messagesPerSec , final double bytesPerSec , final long totalMessages , final long totalBytes ) { System . out . println ( String . format ( \"%.02g msgs/sec, %.02g payload bytes/sec, totals %d messages %d MB\" , messagesPerSec , bytesPerSec , totalMessages , totalBytes / ( 1024 * 1024 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map an existing file as a read only buffer . [CODESPLIT] public static MappedByteBuffer mapExistingFileReadOnly ( final File location ) { if ( ! location . exists ( ) ) { final String msg = \"file not found: \" + location . getAbsolutePath ( ) ; throw new IllegalStateException ( msg ) ; } MappedByteBuffer mappedByteBuffer = null ; try ( RandomAccessFile file = new RandomAccessFile ( location , \"r\" ) ; FileChannel channel = file . getChannel ( ) ) { mappedByteBuffer = channel . map ( READ_ONLY , 0 , channel . size ( ) ) ; } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return mappedByteBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the merge and stop any active replay . Will remove the replay destination from the subscription . Will NOT remove the live destination if it has been added . [CODESPLIT] public void close ( ) { final State state = this . state ; if ( State . CLOSED != state ) { if ( isReplayActive ) { isReplayActive = false ; archive . stopReplay ( replaySessionId ) ; } if ( State . MERGED != state ) { subscription . removeDestination ( replayDestination ) ; } state ( State . CLOSED ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the operation of the merge . Do not call the processing of fragments on the subscription . [CODESPLIT] public int doWork ( ) { int workCount = 0 ; switch ( state ) { case AWAIT_INITIAL_RECORDING_POSITION : workCount += awaitInitialRecordingPosition ( ) ; break ; case AWAIT_REPLAY : workCount += awaitReplay ( ) ; break ; case AWAIT_CATCH_UP : workCount += awaitCatchUp ( ) ; break ; case AWAIT_CURRENT_RECORDING_POSITION : workCount += awaitUpdatedRecordingPosition ( ) ; break ; case AWAIT_STOP_REPLAY : workCount += awaitStopReplay ( ) ; break ; } return workCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll the { @link Image } used for the merging replay and live stream . The { @link ReplayMerge#doWork () } method will be called before the poll so that processing of the merge can be done . [CODESPLIT] public int poll ( final FragmentHandler fragmentHandler , final int fragmentLimit ) { doWork ( ) ; return null == image ? 0 : image . poll ( fragmentHandler , fragmentLimit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current position to which the publication has advanced for this stream . [CODESPLIT] public long position ( ) { if ( isClosed ) { return CLOSED ; } final long rawTail = rawTailVolatile ( logMetaDataBuffer ) ; final int termOffset = termOffset ( rawTail , termBufferLength ) ; return computePosition ( termId ( rawTail ) , termOffset , positionBitsToShift , initialTermId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a partial buffer containing a message . [CODESPLIT] public final long offer ( final DirectBuffer buffer , final int offset , final int length ) { return offer ( buffer , offset , length , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a message composed of two parts e . g . a header and encapsulated payload . [CODESPLIT] public final long offer ( final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo ) { return offer ( bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a partial buffer containing a message . [CODESPLIT] public long offer ( final DirectBuffer buffer , final int offset , final int length , final ReservedValueSupplier reservedValueSupplier ) { long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { final int result ; if ( length <= maxPayloadLength ) { checkPositiveLength ( length ) ; result = termAppender . appendUnfragmentedMessage ( termId , termOffset , headerWriter , buffer , offset , length , reservedValueSupplier ) ; } else { checkMaxMessageLength ( length ) ; result = termAppender . appendFragmentedMessage ( termId , termOffset , headerWriter , buffer , offset , length , maxPayloadLength , reservedValueSupplier ) ; } newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a message composed of two parts e . g . a header and encapsulated payload . [CODESPLIT] public long offer ( final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final ReservedValueSupplier reservedValueSupplier ) { long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; final int length = validateAndComputeLength ( lengthOne , lengthTwo ) ; if ( position < limit ) { final int result ; if ( length <= maxPayloadLength ) { checkPositiveLength ( length ) ; result = termAppender . appendUnfragmentedMessage ( termId , termOffset , headerWriter , bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , reservedValueSupplier ) ; } else { checkMaxMessageLength ( length ) ; result = termAppender . appendFragmentedMessage ( termId , termOffset , headerWriter , bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , maxPayloadLength , reservedValueSupplier ) ; } newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish by gathering buffer vectors into a message . [CODESPLIT] public long offer ( final DirectBufferVector [ ] vectors , final ReservedValueSupplier reservedValueSupplier ) { final int length = DirectBufferVector . validateAndComputeLength ( vectors ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { final int result ; if ( length <= maxPayloadLength ) { result = termAppender . appendUnfragmentedMessage ( termId , termOffset , headerWriter , vectors , length , reservedValueSupplier ) ; } else { checkMaxMessageLength ( length ) ; result = termAppender . appendFragmentedMessage ( termId , termOffset , headerWriter , vectors , length , maxPayloadLength , reservedValueSupplier ) ; } newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to claim a range in the publication log into which a message can be written with zero copy semantics . Once the message has been written then { @link BufferClaim#commit () } should be called thus making it available . <p > <b > Note : < / b > This method can only be used for message lengths less than MTU length minus header . If the claim is held after the publication is closed or the client dies then it will be unblocked to reach end - of - stream ( EOS ) . <pre > { @code final BufferClaim bufferClaim = new BufferClaim () ; [CODESPLIT] public long tryClaim ( final int length , final BufferClaim bufferClaim ) { checkPayloadLength ( length ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { final int result = termAppender . claim ( termId , termOffset , headerWriter , length , bufferClaim ) ; newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a padding record log of a given length to make up the log to a position . [CODESPLIT] public long appendPadding ( final int length ) { checkMaxMessageLength ( length ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final ExclusiveTermAppender termAppender = termAppenders [ activePartitionIndex ] ; final long position = termBeginPosition + termOffset ; if ( position < limit ) { checkPositiveLength ( length ) ; final int result = termAppender . appendPadding ( termId , termOffset , headerWriter , length ) ; newPosition = newPosition ( result ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set channel field in ASCII [CODESPLIT] public DestinationMessageFlyweight channel ( final String channel ) { lengthOfChannel = buffer . putStringAscii ( offset + CHANNEL_OFFSET , channel ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify the archive that this control session is closed so it can promptly release resources then close the local resources associated with the client . [CODESPLIT] public void close ( ) { lock . lock ( ) ; try { if ( ! isClosed ) { isClosed = true ; archiveProxy . closeSession ( controlSessionId ) ; if ( ! context . ownsAeronClient ( ) ) { CloseHelper . close ( controlResponsePoller . subscription ( ) ) ; CloseHelper . close ( archiveProxy . publication ( ) ) ; } context . close ( ) ; } } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connect to an Aeron archive by providing a { @link Context } . This will create a control session . <p > Before connecting { @link Context#conclude () } will be called . If an exception occurs then { @link Context#close () } will be called . [CODESPLIT] public static AeronArchive connect ( final Context ctx ) { Subscription subscription = null ; Publication publication = null ; AsyncConnect asyncConnect = null ; try { ctx . conclude ( ) ; final Aeron aeron = ctx . aeron ( ) ; final long messageTimeoutNs = ctx . messageTimeoutNs ( ) ; final long deadlineNs = aeron . context ( ) . nanoClock ( ) . nanoTime ( ) + messageTimeoutNs ; subscription = aeron . addSubscription ( ctx . controlResponseChannel ( ) , ctx . controlResponseStreamId ( ) ) ; final ControlResponsePoller controlResponsePoller = new ControlResponsePoller ( subscription ) ; publication = aeron . addExclusivePublication ( ctx . controlRequestChannel ( ) , ctx . controlRequestStreamId ( ) ) ; final ArchiveProxy archiveProxy = new ArchiveProxy ( publication , ctx . idleStrategy ( ) , aeron . context ( ) . nanoClock ( ) , messageTimeoutNs , DEFAULT_RETRY_ATTEMPTS ) ; asyncConnect = new AsyncConnect ( ctx , controlResponsePoller , archiveProxy , deadlineNs ) ; final IdleStrategy idleStrategy = ctx . idleStrategy ( ) ; final AgentInvoker aeronClientInvoker = aeron . conductorAgentInvoker ( ) ; AeronArchive aeronArchive ; while ( null == ( aeronArchive = asyncConnect . poll ( ) ) ) { if ( null != aeronClientInvoker ) { aeronClientInvoker . invoke ( ) ; } idleStrategy . idle ( ) ; } return aeronArchive ; } catch ( final Exception ex ) { if ( ! ctx . ownsAeronClient ( ) ) { CloseHelper . quietClose ( subscription ) ; CloseHelper . quietClose ( publication ) ; } CloseHelper . quietClose ( asyncConnect ) ; ctx . close ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Begin an attempt at creating a connection which can be completed by calling { @link AsyncConnect#poll () } until it returns the client before complete it will return null . [CODESPLIT] public static AsyncConnect asyncConnect ( final Context ctx ) { Subscription subscription = null ; Publication publication = null ; try { ctx . conclude ( ) ; final Aeron aeron = ctx . aeron ( ) ; final long messageTimeoutNs = ctx . messageTimeoutNs ( ) ; final long deadlineNs = aeron . context ( ) . nanoClock ( ) . nanoTime ( ) + messageTimeoutNs ; subscription = aeron . addSubscription ( ctx . controlResponseChannel ( ) , ctx . controlResponseStreamId ( ) ) ; final ControlResponsePoller controlResponsePoller = new ControlResponsePoller ( subscription ) ; publication = aeron . addExclusivePublication ( ctx . controlRequestChannel ( ) , ctx . controlRequestStreamId ( ) ) ; final ArchiveProxy archiveProxy = new ArchiveProxy ( publication , ctx . idleStrategy ( ) , aeron . context ( ) . nanoClock ( ) , messageTimeoutNs , DEFAULT_RETRY_ATTEMPTS ) ; return new AsyncConnect ( ctx , controlResponsePoller , archiveProxy , deadlineNs ) ; } catch ( final Exception ex ) { if ( ! ctx . ownsAeronClient ( ) ) { CloseHelper . quietClose ( subscription ) ; CloseHelper . quietClose ( publication ) ; } ctx . close ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll the response stream once for an error . If another message is present then it will be skipped over so only call when not expecting another response . [CODESPLIT] public String pollForErrorResponse ( ) { lock . lock ( ) ; try { ensureOpen ( ) ; if ( controlResponsePoller . poll ( ) != 0 && controlResponsePoller . isPollComplete ( ) ) { if ( controlResponsePoller . controlSessionId ( ) == controlSessionId && controlResponsePoller . templateId ( ) == ControlResponseDecoder . TEMPLATE_ID && controlResponsePoller . code ( ) == ControlResponseCode . ERROR ) { return controlResponsePoller . errorMessage ( ) ; } } return null ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if an error has been returned for the control session and throw a { @link ArchiveException } if { @link Context#errorHandler ( ErrorHandler ) } is not set . <p > To check for an error response without raising an exception then try { @link #pollForErrorResponse () } . [CODESPLIT] public void checkForErrorResponse ( ) { lock . lock ( ) ; try { ensureOpen ( ) ; if ( controlResponsePoller . poll ( ) != 0 && controlResponsePoller . isPollComplete ( ) ) { if ( controlResponsePoller . controlSessionId ( ) == controlSessionId && controlResponsePoller . templateId ( ) == ControlResponseDecoder . TEMPLATE_ID && controlResponsePoller . code ( ) == ControlResponseCode . ERROR ) { final ArchiveException ex = new ArchiveException ( controlResponsePoller . errorMessage ( ) , ( int ) controlResponsePoller . relevantId ( ) ) ; if ( null != context . errorHandler ( ) ) { context . errorHandler ( ) . onError ( ex ) ; } else { throw ex ; } } } } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { @link Publication } and set it up to be recorded . If this is not the first i . e . { @link Publication#isOriginal () } is true then an { @link ArchiveException } will be thrown and the recording not initiated . <p > This is a sessionId specific recording . [CODESPLIT] public Publication addRecordedPublication ( final String channel , final int streamId ) { Publication publication = null ; lock . lock ( ) ; try { ensureOpen ( ) ; publication = aeron . addPublication ( channel , streamId ) ; if ( ! publication . isOriginal ( ) ) { throw new ArchiveException ( \"publication already added for channel=\" + channel + \" streamId=\" + streamId ) ; } startRecording ( ChannelUri . addSessionId ( channel , publication . sessionId ( ) ) , streamId , SourceLocation . LOCAL ) ; } catch ( final RuntimeException ex ) { CloseHelper . quietClose ( publication ) ; throw ex ; } finally { lock . unlock ( ) ; } return publication ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an { @link ExclusivePublication } and set it up to be recorded . <p > This is a sessionId specific recording . [CODESPLIT] public ExclusivePublication addRecordedExclusivePublication ( final String channel , final int streamId ) { ExclusivePublication publication = null ; lock . lock ( ) ; try { ensureOpen ( ) ; publication = aeron . addExclusivePublication ( channel , streamId ) ; startRecording ( ChannelUri . addSessionId ( channel , publication . sessionId ( ) ) , streamId , SourceLocation . LOCAL ) ; } catch ( final RuntimeException ex ) { CloseHelper . quietClose ( publication ) ; throw ex ; } finally { lock . unlock ( ) ; } return publication ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start recording a channel and stream pairing . <p > Channels that include sessionId parameters are considered different than channels without sessionIds . If a publication matches both a sessionId specific channel recording and a non - sessionId specific recording it will be recorded twice . [CODESPLIT] public long startRecording ( final String channel , final int streamId , final SourceLocation sourceLocation ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . startRecording ( channel , streamId , sourceLocation , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send start recording request\" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop recording for a channel and stream pairing . <p > Channels that include sessionId parameters are considered different than channels without sessionIds . Stopping a recording on a channel without a sessionId parameter will not stop the recording of any sessionId specific recordings that use the same channel and streamId . [CODESPLIT] public void stopRecording ( final String channel , final int streamId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . stopRecording ( channel , streamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send stop recording request\" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop recording a sessionId specific recording that pertains to the given { @link Publication } . [CODESPLIT] public void stopRecording ( final Publication publication ) { final String recordingChannel = ChannelUri . addSessionId ( publication . channel ( ) , publication . sessionId ( ) ) ; stopRecording ( recordingChannel , publication . streamId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop recording for a subscriptionId that has been returned from { @link #startRecording ( String int SourceLocation ) } or { @link #extendRecording ( long String int SourceLocation ) } . [CODESPLIT] public void stopRecording ( final long subscriptionId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . stopRecording ( subscriptionId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send stop recording request\" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start a replay for a length in bytes of a recording from a position . If the position is { @link #NULL_POSITION } then the stream will be replayed from the start . <p > The lower 32 - bits of the returned value contains the { @link Image#sessionId () } of the received replay . All 64 - bits are required to uniquely identify the replay when calling { @link #stopReplay ( long ) } . The lower 32 - bits can be obtained by casting the { @code long } value to an { @code int } . [CODESPLIT] public long startReplay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . replay ( recordingId , position , length , replayChannel , replayStreamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send replay request\" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop a replay session . [CODESPLIT] public void stopReplay ( final long replaySessionId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . stopReplay ( replaySessionId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send stop replay request\" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replay a length in bytes of a recording from a position and for convenience create a { @link Subscription } to receive the replay . If the position is { @link #NULL_POSITION } then the stream will be replayed from the start . [CODESPLIT] public Subscription replay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final ChannelUri replayChannelUri = ChannelUri . parse ( replayChannel ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . replay ( recordingId , position , length , replayChannel , replayStreamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send replay request\" ) ; } final int replaySessionId = ( int ) pollForResponse ( correlationId ) ; replayChannelUri . put ( CommonContext . SESSION_ID_PARAM_NAME , Integer . toString ( replaySessionId ) ) ; return aeron . addSubscription ( replayChannelUri . toString ( ) , replayStreamId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List all recording descriptors from a recording id with a limit of record count . <p > If the recording id is greater than the largest known id then nothing is returned . [CODESPLIT] public int listRecordings ( final long fromRecordingId , final int recordCount , final RecordingDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecordings ( fromRecordingId , recordCount , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send list recordings request\" ) ; } return pollForDescriptors ( correlationId , recordCount , consumer ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List recording descriptors from a recording id with a limit of record count for a given channelFragment and stream id . <p > If the recording id is greater than the largest known id then nothing is returned . [CODESPLIT] public int listRecordingsForUri ( final long fromRecordingId , final int recordCount , final String channelFragment , final int streamId , final RecordingDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecordingsForUri ( fromRecordingId , recordCount , channelFragment , streamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send list recordings request\" ) ; } return pollForDescriptors ( correlationId , recordCount , consumer ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List a recording descriptor for a single recording id . <p > If the recording id is greater than the largest known id then nothing is returned . [CODESPLIT] public int listRecording ( final long recordingId , final RecordingDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecording ( recordingId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send list recording request\" ) ; } return pollForDescriptors ( correlationId , 1 , consumer ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the position recorded for an active recording . If no active recording then return { @link #NULL_POSITION } . [CODESPLIT] public long getRecordingPosition ( final long recordingId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . getRecordingPosition ( recordingId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send get recording position request\" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the last recording that matches the given criteria . [CODESPLIT] public long findLastMatchingRecording ( final long minRecordingId , final String channelFragment , final int streamId , final int sessionId ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . findLastMatchingRecording ( minRecordingId , channelFragment , streamId , sessionId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send find last matching recording request\" ) ; } return pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Truncate a stopped recording to a given position that is less than the stopped position . The provided position must be on a fragment boundary . Truncating a recording to the start position effectively deletes the recording . [CODESPLIT] public void truncateRecording ( final long recordingId , final long position ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . truncateRecording ( recordingId , position , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send truncate recording request\" ) ; } pollForResponse ( correlationId ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List active recording subscriptions in the archive . These are the result of requesting one of { @link #startRecording ( String int SourceLocation ) } or a { @link #extendRecording ( long String int SourceLocation ) } . The returned subscription id can be used for passing to { @link #stopRecording ( long ) } . [CODESPLIT] public int listRecordingSubscriptions ( final int pseudoIndex , final int subscriptionCount , final String channelFragment , final int streamId , final boolean applyStreamId , final RecordingSubscriptionDescriptorConsumer consumer ) { lock . lock ( ) ; try { ensureOpen ( ) ; final long correlationId = aeron . nextCorrelationId ( ) ; if ( ! archiveProxy . listRecordingSubscriptions ( pseudoIndex , subscriptionCount , channelFragment , streamId , applyStreamId , correlationId , controlSessionId ) ) { throw new ArchiveException ( \"failed to send list recording subscriptions request\" ) ; } return pollForSubscriptionDescriptors ( correlationId , subscriptionCount , consumer ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump the contents of a segment file to a { @link PrintStream } . [CODESPLIT] public static void dumpSegment ( final PrintStream out , final int messageDumpLimit , final UnsafeBuffer buffer ) { final DataHeaderFlyweight dataHeaderFlyweight = new DataHeaderFlyweight ( ) ; final int length = buffer . capacity ( ) ; int offset = 0 ; while ( offset < length ) { dataHeaderFlyweight . wrap ( buffer , offset , length - offset ) ; out . println ( offset + \": \" + dataHeaderFlyweight . toString ( ) ) ; final int frameLength = dataHeaderFlyweight . frameLength ( ) ; if ( frameLength < DataHeaderFlyweight . HEADER_LENGTH ) { break ; } final int limit = min ( frameLength - HEADER_LENGTH , messageDumpLimit ) ; out . println ( LogInspector . formatBytes ( buffer , offset + HEADER_LENGTH , limit ) ) ; offset += BitUtil . align ( frameLength , FrameDescriptor . FRAME_ALIGNMENT ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the information for an available image to stdout . [CODESPLIT] public static void eventAvailableImage ( final Image image ) { final Subscription subscription = image . subscription ( ) ; System . out . format ( \"new image on %s streamId %x sessionId %x from %s%n\" , subscription . channel ( ) , subscription . streamId ( ) , image . sessionId ( ) , image . sourceIdentity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This handler is called when image is unavailable [CODESPLIT] public static void eventUnavailableImage ( final Image image ) { final Subscription subscription = image . subscription ( ) ; System . out . format ( \"inactive image on %s streamId %d sessionId %x%n\" , subscription . channel ( ) , subscription . streamId ( ) , image . sessionId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a reusable parameterized { @link FragmentHandler } that prints to stdout for the first stream ( STREAM ) [CODESPLIT] public static FragmentHandler reassembledStringMessage1 ( final int streamId ) { return ( buffer , offset , length , header ) -> { final byte [ ] data = new byte [ length ] ; buffer . getBytes ( offset , data ) ; System . out . format ( \"message to stream %d from session %x term id %x term offset %d (%d@%d)%n\" , streamId , header . sessionId ( ) , header . termId ( ) , header . termOffset ( ) , length , offset ) ; if ( length != 10000 ) { System . out . format ( \"Received message was not assembled properly;\" + \" received length was %d, but was expecting 10000%n\" , length ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the controllable idle strategy { @link StatusIndicator } . [CODESPLIT] public static StatusIndicator controllableIdleStrategy ( final CountersReader countersReader ) { StatusIndicator statusIndicator = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , label ) -> { if ( counterId == SystemCounterDescriptor . CONTROLLABLE_IDLE_STRATEGY . id ( ) && label . equals ( SystemCounterDescriptor . CONTROLLABLE_IDLE_STRATEGY . label ( ) ) ) { id . value = counterId ; } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusIndicator = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusIndicator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the read - only status indicator for the given send channel URI . [CODESPLIT] public static StatusIndicatorReader sendChannelStatus ( final CountersReader countersReader , final String channel ) { StatusIndicatorReader statusReader = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( typeId == SendChannelStatus . SEND_CHANNEL_STATUS_TYPE_ID ) { if ( channel . startsWith ( keyBuffer . getStringAscii ( ChannelEndpointStatus . CHANNEL_OFFSET ) ) ) { id . value = counterId ; } } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusReader = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusReader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the read - only status indicator for the given receive channel URI . [CODESPLIT] public static StatusIndicatorReader receiveChannelStatus ( final CountersReader countersReader , final String channel ) { StatusIndicatorReader statusReader = null ; final MutableInteger id = new MutableInteger ( - 1 ) ; countersReader . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( typeId == ReceiveChannelStatus . RECEIVE_CHANNEL_STATUS_TYPE_ID ) { if ( channel . startsWith ( keyBuffer . getStringAscii ( ChannelEndpointStatus . CHANNEL_OFFSET ) ) ) { id . value = counterId ; } } } ) ; if ( Aeron . NULL_VALUE != id . value ) { statusReader = new UnsafeBufferStatusIndicator ( countersReader . valuesBuffer ( ) , id . value ) ; } return statusReader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this limit for this buffer as the position at which the next append operation will occur . [CODESPLIT] public void limit ( final int limit ) { if ( limit < 0 || limit >= buffer . capacity ( ) ) { throw new IllegalArgumentException ( \"limit outside range: capacity=\" + buffer . capacity ( ) + \" limit=\" + limit ) ; } this . limit = limit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a source buffer to the end of the internal buffer resizing the internal buffer as required . [CODESPLIT] public BufferBuilder append ( final DirectBuffer srcBuffer , final int srcOffset , final int length ) { ensureCapacity ( length ) ; buffer . putBytes ( limit , srcBuffer , srcOffset , length ) ; limit += length ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll for control response events . [CODESPLIT] public int poll ( ) { controlSessionId = - 1 ; correlationId = - 1 ; relevantId = - 1 ; templateId = - 1 ; errorMessage = null ; pollComplete = false ; return subscription . controlledPoll ( fragmentAssembler , fragmentLimit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map a new loss report in the Aeron directory for a given length . [CODESPLIT] public static MappedByteBuffer mapLossReport ( final String aeronDirectoryName , final int reportFileLength ) { return mapNewFile ( file ( aeronDirectoryName ) , reportFileLength , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The implementation of { @link ControlledFragmentHandler } that reassembles and forwards whole messages . [CODESPLIT] public Action onFragment ( final DirectBuffer buffer , final int offset , final int length , final Header header ) { final byte flags = header . flags ( ) ; Action action = Action . CONTINUE ; if ( ( flags & UNFRAGMENTED ) == UNFRAGMENTED ) { action = delegate . onFragment ( buffer , offset , length , header ) ; } else { if ( ( flags & BEGIN_FRAG_FLAG ) == BEGIN_FRAG_FLAG ) { builder . reset ( ) . append ( buffer , offset , length ) ; } else { final int limit = builder . limit ( ) ; builder . append ( buffer , offset , length ) ; if ( ( flags & END_FRAG_FLAG ) == END_FRAG_FLAG ) { final int msgLength = builder . limit ( ) ; action = delegate . onFragment ( builder . buffer ( ) , 0 , msgLength , header ) ; if ( Action . ABORT == action ) { builder . limit ( limit ) ; } else { builder . reset ( ) ; } } } } return action ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take a snapshot of all the counters and group them by streams . [CODESPLIT] public Map < StreamCompositeKey , List < StreamPosition > > snapshot ( ) { final Map < StreamCompositeKey , List < StreamPosition > > streams = new HashMap <> ( ) ; counters . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( ( typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID ) || typeId == SENDER_LIMIT_TYPE_ID || typeId == PER_IMAGE_TYPE_ID || typeId == PUBLISHER_POS_TYPE_ID ) { final StreamCompositeKey key = new StreamCompositeKey ( keyBuffer . getInt ( SESSION_ID_OFFSET ) , keyBuffer . getInt ( STREAM_ID_OFFSET ) , keyBuffer . getStringAscii ( CHANNEL_OFFSET ) ) ; final StreamPosition position = new StreamPosition ( keyBuffer . getLong ( REGISTRATION_ID_OFFSET ) , counters . getCounterValue ( counterId ) , typeId ) ; streams . computeIfAbsent ( key , ( ignore ) - > new ArrayList <> ( ) ) . add ( position ) ; } } ) ; return streams ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a snapshot of the stream positions to a { @link PrintStream } . <p > Each stream will be printed on its own line . [CODESPLIT] public int print ( final PrintStream out ) { final Map < StreamCompositeKey , List < StreamPosition > > streams = snapshot ( ) ; final StringBuilder builder = new StringBuilder ( ) ; for ( final Map . Entry < StreamCompositeKey , List < StreamPosition > > entry : streams . entrySet ( ) ) { builder . setLength ( 0 ) ; final StreamCompositeKey key = entry . getKey ( ) ; builder . append ( \"sessionId=\" ) . append ( key . sessionId ( ) ) . append ( \" streamId=\" ) . append ( key . streamId ( ) ) . append ( \" channel=\" ) . append ( key . channel ( ) ) . append ( \" :\" ) ; for ( final StreamPosition streamPosition : entry . getValue ( ) ) { builder . append ( ' ' ) . append ( labelName ( streamPosition . typeId ( ) ) ) . append ( ' ' ) . append ( streamPosition . id ( ) ) . append ( ' ' ) . append ( streamPosition . value ( ) ) ; } out . println ( builder ) ; } return streams . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a new randomized delay value in the units of { @code maxBackoffT }} . [CODESPLIT] public double generateNewOptimalDelay ( ) { final double x = uniformRandom ( randMax ) + baseX ; return constantT * Math . log ( x * factorT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public long onStatusMessage ( final StatusMessageFlyweight flyweight , final InetSocketAddress receiverAddress , final long senderLimit , final int initialTermId , final int positionBitsToShift , final long timeNs ) { final long position = computePosition ( flyweight . consumptionTermId ( ) , flyweight . consumptionTermOffset ( ) , positionBitsToShift , initialTermId ) ; lastPosition = Math . max ( lastPosition , position ) ; timeOfLastStatusMessage = timeNs ; return Math . max ( senderLimit , position + flyweight . receiverWindowLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public long onIdle ( final long timeNs , final long senderLimit , final long senderPosition , final boolean isEos ) { if ( isEos && shouldLinger ) { if ( lastPosition >= senderPosition || ( ( timeOfLastStatusMessage + RECEIVER_TIMEOUT_NS ) - timeNs < 0 ) ) { shouldLinger = false ; } } return senderLimit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the poller to dispatch the descriptors returned from a query . [CODESPLIT] public void reset ( final long correlationId , final int recordCount , final RecordingDescriptorConsumer consumer ) { this . correlationId = correlationId ; this . consumer = consumer ; this . remainingRecordCount = recordCount ; isDispatchComplete = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link LossReport } contained in the buffer . This can be done concurrently . [CODESPLIT] public static int read ( final AtomicBuffer buffer , final EntryConsumer entryConsumer ) { final int capacity = buffer . capacity ( ) ; int recordsRead = 0 ; int offset = 0 ; while ( offset < capacity ) { final long observationCount = buffer . getLongVolatile ( offset + OBSERVATION_COUNT_OFFSET ) ; if ( observationCount <= 0 ) { break ; } ++ recordsRead ; final String channel = buffer . getStringAscii ( offset + CHANNEL_OFFSET ) ; final String source = buffer . getStringAscii ( offset + CHANNEL_OFFSET + SIZE_OF_INT + channel . length ( ) ) ; entryConsumer . accept ( observationCount , buffer . getLong ( offset + TOTAL_BYTES_LOST_OFFSET ) , buffer . getLong ( offset + FIRST_OBSERVATION_OFFSET ) , buffer . getLong ( offset + LAST_OBSERVATION_OFFSET ) , buffer . getInt ( offset + SESSION_ID_OFFSET ) , buffer . getInt ( offset + STREAM_ID_OFFSET ) , channel , source ) ; final int recordLength = CHANNEL_OFFSET + ( SIZE_OF_INT * 2 ) + channel . length ( ) + source . length ( ) ; offset += BitUtil . align ( recordLength , ENTRY_ALIGNMENT ) ; } return recordsRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an initialised default Data Frame Header . [CODESPLIT] public static UnsafeBuffer createDefaultHeader ( final int sessionId , final int streamId , final int termId ) { final UnsafeBuffer buffer = new UnsafeBuffer ( BufferUtil . allocateDirectAligned ( HEADER_LENGTH , CACHE_LINE_LENGTH ) ) ; buffer . putByte ( VERSION_FIELD_OFFSET , CURRENT_VERSION ) ; buffer . putByte ( FLAGS_FIELD_OFFSET , ( byte ) BEGIN_AND_END_FLAGS ) ; buffer . putShort ( TYPE_FIELD_OFFSET , ( short ) HDR_TYPE_DATA , LITTLE_ENDIAN ) ; buffer . putInt ( SESSION_ID_FIELD_OFFSET , sessionId , LITTLE_ENDIAN ) ; buffer . putInt ( STREAM_ID_FIELD_OFFSET , streamId , LITTLE_ENDIAN ) ; buffer . putInt ( TERM_ID_FIELD_OFFSET , termId , LITTLE_ENDIAN ) ; buffer . putLong ( RESERVED_VALUE_OFFSET , DEFAULT_RESERVE_VALUE ) ; return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill the key buffer . [CODESPLIT] public CounterMessageFlyweight keyBuffer ( final DirectBuffer keyBuffer , final int keyOffset , final int keyLength ) { buffer . putInt ( KEY_LENGTH_OFFSET , keyLength ) ; if ( null != keyBuffer && keyLength > 0 ) { buffer . putBytes ( keyBufferOffset ( ) , keyBuffer , keyOffset , keyLength ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill the label buffer . [CODESPLIT] public CounterMessageFlyweight labelBuffer ( final DirectBuffer labelBuffer , final int labelOffset , final int labelLength ) { buffer . putInt ( labelOffset ( ) , labelLength ) ; buffer . putBytes ( labelBufferOffset ( ) , labelBuffer , labelOffset , labelLength ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll the { @link Image } s under the subscription for available message fragments . <p > Each fragment read will be a whole message if it is under MTU length . If larger than MTU then it will come as a series of fragments ordered within a session . <p > To assemble messages that span multiple fragments then use { @link FragmentAssembler } . [CODESPLIT] public int poll ( final FragmentHandler fragmentHandler , final int fragmentLimit ) { final Image [ ] images = this . images ; final int length = images . length ; int fragmentsRead = 0 ; int startingIndex = roundRobinIndex ++ ; if ( startingIndex >= length ) { roundRobinIndex = startingIndex = 0 ; } for ( int i = startingIndex ; i < length && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . poll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } for ( int i = 0 ; i < startingIndex && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . poll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } return fragmentsRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll in a controlled manner the { @link Image } s under the subscription for available message fragments . Control is applied to fragments in the stream . If more fragments can be read on another stream they will even if BREAK or ABORT is returned from the fragment handler . <p > Each fragment read will be a whole message if it is under MTU length . If larger than MTU then it will come as a series of fragments ordered within a session . <p > To assemble messages that span multiple fragments then use { @link ControlledFragmentAssembler } . [CODESPLIT] public int controlledPoll ( final ControlledFragmentHandler fragmentHandler , final int fragmentLimit ) { final Image [ ] images = this . images ; final int length = images . length ; int fragmentsRead = 0 ; int startingIndex = roundRobinIndex ++ ; if ( startingIndex >= length ) { roundRobinIndex = startingIndex = 0 ; } for ( int i = startingIndex ; i < length && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . controlledPoll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } for ( int i = 0 ; i < startingIndex && fragmentsRead < fragmentLimit ; i ++ ) { fragmentsRead += images [ i ] . controlledPoll ( fragmentHandler , fragmentLimit - fragmentsRead ) ; } return fragmentsRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll the { @link Image } s under the subscription for available message fragments in blocks . <p > This method is useful for operations like bulk archiving and messaging indexing . [CODESPLIT] public long blockPoll ( final BlockHandler blockHandler , final int blockLengthLimit ) { long bytesConsumed = 0 ; for ( final Image image : images ) { bytesConsumed += image . blockPoll ( blockHandler , blockLengthLimit ) ; } return bytesConsumed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll the { @link Image } s under the subscription for available message fragments in blocks . <p > This method is useful for operations like bulk archiving a stream to file . [CODESPLIT] public long rawPoll ( final RawBlockHandler rawBlockHandler , final int blockLengthLimit ) { long bytesConsumed = 0 ; for ( final Image image : images ) { bytesConsumed += image . rawPoll ( rawBlockHandler , blockLengthLimit ) ; } return bytesConsumed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the { @link Image } associated with the given sessionId . [CODESPLIT] public Image imageBySessionId ( final int sessionId ) { Image result = null ; for ( final Image image : images ) { if ( sessionId == image . sessionId ( ) ) { result = image ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate over the { @link Image } s for this subscription . [CODESPLIT] public void forEachImage ( final Consumer < Image > consumer ) { for ( final Image image : images ) { consumer . accept ( image ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch a new { @link ArchivingMediaDriver } with provided contexts . [CODESPLIT] public static ArchivingMediaDriver launch ( final MediaDriver . Context driverCtx , final Archive . Context archiveCtx ) { final MediaDriver driver = MediaDriver . launch ( driverCtx ) ; final Archive archive = Archive . launch ( archiveCtx . mediaDriverAgentInvoker ( driver . sharedAgentInvoker ( ) ) . errorHandler ( driverCtx . errorHandler ( ) ) . errorCounter ( driverCtx . systemCounters ( ) . get ( SystemCounterDescriptor . ERRORS ) ) ) ; return new ArchivingMediaDriver ( driver , archive ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////// [CODESPLIT] public static boolean originalChannelContains ( final RecordingDescriptorDecoder descriptorDecoder , final byte [ ] channelFragment ) { final int fragmentLength = channelFragment . length ; if ( fragmentLength == 0 ) { return true ; } final int limit = descriptorDecoder . limit ( ) ; final int strippedChannelLength = descriptorDecoder . strippedChannelLength ( ) ; final int originalChannelOffset = limit + RecordingDescriptorDecoder . strippedChannelHeaderLength ( ) + strippedChannelLength ; descriptorDecoder . limit ( originalChannelOffset ) ; final int channelLength = descriptorDecoder . originalChannelLength ( ) ; descriptorDecoder . limit ( limit ) ; final DirectBuffer buffer = descriptorDecoder . buffer ( ) ; int offset = descriptorDecoder . offset ( ) + descriptorDecoder . sbeBlockLength ( ) + RecordingDescriptorDecoder . strippedChannelHeaderLength ( ) + strippedChannelLength + RecordingDescriptorDecoder . originalChannelHeaderLength ( ) ; nextChar : for ( int end = offset + ( channelLength - fragmentLength ) ; offset <= end ; offset ++ ) { for ( int i = 0 ; i < fragmentLength ; i ++ ) { if ( buffer . getByte ( offset + i ) != channelFragment [ i ] ) { continue nextChar ; } } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On catalog load we verify entries are in coherent state and attempt to recover entries data where untimely termination of recording has resulted in an unaccounted for stopPosition / stopTimestamp . This operation may be expensive for large catalogs . [CODESPLIT] private void refreshCatalog ( final boolean fixOnRefresh ) { if ( fixOnRefresh ) { forEach ( this :: refreshAndFixDescriptor ) ; } else { forEach ( ( ( headerEncoder , headerDecoder , descriptorEncoder , descriptorDecoder ) -> nextRecordingId ++ ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Claim length of a the term buffer for writing in the message with zero copy semantics . [CODESPLIT] public int claim ( final HeaderWriter header , final int length , final BufferClaim bufferClaim , final int activeTermId ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( alignedLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + alignedLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { final int frameOffset = ( int ) termOffset ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; bufferClaim . wrap ( termBuffer , frameOffset , frameLength ) ; } return ( int ) resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append an unfragmented message to the the term buffer . [CODESPLIT] public int appendUnfragmentedMessage ( final HeaderWriter header , final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final ReservedValueSupplier reservedValueSupplier , final int activeTermId ) { final int frameLength = lengthOne + lengthTwo + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( alignedLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + alignedLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { final int frameOffset = ( int ) termOffset ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; termBuffer . putBytes ( frameOffset + HEADER_LENGTH , bufferOne , offsetOne , lengthOne ) ; termBuffer . putBytes ( frameOffset + HEADER_LENGTH + lengthOne , bufferTwo , offsetTwo , lengthTwo ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; } return ( int ) resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append an unfragmented message to the the term buffer . [CODESPLIT] public int appendUnfragmentedMessage ( final HeaderWriter header , final DirectBuffer buffer , final int offset , final int length , final ReservedValueSupplier reservedValueSupplier , final int activeTermId ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( alignedLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + alignedLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { final int frameOffset = ( int ) termOffset ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; termBuffer . putBytes ( frameOffset + HEADER_LENGTH , buffer , offset , length ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; } return ( int ) resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a fragmented message to the the term buffer . The message will be split up into fragments of MTU length minus header . [CODESPLIT] public int appendFragmentedMessage ( final HeaderWriter header , final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final int maxPayloadLength , final ReservedValueSupplier reservedValueSupplier , final int activeTermId ) { final int length = lengthOne + lengthTwo ; final int numMaxPayloads = length / maxPayloadLength ; final int remainingPayload = length % maxPayloadLength ; final int lastFrameLength = remainingPayload > 0 ? align ( remainingPayload + HEADER_LENGTH , FRAME_ALIGNMENT ) : 0 ; final int requiredLength = ( numMaxPayloads * ( maxPayloadLength + HEADER_LENGTH ) ) + lastFrameLength ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; final long rawTail = getAndAddRawTail ( requiredLength ) ; final int termId = termId ( rawTail ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; checkTerm ( activeTermId , termId ) ; long resultingOffset = termOffset + requiredLength ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { int frameOffset = ( int ) termOffset ; byte flags = BEGIN_FRAG_FLAG ; int remaining = length ; int positionOne = 0 ; int positionTwo = 0 ; do { final int bytesToWrite = Math . min ( remaining , maxPayloadLength ) ; final int frameLength = bytesToWrite + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; int bytesWritten = 0 ; int payloadOffset = frameOffset + HEADER_LENGTH ; do { final int remainingOne = lengthOne - positionOne ; if ( remainingOne > 0 ) { final int numBytes = Math . min ( bytesToWrite - bytesWritten , remainingOne ) ; termBuffer . putBytes ( payloadOffset , bufferOne , offsetOne + positionOne , numBytes ) ; bytesWritten += numBytes ; payloadOffset += numBytes ; positionOne += numBytes ; } else { final int numBytes = Math . min ( bytesToWrite - bytesWritten , lengthTwo - positionTwo ) ; termBuffer . putBytes ( payloadOffset , bufferTwo , offsetTwo + positionTwo , numBytes ) ; bytesWritten += numBytes ; payloadOffset += numBytes ; positionTwo += numBytes ; } } while ( bytesWritten < bytesToWrite ) ; if ( remaining <= maxPayloadLength ) { flags |= END_FRAG_FLAG ; } frameFlags ( termBuffer , frameOffset , flags ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; flags = 0 ; frameOffset += alignedLength ; remaining -= bytesToWrite ; } while ( remaining > 0 ) ; } return ( int ) resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connect to an archive on its control interface providing the response stream details . [CODESPLIT] public boolean connect ( final String responseChannel , final int responseStreamId , final long correlationId ) { connectRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . correlationId ( correlationId ) . responseStreamId ( responseStreamId ) . version ( AeronArchive . Configuration . SEMANTIC_VERSION ) . responseChannel ( responseChannel ) ; return offerWithTimeout ( connectRequestEncoder . encodedLength ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try Connect to an archive on its control interface providing the response stream details . Only one attempt will be made to offer the request . [CODESPLIT] public boolean tryConnect ( final String responseChannel , final int responseStreamId , final long correlationId ) { connectRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . correlationId ( correlationId ) . responseStreamId ( responseStreamId ) . version ( AeronArchive . Configuration . SEMANTIC_VERSION ) . responseChannel ( responseChannel ) ; final int length = MessageHeaderEncoder . ENCODED_LENGTH + connectRequestEncoder . encodedLength ( ) ; return publication . offer ( buffer , 0 , length ) > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close this control session with the archive . [CODESPLIT] public boolean closeSession ( final long controlSessionId ) { closeSessionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) ; return offer ( closeSessionRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start recording streams for a given channel and stream id pairing . [CODESPLIT] public boolean startRecording ( final String channel , final int streamId , final SourceLocation sourceLocation , final long correlationId , final long controlSessionId ) { startRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . streamId ( streamId ) . sourceLocation ( sourceLocation ) . channel ( channel ) ; return offer ( startRecordingRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop an active recording . [CODESPLIT] public boolean stopRecording ( final String channel , final int streamId , final long correlationId , final long controlSessionId ) { stopRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . streamId ( streamId ) . channel ( channel ) ; return offer ( stopRecordingRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop an active recording by the { @link Subscription#registrationId () } it was registered with . [CODESPLIT] public boolean stopRecording ( final long subscriptionId , final long correlationId , final long controlSessionId ) { stopRecordingSubscriptionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . subscriptionId ( subscriptionId ) ; return offer ( stopRecordingSubscriptionRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replay a recording from a given position . [CODESPLIT] public boolean replay ( final long recordingId , final long position , final long length , final String replayChannel , final int replayStreamId , final long correlationId , final long controlSessionId ) { replayRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) . position ( position ) . length ( length ) . replayStreamId ( replayStreamId ) . replayChannel ( replayChannel ) ; return offer ( replayRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop an existing replay session . [CODESPLIT] public boolean stopReplay ( final long replaySessionId , final long correlationId , final long controlSessionId ) { stopReplayRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . replaySessionId ( replaySessionId ) ; return offer ( replayRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List a range of recording descriptors . [CODESPLIT] public boolean listRecordings ( final long fromRecordingId , final int recordCount , final long correlationId , final long controlSessionId ) { listRecordingsRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . fromRecordingId ( fromRecordingId ) . recordCount ( recordCount ) ; return offer ( listRecordingsRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List a range of recording descriptors which match a channel URI fragment and stream id . [CODESPLIT] public boolean listRecordingsForUri ( final long fromRecordingId , final int recordCount , final String channelFragment , final int streamId , final long correlationId , final long controlSessionId ) { listRecordingsForUriRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . fromRecordingId ( fromRecordingId ) . recordCount ( recordCount ) . streamId ( streamId ) . channel ( channelFragment ) ; return offer ( listRecordingsForUriRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List a recording descriptor for a given recording id . [CODESPLIT] public boolean listRecording ( final long recordingId , final long correlationId , final long controlSessionId ) { listRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) ; return offer ( listRecordingRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend an existing non - active recorded stream for a the same channel and stream id . [CODESPLIT] public boolean extendRecording ( final String channel , final int streamId , final SourceLocation sourceLocation , final long recordingId , final long correlationId , final long controlSessionId ) { extendRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) . streamId ( streamId ) . sourceLocation ( sourceLocation ) . channel ( channel ) ; return offer ( extendRecordingRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the recorded position of an active recording . [CODESPLIT] public boolean getRecordingPosition ( final long recordingId , final long correlationId , final long controlSessionId ) { recordingPositionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) ; return offer ( recordingPositionRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Truncate a stopped recording to a given position that is less than the stopped position . The provided position must be on a fragment boundary . Truncating a recording to the start position effectively deletes the recording . [CODESPLIT] public boolean truncateRecording ( final long recordingId , final long position , final long correlationId , final long controlSessionId ) { truncateRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) . position ( position ) ; return offer ( truncateRecordingRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the stop position of a recording . [CODESPLIT] public boolean getStopPosition ( final long recordingId , final long correlationId , final long controlSessionId ) { stopPositionRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . recordingId ( recordingId ) ; return offer ( stopPositionRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the last recording that matches the given criteria . [CODESPLIT] public boolean findLastMatchingRecording ( final long minRecordingId , final String channelFragment , final int streamId , final int sessionId , final long correlationId , final long controlSessionId ) { findLastMatchingRecordingRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . minRecordingId ( minRecordingId ) . sessionId ( sessionId ) . streamId ( streamId ) . channel ( channelFragment ) ; return offer ( findLastMatchingRecordingRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List registered subscriptions in the archive which have been used to record streams . [CODESPLIT] public boolean listRecordingSubscriptions ( final int pseudoIndex , final int subscriptionCount , final String channelFragment , final int streamId , final boolean applyStreamId , final long correlationId , final long controlSessionId ) { listRecordingSubscriptionsRequestEncoder . wrapAndApplyHeader ( buffer , 0 , messageHeaderEncoder ) . controlSessionId ( controlSessionId ) . correlationId ( correlationId ) . pseudoIndex ( pseudoIndex ) . subscriptionCount ( subscriptionCount ) . applyStreamId ( applyStreamId ? BooleanType . TRUE : BooleanType . FALSE ) . streamId ( streamId ) . channel ( channelFragment ) ; return offer ( listRecordingSubscriptionsRequestEncoder . encodedLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse channel URI and create a { @link UdpChannel } . [CODESPLIT] @ SuppressWarnings ( \"MethodLength\" ) public static UdpChannel parse ( final String channelUriString ) { try { final ChannelUri channelUri = ChannelUri . parse ( channelUriString ) ; validateConfiguration ( channelUri ) ; InetSocketAddress endpointAddress = getEndpointAddress ( channelUri ) ; final InetSocketAddress explicitControlAddress = getExplicitControlAddress ( channelUri ) ; final String tagIdStr = channelUri . channelTag ( ) ; final String controlMode = channelUri . get ( CommonContext . MDC_CONTROL_MODE_PARAM_NAME ) ; final boolean hasNoDistinguishingCharacteristic = null == endpointAddress && null == explicitControlAddress && null == tagIdStr ; if ( hasNoDistinguishingCharacteristic && null == controlMode ) { throw new IllegalArgumentException ( \"Aeron URIs for UDP must specify an endpoint address, control address, tag-id, or control-mode\" ) ; } if ( null != endpointAddress && endpointAddress . isUnresolved ( ) ) { throw new UnknownHostException ( \"could not resolve endpoint address: \" + endpointAddress ) ; } if ( null != explicitControlAddress && explicitControlAddress . isUnresolved ( ) ) { throw new UnknownHostException ( \"could not resolve control address: \" + explicitControlAddress ) ; } final Context context = new Context ( ) . uriStr ( channelUriString ) . channelUri ( channelUri ) . hasNoDistinguishingCharacteristic ( hasNoDistinguishingCharacteristic ) ; if ( null != tagIdStr ) { context . hasTagId ( true ) . tagId ( Long . parseLong ( tagIdStr ) ) ; } if ( null == endpointAddress ) { endpointAddress = new InetSocketAddress ( \"0.0.0.0\" , 0 ) ; } if ( endpointAddress . getAddress ( ) . isMulticastAddress ( ) ) { final InetSocketAddress controlAddress = getMulticastControlAddress ( endpointAddress ) ; final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress ( channelUri ) ; final NetworkInterface localInterface = findInterface ( searchAddress ) ; final InetSocketAddress resolvedAddress = resolveToAddressOfInterface ( localInterface , searchAddress ) ; context . isMulticast ( true ) . localControlAddress ( resolvedAddress ) . remoteControlAddress ( controlAddress ) . localDataAddress ( resolvedAddress ) . remoteDataAddress ( endpointAddress ) . localInterface ( localInterface ) . protocolFamily ( getProtocolFamily ( endpointAddress . getAddress ( ) ) ) . canonicalForm ( canonicalise ( resolvedAddress , endpointAddress ) ) ; final String ttlValue = channelUri . get ( CommonContext . TTL_PARAM_NAME ) ; if ( null != ttlValue ) { context . hasMulticastTtl ( true ) . multicastTtl ( Integer . parseInt ( ttlValue ) ) ; } } else if ( null != explicitControlAddress ) { context . hasExplicitControl ( true ) . remoteControlAddress ( endpointAddress ) . remoteDataAddress ( endpointAddress ) . localControlAddress ( explicitControlAddress ) . localDataAddress ( explicitControlAddress ) . protocolFamily ( getProtocolFamily ( endpointAddress . getAddress ( ) ) ) . canonicalForm ( canonicalise ( explicitControlAddress , endpointAddress ) ) ; } else { final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress ( channelUri ) ; final InetSocketAddress localAddress = searchAddress . getInetAddress ( ) . isAnyLocalAddress ( ) ? searchAddress . getAddress ( ) : resolveToAddressOfInterface ( findInterface ( searchAddress ) , searchAddress ) ; final String uniqueCanonicalFormSuffix = hasNoDistinguishingCharacteristic ? ( \"-\" + UNIQUE_CANONICAL_FORM_VALUE . getAndAdd ( 1 ) ) : \"\" ; context . remoteControlAddress ( endpointAddress ) . remoteDataAddress ( endpointAddress ) . localControlAddress ( localAddress ) . localDataAddress ( localAddress ) . protocolFamily ( getProtocolFamily ( endpointAddress . getAddress ( ) ) ) . canonicalForm ( canonicalise ( localAddress , endpointAddress ) + uniqueCanonicalFormSuffix ) ; } return new UdpChannel ( context ) ; } catch ( final Exception ex ) { throw new InvalidChannelException ( ErrorCode . INVALID_CHANNEL , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a string which is a canonical form of the channel suitable for use as a file or directory name and also as a method of hashing etc . <p > A canonical form : <ul > <li > begins with the string UDP - < / li > <li > has all addresses converted to hexadecimal< / li > <li > uses - as all field separators< / li > < / ul > <p > The general format is : UDP - interface - localPort - remoteAddress - remotePort [CODESPLIT] public static String canonicalise ( final InetSocketAddress localData , final InetSocketAddress remoteData ) { final StringBuilder builder = new StringBuilder ( 48 ) ; builder . append ( \"UDP-\" ) ; toHex ( builder , localData . getAddress ( ) . getAddress ( ) ) . append ( ' ' ) . append ( localData . getPort ( ) ) ; builder . append ( ' ' ) ; toHex ( builder , remoteData . getAddress ( ) . getAddress ( ) ) . append ( ' ' ) . append ( remoteData . getPort ( ) ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this channel have a tag match to another channel including endpoints . [CODESPLIT] public boolean matchesTag ( final UdpChannel udpChannel ) { if ( ! hasTag || ! udpChannel . hasTag ( ) || tag != udpChannel . tag ( ) ) { return false ; } if ( udpChannel . remoteData ( ) . getAddress ( ) . isAnyLocalAddress ( ) && udpChannel . remoteData ( ) . getPort ( ) == 0 && udpChannel . localData ( ) . getAddress ( ) . isAnyLocalAddress ( ) && udpChannel . localData ( ) . getPort ( ) == 0 ) { return true ; } throw new IllegalArgumentException ( \"matching tag has set endpoint or control address\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the endpoint address from the URI . [CODESPLIT] public static InetSocketAddress destinationAddress ( final ChannelUri uri ) { try { validateConfiguration ( uri ) ; return getEndpointAddress ( uri ) ; } catch ( final Exception ex ) { throw new InvalidChannelException ( ErrorCode . INVALID_CHANNEL , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used for debugging to get a human readable description of the channel . [CODESPLIT] public String description ( ) { final StringBuilder builder = new StringBuilder ( \"UdpChannel - \" ) ; if ( null != localInterface ) { builder . append ( \"interface: \" ) . append ( localInterface . getDisplayName ( ) ) . append ( \", \" ) ; } builder . append ( \"localData: \" ) . append ( localData ) . append ( \", remoteData: \" ) . append ( remoteData ) . append ( \", ttl: \" ) . append ( multicastTtl ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void close ( ) { hwmPosition . close ( ) ; rebuildPosition . close ( ) ; for ( final ReadablePosition position : subscriberPositions ) { position . close ( ) ; } for ( int i = 0 , size = untetheredSubscriptions . size ( ) ; i < size ; i ++ ) { final UntetheredSubscription untetheredSubscription = untetheredSubscriptions . get ( i ) ; if ( UntetheredSubscription . RESTING == untetheredSubscription . state ) { untetheredSubscription . position . close ( ) ; } } congestionControl . close ( ) ; rawLog . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void addSubscriber ( final SubscriptionLink subscriptionLink , final ReadablePosition subscriberPosition ) { subscriberPositions = ArrayUtil . add ( subscriberPositions , subscriberPosition ) ; if ( ! subscriptionLink . isTether ( ) ) { untetheredSubscriptions . add ( new UntetheredSubscription ( subscriptionLink , subscriberPosition , timeOfLastStatusMessageScheduleNs ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void removeSubscriber ( final SubscriptionLink subscriptionLink , final ReadablePosition subscriberPosition ) { subscriberPositions = ArrayUtil . remove ( subscriberPositions , subscriberPosition ) ; subscriberPosition . close ( ) ; if ( ! subscriptionLink . isTether ( ) ) { for ( int lastIndex = untetheredSubscriptions . size ( ) - 1 , i = lastIndex ; i >= 0 ; i -- ) { if ( untetheredSubscriptions . get ( i ) . subscriptionLink == subscriptionLink ) { ArrayListUtil . fastUnorderedRemove ( untetheredSubscriptions , i , lastIndex ) ; break ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from the { @link LossDetector } when gap is detected by the { @link DriverConductor } thread . [CODESPLIT] public void onGapDetected ( final int termId , final int termOffset , final int length ) { final long changeNumber = beginLossChange + 1 ; beginLossChange = changeNumber ; lossTermId = termId ; lossTermOffset = termOffset ; lossLength = length ; endLossChange = changeNumber ; if ( null != reportEntry ) { reportEntry . recordObservation ( length , cachedEpochClock . time ( ) ) ; } else if ( null != lossReport ) { reportEntry = lossReport . createEntry ( length , cachedEpochClock . time ( ) , sessionId , streamId , channel ( ) , sourceAddress . toString ( ) ) ; if ( null == reportEntry ) { lossReport = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a destination to this image so it can merge streams . [CODESPLIT] void addDestination ( final int transportIndex , final ReceiveDestinationUdpTransport transport ) { imageConnections = ArrayUtil . ensureCapacity ( imageConnections , transportIndex + 1 ) ; if ( transport . isMulticast ( ) ) { imageConnections [ transportIndex ] = new ImageConnection ( cachedNanoClock . nanoTime ( ) , transport . udpChannel ( ) . remoteControl ( ) ) ; } else if ( transport . hasExplicitControl ( ) ) { imageConnections [ transportIndex ] = new ImageConnection ( cachedNanoClock . nanoTime ( ) , transport . explicitControlAddress ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from the { @link DriverConductor } . [CODESPLIT] final void trackRebuild ( final long nowNs , final long statusMessageTimeoutNs ) { long minSubscriberPosition = Long . MAX_VALUE ; long maxSubscriberPosition = Long . MIN_VALUE ; for ( final ReadablePosition subscriberPosition : subscriberPositions ) { final long position = subscriberPosition . getVolatile ( ) ; minSubscriberPosition = Math . min ( minSubscriberPosition , position ) ; maxSubscriberPosition = Math . max ( maxSubscriberPosition , position ) ; } final long rebuildPosition = Math . max ( this . rebuildPosition . get ( ) , maxSubscriberPosition ) ; final long hwmPosition = this . hwmPosition . getVolatile ( ) ; final long scanOutcome = lossDetector . scan ( termBuffers [ indexByPosition ( rebuildPosition , positionBitsToShift ) ] , rebuildPosition , hwmPosition , nowNs , termLengthMask , positionBitsToShift , initialTermId ) ; final int rebuildTermOffset = ( int ) rebuildPosition & termLengthMask ; final long newRebuildPosition = ( rebuildPosition - rebuildTermOffset ) + rebuildOffset ( scanOutcome ) ; this . rebuildPosition . proposeMaxOrdered ( newRebuildPosition ) ; final long ccOutcome = congestionControl . onTrackRebuild ( nowNs , minSubscriberPosition , nextSmPosition , hwmPosition , rebuildPosition , newRebuildPosition , lossFound ( scanOutcome ) ) ; final int windowLength = CongestionControl . receiverWindowLength ( ccOutcome ) ; final int threshold = CongestionControl . threshold ( windowLength ) ; if ( CongestionControl . shouldForceStatusMessage ( ccOutcome ) || ( ( timeOfLastStatusMessageScheduleNs + statusMessageTimeoutNs ) - nowNs < 0 ) || ( minSubscriberPosition > ( nextSmPosition + threshold ) ) ) { scheduleStatusMessage ( nowNs , minSubscriberPosition , windowLength ) ; cleanBufferTo ( minSubscriberPosition - ( termLengthMask + 1 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert frame into term buffer . [CODESPLIT] int insertPacket ( final int termId , final int termOffset , final UnsafeBuffer buffer , final int length , final int transportIndex , final InetSocketAddress srcAddress ) { final boolean isHeartbeat = DataHeaderFlyweight . isHeartbeat ( buffer , length ) ; final long packetPosition = computePosition ( termId , termOffset , positionBitsToShift , initialTermId ) ; final long proposedPosition = isHeartbeat ? packetPosition : packetPosition + length ; if ( ! isFlowControlUnderRun ( packetPosition ) && ! isFlowControlOverRun ( proposedPosition ) ) { trackConnection ( transportIndex , srcAddress , lastPacketTimestampNs ) ; if ( isHeartbeat ) { if ( DataHeaderFlyweight . isEndOfStream ( buffer ) && ! isEndOfStream && allEos ( transportIndex ) ) { LogBufferDescriptor . endOfStreamPosition ( rawLog . metaData ( ) , proposedPosition ) ; isEndOfStream = true ; } heartbeatsReceived . incrementOrdered ( ) ; } else { final UnsafeBuffer termBuffer = termBuffers [ indexByPosition ( packetPosition , positionBitsToShift ) ] ; TermRebuilder . insert ( termBuffer , termOffset , buffer , length ) ; } lastPacketTimestampNs = cachedNanoClock . nanoTime ( ) ; hwmPosition . proposeMaxOrdered ( proposedPosition ) ; } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be called from the { @link Receiver } to see if a image should be retained . [CODESPLIT] boolean hasActivityAndNotEndOfStream ( final long nowNs ) { boolean isActive = true ; if ( ( ( lastPacketTimestampNs + imageLivenessTimeoutNs ) - nowNs < 0 ) || ( isEndOfStream && rebuildPosition . getVolatile ( ) >= hwmPosition . get ( ) ) ) { isActive = false ; } return isActive ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from the { @link Receiver } to send any pending Status Messages . [CODESPLIT] int sendPendingStatusMessage ( ) { int workCount = 0 ; if ( ACTIVE == state ) { final long changeNumber = endSmChange ; if ( changeNumber != lastSmChangeNumber ) { final long smPosition = nextSmPosition ; final int receiverWindowLength = nextSmReceiverWindowLength ; UNSAFE . loadFence ( ) ; if ( changeNumber == beginSmChange ) { final int termId = computeTermIdFromPosition ( smPosition , positionBitsToShift , initialTermId ) ; final int termOffset = ( int ) smPosition & termLengthMask ; channelEndpoint . sendStatusMessage ( imageConnections , sessionId , streamId , termId , termOffset , receiverWindowLength , ( byte ) 0 ) ; statusMessagesSent . incrementOrdered ( ) ; lastSmPosition = smPosition ; lastSmWindowLimit = smPosition + receiverWindowLength ; lastSmChangeNumber = changeNumber ; } workCount = 1 ; } } return workCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from the { @link Receiver } thread to processing any pending loss of packets . [CODESPLIT] int processPendingLoss ( ) { int workCount = 0 ; final long changeNumber = endLossChange ; if ( changeNumber != lastLossChangeNumber ) { final int termId = lossTermId ; final int termOffset = lossTermOffset ; final int length = lossLength ; UNSAFE . loadFence ( ) ; if ( changeNumber == beginLossChange ) { if ( isReliable ) { channelEndpoint . sendNakMessage ( imageConnections , sessionId , streamId , termId , termOffset , length ) ; nakMessagesSent . incrementOrdered ( ) ; } else { final UnsafeBuffer termBuffer = termBuffers [ indexByTerm ( initialTermId , termId ) ] ; if ( tryFillGap ( rawLog . metaData ( ) , termBuffer , termId , termOffset , length ) ) { lossGapFills . incrementOrdered ( ) ; } } lastLossChangeNumber = changeNumber ; } workCount = 1 ; } return workCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from the { @link Receiver } thread to check for initiating an RTT measurement . [CODESPLIT] int initiateAnyRttMeasurements ( final long nowNs ) { int workCount = 0 ; if ( congestionControl . shouldMeasureRtt ( nowNs ) ) { final long preciseTimeNs = nanoClock . nanoTime ( ) ; channelEndpoint . sendRttMeasurement ( imageConnections , sessionId , streamId , preciseTimeNs , 0 , true ) ; congestionControl . onRttMeasurementSent ( preciseTimeNs ) ; workCount = 1 ; } return workCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from the { @link Receiver } upon receiving an RTT Measurement that is a reply . [CODESPLIT] void onRttMeasurement ( final RttMeasurementFlyweight header , @ SuppressWarnings ( \"unused\" ) final int transportIndex , final InetSocketAddress srcAddress ) { final long nowNs = nanoClock . nanoTime ( ) ; final long rttInNs = nowNs - header . echoTimestampNs ( ) - header . receptionDelta ( ) ; congestionControl . onRttMeasurement ( nowNs , rttInNs , srcAddress ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onTimeEvent ( final long timeNs , final long timesMs , final DriverConductor conductor ) { switch ( state ) { case ACTIVE : checkUntetheredSubscriptions ( timeNs , conductor ) ; break ; case INACTIVE : if ( isDrained ( ) ) { state = State . LINGER ; timeOfLastStateChangeNs = timeNs ; conductor . transitionToLinger ( this ) ; } isTrackingRebuild = false ; break ; case LINGER : if ( ( timeOfLastStateChangeNs + imageLivenessTimeoutNs ) - timeNs < 0 ) { state = State . DONE ; conductor . cleanupImage ( this ) ; } break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map a { @link CountersReader } over the provided { @link File } for the CnC file . [CODESPLIT] public static CountersReader mapCounters ( final File cncFile ) { final MappedByteBuffer cncByteBuffer = IoUtil . mapExistingFile ( cncFile , \"cnc\" ) ; final DirectBuffer cncMetaData = createMetaDataBuffer ( cncByteBuffer ) ; final int cncVersion = cncMetaData . getInt ( cncVersionOffset ( 0 ) ) ; if ( CncFileDescriptor . CNC_VERSION != cncVersion ) { throw new AeronException ( \"Aeron CnC version does not match: version=\" + cncVersion + \" required=\" + CNC_VERSION ) ; } return new CountersReader ( createCountersMetaDataBuffer ( cncByteBuffer , cncMetaData ) , createCountersValuesBuffer ( cncByteBuffer , cncMetaData ) , StandardCharsets . US_ASCII ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the control toggle counter or return null if not found . [CODESPLIT] public static AtomicCounter findControlToggle ( final CountersReader counters ) { final AtomicBuffer buffer = counters . metaDataBuffer ( ) ; for ( int i = 0 , size = counters . maxCounterId ( ) ; i < size ; i ++ ) { final int recordOffset = CountersReader . metaDataOffset ( i ) ; if ( counters . getCounterState ( i ) == RECORD_ALLOCATED && buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == CONTROL_TOGGLE_TYPE_ID ) { return new AtomicCounter ( counters . valuesBuffer ( ) , i , null ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a key and value pair in the map of params . [CODESPLIT] public String put ( final String key , final String value ) { return params . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the channel tag if it exists that refers to an another channel . [CODESPLIT] public String channelTag ( ) { return ( null != tags && tags . length > CHANNEL_TAG_INDEX ) ? tags [ CHANNEL_TAG_INDEX ] : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the entity tag if it exists that refers to an entity such as subscription or publication . [CODESPLIT] public String entityTag ( ) { return ( null != tags && tags . length > ENTITY_TAG_INDEX ) ? tags [ ENTITY_TAG_INDEX ] : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialise a channel for restarting a publication at a given position . [CODESPLIT] public void initialPosition ( final long position , final int initialTermId , final int termLength ) { if ( position < 0 || 0 != ( position & ( FRAME_ALIGNMENT - 1 ) ) ) { throw new IllegalArgumentException ( \"invalid position: \" + position ) ; } final int bitsToShift = LogBufferDescriptor . positionBitsToShift ( termLength ) ; final int termId = LogBufferDescriptor . computeTermIdFromPosition ( position , bitsToShift , initialTermId ) ; final int termOffset = ( int ) ( position & ( termLength - 1 ) ) ; put ( INITIAL_TERM_ID_PARAM_NAME , Integer . toString ( initialTermId ) ) ; put ( TERM_ID_PARAM_NAME , Integer . toString ( termId ) ) ; put ( TERM_OFFSET_PARAM_NAME , Integer . toString ( termOffset ) ) ; put ( TERM_LENGTH_PARAM_NAME , Integer . toString ( termLength ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a { @link CharSequence } which contains an Aeron URI . [CODESPLIT] public static ChannelUri parse ( final CharSequence cs ) { int position = 0 ; final String prefix ; if ( startsWith ( cs , 0 , SPY_PREFIX ) ) { prefix = SPY_QUALIFIER ; position = SPY_PREFIX . length ( ) ; } else { prefix = \"\" ; } if ( ! startsWith ( cs , position , AERON_PREFIX ) ) { throw new IllegalArgumentException ( \"Aeron URIs must start with 'aeron:', found: '\" + cs + \"'\" ) ; } else { position += AERON_PREFIX . length ( ) ; } final StringBuilder builder = new StringBuilder ( ) ; final Map < String , String > params = new Object2ObjectHashMap <> ( ) ; String media = null ; String key = null ; State state = State . MEDIA ; for ( int i = position ; i < cs . length ( ) ; i ++ ) { final char c = cs . charAt ( i ) ; switch ( state ) { case MEDIA : switch ( c ) { case ' ' : media = builder . toString ( ) ; builder . setLength ( 0 ) ; state = State . PARAMS_KEY ; break ; case ' ' : throw new IllegalArgumentException ( \"encountered ':' within media definition\" ) ; default : builder . append ( c ) ; } break ; case PARAMS_KEY : if ( c == ' ' ) { key = builder . toString ( ) ; builder . setLength ( 0 ) ; state = State . PARAMS_VALUE ; } else { builder . append ( c ) ; } break ; case PARAMS_VALUE : if ( c == ' ' ) { params . put ( key , builder . toString ( ) ) ; builder . setLength ( 0 ) ; state = State . PARAMS_KEY ; } else { builder . append ( c ) ; } break ; default : throw new IllegalStateException ( \"unexpected state=\" + state ) ; } } switch ( state ) { case MEDIA : media = builder . toString ( ) ; break ; case PARAMS_VALUE : params . put ( key , builder . toString ( ) ) ; break ; default : throw new IllegalArgumentException ( \"no more input found, state=\" + state ) ; } return new ChannelUri ( prefix , media , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a sessionId to a given channel . [CODESPLIT] public static String addSessionId ( final String channel , final int sessionId ) { final ChannelUri channelUri = ChannelUri . parse ( channel ) ; channelUri . put ( CommonContext . SESSION_ID_PARAM_NAME , Integer . toString ( sessionId ) ) ; return channelUri . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of the tag from a given parameter value . [CODESPLIT] public static long getTag ( final String paramValue ) { return isTagged ( paramValue ) ? AsciiEncoding . parseLongAscii ( paramValue , 4 , paramValue . length ( ) - 4 ) : INVALID_TAG ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Claim length of a the term buffer for writing in the message with zero copy semantics . [CODESPLIT] public int claim ( final int termId , final int termOffset , final HeaderWriter header , final int length , final BufferClaim bufferClaim ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + alignedLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { header . write ( termBuffer , termOffset , frameLength , termId ) ; bufferClaim . wrap ( termBuffer , termOffset , frameLength ) ; } return resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pad a length of the term buffer with a padding record . [CODESPLIT] public int appendPadding ( final int termId , final int termOffset , final HeaderWriter header , final int length ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + alignedLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { header . write ( termBuffer , termOffset , frameLength , termId ) ; frameType ( termBuffer , termOffset , PADDING_FRAME_TYPE ) ; frameLengthOrdered ( termBuffer , termOffset , frameLength ) ; } return resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append an unfragmented message to the the term buffer . [CODESPLIT] public int appendUnfragmentedMessage ( final int termId , final int termOffset , final HeaderWriter header , final DirectBuffer srcBuffer , final int srcOffset , final int length , final ReservedValueSupplier reservedValueSupplier ) { final int frameLength = length + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + alignedLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { header . write ( termBuffer , termOffset , frameLength , termId ) ; termBuffer . putBytes ( termOffset + HEADER_LENGTH , srcBuffer , srcOffset , length ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , termOffset , frameLength ) ; termBuffer . putLong ( termOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , termOffset , frameLength ) ; } return resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a fragmented message to the the term buffer . The message will be split up into fragments of MTU length minus header . [CODESPLIT] public int appendFragmentedMessage ( final int termId , final int termOffset , final HeaderWriter header , final DirectBufferVector [ ] vectors , final int length , final int maxPayloadLength , final ReservedValueSupplier reservedValueSupplier ) { final int numMaxPayloads = length / maxPayloadLength ; final int remainingPayload = length % maxPayloadLength ; final int lastFrameLength = remainingPayload > 0 ? align ( remainingPayload + HEADER_LENGTH , FRAME_ALIGNMENT ) : 0 ; final int requiredLength = ( numMaxPayloads * ( maxPayloadLength + HEADER_LENGTH ) ) + lastFrameLength ; final UnsafeBuffer termBuffer = this . termBuffer ; final int termLength = termBuffer . capacity ( ) ; int resultingOffset = termOffset + requiredLength ; putRawTailOrdered ( termId , resultingOffset ) ; if ( resultingOffset > termLength ) { resultingOffset = handleEndOfLogCondition ( termBuffer , termOffset , header , termLength , termId ) ; } else { int frameOffset = termOffset ; byte flags = BEGIN_FRAG_FLAG ; int remaining = length ; int vectorIndex = 0 ; int vectorOffset = 0 ; do { final int bytesToWrite = Math . min ( remaining , maxPayloadLength ) ; final int frameLength = bytesToWrite + HEADER_LENGTH ; final int alignedLength = align ( frameLength , FRAME_ALIGNMENT ) ; header . write ( termBuffer , frameOffset , frameLength , termId ) ; int bytesWritten = 0 ; int payloadOffset = frameOffset + HEADER_LENGTH ; do { final DirectBufferVector vector = vectors [ vectorIndex ] ; final int vectorRemaining = vector . length - vectorOffset ; final int numBytes = Math . min ( bytesToWrite - bytesWritten , vectorRemaining ) ; termBuffer . putBytes ( payloadOffset , vector . buffer , vector . offset + vectorOffset , numBytes ) ; bytesWritten += numBytes ; payloadOffset += numBytes ; vectorOffset += numBytes ; if ( vectorRemaining <= numBytes ) { vectorIndex ++ ; vectorOffset = 0 ; } } while ( bytesWritten < bytesToWrite ) ; if ( remaining <= maxPayloadLength ) { flags |= END_FRAG_FLAG ; } frameFlags ( termBuffer , frameOffset , flags ) ; if ( null != reservedValueSupplier ) { final long reservedValue = reservedValueSupplier . get ( termBuffer , frameOffset , frameLength ) ; termBuffer . putLong ( frameOffset + RESERVED_VALUE_OFFSET , reservedValue , LITTLE_ENDIAN ) ; } frameLengthOrdered ( termBuffer , frameOffset , frameLength ) ; flags = 0 ; frameOffset += alignedLength ; remaining -= bytesToWrite ; } while ( remaining > 0 ) ; } return resultingOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the publishers limit for flow control as part of the conductor duty cycle . [CODESPLIT] final int updatePublisherLimit ( ) { int workCount = 0 ; final long senderPosition = this . senderPosition . getVolatile ( ) ; if ( hasReceivers || ( spiesSimulateConnection && spyPositions . length > 0 ) ) { long minConsumerPosition = senderPosition ; for ( final ReadablePosition spyPosition : spyPositions ) { minConsumerPosition = Math . min ( minConsumerPosition , spyPosition . getVolatile ( ) ) ; } final long proposedPublisherLimit = minConsumerPosition + termWindowLength ; if ( publisherLimit . proposeMaxOrdered ( proposedPublisherLimit ) ) { cleanBuffer ( proposedPublisherLimit ) ; workCount = 1 ; } } else if ( publisherLimit . get ( ) > senderPosition ) { publisherLimit . setOrdered ( senderPosition ) ; } return workCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for a list of network interfaces that match the specified address and subnet prefix . The results will be ordered by the length of the subnet prefix ( { @link InterfaceAddress#getNetworkPrefixLength () } ) . If no results match then the collection will be empty . [CODESPLIT] public static NetworkInterface [ ] filterBySubnet ( final InetAddress address , final int subnetPrefix ) throws SocketException { return filterBySubnet ( NetworkInterfaceShim . DEFAULT , address , subnetPrefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a direct { @link ByteBuffer } that is padded at the end with at least alignment bytes . [CODESPLIT] public static ByteBuffer allocateDirectAlignedAndPadded ( final int capacity , final int alignment ) { final ByteBuffer buffer = BufferUtil . allocateDirectAligned ( capacity + alignment , alignment ) ; buffer . limit ( buffer . limit ( ) - alignment ) ; return buffer . slice ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a counter for tracking a position on a stream of messages . [CODESPLIT] public static UnsafeBufferPosition allocate ( final MutableDirectBuffer tempBuffer , final String name , final int typeId , final CountersManager countersManager , final long registrationId , final int sessionId , final int streamId , final String channel ) { return new UnsafeBufferPosition ( ( UnsafeBuffer ) countersManager . valuesBuffer ( ) , allocateCounterId ( tempBuffer , name , typeId , countersManager , registrationId , sessionId , streamId , channel ) , countersManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the label name for a counter type identifier . [CODESPLIT] public static String labelName ( final int typeId ) { switch ( typeId ) { case PublisherLimit . PUBLISHER_LIMIT_TYPE_ID : return PublisherLimit . NAME ; case SenderPos . SENDER_POSITION_TYPE_ID : return SenderPos . NAME ; case ReceiverHwm . RECEIVER_HWM_TYPE_ID : return ReceiverHwm . NAME ; case SubscriberPos . SUBSCRIBER_POSITION_TYPE_ID : return SubscriberPos . NAME ; case ReceiverPos . RECEIVER_POS_TYPE_ID : return ReceiverPos . NAME ; case SenderLimit . SENDER_LIMIT_TYPE_ID : return SenderLimit . NAME ; case PublisherPos . PUBLISHER_POS_TYPE_ID : return PublisherPos . NAME ; case SenderBpe . SENDER_BPE_TYPE_ID : return SenderBpe . NAME ; default : return \"<unknown>\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan the term buffer for availability of new message fragments from a given offset up to a maxLength of bytes . [CODESPLIT] public static long scanForAvailability ( final UnsafeBuffer termBuffer , final int offset , final int maxLength ) { final int limit = Math . min ( maxLength , termBuffer . capacity ( ) - offset ) ; int available = 0 ; int padding = 0 ; do { final int termOffset = offset + available ; final int frameLength = frameLengthVolatile ( termBuffer , termOffset ) ; if ( frameLength <= 0 ) { break ; } int alignedFrameLength = align ( frameLength , FRAME_ALIGNMENT ) ; if ( isPaddingFrame ( termBuffer , termOffset ) ) { padding = alignedFrameLength - HEADER_LENGTH ; alignedFrameLength = HEADER_LENGTH ; } available += alignedFrameLength ; if ( available > limit ) { available -= alignedFrameLength ; padding = 0 ; break ; } } while ( 0 == padding && available < limit ) ; return pack ( padding , available ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear out all the values thus setting back to the initial state . [CODESPLIT] public ChannelUriStringBuilder clear ( ) { prefix = null ; media = null ; endpoint = null ; networkInterface = null ; controlEndpoint = null ; controlMode = null ; tags = null ; alias = null ; reliable = null ; ttl = null ; mtu = null ; termLength = null ; initialTermId = null ; termId = null ; termOffset = null ; sessionId = null ; linger = null ; sparse = null ; eos = null ; tether = null ; isSessionIdTagged = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates that the collection of set parameters are valid together . [CODESPLIT] public ChannelUriStringBuilder validate ( ) { if ( null == media ) { throw new IllegalStateException ( \"media type is mandatory\" ) ; } if ( CommonContext . UDP_MEDIA . equals ( media ) && ( null == endpoint && null == controlEndpoint ) ) { throw new IllegalStateException ( \"either 'endpoint' or 'control' must be specified for UDP.\" ) ; } int count = 0 ; count += null == initialTermId ? 0 : 1 ; count += null == termId ? 0 : 1 ; count += null == termOffset ? 0 : 1 ; if ( count > 0 ) { if ( count < 3 ) { throw new IllegalStateException ( \"if any of then a complete set of 'initialTermId', 'termId', and 'termOffset' must be provided\" ) ; } if ( termId - initialTermId < 0 ) // lgtm [java/dereferenced-value-may-be-null] { throw new IllegalStateException ( \"difference greater than 2^31 - 1: termId=\" + termId + \" - initialTermId=\" + initialTermId ) ; } if ( null != termLength && termOffset > termLength ) // lgtm [java/dereferenced-value-may-be-null] { throw new IllegalStateException ( \"termOffset=\" + termOffset + \" > termLength=\" + termLength ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the prefix for taking an addition action such as spying on an outgoing publication with aeron - spy . [CODESPLIT] public ChannelUriStringBuilder prefix ( final String prefix ) { if ( null != prefix && ! prefix . equals ( \"\" ) && ! prefix . equals ( SPY_QUALIFIER ) ) { throw new IllegalArgumentException ( \"invalid prefix: \" + prefix ) ; } this . prefix = prefix ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the media for this channel . Valid values are udp and ipc . [CODESPLIT] public ChannelUriStringBuilder media ( final String media ) { switch ( media ) { case CommonContext . UDP_MEDIA : case CommonContext . IPC_MEDIA : break ; default : throw new IllegalArgumentException ( \"invalid media: \" + media ) ; } this . media = media ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the control mode for multi - destination - cast . Set to manual for allowing control from the publication API . [CODESPLIT] public ChannelUriStringBuilder controlMode ( final String controlMode ) { if ( null != controlMode && ! controlMode . equals ( CommonContext . MDC_CONTROL_MODE_MANUAL ) && ! controlMode . equals ( CommonContext . MDC_CONTROL_MODE_DYNAMIC ) ) { throw new IllegalArgumentException ( \"invalid control mode: \" + controlMode ) ; } this . controlMode = controlMode ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Time To Live ( TTL ) for a multicast datagram . Valid values are 0 - 255 for the number of hops the datagram can progress along . [CODESPLIT] public ChannelUriStringBuilder ttl ( final Integer ttl ) { if ( null != ttl && ( ttl < 0 || ttl > 255 ) ) { throw new IllegalArgumentException ( \"TTL not in range 0-255: \" + ttl ) ; } this . ttl = ttl ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the maximum transmission unit ( MTU ) including Aeron header for a datagram payload . If this is greater than the network MTU for UDP then the packet will be fragmented and can amplify the impact of loss . [CODESPLIT] public ChannelUriStringBuilder mtu ( final Integer mtu ) { if ( null != mtu ) { if ( mtu < 32 || mtu > 65504 ) { throw new IllegalArgumentException ( \"MTU not in range 32-65504: \" + mtu ) ; } if ( ( mtu & ( FRAME_ALIGNMENT - 1 ) ) != 0 ) { throw new IllegalArgumentException ( \"MTU not a multiple of FRAME_ALIGNMENT: mtu=\" + mtu ) ; } } this . mtu = mtu ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the length of buffer used for each term of the log . Valid values are powers of 2 in the 64K - 1G range . [CODESPLIT] public ChannelUriStringBuilder termLength ( final Integer termLength ) { if ( null != termLength ) { LogBufferDescriptor . checkTermLength ( termLength ) ; } this . termLength = termLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the offset within a term at which a publication will start . This when combined with the term id can establish a starting position . [CODESPLIT] public ChannelUriStringBuilder termOffset ( final Integer termOffset ) { if ( null != termOffset ) { if ( ( termOffset < 0 || termOffset > LogBufferDescriptor . TERM_MAX_LENGTH ) ) { throw new IllegalArgumentException ( \"term offset not in range 0-1g: \" + termOffset ) ; } if ( 0 != ( termOffset & ( FRAME_ALIGNMENT - 1 ) ) ) { throw new IllegalArgumentException ( \"term offset not multiple of FRAME_ALIGNMENT: \" + termOffset ) ; } } this . termOffset = termOffset ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the time a network publication will linger in nanoseconds after being drained . This time is so that tail loss can be recovered . [CODESPLIT] public ChannelUriStringBuilder linger ( final Long lingerNs ) { if ( null != lingerNs && lingerNs < 0 ) { throw new IllegalArgumentException ( \"linger value cannot be negative: \" + lingerNs ) ; } this . linger = lingerNs ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialise a channel for restarting a publication at a given position . [CODESPLIT] public ChannelUriStringBuilder initialPosition ( final long position , final int initialTermId , final int termLength ) { if ( position < 0 || 0 != ( position & ( FRAME_ALIGNMENT - 1 ) ) ) { throw new IllegalArgumentException ( \"invalid position: \" + position ) ; } final int bitsToShift = LogBufferDescriptor . positionBitsToShift ( termLength ) ; this . initialTermId = initialTermId ; this . termId = LogBufferDescriptor . computeTermIdFromPosition ( position , bitsToShift , initialTermId ) ; this . termOffset = ( int ) ( position & ( termLength - 1 ) ) ; this . termLength = termLength ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a channel URI String for the given parameters . [CODESPLIT] @ SuppressWarnings ( \"MethodLength\" ) public String build ( ) { sb . setLength ( 0 ) ; if ( null != prefix && ! \"\" . equals ( prefix ) ) { sb . append ( prefix ) . append ( ' ' ) ; } sb . append ( ChannelUri . AERON_SCHEME ) . append ( ' ' ) . append ( media ) . append ( ' ' ) ; if ( null != tags ) { sb . append ( TAGS_PARAM_NAME ) . append ( ' ' ) . append ( tags ) . append ( ' ' ) ; } if ( null != endpoint ) { sb . append ( ENDPOINT_PARAM_NAME ) . append ( ' ' ) . append ( endpoint ) . append ( ' ' ) ; } if ( null != networkInterface ) { sb . append ( INTERFACE_PARAM_NAME ) . append ( ' ' ) . append ( networkInterface ) . append ( ' ' ) ; } if ( null != controlEndpoint ) { sb . append ( MDC_CONTROL_PARAM_NAME ) . append ( ' ' ) . append ( controlEndpoint ) . append ( ' ' ) ; } if ( null != controlMode ) { sb . append ( MDC_CONTROL_MODE_PARAM_NAME ) . append ( ' ' ) . append ( controlMode ) . append ( ' ' ) ; } if ( null != mtu ) { sb . append ( MTU_LENGTH_PARAM_NAME ) . append ( ' ' ) . append ( mtu . intValue ( ) ) . append ( ' ' ) ; } if ( null != termLength ) { sb . append ( TERM_LENGTH_PARAM_NAME ) . append ( ' ' ) . append ( termLength . intValue ( ) ) . append ( ' ' ) ; } if ( null != initialTermId ) { sb . append ( INITIAL_TERM_ID_PARAM_NAME ) . append ( ' ' ) . append ( initialTermId . intValue ( ) ) . append ( ' ' ) ; } if ( null != termId ) { sb . append ( TERM_ID_PARAM_NAME ) . append ( ' ' ) . append ( termId . intValue ( ) ) . append ( ' ' ) ; } if ( null != termOffset ) { sb . append ( TERM_OFFSET_PARAM_NAME ) . append ( ' ' ) . append ( termOffset . intValue ( ) ) . append ( ' ' ) ; } if ( null != sessionId ) { sb . append ( SESSION_ID_PARAM_NAME ) . append ( ' ' ) . append ( prefixTag ( isSessionIdTagged , sessionId ) ) . append ( ' ' ) ; } if ( null != ttl ) { sb . append ( TTL_PARAM_NAME ) . append ( ' ' ) . append ( ttl . intValue ( ) ) . append ( ' ' ) ; } if ( null != reliable ) { sb . append ( RELIABLE_STREAM_PARAM_NAME ) . append ( ' ' ) . append ( reliable ) . append ( ' ' ) ; } if ( null != linger ) { sb . append ( LINGER_PARAM_NAME ) . append ( ' ' ) . append ( linger . intValue ( ) ) . append ( ' ' ) ; } if ( null != alias ) { sb . append ( ALIAS_PARAM_NAME ) . append ( ' ' ) . append ( alias ) . append ( ' ' ) ; } if ( null != sparse ) { sb . append ( SPARSE_PARAM_NAME ) . append ( ' ' ) . append ( sparse ) . append ( ' ' ) ; } if ( null != eos ) { sb . append ( EOS_PARAM_NAME ) . append ( ' ' ) . append ( eos ) . append ( ' ' ) ; } if ( null != tether ) { sb . append ( TETHER_PARAM_NAME ) . append ( ' ' ) . append ( tether ) . append ( ' ' ) ; } final char lastChar = sb . charAt ( sb . length ( ) - 1 ) ; if ( lastChar == ' ' || lastChar == ' ' ) { sb . setLength ( sb . length ( ) - 1 ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throw a { @link AeronException } with a message for a send error . [CODESPLIT] public static void sendError ( final int bytesToSend , final IOException ex , final InetSocketAddress destination ) { throw new AeronException ( \"failed to send packet of \" + bytesToSend + \" bytes to \" + destination , ex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the underlying channel for reading and writing . [CODESPLIT] public void openDatagramChannel ( final AtomicCounter statusIndicator ) { try { sendDatagramChannel = DatagramChannel . open ( udpChannel . protocolFamily ( ) ) ; receiveDatagramChannel = sendDatagramChannel ; if ( udpChannel . isMulticast ( ) ) { if ( null != connectAddress ) { receiveDatagramChannel = DatagramChannel . open ( udpChannel . protocolFamily ( ) ) ; } receiveDatagramChannel . setOption ( StandardSocketOptions . SO_REUSEADDR , true ) ; receiveDatagramChannel . bind ( new InetSocketAddress ( endPointAddress . getPort ( ) ) ) ; receiveDatagramChannel . join ( endPointAddress . getAddress ( ) , udpChannel . localInterface ( ) ) ; sendDatagramChannel . setOption ( StandardSocketOptions . IP_MULTICAST_IF , udpChannel . localInterface ( ) ) ; if ( udpChannel . isHasMulticastTtl ( ) ) { sendDatagramChannel . setOption ( StandardSocketOptions . IP_MULTICAST_TTL , udpChannel . multicastTtl ( ) ) ; multicastTtl = sendDatagramChannel . getOption ( StandardSocketOptions . IP_MULTICAST_TTL ) ; } else if ( context . socketMulticastTtl ( ) != 0 ) { sendDatagramChannel . setOption ( StandardSocketOptions . IP_MULTICAST_TTL , context . socketMulticastTtl ( ) ) ; multicastTtl = sendDatagramChannel . getOption ( StandardSocketOptions . IP_MULTICAST_TTL ) ; } } else { sendDatagramChannel . bind ( bindAddress ) ; } if ( null != connectAddress ) { sendDatagramChannel . connect ( connectAddress ) ; } if ( 0 != context . socketSndbufLength ( ) ) { sendDatagramChannel . setOption ( SO_SNDBUF , context . socketSndbufLength ( ) ) ; } if ( 0 != context . socketRcvbufLength ( ) ) { receiveDatagramChannel . setOption ( SO_RCVBUF , context . socketRcvbufLength ( ) ) ; } sendDatagramChannel . configureBlocking ( false ) ; receiveDatagramChannel . configureBlocking ( false ) ; } catch ( final IOException ex ) { if ( null != statusIndicator ) { statusIndicator . setOrdered ( ChannelEndpointStatus . ERRORED ) ; } CloseHelper . quietClose ( sendDatagramChannel ) ; if ( receiveDatagramChannel != sendDatagramChannel ) { CloseHelper . quietClose ( receiveDatagramChannel ) ; } sendDatagramChannel = null ; receiveDatagramChannel = null ; throw new AeronException ( \"channel error - \" + ex . getMessage ( ) + \" (at \" + ex . getStackTrace ( ) [ 0 ] . toString ( ) + \"): \" + udpChannel . originalUriString ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close transport canceling any pending read operations and closing channel [CODESPLIT] public void close ( ) { if ( ! isClosed ) { isClosed = true ; try { if ( null != selectionKey ) { selectionKey . cancel ( ) ; } if ( null != transportPoller ) { transportPoller . cancelRead ( this ) ; transportPoller . selectNowWithoutProcessing ( ) ; } if ( null != sendDatagramChannel ) { sendDatagramChannel . close ( ) ; } if ( receiveDatagramChannel != sendDatagramChannel && null != receiveDatagramChannel ) { receiveDatagramChannel . close ( ) ; } if ( null != transportPoller ) { transportPoller . selectNowWithoutProcessing ( ) ; } } catch ( final IOException ex ) { errorLog . record ( ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is the received frame valid . This method will do some basic checks on the header and can be overridden in a subclass for further validation . [CODESPLIT] public boolean isValidFrame ( final UnsafeBuffer buffer , final int length ) { boolean isFrameValid = true ; if ( frameVersion ( buffer , 0 ) != HeaderFlyweight . CURRENT_VERSION ) { isFrameValid = false ; invalidPackets . increment ( ) ; } else if ( length < HeaderFlyweight . MIN_HEADER_LENGTH ) { isFrameValid = false ; invalidPackets . increment ( ) ; } return isFrameValid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive a datagram from the media layer . [CODESPLIT] public InetSocketAddress receive ( final ByteBuffer buffer ) { buffer . clear ( ) ; InetSocketAddress address = null ; try { if ( receiveDatagramChannel . isOpen ( ) ) { address = ( InetSocketAddress ) receiveDatagramChannel . receive ( buffer ) ; } } catch ( final PortUnreachableException ignored ) { } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return address ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called on reception of a NAK to start retransmits handling . [CODESPLIT] public void onNak ( final int termId , final int termOffset , final int length , final int termLength , final RetransmitSender retransmitSender ) { if ( ! isInvalid ( termOffset , termLength ) ) { if ( null == activeRetransmitsMap . get ( termId , termOffset ) && activeRetransmitsMap . size ( ) < MAX_RETRANSMITS_DEFAULT ) { final RetransmitAction action = assignRetransmitAction ( ) ; action . termId = termId ; action . termOffset = termOffset ; action . length = Math . min ( length , termLength - termOffset ) ; final long delay = delayGenerator . generateDelay ( ) ; if ( 0 == delay ) { retransmitSender . resend ( termId , termOffset , action . length ) ; action . linger ( lingerTimeoutGenerator . generateDelay ( ) , nanoClock . nanoTime ( ) ) ; } else { action . delay ( delay , nanoClock . nanoTime ( ) ) ; } activeRetransmitsMap . put ( termId , termOffset , action ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called to indicate a retransmission is received that may obviate the need to send one ourselves . <p > NOTE : Currently only called from unit tests . Would be used for retransmitting from receivers for NAK suppression . [CODESPLIT] public void onRetransmitReceived ( final int termId , final int termOffset ) { final RetransmitAction action = activeRetransmitsMap . get ( termId , termOffset ) ; if ( null != action && DELAYED == action . state ) { activeRetransmitsMap . remove ( termId , termOffset ) ; action . cancel ( ) ; // do not go into linger } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called to process any outstanding timeouts . [CODESPLIT] public void processTimeouts ( final long nowNs , final RetransmitSender retransmitSender ) { if ( activeRetransmitsMap . size ( ) > 0 ) { for ( final RetransmitAction action : retransmitActionPool ) { if ( DELAYED == action . state && ( action . expireNs - nowNs < 0 ) ) { retransmitSender . resend ( action . termId , action . termOffset , action . length ) ; action . linger ( lingerTimeoutGenerator . generateDelay ( ) , nanoClock . nanoTime ( ) ) ; } else if ( LINGERING == action . state && ( action . expireNs - nowNs < 0 ) ) { action . cancel ( ) ; activeRetransmitsMap . remove ( action . termId , action . termOffset ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the poller to dispatch the descriptors returned from a query . [CODESPLIT] public void reset ( final long correlationId , final int subscriptionCount , final RecordingSubscriptionDescriptorConsumer consumer ) { this . correlationId = correlationId ; this . consumer = consumer ; this . remainingSubscriptionCount = subscriptionCount ; isDispatchComplete = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The implementation of { @link ControlledFragmentHandler } that reassembles and forwards whole messages . [CODESPLIT] public Action onFragment ( final DirectBuffer buffer , final int offset , final int length , final Header header ) { final byte flags = header . flags ( ) ; Action action = Action . CONTINUE ; if ( ( flags & UNFRAGMENTED ) == UNFRAGMENTED ) { action = delegate . onFragment ( buffer , offset , length , header ) ; } else { if ( ( flags & BEGIN_FRAG_FLAG ) == BEGIN_FRAG_FLAG ) { final BufferBuilder builder = getBufferBuilder ( header . sessionId ( ) ) ; builder . reset ( ) . append ( buffer , offset , length ) ; } else { final BufferBuilder builder = builderBySessionIdMap . get ( header . sessionId ( ) ) ; if ( null != builder && builder . limit ( ) != 0 ) { final int limit = builder . limit ( ) ; builder . append ( buffer , offset , length ) ; if ( ( flags & END_FRAG_FLAG ) == END_FRAG_FLAG ) { final int msgLength = builder . limit ( ) ; action = delegate . onFragment ( builder . buffer ( ) , 0 , msgLength , header ) ; if ( Action . ABORT == action ) { builder . limit ( limit ) ; } else { builder . reset ( ) ; } } } } } return action ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String representation of the channel status . [CODESPLIT] public static String status ( final long status ) { if ( INITIALIZING == status ) { return \"INITIALIZING\" ; } if ( ERRORED == status ) { return \"ERRORED\" ; } if ( ACTIVE == status ) { return \"ACTIVE\" ; } if ( CLOSING == status ) { return \"CLOSING\" ; } return \"unknown id=\" + status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate an indicator for tracking the status of a channel endpoint . [CODESPLIT] public static AtomicCounter allocate ( final MutableDirectBuffer tempBuffer , final String name , final int typeId , final CountersManager countersManager , final String channel ) { final int keyLength = tempBuffer . putStringWithoutLengthAscii ( CHANNEL_OFFSET + SIZE_OF_INT , channel , 0 , MAX_CHANNEL_LENGTH ) ; tempBuffer . putInt ( CHANNEL_OFFSET , keyLength ) ; int labelLength = 0 ; labelLength += tempBuffer . putStringWithoutLengthAscii ( keyLength + labelLength , name ) ; labelLength += tempBuffer . putStringWithoutLengthAscii ( keyLength + labelLength , \": \" ) ; labelLength += tempBuffer . putStringWithoutLengthAscii ( keyLength + labelLength , channel , 0 , MAX_LABEL_LENGTH - labelLength ) ; return countersManager . newCounter ( typeId , tempBuffer , 0 , keyLength , tempBuffer , keyLength , labelLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The implementation of { @link FragmentHandler } that reassembles and forwards whole messages . [CODESPLIT] public void onFragment ( final DirectBuffer buffer , final int offset , final int length , final Header header ) { final byte flags = header . flags ( ) ; if ( ( flags & UNFRAGMENTED ) == UNFRAGMENTED ) { delegate . onFragment ( buffer , offset , length , header ) ; } else { handleFragment ( buffer , offset , length , header , flags ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the values . [CODESPLIT] public DirectBufferVector reset ( final DirectBuffer buffer , final int offset , final int length ) { this . buffer = buffer ; this . offset = offset ; this . length = length ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure the vector is valid for the buffer . [CODESPLIT] public DirectBufferVector validate ( ) { final int capacity = buffer . capacity ( ) ; if ( offset < 0 || offset >= capacity ) { throw new IllegalArgumentException ( \"offset=\" + offset + \" capacity=\" + capacity ) ; } if ( length < 0 || length > ( capacity - offset ) ) { throw new IllegalArgumentException ( \"offset=\" + offset + \" capacity=\" + capacity + \" length=\" + length ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate an array of vectors to make up a message and compute the total length . [CODESPLIT] public static int validateAndComputeLength ( final DirectBufferVector [ ] vectors ) { int messageLength = 0 ; for ( final DirectBufferVector vector : vectors ) { vector . validate ( ) ; messageLength += vector . length ; if ( messageLength < 0 ) { throw new IllegalStateException ( \"length overflow: \" + Arrays . toString ( vectors ) ) ; } } return messageLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "How far ahead a producer can get from a consumer position . [CODESPLIT] public static int producerWindowLength ( final int termBufferLength , final int defaultTermWindowLength ) { int termWindowLength = termBufferLength / 2 ; if ( 0 != defaultTermWindowLength ) { termWindowLength = Math . min ( defaultTermWindowLength , termWindowLength ) ; } return termWindowLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { @link IdleStrategy } that should be applied to { @link org . agrona . concurrent . Agent } s . [CODESPLIT] public static IdleStrategy agentIdleStrategy ( final String strategyName , final StatusIndicator controllableStatus ) { IdleStrategy idleStrategy = null ; switch ( strategyName ) { case DEFAULT_IDLE_STRATEGY : idleStrategy = new BackoffIdleStrategy ( IDLE_MAX_SPINS , IDLE_MAX_YIELDS , IDLE_MIN_PARK_NS , IDLE_MAX_PARK_NS ) ; break ; case CONTROLLABLE_IDLE_STRATEGY : idleStrategy = new ControllableIdleStrategy ( controllableStatus ) ; controllableStatus . setOrdered ( ControllableIdleStrategy . PARK ) ; break ; default : try { idleStrategy = ( IdleStrategy ) Class . forName ( strategyName ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } break ; } return idleStrategy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supplier of { @link SendChannelEndpoint } s which can be used for debugging monitoring or modifying the behaviour when sending to the channel . [CODESPLIT] public static SendChannelEndpointSupplier sendChannelEndpointSupplier ( ) { SendChannelEndpointSupplier supplier = null ; try { final String className = getProperty ( SEND_CHANNEL_ENDPOINT_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultSendChannelEndpointSupplier ( ) ; } supplier = ( SendChannelEndpointSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supplier of { @link ReceiveChannelEndpoint } s which can be used for debugging monitoring or modifying the behaviour when receiving from the channel . [CODESPLIT] public static ReceiveChannelEndpointSupplier receiveChannelEndpointSupplier ( ) { ReceiveChannelEndpointSupplier supplier = null ; try { final String className = getProperty ( RECEIVE_CHANNEL_ENDPOINT_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultReceiveChannelEndpointSupplier ( ) ; } supplier = ( ReceiveChannelEndpointSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supplier of { @link FlowControl } s which can be used for changing behavior of flow control for unicast publications . [CODESPLIT] public static FlowControlSupplier unicastFlowControlSupplier ( ) { FlowControlSupplier supplier = null ; try { final String className = getProperty ( UNICAST_FLOW_CONTROL_STRATEGY_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultUnicastFlowControlSupplier ( ) ; } supplier = ( FlowControlSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supplier of { @link FlowControl } s which can be used for changing behavior of flow control for multicast publications . [CODESPLIT] public static FlowControlSupplier multicastFlowControlSupplier ( ) { FlowControlSupplier supplier = null ; try { final String className = getProperty ( MULTICAST_FLOW_CONTROL_STRATEGY_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultMulticastFlowControlSupplier ( ) ; } supplier = ( FlowControlSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supplier of { @link CongestionControl } implementations which can be used for receivers . [CODESPLIT] public static CongestionControlSupplier congestionControlSupplier ( ) { CongestionControlSupplier supplier = null ; try { final String className = getProperty ( CONGESTION_CONTROL_STRATEGY_SUPPLIER_PROP_NAME ) ; if ( null == className ) { return new DefaultCongestionControlSupplier ( ) ; } supplier = ( CongestionControlSupplier ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return supplier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that the MTU is an appropriate length . MTU lengths must be a multiple of { @link FrameDescriptor#FRAME_ALIGNMENT } . [CODESPLIT] public static void validateMtuLength ( final int mtuLength ) { if ( mtuLength < DataHeaderFlyweight . HEADER_LENGTH || mtuLength > MAX_UDP_PAYLOAD_LENGTH ) { throw new ConfigurationException ( \"mtuLength must be a >= HEADER_LENGTH and <= MAX_UDP_PAYLOAD_LENGTH: \" + mtuLength ) ; } if ( ( mtuLength & ( FrameDescriptor . FRAME_ALIGNMENT - 1 ) ) != 0 ) { throw new ConfigurationException ( \"mtuLength must be a multiple of FRAME_ALIGNMENT: \" + mtuLength ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { @link TerminationValidator } implementations which can be used for validating a termination request sent to the driver to ensure the client has the right to terminate a driver . [CODESPLIT] public static TerminationValidator terminationValidator ( ) { TerminationValidator validator = null ; try { final String className = getProperty ( TERMINATION_VALIDATOR_PROP_NAME ) ; if ( null == className ) { return new DefaultDenyTerminationValidator ( ) ; } validator = ( TerminationValidator ) Class . forName ( className ) . getConstructor ( ) . newInstance ( ) ; } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } return validator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that the socket buffer lengths are sufficient for the media driver configuration . [CODESPLIT] public static void validateSocketBufferLengths ( final MediaDriver . Context ctx ) { try ( DatagramChannel probe = DatagramChannel . open ( ) ) { final int defaultSoSndBuf = probe . getOption ( StandardSocketOptions . SO_SNDBUF ) ; probe . setOption ( StandardSocketOptions . SO_SNDBUF , Integer . MAX_VALUE ) ; final int maxSoSndBuf = probe . getOption ( StandardSocketOptions . SO_SNDBUF ) ; if ( maxSoSndBuf < ctx . socketSndbufLength ( ) ) { System . err . format ( \"WARNING: Could not get desired SO_SNDBUF, adjust OS to allow %s: attempted=%d, actual=%d%n\" , SOCKET_SNDBUF_LENGTH_PROP_NAME , ctx . socketSndbufLength ( ) , maxSoSndBuf ) ; } probe . setOption ( StandardSocketOptions . SO_RCVBUF , Integer . MAX_VALUE ) ; final int maxSoRcvBuf = probe . getOption ( StandardSocketOptions . SO_RCVBUF ) ; if ( maxSoRcvBuf < ctx . socketRcvbufLength ( ) ) { System . err . format ( \"WARNING: Could not get desired SO_RCVBUF, adjust OS to allow %s: attempted=%d, actual=%d%n\" , SOCKET_RCVBUF_LENGTH_PROP_NAME , ctx . socketRcvbufLength ( ) , maxSoRcvBuf ) ; } final int soSndBuf = 0 == ctx . socketSndbufLength ( ) ? defaultSoSndBuf : ctx . socketSndbufLength ( ) ; if ( ctx . mtuLength ( ) > soSndBuf ) { throw new ConfigurationException ( String . format ( \"MTU greater than socket SO_SNDBUF, adjust %s to match MTU: mtuLength=%d, SO_SNDBUF=%d\" , SOCKET_SNDBUF_LENGTH_PROP_NAME , ctx . mtuLength ( ) , soSndBuf ) ) ; } if ( ctx . initialWindowLength ( ) > maxSoRcvBuf ) { throw new ConfigurationException ( \"window length greater than socket SO_RCVBUF, increase '\" + Configuration . INITIAL_WINDOW_LENGTH_PROP_NAME + \"' to match window: windowLength=\" + ctx . initialWindowLength ( ) + \", SO_RCVBUF=\" + maxSoRcvBuf ) ; } } catch ( final IOException ex ) { throw new AeronException ( \"probe socket: \" + ex . toString ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that page size is valid and alignment is valid . [CODESPLIT] public static void validatePageSize ( final int pageSize ) { if ( pageSize < PAGE_MIN_SIZE ) { throw new ConfigurationException ( \"page size less than min size of \" + PAGE_MIN_SIZE + \": \" + pageSize ) ; } if ( pageSize > PAGE_MAX_SIZE ) { throw new ConfigurationException ( \"page size greater than max size of \" + PAGE_MAX_SIZE + \": \" + pageSize ) ; } if ( ! BitUtil . isPowerOfTwo ( pageSize ) ) { throw new ConfigurationException ( \"page size not a power of 2: \" + pageSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the range of session ids based on a high and low value provided which accounts for the values wrapping . [CODESPLIT] public static void validateSessionIdRange ( final int low , final int high ) { if ( low > high ) { throw new ConfigurationException ( \"low session id value \" + low + \" must be <= high value \" + high ) ; } if ( Math . abs ( ( long ) high - low ) > Integer . MAX_VALUE ) { throw new ConfigurationException ( \"reserved range to too large\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that the timeouts for unblocking publications from a client are valid . [CODESPLIT] public static void validateUnblockTimeout ( final long publicationUnblockTimeoutNs , final long clientLivenessTimeoutNs , final long timerIntervalNs ) { if ( publicationUnblockTimeoutNs <= clientLivenessTimeoutNs ) { throw new ConfigurationException ( \"publicationUnblockTimeoutNs=\" + publicationUnblockTimeoutNs + \" <= clientLivenessTimeoutNs=\" + clientLivenessTimeoutNs ) ; } if ( clientLivenessTimeoutNs <= timerIntervalNs ) { throw new ConfigurationException ( \"clientLivenessTimeoutNs=\" + clientLivenessTimeoutNs + \" <= timerIntervalNs=\" + timerIntervalNs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the error code for the command . [CODESPLIT] public ErrorResponseFlyweight errorCode ( final ErrorCode code ) { buffer . putInt ( offset + ERROR_CODE_OFFSET , code . value ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { @link Set } of { @link ClusterEventCode } s that are enabled for the logger . [CODESPLIT] static Set < ClusterEventCode > getEnabledClusterEventCodes ( final String enabledClusterEventCodes ) { if ( null == enabledClusterEventCodes || \"\" . equals ( enabledClusterEventCodes ) ) { return EnumSet . noneOf ( ClusterEventCode . class ) ; } final Function < Integer , ClusterEventCode > eventCodeById = ClusterEventCode :: get ; final Function < String , ClusterEventCode > eventCodeByName = ClusterEventCode :: valueOf ; final EnumSet < ClusterEventCode > allEventsSet = EnumSet . allOf ( ClusterEventCode . class ) ; return parseEventCodes ( enabledClusterEventCodes , eventCodeById , eventCodeByName , allEventsSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { @link Set } of { @link ArchiveEventCode } s that are enabled for the logger . [CODESPLIT] static Set < ArchiveEventCode > getEnabledArchiveEventCodes ( final String enabledArchiveEventCodes ) { if ( null == enabledArchiveEventCodes || \"\" . equals ( enabledArchiveEventCodes ) ) { return EnumSet . noneOf ( ArchiveEventCode . class ) ; } final Function < Integer , ArchiveEventCode > eventCodeById = ArchiveEventCode :: get ; final Function < String , ArchiveEventCode > eventCodeByName = ArchiveEventCode :: valueOf ; final EnumSet < ArchiveEventCode > allEventsSet = EnumSet . allOf ( ArchiveEventCode . class ) ; return parseEventCodes ( enabledArchiveEventCodes , eventCodeById , eventCodeByName , allEventsSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { @link Set } of { @link DriverEventCode } s that are enabled for the logger . [CODESPLIT] static Set < DriverEventCode > getEnabledDriverEventCodes ( final String enabledLoggerEventCodes ) { if ( null == enabledLoggerEventCodes || \"\" . equals ( enabledLoggerEventCodes ) ) { return EnumSet . noneOf ( DriverEventCode . class ) ; } final Set < DriverEventCode > eventCodeSet = new HashSet <> ( ) ; final String [ ] codeIds = enabledLoggerEventCodes . split ( \",\" ) ; for ( final String codeId : codeIds ) { switch ( codeId ) { case \"all\" : eventCodeSet . addAll ( ALL_LOGGER_EVENT_CODES ) ; break ; case \"admin\" : eventCodeSet . addAll ( ADMIN_ONLY_EVENT_CODES ) ; break ; default : { DriverEventCode code = null ; try { code = DriverEventCode . valueOf ( codeId ) ; } catch ( final IllegalArgumentException ignore ) { } if ( null == code ) { try { code = DriverEventCode . get ( Integer . parseInt ( codeId ) ) ; } catch ( final IllegalArgumentException ignore ) { } } if ( null != code ) { eventCodeSet . add ( code ) ; } else { System . err . println ( \"unknown event code: \" + codeId ) ; } } } } return eventCodeSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the state of a cluster member so it can be canvassed and reestablished . [CODESPLIT] public void reset ( ) { isBallotSent = false ; isLeader = false ; hasRequestedJoin = false ; hasSentTerminationAck = false ; vote = null ; candidateTermId = Aeron . NULL_VALUE ; leadershipTermId = Aeron . NULL_VALUE ; logPosition = NULL_POSITION ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the details for a cluster members from a string . <p > <code > member - id client - facing : port member - facing : port log : port transfer : port archive : port|1 ... < / code > [CODESPLIT] public static ClusterMember [ ] parse ( final String value ) { if ( null == value || value . length ( ) == 0 ) { return ClusterMember . EMPTY_CLUSTER_MEMBER_ARRAY ; } final String [ ] memberValues = value . split ( \"\\\\|\" ) ; final int length = memberValues . length ; final ClusterMember [ ] members = new ClusterMember [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { final String endpointsDetail = memberValues [ i ] ; final String [ ] memberAttributes = endpointsDetail . split ( \",\" ) ; if ( memberAttributes . length != 6 ) { throw new ClusterException ( \"invalid member value: \" + endpointsDetail + \" within: \" + value ) ; } final String justEndpoints = String . join ( \",\" , memberAttributes [ 1 ] , memberAttributes [ 2 ] , memberAttributes [ 3 ] , memberAttributes [ 4 ] , memberAttributes [ 5 ] ) ; members [ i ] = new ClusterMember ( Integer . parseInt ( memberAttributes [ 0 ] ) , memberAttributes [ 1 ] , memberAttributes [ 2 ] , memberAttributes [ 3 ] , memberAttributes [ 4 ] , memberAttributes [ 5 ] , justEndpoints ) ; } return members ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode member details from a cluster members array to a string . [CODESPLIT] public static String encodeAsString ( final ClusterMember [ ] clusterMembers ) { final StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 , length = clusterMembers . length ; i < length ; i ++ ) { final ClusterMember member = clusterMembers [ i ] ; builder . append ( member . id ( ) ) . append ( ' ' ) . append ( member . endpointsDetail ( ) ) ; if ( ( length - 1 ) != i ) { builder . append ( ' ' ) ; } } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the publications for sending status messages to the other members of the cluster . [CODESPLIT] public static void addMemberStatusPublications ( final ClusterMember [ ] members , final ClusterMember exclude , final ChannelUri channelUri , final int streamId , final Aeron aeron ) { for ( final ClusterMember member : members ) { if ( member != exclude ) { channelUri . put ( ENDPOINT_PARAM_NAME , member . memberFacingEndpoint ( ) ) ; member . publication = aeron . addExclusivePublication ( channelUri . toString ( ) , streamId ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the publications associated with members of the cluster . [CODESPLIT] public static void closeMemberPublications ( final ClusterMember [ ] clusterMembers ) { for ( final ClusterMember member : clusterMembers ) { CloseHelper . close ( member . publication ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an exclusive { @link Publication } for communicating to a member on the member status channel . [CODESPLIT] public static void addMemberStatusPublication ( final ClusterMember member , final ChannelUri channelUri , final int streamId , final Aeron aeron ) { channelUri . put ( ENDPOINT_PARAM_NAME , member . memberFacingEndpoint ( ) ) ; member . publication = aeron . addExclusivePublication ( channelUri . toString ( ) , streamId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate map of { @link ClusterMember } s which can be looked up by id . [CODESPLIT] public static void addClusterMemberIds ( final ClusterMember [ ] clusterMembers , final Int2ObjectHashMap < ClusterMember > clusterMemberByIdMap ) { for ( final ClusterMember member : clusterMembers ) { clusterMemberByIdMap . put ( member . id ( ) , member ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the cluster leader has an active quorum of cluster followers . [CODESPLIT] public static boolean hasActiveQuorum ( final ClusterMember [ ] clusterMembers , final long nowMs , final long timeoutMs ) { int threshold = quorumThreshold ( clusterMembers . length ) ; for ( final ClusterMember member : clusterMembers ) { if ( member . isLeader ( ) || nowMs <= ( member . timeOfLastAppendPositionMs ( ) + timeoutMs ) ) { if ( -- threshold <= 0 ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the position reached by a quorum of cluster members . [CODESPLIT] public static long quorumPosition ( final ClusterMember [ ] members , final long [ ] rankedPositions ) { final int length = rankedPositions . length ; for ( int i = 0 ; i < length ; i ++ ) { rankedPositions [ i ] = 0 ; } for ( final ClusterMember member : members ) { long newPosition = member . logPosition ; for ( int i = 0 ; i < length ; i ++ ) { final long rankedPosition = rankedPositions [ i ] ; if ( newPosition > rankedPosition ) { rankedPositions [ i ] = newPosition ; newPosition = rankedPosition ; } } } return rankedPositions [ length - 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the log position of all the members to the provided value . [CODESPLIT] public static void resetLogPositions ( final ClusterMember [ ] clusterMembers , final long logPosition ) { for ( final ClusterMember member : clusterMembers ) { member . logPosition ( logPosition ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has the members of the cluster the voted reached the provided position in their log . [CODESPLIT] public static boolean haveVotersReachedPosition ( final ClusterMember [ ] clusterMembers , final long position , final long leadershipTermId ) { for ( final ClusterMember member : clusterMembers ) { if ( member . vote != null && ( member . logPosition < position || member . leadershipTermId != leadershipTermId ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Become a candidate by voting for yourself and resetting the other votes to { @link Aeron#NULL_VALUE } . [CODESPLIT] public static void becomeCandidate ( final ClusterMember [ ] members , final long candidateTermId , final int candidateMemberId ) { for ( final ClusterMember member : members ) { if ( member . id == candidateMemberId ) { member . vote ( Boolean . TRUE ) . candidateTermId ( candidateTermId ) . isBallotSent ( true ) ; } else { member . vote ( null ) . candidateTermId ( Aeron . NULL_VALUE ) . isBallotSent ( false ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has the candidate got unanimous support of the cluster? [CODESPLIT] public static boolean hasWonVoteOnFullCount ( final ClusterMember [ ] members , final long candidateTermId ) { int votes = 0 ; for ( final ClusterMember member : members ) { if ( null == member . vote || member . candidateTermId != candidateTermId ) { return false ; } votes += member . vote ? 1 : 0 ; } return votes >= ClusterMember . quorumThreshold ( members . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has sufficient votes being counted for a majority for all members observed during { @link Election . State#CANVASS } ? [CODESPLIT] public static boolean hasMajorityVoteWithCanvassMembers ( final ClusterMember [ ] members , final long candidateTermId ) { int votes = 0 ; for ( final ClusterMember member : members ) { if ( NULL_POSITION != member . logPosition && null == member . vote ) { return false ; } if ( Boolean . TRUE . equals ( member . vote ) && member . candidateTermId == candidateTermId ) { ++ votes ; } } return votes >= ClusterMember . quorumThreshold ( members . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has sufficient votes being counted for a majority? [CODESPLIT] public static boolean hasMajorityVote ( final ClusterMember [ ] clusterMembers , final long candidateTermId ) { int votes = 0 ; for ( final ClusterMember member : clusterMembers ) { if ( Boolean . TRUE . equals ( member . vote ) && member . candidateTermId == candidateTermId ) { ++ votes ; } } return votes >= ClusterMember . quorumThreshold ( clusterMembers . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine which member of a cluster this is and check endpoints . [CODESPLIT] public static ClusterMember determineMember ( final ClusterMember [ ] clusterMembers , final int memberId , final String memberEndpoints ) { ClusterMember member = NULL_VALUE != memberId ? ClusterMember . findMember ( clusterMembers , memberId ) : null ; if ( ( null == clusterMembers || 0 == clusterMembers . length ) && null == member ) { member = ClusterMember . parseEndpoints ( NULL_VALUE , memberEndpoints ) ; } else { if ( null == member ) { throw new ClusterException ( \"memberId=\" + memberId + \" not found in clusterMembers\" ) ; } if ( ! \"\" . equals ( memberEndpoints ) ) { ClusterMember . validateMemberEndpoints ( member , memberEndpoints ) ; } } return member ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the member with the memberEndpoints [CODESPLIT] public static void validateMemberEndpoints ( final ClusterMember member , final String memberEndpoints ) { final ClusterMember endpointMember = ClusterMember . parseEndpoints ( Aeron . NULL_VALUE , memberEndpoints ) ; if ( ! areSameEndpoints ( member , endpointMember ) ) { throw new ClusterException ( \"clusterMembers and memberEndpoints differ: \" + member . endpointsDetail ( ) + \" != \" + memberEndpoints ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Are two cluster members using the same endpoints? [CODESPLIT] public static boolean areSameEndpoints ( final ClusterMember lhs , final ClusterMember rhs ) { return lhs . clientFacingEndpoint ( ) . equals ( rhs . clientFacingEndpoint ( ) ) && lhs . memberFacingEndpoint ( ) . equals ( rhs . memberFacingEndpoint ( ) ) && lhs . logEndpoint ( ) . equals ( rhs . logEndpoint ( ) ) && lhs . transferEndpoint ( ) . equals ( rhs . transferEndpoint ( ) ) && lhs . archiveEndpoint ( ) . equals ( rhs . archiveEndpoint ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has the member achieved a unanimous view to be a suitable candidate in an election . [CODESPLIT] public static boolean isUnanimousCandidate ( final ClusterMember [ ] clusterMembers , final ClusterMember candidate ) { for ( final ClusterMember member : clusterMembers ) { if ( NULL_POSITION == member . logPosition || compareLog ( candidate , member ) < 0 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has the member achieved a quorum view to be a suitable candidate in an election . [CODESPLIT] public static boolean isQuorumCandidate ( final ClusterMember [ ] clusterMembers , final ClusterMember candidate ) { int possibleVotes = 0 ; for ( final ClusterMember member : clusterMembers ) { if ( NULL_POSITION == member . logPosition || compareLog ( candidate , member ) < 0 ) { continue ; } ++ possibleVotes ; } return possibleVotes >= ClusterMember . quorumThreshold ( clusterMembers . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The result is positive if lhs has the more recent log zero if logs are equal and negative if rhs has the more recent log . [CODESPLIT] public static int compareLog ( final long lhsLogLeadershipTermId , final long lhsLogPosition , final long rhsLogLeadershipTermId , final long rhsLogPosition ) { if ( lhsLogLeadershipTermId > rhsLogLeadershipTermId ) { return 1 ; } else if ( lhsLogLeadershipTermId < rhsLogLeadershipTermId ) { return - 1 ; } else if ( lhsLogPosition > rhsLogPosition ) { return 1 ; } else if ( lhsLogPosition < rhsLogPosition ) { return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The result is positive if lhs has the more recent log zero if logs are equal and negative if rhs has the more recent log . [CODESPLIT] public static int compareLog ( final ClusterMember lhs , final ClusterMember rhs ) { return compareLog ( lhs . leadershipTermId , lhs . logPosition , rhs . leadershipTermId , rhs . logPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is the string of member endpoints not duplicated in the members . [CODESPLIT] public static boolean isNotDuplicateEndpoints ( final ClusterMember [ ] members , final String memberEndpoints ) { for ( final ClusterMember member : members ) { if ( member . endpointsDetail ( ) . equals ( memberEndpoints ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the index at which a member id is present . [CODESPLIT] public static int findMemberIndex ( final ClusterMember [ ] clusterMembers , final int memberId ) { final int length = clusterMembers . length ; int index = ArrayUtil . UNKNOWN_INDEX ; for ( int i = 0 ; i < length ; i ++ ) { if ( clusterMembers [ i ] . id ( ) == memberId ) { index = i ; } } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a { @link ClusterMember } with a given id . [CODESPLIT] public static ClusterMember findMember ( final ClusterMember [ ] clusterMembers , final int memberId ) { for ( final ClusterMember member : clusterMembers ) { if ( member . id ( ) == memberId ) { return member ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new member to an array of { @link ClusterMember } s . [CODESPLIT] public static ClusterMember [ ] addMember ( final ClusterMember [ ] oldMembers , final ClusterMember newMember ) { return ArrayUtil . add ( oldMembers , newMember ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a member from an array if found otherwise return the array unmodified . [CODESPLIT] public static ClusterMember [ ] removeMember ( final ClusterMember [ ] oldMembers , final int memberId ) { return ArrayUtil . remove ( oldMembers , findMemberIndex ( oldMembers , memberId ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the highest member id in an array of members . [CODESPLIT] public static int highMemberId ( final ClusterMember [ ] clusterMembers ) { int highId = Aeron . NULL_VALUE ; for ( final ClusterMember member : clusterMembers ) { highId = Math . max ( highId , member . id ( ) ) ; } return highId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a string of member facing endpoints by id in format { @code id = endpoint id = endpoint ... } . [CODESPLIT] public static String clientFacingEndpoints ( final ClusterMember [ ] members ) { final StringBuilder builder = new StringBuilder ( 100 ) ; for ( int i = 0 , length = members . length ; i < length ; i ++ ) { if ( 0 != i ) { builder . append ( ' ' ) ; } final ClusterMember member = members [ i ] ; builder . append ( member . id ( ) ) . append ( ' ' ) . append ( member . clientFacingEndpoint ( ) ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public long onIdle ( final long timeNs , final long senderLimit , final long senderPosition , final boolean isEos ) { long minPosition = Long . MAX_VALUE ; long minLimitPosition = Long . MAX_VALUE ; final ArrayList < Receiver > receiverList = this . receiverList ; for ( int lastIndex = receiverList . size ( ) - 1 , i = lastIndex ; i >= 0 ; i -- ) { final Receiver receiver = receiverList . get ( i ) ; if ( ( receiver . timeOfLastStatusMessageNs + RECEIVER_TIMEOUT ) - timeNs < 0 ) { ArrayListUtil . fastUnorderedRemove ( receiverList , i , lastIndex -- ) ; } else { minPosition = Math . min ( minPosition , receiver . lastPosition ) ; minLimitPosition = Math . min ( minLimitPosition , receiver . lastPositionPlusWindow ) ; } } if ( isEos && shouldLinger ) { if ( 0 == receiverList . size ( ) || minPosition >= senderPosition ) { shouldLinger = false ; } } return receiverList . size ( ) > 0 ? minLimitPosition : senderLimit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to unblock the current term at the current offset . <ol > <li > Current position length is &gt ; 0 then return< / li > <li > Current position length is 0 scan forward by frame alignment until one of the following : <ol > <li > reach a non - 0 length unblock up to indicated position ( check original frame length for non - 0 ) < / li > <li > reach end of term and tail position &gt ; = end of term unblock up to end of term ( check original frame length for non - 0 ) < / li > <li > reach tail position &lt ; end of term do NOT unblock< / li > < / ol > < / li > < / ol > [CODESPLIT] public static Status unblock ( final UnsafeBuffer logMetaDataBuffer , final UnsafeBuffer termBuffer , final int blockedOffset , final int tailOffset , final int termId ) { Status status = NO_ACTION ; int frameLength = frameLengthVolatile ( termBuffer , blockedOffset ) ; if ( frameLength < 0 ) { resetHeader ( logMetaDataBuffer , termBuffer , blockedOffset , termId , - frameLength ) ; status = UNBLOCKED ; } else if ( 0 == frameLength ) { int currentOffset = blockedOffset + FRAME_ALIGNMENT ; while ( currentOffset < tailOffset ) { frameLength = frameLengthVolatile ( termBuffer , currentOffset ) ; if ( frameLength != 0 ) { if ( scanBackToConfirmZeroed ( termBuffer , currentOffset , blockedOffset ) ) { final int length = currentOffset - blockedOffset ; resetHeader ( logMetaDataBuffer , termBuffer , blockedOffset , termId , length ) ; status = UNBLOCKED ; } break ; } currentOffset += FRAME_ALIGNMENT ; } if ( currentOffset == termBuffer . capacity ( ) ) { if ( 0 == frameLengthVolatile ( termBuffer , blockedOffset ) ) { final int length = currentOffset - blockedOffset ; resetHeader ( logMetaDataBuffer , termBuffer , blockedOffset , termId , length ) ; status = UNBLOCKED_TO_END ; } } } return status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the CnC file if it exists . [CODESPLIT] public MappedByteBuffer mapExistingCncFile ( final Consumer < String > logger ) { final File cncFile = new File ( aeronDirectory , CncFileDescriptor . CNC_FILE ) ; if ( cncFile . exists ( ) && cncFile . length ( ) > 0 ) { if ( null != logger ) { logger . accept ( \"INFO: Aeron CnC file exists: \" + cncFile ) ; } return IoUtil . mapExistingFile ( cncFile , CncFileDescriptor . CNC_FILE ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is a media driver active in the given directory? [CODESPLIT] public static boolean isDriverActive ( final File directory , final long driverTimeoutMs , final Consumer < String > logger ) { final File cncFile = new File ( directory , CncFileDescriptor . CNC_FILE ) ; if ( cncFile . exists ( ) && cncFile . length ( ) > 0 ) { logger . accept ( \"INFO: Aeron CnC file exists: \" + cncFile ) ; final MappedByteBuffer cncByteBuffer = IoUtil . mapExistingFile ( cncFile , \"CnC file\" ) ; try { return isDriverActive ( driverTimeoutMs , logger , cncByteBuffer ) ; } finally { IoUtil . unmap ( cncByteBuffer ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is a media driver active in the current Aeron directory? [CODESPLIT] public boolean isDriverActive ( final long driverTimeoutMs , final Consumer < String > logger ) { final MappedByteBuffer cncByteBuffer = mapExistingCncFile ( logger ) ; try { return isDriverActive ( driverTimeoutMs , logger , cncByteBuffer ) ; } finally { IoUtil . unmap ( cncByteBuffer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is a media driver active in the current mapped CnC buffer? If the driver is mid start then it will wait for up to the driverTimeoutMs by checking for the cncVersion being set . [CODESPLIT] public static boolean isDriverActive ( final long driverTimeoutMs , final Consumer < String > logger , final ByteBuffer cncByteBuffer ) { if ( null == cncByteBuffer ) { return false ; } final UnsafeBuffer cncMetaDataBuffer = CncFileDescriptor . createMetaDataBuffer ( cncByteBuffer ) ; final long startTimeMs = System . currentTimeMillis ( ) ; int cncVersion ; while ( 0 == ( cncVersion = cncMetaDataBuffer . getIntVolatile ( CncFileDescriptor . cncVersionOffset ( 0 ) ) ) ) { if ( System . currentTimeMillis ( ) > ( startTimeMs + driverTimeoutMs ) ) { throw new DriverTimeoutException ( \"CnC file is created but not initialised.\" ) ; } sleep ( 1 ) ; } if ( CNC_VERSION != cncVersion ) { throw new AeronException ( \"Aeron CnC version does not match: required=\" + CNC_VERSION + \" version=\" + cncVersion ) ; } final ManyToOneRingBuffer toDriverBuffer = new ManyToOneRingBuffer ( CncFileDescriptor . createToDriverBuffer ( cncByteBuffer , cncMetaDataBuffer ) ) ; final long timestamp = toDriverBuffer . consumerHeartbeatTime ( ) ; final long now = System . currentTimeMillis ( ) ; final long timestampAge = now - timestamp ; logger . accept ( \"INFO: Aeron toDriver consumer heartbeat is (ms): \" + timestampAge ) ; return timestampAge <= driverTimeoutMs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Request a driver to run its termination hook . [CODESPLIT] public static boolean requestDriverTermination ( final File directory , final DirectBuffer tokenBuffer , final int tokenOffset , final int tokenLength ) { final File cncFile = new File ( directory , CncFileDescriptor . CNC_FILE ) ; if ( cncFile . exists ( ) && cncFile . length ( ) > 0 ) { final MappedByteBuffer cncByteBuffer = IoUtil . mapExistingFile ( cncFile , \"CnC file\" ) ; try { final UnsafeBuffer cncMetaDataBuffer = CncFileDescriptor . createMetaDataBuffer ( cncByteBuffer ) ; final int cncVersion = cncMetaDataBuffer . getIntVolatile ( cncVersionOffset ( 0 ) ) ; if ( CncFileDescriptor . CNC_VERSION != cncVersion ) { throw new AeronException ( \"Aeron CnC version does not match: required=\" + CNC_VERSION + \" version=\" + cncVersion ) ; } final ManyToOneRingBuffer toDriverBuffer = new ManyToOneRingBuffer ( CncFileDescriptor . createToDriverBuffer ( cncByteBuffer , cncMetaDataBuffer ) ) ; final long clientId = toDriverBuffer . nextCorrelationId ( ) ; final DriverProxy driverProxy = new DriverProxy ( toDriverBuffer , clientId ) ; return driverProxy . terminateDriver ( tokenBuffer , tokenOffset , tokenLength ) ; } finally { IoUtil . unmap ( cncByteBuffer ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the error log to a given { @link PrintStream } [CODESPLIT] public int saveErrorLog ( final PrintStream out ) { final MappedByteBuffer cncByteBuffer = mapExistingCncFile ( null ) ; try { return saveErrorLog ( out , cncByteBuffer ) ; } finally { IoUtil . unmap ( cncByteBuffer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the error log to a given { @link PrintStream } [CODESPLIT] public int saveErrorLog ( final PrintStream out , final ByteBuffer cncByteBuffer ) { if ( null == cncByteBuffer ) { return 0 ; } final UnsafeBuffer cncMetaDataBuffer = CncFileDescriptor . createMetaDataBuffer ( cncByteBuffer ) ; final int cncVersion = cncMetaDataBuffer . getInt ( CncFileDescriptor . cncVersionOffset ( 0 ) ) ; if ( CNC_VERSION != cncVersion ) { throw new AeronException ( \"Aeron CnC version does not match: required=\" + CNC_VERSION + \" version=\" + cncVersion ) ; } int distinctErrorCount = 0 ; final AtomicBuffer buffer = CncFileDescriptor . createErrorLogBuffer ( cncByteBuffer , cncMetaDataBuffer ) ; if ( ErrorLogReader . hasErrors ( buffer ) ) { final SimpleDateFormat dateFormat = new SimpleDateFormat ( \"yyyy-MM-dd HH:mm:ss.SSSZ\" ) ; final ErrorConsumer errorConsumer = ( count , firstTimestamp , lastTimestamp , ex ) -> formatError ( out , dateFormat , count , firstTimestamp , lastTimestamp , ex ) ; distinctErrorCount = ErrorLogReader . read ( buffer , errorConsumer ) ; } out . println ( ) ; out . println ( distinctErrorCount + \" distinct errors observed.\" ) ; return distinctErrorCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the length of a frame from the header as a volatile read . [CODESPLIT] public static int frameLengthVolatile ( final UnsafeBuffer buffer , final int termOffset ) { int frameLength = buffer . getIntVolatile ( termOffset ) ; if ( ByteOrder . nativeOrder ( ) != LITTLE_ENDIAN ) { frameLength = Integer . reverseBytes ( frameLength ) ; } return frameLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the length header for a frame in a memory ordered fashion . [CODESPLIT] public static void frameLengthOrdered ( final UnsafeBuffer buffer , final int termOffset , final int frameLength ) { int length = frameLength ; if ( ByteOrder . nativeOrder ( ) != LITTLE_ENDIAN ) { length = Integer . reverseBytes ( frameLength ) ; } buffer . putIntOrdered ( termOffset , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the type field for a frame . [CODESPLIT] public static void frameType ( final UnsafeBuffer buffer , final int termOffset , final int type ) { buffer . putShort ( typeOffset ( termOffset ) , ( short ) type , LITTLE_ENDIAN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the flags field for a frame . [CODESPLIT] public static void frameFlags ( final UnsafeBuffer buffer , final int termOffset , final byte flags ) { buffer . putByte ( flagsOffset ( termOffset ) , flags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the term offset field for a frame . [CODESPLIT] public static void frameTermOffset ( final UnsafeBuffer buffer , final int termOffset ) { buffer . putInt ( termOffsetOffset ( termOffset ) , termOffset , LITTLE_ENDIAN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the term id field for a frame . [CODESPLIT] public static void frameTermId ( final UnsafeBuffer buffer , final int termOffset , final int termId ) { buffer . putInt ( termIdOffset ( termOffset ) , termId , LITTLE_ENDIAN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from the { @link Sender } to add information to the control packet dispatcher . [CODESPLIT] public void registerForSend ( final NetworkPublication publication ) { publicationBySessionAndStreamId . put ( publication . sessionId ( ) , publication . streamId ( ) , publication ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send contents of a { @link ByteBuffer } to connected address . This is used on the sender side for performance over send ( ByteBuffer SocketAddress ) . [CODESPLIT] public int send ( final ByteBuffer buffer ) { int bytesSent = 0 ; if ( null != sendDatagramChannel ) { final int bytesToSend = buffer . remaining ( ) ; if ( null == multiDestination ) { try { sendHook ( buffer , connectAddress ) ; if ( sendDatagramChannel . isConnected ( ) ) { bytesSent = sendDatagramChannel . write ( buffer ) ; } } catch ( final PortUnreachableException ignore ) { } catch ( final IOException ex ) { sendError ( bytesToSend , ex , connectAddress ) ; } } else { bytesSent = multiDestination . send ( sendDatagramChannel , buffer , this , bytesToSend ) ; } } return bytesSent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the active counter id for a stream based on the recording id . [CODESPLIT] public static int findCounterIdByRecording ( final CountersReader countersReader , final long recordingId ) { final DirectBuffer buffer = countersReader . metaDataBuffer ( ) ; for ( int i = 0 , size = countersReader . maxCounterId ( ) ; i < size ; i ++ ) { if ( countersReader . getCounterState ( i ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( i ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECORDING_POSITION_TYPE_ID && buffer . getLong ( recordOffset + KEY_OFFSET + RECORDING_ID_OFFSET ) == recordingId ) { return i ; } } } return NULL_COUNTER_ID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the active counter id for a stream based on the session id . [CODESPLIT] public static int findCounterIdBySession ( final CountersReader countersReader , final int sessionId ) { final DirectBuffer buffer = countersReader . metaDataBuffer ( ) ; for ( int i = 0 , size = countersReader . maxCounterId ( ) ; i < size ; i ++ ) { if ( countersReader . getCounterState ( i ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( i ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECORDING_POSITION_TYPE_ID && buffer . getInt ( recordOffset + KEY_OFFSET + SESSION_ID_OFFSET ) == sessionId ) { return i ; } } } return NULL_COUNTER_ID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the recording id for a given counter id . [CODESPLIT] public static long getRecordingId ( final CountersReader countersReader , final int counterId ) { final DirectBuffer buffer = countersReader . metaDataBuffer ( ) ; if ( countersReader . getCounterState ( counterId ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( counterId ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECORDING_POSITION_TYPE_ID ) { return buffer . getLong ( recordOffset + KEY_OFFSET + RECORDING_ID_OFFSET ) ; } } return NULL_RECORDING_ID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { @link Image#sourceIdentity () } for the recording . [CODESPLIT] public static String getSourceIdentity ( final CountersReader countersReader , final int counterId ) { final DirectBuffer buffer = countersReader . metaDataBuffer ( ) ; if ( countersReader . getCounterState ( counterId ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( counterId ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECORDING_POSITION_TYPE_ID ) { return buffer . getStringAscii ( recordOffset + KEY_OFFSET + SOURCE_IDENTITY_LENGTH_OFFSET ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is the recording counter still active . [CODESPLIT] public static boolean isActive ( final CountersReader countersReader , final int counterId , final long recordingId ) { final DirectBuffer buffer = countersReader . metaDataBuffer ( ) ; if ( countersReader . getCounterState ( counterId ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( counterId ) ; return buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECORDING_POSITION_TYPE_ID && buffer . getLong ( recordOffset + KEY_OFFSET + RECORDING_ID_OFFSET ) == recordingId ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility for parsing socket addresses from a { @link CharSequence } . Supports hostname : port ipV4Address : port and [ ipV6Address ] : port [CODESPLIT] static InetSocketAddress parse ( final CharSequence cs ) { if ( null == cs || cs . length ( ) == 0 ) { throw new NullPointerException ( \"Input string must not be null or empty\" ) ; } InetSocketAddress address = tryParseIpV4 ( cs ) ; if ( null == address ) { address = tryParseIpV6 ( cs ) ; } if ( null == address ) { throw new IllegalArgumentException ( \"Invalid format: \" + cs ) ; } return address ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public long onStatusMessage ( final StatusMessageFlyweight flyweight , final InetSocketAddress receiverAddress , final long senderLimit , final int initialTermId , final int positionBitsToShift , final long timeNs ) { final long position = computePosition ( flyweight . consumptionTermId ( ) , flyweight . consumptionTermOffset ( ) , positionBitsToShift , initialTermId ) ; final long windowLength = flyweight . receiverWindowLength ( ) ; final long receiverId = flyweight . receiverId ( ) ; final boolean isFromPreferred = isFromPreferred ( flyweight ) ; final long lastPositionPlusWindow = position + windowLength ; boolean isExisting = false ; long minPosition = Long . MAX_VALUE ; final ArrayList < Receiver > receiverList = this . receiverList ; for ( int i = 0 , size = receiverList . size ( ) ; i < size ; i ++ ) { final Receiver receiver = receiverList . get ( i ) ; if ( isFromPreferred && receiverId == receiver . receiverId ) { receiver . lastPosition = Math . max ( position , receiver . lastPosition ) ; receiver . lastPositionPlusWindow = lastPositionPlusWindow ; receiver . timeOfLastStatusMessageNs = timeNs ; isExisting = true ; } minPosition = Math . min ( minPosition , receiver . lastPositionPlusWindow ) ; } if ( isFromPreferred && ! isExisting ) { receiverList . add ( new Receiver ( position , lastPositionPlusWindow , timeNs , receiverId , receiverAddress ) ) ; minPosition = Math . min ( minPosition , lastPositionPlusWindow ) ; } return receiverList . size ( ) > 0 ? Math . max ( senderLimit , minPosition ) : Math . max ( senderLimit , lastPositionPlusWindow ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan for gaps from the scanOffset up to a limit offset . Each gap will be reported to the { @link GapHandler } . [CODESPLIT] public static int scanForGap ( final UnsafeBuffer termBuffer , final int termId , final int termOffset , final int limitOffset , final GapHandler handler ) { int offset = termOffset ; do { final int frameLength = frameLengthVolatile ( termBuffer , offset ) ; if ( frameLength <= 0 ) { break ; } offset += align ( frameLength , FRAME_ALIGNMENT ) ; } while ( offset < limitOffset ) ; final int gapBeginOffset = offset ; if ( offset < limitOffset ) { final int limit = limitOffset - ALIGNED_HEADER_LENGTH ; while ( offset < limit ) { offset += FRAME_ALIGNMENT ; if ( 0 != termBuffer . getIntVolatile ( offset ) ) { offset -= ALIGNED_HEADER_LENGTH ; break ; } } final int gapLength = ( offset - gapBeginOffset ) + ALIGNED_HEADER_LENGTH ; handler . onGap ( termId , gapBeginOffset , gapLength ) ; } return gapBeginOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch a new { @link ClusteredMediaDriver } with provided contexts . [CODESPLIT] public static ClusteredMediaDriver launch ( final MediaDriver . Context driverCtx , final Archive . Context archiveCtx , final ConsensusModule . Context consensusModuleCtx ) { final MediaDriver driver = MediaDriver . launch ( driverCtx . spiesSimulateConnection ( true ) ) ; final Archive archive = Archive . launch ( archiveCtx . mediaDriverAgentInvoker ( driver . sharedAgentInvoker ( ) ) . errorHandler ( driverCtx . errorHandler ( ) ) . errorCounter ( driverCtx . systemCounters ( ) . get ( SystemCounterDescriptor . ERRORS ) ) ) ; final ConsensusModule consensusModule = ConsensusModule . launch ( consensusModuleCtx ) ; return new ClusteredMediaDriver ( driver , archive , consensusModule ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identifier for the receiver to distinguish them for FlowControl strategies . [CODESPLIT] public long receiverId ( ) { final long value ; if ( ByteOrder . nativeOrder ( ) == LITTLE_ENDIAN ) { value = ( ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 7 ) ) << 56 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 6 ) & 0xFF ) << 48 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 5 ) & 0xFF ) << 40 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 4 ) & 0xFF ) << 32 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 3 ) & 0xFF ) << 24 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 2 ) & 0xFF ) << 16 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 1 ) & 0xFF ) << 8 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 0 ) & 0xFF ) ) ) ; } else { value = ( ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 0 ) ) << 56 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 1 ) & 0xFF ) << 48 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 2 ) & 0xFF ) << 40 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 3 ) & 0xFF ) << 32 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 4 ) & 0xFF ) << 24 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 5 ) & 0xFF ) << 16 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 6 ) & 0xFF ) << 8 ) | ( ( ( long ) getByte ( RECEIVER_ID_FIELD_OFFSET + 7 ) & 0xFF ) ) ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identifier for the receiver to distinguish them for FlowControl strategies . [CODESPLIT] public StatusMessageFlyweight receiverId ( final long id ) { if ( ByteOrder . nativeOrder ( ) == LITTLE_ENDIAN ) { putByte ( RECEIVER_ID_FIELD_OFFSET + 7 , ( byte ) ( id >> 56 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 6 , ( byte ) ( id >> 48 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 5 , ( byte ) ( id >> 40 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 4 , ( byte ) ( id >> 32 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 3 , ( byte ) ( id >> 24 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 2 , ( byte ) ( id >> 16 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 1 , ( byte ) ( id >> 8 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 0 , ( byte ) ( id ) ) ; } else { putByte ( RECEIVER_ID_FIELD_OFFSET + 0 , ( byte ) ( id >> 56 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 1 , ( byte ) ( id >> 48 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 2 , ( byte ) ( id >> 40 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 3 , ( byte ) ( id >> 32 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 4 , ( byte ) ( id >> 24 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 5 , ( byte ) ( id >> 16 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 6 , ( byte ) ( id >> 8 ) ) ; putByte ( RECEIVER_ID_FIELD_OFFSET + 7 , ( byte ) ( id ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the Application Specific Feedback ( if present ) from the Status Message . [CODESPLIT] public int applicationSpecificFeedback ( final byte [ ] destination ) { final int frameLength = frameLength ( ) ; int result = 0 ; if ( frameLength > HEADER_LENGTH ) { if ( frameLength > capacity ( ) ) { throw new AeronException ( String . format ( \"SM application specific feedback (%d) is truncated (%d)\" , frameLength - HEADER_LENGTH , capacity ( ) - HEADER_LENGTH ) ) ; } final int copyLength = Math . min ( destination . length , frameLength - HEADER_LENGTH ) ; getBytes ( APP_SPECIFIC_FEEDBACK_FIELD_OFFSET , destination , 0 , copyLength ) ; result = copyLength ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Application Specific Feedback for the Status Message . [CODESPLIT] public StatusMessageFlyweight applicationSpecificFeedback ( final byte [ ] source , final int offset , final int length ) { frameLength ( HEADER_LENGTH + length ) ; putBytes ( APP_SPECIFIC_FEEDBACK_FIELD_OFFSET , source , offset , length ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reload the log from disk . [CODESPLIT] public void reload ( ) { entries . clear ( ) ; indexByLeadershipTermIdMap . clear ( ) ; indexByLeadershipTermIdMap . compact ( ) ; nextEntryIndex = 0 ; byteBuffer . clear ( ) ; try { while ( true ) { final int bytes = fileChannel . read ( byteBuffer ) ; if ( byteBuffer . remaining ( ) == 0 ) { byteBuffer . flip ( ) ; captureEntriesFromBuffer ( byteBuffer , buffer , entries ) ; byteBuffer . clear ( ) ; } if ( - 1 == bytes ) { if ( byteBuffer . position ( ) > 0 ) { byteBuffer . flip ( ) ; captureEntriesFromBuffer ( byteBuffer , buffer , entries ) ; byteBuffer . clear ( ) ; } break ; } } } catch ( final IOException ex ) { LangUtil . rethrowUnchecked ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the last recording id used for a leader ship term . If not found then { @link RecordingPos#NULL_RECORDING_ID } . [CODESPLIT] public long findLastTermRecordingId ( ) { for ( int i = entries . size ( ) - 1 ; i >= 0 ; i -- ) { final Entry entry = entries . get ( i ) ; if ( ENTRY_TYPE_TERM == entry . type ) { return entry . recordingId ; } } return RecordingPos . NULL_RECORDING_ID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the last leadership term in the recording log . [CODESPLIT] public Entry findLastTerm ( ) { for ( int i = entries . size ( ) - 1 ; i >= 0 ; i -- ) { final Entry entry = entries . get ( i ) ; if ( ENTRY_TYPE_TERM == entry . type ) { return entry ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the term { @link Entry } for a given leadership term id . [CODESPLIT] public Entry getTermEntry ( final long leadershipTermId ) { final int index = ( int ) indexByLeadershipTermIdMap . get ( leadershipTermId ) ; if ( NULL_VALUE == index ) { throw new ClusterException ( \"unknown leadershipTermId=\" + leadershipTermId ) ; } return entries . get ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a recovery plan for the cluster that when the steps are replayed will bring the cluster back to the latest stable state . [CODESPLIT] public RecoveryPlan createRecoveryPlan ( final AeronArchive archive , final int serviceCount ) { final ArrayList < Snapshot > snapshots = new ArrayList <> ( ) ; final ArrayList < Log > logs = new ArrayList <> ( ) ; planRecovery ( snapshots , logs , entries , archive , serviceCount ) ; long lastLeadershipTermId = NULL_VALUE ; long lastTermBaseLogPosition = 0 ; long committedLogPosition = - 1 ; long appendedLogPosition = 0 ; final int snapshotStepsSize = snapshots . size ( ) ; if ( snapshotStepsSize > 0 ) { final Snapshot snapshot = snapshots . get ( 0 ) ; lastLeadershipTermId = snapshot . leadershipTermId ; lastTermBaseLogPosition = snapshot . termBaseLogPosition ; appendedLogPosition = snapshot . logPosition ; committedLogPosition = snapshot . logPosition ; } if ( ! logs . isEmpty ( ) ) { final Log log = logs . get ( 0 ) ; lastLeadershipTermId = log . leadershipTermId ; lastTermBaseLogPosition = log . termBaseLogPosition ; appendedLogPosition = log . stopPosition ; committedLogPosition = log . logPosition ; } return new RecoveryPlan ( lastLeadershipTermId , lastTermBaseLogPosition , appendedLogPosition , committedLogPosition , snapshots , logs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a recovery plan that has only snapshots . Used for dynamicJoin snapshot load . [CODESPLIT] public static RecoveryPlan createRecoveryPlan ( final ArrayList < RecordingLog . Snapshot > snapshots ) { long lastLeadershipTermId = NULL_VALUE ; long lastTermBaseLogPosition = 0 ; long committedLogPosition = - 1 ; long appendedLogPosition = 0 ; final int snapshotStepsSize = snapshots . size ( ) ; if ( snapshotStepsSize > 0 ) { final Snapshot snapshot = snapshots . get ( 0 ) ; lastLeadershipTermId = snapshot . leadershipTermId ; lastTermBaseLogPosition = snapshot . termBaseLogPosition ; appendedLogPosition = snapshot . logPosition ; committedLogPosition = snapshot . logPosition ; } return new RecoveryPlan ( lastLeadershipTermId , lastTermBaseLogPosition , appendedLogPosition , committedLogPosition , snapshots , new ArrayList <> ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a log entry for a leadership term . [CODESPLIT] public void appendTerm ( final long recordingId , final long leadershipTermId , final long termBaseLogPosition , final long timestamp ) { final int size = entries . size ( ) ; if ( size > 0 ) { final Entry lastEntry = entries . get ( size - 1 ) ; if ( lastEntry . type != NULL_VALUE && lastEntry . leadershipTermId >= leadershipTermId ) { throw new ClusterException ( \"leadershipTermId out of sequence: previous \" + lastEntry . leadershipTermId + \" this \" + leadershipTermId ) ; } } indexByLeadershipTermIdMap . put ( leadershipTermId , nextEntryIndex ) ; append ( ENTRY_TYPE_TERM , recordingId , leadershipTermId , termBaseLogPosition , NULL_POSITION , timestamp , NULL_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a log entry for a snapshot . [CODESPLIT] public void appendSnapshot ( final long recordingId , final long leadershipTermId , final long termBaseLogPosition , final long logPosition , final long timestamp , final int serviceId ) { final int size = entries . size ( ) ; if ( size > 0 ) { final Entry entry = entries . get ( size - 1 ) ; if ( entry . type == ENTRY_TYPE_TERM && entry . leadershipTermId != leadershipTermId ) { throw new ClusterException ( \"leadershipTermId out of sequence: previous \" + entry . leadershipTermId + \" this \" + leadershipTermId ) ; } } append ( ENTRY_TYPE_SNAPSHOT , recordingId , leadershipTermId , termBaseLogPosition , logPosition , timestamp , serviceId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commit the position reached in a leadership term before a clean shutdown . [CODESPLIT] public void commitLogPosition ( final long leadershipTermId , final long logPosition ) { final int index = getLeadershipTermEntryIndex ( leadershipTermId ) ; commitEntryValue ( index , logPosition , LOG_POSITION_OFFSET ) ; final Entry entry = entries . get ( index ) ; entries . set ( index , new Entry ( entry . recordingId , entry . leadershipTermId , entry . termBaseLogPosition , logPosition , entry . timestamp , entry . serviceId , entry . type , entry . entryIndex ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tombstone an entry in the log so it is no longer valid . [CODESPLIT] public void tombstoneEntry ( final long leadershipTermId , final int entryIndex ) { int index = - 1 ; for ( int i = 0 , size = entries . size ( ) ; i < size ; i ++ ) { final Entry entry = entries . get ( i ) ; if ( entry . leadershipTermId == leadershipTermId && entry . entryIndex == entryIndex ) { index = entry . entryIndex ; if ( ENTRY_TYPE_TERM == entry . type ) { indexByLeadershipTermIdMap . remove ( leadershipTermId ) ; } break ; } } if ( - 1 == index ) { throw new ClusterException ( \"unknown entry index: \" + entryIndex ) ; } buffer . putInt ( 0 , NULL_VALUE , LITTLE_ENDIAN ) ; byteBuffer . limit ( SIZE_OF_INT ) . position ( 0 ) ; final long filePosition = ( index * ( long ) ENTRY_LENGTH ) + ENTRY_TYPE_OFFSET ; try { if ( SIZE_OF_INT != fileChannel . write ( byteBuffer , filePosition ) ) { throw new ClusterException ( \"failed to write field atomically\" ) ; } } catch ( final Exception ex ) { LangUtil . rethrowUnchecked ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connect to the cluster providing { @link Context } for configuration . [CODESPLIT] public static AeronCluster connect ( final AeronCluster . Context ctx ) { Subscription subscription = null ; AsyncConnect asyncConnect = null ; try { ctx . conclude ( ) ; final Aeron aeron = ctx . aeron ( ) ; final long deadlineNs = aeron . context ( ) . nanoClock ( ) . nanoTime ( ) + ctx . messageTimeoutNs ( ) ; subscription = aeron . addSubscription ( ctx . egressChannel ( ) , ctx . egressStreamId ( ) ) ; final IdleStrategy idleStrategy = ctx . idleStrategy ( ) ; asyncConnect = new AsyncConnect ( ctx , subscription , deadlineNs ) ; final AgentInvoker aeronClientInvoker = aeron . conductorAgentInvoker ( ) ; AeronCluster aeronCluster ; while ( null == ( aeronCluster = asyncConnect . poll ( ) ) ) { if ( null != aeronClientInvoker ) { aeronClientInvoker . invoke ( ) ; } idleStrategy . idle ( ) ; } return aeronCluster ; } catch ( final Exception ex ) { if ( ! ctx . ownsAeronClient ( ) ) { CloseHelper . close ( subscription ) ; CloseHelper . close ( asyncConnect ) ; } ctx . close ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Begin an attempt at creating a connection which can be completed by calling { @link AsyncConnect#poll () } until it returns the client before complete it will return null . [CODESPLIT] public static AsyncConnect asyncConnect ( final Context ctx ) { Subscription subscription = null ; try { ctx . conclude ( ) ; final long deadlineNs = ctx . aeron ( ) . context ( ) . nanoClock ( ) . nanoTime ( ) + ctx . messageTimeoutNs ( ) ; subscription = ctx . aeron ( ) . addSubscription ( ctx . egressChannel ( ) , ctx . egressStreamId ( ) ) ; return new AsyncConnect ( ctx , subscription , deadlineNs ) ; } catch ( final Exception ex ) { if ( ! ctx . ownsAeronClient ( ) ) { CloseHelper . quietClose ( subscription ) ; } ctx . close ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close session and release associated resources . [CODESPLIT] public void close ( ) { if ( null != publication && publication . isConnected ( ) ) { closeSession ( ) ; } if ( ! ctx . ownsAeronClient ( ) ) { CloseHelper . close ( subscription ) ; CloseHelper . close ( publication ) ; } ctx . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a partial buffer containing a message plus session header to a cluster . <p > This version of the method will set the timestamp value in the header to zero . [CODESPLIT] public long offer ( final DirectBuffer buffer , final int offset , final int length ) { return publication . offer ( headerBuffer , 0 , INGRESS_HEADER_LENGTH , buffer , offset , length , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish by gathering buffer vectors into a message . The first vector will be replaced by the cluster ingress header so must be left unused . [CODESPLIT] public long offer ( final DirectBufferVector [ ] vectors ) { if ( headerVector != vectors [ 0 ] ) { vectors [ 0 ] = headerVector ; } return publication . offer ( vectors , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a keep alive message to the cluster to keep this session open . <p > <b > Note : < / b > keepalives can fail during a leadership transition . The consumer should continue to call { @link #pollEgress () } to ensure a connection to the new leader is established . [CODESPLIT] public boolean sendKeepAlive ( ) { idleStrategy . reset ( ) ; int attempts = SEND_ATTEMPTS ; while ( true ) { final long result = publication . offer ( keepaliveMsgBuffer , 0 , keepaliveMsgBuffer . capacity ( ) , null ) ; if ( result > 0 ) { return true ; } if ( result == Publication . NOT_CONNECTED || result == Publication . CLOSED ) { return false ; } if ( result == Publication . MAX_POSITION_EXCEEDED ) { throw new ClusterException ( \"unexpected publication state: \" + result ) ; } if ( -- attempts <= 0 ) { break ; } idleStrategy . idle ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be called when a new leader event is delivered . This method needs to be called when using the { @link EgressAdapter } or { @link EgressPoller } rather than { @link #pollEgress () } method . [CODESPLIT] public void onNewLeader ( final long clusterSessionId , final long leadershipTermId , final int leaderMemberId , final String memberEndpoints ) { if ( clusterSessionId != this . clusterSessionId ) { throw new ClusterException ( \"invalid clusterSessionId=\" + clusterSessionId + \" expected \" + this . clusterSessionId ) ; } this . leadershipTermId = leadershipTermId ; this . leaderMemberId = leaderMemberId ; ingressMessageHeaderEncoder . leadershipTermId ( leadershipTermId ) ; sessionKeepAliveEncoder . leadershipTermId ( leadershipTermId ) ; if ( ctx . clusterMemberEndpoints ( ) != null ) { CloseHelper . close ( publication ) ; ctx . clusterMemberEndpoints ( memberEndpoints ) ; updateMemberEndpoints ( memberEndpoints , leaderMemberId ) ; } fragmentAssembler . clear ( ) ; controlledFragmentAssembler . clear ( ) ; egressListener . newLeader ( clusterSessionId , leadershipTermId , leaderMemberId , memberEndpoints ) ; controlledEgressListener . newLeader ( clusterSessionId , leadershipTermId , leaderMemberId , memberEndpoints ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to unblock a log buffer at given position [CODESPLIT] public static boolean unblock ( final UnsafeBuffer [ ] termBuffers , final UnsafeBuffer logMetaDataBuffer , final long blockedPosition , final int termLength ) { final int positionBitsToShift = LogBufferDescriptor . positionBitsToShift ( termLength ) ; final int blockedTermCount = ( int ) ( blockedPosition >> positionBitsToShift ) ; final int blockedOffset = ( int ) blockedPosition & ( termLength - 1 ) ; final int activeTermCount = activeTermCount ( logMetaDataBuffer ) ; if ( activeTermCount == ( blockedTermCount - 1 ) && blockedOffset == 0 ) { final int currentTermId = termId ( rawTailVolatile ( logMetaDataBuffer , indexByTermCount ( activeTermCount ) ) ) ; return rotateLog ( logMetaDataBuffer , activeTermCount , currentTermId ) ; } final int blockedIndex = indexByTermCount ( blockedTermCount ) ; final long rawTail = rawTailVolatile ( logMetaDataBuffer , blockedIndex ) ; final int termId = termId ( rawTail ) ; final int tailOffset = termOffset ( rawTail , termLength ) ; final UnsafeBuffer termBuffer = termBuffers [ blockedIndex ] ; switch ( TermUnblocker . unblock ( logMetaDataBuffer , termBuffer , blockedOffset , tailOffset , termId ) ) { case UNBLOCKED_TO_END : rotateLog ( logMetaDataBuffer , blockedTermCount , termId ) ; // fall through case UNBLOCKED : return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the channel field as ASCII [CODESPLIT] public String channel ( ) { final int length = buffer . getInt ( offset + CHANNEL_OFFSET ) ; lengthOfChannel = SIZE_OF_INT + length ; return buffer . getStringAscii ( offset + CHANNEL_OFFSET , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the channel field as ASCII [CODESPLIT] public ImageMessageFlyweight channel ( final String channel ) { lengthOfChannel = buffer . putStringAscii ( offset + CHANNEL_OFFSET , channel ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that term length is valid and alignment is valid . [CODESPLIT] public static void checkTermLength ( final int termLength ) { if ( termLength < TERM_MIN_LENGTH ) { throw new IllegalStateException ( \"Term length less than min length of \" + TERM_MIN_LENGTH + \": length=\" + termLength ) ; } if ( termLength > TERM_MAX_LENGTH ) { throw new IllegalStateException ( \"Term length more than max length of \" + TERM_MAX_LENGTH + \": length=\" + termLength ) ; } if ( ! BitUtil . isPowerOfTwo ( termLength ) ) { throw new IllegalStateException ( \"Term length not a power of 2: length=\" + termLength ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that page size is valid and alignment is valid . [CODESPLIT] public static void checkPageSize ( final int pageSize ) { if ( pageSize < PAGE_MIN_SIZE ) { throw new IllegalStateException ( \"Page size less than min size of \" + PAGE_MIN_SIZE + \": page size=\" + pageSize ) ; } if ( pageSize > PAGE_MAX_SIZE ) { throw new IllegalStateException ( \"Page size more than max size of \" + PAGE_MAX_SIZE + \": page size=\" + pageSize ) ; } if ( ! BitUtil . isPowerOfTwo ( pageSize ) ) { throw new IllegalStateException ( \"Page size not a power of 2: page size=\" + pageSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare and set the value of the current active term count . [CODESPLIT] public static boolean casActiveTermCount ( final UnsafeBuffer metadataBuffer , final int expectedTermCount , final int updateTermCount ) { return metadataBuffer . compareAndSetInt ( LOG_ACTIVE_TERM_COUNT_OFFSET , expectedTermCount , updateTermCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the current position in absolute number of bytes . [CODESPLIT] public static long computePosition ( final int activeTermId , final int termOffset , final int positionBitsToShift , final int initialTermId ) { final long termCount = activeTermId - initialTermId ; // copes with negative activeTermId on rollover return ( termCount << positionBitsToShift ) + termOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the total length of a log file given the term length . [CODESPLIT] public static long computeLogLength ( final int termLength , final int filePageSize ) { if ( termLength < ( 1024 * 1024 * 1024 ) ) { return align ( ( termLength * PARTITION_COUNT ) + LOG_META_DATA_LENGTH , filePageSize ) ; } return ( PARTITION_COUNT * ( long ) termLength ) + align ( LOG_META_DATA_LENGTH , filePageSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store the default frame header to the log meta data buffer . [CODESPLIT] public static void storeDefaultFrameHeader ( final UnsafeBuffer metadataBuffer , final DirectBuffer defaultHeader ) { if ( defaultHeader . capacity ( ) != HEADER_LENGTH ) { throw new IllegalArgumentException ( \"Default header length not equal to HEADER_LENGTH: length=\" + defaultHeader . capacity ( ) ) ; } metadataBuffer . putInt ( LOG_DEFAULT_FRAME_HEADER_LENGTH_OFFSET , HEADER_LENGTH ) ; metadataBuffer . putBytes ( LOG_DEFAULT_FRAME_HEADER_OFFSET , defaultHeader , 0 , HEADER_LENGTH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply the default header for a message in a term . [CODESPLIT] public static void applyDefaultHeader ( final UnsafeBuffer metadataBuffer , final UnsafeBuffer termBuffer , final int termOffset ) { termBuffer . putBytes ( termOffset , metadataBuffer , LOG_DEFAULT_FRAME_HEADER_OFFSET , HEADER_LENGTH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rotate the log and update the tail counter for the new term . [CODESPLIT] public static boolean rotateLog ( final UnsafeBuffer metadataBuffer , final int termCount , final int termId ) { final int nextTermId = termId + 1 ; final int nextTermCount = termCount + 1 ; final int nextIndex = indexByTermCount ( nextTermCount ) ; final int expectedTermId = nextTermId - PARTITION_COUNT ; long rawTail ; do { rawTail = rawTail ( metadataBuffer , nextIndex ) ; if ( expectedTermId != termId ( rawTail ) ) { break ; } } while ( ! casRawTail ( metadataBuffer , nextIndex , rawTail , packTail ( nextTermId , 0 ) ) ) ; return casActiveTermCount ( metadataBuffer , termCount , nextTermCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the initial value for the termId in the upper bits of the tail counter . [CODESPLIT] public static void initialiseTailWithTermId ( final UnsafeBuffer metadataBuffer , final int partitionIndex , final int termId ) { metadataBuffer . putLong ( TERM_TAIL_COUNTERS_OFFSET + ( partitionIndex * SIZE_OF_LONG ) , packTail ( termId , 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the termOffset from a packed raw tail value . [CODESPLIT] public static int termOffset ( final long rawTail , final long termLength ) { final long tail = rawTail & 0xFFFF_FFFF  L ; return ( int ) Math . min ( tail , termLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the raw value of the tail for the given partition . [CODESPLIT] public static void rawTail ( final UnsafeBuffer metadataBuffer , final int partitionIndex , final long rawTail ) { metadataBuffer . putLong ( TERM_TAIL_COUNTERS_OFFSET + ( SIZE_OF_LONG * partitionIndex ) , rawTail ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the raw value of the tail for the given partition . [CODESPLIT] public static void rawTailVolatile ( final UnsafeBuffer metadataBuffer , final int partitionIndex , final long rawTail ) { metadataBuffer . putLongVolatile ( TERM_TAIL_COUNTERS_OFFSET + ( SIZE_OF_LONG * partitionIndex ) , rawTail ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the raw value of the tail for the current active partition . [CODESPLIT] public static long rawTailVolatile ( final UnsafeBuffer metadataBuffer ) { final int partitionIndex = indexByTermCount ( activeTermCount ( metadataBuffer ) ) ; return metadataBuffer . getLongVolatile ( TERM_TAIL_COUNTERS_OFFSET + ( SIZE_OF_LONG * partitionIndex ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare and set the raw value of the tail for the given partition . [CODESPLIT] public static boolean casRawTail ( final UnsafeBuffer metadataBuffer , final int partitionIndex , final long expectedRawTail , final long updateRawTail ) { final int index = TERM_TAIL_COUNTERS_OFFSET + ( SIZE_OF_LONG * partitionIndex ) ; return metadataBuffer . compareAndSetLong ( index , expectedRawTail , updateRawTail ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch an { @link Archive } with that communicates with an out of process { @link io . aeron . driver . MediaDriver } and await a shutdown signal . [CODESPLIT] public static void main ( final String [ ] args ) { loadPropertiesFiles ( args ) ; try ( Archive ignore = launch ( ) ) { new ShutdownSignalBarrier ( ) . await ( ) ; System . out . println ( \"Shutdown Archive...\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill the token buffer . [CODESPLIT] public TerminateDriverFlyweight tokenBuffer ( final DirectBuffer tokenBuffer , final int tokenOffset , final int tokenLength ) { buffer . putInt ( TOKEN_LENGTH_OFFSET , tokenLength ) ; if ( null != tokenBuffer && tokenLength > 0 ) { buffer . putBytes ( tokenBufferOffset ( ) , tokenBuffer , tokenOffset , tokenLength ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a counter to represent the snapshot services should load on start . [CODESPLIT] public static Counter allocate ( final Aeron aeron , final MutableDirectBuffer tempBuffer , final long leadershipTermId , final long logPosition , final long timestamp , final boolean hasReplay , final long ... snapshotRecordingIds ) { tempBuffer . putLong ( LEADERSHIP_TERM_ID_OFFSET , leadershipTermId ) ; tempBuffer . putLong ( LOG_POSITION_OFFSET , logPosition ) ; tempBuffer . putLong ( TIMESTAMP_OFFSET , timestamp ) ; tempBuffer . putInt ( REPLAY_FLAG_OFFSET , hasReplay ? 1 : 0 ) ; final int serviceCount = snapshotRecordingIds . length ; tempBuffer . putInt ( SERVICE_COUNT_OFFSET , serviceCount ) ; final int keyLength = SNAPSHOT_RECORDING_IDS_OFFSET + ( serviceCount * SIZE_OF_LONG ) ; if ( keyLength > MAX_KEY_LENGTH ) { throw new ClusterException ( keyLength + \" exceeds max key length \" + MAX_KEY_LENGTH ) ; } for ( int i = 0 ; i < serviceCount ; i ++ ) { tempBuffer . putLong ( SNAPSHOT_RECORDING_IDS_OFFSET + ( i * SIZE_OF_LONG ) , snapshotRecordingIds [ i ] ) ; } final int labelOffset = BitUtil . align ( keyLength , SIZE_OF_INT ) ; int labelLength = 0 ; labelLength += tempBuffer . putStringWithoutLengthAscii ( labelOffset + labelLength , NAME ) ; labelLength += tempBuffer . putLongAscii ( keyLength + labelLength , leadershipTermId ) ; labelLength += tempBuffer . putStringWithoutLengthAscii ( labelOffset + labelLength , \" logPosition=\" ) ; labelLength += tempBuffer . putLongAscii ( labelOffset + labelLength , logPosition ) ; labelLength += tempBuffer . putStringWithoutLengthAscii ( labelOffset + labelLength , \" hasReplay=\" + hasReplay ) ; return aeron . addCounter ( RECOVERY_STATE_TYPE_ID , tempBuffer , 0 , keyLength , tempBuffer , labelOffset , labelLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the active counter id for recovery state . [CODESPLIT] public static int findCounterId ( final CountersReader counters ) { final DirectBuffer buffer = counters . metaDataBuffer ( ) ; for ( int i = 0 , size = counters . maxCounterId ( ) ; i < size ; i ++ ) { if ( counters . getCounterState ( i ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( i ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECOVERY_STATE_TYPE_ID ) { return i ; } } } return NULL_COUNTER_ID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the position at which the snapshot was taken . { @link Aeron#NULL_VALUE } if no snapshot for recovery . [CODESPLIT] public static long getLogPosition ( final CountersReader counters , final int counterId ) { final DirectBuffer buffer = counters . metaDataBuffer ( ) ; if ( counters . getCounterState ( counterId ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( counterId ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECOVERY_STATE_TYPE_ID ) { return buffer . getLong ( recordOffset + KEY_OFFSET + LOG_POSITION_OFFSET ) ; } } return NULL_VALUE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has the recovery process got a log to replay? [CODESPLIT] public static boolean hasReplay ( final CountersReader counters , final int counterId ) { final DirectBuffer buffer = counters . metaDataBuffer ( ) ; if ( counters . getCounterState ( counterId ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( counterId ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECOVERY_STATE_TYPE_ID ) { return buffer . getInt ( recordOffset + KEY_OFFSET + REPLAY_FLAG_OFFSET ) == 1 ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the recording id of the snapshot for a service . [CODESPLIT] public static long getSnapshotRecordingId ( final CountersReader counters , final int counterId , final int serviceId ) { final DirectBuffer buffer = counters . metaDataBuffer ( ) ; if ( counters . getCounterState ( counterId ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( counterId ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == RECOVERY_STATE_TYPE_ID ) { final int serviceCount = buffer . getInt ( recordOffset + KEY_OFFSET + SERVICE_COUNT_OFFSET ) ; if ( serviceId < 0 || serviceId >= serviceCount ) { throw new ClusterException ( \"invalid serviceId \" + serviceId + \" for count of \" + serviceCount ) ; } return buffer . getLong ( recordOffset + KEY_OFFSET + SNAPSHOT_RECORDING_IDS_OFFSET + ( serviceId * SIZE_OF_LONG ) ) ; } } throw new ClusterException ( \"Active counter not found \" + counterId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert header flags to an array of chars to be human readable . [CODESPLIT] public static char [ ] flagsToChars ( final short flags ) { final char [ ] chars = new char [ ] { ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' } ; final int length = chars . length ; short mask = ( short ) ( 1 << ( length - 1 ) ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( ( flags & mask ) == mask ) { chars [ i ] = ' ' ; } mask >>= 1 ; } return chars ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new entry for recording loss on a given stream . <p > If not space is remaining in the error report then null is returned . [CODESPLIT] public ReportEntry createEntry ( final long initialBytesLost , final long timestampMs , final int sessionId , final int streamId , final String channel , final String source ) { ReportEntry reportEntry = null ; final int requiredCapacity = CHANNEL_OFFSET + ( SIZE_OF_INT * 2 ) + channel . length ( ) + source . length ( ) ; if ( requiredCapacity <= ( buffer . capacity ( ) - nextRecordOffset ) ) { final int offset = nextRecordOffset ; buffer . putLong ( offset + TOTAL_BYTES_LOST_OFFSET , initialBytesLost ) ; buffer . putLong ( offset + FIRST_OBSERVATION_OFFSET , timestampMs ) ; buffer . putLong ( offset + LAST_OBSERVATION_OFFSET , timestampMs ) ; buffer . putInt ( offset + SESSION_ID_OFFSET , sessionId ) ; buffer . putInt ( offset + STREAM_ID_OFFSET , streamId ) ; final int encodedChannelLength = buffer . putStringAscii ( offset + CHANNEL_OFFSET , channel ) ; buffer . putStringAscii ( offset + CHANNEL_OFFSET + encodedChannelLength , source ) ; buffer . putLongOrdered ( offset + OBSERVATION_COUNT_OFFSET , 1 ) ; reportEntry = new ReportEntry ( buffer , offset ) ; nextRecordOffset += BitUtil . align ( requiredCapacity , ENTRY_ALIGNMENT ) ; } return reportEntry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a partial buffer containing a message plus session header to a cluster . <p > This version of the method will set the timestamp value in the header to { @link Aeron#NULL_VALUE } . [CODESPLIT] public long offer ( final Publication publication , final DirectBuffer buffer , final int offset , final int length ) { return publication . offer ( headerBuffer , 0 , HEADER_LENGTH , buffer , offset , length , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the channel field in ASCII [CODESPLIT] public PublicationMessageFlyweight channel ( final String channel ) { lengthOfChannel = buffer . putStringAscii ( offset + CHANNEL_OFFSET , channel ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to gap fill the current term at a given offset if the gap contains no data . <p > Note : the gap offset plus gap length must end on a { @link FrameDescriptor#FRAME_ALIGNMENT } boundary . [CODESPLIT] public static boolean tryFillGap ( final UnsafeBuffer logMetaDataBuffer , final UnsafeBuffer termBuffer , final int termId , final int gapOffset , final int gapLength ) { int offset = ( gapOffset + gapLength ) - FRAME_ALIGNMENT ; while ( offset >= gapOffset ) { if ( 0 != termBuffer . getInt ( offset ) ) { return false ; } offset -= FRAME_ALIGNMENT ; } applyDefaultHeader ( logMetaDataBuffer , termBuffer , gapOffset ) ; frameType ( termBuffer , gapOffset , HDR_TYPE_PAD ) ; frameTermOffset ( termBuffer , gapOffset ) ; frameTermId ( termBuffer , gapOffset , termId ) ; frameLengthOrdered ( termBuffer , gapOffset , gapLength ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a term in a log buffer and updates a passed { @link Position } so progress is not lost in the event of an exception . [CODESPLIT] public static int read ( final UnsafeBuffer termBuffer , final int termOffset , final FragmentHandler handler , final int fragmentsLimit , final Header header , final ErrorHandler errorHandler , final long currentPosition , final Position subscriberPosition ) { int fragmentsRead = 0 ; int offset = termOffset ; final int capacity = termBuffer . capacity ( ) ; header . buffer ( termBuffer ) ; try { while ( fragmentsRead < fragmentsLimit && offset < capacity ) { final int frameLength = frameLengthVolatile ( termBuffer , offset ) ; if ( frameLength <= 0 ) { break ; } final int frameOffset = offset ; offset += BitUtil . align ( frameLength , FRAME_ALIGNMENT ) ; if ( ! isPaddingFrame ( termBuffer , frameOffset ) ) { header . offset ( frameOffset ) ; handler . onFragment ( termBuffer , frameOffset + HEADER_LENGTH , frameLength - HEADER_LENGTH , header ) ; ++ fragmentsRead ; } } } catch ( final Throwable t ) { errorHandler . onError ( t ) ; } finally { final long newPosition = currentPosition + ( offset - termOffset ) ; if ( newPosition > currentPosition ) { subscriberPosition . setOrdered ( newPosition ) ; } } return fragmentsRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a header to the term buffer in { @link ByteOrder#LITTLE_ENDIAN } format using the minimum instructions . [CODESPLIT] public void write ( final UnsafeBuffer termBuffer , final int offset , final int length , final int termId ) { termBuffer . putLongOrdered ( offset + FRAME_LENGTH_FIELD_OFFSET , versionFlagsType | ( ( - length ) & 0xFFFF_FFFF L ) ) ; UnsafeAccess . UNSAFE . storeFence ( ) ; termBuffer . putLong ( offset + TERM_OFFSET_FIELD_OFFSET , sessionId | offset ) ; termBuffer . putLong ( offset + STREAM_ID_FIELD_OFFSET , streamId | ( ( ( long ) termId ) << 32 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a partial buffer containing a message to a cluster . [CODESPLIT] public long offer ( final DirectBuffer buffer , final int offset , final int length ) { return cluster . offer ( id , responsePublication , buffer , offset , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a region of an underlying log buffer so can can represent a claimed space for use by a publisher . [CODESPLIT] public final void wrap ( final AtomicBuffer buffer , final int offset , final int length ) { this . buffer . wrap ( buffer , offset , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put bytes into the claimed buffer space for a message . To write multiple parts then use { @link #buffer () } and { @link #offset () } . [CODESPLIT] public final BufferClaim putBytes ( final DirectBuffer srcBuffer , final int srcIndex , final int length ) { buffer . putBytes ( HEADER_LENGTH , srcBuffer , srcIndex , length ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commit the message to the log buffer so that is it available to subscribers . [CODESPLIT] public final void commit ( ) { int frameLength = buffer . capacity ( ) ; if ( ByteOrder . nativeOrder ( ) != LITTLE_ENDIAN ) { frameLength = Integer . reverseBytes ( frameLength ) ; } buffer . putIntOrdered ( FRAME_LENGTH_FIELD_OFFSET , frameLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Abort a claim of the message space to the log buffer so that the log can progress by ignoring this claim . [CODESPLIT] public final void abort ( ) { int frameLength = buffer . capacity ( ) ; if ( ByteOrder . nativeOrder ( ) != LITTLE_ENDIAN ) { frameLength = Integer . reverseBytes ( frameLength ) ; } buffer . putShort ( TYPE_FIELD_OFFSET , ( short ) HDR_TYPE_PAD , LITTLE_ENDIAN ) ; buffer . putIntOrdered ( FRAME_LENGTH_FIELD_OFFSET , frameLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start Media Driver as a stand - alone process . [CODESPLIT] public static void main ( final String [ ] args ) { loadPropertiesFiles ( args ) ; final ShutdownSignalBarrier barrier = new ShutdownSignalBarrier ( ) ; final MediaDriver . Context ctx = new MediaDriver . Context ( ) ; ctx . terminationHook ( barrier :: signal ) ; try ( MediaDriver ignore = MediaDriver . launch ( ctx ) ) { barrier . await ( ) ; System . out . println ( \"Shutdown Driver...\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch an isolated MediaDriver embedded in the current process with a provided configuration ctx and a generated aeronDirectoryName ( overwrites configured { @link Context#aeronDirectoryName () } ) that can be retrieved by calling aeronDirectoryName . <p > If the aeronDirectoryName is set as a system property or via context to something different than { @link CommonContext#AERON_DIR_PROP_DEFAULT } then this set value will be used . [CODESPLIT] public static MediaDriver launchEmbedded ( final Context ctx ) { if ( CommonContext . AERON_DIR_PROP_DEFAULT . equals ( ctx . aeronDirectoryName ( ) ) ) { ctx . aeronDirectoryName ( CommonContext . generateRandomDirName ( ) ) ; } return launch ( ctx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdown the media driver by stopping all threads and freeing resources . [CODESPLIT] public void close ( ) { CloseHelper . close ( sharedRunner ) ; CloseHelper . close ( sharedNetworkRunner ) ; CloseHelper . close ( receiverRunner ) ; CloseHelper . close ( senderRunner ) ; CloseHelper . close ( conductorRunner ) ; CloseHelper . close ( sharedInvoker ) ; if ( ctx . useWindowsHighResTimer ( ) && SystemUtil . osName ( ) . startsWith ( \"win\" ) ) { if ( ! wasHighResTimerEnabled ) { HighResolutionTimer . disable ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll for new messages in a stream . If new messages are found beyond the last consumed position then they will be delivered to the { @link FragmentHandler } up to a limited number of fragments as specified . <p > Use a { @link FragmentAssembler } to assemble messages which span multiple fragments . [CODESPLIT] public int poll ( final FragmentHandler fragmentHandler , final int fragmentLimit ) { if ( isClosed ) { return 0 ; } final long position = subscriberPosition . get ( ) ; return TermReader . read ( activeTermBuffer ( position ) , ( int ) position & termLengthMask , fragmentHandler , fragmentLimit , header , errorHandler , position , subscriberPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll for new messages in a stream . If new messages are found beyond the last consumed position then they will be delivered to the { @link ControlledFragmentHandler } up to a limited number of fragments as specified . <p > Use a { @link ControlledFragmentAssembler } to assemble messages which span multiple fragments . [CODESPLIT] public int controlledPoll ( final ControlledFragmentHandler handler , final int fragmentLimit ) { if ( isClosed ) { return 0 ; } int fragmentsRead = 0 ; long initialPosition = subscriberPosition . get ( ) ; int initialOffset = ( int ) initialPosition & termLengthMask ; int resultingOffset = initialOffset ; final UnsafeBuffer termBuffer = activeTermBuffer ( initialPosition ) ; final int capacity = termBuffer . capacity ( ) ; final Header header = this . header ; header . buffer ( termBuffer ) ; try { while ( fragmentsRead < fragmentLimit && resultingOffset < capacity ) { final int length = frameLengthVolatile ( termBuffer , resultingOffset ) ; if ( length <= 0 ) { break ; } final int frameOffset = resultingOffset ; final int alignedLength = BitUtil . align ( length , FRAME_ALIGNMENT ) ; resultingOffset += alignedLength ; if ( isPaddingFrame ( termBuffer , frameOffset ) ) { continue ; } header . offset ( frameOffset ) ; final Action action = handler . onFragment ( termBuffer , frameOffset + HEADER_LENGTH , length - HEADER_LENGTH , header ) ; if ( action == ABORT ) { resultingOffset -= alignedLength ; break ; } ++ fragmentsRead ; if ( action == BREAK ) { break ; } else if ( action == COMMIT ) { initialPosition += ( resultingOffset - initialOffset ) ; initialOffset = resultingOffset ; subscriberPosition . setOrdered ( initialPosition ) ; } } } catch ( final Throwable t ) { errorHandler . onError ( t ) ; } finally { final long resultingPosition = initialPosition + ( resultingOffset - initialOffset ) ; if ( resultingPosition > initialPosition ) { subscriberPosition . setOrdered ( resultingPosition ) ; } } return fragmentsRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peek for new messages in a stream by scanning forward from an initial position . If new messages are found then they will be delivered to the { @link ControlledFragmentHandler } up to a limited position . <p > Use a { @link ControlledFragmentAssembler } to assemble messages which span multiple fragments . Scans must also start at the beginning of a message so that the assembler is reset . [CODESPLIT] public long controlledPeek ( final long initialPosition , final ControlledFragmentHandler handler , final long limitPosition ) { if ( isClosed ) { return 0 ; } validatePosition ( initialPosition ) ; int initialOffset = ( int ) initialPosition & termLengthMask ; int offset = initialOffset ; long position = initialPosition ; final UnsafeBuffer termBuffer = activeTermBuffer ( initialPosition ) ; final int capacity = termBuffer . capacity ( ) ; final Header header = this . header ; header . buffer ( termBuffer ) ; long resultingPosition = initialPosition ; try { while ( position < limitPosition && offset < capacity ) { final int length = frameLengthVolatile ( termBuffer , offset ) ; if ( length <= 0 ) { break ; } final int frameOffset = offset ; final int alignedLength = BitUtil . align ( length , FRAME_ALIGNMENT ) ; offset += alignedLength ; if ( isPaddingFrame ( termBuffer , frameOffset ) ) { position += ( offset - initialOffset ) ; initialOffset = offset ; resultingPosition = position ; continue ; } header . offset ( frameOffset ) ; final Action action = handler . onFragment ( termBuffer , frameOffset + HEADER_LENGTH , length - HEADER_LENGTH , header ) ; if ( action == ABORT ) { break ; } position += ( offset - initialOffset ) ; initialOffset = offset ; if ( ( header . flags ( ) & END_FRAG_FLAG ) == END_FRAG_FLAG ) { resultingPosition = position ; } if ( action == BREAK ) { break ; } } } catch ( final Throwable t ) { errorHandler . onError ( t ) ; } return resultingPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll for new messages in a stream . If new messages are found beyond the last consumed position then they will be delivered to the { @link BlockHandler } up to a limited number of bytes . <p > A scan will terminate if a padding frame is encountered . If first frame in a scan is padding then a block for the padding is notified . If the padding comes after the first frame in a scan then the scan terminates at the offset the padding frame begins . Padding frames are delivered singularly in a block . <p > Padding frames may be for a greater range than the limit offset but only the header needs to be valid so relevant length of the frame is { @link io . aeron . protocol . DataHeaderFlyweight#HEADER_LENGTH } . [CODESPLIT] public int blockPoll ( final BlockHandler handler , final int blockLengthLimit ) { if ( isClosed ) { return 0 ; } final long position = subscriberPosition . get ( ) ; final int termOffset = ( int ) position & termLengthMask ; final UnsafeBuffer termBuffer = activeTermBuffer ( position ) ; final int limitOffset = Math . min ( termOffset + blockLengthLimit , termBuffer . capacity ( ) ) ; final int resultingOffset = TermBlockScanner . scan ( termBuffer , termOffset , limitOffset ) ; final int length = resultingOffset - termOffset ; if ( resultingOffset > termOffset ) { try { final int termId = termBuffer . getInt ( termOffset + TERM_ID_FIELD_OFFSET , LITTLE_ENDIAN ) ; handler . onBlock ( termBuffer , termOffset , length , sessionId , termId ) ; } catch ( final Throwable t ) { errorHandler . onError ( t ) ; } finally { subscriberPosition . setOrdered ( position + length ) ; } } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll for new messages in a stream . If new messages are found beyond the last consumed position then they will be delivered to the { @link RawBlockHandler } up to a limited number of bytes . <p > This method is useful for operations like bulk archiving a stream to file . <p > A scan will terminate if a padding frame is encountered . If first frame in a scan is padding then a block for the padding is notified . If the padding comes after the first frame in a scan then the scan terminates at the offset the padding frame begins . Padding frames are delivered singularly in a block . <p > Padding frames may be for a greater range than the limit offset but only the header needs to be valid so relevant length of the frame is { @link io . aeron . protocol . DataHeaderFlyweight#HEADER_LENGTH } . [CODESPLIT] public int rawPoll ( final RawBlockHandler handler , final int blockLengthLimit ) { if ( isClosed ) { return 0 ; } final long position = subscriberPosition . get ( ) ; final int termOffset = ( int ) position & termLengthMask ; final int activeIndex = indexByPosition ( position , positionBitsToShift ) ; final UnsafeBuffer termBuffer = termBuffers [ activeIndex ] ; final int capacity = termBuffer . capacity ( ) ; final int limitOffset = Math . min ( termOffset + blockLengthLimit , capacity ) ; final int resultingOffset = TermBlockScanner . scan ( termBuffer , termOffset , limitOffset ) ; final int length = resultingOffset - termOffset ; if ( resultingOffset > termOffset ) { try { final long fileOffset = ( ( long ) capacity * activeIndex ) + termOffset ; final int termId = termBuffer . getInt ( termOffset + TERM_ID_FIELD_OFFSET , LITTLE_ENDIAN ) ; handler . onBlock ( logBuffers . fileChannel ( ) , fileOffset , termBuffer , termOffset , length , sessionId , termId ) ; } catch ( final Throwable t ) { errorHandler . onError ( t ) ; } finally { subscriberPosition . setOrdered ( position + length ) ; } } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current position to which the image has advanced on reading this message . [CODESPLIT] public final long position ( ) { final int resultingOffset = BitUtil . align ( termOffset ( ) + frameLength ( ) , FRAME_ALIGNMENT ) ; return computePosition ( termId ( ) , resultingOffset , positionBitsToShift , initialTermId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set channel field in ASCII [CODESPLIT] public SubscriptionMessageFlyweight channel ( final String channel ) { lengthOfChannel = buffer . putStringAscii ( offset + CHANNEL_OFFSET , channel ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new { @link RawLog } in the publications directory for the supplied triplet . [CODESPLIT] public RawLog newPublication ( final String channel , final int sessionId , final int streamId , final long correlationId , final int termBufferLength , final boolean useSparseFiles ) { return newInstance ( publicationsDir , channel , sessionId , streamId , correlationId , termBufferLength , useSparseFiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new { @link RawLog } in the rebuilt publication images directory for the supplied triplet . [CODESPLIT] public RawLog newImage ( final String channel , final int sessionId , final int streamId , final long correlationId , final int termBufferLength , final boolean useSparseFiles ) { return newInstance ( imagesDir , channel , sessionId , streamId , correlationId , termBufferLength , useSparseFiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a counter to represent the heartbeat of a clustered service . [CODESPLIT] public static Counter allocate ( final Aeron aeron , final MutableDirectBuffer tempBuffer , final int serviceId ) { tempBuffer . putInt ( SERVICE_ID_OFFSET , serviceId ) ; final int labelOffset = BitUtil . align ( KEY_LENGTH , SIZE_OF_INT ) ; int labelLength = 0 ; labelLength += tempBuffer . putStringWithoutLengthAscii ( labelOffset + labelLength , NAME ) ; labelLength += tempBuffer . putIntAscii ( labelOffset + labelLength , serviceId ) ; return aeron . addCounter ( SERVICE_HEARTBEAT_TYPE_ID , tempBuffer , 0 , KEY_LENGTH , tempBuffer , labelOffset , labelLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the active counter id for heartbeat of a given service id . [CODESPLIT] public static int findCounterId ( final CountersReader counters , final int serviceId ) { final DirectBuffer buffer = counters . metaDataBuffer ( ) ; for ( int i = 0 , size = counters . maxCounterId ( ) ; i < size ; i ++ ) { if ( counters . getCounterState ( i ) == RECORD_ALLOCATED ) { final int recordOffset = CountersReader . metaDataOffset ( i ) ; if ( buffer . getInt ( recordOffset + TYPE_ID_OFFSET ) == SERVICE_HEARTBEAT_TYPE_ID && buffer . getInt ( recordOffset + KEY_OFFSET + SERVICE_ID_OFFSET ) == serviceId ) { return i ; } } } return NULL_COUNTER_ID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take a snapshot of all the backlog information and group by stream . [CODESPLIT] public Map < StreamCompositeKey , StreamBacklog > snapshot ( ) { final Map < StreamCompositeKey , StreamBacklog > streams = new HashMap <> ( ) ; counters . forEach ( ( counterId , typeId , keyBuffer , label ) -> { if ( ( typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID ) || typeId == SENDER_LIMIT_TYPE_ID || typeId == PER_IMAGE_TYPE_ID || typeId == PUBLISHER_POS_TYPE_ID ) { final StreamCompositeKey key = new StreamCompositeKey ( keyBuffer . getInt ( SESSION_ID_OFFSET ) , keyBuffer . getInt ( STREAM_ID_OFFSET ) , keyBuffer . getStringAscii ( CHANNEL_OFFSET ) ) ; final StreamBacklog streamBacklog = streams . computeIfAbsent ( key , ( ignore ) - > new StreamBacklog ( ) ) ; final long registrationId = keyBuffer . getLong ( REGISTRATION_ID_OFFSET ) ; final long value = counters . getCounterValue ( counterId ) ; switch ( typeId ) { case PublisherLimit . PUBLISHER_LIMIT_TYPE_ID : streamBacklog . createPublisherIfAbsent ( ) . registrationId ( registrationId ) ; streamBacklog . createPublisherIfAbsent ( ) . limit ( value ) ; break ; case PublisherPos . PUBLISHER_POS_TYPE_ID : streamBacklog . createPublisherIfAbsent ( ) . registrationId ( registrationId ) ; streamBacklog . createPublisherIfAbsent ( ) . position ( value ) ; break ; case SenderPos . SENDER_POSITION_TYPE_ID : streamBacklog . createSenderIfAbsent ( ) . registrationId ( registrationId ) ; streamBacklog . createSenderIfAbsent ( ) . position ( value ) ; break ; case SenderLimit . SENDER_LIMIT_TYPE_ID : streamBacklog . createSenderIfAbsent ( ) . registrationId ( registrationId ) ; streamBacklog . createSenderIfAbsent ( ) . limit ( value ) ; break ; case ReceiverHwm . RECEIVER_HWM_TYPE_ID : streamBacklog . createReceiverIfAbsent ( ) . registrationId ( registrationId ) ; streamBacklog . createReceiverIfAbsent ( ) . highWaterMark ( value ) ; break ; case ReceiverPos . RECEIVER_POS_TYPE_ID : streamBacklog . createReceiverIfAbsent ( ) . registrationId ( registrationId ) ; streamBacklog . createReceiverIfAbsent ( ) . position ( value ) ; break ; case SubscriberPos . SUBSCRIBER_POSITION_TYPE_ID : streamBacklog . subscriberBacklogs ( ) . put ( registrationId , new Subscriber ( value ) ) ; break ; } } } ) ; return streams ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a snapshot of the stream backlog with some explanation to a { @link PrintStream } . <p > Each stream will be printed in its own section . [CODESPLIT] public void print ( final PrintStream out ) { final StringBuilder builder = new StringBuilder ( ) ; for ( final Map . Entry < StreamCompositeKey , StreamBacklog > entry : snapshot ( ) . entrySet ( ) ) { builder . setLength ( 0 ) ; final StreamCompositeKey key = entry . getKey ( ) ; builder . append ( \"sessionId=\" ) . append ( key . sessionId ( ) ) . append ( \" streamId=\" ) . append ( key . streamId ( ) ) . append ( \" channel=\" ) . append ( key . channel ( ) ) . append ( \" : \" ) ; final StreamBacklog streamBacklog = entry . getValue ( ) ; if ( streamBacklog . publisher ( ) != null ) { builder . append ( \"\\n┌─for publisher \")  . append ( streamBacklog . publisher ( ) . registrationId ( ) ) . append ( \" the last sampled position is \" ) . append ( streamBacklog . publisher ( ) . position ( ) ) . append ( \" (~\" ) . append ( streamBacklog . publisher ( ) . remainingWindow ( ) ) . append ( \" bytes before back-pressure)\" ) ; final Sender sender = streamBacklog . sender ( ) ; if ( sender != null ) { final long senderBacklog = sender . backlog ( streamBacklog . publisher ( ) . position ( ) ) ; builder . append ( \"\\n└─sender \").ap p e nd(sen d er.reg i strationId());     if ( senderBacklog >= 0 ) { builder . append ( \" has to send \" ) . append ( senderBacklog ) . append ( \" bytes\" ) ; } else { builder . append ( \" is at position \" ) . append ( sender . position ( ) ) ; } builder . append ( \" (\" ) . append ( sender . window ( ) ) . append ( \" bytes remaining in the sender window)\" ) ; } else { builder . append ( \"\\n└─no sender yet...\");   } } if ( streamBacklog . receiver ( ) != null ) { builder . append ( \"\\n┌─receiver \")  . append ( streamBacklog . receiver ( ) . registrationId ( ) ) . append ( \" is at position \" ) . append ( streamBacklog . receiver ( ) . position ( ) ) ; final Iterator < Map . Entry < Long , Subscriber > > subscriberIterator = streamBacklog . subscriberBacklogs ( ) . entrySet ( ) . iterator ( ) ; while ( subscriberIterator . hasNext ( ) ) { final Map . Entry < Long , Subscriber > subscriber = subscriberIterator . next ( ) ; builder . append ( subscriberIterator . hasNext ( ) ? \"\\n├\" : \" n└\")  . append ( \"─subscriber \")  . append ( subscriber . getKey ( ) ) . append ( \" has \" ) . append ( subscriber . getValue ( ) . backlog ( streamBacklog . receiver ( ) . highWaterMark ( ) ) ) . append ( \" backlog bytes\" ) ; } } builder . append ( ' ' ) ; out . println ( builder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan for gaps and handle received data . <p > The handler keeps track from scan to scan what is a gap and what must have been repaired . [CODESPLIT] public long scan ( final UnsafeBuffer termBuffer , final long rebuildPosition , final long hwmPosition , final long nowNs , final int termLengthMask , final int positionBitsToShift , final int initialTermId ) { boolean lossFound = false ; int rebuildOffset = ( int ) rebuildPosition & termLengthMask ; if ( rebuildPosition < hwmPosition ) { final int rebuildTermCount = ( int ) ( rebuildPosition >>> positionBitsToShift ) ; final int hwmTermCount = ( int ) ( hwmPosition >>> positionBitsToShift ) ; final int rebuildTermId = initialTermId + rebuildTermCount ; final int hwmTermOffset = ( int ) hwmPosition & termLengthMask ; final int limitOffset = rebuildTermCount == hwmTermCount ? hwmTermOffset : termLengthMask + 1 ; rebuildOffset = scanForGap ( termBuffer , rebuildTermId , rebuildOffset , limitOffset , this ) ; if ( rebuildOffset < limitOffset ) { if ( scannedTermOffset != activeTermOffset || scannedTermId != activeTermId ) { activateGap ( nowNs ) ; lossFound = true ; } checkTimerExpiry ( nowNs ) ; } } return pack ( rebuildOffset , lossFound ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a partial buffer containing a message . [CODESPLIT] public long offer ( final DirectBuffer buffer , final int offset , final int length , final ReservedValueSupplier reservedValueSupplier ) { long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final int termCount = activeTermCount ( logMetaDataBuffer ) ; final TermAppender termAppender = termAppenders [ indexByTermCount ( termCount ) ] ; final long rawTail = termAppender . rawTailVolatile ( ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; final int termId = termId ( rawTail ) ; final long position = computeTermBeginPosition ( termId , positionBitsToShift , initialTermId ) + termOffset ; if ( termCount != ( termId - initialTermId ) ) { return ADMIN_ACTION ; } if ( position < limit ) { final int resultingOffset ; if ( length <= maxPayloadLength ) { checkPositiveLength ( length ) ; resultingOffset = termAppender . appendUnfragmentedMessage ( headerWriter , buffer , offset , length , reservedValueSupplier , termId ) ; } else { checkMaxMessageLength ( length ) ; resultingOffset = termAppender . appendFragmentedMessage ( headerWriter , buffer , offset , length , maxPayloadLength , reservedValueSupplier , termId ) ; } newPosition = newPosition ( termCount , ( int ) termOffset , termId , position , resultingOffset ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - blocking publish of a message composed of two parts e . g . a header and encapsulated payload . [CODESPLIT] public long offer ( final DirectBuffer bufferOne , final int offsetOne , final int lengthOne , final DirectBuffer bufferTwo , final int offsetTwo , final int lengthTwo , final ReservedValueSupplier reservedValueSupplier ) { long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final int termCount = activeTermCount ( logMetaDataBuffer ) ; final TermAppender termAppender = termAppenders [ indexByTermCount ( termCount ) ] ; final long rawTail = termAppender . rawTailVolatile ( ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; final int termId = termId ( rawTail ) ; final long position = computeTermBeginPosition ( termId , positionBitsToShift , initialTermId ) + termOffset ; if ( termCount != ( termId - initialTermId ) ) { return ADMIN_ACTION ; } final int length = validateAndComputeLength ( lengthOne , lengthTwo ) ; if ( position < limit ) { final int resultingOffset ; if ( length <= maxPayloadLength ) { resultingOffset = termAppender . appendUnfragmentedMessage ( headerWriter , bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , reservedValueSupplier , termId ) ; } else { checkMaxMessageLength ( length ) ; resultingOffset = termAppender . appendFragmentedMessage ( headerWriter , bufferOne , offsetOne , lengthOne , bufferTwo , offsetTwo , lengthTwo , maxPayloadLength , reservedValueSupplier , termId ) ; } newPosition = newPosition ( termCount , ( int ) termOffset , termId , position , resultingOffset ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to claim a range in the publication log into which a message can be written with zero copy semantics . Once the message has been written then { @link BufferClaim#commit () } should be called thus making it available . <p > <b > Note : < / b > This method can only be used for message lengths less than MTU length minus header . If the claim is held for more than the aeron . publication . unblock . timeout system property then the driver will assume the publication thread is dead and will unblock the claim thus allowing other threads to make progress or to reach end - of - stream ( EOS ) . <pre > { @code final BufferClaim bufferClaim = new BufferClaim () ; // Can be stored and reused to avoid allocation [CODESPLIT] public long tryClaim ( final int length , final BufferClaim bufferClaim ) { checkPayloadLength ( length ) ; long newPosition = CLOSED ; if ( ! isClosed ) { final long limit = positionLimit . getVolatile ( ) ; final int termCount = activeTermCount ( logMetaDataBuffer ) ; final TermAppender termAppender = termAppenders [ indexByTermCount ( termCount ) ] ; final long rawTail = termAppender . rawTailVolatile ( ) ; final long termOffset = rawTail & 0xFFFF_FFFF  L ; final int termId = termId ( rawTail ) ; final long position = computeTermBeginPosition ( termId , positionBitsToShift , initialTermId ) + termOffset ; if ( termCount != ( termId - initialTermId ) ) { return ADMIN_ACTION ; } if ( position < limit ) { final int resultingOffset = termAppender . claim ( headerWriter , length , bufferClaim , termId ) ; newPosition = newPosition ( termCount , ( int ) termOffset , termId , position , resultingOffset ) ; } else { newPosition = backPressureStatus ( position , length ) ; } } return newPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan a term buffer for a block of message fragments from an offset up to a limitOffset . <p > A scan will terminate if a padding frame is encountered . If first frame in a scan is padding then a block for the padding is notified . If the padding comes after the first frame in a scan then the scan terminates at the offset the padding frame begins . Padding frames are delivered singularly in a block . <p > Padding frames may be for a greater range than the limit offset but only the header needs to be valid so relevant length of the frame is { @link io . aeron . protocol . DataHeaderFlyweight#HEADER_LENGTH } . [CODESPLIT] public static int scan ( final UnsafeBuffer termBuffer , final int termOffset , final int limitOffset ) { int offset = termOffset ; while ( offset < limitOffset ) { final int frameLength = frameLengthVolatile ( termBuffer , offset ) ; if ( frameLength <= 0 ) { break ; } final int alignedFrameLength = align ( frameLength , FRAME_ALIGNMENT ) ; if ( isPaddingFrame ( termBuffer , offset ) ) { if ( termOffset == offset ) { offset += alignedFrameLength ; } break ; } if ( offset + alignedFrameLength > limitOffset ) { break ; } offset += alignedFrameLength ; } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch an { @link ConsensusModule } with that communicates with an out of process { @link io . aeron . archive . Archive } and { @link io . aeron . driver . MediaDriver } then awaits shutdown signal . [CODESPLIT] public static void main ( final String [ ] args ) { loadPropertiesFiles ( args ) ; try ( ConsensusModule consensusModule = launch ( ) ) { consensusModule . context ( ) . shutdownSignalBarrier ( ) . await ( ) ; System . out . println ( \"Shutdown ConsensusModule...\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a counter for tracking the last heartbeat of an entity . [CODESPLIT] public static AtomicCounter allocate ( final MutableDirectBuffer tempBuffer , final String name , final int typeId , final CountersManager countersManager , final long registrationId ) { return new AtomicCounter ( countersManager . valuesBuffer ( ) , allocateCounterId ( tempBuffer , name , typeId , countersManager , registrationId ) , countersManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an Aeron instance and connect to the media driver . <p > Threads required for interacting with the media driver are created and managed within the Aeron instance . <p > If an exception occurs while trying to establish a connection then the { @link Context#close () } method will be called on the passed context . [CODESPLIT] public static Aeron connect ( final Context ctx ) { try { final Aeron aeron = new Aeron ( ctx ) ; if ( ctx . useConductorAgentInvoker ( ) ) { aeron . conductorInvoker . start ( ) ; } else { AgentRunner . startOnThread ( aeron . conductorRunner , ctx . threadFactory ( ) ) ; } return aeron ; } catch ( final Exception ex ) { ctx . close ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out the values from { @link #countersReader () } which can be useful for debugging . [CODESPLIT] public void printCounters ( final PrintStream out ) { final CountersReader counters = countersReader ( ) ; counters . forEach ( ( value , id , label ) -> out . format ( \"%3d: %,20d - %s%n\" , id , value , label ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new { @link Subscription } for subscribing to messages from publishers . <p > This method will override the default handlers from the { @link Aeron . Context } i . e . { @link Aeron . Context#availableImageHandler ( AvailableImageHandler ) } and { @link Aeron . Context#unavailableImageHandler ( UnavailableImageHandler ) } . Null values are valid and will result in no action being taken . [CODESPLIT] public Subscription addSubscription ( final String channel , final int streamId , final AvailableImageHandler availableImageHandler , final UnavailableImageHandler unavailableImageHandler ) { return conductor . addSubscription ( channel , streamId , availableImageHandler , unavailableImageHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a counter on the media driver and return a { @link Counter } for it . <p > The counter should be freed by calling { @link Counter#close () } . [CODESPLIT] public Counter addCounter ( final int typeId , final DirectBuffer keyBuffer , final int keyOffset , final int keyLength , final DirectBuffer labelBuffer , final int labelOffset , final int labelLength ) { return conductor . addCounter ( typeId , keyBuffer , keyOffset , keyLength , labelBuffer , labelOffset , labelLength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is called automatically by { @link Aeron#connect ( Aeron . Context ) } and its overloads . There is no need to call it from a client application . It is responsible for providing default values for options that are not individually changed through field setters . [CODESPLIT] public Context conclude ( ) { super . conclude ( ) ; if ( null == clientLock ) { clientLock = new ReentrantLock ( ) ; } if ( null == epochClock ) { epochClock = new SystemEpochClock ( ) ; } if ( null == nanoClock ) { nanoClock = new SystemNanoClock ( ) ; } if ( null == idleStrategy ) { idleStrategy = new SleepingMillisIdleStrategy ( Configuration . IDLE_SLEEP_MS ) ; } if ( cncFile ( ) != null ) { connectToDriver ( ) ; } interServiceTimeoutNs = CncFileDescriptor . clientLivenessTimeout ( cncMetaDataBuffer ) ; if ( interServiceTimeoutNs <= keepAliveIntervalNs ) { throw new ConfigurationException ( \"interServiceTimeoutNs=\" + interServiceTimeoutNs + \" <= keepAliveIntervalNs=\" + keepAliveIntervalNs ) ; } if ( null == toDriverBuffer ) { toDriverBuffer = new ManyToOneRingBuffer ( CncFileDescriptor . createToDriverBuffer ( cncByteBuffer , cncMetaDataBuffer ) ) ; } if ( null == toClientBuffer ) { toClientBuffer = new CopyBroadcastReceiver ( new BroadcastReceiver ( CncFileDescriptor . createToClientsBuffer ( cncByteBuffer , cncMetaDataBuffer ) ) ) ; } if ( countersMetaDataBuffer ( ) == null ) { countersMetaDataBuffer ( CncFileDescriptor . createCountersMetaDataBuffer ( cncByteBuffer , cncMetaDataBuffer ) ) ; } if ( countersValuesBuffer ( ) == null ) { countersValuesBuffer ( CncFileDescriptor . createCountersValuesBuffer ( cncByteBuffer , cncMetaDataBuffer ) ) ; } if ( null == logBuffersFactory ) { logBuffersFactory = new MappedLogBuffersFactory ( ) ; } if ( null == errorHandler ) { errorHandler = Configuration . DEFAULT_ERROR_HANDLER ; } if ( null == driverProxy ) { clientId = toDriverBuffer . nextCorrelationId ( ) ; driverProxy = new DriverProxy ( toDriverBuffer , clientId ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean up all resources that the client uses to communicate with the Media Driver . [CODESPLIT] public void close ( ) { final MappedByteBuffer cncByteBuffer = this . cncByteBuffer ; this . cncByteBuffer = null ; IoUtil . unmap ( cncByteBuffer ) ; super . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dispatch a descriptor message to a consumer by reading the fields in the correct order . [CODESPLIT] public static void dispatchDescriptor ( final RecordingDescriptorDecoder decoder , final RecordingDescriptorConsumer consumer ) { consumer . onRecordingDescriptor ( decoder . controlSessionId ( ) , decoder . correlationId ( ) , decoder . recordingId ( ) , decoder . startTimestamp ( ) , decoder . stopTimestamp ( ) , decoder . startPosition ( ) , decoder . stopPosition ( ) , decoder . initialTermId ( ) , decoder . segmentFileLength ( ) , decoder . termBufferLength ( ) , decoder . mtuLength ( ) , decoder . sessionId ( ) , decoder . streamId ( ) , decoder . strippedChannel ( ) , decoder . originalChannel ( ) , decoder . sourceIdentity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a packet of frames into the log at the appropriate termOffset as indicated by the term termOffset header . <p > If the packet has already been inserted then this is a noop . [CODESPLIT] public static void insert ( final UnsafeBuffer termBuffer , final int termOffset , final UnsafeBuffer packet , final int length ) { if ( 0 == termBuffer . getInt ( termOffset ) ) { termBuffer . putBytes ( termOffset + HEADER_LENGTH , packet , HEADER_LENGTH , length - HEADER_LENGTH ) ; termBuffer . putLong ( termOffset + 24 , packet . getLong ( 24 ) ) ; termBuffer . putLong ( termOffset + 16 , packet . getLong ( 16 ) ) ; termBuffer . putLong ( termOffset + 8 , packet . getLong ( 8 ) ) ; termBuffer . putLongOrdered ( termOffset , packet . getLong ( 0 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a CapacityByteArrayOutputStream configured such that its initial slab size is determined by { @link #initialSlabSizeHeuristic } with targetCapacity == maxCapacityHint [CODESPLIT] public static CapacityByteArrayOutputStream withTargetNumSlabs ( int minSlabSize , int maxCapacityHint , int targetNumSlabs , ByteBufferAllocator allocator ) { return new CapacityByteArrayOutputStream ( initialSlabSizeHeuristic ( minSlabSize , maxCapacityHint , targetNumSlabs ) , maxCapacityHint , allocator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the new slab is guaranteed to be at least minimumSize [CODESPLIT] private void addSlab ( int minimumSize ) { int nextSlabSize ; if ( bytesUsed == 0 ) { nextSlabSize = initialSlabSize ; } else if ( bytesUsed > maxCapacityHint / 5 ) { // to avoid an overhead of up to twice the needed size, we get linear when approaching target page size nextSlabSize = maxCapacityHint / 5 ; } else { // double the size every time nextSlabSize = bytesUsed ; } if ( nextSlabSize < minimumSize ) { LOG . debug ( \"slab size {} too small for value of size {}. Bumping up slab size\" , nextSlabSize , minimumSize ) ; nextSlabSize = minimumSize ; } LOG . debug ( \"used {} slabs, adding new slab of size {}\" , slabs . size ( ) , nextSlabSize ) ; this . currentSlab = allocator . allocate ( nextSlabSize ) ; this . slabs . add ( currentSlab ) ; this . bytesAllocated += nextSlabSize ; this . currentSlabIndex = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the complete contents of this buffer to the specified output stream argument . the output stream s write method <code > out . write ( slab 0 slab . length ) < / code > ) will be called once per slab . [CODESPLIT] public void writeTo ( OutputStream out ) throws IOException { for ( int i = 0 ; i < slabs . size ( ) - 1 ; i ++ ) { writeToOutput ( out , slabs . get ( i ) , slabs . get ( i ) . position ( ) ) ; } writeToOutput ( out , currentSlab , currentSlabIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When re - using an instance with reset it will adjust slab size based on previous data size . The intent is to reuse the same instance for the same type of data ( for example the same column ) . The assumption is that the size in the buffer will be consistent . [CODESPLIT] public void reset ( ) { // readjust slab size. // 7 = 2^3 - 1 so that doubling the initial size 3 times will get to the same size this . initialSlabSize = max ( bytesUsed / 7 , initialSlabSize ) ; LOG . debug ( \"initial slab of size {}\" , initialSlabSize ) ; for ( ByteBuffer slab : slabs ) { allocator . release ( slab ) ; } this . slabs . clear ( ) ; this . bytesAllocated = 0 ; this . bytesUsed = 0 ; this . currentSlab = EMPTY_SLAB ; this . currentSlabIndex = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the byte stored at position index in this stream with value [CODESPLIT] public void setByte ( long index , byte value ) { checkArgument ( index < bytesUsed , \"Index: \" + index + \" is >= the current size of: \" + bytesUsed ) ; long seen = 0 ; for ( int i = 0 ; i < slabs . size ( ) ; i ++ ) { ByteBuffer slab = slabs . get ( i ) ; if ( index < seen + slab . limit ( ) ) { // ok found index slab . put ( ( int ) ( index - seen ) , value ) ; break ; } seen += slab . limit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the data from the specified statistics to this builder [CODESPLIT] public void add ( Statistics < ? > stats ) { if ( stats . hasNonNullValue ( ) ) { nullPages . add ( false ) ; Object min = stats . genericGetMin ( ) ; Object max = stats . genericGetMax ( ) ; addMinMax ( min , max ) ; pageIndexes . add ( nextPageIndex ) ; minMaxSize += sizeOf ( min ) ; minMaxSize += sizeOf ( max ) ; } else { nullPages . add ( true ) ; } nullCounts . add ( stats . getNumNulls ( ) ) ; ++ nextPageIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "min [ i ] > = min [ i + 1 ] && max [ i ] > = max [ i + 1 ] [CODESPLIT] private boolean isDescending ( PrimitiveComparator < Binary > comparator ) { for ( int i = 1 , n = pageIndexes . size ( ) ; i < n ; ++ i ) { if ( compareMinValues ( comparator , i - 1 , i ) < 0 || compareMaxValues ( comparator , i - 1 , i ) < 0 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called to initialize the column reader from a part of a page . [CODESPLIT] @ Deprecated public void initFromPage ( int valueCount , ByteBuffer page , int offset ) throws IOException { if ( offset < 0 ) { throw new IllegalArgumentException ( \"Illegal offset: \" + offset ) ; } actualOffset = offset ; ByteBuffer pageWithOffset = page . duplicate ( ) ; pageWithOffset . position ( offset ) ; initFromPage ( valueCount , ByteBufferInputStream . wrap ( pageWithOffset ) ) ; actualOffset = - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same functionality as method of the same name that takes a ByteBuffer instead of a byte [] . [CODESPLIT] @ Deprecated public void initFromPage ( int valueCount , byte [ ] page , int offset ) throws IOException { this . initFromPage ( valueCount , ByteBuffer . wrap ( page ) , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called to initialize the column reader from a part of a page . [CODESPLIT] public void initFromPage ( int valueCount , ByteBufferInputStream in ) throws IOException { if ( actualOffset != - 1 ) { throw new UnsupportedOperationException ( \"Either initFromPage(int, ByteBuffer, int) or initFromPage(int, ByteBufferInputStream) must be implemented in \" + getClass ( ) . getName ( ) ) ; } initFromPage ( valueCount , in . slice ( valueCount ) , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the subset of columns to read ( projection pushdown ) . Specified as an Avro schema the requested projection is converted into a Parquet schema for Parquet column projection . <p > This is useful if the full schema is large and you only want to read a few columns since it saves time by not reading unused columns . <p > If a requested projection is set then the Avro schema used for reading must be compatible with the projection . For instance if a column is not included in the projection then it must either not be included or be optional in the read schema . Use { [CODESPLIT] public static void setRequestedProjection ( Job job , Schema requestedProjection ) { AvroReadSupport . setRequestedProjection ( ContextUtil . getConfiguration ( job ) , requestedProjection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the Avro schema to use for reading . If not set the Avro schema used for writing is used . <p > Differences between the read and write schemas are resolved using <a href = http : // avro . apache . org / docs / current / spec . html#Schema + Resolution > Avro s schema resolution rules< / a > . [CODESPLIT] public static void setAvroReadSchema ( Job job , Schema avroReadSchema ) { AvroReadSupport . setAvroReadSchema ( ContextUtil . getConfiguration ( job ) , avroReadSchema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses an instance of the specified { [CODESPLIT] public static void setAvroDataSupplier ( Job job , Class < ? extends AvroDataSupplier > supplierClass ) { AvroReadSupport . setAvroDataSupplier ( ContextUtil . getConfiguration ( job ) , supplierClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : making the assumption that getConverter ( i ) is only called once is that valid? [CODESPLIT] @ Override public Converter getConverter ( int fieldIndex ) { // get the real converter from the delegate Converter delegateConverter = checkNotNull ( delegate . getConverter ( fieldIndex ) , \"delegate converter\" ) ; // determine the indexFieldPath for the converter proxy we're about to make, which is // this converter's path + the requested fieldIndex List < Integer > newIndexFieldPath = new ArrayList < Integer > ( indexFieldPath . size ( ) + 1 ) ; newIndexFieldPath . addAll ( indexFieldPath ) ; newIndexFieldPath . add ( fieldIndex ) ; if ( delegateConverter . isPrimitive ( ) ) { PrimitiveColumnIO columnIO = getColumnIO ( newIndexFieldPath ) ; ColumnPath columnPath = ColumnPath . get ( columnIO . getColumnDescriptor ( ) . getPath ( ) ) ; ValueInspector [ ] valueInspectors = getValueInspectors ( columnPath ) ; return new FilteringPrimitiveConverter ( delegateConverter . asPrimitiveConverter ( ) , valueInspectors ) ; } else { return new FilteringGroupConverter ( delegateConverter . asGroupConverter ( ) , newIndexFieldPath , valueInspectorsByColumn , columnIOsByIndexFieldPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the row ranges containing the indexes of the rows might match the specified filter . [CODESPLIT] public static RowRanges calculateRowRanges ( FilterCompat . Filter filter , ColumnIndexStore columnIndexStore , Set < ColumnPath > paths , long rowCount ) { return filter . accept ( new FilterCompat . Visitor < RowRanges > ( ) { @ Override public RowRanges visit ( FilterPredicateCompat filterPredicateCompat ) { try { return filterPredicateCompat . getFilterPredicate ( ) . accept ( new ColumnIndexFilter ( columnIndexStore , paths , rowCount ) ) ; } catch ( MissingOffsetIndexException e ) { LOGGER . info ( e . getMessage ( ) ) ; return RowRanges . createSingle ( rowCount ) ; } } @ Override public RowRanges visit ( UnboundRecordFilterCompat unboundRecordFilterCompat ) { return RowRanges . createSingle ( rowCount ) ; } @ Override public RowRanges visit ( NoOpFilter noOpFilter ) { return RowRanges . createSingle ( rowCount ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this method when setting up your Hadoop job if reading into a Thrift object that is not encoded into the parquet - serialized thrift metadata ( for example writing with Apache Thrift but reading back into Twitter Scrooge version of the same thrift definition or a different but compatible Apache Thrift class ) . [CODESPLIT] public static < T > void setThriftClass ( JobConf conf , Class < T > klass ) { conf . set ( ThriftReadSupport . THRIFT_READ_CLASS_KEY , klass . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "1 anonymous element array_element [CODESPLIT] private static GroupType convertArrayType ( final String name , final ListTypeInfo typeInfo ) { final TypeInfo subType = typeInfo . getListElementTypeInfo ( ) ; return listWrapper ( name , listType ( ) , new GroupType ( Repetition . REPEATED , ParquetHiveSerDe . ARRAY . toString ( ) , convertType ( \"array_element\" , subType ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An optional group containing multiple elements [CODESPLIT] private static GroupType convertStructType ( final String name , final StructTypeInfo typeInfo ) { final List < String > columnNames = typeInfo . getAllStructFieldNames ( ) ; final List < TypeInfo > columnTypes = typeInfo . getAllStructFieldTypeInfos ( ) ; return new GroupType ( Repetition . OPTIONAL , name , convertTypes ( columnNames , columnTypes ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "2 elements : key value [CODESPLIT] private static GroupType convertMapType ( final String name , final MapTypeInfo typeInfo ) { final Type keyType = convertType ( ParquetHiveSerDe . MAP_KEY . toString ( ) , typeInfo . getMapKeyTypeInfo ( ) , Repetition . REQUIRED ) ; final Type valueType = convertType ( ParquetHiveSerDe . MAP_VALUE . toString ( ) , typeInfo . getMapValueTypeInfo ( ) ) ; return ConversionPatterns . mapType ( Repetition . OPTIONAL , name , keyType , valueType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands a string with braces ( {} ) into all of its possible permutations . We call anything inside of {} braces a one - of group . [CODESPLIT] public static List < String > expand ( String globPattern ) { return GlobExpanderImpl . expand ( GlobParser . parse ( globPattern ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates a new RowRanges object with the single range [ 0 rowCount - 1 ] . [CODESPLIT] static RowRanges createSingle ( long rowCount ) { RowRanges ranges = new RowRanges ( ) ; ranges . add ( new Range ( 0 , rowCount - 1 ) ) ; return ranges ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates a new RowRanges object with the following ranges . [ firstRowIndex [ 0 ] lastRowIndex [ 0 ]] [ firstRowIndex [ 1 ] lastRowIndex [ 1 ]] ... [ firstRowIndex [ n ] lastRowIndex [ n ]] ( See OffsetIndex . getFirstRowIndex and OffsetIndex . getLastRowIndex for details . ) [CODESPLIT] static RowRanges create ( long rowCount , PrimitiveIterator . OfInt pageIndexes , OffsetIndex offsetIndex ) { RowRanges ranges = new RowRanges ( ) ; while ( pageIndexes . hasNext ( ) ) { int pageIndex = pageIndexes . nextInt ( ) ; ranges . add ( new Range ( offsetIndex . getFirstRowIndex ( pageIndex ) , offsetIndex . getLastRowIndex ( pageIndex , rowCount ) ) ) ; } return ranges ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Calculates the union of the two specified RowRanges object . The union of two range is calculated if there are no elements between them . Otherwise the two disjunct ranges are stored separately . For example : [ 113 241 ] ∪ [ 221 340 ] = [ 113 330 ] [ 113 230 ] ∪ [ 231 340 ] = [ 113 340 ] while [ 113 230 ] ∪ [ 232 340 ] = [ 113 230 ] [ 232 340 ] [CODESPLIT] static RowRanges union ( RowRanges left , RowRanges right ) { RowRanges result = new RowRanges ( ) ; Iterator < Range > it1 = left . ranges . iterator ( ) ; Iterator < Range > it2 = right . ranges . iterator ( ) ; if ( it2 . hasNext ( ) ) { Range range2 = it2 . next ( ) ; while ( it1 . hasNext ( ) ) { Range range1 = it1 . next ( ) ; if ( range1 . isAfter ( range2 ) ) { result . add ( range2 ) ; range2 = range1 ; Iterator < Range > tmp = it1 ; it1 = it2 ; it2 = tmp ; } else { result . add ( range1 ) ; } } result . add ( range2 ) ; } else { it2 = it1 ; } while ( it2 . hasNext ( ) ) { result . add ( it2 . next ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Calculates the intersection of the two specified RowRanges object . Two ranges intersect if they have common elements otherwise the result is empty . For example : [ 113 241 ] ∩ [ 221 340 ] = [ 221 241 ] while [ 113 230 ] ∩ [ 231 340 ] = <EMPTY > [CODESPLIT] static RowRanges intersection ( RowRanges left , RowRanges right ) { RowRanges result = new RowRanges ( ) ; int rightIndex = 0 ; for ( Range l : left . ranges ) { for ( int i = rightIndex , n = right . ranges . size ( ) ; i < n ; ++ i ) { Range r = right . ranges . get ( i ) ; if ( l . isBefore ( r ) ) { break ; } else if ( l . isAfter ( r ) ) { rightIndex = i + 1 ; continue ; } result . add ( Range . intersection ( l , r ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Adds a range to the end of the list of ranges . It maintains the disjunct ascending order ( * ) of the ranges by trying to union the specified range to the last ranges in the list . The specified range shall be larger ( * ) than the last one or might be overlapped with some of the last ones . ( * ) [ a b ] < [ c d ] if b < c [CODESPLIT] private void add ( Range range ) { Range rangeToAdd = range ; for ( int i = ranges . size ( ) - 1 ; i >= 0 ; -- i ) { Range last = ranges . get ( i ) ; assert ! last . isAfter ( range ) ; Range u = Range . union ( last , rangeToAdd ) ; if ( u == null ) { break ; } rangeToAdd = u ; ranges . remove ( i ) ; } ranges . add ( rangeToAdd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stores a positive long into an int ( assuming it fits ) [CODESPLIT] private int positiveLongToInt ( long value ) { if ( ! ColumnChunkMetaData . positiveLongFitsInAnInt ( value ) ) { throw new IllegalArgumentException ( \"value should be positive and fit in an int: \" + value ) ; } return ( int ) ( value + Integer . MIN_VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a String into a { @link GlobNodeSequence } [CODESPLIT] public static GlobNodeSequence parse ( String pattern ) { /*\n     * The parse algorithm works as follows, assuming we are parsing:\n     * \"apache{one,pre{x,y}post,two}parquet{a,b}\"\n     *\n     * 1) Begin scanning the string until we find the first {\n     *\n     * 2) Now that we've found the beginning of a glob group, scan forwards\n     *    until the end of this glob group (by counting { and } we see until we find\n     *    the closing } for the group we found in step 1).\n     *\n     * 3) Once the matching closing } is found we need to do two things. First, everything\n     *    from the end of the last group up to start of this group is an Atom, so in the example\n     *    above, once we've found that \"{one,pre{x,y}post,two}\" is the first group, we need to grab\n     *    \"apache\" and treat it as an atom and add it to our sequence.\n     *    Then, we parse \"{one,pre{x,y}post,two}\" using a similar but slightly different function (parseOneOf)\n     *    and add the result from that to our sequence.\n     *\n     * 4) Repeat until the end of the string -- so next we find {a,b} and add \"parquet\" as an Atom and parse\n     *    {a,b} using parseOneOf.\n     */ if ( pattern . isEmpty ( ) || pattern . equals ( \"{}\" ) ) { return new GlobNodeSequence ( Arrays . < GlobNode > asList ( new Atom ( \"\" ) ) ) ; } // the outer parse method needs to parse the pattern into a // GlobNodeSequence, though it may end up being a singleton sequence List < GlobNode > children = new ArrayList < GlobNode > ( ) ; int unmatchedBraces = 0 ; // count of unmatched braces int firstBrace = 0 ; // open brace of current group being processsed int anchor = 0 ; // first un-parsed character position for ( int i = 0 ; i < pattern . length ( ) ; i ++ ) { char c = pattern . charAt ( i ) ; switch ( c ) { case ' ' : if ( unmatchedBraces == 0 ) { // commas not allowed in the top level expression // TODO: maybe turn this check off? throw new GlobParseException ( \"Unexpected comma outside of a {} group:\\n\" + annotateMessage ( pattern , i ) ) ; } break ; case ' ' : if ( unmatchedBraces == 0 ) { // this is the first brace of an outermost {} group firstBrace = i ; } unmatchedBraces ++ ; break ; case ' ' : unmatchedBraces -- ; if ( unmatchedBraces < 0 ) { throw new GlobParseException ( \"Unexpected closing }:\\n\" + annotateMessage ( pattern , i ) ) ; } if ( unmatchedBraces == 0 ) { // grab everything from the end of the last group up to here, // not including the close brace, it is an Atom in our sequence // (assuming it's not empty) if ( anchor != firstBrace ) { // not empty! // (substring's end param is exclusive) children . add ( new Atom ( pattern . substring ( anchor , firstBrace ) ) ) ; } // grab the group, parse it, add it to our sequence, and then continue // note that we skip the braces on both sides (substring's end param is exclusive) children . add ( parseOneOf ( pattern . substring ( firstBrace + 1 , i ) ) ) ; // we have now parsed all the way up to here, the next un-parsed char is i + 1 anchor = i + 1 ; } break ; } } if ( unmatchedBraces > 0 ) { throw new GlobParseException ( \"Not enough close braces in: \" + pattern ) ; } if ( anchor != pattern . length ( ) ) { // either there were no {} groups, or there were some characters after the // last }, either way whatever is left (could be the entire input) is an Atom // in our sequence children . add ( new Atom ( pattern . substring ( anchor , pattern . length ( ) ) ) ) ; } return new GlobNodeSequence ( children ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for pretty printing which character had the error [CODESPLIT] private static String annotateMessage ( String message , int pos ) { StringBuilder sb = new StringBuilder ( message ) ; sb . append ( ' ' ) ; for ( int i = 0 ; i < pos ; i ++ ) { sb . append ( ' ' ) ; } sb . append ( ' ' ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If we are currently writing a bit - packed - run update the bit - packed - header and consider this run to be over [CODESPLIT] private void endPreviousBitPackedRun ( ) { if ( bitPackedRunHeaderPointer == - 1 ) { // we're not currently in a bit-packed-run return ; } // create bit-packed-header, which needs to fit in 1 byte byte bitPackHeader = ( byte ) ( ( bitPackedGroupCount << 1 ) | 1 ) ; // update this byte baos . setByte ( bitPackedRunHeaderPointer , bitPackHeader ) ; // mark that this run is over bitPackedRunHeaderPointer = - 1 ; // reset the number of groups bitPackedGroupCount = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads one record from in and writes it to out exceptions are not recoverable as record might be halfway written [CODESPLIT] @ Override public void readOne ( TProtocol in , TProtocol out ) throws TException { readOneStruct ( in , out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a FilterPredicate return a Filter that wraps it . This method also logs the filter being used and rewrites the predicate to not include the not () operator . [CODESPLIT] public static Filter get ( FilterPredicate filterPredicate ) { checkNotNull ( filterPredicate , \"filterPredicate\" ) ; LOG . info ( \"Filtering using predicate: {}\" , filterPredicate ) ; // rewrite the predicate to not include the not() operator FilterPredicate collapsedPredicate = LogicalInverseRewriter . rewrite ( filterPredicate ) ; if ( ! filterPredicate . equals ( collapsedPredicate ) ) { LOG . info ( \"Predicate has been collapsed to: {}\" , collapsedPredicate ) ; } return new FilterPredicateCompat ( collapsedPredicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given either a FilterPredicate or the class of an UnboundRecordFilter or neither ( but not both ) return a Filter that wraps whichever was provided . <p > Either filterPredicate or unboundRecordFilterClass must be null or an exception is thrown . <p > If both are null the no op filter will be returned . [CODESPLIT] public static Filter get ( FilterPredicate filterPredicate , UnboundRecordFilter unboundRecordFilter ) { checkArgument ( filterPredicate == null || unboundRecordFilter == null , \"Cannot provide both a FilterPredicate and an UnboundRecordFilter\" ) ; if ( filterPredicate != null ) { return get ( filterPredicate ) ; } if ( unboundRecordFilter != null ) { return get ( unboundRecordFilter ) ; } return NOOP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for files provided check if there s a summary file . If a summary file is found it is used otherwise the file footer is used . [CODESPLIT] @ Deprecated public static List < Footer > readAllFootersInParallelUsingSummaryFiles ( Configuration configuration , List < FileStatus > partFiles ) throws IOException { return readAllFootersInParallelUsingSummaryFiles ( configuration , partFiles , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for files provided check if there s a summary file . If a summary file is found it is used otherwise the file footer is used . [CODESPLIT] @ Deprecated public static List < Footer > readAllFootersInParallelUsingSummaryFiles ( final Configuration configuration , final Collection < FileStatus > partFiles , final boolean skipRowGroups ) throws IOException { // figure out list of all parents to part files Set < Path > parents = new HashSet < Path > ( ) ; for ( FileStatus part : partFiles ) { parents . add ( part . getPath ( ) . getParent ( ) ) ; } // read corresponding summary files if they exist List < Callable < Map < Path , Footer > > > summaries = new ArrayList < Callable < Map < Path , Footer > > > ( ) ; for ( final Path path : parents ) { summaries . add ( new Callable < Map < Path , Footer > > ( ) { @ Override public Map < Path , Footer > call ( ) throws Exception { ParquetMetadata mergedMetadata = readSummaryMetadata ( configuration , path , skipRowGroups ) ; if ( mergedMetadata != null ) { final List < Footer > footers ; if ( skipRowGroups ) { footers = new ArrayList < Footer > ( ) ; for ( FileStatus f : partFiles ) { footers . add ( new Footer ( f . getPath ( ) , mergedMetadata ) ) ; } } else { footers = footersFromSummaryFile ( path , mergedMetadata ) ; } Map < Path , Footer > map = new HashMap < Path , Footer > ( ) ; for ( Footer footer : footers ) { // the folder may have been moved footer = new Footer ( new Path ( path , footer . getFile ( ) . getName ( ) ) , footer . getParquetMetadata ( ) ) ; map . put ( footer . getFile ( ) , footer ) ; } return map ; } else { return Collections . emptyMap ( ) ; } } } ) ; } Map < Path , Footer > cache = new HashMap < Path , Footer > ( ) ; try { List < Map < Path , Footer > > footersFromSummaries = runAllInParallel ( configuration . getInt ( PARQUET_READ_PARALLELISM , 5 ) , summaries ) ; for ( Map < Path , Footer > footers : footersFromSummaries ) { cache . putAll ( footers ) ; } } catch ( ExecutionException e ) { throw new IOException ( \"Error reading summaries\" , e ) ; } // keep only footers for files actually requested and read file footer if not found in summaries List < Footer > result = new ArrayList < Footer > ( partFiles . size ( ) ) ; List < FileStatus > toRead = new ArrayList < FileStatus > ( ) ; for ( FileStatus part : partFiles ) { Footer f = cache . get ( part . getPath ( ) ) ; if ( f != null ) { result . add ( f ) ; } else { toRead . add ( part ) ; } } if ( toRead . size ( ) > 0 ) { // read the footers of the files that did not have a summary file LOG . info ( \"reading another {} footers\" , toRead . size ( ) ) ; result . addAll ( readAllFootersInParallel ( configuration , toRead , skipRowGroups ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read all the footers of the files provided ( not using summary files ) [CODESPLIT] @ Deprecated public static List < Footer > readAllFootersInParallel ( final Configuration configuration , List < FileStatus > partFiles , final boolean skipRowGroups ) throws IOException { List < Callable < Footer >> footers = new ArrayList < Callable < Footer > > ( ) ; for ( final FileStatus currentFile : partFiles ) { footers . add ( new Callable < Footer > ( ) { @ Override public Footer call ( ) throws Exception { try { return new Footer ( currentFile . getPath ( ) , readFooter ( configuration , currentFile , filter ( skipRowGroups ) ) ) ; } catch ( IOException e ) { throw new IOException ( \"Could not read footer for file \" + currentFile , e ) ; } } } ) ; } try { return runAllInParallel ( configuration . getInt ( PARQUET_READ_PARALLELISM , 5 ) , footers ) ; } catch ( ExecutionException e ) { throw new IOException ( \"Could not read footer: \" + e . getMessage ( ) , e . getCause ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the footers of all the files under that path ( recursively ) not using summary files . [CODESPLIT] @ Deprecated public static List < Footer > readAllFootersInParallel ( Configuration configuration , FileStatus fileStatus , boolean skipRowGroups ) throws IOException { List < FileStatus > statuses = listFiles ( configuration , fileStatus ) ; return readAllFootersInParallel ( configuration , statuses , skipRowGroups ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the footers of all the files under that path ( recursively ) not using summary files . rowGroups are not skipped [CODESPLIT] @ Deprecated public static List < Footer > readAllFootersInParallel ( Configuration configuration , FileStatus fileStatus ) throws IOException { return readAllFootersInParallel ( configuration , fileStatus , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this always returns the row groups [CODESPLIT] @ Deprecated public static List < Footer > readFooters ( Configuration configuration , FileStatus pathStatus ) throws IOException { return readFooters ( configuration , pathStatus , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the footers of all the files under that path ( recursively ) using summary files if possible [CODESPLIT] @ Deprecated public static List < Footer > readFooters ( Configuration configuration , FileStatus pathStatus , boolean skipRowGroups ) throws IOException { List < FileStatus > files = listFiles ( configuration , pathStatus ) ; return readAllFootersInParallelUsingSummaryFiles ( configuration , files , skipRowGroups ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifically reads a given summary file [CODESPLIT] @ Deprecated public static List < Footer > readSummaryFile ( Configuration configuration , FileStatus summaryStatus ) throws IOException { final Path parent = summaryStatus . getPath ( ) . getParent ( ) ; ParquetMetadata mergedFooters = readFooter ( configuration , summaryStatus , filter ( false ) ) ; return footersFromSummaryFile ( parent , mergedFooters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the meta data block in the footer of the file [CODESPLIT] @ Deprecated public static final ParquetMetadata readFooter ( Configuration configuration , Path file ) throws IOException { return readFooter ( configuration , file , NO_FILTER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the meta data in the footer of the file . Skipping row groups ( or not ) based on the provided filter [CODESPLIT] public static ParquetMetadata readFooter ( Configuration configuration , Path file , MetadataFilter filter ) throws IOException { return readFooter ( HadoopInputFile . fromPath ( file , configuration ) , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the meta data block in the footer of the file [CODESPLIT] @ Deprecated public static final ParquetMetadata readFooter ( Configuration configuration , FileStatus file , MetadataFilter filter ) throws IOException { return readFooter ( HadoopInputFile . fromStatus ( file , configuration ) , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the meta data block in the footer of the file using provided input stream [CODESPLIT] @ Deprecated public static final ParquetMetadata readFooter ( InputFile file , MetadataFilter filter ) throws IOException { ParquetReadOptions options ; if ( file instanceof HadoopInputFile ) { options = HadoopReadOptions . builder ( ( ( HadoopInputFile ) file ) . getConfiguration ( ) ) . withMetadataFilter ( filter ) . build ( ) ; } else { options = ParquetReadOptions . builder ( ) . withMetadataFilter ( filter ) . build ( ) ; } try ( SeekableInputStream in = file . newStream ( ) ) { return readFooter ( file , options , in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a { @link InputFile file } . [CODESPLIT] public static ParquetFileReader open ( InputFile file ) throws IOException { return new ParquetFileReader ( file , ParquetReadOptions . builder ( ) . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a { @link InputFile file } with { @link ParquetReadOptions options } . [CODESPLIT] public static ParquetFileReader open ( InputFile file , ParquetReadOptions options ) throws IOException { return new ParquetFileReader ( file , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all the columns requested from the row group at the current file position . [CODESPLIT] public PageReadStore readNextRowGroup ( ) throws IOException { if ( currentBlock == blocks . size ( ) ) { return null ; } BlockMetaData block = blocks . get ( currentBlock ) ; if ( block . getRowCount ( ) == 0 ) { throw new RuntimeException ( \"Illegal row group of 0 rows\" ) ; } this . currentRowGroup = new ColumnChunkPageReadStore ( block . getRowCount ( ) ) ; // prepare the list of consecutive parts to read them in one scan List < ConsecutivePartList > allParts = new ArrayList < ConsecutivePartList > ( ) ; ConsecutivePartList currentParts = null ; for ( ColumnChunkMetaData mc : block . getColumns ( ) ) { ColumnPath pathKey = mc . getPath ( ) ; BenchmarkCounter . incrementTotalBytes ( mc . getTotalSize ( ) ) ; ColumnDescriptor columnDescriptor = paths . get ( pathKey ) ; if ( columnDescriptor != null ) { long startingPos = mc . getStartingPos ( ) ; // first part or not consecutive => new list if ( currentParts == null || currentParts . endPos ( ) != startingPos ) { currentParts = new ConsecutivePartList ( startingPos ) ; allParts . add ( currentParts ) ; } currentParts . addChunk ( new ChunkDescriptor ( columnDescriptor , mc , startingPos , ( int ) mc . getTotalSize ( ) ) ) ; } } // actually read all the chunks ChunkListBuilder builder = new ChunkListBuilder ( ) ; for ( ConsecutivePartList consecutiveChunks : allParts ) { consecutiveChunks . readAll ( f , builder ) ; } for ( Chunk chunk : builder . build ( ) ) { currentRowGroup . addColumn ( chunk . descriptor . col , chunk . readAllPages ( ) ) ; } // avoid re-reading bytes the dictionary reader is used after this call if ( nextDictionaryReader != null ) { nextDictionaryReader . setRowGroup ( currentRowGroup ) ; } advanceToNextBlock ( ) ; return currentRowGroup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all the columns requested from the row group at the current file position . It may skip specific pages based on the column indexes according to the actual filter . As the rows are not aligned among the pages of the different columns row synchronization might be required . See the documentation of the class SynchronizingColumnReader for details . [CODESPLIT] public PageReadStore readNextFilteredRowGroup ( ) throws IOException { if ( currentBlock == blocks . size ( ) ) { return null ; } if ( ! options . useColumnIndexFilter ( ) ) { return readNextRowGroup ( ) ; } BlockMetaData block = blocks . get ( currentBlock ) ; if ( block . getRowCount ( ) == 0 ) { throw new RuntimeException ( \"Illegal row group of 0 rows\" ) ; } ColumnIndexStore ciStore = getColumnIndexStore ( currentBlock ) ; RowRanges rowRanges = getRowRanges ( currentBlock ) ; long rowCount = rowRanges . rowCount ( ) ; if ( rowCount == 0 ) { // There are no matching rows -> skipping this row-group advanceToNextBlock ( ) ; return readNextFilteredRowGroup ( ) ; } if ( rowCount == block . getRowCount ( ) ) { // All rows are matching -> fall back to the non-filtering path return readNextRowGroup ( ) ; } this . currentRowGroup = new ColumnChunkPageReadStore ( rowRanges ) ; // prepare the list of consecutive parts to read them in one scan ChunkListBuilder builder = new ChunkListBuilder ( ) ; List < ConsecutivePartList > allParts = new ArrayList < ConsecutivePartList > ( ) ; ConsecutivePartList currentParts = null ; for ( ColumnChunkMetaData mc : block . getColumns ( ) ) { ColumnPath pathKey = mc . getPath ( ) ; ColumnDescriptor columnDescriptor = paths . get ( pathKey ) ; if ( columnDescriptor != null ) { OffsetIndex offsetIndex = ciStore . getOffsetIndex ( mc . getPath ( ) ) ; OffsetIndex filteredOffsetIndex = filterOffsetIndex ( offsetIndex , rowRanges , block . getRowCount ( ) ) ; for ( OffsetRange range : calculateOffsetRanges ( filteredOffsetIndex , mc , offsetIndex . getOffset ( 0 ) ) ) { BenchmarkCounter . incrementTotalBytes ( range . getLength ( ) ) ; long startingPos = range . getOffset ( ) ; // first part or not consecutive => new list if ( currentParts == null || currentParts . endPos ( ) != startingPos ) { currentParts = new ConsecutivePartList ( startingPos ) ; allParts . add ( currentParts ) ; } ChunkDescriptor chunkDescriptor = new ChunkDescriptor ( columnDescriptor , mc , startingPos , ( int ) range . getLength ( ) ) ; currentParts . addChunk ( chunkDescriptor ) ; builder . setOffsetIndex ( chunkDescriptor , filteredOffsetIndex ) ; } } } // actually read all the chunks for ( ConsecutivePartList consecutiveChunks : allParts ) { consecutiveChunks . readAll ( f , builder ) ; } for ( Chunk chunk : builder . build ( ) ) { currentRowGroup . addColumn ( chunk . descriptor . col , chunk . readAllPages ( ) ) ; } // avoid re-reading bytes the dictionary reader is used after this call if ( nextDictionaryReader != null ) { nextDictionaryReader . setRowGroup ( currentRowGroup ) ; } advanceToNextBlock ( ) ; return currentRowGroup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link DictionaryPageReadStore } for the row group that would be returned by calling { @link #readNextRowGroup () } or skipped by calling { @link #skipNextRowGroup () } . [CODESPLIT] public DictionaryPageReadStore getNextDictionaryReader ( ) { if ( nextDictionaryReader == null && currentBlock < blocks . size ( ) ) { this . nextDictionaryReader = getDictionaryReader ( blocks . get ( currentBlock ) ) ; } return nextDictionaryReader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads and decompresses a dictionary page for the given column chunk . [CODESPLIT] DictionaryPage readDictionary ( ColumnChunkMetaData meta ) throws IOException { if ( ! meta . getEncodings ( ) . contains ( Encoding . PLAIN_DICTIONARY ) && ! meta . getEncodings ( ) . contains ( Encoding . RLE_DICTIONARY ) ) { return null ; } // TODO: this should use getDictionaryPageOffset() but it isn't reliable. if ( f . getPos ( ) != meta . getStartingPos ( ) ) { f . seek ( meta . getStartingPos ( ) ) ; } PageHeader pageHeader = Util . readPageHeader ( f ) ; if ( ! pageHeader . isSetDictionary_page_header ( ) ) { return null ; // TODO: should this complain? } DictionaryPage compressedPage = readCompressedDictionary ( pageHeader , f ) ; BytesInputDecompressor decompressor = options . getCodecFactory ( ) . getDecompressor ( meta . getCodec ( ) ) ; return new DictionaryPage ( decompressor . decompress ( compressedPage . getBytes ( ) , compressedPage . getUncompressedSize ( ) ) , compressedPage . getDictionarySize ( ) , compressedPage . getEncoding ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new writer and its memory allocation to the memory manager . [CODESPLIT] synchronized void addWriter ( InternalParquetRecordWriter writer , Long allocation ) { Long oldValue = writerList . get ( writer ) ; if ( oldValue == null ) { writerList . put ( writer , allocation ) ; } else { throw new IllegalArgumentException ( \"[BUG] The Parquet Memory Manager should not add an \" + \"instance of InternalParquetRecordWriter more than once. The Manager already contains \" + \"the writer: \" + writer ) ; } updateAllocation ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given writer from the memory manager . [CODESPLIT] synchronized void removeWriter ( InternalParquetRecordWriter writer ) { if ( writerList . containsKey ( writer ) ) { writerList . remove ( writer ) ; } if ( ! writerList . isEmpty ( ) ) { updateAllocation ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the allocated size of each writer based on the current allocations and pool size . [CODESPLIT] private void updateAllocation ( ) { long totalAllocations = 0 ; for ( Long allocation : writerList . values ( ) ) { totalAllocations += allocation ; } if ( totalAllocations <= totalMemoryPool ) { scale = 1.0 ; } else { scale = ( double ) totalMemoryPool / totalAllocations ; LOG . warn ( String . format ( \"Total allocation exceeds %.2f%% (%,d bytes) of heap memory\\n\" + \"Scaling row group sizes to %.2f%% for %d writers\" , 100 * memoryPoolRatio , totalMemoryPool , 100 * scale , writerList . size ( ) ) ) ; for ( Runnable callBack : callBacks . values ( ) ) { // we do not really want to start a new thread here. callBack . run ( ) ; } } int maxColCount = 0 ; for ( InternalParquetRecordWriter w : writerList . keySet ( ) ) { maxColCount = Math . max ( w . getSchema ( ) . getColumns ( ) . size ( ) , maxColCount ) ; } for ( Map . Entry < InternalParquetRecordWriter , Long > entry : writerList . entrySet ( ) ) { long newSize = ( long ) Math . floor ( entry . getValue ( ) * scale ) ; if ( scale < 1.0 && minMemoryAllocation > 0 && newSize < minMemoryAllocation ) { throw new ParquetRuntimeException ( String . format ( \"New Memory allocation %d bytes\" + \" is smaller than the minimum allocation size of %d bytes.\" , newSize , minMemoryAllocation ) ) { } ; } entry . getKey ( ) . setRowGroupSizeThreshold ( newSize ) ; LOG . debug ( String . format ( \"Adjust block size from %,d to %,d for writer: %s\" , entry . getValue ( ) , newSize , entry . getKey ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register callback and deduplicate it if any . [CODESPLIT] public void registerScaleCallBack ( String callBackName , Runnable callBack ) { Preconditions . checkNotNull ( callBackName , \"callBackName\" ) ; Preconditions . checkNotNull ( callBack , \"callBack\" ) ; if ( callBacks . containsKey ( callBackName ) ) { throw new IllegalArgumentException ( \"The callBackName \" + callBackName + \" is duplicated and has been registered already.\" ) ; } else { callBacks . put ( callBackName , callBack ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start the file [CODESPLIT] public void start ( ) throws IOException { state = state . start ( ) ; LOG . debug ( \"{}: start\" , out . getPos ( ) ) ; out . write ( MAGIC ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start a block [CODESPLIT] public void startBlock ( long recordCount ) throws IOException { state = state . startBlock ( ) ; LOG . debug ( \"{}: start block\" , out . getPos ( ) ) ; //    out.write(MAGIC); // TODO: add a magic delimiter alignment . alignForRowGroup ( out ) ; currentBlock = new BlockMetaData ( ) ; currentRecordCount = recordCount ; currentColumnIndexes = new ArrayList <> ( ) ; currentOffsetIndexes = new ArrayList <> ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start a column inside a block [CODESPLIT] public void startColumn ( ColumnDescriptor descriptor , long valueCount , CompressionCodecName compressionCodecName ) throws IOException { state = state . startColumn ( ) ; encodingStatsBuilder . clear ( ) ; currentEncodings = new HashSet < Encoding > ( ) ; currentChunkPath = ColumnPath . get ( descriptor . getPath ( ) ) ; currentChunkType = descriptor . getPrimitiveType ( ) ; currentChunkCodec = compressionCodecName ; currentChunkValueCount = valueCount ; currentChunkFirstDataPage = out . getPos ( ) ; compressedLength = 0 ; uncompressedLength = 0 ; // The statistics will be copied from the first one added at writeDataPage(s) so we have the correct typed one currentStatistics = null ; columnIndexBuilder = ColumnIndexBuilder . getBuilder ( currentChunkType , columnIndexTruncateLength ) ; offsetIndexBuilder = OffsetIndexBuilder . getBuilder ( ) ; firstPageOffset = - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes a dictionary page page [CODESPLIT] public void writeDictionaryPage ( DictionaryPage dictionaryPage ) throws IOException { state = state . write ( ) ; LOG . debug ( \"{}: write dictionary page: {} values\" , out . getPos ( ) , dictionaryPage . getDictionarySize ( ) ) ; currentChunkDictionaryPageOffset = out . getPos ( ) ; int uncompressedSize = dictionaryPage . getUncompressedSize ( ) ; int compressedPageSize = ( int ) dictionaryPage . getBytes ( ) . size ( ) ; // TODO: fix casts metadataConverter . writeDictionaryPageHeader ( uncompressedSize , compressedPageSize , dictionaryPage . getDictionarySize ( ) , dictionaryPage . getEncoding ( ) , out ) ; long headerSize = out . getPos ( ) - currentChunkDictionaryPageOffset ; this . uncompressedLength += uncompressedSize + headerSize ; this . compressedLength += compressedPageSize + headerSize ; LOG . debug ( \"{}: write dictionary page content {}\" , out . getPos ( ) , compressedPageSize ) ; dictionaryPage . getBytes ( ) . writeAllTo ( out ) ; encodingStatsBuilder . addDictEncoding ( dictionaryPage . getEncoding ( ) ) ; currentEncodings . add ( dictionaryPage . getEncoding ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes a single page [CODESPLIT] @ Deprecated public void writeDataPage ( int valueCount , int uncompressedPageSize , BytesInput bytes , Encoding rlEncoding , Encoding dlEncoding , Encoding valuesEncoding ) throws IOException { state = state . write ( ) ; // We are unable to build indexes without rowCount so skip them for this column offsetIndexBuilder = OffsetIndexBuilder . getNoOpBuilder ( ) ; columnIndexBuilder = ColumnIndexBuilder . getNoOpBuilder ( ) ; long beforeHeader = out . getPos ( ) ; LOG . debug ( \"{}: write data page: {} values\" , beforeHeader , valueCount ) ; int compressedPageSize = ( int ) bytes . size ( ) ; metadataConverter . writeDataPageV1Header ( uncompressedPageSize , compressedPageSize , valueCount , rlEncoding , dlEncoding , valuesEncoding , out ) ; long headerSize = out . getPos ( ) - beforeHeader ; this . uncompressedLength += uncompressedPageSize + headerSize ; this . compressedLength += compressedPageSize + headerSize ; LOG . debug ( \"{}: write data page content {}\" , out . getPos ( ) , compressedPageSize ) ; bytes . writeAllTo ( out ) ; encodingStatsBuilder . addDataEncoding ( valuesEncoding ) ; currentEncodings . add ( rlEncoding ) ; currentEncodings . add ( dlEncoding ) ; currentEncodings . add ( valuesEncoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes a single page [CODESPLIT] @ Deprecated public void writeDataPage ( int valueCount , int uncompressedPageSize , BytesInput bytes , Statistics statistics , Encoding rlEncoding , Encoding dlEncoding , Encoding valuesEncoding ) throws IOException { // We are unable to build indexes without rowCount so skip them for this column offsetIndexBuilder = OffsetIndexBuilder . getNoOpBuilder ( ) ; columnIndexBuilder = ColumnIndexBuilder . getNoOpBuilder ( ) ; innerWriteDataPage ( valueCount , uncompressedPageSize , bytes , statistics , rlEncoding , dlEncoding , valuesEncoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a single page [CODESPLIT] public void writeDataPage ( int valueCount , int uncompressedPageSize , BytesInput bytes , Statistics statistics , long rowCount , Encoding rlEncoding , Encoding dlEncoding , Encoding valuesEncoding ) throws IOException { long beforeHeader = out . getPos ( ) ; innerWriteDataPage ( valueCount , uncompressedPageSize , bytes , statistics , rlEncoding , dlEncoding , valuesEncoding ) ; offsetIndexBuilder . add ( ( int ) ( out . getPos ( ) - beforeHeader ) , rowCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a column chunk at once [CODESPLIT] void writeColumnChunk ( ColumnDescriptor descriptor , long valueCount , CompressionCodecName compressionCodecName , DictionaryPage dictionaryPage , BytesInput bytes , long uncompressedTotalPageSize , long compressedTotalPageSize , Statistics < ? > totalStats , ColumnIndexBuilder columnIndexBuilder , OffsetIndexBuilder offsetIndexBuilder , Set < Encoding > rlEncodings , Set < Encoding > dlEncodings , List < Encoding > dataEncodings ) throws IOException { startColumn ( descriptor , valueCount , compressionCodecName ) ; state = state . write ( ) ; if ( dictionaryPage != null ) { writeDictionaryPage ( dictionaryPage ) ; } LOG . debug ( \"{}: write data pages\" , out . getPos ( ) ) ; long headersSize = bytes . size ( ) - compressedTotalPageSize ; this . uncompressedLength += uncompressedTotalPageSize + headersSize ; this . compressedLength += compressedTotalPageSize + headersSize ; LOG . debug ( \"{}: write data pages content\" , out . getPos ( ) ) ; firstPageOffset = out . getPos ( ) ; bytes . writeAllTo ( out ) ; encodingStatsBuilder . addDataEncodings ( dataEncodings ) ; if ( rlEncodings . isEmpty ( ) ) { encodingStatsBuilder . withV2Pages ( ) ; } currentEncodings . addAll ( rlEncodings ) ; currentEncodings . addAll ( dlEncodings ) ; currentEncodings . addAll ( dataEncodings ) ; currentStatistics = totalStats ; this . columnIndexBuilder = columnIndexBuilder ; this . offsetIndexBuilder = offsetIndexBuilder ; endColumn ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end a column ( once all rep def and data have been written ) [CODESPLIT] public void endColumn ( ) throws IOException { state = state . endColumn ( ) ; LOG . debug ( \"{}: end column\" , out . getPos ( ) ) ; if ( columnIndexBuilder . getMinMaxSize ( ) > columnIndexBuilder . getPageCount ( ) * MAX_STATS_SIZE ) { currentColumnIndexes . add ( null ) ; } else { currentColumnIndexes . add ( columnIndexBuilder . build ( ) ) ; } currentOffsetIndexes . add ( offsetIndexBuilder . build ( firstPageOffset ) ) ; currentBlock . addColumn ( ColumnChunkMetaData . get ( currentChunkPath , currentChunkType , currentChunkCodec , encodingStatsBuilder . build ( ) , currentEncodings , currentStatistics , currentChunkFirstDataPage , currentChunkDictionaryPageOffset , currentChunkValueCount , compressedLength , uncompressedLength ) ) ; this . currentBlock . setTotalByteSize ( currentBlock . getTotalByteSize ( ) + uncompressedLength ) ; this . uncompressedLength = 0 ; this . compressedLength = 0 ; columnIndexBuilder = null ; offsetIndexBuilder = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ends a block once all column chunks have been written [CODESPLIT] public void endBlock ( ) throws IOException { state = state . endBlock ( ) ; LOG . debug ( \"{}: end block\" , out . getPos ( ) ) ; currentBlock . setRowCount ( currentRecordCount ) ; blocks . add ( currentBlock ) ; columnIndexes . add ( currentColumnIndexes ) ; offsetIndexes . add ( currentOffsetIndexes ) ; currentColumnIndexes = null ; currentOffsetIndexes = null ; currentBlock = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy from a FS input stream to an output stream . Thread - safe [CODESPLIT] private static void copy ( SeekableInputStream from , PositionOutputStream to , long start , long length ) throws IOException { LOG . debug ( \"Copying {} bytes at {} to {}\" , length , start , to . getPos ( ) ) ; from . seek ( start ) ; long bytesCopied = 0 ; byte [ ] buffer = COPY_BUFFER . get ( ) ; while ( bytesCopied < length ) { long bytesLeft = length - bytesCopied ; int bytesRead = from . read ( buffer , 0 , ( buffer . length < bytesLeft ? buffer . length : ( int ) bytesLeft ) ) ; if ( bytesRead < 0 ) { throw new IllegalArgumentException ( \"Unexpected end of input file at \" + start + bytesCopied ) ; } to . write ( buffer , 0 , bytesRead ) ; bytesCopied += bytesRead ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ends a file once all blocks have been written . closes the file . [CODESPLIT] public void end ( Map < String , String > extraMetaData ) throws IOException { state = state . end ( ) ; serializeColumnIndexes ( columnIndexes , blocks , out ) ; serializeOffsetIndexes ( offsetIndexes , blocks , out ) ; LOG . debug ( \"{}: end\" , out . getPos ( ) ) ; this . footer = new ParquetMetadata ( new FileMetaData ( schema , extraMetaData , Version . FULL_VERSION ) , blocks ) ; serializeFooter ( footer , out ) ; out . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a list of metadata files merge them into a single ParquetMetadata Requires that the schemas be compatible and the extraMetadata be exactly equal . [CODESPLIT] @ Deprecated public static ParquetMetadata mergeMetadataFiles ( List < Path > files , Configuration conf ) throws IOException { Preconditions . checkArgument ( ! files . isEmpty ( ) , \"Cannot merge an empty list of metadata\" ) ; GlobalMetaData globalMetaData = null ; List < BlockMetaData > blocks = new ArrayList < BlockMetaData > ( ) ; for ( Path p : files ) { ParquetMetadata pmd = ParquetFileReader . readFooter ( conf , p , ParquetMetadataConverter . NO_FILTER ) ; FileMetaData fmd = pmd . getFileMetaData ( ) ; globalMetaData = mergeInto ( fmd , globalMetaData , true ) ; blocks . addAll ( pmd . getBlocks ( ) ) ; } // collapse GlobalMetaData into a single FileMetaData, which will throw if they are not compatible return new ParquetMetadata ( globalMetaData . merge ( ) , blocks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a list of metadata files merge them into a single metadata file . Requires that the schemas be compatible and the extraMetaData be exactly equal . This is useful when merging 2 directories of parquet files into a single directory as long as both directories were written with compatible schemas and equal extraMetaData . [CODESPLIT] @ Deprecated public static void writeMergedMetadataFile ( List < Path > files , Path outputPath , Configuration conf ) throws IOException { ParquetMetadata merged = mergeMetadataFiles ( files , conf ) ; writeMetadataFile ( outputPath , merged , outputPath . getFileSystem ( conf ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes a _metadata and _common_metadata file [CODESPLIT] @ Deprecated public static void writeMetadataFile ( Configuration configuration , Path outputPath , List < Footer > footers ) throws IOException { writeMetadataFile ( configuration , outputPath , footers , JobSummaryLevel . ALL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes _common_metadata file and optionally a _metadata file depending on the { [CODESPLIT] @ Deprecated public static void writeMetadataFile ( Configuration configuration , Path outputPath , List < Footer > footers , JobSummaryLevel level ) throws IOException { Preconditions . checkArgument ( level == JobSummaryLevel . ALL || level == JobSummaryLevel . COMMON_ONLY , \"Unsupported level: \" + level ) ; FileSystem fs = outputPath . getFileSystem ( configuration ) ; outputPath = outputPath . makeQualified ( fs ) ; ParquetMetadata metadataFooter = mergeFooters ( outputPath , footers ) ; if ( level == JobSummaryLevel . ALL ) { writeMetadataFile ( outputPath , metadataFooter , fs , PARQUET_METADATA_FILE ) ; } metadataFooter . getBlocks ( ) . clear ( ) ; writeMetadataFile ( outputPath , metadataFooter , fs , PARQUET_COMMON_METADATA_FILE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will return the result of merging toMerge into mergedMetadata [CODESPLIT] static GlobalMetaData mergeInto ( FileMetaData toMerge , GlobalMetaData mergedMetadata ) { return mergeInto ( toMerge , mergedMetadata , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "will return the result of merging toMerge into mergedSchema [CODESPLIT] static MessageType mergeInto ( MessageType toMerge , MessageType mergedSchema ) { return mergeInto ( toMerge , mergedSchema , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "will return the result of merging toMerge into mergedSchema [CODESPLIT] static MessageType mergeInto ( MessageType toMerge , MessageType mergedSchema , boolean strict ) { if ( mergedSchema == null ) { return toMerge ; } return mergedSchema . union ( toMerge , strict ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the value into the binding . [CODESPLIT] public void readValue ( ) { try { if ( ! valueRead ) { binding . read ( ) ; valueRead = true ; } } catch ( RuntimeException e ) { if ( CorruptDeltaByteArrays . requiresSequentialReads ( writerVersion , currentEncoding ) && e instanceof ArrayIndexOutOfBoundsException ) { // this is probably PARQUET-246, which may happen if reading data with // MR because this can't be detected without reading all footers throw new ParquetDecodingException ( \"Read failure possibly due to \" + \"PARQUET-246: try setting parquet.split.files to false\" , new ParquetDecodingException ( format ( \"Can't read value in column %s at value %d out of %d, \" + \"%d out of %d in currentPage. repetition level: \" + \"%d, definition level: %d\" , path , readValues , totalValueCount , readValues - ( endOfPageValueCount - pageValueCount ) , pageValueCount , repetitionLevel , definitionLevel ) , e ) ) ; } throw new ParquetDecodingException ( format ( \"Can't read value in column %s at value %d out of %d, \" + \"%d out of %d in currentPage. repetition level: \" + \"%d, definition level: %d\" , path , readValues , totalValueCount , readValues - ( endOfPageValueCount - pageValueCount ) , pageValueCount , repetitionLevel , definitionLevel ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether null is allowed by the schema . [CODESPLIT] public static boolean nullOk ( Schema schema ) { if ( Schema . Type . NULL == schema . getType ( ) ) { return true ; } else if ( Schema . Type . UNION == schema . getType ( ) ) { for ( Schema possible : schema . getTypes ( ) ) { if ( nullOk ( possible ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges { @link Schema } instances if they are compatible . <p > Schemas are incompatible if : <ul > <li > The { @link Schema . Type } does not match . < / li > <li > For record schemas the record name does not match< / li > <li > For enum schemas the enum name does not match< / li > < / ul > <p > Map value array element and record field types types will use unions if necessary and union schemas are merged recursively . [CODESPLIT] public static Schema merge ( Iterable < Schema > schemas ) { Iterator < Schema > iter = schemas . iterator ( ) ; if ( ! iter . hasNext ( ) ) { return null ; } Schema result = iter . next ( ) ; while ( iter . hasNext ( ) ) { result = merge ( result , iter . next ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges two { @link Schema } instances if they are compatible . <p > Two schemas are incompatible if : <ul > <li > The { @link Schema . Type } does not match . < / li > <li > For record schemas the record name does not match< / li > <li > For enum schemas the enum name does not match< / li > < / ul > <p > Map value and array element types will use unions if necessary and union schemas are merged recursively . [CODESPLIT] public static Schema merge ( Schema left , Schema right ) { Schema merged = mergeOnly ( left , right ) ; Preconditions . checkState ( merged != null , \"Cannot merge %s and %s\" , left , right ) ; return merged ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges two { @link Schema } instances or returns { @code null } . <p > The two schemas are merged if they are the same type . Records are merged if the two records have the same name or have no names but have a significant number of shared fields . <p > @see { @link #mergeOrUnion } to return a union when a merge is not possible . [CODESPLIT] private static Schema mergeOrUnion ( Schema left , Schema right ) { Schema merged = mergeOnly ( left , right ) ; if ( merged != null ) { return merged ; } return union ( left , right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a union of two { @link Schema } instances . <p > If either { @code Schema } is a union this will attempt to merge the other schema with the types contained in that union before adding more types to the union that is produced . <p > If both schemas are not unions no merge is attempted . [CODESPLIT] private static Schema union ( Schema left , Schema right ) { if ( left . getType ( ) == Schema . Type . UNION ) { if ( right . getType ( ) == Schema . Type . UNION ) { // combine the unions by adding each type in right individually Schema combined = left ; for ( Schema type : right . getTypes ( ) ) { combined = union ( combined , type ) ; } return combined ; } else { boolean notMerged = true ; // combine a union with a non-union by checking if each type will merge List < Schema > types = Lists . newArrayList ( ) ; Iterator < Schema > schemas = left . getTypes ( ) . iterator ( ) ; // try to merge each type and stop when one succeeds while ( schemas . hasNext ( ) ) { Schema next = schemas . next ( ) ; Schema merged = mergeOnly ( next , right ) ; if ( merged != null ) { types . add ( merged ) ; notMerged = false ; break ; } else { // merge didn't work, add the type types . add ( next ) ; } } // add the remaining types from the left union while ( schemas . hasNext ( ) ) { types . add ( schemas . next ( ) ) ; } if ( notMerged ) { types . add ( right ) ; } return Schema . createUnion ( types ) ; } } else if ( right . getType ( ) == Schema . Type . UNION ) { return union ( right , left ) ; } return Schema . createUnion ( ImmutableList . of ( left , right ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges two { @link Schema } instances or returns { @code null } . <p > The two schemas are merged if they are the same type . Records are merged if the two records have the same name or have no names but have a significant number of shared fields . <p > @see { @link #mergeOrUnion } to return a union when a merge is not possible . [CODESPLIT] private static Schema mergeOnly ( Schema left , Schema right ) { if ( Objects . equal ( left , right ) ) { return left ; } // handle primitive type promotion; doesn't promote integers to floats switch ( left . getType ( ) ) { case INT : if ( right . getType ( ) == Schema . Type . LONG ) { return right ; } break ; case LONG : if ( right . getType ( ) == Schema . Type . INT ) { return left ; } break ; case FLOAT : if ( right . getType ( ) == Schema . Type . DOUBLE ) { return right ; } break ; case DOUBLE : if ( right . getType ( ) == Schema . Type . FLOAT ) { return left ; } } // any other cases where the types don't match must be combined by a union if ( left . getType ( ) != right . getType ( ) ) { return null ; } switch ( left . getType ( ) ) { case UNION : return union ( left , right ) ; case RECORD : if ( left . getName ( ) == null && right . getName ( ) == null && fieldSimilarity ( left , right ) < SIMILARITY_THRESH ) { return null ; } else if ( ! Objects . equal ( left . getName ( ) , right . getName ( ) ) ) { return null ; } Schema combinedRecord = Schema . createRecord ( coalesce ( left . getName ( ) , right . getName ( ) ) , coalesce ( left . getDoc ( ) , right . getDoc ( ) ) , coalesce ( left . getNamespace ( ) , right . getNamespace ( ) ) , false ) ; combinedRecord . setFields ( mergeFields ( left , right ) ) ; return combinedRecord ; case MAP : return Schema . createMap ( mergeOrUnion ( left . getValueType ( ) , right . getValueType ( ) ) ) ; case ARRAY : return Schema . createArray ( mergeOrUnion ( left . getElementType ( ) , right . getElementType ( ) ) ) ; case ENUM : if ( ! Objects . equal ( left . getName ( ) , right . getName ( ) ) ) { return null ; } Set < String > symbols = Sets . newLinkedHashSet ( ) ; symbols . addAll ( left . getEnumSymbols ( ) ) ; symbols . addAll ( right . getEnumSymbols ( ) ) ; return Schema . createEnum ( left . getName ( ) , coalesce ( left . getDoc ( ) , right . getDoc ( ) ) , coalesce ( left . getNamespace ( ) , right . getNamespace ( ) ) , ImmutableList . copyOf ( symbols ) ) ; default : // all primitives are handled before the switch by the equality check. // schemas that reach this point are not primitives and also not any of // the above known types. throw new UnsupportedOperationException ( \"Unknown schema type: \" + left . getType ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a union { @link Schema } of NULL and the given { @code schema } . <p > A NULL schema is always the first type in the union so that a null default value can be set . [CODESPLIT] private static Schema nullableForDefault ( Schema schema ) { if ( schema . getType ( ) == Schema . Type . NULL ) { return schema ; } if ( schema . getType ( ) != Schema . Type . UNION ) { return Schema . createUnion ( ImmutableList . of ( NULL , schema ) ) ; } if ( schema . getTypes ( ) . get ( 0 ) . getType ( ) == Schema . Type . NULL ) { return schema ; } List < Schema > types = Lists . newArrayList ( ) ; types . add ( NULL ) ; for ( Schema type : schema . getTypes ( ) ) { if ( type . getType ( ) != Schema . Type . NULL ) { types . add ( type ) ; } } return Schema . createUnion ( types ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new field with the same name schema doc and default value as the incoming schema . <p > Fields cannot be used in more than one record ( not Immutable? ) . [CODESPLIT] public static Schema . Field copy ( Schema . Field field ) { return new Schema . Field ( field . name ( ) , field . schema ( ) , field . doc ( ) , field . defaultValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first non - null object that is passed in . [CODESPLIT] @ SafeVarargs private static < E > E coalesce ( E ... objects ) { for ( E object : objects ) { if ( object != null ) { return object ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void close ( TaskAttemptContext context ) throws IOException , InterruptedException { try { internalWriter . close ( ) ; // release after the writer closes in case it is used for a last flush } finally { if ( codecFactory != null ) { codecFactory . release ( ) ; } if ( memoryManager != null ) { memoryManager . removeWriter ( internalWriter ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void write ( Void key , T value ) throws IOException , InterruptedException { internalWriter . write ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a the value as the first matching schema type or null . [CODESPLIT] private static Object makeValue ( String string , Schema schema ) { if ( string == null ) { return null ; } try { switch ( schema . getType ( ) ) { case BOOLEAN : return Boolean . valueOf ( string ) ; case STRING : return string ; case FLOAT : return Float . valueOf ( string ) ; case DOUBLE : return Double . valueOf ( string ) ; case INT : return Integer . valueOf ( string ) ; case LONG : return Long . valueOf ( string ) ; case ENUM : // TODO: translate to enum class if ( schema . hasEnumSymbol ( string ) ) { return string ; } else { try { return schema . getEnumSymbols ( ) . get ( Integer . parseInt ( string ) ) ; } catch ( IndexOutOfBoundsException ex ) { return null ; } } case UNION : Object value = null ; for ( Schema possible : schema . getTypes ( ) ) { value = makeValue ( string , possible ) ; if ( value != null ) { return value ; } } return null ; case NULL : return null ; default : // FIXED, BYTES, MAP, ARRAY, RECORD are not supported throw new RecordException ( \"Unsupported field type:\" + schema . getType ( ) ) ; } } catch ( NumberFormatException e ) { // empty string is considered null for numeric types if ( string . isEmpty ( ) ) { return null ; } else { throw e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads ThriftMetadata from the parquet file footer . [CODESPLIT] public static ThriftMetaData fromExtraMetaData ( Map < String , String > extraMetaData ) { final String thriftClassName = extraMetaData . get ( THRIFT_CLASS ) ; final String thriftDescriptorString = extraMetaData . get ( THRIFT_DESCRIPTOR ) ; if ( thriftClassName == null || thriftDescriptorString == null ) { return null ; } final StructType descriptor = parseDescriptor ( thriftDescriptorString ) ; return new ThriftMetaData ( thriftClassName , descriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates ThriftMetaData from a Thrift - generated class . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static ThriftMetaData fromThriftClass ( Class < ? > thriftClass ) { if ( thriftClass != null && TBase . class . isAssignableFrom ( thriftClass ) ) { Class < ? extends TBase < ? , ? > > tClass = ( Class < ? extends TBase < ? , ? > > ) thriftClass ; StructType descriptor = new ThriftSchemaConverter ( ) . toStructType ( tClass ) ; return new ThriftMetaData ( thriftClass . getName ( ) , descriptor ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generates a map of key values to store in the footer [CODESPLIT] public Map < String , String > toExtraMetaData ( ) { final Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( THRIFT_CLASS , getThriftClass ( ) . getName ( ) ) ; map . put ( THRIFT_DESCRIPTOR , descriptor . toJSON ( ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the current null value [CODESPLIT] @ Override public void writeNull ( int repetitionLevel , int definitionLevel ) { if ( DEBUG ) log ( null , repetitionLevel , definitionLevel ) ; repetitionLevel ( repetitionLevel ) ; definitionLevel ( definitionLevel ) ; statistics . incrementNumNulls ( ) ; ++ valueCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the current value [CODESPLIT] @ Override public void write ( double value , int repetitionLevel , int definitionLevel ) { if ( DEBUG ) log ( value , repetitionLevel , definitionLevel ) ; repetitionLevel ( repetitionLevel ) ; definitionLevel ( definitionLevel ) ; dataColumn . writeDouble ( value ) ; statistics . updateStats ( value ) ; ++ valueCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the current value [CODESPLIT] @ Override public void write ( Binary value , int repetitionLevel , int definitionLevel ) { if ( DEBUG ) log ( value , repetitionLevel , definitionLevel ) ; repetitionLevel ( repetitionLevel ) ; definitionLevel ( definitionLevel ) ; dataColumn . writeBytes ( value ) ; statistics . updateStats ( value ) ; ++ valueCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finalizes the Column chunk . Possibly adding extra pages if needed ( dictionary ... ) Is called right after writePage [CODESPLIT] void finalizeColumnChunk ( ) { final DictionaryPage dictionaryPage = dataColumn . toDictPageAndClose ( ) ; if ( dictionaryPage != null ) { if ( DEBUG ) LOG . debug ( \"write dictionary\" ) ; try { pageWriter . writeDictionaryPage ( dictionaryPage ) ; } catch ( IOException e ) { throw new ParquetEncodingException ( \"could not write dictionary page for \" + path , e ) ; } dataColumn . resetDictionary ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the current data to a new page in the page store [CODESPLIT] void writePage ( ) { if ( valueCount == 0 ) { throw new ParquetEncodingException ( \"writing empty page\" ) ; } this . rowsWrittenSoFar += pageRowCount ; if ( DEBUG ) LOG . debug ( \"write page\" ) ; try { writePage ( pageRowCount , valueCount , statistics , repetitionLevelColumn , definitionLevelColumn , dataColumn ) ; } catch ( IOException e ) { throw new ParquetEncodingException ( \"could not write page for \" + path , e ) ; } repetitionLevelColumn . reset ( ) ; definitionLevelColumn . reset ( ) ; dataColumn . reset ( ) ; valueCount = 0 ; resetStatistics ( ) ; pageRowCount = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing [CODESPLIT] static List < String > parseSemicolonDelimitedString ( String columnsToKeepGlobs ) { String [ ] splits = columnsToKeepGlobs . split ( GLOB_SEPARATOR ) ; List < String > globs = new ArrayList < String > ( ) ; for ( String s : splits ) { if ( ! s . isEmpty ( ) ) { globs . add ( s ) ; } } if ( globs . isEmpty ( ) ) { throw new ThriftProjectionException ( String . format ( \"Semicolon delimited string '%s' contains 0 glob strings\" , columnsToKeepGlobs ) ) ; } return globs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing [CODESPLIT] boolean keep ( String path ) { WildcardPath match = null ; // since we have a rule of every path must match at least one column, // we visit every single wildcard path, instead of short circuiting, // for the case where more than one pattern matches a column. Otherwise // we'd get a misleading exception saying a path didn't match a column, // even though it looks like it should have (but didn't because of short circuiting). // This also allows us log a warning when more than one glob path matches. for ( WildcardPathStatus wp : columnsToKeep ) { if ( wp . matches ( path ) ) { if ( match != null && ! match . getParentGlobPath ( ) . equals ( wp . getWildcardPath ( ) . getParentGlobPath ( ) ) ) { String message = \"Field path: '%s' matched more than one glob path pattern. First match: \" + \"'%s' (when expanded to '%s') second match:'%s' (when expanded to '%s')\" ; warn ( String . format ( message , path , match . getParentGlobPath ( ) , match . getOriginalPattern ( ) , wp . getWildcardPath ( ) . getParentGlobPath ( ) , wp . getWildcardPath ( ) . getOriginalPattern ( ) ) ) ; } else { match = wp . getWildcardPath ( ) ; } } } return match != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void endMessage ( ) { delegate . endMessage ( ) ; validateMissingFields ( types . peek ( ) . asGroupType ( ) . getFieldCount ( ) ) ; previousField . pop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void startField ( String field , int index ) { if ( index <= previousField . peek ( ) ) { throw new InvalidRecordException ( \"fields must be added in order \" + field + \" index \" + index + \" is before previous field \" + previousField . peek ( ) ) ; } validateMissingFields ( index ) ; fields . push ( index ) ; fieldValueCount . push ( 0 ) ; delegate . startField ( field , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void endField ( String field , int index ) { delegate . endField ( field , index ) ; fieldValueCount . pop ( ) ; previousField . push ( fields . pop ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void startGroup ( ) { previousField . push ( - 1 ) ; types . push ( types . peek ( ) . asGroupType ( ) . getType ( fields . peek ( ) ) ) ; delegate . startGroup ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void endGroup ( ) { delegate . endGroup ( ) ; validateMissingFields ( types . peek ( ) . asGroupType ( ) . getFieldCount ( ) ) ; types . pop ( ) ; previousField . pop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void addBinary ( Binary value ) { validate ( BINARY , INT96 , FIXED_LEN_BYTE_ARRAY ) ; delegate . addBinary ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeToStringBuilder ( StringBuilder sb , String indent ) { sb . append ( indent ) . append ( getRepetition ( ) . name ( ) . toLowerCase ( Locale . ENGLISH ) ) . append ( \" \" ) . append ( primitive . name ( ) . toLowerCase ( ) ) ; if ( primitive == PrimitiveTypeName . FIXED_LEN_BYTE_ARRAY ) { sb . append ( \"(\" + length + \")\" ) ; } sb . append ( \" \" ) . append ( getName ( ) ) ; if ( getLogicalTypeAnnotation ( ) != null ) { // TODO: should we print decimal metadata too? sb . append ( \" (\" ) . append ( getLogicalTypeAnnotation ( ) . toString ( ) ) . append ( \")\" ) ; } if ( getId ( ) != null ) { sb . append ( \" = \" ) . append ( getId ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link Type } specific comparator for properly comparing values . The natural ordering of the values might not proper in certain cases ( e . g . { @code UINT_32 } requires unsigned comparison of { @code int } values while the natural ordering is signed . ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > PrimitiveComparator < T > comparator ( ) { return ( PrimitiveComparator < T > ) getPrimitiveTypeName ( ) . comparator ( getLogicalTypeAnnotation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eagerly loads all the data into memory [CODESPLIT] @ Override public void initFromPage ( int valueCount , ByteBufferInputStream stream ) throws IOException { this . in = stream ; long startPos = in . position ( ) ; this . config = DeltaBinaryPackingConfig . readConfig ( in ) ; this . totalValueCount = BytesUtils . readUnsignedVarInt ( in ) ; allocateValuesBuffer ( ) ; bitWidths = new int [ config . miniBlockNumInABlock ] ; //read first value from header valuesBuffer [ valuesBuffered ++ ] = BytesUtils . readZigZagVarLong ( in ) ; while ( valuesBuffered < totalValueCount ) { //values Buffered could be more than totalValueCount, since we flush on a mini block basis loadNewBlockToBuffer ( ) ; } updateNextOffset ( ( int ) ( in . position ( ) - startPos ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the value buffer is allocated so that the size of it is multiple of mini block because when writing data is flushed on a mini block basis [CODESPLIT] private void allocateValuesBuffer ( ) { int totalMiniBlockCount = ( int ) Math . ceil ( ( double ) totalValueCount / config . miniBlockSizeInValues ) ; //+ 1 because first value written to header is also stored in values buffer valuesBuffer = new long [ totalMiniBlockCount * config . miniBlockSizeInValues + 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mini block has a size of 8 * n unpack 8 value each time [CODESPLIT] private void unpackMiniBlock ( BytePackerForLong packer ) throws IOException { for ( int j = 0 ; j < config . miniBlockSizeInValues ; j += 8 ) { unpack8Values ( packer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will merge the metadata as if it was coming from a single file . ( for all part files written together this will always work ) If there are conflicting values an exception will be thrown [CODESPLIT] public FileMetaData merge ( ) { String createdByString = createdBy . size ( ) == 1 ? createdBy . iterator ( ) . next ( ) : createdBy . toString ( ) ; Map < String , String > mergedKeyValues = new HashMap < String , String > ( ) ; for ( Entry < String , Set < String > > entry : keyValueMetaData . entrySet ( ) ) { if ( entry . getValue ( ) . size ( ) > 1 ) { throw new RuntimeException ( \"could not merge metadata: key \" + entry . getKey ( ) + \" has conflicting values: \" + entry . getValue ( ) ) ; } mergedKeyValues . put ( entry . getKey ( ) , entry . getValue ( ) . iterator ( ) . next ( ) ) ; } return new FileMetaData ( schema , mergedKeyValues , createdByString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to convert the old representation of logical types ( OriginalType ) to new logical type . [CODESPLIT] @ InterfaceAudience . Private public static LogicalTypeAnnotation fromOriginalType ( OriginalType originalType , DecimalMetadata decimalMetadata ) { if ( originalType == null ) { return null ; } switch ( originalType ) { case UTF8 : return stringType ( ) ; case MAP : return mapType ( ) ; case DECIMAL : int scale = ( decimalMetadata == null ? 0 : decimalMetadata . getScale ( ) ) ; int precision = ( decimalMetadata == null ? 0 : decimalMetadata . getPrecision ( ) ) ; return decimalType ( scale , precision ) ; case LIST : return listType ( ) ; case DATE : return dateType ( ) ; case INTERVAL : return IntervalLogicalTypeAnnotation . getInstance ( ) ; case TIMESTAMP_MILLIS : return timestampType ( true , LogicalTypeAnnotation . TimeUnit . MILLIS ) ; case TIMESTAMP_MICROS : return timestampType ( true , LogicalTypeAnnotation . TimeUnit . MICROS ) ; case TIME_MILLIS : return timeType ( true , LogicalTypeAnnotation . TimeUnit . MILLIS ) ; case TIME_MICROS : return timeType ( true , LogicalTypeAnnotation . TimeUnit . MICROS ) ; case UINT_8 : return intType ( 8 , false ) ; case UINT_16 : return intType ( 16 , false ) ; case UINT_32 : return intType ( 32 , false ) ; case UINT_64 : return intType ( 64 , false ) ; case INT_8 : return intType ( 8 , true ) ; case INT_16 : return intType ( 16 , true ) ; case INT_32 : return intType ( 32 , true ) ; case INT_64 : return intType ( 64 , true ) ; case ENUM : return enumType ( ) ; case JSON : return jsonType ( ) ; case BSON : return bsonType ( ) ; case MAP_KEY_VALUE : return MapKeyValueTypeAnnotation . getInstance ( ) ; default : throw new RuntimeException ( \"Can't convert original type to logical type, unknown original type \" + originalType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OutputFormat < Void , Tuple > getOutputFormat ( ) throws IOException { return new ParquetOutputFormat < Tuple > ( new TupleToThriftWriteSupport ( className ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getBytes will trigger flushing block buffer DO NOT write after getBytes () is called without calling reset () [CODESPLIT] @ Override public BytesInput getBytes ( ) { // The Page Header should include: blockSizeInValues, numberOfMiniBlocks, totalValueCount if ( deltaValuesToFlush != 0 ) { flushBlockBuffer ( ) ; } return BytesInput . concat ( config . toBytesInput ( ) , BytesInput . fromUnsignedVarInt ( totalValueCount ) , BytesInput . fromZigZagVarLong ( firstValue ) , BytesInput . from ( baos ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Precondition - style validation that throws { @link IllegalArgumentException } . [CODESPLIT] public static void checkArgument ( boolean isValid , String message , Object ... args ) throws IllegalArgumentException { if ( ! isValid ) { throw new IllegalArgumentException ( String . format ( String . valueOf ( message ) , strings ( args ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Precondition - style validation that throws { @link IllegalStateException } . [CODESPLIT] public static void checkState ( boolean isValid , String message , Object ... args ) throws IllegalStateException { if ( ! isValid ) { throw new IllegalStateException ( String . format ( String . valueOf ( message ) , strings ( args ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads one record from in and writes it to out . Exceptions encountered during reading are treated as skippable exceptions { @link FieldIgnoredHandler } will be notified when registered . [CODESPLIT] @ Override public void readOne ( TProtocol in , TProtocol out ) throws TException { List < Action > buffer = new LinkedList < Action > ( ) ; try { boolean hasFieldsIgnored = readOneStruct ( in , buffer , thriftType ) ; if ( hasFieldsIgnored ) { notifyRecordHasFieldIgnored ( ) ; } } catch ( Exception e ) { throw new SkippableException ( error ( \"Error while reading\" , buffer ) , e ) ; } try { for ( Action a : buffer ) { a . write ( out ) ; } } catch ( Exception e ) { throw new TException ( error ( \"Can not write record\" , buffer ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In thrift enum values are written as ints this method checks if the enum index is defined . [CODESPLIT] private void checkEnum ( ThriftType expectedType , int i ) { if ( expectedType . getType ( ) == ThriftTypeID . ENUM ) { ThriftType . EnumType expectedEnumType = ( ThriftType . EnumType ) expectedType ; if ( expectedEnumType . getEnumValueById ( i ) == null ) { throw new DecodingSchemaMismatchException ( \"can not find index \" + i + \" in enum \" + expectedType ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attempts to validate and construct a { @link MessageType } from a read projection schema [CODESPLIT] public static MessageType getSchemaForRead ( MessageType fileMessageType , String partialReadSchemaString ) { if ( partialReadSchemaString == null ) return fileMessageType ; MessageType requestedMessageType = MessageTypeParser . parseMessageType ( partialReadSchemaString ) ; return getSchemaForRead ( fileMessageType , requestedMessageType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called in { @link org . apache . hadoop . mapreduce . InputFormat#getSplits ( org . apache . hadoop . mapreduce . JobContext ) } in the front end [CODESPLIT] @ Deprecated public ReadContext init ( Configuration configuration , Map < String , String > keyValueMetaData , MessageType fileSchema ) { throw new UnsupportedOperationException ( \"Override init(InitContext)\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called in { @link org . apache . hadoop . mapreduce . InputFormat#getSplits ( org . apache . hadoop . mapreduce . JobContext ) } in the front end [CODESPLIT] public ReadContext init ( InitContext context ) { return init ( context . getConfiguration ( ) , context . getMergedKeyValueMetaData ( ) , context . getFileSchema ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets min and max values re - uses the byte [] passed in . Any changes made to byte [] will be reflected in min and max values as well . [CODESPLIT] @ Override public void setMinMaxFromBytes ( byte [ ] minBytes , byte [ ] maxBytes ) { max = Binary . fromReusedByteArray ( maxBytes ) ; min = Binary . fromReusedByteArray ( minBytes ) ; this . markAsNotEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "iterate through values in each mini block and calculate the bitWidths of max values . [CODESPLIT] private void calculateBitWidthsForDeltaBlockBuffer ( int miniBlocksToFlush ) { for ( int miniBlockIndex = 0 ; miniBlockIndex < miniBlocksToFlush ; miniBlockIndex ++ ) { int mask = 0 ; int miniStart = miniBlockIndex * config . miniBlockSizeInValues ; //The end of current mini block could be the end of current block(deltaValuesToFlush) buffer when data is not aligned to mini block int miniEnd = Math . min ( ( miniBlockIndex + 1 ) * config . miniBlockSizeInValues , deltaValuesToFlush ) ; for ( int i = miniStart ; i < miniEnd ; i ++ ) { mask |= deltaBlockBuffer [ i ] ; } bitWidths [ miniBlockIndex ] = 32 - Integer . numberOfLeadingZeros ( mask ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns builder for creating an and filter . [CODESPLIT] public static final UnboundRecordFilter and ( final UnboundRecordFilter filter1 , final UnboundRecordFilter filter2 ) { Preconditions . checkNotNull ( filter1 , \"filter1\" ) ; Preconditions . checkNotNull ( filter2 , \"filter2\" ) ; return new UnboundRecordFilter ( ) { @ Override public RecordFilter bind ( Iterable < ColumnReader > readers ) { return new AndRecordFilter ( filter1 . bind ( readers ) , filter2 . bind ( readers ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeToStringBuilder ( StringBuilder sb , String indent ) { sb . append ( \"message \" ) . append ( getName ( ) ) . append ( getLogicalTypeAnnotation ( ) == null ? \"\" : \" (\" + getLogicalTypeAnnotation ( ) . toString ( ) + \")\" ) . append ( \" {\\n\" ) ; membersDisplayString ( sb , \"  \" ) ; sb . append ( \"}\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates a column index store which lazily reads column / offset indexes for the columns in paths . ( paths are the set of columns used for the projection ) [CODESPLIT] static ColumnIndexStore create ( ParquetFileReader reader , BlockMetaData block , Set < ColumnPath > paths ) { try { return new ColumnIndexStoreImpl ( reader , block , paths ) ; } catch ( MissingOffsetIndexException e ) { return EMPTY ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns builder for creating an and filter . [CODESPLIT] public static final UnboundRecordFilter not ( final UnboundRecordFilter filter ) { Preconditions . checkNotNull ( filter , \"filter\" ) ; return new UnboundRecordFilter ( ) { @ Override public RecordFilter bind ( Iterable < ColumnReader > readers ) { return new NotRecordFilter ( filter . bind ( readers ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given throwable is an instance of E throw it as an E . [CODESPLIT] public static < E extends Exception > void throwIfInstance ( Throwable t , Class < E > excClass ) throws E { if ( excClass . isAssignableFrom ( t . getClass ( ) ) ) { // the throwable is already an exception, so return it throw excClass . cast ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the typed statistics object based on the passed type parameter [CODESPLIT] @ Deprecated public static Statistics getStatsBasedOnType ( PrimitiveTypeName type ) { switch ( type ) { case INT32 : return new IntStatistics ( ) ; case INT64 : return new LongStatistics ( ) ; case FLOAT : return new FloatStatistics ( ) ; case DOUBLE : return new DoubleStatistics ( ) ; case BOOLEAN : return new BooleanStatistics ( ) ; case BINARY : return new BinaryStatistics ( ) ; case INT96 : return new BinaryStatistics ( ) ; case FIXED_LEN_BYTE_ARRAY : return new BinaryStatistics ( ) ; default : throw new UnknownColumnTypeException ( type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an empty { @code Statistics } instance for the specified type to be used for reading / writing the new min / max statistics used in the V2 format . [CODESPLIT] public static Statistics < ? > createStats ( Type type ) { PrimitiveType primitive = type . asPrimitiveType ( ) ; switch ( primitive . getPrimitiveTypeName ( ) ) { case INT32 : return new IntStatistics ( primitive ) ; case INT64 : return new LongStatistics ( primitive ) ; case FLOAT : return new FloatStatistics ( primitive ) ; case DOUBLE : return new DoubleStatistics ( primitive ) ; case BOOLEAN : return new BooleanStatistics ( primitive ) ; case BINARY : case INT96 : case FIXED_LEN_BYTE_ARRAY : return new BinaryStatistics ( primitive ) ; default : throw new UnknownColumnTypeException ( primitive . getPrimitiveTypeName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a builder to create new statistics object . Used to read the statistics from the parquet file . [CODESPLIT] public static Builder getBuilderForReading ( PrimitiveType type ) { switch ( type . getPrimitiveTypeName ( ) ) { case FLOAT : return new FloatBuilder ( type ) ; case DOUBLE : return new DoubleBuilder ( type ) ; default : return new Builder ( type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to merge this statistics object with the object passed as parameter . Merging keeps the smallest of min values largest of max values and combines the number of null counts . [CODESPLIT] public void mergeStatistics ( Statistics stats ) { if ( stats . isEmpty ( ) ) return ; // Merge stats only if they have the same type if ( type . equals ( stats . type ) ) { incrementNumNulls ( stats . getNumNulls ( ) ) ; if ( stats . hasNonNullValue ( ) ) { mergeStatisticsMinMax ( stats ) ; markAsNotEmpty ( ) ; } } else { throw StatisticsClassException . create ( this , stats ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a schema check to see if it is a union of a null type and a regular schema and then return the non - null sub - schema . Otherwise return the given schema . [CODESPLIT] public static Schema getNonNull ( Schema schema ) { if ( schema . getType ( ) . equals ( Schema . Type . UNION ) ) { List < Schema > schemas = schema . getTypes ( ) ; if ( schemas . size ( ) == 2 ) { if ( schemas . get ( 0 ) . getType ( ) . equals ( Schema . Type . NULL ) ) { return schemas . get ( 1 ) ; } else if ( schemas . get ( 1 ) . getType ( ) . equals ( Schema . Type . NULL ) ) { return schemas . get ( 0 ) ; } else { return schema ; } } else { return schema ; } } else { return schema ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements the rules for interpreting existing data from the logical type spec for the LIST annotation . This is used to produce the expected schema . <p > The AvroArrayConverter will decide whether the repeated type is the array element type by testing whether the element schema and repeated type are the same . This ensures that the LIST rules are followed when there is no schema and that a schema can be provided to override the default behavior . [CODESPLIT] private boolean isElementType ( Type repeatedType , String parentName ) { return ( // can't be a synthetic layer because it would be invalid repeatedType . isPrimitive ( ) || repeatedType . asGroupType ( ) . getFieldCount ( ) > 1 || repeatedType . asGroupType ( ) . getType ( 0 ) . isRepetition ( REPEATED ) || // known patterns without the synthetic layer repeatedType . getName ( ) . equals ( \"array\" ) || repeatedType . getName ( ) . equals ( parentName + \"_tuple\" ) || // default assumption assumeRepeatedIsListElement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates JobContext from a JobConf and jobId using the correct constructor for based on Hadoop version . <code > jobId< / code > could be null . [CODESPLIT] public static JobContext newJobContext ( Configuration conf , JobID jobId ) { try { return ( JobContext ) JOB_CONTEXT_CONSTRUCTOR . newInstance ( conf , jobId ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( \"Can't instantiate JobContext\" , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"Can't instantiate JobContext\" , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( \"Can't instantiate JobContext\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates TaskAttemptContext from a JobConf and jobId using the correct constructor for based on Hadoop version . [CODESPLIT] public static TaskAttemptContext newTaskAttemptContext ( Configuration conf , TaskAttemptID taskAttemptId ) { try { return ( TaskAttemptContext ) TASK_CONTEXT_CONSTRUCTOR . newInstance ( conf , taskAttemptId ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( \"Can't instantiate TaskAttemptContext\" , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"Can't instantiate TaskAttemptContext\" , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( \"Can't instantiate TaskAttemptContext\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke getConfiguration () method on JobContext . Works with both Hadoop 1 and 2 . [CODESPLIT] public static Configuration getConfiguration ( JobContext context ) { try { return ( Configuration ) GET_CONFIGURATION_METHOD . invoke ( context ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"Can't invoke method\" , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( \"Can't invoke method\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes a method and rethrows any exception as runtime exceptions . [CODESPLIT] private static Object invoke ( Method method , Object obj , Object ... args ) { try { return method . invoke ( obj , args ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"Can't invoke method \" + method . getName ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( \"Can't invoke method \" + method . getName ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "appends a display string for of the members of this group to sb [CODESPLIT] void membersDisplayString ( StringBuilder sb , String indent ) { for ( Type field : fields ) { field . writeToStringBuilder ( sb , indent ) ; if ( field . isPrimitive ( ) ) { sb . append ( \";\" ) ; } sb . append ( \"\\n\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeToStringBuilder ( StringBuilder sb , String indent ) { sb . append ( indent ) . append ( getRepetition ( ) . name ( ) . toLowerCase ( Locale . ENGLISH ) ) . append ( \" group \" ) . append ( getName ( ) ) . append ( getLogicalTypeAnnotation ( ) == null ? \"\" : \" (\" + getLogicalTypeAnnotation ( ) . toString ( ) + \")\" ) . append ( getId ( ) == null ? \"\" : \" = \" + getId ( ) ) . append ( \" {\\n\" ) ; membersDisplayString ( sb , indent + \"  \" ) ; sb . append ( indent ) . append ( \"}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "produces the list of fields resulting from merging toMerge into the fields of this [CODESPLIT] List < Type > mergeFields ( GroupType toMerge , boolean strict ) { List < Type > newFields = new ArrayList < Type > ( ) ; // merge existing fields for ( Type type : this . getFields ( ) ) { Type merged ; if ( toMerge . containsField ( type . getName ( ) ) ) { Type fieldToMerge = toMerge . getType ( type . getName ( ) ) ; if ( type . getLogicalTypeAnnotation ( ) != null && ! type . getLogicalTypeAnnotation ( ) . equals ( fieldToMerge . getLogicalTypeAnnotation ( ) ) ) { throw new IncompatibleSchemaModificationException ( \"cannot merge logical type \" + fieldToMerge . getLogicalTypeAnnotation ( ) + \" into \" + type . getLogicalTypeAnnotation ( ) ) ; } merged = type . union ( fieldToMerge , strict ) ; } else { merged = type ; } newFields . add ( merged ) ; } // add new fields for ( Type type : toMerge . getFields ( ) ) { if ( ! this . containsField ( type . getName ( ) ) ) { newFields . add ( type ) ; } } return newFields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Init counters in hadoop s mapred API which is used by cascading and Hive . [CODESPLIT] public static void initCounterFromReporter ( Reporter reporter , Configuration configuration ) { counterLoader = new MapRedCounterLoader ( reporter , configuration ) ; loadCounters ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fills specified buffer with compressed data . Returns actual number of bytes of compressed data . A return value of 0 indicates that needsInput () should be called in order to determine if more input data is required . [CODESPLIT] @ Override public synchronized int compress ( byte [ ] buffer , int off , int len ) throws IOException { SnappyUtil . validateBuffer ( buffer , off , len ) ; if ( needsInput ( ) ) { // No buffered output bytes and no input to consume, need more input return 0 ; } if ( ! outputBuffer . hasRemaining ( ) ) { // There is uncompressed input, compress it now int maxOutputSize = Snappy . maxCompressedLength ( inputBuffer . position ( ) ) ; if ( maxOutputSize > outputBuffer . capacity ( ) ) { ByteBuffer oldBuffer = outputBuffer ; outputBuffer = ByteBuffer . allocateDirect ( maxOutputSize ) ; CleanUtil . clean ( oldBuffer ) ; } // Reset the previous outputBuffer outputBuffer . clear ( ) ; inputBuffer . limit ( inputBuffer . position ( ) ) ; inputBuffer . position ( 0 ) ; int size = Snappy . compress ( inputBuffer , outputBuffer ) ; outputBuffer . limit ( size ) ; inputBuffer . limit ( 0 ) ; inputBuffer . rewind ( ) ; } // Return compressed output up to 'len' int numBytes = Math . min ( len , outputBuffer . remaining ( ) ) ; outputBuffer . get ( buffer , off , numBytes ) ; bytesWritten += numBytes ; return numBytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes a ( potentially null ) closeable swallowing any IOExceptions thrown by c . close () . The exception will be logged . [CODESPLIT] public static void closeAndSwallowIOExceptions ( Closeable c ) { if ( c == null ) { return ; } try { c . close ( ) ; } catch ( IOException e ) { LOG . warn ( \"Encountered exception closing closeable\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a non - null Filter which is a wrapper around either a FilterPredicate an UnboundRecordFilter or a no - op filter . [CODESPLIT] public static Filter getFilter ( Configuration conf ) { return FilterCompat . get ( getFilterPredicate ( conf ) , getUnboundRecordFilterInstance ( conf ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public RecordReader < Void , T > createRecordReader ( InputSplit inputSplit , TaskAttemptContext taskAttemptContext ) throws IOException , InterruptedException { Configuration conf = ContextUtil . getConfiguration ( taskAttemptContext ) ; ReadSupport < T > readSupport = getReadSupport ( conf ) ; return new ParquetRecordReader < T > ( readSupport , getFilter ( conf ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < InputSplit > getSplits ( JobContext jobContext ) throws IOException { Configuration configuration = ContextUtil . getConfiguration ( jobContext ) ; List < InputSplit > splits = new ArrayList < InputSplit > ( ) ; if ( isTaskSideMetaData ( configuration ) ) { // Although not required by the API, some clients may depend on always // receiving ParquetInputSplit. Translation is required at some point. for ( InputSplit split : super . getSplits ( jobContext ) ) { Preconditions . checkArgument ( split instanceof FileSplit , \"Cannot wrap non-FileSplit: \" + split ) ; splits . add ( ParquetInputSplit . from ( ( FileSplit ) split ) ) ; } return splits ; } else { splits . addAll ( getSplits ( configuration , getFooters ( jobContext ) ) ) ; } return splits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This is to support multi - level / recursive directory listing until MAPREDUCE - 1577 is fixed . [CODESPLIT] @ Override protected List < FileStatus > listStatus ( JobContext jobContext ) throws IOException { return getAllFileRecursively ( super . listStatus ( jobContext ) , ContextUtil . getConfiguration ( jobContext ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the footers for the files [CODESPLIT] public List < Footer > getFooters ( Configuration configuration , Collection < FileStatus > statuses ) throws IOException { LOG . debug ( \"reading {} files\" , statuses . size ( ) ) ; boolean taskSideMetaData = isTaskSideMetaData ( configuration ) ; return ParquetFileReader . readAllFootersInParallelUsingSummaryFiles ( configuration , statuses , taskSideMetaData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "groups together all the data blocks for the same HDFS block [CODESPLIT] static < T > List < ParquetInputSplit > generateSplits ( List < BlockMetaData > rowGroupBlocks , BlockLocation [ ] hdfsBlocksArray , FileStatus fileStatus , String requestedSchema , Map < String , String > readSupportMetadata , long minSplitSize , long maxSplitSize ) throws IOException { List < SplitInfo > splitRowGroups = generateSplitInfo ( rowGroupBlocks , hdfsBlocksArray , minSplitSize , maxSplitSize ) ; //generate splits from rowGroups of each split List < ParquetInputSplit > resultSplits = new ArrayList < ParquetInputSplit > ( ) ; for ( SplitInfo splitInfo : splitRowGroups ) { ParquetInputSplit split = splitInfo . getParquetInputSplit ( fileStatus , requestedSchema , readSupportMetadata ) ; resultSplits . add ( split ) ; } return resultSplits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records if their value is equal to the provided value . Nulls are treated the same way the java programming language does . <p > For example : eq ( column null ) will keep all records whose value is null . eq ( column 7 ) will keep all records whose value is 7 and will drop records whose value is null [CODESPLIT] public static < T extends Comparable < T > , C extends Column < T > & SupportsEqNotEq > Eq < T > eq ( C column , T value ) { return new Eq < T > ( column , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records if their value is not equal to the provided value . Nulls are treated the same way the java programming language does . <p > For example : notEq ( column null ) will keep all records whose value is not null . notEq ( column 7 ) will keep all records whose value is not 7 including records whose value is null . [CODESPLIT] public static < T extends Comparable < T > , C extends Column < T > & SupportsEqNotEq > NotEq < T > notEq ( C column , T value ) { return new NotEq < T > ( column , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records if their value is less than ( but not equal to ) the provided value . The provided value cannot be null as less than null has no meaning . Records with null values will be dropped . <p > For example : lt ( column 7 ) will keep all records whose value is less than ( but not equal to ) 7 and not null . [CODESPLIT] public static < T extends Comparable < T > , C extends Column < T > & SupportsLtGt > Lt < T > lt ( C column , T value ) { return new Lt < T > ( column , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records if their value is less than or equal to the provided value . The provided value cannot be null as less than null has no meaning . Records with null values will be dropped . <p > For example : ltEq ( column 7 ) will keep all records whose value is less than or equal to 7 and not null . [CODESPLIT] public static < T extends Comparable < T > , C extends Column < T > & SupportsLtGt > LtEq < T > ltEq ( C column , T value ) { return new LtEq < T > ( column , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records if their value is greater than ( but not equal to ) the provided value . The provided value cannot be null as less than null has no meaning . Records with null values will be dropped . <p > For example : gt ( column 7 ) will keep all records whose value is greater than ( but not equal to ) 7 and not null . [CODESPLIT] public static < T extends Comparable < T > , C extends Column < T > & SupportsLtGt > Gt < T > gt ( C column , T value ) { return new Gt < T > ( column , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records if their value is greater than or equal to the provided value . The provided value cannot be null as less than null has no meaning . Records with null values will be dropped . <p > For example : gtEq ( column 7 ) will keep all records whose value is greater than or equal to 7 and not null . [CODESPLIT] public static < T extends Comparable < T > , C extends Column < T > & SupportsLtGt > GtEq < T > gtEq ( C column , T value ) { return new GtEq < T > ( column , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records that pass the provided { @link UserDefinedPredicate } <p > The provided class must have a default constructor . To use an instance of a UserDefinedPredicate instead see userDefined below . [CODESPLIT] public static < T extends Comparable < T > , U extends UserDefinedPredicate < T > > UserDefined < T , U > userDefined ( Column < T > column , Class < U > clazz ) { return new UserDefinedByClass < T , U > ( column , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps records that pass the provided { @link UserDefinedPredicate } <p > The provided instance of UserDefinedPredicate must be serializable . [CODESPLIT] public static < T extends Comparable < T > , U extends UserDefinedPredicate < T > & Serializable > UserDefined < T , U > userDefined ( Column < T > column , U udp ) { return new UserDefinedByInstance < T , U > ( column , udp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints a debug message [CODESPLIT] public void debug ( Object m ) { if ( m instanceof Throwable ) { logger . debug ( \"\" , ( Throwable ) m ) ; } else { logger . debug ( String . valueOf ( m ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints a debug message [CODESPLIT] public void debug ( Object m , Throwable t ) { logger . debug ( String . valueOf ( m ) , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints an info message [CODESPLIT] public void info ( Object m ) { if ( m instanceof Throwable ) { logger . info ( \"\" , ( Throwable ) m ) ; } else { logger . info ( String . valueOf ( m ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints an info message [CODESPLIT] public void info ( Object m , Throwable t ) { logger . info ( String . valueOf ( m ) , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints a warn message [CODESPLIT] public void warn ( Object m ) { if ( m instanceof Throwable ) { logger . warn ( \"\" , ( Throwable ) m ) ; } else { logger . warn ( String . valueOf ( m ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints a warn message [CODESPLIT] public void warn ( Object m , Throwable t ) { logger . warn ( String . valueOf ( m ) , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints an error message [CODESPLIT] public void error ( Object m ) { if ( m instanceof Throwable ) { logger . error ( \"\" , ( Throwable ) m ) ; } else { logger . error ( String . valueOf ( m ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints an error message [CODESPLIT] public void error ( Object m , Throwable t ) { logger . error ( String . valueOf ( m ) , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns builder for creating an and filter . [CODESPLIT] public static final UnboundRecordFilter or ( final UnboundRecordFilter filter1 , final UnboundRecordFilter filter2 ) { Preconditions . checkNotNull ( filter1 , \"filter1\" ) ; Preconditions . checkNotNull ( filter2 , \"filter2\" ) ; return new UnboundRecordFilter ( ) { @ Override public RecordFilter bind ( Iterable < ColumnReader > readers ) { return new OrRecordFilter ( filter1 . bind ( readers ) , filter2 . bind ( readers ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes Protocol buffer to parquet file . [CODESPLIT] @ Override public void write ( T record ) { recordConsumer . startMessage ( ) ; try { messageWriter . writeTopLevelMessage ( record ) ; } catch ( RuntimeException e ) { Message m = ( record instanceof Message . Builder ) ? ( ( Message . Builder ) record ) . build ( ) : ( Message ) record ; LOG . error ( \"Cannot write message \" + e . getMessage ( ) + \" : \" + m ) ; throw e ; } recordConsumer . endMessage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "validates mapping between protobuffer fields and parquet fields . [CODESPLIT] private void validatedMapping ( Descriptor descriptor , GroupType parquetSchema ) { List < FieldDescriptor > allFields = descriptor . getFields ( ) ; for ( FieldDescriptor fieldDescriptor : allFields ) { String fieldName = fieldDescriptor . getName ( ) ; int fieldIndex = fieldDescriptor . getIndex ( ) ; int parquetIndex = parquetSchema . getFieldIndex ( fieldName ) ; if ( fieldIndex != parquetIndex ) { String message = \"FieldIndex mismatch name=\" + fieldName + \": \" + fieldIndex + \" != \" + parquetIndex ; throw new IncompatibleSchemaModificationException ( message ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns message descriptor as JSON String [CODESPLIT] private String serializeDescriptor ( Class < ? extends Message > protoClass ) { Descriptor descriptor = Protobufs . getMessageDescriptor ( protoClass ) ; DescriptorProtos . DescriptorProto asProto = descriptor . toProto ( ) ; return TextFormat . printToString ( asProto ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a codec factory that will provide compressors and decompressors that will work natively with ByteBuffers backed by direct memory . [CODESPLIT] public static CodecFactory createDirectCodecFactory ( Configuration config , ByteBufferAllocator allocator , int pageSize ) { return new DirectCodecFactory ( config , allocator , pageSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a . 2 . b [ 3 ] [ key ] * optional ( union with null ) should be ignored * unions should match by position number or short name ( e . g . 2 user ) * fields should match by name * arrays are dereferenced by position [ n ] = &gt ; schema is the element schema * maps are dereferenced by key = &gt ; schema is the value schema [CODESPLIT] public static Schema filterSchema ( Schema schema , String ... fieldPaths ) { return filterSchema ( schema , Lists . newArrayList ( fieldPaths ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a thrift definition protocols events it checks all the required fields and create default value if a required field is missing [CODESPLIT] public List < TProtocol > amendMissingRequiredFields ( StructType recordThriftType ) throws TException { Iterator < TProtocol > protocolIter = rootEvents . iterator ( ) ; checkStruct ( protocolIter , recordThriftType ) ; return fixedEvents ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check each element of the Set make sure all the element contain required fields [CODESPLIT] private void checkSet ( Iterator < TProtocol > eventIter , ThriftField setFieldDefinition ) throws TException { TSet thriftSet = acceptProtocol ( eventIter . next ( ) ) . readSetBegin ( ) ; ThriftField elementFieldDefinition = ( ( ThriftType . SetType ) setFieldDefinition . getType ( ) ) . getValues ( ) ; int setSize = thriftSet . size ; for ( int i = 0 ; i < setSize ; i ++ ) { checkField ( thriftSet . elemType , eventIter , elementFieldDefinition ) ; } acceptProtocol ( eventIter . next ( ) ) . readSetEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads the meta data from the stream [CODESPLIT] public static FileMetaData readFileMetaData ( InputStream from , boolean skipRowGroups ) throws IOException { FileMetaData md = new FileMetaData ( ) ; if ( skipRowGroups ) { readFileMetaData ( from , new DefaultFileMetaDataConsumer ( md ) , skipRowGroups ) ; } else { read ( from , md ) ; } return md ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "close the file [CODESPLIT] @ Override public void close ( ) throws IOException { try { recordWriter . close ( taskAttemptContext ) ; } catch ( InterruptedException e ) { Thread . interrupted ( ) ; throw new IOException ( \"The thread was interrupted\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the schema being written to the job conf [CODESPLIT] public static void setSchema ( Job job , MessageType schema ) { GroupWriteSupport . setSchema ( schema , ContextUtil . getConfiguration ( job ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set up the mapping in both directions [CODESPLIT] private static void add ( Class < ? > c , PrimitiveTypeName p ) { Set < PrimitiveTypeName > descriptors = classToParquetType . get ( c ) ; if ( descriptors == null ) { descriptors = new HashSet < PrimitiveTypeName > ( ) ; classToParquetType . put ( c , descriptors ) ; } descriptors . add ( p ) ; Set < Class < ? > > classes = parquetTypeToClass . get ( p ) ; if ( classes == null ) { classes = new HashSet < Class < ? > > ( ) ; parquetTypeToClass . put ( p , classes ) ; } classes . add ( c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts that foundColumn was declared as a type that is compatible with the type for this column found in the schema of the parquet file . [CODESPLIT] public static < T extends Comparable < T > > void assertTypeValid ( Column < T > foundColumn , PrimitiveTypeName primitiveType ) { Class < T > foundColumnType = foundColumn . getColumnType ( ) ; ColumnPath columnPath = foundColumn . getColumnPath ( ) ; Set < PrimitiveTypeName > validTypeDescriptors = classToParquetType . get ( foundColumnType ) ; if ( validTypeDescriptors == null ) { StringBuilder message = new StringBuilder ( ) ; message . append ( \"Column \" ) . append ( columnPath . toDotString ( ) ) . append ( \" was declared as type: \" ) . append ( foundColumnType . getName ( ) ) . append ( \" which is not supported in FilterPredicates.\" ) ; Set < Class < ? > > supportedTypes = parquetTypeToClass . get ( primitiveType ) ; if ( supportedTypes != null ) { message . append ( \" Supported types for this column are: \" ) . append ( supportedTypes ) ; } else { message . append ( \" There are no supported types for columns of \" + primitiveType ) ; } throw new IllegalArgumentException ( message . toString ( ) ) ; } if ( ! validTypeDescriptors . contains ( primitiveType ) ) { StringBuilder message = new StringBuilder ( ) ; message . append ( \"FilterPredicate column: \" ) . append ( columnPath . toDotString ( ) ) . append ( \"'s declared type (\" ) . append ( foundColumnType . getName ( ) ) . append ( \") does not match the schema found in file metadata. Column \" ) . append ( columnPath . toDotString ( ) ) . append ( \" is of type: \" ) . append ( primitiveType ) . append ( \"\\nValid types for this column are: \" ) . append ( parquetTypeToClass . get ( primitiveType ) ) ; throw new IllegalArgumentException ( message . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join an Iterable of Strings into a single string with a delimiter . For example join ( Arrays . asList ( foo bar x ) | ) would return foo||bar|x [CODESPLIT] public static String join ( Iterable < String > s , String on ) { return join ( s . iterator ( ) , on ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join an Iterator of Strings into a single string with a delimiter . For example join ( Arrays . asList ( foo bar x ) | ) would return foo||bar|x [CODESPLIT] public static String join ( Iterator < String > iter , String on ) { StringBuilder sb = new StringBuilder ( ) ; while ( iter . hasNext ( ) ) { sb . append ( iter . next ( ) ) ; if ( iter . hasNext ( ) ) { sb . append ( on ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join an Array of Strings into a single string with a delimiter . For example join ( new String [] { foo bar x } | ) would return foo||bar|x [CODESPLIT] public static String join ( String [ ] s , String on ) { return join ( Arrays . asList ( s ) , on ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands a string according to { @link #expandGlob ( String ) } and then constructs a { @link WildcardPath } for each expanded result which can be used to match strings as described in { @link WildcardPath } . [CODESPLIT] public static List < WildcardPath > expandGlobToWildCardPaths ( String globPattern , char delim ) { List < WildcardPath > ret = new ArrayList < WildcardPath > ( ) ; for ( String expandedGlob : Strings . expandGlob ( globPattern ) ) { ret . add ( new WildcardPath ( globPattern , expandedGlob , delim ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cast value to a an int or throw an exception if there is an overflow . [CODESPLIT] public static int checkedCast ( long value ) { int valueI = ( int ) value ; if ( valueI != value ) { throw new IllegalArgumentException ( String . format ( \"Overflow casting %d to an int\" , value ) ) ; } return valueI ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method visible for testing purposes [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) Class < ? extends HiveBinding > create ( ClassLoader classLoader ) { // HiveVersionInfo was added in 0.11, if the class does // not exist then return the hive binding for 0.10 Class hiveVersionInfo ; try { hiveVersionInfo = Class . forName ( HIVE_VERSION_CLASS_NAME , true , classLoader ) ; } catch ( ClassNotFoundException e ) { LOG . debug ( \"Class \" + HIVE_VERSION_CLASS_NAME + \", not found, returning {}\" , Hive010Binding . class . getSimpleName ( ) ) ; return Hive010Binding . class ; } return createInternal ( hiveVersionInfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method visible for testing purposes [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) Class < ? extends HiveBinding > createInternal ( Class hiveVersionInfo ) { String hiveVersion ; try { Method getVersionMethod = hiveVersionInfo . getMethod ( HIVE_VERSION_METHOD_NAME , ( Class [ ] ) null ) ; String rawVersion = ( String ) getVersionMethod . invoke ( null , ( Object [ ] ) null ) ; LOG . debug ( \"Raw Version from {} is '{}'\" , hiveVersionInfo . getSimpleName ( ) , rawVersion ) ; hiveVersion = trimVersion ( rawVersion ) ; } catch ( Exception e ) { throw new UnexpectedHiveVersionProviderError ( \"Unexpected error whilst \" + \"determining Hive version\" , e ) ; } if ( hiveVersion . equalsIgnoreCase ( HIVE_VERSION_UNKNOWN ) ) { LOG . debug ( \"Unknown hive version, attempting to guess\" ) ; return createBindingForUnknownVersion ( ) ; } if ( hiveVersion . startsWith ( HIVE_VERSION_010 ) ) { LOG . debug ( \"Hive version {}, returning {}\" , hiveVersion , Hive010Binding . class . getSimpleName ( ) ) ; return Hive010Binding . class ; } else if ( hiveVersion . startsWith ( HIVE_VERSION_011 ) ) { LOG . debug ( \"Hive version \" + hiveVersion + \", returning \" + Hive010Binding . class . getSimpleName ( ) + \" as it's expected the 0.10 \" + \"binding will work with 0.11\" ) ; return Hive010Binding . class ; } else if ( hiveVersion . startsWith ( HIVE_VERSION_013 ) ) { throw new HiveBindingInstantiationError ( \"Hive 0.13 contains native Parquet support \" + \"and the parquet-hive jars from the parquet project should not be included \" + \"in Hive's classpath.\" ) ; } LOG . debug ( \"Hive version {}, returning {}\" , hiveVersion , Hive012Binding . class . getSimpleName ( ) ) ; // as of 11/26/2013 it looks like the 0.12 binding will work for 0.13 return Hive012Binding . class ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : all the catching of Exceptions below -- see PARQUET - 383 [CODESPLIT] public static void writeMetaDataFile ( Configuration configuration , Path outputPath ) { JobSummaryLevel level = ParquetOutputFormat . getJobSummaryLevel ( configuration ) ; if ( level == JobSummaryLevel . NONE ) { return ; } try { final FileSystem fileSystem = outputPath . getFileSystem ( configuration ) ; FileStatus outputStatus = fileSystem . getFileStatus ( outputPath ) ; List < Footer > footers ; switch ( level ) { case ALL : footers = ParquetFileReader . readAllFootersInParallel ( configuration , outputStatus , false ) ; // don't skip row groups break ; case COMMON_ONLY : footers = ParquetFileReader . readAllFootersInParallel ( configuration , outputStatus , true ) ; // skip row groups break ; default : throw new IllegalArgumentException ( \"Unrecognized job summary level: \" + level ) ; } // If there are no footers, _metadata file cannot be written since there is no way to determine schema! // Onus of writing any summary files lies with the caller in this case. if ( footers . isEmpty ( ) ) { return ; } try { ParquetFileWriter . writeMetadataFile ( configuration , outputPath , footers , level ) ; } catch ( Exception e ) { LOG . warn ( \"could not write summary file(s) for \" + outputPath , e ) ; final Path metadataPath = new Path ( outputPath , ParquetFileWriter . PARQUET_METADATA_FILE ) ; try { if ( fileSystem . exists ( metadataPath ) ) { fileSystem . delete ( metadataPath , true ) ; } } catch ( Exception e2 ) { LOG . warn ( \"could not delete metadata file\" + outputPath , e2 ) ; } try { final Path commonMetadataPath = new Path ( outputPath , ParquetFileWriter . PARQUET_COMMON_METADATA_FILE ) ; if ( fileSystem . exists ( commonMetadataPath ) ) { fileSystem . delete ( commonMetadataPath , true ) ; } } catch ( Exception e2 ) { LOG . warn ( \"could not delete metadata file\" + outputPath , e2 ) ; } } } catch ( Exception e ) { LOG . warn ( \"could not write summary file for \" + outputPath , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compatibility API [CODESPLIT] @ Deprecated public void unpack8Values ( final byte [ ] input , final int inPos , final int [ ] output , final int outPos ) { unpack8Values ( ByteBuffer . wrap ( input ) , inPos , output , outPos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compatibility API [CODESPLIT] @ Deprecated public void unpack32Values ( byte [ ] input , int inPos , int [ ] output , int outPos ) { unpack32Values ( ByteBuffer . wrap ( input ) , inPos , output , outPos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Parquet Schema from an Arrow one and returns the mapping [CODESPLIT] public SchemaMapping fromArrow ( Schema arrowSchema ) { List < Field > fields = arrowSchema . getFields ( ) ; List < TypeMapping > parquetFields = fromArrow ( fields ) ; MessageType parquetType = addToBuilder ( parquetFields , Types . buildMessage ( ) ) . named ( \"root\" ) ; return new SchemaMapping ( arrowSchema , parquetType , parquetFields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an Arrow Schema from an Parquet one and returns the mapping [CODESPLIT] public SchemaMapping fromParquet ( MessageType parquetSchema ) { List < Type > fields = parquetSchema . getFields ( ) ; List < TypeMapping > mappings = fromParquet ( fields ) ; List < Field > arrowFields = fields ( mappings ) ; return new SchemaMapping ( new Schema ( arrowFields ) , parquetSchema , mappings ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a Parquet and Arrow Schema For now does not validate primitive type compatibility [CODESPLIT] public SchemaMapping map ( Schema arrowSchema , MessageType parquetSchema ) { List < TypeMapping > children = map ( arrowSchema . getFields ( ) , parquetSchema . getFields ( ) ) ; return new SchemaMapping ( arrowSchema , parquetSchema , children ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] List < SchemaElement > toParquetSchema ( MessageType schema ) { List < SchemaElement > result = new ArrayList < SchemaElement > ( ) ; addToList ( result , schema ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] Set < org . apache . parquet . column . Encoding > fromFormatEncodings ( List < Encoding > encodings ) { Set < org . apache . parquet . column . Encoding > converted = new HashSet < org . apache . parquet . column . Encoding > ( ) ; for ( Encoding encoding : encodings ) { converted . add ( getEncoding ( encoding ) ) ; } // make converted unmodifiable, drop reference to modifiable copy converted = Collections . unmodifiableSet ( converted ) ; // atomically update the cache Set < org . apache . parquet . column . Encoding > cached = cachedEncodingSets . putIfAbsent ( converted , converted ) ; if ( cached == null ) { // cached == null signifies that converted was *not* in the cache previously // so we can return converted instead of throwing it away, it has now // been cached cached = converted ; } return cached ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static org . apache . parquet . column . statistics . Statistics fromParquetStatisticsInternal ( String createdBy , Statistics formatStats , PrimitiveType type , SortOrder typeSortOrder ) { // create stats object based on the column type org . apache . parquet . column . statistics . Statistics . Builder statsBuilder = org . apache . parquet . column . statistics . Statistics . getBuilderForReading ( type ) ; if ( formatStats != null ) { // Use the new V2 min-max statistics over the former one if it is filled if ( formatStats . isSetMin_value ( ) && formatStats . isSetMax_value ( ) ) { byte [ ] min = formatStats . min_value . array ( ) ; byte [ ] max = formatStats . max_value . array ( ) ; if ( isMinMaxStatsSupported ( type ) || Arrays . equals ( min , max ) ) { statsBuilder . withMin ( min ) ; statsBuilder . withMax ( max ) ; } } else { boolean isSet = formatStats . isSetMax ( ) && formatStats . isSetMin ( ) ; boolean maxEqualsMin = isSet ? Arrays . equals ( formatStats . getMin ( ) , formatStats . getMax ( ) ) : false ; boolean sortOrdersMatch = SortOrder . SIGNED == typeSortOrder ; // NOTE: See docs in CorruptStatistics for explanation of why this check is needed // The sort order is checked to avoid returning min/max stats that are not // valid with the type's sort order. In previous releases, all stats were // aggregated using a signed byte-wise ordering, which isn't valid for all the // types (e.g. strings, decimals etc.). if ( ! CorruptStatistics . shouldIgnoreStatistics ( createdBy , type . getPrimitiveTypeName ( ) ) && ( sortOrdersMatch || maxEqualsMin ) ) { if ( isSet ) { statsBuilder . withMin ( formatStats . min . array ( ) ) ; statsBuilder . withMax ( formatStats . max . array ( ) ) ; } } } if ( formatStats . isSetNull_count ( ) ) { statsBuilder . withNumNulls ( formatStats . null_count ) ; } } return statsBuilder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether to use signed order min and max with a type . It is safe to use signed min and max when the type is a string type and contains only ASCII characters ( where the sign bit was 0 ) . This checks whether the type is a string type and uses { @code useSignedStringMinMax } to determine if only ASCII characters were written . [CODESPLIT] private boolean overrideSortOrderToSigned ( PrimitiveType type ) { // even if the override is set, only return stats for string-ish types // a null type annotation is considered string-ish because some writers // failed to use the UTF8 annotation. LogicalTypeAnnotation annotation = type . getLogicalTypeAnnotation ( ) ; return useSignedStringMinMax && PrimitiveTypeName . BINARY == type . getPrimitiveTypeName ( ) && ( annotation == null || STRING_TYPES . contains ( annotation . getClass ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] Type getType ( PrimitiveTypeName type ) { switch ( type ) { case INT64 : return Type . INT64 ; case INT32 : return Type . INT32 ; case BOOLEAN : return Type . BOOLEAN ; case BINARY : return Type . BYTE_ARRAY ; case FLOAT : return Type . FLOAT ; case DOUBLE : return Type . DOUBLE ; case INT96 : return Type . INT96 ; case FIXED_LEN_BYTE_ARRAY : return Type . FIXED_LEN_BYTE_ARRAY ; default : throw new RuntimeException ( \"Unknown primitive type \" + type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] LogicalTypeAnnotation getLogicalTypeAnnotation ( ConvertedType type , SchemaElement schemaElement ) { switch ( type ) { case UTF8 : return LogicalTypeAnnotation . stringType ( ) ; case MAP : return LogicalTypeAnnotation . mapType ( ) ; case MAP_KEY_VALUE : return LogicalTypeAnnotation . MapKeyValueTypeAnnotation . getInstance ( ) ; case LIST : return LogicalTypeAnnotation . listType ( ) ; case ENUM : return LogicalTypeAnnotation . enumType ( ) ; case DECIMAL : int scale = ( schemaElement == null ? 0 : schemaElement . scale ) ; int precision = ( schemaElement == null ? 0 : schemaElement . precision ) ; return LogicalTypeAnnotation . decimalType ( scale , precision ) ; case DATE : return LogicalTypeAnnotation . dateType ( ) ; case TIME_MILLIS : return LogicalTypeAnnotation . timeType ( true , LogicalTypeAnnotation . TimeUnit . MILLIS ) ; case TIME_MICROS : return LogicalTypeAnnotation . timeType ( true , LogicalTypeAnnotation . TimeUnit . MICROS ) ; case TIMESTAMP_MILLIS : return LogicalTypeAnnotation . timestampType ( true , LogicalTypeAnnotation . TimeUnit . MILLIS ) ; case TIMESTAMP_MICROS : return LogicalTypeAnnotation . timestampType ( true , LogicalTypeAnnotation . TimeUnit . MICROS ) ; case INTERVAL : return LogicalTypeAnnotation . IntervalLogicalTypeAnnotation . getInstance ( ) ; case INT_8 : return LogicalTypeAnnotation . intType ( 8 , true ) ; case INT_16 : return LogicalTypeAnnotation . intType ( 16 , true ) ; case INT_32 : return LogicalTypeAnnotation . intType ( 32 , true ) ; case INT_64 : return LogicalTypeAnnotation . intType ( 64 , true ) ; case UINT_8 : return LogicalTypeAnnotation . intType ( 8 , false ) ; case UINT_16 : return LogicalTypeAnnotation . intType ( 16 , false ) ; case UINT_32 : return LogicalTypeAnnotation . intType ( 32 , false ) ; case UINT_64 : return LogicalTypeAnnotation . intType ( 64 , false ) ; case JSON : return LogicalTypeAnnotation . jsonType ( ) ; case BSON : return LogicalTypeAnnotation . bsonType ( ) ; default : throw new RuntimeException ( \"Can't convert converted type to logical type, unknown converted type \" + type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static FileMetaData filterFileMetaDataByMidpoint ( FileMetaData metaData , RangeMetadataFilter filter ) { List < RowGroup > rowGroups = metaData . getRow_groups ( ) ; List < RowGroup > newRowGroups = new ArrayList < RowGroup > ( ) ; for ( RowGroup rowGroup : rowGroups ) { long totalSize = 0 ; long startIndex = getOffset ( rowGroup . getColumns ( ) . get ( 0 ) ) ; for ( ColumnChunk col : rowGroup . getColumns ( ) ) { totalSize += col . getMeta_data ( ) . getTotal_compressed_size ( ) ; } long midPoint = startIndex + totalSize / 2 ; if ( filter . contains ( midPoint ) ) { newRowGroups . add ( rowGroup ) ; } } metaData . setRow_groups ( newRowGroups ) ; return metaData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static FileMetaData filterFileMetaDataByStart ( FileMetaData metaData , OffsetMetadataFilter filter ) { List < RowGroup > rowGroups = metaData . getRow_groups ( ) ; List < RowGroup > newRowGroups = new ArrayList < RowGroup > ( ) ; for ( RowGroup rowGroup : rowGroups ) { long startIndex = getOffset ( rowGroup . getColumns ( ) . get ( 0 ) ) ; if ( filter . contains ( startIndex ) ) { newRowGroups . add ( rowGroup ) ; } } metaData . setRow_groups ( newRowGroups ) ; return metaData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static long getOffset ( ColumnChunk columnChunk ) { ColumnMetaData md = columnChunk . getMeta_data ( ) ; long offset = md . getData_page_offset ( ) ; if ( md . isSetDictionary_page_offset ( ) && offset > md . getDictionary_page_offset ( ) ) { offset = md . getDictionary_page_offset ( ) ; } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] MessageType fromParquetSchema ( List < SchemaElement > schema , List < ColumnOrder > columnOrders ) { Iterator < SchemaElement > iterator = schema . iterator ( ) ; SchemaElement root = iterator . next ( ) ; Types . MessageTypeBuilder builder = Types . buildMessage ( ) ; if ( root . isSetField_id ( ) ) { builder . id ( root . field_id ) ; } buildChildren ( builder , iterator , root . getNum_children ( ) , columnOrders , 0 ) ; return builder . named ( root . name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Statistics are no longer saved in page headers [CODESPLIT] @ Deprecated public void writeDataPageV2Header ( int uncompressedSize , int compressedSize , int valueCount , int nullCount , int rowCount , org . apache . parquet . column . statistics . Statistics statistics , org . apache . parquet . column . Encoding dataEncoding , int rlByteLength , int dlByteLength , OutputStream to ) throws IOException { writePageHeader ( newDataPageV2Header ( uncompressedSize , compressedSize , valueCount , nullCount , rowCount , dataEncoding , rlByteLength , dlByteLength ) , to ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a <code > long< / code > to the underlying output stream as eight bytes low byte first . In no exception is thrown the counter <code > written< / code > is incremented by <code > 8< / code > . [CODESPLIT] public final void writeLong ( long v ) throws IOException { writeBuffer [ 7 ] = ( byte ) ( v >>> 56 ) ; writeBuffer [ 6 ] = ( byte ) ( v >>> 48 ) ; writeBuffer [ 5 ] = ( byte ) ( v >>> 40 ) ; writeBuffer [ 4 ] = ( byte ) ( v >>> 32 ) ; writeBuffer [ 3 ] = ( byte ) ( v >>> 24 ) ; writeBuffer [ 2 ] = ( byte ) ( v >>> 16 ) ; writeBuffer [ 1 ] = ( byte ) ( v >>> 8 ) ; writeBuffer [ 0 ] = ( byte ) ( v >>> 0 ) ; out . write ( writeBuffer , 0 , 8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips forwards until the filter finds the first match . Returns false if none found . [CODESPLIT] private void skipToMatch ( ) { while ( recordsRead < recordCount && ! recordFilter . isMatch ( ) ) { State currentState = getState ( 0 ) ; do { ColumnReader columnReader = currentState . column ; // currentLevel = depth + 1 at this point // set the current value if ( columnReader . getCurrentDefinitionLevel ( ) >= currentState . maxDefinitionLevel ) { columnReader . skip ( ) ; } columnReader . consume ( ) ; // Based on repetition level work out next state to go to int nextR = currentState . maxRepetitionLevel == 0 ? 0 : columnReader . getCurrentRepetitionLevel ( ) ; currentState = currentState . getNextState ( nextR ) ; } while ( currentState != null ) ; ++ recordsRead ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an object to a configuration . [CODESPLIT] public static void writeObjectToConfAsBase64 ( String key , Object obj , Configuration conf ) throws IOException { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ) { try ( GZIPOutputStream gos = new GZIPOutputStream ( baos ) ; ObjectOutputStream oos = new ObjectOutputStream ( gos ) ) { oos . writeObject ( obj ) ; } conf . set ( key , new String ( Base64 . encodeBase64 ( baos . toByteArray ( ) ) , StandardCharsets . UTF_8 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads an object ( that was written using { @link #writeObjectToConfAsBase64 } ) from a configuration [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T readObjectFromConfAsBase64 ( String key , Configuration conf ) throws IOException { String b64 = conf . get ( key ) ; if ( b64 == null ) { return null ; } byte [ ] bytes = Base64 . decodeBase64 ( b64 . getBytes ( StandardCharsets . UTF_8 ) ) ; try ( ByteArrayInputStream bais = new ByteArrayInputStream ( bytes ) ; GZIPInputStream gis = new GZIPInputStream ( bais ) ; ObjectInputStream ois = new ObjectInputStream ( gis ) ) { return ( T ) ois . readObject ( ) ; } catch ( ClassNotFoundException e ) { throw new IOException ( \"Could not read object from config with key \" + key , e ) ; } catch ( ClassCastException e ) { throw new IOException ( \"Couldn't cast object read from config with key \" + key , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified parameters to this builder . Used by the writers to building up { @link OffsetIndex } objects to be written to the Parquet file . [CODESPLIT] public void add ( int compressedPageSize , long rowCount ) { add ( previousOffset + previousPageSize , compressedPageSize , previousRowIndex + previousRowCount ) ; previousRowCount = rowCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified parameters to this builder . Used by the metadata converter to building up { @link OffsetIndex } objects read from the Parquet file . [CODESPLIT] public void add ( long offset , int compressedPageSize , long firstRowIndex ) { previousOffset = offset ; offsets . add ( offset ) ; previousPageSize = compressedPageSize ; compressedPageSizes . add ( compressedPageSize ) ; previousRowIndex = firstRowIndex ; firstRowIndexes . add ( firstRowIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the offset index . Used by the writers to building up { @link OffsetIndex } objects to be written to the Parquet file . [CODESPLIT] public OffsetIndex build ( long firstPageOffset ) { if ( compressedPageSizes . isEmpty ( ) ) { return null ; } long [ ] offsets = this . offsets . toLongArray ( ) ; if ( firstPageOffset != 0 ) { for ( int i = 0 , n = offsets . length ; i < n ; ++ i ) { offsets [ i ] += firstPageOffset ; } } OffsetIndexImpl offsetIndex = new OffsetIndexImpl ( ) ; offsetIndex . offsets = offsets ; offsetIndex . compressedPageSizes = compressedPageSizes . toIntArray ( ) ; offsetIndex . firstRowIndexes = firstRowIndexes . toLongArray ( ) ; return offsetIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the mapping for the specified key from this cache if present . [CODESPLIT] public V remove ( final K key ) { V oldValue = cacheMap . remove ( key ) ; if ( oldValue != null ) { LOG . debug ( \"Removed cache entry for '{}'\" , key ) ; } return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified key in this cache . The value is only inserted if it is not null and it is considered current . If the cache previously contained a mapping for the key the old value is replaced only if the new value is newer than the old one . [CODESPLIT] public void put ( final K key , final V newValue ) { if ( newValue == null || ! newValue . isCurrent ( key ) ) { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( \"Ignoring new cache entry for '{}' because it is {}\" , key , ( newValue == null ? \"null\" : \"not current\" ) ) ; } return ; } V oldValue = cacheMap . get ( key ) ; if ( oldValue != null && oldValue . isNewerThan ( newValue ) ) { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( \"Ignoring new cache entry for '{}' because \" + \"existing cache entry is newer\" , key ) ; } return ; } // no existing value or new value is newer than old value oldValue = cacheMap . put ( key , newValue ) ; if ( LOG . isDebugEnabled ( ) ) { if ( oldValue == null ) { LOG . debug ( \"Added new cache entry for '{}'\" , key ) ; } else { LOG . debug ( \"Overwrote existing cache entry for '{}'\" , key ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which the specified key is mapped or null if 1 ) the value is not current or 2 ) this cache contains no mapping for the key . [CODESPLIT] public V getCurrentValue ( final K key ) { V value = cacheMap . get ( key ) ; LOG . debug ( \"Value for '{}' {} in cache\" , key , ( value == null ? \"not \" : \"\" ) ) ; if ( value != null && ! value . isCurrent ( key ) ) { // value is not current; remove it and return null remove ( key ) ; return null ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls an appropriate write method based on the value . Value MUST not be null . [CODESPLIT] private void writeValue ( Type type , Schema avroSchema , Object value ) { Schema nonNullAvroSchema = AvroSchemaConverter . getNonNull ( avroSchema ) ; LogicalType logicalType = nonNullAvroSchema . getLogicalType ( ) ; if ( logicalType != null ) { Conversion < ? > conversion = model . getConversionByClass ( value . getClass ( ) , logicalType ) ; writeValueWithoutConversion ( type , nonNullAvroSchema , convert ( nonNullAvroSchema , logicalType , conversion , value ) ) ; } else { writeValueWithoutConversion ( type , nonNullAvroSchema , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls an appropriate write method based on the value . Value must not be null and the schema must not be nullable . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void writeValueWithoutConversion ( Type type , Schema avroSchema , Object value ) { switch ( avroSchema . getType ( ) ) { case BOOLEAN : recordConsumer . addBoolean ( ( Boolean ) value ) ; break ; case INT : if ( value instanceof Character ) { recordConsumer . addInteger ( ( Character ) value ) ; } else { recordConsumer . addInteger ( ( ( Number ) value ) . intValue ( ) ) ; } break ; case LONG : recordConsumer . addLong ( ( ( Number ) value ) . longValue ( ) ) ; break ; case FLOAT : recordConsumer . addFloat ( ( ( Number ) value ) . floatValue ( ) ) ; break ; case DOUBLE : recordConsumer . addDouble ( ( ( Number ) value ) . doubleValue ( ) ) ; break ; case FIXED : recordConsumer . addBinary ( Binary . fromReusedByteArray ( ( ( GenericFixed ) value ) . bytes ( ) ) ) ; break ; case BYTES : if ( value instanceof byte [ ] ) { recordConsumer . addBinary ( Binary . fromReusedByteArray ( ( byte [ ] ) value ) ) ; } else { recordConsumer . addBinary ( Binary . fromReusedByteBuffer ( ( ByteBuffer ) value ) ) ; } break ; case STRING : recordConsumer . addBinary ( fromAvroString ( value ) ) ; break ; case RECORD : writeRecord ( type . asGroupType ( ) , avroSchema , value ) ; break ; case ENUM : recordConsumer . addBinary ( Binary . fromString ( value . toString ( ) ) ) ; break ; case ARRAY : listWriter . writeList ( type . asGroupType ( ) , avroSchema , value ) ; break ; case MAP : writeMap ( type . asGroupType ( ) , avroSchema , ( Map < CharSequence , ? > ) value ) ; break ; case UNION : writeUnion ( type . asGroupType ( ) , avroSchema , value ) ; break ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set and compile a glob pattern [CODESPLIT] public void set ( String glob ) { StringBuilder regex = new StringBuilder ( ) ; int setOpen = 0 ; int curlyOpen = 0 ; int len = glob . length ( ) ; hasWildcard = false ; for ( int i = 0 ; i < len ; i ++ ) { char c = glob . charAt ( i ) ; switch ( c ) { case BACKSLASH : if ( ++ i >= len ) { error ( \"Missing escaped character\" , glob , i ) ; } regex . append ( c ) . append ( glob . charAt ( i ) ) ; continue ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : // escape regex special chars that are not glob special chars regex . append ( BACKSLASH ) ; break ; case ' ' : if ( i + 1 < len && glob . charAt ( i + 1 ) == ' ' ) { regex . append ( ' ' ) ; i ++ ; break ; } regex . append ( \"[^\" + PATH_SEPARATOR + \"]\" ) ; hasWildcard = true ; break ; case ' ' : regex . append ( ' ' ) ; hasWildcard = true ; continue ; case ' ' : // start of a group regex . append ( \"(?:\" ) ; // non-capturing curlyOpen ++ ; hasWildcard = true ; continue ; case ' ' : regex . append ( curlyOpen > 0 ? ' ' : c ) ; continue ; case ' ' : if ( curlyOpen > 0 ) { // end of a group curlyOpen -- ; regex . append ( \")\" ) ; continue ; } break ; case ' ' : if ( setOpen > 0 ) { error ( \"Unclosed character class\" , glob , i ) ; } setOpen ++ ; hasWildcard = true ; break ; case ' ' : // ^ inside [...] can be unescaped if ( setOpen == 0 ) { regex . append ( BACKSLASH ) ; } break ; case ' ' : // [! needs to be translated to [^ regex . append ( setOpen > 0 && ' ' == glob . charAt ( i - 1 ) ? ' ' : ' ' ) ; continue ; case ' ' : // Many set errors like [][] could not be easily detected here, // as []], []-] and [-] are all valid POSIX glob and java regex. // We'll just let the regex compiler do the real work. setOpen = 0 ; break ; default : } regex . append ( c ) ; } if ( setOpen > 0 ) { error ( \"Unclosed character class\" , glob , len ) ; } if ( curlyOpen > 0 ) { error ( \"Unclosed group\" , glob , len ) ; } compiled = Pattern . compile ( regex . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Output content to the console or a file . [CODESPLIT] public void output ( String content , Logger console , String filename ) throws IOException { if ( filename == null || \"-\" . equals ( filename ) ) { console . info ( content ) ; } else { FSDataOutputStream outgoing = create ( filename ) ; try { outgoing . write ( content . getBytes ( StandardCharsets . UTF_8 ) ) ; } finally { outgoing . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a qualified { @link Path } for the { @code filename } . [CODESPLIT] public Path qualifiedPath ( String filename ) throws IOException { Path cwd = defaultFS ( ) . makeQualified ( new Path ( \".\" ) ) ; return new Path ( filename ) . makeQualified ( defaultFS ( ) . getUri ( ) , cwd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link URI } for the { @code filename } that is a qualified Path or a resource URI . [CODESPLIT] public URI qualifiedURI ( String filename ) throws IOException { URI fileURI = URI . create ( filename ) ; if ( RESOURCE_URI_SCHEME . equals ( fileURI . getScheme ( ) ) ) { return fileURI ; } else { return qualifiedPath ( filename ) . toUri ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens an existing file or resource . [CODESPLIT] public InputStream open ( String filename ) throws IOException { if ( STDIN_AS_SOURCE . equals ( filename ) ) { return System . in ; } URI uri = qualifiedURI ( filename ) ; if ( RESOURCE_URI_SCHEME . equals ( uri . getScheme ( ) ) ) { return Resources . getResource ( uri . getRawSchemeSpecificPart ( ) ) . openStream ( ) ; } else { Path filePath = new Path ( uri ) ; // even though it was qualified using the default FS, it may not be in it FileSystem fs = filePath . getFileSystem ( getConf ( ) ) ; return fs . open ( filePath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ClassLoader } for a set of jars and directories . [CODESPLIT] protected static ClassLoader loaderFor ( List < String > jars , List < String > paths ) throws MalformedURLException { return AccessController . doPrivileged ( new GetClassLoader ( urls ( jars , paths ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ClassLoader } for a set of jars . [CODESPLIT] protected static ClassLoader loaderForJars ( List < String > jars ) throws MalformedURLException { return AccessController . doPrivileged ( new GetClassLoader ( urls ( jars , null ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ClassLoader } for a set of directories . [CODESPLIT] protected static ClassLoader loaderForPaths ( List < String > paths ) throws MalformedURLException { return AccessController . doPrivileged ( new GetClassLoader ( urls ( null , paths ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeInteger ( int v ) { try { bitPackingWriter . write ( v ) ; } catch ( IOException e ) { throw new ParquetEncodingException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BytesInput getBytes ( ) { try { this . bitPackingWriter . finish ( ) ; return BytesInput . from ( out ) ; } catch ( IOException e ) { throw new ParquetEncodingException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for record filter which applies the supplied predicate to the specified column . Note that if searching for a repeated sub - attribute it will only ever match against the first instance of it in the object . [CODESPLIT] public static final UnboundRecordFilter column ( final String columnPath , final ColumnPredicates . Predicate predicate ) { checkNotNull ( columnPath , \"columnPath\" ) ; checkNotNull ( predicate , \"predicate\" ) ; return new UnboundRecordFilter ( ) { final String [ ] filterPath = columnPath . split ( \"\\\\.\" ) ; @ Override public RecordFilter bind ( Iterable < ColumnReader > readers ) { for ( ColumnReader reader : readers ) { if ( Arrays . equals ( reader . getDescriptor ( ) . getPath ( ) , filterPath ) ) { return new ColumnRecordFilter ( reader , predicate ) ; } } throw new IllegalArgumentException ( \"Column \" + columnPath + \" does not exist.\" ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the filtered offset index containing only the pages which are overlapping with rowRanges . [CODESPLIT] static OffsetIndex filterOffsetIndex ( OffsetIndex offsetIndex , RowRanges rowRanges , long totalRowCount ) { IntList indexMap = new IntArrayList ( ) ; for ( int i = 0 , n = offsetIndex . getPageCount ( ) ; i < n ; ++ i ) { long from = offsetIndex . getFirstRowIndex ( i ) ; if ( rowRanges . isOverlapping ( from , offsetIndex . getLastRowIndex ( i , totalRowCount ) ) ) { indexMap . add ( i ) ; } } return new FilteredOffsetIndex ( offsetIndex , indexMap . toIntArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "struct is assumed to contain valid structOrUnionType metadata when used with this method . This method may throw if structOrUnionType is unknown . [CODESPLIT] public MessageType convert ( StructType struct ) { MessageType messageType = ThriftSchemaConvertVisitor . convert ( struct , fieldProjectionFilter , true ) ; fieldProjectionFilter . assertNoUnmatchedPatterns ( ) ; return messageType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "struct is not required to have known structOrUnionType which is useful for converting a StructType from an ( older ) file schema to a MessageType [CODESPLIT] public static MessageType convertWithoutProjection ( StructType struct ) { return ThriftSchemaConvertVisitor . convert ( struct , FieldProjectionFilter . ALL_COLUMNS , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given type is the element type of a list or is a synthetic group with one field that is the element type . This is determined by checking whether the type can be a synthetic group and by checking whether a potential synthetic group matches the expected ThriftField . <p > This method never guesses because the expected ThriftField is known . [CODESPLIT] static boolean isListElementType ( Type repeatedType , ThriftField thriftElement ) { if ( repeatedType . isPrimitive ( ) || ( repeatedType . asGroupType ( ) . getFieldCount ( ) != 1 ) || ( repeatedType . asGroupType ( ) . getType ( 0 ) . isRepetition ( REPEATED ) ) ) { // The repeated type must be the element type because it is an invalid // synthetic wrapper. Must be a group with one optional or required field return true ; } else if ( thriftElement != null && thriftElement . getType ( ) instanceof StructType ) { Set < String > fieldNames = new HashSet < String > ( ) ; for ( ThriftField field : ( ( StructType ) thriftElement . getType ( ) ) . getChildren ( ) ) { fieldNames . add ( field . getName ( ) ) ; } // If the repeated type is a subset of the structure of the ThriftField, // then it must be the element type. return fieldNames . contains ( repeatedType . asGroupType ( ) . getFieldName ( 0 ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to preserve the difference between empty list and null when optional [CODESPLIT] private static GroupType listWrapper ( Repetition repetition , String alias , LogicalTypeAnnotation logicalTypeAnnotation , Type nested ) { if ( ! nested . isRepetition ( Repetition . REPEATED ) ) { throw new IllegalArgumentException ( \"Nested type should be repeated: \" + nested ) ; } return new GroupType ( repetition , alias , logicalTypeAnnotation , nested ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a 3 - level list structure annotated with LIST with elements of the given elementType . The repeated level is inserted automatically and the elementType s repetition should be the correct repetition of the elements required for non - null and optional for nullable . [CODESPLIT] public static GroupType listOfElements ( Repetition listRepetition , String name , Type elementType ) { Preconditions . checkArgument ( elementType . getName ( ) . equals ( ELEMENT_NAME ) , \"List element type must be named 'element'\" ) ; return listWrapper ( listRepetition , name , LogicalTypeAnnotation . listType ( ) , new GroupType ( Repetition . REPEATED , \"list\" , elementType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void checkSchema ( ResourceSchema s ) throws IOException { getProperties ( ) . setProperty ( SCHEMA , s . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OutputFormat < Void , Tuple > getOutputFormat ( ) throws IOException { Schema pigSchema = getSchema ( ) ; return new ParquetOutputFormat < Tuple > ( new TupleWriteSupport ( pigSchema ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void putNext ( Tuple tuple ) throws IOException { try { this . recordWriter . write ( null , tuple ) ; } catch ( InterruptedException e ) { Thread . interrupted ( ) ; throw new ParquetEncodingException ( \"Interrupted while writing\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there is a conflicting value when reading from multiple files an exception will be thrown [CODESPLIT] @ Deprecated public Map < String , String > getMergedKeyValueMetaData ( ) { if ( mergedKeyValueMetadata == null ) { Map < String , String > mergedKeyValues = new HashMap < String , String > ( ) ; for ( Entry < String , Set < String > > entry : keyValueMetadata . entrySet ( ) ) { if ( entry . getValue ( ) . size ( ) > 1 ) { throw new RuntimeException ( \"could not merge metadata: key \" + entry . getKey ( ) + \" has conflicting values: \" + entry . getValue ( ) ) ; } mergedKeyValues . put ( entry . getKey ( ) , entry . getValue ( ) . iterator ( ) . next ( ) ) ; } mergedKeyValueMetadata = mergedKeyValues ; } return mergedKeyValueMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets a ParquetInputSplit corresponding to a split given by Hive [CODESPLIT] protected ParquetInputSplit getSplit ( final InputSplit oldSplit , final JobConf conf ) throws IOException { if ( oldSplit instanceof FileSplit ) { FileSplit fileSplit = ( FileSplit ) oldSplit ; final long splitStart = fileSplit . getStart ( ) ; final long splitLength = fileSplit . getLength ( ) ; final Path finalPath = fileSplit . getPath ( ) ; final JobConf cloneJob = hiveBinding . pushProjectionsAndFilters ( conf , finalPath . getParent ( ) ) ; final ParquetMetadata parquetMetadata = ParquetFileReader . readFooter ( cloneJob , finalPath , SKIP_ROW_GROUPS ) ; final FileMetaData fileMetaData = parquetMetadata . getFileMetaData ( ) ; final ReadContext readContext = new DataWritableReadSupport ( ) . init ( cloneJob , fileMetaData . getKeyValueMetaData ( ) , fileMetaData . getSchema ( ) ) ; schemaSize = MessageTypeParser . parseMessageType ( readContext . getReadSupportMetadata ( ) . get ( DataWritableReadSupport . HIVE_SCHEMA_KEY ) ) . getFieldCount ( ) ; return new ParquetInputSplit ( finalPath , splitStart , splitStart + splitLength , splitLength , fileSplit . getLocations ( ) , null ) ; } else { throw new IllegalArgumentException ( \"Unknown split type: \" + oldSplit ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public RecordWriter < Void , T > getRecordWriter ( TaskAttemptContext taskAttemptContext ) throws IOException , InterruptedException { final Configuration conf = getConfiguration ( taskAttemptContext ) ; CompressionCodecName codec = getCodec ( taskAttemptContext ) ; String extension = codec . getExtension ( ) + \".parquet\" ; Path file = getDefaultWorkFile ( taskAttemptContext , extension ) ; return getRecordWriter ( conf , file , codec ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See the general contract of the <code > skipBytes< / code > method of <code > DataInput< / code > . <p > Bytes for this operation are read from the contained input stream . [CODESPLIT] public final int skipBytes ( int n ) throws IOException { int total = 0 ; int cur = 0 ; while ( ( total < n ) && ( ( cur = ( int ) in . skip ( n - total ) ) > 0 ) ) { total += cur ; } return total ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bytes for this operation are read from the contained input stream . [CODESPLIT] public final int readUnsignedShort ( ) throws IOException { int ch2 = in . read ( ) ; int ch1 = in . read ( ) ; if ( ( ch1 | ch2 ) < 0 ) throw new EOFException ( ) ; return ( ch1 << 8 ) + ( ch2 << 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bytes for this operation are read from the contained input stream . [CODESPLIT] public final long readLong ( ) throws IOException { // TODO: see perf question above in readInt readFully ( readBuffer , 0 , 8 ) ; return ( ( ( long ) readBuffer [ 7 ] << 56 ) + ( ( long ) ( readBuffer [ 6 ] & 255 ) << 48 ) + ( ( long ) ( readBuffer [ 5 ] & 255 ) << 40 ) + ( ( long ) ( readBuffer [ 4 ] & 255 ) << 32 ) + ( ( long ) ( readBuffer [ 3 ] & 255 ) << 24 ) + ( ( readBuffer [ 2 ] & 255 ) << 16 ) + ( ( readBuffer [ 1 ] & 255 ) << 8 ) + ( ( readBuffer [ 0 ] & 255 ) << 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a { @code ParquetInputSplit } from a mapreduce { @link FileSplit } . [CODESPLIT] static ParquetInputSplit from ( FileSplit split ) throws IOException { return new ParquetInputSplit ( split . getPath ( ) , split . getStart ( ) , split . getStart ( ) + split . getLength ( ) , split . getLength ( ) , split . getLocations ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a { @code ParquetInputSplit } from a mapred { @link org . apache . hadoop . mapred . FileSplit } . [CODESPLIT] static ParquetInputSplit from ( org . apache . hadoop . mapred . FileSplit split ) throws IOException { return new ParquetInputSplit ( split . getPath ( ) , split . getStart ( ) , split . getStart ( ) + split . getLength ( ) , split . getLength ( ) , split . getLocations ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readFields ( DataInput hin ) throws IOException { byte [ ] bytes = readArray ( hin ) ; DataInputStream in = new DataInputStream ( new GZIPInputStream ( new ByteArrayInputStream ( bytes ) ) ) ; super . readFields ( in ) ; this . end = in . readLong ( ) ; if ( in . readBoolean ( ) ) { this . rowGroupOffsets = new long [ in . readInt ( ) ] ; for ( int i = 0 ; i < rowGroupOffsets . length ; i ++ ) { rowGroupOffsets [ i ] = in . readLong ( ) ; } } in . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void write ( DataOutput hout ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; DataOutputStream out = new DataOutputStream ( new GZIPOutputStream ( baos ) ) ; super . write ( out ) ; out . writeLong ( end ) ; out . writeBoolean ( rowGroupOffsets != null ) ; if ( rowGroupOffsets != null ) { out . writeInt ( rowGroupOffsets . length ) ; for ( long o : rowGroupOffsets ) { out . writeLong ( o ) ; } } out . close ( ) ; writeArray ( hout , baos . toByteArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a builder to construct a required { @link PrimitiveType } . [CODESPLIT] public static PrimitiveBuilder < PrimitiveType > required ( PrimitiveTypeName type ) { return new PrimitiveBuilder < PrimitiveType > ( PrimitiveType . class , type ) . repetition ( Type . Repetition . REQUIRED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a builder to construct an optional { @link PrimitiveType } . [CODESPLIT] public static PrimitiveBuilder < PrimitiveType > optional ( PrimitiveTypeName type ) { return new PrimitiveBuilder < PrimitiveType > ( PrimitiveType . class , type ) . repetition ( Type . Repetition . OPTIONAL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a builder to construct a repeated { @link PrimitiveType } . [CODESPLIT] public static PrimitiveBuilder < PrimitiveType > repeated ( PrimitiveTypeName type ) { return new PrimitiveBuilder < PrimitiveType > ( PrimitiveType . class , type ) . repetition ( Type . Repetition . REPEATED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a builder to construct a required { @link GroupType } . [CODESPLIT] public static GroupBuilder < GroupType > requiredGroup ( ) { return new GroupBuilder < GroupType > ( GroupType . class ) . repetition ( Type . Repetition . REQUIRED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a builder to construct an optional { @link GroupType } . [CODESPLIT] public static GroupBuilder < GroupType > optionalGroup ( ) { return new GroupBuilder < GroupType > ( GroupType . class ) . repetition ( Type . Repetition . OPTIONAL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a builder to construct a repeated { @link GroupType } . [CODESPLIT] public static GroupBuilder < GroupType > repeatedGroup ( ) { return new GroupBuilder < GroupType > ( GroupType . class ) . repetition ( Type . Repetition . REPEATED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( not an actual Iterable ) [CODESPLIT] public IntIterator iterator ( ) { if ( currentSlab == null ) { allocateSlab ( ) ; } int [ ] [ ] itSlabs = slabs . toArray ( new int [ slabs . size ( ) + 1 ] [  ] ) ; itSlabs [ slabs . size ( ) ] = currentSlab ; return new IntIterator ( itSlabs , size ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides if the statistics from a file created by createdBy ( the created_by field from parquet format ) should be ignored because they are potentially corrupt . [CODESPLIT] public static boolean shouldIgnoreStatistics ( String createdBy , PrimitiveTypeName columnType ) { if ( columnType != PrimitiveTypeName . BINARY && columnType != PrimitiveTypeName . FIXED_LEN_BYTE_ARRAY ) { // the bug only applies to binary columns return false ; } if ( Strings . isNullOrEmpty ( createdBy ) ) { // created_by is not populated, which could have been caused by // parquet-mr during the same time as PARQUET-251, see PARQUET-297 warnOnce ( \"Ignoring statistics because created_by is null or empty! See PARQUET-251 and PARQUET-297\" ) ; return true ; } try { ParsedVersion version = VersionParser . parse ( createdBy ) ; if ( ! \"parquet-mr\" . equals ( version . application ) ) { // assume other applications don't have this bug return false ; } if ( Strings . isNullOrEmpty ( version . version ) ) { warnOnce ( \"Ignoring statistics because created_by did not contain a semver (see PARQUET-251): \" + createdBy ) ; return true ; } SemanticVersion semver = SemanticVersion . parse ( version . version ) ; if ( semver . compareTo ( PARQUET_251_FIXED_VERSION ) < 0 && ! ( semver . compareTo ( CDH_5_PARQUET_251_FIXED_START ) >= 0 && semver . compareTo ( CDH_5_PARQUET_251_FIXED_END ) < 0 ) ) { warnOnce ( \"Ignoring statistics because this file was created prior to \" + PARQUET_251_FIXED_VERSION + \", see PARQUET-251\" ) ; return true ; } // this file was created after the fix return false ; } catch ( RuntimeException e ) { // couldn't parse the created_by field, log what went wrong, don't trust the stats, // but don't make this fatal. warnParseErrorOnce ( createdBy , e ) ; return true ; } catch ( SemanticVersionParseException e ) { // couldn't parse the created_by field, log what went wrong, don't trust the stats, // but don't make this fatal. warnParseErrorOnce ( createdBy , e ) ; return true ; } catch ( VersionParseException e ) { // couldn't parse the created_by field, log what went wrong, don't trust the stats, // but don't make this fatal. warnParseErrorOnce ( createdBy , e ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : have those wrappers for a converter [CODESPLIT] private RecordConsumer validator ( RecordConsumer recordConsumer , boolean validating , MessageType schema ) { return validating ? new ValidatingRecordConsumer ( recordConsumer , schema ) : recordConsumer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this was taken from Avro s ReflectData [CODESPLIT] private static Map < String , Class < ? > > getFieldsByName ( Class < ? > recordClass , boolean excludeJava ) { Map < String , Class < ? > > fields = new LinkedHashMap < String , Class < ? > > ( ) ; if ( recordClass != null ) { Class < ? > current = recordClass ; do { if ( excludeJava && current . getPackage ( ) != null && current . getPackage ( ) . getName ( ) . startsWith ( \"java.\" ) ) { break ; // skip java built-in classes } for ( Field field : current . getDeclaredFields ( ) ) { if ( field . isAnnotationPresent ( AvroIgnore . class ) || isTransientOrStatic ( field ) ) { continue ; } AvroName altName = field . getAnnotation ( AvroName . class ) ; Class < ? > existing = fields . put ( altName != null ? altName . value ( ) : field . getName ( ) , field . getType ( ) ) ; if ( existing != null ) { throw new AvroTypeException ( current + \" contains two fields named: \" + field . getName ( ) ) ; } } current = current . getSuperclass ( ) ; } while ( current != null ) ; } return fields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given type is the element type of a list or is a synthetic group with one field that is the element type . This is determined by checking whether the type can be a synthetic group and by checking whether a potential synthetic group matches the expected schema . <p > Unlike { @link AvroSchemaConverter#isElementType ( Type String ) } this method never guesses because the expected schema is known . [CODESPLIT] static boolean isElementType ( Type repeatedType , Schema elementSchema ) { if ( repeatedType . isPrimitive ( ) || repeatedType . asGroupType ( ) . getFieldCount ( ) > 1 || repeatedType . asGroupType ( ) . getType ( 0 ) . isRepetition ( REPEATED ) ) { // The repeated type must be the element type because it is an invalid // synthetic wrapper. Must be a group with one optional or required field return true ; } else if ( elementSchema != null && elementSchema . getType ( ) == Schema . Type . RECORD ) { Schema schemaFromRepeated = CONVERTER . convert ( repeatedType . asGroupType ( ) ) ; if ( checkReaderWriterCompatibility ( elementSchema , schemaFromRepeated ) . getType ( ) == COMPATIBLE ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeMessageBegin ( TMessage message ) throws TException { LOG . debug ( \"writeMessageBegin({})\" , message ) ; currentProtocol . writeMessageBegin ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeStructBegin ( TStruct struct ) throws TException { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( \"writeStructBegin(\" + toString ( struct ) + \")\" ) ; currentProtocol . writeStructBegin ( struct ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeFieldBegin ( TField field ) throws TException { LOG . debug ( \"writeFieldBegin({})\" , field ) ; currentProtocol . writeFieldBegin ( field ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeMapBegin ( TMap map ) throws TException { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( \"writeMapBegin(\" + toString ( map ) + \")\" ) ; currentProtocol . writeMapBegin ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeListBegin ( TList list ) throws TException { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( \"writeListBegin(\" + toString ( list ) + \")\" ) ; currentProtocol . writeListBegin ( list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeSetBegin ( TSet set ) throws TException { LOG . debug ( \"writeSetBegin({})\" , set ) ; currentProtocol . writeSetBegin ( set ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeBool ( boolean b ) throws TException { LOG . debug ( \"writeBool({})\" , b ) ; currentProtocol . writeBool ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeByte ( byte b ) throws TException { LOG . debug ( \"writeByte({})\" , b ) ; currentProtocol . writeByte ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeI16 ( short i16 ) throws TException { LOG . debug ( \"writeI16({})\" , i16 ) ; currentProtocol . writeI16 ( i16 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeI32 ( int i32 ) throws TException { LOG . debug ( \"writeI32({})\" , i32 ) ; currentProtocol . writeI32 ( i32 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeI64 ( long i64 ) throws TException { LOG . debug ( \"writeI64({})\" , i64 ) ; currentProtocol . writeI64 ( i64 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeDouble ( double dub ) throws TException { LOG . debug ( \"writeDouble({})\" , dub ) ; currentProtocol . writeDouble ( dub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeString ( String str ) throws TException { LOG . debug ( \"writeString({})\" , str ) ; currentProtocol . writeString ( str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeBinary ( ByteBuffer buf ) throws TException { LOG . debug ( \"writeBinary({})\" , buf ) ; currentProtocol . writeBinary ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the file column names based on the position within the requested columns and use that as the requested schema . [CODESPLIT] private MessageType resolveSchemaAccess ( MessageType requestedSchema , MessageType fileSchema , Configuration configuration ) { if ( configuration . getBoolean ( PARQUET_COLUMN_INDEX_ACCESS , false ) ) { final List < String > listColumns = getColumns ( configuration . get ( IOConstants . COLUMNS ) ) ; List < Type > requestedTypes = new ArrayList < Type > ( ) ; for ( Type t : requestedSchema . getFields ( ) ) { int index = listColumns . indexOf ( t . getName ( ) ) ; requestedTypes . add ( fileSchema . getType ( index ) ) ; } requestedSchema = new MessageType ( requestedSchema . getName ( ) , requestedTypes ) ; } return requestedSchema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void startField ( String field , int index ) { logOpen ( field ) ; delegate . startField ( field , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void addBinary ( Binary value ) { if ( LOG . isDebugEnabled ( ) ) log ( Arrays . toString ( value . getBytesUnsafe ( ) ) ) ; delegate . addBinary ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void endField ( String field , int index ) { logClose ( field ) ; delegate . endField ( field , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all input files . [CODESPLIT] private List < Path > getInputFiles ( List < String > input ) throws IOException { List < Path > inputFiles = null ; if ( input . size ( ) == 1 ) { Path p = new Path ( input . get ( 0 ) ) ; FileSystem fs = p . getFileSystem ( conf ) ; FileStatus status = fs . getFileStatus ( p ) ; if ( status . isDir ( ) ) { inputFiles = getInputFilesFromDirectory ( status ) ; } } else { inputFiles = parseInputFiles ( input ) ; } checkParquetFiles ( inputFiles ) ; return inputFiles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check input files basically . ParquetFileReader will throw exception when reading an illegal parquet file . [CODESPLIT] private void checkParquetFiles ( List < Path > inputFiles ) throws IOException { if ( inputFiles == null || inputFiles . size ( ) <= 1 ) { throw new IllegalArgumentException ( \"Not enough files to merge\" ) ; } for ( Path inputFile : inputFiles ) { FileSystem fs = inputFile . getFileSystem ( conf ) ; FileStatus status = fs . getFileStatus ( inputFile ) ; if ( status . isDir ( ) ) { throw new IllegalArgumentException ( \"Illegal parquet file: \" + inputFile . toUri ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all parquet files under partition directory . [CODESPLIT] private List < Path > getInputFilesFromDirectory ( FileStatus partitionDir ) throws IOException { FileSystem fs = partitionDir . getPath ( ) . getFileSystem ( conf ) ; FileStatus [ ] inputFiles = fs . listStatus ( partitionDir . getPath ( ) , HiddenFileFilter . INSTANCE ) ; List < Path > input = new ArrayList < Path > ( ) ; for ( FileStatus f : inputFiles ) { input . add ( f . getPath ( ) ) ; } return input ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initFromPage ( int valueCount , ByteBufferInputStream stream ) throws IOException { int effectiveBitLength = valueCount * bitsPerValue ; int length = BytesUtils . paddedByteCountFromBits ( effectiveBitLength ) ; LOG . debug ( \"reading {} bytes for {} values of size {} bits.\" , length , valueCount , bitsPerValue ) ; this . in = stream . sliceStream ( length ) ; this . bitPackingReader = createBitPackingReader ( bitsPerValue , this . in , valueCount ) ; updateNextOffset ( length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns builder for creating a paged query . [CODESPLIT] public static final UnboundRecordFilter page ( final long startPos , final long pageSize ) { return new UnboundRecordFilter ( ) { @ Override public RecordFilter bind ( Iterable < ColumnReader > readers ) { return new PagedRecordFilter ( startPos , pageSize ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static void readFully ( InputStream f , byte [ ] bytes , int start , int len ) throws IOException { int offset = start ; int remaining = len ; while ( remaining > 0 ) { int bytesRead = f . read ( bytes , offset , remaining ) ; if ( bytesRead < 0 ) { throw new EOFException ( \"Reached the end of stream with \" + remaining + \" bytes left to read\" ) ; } remaining -= bytesRead ; offset += bytesRead ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static int readHeapBuffer ( InputStream f , ByteBuffer buf ) throws IOException { int bytesRead = f . read ( buf . array ( ) , buf . arrayOffset ( ) + buf . position ( ) , buf . remaining ( ) ) ; if ( bytesRead < 0 ) { // if this resulted in EOF, don't update position return bytesRead ; } else { buf . position ( buf . position ( ) + bytesRead ) ; return bytesRead ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static void readFullyHeapBuffer ( InputStream f , ByteBuffer buf ) throws IOException { readFully ( f , buf . array ( ) , buf . arrayOffset ( ) + buf . position ( ) , buf . remaining ( ) ) ; buf . position ( buf . limit ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static int readDirectBuffer ( InputStream f , ByteBuffer buf , byte [ ] temp ) throws IOException { // copy all the bytes that return immediately, stopping at the first // read that doesn't return a full buffer. int nextReadLength = Math . min ( buf . remaining ( ) , temp . length ) ; int totalBytesRead = 0 ; int bytesRead ; while ( ( bytesRead = f . read ( temp , 0 , nextReadLength ) ) == temp . length ) { buf . put ( temp ) ; totalBytesRead += bytesRead ; nextReadLength = Math . min ( buf . remaining ( ) , temp . length ) ; } if ( bytesRead < 0 ) { // return -1 if nothing was read return totalBytesRead == 0 ? - 1 : totalBytesRead ; } else { // copy the last partial buffer buf . put ( temp , 0 , bytesRead ) ; totalBytesRead += bytesRead ; return totalBytesRead ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] static void readFullyDirectBuffer ( InputStream f , ByteBuffer buf , byte [ ] temp ) throws IOException { int nextReadLength = Math . min ( buf . remaining ( ) , temp . length ) ; int bytesRead = 0 ; while ( nextReadLength > 0 && ( bytesRead = f . read ( temp , 0 , nextReadLength ) ) >= 0 ) { buf . put ( temp , 0 , bytesRead ) ; nextReadLength = Math . min ( buf . remaining ( ) , temp . length ) ; } if ( bytesRead < 0 && buf . remaining ( ) > 0 ) { throw new EOFException ( \"Reached the end of stream with \" + buf . remaining ( ) + \" bytes left to read\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To consume a list of elements [CODESPLIT] public static < T extends TBase < T , ? extends TFieldIdEnum > > ListConsumer listOf ( Class < T > c , final Consumer < List < T > > consumer ) { class ListConsumer implements Consumer < T > { List < T > list ; @ Override public void consume ( T t ) { list . add ( t ) ; } } final ListConsumer co = new ListConsumer ( ) ; return new DelegatingListElementsConsumer ( struct ( c , co ) ) { @ Override public void consumeList ( TProtocol protocol , EventBasedThriftReader reader , TList tList ) throws TException { co . list = new ArrayList < T > ( ) ; super . consumeList ( protocol , reader , tList ) ; consumer . consume ( co . list ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the mrwork variable in order to get all the partition and start to update the jobconf [CODESPLIT] private void init ( final JobConf job ) { final String plan = HiveConf . getVar ( job , HiveConf . ConfVars . PLAN ) ; if ( mrwork == null && plan != null && plan . length ( ) > 0 ) { mrwork = Utilities . getMapRedWork ( job ) ; pathToPartitionInfo . clear ( ) ; for ( final Map . Entry < String , PartitionDesc > entry : mrwork . getPathToPartitionInfo ( ) . entrySet ( ) ) { pathToPartitionInfo . put ( new Path ( entry . getKey ( ) ) . toUri ( ) . getPath ( ) . toString ( ) , entry . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public JobConf pushProjectionsAndFilters ( JobConf jobConf , Path path ) throws IOException { init ( jobConf ) ; final JobConf cloneJobConf = new JobConf ( jobConf ) ; final PartitionDesc part = pathToPartitionInfo . get ( path . toString ( ) ) ; if ( ( part != null ) && ( part . getTableDesc ( ) != null ) ) { Utilities . copyTableJobPropertiesToConf ( part . getTableDesc ( ) , cloneJobConf ) ; } pushProjectionsAndFilters ( cloneJobConf , path . toString ( ) , path . toUri ( ) . toString ( ) ) ; return cloneJobConf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Iterates over list of fields . * [CODESPLIT] private < T > GroupBuilder < T > convertFields ( GroupBuilder < T > groupBuilder , List < FieldDescriptor > fieldDescriptors ) { for ( FieldDescriptor fieldDescriptor : fieldDescriptors ) { groupBuilder = addField ( fieldDescriptor , groupBuilder ) . id ( fieldDescriptor . getNumber ( ) ) . named ( fieldDescriptor . getName ( ) ) ; } return groupBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "filters a Parquet schema based on a pig schema for projection [CODESPLIT] public MessageType filter ( MessageType schemaToFilter , Schema requestedPigSchema ) { return filter ( schemaToFilter , requestedPigSchema , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "filters a Parquet schema based on a pig schema for projection [CODESPLIT] public MessageType filter ( MessageType schemaToFilter , Schema requestedPigSchema , RequiredFieldList requiredFieldList ) { try { if ( LOG . isDebugEnabled ( ) ) LOG . debug ( \"filtering schema:\\n\" + schemaToFilter + \"\\nwith requested pig schema:\\n \" + requestedPigSchema ) ; List < Type > result = columnAccess . filterTupleSchema ( schemaToFilter , requestedPigSchema , requiredFieldList ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( \"schema:\\n\" + schemaToFilter + \"\\nfiltered to:\\n\" + result ) ; return new MessageType ( schemaToFilter . getName ( ) , result ) ; } catch ( RuntimeException e ) { throw new RuntimeException ( \"can't filter \" + schemaToFilter + \" with \" + requestedPigSchema , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Schema } for the given type . If the type is null the schema will be a nullable String . If isNullable is true the returned schema will be nullable . [CODESPLIT] private static Schema schema ( Schema . Type type , boolean makeNullable ) { Schema schema = Schema . create ( type == null ? Schema . Type . STRING : type ) ; if ( makeNullable || type == null ) { schema = Schema . createUnion ( Lists . newArrayList ( Schema . create ( Schema . Type . NULL ) , schema ) ) ; } return schema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A { @link ThriftRecordConverter } builds an object by working with { @link TProtocol } . The default implementation creates standard Apache Thrift { @link TBase } objects ; to support alternatives such as <a href = http : // github . com / twitter / scrooge > Twiter s Scrooge< / a > a custom converter can be specified ( for example ScroogeRecordConverter from parquet - scrooge ) . [CODESPLIT] @ Deprecated public static void setRecordConverterClass ( JobConf conf , Class < ? > klass ) { setRecordConverterClass ( ( Configuration ) conf , klass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A { @link ThriftRecordConverter } builds an object by working with { @link TProtocol } . The default implementation creates standard Apache Thrift { @link TBase } objects ; to support alternatives such as <a href = http : // github . com / twitter / scrooge > Twiter s Scrooge< / a > a custom converter can be specified ( for example ScroogeRecordConverter from parquet - scrooge ) . [CODESPLIT] public static void setRecordConverterClass ( Configuration conf , Class < ? > klass ) { conf . set ( RECORD_CONVERTER_CLASS_KEY , klass . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the input tuple contains a bag of string representations of TupleSummaryData [CODESPLIT] private static TupleSummaryData merge ( Tuple t ) throws IOException { TupleSummaryData summaryData = new TupleSummaryData ( ) ; DataBag bag = ( DataBag ) t . get ( 0 ) ; for ( Tuple tuple : bag ) { summaryData . merge ( getData ( tuple ) ) ; } return summaryData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The input tuple contains a bag of Tuples to sum up [CODESPLIT] private static TupleSummaryData sumUp ( Schema schema , Tuple t ) throws ExecException { TupleSummaryData summaryData = new TupleSummaryData ( ) ; DataBag bag = ( DataBag ) t . get ( 0 ) ; for ( Tuple tuple : bag ) { summaryData . addTuple ( schema , tuple ) ; } return summaryData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( InputSplit inputSplit , TaskAttemptContext context ) throws IOException , InterruptedException { if ( ContextUtil . hasCounterMethod ( context ) ) { BenchmarkCounter . initCounterFromContext ( context ) ; } else { LOG . error ( String . format ( \"Can not initialize counter because the class '%s' does not have a '.getCounterMethod'\" , context . getClass ( ) . getCanonicalName ( ) ) ) ; } initializeInternalReader ( toParquetSplit ( inputSplit ) , ContextUtil . getConfiguration ( context ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] @ Benchmark public void write1MRowsDefaultBlockAndPageSizeSNAPPY ( ) throws IOException { dataGenerator . generateData ( file_1M_SNAPPY , configuration , PARQUET_2_0 , BLOCK_SIZE_DEFAULT , PAGE_SIZE_DEFAULT , FIXED_LEN_BYTEARRAY_SIZE , SNAPPY , ONE_MILLION ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads a Struct from the underlying protocol and passes the field events to the FieldConsumer [CODESPLIT] public void readStruct ( FieldConsumer c ) throws TException { protocol . readStructBegin ( ) ; readStructContent ( c ) ; protocol . readStructEnd ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads the content of a struct ( fields ) from the underlying protocol and passes the events to c [CODESPLIT] public void readStructContent ( FieldConsumer c ) throws TException { TField field ; while ( true ) { field = protocol . readFieldBegin ( ) ; if ( field . type == TType . STOP ) { break ; } c . consumeField ( protocol , this , field . id , field . type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads the set content ( elements ) from the underlying protocol and passes the events to the set event consumer [CODESPLIT] public void readSetContent ( SetConsumer eventConsumer , TSet tSet ) throws TException { for ( int i = 0 ; i < tSet . size ; i ++ ) { eventConsumer . consumeElement ( protocol , this , tSet . elemType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads the map content ( key values ) from the underlying protocol and passes the events to the map event consumer [CODESPLIT] public void readMapContent ( MapConsumer eventConsumer , TMap tMap ) throws TException { for ( int i = 0 ; i < tMap . size ; i ++ ) { eventConsumer . consumeEntry ( protocol , this , tMap . keyType , tMap . valueType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads a key - value pair [CODESPLIT] public void readMapEntry ( byte keyType , TypedConsumer keyConsumer , byte valueType , TypedConsumer valueConsumer ) throws TException { keyConsumer . read ( protocol , this , keyType ) ; valueConsumer . read ( protocol , this , valueType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads the list content ( elements ) from the underlying protocol and passes the events to the list event consumer [CODESPLIT] public void readListContent ( ListConsumer eventConsumer , TList tList ) throws TException { for ( int i = 0 ; i < tList . size ; i ++ ) { eventConsumer . consumeElement ( protocol , this , tList . elemType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes an int using the requested number of bits . accepts only values less than 2^bitWidth [CODESPLIT] public void writeInt ( int value ) throws IOException { input [ inputSize ] = value ; ++ inputSize ; if ( inputSize == VALUES_WRITTEN_AT_A_TIME ) { pack ( ) ; if ( packedPosition == slabSize ) { slabs . add ( BytesInput . from ( packed ) ) ; totalFullSlabSize += slabSize ; if ( slabSize < bitWidth * MAX_SLAB_SIZE_MULT ) { slabSize *= 2 ; } initPackedSlab ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reads an int in little endian at the given position [CODESPLIT] public static int readIntLittleEndian ( ByteBuffer in , int offset ) throws IOException { int ch4 = in . get ( offset ) & 0xff ; int ch3 = in . get ( offset + 1 ) & 0xff ; int ch2 = in . get ( offset + 2 ) & 0xff ; int ch1 = in . get ( offset + 3 ) & 0xff ; return ( ( ch1 << 24 ) + ( ch2 << 16 ) + ( ch3 << 8 ) + ( ch4 << 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a little endian int to out using the the number of bytes required by bit width @param out an output stream @param v an int value @param bitWidth bit width for padding @throws IOException if there is an exception while writing [CODESPLIT] public static void writeIntLittleEndianPaddedOnBitWidth ( OutputStream out , int v , int bitWidth ) throws IOException { int bytesWidth = paddedByteCountFromBits ( bitWidth ) ; switch ( bytesWidth ) { case 0 : break ; case 1 : writeIntLittleEndianOnOneByte ( out , v ) ; break ; case 2 : writeIntLittleEndianOnTwoBytes ( out , v ) ; break ; case 3 : writeIntLittleEndianOnThreeBytes ( out , v ) ; break ; case 4 : writeIntLittleEndian ( out , v ) ; break ; default : throw new IOException ( String . format ( \"Encountered value (%d) that requires more than 4 bytes\" , v ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uses a trick mentioned in https : // developers . google . com / protocol - buffers / docs / encoding to read zigZag encoded data [CODESPLIT] public static int readZigZagVarInt ( InputStream in ) throws IOException { int raw = readUnsignedVarInt ( in ) ; int temp = ( ( ( raw << 31 ) >> 31 ) ^ raw ) >> 1 ; return temp ^ ( raw & ( 1 << 31 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uses a trick mentioned in https : // developers . google . com / protocol - buffers / docs / encoding to read zigZag encoded data TODO : the implementation is compatible with readZigZagVarInt . Is there a need for different functions? [CODESPLIT] public static long readZigZagVarLong ( InputStream in ) throws IOException { long raw = readUnsignedVarLong ( in ) ; long temp = ( ( ( raw << 63 ) >> 63 ) ^ raw ) >> 1 ; return temp ^ ( raw & ( 1L << 63 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fills specified buffer with uncompressed data . Returns actual number of bytes of uncompressed data . A return value of 0 indicates that { @link #needsInput () } should be called in order to determine if more input data is required . [CODESPLIT] @ Override public synchronized int decompress ( byte [ ] buffer , int off , int len ) throws IOException { SnappyUtil . validateBuffer ( buffer , off , len ) ; if ( inputBuffer . position ( ) == 0 && ! outputBuffer . hasRemaining ( ) ) { return 0 ; } if ( ! outputBuffer . hasRemaining ( ) ) { inputBuffer . rewind ( ) ; Preconditions . checkArgument ( inputBuffer . position ( ) == 0 , \"Invalid position of 0.\" ) ; Preconditions . checkArgument ( outputBuffer . position ( ) == 0 , \"Invalid position of 0.\" ) ; // There is compressed input, decompress it now. int decompressedSize = Snappy . uncompressedLength ( inputBuffer ) ; if ( decompressedSize > outputBuffer . capacity ( ) ) { ByteBuffer oldBuffer = outputBuffer ; outputBuffer = ByteBuffer . allocateDirect ( decompressedSize ) ; CleanUtil . clean ( oldBuffer ) ; } // Reset the previous outputBuffer (i.e. set position to 0) outputBuffer . clear ( ) ; int size = Snappy . uncompress ( inputBuffer , outputBuffer ) ; outputBuffer . limit ( size ) ; // We've decompressed the entire input, reset the input now inputBuffer . clear ( ) ; inputBuffer . limit ( 0 ) ; finished = true ; } // Return compressed output up to 'len' int numBytes = Math . min ( len , outputBuffer . remaining ( ) ) ; outputBuffer . get ( buffer , off , numBytes ) ; return numBytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets input data for decompression . This should be called if and only if { @link #needsInput () } returns <code > true< / code > indicating that more input data is required . ( Both native and non - native versions of various Decompressors require that the data passed in via <code > b [] < / code > remain unmodified until the caller is explicitly notified -- via { @link #needsInput () } -- that the buffer may be safely modified . With this requirement an extra buffer - copy can be avoided . ) [CODESPLIT] @ Override public synchronized void setInput ( byte [ ] buffer , int off , int len ) { SnappyUtil . validateBuffer ( buffer , off , len ) ; if ( inputBuffer . capacity ( ) - inputBuffer . position ( ) < len ) { ByteBuffer newBuffer = ByteBuffer . allocateDirect ( inputBuffer . position ( ) + len ) ; inputBuffer . rewind ( ) ; newBuffer . put ( inputBuffer ) ; ByteBuffer oldBuffer = inputBuffer ; inputBuffer = newBuffer ; CleanUtil . clean ( oldBuffer ) ; } else { inputBuffer . limit ( inputBuffer . position ( ) + len ) ; } inputBuffer . put ( buffer , off , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Avro schema to use for writing . The schema is translated into a Parquet schema so that the records can be written in Parquet format . It is also stored in the Parquet metadata so that records can be reconstructed as Avro objects at read time without specifying a read schema . [CODESPLIT] public static void setSchema ( Job job , Schema schema ) { AvroWriteSupport . setSchema ( ContextUtil . getConfiguration ( job ) , schema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < String > getColumns ( final String columns ) { final List < String > result = ( List < String > ) StringUtils . getStringCollection ( columns ) ; result . removeAll ( virtualColumns ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps a { @link FSDataInputStream } in a { @link SeekableInputStream } implementation for Parquet readers . [CODESPLIT] public static SeekableInputStream wrap ( FSDataInputStream stream ) { Preconditions . checkNotNull ( stream , \"Cannot wrap a null input stream\" ) ; if ( byteBufferReadableClass != null && h2SeekableConstructor != null && byteBufferReadableClass . isInstance ( stream . getWrappedStream ( ) ) ) { try { return h2SeekableConstructor . newInstance ( stream ) ; } catch ( InstantiationException e ) { LOG . warn ( \"Could not instantiate H2SeekableInputStream, falling back to byte array reads\" , e ) ; return new H1SeekableInputStream ( stream ) ; } catch ( IllegalAccessException e ) { LOG . warn ( \"Could not instantiate H2SeekableInputStream, falling back to byte array reads\" , e ) ; return new H1SeekableInputStream ( stream ) ; } catch ( InvocationTargetException e ) { throw new ParquetDecodingException ( \"Could not instantiate H2SeekableInputStream\" , e . getTargetException ( ) ) ; } } else { return new H1SeekableInputStream ( stream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "theoretically they could just copy / paste the output into the Topics bulk edit field in the Kafka config [CODESPLIT] private < T > String convertToRawListString ( Collection < T > collection ) { return \"[ \" + collection . stream ( ) . map ( x -> ' ' + x . toString ( ) + ' ' ) . collect ( Collectors . joining ( \", \" ) ) + \" ]\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should be called only by MapR Streams Producer . It creates a topic using KafkaProducer . [CODESPLIT] @ Override public void createTopicIfNotExists ( String topic , Map < String , Object > kafkaClientConfigs , String metadataBrokerList ) throws StageException { // check stream path and topic if ( topic . startsWith ( \"/\" ) && topic . contains ( \":\" ) ) { String [ ] path = topic . split ( \":\" ) ; if ( path . length != 2 ) { // Stream topic has invalid format. Record will be sent to error throw new StageException ( MapRStreamsErrors . MAPRSTREAMS_21 , topic ) ; } String streamPath = path [ 0 ] ; if ( ! streamCache . contains ( streamPath ) ) { // This pipeline sees this stream path for the 1st time Configuration conf = new Configuration ( ) ; kafkaClientConfigs . forEach ( ( k , v ) -> { conf . set ( k , v . toString ( ) ) ; } ) ; Admin streamAdmin = null ; try { streamAdmin = Streams . newAdmin ( conf ) ; // Check if the stream path exists already streamAdmin . countTopics ( streamPath ) ; streamCache . add ( streamPath ) ; } catch ( TableNotFoundException e ) { LOG . debug ( \"Stream not found. Creating a new stream: \" + streamPath ) ; try { streamAdmin . createStream ( streamPath , Streams . newStreamDescriptor ( ) ) ; streamCache . add ( streamPath ) ; } catch ( IOException ioex ) { throw new StageException ( MapRStreamsErrors . MAPRSTREAMS_22 , streamPath , e . getMessage ( ) , e ) ; } } catch ( IOException | IllegalArgumentException e ) { throw new StageException ( MapRStreamsErrors . MAPRSTREAMS_23 , e . getMessage ( ) , e ) ; } finally { if ( streamAdmin != null ) { streamAdmin . close ( ) ; } } } } // Stream topic can be created through KafkaProducer if Stream Path exists already KafkaProducer < String , String > kafkaProducer = createProducerTopicMetadataClient ( kafkaClientConfigs ) ; kafkaProducer . partitionsFor ( topic ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a StringRedactor based on the JSON found in a file . The file format looks like this : { version : 1 rules : [ { description : This is the first rule trigger : triggerstring 1 search : regex 1 replace : replace 1 } { description : This is the second rule trigger : triggerstring 2 search : regex 2 replace : replace 2 } ] } [CODESPLIT] public static StringRedactor createFromJsonFile ( String fileName ) throws IOException { StringRedactor sr = new StringRedactor ( ) ; if ( fileName == null ) { sr . policy = RedactionPolicy . emptyRedactionPolicy ( ) ; return sr ; } File file = new File ( fileName ) ; // An empty file is explicitly allowed as \"no rules\" if ( file . exists ( ) && file . length ( ) == 0 ) { sr . policy = RedactionPolicy . emptyRedactionPolicy ( ) ; return sr ; } ObjectMapper mapper = new ObjectMapper ( ) ; RedactionPolicy policy = mapper . readValue ( file , RedactionPolicy . class ) ; policy . postProcess ( ) ; sr . policy = policy ; return sr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a StringRedactor based on the JSON found in the given String . The format is identical to that described in createFromJsonFile () . [CODESPLIT] public static StringRedactor createFromJsonString ( String json ) throws IOException { StringRedactor sr = new StringRedactor ( ) ; if ( ( json == null ) || json . isEmpty ( ) ) { sr . policy = RedactionPolicy . emptyRedactionPolicy ( ) ; return sr ; } ObjectMapper mapper = new ObjectMapper ( ) ; RedactionPolicy policy = mapper . readValue ( json , RedactionPolicy . class ) ; policy . postProcess ( ) ; sr . policy = policy ; return sr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create PipelineBean which means instantiating all stages for the pipeline . [CODESPLIT] public PipelineBean create ( boolean forExecution , StageLibraryTask library , PipelineConfiguration pipelineConf , InterceptorCreatorContextBuilder interceptorContextBuilder , List < Issue > errors , Map < String , Object > runtimeParameters ) { int priorErrors = errors . size ( ) ; PipelineConfigBean pipelineConfigBean = create ( pipelineConf , errors , runtimeParameters ) ; StageBean errorStageBean = null ; StageBean statsStageBean = null ; StageBean origin = null ; PipelineStageBeans stages = null ; PipelineStageBeans startEventBeans = null ; PipelineStageBeans stopEventBeans = null ; if ( pipelineConfigBean != null && pipelineConfigBean . constants != null ) { Map < String , Object > resolvedConstants = pipelineConfigBean . constants ; if ( interceptorContextBuilder != null ) { interceptorContextBuilder . withExecutionMode ( pipelineConfigBean . executionMode ) . withDeliveryGuarantee ( pipelineConfigBean . deliveryGuarantee ) ; } // Instantiate usual stages if ( ! pipelineConf . getStages ( ) . isEmpty ( ) ) { origin = createStageBean ( forExecution , library , pipelineConf . getStages ( ) . get ( 0 ) , true , false , false , resolvedConstants , interceptorContextBuilder , errors ) ; stages = createPipelineStageBeans ( forExecution , library , pipelineConf . getStages ( ) . subList ( 1 , pipelineConf . getStages ( ) . size ( ) ) , interceptorContextBuilder , resolvedConstants , errors ) ; } // It is not mandatory to have a stats aggregating target configured StageConfiguration statsStageConf = pipelineConf . getStatsAggregatorStage ( ) ; if ( statsStageConf != null ) { statsStageBean = createStageBean ( forExecution , library , statsStageConf , true , false , false , resolvedConstants , interceptorContextBuilder , errors ) ; } // Error stage is mandatory StageConfiguration errorStageConf = pipelineConf . getErrorStage ( ) ; if ( errorStageConf != null ) { errorStageBean = createStageBean ( forExecution , library , errorStageConf , true , true , false , resolvedConstants , interceptorContextBuilder , errors ) ; } else if ( ! ( pipelineConfigBean . executionMode . equals ( ExecutionMode . BATCH ) || pipelineConfigBean . executionMode . equals ( ExecutionMode . STREAMING ) ) ) { errors . add ( IssueCreator . getPipeline ( ) . create ( PipelineGroups . BAD_RECORDS . name ( ) , \"badRecordsHandling\" , CreationError . CREATION_009 ) ) ; } // Pipeline Lifecycle event handlers StageBean startBean = null ; if ( CollectionUtils . isNotEmpty ( pipelineConf . getStartEventStages ( ) ) ) { startBean = createStageBean ( forExecution , library , pipelineConf . getStartEventStages ( ) . get ( 0 ) , true , false , true , resolvedConstants , interceptorContextBuilder , errors ) ; } startEventBeans = new PipelineStageBeans ( startBean == null ? Collections . emptyList ( ) : ImmutableList . of ( startBean ) ) ; StageBean stopBean = null ; if ( CollectionUtils . isNotEmpty ( pipelineConf . getStopEventStages ( ) ) ) { stopBean = createStageBean ( forExecution , library , pipelineConf . getStopEventStages ( ) . get ( 0 ) , true , false , true , resolvedConstants , interceptorContextBuilder , errors ) ; } stopEventBeans = new PipelineStageBeans ( stopBean == null ? Collections . emptyList ( ) : ImmutableList . of ( stopBean ) ) ; // Validate Webhook Configs if ( pipelineConfigBean . webhookConfigs != null && ! pipelineConfigBean . webhookConfigs . isEmpty ( ) ) { int index = 0 ; for ( PipelineWebhookConfig webhookConfig : pipelineConfigBean . webhookConfigs ) { if ( StringUtils . isEmpty ( webhookConfig . webhookUrl ) ) { Issue issue = IssueCreator . getPipeline ( ) . create ( PipelineGroups . NOTIFICATIONS . name ( ) , \"webhookUrl\" , CreationError . CREATION_080 ) ; issue . setAdditionalInfo ( \"index\" , index ) ; errors . add ( issue ) ; break ; } index ++ ; } } } // Something went wrong if ( errors . size ( ) != priorErrors ) { return null ; } return new PipelineBean ( pipelineConfigBean , origin , stages , errorStageBean , statsStageBean , startEventBeans , stopEventBeans ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates additional PipelineStageBeans for additional runners . Stages will share stage definition and thus class loader with the first given runner . That includes stages with private class loader as well . [CODESPLIT] public PipelineStageBeans duplicatePipelineStageBeans ( StageLibraryTask stageLib , PipelineStageBeans pipelineStageBeans , InterceptorCreatorContextBuilder interceptorCreatorContextBuilder , Map < String , Object > constants , List < Issue > errors ) { List < StageBean > stageBeans = new ArrayList <> ( pipelineStageBeans . size ( ) ) ; for ( StageBean original : pipelineStageBeans . getStages ( ) ) { // Create StageDefinition map for this stage Map < Class , ServiceDefinition > services = original . getServices ( ) . stream ( ) . collect ( Collectors . toMap ( c -> c . getDefinition ( ) . getProvides ( ) , ServiceBean :: getDefinition ) ) ; StageBean stageBean = createStage ( stageLib , original . getDefinition ( ) , ClassLoaderReleaser . NOOP_RELEASER , original . getConfiguration ( ) , services :: get , interceptorCreatorContextBuilder , constants , errors ) ; if ( stageBean != null ) { stageBeans . add ( stageBean ) ; } } return new PipelineStageBeans ( stageBeans ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new instance of StageBean . [CODESPLIT] public StageBean createStageBean ( boolean forExecution , StageLibraryTask library , StageConfiguration stageConf , boolean validateAnnotations , boolean errorStage , boolean pipelineLifecycleStage , Map < String , Object > constants , InterceptorCreatorContextBuilder interceptorContextBuilder , List < Issue > errors ) { IssueCreator issueCreator = IssueCreator . getStage ( stageConf . getInstanceName ( ) ) ; StageBean bean = null ; StageDefinition stageDef = library . getStage ( stageConf . getLibrary ( ) , stageConf . getStageName ( ) , forExecution ) ; if ( stageDef != null ) { // Pipeline lifecycle events validation must match, whether it's also marked as error stage does not matter if ( validateAnnotations ) { if ( pipelineLifecycleStage ) { if ( ! stageDef . isPipelineLifecycleStage ( ) ) { errors . add ( issueCreator . create ( CreationError . CREATION_018 , stageDef . getLibraryLabel ( ) , stageDef . getLabel ( ) , stageConf . getStageVersion ( ) ) ) ; } // For non pipeline lifecycle stages, the error stage annotation must match } else if ( stageDef . isErrorStage ( ) != errorStage ) { if ( stageDef . isErrorStage ( ) ) { errors . add ( issueCreator . create ( CreationError . CREATION_007 , stageDef . getLibraryLabel ( ) , stageDef . getLabel ( ) , stageConf . getStageVersion ( ) ) ) ; } else { errors . add ( issueCreator . create ( CreationError . CREATION_008 , stageDef . getLibraryLabel ( ) , stageDef . getLabel ( ) , stageConf . getStageVersion ( ) ) ) ; } } } bean = createStage ( library , stageDef , library , stageConf , serviceClass -> library . getServiceDefinition ( serviceClass , true ) , interceptorContextBuilder , constants , errors ) ; } else { errors . add ( issueCreator . create ( CreationError . CREATION_006 , stageConf . getLibrary ( ) , stageConf . getStageName ( ) , stageConf . getStageVersion ( ) ) ) ; } return bean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create interceptors for given stage . [CODESPLIT] public List < InterceptorBean > createInterceptors ( StageLibraryTask stageLib , StageConfiguration stageConfiguration , StageDefinition stageDefinition , InterceptorCreatorContextBuilder contextBuilder , InterceptorCreator . InterceptorType interceptorType , List < Issue > issues ) { List < InterceptorBean > beans = new ArrayList <> ( ) ; if ( contextBuilder == null ) { return beans ; } for ( InterceptorDefinition definition : stageLib . getInterceptorDefinitions ( ) ) { InterceptorBean bean = createInterceptor ( stageLib , definition , stageConfiguration , stageDefinition , contextBuilder , interceptorType , issues ) ; if ( bean != null ) { beans . add ( bean ) ; } } return beans ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a default interceptor for given InterceptorDefinition . This method might return null as the underlying interface for default creation allows it as well - in such case no interceptor is needed . [CODESPLIT] public InterceptorBean createInterceptor ( StageLibraryTask stageLib , InterceptorDefinition definition , StageConfiguration stageConfiguration , StageDefinition stageDefinition , InterceptorCreatorContextBuilder contextBuilder , InterceptorCreator . InterceptorType interceptorType , List < Issue > issues ) { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; InterceptorCreator . Context context = contextBuilder . buildFor ( definition . getLibraryDefinition ( ) . getName ( ) , definition . getKlass ( ) . getName ( ) , stageConfiguration , stageDefinition , interceptorType ) ; try { Thread . currentThread ( ) . setContextClassLoader ( definition . getStageClassLoader ( ) ) ; InterceptorCreator creator = definition . getDefaultCreator ( ) . newInstance ( ) ; Interceptor interceptor = creator . create ( context ) ; if ( interceptor == null ) { return null ; } return new InterceptorBean ( definition , interceptor , stageLib ) ; } catch ( IllegalAccessException | InstantiationException e ) { LOG . debug ( \"Can't instantiate interceptor: {}\" , e . toString ( ) , e ) ; IssueCreator issueCreator = IssueCreator . getStage ( stageDefinition . getName ( ) ) ; issues . add ( issueCreator . create ( CreationError . CREATION_000 , \"interceptor\" , definition . getKlass ( ) . getName ( ) , e . toString ( ) ) ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse JSON representation of Avro schema to Avro s Schema JAVA object [CODESPLIT] public static Schema parseSchema ( String schema ) { Schema . Parser parser = new Schema . Parser ( ) ; parser . setValidate ( true ) ; // We sadly can't use this method directly because it was added after 1.7.3 and we have to stay // compatible with 1.7.3 as this version ships with mapr (and thus we end up using it). This code is // however compiled against 1.7.7 and hence we don't have to do reflection here. try { parser . setValidateDefaults ( true ) ; } catch ( NoSuchMethodError e ) { LOG . debug ( \"Running old Avro version that doesn't have 'setValidateDefaults' method\" , e ) ; } return parser . parse ( schema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return Date in milliseconds @param days Number of days since unix epoch @return Milliseconds representation for date [CODESPLIT] public static long daysToMillis ( int days ) { long millisUtc = ( long ) days * MILLIS_PER_DAY ; long tmp = millisUtc - ( long ) ( localTimeZone . getOffset ( millisUtc ) ) ; return millisUtc - ( long ) ( localTimeZone . getOffset ( tmp ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return number of days since the unix epoch . [CODESPLIT] private static int millisToDays ( long millisLocal ) { // We assume millisLocal is midnight of some date. What we are basically trying to do // here is go from local-midnight to UTC-midnight (or whatever time that happens to be). long millisUtc = millisLocal + localTimeZone . getOffset ( millisLocal ) ; int days ; if ( millisUtc >= 0L ) { days = ( int ) ( millisUtc / MILLIS_PER_DAY ) ; } else { days = ( int ) ( ( millisUtc - 86399999 /*(MILLIS_PER_DAY - 1)*/ ) / MILLIS_PER_DAY ) ; } return days ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves avro schema from given header . Throws an exception if the header is missing or is empty . [CODESPLIT] public static String getAvroSchemaFromHeader ( Record record , String headerName ) throws DataGeneratorException { String jsonSchema = record . getHeader ( ) . getAttribute ( headerName ) ; if ( jsonSchema == null || jsonSchema . isEmpty ( ) ) { throw new DataGeneratorException ( Errors . AVRO_GENERATOR_03 , record . getHeader ( ) . getSourceId ( ) ) ; } return jsonSchema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link BigDecimal } from the given bytes and scale . The bytes must adhere to the format that Avro stores decimals in . <br > Avro stores decimal values as two s complement big - endian for the integral portion then the decimal place separately ( via the scale ) . [CODESPLIT] public static BigDecimal bigDecimalFromBytes ( byte [ ] decimalBytes , int scale ) { final BigInteger bigInt = new BigInteger ( decimalBytes ) ; return new BigDecimal ( bigInt , scale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Migrating to service for data format library . [CODESPLIT] private void upgradeV1ToV2 ( List < Config > configs , Context context ) { List < Config > dataFormatConfigs = configs . stream ( ) . filter ( c -> c . getName ( ) . startsWith ( \"dataFormat\" ) ) . collect ( Collectors . toList ( ) ) ; // Remove those configs configs . removeAll ( dataFormatConfigs ) ; // Provide proper prefix dataFormatConfigs = dataFormatConfigs . stream ( ) . map ( c -> new Config ( c . getName ( ) . replace ( \"dataFormatConfig.\" , \"dataGeneratorFormatConfig.\" ) , c . getValue ( ) ) ) . collect ( Collectors . toList ( ) ) ; // And finally register new service context . registerService ( DataFormatGeneratorService . class , dataFormatConfigs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "buffer size . [CODESPLIT] public long getLength ( ) throws IOException { long length = - 1 ; if ( generator != null ) { length = textOutputStream . getByteCount ( ) ; } else if ( seqWriter != null ) { length = seqWriter . getLength ( ) ; } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy BlobStore resources to data directory [CODESPLIT] private void copyBlobstore ( List < String > blobStoreResources , File rootDataDir , File pipelineDir ) throws IOException { if ( blobStoreResources == null ) { return ; } File blobstoreDir = new File ( runtimeInfo . getDataDir ( ) , BLOBSTORE_BASE_DIR ) ; File stagingBlobstoreDir = new File ( rootDataDir , BLOBSTORE_BASE_DIR ) ; if ( ! stagingBlobstoreDir . exists ( ) ) { if ( ! stagingBlobstoreDir . mkdirs ( ) ) { throw new RuntimeException ( \"Failed to create blobstore directory: \" + pipelineDir . getPath ( ) ) ; } } for ( String blobstoreFile : blobStoreResources ) { File srcFile = new File ( blobstoreDir , blobstoreFile ) ; if ( srcFile . exists ( ) ) { final File dstFile = new File ( stagingBlobstoreDir , srcFile . getName ( ) ) ; if ( srcFile . canRead ( ) ) { // ignore files which cannot be read try ( InputStream in = new FileInputStream ( ( srcFile ) ) ) { try ( OutputStream out = new FileOutputStream ( ( dstFile ) ) ) { IOUtils . copy ( in , out ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the listener to use with the next statement . All column information is cleared . [CODESPLIT] public void reset ( ) { columns . clear ( ) ; this . columnsExpected = null ; columnNames = null ; table = null ; schema = null ; insideStatement = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates gauge for the registered thread with the given details . Note that the value of the threadName argument must match the one used to register . [CODESPLIT] public boolean reportHealth ( String threadName , int scheduledDelay , long timestamp ) { ThreadHealthReport threadHealthReport = new ThreadHealthReport ( threadName , scheduledDelay , timestamp ) ; if ( threadToGaugeMap . containsKey ( threadName ) ) { threadToGaugeMap . get ( threadName ) . setThreadHealthReport ( threadHealthReport ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and registers a Gauge with the given thread name . The same name must be used to report health . [CODESPLIT] public boolean register ( String threadName ) { if ( threadToGaugeMap . containsKey ( threadName ) ) { return false ; } ThreadHealthReportGauge threadHealthReportGauge = new ThreadHealthReportGauge ( ) ; MetricsConfigurator . createGauge ( metrics , getHealthGaugeName ( threadName ) , threadHealthReportGauge , name , rev ) ; threadToGaugeMap . put ( threadName , threadHealthReportGauge ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store configuration from control hub in persistent manner inside data directory . This configuration will be loaded on data collector start and will override any configuration from sdc . properties . [CODESPLIT] public static void storeControlHubConfigs ( RuntimeInfo runtimeInfo , Map < String , String > newConfigs ) throws IOException { File configFile = new File ( runtimeInfo . getDataDir ( ) , SCH_CONF_OVERRIDE ) ; Properties properties = new Properties ( ) ; // Load existing properties from disk if they exists if ( configFile . exists ( ) ) { try ( FileReader reader = new FileReader ( configFile ) ) { properties . load ( reader ) ; } } // Propagate updated configuration for ( Map . Entry < String , String > entry : newConfigs . entrySet ( ) ) { if ( entry . getValue ( ) == null ) { properties . remove ( entry . getKey ( ) ) ; } else { properties . setProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } // Store the new updated configuration back to disk try ( FileWriter writer = new FileWriter ( configFile ) ) { properties . store ( writer , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the available information about the user <p / > for this LoginModule the credential can be null which will result in a binding ldap authentication scenario <p / > roles are also an optional concept if required [CODESPLIT] @ Override public UserInfo getUserInfo ( String username ) throws Exception { LdapEntry entry = getEntryWithCredential ( username ) ; if ( entry == null ) { return null ; } String pwdCredential = getUserCredential ( entry ) ; pwdCredential = convertCredentialLdapToJetty ( pwdCredential ) ; Credential credential = Credential . getCredential ( pwdCredential ) ; List < String > roles = getUserRoles ( username , entry . getDn ( ) ) ; return new UserInfo ( username , credential , roles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attempts to get the users credentials from the users context <p / > NOTE : this is not an user authenticated operation [CODESPLIT] private LdapEntry getEntryWithCredential ( String username ) throws LdapException { if ( StringUtils . isBlank ( _userObjectClass ) || StringUtils . isBlank ( _userIdAttribute ) || StringUtils . isBlank ( _userBaseDn ) || StringUtils . isBlank ( _userPasswordAttribute ) ) { LOG . error ( \"Failed to get user because at least one of the following is null : \" + \"[_userObjectClass, _userIdAttribute, _userBaseDn, _userPasswordAttribute ]\" ) ; return null ; } // Create the format of &(objectClass=_userObjectClass)(_userIdAttribute={user})) String userFilter = buildFilter ( _userFilter , _userObjectClass , _userIdAttribute ) ; if ( userFilter . contains ( \"{user}\" ) ) { userFilter = userFilter . replace ( \"{user}\" , username ) ; } LOG . debug ( \"Searching user using the filter {} on user baseDn {}\" , userFilter , _userBaseDn ) ; // Get the group names from each group, which is obtained from roleNameAttribute attribute. SearchRequest request = new SearchRequest ( _userBaseDn , userFilter , _userPasswordAttribute ) ; request . setSearchScope ( SearchScope . SUBTREE ) ; request . setSizeLimit ( 1 ) ; try { SearchOperation search = new SearchOperation ( conn ) ; org . ldaptive . SearchResult result = search . execute ( request ) . getResult ( ) ; LdapEntry entry = result . getEntry ( ) ; LOG . info ( \"Found user?: {}\" , entry != null ) ; return entry ; } catch ( LdapException ex ) { LOG . error ( \"{}\" , ex . toString ( ) , ex ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attempts to get the users roles <p / > NOTE : this is not an user authenticated operation [CODESPLIT] private List < String > getUserRoles ( String username , String userDn ) { List < String > roleList = new ArrayList <> ( ) ; if ( StringUtils . isBlank ( _roleBaseDn ) || StringUtils . isBlank ( _roleObjectClass ) || StringUtils . isBlank ( _roleNameAttribute ) || StringUtils . isBlank ( _roleMemberAttribute ) ) { LOG . debug ( \"Failed to get roles because at least one of the following is null : \" + \"[_roleBaseDn, _roleObjectClass, _roleNameAttribute, _roleMemberAttribute ]\" ) ; return roleList ; } String roleFilter = buildFilter ( _roleFilter , _roleObjectClass , _roleMemberAttribute ) ; if ( _roleFilter . contains ( DN ) ) { userDn = userDn . replace ( \"\\\\\" , \"\\\\\\\\\\\\\" ) ; roleFilter = roleFilter . replace ( DN , userDn ) ; } else if ( _roleFilter . contains ( USER ) ) { roleFilter = roleFilter . replace ( USER , username ) ; } else { LOG . error ( \"roleFilter contains invalid filter {}. Check the roleFilter option\" ) ; return roleList ; } LOG . debug ( \"Searching roles using the filter {} on role baseDn {}\" , roleFilter , _roleBaseDn ) ; // Get the group names from each group, which is obtained from roleNameAttribute attribute. SearchRequest request = new SearchRequest ( _roleBaseDn , roleFilter , _roleNameAttribute ) ; request . setSearchScope ( SearchScope . SUBTREE ) ; try { SearchOperation search = new SearchOperation ( conn ) ; org . ldaptive . SearchResult result = search . execute ( request ) . getResult ( ) ; Collection < LdapEntry > entries = result . getEntries ( ) ; LOG . info ( \"Found roles?: {}\" , ! ( entries == null || entries . isEmpty ( ) ) ) ; if ( entries != null ) { for ( LdapEntry entry : entries ) { roleList . add ( entry . getAttribute ( ) . getStringValue ( ) ) ; } } } catch ( LdapException ex ) { LOG . error ( ex . getMessage ( ) , ex ) ; } LOG . info ( \"Found roles: {}\" , roleList ) ; return roleList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a filter ( user / role filter ) replace attributes using given information from config . This will create complete filter which will look like & ( objectClass = inetOrgPerson ) ( uid = { user } )) [CODESPLIT] @ VisibleForTesting static String buildFilter ( String attrFilter , String objClass , String attrName ) { // check if the filter has surrounding \"()\" if ( ! attrFilter . startsWith ( \"(\" ) ) { attrFilter = \"(\" + attrFilter ; } if ( ! attrFilter . endsWith ( \")\" ) ) { attrFilter = attrFilter + \")\" ; } return String . format ( filterFormat , objClass , String . format ( attrFilter , attrName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "since ldap uses a context bind for valid authentication checking we override login () <p / > if credentials are not available from the users context or if we are forcing the binding check then we try a binding authentication check otherwise if we have the users encoded password then we can try authentication via that mechanic [CODESPLIT] @ Override public boolean login ( ) throws LoginException { try { if ( getCallbackHandler ( ) == null ) { throw new LoginException ( \"No callback handler\" ) ; } if ( conn == null ) { return false ; } Callback [ ] callbacks = configureCallbacks ( ) ; getCallbackHandler ( ) . handle ( callbacks ) ; String webUserName = ( ( NameCallback ) callbacks [ 0 ] ) . getName ( ) ; Object webCredential = ( ( ObjectCallback ) callbacks [ 1 ] ) . getObject ( ) ; if ( webUserName == null || webCredential == null ) { setAuthenticated ( false ) ; return isAuthenticated ( ) ; } // Please see the following stackoverflow article // http://security.stackexchange.com/questions/6713/ldap-security-problems // Some LDAP implementation \"MAY\" accept empty password as a sign of anonymous connection and thus // return \"true\" for the authentication request. if ( ( webCredential instanceof String ) && ( ( String ) webCredential ) . isEmpty ( ) ) { LOG . info ( \"Ignoring login request for user {} as the password is empty.\" , webUserName ) ; setAuthenticated ( false ) ; return isAuthenticated ( ) ; } if ( _forceBindingLogin ) { return bindingLogin ( webUserName , webCredential ) ; } // This sets read and the credential UserInfo userInfo = getUserInfo ( webUserName ) ; if ( userInfo == null ) { setAuthenticated ( false ) ; return false ; } JAASUserInfo jaasUserInfo = new JAASUserInfo ( userInfo ) ; jaasUserInfo . fetchRoles ( ) ; setCurrentUser ( jaasUserInfo ) ; if ( webCredential instanceof String ) { return credentialLogin ( Credential . getCredential ( ( String ) webCredential ) ) ; } return credentialLogin ( webCredential ) ; } catch ( UnsupportedCallbackException e ) { throw new LoginException ( \"Error obtaining callback information.\" ) ; } catch ( IOException e ) { LOG . error ( \"IO Error performing login\" , e ) ; } catch ( Exception e ) { LOG . error ( \"IO Error performing login\" , e ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "password supplied authentication check [CODESPLIT] protected boolean credentialLogin ( Object webCredential ) throws LoginException { boolean credResult = getCurrentUser ( ) . checkCredential ( webCredential ) ; setAuthenticated ( credResult ) ; if ( ! credResult ) { LOG . warn ( \"Authentication failed - Possibly the user password is wrong\" ) ; } return isAuthenticated ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "binding authentication check This method of authentication works only if the user branch of the DIT ( ldap tree ) has an ACI ( access control instruction ) that allow the access to any user or at least for the user that logs in . [CODESPLIT] public boolean bindingLogin ( String username , Object password ) throws Exception { if ( StringUtils . isBlank ( _userObjectClass ) || StringUtils . isBlank ( _userIdAttribute ) || StringUtils . isBlank ( _userBaseDn ) ) { LOG . error ( \"Failed to get user because at least one of the following is null : \" + \"[_userObjectClass, _userIdAttribute, _userBaseDn ]\" ) ; return false ; } LdapEntry userEntry = authenticate ( username , password ) ; if ( userEntry == null ) { return false ; } // If authenticated by LDAP server, the returned LdapEntry contains full DN of the user String userDn = userEntry . getDn ( ) ; if ( userDn == null ) { // This shouldn't happen if LDAP server is configured properly. LOG . error ( \"userDn is found null for the user {}\" , username ) ; return false ; } List < String > roles = getUserRoles ( username , userDn ) ; //Authentication already succeeded. We won't store user password so passing empty credential UserInfo userInfo = new UserInfo ( username , Credential . getCredential ( \"\" ) , roles ) ; JAASUserInfo jaasUserInfo = new JAASUserInfo ( userInfo ) ; jaasUserInfo . fetchRoles ( ) ; setCurrentUser ( jaasUserInfo ) ; setAuthenticated ( true ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform authentication with given username and password . Receive the result from Ldap server [CODESPLIT] private LdapEntry authenticate ( String username , Object password ) { try { SearchDnResolver dnResolver = new SearchDnResolver ( new DefaultConnectionFactory ( connConfig ) ) ; dnResolver . setBaseDn ( _userBaseDn ) ; dnResolver . setSubtreeSearch ( true ) ; String userFilter = buildFilter ( _userFilter , _userObjectClass , _userIdAttribute ) ; LOG . debug ( \"Searching a user with filter {} where user is {}\" , userFilter , username ) ; dnResolver . setUserFilter ( userFilter ) ; // Set Authenticator with username and password. It will return the user if username/password matches. BindAuthenticationHandler authHandler = new BindAuthenticationHandler ( new DefaultConnectionFactory ( connConfig ) ) ; Authenticator auth = new Authenticator ( dnResolver , authHandler ) ; AuthenticationRequest authRequest = new AuthenticationRequest ( ) ; authRequest . setUser ( username ) ; if ( password instanceof char [ ] ) { authRequest . setCredential ( new org . ldaptive . Credential ( new String ( ( char [ ] ) password ) ) ) ; } else if ( password instanceof String ) { authRequest . setCredential ( new org . ldaptive . Credential ( ( String ) password ) ) ; } else { LOG . error ( \"Unexpected type for password '{}'\" , ( password != null ) ? password . getClass ( ) : \"NULL\" ) ; return null ; } String [ ] userRoleAttribute = ReturnAttributes . ALL . value ( ) ; authRequest . setReturnAttributes ( userRoleAttribute ) ; LOG . debug ( \"Retrieved authenticator from factory: {}\" , auth ) ; LOG . debug ( \"Retrieved authentication request from factory: {}\" , authRequest ) ; AuthenticationResponse response = auth . authenticate ( authRequest ) ; LOG . info ( \"Found user?: {}\" , response . getResult ( ) ) ; if ( response . getResult ( ) ) { LdapEntry entry = response . getLdapEntry ( ) ; return entry ; } else { // User not found. Most likely username/password didn't match. Log the reason. LOG . error ( \"Result code: {} - {}\" , response . getResultCode ( ) , response . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Move a series of config values from old names to new names ( one to one correspondence ) . Config values will be preserved . < / p > [CODESPLIT] public static int moveAllTo ( List < Config > configs , String ... names ) { Map < String , String > nameMap = new HashMap <> ( ) ; if ( names . length % 2 == 1 ) { throw new IllegalArgumentException ( \"names was of uneven length\" ) ; } for ( int i = 0 ; i < names . length ; ) { nameMap . put ( names [ i ] , names [ i + 1 ] ) ; i += 2 ; } return moveAllTo ( configs , nameMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Move a series of config values from old names to new names ( one to one correspondence ) . Config values will be preserved . < / p > [CODESPLIT] public static int moveAllTo ( List < Config > configs , Map < String , String > oldToNewNames ) { List < Config > configsToAdd = new ArrayList <> ( ) ; List < Config > configsToRemove = new ArrayList <> ( ) ; int numMoved = 0 ; for ( Config config : configs ) { final String oldName = config . getName ( ) ; if ( oldToNewNames . containsKey ( oldName ) ) { configsToRemove . add ( config ) ; final Object value = config . getValue ( ) ; final String newName = oldToNewNames . get ( oldName ) ; configsToAdd . add ( new Config ( newName , value ) ) ; LOG . info ( String . format ( \"Moving config value %s from old name %s to new name %s\" , value , oldName , newName ) ) ; numMoved ++ ; } } configs . removeAll ( configsToRemove ) ; configs . addAll ( configsToAdd ) ; return numMoved ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns a { @link Config } object from the supplied list with the supplied name if it exists . If a non - null Config is returned the supplied list of { @code configs } will be modified such that it no longer contains the returned value . < / p > [CODESPLIT] public static Config getAndRemoveConfigWithName ( List < Config > configs , String name ) { final Config config = getConfigWithName ( configs , name ) ; if ( config != null ) { configs . remove ( config ) ; } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - login a principal . This method assumes that { [CODESPLIT] private synchronized void reLogin ( ) throws LoginException { if ( ! isKrbTicket ) { return ; } if ( login == null ) { throw new LoginException ( \"Login must be done first\" ) ; } if ( ! hasSufficientTimeElapsed ( ) ) { return ; } log . info ( \"Initiating logout for {}\" , principal ) ; synchronized ( Login . class ) { // register most recent relogin attempt lastLogin = currentElapsedTime ( ) ; //clear up the kerberos state. But the tokens are not cleared! As per //the Java kerberos login module code, only the kerberos credentials //are cleared login . logout ( ) ; //login and also update the subject field of this instance to //have the new credentials (pass it to the LoginContext constructor) login = new LoginContext ( loginContextName , subject ) ; log . info ( \"Initiating re-login for {}\" , principal ) ; login . login ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade whole pipeline at once and return updated variant . [CODESPLIT] public PipelineConfiguration upgradeIfNecessary ( StageLibraryTask library , PipelineConfiguration pipelineConf , List < Issue > issues ) { Preconditions . checkArgument ( issues . isEmpty ( ) , \"Given list of issues must be empty.\" ) ; boolean upgrade ; // Firstly upgrading schema if needed, then data upgrade = needsSchemaUpgrade ( pipelineConf , issues ) ; if ( upgrade && issues . isEmpty ( ) ) { pipelineConf = upgradeSchema ( library , pipelineConf , issues ) ; } // Something went wrong with the schema upgrade if ( ! issues . isEmpty ( ) ) { return null ; } // Upgrading data if needed upgrade = needsUpgrade ( library , pipelineConf , issues ) ; if ( upgrade && issues . isEmpty ( ) ) { //we try to upgrade only if we have all defs for the pipelineConf pipelineConf = upgrade ( library , pipelineConf , issues ) ; } return ( issues . isEmpty ( ) ) ? pipelineConf : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade detached stage ( stage not associated directly with the pipeline ) . [CODESPLIT] public StageConfiguration upgradeIfNecessary ( StageLibraryTask libraryTask , StageConfiguration stageConf , List < Issue > issues ) { Preconditions . checkArgument ( issues . isEmpty ( ) , \"Given list of issues must be empty.\" ) ; boolean upgrade = needsUpgrade ( libraryTask , stageConf , issues ) ; if ( upgrade ) { stageConf = upgradeIfNeeded ( libraryTask , stageConf , issues ) ; } return issues . isEmpty ( ) ? stageConf : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade whole Stage configuration including all services if needed . Convenience method that will lookup stage definition from the library . [CODESPLIT] static StageConfiguration upgradeIfNeeded ( StageLibraryTask library , StageConfiguration conf , List < Issue > issues ) { return upgradeIfNeeded ( library , library . getStage ( conf . getLibrary ( ) , conf . getStageName ( ) , false ) , conf , issues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade whole Stage configuration including all services if needed . [CODESPLIT] static StageConfiguration upgradeIfNeeded ( StageLibraryTask library , StageDefinition def , StageConfiguration conf , List < Issue > issues ) { IssueCreator issueCreator = IssueCreator . getStage ( conf . getInstanceName ( ) ) ; int fromVersion = conf . getStageVersion ( ) ; int toVersion = def . getVersion ( ) ; try { // Firstly upgrade stage itself (register any new services) upgradeStageIfNeeded ( def , conf , issueCreator , issues ) ; // And then upgrade all it's services conf . getServices ( ) . forEach ( serviceConf -> upgradeServicesIfNeeded ( library , conf , serviceConf , issueCreator . forService ( serviceConf . getService ( ) . getName ( ) ) , issues ) ) ; } catch ( Exception ex ) { LOG . error ( \"Unknown exception during upgrade: \" + ex , ex ) ; issues . add ( issueCreator . create ( ContainerError . CONTAINER_0900 , fromVersion , toVersion , ex . toString ( ) ) ) ; } return conf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method that will upgrade service configuration if needed . [CODESPLIT] private static ServiceConfiguration upgradeServicesIfNeeded ( StageLibraryTask library , StageConfiguration stageConf , ServiceConfiguration conf , IssueCreator issueCreator , List < Issue > issues ) { ServiceDefinition def = library . getServiceDefinition ( conf . getService ( ) , false ) ; if ( def == null ) { issues . add ( issueCreator . create ( ContainerError . CONTAINER_0903 , conf . getService ( ) . getName ( ) ) ) ; } int fromVersion = conf . getServiceVersion ( ) ; int toVersion = def . getVersion ( ) ; // In case we don't need an upgrade if ( ! needsUpgrade ( toVersion , fromVersion , issueCreator , issues ) ) { return conf ; } ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { LOG . warn ( \"Upgrading service instance from version '{}' to version '{}'\" , conf . getServiceVersion ( ) , def . getVersion ( ) ) ; UpgradeContext upgradeContext = new UpgradeContext ( \"\" , def . getName ( ) , stageConf . getInstanceName ( ) , fromVersion , toVersion ) ; List < Config > configs = def . getUpgrader ( ) . upgrade ( conf . getConfiguration ( ) , upgradeContext ) ; if ( ! upgradeContext . registeredServices . isEmpty ( ) ) { throw new StageException ( ContainerError . CONTAINER_0904 ) ; } conf . setServiceVersion ( toVersion ) ; conf . setConfig ( configs ) ; } catch ( StageException ex ) { issues . add ( issueCreator . create ( ex . getErrorCode ( ) , ex . getParams ( ) ) ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; } return conf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method that will upgrade only Stage configuration - not the associated services - and only if needed . [CODESPLIT] static private void upgradeStageIfNeeded ( StageDefinition def , StageConfiguration conf , IssueCreator issueCreator , List < Issue > issues ) { int fromVersion = conf . getStageVersion ( ) ; int toVersion = def . getVersion ( ) ; // In case we don't need an upgrade if ( ! needsUpgrade ( toVersion , fromVersion , IssueCreator . getStage ( conf . getInstanceName ( ) ) , issues ) ) { return ; } ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( def . getStageClassLoader ( ) ) ; LOG . warn ( \"Upgrading stage instance '{}' from version '{}' to version '{}'\" , conf . getInstanceName ( ) , fromVersion , toVersion ) ; UpgradeContext upgradeContext = new UpgradeContext ( def . getLibrary ( ) , def . getName ( ) , conf . getInstanceName ( ) , fromVersion , toVersion ) ; List < Config > configs = def . getUpgrader ( ) . upgrade ( conf . getConfiguration ( ) , upgradeContext ) ; conf . setStageVersion ( def . getVersion ( ) ) ; conf . setConfig ( configs ) ; // Propagate newly registered services to the StageConfiguration if ( ! upgradeContext . registeredServices . isEmpty ( ) ) { List < ServiceConfiguration > services = new ArrayList <> ( ) ; services . addAll ( conf . getServices ( ) ) ; // Version -1 is special to note that this version has been created by stage and not by the service itself upgradeContext . registeredServices . forEach ( ( s , c ) -> services . add ( new ServiceConfiguration ( s , - 1 , c ) ) ) ; conf . setServices ( services ) ; } } catch ( StageException ex ) { issues . add ( issueCreator . create ( ex . getErrorCode ( ) , ex . getParams ( ) ) ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the file offsets to use for the next read . To work correctly the last return offsets should be used or an empty <code > Map< / code > if there is none . <p / > If a reader is already live the corresponding set offset is ignored as we cache all the contextual information of live readers . [CODESPLIT] @ Override public void setOffsets ( Map < String , String > offsets ) throws IOException { Utils . checkNotNull ( offsets , \"offsets\" ) ; LOG . trace ( \"setOffsets()\" ) ; // We look for created directory paths here findCreatedDirectories ( ) ; // we look for new files only here findNewFileContexts ( ) ; // we purge file only here purge ( ) ; super . setOffsets ( offsets ) ; startNewLoop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "should be replaced by null . [CODESPLIT] private List < String > getFieldsToNull ( List < NullReplacerConditionalConfig > nullReplacerConditionalConfigs , Set < String > fieldsThatDoNotExist , Set < String > fieldPaths , Record record ) throws OnRecordErrorException { //Gather in this all fields to null List < String > fieldsToNull = new ArrayList <> ( ) ; for ( NullReplacerConditionalConfig nullReplacerConditionalConfig : nullReplacerConditionalConfigs ) { List < String > fieldNamesToNull = nullReplacerConditionalConfig . fieldsToNull ; //Gather fieldsPathsToNull for this nullReplacerConditionalConfig List < String > fieldPathsToNull = new ArrayList <> ( ) ; //Gather existing paths for each nullReplacerConditionalConfig //And if field does not exist gather them in fieldsThatDoNotExist for ( String fieldNameToNull : fieldNamesToNull ) { try { final List < String > matchingPaths = FieldPathExpressionUtil . evaluateMatchingFieldPaths ( fieldNameToNull , fieldPathEval , fieldPathVars , record , fieldPaths ) ; if ( matchingPaths . isEmpty ( ) ) { // FieldPathExpressionUtil.evaluateMatchingFieldPaths does NOT return the supplied param in its result // regardless, like FieldRegexUtil#getMatchingFieldPaths did, so we add manually here fieldsThatDoNotExist . add ( fieldNameToNull ) ; } else { for ( String matchingField : matchingPaths ) { if ( record . has ( matchingField ) ) { fieldPathsToNull . add ( matchingField ) ; } else { fieldsThatDoNotExist . add ( matchingField ) ; } } } } catch ( ELEvalException e ) { LOG . error ( \"Error evaluating condition: \" + nullReplacerConditionalConfig . condition , e ) ; throw new OnRecordErrorException ( record , Errors . VALUE_REPLACER_07 , fieldNameToNull , e . toString ( ) , e ) ; } } //Now evaluate the condition in nullReplacerConditionalConfig //If it empty or condition evaluates to true, add all the gathered fields in fieldsPathsToNull // for this nullReplacerConditionalConfig to fieldsToNull try { boolean evaluatedCondition = true ; //If it is empty we assume it is true. if ( ! StringUtils . isEmpty ( nullReplacerConditionalConfig . condition ) ) { evaluatedCondition = nullConditionELEval . eval ( nullConditionELVars , nullReplacerConditionalConfig . condition , Boolean . class ) ; } if ( evaluatedCondition ) { fieldsToNull . addAll ( fieldPathsToNull ) ; } } catch ( ELEvalException e ) { LOG . error ( \"Error evaluating condition: \" + nullReplacerConditionalConfig . condition , e ) ; throw new OnRecordErrorException ( record , Errors . VALUE_REPLACER_06 , nullReplacerConditionalConfig . condition , e . toString ( ) ) ; } } return fieldsToNull ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a class should be included as a system class . [CODESPLIT] private static boolean isSystemClass ( String name , List < String > packageList ) { boolean result = false ; if ( packageList != null ) { String canonicalName = ClassLoaderUtil . canonicalizeClassOrResource ( name ) ; for ( String c : packageList ) { boolean shouldInclude = true ; if ( c . startsWith ( \"-\" ) ) { c = c . substring ( 1 ) ; shouldInclude = false ; } if ( canonicalName . startsWith ( c ) ) { if ( c . endsWith ( \".\" ) // package || canonicalName . length ( ) == c . length ( ) // class || canonicalName . length ( ) > c . length ( ) // nested && canonicalName . charAt ( c . length ( ) ) == ' ' ) { if ( shouldInclude ) { result = true ; } else { return false ; } } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible For Testing ( TODO - Import guava and make sure it doesn t conflict with spark s rootclassloader ) [CODESPLIT] CheckpointPath getCheckPointPath ( String topic , String consumerGroup ) { return new CheckpointPath . Builder ( CHECKPOINT_BASE_DIR ) . sdcId ( Utils . getPropertyNotNull ( properties , SDC_ID ) ) . topic ( topic ) . consumerGroup ( consumerGroup ) . pipelineName ( Utils . getPropertyNotNull ( properties , ClusterModeConstants . CLUSTER_PIPELINE_NAME ) ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given element to this queue . If the queue is currently full the element at the head of the queue is evicted to make room . [CODESPLIT] @ Override public boolean add ( E e ) { checkNotNull ( e ) ; // check before removing if ( maxSize == 0 ) { return true ; } if ( size ( ) == maxSize ) { delegate . remove ( ) ; } delegate . add ( e ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given element to this queue . If the queue is currently full the element at the head of the queue is evicted to make room and returns the evicted element . [CODESPLIT] public E addAndGetEvicted ( E e ) { checkNotNull ( e ) ; // check before removing if ( maxSize == 0 ) { return null ; } E evicted = null ; if ( size ( ) == maxSize ) { evicted = delegate . remove ( ) ; } delegate . add ( e ) ; return evicted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to ensure that we return and not cache the default value if needed [CODESPLIT] private Optional < Value > valueOrDefault ( Key key , Optional < Value > value ) { // If value is present simply return it if ( value . isPresent ( ) ) { return value ; } if ( ! cacheMissingValues ) { delegate . invalidate ( key ) ; } return defaultValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Preview only returns data associated with batches however errors are reported outside of batch context for multi - threaded pipelines . Thus we emulate the behavior by simply adding into the current batch all so - far reported errors . [CODESPLIT] private List < StageOutput > addReportedErrorsIfNeeded ( List < StageOutput > snapshotsOfAllStagesOutput ) { synchronized ( this . reportedErrors ) { if ( reportedErrors . isEmpty ( ) ) { return snapshotsOfAllStagesOutput ; } try { return snapshotsOfAllStagesOutput . stream ( ) . map ( so -> new StageOutput ( so . getInstanceName ( ) , so . getOutput ( ) , so . getErrorRecords ( ) , reportedErrors . get ( so . getInstanceName ( ) ) , so . getEventRecords ( ) ) ) . collect ( Collectors . toList ( ) ) ; } finally { reportedErrors . clear ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a protobuf descriptor instance from the provided descriptor file . [CODESPLIT] public static Descriptors . Descriptor getDescriptor ( ProtoConfigurableEntity . Context context , String protoDescriptorFile , String messageType , Map < String , Set < Descriptors . FieldDescriptor > > messageTypeToExtensionMap , Map < String , Object > defaultValueMap ) throws StageException { File descriptorFileHandle = new File ( context . getResourcesDirectory ( ) , protoDescriptorFile ) ; try ( FileInputStream fin = new FileInputStream ( descriptorFileHandle ) ; ) { DescriptorProtos . FileDescriptorSet set = DescriptorProtos . FileDescriptorSet . parseFrom ( fin ) ; // Iterate over all the file descriptor set computed above and cache dependencies and all encountered // file descriptors // this map holds all the dependencies that a given file descriptor has. // This cached map will be looked up while building FileDescriptor instances Map < String , Set < Descriptors . FileDescriptor > > fileDescriptorDependentsMap = new HashMap <> ( ) ; // All encountered FileDescriptor instances cached based on their name. Map < String , Descriptors . FileDescriptor > fileDescriptorMap = new HashMap <> ( ) ; ProtobufTypeUtil . getAllFileDescriptors ( set , fileDescriptorDependentsMap , fileDescriptorMap ) ; // Get the descriptor for the expected message type Descriptors . Descriptor descriptor = ProtobufTypeUtil . getDescriptor ( set , fileDescriptorMap , protoDescriptorFile , messageType ) ; // Compute and cache all extensions defined for each message type ProtobufTypeUtil . populateDefaultsAndExtensions ( fileDescriptorMap , messageTypeToExtensionMap , defaultValueMap ) ; return descriptor ; } catch ( FileNotFoundException e ) { throw new StageException ( Errors . PROTOBUF_06 , descriptorFileHandle . getAbsolutePath ( ) , e ) ; } catch ( IOException e ) { throw new StageException ( Errors . PROTOBUF_08 , e . toString ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a Protobuf file descriptor set into an ubermap of file descriptors . [CODESPLIT] public static void getAllFileDescriptors ( DescriptorProtos . FileDescriptorSet set , Map < String , Set < Descriptors . FileDescriptor > > dependenciesMap , Map < String , Descriptors . FileDescriptor > fileDescriptorMap ) throws StageException { List < DescriptorProtos . FileDescriptorProto > fileList = set . getFileList ( ) ; try { for ( DescriptorProtos . FileDescriptorProto fdp : fileList ) { if ( ! fileDescriptorMap . containsKey ( fdp . getName ( ) ) ) { Set < Descriptors . FileDescriptor > dependencies = dependenciesMap . get ( fdp . getName ( ) ) ; if ( dependencies == null ) { dependencies = new LinkedHashSet <> ( ) ; dependenciesMap . put ( fdp . getName ( ) , dependencies ) ; dependencies . addAll ( getDependencies ( dependenciesMap , fileDescriptorMap , fdp , set ) ) ; } Descriptors . FileDescriptor fileDescriptor = Descriptors . FileDescriptor . buildFrom ( fdp , dependencies . toArray ( new Descriptors . FileDescriptor [ dependencies . size ( ) ] ) ) ; fileDescriptorMap . put ( fdp . getName ( ) , fileDescriptor ) ; } } } catch ( Descriptors . DescriptorValidationException e ) { throw new StageException ( Errors . PROTOBUF_07 , e . getDescription ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates a map of protobuf extensions and map with the default values for each message field from a map of file descriptors . [CODESPLIT] public static void populateDefaultsAndExtensions ( Map < String , Descriptors . FileDescriptor > fileDescriptorMap , Map < String , Set < Descriptors . FieldDescriptor > > typeToExtensionMap , Map < String , Object > defaultValueMap ) { for ( Descriptors . FileDescriptor f : fileDescriptorMap . values ( ) ) { // go over every file descriptor and look for extensions and default values of those extensions for ( Descriptors . FieldDescriptor fieldDescriptor : f . getExtensions ( ) ) { String containingType = fieldDescriptor . getContainingType ( ) . getFullName ( ) ; Set < Descriptors . FieldDescriptor > fieldDescriptors = typeToExtensionMap . get ( containingType ) ; if ( fieldDescriptors == null ) { fieldDescriptors = new LinkedHashSet <> ( ) ; typeToExtensionMap . put ( containingType , fieldDescriptors ) ; } fieldDescriptors . add ( fieldDescriptor ) ; if ( fieldDescriptor . hasDefaultValue ( ) ) { defaultValueMap . put ( containingType + \".\" + fieldDescriptor . getName ( ) , fieldDescriptor . getDefaultValue ( ) ) ; } } // go over messages within file descriptor and look for all fields and extensions and their defaults for ( Descriptors . Descriptor d : f . getMessageTypes ( ) ) { addDefaultsAndExtensions ( typeToExtensionMap , defaultValueMap , d ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a protobuf descriptor instance from a FileDescriptor set . [CODESPLIT] public static Descriptors . Descriptor getDescriptor ( DescriptorProtos . FileDescriptorSet set , Map < String , Descriptors . FileDescriptor > fileDescriptorMap , String descriptorFile , String qualifiedMessageType ) throws StageException { // find the FileDescriptorProto which contains the message type // IF cannot find, then bail out String packageName = null ; String messageType = qualifiedMessageType ; int lastIndex = qualifiedMessageType . lastIndexOf ( ' ' ) ; if ( lastIndex != - 1 ) { packageName = qualifiedMessageType . substring ( 0 , lastIndex ) ; messageType = qualifiedMessageType . substring ( lastIndex + 1 ) ; } DescriptorProtos . FileDescriptorProto file = getFileDescProtoForMsgType ( packageName , messageType , set ) ; if ( file == null ) { // could not find the message type from all the proto files contained in the descriptor file throw new StageException ( Errors . PROTOBUF_00 , qualifiedMessageType , descriptorFile ) ; } // finally get the FileDescriptor for the message type Descriptors . FileDescriptor fileDescriptor = fileDescriptorMap . get ( file . getName ( ) ) ; // create builder using the FileDescriptor // this can only find the top level message types return fileDescriptor . findMessageTypeByName ( messageType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a protobuf message to an SDC Record Field . [CODESPLIT] public static Field protobufToSdcField ( Record record , String fieldPath , Descriptors . Descriptor descriptor , Map < String , Set < Descriptors . FieldDescriptor > > messageTypeToExtensionMap , Object message ) throws DataParserException { LinkedHashMap < String , Field > sdcRecordMapFieldValue = new LinkedHashMap <> ( ) ; // get all the expected fields from the proto file Map < String , Descriptors . FieldDescriptor > protobufFields = new LinkedHashMap <> ( ) ; for ( Descriptors . FieldDescriptor fieldDescriptor : descriptor . getFields ( ) ) { protobufFields . put ( fieldDescriptor . getName ( ) , fieldDescriptor ) ; } // get all fields in the read message Map < Descriptors . FieldDescriptor , Object > values = ( ( DynamicMessage ) message ) . getAllFields ( ) ; // for every field present in the proto definition create an sdc field. for ( Descriptors . FieldDescriptor fieldDescriptor : protobufFields . values ( ) ) { Object value = values . get ( fieldDescriptor ) ; sdcRecordMapFieldValue . put ( fieldDescriptor . getName ( ) , createField ( record , fieldPath , fieldDescriptor , messageTypeToExtensionMap , value ) ) ; } // handle applicable extensions for this message type if ( messageTypeToExtensionMap . containsKey ( descriptor . getFullName ( ) ) ) { for ( Descriptors . FieldDescriptor fieldDescriptor : messageTypeToExtensionMap . get ( descriptor . getFullName ( ) ) ) { if ( values . containsKey ( fieldDescriptor ) ) { Object value = values . get ( fieldDescriptor ) ; sdcRecordMapFieldValue . put ( fieldDescriptor . getName ( ) , createField ( record , fieldPath , fieldDescriptor , messageTypeToExtensionMap , value ) ) ; } } } // handle unknown fields // unknown fields can go into the record header UnknownFieldSet unknownFields = ( ( DynamicMessage ) message ) . getUnknownFields ( ) ; if ( ! unknownFields . asMap ( ) . isEmpty ( ) ) { ByteArrayOutputStream bOut = new ByteArrayOutputStream ( ) ; try { unknownFields . writeDelimitedTo ( bOut ) ; bOut . flush ( ) ; bOut . close ( ) ; } catch ( IOException e ) { throw new DataParserException ( Errors . PROTOBUF_10 , e . toString ( ) , e ) ; } String path = fieldPath . isEmpty ( ) ? FORWARD_SLASH : fieldPath ; byte [ ] bytes = org . apache . commons . codec . binary . Base64 . encodeBase64 ( bOut . toByteArray ( ) ) ; record . getHeader ( ) . setAttribute ( PROTOBUF_UNKNOWN_FIELDS_PREFIX + path , new String ( bytes , StandardCharsets . UTF_8 ) ) ; } return Field . createListMap ( sdcRecordMapFieldValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an SDC Record Field from the provided protobuf message and descriptor . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static Field createField ( Record record , String fieldPath , Descriptors . FieldDescriptor fieldDescriptor , Map < String , Set < Descriptors . FieldDescriptor > > messageTypeToExtensionMap , Object message ) throws DataParserException { Field newField ; if ( message == null ) { // If the message does not contain required fields then builder.build() throws UninitializedMessageException Object defaultValue = null ; Descriptors . FieldDescriptor . JavaType javaType = fieldDescriptor . getJavaType ( ) ; // get default values only for optional fields and non-message types if ( fieldDescriptor . isOptional ( ) && fieldDescriptor . getJavaType ( ) != Descriptors . FieldDescriptor . JavaType . MESSAGE ) { defaultValue = fieldDescriptor . getDefaultValue ( ) ; //Default value for byte string should be converted to byte array if ( javaType == Descriptors . FieldDescriptor . JavaType . BYTE_STRING && defaultValue instanceof ByteString ) { defaultValue = ( ( ByteString ) defaultValue ) . toByteArray ( ) ; } } newField = Field . create ( getFieldType ( javaType ) , defaultValue ) ; } else if ( fieldDescriptor . isMapField ( ) ) { // Map entry (protobuf 3 map) Map < String , Field > sdcMapFieldValues = new HashMap <> ( ) ; Collection < DynamicMessage > mapEntries = ( Collection < DynamicMessage > ) message ; // MapEntry for ( DynamicMessage dynamicMessage : mapEntries ) { // MapEntry has 2 fields, key and value Map < Descriptors . FieldDescriptor , Object > kv = dynamicMessage . getAllFields ( ) ; String key = null ; Object value = null ; Descriptors . FieldDescriptor valueDescriptor = null ; for ( Map . Entry < Descriptors . FieldDescriptor , Object > entry : kv . entrySet ( ) ) { switch ( entry . getKey ( ) . getName ( ) ) { case KEY : key = entry . getValue ( ) . toString ( ) ; break ; case VALUE : value = entry . getValue ( ) ; valueDescriptor = entry . getKey ( ) ; break ; default : throw new DataParserException ( Errors . PROTOBUF_09 , entry . getKey ( ) . getName ( ) ) ; } } if ( key != null && valueDescriptor != null ) { sdcMapFieldValues . put ( key , createSdcField ( record , fieldPath , valueDescriptor , messageTypeToExtensionMap , value ) ) ; } } newField = Field . create ( sdcMapFieldValues ) ; } else if ( fieldDescriptor . isRepeated ( ) ) { // List entry (repeated) List < ? > list = ( List < ? > ) message ; List < Field > listField = new ArrayList <> ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( fieldDescriptor . getJavaType ( ) == Descriptors . FieldDescriptor . JavaType . MESSAGE ) { listField . add ( protobufToSdcField ( record , fieldPath + \"[\" + i + \"]\" , fieldDescriptor . getMessageType ( ) , messageTypeToExtensionMap , list . get ( i ) ) ) ; } else { listField . add ( createSdcField ( record , fieldPath + \"[\" + i + \"]\" , fieldDescriptor , messageTypeToExtensionMap , list . get ( i ) ) ) ; } } newField = Field . create ( listField ) ; } else { // normal entry newField = createSdcField ( record , fieldPath , fieldDescriptor , messageTypeToExtensionMap , message ) ; } return newField ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a record to a protobuf message using the specified descriptor . [CODESPLIT] public static DynamicMessage sdcFieldToProtobufMsg ( Record record , Descriptors . Descriptor desc , Map < String , Set < Descriptors . FieldDescriptor > > messageTypeToExtensionMap , Map < String , Object > defaultValueMap ) throws DataGeneratorException { return sdcFieldToProtobufMsg ( record , record . get ( ) , \"\" , desc , messageTypeToExtensionMap , defaultValueMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a field path in a record to a protobuf message using the specified descriptor . [CODESPLIT] private static DynamicMessage sdcFieldToProtobufMsg ( Record record , Field field , String fieldPath , Descriptors . Descriptor desc , Map < String , Set < Descriptors . FieldDescriptor > > messageTypeToExtensionMap , Map < String , Object > defaultValueMap ) throws DataGeneratorException { if ( field == null ) { return null ; } // compute all fields to look for including extensions DynamicMessage . Builder builder = DynamicMessage . newBuilder ( desc ) ; List < Descriptors . FieldDescriptor > fields = new ArrayList <> ( ) ; fields . addAll ( desc . getFields ( ) ) ; if ( messageTypeToExtensionMap . containsKey ( desc . getFullName ( ) ) ) { fields . addAll ( messageTypeToExtensionMap . get ( desc . getFullName ( ) ) ) ; } // root field is always a Map in a record representing protobuf data Map < String , Field > valueAsMap = field . getValueAsMap ( ) ; for ( Descriptors . FieldDescriptor f : fields ) { Field mapField = valueAsMap . get ( f . getName ( ) ) ; // Repeated field if ( f . isMapField ( ) ) { handleMapField ( record , mapField , fieldPath , messageTypeToExtensionMap , defaultValueMap , f , builder ) ; } else if ( f . isRepeated ( ) ) { if ( mapField != null ) { handleRepeatedField ( record , mapField , fieldPath , messageTypeToExtensionMap , defaultValueMap , f , builder ) ; } } else { // non repeated field handleNonRepeatedField ( record , valueAsMap , fieldPath , messageTypeToExtensionMap , defaultValueMap , desc , f , builder ) ; } } // if record has unknown fields for this field path, handle it try { handleUnknownFields ( record , fieldPath , builder ) ; } catch ( IOException e ) { throw new DataGeneratorException ( Errors . PROTOBUF_05 , e . toString ( ) , e ) ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to upgrade both HTTP stages to the JerseyConfigBean [CODESPLIT] public static void upgradeToJerseyConfigBean ( List < Config > configs ) { List < Config > configsToAdd = new ArrayList <> ( ) ; List < Config > configsToRemove = new ArrayList <> ( ) ; List < String > movedConfigs = ImmutableList . of ( \"conf.requestTimeoutMillis\" , \"conf.numThreads\" , \"conf.authType\" , \"conf.oauth\" , \"conf.basicAuth\" , \"conf.useProxy\" , \"conf.proxy\" , \"conf.sslConfig\" ) ; for ( Config config : configs ) { if ( hasPrefixIn ( movedConfigs , config . getName ( ) ) ) { configsToRemove . add ( config ) ; configsToAdd . add ( new Config ( config . getName ( ) . replace ( \"conf.\" , \"conf.client.\" ) , config . getValue ( ) ) ) ; } } configsToAdd . add ( new Config ( \"conf.client.transferEncoding\" , RequestEntityProcessing . CHUNKED ) ) ; configs . removeAll ( configsToRemove ) ; configs . addAll ( configsToAdd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check network connection to the kudu master . [CODESPLIT] public static void checkConnection ( AsyncKuduClient kuduClient , Context context , String KUDU_MASTER , final List < Stage . ConfigIssue > issues ) { try { kuduClient . getTablesList ( ) . join ( ) ; } catch ( Exception ex ) { issues . add ( context . createConfigIssue ( Groups . KUDU . name ( ) , KuduLookupConfig . CONF_PREFIX + KUDU_MASTER , Errors . KUDU_00 , ex . toString ( ) , ex ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert from Kudu type to SDC Field type [CODESPLIT] public static Field . Type convertFromKuduType ( Type kuduType ) { switch ( kuduType ) { case BINARY : return Field . Type . BYTE_ARRAY ; case BOOL : return Field . Type . BOOLEAN ; case DOUBLE : return Field . Type . DOUBLE ; case FLOAT : return Field . Type . FLOAT ; case INT8 : return Field . Type . BYTE ; case INT16 : return Field . Type . SHORT ; case INT32 : return Field . Type . INTEGER ; case INT64 : return Field . Type . LONG ; case STRING : return Field . Type . STRING ; case UNIXTIME_MICROS : return Field . Type . DATETIME ; default : if ( \"DECIMAL\" . equals ( kuduType . name ( ) ) ) { return Field . Type . DECIMAL ; } throw new UnsupportedOperationException ( \"Unknown data type: \" + kuduType . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a field and assign a value off of RowResult . [CODESPLIT] public static Field createField ( RowResult result , String fieldName , Type type ) throws StageException { switch ( type ) { case INT8 : return Field . create ( Field . Type . BYTE , result . getByte ( fieldName ) ) ; case INT16 : return Field . create ( Field . Type . SHORT , result . getShort ( fieldName ) ) ; case INT32 : return Field . create ( Field . Type . INTEGER , result . getInt ( fieldName ) ) ; case INT64 : return Field . create ( Field . Type . LONG , result . getLong ( fieldName ) ) ; case BINARY : try { return Field . create ( Field . Type . BYTE_ARRAY , result . getBinary ( fieldName ) ) ; } catch ( IllegalArgumentException ex ) { throw new OnRecordErrorException ( Errors . KUDU_35 , fieldName ) ; } case STRING : return Field . create ( Field . Type . STRING , result . getString ( fieldName ) ) ; case BOOL : return Field . create ( Field . Type . BOOLEAN , result . getBoolean ( fieldName ) ) ; case FLOAT : return Field . create ( Field . Type . FLOAT , result . getFloat ( fieldName ) ) ; case DOUBLE : return Field . create ( Field . Type . DOUBLE , result . getDouble ( fieldName ) ) ; case UNIXTIME_MICROS : //UNIXTIME_MICROS is in microsecond return Field . create ( Field . Type . DATETIME , new Date ( result . getLong ( fieldName ) / 1000L ) ) ; default : if ( \"DECIMAL\" . equals ( type . name ( ) ) ) { return Field . create ( Field . Type . DECIMAL , result . getDecimal ( fieldName ) ) ; } throw new StageException ( Errors . KUDU_10 , fieldName , type . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Intercept given records with all the interceptors . [CODESPLIT] private List < Record > intercept ( List < Record > records , List < ? extends Interceptor > interceptors ) throws StageException { for ( Interceptor interceptor : interceptors ) { records = interceptor . intercept ( records ) ; } return records ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the text of the line . [CODESPLIT] public String getText ( ) { if ( line == null ) { line = new String ( buffer , offsetInChunk , length , charset ) ; } return line ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configuration [CODESPLIT] private boolean isConfigurationActive ( ConfigDef configDef , Map < String , Object > configuration ) { String dependsOn = configDef . dependsOn ( ) ; if ( ! dependsOn . isEmpty ( ) ) { Object dependsOnValue = configuration . get ( dependsOn ) ; if ( dependsOnValue != null ) { String valueStr = dependsOnValue . toString ( ) ; for ( String trigger : configDef . triggeredByValue ( ) ) { if ( valueStr . equals ( trigger ) ) { return true ; } } return false ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve stage aliases ( e . g . when a stage is renamed ) . [CODESPLIT] public static void resolveStageAlias ( StageLibraryTask stageLibrary , StageConfiguration stageConf ) { String aliasKey = Joiner . on ( \",\" ) . join ( stageConf . getLibrary ( ) , stageConf . getStageName ( ) ) ; String aliasValue = Strings . nullToEmpty ( stageLibrary . getStageNameAliases ( ) . get ( aliasKey ) ) ; if ( LOG . isTraceEnabled ( ) ) { for ( String key : stageLibrary . getStageNameAliases ( ) . keySet ( ) ) { LOG . trace ( \"Stage Lib Alias: {} => {}\" , key , stageLibrary . getStageNameAliases ( ) . get ( key ) ) ; } LOG . trace ( \"Looking for '{}' and found '{}'\" , aliasKey , aliasValue ) ; } if ( ! aliasValue . isEmpty ( ) ) { List < String > alias = Splitter . on ( \",\" ) . splitToList ( aliasValue ) ; if ( alias . size ( ) == 2 ) { LOG . debug ( \"Converting '{}' to '{}'\" , aliasKey , aliasValue ) ; stageConf . setLibrary ( alias . get ( 0 ) ) ; stageConf . setStageName ( alias . get ( 1 ) ) ; } else { LOG . error ( \"Malformed stage alias: '{}'\" , aliasValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve all stage library relevant aliases - this includes : [CODESPLIT] public static boolean resolveLibraryAliases ( StageLibraryTask stageLibrary , List < StageConfiguration > stageConfigurations ) { for ( StageConfiguration stageConf : stageConfigurations ) { String name = stageConf . getLibrary ( ) ; if ( stageLibrary . getLibraryNameAliases ( ) . containsKey ( name ) ) { stageConf . setLibrary ( stageLibrary . getLibraryNameAliases ( ) . get ( name ) ) ; } resolveStageAlias ( stageLibrary , stageConf ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add any missing configs to the stage configuration . [CODESPLIT] public static void addMissingConfigsToStage ( StageLibraryTask stageLibrary , StageConfiguration stageConf ) { StageDefinition stageDef = stageLibrary . getStage ( stageConf . getLibrary ( ) , stageConf . getStageName ( ) , false ) ; if ( stageDef != null ) { for ( ConfigDefinition configDef : stageDef . getConfigDefinitions ( ) ) { String configName = configDef . getName ( ) ; Config config = stageConf . getConfig ( configName ) ; if ( config == null ) { Object defaultValue = configDef . getDefaultValue ( ) ; LOG . warn ( \"Stage '{}' missing configuration '{}', adding with '{}' as default\" , stageConf . getInstanceName ( ) , configName , defaultValue ) ; config = new Config ( configName , defaultValue ) ; stageConf . addConfig ( config ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate given stage configuration . [CODESPLIT] public static boolean validateStageConfiguration ( StageLibraryTask stageLibrary , boolean shouldBeSource , StageConfiguration stageConf , boolean notOnMainCanvas , IssueCreator issueCreator , boolean isPipelineFragment , Map < String , Object > constants , List < Issue > issues ) { boolean preview = true ; StageDefinition stageDef = stageLibrary . getStage ( stageConf . getLibrary ( ) , stageConf . getStageName ( ) , false ) ; if ( stageDef == null ) { // stage configuration refers to an undefined stage definition issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0006 , stageConf . getLibrary ( ) , stageConf . getStageName ( ) , stageConf . getStageVersion ( ) ) ) ; preview = false ; } else { if ( shouldBeSource ) { if ( stageDef . getType ( ) != StageType . SOURCE && ! isPipelineFragment ) { // first stage must be a Source issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0003 ) ) ; preview = false ; } } else { if ( ! stageLibrary . isMultipleOriginSupported ( ) && stageDef . getType ( ) == StageType . SOURCE ) { // no stage other than first stage can be a Source issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0004 ) ) ; preview = false ; } } if ( ! stageConf . isSystemGenerated ( ) && ! TextUtils . isValidName ( stageConf . getInstanceName ( ) ) ) { // stage instance name has an invalid name (it must match '[0-9A-Za-z_]+') issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0016 , stageConf . getInstanceName ( ) , TextUtils . VALID_NAME ) ) ; preview = false ; } // Hidden stages can't appear on the main canvas if ( ! notOnMainCanvas && ! stageDef . getHideStage ( ) . isEmpty ( ) ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0037 ) ) ; preview = false ; } for ( String lane : stageConf . getInputLanes ( ) ) { if ( ! TextUtils . isValidName ( lane ) ) { // stage instance input lane has an invalid name (it must match '[0-9A-Za-z_]+') issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0017 , lane , TextUtils . VALID_NAME ) ) ; preview = false ; } } for ( String lane : stageConf . getOutputLanes ( ) ) { if ( ! TextUtils . isValidName ( lane ) ) { // stage instance output lane has an invalid name (it must match '[0-9A-Za-z_]+') issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0018 , lane , TextUtils . VALID_NAME ) ) ; preview = false ; } } for ( String lane : stageConf . getEventLanes ( ) ) { if ( ! TextUtils . isValidName ( lane ) ) { // stage instance output lane has an invalid name (it must match '[0-9A-Za-z_]+') issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0100 , lane , TextUtils . VALID_NAME ) ) ; preview = false ; } } // Special validation for stage exposed limit of input lanes // -1: Means that framework is fully in control on how many input lanes should be present //  0: Means that the stage supports unlimited number of input lanes // >0: Means that stage needs exactly that amount of lanes which we will validate here if ( stageDef . getInputStreams ( ) > 0 ) { if ( stageDef . getInputStreams ( ) != stageConf . getInputLanes ( ) . size ( ) ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0094 , stageDef . getInputStreams ( ) , stageConf . getInputLanes ( ) . size ( ) ) ) ; } } // Validate proper input/output lane configuration switch ( stageDef . getType ( ) ) { case SOURCE : if ( ! stageConf . getInputLanes ( ) . isEmpty ( ) ) { // source stage cannot have input lanes issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0012 , stageDef . getType ( ) , stageConf . getInputLanes ( ) ) ) ; preview = false ; } if ( ! notOnMainCanvas && ! stageDef . isVariableOutputStreams ( ) ) { // source stage must match the output stream defined in StageDef if ( stageDef . getOutputStreams ( ) != stageConf . getOutputLanes ( ) . size ( ) ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0015 , stageDef . getOutputStreams ( ) , stageConf . getOutputLanes ( ) . size ( ) ) ) ; } } else if ( ! notOnMainCanvas && stageConf . getOutputLanes ( ) . isEmpty ( ) ) { // source stage must have at least one output lane issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0032 ) ) ; } break ; case PROCESSOR : if ( ! notOnMainCanvas && stageConf . getInputLanes ( ) . isEmpty ( ) && ! isPipelineFragment ) { // processor stage must have at least one input lane issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0014 , \"Processor\" ) ) ; preview = false ; } if ( ! notOnMainCanvas ) { if ( ! stageDef . isVariableOutputStreams ( ) ) { // processor stage must match the output stream defined in StageDef if ( stageDef . getOutputStreams ( ) != stageConf . getOutputLanes ( ) . size ( ) ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0015 , stageDef . getOutputStreams ( ) , stageConf . getOutputLanes ( ) . size ( ) ) ) ; } } else if ( stageConf . getOutputLanes ( ) . isEmpty ( ) ) { // processor stage must have at least one output lane issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0032 ) ) ; } } break ; case EXECUTOR : case TARGET : // Normal target stage must have at least one input lane if ( ! notOnMainCanvas && stageConf . getInputLanes ( ) . isEmpty ( ) && ! isPipelineFragment ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0014 , \"Target\" ) ) ; preview = false ; } // Error/Stats/Pipeline lifecycle must not have an input lane if ( notOnMainCanvas && ! stageConf . getInputLanes ( ) . isEmpty ( ) ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0012 , \"Error/Stats/Lifecycle\" , stageConf . getInputLanes ( ) ) ) ; preview = false ; } if ( ! stageConf . getOutputLanes ( ) . isEmpty ( ) ) { // target stage cannot have output lanes issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0013 , stageDef . getType ( ) , stageConf . getOutputLanes ( ) ) ) ; preview = false ; } if ( notOnMainCanvas && ! stageConf . getEventLanes ( ) . isEmpty ( ) ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0036 , stageDef . getType ( ) , stageConf . getEventLanes ( ) ) ) ; preview = false ; } break ; default : throw new IllegalStateException ( \"Unexpected stage type \" + stageDef . getType ( ) ) ; } // Validate proper event configuration if ( ! notOnMainCanvas && stageConf . getEventLanes ( ) . size ( ) > 1 ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0101 ) ) ; preview = false ; } if ( ! notOnMainCanvas && ! stageDef . isProducingEvents ( ) && stageConf . getEventLanes ( ) . size ( ) > 0 ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0102 ) ) ; preview = false ; } // Validate stage owns configuration preview &= validateComponentConfigs ( stageConf , stageDef . getConfigDefinitions ( ) , stageDef . getConfigDefinitionsMap ( ) , stageDef . getHideConfigs ( ) , stageDef . hasPreconditions ( ) , constants , issueCreator , issues ) ; // Validate service definitions Set < String > expectedServices = stageDef . getServices ( ) . stream ( ) . map ( service -> service . getService ( ) . getName ( ) ) . collect ( Collectors . toSet ( ) ) ; Set < String > configuredServices = stageConf . getServices ( ) . stream ( ) . map ( service -> service . getService ( ) . getName ( ) ) . collect ( Collectors . toSet ( ) ) ; if ( ! expectedServices . equals ( configuredServices ) ) { issues . add ( issueCreator . create ( stageConf . getInstanceName ( ) , ValidationError . VALIDATION_0200 , StringUtils . join ( expectedServices , \",\" ) , StringUtils . join ( configuredServices , \",\" ) ) ) ; preview = false ; } else { // Validate all services for ( ServiceConfiguration serviceConf : stageConf . getServices ( ) ) { ServiceDefinition serviceDef = stageLibrary . getServiceDefinition ( serviceConf . getService ( ) , false ) ; preview &= validateComponentConfigs ( serviceConf , serviceDef . getConfigDefinitions ( ) , serviceDef . getConfigDefinitionsMap ( ) , Collections . emptySet ( ) , false , constants , issueCreator . forService ( serviceConf . getService ( ) . getName ( ) ) , issues ) ; } } } return preview ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { List < ConfigIssue > issues = super . init ( ) ; errorRecordHandler = new DefaultErrorRecordHandler ( getContext ( ) ) ; // NOSONAR double rateLimit = conf . rateLimit > 0 ? ( 1000.0 / conf . rateLimit ) : Double . MAX_VALUE ; rateLimiter = RateLimiter . create ( rateLimit ) ; httpClientCommon . init ( issues , getContext ( ) ) ; conf . dataFormatConfig . init ( getContext ( ) , conf . dataFormat , Groups . HTTP . name ( ) , HttpClientCommon . DATA_FORMAT_CONFIG_PREFIX , issues ) ; bodyVars = getContext ( ) . createELVars ( ) ; bodyEval = getContext ( ) . createELEval ( REQUEST_BODY_CONFIG_NAME ) ; if ( issues . isEmpty ( ) ) { parserFactory = conf . dataFormatConfig . getParserFactory ( ) ; } return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( Batch batch , SingleLaneBatchMaker batchMaker ) throws StageException { List < Future < Response >> responses = new ArrayList <> ( ) ; resolvedRecords . clear ( ) ; Iterator < Record > records = batch . getRecords ( ) ; while ( records . hasNext ( ) ) { Record record = records . next ( ) ; String resolvedUrl = httpClientCommon . getResolvedUrl ( conf . resourceUrl , record ) ; WebTarget target = httpClientCommon . getClient ( ) . target ( resolvedUrl ) ; LOG . debug ( \"Resolved HTTP Client URL: '{}'\" , resolvedUrl ) ; // If the request (headers or body) contain a known sensitive EL and we're not using https then fail the request. if ( httpClientCommon . requestContainsSensitiveInfo ( conf . headers , conf . requestBody ) && ! target . getUri ( ) . getScheme ( ) . toLowerCase ( ) . startsWith ( \"https\" ) ) { throw new StageException ( Errors . HTTP_07 ) ; } // from HttpStreamConsumer final MultivaluedMap < String , Object > resolvedHeaders = httpClientCommon . resolveHeaders ( conf . headers , record ) ; String contentType = HttpStageUtil . getContentTypeWithDefault ( resolvedHeaders , conf . defaultRequestContentType ) ; final AsyncInvoker asyncInvoker = target . request ( ) . property ( OAuth1ClientSupport . OAUTH_PROPERTY_ACCESS_TOKEN , httpClientCommon . getAuthToken ( ) ) . headers ( resolvedHeaders ) . async ( ) ; HttpMethod method = httpClientCommon . getHttpMethod ( conf . httpMethod , conf . methodExpression , record ) ; rateLimiter . acquire ( ) ; if ( conf . requestBody != null && ! conf . requestBody . isEmpty ( ) && method != HttpMethod . GET ) { RecordEL . setRecordInContext ( bodyVars , record ) ; final String requestBody = bodyEval . eval ( bodyVars , conf . requestBody , String . class ) ; resolvedRecords . put ( record , new HeadersAndBody ( resolvedHeaders , requestBody , contentType , method , target ) ) ; responses . add ( asyncInvoker . method ( method . getLabel ( ) , Entity . entity ( requestBody , contentType ) ) ) ; } else { resolvedRecords . put ( record , new HeadersAndBody ( resolvedHeaders , null , null , method , target ) ) ; responses . add ( asyncInvoker . method ( method . getLabel ( ) ) ) ; } } records = batch . getRecords ( ) ; int recordNum = 0 ; while ( records . hasNext ( ) ) { try { Record record = processResponse ( records . next ( ) , responses . get ( recordNum ) , conf . maxRequestCompletionSecs , false ) ; if ( record != null ) { batchMaker . addRecord ( record ) ; } } catch ( OnRecordErrorException e ) { errorRecordHandler . onError ( e ) ; } finally { ++ recordNum ; } } if ( ! resolvedRecords . isEmpty ( ) ) { reprocessIfRequired ( batchMaker ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for the Jersey client to complete an asynchronous request checks the response code and continues to parse the response if it is deemed ok . [CODESPLIT] private Record processResponse ( Record record , Future < Response > responseFuture , long maxRequestCompletionSecs , boolean failOn403 ) throws StageException { Response response = null ; try { response = responseFuture . get ( maxRequestCompletionSecs , TimeUnit . SECONDS ) ; InputStream responseBody = null ; if ( response . hasEntity ( ) ) { responseBody = response . readEntity ( InputStream . class ) ; } int responseStatus = response . getStatus ( ) ; if ( conf . client . useOAuth2 && response . getStatus ( ) == 403 && ! failOn403 ) { HttpStageUtil . getNewOAuth2Token ( conf . client . oauth2 , httpClientCommon . getClient ( ) ) ; return null ; } else if ( responseStatus < 200 || responseStatus >= 300 ) { resolvedRecords . remove ( record ) ; throw new OnRecordErrorException ( record , Errors . HTTP_01 , response . getStatus ( ) , response . getStatusInfo ( ) . getReasonPhrase ( ) + \" \" + responseBody ) ; } resolvedRecords . remove ( record ) ; Record parsedResponse = parseResponse ( responseBody ) ; if ( parsedResponse != null ) { record . set ( conf . outputField , parsedResponse . get ( ) ) ; addResponseHeaders ( record , response ) ; } else if ( responseBody == null && responseStatus != 204 ) { throw new OnRecordErrorException ( record , Errors . HTTP_34 ) ; } return record ; } catch ( InterruptedException | ExecutionException e ) { LOG . error ( Errors . HTTP_03 . getMessage ( ) , e . toString ( ) , e ) ; throw new OnRecordErrorException ( record , Errors . HTTP_03 , e . toString ( ) ) ; } catch ( TimeoutException e ) { LOG . error ( \"HTTP request future timed out\" , e . toString ( ) , e ) ; throw new OnRecordErrorException ( record , Errors . HTTP_03 , e . toString ( ) ) ; } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the HTTP response text from a request into SDC Records [CODESPLIT] private Record parseResponse ( InputStream response ) throws StageException { Record record = null ; if ( conf . httpMethod == HttpMethod . HEAD ) { // Head will have no body so can't be parsed.   Return an empty record. record = getContext ( ) . createRecord ( \"\" ) ; record . set ( Field . create ( new HashMap ( ) ) ) ; } else if ( response != null ) { try ( DataParser parser = parserFactory . getParser ( \"\" , response , \"0\" ) ) { // A response may only contain a single record, so we only parse it once. record = parser . parse ( ) ; if ( conf . dataFormat == DataFormat . TEXT ) { // Output is placed in a field \"/text\" so we remove it here. record . set ( record . get ( \"/text\" ) ) ; } } catch ( IOException | DataParserException e ) { errorRecordHandler . onError ( Errors . HTTP_00 , e . toString ( ) , e ) ; } } return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates HTTP response headers to the configured location [CODESPLIT] private void addResponseHeaders ( Record record , Response response ) throws StageException { if ( conf . headerOutputLocation == HeaderOutputLocation . NONE ) { return ; } Record . Header header = record . getHeader ( ) ; if ( conf . headerOutputLocation == HeaderOutputLocation . FIELD ) { writeResponseHeaderToField ( record , response ) ; } else if ( conf . headerOutputLocation == HeaderOutputLocation . HEADER ) { writeResponseHeaderToRecordHeader ( response , header ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes HTTP response headers to the SDC Record at the configured field path . [CODESPLIT] private void writeResponseHeaderToField ( Record record , Response response ) throws StageException { if ( record . has ( conf . headerOutputField ) ) { throw new StageException ( Errors . HTTP_11 , conf . headerOutputField ) ; } Map < String , Field > headers = new HashMap <> ( response . getStringHeaders ( ) . size ( ) ) ; for ( Map . Entry < String , List < String > > entry : response . getStringHeaders ( ) . entrySet ( ) ) { if ( ! entry . getValue ( ) . isEmpty ( ) ) { String firstValue = entry . getValue ( ) . get ( 0 ) ; headers . put ( entry . getKey ( ) , Field . create ( firstValue ) ) ; } } record . set ( conf . headerOutputField , Field . create ( headers ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes HTTP response headers to the SDC Record header with the configured optional prefix . [CODESPLIT] private void writeResponseHeaderToRecordHeader ( Response response , Record . Header header ) { for ( Map . Entry < String , List < String > > entry : response . getStringHeaders ( ) . entrySet ( ) ) { if ( ! entry . getValue ( ) . isEmpty ( ) ) { String firstValue = entry . getValue ( ) . get ( 0 ) ; header . setAttribute ( conf . headerAttributePrefix + entry . getKey ( ) , firstValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commit metadata content to a file to disk . [CODESPLIT] synchronized private void saveMetadata ( ) throws StageException { // 0) Validate pre-conditions if ( Files . exists ( newMetadataFile ) ) { throw new StageException ( BlobStoreError . BLOB_STORE_0010 ) ; } // 1) New content is written into a new temporary file. try ( OutputStream os = Files . newOutputStream ( newMetadataFile , StandardOpenOption . CREATE , StandardOpenOption . TRUNCATE_EXISTING ) ) { jsonMapper . writeValue ( os , metadata ) ; } catch ( IOException e ) { throw new StageException ( BlobStoreError . BLOB_STORE_0001 , e . toString ( ) , e ) ; } // 2) Old metadata is dropped try { if ( Files . exists ( metadataFile ) ) { Files . delete ( metadataFile ) ; } } catch ( IOException e ) { throw new StageException ( BlobStoreError . BLOB_STORE_0011 , e . toString ( ) , e ) ; } // 3) Rename from new to old is done try { Files . move ( newMetadataFile , metadataFile ) ; } catch ( IOException e ) { throw new StageException ( BlobStoreError . BLOB_STORE_0012 , e . toString ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { List < ConfigIssue > issues = super . init ( ) ; errorRecordHandler = new DefaultErrorRecordHandler ( getContext ( ) ) ; // NOSONAR conf . basic . init ( getContext ( ) , Groups . HTTP . name ( ) , BASIC_CONFIG_PREFIX , issues ) ; conf . dataFormatConfig . init ( getContext ( ) , conf . dataFormat , Groups . HTTP . name ( ) , DATA_FORMAT_CONFIG_PREFIX , issues ) ; conf . init ( getContext ( ) , Groups . HTTP . name ( ) , \"conf.\" , issues ) ; if ( conf . client . tlsConfig . isEnabled ( ) ) { conf . client . tlsConfig . init ( getContext ( ) , Groups . TLS . name ( ) , TLS_CONFIG_PREFIX , issues ) ; } resourceVars = getContext ( ) . createELVars ( ) ; resourceEval = getContext ( ) . createELEval ( RESOURCE_CONFIG_NAME ) ; bodyVars = getContext ( ) . createELVars ( ) ; bodyEval = getContext ( ) . createELEval ( REQUEST_BODY_CONFIG_NAME ) ; Calendar calendar = Calendar . getInstance ( TimeZone . getTimeZone ( ZoneId . of ( conf . timeZoneID ) ) ) ; TimeEL . setCalendarInContext ( bodyVars , calendar ) ; headerVars = getContext ( ) . createELVars ( ) ; headerEval = getContext ( ) . createELEval ( HEADER_CONFIG_NAME ) ; stopVars = getContext ( ) . createELVars ( ) ; stopEval = getContext ( ) . createELEval ( STOP_CONFIG_NAME ) ; next = null ; haveMorePages = false ; if ( conf . responseStatusActionConfigs != null ) { final String cfgName = \"conf.responseStatusActionConfigs\" ; final EnumSet < ResponseAction > backoffRetries = EnumSet . of ( ResponseAction . RETRY_EXPONENTIAL_BACKOFF , ResponseAction . RETRY_LINEAR_BACKOFF ) ; for ( HttpResponseActionConfigBean actionConfig : conf . responseStatusActionConfigs ) { final HttpResponseActionConfigBean prevAction = statusToActionConfigs . put ( actionConfig . getStatusCode ( ) , actionConfig ) ; if ( prevAction != null ) { issues . add ( getContext ( ) . createConfigIssue ( Groups . HTTP . name ( ) , cfgName , Errors . HTTP_17 , actionConfig . getStatusCode ( ) ) ) ; } if ( backoffRetries . contains ( actionConfig . getAction ( ) ) && actionConfig . getBackoffInterval ( ) <= 0 ) { issues . add ( getContext ( ) . createConfigIssue ( Groups . HTTP . name ( ) , cfgName , Errors . HTTP_15 ) ) ; } if ( actionConfig . getStatusCode ( ) >= 200 && actionConfig . getStatusCode ( ) < 300 ) { issues . add ( getContext ( ) . createConfigIssue ( Groups . HTTP . name ( ) , cfgName , Errors . HTTP_16 ) ) ; } } } this . timeoutActionConfig = conf . responseTimeoutActionConfig ; // Validation succeeded so configure the client. if ( issues . isEmpty ( ) ) { try { configureClient ( issues ) ; } catch ( StageException e ) { // should not happen on initial connect ExceptionUtils . throwUndeclared ( e ) ; } } return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to apply Jersey client configuration properties . [CODESPLIT] private void configureClient ( List < ConfigIssue > issues ) throws StageException { clientCommon . init ( issues , getContext ( ) ) ; if ( issues . isEmpty ( ) ) { client = clientCommon . getClient ( ) ; parserFactory = conf . dataFormatConfig . getParserFactory ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String produce ( String lastSourceOffset , int maxBatchSize , BatchMaker batchMaker ) throws StageException { long start = System . currentTimeMillis ( ) ; int chunksToFetch = Math . min ( conf . basic . maxBatchSize , maxBatchSize ) ; Optional < String > newSourceOffset = Optional . empty ( ) ; recordCount = 0 ; setPageOffset ( lastSourceOffset ) ; setResolvedUrl ( resolveInitialUrl ( lastSourceOffset ) ) ; WebTarget target = client . target ( getResolvedUrl ( ) ) ; // If the request (headers or body) contain a known sensitive EL and we're not using https then fail the request. if ( requestContainsSensitiveInfo ( ) && ! target . getUri ( ) . getScheme ( ) . toLowerCase ( ) . startsWith ( \"https\" ) ) { LOG . error ( Errors . HTTP_07 . getMessage ( ) ) ; throw new StageException ( Errors . HTTP_07 ) ; } boolean uninterrupted = true ; while ( ! waitTimeExpired ( start ) && uninterrupted && ( recordCount < chunksToFetch ) ) { if ( parser != null ) { // We already have an response that we haven't finished reading. newSourceOffset = Optional . of ( parseResponse ( start , chunksToFetch , batchMaker ) ) ; } else if ( shouldMakeRequest ( ) ) { if ( conf . pagination . mode != PaginationMode . NONE ) { target = client . target ( resolveNextPageUrl ( newSourceOffset . orElse ( null ) ) ) ; // Pause between paging requests so we don't get rate limited. uninterrupted = ThreadUtil . sleep ( conf . pagination . rateLimit ) ; } makeRequest ( target ) ; if ( lastRequestTimedOut ) { String actionName = conf . responseTimeoutActionConfig . getAction ( ) . name ( ) ; LOG . warn ( \"HTTPClient timed out after waiting {} ms for response from server;\" + \" reconnecting client and proceeding as per configured {} action\" , conf . client . readTimeoutMillis , actionName ) ; reconnectClient ( ) ; return nonTerminating ( lastSourceOffset ) ; } else { newSourceOffset = processResponse ( start , chunksToFetch , batchMaker ) ; } } else if ( conf . httpMode == HttpClientMode . BATCH ) { // We are done. return null ; } else { // In polling mode, waiting for the next polling interval. uninterrupted = ThreadUtil . sleep ( SLEEP_TIME_WAITING_FOR_BATCH_SIZE_MS ) ; } } return newSourceOffset . orElse ( lastSourceOffset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the URL of the next page to fetch when paging is enabled . Otherwise returns the previously configured URL . [CODESPLIT] @ VisibleForTesting String resolveNextPageUrl ( String sourceOffset ) throws ELEvalException { String url ; if ( LINK_PAGINATION . contains ( conf . pagination . mode ) && next != null ) { url = next . getUri ( ) . toString ( ) ; setResolvedUrl ( url ) ; } else if ( conf . pagination . mode == PaginationMode . BY_OFFSET || conf . pagination . mode == PaginationMode . BY_PAGE ) { if ( sourceOffset != null ) { setPageOffset ( sourceOffset ) ; } url = resourceEval . eval ( resourceVars , conf . resourceUrl , String . class ) ; } else { url = getResolvedUrl ( ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the startAt EL variable in scope for the resource and request body . If the source offset is null ( origin was reset ) then the initial value from the user provided configuration is used . [CODESPLIT] private void setPageOffset ( String sourceOffset ) { if ( conf . pagination . mode == PaginationMode . NONE ) { return ; } int startAt = conf . pagination . startAt ; if ( StringUtils . isNotEmpty ( sourceOffset ) ) { startAt = HttpSourceOffset . fromString ( sourceOffset ) . getStartAt ( ) ; } resourceVars . addVariable ( START_AT , startAt ) ; bodyVars . addVariable ( START_AT , startAt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to construct an HTTP request and fetch a response . [CODESPLIT] private void makeRequest ( WebTarget target ) throws StageException { hasher = HF . newHasher ( ) ; MultivaluedMap < String , Object > resolvedHeaders = resolveHeaders ( ) ; final Invocation . Builder invocationBuilder = target . request ( ) . property ( OAuth1ClientSupport . OAUTH_PROPERTY_ACCESS_TOKEN , authToken ) . headers ( resolvedHeaders ) ; boolean keepRequesting = ! getContext ( ) . isStopped ( ) ; boolean gotNewToken = false ; while ( keepRequesting ) { long startTime = System . currentTimeMillis ( ) ; try { if ( conf . requestBody != null && ! conf . requestBody . isEmpty ( ) && conf . httpMethod != HttpMethod . GET ) { final String requestBody = bodyEval . eval ( bodyVars , conf . requestBody , String . class ) ; final String contentType = HttpStageUtil . getContentTypeWithDefault ( resolvedHeaders , conf . defaultRequestContentType ) ; hasher . putString ( requestBody , Charset . forName ( conf . dataFormatConfig . charset ) ) ; setResponse ( invocationBuilder . method ( conf . httpMethod . getLabel ( ) , Entity . entity ( requestBody , contentType ) ) ) ; } else { setResponse ( invocationBuilder . method ( conf . httpMethod . getLabel ( ) ) ) ; } LOG . debug ( \"Retrieved response in {} ms\" , System . currentTimeMillis ( ) - startTime ) ; lastRequestTimedOut = false ; final int status = response . getStatus ( ) ; final boolean statusOk = status >= 200 && status < 300 ; if ( conf . client . useOAuth2 && status == 403 ) { // Token may have expired if ( gotNewToken ) { LOG . error ( HTTP_21 . getMessage ( ) ) ; throw new StageException ( HTTP_21 ) ; } gotNewToken = HttpStageUtil . getNewOAuth2Token ( conf . client . oauth2 , client ) ; } else if ( ! statusOk && this . statusToActionConfigs . containsKey ( status ) ) { final HttpResponseActionConfigBean actionConf = this . statusToActionConfigs . get ( status ) ; final boolean statusChanged = lastStatus != status || lastRequestTimedOut ; keepRequesting = applyResponseAction ( actionConf , statusChanged , input -> { final StageException stageException = new StageException ( Errors . HTTP_14 , status , response . readEntity ( String . class ) ) ; LOG . error ( stageException . getMessage ( ) ) ; return stageException ; } ) ; } else { keepRequesting = false ; retryCount = 0 ; } lastStatus = status ; } catch ( Exception e ) { LOG . debug ( \"Request failed after {} ms\" , System . currentTimeMillis ( ) - startTime ) ; final Throwable cause = e . getCause ( ) ; if ( cause != null && ( cause instanceof TimeoutException || cause instanceof SocketTimeoutException ) ) { LOG . warn ( \"{} attempting to read response in HttpClientSource: {}\" , cause . getClass ( ) . getSimpleName ( ) , e . getMessage ( ) , e ) ; // read timeout; consult configured action to decide on backoff and retry strategy if ( this . timeoutActionConfig != null ) { final HttpResponseActionConfigBean actionConf = this . timeoutActionConfig ; final boolean firstTimeout = ! lastRequestTimedOut ; applyResponseAction ( actionConf , firstTimeout , input -> { LOG . error ( Errors . HTTP_18 . getMessage ( ) ) ; return new StageException ( Errors . HTTP_18 ) ; } ) ; } lastRequestTimedOut = true ; keepRequesting = false ; } else if ( cause != null && cause instanceof InterruptedException ) { LOG . error ( String . format ( \"InterruptedException attempting to make request in HttpClientSource; stopping: %s\" , e . getMessage ( ) ) , e ) ; keepRequesting = false ; } else { LOG . error ( String . format ( \"ProcessingException attempting to make request in HttpClientSource: %s\" , e . getMessage ( ) ) , e ) ; Throwable reportEx = cause != null ? cause : e ; final StageException stageException = new StageException ( Errors . HTTP_32 , reportEx . toString ( ) , reportEx ) ; LOG . error ( stageException . getMessage ( ) ) ; throw stageException ; } } keepRequesting &= ! getContext ( ) . isStopped ( ) ; } // Calculate request parameter hash currentParameterHash = hasher . hash ( ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether or not we should continue making additional HTTP requests in the current produce () call or whether to return the current batch . [CODESPLIT] private boolean shouldMakeRequest ( ) { final long now = System . currentTimeMillis ( ) ; boolean shouldMakeRequest = lastRequestCompletedTime == - 1 ; shouldMakeRequest |= lastRequestTimedOut ; shouldMakeRequest |= next != null ; shouldMakeRequest |= ( haveMorePages && conf . pagination . mode != PaginationMode . LINK_HEADER ) ; shouldMakeRequest |= now > lastRequestCompletedTime + conf . pollingInterval && conf . httpMode == HttpClientMode . POLLING ; shouldMakeRequest |= now > lastRequestCompletedTime && conf . httpMode == HttpClientMode . STREAMING && conf . httpMethod != HttpMethod . HEAD ; return shouldMakeRequest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the response of a completed request into records and adds them to the batch . If more records are available in the response than we can add to the batch the response is not closed and parsing will continue on the next batch . [CODESPLIT] @ VisibleForTesting String parseResponse ( long start , int maxRecords , BatchMaker batchMaker ) throws StageException { HttpSourceOffset sourceOffset = new HttpSourceOffset ( getResolvedUrl ( ) , currentParameterHash , System . currentTimeMillis ( ) , getCurrentPage ( ) ) ; InputStream in = null ; if ( parser == null ) { // Only get a new parser if we are done with the old one. in = getResponse ( ) . readEntity ( InputStream . class ) ; try { parser = parserFactory . getParser ( sourceOffset . toString ( ) , in , \"0\" ) ; } catch ( DataParserException e ) { if ( e . getErrorCode ( ) == JSON_PARSER_00 ) { LOG . warn ( \"No data returned in HTTP response body.\" , e ) ; return sourceOffset . toString ( ) ; } LOG . warn ( \"Error parsing response\" , e ) ; throw e ; } } Record record = null ; int subRecordCount = 0 ; try { do { record = parser . parse ( ) ; if ( record == null ) { break ; } // LINK_FIELD pagination if ( conf . pagination . mode == PaginationMode . LINK_FIELD ) { // evaluate stopping condition RecordEL . setRecordInContext ( stopVars , record ) ; haveMorePages = ! stopEval . eval ( stopVars , conf . pagination . stopCondition , Boolean . class ) ; if ( haveMorePages ) { next = Link . fromUri ( record . get ( conf . pagination . nextPageFieldPath ) . getValueAsString ( ) ) . build ( ) ; } else { next = null ; } } if ( conf . pagination . mode != PaginationMode . NONE && record . has ( conf . pagination . resultFieldPath ) ) { subRecordCount = parsePaginatedResult ( batchMaker , sourceOffset . toString ( ) , record ) ; recordCount += subRecordCount ; } else { addResponseHeaders ( record . getHeader ( ) ) ; batchMaker . addRecord ( record ) ; ++ recordCount ; } } while ( recordCount < maxRecords && ! waitTimeExpired ( start ) ) ; } catch ( IOException e ) { LOG . error ( Errors . HTTP_00 . getMessage ( ) , e . toString ( ) , e ) ; errorRecordHandler . onError ( Errors . HTTP_00 , e . toString ( ) , e ) ; } finally { try { if ( record == null ) { cleanupResponse ( in ) ; } if ( subRecordCount != 0 ) { incrementSourceOffset ( sourceOffset , subRecordCount ) ; } } catch ( IOException e ) { LOG . warn ( Errors . HTTP_28 . getMessage ( ) , e . toString ( ) , e ) ; errorRecordHandler . onError ( Errors . HTTP_28 , e . toString ( ) , e ) ; } } return sourceOffset . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used only for HEAD requests . Sets up a record for output based on headers only with an empty body . [CODESPLIT] String parseHeadersOnly ( BatchMaker batchMaker ) throws StageException { HttpSourceOffset sourceOffset = new HttpSourceOffset ( getResolvedUrl ( ) , currentParameterHash , System . currentTimeMillis ( ) , getCurrentPage ( ) ) ; Record record = getContext ( ) . createRecord ( sourceOffset + \"::0\" ) ; addResponseHeaders ( record . getHeader ( ) ) ; record . set ( Field . create ( new HashMap ( ) ) ) ; batchMaker . addRecord ( record ) ; recordCount ++ ; incrementSourceOffset ( sourceOffset , 1 ) ; lastRequestCompletedTime = System . currentTimeMillis ( ) ; return sourceOffset . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increments the current source offset s startAt portion by the specified amount . This is the number of records parsed when paging BY_OFFSET or 1 if incrementing BY_PAGE . [CODESPLIT] private void incrementSourceOffset ( HttpSourceOffset sourceOffset , int increment ) { if ( conf . pagination . mode == PaginationMode . BY_PAGE ) { sourceOffset . incrementStartAt ( 1 ) ; } else if ( conf . pagination . mode == PaginationMode . BY_OFFSET ) { sourceOffset . incrementStartAt ( increment ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleanup the { [CODESPLIT] private void cleanupResponse ( InputStream in ) throws IOException { IOException ex = null ; LOG . debug ( \"Cleanup after request processing complete.\" ) ; lastRequestCompletedTime = System . currentTimeMillis ( ) ; if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { LOG . warn ( \"Error closing input stream\" , ex ) ; ex = e ; } } getResponse ( ) . close ( ) ; setResponse ( null ) ; try { parser . close ( ) ; } catch ( IOException e ) { LOG . warn ( \"Error closing parser\" , ex ) ; ex = e ; } parser = null ; if ( ex != null ) { throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the most recently requested page number or page offset requested . [CODESPLIT] @ VisibleForTesting int getCurrentPage ( ) { // Body params take precedence, but usually only one or the other should be used. if ( bodyVars . hasVariable ( START_AT ) ) { return ( int ) bodyVars . getVariable ( START_AT ) ; } else if ( resourceVars . hasVariable ( START_AT ) ) { return ( int ) resourceVars . getVariable ( START_AT ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a paginated result from the configured field . [CODESPLIT] private int parsePaginatedResult ( BatchMaker batchMaker , String sourceOffset , Record record ) throws StageException { int numSubRecords = 0 ; if ( ! record . has ( conf . pagination . resultFieldPath ) ) { final StageException stageException = new StageException ( Errors . HTTP_12 , conf . pagination . resultFieldPath ) ; LOG . error ( stageException . getMessage ( ) ) ; throw stageException ; } Field resultField = record . get ( conf . pagination . resultFieldPath ) ; if ( resultField . getType ( ) != Field . Type . LIST ) { final StageException stageException = new StageException ( Errors . HTTP_08 , resultField . getType ( ) ) ; LOG . error ( stageException . getMessage ( ) ) ; throw stageException ; } List < Field > results = resultField . getValueAsList ( ) ; int subRecordIdx = 0 ; for ( Field result : results ) { Record r = getContext ( ) . createRecord ( sourceOffset + \"::\" + subRecordIdx ++ ) ; if ( conf . pagination . keepAllFields ) { r . set ( record . get ( ) . clone ( ) ) ; r . set ( conf . pagination . resultFieldPath , result ) ; } else { r . set ( result ) ; } addResponseHeaders ( r . getHeader ( ) ) ; batchMaker . addRecord ( r ) ; ++ numSubRecords ; } if ( conf . pagination . mode != PaginationMode . LINK_FIELD ) { haveMorePages = numSubRecords > 0 ; } return numSubRecords ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the HTTP response headers to the record header . [CODESPLIT] private void addResponseHeaders ( Record . Header header ) { final MultivaluedMap < String , String > headers = getResponse ( ) . getStringHeaders ( ) ; if ( headers == null ) { return ; } for ( Map . Entry < String , List < String > > entry : headers . entrySet ( ) ) { if ( ! entry . getValue ( ) . isEmpty ( ) ) { String firstValue = entry . getValue ( ) . get ( 0 ) ; header . setAttribute ( entry . getKey ( ) , firstValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves any expressions in the Header value entries of the request . [CODESPLIT] private MultivaluedMap < String , Object > resolveHeaders ( ) throws StageException { MultivaluedMap < String , Object > requestHeaders = new MultivaluedHashMap <> ( ) ; for ( Map . Entry < String , String > entry : conf . headers . entrySet ( ) ) { List < Object > header = new ArrayList <> ( 1 ) ; Object resolvedValue = headerEval . eval ( headerVars , entry . getValue ( ) , String . class ) ; header . add ( resolvedValue ) ; requestHeaders . put ( entry . getKey ( ) , header ) ; hasher . putString ( entry . getKey ( ) , Charset . forName ( conf . dataFormatConfig . charset ) ) ; hasher . putString ( entry . getValue ( ) , Charset . forName ( conf . dataFormatConfig . charset ) ) ; } return requestHeaders ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies that the response was a successful one and has data and continues to parse the response . [CODESPLIT] private Optional < String > processResponse ( long start , int maxRecords , BatchMaker batchMaker ) throws StageException { Optional < String > newSourceOffset = Optional . empty ( ) ; if ( getResponse ( ) == null ) { return newSourceOffset ; } // Response was not in the OK range, so treat as an error int status = getResponse ( ) . getStatus ( ) ; if ( status < 200 || status >= 300 ) { lastRequestCompletedTime = System . currentTimeMillis ( ) ; String reason = getResponse ( ) . getStatusInfo ( ) . getReasonPhrase ( ) ; String respString = getResponse ( ) . readEntity ( String . class ) ; getResponse ( ) . close ( ) ; setResponse ( null ) ; final String errorMsg = reason + \" : \" + respString ; LOG . warn ( Errors . HTTP_01 . getMessage ( ) , status , errorMsg ) ; errorRecordHandler . onError ( Errors . HTTP_01 , status , errorMsg ) ; return newSourceOffset ; } if ( conf . pagination . mode == PaginationMode . LINK_HEADER ) { next = getResponse ( ) . getLink ( \"next\" ) ; if ( next == null ) { haveMorePages = false ; } } if ( getResponse ( ) . hasEntity ( ) ) { newSourceOffset = Optional . of ( parseResponse ( start , maxRecords , batchMaker ) ) ; } else if ( conf . httpMethod . getLabel ( ) == \"HEAD\" ) { // Handle HEAD only requests, which have no body, by creating a blank record for output with headers. newSourceOffset = Optional . of ( parseHeadersOnly ( batchMaker ) ) ; } return newSourceOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if and only if given property is defined with non empty non default value [CODESPLIT] protected boolean propertyDefined ( Configuration conf , String propertyName ) { String prop = conf . get ( propertyName ) ; // String property will have default empty, integer -1, we'll skip both of them return prop != null && ! prop . isEmpty ( ) && ! prop . equals ( \"-1\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change package name for DataParserException . [CODESPLIT] public static DataParserException convert ( com . streamsets . pipeline . lib . parser . DataParserException original ) { if ( original instanceof com . streamsets . pipeline . lib . parser . RecoverableDataParserException ) { return new RecoverableDataParserException ( ( ( com . streamsets . pipeline . lib . parser . RecoverableDataParserException ) original ) . getUnparsedRecord ( ) , original . getErrorCode ( ) , original . getParams ( ) ) ; } return new DataParserException ( original . getErrorCode ( ) , original . getParams ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change package name for DataGeneratorException . [CODESPLIT] public static DataGeneratorException convert ( com . streamsets . pipeline . lib . generator . DataGeneratorException original ) { return new DataGeneratorException ( original . getErrorCode ( ) , original . getParams ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to create a { @link CredentialsProvider } for the appropriate type of credentials supplied . [CODESPLIT] public Optional < CredentialsProvider > getCredentialsProvider ( Stage . Context context , List < Stage . ConfigIssue > issues ) { CredentialsProvider provider = null ; if ( credentialsProvider . equals ( CredentialsProviderType . DEFAULT_PROVIDER ) ) { return Optional . of ( SubscriptionAdminSettings . defaultCredentialsProviderBuilder ( ) . build ( ) ) ; } else if ( credentialsProvider . equals ( CredentialsProviderType . JSON_PROVIDER ) ) { Credentials credentials = getCredentials ( context , issues ) ; provider = new FixedCredentialsProvider ( ) { @ Nullable @ Override public Credentials getCredentials ( ) { return credentials ; } } ; } return Optional . ofNullable ( provider ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JSON credentials file for a service account from and returns any errors . [CODESPLIT] private Credentials getCredentials ( Stage . Context context , List < Stage . ConfigIssue > issues ) { Credentials credentials = null ; File credentialsFile ; if ( Paths . get ( path ) . isAbsolute ( ) ) { credentialsFile = new File ( path ) ; } else { credentialsFile = new File ( context . getResourcesDirectory ( ) , path ) ; } if ( ! credentialsFile . exists ( ) || ! credentialsFile . isFile ( ) ) { LOG . error ( GOOGLE_01 . getMessage ( ) , credentialsFile . getPath ( ) ) ; issues . add ( context . createConfigIssue ( Groups . CREDENTIALS . name ( ) , CONF_CREDENTIALS_CREDENTIALS_PROVIDER , GOOGLE_01 , credentialsFile . getPath ( ) ) ) ; return null ; } try ( InputStream in = new FileInputStream ( credentialsFile ) ) { credentials = ServiceAccountCredentials . fromStream ( in ) ; } catch ( IOException | IllegalArgumentException e ) { LOG . error ( GOOGLE_02 . getMessage ( ) , e ) ; issues . add ( context . createConfigIssue ( Groups . CREDENTIALS . name ( ) , CONF_CREDENTIALS_CREDENTIALS_PROVIDER , GOOGLE_02 ) ) ; } return credentials ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run Pipeline preview [CODESPLIT] public PreviewInfoJson previewWithOverride ( String pipelineId , List < StageOutputJson > stageOutputsToOverrideJson , String rev , Integer batchSize , Integer batches , Boolean skipTargets , String endStage , Long timeout ) throws ApiException { Object postBody = stageOutputsToOverrideJson ; byte [ ] postBinaryBody = null ; // verify the required parameter 'pipelineId' is set if ( pipelineId == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'pipelineId' when calling previewWithOverride\" ) ; } // verify the required parameter 'stageOutputsToOverrideJson' is set if ( stageOutputsToOverrideJson == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'stageOutputsToOverrideJson' when calling previewWithOverride\" ) ; } // create path and map variables String path = \"/v1/pipeline/{pipelineId}/preview\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) . replaceAll ( \"\\\\{\" + \"pipelineId\" + \"\\\\}\" , apiClient . escapeString ( pipelineId . toString ( ) ) ) ; // query params List < Pair > queryParams = new ArrayList < Pair > ( ) ; Map < String , String > headerParams = new HashMap < String , String > ( ) ; Map < String , Object > formParams = new HashMap < String , Object > ( ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"rev\" , rev ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"batchSize\" , batchSize ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"batches\" , batches ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"skipTargets\" , skipTargets ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"endStage\" , endStage ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"timeout\" , timeout ) ) ; final String [ ] accepts = { \"application/json\" } ; final String accept = apiClient . selectHeaderAccept ( accepts ) ; final String [ ] contentTypes = { } ; final String contentType = apiClient . selectHeaderContentType ( contentTypes ) ; String [ ] authNames = new String [ ] { \"basic\" } ; TypeRef returnType = new TypeRef < PreviewInfoJson > ( ) { } ; return apiClient . invokeAPI ( path , \"POST\" , queryParams , postBody , postBinaryBody , headerParams , formParams , accept , contentType , authNames , returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we use this to trim the output in case of overruns [CODESPLIT] protected int copyToBuffer ( StringBuilder s , int initialLen , int startChar , int currentChar ) { int overrun = 0 ; int currentSize = s . length ( ) - initialLen ; int readSize = currentChar - startChar ; if ( maxLine > - 1 && currentSize + readSize > maxLine ) { int adjustedReadSize = maxLine - currentSize ; if ( adjustedReadSize > 0 ) { s . append ( cb , startChar , adjustedReadSize ) ; overrun = readSize - adjustedReadSize ; } else { overrun = readSize ; } } else { s . append ( cb , startChar , readSize ) ; } return overrun ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds package names associated with a class loader which which are not JVM level packages . Anything inside java home are specifically excluded as well as some OS specific install locations ( MacOS ) . [CODESPLIT] private static SortedSet < String > findApplicationPackageNames ( ClassLoader cl ) { SortedSet < String > packages = new TreeSet <> ( ) ; while ( cl != null ) { if ( cl instanceof URLClassLoader ) { for ( URL url : ( ( URLClassLoader ) cl ) . getURLs ( ) ) { String path = url . getPath ( ) ; if ( ! path . startsWith ( JAVA_HOME ) && ! path . startsWith ( MACOS_JAVA_EXTENSIONS_DIR ) && path . endsWith ( JAR_FILE_SUFFIX ) ) { try { try ( ZipInputStream zip = new ZipInputStream ( url . openStream ( ) ) ) { for ( ZipEntry entry = zip . getNextEntry ( ) ; entry != null ; entry = zip . getNextEntry ( ) ) { if ( ! entry . isDirectory ( ) && entry . getName ( ) . endsWith ( CLASS_FILE_SUFFIX ) ) { // This ZipEntry represents a class. Now, what class does it represent? String className = entry . getName ( ) . replace ( ' ' , ' ' ) ; // including \".class\" className = className . substring ( 0 , className . length ( ) - CLASS_FILE_SUFFIX . length ( ) ) ; if ( className . contains ( \".\" ) && ! className . startsWith ( STREAMSETS_PACKAGE ) ) { // must end with a . as we don't want o.a.h matching o.a.ha packages . add ( className . substring ( 0 , className . lastIndexOf ( ' ' ) ) + \".\" ) ; } } } } } catch ( IOException unlikely ) { // since these are local URL we will likely only // hit this if there is a corrupt jar in the classpath // which we will ignore if ( SDCClassLoader . isDebug ( ) ) { System . err . println ( \"Error opening '\" + url + \"' : \" + unlikely ) ; unlikely . printStackTrace ( ) ; } } } } } cl = cl . getParent ( ) ; } SystemPackage systemPackage = new SystemPackage ( SDCClassLoader . SYSTEM_API_CHILDREN_CLASSES ) ; Iterator < String > iterator = packages . iterator ( ) ; while ( iterator . hasNext ( ) ) { String packageName = iterator . next ( ) ; if ( systemPackage . isSystem ( packageName ) ) { iterator . remove ( ) ; } } removeLogicalDuplicates ( packages ) ; return packages ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traverses sorted list of packages and removes logical duplicates . For example if the set contains akka . akka . io . and akka . util . only akka . will remain . Note that if the set contains only akka . io . and akka . util . both will remain . Otherwise all of the org . apache . would devolve to org . [CODESPLIT] static void removeLogicalDuplicates ( SortedSet < String > packages ) { Iterator < String > iterator = packages . iterator ( ) ; if ( ! iterator . hasNext ( ) ) { return ; } String last = iterator . next ( ) ; while ( iterator . hasNext ( ) ) { String current = iterator . next ( ) ; if ( current . startsWith ( last ) ) { iterator . remove ( ) ; } else { last = current ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "new data . [CODESPLIT] protected void emptyBatch ( ) throws StageException { setBatchTime ( ) ; try { hdfsTargetConfigBean . getUGI ( ) . doAs ( new PrivilegedExceptionAction < Void > ( ) { @ Override public Void run ( ) throws Exception { hdfsTargetConfigBean . getCurrentWriters ( ) . purge ( ) ; if ( hdfsTargetConfigBean . getLateWriters ( ) != null ) { hdfsTargetConfigBean . getLateWriters ( ) . purge ( ) ; } return null ; } } ) ; } catch ( Exception ex ) { throw throwStageException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { // Validate configuration values and open any required resources. List < ConfigIssue > issues = super . init ( ) ; errorRecordHandler = new DefaultErrorRecordHandler ( getContext ( ) ) ; elEvals . init ( getContext ( ) ) ; Processor . Context context = getContext ( ) ; issues . addAll ( hikariConfigBean . validateConfigs ( context , issues ) ) ; if ( issues . isEmpty ( ) && null == dataSource ) { try { dataSource = jdbcUtil . createDataSourceForWrite ( hikariConfigBean , null , null , false , issues , Collections . emptyList ( ) , getContext ( ) ) ; } catch ( RuntimeException | SQLException | StageException e ) { LOG . debug ( \"Could not connect to data source\" , e ) ; issues . add ( getContext ( ) . createConfigIssue ( Groups . JDBC . name ( ) , CONNECTION_STRING , JdbcErrors . JDBC_00 , e . toString ( ) ) ) ; } } if ( issues . isEmpty ( ) ) { try { schemaWriter = JdbcSchemaWriterFactory . create ( hikariConfigBean . getConnectionString ( ) , dataSource ) ; } catch ( JdbcStageCheckedException e ) { issues . add ( getContext ( ) . createConfigIssue ( Groups . JDBC . name ( ) , CONNECTION_STRING , e . getErrorCode ( ) , e . getParams ( ) ) ) ; } schemaReader = new JdbcSchemaReader ( dataSource , schemaWriter ) ; tableCache = CacheBuilder . newBuilder ( ) . maximumSize ( 50 ) . build ( new CacheLoader < Pair < String , String > , LinkedHashMap < String , JdbcTypeInfo > > ( ) { @ Override public LinkedHashMap < String , JdbcTypeInfo > load ( Pair < String , String > pair ) throws Exception { return schemaReader . getTableSchema ( pair . getLeft ( ) , pair . getRight ( ) ) ; } } ) ; } // If issues is not empty, the UI will inform the user of each configuration issue in the list. return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "finds the first main line in the chunk from the specified index position onwards [CODESPLIT] int findNextMainLine ( LiveFileChunk chunk , int startIdx ) { List < FileLine > lines = chunk . getLines ( ) ; int found = - 1 ; for ( int i = startIdx ; found == - 1 && i < lines . size ( ) ; i ++ ) { if ( pattern . matcher ( lines . get ( i ) . getText ( ) . trim ( ) ) . matches ( ) ) { found = i ; } } return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "it there is an incomplete multiline from a previous chunk it starts from it . [CODESPLIT] LiveFileChunk resolveChunk ( LiveFileChunk chunk ) { List < FileLine > completeLines = new ArrayList <> ( ) ; List < FileLine > chunkLines = chunk . getLines ( ) ; if ( incompleteMultiLine . length ( ) == 0 ) { incompleteMultiLineOffset = chunk . getOffset ( ) ; incompleteMultiLineTruncated = chunk . isTruncated ( ) ; } incompleteMultiLineTruncated |= chunk . isTruncated ( ) ; int pos = 0 ; int idx = findNextMainLine ( chunk , pos ) ; // while we have main lines we keep adding/compacting into the new chunk while ( idx > - 1 ) { //any multi lines up to the next main line belong to the previous main line for ( int i = pos ; i < idx ; i ++ ) { incompleteMultiLine . append ( chunkLines . get ( i ) . getText ( ) ) ; } // if we have incomplete lines, at this point they are a complete multiline, compact and add to new chunk lines if ( incompleteMultiLine . length ( ) != 0 ) { completeLines . add ( new FileLine ( incompleteMultiLineOffset , incompleteMultiLine . toString ( ) ) ) ; incompleteMultiLineOffset += incompleteMultiLine . length ( ) ; // clear the incomplete multi lines as we just used them to create a full line incompleteMultiLine . setLength ( 0 ) ; incompleteMultiLineTruncated = false ; } // add the current main line as incomplete as we still don't if it is a complete line incompleteMultiLine . append ( chunkLines . get ( idx ) . getText ( ) ) ; // find the next main line pos = idx + 1 ; idx = findNextMainLine ( chunk , pos ) ; } // lets process the left over multi lines in the chunk after the last main line. // if any they will kept to completed with lines from the next chunk. for ( int i = pos ; i < chunkLines . size ( ) ; i ++ ) { incompleteMultiLine . append ( chunkLines . get ( i ) . getText ( ) ) ; } if ( completeLines . isEmpty ( ) ) { // didn't get a complete multi line yet, we keep storing lines but return a null chunk chunk = null ; } else { // create a new chunk with all complete multi lines chunk = new LiveFileChunk ( chunk . getTag ( ) , chunk . getFile ( ) , chunk . getCharset ( ) , completeLines , incompleteMultiLineTruncated ) ; } return chunk ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get { [CODESPLIT] public Connection getConnection ( ) throws SQLException { if ( threadLocalConnection . get ( ) == null ) { threadLocalConnection . set ( getNewConnection ( ) ) ; } return threadLocalConnection . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the current thread s connection [CODESPLIT] public void closeConnection ( ) { LOGGER . debug ( \"Closing connection\" ) ; Connection connectionToRemove = threadLocalConnection . get ( ) ; jdbcUtil . closeQuietly ( connectionToRemove ) ; if ( connectionToRemove != null ) { synchronized ( this ) { connectionsToCloseDuringDestroy . remove ( connectionToRemove ) ; } } threadLocalConnection . set ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "InputStream [CODESPLIT] @ Override public int read ( byte [ ] b ) throws IOException { checkState ( InputStream . class ) ; return ( ( InputStream ) stream ) . read ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "InputStream [CODESPLIT] @ Override public int read ( byte [ ] b , int offset , int len ) throws IOException { checkState ( InputStream . class ) ; return ( ( InputStream ) stream ) . read ( b , offset , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "InputStream [CODESPLIT] @ Override public long skip ( long n ) throws IOException { checkState ( InputStream . class ) ; return ( ( InputStream ) stream ) . skip ( n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ReadableByteChannel [CODESPLIT] @ Override public int read ( ByteBuffer dst ) throws IOException { checkState ( ReadableByteChannel . class ) ; return ( ( ReadableByteChannel ) stream ) . read ( dst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add backslash to escape the | character within quoted sections of the input string . This prevents the | from being processed as part of a regex . [CODESPLIT] private static String escapeQuotedSubstring ( String input ) { String [ ] parts = input . split ( \"'\" ) ; StringBuilder output = new StringBuilder ( input . length ( ) * 2 ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { if ( ( i % 2 ) == 1 ) { output . append ( \"'\" ) . append ( parts [ i ] . replace ( \"|\" , \"\\\\|\" ) ) . append ( \"'\" ) ; } else { output . append ( parts [ i ] ) ; } } return output . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a flow control setting such that a subscriber will block if it has buffered more messages than can be processed in a single batch times the number of record processors . Since the flow control settings are per subscriber we should divide by the number of subscribers to avoid buffering too much data in each subscriber . [CODESPLIT] private FlowControlSettings getFlowControlSettings ( ) { return FlowControlSettings . newBuilder ( ) . setLimitExceededBehavior ( FlowController . LimitExceededBehavior . Block ) . setMaxOutstandingElementCount ( ( long ) conf . basic . maxBatchSize * conf . maxThreads / conf . advanced . numSubscribers ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a channel provider shared by each subscriber . It is basically the default ChannelProvider with the exception that it can be configured with a custom endpoint for example when running against the PubSub Emulator . [CODESPLIT] private InstantiatingGrpcChannelProvider getChannelProvider ( ) { return SubscriptionAdminSettings . defaultGrpcTransportProviderBuilder ( ) . setMaxInboundMessageSize ( MAX_INBOUND_MESSAGE_SIZE ) . setEndpoint ( Strings . isNullOrEmpty ( conf . advanced . customEndpoint ) ? SubscriptionAdminSettings . getDefaultEndpoint ( ) : conf . advanced . customEndpoint ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate Hive Type Info Representation inside the Metadata Record . [CODESPLIT] public Field generateHiveTypeInfoFieldForMetadataRecord ( HiveTypeInfo hiveTypeInfo ) { Map < String , Field > fields = new HashMap <> ( ) ; fields . put ( HiveMetastoreUtil . TYPE , Field . create ( hiveTypeInfo . getHiveType ( ) . name ( ) ) ) ; fields . put ( HiveMetastoreUtil . EXTRA_INFO , generateExtraInfoFieldForMetadataRecord ( hiveTypeInfo ) ) ; fields . put ( HiveMetastoreUtil . COMMENT , Field . create ( Field . Type . STRING , hiveTypeInfo . getComment ( ) ) ) ; return Field . create ( fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate { @link HiveTypeInfo } from the Metadata Record <br > . ( Reverse of { @link #generateHiveTypeInfoFieldForMetadataRecord ( HiveTypeInfo ) } ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public HiveTypeInfo generateHiveTypeInfoFromMetadataField ( Field hiveTypeInfoField ) throws StageException { if ( hiveTypeInfoField . getType ( ) == Field . Type . MAP ) { Map < String , Field > fields = ( Map < String , Field > ) hiveTypeInfoField . getValue ( ) ; if ( ! fields . containsKey ( HiveMetastoreUtil . TYPE ) || ! fields . containsKey ( HiveMetastoreUtil . EXTRA_INFO ) ) { throw new StageException ( Errors . HIVE_17 , HiveMetastoreUtil . TYPE_INFO ) ; } HiveType hiveType = HiveType . getHiveTypeFromString ( fields . get ( HiveMetastoreUtil . TYPE ) . getValueAsString ( ) ) ; String comment = \"\" ; if ( fields . containsKey ( HiveMetastoreUtil . COMMENT ) ) { comment = fields . get ( HiveMetastoreUtil . COMMENT ) . getValueAsString ( ) ; } return generateHiveTypeInfoFromMetadataField ( hiveType , comment , fields . get ( HiveMetastoreUtil . EXTRA_INFO ) ) ; } else { throw new StageException ( Errors . HIVE_17 , HiveMetastoreUtil . TYPE_INFO ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate Column Definition for create table / add columns [CODESPLIT] public String generateColumnTypeDefinition ( HiveTypeInfo hiveTypeInfo , String columnName ) { return String . format ( HiveMetastoreUtil . COLUMN_TYPE , columnName , hiveTypeInfo . toString ( ) , hiveTypeInfo . getComment ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queues the batch for the consumer and waits until the consumer successfully commits the batch . While waiting processes any control messages from the consumer . Throws an exception when the consumer has indicated it encountered an error . [CODESPLIT] public Object put ( OffsetAndResult < Map . Entry > batch ) { if ( consumerError != null ) { throw new RuntimeException ( Utils . format ( \"Consumer encountered error: {}\" , consumerError ) , consumerError ) ; } if ( producerError != null ) { throw new RuntimeException ( Utils . format ( \"Producer encountered error: {}\" , producerError ) , producerError ) ; } try { Object expectedOffset = \"EMPTY_BATCH\" ; if ( ! batch . getResult ( ) . isEmpty ( ) ) { expectedOffset = batch . getResult ( ) . get ( batch . getResult ( ) . size ( ) - 1 ) . getKey ( ) ; // get the last one } while ( ! dataChannel . offer ( batch , 10 , TimeUnit . MILLISECONDS ) ) { for ( ControlChannel . Message controlMessage : controlChannel . getProducerMessages ( ) ) { switch ( controlMessage . getType ( ) ) { case CONSUMER_ERROR : Throwable throwable = ( Throwable ) controlMessage . getPayload ( ) ; consumerError = throwable ; throw new ConsumerRuntimeException ( Utils . format ( \"Consumer encountered error: {}\" , throwable ) , throwable ) ; default : String msg = Utils . format ( \"Illegal control message type: '{}'\" , controlMessage . getType ( ) ) ; throw new IllegalStateException ( msg ) ; } } } return expectedOffset ; } catch ( Throwable throwable ) { controlChannel . producerComplete ( ) ; if ( ! ( throwable instanceof ConsumerRuntimeException ) ) { String msg = \"Error caught in producer: \" + throwable ; LOG . error ( msg , throwable ) ; controlChannel . producerError ( throwable ) ; if ( producerError == null ) { producerError = throwable ; } } throw Throwables . propagate ( throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the expression into a pattern [CODESPLIT] public Grok compileExpression ( final String expression ) { throwErrorIfDictionaryIsNotReady ( ) ; final String digestedExpression = digestExpressionAux ( expression ) ; logger . debug ( \"Digested [\" + expression + \"] into [\" + digestedExpression + \"] before compilation\" ) ; return new Grok ( Pattern . compile ( digestedExpression ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Digests the original expression into a pure named regex [CODESPLIT] private String digestExpressionAux ( String originalExpression ) { final String PATTERN_START = \"%{\" ; final String PATTERN_STOP = \"}\" ; final char PATTERN_DELIMITER = ' ' ; while ( true ) { int PATTERN_START_INDEX = originalExpression . indexOf ( PATTERN_START ) ; int PATTERN_STOP_INDEX = originalExpression . indexOf ( PATTERN_STOP , PATTERN_START_INDEX + PATTERN_START . length ( ) ) ; // End the loop is %{ or } is not in the current line if ( PATTERN_START_INDEX < 0 || PATTERN_STOP_INDEX < 0 ) { break ; } // Grab what's inside %{ } String grokPattern = originalExpression . substring ( PATTERN_START_INDEX + PATTERN_START . length ( ) , PATTERN_STOP_INDEX ) ; // Where is the : character int PATTERN_DELIMITER_INDEX = grokPattern . indexOf ( PATTERN_DELIMITER ) ; String regexName = grokPattern ; String groupName = null ; if ( PATTERN_DELIMITER_INDEX >= 0 ) { regexName = grokPattern . substring ( 0 , PATTERN_DELIMITER_INDEX ) ; groupName = grokPattern . substring ( PATTERN_DELIMITER_INDEX + 1 , grokPattern . length ( ) ) ; } final String dictionaryValue = regexDictionary . get ( regexName ) ; if ( dictionaryValue == null ) { throw new GrokCompilationException ( \"Missing value for regex name : \" + regexName ) ; } // Defer till next iteration if ( dictionaryValue . contains ( PATTERN_START ) ) { break ; } String replacement = dictionaryValue ; // Named capture group if ( null != groupName ) { replacement = \"(?<\" + groupName + \">\" + dictionaryValue + \")\" ; } originalExpression = new StringBuilder ( originalExpression ) . replace ( PATTERN_START_INDEX , PATTERN_STOP_INDEX + PATTERN_STOP . length ( ) , replacement ) . toString ( ) ; } return originalExpression ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads dictionary from an input stream [CODESPLIT] public void addDictionary ( final InputStream inputStream ) { try { addDictionaryAux ( new InputStreamReader ( inputStream , \"UTF-8\" ) ) ; } catch ( IOException e ) { throw new GrokCompilationException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a dictionary entry via a Reader object [CODESPLIT] public void addDictionary ( Reader reader ) { try { addDictionaryAux ( reader ) ; } catch ( IOException e ) { throw new GrokCompilationException ( e ) ; } finally { IOUtils . closeQuietly ( reader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the AggregatorDataProvider instance . [CODESPLIT] public Map < Aggregator , AggregatorData > stop ( ) { Utils . checkState ( started , \"Not started\" ) ; Utils . checkState ( ! stopped , \"Already stopped\" ) ; stopped = true ; long currentTimeMillis = System . currentTimeMillis ( ) ; for ( Map . Entry < Aggregator , AggregatorData > e : data . entrySet ( ) ) { e . getValue ( ) . setTime ( currentTimeMillis ) ; } Map < Aggregator , AggregatorData > result = data ; result = aggregateDataWindows ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically rolls the DataWindow of all aggregators associated with the AggregatorDataProvider . [CODESPLIT] public Map < Aggregator , AggregatorData > roll ( long newDataWindowEndTimeMillis ) { Utils . checkState ( started , \"Not started\" ) ; Utils . checkState ( ! stopped , \"Already stopped\" ) ; Map < Aggregator , AggregatorData > result = data ; Map < Aggregator , AggregatorData > newData = new ConcurrentHashMap <> ( ) ; for ( Aggregator aggregator : aggregators ) { newData . put ( aggregator , aggregator . createAggregatorData ( newDataWindowEndTimeMillis ) ) ; } data = newData ; Map < Aggregator , AggregatorData > oldData = result ; // In case of sliding window, aggregate the data windows to get the result result = aggregateDataWindows ( result ) ; if ( currentDataWindow != null ) { currentDataWindow . setDataAndClose ( oldData ) ; } DataWindow newDataWindow = createDataWindow ( newDataWindowEndTimeMillis ) ; synchronized ( dataWindowQueue ) { dataWindowQueue . add ( newDataWindow ) ; dataWindowList = new ArrayList <> ( dataWindowQueue ) ; } currentDataWindow = newDataWindow ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current AggregatorData for an Aggregator . <p / > This method is also used by the group - by element Aggregators . [CODESPLIT] public AggregatorData getData ( Aggregator aggregator ) { Utils . checkState ( started , \"Not started\" ) ; Utils . checkState ( ! stopped , \"Already stopped\" ) ; Utils . checkNotNull ( aggregator , \"aggregator\" ) ; Utils . checkArgument ( aggregators . contains ( aggregator ) , Utils . formatL ( \"Aggregator {} is not registered to provider\" , aggregator ) ) ; return data . get ( aggregator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the given Java object into JSON string . [CODESPLIT] public String serialize ( Object obj ) throws ApiException { try { if ( obj != null ) return mapper . writeValueAsString ( obj ) ; else return null ; } catch ( Exception e ) { throw new ApiException ( 400 , e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize the given JSON string to Java object . [CODESPLIT] public < T > T deserialize ( String body , TypeRef returnType ) throws ApiException { JavaType javaType = mapper . constructType ( returnType . getType ( ) ) ; try { return mapper . readValue ( body , javaType ) ; } catch ( IOException e ) { if ( returnType . getType ( ) . equals ( String . class ) ) return ( T ) body ; else throw new ApiException ( 500 , e . getMessage ( ) , null , body ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize the given File to Java object . [CODESPLIT] public < T > T deserialize ( File file , TypeRef returnType ) throws ApiException { JavaType javaType = mapper . constructType ( returnType . getType ( ) ) ; try { return mapper . readValue ( file , javaType ) ; } catch ( IOException e ) { throw new ApiException ( 500 , e . getMessage ( ) , null , \"File to read file\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { // Validate configuration values and open any required resources. List < ConfigIssue > issues = super . init ( ) ; if ( getConfig ( ) . equals ( \"invalidValue\" ) ) { issues . add ( getContext ( ) . createConfigIssue ( Groups . SAMPLE . name ( ) , \"config\" , Errors . SAMPLE_00 , \"Here's what's wrong...\" ) ) ; } // If issues is not empty, the UI will inform the user of each configuration issue in the list. return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void write ( Batch batch ) throws StageException { Iterator < Record > batchIterator = batch . getRecords ( ) ; while ( batchIterator . hasNext ( ) ) { Record record = batchIterator . next ( ) ; try { write ( record ) ; } catch ( Exception e ) { switch ( getContext ( ) . getOnErrorRecord ( ) ) { case DISCARD : break ; case TO_ERROR : getContext ( ) . toError ( record , Errors . SAMPLE_01 , e . toString ( ) ) ; break ; case STOP_PIPELINE : throw new StageException ( Errors . SAMPLE_01 , e . toString ( ) ) ; default : throw new IllegalStateException ( Utils . format ( \"Unknown OnError value '{}'\" , getContext ( ) . getOnErrorRecord ( ) , e ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a single record to the destination . [CODESPLIT] private void write ( Record record ) throws OnRecordErrorException { // This is a contrived example, normally you may be performing an operation that could throw // an exception or produce an error condition. In that case you can throw an OnRecordErrorException // to send this record to the error pipeline with some details. if ( ! record . has ( \"/someField\" ) ) { throw new OnRecordErrorException ( Errors . SAMPLE_01 , record , \"exception detail message.\" ) ; } // TODO: write the records to your final destination }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve expression from record [CODESPLIT] public static String resolveEL ( ELEval elEval , ELVars variables , String val ) throws ELEvalException { return elEval . eval ( variables , val , String . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Extract information from the list fields of form : [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static < T > void extractInnerMapFromTheList ( Record metadataRecord , String listFieldName , String innerPairFirstFieldName , String innerPairSecondFieldName , boolean isSecondFieldHiveType , LinkedHashMap < String , T > returnValMap , HiveStageCheckedException exception ) throws HiveStageCheckedException { boolean throwException = false ; try { if ( metadataRecord . has ( SEP + listFieldName ) ) { Field columnField = metadataRecord . get ( SEP + listFieldName ) ; List < Field > columnList = columnField . getValueAsList ( ) ; if ( columnList != null ) { for ( Field listElementField : columnList ) { if ( listElementField . getType ( ) != Field . Type . MAP && listElementField . getType ( ) != Field . Type . LIST_MAP ) { throwException = true ; break ; } LinkedHashMap < String , Field > innerPair = listElementField . getValueAsListMap ( ) ; String innerPairFirstField = innerPair . get ( innerPairFirstFieldName ) . getValueAsString ( ) ; T retVal ; if ( isSecondFieldHiveType ) { Field hiveTypeInfoField = innerPair . get ( innerPairSecondFieldName ) ; HiveType hiveType = HiveType . getHiveTypeFromString ( hiveTypeInfoField . getValueAsMap ( ) . get ( HiveMetastoreUtil . TYPE ) . getValueAsString ( ) ) ; retVal = ( T ) ( hiveType . getSupport ( ) . generateHiveTypeInfoFromMetadataField ( hiveTypeInfoField ) ) ; } else { retVal = ( T ) innerPair . get ( innerPairSecondFieldName ) . getValueAsString ( ) ; } returnValMap . put ( innerPairFirstField , retVal ) ; } } } else { // we allow partition to be empty for non-partitioned table if ( ! listFieldName . equals ( PARTITION_FIELD ) ) throwException = true ; } } catch ( Exception e ) { LOG . error ( \"Can't parse metadata record\" , e ) ; throwException = true ; exception . initCause ( e ) ; } if ( throwException ) { throw exception ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opposite operation of extractInnerMapFromTheList . It takes LinkedHashMap and generate a Field that contains the list . This is to send metadata record to HMS target . This function is called to for partition type list and partition value list . [CODESPLIT] private static < T > Field generateInnerFieldFromTheList ( LinkedHashMap < String , T > original , String innerPairFirstFieldName , String innerPairSecondFieldName , boolean isSecondFieldHiveType ) throws HiveStageCheckedException { List < Field > columnList = new LinkedList <> ( ) ; for ( Map . Entry < String , T > pair : original . entrySet ( ) ) { LinkedHashMap < String , Field > entry = new LinkedHashMap <> ( ) ; entry . put ( innerPairFirstFieldName , Field . create ( pair . getKey ( ) ) ) ; if ( isSecondFieldHiveType ) { HiveTypeInfo hiveTypeInfo = ( HiveTypeInfo ) pair . getValue ( ) ; entry . put ( innerPairSecondFieldName , hiveTypeInfo . getHiveType ( ) . getSupport ( ) . generateHiveTypeInfoFieldForMetadataRecord ( hiveTypeInfo ) ) ; } else { entry . put ( innerPairSecondFieldName , Field . create ( pair . getValue ( ) . toString ( ) ) ) ; //stored value is \"INT\". need to fix this } columnList . add ( Field . createListMap ( entry ) ) ; } return ! columnList . isEmpty ( ) ? Field . create ( columnList ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get qualified table name ( defined as dbName . tableName ) [CODESPLIT] public static String getQualifiedTableName ( String dbName , String tableName ) { return ( dbName == null || dbName . isEmpty ( ) ) ? escapeHiveObjectName ( tableName ) : JOINER . join ( escapeHiveObjectName ( dbName ) , escapeHiveObjectName ( tableName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract column information from the column list in / columns field . <br > [CODESPLIT] public static LinkedHashMap < String , HiveTypeInfo > getColumnNameType ( Record metadataRecord ) throws HiveStageCheckedException { LinkedHashMap < String , HiveTypeInfo > columnNameType = new LinkedHashMap <> ( ) ; extractInnerMapFromTheList ( metadataRecord , COLUMNS_FIELD , COLUMN_NAME , TYPE_INFO , true , columnNameType , new HiveStageCheckedException ( Errors . HIVE_17 , COLUMNS_FIELD , metadataRecord ) ) ; return columnNameType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract column information from the Partition list in / partitions field . <br > [CODESPLIT] public static LinkedHashMap < String , HiveTypeInfo > getPartitionNameType ( Record metadataRecord ) throws HiveStageCheckedException { LinkedHashMap < String , HiveTypeInfo > partitionNameType = new LinkedHashMap <> ( ) ; extractInnerMapFromTheList ( metadataRecord , PARTITION_FIELD , PARTITION_NAME , TYPE_INFO , true , partitionNameType , new HiveStageCheckedException ( Errors . HIVE_17 , PARTITION_FIELD , metadataRecord ) ) ; return partitionNameType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract column information from the Partition list in / partitions field . <br > [CODESPLIT] public static LinkedHashMap < String , String > getPartitionNameValue ( Record metadataRecord ) throws HiveStageCheckedException { LinkedHashMap < String , String > partitionNameValue = new LinkedHashMap <> ( ) ; extractInnerMapFromTheList ( metadataRecord , PARTITION_FIELD , PARTITION_NAME , PARTITION_VALUE , false , partitionNameValue , new HiveStageCheckedException ( Errors . HIVE_17 , PARTITION_FIELD , metadataRecord ) ) ; return partitionNameValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this is a TABLE metadata request ( new or changed table ) . [CODESPLIT] public static boolean isSchemaChangeRecord ( Record metadataRecord ) { return MetadataRecordType . TABLE . name ( ) . equals ( metadataRecord . get ( SEP + METADATA_RECORD_TYPE ) . getValueAsString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this is a TABLE metadata request ( new or changed table ) . [CODESPLIT] public static void validateTblPropertiesInfo ( HMPDataFormat hmpDataFormat , TBLPropertiesInfoCacheSupport . TBLPropertiesInfo tblPropertiesInfo , String qualifiedTableName ) throws HiveStageCheckedException { if ( hmpDataFormat == HMPDataFormat . AVRO && ! tblPropertiesInfo . getSerdeLibrary ( ) . equals ( HiveMetastoreUtil . AVRO_SERDE ) ) { throw new HiveStageCheckedException ( Errors . HIVE_32 , qualifiedTableName , tblPropertiesInfo . getSerdeLibrary ( ) , hmpDataFormat . getLabel ( ) ) ; } else if ( hmpDataFormat == HMPDataFormat . PARQUET && ! tblPropertiesInfo . getSerdeLibrary ( ) . equals ( HiveMetastoreUtil . PARQUET_SERDE ) ) { throw new HiveStageCheckedException ( Errors . HIVE_32 , qualifiedTableName , tblPropertiesInfo . getSerdeLibrary ( ) , hmpDataFormat . getLabel ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Table Name from the metadata record . [CODESPLIT] public static String getTableName ( Record metadataRecord ) throws HiveStageCheckedException { if ( metadataRecord . has ( SEP + TABLE_FIELD ) ) { return metadataRecord . get ( SEP + TABLE_FIELD ) . getValueAsString ( ) ; } throw new HiveStageCheckedException ( Errors . HIVE_17 , TABLE_FIELD , metadataRecord ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Database Name from the metadata record . [CODESPLIT] public static String getDatabaseName ( Record metadataRecord ) throws HiveStageCheckedException { if ( metadataRecord . has ( SEP + DATABASE_FIELD ) ) { String dbName = metadataRecord . get ( SEP + DATABASE_FIELD ) . getValueAsString ( ) ; return dbName . isEmpty ( ) ? DEFAULT_DBNAME : dbName ; } throw new HiveStageCheckedException ( Errors . HIVE_17 , DATABASE_FIELD , metadataRecord ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get internal field from the metadata record . [CODESPLIT] public static boolean getInternalField ( Record metadataRecord ) throws HiveStageCheckedException { if ( metadataRecord . has ( SEP + INTERNAL_FIELD ) ) { return metadataRecord . get ( SEP + INTERNAL_FIELD ) . getValueAsBoolean ( ) ; } throw new HiveStageCheckedException ( Errors . HIVE_17 , INTERNAL_FIELD , metadataRecord ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Location from the metadata record . [CODESPLIT] public static String getLocation ( Record metadataRecord ) throws HiveStageCheckedException { if ( metadataRecord . has ( SEP + LOCATION_FIELD ) ) { return metadataRecord . get ( SEP + LOCATION_FIELD ) . getValueAsString ( ) ; } throw new HiveStageCheckedException ( Errors . HIVE_17 , LOCATION_FIELD , metadataRecord ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the customLocation flag from the metadata record . This flag marks whether or not the Hive database object is stored into a custom path on the Hadoop filesystem . In both cases the path is stored in the location field of the metadata record . [CODESPLIT] public static boolean getCustomLocation ( Record metadataRecord ) throws HiveStageCheckedException { if ( metadataRecord . get ( SEP + VERSION ) . getValueAsInteger ( ) < 3 ) { return DEFAULT_CUSTOM_LOCATION ; } if ( metadataRecord . has ( SEP + CUSTOM_LOCATION ) ) { return metadataRecord . get ( SEP + CUSTOM_LOCATION ) . getValueAsBoolean ( ) ; } throw new HiveStageCheckedException ( Errors . HIVE_17 , CUSTOM_LOCATION , metadataRecord ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Avro Schema from Metadata Record . [CODESPLIT] public static String getAvroSchema ( Record metadataRecord ) throws HiveStageCheckedException { if ( metadataRecord . has ( SEP + AVRO_SCHEMA ) ) { return metadataRecord . get ( SEP + AVRO_SCHEMA ) . getValueAsString ( ) ; } throw new HiveStageCheckedException ( Errors . HIVE_17 , AVRO_SCHEMA , metadataRecord ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get DataFormat from Metadata Record . [CODESPLIT] public static String getDataFormat ( Record metadataRecord ) throws HiveStageCheckedException { if ( metadataRecord . get ( SEP + VERSION ) . getValueAsInteger ( ) == 1 ) { return DEFAULT_DATA_FORMAT ; } if ( metadataRecord . has ( SEP + DATA_FORMAT ) ) { return metadataRecord . get ( SEP + DATA_FORMAT ) . getValueAsString ( ) ; } throw new HiveStageCheckedException ( Errors . HIVE_17 , DATA_FORMAT , metadataRecord ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill in metadata to Record . This is for new partition creation . Use the { [CODESPLIT] public static Field newPartitionMetadataFieldBuilder ( String database , String tableName , LinkedHashMap < String , String > partitionList , String location , boolean customLocation , HMPDataFormat dataFormat ) throws HiveStageCheckedException { LinkedHashMap < String , Field > metadata = new LinkedHashMap <> ( ) ; metadata . put ( VERSION , Field . create ( PARTITION_ADDITION_METADATA_RECORD_VERSION ) ) ; metadata . put ( METADATA_RECORD_TYPE , Field . create ( MetadataRecordType . PARTITION . name ( ) ) ) ; metadata . put ( DATABASE_FIELD , Field . create ( database ) ) ; metadata . put ( TABLE_FIELD , Field . create ( tableName ) ) ; metadata . put ( LOCATION_FIELD , Field . create ( location ) ) ; metadata . put ( CUSTOM_LOCATION , Field . create ( customLocation ) ) ; metadata . put ( DATA_FORMAT , Field . create ( dataFormat . name ( ) ) ) ; //fill in the partition list here metadata . put ( PARTITION_FIELD , generateInnerFieldFromTheList ( partitionList , PARTITION_NAME , PARTITION_VALUE , false ) ) ; return Field . createListMap ( metadata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill in metadata to Record . This is for new schema creation . [CODESPLIT] public static Field newSchemaMetadataFieldBuilder ( String database , String tableName , LinkedHashMap < String , HiveTypeInfo > columnList , LinkedHashMap < String , HiveTypeInfo > partitionTypeList , boolean internal , String location , String avroSchema , HMPDataFormat dataFormat ) throws HiveStageCheckedException { LinkedHashMap < String , Field > metadata = new LinkedHashMap <> ( ) ; metadata . put ( VERSION , Field . create ( SCHEMA_CHANGE_METADATA_RECORD_VERSION ) ) ; metadata . put ( METADATA_RECORD_TYPE , Field . create ( MetadataRecordType . TABLE . name ( ) ) ) ; metadata . put ( DATABASE_FIELD , Field . create ( database ) ) ; metadata . put ( TABLE_FIELD , Field . create ( tableName ) ) ; metadata . put ( LOCATION_FIELD , Field . create ( location ) ) ; metadata . put ( DATA_FORMAT , Field . create ( dataFormat . name ( ) ) ) ; //fill in column type list here metadata . put ( COLUMNS_FIELD , generateInnerFieldFromTheList ( columnList , COLUMN_NAME , TYPE_INFO , true ) ) ; //fill in partition type list here if ( partitionTypeList != null && ! partitionTypeList . isEmpty ( ) ) { metadata . put ( PARTITION_FIELD , generateInnerFieldFromTheList ( partitionTypeList , PARTITION_NAME , TYPE_INFO , true ) ) ; } metadata . put ( INTERNAL_FIELD , Field . create ( internal ) ) ; metadata . put ( AVRO_SCHEMA , Field . create ( avroSchema ) ) ; return Field . createListMap ( metadata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate precision or scale in context of record and given field path . [CODESPLIT] private static int resolveScaleOrPrecisionExpression ( String type , ELEval elEval , ELVars variables , String defaultScaleEL , String fieldPath ) throws ELEvalException , HiveStageCheckedException { // By default we take the constant given to this method String value = defaultScaleEL ; // And if so evaluate it if ( elEval != null ) { value = elEval . eval ( variables , defaultScaleEL , String . class ) ; } // Finally try to parse output as an integer. Failure means that we are unable to calculate proper scale/precision. try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { throw new HiveStageCheckedException ( Errors . HIVE_29 , type , fieldPath , defaultScaleEL , value , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a Record to LinkedHashMap . This is for comparing the structure of incoming Record with cache . Since Avro does not support char short and date types it needs to convert the type to corresponding supported types and change the value in record . [CODESPLIT] public static LinkedHashMap < String , HiveTypeInfo > convertRecordToHMSType ( Record record , ELEval scaleEL , ELEval precisionEL , ELEval commentEL , String scaleExpression , String precisionExpression , String commentExpression , ELVars variables ) throws HiveStageCheckedException , ELEvalException { if ( ! record . get ( ) . getType ( ) . isOneOf ( Field . Type . MAP , Field . Type . LIST_MAP ) ) { throw new HiveStageCheckedException ( Errors . HIVE_33 , record . getHeader ( ) . getSourceId ( ) , record . get ( ) . getType ( ) . toString ( ) ) ; } LinkedHashMap < String , HiveTypeInfo > columns = new LinkedHashMap <> ( ) ; Map < String , Field > list = record . get ( ) . getValueAsMap ( ) ; for ( Map . Entry < String , Field > pair : list . entrySet ( ) ) { if ( StringUtils . isEmpty ( pair . getKey ( ) ) ) { throw new HiveStageCheckedException ( Errors . HIVE_01 , \"Field name is empty\" ) ; } Field currField = pair . getValue ( ) ; switch ( currField . getType ( ) ) { case SHORT : currField = Field . create ( Field . Type . INTEGER , currField . getValue ( ) ) ; break ; case CHAR : currField = Field . create ( currField . getValueAsString ( ) ) ; break ; case DATETIME : currField = Field . create ( Field . Type . STRING , currField . getValue ( ) == null ? null : datetimeFormat . get ( ) . format ( currField . getValueAsDate ( ) ) ) ; break ; case TIME : currField = Field . create ( Field . Type . STRING , currField . getValue ( ) == null ? null : timeFormat . get ( ) . format ( currField . getValueAsTime ( ) ) ) ; break ; default : break ; } // Set current field in the context - used by subsequent ELs (decimal resolution, comments, ...) FieldPathEL . setFieldInContext ( variables , pair . getKey ( ) ) ; String comment = commentEL . eval ( variables , commentExpression , String . class ) ; if ( ! COMMENT_PATTERN . matcher ( comment ) . matches ( ) ) { throw new HiveStageCheckedException ( com . streamsets . pipeline . stage . processor . hive . Errors . HIVE_METADATA_11 , pair . getKey ( ) , comment ) ; } // Update the Field type and value in Record pair . setValue ( currField ) ; HiveType hiveType = HiveType . getHiveTypeforFieldType ( currField . getType ( ) ) ; HiveTypeInfo hiveTypeInfo ; // Some types requires special checks or alterations if ( hiveType == HiveType . DECIMAL ) { int precision = resolveScaleOrPrecisionExpression ( \"precision\" , precisionEL , variables , precisionExpression , pair . getKey ( ) ) ; int scale = resolveScaleOrPrecisionExpression ( \"scale\" , scaleEL , variables , scaleExpression , pair . getKey ( ) ) ; validateScaleAndPrecision ( pair . getKey ( ) , currField , precision , scale ) ; hiveTypeInfo = hiveType . getSupport ( ) . generateHiveTypeInfoFromRecordField ( currField , comment , precision , scale ) ; // We need to make sure that all java objects have the same scale if ( currField . getValue ( ) != null ) { pair . setValue ( Field . create ( currField . getValueAsDecimal ( ) . setScale ( scale ) ) ) ; } } else { hiveTypeInfo = hiveType . getSupport ( ) . generateHiveTypeInfoFromRecordField ( currField , comment ) ; } columns . put ( pair . getKey ( ) . toLowerCase ( ) , hiveTypeInfo ) ; } return columns ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate avro schema from column name and type information . typeInfo in 1st parameter needs to contain precision and scale information in the value ( HiveTypeInfo ) . The 2nd parameter qualifiedName will be the name of Avro Schema . [CODESPLIT] public static String generateAvroSchema ( Map < String , HiveTypeInfo > typeInfo , String qualifiedName ) throws HiveStageCheckedException { Utils . checkNotNull ( typeInfo , \"Error TypeInfo cannot be null\" ) ; // Avro doesn't allow \"`\" in names, so we're dropping those from qualified name AvroHiveSchemaGenerator gen = new AvroHiveSchemaGenerator ( qualifiedName . replace ( \"`\" , \"\" ) ) ; try { return gen . inferSchema ( typeInfo ) ; } catch ( StageException e ) { //So that any error to generate avro schema will result in onRecordErrorException and routed to error lane. throw new HiveStageCheckedException ( e . getErrorCode ( ) , e . getParams ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the number of partition columns and names match w . r . t hive . [CODESPLIT] public static void validatePartitionInformation ( TypeInfoCacheSupport . TypeInfo typeInfo , LinkedHashMap < String , String > partitionValMap , String qualifiedTableName ) throws HiveStageCheckedException { Set < String > partitionNamesInHive = typeInfo . getPartitionTypeInfo ( ) . keySet ( ) ; Set < String > partitionNames = partitionValMap . keySet ( ) ; if ( ! ( partitionNamesInHive . size ( ) == partitionNames . size ( ) && partitionNamesInHive . containsAll ( partitionNames ) ) ) { LOG . error ( Utils . format ( \"Partition mismatch. In Hive: {}, In Record : {}\" , partitionNamesInHive . size ( ) , partitionNames . size ( ) ) ) ; throw new HiveStageCheckedException ( Errors . HIVE_27 , qualifiedTableName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a partition path for the external table . [CODESPLIT] public static String generatePartitionPath ( LinkedHashMap < String , String > partitions ) { StringBuilder builder = new StringBuilder ( ) ; for ( Map . Entry < String , String > pair : partitions . entrySet ( ) ) { builder . append ( String . format ( PARTITION_PATH , pair . getKey ( ) , pair . getValue ( ) ) ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the hdfs paths where the avro schema is stored after serializing . Path is appended with current time so as to have an ordering . [CODESPLIT] public static String serializeSchemaToHDFS ( UserGroupInformation loginUGI , final FileSystem fs , final String location , final String schemaFolder , final String databaseName , final String tableName , final String schemaJson ) throws StageException { String folderLocation ; if ( schemaFolder . startsWith ( SEP ) ) { folderLocation = schemaFolder ; } else { folderLocation = location + SEP + schemaFolder ; } final Path schemasFolderPath = new Path ( folderLocation ) ; final String path = folderLocation + SEP + String . format ( AVRO_SCHEMA_FILE_FORMAT , databaseName , tableName , UUID . randomUUID ( ) . toString ( ) ) ; try { loginUGI . doAs ( new PrivilegedExceptionAction < Void > ( ) { @ Override public Void run ( ) throws Exception { if ( ! fs . exists ( schemasFolderPath ) ) { fs . mkdirs ( schemasFolderPath ) ; } Path schemaFilePath = new Path ( path ) ; //This will never happen unless two HMS targets are writing, we will error out for this //and let user handle this via error record handling. if ( ! fs . exists ( schemaFilePath ) ) { try ( FSDataOutputStream os = fs . create ( schemaFilePath ) ) { byte [ ] schemaBytes = schemaJson . getBytes ( \"UTF-8\" ) ; os . write ( schemaBytes , 0 , schemaBytes . length ) ; } } else { LOG . error ( Utils . format ( \"Already schema file {} exists in HDFS\" , path ) ) ; throw new IOException ( \"Already schema file exists\" ) ; } return null ; } } ) ; } catch ( Exception e ) { LOG . error ( \"Error in Writing Schema to HDFS: \" + e . toString ( ) , e ) ; throw new StageException ( Errors . HIVE_18 , path , e . getMessage ( ) ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets cached { @link com . streamsets . pipeline . stage . lib . hive . cache . HMSCacheSupport . HMSCacheInfo } from cache . <br > First call getIfPresent to obtain data from local cache . If not exists load from HMS [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T extends HMSCacheSupport . HMSCacheInfo > T getCacheInfo ( HMSCache hmsCache , HMSCacheType cacheType , String qualifiedName , HiveQueryExecutor queryExecutor ) throws StageException { HMSCacheSupport . HMSCacheInfo cacheInfo = hmsCache . getIfPresent ( cacheType , qualifiedName ) ; if ( cacheType != HMSCacheType . AVRO_SCHEMA_INFO && cacheInfo == null ) { // Try loading by executing HMS query cacheInfo = hmsCache . getOrLoad ( cacheType , qualifiedName , queryExecutor ) ; } return ( T ) cacheInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set parameters and primary keys in query . [CODESPLIT] @ VisibleForTesting @ SuppressWarnings ( \"unchecked\" ) int setParameters ( int opCode , SortedMap < String , String > columnsToParameters , final Record record , final Connection connection , PreparedStatement statement ) throws OnRecordErrorException { int paramIdx = 1 ; // Set columns and their value in query. No need to perform this for delete operation. if ( opCode != OperationType . DELETE_CODE ) { paramIdx = setParamsToStatement ( paramIdx , statement , columnsToParameters , record , connection , opCode ) ; } // Set primary keys in WHERE clause for update and delete operations if ( opCode != OperationType . INSERT_CODE ) { paramIdx = setPrimaryKeys ( paramIdx , record , statement , opCode ) ; } return paramIdx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Some databases drivers allow us to figure out which record in a particular batch failed . < / p > <p > In the case that we have a list of update counts we can mark just the record as erroneous . Otherwise we must send the entire batch to error . < / p > [CODESPLIT] private void handleBatchUpdateException ( Collection < Record > failedRecords , SQLException e , List < OnRecordErrorException > errorRecords ) throws StageException { if ( jdbcUtil . isDataError ( getCustomDataSqlStateCodes ( ) , getConnectionString ( ) , e ) ) { String formattedError = JdbcErrors . JDBC_79 . getMessage ( ) ; LOG . error ( formattedError ) ; LOG . debug ( formattedError , e ) ; if ( ! getRollbackOnError ( ) && e instanceof BatchUpdateException && ( ( BatchUpdateException ) e ) . getUpdateCounts ( ) . length > 0 ) { BatchUpdateException bue = ( BatchUpdateException ) e ; int i = 0 ; for ( Record record : failedRecords ) { if ( i >= bue . getUpdateCounts ( ) . length || bue . getUpdateCounts ( ) [ i ] == PreparedStatement . EXECUTE_FAILED ) { errorRecords . add ( new OnRecordErrorException ( record , JDBC_14 , e . getSQLState ( ) , e . getErrorCode ( ) , e . getMessage ( ) , jdbcUtil . formatSqlException ( e ) , e ) ) ; } i ++ ; } } else { for ( Record record : failedRecords ) { errorRecords . add ( new OnRecordErrorException ( record , JDBC_14 , e . getSQLState ( ) , e . getErrorCode ( ) , e . getMessage ( ) , jdbcUtil . formatSqlException ( e ) , e ) ) ; } } } else { handleSqlException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns ALL SDC Configuration [CODESPLIT] public Map < String , Object > getConfiguration ( ) throws ApiException { Object postBody = null ; byte [ ] postBinaryBody = null ; // create path and map variables String path = \"/v1/system/configuration\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > queryParams = new ArrayList < Pair > ( ) ; Map < String , String > headerParams = new HashMap < String , String > ( ) ; Map < String , Object > formParams = new HashMap < String , Object > ( ) ; final String [ ] accepts = { \"application/json\" } ; final String accept = apiClient . selectHeaderAccept ( accepts ) ; final String [ ] contentTypes = { } ; final String contentType = apiClient . selectHeaderContentType ( contentTypes ) ; String [ ] authNames = new String [ ] { \"basic\" } ; TypeRef returnType = new TypeRef < Map < String , Object > > ( ) { } ; return apiClient . invokeAPI ( path , \"GET\" , queryParams , postBody , postBinaryBody , headerParams , formParams , accept , contentType , authNames , returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the Read Context Cache { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private LoadingCache < TableRuntimeContext , TableReadContext > buildReadContextCache ( CacheLoader < TableRuntimeContext , TableReadContext > tableCacheLoader ) { CacheBuilder resultSetCacheBuilder = CacheBuilder . newBuilder ( ) . removalListener ( new JdbcTableReadContextInvalidationListener ( ) ) ; if ( tableJdbcConfigBean . batchTableStrategy == BatchTableStrategy . SWITCH_TABLES ) { if ( tableJdbcConfigBean . resultCacheSize > 0 ) { resultSetCacheBuilder = resultSetCacheBuilder . maximumSize ( tableJdbcConfigBean . resultCacheSize ) ; } } else { resultSetCacheBuilder = resultSetCacheBuilder . maximumSize ( 1 ) ; } if ( tableCacheLoader != null ) { return resultSetCacheBuilder . build ( tableCacheLoader ) ; } else { return resultSetCacheBuilder . build ( new JdbcTableReadContextLoader ( connectionManager , offsets , tableJdbcConfigBean . fetchSize , tableJdbcConfigBean . quoteChar . getQuoteCharacter ( ) , tableJdbcELEvalContext , isReconnect ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the gauge with needed information [CODESPLIT] private void initGaugeIfNeeded ( ) { gaugeMap . put ( THREAD_NAME , Thread . currentThread ( ) . getName ( ) ) ; gaugeMap . put ( STATUS , \"\" ) ; gaugeMap . put ( TABLES_OWNED_COUNT , tableReadContextCache . size ( ) ) ; gaugeMap . put ( CURRENT_TABLE , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a batch ( looping through as many tables as needed ) until a batch can be generated and then commit offset . [CODESPLIT] private void generateBatchAndCommitOffset ( BatchContext batchContext ) { int recordCount = 0 ; int eventCount = 0 ; try { while ( tableRuntimeContext == null ) { tableRuntimeContext = tableProvider . nextTable ( threadNumber ) ; if ( tableRuntimeContext == null ) { // small sleep before trying to acquire a table again, to potentially allow a new partition to be // returned to shared queue or created final boolean uninterrupted = ThreadUtil . sleep ( ACQUIRE_TABLE_SLEEP_INTERVAL ) ; if ( ! uninterrupted ) { LOG . trace ( \"Interrupted which trying to acquire table\" ) ; } if ( ! uninterrupted || tableRuntimeContext == null ) { return ; } } } updateGauge ( JdbcBaseRunnable . Status . QUERYING_TABLE ) ; tableReadContext = getOrLoadTableReadContext ( ) ; ResultSet rs = tableReadContext . getResultSet ( ) ; boolean resultSetEndReached = false ; try { updateGauge ( JdbcBaseRunnable . Status . GENERATING_BATCH ) ; while ( recordCount < batchSize ) { if ( rs . isClosed ( ) || ! rs . next ( ) ) { if ( rs . isClosed ( ) ) { LOG . trace ( \"ResultSet is closed\" ) ; } resultSetEndReached = true ; break ; } createAndAddRecord ( rs , tableRuntimeContext , batchContext ) ; recordCount ++ ; } LOG . trace ( \"{} records generated\" , recordCount ) ; if ( commonSourceConfigBean . enableSchemaChanges ) { generateSchemaChanges ( batchContext ) ; } tableRuntimeContext . setResultSetProduced ( true ) ; //Reset numSqlErrors if we are able to read result set and add records to the batch context. numSQLErrors = 0 ; firstSqlException = null ; //If exception happened we do not report anything about no more data event //We report noMoreData if either evictTableReadContext is true (result set no more rows) / record count is 0. final AtomicBoolean tableFinished = new AtomicBoolean ( false ) ; final AtomicBoolean schemaFinished = new AtomicBoolean ( false ) ; final List < String > schemaFinishedTables = new LinkedList <> ( ) ; tableProvider . reportDataOrNoMoreData ( tableRuntimeContext , recordCount , batchSize , resultSetEndReached , tableFinished , schemaFinished , schemaFinishedTables ) ; if ( tableFinished . get ( ) ) { TableJdbcEvents . createTableFinishedEvent ( context , batchContext , tableRuntimeContext ) ; eventCount ++ ; } if ( schemaFinished . get ( ) ) { TableJdbcEvents . createSchemaFinishedEvent ( context , batchContext , tableRuntimeContext , schemaFinishedTables ) ; eventCount ++ ; } } finally { if ( resultSetEndReached ) { tableReadContext . closeResultSet ( ) ; } handlePostBatchAsNeeded ( resultSetEndReached , recordCount , eventCount , batchContext ) ; } } catch ( SQLException | ExecutionException | StageException | InterruptedException e ) { LOG . error ( \"Error happened\" , e ) ; //invalidate if the connection is closed tableReadContextCache . invalidateAll ( ) ; connectionManager . closeConnection ( ) ; //If we have executed post batch that had errored out if ( tableRuntimeContext != null ) { final TableContext table = tableRuntimeContext . getSourceTableContext ( ) ; //if the currently acquired tableContext is no longer a valid candidate, try re-fetch the table from table provider if ( commonSourceConfigBean . allowLateTable && ! tableProvider . getActiveRuntimeContexts ( ) . containsKey ( table ) ) { tableRuntimeContext = null ; } } Throwable th = ( e instanceof ExecutionException ) ? e . getCause ( ) : e ; if ( th instanceof SQLException ) { handleSqlException ( ( SQLException ) th ) ; } else if ( e instanceof InterruptedException ) { LOG . error ( \"Thread {} interrupted\" , gaugeMap . get ( THREAD_NAME ) ) ; } else { handleStageError ( JdbcErrors . JDBC_67 , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After a batch is generate perform needed operations generate and commit batch Evict entries from { [CODESPLIT] protected void handlePostBatchAsNeeded ( boolean resultSetEndReached , int recordCount , int eventCount , BatchContext batchContext ) { AtomicBoolean shouldEvict = new AtomicBoolean ( resultSetEndReached ) ; // If we read at least one record, it's safe to drop the starting offsets, otherwise they have to re-used if ( recordCount > 0 ) { tableRuntimeContext . getSourceTableContext ( ) . clearStartOffset ( ) ; } //Only process batch if there are records or events if ( recordCount > 0 || eventCount > 0 ) { TableReadContext tableReadContext = tableReadContextCache . getIfPresent ( tableRuntimeContext ) ; Optional . ofNullable ( tableReadContext ) . ifPresent ( readContext -> { readContext . addProcessingMetrics ( 1 , recordCount ) ; LOG . debug ( \"Table {} read batches={} and records={}\" , tableRuntimeContext . getQualifiedName ( ) , readContext . getNumberOfBatches ( ) , readContext . getNumberOfRecords ( ) ) ; calculateEvictTableFlag ( shouldEvict , tableReadContext ) ; } ) ; updateGauge ( JdbcBaseRunnable . Status . BATCH_GENERATED ) ; //Process And Commit offsets if ( tableRuntimeContext . isUsingNonIncrementalLoad ( ) ) { // process the batch now, will handle the offset commit outside this block context . processBatch ( batchContext ) ; } else { // for incremental (normal) mode, the offset was already stored in this map // by the specific subclass's createAndAddRecord method final String offsetValue = offsets . get ( tableRuntimeContext . getOffsetKey ( ) ) ; context . processBatch ( batchContext , tableRuntimeContext . getOffsetKey ( ) , offsetValue ) ; } } if ( tableRuntimeContext . isUsingNonIncrementalLoad ( ) ) { // for non-incremental mode, the offset is simply a singleton map indicating whether it's finished final String offsetValue = createNonIncrementalLoadOffsetValue ( resultSetEndReached ) ; context . commitOffset ( tableRuntimeContext . getOffsetKey ( ) , offsetValue ) ; } //Make sure we close the result set only when there are no more rows in the result set if ( shouldEvict . get ( ) ) { //Invalidate so as to fetch a new result set //We close the result set/statement in Removal Listener tableReadContextCache . invalidate ( tableRuntimeContext ) ; tableProvider . releaseOwnedTable ( tableRuntimeContext , threadNumber ) ; tableRuntimeContext = null ; } else if ( tableJdbcConfigBean . batchTableStrategy == BatchTableStrategy . SWITCH_TABLES && ! tableRuntimeContext . isUsingNonIncrementalLoad ( ) ) { tableRuntimeContext = null ; } final List < TableRuntimeContext > removedPartitions = tableProvider . getAndClearRemovedPartitions ( ) ; if ( removedPartitions != null && removedPartitions . size ( ) > 0 ) { for ( TableRuntimeContext partition : removedPartitions ) { LOG . debug ( \"Removing offset entry for partition {} since it has been removed from the table provider\" , partition . getDescription ( ) ) ; context . commitOffset ( partition . getOffsetKey ( ) , null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the { [CODESPLIT] private static void initTableEvalContextForProduce ( TableJdbcELEvalContext tableJdbcELEvalContext , TableRuntimeContext tableContext , Calendar calendar ) { tableJdbcELEvalContext . setCalendar ( calendar ) ; tableJdbcELEvalContext . setTime ( calendar . getTime ( ) ) ; tableJdbcELEvalContext . setTableContext ( tableContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait If needed before a new query is issued . ( Does not wait if the result set is already cached ) [CODESPLIT] private void waitIfNeeded ( ) throws InterruptedException { if ( queryRateLimiter != null ) { updateGauge ( Status . WAITING_FOR_RATE_LIMIT_PERMIT ) ; double waitTime = queryRateLimiter . acquire ( ) ; updateGauge ( Status . ACQUIRED_RATE_LIMIT_PERMIT ) ; gaugeMap . put ( LAST_RATE_LIMIT_WAIT_TIME , waitTime ) ; } else { LOG . debug ( \"No query rate limiter in effect; not waiting\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Or Load { [CODESPLIT] private TableReadContext getOrLoadTableReadContext ( ) throws ExecutionException , InterruptedException { initTableEvalContextForProduce ( tableJdbcELEvalContext , tableRuntimeContext , Calendar . getInstance ( TimeZone . getTimeZone ( ZoneId . of ( tableJdbcConfigBean . timeZoneID ) ) ) ) ; //Check and then if we want to wait for query being issued do that TableReadContext tableReadContext = tableReadContextCache . getIfPresent ( tableRuntimeContext ) ; LOG . trace ( \"Selected table : '{}' for generating records\" , tableRuntimeContext . getDescription ( ) ) ; if ( tableReadContext == null ) { //Wait before issuing query (Optimization instead of waiting during each batch) waitIfNeeded ( ) ; //Set time before query initTableEvalContextForProduce ( tableJdbcELEvalContext , tableRuntimeContext , Calendar . getInstance ( TimeZone . getTimeZone ( ZoneId . of ( tableJdbcConfigBean . timeZoneID ) ) ) ) ; tableReadContext = tableReadContextCache . get ( tableRuntimeContext ) ; //Record query time lastQueryIntervalTime = System . currentTimeMillis ( ) ; } return tableReadContext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the file offsets to use for the next read . To work correctly the last return offsets should be used or an empty <code > Map< / code > if there is none . <p / > If a reader is already live the corresponding set offset is ignored as we cache all the contextual information of live readers . [CODESPLIT] @ Override public void setOffsets ( Map < String , String > offsets ) throws IOException { Utils . checkNotNull ( offsets , \"offsets\" ) ; // retrieve file:offset for each directory for ( FileContext fileContext : fileContexts ) { String offset = offsets . get ( fileContext . getMultiFileInfo ( ) . getFileKey ( ) ) ; LiveFile file = null ; long fileOffset = 0 ; if ( offset != null && ! offset . isEmpty ( ) ) { file = FileContextProviderUtil . getRefreshedLiveFileFromFileOffset ( offset ) ; fileOffset = FileContextProviderUtil . getLongOffsetFromFileOffset ( offset ) ; } fileContext . setStartingCurrentFileName ( file ) ; fileContext . setStartingOffset ( fileOffset ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"Setting offset: directory '{}', file '{}', offset '{}'\" , fileContext . getMultiFileInfo ( ) . getFileFullPath ( ) , file , fileOffset ) ; } } currentIdx = startingIdx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse date in RFC 5424 format . Uses an LRU cache to speed up parsing for multiple messages that occur in the same second . [CODESPLIT] public static long parseRfc5424Date ( LoadingCache < String , Long > cache , String tsStr ) throws OnRecordErrorException { boolean includesTimezone = true ; long ts ; int curPos = 0 ; int msgLen = tsStr . length ( ) ; if ( msgLen <= RFC5424_PREFIX_LEN ) { throw new OnRecordErrorException ( Errors . SYSLOG_09 , tsStr ) ; } String timestampPrefix = tsStr . substring ( curPos , RFC5424_PREFIX_LEN ) ; try { ts = cache . get ( timestampPrefix ) ; } catch ( ExecutionException ex ) { Throwable cause = Throwables . getRootCause ( ex ) ; if ( cause instanceof IllegalArgumentException ) { throw new OnRecordErrorException ( Errors . SYSLOG_05 , cause , timestampPrefix , cause ) ; } else { // I don't believe this will ever occur throw new IllegalStateException ( Utils . format ( Errors . SYSLOG_05 . getMessage ( ) , cause , timestampPrefix ) , cause ) ; } } curPos += RFC5424_PREFIX_LEN ; // look for the optional fractional seconds if ( tsStr . charAt ( curPos ) == ' ' ) { // figure out how many numeric digits boolean foundEnd = false ; int endMillisPos = curPos + 1 ; if ( msgLen <= endMillisPos ) { throw new OnRecordErrorException ( Errors . SYSLOG_06 , tsStr ) ; } // FIXME: TODO: ensure we handle all bad formatting cases while ( ! foundEnd && endMillisPos < msgLen ) { char curDigit = tsStr . charAt ( endMillisPos ) ; if ( curDigit >= ' ' && curDigit <= ' ' ) { endMillisPos ++ ; } else { foundEnd = true ; } } includesTimezone = foundEnd ; if ( ! includesTimezone ) { endMillisPos -- ; } // if they had a valid fractional second, append it rounded to millis final int fractionalPositions = endMillisPos - ( curPos + 1 ) ; if ( fractionalPositions > 0 ) { long milliseconds = Long . parseLong ( tsStr . substring ( curPos + 1 , endMillisPos ) ) ; if ( fractionalPositions > 3 ) { milliseconds /= Math . pow ( 10 , ( fractionalPositions - 3 ) ) ; } else if ( fractionalPositions < 3 ) { milliseconds *= Math . pow ( 10 , ( 3 - fractionalPositions ) ) ; } ts += milliseconds ; } else { throw new OnRecordErrorException ( Errors . SYSLOG_07 , tsStr ) ; } curPos = endMillisPos ; } // look for timezone if ( includesTimezone ) { char tzFirst = tsStr . charAt ( curPos ) ; // UTC if ( tzFirst == ' ' ) { // no-op } else if ( tzFirst == ' ' || tzFirst == ' ' ) { if ( msgLen <= curPos + 5 ) { throw new OnRecordErrorException ( Errors . SYSLOG_08 , tsStr ) ; } int polarity ; if ( tzFirst == ' ' ) { polarity = + 1 ; } else { polarity = - 1 ; } char [ ] h = new char [ 5 ] ; for ( int i = 0 ; i < 5 ; i ++ ) { h [ i ] = tsStr . charAt ( curPos + 1 + i ) ; } if ( h [ 0 ] >= ' ' && h [ 0 ] <= ' ' && h [ 1 ] >= ' ' && h [ 1 ] <= ' ' && h [ 2 ] == ' ' && h [ 3 ] >= ' ' && h [ 3 ] <= ' ' && h [ 4 ] >= ' ' && h [ 4 ] <= ' ' ) { try { int hourOffset = Integer . parseInt ( tsStr . substring ( curPos + 1 , curPos + 3 ) ) ; int minOffset = Integer . parseInt ( tsStr . substring ( curPos + 4 , curPos + 6 ) ) ; ts -= polarity * ( ( hourOffset * 60L ) + minOffset ) * 60000L ; } catch ( NumberFormatException nfe ) { throw new OnRecordErrorException ( Errors . SYSLOG_08 , tsStr , nfe ) ; } } else { throw new OnRecordErrorException ( Errors . SYSLOG_08 , tsStr ) ; } } } return ts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the RFC3164 date format . This is trickier than it sounds because this format does not specify a year so we get weird edge cases at year boundaries . This implementation tries to do what I mean . [CODESPLIT] public static long parseRfc3164Time ( String ts ) throws OnRecordErrorException { LocalDateTime now = LocalDateTime . now ( ) ; int year = now . getYear ( ) ; ts = TWO_SPACES . matcher ( ts ) . replaceFirst ( \" \" ) ; LocalDateTime date ; try { MonthDay monthDay = MonthDay . parse ( ts , rfc3164Format ) ; LocalTime time = LocalTime . parse ( ts , rfc3164Format ) ; // this is overly complicated because of the way Java 8 Time API works, as compared to Joda // essentially, we just want to pull year out of \"now\" and set all other fields based on // what was parsed date = now ; // zero out millis since we aren't actually parsing those date = date . with ( ChronoField . MILLI_OF_SECOND , 0 ) ; // set month and day of month from parsed date = date . withMonth ( monthDay . getMonthValue ( ) ) . withDayOfMonth ( monthDay . getDayOfMonth ( ) ) ; // set time fields from parsed date = date . withHour ( time . getHour ( ) ) . withMinute ( time . getMinute ( ) ) . withSecond ( time . getSecond ( ) ) ; } catch ( DateTimeParseException e ) { throw new OnRecordErrorException ( Errors . SYSLOG_10 , ts , e ) ; } // The RFC3164 is a bit weird date format - it contains day and month, but no year. So we have to somehow guess // the year. The current logic is to provide a sliding window - going 11 months to the past and 1 month to the // future. If the message is outside of this window, it will have incorrectly guessed year. We go 11 months to the // past as we're expecting that more messages will be from the past (syslog usually contains historical data). LocalDateTime fixed = date ; if ( fixed . isAfter ( now ) && fixed . minusMonths ( 1 ) . isAfter ( now ) ) { fixed = date . withYear ( year - 1 ) ; } else if ( fixed . isBefore ( now ) && fixed . plusMonths ( 11 ) . isBefore ( now ) ) { fixed = date . withYear ( year + 1 ) ; } date = fixed ; return date . toInstant ( ZoneOffset . UTC ) . toEpochMilli ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Puts the current thread to sleep for the specified number of milliseconds . < / p > <p > If the thread was interrupted before the sleep method is called the sleep method wont sleep . < / p > @param milliseconds number of milliseconds to sleep . [CODESPLIT] public static boolean sleep ( long milliseconds ) { //checking if we got pre-interrupted. boolean interrupted = Thread . interrupted ( ) ; if ( ! interrupted ) { try { Thread . sleep ( milliseconds ) ; } catch ( InterruptedException ex ) { interrupted = true ; // clearing the interrupt flag Thread . interrupted ( ) ; } } return ! interrupted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "no escaping is supported no array content printing either . [CODESPLIT] public static String format ( String template , Object ... args ) { String [ ] templateArr = TEMPLATES . get ( template ) ; if ( templateArr == null ) { // we may have a race condition here but the end result is idempotent templateArr = prepareTemplate ( template ) ; TEMPLATES . put ( template , templateArr ) ; } StringBuilder sb = new StringBuilder ( template . length ( ) * 2 ) ; for ( int i = 0 ; i < templateArr . length ; i ++ ) { sb . append ( templateArr [ i ] ) ; if ( args != null && ( i < templateArr . length - 1 ) ) { sb . append ( ( i < args . length ) ? args [ i ] : TOKEN ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes the <code > LiveFile< / code > as a string . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public String serialize ( ) { Map map = new LinkedHashMap ( ) ; map . put ( \"path\" , path . toString ( ) ) ; map . put ( \"headHash\" , headHash ) ; map . put ( \"headLen\" , headLen ) ; map . put ( \"inode\" , iNode ) ; try { JsonMapper objectMapper = DataCollectorServices . instance ( ) . get ( JsonMapper . SERVICE_KEY ) ; return objectMapper . writeValueAsString ( map ) ; } catch ( Exception ex ) { throw new RuntimeException ( Utils . format ( \"Unexpected exception: {}\" , ex . toString ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserializes a string representation of a <code > LiveFile< / code > . <p / > [CODESPLIT] public static LiveFile deserialize ( String str ) throws IOException { Utils . checkNotNull ( str , \"str\" ) ; try { JsonMapper objectMapper = DataCollectorServices . instance ( ) . get ( JsonMapper . SERVICE_KEY ) ; Map map = objectMapper . readValue ( str , Map . class ) ; Path path = Paths . get ( ( String ) map . get ( \"path\" ) ) ; String headHash = ( map . containsKey ( \"headHash\" ) ) ? ( String ) map . get ( \"headHash\" ) : \"\" ; int headLen = ( map . containsKey ( \"headLen\" ) ) ? ( int ) map . get ( \"headLen\" ) : 0 ; String inode = ( String ) map . get ( \"inode\" ) ; return new LiveFile ( path , inode , headHash , headLen ) ; } catch ( RuntimeException | IOException ex ) { throw new IllegalArgumentException ( Utils . format ( \"Invalid LiveFile serialized string '{}': {}\" , str , ex . toString ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refreshes the <code > LiveFile< / code > if the file was renamed the path will have the new name . [CODESPLIT] public LiveFile refresh ( ) throws IOException { LiveFile refresh = this ; boolean changed ; try { BasicFileAttributes attrs = Files . readAttributes ( path , BasicFileAttributes . class ) ; String iNodeCurrent = attrs . fileKey ( ) . toString ( ) ; int headLenCurrent = ( int ) Math . min ( headLen , attrs . size ( ) ) ; String headHashCurrent = computeHash ( path , headLenCurrent ) ; changed = ! this . iNode . equals ( iNodeCurrent ) || ! this . headHash . equals ( headHashCurrent ) ; } catch ( NoSuchFileException ex ) { changed = true ; } if ( changed ) { try ( DirectoryStream < Path > directoryStream = Files . newDirectoryStream ( path . getParent ( ) ) ) { for ( Path path : directoryStream ) { BasicFileAttributes attrs = Files . readAttributes ( path , BasicFileAttributes . class ) ; String iNode = attrs . fileKey ( ) . toString ( ) ; int headLen = ( int ) Math . min ( this . headLen , attrs . size ( ) ) ; String headHash = computeHash ( path , headLen ) ; if ( iNode . equals ( this . iNode ) && headHash . equals ( this . headHash ) ) { if ( headLen == 0 ) { headLen = ( int ) Math . min ( HEAD_LEN , attrs . size ( ) ) ; headHash = computeHash ( path , headLen ) ; } refresh = new LiveFile ( path , iNode , headHash , headLen ) ; break ; } } } } return refresh ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { // Validate configuration values and open any required resources. List < ConfigIssue > issues = super . init ( ) ; errorRecordHandler = new DefaultErrorRecordHandler ( getContext ( ) ) ; Processor . Context context = getContext ( ) ; issues = hikariConfigBean . validateConfigs ( context , issues ) ; if ( hikariConfigBean . getConnectionString ( ) . toLowerCase ( ) . startsWith ( \"jdbc:sqlserver\" ) && useMultiRowOp ) { issues . add ( getContext ( ) . createConfigIssue ( Groups . JDBC . name ( ) , MULTI_ROW_OP , JdbcErrors . JDBC_57 ) ) ; } if ( dynamicTableName ) { tableNameVars = getContext ( ) . createELVars ( ) ; tableNameEval = context . createELEval ( JdbcUtil . TABLE_NAME ) ; ELUtils . validateExpression ( tableNameTemplate , getContext ( ) , Groups . JDBC . getLabel ( ) , JdbcUtil . TABLE_NAME , JdbcErrors . JDBC_26 , issues ) ; } if ( issues . isEmpty ( ) && null == dataSource ) { try { dataSource = jdbcUtil . createDataSourceForWrite ( hikariConfigBean , schema , tableNameTemplate , caseSensitive , issues , customMappings , getContext ( ) ) ; } catch ( RuntimeException | SQLException | StageException e ) { LOG . debug ( \"Could not connect to data source\" , e ) ; issues . add ( getContext ( ) . createConfigIssue ( Groups . JDBC . name ( ) , CONNECTION_STRING , JdbcErrors . JDBC_00 , e . toString ( ) ) ) ; } } // If issues is not empty, the UI will inform the user of each configuration issue in the list. return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( Batch batch , SingleLaneBatchMaker batchMaker ) throws StageException { if ( ! batch . getRecords ( ) . hasNext ( ) ) { // No records - take the opportunity to clean up the cache so that we don't hold on to memory indefinitely cacheCleaner . periodicCleanUp ( ) ; } boolean perRecord = false ; // MS SQL Server does not support returning generateKey after executeBatch // Instead of executeBatch, do executeUpdate per record if ( hikariConfigBean . getConnectionString ( ) . toLowerCase ( ) . startsWith ( \"jdbc:sqlserver\" ) ) { perRecord = true ; } if ( dynamicTableName ) { jdbcUtil . write ( batch , tableNameEval , tableNameVars , tableNameTemplate , recordWriters , errorRecordHandler , perRecord ) ; } else { jdbcUtil . write ( batch . getRecords ( ) , tableNameTemplate , recordWriters , errorRecordHandler , perRecord ) ; } Iterator < Record > it = batch . getRecords ( ) ; while ( it . hasNext ( ) ) { batchMaker . addRecord ( it . next ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is used by destination which performs CRUD operations . Records sent from MongoOpLog origin have / o field that contains a map of key - value for INSERT and DELETE operation but UPDATE record has / o2 field which contains _id and / o / $set field which contains a map of key - value to update . This method looks into the right field path for UPDATE so that users don t need a separate field - column mapping for UPDATE . [CODESPLIT] @ Override public String getFieldPath ( String fieldPath , int operation ) { if ( operation == OperationType . UPDATE_CODE ) { if ( fieldPath . contains ( ID_FIELD ) ) { // _id is stored in \"/o2/column_name for update records. Need to change the fieldpath\" return fieldPath . replace ( OP_FIELD , OP2_FIELD ) ; } else { // column and values are stored in \"/o/$set/column_name\". Need to change the fieldpath return fieldPath . replaceFirst ( OP_FIELD , String . format ( \"%s/%s\" , OP_FIELD , SET_FIELD ) ) ; } } return fieldPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For all PushSource callbacks we have to make sure that we get back to a security context of SDC container module otherwise we won t be able to update state files with new offsets and other stuff . [CODESPLIT] @ Override public final BatchContext startBatch ( ) { return ( BatchContext ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { try { Thread . currentThread ( ) . setContextClassLoader ( mainClassLoader ) ; return pushSourceContextDelegate . startBatch ( ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( getDefinition ( ) . getStageClassLoader ( ) ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses an HttpSourceOffset from a string e . g . from lastSourceOffset in { [CODESPLIT] static HttpSourceOffset fromString ( String s ) { LOG . debug ( \"Parsing HttpSourceOffset from '{}'\" , s ) ; String [ ] parts = s . split ( \"::\" ) ; if ( parts . length < 8 ) { throw new IllegalArgumentException ( \"Offset must have at least 8 parts\" ) ; } return new HttpSourceOffset ( parts [ 1 ] , parts [ 3 ] , Long . parseLong ( parts [ 5 ] ) , Integer . parseInt ( parts [ 7 ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the parameters for this config bean . [CODESPLIT] public void init ( Stage . Context context , String prefix , List < Stage . ConfigIssue > issues ) { underlyingConfig = new TlsConfigBean ( ) ; underlyingConfig . tlsEnabled = true ; if ( useMutualAuth ) { underlyingConfig . keyStorePassword = keyStorePassword ; underlyingConfig . keyStoreFilePath = keyStoreFilePath ; underlyingConfig . keyStoreAlgorithm = keyStoreAlgorithm ; underlyingConfig . keyStoreType = keyStoreType ; underlyingConfig . init ( context , \"TLS\" , prefix , issues ) ; LOG . debug ( \"Initialized Mutual Authentication config with {} keystore file {}\" , underlyingConfig . keyStoreType , underlyingConfig . keyStoreFilePath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the record contains solr fields in solrFieldsMap or not . [CODESPLIT] private boolean checkRecordContainsSolrFields ( Map < String , Field > recordFieldMap , Record record , List < String > solrFieldsMap , Errors errorToThrow ) throws StageException { // for (Map.Entry<String, Field> recordFieldMapEntry : recordFieldMap.entrySet()) List < String > fieldsFound = new ArrayList <> ( ) ; recordFieldMap . keySet ( ) . forEach ( recordFieldKey -> { if ( solrFieldsMap . contains ( recordFieldKey ) ) { fieldsFound . add ( recordFieldKey ) ; } } ) ; // if record does not contain solr fields then process error accordingly if ( solrFieldsMap . size ( ) != fieldsFound . size ( ) ) { Set < String > missingFields = new HashSet <> ( ) ; solrFieldsMap . forEach ( requiredField -> { if ( ! fieldsFound . contains ( requiredField ) ) { missingFields . add ( requiredField ) ; } } ) ; handleError ( record , errorToThrow , Joiner . on ( \",\" ) . join ( missingFields ) ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter auto - generated fields from the list passed as argument . [CODESPLIT] private List < String > filterAutogeneratedFieldNames ( List < String > fieldNames ) { List < String > result = new ArrayList <> ( ) ; fieldNames . forEach ( name -> { if ( ! autogeneratedFieldNamesMap . contains ( name ) ) { result . add ( name ) ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that the list of mappings in { @code mappings } covers all the fields in { @code solrFields } . [CODESPLIT] private List < String > checkMissingFields ( List < SolrFieldMappingConfig > mappings , List < String > solrFields ) { List < String > missingFields = new ArrayList <> ( solrFields ) ; for ( SolrFieldMappingConfig map : mappings ) { missingFields . remove ( map . solrFieldName ) ; } return missingFields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles an error that occurred when processing a record . The error can either be logged or thrown in an exception . [CODESPLIT] private void handleError ( Record record , Errors errorTemplate , String errorMessage ) throws StageException { handleError ( record , errorTemplate , new String [ ] { errorMessage } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles an error that occurred when processing a record . The error can either be logged or thrown in an exception . [CODESPLIT] private void handleError ( Record record , Errors errorTemplate , String ... errorArguments ) throws StageException { switch ( missingFieldAction ) { case DISCARD : LOG . debug ( errorTemplate . getMessage ( ) , errorArguments ) ; break ; case STOP_PIPELINE : throw new StageException ( errorTemplate , errorArguments ) ; case TO_ERROR : throw new OnRecordErrorException ( record , errorTemplate , errorArguments ) ; default : //unknown operation LOG . debug ( \"Sending record to error due to unknown operation {}\" , missingFieldAction ) ; throw new OnRecordErrorException ( record , errorTemplate , errorArguments ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send exception ex to errorRecordHandler in order to let the handler process it . [CODESPLIT] private void sendOnRecordErrorExceptionToHandler ( Record record , Errors error , StageException ex ) throws StageException { errorRecordHandler . onError ( new OnRecordErrorException ( record , error , record . getHeader ( ) . getSourceId ( ) , ex . toString ( ) , ex ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate dependency from a jar file name . [CODESPLIT] public static Optional < Dependency > parseJarName ( String sourceName , String jarName ) { if ( SPECIAL_CASES . containsKey ( jarName ) ) { Dependency specialCase = SPECIAL_CASES . get ( jarName ) ; return Optional . of ( new Dependency ( sourceName , specialCase . getName ( ) , specialCase . getVersion ( ) ) ) ; } // Go over all known patterns for ( Pattern p : PATTERNS ) { Matcher m = p . matcher ( jarName ) ; if ( m . matches ( ) ) { LOG . trace ( \"Applied pattern '{}' to {}\" , p . pattern ( ) , jarName ) ; return Optional . of ( new Dependency ( sourceName , m . group ( 1 ) , m . group ( 2 ) ) ) ; } } // Otherwise this jar name is unknown to us return Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate dependency from a URL . [CODESPLIT] public static Optional < Dependency > parseURL ( URL url ) { return parseJarName ( url . toString ( ) , Paths . get ( url . getPath ( ) ) . getFileName ( ) . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maintains a singleton instance of the CouchbaseConnector object per pipeline [CODESPLIT] public static synchronized CouchbaseConnector getInstance ( BaseCouchbaseConfig config , List < Stage . ConfigIssue > issues , Stage . Context context ) { Map < String , Object > runnerSharedMap = context . getStageRunnerSharedMap ( ) ; if ( runnerSharedMap . containsKey ( INSTANCE ) ) { LOG . debug ( \"Using existing instance of CouchbaseConnector\" ) ; } else { LOG . debug ( \"CouchbaseConnector not yet instantiated. Creating new instance\" ) ; validateConfig ( config , issues , context ) ; if ( issues . isEmpty ( ) ) { runnerSharedMap . put ( INSTANCE , new CouchbaseConnector ( config , issues , context ) ) ; } } return ( CouchbaseConnector ) runnerSharedMap . get ( INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disconnects from Couchbase and releases all resources [CODESPLIT] public synchronized void close ( ) { if ( ! isClosed ) { if ( bucket != null ) { LOG . debug ( \"Closing Couchbase bucket\" ) ; bucket . close ( ) ; } if ( cluster != null ) { LOG . debug ( \"Disconnecting Couchbase cluster\" ) ; cluster . disconnect ( ) ; } if ( env != null ) { LOG . debug ( \"Shutting down Couchbase environment\" ) ; env . shutdown ( ) ; } // Explicitly shutdown the RxJava scheduler threads. Not doing so will leak threads when a pipeline stops. // Note: this disallows restarting scheduler threads without also explicitly calling Schedulers.start() // LOG.debug(\"Stopping RxJava schedulers\"); // Schedulers.shutdown(); isClosed = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates connection configurations that don t require runtime exception handling [CODESPLIT] private static void validateConfig ( BaseCouchbaseConfig config , List < Stage . ConfigIssue > issues , Stage . Context context ) { if ( config . couchbase . nodes == null ) { issues . add ( context . createConfigIssue ( Groups . COUCHBASE . name ( ) , \"config.couchbase.nodes\" , Errors . COUCHBASE_29 ) ) ; } if ( config . couchbase . kvTimeout < 0 ) { issues . add ( context . createConfigIssue ( Groups . COUCHBASE . name ( ) , \"config.couchbase.kvTimeout\" , Errors . COUCHBASE_30 ) ) ; } if ( config . couchbase . connectTimeout < 0 ) { issues . add ( context . createConfigIssue ( Groups . COUCHBASE . name ( ) , \"config.couchbase.connectTimeout\" , Errors . COUCHBASE_31 ) ) ; } if ( config . couchbase . disconnectTimeout < 0 ) { issues . add ( context . createConfigIssue ( Groups . COUCHBASE . name ( ) , \"config.couchbase.disconnectTimeout\" , Errors . COUCHBASE_32 ) ) ; } if ( config . couchbase . tls . tlsEnabled ) { config . couchbase . tls . init ( context , Groups . COUCHBASE . name ( ) , \"config.couchbase.tls.\" , issues ) ; } if ( config . credentials . version == null ) { issues . add ( context . createConfigIssue ( Groups . CREDENTIALS . name ( ) , \"config.credentials.version\" , Errors . COUCHBASE_33 ) ) ; } if ( config . credentials . version == AuthenticationType . USER ) { if ( config . credentials . userName == null ) { issues . add ( context . createConfigIssue ( Groups . CREDENTIALS . name ( ) , \"config.credentials.userName\" , Errors . COUCHBASE_34 ) ) ; } if ( config . credentials . userPassword == null ) { issues . add ( context . createConfigIssue ( Groups . CREDENTIALS . name ( ) , \"config.credentials.userPassword\" , Errors . COUCHBASE_35 ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String produce ( String lastSourceOffset , int maxBatchSize , BatchMaker batchMaker ) throws StageException { // Offsets can vary depending on the data source. Here we use an integer as an example only. long nextSourceOffset = 0 ; lastSourceOffset = lastSourceOffset == null ? \"\" : lastSourceOffset ; if ( ! lastSourceOffset . equals ( \"\" ) ) { nextSourceOffset = Long . parseLong ( lastSourceOffset ) ; } int recordCounter = 0 ; long startTime = System . currentTimeMillis ( ) ; int maxRecords = Math . min ( maxBatchSize , conf . maxBatchSize ) ; while ( recordCounter < maxRecords && ( startTime + conf . maxWaitTime ) > System . currentTimeMillis ( ) ) { String message = buffer . poll ( ) ; if ( null == message ) { try { Thread . sleep ( 100 ) ; } catch ( Exception e ) { LOG . debug ( e . getMessage ( ) , e ) ; break ; } } else { List < Record > records = processRedisMessage ( \"id::\" + nextSourceOffset , message ) ; for ( Record record : records ) { batchMaker . addRecord ( record ) ; } recordCounter += records . size ( ) ; ++ nextSourceOffset ; } } return lastSourceOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert from code in String type to label [CODESPLIT] public static String getLabelFromStringCode ( String code ) throws NumberFormatException { try { int intCode = Integer . parseInt ( code ) ; return getLabelFromIntCode ( intCode ) ; } catch ( NumberFormatException ex ) { throw new NumberFormatException ( String . format ( \"%s but received '%s'\" , \"operation code must be numeric\" , code ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verify that the config definition s dependency actually maps to a valid config definition [CODESPLIT] private void verifyDependencyExists ( Map < String , ConfigDefinition > definitionsMap , ConfigDefinition def , String dependsOnKey , Object contextMsg ) { Preconditions . checkState ( definitionsMap . containsKey ( dependsOnKey ) , Utils . format ( \"Error while processing {} ConfigDef='{}'. Dependency='{}' does not exist.\" , contextMsg , def . getName ( ) , dependsOnKey ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if child creates a dependency with any member ( s ) of dependencyAncestors . Also adds the stringified cycle to the cycles list [CODESPLIT] private boolean detectCycle ( LinkedHashSet < String > dependencyAncestors , Set < String > cycles , final String child ) { if ( dependencyAncestors . contains ( child ) ) { // Find index of the child in the ancestors list int index = - 1 ; for ( String s : dependencyAncestors ) { index ++ ; if ( s . equals ( child ) ) { break ; } } // The cycle starts from the first time the child is seen in the ancestors list // and continues till the end of the list, followed by the child again. cycles . add ( Joiner . on ( \" -> \" ) . join ( Iterables . skip ( dependencyAncestors , index ) ) + \" -> \" + child ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing [CODESPLIT] AWSCredentialsProvider createCredentialsProvider ( ) throws StageException { String accessKey = credentialConfigs . getAccessKey ( ) . get ( ) ; String secretKey = credentialConfigs . getSecretKey ( ) . get ( ) ; if ( accessKey != null && ! accessKey . isEmpty ( ) && secretKey != null && ! secretKey . isEmpty ( ) ) { return new AWSStaticCredentialsProvider ( new BasicAWSCredentials ( credentialConfigs . getAccessKey ( ) . get ( ) , credentialConfigs . getSecretKey ( ) . get ( ) ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing [CODESPLIT] ClientConfiguration createClientConfiguration ( ) throws StageException { ClientConfiguration clientConfig = new ClientConfiguration ( ) ; clientConfig . setConnectionTimeout ( connectionConfigs . getConnectionTimeoutMillis ( ) ) ; clientConfig . setSocketTimeout ( connectionConfigs . getSocketTimeoutMillis ( ) ) ; clientConfig . withMaxErrorRetry ( connectionConfigs . getMaxErrorRetry ( ) ) ; if ( connectionConfigs . isProxyEnabled ( ) ) { clientConfig . setProxyHost ( connectionConfigs . getProxyHost ( ) ) ; clientConfig . setProxyPort ( connectionConfigs . getProxyPort ( ) ) ; if ( connectionConfigs . isProxyAuthenticationEnabled ( ) ) { clientConfig . setProxyUsername ( connectionConfigs . getProxyUser ( ) . get ( ) ) ; clientConfig . setProxyPassword ( connectionConfigs . getProxyPassword ( ) . get ( ) ) ; } } return clientConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing [CODESPLIT] AmazonS3Client createS3Client ( ) throws StageException { AmazonS3ClientBuilder builder = createAmazonS3ClientBuilder ( ) . withClientConfiguration ( createClientConfiguration ( ) ) . withChunkedEncodingDisabled ( connectionConfigs . isChunkedEncodingEnabled ( ) ) . withPathStyleAccessEnabled ( true ) ; AWSCredentialsProvider awsCredentialsProvider = getCredentialsProvider ( ) ; // If we don't call build.withCredentials(...) then we will not overwrite the default credentials provider // already set in the builder when doing AmazonS3ClientBuilder.standard() so only calling build.withCredentials(...) // if our own provider exists if ( awsCredentialsProvider != null ) { builder . withCredentials ( awsCredentialsProvider ) ; } String region = ( connectionConfigs . getRegion ( ) == null || connectionConfigs . getRegion ( ) . isEmpty ( ) ) ? null : connectionConfigs . getRegion ( ) ; if ( connectionConfigs . isUseEndpoint ( ) ) { builder . withEndpointConfiguration ( new AwsClientBuilder . EndpointConfiguration ( connectionConfigs . getEndpoint ( ) , region ) ) ; } else if ( region != null ) { builder . withRegion ( connectionConfigs . getRegion ( ) ) ; } else { builder . withRegion ( AwsRegion . US_WEST_1 . getId ( ) ) ; builder . withForceGlobalBucketAccessEnabled ( true ) ; } return ( AmazonS3Client ) builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing [CODESPLIT] TransferManager createTransferManager ( AmazonS3 s3Client ) throws StageException { return createTransferManagerBuilder ( ) . withS3Client ( s3Client ) . withExecutorFactory ( createExecutorFactory ( transferManagerConfigs . getThreads ( ) ) ) . withShutDownThreadPools ( true ) . withMinimumUploadPartSize ( transferManagerConfigs . getMinimumUploadPartSize ( ) ) . withMultipartUploadThreshold ( transferManagerConfigs . getMultipartUploadThreshold ( ) ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The user - id portion of Vault s app - auth should be machine specific and at least somewhat obfuscated to make it more difficult to derive . We use the sha256 hash of the MAC address of the first interface found by InetAddress . getLocalHost () . [CODESPLIT] static String calculateUserId ( String csId ) { try { // Try to hash based on default interface InetAddress ip = InetAddress . getLocalHost ( ) ; NetworkInterface netIf = NetworkInterface . getByInetAddress ( ip ) ; byte [ ] mac = netIf . getHardwareAddress ( ) ; if ( mac == null ) { // In some cases the default interface may be a tap/tun device which has no MAC // instead pick the first available interface. Enumeration < NetworkInterface > netIfs = NetworkInterface . getNetworkInterfaces ( ) ; while ( netIfs . hasMoreElements ( ) && mac == null ) { netIf = netIfs . nextElement ( ) ; mac = netIf . getHardwareAddress ( ) ; } } if ( mac == null ) { throw new IllegalStateException ( \"Could not find network interface with MAC address.\" ) ; } Hasher hasher = HASH_FUNCTION . newHasher ( 6 ) ; // MAC is 6 bytes. return hasher . putBytes ( mac ) . hash ( ) . toString ( ) ; } catch ( IOException e ) { LOG . error ( \"CredentialStore '{}' Vault, could not compute Vault user-id: '{}'\" , csId , e ) ; throw new VaultRuntimeException ( \"Could not compute Vault user-id: \" + e . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a secret from the local cache if it hasn t expired and returns the value for the specified key . If the secret isn t cached or has expired it requests it from Vault again . [CODESPLIT] public String read ( String path , String key , long delay ) { if ( ! secrets . containsKey ( path ) ) { VaultClient vault = new VaultClient ( getConfig ( ) ) ; Secret secret ; try { secret = vault . logical ( ) . read ( path ) ; } catch ( VaultException e ) { LOG . error ( e . toString ( ) , e ) ; throw new VaultRuntimeException ( e . toString ( ) ) ; } // Record the expiration date of this lease String leaseId ; if ( secret . isRenewable ( ) ) { // Only renewable secrets seem to have a leaseId leaseId = secret . getLeaseId ( ) ; } else { // So for non-renewable secrets we'll store the path with an extra / so that we can purge them correctly. leaseId = path + \"/\" ; } leases . put ( leaseId , System . currentTimeMillis ( ) + ( secret . getLeaseDuration ( ) * 1000 ) ) ; secrets . put ( path , secret ) ; try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } Map < String , Object > data = secrets . get ( path ) . getData ( ) ; String value = getSecretValue ( data , key ) . orElseThrow ( ( ) -> new VaultRuntimeException ( \"Value not found for key\" ) ) ; LOG . trace ( \"CredentialStore '{}' Vault, retrieved value for key '{}'\" , csId , key ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the sdc . operation . type header for a record and returns the equivalent Couchbase write operation type . [CODESPLIT] private WriteOperationType getOperationFromHeader ( Record record , String key ) { String op = record . getHeader ( ) . getAttribute ( OperationType . SDC_OPERATION_TYPE ) ; if ( op == null || op . isEmpty ( ) ) { return config . defaultWriteOperation ; } int opCode ; try { opCode = Integer . parseInt ( op ) ; } catch ( NumberFormatException e ) { LOG . debug ( \"Unparsable CDC operation. Sending record to error.\" ) ; handleError ( record , Errors . COUCHBASE_08 , e ) ; return null ; } switch ( opCode ) { case OperationType . INSERT_CODE : return WriteOperationType . INSERT ; case OperationType . UPDATE_CODE : return WriteOperationType . REPLACE ; case OperationType . UPSERT_CODE : return WriteOperationType . UPSERT ; case OperationType . DELETE_CODE : return WriteOperationType . DELETE ; default : switch ( config . unsupportedOperation ) { case DISCARD : LOG . debug ( \"Unsupported CDC operation for key: {}. Discarding record per configuration.\" , key ) ; return null ; case TOERROR : LOG . debug ( \"Unsupported CDC operation for key: {}. Sending record to error configuration.\" , key ) ; handleError ( record , Errors . COUCHBASE_09 , new RuntimeException ( ) ) ; return null ; default : LOG . debug ( \"Unsupported CDC operation for key: {}. Using default write operation per configuration.\" , key ) ; return config . defaultWriteOperation ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a document write operation . [CODESPLIT] private Observable < AbstractDocument > writeDoc ( String key , int ttl , long cas , ByteArrayOutputStream baos , Record record ) { WriteOperationType opType = getOperationFromHeader ( record , key ) ; if ( opType == null ) { return Observable . empty ( ) ; } AbstractDocument doc ; if ( config . dataFormat == DataFormat . JSON ) { try { doc = JsonDocument . create ( key , ttl , JsonObject . fromJson ( baos . toString ( config . dataFormatConfig . charset ) ) , cas ) ; } catch ( Exception e ) { return handleError ( record , Errors . COUCHBASE_10 , e ) ; } } else { doc = ByteArrayDocument . create ( key , ttl , baos . toByteArray ( ) , cas ) ; } switch ( opType ) { case DELETE : { LOG . debug ( \"DELETE key: {}, TTL: {}, CAS: {}\" , key , ttl , cas ) ; return connector . bucket ( ) . remove ( doc , config . persistTo , config . replicateTo ) . timeout ( config . couchbase . kvTimeout , TimeUnit . MILLISECONDS ) ; } case INSERT : { LOG . debug ( \"INSERT key: {}, TTL: {}, CAS: {}\" , key , ttl , cas ) ; return connector . bucket ( ) . insert ( doc , config . persistTo , config . replicateTo ) . timeout ( config . couchbase . kvTimeout , TimeUnit . MILLISECONDS ) ; } case REPLACE : { LOG . debug ( \"REPLACE key: {}, TTL: {}, CAS: {}\" , key , ttl , cas ) ; return connector . bucket ( ) . replace ( doc , config . persistTo , config . replicateTo ) . timeout ( config . couchbase . kvTimeout , TimeUnit . MILLISECONDS ) ; } case UPSERT : { LOG . debug ( \"UPSERT key: {}, TTL: {}, CAS: {}\" , key , ttl , cas ) ; return connector . bucket ( ) . upsert ( doc , config . persistTo , config . replicateTo ) . timeout ( config . couchbase . kvTimeout , TimeUnit . MILLISECONDS ) ; } default : return Observable . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a sub - document write operation . [CODESPLIT] private Observable < DocumentFragment < Mutation > > writeSubdoc ( String key , int ttl , long cas , ByteArrayOutputStream baos , String subdocPath , Record record ) { JsonObject frag ; try { frag = JsonObject . fromJson ( baos . toString ( config . dataFormatConfig . charset ) ) ; } catch ( IOException e ) { return handleError ( record , Errors . COUCHBASE_12 , e ) ; } AsyncMutateInBuilder mutation = connector . bucket ( ) . mutateIn ( key ) ; SubdocOptionsBuilder options = new SubdocOptionsBuilder ( ) . createPath ( true ) ; String subdocOpType ; try { subdocOpType = subdocOperationELEval . eval ( elVars , config . subdocOperationEL , String . class ) ; } catch ( ELEvalException e ) { return handleError ( record , Errors . COUCHBASE_13 , e ) ; } if ( config . allowSubdoc && ! subdocOpType . isEmpty ( ) ) { switch ( subdocOpType . toUpperCase ( ) ) { case \"DELETE\" : LOG . debug ( \"Sub-document DELETE key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . remove ( subdocPath , options ) , ttl , cas , false ) ; case \"INSERT\" : LOG . debug ( \"Sub-document INSERT key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . insert ( subdocPath , frag , options ) , ttl , cas , true ) ; case \"REPLACE\" : LOG . debug ( \"Sub-document REPLACE key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . replace ( subdocPath , frag ) , ttl , cas , false ) ; case \"UPSERT\" : LOG . debug ( \"Sub-document UPSERT key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . upsert ( subdocPath , frag , options ) , ttl , cas , true ) ; case \"ARRAY_PREPEND\" : LOG . debug ( \"Sub-document ARRAY_PREPEND key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . arrayPrepend ( subdocPath , frag , options ) , ttl , cas , true ) ; case \"ARRAY_APPEND\" : LOG . debug ( \"Sub-document ARRAY_APPEND key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . arrayAppend ( subdocPath , frag , options ) , ttl , cas , true ) ; case \"ARRAY_ADD_UNIQUE\" : LOG . debug ( \"Sub-document ARRAY_ADD_UNIQUE key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . arrayAddUnique ( subdocPath , frag , options ) , ttl , cas , true ) ; default : switch ( config . unsupportedOperation ) { case DISCARD : LOG . debug ( \"Unsupported sub-document operation: {} for key: {}. Discarding record per configuration.\" , subdocOpType , key ) ; return Observable . empty ( ) ; case TOERROR : LOG . debug ( \"Unsupported sub-document operation: {} for key: {}. Sending record to error per configuration.\" , subdocOpType , key ) ; return handleError ( record , Errors . COUCHBASE_14 , new RuntimeException ( ) ) ; default : LOG . debug ( \"Unsupported sub-document operation: {} for key: {}. Using default write operation per configuration.\" , subdocOpType , key ) ; // Fall through // Inherit the CDC or default operation } } } WriteOperationType opType = getOperationFromHeader ( record , key ) ; if ( opType == null ) { return Observable . empty ( ) ; } switch ( opType ) { case DELETE : LOG . debug ( \"Sub-document DELETE key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . remove ( subdocPath , options ) , ttl , cas , false ) ; case INSERT : LOG . debug ( \"Sub-document INSERT key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . insert ( subdocPath , frag , options ) , ttl , cas , true ) ; case REPLACE : LOG . debug ( \"Sub-document REPLACE key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . replace ( subdocPath , frag ) , ttl , cas , false ) ; case UPSERT : LOG . debug ( \"Sub-document UPSERT key: {}, sub-document path: {}, TTL: {}, CAS: {}\" , key , subdocPath , ttl , cas ) ; return buildSubdocMutation ( mutation . upsert ( subdocPath , frag , options ) , ttl , cas , true ) ; default : return Observable . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies standard options to sub - document mutations [CODESPLIT] private Observable < DocumentFragment < Mutation > > buildSubdocMutation ( AsyncMutateInBuilder mutation , int ttl , long cas , boolean upsertDoc ) { return mutation . upsertDocument ( upsertDoc ) . withExpiry ( ttl ) . withCas ( cas ) . withDurability ( config . persistTo , config . replicateTo ) . execute ( ) . timeout ( config . couchbase . kvTimeout , TimeUnit . MILLISECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Influenced by javax . security . auth . Subject . #doAs [CODESPLIT] public static < T > T doAs ( Subject subject , PrivilegedExceptionAction < T > privilegedExceptionAction ) throws PrivilegedActionException { checkDoAsPermission ( ) ; if ( privilegedExceptionAction == null ) { throw new RuntimeException ( \"No privileged exception action provided\" ) ; } return AccessController . doPrivileged ( privilegedExceptionAction , createContext ( subject , AccessController . getContext ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Influenced by javax . security . auth . Subject . #doAs [CODESPLIT] public static < T > T doAs ( final Subject subject , final PrivilegedAction < T > privilegedAction ) { checkDoAsPermission ( ) ; if ( privilegedAction == null ) { throw new RuntimeException ( \"No privileged action provided\" ) ; } return AccessController . doPrivileged ( privilegedAction , createContext ( subject , AccessController . getContext ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "because the path is going to be used only once ( because only one record is used ) . [CODESPLIT] @ Override public Path getPath ( FileSystem fs , Date recordDate , Record record ) throws StageException , IOException { //Check whether the real file already exists Path path = new Path ( mgr . getDirPath ( recordDate , record ) , getTempFile ( recordDate , record ) ) ; //this will check the file exists. Path renamableFinalPath = getRenamablePath ( fs , path ) ; updateFsPermissionsIfNeeded ( record ) ; wholeFileEventRecord = createWholeFileEventRecord ( record , renamableFinalPath ) ; return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "H2 wants an ALTER TABLE command per column [CODESPLIT] @ Override protected String makeAlterTableSqlString ( String schema , String tableName , LinkedHashMap < String , JdbcTypeInfo > columnDiff ) { String tableSchema = ( schema == null ) ? getDefaultSchema ( ) : schema ; StringBuilder sqlString = new StringBuilder ( ) ; boolean first = true ; for ( Map . Entry < String , JdbcTypeInfo > entry : columnDiff . entrySet ( ) ) { if ( first ) { first = false ; } else { sqlString . append ( \"\\n\" ) ; } sqlString . append ( ALTER_TABLE ) . append ( \" \" ) ; if ( tableSchema != null ) { sqlString . append ( tableSchema ) ; sqlString . append ( \".\" ) ; } sqlString . append ( tableName ) . append ( \" \" ) . append ( \"ADD COLUMN\" ) . append ( \" \" ) . append ( entry . getKey ( ) ) . append ( \" \" ) . append ( entry . getValue ( ) . toString ( ) ) . append ( \";\" ) ; } return sqlString . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a frame out of the { @link ByteBuf } and return it . [CODESPLIT] protected Object decode ( ChannelHandlerContext ctx , ByteBuf in ) throws Exception { if ( discardingTooLongFrame ) { long bytesToDiscard = this . bytesToDiscard ; int localBytesToDiscard = ( int ) Math . min ( bytesToDiscard , in . readableBytes ( ) ) ; in . skipBytes ( localBytesToDiscard ) ; bytesToDiscard -= localBytesToDiscard ; this . bytesToDiscard = bytesToDiscard ; failIfNecessary ( false ) ; return null ; } if ( consumingLength ) { int delimIndex = indexOf ( in , delimiter ) ; if ( delimIndex < 0 ) { return null ; } final String lengthStr = in . toString ( in . readerIndex ( ) , delimIndex , lengthFieldCharset ) ; try { frameLength = Long . parseLong ( trimLengthString ? lengthStr . trim ( ) : lengthStr ) ; } catch ( NumberFormatException e ) { throw new CorruptedFrameException ( String . format ( \"Invalid length field decoded (in %s charset): %s\" , lengthFieldCharset . name ( ) , lengthStr ) , e ) ; } if ( frameLength < 0 ) { throw new CorruptedFrameException ( \"negative pre-adjustment length field: \" + frameLength ) ; } frameLength += lengthAdjustment ; //consume length field and delimiter bytes in . skipBytes ( delimIndex + delimiter . capacity ( ) ) ; //consume delimiter bytes consumingLength = false ; } if ( frameLength > maxFrameLength ) { long discard = frameLength - in . readableBytes ( ) ; tooLongFrameLength = frameLength ; if ( discard < 0 ) { // buffer contains more bytes then the frameLength so we can discard all now in . skipBytes ( ( int ) frameLength ) ; } else { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true ; consumingLength = true ; bytesToDiscard = discard ; in . skipBytes ( in . readableBytes ( ) ) ; } failIfNecessary ( true ) ; return null ; } // never overflows because it's less than maxFrameLength int frameLengthInt = ( int ) frameLength ; if ( in . readableBytes ( ) < frameLengthInt ) { // need more bytes available to read actual frame return null ; } // the frame is now entirely present, reset state vars consumingLength = true ; frameLength = 0 ; // extract frame int readerIndex = in . readerIndex ( ) ; int actualFrameLength = frameLengthInt ; // - initialBytesToStrip; ByteBuf frame = extractFrame ( ctx , in , readerIndex , actualFrameLength ) ; in . readerIndex ( readerIndex + actualFrameLength ) ; return frame ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the sub - region of the specified buffer . <p > If you are sure that the frame and its content are not accessed after the current { [CODESPLIT] protected ByteBuf extractFrame ( ChannelHandlerContext ctx , ByteBuf buffer , int index , int length ) { return buffer . slice ( index , length ) . retain ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Login constructor . The constructor starts the thread used to periodically re - login to the Kerberos Ticket Granting Server . [CODESPLIT] public void configure ( Map < String , ? > configs , final String loginContextName ) { super . configure ( configs , loginContextName ) ; this . loginContextName = loginContextName ; this . ticketRenewWindowFactor = ( Double ) configs . get ( SaslConfigs . SASL_KERBEROS_TICKET_RENEW_WINDOW_FACTOR ) ; this . ticketRenewJitter = ( Double ) configs . get ( SaslConfigs . SASL_KERBEROS_TICKET_RENEW_JITTER ) ; this . minTimeBeforeRelogin = ( Long ) configs . get ( SaslConfigs . SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN ) ; this . kinitCmd = ( String ) configs . get ( SaslConfigs . SASL_KERBEROS_KINIT_CMD ) ; this . serviceName = getServiceName ( configs , loginContextName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - login a principal . This method assumes that { [CODESPLIT] private synchronized void reLogin ( ) throws LoginException { if ( ! isKrbTicket ) { return ; } if ( loginContext == null ) { throw new LoginException ( \"Login must be done first\" ) ; } if ( ! hasSufficientTimeElapsed ( ) ) { return ; } log . info ( \"Initiating logout for {}\" , principal ) ; synchronized ( KerberosLogin . class ) { // register most recent relogin attempt lastLogin = currentElapsedTime ( ) ; //clear up the kerberos state. But the tokens are not cleared! As per //the Java kerberos login module code, only the kerberos credentials //are cleared loginContext . logout ( ) ; //login and also update the subject field of this instance to //have the new credentials (pass it to the LoginContext constructor) loginContext = new LoginContext ( loginContextName , subject ) ; log . info ( \"Initiating re-login for {}\" , principal ) ; loginContext . login ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether any of the { [CODESPLIT] private void checkWorkerStatus ( ExecutorCompletionService < Future > completionService ) throws StageException { Future future = completionService . poll ( ) ; if ( future != null ) { try { future . get ( ) ; } catch ( InterruptedException e ) { LOG . error ( \"Thread interrupted\" , e ) ; } catch ( ExecutionException e ) { Throwable cause = Throwables . getRootCause ( e ) ; if ( cause != null && cause instanceof StageException ) { throw ( StageException ) cause ; } else { LOG . error ( \"Internal Error\" , e ) ; throw new StageException ( JdbcErrors . JDBC_75 , e . toString ( ) , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes messages off the queue . Returns null when the producer has indicated it is complete and throws an exception when the consumer producer has indicated it is in error . [CODESPLIT] public OffsetAndResult < Map . Entry > take ( ) { if ( producerError != null ) { throw new RuntimeException ( Utils . format ( \"Producer encountered error: {}\" , producerError ) , producerError ) ; } if ( consumerError != null ) { throw new RuntimeException ( Utils . format ( \"Consumer encountered error: {}\" , consumerError ) , consumerError ) ; } try { Utils . checkState ( batchCommitted , \"Cannot take messages when last batch is uncommitted\" ) ; while ( running ) { for ( ControlChannel . Message controlMessage : controlChannel . getConsumerMessages ( ) ) { switch ( controlMessage . getType ( ) ) { case PRODUCER_COMPLETE : // producer is complete, empty channel and afterwards return null running = false ; break ; case PRODUCER_ERROR : running = false ; Throwable throwable = ( Throwable ) controlMessage . getPayload ( ) ; producerError = throwable ; throw new ProducerRuntimeException ( Utils . format ( \"Producer encountered error: {}\" , throwable ) , throwable ) ; default : String msg = Utils . format ( \"Illegal control message type: '{}'\" , controlMessage . getType ( ) ) ; throw new IllegalStateException ( msg ) ; } } OffsetAndResult < Map . Entry > batch = dataChannel . take ( 10 , TimeUnit . MILLISECONDS ) ; LOG . trace ( \"Received batch: {}\" , batch ) ; if ( batch != null ) { batchCommitted = false ; // got a new batch return batch ; } } LOG . trace ( \"Returning null\" ) ; return null ; } catch ( Throwable throwable ) { if ( ! ( throwable instanceof ProducerRuntimeException ) ) { String msg = \"Error caught in consumer: \" + throwable ; LOG . error ( msg , throwable ) ; error ( throwable ) ; } throw Throwables . propagate ( throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commit the offset . Required after take has returned a non - null value . [CODESPLIT] public void commit ( String offset ) { batchCommitted = true ; LOG . trace ( \"Last committed offset '{}', attempting to commit '{}'\" , lastCommittedOffset , offset ) ; Utils . checkState ( null != lastCommittedOffset , \"Last committed offset cannot be null\" ) ; controlChannel . consumerCommit ( offset ) ; lastCommittedOffset = offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a control message indicating the consumer has encountered an error . [CODESPLIT] public void error ( Throwable throwable ) { if ( consumerError == null ) { consumerError = throwable ; controlChannel . consumerError ( throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * t0 = [ SORTED_INTERSECTION ] t1 = [ SORTED_INTERSECTION ] + [ SORTED_REST_OF_STRING1 ] t2 = [ SORTED_INTERSECTION ] + [ SORTED_REST_OF_STRING2 ] [CODESPLIT] public static int getRatio ( String s1 , String s2 ) { if ( s1 . length ( ) >= s2 . length ( ) ) { // We need to swap s1 and s2 String temp = s2 ; s2 = s1 ; s1 = temp ; } // Get alpha numeric characters Set < String > set1 = tokenizeString ( escapeString ( s1 ) ) ; Set < String > set2 = tokenizeString ( escapeString ( s2 ) ) ; SetView < String > intersection = Sets . intersection ( set1 , set2 ) ; TreeSet < String > sortedIntersection = Sets . newTreeSet ( intersection ) ; if ( LOG . isTraceEnabled ( ) ) { StringBuilder sortedSb = new StringBuilder ( ) ; for ( String s : sortedIntersection ) { sortedSb . append ( s ) . append ( \" \" ) ; } LOG . trace ( \"Sorted intersection --> {}\" , sortedSb . toString ( ) ) ; } // Find out difference of sets set1 and intersection of set1,set2 SetView < String > restOfSet1 = Sets . symmetricDifference ( set1 , intersection ) ; // Sort it TreeSet < String > sortedRestOfSet1 = Sets . newTreeSet ( restOfSet1 ) ; SetView < String > restOfSet2 = Sets . symmetricDifference ( set2 , intersection ) ; TreeSet < String > sortedRestOfSet2 = Sets . newTreeSet ( restOfSet2 ) ; if ( LOG . isTraceEnabled ( ) ) { StringBuilder sb1 = new StringBuilder ( ) ; for ( String s : sortedRestOfSet1 ) { sb1 . append ( s ) . append ( \" \" ) ; } LOG . trace ( \"Sorted rest of 1 --> {}\" , sb1 . toString ( ) ) ; StringBuilder sb2 = new StringBuilder ( ) ; for ( String s : sortedRestOfSet1 ) { sb2 . append ( s ) . append ( \" \" ) ; } LOG . trace ( \"Sorted rest of 2 --> {}\" , sb2 . toString ( ) ) ; } StringBuilder t0Builder = new StringBuilder ( \"\" ) ; StringBuilder t1Builder = new StringBuilder ( \"\" ) ; StringBuilder t2Builder = new StringBuilder ( \"\" ) ; for ( String s : sortedIntersection ) { t0Builder . append ( \" \" ) . append ( s ) ; } String t0 = t0Builder . toString ( ) . trim ( ) ; Set < String > setT1 = Sets . union ( sortedIntersection , sortedRestOfSet1 ) ; for ( String s : setT1 ) { t1Builder . append ( \" \" ) . append ( s ) ; } String t1 = t1Builder . toString ( ) . trim ( ) ; Set < String > setT2 = Sets . union ( intersection , sortedRestOfSet2 ) ; for ( String s : setT2 ) { t2Builder . append ( \" \" ) . append ( s ) ; } String t2 = t2Builder . toString ( ) . trim ( ) ; int amt1 = calculateLevenshteinDistance ( t0 , t1 ) ; int amt2 = calculateLevenshteinDistance ( t0 , t2 ) ; int amt3 = calculateLevenshteinDistance ( t1 , t2 ) ; LOG . trace ( \"t0 = {} --> {}\" , t0 , amt1 ) ; LOG . trace ( \"t1 = {} --> {}\" , t1 , amt2 ) ; LOG . trace ( \"t2 = {} --> {}\" , t2 , amt3 ) ; return Math . max ( Math . max ( amt1 , amt2 ) , amt3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private Methods [CODESPLIT] private void close ( boolean idleClosed ) throws IOException , StageException { closeLock . writeLock ( ) . lock ( ) ; LOG . debug ( \"Path[{}] - Closing\" , filePath ) ; try { throwIfIdleClosed ( ) ; // If this was closed previously, just return if ( isClosed ( ) ) { return ; } if ( generator != null ) { generator . close ( ) ; } this . idleClosed = idleClosed ; // writers can never be null, except in tests if ( idleClosed && outputStreamHelper != null ) { //writers.release(this, false); outputStreamHelper . commitFile ( filePath ) ; } } finally { closeLock . writeLock ( ) . unlock ( ) ; //Gracefully Shutdown the thread, so rename goes through without glitch. if ( ! idleClosed ) { idleCloseExecutor . shutdown ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance of a stage that does not directly live in the pipeline canvas . [CODESPLIT] public < S > DetachedStageRuntime < ? extends S > createDetachedStage ( String jsonDefinition , StageLibraryTask stageLibrary , String pipelineId , String pipelineTitle , String rev , Stage . UserContext userContext , MetricRegistry metrics , ExecutionMode executionMode , DeliveryGuarantee deliveryGuarantee , RuntimeInfo runtimeInfo , EmailSender emailSender , Configuration configuration , long startTime , LineagePublisherDelegator lineagePublisherDelegator , Class < S > klass , List < Issue > errors ) { DetachedStageConfiguration stageConf ; try { ObjectMapper objectMapper = ObjectMapperFactory . get ( ) ; DetachedStageConfigurationJson stageConfJson = objectMapper . readValue ( jsonDefinition , DetachedStageConfigurationJson . class ) ; stageConf = stageConfJson . getDetachedStageConfiguration ( ) ; } catch ( IOException e ) { LOG . error ( CreationError . CREATION_0900 . getMessage ( ) , e . toString ( ) , e ) ; errors . add ( IssueCreator . getPipeline ( ) . create ( CreationError . CREATION_0900 , e . toString ( ) ) ) ; return null ; } return createDetachedStage ( stageConf , stageLibrary , pipelineId , pipelineTitle , rev , userContext , metrics , executionMode , deliveryGuarantee , runtimeInfo , emailSender , configuration , startTime , lineagePublisherDelegator , klass , errors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance of a stage that does not directly live in the pipeline canvas . [CODESPLIT] public < S > DetachedStageRuntime < ? extends S > createDetachedStage ( DetachedStageConfiguration stageConf , StageLibraryTask stageLibrary , String pipelineId , String pipelineTitle , String rev , Stage . UserContext userContext , MetricRegistry metrics , ExecutionMode executionMode , DeliveryGuarantee deliveryGuarantee , RuntimeInfo runtimeInfo , EmailSender emailSender , Configuration configuration , long startTime , LineagePublisherDelegator lineagePublisherDelegator , Class < S > klass , List < Issue > errors ) { // Firstly validate that the configuration is correct and up to date DetachedStageValidator validator = new DetachedStageValidator ( stageLibrary , stageConf ) ; DetachedStageConfiguration detachedStageConfiguration = validator . validate ( ) ; // If the stage is not valid, we can't create instance of it if ( detachedStageConfiguration . getIssues ( ) . hasIssues ( ) ) { errors . addAll ( detachedStageConfiguration . getIssues ( ) . getIssues ( ) ) ; return null ; } // Then stageBean that will create new instance and properly propagate all the StageBean stageBean = PipelineBeanCreator . get ( ) . createStageBean ( true , stageLibrary , stageConf . getStageConfiguration ( ) , false , false , false , Collections . emptyMap ( ) , null , errors ) ; if ( ! errors . isEmpty ( ) ) { return null ; } // Stage.Info and Stage.Context Stage . Info stageInfo = new Stage . Info ( ) { @ Override public String getName ( ) { return stageBean . getDefinition ( ) . getName ( ) ; } @ Override public int getVersion ( ) { return stageBean . getDefinition ( ) . getVersion ( ) ; } @ Override public String getInstanceName ( ) { return stageBean . getConfiguration ( ) . getInstanceName ( ) ; } @ Override public String getLabel ( ) { return stageBean . getConfiguration ( ) . getInstanceName ( ) ; } } ; StageContext context = new StageContext ( pipelineId , pipelineTitle , null , //TODO. Will need to set here if this stage needs to publish lineage events rev , null , //TODO. Will need to set here if this stage needs to publish lineage events Collections . emptyList ( ) , userContext , stageBean . getDefinition ( ) . getType ( ) , 0 , false , metrics , stageBean . getDefinition ( ) . getConfigDefinitions ( ) , stageBean . getSystemConfigs ( ) . stageOnRecordError , Collections . emptyList ( ) , Collections . emptyMap ( ) , stageInfo , executionMode , deliveryGuarantee , runtimeInfo , emailSender , configuration , Collections . emptyMap ( ) , startTime , lineagePublisherDelegator , Collections . emptyMap ( ) , false ) ; return DetachedStageRuntime . create ( stageBean , stageInfo , context , klass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stuff a function into the namespace / name dual level map structure [CODESPLIT] private void registerFunction ( ElFunctionDefinition function ) { String namespace ; String functionName ; if ( function . getName ( ) . contains ( \":\" ) ) { String [ ] tokens = function . getName ( ) . split ( \":\" ) ; namespace = tokens [ 0 ] ; functionName = tokens [ 1 ] ; } else { namespace = \"\" ; functionName = function . getName ( ) ; } Map < String , Method > namespaceFunctions = functionsByNamespace . get ( namespace ) ; if ( namespaceFunctions == null ) { namespaceFunctions = new HashMap <> ( ) ; functionsByNamespace . put ( namespace , namespaceFunctions ) ; } namespaceFunctions . put ( functionName , function . getMethod ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject config values to given Stage . [CODESPLIT] public void injectStage ( Object stage , StageDefinition stageDef , StageConfiguration stageConf , Map < String , Object > constants , List < Issue > issues ) { injectConfigsToObject ( stage , new StageInjectorContext ( stageDef , stageConf , constants , issues ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processor . Context [CODESPLIT] @ Override public Record createRecord ( Record originatorRecord ) { Preconditions . checkNotNull ( originatorRecord , \"originatorRecord cannot be null\" ) ; RecordImpl record = new RecordImpl ( stageInfo . getInstanceName ( ) , originatorRecord , null , null ) ; HeaderImpl header = record . getHeader ( ) ; header . setStagesPath ( \"\" ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processor . Context [CODESPLIT] @ Override public Record createRecord ( Record originatorRecord , String sourceIdPostfix ) { Preconditions . checkNotNull ( originatorRecord , \"originatorRecord cannot be null\" ) ; RecordImpl record = new RecordImpl ( stageInfo . getInstanceName ( ) , originatorRecord , null , null ) ; HeaderImpl header = record . getHeader ( ) ; header . setSourceId ( header . getSourceId ( ) + \"_\" + sourceIdPostfix ) ; header . setStagesPath ( \"\" ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processor . Context [CODESPLIT] @ Override public Record createRecord ( Record originatorRecord , byte [ ] raw , String rawMime ) { return new RecordImpl ( stageInfo . getInstanceName ( ) , originatorRecord , raw , rawMime ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processor . Context [CODESPLIT] @ Override public Record cloneRecord ( Record record ) { RecordImpl clonedRecord = ( ( RecordImpl ) record ) . clone ( ) ; HeaderImpl header = clonedRecord . getHeader ( ) ; header . setStagesPath ( \"\" ) ; return clonedRecord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processor . Context [CODESPLIT] @ Override public Record cloneRecord ( Record record , String sourceIdPostfix ) { RecordImpl clonedRecord = ( ( RecordImpl ) record ) . clone ( ) ; HeaderImpl header = clonedRecord . getHeader ( ) ; header . setSourceId ( header . getSourceId ( ) + \"_\" + sourceIdPostfix ) ; header . setStagesPath ( \"\" ) ; return clonedRecord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns if the { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T extends HMSCacheSupport . HMSCacheInfo > T getIfPresent ( HMSCacheType hmsCacheType , String qualifiedTableName ) throws StageException { if ( ! cacheMap . containsKey ( hmsCacheType ) ) { throw new StageException ( Errors . HIVE_16 , hmsCacheType ) ; } Optional < HMSCacheSupport . HMSCacheInfo > ret = cacheMap . get ( hmsCacheType ) . getIfPresent ( qualifiedTableName ) ; return ret == null ? null : ( T ) ret . orNull ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns if the { @link HMSCache } has the corresponding { @link HMSCacheSupport . HMSCacheInfo } and qualified table name . This method is safe to call from multiple threads - it will block and serialize multiple readers . It guarantees that each value will be loaded at most once to limit load on HS2 as much as possible . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T extends HMSCacheSupport . HMSCacheInfo > T getOrLoad ( HMSCacheType hmsCacheType , String qualifiedTableName , HiveQueryExecutor queryExecutor ) throws StageException { if ( ! cacheMap . containsKey ( hmsCacheType ) ) { throw new StageException ( Errors . HIVE_16 , hmsCacheType ) ; } // Firstly validate if the data already exists to avoid locking T cacheValue = getIfPresent ( hmsCacheType , qualifiedTableName ) ; if ( cacheValue != null ) { return cacheValue ; } // For altering operation, get exclusive lock Lock lock = null ; try { lock = tableLocks . get ( keyForLockMap ( hmsCacheType , qualifiedTableName ) ) ; lock . lock ( ) ; // Check the presence again as another thread could load the value before we got the lock cacheValue = getIfPresent ( hmsCacheType , qualifiedTableName ) ; if ( cacheValue != null ) { return cacheValue ; } // Load the value from Hive return ( T ) ( cacheMap . get ( hmsCacheType ) . get ( qualifiedTableName , ( ) -> hmsCacheType . getSupport ( ) . newHMSCacheLoader ( queryExecutor ) . load ( qualifiedTableName ) ) ) . orNull ( ) ; } catch ( ExecutionException e ) { throw new StageException ( Errors . HIVE_01 , e ) ; } finally { if ( lock != null ) { lock . unlock ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts / updates the { @link HMSCache } with { @link HMSCacheSupport . HMSCacheInfo } for corresponding { @link HMSCacheType } and qualified table name . [CODESPLIT] public < T extends HMSCacheSupport . HMSCacheInfo > void put ( HMSCacheType cacheType , String qualifiedTableName , T hmsCacheInfo ) throws StageException { if ( ! cacheMap . containsKey ( cacheType ) ) { throw new StageException ( Errors . HIVE_16 , cacheType ) ; } cacheMap . get ( cacheType ) . put ( qualifiedTableName , Optional . of ( hmsCacheInfo ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns pipeline &amp ; stage configuration definitions This will fetch defintions based on the hideStage filter [CODESPLIT] public DefinitionsJson getDefinitions ( HideStage . Type hideStage ) throws ApiException { Object postBody = null ; byte [ ] postBinaryBody = null ; // create path and map variables String path = \"/v1/definitions\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > queryParams = new ArrayList < Pair > ( ) ; if ( hideStage != null ) { queryParams . add ( new Pair ( \"hideStage\" , hideStage . name ( ) ) ) ; } Map < String , String > headerParams = new HashMap < String , String > ( ) ; Map < String , Object > formParams = new HashMap < String , Object > ( ) ; final String [ ] accepts = { \"application/json\" } ; final String accept = apiClient . selectHeaderAccept ( accepts ) ; final String [ ] contentTypes = { } ; final String contentType = apiClient . selectHeaderContentType ( contentTypes ) ; String [ ] authNames = new String [ ] { \"basic\" } ; TypeRef returnType = new TypeRef < DefinitionsJson > ( ) { } ; return apiClient . invokeAPI ( path , \"GET\" , queryParams , postBody , postBinaryBody , headerParams , formParams , accept , contentType , authNames , returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse given configuration declaration of lineage plugin and return appropriate definition . [CODESPLIT] private LineagePublisherDefinition getDefinition ( String name ) { String defConfig = LineagePublisherConstants . configDef ( name ) ; String publisherDefinition = configuration . get ( defConfig , null ) ; if ( StringUtils . isEmpty ( publisherDefinition ) ) { throw new IllegalArgumentException ( Utils . format ( \"Missing definition '{}'\" , defConfig ) ) ; } String [ ] lineagePluginDefs = publisherDefinition . split ( \"::\" ) ; if ( lineagePluginDefs . length != 2 ) { throw new IllegalStateException ( Utils . format ( \"Invalid definition '{}', expected $libraryName::$publisherName\" , publisherDefinition ) ) ; } LineagePublisherDefinition def = stageLibraryTask . getLineagePublisherDefinition ( lineagePluginDefs [ 0 ] , // Library lineagePluginDefs [ 1 ] // Plugin name ) ; if ( def == null ) { throw new IllegalStateException ( Utils . format ( \"Can't find publisher '{}'\" , publisherDefinition ) ) ; } return def ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format column names based on whether they are case - sensitive [CODESPLIT] private static String formatName ( String columnName , boolean caseSensitive ) { String returnValue = format ( columnName ) ; if ( caseSensitive ) { return returnValue ; } return returnValue . toUpperCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unescapes strings and returns them . [CODESPLIT] private static String formatValue ( String value ) { // The value can either be null (if the IS keyword is present before it or just a NULL string with no quotes) if ( value == null || NULL_STRING . equalsIgnoreCase ( value ) ) { return null ; } String returnValue = format ( value ) ; return returnValue . replaceAll ( \"''\" , \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find Pipeline Configuration by name and revision [CODESPLIT] public PipelineConfigurationJson getPipelineInfo ( String pipelineId , String rev , String get , Boolean attachment ) throws ApiException { Object postBody = null ; byte [ ] postBinaryBody = null ; // verify the required parameter 'pipelineId' is set if ( pipelineId == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'pipelineId' when calling getPipelineInfo\" ) ; } // create path and map variables String path = \"/v1/pipeline/{pipelineId}\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) . replaceAll ( \"\\\\{\" + \"pipelineId\" + \"\\\\}\" , apiClient . escapeString ( pipelineId . toString ( ) ) ) ; // query params List < Pair > queryParams = new ArrayList < Pair > ( ) ; Map < String , String > headerParams = new HashMap < String , String > ( ) ; Map < String , Object > formParams = new HashMap < String , Object > ( ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"rev\" , rev ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"get\" , get ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"attachment\" , attachment ) ) ; final String [ ] accepts = { \"application/json\" } ; final String accept = apiClient . selectHeaderAccept ( accepts ) ; final String [ ] contentTypes = { } ; final String contentType = apiClient . selectHeaderContentType ( contentTypes ) ; String [ ] authNames = new String [ ] { \"basic\" } ; TypeRef returnType = new TypeRef < PipelineConfigurationJson > ( ) { } ; return apiClient . invokeAPI ( path , \"GET\" , queryParams , postBody , postBinaryBody , headerParams , formParams , accept , contentType , authNames , returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new Pipeline Fragment Configuration to the store [CODESPLIT] public PipelineFragmentEnvelopeJson createDraftPipelineFragment ( String fragmentId , String description , List < StageConfigurationJson > stageInstances ) throws ApiException { Object postBody = stageInstances ; byte [ ] postBinaryBody = null ; // verify the required parameter 'pipelineId' is set if ( fragmentId == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'fragmentId' when calling createPipelineFragment\" ) ; } // create path and map variables String path = \"/v1/fragment/{fragmentId}\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) . replaceAll ( \"\\\\{\" + \"fragmentId\" + \"\\\\}\" , apiClient . escapeString ( fragmentId . toString ( ) ) ) ; // query params List < Pair > queryParams = new ArrayList < Pair > ( ) ; Map < String , String > headerParams = new HashMap < String , String > ( ) ; Map < String , Object > formParams = new HashMap < String , Object > ( ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"description\" , description ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"draft\" , true ) ) ; final String [ ] accepts = { \"application/json\" } ; final String accept = apiClient . selectHeaderAccept ( accepts ) ; final String [ ] contentTypes = { } ; final String contentType = apiClient . selectHeaderContentType ( contentTypes ) ; String [ ] authNames = new String [ ] { \"basic\" } ; TypeRef returnType = new TypeRef < PipelineFragmentEnvelopeJson > ( ) { } ; return apiClient . invokeAPI ( path , \"PUT\" , queryParams , postBody , postBinaryBody , headerParams , formParams , accept , contentType , authNames , returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all Pipeline Configuration Info [CODESPLIT] public List < PipelineInfoJson > getPipelines ( String filterText , String label , int offset , int len , PipelineOrderByFields orderBy , Order order , boolean includeStatus ) throws ApiException { Object postBody = null ; byte [ ] postBinaryBody = null ; // create path and map variables String path = \"/v1/pipelines\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > queryParams = new ArrayList < Pair > ( ) ; Map < String , String > headerParams = new HashMap < String , String > ( ) ; Map < String , Object > formParams = new HashMap < String , Object > ( ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"filterText\" , filterText ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"label\" , label ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"offset\" , offset ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"len\" , len ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"orderBy\" , orderBy ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"order\" , order ) ) ; final String [ ] accepts = { \"application/json\" } ; final String accept = apiClient . selectHeaderAccept ( accepts ) ; final String [ ] contentTypes = { } ; final String contentType = apiClient . selectHeaderContentType ( contentTypes ) ; String [ ] authNames = new String [ ] { \"basic\" } ; TypeRef returnType = new TypeRef < List < PipelineInfoJson > > ( ) { } ; return apiClient . invokeAPI ( path , \"GET\" , queryParams , postBody , postBinaryBody , headerParams , formParams , accept , contentType , authNames , returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Import Pipeline Fragment Configuration & Rules [CODESPLIT] public PipelineFragmentEnvelopeJson importPipelineFragment ( String fragmentId , boolean draft , boolean includeLibraryDefinitions , PipelineFragmentEnvelopeJson fragmentEnvelope ) throws ApiException { Object postBody = fragmentEnvelope ; byte [ ] postBinaryBody = null ; // verify the required parameter 'fragmentId' is set if ( fragmentId == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'fragmentId' when calling importPipelineFragment\" ) ; } // verify the required parameter 'fragmentEnvelope' is set if ( fragmentEnvelope == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'pipelineEnvelope' when calling importPipelineFragment\" ) ; } // create path and map variables String path = \"/v1/fragment/{fragmentId}/import\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) . replaceAll ( \"\\\\{\" + \"fragmentId\" + \"\\\\}\" , apiClient . escapeString ( fragmentId . toString ( ) ) ) ; // query params List < Pair > queryParams = new ArrayList < Pair > ( ) ; Map < String , String > headerParams = new HashMap < String , String > ( ) ; Map < String , Object > formParams = new HashMap < String , Object > ( ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"draft\" , draft ) ) ; queryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"includeLibraryDefinitions\" , includeLibraryDefinitions ) ) ; final String [ ] accepts = { \"application/json\" } ; final String accept = apiClient . selectHeaderAccept ( accepts ) ; final String [ ] contentTypes = { \"application/json\" } ; final String contentType = apiClient . selectHeaderContentType ( contentTypes ) ; String [ ] authNames = new String [ ] { \"basic\" } ; TypeRef returnType = new TypeRef < PipelineFragmentEnvelopeJson > ( ) { } ; return apiClient . invokeAPI ( path , \"POST\" , queryParams , postBody , postBinaryBody , headerParams , formParams , accept , contentType , authNames , returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "and the hdfsTarget ( in the pipeline runnable thread ) calls flushAll [CODESPLIT] public synchronized void release ( RecordWriter writer , boolean roll ) throws StageException , IOException { writer . closeLock ( ) ; try { if ( roll || writer . isIdleClosed ( ) || manager . isOverThresholds ( writer ) ) { if ( IS_TRACE_ENABLED ) { LOG . trace ( \"Release '{}'\" , writer . getPath ( ) ) ; } writers . remove ( writer . getPath ( ) . toString ( ) ) ; manager . commitWriter ( writer ) ; } } finally { writer . closeUnlock ( ) ; } purge ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the temp file path to write records to [CODESPLIT] public String getFilePath ( String dirPathTemplate , Record record , Date recordTime ) throws StageException { String dirPath ; // get directory path if ( dirPathTemplateInHeader ) { dirPath = record . getHeader ( ) . getAttribute ( DataLakeTarget . TARGET_DIRECTORY_HEADER ) ; Utils . checkArgument ( ! ( dirPath == null || dirPath . isEmpty ( ) ) , \"Directory Path cannot be null\" ) ; } else { dirPath = resolvePath ( dirPathTemplateEval , dirPathTemplateVars , dirPathTemplate , recordTime , record ) ; } // SDC-5492: replace \"//\" to \"/\" in file path dirPath = dirPath . replaceAll ( \"/+\" , \"/\" ) ; if ( dirPath . endsWith ( \"/\" ) ) { dirPath = dirPath . substring ( 0 , dirPath . length ( ) - 1 ) ; } return outputStreamHelper . getTempFilePath ( dirPath , record , recordTime ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close all generators ( and underlying streams / files ) [CODESPLIT] public void closeAll ( ) throws IOException , StageException { Set < String > filePathsToClose = ImmutableSet . copyOf ( tmpFilePathToGenerators . keySet ( ) ) ; for ( String filePath : filePathsToClose ) { close ( filePath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produce events that were cached during the batch processing . [CODESPLIT] public void issueCachedEvents ( ) throws IOException { String closedPath ; while ( ( closedPath = closedPaths . poll ( ) ) != null ) { produceCloseFileEvent ( closedPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the numeric operation code from record header . The default code is used if the operation code is not found in the header . [CODESPLIT] @ VisibleForTesting final int getOperationFromRecord ( Record record , JDBCOperationType defaultOp , UnsupportedOperationAction unsupportedAction , List < OnRecordErrorException > errorRecords ) { return getOperationFromRecord ( record , defaultOp . getCode ( ) , unsupportedAction , errorRecords ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the numeric operation code from record header . The default code is used if the operation code is not found in the header . This can be overwritten in inherited classes . [CODESPLIT] int getOperationFromRecord ( Record record , int defaultOpCode , UnsupportedOperationAction unsupportedAction , List < OnRecordErrorException > errorRecords ) { String op = record . getHeader ( ) . getAttribute ( OperationType . SDC_OPERATION_TYPE ) ; int opCode = - 1 ; // unsupported if ( Strings . isNullOrEmpty ( op ) ) { return defaultOpCode ; } // Check if the operation code from header attribute is valid try { opCode = JDBCOperationType . convertToIntCode ( op ) ; } catch ( NumberFormatException | UnsupportedOperationException ex ) { LOG . debug ( \"Operation obtained from record is not supported. Handle by UnsupportedOperationAction {}. {}\" , unsupportedAction . getLabel ( ) , ex ) ; switch ( unsupportedAction ) { case SEND_TO_ERROR : LOG . debug ( \"Sending record to error due to unsupported operation {}\" , op ) ; errorRecords . add ( new OnRecordErrorException ( record , JdbcErrors . JDBC_70 , op ) ) ; break ; case USE_DEFAULT : opCode = defaultOpCode ; break ; case DISCARD : default : // unknown action LOG . debug ( \"Discarding record with unsupported operation {}\" , op ) ; } } return opCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate the columnsToField map and check if the record has all the necessary columns . The returned SortedMap contains columnName - param mapping which is only contained in this record . For example if a table in destination DB has a column A but record doesn t have a field named A the column A is not included in the returning SortedMap . [CODESPLIT] @ VisibleForTesting SortedMap < String , String > getColumnsToParameters ( final Record record , int op , Map < String , String > parameters , Map < String , String > columnsToFields ) { SortedMap < String , String > filtered = new TreeMap <> ( ) ; for ( Map . Entry < String , String > entry : columnsToFields . entrySet ( ) ) { String columnName = entry . getKey ( ) ; String fieldPath = entry . getValue ( ) ; if ( record . has ( fieldPath ) ) { filtered . put ( columnName , parameters . get ( columnName ) ) ; } else { LOG . trace ( \"Record is missing a field for column {} for the operation code {}\" , columnName , op ) ; } } return filtered ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function simply returns field path in record for the corresponding column name . This is needed because records generated by CDC origins store data in different location for different operation . Subclasses will override this function and implement special handling . [CODESPLIT] String getFieldPath ( String columnName , Map < String , String > columnsToField , int op ) { return columnsToField . get ( columnName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the vertices in the topological order using { @link #tieComparator } if needed to break ties . Throws { @link IllegalStateException } if there is a cycle detected . [CODESPLIT] public SortedSet < V > sort ( ) { Utils . checkState ( ! new CycleDetector <> ( directedGraph ) . isGraphCyclic ( ) , \"Cycles found in the graph\" ) ; final Map < V , Integer > vertexToSortedNumber = new HashMap <> ( ) ; Map < V , Integer > inEdgesCount = new TreeMap <> ( ) ; SortedSet < V > sortedSet = new TreeSet <> ( ( o1 , o2 ) -> { Integer sortedNumber1 = vertexToSortedNumber . get ( o1 ) ; Integer sortedNumber2 = vertexToSortedNumber . get ( o2 ) ; if ( sortedNumber1 . intValue ( ) == sortedNumber2 . intValue ( ) ) { //If there is no tie comparator and there is a tie, arrange o1 before o2. return ( tieComparator != null ) ? tieComparator . compare ( o1 , o2 ) : - 1 ; } return sortedNumber1 . compareTo ( sortedNumber2 ) ; } ) ; final AtomicInteger startNumber = new AtomicInteger ( 1 ) ; directedGraph . vertices ( ) . forEach ( vertex -> { Collection < V > inwardVertices = directedGraph . getInwardEdgeVertices ( vertex ) ; inEdgesCount . put ( vertex , inwardVertices . size ( ) ) ; } ) ; while ( ! inEdgesCount . isEmpty ( ) ) { Set < V > nextVertices = nextVerticesForProcessing ( inEdgesCount ) ; nextVertices . forEach ( vertexForProcessing -> { inEdgesCount . remove ( vertexForProcessing ) ; updateCounts ( vertexForProcessing , inEdgesCount ) ; vertexToSortedNumber . put ( vertexForProcessing , startNumber . getAndIncrement ( ) ) ; } ) ; } sortedSet . addAll ( vertexToSortedNumber . keySet ( ) ) ; return sortedSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read next event from buffer with respect to maximum timeout . [CODESPLIT] public EnrichedEvent poll ( long timeout , TimeUnit unit ) throws StageException { try { return queue . poll ( timeout , unit ) ; } catch ( InterruptedException e ) { LOG . error ( Errors . MYSQL_001 . getMessage ( ) , e . toString ( ) , e ) ; Thread . currentThread ( ) . interrupt ( ) ; throw new StageException ( Errors . MYSQL_001 , e . toString ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing ( can t annotate as can t depend on Guava ) [CODESPLIT] public static Integer getMapMemoryMb ( String javaOpts , Configuration conf ) { String [ ] javaOptsArray = javaOpts . split ( \" \" ) ; Integer upperLimitMemory = null ; for ( String opts : javaOptsArray ) { if ( opts . contains ( \"-Xmx\" ) ) { Integer memoryMb = Integer . valueOf ( opts . substring ( 4 , opts . length ( ) - 1 ) ) ; switch ( opts . charAt ( opts . length ( ) - 1 ) ) { case ' ' : case ' ' : break ; case ' ' : case ' ' : memoryMb = memoryMb / ( 1024 ) ; break ; case ' ' : case ' ' : memoryMb = memoryMb * 1024 ; break ; default : memoryMb = Integer . valueOf ( opts . substring ( 4 , opts . length ( ) ) ) / ( 1024 * 1024 ) ; break ; } // Add 25% to Java heap as MAP_MEMORY_MB is the total physical memory for the map task upperLimitMemory = ( ( int ) ( memoryMb * 0.25 ) ) + memoryMb ; // dont break as there could be multiple -Xmx, we need to honor the last } } if ( upperLimitMemory != null ) { String defaultMapMemoryString = conf . get ( MAPREDUCE_MAP_MEMORY_MB ) ; if ( defaultMapMemoryString != null ) { Integer defaultMapMemory = Integer . valueOf ( defaultMapMemoryString ) ; upperLimitMemory = ( upperLimitMemory > defaultMapMemory ? upperLimitMemory : defaultMapMemory ) ; } } return upperLimitMemory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copied from https : // raw . githubusercontent . com / kamranzafar / jtar / master / src / test / java / org / kamranzafar / jtar / JTarTest . java [CODESPLIT] private static void tarFolder ( String parent , String path , TarOutputStream out ) throws IOException { BufferedInputStream src = null ; File f = new File ( path ) ; String files [ ] = f . list ( ) ; // is file if ( files == null ) { files = new String [ 1 ] ; files [ 0 ] = f . getName ( ) ; } parent = ( ( parent == null ) ? ( f . isFile ( ) ) ? \"\" : f . getName ( ) + \"/\" : parent + f . getName ( ) + \"/\" ) ; for ( int i = 0 ; i < files . length ; i ++ ) { File fe = f ; if ( f . isDirectory ( ) ) { fe = new File ( f , files [ i ] ) ; } if ( fe . isDirectory ( ) ) { String [ ] fl = fe . list ( ) ; if ( fl != null && fl . length != 0 ) { tarFolder ( parent , fe . getPath ( ) , out ) ; } else { TarEntry entry = new TarEntry ( fe , parent + files [ i ] + \"/\" ) ; out . putNextEntry ( entry ) ; } continue ; } FileInputStream fi = new FileInputStream ( fe ) ; src = new BufferedInputStream ( fi ) ; TarEntry entry = new TarEntry ( fe , parent + files [ i ] ) ; out . putNextEntry ( entry ) ; IOUtils . copy ( src , out ) ; src . close ( ) ; out . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get exclusive runner for use . [CODESPLIT] public T getRunner ( ) throws PipelineRuntimeException { validateNotDestroyed ( ) ; try { return queue . take ( ) . runner ; } catch ( InterruptedException e ) { throw new PipelineRuntimeException ( ContainerError . CONTAINER_0801 , e ) ; } finally { runtimeStats . setAvailableRunners ( queue . size ( ) ) ; histogram . update ( queue . size ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a runner that haven t been used at least for the configured number of milliseconds . [CODESPLIT] public T getIdleRunner ( long idleTime ) { // Take the first runner QueueItem < T > item = queue . poll ( ) ; // All runners might be currently in use, which is fine in this case. if ( item == null ) { return null ; } // If the runner wasn't idle for the expected time, we need to put it back to the queue (it will be added to the // begging again). if ( ( System . currentTimeMillis ( ) - item . timestamp ) < idleTime ) { queue . add ( item ) ; return null ; } // Otherwise we do have runner that hasn't been used for at least idleTime, so we can return it now return item . runner ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return given runner back to the pool . [CODESPLIT] public void returnRunner ( T runner ) throws PipelineRuntimeException { validateNotDestroyed ( ) ; queue . add ( new QueueItem <> ( runner ) ) ; runtimeStats . setAvailableRunners ( queue . size ( ) ) ; histogram . update ( queue . size ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroy only the pool itself - not the individual pipe runners . [CODESPLIT] public void destroy ( ) throws PipelineRuntimeException { // Firstly set this runner as destroyed destroyed . set ( true ) ; // Validate that this thread pool have all runners back, otherwise we're missing something and that is sign of // a trouble. if ( queue . size ( ) < runtimeStats . getTotalRunners ( ) ) { throw new PipelineRuntimeException ( ContainerError . CONTAINER_0802 , queue . size ( ) , runtimeStats . getTotalRunners ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throw an exception if the runner was already destroyed . [CODESPLIT] private void validateNotDestroyed ( ) throws PipelineRuntimeException { if ( destroyed . get ( ) ) { throw new PipelineRuntimeException ( ContainerError . CONTAINER_0803 , queue . size ( ) , runtimeStats . getTotalRunners ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for existence of the requested stream and adds any configuration issues to the list . [CODESPLIT] public static long checkStreamExists ( ClientConfiguration awsClientConfig , KinesisConfigBean conf , String streamName , List < Stage . ConfigIssue > issues , Stage . Context context ) { long numShards = 0 ; try { numShards = getShardCount ( awsClientConfig , conf , streamName ) ; } catch ( AmazonClientException | StageException e ) { LOG . error ( Errors . KINESIS_01 . getMessage ( ) , e . toString ( ) , e ) ; issues . add ( context . createConfigIssue ( Groups . KINESIS . name ( ) , KINESIS_CONFIG_BEAN + \".streamName\" , Errors . KINESIS_01 , e . toString ( ) ) ) ; } return numShards ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the last shard Id in the given stream In preview mode kinesis source uses the last Shard Id to get records from kinesis [CODESPLIT] public static String getLastShardId ( ClientConfiguration awsClientConfig , KinesisConfigBean conf , String streamName ) throws StageException { AmazonKinesis kinesisClient = getKinesisClient ( awsClientConfig , conf ) ; String lastShardId = null ; try { StreamDescription description ; do { if ( lastShardId == null ) { description = kinesisClient . describeStream ( streamName ) . getStreamDescription ( ) ; } else { description = kinesisClient . describeStream ( streamName , lastShardId ) . getStreamDescription ( ) ; } int pageSize = description . getShards ( ) . size ( ) ; lastShardId = description . getShards ( ) . get ( pageSize - 1 ) . getShardId ( ) ; } while ( description . getHasMoreShards ( ) ) ; return lastShardId ; } finally { kinesisClient . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all records in queue . All records have same operation to same table . Generate a query and set parameters from each record . INSERT and DELETE can be multi - row operation but UPDATE is single - row operation . If maxStatement [CODESPLIT] private void processQueue ( LinkedList < Record > queue , List < OnRecordErrorException > errorRecords , Connection connection , int maxRowsPerBatch , int opCode ) throws StageException { if ( queue . isEmpty ( ) ) { return ; } int rowCount = 0 ; // Assume that columns are all same for the same operation to the same table // If some columns are missing in record, the record goes to error. final Record first = queue . getFirst ( ) ; SortedMap < String , String > columnsToParameters = recordReader . getColumnsToParameters ( first , opCode , getColumnsToParameters ( ) , opCode == OperationType . UPDATE_CODE ? getColumnsToFieldNoPK ( ) : getColumnsToFields ( ) ) ; if ( columnsToParameters . isEmpty ( ) ) { // no parameters found for configured columns if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( \"No parameters found for record with ID {}; skipping\" , first . getHeader ( ) . getSourceId ( ) ) ; } return ; } String query = generateQueryForMultiRow ( opCode , columnsToParameters , getPrimaryKeyColumns ( ) , // the next batch will have either the max number of records, or however many are left. Math . min ( maxRowsPerBatch , queue . size ( ) ) ) ; // Need to store removed records from queue, because we might need to add newly generated columns // to records for Jdbc Tee Processor. LinkedList < Record > removed = new LinkedList <> ( ) ; try ( PreparedStatement statement = jdbcUtil . getPreparedStatement ( getGeneratedColumnMappings ( ) , query , connection ) ) { int paramIdx = 1 ; // Start processing records in queue. All records have the same operation to the same table. while ( ! queue . isEmpty ( ) ) { Record r = queue . removeFirst ( ) ; if ( opCode != DELETE_CODE ) { paramIdx = setParamsToStatement ( paramIdx , statement , columnsToParameters , r , connection , opCode ) ; } if ( opCode != OperationType . INSERT_CODE ) { paramIdx = setPrimaryKeys ( paramIdx , r , statement , opCode ) ; } removed . add ( r ) ; ++ rowCount ; if ( rowCount == maxRowsPerBatch ) { // time to execute the current batch processBatch ( removed , errorRecords , statement , connection ) ; // reset our counters rowCount = 0 ; paramIdx = 1 ; removed . clear ( ) ; } } } catch ( SQLException e ) { handleSqlException ( e , removed , errorRecords ) ; } // Process the rest of the records that are removed from queue but haven't processed yet // this happens when rowCount is still less than maxRowsPerBatch. // This is a bit of an ugly fix as its not very DRY but sufficient until there's a larger // refactoring of this code. if ( ! removed . isEmpty ( ) ) { query = generateQueryForMultiRow ( opCode , columnsToParameters , getPrimaryKeyColumns ( ) , removed . size ( ) // always the remainder ) ; try ( PreparedStatement statement = jdbcUtil . getPreparedStatement ( getGeneratedColumnMappings ( ) , query , connection ) ) { int paramIdx = 1 ; for ( Record r : removed ) { if ( opCode != DELETE_CODE ) { paramIdx = setParamsToStatement ( paramIdx , statement , columnsToParameters , r , connection , opCode ) ; } if ( opCode != OperationType . INSERT_CODE ) { paramIdx = setPrimaryKeys ( paramIdx , r , statement , opCode ) ; } } processBatch ( removed , errorRecords , statement , connection ) ; } catch ( SQLException e ) { handleSqlException ( e , removed , errorRecords ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle SQLException in a smart way detecting if the exception is data oriented or not . [CODESPLIT] private void handleSqlException ( SQLException exception , List < Record > inputRecords , List < OnRecordErrorException > errors ) throws StageException { if ( jdbcUtil . isDataError ( getCustomDataSqlStateCodes ( ) , getConnectionString ( ) , exception ) ) { String formattedError = jdbcUtil . formatSqlException ( exception ) ; LOG . error ( JdbcErrors . JDBC_89 . getMessage ( ) , formattedError ) ; for ( Record inputRecord : inputRecords ) { errors . add ( new OnRecordErrorException ( inputRecord , JdbcErrors . JDBC_89 , formattedError ) ) ; } return ; } super . handleSqlException ( exception ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a hash for the fields present in a record and their mappings . A specific implementation of the hash function is not guaranteed . [CODESPLIT] private HashCode getColumnHash ( Record record , int op ) throws OnRecordErrorException { Map < String , String > parameters = getColumnsToParameters ( ) ; SortedMap < String , String > columnsToParameters = recordReader . getColumnsToParameters ( record , op , parameters , getColumnsToFields ( ) ) ; return columnHashFunction . newHasher ( ) . putObject ( columnsToParameters , stringMapFunnel ) . hash ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates Login url with request URL as parameter for a callback redirection on a successful login . [CODESPLIT] String getLoginUrl ( HttpServletRequest request , boolean repeatedRedirect ) { String requestUrl = getRequestUrl ( request , TOKEN_PARAM_SET ) . toString ( ) ; return getSsoService ( ) . createRedirectToLoginUrl ( requestUrl , repeatedRedirect ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Removes the token from request URL redirects to the modified URL returns the token as a header [CODESPLIT] Authentication redirectToSelf ( HttpServletRequest httpReq , HttpServletResponse httpRes ) throws ServerAuthException { String authToken = httpReq . getParameter ( SSOConstants . USER_AUTH_TOKEN_PARAM ) ; String urlWithoutToken = getRequestUrlWithoutToken ( httpReq ) ; httpRes . setHeader ( SSOConstants . X_USER_AUTH_TOKEN , authToken ) ; try { LOG . debug ( \"Redirecting to self without token '{}'\" , urlWithoutToken ) ; httpRes . sendRedirect ( urlWithoutToken ) ; return Authentication . SEND_CONTINUE ; } catch ( IOException ex ) { throw new ServerAuthException ( Utils . format ( \"Could not redirect to '{}': {}\" , urlWithoutToken , ex . toString ( ) , ex ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Terminates the request with an HTTP Unauthorized response or redirects to login for page requests [CODESPLIT] @ Override protected Authentication returnUnauthorized ( HttpServletRequest httpReq , HttpServletResponse httpRes , String principalId , String logMessageTemplate ) throws ServerAuthException { Authentication ret ; httpRes . addCookie ( createAuthCookie ( httpReq , \"\" , 0 ) ) ; if ( httpReq . getHeader ( SSOConstants . X_REST_CALL ) != null ) { ret = super . returnUnauthorized ( httpReq , httpRes , null , logMessageTemplate ) ; } else { redirectToLogin ( httpReq , httpRes ) ; ret = Authentication . SEND_FAILURE ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO this is a great place for generic validator [CODESPLIT] public Optional < List < ConfigIssue > > validateSchemaAndTables ( List < SchemaTableConfigBean > schemaTableConfigs ) { List < ConfigIssue > issues = new ArrayList <> ( ) ; for ( SchemaTableConfigBean tables : configBean . baseConfigBean . schemaTableConfigs ) { validateSchemaAndTable ( tables ) . ifPresent ( issues :: add ) ; } return Optional . ofNullable ( issues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "True if f1 is newer than f2 . [CODESPLIT] public static boolean compareFiles ( WrappedFileSystem fs , WrappedFile f1 , WrappedFile f2 ) { if ( ! fs . exists ( f2 ) ) { return true ; } try { long mtime1 = fs . getLastModifiedTime ( f1 ) ; long mtime2 = fs . getLastModifiedTime ( f2 ) ; long ctime1 = fs . getChangedTime ( f1 ) ; long ctime2 = fs . getChangedTime ( f2 ) ; long time1 = Math . max ( mtime1 , ctime1 ) ; long time2 = Math . max ( mtime2 , ctime2 ) ; int compares = Long . compare ( time1 , time2 ) ; if ( compares != 0 ) { return compares > 0 ; } } catch ( IOException ex ) { LOG . error ( \"Failed to get ctime: '{}'\" , f1 . getFileName ( ) , ex ) ; return false ; } return f1 . getAbsolutePath ( ) . compareTo ( f2 . getAbsolutePath ( ) ) > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the { @code DataParser } of the file could be local file and hdfs file [CODESPLIT] public static DataParser getParser ( WrappedFileSystem fs , WrappedFile file , DataFormat dataFormat , DataParserFactory parserFactory , String offset , int wholeFileMaxObjectLen , ELEval rateLimitElEval , ELVars rateLimitElVars , String rateLimit ) throws DataParserException , ELEvalException , IOException { DataParser parser ; switch ( dataFormat ) { case WHOLE_FILE : FileRef fileRef = fs . getFileRefBuilder ( ) . filePath ( file . getAbsolutePath ( ) ) . bufferSize ( wholeFileMaxObjectLen ) . rateLimit ( FileRefUtil . evaluateAndGetRateLimit ( rateLimitElEval , rateLimitElVars , rateLimit ) ) . createMetrics ( true ) . totalSizeInBytes ( file . getSize ( ) ) . build ( ) ; parser = parserFactory . getParser ( file . getFileName ( ) , file . getFileMetadata ( ) , fileRef ) ; break ; default : parser = parserFactory . getParser ( file . getFileName ( ) , file . getInputStream ( ) , offset ) ; } return parser ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute path from the root to the last base directory Meaning the path until the last / before the first * [CODESPLIT] public static String truncateGlobPatternDirectory ( String directory ) { String [ ] absolutePath = directory . split ( ESCAPED_ASTERISK ) ; String truncatedString = absolutePath [ 0 ] ; if ( lastCharacterIsAsterisk ( truncatedString ) != SLASH . toCharArray ( ) [ 0 ] ) { List < String > subDirectories = Arrays . asList ( truncatedString . split ( SLASH ) ) ; StringBuffer stringBuffer = new StringBuffer ( ) ; stringBuffer . append ( String . join ( SLASH , subDirectories . subList ( 0 , subDirectories . size ( ) - 1 ) ) ) . append ( SLASH ) ; truncatedString = stringBuffer . toString ( ) ; } LOG . debug ( String . format ( \"Checking existence of path: %s\" , truncatedString ) ) ; return truncatedString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to retrieve PID from internal JVM classes . This method is not guaranteed to work as JVM is free to change their implementation at will . Hence the return value should be only used for troubleshooting or debug and not for main functionality . [CODESPLIT] private static int retrievePidIfFeasible ( Process process ) { if ( unixProcessClass == null ) { return UNDETERMINED_PID ; } if ( ! unixProcessClass . isInstance ( process ) ) { LOG . debug ( \"Do not support retrieving PID from {}\" , process . getClass ( ) . getName ( ) ) ; return UNDETERMINED_PID ; } try { return ( int ) pidField . get ( process ) ; } catch ( IllegalAccessException e ) { LOG . debug ( \"Can't retrieve PID value from the field\" , e ) ; return UNDETERMINED_PID ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Basically throw out map list map list and null values fields . [CODESPLIT] private Set < String > validateAndExtractFieldsToHash ( Record record , Set < String > fieldsDontExist , Set < String > fieldsWithListOrMapType , Set < String > fieldsWithNull , Collection < String > matchingFieldsPath ) { Set < String > validFieldsToHashForThisConfig = new HashSet < String > ( ) ; for ( String matchingFieldPath : matchingFieldsPath ) { if ( record . has ( matchingFieldPath ) ) { Field field = record . get ( matchingFieldPath ) ; if ( UNSUPPORTED_FIELD_TYPES . contains ( field . getType ( ) ) ) { fieldsWithListOrMapType . add ( matchingFieldPath ) ; } else if ( field . getValue ( ) == null ) { fieldsWithNull . add ( matchingFieldPath ) ; } else { validFieldsToHashForThisConfig . add ( matchingFieldPath ) ; } } else { fieldsDontExist . add ( matchingFieldPath ) ; } } return validFieldsToHashForThisConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return UGI object that should be used for any remote operation . [CODESPLIT] public static UserGroupInformation getProxyUser ( String user , // Hadoop user (HDFS User, HBase user, generally the to-be-impersonated user in component's configuration) Stage . Context context , // Stage context object UserGroupInformation loginUser , // Login UGI (sdc user) List < Stage . ConfigIssue > issues , // Reports errors String configGroup , // Group where \"HDFS User\" is present String configName // Config name of \"HDFS User\" ) { // Should we always impersonate current user? boolean alwaysImpersonate = context . getConfiguration ( ) . get ( HadoopConfigConstants . IMPERSONATION_ALWAYS_CURRENT_USER , false ) ; // If so, propagate current user to \"user\" (the one to be impersonated) if ( alwaysImpersonate ) { if ( ! StringUtils . isEmpty ( user ) ) { issues . add ( context . createConfigIssue ( configGroup , configName , Errors . HADOOP_00001 ) ) ; } user = context . getUserContext ( ) . getAliasName ( ) ; } // If impersonated user is empty, simply return login UGI (no impersonation performed) if ( StringUtils . isEmpty ( user ) ) { return loginUser ; } // Optionally lower case the user name boolean lowerCase = context . getConfiguration ( ) . get ( HadoopConfigConstants . LOWERCASE_USER , false ) ; if ( lowerCase ) { user = user . toLowerCase ( ) ; } return UserGroupInformation . createProxyUser ( user , loginUser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns fresh bean with same UsageTimers just reset to zero accumulated time to be used as the new live stats [CODESPLIT] public ActiveStats roll ( ) { long now = System . currentTimeMillis ( ) ; setEndTime ( now ) ; ActiveStats statsBean = new ActiveStats ( ) . setStartTime ( now ) . setDataCollectorVersion ( getDataCollectorVersion ( ) ) . setDpmEnabled ( isDpmEnabled ( ) ) . setUpTime ( getUpTime ( ) . roll ( ) ) ; statsBean . setPipelines ( getPipelines ( ) . stream ( ) . map ( UsageTimer :: roll ) . collect ( Collectors . toList ( ) ) ) ; statsBean . setStages ( getStages ( ) . stream ( ) . filter ( timer -> timer . getMultiplier ( ) > 0 ) . map ( UsageTimer :: roll ) . collect ( Collectors . toList ( ) ) ) ; return statsBean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a snapshot for persistency [CODESPLIT] public ActiveStats snapshot ( ) { ActiveStats snapshot = new ActiveStats ( ) . setStartTime ( getStartTime ( ) ) . setDataCollectorVersion ( getDataCollectorVersion ( ) ) . setDpmEnabled ( isDpmEnabled ( ) ) . setUpTime ( getUpTime ( ) . snapshot ( ) ) . setRecordCount ( getRecordCount ( ) ) ; snapshot . setPipelines ( getPipelines ( ) . stream ( ) . map ( UsageTimer :: snapshot ) . collect ( Collectors . toList ( ) ) ) ; snapshot . setStages ( getStages ( ) . stream ( ) . map ( UsageTimer :: snapshot ) . collect ( Collectors . toList ( ) ) ) ; return snapshot ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure that given directory exists . [CODESPLIT] private void ensureDirectoryExists ( FileSystem fs , Path path ) throws IOException { if ( ! fs . exists ( path ) ) { LOG . debug ( \"Creating directory: {}\" , path ) ; if ( ! fs . mkdirs ( path ) ) { throw new IOException ( \"Can't create directory: \" + path ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Name format is Vault s [ path ] [CODESPLIT] @ Override public CredentialValue get ( String group , String name , String credentialStoreOptions ) throws StageException { Utils . checkNotNull ( group , \"group cannot be NULL\" ) ; Utils . checkNotNull ( name , \"name cannot be NULL\" ) ; try { Map < String , String > optionsMap = Splitter . on ( \",\" ) . omitEmptyStrings ( ) . trimResults ( ) . withKeyValueSeparator ( \"=\" ) . split ( credentialStoreOptions ) ; String separator = optionsMap . get ( SEPARATOR_OPTION ) ; if ( separator == null ) { separator = pathKeySeparator ; } String [ ] splits = name . split ( separator , 2 ) ; if ( splits . length != 2 ) { throw new IllegalArgumentException ( Utils . format ( \"Vault CredentialStore name '{}' should be <path>{}<key>\" , name , separator ) ) ; } String delayStr = optionsMap . get ( DELAY_OPTION ) ; long delay = ( delayStr == null ) ? 0 : Long . parseLong ( delayStr ) ; CredentialValue credential = new VaultCredentialValue ( splits [ 0 ] , splits [ 1 ] , delay ) ; credential . get ( ) ; return credential ; } catch ( Exception ex ) { throw new StageException ( Errors . VAULT_001 , name , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats the error message of a { @link java . sql . SQLException } for human consumption . [CODESPLIT] public String formatSqlException ( SQLException ex ) { StringBuilder sb = new StringBuilder ( ) ; Set < String > messages = new HashSet <> ( ) ; for ( Throwable e : ex ) { if ( e instanceof SQLException ) { String message = e . getMessage ( ) ; if ( ! messages . add ( message ) ) { continue ; } sb . append ( \"SQLState: \" + ( ( SQLException ) e ) . getSQLState ( ) + \"\\n\" ) . append ( \"Error Code: \" + ( ( SQLException ) e ) . getErrorCode ( ) + \"\\n\" ) . append ( \"Message: \" + message + \"\\n\" ) ; Throwable t = ex . getCause ( ) ; while ( t != null ) { if ( messages . add ( t . getMessage ( ) ) ) { sb . append ( \"Cause: \" + t + \"\\n\" ) ; } t = t . getCause ( ) ; } } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for { @link Connection#getCatalog () } to solve problems with RDBMs for which catalog and schema are the same thing . For these RDBMs it returns the schema name when it is not - null and not - empty ; otherwise it returns the value of java . sql . Connection . getCatalog () . For other RDBMs it returns always the value of java . sql . Connection . getCatalog () . [CODESPLIT] private String getCatalog ( Connection connection , String schema ) throws SQLException { if ( Strings . isNullOrEmpty ( schema ) ) { return connection . getCatalog ( ) ; } String name = connection . getMetaData ( ) . getDatabaseProductName ( ) . toLowerCase ( ) ; for ( String d : RDBMS_WITHOUT_SCHEMAS ) { if ( name . contains ( d ) ) { return schema ; } } return connection . getCatalog ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for { @link java . sql . DatabaseMetaData#getColumns ( String String String String ) } that detects the format of the supplied tableName . [CODESPLIT] public ResultSet getColumnMetadata ( Connection connection , String schema , String tableName ) throws SQLException { DatabaseMetaData metadata = connection . getMetaData ( ) ; // Get all columns for this table return metadata . getColumns ( getCatalog ( connection , schema ) , schema , tableName , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for { @link java . sql . DatabaseMetaData#getTables ( String String String String [] ) } [CODESPLIT] public ResultSet getTableAndViewMetadata ( Connection connection , String schema , String tableName ) throws SQLException { return connection . getMetaData ( ) . getTables ( getCatalog ( connection , schema ) , schema , tableName , METADATA_TABLE_VIEW_TYPE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for { @link java . sql . DatabaseMetaData#getTables ( String String String String [] ) } [CODESPLIT] public ResultSet getTableMetadata ( Connection connection , String schema , String tableName ) throws SQLException { DatabaseMetaData metadata = connection . getMetaData ( ) ; return metadata . getTables ( getCatalog ( connection , schema ) , schema , tableName , METADATA_TABLE_TYPE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for { @link java . sql . DatabaseMetaData#getPrimaryKeys ( String String String ) } [CODESPLIT] public List < String > getPrimaryKeys ( Connection connection , String schema , String tableName ) throws SQLException { String table = tableName ; DatabaseMetaData metadata = connection . getMetaData ( ) ; List < String > keys = new ArrayList <> ( ) ; try ( ResultSet result = metadata . getPrimaryKeys ( getCatalog ( connection , schema ) , schema , table ) ) { while ( result . next ( ) ) { keys . add ( result . getString ( COLUMN_NAME ) ) ; } } return keys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for { @link java . sql . DatabaseMetaData#getImportedKeys ( String String String ) } [CODESPLIT] public Set < String > getReferredTables ( Connection connection , String schema , String tableName ) throws SQLException { DatabaseMetaData metadata = connection . getMetaData ( ) ; ResultSet result = metadata . getImportedKeys ( getCatalog ( connection , schema ) , schema , tableName ) ; Set < String > referredTables = new HashSet <> ( ) ; while ( result . next ( ) ) { referredTables . add ( result . getString ( PK_TABLE_NAME ) ) ; } return referredTables ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write records to potentially different schemas and tables using EL expressions and handle errors . [CODESPLIT] public void write ( Batch batch , SchemaTableClassifier schemaTableClassifier , LoadingCache < SchemaAndTable , JdbcRecordWriter > recordWriters , ErrorRecordHandler errorRecordHandler , boolean perRecord ) throws StageException { Multimap < SchemaAndTable , Record > partitions = schemaTableClassifier . classify ( batch ) ; for ( SchemaAndTable key : partitions . keySet ( ) ) { Iterator < Record > recordIterator = partitions . get ( key ) . iterator ( ) ; write ( recordIterator , key , recordWriters , errorRecordHandler , perRecord ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write records to the evaluated tables and handle errors . [CODESPLIT] public void write ( Batch batch , ELEval tableNameEval , ELVars tableNameVars , String tableNameTemplate , LoadingCache < String , JdbcRecordWriter > recordWriters , ErrorRecordHandler errorRecordHandler , boolean perRecord ) throws StageException { Multimap < String , Record > partitions = ELUtils . partitionBatchByExpression ( tableNameEval , tableNameVars , tableNameTemplate , batch ) ; for ( String tableName : partitions . keySet ( ) ) { Iterator < Record > recordIterator = partitions . get ( tableName ) . iterator ( ) ; write ( recordIterator , tableName , recordWriters , errorRecordHandler , perRecord ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write records to a JDBC destination using the recordWriter specified by key and handle errors [CODESPLIT] public < T > void write ( Iterator < Record > recordIterator , T key , LoadingCache < T , JdbcRecordWriter > recordWriters , ErrorRecordHandler errorRecordHandler , boolean perRecord ) throws StageException { final JdbcRecordWriter jdbcRecordWriter ; try { jdbcRecordWriter = recordWriters . getUnchecked ( key ) ; } catch ( UncheckedExecutionException ex ) { final Throwable throwable = ex . getCause ( ) ; final ErrorCode errorCode ; final Object [ ] messageParams ; if ( throwable instanceof StageException ) { StageException stageEx = ( StageException ) ex . getCause ( ) ; errorCode = stageEx . getErrorCode ( ) ; messageParams = stageEx . getParams ( ) ; } else { errorCode = JdbcErrors . JDBC_301 ; messageParams = new Object [ ] { ex . getMessage ( ) , ex . getCause ( ) } ; } // Failed to create RecordWriter, report all as error records. while ( recordIterator . hasNext ( ) ) { Record record = recordIterator . next ( ) ; errorRecordHandler . onError ( new OnRecordErrorException ( record , errorCode , messageParams ) ) ; } return ; } List < OnRecordErrorException > errors = perRecord ? jdbcRecordWriter . writePerRecord ( recordIterator ) : jdbcRecordWriter . writeBatch ( recordIterator ) ; for ( OnRecordErrorException error : errors ) { errorRecordHandler . onError ( error ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the no - more - data event [CODESPLIT] public void generateNoMoreDataEvent ( PushSource . Context context ) { LOG . info ( \"No More data to process, Triggered No More Data Event\" ) ; BatchContext batchContext = context . startBatch ( ) ; CommonEvents . NO_MORE_DATA . create ( context , batchContext ) . createAndSend ( ) ; context . processBatch ( batchContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Using partition name and value that were obtained from record compare them with cached partition . [CODESPLIT] private Map < PartitionInfoCacheSupport . PartitionValues , String > detectNewPartition ( PartitionInfoCacheSupport . PartitionValues partitionValues , PartitionInfoCacheSupport . PartitionInfo pCache , String location ) throws StageException { Map < PartitionInfoCacheSupport . PartitionValues , String > partitionInfoDiff = new HashMap <> ( ) ; partitionInfoDiff . put ( partitionValues , location ) ; partitionInfoDiff = ( pCache != null ) ? pCache . getDiff ( partitionInfoDiff ) : partitionInfoDiff ; if ( pCache == null || ! partitionInfoDiff . isEmpty ( ) ) { return partitionInfoDiff ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a list of partition values from record . [CODESPLIT] @ VisibleForTesting LinkedHashMap < String , String > getPartitionValuesFromRecord ( ELVars variables ) throws StageException { LinkedHashMap < String , String > values = new LinkedHashMap <> ( ) ; for ( PartitionConfig pName : partitionConfigList ) { String ret = HiveMetastoreUtil . resolveEL ( elEvals . partitionValueELEval , variables , pName . valueEL ) ; if ( ret == null || ret . isEmpty ( ) ) { // If no partition value is found in record, this record goes to Error Record throw new HiveStageCheckedException ( Errors . HIVE_METADATA_02 , pName . valueEL ) ; } else if ( HiveMetastoreUtil . hasUnsupportedChar ( ret ) ) { throw new HiveStageCheckedException ( Errors . HIVE_METADATA_10 , pName . valueEL , ret ) ; } values . put ( pName . name . toLowerCase ( ) , ret ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a record for new partition . It creates a new Record and fill in metadata . [CODESPLIT] @ VisibleForTesting Record generateNewPartitionRecord ( String database , String tableName , LinkedHashMap < String , String > partitionList , String location , boolean customLocation , Map < String , String > metadataHeaderAttributes ) throws StageException { //creating a record with uuid as postfix so multiple SDCs won't generate the record with same id. Record metadataRecord = getContext ( ) . createRecord ( \"Partition Metadata Record\" + UUID . randomUUID ( ) . toString ( ) ) ; Field metadataField = HiveMetastoreUtil . newPartitionMetadataFieldBuilder ( database , tableName , partitionList , location , customLocation , dataFormat ) ; metadataRecord . set ( metadataField ) ; for ( Map . Entry < String , String > entry : metadataHeaderAttributes . entrySet ( ) ) { metadataRecord . getHeader ( ) . setAttribute ( entry . getKey ( ) , entry . getValue ( ) ) ; } return metadataRecord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add header information to send to HDFS [CODESPLIT] @ VisibleForTesting static void updateRecordForHDFS ( Record record , boolean roll , String avroSchema , String location ) { if ( roll ) { record . getHeader ( ) . setAttribute ( HDFS_HEADER_ROLL , \"true\" ) ; } record . getHeader ( ) . setAttribute ( HDFS_HEADER_AVROSCHEMA , avroSchema ) ; record . getHeader ( ) . setAttribute ( HDFS_HEADER_TARGET_DIRECTORY , location ) ; LOG . trace ( \"Record {} will be stored in {} path: roll({}), avro schema: {}\" , record . getHeader ( ) . getSourceId ( ) , location , roll , avroSchema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the given value into the corresponding group - by element of the aggregator . [CODESPLIT] public void process ( String group , T value ) { getData ( ) . process ( ImmutableMap . of ( group , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns if and only if both stage classes have defined the same version . [CODESPLIT] public static boolean isSameVersion ( Class < ? extends Stage > a , Class < ? extends Stage > b ) { StageDef aDef = a . getAnnotation ( StageDef . class ) ; StageDef bDef = b . getAnnotation ( StageDef . class ) ; return aDef . version ( ) == bDef . version ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bootstrapping the Driver which starts a Spark job on Mesos [CODESPLIT] public static void main ( String [ ] args ) throws Exception { BootstrapCluster . printSystemPropsEnvVariables ( ) ; String mesosDir = System . getenv ( \"MESOS_DIRECTORY\" ) ; if ( mesosDir == null ) { throw new IllegalStateException ( \"Expected the env. variable MESOS_DIRECTORY to be defined\" ) ; } File mesosHomeDir = new File ( mesosDir ) ; String sparkDir = System . getenv ( \"SPARK_HOME\" ) ; if ( sparkDir == null ) { throw new IllegalStateException ( \"Expected the env. variable SPARK_HOME to be defined\" ) ; } File sparkHomeDir = new File ( sparkDir ) ; int processExitValue = BootstrapCluster . findAndExtractJar ( mesosHomeDir , sparkHomeDir ) ; if ( processExitValue != 0 ) { throw new IllegalStateException ( \"Process extracting archives from uber jar exited abnormally; check Mesos driver stdout file\" ) ; } System . setProperty ( \"SDC_MESOS_BASE_DIR\" , new File ( mesosHomeDir , BootstrapCluster . SDC_MESOS_BASE_DIR ) . getAbsolutePath ( ) ) ; final Class < ? > clazz = Class . forName ( \"com.streamsets.pipeline.BootstrapClusterStreaming\" ) ; final Method method = clazz . getMethod ( \"main\" , String [ ] . class ) ; method . invoke ( null , new Object [ ] { args } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function is called while thread is waiting at countDownLatch . await in stop () . It cancels tasks change pipeline state and call countDown () so that the waiting thread can proceed to terminate . [CODESPLIT] public void forceQuit ( ) { synchronized ( relatedTasks ) { if ( runningThread != null ) { runningThread . interrupt ( ) ; runningThread = null ; cancelTask ( ) ; postStop ( ) ; } } countDownLatch . countDown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper to apply authentication properties to Jersey client . [CODESPLIT] private void configureAuthAndBuildClient ( ClientBuilder clientBuilder , List < Stage . ConfigIssue > issues ) { if ( jerseyClientConfig . authType == AuthenticationType . OAUTH ) { String consumerKey = jerseyClientConfig . oauth . resolveConsumerKey ( context , \"CREDENTIALS\" , \"conf.oauth.\" , issues ) ; String consumerSecret = jerseyClientConfig . oauth . resolveConsumerSecret ( context , \"CREDENTIALS\" , \"conf.oauth.\" , issues ) ; String token = jerseyClientConfig . oauth . resolveToken ( context , \"CREDENTIALS\" , \"conf.oauth.\" , issues ) ; String tokenSecret = jerseyClientConfig . oauth . resolveTokenSecret ( context , \"CREDENTIALS\" , \"conf.oauth.\" , issues ) ; if ( issues . isEmpty ( ) ) { authToken = JerseyClientUtil . configureOAuth1 ( consumerKey , consumerSecret , token , tokenSecret , clientBuilder ) ; } } else if ( jerseyClientConfig . authType . isOneOf ( AuthenticationType . DIGEST , AuthenticationType . BASIC , AuthenticationType . UNIVERSAL ) ) { String username = jerseyClientConfig . basicAuth . resolveUsername ( context , \"CREDENTIALS\" , \"conf.basicAuth.\" , issues ) ; String password = jerseyClientConfig . basicAuth . resolvePassword ( context , \"CREDENTIALS\" , \"conf.basicAuth.\" , issues ) ; if ( issues . isEmpty ( ) ) { JerseyClientUtil . configurePasswordAuth ( jerseyClientConfig . authType , username , password , clientBuilder ) ; } } try { buildNewAuthenticatedClient ( issues , false ) ; clientInitialized = true ; } catch ( StageException e ) { // should not happen, since we passed throwExceptions as false above ExceptionUtils . throwUndeclared ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the request contains potentially sensitive information such as a vault : read EL . [CODESPLIT] public boolean requestContainsSensitiveInfo ( Map < String , String > headers , String requestBody ) { boolean sensitive = false ; for ( Map . Entry < String , String > header : headers . entrySet ( ) ) { if ( header . getKey ( ) . contains ( VAULT_EL_PREFIX ) || header . getValue ( ) . contains ( VAULT_EL_PREFIX ) ) { sensitive = true ; break ; } } if ( requestBody != null && requestBody . contains ( VAULT_EL_PREFIX ) ) { sensitive = true ; } return sensitive ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates any EL expressions in the headers section of the stage configuration . [CODESPLIT] public MultivaluedMap < String , Object > resolveHeaders ( Map < String , String > headers , Record record ) throws StageException { RecordEL . setRecordInContext ( headerVars , record ) ; MultivaluedMap < String , Object > requestHeaders = new MultivaluedHashMap <> ( ) ; for ( Map . Entry < String , String > entry : headers . entrySet ( ) ) { List < Object > header = new ArrayList <> ( 1 ) ; Object resolvedValue = headerEval . eval ( headerVars , entry . getValue ( ) , String . class ) ; header . add ( resolvedValue ) ; requestHeaders . put ( entry . getKey ( ) , header ) ; } return requestHeaders ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines the HTTP method to use for the next request . It may include an EL expression to evaluate . [CODESPLIT] public HttpMethod getHttpMethod ( HttpMethod httpMethod , String methodExpression , Record record ) throws ELEvalException { if ( httpMethod != HttpMethod . EXPRESSION ) { return httpMethod ; } RecordEL . setRecordInContext ( methodVars , record ) ; return HttpMethod . valueOf ( methodEval . eval ( methodVars , methodExpression , String . class ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add each object of typed null to SimpleBindings so that script languages can use constants such as NULL_INTEGER NULL_LONG without importing other files . [CODESPLIT] public static void fillNullTypes ( SimpleBindings bindings ) { bindings . put ( \"NULL_BOOLEAN\" , NULL_BOOLEAN ) ; bindings . put ( \"NULL_CHAR\" , NULL_CHAR ) ; bindings . put ( \"NULL_BYTE\" , NULL_BYTE ) ; bindings . put ( \"NULL_SHORT\" , NULL_SHORT ) ; bindings . put ( \"NULL_INTEGER\" , NULL_INTEGER ) ; bindings . put ( \"NULL_LONG\" , NULL_LONG ) ; bindings . put ( \"NULL_FLOAT\" , NULL_FLOAT ) ; bindings . put ( \"NULL_DOUBLE\" , NULL_DOUBLE ) ; bindings . put ( \"NULL_DATE\" , NULL_DATE ) ; bindings . put ( \"NULL_DATETIME\" , NULL_DATETIME ) ; bindings . put ( \"NULL_TIME\" , NULL_TIME ) ; bindings . put ( \"NULL_DECIMAL\" , NULL_DECIMAL ) ; bindings . put ( \"NULL_BYTE_ARRAY\" , NULL_BYTE_ARRAY ) ; bindings . put ( \"NULL_STRING\" , NULL_STRING ) ; bindings . put ( \"NULL_LIST\" , NULL_LIST ) ; bindings . put ( \"NULL_MAP\" , NULL_MAP ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive record and fieldPath from scripting processor . It resolves type of the field and if value is null it returns one of the NULL_XXX objects defined in this class . If field value is not null it returns the value stored in the field . [CODESPLIT] public static Object getFieldNull ( Record record , String fieldPath ) { Field f = record . get ( fieldPath ) ; if ( f != null ) { return f . getValue ( ) == null ? getTypedNullFromField ( f ) : f . getValue ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive a scriptOject and find out if the scriptObect is one of the NULL_ ** object defined in this class . If so create a new field with the type and null value then return the field . If the scriptObject is not one of the typed null object it returns a new field with string converted from the value . [CODESPLIT] public static Field getTypedNullFieldFromScript ( Object scriptObject ) { Field field ; if ( scriptObject == NULL_BOOLEAN ) field = Field . create ( Field . Type . BOOLEAN , null ) ; else if ( scriptObject == NULL_CHAR ) field = Field . create ( Field . Type . CHAR , null ) ; else if ( scriptObject == NULL_BYTE ) field = Field . create ( Field . Type . BYTE , null ) ; else if ( scriptObject == NULL_SHORT ) field = Field . create ( Field . Type . SHORT , null ) ; else if ( scriptObject == NULL_INTEGER ) field = Field . create ( Field . Type . INTEGER , null ) ; else if ( scriptObject == NULL_LONG ) field = Field . create ( Field . Type . LONG , null ) ; else if ( scriptObject == NULL_FLOAT ) field = Field . create ( Field . Type . FLOAT , null ) ; else if ( scriptObject == NULL_DOUBLE ) field = Field . create ( Field . Type . DOUBLE , null ) ; else if ( scriptObject == NULL_DATE ) field = Field . createDate ( null ) ; else if ( scriptObject == NULL_DATETIME ) field = Field . createDatetime ( null ) ; else if ( scriptObject == NULL_TIME ) field = Field . createTime ( null ) ; else if ( scriptObject == NULL_DECIMAL ) field = Field . create ( Field . Type . DECIMAL , null ) ; else if ( scriptObject == NULL_BYTE_ARRAY ) field = Field . create ( Field . Type . BYTE_ARRAY , null ) ; else if ( scriptObject == NULL_STRING ) field = Field . create ( Field . Type . STRING , null ) ; else if ( scriptObject == NULL_LIST ) field = Field . create ( Field . Type . LIST , null ) ; else if ( scriptObject == NULL_MAP ) field = Field . create ( Field . Type . MAP , null ) ; else //this scriptObject is not Null typed field. Return null. field = null ; return field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns an { [CODESPLIT] public Field getDateTimeStampField ( String column , String columnValue , int columnType , String actualType ) throws StageException { Field . Type type ; if ( DATE . equalsIgnoreCase ( actualType ) ) { type = Field . Type . DATE ; } else if ( TIME . equalsIgnoreCase ( actualType ) ) { type = Field . Type . TIME ; } else if ( TIMESTAMP . equalsIgnoreCase ( actualType ) ) { type = Field . Type . DATETIME ; } else { throw new StageException ( JDBC_37 , columnType , column ) ; } if ( columnValue == null ) { return Field . create ( type , null ) ; } else { Optional < String > ts = matchDateTimeString ( toTimestampPattern . matcher ( columnValue ) ) ; if ( ts . isPresent ( ) ) { if ( timestampAsString ) { return Field . create ( Field . Type . STRING , ts . get ( ) ) ; } Timestamp timestamp = Timestamp . valueOf ( ts . get ( ) ) ; Field field = Field . create ( type , timestamp ) ; JdbcUtil . setNanosecondsinAttribute ( timestamp . getNanos ( ) , field ) ; return field ; } // We did not find TO_TIMESTAMP, so try TO_DATE Optional < String > dt = matchDateTimeString ( toDatePattern . matcher ( columnValue ) ) ; return Field . create ( Field . Type . DATE , dt . map ( s -> Date . from ( getDate ( s ) . atZone ( zoneId ) . toInstant ( ) ) ) . orElse ( null ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses and returns an Avro schema loaded from the schema registry using the provided schema ID if available or the latest version of a schema for the specified subject . [CODESPLIT] public Schema loadFromRegistry ( String subject , int schemaId ) throws SchemaRegistryException { try { if ( isEmpty ( subject ) ) { return loadFromRegistry ( schemaId ) ; } else { return loadFromRegistry ( subject ) ; } } catch ( SchemaRegistryException e ) { throw new SchemaRegistryException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a parsed schema with the schema registry under the specified subject . [CODESPLIT] public int registerSchema ( Schema schema , String subject ) throws SchemaRegistryException { try { return schemaIdCache . get ( subject + schema . hashCode ( ) , ( ) -> registryClient . register ( subject , schema ) ) ; } catch ( ExecutionException e ) { throw new SchemaRegistryException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads and parses a schema for the specified subject from the schema registry [CODESPLIT] public Schema loadFromRegistry ( String subject ) throws SchemaRegistryException { try { SchemaMetadata metadata = registryClient . getLatestSchemaMetadata ( subject ) ; return registryClient . getByID ( metadata . getId ( ) ) ; } catch ( IOException | RestClientException e ) { throw new SchemaRegistryException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up schema id for the specified subject from the schema registry [CODESPLIT] public int getSchemaIdFromSubject ( String subject ) throws SchemaRegistryException { try { SchemaMetadata metadata = registryClient . getLatestSchemaMetadata ( subject ) ; return metadata . getId ( ) ; } catch ( IOException | RestClientException e ) { throw new SchemaRegistryException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads and parses a schema for the specified schema ID from the schema registry [CODESPLIT] public Schema loadFromRegistry ( int id ) throws SchemaRegistryException { try { return registryClient . getByID ( id ) ; } catch ( IOException | RestClientException e ) { throw new SchemaRegistryException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the magic byte and schema ID to an output stream replicating the functionality of the Confluent Kafka Avro Serializer [CODESPLIT] public int writeSchemaId ( OutputStream os , int schemaId ) throws IOException { if ( schemaId > 0 ) { os . write ( MAGIC_BYTE ) ; os . write ( ByteBuffer . allocate ( ID_SIZE ) . putInt ( schemaId ) . array ( ) ) ; } return schemaId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for a magic byte in the data and if present extracts the schemaId [CODESPLIT] public Optional < Integer > detectSchemaId ( byte [ ] data ) { if ( data . length < 5 ) { return Optional . empty ( ) ; } ByteBuffer wrapped = ByteBuffer . wrap ( data ) ; // 5 == MAGIC_BYTE + ID_SIZE if ( wrapped . get ( ) != MAGIC_BYTE ) { return Optional . empty ( ) ; } return Optional . of ( wrapped . getInt ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to extract default values from a Schema . This is normally done in DataGeneratorFormat validation however we have to do it at runtime for Schema Registry . [CODESPLIT] public static Map < String , Object > getDefaultValues ( Schema schema ) throws SchemaRegistryException { Map < String , Object > defaultValues = new HashMap <> ( ) ; try { defaultValues . putAll ( AvroTypeUtil . getDefaultValuesFromSchema ( schema , new HashSet < String > ( ) ) ) ; } catch ( IOException e ) { throw new SchemaRegistryException ( e ) ; } return defaultValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method to parse all available records in given payload . This method assumes that the stage already depends on DataFormatParserService service and loads the service instance from Stage . Context . [CODESPLIT] public static List < Record > parseAll ( Stage . Context stageContext , ToErrorContext toErrorContext , boolean produceSingleRecordPerMessage , String messageId , byte [ ] payload ) throws StageException { List < Record > records = new ArrayList <> ( ) ; try ( DataParser parser = stageContext . getService ( DataFormatParserService . class ) . getParser ( messageId , payload ) ) { Record record = null ; do { try { record = parser . parse ( ) ; } catch ( RecoverableDataParserException e ) { handleException ( stageContext , toErrorContext , messageId , e , e . getUnparsedRecord ( ) ) ; //Go to next record continue ; } if ( record != null ) { records . add ( record ) ; } } while ( record != null ) ; } catch ( IOException | DataParserException ex ) { Record record = stageContext . createRecord ( messageId ) ; record . set ( Field . create ( payload ) ) ; handleException ( stageContext , toErrorContext , messageId , ex , record ) ; return records ; } if ( produceSingleRecordPerMessage ) { List < Field > list = new ArrayList <> ( ) ; for ( Record record : records ) { list . add ( record . get ( ) ) ; } Record record = records . get ( 0 ) ; record . set ( Field . create ( list ) ) ; records . clear ( ) ; records . add ( record ) ; } return records ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate small report into log . [CODESPLIT] public void logDetails ( ) { if ( isValid ( ) ) { return ; } LOG . warn ( \"Validation results for {}\" , name ) ; if ( ! unparseablePaths . isEmpty ( ) ) { LOG . warn ( \"Can't parse the following artifacts:\" ) ; for ( String path : unparseablePaths ) { LOG . warn ( \"  {}\" , path ) ; } } if ( ! versionCollisions . isEmpty ( ) ) { LOG . warn ( \"Detected colliding dependency versions:\" ) ; for ( Map . Entry < String , Map < String , List < Dependency > > > entry : versionCollisions . entrySet ( ) ) { LOG . warn ( \"  Dependency {} have versions: {}\" , entry . getKey ( ) , StringUtils . join ( entry . getValue ( ) . keySet ( ) , \", \" ) ) ; for ( Map . Entry < String , List < Dependency > > versionEntry : entry . getValue ( ) . entrySet ( ) ) { LOG . warn ( \"    Version: {}\" , versionEntry . getKey ( ) ) ; for ( Dependency dependency : versionEntry . getValue ( ) ) { LOG . warn ( \"      {}\" , dependency . getSourceName ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove initial / replace all other slashes with dots [CODESPLIT] private String toFieldName ( String fieldPath ) { String path = fieldPath . substring ( 1 ) . replaceAll ( \"/\" , \".\" ) ; path = \"/\" + path ; return EscapeUtil . getLastFieldNameFromPath ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the parameters for this config bean . [CODESPLIT] public void init ( Source . Context context , String groupName , String prefix , List < Stage . ConfigIssue > issues ) { // Validate the ELs for string configs List < String > elConfigs = ImmutableList . of ( \"resourceUrl\" , \"requestBody\" ) ; for ( String configName : elConfigs ) { ELVars vars = context . createELVars ( ) ; vars . addVariable ( START_AT , 0 ) ; ELEval eval = context . createELEval ( configName ) ; try { eval . eval ( vars , ( String ) getClass ( ) . getField ( configName ) . get ( this ) , String . class ) ; } catch ( ELEvalException | NoSuchFieldException | IllegalAccessException e ) { LOG . error ( Errors . HTTP_06 . getMessage ( ) , e . toString ( ) , e ) ; issues . add ( context . createConfigIssue ( groupName , prefix + configName , Errors . HTTP_06 , e . toString ( ) ) ) ; } } client . init ( context , Groups . PROXY . name ( ) , prefix + \"client.\" , issues ) ; // Validate the EL for each header entry ELVars headerVars = context . createELVars ( ) ; ELEval headerEval = context . createELEval ( \"headers\" ) ; for ( String headerValue : headers . values ( ) ) { try { headerEval . eval ( headerVars , headerValue , String . class ) ; } catch ( ELEvalException e ) { LOG . error ( Errors . HTTP_06 . getMessage ( ) , e . toString ( ) , e ) ; issues . add ( context . createConfigIssue ( groupName , prefix + \"headers\" , Errors . HTTP_06 , e . toString ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for the Jersey client to complete an asynchronous request checks the response code and continues to parse the response if it is deemed ok . [CODESPLIT] private void processResponse ( Record record , Future < Response > responseFuture , long maxRequestCompletionSecs , boolean failOn403 ) throws StageException { Response response ; try { response = responseFuture . get ( maxRequestCompletionSecs , TimeUnit . SECONDS ) ; String responseBody = \"\" ; if ( response . hasEntity ( ) ) { responseBody = response . readEntity ( String . class ) ; } response . close ( ) ; if ( conf . client . useOAuth2 && response . getStatus ( ) == 403 && ! failOn403 ) { HttpStageUtil . getNewOAuth2Token ( conf . client . oauth2 , httpClientCommon . getClient ( ) ) ; } else if ( response . getStatus ( ) < 200 || response . getStatus ( ) >= 300 ) { throw new OnRecordErrorException ( record , Errors . HTTP_40 , response . getStatus ( ) , response . getStatusInfo ( ) . getReasonPhrase ( ) + \" \" + responseBody ) ; } else { if ( conf . responseConf . sendResponseToOrigin ) { if ( ResponseType . SUCCESS_RECORDS . equals ( conf . responseConf . responseType ) ) { getContext ( ) . toSourceResponse ( record ) ; } else { getContext ( ) . toSourceResponse ( createResponseRecord ( responseBody ) ) ; } } } } catch ( InterruptedException | ExecutionException e ) { LOG . error ( Errors . HTTP_41 . getMessage ( ) , e . toString ( ) , e ) ; throw new OnRecordErrorException ( record , Errors . HTTP_41 , e . toString ( ) ) ; } catch ( TimeoutException e ) { LOG . error ( \"HTTP request future timed out\" , e . toString ( ) , e ) ; throw new OnRecordErrorException ( record , Errors . HTTP_41 , e . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "delete record have / OldData [CODESPLIT] private String binLogRecordFieldtoSdc ( String fieldPath , int operation ) { if ( operation == KuduOperationType . DELETE . code ) { return \"/OldData\" + fieldPath ; } return fieldPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate list of error records from the error sink . What precise records will be returned depends on the error record policy configuration . [CODESPLIT] private List < Record > getBadRecords ( ErrorSink errorSink ) { List < Record > badRecords = new ArrayList <> ( ) ; for ( Map . Entry < String , List < Record > > entry : errorSink . getErrorRecords ( ) . entrySet ( ) ) { for ( Record record : entry . getValue ( ) ) { RecordImpl errorRecord ; switch ( errorRecordPolicy ) { case ORIGINAL_RECORD : errorRecord = ( RecordImpl ) ( ( RecordImpl ) record ) . getHeader ( ) . getSourceRecord ( ) ; errorRecord . getHeader ( ) . copyErrorFrom ( record ) ; break ; case STAGE_RECORD : errorRecord = ( RecordImpl ) record ; break ; default : throw new IllegalArgumentException ( \"Uknown error record policy: \" + errorRecordPolicy ) ; } errorRecord . getHeader ( ) . setErrorContext ( runtimeInfo . getId ( ) , pipelineName ) ; badRecords . add ( errorRecord ) ; } } return badRecords ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actual comparison with the same semantics as compareTo () method . [CODESPLIT] public int compare ( Version other ) { int maxParts = Math . max ( this . versions . length , other . versions . length ) ; for ( int i = 0 ; i < maxParts ; i ++ ) { int eq = this . getVersionPosition ( i ) - other . getVersionPosition ( i ) ; if ( eq != 0 ) { if ( eq > 0 ) { return 1 ; } else { return - 1 ; } } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the schema generator [CODESPLIT] public List < Stage . ConfigIssue > init ( SchemaGeneratorConfig config , Stage . Context context ) { this . config = config ; return Collections . emptyList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the outward flowing edge vertices . [CODESPLIT] public Collection < V > getOutwardEdgeVertices ( V vertex ) { Collection < V > outwardEdgeVerticesForVertex = outwardEdgeVertices . get ( vertex ) ; return outwardEdgeVerticesForVertex != null ? outwardEdgeVerticesForVertex : Collections . < V > emptySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the inward flowing edge vertices . [CODESPLIT] public Collection < V > getInwardEdgeVertices ( V vertex ) { Collection < V > inwardEdgeVerticesForVertex = inwardEdgesVertices . get ( vertex ) ; return inwardEdgeVerticesForVertex != null ? inwardEdgeVerticesForVertex : Collections . < V > emptySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a directed edge from vertex1 to vertex2 adding those vertices graph ( if needed ) [CODESPLIT] public void addDirectedEdge ( V vertex1 , V vertex2 ) { addVertex ( vertex1 ) ; addVertex ( vertex2 ) ; outwardEdgeVertices . put ( vertex1 , vertex2 ) ; inwardEdgesVertices . put ( vertex2 , vertex1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the Map of table to offset to a String [CODESPLIT] public static String serializeOffsetMap ( Map < String , String > offsetMap ) throws IOException { return JSON_MAPPER . writeValueAsString ( offsetMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize String offset to Map of table to offset [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Map < String , String > deserializeOffsetMap ( String lastSourceOffset ) throws IOException { Map < String , String > offsetMap ; if ( lastSourceOffset == null || lastSourceOffset . isEmpty ( ) ) { offsetMap = new HashMap <> ( ) ; } else { offsetMap = JSON_MAPPER . readValue ( lastSourceOffset , Map . class ) ; } return offsetMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue a report using the Report . Queue method . This will post a request with the report description to the Omniture API and return a report ID that can be used to retrieve the report once it s ready . [CODESPLIT] public int queueReport ( ) throws IOException , InterruptedException , ExecutionException , TimeoutException , StageException { final AsyncInvoker asyncInvoker = queueResource . request ( ) . header ( WSSE_HEADER , OmnitureAuthUtil . getHeader ( username . get ( ) , sharedSecret . get ( ) ) ) . async ( ) ; LOG . debug ( \"Queueing report using URL {} with description {}\" , queueResource . getUri ( ) . toURL ( ) . toString ( ) , reportDescription ) ; final Future < Response > responseFuture = asyncInvoker . post ( Entity . json ( reportDescription ) ) ; Response response = responseFuture . get ( responseTimeoutMillis , TimeUnit . MILLISECONDS ) ; if ( response == null ) { LOG . error ( \"Failed to get response using URL {}\" , queueResource . getUri ( ) . toURL ( ) . toString ( ) ) ; throw new StageException ( Errors . OMNITURE_01 , \"HTTP response was null\" ) ; } LOG . debug ( \"Received response: status {}\" , response . getStatus ( ) ) ; ObjectMapper mapper = new ObjectMapper ( ) ; String json = response . readEntity ( String . class ) ; LOG . trace ( \"Response JSON: {}\" , json ) ; JsonNode root = mapper . readTree ( json ) ; if ( root == null ) { LOG . error ( \"Invalid JSON in response: {}\" , json ) ; throw new StageException ( Errors . OMNITURE_01 , json ) ; } if ( root . has ( \"error\" ) ) { throw new StageException ( Errors . OMNITURE_01 , root . get ( \"error_description\" ) . asText ( ) ) ; } LOG . info ( \"Omniture report queued\" ) ; return root . get ( \"reportID\" ) . asInt ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Posts a request to the Omniture API to get a report back . Reports may take a while to generate so this will loop on the Report . Get request and ignore any errors indicating that the report is not yet ready . [CODESPLIT] public void getReport ( int reportId ) throws InterruptedException , ExecutionException , TimeoutException , IOException , StageException { int waitTime = 1000 ; Response response = null ; while ( ! stop ) { final AsyncInvoker asyncInvoker = getResource . request ( ) . header ( WSSE_HEADER , OmnitureAuthUtil . getHeader ( username . get ( ) , sharedSecret . get ( ) ) ) . async ( ) ; LOG . debug ( \"Getting report using URL {} with report ID {}\" , getResource . getUri ( ) . toURL ( ) . toString ( ) , reportId ) ; final Future < Response > responseFuture = asyncInvoker . post ( Entity . json ( \"{ \\\"reportID\\\": \" + reportId + \" }\" ) ) ; response = responseFuture . get ( responseTimeoutMillis , TimeUnit . MILLISECONDS ) ; String input = response . readEntity ( String . class ) ; ObjectMapper mapper = new ObjectMapper ( ) ; JsonNode root = mapper . readTree ( input ) ; // If the report has an error field, it means the report has not finished generating if ( ! root . has ( \"error\" ) ) { boolean accepted = entityQueue . offer ( input , responseTimeoutMillis , TimeUnit . MILLISECONDS ) ; if ( ! accepted ) { LOG . warn ( \"Response buffer full, dropped record.\" ) ; } break ; } else { // Exponential backoff while making subsequent Report.Get requests if ( root . get ( \"error\" ) . textValue ( ) . equals ( \"report_not_ready\" ) ) { waitTime *= 2 ; LOG . info ( \"Report not available. Sleeping for {} seconds\" , waitTime / 1000 ) ; Thread . sleep ( waitTime ) ; } else { throw new StageException ( Errors . OMNITURE_02 , root . get ( \"error\" ) . get ( \"error_description\" ) . asText ( ) ) ; } } } response . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This tell us SDC is check pointing [CODESPLIT] public boolean isSDCCheckPointing ( ) { try { return fs . exists ( checkPointFilePath ) || fs . exists ( backupCheckPointFilePath ) ; } catch ( IOException ex ) { LOG . error ( \"Error doing isSDCCheckPointing\" , ex ) ; throw new RuntimeException ( Utils . format ( \"Error checking exists on hdfs path: {}. Reason: {}\" , checkPointFilePath . toString ( ) , ex . toString ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Or if the file is corrupted we want to update the right offsets to the main offset file . [CODESPLIT] private void writeOffsetsToMainOffsetFile ( Map < Integer , Long > partitionToOffsetMap ) throws IOException { LOG . info ( \"Saving the following offset {} to {}\" , partitionToOffsetMap , checkPointFilePath ) ; //Creating a marker file (overwriting if it already exists) to mark that we are going to write offsets out the offsets to the main offset file. try ( OutputStream os = fs . create ( checkPointMarkerFilePath , true ) ) { //NOOP } //If the both above passes and writing fails or leaves corrupted file we will have the back file try ( OutputStream os = fs . create ( checkPointFilePath , true ) ) { OBJECT_MAPPER . writeValue ( os , new ClusterSourceOffsetJson ( serializeKafkaPartitionOffset ( partitionToOffsetMap ) , SDC_STREAMING_OFFSET_VERSION ) ) ; } //If this fails we are still good, as we will start from the backup offset file. (Not optimal, but deterministic) boolean deleted = fs . delete ( checkPointMarkerFilePath , false ) ; LOG . warn ( \"Status {} for Deleting Marker File {}\" , deleted , checkPointMarkerFilePath ) ; //If the write fails we don't want to touch the timestamp and will error out so not doing this in finally lastOffsetStoredTime = System . currentTimeMillis ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ex : Partition Offset empty empty map in the offset cannot deserialize [CODESPLIT] private Map < Integer , Long > readClusterOffsetFile ( Path checkPointFilePath , int numberOfPartitions ) throws IOException { if ( ! fs . exists ( checkPointFilePath ) ) { throw new IOException ( Utils . format ( \"Checkpoint file path {} does not exist\" , checkPointFilePath ) ) ; } ClusterSourceOffsetJson clusterSourceOffsetJson = OBJECT_MAPPER . readValue ( ( InputStream ) fs . open ( checkPointFilePath ) , ClusterSourceOffsetJson . class ) ; String lastSourceOffset = clusterSourceOffsetJson . getOffset ( ) ; if ( ! StringUtils . isEmpty ( lastSourceOffset ) ) { return deserializeKafkaPartitionOffset ( lastSourceOffset , numberOfPartitions ) ; } else { throw new IOException ( \"Partition Offset Cannot be empty\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create { [CODESPLIT] public TableOrderProvider create ( ) { switch ( tableOrderStrategy ) { case NONE : //Don't do any ordering, just add tables as per the incoming order. return new DefaultTableOrderProvider ( new LinkedHashSet <> ( ) ) ; case ALPHABETICAL : //Alphabetical sorting based on table qualified names. return new DefaultTableOrderProvider ( new TreeSet <> ( ) ) ; case REFERENTIAL_CONSTRAINTS : return new ReferentialTblOrderProvider ( connection ) ; default : throw new IllegalArgumentException ( Utils . format ( \"Unknown table order strategy: {}\" , tableOrderStrategy ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a blob for gcs [CODESPLIT] private void delete ( BlobId blobId ) { LOG . debug ( \"Deleting object '{}'\" , String . format ( BLOB_PATH_TEMPLATE , blobId . getBucket ( ) , blobId . getName ( ) ) ) ; boolean deleted = storage . delete ( blobId ) ; if ( ! deleted ) { LOG . error ( \"Cannot delete object '{}'\" , String . format ( BLOB_PATH_TEMPLATE , blobId . getBucket ( ) , blobId . getName ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy a blob for gcs to a destination bucket and a path ( and delete the source blob if needed ) [CODESPLIT] private void copy ( BlobId sourceBlobId , String destinationBucket , String destinationPath , boolean deleteSource ) { LOG . debug ( \"Copying object '{}' to Object '{}'\" , String . format ( BLOB_PATH_TEMPLATE , sourceBlobId . getBucket ( ) , sourceBlobId . getName ( ) ) , String . format ( BLOB_PATH_TEMPLATE , destinationBucket , destinationPath ) ) ; Storage . CopyRequest copyRequest = new Storage . CopyRequest . Builder ( ) . setSource ( sourceBlobId ) . setTarget ( BlobId . of ( destinationBucket , destinationPath ) ) . build ( ) ; Blob destinationBlob = storage . copy ( copyRequest ) . getResult ( ) ; LOG . debug ( \"Copied object '{}' to Object '{}'\" , String . format ( BLOB_PATH_TEMPLATE , sourceBlobId . getBucket ( ) , sourceBlobId . getName ( ) ) , String . format ( BLOB_PATH_TEMPLATE , destinationBlob . getBlobId ( ) . getBucket ( ) , destinationBlob . getBlobId ( ) . getName ( ) ) ) ; if ( deleteSource ) { delete ( sourceBlobId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle error Blob [CODESPLIT] void handleError ( BlobId blobId ) { switch ( gcsOriginErrorConfig . errorHandlingOption ) { case NONE : break ; case ARCHIVE : handleArchive ( blobId ) ; break ; case DELETE : delete ( blobId ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Archive the blob [CODESPLIT] private void handleArchive ( BlobId blobId ) { String destinationPath = getDestinationPath ( blobId , gcsOriginErrorConfig . errorPrefix ) ; switch ( gcsOriginErrorConfig . archivingOption ) { case COPY_TO_BUCKET : copy ( blobId , gcsOriginErrorConfig . errorBucket , destinationPath , false ) ; break ; case MOVE_TO_BUCKET : copy ( blobId , gcsOriginErrorConfig . errorBucket , destinationPath , true ) ; break ; case COPY_TO_PREFIX : copy ( blobId , blobId . getBucket ( ) , destinationPath , false ) ; break ; case MOVE_TO_PREFIX : copy ( blobId , blobId . getBucket ( ) , destinationPath , true ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prepares and gets the reader if available before a read . [CODESPLIT] public LiveFileReader getReader ( ) throws IOException { Utils . checkState ( open , \"FileContext is closed\" ) ; if ( reader == null ) { currentFile = getStartingCurrentFileName ( ) ; long fileOffset = getStartingOffset ( ) ; boolean needsToScan = currentFile == null || fileOffset == Long . MAX_VALUE ; if ( needsToScan ) { if ( currentFile != null ) { // we need to refresh the file in case the name changed before scanning as the scanner does not refresh currentFile = currentFile . refresh ( ) ; } currentFile = scanner . scan ( currentFile ) ; fileOffset = 0 ; } if ( currentFile != null ) { reader = new SingleLineLiveFileReader ( getRollMode ( ) , getMultiFileInfo ( ) . getTag ( ) , currentFile , charset , fileOffset , maxLineLength ) ; if ( ! multiFileInfo . getMultiLineMainLinePatter ( ) . isEmpty ( ) ) { reader = new MultiLineLiveFileReader ( getMultiFileInfo ( ) . getTag ( ) , reader , Pattern . compile ( multiFileInfo . getMultiLineMainLinePatter ( ) ) ) ; } if ( fileOffset == 0 ) { // file start event eventPublisher . publish ( new FileEvent ( currentFile , FileEvent . Action . START ) ) ; } } } return reader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "updates reader and offsets after a read . [CODESPLIT] public void releaseReader ( boolean inErrorDiscardReader ) throws IOException { Utils . checkState ( open , \"FileContext is closed\" ) ; // update starting offsets for next invocation either cold (no reader) or hot (reader) boolean hasNext ; try { hasNext = reader != null && reader . hasNext ( ) ; } catch ( IOException ex ) { IOUtils . closeQuietly ( reader ) ; reader = null ; hasNext = false ; } boolean doneWithFile = ! hasNext || inErrorDiscardReader ; if ( doneWithFile ) { IOUtils . closeQuietly ( reader ) ; reader = null ; // Using Long.MAX_VALUE to signal we reach the end of the file and next iteration should get the next file. setStartingCurrentFileName ( currentFile ) ; setStartingOffset ( Long . MAX_VALUE ) ; // If we failed to open the file in first place, it will be null and hence we won't do anything with it. if ( currentFile == null ) { return ; } // File end event LiveFile file = currentFile . refresh ( ) ; if ( inErrorDiscardReader ) { LOG . warn ( \"Processing file '{}' produced an error, skipping '{}' post processing on that file\" , file , postProcessing ) ; eventPublisher . publish ( new FileEvent ( file , FileEvent . Action . ERROR ) ) ; } else { eventPublisher . publish ( new FileEvent ( file , FileEvent . Action . END ) ) ; switch ( postProcessing ) { case NONE : LOG . debug ( \"File '{}' processing completed, post processing action 'NONE'\" , file ) ; break ; case DELETE : if ( ! inPreviewMode ) { try { Files . delete ( file . getPath ( ) ) ; LOG . debug ( \"File '{}' processing completed, post processing action 'DELETED'\" , file ) ; } catch ( IOException ex ) { throw new IOException ( Utils . format ( \"Could not delete '{}': {}\" , file , ex . toString ( ) ) , ex ) ; } } break ; case ARCHIVE : if ( ! inPreviewMode ) { Path fileArchive = Paths . get ( archiveDir , file . getPath ( ) . toString ( ) ) ; if ( fileArchive == null ) { throw new IOException ( \"Could not find archive file\" ) ; } try { Files . createDirectories ( fileArchive . getParent ( ) ) ; Files . move ( file . getPath ( ) , fileArchive ) ; LOG . debug ( \"File '{}' processing completed, post processing action 'ARCHIVED' as\" , file ) ; } catch ( IOException ex ) { throw new IOException ( Utils . format ( \"Could not archive '{}': {}\" , file , ex . toString ( ) ) , ex ) ; } } break ; } } } else { setStartingCurrentFileName ( currentFile ) ; setStartingOffset ( getReader ( ) . getOffset ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to set dpmBaseURL for the first HTTP DPM authentication . [CODESPLIT] public ApiClient setDPMBaseURL ( String dpmBaseURL ) { if ( dpmBaseURL != null && authentication != null ) { authentication . setDPMBaseURL ( dpmBaseURL ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a default header . [CODESPLIT] public ApiClient addDefaultHeader ( String key , String value ) { defaultHeaderMap . put ( key , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given string into Date object . [CODESPLIT] public Date parseDate ( String str ) { try { return dateFormat . parse ( str ) ; } catch ( java . text . ParseException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select the Accept header s value from the given accepts array : if JSON exists in the given array use it ; otherwise use all of them ( joining into a string ) [CODESPLIT] public String selectHeaderAccept ( String [ ] accepts ) { if ( accepts . length == 0 ) return null ; if ( StringUtil . containsIgnoreCase ( accepts , \"application/json\" ) ) return \"application/json\" ; return StringUtil . join ( accepts , \",\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select the Content - Type header s value from the given array : if JSON exists in the given array use it ; otherwise use the first one of the array . [CODESPLIT] public String selectHeaderContentType ( String [ ] contentTypes ) { if ( contentTypes . length == 0 ) return \"application/json\" ; if ( StringUtil . containsIgnoreCase ( contentTypes , \"application/json\" ) ) return \"application/json\" ; return contentTypes [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape the given string to be used as URL query value . [CODESPLIT] public String escapeString ( String str ) { try { return URLEncoder . encode ( str , \"utf8\" ) . replaceAll ( \"\\\\+\" , \"%20\" ) ; } catch ( UnsupportedEncodingException e ) { return str ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the given Java object into string according the given Content - Type ( only JSON is supported for now ) . [CODESPLIT] public String serialize ( Object obj , String contentType ) throws ApiException { if ( contentType . startsWith ( \"application/json\" ) ) { return json . serialize ( obj ) ; } else { throw new ApiException ( 400 , \"can not serialize object into Content-Type: \" + contentType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize response body to Java object according to the Content - Type . [CODESPLIT] private < T > T deserialize ( Response response , TypeRef returnType ) throws ApiException { String contentType = null ; List < Object > contentTypes = response . getHeaders ( ) . get ( \"Content-Type\" ) ; if ( contentTypes != null && ! contentTypes . isEmpty ( ) ) { contentType = ( String ) contentTypes . get ( 0 ) ; } if ( contentType == null ) { throw new ApiException ( 500 , \"missing Content-Type in response\" ) ; } if ( contentType . startsWith ( \"application/json\" ) ) { String body ; if ( response . hasEntity ( ) ) { body = response . readEntity ( String . class ) ; } else { body = \"\" ; } if ( body . length ( ) > 0 ) { return json . deserialize ( body , returnType ) ; } return null ; } if ( contentType . startsWith ( \"image\" ) ) { return ( T ) response . readEntity ( InputStream . class ) ; } else { throw new ApiException ( 500 , \"can not deserialize Content-Type: \" + contentType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an existing client or create a new client to handle HTTP request . [CODESPLIT] private Client getClient ( ) { if ( ! hostMap . containsKey ( basePath ) ) { ClientConfig config = new ClientConfig ( ) ; config . property ( ClientProperties . SUPPRESS_HTTP_COMPLIANCE_VALIDATION , true ) ; Client client = ClientBuilder . newClient ( config ) ; client . register ( new CsrfProtectionFilter ( \"CSRF\" ) ) ; hostMap . put ( basePath , client ) ; } return hostMap . get ( basePath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connect to the database [CODESPLIT] private GPUdb initConnection ( KineticaConfigBean conf ) throws GPUdbException , StageException { KineticaConnectionUtils kineticaConnectionUtils = new KineticaConnectionUtils ( ) ; return kineticaConnectionUtils . getGPUdb ( conf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get metadata for the table [CODESPLIT] private void getTableMetadata ( GPUdb gpudb , String tableName ) throws GPUdbException { KineticaTableUtils kineticaTableUtils = new KineticaTableUtils ( gpudb , tableName ) ; type = kineticaTableUtils . getType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a BulkInserter [CODESPLIT] private BulkInserter < IndexedRecord > createBulkInserter ( GPUdb gpudb , Type type , KineticaConfigBean conf ) throws GPUdbException { KineticaBulkInserterUtils kineticaBulkInserterUtils = new KineticaBulkInserterUtils ( gpudb , type , conf ) ; return kineticaBulkInserterUtils . createBulkInserter ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new event record according for this stage context and event context . [CODESPLIT] public EventBuilder create ( Stage . Context context , ToEventContext toEvent ) { return new EventBuilder ( context , toEvent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a schema with type record . This will be the top level schema and contains fields [CODESPLIT] public static Schema buildSchema ( Map < String , Schema > fields , Object ... levels ) { List < Schema . Field > recordFields = new ArrayList <> ( fields . size ( ) ) ; for ( Map . Entry < String , Schema > entry : fields . entrySet ( ) ) { recordFields . add ( new Schema . Field ( entry . getKey ( ) , entry . getValue ( ) , null , // Avro's Schema.Field constructor requires doc. entry . getValue ( ) . getJsonProp ( \"default\" ) ) ) ; } Schema recordSchema ; if ( levels . length == 0 ) { recordSchema = Schema . createRecord ( schemaName , null , null , false ) ; } else { LinkedList < String > lvl = ( LinkedList < String > ) levels [ 0 ] ; recordSchema = Schema . createRecord ( joiner . join ( lvl ) , null , null , false ) ; } recordSchema . setFields ( recordFields ) ; return recordSchema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is called when JDBC target didn t find sdc . operation . code in record header but found oracle . cdc . operation . Since oracle . cdc . operation contains Oracle specific operation code we need to convert to SDC operation code . [CODESPLIT] public static int convertFromOracleToSDCCode ( String code ) { try { int intCode = Integer . parseInt ( code ) ; switch ( intCode ) { case INSERT_CODE : return OperationType . INSERT_CODE ; case DELETE_CODE : return OperationType . DELETE_CODE ; case UPDATE_CODE : case SELECT_FOR_UPDATE_CODE : return OperationType . UPDATE_CODE ; default : //DDL_CODE throw new UnsupportedOperationException ( Utils . format ( \"Operation code {} is not supported\" , code ) ) ; } } catch ( NumberFormatException ex ) { throw new NumberFormatException ( \"Operation code must be a numeric value. \" + ex . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add jars containing the following classes to the job s classpath . [CODESPLIT] public static void addJarsToJob ( Configuration conf , Class ... klasses ) { // Build set of jars that needs to be added, order doesn't matter for us and we will remove duplicates Set < String > additinonalJars = new HashSet <> ( ) ; for ( Class klass : klasses ) { final String jar = jarForClass ( klass ) ; LOG . info ( \"Adding jar {} for class {}\" , jar , klass . getCanonicalName ( ) ) ; additinonalJars . add ( jar ) ; } appendJars ( conf , additinonalJars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add jars whose names contain the given patterns to the job s classpath . [CODESPLIT] public static void addJarsToJob ( Configuration conf , boolean allowMultiple , String ... jarPatterns ) { final ClassLoader loader = MapreduceUtils . class . getClassLoader ( ) ; if ( ! ( loader instanceof URLClassLoader ) ) { throw new IllegalStateException ( String . format ( \"ClassLoader for %s is not an instance of URLClassLoader (it is %s), and thus this method cannot be used\" , MapreduceUtils . class . getCanonicalName ( ) , loader . getClass ( ) . getCanonicalName ( ) ) ) ; } final URLClassLoader urlClassLoader = ( URLClassLoader ) loader ; addJarsToJob ( conf , allowMultiple , urlClassLoader . getURLs ( ) , jarPatterns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( InitializationInput initializationInput ) { shardId = initializationInput . getShardId ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Initializing record processor at: {}\" , initializationInput . getExtendedSequenceNumber ( ) . toString ( ) ) ; LOG . debug ( \"Initializing record processor for shard: {}\" , shardId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void processRecords ( ProcessRecordsInput processRecordsInput ) { LOG . debug ( \"RecordProcessor processRecords called\" ) ; try { IRecordProcessorCheckpointer checkpointer = processRecordsInput . getCheckpointer ( ) ; startBatch ( ) ; Optional < Record > lastProcessedRecord = Optional . empty ( ) ; int recordCount = 0 ; for ( Record kRecord : processRecordsInput . getRecords ( ) ) { try { KinesisUtil . processKinesisRecord ( shardId , kRecord , parserFactory ) . forEach ( batchMaker :: addRecord ) ; lastProcessedRecord = Optional . of ( kRecord ) ; if ( ++ recordCount == maxBatchSize ) { recordCount = 0 ; finishBatch ( checkpointer , kRecord ) ; startBatch ( ) ; } } catch ( DataParserException | IOException e ) { com . streamsets . pipeline . api . Record record = context . createRecord ( kRecord . getSequenceNumber ( ) ) ; record . set ( Field . create ( kRecord . getData ( ) . array ( ) ) ) ; try { errorRecordHandler . onError ( new OnRecordErrorException ( record , Errors . KINESIS_03 , kRecord . getSequenceNumber ( ) , e . toString ( ) , e ) ) ; // move the lastProcessedRecord forward if not set to stop pipeline lastProcessedRecord = Optional . of ( kRecord ) ; } catch ( StageException ex ) { // KCL skips over the data records that were passed prior to the exception // that is, these records are not re-sent to this record processor // or to any other record processor in the consumer. lastProcessedRecord . ifPresent ( r -> finishBatch ( checkpointer , r ) ) ; try { error . put ( ex ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; } return ; } } } lastProcessedRecord . ifPresent ( r -> finishBatch ( checkpointer , r ) ) ; } catch ( Exception e ) { LOG . error ( \"Unknown error while processing records: {}\" , e . toString ( ) , e ) ; context . reportError ( Errors . KINESIS_17 , e . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We don t checkpoint on SHUTDOWN_REQUESTED because we currently always checkpoint each batch in { @link #processRecords } . [CODESPLIT] @ Override public void shutdown ( ShutdownInput shutdownInput ) { LOG . info ( \"Shutting down record processor for shard: {}\" , shardId ) ; if ( ShutdownReason . TERMINATE . equals ( shutdownInput . getShutdownReason ( ) ) ) { // Shard is closed / finished processing. Checkpoint all processing up to here. try { shutdownInput . getCheckpointer ( ) . checkpoint ( ) ; LOG . debug ( \"Checkpointed due to record processor shutdown request.\" ) ; } catch ( InvalidStateException | ShutdownException e ) { LOG . error ( \"Error checkpointing batch: {}\" , e . toString ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final HttpRequest request , final HttpContext context ) throws HttpException , IOException { URIBuilder uriBuilder ; try { uriBuilder = new URIBuilder ( request . getRequestLine ( ) . getUri ( ) ) ; } catch ( URISyntaxException e ) { throw new IOException ( \"Invalid URI\" , e ) ; } // Copy Apache HttpRequest to AWS DefaultRequest DefaultRequest < ? > signableRequest = new DefaultRequest <> ( service ) ; HttpHost host = ( HttpHost ) context . getAttribute ( HttpCoreContext . HTTP_TARGET_HOST ) ; if ( host != null ) { signableRequest . setEndpoint ( URI . create ( host . toURI ( ) ) ) ; } final HttpMethodName httpMethod = HttpMethodName . fromValue ( request . getRequestLine ( ) . getMethod ( ) ) ; signableRequest . setHttpMethod ( httpMethod ) ; try { signableRequest . setResourcePath ( uriBuilder . build ( ) . getRawPath ( ) ) ; } catch ( URISyntaxException e ) { throw new IOException ( \"Invalid URI\" , e ) ; } if ( request instanceof HttpEntityEnclosingRequest ) { HttpEntityEnclosingRequest httpEntityEnclosingRequest = ( HttpEntityEnclosingRequest ) request ; if ( httpEntityEnclosingRequest . getEntity ( ) != null ) { signableRequest . setContent ( httpEntityEnclosingRequest . getEntity ( ) . getContent ( ) ) ; } } signableRequest . setParameters ( nvpToMapParams ( uriBuilder . getQueryParams ( ) ) ) ; signableRequest . setHeaders ( headerArrayToMap ( request . getAllHeaders ( ) ) ) ; // Sign it signer . sign ( signableRequest , awsCredentialsProvider . getCredentials ( ) ) ; // Now copy everything back request . setHeaders ( mapToHeaderArray ( signableRequest . getHeaders ( ) ) ) ; if ( request instanceof HttpEntityEnclosingRequest ) { HttpEntityEnclosingRequest httpEntityEnclosingRequest = ( HttpEntityEnclosingRequest ) request ; if ( httpEntityEnclosingRequest . getEntity ( ) != null ) { BasicHttpEntity basicHttpEntity = new BasicHttpEntity ( ) ; basicHttpEntity . setContent ( signableRequest . getContent ( ) ) ; httpEntityEnclosingRequest . setEntity ( basicHttpEntity ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the first ORDER BY field matches fieldName [CODESPLIT] private boolean checkFieldOrderByList ( SOQLParser . FieldOrderByListContext fieldOrderByList , String fieldName ) { return fieldOrderByList . fieldOrderByElement ( 0 ) . fieldElement ( ) . getText ( ) . equalsIgnoreCase ( fieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if any of the nested conditions contains fieldName [CODESPLIT] private boolean checkConditionExpressions ( SOQLParser . ConditionExpressionsContext conditionExpressions , String fieldName ) { for ( SOQLParser . ConditionExpressionContext ce : conditionExpressions . conditionExpression ( ) ) { if ( ( ce . conditionExpressions ( ) != null && checkConditionExpressions ( ce . conditionExpressions ( ) , fieldName ) ) || ( ce . fieldExpression ( ) != null && ce . fieldExpression ( ) . fieldElement ( ) . getText ( ) . equalsIgnoreCase ( fieldName ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void destroy ( ) { // SDC-6258 - destroy() is called from a different thread, so we // need to signal produce() to terminate early destroyed . set ( true ) ; if ( job != null ) { try { try { bulkConnection . abortJob ( job . getId ( ) ) ; } catch ( AsyncApiException e ) { ForceUtils . renewSession ( bulkConnection , e ) ; bulkConnection . abortJob ( job . getId ( ) ) ; } job = null ; } catch ( AsyncApiException e ) { LOG . error ( \"Exception while aborting job\" , e ) ; } } job = null ; if ( forceConsumer != null ) { try { forceConsumer . stop ( ) ; forceConsumer = null ; } catch ( Exception e ) { LOG . error ( \"Exception while stopping ForceStreamConsumer.\" , e ) ; } if ( ! messageQueue . isEmpty ( ) ) { LOG . error ( \"Queue still had {} entities at shutdown.\" , messageQueue . size ( ) ) ; } else { LOG . info ( \"Queue was empty at shutdown. No data lost.\" ) ; } } if ( recordCreator != null ) { recordCreator . destroy ( ) ; } // Clean up any open resources. super . destroy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String produce ( String lastSourceOffset , int maxBatchSize , BatchMaker batchMaker ) throws StageException { String nextSourceOffset = null ; LOG . debug ( \"lastSourceOffset: {}\" , lastSourceOffset ) ; // send event only once for each time we run out of data. if ( shouldSendNoMoreDataEvent ) { CommonEvents . NO_MORE_DATA . create ( getContext ( ) ) . createAndSend ( ) ; shouldSendNoMoreDataEvent = false ; return lastSourceOffset ; } int batchSize = Math . min ( conf . basicConfig . maxBatchSize , maxBatchSize ) ; if ( ! conf . queryExistingData || ( null != lastSourceOffset && lastSourceOffset . startsWith ( EVENT_ID_OFFSET_PREFIX ) ) ) { if ( conf . subscribeToStreaming ) { nextSourceOffset = streamingProduce ( lastSourceOffset , batchSize , batchMaker ) ; } else { // We're done reading existing data, but we don't want to subscribe to Streaming API return null ; } } else if ( conf . queryExistingData ) { if ( ! queryInProgress ( ) ) { long now = System . currentTimeMillis ( ) ; long delay = Math . max ( 0 , ( lastQueryCompletedTime + ( 1000 * conf . queryInterval ) ) - now ) ; if ( delay > 0 ) { // Sleep in one second increments so we don't tie up the app. LOG . info ( \"{}ms remaining until next fetch.\" , delay ) ; ThreadUtil . sleep ( Math . min ( delay , 1000 ) ) ; return lastSourceOffset ; } } if ( conf . useBulkAPI ) { nextSourceOffset = bulkProduce ( lastSourceOffset , batchSize , batchMaker ) ; } else { nextSourceOffset = soapProduce ( lastSourceOffset , batchSize , batchMaker ) ; } } else if ( conf . subscribeToStreaming ) { // No offset, and we're not querying existing data, so switch to streaming nextSourceOffset = READ_EVENTS_FROM_NOW ; } LOG . debug ( \"nextSourceOffset: {}\" , nextSourceOffset ) ; return nextSourceOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If passed a valid fileOffsetString it will return what is the offset lag in the file . [CODESPLIT] public static long getOffsetLagForFile ( String fileOffsetString ) throws IOException { long offset = FileContextProviderUtil . getLongOffsetFromFileOffset ( fileOffsetString ) ; //We are refreshing the live file here because we are going to get the size by using path. LiveFile file = FileContextProviderUtil . getRefreshedLiveFileFromFileOffset ( fileOffsetString ) ; long fileSizeInBytes = Files . size ( file . getPath ( ) . toAbsolutePath ( ) ) ; return ( fileSizeInBytes - offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible due to JVM requirements only [CODESPLIT] public static void premain ( String args , Instrumentation instrumentation ) { if ( BootstrapMain . instrumentation == null ) { BootstrapMain . instrumentation = instrumentation ; } else { throw new IllegalStateException ( \"Premain method cannot be called twice (\" + BootstrapMain . instrumentation + \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if whitelist is * set is NULL else whitelist has the whitelisted values [CODESPLIT] public static Set < String > getWhiteList ( String configDir , String property ) { Set < String > set = null ; File whiteListFile = new File ( configDir , WHITE_LIST_FILE ) . getAbsoluteFile ( ) ; if ( whiteListFile . exists ( ) ) { try ( InputStream is = new FileInputStream ( whiteListFile ) ) { Properties props = new Properties ( ) ; props . load ( is ) ; String whiteList = props . getProperty ( property ) ; if ( whiteList == null ) { throw new IllegalArgumentException ( String . format ( WHITE_LIST_PROPERTY_MISSING_MSG , property , whiteListFile ) ) ; } whiteList = whiteList . trim ( ) ; if ( ! whiteList . equals ( ALL_VALUES ) ) { set = new HashSet <> ( ) ; for ( String name : whiteList . split ( \",\" ) ) { name = name . trim ( ) ; if ( ! name . isEmpty ( ) ) { set . add ( \"+\" + name . trim ( ) ) ; } } } } catch ( IOException ex ) { throw new IllegalArgumentException ( String . format ( WHITE_LIST_COULD_NOT_LOAD_FILE_MSG , whiteListFile , ex . toString ( ) ) , ex ) ; } } return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] public static Map < String , List < URL > > getStageLibrariesClasspaths ( String stageLibrariesDir , String librariesExtraDir , final Set < String > stageLibs , String libsCommonLibDir ) throws Exception { Map < String , List < URL > > map = new LinkedHashMap < String , List < URL > > ( ) ; File baseDir = new File ( stageLibrariesDir ) . getAbsoluteFile ( ) ; if ( baseDir . exists ( ) ) { File [ ] libDirs = baseDir . listFiles ( createStageLibFilter ( stageLibs ) ) ; StringBuilder commonLibJars = new StringBuilder ( ) ; if ( libsCommonLibDir != null ) { commonLibJars . append ( new File ( libsCommonLibDir ) . getAbsolutePath ( ) ) . append ( FILE_SEPARATOR ) . append ( JARS_WILDCARD ) . append ( CLASSPATH_SEPARATOR ) ; } for ( File libDir : libDirs ) { File jarsDir = new File ( libDir , STAGE_LIB_JARS_DIR ) ; File etc = new File ( libDir , STAGE_LIB_CONF_DIR ) ; if ( ! jarsDir . exists ( ) ) { throw new IllegalArgumentException ( String . format ( MISSING_STAGE_LIB_JARS_DIR_MSG , libDir ) ) ; } StringBuilder sb = new StringBuilder ( ) ; if ( etc . exists ( ) ) { sb . append ( etc . getAbsolutePath ( ) ) . append ( FILE_SEPARATOR ) . append ( CLASSPATH_SEPARATOR ) ; } sb . append ( commonLibJars ) ; sb . append ( jarsDir . getAbsolutePath ( ) ) . append ( FILE_SEPARATOR ) . append ( JARS_WILDCARD ) ; // add extralibs if avail if ( librariesExtraDir != null ) { File libExtraDir = new File ( librariesExtraDir , libDir . getName ( ) ) ; if ( libExtraDir . exists ( ) ) { File extraJarsDir = new File ( libExtraDir , STAGE_LIB_JARS_DIR ) ; if ( extraJarsDir . exists ( ) ) { sb . append ( CLASSPATH_SEPARATOR ) . append ( extraJarsDir . getAbsolutePath ( ) ) . append ( FILE_SEPARATOR ) . append ( JARS_WILDCARD ) ; } File extraEtc = new File ( libExtraDir , STAGE_LIB_CONF_DIR ) ; if ( extraEtc . exists ( ) ) { sb . append ( CLASSPATH_SEPARATOR ) . append ( extraEtc . getAbsolutePath ( ) ) ; } } } map . put ( libDir . getParentFile ( ) . getName ( ) + FILE_SEPARATOR + libDir . getName ( ) , getClasspathUrls ( sb . toString ( ) ) ) ; } } else { throw new IllegalArgumentException ( String . format ( MISSING_STAGE_LIBRARIES_DIR_MSG , baseDir ) ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing [CODESPLIT] public static List < URL > getClasspathUrls ( String classPath ) throws Exception { List < URL > urls = new ArrayList < URL > ( ) ; for ( String path : classPath . split ( CLASSPATH_SEPARATOR ) ) { if ( ! path . isEmpty ( ) ) { if ( path . toLowerCase ( ) . endsWith ( JARS_WILDCARD ) ) { path = path . substring ( 0 , path . length ( ) - JARS_WILDCARD . length ( ) ) ; File f = new File ( path ) . getAbsoluteFile ( ) ; if ( f . exists ( ) ) { File [ ] jars = f . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { return pathname . getName ( ) . toLowerCase ( ) . endsWith ( JARS_WILDCARD . substring ( 1 ) ) ; } } ) ; for ( File jar : jars ) { urls . add ( jar . toURI ( ) . toURL ( ) ) ; } } else { throw new IllegalArgumentException ( String . format ( CLASSPATH_DIR_DOES_NOT_EXIST_MSG , f ) ) ; } } else { if ( ! path . endsWith ( FILE_SEPARATOR ) ) { path = path + FILE_SEPARATOR ; } File f = new File ( path ) . getAbsoluteFile ( ) ; if ( f . exists ( ) ) { if ( f . isDirectory ( ) ) { urls . add ( f . toURI ( ) . toURL ( ) ) ; } else { throw new IllegalArgumentException ( String . format ( CLASSPATH_PATH_S_IS_NOT_A_DIR_MSG , f ) ) ; } } else { throw new IllegalArgumentException ( String . format ( CLASSPATH_DIR_DOES_NOT_EXIST_MSG , f ) ) ; } } } } return urls ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This API is being used by ClusterKafkaSource [CODESPLIT] public int getParallelism ( ) throws StageException { if ( originParallelism == 0 ) { //origin parallelism is not yet calculated originParallelism = kafkaValidationUtil . getPartitionCount ( conf . metadataBrokerList , conf . topic , new HashMap < String , Object > ( conf . kafkaConsumerConfigs ) , 3 , 1000 ) ; if ( originParallelism < 1 ) { throw new StageException ( KafkaErrors . KAFKA_42 , conf . topic ) ; } } return originParallelism ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Arranges the urls in the following order : <ul > <li > stage lib jars< / li > <li > protolib jars< / li > <li > non protolib jars< / li > < / ul > [CODESPLIT] static List < URL > bringStageAndProtoLibsToFront ( String stageLibName , List < URL > urls ) { List < URL > otherJars = new ArrayList <> ( ) ; List < URL > protolibJars = new ArrayList <> ( ) ; List < URL > stageLibjars = new ArrayList <> ( ) ; for ( URL url : urls ) { String str = url . toExternalForm ( ) ; if ( str . endsWith ( \".jar\" ) ) { int nameIdx = str . lastIndexOf ( \"/\" ) ; if ( nameIdx > - 1 ) { String jarName = str . substring ( nameIdx + 1 ) ; if ( jarName . contains ( \"-protolib-\" ) ) { // adding only protolib jars protolibJars . add ( url ) ; } else if ( jarName . contains ( stageLibName ) ) { stageLibjars . add ( url ) ; } else { otherJars . add ( url ) ; } } else { otherJars . add ( url ) ; } } else { otherJars . add ( url ) ; } } List < URL > allJars = new ArrayList <> ( ) ; if ( stageLibjars . size ( ) != 1 ) { throw new ExceptionInInitializerError ( \"Expected exactly 1 stage lib jar but found \" + stageLibjars . size ( ) + \" with name \" + stageLibName ) ; } allJars . addAll ( stageLibjars ) ; allJars . addAll ( protolibJars ) ; allJars . addAll ( otherJars ) ; return allJars ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a query request and returns the results . A timeout is required to avoid waiting for an indeterminate amount of time . If the query fails to complete within the timeout it is aborted . [CODESPLIT] public TableResult runQuery ( QueryJobConfiguration queryConfig , long timeout , long pageSize ) throws StageException { checkArgument ( timeout >= 1000 , \"Timeout must be at least one second.\" ) ; Instant maxTime = Instant . now ( ) . plusMillis ( timeout ) ; // Create a job ID so that we can safely retry. JobId jobId = JobId . of ( UUID . randomUUID ( ) . toString ( ) ) ; JobInfo jobInfo = JobInfo . newBuilder ( queryConfig ) . setJobId ( jobId ) . build ( ) ; Job queryJob = bigquery . create ( jobInfo ) ; // Check for errors if ( queryJob == null ) { LOG . error ( \"Job no longer exists: {}\" , jobInfo ) ; throw new RuntimeException ( \"Job no longer exists: \" + jobInfo ) ; } else if ( queryJob . getStatus ( ) . getError ( ) != null ) { BigQueryError error = queryJob . getStatus ( ) . getError ( ) ; LOG . error ( \"Query Job execution error: {}\" , error ) ; throw new StageException ( Errors . BIGQUERY_02 , error ) ; } //Should consider using .waitFor(RetryOption.totalTimeout()) while ( ! queryJob . isDone ( ) ) { if ( Instant . now ( clock ) . isAfter ( maxTime ) || ! ThreadUtil . sleep ( 100 ) ) { if ( bigquery . cancel ( queryJob . getJobId ( ) ) ) { LOG . info ( \"Job {} cancelled successfully.\" , queryJob . getJobId ( ) ) ; } else { LOG . warn ( \"Job {} not found\" , queryJob . getJobId ( ) ) ; } throw new StageException ( Errors . BIGQUERY_00 ) ; } } if ( queryJob . getStatus ( ) . getError ( ) != null ) { String errorMsg = queryJob . getStatus ( ) . getError ( ) . toString ( ) ; throw new StageException ( Errors . BIGQUERY_02 , errorMsg ) ; } // Get the results. TableResult result = null ; try { result = queryJob . getQueryResults ( QueryResultsOption . pageSize ( pageSize ) ) ; } catch ( InterruptedException e ) { String errorMsg = e . getMessage ( ) ; throw new StageException ( Errors . BIGQUERY_02 , errorMsg ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the SDC record { @link Field } type mapped from a BigQuery { @link com . google . cloud . bigquery . Field } type . [CODESPLIT] public Field . Type asRecordFieldType ( com . google . cloud . bigquery . Field field ) { Field . Type type = asRecordFieldTypeFunction . apply ( field ) ; return checkNotNull ( type , Utils . format ( \"Unsupported type '{}'\" , field . getType ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a list of BigQuery fields to SDC Record fields . The provided parameters must have matching lengths . [CODESPLIT] public LinkedHashMap < String , Field > fieldsToMap ( // NOSONAR List < com . google . cloud . bigquery . Field > schema , List < FieldValue > values ) { checkState ( schema . size ( ) == values . size ( ) , \"Schema '{}' and Values '{}' sizes do not match.\" , schema . size ( ) , values . size ( ) ) ; LinkedHashMap < String , Field > root = new LinkedHashMap <> ( ) ; for ( int i = 0 ; i < values . size ( ) ; i ++ ) { FieldValue value = values . get ( i ) ; com . google . cloud . bigquery . Field field = schema . get ( i ) ; if ( value . getAttribute ( ) . equals ( FieldValue . Attribute . PRIMITIVE ) ) { root . put ( field . getName ( ) , fromPrimitiveField ( field , value ) ) ; } else if ( value . getAttribute ( ) . equals ( FieldValue . Attribute . RECORD ) ) { root . put ( field . getName ( ) , Field . create ( fieldsToMap ( field . getSubFields ( ) , value . getRecordValue ( ) ) ) ) ; } else if ( value . getAttribute ( ) . equals ( FieldValue . Attribute . REPEATED ) ) { root . put ( field . getName ( ) , Field . create ( fromRepeatedField ( field , value . getRepeatedValue ( ) ) ) ) ; } } return root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repeated fields are simply fields that may appear more than once . In SDC we will represent them as a list field . For example a repeated field of type RECORD would be a { @link Field . Type#LIST } of { @link Field . Type#LIST_MAP } and a repeated field of type STRING would be a { @link Field . Type#LIST } of { @link Field . Type#STRING } . [CODESPLIT] public List < Field > fromRepeatedField ( com . google . cloud . bigquery . Field schema , List < FieldValue > repeatedValue ) { if ( repeatedValue . isEmpty ( ) ) { return Collections . emptyList ( ) ; } FieldValue . Attribute repeatedFieldType = repeatedValue . get ( 0 ) . getAttribute ( ) ; BiFunction < com . google . cloud . bigquery . Field , FieldValue , Field > transform = transforms . get ( repeatedFieldType ) ; return repeatedValue . stream ( ) . map ( v -> transform . apply ( schema , v ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the table description from the ShowTableResponse [CODESPLIT] private List < String > getTableDescription ( ) throws GPUdbException { List < List < String >> descriptions = showTableResponse . getTableDescriptions ( ) ; if ( descriptions == null || descriptions . size ( ) != 1 ) { throw new GPUdbException ( \"Error getting description for table \" + tableName ) ; } return descriptions . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if it is not [CODESPLIT] private void validateTableAcceptsInserts ( ) throws GPUdbException { for ( String s : tableDescription ) { if ( s . equalsIgnoreCase ( \"COLLECTION\" ) ) { throw new GPUdbException ( \"Error: table \" + tableName + \" is a Collection\" ) ; } else if ( s . equalsIgnoreCase ( \"VIEW\" ) ) { throw new GPUdbException ( \"Error: table \" + tableName + \" is a View\" ) ; } else if ( s . equalsIgnoreCase ( \"JOIN\" ) ) { throw new GPUdbException ( \"Error: table \" + tableName + \" is a Join Table\" ) ; } else if ( s . equalsIgnoreCase ( \"RESULT_TABLE\" ) ) { throw new GPUdbException ( \"Error: table \" + tableName + \" is a Result Table\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Class for the column type [CODESPLIT] private Class < ? > getColumnType ( JSONObject field ) throws GPUdbException { Class < ? > columnType = null ; // The Avro \"type\" element might be an array if the type is nullable if ( field . get ( \"type\" ) instanceof JSONArray ) { JSONArray columnTypes = field . getJSONArray ( \"type\" ) ; for ( int j = 0 ; j < columnTypes . length ( ) ; j ++ ) { String ct = ( String ) columnTypes . get ( j ) ; if ( ! ct . equals ( \"null\" ) ) { columnType = getClassForType ( ct ) ; break ; } } } else { columnType = getClassForType ( field . getString ( \"type\" ) ) ; } if ( columnType == null ) { throw new GPUdbException ( \"Error getting column type for field: \" + field . toString ( ) ) ; } return columnType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the Avro type field ) [CODESPLIT] private boolean typeIsNullable ( JSONObject field ) throws GPUdbException { if ( field . get ( \"type\" ) instanceof JSONArray ) { JSONArray columnTypes = field . getJSONArray ( \"type\" ) ; for ( int j = 0 ; j < columnTypes . length ( ) ; j ++ ) { String ct = ( String ) columnTypes . get ( j ) ; if ( ct . equals ( \"null\" ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the table s schema as a JSON Object [CODESPLIT] private JSONObject getTableSchema ( String tableName , ShowTableResponse showTableResponse ) throws GPUdbException { List < String > schemas = showTableResponse . getTypeSchemas ( ) ; if ( schemas == null || schemas . size ( ) != 1 ) { throw new GPUdbException ( \"Error getting schema for table \" + tableName ) ; } return new JSONObject ( schemas . get ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the table s extended column properties [CODESPLIT] private Map < String , List < String > > getColumnProperties ( String tableName , ShowTableResponse showTableResponse ) throws GPUdbException { List < Map < String , List < String > > > columnPropertiesList = showTableResponse . getProperties ( ) ; if ( columnPropertiesList == null || columnPropertiesList . size ( ) != 1 ) { throw new GPUdbException ( \"Error getting properties for table \" + tableName ) ; } return columnPropertiesList . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Java type for a type name [CODESPLIT] private Class < ? > getClassForType ( String typeName ) throws GPUdbException { typeName = typeName . replace ( \" \" , \"\" ) ; if ( typeName . equalsIgnoreCase ( STRING_TYPE_NAME ) ) { return String . class ; } else if ( typeName . equalsIgnoreCase ( LONG_TYPE_NAME ) ) { return Long . class ; } else if ( typeName . equalsIgnoreCase ( INTEGER_TYPE_NAME ) ) { return Integer . class ; } else if ( typeName . equalsIgnoreCase ( FLOAT_TYPE_NAME ) ) { return Float . class ; } else if ( typeName . equalsIgnoreCase ( DOUBLE_TYPE_NAME ) ) { return Double . class ; } else if ( typeName . equalsIgnoreCase ( BYTES_TYPE_NAME ) ) { return ByteBuffer . class ; } else { throw new GPUdbException ( \"Error: unknown type '\" + typeName + \"' in table schema\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize and validate configuration options [CODESPLIT] public void init ( Target . Context context , List < Target . ConfigIssue > issues ) { List < Host > hosts = getAerospikeHosts ( issues , connectionString , Groups . AEROSPIKE . getLabel ( ) , \"aerospikeBeanConfig.connectionString\" , context ) ; ClientPolicy cp = new ClientPolicy ( ) ; try { client = new AerospikeClient ( cp , hosts . toArray ( new Host [ hosts . size ( ) ] ) ) ; int retries = 0 ; while ( ! client . isConnected ( ) && retries <= maxRetries ) { if ( retries > maxRetries ) { issues . add ( context . createConfigIssue ( Groups . AEROSPIKE . getLabel ( ) , \"aerospikeBeanConfig.connectionString\" , AerospikeErrors . AEROSPIKE_03 , connectionString ) ) ; return ; } retries ++ ; try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ignored ) { } } } catch ( AerospikeException ex ) { issues . add ( context . createConfigIssue ( Groups . AEROSPIKE . getLabel ( ) , \"aerospikeBeanConfig.connectionString\" , AerospikeErrors . AEROSPIKE_03 , connectionString ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the topic given the record . [CODESPLIT] String getTopic ( Record record ) throws StageException { String result = publisherConf . topic ; if ( publisherConf . runtimeTopicResolution ) { RecordEL . setRecordInContext ( topicVars , record ) ; try { result = topicEval . eval ( topicVars , publisherConf . topicExpression , String . class ) ; if ( isEmpty ( result ) ) { throw new StageException ( Errors . MQTT_08 , publisherConf . topicExpression , record . getHeader ( ) . getSourceId ( ) ) ; } if ( ! allowedTopics . contains ( result ) && ! allowAllTopics ) { throw new StageException ( Errors . MQTT_09 , result , record . getHeader ( ) . getSourceId ( ) ) ; } } catch ( ELEvalException e ) { throw new StageException ( Errors . MQTT_10 , publisherConf . topicExpression , record . getHeader ( ) . getSourceId ( ) , e . toString ( ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the provided pattern and get the C standard Date / Time formatting rules and convert them to the Java equivalent . [CODESPLIT] public String convertDateFormat ( String pattern ) { boolean inside = false ; boolean mark = false ; boolean modifiedCommand = false ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < pattern . length ( ) ; i ++ ) { char c = pattern . charAt ( i ) ; if ( c == ' ' && ! mark ) { mark = true ; } else { if ( mark ) { if ( modifiedCommand ) { //don't do anything--we just wanted to skip a char modifiedCommand = false ; mark = false ; } else { inside = translateCommand ( buf , pattern , i , inside ) ; //It's a modifier code if ( c == ' ' || c == ' ' ) { modifiedCommand = true ; } else { mark = false ; } } } else { if ( ! inside && c != ' ' ) { //We start a literal, which we need to quote buf . append ( \"'\" ) ; inside = true ; } buf . append ( c ) ; } } } if ( buf . length ( ) > 0 ) { char lastChar = buf . charAt ( buf . length ( ) - 1 ) ; if ( lastChar != ' ' && inside ) { buf . append ( ' ' ) ; } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to get the Java Date / Time formatting associated with the C standard provided . [CODESPLIT] protected boolean translateCommand ( StringBuilder buf , String pattern , int index , boolean oldInside ) { char firstChar = pattern . charAt ( index ) ; boolean newInside = oldInside ; //O and E are modifiers, they mean to present an alternative representation of the next char //we just handle the next char as if the O or E wasn't there if ( firstChar == ' ' || firstChar == ' ' ) { if ( index + 1 < pattern . length ( ) ) { newInside = translateCommand ( buf , pattern , index + 1 , oldInside ) ; } else { buf . append ( quote ( \"%\" + firstChar , oldInside ) ) ; } } else { String command = translate . getProperty ( String . valueOf ( firstChar ) ) ; //If we don't find a format, treat it as a literal--That's what apache does if ( command == null ) { buf . append ( quote ( \"%\" + firstChar , oldInside ) ) ; } else { //If we were inside quotes, close the quotes if ( oldInside ) { buf . append ( ' ' ) ; } buf . append ( command ) ; newInside = false ; } } return newInside ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Max Error retries > = 0 are set in ClientConfig for S3Client < 0 will use default ( 3 ) [CODESPLIT] public void init ( Stage . Context context , String configPrefix , ProxyConfig proxyConfig , List < Stage . ConfigIssue > issues , int maxErrorRetries ) { this . maxErrorRetries = maxErrorRetries ; commonPrefix = AWSUtil . normalizePrefix ( commonPrefix , delimiter ) ; try { createConnection ( context , configPrefix , proxyConfig , issues , maxErrorRetries ) ; } catch ( StageException ex ) { LOG . debug ( Errors . S3_SPOOLDIR_20 . getMessage ( ) , ex . toString ( ) , ex ) ; issues . add ( context . createConfigIssue ( Groups . S3 . name ( ) , configPrefix + S3ConnectionBaseConfig . AWS_CONFIG_PREFIX + \"awsAccessKeyId\" , Errors . S3_SPOOLDIR_20 , ex . toString ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transition to services [CODESPLIT] private static void upgradeV5ToV6 ( List < Config > configs , Context context ) { List < Config > dataFormatConfigs = configs . stream ( ) . filter ( c -> c . getName ( ) . startsWith ( \"dataFormat\" ) ) . collect ( Collectors . toList ( ) ) ; // Remove those configs configs . removeAll ( dataFormatConfigs ) ; // There is an interesting history with compression - at some point (version 2), we explicitly added it, then // we have hidden it. So this config might or might not exists, depending on the version in which the pipeline // was created. However the service is expecting it and thus we need to ensure that it's there. if ( dataFormatConfigs . stream ( ) . noneMatch ( c -> \"dataFormatConfig.compression\" . equals ( c . getName ( ) ) ) ) { dataFormatConfigs . add ( new Config ( \"dataFormatConfig.compression\" , \"NONE\" ) ) ; } // And finally register new service context . registerService ( DataFormatParserService . class , dataFormatConfigs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a given field path expression against a given record and returns all field paths that satisfy the expression upon evaluation . Analagous in function to { @link FieldRegexUtil#getMatchingFieldPaths ( String Set ) } and even identical in behavior to it when the given { @code fieldExpression } does not contain any EL expressions . [CODESPLIT] public static List < String > evaluateMatchingFieldPaths ( String fieldExpression , ELEval elEval , ELVars elVars , Record record , Iterable < String > recordEscapedFieldPaths ) throws ELEvalException { if ( isFieldPathExpressionFast ( fieldExpression ) ) { // this field path expression actually does contain an EL expression, so need to evaluate against all fields return evaluateMatchingFieldPathsImpl ( fieldExpression , elEval , elVars , record ) ; } else { // else it does NOT contain one, so the field regex util (which is faster) can be used return FieldRegexUtil . getMatchingFieldPaths ( fieldExpression , recordEscapedFieldPaths ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a field expression against a specific field in a record to see if it matches [CODESPLIT] private static boolean pathMatches ( Record record , String fieldPath , String fieldExpression , ELEval elEval , ELVars elVars ) throws ELEvalException { List < PathElement > actualPathElements = PathElement . parse ( fieldPath , true ) ; List < PathElement > matcherPathElements = PathElement . parse ( fieldExpression , false , true ) ; Iterator < PathElement > currentPathIter = actualPathElements . iterator ( ) ; Iterator < PathElement > matcherPathIter = matcherPathElements . iterator ( ) ; PathElement currentMatcher = null ; PathElement currentPath = null ; Field currentField = null ; StringBuilder currentFieldPath = new StringBuilder ( ) ; while ( matcherPathIter . hasNext ( ) ) { currentMatcher = matcherPathIter . next ( ) ; switch ( currentMatcher . getType ( ) ) { case MAP : if ( ! currentPathIter . hasNext ( ) ) { // we are expecting to match a MAP, but there are no more elements in the path return false ; } currentPath = currentPathIter . next ( ) ; // see if the name matches the pattern String childName = currentPath . getName ( ) ; String patternName = currentMatcher . getName ( ) ; if ( FieldRegexUtil . hasWildCards ( patternName ) ) { patternName = FieldRegexUtil . transformFieldPathRegex ( patternName ) ; } if ( childName . matches ( patternName ) ) { currentField = currentField . getValueAsMap ( ) . get ( childName ) ; currentFieldPath . append ( \"/\" ) ; currentFieldPath . append ( childName ) ; } else { return false ; } break ; case LIST : // see if the index matches the pattern if ( ! currentPathIter . hasNext ( ) ) { // we are expecting to match a LIST, but there are no more elements in the path return false ; } currentPath = currentPathIter . next ( ) ; int childIndex = currentPath . getIndex ( ) ; final int matchInd = currentMatcher . getIndex ( ) ; if ( matchInd == PathElement . WILDCARD_INDEX_ANY_LENGTH || ( matchInd == PathElement . WILDCARD_INDEX_SINGLE_CHAR && childIndex < 10 ) || matchInd == childIndex ) { currentField = currentField . getValueAsList ( ) . get ( childIndex ) ; currentFieldPath . append ( \"[\" ) ; currentFieldPath . append ( childIndex ) ; currentFieldPath . append ( \"]\" ) ; } else { return false ; } break ; case ROOT : if ( ! currentPathIter . hasNext ( ) ) { // we are expecting to match the ROOT, but there are no more elements in the path return false ; } currentPath = currentPathIter . next ( ) ; if ( currentPath . getType ( ) != PathElement . Type . ROOT ) { // we are expecting to match the ROOT, the root element wasn't for some reason return false ; } currentField = record . get ( ) ; break ; case FIELD_EXPRESSION : // see if the current field matches the given expression FieldEL . setFieldInContext ( elVars , currentFieldPath . toString ( ) , currentPath . getName ( ) , currentField ) ; String expression = currentMatcher . getName ( ) ; final boolean result = elEval . eval ( elVars , expression , Boolean . class ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Result of evaluating expression {} on field {} with path {} was {}\" , expression , currentField , currentFieldPath , result ) ; } if ( ! result ) { return false ; } break ; } } return ! currentPathIter . hasNext ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method must be used after completing the write to output stream which was obtained by calling the { @link #getOutputStream () } method . [CODESPLIT] public void release ( ) { CounterLock lock ; synchronized ( DataStore . class ) { lock = FILE_LOCKS . get ( file ) ; if ( lock == null ) { LOG . error ( \"Trying to release unlocked file {}\" , file ) ; return ; } lock . dec ( ) ; if ( lock . counter == 0 ) { FILE_LOCKS . remove ( file ) ; } } LOG . trace ( \"Releasing the lock {} for '{}'\" , lock , file ) ; lock . unlock ( ) ; LOG . trace ( \"Released the lock {} for '{}'\" , lock , file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an input stream for the requested file . [CODESPLIT] public InputStream getInputStream ( ) throws IOException { acquireLock ( ) ; try { isClosed = false ; forWrite = false ; LOG . trace ( \"Starts read '{}'\" , file ) ; verifyAndRecover ( ) ; InputStream is = new ProxyInputStream ( new FileInputStream ( file . toFile ( ) ) ) { @ Override public void close ( ) throws IOException { if ( isClosed ) { return ; } try { super . close ( ) ; } finally { release ( ) ; isClosed = true ; stream = null ; } LOG . trace ( \"Finishes read '{}'\" , file ) ; } } ; stream = is ; return is ; } catch ( Exception ex ) { release ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an output stream for the requested file . [CODESPLIT] public OutputStream getOutputStream ( ) throws IOException { acquireLock ( ) ; try { isClosed = false ; forWrite = true ; LOG . trace ( \"Starts write '{}'\" , file ) ; verifyAndRecover ( ) ; if ( Files . exists ( file ) ) { Files . move ( file , fileOld ) ; LOG . trace ( \"Starting write, move '{}' to '{}'\" , file , fileOld ) ; } OutputStream os = new ProxyOutputStream ( new FileOutputStream ( fileTmp . toFile ( ) ) ) { @ Override public void close ( ) throws IOException { if ( isClosed ) { return ; } try { super . close ( ) ; } finally { isClosed = true ; stream = null ; } LOG . trace ( \"Finishes write '{}'\" , file ) ; } } ; stream = os ; return os ; } catch ( Exception ex ) { release ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method must be used to commit contents written to the output stream which is obtained by calling the { @link #getOutputStream () } method . This method closes the argument output stream . [CODESPLIT] public void commit ( OutputStream out ) throws IOException { // close the stream in order to flush the contents into the disk Utils . checkNotNull ( out , \"Argument output stream cannot be null\" ) ; Utils . checkState ( stream == out , \"The argument output stream must be the same as the output stream obtained \" + \"from this data store instance\" ) ; out . close ( ) ; Files . move ( fileTmp , fileNew ) ; LOG . trace ( \"Committing write, move '{}' to '{}'\" , fileTmp , fileNew ) ; Files . move ( fileNew , file ) ; LOG . trace ( \"Committing write, move '{}' to '{}'\" , fileNew , file ) ; if ( Files . exists ( fileOld ) ) { Files . delete ( fileOld ) ; LOG . trace ( \"Committing write, deleting '{}'\" , fileOld ) ; } LOG . trace ( \"Committed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the DataStore exists and contains data . This method will check for the presence of the set of files that can be used to read data from the store . [CODESPLIT] public boolean exists ( ) throws IOException { acquireLock ( ) ; try { verifyAndRecover ( ) ; return Files . exists ( file ) && Files . size ( file ) > 0 ; } finally { release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an operation code from record . First look for sdc . operation . code from record header . If not set look for __$operation in record . It is a specific field that MS SQL CDC origin set . [CODESPLIT] @ Override @ VisibleForTesting int getOperationFromRecord ( Record record , int defaultOpCode , UnsupportedOperationAction unsupportedAction , List < OnRecordErrorException > errorRecords ) { int opCode = - 1 ; // -1 is invalid and not used in OperationType. String op = null ; try { // Try sdc.operation.type first op = record . getHeader ( ) . getAttribute ( OperationType . SDC_OPERATION_TYPE ) ; // If not set, look for \"__$operation\" in record. if ( StringUtils . isBlank ( op ) ) { if ( record . has ( MSOperationCode . getOpField ( ) ) ) { int intOp = record . get ( MSOperationCode . getOpField ( ) ) . getValueAsInteger ( ) ; // Convert the MS specific operation code to SDC standard operation code opCode = MSOperationCode . convertToJDBCCode ( intOp ) ; } } else { opCode = JDBCOperationType . convertToIntCode ( op ) ; } if ( opCode == - 1 ) { // Both MS code and sdc code are not set. Use default. opCode = defaultOpCode ; } } catch ( NumberFormatException | UnsupportedOperationException ex ) { LOG . debug ( \"Operation obtained from record is not supported: {}. Handle by UnsupportedOpertaionAction {}. {}\" , ex . getMessage ( ) , unsupportedAction . getLabel ( ) , ex ) ; switch ( unsupportedAction ) { case DISCARD : LOG . debug ( \"Discarding record with unsupported operation {}\" , op ) ; break ; case SEND_TO_ERROR : LOG . debug ( \"Sending record to error due to unsupported operation {}\" , op ) ; errorRecords . add ( new OnRecordErrorException ( record , JdbcErrors . JDBC_70 , op ) ) ; break ; case USE_DEFAULT : opCode = defaultOpCode ; break ; default : //unknown action LOG . debug ( \"Sending record to error due to unknown operation: {}\" , op ) ; } } return opCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse String representation of permissions into HDFS FsPermission class . [CODESPLIT] public static FsPermission parseFsPermission ( String permissions ) throws IllegalArgumentException { try { // Octal or symbolic representation return new FsPermission ( permissions ) ; } catch ( IllegalArgumentException e ) { // FsPermission.valueOf will work with unix style permissions which is 10 characters // where the first character says the type of file if ( permissions . length ( ) == 9 ) { // This means it is a posix standard without the first character for file type // We will simply set it to '-' suggesting regular file permissions = \"-\" + permissions ; } // Try to parse unix style format. return FsPermission . valueOf ( permissions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that all required libraries are available and loaded . [CODESPLIT] @ VisibleForTesting void validateRequiredStageLibraries ( ) { // Name of all installed libraries Set < String > installedLibraries = stageLibraries . stream ( ) . map ( StageLibraryDefinition :: getName ) . collect ( Collectors . toSet ( ) ) ; // Required libraries Set < String > requiredLibraries = new HashSet <> ( ) ; String config = configuration . get ( SdcConfiguration . REQUIRED_STAGELIBS , DEFAULT_REQUIRED_STAGELIBS ) ; for ( String stageLib : config . split ( \",\" ) ) { if ( ! stageLib . isEmpty ( ) ) { requiredLibraries . add ( stageLib ) ; } } Set < String > missingLibraries = Sets . difference ( requiredLibraries , installedLibraries ) ; if ( ! missingLibraries . isEmpty ( ) ) { throw new RuntimeException ( Utils . format ( \"Some required stage libraries are missing: {}\" , StringUtils . join ( missingLibraries , \", \" ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate service dependencies . [CODESPLIT] private void validateAllServicesAvailable ( ) { // Firstly validate that all stages have satisfied service dependencies List < String > missingServices = new LinkedList <> ( ) ; for ( StageDefinition stage : stageList ) { for ( ServiceDependencyDefinition service : stage . getServices ( ) ) { if ( ! serviceMap . containsKey ( service . getService ( ) ) ) { missingServices . add ( Utils . format ( \"Stage {} is missing service {}\" , stage . getName ( ) , service . getService ( ) . getName ( ) ) ) ; } } } if ( ! missingServices . isEmpty ( ) ) { throw new RuntimeException ( \"Missing services: \" + StringUtils . join ( missingServices , \", \" ) ) ; } // Secondly ensure that all loaded services are compatible with what is supported by our runtime engine List < String > unsupportedServices = new LinkedList <> ( ) ; for ( ServiceDefinition serviceDefinition : serviceList ) { if ( ! ServiceRuntime . supports ( serviceDefinition . getProvides ( ) ) ) { unsupportedServices . add ( serviceDefinition . getProvides ( ) . toString ( ) ) ; } } if ( ! unsupportedServices . isEmpty ( ) ) { throw new RuntimeException ( \"Unsupported services: \" + StringUtils . join ( unsupportedServices , \", \" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a simple Aggregator . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < A extends SimpleAggregator > A createSimple ( String name , Class < ? extends Aggregator > klass ) { Utils . checkState ( ! started , \"Already started\" ) ; try { A aggregator = ( A ) CONSTRUCTORS . get ( klass ) . newInstance ( name ) ; dataProvider . addAggregator ( aggregator ) ; aggregator . setDataProvider ( dataProvider ) ; return aggregator ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the unit type of an aggregator value . Typically Long or Double . [CODESPLIT] < A extends SimpleAggregator , T > Class < ? extends Number > getAggregatorUnit ( Class < A > klass ) { try { A aggregator = ( A ) CONSTRUCTORS . get ( klass ) . newInstance ( \"forAggregatorTypeDiscoveryOnly\" ) ; return aggregator . getValueType ( ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an AggregatorData . [CODESPLIT] < A extends SimpleAggregator , T > AggregatorData < A , T > createAggregatorData ( Class < A > klass , String name , long timeWindowMillis ) { try { A aggregator = ( A ) CONSTRUCTORS . get ( klass ) . newInstance ( name ) ; return aggregator . createAggregatorData ( timeWindowMillis ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a group - by Agregator . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < A extends SimpleAggregator , N extends Number > GroupByAggregator < A , N > createGroupBy ( String name , Class < ? extends Aggregator > aKlass ) { Utils . checkState ( ! started , \"Already started\" ) ; GroupByAggregator < A , N > aggregator = new GroupByAggregator ( name , aKlass , this ) ; dataProvider . addAggregator ( aggregator ) ; aggregator . setDataProvider ( dataProvider ) ; return aggregator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the Aggregators instance . [CODESPLIT] public void start ( long newDataWindowEndTimeMillis ) { Utils . checkState ( ! started , \"Already started\" ) ; Utils . checkState ( ! stopped , \"Already stopped\" ) ; dataProvider . start ( newDataWindowEndTimeMillis ) ; started = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the Aggregators instance . [CODESPLIT] public Map < Aggregator , AggregatorData > stop ( ) { Utils . checkState ( started , \"Already started\" ) ; Utils . checkState ( ! stopped , \"Already stopped\" ) ; Map < Aggregator , AggregatorData > aggregatorDataMap = dataProvider . stop ( ) ; stopped = true ; return aggregatorDataMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically rolls the DataWindow of all aggregators associated with the Aggregators instance . [CODESPLIT] public Map < Aggregator , AggregatorData > roll ( long newDataWindowEndTimeMillis ) { Utils . checkState ( started , \"Not started\" ) ; Utils . checkState ( ! stopped , \"Already stopped\" ) ; return dataProvider . roll ( newDataWindowEndTimeMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate precision or scale in context of record and given field path . [CODESPLIT] private static int resolveScaleOrPrecisionExpression ( String type , Field field , String attributeName , String fieldPath ) throws JdbcStageCheckedException { String stringValue = field . getAttribute ( attributeName ) ; try { return Integer . parseInt ( stringValue ) ; } catch ( NumberFormatException e ) { throw new JdbcStageCheckedException ( JdbcErrors . JDBC_304 , type , fieldPath , attributeName , stringValue , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance of LoginManager and increases its reference count . [CODESPLIT] public static final LoginManager acquireLoginManager ( LoginType loginType , Map < String , ? > configs ) throws IOException , LoginException { synchronized ( LoginManager . class ) { LoginManager loginManager = CACHED_INSTANCES . get ( loginType ) ; if ( loginManager == null ) { loginManager = new LoginManager ( loginType , configs ) ; CACHED_INSTANCES . put ( loginType , loginManager ) ; } return loginManager . acquire ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decrease the reference count for this instance and release resources if it reaches 0 . [CODESPLIT] public void release ( ) { synchronized ( LoginManager . class ) { if ( refCount == 0 ) throw new IllegalStateException ( \"release called on LoginManager with refCount == 0\" ) ; else if ( refCount == 1 ) { CACHED_INSTANCES . remove ( loginType ) ; login . shutdown ( ) ; } -- refCount ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Should only be used in tests . [CODESPLIT] public static void closeAll ( ) { synchronized ( LoginManager . class ) { for ( LoginType loginType : new ArrayList <> ( CACHED_INSTANCES . keySet ( ) ) ) { LoginManager loginManager = CACHED_INSTANCES . remove ( loginType ) ; loginManager . login . shutdown ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a limited file glob into a simple regex . [CODESPLIT] private static String globToRegex ( String glob ) { if ( glob . charAt ( 0 ) == ' ' || glob . contains ( \"/\" ) || glob . contains ( \"~\" ) ) { throw new IllegalArgumentException ( \"Invalid character in file glob\" ) ; } // treat dot as a literal. glob = glob . replace ( \".\" , \"\\\\.\" ) ; glob = glob . replace ( \"*\" , \".+\" ) ; glob = glob . replace ( \"?\" , \".{1}+\" ) ; return glob ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes one or more { @link NetflowV5Message } from a packet . For this method the data ( ByteBuf ) is assumed to be complete ( i . e . it will contain all the data ) which is the case for UDP . [CODESPLIT] public void decodeStandaloneBuffer ( ByteBuf buf , List < BaseNetflowMessage > resultMessages , InetSocketAddress sender , InetSocketAddress recipient ) throws OnRecordErrorException { final List < Object > results = new LinkedList <> ( ) ; try { decode ( null , buf , results , sender , recipient , true ) ; for ( Object result : results ) { if ( result == null ) { LOG . warn ( \"null result found from decoding standalone Netflow buffer; skipping\" ) ; continue ; } if ( result instanceof BaseNetflowMessage ) { resultMessages . add ( ( BaseNetflowMessage ) result ) ; } else { throw new IllegalStateException ( String . format ( \"Found unexpected object type in results: %s\" , result . getClass ( ) . getName ( ) ) ) ; } } } finally { resetStateVariables ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists objects from AmazonS3 in lexicographical order [CODESPLIT] static List < S3ObjectSummary > listObjectsLexicographically ( AmazonS3 s3Client , S3ConfigBean s3ConfigBean , AntPathMatcher pathMatcher , S3Offset s3Offset , int fetchSize ) { // Incrementally scan objects after the marker (s3Offset). List < S3ObjectSummary > list = new ArrayList <> ( fetchSize ) ; ListObjectsRequest listObjectsRequest = new ListObjectsRequest ( ) ; listObjectsRequest . setBucketName ( s3ConfigBean . s3Config . bucket ) ; listObjectsRequest . setPrefix ( s3ConfigBean . s3Config . commonPrefix ) ; listObjectsRequest . setMaxKeys ( BATCH_SIZE ) ; if ( s3Offset . getKey ( ) != null ) { listObjectsRequest . setMarker ( s3Offset . getKey ( ) ) ; } ObjectListing objectListing = s3Client . listObjects ( listObjectsRequest ) ; while ( true ) { for ( S3ObjectSummary s : objectListing . getObjectSummaries ( ) ) { String fullPrefix = s . getKey ( ) ; String remainingPrefix = fullPrefix . substring ( s3ConfigBean . s3Config . commonPrefix . length ( ) , fullPrefix . length ( ) ) ; if ( ! remainingPrefix . isEmpty ( ) ) { if ( pathMatcher . match ( s3ConfigBean . s3FileConfig . prefixPattern , remainingPrefix ) ) { list . add ( s ) ; } // We've got enough objects. if ( list . size ( ) == fetchSize ) { return list ; } } } // Listing is complete. No more objects to be listed. if ( ! objectListing . isTruncated ( ) ) { break ; } objectListing = s3Client . listNextBatchOfObjects ( objectListing ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists objects from AmazonS3 in chronological order [ lexicographical order if 2 files have same timestamp ] which are later than or equal to the timestamp of the previous offset object [CODESPLIT] static List < S3ObjectSummary > listObjectsChronologically ( AmazonS3 s3Client , S3ConfigBean s3ConfigBean , AntPathMatcher pathMatcher , S3Offset s3Offset , int fetchSize ) { //Algorithm: // - Full scan all objects that match the file name pattern and which are later than the file in the offset // - Select the oldest \"fetchSize\" number of files and return them. TreeSet < S3ObjectSummary > treeSet = new TreeSet <> ( ( o1 , o2 ) -> { int result = o1 . getLastModified ( ) . compareTo ( o2 . getLastModified ( ) ) ; if ( result != 0 ) { //same modified time. Use name to sort return result ; } return o1 . getKey ( ) . compareTo ( o2 . getKey ( ) ) ; } ) ; S3Objects s3ObjectSummaries = S3Objects . withPrefix ( s3Client , s3ConfigBean . s3Config . bucket , s3ConfigBean . s3Config . commonPrefix ) ; // SDC-9413: since the s3ObjectSummaries is in lexical order, we should get all list of files in one api call for ( S3ObjectSummary s : s3ObjectSummaries ) { String fullPrefix = s . getKey ( ) ; String remainingPrefix = fullPrefix . substring ( s3ConfigBean . s3Config . commonPrefix . length ( ) , fullPrefix . length ( ) ) ; if ( ! remainingPrefix . isEmpty ( ) ) { // remainingPrefix can be empty. // If the user manually creates a prefix \"myFolder/mySubFolder\" in bucket \"myBucket\" and uploads \"myObject\", // then the first objects returned here are: // myFolder/mySubFolder // myFolder/mySubFolder/myObject // // All is good when pipeline is run but preview returns with no data. So we should ignore the empty file as it // has no data if ( pathMatcher . match ( s3ConfigBean . s3FileConfig . prefixPattern , remainingPrefix ) && isEligible ( s , s3Offset ) ) { treeSet . add ( s ) ; } if ( treeSet . size ( ) > fetchSize ) { treeSet . pollLast ( ) ; } } } return new ArrayList <> ( treeSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ------------------------------------------------------------ [CODESPLIT] @ Override protected String [ ] loadRoleInfo ( UserPrincipal user ) { UserIdentity id = _userStore . getUserIdentity ( user . getName ( ) ) ; if ( id == null ) return null ; Set < RolePrincipal > roles = id . getSubject ( ) . getPrincipals ( RolePrincipal . class ) ; if ( roles == null ) return null ; List < String > list = roles . stream ( ) . map ( RolePrincipal :: getName ) . collect ( Collectors . toList ( ) ) ; return list . toArray ( new String [ roles . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ------------------------------------------------------------ [CODESPLIT] @ Override protected UserPrincipal loadUserInfo ( String userName ) { UserIdentity id = _userStore . getUserIdentity ( userName ) ; if ( id != null ) { return ( UserPrincipal ) id . getUserPrincipal ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Since stages are allowed to produce events during destroy () phase we handle the destroy event as simplified runBatch . We go over all the StagePipes and if it s on data path we destroy it immediately if it s on event path we run it one more time . Since the stages are sorted we know that destroyed stage will never be needed again . Non stage pipes are always processed to generate required structures in PipeBatch . [CODESPLIT] @ Override public void destroy ( SourcePipe originPipe , List < PipeRunner > pipeRunners , BadRecordsHandler badRecordsHandler , StatsAggregationHandler statsAggregationHandler ) throws StageException , PipelineRuntimeException { // We're no longer running running = false ; // There are two ways a runner can be in use - used by real runner (e.g. when origin produced data) or when it's // processing \"empty\" batch when the runner was idle for too long. The first case is guarded by the framework - this // method won't be called until the execution successfully finished. However the second way with idle drivers is run // from a separate thread and hence we have to ensure here that it's \"done\" before moving on with the destroy phase. try { destroyLock . lock ( ) ; // Firstly destroy the runner, to make sure that any potential run away thread from origin will be denied // further processing. if ( runnerPool != null ) { runnerPool . destroy ( ) ; } int batchSize = configuration . get ( Constants . MAX_BATCH_SIZE_KEY , Constants . MAX_BATCH_SIZE_DEFAULT ) ; long lastBatchTime = offsetTracker . getLastBatchTime ( ) ; long start = System . currentTimeMillis ( ) ; FullPipeBatch pipeBatch ; // Destroy origin pipe pipeBatch = new FullPipeBatch ( null , null , batchSize , false ) ; try { LOG . trace ( \"Destroying origin pipe\" ) ; pipeBatch . skipStage ( originPipe ) ; originPipe . destroy ( pipeBatch ) ; } catch ( RuntimeException e ) { LOG . warn ( \"Exception throw while destroying pipe\" , e ) ; } // Now destroy the pipe runners // // We're destroying them in reverser order to make sure that the last runner to destroy is the one with id '0' // that holds reference to all class loaders. Runners with id >0 do not own their class loaders and hence needs to // be destroyed before the runner with id '0'. for ( PipeRunner pipeRunner : Lists . reverse ( pipeRunners ) ) { final FullPipeBatch finalPipeBatch = pipeBatch ; pipeRunner . executeBatch ( null , null , start , pipe -> { // Set the last batch time in the stage context of each pipe ( ( StageContext ) pipe . getStage ( ) . getContext ( ) ) . setLastBatchTime ( lastBatchTime ) ; String instanceName = pipe . getStage ( ) . getConfiguration ( ) . getInstanceName ( ) ; if ( pipe instanceof StagePipe ) { // Stage pipes are processed only if they are in event path if ( pipe . getStage ( ) . getConfiguration ( ) . isInEventPath ( ) ) { LOG . trace ( \"Stage pipe {} is in event path, running last process\" , instanceName ) ; pipe . process ( finalPipeBatch ) ; } else { LOG . trace ( \"Stage pipe {} is in data path, skipping it's processing.\" , instanceName ) ; finalPipeBatch . skipStage ( pipe ) ; } } else { // Non stage pipes are executed always LOG . trace ( \"Non stage pipe {}, running last process\" , instanceName ) ; pipe . process ( finalPipeBatch ) ; } // And finally destroy the pipe try { LOG . trace ( \"Running destroy for {}\" , instanceName ) ; pipe . destroy ( finalPipeBatch ) ; } catch ( RuntimeException e ) { LOG . warn ( \"Exception throw while destroying pipe\" , e ) ; } } ) ; badRecordsHandler . handle ( null , null , pipeBatch . getErrorSink ( ) , pipeBatch . getSourceResponseSink ( ) ) ; // Next iteration should have new and empty PipeBatch pipeBatch = new FullPipeBatch ( null , null , batchSize , false ) ; pipeBatch . skipStage ( originPipe ) ; } if ( isStatsAggregationEnabled ( ) ) { List < Record > stats = new ArrayList <> ( ) ; statsAggregatorRequests . drainTo ( stats ) ; Object timeSeriesString = pipelineConfigBean . constants . get ( MetricsEventRunnable . TIME_SERIES_ANALYSIS ) ; boolean timeSeriesAnalysis = ( timeSeriesString != null ) ? ( Boolean ) timeSeriesString : true ; String metricRegistryStr ; try { metricRegistryStr = ObjectMapperFactory . get ( ) . writer ( ) . writeValueAsString ( metrics ) ; } catch ( Exception e ) { throw new RuntimeException ( Utils . format ( \"Error converting metric json to string: {}\" , e ) , e ) ; } LOG . info ( \"Queueing last batch of record to be sent to stats aggregator\" ) ; stats . add ( AggregatorUtil . createMetricJsonRecord ( runtimeInfo . getId ( ) , runtimeInfo . getMasterSDCId ( ) , pipelineConfiguration . getMetadata ( ) , false , timeSeriesAnalysis , true , metricRegistryStr ) ) ; statsAggregationHandler . handle ( null , null , stats ) ; } } finally { destroyLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops execution of the pipeline after the current batch completes [CODESPLIT] public void stop ( ) throws PipelineException { this . stop = true ; if ( batchesToCapture > 0 ) { cancelSnapshot ( this . snapshotName ) ; snapshotStore . deleteSnapshot ( pipelineName , revision , snapshotName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method should be called periodically from a scheduler if the pipeline should not allow runners to be idle for more then idleTime . [CODESPLIT] public int produceEmptyBatchesForIdleRunners ( long idleTime ) throws PipelineException , StageException { LOG . debug ( \"Checking if any active runner is idle\" ) ; // The empty batch is suppose to be fast - almost as a zero time. It could however happened that from some reason it // will take a long time (possibly more then idleTime). To avoid infinite loops, this method will only processes up // to total number of runners before returning. int counter = 0 ; try { destroyLock . lock ( ) ; while ( running && counter < pipes . size ( ) ) { counter ++ ; PipeRunner runner = null ; try { runner = runnerPool . getIdleRunner ( idleTime ) ; // No more idle runners, simply stop the idle execution now if ( runner == null ) { return counter ; } LOG . debug ( \"Generating empty batch for runner: {}\" , runner . getRunnerId ( ) ) ; pipeContext . getRuntimeStats ( ) . incIdleBatchCount ( ) ; // Pipe batch to keep the batch info FullPipeBatch pipeBatch = new FullPipeBatch ( null , null , 0 , false ) ; pipeBatch . setIdleBatch ( true ) ; // We're explicitly skipping origin because this is framework generated, empty batch pipeBatch . skipStage ( originPipe ) ; executeRunner ( runner , System . currentTimeMillis ( ) , pipeBatch , null , null , new HashMap <> ( ) , new HashMap <> ( ) ) ; } finally { if ( runner != null ) { runnerPool . returnRunner ( runner ) ; } } } } finally { destroyLock . unlock ( ) ; } return counter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create special batch by salvaging memory structures when pipelines gets into un - recoverable error . [CODESPLIT] private void createFailureBatch ( FullPipeBatch pipeBatch ) { if ( ! pipelineConfigBean . shouldCreateFailureSnapshot ) { return ; } try { for ( SnapshotInfo info : snapshotStore . getSummaryForPipeline ( pipelineName , revision ) ) { // Allow only one failure snapshot to be present on a pipeline if ( info . isFailureSnapshot ( ) ) { LOG . trace ( \"Skipping creation of failure snapshot as {} already exists.\" , info . getId ( ) ) ; return ; } } String snapshotName = \"Failure_\" + UUID . randomUUID ( ) . toString ( ) ; String snapshotLabel = \"Failure at \" + LocalDateTime . now ( ) . toString ( ) ; snapshotStore . create ( \"\" , pipelineName , revision , snapshotName , snapshotLabel , true ) ; snapshotStore . save ( pipelineName , revision , snapshotName , - 1 , ImmutableList . of ( pipeBatch . createFailureSnapshot ( ) ) ) ; } catch ( PipelineException ex ) { LOG . error ( \"Can't serialize failure snapshot\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a Record into a fully - bound statement . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private BoundStatement recordToBoundStatement ( Record record ) throws StageException { ImmutableList . Builder < Object > values = new ImmutableList . Builder <> ( ) ; SortedSet < String > columnsPresent = Sets . newTreeSet ( columnMappings . keySet ( ) ) ; for ( Map . Entry < String , String > mapping : columnMappings . entrySet ( ) ) { String columnName = mapping . getKey ( ) ; String fieldPath = mapping . getValue ( ) ; // If we're missing fields, skip them. // If a field is present, but null, also remove it from columnsPresent since we can't write nulls. if ( ! record . has ( fieldPath ) || record . get ( fieldPath ) . getValue ( ) == null ) { columnsPresent . remove ( columnName ) ; continue ; } final Object value = record . get ( fieldPath ) . getValue ( ) ; // Special cases for handling SDC Lists and Maps, // basically unpacking them into raw types. if ( value instanceof List ) { List < Object > unpackedList = new ArrayList <> ( ) ; for ( Field item : ( List < Field > ) value ) { unpackedList . add ( item . getValue ( ) ) ; } values . add ( unpackedList ) ; } else if ( value instanceof Map ) { Map < Object , Object > unpackedMap = new HashMap <> ( ) ; for ( Map . Entry < String , Field > entry : ( ( Map < String , Field > ) value ) . entrySet ( ) ) { unpackedMap . put ( entry . getKey ( ) , entry . getValue ( ) . getValue ( ) ) ; } values . add ( unpackedMap ) ; } else { values . add ( value ) ; } } PreparedStatement stmt = statementCache . getUnchecked ( columnsPresent ) ; // .toArray required to pass in a list to a varargs method. Object [ ] valuesArray = values . build ( ) . toArray ( ) ; BoundStatement boundStmt = null ; try { boundStmt = stmt . bind ( valuesArray ) ; } catch ( CodecNotFoundException | InvalidTypeException | NullPointerException e ) { // NPE can occur if one of the values is a collection type with a null value inside it. Thus, it's a record // error. Note that this runs the risk of mistakenly treating a bug as a record error. // CodecNotFound is caused when there is no type conversion definition available from the provided type // to the target type. errorRecordHandler . onError ( new OnRecordErrorException ( record , Errors . CASSANDRA_06 , record . getHeader ( ) . getSourceId ( ) , e . toString ( ) , e ) ) ; } return boundStmt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { // Validate configuration values and open any required resources. List < ConfigIssue > issues = super . init ( ) ; Target . Context context = getContext ( ) ; Optional . ofNullable ( conf . init ( context , CONF_PREFIX ) ) . ifPresent ( issues :: addAll ) ; errorRecordHandler = new DefaultErrorRecordHandler ( context ) ; sObjectNameVars = getContext ( ) . createELVars ( ) ; sObjectNameEval = context . createELEval ( SOBJECT_NAME ) ; ELUtils . validateExpression ( conf . sObjectNameTemplate , context , Groups . FORCE . getLabel ( ) , SOBJECT_NAME , Errors . FORCE_12 , issues ) ; externalIdFieldVars = getContext ( ) . createELVars ( ) ; externalIdFieldEval = context . createELEval ( EXTERNAL_ID_NAME ) ; ELUtils . validateExpression ( conf . externalIdField , context , Groups . FORCE . getLabel ( ) , EXTERNAL_ID_NAME , Errors . FORCE_24 , issues ) ; if ( issues . isEmpty ( ) ) { fieldMappings = new TreeMap <> ( ) ; for ( ForceFieldMapping mapping : conf . fieldMapping ) { // SDC-7446 Allow colon as well as period as field separator String salesforceField = conf . useBulkAPI ? mapping . salesforceField . replace ( ' ' , ' ' ) : mapping . salesforceField ; fieldMappings . put ( salesforceField , mapping . sdcField ) ; } try { ConnectorConfig partnerConfig = ForceUtils . getPartnerConfig ( conf , new ForceSessionRenewer ( ) ) ; partnerConnection = Connector . newConnection ( partnerConfig ) ; if ( conf . mutualAuth . useMutualAuth ) { ForceUtils . setupMutualAuth ( partnerConfig , conf . mutualAuth ) ; } bulkConnection = ForceUtils . getBulkConnection ( partnerConfig , conf ) ; LOG . info ( \"Successfully authenticated as {}\" , conf . username ) ; } catch ( ConnectionException | AsyncApiException | StageException | URISyntaxException ce ) { LOG . error ( \"Can't connect to SalesForce\" , ce ) ; issues . add ( getContext ( ) . createConfigIssue ( Groups . FORCE . name ( ) , \"connectorConfig\" , Errors . FORCE_00 , ForceUtils . getExceptionCode ( ce ) + \", \" + ForceUtils . getExceptionMessage ( ce ) ) ) ; } if ( conf . useBulkAPI ) { writer = new ForceBulkWriter ( fieldMappings , bulkConnection , getContext ( ) ) ; } else { writer = new ForceSoapWriter ( fieldMappings , partnerConnection ) ; } } // If issues is not empty, the UI will inform the user of each configuration issue in the list. return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void write ( Batch batch ) throws StageException { Multimap < String , Record > partitions = ELUtils . partitionBatchByExpression ( sObjectNameEval , sObjectNameVars , conf . sObjectNameTemplate , batch ) ; Set < String > sObjectNames = partitions . keySet ( ) ; for ( String sObjectName : sObjectNames ) { List < OnRecordErrorException > errors = writer . writeBatch ( sObjectName , partitions . get ( sObjectName ) , this ) ; for ( OnRecordErrorException error : errors ) { errorRecordHandler . onError ( error ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set multiple configs at once . [CODESPLIT] public void set ( Map < String , String > newConfiguration ) { for ( Map . Entry < String , String > entry : newConfiguration . entrySet ( ) ) { if ( entry . getValue ( ) == null ) { this . unset ( entry . getKey ( ) ) ; } else { this . set ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void process ( Record record , SingleLaneProcessor . SingleLaneBatchMaker batchMaker ) throws StageException { RecordEL . setRecordInContext ( tableNameVars , record ) ; String tableName = tableNameEval . eval ( tableNameVars , conf . kuduTableTemplate , String . class ) ; if ( ! conf . caseSensitive ) { tableName = tableName . toLowerCase ( ) ; } LOG . trace ( \"Processing record:{}  TableName={}\" , record . toString ( ) , tableName ) ; try { try { KuduLookupKey key = generateLookupKey ( record , tableName ) ; List < Map < String , Field > > values = cache . get ( key ) ; if ( values . isEmpty ( ) ) { // No record found if ( conf . missingLookupBehavior == MissingValuesBehavior . SEND_TO_ERROR ) { errorRecordHandler . onError ( new OnRecordErrorException ( record , Errors . KUDU_31 ) ) ; } else { // Configured to 'Send to next stage' and 'pass as it is' batchMaker . addRecord ( record ) ; } } else { switch ( conf . multipleValuesBehavior ) { case FIRST_ONLY : setFieldsInRecord ( record , values . get ( 0 ) ) ; batchMaker . addRecord ( record ) ; break ; case SPLIT_INTO_MULTIPLE_RECORDS : for ( Map < String , Field > lookupItem : values ) { Record newRecord = getContext ( ) . cloneRecord ( record ) ; setFieldsInRecord ( newRecord , lookupItem ) ; batchMaker . addRecord ( newRecord ) ; } break ; default : throw new IllegalStateException ( \"Unknown multiple value behavior: \" + conf . multipleValuesBehavior ) ; } } } catch ( ExecutionException e ) { Throwables . propagateIfPossible ( e . getCause ( ) , StageException . class ) ; Throwables . propagateIfPossible ( e . getCause ( ) , OnRecordErrorException . class ) ; throw new IllegalStateException ( e ) ; // The cache loader shouldn't throw anything that isn't a StageException. } } catch ( OnRecordErrorException error ) { // NOSONAR errorRecordHandler . onError ( new OnRecordErrorException ( record , error . getErrorCode ( ) , error . getParams ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a map of keyColumn - value to lookup in cache . [CODESPLIT] private KuduLookupKey generateLookupKey ( final Record record , final String tableName ) throws OnRecordErrorException { Map < String , Field > keyList = new HashMap <> ( ) ; for ( Map . Entry < String , String > key : columnToField . entrySet ( ) ) { String fieldName = key . getValue ( ) ; if ( ! record . has ( fieldName ) ) { throw new OnRecordErrorException ( record , Errors . KUDU_32 , fieldName ) ; } keyList . put ( key . getKey ( ) , record . get ( fieldName ) ) ; } return new KuduLookupKey ( tableName , keyList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "no trespassing ... [CODESPLIT] private Properties getKafkaProperties ( Stage . Context context ) { Properties props = new Properties ( ) ; props . putAll ( conf . kafkaOptions ) ; props . setProperty ( \"bootstrap.servers\" , conf . brokerURI ) ; props . setProperty ( \"group.id\" , conf . consumerGroup ) ; props . setProperty ( \"max.poll.records\" , String . valueOf ( batchSize ) ) ; props . setProperty ( KafkaConstants . KEY_DESERIALIZER_CLASS_CONFIG , conf . keyDeserializer . getKeyClass ( ) ) ; props . setProperty ( KafkaConstants . VALUE_DESERIALIZER_CLASS_CONFIG , conf . valueDeserializer . getValueClass ( ) ) ; props . setProperty ( KafkaConstants . CONFLUENT_SCHEMA_REGISTRY_URL_CONFIG , StringUtils . join ( conf . dataFormatConfig . schemaRegistryUrls , \",\" ) ) ; props . setProperty ( KafkaConstants . AUTO_COMMIT_OFFEST , \"false\" ) ; if ( context . isPreview ( ) ) { props . setProperty ( KafkaConstants . AUTO_OFFSET_RESET_CONFIG , KafkaConstants . AUTO_OFFSET_RESET_PREVIEW_VALUE ) ; } return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether any tables have had partitioning turned off or not and updates the partition map appropriately [CODESPLIT] private void handlePartitioningTurnedOffOrOn ( SortedSetMultimap < TableContext , TableRuntimeContext > reconstructedPartitions ) { for ( TableContext tableContext : reconstructedPartitions . keySet ( ) ) { final SortedSet < TableRuntimeContext > partitions = reconstructedPartitions . get ( tableContext ) ; final TableRuntimeContext lastPartition = partitions . last ( ) ; final TableContext sourceTableContext = lastPartition . getSourceTableContext ( ) ; Utils . checkState ( sourceTableContext . equals ( tableContext ) , String . format ( \"Source table context for %s should match TableContext map key of %s\" , lastPartition . getDescription ( ) , tableContext . getQualifiedName ( ) ) ) ; final boolean partitioningTurnedOff = lastPartition . isPartitioned ( ) && sourceTableContext . getPartitioningMode ( ) == PartitioningMode . DISABLED ; final boolean partitioningTurnedOn = ! lastPartition . isPartitioned ( ) && sourceTableContext . isPartitionable ( ) && sourceTableContext . getPartitioningMode ( ) != PartitioningMode . DISABLED ; if ( ! partitioningTurnedOff && ! partitioningTurnedOn ) { continue ; } final Map < String , String > nextStartingOffsets = new HashMap <> ( ) ; final Map < String , String > nextMaxOffsets = new HashMap <> ( ) ; final int newPartitionSequence = lastPartition . getPartitionSequence ( ) > 0 ? lastPartition . getPartitionSequence ( ) + 1 : 1 ; if ( partitioningTurnedOff ) { LOG . info ( \"Table {} has switched from partitioned to non-partitioned; partition sequence {} will be the last (with\" + \" no max offsets)\" , sourceTableContext . getQualifiedName ( ) , newPartitionSequence ) ; lastPartition . getStartingPartitionOffsets ( ) . forEach ( ( col , off ) -> { String basedOnStartOffset = lastPartition . generateNextPartitionOffset ( col , off ) ; nextStartingOffsets . put ( col , basedOnStartOffset ) ; } ) ; } else if ( partitioningTurnedOn ) { lastPartition . getStartingPartitionOffsets ( ) . forEach ( ( col , off ) -> { String basedOnStoredOffset = lastPartition . getInitialStoredOffsets ( ) . get ( col ) ; nextStartingOffsets . put ( col , basedOnStoredOffset ) ; } ) ; nextStartingOffsets . forEach ( ( col , off ) -> nextMaxOffsets . put ( col , lastPartition . generateNextPartitionOffset ( col , off ) ) ) ; if ( ! reconstructedPartitions . remove ( sourceTableContext , lastPartition ) ) { throw new IllegalStateException ( String . format ( \"Failed to remove partition %s for table %s in switching partitioning from off to on\" , lastPartition . getDescription ( ) , sourceTableContext . getQualifiedName ( ) ) ) ; } LOG . info ( \"Table {} has switched from non-partitioned to partitioned; using last stored offsets as the starting\" + \" offsets for the new partition {}\" , sourceTableContext . getQualifiedName ( ) , newPartitionSequence ) ; } final TableRuntimeContext nextPartition = new TableRuntimeContext ( sourceTableContext , lastPartition . isUsingNonIncrementalLoad ( ) , ( lastPartition . isPartitioned ( ) && ! partitioningTurnedOff ) || partitioningTurnedOn , newPartitionSequence , nextStartingOffsets , nextMaxOffsets ) ; reconstructedPartitions . put ( sourceTableContext , nextPartition ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Basically acquires more tables for the current thread to work on . The maximum a thread can hold is upper bounded to the value the thread number was allocated in { [CODESPLIT] @ VisibleForTesting void acquireTableAsNeeded ( int threadNumber ) throws InterruptedException { if ( ! getOwnedTablesQueue ( ) . isEmpty ( ) && batchTableStrategy == BatchTableStrategy . SWITCH_TABLES ) { final TableRuntimeContext lastOwnedPartition = getOwnedTablesQueue ( ) . pollLast ( ) ; if ( getTableContextMap ( ) . containsValue ( lastOwnedPartition . getSourceTableContext ( ) ) ) { sharedAvailableTablesQueue . offer ( lastOwnedPartition ) ; } TableContext lastOwnedTable = lastOwnedPartition . getSourceTableContext ( ) ; // need to cycle off all partitions from the same table to the end of the queue TableRuntimeContext first = sharedAvailableTablesQueue . peek ( ) ; while ( first != null && first . getSourceTableContext ( ) . equals ( lastOwnedTable ) && ! first . equals ( lastOwnedPartition ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Moving partition {} to end of shared queue to comply with BatchTableStrategy of {}\" , first . getDescription ( ) , batchTableStrategy . getLabel ( ) ) ; } // poll() should never return null since it is actually returning 'first' as we want to move it from the head // of the queue, that's why we are calling offer, to basically remove it from the head but keep it in the queue TableRuntimeContext toMove = sharedAvailableTablesQueue . poll ( ) ; sharedAvailableTablesQueue . offer ( toMove ) ; // Get the new head of the queue first = sharedAvailableTablesQueue . peek ( ) ; } } if ( getOwnedTablesQueue ( ) . isEmpty ( ) ) { TableRuntimeContext head = sharedAvailableTablesQueue . poll ( ) ; if ( head != null ) { offerToOwnedTablesQueue ( head , threadNumber ) ; } } partitionFirstSharedQueueItemIfNeeded ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Examines the first item ( head ) im the shared partition queue and adds a new partition if appropriate< / p > <p > A new partition will be created if the number of partitions for the head item s table is still less than the maximum and that table itself is partitionable< / p > [CODESPLIT] @ VisibleForTesting void partitionFirstSharedQueueItemIfNeeded ( ) { final TableRuntimeContext headPartition = getOwnedTablesQueue ( ) . peek ( ) ; if ( headPartition != null ) { synchronized ( partitionStateLock ) { keepPartitioningIfNeeded ( headPartition ) ; } } else if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"No item at head of shared partition queue\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the next table to work on for the current thread ( Will not return null ) Deque the current element from head of the queue and put it back at the tail to queue . [CODESPLIT] public TableRuntimeContext nextTable ( int threadNumber ) throws InterruptedException { synchronized ( partitionStateLock ) { acquireTableAsNeeded ( threadNumber ) ; final TableRuntimeContext partition = getOwnedTablesQueue ( ) . pollFirst ( ) ; if ( partition != null ) { offerToOwnedTablesQueue ( partition , threadNumber ) ; } return partition ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Each { [CODESPLIT] public void reportDataOrNoMoreData ( TableRuntimeContext tableRuntimeContext , int recordCount , int batchSize , boolean resultSetEndReached , AtomicBoolean tableFinished , AtomicBoolean schemaFinished , List < String > schemaFinishedTables ) { final TableContext sourceContext = tableRuntimeContext . getSourceTableContext ( ) ; // When we see a table with data, we mark isNoMoreDataEventGeneratedAlready to false // so we can generate event again if we don't see data from all tables. if ( recordCount > 0 ) { isNoMoreDataEventGeneratedAlready = false ; tablesWithNoMoreData . remove ( tableRuntimeContext . getSourceTableContext ( ) ) ; remainingSchemasToTableContexts . put ( sourceContext . getSchema ( ) , sourceContext ) ; completedSchemasToTableContexts . remove ( sourceContext . getSchema ( ) , sourceContext ) ; } // we need to account for the activeRuntimeContexts here // if there are still other active contexts in process, then this should do \"nothing\" // if there are not other contexts, we need to figure out what the highest offset completed by the last batch was final boolean noMoreData = recordCount == 0 || resultSetEndReached ; if ( noMoreData ) { tableRuntimeContext . setMarkedNoMoreData ( true ) ; } if ( recordCount > 0 ) { maxPartitionWithDataPerTable . put ( sourceContext , tableRuntimeContext . getPartitionSequence ( ) ) ; } boolean tableExhausted = removePartitionIfNeeded ( tableRuntimeContext ) ; if ( noMoreData ) { if ( tableExhausted ) { synchronized ( this ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Table {} exhausted\" , sourceContext . getQualifiedName ( ) ) ; } final boolean newlyFinished = tablesWithNoMoreData . add ( sourceContext ) ; if ( newlyFinished && tableFinished != null ) { tableFinished . set ( true ) ; } final boolean remainingSchemaChanged = remainingSchemasToTableContexts . remove ( sourceContext . getSchema ( ) , sourceContext ) ; completedSchemasToTableContexts . put ( sourceContext . getSchema ( ) , sourceContext ) ; if ( remainingSchemaChanged && remainingSchemasToTableContexts . get ( sourceContext . getSchema ( ) ) . isEmpty ( ) && schemaFinished != null ) { schemaFinished . set ( true ) ; if ( schemaFinishedTables != null ) { completedSchemasToTableContexts . get ( sourceContext . getSchema ( ) ) . forEach ( t -> schemaFinishedTables . add ( t . getTableName ( ) ) ) ; } } } } } if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"Just released table {}; Number of Tables With No More Data {}\" , tableRuntimeContext . getDescription ( ) , tablesWithNoMoreData . size ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by the main thread { [CODESPLIT] public synchronized boolean shouldGenerateNoMoreDataEvent ( ) { boolean noMoreData = ( ! isNoMoreDataEventGeneratedAlready && tablesWithNoMoreData . size ( ) == tableContextMap . size ( ) ) ; if ( noMoreData ) { isNoMoreDataEventGeneratedAlready = true ; } return noMoreData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Captures valid lines in currentLine and corresponding fields in fieldsFromLogLine . Captures stack traces if any in the argument stackTrace [CODESPLIT] private int readAhead ( Map < String , Field > fieldsFromLogLine , StringBuilder stackTrace ) throws DataParserException , IOException { StringBuilder multilineLog = new StringBuilder ( ) ; int read = readLine ( multilineLog ) ; int numberOfLinesRead = 0 ; while ( read > - 1 ) { try { Map < String , Field > stringFieldMap = parseLogLine ( multilineLog ) ; fieldsFromLogLine . putAll ( stringFieldMap ) ; currentLine . append ( multilineLog ) ; //If the line can be parsed successfully, do not read further //This line will be used in the current record if this is the first line being read //or stored for the next round if there is a line from the previous round. break ; } catch ( DataParserException e ) { //is this the first line being read? Yes -> throw exception if ( previousLine . length ( ) == 0 || maxStackTraceLines == - 1 ) { throw e ; } //otherwise read until we get a line that matches pattern if ( numberOfLinesRead < maxStackTraceLines ) { if ( numberOfLinesRead != 0 ) { stackTrace . append ( \"\\n\" ) ; } stackTrace . append ( multilineLog . toString ( ) ) ; } numberOfLinesRead ++ ; multilineLog . setLength ( 0 ) ; read = readLine ( multilineLog ) ; } } return read ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the reader line length the StringBuilder has up to maxObjectLen chars [CODESPLIT] int readLine ( StringBuilder sb ) throws IOException { int c = reader . read ( ) ; int count = ( c == - 1 ) ? - 1 : 0 ; while ( c > - 1 && ! isOverMaxObjectLen ( count ) && ! checkEolAndAdjust ( c ) ) { count ++ ; sb . append ( ( char ) c ) ; c = reader . read ( ) ; } if ( isOverMaxObjectLen ( count ) ) { sb . setLength ( sb . length ( ) - 1 ) ; while ( c > - 1 && c != ' ' && c != ' ' ) { count ++ ; c = reader . read ( ) ; } checkEolAndAdjust ( c ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns fresh UsageTimer just reset to zero accumulated time [CODESPLIT] public UsageTimer roll ( ) { int multiplier ; synchronized ( this ) { multiplier = getMultiplier ( ) ; changeMultiplier ( - multiplier ) ; //stopAll; } return new UsageTimer ( ) . setName ( getName ( ) ) . changeMultiplier ( multiplier ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable Control Hub on this Data Collector . [CODESPLIT] public static void enableDPM ( DPMInfoJson dpmInfo , Context context ) throws IOException { Utils . checkNotNull ( dpmInfo , \"DPMInfo\" ) ; String dpmBaseURL = normalizeDpmBaseURL ( dpmInfo . getBaseURL ( ) ) ; // Since we support enabling/Disabling DPM, first check if token already exists for the given DPM URL. // If token exists skip first 3 steps String currentDPMBaseURL = context . configuration . get ( RemoteSSOService . DPM_BASE_URL_CONFIG , \"\" ) ; String currentAppAuthToken = context . configuration . get ( RemoteSSOService . SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG , \"\" ) . trim ( ) ; if ( ! currentDPMBaseURL . equals ( dpmBaseURL ) || currentAppAuthToken . length ( ) == 0 ) { // 1. Login to DPM to get user auth token String userAuthToken = retrieveUserToken ( dpmBaseURL , dpmInfo . getUserID ( ) , dpmInfo . getUserPassword ( ) ) ; String appAuthToken = null ; // 2. Create Data Collector application token Response response = null ; try { Map < String , Object > newComponentJson = new HashMap <> ( ) ; newComponentJson . put ( \"organization\" , dpmInfo . getOrganization ( ) ) ; newComponentJson . put ( \"componentType\" , \"dc\" ) ; newComponentJson . put ( \"numberOfComponents\" , 1 ) ; newComponentJson . put ( \"active\" , true ) ; response = ClientBuilder . newClient ( ) . target ( dpmBaseURL + \"/security/rest/v1/organization/\" + dpmInfo . getOrganization ( ) + \"/components\" ) . register ( new CsrfProtectionFilter ( \"CSRF\" ) ) . request ( ) . header ( SSOConstants . X_USER_AUTH_TOKEN , userAuthToken ) . put ( Entity . json ( newComponentJson ) ) ; if ( response . getStatus ( ) != Response . Status . CREATED . getStatusCode ( ) ) { throw new RuntimeException ( Utils . format ( \"DPM Create Application Token failed, status code '{}': {}\" , response . getStatus ( ) , response . readEntity ( String . class ) ) ) ; } List < Map < String , Object > > newComponent = response . readEntity ( new GenericType < List < Map < String , Object > > > ( ) { } ) ; if ( newComponent . size ( ) > 0 ) { appAuthToken = ( String ) newComponent . get ( 0 ) . get ( \"fullAuthToken\" ) ; } else { throw new RuntimeException ( \"DPM Create Application Token failed: No token data from DPM Server.\" ) ; } } finally { if ( response != null ) { response . close ( ) ; } // Logout from DPM logout ( dpmBaseURL , userAuthToken ) ; } // 3. Update App Token file updateTokenFile ( context , appAuthToken ) ; } // 4. Update dpm.properties file updateDpmProperties ( context , dpmBaseURL , dpmInfo . getLabels ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable Control Hub on this Data Collector - with explicit login . [CODESPLIT] public static void disableDPM ( String username , String password , String organizationId , Context context ) throws IOException { String dpmBaseURL = normalizeDpmBaseURL ( context . configuration . get ( RemoteSSOService . DPM_BASE_URL_CONFIG , \"\" ) ) ; String userToken = retrieveUserToken ( dpmBaseURL , username , password ) ; try { disableDPM ( userToken , organizationId , context ) ; } finally { logout ( dpmBaseURL , userToken ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable Control Hub on this Data Collector - using existing auth token . [CODESPLIT] public static void disableDPM ( String userAuthToken , String organizationId , Context context ) throws IOException { // check if DPM enabled if ( ! context . runtimeInfo . isDPMEnabled ( ) ) { throw new RuntimeException ( \"disableDPM is supported only when DPM is enabled\" ) ; } String dpmBaseURL = normalizeDpmBaseURL ( context . configuration . get ( RemoteSSOService . DPM_BASE_URL_CONFIG , \"\" ) ) ; String componentId = context . runtimeInfo . getId ( ) ; // 2. Deactivate Data Collector System Component Response response = null ; try { response = ClientBuilder . newClient ( ) . target ( dpmBaseURL + \"/security/rest/v1/organization/\" + organizationId + \"/components/deactivate\" ) . register ( new CsrfProtectionFilter ( \"CSRF\" ) ) . request ( ) . header ( SSOConstants . X_USER_AUTH_TOKEN , userAuthToken ) . header ( SSOConstants . X_REST_CALL , true ) . post ( Entity . json ( ImmutableList . of ( componentId ) ) ) ; if ( response . getStatus ( ) != Response . Status . OK . getStatusCode ( ) ) { throw new RuntimeException ( Utils . format ( \" Deactivate Data Collector System Component from DPM failed, status code '{}': {}\" , response . getStatus ( ) , response . readEntity ( String . class ) ) ) ; } } finally { if ( response != null ) { response . close ( ) ; } } // 3. Delete Data Collector System Component try { response = ClientBuilder . newClient ( ) . target ( dpmBaseURL + \"/security/rest/v1/organization/\" + organizationId + \"/components/delete\" ) . register ( new CsrfProtectionFilter ( \"CSRF\" ) ) . request ( ) . header ( SSOConstants . X_USER_AUTH_TOKEN , userAuthToken ) . header ( SSOConstants . X_REST_CALL , true ) . post ( Entity . json ( ImmutableList . of ( componentId ) ) ) ; if ( response . getStatus ( ) != Response . Status . OK . getStatusCode ( ) ) { throw new RuntimeException ( Utils . format ( \" Deactivate Data Collector System Component from DPM failed, status code '{}': {}\" , response . getStatus ( ) , response . readEntity ( String . class ) ) ) ; } } finally { if ( response != null ) { response . close ( ) ; } } // 4. Delete from Job Runner SDC list try { response = ClientBuilder . newClient ( ) . target ( dpmBaseURL + \"/jobrunner/rest/v1/sdc/\" + componentId ) . register ( new CsrfProtectionFilter ( \"CSRF\" ) ) . request ( ) . header ( SSOConstants . X_USER_AUTH_TOKEN , userAuthToken ) . header ( SSOConstants . X_REST_CALL , true ) . delete ( ) ; if ( response . getStatus ( ) != Response . Status . OK . getStatusCode ( ) ) { throw new RuntimeException ( Utils . format ( \"Delete from DPM Job Runner SDC list failed, status code '{}': {}\" , response . getStatus ( ) , response . readEntity ( String . class ) ) ) ; } } finally { if ( response != null ) { response . close ( ) ; } } // 5. Update App Token file updateTokenFile ( context , \"\" ) ; // 4. Update dpm.properties file updateDpmProperties ( context , dpmBaseURL , null , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize Control Hub URL - primarily drop training slash . [CODESPLIT] private static String normalizeDpmBaseURL ( String url ) { if ( url . endsWith ( \"/\" ) ) { url = url . substring ( 0 , url . length ( ) - 1 ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Login user and retrieve authentication token . [CODESPLIT] private static String retrieveUserToken ( String url , String username , String password ) { Response response = null ; try { Map < String , String > loginJson = new HashMap <> ( ) ; loginJson . put ( \"userName\" , username ) ; loginJson . put ( \"password\" , password ) ; response = ClientBuilder . newClient ( ) . target ( url + \"/security/public-rest/v1/authentication/login\" ) . register ( new CsrfProtectionFilter ( \"CSRF\" ) ) . request ( ) . post ( Entity . json ( loginJson ) ) ; if ( response . getStatus ( ) != Response . Status . OK . getStatusCode ( ) ) { throw new RuntimeException ( Utils . format ( \"DPM Login failed, status code '{}': {}\" , response . getStatus ( ) , response . readEntity ( String . class ) ) ) ; } } finally { if ( response != null ) { response . close ( ) ; } } return response . getHeaderString ( SSOConstants . X_USER_AUTH_TOKEN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logout given token . [CODESPLIT] private static void logout ( String dpmBaseURL , String userAuthToken ) { Response response = null ; try { response = ClientBuilder . newClient ( ) . target ( dpmBaseURL + \"/security/_logout\" ) . register ( new CsrfProtectionFilter ( \"CSRF\" ) ) . request ( ) . header ( SSOConstants . X_USER_AUTH_TOKEN , userAuthToken ) . cookie ( SSOConstants . AUTHENTICATION_COOKIE_PREFIX + \"LOGIN\" , userAuthToken ) . get ( ) ; } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update token file with the SDC access token . [CODESPLIT] private static void updateTokenFile ( Context context , String appAuthToken ) throws IOException { File tokenFile = context . tokenFilePath == null ? new File ( context . runtimeInfo . getConfigDir ( ) , APP_TOKEN_FILE ) : new File ( context . tokenFilePath ) ; DataStore dataStore = new DataStore ( tokenFile ) ; try ( OutputStream os = dataStore . getOutputStream ( ) ) { IOUtils . write ( appAuthToken , os ) ; dataStore . commit ( os ) ; } finally { dataStore . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update dpm . properties file with new configuration . [CODESPLIT] private static void updateDpmProperties ( Context context , String dpmBaseURL , List < String > labels , boolean enableSch ) { if ( context . skipUpdatingDpmProperties ) { return ; } try { FileBasedConfigurationBuilder < PropertiesConfiguration > builder = new FileBasedConfigurationBuilder <> ( PropertiesConfiguration . class ) . configure ( new Parameters ( ) . properties ( ) . setFileName ( context . runtimeInfo . getConfigDir ( ) + \"/dpm.properties\" ) . setThrowExceptionOnMissing ( true ) . setListDelimiterHandler ( new DefaultListDelimiterHandler ( ' ' ) ) . setIncludesAllowed ( false ) ) ; PropertiesConfiguration config = null ; config = builder . getConfiguration ( ) ; config . setProperty ( RemoteSSOService . DPM_ENABLED , Boolean . toString ( enableSch ) ) ; config . setProperty ( RemoteSSOService . DPM_BASE_URL_CONFIG , dpmBaseURL ) ; config . setProperty ( RemoteSSOService . SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG , APP_TOKEN_FILE_PROP_VAL ) ; if ( labels != null && labels . size ( ) > 0 ) { config . setProperty ( RemoteEventHandlerTask . REMOTE_JOB_LABELS , StringUtils . join ( labels , ' ' ) ) ; } else { config . setProperty ( RemoteEventHandlerTask . REMOTE_JOB_LABELS , \"\" ) ; } builder . save ( ) ; } catch ( ConfigurationException e ) { throw new RuntimeException ( Utils . format ( \"Updating dpm.properties file failed: {}\" , e . getMessage ( ) ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create record and add it to { [CODESPLIT] @ Override public void createAndAddRecord ( ResultSet rs , TableRuntimeContext tableRuntimeContext , BatchContext batchContext ) throws SQLException , StageException { ResultSetMetaData md = rs . getMetaData ( ) ; LinkedHashMap < String , Field > fields = jdbcUtil . resultSetToFields ( rs , commonSourceConfigBean , errorRecordHandler , tableJdbcConfigBean . unknownTypeAction , recordHeader , DatabaseVendor . SQL_SERVER ) ; Map < String , String > columnOffsets = new HashMap <> ( ) ; // Generate Offset includes primary keys, sys_change_version, and sys_change_operation for ( String key : tableRuntimeContext . getSourceTableContext ( ) . getOffsetColumns ( ) ) { String value = rs . getString ( key ) ; if ( Strings . isNullOrEmpty ( value ) ) { value = fields . get ( key ) != null ? fields . get ( key ) . getValueAsString ( ) : \"\" ; } columnOffsets . put ( key , value ) ; } columnOffsets . put ( SYS_CHANGE_OPERATION , rs . getString ( SYS_CHANGE_OPERATION ) ) ; String offsetFormat = OffsetQueryUtil . getOffsetFormat ( columnOffsets ) ; Record record = context . createRecord ( tableRuntimeContext . getQualifiedName ( ) + \"::\" + offsetFormat ) ; record . set ( Field . createListMap ( fields ) ) ; //Set Column Headers jdbcUtil . setColumnSpecificHeaders ( record , Collections . singleton ( tableRuntimeContext . getSourceTableContext ( ) . getTableName ( ) ) , md , JDBC_NAMESPACE_HEADER ) ; //Set Operation Headers int op = MSOperationCode . convertToJDBCCode ( rs . getString ( SYS_CHANGE_OPERATION ) ) ; record . getHeader ( ) . setAttribute ( OperationType . SDC_OPERATION_TYPE , String . valueOf ( op ) ) ; for ( String fieldName : recordHeader ) { record . getHeader ( ) . setAttribute ( JDBC_NAMESPACE_HEADER + fieldName , rs . getString ( fieldName ) != null ? rs . getString ( fieldName ) : \"NULL\" ) ; } int columns = rs . getMetaData ( ) . getColumnCount ( ) ; if ( fields . size ( ) != columns ) { errorRecordHandler . onError ( JdbcErrors . JDBC_35 , fields . size ( ) , columns ) ; return ; // Don't output this record. } else { batchContext . getBatchMaker ( ) . addRecord ( record ) ; } offsets . put ( tableRuntimeContext . getOffsetKey ( ) , offsetFormat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When pullMap is called the caller should have consumed the opening tag for the record [CODESPLIT] private Field pullMap ( XMLEventReader reader ) throws StageException , XMLStreamException { LinkedHashMap < String , Field > map = new LinkedHashMap <> ( ) ; String type = null ; String fieldValue = null ; while ( reader . hasNext ( ) ) { XMLEvent event = reader . nextEvent ( ) ; if ( event . isStartElement ( ) ) { if ( event . asStartElement ( ) . getName ( ) . getLocalPart ( ) . equals ( TYPE ) ) { // Move to content event = reader . nextEvent ( ) ; type = event . asCharacters ( ) . getData ( ) . toLowerCase ( ) ; // Consume closing tag reader . nextEvent ( ) ; } else { String fieldName = event . asStartElement ( ) . getName ( ) . getLocalPart ( ) ; Attribute attr = event . asStartElement ( ) . getAttributeByName ( XSI_TYPE ) ; if ( attr != null && attr . getValue ( ) . equals ( S_OBJECT ) ) { // Element is a nested record map . put ( fieldName , pullMap ( reader ) ) ; } else { event = reader . nextEvent ( ) ; fieldValue = null ; switch ( event . getEventType ( ) ) { case XMLEvent . START_ELEMENT : // Element is a nested list of records // Advance over <done>, <queryLocator> to record list while ( ! ( event . isStartElement ( ) && event . asStartElement ( ) . getName ( ) . getLocalPart ( ) . equals ( RECORDS ) ) ) { event = reader . nextEvent ( ) ; } // Read record list List < Field > recordList = new ArrayList <> ( ) ; while ( event . isStartElement ( ) && event . asStartElement ( ) . getName ( ) . getLocalPart ( ) . equals ( RECORDS ) ) { recordList . add ( pullMap ( reader ) ) ; event = reader . nextEvent ( ) ; } map . put ( fieldName , Field . create ( recordList ) ) ; break ; case XMLEvent . CHARACTERS : // Element is a field value fieldValue = event . asCharacters ( ) . getData ( ) ; // Consume closing tag reader . nextEvent ( ) ; // Intentional fall through to next case! case XMLEvent . END_ELEMENT : // Create the SDC field if ( type == null ) { throw new StageException ( Errors . FORCE_38 ) ; } // Is this a relationship to another object? com . sforce . soap . partner . Field sfdcField = metadataCache . get ( type ) . getFieldFromRelationship ( fieldName ) ; if ( sfdcField != null ) { // See if we already added fields from the related record if ( map . get ( fieldName ) != null ) { // We already created this node - don't overwrite it! sfdcField = null ; } } else { sfdcField = getFieldMetadata ( type , fieldName ) ; } if ( sfdcField != null ) { Field field = createField ( fieldValue , sfdcField ) ; if ( conf . createSalesforceNsHeaders ) { setHeadersOnField ( field , getFieldMetadata ( type , fieldName ) ) ; } map . put ( fieldName , field ) ; } break ; default : throw new StageException ( Errors . FORCE_41 , event . getEventType ( ) ) ; } } } } else if ( event . isEndElement ( ) ) { // Done with record return Field . createListMap ( map ) ; } } throw new StageException ( Errors . FORCE_39 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Terminates the request with an HTTP Unauthorized response [CODESPLIT] protected Authentication returnUnauthorized ( HttpServletRequest httpReq , HttpServletResponse httpRes , String principalId , String logMessageTemplate ) throws ServerAuthException { return returnUnauthorized ( httpReq , httpRes , UNAUTHORIZED_JSON , principalId , logMessageTemplate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate schema for given field and optionally wrap it in union with null if configured . [CODESPLIT] private Schema . Field schemaFieldForType ( String fieldPath , Record record , String fieldName , Field field ) throws OnRecordErrorException { Schema simpleSchema = simpleSchemaForType ( fieldPath , record , field ) ; Schema finalSchema = simpleSchema ; // If Nullable check box was selected, wrap the whole schema in union with null if ( getConfig ( ) . avroNullableFields ) { finalSchema = Schema . createUnion ( ImmutableList . of ( Schema . create ( Schema . Type . NULL ) , simpleSchema ) ) ; } return new Schema . Field ( fieldName , finalSchema , null , getDefaultValue ( simpleSchema ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates complex schema for given field that will include optional union with null and potentially default value as well . Particularly useful to generate nested structures . [CODESPLIT] private Schema complexSchemaForType ( String fieldPath , Record record , Field field ) throws OnRecordErrorException { Schema simpleSchema = simpleSchemaForType ( fieldPath , record , field ) ; Schema finalSchema = simpleSchema ; if ( getConfig ( ) . avroNullableFields ) { finalSchema = Schema . createUnion ( ImmutableList . of ( Schema . create ( Schema . Type . NULL ) , simpleSchema ) ) ; } JsonNode defaultValue = getDefaultValue ( simpleSchema ) ; if ( defaultValue != null ) { finalSchema . addProp ( \"defaultValue\" , defaultValue ) ; } return finalSchema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate simple schema for given field - it will never contain union nor a default value . Particularly useful for generating Schema . Field as this will not convert simple string to { type : string defaultValue : something } which is hard to undo . [CODESPLIT] private Schema simpleSchemaForType ( String fieldPath , Record record , Field field ) throws OnRecordErrorException { switch ( field . getType ( ) ) { // Primitive types case BOOLEAN : return Schema . create ( Schema . Type . BOOLEAN ) ; case INTEGER : return Schema . create ( Schema . Type . INT ) ; case LONG : return Schema . create ( Schema . Type . LONG ) ; case FLOAT : return Schema . create ( Schema . Type . FLOAT ) ; case DOUBLE : return Schema . create ( Schema . Type . DOUBLE ) ; case STRING : return Schema . create ( Schema . Type . STRING ) ; case BYTE_ARRAY : return Schema . create ( Schema . Type . BYTES ) ; // Logical types case DECIMAL : int precision = getDecimalScaleOrPrecision ( record , field , getConfig ( ) . precisionAttribute , getConfig ( ) . defaultPrecision , 1 ) ; int scale = getDecimalScaleOrPrecision ( record , field , getConfig ( ) . scaleAttribute , getConfig ( ) . defaultScale , 0 ) ; Schema decimalSchema = Schema . create ( Schema . Type . BYTES ) ; decimalSchema . addProp ( AvroTypeUtil . LOGICAL_TYPE , AvroTypeUtil . LOGICAL_TYPE_DECIMAL ) ; decimalSchema . addProp ( AvroTypeUtil . LOGICAL_TYPE_ATTR_PRECISION , new IntNode ( precision ) ) ; decimalSchema . addProp ( AvroTypeUtil . LOGICAL_TYPE_ATTR_SCALE , new IntNode ( scale ) ) ; return decimalSchema ; case DATE : Schema dateSchema = Schema . create ( Schema . Type . INT ) ; dateSchema . addProp ( AvroTypeUtil . LOGICAL_TYPE , AvroTypeUtil . LOGICAL_TYPE_DATE ) ; return dateSchema ; case TIME : Schema timeSchema = Schema . create ( Schema . Type . INT ) ; timeSchema . addProp ( AvroTypeUtil . LOGICAL_TYPE , AvroTypeUtil . LOGICAL_TYPE_TIME_MILLIS ) ; return timeSchema ; case DATETIME : Schema dateTimeSchema = Schema . create ( Schema . Type . LONG ) ; dateTimeSchema . addProp ( AvroTypeUtil . LOGICAL_TYPE , AvroTypeUtil . LOGICAL_TYPE_TIMESTAMP_MILLIS ) ; return dateTimeSchema ; // Complex types case LIST : // In avro list must be of the same type - which is not true with our records // We can't generate the list type from empty list if ( field . getValueAsList ( ) . isEmpty ( ) ) { throw new OnRecordErrorException ( record , Errors . SCHEMA_GEN_0006 , fieldPath ) ; } // And all items in the list must have the same schema Schema itemSchema = null ; int index = 0 ; for ( Field listItem : field . getValueAsList ( ) ) { Schema currentListItemSchema = complexSchemaForType ( fieldPath + \"[\" + index + \"]\" , record , listItem ) ; if ( itemSchema == null ) { itemSchema = currentListItemSchema ; } else if ( ! itemSchema . equals ( currentListItemSchema ) ) { throw new OnRecordErrorException ( record , Errors . SCHEMA_GEN_0005 , fieldPath , itemSchema , currentListItemSchema ) ; } index ++ ; } return Schema . createArray ( itemSchema ) ; case MAP : case LIST_MAP : // In avro maps must have key of string (same as us) and value must be the same for all items - which // is different then our records. // We can't generate the map value type from null or empty map if ( field . getValueAsMap ( ) == null || field . getValueAsMap ( ) . isEmpty ( ) ) { throw new OnRecordErrorException ( record , Errors . SCHEMA_GEN_0008 , fieldPath ) ; } // And all values in the map must be the same Schema mapSchema = null ; for ( Map . Entry < String , Field > item : field . getValueAsMap ( ) . entrySet ( ) ) { Schema currentListItemSchema = complexSchemaForType ( fieldPath + \"/\" + item . getKey ( ) , record , item . getValue ( ) ) ; if ( mapSchema == null ) { mapSchema = currentListItemSchema ; } else if ( ! mapSchema . equals ( currentListItemSchema ) ) { throw new OnRecordErrorException ( record , Errors . SCHEMA_GEN_0007 , fieldPath , mapSchema , currentListItemSchema ) ; } } return Schema . createMap ( mapSchema ) ; // Types that does not have direct equivalent in Avro case SHORT : if ( getConfig ( ) . avroExpandTypes ) { return Schema . create ( Schema . Type . INT ) ; } // fall through case CHAR : if ( getConfig ( ) . avroExpandTypes ) { return Schema . create ( Schema . Type . STRING ) ; } // fall through // Not supported data types: case BYTE : case FILE_REF : default : throw new OnRecordErrorException ( record , Errors . SCHEMA_GEN_0002 , field . getType ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve parameters of decimal type . [CODESPLIT] private int getDecimalScaleOrPrecision ( Record record , Field field , String attributeName , int defaultValue , int minAllowed ) throws OnRecordErrorException { int finalValue = - 1 ; // Invalid value // Firstly try the field attribute String stringValue = field . getAttribute ( attributeName ) ; if ( ! StringUtils . isEmpty ( stringValue ) ) { finalValue = Integer . valueOf ( stringValue ) ; } // If it's invalid, then use the default value if ( finalValue < minAllowed ) { finalValue = defaultValue ; } // If even the default value is invalid, then send the record to error if ( finalValue < minAllowed ) { throw new OnRecordErrorException ( record , Errors . SCHEMA_GEN_0004 , finalValue , field ) ; } return finalValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns default value for given field or null if no default value should be used . [CODESPLIT] private JsonNode getDefaultValue ( Schema schema ) { if ( getConfig ( ) . avroNullableFields && getConfig ( ) . avroDefaultNullable ) { return NullNode . getInstance ( ) ; } if ( ! getConfig ( ) . avroNullableFields && defaultValuesForTypes . containsKey ( schema . getType ( ) ) ) { return defaultValuesForTypes . get ( schema . getType ( ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a gauge if it is already not . This is done only once for the stage [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static synchronized void initMetricsIfNeeded ( ProtoConfigurableEntity . Context context ) { Gauge < Map < String , Object > > gauge = context . getGauge ( fileStatisticGaugeName ( context ) ) ; if ( gauge == null ) { gauge = context . createGauge ( fileStatisticGaugeName ( context ) , Comparator . comparing ( GAUGE_MAP_ORDERING :: get ) ) ; Map < String , Object > gaugeStatistics = gauge . getValue ( ) ; //File name is populated at the MetricEnabledWrapperStream. gaugeStatistics . put ( FileRefUtil . FILE , \"\" ) ; gaugeStatistics . put ( FileRefUtil . TRANSFER_THROUGHPUT , 0L ) ; gaugeStatistics . put ( FileRefUtil . SENT_BYTES , String . format ( FileRefUtil . BRACKETED_TEMPLATE , 0 , 0 ) ) ; gaugeStatistics . put ( FileRefUtil . REMAINING_BYTES , 0L ) ; gaugeStatistics . put ( FileRefUtil . COMPLETED_FILE_COUNT , 0L ) ; } Meter dataTransferMeter = context . getMeter ( FileRefUtil . TRANSFER_THROUGHPUT_METER ) ; if ( dataTransferMeter == null ) { context . createMeter ( FileRefUtil . TRANSFER_THROUGHPUT_METER ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is a simple wrapper that lets us find the NoSuchFileException if that was the cause . [CODESPLIT] public int compare ( WrappedFile path1 , WrappedFile path2 , boolean useLastModified ) { // why not just check if the file exists? Well, there is a possibility file gets moved/archived/deleted right after // that check. In that case we will still fail. So fail, and recover. try { if ( useLastModified && ! exists ( path2 ) ) { return 1 ; } return getComparator ( useLastModified ) . compare ( path1 , path2 ) ; } catch ( RuntimeException ex ) { Throwable cause = ex . getCause ( ) ; // Happens only in timestamp ordering. // Very unlikely this will happen, new file has to be added to the queue at the exact time when // the currentFile was consumed and archived while a new file has not yet been picked up for processing. // Ignore - we just add the new file, since this means this file is indeed newer // (else this would have been consumed and archived first) if ( cause != null && cause instanceof NoSuchFileException ) { LOG . debug ( \"Starting file may have already been archived.\" , cause ) ; return 1 ; } LOG . warn ( \"Error while comparing files\" , ex ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the group index of a named capture group at the specified index . If only one instance of the named group exists use index 0 . [CODESPLIT] public int indexOf ( String groupName , int index ) { int idx = - 1 ; if ( groupInfo . containsKey ( groupName ) ) { List < GroupInfo > list = groupInfo . get ( groupName ) ; idx = list . get ( index ) . groupIndex ( ) ; } return idx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the names of all capture groups [CODESPLIT] public List < String > groupNames ( ) { if ( groupNames == null ) { groupNames = new ArrayList < String > ( groupInfo . keySet ( ) ) ; } return groupNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the character at the specified position of a string is escaped [CODESPLIT] static private boolean isEscapedChar ( String s , int pos ) { return isSlashEscapedChar ( s , pos ) || isQuoteEscapedChar ( s , pos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the character at the specified position of a string is escaped with a backslash [CODESPLIT] static private boolean isSlashEscapedChar ( String s , int pos ) { // Count the backslashes preceding this position. If it's // even, there is no escape and the slashes are just literals. // If it's odd, one of the slashes (the last one) is escaping // the character at the given position. int numSlashes = 0 ; while ( pos > 0 && ( s . charAt ( pos - 1 ) == ' ' ) ) { pos -- ; numSlashes ++ ; } return numSlashes % 2 != 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the character at the specified position of a string is quote - escaped ( between \\\\ Q and \\\\ E ) [CODESPLIT] static private boolean isQuoteEscapedChar ( String s , int pos ) { boolean openQuoteFound = false ; boolean closeQuoteFound = false ; // find last non-escaped open-quote String s2 = s . substring ( 0 , pos ) ; int posOpen = pos ; while ( ( posOpen = s2 . lastIndexOf ( \"\\\\Q\" , posOpen - 1 ) ) != - 1 ) { if ( ! isSlashEscapedChar ( s2 , posOpen ) ) { openQuoteFound = true ; break ; } } if ( openQuoteFound ) { // search remainder of string (after open-quote) for a close-quote; // no need to check that it's slash-escaped because it can't be // (the escape character itself is part of the literal when quoted) if ( s2 . indexOf ( \"\\\\E\" , posOpen ) != - 1 ) { closeQuoteFound = true ; } } return openQuoteFound && ! closeQuoteFound ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if a string s character is within a regex character class [CODESPLIT] static private boolean isInsideCharClass ( String s , int pos ) { boolean openBracketFound = false ; boolean closeBracketFound = false ; // find last non-escaped open-bracket String s2 = s . substring ( 0 , pos ) ; int posOpen = pos ; while ( ( posOpen = s2 . lastIndexOf ( ' ' , posOpen - 1 ) ) != - 1 ) { if ( ! isEscapedChar ( s2 , posOpen ) ) { openBracketFound = true ; break ; } } if ( openBracketFound ) { // search remainder of string (after open-bracket) for a close-bracket String s3 = s . substring ( posOpen , pos ) ; int posClose = - 1 ; while ( ( posClose = s3 . indexOf ( ' ' , posClose + 1 ) ) != - 1 ) { if ( ! isEscapedChar ( s3 , posClose ) ) { closeBracketFound = true ; break ; } } } return openBracketFound && ! closeBracketFound ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the parenthesis at the specified position of a string is for a non - capturing group which is one of the flag specifiers ( e . g . ( ?s ) or ( ?m ) or ( ? : pattern ) . If the parenthesis is followed by ? it must be a non - capturing group unless it s a named group ( which begins with ?< ) . Make sure not to confuse it with the lookbehind construct ( ?< = or ?<! ) . [CODESPLIT] static private boolean isNoncapturingParen ( String s , int pos ) { //int len = s.length(); boolean isLookbehind = false ; // code-coverage reports show that pos and the text to // check never exceed len in this class, so it's safe // to not test for it, which resolves uncovered branches // in Cobertura /*if (pos >= 0 && pos + 4 < len)*/ { String pre = s . substring ( pos , pos + 4 ) ; isLookbehind = pre . equals ( \"(?<=\" ) || pre . equals ( \"(?<!\" ) ; } return /*(pos >= 0 && pos + 2 < len) &&*/ s . charAt ( pos + 1 ) == ' ' && ( isLookbehind || s . charAt ( pos + 2 ) != ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Counts the open - parentheses to the left of a string position excluding escaped parentheses [CODESPLIT] static private int countOpenParens ( String s , int pos ) { java . util . regex . Pattern p = java . util . regex . Pattern . compile ( \"\\\\(\" ) ; java . util . regex . Matcher m = p . matcher ( s . subSequence ( 0 , pos ) ) ; int numParens = 0 ; while ( m . find ( ) ) { // ignore parentheses inside character classes: [0-9()a-f] // which are just literals if ( isInsideCharClass ( s , m . start ( ) ) ) { continue ; } // ignore escaped parens if ( isEscapedChar ( s , m . start ( ) ) ) continue ; if ( ! isNoncapturingParen ( s , m . start ( ) ) ) { numParens ++ ; } } return numParens ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses info on named capture groups from a pattern [CODESPLIT] static public Map < String , List < GroupInfo > > extractGroupInfo ( String namedPattern ) { Map < String , List < GroupInfo > > groupInfo = new LinkedHashMap < String , List < GroupInfo > > ( ) ; java . util . regex . Matcher matcher = NAMED_GROUP_PATTERN . matcher ( namedPattern ) ; while ( matcher . find ( ) ) { int pos = matcher . start ( ) ; // ignore escaped paren if ( isEscapedChar ( namedPattern , pos ) ) continue ; String name = matcher . group ( INDEX_GROUP_NAME ) ; int groupIndex = countOpenParens ( namedPattern , pos ) ; List < GroupInfo > list ; if ( groupInfo . containsKey ( name ) ) { list = groupInfo . get ( name ) ; } else { list = new ArrayList < GroupInfo > ( ) ; } list . add ( new GroupInfo ( groupIndex , pos ) ) ; groupInfo . put ( name , list ) ; } return groupInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces strings matching a pattern with another string . If the string to be replaced is escaped with a slash it is skipped . [CODESPLIT] static private StringBuilder replace ( StringBuilder input , java . util . regex . Pattern pattern , String replacement ) { java . util . regex . Matcher m = pattern . matcher ( input ) ; while ( m . find ( ) ) { if ( isEscapedChar ( input . toString ( ) , m . start ( ) ) ) { continue ; } // since we're replacing the original string being matched, // we have to reset the matcher so that it searches the new // string input . replace ( m . start ( ) , m . end ( ) , replacement ) ; m . reset ( input ) ; } return input ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces referenced group names with the reference to the corresponding group index ( e . g . <b > <code > \\ k&lt ; named > < / code > < / b > } to <b > <code > \\ k2< / code > < / b > } ; <b > <code > $ { named } < / code > < / b > to <b > <code > $2< / code > < / b > } ) . This assumes the group names have already been parsed from the pattern . [CODESPLIT] private StringBuilder replaceGroupNameWithIndex ( StringBuilder input , java . util . regex . Pattern pattern , String prefix ) { java . util . regex . Matcher m = pattern . matcher ( input ) ; while ( m . find ( ) ) { if ( isEscapedChar ( input . toString ( ) , m . start ( ) ) ) { continue ; } int index = indexOf ( m . group ( INDEX_GROUP_NAME ) ) ; if ( index >= 0 ) { index ++ ; } else { throw new PatternSyntaxException ( \"unknown group name\" , input . toString ( ) , m . start ( INDEX_GROUP_NAME ) ) ; } // since we're replacing the original string being matched, // we have to reset the matcher so that it searches the new // string input . replace ( m . start ( ) , m . end ( ) , prefix + index ) ; m . reset ( input ) ; } return input ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a { @code java . util . regex . Pattern } from a given regular expression pattern ( which may contain named groups ) and flags [CODESPLIT] private java . util . regex . Pattern buildStandardPattern ( String namedPattern , Integer flags ) { // replace the named-group construct with left-paren but // make sure we're actually looking at the construct (ignore escapes) StringBuilder s = new StringBuilder ( namedPattern ) ; s = replace ( s , NAMED_GROUP_PATTERN , \"(\" ) ; s = replaceGroupNameWithIndex ( s , BACKREF_NAMED_GROUP_PATTERN , \"\\\\\" ) ; return java . util . regex . Pattern . compile ( s . toString ( ) , flags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a GET request for the specified resource . [CODESPLIT] @ Override public void doGet ( HttpServletRequest request , HttpServletResponse response ) { try { JsonGenerator jg = null ; String jsonpcb = null ; PrintWriter writer = null ; try { writer = response . getWriter ( ) ; // \"callback\" parameter implies JSONP outpout jsonpcb = request . getParameter ( CALLBACK_PARAM ) ; if ( jsonpcb != null ) { response . setContentType ( \"application/javascript; charset=utf8\" ) ; writer . write ( jsonpcb + \"(\" ) ; } else { response . setContentType ( \"application/json; charset=utf8\" ) ; } jg = jsonFactory . createGenerator ( writer ) ; jg . disable ( JsonGenerator . Feature . AUTO_CLOSE_TARGET ) ; jg . useDefaultPrettyPrinter ( ) ; jg . writeStartObject ( ) ; // query per mbean attribute String getmethod = request . getParameter ( \"get\" ) ; if ( getmethod != null ) { String [ ] splitStrings = getmethod . split ( \"\\\\:\\\\:\" ) ; if ( splitStrings . length != 2 ) { jg . writeStringField ( \"result\" , \"ERROR\" ) ; jg . writeStringField ( \"message\" , \"query format is not as expected.\" ) ; jg . flush ( ) ; response . setStatus ( HttpServletResponse . SC_BAD_REQUEST ) ; return ; } listBeans ( jg , new ObjectName ( splitStrings [ 0 ] ) , splitStrings [ 1 ] , response ) ; return ; } // query per mbean String qry = request . getParameter ( \"qry\" ) ; if ( qry == null ) { qry = \"*:*\" ; } listBeans ( jg , new ObjectName ( qry ) , null , response ) ; } finally { if ( jg != null ) { jg . close ( ) ; } if ( jsonpcb != null ) { writer . write ( \");\" ) ; } if ( writer != null ) { writer . close ( ) ; } } } catch ( IOException e ) { response . setStatus ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; } catch ( MalformedObjectNameException e ) { response . setStatus ( HttpServletResponse . SC_BAD_REQUEST ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--------------------------------------------------------- Private Methods [CODESPLIT] private void listBeans ( JsonGenerator jg , ObjectName qry , String attribute , HttpServletResponse response ) throws IOException { Set < ObjectName > names = null ; names = mBeanServer . queryNames ( qry , null ) ; jg . writeArrayFieldStart ( \"beans\" ) ; Iterator < ObjectName > it = names . iterator ( ) ; while ( it . hasNext ( ) ) { ObjectName oname = it . next ( ) ; MBeanInfo minfo ; String code = \"\" ; Object attributeinfo = null ; try { minfo = mBeanServer . getMBeanInfo ( oname ) ; code = minfo . getClassName ( ) ; String prs = \"\" ; try { if ( \"org.apache.commons.modeler.BaseModelMBean\" . equals ( code ) ) { prs = \"modelerType\" ; code = ( String ) mBeanServer . getAttribute ( oname , prs ) ; } if ( attribute != null ) { prs = attribute ; attributeinfo = mBeanServer . getAttribute ( oname , prs ) ; } } catch ( AttributeNotFoundException e ) { // If the modelerType attribute was not found, the class name is used // instead. } catch ( MBeanException e ) { // The code inside the attribute getter threw an exception so // and fall back on the class name } catch ( RuntimeException e ) { // For some reason even with an MBeanException available to them // Runtime exceptionscan still find their way through, so treat them // the same as MBeanException } catch ( ReflectionException e ) { // This happens when the code inside the JMX bean (setter?? from the // java docs) threw an exception, so // class name } } catch ( InstanceNotFoundException e ) { //Ignored for some reason the bean was not found so don't output it continue ; } catch ( IntrospectionException e ) { // This is an internal error, something odd happened with reflection so // continue ; } catch ( ReflectionException e ) { // This happens when the code inside the JMX bean threw an exception, so // continue ; } jg . writeStartObject ( ) ; jg . writeStringField ( \"name\" , oname . toString ( ) ) ; jg . writeStringField ( \"modelerType\" , code ) ; if ( ( attribute != null ) && ( attributeinfo == null ) ) { jg . writeStringField ( \"result\" , \"ERROR\" ) ; jg . writeStringField ( \"message\" , \"No attribute with name \" + attribute + \" was found.\" ) ; jg . writeEndObject ( ) ; jg . writeEndArray ( ) ; jg . close ( ) ; response . setStatus ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } if ( attribute != null ) { writeAttribute ( jg , attribute , attributeinfo ) ; } else { MBeanAttributeInfo attrs [ ] = minfo . getAttributes ( ) ; for ( int i = 0 ; i < attrs . length ; i ++ ) { writeAttribute ( jg , oname , attrs [ i ] ) ; } } jg . writeEndObject ( ) ; } jg . writeEndArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh the schema for the table if the last update of this table was before the given SCN . Returns true if it was updated else returns false . [CODESPLIT] private boolean refreshSchema ( BigDecimal scnDecimal , SchemaAndTable schemaAndTable ) throws SQLException { try { if ( ! tableSchemaLastUpdate . containsKey ( schemaAndTable ) || scnDecimal . compareTo ( tableSchemaLastUpdate . get ( schemaAndTable ) ) > 0 ) { if ( containerized ) { try ( Statement switchToPdb = connection . createStatement ( ) ) { switchToPdb . execute ( \"ALTER SESSION SET CONTAINER = \" + configBean . pdb ) ; } } tableSchemas . put ( schemaAndTable , getTableSchema ( schemaAndTable ) ) ; tableSchemaLastUpdate . put ( schemaAndTable , scnDecimal ) ; return true ; } return false ; } finally { alterSession ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method needs to get SQL like string with all required schemas and tables . [CODESPLIT] @ VisibleForTesting String getListOfSchemasAndTables ( List < SchemaAndTable > schemaAndTables ) { Map < String , List < String > > schemas = new HashMap <> ( ) ; for ( SchemaAndTable schemaAndTable : schemaAndTables ) { if ( schemas . containsKey ( schemaAndTable . getSchema ( ) ) ) { schemas . get ( schemaAndTable . getSchema ( ) ) . add ( schemaAndTable . getTable ( ) ) ; } else { List < String > tbls = new ArrayList <> ( ) ; tbls . add ( schemaAndTable . getTable ( ) ) ; schemas . put ( schemaAndTable . getSchema ( ) , tbls ) ; } } List < String > queries = new ArrayList <> ( ) ; for ( Map . Entry < String , List < String > > entry : schemas . entrySet ( ) ) { List < String > tables = new ArrayList <> ( ) ; int fromIndex = 0 ; int range = 1000 ; int maxIndex = entry . getValue ( ) . size ( ) ; int toIndex = range < maxIndex ? range : maxIndex ; while ( fromIndex < toIndex ) { tables . add ( Utils . format ( \"TABLE_NAME IN ({})\" , formatTableList ( entry . getValue ( ) . subList ( fromIndex , toIndex ) ) ) ) ; fromIndex = toIndex ; toIndex = ( toIndex + range ) < maxIndex ? ( toIndex + range ) : maxIndex ; } queries . add ( Utils . format ( \"(SEG_OWNER='{}' AND ({}))\" , entry . getKey ( ) , String . join ( \" OR \" , tables ) ) ) ; } return \"( \" + String . join ( \" OR \" , queries ) + \" )\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An element is expired if the transaction started before the current window being processed and if no records have actually been sent to the pipeline . If a record has been sent then a commit was seen so it is not expired . [CODESPLIT] private boolean expired ( Map . Entry < TransactionIdKey , HashQueue < RecordSequence > > entry , LocalDateTime startTime ) { return startTime != null && // Can be null if starting from SCN and first batch is not complete yet. entry . getKey ( ) . txnStartTime . isBefore ( startTime . minusSeconds ( configBean . txnWindow ) ) && entry . getValue ( ) . peek ( ) . seq == 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "offset will be negative if we are in truncate mode . [CODESPLIT] @ Override public long getOffset ( ) { Utils . checkState ( open , Utils . formatL ( \"LiveFileReder for '{}' is not open\" , currentFile ) ) ; return ( truncateMode ) ? - offset : offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if still in truncate mode false otherwise [CODESPLIT] private boolean fastForward ( ) throws IOException { try { boolean stillTruncate ; buffer . clear ( ) ; if ( channel . read ( buffer ) > - 1 || isEof ( ) ) { //set the buffer into read from mode buffer . flip ( ) ; //we have data, lets look for the first EOL in it. int firstEolIdx = findEndOfFirstLine ( buffer ) ; if ( firstEolIdx > - 1 ) { // set position to position after first EOL buffer . position ( firstEolIdx + 1 ) ; // set the buffer back into write into mode keeping data after first EOL buffer . compact ( ) ; stillTruncate = false ; offset = channel . position ( ) - buffer . position ( ) ; } else { // no EOL yet // whatever was read will be discarded on next next() call stillTruncate = true ; offset = channel . position ( ) ; } } else { // no data read // whatever was read will be discarded on next next() call stillTruncate = true ; offset = channel . position ( ) ; } return stillTruncate ; } catch ( IOException ex ) { closeChannel ( ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------- Private Members --------------------------------------------------- [CODESPLIT] private static void initRabbitConf ( Channel channel , BaseRabbitConfigBean conf ) throws IOException { // Channel is always bound to the default exchange. When specified, we must declare the exchange. for ( RabbitExchangeConfigBean exchange : conf . exchanges ) { channel . exchangeDeclare ( exchange . name , exchange . type . getValue ( ) , exchange . durable , exchange . autoDelete , exchange . declarationProperties ) ; } channel . queueDeclare ( conf . queue . name , conf . queue . durable , conf . queue . exclusive , conf . queue . autoDelete , conf . queue . properties ) ; for ( RabbitExchangeConfigBean exchange : conf . exchanges ) { bindQueue ( channel , conf , exchange ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detached stage APIs [CODESPLIT] @ Path ( \"/detachedstage\" ) @ GET @ ApiOperation ( value = \"Returns empty envelope for detached stage.\" , response = DetachedStageConfigurationJson . class , authorizations = @ Authorization ( value = \"basic\" ) ) @ Produces ( MediaType . APPLICATION_JSON ) @ RolesAllowed ( { AuthzRole . CREATOR , AuthzRole . ADMIN , AuthzRole . CREATOR_REMOTE , AuthzRole . ADMIN_REMOTE } ) public Response createDetachedStageEnvelope ( ) throws PipelineException { DetachedStageConfigurationJson detachedStage = new DetachedStageConfigurationJson ( new DetachedStageConfiguration ( ) ) ; return Response . ok ( ) . entity ( detachedStage ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "max array size will be limit + 1 ( because the magic byte is being added ) [CODESPLIT] static byte [ ] extract ( InputStream is , ByteArrayOutputStream overflowBuffer , int limit ) throws IOException { // the inputstream we get has been already stripped of the magic byte if first call byte [ ] message ; if ( copy ( is , overflowBuffer , limit - overflowBuffer . size ( ) ) ) { // got rest of payload without exceeding the max message size if ( overflowBuffer . size ( ) == 0 ) { // there is no more payload message = null ; } else { // extract the rest payload and prefix it with the magic byte byte [ ] data = overflowBuffer . toByteArray ( ) ; message = new byte [ data . length + 1 ] ; message [ 0 ] = JSON1_MAGIC_NUMBER ; System . arraycopy ( data , 0 , message , 1 , data . length ) ; overflowBuffer . reset ( ) ; } } else { // got partial payload, exceeded the max message size byte [ ] data = overflowBuffer . toByteArray ( ) ; // find last full record in partial payload int lastEOL = findEndOfLastLineBeforeLimit ( data , limit ) ; if ( lastEOL == - 1 ) { throw new IOException ( Utils . format ( \"Maximum message size '{}' exceeded\" , limit ) ) ; } // extract payload up to last EOL and prefix with the magic byte message = new byte [ lastEOL + 1 ] ; message [ 0 ] = JSON1_MAGIC_NUMBER ; System . arraycopy ( data , 0 , message , 1 , lastEOL ) ; // put back in the stream buffer the portion of the payload that did not make it to the message overflowBuffer . reset ( ) ; overflowBuffer . write ( data , lastEOL , data . length - lastEOL ) ; } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContextExtensions [CODESPLIT] @ Override public RecordReader createRecordReader ( InputStream inputStream , long initialPosition , int maxObjectLen ) throws IOException { return RecordWriterReaderFactory . createRecordReader ( inputStream , initialPosition , maxObjectLen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We need to support Strings as some information that user might need to deal with is inherently stored in String variables - for example header values or CSV files . [CODESPLIT] private static Object convertStringToAppropriateNumber ( String value ) { if ( value . contains ( \".\" ) ) { return Double . valueOf ( value ) ; } else { return Long . valueOf ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a collectd packet part . [CODESPLIT] private int parsePart ( int startOffset , ByteBuf buf , Map < String , Field > fields ) throws OnRecordErrorException { int offset = startOffset ; int type = buf . getUnsignedShort ( offset ) ; // 0-1 offset += 2 ; final int length = buf . getUnsignedShort ( offset ) ; // 2-3 offset += 2 ; switch ( type ) { case HOST : case PLUGIN : case PLUGIN_INSTANCE : case TYPE : case TYPE_INSTANCE : case MESSAGE : pruneFields ( type ) ; fields . put ( PART_TYPES . get ( type ) , Field . create ( parseString ( offset , length , buf ) ) ) ; offset += length - 4 ; break ; case TIME_HIRES : case INTERVAL_HIRES : if ( type != INTERVAL_HIRES || ! excludeInterval ) { long value = parseNumeric ( offset , buf ) ; if ( convertTime ) { value *= ( Math . pow ( 2 , - 30 ) * 1000 ) ; type = type == TIME_HIRES ? TIME : INTERVAL ; } fields . put ( PART_TYPES . get ( type ) , Field . create ( value ) ) ; } offset += 8 ; break ; case TIME : case INTERVAL : case SEVERITY : if ( type != INTERVAL || ! excludeInterval ) { fields . put ( PART_TYPES . get ( type ) , Field . create ( parseNumeric ( offset , buf ) ) ) ; } offset += 8 ; break ; case VALUES : offset = parseValues ( offset , buf ) ; startNewRecord ( ) ; break ; case SIGNATURE : if ( ! verifySignature ( offset , length , buf ) ) { throw new OnRecordErrorException ( Errors . COLLECTD_02 ) ; } offset += length - 4 ; break ; case ENCRYPTION : String user = parseUser ( offset , buf ) ; offset += ( 2 + user . length ( ) ) ; byte [ ] iv = parseIv ( offset , buf ) ; offset += 16 ; decrypt ( offset , length , buf , user , iv ) ; // Skip the checksum and continue processing. offset += 20 ; break ; default : // Don't recognize this part type, so skip it LOG . warn ( \"Unrecognized part type: {}\" , type ) ; offset += length - 4 ; break ; } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the value part of the packet where metrics are located [CODESPLIT] private int parseValues ( int startOffset , ByteBuf buf ) throws OnRecordErrorException { int offset = startOffset ; // N Values // For each Value: // 1 byte data type code int numValues = buf . getUnsignedShort ( offset ) ; // 4-5 offset += 2 ; List < Byte > types = new ArrayList <> ( numValues ) ; while ( numValues -- > 0 ) { types . add ( buf . getByte ( offset ) ) ; offset += 1 ; } for ( int i = 0 ; i < types . size ( ) ; i ++ ) { Byte type = types . get ( i ) ; String label = getValueLabel ( i , type ) ; switch ( type ) { case COUNTER : fields . put ( label , Field . create ( buf . getUnsignedInt ( offset ) ) ) ; offset += 8 ; break ; case GAUGE : fields . put ( label , Field . create ( buf . order ( ByteOrder . LITTLE_ENDIAN ) . getDouble ( offset ) ) ) ; offset += 8 ; break ; case DERIVE : fields . put ( label , Field . create ( buf . getLong ( offset ) ) ) ; offset += 8 ; break ; case ABSOLUTE : fields . put ( label , Field . create ( buf . getUnsignedInt ( offset ) ) ) ; offset += 8 ; break ; default : // error throw new OnRecordErrorException ( Errors . COLLECTD_01 , type ) ; } } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapted from https : // stackoverflow . com / a / 7932774 / 375670 [CODESPLIT] public static Field getUnsignedShortField ( byte [ ] bytes ) { Utils . checkState ( bytes . length == 2 , \"2 bytes required to parse an unsigned short\" ) ; final short shortVal = Shorts . fromByteArray ( bytes ) ; int intVal = shortVal >= 0 ? shortVal : 0x10000 + shortVal ; return Field . create ( intVal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It takes a record structure in <String HiveTypeInfo > format . Generate a schema and return in String . [CODESPLIT] @ Override public String inferSchema ( Map < String , HiveTypeInfo > record ) throws StageException { Map < String , Schema > fields = new LinkedHashMap <> ( ) ; for ( Map . Entry < String , HiveTypeInfo > pair : record . entrySet ( ) ) { if ( ! HiveMetastoreUtil . validateObjectName ( pair . getKey ( ) ) ) { throw new HiveStageCheckedException ( Errors . HIVE_30 , pair . getKey ( ) ) ; } Schema columnSchema = Schema . createUnion ( ImmutableList . of ( Schema . create ( Schema . Type . NULL ) , traverse ( pair ) ) ) ; // We always set default value to null columnSchema . addProp ( \"default\" , NullNode . getInstance ( ) ) ; fields . put ( pair . getKey ( ) , columnSchema ) ; } Schema schema = buildSchema ( fields ) ; return schema . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Our own implementation of JDBCType . valueOf () that won t throw an exception in case of unknown type . [CODESPLIT] public static String nameForType ( DatabaseVendor vendor , int jdbcType ) { for ( JDBCType sqlType : JDBCType . class . getEnumConstants ( ) ) { if ( jdbcType == sqlType . getVendorTypeNumber ( ) ) return sqlType . name ( ) ; } switch ( vendor ) { case ORACLE : switch ( jdbcType ) { case - 101 : return \"TIMESTAMP WITH TIME ZONE\" ; case - 102 : return \"TIMESTAMP WITH LOCAL TIME ZONE\" ; } break ; } return \"Unknown\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns qualified table name ( schema . table name ) [CODESPLIT] public static String getQualifiedTableName ( String schema , String tableName ) { return StringUtils . isEmpty ( schema ) ? tableName : schema + \".\" + tableName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns quoted qualified table name ( schema . table name ) based on quoteChar [CODESPLIT] public static String getQuotedQualifiedTableName ( String schema , String tableName , String qC ) { String quotedTableName = String . format ( OffsetQueryUtil . QUOTED_NAME , qC , tableName , qC ) ; return StringUtils . isEmpty ( schema ) ? quotedTableName : String . format ( OffsetQueryUtil . QUOTED_NAME , qC , schema , qC ) + \".\" + quotedTableName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate ELs in Initial offsets as needed and populate the final String representation of initial offsets in { [CODESPLIT] private void populateInitialOffset ( PushSource . Context context , List < Stage . ConfigIssue > issues , Map < String , String > configuredColumnToInitialOffset , TableJdbcELEvalContext tableJdbcELEvalContext , Map < String , String > offsetColumnToStartOffset ) throws StageException { for ( Map . Entry < String , String > partitionColumnInitialOffsetEntry : configuredColumnToInitialOffset . entrySet ( ) ) { String value ; try { value = tableJdbcELEvalContext . evaluateAsString ( \"offsetColumnToInitialOffsetValue\" , partitionColumnInitialOffsetEntry . getValue ( ) ) ; if ( value == null ) { issues . add ( context . createConfigIssue ( Groups . TABLE . name ( ) , TableJdbcConfigBean . TABLE_CONFIG , JdbcErrors . JDBC_73 , partitionColumnInitialOffsetEntry . getValue ( ) , Utils . format ( \"Expression returned date as null. Check Expression\" ) ) ) ; return ; } } catch ( ELEvalException e ) { issues . add ( context . createConfigIssue ( Groups . TABLE . name ( ) , TableJdbcConfigBean . TABLE_CONFIG , JdbcErrors . JDBC_73 , partitionColumnInitialOffsetEntry . getValue ( ) , e ) ) ; return ; } offsetColumnToStartOffset . put ( partitionColumnInitialOffsetEntry . getKey ( ) , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists all tables matching the { [CODESPLIT] public Map < String , TableContext > listTablesForConfig ( DatabaseVendor vendor , PushSource . Context context , List < Stage . ConfigIssue > issues , Connection connection , TableConfigBean tableConfigBean , TableJdbcELEvalContext tableJdbcELEvalContext , QuoteChar quoteChar ) throws SQLException , StageException { Map < String , TableContext > tableContextMap = new LinkedHashMap <> ( ) ; Pattern tableExclusion = StringUtils . isEmpty ( tableConfigBean . tableExclusionPattern ) ? null : Pattern . compile ( tableConfigBean . tableExclusionPattern ) ; Pattern schemaExclusion = StringUtils . isEmpty ( tableConfigBean . schemaExclusionPattern ) ? null : Pattern . compile ( tableConfigBean . schemaExclusionPattern ) ; try ( ResultSet rs = jdbcUtil . getTableAndViewMetadata ( connection , tableConfigBean . schema , tableConfigBean . tablePattern ) ) { while ( rs . next ( ) ) { String schemaName = rs . getString ( TABLE_METADATA_TABLE_SCHEMA_CONSTANT ) ; String tableName = rs . getString ( TABLE_METADATA_TABLE_NAME_CONSTANT ) ; if ( ( tableExclusion == null || ! tableExclusion . matcher ( tableName ) . matches ( ) ) && ( schemaExclusion == null || ! schemaExclusion . matcher ( schemaName ) . matches ( ) ) ) { TableContext tableContext = createTableContext ( vendor , context , issues , connection , schemaName , tableName , tableConfigBean , tableJdbcELEvalContext , quoteChar ) ; if ( tableContext != null ) { tableContextMap . put ( getQualifiedTableName ( schemaName , tableName ) , tableContext ) ; } } } } return tableContextMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Access the database obtain a list of primary key columns and store them in primaryKeyColumns . If table has no primary keys primaryKeyColumns stays empty . [CODESPLIT] void lookupPrimaryKeys ( ) throws StageException { Connection connection = null ; try { connection = dataSource . getConnection ( ) ; primaryKeyColumns = jdbcUtil . getPrimaryKeys ( connection , schema , tableName ) ; } catch ( SQLException e ) { String formattedError = jdbcUtil . formatSqlException ( e ) ; LOG . error ( formattedError , e ) ; throw new StageException ( JdbcErrors . JDBC_17 , tableName , formattedError ) ; } finally { if ( connection != null ) { try { connection . close ( ) ; } catch ( SQLException e ) { String formattedError = jdbcUtil . formatSqlException ( e ) ; LOG . error ( formattedError , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Access database and obtain the metadata for the table . Store columnName and / columnName to the columnsToFields map as a default column - to - field mapping . Store columnName and ? to columnsToParameters map as a default column - to - value mapping . They will be updated later in createCustomFieldMappings () . [CODESPLIT] private void createDefaultFieldMappings ( ) throws StageException { try ( Connection connection = dataSource . getConnection ( ) ) { try ( ResultSet res = jdbcUtil . getTableMetadata ( connection , schema , tableName ) ) { if ( ! res . next ( ) ) { throw new StageException ( JdbcErrors . JDBC_16 , getTableName ( ) ) ; } } try ( ResultSet columns = jdbcUtil . getColumnMetadata ( connection , schema , tableName ) ) { while ( columns . next ( ) ) { String columnName = columns . getString ( COLUMN_NAME ) ; columnsToFields . put ( columnName , \"/\" + columnName ) ; // Default implicit field mappings columnsToParameters . put ( columnName , \"?\" ) ; columnType . put ( columnName , columns . getInt ( DATA_TYPE ) ) ; } } } catch ( SQLException e ) { String errorMessage = jdbcUtil . formatSqlException ( e ) ; LOG . error ( errorMessage ) ; LOG . debug ( errorMessage , e ) ; throw new StageException ( JdbcErrors . JDBC_09 , tableName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use Field to Column Mapping option obtained from configuration and update columnsToFields and columnsToParameters . [CODESPLIT] private void createCustomFieldMappings ( ) { for ( JdbcFieldColumnParamMapping mapping : customMappings ) { LOG . debug ( \"Custom mapping field {} to column {}\" , mapping . field , mapping . columnName ) ; if ( columnsToFields . containsKey ( mapping . columnName ) ) { LOG . debug ( \"Mapping field {} to column {}\" , mapping . field , mapping . columnName ) ; columnsToFields . put ( mapping . columnName , mapping . field ) ; columnsToParameters . put ( mapping . columnName , mapping . paramValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "spec requires a string name for a data type rather than just an enum . [CODESPLIT] static String getSQLTypeName ( Field . Type type ) throws OnRecordErrorException { switch ( type ) { case BOOLEAN : return \"BOOLEAN\" ; case CHAR : return \"CHAR\" ; case BYTE : return \"BINARY\" ; case SHORT : return \"SMALLINT\" ; case INTEGER : return \"INTEGER\" ; case LONG : return \"BIGINT\" ; case FLOAT : return \"FLOAT\" ; case DOUBLE : return \"DOUBLE\" ; case DATE : return \"DATE\" ; case TIME : return \"TIME\" ; case DATETIME : return \"TIMESTAMP\" ; case DECIMAL : return \"DECIMAL\" ; case STRING : return \"VARCHAR\" ; case BYTE_ARRAY : return \"VARBINARY\" ; case LIST_MAP : case MAP : throw new OnRecordErrorException ( JdbcErrors . JDBC_05 , \"Unsupported list or map type: MAP\" ) ; case LIST : return \"ARRAY\" ; default : throw new OnRecordErrorException ( JdbcErrors . JDBC_05 , \"Unsupported type: \" + type . name ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Table this writer will write to . [CODESPLIT] protected String getTableName ( ) { if ( ! Strings . isNullOrEmpty ( schema ) ) { if ( caseSensitive ) { return \"\\\"\" + schema + \"\\\".\" + \"\\\"\" + tableName + \"\\\"\" ; } else { return schema + \".\" + tableName ; } } if ( caseSensitive ) { return \"\\\"\" + tableName + \"\\\"\" ; } return tableName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set primary key values to query . This is called only for UPDATE and DELETE operations . If primary key value is missing in record it throws OnRecordErrorException . [CODESPLIT] int setPrimaryKeys ( int index , final Record record , PreparedStatement statement , int opCode ) throws OnRecordErrorException { for ( String key : getPrimaryKeyColumns ( ) ) { Field field = record . get ( recordReader . getFieldPath ( key , getColumnsToFields ( ) , opCode ) ) ; if ( field == null ) { LOG . error ( \"Primary key {} is missing in record\" , key ) ; throw new OnRecordErrorException ( record , JdbcErrors . JDBC_19 , key ) ; } Object value = field . getValue ( ) ; try { statement . setObject ( index , value , getColumnType ( key ) ) ; } catch ( SQLException ex ) { LOG . error ( \"SQLException thrown: {}\" , ex . getMessage ( ) ) ; throw new OnRecordErrorException ( record , JdbcErrors . JDBC_19 , key , ex ) ; } ++ index ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is an error that is not due to bad input record and should throw a StageException once we format the error . [CODESPLIT] void handleSqlException ( SQLException e ) throws StageException { String formattedError = jdbcUtil . formatSqlException ( e ) ; LOG . error ( formattedError , e ) ; throw new StageException ( JdbcErrors . JDBC_14 , e . getSQLState ( ) , e . getErrorCode ( ) , e . getMessage ( ) , formattedError , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the numeric operation code from record header . The default code is used if the operation code is not found in the header . [CODESPLIT] protected int getOperationCode ( Record record , List < OnRecordErrorException > errorRecords ) { return recordReader . getOperationFromRecord ( record , defaultOpCode , unsupportedAction , errorRecords ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split records according to tuples ( schemaName tableName ) [CODESPLIT] public Multimap < SchemaAndTable , Record > classify ( Batch batch ) throws OnRecordErrorException { Multimap < SchemaAndTable , Record > partitions = ArrayListMultimap . create ( ) ; Iterator < Record > batchIterator = batch . getRecords ( ) ; while ( batchIterator . hasNext ( ) ) { Record record = batchIterator . next ( ) ; String schemaName = schemaNameExpr ; String tableName = tableNameExpr ; if ( dynamicSchemaName ) { try { RecordEL . setRecordInContext ( schemaNameVars , record ) ; schemaName = schemaNameEval . eval ( schemaNameVars , schemaNameExpr , String . class ) ; LOG . debug ( \"Expression '{}' is evaluated to '{}' : \" , schemaNameExpr , schemaName ) ; } catch ( ELEvalException e ) { LOG . error ( \"Failed to evaluate expression '{}' : \" , schemaNameExpr , e . toString ( ) , e ) ; throw new OnRecordErrorException ( record , e . getErrorCode ( ) , e . getParams ( ) ) ; } } if ( dynamicTableName ) { try { RecordEL . setRecordInContext ( tableNameVars , record ) ; tableName = tableNameEval . eval ( tableNameVars , tableNameExpr , String . class ) ; LOG . debug ( \"Expression '{}' is evaluated to '{}' : \" , tableNameExpr , tableName ) ; } catch ( ELEvalException e ) { LOG . error ( \"Failed to evaluate expression '{}' : \" , tableNameExpr , e . toString ( ) , e ) ; throw new OnRecordErrorException ( record , e . getErrorCode ( ) , e . getParams ( ) ) ; } } SchemaAndTable partitionKey = new SchemaAndTable ( schemaName , tableName ) ; partitions . put ( partitionKey , record ) ; } return partitions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process method for Push source that will give control of the execution to the origin . [CODESPLIT] public void process ( Map < String , String > offsets , int batchSize , ReportErrorDelegate reportErrorDelegate ) throws StageException , PipelineRuntimeException { this . reportErrorDelegate = reportErrorDelegate ; getStage ( ) . setReportErrorDelegate ( this ) ; try { MDC . put ( LogConstants . STAGE , getStage ( ) . getInfo ( ) . getInstanceName ( ) ) ; getStage ( ) . execute ( offsets , batchSize ) ; } finally { MDC . put ( LogConstants . STAGE , \"\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by PipelineRunner when push origin started a new batch to prepare context for it . [CODESPLIT] public void prepareBatchContext ( BatchContextImpl batchContext ) { PipeBatch pipeBatch = batchContext . getPipeBatch ( ) ; // Start stage in the pipe batch and persist reference to batch maker in the batch context BatchMakerImpl batchMaker = pipeBatch . startStage ( this ) ; batchContext . setBatchMaker ( batchMaker ) ; batchContext . setOriginStageName ( getStage ( ) . getInfo ( ) . getInstanceName ( ) , getStage ( ) . getInfo ( ) . getLabel ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finish batch from the origin s perspective . [CODESPLIT] public Map < String , Object > finishBatchContext ( BatchContextImpl batchContext ) throws StageException { return finishBatchAndCalculateMetrics ( batchContext . getStartTime ( ) , batchContext . getPipeBatch ( ) , ( BatchMakerImpl ) batchContext . getBatchMaker ( ) , batchContext . getPipeBatch ( ) . getBatch ( this ) , batchContext . getPipeBatch ( ) . getErrorSink ( ) , batchContext . getPipeBatch ( ) . getEventSink ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flatten the entire record to one giant map [CODESPLIT] private Map < String , Field > flattenEntireRecord ( Field rootField ) { Map < String , Field > ret = new LinkedHashMap <> ( ) ; switch ( rootField . getType ( ) ) { case MAP : case LIST_MAP : flattenMap ( \"\" , rootField . getValueAsMap ( ) , ret ) ; break ; case LIST : flattenList ( \"\" , rootField . getValueAsList ( ) , ret ) ; break ; default : break ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new instance of detached stage runtime . [CODESPLIT] public static < T > DetachedStageRuntime < ? extends T > create ( StageBean bean , Stage . Info info , Stage . Context context , Class < T > klass ) { switch ( bean . getDefinition ( ) . getType ( ) ) { case PROCESSOR : return new DetachedStageRuntime . DetachedProcessor ( bean , info , context ) ; case TARGET : case EXECUTOR : return new DetachedStageRuntime . DetachedTarget ( bean , info , context ) ; default : throw new RuntimeException ( \"Unsupported stage type: \" + bean . getDefinition ( ) . getType ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes an action for given record . [CODESPLIT] private void execute ( Record record ) throws OnRecordErrorException { // This is a contrived example, normally you may be performing an operation that could throw // an exception or produce an error condition. In that case you can throw an OnRecordErrorException // to send this record to the error pipeline with some details. if ( ! record . has ( \"/someField\" ) ) { throw new OnRecordErrorException ( Errors . SAMPLE_01 , record , \"exception detail message.\" ) ; } // TODO: execute action }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records from MySQL BinLog origin have a bit unique structure . [CODESPLIT] @ Override public SortedMap < String , String > getColumnsToParameters ( final Record record , int op , Map < String , String > parameters , Map < String , String > columnsToFields ) { SortedMap < String , String > columnsToParameters = new TreeMap <> ( ) ; for ( Map . Entry < String , String > entry : columnsToFields . entrySet ( ) ) { String columnName = entry . getKey ( ) ; String fieldPath = entry . getValue ( ) ; if ( op == OperationType . DELETE_CODE ) { fieldPath = fieldPath . replace ( DATA_FIELD , OLD_DATA_FIELD ) ; } if ( record . has ( fieldPath ) ) { columnsToParameters . put ( columnName , parameters . get ( columnName ) ) ; } } return columnsToParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a fieldpath for the corresponding column name . The columnToField Map contains column - to - field mapping so simply get fieldpath for the column name if operation is INSERT or UPDATE . We replace / Data to / OldData for delete operation because that s where records store primary key info . [CODESPLIT] @ Override String getFieldPath ( String columnName , Map < String , String > columnsToField , int op ) { if ( op == OperationType . DELETE_CODE ) { String fieldPath = columnsToField . get ( columnName ) ; if ( fieldPath == null ) { LOG . error ( \"Column name {} is not defined in column-filed mapping\" , columnName ) ; return null ; } return fieldPath . replace ( \"/Data\" , \"/OldData\" ) ; } // For insert and update, ok to use the field name set by column-field mapping return columnsToField . get ( columnName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build query using the lastOffset which is of the form ( <column1 > = <value1 > :: <column2 > = <value2 > :: <column3 > = <value3 > ) [CODESPLIT] public static Pair < String , List < Pair < Integer , String > > > buildAndReturnQueryAndParamValToSet ( TableRuntimeContext tableRuntimeContext , String lastOffset , String quoteChar , TableJdbcELEvalContext tableJdbcELEvalContext ) throws ELEvalException { final TableContext tableContext = tableRuntimeContext . getSourceTableContext ( ) ; StringBuilder queryBuilder = new StringBuilder ( ) ; List < Pair < Integer , String > > paramValueToSet = new ArrayList <> ( ) ; queryBuilder . append ( buildBaseTableQuery ( tableRuntimeContext , quoteChar ) ) ; Map < String , String > storedTableToOffset = getColumnsToOffsetMapFromOffsetFormat ( lastOffset ) ; final boolean noStoredOffsets = storedTableToOffset . isEmpty ( ) ; //Determines whether an initial offset is specified in the config and there is no stored offset. boolean isOffsetOverriden = tableContext . isOffsetOverriden ( ) && noStoredOffsets ; OffsetComparison minComparison = OffsetComparison . GREATER_THAN ; Map < String , String > offset = null ; if ( isOffsetOverriden ) { //Use the offset in the configuration offset = tableContext . getOffsetColumnToStartOffset ( ) ; } else if ( tableRuntimeContext . isPartitioned ( ) && noStoredOffsets ) { // use partitioned starting offsets offset = tableRuntimeContext . getStartingPartitionOffsets ( ) ; minComparison = OffsetComparison . GREATER_THAN_OR_EQUALS ; } else { // if offset is available // get the stored offset (which is of the form partitionName=value) and strip off 'offsetColumns=' prefix // else null // offset = storedOffsets; offset = storedTableToOffset ; } Map < String , String > maxOffsets = new HashMap <> ( ) ; if ( tableRuntimeContext . isPartitioned ( ) ) { maxOffsets . putAll ( tableRuntimeContext . getMaxPartitionOffsets ( ) ) ; } List < String > finalAndConditions = new ArrayList <> ( ) ; //Apply last offset conditions if ( offset != null && ! offset . isEmpty ( ) ) { List < String > finalOrConditions = new ArrayList <> ( ) ; List < String > preconditions = new ArrayList <> ( ) ; List < Pair < Integer , String > > preconditionParamVals = new ArrayList <> ( ) ; //For partition columns p1, p2 and p3 with offsets o1, o2 and o3 respectively, the query will look something like //select * from tableName where (p1 > o1) or (p1 = o1 and p2 > o2) or (p1 = o1 and p2 = o2 and p3 > o3) order by p1, p2, p3. for ( String partitionColumn : tableContext . getOffsetColumns ( ) ) { int partitionSqlType = tableContext . getOffsetColumnType ( partitionColumn ) ; String partitionOffset = offset . get ( partitionColumn ) ; String thisPartitionColumnMax = null ; boolean hasMaxOffset = false ; // add max value for partition column (if applicable) if ( maxOffsets . containsKey ( partitionColumn ) ) { final String maxOffset = maxOffsets . get ( partitionColumn ) ; if ( ! Strings . isNullOrEmpty ( maxOffset ) ) { Pair < Integer , String > paramValForCurrentOffsetColumnMax = Pair . of ( partitionSqlType , maxOffset ) ; // add for current partition column max value paramValueToSet . add ( paramValForCurrentOffsetColumnMax ) ; thisPartitionColumnMax = getConditionForPartitionColumn ( partitionColumn , OffsetComparison . LESS_THAN , preconditions , quoteChar ) ; hasMaxOffset = true ; } } final String thisPartitionColumnMin = getConditionForPartitionColumn ( partitionColumn , minComparison , preconditions , quoteChar ) ; String conditionForThisPartitionColumn ; if ( hasMaxOffset ) { conditionForThisPartitionColumn = String . format ( AND_CONDITION_FORMAT , // add max condition first, since its param to set was already added thisPartitionColumnMax , thisPartitionColumnMin ) ; } else { conditionForThisPartitionColumn = String . format ( CONDITION_FORMAT , thisPartitionColumnMin ) ; } //Add for preconditions (EX: composite keys) paramValueToSet . addAll ( new ArrayList <> ( preconditionParamVals ) ) ; Pair < Integer , String > paramValForCurrentOffsetColumn = Pair . of ( partitionSqlType , partitionOffset ) ; //Add for current partition column paramValueToSet . add ( paramValForCurrentOffsetColumn ) ; finalOrConditions . add ( conditionForThisPartitionColumn ) ; preconditions . add ( getConditionForPartitionColumn ( partitionColumn , OffsetComparison . EQUALS , Collections . emptyList ( ) , quoteChar ) ) ; preconditionParamVals . add ( paramValForCurrentOffsetColumn ) ; } finalAndConditions . add ( String . format ( CONDITION_FORMAT , OR_JOINER . join ( finalOrConditions ) ) ) ; } if ( ! StringUtils . isEmpty ( tableContext . getExtraOffsetColumnConditions ( ) ) ) { //Apply extra offset column conditions configured which will be appended as AND on the query String condition = tableJdbcELEvalContext . evaluateAsString ( \"extraOffsetColumnConditions\" , tableContext . getExtraOffsetColumnConditions ( ) ) ; finalAndConditions . add ( String . format ( CONDITION_FORMAT , condition ) ) ; } if ( ! finalAndConditions . isEmpty ( ) ) { queryBuilder . append ( String . format ( WHERE_CLAUSE , AND_JOINER . join ( finalAndConditions ) ) ) ; } Collection < String > quotedOffsetColumns = tableContext . getOffsetColumns ( ) . stream ( ) . map ( offsetCol -> String . format ( QUOTED_NAME , quoteChar , offsetCol , quoteChar ) ) . collect ( Collectors . toList ( ) ) ; queryBuilder . append ( String . format ( ORDER_BY_CLAUSE , COMMA_SPACE_JOINER . join ( quotedOffsetColumns ) ) ) ; return Pair . of ( queryBuilder . toString ( ) , paramValueToSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds parts of the query in the where clause for the the partitition column . [CODESPLIT] private static String getConditionForPartitionColumn ( String partitionColumn , OffsetComparison comparison , List < String > preconditions , String quoteChar ) { String conditionTemplate = comparison . getQueryCondition ( ) ; List < String > finalConditions = new ArrayList <> ( preconditions ) ; finalConditions . add ( String . format ( conditionTemplate , String . format ( QUOTED_NAME , quoteChar , partitionColumn , quoteChar ) , PREPARED_STATEMENT_POSITIONAL_PARAMETER ) ) ; return AND_JOINER . join ( finalConditions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits the offset in the form of ( <column1 > = <value1 > :: <column2 > = <value2 > :: <column3 > = <value3 > ) into a map of columns and values [CODESPLIT] public static Map < String , String > getColumnsToOffsetMapFromOffsetFormat ( String lastOffset ) { Map < String , String > offsetColumnsToOffsetMap = new HashMap <> ( ) ; if ( StringUtils . isNotBlank ( lastOffset ) ) { Iterator < String > offsetColumnsAndOffsetIterator = OFFSET_COLUMN_SPLITTER . split ( lastOffset ) . iterator ( ) ; while ( offsetColumnsAndOffsetIterator . hasNext ( ) ) { String offsetColumnAndOffset = offsetColumnsAndOffsetIterator . next ( ) ; String [ ] offsetColumnOffsetSplit = offsetColumnAndOffset . split ( \"=\" ) ; String offsetColumn = offsetColumnOffsetSplit [ 0 ] ; String offset = offsetColumnOffsetSplit [ 1 ] ; offsetColumnsToOffsetMap . put ( offsetColumn , offset ) ; } } return offsetColumnsToOffsetMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins the map of column to values to a string offset in the form of ( <column1 > = <value1 > :: <column2 > = <value2 > :: <column3 > = <value3 > ) [CODESPLIT] public static String getOffsetFormatFromColumns ( TableRuntimeContext tableContext , Map < String , Field > fields ) throws StageException { return getOffsetFormat ( getOffsetsFromColumns ( tableContext , fields ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the inverse of { @link #getSourceKeyOffsetsRepresentation ( Map ) } . [CODESPLIT] public static Map < String , String > getOffsetsFromSourceKeyRepresentation ( String offsets ) { final Map < String , String > offsetMap = new HashMap <> ( ) ; if ( StringUtils . isNotBlank ( offsets ) ) { for ( String col : StringUtils . splitByWholeSeparator ( offsets , OFFSET_KEY_COLUMN_SEPARATOR ) ) { final String [ ] parts = StringUtils . splitByWholeSeparator ( col , OFFSET_KEY_COLUMN_NAME_VALUE_SEPARATOR , 2 ) ; if ( parts . length != 2 ) { throw new IllegalArgumentException ( String . format ( \"Invalid column offset of \\\"%s\\\" seen.  Expected colName%svalue.  Full offsets representation: %s\" , col , OFFSET_KEY_COLUMN_NAME_VALUE_SEPARATOR , offsets ) ) ; } offsetMap . put ( parts [ 0 ] , parts [ 1 ] ) ; } } return offsetMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates whether offset names match in the stored offset with respect to table configuration [CODESPLIT] public static Map < String , String > validateStoredAndSpecifiedOffset ( TableContext tableContext , String offset ) throws StageException { Set < String > expectedColumns = Sets . newHashSet ( tableContext . getOffsetColumns ( ) ) ; final Map < String , String > actualOffsets = getColumnsToOffsetMapFromOffsetFormat ( offset ) ; // only perform the actual validation below if there ARE stored offsets if ( actualOffsets . size ( ) == 0 ) { return actualOffsets ; } Set < String > actualColumns = actualOffsets . keySet ( ) ; Set < String > expectedSetDifference = Sets . difference ( expectedColumns , actualColumns ) ; Set < String > actualSetDifference = Sets . difference ( actualColumns , expectedColumns ) ; if ( expectedSetDifference . size ( ) > 0 || actualSetDifference . size ( ) > 0 ) { throw new StageException ( JdbcErrors . JDBC_71 , tableContext . getQualifiedName ( ) , COMMA_SPACE_JOINER . join ( actualColumns ) , COMMA_SPACE_JOINER . join ( expectedColumns ) ) ; } return actualOffsets ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return InputStream from which a new generated resource bundle can be retrieved . [CODESPLIT] public SupportBundle generateNewBundle ( List < String > generators , BundleType bundleType ) throws IOException { List < BundleContentGeneratorDefinition > defs = getRequestedDefinitions ( generators ) ; return generateNewBundleFromInstances ( defs . stream ( ) . map ( BundleContentGeneratorDefinition :: createInstance ) . collect ( Collectors . toList ( ) ) , bundleType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return InputStream from which a new generated resource bundle can be retrieved . [CODESPLIT] public SupportBundle generateNewBundleFromInstances ( List < BundleContentGenerator > generators , BundleType bundleType ) throws IOException { PipedInputStream inputStream = new PipedInputStream ( ) ; PipedOutputStream outputStream = new PipedOutputStream ( ) ; inputStream . connect ( outputStream ) ; ZipOutputStream zipOutputStream = new ZipOutputStream ( outputStream ) ; executor . submit ( ( ) -> generateNewBundleInternal ( generators , bundleType , zipOutputStream ) ) ; String bundleName = generateBundleName ( bundleType ) ; String bundleKey = generateBundleDate ( bundleType ) + \"/\" + bundleName ; return new SupportBundle ( bundleKey , bundleName , inputStream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instead of providing support bundle directly to user upload it to StreamSets backend services . [CODESPLIT] public void uploadNewBundle ( List < String > generators , BundleType bundleType ) throws IOException { List < BundleContentGeneratorDefinition > defs = getRequestedDefinitions ( generators ) ; uploadNewBundleFromInstances ( defs . stream ( ) . map ( BundleContentGeneratorDefinition :: createInstance ) . collect ( Collectors . toList ( ) ) , bundleType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instead of providing support bundle directly to user upload it to StreamSets backend services . [CODESPLIT] public void uploadNewBundleFromInstances ( List < BundleContentGenerator > generators , BundleType bundleType ) throws IOException { // Generate bundle SupportBundle bundle = generateNewBundleFromInstances ( generators , bundleType ) ; boolean enabled = configuration . get ( Constants . UPLOAD_ENABLED , Constants . DEFAULT_UPLOAD_ENABLED ) ; String accessKey = configuration . get ( Constants . UPLOAD_ACCESS , Constants . DEFAULT_UPLOAD_ACCESS ) ; String secretKey = configuration . get ( Constants . UPLOAD_SECRET , Constants . DEFAULT_UPLOAD_SECRET ) ; String bucket = configuration . get ( Constants . UPLOAD_BUCKET , Constants . DEFAULT_UPLOAD_BUCKET ) ; int bufferSize = configuration . get ( Constants . UPLOAD_BUFFER_SIZE , Constants . DEFAULT_UPLOAD_BUFFER_SIZE ) ; if ( ! enabled ) { throw new IOException ( \"Uploading support bundles was disabled by administrator.\" ) ; } AWSCredentialsProvider credentialsProvider = new StaticCredentialsProvider ( new BasicAWSCredentials ( accessKey , secretKey ) ) ; AmazonS3Client s3Client = new AmazonS3Client ( credentialsProvider , new ClientConfiguration ( ) ) ; s3Client . setS3ClientOptions ( new S3ClientOptions ( ) . withPathStyleAccess ( true ) ) ; s3Client . setRegion ( Region . getRegion ( Regions . US_WEST_2 ) ) ; // Object Metadata ObjectMetadata s3Metadata = new ObjectMetadata ( ) ; for ( Map . Entry < Object , Object > entry : getMetadata ( bundleType ) . entrySet ( ) ) { s3Metadata . addUserMetadata ( ( String ) entry . getKey ( ) , ( String ) entry . getValue ( ) ) ; } List < PartETag > partETags ; InitiateMultipartUploadResult initResponse = null ; try { // Uploading part by part LOG . info ( \"Initiating multi-part support bundle upload\" ) ; partETags = new ArrayList <> ( ) ; InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest ( bucket , bundle . getBundleKey ( ) ) ; initRequest . setObjectMetadata ( s3Metadata ) ; initResponse = s3Client . initiateMultipartUpload ( initRequest ) ; } catch ( AmazonClientException e ) { LOG . error ( \"Support bundle upload failed: \" , e ) ; throw new IOException ( \"Support bundle upload failed\" , e ) ; } try { byte [ ] buffer = new byte [ bufferSize ] ; int partId = 1 ; int size = - 1 ; while ( ( size = readFully ( bundle . getInputStream ( ) , buffer ) ) != - 1 ) { LOG . debug ( \"Uploading part {} of size {}\" , partId , size ) ; UploadPartRequest uploadRequest = new UploadPartRequest ( ) . withBucketName ( bucket ) . withKey ( bundle . getBundleKey ( ) ) . withUploadId ( initResponse . getUploadId ( ) ) . withPartNumber ( partId ++ ) . withInputStream ( new ByteArrayInputStream ( buffer ) ) . withPartSize ( size ) ; partETags . add ( s3Client . uploadPart ( uploadRequest ) . getPartETag ( ) ) ; } CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest ( bucket , bundle . getBundleKey ( ) , initResponse . getUploadId ( ) , partETags ) ; s3Client . completeMultipartUpload ( compRequest ) ; LOG . info ( \"Support bundle upload finished\" ) ; } catch ( Exception e ) { LOG . error ( \"Support bundle upload failed\" , e ) ; s3Client . abortMultipartUpload ( new AbortMultipartUploadRequest ( bucket , bundle . getBundleKey ( ) , initResponse . getUploadId ( ) ) ) ; throw new IOException ( \"Can't upload support bundle\" , e ) ; } finally { // Close the client s3Client . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to upload bundle as part of internal SDC error ( for example failing pipeline ) . [CODESPLIT] public void uploadNewBundleOnError ( ) { boolean enabled = configuration . get ( Constants . UPLOAD_ON_ERROR , Constants . DEFAULT_UPLOAD_ON_ERROR ) ; LOG . info ( \"Upload bundle on error: {}\" , enabled ) ; // We won't upload the bundle unless it's explicitly allowed if ( ! enabled ) { return ; } try { uploadNewBundle ( Collections . emptyList ( ) , BundleType . SUPPORT ) ; } catch ( IOException e ) { LOG . error ( \"Failed to upload error bundle\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will read from the input stream until the whole buffer is loaded up with actual bytes or end of stream has been reached . Hence it will return buffer . length of all executions except the last two - one to the last call will return less then buffer . length ( reminder of the data ) and returns - 1 on any subsequent calls . [CODESPLIT] private int readFully ( InputStream inputStream , byte [ ] buffer ) throws IOException { int readBytes = 0 ; while ( readBytes < buffer . length ) { int loaded = inputStream . read ( buffer , readBytes , buffer . length - readBytes ) ; if ( loaded == - 1 ) { return readBytes == 0 ? - 1 : readBytes ; } readBytes += loaded ; } return readBytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Orchestrate what definitions should be used for this bundle . [CODESPLIT] private List < BundleContentGeneratorDefinition > getRequestedDefinitions ( List < String > generators ) { Stream < BundleContentGeneratorDefinition > stream = definitions . stream ( ) ; if ( generators == null || generators . isEmpty ( ) ) { // Filter out default generators stream = stream . filter ( BundleContentGeneratorDefinition :: isEnabledByDefault ) ; } else { stream = stream . filter ( def -> generators . contains ( def . getId ( ) ) ) ; } return stream . sorted ( Comparator . comparingInt ( BundleContentGeneratorDefinition :: getOrder ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "From https : // stackoverflow . com / a / 31928740 / 33905 [CODESPLIT] @ VisibleForTesting protected static Map < String , String [ ] > getQueryParameters ( HttpServletRequest request ) { Map < String , String [ ] > queryParameters = new HashMap <> ( ) ; String queryString = request . getQueryString ( ) ; if ( StringUtils . isEmpty ( queryString ) ) { return queryParameters ; } String [ ] parameters = queryString . split ( \"&\" ) ; for ( String parameter : parameters ) { String [ ] keyValuePair = parameter . split ( \"=\" ) ; String [ ] values = queryParameters . get ( keyValuePair [ 0 ] ) ; values = ArrayUtils . add ( values , keyValuePair . length == 1 ? \"\" : keyValuePair [ 1 ] ) ; //length is one if no value is available. queryParameters . put ( keyValuePair [ 0 ] , values ) ; } return queryParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is used by destination which performs CRUD operations . Records sent from MySQLBinLog origin have / Data field that contains a map of key - value for INSERT and UPDATE operation but / OldData field for DELETE operation . This method looks into / OldData for DELETE operation so that users don t need a separate field - column mapping for DELETE . [CODESPLIT] @ Override public String getFieldPath ( String fieldPath , int operation ) { if ( operation == OperationType . DELETE_CODE ) { return fieldPath . replace ( DATA_FIELD , OLDDATA_FIELD ) ; } return fieldPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there is a RecordEL then an arg could eval to empty string . This method returns args that are not null or empty . [CODESPLIT] private String [ ] getNonEmptyArgs ( List < String > appArgs ) { List < String > nonEmpty = new ArrayList <> ( ) ; appArgs . forEach ( ( String val ) -> { if ( ! StringUtils . isEmpty ( val ) ) { nonEmpty . add ( val ) ; } } ) ; return nonEmpty . toArray ( new String [ nonEmpty . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return Operation based on the operation code . If the code has a number that Kudu destination doesn t support it throws UnsupportedOperationException . [CODESPLIT] protected Operation getOperation ( KuduTable table , int op ) throws UnsupportedOperationException { Operation operation = null ; switch ( op ) { case OperationType . INSERT_CODE : operation = table . newInsert ( ) ; break ; case OperationType . UPSERT_CODE : operation = table . newUpsert ( ) ; break ; case OperationType . UPDATE_CODE : operation = table . newUpdate ( ) ; break ; case OperationType . DELETE_CODE : operation = table . newDelete ( ) ; break ; default : LOG . error ( \"Operation {} not supported\" , op ) ; throw new UnsupportedOperationException ( String . format ( \"Unsupported Operation: %s\" , op ) ) ; } return operation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the bytes to a human readable format upto 2 decimal places The maximum unit is TB so anything exceeding 1024 TB will be shown with TB unit . [CODESPLIT] static String convertBytesToDisplayFormat ( double bytes ) { int unitIdx = 0 ; double unitChangedBytes = bytes ; while ( unitIdx < UNITS . length - 1 && Math . floor ( unitChangedBytes / 1024 ) > 0 ) { unitChangedBytes = unitChangedBytes / 1024 ; unitIdx ++ ; } return df . format ( unitChangedBytes ) + \" \" + UNITS [ unitIdx ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans the directory of for the next file . [CODESPLIT] public LiveFile scan ( LiveFile current ) throws IOException { try { return scanInternal ( current ) ; } catch ( NoSuchFileException ex ) { // this could happen because there has been a file rotation/deletion after the search/filter/sort and before // the creation of the nen current. Lets sleep for 50ms and try again, if fails again give up. ThreadUtil . sleep ( 50 ) ; return scanInternal ( current ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans the directory for number of files yet to be processed . [CODESPLIT] public long getPendingFiles ( LiveFile current ) throws IOException { //Current will not be acceptable for roll files (if active file is without a counter/date pattern) //and will be later renamed to a file with counter/date suffix, if that is the case we should //return 0 as number of pending files if ( current == null || rollMode . isCurrentAcceptable ( current . getPath ( ) . getFileName ( ) . toString ( ) ) ) { return findToBeProcessedMatchingFiles ( current != null ? current . refresh ( ) : null ) . size ( ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if this dependency and given set of versions is whitelisted . [CODESPLIT] public static boolean isWhitelisted ( String name , Properties specificWhitelist , Map < String , List < Dependency > > dependencies ) { if ( specificWhitelist != null && specificWhitelist . containsKey ( name ) ) { return versionsMatch ( specificWhitelist . getProperty ( name ) , dependencies . keySet ( ) ) ; } // Otherwise try hardcoded rules: WhitelistRule rule = WHITELIST_RULES . get ( name ) ; return rule != null && rule . isWhitelisted ( dependencies ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare expected versions with given versions to see if they are the same or not . [CODESPLIT] private static boolean versionsMatch ( String expectedVersions , Set < String > versions ) { Set < String > expectedSet = Sets . newHashSet ( expectedVersions . split ( \",\" ) ) ; return Sets . symmetricDifference ( expectedSet , versions ) . isEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the parameters for this config bean . [CODESPLIT] public void init ( Stage . Context context , String groupName , String prefix , List < Stage . ConfigIssue > issues ) { if ( ! trustStorePath . isEmpty ( ) ) { if ( Files . notExists ( Paths . get ( trustStorePath ) ) ) { issues . add ( context . createConfigIssue ( groupName , prefix + \"trustStorePath\" , HTTP_04 , trustStorePath ) ) ; } try { if ( trustStorePassword . get ( ) . isEmpty ( ) ) { issues . add ( context . createConfigIssue ( groupName , prefix + \"trustStorePassword\" , HTTP_05 ) ) ; } } catch ( StageException e ) { issues . add ( context . createConfigIssue ( groupName , prefix + \"trustStorePassword\" , HTTP_29 , e . toString ( ) ) ) ; } } if ( ! keyStorePath . isEmpty ( ) ) { if ( Files . notExists ( Paths . get ( keyStorePath ) ) ) { issues . add ( context . createConfigIssue ( groupName , prefix + \"keyStorePath\" , HTTP_04 , keyStorePath ) ) ; } try { if ( keyStorePassword . get ( ) . isEmpty ( ) ) { issues . add ( context . createConfigIssue ( groupName , prefix + \"keyStorePassword\" , HTTP_05 ) ) ; } } catch ( StageException e ) { issues . add ( context . createConfigIssue ( groupName , prefix + \"keyStorePassword\" , HTTP_29 , e . toString ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if given snapshot output is usable - e . g . if it make sense to persist . [CODESPLIT] public static boolean isSnapshotOutputUsable ( List < StageOutput > stagesOutput ) { // In case that the snapshot actually does not exists if ( stagesOutput == null ) { return false ; } // We're looking for at least one output lane that is not empty. In most cases the first stage in the list will // be origin that generated some data and hence the loop will terminate fast. In the worst case scenario we will // iterate over all stages in attempt to find at least one record in the snapshot. for ( StageOutput output : stagesOutput ) { if ( CollectionUtils . isNotEmpty ( output . getErrorRecords ( ) ) || CollectionUtils . isNotEmpty ( output . getEventRecords ( ) ) || CollectionUtils . isNotEmpty ( output . getStageErrors ( ) ) ) { return true ; } for ( Map . Entry < String , List < Record > > entry : output . getOutput ( ) . entrySet ( ) ) { if ( ! entry . getValue ( ) . isEmpty ( ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bootstrapping the Driver which starts a Spark job on cluster [CODESPLIT] public static void main ( String [ ] args ) throws Exception { SparkStreamingBinding binding = null ; try { binding = SparkStreamingBindingFactory . build ( BootstrapCluster . getProperties ( ) ) ; binding . init ( ) ; BootstrapCluster . createTransformers ( binding . getStreamingContext ( ) . sparkContext ( ) , binding . getSparkSession ( ) ) ; binding . startContext ( ) ; binding . awaitTermination ( ) ; } catch ( Throwable error ) { String msg = \"Error trying to invoke BootstrapClusterStreaming.main: \" + error ; System . err . println ( new Date ( ) + \": \" + msg ) ; error . printStackTrace ( System . err ) ; // required as in local mode the following seems to be lost LOG . error ( msg , error ) ; throw new IllegalStateException ( msg , error ) ; } finally { try { if ( binding != null ) { binding . close ( ) ; } } catch ( Exception ex ) { LOG . warn ( \"Error on binding close: \" + ex , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { // Validate configuration values and open any required resources. List < ConfigIssue > issues = super . init ( ) ; Optional . ofNullable ( conf . init ( getContext ( ) , CONF_PREFIX ) ) . ifPresent ( issues :: addAll ) ; try { ConnectorConfig partnerConfig = ForceUtils . getPartnerConfig ( conf , new WaveSessionRenewer ( ) ) ; connection = Connector . newConnection ( partnerConfig ) ; LOG . info ( \"Successfully authenticated as {}\" , conf . username ) ; if ( conf . mutualAuth . useMutualAuth ) { ForceUtils . setupMutualAuth ( partnerConfig , conf . mutualAuth ) ; } String soapEndpoint = connection . getConfig ( ) . getServiceEndpoint ( ) ; restEndpoint = soapEndpoint . substring ( 0 , soapEndpoint . indexOf ( \"services/Soap/\" ) ) ; httpClient = new HttpClient ( ForceUtils . makeSslContextFactory ( conf ) ) ; if ( conf . useProxy ) { ForceUtils . setProxy ( httpClient , conf ) ; } httpClient . start ( ) ; } catch ( Exception e ) { LOG . error ( \"Exception during init()\" , e ) ; issues . add ( getContext ( ) . createConfigIssue ( Groups . FORCE . name ( ) , ForceConfigBean . CONF_PREFIX + \"authEndpoint\" , Errors . WAVE_00 , ForceUtils . getExceptionCode ( e ) + \", \" + ForceUtils . getExceptionMessage ( e ) ) ) ; } // If issues is not empty, the UI will inform the user of each configuration issue in the list. return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void write ( Batch batch ) throws StageException { if ( batch . getRecords ( ) . hasNext ( ) ) { if ( datasetID == null ) { LOG . info ( \"Opening dataset\" ) ; try { openDataset ( ) ; } catch ( ConnectionException ce ) { throw new StageException ( Errors . WAVE_01 , ce ) ; } } LOG . info ( \"Writing batch to dataset\" ) ; writeToDataset ( batch ) ; try { commitDataset ( ) ; } catch ( ConnectionException | IOException e ) { throw new StageException ( Errors . WAVE_01 , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We have special type of a ConfigDef called RUNTIME . This config is never displayed in UI and instead it s values are supplied at runtime . This method is the runtime method that propagates them . [CODESPLIT] private void propagateRuntimeConfiguration ( ) { // If pipeline wasn't loaded or there if there are no stages, there is nothing to propagate if ( pipelineBean == null || pipelineBean . getPipelineStageBeans ( ) == null ) { return ; } for ( StageBean stageBean : pipelineBean . getPipelineStageBeans ( ) . getStages ( ) ) { for ( ServiceDependencyDefinition serviceDependency : stageBean . getDefinition ( ) . getServices ( ) ) { ServiceBean stageService = stageBean . getService ( serviceDependency . getService ( ) ) ; if ( stageService == null ) { continue ; } ServiceConfiguration serviceConfiguration = stageService . getConf ( ) ; List < Config > configs = serviceConfiguration . getConfiguration ( ) ; // Simply remove all RUNTIME configs configs . removeAll ( serviceDependency . getConfiguration ( ) . keySet ( ) . stream ( ) . map ( serviceConfiguration :: getConfig ) . collect ( Collectors . toList ( ) ) ) ; // And insert them with the stage-instance-constant values serviceDependency . getConfiguration ( ) . forEach ( ( key , value ) -> configs . add ( new Config ( key , value ) ) ) ; // And overwrite the new state serviceConfiguration . setConfig ( configs ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected List < ConfigIssue > init ( ) { // Validate configuration values and open any required resources. List < ConfigIssue > issues = super . init ( ) ; if ( issues . isEmpty ( ) ) { jdbcUtil = UtilsProvider . getJdbcUtil ( ) ; } errorRecordHandler = new DefaultErrorRecordHandler ( getContext ( ) ) ; Processor . Context context = getContext ( ) ; queryEval = getContext ( ) . createELEval ( \"query\" ) ; issues = hikariConfigBean . validateConfigs ( context , issues ) ; if ( context . getRunnerId ( ) == 0 ) { if ( issues . isEmpty ( ) && null == dataSource ) { try { dataSource = jdbcUtil . createDataSourceForRead ( hikariConfigBean ) ; context . getStageRunnerSharedMap ( ) . put ( \"jdbcLookupProcessor.dataSource\" , dataSource ) ; } catch ( StageException e ) { issues . add ( context . createConfigIssue ( Groups . JDBC . name ( ) , CONNECTION_STRING , JdbcErrors . JDBC_00 , e . toString ( ) ) ) ; } } } else { dataSource = ( HikariDataSource ) context . getStageRunnerSharedMap ( ) . get ( \"jdbcLookupProcessor.dataSource\" ) ; } if ( issues . isEmpty ( ) ) { this . defaultValue = calculateDefault ( context , issues ) ; } if ( issues . isEmpty ( ) ) { cache = buildCache ( ) ; cacheCleaner = new CacheCleaner ( cache , \"JdbcLookupProcessor\" , 10 * 60 * 1000 ) ; if ( cacheConfig . enabled ) { preprocessThreads = Math . min ( hikariConfigBean . minIdle , Runtime . getRuntime ( ) . availableProcessors ( ) - 1 ) ; preprocessThreads = Math . max ( preprocessThreads , 1 ) ; } } if ( context . getRunnerId ( ) == 0 ) { if ( issues . isEmpty ( ) && generationExecutor == null ) { generationExecutor = new SafeScheduledExecutorService ( hikariConfigBean . maximumPoolSize , \"JDBC Lookup Cache Warmer\" ) ; context . getStageRunnerSharedMap ( ) . put ( \"jdbcLookupProcessor.generationExecutor\" , generationExecutor ) ; } } else { generationExecutor = ( SafeScheduledExecutorService ) context . getStageRunnerSharedMap ( ) . get ( \"jdbcLookupProcessor.generationExecutor\" ) ; } // If issues is not empty, the UI will inform the user of each configuration issue in the list. return issues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void destroy ( ) { if ( getContext ( ) . getRunnerId ( ) == 0 ) { if ( generationExecutor != null ) { generationExecutor . shutdown ( ) ; try { if ( ! generationExecutor . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { generationExecutor . shutdownNow ( ) ; } } catch ( InterruptedException ex ) { LOG . error ( \"Interrupted while attempting to shutdown Generator Executor: \" , ex ) ; Thread . currentThread ( ) . interrupt ( ) ; } } // close dataSource after closing threadpool executor as we could have queries running before closing the executor if ( jdbcUtil != null ) { jdbcUtil . closeQuietly ( dataSource ) ; } } super . destroy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void process ( Record record , SingleLaneBatchMaker batchMaker ) throws StageException { try { ELVars elVars = getContext ( ) . createELVars ( ) ; RecordEL . setRecordInContext ( elVars , record ) ; String preparedQuery = queryEval . eval ( elVars , query , String . class ) ; Optional < List < Map < String , Field > > > entry = cache . get ( preparedQuery ) ; if ( ! entry . isPresent ( ) ) { // No results switch ( missingValuesBehavior ) { case SEND_TO_ERROR : LOG . error ( JdbcErrors . JDBC_04 . getMessage ( ) , preparedQuery ) ; errorRecordHandler . onError ( new OnRecordErrorException ( record , JdbcErrors . JDBC_04 , preparedQuery ) ) ; break ; case PASS_RECORD_ON : batchMaker . addRecord ( record ) ; break ; default : throw new IllegalStateException ( \"Unknown missing value behavior: \" + missingValuesBehavior ) ; } } else { List < Map < String , Field > > values = entry . get ( ) ; switch ( multipleValuesBehavior ) { case FIRST_ONLY : setFieldsInRecord ( record , values . get ( 0 ) ) ; batchMaker . addRecord ( record ) ; break ; case SPLIT_INTO_MULTIPLE_RECORDS : for ( Map < String , Field > lookupItem : values ) { Record newRecord = getContext ( ) . cloneRecord ( record ) ; setFieldsInRecord ( newRecord , lookupItem ) ; batchMaker . addRecord ( newRecord ) ; } break ; case ALL_AS_LIST : Map < String , List < Field > > valuesMap = new HashMap <> ( ) ; for ( Map < String , Field > lookupItem : values ) { lookupItem . forEach ( ( k , v ) -> { if ( valuesMap . get ( k ) == null ) { List < Field > lookupValue = new ArrayList <> ( ) ; valuesMap . put ( k , lookupValue ) ; } valuesMap . get ( k ) . add ( v ) ; } ) ; } Map < String , Field > valueMap = new HashMap <> ( ) ; valuesMap . forEach ( ( k , v ) -> valueMap . put ( k , Field . create ( v ) ) ) ; setFieldsInRecord ( record , valueMap ) ; batchMaker . addRecord ( record ) ; break ; default : throw new IllegalStateException ( \"Unknown multiple value behavior: \" + multipleValuesBehavior ) ; } } } catch ( ELEvalException e ) { LOG . error ( JdbcErrors . JDBC_01 . getMessage ( ) , query , e ) ; throw new OnRecordErrorException ( record , JdbcErrors . JDBC_01 , query ) ; } catch ( ExecutionException e ) { Throwables . propagateIfPossible ( e . getCause ( ) , StageException . class ) ; throw new IllegalStateException ( e ) ; // The cache loader shouldn't throw anything that isn't a StageException. } catch ( OnRecordErrorException error ) { // NOSONAR errorRecordHandler . onError ( new OnRecordErrorException ( record , error . getErrorCode ( ) , error . getParams ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate Ominture Report Description . [CODESPLIT] private void validateReportDescription ( List < ConfigIssue > issues ) { if ( ! jsonMapper . isValidJson ( this . reportDescription ) ) { issues . add ( getContext ( ) . createConfigIssue ( Groups . REPORT . name ( ) , \"reportDescription\" , Errors . OMNITURE_03 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Escapes special characters with a preceding slash [CODESPLIT] private String escapeValue ( String str , boolean escapeSpace ) { int len = str . length ( ) ; int bufLen = len * 2 ; if ( bufLen < 0 ) { bufLen = Integer . MAX_VALUE ; } StringBuilder outBuffer = new StringBuilder ( bufLen ) ; for ( int x = 0 ; x < len ; x ++ ) { char aChar = str . charAt ( x ) ; // Handle common case first, selecting largest block that // avoids the specials below if ( ( aChar > 61 ) && ( aChar < 127 ) ) { if ( aChar == ' ' ) { outBuffer . append ( ' ' ) ; outBuffer . append ( ' ' ) ; continue ; } outBuffer . append ( aChar ) ; continue ; } switch ( aChar ) { case ' ' : if ( x == 0 || escapeSpace ) outBuffer . append ( ' ' ) ; outBuffer . append ( ' ' ) ; break ; case ' ' : outBuffer . append ( ' ' ) ; outBuffer . append ( ' ' ) ; break ; case ' ' : outBuffer . append ( ' ' ) ; outBuffer . append ( ' ' ) ; break ; case ' ' : outBuffer . append ( ' ' ) ; outBuffer . append ( ' ' ) ; break ; case ' ' : outBuffer . append ( ' ' ) ; outBuffer . append ( ' ' ) ; break ; case ' ' : // Fall through case ' ' : // Fall through case ' ' : // Fall through case ' ' : outBuffer . append ( ' ' ) ; outBuffer . append ( aChar ) ; break ; default : outBuffer . append ( aChar ) ; } } return outBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by JdbcTarget [CODESPLIT] public static JdbcRecordWriter createJdbcRecordWriter ( String connectionString , HikariDataSource dataSource , String schema , String tableName , List < JdbcFieldColumnParamMapping > customMappings , boolean rollbackOnError , boolean useMultiRowOp , int maxPrepStmtParameters , int defaultOpCode , UnsupportedOperationAction unsupportedAction , DuplicateKeyAction duplicateKeyAction , JdbcRecordReader recordReader , boolean caseSensitive , List < String > customDataSqlStateCodes ) throws StageException { if ( defaultOpCode == OperationType . LOAD_CODE ) { return new JdbcLoadRecordWriter ( connectionString , dataSource , schema , tableName , customMappings , duplicateKeyAction , recordReader , caseSensitive , customDataSqlStateCodes ) ; } else { return createJdbcRecordWriter ( connectionString , dataSource , schema , tableName , customMappings , null , rollbackOnError , useMultiRowOp , maxPrepStmtParameters , defaultOpCode , unsupportedAction , recordReader , caseSensitive , customDataSqlStateCodes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by JdbcTeeProcessor [CODESPLIT] public static JdbcRecordWriter createJdbcRecordWriter ( String connectionString , HikariDataSource dataSource , String schema , String tableName , List < JdbcFieldColumnParamMapping > customMappings , List < JdbcFieldColumnMapping > generatedColumnMappings , boolean rollbackOnError , boolean useMultiRowOp , int maxPrepStmtParameters , int defaultOpCode , UnsupportedOperationAction unsupportedAction , JdbcRecordReader recordReader , boolean caseSensitive , List < String > customDataSqlStateCodes ) throws StageException { JdbcRecordWriter recordWriter ; if ( useMultiRowOp ) { recordWriter = new JdbcMultiRowRecordWriter ( connectionString , dataSource , schema , tableName , rollbackOnError , customMappings , maxPrepStmtParameters , defaultOpCode , unsupportedAction , generatedColumnMappings , recordReader , caseSensitive , customDataSqlStateCodes ) ; } else { recordWriter = new JdbcGenericRecordWriter ( connectionString , dataSource , schema , tableName , rollbackOnError , customMappings , defaultOpCode , unsupportedAction , generatedColumnMappings , recordReader , caseSensitive , customDataSqlStateCodes ) ; } return recordWriter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove implicit field mapping [CODESPLIT] private void upgradeV1toV2 ( List < Config > configs ) { configs . removeIf ( config -> ( config . getName ( ) . equals ( IMPLICIT_FIELD_MAPPING_CONFIG ) || config . getName ( ) . equals ( BIG_QUERY_IMPLICIT_FIELD_MAPPING_CONFIG ) ) ) ; configs . add ( new Config ( MAX_CACHE_SIZE , - 1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts named groups from the raw data [CODESPLIT] public Map < String , String > extractNamedGroups ( final CharSequence rawData ) { Matcher matcher = compiledPattern . matcher ( rawData ) ; if ( matcher . find ( ) ) { MatchResult r = matcher . toMatchResult ( ) ; if ( r != null && r . namedGroups ( ) != null ) { return r . namedGroups ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a null value is passed to this method it s replaced with a dummy due to the fact the payload for each message is wrapped in an Optional . [CODESPLIT] public void consumerCommit ( String offset ) { Object offsetValue = offset ; if ( offsetValue == null ) { offsetValue = new NullOffset ( ) ; } LOG . trace ( \"Commit Offset: '{}'\" , offsetValue ) ; try { producerQueue . put ( new Message ( MessageType . CONSUMER_COMMIT , offsetValue ) ) ; } catch ( InterruptedException e ) { LOG . info ( \"Interrupted while queuing '{}'\" , MessageType . CONSUMER_COMMIT . name ( ) , offsetValue ) ; Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of SDC and adds to pool [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected EmbeddedSDC create ( ) throws Exception { Utils . checkState ( open , \"Not open\" ) ; final EmbeddedSDC embeddedSDC = new EmbeddedSDC ( ) ; Object source ; // post-batch runnable Object pipelineStartResult = BootstrapCluster . startPipeline ( ( ) -> LOG . debug ( \"Batch completed\" ) ) ; source = pipelineStartResult . getClass ( ) . getDeclaredField ( \"source\" ) . get ( pipelineStartResult ) ; if ( source instanceof DSource ) { long startTime = System . currentTimeMillis ( ) ; long endTime = startTime ; long diff = 0 ; Source actualSource = ( ( DSource ) source ) . getSource ( ) ; while ( actualSource == null && diff < 60000 ) { Thread . sleep ( 100 ) ; actualSource = ( ( DSource ) source ) . getSource ( ) ; endTime = System . currentTimeMillis ( ) ; diff = endTime - startTime ; } if ( actualSource == null ) { throw new IllegalStateException ( \"Actual source is null, pipeline may not have been initialized\" ) ; } source = actualSource ; } if ( ! ( source instanceof ClusterSource ) ) { throw new IllegalArgumentException ( \"Source is not of type ClusterSource: \" + source . getClass ( ) . getName ( ) ) ; } embeddedSDC . setSource ( ( ClusterSource ) source ) ; embeddedSDC . setSparkProcessors ( ( List < Object > ) pipelineStartResult . getClass ( ) . getDeclaredField ( \"sparkProcessors\" ) . get ( pipelineStartResult ) ) ; return embeddedSDC ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "What is this?! Spark could end up scheduling transformers to run on machines that may actually not have received the data due to : - Non - local reads : Spark Locality is time - bound so if local executor where the data is located is not available Spark will tell another one to pick up the task . - Shuffle in the transformer : After a shuffle it is possible the next task passing the data to the next batch could end up on a different executor . [CODESPLIT] private EmbeddedSDC fastForward ( int id ) throws Exception { if ( id == sparkProcessorCount ) { return null ; } LOG . info ( \"No SDC was found at ID: \" + id + \". Fast-forwarding..\" ) ; EmbeddedSDC sdc ; // If there are not SDCs that are just idling, create a new one, else return one from the not started pool. if ( notStarted . isEmpty ( ) ) { sdc = create ( ) ; } else { sdc = getNotStartedSDC ( ) ; } Class < ? > clusterFunctionClass = Class . forName ( \"com.streamsets.pipeline.cluster.ClusterFunctionImpl\" ) ; Method getBatch = clusterFunctionClass . getMethod ( \"getNextBatch\" , int . class , EmbeddedSDC . class ) ; Method forward = clusterFunctionClass . getMethod ( \"doForward\" , Iterator . class , int . class , EmbeddedSDC . class ) ; sdc . getSource ( ) . put ( Collections . emptyList ( ) ) ; getBatch . invoke ( null , 0 , sdc ) ; for ( int i = 0 ; i <= id - 1 ; i ++ ) { forward . invoke ( null , Collections . emptyIterator ( ) , i , sdc ) ; } return sdc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the lookup reuslt in the result field [CODESPLIT] private void setFieldsInRecord ( Record record , Map < String , Field > fields ) { record . set ( configBean . resultField , Field . createListMap ( new LinkedHashMap <> ( fields ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns info about remote pipelines that have changed since the last sending of events [CODESPLIT] @ Override public List < PipelineAndValidationStatus > getRemotePipelinesWithChanges ( ) throws PipelineException { List < PipelineAndValidationStatus > pipelineAndValidationStatuses = new ArrayList <> ( ) ; for ( Pair < PipelineState , Map < String , String > > pipelineStateAndOffset : stateEventListener . getPipelineStateEvents ( ) ) { PipelineState pipelineState = pipelineStateAndOffset . getLeft ( ) ; Map < String , String > offset = pipelineStateAndOffset . getRight ( ) ; String name = pipelineState . getPipelineId ( ) ; String rev = pipelineState . getRev ( ) ; boolean isClusterMode = ( pipelineState . getExecutionMode ( ) != ExecutionMode . STANDALONE ) ? true : false ; List < WorkerInfo > workerInfos = new ArrayList <> ( ) ; String title ; int runnerCount = 0 ; if ( pipelineStore . hasPipeline ( name ) ) { title = pipelineStore . getInfo ( name ) . getTitle ( ) ; Runner runner = manager . getRunner ( name , rev ) ; if ( isClusterMode ) { workerInfos = getWorkers ( runner . getSlaveCallbackList ( CallbackObjectType . METRICS ) ) ; } runnerCount = runner . getRunnerCount ( ) ; } else { title = null ; } pipelineAndValidationStatuses . add ( new PipelineAndValidationStatus ( getSchGeneratedPipelineName ( name , rev ) , title , rev , pipelineState . getTimeStamp ( ) , true , pipelineState . getStatus ( ) , pipelineState . getMessage ( ) , workerInfos , isClusterMode , getSourceOffset ( name , offset ) , null , runnerCount ) ) ; } return pipelineAndValidationStatuses ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a future ack result from the given parameter . It is expected that the caller will eventually wait for the future ack result that is returned . [CODESPLIT] public static RemoteDataCollectorResult futureAck ( Future < AckEvent > futureResult ) { return new RemoteDataCollectorResult ( futureResult , null , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an operation code from record . First look for sdc . operation . code from record header . If not set look for __$operation in record . It is a specific field that MS SQL CDC origin set . [CODESPLIT] @ Override @ VisibleForTesting int getOperationFromRecord ( Record record , int defaultOpCode , UnsupportedOperationAction unsupportedAction , List < OnRecordErrorException > errorRecords ) { int opCode = - 1 ; // -1 is invalid and not used in OperationType. String op = null ; try { // Try sdc.operation.type first op = record . getHeader ( ) . getAttribute ( OperationType . SDC_OPERATION_TYPE ) ; // If not set, look for oracle.cdc.operation in record header. if ( StringUtils . isBlank ( op ) ) { op = record . getHeader ( ) . getAttribute ( OracleCDCOperationCode . OPERATION ) ; if ( op != null ) { // Convert the Oracle specific operation code to SDC standard operation code opCode = OracleCDCOperationCode . convertFromOracleToSDCCode ( op ) ; } } else { opCode = JDBCOperationType . convertToIntCode ( op ) ; } if ( opCode == - 1 ) { opCode = defaultOpCode ; } } catch ( NumberFormatException | UnsupportedOperationException ex ) { LOG . debug ( \"Operation obtained from record is not supported: {}. Handle by UnsupportedOpertaionAction {}. {}\" , ex . getMessage ( ) , unsupportedAction . getLabel ( ) , ex ) ; switch ( unsupportedAction ) { case DISCARD : LOG . debug ( \"Discarding record with unsupported operation {}\" , op ) ; break ; case SEND_TO_ERROR : LOG . debug ( \"Sending record to error due to unsupported operation {}\" , op ) ; errorRecords . add ( new OnRecordErrorException ( record , JdbcErrors . JDBC_70 , op ) ) ; break ; case USE_DEFAULT : opCode = defaultOpCode ; break ; default : //unknown action LOG . debug ( \"Sending record to error due to unknown operation: {}\" , op ) ; } } return opCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Kept for backward compatibility with runtime stats to be removed in future [CODESPLIT] public static Gauge < Map < String , Object > > createGauge ( MetricRegistry metrics , String name , Gauge gauge , final String pipelineName , final String pipelineRev ) { return create ( metrics , gauge , metricName ( name , GAUGE_SUFFIX ) , pipelineName , pipelineRev ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove metric object ( regardless of it s type ) [CODESPLIT] private static boolean remove ( final MetricRegistry metrics , final String name , String pipelineName , String pipelineRev ) { final String jmxNamePrefix = jmxPipelinePrefix ( pipelineName , pipelineRev ) ; final MetricRegistry metricRegistry = sdcMetrics ; if ( metricRegistry != null ) { AccessController . doPrivileged ( new PrivilegedAction < Void > ( ) { @ Override public Void run ( ) { metricRegistry . remove ( jmxNamePrefix + name ) ; return null ; } } ) ; } return metrics . remove ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records from MongoDB Oplog origin have a bit unique structure . [CODESPLIT] @ Override public SortedMap < String , String > getColumnsToParameters ( final Record record , int op , Map < String , String > parameters , Map < String , String > columnsToFields ) { SortedMap < String , String > columnsToParameters = new TreeMap <> ( ) ; for ( Map . Entry < String , String > entry : columnsToFields . entrySet ( ) ) { String columnName = entry . getKey ( ) ; String fieldPath = getFieldPath ( columnName , columnsToFields , op ) ; if ( record . has ( fieldPath ) ) { columnsToParameters . put ( columnName , parameters . get ( columnName ) ) ; } else { LOG . trace ( \"Record is missing a field for column {} for the operation code {}\" , columnName , op ) ; } } return columnsToParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a fieldpath for the corresponding column name . The columnToField Map contains column - to - field mapping so simply get fieldpath for the column name if operation is INSERT or DELETE . We replace / o with / o2 to get _id field and change / o to / o / $set to get updating column & value fields . [CODESPLIT] @ Override String getFieldPath ( String columnName , Map < String , String > columnsToField , int op ) { if ( op == OperationType . UPDATE_CODE ) { String fieldPath = columnsToField . get ( columnName ) ; if ( fieldPath == null ) { LOG . error ( \"Column name {} is not defined in column-filed mapping\" , columnName ) ; return null ; } if ( fieldPath . contains ( ID_FIELD ) ) { // _id is stored in \"/o2/column_name for update records. Need to change the fieldpath\" return fieldPath . replace ( OP_FIELD , OP2_FIELD ) ; } else { // column and values are stored in \"/o/$set/column_name\". Need to change the fieldpath return fieldPath . replaceFirst ( OP_FIELD , String . format ( \"%s/%s\" , OP_FIELD , SET_FIELD ) ) ; } } return columnsToField . get ( columnName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the Header attributes [CODESPLIT] private Map < String , Object > generateHeaderAttrs ( Path file ) throws StageException { try { Map < String , Object > recordHeaderAttr = new HashMap <> ( ) ; recordHeaderAttr . put ( HeaderAttributeConstants . FILE , file . toAbsolutePath ( ) ) ; recordHeaderAttr . put ( HeaderAttributeConstants . FILE_NAME , file . getFileName ( ) ) ; recordHeaderAttr . put ( HeaderAttributeConstants . SIZE , Files . size ( file ) ) ; recordHeaderAttr . put ( HeaderAttributeConstants . LAST_MODIFIED_TIME , Files . getLastModifiedTime ( file ) ) ; return recordHeaderAttr ; } catch ( IOException e ) { throw new TransformerStageCheckedException ( Errors . CONVERT_09 , e . toString ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the record is a whole file record [CODESPLIT] private void validateRecord ( Record record ) throws StageException { try { FileRefUtil . validateWholeFileRecord ( record ) ; } catch ( IllegalArgumentException e ) { throw new TransformerStageCheckedException ( Errors . CONVERT_01 , e . toString ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the temporary parquet file path and validate the path [CODESPLIT] @ VisibleForTesting Path getAndValidateTempFilePath ( Record record , String sourceFileName ) throws StageException { RecordEL . setRecordInContext ( variables , record ) ; String dirPath ; try { dirPath = resolveEL ( tempDirElEval , variables , jobConfig . tempDir , String . class ) ; } catch ( ELEvalException ex ) { throw new TransformerStageCheckedException ( Errors . CONVERT_04 , jobConfig . tempDir ) ; } if ( Strings . isNullOrEmpty ( dirPath ) ) { throw new TransformerStageCheckedException ( Errors . CONVERT_02 , jobConfig . tempDir ) ; } if ( Strings . isNullOrEmpty ( sourceFileName ) ) { throw new TransformerStageCheckedException ( Errors . CONVERT_03 , FILENAME ) ; } String fileName = jobConfig . uniquePrefix + sourceFileName + jobConfig . fileNameSuffix ; Path tempParquetFile = Paths . get ( dirPath , fileName ) ; if ( ! tempParquetFile . isAbsolute ( ) ) { throw new TransformerStageCheckedException ( Errors . CONVERT_05 , tempParquetFile ) ; } try { if ( ! Files . exists ( tempParquetFile . getParent ( ) ) ) { Files . createDirectories ( Paths . get ( dirPath ) ) ; } } catch ( IOException ex ) { throw new TransformerStageCheckedException ( Errors . CONVERT_10 , tempParquetFile . toString ( ) , ex ) ; } // handle old temp files try { handleOldTempFiles ( tempParquetFile ) ; } catch ( IOException ex ) { throw new TransformerStageCheckedException ( Errors . CONVERT_06 , tempParquetFile . toString ( ) , ex ) ; } return tempParquetFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete temporary parquet file [CODESPLIT] private void handleOldTempFiles ( Path tempParquetFile ) throws IOException { if ( tempParquetFile == null ) { LOG . warn ( \"temporary parquet file is empty\" ) ; return ; } Files . deleteIfExists ( tempParquetFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the Avro file input stream [CODESPLIT] private InputStream getAvroInputStream ( Record record ) throws StageException { try { FileRef fileRef = record . get ( FileRefUtil . FILE_REF_FIELD_PATH ) . getValueAsFileRef ( ) ; // get avro reader final boolean includeChecksumInTheEvents = false ; InputStream is = FileRefUtil . getReadableStream ( getContext ( ) , fileRef , InputStream . class , includeChecksumInTheEvents , null , null ) ; return is ; } catch ( IOException ex ) { throw new TransformerStageCheckedException ( Errors . CONVERT_07 , ex . toString ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the Avro file reader [CODESPLIT] private DataFileStream < GenericRecord > getFileReader ( InputStream is , String sourceFileName ) throws StageException { try { DatumReader < GenericRecord > reader = new GenericDatumReader <> ( ) ; DataFileStream < GenericRecord > fileReader = new DataFileStream <> ( is , reader ) ; return fileReader ; } catch ( IOException ex ) { throw new TransformerStageCheckedException ( Errors . CONVERT_11 , sourceFileName , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert Avro record to Parquet [CODESPLIT] private void writeParquet ( String sourceFileName , DataFileStream < GenericRecord > fileReader , Path tempParquetFile ) throws StageException { long recordCount = 0 ; GenericRecord avroRecord ; Schema schema = fileReader . getSchema ( ) ; LOG . debug ( \"Start reading input file : {}\" , sourceFileName ) ; try { // initialize parquet writer Configuration jobConfiguration = new Configuration ( ) ; String compressionCodecName = compressionElEval . eval ( variables , jobConfig . avroParquetConfig . compressionCodec , String . class ) ; jobConfiguration . set ( AvroParquetConstants . COMPRESSION_CODEC_NAME , compressionCodecName ) ; jobConfiguration . setInt ( AvroParquetConstants . ROW_GROUP_SIZE , jobConfig . avroParquetConfig . rowGroupSize ) ; jobConfiguration . setInt ( AvroParquetConstants . PAGE_SIZE , jobConfig . avroParquetConfig . pageSize ) ; jobConfiguration . setInt ( AvroParquetConstants . DICTIONARY_PAGE_SIZE , jobConfig . avroParquetConfig . dictionaryPageSize ) ; jobConfiguration . setInt ( AvroParquetConstants . MAX_PADDING_SIZE , jobConfig . avroParquetConfig . maxPaddingSize ) ; // Parquet writer ParquetWriter . Builder builder = AvroToParquetConverterUtil . initializeWriter ( new org . apache . hadoop . fs . Path ( tempParquetFile . toString ( ) ) , schema , jobConfiguration ) ; parquetWriter = builder . build ( ) ; while ( fileReader . hasNext ( ) ) { avroRecord = fileReader . next ( ) ; parquetWriter . write ( avroRecord ) ; recordCount ++ ; } parquetWriter . close ( ) ; } catch ( IOException ex ) { throw new TransformerStageCheckedException ( Errors . CONVERT_08 , sourceFileName , recordCount , ex ) ; } LOG . debug ( \"Finished writing {} records to {}\" , recordCount , tempParquetFile . getFileName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void destroy ( ) { // Clean up any open resources. if ( null != redisClient ) { redisClient . disconnect ( ) ; redisClient . close ( ) ; redisClient = null ; } super . destroy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing only [CODESPLIT] void validateClass ( String name ) { // python scripting engine generates __*__ classes under all packages (including SDC api package) if ( ! ( name . endsWith ( \"__\" ) ) ) { for ( String blacklistedPackage : blacklistedPackages ) { if ( name . startsWith ( blacklistedPackage ) ) { throw new IllegalArgumentException ( String . format ( \"Class '%s' cannot be present in %s\" , name , toString ( ) ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visible for testing only [CODESPLIT] void validateResource ( String name ) { for ( String blacklistedPackage : blacklistedDirs ) { if ( name . startsWith ( blacklistedPackage ) ) { throw new IllegalArgumentException ( String . format ( \"Resource '%s' cannot be present in %s\" , name , toString ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the encryption input is a supported type otherwise sends the record to error . [CODESPLIT] public Optional < Field > checkInputEncrypt ( Record record , Field field ) { if ( UNSUPPORTED_TYPES . contains ( field . getType ( ) ) ) { getContext ( ) . toError ( record , CRYPTO_03 , field . getType ( ) ) ; return Optional . empty ( ) ; } return Optional . of ( field ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the encryption input is a supported type otherwise sends the record to StageException . [CODESPLIT] public Optional < Field > checkInputEncrypt ( Field field ) throws StageException { if ( UNSUPPORTED_TYPES . contains ( field . getType ( ) ) ) { throw new StageException ( CRYPTO_03 , field . getType ( ) ) ; } return Optional . of ( field ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the decryption input is a valid type otherwise sends the record to error . [CODESPLIT] public Optional < Field > checkInputDecrypt ( Record record , Field field ) { if ( field . getType ( ) != Field . Type . BYTE_ARRAY ) { getContext ( ) . toError ( record , CRYPTO_02 , field . getType ( ) ) ; return Optional . empty ( ) ; } return Optional . of ( field ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the decryption input is a valid type otherwise sends the record to StageException . [CODESPLIT] public Optional < Field > checkInputDecrypt ( Field field ) throws StageException { if ( field . getType ( ) != Field . Type . BYTE_ARRAY ) { throw new StageException ( CRYPTO_02 , field . getType ( ) ) ; } return Optional . of ( field ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does data type conversions in preparation for encryption . [CODESPLIT] public byte [ ] prepareEncrypt ( Field field , Map < String , String > context ) { context . put ( SDC_FIELD_TYPE , field . getType ( ) . name ( ) ) ; if ( field . getType ( ) == Field . Type . BYTE_ARRAY ) { return field . getValueAsByteArray ( ) ; } else { // Treat all other data as strings return field . getValueAsString ( ) . getBytes ( Charsets . UTF_8 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a decrypted { @link Field } with its original type preserved when type information has been preserved in the AAD . [CODESPLIT] public Field createResultFieldDecrypt ( CryptoResult < byte [ ] , ? > result ) { Field . Type fieldType = Field . Type . valueOf ( result . getEncryptionContext ( ) . getOrDefault ( SDC_FIELD_TYPE , Field . Type . BYTE_ARRAY . name ( ) ) ) ; // Field API prohibits STRING to BYTE_ARRAY conversion so this is a special case if ( fieldType == Field . Type . BYTE_ARRAY ) { return Field . create ( result . getResult ( ) ) ; } // Field API supports STRING to other primitive types. return Field . create ( fieldType , new String ( result . getResult ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes a batch from the specified file and offset up to a maximum batch size . If the file is fully processed it must return - 1 otherwise it must return the offset to continue from next invocation . [CODESPLIT] public String generateBatch ( WrappedFile file , String offset , int maxBatchSize , BatchMaker batchMaker ) throws StageException , BadSpoolFileException { if ( offset == null ) { offset = \"0\" ; } String sourceFile = file . getFileName ( ) ; try { if ( parser == null ) { parser = SpoolDirUtil . getParser ( fs , file , conf . dataFormat , parserFactory , offset , conf . dataFormatConfig . wholeFileMaxObjectLen , rateLimitElEval , rateLimitElVars , conf . dataFormatConfig . rateLimit ) ; } Map < String , Object > recordHeaderAttr = generateHeaderAttrs ( file ) ; for ( int i = 0 ; i < maxBatchSize ; i ++ ) { try { Record record ; try { record = parser . parse ( ) ; } catch ( RecoverableDataParserException ex ) { // Propagate partially parsed record to error stream record = ex . getUnparsedRecord ( ) ; recordHeaderAttr . put ( HeaderAttributeConstants . OFFSET , offset ) ; setHeaders ( record , recordHeaderAttr ) ; errorRecordHandler . onError ( new OnRecordErrorException ( record , ex . getErrorCode ( ) , ex . getParams ( ) ) ) ; perFileErrorCount ++ ; noMoreDataErrorCount ++ ; // We'll simply continue reading once this continue ; } if ( record != null ) { recordHeaderAttr . put ( HeaderAttributeConstants . OFFSET , offset ) ; setHeaders ( record , recordHeaderAttr ) ; batchMaker . addRecord ( record ) ; offset = parser . getOffset ( ) ; if ( offset == null ) { offset = \"0\" ; } noMoreDataRecordCount ++ ; perFileRecordCount ++ ; } else { parser . close ( ) ; parser = null ; offset = MINUS_ONE ; break ; } } catch ( ObjectLengthException ex ) { String exOffset = offset ; offset = ( parser != null ) ? parser . getOffset ( ) : MINUS_ONE ; if ( offset == null ) { offset = \"0\" ; } errorRecordHandler . onError ( Errors . SPOOLDIR_02 , sourceFile , exOffset , ex ) ; perFileErrorCount ++ ; noMoreDataErrorCount ++ ; } } } catch ( IOException | DataParserException ex ) { if ( ex instanceof ClosedByInterruptException || ex . getCause ( ) instanceof ClosedByInterruptException ) { //If the pipeline was stopped, we may get a ClosedByInterruptException while reading avro data. //This is because the thread is interrupted when the pipeline is stopped. //Instead of sending the file to error, publish batch and move one. } else { offset = MINUS_ONE ; String exOffset ; if ( ex instanceof OverrunException ) { exOffset = String . valueOf ( ( ( OverrunException ) ex ) . getStreamOffset ( ) ) ; } else { try { exOffset = ( parser != null ) ? parser . getOffset ( ) : MINUS_ONE ; } catch ( IOException ex1 ) { LOG . warn ( \"Could not get the file offset to report with error, reason: {}\" , ex1 . toString ( ) , ex ) ; exOffset = MINUS_ONE ; } } switch ( context . getOnErrorRecord ( ) ) { case DISCARD : break ; case TO_ERROR : // we failed to produce a record, which leaves the input file in an unknown state. all we can do here is // throw an exception. throw new BadSpoolFileException ( file . getAbsolutePath ( ) , exOffset , ex ) ; case STOP_PIPELINE : context . reportError ( Errors . SPOOLDIR_04 , sourceFile , exOffset , ex . toString ( ) , ex ) ; throw new StageException ( Errors . SPOOLDIR_04 , sourceFile , exOffset , ex . toString ( ) ) ; default : throw new IllegalStateException ( Utils . format ( \"Unknown OnError value '{}'\" , context . getOnErrorRecord ( ) , ex ) ) ; } } } finally { if ( MINUS_ONE . equals ( offset ) ) { if ( parser != null ) { try { parser . close ( ) ; parser = null ; } catch ( IOException ex ) { //NOP } } } } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the gauge with needed information [CODESPLIT] private void initGaugeIfNeeded ( ) { gaugeMap . put ( THREAD_NAME , Thread . currentThread ( ) . getName ( ) ) ; gaugeMap . put ( STATUS , \"\" ) ; gaugeMap . put ( CURRENT_FILE , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle Exception [CODESPLIT] private void handleStageError ( ErrorCode errorCode , Exception e ) { final String errorMessage = \"Failure Happened\" ; LOG . error ( errorMessage , e ) ; try { errorRecordHandler . onError ( errorCode , e ) ; } catch ( StageException se ) { LOG . error ( \"Error when routing to stage error\" , se ) ; //Way to throw stage exception from runnable to main source thread Throwables . propagate ( se ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find cycles in the { [CODESPLIT] boolean isGraphCyclic ( ) { for ( V vertex : directedGraph . vertices ( ) ) { boolean areThereCycles = findCycles ( new LinkedHashSet < V > ( ) , vertex ) ; if ( areThereCycles ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the Pattern that this Matcher uses to find matches with [CODESPLIT] public Matcher usePattern ( Pattern newPattern ) { if ( newPattern == null ) { throw new IllegalArgumentException ( \"newPattern cannot be null\" ) ; } this . parentPattern = newPattern ; matcher . usePattern ( newPattern . pattern ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements a non - terminal append - and - replace step . [CODESPLIT] public Matcher appendReplacement ( StringBuffer sb , String replacement ) { matcher . appendReplacement ( sb , parentPattern . replaceProperties ( replacement ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all named groups that exist in the input string . This resets the matcher and attempts to match the input against the pre - specified pattern . [CODESPLIT] @ Override public Map < String , String > namedGroups ( ) { Map < String , String > result = new LinkedHashMap < String , String > ( ) ; if ( matcher . find ( 0 ) ) { for ( String groupName : parentPattern . groupNames ( ) ) { String groupValue = matcher . group ( groupIndex ( groupName ) ) ; result . put ( groupName , groupValue ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces every subsequence of the input sequence that matches the pattern with the given replacement string . [CODESPLIT] public String replaceAll ( String replacement ) { String r = parentPattern . replaceProperties ( replacement ) ; return matcher . replaceAll ( r ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "no trespassing ... [CODESPLIT] private Properties getKafkaProperties ( ) { Properties props = new Properties ( ) ; props . putAll ( conf . streamsOptions ) ; props . setProperty ( \"group.id\" , conf . consumerGroup ) ; props . setProperty ( \"max.poll.records\" , String . valueOf ( batchSize ) ) ; props . setProperty ( \"enable.auto.commit\" , \"true\" ) ; props . setProperty ( \"auto.commit.interval.ms\" , \"1000\" ) ; props . setProperty ( \"key.deserializer\" , \"org.apache.kafka.common.serialization.ByteArrayDeserializer\" ) ; props . setProperty ( \"value.deserializer\" , \"com.mapr.db.cdc.ChangeDataRecordDeserializer\" ) ; return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used during deserializer and sqpath ( Single quote escaped path ) is passed to determine the last field name . [CODESPLIT] public static String getLastFieldNameFromPath ( String path ) { String [ ] pathSplit = ( path != null ) ? path . split ( \"/\" ) : null ; if ( pathSplit != null && pathSplit . length > 0 ) { String lastFieldName = pathSplit [ pathSplit . length - 1 ] ; //handle special case field name containing slash eg. /'foo/bar' boolean singleQuoted = lastFieldName . charAt ( 0 ) == QUOTE_CHAR && lastFieldName . charAt ( lastFieldName . length ( ) - 1 ) == QUOTE_CHAR ; if ( lastFieldName . contains ( \"'\" ) && ! singleQuoted ) { //If path contains slash inside name, split it by \"/'\" pathSplit = path . split ( \"/'\" ) ; if ( pathSplit . length > 0 ) { lastFieldName = \"'\" + pathSplit [ pathSplit . length - 1 ] ; singleQuoted = true ; } } if ( singleQuoted ) { return singleQuoteUnescape ( lastFieldName ) ; } else { return lastFieldName ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method escapes backslash double quotes and single quotes ( keeping replacement of to \\\\\\\\\\ as is so as to maintain backward compatibility any serialization / deserialization ) [CODESPLIT] private static String escapeQuotesAndBackSlash ( String path , boolean isSingleQuoteEscape ) { String quoteChar = isSingleQuoteEscape ? \"'\" : \"\\\"\" ; StringBuilder sb = new StringBuilder ( path . length ( ) * 2 ) . append ( quoteChar ) ; char [ ] chars = path . toCharArray ( ) ; for ( char c : chars ) { if ( c == ' ' ) { sb . append ( \"\\\\\\\\\" ) ; } else if ( c == ' ' ) { sb . append ( isSingleQuoteEscape ? \"\\\\\\\"\" : \"\\\\\\\\\\\"\" ) ; } else if ( c == ' ' ) { sb . append ( isSingleQuoteEscape ? \"\\\\\\\\\\'\" : \"\\\\\\'\" ) ; } else { sb . append ( c ) ; } } return sb . append ( quoteChar ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method un escapes backslash double quotes and single quotes ( keeping replacement of \\\\\\\\\\ to as is so as to maintain backward compatibility any serialization / deserialization ) [CODESPLIT] private static String unescapeQuotesAndBackSlash ( String path , boolean isSingleQuoteUnescape ) { path = ( isSingleQuoteUnescape ) ? path . replace ( \"\\\\\\\"\" , \"\\\"\" ) . replace ( \"\\\\\\\\\\'\" , \"'\" ) : path . replace ( \"\\\\\\\\\\\"\" , \"\\\"\" ) . replace ( \"\\\\\\'\" , \"'\" ) ; return path . replace ( \"\\\\\\\\\" , \"\\\\\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method un escapes backslash and un escapes extra escapes before double quotes and single quotes ( appended by { [CODESPLIT] public static String standardizePathForParse ( String path , boolean isSingleQuoteEscape ) { path = isSingleQuoteEscape ? path . replace ( \"\\\\\\\\\\'\" , \"\\\\'\" ) : path . replace ( \"\\\\\\\\\\\"\" , \"\\\\\\\"\" ) ; return path . replace ( \"\\\\\\\\\" , \"\\\\\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There is a problem with some older stages that originally were not using our data parser library as the upgrade on those stages does not create all the properties that were introduced by the data parser library . For example File Tail origin doesn t support avro so the upgrade procedure doesn t use create the avro specific properties . This is normally not a problem as post - upgrade SDC will create all missing properties with default values . However this particular upgrade will fail if the property avroSchema is missing . [CODESPLIT] public static void ensureAvroSchemaExists ( List < Config > configs , String prefix ) { Optional < Config > avroSchema = findByName ( configs , \"avroSchema\" ) ; if ( ! avroSchema . isPresent ( ) ) { configs . add ( new Config ( prefix + \".avroSchema\" , null ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get global variable value . [CODESPLIT] public static String getGlobalVariable ( DataSource dataSource , String variable ) throws SQLException { try ( Connection conn = dataSource . getConnection ( ) ) { try ( Statement stmt = conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( String . format ( \"show global variables like '%s'\" , variable ) ) ; ) { if ( rs . next ( ) ) { return rs . getString ( 2 ) ; } else { return \"\" ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************** [CODESPLIT] public static StatusJson wrapState ( PipelineStatus status ) { if ( status == null ) { return null ; } switch ( status ) { case STOPPED : return StatusJson . STOPPED ; case STOPPING : return StatusJson . STOPPING ; case RUNNING : return StatusJson . RUNNING ; case RUN_ERROR : return StatusJson . RUN_ERROR ; case FINISHED : return StatusJson . FINISHED ; case CONNECTING : return StatusJson . CONNECTING ; case CONNECT_ERROR : return StatusJson . CONNECT_ERROR ; case DISCONNECTED : return StatusJson . DISCONNECTED ; case DISCONNECTING : return StatusJson . DISCONNECTING ; case EDITED : return StatusJson . EDITED ; case FINISHING : return StatusJson . FINISHING ; case KILLED : return StatusJson . KILLED ; case RUNNING_ERROR : return StatusJson . RUNNING_ERROR ; case STARTING : return StatusJson . STARTING ; case STARTING_ERROR : return StatusJson . STARTING_ERROR ; case START_ERROR : return StatusJson . START_ERROR ; case RETRY : return StatusJson . RETRY ; case STOP_ERROR : return StatusJson . STOP_ERROR ; case STOPPING_ERROR : return StatusJson . STOPPING_ERROR ; case DELETED : return StatusJson . DELETED ; default : throw new IllegalArgumentException ( \"Unrecognized state\" + status ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create pipeline start event . [CODESPLIT] private Record createStartEvent ( ) { Preconditions . checkState ( startEventStage != null , \"Start Event Stage is not set!\" ) ; EventRecord eventRecord = new EventRecordImpl ( \"pipeline-start\" , 1 , startEventStage . getInfo ( ) . getInstanceName ( ) , \"\" , null , null ) ; Map < String , Field > rootField = new LinkedHashMap <> ( ) ; rootField . put ( \"user\" , Field . create ( Field . Type . STRING , userContext . getUser ( ) ) ) ; rootField . put ( \"pipelineId\" , Field . create ( Field . Type . STRING , name ) ) ; rootField . put ( \"pipelineTitle\" , Field . create ( Field . Type . STRING , pipelineConf . getTitle ( ) ) ) ; // Pipeline parameters Map < String , Field > parameters = new LinkedHashMap <> ( ) ; if ( runtimeParameters != null ) { for ( Map . Entry < String , Object > entry : runtimeParameters . entrySet ( ) ) { parameters . put ( entry . getKey ( ) , Field . create ( Field . Type . STRING , entry . getValue ( ) . toString ( ) ) ) ; } } rootField . put ( \"parameters\" , Field . create ( parameters ) ) ; eventRecord . set ( Field . create ( rootField ) ) ; return eventRecord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create pipeline stop event . [CODESPLIT] private Record createStopEvent ( PipelineStopReason stopReason ) { Preconditions . checkState ( stopEventStage != null , \"Stop Event Stage is not set!\" ) ; EventRecord eventRecord = new EventRecordImpl ( \"pipeline-stop\" , 1 , stopEventStage . getInfo ( ) . getInstanceName ( ) , \"\" , null , null ) ; Map < String , Field > rootField = new LinkedHashMap <> ( ) ; rootField . put ( \"reason\" , Field . create ( Field . Type . STRING , stopReason . name ( ) ) ) ; rootField . put ( \"pipelineId\" , Field . create ( Field . Type . STRING , name ) ) ; rootField . put ( \"pipelineTitle\" , Field . create ( Field . Type . STRING , pipelineConf . getTitle ( ) ) ) ; eventRecord . set ( Field . create ( rootField ) ) ; return eventRecord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "infinite recursion [CODESPLIT] private void getAllReferences ( PartnerConnection partnerConnection , Map < String , ObjectMetadata > metadataMap , List < List < Pair < String , String > > > references , String [ ] allTypes , int depth ) throws ConnectionException { if ( depth < 0 ) { return ; } List < String > next = new ArrayList <> ( ) ; for ( int typeIndex = 0 ; typeIndex < allTypes . length ; typeIndex += MAX_METADATA_TYPES ) { int copyTo = Math . min ( typeIndex + MAX_METADATA_TYPES , allTypes . length ) ; String [ ] types = Arrays . copyOfRange ( allTypes , typeIndex , copyTo ) ; // Special case - we prepopulate the cache with the root sobject type - don't repeat // ourselves if ( types . length > 1 || ! metadataMap . containsKey ( types [ 0 ] ) ) { for ( DescribeSObjectResult result : partnerConnection . describeSObjects ( types ) ) { Map < String , Field > fieldMap = new LinkedHashMap <> ( ) ; Map < String , Field > relationshipMap = new LinkedHashMap <> ( ) ; for ( Field field : result . getFields ( ) ) { fieldMap . put ( field . getName ( ) . toLowerCase ( ) , field ) ; String relationshipName = field . getRelationshipName ( ) ; if ( relationshipName != null ) { relationshipMap . put ( relationshipName . toLowerCase ( ) , field ) ; } } Map < String , String > childRelationships = new LinkedHashMap <> ( ) ; for ( ChildRelationship child : result . getChildRelationships ( ) ) { if ( child . getRelationshipName ( ) != null ) { childRelationships . put ( child . getRelationshipName ( ) . toLowerCase ( ) , child . getChildSObject ( ) . toLowerCase ( ) ) ; } } metadataMap . put ( result . getName ( ) . toLowerCase ( ) , new ObjectMetadata ( fieldMap , relationshipMap , childRelationships ) ) ; } } if ( references != null ) { for ( List < Pair < String , String > > path : references ) { // Top field name in the path should be in the metadata now if ( ! path . isEmpty ( ) ) { Pair < String , String > top = path . get ( 0 ) ; Field field = metadataMap . get ( top . getLeft ( ) ) . getFieldFromRelationship ( top . getRight ( ) ) ; Set < String > sobjectNames = metadataMap . keySet ( ) ; for ( String ref : field . getReferenceTo ( ) ) { ref = ref . toLowerCase ( ) ; if ( ! sobjectNames . contains ( ref ) && ! next . contains ( ref ) ) { next . add ( ref ) ; } if ( path . size ( ) > 1 ) { path . set ( 1 , Pair . of ( ref , path . get ( 1 ) . getRight ( ) ) ) ; } } // SDC-10422 Polymorphic references have an implicit reference to the Name object type if ( field . isPolymorphicForeignKey ( ) ) { next . add ( NAME ) ; } path . remove ( 0 ) ; } } } } if ( ! next . isEmpty ( ) ) { getAllReferences ( partnerConnection , metadataMap , references , next . toArray ( new String [ 0 ] ) , depth - 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "since Salesforce doesn t like scientific notation in queries [CODESPLIT] protected String fixOffset ( String offsetColumn , String offset ) { com . sforce . soap . partner . Field sfdcField = getFieldMetadata ( sobjectType , offsetColumn ) ; if ( SobjectRecordCreator . DECIMAL_TYPES . contains ( sfdcField . getType ( ) . toString ( ) ) && offset . contains ( \"E\" ) ) { BigDecimal val = new BigDecimal ( offset ) ; offset = val . toPlainString ( ) ; if ( val . compareTo ( MAX_OFFSET_INT ) > 0 && ! offset . contains ( \".\" ) ) { // We need the \".0\" suffix since Salesforce doesn't like integer // bigger than 2147483647 offset += \".0\" ; } } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RUNTIME supports only Numeric types and String at the moment [CODESPLIT] private Object extractAsRuntime ( Field field , String valueStr ) { if ( field . getType ( ) == Byte . TYPE || field . getType ( ) == Byte . class || field . getType ( ) == Short . TYPE || field . getType ( ) == Short . class || field . getType ( ) == Integer . TYPE || field . getType ( ) == Integer . class || field . getType ( ) == Long . TYPE || field . getType ( ) == Long . class || field . getType ( ) == Float . TYPE || field . getType ( ) == Float . class || field . getType ( ) == Double . TYPE || field . getType ( ) == Double . class ) { return extractAsNumber ( field , valueStr ) ; } else if ( String . class . isAssignableFrom ( field . getType ( ) ) ) { return valueStr ; } throw new IllegalArgumentException ( Utils . format ( \"Invalid type for RUNTIME type: {}\" , field . getType ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new partition to the given table with optional custom location . [CODESPLIT] public void executeAlterTableAddPartitionQuery ( String qualifiedTableName , LinkedHashMap < String , String > partitionNameValueMap , Map < String , HiveTypeInfo > partitionTypeMap , String partitionPath ) throws StageException { String sql = buildPartitionAdditionQuery ( qualifiedTableName , partitionNameValueMap , partitionTypeMap , partitionPath ) ; execute ( sql ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute Alter Table set Table Properties [CODESPLIT] public void executeAlterTableSetTblPropertiesQuery ( String qualifiedTableName , String partitionPath ) throws StageException { String sql = buildSetTablePropertiesQuery ( qualifiedTableName , partitionPath ) ; execute ( sql ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public Set < PartitionInfoCacheSupport . PartitionValues > executeShowPartitionsQuery ( String qualifiedTableName ) throws StageException { String sql = buildShowPartitionsQuery ( qualifiedTableName ) ; return executeQuery ( sql , new WithResultSet < Set < PartitionInfoCacheSupport . PartitionValues > > ( ) { @ Override public Set < PartitionInfoCacheSupport . PartitionValues > run ( ResultSet rs ) throws SQLException , StageException { Set < PartitionInfoCacheSupport . PartitionValues > partitionValuesSet = new HashSet <> ( ) ; while ( rs . next ( ) ) { String partitionInfoString = rs . getString ( 1 ) ; String [ ] partitionInfoSplit = partitionInfoString . split ( HiveMetastoreUtil . SEP ) ; LinkedHashMap < String , String > vals = new LinkedHashMap <> ( ) ; for ( String partitionValInfo : partitionInfoSplit ) { String [ ] partitionNameVal = partitionValInfo . split ( \"=\" ) ; vals . put ( partitionNameVal [ 0 ] , partitionNameVal [ 1 ] ) ; } partitionValuesSet . add ( new PartitionInfoCacheSupport . PartitionValues ( vals ) ) ; } return partitionValuesSet ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public Pair < LinkedHashMap < String , HiveTypeInfo > , LinkedHashMap < String , HiveTypeInfo > > executeDescTableQuery ( String qualifiedTableName ) throws StageException { String sql = buildDescTableQuery ( qualifiedTableName ) ; return executeQuery ( sql , new WithResultSet < Pair < LinkedHashMap < String , HiveTypeInfo > , LinkedHashMap < String , HiveTypeInfo > > > ( ) { @ Override public Pair < LinkedHashMap < String , HiveTypeInfo > , LinkedHashMap < String , HiveTypeInfo > > run ( ResultSet rs ) throws SQLException , StageException { LinkedHashMap < String , HiveTypeInfo > columnTypeInfo = extractTypeInfo ( rs ) ; processDelimiter ( rs , \"#\" ) ; processDelimiter ( rs , \"#\" ) ; processDelimiter ( rs , \"\" ) ; LinkedHashMap < String , HiveTypeInfo > partitionTypeInfo = extractTypeInfo ( rs ) ; //Remove partition columns from the columns map. for ( String partitionCol : partitionTypeInfo . keySet ( ) ) { columnTypeInfo . remove ( partitionCol ) ; } return Pair . of ( columnTypeInfo , partitionTypeInfo ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns location for given database . [CODESPLIT] public String executeDescribeDatabase ( String dbName ) throws StageException { String sql = buildDescribeDatabase ( dbName ) ; return executeQuery ( sql , rs -> { if ( ! rs . next ( ) ) { throw new HiveStageCheckedException ( Errors . HIVE_35 , \"Database doesn't exists.\" ) ; } return HiveMetastoreUtil . stripHdfsHostAndPort ( rs . getString ( RESULT_SET_LOCATION ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public Pair < Boolean , Boolean > executeShowTBLPropertiesQuery ( String qualifiedTableName ) throws StageException { String sql = String . format ( SHOW_TBLPROPERTIES , qualifiedTableName ) ; return executeQuery ( sql , new WithResultSet < Pair < Boolean , Boolean > > ( ) { @ Override public Pair < Boolean , Boolean > run ( ResultSet rs ) throws SQLException { boolean isExternal = false , useAsAvro = true ; while ( rs . next ( ) ) { String propName = rs . getString ( RESULT_SET_PROP_NAME ) ; String propValue = rs . getString ( RESULT_SET_PROP_VALUE ) ; if ( propName . toUpperCase ( ) . equals ( EXTERNAL ) ) { isExternal = Boolean . valueOf ( propValue ) ; } else if ( propName . equals ( AVRO_SCHEMA_URL ) ) { useAsAvro = false ; } } return Pair . of ( isExternal , useAsAvro ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute given query . [CODESPLIT] private void execute ( String query ) throws StageException { LOG . debug ( \"Executing SQL: {}\" , query ) ; Timer . Context t = updateTimer . time ( ) ; try ( Statement statement = hiveConfigBean . getHiveConnection ( ) . createStatement ( ) ) { statement . execute ( query ) ; } catch ( Exception e ) { LOG . error ( \"Exception while processing query: {}\" , query , e ) ; throw new HiveStageCheckedException ( Errors . HIVE_20 , query , e . getMessage ( ) ) ; } finally { long time = t . stop ( ) ; LOG . debug ( \"Query '{}' took {} nanoseconds\" , query , time ) ; updateMeter . mark ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute given query and process it s result set . [CODESPLIT] private < T > T executeQuery ( String query , WithResultSet < T > execution ) throws StageException { LOG . debug ( \"Executing SQL:  {}\" , query ) ; Timer . Context t = selectTimer . time ( ) ; try ( Statement statement = hiveConfigBean . getHiveConnection ( ) . createStatement ( ) ; ResultSet rs = statement . executeQuery ( query ) ; ) { // Stop timer immediately so that we're calculating only query execution time and not the processing time long time = t . stop ( ) ; LOG . debug ( \"Query '{}' took {} nanoseconds\" , query , time ) ; t = null ; return execution . run ( rs ) ; } catch ( Exception e ) { LOG . error ( \"Exception while processing query: {}\" , query , e ) ; throw new HiveStageCheckedException ( Errors . HIVE_20 , query , e . getMessage ( ) ) ; } finally { // If the timer wasn't stopped due to exception yet, stop it now if ( t != null ) { long time = t . stop ( ) ; LOG . debug ( \"Query '{}' took {} nanoseconds\" , query , time ) ; } selectMeter . mark ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String produce ( String lastSourceOffset , int maxBatchSize , BatchMaker batchMaker ) throws StageException { // Offsets can vary depending on the data source. Here we use an integer as an example only. long nextSourceOffset = 0 ; if ( lastSourceOffset != null ) { nextSourceOffset = Long . parseLong ( lastSourceOffset ) ; } int numRecords = 0 ; // TODO: As the developer, implement your logic that reads from a data source in this method. // Create records and add to batch. Records must have a string id. This can include the source offset // or other metadata to help uniquely identify the record itself. while ( numRecords < maxBatchSize ) { Record record = getContext ( ) . createRecord ( \"some-id::\" + nextSourceOffset ) ; Map < String , Field > map = new HashMap <> ( ) ; map . put ( \"fieldName\" , Field . create ( \"Some Value\" ) ) ; record . set ( Field . create ( map ) ) ; batchMaker . addRecord ( record ) ; ++ nextSourceOffset ; ++ numRecords ; } return String . valueOf ( nextSourceOffset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run batch with given consumer for each pipe . [CODESPLIT] public void executeBatch ( String offsetKey , String offsetValue , long batchStartTime , ThrowingConsumer < Pipe > consumer ) throws PipelineRuntimeException , StageException { MDC . put ( LogConstants . RUNNER , String . valueOf ( runnerId ) ) ; // Persist static information for the batch (this won't change as the batch progresses) this . runtimeMetricGauge . put ( METRIC_BATCH_START_TIME , batchStartTime ) ; this . runtimeMetricGauge . put ( METRIC_OFFSET_KEY , Optional . ofNullable ( offsetKey ) . orElse ( \"\" ) ) ; this . runtimeMetricGauge . put ( METRIC_OFFSET_VALUE , Optional . ofNullable ( offsetValue ) . orElse ( \"\" ) ) ; this . runtimeMetricGauge . put ( METRIC_STAGE_START_TIME , System . currentTimeMillis ( ) ) ; try { // Run one pipe at a time for ( Pipe p : pipes ) { String instanceName = p . getStage ( ) . getInfo ( ) . getInstanceName ( ) ; this . runtimeMetricGauge . put ( METRIC_CURRENT_STAGE , instanceName ) ; MDC . put ( LogConstants . STAGE , instanceName ) ; if ( p instanceof StagePipe ) { this . runtimeMetricGauge . put ( METRIC_STAGE_START_TIME , System . currentTimeMillis ( ) ) ; } acceptConsumer ( consumer , p ) ; } // We've successfully finished batch this . runtimeMetricGauge . computeIfPresent ( METRIC_BATCH_COUNT , ( key , value ) -> ( ( long ) value ) + 1 ) ; } finally { resetBatchSpecificMetrics ( ) ; MDC . put ( LogConstants . RUNNER , \"\" ) ; MDC . put ( LogConstants . STAGE , \"\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute given consumer for each pipe rethrowing usual exceptions as RuntimeException . [CODESPLIT] public void forEach ( ThrowingConsumer < Pipe > consumer ) { try { MDC . put ( LogConstants . RUNNER , String . valueOf ( runnerId ) ) ; try { for ( Pipe p : pipes ) { MDC . put ( LogConstants . STAGE , p . getStage ( ) . getInfo ( ) . getInstanceName ( ) ) ; acceptConsumer ( consumer , p ) ; } } finally { MDC . put ( LogConstants . RUNNER , \"\" ) ; MDC . put ( LogConstants . STAGE , \"\" ) ; } } catch ( PipelineException | StageException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve OffsetCommitTrigger pipe . [CODESPLIT] public OffsetCommitTrigger getOffsetCommitTrigger ( ) { for ( Pipe pipe : pipes ) { Stage stage = pipe . getStage ( ) . getStage ( ) ; if ( stage instanceof Target && stage instanceof OffsetCommitTrigger ) { return ( OffsetCommitTrigger ) stage ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if at least one stage is configured with STOP_PIPELINE for OnRecordError policy . [CODESPLIT] public boolean onRecordErrorStopPipeline ( ) { for ( Pipe pipe : pipes ) { StageContext stageContext = pipe . getStage ( ) . getContext ( ) ; if ( stageContext . getOnErrorRecord ( ) == OnRecordError . STOP_PIPELINE ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accept given consumer and proper log context of any exception . [CODESPLIT] private void acceptConsumer ( ThrowingConsumer < Pipe > consumer , Pipe p ) throws PipelineRuntimeException , StageException { try { // Process pipe consumer . accept ( p ) ; } catch ( Throwable t ) { String instanceName = p . getStage ( ) . getInfo ( ) . getInstanceName ( ) ; LOG . error ( \"Failed executing stage '{}': {}\" , instanceName , t . toString ( ) , t ) ; Throwables . propagateIfInstanceOf ( t , PipelineRuntimeException . class ) ; Throwables . propagateIfInstanceOf ( t , StageException . class ) ; Throwables . propagate ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate and obtain the row id if the expression is present or return null . [CODESPLIT] private String getInsertIdForRecord ( ELVars elVars , Record record ) throws OnRecordErrorException { String recordId = null ; RecordEL . setRecordInContext ( elVars , record ) ; try { if ( ! ( StringUtils . isEmpty ( conf . rowIdExpression ) ) ) { recordId = rowIdELEval . eval ( elVars , conf . rowIdExpression , String . class ) ; if ( StringUtils . isEmpty ( recordId ) ) { throw new OnRecordErrorException ( record , Errors . BIGQUERY_15 ) ; } } } catch ( ELEvalException e ) { LOG . error ( \"Error evaluating Row Expression EL\" , e ) ; throw new OnRecordErrorException ( record , Errors . BIGQUERY_10 , e ) ; } return recordId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the root field to a java map object implicitly mapping each field to the column ( only non nested objects ) [CODESPLIT] private Map < String , Object > convertToRowObjectFromRecord ( Record record ) throws OnRecordErrorException { Field rootField = record . get ( ) ; Map < String , Object > rowObject = new LinkedHashMap <> ( ) ; if ( rootField . getType ( ) . isOneOf ( Field . Type . MAP , Field . Type . LIST_MAP ) ) { Map < String , Field > fieldMap = rootField . getValueAsMap ( ) ; for ( Map . Entry < String , Field > fieldEntry : fieldMap . entrySet ( ) ) { Field field = fieldEntry . getValue ( ) ; //Skip null value fields if ( field . getValue ( ) != null ) { try { rowObject . put ( fieldEntry . getKey ( ) , getValueFromField ( \"/\" + fieldEntry . getKey ( ) , field ) ) ; } catch ( IllegalArgumentException e ) { throw new OnRecordErrorException ( record , Errors . BIGQUERY_13 , e . getMessage ( ) ) ; } } } } else { throw new OnRecordErrorException ( record , Errors . BIGQUERY_16 ) ; } return rowObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the sdc Field to an object for row content [CODESPLIT] private Object getValueFromField ( String fieldPath , Field field ) { LOG . trace ( \"Visiting Field Path '{}' of type '{}'\" , fieldPath , field . getType ( ) ) ; switch ( field . getType ( ) ) { case LIST : //REPEATED List < Field > listField = field . getValueAsList ( ) ; //Convert the list to map with indices as key and Field as value (Map<Integer, Field>) Map < Integer , Field > fields = IntStream . range ( 0 , listField . size ( ) ) . boxed ( ) . collect ( Collectors . toMap ( Function . identity ( ) , listField :: get ) ) ; //filter map to remove fields with null value fields = fields . entrySet ( ) . stream ( ) . filter ( e -> e . getValue ( ) . getValue ( ) != null ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; //now use the map index to generate field path and generate object for big query write return fields . entrySet ( ) . stream ( ) . map ( e -> getValueFromField ( fieldPath + \"[\" + e . getKey ( ) + \"]\" , e . getValue ( ) ) ) . collect ( Collectors . toList ( ) ) ; case MAP : case LIST_MAP : //RECORD return field . getValueAsMap ( ) . entrySet ( ) . stream ( ) . filter ( me -> me . getValue ( ) . getValue ( ) != null ) . collect ( Collectors . toMap ( Map . Entry :: getKey , e -> getValueFromField ( fieldPath + \"/\" + e . getKey ( ) , e . getValue ( ) ) ) ) ; case DATE : return dateFormat . format ( field . getValueAsDate ( ) ) ; case TIME : return timeFormat . format ( field . getValueAsTime ( ) ) ; case DATETIME : return dateTimeFormat . format ( field . getValueAsDatetime ( ) ) ; case BYTE_ARRAY : return Base64 . getEncoder ( ) . encodeToString ( field . getValueAsByteArray ( ) ) ; case DECIMAL : case BYTE : case CHAR : case FILE_REF : throw new IllegalArgumentException ( Utils . format ( Errors . BIGQUERY_12 . getMessage ( ) , fieldPath , field . getType ( ) ) ) ; default : //Boolean -> Map to Boolean in big query //Float, Double -> Map to Float in big query //String -> maps to String in big query //Short, Integer, Long -> Map to integer in big query return field . getValue ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "port . [CODESPLIT] private void checkValidPorts ( ) { if ( ( conf . get ( HTTP_PORT_KEY , HTTP_PORT_DEFAULT ) == 0 && conf . get ( HTTPS_PORT_KEY , HTTPS_PORT_DEFAULT ) != - 1 ) || ( conf . get ( HTTPS_PORT_KEY , HTTPS_PORT_DEFAULT ) == 0 && conf . get ( HTTP_PORT_KEY , HTTP_PORT_DEFAULT ) != - 1 ) ) { throw new IllegalArgumentException ( \"Invalid port combination for http and https, If http port is set to 0 (random), then https should be \" + \"set to -1 or vice versa\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aggregates errors that occur during the processing of a batch . [CODESPLIT] private < T > Observable < T > handleError ( Record record , Errors error , Throwable ex , boolean passable ) { errors . put ( record , new ErrorRecord ( error , ex , passable ) ) ; return Observable . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aggregates errors that occur during the processing of a batch . [CODESPLIT] private < T > Observable < T > handleError ( Record record , Errors error , boolean passable ) { return handleError ( record , error , new RuntimeException ( ) , passable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes sub - document lookup values to the record [CODESPLIT] private Observable < Record > setFragmentInRecord ( Record record , DocumentFragment < Lookup > frag ) { if ( frag . content ( 0 ) == null ) { LOG . debug ( \"Sub-document path not found\" ) ; return handleError ( record , Errors . COUCHBASE_25 , true ) ; } for ( SubdocMappingConfig subdocMapping : config . subdocMappingConfigs ) { Object fragJson = frag . content ( subdocMapping . subdocPath ) ; if ( fragJson == null ) { return handleError ( record , Errors . COUCHBASE_25 , true ) ; } try { record . set ( subdocMapping . sdcField , jsonToField ( fragJson ) ) ; record . getHeader ( ) . setAttribute ( config . CAS_HEADER_ATTRIBUTE , String . valueOf ( frag . cas ( ) ) ) ; } catch ( IOException e ) { try { record . set ( subdocMapping . sdcField , jsonToField ( JsonObject . fromJson ( fragJson . toString ( ) ) . toMap ( ) ) ) ; record . getHeader ( ) . setAttribute ( config . CAS_HEADER_ATTRIBUTE , String . valueOf ( frag . cas ( ) ) ) ; } catch ( IOException ex ) { return handleError ( record , Errors . COUCHBASE_19 , ex , false ) ; } } } return Observable . just ( record ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes full document lookup values to the record [CODESPLIT] private Observable < Record > setDocumentInRecord ( Record record , JsonDocument doc ) { if ( doc . content ( ) == null ) { LOG . debug ( \"Document does not exist: {}\" , doc . id ( ) ) ; return handleError ( record , Errors . COUCHBASE_26 , true ) ; } try { record . set ( config . outputField , jsonToField ( doc . content ( ) . toMap ( ) ) ) ; record . getHeader ( ) . setAttribute ( config . CAS_HEADER_ATTRIBUTE , String . valueOf ( doc . cas ( ) ) ) ; return Observable . just ( record ) ; } catch ( IOException e ) { LOG . debug ( \"Unable to set KV lookup in record for: {}\" , doc . id ( ) ) ; return handleError ( record , Errors . COUCHBASE_19 , e , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes N1QL query result rows to the record [CODESPLIT] private Observable < Record > setN1QLRowInRecord ( Record record , AsyncN1qlQueryRow row ) { for ( N1QLMappingConfig n1qlMapping : config . n1qlMappingConfigs ) { if ( config . multipleValueOperation == MultipleValueType . FIRST && record . get ( n1qlMapping . sdcField ) != null ) { LOG . debug ( \"Only populating output field with first record. Skipping additional result.\" ) ; return Observable . empty ( ) ; } Object property = row . value ( ) . get ( n1qlMapping . property ) ; if ( property == null ) { LOG . debug ( \"Requested property not returned: {}\" , n1qlMapping . property ) ; return handleError ( record , Errors . COUCHBASE_27 , true ) ; } try { record . set ( n1qlMapping . sdcField , jsonToField ( property ) ) ; } catch ( IOException e ) { try { record . set ( n1qlMapping . sdcField , jsonToField ( JsonObject . fromJson ( property . toString ( ) ) . toMap ( ) ) ) ; } catch ( IOException ex ) { LOG . debug ( \"Unable to set N1QL property in record\" ) ; return handleError ( record , Errors . COUCHBASE_19 , ex , false ) ; } } } return Observable . just ( record ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take an numeric operation code and check if the number is valid operation code . The operation code must be numeric : 1 ( insert ) 2 ( update ) 3 ( delete ) etc [CODESPLIT] public static int convertToJDBCCode ( int op ) { if ( CRUD_MAP . containsKey ( op ) ) { return CRUD_MAP . get ( op ) ; } throw new UnsupportedOperationException ( Utils . format ( \"Operation code {} is not supported\" , op ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "as the record is just the metadata along with file ref . [CODESPLIT] private void handleWholeFileDataFormat ( S3ObjectSummary s3ObjectSummary , String recordId ) throws StageException { S3Object partialS3ObjectForMetadata ; //partialObject with fetchSize 1 byte. //This is mostly used for extracting metadata and such. partialS3ObjectForMetadata = AmazonS3Util . getObjectRange ( s3Client , s3ConfigBean . s3Config . bucket , s3ObjectSummary . getKey ( ) , 1 , s3ConfigBean . sseConfig . useCustomerSSEKey , s3ConfigBean . sseConfig . customerKey , s3ConfigBean . sseConfig . customerKeyMd5 ) ; S3FileRef . Builder s3FileRefBuilder = new S3FileRef . Builder ( ) . s3Client ( s3Client ) . s3ObjectSummary ( s3ObjectSummary ) . useSSE ( s3ConfigBean . sseConfig . useCustomerSSEKey ) . customerKey ( s3ConfigBean . sseConfig . customerKey ) . customerKeyMd5 ( s3ConfigBean . sseConfig . customerKeyMd5 ) . bufferSize ( ( int ) dataParser . suggestedWholeFileBufferSize ( ) ) . createMetrics ( true ) . totalSizeInBytes ( s3ObjectSummary . getSize ( ) ) . rateLimit ( dataParser . wholeFileRateLimit ( ) ) ; if ( dataParser . isWholeFileChecksumRequired ( ) ) { s3FileRefBuilder . verifyChecksum ( true ) . checksumAlgorithm ( HashingUtil . HashType . MD5 ) //128 bit hex encoded md5 checksum. . checksum ( partialS3ObjectForMetadata . getObjectMetadata ( ) . getETag ( ) ) ; } Map < String , Object > metadata = AmazonS3Util . getMetaData ( partialS3ObjectForMetadata ) ; metadata . put ( S3Constants . BUCKET , s3ObjectSummary . getBucketName ( ) ) ; metadata . put ( S3Constants . OBJECT_KEY , s3ObjectSummary . getKey ( ) ) ; metadata . put ( S3Constants . OWNER , s3ObjectSummary . getOwner ( ) ) ; metadata . put ( S3Constants . SIZE , s3ObjectSummary . getSize ( ) ) ; metadata . put ( HeaderAttributeConstants . FILE_NAME , s3ObjectSummary . getKey ( ) ) ; metadata . remove ( S3Constants . CONTENT_LENGTH ) ; parser = dataParser . getParser ( recordId , metadata , s3FileRefBuilder . build ( ) ) ; //Object is assigned so that setHeaders() function can use this to get metadata //information about the object object = partialS3ObjectForMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the gauge with needed information [CODESPLIT] private void initGaugeIfNeeded ( ) { gaugeMap . put ( S3Constants . THREAD_NAME , Thread . currentThread ( ) . getName ( ) ) ; gaugeMap . put ( S3Constants . STATUS , \"\" ) ; gaugeMap . put ( S3Constants . BUCKET , \"\" ) ; gaugeMap . put ( S3Constants . OBJECT_KEY , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if given gtid + seqNo pair is contained in this incomplete transactions . [CODESPLIT] public boolean incompleteTransactionsContain ( String gtid , long seqNo ) { Long s = incompleteTransactions . get ( gtid ) ; return s != null && s >= seqNo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a Supplier within the context of a specified ClassLoader . [CODESPLIT] public static < T > T withClassLoader ( ClassLoader classLoader , ExceptionSupplier < T > supplier ) { try { return withClassLoaderInternal ( classLoader , supplier ) ; } catch ( Exception e ) { Throwables . propagate ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a Supplier within the context of a specified ClassLoader . [CODESPLIT] public static < T , E1 extends Exception > T withClassLoader ( ClassLoader classLoader , Class < E1 > e1 , ExceptionSupplier < T > supplier ) throws E1 { try { return withClassLoaderInternal ( classLoader , supplier ) ; } catch ( Exception e ) { Throwables . propagateIfPossible ( e , e1 ) ; Throwables . propagate ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a Supplier within the context of a specified ClassLoader and in priviledged mode . [CODESPLIT] public static < T > T privilegedWithClassLoader ( ClassLoader classLoader , ExceptionSupplier < T > supplier ) { try { return AccessController . doPrivileged ( ( PrivilegedExceptionAction < T > ) ( ) -> withClassLoaderInternal ( classLoader , supplier ) ) ; } catch ( PrivilegedActionException e ) { Throwables . propagate ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a Supplier within the context of a specified ClassLoader and in priviledged mode . [CODESPLIT] public static < T , E1 extends Exception > T privilegedWithClassLoader ( ClassLoader classLoader , Class < E1 > e1 , ExceptionSupplier < T > supplier ) throws E1 { try { return AccessController . doPrivileged ( ( PrivilegedExceptionAction < T > ) ( ) -> withClassLoaderInternal ( classLoader , supplier ) ) ; } catch ( PrivilegedActionException e ) { Throwables . propagateIfPossible ( e . getCause ( ) , e1 ) ; Throwables . propagate ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal version of the wrapping function that will simply propagate all exceptions up . [CODESPLIT] private static < T > T withClassLoaderInternal ( ClassLoader classLoader , ExceptionSupplier < T > supplier ) throws Exception { ClassLoader previousClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; return supplier . get ( ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( previousClassLoader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HeaderImpl setter methods [CODESPLIT] public void setStageCreator ( String stateCreator ) { Preconditions . checkNotNull ( stateCreator , \"stateCreator cannot be null\" ) ; map . put ( STAGE_CREATOR_INSTANCE_ATTR , stateCreator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be removed [CODESPLIT] public Map < String , Object > getUserAttributes ( ) { return map . entrySet ( ) . stream ( ) . filter ( map -> ! map . getKey ( ) . startsWith ( RESERVED_PREFIX ) ) . collect ( Collectors . toMap ( map -> map . getKey ( ) , map -> map . getValue ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be removed [CODESPLIT] public Map < String , Object > setUserAttributes ( Map < String , Object > newAttributes ) { // ImmutableMap can't have null values and our map could have, so use unmodifiable map Map < String , Object > old = Collections . unmodifiableMap ( getUserAttributes ( ) ) ; //Set current map to just the Reserved System Attributes map = getSystemAttributes ( ) ; // Add and validate each of the new user attributes newAttributes . forEach ( ( k , v ) -> setAttribute ( k , v . toString ( ) ) ) ; return old ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs in . If Kerberos is enabled it logs in against the KDC otherwise is a NOP . [CODESPLIT] public synchronized void login ( ) { if ( subject != null ) { throw new IllegalStateException ( Utils . format ( \"Service already login, Principal '{}'\" , subject . getPrincipals ( ) ) ) ; } if ( securityConfiguration . isKerberosEnabled ( ) ) { try { loginContext = createLoginContext ( ) ; subject = loginContext . getSubject ( ) ; } catch ( Exception ex ) { throw new RuntimeException ( Utils . format ( \"Could not get Kerberos credentials: {}\" , ex . toString ( ) ) , ex ) ; } if ( renewalThread == null ) { renewalThread = new Thread ( ) { @ Override public void run ( ) { LOG . debug ( \"Starting renewal thread\" ) ; if ( ! SecurityContext . this . sleep ( THIRTY_SECONDS_MS ) ) { LOG . info ( \"Interrupted, exiting renewal thread\" ) ; return ; } while ( true ) { LOG . trace ( \"Renewal check starts\" ) ; try { KerberosTicket lastExpiringTGT = getNewestTGT ( ) ; if ( lastExpiringTGT == null ) { LOG . warn ( \"Could not obtain kerberos ticket, it may have expired already or it was logged out, will wait\" + \"30 secs to attempt a relogin\" ) ; LOG . trace ( \"Ticket not found, sleeping 30 secs and trying to login\" ) ; if ( ! SecurityContext . this . sleep ( THIRTY_SECONDS_MS ) ) { LOG . info ( \"Interrupted, exiting renewal thread\" ) ; return ; } } else { long renewalTimeMs = calculateRenewalTime ( lastExpiringTGT ) - THIRTY_SECONDS_MS ; LOG . trace ( \"Ticket found time to renewal '{}ms', sleeping that time\" , renewalTimeMs ) ; if ( renewalTimeMs > 0 ) { if ( ! SecurityContext . this . sleep ( renewalTimeMs ) ) { LOG . info ( \"Interrupted, exiting renewal thread\" ) ; return ; } } } LOG . debug ( \"Triggering relogin\" ) ; Set < KerberosTicket > oldTickets = getSubject ( ) . getPrivateCredentials ( KerberosTicket . class ) ; relogin ( 3 ) ; // Remove all old private credentials, since we only need the new one we just added getSubject ( ) . getPrivateCredentials ( ) . removeAll ( oldTickets ) ; } catch ( Exception exception ) { LOG . error ( \"Stopping renewal thread because of exception: \" + exception , exception ) ; return ; } catch ( Throwable throwable ) { LOG . error ( \"Error in renewal thread: \" + throwable , throwable ) ; return ; } } } } ; List < String > principals = new ArrayList <> ( ) ; for ( Principal p : subject . getPrincipals ( ) ) { principals . add ( p . getName ( ) ) ; } renewalThread . setName ( \"Kerberos-Renewal-Thread-\" + Joiner . on ( \",\" ) . join ( principals ) ) ; renewalThread . setContextClassLoader ( Thread . currentThread ( ) . getContextClassLoader ( ) ) ; renewalThread . setDaemon ( true ) ; renewalThread . start ( ) ; } } else { subject = new Subject ( ) ; } LOG . debug ( \"Login. Kerberos enabled '{}', Principal '{}'\" , securityConfiguration . isKerberosEnabled ( ) , subject . getPrincipals ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs out . If Keberos is enabled it logs out from the KDC otherwise is a NOP . [CODESPLIT] public synchronized void logout ( ) { if ( subject != null ) { LOG . debug ( \"Logout. Kerberos enabled '{}', Principal '{}'\" , securityConfiguration . isKerberosEnabled ( ) , subject . getPrincipals ( ) ) ; if ( loginContext != null ) { try { loginContext . logout ( ) ; } catch ( LoginException ex ) { LOG . warn ( \"Error while doing logout from Kerberos: {}\" , ex . toString ( ) , ex ) ; } finally { loginContext = null ; } } subject = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method should be called only once and before any stages are loaded . [CODESPLIT] private void setExceptions ( Configuration configuration ) { this . exceptions . clear ( ) ; this . stageLibExceptions . clear ( ) ; // Load general exceptions for ( String path : configuration . get ( PROPERTY_EXCEPTIONS , \"\" ) . split ( \",\" ) ) { this . exceptions . add ( replaceVariables ( path ) ) ; } // Load Stage library specific exceptions Configuration stageSpecific = configuration . getSubSetConfiguration ( PROPERTY_STAGE_EXCEPTIONS , true ) ; for ( Map . Entry < String , String > entry : stageSpecific . getValues ( ) . entrySet ( ) ) { Set < String > stageExceptions = new HashSet <> ( ) ; for ( String path : entry . getValue ( ) . split ( \",\" ) ) { stageExceptions . add ( replaceVariables ( path ) ) ; } this . stageLibExceptions . put ( entry . getKey ( ) , stageExceptions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace variables to internal SDC directories so that users don t have to be entering FQDN . [CODESPLIT] private String replaceVariables ( String path ) { return path . replace ( \"$SDC_DATA\" , dataDir ) . replace ( \"$SDC_CONF\" , configDir ) . replace ( \"$SDC_RESOURCES\" , resourcesDir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make sure that the active code have proper rights to access the file inside protected directory . [CODESPLIT] private void ensureProperPermissions ( String path ) { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; // 1) Container can access anything if ( cl instanceof ContainerClassLoader ) { return ; } // 2. Some files are whitelisted globally for all stage libraries if ( exceptions . contains ( path ) ) { return ; } // 3. Some stage libraries have some files whitelisted globally if ( cl instanceof SDCClassLoader ) { String libraryName = ( ( SDCClassLoader ) cl ) . getName ( ) ; if ( stageLibExceptions . containsKey ( libraryName ) && stageLibExceptions . get ( libraryName ) . contains ( path ) ) { return ; } } // No whitelist, no fun, go away throw new SecurityException ( Utils . format ( \"Classloader {} is not allowed access to Data Collector internal directories ({}).\" , cl . toString ( ) , path ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate Hive Type Info Representation inside the Metadata Record . [CODESPLIT] public Field generateJdbcTypeInfoFieldForMetadataRecord ( JdbcTypeInfo jdbcTypeInfo ) { Map < String , Field > fields = new HashMap <> ( ) ; fields . put ( TYPE , Field . create ( jdbcTypeInfo . getJdbcType ( ) . name ( ) ) ) ; fields . put ( EXTRA_INFO , generateExtraInfoFieldForMetadataRecord ( jdbcTypeInfo ) ) ; return Field . create ( fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate { @link JdbcTypeInfo } from the Metadata Record <br > . ( Reverse of { @link #generateJdbcTypeInfoFieldForMetadataRecord ( JdbcTypeInfo ) } ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public JdbcTypeInfo generateJdbcTypeInfoFromMetadataField ( Field jdbcTypeInfoField , JdbcSchemaWriter schemaWriter ) throws StageException { if ( jdbcTypeInfoField . getType ( ) == Field . Type . MAP ) { Map < String , Field > fields = ( Map < String , Field > ) jdbcTypeInfoField . getValue ( ) ; if ( ! fields . containsKey ( TYPE ) || ! fields . containsKey ( EXTRA_INFO ) ) { throw new StageException ( JdbcErrors . JDBC_308 , TYPE_INFO ) ; } JdbcType jdbcType = JdbcType . getJdbcTypeFromString ( fields . get ( TYPE ) . getValueAsString ( ) ) ; return generateJdbcTypeInfoFromMetadataField ( jdbcType , fields . get ( EXTRA_INFO ) , schemaWriter ) ; } else { throw new StageException ( JdbcErrors . JDBC_308 , TYPE_INFO ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate Column Definition for create table / add columns [CODESPLIT] public String generateColumnTypeDefinition ( JdbcTypeInfo jdbcTypeInfo , String columnName ) { return String . format ( COLUMN_TYPE , columnName , jdbcTypeInfo . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtaining a reference on the dummy source which is used to feed a pipeline<br / > Direction : Stage - > Container [CODESPLIT] public static /*PipelineStartResult*/ Object startPipeline ( Runnable postBatchRunnable ) throws Exception { BootstrapCluster . initialize ( ) ; ClassLoader originalClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( containerCL ) ; Class embeddedPipelineFactoryClz = Class . forName ( \"com.streamsets.datacollector.EmbeddedDataCollectorFactory\" , true , containerCL ) ; Method createPipelineMethod = embeddedPipelineFactoryClz . getMethod ( \"startPipeline\" , Runnable . class ) ; return createPipelineMethod . invoke ( null , postBatchRunnable ) ; } catch ( Exception ex ) { String msg = \"Error trying to create pipeline: \" + ex ; throw new IllegalStateException ( msg , ex ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( originalClassLoader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bootstrapping the Driver which starts a EMR job on cluster [CODESPLIT] public static void main ( String [ ] args ) throws Exception { EmrBinding binding = null ; try { binding = new EmrBinding ( args ) ; binding . init ( ) ; binding . awaitTermination ( ) ; // killed by ClusterProviderImpl before returning } catch ( Exception ex ) { String msg = \"Error trying to invoke BootstrapEmrBatch.main: \" + ex ; throw new IllegalStateException ( msg , ex ) ; } finally { try { if ( binding != null ) { binding . close ( ) ; } } catch ( Exception ex ) { LOG . warn ( \"Error on binding close: \" + ex , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns directory path for given record and date . [CODESPLIT] String getDirPath ( Date date , Record record ) throws StageException { if ( dirPathTemplateInHeader ) { // We're not validating if the header exists as that job is already done return record . getHeader ( ) . getAttribute ( HdfsTarget . TARGET_DIRECTORY_HEADER ) ; } return pathResolver . resolvePath ( date , record ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method should be called every time we finish writing into a file and consider it done . [CODESPLIT] Path renameToFinalName ( FileSystem fs , Path tempPath ) throws IOException , StageException { return fsHelper . renameAndGetPath ( fs , tempPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produce events that were cached during the batch processing . [CODESPLIT] public void issueCachedEvents ( ) throws IOException { Path closedPath ; while ( ( closedPath = closedPaths . poll ( ) ) != null ) { produceCloseFileEvent ( fs , closedPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rename all _tmp_ files under directory path ( dirPathTemplate ) return the number of _tmp_ files [CODESPLIT] public int handleAlreadyExistingFiles ( ) throws StageException , IOException { int result = 0 ; String globPath = dirPathTemplate ; final String staticExpReg = \"\\\\$\\\\{(sdc:|pipeline:|runtime:)[a-zA-Z0-9\\\\(\\\\)]*\\\\}\" ; Pattern pattern = Pattern . compile ( staticExpReg ) ; Matcher matcher = pattern . matcher ( globPath ) ; ELEval eval = context . createELEval ( \"dirPathTemplate\" ) ; ELVars vars = context . createELVars ( ) ; while ( matcher . find ( ) ) { String expressionString = eval . eval ( vars , matcher . group ( ) , String . class ) ; globPath = globPath . replace ( matcher . group ( ) , expressionString ) ; } final String expReg = \"\\\\$\\\\{[^}]*\\\\}\" ; pattern = Pattern . compile ( expReg ) ; matcher = pattern . matcher ( globPath ) ; while ( matcher . find ( ) ) { globPath = globPath . replace ( matcher . group ( ) , \"*\" ) ; } globPath = globPath . replaceAll ( \"\\\\*+\" , \"*\" ) ; globPath = globPath + \"/\" + TMP_FILE_PREFIX + uniquePrefix + \"*\" ; LOG . info ( \"Created the following glob path for file recovery: {}\" , globPath ) ; FileStatus [ ] fileStatuses = fs . globStatus ( new Path ( globPath ) ) ; for ( FileStatus fileStatus : fileStatuses ) { fsHelper . handleAlreadyExistingFile ( fs , fileStatus . getPath ( ) ) ; result ++ ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method must always be called after the closeLock () method on the writer has been called . [CODESPLIT] public Path commitWriter ( RecordWriter writer ) throws IOException , StageException { Path path = null ; if ( ( ! writer . isClosed ( ) || writer . isIdleClosed ( ) ) && ! writer . isRenamed ( ) ) { // Unset the interrupt flag before close(). InterruptedIOException makes close() fail // resulting that the tmp file never gets renamed when stopping the pipeline. boolean interrupted = Thread . interrupted ( ) ; try { // Since this method is always called from exactly one thread, and // we checked to make sure that it was not closed or it was idle closed, this method either closes // the file or pushes us into the catch block. writer . close ( ) ; } catch ( IdleClosedException e ) { LOG . info ( \"Writer for {} was idle closed, renaming..\" , writer . getPath ( ) ) ; } LOG . debug ( \"Path[{}] - Committing Writer\" , writer . getPath ( ) ) ; path = renameToFinalName ( fs , writer . getPath ( ) ) ; writer . setRenamed ( true ) ; LOG . debug ( \"Path[{}] - Committed Writer to '{}'\" , writer . getPath ( ) , path ) ; // Reset the interrupt flag back. if ( interrupted ) { Thread . currentThread ( ) . interrupt ( ) ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if this record should be written into a new file regardless whether we have a file for the record currently opened or not . [CODESPLIT] public boolean shouldRoll ( RecordWriter writer , Record record ) { if ( rollIfHeader && record . getHeader ( ) . getAttribute ( rollHeaderName ) != null ) { LOG . debug ( \"Path[{}] - will be rolled because of roll attribute '{}' set to '{}' in the record : '{}'\" , writer . getPath ( ) , rollHeaderName , record . getHeader ( ) . getAttribute ( rollHeaderName ) , record . getHeader ( ) . getSourceId ( ) ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * When we start with a file ( empty or not ) the file offset is zero . If the file is a rolled file the file will be EOF immediately triggering a close of the reader and setting the offset to Long . MAX_VALUE ( this happens in the MultiDirectoryReader class ) . This is the signal that in the next read a directory scan should be triggered to get the next rolled file or the live file if we were scanning the last rolled file . If the file you are starting is the live file we don t get an EOF as we expect data to be appended . We just return null chunks while there is no data . If the file is rolled we ll detect that and then do what is described in the previous paragraph . [CODESPLIT] @ Override public String produce ( String lastSourceOffset , int maxBatchSize , BatchMaker batchMaker ) throws StageException { int recordCounter = 0 ; long startTime = System . currentTimeMillis ( ) ; maxBatchSize = Math . min ( conf . batchSize , maxBatchSize ) ; // deserializing offsets of all directories Map < String , String > offsetMap = deserializeOffsetMap ( lastSourceOffset ) ; boolean offsetSet = false ; while ( ! offsetSet ) { try { multiDirReader . setOffsets ( offsetMap ) ; offsetSet = true ; } catch ( IOException ex ) { LOG . warn ( \"Error while creating reading previous offset: {}\" , ex . toString ( ) , ex ) ; multiDirReader . purge ( ) ; } } while ( recordCounter < maxBatchSize && ! isTimeout ( startTime ) ) { LiveFileChunk chunk = multiDirReader . next ( getRemainingWaitTime ( startTime ) ) ; if ( chunk != null ) { String tag = chunk . getTag ( ) ; tag = ( tag != null && tag . isEmpty ( ) ) ? null : tag ; String liveFileStr = chunk . getFile ( ) . serialize ( ) ; List < FileLine > lines = chunk . getLines ( ) ; int truncatedLine = chunk . isTruncated ( ) ? lines . size ( ) - 1 : - 1 ; for ( int i = 0 ; i < lines . size ( ) ; i ++ ) { FileLine line = lines . get ( i ) ; String sourceId = liveFileStr + \"::\" + line . getFileOffset ( ) ; try ( DataParser parser = parserFactory . getParser ( sourceId , line . getText ( ) ) ) { if ( i == truncatedLine ) { //set truncated parser . setTruncated ( ) ; } Record record = parser . parse ( ) ; if ( record != null ) { if ( tag != null ) { record . getHeader ( ) . setAttribute ( \"tag\" , tag ) ; } record . getHeader ( ) . setAttribute ( HeaderAttributeConstants . FILE , chunk . getFile ( ) . getPath ( ) . toString ( ) ) ; record . getHeader ( ) . setAttribute ( HeaderAttributeConstants . FILE_NAME , chunk . getFile ( ) . getPath ( ) . getFileName ( ) . toString ( ) ) ; record . getHeader ( ) . setAttribute ( HeaderAttributeConstants . OFFSET , String . valueOf ( line . getFileOffset ( ) ) ) ; record . getHeader ( ) . setAttribute ( HeaderAttributeConstants . LAST_MODIFIED_TIME , String . valueOf ( Files . getLastModifiedTime ( chunk . getFile ( ) . getPath ( ) ) . toMillis ( ) ) ) ; batchMaker . addRecord ( record , outputLane ) ; recordCounter ++ ; } } catch ( IOException | DataParserException ex ) { errorRecordHandler . onError ( Errors . TAIL_12 , sourceId , ex . toString ( ) , ex ) ; } } } } boolean metadataGenerationFailure = false ; Date now = new Date ( startTime ) ; for ( FileEvent event : multiDirReader . getEvents ( ) ) { try { LiveFile file = event . getFile ( ) . refresh ( ) ; Record metadataRecord = getContext ( ) . createRecord ( \"\" ) ; Map < String , Field > map = new HashMap <> ( ) ; map . put ( \"fileName\" , Field . create ( file . getPath ( ) . toString ( ) ) ) ; map . put ( \"inode\" , Field . create ( file . getINode ( ) ) ) ; map . put ( \"time\" , Field . createDate ( now ) ) ; map . put ( \"event\" , Field . create ( ( event . getAction ( ) . name ( ) ) ) ) ; metadataRecord . set ( Field . create ( map ) ) ; batchMaker . addRecord ( metadataRecord , metadataLane ) ; // We're also sending the same information on event lane String eventRecordSourceId = Utils . format ( \"event:{}:{}:{}\" , event . getAction ( ) . name ( ) , 1 , file . getPath ( ) . toString ( ) ) ; EventRecord eventRecord = getContext ( ) . createEventRecord ( event . getAction ( ) . name ( ) , 1 , eventRecordSourceId ) ; eventRecord . set ( Field . create ( map ) ) ; getContext ( ) . toEvent ( eventRecord ) ; } catch ( IOException ex ) { LOG . warn ( \"Error while creating metadata records: {}\" , ex . toString ( ) , ex ) ; metadataGenerationFailure = true ; } } if ( metadataGenerationFailure ) { multiDirReader . purge ( ) ; } boolean offsetExtracted = false ; while ( ! offsetExtracted ) { try { offsetMap = multiDirReader . getOffsets ( ) ; offsetExtracted = true ; } catch ( IOException ex ) { LOG . warn ( \"Error while creating creating new offset: {}\" , ex . toString ( ) , ex ) ; multiDirReader . purge ( ) ; } } //Calculate Offset lag Metric. calculateOffsetLagMetric ( offsetMap ) ; //Calculate Pending Files Metric calculatePendingFilesMetric ( ) ; // serializing offsets of all directories return serializeOffsetMap ( offsetMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the path separator to use for pattern parsing . <p > Default is / as in Ant . [CODESPLIT] public void setPathSeparator ( String pathSeparator ) { this . pathSeparator = ( pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR ) ; this . pathSeparatorPatternCache = new PathSeparatorPatternCache ( this . pathSeparator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tokenize the given path pattern into parts based on this matcher s settings . <p > Performs caching based on { [CODESPLIT] protected String [ ] tokenizePattern ( String pattern ) { String [ ] tokenized = null ; Boolean cachePatterns = this . cachePatterns ; if ( cachePatterns == null || cachePatterns . booleanValue ( ) ) { tokenized = this . tokenizedPatternCache . get ( pattern ) ; } if ( tokenized == null ) { tokenized = tokenizePath ( pattern ) ; if ( cachePatterns == null && this . tokenizedPatternCache . size ( ) >= CACHE_TURNOFF_THRESHOLD ) { // Try to adapt to the runtime situation that we're encountering: // There are obviously too many different patterns coming in here... // So let's turn off the cache since the patterns are unlikely to be reoccurring. deactivatePatternCache ( ) ; return tokenized ; } if ( cachePatterns == null || cachePatterns . booleanValue ( ) ) { this . tokenizedPatternCache . put ( pattern , tokenized ) ; } } return tokenized ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the given { [CODESPLIT] private static String [ ] toStringArray ( Collection < String > collection ) { if ( collection == null ) { return null ; } return collection . toArray ( new String [ collection . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test whether or not a string matches against a pattern . [CODESPLIT] private boolean matchStrings ( String pattern , String str , Map < String , String > uriTemplateVariables ) { return getStringMatcher ( pattern ) . matchStrings ( str , uriTemplateVariables ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the file offsets to use for the next read . To work correctly the last return offsets should be used or an empty <code > Map< / code > if there is none . <p / > If a reader is already live the corresponding set offset is ignored as we cache all the contextual information of live readers . [CODESPLIT] public void setOffsets ( Map < String , String > offsets ) throws IOException { Utils . checkState ( open , \"Not open\" ) ; fileContextProvider . setOffsets ( offsets ) ; // we reset the events on every setOffsets(). events . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current file offsets . The returned offsets should be set before the next read . [CODESPLIT] public Map < String , String > getOffsets ( ) throws IOException { Utils . checkState ( open , \"Not open\" ) ; return fileContextProvider . getOffsets ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remaining time till timeout return zero if already in timeout [CODESPLIT] private long getRemainingWaitTime ( long startTime , long maxWaitTimeMillis ) { long remaining = maxWaitTimeMillis - ( System . currentTimeMillis ( ) - startTime ) ; return ( remaining > 0 ) ? remaining : 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the next { @link LiveFileChunk } from the directories waiting the specified time for one . [CODESPLIT] public LiveFileChunk next ( long waitMillis ) { Utils . checkState ( open , \"Not open\" ) ; waitMillis = ( waitMillis > 0 ) ? waitMillis : 0 ; long startTime = System . currentTimeMillis ( ) ; LiveFileChunk chunk = null ; boolean exit = false ; fileContextProvider . startNewLoop ( ) ; while ( ! exit ) { if ( ! fileContextProvider . didFullLoop ( ) ) { FileContext fileContext = fileContextProvider . next ( ) ; try { LiveFileReader reader = fileContext . getReader ( ) ; if ( reader != null ) { if ( reader . hasNext ( ) ) { chunk = reader . next ( 0 ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"next(): directory '{}', file '{}', offset '{}' got data '{}'\" , fileContext . getMultiFileInfo ( ) . getFileFullPath ( ) , reader . getLiveFile ( ) , reader . getOffset ( ) , chunk != null ) ; } } else { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"next(): directory '{}', file '{}', offset '{}' EOF reached\" , fileContext . getMultiFileInfo ( ) . getFileFullPath ( ) , reader . getLiveFile ( ) , reader . getOffset ( ) ) ; } } fileContext . releaseReader ( false ) ; } else { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"next(): directory '{}', no reader available\" , fileContext . getMultiFileInfo ( ) . getFileFullPath ( ) ) ; } } } catch ( IOException ex ) { LOG . error ( \"Error while reading file: {}\" , ex . toString ( ) , ex ) ; try { fileContext . releaseReader ( true ) ; } catch ( IOException ex1 ) { LOG . warn ( \"Error while releasing reader in error: {}\" , ex1 . toString ( ) , ex1 ) ; } } } // check exit conditions (we have a chunk, or we timed-out waitMillis) exit = chunk != null ; if ( ! exit ) { // if we looped thru all dir contexts in this call we yield CPU if ( fileContextProvider . didFullLoop ( ) ) { exit = isTimeout ( startTime , waitMillis ) ; if ( ! exit && LOG . isTraceEnabled ( ) ) { LOG . trace ( \"next(): looped through all directories, yielding CPU\" ) ; } exit = exit || ! ThreadUtil . sleep ( Math . min ( getRemainingWaitTime ( startTime , waitMillis ) , MAX_YIELD_TIME ) ) ; fileContextProvider . startNewLoop ( ) ; } } } return chunk ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines the offset lag for each active file being read . [CODESPLIT] public Map < String , Long > getOffsetsLag ( Map < String , String > offsetMap ) throws IOException { return fileContextProvider . getOffsetsLag ( offsetMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and initialize new delegate . [CODESPLIT] public < R > R createAndInitialize ( StageLibraryTask stageLib , Configuration configuration , String stageLibraryName , Class < R > exportedInterface ) { StageLibraryDelegate instance = create ( stageLib , stageLibraryName , exportedInterface ) ; if ( instance == null ) { return null ; } // Create & set context StageLibraryDelegateContext context = new StageLibraryDelegateContext ( configuration ) ; instance . setContext ( context ) ; return ( R ) new StageLibraryDelegateRuntime ( instance . getClass ( ) . getClassLoader ( ) , instance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new instance of the delegator from given stage library . [CODESPLIT] public StageLibraryDelegate create ( StageLibraryTask stageLib , String stageLibraryName , Class exportedInterface ) { StageLibraryDelegateDefinitition def = stageLib . getStageLibraryDelegateDefinition ( stageLibraryName , exportedInterface ) ; if ( def == null ) { return null ; } return createInstance ( def ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create actual instance of delegator . [CODESPLIT] private StageLibraryDelegate createInstance ( StageLibraryDelegateDefinitition def ) { StageLibraryDelegate instance = null ; ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( def . getClassLoader ( ) ) ; instance = def . getKlass ( ) . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException ex ) { LOG . error ( \"Can't create instance of delegator: \" + ex . toString ( ) , ex ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; } return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private static final Configuration jaasConfig = new org . apache . solr . client . solrj . impl . Krb5HttpClientConfigurer . SolrJaasConfiguration () ; [CODESPLIT] public void configure ( DefaultHttpClient httpClient , SolrParams config ) { super . configure ( httpClient , config ) ; // Begin change for SDC-2962 // Instead of checking existence of JAAS file, do the following if solr kerberos is enabled //if (System.getProperty(LOGIN_CONFIG_PROP) != null) { //String configValue = System.getProperty(LOGIN_CONFIG_PROP); //if (configValue != null) { // logger.info(\"Setting up SPNego auth with config: \" + configValue); final String useSubjectCredsProp = \"javax.security.auth.useSubjectCredsOnly\" ; String useSubjectCredsVal = System . getProperty ( useSubjectCredsProp ) ; // \"javax.security.auth.useSubjectCredsOnly\" should be false so that the underlying // authentication mechanism can load the credentials from the JAAS configuration. if ( useSubjectCredsVal == null ) { System . setProperty ( useSubjectCredsProp , \"false\" ) ; } else if ( ! useSubjectCredsVal . toLowerCase ( Locale . ROOT ) . equals ( \"false\" ) ) { // Don't overwrite the prop value if it's already been written to something else, // but log because it is likely the Credentials won't be loaded correctly. logger . warn ( \"System Property: \" + useSubjectCredsProp + \" set to: \" + useSubjectCredsVal + \" not false.  SPNego authentication may not be successful.\" ) ; } // Change for SDC-2962 //javax.security.auth.login.Configuration.setConfiguration(jaasConfig); //Enable only SPNEGO authentication scheme. AuthSchemeRegistry registry = new AuthSchemeRegistry ( ) ; registry . register ( AuthSchemes . SPNEGO , new SPNegoSchemeFactory ( true , false ) ) ; httpClient . setAuthSchemes ( registry ) ; // Get the credentials from the JAAS configuration rather than here Credentials useJaasCreds = new Credentials ( ) { public String getPassword ( ) { return null ; } public Principal getUserPrincipal ( ) { return null ; } } ; SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory ( ) ; httpClient . getCookieSpecs ( ) . register ( cookieFactory . POLICY_NAME , cookieFactory ) ; httpClient . getParams ( ) . setParameter ( ClientPNames . COOKIE_POLICY , cookieFactory . POLICY_NAME ) ; httpClient . getCredentialsProvider ( ) . setCredentials ( AuthScope . ANY , useJaasCreds ) ; httpClient . addRequestInterceptor ( bufferedEntityInterceptor ) ; //} else { //httpClient.getCredentialsProvider().clear(); //} // } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Scheduler is not used since a dedicated thread will be running to update the token . Even if the thycotic server is not being used the thread will hit for every refresh interval to get a new access token . So instead <tt > volatile< / tt > variables are used to store the token . So only when the token expires thycotic server will be called to fetch the new token . < / p > <p > There are 2 expire checks to make sure that not more than one thread updates the token in case of expiration [CODESPLIT] public String getAccessToken ( ) { if ( System . currentTimeMillis ( ) > getExpireTime ( ) ) { try { synchronized ( this ) { if ( System . currentTimeMillis ( ) > getExpireTime ( ) ) { accessToken = fetchAccessToken ( ) ; if ( accessToken != null && ! accessToken . isEmpty ( ) ) { expires = ( System . currentTimeMillis ( ) + expires ) ; } } } } catch ( Exception e ) { LOG . debug ( \"Error in fetching the access token: {} \" , e ) ; } } return accessToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get metric value for given rule evaluation . [CODESPLIT] public static Object getMetricValue ( MetricRegistry metrics , String metricId , MetricType metricType , MetricElement metricElement ) throws ObserverException { // We moved the logic of CURRENT_BATCH_AGE and TIME_IN_CURRENT_STAGE due to multi-threaded framework if ( metricElement . isOneOf ( MetricElement . CURRENT_BATCH_AGE , MetricElement . TIME_IN_CURRENT_STAGE ) ) { switch ( metricElement ) { case CURRENT_BATCH_AGE : return getTimeFromRunner ( metrics , PipeRunner . METRIC_BATCH_START_TIME ) ; case TIME_IN_CURRENT_STAGE : return getTimeFromRunner ( metrics , PipeRunner . METRIC_STAGE_START_TIME ) ; default : throw new IllegalStateException ( Utils . format ( \"Unknown metric type '{}'\" , metricType ) ) ; } } // Default path Metric metric = getMetric ( metrics , metricId , metricType ) ; if ( metric != null ) { return getMetricValue ( metricElement , metricType , metric ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return calculated metric - from all the runners that are available for given pipeline return the biggest difference between given metric and System . currentTimeMillis () . The semantic is that the runner metric stores start time of certain events ( batch start time stage start time ) and we need to find out what is the longer running time for one of those metrics . [CODESPLIT] private static long getTimeFromRunner ( MetricRegistry metrics , String runnerMetricName ) { // First get number of total runners from the runtime gauge RuntimeStats runtimeStats = ( RuntimeStats ) ( ( Gauge ) getMetric ( metrics , \"RuntimeStatsGauge.gauge\" , MetricType . GAUGE ) ) . getValue ( ) ; long totalRunners = runtimeStats . getTotalRunners ( ) ; long currentTime = System . currentTimeMillis ( ) ; long maxTime = 0 ; // Then iterate over all runners and find the biggest time difference for ( int runnerId = 0 ; runnerId < totalRunners ; runnerId ++ ) { Map < String , Object > runnerMetrics = ( Map < String , Object > ) ( ( Gauge ) getMetric ( metrics , \"runner.\" + runnerId , MetricType . GAUGE ) ) . getValue ( ) ; // Get current value long value = ( long ) runnerMetrics . getOrDefault ( runnerMetricName , 0L ) ; // Zero means that the runner is not in use at all and thus calculating running time makes no sense if ( value == 0 ) { continue ; } long runTime = currentTime - value ; if ( maxTime < runTime ) { maxTime = runTime ; } } return maxTime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts as a standalone file server and waits for Enter . [CODESPLIT] public static void main ( String [ ] args ) { // Defaults int port = 8080 ; String host = null ; // bind to all interfaces by default List < File > rootDirs = new ArrayList < File > ( ) ; boolean quiet = false ; String cors = null ; Map < String , String > options = new HashMap < String , String > ( ) ; // Parse command-line, with short and long versions of the options. for ( int i = 0 ; i < args . length ; ++ i ) { if ( \"-h\" . equalsIgnoreCase ( args [ i ] ) || \"--host\" . equalsIgnoreCase ( args [ i ] ) ) { host = args [ i + 1 ] ; } else if ( \"-p\" . equalsIgnoreCase ( args [ i ] ) || \"--port\" . equalsIgnoreCase ( args [ i ] ) ) { port = Integer . parseInt ( args [ i + 1 ] ) ; } else if ( \"-q\" . equalsIgnoreCase ( args [ i ] ) || \"--quiet\" . equalsIgnoreCase ( args [ i ] ) ) { quiet = true ; } else if ( \"-d\" . equalsIgnoreCase ( args [ i ] ) || \"--dir\" . equalsIgnoreCase ( args [ i ] ) ) { rootDirs . add ( new File ( args [ i + 1 ] ) . getAbsoluteFile ( ) ) ; } else if ( args [ i ] . startsWith ( \"--cors\" ) ) { cors = \"*\" ; int equalIdx = args [ i ] . indexOf ( ' ' ) ; if ( equalIdx > 0 ) { cors = args [ i ] . substring ( equalIdx + 1 ) ; } } else if ( \"--licence\" . equalsIgnoreCase ( args [ i ] ) ) { System . out . println ( SimpleWebServer . LICENCE + \"\\n\" ) ; } else if ( args [ i ] . startsWith ( \"-X:\" ) ) { int dot = args [ i ] . indexOf ( ' ' ) ; if ( dot > 0 ) { String name = args [ i ] . substring ( 0 , dot ) ; String value = args [ i ] . substring ( dot + 1 , args [ i ] . length ( ) ) ; options . put ( name , value ) ; } } } if ( rootDirs . isEmpty ( ) ) { rootDirs . add ( new File ( \".\" ) . getAbsoluteFile ( ) ) ; } options . put ( \"host\" , host ) ; options . put ( \"port\" , \"\" + port ) ; options . put ( \"quiet\" , String . valueOf ( quiet ) ) ; StringBuilder sb = new StringBuilder ( ) ; for ( File dir : rootDirs ) { if ( sb . length ( ) > 0 ) { sb . append ( \":\" ) ; } try { sb . append ( dir . getCanonicalPath ( ) ) ; } catch ( IOException ignored ) { } } options . put ( \"home\" , sb . toString ( ) ) ; ServiceLoader < WebServerPluginInfo > serviceLoader = ServiceLoader . load ( WebServerPluginInfo . class ) ; for ( WebServerPluginInfo info : serviceLoader ) { String [ ] mimeTypes = info . getMimeTypes ( ) ; for ( String mime : mimeTypes ) { String [ ] indexFiles = info . getIndexFilesForMimeType ( mime ) ; if ( ! quiet ) { System . out . print ( \"# Found plugin for Mime type: \\\"\" + mime + \"\\\"\" ) ; if ( indexFiles != null ) { System . out . print ( \" (serving index files: \" ) ; for ( String indexFile : indexFiles ) { System . out . print ( indexFile + \" \" ) ; } } System . out . println ( \").\" ) ; } registerPluginForMimeType ( indexFiles , mime , info . getWebServerPlugin ( mime ) , options ) ; } } ServerRunner . executeInstance ( new SimpleWebServer ( host , port , rootDirs , quiet , cors ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serves file from homeDir and its subdirectories ( only ) . Uses only URI ignores all headers and HTTP parameters . [CODESPLIT] Response serveFile ( String uri , Map < String , String > header , File file , String mime ) { Response res ; try { // Calculate etag String etag = Integer . toHexString ( ( file . getAbsolutePath ( ) + file . lastModified ( ) + \"\" + file . length ( ) ) . hashCode ( ) ) ; // Support (simple) skipping: long startFrom = 0 ; long endAt = - 1 ; String range = header . get ( \"range\" ) ; if ( range != null ) { if ( range . startsWith ( \"bytes=\" ) ) { range = range . substring ( \"bytes=\" . length ( ) ) ; int minus = range . indexOf ( ' ' ) ; try { if ( minus > 0 ) { startFrom = Long . parseLong ( range . substring ( 0 , minus ) ) ; endAt = Long . parseLong ( range . substring ( minus + 1 ) ) ; } } catch ( NumberFormatException ignored ) { } } } // get if-range header. If present, it must match etag or else we // should ignore the range request String ifRange = header . get ( \"if-range\" ) ; boolean headerIfRangeMissingOrMatching = ( ifRange == null || etag . equals ( ifRange ) ) ; String ifNoneMatch = header . get ( \"if-none-match\" ) ; boolean headerIfNoneMatchPresentAndMatching = ifNoneMatch != null && ( \"*\" . equals ( ifNoneMatch ) || ifNoneMatch . equals ( etag ) ) ; // Change return code and add Content-Range header when skipping is // requested long fileLen = file . length ( ) ; if ( headerIfRangeMissingOrMatching && range != null && startFrom >= 0 && startFrom < fileLen ) { // range request that matches current etag // and the startFrom of the range is satisfiable if ( headerIfNoneMatchPresentAndMatching ) { // range request that matches current etag // and the startFrom of the range is satisfiable // would return range from file // respond with not-modified res = newFixedLengthResponse ( Status . NOT_MODIFIED , mime , \"\" ) ; res . addHeader ( \"ETag\" , etag ) ; } else { if ( endAt < 0 ) { endAt = fileLen - 1 ; } long newLen = endAt - startFrom + 1 ; if ( newLen < 0 ) { newLen = 0 ; } FileInputStream fis = new FileInputStream ( file ) ; fis . skip ( startFrom ) ; res = Response . newFixedLengthResponse ( Status . PARTIAL_CONTENT , mime , fis , newLen ) ; res . addHeader ( \"Accept-Ranges\" , \"bytes\" ) ; res . addHeader ( \"Content-Length\" , \"\" + newLen ) ; res . addHeader ( \"Content-Range\" , \"bytes \" + startFrom + \"-\" + endAt + \"/\" + fileLen ) ; res . addHeader ( \"ETag\" , etag ) ; } } else { if ( headerIfRangeMissingOrMatching && range != null && startFrom >= fileLen ) { // return the size of the file // 4xx responses are not trumped by if-none-match res = newFixedLengthResponse ( Status . RANGE_NOT_SATISFIABLE , NanoHTTPD . MIME_PLAINTEXT , \"\" ) ; res . addHeader ( \"Content-Range\" , \"bytes */\" + fileLen ) ; res . addHeader ( \"ETag\" , etag ) ; } else if ( range == null && headerIfNoneMatchPresentAndMatching ) { // full-file-fetch request // would return entire file // respond with not-modified res = newFixedLengthResponse ( Status . NOT_MODIFIED , mime , \"\" ) ; res . addHeader ( \"ETag\" , etag ) ; } else if ( ! headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching ) { // range request that doesn't match current etag // would return entire (different) file // respond with not-modified res = newFixedLengthResponse ( Status . NOT_MODIFIED , mime , \"\" ) ; res . addHeader ( \"ETag\" , etag ) ; } else { // supply the file res = newFixedFileResponse ( file , mime ) ; res . addHeader ( \"Content-Length\" , \"\" + fileLen ) ; res . addHeader ( \"ETag\" , etag ) ; } } } catch ( IOException ioe ) { res = getForbiddenResponse ( \"Reading file failed.\" ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the sent headers and loads the data into Key / value pairs [CODESPLIT] private void decodeHeader ( BufferedReader in , Map < String , String > pre , Map < String , List < String > > parms , Map < String , String > headers ) throws ResponseException { try { // Read the request line String inLine = in . readLine ( ) ; if ( inLine == null ) { return ; } StringTokenizer st = new StringTokenizer ( inLine ) ; if ( ! st . hasMoreTokens ( ) ) { throw new ResponseException ( Status . BAD_REQUEST , \"BAD REQUEST: Syntax error. Usage: GET /example/file.html\" ) ; } pre . put ( \"method\" , st . nextToken ( ) ) ; if ( ! st . hasMoreTokens ( ) ) { throw new ResponseException ( Status . BAD_REQUEST , \"BAD REQUEST: Missing URI. Usage: GET /example/file.html\" ) ; } String uri = st . nextToken ( ) ; // Decode parameters from the URI int qmi = uri . indexOf ( ' ' ) ; if ( qmi >= 0 ) { decodeParms ( uri . substring ( qmi + 1 ) , parms ) ; uri = NanoHTTPD . decodePercent ( uri . substring ( 0 , qmi ) ) ; } else { uri = NanoHTTPD . decodePercent ( uri ) ; } // If there's another token, its protocol version, // followed by HTTP headers. // NOTE: this now forces header names lower case since they are // case insensitive and vary by client. if ( st . hasMoreTokens ( ) ) { protocolVersion = st . nextToken ( ) ; } else { protocolVersion = \"HTTP/1.1\" ; NanoHTTPD . LOG . log ( Level . FINE , \"no protocol version specified, strange. Assuming HTTP/1.1.\" ) ; } String line = in . readLine ( ) ; while ( line != null && ! line . trim ( ) . isEmpty ( ) ) { int p = line . indexOf ( ' ' ) ; if ( p >= 0 ) { headers . put ( line . substring ( 0 , p ) . trim ( ) . toLowerCase ( Locale . US ) , line . substring ( p + 1 ) . trim ( ) ) ; } line = in . readLine ( ) ; } pre . put ( \"uri\" , uri ) ; } catch ( IOException ioe ) { throw new ResponseException ( Status . INTERNAL_ERROR , \"SERVER INTERNAL ERROR: IOException: \" + ioe . getMessage ( ) , ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the Multipart Body data and put it into Key / Value pairs . [CODESPLIT] private void decodeMultipartFormData ( ContentType contentType , ByteBuffer fbuf , Map < String , List < String > > parms , Map < String , String > files ) throws ResponseException { int pcount = 0 ; try { int [ ] boundaryIdxs = getBoundaryPositions ( fbuf , contentType . getBoundary ( ) . getBytes ( ) ) ; if ( boundaryIdxs . length < 2 ) { throw new ResponseException ( Status . BAD_REQUEST , \"BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings.\" ) ; } byte [ ] partHeaderBuff = new byte [ MAX_HEADER_SIZE ] ; for ( int boundaryIdx = 0 ; boundaryIdx < boundaryIdxs . length - 1 ; boundaryIdx ++ ) { fbuf . position ( boundaryIdxs [ boundaryIdx ] ) ; int len = ( fbuf . remaining ( ) < MAX_HEADER_SIZE ) ? fbuf . remaining ( ) : MAX_HEADER_SIZE ; fbuf . get ( partHeaderBuff , 0 , len ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( new ByteArrayInputStream ( partHeaderBuff , 0 , len ) , Charset . forName ( contentType . getEncoding ( ) ) ) , len ) ; int headerLines = 0 ; // First line is boundary string String mpline = in . readLine ( ) ; headerLines ++ ; if ( mpline == null || ! mpline . contains ( contentType . getBoundary ( ) ) ) { throw new ResponseException ( Status . BAD_REQUEST , \"BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary.\" ) ; } String partName = null , fileName = null , partContentType = null ; // Parse the reset of the header lines mpline = in . readLine ( ) ; headerLines ++ ; while ( mpline != null && mpline . trim ( ) . length ( ) > 0 ) { Matcher matcher = NanoHTTPD . CONTENT_DISPOSITION_PATTERN . matcher ( mpline ) ; if ( matcher . matches ( ) ) { String attributeString = matcher . group ( 2 ) ; matcher = NanoHTTPD . CONTENT_DISPOSITION_ATTRIBUTE_PATTERN . matcher ( attributeString ) ; while ( matcher . find ( ) ) { String key = matcher . group ( 1 ) ; if ( \"name\" . equalsIgnoreCase ( key ) ) { partName = matcher . group ( 2 ) ; } else if ( \"filename\" . equalsIgnoreCase ( key ) ) { fileName = matcher . group ( 2 ) ; // add these two line to support multiple // files uploaded using the same field Id if ( ! fileName . isEmpty ( ) ) { if ( pcount > 0 ) partName = partName + String . valueOf ( pcount ++ ) ; else pcount ++ ; } } } } matcher = NanoHTTPD . CONTENT_TYPE_PATTERN . matcher ( mpline ) ; if ( matcher . matches ( ) ) { partContentType = matcher . group ( 2 ) . trim ( ) ; } mpline = in . readLine ( ) ; headerLines ++ ; } int partHeaderLength = 0 ; while ( headerLines -- > 0 ) { partHeaderLength = scipOverNewLine ( partHeaderBuff , partHeaderLength ) ; } // Read the part data if ( partHeaderLength >= len - 4 ) { throw new ResponseException ( Status . INTERNAL_ERROR , \"Multipart header size exceeds MAX_HEADER_SIZE.\" ) ; } int partDataStart = boundaryIdxs [ boundaryIdx ] + partHeaderLength ; int partDataEnd = boundaryIdxs [ boundaryIdx + 1 ] - 4 ; fbuf . position ( partDataStart ) ; List < String > values = parms . get ( partName ) ; if ( values == null ) { values = new ArrayList < String > ( ) ; parms . put ( partName , values ) ; } if ( partContentType == null ) { // Read the part into a string byte [ ] data_bytes = new byte [ partDataEnd - partDataStart ] ; fbuf . get ( data_bytes ) ; values . add ( new String ( data_bytes , contentType . getEncoding ( ) ) ) ; } else { // Read it into a file String path = saveTmpFile ( fbuf , partDataStart , partDataEnd - partDataStart , fileName ) ; if ( ! files . containsKey ( partName ) ) { files . put ( partName , path ) ; } else { int count = 2 ; while ( files . containsKey ( partName + count ) ) { count ++ ; } files . put ( partName + count , path ) ; } values . add ( fileName ) ; } } } catch ( ResponseException re ) { throw re ; } catch ( Exception e ) { throw new ResponseException ( Status . INTERNAL_ERROR , e . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes parameters in percent - encoded URI - format ( e . g . name = Jack%20Daniels&pass = Single%20Malt ) and adds them to given Map . [CODESPLIT] private void decodeParms ( String parms , Map < String , List < String > > p ) { if ( parms == null ) { this . queryParameterString = \"\" ; return ; } this . queryParameterString = parms ; StringTokenizer st = new StringTokenizer ( parms , \"&\" ) ; while ( st . hasMoreTokens ( ) ) { String e = st . nextToken ( ) ; int sep = e . indexOf ( ' ' ) ; String key = null ; String value = null ; if ( sep >= 0 ) { key = NanoHTTPD . decodePercent ( e . substring ( 0 , sep ) ) . trim ( ) ; value = NanoHTTPD . decodePercent ( e . substring ( sep + 1 ) ) ; } else { key = NanoHTTPD . decodePercent ( e ) . trim ( ) ; value = \"\" ; } List < String > values = p . get ( key ) ; if ( values == null ) { values = new ArrayList < String > ( ) ; p . put ( key , values ) ; } values . add ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find byte index separating header from body . It must be the last byte of the first two sequential new lines . [CODESPLIT] private int findHeaderEnd ( final byte [ ] buf , int rlen ) { int splitbyte = 0 ; while ( splitbyte + 1 < rlen ) { // RFC2616 if ( buf [ splitbyte ] == ' ' && buf [ splitbyte + 1 ] == ' ' && splitbyte + 3 < rlen && buf [ splitbyte + 2 ] == ' ' && buf [ splitbyte + 3 ] == ' ' ) { return splitbyte + 4 ; } // tolerance if ( buf [ splitbyte ] == ' ' && buf [ splitbyte + 1 ] == ' ' ) { return splitbyte + 2 ; } splitbyte ++ ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the byte positions where multipart boundaries start . This reads a large block at a time and uses a temporary buffer to optimize ( memory mapped ) file access . [CODESPLIT] private int [ ] getBoundaryPositions ( ByteBuffer b , byte [ ] boundary ) { int [ ] res = new int [ 0 ] ; if ( b . remaining ( ) < boundary . length ) { return res ; } int search_window_pos = 0 ; byte [ ] search_window = new byte [ 4 * 1024 + boundary . length ] ; int first_fill = ( b . remaining ( ) < search_window . length ) ? b . remaining ( ) : search_window . length ; b . get ( search_window , 0 , first_fill ) ; int new_bytes = first_fill - boundary . length ; do { // Search the search_window for ( int j = 0 ; j < new_bytes ; j ++ ) { for ( int i = 0 ; i < boundary . length ; i ++ ) { if ( search_window [ j + i ] != boundary [ i ] ) break ; if ( i == boundary . length - 1 ) { // Match found, add it to results int [ ] new_res = new int [ res . length + 1 ] ; System . arraycopy ( res , 0 , new_res , 0 , res . length ) ; new_res [ res . length ] = search_window_pos + j ; res = new_res ; } } } search_window_pos += new_bytes ; // Copy the end of the buffer to the start System . arraycopy ( search_window , search_window . length - boundary . length , search_window , 0 , boundary . length ) ; // Refill search_window new_bytes = search_window . length - boundary . length ; new_bytes = ( b . remaining ( ) < new_bytes ) ? b . remaining ( ) : new_bytes ; b . get ( search_window , boundary . length , new_bytes ) ; } while ( new_bytes > 0 ) ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deduce body length in bytes . Either from content - length header or read bytes . [CODESPLIT] public long getBodySize ( ) { if ( this . headers . containsKey ( \"content-length\" ) ) { return Long . parseLong ( this . headers . get ( \"content-length\" ) ) ; } else if ( this . splitbyte < this . rlen ) { return this . rlen - this . splitbyte ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the content of a sent file and saves it to a temporary file . The full path to the saved file is returned . [CODESPLIT] private String saveTmpFile ( ByteBuffer b , int offset , int len , String filename_hint ) { String path = \"\" ; if ( len > 0 ) { FileOutputStream fileOutputStream = null ; try { ITempFile tempFile = this . tempFileManager . createTempFile ( filename_hint ) ; ByteBuffer src = b . duplicate ( ) ; fileOutputStream = new FileOutputStream ( tempFile . getName ( ) ) ; FileChannel dest = fileOutputStream . getChannel ( ) ; src . position ( offset ) . limit ( offset + len ) ; dest . write ( src . slice ( ) ) ; path = tempFile . getName ( ) ; } catch ( Exception e ) { // Catch exception if any throw new Error ( e ) ; // we won't recover, so throw an error } finally { NanoHTTPD . safeClose ( fileOutputStream ) ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an SSLSocketFactory for HTTPS . Pass a loaded KeyStore and an array of loaded KeyManagers . These objects must properly loaded / initialized by the caller . [CODESPLIT] public static SSLServerSocketFactory makeSSLSocketFactory ( KeyStore loadedKeyStore , KeyManager [ ] keyManagers ) throws IOException { SSLServerSocketFactory res = null ; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustManagerFactory . init ( loadedKeyStore ) ; SSLContext ctx = SSLContext . getInstance ( \"TLS\" ) ; ctx . init ( keyManagers , trustManagerFactory . getTrustManagers ( ) , null ) ; res = ctx . getServerSocketFactory ( ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an SSLSocketFactory for HTTPS . Pass a loaded KeyStore and a loaded KeyManagerFactory . These objects must properly loaded / initialized by the caller . [CODESPLIT] public static SSLServerSocketFactory makeSSLSocketFactory ( KeyStore loadedKeyStore , KeyManagerFactory loadedKeyFactory ) throws IOException { try { return makeSSLSocketFactory ( loadedKeyStore , loadedKeyFactory . getKeyManagers ( ) ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an SSLSocketFactory for HTTPS . Pass a KeyStore resource with your certificate and passphrase [CODESPLIT] public static SSLServerSocketFactory makeSSLSocketFactory ( String keyAndTrustStoreClasspathPath , char [ ] passphrase ) throws IOException { try { KeyStore keystore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; InputStream keystoreStream = NanoHTTPD . class . getResourceAsStream ( keyAndTrustStoreClasspathPath ) ; if ( keystoreStream == null ) { throw new IOException ( \"Unable to load keystore from classpath: \" + keyAndTrustStoreClasspathPath ) ; } keystore . load ( keystoreStream , passphrase ) ; KeyManagerFactory keyManagerFactory = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; keyManagerFactory . init ( keystore , passphrase ) ; return makeSSLSocketFactory ( keystore , keyManagerFactory ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get MIME type from file name extension if possible [CODESPLIT] public static String getMimeTypeForFile ( String uri ) { int dot = uri . lastIndexOf ( ' ' ) ; String mime = null ; if ( dot >= 0 ) { mime = mimeTypes ( ) . get ( uri . substring ( dot + 1 ) . toLowerCase ( ) ) ; } return mime == null ? \"application/octet-stream\" : mime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the master method that delegates requests to handlers and makes sure there is a response to every request . You are not supposed to call or override this method in any circumstances . But no one will stop you if you do . I m a Javadoc not Code Police . [CODESPLIT] public Response handle ( IHTTPSession session ) { for ( IHandler < IHTTPSession , Response > interceptor : interceptors ) { Response response = interceptor . handle ( session ) ; if ( response != null ) return response ; } return httpHandler . handle ( session ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override this to customize the server . <p / > <p / > ( By default this returns a 404 Not Found plain text error response . ) [CODESPLIT] @ Deprecated protected Response serve ( IHTTPSession session ) { return Response . newFixedLengthResponse ( Status . NOT_FOUND , NanoHTTPD . MIME_PLAINTEXT , \"Not Found\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop the server . [CODESPLIT] public void stop ( ) { try { safeClose ( this . myServerSocket ) ; this . asyncRunner . closeAll ( ) ; if ( this . myThread != null ) { this . myThread . join ( ) ; } } catch ( Exception e ) { NanoHTTPD . LOG . log ( Level . SEVERE , \"Could not stop all connections\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "default routings they are over writable . [CODESPLIT] public void addMappings ( ) { router . setNotImplemented ( NotImplementedHandler . class ) ; router . setNotFoundHandler ( Error404UriHandler . class ) ; router . addRoute ( \"/\" , Integer . MAX_VALUE / 2 , IndexHandler . class ) ; router . addRoute ( \"/index.html\" , Integer . MAX_VALUE / 2 , IndexHandler . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends given response to the socket . [CODESPLIT] public void send ( OutputStream outputStream ) { SimpleDateFormat gmtFrmt = new SimpleDateFormat ( \"E, d MMM yyyy HH:mm:ss 'GMT'\" , Locale . US ) ; gmtFrmt . setTimeZone ( TimeZone . getTimeZone ( \"GMT\" ) ) ; try { if ( this . status == null ) { throw new Error ( \"sendResponse(): Status can't be null.\" ) ; } PrintWriter pw = new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( outputStream , new ContentType ( this . mimeType ) . getEncoding ( ) ) ) , false ) ; pw . append ( \"HTTP/1.1 \" ) . append ( this . status . getDescription ( ) ) . append ( \" \\r\\n\" ) ; if ( this . mimeType != null ) { printHeader ( pw , \"Content-Type\" , this . mimeType ) ; } if ( getHeader ( \"date\" ) == null ) { printHeader ( pw , \"Date\" , gmtFrmt . format ( new Date ( ) ) ) ; } for ( Entry < String , String > entry : this . header . entrySet ( ) ) { printHeader ( pw , entry . getKey ( ) , entry . getValue ( ) ) ; } for ( String cookieHeader : this . cookieHeaders ) { printHeader ( pw , \"Set-Cookie\" , cookieHeader ) ; } if ( getHeader ( \"connection\" ) == null ) { printHeader ( pw , \"Connection\" , ( this . keepAlive ? \"keep-alive\" : \"close\" ) ) ; } if ( getHeader ( \"content-length\" ) != null ) { setUseGzip ( false ) ; } if ( useGzipWhenAccepted ( ) ) { printHeader ( pw , \"Content-Encoding\" , \"gzip\" ) ; setChunkedTransfer ( true ) ; } long pending = this . data != null ? this . contentLength : 0 ; if ( this . requestMethod != Method . HEAD && this . chunkedTransfer ) { printHeader ( pw , \"Transfer-Encoding\" , \"chunked\" ) ; } else if ( ! useGzipWhenAccepted ( ) ) { pending = sendContentLengthHeaderIfNotAlreadyPresent ( pw , pending ) ; } pw . append ( \"\\r\\n\" ) ; pw . flush ( ) ; sendBodyWithCorrectTransferAndEncoding ( outputStream , pending ) ; outputStream . flush ( ) ; NanoHTTPD . safeClose ( this . data ) ; } catch ( IOException ioe ) { NanoHTTPD . LOG . log ( Level . SEVERE , \"Could not send response to the client\" , ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends the body to the specified OutputStream . The pending parameter limits the maximum amounts of bytes sent unless it is - 1 in which case everything is sent . [CODESPLIT] private void sendBody ( OutputStream outputStream , long pending ) throws IOException { long BUFFER_SIZE = 16 * 1024 ; byte [ ] buff = new byte [ ( int ) BUFFER_SIZE ] ; boolean sendEverything = pending == - 1 ; while ( pending > 0 || sendEverything ) { long bytesToRead = sendEverything ? BUFFER_SIZE : Math . min ( pending , BUFFER_SIZE ) ; int read = this . data . read ( buff , 0 , ( int ) bytesToRead ) ; if ( read <= 0 ) { break ; } try { outputStream . write ( buff , 0 , read ) ; } catch ( Exception e ) { if ( this . data != null ) { this . data . close ( ) ; } } if ( ! sendEverything ) { pending -= read ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a response with unknown length ( using HTTP 1 . 1 chunking ) . [CODESPLIT] public static Response newChunkedResponse ( IStatus status , String mimeType , InputStream data ) { return new Response ( status , mimeType , data , - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a response with known length . [CODESPLIT] public static Response newFixedLengthResponse ( IStatus status , String mimeType , InputStream data , long totalBytes ) { return new Response ( status , mimeType , data , totalBytes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a text response with known length . [CODESPLIT] public static Response newFixedLengthResponse ( IStatus status , String mimeType , String txt ) { ContentType contentType = new ContentType ( mimeType ) ; if ( txt == null ) { return newFixedLengthResponse ( status , mimeType , new ByteArrayInputStream ( new byte [ 0 ] ) , 0 ) ; } else { byte [ ] bytes ; try { CharsetEncoder newEncoder = Charset . forName ( contentType . getEncoding ( ) ) . newEncoder ( ) ; if ( ! newEncoder . canEncode ( txt ) ) { contentType = contentType . tryUTF8 ( ) ; } bytes = txt . getBytes ( contentType . getEncoding ( ) ) ; } catch ( UnsupportedEncodingException e ) { NanoHTTPD . LOG . log ( Level . SEVERE , \"encoding problem, responding nothing\" , e ) ; bytes = new byte [ 0 ] ; } return newFixedLengthResponse ( status , contentType . getContentTypeHeader ( ) , new ByteArrayInputStream ( bytes ) , bytes . length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a text response with known length . [CODESPLIT] public static Response newFixedLengthResponse ( String msg ) { return newFixedLengthResponse ( Status . OK , NanoHTTPD . MIME_HTML , msg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Else decide whether or not to use Gzip . [CODESPLIT] public boolean useGzipWhenAccepted ( ) { if ( gzipUsage == GzipUsage . DEFAULT ) return getMimeType ( ) != null && ( getMimeType ( ) . toLowerCase ( ) . contains ( \"text/\" ) || getMimeType ( ) . toLowerCase ( ) . contains ( \"/json\" ) ) ; else return gzipUsage == GzipUsage . ALWAYS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Facade --------------------------- [CODESPLIT] private void readWebsocket ( ) { try { while ( this . state == State . OPEN ) { handleWebsocketFrame ( WebSocketFrame . read ( this . in ) ) ; } } catch ( CharacterCodingException e ) { onException ( e ) ; doClose ( CloseCode . InvalidFramePayloadData , e . toString ( ) , false ) ; } catch ( IOException e ) { onException ( e ) ; if ( e instanceof WebSocketException ) { doClose ( ( ( WebSocketException ) e ) . getCode ( ) , ( ( WebSocketException ) e ) . getReason ( ) , false ) ; } } finally { doClose ( CloseCode . InternalServerError , \"Handler terminated without closing the connection.\" , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates the specified byte array into Base64 string . <p > Android has android . util . Base64 sun has sun . misc . Base64Encoder Java 8 hast java . util . Base64 I have this from stackoverflow : http : // stackoverflow . com / a / 4265472 < / p > [CODESPLIT] private static String encodeBase64 ( byte [ ] buf ) { int size = buf . length ; char [ ] ar = new char [ ( size + 2 ) / 3 * 4 ] ; int a = 0 ; int i = 0 ; while ( i < size ) { byte b0 = buf [ i ++ ] ; byte b1 = i < size ? buf [ i ++ ] : 0 ; byte b2 = i < size ? buf [ i ++ ] : 0 ; int mask = 0x3F ; ar [ a ++ ] = NanoWSD . ALPHABET [ b0 >> 2 & mask ] ; ar [ a ++ ] = NanoWSD . ALPHABET [ ( b0 << 4 | ( b1 & 0xFF ) >> 4 ) & mask ] ; ar [ a ++ ] = NanoWSD . ALPHABET [ ( b1 << 2 | ( b2 & 0xFF ) >> 6 ) & mask ] ; ar [ a ++ ] = NanoWSD . ALPHABET [ b2 & mask ] ; } switch ( size % 3 ) { case 1 : ar [ -- a ] = ' ' ; case 2 : ar [ -- a ] = ' ' ; } return new String ( ar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------- SERIALIZATION --------------------------- [CODESPLIT] public String getTextPayload ( ) { if ( this . _payloadString == null ) { try { this . _payloadString = binary2Text ( getBinaryPayload ( ) ) ; } catch ( CharacterCodingException e ) { throw new RuntimeException ( \"Undetected CharacterCodingException\" , e ) ; } } return this . _payloadString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------- ENCODING -------------------------------- [CODESPLIT] private void readPayloadInfo ( InputStream in ) throws IOException { byte b = ( byte ) checkedRead ( in . read ( ) ) ; boolean masked = ( b & 0x80 ) != 0 ; this . _payloadLength = ( byte ) ( 0x7F & b ) ; if ( this . _payloadLength == 126 ) { // checkedRead must return int for this to work this . _payloadLength = ( checkedRead ( in . read ( ) ) << 8 | checkedRead ( in . read ( ) ) ) & 0xFFFF ; if ( this . _payloadLength < 126 ) { throw new WebSocketException ( CloseCode . ProtocolError , \"Invalid data frame 2byte length. (not using minimal length encoding)\" ) ; } } else if ( this . _payloadLength == 127 ) { long _payloadLength = ( long ) checkedRead ( in . read ( ) ) << 56 | ( long ) checkedRead ( in . read ( ) ) << 48 | ( long ) checkedRead ( in . read ( ) ) << 40 | ( long ) checkedRead ( in . read ( ) ) << 32 | checkedRead ( in . read ( ) ) << 24 | checkedRead ( in . read ( ) ) << 16 | checkedRead ( in . read ( ) ) << 8 | checkedRead ( in . read ( ) ) ; if ( _payloadLength < 65536 ) { throw new WebSocketException ( CloseCode . ProtocolError , \"Invalid data frame 4byte length. (not using minimal length encoding)\" ) ; } if ( _payloadLength < 0 || _payloadLength > Integer . MAX_VALUE ) { throw new WebSocketException ( CloseCode . MessageTooBig , \"Max frame length has been exceeded.\" ) ; } this . _payloadLength = ( int ) _payloadLength ; } if ( this . opCode . isControlFrame ( ) ) { if ( this . _payloadLength > 125 ) { throw new WebSocketException ( CloseCode . ProtocolError , \"Control frame with payload length > 125 bytes.\" ) ; } if ( this . opCode == OpCode . Close && this . _payloadLength == 1 ) { throw new WebSocketException ( CloseCode . ProtocolError , \"Received close frame with payload len 1.\" ) ; } } if ( masked ) { this . maskingKey = new byte [ 4 ] ; int read = 0 ; while ( read < this . maskingKey . length ) { read += checkedRead ( in . read ( this . maskingKey , read , this . maskingKey . length - read ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------ [CODESPLIT] public void write ( OutputStream out ) throws IOException { byte header = 0 ; if ( this . fin ) { header |= 0x80 ; } header |= this . opCode . getValue ( ) & 0x0F ; out . write ( header ) ; this . _payloadLength = getBinaryPayload ( ) . length ; if ( this . _payloadLength <= 125 ) { out . write ( isMasked ( ) ? 0x80 | ( byte ) this . _payloadLength : ( byte ) this . _payloadLength ) ; } else if ( this . _payloadLength <= 0xFFFF ) { out . write ( isMasked ( ) ? 0xFE : 126 ) ; out . write ( this . _payloadLength >>> 8 ) ; out . write ( this . _payloadLength ) ; } else { out . write ( isMasked ( ) ? 0xFF : 127 ) ; out . write ( this . _payloadLength >>> 56 & 0 ) ; // integer only // contains // 31 bit out . write ( this . _payloadLength >>> 48 & 0 ) ; out . write ( this . _payloadLength >>> 40 & 0 ) ; out . write ( this . _payloadLength >>> 32 & 0 ) ; out . write ( this . _payloadLength >>> 24 ) ; out . write ( this . _payloadLength >>> 16 ) ; out . write ( this . _payloadLength >>> 8 ) ; out . write ( this . _payloadLength ) ; } if ( isMasked ( ) ) { out . write ( this . maskingKey ) ; for ( int i = 0 ; i < this . _payloadLength ; i ++ ) { out . write ( getBinaryPayload ( ) [ i ] ^ this . maskingKey [ i % 4 ] ) ; } } else { out . write ( getBinaryPayload ( ) ) ; } out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a cookie . [CODESPLIT] public void set ( String name , String value , int expires ) { this . queue . add ( new Cookie ( name , value , Cookie . getHTTPTime ( expires ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internally used by the webserver to add all queued cookies into the Response s HTTP Headers . [CODESPLIT] public void unloadQueue ( Response response ) { for ( Cookie cookie : this . queue ) { response . addCookieHeader ( cookie . getHTTPHeader ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end :: findbyusername [] [CODESPLIT] @ RequestMapping ( value = \"/sessions/{sessionIdToDelete}\" , method = RequestMethod . DELETE ) public String removeSession ( Principal principal , @ PathVariable String sessionIdToDelete ) { Set < String > usersSessionIds = this . sessions . findByPrincipalName ( principal . getName ( ) ) . keySet ( ) ; if ( usersSessionIds . contains ( sessionIdToDelete ) ) { this . sessions . deleteById ( sessionIdToDelete ) ; } return \"redirect:/\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public List < String > readCookieValues ( HttpServletRequest request ) { Cookie [ ] cookies = request . getCookies ( ) ; List < String > matchingCookieValues = new ArrayList <> ( ) ; if ( cookies != null ) { for ( Cookie cookie : cookies ) { if ( this . cookieName . equals ( cookie . getName ( ) ) ) { String sessionId = ( this . useBase64Encoding ? base64Decode ( cookie . getValue ( ) ) : cookie . getValue ( ) ) ; if ( sessionId == null ) { continue ; } if ( this . jvmRoute != null && sessionId . endsWith ( this . jvmRoute ) ) { sessionId = sessionId . substring ( 0 , sessionId . length ( ) - this . jvmRoute . length ( ) ) ; } matchingCookieValues . add ( sessionId ) ; } } } return matchingCookieValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeCookieValue ( CookieValue cookieValue ) { HttpServletRequest request = cookieValue . getRequest ( ) ; HttpServletResponse response = cookieValue . getResponse ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( this . cookieName ) . append ( ' ' ) ; String value = getValue ( cookieValue ) ; if ( value != null && value . length ( ) > 0 ) { validateValue ( value ) ; sb . append ( value ) ; } int maxAge = getMaxAge ( cookieValue ) ; if ( maxAge > - 1 ) { sb . append ( \"; Max-Age=\" ) . append ( cookieValue . getCookieMaxAge ( ) ) ; OffsetDateTime expires = ( maxAge != 0 ) ? OffsetDateTime . now ( ) . plusSeconds ( maxAge ) : Instant . EPOCH . atOffset ( ZoneOffset . UTC ) ; sb . append ( \"; Expires=\" ) . append ( expires . format ( DateTimeFormatter . RFC_1123_DATE_TIME ) ) ; } String domain = getDomainName ( request ) ; if ( domain != null && domain . length ( ) > 0 ) { validateDomain ( domain ) ; sb . append ( \"; Domain=\" ) . append ( domain ) ; } String path = getCookiePath ( request ) ; if ( path != null && path . length ( ) > 0 ) { validatePath ( path ) ; sb . append ( \"; Path=\" ) . append ( path ) ; } if ( isSecureCookie ( request ) ) { sb . append ( \"; Secure\" ) ; } if ( this . useHttpOnlyCookie ) { sb . append ( \"; HttpOnly\" ) ; } if ( this . sameSite != null ) { sb . append ( \"; SameSite=\" ) . append ( this . sameSite ) ; } response . addHeader ( \"Set-Cookie\" , sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode the value using Base64 . [CODESPLIT] private String base64Decode ( String base64Value ) { try { byte [ ] decodedCookieBytes = Base64 . getDecoder ( ) . decode ( base64Value ) ; return new String ( decodedCookieBytes ) ; } catch ( Exception ex ) { logger . debug ( \"Unable to Base64 decode value: \" + base64Value ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the value using Base64 . [CODESPLIT] private String base64Encode ( String value ) { byte [ ] encodedCookieBytes = Base64 . getEncoder ( ) . encode ( value . getBytes ( ) ) ; return new String ( encodedCookieBytes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets a case insensitive pattern used to extract the domain name from the { @link HttpServletRequest#getServerName () } . The pattern should provide a single grouping that defines what the value is that should be matched . User s should be careful not to output malicious characters like new lines to prevent from things like <a href = https : // www . owasp . org / index . php / HTTP_Response_Splitting > HTTP Response Splitting< / a > . < / p > [CODESPLIT] public void setDomainNamePattern ( String domainNamePattern ) { if ( this . domainName != null ) { throw new IllegalStateException ( \"Cannot set both domainName and domainNamePattern\" ) ; } this . domainNamePattern = Pattern . compile ( domainNamePattern , Pattern . CASE_INSENSITIVE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the name of database table used to store sessions . [CODESPLIT] public void setTableName ( String tableName ) { Assert . hasText ( tableName , \"Table name must not be empty\" ) ; this . tableName = tableName . trim ( ) ; prepareQueries ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void onApplicationEvent ( AbstractSessionEvent event ) { if ( this . listeners . isEmpty ( ) ) { return ; } HttpSessionEvent httpSessionEvent = createHttpSessionEvent ( event ) ; for ( HttpSessionListener listener : this . listeners ) { if ( event instanceof SessionDestroyedEvent ) { listener . sessionDestroyed ( httpSessionEvent ) ; } else if ( event instanceof SessionCreatedEvent ) { listener . sessionCreated ( httpSessionEvent ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tag :: cookie - serializer [] [CODESPLIT] @ Bean public CookieSerializer cookieSerializer ( ) { DefaultCookieSerializer serializer = new DefaultCookieSerializer ( ) ; serializer . setCookieName ( \"JSESSIONID\" ) ; // <1> serializer . setCookiePath ( \"/\" ) ; // <2> serializer . setDomainNamePattern ( \"^.+?\\\\.(\\\\w+\\\\.[a-z]+)$\" ) ; // <3> return serializer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Customized { @link ObjectMapper } to add mix - in for class that doesn t have default constructors [CODESPLIT] private ObjectMapper objectMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; mapper . registerModules ( SecurityJackson2Modules . getModules ( this . loader ) ) ; return mapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tag :: dofilterinternal [] [CODESPLIT] @ Override public void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws IOException , ServletException { chain . doFilter ( request , response ) ; HttpSession session = request . getSession ( false ) ; if ( session != null ) { String remoteAddr = getRemoteAddress ( request ) ; String geoLocation = getGeoLocation ( remoteAddr ) ; SessionDetails details = new SessionDetails ( ) ; details . setAccessType ( request . getHeader ( \"User-Agent\" ) ) ; details . setLocation ( remoteAddr + \" \" + geoLocation ) ; session . setAttribute ( \"SESSION_DETAILS\" , details ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end :: dofilterinternal [] [CODESPLIT] String getGeoLocation ( String remoteAddr ) { try { CityResponse city = this . reader . city ( InetAddress . getByName ( remoteAddr ) ) ; String cityName = city . getCity ( ) . getName ( ) ; String countryName = city . getCountry ( ) . getName ( ) ; if ( cityName == null && countryName == null ) { return null ; } else if ( cityName == null ) { return countryName ; } else if ( countryName == null ) { return cityName ; } return cityName + \", \" + countryName ; } catch ( Exception ex ) { return UNKNOWN ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void configure ( RedisConnection connection ) { String notifyOptions = getNotifyOptions ( connection ) ; String customizedNotifyOptions = notifyOptions ; if ( ! customizedNotifyOptions . contains ( \"E\" ) ) { customizedNotifyOptions += \"E\" ; } boolean A = customizedNotifyOptions . contains ( \"A\" ) ; if ( ! ( A || customizedNotifyOptions . contains ( \"g\" ) ) ) { customizedNotifyOptions += \"g\" ; } if ( ! ( A || customizedNotifyOptions . contains ( \"x\" ) ) ) { customizedNotifyOptions += \"x\" ; } if ( ! notifyOptions . equals ( customizedNotifyOptions ) ) { connection . setConfig ( CONFIG_NOTIFY_KEYSPACE_EVENTS , customizedNotifyOptions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure a { @link WebSessionManager } using a provided { @link ReactiveSessionRepository } . [CODESPLIT] @ Bean ( WebHttpHandlerBuilder . WEB_SESSION_MANAGER_BEAN_NAME ) public WebSessionManager webSessionManager ( ReactiveSessionRepository < ? extends Session > repository ) { SpringSessionWebSessionStore < ? extends Session > sessionStore = new SpringSessionWebSessionStore <> ( repository ) ; DefaultWebSessionManager manager = new DefaultWebSessionManager ( ) ; manager . setSessionStore ( sessionStore ) ; if ( this . webSessionIdResolver != null ) { manager . setSessionIdResolver ( this . webSessionIdResolver ) ; } return manager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public UserDetails loadUserByUsername ( String username ) throws UsernameNotFoundException { User user = this . userRepository . findByEmail ( username ) ; if ( user == null ) { throw new UsernameNotFoundException ( \"Could not find user \" + username ) ; } return new CustomUserDetails ( user ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows customization of whether a remember - me login has been requested . The default is to return { [CODESPLIT] protected boolean rememberMeRequested ( HttpServletRequest request , String parameter ) { String rememberMe = request . getParameter ( parameter ) ; if ( rememberMe != null ) { if ( rememberMe . equalsIgnoreCase ( \"true\" ) || rememberMe . equalsIgnoreCase ( \"on\" ) || rememberMe . equalsIgnoreCase ( \"yes\" ) || rememberMe . equals ( \"1\" ) ) { return true ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Did not send remember-me cookie (principal did not set \" + \"parameter '\" + parameter + \"')\" ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Derives a String name for the given principal . [CODESPLIT] protected String name ( Object principal ) { if ( principal instanceof UserDetails ) { return ( ( UserDetails ) principal ) . getUsername ( ) ; } if ( principal instanceof Principal ) { return ( ( Principal ) principal ) . getName ( ) ; } return principal . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the springSessionRepositoryFilter . [CODESPLIT] private void insertSessionRepositoryFilter ( ServletContext servletContext ) { String filterName = DEFAULT_FILTER_NAME ; DelegatingFilterProxy springSessionRepositoryFilter = new DelegatingFilterProxy ( filterName ) ; String contextAttribute = getWebApplicationContextAttribute ( ) ; if ( contextAttribute != null ) { springSessionRepositoryFilter . setContextAttribute ( contextAttribute ) ; } registerFilter ( servletContext , true , filterName , springSessionRepositoryFilter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { [CODESPLIT] protected EnumSet < DispatcherType > getSessionDispatcherTypes ( ) { return EnumSet . of ( DispatcherType . REQUEST , DispatcherType . ERROR , DispatcherType . ASYNC ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to determine the principal s name from the given Session . [CODESPLIT] private static String resolvePrincipal ( Session session ) { String principalName = session . getAttribute ( FindByIndexNameSessionRepository . PRINCIPAL_NAME_INDEX_NAME ) ; if ( principalName != null ) { return principalName ; } SecurityContext securityContext = session . getAttribute ( SPRING_SECURITY_CONTEXT ) ; if ( securityContext != null && securityContext . getAuthentication ( ) != null ) { return securityContext . getAuthentication ( ) . getName ( ) ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This { [CODESPLIT] @ Override public final void doFilter ( ServletRequest request , ServletResponse response , FilterChain filterChain ) throws ServletException , IOException { if ( ! ( request instanceof HttpServletRequest ) || ! ( response instanceof HttpServletResponse ) ) { throw new ServletException ( \"OncePerRequestFilter just supports HTTP requests\" ) ; } HttpServletRequest httpRequest = ( HttpServletRequest ) request ; HttpServletResponse httpResponse = ( HttpServletResponse ) response ; boolean hasAlreadyFilteredAttribute = request . getAttribute ( this . alreadyFilteredAttributeName ) != null ; if ( hasAlreadyFilteredAttribute ) { // Proceed without invoking this filter... filterChain . doFilter ( request , response ) ; } else { // Do invoke this filter... request . setAttribute ( this . alreadyFilteredAttributeName , Boolean . TRUE ) ; try { doFilterInternal ( httpRequest , httpResponse , filterChain ) ; } finally { // Remove the \"already filtered\" request attribute for this request. request . removeAttribute ( this . alreadyFilteredAttributeName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the session . [CODESPLIT] private RedisSession getSession ( String id , boolean allowExpired ) { Map < Object , Object > entries = getSessionBoundHashOperations ( id ) . entries ( ) ; if ( entries . isEmpty ( ) ) { return null ; } MapSession loaded = loadSession ( id , entries ) ; if ( ! allowExpired && loaded . isExpired ( ) ) { return null ; } RedisSession result = new RedisSession ( loaded ) ; result . originalLastAccessTime = loaded . getLastAccessedTime ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] private BoundHashOperations < Object , Object , Object > getSessionBoundHashOperations ( String sessionId ) { String key = getSessionKey ( sessionId ) ; return this . sessionRedisOperations . boundHashOps ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make any runtime changes necessary to effect the changes indicated by the given { @code operation } . E <p > It constructs a MailSessionService that provides mail session and registers it to Naming service . < / p > [CODESPLIT] @ Override protected void performRuntime ( OperationContext context , ModelNode operation , ModelNode model ) throws OperationFailedException { final PathAddress address = context . getCurrentAddress ( ) ; ModelNode fullTree = Resource . Tools . readModel ( context . readResource ( PathAddress . EMPTY_ADDRESS ) ) ; installRuntimeServices ( context , address , fullTree ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the raw JNDI_NAME value from the given model node and depending on the value and the value of any USE_JAVA_CONTEXT child node converts the raw name into a compliant jndi name . [CODESPLIT] static String getJndiName ( final ModelNode modelNode , OperationContext context ) throws OperationFailedException { final String rawJndiName = MailSessionDefinition . JNDI_NAME . resolveModelAttribute ( context , modelNode ) . asString ( ) ; return getJndiName ( rawJndiName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the class names of the parameters of the given method in canonical form . In case of a method without parameters it will return an empty array . [CODESPLIT] public static String [ ] getCanonicalParameterTypes ( Method viewMethod ) { Class < ? > [ ] parameterTypes = viewMethod . getParameterTypes ( ) ; if ( parameterTypes == null ) { return NO_STRINGS ; } String [ ] canonicalNames = new String [ parameterTypes . length ] ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { canonicalNames [ i ] = parameterTypes [ i ] . getCanonicalName ( ) ; } return canonicalNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is only allowed at various points of the transaction lifecycle . [CODESPLIT] public void registerInterposedSynchronization ( Synchronization synchronization ) throws IllegalStateException , SystemException { int status = ContextTransactionSynchronizationRegistry . getInstance ( ) . getTransactionStatus ( ) ; switch ( status ) { case javax . transaction . Status . STATUS_ACTIVE : case javax . transaction . Status . STATUS_PREPARING : break ; case Status . STATUS_MARKED_ROLLBACK : // do nothing; we can pretend like it was registered, but it'll never be run anyway. return ; default : throw TransactionLogger . ROOT_LOGGER . syncsnotallowed ( status ) ; } if ( synchronization . getClass ( ) . getName ( ) . startsWith ( \"org.jboss.jca\" ) ) { if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( \"JCAOrderedLastSynchronizationList.jcaSyncs.add - Class: \" + synchronization . getClass ( ) + \" HashCode: \" + synchronization . hashCode ( ) + \" toString: \" + synchronization ) ; } jcaSyncs . add ( synchronization ) ; } else { if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( \"JCAOrderedLastSynchronizationList.preJcaSyncs.add - Class: \" + synchronization . getClass ( ) + \" HashCode: \" + synchronization . hashCode ( ) + \" toString: \" + synchronization ) ; } preJcaSyncs . add ( synchronization ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exceptions from Synchronizations that are registered with this TSR are not trapped for before completion . This is because an error in a Sync here should result in the transaction rolling back . [CODESPLIT] @ Override public void beforeCompletion ( ) { // This is needed to guard against syncs being registered during the run, otherwise we could have used an iterator int lastIndexProcessed = 0 ; while ( ( lastIndexProcessed < preJcaSyncs . size ( ) ) ) { Synchronization preJcaSync = preJcaSyncs . get ( lastIndexProcessed ) ; if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( \"JCAOrderedLastSynchronizationList.preJcaSyncs.before_completion - Class: \" + preJcaSync . getClass ( ) + \" HashCode: \" + preJcaSync . hashCode ( ) + \" toString: \" + preJcaSync ) ; } preJcaSync . beforeCompletion ( ) ; lastIndexProcessed = lastIndexProcessed + 1 ; } // Do the same for the jca syncs lastIndexProcessed = 0 ; while ( ( lastIndexProcessed < jcaSyncs . size ( ) ) ) { Synchronization jcaSync = jcaSyncs . get ( lastIndexProcessed ) ; if ( TransactionLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { TransactionLogger . ROOT_LOGGER . trace ( \"JCAOrderedLastSynchronizationList.jcaSyncs.before_completion - Class: \" + jcaSync . getClass ( ) + \" HashCode: \" + jcaSync . hashCode ( ) + \" toString: \" + jcaSync ) ; } jcaSync . beforeCompletion ( ) ; lastIndexProcessed = lastIndexProcessed + 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by <code > TxServerInterceptorInitializer< / code > at ORB initialization time . [CODESPLIT] static void init ( int slotId , Codec codec , org . omg . PortableInterceptor . Current piCurrent ) { TxServerInterceptor . slotId = slotId ; TxServerInterceptor . codec = codec ; TxServerInterceptor . piCurrent = piCurrent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the transaction associated with the transaction propagation context that arrived in the current IIOP request . [CODESPLIT] public static Transaction getCurrentTransaction ( ) { Transaction tx = null ; if ( piCurrent != null ) { // A non-null piCurrent means that a TxServerInterceptor was // installed: check if there is a transaction propagation context try { Any any = piCurrent . get_slot ( slotId ) ; if ( any . type ( ) . kind ( ) . value ( ) != TCKind . _tk_null ) { // Yes, there is a TPC: add the foreign transaction marker tx = ForeignTransaction . INSTANCE ; } } catch ( InvalidSlot e ) { throw IIOPLogger . ROOT_LOGGER . errorGettingSlotInTxInterceptor ( e ) ; } } return tx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads and trims the text for the given attribute and returns it or { @code defaultValue } if there is no value for the attribute [CODESPLIT] private String rawAttributeText ( XMLStreamReader reader , String attributeName , String defaultValue ) { return reader . getAttributeValue ( \"\" , attributeName ) == null ? defaultValue : reader . getAttributeValue ( \"\" , attributeName ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public synchronized void start ( StartContext context ) throws StartException { SecurityLogger . ROOT_LOGGER . debugf ( \"Starting SubjectFactoryService\" ) ; final ISecurityManagement injectedSecurityManagement = securityManagementValue . getValue ( ) ; int i = subjectFactoryClassName . lastIndexOf ( \":\" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( \"subject-factory-class-name attribute\" ) ; String moduleSpec = subjectFactoryClassName . substring ( 0 , i ) ; String className = subjectFactoryClassName . substring ( i + 1 ) ; JBossSecuritySubjectFactory subjectFactory = null ; try { Class < ? > subjectFactoryClazz = SecurityActions . getModuleClassLoader ( moduleSpec ) . loadClass ( className ) ; subjectFactory = ( JBossSecuritySubjectFactory ) subjectFactoryClazz . newInstance ( ) ; } catch ( Exception e ) { throw SecurityLogger . ROOT_LOGGER . unableToStartException ( \"SubjectFactoryService\" , e ) ; } subjectFactory . setSecurityManagement ( injectedSecurityManagement ) ; this . subjectFactory = subjectFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add POJO module if we have any bean factories . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext . getDeploymentUnit ( ) ; final List < KernelDeploymentXmlDescriptor > kdXmlDescriptors = unit . getAttachment ( KernelDeploymentXmlDescriptor . ATTACHMENT_KEY ) ; if ( kdXmlDescriptors == null || kdXmlDescriptors . isEmpty ( ) ) return ; for ( KernelDeploymentXmlDescriptor kdxd : kdXmlDescriptors ) { if ( kdxd . getBeanFactoriesCount ( ) > 0 ) { final ModuleSpecification moduleSpecification = unit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; ModuleDependency dependency = new ModuleDependency ( moduleLoader , POJO_MODULE , false , false , false , false ) ; PathFilter filter = PathFilters . isChildOf ( BaseBeanFactory . class . getPackage ( ) . getName ( ) ) ; dependency . addImportFilter ( filter , true ) ; dependency . addImportFilter ( PathFilters . rejectAll ( ) , false ) ; moduleSpecification . addSystemDependency ( dependency ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a list of all the entries contained here . [CODESPLIT] protected ArrayList getContainedEntries ( ) { final ArrayList ret = new ArrayList ( constants . length + attributes . length + members . length ) ; for ( int i = 0 ; i < constants . length ; ++ i ) ret . ( constants [ i ] ) ; for ( int i = 0 ; i < attributes . length ; ++ i ) ret . ( attributes [ i ] ) ; for ( int i = 0 ; i < members . length ; ++ i ) ret . ( members [ i ] ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "determine if management console can display the second level cache entries [CODESPLIT] @ Override public boolean doesScopedPersistenceUnitNameIdentifyCacheRegionName ( PersistenceUnitMetadata pu ) { String cacheRegionPrefix = pu . getProperties ( ) . getProperty ( AvailableSettings . CACHE_REGION_PREFIX ) ; return cacheRegionPrefix == null || cacheRegionPrefix . equals ( pu . getScopedPersistenceUnitName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the model to figure out the name of the services the server config service has to depend on [CODESPLIT] private static List < ServiceName > getServerConfigDependencies ( OperationContext context , boolean appclient ) { final List < ServiceName > serviceNames = new ArrayList < ServiceName > ( ) ; final Resource subsystemResource = context . readResourceFromRoot ( PathAddress . pathAddress ( WSExtension . SUBSYSTEM_PATH ) , false ) ; readConfigServiceNames ( serviceNames , subsystemResource , Constants . CLIENT_CONFIG ) ; readConfigServiceNames ( serviceNames , subsystemResource , Constants . ENDPOINT_CONFIG ) ; if ( ! appclient ) { serviceNames . add ( CommonWebServer . SERVICE_NAME ) ; } return serviceNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the credential . Unfortunately there is not much we can do here by default . <p / > This method can be overridden to provide some real validation logic [CODESPLIT] protected void validateCredential ( final String username , final SASCurrent credential ) throws LoginException { if ( credential . get_incoming_principal_name ( ) == null || credential . get_incoming_principal_name ( ) . length == 0 ) { throw new LoginException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the passed <code > mdbClass< / code > meets the requirements set by the EJB3 spec about bean implementation classes . The passed <code > mdbClass< / code > must not be an interface and must be public and not final and not abstract . If it passes these requirements then this method returns true . Else it returns false . [CODESPLIT] public static Collection < MdbValidityStatus > assertEjbClassValidity ( final ClassInfo mdbClass ) throws DeploymentUnitProcessingException { Collection < MdbValidityStatus > mdbComplianceIssueList = new ArrayList <> ( MdbValidityStatus . values ( ) . length ) ; final String className = mdbClass . name ( ) . toString ( ) ; verifyModifiers ( className , mdbClass . flags ( ) , mdbComplianceIssueList ) ; for ( MethodInfo method : mdbClass . methods ( ) ) { if ( \"onMessage\" . equals ( method . name ( ) ) ) { verifyOnMessageMethod ( className , method . flags ( ) , mdbComplianceIssueList ) ; } if ( \"finalize\" . equals ( method . name ( ) ) ) { EjbLogger . DEPLOYMENT_LOGGER . mdbCantHaveFinalizeMethod ( className ) ; mdbComplianceIssueList . add ( MdbValidityStatus . MDB_SHOULD_NOT_HAVE_FINALIZE_METHOD ) ; } } return mdbComplianceIssueList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > This method needs to be called once to initialize the static fields orb and rootPoa . < / p > [CODESPLIT] public static void init ( org . omg . CORBA . ORB orb , org . omg . PortableServer . POA rootPoa ) { CorbaNamingContext . orb = orb ; CorbaNamingContext . rootPoa = rootPoa ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > This method needs to be called for each newly created or re - read naming context to set its POA . < / p > [CODESPLIT] public void init ( POA poa , boolean doPurge , boolean noPing ) { this . poa = poa ; this . doPurge = doPurge ; this . noPing = noPing ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================= NamingContextOperation Methods ================================== // [CODESPLIT] public void bind ( NameComponent [ ] nc , org . omg . CORBA . Object obj ) throws NotFound , CannotProceed , InvalidName , AlreadyBound { if ( this . destroyed ) throw new CannotProceed ( ) ; if ( nc == null || nc . length == 0 ) throw new InvalidName ( ) ; if ( obj == null ) throw new org . omg . CORBA . BAD_PARAM ( ) ; Name n = new Name ( nc ) ; Name ctx = n . ctxName ( ) ; NameComponent nb = n . baseNameComponent ( ) ; if ( ctx == null ) { if ( this . names . containsKey ( n ) ) { // if the name is still in use, try to ping the object org . omg . CORBA . Object ref = ( org . omg . CORBA . Object ) this . names . get ( n ) ; if ( isDead ( ref ) ) { rebind ( n . components ( ) , obj ) ; return ; } throw new AlreadyBound ( ) ; } else if ( this . contexts . containsKey ( n ) ) { // if the name is still in use, try to ping the object org . omg . CORBA . Object ref = ( org . omg . CORBA . Object ) this . contexts . get ( n ) ; if ( isDead ( ref ) ) unbind ( n . components ( ) ) ; throw new AlreadyBound ( ) ; } if ( ( this . names . put ( n , obj ) ) != null ) throw new CannotProceed ( _this ( ) , n . components ( ) ) ; IIOPLogger . ROOT_LOGGER . debugf ( \"Bound name: %s\" , n ) ; } else { NameComponent [ ] ncx = new NameComponent [ ] { nb } ; org . omg . CORBA . Object context = this . resolve ( ctx . components ( ) ) ; // try first to call the context implementation object directly. String contextOID = this . getObjectOID ( context ) ; CorbaNamingContext jbossContext = ( contextOID == null ? null : contextImpls . get ( contextOID ) ) ; if ( jbossContext != null ) jbossContext . bind ( ncx , obj ) ; else NamingContextExtHelper . narrow ( context ) . bind ( ncx , obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================= NamingContextExtOperations Methods ================================== // [CODESPLIT] public org . omg . CORBA . Object resolve_str ( String n ) throws NotFound , CannotProceed , InvalidName { return resolve ( to_name ( n ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Cleanup bindings i . e . ping every object and remove bindings to non - existent objects . < / p > [CODESPLIT] private void cleanup ( ) { // Check if object purging enabled if ( ! this . doPurge ) return ; for ( Name key : this . names . keySet ( ) ) { if ( isDead ( ( ( org . omg . CORBA . Object ) this . names . get ( key ) ) ) ) { this . names . remove ( key ) ; } } for ( Name key : this . contexts . keySet ( ) ) { org . omg . CORBA . Object object = ( org . omg . CORBA . Object ) this . contexts . get ( key ) ; if ( isDead ( object ) ) { this . contexts . remove ( key ) ; String oid = this . getObjectOID ( object ) ; if ( oid != null ) contextImpls . remove ( oid ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Obtains the OID of the specified CORBA object . < / p > [CODESPLIT] private String getObjectOID ( org . omg . CORBA . Object object ) { String oid = null ; try { byte [ ] oidBytes = this . poa . reference_to_id ( object ) ; if ( oidBytes != null ) oid = new String ( oidBytes , StandardCharsets . UTF_8 ) ; } catch ( Exception e ) { IIOPLogger . ROOT_LOGGER . debug ( \"Unable to obtain id from object\" , e ) ; } return oid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Determines if the supplied object is non_existent < / p > [CODESPLIT] private boolean isDead ( org . omg . CORBA . Object o ) { boolean non_exist ; try { non_exist = o . _non_existent ( ) ; } catch ( org . omg . CORBA . SystemException e ) { non_exist = true ; } return non_exist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Overrides readObject in Serializable . < / p > [CODESPLIT] private void readObject ( ObjectInputStream in ) throws Exception { in . defaultReadObject ( ) ; /**\n         * Recreate tables. For serialization, object references have been transformed into strings\n         */ for ( Name key : this . contexts . keySet ( ) ) { String ref = ( String ) this . contexts . remove ( key ) ; this . contexts . put ( key , orb . string_to_object ( ref ) ) ; } for ( Name key : this . names . keySet ( ) ) { String ref = ( String ) this . names . remove ( key ) ; this . names . put ( key , orb . string_to_object ( ref ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Overrides writeObject in Serializable . < / p > [CODESPLIT] private void writeObject ( java . io . ObjectOutputStream out ) throws IOException { /*\n        * For serialization, object references are transformed into strings\n        */ for ( Name key : this . contexts . keySet ( ) ) { org . omg . CORBA . Object o = ( org . omg . CORBA . Object ) this . contexts . remove ( key ) ; this . contexts . put ( key , orb . object_to_string ( o ) ) ; } for ( Name key : this . names . keySet ( ) ) { org . omg . CORBA . Object o = ( org . omg . CORBA . Object ) this . names . remove ( key ) ; this . names . put ( key , orb . object_to_string ( o ) ) ; } out . defaultWriteObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the current thread doesn t hold any read locks . If the thread holds any read locks this method throws a { [CODESPLIT] private void checkLoopback ( ) { Integer current = readLockCount . get ( ) ; if ( current != null ) { assert current . intValue ( ) > 0 : \"readLockCount is set, but to 0\" ; throw EjbLogger . ROOT_LOGGER . failToUpgradeToWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decrements the read lock count held by the thread [CODESPLIT] private void decReadLockCount ( ) { Integer current = readLockCount . get ( ) ; int next ; assert current != null : \"can't decrease, readLockCount is not set\" ; next = current . intValue ( ) - 1 ; if ( next == 0 ) readLockCount . remove ( ) ; else readLockCount . set ( new Integer ( next ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increments the read lock count held by the thread [CODESPLIT] private void incReadLockCount ( ) { Integer current = readLockCount . get ( ) ; int next ; if ( current == null ) next = 1 ; else next = current . intValue ( ) + 1 ; readLockCount . set ( new Integer ( next ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes all { @link BeanDeploymentArchiveImpl } s in the given module accessible to all bdas in this module [CODESPLIT] public synchronized void addBeanDeploymentModule ( BeanDeploymentModule module ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { bda . addBeanDeploymentArchives ( module . beanDeploymentArchives ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes all { @link BeanDeploymentArchiveImpl } s in the given modules accessible to all bdas in this module [CODESPLIT] public synchronized void addBeanDeploymentModules ( Collection < BeanDeploymentModule > modules ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { for ( BeanDeploymentModule bdm : modules ) { bda . addBeanDeploymentArchives ( bdm . beanDeploymentArchives ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a service to all bean deployment archives in the module [CODESPLIT] public synchronized < S extends Service > void addService ( Class < S > clazz , S service ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { bda . getServices ( ) . add ( clazz , service ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the JACC contextID using a privileged action and returns the previousID from the { @code PolicyContext } . < / p > [CODESPLIT] protected String setContextID ( final String contextID ) { if ( ! WildFlySecurityManager . isChecking ( ) ) { final String previousID = PolicyContext . getContextID ( ) ; PolicyContext . setContextID ( contextID ) ; return previousID ; } else { final PrivilegedAction < String > action = new SetContextIDAction ( contextID ) ; return AccessController . doPrivileged ( action ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FunctionalService#destroyer implementation [CODESPLIT] @ Override public void accept ( ModClusterConfiguration modClusterConfiguration ) { if ( advertiseSocketDependency != null ) { SocketBinding binding = advertiseSocketDependency . get ( ) ; ManagedBinding simpleManagedBinding = ManagedBinding . Factory . createSimpleManagedBinding ( binding ) ; binding . getSocketBindings ( ) . getNamedRegistry ( ) . unregisterBinding ( simpleManagedBinding ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void registerOperations ( ManagementResourceRegistration container ) { super . registerOperations ( container ) ; container . registerOperationHandler ( ADD_PARAM , WebValveParamAdd . INSTANCE ) ; container . registerOperationHandler ( REMOVE_PARAM , ReloadRequiredRemoveStepHandler . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes sure that the timer is only run once after being restored . [CODESPLIT] public void handleRestorationCalculation ( ) { if ( nextExpiration == null ) { return ; } //next expiration in the future, we don't care if ( nextExpiration . getTime ( ) >= System . currentTimeMillis ( ) ) { return ; } //just set the next expiration to 1ms in the past //this means it will run to catch up the missed expiration //and then the next calculated expiration will be in the future nextExpiration = new Date ( System . currentTimeMillis ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link java . lang . reflect . Method } represented by the { @link org . jboss . as . ejb3 . timerservice . persistence . TimeoutMethod } <p > Note : This method uses the { @link Thread#getContextClassLoader () } to load the relevant classes while getting the { @link java . lang . reflect . Method } < / p > [CODESPLIT] public static Method getTimeoutMethod ( TimeoutMethod timeoutMethodInfo , ClassLoader classLoader ) { if ( timeoutMethodInfo == null ) { return null ; } String declaringClass = timeoutMethodInfo . getDeclaringClass ( ) ; Class < ? > timeoutMethodDeclaringClass = null ; try { timeoutMethodDeclaringClass = Class . forName ( declaringClass , false , classLoader ) ; } catch ( ClassNotFoundException cnfe ) { throw EjbLogger . EJB3_TIMER_LOGGER . failToLoadDeclaringClassOfTimeOut ( declaringClass ) ; } String timeoutMethodName = timeoutMethodInfo . getMethodName ( ) ; String [ ] timeoutMethodParams = timeoutMethodInfo . getMethodParams ( ) ; // load the method param classes Class < ? > [ ] timeoutMethodParamTypes = new Class < ? > [ ] { } ; if ( timeoutMethodParams != null ) { timeoutMethodParamTypes = new Class < ? > [ timeoutMethodParams . length ] ; int i = 0 ; for ( String paramClassName : timeoutMethodParams ) { Class < ? > methodParamClass = null ; try { methodParamClass = Class . forName ( paramClassName , false , classLoader ) ; } catch ( ClassNotFoundException cnfe ) { throw EjbLogger . EJB3_TIMER_LOGGER . failedToLoadTimeoutMethodParamClass ( cnfe , paramClassName ) ; } timeoutMethodParamTypes [ i ++ ] = methodParamClass ; } } // now start looking for the method Class < ? > klass = timeoutMethodDeclaringClass ; while ( klass != null ) { Method [ ] methods = klass . getDeclaredMethods ( ) ; for ( Method method : methods ) { if ( method . getName ( ) . equals ( timeoutMethodName ) ) { Class < ? > [ ] methodParamTypes = method . getParameterTypes ( ) ; // param length doesn't match if ( timeoutMethodParamTypes . length != methodParamTypes . length ) { continue ; } boolean match = true ; for ( int i = 0 ; i < methodParamTypes . length ; i ++ ) { // param type doesn't match if ( ! timeoutMethodParamTypes [ i ] . equals ( methodParamTypes [ i ] ) ) { match = false ; break ; } } if ( match ) { // match found return method ; } } } klass = klass . getSuperclass ( ) ; } // no match found return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void handle ( javax . security . auth . callback . Callback [ ] callbacks ) throws UnsupportedCallbackException , IOException { if ( SUBSYSTEM_RA_LOGGER . isTraceEnabled ( ) ) SUBSYSTEM_RA_LOGGER . elytronHandlerHandle ( Arrays . toString ( callbacks ) ) ; // work wrapper calls the callback handler a second time with default callback values after the handler was invoked // by the RA. We must check if the execution subject already contains an identity and allow for replacement of the // identity with values found in the default callbacks only if the subject has no identity yet or if the identity // is the anonymous one. if ( this . executionSubject != null ) { final SecurityIdentity subjectIdentity = this . getPrivateCredential ( this . executionSubject , SecurityIdentity . class ) ; if ( subjectIdentity != null && ! subjectIdentity . isAnonymous ( ) ) { return ; } } if ( callbacks != null && callbacks . length > 0 ) { if ( this . mappings != null && this . mappings . isMappingRequired ( ) ) { callbacks = this . mappings . mapCallbacks ( callbacks ) ; } GroupPrincipalCallback groupPrincipalCallback = null ; CallerPrincipalCallback callerPrincipalCallback = null ; PasswordValidationCallback passwordValidationCallback = null ; for ( javax . security . auth . callback . Callback callback : callbacks ) { if ( callback instanceof GroupPrincipalCallback ) { groupPrincipalCallback = ( GroupPrincipalCallback ) callback ; if ( this . executionSubject == null ) { this . executionSubject = groupPrincipalCallback . getSubject ( ) ; } else if ( ! this . executionSubject . equals ( groupPrincipalCallback . getSubject ( ) ) ) { // TODO merge the contents of the subjects? } } else if ( callback instanceof CallerPrincipalCallback ) { callerPrincipalCallback = ( CallerPrincipalCallback ) callback ; if ( this . executionSubject == null ) { this . executionSubject = callerPrincipalCallback . getSubject ( ) ; } else if ( ! this . executionSubject . equals ( callerPrincipalCallback . getSubject ( ) ) ) { // TODO merge the contents of the subjects? } } else if ( callback instanceof PasswordValidationCallback ) { passwordValidationCallback = ( PasswordValidationCallback ) callback ; if ( this . executionSubject == null ) { this . executionSubject = passwordValidationCallback . getSubject ( ) ; } else if ( ! this . executionSubject . equals ( passwordValidationCallback . getSubject ( ) ) ) { // TODO merge the contents of the subjects? } } else { throw new UnsupportedCallbackException ( callback ) ; } } this . handleInternal ( callerPrincipalCallback , groupPrincipalCallback , passwordValidationCallback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate the user with the given credential against the configured Elytron security domain . [CODESPLIT] private SecurityIdentity authenticate ( final String username , final char [ ] credential ) throws IOException { final ServerAuthenticationContext context = this . securityDomain . createNewAuthenticationContext ( ) ; final PasswordGuessEvidence evidence = new PasswordGuessEvidence ( credential != null ? credential : null ) ; try { context . setAuthenticationName ( username ) ; if ( context . verifyEvidence ( evidence ) ) { if ( context . authorize ( ) ) { context . succeed ( ) ; return context . getAuthorizedIdentity ( ) ; } else { context . fail ( ) ; throw new SecurityException ( \"Authorization failed\" ) ; } } else { context . fail ( ) ; throw new SecurityException ( \"Authentication failed\" ) ; } } catch ( IllegalArgumentException | IllegalStateException | RealmUnavailableException e ) { context . fail ( ) ; throw e ; } finally { if ( ! context . isDone ( ) ) { context . fail ( ) ; } evidence . destroy ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the persistence provider adapter [CODESPLIT] public static PersistenceProviderAdaptor loadPersistenceAdapterModule ( final String adapterModule , final Platform platform , JtaManagerImpl manager ) throws ModuleLoadException { final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; if ( adapterModule == null ) { return noopAdaptor ; } PersistenceProviderAdaptor persistenceProviderAdaptor = null ; Module module = moduleLoader . loadModule ( ModuleIdentifier . fromString ( adapterModule ) ) ; final ServiceLoader < PersistenceProviderAdaptor > serviceLoader = module . loadService ( PersistenceProviderAdaptor . class ) ; if ( serviceLoader != null ) { for ( PersistenceProviderAdaptor adaptor : serviceLoader ) { if ( persistenceProviderAdaptor != null ) { throw JpaLogger . ROOT_LOGGER . multipleAdapters ( adapterModule ) ; } persistenceProviderAdaptor = adaptor ; ROOT_LOGGER . debugf ( \"loaded persistence provider adapter %s\" , adapterModule ) ; } if ( persistenceProviderAdaptor != null ) { persistenceProviderAdaptor . injectJtaManager ( manager ) ; persistenceProviderAdaptor . injectPlatform ( platform ) ; } } return persistenceProviderAdaptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the persistence provider adapter [CODESPLIT] public static PersistenceProviderAdaptor loadPersistenceAdapter ( final PersistenceProvider persistenceProvider , final Platform platform , final JtaManagerImpl jtaManager ) { PersistenceProviderAdaptor persistenceProviderAdaptor = null ; final ServiceLoader < PersistenceProviderAdaptor > serviceLoader = ServiceLoader . load ( PersistenceProviderAdaptor . class , persistenceProvider . getClass ( ) . getClassLoader ( ) ) ; if ( serviceLoader != null ) { for ( PersistenceProviderAdaptor adaptor : serviceLoader ) { if ( persistenceProviderAdaptor != null ) { throw JpaLogger . ROOT_LOGGER . classloaderHasMultipleAdapters ( persistenceProvider . getClass ( ) . getClassLoader ( ) . toString ( ) ) ; } persistenceProviderAdaptor = adaptor ; ROOT_LOGGER . debugf ( \"loaded persistence provider adapter %s from classloader %s\" , persistenceProviderAdaptor . getClass ( ) . getName ( ) , persistenceProvider . getClass ( ) . getClassLoader ( ) . toString ( ) ) ; } if ( persistenceProviderAdaptor != null ) { persistenceProviderAdaptor . injectJtaManager ( jtaManager ) ; persistenceProviderAdaptor . injectPlatform ( platform ) ; } } return persistenceProviderAdaptor == null ? noopAdaptor : persistenceProviderAdaptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if set to auto will behave like not having set the property [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; if ( JPADeploymentMarker . isJPADeployment ( deploymentUnit ) ) { addSearchDependency ( moduleSpecification , moduleLoader , deploymentUnit ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { [CODESPLIT] public Timer getTimer ( ) throws IllegalStateException , EJBException { if ( service == null ) { // get hold of the timer service through the use of timed object id service = ( TimerServiceImpl ) currentServiceContainer ( ) . getRequiredService ( ServiceName . parse ( serviceName ) ) . getValue ( ) ; if ( service == null ) { throw EjbLogger . EJB3_TIMER_LOGGER . timerServiceWithIdNotRegistered ( timedObjectId ) ; } } final TimerImpl timer = this . service . getTimer ( this ) ; if ( timer == null || ! timer . isActive ( ) ) { throw EjbLogger . EJB3_TIMER_LOGGER . timerHandleIsNotActive ( this ) ; } return timer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @link org . jboss . as . weld . deployment . processors . WeldDeploymentProcessor } assembles a basic accessibility graph based on the deployment structure . Here we complete the graph by examining classloader visibility . This allows additional accessibility edges caused e . g . by the Class - Path declaration in the manifest file to be recognized . [CODESPLIT] private void calculateAccessibilityGraph ( Iterable < BeanDeploymentArchiveImpl > beanDeploymentArchives ) { for ( BeanDeploymentArchiveImpl from : beanDeploymentArchives ) { for ( BeanDeploymentArchiveImpl target : beanDeploymentArchives ) { if ( from . isAccessible ( target ) ) { from . addBeanDeploymentArchive ( target ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds additional edges to the accessibility graph that allow static CDI - enabled modules to inject beans from top - level deployment units [CODESPLIT] private void makeTopLevelBdasVisibleFromStaticModules ( ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { if ( bda . getBeanArchiveType ( ) . equals ( BeanDeploymentArchiveImpl . BeanArchiveType . EXTERNAL ) || bda . getBeanArchiveType ( ) . equals ( BeanDeploymentArchiveImpl . BeanArchiveType . SYNTHETIC ) ) { for ( BeanDeploymentArchiveImpl topLevelBda : rootBeanDeploymentModule . getBeanDeploymentArchives ( ) ) { bda . addBeanDeploymentArchive ( topLevelBda ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public synchronized BeanDeploymentArchive loadBeanDeploymentArchive ( final Class < ? > beanClass ) { final BeanDeploymentArchive bda = this . getBeanDeploymentArchive ( beanClass ) ; if ( bda != null ) { return bda ; } Module module = Module . forClass ( beanClass ) ; if ( module == null ) { // Bean class loaded by the bootstrap class loader if ( bootstrapClassLoaderBeanDeploymentArchive == null ) { bootstrapClassLoaderBeanDeploymentArchive = createAndRegisterAdditionalBeanDeploymentArchive ( module , beanClass ) ; } else { bootstrapClassLoaderBeanDeploymentArchive . addBeanClass ( beanClass ) ; } return bootstrapClassLoaderBeanDeploymentArchive ; } /*\n         * No, there is no BDA for the class yet. Let's create one.\n         */ return createAndRegisterAdditionalBeanDeploymentArchive ( module , beanClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds universal JSE meta data model that is AS agnostic . [CODESPLIT] JSEArchiveMetaData create ( final Deployment dep ) { if ( WSLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { WSLogger . ROOT_LOGGER . tracef ( \"Creating JBoss agnostic meta data for POJO webservice deployment: %s\" , dep . getSimpleName ( ) ) ; } final JBossWebMetaData jbossWebMD = WSHelper . getRequiredAttachment ( dep , JBossWebMetaData . class ) ; final DeploymentUnit unit = WSHelper . getRequiredAttachment ( dep , DeploymentUnit . class ) ; final List < POJOEndpoint > pojoEndpoints = getPojoEndpoints ( unit ) ; final JSEArchiveMetaData . Builder builder = new JSEArchiveMetaData . Builder ( ) ; // set context root final String contextRoot = getContextRoot ( dep , jbossWebMD ) ; builder . setContextRoot ( contextRoot ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting context root: %s\" , contextRoot ) ; // set servlet url patterns mappings final Map < String , String > servletMappings = getServletUrlPatternsMappings ( jbossWebMD , pojoEndpoints ) ; builder . setServletMappings ( servletMappings ) ; // set servlet class names mappings final Map < String , String > servletClassNamesMappings = getServletClassMappings ( jbossWebMD , pojoEndpoints ) ; builder . setServletClassNames ( servletClassNamesMappings ) ; // set security domain final String securityDomain = jbossWebMD . getSecurityDomain ( ) ; builder . setSecurityDomain ( securityDomain ) ; // set wsdl location resolver final JBossWebservicesMetaData jbossWebservicesMD = WSHelper . getOptionalAttachment ( dep , JBossWebservicesMetaData . class ) ; if ( jbossWebservicesMD != null ) { final PublishLocationAdapter resolver = new PublishLocationAdapterImpl ( jbossWebservicesMD . getWebserviceDescriptions ( ) ) ; builder . setPublishLocationAdapter ( resolver ) ; } // set security meta data final List < JSESecurityMetaData > jseSecurityMDs = getSecurityMetaData ( jbossWebMD . getSecurityConstraints ( ) ) ; builder . setSecurityMetaData ( jseSecurityMDs ) ; // set config name and file setConfigNameAndFile ( builder , jbossWebMD , jbossWebservicesMD ) ; return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets config name and config file . [CODESPLIT] private void setConfigNameAndFile ( final JSEArchiveMetaData . Builder builder , final JBossWebMetaData jbossWebMD , final JBossWebservicesMetaData jbossWebservicesMD ) { if ( jbossWebservicesMD != null ) { if ( jbossWebservicesMD . getConfigName ( ) != null ) { final String configName = jbossWebservicesMD . getConfigName ( ) ; builder . setConfigName ( configName ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting config name: %s\" , configName ) ; final String configFile = jbossWebservicesMD . getConfigFile ( ) ; builder . setConfigFile ( configFile ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting config file: %s\" , configFile ) ; // ensure higher priority against web.xml context parameters return ; } } final List < ParamValueMetaData > contextParams = jbossWebMD . getContextParams ( ) ; if ( contextParams != null ) { for ( final ParamValueMetaData contextParam : contextParams ) { if ( WSConstants . JBOSSWS_CONFIG_NAME . equals ( contextParam . getParamName ( ) ) ) { final String configName = contextParam . getParamValue ( ) ; builder . setConfigName ( configName ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting config name: %s\" , configName ) ; } if ( WSConstants . JBOSSWS_CONFIG_FILE . equals ( contextParam . getParamName ( ) ) ) { final String configFile = contextParam . getParamValue ( ) ; builder . setConfigFile ( configFile ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting config file: %s\" , configFile ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds security meta data . [CODESPLIT] private List < JSESecurityMetaData > getSecurityMetaData ( final List < SecurityConstraintMetaData > securityConstraintsMD ) { final List < JSESecurityMetaData > jseSecurityMDs = new LinkedList < JSESecurityMetaData > ( ) ; if ( securityConstraintsMD != null ) { for ( final SecurityConstraintMetaData securityConstraintMD : securityConstraintsMD ) { final JSESecurityMetaData . Builder jseSecurityMDBuilder = new JSESecurityMetaData . Builder ( ) ; // transport guarantee jseSecurityMDBuilder . setTransportGuarantee ( securityConstraintMD . getTransportGuarantee ( ) . name ( ) ) ; // web resources for ( final WebResourceCollectionMetaData webResourceMD : securityConstraintMD . getResourceCollections ( ) ) { jseSecurityMDBuilder . addWebResource ( webResourceMD . getName ( ) , webResourceMD . getUrlPatterns ( ) ) ; } jseSecurityMDs . add ( jseSecurityMDBuilder . build ( ) ) ; } } return jseSecurityMDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns servlet name to url pattern mappings . [CODESPLIT] private Map < String , String > getServletUrlPatternsMappings ( final JBossWebMetaData jbossWebMD , final List < POJOEndpoint > pojoEndpoints ) { final Map < String , String > mappings = new HashMap < String , String > ( ) ; final List < ServletMappingMetaData > servletMappings = WebMetaDataHelper . getServletMappings ( jbossWebMD ) ; for ( final POJOEndpoint pojoEndpoint : pojoEndpoints ) { mappings . put ( pojoEndpoint . getName ( ) , pojoEndpoint . getUrlPattern ( ) ) ; if ( ! pojoEndpoint . isDeclared ( ) ) { final String endpointName = pojoEndpoint . getName ( ) ; final List < String > urlPatterns = WebMetaDataHelper . getUrlPatterns ( pojoEndpoint . getUrlPattern ( ) ) ; WebMetaDataHelper . newServletMapping ( endpointName , urlPatterns , servletMappings ) ; } } return mappings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns servlet name to servlet class mappings . [CODESPLIT] private Map < String , String > getServletClassMappings ( final JBossWebMetaData jbossWebMD , final List < POJOEndpoint > pojoEndpoints ) { final Map < String , String > mappings = new HashMap < String , String > ( ) ; final JBossServletsMetaData servlets = WebMetaDataHelper . getServlets ( jbossWebMD ) ; for ( final POJOEndpoint pojoEndpoint : pojoEndpoints ) { final String pojoName = pojoEndpoint . getName ( ) ; final String pojoClassName = pojoEndpoint . getClassName ( ) ; mappings . put ( pojoName , pojoClassName ) ; if ( ! pojoEndpoint . isDeclared ( ) ) { final String endpointName = pojoEndpoint . getName ( ) ; final String endpointClassName = pojoEndpoint . getClassName ( ) ; WebMetaDataHelper . newServlet ( endpointName , endpointClassName , servlets ) ; } } return mappings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if this ejb injection has been resolved yet and if not resolves it . [CODESPLIT] private void resolve ( ) { if ( ! resolved ) { synchronized ( this ) { if ( ! resolved ) { final Set < ViewDescription > views = getViews ( ) ; final Set < EJBViewDescription > ejbsForViewName = new HashSet < EJBViewDescription > ( ) ; for ( final ViewDescription view : views ) { if ( view instanceof EJBViewDescription ) { final MethodIntf viewType = ( ( EJBViewDescription ) view ) . getMethodIntf ( ) ; // @EJB injection *shouldn't* consider the @WebService endpoint view or MDBs if ( viewType == MethodIntf . SERVICE_ENDPOINT || viewType == MethodIntf . MESSAGE_ENDPOINT ) { continue ; } ejbsForViewName . add ( ( EJBViewDescription ) view ) ; } } if ( ejbsForViewName . isEmpty ( ) ) { if ( beanName == null ) { error = EjbLogger . ROOT_LOGGER . ejbNotFound ( typeName , bindingName ) ; } else { error = EjbLogger . ROOT_LOGGER . ejbNotFound ( typeName , beanName , bindingName ) ; } } else if ( ejbsForViewName . size ( ) > 1 ) { if ( beanName == null ) { error = EjbLogger . ROOT_LOGGER . moreThanOneEjbFound ( typeName , bindingName , ejbsForViewName ) ; } else { error = EjbLogger . ROOT_LOGGER . moreThanOneEjbFound ( typeName , beanName , bindingName , ejbsForViewName ) ; } } else { final EJBViewDescription description = ejbsForViewName . iterator ( ) . next ( ) ; final EJBViewDescription ejbViewDescription = ( EJBViewDescription ) description ; //for remote interfaces we do not want to use a normal binding //we need to bind the remote proxy factory into JNDI instead to get the correct behaviour if ( ejbViewDescription . getMethodIntf ( ) == MethodIntf . REMOTE || ejbViewDescription . getMethodIntf ( ) == MethodIntf . HOME ) { final EJBComponentDescription componentDescription = ( EJBComponentDescription ) description . getComponentDescription ( ) ; final EEModuleDescription moduleDescription = componentDescription . getModuleDescription ( ) ; final String earApplicationName = moduleDescription . getEarApplicationName ( ) ; final Value < ClassLoader > viewClassLoader = new Value < ClassLoader > ( ) { @ Override public ClassLoader getValue ( ) throws IllegalStateException , IllegalArgumentException { final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; return module != null ? module . getClassLoader ( ) : null ; } } ; remoteFactory = new RemoteViewManagedReferenceFactory ( earApplicationName , moduleDescription . getModuleName ( ) , moduleDescription . getDistinctName ( ) , componentDescription . getComponentName ( ) , description . getViewClassName ( ) , componentDescription . isStateful ( ) , viewClassLoader , appclient ) ; } final ServiceName serviceName = description . getServiceName ( ) ; resolvedViewName = serviceName ; } resolved = true ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Node elect ( List < Node > nodes ) { int size = nodes . size ( ) ; return ( size > 0 ) ? nodes . get ( this . random . nextInt ( size ) ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FIXME use capabilities & requirements [CODESPLIT] private static Set < String > getAvailableConnectors ( final OperationContext context , final ModelNode operation ) throws OperationFailedException { PathAddress address = PathAddress . pathAddress ( operation . get ( ModelDescriptionConstants . OP_ADDR ) ) ; PathAddress active = MessagingServices . getActiveMQServerPathAddress ( address ) ; Set < String > availableConnectors = new HashSet < String > ( ) ; Resource subsystemResource = context . readResourceFromRoot ( active . getParent ( ) , false ) ; availableConnectors . addAll ( subsystemResource . getChildrenNames ( CommonAttributes . REMOTE_CONNECTOR ) ) ; Resource activeMQServerResource = context . readResourceFromRoot ( active , false ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . HTTP_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . IN_VM_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . REMOTE_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . CONNECTOR ) ) ; return availableConnectors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void getResourceValue ( final ResolutionContext resolutionContext , final ServiceBuilder < ? > serviceBuilder , final DeploymentPhaseContext phaseContext , final Injector < ManagedReferenceFactory > injector ) { if ( serviceName != null ) { serviceBuilder . requires ( serviceName ) ; } final RemoteViewManagedReferenceFactory factory = new RemoteViewManagedReferenceFactory ( appName , moduleName , distinctName , beanName , viewClass , stateful , viewClassLoader , appclient ) ; injector . inject ( factory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle the core - environment element and children [CODESPLIT] static void parseCoreEnvironmentElement ( final XMLExtendedStreamReader reader , final ModelNode operation ) throws XMLStreamException { final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { requireNoNamespaceAttribute ( reader , i ) ; final String value = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; switch ( attribute ) { case NODE_IDENTIFIER : TransactionSubsystemRootResourceDefinition . NODE_IDENTIFIER . parseAndSetParameter ( value , operation , reader ) ; break ; case PATH : case RELATIVE_TO : throw TransactionLogger . ROOT_LOGGER . unsupportedAttribute ( attribute . getLocalName ( ) , reader . getLocation ( ) ) ; default : throw unexpectedAttribute ( reader , i ) ; } } // elements final EnumSet < Element > required = EnumSet . of ( Element . PROCESS_ID ) ; final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { final Element element = Element . forName ( reader . getLocalName ( ) ) ; required . remove ( element ) ; switch ( element ) { case PROCESS_ID : { if ( ! encountered . add ( element ) ) { throw duplicateNamedElement ( reader , reader . getLocalName ( ) ) ; } parseProcessIdEnvironmentElement ( reader , operation ) ; break ; } default : throw unexpectedElement ( reader ) ; } } if ( ! required . isEmpty ( ) ) { throw missingRequiredElement ( reader , required ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle the process - id child elements [CODESPLIT] static void parseProcessIdEnvironmentElement ( XMLExtendedStreamReader reader , ModelNode coreEnvironmentAdd ) throws XMLStreamException { // no attributes if ( reader . getAttributeCount ( ) > 0 ) { throw unexpectedAttribute ( reader , 0 ) ; } // elements boolean encountered = false ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { final Element element = Element . forName ( reader . getLocalName ( ) ) ; switch ( element ) { case UUID : if ( encountered ) { throw unexpectedElement ( reader ) ; } encountered = true ; if ( reader . getAttributeCount ( ) > 0 ) { throw unexpectedAttribute ( reader , 0 ) ; } coreEnvironmentAdd . get ( TransactionSubsystemRootResourceDefinition . PROCESS_ID_UUID . getName ( ) ) . set ( true ) ; requireNoContent ( reader ) ; break ; case SOCKET : { if ( encountered ) { throw unexpectedElement ( reader ) ; } encountered = true ; parseSocketProcessIdElement ( reader , coreEnvironmentAdd ) ; break ; } default : throw unexpectedElement ( reader ) ; } } if ( ! encountered ) { throw missingOneOf ( reader , EnumSet . of ( Element . UUID , Element . SOCKET ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create EE container entity manager factory [CODESPLIT] private EntityManagerFactoryBuilder createContainerEntityManagerFactoryBuilder ( ) { persistenceProviderAdaptor . beforeCreateContainerEntityManagerFactory ( pu ) ; try { TwoPhaseBootstrapCapable twoPhaseBootstrapCapable = ( TwoPhaseBootstrapCapable ) persistenceProviderAdaptor ; return twoPhaseBootstrapCapable . getBootstrap ( pu , properties . getValue ( ) ) ; } finally { try { persistenceProviderAdaptor . afterCreateContainerEntityManagerFactory ( pu ) ; } finally { pu . setAnnotationIndex ( null ) ; // close reference to Annotation Index (only needed during call to createContainerEntityManagerFactory) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "org . hibernate . jpa . event . spi . jpa . ExtendedBeanManager is added to Hibernate 5 . 1 as an extension for delaying registration of entity listeners until the CDI AfterDeploymentValidation event is triggered . This allows entity listener classes to reference the ( origin ) persistence unit ( WFLY - 2387 ) . [CODESPLIT] private boolean isHibernateExtendedBeanManagerSupported ( ) { try { Class . forName ( HIBERNATE_EXTENDED_BEANMANAGER ) ; return true ; } catch ( ClassNotFoundException ignore ) { return false ; } catch ( NoClassDefFoundError ignore ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the address of the specified operation [CODESPLIT] public static PathAddress getPathAddress ( ModelNode operation ) { return PathAddress . pathAddress ( operation . require ( ModelDescriptionConstants . OP_ADDR ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the address of the specified operation . [CODESPLIT] public static void setPathAddress ( ModelNode operation , PathAddress address ) { operation . get ( ModelDescriptionConstants . OP_ADDR ) . set ( address . toModelNode ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the attribute value of the specified operation [CODESPLIT] public static ModelNode getAttributeValue ( ModelNode operation ) { return operation . hasDefined ( ModelDescriptionConstants . VALUE ) ? operation . get ( ModelDescriptionConstants . VALUE ) : new ModelNode ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates whether or not this operation expects to include default values . [CODESPLIT] public static boolean isIncludeDefaults ( ModelNode operation ) { return operation . hasDefined ( ModelDescriptionConstants . INCLUDE_DEFAULTS ) ? operation . get ( ModelDescriptionConstants . INCLUDE_DEFAULTS ) . asBoolean ( ) : true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a composite operation using the specified operation steps . [CODESPLIT] public static ModelNode createCompositeOperation ( List < ModelNode > operations ) { ModelNode operation = Util . createOperation ( ModelDescriptionConstants . COMPOSITE , PathAddress . EMPTY_ADDRESS ) ; ModelNode steps = operation . get ( ModelDescriptionConstants . STEPS ) ; for ( ModelNode step : operations ) { steps . add ( step ) ; } return operation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an add operation using the specified address and parameters [CODESPLIT] public static ModelNode createAddOperation ( PathAddress address , Map < Attribute , ModelNode > parameters ) { ModelNode operation = Util . createAddOperation ( address ) ; for ( Map . Entry < Attribute , ModelNode > entry : parameters . entrySet ( ) ) { operation . get ( entry . getKey ( ) . getName ( ) ) . set ( entry . getValue ( ) ) ; } return operation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an indexed add operation using the specified address and index [CODESPLIT] public static ModelNode createAddOperation ( PathAddress address , int index ) { return createAddOperation ( address , index , Collections . emptyMap ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a read - attribute operation using the specified address and name . [CODESPLIT] public static ModelNode createReadAttributeOperation ( PathAddress address , Attribute attribute ) { return createAttributeOperation ( ModelDescriptionConstants . READ_ATTRIBUTE_OPERATION , address , attribute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a write - attribute operation using the specified address name and value . [CODESPLIT] public static ModelNode createWriteAttributeOperation ( PathAddress address , Attribute attribute , ModelNode value ) { ModelNode operation = createAttributeOperation ( ModelDescriptionConstants . WRITE_ATTRIBUTE_OPERATION , address , attribute ) ; operation . get ( ModelDescriptionConstants . VALUE ) . set ( value ) ; return operation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an undefine - attribute operation using the specified address and name . [CODESPLIT] public static ModelNode createUndefineAttributeOperation ( PathAddress address , Attribute attribute ) { return createAttributeOperation ( ModelDescriptionConstants . UNDEFINE_ATTRIBUTE_OPERATION , address , attribute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup the value from the naming context . [CODESPLIT] public T getValue ( ) throws IllegalStateException { final Context context = contextValue . getValue ( ) ; try { return ( T ) context . lookup ( contextName ) ; } catch ( NamingException e ) { throw NamingLogger . ROOT_LOGGER . entryNotRegistered ( e , contextName , context ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an ObjectFactory to handle requests for a specific URL scheme . [CODESPLIT] public static synchronized void addUrlContextFactory ( final String scheme , ObjectFactory factory ) { Map < String , ObjectFactory > factories = new HashMap < String , ObjectFactory > ( urlContextFactories ) ; factories . put ( scheme , factory ) ; urlContextFactories = Collections . unmodifiableMap ( factories ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an ObjectFactory from the map of registered ones . To make sure that not anybody can remove an ObjectFactory both the scheme as well as the actual object factory itself need to be supplied . So you can only remove the factory if you have the factory object . [CODESPLIT] public static synchronized void removeUrlContextFactory ( final String scheme , ObjectFactory factory ) { Map < String , ObjectFactory > factories = new HashMap < String , ObjectFactory > ( urlContextFactories ) ; ObjectFactory f = factories . get ( scheme ) ; if ( f == factory ) { factories . remove ( scheme ) ; urlContextFactories = Collections . unmodifiableMap ( factories ) ; return ; } else { throw new IllegalArgumentException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list with all { @link ValidationProvider } validation providers . [CODESPLIT] @ Override public List < ValidationProvider < ? > > getValidationProviders ( ) { // first try the TCCL List < ValidationProvider < ? > > providers = loadProviders ( WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ) ; if ( providers != null && ! providers . isEmpty ( ) ) { return providers ; } // otherwise use the loader of this class else { return loadProviders ( WildFlySecurityManager . getClassLoaderPrivileged ( WildFlyProviderResolver . class ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the providers from the given loader using the service loader mechanism . [CODESPLIT] private List < ValidationProvider < ? > > loadProviders ( ClassLoader classLoader ) { @ SuppressWarnings ( \"rawtypes\" ) Iterator < ValidationProvider > providerIterator = ServiceLoader . load ( ValidationProvider . class , classLoader ) . iterator ( ) ; LinkedList < ValidationProvider < ? > > providers = new LinkedList < ValidationProvider < ? > > ( ) ; while ( providerIterator . hasNext ( ) ) { try { ValidationProvider < ? > provider = providerIterator . next ( ) ; // put Hibernate Validator to the beginning of the list if ( provider . getClass ( ) . getName ( ) . equals ( \"org.hibernate.validator.HibernateValidator\" ) ) { providers . addFirst ( provider ) ; } else { providers . add ( provider ) ; } } catch ( ServiceConfigurationError e ) { // ignore, because it can happen when multiple // providers are present and some of them are not class loader // compatible with our API. } } return providers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( StartContext context ) throws StartException { try { PolicyConfigurationFactory pcf = getPolicyConfigurationFactory ( ) ; synchronized ( pcf ) { // synchronize on the factory policyConfiguration = pcf . getPolicyConfiguration ( contextId , false ) ; if ( metaData != null ) { createPermissions ( metaData , policyConfiguration ) ; } else { SecurityLogger . ROOT_LOGGER . debugf ( \"Cannot create permissions with 'null' metaData for id=%s\" , contextId ) ; } if ( ! standalone ) { PolicyConfiguration parent = parentPolicy . getValue ( ) ; if ( parent != null ) { parent = pcf . getPolicyConfiguration ( parent . getContextID ( ) , false ) ; parent . linkConfiguration ( policyConfiguration ) ; policyConfiguration . commit ( ) ; parent . commit ( ) ; } else { SecurityLogger . ROOT_LOGGER . debugf ( \"Could not retrieve parent policy for policy %s\" , contextId ) ; } } else { policyConfiguration . commit ( ) ; } // Allow the policy to incorporate the policy configs Policy . getPolicy ( ) . refresh ( ) ; } } catch ( Exception e ) { throw SecurityLogger . ROOT_LOGGER . unableToStartException ( \"JaccService\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void stop ( StopContext context ) { try { PolicyConfigurationFactory pcf = PolicyConfigurationFactory . getPolicyConfigurationFactory ( ) ; synchronized ( pcf ) { // synchronize on the factory policyConfiguration = pcf . getPolicyConfiguration ( contextId , false ) ; policyConfiguration . delete ( ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . errorDeletingJACCPolicy ( e ) ; } policyConfiguration = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the canonical request URI - that is the request URI minus the context path . < / p > [CODESPLIT] private String getCanonicalURI ( HttpServletRequest request ) { String canonicalURI = request . getRequestURI ( ) . substring ( request . getContextPath ( ) . length ( ) ) ; if ( canonicalURI == null || canonicalURI . equals ( \"/\" ) ) canonicalURI = \"\" ; return canonicalURI ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : should this be part of the messaging subsystem [CODESPLIT] private List < BindingConfiguration > getMessageDestinationRefs ( final DeploymentDescriptorEnvironment environment , final ClassLoader classLoader , final DeploymentReflectionIndex deploymentReflectionIndex , final ResourceInjectionTarget resourceInjectionTarget , final DeploymentUnit deploymentUnit ) throws DeploymentUnitProcessingException { final List < BindingConfiguration > bindings = new ArrayList < BindingConfiguration > ( ) ; final MessageDestinationReferencesMetaData messageDestinationReferences = environment . getEnvironment ( ) . getMessageDestinationReferences ( ) ; if ( messageDestinationReferences == null ) { return bindings ; } for ( final MessageDestinationReferenceMetaData messageRef : messageDestinationReferences ) { if ( messageRef . isDependencyIgnored ( ) ) { continue ; } final String name ; if ( messageRef . getName ( ) . startsWith ( \"java:\" ) ) { name = messageRef . getName ( ) ; } else { name = environment . getDefaultContext ( ) + messageRef . getName ( ) ; } Class < ? > classType = null ; if ( messageRef . getType ( ) != null ) { try { classType = classLoader . loadClass ( messageRef . getType ( ) ) ; } catch ( ClassNotFoundException e ) { throw EeLogger . ROOT_LOGGER . cannotLoad ( e , messageRef . getType ( ) ) ; } } // our injection (source) comes from the local (ENC) lookup, no matter what. final LookupInjectionSource injectionSource = new LookupInjectionSource ( name ) ; classType = processInjectionTargets ( resourceInjectionTarget , injectionSource , classLoader , deploymentReflectionIndex , messageRef , classType ) ; final BindingConfiguration bindingConfiguration ; if ( ! isEmpty ( messageRef . getLookupName ( ) ) ) { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( messageRef . getLookupName ( ) ) ) ; bindings . add ( bindingConfiguration ) ; } else if ( ! isEmpty ( messageRef . getMappedName ( ) ) ) { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( messageRef . getMappedName ( ) ) ) ; bindings . add ( bindingConfiguration ) ; } else if ( ! isEmpty ( messageRef . getLink ( ) ) ) { final MessageDestinationInjectionSource messageDestinationInjectionSource = new MessageDestinationInjectionSource ( messageRef . getLink ( ) , name ) ; bindingConfiguration = new BindingConfiguration ( name , messageDestinationInjectionSource ) ; deploymentUnit . addToAttachmentList ( Attachments . MESSAGE_DESTINATIONS , messageDestinationInjectionSource ) ; bindings . add ( bindingConfiguration ) ; } else { ROOT_LOGGER . cannotResolve ( \"message-destination-ref\" , name ) ; } } return bindings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies web meta data to configure webservice stack transport and properties . [CODESPLIT] void modify ( final Deployment dep ) { final JBossWebMetaData jbossWebMD = WSHelper . getOptionalAttachment ( dep , JBossWebMetaData . class ) ; if ( jbossWebMD != null ) { this . configureEndpoints ( dep , jbossWebMD ) ; this . modifyContextRoot ( dep , jbossWebMD ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures transport servlet class for every found webservice endpoint . [CODESPLIT] private void configureEndpoints ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { final String transportClassName = this . getTransportClassName ( dep ) ; WSLogger . ROOT_LOGGER . trace ( \"Modifying servlets\" ) ; // get a list of the endpoint bean class names final Set < String > epNames = new HashSet < String > ( ) ; for ( Endpoint ep : dep . getService ( ) . getEndpoints ( ) ) { epNames . add ( ep . getTargetBeanName ( ) ) ; } // fix servlet class names for endpoints for ( final ServletMetaData servletMD : jbossWebMD . getServlets ( ) ) { final String endpointClassName = ASHelper . getEndpointClassName ( servletMD ) ; if ( endpointClassName != null && endpointClassName . length ( ) > 0 ) { // exclude JSP if ( epNames . contains ( endpointClassName ) ) { // set transport servlet servletMD . setServletClass ( WSFServlet . class . getName ( ) ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting transport class: %s for endpoint: %s\" , transportClassName , endpointClassName ) ; final List < ParamValueMetaData > initParams = WebMetaDataHelper . getServletInitParams ( servletMD ) ; // configure transport class name WebMetaDataHelper . newParamValue ( WSFServlet . STACK_SERVLET_DELEGATE_CLASS , transportClassName , initParams ) ; // configure webservice endpoint WebMetaDataHelper . newParamValue ( Endpoint . SEPID_DOMAIN_ENDPOINT , endpointClassName , initParams ) ; } else if ( endpointClassName . startsWith ( \"org.apache.cxf\" ) ) { throw WSLogger . ROOT_LOGGER . invalidWSServlet ( endpointClassName ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies context root . [CODESPLIT] private void modifyContextRoot ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { final String contextRoot = dep . getService ( ) . getContextRoot ( ) ; if ( WSLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { WSLogger . ROOT_LOGGER . tracef ( \"Setting context root: %s for deployment: %s\" , contextRoot , dep . getSimpleName ( ) ) ; } jbossWebMD . setContextRoot ( contextRoot ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns stack specific transport class name . [CODESPLIT] private String getTransportClassName ( final Deployment dep ) { String transportClassName = ( String ) dep . getProperty ( WSConstants . STACK_TRANSPORT_CLASS ) ; if ( transportClassName == null ) throw WSLogger . ROOT_LOGGER . missingDeploymentProperty ( WSConstants . STACK_TRANSPORT_CLASS ) ; return transportClassName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public synchronized T get ( MarshallingContext context ) throws IOException , ClassNotFoundException { if ( this . object == null ) { this . context = context ; if ( this . bytes != null ) { ByteArrayInputStream input = new ByteArrayInputStream ( this . bytes ) ; ClassLoader loader = setThreadContextClassLoader ( this . context . getClassLoader ( ) ) ; try ( SimpleDataInput data = new SimpleDataInput ( Marshalling . createByteInput ( input ) ) ) { int version = IndexSerializer . VARIABLE . readInt ( data ) ; try ( Unmarshaller unmarshaller = context . createUnmarshaller ( version ) ) { unmarshaller . start ( data ) ; this . object = ( T ) unmarshaller . readObject ( ) ; unmarshaller . finish ( ) ; this . bytes = null ; // Free up memory } } finally { setThreadContextClassLoader ( loader ) ; } } } return this . object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last date of the month represented by the passed <code > cal< / code > [CODESPLIT] public static int getLastDateOfMonth ( Calendar calendar ) { Calendar tmpCal = new GregorianCalendar ( calendar . getTimeZone ( ) ) ; tmpCal . set ( Calendar . YEAR , calendar . get ( Calendar . YEAR ) ) ; tmpCal . set ( Calendar . MONTH , calendar . get ( Calendar . MONTH ) ) ; tmpCal . set ( Calendar . DAY_OF_MONTH , 1 ) ; return tmpCal . getActualMaximum ( Calendar . DAY_OF_MONTH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes activation config properties which aren t recognized by the resource adapter <code > activation< / code > from the passed <code > activationConfigProps< / code > and returns only those Properties which are valid . [CODESPLIT] private Properties filterUnknownActivationConfigProperties ( final String resourceAdapterName , final Activation activation , final Properties activationConfigProps ) { if ( activationConfigProps == null ) { return null ; } final Map < String , Class < ? > > raActivationConfigProps = activation . getConfigProperties ( ) ; final Set < String > raRequiredConfigProps = activation . getRequiredConfigProperties ( ) ; final Enumeration < ? > propNames = activationConfigProps . propertyNames ( ) ; final Properties validActivationConfigProps = new Properties ( ) ; // initialize to all the activation config properties that have been set on the MDB validActivationConfigProps . putAll ( activationConfigProps ) ; while ( propNames . hasMoreElements ( ) ) { final Object propName = propNames . nextElement ( ) ; if ( raActivationConfigProps . containsKey ( propName ) == false && raRequiredConfigProps . contains ( propName ) == false ) { // not a valid activation config property, so log a WARN and filter it out from the valid activation config properties validActivationConfigProps . remove ( propName ) ; EjbLogger . ROOT_LOGGER . activationConfigPropertyIgnored ( propName , resourceAdapterName ) ; } } return validActivationConfigProps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link org . jboss . jca . core . spi . rar . Endpoint } corresponding to the passed <code > resourceAdapterName< / code > [CODESPLIT] private Endpoint getEndpoint ( final String resourceAdapterName ) { // first get the ra \"identifier\" (with which it is registered in the resource adapter repository) for the // ra name final String raIdentifier = ConnectorServices . getRegisteredResourceAdapterIdentifier ( resourceAdapterName ) ; if ( raIdentifier == null ) { throw EjbLogger . ROOT_LOGGER . unknownResourceAdapter ( resourceAdapterName ) ; } final ResourceAdapterRepository resourceAdapterRepository = resourceAdapterRepositoryInjectedValue . getValue ( ) ; if ( resourceAdapterRepository == null ) { throw EjbLogger . ROOT_LOGGER . resourceAdapterRepositoryUnAvailable ( ) ; } try { return resourceAdapterRepository . getEndpoint ( raIdentifier ) ; } catch ( NotFoundException nfe ) { throw EjbLogger . ROOT_LOGGER . noSuchEndpointException ( resourceAdapterName , nfe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a JBoss Security Context with the given security domain name [CODESPLIT] static SecurityContext createSecurityContext ( final String domain ) { if ( WildFlySecurityManager . isChecking ( ) ) { return WildFlySecurityManager . doUnchecked ( new PrivilegedAction < SecurityContext > ( ) { @ Override public SecurityContext run ( ) { try { return SecurityContextFactory . createSecurityContext ( domain ) ; } catch ( Exception e ) { throw UndertowLogger . ROOT_LOGGER . failToCreateSecurityContext ( e ) ; } } } ) ; } else { try { return SecurityContextFactory . createSecurityContext ( domain ) ; } catch ( Exception e ) { throw UndertowLogger . ROOT_LOGGER . failToCreateSecurityContext ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the { @code SecurityContext } on the { @code SecurityContextAssociation } [CODESPLIT] static void setSecurityContextOnAssociation ( final SecurityContext sc ) { if ( WildFlySecurityManager . isChecking ( ) ) { WildFlySecurityManager . doUnchecked ( new PrivilegedAction < Void > ( ) { @ Override public Void run ( ) { SecurityContextAssociation . setSecurityContext ( sc ) ; return null ; } } ) ; } else { SecurityContextAssociation . setSecurityContext ( sc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current { @code SecurityContext } [CODESPLIT] static SecurityContext getSecurityContext ( ) { if ( WildFlySecurityManager . isChecking ( ) ) { return WildFlySecurityManager . doUnchecked ( new PrivilegedAction < SecurityContext > ( ) { public SecurityContext run ( ) { return SecurityContextAssociation . getSecurityContext ( ) ; } } ) ; } else { return SecurityContextAssociation . getSecurityContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears current { [CODESPLIT] static void clearSecurityContext ( ) { if ( WildFlySecurityManager . isChecking ( ) ) { WildFlySecurityManager . doUnchecked ( new PrivilegedAction < Void > ( ) { public Void run ( ) { SecurityContextAssociation . clearSecurityContext ( ) ; return null ; } } ) ; } else { SecurityContextAssociation . clearSecurityContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the run as identity [CODESPLIT] static RunAs setRunAsIdentity ( final RunAs principal , final SecurityContext sc ) { if ( WildFlySecurityManager . isChecking ( ) ) { return WildFlySecurityManager . doUnchecked ( new PrivilegedAction < RunAs > ( ) { @ Override public RunAs run ( ) { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs old = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( principal ) ; return old ; } } ) ; } else { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs old = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( principal ) ; return old ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the run as identity [CODESPLIT] static RunAs popRunAsIdentity ( final SecurityContext sc ) { if ( WildFlySecurityManager . isChecking ( ) ) { return AccessController . doPrivileged ( new PrivilegedAction < RunAs > ( ) { @ Override public RunAs run ( ) { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs principal = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( null ) ; return principal ; } } ) ; } else { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs principal = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( null ) ; return principal ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo move to UndertowDeploymentService and use all registered servlets from Deployment instead of just one found by metadata [CODESPLIT] void processManagement ( final DeploymentUnit unit , JBossWebMetaData metaData ) { final DeploymentResourceSupport deploymentResourceSupport = unit . getAttachment ( Attachments . DEPLOYMENT_RESOURCE_SUPPORT ) ; for ( final JBossServletMetaData servlet : metaData . getServlets ( ) ) { try { final String name = servlet . getName ( ) ; final ModelNode node = deploymentResourceSupport . getDeploymentSubModel ( UndertowExtension . SUBSYSTEM_NAME , PathElement . pathElement ( \"servlet\" , name ) ) ; node . get ( \"servlet-class\" ) . set ( servlet . getServletClass ( ) ) ; node . get ( \"servlet-name\" ) . set ( servlet . getServletName ( ) ) ; } catch ( Exception e ) { // Should a failure in creating the mgmt view also make to the deployment to fail? continue ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to obtain the security domain configured in jboss - app . xml at the ear level if available [CODESPLIT] private String getJBossAppSecurityDomain ( final DeploymentUnit deploymentUnit ) { String securityDomain = null ; DeploymentUnit parent = deploymentUnit . getParent ( ) ; if ( parent != null ) { final EarMetaData jbossAppMetaData = parent . getAttachment ( org . jboss . as . ee . structure . Attachments . EAR_METADATA ) ; if ( jbossAppMetaData instanceof JBossAppMetaData ) { securityDomain = ( ( JBossAppMetaData ) jbossAppMetaData ) . getSecurityDomain ( ) ; } } return securityDomain != null ? securityDomain . trim ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof ContainedOperations ) defined_in_id = ( ( ContainedOperations ) defined_in ) . id ( ) ; ConstantDescription d = new ConstantDescription ( name , id , defined_in_id , version , typeCode , value ) ; Any any = getORB ( ) . create_any ( ) ; ConstantDescriptionHelper . insert ( any , d ) ; return new Description ( DefinitionKind . dk_Constant , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install a binder service to bind the { @code obj } using the binding { @code name } . [CODESPLIT] public static void installBinderService ( final ServiceTarget serviceTarget , final String name , final Object obj ) { final BindInfo bindInfo = ContextNames . bindInfoFor ( name ) ; final BinderService binderService = new BinderService ( bindInfo . getBindName ( ) ) ; binderService . getManagedObjectInjector ( ) . inject ( new ValueManagedReferenceFactory ( Values . immediateValue ( obj ) ) ) ; serviceTarget . addService ( bindInfo . getBinderServiceName ( ) , binderService ) . addDependency ( bindInfo . getParentContextServiceName ( ) , ServiceBasedNamingStore . class , binderService . getNamingStoreInjector ( ) ) . install ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install a binder service to bind the value of the { @code service } using the binding { @code name } . [CODESPLIT] public static void installBinderService ( final ServiceTarget serviceTarget , final String name , final Service < ? > service , final ServiceName dependency ) { final BindInfo bindInfo = ContextNames . bindInfoFor ( name ) ; final BinderService binderService = new BinderService ( bindInfo . getBindName ( ) ) ; binderService . getManagedObjectInjector ( ) . inject ( new ValueManagedReferenceFactory ( service ) ) ; final ServiceBuilder serviceBuilder = serviceTarget . addService ( bindInfo . getBinderServiceName ( ) , binderService ) . addDependency ( bindInfo . getParentContextServiceName ( ) , ServiceBasedNamingStore . class , binderService . getNamingStoreInjector ( ) ) // we set it in passive mode so that missing dependencies (which is possible/valid when it's a backup HornetQ server and the services // haven't been activated on it due to the presence of a different live server) don't cause jms-topic/jms-queue add operations // to fail . setInitialMode ( ServiceController . Mode . PASSIVE ) ; if ( dependency != null ) { serviceBuilder . requires ( dependency ) ; } serviceBuilder . install ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overrides the default impl to use a special definition of the add op that includes additional parameter { [CODESPLIT] @ Override protected void registerAddOperation ( ManagementResourceRegistration registration , AbstractAddStepHandler handler , OperationEntry . Flag ... flags ) { OperationDefinition od = new SimpleOperationDefinitionBuilder ( ADD , getResourceDescriptionResolver ( ) ) . setParameters ( ATTRIBUTES ) . addParameter ( DEFAULT_CLUSTERED_SFSB_CACHE ) . withFlags ( flags ) . build ( ) ; registration . registerOperationHandler ( od , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject a value into an object property [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void inject ( Object object , String propertyName , Object propertyValue ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { inject ( object , propertyName , propertyValue , null , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare the type of a class with the actual value [CODESPLIT] private boolean argumentMatches ( String classType , String propertyType ) { return ( classType . equals ( propertyType ) ) || ( classType . equals ( \"java.lang.Byte\" ) && propertyType . equals ( \"byte\" ) ) || ( classType . equals ( \"java.lang.Short\" ) && propertyType . equals ( \"short\" ) ) || ( classType . equals ( \"java.lang.Integer\" ) && propertyType . equals ( \"int\" ) ) || ( classType . equals ( \"java.lang.Long\" ) && propertyType . equals ( \"long\" ) ) || ( classType . equals ( \"java.lang.Float\" ) && propertyType . equals ( \"float\" ) ) || ( classType . equals ( \"java.lang.Double\" ) && propertyType . equals ( \"double\" ) ) || ( classType . equals ( \"java.lang.Boolean\" ) && propertyType . equals ( \"boolean\" ) ) || ( classType . equals ( \"java.lang.Character\" ) && propertyType . equals ( \"char\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a method [CODESPLIT] protected Method findMethod ( Class < ? > clz , String methodName , String propertyType ) { while ( ! clz . equals ( Object . class ) ) { List < Method > hits = null ; Method [ ] methods = SecurityActions . getDeclaredMethods ( clz ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { final Method method = methods [ i ] ; if ( methodName . equals ( method . getName ( ) ) && method . getParameterTypes ( ) . length == 1 ) { if ( propertyType == null || argumentMatches ( propertyType , method . getParameterTypes ( ) [ 0 ] . getName ( ) ) ) { if ( hits == null ) hits = new ArrayList < Method > ( 1 ) ; SecurityActions . setAccessible ( method ) ; hits . add ( method ) ; } } } if ( hits != null ) { if ( hits . size ( ) == 1 ) { return hits . get ( 0 ) ; } else { Collections . sort ( hits , new MethodSorter ( ) ) ; if ( propertyType != null ) { for ( Method m : hits ) { if ( propertyType . equals ( m . getParameterTypes ( ) [ 0 ] . getName ( ) ) ) return m ; } } return hits . get ( 0 ) ; } } clz = clz . getSuperclass ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a field [CODESPLIT] protected Field findField ( Class < ? > clz , String fieldName , String fieldType ) { while ( ! clz . equals ( Object . class ) ) { List < Field > hits = null ; Field [ ] fields = SecurityActions . getDeclaredFields ( clz ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { final Field field = fields [ i ] ; if ( fieldName . equals ( field . getName ( ) ) ) { if ( fieldType == null || argumentMatches ( fieldType , field . getType ( ) . getName ( ) ) ) { if ( hits == null ) hits = new ArrayList < Field > ( 1 ) ; SecurityActions . setAccessible ( field ) ; hits . add ( field ) ; } } } if ( hits != null ) { if ( hits . size ( ) == 1 ) { return hits . get ( 0 ) ; } else { Collections . sort ( hits , new FieldSorter ( ) ) ; if ( fieldType != null ) { for ( Field f : hits ) { if ( fieldType . equals ( f . getType ( ) . getName ( ) ) ) return f ; } } return hits . get ( 0 ) ; } } clz = clz . getSuperclass ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object processInvocation ( final InterceptorContext context ) throws Exception { final ManagedReference reference = ( ManagedReference ) context . getPrivateData ( ComponentInstance . class ) . getInstanceData ( contextKey ) ; final Object instance = reference . getInstance ( ) ; try { final Method method = this . method ; if ( withContext ) { final Method oldMethod = context . getMethod ( ) ; try { if ( this . lifecycleMethod ) { // because InvocationContext#getMethod() is expected to return null for lifecycle methods context . setMethod ( null ) ; return method . invoke ( instance , context . getInvocationContext ( ) ) ; } else if ( this . changeMethod ) { context . setMethod ( method ) ; return method . invoke ( instance , context . getInvocationContext ( ) ) ; } else { return method . invoke ( instance , context . getInvocationContext ( ) ) ; } } finally { // reset any changed method on the interceptor context context . setMethod ( oldMethod ) ; } } else { method . invoke ( instance ) ; return context . proceed ( ) ; } } catch ( IllegalAccessException e ) { final IllegalAccessError n = new IllegalAccessError ( e . getMessage ( ) ) ; n . setStackTrace ( e . getStackTrace ( ) ) ; throw n ; } catch ( InvocationTargetException e ) { throw Interceptors . rethrow ( e . getCause ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for standard ra deployment files . Will parse the xml file and attach a configuration discovered during processing . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; boolean resolveProperties = Util . shouldResolveJBoss ( deploymentUnit ) ; final PropertyResolver propertyResolver = deploymentUnit . getAttachment ( org . jboss . as . ee . metadata . property . Attachments . FINAL_PROPERTY_RESOLVER ) ; final PropertyReplacer propertyReplacer = deploymentUnit . getAttachment ( org . jboss . as . ee . metadata . property . Attachments . FINAL_PROPERTY_REPLACER ) ; final Set < VirtualFile > files = dataSources ( deploymentUnit ) ; boolean loggedDeprication = false ; for ( VirtualFile f : files ) { InputStream xmlStream = null ; try { xmlStream = new FileInputStream ( f . getPhysicalFile ( ) ) ; DsXmlParser parser = new DsXmlParser ( propertyResolver , propertyReplacer ) ; parser . setSystemPropertiesResolved ( resolveProperties ) ; DataSources dataSources = parser . parse ( xmlStream ) ; if ( dataSources != null ) { if ( ! loggedDeprication ) { loggedDeprication = true ; ConnectorLogger . ROOT_LOGGER . deprecated ( ) ; } for ( DataSource ds : dataSources . getDataSource ( ) ) { if ( ds . getDriver ( ) == null ) { throw ConnectorLogger . ROOT_LOGGER . FailedDeployDriverNotSpecified ( ds . getJndiName ( ) ) ; } } deploymentUnit . addToAttachmentList ( DATA_SOURCES_ATTACHMENT_KEY , dataSources ) ; } } catch ( Exception e ) { throw new DeploymentUnitProcessingException ( e . getMessage ( ) , e ) ; } finally { VFSUtils . safeClose ( xmlStream ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "escape any occurrence of / . and \\ [CODESPLIT] private static String escape ( String s ) { StringBuffer sb = new StringBuffer ( s ) ; for ( int i = 0 ; i < sb . length ( ) ; i ++ ) { if ( sb . charAt ( i ) == ' ' || sb . charAt ( i ) == ' ' || sb . charAt ( i ) == ' ' ) { sb . insert ( i , ' ' ) ; i ++ ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build options for non - interactive VaultTool usage scenario . [CODESPLIT] private void initOptions ( ) { options = new Options ( ) ; options . addOption ( \"k\" , KEYSTORE_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineKeyStoreURL ( ) ) ; options . addOption ( \"p\" , KEYSTORE_PASSWORD_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineKeyStorePassword ( ) ) ; options . addOption ( \"e\" , ENC_DIR_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineEncryptionDirectory ( ) ) ; options . addOption ( \"s\" , SALT_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineSalt ( ) ) ; options . addOption ( \"i\" , ITERATION_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineIterationCount ( ) ) ; options . addOption ( \"v\" , ALIAS_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineVaultKeyStoreAlias ( ) ) ; options . addOption ( \"b\" , VAULT_BLOCK_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineVaultBlock ( ) ) ; options . addOption ( \"a\" , ATTRIBUTE_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineAttributeName ( ) ) ; options . addOption ( \"t\" , CREATE_KEYSTORE_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineAutomaticallyCreateKeystore ( ) ) ; OptionGroup og = new OptionGroup ( ) ; Option x = new Option ( \"x\" , SEC_ATTR_VALUE_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineSecuredAttribute ( ) ) ; Option c = new Option ( \"c\" , CHECK_SEC_ATTR_EXISTS_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineCheckAttribute ( ) ) ; Option r = new Option ( \"r\" , REMOVE_SEC_ATTR_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineRemoveSecuredAttribute ( ) ) ; Option h = new Option ( \"h\" , HELP_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineHelp ( ) ) ; og . addOption ( x ) ; og . addOption ( c ) ; og . addOption ( r ) ; og . addOption ( h ) ; og . setRequired ( true ) ; options . addOptionGroup ( og ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof ContainedOperations ) defined_in_id = ( ( ContainedOperations ) defined_in ) . id ( ) ; TypeDescription td = new TypeDescription ( name , id , defined_in_id , version , typeCode ) ; Any any = getORB ( ) . create_any ( ) ; TypeDescriptionHelper . insert ( any , td ) ; return new Description ( DefinitionKind . dk_Typedef , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( final XMLExtendedStreamReader reader , final List < ModelNode > list ) throws XMLStreamException { ParseUtils . requireNoAttributes ( reader ) ; ParseUtils . requireNoContent ( reader ) ; final ModelNode ejb3Subsystem = new ModelNode ( ) ; ejb3Subsystem . get ( OP ) . set ( ADD ) ; ejb3Subsystem . get ( OP_ADDR ) . add ( SUBSYSTEM , EJB3Extension . SUBSYSTEM_NAME ) ; list . add ( ejb3Subsystem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain debug information from the servlet request object [CODESPLIT] private static String deriveUsefulInfo ( HttpServletRequest httpRequest ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( \"[\" ) . append ( httpRequest . getContextPath ( ) ) ; sb . append ( \":cookies=\" ) . append ( Arrays . toString ( httpRequest . getCookies ( ) ) ) . append ( \":headers=\" ) ; // Append Header information Enumeration < ? > en = httpRequest . getHeaderNames ( ) ; while ( en . hasMoreElements ( ) ) { String headerName = ( String ) en . nextElement ( ) ; sb . append ( headerName ) . append ( \"=\" ) ; // Ensure HTTP Basic Password is not logged if ( ! headerName . contains ( \"authorization\" ) ) { sb . append ( httpRequest . getHeader ( headerName ) ) . append ( \",\" ) ; } } sb . append ( \"]\" ) ; // Append Request parameter information sb . append ( \"[parameters=\" ) ; Enumeration < ? > enparam = httpRequest . getParameterNames ( ) ; while ( enparam . hasMoreElements ( ) ) { String paramName = ( String ) enparam . nextElement ( ) ; String [ ] paramValues = httpRequest . getParameterValues ( paramName ) ; int len = paramValues != null ? paramValues . length : 0 ; for ( int i = 0 ; i < len ; i ++ ) { sb . append ( paramValues [ i ] ) . append ( \"::\" ) ; } sb . append ( \",\" ) ; } sb . append ( \"][attributes=\" ) ; // Append Request attribute information Enumeration < ? > enu = httpRequest . getAttributeNames ( ) ; while ( enu . hasMoreElements ( ) ) { String attrName = ( String ) enu . nextElement ( ) ; sb . append ( attrName ) . append ( \"=\" ) ; sb . append ( httpRequest . getAttribute ( attrName ) ) . append ( \",\" ) ; } sb . append ( \"]\" ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public String getSessionCookieName ( ) { SessionCookieConfig override = server . getServletContainer ( ) . getSessionCookieConfig ( ) ; if ( override == null || override . getName ( ) == null ) { return io . undertow . server . session . SessionCookieConfig . DEFAULT_SESSION_ID ; } return override . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect a JDR report when run outside the Application Server . [CODESPLIT] public JdrReport standaloneCollect ( CLI cli , String protocol , String host , int port ) throws OperationFailedException { return new JdrRunner ( cli , protocol , host , port , null , null ) . collect ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect a JDR report . [CODESPLIT] public JdrReport collect ( ) throws OperationFailedException { JdrRunner runner = new JdrRunner ( true ) ; serverEnvironment = serverEnvironmentValue . getValue ( ) ; runner . setJbossHomeDir ( serverEnvironment . getHomeDir ( ) . getAbsolutePath ( ) ) ; runner . setReportLocationDir ( serverEnvironment . getServerTempDir ( ) . getAbsolutePath ( ) ) ; runner . setControllerClient ( controllerClient ) ; runner . setHostControllerName ( serverEnvironment . getHostControllerName ( ) ) ; runner . setServerName ( serverEnvironment . getServerName ( ) ) ; return runner . collect ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a resource adapter deployment [CODESPLIT] public void registerResourceAdapterDeployment ( ResourceAdapterDeployment deployment ) { if ( deployment == null ) throw new IllegalArgumentException ( ConnectorLogger . ROOT_LOGGER . nullVar ( \"Deployment\" ) ) ; DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER . tracef ( \"Adding deployment: %s\" , deployment ) ; deployments . add ( deployment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregister a resource adapter deployment [CODESPLIT] public void unregisterResourceAdapterDeployment ( ResourceAdapterDeployment deployment ) { if ( deployment == null ) throw new IllegalArgumentException ( ConnectorLogger . ROOT_LOGGER . nullVar ( \"Deployment\" ) ) ; DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER . tracef ( \"Removing deployment: %s\" , deployment ) ; deployments . remove ( deployment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void performBoottime ( OperationContext context , ModelNode operation , Resource resource ) throws OperationFailedException { try { Class . forName ( \"org.apache.jasper.compiler.JspRuntimeContext\" , true , this . getClass ( ) . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { UndertowLogger . ROOT_LOGGER . couldNotInitJsp ( e ) ; } final ModelNode model = resource . getModel ( ) ; final String defaultVirtualHost = UndertowRootDefinition . DEFAULT_VIRTUAL_HOST . resolveModelAttribute ( context , model ) . asString ( ) ; final String defaultContainer = UndertowRootDefinition . DEFAULT_SERVLET_CONTAINER . resolveModelAttribute ( context , model ) . asString ( ) ; final String defaultServer = UndertowRootDefinition . DEFAULT_SERVER . resolveModelAttribute ( context , model ) . asString ( ) ; final boolean stats = UndertowRootDefinition . STATISTICS_ENABLED . resolveModelAttribute ( context , model ) . asBoolean ( ) ; final String defaultSecurityDomain = UndertowRootDefinition . DEFAULT_SECURITY_DOMAIN . resolveModelAttribute ( context , model ) . asString ( ) ; final ModelNode instanceIdModel = UndertowRootDefinition . INSTANCE_ID . resolveModelAttribute ( context , model ) ; final String instanceId = instanceIdModel . isDefined ( ) ? instanceIdModel . asString ( ) : null ; DefaultDeploymentMappingProvider . instance ( ) . clear ( ) ; //we clear provider on system boot, as on reload it could cause issues. context . getCapabilityServiceTarget ( ) . addCapability ( UndertowRootDefinition . UNDERTOW_CAPABILITY , new UndertowService ( defaultContainer , defaultServer , defaultVirtualHost , instanceId , stats ) ) . setInitialMode ( ServiceController . Mode . ACTIVE ) . addAliases ( UndertowService . UNDERTOW ) . install ( ) ; context . addStep ( new AbstractDeploymentChainStep ( ) { @ Override protected void execute ( DeploymentProcessorTarget processorTarget ) { final SharedTldsMetaDataBuilder sharedTldsBuilder = new SharedTldsMetaDataBuilder ( model . clone ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . STRUCTURE , Phase . STRUCTURE_EXPLODED_MOUNT , new DeploymentRootExplodedMountProcessor ( ) ) ; JBossAllXmlParserRegisteringProcessor . Builder builder = JBossAllXmlParserRegisteringProcessor . builder ( ) ; for ( SharedSessionConfigSchema schema : EnumSet . allOf ( SharedSessionConfigSchema . class ) ) { builder . addParser ( schema . getRoot ( ) , SharedSessionManagerConfig . ATTACHMENT_KEY , new SharedSessionConfigParser ( schema ) ) ; } processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . STRUCTURE , Phase . STRUCTURE_REGISTER_JBOSS_ALL_UNDERTOW_SHARED_SESSION , builder . build ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . STRUCTURE , Phase . STRUCTURE_REGISTER_JBOSS_ALL_WEB , new JBossAllXmlParserRegisteringProcessor <> ( WebJBossAllParser . ROOT_ELEMENT , WebJBossAllParser . ATTACHMENT_KEY , new WebJBossAllParser ( ) ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . STRUCTURE , Phase . STRUCTURE_WAR_DEPLOYMENT_INIT , new WarDeploymentInitializingProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . STRUCTURE , Phase . STRUCTURE_WAR , new WarStructureDeploymentProcessor ( sharedTldsBuilder ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_WEB_DEPLOYMENT , new WebParsingDeploymentProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_WEB_DEPLOYMENT_FRAGMENT , new WebFragmentParsingDeploymentProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_JBOSS_WEB_DEPLOYMENT , new JBossWebParsingDeploymentProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_ANNOTATION_WAR , new WarAnnotationDeploymentProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_EAR_CONTEXT_ROOT , new EarContextRootProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_WEB_MERGE_METADATA , new WarMetaDataProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_WEB_MERGE_METADATA + 1 , new TldParsingDeploymentProcessor ( ) ) ; //todo: fix priority processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_WEB_MERGE_METADATA + 2 , new org . wildfly . extension . undertow . deployment . WebComponentProcessor ( ) ) ; //todo: fix priority processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . PARSE , Phase . PARSE_WEB_MERGE_METADATA + 3 , new DefaultSecurityDomainProcessor ( defaultSecurityDomain ) ) ; //todo: fix priority processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . DEPENDENCIES , Phase . DEPENDENCIES_WAR_MODULE , new UndertowDependencyProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . POST_MODULE , Phase . POST_MODULE_UNDERTOW_WEBSOCKETS , new UndertowJSRWebSocketDeploymentProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . POST_MODULE , Phase . POST_MODULE_UNDERTOW_HANDLERS , new UndertowHandlersDeploymentProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . POST_MODULE , Phase . POST_MODULE_UNDERTOW_HANDLERS + 1 , new ExternalTldParsingDeploymentProcessor ( ) ) ; //todo: fix priority processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . POST_MODULE , Phase . POST_MODULE_UNDERTOW_HANDLERS + 2 , new UndertowServletContainerDependencyProcessor ( defaultContainer ) ) ; //todo: fix priority processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . INSTALL , Phase . INSTALL_SHARED_SESSION_MANAGER , new SharedSessionManagerDeploymentProcessor ( defaultServer ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . INSTALL , Phase . INSTALL_SERVLET_INIT_DEPLOYMENT , new ServletContainerInitializerDeploymentProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( UndertowExtension . SUBSYSTEM_NAME , Phase . INSTALL , Phase . INSTALL_WAR_DEPLOYMENT , new UndertowDeploymentProcessor ( defaultVirtualHost , defaultContainer , defaultServer , defaultSecurityDomain , knownSecurityDomain ) ) ; } } , OperationContext . Stage . RUNTIME ) ; context . getCapabilityServiceTarget ( ) . addCapability ( HTTP_INVOKER_RUNTIME_CAPABILITY , new RemoteHttpInvokerService ( ) ) . install ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > JASPIC 1 . 1 specification : if there is an { @code AuthConfigProvider } for the { @code HttpServlet } layer and application context then @ { @code login } must throw a { @code ServletException } which may convey that the exception was caused by an incompatibility between the { @code login } method and the configured authentication mechanism . If there is no such provider then the container must proceed with the regular { @code login } processing . < / p > [CODESPLIT] @ Override public boolean login ( final String username , final String password ) { // if there is an AuthConfigProvider for the HttpServlet layer and appContext, this method must throw an exception. String appContext = this . buildAppContext ( ) ; AuthConfigProvider provider = AuthConfigFactory . getFactory ( ) . getConfigProvider ( layer , appContext , null ) ; if ( provider != null ) { ServletException se = new ServletException ( \"login is not supported by the JASPIC mechanism\" ) ; throw new SecurityException ( se ) ; } return super . login ( username , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > JASPIC 1 . 1 specification : if there is an { [CODESPLIT] @ Override public void logout ( ) { if ( ! isAuthenticated ( ) ) return ; // call cleanSubject() if there is an AuthConfigProvider for the HttpServlet layer and appContext. String appContext = this . buildAppContext ( ) ; if ( AuthConfigFactory . getFactory ( ) . getConfigProvider ( layer , appContext , null ) != null ) { Subject authenticatedSubject = this . getAuthenticatedSubject ( ) ; MessageInfo messageInfo = this . buildMessageInfo ( ) ; this . manager . cleanSubject ( messageInfo , authenticatedSubject , layer , appContext , handler ) ; } // following the return from cleanSubject(), logout must perform the regular logout processing. super . logout ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Overrides the parent method to return the cached authenticated account ( that is the account that was set in the session as a result of a SAM setting the { @code javax . servlet . http . registerSession } property ) when the regular account is null . This allows a SAM to retrieve the cached account principal by calling { @code getUserPrincipal () } on { @code HttpServletRequest } . < / p > [CODESPLIT] @ Override public Account getAuthenticatedAccount ( ) { Account account = super . getAuthenticatedAccount ( ) ; if ( account == null ) account = this . cachedAuthenticatedAccount ; return account ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Builds the JASPIC application context . < / p > [CODESPLIT] private String buildAppContext ( ) { final ServletRequestContext requestContext = exchange . getAttachment ( ServletRequestContext . ATTACHMENT_KEY ) ; ServletRequest servletRequest = requestContext . getServletRequest ( ) ; return servletRequest . getServletContext ( ) . getVirtualServerName ( ) + \" \" + servletRequest . getServletContext ( ) . getContextPath ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Builds the { @code MessageInfo } instance for the { @code cleanSubject () } call . < / p > [CODESPLIT] private MessageInfo buildMessageInfo ( ) { ServletRequestContext servletRequestContext = exchange . getAttachment ( ServletRequestContext . ATTACHMENT_KEY ) ; GenericMessageInfo messageInfo = new GenericMessageInfo ( ) ; messageInfo . setRequestMessage ( servletRequestContext . getServletRequest ( ) ) ; messageInfo . setResponseMessage ( servletRequestContext . getServletResponse ( ) ) ; // when calling cleanSubject, isMandatory must be set to true. messageInfo . getMap ( ) . put ( \"javax.security.auth.message.MessagePolicy.isMandatory\" , \"true\" ) ; return messageInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Retrieves the authenticated subject from the underlying security context . < / p > [CODESPLIT] private Subject getAuthenticatedSubject ( ) { Subject subject = null ; org . jboss . security . SecurityContext picketBoxContext = SecurityActions . getSecurityContext ( ) ; if ( picketBoxContext != null && picketBoxContext . getSubjectInfo ( ) != null ) subject = picketBoxContext . getSubjectInfo ( ) . getAuthenticatedSubject ( ) ; return subject != null ? subject : new Subject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a { @code name } attribute on an element . [CODESPLIT] static String readNameAttribute ( final XMLExtendedStreamReader reader ) throws XMLStreamException { return readRequiredAttributes ( reader , EnumSet . of ( Attribute . NAME ) ) . get ( Attribute . NAME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a { @code value } attribute on an element . [CODESPLIT] static String readValueAttribute ( final XMLExtendedStreamReader reader ) throws XMLStreamException { return readRequiredAttributes ( reader , EnumSet . of ( Attribute . VALUE ) ) . get ( Attribute . VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the required attributes from an XML configuration . <p > The reader must be on an element with attributes . < / p > [CODESPLIT] static Map < Attribute , String > readRequiredAttributes ( final XMLExtendedStreamReader reader , final Set < Attribute > attributes ) throws XMLStreamException { final int attributeCount = reader . getAttributeCount ( ) ; final Map < Attribute , String > result = new EnumMap <> ( Attribute . class ) ; for ( int i = 0 ; i < attributeCount ; i ++ ) { final Attribute current = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; if ( attributes . contains ( current ) ) { if ( result . put ( current , reader . getAttributeValue ( i ) ) != null ) { throw ParseUtils . duplicateAttribute ( reader , current . getLocalName ( ) ) ; } } else { throw ParseUtils . unexpectedAttribute ( reader , i , attributes . stream ( ) . map ( Attribute :: getLocalName ) . collect ( Collectors . toSet ( ) ) ) ; } } if ( result . isEmpty ( ) ) { throw ParseUtils . missingRequired ( reader , attributes . stream ( ) . map ( Attribute :: getLocalName ) . collect ( Collectors . toSet ( ) ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add dependencies for modules required for JPA deployments [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; // all applications get the javax.persistence module added to their deplyoment by default addDependency ( moduleSpecification , moduleLoader , deploymentUnit , JAVAX_PERSISTENCE_API_ID , HIBERNATE_TRANSFORMER_ID ) ; if ( ! JPADeploymentMarker . isJPADeployment ( deploymentUnit ) ) { return ; // Skip if there are no persistence use in the deployment } addDependency ( moduleSpecification , moduleLoader , deploymentUnit , JBOSS_AS_JPA_ID , JBOSS_AS_JPA_SPI_ID ) ; addPersistenceProviderModuleDependencies ( phaseContext , moduleSpecification , moduleLoader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the <code > puServiceName< / code > as a dependency on each of the passed <code > components< / code > [CODESPLIT] private static void addPUServiceDependencyToComponents ( final Collection < ComponentDescription > components , final PersistenceUnitMetadataHolder holder ) { if ( components == null || components . isEmpty ( ) || holder == null ) { return ; } for ( PersistenceUnitMetadata pu : holder . getPersistenceUnits ( ) ) { String jpaContainerManaged = pu . getProperties ( ) . getProperty ( Configuration . JPA_CONTAINER_MANAGED ) ; boolean deployPU = ( jpaContainerManaged == null ? true : Boolean . parseBoolean ( jpaContainerManaged ) ) ; if ( deployPU ) { final ServiceName puServiceName = PersistenceUnitServiceImpl . getPUServiceName ( pu ) ; for ( final ComponentDescription component : components ) { ROOT_LOGGER . debugf ( \"Adding dependency on PU service %s for component %s\" , puServiceName , component . getComponentClassName ( ) ) ; component . addDependency ( puServiceName ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the transformers for the 1 . 3 . 0 version . [CODESPLIT] protected static void registerTransformers ( final SubsystemRegistration subsystem ) { ChainedTransformationDescriptionBuilder chained = ResourceTransformationDescriptionBuilder . Factory . createChainedSubystemInstance ( CURRENT_MODEL_VERSION ) ; ModelVersion MODEL_VERSION_EAP64 = ModelVersion . create ( 1 , 4 , 0 ) ; ModelVersion MODEL_VERSION_EAP63 = ModelVersion . create ( 1 , 3 , 0 ) ; //also EAP6.2 ResourceTransformationDescriptionBuilder builder64 = chained . createBuilder ( CURRENT_MODEL_VERSION , MODEL_VERSION_EAP64 ) ; builder64 . getAttributeBuilder ( ) . addRejectCheck ( RejectAttributeChecker . DEFINED , JacORBSubsystemDefinitions . PERSISTENT_SERVER_ID ) . setDiscard ( new DiscardAttributeChecker . DiscardAttributeValueChecker ( JacORBSubsystemDefinitions . PERSISTENT_SERVER_ID . getDefaultValue ( ) ) , JacORBSubsystemDefinitions . PERSISTENT_SERVER_ID ) . setValueConverter ( new AttributeConverter . DefaultValueAttributeConverter ( JacORBSubsystemDefinitions . INTEROP_CHUNK_RMI_VALUETYPES ) , JacORBSubsystemDefinitions . INTEROP_CHUNK_RMI_VALUETYPES ) ; ResourceTransformationDescriptionBuilder builder63 = chained . createBuilder ( MODEL_VERSION_EAP64 , MODEL_VERSION_EAP63 ) ; builder63 . getAttributeBuilder ( ) . addRejectCheck ( RejectAttributeChecker . DEFINED , IORTransportConfigDefinition . ATTRIBUTES . toArray ( new AttributeDefinition [ 0 ] ) ) . addRejectCheck ( RejectAttributeChecker . DEFINED , IORASContextDefinition . ATTRIBUTES . toArray ( new AttributeDefinition [ 0 ] ) ) . addRejectCheck ( RejectAttributeChecker . DEFINED , IORSASContextDefinition . ATTRIBUTES . toArray ( new AttributeDefinition [ 0 ] ) ) . end ( ) . rejectChildResource ( IORSettingsDefinition . INSTANCE . getPathElement ( ) ) ; chained . buildAndRegister ( subsystem , new ModelVersion [ ] { MODEL_VERSION_EAP64 , MODEL_VERSION_EAP63 } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > StubStrategy< / code > for a method given descriptions of the method parameters exceptions and return value . Parameter and return value descriptions are marshaller abbreviated names . [CODESPLIT] public static StubStrategy forMethod ( String [ ] paramTypes , String [ ] excepIds , String [ ] excepTypes , String retvalType , ClassLoader cl ) { // This \"factory method\" exists just because I have found it easier // to invoke a static method (rather than invoking operator new) // from a stub class dynamically assembled by an instance of // org.jboss.proxy.ProxyAssembler. return new StubStrategy ( paramTypes , excepIds , excepTypes , retvalType , cl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marshals the sequence of method parameters into an output stream . [CODESPLIT] public void writeParams ( OutputStream out , Object [ ] params ) { int len = params . length ; if ( len != paramWriters . length ) { throw IIOPLogger . ROOT_LOGGER . errorMashalingParams ( ) ; } for ( int i = 0 ; i < len ; i ++ ) { Object param = params [ i ] ; if ( param instanceof PortableRemoteObject ) { try { param = PortableRemoteObject . toStub ( ( Remote ) param ) ; } catch ( NoSuchObjectException e ) { throw new RuntimeException ( e ) ; } } paramWriters [ i ] . write ( out , RemoteObjectSubstitutionManager . writeReplaceRemote ( param ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unmarshals from an input stream an exception thrown by the method . [CODESPLIT] public Exception readException ( String id , InputStream in ) { ExceptionReader exceptionReader = ( ExceptionReader ) exceptionMap . get ( id ) ; if ( exceptionReader == null ) { return new UnexpectedException ( id ) ; } else { return exceptionReader . read ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a given <code > Throwable< / code > instance corresponds to an exception declared by this <code > StubStrategy< / code > s method . [CODESPLIT] public boolean isDeclaredException ( Throwable t ) { Iterator < Class < ? > > iterator = exceptionList . iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( ( ( Class < ? > ) iterator . next ( ) ) . isInstance ( t ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the return value of a local invocation into the expected type . A conversion is needed if the return value is a remote interface ( in this case <code > PortableRemoteObject . narrow () < / code > must be called ) . [CODESPLIT] public Object convertLocalRetval ( Object obj ) { if ( retvalRemoteInterface == null ) return obj ; else return PortableRemoteObject . narrow ( obj , retvalRemoteInterface ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public synchronized void start ( StartContext context ) throws StartException { if ( createQueue ) { try { final ActiveMQServer server = this . activeMQServerSupplier . get ( ) ; MessagingLogger . ROOT_LOGGER . debugf ( \"Deploying queue on server %s with address: %s ,  name: %s, filter: %s ands durable: %s, temporary: %s\" , server . getNodeID ( ) , new SimpleString ( queueConfiguration . getAddress ( ) ) , new SimpleString ( queueConfiguration . getName ( ) ) , SimpleString . toSimpleString ( queueConfiguration . getFilterString ( ) ) , queueConfiguration . isDurable ( ) , temporary ) ; final SimpleString resourceName = new SimpleString ( queueConfiguration . getName ( ) ) ; final SimpleString address = new SimpleString ( queueConfiguration . getAddress ( ) ) ; final SimpleString filterString = SimpleString . toSimpleString ( queueConfiguration . getFilterString ( ) ) ; server . createQueue ( address , queueConfiguration . getRoutingType ( ) , resourceName , filterString , queueConfiguration . isDurable ( ) , temporary ) ; } catch ( Exception e ) { throw new StartException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public synchronized void stop ( StopContext context ) { try { final ActiveMQServer server = this . activeMQServerSupplier . get ( ) ; server . destroyQueue ( new SimpleString ( queueConfiguration . getName ( ) ) , null , false ) ; MessagingLogger . ROOT_LOGGER . debugf ( \"Destroying queue from server %s queue with name: %s\" , server . getNodeID ( ) , new SimpleString ( queueConfiguration . getName ( ) ) ) ; } catch ( Exception e ) { MessagingLogger . ROOT_LOGGER . failedToDestroy ( \"queue\" , queueConfiguration . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all interfaces implemented by a bean that are eligible to be view interfaces [CODESPLIT] static Set < Class < ? > > getPotentialViewInterfaces ( Class < ? > beanClass ) { Class < ? > [ ] interfaces = beanClass . getInterfaces ( ) ; if ( interfaces == null ) { return Collections . emptySet ( ) ; } final Set < Class < ? > > potentialBusinessInterfaces = new HashSet < Class < ? > > ( ) ; for ( Class < ? > klass : interfaces ) { // EJB 3.1 FR 4.9.7 bullet 5.3 if ( klass . equals ( Serializable . class ) || klass . equals ( Externalizable . class ) || klass . getName ( ) . startsWith ( \"javax.ejb.\" ) || klass . getName ( ) . startsWith ( \"groovy.lang.\" ) ) { continue ; } potentialBusinessInterfaces . add ( klass ) ; } return potentialBusinessInterfaces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all interfaces implemented by a bean that are eligible to be view interfaces [CODESPLIT] static Set < DotName > getPotentialViewInterfaces ( ClassInfo beanClass ) { DotName [ ] interfaces = beanClass . interfaces ( ) ; if ( interfaces == null ) { return Collections . emptySet ( ) ; } final Set < DotName > names = new HashSet < DotName > ( ) ; for ( DotName dotName : interfaces ) { String name = dotName . toString ( ) ; // EJB 3.1 FR 4.9.7 bullet 5.3 // & FR 5.4.2 if ( name . equals ( Serializable . class . getName ( ) ) || name . equals ( Externalizable . class . getName ( ) ) || name . startsWith ( \"javax.ejb.\" ) || name . startsWith ( \"groovy.lang.\" ) ) { continue ; } names . add ( dotName ) ; } return names ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the specified EntityManager in the local threads active transaction . The TransactionSynchronizationRegistry will clear the reference to the EntityManager when the transaction completes . [CODESPLIT] public static void putEntityManagerInTransactionRegistry ( String scopedPuName , EntityManager entityManager , TransactionSynchronizationRegistry tsr ) { tsr . putResource ( scopedPuName , entityManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO use a custom attribute marshaller [CODESPLIT] private static void writeFilter ( final XMLExtendedStreamWriter writer , final ModelNode node ) throws XMLStreamException { if ( node . hasDefined ( CommonAttributes . FILTER . getName ( ) ) ) { writer . writeEmptyElement ( CommonAttributes . FILTER . getXmlName ( ) ) ; writer . writeAttribute ( CommonAttributes . STRING , node . get ( CommonAttributes . FILTER . getName ( ) ) . asString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the Jar processing order . [CODESPLIT] protected static void resolveOrder ( List < WebOrdering > webOrderings , List < String > order ) { List < Ordering > work = new ArrayList < Ordering > ( ) ; // Populate the work Ordering list Iterator < WebOrdering > webOrderingsIterator = webOrderings . iterator ( ) ; while ( webOrderingsIterator . hasNext ( ) ) { WebOrdering webOrdering = webOrderingsIterator . next ( ) ; Ordering ordering = new Ordering ( ) ; ordering . ordering = webOrdering ; ordering . afterOthers = webOrdering . isAfterOthers ( ) ; ordering . beforeOthers = webOrdering . isBeforeOthers ( ) ; if ( ordering . afterOthers && ordering . beforeOthers ) { // Cannot be both after and before others throw new IllegalStateException ( UndertowLogger . ROOT_LOGGER . invalidRelativeOrderingBeforeAndAfter ( webOrdering . getJar ( ) ) ) ; } work . add ( ordering ) ; } // Create double linked relationships between the orderings, // and resolve names Iterator < Ordering > workIterator = work . iterator ( ) ; while ( workIterator . hasNext ( ) ) { Ordering ordering = workIterator . next ( ) ; WebOrdering webOrdering = ordering . ordering ; Iterator < String > after = webOrdering . getAfter ( ) . iterator ( ) ; while ( after . hasNext ( ) ) { String name = after . next ( ) ; Iterator < Ordering > workIterator2 = work . iterator ( ) ; boolean found = false ; while ( workIterator2 . hasNext ( ) ) { Ordering ordering2 = workIterator2 . next ( ) ; if ( name . equals ( ordering2 . ordering . getName ( ) ) ) { if ( found ) { // Duplicate name throw new IllegalStateException ( UndertowLogger . ROOT_LOGGER . invalidRelativeOrderingDuplicateName ( webOrdering . getJar ( ) ) ) ; } ordering . addAfter ( ordering2 ) ; ordering2 . addBefore ( ordering ) ; found = true ; } } if ( ! found ) { // Unknown name UndertowLogger . ROOT_LOGGER . invalidRelativeOrderingUnknownName ( webOrdering . getJar ( ) ) ; } } Iterator < String > before = webOrdering . getBefore ( ) . iterator ( ) ; while ( before . hasNext ( ) ) { String name = before . next ( ) ; Iterator < Ordering > workIterator2 = work . iterator ( ) ; boolean found = false ; while ( workIterator2 . hasNext ( ) ) { Ordering ordering2 = workIterator2 . next ( ) ; if ( name . equals ( ordering2 . ordering . getName ( ) ) ) { if ( found ) { // Duplicate name throw new IllegalStateException ( UndertowLogger . ROOT_LOGGER . invalidRelativeOrderingDuplicateName ( webOrdering . getJar ( ) ) ) ; } ordering . addBefore ( ordering2 ) ; ordering2 . addAfter ( ordering ) ; found = true ; } } if ( ! found ) { // Unknown name UndertowLogger . ROOT_LOGGER . invalidRelativeOrderingUnknownName ( webOrdering . getJar ( ) ) ; } } } // Validate ordering workIterator = work . iterator ( ) ; while ( workIterator . hasNext ( ) ) { workIterator . next ( ) . validate ( ) ; } // Create three ordered lists that will then be merged List < Ordering > tempOrder = new ArrayList < Ordering > ( ) ; // Create the ordered list of fragments which are before others workIterator = work . iterator ( ) ; while ( workIterator . hasNext ( ) ) { Ordering ordering = workIterator . next ( ) ; if ( ordering . beforeOthers ) { // Insert at the first possible position int insertAfter = - 1 ; boolean last = ordering . isLastBeforeOthers ( ) ; int lastBeforeOthers = - 1 ; for ( int i = 0 ; i < tempOrder . size ( ) ; i ++ ) { if ( ordering . isAfter ( tempOrder . get ( i ) ) ) { insertAfter = i ; } if ( tempOrder . get ( i ) . beforeOthers ) { lastBeforeOthers = i ; } } int pos = insertAfter ; if ( last && lastBeforeOthers > insertAfter ) { pos = lastBeforeOthers ; } tempOrder . add ( pos + 1 , ordering ) ; } else if ( ordering . afterOthers ) { // Insert at the last possible element int insertBefore = tempOrder . size ( ) ; boolean first = ordering . isFirstAfterOthers ( ) ; int firstAfterOthers = tempOrder . size ( ) ; for ( int i = tempOrder . size ( ) - 1 ; i >= 0 ; i -- ) { if ( ordering . isBefore ( tempOrder . get ( i ) ) ) { insertBefore = i ; } if ( tempOrder . get ( i ) . afterOthers ) { firstAfterOthers = i ; } } int pos = insertBefore ; if ( first && firstAfterOthers < insertBefore ) { pos = firstAfterOthers ; } tempOrder . add ( pos , ordering ) ; } else { // Insert according to other already inserted elements int insertAfter = - 1 ; int insertBefore = tempOrder . size ( ) ; for ( int i = 0 ; i < tempOrder . size ( ) ; i ++ ) { if ( ordering . isAfter ( tempOrder . get ( i ) ) || tempOrder . get ( i ) . beforeOthers ) { insertAfter = i ; } if ( ordering . isBefore ( tempOrder . get ( i ) ) || tempOrder . get ( i ) . afterOthers ) { insertBefore = i ; } } if ( insertAfter > insertBefore ) { // Conflicting order (probably caught earlier) throw new IllegalStateException ( UndertowLogger . ROOT_LOGGER . invalidRelativeOrderingConflict ( ordering . ordering . getJar ( ) ) ) ; } // Insert somewhere in the range tempOrder . add ( insertAfter + 1 , ordering ) ; } } // Create the final ordered list Iterator < Ordering > tempOrderIterator = tempOrder . iterator ( ) ; while ( tempOrderIterator . hasNext ( ) ) { Ordering ordering = tempOrderIterator . next ( ) ; order . add ( ordering . ordering . getJar ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a JBoss Security Context with the given security domain name [CODESPLIT] private static SecurityContext createSecurityContext ( final String domain ) { return AccessController . doPrivileged ( new PrivilegedAction < SecurityContext > ( ) { @ Override public SecurityContext run ( ) { try { return SecurityContextFactory . createSecurityContext ( domain ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the { @code SecurityContext } on the { @code SecurityContextAssociation } [CODESPLIT] private static void setSecurityContextOnAssociation ( final SecurityContext sc ) { AccessController . doPrivileged ( new PrivilegedAction < Void > ( ) { @ Override public Void run ( ) { SecurityContextAssociation . setSecurityContext ( sc ) ; return null ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void writeContent ( final XMLExtendedStreamWriter writer , final SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( org . jboss . as . jdr . Namespace . CURRENT . getUriString ( ) , false ) ; writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds a key / value parameter pair to the call [CODESPLIT] public CallAS7 param ( String key , String val ) { this . parameters . put ( key , val ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "appends resource parts to the resource to call <p > < / p > If you want to call / foo = bar / baz = boo / do this : <pre > . resource ( foo bar baz boo ) < / pre > [CODESPLIT] public CallAS7 resource ( String ... parts ) { for ( String part : parts ) { this . resource . add ( part ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use either the active transaction or the current thread as the lock owner [CODESPLIT] private static Object getLockOwner ( final TransactionSynchronizationRegistry transactionSynchronizationRegistry ) { Object owner = transactionSynchronizationRegistry . getTransactionKey ( ) ; return owner != null ? owner : Thread . currentThread ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Releases the passed { @link StatefulSessionComponentInstance } i . e . marks it as no longer in use . After releasing the instance this method releases the lock held by this thread on the stateful component instance . [CODESPLIT] static void releaseInstance ( final StatefulSessionComponentInstance instance , boolean toDiscard ) { try { if ( ! instance . isDiscarded ( ) && ! toDiscard ) { // mark the SFSB instance as no longer in use instance . getComponent ( ) . getCache ( ) . release ( instance ) ; } } finally { instance . setSynchronizationRegistered ( false ) ; // release the lock on the SFSB instance releaseLock ( instance ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Releases the lock held by this thread on the stateful component instance . [CODESPLIT] static void releaseLock ( final StatefulSessionComponentInstance instance ) { instance . getLock ( ) . unlock ( getLockOwner ( instance . getComponent ( ) . getTransactionSynchronizationRegistry ( ) ) ) ; ROOT_LOGGER . tracef ( \"Released lock: %s\" , instance . getLock ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the contents of the { @link InputStream } to the path in the zip . [CODESPLIT] public void add ( InputStream is , String path ) { byte [ ] buffer = new byte [ 1024 ] ; try { String entryName = this . baseName + \"/\" + path ; ZipEntry ze = new ZipEntry ( entryName ) ; zos . putNextEntry ( ze ) ; int bytesRead = is . read ( buffer ) ; while ( bytesRead > - 1 ) { zos . write ( buffer , 0 , bytesRead ) ; bytesRead = is . read ( buffer ) ; } } catch ( ZipException ze ) { ROOT_LOGGER . debugf ( ze , \"%s is already in the zip\" , path ) ; } catch ( Exception e ) { ROOT_LOGGER . debugf ( e , \"Error when adding %s\" , path ) ; } finally { try { zos . closeEntry ( ) ; } catch ( Exception e ) { ROOT_LOGGER . debugf ( e , \"Error when closing entry for %s\" , path ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the content of the { @link InputStream } to the zip in a location that mirrors where { @link VirtualFile file } is located . [CODESPLIT] public void add ( VirtualFile file , InputStream is ) throws Exception { String name = \"JBOSS_HOME\" + file . getPhysicalFile ( ) . getAbsolutePath ( ) . substring ( this . jbossHome . length ( ) ) ; this . add ( is , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds content to the zipfile at path [CODESPLIT] public void add ( String content , String path ) throws Exception { StringBuilder name = new StringBuilder ( \"sos_strings/\" ) ; name . append ( this . env . getProductName ( ) . replace ( \" \" , \"_\" ) . toLowerCase ( ) ) ; name . append ( \"-\" ) ; name . append ( this . env . getProductVersion ( ) . split ( \"\\\\.\" ) [ 0 ] ) ; name . append ( \"/\" ) ; name . append ( path ) ; this . add ( new ByteArrayInputStream ( content . getBytes ( StandardCharsets . UTF_8 ) ) , name . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds content to the zipfile at path [CODESPLIT] public void addAsString ( InputStream stream , String path ) throws Exception { StringBuilder name = new StringBuilder ( \"sos_strings/\" ) ; name . append ( this . env . getProductName ( ) . replace ( \" \" , \"_\" ) . toLowerCase ( ) ) ; name . append ( \"-\" ) ; name . append ( this . env . getProductVersion ( ) . split ( \"\\\\.\" ) [ 0 ] ) ; name . append ( \"/\" ) ; name . append ( path ) ; this . add ( stream , name . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds content to the zipfile in a file named logName [CODESPLIT] public void addLog ( String content , String logName ) throws Exception { String name = \"sos_logs/\" + logName ; this . add ( new ByteArrayInputStream ( content . getBytes ( StandardCharsets . UTF_8 ) ) , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Creates a thread with the specified { @code Runnable } and name . < / p > [CODESPLIT] static Thread createThread ( final Runnable runnable , final String threadName ) { return ! WildFlySecurityManager . isChecking ( ) ? new Thread ( runnable , threadName ) : doPrivileged ( new CreateThreadAction ( runnable , threadName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private boolean isJSFSpecOver1_1 ( ModuleIdentifier jsfModule ModuleDependency jsfAPI ) throws DeploymentUnitProcessingException { try { return ( jsfAPI . getModuleLoader () . loadModule ( jsfModule ) . getClassLoader () . getResource ( / javax / faces / component / ActionSource2 . class ) ! = null ) ; } catch ( ModuleLoadException e ) { throw new DeploymentUnitProcessingException ( e ) ; } } [CODESPLIT] private void addJSFImpl ( String jsfVersion , ModuleSpecification moduleSpecification , ModuleLoader moduleLoader ) { if ( jsfVersion . equals ( JsfVersionMarker . WAR_BUNDLES_JSF_IMPL ) ) return ; ModuleIdentifier jsfModule = moduleIdFactory . getImplModId ( jsfVersion ) ; ModuleDependency jsfImpl = new ModuleDependency ( moduleLoader , jsfModule , false , false , true , false ) ; jsfImpl . addImportFilter ( PathFilters . getMetaInfFilter ( ) , true ) ; moduleSpecification . addSystemDependency ( jsfImpl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a CDI ViewHandler . [CODESPLIT] private void addCDIFlag ( WarMetaData warMetaData , DeploymentUnit deploymentUnit ) { JBossWebMetaData webMetaData = warMetaData . getMergedJBossWebMetaData ( ) ; if ( webMetaData == null ) { webMetaData = new JBossWebMetaData ( ) ; warMetaData . setMergedJBossWebMetaData ( webMetaData ) ; } List < ParamValueMetaData > contextParams = webMetaData . getContextParams ( ) ; if ( contextParams == null ) { contextParams = new ArrayList < ParamValueMetaData > ( ) ; } boolean isCDI = false ; final CapabilityServiceSupport support = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; if ( support . hasCapability ( WELD_CAPABILITY_NAME ) ) { isCDI = support . getOptionalCapabilityRuntimeAPI ( WELD_CAPABILITY_NAME , WeldCapability . class ) . get ( ) . isPartOfWeldDeployment ( deploymentUnit ) ; } ParamValueMetaData param = new ParamValueMetaData ( ) ; param . setParamName ( IS_CDI_PARAM ) ; param . setParamValue ( Boolean . toString ( isCDI ) ) ; contextParams . add ( param ) ; webMetaData . setContextParams ( contextParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets endpoint container lazily . [CODESPLIT] protected ComponentView getComponentView ( ) { ComponentView cv = componentView ; // we need to check both, otherwise it is possible for // componentView to be initialized before reference if ( cv == null ) { synchronized ( this ) { cv = componentView ; if ( cv == null ) { cv = getMSCService ( componentViewName , ComponentView . class ) ; if ( cv == null ) { throw WSLogger . ROOT_LOGGER . cannotFindComponentView ( componentViewName ) ; } if ( reference == null ) { try { reference = cv . createInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } componentView = cv ; } } } return cv ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes WS endpoint . [CODESPLIT] public void invoke ( final Endpoint endpoint , final Invocation wsInvocation ) throws Exception { try { if ( ! EndpointState . STARTED . equals ( endpoint . getState ( ) ) ) { throw WSLogger . ROOT_LOGGER . endpointAlreadyStopped ( endpoint . getShortName ( ) ) ; } SecurityDomainContext securityDomainContext = endpoint . getSecurityDomainContext ( ) ; securityDomainContext . runAs ( ( Callable < Void > ) ( ) -> { invokeInternal ( endpoint , wsInvocation ) ; return null ; } ) ; } catch ( Throwable t ) { handleInvocationException ( t ) ; } finally { onAfterInvocation ( wsInvocation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates SEI method to component view method . [CODESPLIT] protected Method getComponentViewMethod ( final Method seiMethod , final Collection < Method > viewMethods ) { for ( final Method viewMethod : viewMethods ) { if ( matches ( seiMethod , viewMethod ) ) { return viewMethod ; } } throw new IllegalStateException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two methods if they are identical . [CODESPLIT] private boolean matches ( final Method seiMethod , final Method viewMethod ) { if ( ! seiMethod . getName ( ) . equals ( viewMethod . getName ( ) ) ) return false ; final Class < ? > [ ] sourceParams = seiMethod . getParameterTypes ( ) ; final Class < ? > [ ] targetParams = viewMethod . getParameterTypes ( ) ; if ( sourceParams . length != targetParams . length ) return false ; for ( int i = 0 ; i < sourceParams . length ; i ++ ) { if ( ! sourceParams [ i ] . equals ( targetParams [ i ] ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create single instance of management statistics resource per managementAdaptor version . [CODESPLIT] public static Resource createManagementStatisticsResource ( final ManagementAdaptor managementAdaptor , final String scopedPersistenceUnitName , final DeploymentUnit deploymentUnit ) { synchronized ( existingResourceDescriptionResolver ) { final EntityManagerFactoryLookup entityManagerFactoryLookup = new EntityManagerFactoryLookup ( ) ; final Statistics statistics = managementAdaptor . getStatistics ( ) ; if ( false == existingResourceDescriptionResolver . contains ( managementAdaptor . getVersion ( ) ) ) { // setup statistics (this used to be part of JPA subsystem startup) ResourceDescriptionResolver resourceDescriptionResolver = new StandardResourceDescriptionResolver ( statistics . getResourceBundleKeyPrefix ( ) , statistics . getResourceBundleName ( ) , statistics . getClass ( ) . getClassLoader ( ) ) { private ResourceDescriptionResolver fallback = JPAExtension . getResourceDescriptionResolver ( ) ; //add a fallback in case provider doesn't have all properties properly defined @ Override public String getResourceAttributeDescription ( String attributeName , Locale locale , ResourceBundle bundle ) { if ( bundle . containsKey ( getBundleKey ( attributeName ) ) ) { return super . getResourceAttributeDescription ( attributeName , locale , bundle ) ; } else { return fallback . getResourceAttributeDescription ( attributeName , locale , fallback . getResourceBundle ( locale ) ) ; } } } ; PathElement subsystemPE = PathElement . pathElement ( ModelDescriptionConstants . SUBSYSTEM , JPAExtension . SUBSYSTEM_NAME ) ; ManagementResourceRegistration deploymentResourceRegistration = deploymentUnit . getAttachment ( DeploymentModelUtils . MUTABLE_REGISTRATION_ATTACHMENT ) ; ManagementResourceRegistration deploymentSubsystemRegistration = deploymentResourceRegistration . getSubModel ( PathAddress . pathAddress ( subsystemPE ) ) ; ManagementResourceRegistration subdeploymentSubsystemRegistration = deploymentResourceRegistration . getSubModel ( PathAddress . pathAddress ( PathElement . pathElement ( ModelDescriptionConstants . SUBDEPLOYMENT ) , subsystemPE ) ) ; ManagementResourceRegistration providerResource = deploymentSubsystemRegistration . registerSubModel ( new ManagementResourceDefinition ( PathElement . pathElement ( managementAdaptor . getIdentificationLabel ( ) ) , resourceDescriptionResolver , statistics , entityManagerFactoryLookup ) ) ; providerResource . registerReadOnlyAttribute ( PersistenceUnitServiceHandler . SCOPED_UNIT_NAME , null ) ; providerResource = subdeploymentSubsystemRegistration . registerSubModel ( new ManagementResourceDefinition ( PathElement . pathElement ( managementAdaptor . getIdentificationLabel ( ) ) , resourceDescriptionResolver , statistics , entityManagerFactoryLookup ) ) ; providerResource . registerReadOnlyAttribute ( PersistenceUnitServiceHandler . SCOPED_UNIT_NAME , null ) ; existingResourceDescriptionResolver . add ( managementAdaptor . getVersion ( ) ) ; } // create (per deployment) dynamic Resource implementation that can reflect the deployment specific names (e.g. jpa entity classname/Hibernate region name) return new DynamicManagementStatisticsResource ( statistics , scopedPersistenceUnitName , managementAdaptor . getIdentificationLabel ( ) , entityManagerFactoryLookup ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( XMLExtendedStreamReader reader , List < ModelNode > list ) throws XMLStreamException { // no attributes if ( reader . getAttributeCount ( ) > 0 ) { throw unexpectedAttribute ( reader , 0 ) ; } final ModelNode address = new ModelNode ( ) ; address . add ( ModelDescriptionConstants . SUBSYSTEM , TransactionExtension . SUBSYSTEM_NAME ) ; address . protect ( ) ; final ModelNode subsystem = new ModelNode ( ) ; subsystem . get ( OP ) . set ( ADD ) ; subsystem . get ( OP_ADDR ) . set ( address ) ; list . add ( subsystem ) ; // elements final EnumSet < Element > required = EnumSet . of ( Element . RECOVERY_ENVIRONMENT , Element . CORE_ENVIRONMENT ) ; final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { switch ( Namespace . forUri ( reader . getNamespaceURI ( ) ) ) { case TRANSACTIONS_1_1 : { final Element element = Element . forName ( reader . getLocalName ( ) ) ; required . remove ( element ) ; if ( ! encountered . add ( element ) ) { throw unexpectedElement ( reader ) ; } switch ( element ) { case RECOVERY_ENVIRONMENT : { parseRecoveryEnvironmentElement ( reader , subsystem ) ; break ; } case CORE_ENVIRONMENT : { parseCoreEnvironmentElement ( reader , subsystem ) ; break ; } case COORDINATOR_ENVIRONMENT : { parseCoordinatorEnvironmentElement ( reader , subsystem ) ; break ; } case OBJECT_STORE : { parseObjectStoreEnvironmentElementAndEnrichOperation ( reader , subsystem ) ; break ; } case JTS : { parseJts ( reader , subsystem ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } break ; } default : { throw unexpectedElement ( reader ) ; } } } if ( ! required . isEmpty ( ) ) { throw missingRequiredElement ( reader , required ) ; } final ModelNode logStoreAddress = address . clone ( ) ; final ModelNode operation = new ModelNode ( ) ; operation . get ( OP ) . set ( ADD ) ; logStoreAddress . add ( LogStoreConstants . LOG_STORE , LogStoreConstants . LOG_STORE ) ; logStoreAddress . protect ( ) ; operation . get ( OP_ADDR ) . set ( logStoreAddress ) ; list . add ( operation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get { [CODESPLIT] public InjectedValue < ExceptionSupplier < CredentialSource , Exception > > getBridgeCredentialSourceSupplierInjector ( String name ) { if ( bridgeCredentialSource . containsKey ( name ) ) { return bridgeCredentialSource . get ( name ) ; } else { InjectedValue < ExceptionSupplier < CredentialSource , Exception > > injector = new InjectedValue <> ( ) ; bridgeCredentialSource . put ( name , injector ) ; return injector ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Interception of register work call to get transaction being imported to wildfly transacton client . <p > For importing a transaction Wildfly transaction client eventually calls { [CODESPLIT] @ Override public void registerWork ( Work work , Xid xid , long timeout ) throws WorkCompletedException { try { // jca provides timeout in milliseconds, SubordinationManager expects seconds int timeout_seconds = ( int ) timeout / 1000 ; // unlimited timeout for jca means -1 which fails in wfly client if ( timeout_seconds <= 0 ) timeout_seconds = ContextTransactionManager . getGlobalDefaultTransactionTimeout ( ) ; localTransactionContext . findOrImportTransaction ( xid , timeout_seconds ) ; } catch ( XAException xae ) { throw TransactionLogger . ROOT_LOGGER . cannotFindOrImportInflowTransaction ( xid , work , xae ) ; } jbossXATerminator . registerWork ( work , xid , timeout ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Start work gets imported transaction and assign it to current thread . <p > This method mimics behavior of Narayana s { [CODESPLIT] @ Override public void startWork ( Work work , Xid xid ) throws WorkCompletedException { LocalTransaction transaction = null ; try { ImportResult < LocalTransaction > transactionImportResult = localTransactionContext . findOrImportTransaction ( xid , 0 ) ; transaction = transactionImportResult . getTransaction ( ) ; ContextTransactionManager . getInstance ( ) . resume ( transaction ) ; } catch ( XAException xae ) { throw TransactionLogger . ROOT_LOGGER . cannotFindOrImportInflowTransaction ( xid , work , xae ) ; } catch ( InvalidTransactionException ite ) { throw TransactionLogger . ROOT_LOGGER . importedInflowTransactionIsInactive ( xid , work , ite ) ; } catch ( SystemException se ) { throw TransactionLogger . ROOT_LOGGER . cannotResumeInflowTransactionUnexpectedError ( transaction , work , se ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Suspending transaction and canceling the work . <p > Suspend transaction has to be called on the wildfly transaction manager and the we delegate work cancellation to { [CODESPLIT] @ Override public void endWork ( Work work , Xid xid ) { jbossXATerminator . cancelWork ( work , xid ) ; try { ContextTransactionManager . getInstance ( ) . suspend ( ) ; } catch ( SystemException se ) { throw TransactionLogger . ROOT_LOGGER . cannotSuspendInflowTransactionUnexpectedError ( work , se ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Calling { [CODESPLIT] @ Override public void cancelWork ( Work work , Xid xid ) { jbossXATerminator . cancelWork ( work , xid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@see org . jboss . webservices . integration . tomcat . AbstractSecurityMetaDataAccessorEJB#getSecurityDomain ( Deployment ) [CODESPLIT] public String getSecurityDomain ( final Deployment dep ) { String securityDomain = null ; for ( final EJBEndpoint ejbEndpoint : getEjbEndpoints ( dep ) ) { String nextSecurityDomain = ejbEndpoint . getSecurityDomain ( ) ; if ( nextSecurityDomain == null || nextSecurityDomain . isEmpty ( ) ) { nextSecurityDomain = null ; } securityDomain = getDomain ( securityDomain , nextSecurityDomain ) ; } if ( securityDomain == null ) { final DeploymentUnit unit = WSHelper . getRequiredAttachment ( dep , DeploymentUnit . class ) ; if ( unit . getParent ( ) != null ) { final EarMetaData jbossAppMD = unit . getParent ( ) . getAttachment ( Attachments . EAR_METADATA ) ; return jbossAppMD instanceof JBossAppMetaData ? ( ( JBossAppMetaData ) jbossAppMD ) . getSecurityDomain ( ) : null ; } } return securityDomain ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@see org . jboss . webservices . integration . tomcat . SecurityMetaDataAccessorEJB#isSecureWsdlAccess ( Endpoint ) [CODESPLIT] public boolean isSecureWsdlAccess ( final Endpoint endpoint ) { final EJBSecurityMetaData ejbSecurityMD = this . getEjbSecurityMetaData ( endpoint ) ; final boolean hasEjbSecurityMD = ejbSecurityMD != null ; return hasEjbSecurityMD ? ejbSecurityMD . getSecureWSDLAccess ( ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@see org . jboss . webservices . integration . tomcat . SecurityMetaDataAccessorEJB#getTransportGuarantee ( Endpoint ) [CODESPLIT] public String getTransportGuarantee ( final Endpoint endpoint ) { final EJBSecurityMetaData ejbSecurityMD = this . getEjbSecurityMetaData ( endpoint ) ; final boolean hasEjbSecurityMD = ejbSecurityMD != null ; return hasEjbSecurityMD ? ejbSecurityMD . getTransportGuarantee ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets EJB security meta data if associated with EJB endpoint . [CODESPLIT] private EJBSecurityMetaData getEjbSecurityMetaData ( final Endpoint endpoint ) { final String ejbName = endpoint . getShortName ( ) ; final Deployment dep = endpoint . getService ( ) . getDeployment ( ) ; final EJBArchiveMetaData ejbArchiveMD = WSHelper . getOptionalAttachment ( dep , EJBArchiveMetaData . class ) ; final EJBMetaData ejbMD = ejbArchiveMD != null ? ejbArchiveMD . getBeanByEjbName ( ejbName ) : null ; return ejbMD != null ? ejbMD . getSecurityMetaData ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns security domain value . This method checks domain is the same for every EJB 3 endpoint . [CODESPLIT] private String getDomain ( final String oldSecurityDomain , final String nextSecurityDomain ) { if ( nextSecurityDomain == null ) { return oldSecurityDomain ; } if ( oldSecurityDomain == null ) { return nextSecurityDomain ; } ensureSameDomains ( oldSecurityDomain , nextSecurityDomain ) ; return oldSecurityDomain ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method ensures both passed domains contain the same value . [CODESPLIT] private void ensureSameDomains ( final String oldSecurityDomain , final String newSecurityDomain ) { final boolean domainsDiffer = ! oldSecurityDomain . equals ( newSecurityDomain ) ; if ( domainsDiffer ) throw WSLogger . ROOT_LOGGER . multipleSecurityDomainsDetected ( oldSecurityDomain , newSecurityDomain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void getResourceValue ( final ResolutionContext resolutionContext , final ServiceBuilder < ? > serviceBuilder , final DeploymentPhaseContext phaseContext , final Injector < ManagedReferenceFactory > injector ) { final String applicationName = resolutionContext . getApplicationName ( ) ; final String moduleName = resolutionContext . getModuleName ( ) ; final String componentName = resolutionContext . getComponentName ( ) ; final boolean compUsesModule = resolutionContext . isCompUsesModule ( ) ; final String scheme = org . jboss . as . naming . InitialContext . getURLScheme ( lookupName ) ; if ( scheme == null ) { // relative name, build absolute name and setup normal lookup injection if ( componentName != null && ! compUsesModule ) { ContextNames . bindInfoFor ( applicationName , moduleName , componentName , \"java:comp/env/\" + lookupName ) . setupLookupInjection ( serviceBuilder , injector , phaseContext . getDeploymentUnit ( ) , optional ) ; } else if ( compUsesModule ) { ContextNames . bindInfoFor ( applicationName , moduleName , componentName , \"java:module/env/\" + lookupName ) . setupLookupInjection ( serviceBuilder , injector , phaseContext . getDeploymentUnit ( ) , optional ) ; } else { ContextNames . bindInfoFor ( applicationName , moduleName , componentName , \"java:jboss/env/\" + lookupName ) . setupLookupInjection ( serviceBuilder , injector , phaseContext . getDeploymentUnit ( ) , optional ) ; } } else { if ( scheme . equals ( \"java\" ) ) { // an absolute java name, setup normal lookup injection if ( compUsesModule && lookupName . startsWith ( \"java:comp/\" ) ) { // switch \"comp\" with \"module\" ContextNames . bindInfoFor ( applicationName , moduleName , componentName , \"java:module/\" + lookupName . substring ( 10 ) ) . setupLookupInjection ( serviceBuilder , injector , phaseContext . getDeploymentUnit ( ) , optional ) ; } else { ContextNames . bindInfoFor ( applicationName , moduleName , componentName , lookupName ) . setupLookupInjection ( serviceBuilder , injector , phaseContext . getDeploymentUnit ( ) , optional ) ; } } else { // an absolute non java name final ManagedReferenceFactory managedReferenceFactory ; if ( URL_SCHEMES . contains ( scheme ) ) { // a Java EE Standard Resource Manager Connection Factory for URLs, using lookup to define value of URL, inject factory that creates URL instances managedReferenceFactory = new ManagedReferenceFactory ( ) { @ Override public ManagedReference getReference ( ) { try { return new ImmediateManagedReference ( new URL ( lookupName ) ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } ; } else { // lookup for a non java jndi resource, inject factory which does a true jndi lookup managedReferenceFactory = new ManagedReferenceFactory ( ) { @ Override public ManagedReference getReference ( ) { try { return new ImmediateManagedReference ( new InitialContext ( ) . lookup ( lookupName ) ) ; } catch ( NamingException e ) { EeLogger . ROOT_LOGGER . tracef ( e , \"failed to lookup %s\" , lookupName ) ; return null ; } } } ; } injector . inject ( managedReferenceFactory ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( final XMLExtendedStreamReader reader , final List < ModelNode > list ) throws XMLStreamException { // Require no attributes or content requireNoAttributes ( reader ) ; requireNoContent ( reader ) ; list . add ( Util . createAddOperation ( PathAddress . pathAddress ( WeldExtension . PATH_SUBSYSTEM ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set my unqualified IDL name . This also sets the names of the associated operations . [CODESPLIT] void setIDLName ( String idlName ) { super . setIDLName ( idlName ) ; // If the first char is an uppercase letter and the second char is not // an uppercase letter, then convert the first char to lowercase. if ( idlName . charAt ( 0 ) >= 0x41 && idlName . charAt ( 0 ) <= 0x5a && ( idlName . length ( ) <= 1 || idlName . charAt ( 1 ) < 0x41 || idlName . charAt ( 1 ) > 0x5a ) ) { idlName = idlName . substring ( 0 , 1 ) . toLowerCase ( Locale . ENGLISH ) + idlName . substring ( 1 ) ; } if ( accessorAnalysis != null ) accessorAnalysis . setIDLName ( \"_get_\" + idlName ) ; if ( mutatorAnalysis != null ) mutatorAnalysis . setIDLName ( \"_set_\" + idlName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the absolute JNDI name as a string . [CODESPLIT] public String getAbsoluteName ( ) { final StringBuilder absolute = new StringBuilder ( ) ; if ( parent != null ) { absolute . append ( parent ) . append ( ENTRY_SEPARATOR ) ; } absolute . append ( local ) ; return absolute . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance of the JndiName by breaking the provided string format into a JndiName parts . [CODESPLIT] public static JndiName of ( final String name ) { if ( name == null || name . isEmpty ( ) ) throw NamingLogger . ROOT_LOGGER . invalidJndiName ( name ) ; final String [ ] parts = name . split ( ENTRY_SEPARATOR ) ; JndiName current = null ; for ( String part : parts ) { current = new JndiName ( current , part ) ; } return current ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for iron - jacamar . xml files . Will parse the xml file and attach metadata discovered during processing . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ResourceRoot resourceRoot = deploymentUnit . getAttachment ( Attachments . DEPLOYMENT_ROOT ) ; final VirtualFile deploymentRoot = resourceRoot . getRoot ( ) ; final boolean resolveProperties = Util . shouldResolveJBoss ( deploymentUnit ) ; IronJacamarXmlDescriptor xmlDescriptor = process ( deploymentRoot , resolveProperties ) ; if ( xmlDescriptor != null ) { deploymentUnit . putAttachment ( IronJacamarXmlDescriptor . ATTACHMENT_KEY , xmlDescriptor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increments the counter and registers a listener to decrement the counter upon exchange complete event . [CODESPLIT] @ Override public void handleRequest ( HttpServerExchange exchange ) throws Exception { runningCount . increment ( ) ; exchange . addExchangeCompleteListener ( new ExchangeCompletionListener ( ) { @ Override public void exchangeEvent ( HttpServerExchange exchange , NextListener nextListener ) { runningCount . decrement ( ) ; // Proceed to next listener must be called! nextListener . proceed ( ) ; } } ) ; wrappedHandler . handleRequest ( exchange ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the actual JMSContext used by this injection . [CODESPLIT] @ Override JMSContext getDelegate ( ) { boolean inTx = isInTransaction ( ) ; AbstractJMSContext jmsContext = inTx ? transactedJMSContext . get ( ) : requestedJMSContext ; ROOT_LOGGER . debugf ( \"using %s to create the injected JMSContext\" , jmsContext , id ) ; ConnectionFactory connectionFactory = getConnectionFactory ( ) ; JMSContext contextInstance = jmsContext . getContext ( id , info , connectionFactory ) ; //fix of  WFLY-9501 // CCM tries to clean opened connections before execution of @PreDestroy method on JMSContext - which is executed after completion, see . // Correct phase to call close is afterCompletion {@see TransactionSynchronizationRegistry.registerInterposedSynchronization} if ( inTx ) { TransactedJMSContext transactedJMSContext = ( TransactedJMSContext ) jmsContext ; transactedJMSContext . registerCleanUpListener ( transactionSynchronizationRegistry , contextInstance ) ; } return contextInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check whether there is an active transaction . [CODESPLIT] private boolean isInTransaction ( ) { TransactionSynchronizationRegistry tsr = getTransactionSynchronizationRegistry ( ) ; boolean inTx = tsr . getTransactionStatus ( ) == Status . STATUS_ACTIVE ; return inTx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lookup the transactionSynchronizationRegistry and cache it . [CODESPLIT] private TransactionSynchronizationRegistry getTransactionSynchronizationRegistry ( ) { TransactionSynchronizationRegistry cachedTSR = transactionSynchronizationRegistry ; if ( cachedTSR == null ) { cachedTSR = ( TransactionSynchronizationRegistry ) lookup ( TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP ) ; transactionSynchronizationRegistry = cachedTSR ; } return cachedTSR ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lookup the connectionFactory and cache it . [CODESPLIT] private ConnectionFactory getConnectionFactory ( ) { ConnectionFactory cachedCF = connectionFactory ; if ( cachedCF == null ) { cachedCF = ( ConnectionFactory ) lookup ( info . getConnectionFactoryLookup ( ) ) ; connectionFactory = cachedCF ; } return cachedCF ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the last component of a name . [CODESPLIT] public static String getLastComponent ( final Name name ) { if ( name . size ( ) > 0 ) return name . get ( name . size ( ) - 1 ) ; return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a name is empty or if ot contains only one component which is the empty string . [CODESPLIT] public static boolean isEmpty ( final Name name ) { return name . isEmpty ( ) || ( name . size ( ) == 1 && \"\" . equals ( name . get ( 0 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a name - not - found exception . [CODESPLIT] public static NameNotFoundException nameNotFoundException ( final String name , final Name contextName ) { return NamingLogger . ROOT_LOGGER . nameNotFoundInContext ( name , contextName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a general naming exception with a root cause . [CODESPLIT] public static NamingException namingException ( final String message , final Throwable cause ) { final NamingException exception = new NamingException ( message ) ; if ( cause != null ) exception . initCause ( cause ) ; return exception ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a general naming exception with a root cause and a remaining name field . [CODESPLIT] public static NamingException namingException ( final String message , final Throwable cause , final Name remainingName ) { final NamingException exception = namingException ( message , cause ) ; exception . setRemainingName ( remainingName ) ; return exception ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a cannot - proceed exception . [CODESPLIT] public static CannotProceedException cannotProceedException ( final Object resolvedObject , final Name remainingName ) { final CannotProceedException cpe = new CannotProceedException ( ) ; cpe . setResolvedObj ( resolvedObject ) ; cpe . setRemainingName ( remainingName ) ; return cpe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a naming enumeration over a collection . [CODESPLIT] public static < T > NamingEnumeration < T > namingEnumeration ( final Collection < T > collection ) { final Iterator < T > iterator = collection . iterator ( ) ; return new NamingEnumeration < T > ( ) { public T next ( ) { return nextElement ( ) ; } public boolean hasMore ( ) { return hasMoreElements ( ) ; } public void close ( ) { } public boolean hasMoreElements ( ) { return iterator . hasNext ( ) ; } public T nextElement ( ) { return iterator . next ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rebind val to name in ctx and make sure that all intermediate contexts exist [CODESPLIT] public static void rebind ( final Context ctx , final String name , final Object value ) throws NamingException { final Name n = ctx . getNameParser ( \"\" ) . parse ( name ) ; rebind ( ctx , n , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbinds a name from ctx and removes parents if they are empty [CODESPLIT] public static void unbind ( Context ctx , String name ) throws NamingException { unbind ( ctx , ctx . getNameParser ( \"\" ) . parse ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hook to allow subclasses to handle read - attribute requests for attributes other than { @link CommonAttributes#STARTED } . Implementations must not call any of the { @link org . jboss . as . controller . OperationContext#completeStep ( OperationContext . ResultHandler ) context . completeStep variants } . <p > This default implementation just throws the exception returned by { @link #unsupportedAttribute ( String ) } . < / p > [CODESPLIT] protected void handleReadAttribute ( String attributeName , OperationContext context , ModelNode operation ) throws OperationFailedException { unsupportedAttribute ( attributeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hook to allow subclasses to handle operations other than { @code read - attribute } { @code start } and { @code stop } . Implementations must not call any of the { @link org . jboss . as . controller . OperationContext#completeStep ( OperationContext . ResultHandler ) context . completeStep variants } . <p > This default implementation just throws the exception returned by { @link #unsupportedOperation ( String ) } . < / p > [CODESPLIT] protected Object handleOperation ( String operationName , OperationContext context , ModelNode operation ) throws OperationFailedException { unsupportedOperation ( operationName ) ; throw MessagingLogger . ROOT_LOGGER . unsupportedOperation ( operationName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the runtime ActiveMQ control object that can help service this request . [CODESPLIT] protected final T getActiveMQComponentControl ( final OperationContext context , final ModelNode operation , final boolean forWrite ) throws OperationFailedException { final ServiceName artemisServiceName = MessagingServices . getActiveMQServiceName ( PathAddress . pathAddress ( operation . get ( ModelDescriptionConstants . OP_ADDR ) ) ) ; ServiceController < ? > artemisService = context . getServiceRegistry ( forWrite ) . getService ( artemisServiceName ) ; ActiveMQServer server = ActiveMQServer . class . cast ( artemisService . getValue ( ) ) ; PathAddress address = PathAddress . pathAddress ( operation . require ( OP_ADDR ) ) ; T control = getActiveMQComponentControl ( server , address ) ; if ( control == null ) { throw ControllerLogger . ROOT_LOGGER . managementResourceNotFound ( address ) ; } return control ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses connection attributes for version 5 . 0 [CODESPLIT] private String parseConnectionAttributes_5_0 ( final XMLExtendedStreamReader reader , final ModelNode connectionDefinitionNode ) throws XMLStreamException { String poolName = null ; String jndiName = null ; int attributeSize = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < attributeSize ; i ++ ) { ConnectionDefinition . Attribute attribute = ConnectionDefinition . Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; String value = reader . getAttributeValue ( i ) ; switch ( attribute ) { case ENABLED : { ENABLED . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case CONNECTABLE : { CONNECTABLE . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case TRACKING : { TRACKING . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case JNDI_NAME : { jndiName = value ; JNDINAME . parseAndSetParameter ( jndiName , connectionDefinitionNode , reader ) ; break ; } case POOL_NAME : { poolName = value ; break ; } case USE_JAVA_CONTEXT : { USE_JAVA_CONTEXT . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case USE_CCM : { USE_CCM . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case SHARABLE : { SHARABLE . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case ENLISTMENT : { ENLISTMENT . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case CLASS_NAME : { CLASS_NAME . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case MCP : { MCP . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case ENLISTMENT_TRACE : ENLISTMENT_TRACE . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; default : throw ParseUtils . unexpectedAttribute ( reader , i ) ; } } if ( poolName == null || poolName . trim ( ) . equals ( \"\" ) ) { if ( jndiName != null && jndiName . trim ( ) . length ( ) != 0 ) { if ( jndiName . contains ( \"/\" ) ) { poolName = jndiName . substring ( jndiName . lastIndexOf ( \"/\" ) + 1 ) ; } else { poolName = jndiName . substring ( jndiName . lastIndexOf ( \":\" ) + 1 ) ; } } else { throw ParseUtils . missingRequired ( reader , EnumSet . of ( ConnectionDefinition . Attribute . JNDI_NAME ) ) ; } } return poolName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse a single connection - definition tag [CODESPLIT] protected void parseConnectionDefinitions_5_0 ( final XMLExtendedStreamReader reader , final Map < String , ModelNode > map , final Map < String , HashMap < String , ModelNode > > configMap , final boolean isXa ) throws XMLStreamException , ParserException , ValidateException { final ModelNode connectionDefinitionNode = new ModelNode ( ) ; connectionDefinitionNode . get ( OP ) . set ( ADD ) ; final String poolName = parseConnectionAttributes_5_0 ( reader , connectionDefinitionNode ) ; boolean poolDefined = Boolean . FALSE ; while ( reader . hasNext ( ) ) { switch ( reader . nextTag ( ) ) { case END_ELEMENT : { if ( Activation . Tag . forName ( reader . getLocalName ( ) ) == Activation . Tag . CONNECTION_DEFINITION ) { map . put ( poolName , connectionDefinitionNode ) ; return ; } else { if ( ConnectionDefinition . Tag . forName ( reader . getLocalName ( ) ) == ConnectionDefinition . Tag . UNKNOWN ) { throw ParseUtils . unexpectedEndElement ( reader ) ; } } break ; } case START_ELEMENT : { switch ( ConnectionDefinition . Tag . forName ( reader . getLocalName ( ) ) ) { case CONFIG_PROPERTY : { if ( ! configMap . containsKey ( poolName ) ) { configMap . put ( poolName , new HashMap < String , ModelNode > ( 0 ) ) ; } parseConfigProperties ( reader , configMap . get ( poolName ) ) ; break ; } case SECURITY : { parseElytronSupportedSecuritySettings ( reader , connectionDefinitionNode ) ; break ; } case TIMEOUT : { parseTimeOut ( reader , isXa , connectionDefinitionNode ) ; break ; } case VALIDATION : { parseValidation ( reader , connectionDefinitionNode ) ; break ; } case XA_POOL : { if ( ! isXa ) { throw ParseUtils . unexpectedElement ( reader ) ; } if ( poolDefined ) { throw new ParserException ( bundle . multiplePools ( ) ) ; } parseXaPool ( reader , connectionDefinitionNode ) ; poolDefined = true ; break ; } case POOL : { if ( isXa ) { throw ParseUtils . unexpectedElement ( reader ) ; } if ( poolDefined ) { throw new ParserException ( bundle . multiplePools ( ) ) ; } parsePool ( reader , connectionDefinitionNode ) ; poolDefined = true ; break ; } case RECOVERY : { parseElytronSupportedRecovery ( reader , connectionDefinitionNode ) ; break ; } default : throw ParseUtils . unexpectedElement ( reader ) ; } break ; } } } throw ParseUtils . unexpectedEndElement ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse a single connection - definition tag [CODESPLIT] protected void parseConnectionDefinitions_1_0 ( final XMLExtendedStreamReader reader , final Map < String , ModelNode > map , final Map < String , HashMap < String , ModelNode > > configMap , final boolean isXa ) throws XMLStreamException , ParserException , ValidateException { final ModelNode connectionDefinitionNode = new ModelNode ( ) ; connectionDefinitionNode . get ( OP ) . set ( ADD ) ; String poolName = null ; String jndiName = null ; int attributeSize = reader . getAttributeCount ( ) ; boolean poolDefined = Boolean . FALSE ; for ( int i = 0 ; i < attributeSize ; i ++ ) { ConnectionDefinition . Attribute attribute = ConnectionDefinition . Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; String value = reader . getAttributeValue ( i ) ; switch ( attribute ) { case ENABLED : { ENABLED . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case JNDI_NAME : { jndiName = value ; JNDINAME . parseAndSetParameter ( jndiName , connectionDefinitionNode , reader ) ; break ; } case POOL_NAME : { poolName = value ; break ; } case USE_JAVA_CONTEXT : { USE_JAVA_CONTEXT . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case USE_CCM : { USE_CCM . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case SHARABLE : { SHARABLE . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case ENLISTMENT : { ENLISTMENT . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } case CLASS_NAME : { CLASS_NAME . parseAndSetParameter ( value , connectionDefinitionNode , reader ) ; break ; } default : throw ParseUtils . unexpectedAttribute ( reader , i ) ; } } if ( poolName == null || poolName . trim ( ) . equals ( \"\" ) ) { if ( jndiName != null && jndiName . trim ( ) . length ( ) != 0 ) { if ( jndiName . contains ( \"/\" ) ) { poolName = jndiName . substring ( jndiName . lastIndexOf ( \"/\" ) + 1 ) ; } else { poolName = jndiName . substring ( jndiName . lastIndexOf ( \":\" ) + 1 ) ; } } else { throw ParseUtils . missingRequired ( reader , EnumSet . of ( ConnectionDefinition . Attribute . JNDI_NAME ) ) ; } } while ( reader . hasNext ( ) ) { switch ( reader . nextTag ( ) ) { case END_ELEMENT : { if ( Activation . Tag . forName ( reader . getLocalName ( ) ) == Activation . Tag . CONNECTION_DEFINITION ) { map . put ( poolName , connectionDefinitionNode ) ; return ; } else { if ( ConnectionDefinition . Tag . forName ( reader . getLocalName ( ) ) == ConnectionDefinition . Tag . UNKNOWN ) { throw ParseUtils . unexpectedEndElement ( reader ) ; } } break ; } case START_ELEMENT : { switch ( ConnectionDefinition . Tag . forName ( reader . getLocalName ( ) ) ) { case CONFIG_PROPERTY : { if ( ! configMap . containsKey ( poolName ) ) { configMap . put ( poolName , new HashMap < String , ModelNode > ( 0 ) ) ; } parseConfigProperties ( reader , configMap . get ( poolName ) ) ; break ; } case SECURITY : { parseSecuritySettings ( reader , connectionDefinitionNode ) ; break ; } case TIMEOUT : { parseTimeOut ( reader , isXa , connectionDefinitionNode ) ; break ; } case VALIDATION : { parseValidation ( reader , connectionDefinitionNode ) ; break ; } case XA_POOL : { if ( ! isXa ) { throw ParseUtils . unexpectedElement ( reader ) ; } if ( poolDefined ) { throw new ParserException ( bundle . multiplePools ( ) ) ; } parseXaPool ( reader , connectionDefinitionNode ) ; poolDefined = true ; break ; } case POOL : { if ( isXa ) { throw ParseUtils . unexpectedElement ( reader ) ; } if ( poolDefined ) { throw new ParserException ( bundle . multiplePools ( ) ) ; } parsePool ( reader , connectionDefinitionNode ) ; poolDefined = true ; break ; } case RECOVERY : { parseRecovery ( reader , connectionDefinitionNode ) ; break ; } default : throw ParseUtils . unexpectedElement ( reader ) ; } break ; } } } throw ParseUtils . unexpectedEndElement ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse a { @link XaPool } object [CODESPLIT] protected void parseXaPool ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException , ParserException , ValidateException { while ( reader . hasNext ( ) ) { switch ( reader . nextTag ( ) ) { case END_ELEMENT : { if ( XaDataSource . Tag . forName ( reader . getLocalName ( ) ) == XaDataSource . Tag . XA_POOL ) { return ; } else { if ( XaPool . Tag . forName ( reader . getLocalName ( ) ) == XaPool . Tag . UNKNOWN ) { throw ParseUtils . unexpectedEndElement ( reader ) ; } } break ; } case START_ELEMENT : { switch ( XaPool . Tag . forName ( reader . getLocalName ( ) ) ) { case MAX_POOL_SIZE : { String value = rawElementText ( reader ) ; MAX_POOL_SIZE . parseAndSetParameter ( value , node , reader ) ; break ; } case MIN_POOL_SIZE : { String value = rawElementText ( reader ) ; MIN_POOL_SIZE . parseAndSetParameter ( value , node , reader ) ; break ; } case INITIAL_POOL_SIZE : { String value = rawElementText ( reader ) ; INITIAL_POOL_SIZE . parseAndSetParameter ( value , node , reader ) ; break ; } case PREFILL : { String value = rawElementText ( reader ) ; POOL_PREFILL . parseAndSetParameter ( value , node , reader ) ; break ; } case FAIR : { String value = rawElementText ( reader ) ; POOL_FAIR . parseAndSetParameter ( value , node , reader ) ; break ; } case USE_STRICT_MIN : { String value = rawElementText ( reader ) ; POOL_USE_STRICT_MIN . parseAndSetParameter ( value , node , reader ) ; break ; } case FLUSH_STRATEGY : { String value = rawElementText ( reader ) ; POOL_FLUSH_STRATEGY . parseAndSetParameter ( value , node , reader ) ; break ; } case INTERLEAVING : { String value = rawElementText ( reader ) ; //just presence means true value = value == null ? \"true\" : value ; INTERLEAVING . parseAndSetParameter ( value , node , reader ) ; break ; } case IS_SAME_RM_OVERRIDE : { String value = rawElementText ( reader ) ; SAME_RM_OVERRIDE . parseAndSetParameter ( value , node , reader ) ; break ; } case NO_TX_SEPARATE_POOLS : { String value = rawElementText ( reader ) ; //just presence means true value = value == null ? \"true\" : value ; NOTXSEPARATEPOOL . parseAndSetParameter ( value , node , reader ) ; break ; } case PAD_XID : { String value = rawElementText ( reader ) ; PAD_XID . parseAndSetParameter ( value , node , reader ) ; break ; } case WRAP_XA_RESOURCE : { String value = rawElementText ( reader ) ; WRAP_XA_RESOURCE . parseAndSetParameter ( value , node , reader ) ; break ; } case CAPACITY : { parseCapacity ( reader , node ) ; break ; } default : throw ParseUtils . unexpectedElement ( reader ) ; } break ; } } } throw ParseUtils . unexpectedEndElement ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps an existing object instance in a ComponentInstance and run the post construct interceptor chain on it . [CODESPLIT] public ComponentInstance createInstance ( Object instance ) { BasicComponentInstance obj = constructComponentInstance ( new ImmediateManagedReference ( instance ) , true ) ; obj . constructionFinished ( ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct the component instance . Upon return the object instance should have injections and lifecycle invocations completed already . [CODESPLIT] protected BasicComponentInstance constructComponentInstance ( ManagedReference instance , boolean invokePostConstruct ) { return constructComponentInstance ( instance , invokePostConstruct , Collections . emptyMap ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct the component instance . Upon return the object instance should have injections and lifecycle invocations completed already . [CODESPLIT] protected BasicComponentInstance constructComponentInstance ( ManagedReference instance , boolean invokePostConstruct , final Map < Object , Object > context ) { waitForComponentStart ( ) ; // create the component instance final BasicComponentInstance basicComponentInstance = this . instantiateComponentInstance ( preDestroyInterceptor , interceptorInstanceMap , context ) ; if ( instance != null ) { basicComponentInstance . setInstanceData ( BasicComponentInstance . INSTANCE_KEY , instance ) ; } if ( invokePostConstruct ) { // now invoke the postconstruct interceptors final InterceptorContext interceptorContext = new InterceptorContext ( ) ; interceptorContext . putPrivateData ( Component . class , this ) ; interceptorContext . putPrivateData ( ComponentInstance . class , basicComponentInstance ) ; interceptorContext . putPrivateData ( InvocationType . class , InvocationType . POST_CONSTRUCT ) ; interceptorContext . setContextData ( new HashMap < String , Object > ( ) ) ; try { postConstructInterceptor . processInvocation ( interceptorContext ) ; } catch ( Exception e ) { throw EeLogger . ROOT_LOGGER . componentConstructionFailure ( e ) ; } } componentInstanceCreated ( basicComponentInstance ) ; // return the component instance return basicComponentInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void stop ( ) { if ( stopping . compareAndSet ( false , true ) ) { synchronized ( this ) { gate = false ; this . interceptorInstanceMap = null ; this . preDestroyInterceptor = null ; this . postConstructInterceptor = null ; } //TODO: only run this if there is no instances //TODO: trigger destruction of all component instances //TODO: this has lots of potential for race conditions unless we are careful //TODO: using stopContext.asynchronous() and then executing synchronously is pointless. // Use org.jboss.as.server.Services#addServerExecutorDependency to inject an executor to do this async } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges two descriptors either of the parameters will be null . <p / > this method will never return null ; [CODESPLIT] public static InterceptorClassDescription merge ( InterceptorClassDescription existing , InterceptorClassDescription override ) { if ( existing == null && override == null ) { return EMPTY_INSTANCE ; } if ( override == null ) { return existing ; } if ( existing == null ) { return override ; } final Builder builder = builder ( existing ) ; if ( override . getAroundInvoke ( ) != null ) { builder . setAroundInvoke ( override . getAroundInvoke ( ) ) ; } if ( override . getAroundTimeout ( ) != null ) { builder . setAroundTimeout ( override . getAroundTimeout ( ) ) ; } if ( override . getAroundConstruct ( ) != null ) { builder . setAroundConstruct ( override . getAroundConstruct ( ) ) ; } if ( override . getPostConstruct ( ) != null ) { builder . setPostConstruct ( override . getPostConstruct ( ) ) ; } if ( override . getPreDestroy ( ) != null ) { builder . setPreDestroy ( override . getPreDestroy ( ) ) ; } if ( override . getPrePassivate ( ) != null ) { builder . setPrePassivate ( override . getPrePassivate ( ) ) ; } if ( override . getPostActivate ( ) != null ) { builder . setPostActivate ( override . getPostActivate ( ) ) ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup Seam integration resource loader . [CODESPLIT] protected synchronized VirtualFile getResteasySpringVirtualFile ( ) throws DeploymentUnitProcessingException { if ( resourceRoot != null ) { return resourceRoot ; } try { Module module = Module . getBootModuleLoader ( ) . loadModule ( MODULE ) ; URL fileUrl = module . getClassLoader ( ) . getResource ( JAR_LOCATION ) ; if ( fileUrl == null ) { throw JaxrsLogger . JAXRS_LOGGER . noSpringIntegrationJar ( ) ; } File dir = new File ( fileUrl . toURI ( ) ) ; File file = null ; for ( String jar : dir . list ( ) ) { if ( jar . endsWith ( \".jar\" ) ) { file = new File ( dir , jar ) ; break ; } } if ( file == null ) { throw JaxrsLogger . JAXRS_LOGGER . noSpringIntegrationJar ( ) ; } VirtualFile vf = VFS . getChild ( file . toURI ( ) ) ; final Closeable mountHandle = VFS . mountZip ( file , vf , TempFileProviderService . provider ( ) ) ; Service < Closeable > mountHandleService = new Service < Closeable > ( ) { public void start ( StartContext startContext ) throws StartException { } public void stop ( StopContext stopContext ) { VFSUtils . safeClose ( mountHandle ) ; } public Closeable getValue ( ) throws IllegalStateException , IllegalArgumentException { return mountHandle ; } } ; ServiceBuilder < Closeable > builder = serviceTarget . addService ( ServiceName . JBOSS . append ( SERVICE_NAME ) , mountHandleService ) ; builder . setInitialMode ( ServiceController . Mode . ACTIVE ) . install ( ) ; resourceRoot = vf ; return resourceRoot ; } catch ( Exception e ) { throw new DeploymentUnitProcessingException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves runtime name of model resource . [CODESPLIT] protected static String resolveRuntimeName ( final OperationContext context , final PathElement address ) { final ModelNode runtimeName = context . readResourceFromRoot ( PathAddress . pathAddress ( address ) , false ) . getModel ( ) . get ( ModelDescriptionConstants . RUNTIME_NAME ) ; return runtimeName . asString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the deployment annotation index for all classes with the @ManagedBean annotation . For each class with the annotation collect all the required information to create a managed bean instance and attach it to the context . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final EEResourceReferenceProcessorRegistry registry = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . RESOURCE_REFERENCE_PROCESSOR_REGISTRY ) ; final EEModuleDescription moduleDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_MODULE_DESCRIPTION ) ; final CompositeIndex compositeIndex = deploymentUnit . getAttachment ( Attachments . COMPOSITE_ANNOTATION_INDEX ) ; final PropertyReplacer replacer = EJBAnnotationPropertyReplacement . propertyReplacer ( deploymentUnit ) ; if ( compositeIndex == null ) { return ; } final List < AnnotationInstance > instances = compositeIndex . getAnnotations ( MANAGED_BEAN_ANNOTATION_NAME ) ; if ( instances == null || instances . isEmpty ( ) ) { return ; } for ( AnnotationInstance instance : instances ) { AnnotationTarget target = instance . target ( ) ; if ( ! ( target instanceof ClassInfo ) ) { throw EeLogger . ROOT_LOGGER . classOnlyAnnotation ( \"@ManagedBean\" , target ) ; } final ClassInfo classInfo = ( ClassInfo ) target ; // skip if it's not a valid managed bean class if ( ! assertManagedBeanClassValidity ( classInfo ) ) { continue ; } final String beanClassName = classInfo . name ( ) . toString ( ) ; // Get the managed bean name from the annotation final AnnotationValue nameValue = instance . value ( ) ; final String beanName = ( nameValue == null || nameValue . asString ( ) . isEmpty ( ) ) ? beanClassName : replacer . replaceProperties ( nameValue . asString ( ) ) ; final ManagedBeanComponentDescription componentDescription = new ManagedBeanComponentDescription ( beanName , beanClassName , moduleDescription , deploymentUnit . getServiceName ( ) ) ; // Add the view ViewDescription viewDescription = new ViewDescription ( componentDescription , beanClassName ) ; viewDescription . getConfigurators ( ) . addFirst ( new ViewConfigurator ( ) { public void configure ( final DeploymentPhaseContext context , final ComponentConfiguration componentConfiguration , final ViewDescription description , final ViewConfiguration configuration ) throws DeploymentUnitProcessingException { // Add MB association interceptors configuration . addClientPostConstructInterceptor ( ManagedBeanCreateInterceptor . FACTORY , InterceptorOrder . ClientPostConstruct . INSTANCE_CREATE ) ; final ClassLoader classLoader = componentConfiguration . getModuleClassLoader ( ) ; configuration . addViewInterceptor ( AccessCheckingInterceptor . getFactory ( ) , InterceptorOrder . View . CHECKING_INTERCEPTOR ) ; configuration . addViewInterceptor ( new ImmediateInterceptorFactory ( new ContextClassLoaderInterceptor ( classLoader ) ) , InterceptorOrder . View . TCCL_INTERCEPTOR ) ; } } ) ; viewDescription . getBindingNames ( ) . addAll ( Arrays . asList ( \"java:module/\" + beanName , \"java:app/\" + moduleDescription . getModuleName ( ) + \"/\" + beanName ) ) ; componentDescription . getViews ( ) . add ( viewDescription ) ; moduleDescription . addComponent ( componentDescription ) ; // register an EEResourceReferenceProcessor which can process @Resource references to this managed bean. registry . registerResourceReferenceProcessor ( new ManagedBeanResourceReferenceProcessor ( beanClassName ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the passed <code > managedBeanClass< / code > meets the requirements set by the Managed bean spec about bean implementation classes . The passed <code > managedBeanClass< / code > must not be an interface and must not be final or abstract . If it passes these requirements then this method returns true . Else it returns false . [CODESPLIT] private static boolean assertManagedBeanClassValidity ( final ClassInfo managedBeanClass ) { final short flags = managedBeanClass . flags ( ) ; final String className = managedBeanClass . name ( ) . toString ( ) ; // must *not* be an interface if ( Modifier . isInterface ( flags ) ) { ROOT_LOGGER . invalidManagedBeanInterface ( \"MB.2.1.1\" , className ) ; return false ; } // bean class must *not* be abstract or final if ( Modifier . isAbstract ( flags ) || Modifier . isFinal ( flags ) ) { ROOT_LOGGER . invalidManagedBeanAbstractOrFinal ( \"MB.2.1.1\" , className ) ; return false ; } // valid class return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers attributes common across listener types [CODESPLIT] private static PersistentResourceXMLDescription . PersistentResourceXMLBuilder listenerBuilder ( PersistentResourceDefinition resource ) { return builder ( resource . getPathElement ( ) ) // xsd socket-optionsType . addAttributes ( ListenerResourceDefinition . RECEIVE_BUFFER , ListenerResourceDefinition . SEND_BUFFER , ListenerResourceDefinition . BACKLOG , ListenerResourceDefinition . KEEP_ALIVE , ListenerResourceDefinition . READ_TIMEOUT , ListenerResourceDefinition . WRITE_TIMEOUT , ListenerResourceDefinition . MAX_CONNECTIONS ) // xsd listener-type . addAttributes ( ListenerResourceDefinition . SOCKET_BINDING , ListenerResourceDefinition . WORKER , ListenerResourceDefinition . BUFFER_POOL , ListenerResourceDefinition . ENABLED , ListenerResourceDefinition . RESOLVE_PEER_ADDRESS , ListenerResourceDefinition . MAX_ENTITY_SIZE , ListenerResourceDefinition . BUFFER_PIPELINED_DATA , ListenerResourceDefinition . MAX_HEADER_SIZE , ListenerResourceDefinition . MAX_PARAMETERS , ListenerResourceDefinition . MAX_HEADERS , ListenerResourceDefinition . MAX_COOKIES , ListenerResourceDefinition . ALLOW_ENCODED_SLASH , ListenerResourceDefinition . DECODE_URL , ListenerResourceDefinition . URL_CHARSET , ListenerResourceDefinition . ALWAYS_SET_KEEP_ALIVE , ListenerResourceDefinition . MAX_BUFFERED_REQUEST_SIZE , ListenerResourceDefinition . RECORD_REQUEST_START_TIME , ListenerResourceDefinition . ALLOW_EQUALS_IN_COOKIE_VALUE , ListenerResourceDefinition . NO_REQUEST_TIMEOUT , ListenerResourceDefinition . REQUEST_PARSE_TIMEOUT , ListenerResourceDefinition . DISALLOWED_METHODS , ListenerResourceDefinition . SECURE , ListenerResourceDefinition . RFC6265_COOKIE_VALIDATION , ListenerResourceDefinition . ALLOW_UNESCAPED_CHARACTERS_IN_URL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void initialize ( ExtensionContext context ) { TransactionLogger . ROOT_LOGGER . debug ( \"Initializing Transactions Extension\" ) ; final LogStoreResource resource = new LogStoreResource ( ) ; final boolean registerRuntimeOnly = context . isRuntimeOnlyRegistrationValid ( ) ; final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; final TransactionSubsystemRootResourceDefinition rootResourceDefinition = new TransactionSubsystemRootResourceDefinition ( registerRuntimeOnly ) ; final ManagementResourceRegistration registration = subsystem . registerSubsystemModel ( rootResourceDefinition ) ; registration . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; // Create the path resolver handlers if ( context . getProcessType ( ) . isServer ( ) ) { // It's less than ideal to create a separate operation here, but this extension contains two relative-to attributes final ResolvePathHandler objectStorePathHandler = ResolvePathHandler . Builder . of ( RESOLVE_OBJECT_STORE_PATH , context . getPathManager ( ) ) . setPathAttribute ( TransactionSubsystemRootResourceDefinition . OBJECT_STORE_PATH ) . setRelativeToAttribute ( TransactionSubsystemRootResourceDefinition . OBJECT_STORE_RELATIVE_TO ) . build ( ) ; registration . registerOperationHandler ( objectStorePathHandler . getOperationDefinition ( ) , objectStorePathHandler ) ; } ManagementResourceRegistration logStoreChild = registration . registerSubModel ( new LogStoreDefinition ( resource , registerRuntimeOnly ) ) ; if ( registerRuntimeOnly ) { ManagementResourceRegistration transactionChild = logStoreChild . registerSubModel ( new LogStoreTransactionDefinition ( resource ) ) ; transactionChild . registerSubModel ( LogStoreTransactionParticipantDefinition . INSTANCE ) ; } subsystem . registerXMLElementWriter ( TransactionSubsystemXMLPersister . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_1_0 . getUriString ( ) , TransactionSubsystem10Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_1_1 . getUriString ( ) , TransactionSubsystem11Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_1_2 . getUriString ( ) , TransactionSubsystem12Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_1_3 . getUriString ( ) , TransactionSubsystem13Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_1_4 . getUriString ( ) , TransactionSubsystem14Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_1_5 . getUriString ( ) , TransactionSubsystem15Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_2_0 . getUriString ( ) , TransactionSubsystem20Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_3_0 . getUriString ( ) , TransactionSubsystem30Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_4_0 . getUriString ( ) , TransactionSubsystem40Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . TRANSACTIONS_5_0 . getUriString ( ) , TransactionSubsystem50Parser :: new ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a singleton instance representing one of the primitive types . [CODESPLIT] public static PrimitiveAnalysis getPrimitiveAnalysis ( final Class cls ) { if ( cls == null ) throw IIOPLogger . ROOT_LOGGER . cannotAnalyzeNullClass ( ) ; if ( cls == Void . TYPE ) return voidAnalysis ; if ( cls == Boolean . TYPE ) return booleanAnalysis ; if ( cls == Character . TYPE ) return charAnalysis ; if ( cls == Byte . TYPE ) return byteAnalysis ; if ( cls == Short . TYPE ) return shortAnalysis ; if ( cls == Integer . TYPE ) return intAnalysis ; if ( cls == Long . TYPE ) return longAnalysis ; if ( cls == Float . TYPE ) return floatAnalysis ; if ( cls == Double . TYPE ) return doubleAnalysis ; throw IIOPLogger . ROOT_LOGGER . notAPrimitive ( cls . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upon calling this method the EJB will be set to a shutdown state and no further invocations will be allowed . It will then wait for all active invocation to finish and then return . [CODESPLIT] public void shutdown ( ) { int value ; int oldValue ; //set the shutdown bit do { oldValue = invocationCount ; value = SHUTDOWN_FLAG | oldValue ; //the component has already been shutdown if ( oldValue == value ) { return ; } } while ( ! updater . compareAndSet ( this , oldValue , value ) ) ; synchronized ( lock ) { value = invocationCount ; while ( value != SHUTDOWN_FLAG ) { try { lock . wait ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } value = invocationCount ; if ( ( value & SHUTDOWN_FLAG ) == 0 ) { return ; //component has been restarted } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create EE container entity manager factory [CODESPLIT] private EntityManagerFactory createContainerEntityManagerFactory ( ) { persistenceProviderAdaptor . beforeCreateContainerEntityManagerFactory ( pu ) ; try { ROOT_LOGGER . tracef ( \"calling createContainerEntityManagerFactory for pu=%s with integration properties=%s, application properties=%s\" , pu . getScopedPersistenceUnitName ( ) , properties , pu . getProperties ( ) ) ; return persistenceProvider . createContainerEntityManagerFactory ( pu , properties ) ; } finally { try { persistenceProviderAdaptor . afterCreateContainerEntityManagerFactory ( pu ) ; } finally { pu . setAnnotationIndex ( null ) ; // close reference to Annotation Index (only needed during call to createContainerEntityManagerFactory) //This is needed if the datasource is restarted //pu.setTempClassLoaderFactory(null);    // close reference to temp classloader factory (only needed during call to createEntityManagerFactory) } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates URL pattern list from passed string . [CODESPLIT] public static List < String > getUrlPatterns ( final String urlPattern ) { final List < String > linkedList = new LinkedList < String > ( ) ; linkedList . add ( urlPattern ) ; return linkedList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets servlets meta data from jboss web meta data . If not found it creates new servlets meta data and associates them with jboss web meta data . [CODESPLIT] public static JBossServletsMetaData getServlets ( final JBossWebMetaData jbossWebMD ) { JBossServletsMetaData servletsMD = jbossWebMD . getServlets ( ) ; if ( servletsMD == null ) { servletsMD = new JBossServletsMetaData ( ) ; jbossWebMD . setServlets ( servletsMD ) ; } return servletsMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets servlet mappings meta data from jboss web meta data . If not found it creates new servlet mappings meta data and associates them with jboss web meta data . [CODESPLIT] public static List < ServletMappingMetaData > getServletMappings ( final JBossWebMetaData jbossWebMD ) { List < ServletMappingMetaData > servletMappingsMD = jbossWebMD . getServletMappings ( ) ; if ( servletMappingsMD == null ) { servletMappingsMD = new LinkedList < ServletMappingMetaData > ( ) ; jbossWebMD . setServletMappings ( servletMappingsMD ) ; } return servletMappingsMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets security constraints meta data from jboss web meta data . If not found it creates new security constraints meta data and associates them with jboss web meta data . [CODESPLIT] public static List < SecurityConstraintMetaData > getSecurityConstraints ( final JBossWebMetaData jbossWebMD ) { List < SecurityConstraintMetaData > securityConstraintsMD = jbossWebMD . getSecurityConstraints ( ) ; if ( securityConstraintsMD == null ) { securityConstraintsMD = new LinkedList < SecurityConstraintMetaData > ( ) ; jbossWebMD . setSecurityConstraints ( securityConstraintsMD ) ; } return securityConstraintsMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets login config meta data from jboss web meta data . If not found it creates new login config meta data and associates them with jboss web meta data . [CODESPLIT] public static LoginConfigMetaData getLoginConfig ( final JBossWebMetaData jbossWebMD ) { LoginConfigMetaData loginConfigMD = jbossWebMD . getLoginConfig ( ) ; if ( loginConfigMD == null ) { loginConfigMD = new LoginConfigMetaData ( ) ; jbossWebMD . setLoginConfig ( loginConfigMD ) ; } return loginConfigMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets context parameters meta data from jboss web meta data . If not found it creates new context parameters meta data and associates them with jboss web meta data . [CODESPLIT] public static List < ParamValueMetaData > getContextParams ( final JBossWebMetaData jbossWebMD ) { List < ParamValueMetaData > contextParamsMD = jbossWebMD . getContextParams ( ) ; if ( contextParamsMD == null ) { contextParamsMD = new LinkedList < ParamValueMetaData > ( ) ; jbossWebMD . setContextParams ( contextParamsMD ) ; } return contextParamsMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets web resource collections meta data from security constraint meta data . If not found it creates new web resource collections meta data and associates them with security constraint meta data . [CODESPLIT] public static WebResourceCollectionsMetaData getWebResourceCollections ( final SecurityConstraintMetaData securityConstraintMD ) { WebResourceCollectionsMetaData webResourceCollectionsMD = securityConstraintMD . getResourceCollections ( ) ; if ( webResourceCollectionsMD == null ) { webResourceCollectionsMD = new WebResourceCollectionsMetaData ( ) ; securityConstraintMD . setResourceCollections ( webResourceCollectionsMD ) ; } return webResourceCollectionsMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets init parameters meta data from servlet meta data . If not found it creates new init parameters meta data and associates them with servlet meta data . [CODESPLIT] public static List < ParamValueMetaData > getServletInitParams ( final ServletMetaData servletMD ) { List < ParamValueMetaData > initParamsMD = servletMD . getInitParam ( ) ; if ( initParamsMD == null ) { initParamsMD = new LinkedList < ParamValueMetaData > ( ) ; servletMD . setInitParam ( initParamsMD ) ; } return initParamsMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new security constraint meta data and associates them with security constraints meta data . [CODESPLIT] public static SecurityConstraintMetaData newSecurityConstraint ( final List < SecurityConstraintMetaData > securityConstraintsMD ) { final SecurityConstraintMetaData securityConstraintMD = new SecurityConstraintMetaData ( ) ; securityConstraintsMD . add ( securityConstraintMD ) ; return securityConstraintMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new web resource collection meta data and associates them with web resource collections meta data . [CODESPLIT] public static WebResourceCollectionMetaData newWebResourceCollection ( final String servletName , final String urlPattern , final boolean securedWsdl , final WebResourceCollectionsMetaData webResourceCollectionsMD ) { final WebResourceCollectionMetaData webResourceCollectionMD = new WebResourceCollectionMetaData ( ) ; webResourceCollectionMD . setWebResourceName ( servletName ) ; webResourceCollectionMD . setUrlPatterns ( WebMetaDataHelper . getUrlPatterns ( urlPattern ) ) ; webResourceCollectionMD . setHttpMethods ( WebMetaDataHelper . getHttpMethods ( securedWsdl ) ) ; webResourceCollectionsMD . add ( webResourceCollectionMD ) ; return webResourceCollectionMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new servlet meta data and associates them with servlets meta data . [CODESPLIT] public static JBossServletMetaData newServlet ( final String servletName , final String servletClass , final JBossServletsMetaData servletsMD ) { final JBossServletMetaData servletMD = new JBossServletMetaData ( ) ; servletMD . setServletName ( servletName ) ; servletMD . setServletClass ( servletClass ) ; servletsMD . add ( servletMD ) ; return servletMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new servlet mapping meta data and associates them with servlet mappings meta data . [CODESPLIT] public static ServletMappingMetaData newServletMapping ( final String servletName , final List < String > urlPatterns , final List < ServletMappingMetaData > servletMappingsMD ) { final ServletMappingMetaData servletMappingMD = new ServletMappingMetaData ( ) ; servletMappingMD . setServletName ( servletName ) ; servletMappingMD . setUrlPatterns ( urlPatterns ) ; servletMappingsMD . add ( servletMappingMD ) ; return servletMappingMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new authentication constraint and associates it with security constraint meta data . [CODESPLIT] public static AuthConstraintMetaData newAuthConstraint ( final List < String > roleNames , final SecurityConstraintMetaData securityConstraintMD ) { final AuthConstraintMetaData authConstraintMD = new AuthConstraintMetaData ( ) ; authConstraintMD . setRoleNames ( roleNames ) ; securityConstraintMD . setAuthConstraint ( authConstraintMD ) ; return authConstraintMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new user constraint meta data and associates it with security constraint meta data . [CODESPLIT] public static UserDataConstraintMetaData newUserDataConstraint ( final String transportGuarantee , final SecurityConstraintMetaData securityConstraintMD ) { final UserDataConstraintMetaData userDataConstraintMD = new UserDataConstraintMetaData ( ) ; final TransportGuaranteeType transportGuaranteeValue = TransportGuaranteeType . valueOf ( transportGuarantee ) ; userDataConstraintMD . setTransportGuarantee ( transportGuaranteeValue ) ; securityConstraintMD . setUserDataConstraint ( userDataConstraintMD ) ; return userDataConstraintMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new parameter meta data and associates it with parameters meta data . [CODESPLIT] public static ParamValueMetaData newParamValue ( final String key , final String value , final List < ParamValueMetaData > paramsMD ) { final ParamValueMetaData paramValueMD = WebMetaDataHelper . newParamValue ( key , value ) ; paramsMD . add ( paramValueMD ) ; return paramValueMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new parameter with specified key and value . [CODESPLIT] private static ParamValueMetaData newParamValue ( final String key , final String value ) { final ParamValueMetaData paramMD = new ParamValueMetaData ( ) ; paramMD . setParamName ( key ) ; paramMD . setParamValue ( value ) ; return paramMD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for standard ra deployment files . Will parse the xml file and attach a configuration discovered during processing . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final CapabilityServiceSupport support = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; final List < DataSources > dataSourcesList = deploymentUnit . getAttachmentList ( DsXmlDeploymentParsingProcessor . DATA_SOURCES_ATTACHMENT_KEY ) ; final boolean legacySecurityPresent = phaseContext . getDeploymentUnit ( ) . hasAttachment ( SecurityAttachments . SECURITY_ENABLED ) ; for ( DataSources dataSources : dataSourcesList ) { if ( dataSources . getDrivers ( ) != null && dataSources . getDrivers ( ) . size ( ) > 0 ) { ConnectorLogger . DS_DEPLOYER_LOGGER . driversElementNotSupported ( deploymentUnit . getName ( ) ) ; } ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; if ( dataSources . getDataSource ( ) != null && dataSources . getDataSource ( ) . size ( ) > 0 ) { for ( int i = 0 ; i < dataSources . getDataSource ( ) . size ( ) ; i ++ ) { DataSource ds = ( DataSource ) dataSources . getDataSource ( ) . get ( i ) ; if ( ds . isEnabled ( ) && ds . getDriver ( ) != null ) { try { final String jndiName = Util . cleanJndiName ( ds . getJndiName ( ) , ds . isUseJavaContext ( ) ) ; LocalDataSourceService lds = new LocalDataSourceService ( jndiName , ContextNames . bindInfoFor ( jndiName ) ) ; lds . getDataSourceConfigInjector ( ) . inject ( buildDataSource ( ds ) ) ; final String dsName = ds . getJndiName ( ) ; final PathAddress addr = getDataSourceAddress ( dsName , deploymentUnit , false ) ; installManagementModel ( ds , deploymentUnit , addr ) ; // TODO why have we been ignoring a configured legacy security domain but no legacy security present? boolean useLegacySecurity = legacySecurityPresent && isLegacySecurityRequired ( ds . getSecurity ( ) ) ; startDataSource ( lds , jndiName , ds . getDriver ( ) , serviceTarget , getRegistration ( false , deploymentUnit ) , getResource ( dsName , false , deploymentUnit ) , dsName , useLegacySecurity , ds . isJTA ( ) , support ) ; } catch ( Exception e ) { throw ConnectorLogger . ROOT_LOGGER . exceptionDeployingDatasource ( e , ds . getJndiName ( ) ) ; } } else { ConnectorLogger . DS_DEPLOYER_LOGGER . debugf ( \"Ignoring: %s\" , ds . getJndiName ( ) ) ; } } } if ( dataSources . getXaDataSource ( ) != null && dataSources . getXaDataSource ( ) . size ( ) > 0 ) { for ( int i = 0 ; i < dataSources . getXaDataSource ( ) . size ( ) ; i ++ ) { XaDataSource xads = ( XaDataSource ) dataSources . getXaDataSource ( ) . get ( i ) ; if ( xads . isEnabled ( ) && xads . getDriver ( ) != null ) { try { String jndiName = Util . cleanJndiName ( xads . getJndiName ( ) , xads . isUseJavaContext ( ) ) ; XaDataSourceService xds = new XaDataSourceService ( jndiName , ContextNames . bindInfoFor ( jndiName ) ) ; xds . getDataSourceConfigInjector ( ) . inject ( buildXaDataSource ( xads ) ) ; final String dsName = xads . getJndiName ( ) ; final PathAddress addr = getDataSourceAddress ( dsName , deploymentUnit , true ) ; installManagementModel ( xads , deploymentUnit , addr ) ; final Credential credential = xads . getRecovery ( ) == null ? null : xads . getRecovery ( ) . getCredential ( ) ; // TODO why have we been ignoring a configured legacy security domain but no legacy security present? boolean useLegacySecurity = legacySecurityPresent && ( isLegacySecurityRequired ( xads . getSecurity ( ) ) || isLegacySecurityRequired ( credential ) ) ; startDataSource ( xds , jndiName , xads . getDriver ( ) , serviceTarget , getRegistration ( true , deploymentUnit ) , getResource ( dsName , true , deploymentUnit ) , dsName , useLegacySecurity , true , support ) ; } catch ( Exception e ) { throw ConnectorLogger . ROOT_LOGGER . exceptionDeployingDatasource ( e , xads . getJndiName ( ) ) ; } } else { ConnectorLogger . DS_DEPLOYER_LOGGER . debugf ( \"Ignoring %s\" , xads . getJndiName ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; final ServicesAttachment servicesAttachment = deploymentUnit . getAttachment ( Attachments . SERVICES ) ; if ( module != null && servicesAttachment != null ) { final ModuleClassLoader classLoader = module . getClassLoader ( ) ; final List < String > driverNames = servicesAttachment . getServiceImplementations ( Driver . class . getName ( ) ) ; int idx = 0 ; for ( String driverClassName : driverNames ) { try { final Class < ? extends Driver > driverClass = classLoader . loadClass ( driverClassName ) . asSubclass ( Driver . class ) ; final Constructor < ? extends Driver > constructor = driverClass . getConstructor ( ) ; final Driver driver = constructor . newInstance ( ) ; final int majorVersion = driver . getMajorVersion ( ) ; final int minorVersion = driver . getMinorVersion ( ) ; final boolean compliant = driver . jdbcCompliant ( ) ; if ( compliant ) { DEPLOYER_JDBC_LOGGER . deployingCompliantJdbcDriver ( driverClass , Integer . valueOf ( majorVersion ) , Integer . valueOf ( minorVersion ) ) ; } else { DEPLOYER_JDBC_LOGGER . deployingNonCompliantJdbcDriver ( driverClass , Integer . valueOf ( majorVersion ) , Integer . valueOf ( minorVersion ) ) ; } String driverName = deploymentUnit . getName ( ) ; if ( ( driverName . contains ( \".\" ) && ! driverName . endsWith ( \".jar\" ) ) || driverNames . size ( ) != 1 ) { driverName += \"_\" + driverClassName + \"_\" + majorVersion + \"_\" + minorVersion ; } InstalledDriver driverMetadata = new InstalledDriver ( driverName , driverClass . getName ( ) , null , null , majorVersion , minorVersion , compliant ) ; DriverService driverService = new DriverService ( driverMetadata , driver ) ; phaseContext . getServiceTarget ( ) . addService ( ServiceName . JBOSS . append ( \"jdbc-driver\" , driverName . replaceAll ( \"\\\\.\" , \"_\" ) ) , driverService ) . addDependency ( ConnectorServices . JDBC_DRIVER_REGISTRY_SERVICE , DriverRegistry . class , driverService . getDriverRegistryServiceInjector ( ) ) . setInitialMode ( Mode . ACTIVE ) . install ( ) ; if ( idx == 0 && driverNames . size ( ) != 1 ) { // create short name driver service driverName = deploymentUnit . getName ( ) ; // reset driverName to the deployment unit name driverMetadata = new InstalledDriver ( driverName , driverClass . getName ( ) , null , null , majorVersion , minorVersion , compliant ) ; driverService = new DriverService ( driverMetadata , driver ) ; phaseContext . getServiceTarget ( ) . addService ( ServiceName . JBOSS . append ( \"jdbc-driver\" , driverName . replaceAll ( \"\\\\.\" , \"_\" ) ) , driverService ) . addDependency ( ConnectorServices . JDBC_DRIVER_REGISTRY_SERVICE , DriverRegistry . class , driverService . getDriverRegistryServiceInjector ( ) ) . setInitialMode ( Mode . ACTIVE ) . install ( ) ; } idx ++ ; } catch ( Throwable e ) { DEPLOYER_JDBC_LOGGER . cannotInstantiateDriverClass ( driverClassName , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the <code > interceptor - binding< / code > element and returns the corresponding { @link InterceptorBindingMetaData } [CODESPLIT] private InterceptorBindingMetaData readInterceptorBinding ( final XMLStreamReader reader , final PropertyReplacer propertyReplacer ) throws XMLStreamException { return InterceptorBindingMetaDataParser . INSTANCE . parse ( reader , propertyReplacer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register our listeners on SFSB that will be created [CODESPLIT] private void registerSessionBeanInterceptors ( SessionBeanComponentDescription componentDescription , final DeploymentUnit deploymentUnit ) { // if it's a SFSB then setup appropriate interceptors if ( componentDescription . isStateful ( ) ) { // first setup the post construct and pre destroy component interceptors componentDescription . getConfigurators ( ) . addFirst ( new ComponentConfigurator ( ) { @ Override public void configure ( DeploymentPhaseContext context , ComponentDescription description , ComponentConfiguration configuration ) throws DeploymentUnitProcessingException { configuration . addPostConstructInterceptor ( SFSBPreCreateInterceptor . FACTORY , InterceptorOrder . ComponentPostConstruct . JPA_SFSB_PRE_CREATE ) ; configuration . addPostConstructInterceptor ( SFSBCreateInterceptor . FACTORY , InterceptorOrder . ComponentPostConstruct . JPA_SFSB_CREATE ) ; configuration . addPreDestroyInterceptor ( SFSBDestroyInterceptor . FACTORY , InterceptorOrder . ComponentPreDestroy . JPA_SFSB_DESTROY ) ; configuration . addComponentInterceptor ( SFSBInvocationInterceptor . FACTORY , InterceptorOrder . Component . JPA_SFSB_INTERCEPTOR , false ) ; //we need to serialized the entity manager state configuration . getInterceptorContextKeys ( ) . add ( SFSBInvocationInterceptor . CONTEXT_KEY ) ; } } ) ; } // register interceptor on stateful/stateless SB with transactional entity manager. if ( ( componentDescription . isStateful ( ) || componentDescription . isStateless ( ) ) ) { componentDescription . getConfigurators ( ) . add ( new ComponentConfigurator ( ) { @ Override public void configure ( DeploymentPhaseContext context , ComponentDescription description , ComponentConfiguration configuration ) throws DeploymentUnitProcessingException { configuration . addComponentInterceptor ( SBInvocationInterceptor . FACTORY , InterceptorOrder . Component . JPA_SESSION_BEAN_INTERCEPTOR , false ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Make a deep copy of an { @code IOP : TaggedComponent } . < / p > [CODESPLIT] public static TaggedComponent createCopy ( TaggedComponent tc ) { TaggedComponent copy = null ; if ( tc != null ) { byte [ ] buf = new byte [ tc . component_data . length ] ; System . arraycopy ( tc . component_data , 0 , buf , 0 , tc . component_data . length ) ; copy = new TaggedComponent ( tc . tag , buf ) ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Return a top - level { @code IOP :: TaggedComponent } to be stuffed into an IOR containing a structure { @code SSLIOP :: SSL } tagged as { @code TAG_SSL_SEC_TRANS } . < / p > <p > Should be called with non - null metadata in which case we probably don t want to include security info in the IOR . < / p > [CODESPLIT] public static TaggedComponent createSSLTaggedComponent ( IORSecurityConfigMetaData metadata , Codec codec , int sslPort , ORB orb ) { if ( metadata == null ) { IIOPLogger . ROOT_LOGGER . debug ( \"Method createSSLTaggedComponent() called with null metadata\" ) ; return null ; } if ( sslPort == 0 ) { // no support for transport security. return null ; } TaggedComponent tc ; try { int supports = createTargetSupports ( metadata . getTransportConfig ( ) ) ; int requires = createTargetRequires ( metadata . getTransportConfig ( ) ) ; SSL ssl = new SSL ( ( short ) supports , ( short ) requires , ( short ) sslPort ) ; Any any = orb . create_any ( ) ; SSLHelper . insert ( any , ssl ) ; byte [ ] componentData = codec . encode_value ( any ) ; tc = new TaggedComponent ( TAG_SSL_SEC_TRANS . value , componentData ) ; } catch ( InvalidTypeForEncoding e ) { throw IIOPLogger . ROOT_LOGGER . unexpectedException ( e ) ; } return tc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Return a top - level { @code IOP : TaggedComponent } to be stuffed into an IOR containing a { @code org . omg . CSIIOP } . { @code CompoundSecMechList } tagged as { @code TAG_CSI_SEC_MECH_LIST } . Only one such component can exist inside an IOR . < / p > <p > Should be called with non - null metadata in which case we probably don t want to include security info in the IOR . < / p > [CODESPLIT] public static TaggedComponent createSecurityTaggedComponent ( IORSecurityConfigMetaData metadata , Codec codec , int sslPort , ORB orb ) { if ( metadata == null ) { IIOPLogger . ROOT_LOGGER . debug ( \"Method createSecurityTaggedComponent() called with null metadata\" ) ; return null ; } TaggedComponent tc ; // get the the supported security mechanisms. CompoundSecMech [ ] mechList = createCompoundSecMechanisms ( metadata , codec , sslPort , orb ) ; // the above is wrapped into a org.omg.CSIIOP.CompoundSecMechList structure, which is NOT a CompoundSecMech[]. // we don't support stateful/reusable security contexts (false). CompoundSecMechList csmList = new CompoundSecMechList ( false , mechList ) ; // finally, the CompoundSecMechList must be encoded as a TaggedComponent try { Any any = orb . create_any ( ) ; CompoundSecMechListHelper . insert ( any , csmList ) ; byte [ ] b = codec . encode_value ( any ) ; tc = new TaggedComponent ( TAG_CSI_SEC_MECH_LIST . value , b ) ; } catch ( InvalidTypeForEncoding e ) { throw IIOPLogger . ROOT_LOGGER . unexpectedException ( e ) ; } return tc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create a { @code org . omg . CSIIOP . CompoundSecMechanisms } which is a sequence of { @code CompoundSecMech } . Here we only support one security mechanism . < / p > [CODESPLIT] public static CompoundSecMech [ ] createCompoundSecMechanisms ( IORSecurityConfigMetaData metadata , Codec codec , int sslPort , ORB orb ) { // support just 1 security mechanism for now (and ever). CompoundSecMech [ ] csmList = new CompoundSecMech [ 1 ] ; // a CompoundSecMech contains: target_requires, transport_mech, as_context_mech, sas_context_mech. TaggedComponent transport_mech = createTransportMech ( metadata . getTransportConfig ( ) , codec , sslPort , orb ) ; // create AS Context. AS_ContextSec asContext = createAuthenticationServiceContext ( metadata ) ; // create SAS Context. SAS_ContextSec sasContext = createSecureAttributeServiceContext ( metadata ) ; // create target_requires bit field (AssociationOption) can't read directly the transport_mech TaggedComponent. int target_requires = createTargetRequires ( metadata . getTransportConfig ( ) ) | asContext . target_requires | sasContext . target_requires ; CompoundSecMech csm = new CompoundSecMech ( ( short ) target_requires , transport_mech , asContext , sasContext ) ; csmList [ 0 ] = csm ; return csmList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create the Secure Attribute Service ( SAS ) context included in a { @code CompoundSecMech } definition . < / p > [CODESPLIT] public static SAS_ContextSec createSecureAttributeServiceContext ( IORSecurityConfigMetaData metadata ) { SAS_ContextSec context ; // context contains target_supports, target_requires, privilige_authorities, supported_naming_mechanisms, supported_identity_types. int support = 0 ; int require = 0 ; ServiceConfiguration [ ] privilAuth = new ServiceConfiguration [ 0 ] ; byte [ ] [ ] supNamMechs = { } ; int supIdenTypes = 0 ; // 0 means ITTAbsent // the the SasContext metadata. IORSASContextMetaData sasMeta = metadata . getSasContext ( ) ; // if no SAS context metadata, or caller propagation is not supported, we return with a more or less empty sas context. if ( sasMeta == null || sasMeta . getCallerPropagation ( ) . equals ( IORSASContextMetaData . CALLER_PROPAGATION_NONE ) ) { context = new SAS_ContextSec ( ( short ) support , ( short ) require , privilAuth , supNamMechs , supIdenTypes ) ; } else { support = IdentityAssertion . value ; // supporting GSSUP (username/password) naming mechanism. byte [ ] upMech = createGSSUPMechOID ( ) ; supNamMechs = new byte [ 1 ] [ upMech . length ] ; System . arraycopy ( upMech , 0 , supNamMechs [ 0 ] , 0 , upMech . length ) ; // since we support IdentityAssertion we need to specify supported identity types. CTS says we need them all supIdenTypes = ITTAnonymous . value | ITTPrincipalName . value | ITTX509CertChain . value | ITTDistinguishedName . value ; context = new SAS_ContextSec ( ( short ) support , ( short ) require , privilAuth , supNamMechs , supIdenTypes ) ; } return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create the client Authentication Service ( AS ) context included in a { @code CompoundSecMech } definition . < / p > [CODESPLIT] public static AS_ContextSec createAuthenticationServiceContext ( IORSecurityConfigMetaData metadata ) { AS_ContextSec context ; // the content of the context. int support = 0 ; int require = 0 ; byte [ ] clientAuthMech = { } ; byte [ ] targetName = { } ; IORASContextMetaData asMeta = metadata . getAsContext ( ) ; // if no AS context metatada exists, or authentication method \"none\" is specified, we can produce an empty AS context. if ( asMeta == null || asMeta . getAuthMethod ( ) . equals ( IORASContextMetaData . AUTH_METHOD_NONE ) ) { context = new AS_ContextSec ( ( short ) support , ( short ) require , clientAuthMech , targetName ) ; } else { // we do support. support = EstablishTrustInClient . value ; // required depends on the metadata. if ( asMeta . isRequired ( ) ) { require = EstablishTrustInClient . value ; } // we only support GSSUP authentication method. clientAuthMech = createGSSUPMechOID ( ) ; // finally, encode the \"realm\" name as a CSI.GSS_NT_ExportedName. // clientAuthMech should contain the DER encoded GSSUPMechOID at this point. String realm = asMeta . getRealm ( ) ; targetName = createGSSExportedName ( clientAuthMech , realm . getBytes ( StandardCharsets . UTF_8 ) ) ; context = new AS_ContextSec ( ( short ) support , ( short ) require , clientAuthMech , targetName ) ; } return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create a transport mechanism { @code TaggedComponent } to be stuffed into a { @code CompoundSecMech } . < / p > <p > If no { @code TransportConfig } metadata is specified or ssl port is negative or the specified metadata indicates that transport config is not supported then a { @code TAG_NULL_TAG } ( empty ) { @code TaggedComponent } will be returned . < / p > <p > Otherwise a { @code org . omg . CSIIOP . TLS_SEC_TRANS } tagged as { @code TAG_TLS_SEC_TRANS } will be returned indicating support for TLS / SSL as a CSIv2 transport mechanism . < / p > <p > Multiple { @code TransportAddress } may be included in the SSL info ( host / port pairs ) but we only include one . < / p > [CODESPLIT] public static TaggedComponent createTransportMech ( IORTransportConfigMetaData tconfig , Codec codec , int sslPort , ORB orb ) { TaggedComponent tc ; // what we support and require as a target. int support = 0 ; int require = 0 ; if ( tconfig != null ) { require = createTargetRequires ( tconfig ) ; support = createTargetSupports ( tconfig ) ; } if ( tconfig == null || support == 0 || sslPort == 0 ) { // no support for transport security. tc = new TaggedComponent ( TAG_NULL_TAG . value , new byte [ 0 ] ) ; } else { // my ip address. String host = CorbaORBService . getORBProperty ( Constants . ORB_ADDRESS ) ; // this will create only one transport address. TransportAddress [ ] taList = createTransportAddress ( host , sslPort ) ; TLS_SEC_TRANS tst = new TLS_SEC_TRANS ( ( short ) support , ( short ) require , taList ) ; // The tricky part, we must encode TLS_SEC_TRANS into an octet sequence. try { Any any = orb . create_any ( ) ; TLS_SEC_TRANSHelper . insert ( any , tst ) ; byte [ ] b = codec . encode_value ( any ) ; tc = new TaggedComponent ( TAG_TLS_SEC_TRANS . value , b ) ; } catch ( InvalidTypeForEncoding e ) { throw IIOPLogger . ROOT_LOGGER . unexpectedException ( e ) ; } } return tc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create a { @code TransportAddress [] } with a single { @code TransportAddress } . < / p > [CODESPLIT] public static TransportAddress [ ] createTransportAddress ( String host , int port ) { // idl type is unsigned sort, so we need this trick short short_port = ( port > 32767 ) ? ( short ) ( port - 65536 ) : ( short ) port ; TransportAddress ta = new TransportAddress ( host , short_port ) ; TransportAddress [ ] taList = new TransportAddress [ 1 ] ; taList [ 0 ] = ta ; return taList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create the bitmask of what the target requires . < / p > [CODESPLIT] public static int createTargetRequires ( IORTransportConfigMetaData tc ) { int requires = 0 ; if ( tc != null ) { if ( tc . getIntegrity ( ) . equals ( IORTransportConfigMetaData . INTEGRITY_REQUIRED ) ) { requires = requires | Integrity . value ; } if ( tc . getConfidentiality ( ) . equals ( IORTransportConfigMetaData . CONFIDENTIALITY_REQUIRED ) ) { requires = requires | Confidentiality . value ; } if ( tc . getDetectMisordering ( ) . equalsIgnoreCase ( IORTransportConfigMetaData . DETECT_MISORDERING_REQUIRED ) ) { requires = requires | DetectMisordering . value ; } if ( tc . getDetectReplay ( ) . equalsIgnoreCase ( IORTransportConfigMetaData . DETECT_REPLAY_REQUIRED ) ) { requires = requires | DetectReplay . value ; } // no EstablishTrustInTarget required - client decides if ( tc . getEstablishTrustInClient ( ) . equals ( IORTransportConfigMetaData . ESTABLISH_TRUST_IN_CLIENT_REQUIRED ) ) { requires = requires | EstablishTrustInClient . value ; } } return requires ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create the bitmask of what the target supports . < / p > [CODESPLIT] public static int createTargetSupports ( IORTransportConfigMetaData tc ) { int supports = 0 ; if ( tc != null ) { if ( ! tc . getIntegrity ( ) . equals ( IORTransportConfigMetaData . INTEGRITY_NONE ) ) { supports = supports | Integrity . value ; } if ( ! tc . getConfidentiality ( ) . equals ( IORTransportConfigMetaData . CONFIDENTIALITY_NONE ) ) { supports = supports | Confidentiality . value ; } if ( ! tc . getDetectMisordering ( ) . equalsIgnoreCase ( IORTransportConfigMetaData . DETECT_MISORDERING_NONE ) ) { supports = supports | DetectMisordering . value ; } if ( ! tc . getDetectReplay ( ) . equalsIgnoreCase ( IORTransportConfigMetaData . DETECT_REPLAY_NONE ) ) { supports = supports | DetectReplay . value ; } if ( ! tc . getEstablishTrustInTarget ( ) . equals ( IORTransportConfigMetaData . ESTABLISH_TRUST_IN_TARGET_NONE ) ) { supports = supports | EstablishTrustInTarget . value ; } if ( ! tc . getEstablishTrustInClient ( ) . equals ( IORTransportConfigMetaData . ESTABLISH_TRUST_IN_CLIENT_NONE ) ) { supports = supports | EstablishTrustInClient . value ; } } return supports ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create an ASN . 1 DER encoded representation for the GSSUP OID mechanism . < / p > [CODESPLIT] public static byte [ ] createGSSUPMechOID ( ) { // kudos to org.ietf.jgss.Oid for the Oid utility need to strip the \"oid:\" part of the GSSUPMechOID first. byte [ ] retval = { } ; try { Oid oid = new Oid ( GSSUPMechOID . value . substring ( 4 ) ) ; retval = oid . getDER ( ) ; } catch ( GSSException e ) { IIOPLogger . ROOT_LOGGER . caughtExceptionEncodingGSSUPMechOID ( e ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p / > Generate an exported name as specified in [ RFC 2743 ] section 3 . 2 copied below : <p / > 3 . 2 : Mechanism - Independent Exported Name Object Format <p / > This section specifies a mechanism - independent level of encapsulating representation for names exported via the GSS_Export_name () call including an object identifier representing the exporting mechanism . The format of names encapsulated via this representation shall be defined within individual mechanism drafts . The Object Identifier value to indicate names of this type is defined in Section 4 . 7 of this document . <p / > No name type OID is included in this mechanism - independent level of format definition since ( depending on individual mechanism specifications ) the enclosed name may be implicitly typed or may be explicitly typed using a means other than OID encoding . <p / > The bytes within MECH_OID_LEN and NAME_LEN elements are represented most significant byte first ( equivalently in IP network byte order ) . <p / > Length Name Description <p / > 2 TOK_ID Token Identifier For exported name objects this must be hex 04 01 . 2 MECH_OID_LEN Length of the Mechanism OID MECH_OID_LEN MECH_OID Mechanism OID in DER 4 NAME_LEN Length of name NAME_LEN NAME Exported name ; format defined in applicable mechanism draft . <p / > A concrete example of the contents of an exported name object derived from the Kerberos Version 5 mechanism is as follows : <p / > 04 01 00 0B 06 09 2A 86 48 86 F7 12 01 02 02 hx xx xx xl pp qq ... zz <p / > ... [CODESPLIT] public static byte [ ] createGSSExportedName ( byte [ ] oid , byte [ ] name ) { int olen = oid . length ; int nlen = name . length ; // size according to spec. int size = 2 + 2 + olen + 4 + nlen ; // allocate space for the exported name. byte [ ] buf = new byte [ size ] ; // index. int i = 0 ; // standard header. buf [ i ++ ] = 0x04 ; buf [ i ++ ] = 0x01 ; // encode oid length. buf [ i ++ ] = ( byte ) ( olen & 0xFF00 ) ; buf [ i ++ ] = ( byte ) ( olen & 0x00FF ) ; // copy the oid in the exported name buffer. System . arraycopy ( oid , 0 , buf , i , olen ) ; i += olen ; // encode the name length in the exported buffer. buf [ i ++ ] = ( byte ) ( nlen & 0xFF000000 ) ; buf [ i ++ ] = ( byte ) ( nlen & 0x00FF0000 ) ; buf [ i ++ ] = ( byte ) ( nlen & 0x0000FF00 ) ; buf [ i ++ ] = ( byte ) ( nlen & 0x000000FF ) ; // finally, copy the name bytes. System . arraycopy ( name , 0 , buf , i , nlen ) ; return buf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > ASN . 1 - encode an { @code InitialContextToken } as defined in RFC 2743 Section 3 . 1 Mechanism - Independent Token Format pp . 81 - 82 . The encoded token contains the ASN . 1 tag 0x60 followed by a token length ( which is itself stored in a variable - length format and takes 1 to 5 bytes ) the GSSUP mechanism identifier and a mechanism - specific token which in this case is a CDR encapsulation of the GSSUP { @code InitialContextToken } in the { @code authToken } parameter . < / p > [CODESPLIT] public static byte [ ] encodeInitialContextToken ( InitialContextToken authToken , Codec codec ) { byte [ ] out ; Any any = ORB . init ( ) . create_any ( ) ; InitialContextTokenHelper . insert ( any , authToken ) ; try { out = codec . encode_value ( any ) ; } catch ( Exception e ) { return new byte [ 0 ] ; } int length = out . length + gssUpMechOidArray . length ; int n ; if ( length < ( 1 << 7 ) ) { n = 0 ; } else if ( length < ( 1 << 8 ) ) { n = 1 ; } else if ( length < ( 1 << 16 ) ) { n = 2 ; } else if ( length < ( 1 << 24 ) ) { n = 3 ; } else { // if (length < (1 << 32)) n = 4 ; } byte [ ] encodedToken = new byte [ 2 + n + length ] ; encodedToken [ 0 ] = 0x60 ; if ( n == 0 ) { encodedToken [ 1 ] = ( byte ) length ; } else { encodedToken [ 1 ] = ( byte ) ( n | 0x80 ) ; switch ( n ) { case 1 : encodedToken [ 2 ] = ( byte ) length ; break ; case 2 : encodedToken [ 2 ] = ( byte ) ( length >> 8 ) ; encodedToken [ 3 ] = ( byte ) length ; break ; case 3 : encodedToken [ 2 ] = ( byte ) ( length >> 16 ) ; encodedToken [ 3 ] = ( byte ) ( length >> 8 ) ; encodedToken [ 4 ] = ( byte ) length ; break ; default : // case 4: encodedToken [ 2 ] = ( byte ) ( length >> 24 ) ; encodedToken [ 3 ] = ( byte ) ( length >> 16 ) ; encodedToken [ 4 ] = ( byte ) ( length >> 8 ) ; encodedToken [ 5 ] = ( byte ) length ; } } System . arraycopy ( gssUpMechOidArray , 0 , encodedToken , 2 + n , gssUpMechOidArray . length ) ; System . arraycopy ( out , 0 , encodedToken , 2 + n + gssUpMechOidArray . length , out . length ) ; return encodedToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Decodes an ASN . 1 - encoded { @code InitialContextToken } . See { @code encodeInitialContextToken } for a description of the encoded token format . < / p > [CODESPLIT] public static InitialContextToken decodeInitialContextToken ( byte [ ] encodedToken , Codec codec ) { if ( encodedToken [ 0 ] != 0x60 ) return null ; int encodedLength = 0 ; int n = 0 ; if ( encodedToken [ 1 ] >= 0 ) encodedLength = encodedToken [ 1 ] ; else { n = encodedToken [ 1 ] & 0x7F ; for ( int i = 1 ; i <= n ; i ++ ) { encodedLength += ( encodedToken [ 1 + i ] & 0xFF ) << ( n - i ) * 8 ; } } int length = encodedLength - gssUpMechOidArray . length ; byte [ ] encodedInitialContextToken = new byte [ length ] ; System . arraycopy ( encodedToken , 2 + n + gssUpMechOidArray . length , encodedInitialContextToken , 0 , length ) ; Any any ; try { any = codec . decode_value ( encodedInitialContextToken , InitialContextTokenHelper . type ( ) ) ; } catch ( Exception e ) { return null ; } return InitialContextTokenHelper . extract ( any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Decodes a GSS exported name that has been encoded with the GSSUP mechanism OID . See { @code createGSSExportedName } for a description of the encoding format . < / p > [CODESPLIT] public static byte [ ] decodeGssExportedName ( byte [ ] encodedName ) { if ( encodedName [ 0 ] != 0x04 || encodedName [ 1 ] != 0x01 ) return null ; int mechOidLength = ( encodedName [ 2 ] & 0xFF ) << 8 ; //MECH_OID_LEN mechOidLength += ( encodedName [ 3 ] & 0xFF ) ; // MECH_OID_LEN byte [ ] oidArray = new byte [ mechOidLength ] ; System . arraycopy ( encodedName , 4 , oidArray , 0 , mechOidLength ) ; for ( int i = 0 ; i < mechOidLength ; i ++ ) { if ( gssUpMechOidArray [ i ] != oidArray [ i ] ) { return null ; } } int offset = 4 + mechOidLength ; int nameLength = ( encodedName [ offset ] & 0xFF ) << 24 ; nameLength += ( encodedName [ ++ offset ] & 0xFF ) << 16 ; nameLength += ( encodedName [ ++ offset ] & 0xFF ) << 8 ; nameLength += ( encodedName [ ++ offset ] & 0xFF ) ; byte [ ] name = new byte [ nameLength ] ; System . arraycopy ( encodedName , ++ offset , name , 0 , nameLength ) ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Helper method to be called from a client request interceptor . The { @code ri } parameter refers to the current request . This method returns the first { @code CompoundSecMech } found in the target IOR such that <ul > <li > all { @code CompoundSecMech } requirements are satisfied by the options in the { @code clientSupports } parameter and< / li > <li > every requirement in the { @code clientRequires } parameter is satisfied by the { @code CompoundSecMech } . < / li > < / ul > The method returns null if the target IOR contains no { @code CompoundSecMech } s or if no matching { @code CompoundSecMech } is found . < / p > <p > Since this method is intended to be called from a client request interceptor it converts unexpected exceptions into { @code MARSHAL } exceptions . < / p > [CODESPLIT] public static CompoundSecMech getMatchingSecurityMech ( ClientRequestInfo ri , Codec codec , short clientSupports , short clientRequires ) { CompoundSecMechList csmList ; try { TaggedComponent tc = ri . get_effective_component ( org . omg . IOP . TAG_CSI_SEC_MECH_LIST . value ) ; Any any = codec . decode_value ( tc . component_data , CompoundSecMechListHelper . type ( ) ) ; csmList = CompoundSecMechListHelper . extract ( any ) ; // look for the first matching security mech. for ( int i = 0 ; i < csmList . mechanism_list . length ; i ++ ) { CompoundSecMech securityMech = csmList . mechanism_list [ i ] ; AS_ContextSec authConfig = securityMech . as_context_mech ; if ( ( EstablishTrustInTarget . value & ( clientRequires ^ authConfig . target_supports ) & ~ authConfig . target_supports ) != 0 ) { // client requires EstablishTrustInTarget, but target does not support it: skip this securityMech. continue ; } if ( ( EstablishTrustInClient . value & ( authConfig . target_requires ^ clientSupports ) & ~ clientSupports ) != 0 ) { // target requires EstablishTrustInClient, but client does not support it: skip this securityMech. continue ; } SAS_ContextSec identityConfig = securityMech . sas_context_mech ; if ( ( IdentityAssertion . value & ( identityConfig . target_requires ^ clientSupports ) & ~ clientSupports ) != 0 ) { // target requires IdentityAssertion, but client does not support it: skip this securityMech continue ; } // found matching securityMech. return securityMech ; } // no matching securityMech was found. return null ; } catch ( BAD_PARAM e ) { // no component with TAG_CSI_SEC_MECH_LIST was found. return null ; } catch ( org . omg . IOP . CodecPackage . TypeMismatch e ) { // unexpected exception in codec throw IIOPLogger . ROOT_LOGGER . unexpectedException ( e ) ; } catch ( org . omg . IOP . CodecPackage . FormatMismatch e ) { // unexpected exception in codec throw IIOPLogger . ROOT_LOGGER . unexpectedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( XMLExtendedStreamReader reader , List < ModelNode > list ) throws XMLStreamException { // EE subsystem doesn't have any attributes, so make sure that the xml doesn't have any requireNoAttributes ( reader ) ; final ModelNode eeSubSystem = Util . createAddOperation ( PathAddress . pathAddress ( EeExtension . PATH_SUBSYSTEM ) ) ; // add the subsystem to the ModelNode(s) list . add ( eeSubSystem ) ; // elements final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { switch ( Namespace . forUri ( reader . getNamespaceURI ( ) ) ) { case EE_1_0 : { final Element element = Element . forName ( reader . getLocalName ( ) ) ; if ( ! encountered . add ( element ) ) { throw unexpectedElement ( reader ) ; } switch ( element ) { case GLOBAL_MODULES : { final ModelNode model = parseGlobalModules ( reader ) ; eeSubSystem . get ( GlobalModulesDefinition . GLOBAL_MODULES ) . set ( model ) ; break ; } case EAR_SUBDEPLOYMENTS_ISOLATED : { final String earSubDeploymentsIsolated = parseEarSubDeploymentsIsolatedElement ( reader ) ; // set the ear subdeployment isolation on the subsystem operation EeSubsystemRootResource . EAR_SUBDEPLOYMENTS_ISOLATED . parseAndSetParameter ( earSubDeploymentsIsolated , eeSubSystem , reader ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves ejb - ref and ejb - local - ref elements [CODESPLIT] protected List < BindingConfiguration > processDescriptorEntries ( DeploymentUnit deploymentUnit , DeploymentDescriptorEnvironment environment , ResourceInjectionTarget resourceInjectionTarget , final ComponentDescription componentDescription , ClassLoader classLoader , DeploymentReflectionIndex deploymentReflectionIndex , final EEApplicationClasses applicationClasses ) throws DeploymentUnitProcessingException { final RemoteEnvironment remoteEnvironment = environment . getEnvironment ( ) ; List < BindingConfiguration > bindingDescriptions = new ArrayList < BindingConfiguration > ( ) ; EJBReferencesMetaData ejbRefs = remoteEnvironment . getEjbReferences ( ) ; if ( ejbRefs != null ) { for ( EJBReferenceMetaData ejbRef : ejbRefs ) { String name = ejbRef . getEjbRefName ( ) ; String ejbName = ejbRef . getLink ( ) ; String lookup = ejbRef . getLookupName ( ) != null ? ejbRef . getLookupName ( ) : ejbRef . getMappedName ( ) ; String remoteInterface = ejbRef . getRemote ( ) ; String home = ejbRef . getHome ( ) ; Class < ? > remoteInterfaceType = null ; //if a home is specified this is the type that is bound if ( ! isEmpty ( home ) ) { try { remoteInterfaceType = ClassLoadingUtils . loadClass ( home , deploymentUnit ) ; } catch ( ClassNotFoundException e ) { throw EjbLogger . ROOT_LOGGER . failedToLoadViewClass ( e , home ) ; } } else if ( ! isEmpty ( remoteInterface ) ) { try { remoteInterfaceType = ClassLoadingUtils . loadClass ( remoteInterface , deploymentUnit ) ; } catch ( ClassNotFoundException e ) { throw EjbLogger . ROOT_LOGGER . failedToLoadViewClass ( e , remoteInterface ) ; } } if ( ! name . startsWith ( \"java:\" ) ) { name = environment . getDefaultContext ( ) + name ; } // our injection (source) comes from the local (ENC) lookup, no matter what. LookupInjectionSource injectionSource = new LookupInjectionSource ( name ) ; //add any injection targets remoteInterfaceType = processInjectionTargets ( resourceInjectionTarget , injectionSource , classLoader , deploymentReflectionIndex , ejbRef , remoteInterfaceType ) ; final BindingConfiguration bindingConfiguration ; EjbInjectionSource ejbInjectionSource = null ; if ( ! isEmpty ( lookup ) ) { if ( ! lookup . startsWith ( \"java:\" ) ) { bindingConfiguration = new BindingConfiguration ( name , new EjbLookupInjectionSource ( lookup , remoteInterfaceType ) ) ; } else { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( lookup ) ) ; } } else { if ( remoteInterfaceType == null ) { throw EjbLogger . ROOT_LOGGER . couldNotDetermineEjbRefForInjectionTarget ( name , resourceInjectionTarget ) ; } if ( ! isEmpty ( ejbName ) ) { bindingConfiguration = new BindingConfiguration ( name , ejbInjectionSource = new EjbInjectionSource ( ejbName , remoteInterfaceType . getName ( ) , name , deploymentUnit , appclient ) ) ; } else { bindingConfiguration = new BindingConfiguration ( name , ejbInjectionSource = new EjbInjectionSource ( remoteInterfaceType . getName ( ) , name , deploymentUnit , appclient ) ) ; } } if ( ejbInjectionSource != null ) { deploymentUnit . addToAttachmentList ( EjbDeploymentAttachmentKeys . EJB_INJECTIONS , ejbInjectionSource ) ; } bindingDescriptions . add ( bindingConfiguration ) ; } } if ( remoteEnvironment instanceof Environment && ! appclient ) { EJBLocalReferencesMetaData ejbLocalRefs = ( ( Environment ) remoteEnvironment ) . getEjbLocalReferences ( ) ; if ( ejbLocalRefs != null ) { for ( EJBLocalReferenceMetaData ejbRef : ejbLocalRefs ) { String name = ejbRef . getEjbRefName ( ) ; String ejbName = ejbRef . getLink ( ) ; String lookup = ejbRef . getLookupName ( ) != null ? ejbRef . getLookupName ( ) : ejbRef . getMappedName ( ) ; String localInterface = ejbRef . getLocal ( ) ; String localHome = ejbRef . getLocalHome ( ) ; Class < ? > localInterfaceType = null ; //if a home is specified this is the type that is bound if ( ! isEmpty ( localHome ) ) { try { localInterfaceType = ClassLoadingUtils . loadClass ( localHome , deploymentUnit ) ; } catch ( ClassNotFoundException e ) { throw EjbLogger . ROOT_LOGGER . failedToLoadViewClass ( e , localHome ) ; } } else if ( ! isEmpty ( localInterface ) ) { try { localInterfaceType = ClassLoadingUtils . loadClass ( localInterface , deploymentUnit ) ; } catch ( ClassNotFoundException e ) { throw EjbLogger . ROOT_LOGGER . failedToLoadViewClass ( e , localInterface ) ; } } if ( ! name . startsWith ( \"java:\" ) ) { name = environment . getDefaultContext ( ) + name ; } // our injection (source) comes from the local (ENC) lookup, no matter what. LookupInjectionSource injectionSource = new LookupInjectionSource ( name ) ; //add any injection targets localInterfaceType = processInjectionTargets ( resourceInjectionTarget , injectionSource , classLoader , deploymentReflectionIndex , ejbRef , localInterfaceType ) ; if ( localInterfaceType == null ) { throw EjbLogger . ROOT_LOGGER . couldNotDetermineEjbLocalRefForInjectionTarget ( name , resourceInjectionTarget ) ; } final BindingConfiguration bindingConfiguration ; EjbInjectionSource ejbInjectionSource = null ; if ( ! isEmpty ( lookup ) ) { if ( ! lookup . startsWith ( \"java:\" ) ) { bindingConfiguration = new BindingConfiguration ( name , new EjbLookupInjectionSource ( lookup , localInterfaceType ) ) ; } else { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( lookup ) ) ; } } else if ( ! isEmpty ( ejbName ) ) { bindingConfiguration = new BindingConfiguration ( name , ejbInjectionSource = new EjbInjectionSource ( ejbName , localInterfaceType . getName ( ) , name , deploymentUnit , appclient ) ) ; } else { bindingConfiguration = new BindingConfiguration ( name , ejbInjectionSource = new EjbInjectionSource ( localInterfaceType . getName ( ) , name , deploymentUnit , appclient ) ) ; } if ( ejbInjectionSource != null ) { deploymentUnit . addToAttachmentList ( EjbDeploymentAttachmentKeys . EJB_INJECTIONS , ejbInjectionSource ) ; } bindingDescriptions . add ( bindingConfiguration ) ; } } } return bindingDescriptions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the injection targets of a resource binding [CODESPLIT] protected Class < ? > processInjectionTargets ( final ResourceInjectionTarget resourceInjectionTarget , InjectionSource injectionSource , ClassLoader classLoader , DeploymentReflectionIndex deploymentReflectionIndex , ResourceInjectionMetaData entry , Class < ? > classType ) throws DeploymentUnitProcessingException { if ( entry . getInjectionTargets ( ) != null ) { for ( ResourceInjectionTargetMetaData injectionTarget : entry . getInjectionTargets ( ) ) { final String injectionTargetClassName = injectionTarget . getInjectionTargetClass ( ) ; final String injectionTargetName = injectionTarget . getInjectionTargetName ( ) ; final AccessibleObject fieldOrMethod = getInjectionTarget ( injectionTargetClassName , injectionTargetName , classLoader , deploymentReflectionIndex ) ; final Class < ? > injectionTargetType = fieldOrMethod instanceof Field ? ( ( Field ) fieldOrMethod ) . getType ( ) : ( ( Method ) fieldOrMethod ) . getParameterTypes ( ) [ 0 ] ; final String memberName = fieldOrMethod instanceof Field ? ( ( Field ) fieldOrMethod ) . getName ( ) : ( ( Method ) fieldOrMethod ) . getName ( ) ; if ( classType != null ) { if ( ! injectionTargetType . isAssignableFrom ( classType ) ) { boolean ok = false ; if ( classType . isPrimitive ( ) ) { if ( BOXED_TYPES . get ( classType ) . equals ( injectionTargetType ) ) { ok = true ; } } else if ( injectionTargetType . isPrimitive ( ) ) { if ( BOXED_TYPES . get ( injectionTargetType ) . equals ( classType ) ) { ok = true ; } } if ( ! ok ) { throw EeLogger . ROOT_LOGGER . invalidInjectionTarget ( injectionTarget . getInjectionTargetName ( ) , injectionTarget . getInjectionTargetClass ( ) , classType ) ; } classType = injectionTargetType ; } } else { classType = injectionTargetType ; } final InjectionTarget injectionTargetDescription = fieldOrMethod instanceof Field ? new FieldInjectionTarget ( injectionTargetClassName , memberName , classType . getName ( ) ) : new MethodInjectionTarget ( injectionTargetClassName , memberName , classType . getName ( ) ) ; final ResourceInjectionConfiguration injectionConfiguration = new ResourceInjectionConfiguration ( injectionTargetDescription , injectionSource ) ; resourceInjectionTarget . addResourceInjection ( injectionConfiguration ) ; } } return classType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the container Executed in WeldStartService to shutdown the runtime before NamingService is closed . [CODESPLIT] @ Override public void stop ( final StopContext context ) { final WeldBootstrapService bootstrapService = bootstrapSupplier . get ( ) ; if ( ! bootstrapService . isStarted ( ) ) { throw WeldLogger . ROOT_LOGGER . notStarted ( \"WeldContainer\" ) ; } WeldLogger . DEPLOYMENT_LOGGER . stoppingWeldService ( bootstrapService . getDeploymentName ( ) ) ; ClassLoader oldTccl = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( bootstrapService . getDeployment ( ) . getModule ( ) . getClassLoader ( ) ) ; WeldProvider . containerShutDown ( Container . instance ( bootstrapService . getDeploymentName ( ) ) ) ; bootstrapService . getBootstrap ( ) . shutdown ( ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( oldTccl ) ; ModuleGroupSingletonProvider . removeClassLoader ( bootstrapService . getDeployment ( ) . getModule ( ) . getClassLoader ( ) ) ; } bootstrapService . setStarted ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the raw JNDINAME value from the given model node and depending on the value and the value of any USE_JAVA_CONTEXT child node converts the raw name into a compliant jndi name . [CODESPLIT] public static String getJndiName ( final OperationContext context , final ModelNode modelNode ) throws OperationFailedException { final String rawJndiName = JNDI_NAME . resolveModelAttribute ( context , modelNode ) . asString ( ) ; return cleanJndiName ( rawJndiName , modelNode . hasDefined ( USE_JAVA_CONTEXT . getName ( ) ) && modelNode . get ( USE_JAVA_CONTEXT . getName ( ) ) . asBoolean ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void performBoottime ( OperationContext context , ModelNode operation , ModelNode model ) { MicroProfileConfigLogger . ROOT_LOGGER . activatingSubsystem ( ) ; ConfigProviderService . install ( context ) ; context . addStep ( new AbstractDeploymentChainStep ( ) { public void execute ( DeploymentProcessorTarget processorTarget ) { processorTarget . addDeploymentProcessor ( MicroProfileConfigExtension . SUBSYSTEM_NAME , Phase . DEPENDENCIES , Phase . DEPENDENCIES_MICROPROFILE_CONFIG , new DependencyProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( MicroProfileConfigExtension . SUBSYSTEM_NAME , Phase . POST_MODULE , Phase . POST_MODULE_MICROPROFILE_CONFIG , new SubsystemDeploymentProcessor ( ) ) ; } } , OperationContext . Stage . RUNTIME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return null if the resolved attribute is not defined [CODESPLIT] private String resolveAttribute ( SimpleAttributeDefinition attr , OperationContext context , ModelNode model ) throws OperationFailedException { final ModelNode node = attr . resolveModelAttribute ( context , model ) ; return node . isDefined ( ) ? node . asString ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds an ejb - jar . xml ( at WEB - INF of a . war or META - INF of a . jar ) parses the file and creates metadata out of it . The metadata is then attached to the deployment unit . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext deploymentPhase ) throws DeploymentUnitProcessingException { // get hold of the deployment unit. final DeploymentUnit deploymentUnit = deploymentPhase . getDeploymentUnit ( ) ; // get the root of the deployment unit final EEModuleDescription eeModuleDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_MODULE_DESCRIPTION ) ; final EEApplicationClasses applicationClassesDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_APPLICATION_CLASSES_DESCRIPTION ) ; final EjbJarMetaData ejbJarMetaData ; final EjbJarMetaData specMetaData = parseEjbJarXml ( deploymentUnit ) ; final EjbJarMetaData jbossMetaData = parseJBossEjb3Xml ( deploymentUnit ) ; if ( specMetaData == null ) { if ( jbossMetaData == null ) return ; ejbJarMetaData = jbossMetaData ; } else if ( jbossMetaData == null ) { ejbJarMetaData = specMetaData ; } else { ejbJarMetaData = jbossMetaData . createMerged ( specMetaData ) ; } // Mark it as an EJB deployment EjbDeploymentMarker . mark ( deploymentUnit ) ; if ( ! deploymentUnit . hasAttachment ( EjbDeploymentAttachmentKeys . EJB_JAR_DESCRIPTION ) ) { final EEModuleDescription moduleDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_MODULE_DESCRIPTION ) ; final EjbJarDescription ejbModuleDescription = new EjbJarDescription ( moduleDescription , deploymentUnit . getName ( ) . endsWith ( \".war\" ) ) ; deploymentUnit . putAttachment ( EjbDeploymentAttachmentKeys . EJB_JAR_DESCRIPTION , ejbModuleDescription ) ; } // attach the EjbJarMetaData to the deployment unit deploymentUnit . putAttachment ( EjbDeploymentAttachmentKeys . EJB_JAR_METADATA , ejbJarMetaData ) ; // if the jboss-ejb3.xml has a distinct-name configured then attach it to the deployment unit if ( jbossMetaData != null && jbossMetaData . getDistinctName ( ) != null ) { deploymentUnit . putAttachment ( org . jboss . as . ee . structure . Attachments . DISTINCT_NAME , jbossMetaData . getDistinctName ( ) ) ; } if ( ejbJarMetaData . getModuleName ( ) != null ) { eeModuleDescription . setModuleName ( ejbJarMetaData . getModuleName ( ) ) ; } if ( ejbJarMetaData . isMetadataComplete ( ) ) { MetadataCompleteMarker . setMetadataComplete ( deploymentUnit , true ) ; } if ( ! ejbJarMetaData . isEJB3x ( ) ) { //EJB spec 20.5.1, we do not process annotations for older deployments MetadataCompleteMarker . setMetadataComplete ( deploymentUnit , true ) ; } if ( ejbJarMetaData . getEnterpriseBeans ( ) != null ) { //check for entity beans StringBuilder beans = new StringBuilder ( ) ; boolean error = false ; for ( AbstractEnterpriseBeanMetaData bean : ejbJarMetaData . getEnterpriseBeans ( ) ) { if ( bean . getEjbType ( ) == EjbType . ENTITY ) { if ( ! error ) { error = true ; } else { beans . append ( \", \" ) ; } beans . append ( bean . getEjbName ( ) ) ; } } if ( error ) { throw EjbLogger . ROOT_LOGGER . entityBeansAreNotSupported ( beans . toString ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a { @link XMLStreamReader } for the passed { @link VirtualFile ejb - jar . xml } [CODESPLIT] private static XMLStreamReader getXMLStreamReader ( InputStream stream , VirtualFile ejbJarXml , XMLResolver resolver ) throws DeploymentUnitProcessingException { try { final XMLInputFactory inputFactory = XMLInputFactory . newInstance ( ) ; inputFactory . setXMLResolver ( resolver ) ; XMLStreamReader xmlReader = inputFactory . createXMLStreamReader ( stream ) ; return xmlReader ; } catch ( XMLStreamException xmlse ) { throw EjbLogger . ROOT_LOGGER . failedToParse ( xmlse , \"ejb-jar.xml: \" + ejbJarXml . getPathName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void createPermissions ( WarMetaData metaData , PolicyConfiguration pc ) throws PolicyContextException { JBossWebMetaData jbossWebMetaData = metaData . getMergedJBossWebMetaData ( ) ; HashMap < String , PatternInfo > patternMap = qualifyURLPatterns ( jbossWebMetaData ) ; List < SecurityConstraintMetaData > secConstraints = jbossWebMetaData . getSecurityConstraints ( ) ; if ( secConstraints != null ) { for ( SecurityConstraintMetaData secConstraint : secConstraints ) { WebResourceCollectionsMetaData resourceCollectionsMetaData = secConstraint . getResourceCollections ( ) ; UserDataConstraintMetaData userDataConstraintMetaData = secConstraint . getUserDataConstraint ( ) ; if ( resourceCollectionsMetaData != null ) { if ( secConstraint . isExcluded ( ) || secConstraint . isUnchecked ( ) ) { // Process the permissions for the excluded/unchecked resources for ( WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData ) { List < String > httpMethods = new ArrayList <> ( resourceCollectionMetaData . getHttpMethods ( ) ) ; List < String > ommisions = resourceCollectionMetaData . getHttpMethodOmissions ( ) ; if ( httpMethods . isEmpty ( ) && ! ommisions . isEmpty ( ) ) { httpMethods . addAll ( WebResourceCollectionMetaData . ALL_HTTP_METHODS ) ; httpMethods . removeAll ( ommisions ) ; } List < String > urlPatterns = resourceCollectionMetaData . getUrlPatterns ( ) ; for ( String urlPattern : urlPatterns ) { PatternInfo info = patternMap . get ( urlPattern ) ; info . descriptor = true ; // Add the excluded methods if ( secConstraint . isExcluded ( ) ) { info . addExcludedMethods ( httpMethods ) ; } // SECURITY-63: Missing auth-constraint needs unchecked policy if ( secConstraint . isUnchecked ( ) && httpMethods . isEmpty ( ) ) { info . isMissingAuthConstraint = true ; } else { info . missingAuthConstraintMethods . addAll ( httpMethods ) ; } } } } else { // Process the permission for the resources x roles for ( WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData ) { List < String > httpMethods = new ArrayList <> ( resourceCollectionMetaData . getHttpMethods ( ) ) ; List < String > methodOmissions = resourceCollectionMetaData . getHttpMethodOmissions ( ) ; if ( httpMethods . isEmpty ( ) && ! methodOmissions . isEmpty ( ) ) { httpMethods . addAll ( WebResourceCollectionMetaData . ALL_HTTP_METHODS ) ; httpMethods . removeAll ( methodOmissions ) ; } List < String > urlPatterns = resourceCollectionMetaData . getUrlPatterns ( ) ; for ( String urlPattern : urlPatterns ) { // Get the qualified url pattern PatternInfo info = patternMap . get ( urlPattern ) ; info . descriptor = true ; HashSet < String > mappedRoles = new HashSet < String > ( ) ; secConstraint . getAuthConstraint ( ) . getRoleNames ( ) ; List < String > authRoles = secConstraint . getAuthConstraint ( ) . getRoleNames ( ) ; for ( String role : authRoles ) { if ( \"*\" . equals ( role ) ) { // The wildcard ref maps to all declared security-role names mappedRoles . addAll ( jbossWebMetaData . getSecurityRoleNames ( ) ) ; } else { mappedRoles . add ( role ) ; } } info . addRoles ( mappedRoles , httpMethods ) ; // Add the transport to methods if ( userDataConstraintMetaData != null && userDataConstraintMetaData . getTransportGuarantee ( ) != null ) info . addTransport ( userDataConstraintMetaData . getTransportGuarantee ( ) . name ( ) , httpMethods ) ; } } } } } } JBossServletsMetaData servlets = jbossWebMetaData . getServlets ( ) ; List < ServletMappingMetaData > mappings = jbossWebMetaData . getServletMappings ( ) ; if ( servlets != null && mappings != null ) { Map < String , List < String > > servletMappingMap = new HashMap <> ( ) ; for ( ServletMappingMetaData mapping : mappings ) { List < String > list = servletMappingMap . get ( mapping . getServletName ( ) ) ; if ( list == null ) { servletMappingMap . put ( mapping . getServletName ( ) , list = new ArrayList <> ( ) ) ; } list . addAll ( mapping . getUrlPatterns ( ) ) ; } if ( ! jbossWebMetaData . isMetadataComplete ( ) ) { for ( JBossServletMetaData servlet : servlets ) { ServletSecurityMetaData security = servlet . getServletSecurity ( ) ; if ( security != null ) { List < String > servletMappings = servletMappingMap . get ( servlet . getServletName ( ) ) ; if ( servletMappings != null ) { if ( security . getHttpMethodConstraints ( ) != null ) { for ( HttpMethodConstraintMetaData s : security . getHttpMethodConstraints ( ) ) { if ( s . getRolesAllowed ( ) == null || s . getRolesAllowed ( ) . isEmpty ( ) ) { for ( String urlPattern : servletMappings ) { // Get the qualified url pattern PatternInfo info = patternMap . get ( urlPattern ) ; if ( info . descriptor ) { continue ; } // Add the excluded methods if ( s . getEmptyRoleSemantic ( ) == null || s . getEmptyRoleSemantic ( ) == EmptyRoleSemanticType . PERMIT ) { info . missingAuthConstraintMethods . add ( s . getMethod ( ) ) ; } else { info . addExcludedMethods ( Collections . singletonList ( s . getMethod ( ) ) ) ; } // Add the transport to methods if ( s . getTransportGuarantee ( ) != null ) info . addTransport ( s . getTransportGuarantee ( ) . name ( ) , Collections . singletonList ( s . getMethod ( ) ) ) ; } } else { for ( String urlPattern : servletMappings ) { // Get the qualified url pattern PatternInfo info = patternMap . get ( urlPattern ) ; if ( info . descriptor ) { continue ; } HashSet < String > mappedRoles = new HashSet < String > ( ) ; List < String > authRoles = s . getRolesAllowed ( ) ; for ( String role : authRoles ) { if ( \"*\" . equals ( role ) ) { // The wildcard ref maps to all declared security-role names mappedRoles . addAll ( jbossWebMetaData . getSecurityRoleNames ( ) ) ; } else { mappedRoles . add ( role ) ; } } info . addRoles ( mappedRoles , Collections . singletonList ( s . getMethod ( ) ) ) ; // Add the transport to methods if ( s . getTransportGuarantee ( ) != null ) info . addTransport ( s . getTransportGuarantee ( ) . name ( ) , Collections . singletonList ( s . getMethod ( ) ) ) ; } } } } if ( security . getRolesAllowed ( ) == null || security . getRolesAllowed ( ) . isEmpty ( ) ) { for ( String urlPattern : servletMappings ) { // Get the qualified url pattern PatternInfo info = patternMap . get ( urlPattern ) ; if ( info . descriptor ) { continue ; } // Add the excluded methods if ( security . getEmptyRoleSemantic ( ) == null || security . getEmptyRoleSemantic ( ) == EmptyRoleSemanticType . PERMIT ) { info . isMissingAuthConstraint = true ; } else { Set < String > methods = new HashSet <> ( WebResourceCollectionMetaData . ALL_HTTP_METHODS ) ; if ( security . getHttpMethodConstraints ( ) != null ) { for ( HttpMethodConstraintMetaData method : security . getHttpMethodConstraints ( ) ) { methods . remove ( method . getMethod ( ) ) ; } } info . addExcludedMethods ( new ArrayList <> ( methods ) ) ; } // Add the transport to methods if ( security . getTransportGuarantee ( ) != null ) info . addTransport ( security . getTransportGuarantee ( ) . name ( ) , Collections . emptyList ( ) ) ; } } else { for ( String urlPattern : servletMappings ) { // Get the qualified url pattern PatternInfo info = patternMap . get ( urlPattern ) ; if ( info . descriptor ) { continue ; } HashSet < String > mappedRoles = new HashSet < String > ( ) ; List < String > authRoles = security . getRolesAllowed ( ) ; for ( String role : authRoles ) { if ( \"*\" . equals ( role ) ) { // The wildcard ref maps to all declared security-role names mappedRoles . addAll ( jbossWebMetaData . getSecurityRoleNames ( ) ) ; } else { mappedRoles . add ( role ) ; } } info . addRoles ( mappedRoles , Collections . emptyList ( ) ) ; // Add the transport to methods if ( security . getTransportGuarantee ( ) != null ) info . addTransport ( security . getTransportGuarantee ( ) . name ( ) , Collections . emptyList ( ) ) ; } } } } } } } // Create the permissions for ( PatternInfo info : patternMap . values ( ) ) { String qurl = info . getQualifiedPattern ( ) ; if ( info . isOverridden ) { continue ; } // Create the excluded permissions String [ ] httpMethods = info . getExcludedMethods ( ) ; if ( httpMethods != null ) { // There were excluded security-constraints WebResourcePermission wrp = new WebResourcePermission ( qurl , httpMethods ) ; WebUserDataPermission wudp = new WebUserDataPermission ( qurl , httpMethods , null ) ; pc . addToExcludedPolicy ( wrp ) ; pc . addToExcludedPolicy ( wudp ) ; } // Create the role permissions Iterator < Map . Entry < String , Set < String > > > roles = info . getRoleMethods ( ) ; Set < String > seenMethods = new HashSet <> ( ) ; while ( roles . hasNext ( ) ) { Map . Entry < String , Set < String > > roleMethods = roles . next ( ) ; String role = roleMethods . getKey ( ) ; Set < String > methods = roleMethods . getValue ( ) ; seenMethods . addAll ( methods ) ; httpMethods = methods . toArray ( new String [ methods . size ( ) ] ) ; pc . addToRole ( role , new WebResourcePermission ( qurl , httpMethods ) ) ; } //there are totally 7 http methods from the jacc spec (See WebResourceCollectionMetaData.ALL_HTTP_METHOD_NAMES) final int NUMBER_OF_HTTP_METHODS = 7 ; // JACC 1.1: create !(httpmethods) in unchecked perms if ( jbossWebMetaData . getDenyUncoveredHttpMethods ( ) == null ) { if ( seenMethods . size ( ) != NUMBER_OF_HTTP_METHODS ) { WebResourcePermission wrpUnchecked = new WebResourcePermission ( qurl , \"!\" + getCommaSeparatedString ( seenMethods . toArray ( new String [ seenMethods . size ( ) ] ) ) ) ; pc . addToUncheckedPolicy ( wrpUnchecked ) ; } } if ( jbossWebMetaData . getDenyUncoveredHttpMethods ( ) == null ) { // Create the unchecked permissions String [ ] missingHttpMethods = info . getMissingMethods ( ) ; int length = missingHttpMethods . length ; roles = info . getRoleMethods ( ) ; if ( length > 0 && ! roles . hasNext ( ) ) { // Create the unchecked permissions WebResourcePermissions WebResourcePermission wrp = new WebResourcePermission ( qurl , missingHttpMethods ) ; pc . addToUncheckedPolicy ( wrp ) ; } else if ( ! roles . hasNext ( ) ) { pc . addToUncheckedPolicy ( new WebResourcePermission ( qurl , ( String ) null ) ) ; } // SECURITY-63: Missing auth-constraint needs unchecked policy if ( info . isMissingAuthConstraint ) { pc . addToUncheckedPolicy ( new WebResourcePermission ( qurl , ( String ) null ) ) ; } else if ( ! info . allMethods . containsAll ( WebResourceCollectionMetaData . ALL_HTTP_METHODS ) ) { List < String > methods = new ArrayList <> ( WebResourceCollectionMetaData . ALL_HTTP_METHODS ) ; methods . removeAll ( info . allMethods ) ; pc . addToUncheckedPolicy ( new WebResourcePermission ( qurl , methods . toArray ( new String [ methods . size ( ) ] ) ) ) ; } if ( ! info . missingAuthConstraintMethods . isEmpty ( ) ) { pc . addToUncheckedPolicy ( new WebResourcePermission ( qurl , info . missingAuthConstraintMethods . toArray ( new String [ info . missingAuthConstraintMethods . size ( ) ] ) ) ) ; } } // Create the unchecked permissions WebUserDataPermissions Iterator < Map . Entry < String , Set < String > > > transportConstraints = info . getTransportMethods ( ) ; while ( transportConstraints . hasNext ( ) ) { Map . Entry < String , Set < String > > transportMethods = transportConstraints . next ( ) ; String transport = transportMethods . getKey ( ) ; Set < String > methods = transportMethods . getValue ( ) ; httpMethods = new String [ methods . size ( ) ] ; methods . toArray ( httpMethods ) ; WebUserDataPermission wudp = new WebUserDataPermission ( qurl , httpMethods , transport ) ; pc . addToUncheckedPolicy ( wudp ) ; // If the transport is \"NONE\", then add an exclusive WebUserDataPermission // with the url pattern and null if ( \"NONE\" . equals ( transport ) ) { WebUserDataPermission wudp1 = new WebUserDataPermission ( qurl , null ) ; pc . addToUncheckedPolicy ( wudp1 ) ; } else { // JACC 1.1: Transport is CONFIDENTIAL/INTEGRAL, add a !(http methods) WebUserDataPermission wudpNonNull = new WebUserDataPermission ( qurl , \"!\" + getCommaSeparatedString ( httpMethods ) ) ; pc . addToUncheckedPolicy ( wudpNonNull ) ; } } } Set < String > declaredRoles = jbossWebMetaData . getSecurityRoleNames ( ) ; declaredRoles . add ( ANY_AUTHENTICATED_USER_ROLE ) ; /*\n         * Create WebRoleRefPermissions for all servlet/security-role-refs along with all the cross product of servlets and\n         * security-role elements that are not referenced via a security-role-ref as described in JACC section 3.1.3.2\n         */ JBossServletsMetaData servletsMetaData = jbossWebMetaData . getServlets ( ) ; for ( JBossServletMetaData servletMetaData : servletsMetaData ) { Set < String > unrefRoles = new HashSet < String > ( declaredRoles ) ; String servletName = servletMetaData . getName ( ) ; SecurityRoleRefsMetaData roleRefsMetaData = servletMetaData . getSecurityRoleRefs ( ) ; // Perform the unreferenced roles processing for every servlet name if ( roleRefsMetaData != null ) { for ( SecurityRoleRefMetaData roleRefMetaData : roleRefsMetaData ) { String roleRef = roleRefMetaData . getRoleLink ( ) ; String roleName = roleRefMetaData . getRoleName ( ) ; WebRoleRefPermission wrrp = new WebRoleRefPermission ( servletName , roleName ) ; pc . addToRole ( roleRef , wrrp ) ; // Remove the role from the unreferencedRoles unrefRoles . remove ( roleName ) ; } } // Spec 3.1.3.2: For each servlet element in the deployment descriptor // a WebRoleRefPermission must be added to each security-role of the // application whose name does not appear as the rolename // in a security-role-ref within the servlet element. for ( String unrefRole : unrefRoles ) { WebRoleRefPermission unrefP = new WebRoleRefPermission ( servletName , unrefRole ) ; pc . addToRole ( unrefRole , unrefP ) ; } } // JACC 1.1:Spec 3.1.3.2: For each security-role defined in the deployment descriptor, an // additional WebRoleRefPermission must be added to the corresponding role by // calling the addToRole method on the PolicyConfiguration object. The // name of all such permissions must be the empty string, and the actions of each // such permission must be the role-name of the corresponding role. for ( String role : declaredRoles ) { WebRoleRefPermission wrrep = new WebRoleRefPermission ( \"\" , role ) ; pc . addToRole ( role , wrrep ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the url - pattern type [CODESPLIT] static int getPatternType ( String urlPattern ) { int type = EXACT ; if ( urlPattern . startsWith ( \"*.\" ) ) type = EXTENSION ; else if ( urlPattern . startsWith ( \"/\" ) && urlPattern . endsWith ( \"/*\" ) ) type = PREFIX ; else if ( urlPattern . equals ( \"/\" ) ) type = DEFAULT ; return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JACC url pattern Qualified URL Pattern Names . [CODESPLIT] static HashMap < String , PatternInfo > qualifyURLPatterns ( JBossWebMetaData metaData ) { ArrayList < PatternInfo > prefixList = new ArrayList < PatternInfo > ( ) ; ArrayList < PatternInfo > extensionList = new ArrayList < PatternInfo > ( ) ; ArrayList < PatternInfo > exactList = new ArrayList < PatternInfo > ( ) ; HashMap < String , PatternInfo > patternMap = new HashMap < String , PatternInfo > ( ) ; PatternInfo defaultInfo = null ; List < SecurityConstraintMetaData > constraints = metaData . getSecurityConstraints ( ) ; if ( constraints != null ) { for ( SecurityConstraintMetaData constraint : constraints ) { WebResourceCollectionsMetaData resourceCollectionsMetaData = constraint . getResourceCollections ( ) ; if ( resourceCollectionsMetaData != null ) { for ( WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData ) { List < String > urlPatterns = resourceCollectionMetaData . getUrlPatterns ( ) ; for ( String url : urlPatterns ) { int type = getPatternType ( url ) ; PatternInfo info = patternMap . get ( url ) ; if ( info == null ) { info = new PatternInfo ( url , type ) ; patternMap . put ( url , info ) ; switch ( type ) { case PREFIX : prefixList . add ( info ) ; break ; case EXTENSION : extensionList . add ( info ) ; break ; case EXACT : exactList . add ( info ) ; break ; case DEFAULT : defaultInfo = info ; break ; } } } } } } } JBossServletsMetaData servlets = metaData . getServlets ( ) ; List < ServletMappingMetaData > mappings = metaData . getServletMappings ( ) ; if ( ! metaData . isMetadataComplete ( ) && servlets != null && mappings != null ) { Map < String , List < String > > servletMappingMap = new HashMap <> ( ) ; for ( ServletMappingMetaData mapping : mappings ) { List < String > list = servletMappingMap . get ( mapping . getServletName ( ) ) ; if ( list == null ) { servletMappingMap . put ( mapping . getServletName ( ) , list = new ArrayList <> ( ) ) ; } list . addAll ( mapping . getUrlPatterns ( ) ) ; } for ( JBossServletMetaData servlet : servlets ) { ServletSecurityMetaData security = servlet . getServletSecurity ( ) ; if ( security != null ) { List < String > servletMappings = servletMappingMap . get ( servlet . getServletName ( ) ) ; if ( servletMappings != null ) { for ( String url : servletMappings ) { int type = getPatternType ( url ) ; PatternInfo info = patternMap . get ( url ) ; if ( info == null ) { info = new PatternInfo ( url , type ) ; patternMap . put ( url , info ) ; switch ( type ) { case PREFIX : prefixList . add ( info ) ; break ; case EXTENSION : extensionList . add ( info ) ; break ; case EXACT : exactList . add ( info ) ; break ; case DEFAULT : defaultInfo = info ; break ; } } } } } } } // Qualify all prefix patterns for ( int i = 0 ; i < prefixList . size ( ) ; i ++ ) { PatternInfo info = prefixList . get ( i ) ; // Qualify by every other prefix pattern matching this pattern for ( int j = 0 ; j < prefixList . size ( ) ; j ++ ) { if ( i == j ) continue ; PatternInfo other = prefixList . get ( j ) ; if ( info . matches ( other ) ) info . addQualifier ( other ) ; } // Qualify by every exact pattern that is matched by this pattern for ( PatternInfo other : exactList ) { if ( info . matches ( other ) ) info . addQualifier ( other ) ; } } // Qualify all extension patterns for ( PatternInfo info : extensionList ) { // Qualify by every path prefix pattern for ( PatternInfo other : prefixList ) { // Any extension info . addQualifier ( other ) ; } // Qualify by every matching exact pattern for ( PatternInfo other : exactList ) { if ( info . isExtensionFor ( other ) ) info . addQualifier ( other ) ; } } // Qualify the default pattern if ( defaultInfo == null ) { defaultInfo = new PatternInfo ( \"/\" , DEFAULT ) ; patternMap . put ( \"/\" , defaultInfo ) ; } for ( PatternInfo info : patternMap . values ( ) ) { if ( info == defaultInfo ) continue ; defaultInfo . addQualifier ( info ) ; } return patternMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associate the extended persistence context with the current JTA transaction ( if one is found ) [CODESPLIT] public void internalAssociateWithJtaTx ( ) { isInTx = TransactionUtil . isInTx ( transactionManager ) ; // ensure that a different XPC (with same name) is not already present in the TX if ( isInTx ) { // 7.6.3.1 throw EJBException if a different persistence context is already joined to the // transaction (with the same puScopedName). EntityManager existing = TransactionUtil . getTransactionScopedEntityManager ( puScopedName , transactionSynchronizationRegistry ) ; if ( existing != null && existing != this ) { // should be enough to test if not the same object throw JpaLogger . ROOT_LOGGER . cannotUseExtendedPersistenceTransaction ( puScopedName , existing , this ) ; } else if ( existing == null ) { if ( SynchronizationType . SYNCHRONIZED . equals ( synchronizationType ) ) { // JPA 7.9.1 join the transaction if not already done for SynchronizationType.SYNCHRONIZED. underlyingEntityManager . joinTransaction ( ) ; } // associate the entity manager with the current transaction TransactionUtil . putEntityManagerInTransactionRegistry ( puScopedName , this , transactionSynchronizationRegistry ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return whether the definition targets an existing pooled connection factory or use a JCA - based ConnectionFactory . [CODESPLIT] static boolean targetsPooledConnectionFactory ( String server , String resourceAdapter , ServiceRegistry serviceRegistry ) { // if the resourceAdapter is not defined, the default behaviour is to create a pooled-connection-factory. if ( resourceAdapter == null || resourceAdapter . isEmpty ( ) ) { return true ; } ServiceName activeMQServiceName = MessagingServices . getActiveMQServiceName ( server ) ; ServiceName pcfName = JMSServices . getPooledConnectionFactoryBaseServiceName ( activeMQServiceName ) . append ( resourceAdapter ) ; return serviceRegistry . getServiceNames ( ) . contains ( pcfName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return whether the definition targets an existing external pooled connection factory . [CODESPLIT] static boolean targetsExternalPooledConnectionFactory ( String resourceAdapter , ServiceRegistry serviceRegistry ) { // if the resourceAdapter is not defined, the default behaviour is to create a pooled-connection-factory. if ( resourceAdapter == null || resourceAdapter . isEmpty ( ) ) { return false ; } //let's look into the external-pooled-connection-factory ServiceName pcfName = JMSServices . getPooledConnectionFactoryBaseServiceName ( MessagingServices . getActiveMQServiceName ( \"\" ) ) . append ( resourceAdapter ) ; return serviceRegistry . getServiceNames ( ) . contains ( pcfName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The JMS connection factory can specify another server to deploy its destinations by passing a property server = &lt ; name of the server > . Otherwise default is used by default . [CODESPLIT] static String getActiveMQServerName ( Map < String , String > properties ) { return properties . getOrDefault ( SERVER , DEFAULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * When finding the default persistence unit the first persistence unit encountered is returned . [CODESPLIT] private static PersistenceUnitMetadata findWithinDeployment ( DeploymentUnit unit , String persistenceUnitName ) { if ( traceEnabled ) { ROOT_LOGGER . tracef ( \"pu findWithinDeployment searching for %s\" , persistenceUnitName ) ; } for ( ResourceRoot root : DeploymentUtils . allResourceRoots ( unit ) ) { PersistenceUnitMetadataHolder holder = root . getAttachment ( PersistenceUnitMetadataHolder . PERSISTENCE_UNITS ) ; if ( holder == null || holder . getPersistenceUnits ( ) == null ) { if ( traceEnabled ) { ROOT_LOGGER . tracef ( \"pu findWithinDeployment skipping empty pu holder for %s\" , persistenceUnitName ) ; } continue ; } ambiguousPUError ( unit , persistenceUnitName , holder ) ; persistenceUnitName = defaultPersistenceUnitName ( persistenceUnitName , holder ) ; for ( PersistenceUnitMetadata persistenceUnit : holder . getPersistenceUnits ( ) ) { if ( traceEnabled ) { ROOT_LOGGER . tracef ( \"findWithinDeployment check '%s' against pu '%s'\" , persistenceUnitName , persistenceUnit . getPersistenceUnitName ( ) ) ; } if ( persistenceUnitName == null || persistenceUnitName . length ( ) == 0 || persistenceUnit . getPersistenceUnitName ( ) . equals ( persistenceUnitName ) ) { if ( traceEnabled ) { ROOT_LOGGER . tracef ( \"findWithinDeployment matched '%s' against pu '%s'\" , persistenceUnitName , persistenceUnit . getPersistenceUnitName ( ) ) ; } return persistenceUnit ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if no persistence unit name is specified return name of default persistence unit [CODESPLIT] private static String defaultPersistenceUnitName ( String persistenceUnitName , PersistenceUnitMetadataHolder holder ) { if ( ( persistenceUnitName == null || persistenceUnitName . length ( ) == 0 ) ) { for ( PersistenceUnitMetadata persistenceUnit : holder . getPersistenceUnits ( ) ) { String defaultPU = persistenceUnit . getProperties ( ) . getProperty ( Configuration . JPA_DEFAULT_PERSISTENCE_UNIT ) ; if ( Boolean . TRUE . toString ( ) . equals ( defaultPU ) ) { persistenceUnitName = persistenceUnit . getPersistenceUnitName ( ) ; } } } return persistenceUnitName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for a Connector . Will install a { @Code JBossService } for this ResourceAdapter . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ConnectorXmlDescriptor connectorXmlDescriptor = deploymentUnit . getAttachment ( ConnectorXmlDescriptor . ATTACHMENT_KEY ) ; final ManagementResourceRegistration registration ; final ManagementResourceRegistration baseRegistration = deploymentUnit . getAttachment ( DeploymentModelUtils . MUTABLE_REGISTRATION_ATTACHMENT ) ; final Resource deploymentResource = deploymentUnit . getAttachment ( DeploymentModelUtils . DEPLOYMENT_RESOURCE ) ; final CapabilityServiceSupport support = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; if ( connectorXmlDescriptor == null ) { return ; } final ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; if ( deploymentUnit . getParent ( ) != null ) { registration = baseRegistration . getSubModel ( PathAddress . pathAddress ( PathElement . pathElement ( \"subdeployment\" ) ) ) ; } else { registration = baseRegistration ; } final IronJacamarXmlDescriptor ironJacamarXmlDescriptor = deploymentUnit . getAttachment ( IronJacamarXmlDescriptor . ATTACHMENT_KEY ) ; final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; DEPLOYMENT_CONNECTOR_LOGGER . debugf ( \"ParsedRaDeploymentProcessor: Processing=%s\" , deploymentUnit ) ; final ClassLoader classLoader = module . getClassLoader ( ) ; Map < ResourceRoot , Index > annotationIndexes = AnnotationIndexUtils . getAnnotationIndexes ( deploymentUnit ) ; ServiceBuilder builder = process ( connectorXmlDescriptor , ironJacamarXmlDescriptor , classLoader , serviceTarget , annotationIndexes , deploymentUnit . getServiceName ( ) , registration , deploymentResource , support ) ; if ( builder != null ) { String bootstrapCtx = null ; if ( ironJacamarXmlDescriptor != null && ironJacamarXmlDescriptor . getIronJacamar ( ) != null && ironJacamarXmlDescriptor . getIronJacamar ( ) . getBootstrapContext ( ) != null ) bootstrapCtx = ironJacamarXmlDescriptor . getIronJacamar ( ) . getBootstrapContext ( ) ; if ( bootstrapCtx == null ) bootstrapCtx = \"default\" ; builder . requires ( ConnectorServices . BOOTSTRAP_CONTEXT_SERVICE . append ( bootstrapCtx ) ) ; //Register an empty override model regardless of we're enabled or not - the statistics listener will add the relevant childresources if ( registration . isAllowsOverride ( ) && registration . getOverrideModel ( deploymentUnit . getName ( ) ) == null ) { registration . registerOverrideModel ( deploymentUnit . getName ( ) , new OverrideDescriptionProvider ( ) { @ Override public Map < String , ModelNode > getAttributeOverrideDescriptions ( Locale locale ) { return Collections . emptyMap ( ) ; } @ Override public Map < String , ModelNode > getChildTypeOverrideDescriptions ( Locale locale ) { return Collections . emptyMap ( ) ; } } ) ; } builder . setInitialMode ( Mode . ACTIVE ) . install ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A simple implementation of the { @link org . jboss . weld . resources . spi . AnnotationDiscovery#containsAnnotation ( Class Class ) } contract . This implementation uses reflection . [CODESPLIT] public static boolean containsAnnotation ( Class < ? > javaClass , Class < ? extends Annotation > requiredAnnotation ) { for ( Class < ? > clazz = javaClass ; clazz != null && clazz != Object . class ; clazz = clazz . getSuperclass ( ) ) { // class level annotations if ( clazz == javaClass || requiredAnnotation . isAnnotationPresent ( Inherited . class ) ) { if ( containsAnnotations ( clazz . getAnnotations ( ) , requiredAnnotation ) ) { return true ; } } // fields for ( Field field : clazz . getDeclaredFields ( ) ) { if ( containsAnnotations ( field . getAnnotations ( ) , requiredAnnotation ) ) { return true ; } } // constructors for ( Constructor < ? > constructor : clazz . getConstructors ( ) ) { if ( containsAnnotations ( constructor . getAnnotations ( ) , requiredAnnotation ) ) { return true ; } for ( Annotation [ ] parameterAnnotations : constructor . getParameterAnnotations ( ) ) { if ( containsAnnotations ( parameterAnnotations , requiredAnnotation ) ) { return true ; } } } // methods for ( Method method : clazz . getDeclaredMethods ( ) ) { if ( containsAnnotations ( method . getAnnotations ( ) , requiredAnnotation ) ) { return true ; } for ( Annotation [ ] parameterAnnotations : method . getParameterAnnotations ( ) ) { if ( containsAnnotations ( parameterAnnotations , requiredAnnotation ) ) { return true ; } } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the service . Registers server activity sets transaction listener on local transaction context and creates and installs deployment controller service . [CODESPLIT] public void start ( StartContext context ) { final SuspendController suspendController = suspendControllerInjectedValue . getValue ( ) ; suspendController . registerActivity ( this ) ; final LocalTransactionContext localTransactionContext = localTransactionContextInjectedValue . getValue ( ) ; localTransactionContext . registerCreationListener ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the service . Unregisters service activity and clears transaction listener . [CODESPLIT] public void stop ( StopContext context ) { final SuspendController suspendController = suspendControllerInjectedValue . getValue ( ) ; suspendController . unRegisterActivity ( this ) ; final LocalTransactionContext localTransactionContext = localTransactionContextInjectedValue . getValue ( ) ; localTransactionContext . removeCreationListener ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies local transaction context that server is suspended and only completes suspension if there are no active invocations nor transactions . [CODESPLIT] @ Override public void suspended ( ServerActivityCallback listener ) { this . suspended = true ; listenerUpdater . set ( this , listener ) ; localTransactionContextInjectedValue . getValue ( ) . suspendRequests ( ) ; final int activeInvocationCount = activeInvocationCountUpdater . get ( this ) ; if ( activeInvocationCount == 0 ) { if ( gracefulTxnShutdown ) { if ( activeTransactionCountUpdater . get ( this ) == 0 ) { this . doneSuspended ( ) ; } else { EjbLogger . ROOT_LOGGER . suspensionWaitingActiveTransactions ( activeInvocationCount ) ; } } else { this . doneSuspended ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies local transaction context that server is resumed and restarts deployment controller . [CODESPLIT] @ Override public void resume ( ) { this . suspended = false ; localTransactionContextInjectedValue . getValue ( ) . resumeRequests ( ) ; ServerActivityCallback listener = listenerUpdater . get ( this ) ; if ( listener != null ) { listenerUpdater . compareAndSet ( this , listener , null ) ; } deploymentRepositoryInjectedValue . getValue ( ) . resume ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if a invocation should be accepted : which will happen only if server is not suspended or if the invocation involves a still active transaction . [CODESPLIT] public boolean acceptInvocation ( InterceptorContext context ) throws SystemException { if ( suspended ) { if ( ! gracefulTxnShutdown ) return false ; // a null listener means that we are done suspending; if ( listenerUpdater . get ( this ) == null || activeTransactionCountUpdater . get ( this ) == 0 ) return false ; // retrieve attachment only when we are not entirely suspended, meaning we are mid-suspension if ( ! context . hasTransaction ( ) ) { // all requests with no transaction must be rejected at this point // we need also to block requests with new transactions, which is not being done here. Instead, // we are relying on a future call to getTransaction in the same thread, before the invocation is executed; // this call will throw an exception if the transaction is new, because this suspend handler // has invoked clientTransactionContext.suspendRequests return false ; } } activeInvocationCountUpdater . incrementAndGet ( this ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies handler that an active invocation is complete . [CODESPLIT] public void invocationComplete ( ) { int activeInvocations = activeInvocationCountUpdater . decrementAndGet ( this ) ; if ( suspended && activeInvocations == 0 && ( ! gracefulTxnShutdown || ( activeTransactionCountUpdater . get ( this ) == 0 ) ) ) { doneSuspended ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies handler that a new transaction has been created . [CODESPLIT] @ Override public void transactionCreated ( AbstractTransaction transaction , CreatedBy createdBy ) { activeTransactionCountUpdater . incrementAndGet ( this ) ; try { transaction . registerSynchronization ( this ) ; } catch ( RollbackException | IllegalStateException e ) { // it means the transaction is marked for rollback, or is prepared for commit, at this point we cannot register synchronization decrementTransactionCount ( ) ; } catch ( SystemException e ) { decrementTransactionCount ( ) ; EjbLogger . ROOT_LOGGER . debug ( \"Unexpected exception\" , e ) ; throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completes suspension : stop deployment controller . [CODESPLIT] private void doneSuspended ( ) { final ServerActivityCallback oldListener = listener ; if ( oldListener != null && listenerUpdater . compareAndSet ( this , oldListener , null ) ) { deploymentRepositoryInjectedValue . getValue ( ) . suspend ( ) ; oldListener . done ( ) ; EjbLogger . ROOT_LOGGER . suspensionComplete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Releases the service returns <code > true< / code > if the service is removed as a result or false otherwise [CODESPLIT] public boolean release ( ) { if ( refcnt != null && refcnt . decrementAndGet ( ) <= 0 && controller != null ) { controller . setMode ( ServiceController . Mode . REMOVE ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind the entry into the injected context . [CODESPLIT] public void start ( StartContext context ) throws StartException { final ServiceBasedNamingStore namingStore = namingStoreValue . getValue ( ) ; controller = context . getController ( ) ; namingStore . add ( controller . getName ( ) ) ; ROOT_LOGGER . tracef ( \"Bound resource %s into naming store %s (service name %s)\" , name , namingStore , controller . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbind the entry from the injected context . [CODESPLIT] public void stop ( StopContext context ) { final ServiceBasedNamingStore namingStore = namingStoreValue . getValue ( ) ; namingStore . remove ( controller . getName ( ) ) ; ROOT_LOGGER . tracef ( \"Unbound resource %s into naming store %s (service name %s)\" , name , namingStore , context . getController ( ) . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines a ServiceName from a capability name . Only supported for use by services installed by this subsystem ; will not function reliably until the subsystem has begun adding runtime services . [CODESPLIT] public static ServiceName getCapabilityServiceName ( String capabilityBaseName , String ... dynamicParts ) { if ( capabilityServiceSupport == null ) { throw new IllegalStateException ( ) ; } if ( dynamicParts == null || dynamicParts . length == 0 ) { return capabilityServiceSupport . getCapabilityServiceName ( capabilityBaseName ) ; } return capabilityServiceSupport . getCapabilityServiceName ( capabilityBaseName , dynamicParts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the resource roots for a . war deployment [CODESPLIT] private List < ResourceRoot > createResourceRoots ( final VirtualFile deploymentRoot , final DeploymentUnit deploymentUnit ) throws IOException , DeploymentUnitProcessingException { final List < ResourceRoot > entries = new ArrayList < ResourceRoot > ( ) ; // WEB-INF classes final VirtualFile webinfClasses = deploymentRoot . getChild ( WEB_INF_CLASSES ) ; if ( webinfClasses . exists ( ) ) { final ResourceRoot webInfClassesRoot = new ResourceRoot ( webinfClasses . getName ( ) , webinfClasses , null ) ; ModuleRootMarker . mark ( webInfClassesRoot ) ; entries . add ( webInfClassesRoot ) ; } // WEB-INF lib Map < String , MountedDeploymentOverlay > overlays = deploymentUnit . getAttachment ( Attachments . DEPLOYMENT_OVERLAY_LOCATIONS ) ; final VirtualFile webinfLib = deploymentRoot . getChild ( WEB_INF_LIB ) ; if ( webinfLib . exists ( ) ) { final List < VirtualFile > archives = webinfLib . getChildren ( DEFAULT_WEB_INF_LIB_FILTER ) ; for ( final VirtualFile archive : archives ) { try { String relativeName = archive . getPathNameRelativeTo ( deploymentRoot ) ; MountedDeploymentOverlay overlay = overlays . get ( relativeName ) ; Closeable closable = null ; if ( overlay != null ) { overlay . remountAsZip ( false ) ; } else if ( archive . isFile ( ) ) { closable = VFS . mountZip ( archive , archive , TempFileProviderService . provider ( ) ) ; } else { closable = null ; } final ResourceRoot webInfArchiveRoot = new ResourceRoot ( archive . getName ( ) , archive , new MountHandle ( closable ) ) ; ModuleRootMarker . mark ( webInfArchiveRoot ) ; entries . add ( webInfArchiveRoot ) ; } catch ( IOException e ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . failToProcessWebInfLib ( archive ) , e ) ; } } } return entries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( ExtensionContext context ) { final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; final ManagementResourceRegistration registration = subsystem . registerSubsystemModel ( new NamingSubsystemRootResourceDefinition ( ) ) ; registration . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; registration . registerSubModel ( NamingBindingResourceDefinition . INSTANCE ) ; registration . registerSubModel ( RemoteNamingResourceDefinition . INSTANCE ) ; if ( context . isRuntimeOnlyRegistrationValid ( ) ) { registration . registerOperationHandler ( NamingSubsystemRootResourceDefinition . JNDI_VIEW , JndiViewOperation . INSTANCE , false ) ; } subsystem . registerXMLElementWriter ( NamingSubsystemXMLPersister . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_0 , ( ) -> new NamingSubsystem10Parser ( context . getProcessType ( ) == ProcessType . APPLICATION_CLIENT ) ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_1 , NamingSubsystem11Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_2 , NamingSubsystem12Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_3 , NamingSubsystem13Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_4 , NamingSubsystem14Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_2_0 , NamingSubsystem20Parser :: new ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used by TransactionScopedEntityManager to detach entities loaded by a query in a non - jta invocation . [CODESPLIT] protected Query detachQueryNonTxInvocation ( EntityManager underlyingEntityManager , Query underLyingQuery ) { if ( ! this . isExtendedPersistenceContext ( ) && ! this . isInTx ( ) ) { return new QueryNonTxInvocationDetacher ( underlyingEntityManager , underLyingQuery ) ; } return underLyingQuery ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used by TransactionScopedEntityManager to detach entities loaded by a query in a non - jta invocation . [CODESPLIT] protected < T > TypedQuery < T > detachTypedQueryNonTxInvocation ( EntityManager underlyingEntityManager , TypedQuery < T > underLyingQuery ) { if ( ! this . isExtendedPersistenceContext ( ) && ! this . isInTx ( ) ) { return new TypedQueryNonTxInvocationDetacher <> ( underlyingEntityManager , underLyingQuery ) ; } return underLyingQuery ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation --------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . PrimitiveDefHelper . narrow ( servantToReference ( new PrimitiveDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( final ExtensionContext context ) { JAXRS_LOGGER . debug ( \"Activating JAX-RS Extension\" ) ; final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; final ManagementResourceRegistration registration = subsystem . registerSubsystemModel ( JaxrsSubsystemDefinition . INSTANCE ) ; registration . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; ManagementResourceRegistration jaxrsResReg = subsystem . registerDeploymentModel ( JaxrsDeploymentDefinition . INSTANCE ) ; jaxrsResReg . registerSubModel ( DeploymentRestResourcesDefintion . INSTANCE ) ; subsystem . registerXMLElementWriter ( parser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( final ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , JaxrsExtension . NAMESPACE , ( ) -> parser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the session bean for remote and local views and updates the { @link SessionBeanComponentDescription } accordingly [CODESPLIT] private void processViewAnnotations ( final DeploymentUnit deploymentUnit , final Class < ? > sessionBeanClass , final SessionBeanComponentDescription sessionBeanComponentDescription ) throws DeploymentUnitProcessingException { final Collection < Class < ? > > remoteBusinessInterfaces = this . getRemoteBusinessInterfaces ( deploymentUnit , sessionBeanClass ) ; if ( remoteBusinessInterfaces != null && ! remoteBusinessInterfaces . isEmpty ( ) ) { sessionBeanComponentDescription . addRemoteBusinessInterfaceViews ( this . toString ( remoteBusinessInterfaces ) ) ; } // fetch the local business interfaces of the bean Collection < Class < ? > > localBusinessInterfaces = this . getLocalBusinessInterfaces ( deploymentUnit , sessionBeanClass ) ; if ( localBusinessInterfaces != null && ! localBusinessInterfaces . isEmpty ( ) ) { sessionBeanComponentDescription . addLocalBusinessInterfaceViews ( this . toString ( localBusinessInterfaces ) ) ; } if ( hasNoInterfaceView ( sessionBeanClass ) ) { sessionBeanComponentDescription . addNoInterfaceView ( ) ; } // EJB 3.1 FR 4.9.7 & 4.9.8, if the bean exposes no views if ( hasNoViews ( sessionBeanComponentDescription ) ) { final Set < Class < ? > > potentialBusinessInterfaces = getPotentialBusinessInterfaces ( sessionBeanClass ) ; if ( potentialBusinessInterfaces . isEmpty ( ) ) { sessionBeanComponentDescription . addNoInterfaceView ( ) ; } else if ( potentialBusinessInterfaces . size ( ) == 1 ) { sessionBeanComponentDescription . addLocalBusinessInterfaceViews ( potentialBusinessInterfaces . iterator ( ) . next ( ) . getName ( ) ) ; } else if ( isEjbVersionGreaterThanOrEqualTo32 ( deploymentUnit ) ) { // EJB 3.2 spec states (section 4.9.7): // ... or if the bean class is annotated with neither the Local nor the Remote annotation, all implemented interfaces (excluding the interfaces listed above) // are assumed to be local business interfaces of the bean sessionBeanComponentDescription . addLocalBusinessInterfaceViews ( toString ( potentialBusinessInterfaces ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final EEModuleDescription eeModuleDescription = deploymentUnit . getAttachment ( Attachments . EE_MODULE_DESCRIPTION ) ; final Collection < ComponentDescription > componentConfigurations = eeModuleDescription . getComponentDescriptions ( ) ; if ( componentConfigurations == null || componentConfigurations . isEmpty ( ) ) { return ; } for ( ComponentDescription componentConfiguration : componentConfigurations ) { final CompositeIndex index = deploymentUnit . getAttachment ( org . jboss . as . server . deployment . Attachments . COMPOSITE_ANNOTATION_INDEX ) ; if ( index != null ) { processComponentConfig ( deploymentUnit , phaseContext , index , componentConfiguration ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the toplevel deployment module classloader and all subdeployment classloaders [CODESPLIT] private static Set < ClassLoader > allDeploymentModuleClassLoaders ( DeploymentUnit deploymentUnit ) { Set < ClassLoader > deploymentClassLoaders = new HashSet < ClassLoader > ( ) ; final DeploymentUnit topDeploymentUnit = DeploymentUtils . getTopDeploymentUnit ( deploymentUnit ) ; final Module toplevelModule = topDeploymentUnit . getAttachment ( Attachments . MODULE ) ; if ( toplevelModule != null ) { deploymentClassLoaders . add ( toplevelModule . getClassLoader ( ) ) ; final List < DeploymentUnit > subDeployments = topDeploymentUnit . getAttachmentList ( Attachments . SUB_DEPLOYMENTS ) ; for ( DeploymentUnit subDeploymentUnit : subDeployments ) { final Module subDeploymentModule = subDeploymentUnit . getAttachment ( Attachments . MODULE ) ; if ( subDeploymentModule != null ) { deploymentClassLoaders . add ( subDeploymentModule . getClassLoader ( ) ) ; } } } return deploymentClassLoaders ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if class file transformer is needed for the specified persistence unit [CODESPLIT] public static boolean needClassFileTransformer ( PersistenceUnitMetadata pu ) { boolean result = true ; String provider = pu . getPersistenceProviderClassName ( ) ; if ( pu . getProperties ( ) . containsKey ( Configuration . JPA_CONTAINER_CLASS_TRANSFORMER ) ) { result = Boolean . parseBoolean ( pu . getProperties ( ) . getProperty ( Configuration . JPA_CONTAINER_CLASS_TRANSFORMER ) ) ; } else if ( isHibernateProvider ( provider ) ) { result = ( Boolean . TRUE . toString ( ) . equals ( pu . getProperties ( ) . getProperty ( HIBERNATE_USE_CLASS_ENHANCER ) ) || Boolean . TRUE . toString ( ) . equals ( pu . getProperties ( ) . getProperty ( HIBERNATE_ENABLE_DIRTY_TRACKING ) ) || Boolean . TRUE . toString ( ) . equals ( pu . getProperties ( ) . getProperty ( HIBERNATE_ENABLE_LAZY_INITIALIZATION ) ) || Boolean . TRUE . toString ( ) . equals ( pu . getProperties ( ) . getProperty ( HIBERNATE_ENABLE_ASSOCIATION_MANAGEMENT ) ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if two phase persistence unit start is allowed [CODESPLIT] public static boolean allowTwoPhaseBootstrap ( PersistenceUnitMetadata pu ) { boolean result = true ; if ( EE_DEFAULT_DATASOURCE . equals ( pu . getJtaDataSourceName ( ) ) ) { result = false ; } if ( pu . getProperties ( ) . containsKey ( Configuration . JPA_ALLOW_TWO_PHASE_BOOTSTRAP ) ) { result = Boolean . parseBoolean ( pu . getProperties ( ) . getProperty ( Configuration . JPA_ALLOW_TWO_PHASE_BOOTSTRAP ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the default data - source should be used [CODESPLIT] public static boolean allowDefaultDataSourceUse ( PersistenceUnitMetadata pu ) { boolean result = true ; if ( pu . getProperties ( ) . containsKey ( Configuration . JPA_ALLOW_DEFAULT_DATA_SOURCE_USE ) ) { result = Boolean . parseBoolean ( pu . getProperties ( ) . getProperty ( Configuration . JPA_ALLOW_DEFAULT_DATA_SOURCE_USE ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if detaching of managed entities should be deferred until the entity manager is closed . Note : only applies to transaction scoped entity managers used without an active JTA transaction . [CODESPLIT] public static boolean deferEntityDetachUntilClose ( final Map < String , Object > properties ) { boolean result = false ; if ( properties . containsKey ( JPA_DEFER_DETACH ) ) result = Boolean . parseBoolean ( ( String ) properties . get ( JPA_DEFER_DETACH ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow the mixed synchronization checking to be skipped for backward compatibility with WildFly 10 . 1 . 0 [CODESPLIT] public static boolean skipMixedSynchronizationTypeCheck ( EntityManagerFactory emf , Map targetEntityManagerProperties ) { boolean result = false ; // EntityManager properties will take priority over persistence.xml level (emf) properties if ( targetEntityManagerProperties != null && targetEntityManagerProperties . containsKey ( SKIPMIXEDSYNCTYPECHECKING ) ) { result = Boolean . parseBoolean ( ( String ) targetEntityManagerProperties . get ( SKIPMIXEDSYNCTYPECHECKING ) ) ; } else if ( emf . getProperties ( ) != null && emf . getProperties ( ) . containsKey ( SKIPMIXEDSYNCTYPECHECKING ) ) { result = Boolean . parseBoolean ( ( String ) emf . getProperties ( ) . get ( SKIPMIXEDSYNCTYPECHECKING ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow an unsynchronized persistence context that is joined to the transaction be treated the same as a synchronized persistence context with respect to the checking for mixed unsync / sync types . [CODESPLIT] public static boolean allowJoinedUnsyncPersistenceContext ( EntityManagerFactory emf , Map targetEntityManagerProperties ) { boolean result = false ; // EntityManager properties will take priority over persistence.xml (emf) properties if ( targetEntityManagerProperties != null && targetEntityManagerProperties . containsKey ( ALLOWJOINEDUNSYNCPC ) ) { result = Boolean . parseBoolean ( ( String ) targetEntityManagerProperties . get ( ALLOWJOINEDUNSYNCPC ) ) ; } else if ( emf . getProperties ( ) != null && emf . getProperties ( ) . containsKey ( ALLOWJOINEDUNSYNCPC ) ) { result = Boolean . parseBoolean ( ( String ) emf . getProperties ( ) . get ( ALLOWJOINEDUNSYNCPC ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the <code > strictMaxPoolModel< / code > from the <code > operation< / code > [CODESPLIT] @ Override protected void populateModel ( ModelNode operation , ModelNode strictMaxPoolModel ) throws OperationFailedException { for ( AttributeDefinition attr : StrictMaxPoolResourceDefinition . ATTRIBUTES . values ( ) ) { attr . validateAndSet ( operation , strictMaxPoolModel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the CORBA object reference associated with a Remote object by using the javax . rmi . CORBA package . <p / > Use reflection to avoid hard dependencies on javax . rmi . CORBA package . This method effective does the following : <blockquote > <pre > java . lang . Object stub ; try { stub = PortableRemoteObject . toStub ( remoteObj ) ; } catch ( Exception e ) { throw new ConfigurationException ( Object not exported or not found ) ; } if ( ! ( stub instanceof javax . rmi . CORBA . Stub )) { return null ; // JRMP impl or JRMP stub } try { (( javax . rmi . CORBA . Stub ) stub ) . connect ( orb ) ; // try to connect IIOP stub } catch ( RemoteException e ) { // ignore already connected error } return ( javax . rmi . CORBA . Stub ) stub ; [CODESPLIT] public static org . omg . CORBA . Object remoteToCorba ( Remote remoteObj , ORB orb ) throws ClassNotFoundException , ConfigurationException { synchronized ( CorbaUtils . class ) { if ( toStubMethod == null ) { initMethodHandles ( ) ; } } // First, get remoteObj's stub // javax.rmi.CORBA.Stub stub = PortableRemoteObject.toStub(remoteObj); java . lang . Object stub ; try { stub = toStubMethod . invoke ( null , new java . lang . Object [ ] { remoteObj } ) ; } catch ( InvocationTargetException e ) { Throwable realException = e . getTargetException ( ) ; // realException.printStackTrace(); ConfigurationException ce = IIOPLogger . ROOT_LOGGER . problemInvokingPortableRemoteObjectToStub ( ) ; ce . setRootCause ( realException ) ; throw ce ; } catch ( IllegalAccessException e ) { ConfigurationException ce = IIOPLogger . ROOT_LOGGER . cannotInvokePortableRemoteObjectToStub ( ) ; ce . setRootCause ( e ) ; throw ce ; } // Next, make sure that the stub is javax.rmi.CORBA.Stub if ( ! corbaStubClass . isInstance ( stub ) ) { return null ; // JRMP implementation or JRMP stub } // Next, make sure that the stub is connected // Invoke stub.connect(orb) try { connectMethod . invoke ( stub , new java . lang . Object [ ] { orb } ) ; } catch ( InvocationTargetException e ) { Throwable realException = e . getTargetException ( ) ; // realException.printStackTrace(); if ( ! ( realException instanceof java . rmi . RemoteException ) ) { ConfigurationException ce = IIOPLogger . ROOT_LOGGER . problemInvokingStubConnect ( ) ; ce . setRootCause ( realException ) ; throw ce ; } // ignore RemoteException because stub might have already // been connected } catch ( IllegalAccessException e ) { ConfigurationException ce = IIOPLogger . ROOT_LOGGER . cannotInvokeStubConnect ( ) ; ce . setRootCause ( e ) ; throw ce ; } // Finally, return stub return ( org . omg . CORBA . Object ) stub ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get ORB using given server and port number and properties from environment . [CODESPLIT] public static ORB getOrb ( String server , int port , Hashtable env ) { // See if we can get info from environment Properties orbProp ; // Extract any org.omg.CORBA properties from environment if ( env != null ) { // Get all String properties orbProp = new Properties ( ) ; final Enumeration envProp = env . keys ( ) ; while ( envProp . hasMoreElements ( ) ) { String key = ( String ) envProp . nextElement ( ) ; Object val = env . get ( key ) ; if ( val instanceof String ) { orbProp . put ( key , val ) ; } } final Enumeration mainProps = orbProperties . keys ( ) ; while ( mainProps . hasMoreElements ( ) ) { String key = ( String ) mainProps . nextElement ( ) ; Object val = orbProperties . get ( key ) ; if ( val instanceof String ) { orbProp . put ( key , val ) ; } } } else { orbProp = orbProperties ; } if ( server != null ) { orbProp . put ( \"org.omg.CORBA.ORBInitialHost\" , server ) ; } if ( port >= 0 ) { orbProp . put ( \"org.omg.CORBA.ORBInitialPort\" , \"\" + port ) ; } // Get Applet from environment if ( env != null ) { Object applet = env . get ( Context . APPLET ) ; if ( applet != null ) { // Create ORBs for an applet return initAppletORB ( applet , orbProp ) ; } } // Create ORBs using orbProp for a standalone application return ORB . init ( new String [ 0 ] , orbProp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns a new ORB instance for the given applet without creating a static dependency on java . applet . [CODESPLIT] private static ORB initAppletORB ( Object applet , Properties orbProp ) { try { Class < ? > appletClass = Class . forName ( \"java.applet.Applet\" , true , null ) ; if ( ! appletClass . isInstance ( applet ) ) { throw new ClassCastException ( applet . getClass ( ) . getName ( ) ) ; } // invoke the static method ORB.init(applet, orbProp); Method method = ORB . class . getMethod ( \"init\" , appletClass , Properties . class ) ; return ( ORB ) method . invoke ( null , applet , orbProp ) ; } catch ( ClassNotFoundException e ) { // java.applet.Applet doesn't exist and the applet parameter is // non-null; so throw CCE throw new ClassCastException ( applet . getClass ( ) . getName ( ) ) ; } catch ( NoSuchMethodException e ) { throw new AssertionError ( e ) ; } catch ( InvocationTargetException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else if ( cause instanceof Error ) { throw ( Error ) cause ; } throw new AssertionError ( e ) ; } catch ( IllegalAccessException iae ) { throw new AssertionError ( iae ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes reflection method handles for RMI - IIOP . [CODESPLIT] private static void initMethodHandles ( ) throws ClassNotFoundException { // Get javax.rmi.CORBA.Stub class corbaStubClass = Class . forName ( \"javax.rmi.CORBA.Stub\" ) ; // Get javax.rmi.CORBA.Stub.connect(org.omg.CORBA.ORB) method try { connectMethod = corbaStubClass . getMethod ( \"connect\" , new Class [ ] { org . omg . CORBA . ORB . class } ) ; } catch ( NoSuchMethodException e ) { throw IIOPLogger . ROOT_LOGGER . noMethodDefForStubConnect ( ) ; } // Get javax.rmi.PortableRemoteObject method Class proClass = Class . forName ( \"javax.rmi.PortableRemoteObject\" ) ; // Get javax.rmi.PortableRemoteObject(java.rmi.Remote) method try { toStubMethod = proClass . getMethod ( \"toStub\" , new Class [ ] { java . rmi . Remote . class } ) ; } catch ( NoSuchMethodException e ) { throw IIOPLogger . ROOT_LOGGER . noMethodDefForPortableRemoteObjectToStub ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the active naming store [CODESPLIT] public static void setActiveNamingStore ( final NamingStore namingStore ) { if ( WildFlySecurityManager . isChecking ( ) ) { System . getSecurityManager ( ) . checkPermission ( SET_ACTIVE_NAMING_STORE ) ; } ACTIVE_NAMING_STORE = namingStore ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the naming components required by { [CODESPLIT] public static void initializeNamingManager ( ) { // Setup naming environment final String property = WildFlySecurityManager . getPropertyPrivileged ( Context . URL_PKG_PREFIXES , null ) ; if ( property == null || property . isEmpty ( ) ) { WildFlySecurityManager . setPropertyPrivileged ( Context . URL_PKG_PREFIXES , PACKAGE_PREFIXES ) ; } else if ( ! Arrays . asList ( property . split ( \":\" ) ) . contains ( PACKAGE_PREFIXES ) ) { WildFlySecurityManager . setPropertyPrivileged ( Context . URL_PKG_PREFIXES , PACKAGE_PREFIXES + \":\" + property ) ; } try { //If we are reusing the JVM. e.g. in tests we should not set this again if ( ! NamingManager . hasInitialContextFactoryBuilder ( ) ) NamingManager . setInitialContextFactoryBuilder ( new InitialContextFactoryBuilder ( ) ) ; } catch ( NamingException e ) { ROOT_LOGGER . failedToSet ( e , \"InitialContextFactoryBuilder\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void bind ( final Name name , final Object object ) throws NamingException { check ( name , JndiPermission . ACTION_BIND ) ; if ( namingStore instanceof WritableNamingStore ) { final Name absoluteName = getAbsoluteName ( name ) ; final Object value ; if ( object instanceof Referenceable ) { value = ( ( Referenceable ) object ) . getReference ( ) ; } else { value = object ; } if ( System . getSecurityManager ( ) == null ) { getWritableNamingStore ( ) . bind ( absoluteName , value ) ; } else { // The permissions check has already happened for the binding further permissions should be allowed final NamingException e = AccessController . doPrivileged ( new PrivilegedAction < NamingException > ( ) { @ Override public NamingException run ( ) { try { getWritableNamingStore ( ) . bind ( absoluteName , value ) ; } catch ( NamingException e ) { return e ; } return null ; } } ) ; // Check that a NamingException wasn't thrown during the bind if ( e != null ) { throw e ; } } } else { throw NamingLogger . ROOT_LOGGER . readOnlyNamingContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void bind ( final String name , final Object obj ) throws NamingException { bind ( parseName ( name ) , obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void rebind ( final Name name , Object object ) throws NamingException { check ( name , JndiPermission . ACTION_REBIND ) ; if ( namingStore instanceof WritableNamingStore ) { final Name absoluteName = getAbsoluteName ( name ) ; if ( object instanceof Referenceable ) { object = ( ( Referenceable ) object ) . getReference ( ) ; } getWritableNamingStore ( ) . rebind ( absoluteName , object ) ; } else { throw NamingLogger . ROOT_LOGGER . readOnlyNamingContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void rebind ( final String name , final Object object ) throws NamingException { rebind ( parseName ( name ) , object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void unbind ( final Name name ) throws NamingException { check ( name , JndiPermission . ACTION_UNBIND ) ; if ( namingStore instanceof WritableNamingStore ) { final Name absoluteName = getAbsoluteName ( name ) ; getWritableNamingStore ( ) . unbind ( absoluteName ) ; } else { throw NamingLogger . ROOT_LOGGER . readOnlyNamingContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void rename ( final Name oldName , final Name newName ) throws NamingException { //check for appropriate permissions first so that no other info leaks from this context //in case of insufficient perms (like the fact if it is readonly or not) check ( oldName , JndiPermission . ACTION_LOOKUP | JndiPermission . ACTION_UNBIND ) ; check ( newName , JndiPermission . ACTION_BIND ) ; if ( namingStore instanceof WritableNamingStore ) { bind ( newName , lookup ( oldName ) ) ; unbind ( oldName ) ; } else { throw NamingLogger . ROOT_LOGGER . readOnlyNamingContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void rename ( final String oldName , final String newName ) throws NamingException { rename ( parseName ( oldName ) , parseName ( newName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public NamingEnumeration < NameClassPair > list ( final Name name ) throws NamingException { check ( name , JndiPermission . ACTION_LIST ) ; try { return namingEnumeration ( namingStore . list ( getAbsoluteName ( name ) ) ) ; } catch ( CannotProceedException cpe ) { final Context continuationContext = NamingManager . getContinuationContext ( cpe ) ; return continuationContext . list ( cpe . getRemainingName ( ) ) ; } catch ( RequireResolveException r ) { final Object o = lookup ( r . getResolve ( ) ) ; if ( o instanceof Context ) { return ( ( Context ) o ) . list ( name . getSuffix ( r . getResolve ( ) . size ( ) ) ) ; } throw notAContextException ( r . getResolve ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void destroySubcontext ( final Name name ) throws NamingException { check ( name , JndiPermission . ACTION_DESTROY_SUBCONTEXT ) ; if ( ! ( namingStore instanceof WritableNamingStore ) ) { throw NamingLogger . ROOT_LOGGER . readOnlyNamingContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Context createSubcontext ( Name name ) throws NamingException { check ( name , JndiPermission . ACTION_CREATE_SUBCONTEXT ) ; if ( namingStore instanceof WritableNamingStore ) { final Name absoluteName = getAbsoluteName ( name ) ; return getWritableNamingStore ( ) . createSubcontext ( absoluteName ) ; } else { throw NamingLogger . ROOT_LOGGER . readOnlyNamingContext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object lookupLink ( Name name ) throws NamingException { check ( name , JndiPermission . ACTION_LOOKUP ) ; if ( name . isEmpty ( ) ) { return lookup ( name ) ; } try { final Name absoluteName = getAbsoluteName ( name ) ; Object link = namingStore . lookup ( absoluteName ) ; if ( ! ( link instanceof LinkRef ) && link instanceof Reference ) { link = getObjectInstance ( link , name , null ) ; } return link ; } catch ( Exception e ) { throw namingException ( NamingLogger . ROOT_LOGGER . cannotLookupLink ( ) , e , name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Name composeName ( Name name , Name prefix ) throws NamingException { final Name result = ( Name ) prefix . clone ( ) ; if ( name instanceof CompositeName ) { if ( name . size ( ) == 1 ) { // name could be a nested name final String firstComponent = name . get ( 0 ) ; result . addAll ( parseName ( firstComponent ) ) ; } else { result . addAll ( name ) ; } } else { result . addAll ( new CompositeName ( name . toString ( ) ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String composeName ( String name , String prefix ) throws NamingException { return composeName ( parseName ( name ) , parseName ( prefix ) ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object addToEnvironment ( String propName , Object propVal ) throws NamingException { final Object existing = environment . get ( propName ) ; environment . put ( propName , propVal ) ; return existing ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void addNamingListener ( final Name target , final int scope , final NamingListener listener ) throws NamingException { check ( target , JndiPermission . ACTION_ADD_NAMING_LISTENER ) ; namingStore . addNamingListener ( target , scope , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void addNamingListener ( final String target , final int scope , final NamingListener listener ) throws NamingException { addNamingListener ( parseName ( target ) , scope , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void configure ( final DeploymentPhaseContext context , final ComponentDescription description , final ComponentConfiguration configuration ) throws DeploymentUnitProcessingException { final ComponentNamingMode namingMode = description . getNamingMode ( ) ; final InjectedEENamespaceContextSelector selector = new InjectedEENamespaceContextSelector ( ) ; final String applicationName = configuration . getApplicationName ( ) ; final String moduleName = configuration . getModuleName ( ) ; final String compName = configuration . getComponentName ( ) ; final ServiceName appContextServiceName = ContextNames . contextServiceNameOfApplication ( applicationName ) ; final ServiceName moduleContextServiceName = ContextNames . contextServiceNameOfModule ( applicationName , moduleName ) ; final ServiceName compContextServiceName = ContextNames . contextServiceNameOfComponent ( applicationName , moduleName , compName ) ; final Injector < NamingStore > appInjector = selector . getAppContextInjector ( ) ; final Injector < NamingStore > moduleInjector = selector . getModuleContextInjector ( ) ; final Injector < NamingStore > compInjector = selector . getCompContextInjector ( ) ; final Injector < NamingStore > jbossInjector = selector . getJbossContextInjector ( ) ; final Injector < NamingStore > globalInjector = selector . getGlobalContextInjector ( ) ; final Injector < NamingStore > exportedInjector = selector . getExportedContextInjector ( ) ; configuration . getStartDependencies ( ) . add ( new DependencyConfigurator < ComponentStartService > ( ) { public void configureDependency ( final ServiceBuilder < ? > serviceBuilder , ComponentStartService service ) { serviceBuilder . addDependency ( appContextServiceName , NamingStore . class , appInjector ) ; serviceBuilder . addDependency ( moduleContextServiceName , NamingStore . class , moduleInjector ) ; if ( namingMode == ComponentNamingMode . CREATE ) { serviceBuilder . addDependency ( compContextServiceName , NamingStore . class , compInjector ) ; } else if ( namingMode == ComponentNamingMode . USE_MODULE ) { serviceBuilder . addDependency ( moduleContextServiceName , NamingStore . class , compInjector ) ; } serviceBuilder . addDependency ( ContextNames . GLOBAL_CONTEXT_SERVICE_NAME , NamingStore . class , globalInjector ) ; serviceBuilder . addDependency ( ContextNames . JBOSS_CONTEXT_SERVICE_NAME , NamingStore . class , jbossInjector ) ; serviceBuilder . addDependency ( ContextNames . EXPORTED_CONTEXT_SERVICE_NAME , NamingStore . class , exportedInjector ) ; } } ) ; final InterceptorFactory interceptorFactory = new ImmediateInterceptorFactory ( new NamespaceContextInterceptor ( selector , context . getDeploymentUnit ( ) . getServiceName ( ) ) ) ; configuration . addPostConstructInterceptor ( interceptorFactory , InterceptorOrder . ComponentPostConstruct . JNDI_NAMESPACE_INTERCEPTOR ) ; configuration . addPreDestroyInterceptor ( interceptorFactory , InterceptorOrder . ComponentPreDestroy . JNDI_NAMESPACE_INTERCEPTOR ) ; if ( description . isPassivationApplicable ( ) ) { configuration . addPrePassivateInterceptor ( interceptorFactory , InterceptorOrder . ComponentPassivation . JNDI_NAMESPACE_INTERCEPTOR ) ; configuration . addPostActivateInterceptor ( interceptorFactory , InterceptorOrder . ComponentPassivation . JNDI_NAMESPACE_INTERCEPTOR ) ; } configuration . setNamespaceContextInterceptorFactory ( interceptorFactory ) ; configuration . setNamespaceContextSelector ( selector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void registerOperations ( ManagementResourceRegistration container ) { super . registerOperations ( container ) ; container . registerOperationHandler ( ADD_MIME , MimeMappingAdd . INSTANCE ) ; container . registerOperationHandler ( REMOVE_MIME , MimeMappingRemove . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all parameter DefaulValue objects . Flag all parameters with missing and invalid converters . [CODESPLIT] private void validateDefaultValues ( List < ParamDetail > detailList , HashMap < String , List < Validator > > paramConverterMap ) throws DeploymentUnitProcessingException { for ( ParamDetail detail : detailList ) { // check param converter for specific return type List < Validator > validators = paramConverterMap . get ( detail . parameter . getName ( ) ) ; if ( validators == null ) { // check for paramConverterProvider validators = paramConverterMap . get ( Object . class . getName ( ) ) ; } boolean isCheckClazzMethods = true ; if ( validators != null ) { for ( Validator v : validators ) { if ( ! v . isLazyLoad ( ) ) { try { Object obj = v . verify ( detail ) ; if ( obj != null ) { isCheckClazzMethods = false ; break ; } } catch ( Exception e ) { JAXRS_LOGGER . paramConverterFailed ( detail . defaultValue . value ( ) , detail . parameter . getSimpleName ( ) , detail . method . toString ( ) , v . toString ( ) , e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; } } } } if ( isCheckClazzMethods ) { Class baseType = detail . parameter ; Method valueOf = null ; // constructor rule try { Constructor < ? > ctor = baseType . getConstructor ( String . class ) ; if ( Modifier . isPublic ( ctor . getModifiers ( ) ) ) { continue ; // success move to next detail } } catch ( NoSuchMethodException ignored ) { } // method fromValue(String.class) rule try { Method fromValue = baseType . getDeclaredMethod ( \"fromValue\" , String . class ) ; if ( Modifier . isPublic ( fromValue . getModifiers ( ) ) ) { for ( Annotation ann : baseType . getAnnotations ( ) ) { if ( ann . annotationType ( ) . getName ( ) . equals ( \"javax.xml.bind.annotation.XmlEnum\" ) ) { valueOf = fromValue ; } } validateBaseType ( fromValue , detail . defaultValue . value ( ) , detail ) ; continue ; // success move to next detail } } catch ( NoSuchMethodException ignoredA ) { } // method fromString(String.class) rule Method fromString = null ; try { fromString = baseType . getDeclaredMethod ( \"fromString\" , String . class ) ; if ( Modifier . isStatic ( fromString . getModifiers ( ) ) ) { validateBaseType ( fromString , detail . defaultValue . value ( ) , detail ) ; continue ; // success move to next detail } } catch ( NoSuchMethodException ignoredB ) { } // method valueof(String.class) rule try { valueOf = baseType . getDeclaredMethod ( \"valueOf\" , String . class ) ; if ( Modifier . isStatic ( valueOf . getModifiers ( ) ) ) { validateBaseType ( valueOf , detail . defaultValue . value ( ) , detail ) ; continue ; // success move to next detail } } catch ( NoSuchMethodException ignored ) { } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a list of ParamConverters and ParamConverterProviders present in the application . [CODESPLIT] private HashMap < String , List < Validator > > getParamConverters ( final CompositeIndex index , final ClassLoader classLoader , Set < String > knownProviderClasses , boolean isFromUnitTest ) { HashMap < String , List < Validator > > paramConverterMap = new HashMap <> ( ) ; List < Validator > converterProviderList = new ArrayList <> ( ) ; paramConverterMap . put ( Object . class . getName ( ) , converterProviderList ) ; Set < ClassInfo > paramConverterSet = new HashSet < ClassInfo > ( ) ; if ( isFromUnitTest ) { Indexer indexer = new Indexer ( ) ; for ( String className : knownProviderClasses ) { try { String pathName = className . replace ( \".\" , File . separator ) ; InputStream stream = classLoader . getResourceAsStream ( pathName + \".class\" ) ; indexer . index ( stream ) ; stream . close ( ) ; } catch ( IOException e ) { JAXRS_LOGGER . classIntrospectionFailure ( e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; } } List < ClassInfo > paramConverterList = indexer . complete ( ) . getKnownDirectImplementors ( PARAM_CONVERTER_DOTNAME ) ; List < ClassInfo > paramConverterProviderList = indexer . complete ( ) . getKnownDirectImplementors ( PARAM_CONVERTER_PROVIDER_DOTNAME ) ; paramConverterSet . addAll ( paramConverterList ) ; paramConverterSet . addAll ( paramConverterProviderList ) ; } else { for ( String clazzName : knownProviderClasses ) { ClassInfo classInfo = index . getClassByName ( DotName . createSimple ( clazzName ) ) ; if ( classInfo != null ) { List < DotName > intfNamesList = classInfo . interfaceNames ( ) ; for ( DotName dotName : intfNamesList ) { if ( dotName . compareTo ( PARAM_CONVERTER_DOTNAME ) == 0 || dotName . compareTo ( PARAM_CONVERTER_PROVIDER_DOTNAME ) == 0 ) { paramConverterSet . add ( classInfo ) ; break ; } } } } } for ( ClassInfo classInfo : paramConverterSet ) { Class < ? > clazz = null ; Method method = null ; try { String clazzName = classInfo . name ( ) . toString ( ) ; if ( clazzName . endsWith ( \"$1\" ) ) { clazzName = clazzName . substring ( 0 , clazzName . length ( ) - 2 ) ; } clazz = classLoader . loadClass ( clazzName ) ; Constructor < ? > ctor = clazz . getConstructor ( ) ; Object object = ctor . newInstance ( ) ; List < AnnotationInstance > lazyLoadAnnotations = classInfo . annotations ( ) . get ( PARAM_CONVERTER_LAZY_DOTNAME ) ; if ( object instanceof ParamConverterProvider ) { ParamConverterProvider pcpObj = ( ParamConverterProvider ) object ; method = pcpObj . getClass ( ) . getMethod ( \"getConverter\" , Class . class , Type . class , Annotation [ ] . class ) ; converterProviderList . add ( new ConverterProvider ( pcpObj , method , lazyLoadAnnotations ) ) ; } if ( object instanceof ParamConverter ) { ParamConverter pc = ( ParamConverter ) object ; method = getFromStringMethod ( pc . getClass ( ) ) ; Class < ? > returnClazz = method . getReturnType ( ) ; List < Validator > verifiers = paramConverterMap . get ( returnClazz . getName ( ) ) ; PConverter pConverter = new PConverter ( pc , method , lazyLoadAnnotations ) ; if ( verifiers == null ) { List < Validator > vList = new ArrayList <> ( ) ; vList . add ( pConverter ) ; paramConverterMap . put ( returnClazz . getName ( ) , vList ) ; } else { verifiers . add ( pConverter ) ; } } } catch ( NoSuchMethodException nsne ) { JAXRS_LOGGER . classIntrospectionFailure ( nsne . getClass ( ) . getName ( ) , nsne . getMessage ( ) ) ; } catch ( Exception e ) { JAXRS_LOGGER . classIntrospectionFailure ( e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; } } return paramConverterMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create list of objects that represents resource method parameters with a DefaultValue annontation assigned to it . [CODESPLIT] private ArrayList < ParamDetail > getResouceClasses ( final CompositeIndex index , final ClassLoader classLoader , Set < String > knownResourceClasses , boolean isFromUnitTest ) { ArrayList < ParamDetail > detailList = new ArrayList <> ( ) ; ArrayList < String > classNameArr = new ArrayList <> ( ) ; if ( isFromUnitTest ) { Indexer indexer = new Indexer ( ) ; for ( String className : knownResourceClasses ) { try { String pathName = className . replace ( \".\" , File . separator ) ; InputStream stream = classLoader . getResourceAsStream ( pathName + \".class\" ) ; ClassInfo classInfo = indexer . index ( stream ) ; List < AnnotationInstance > defaultValuesList = classInfo . annotations ( ) . get ( DEFAULT_VALUE_DOTNAME ) ; if ( ! defaultValuesList . isEmpty ( ) ) { classNameArr . add ( ( classInfo ) . name ( ) . toString ( ) ) ; } stream . close ( ) ; } catch ( IOException e ) { JAXRS_LOGGER . classIntrospectionFailure ( e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; } } } else { for ( String clazzName : knownResourceClasses ) { ClassInfo classInfo = index . getClassByName ( DotName . createSimple ( clazzName ) ) ; if ( classInfo != null ) { Map < DotName , List < AnnotationInstance > > annotationsMap = classInfo . annotations ( ) ; if ( annotationsMap != null && ! annotationsMap . isEmpty ( ) ) { List < AnnotationInstance > xInstance = annotationsMap . get ( JaxrsAnnotations . PATH . getDotName ( ) ) ; List < AnnotationInstance > xdefaultValuesList = annotationsMap . get ( DEFAULT_VALUE_DOTNAME ) ; if ( ( xInstance != null && ! xInstance . isEmpty ( ) ) && ( xdefaultValuesList != null && ! xdefaultValuesList . isEmpty ( ) ) ) { classNameArr . add ( ( classInfo ) . name ( ) . toString ( ) ) ; } } } } } // resource classes with @DefaultValue // find methods and method params with @DefaultValue for ( String className : classNameArr ) { Class < ? > clazz = null ; try { clazz = classLoader . loadClass ( className ) ; for ( Method method : clazz . getMethods ( ) ) { if ( clazz == method . getDeclaringClass ( ) ) { Type [ ] genParamTypeArr = method . getGenericParameterTypes ( ) ; Annotation [ ] [ ] annotationMatrix = method . getParameterAnnotations ( ) ; for ( int j = 0 ; j < genParamTypeArr . length ; j ++ ) { DefaultValue defaultValue = lookupDefaultValueAnn ( annotationMatrix [ j ] ) ; if ( defaultValue != null ) { Class paramClazz = checkParamType ( genParamTypeArr [ j ] , method , j , classLoader ) ; if ( paramClazz != null ) { detailList . add ( new ParamDetail ( method , defaultValue , paramClazz , annotationMatrix [ j ] ) ) ; } } } } } } catch ( ClassNotFoundException e ) { JAXRS_LOGGER . classIntrospectionFailure ( e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; } } return detailList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take steps to properly identify the parameter s data type [CODESPLIT] private Class checkParamType ( Type genParamType , final Method method , final int paramPos , final ClassLoader classLoader ) { Class paramClazz = null ; if ( genParamType instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) genParamType ; Type [ ] actualTypeArgs = pType . getActualTypeArguments ( ) ; // skip Map types. Don't know how to set default value for these if ( actualTypeArgs . length == 1 ) { try { paramClazz = classLoader . loadClass ( actualTypeArgs [ 0 ] . getTypeName ( ) ) ; } catch ( Exception ee ) { JAXRS_LOGGER . classIntrospectionFailure ( ee . getClass ( ) . getName ( ) , ee . getMessage ( ) ) ; } } } else { Class < ? > [ ] paramArr = method . getParameterTypes ( ) ; if ( paramArr [ paramPos ] . isArray ( ) ) { Class compClazz = paramArr [ paramPos ] . getComponentType ( ) ; if ( ! compClazz . isPrimitive ( ) ) { paramClazz = compClazz ; } } else { if ( ! paramArr [ paramPos ] . isPrimitive ( ) ) { paramClazz = paramArr [ paramPos ] ; } } } return paramClazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract a DefaultValue annotation from the list of parameter annotations [CODESPLIT] private DefaultValue lookupDefaultValueAnn ( Annotation [ ] annotationArr ) { for ( Annotation ann : annotationArr ) { if ( ann instanceof DefaultValue ) { return ( DefaultValue ) ann ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Confirm the method can handle the default value without throwing and exception . [CODESPLIT] private void validateBaseType ( Method method , String defaultValue , ParamDetail detail ) throws DeploymentUnitProcessingException { if ( defaultValue != null ) { try { method . invoke ( method . getDeclaringClass ( ) , defaultValue ) ; } catch ( Exception e ) { JAXRS_LOGGER . baseTypeMethodFailed ( defaultValue , detail . parameter . getSimpleName ( ) , detail . method . toString ( ) , method . toString ( ) , e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( ExtensionContext context ) { final boolean registerRuntimeOnly = context . isRuntimeOnlyRegistrationValid ( ) ; final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; subsystem . registerXMLElementWriter ( EJB3SubsystemXMLPersister . INSTANCE ) ; PathManager pathManager = context . getProcessType ( ) . isServer ( ) ? context . getPathManager ( ) : null ; subsystem . registerSubsystemModel ( new EJB3SubsystemRootResourceDefinition ( registerRuntimeOnly , pathManager ) ) ; if ( registerRuntimeOnly ) { ResourceDefinition deploymentsDef = new SimpleResourceDefinition ( new Parameters ( PathElement . pathElement ( ModelDescriptionConstants . SUBSYSTEM , SUBSYSTEM_NAME ) , getResourceDescriptionResolver ( \"deployed\" ) ) . setFeature ( false ) ) ; final ManagementResourceRegistration deploymentsRegistration = subsystem . registerDeploymentModel ( deploymentsDef ) ; deploymentsRegistration . registerSubModel ( MessageDrivenBeanResourceDefinition . INSTANCE ) ; deploymentsRegistration . registerSubModel ( SingletonBeanDeploymentResourceDefinition . INSTANCE ) ; deploymentsRegistration . registerSubModel ( StatelessSessionBeanDeploymentResourceDefinition . INSTANCE ) ; deploymentsRegistration . registerSubModel ( StatefulSessionBeanDeploymentResourceDefinition . INSTANCE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_0 , EJB3Subsystem10Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_1 , EJB3Subsystem11Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_2 , EJB3Subsystem12Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_3 , EJB3Subsystem13Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_4 , EJB3Subsystem14Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_1_5 , EJB3Subsystem15Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_2_0 , EJB3Subsystem20Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_3_0 , EJB3Subsystem30Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_4_0 , EJB3Subsystem40Parser :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , NAMESPACE_5_0 , EJB3Subsystem50Parser :: new ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "At injection time of a XPC register the XPC ( step 1 of 2 ) finishRegistrationOfPersistenceContext is step 2 [CODESPLIT] public static void registerPersistenceContext ( ExtendedEntityManager xpc ) { if ( xpc == null ) { throw JpaLogger . ROOT_LOGGER . nullParameter ( \"SFSBXPCMap.RegisterPersistenceContext\" , \"EntityManager\" ) ; } final List < ExtendedEntityManager > store = deferToPostConstruct . get ( ) ; store . add ( xpc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by postconstruct interceptor [CODESPLIT] public static ExtendedEntityManager [ ] getDeferredEntityManagers ( ) { List < ExtendedEntityManager > store = deferToPostConstruct . get ( ) ; try { if ( store . isEmpty ( ) ) { return EMPTY ; } else { return store . toArray ( new ExtendedEntityManager [ store . size ( ) ] ) ; } } finally { store . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a tx Status index to a String [CODESPLIT] public static String statusAsString ( int status ) { if ( status >= Status . STATUS_ACTIVE && status <= Status . STATUS_ROLLING_BACK ) { return TxStatusStrings [ status ] ; } else { return \"STATUS_INVALID(\" + status + \")\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Check that none of the attrs are defined or log a warning . [CODESPLIT] private void checkNoAttributesIsDefined ( String definedAttributeName , PathAddress address , ModelNode model , AttributeDefinition ... attrs ) throws OperationFailedException { List < String > definedAttributes = new ArrayList <> ( ) ; for ( AttributeDefinition attr : attrs ) { if ( model . get ( attr . getName ( ) ) . isDefined ( ) ) { definedAttributes . add ( attr . getName ( ) ) ; } } if ( ! definedAttributes . isEmpty ( ) ) { MessagingLogger . ROOT_LOGGER . invalidConfiguration ( address , definedAttributeName , definedAttributes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called before call to PersistenceProvider . createContainerEntityManagerFactory ( PersistenceUnit Map ) [CODESPLIT] public static void beforeEntityManagerFactoryCreate ( Classification cacheType , PersistenceUnitMetadata persistenceUnitMetadata ) { for ( EventListener eventListener : eventListeners ) { eventListener . beforeEntityManagerFactoryCreate ( cacheType , persistenceUnitMetadata ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called after call to PersistenceProvider . createContainerEntityManagerFactory ( PersistenceUnit Map ) [CODESPLIT] public static void afterEntityManagerFactoryCreate ( Classification cacheType , PersistenceUnitMetadata persistenceUnitMetadata ) { for ( EventListener eventListener : eventListeners ) { eventListener . afterEntityManagerFactoryCreate ( cacheType , persistenceUnitMetadata ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start cache [CODESPLIT] public static Wrapper startCache ( Classification cacheType , Properties properties ) throws Exception { Wrapper result = null ; for ( EventListener eventListener : eventListeners ) { Wrapper value = eventListener . startCache ( cacheType , properties ) ; if ( value != null && result == null ) { result = value ; // return the first non-null wrapper value returned from a listener } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add cache dependencies [CODESPLIT] public static void addCacheDependencies ( Classification cacheType , Properties properties ) { for ( EventListener eventListener : eventListeners ) { eventListener . addCacheDependencies ( cacheType , properties ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop cache [CODESPLIT] public static void stopCache ( Classification cacheType , Wrapper wrapper ) { for ( EventListener eventListener : eventListeners ) { eventListener . stopCache ( cacheType , wrapper ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeContent ( XMLExtendedStreamWriter writer , SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( Namespace . CURRENT . getUriString ( ) , false ) ; ModelNode node = context . getModelNode ( ) ; writer . writeStartElement ( Element . CORE_ENVIRONMENT . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . NODE_IDENTIFIER . marshallAsAttribute ( node , writer ) ; writeProcessId ( writer , node ) ; writer . writeEndElement ( ) ; if ( TransactionSubsystemRootResourceDefinition . BINDING . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . STATUS_BINDING . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . RECOVERY_LISTENER . isMarshallable ( node ) ) { writer . writeStartElement ( Element . RECOVERY_ENVIRONMENT . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . BINDING . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . STATUS_BINDING . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . RECOVERY_LISTENER . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } if ( TransactionSubsystemRootResourceDefinition . STATISTICS_ENABLED . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . ENABLE_TSM_STATUS . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . DEFAULT_TIMEOUT . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . MAXIMUM_TIMEOUT . isMarshallable ( node ) ) { writer . writeStartElement ( Element . COORDINATOR_ENVIRONMENT . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . STATISTICS_ENABLED . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . ENABLE_TSM_STATUS . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . DEFAULT_TIMEOUT . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . MAXIMUM_TIMEOUT . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } if ( TransactionSubsystemRootResourceDefinition . OBJECT_STORE_RELATIVE_TO . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . OBJECT_STORE_PATH . isMarshallable ( node ) ) { writer . writeStartElement ( Element . OBJECT_STORE . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . OBJECT_STORE_PATH . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . OBJECT_STORE_RELATIVE_TO . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } if ( node . hasDefined ( CommonAttributes . JTS ) && node . get ( CommonAttributes . JTS ) . asBoolean ( ) ) { writer . writeStartElement ( Element . JTS . getLocalName ( ) ) ; writer . writeEndElement ( ) ; } if ( node . hasDefined ( CommonAttributes . USE_JOURNAL_STORE ) && node . get ( CommonAttributes . USE_JOURNAL_STORE ) . asBoolean ( ) ) { writer . writeStartElement ( Element . USE_JOURNAL_STORE . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . JOURNAL_STORE_ENABLE_ASYNC_IO . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } if ( node . hasDefined ( CommonAttributes . USE_JDBC_STORE ) && node . get ( CommonAttributes . USE_JDBC_STORE ) . asBoolean ( ) ) { writer . writeStartElement ( Element . JDBC_STORE . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . JDBC_STORE_DATASOURCE . marshallAsAttribute ( node , writer ) ; if ( TransactionSubsystemRootResourceDefinition . JDBC_ACTION_STORE_TABLE_PREFIX . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . JDBC_ACTION_STORE_DROP_TABLE . isMarshallable ( node ) ) { writer . writeEmptyElement ( Element . JDBC_ACTION_STORE . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . JDBC_ACTION_STORE_TABLE_PREFIX . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . JDBC_ACTION_STORE_DROP_TABLE . marshallAsAttribute ( node , writer ) ; } if ( TransactionSubsystemRootResourceDefinition . JDBC_COMMUNICATION_STORE_TABLE_PREFIX . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . JDBC_COMMUNICATION_STORE_DROP_TABLE . isMarshallable ( node ) ) { writer . writeEmptyElement ( Element . JDBC_COMMUNICATION_STORE . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . JDBC_COMMUNICATION_STORE_TABLE_PREFIX . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . JDBC_COMMUNICATION_STORE_DROP_TABLE . marshallAsAttribute ( node , writer ) ; } if ( TransactionSubsystemRootResourceDefinition . JDBC_STATE_STORE_TABLE_PREFIX . isMarshallable ( node ) || TransactionSubsystemRootResourceDefinition . JDBC_STATE_STORE_DROP_TABLE . isMarshallable ( node ) ) { writer . writeEmptyElement ( Element . JDBC_STATE_STORE . getLocalName ( ) ) ; TransactionSubsystemRootResourceDefinition . JDBC_STATE_STORE_TABLE_PREFIX . marshallAsAttribute ( node , writer ) ; TransactionSubsystemRootResourceDefinition . JDBC_STATE_STORE_DROP_TABLE . marshallAsAttribute ( node , writer ) ; } writer . writeEndElement ( ) ; } if ( node . hasDefined ( CommonAttributes . CM_RESOURCE ) && node . get ( CommonAttributes . CM_RESOURCE ) . asList ( ) . size ( ) > 0 ) { writer . writeStartElement ( Element . CM_RESOURCES . getLocalName ( ) ) ; for ( Property cmr : node . get ( CommonAttributes . CM_RESOURCE ) . asPropertyList ( ) ) { writer . writeStartElement ( CommonAttributes . CM_RESOURCE ) ; writer . writeAttribute ( Attribute . JNDI_NAME . getLocalName ( ) , cmr . getName ( ) ) ; if ( cmr . getValue ( ) . hasDefined ( CMResourceResourceDefinition . CM_TABLE_NAME . getName ( ) ) || cmr . getValue ( ) . hasDefined ( CMResourceResourceDefinition . CM_TABLE_BATCH_SIZE . getName ( ) ) || cmr . getValue ( ) . hasDefined ( CMResourceResourceDefinition . CM_TABLE_IMMEDIATE_CLEANUP . getName ( ) ) ) { writer . writeStartElement ( Element . CM_TABLE . getLocalName ( ) ) ; CMResourceResourceDefinition . CM_TABLE_NAME . marshallAsAttribute ( cmr . getValue ( ) , writer ) ; CMResourceResourceDefinition . CM_TABLE_BATCH_SIZE . marshallAsAttribute ( cmr . getValue ( ) , writer ) ; CMResourceResourceDefinition . CM_TABLE_IMMEDIATE_CLEANUP . marshallAsAttribute ( cmr . getValue ( ) , writer ) ; writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the properties from the timer - sql and extract the database dialects . [CODESPLIT] private void extractDialects ( ) { for ( Object prop : sql . keySet ( ) ) { int dot = ( ( String ) prop ) . indexOf ( ' ' ) ; if ( dot > 0 ) { databaseDialects . add ( ( ( String ) prop ) . substring ( dot + 1 ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the connection MetaData and driver name to guess which database dialect to use . [CODESPLIT] private void investigateDialect ( ) { Connection connection = null ; if ( database == null ) { // no database dialect from configuration guessing from MetaData try { connection = dataSource . getConnection ( ) ; DatabaseMetaData metaData = connection . getMetaData ( ) ; String dbProduct = metaData . getDatabaseProductName ( ) ; database = identifyDialect ( dbProduct ) ; if ( database == null ) { EjbLogger . EJB3_TIMER_LOGGER . debug ( \"Attempting to guess on driver name.\" ) ; database = identifyDialect ( metaData . getDriverName ( ) ) ; } } catch ( Exception e ) { EjbLogger . EJB3_TIMER_LOGGER . debug ( \"Unable to read JDBC metadata.\" , e ) ; } finally { safeClose ( connection ) ; } if ( database == null ) { EjbLogger . EJB3_TIMER_LOGGER . jdbcDatabaseDialectDetectionFailed ( databaseDialects . toString ( ) ) ; } else { EjbLogger . EJB3_TIMER_LOGGER . debugf ( \"Detect database dialect as '%s'.  If this is incorrect, please specify the correct dialect using the 'database' attribute in your configuration.  Supported database dialect strings are %s\" , database , databaseDialects ) ; } } else { EjbLogger . EJB3_TIMER_LOGGER . debugf ( \"Database dialect '%s' read from configuration, adjusting it to match the final database valid value.\" , database ) ; database = identifyDialect ( database ) ; EjbLogger . EJB3_TIMER_LOGGER . debugf ( \"New Database dialect is '%s'.\" , database ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the given name and check for different database types to have a unified identifier for the dialect [CODESPLIT] private String identifyDialect ( String name ) { String unified = null ; if ( name != null ) { if ( name . toLowerCase ( ) . contains ( \"postgres\" ) ) { unified = \"postgresql\" ; } else if ( name . toLowerCase ( ) . contains ( \"mysql\" ) ) { unified = \"mysql\" ; } else if ( name . toLowerCase ( ) . contains ( \"mariadb\" ) ) { unified = \"mariadb\" ; } else if ( name . toLowerCase ( ) . contains ( \"db2\" ) ) { unified = \"db2\" ; } else if ( name . toLowerCase ( ) . contains ( \"hsql\" ) || name . toLowerCase ( ) . contains ( \"hypersonic\" ) ) { unified = \"hsql\" ; } else if ( name . toLowerCase ( ) . contains ( \"h2\" ) ) { unified = \"h2\" ; } else if ( name . toLowerCase ( ) . contains ( \"oracle\" ) ) { unified = \"oracle\" ; } else if ( name . toLowerCase ( ) . contains ( \"microsoft\" ) ) { unified = \"mssql\" ; } else if ( name . toLowerCase ( ) . contains ( \"jconnect\" ) ) { unified = \"sybase\" ; } } EjbLogger . EJB3_TIMER_LOGGER . debugf ( \"Check dialect for '%s', result is '%s'\" , name , unified ) ; return unified ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the database transaction configuration is appropriate and create the timer table if necessary . [CODESPLIT] private void checkDatabase ( ) { String loadTimer = sql ( LOAD_TIMER ) ; Connection connection = null ; Statement statement = null ; PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; try { //test for the existence of the table by running the load timer query connection = dataSource . getConnection ( ) ; if ( connection . getTransactionIsolation ( ) < Connection . TRANSACTION_READ_COMMITTED ) { EjbLogger . EJB3_TIMER_LOGGER . wrongTransactionIsolationConfiguredForTimer ( ) ; } preparedStatement = connection . prepareStatement ( loadTimer ) ; preparedStatement . setString ( 1 , \"NON-EXISTENT\" ) ; preparedStatement . setString ( 2 , \"NON-EXISTENT\" ) ; preparedStatement . setString ( 3 , \"NON-EXISTENT\" ) ; resultSet = preparedStatement . executeQuery ( ) ; } catch ( SQLException e ) { //the query failed, assume it is because the table does not exist if ( connection != null ) { try { String createTable = sql ( CREATE_TABLE ) ; String [ ] statements = createTable . split ( \";\" ) ; for ( final String sql : statements ) { try { statement = connection . createStatement ( ) ; statement . executeUpdate ( sql ) ; } finally { safeClose ( statement ) ; } } } catch ( SQLException e1 ) { EjbLogger . EJB3_TIMER_LOGGER . couldNotCreateTable ( e1 ) ; } } else { EjbLogger . EJB3_TIMER_LOGGER . couldNotCreateTable ( e ) ; } } finally { safeClose ( resultSet ) ; safeClose ( preparedStatement ) ; safeClose ( statement ) ; safeClose ( connection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the stored date - string from database back to Date [CODESPLIT] private Date stringAsSchedulerDate ( final String date , final String timerId ) { if ( date == null ) { return null ; } try { return new SimpleDateFormat ( SCHEDULER_DATE_FORMAT ) . parse ( date ) ; } catch ( ParseException e ) { EjbLogger . EJB3_TIMER_LOGGER . scheduleExpressionDateFromTimerPersistenceInvalid ( timerId , e . getMessage ( ) ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the node name for persistence if the state is IN_TIMEOUT or RETRY_TIMEOUT to show which node is current active for the timer . [CODESPLIT] private void setNodeName ( final TimerState timerState , PreparedStatement statement , int paramIndex ) throws SQLException { if ( timerState == TimerState . IN_TIMEOUT || timerState == TimerState . RETRY_TIMEOUT ) { statement . setString ( paramIndex , nodeName ) ; } else { statement . setNull ( paramIndex , Types . VARCHAR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mark this deployment and the top level deployment as being a weld deployment . [CODESPLIT] public static void mark ( DeploymentUnit unit ) { unit . putAttachment ( MARKER , Boolean . TRUE ) ; if ( unit . getParent ( ) != null ) { mark ( unit . getParent ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if the { [CODESPLIT] public static boolean isPartOfWeldDeployment ( DeploymentUnit unit ) { if ( unit . getParent ( ) == null ) { return unit . getAttachment ( MARKER ) != null ; } else { return unit . getParent ( ) . getAttachment ( MARKER ) != null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unmarshals the sequence of method parameters from an input stream . [CODESPLIT] public Object [ ] readParams ( InputStream in ) { int len = paramReaders . length ; Object [ ] params = new Object [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { params [ i ] = paramReaders [ i ] . read ( in ) ; } return params ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marshals into an output stream the return value of the method . [CODESPLIT] public void writeRetval ( OutputStream out , Object retVal ) { retvalWriter . write ( out , RemoteObjectSubstitutionManager . writeReplaceRemote ( retVal ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marshals into an output stream an exception thrown by the method . [CODESPLIT] public void writeException ( OutputStream out , Throwable e ) { int len = excepWriters . length ; for ( int i = 0 ; i < len ; i ++ ) { if ( excepWriters [ i ] . getExceptionClass ( ) . isInstance ( e ) ) { excepWriters [ i ] . write ( out , e ) ; return ; } } throw new UnknownException ( e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation --------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . OperationDefHelper . narrow ( servantToReference ( new OperationDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof ContainedOperations ) defined_in_id = ( ( ContainedOperations ) defined_in ) . id ( ) ; ExceptionDescription [ ] exds ; exds = new ExceptionDescription [ exceptions . length ] ; for ( int i = 0 ; i < exceptions . length ; ++ i ) { Description d = exceptions [ i ] . describe ( ) ; exds [ i ] = ExceptionDescriptionHelper . extract ( d . value ) ; } OperationDescription od ; od = new OperationDescription ( name , id , defined_in_id , version , typeCode , mode ( ) , contexts ( ) , params ( ) , exds ) ; Any any = getORB ( ) . create_any ( ) ; OperationDescriptionHelper . insert ( any , od ) ; return new Description ( DefinitionKind . dk_Operation , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void readElement ( XMLExtendedStreamReader reader , List < ModelNode > list ) throws XMLStreamException { final PathAddress address = PathAddress . pathAddress ( MailExtension . SUBSYSTEM_PATH ) ; list . add ( Util . createAddOperation ( address ) ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { switch ( Namespace . forUri ( reader . getNamespaceURI ( ) ) ) { case MAIL_1_0 : case MAIL_1_1 : case MAIL_1_2 : { final String element = reader . getLocalName ( ) ; switch ( element ) { case MAIL_SESSION : { parseMailSession ( reader , list , address ) ; break ; } default : { reader . handleAny ( list ) ; break ; } } break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do lazy lookup . [CODESPLIT] protected < U > U lookup ( Lookup < U > lookup , int start , int depth ) { int size ; synchronized ( indexes ) { size = indexes . size ( ) ; for ( int i = start ; i < depth && i < size ; i ++ ) { U result = lookup . lookup ( indexes . get ( i ) ) ; if ( result != null ) return result ; } } if ( currentClass == null ) return null ; synchronized ( indexes ) { ClassReflectionIndex cri = index . getClassIndex ( currentClass ) ; indexes . add ( cri ) ; currentClass = currentClass . getSuperclass ( ) ; } return lookup ( lookup , size , depth ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- // [CODESPLIT] @ Override public void getResourceValue ( ResolutionContext context , ServiceBuilder < ? > serviceBuilder , DeploymentPhaseContext phaseContext , Injector < ManagedReferenceFactory > injector ) throws DeploymentUnitProcessingException { AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration = new AgroalConnectionFactoryConfigurationSupplier ( ) ; try { Class < ? > providerClass = phaseContext . getDeploymentUnit ( ) . getAttachment ( MODULE ) . getClassLoader ( ) . loadClass ( className ) ; if ( providerClass != null && ! DataSource . class . isAssignableFrom ( providerClass ) && ! Driver . class . isAssignableFrom ( providerClass ) ) { throw AgroalLogger . SERVICE_LOGGER . invalidDeploymentConnectionProvider ( ) ; } connectionFactoryConfiguration . connectionProviderClass ( providerClass ) ; } catch ( ClassNotFoundException e ) { throw AgroalLogger . SERVICE_LOGGER . loadClassDeploymentException ( e , className ) ; } for ( Map . Entry < String , String > property : properties . entrySet ( ) ) { connectionFactoryConfiguration . jdbcProperty ( property . getKey ( ) , property . getValue ( ) ) ; } if ( databaseName != null && ! databaseName . isEmpty ( ) ) { connectionFactoryConfiguration . jdbcProperty ( DATABASE_NAME_PROP , databaseName ) ; } if ( description != null && ! description . isEmpty ( ) ) { connectionFactoryConfiguration . jdbcProperty ( DESCRIPTION_PROP , description ) ; } if ( serverName != null && ! serverName . isEmpty ( ) ) { connectionFactoryConfiguration . jdbcProperty ( SERVER_NAME_PROP , serverName ) ; } if ( portNumber >= 0 ) { connectionFactoryConfiguration . jdbcProperty ( PORT_NUMBER_PROP , Integer . toString ( portNumber ) ) ; } if ( loginTimeout >= 0 ) { connectionFactoryConfiguration . jdbcProperty ( LOGIN_TIMEOUT_PROP , Integer . toString ( loginTimeout ) ) ; } if ( maxStatements >= 0 ) { connectionFactoryConfiguration . jdbcProperty ( MAX_STATEMENTS_PROP , Integer . toString ( maxStatements ) ) ; } if ( url != null && ! url . isEmpty ( ) ) { connectionFactoryConfiguration . jdbcUrl ( url ) ; } if ( user != null && ! user . isEmpty ( ) ) { connectionFactoryConfiguration . principal ( new NamePrincipal ( user ) ) ; } if ( password != null && ! password . isEmpty ( ) ) { connectionFactoryConfiguration . credential ( new SimplePassword ( password ) ) ; } connectionFactoryConfiguration . jdbcTransactionIsolation ( AgroalConnectionFactoryConfiguration . TransactionIsolation . fromLevel ( isolationLevel ) ) ; AgroalConnectionPoolConfigurationSupplier connectionPoolConfiguration = new AgroalConnectionPoolConfigurationSupplier ( ) ; connectionPoolConfiguration . connectionFactoryConfiguration ( connectionFactoryConfiguration ) ; if ( initialPoolSize >= 0 ) { connectionPoolConfiguration . initialSize ( initialPoolSize ) ; } if ( minPoolSize >= 0 ) { connectionPoolConfiguration . minSize ( minPoolSize ) ; } if ( maxPoolSize >= 0 ) { connectionPoolConfiguration . maxSize ( maxPoolSize ) ; } if ( maxIdleTime >= 0 ) { connectionPoolConfiguration . reapTimeout ( Duration . ofSeconds ( maxIdleTime ) ) ; } AgroalDataSourceConfigurationSupplier dataSourceConfiguration = new AgroalDataSourceConfigurationSupplier ( ) ; dataSourceConfiguration . connectionPoolConfiguration ( connectionPoolConfiguration ) ; ContextNames . BindInfo bindInfo = ContextNames . bindInfoForEnvEntry ( context . getApplicationName ( ) , context . getModuleName ( ) , context . getComponentName ( ) , ! context . isCompUsesModule ( ) , jndiName ) ; ServiceName dataSourceServiceName = DATASOURCE_DEFINITION_SERVICE_PREFIX . append ( bindInfo . getBinderServiceName ( ) . getCanonicalName ( ) ) ; // This is the service responsible for the JNDI binding, with a dependency on the datasource service that acts as a ManagedReferenceFactory and is used as the injection source BinderService binderService = new BinderService ( bindInfo . getBindName ( ) , this ) ; phaseContext . getServiceTarget ( ) . addService ( bindInfo . getBinderServiceName ( ) , binderService ) . addDependency ( dataSourceServiceName , ManagedReferenceFactory . class , binderService . getManagedObjectInjector ( ) ) . addDependency ( bindInfo . getParentContextServiceName ( ) , ServiceBasedNamingStore . class , binderService . getNamingStoreInjector ( ) ) . install ( ) ; ServiceBuilder svcBuilder = phaseContext . getServiceTarget ( ) . addService ( dataSourceServiceName ) ; Supplier < TransactionSynchronizationRegistry > tsrSupplier = null ; if ( transactional ) { CapabilityServiceSupport css = phaseContext . getDeploymentUnit ( ) . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; ServiceName tsrName = css . getCapabilityServiceName ( \"org.wildfly.transactions.transaction-synchronization-registry\" ) ; //noinspection unchecked tsrSupplier = ( Supplier < TransactionSynchronizationRegistry > ) svcBuilder . requires ( tsrName ) ; } DataSourceDefinitionService dataSourceService = new DataSourceDefinitionService ( bindInfo , transactional , dataSourceConfiguration , tsrSupplier ) ; svcBuilder . setInstance ( dataSourceService ) . install ( ) ; serviceBuilder . requires ( bindInfo . getBinderServiceName ( ) ) ; serviceBuilder . addDependency ( dataSourceServiceName , ManagedReferenceFactory . class , injector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called from SFSBPreCreateInterceptor before bean creation [CODESPLIT] public static void beginSfsbCreation ( ) { SFSBCallStackThreadData data = CURRENT . get ( ) ; int no = data . creationBeanNestingLevel ; if ( no == 0 ) { data . creationTimeXPCRegistration = new HashMap < String , ExtendedEntityManager > ( ) ; // create new tracking structure (passing in parent levels tracking structure or null if toplevel) data . creationTimeInjectedXPCs = new SFSBInjectedXPCs ( data . creationTimeInjectedXPCs , null ) ; } else { // create new tracking structure (passing in parent levels tracking structure or null if toplevel) SFSBInjectedXPCs parent = data . creationTimeInjectedXPCs ; data . creationTimeInjectedXPCs = new SFSBInjectedXPCs ( parent , parent . getTopLevel ( ) ) ; } data . creationBeanNestingLevel ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called from SFSBPreCreateInterceptor after bean creation [CODESPLIT] public static void endSfsbCreation ( ) { SFSBCallStackThreadData data = CURRENT . get ( ) ; int no = data . creationBeanNestingLevel ; no -- ; data . creationBeanNestingLevel = no ; if ( no == 0 ) { // Completed creating top level bean, remove 'xpc creation tracking' thread local data . creationTimeXPCRegistration = null ; data . creationTimeInjectedXPCs = null ; } else { // finished creating a sub-bean, switch to parent level 'xpc creation tracking' data . creationTimeInjectedXPCs = data . creationTimeInjectedXPCs . getParent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return for just the current entity manager invocation [CODESPLIT] public static Map < String , ExtendedEntityManager > currentSFSBCallStackInvocation ( ) { ArrayList < Map < String , ExtendedEntityManager > > stack = CURRENT . get ( ) . invocationStack ; if ( stack != null && stack . size ( ) > 0 ) { return stack . get ( stack . size ( ) - 1 ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push the passed SFSB context handle onto the invocation call stack [CODESPLIT] public static void pushCall ( Map < String , ExtendedEntityManager > entityManagers ) { currentSFSBCallStack ( ) . add ( entityManagers ) ; if ( entityManagers != null ) { /**\n             * JPA 2.0 spec section 7.9.1 Container Responsibilities:\n             * \"When a business method of the stateful session bean is invoked,\n             *  if the stateful session bean uses container managed transaction demarcation,\n             *  and the entity manager is not already associated with the current JTA transaction,\n             *  the container associates the entity manager with the current JTA transaction and\n             *  calls EntityManager.joinTransaction.\n             *  \"\n             */ for ( ExtendedEntityManager extendedEntityManager : entityManagers . values ( ) ) { extendedEntityManager . internalAssociateWithJtaTx ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops the current SFSB invocation off the invocation call stack [CODESPLIT] public static Map < String , ExtendedEntityManager > popCall ( ) { ArrayList < Map < String , ExtendedEntityManager > > stack = currentSFSBCallStack ( ) ; Map < String , ExtendedEntityManager > result = stack . remove ( stack . size ( ) - 1 ) ; stack . trimToSize ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the current SFSB invocation off the invocation call stack [CODESPLIT] static Map < String , ExtendedEntityManager > getCurrentCall ( ) { ArrayList < Map < String , ExtendedEntityManager > > stack = currentSFSBCallStack ( ) ; Map < String , ExtendedEntityManager > result = null ; if ( stack != null ) { result = stack . get ( stack . size ( ) - 1 ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add dependencies for modules required for weld deployments if managed weld configurations are attached to the deployment [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; addDependency ( moduleSpecification , moduleLoader , JAVAX_ENTERPRISE_API ) ; addDependency ( moduleSpecification , moduleLoader , JAVAX_INJECT_API ) ; if ( ! WeldDeploymentMarker . isPartOfWeldDeployment ( deploymentUnit ) ) { return ; // Skip if there are no beans.xml files in the deployment } addDependency ( moduleSpecification , moduleLoader , JAVAX_PERSISTENCE_API_ID ) ; addDependency ( moduleSpecification , moduleLoader , WELD_CORE_ID ) ; addDependency ( moduleSpecification , moduleLoader , WELD_PROBE_ID , true ) ; addDependency ( moduleSpecification , moduleLoader , WELD_API_ID ) ; addDependency ( moduleSpecification , moduleLoader , WELD_SPI_ID ) ; ModuleDependency weldSubsystemDependency = new ModuleDependency ( moduleLoader , JBOSS_AS_WELD_ID , false , false , false , false ) ; weldSubsystemDependency . addImportFilter ( PathFilters . getMetaInfFilter ( ) , true ) ; weldSubsystemDependency . addImportFilter ( PathFilters . is ( \"org/jboss/as/weld/injection\" ) , true ) ; weldSubsystemDependency . addImportFilter ( PathFilters . acceptAll ( ) , false ) ; weldSubsystemDependency . addExportFilter ( PathFilters . getMetaInfFilter ( ) , true ) ; moduleSpecification . addSystemDependency ( weldSubsystemDependency ) ; // Due to serialization of EJBs ModuleDependency weldEjbDependency = new ModuleDependency ( moduleLoader , JBOSS_AS_WELD_EJB_ID , true , false , false , false ) ; weldEjbDependency . addImportFilter ( PathFilters . is ( \"org/jboss/as/weld/ejb\" ) , true ) ; weldEjbDependency . addImportFilter ( PathFilters . acceptAll ( ) , false ) ; moduleSpecification . addSystemDependency ( weldEjbDependency ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the faces config files looking for managed bean classes . The parser is quite simplistic as the only information we need is the managed - bean - class element [CODESPLIT] private void processXmlManagedBeans ( final DeploymentUnit deploymentUnit , final Set < String > managedBeanClasses ) { for ( final VirtualFile facesConfig : getConfigurationFiles ( deploymentUnit ) ) { InputStream is = null ; try { is = facesConfig . openStream ( ) ; final XMLInputFactory inputFactory = XMLInputFactory . newInstance ( ) ; inputFactory . setXMLResolver ( NoopXMLResolver . create ( ) ) ; XMLStreamReader parser = inputFactory . createXMLStreamReader ( is ) ; StringBuilder className = null ; int indent = 0 ; boolean managedBean = false ; boolean managedBeanClass = false ; while ( true ) { int event = parser . next ( ) ; if ( event == XMLStreamConstants . END_DOCUMENT ) { parser . close ( ) ; break ; } if ( event == XMLStreamConstants . START_ELEMENT ) { indent ++ ; if ( indent == 2 ) { if ( parser . getLocalName ( ) . equals ( MANAGED_BEAN ) ) { managedBean = true ; } } else if ( indent == 3 && managedBean ) { if ( parser . getLocalName ( ) . equals ( MANAGED_BEAN_CLASS ) ) { managedBeanClass = true ; className = new StringBuilder ( ) ; } } } else if ( event == XMLStreamConstants . END_ELEMENT ) { indent -- ; managedBeanClass = false ; if ( indent == 1 ) { managedBean = false ; } if ( className != null ) { managedBeanClasses . add ( className . toString ( ) . trim ( ) ) ; className = null ; } } else if ( managedBeanClass && event == XMLStreamConstants . CHARACTERS ) { className . append ( parser . getText ( ) ) ; } } } catch ( Exception e ) { JSFLogger . ROOT_LOGGER . managedBeansConfigParseFailed ( facesConfig ) ; } finally { try { if ( is != null ) { is . close ( ) ; } } catch ( IOException e ) { // Ignore } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "WFLY - 6617 According to JSF 2 . 2 spec it should be possible to inject beans using [CODESPLIT] private void processPhaseListeners ( final DeploymentUnit deploymentUnit , final Set < String > managedBeanClasses ) { for ( final VirtualFile facesConfig : getConfigurationFiles ( deploymentUnit ) ) { InputStream is = null ; try { is = facesConfig . openStream ( ) ; final XMLInputFactory inputFactory = XMLInputFactory . newInstance ( ) ; inputFactory . setXMLResolver ( NoopXMLResolver . create ( ) ) ; XMLStreamReader parser = inputFactory . createXMLStreamReader ( is ) ; StringBuilder phaseListenerName = null ; int indent = 0 ; boolean lifecycle = false ; boolean phaseListener = false ; while ( true ) { int event = parser . next ( ) ; if ( event == XMLStreamConstants . END_DOCUMENT ) { parser . close ( ) ; break ; } if ( event == XMLStreamConstants . START_ELEMENT ) { indent ++ ; if ( indent == 2 ) { if ( parser . getLocalName ( ) . equals ( LIFECYCLE ) ) { lifecycle = true ; } } else if ( indent == 3 && lifecycle ) { if ( parser . getLocalName ( ) . equals ( PHASE_LISTENER ) ) { phaseListener = true ; phaseListenerName = new StringBuilder ( ) ; } } } else if ( event == XMLStreamConstants . END_ELEMENT ) { indent -- ; phaseListener = false ; if ( indent == 1 ) { lifecycle = false ; } if ( phaseListenerName != null ) { managedBeanClasses . add ( phaseListenerName . toString ( ) . trim ( ) ) ; phaseListenerName = null ; } } else if ( phaseListener && event == XMLStreamConstants . CHARACTERS ) { phaseListenerName . append ( parser . getText ( ) ) ; } } } catch ( Exception e ) { JSFLogger . ROOT_LOGGER . phaseListenersConfigParseFailed ( facesConfig ) ; } finally { try { if ( is != null ) { is . close ( ) ; } } catch ( IOException e ) { // Ignore } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the IDL type name for the given class . Here we use the mapping for parameter types and return values . [CODESPLIT] public static String getTypeIDLName ( Class cls ) throws RMIIIOPViolationException { if ( cls . isPrimitive ( ) ) return PrimitiveAnalysis . getPrimitiveAnalysis ( cls ) . getIDLName ( ) ; if ( cls . isArray ( ) ) { // boxedRMI 1.3.6 Class componentClass = cls ; int sequence = 0 ; while ( componentClass . isArray ( ) ) { componentClass = componentClass . getComponentType ( ) ; ++ sequence ; } String idlName = getTypeIDLName ( componentClass ) ; int idx = idlName . lastIndexOf ( \"::\" ) ; String idlModule = idlName . substring ( 0 , idx + 2 ) ; String baseName = idlName . substring ( idx + 2 ) ; return \"::org::omg::boxedRMI\" + idlModule + \"seq\" + sequence + \"_\" + baseName ; } // special classes if ( cls == java . lang . String . class ) return \"::CORBA::WStringValue\" ; if ( cls == java . lang . Object . class ) return \"::java::lang::_Object\" ; if ( cls == java . lang . Class . class ) return \"::javax::rmi::CORBA::ClassDesc\" ; if ( cls == java . io . Serializable . class ) return \"::java::io::Serializable\" ; if ( cls == java . io . Externalizable . class ) return \"::java::io::Externalizable\" ; if ( cls == java . rmi . Remote . class ) return \"::java::rmi::Remote\" ; if ( cls == org . omg . CORBA . Object . class ) return \"::CORBA::Object\" ; // remote interface? if ( cls . isInterface ( ) && java . rmi . Remote . class . isAssignableFrom ( cls ) ) { InterfaceAnalysis ia = InterfaceAnalysis . getInterfaceAnalysis ( cls ) ; return ia . getIDLModuleName ( ) + \"::\" + ia . getIDLName ( ) ; } // IDL interface? if ( cls . isInterface ( ) && org . omg . CORBA . Object . class . isAssignableFrom ( cls ) && org . omg . CORBA . portable . IDLEntity . class . isAssignableFrom ( cls ) ) { InterfaceAnalysis ia = InterfaceAnalysis . getInterfaceAnalysis ( cls ) ; return ia . getIDLModuleName ( ) + \"::\" + ia . getIDLName ( ) ; } // exception? if ( Throwable . class . isAssignableFrom ( cls ) ) { if ( Exception . class . isAssignableFrom ( cls ) && ! RuntimeException . class . isAssignableFrom ( cls ) ) { ExceptionAnalysis ea = ExceptionAnalysis . getExceptionAnalysis ( cls ) ; return ea . getIDLModuleName ( ) + \"::\" + ea . getIDLName ( ) ; } } // got to be value ValueAnalysis va = ValueAnalysis . getValueAnalysis ( cls ) ; return va . getIDLModuleName ( ) + \"::\" + va . getIDLName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if this class is valid for RMI / IIOP mapping . This method will either throw an exception or return true . [CODESPLIT] public static boolean isValidRMIIIOP ( Class cls ) throws RMIIIOPViolationException { if ( cls . isPrimitive ( ) ) return true ; if ( cls . isArray ( ) ) return isValidRMIIIOP ( cls . getComponentType ( ) ) ; // special interfaces if ( cls == Serializable . class || cls == Externalizable . class ) return true ; // interface? if ( cls . isInterface ( ) && java . rmi . Remote . class . isAssignableFrom ( cls ) ) { InterfaceAnalysis . getInterfaceAnalysis ( cls ) ; return true ; } // exception? if ( Throwable . class . isAssignableFrom ( cls ) ) { if ( Exception . class . isAssignableFrom ( cls ) && ! RuntimeException . class . isAssignableFrom ( cls ) ) { ExceptionAnalysis . getExceptionAnalysis ( cls ) ; } return true ; } // special values if ( cls == Object . class || cls == String . class || cls == Class . class ) return true ; // got to be value ValueAnalysis . getValueAnalysis ( cls ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a java primitive into an Any . The primitive is assumed to be wrapped in one of the primitive wrapper classes . [CODESPLIT] public static void insertAnyPrimitive ( Any any , Object primitive ) { Class type = primitive . getClass ( ) ; if ( type == Boolean . class ) any . insert_boolean ( ( ( Boolean ) primitive ) . booleanValue ( ) ) ; else if ( type == Character . class ) any . insert_wchar ( ( ( Character ) primitive ) . charValue ( ) ) ; else if ( type == Byte . class ) any . insert_octet ( ( ( Byte ) primitive ) . byteValue ( ) ) ; else if ( type == Short . class ) any . insert_short ( ( ( Short ) primitive ) . shortValue ( ) ) ; else if ( type == Integer . class ) any . insert_long ( ( ( Integer ) primitive ) . intValue ( ) ) ; else if ( type == Long . class ) any . insert_longlong ( ( ( Long ) primitive ) . longValue ( ) ) ; else if ( type == Float . class ) any . insert_float ( ( ( Float ) primitive ) . floatValue ( ) ) ; else if ( type == Double . class ) any . insert_double ( ( ( Double ) primitive ) . doubleValue ( ) ) ; else throw IIOPLogger . ROOT_LOGGER . notAPrimitive ( type . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map Java name to IDL name as per sections 1 . 3 . 2 . 3 1 . 3 . 2 . 4 and 1 . 3 . 2 . 2 . This only works for a single name component without a qualifying dot . [CODESPLIT] public static String javaToIDLName ( String name ) { if ( name == null || \"\" . equals ( name ) || name . indexOf ( ' ' ) != - 1 ) throw IIOPLogger . ROOT_LOGGER . nameCannotBeNullEmptyOrQualified ( ) ; StringBuffer res = new StringBuffer ( name . length ( ) ) ; if ( name . charAt ( 0 ) == ' ' ) res . append ( ' ' ) ; // 1.3.2.3 for ( int i = 0 ; i < name . length ( ) ; ++ i ) { char c = name . charAt ( i ) ; if ( isLegalIDLIdentifierChar ( c ) ) res . append ( c ) ; else // 1.3.2.4 res . append ( ' ' ) . append ( toHexString ( ( int ) c ) ) ; } String s = res . toString ( ) ; if ( isReservedIDLKeyword ( s ) ) return \"_\" + s ; else return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the IR global ID of the given class or interface . This is described in section 1 . 3 . 5 . 7 . The returned string is in the RMI hashed format like RMI : java . util . Hashtable : C03324C0EA357270 : 13BB0F25214AE4B8 . [CODESPLIT] public static String getIRIdentifierOfClass ( Class cls ) { if ( cls . isPrimitive ( ) ) throw IIOPLogger . ROOT_LOGGER . primitivesHaveNoIRIds ( ) ; String result = ( String ) classIRIdentifierCache . get ( cls ) ; if ( result != null ) return result ; String name = cls . getName ( ) ; StringBuffer b = new StringBuffer ( \"RMI:\" ) ; for ( int i = 0 ; i < name . length ( ) ; ++ i ) { char c = name . charAt ( i ) ; if ( c < 256 ) b . append ( c ) ; else b . append ( \"\\\\U\" ) . append ( toHexString ( ( int ) c ) ) ; } long clsHash = getClassHashCode ( cls ) ; b . append ( ' ' ) . append ( toHexString ( clsHash ) ) ; ObjectStreamClass osClass = ObjectStreamClass . lookup ( cls ) ; if ( osClass != null ) { long serialVersionUID = osClass . getSerialVersionUID ( ) ; if ( clsHash != serialVersionUID ) b . append ( ' ' ) . append ( toHexString ( serialVersionUID ) ) ; } result = b . toString ( ) ; classIRIdentifierCache . put ( cls , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the argument is a reserved IDL keyword . [CODESPLIT] private static boolean isReservedIDLKeyword ( String s ) { // TODO: faster lookup for ( int i = 0 ; i < reservedIDLKeywords . length ; ++ i ) if ( reservedIDLKeywords [ i ] . equals ( s ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a <code > char< / code > is a legal IDL identifier character . [CODESPLIT] private static boolean isLegalIDLIdentifierChar ( char c ) { if ( c >= 0x61 && c <= 0x7a ) return true ; // lower case letter if ( c >= 0x30 && c <= 0x39 ) return true ; // digit if ( c >= 0x41 && c <= 0x5a ) return true ; // upper case letter if ( c == ' ' ) return true ; // underscore return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the class hash code as specified in The Common Object Request Broker : Architecture and Specification ( 01 - 02 - 33 ) section 10 . 6 . 2 . [CODESPLIT] static long getClassHashCode ( Class cls ) { // The simple cases if ( cls . isInterface ( ) ) return 0 ; if ( ! Serializable . class . isAssignableFrom ( cls ) ) return 0 ; if ( Externalizable . class . isAssignableFrom ( cls ) ) return 1 ; // Try cache Long l = ( Long ) classHashCodeCache . get ( cls ) ; if ( l != null ) return l . longValue ( ) ; // Has to calculate the hash. ByteArrayOutputStream baos = new ByteArrayOutputStream ( 256 ) ; DataOutputStream dos = new DataOutputStream ( baos ) ; // Step 1 Class superClass = cls . getSuperclass ( ) ; if ( superClass != null && superClass != Object . class ) { try { dos . writeLong ( getClassHashCode ( superClass ) ) ; } catch ( IOException ex ) { throw IIOPLogger . ROOT_LOGGER . unexpectedException ( ex ) ; } } // Step 2 boolean hasWriteObject = false ; try { Method m ; int mods ; m = cls . getDeclaredMethod ( \"writeObject\" , new Class [ ] { ObjectOutputStream . class } ) ; mods = m . getModifiers ( ) ; if ( ! Modifier . isPrivate ( mods ) && ! Modifier . isStatic ( mods ) ) hasWriteObject = true ; } catch ( NoSuchMethodException ex ) { // ignore } try { dos . writeInt ( hasWriteObject ? 2 : 1 ) ; } catch ( IOException ex ) { throw IIOPLogger . ROOT_LOGGER . unexpectedException ( ex ) ; } // Step 3 Field [ ] fields = cls . getDeclaredFields ( ) ; SortedSet set = new TreeSet ( new FieldComparator ( ) ) ; for ( int i = 0 ; i < fields . length ; ++ i ) { int mods = fields [ i ] . getModifiers ( ) ; if ( ! Modifier . isStatic ( mods ) && ! Modifier . isTransient ( mods ) ) set . add ( fields [ i ] ) ; } Iterator iter = set . iterator ( ) ; try { while ( iter . hasNext ( ) ) { Field f = ( Field ) iter . next ( ) ; dos . writeUTF ( f . getName ( ) ) ; dos . writeUTF ( getSignature ( f . getType ( ) ) ) ; } } catch ( IOException ex ) { throw IIOPLogger . ROOT_LOGGER . unexpectedException ( ex ) ; } // Convert to byte[] try { dos . flush ( ) ; } catch ( IOException ex ) { throw IIOPLogger . ROOT_LOGGER . unexpectedException ( ex ) ; } byte [ ] bytes = baos . toByteArray ( ) ; // Calculate SHA digest MessageDigest digest ; try { digest = MessageDigest . getInstance ( \"SHA\" ) ; } catch ( NoSuchAlgorithmException ex ) { throw IIOPLogger . ROOT_LOGGER . unavailableSHADigest ( ex ) ; } digest . update ( bytes ) ; byte [ ] sha = digest . digest ( ) ; // Calculate hash as per section 10.6.2 long hash = 0 ; for ( int i = 0 ; i < Math . min ( 8 , sha . length ) ; i ++ ) { hash += ( long ) ( sha [ i ] & 255 ) << ( i * 8 ) ; } // Save in cache classHashCodeCache . put ( cls , new Long ( hash ) ) ; return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the signature of a class according to the Java VM specification section 4 . 3 . 2 . [CODESPLIT] private static String getSignature ( Class cls ) { if ( cls . isArray ( ) ) return \"[\" + cls . getComponentType ( ) ; if ( cls . isPrimitive ( ) ) { if ( cls == Byte . TYPE ) return \"B\" ; if ( cls == Character . TYPE ) return \"C\" ; if ( cls == Double . TYPE ) return \"D\" ; if ( cls == Float . TYPE ) return \"F\" ; if ( cls == Integer . TYPE ) return \"I\" ; if ( cls == Long . TYPE ) return \"J\" ; if ( cls == Short . TYPE ) return \"S\" ; if ( cls == Boolean . TYPE ) return \"Z\" ; throw IIOPLogger . ROOT_LOGGER . unknownPrimitiveType ( cls . getName ( ) ) ; } return \"L\" + cls . getName ( ) . replace ( ' ' , ' ' ) + \";\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the signature of a method according to the Java VM specification section 4 . 3 . 3 . [CODESPLIT] private static String getSignature ( Method method ) { StringBuffer b = new StringBuffer ( \"(\" ) ; Class [ ] parameterTypes = method . getParameterTypes ( ) ; for ( int i = 0 ; i < parameterTypes . length ; ++ i ) b . append ( getSignature ( parameterTypes [ i ] ) ) ; b . append ( ' ' ) . append ( getSignature ( method . getReturnType ( ) ) ) ; return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle mappings for primitive types as per section 1 . 3 . 3 . [CODESPLIT] static String primitiveTypeIDLName ( Class type ) { if ( type == Void . TYPE ) return \"void\" ; if ( type == Boolean . TYPE ) return \"boolean\" ; if ( type == Character . TYPE ) return \"wchar\" ; if ( type == Byte . TYPE ) return \"octet\" ; if ( type == Short . TYPE ) return \"short\" ; if ( type == Integer . TYPE ) return \"long\" ; if ( type == Long . TYPE ) return \"long long\" ; if ( type == Float . TYPE ) return \"float\" ; if ( type == Double . TYPE ) return \"double\" ; throw IIOPLogger . ROOT_LOGGER . notAPrimitive ( type . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for standard ra deployment files . Will parse the xml file and attach a configuration discovered during processing . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final VirtualFile deploymentRoot = phaseContext . getDeploymentUnit ( ) . getAttachment ( Attachments . DEPLOYMENT_ROOT ) . getRoot ( ) ; process ( deploymentRoot ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the permission with the given name . [CODESPLIT] public static BatchPermission forName ( final String name ) { Assert . checkNotNullParam ( \"name\" , name ) ; return \"*\" . equals ( name ) ? allPermission : mapping . getItemByString ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the java : comp / UserTransaction service and the java : comp / TransactionSynchronizationRegistry [CODESPLIT] private void bindServices ( DeploymentUnit deploymentUnit , ServiceTarget serviceTarget , ServiceName contextServiceName ) { final ServiceName userTransactionServiceName = contextServiceName . append ( \"UserTransaction\" ) ; final UserTransactionBindingService userTransactionBindingService = new UserTransactionBindingService ( \"UserTransaction\" ) ; serviceTarget . addService ( userTransactionServiceName , userTransactionBindingService ) . addDependency ( UserTransactionAccessControlService . SERVICE_NAME , UserTransactionAccessControlService . class , userTransactionBindingService . getUserTransactionAccessControlServiceInjector ( ) ) . addDependency ( UserTransactionService . INTERNAL_SERVICE_NAME , UserTransaction . class , new ManagedReferenceInjector < UserTransaction > ( userTransactionBindingService . getManagedObjectInjector ( ) ) ) . addDependency ( contextServiceName , ServiceBasedNamingStore . class , userTransactionBindingService . getNamingStoreInjector ( ) ) . install ( ) ; final Map < ServiceName , Set < ServiceName > > jndiComponentDependencies = deploymentUnit . getAttachment ( org . jboss . as . server . deployment . Attachments . COMPONENT_JNDI_DEPENDENCIES ) ; Set < ServiceName > jndiDependencies = jndiComponentDependencies . get ( contextServiceName ) ; if ( jndiDependencies == null ) { jndiComponentDependencies . put ( contextServiceName , jndiDependencies = new HashSet <> ( ) ) ; } jndiDependencies . add ( userTransactionServiceName ) ; final ServiceName transactionSynchronizationRegistryName = contextServiceName . append ( \"TransactionSynchronizationRegistry\" ) ; BinderService transactionSyncBinderService = new BinderService ( \"TransactionSynchronizationRegistry\" ) ; serviceTarget . addService ( transactionSynchronizationRegistryName , transactionSyncBinderService ) . addDependency ( TransactionSynchronizationRegistryService . INTERNAL_SERVICE_NAME , TransactionSynchronizationRegistry . class , new ManagedReferenceInjector < TransactionSynchronizationRegistry > ( transactionSyncBinderService . getManagedObjectInjector ( ) ) ) . addDependency ( contextServiceName , ServiceBasedNamingStore . class , transactionSyncBinderService . getNamingStoreInjector ( ) ) . install ( ) ; jndiDependencies . add ( transactionSynchronizationRegistryName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( final XMLExtendedStreamReader reader , final List < ModelNode > operations ) throws XMLStreamException { final ModelNode ejb3SubsystemAddOperation = new ModelNode ( ) ; ejb3SubsystemAddOperation . get ( OP ) . set ( ADD ) ; ejb3SubsystemAddOperation . get ( OP_ADDR ) . add ( SUBSYSTEM , EJB3Extension . SUBSYSTEM_NAME ) ; operations . add ( ejb3SubsystemAddOperation ) ; // elements final EnumSet < EJB3SubsystemXMLElement > encountered = EnumSet . noneOf ( EJB3SubsystemXMLElement . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != XMLStreamConstants . END_ELEMENT ) { switch ( EJB3SubsystemNamespace . forUri ( reader . getNamespaceURI ( ) ) ) { case EJB3_1_1 : { final EJB3SubsystemXMLElement element = EJB3SubsystemXMLElement . forName ( reader . getLocalName ( ) ) ; if ( ! encountered . add ( element ) ) { throw unexpectedElement ( reader ) ; } switch ( element ) { case MDB : { // read <mdb> this . parseMDB ( reader , operations , ejb3SubsystemAddOperation ) ; break ; } case POOLS : { // read <pools> this . parsePools ( reader , operations ) ; break ; } case SESSION_BEAN : { // read <session-bean> this . parseSessionBean ( reader , operations , ejb3SubsystemAddOperation ) ; break ; } case TIMER_SERVICE : { parseTimerService ( reader , operations ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new InjectionTarget for a given class . If the interceptionSupport flag is set to true the resulting instance will support interception ( support provided by Weld ) . If an InjectionTarget is created for a component where interception support is implemented through component s view ( EJBs managed beans ) the flag must be set to false . [CODESPLIT] public static < T > WeldInjectionTarget < T > createInjectionTarget ( Class < ? > componentClass , Bean < T > bean , BeanManagerImpl beanManager , boolean interceptionSupport ) { final ClassTransformer transformer = beanManager . getServices ( ) . get ( ClassTransformer . class ) ; @ SuppressWarnings ( \"unchecked\" ) final Class < T > clazz = ( Class < T > ) componentClass ; EnhancedAnnotatedType < T > type = transformer . getEnhancedAnnotatedType ( clazz , beanManager . getId ( ) ) ; if ( ! type . getJavaClass ( ) . equals ( componentClass ) ) { /*\n             * Jasper loads a class with multiple classloaders which is not supported by Weld.\n             * If this happens, use a combination of a bean archive identifier and class' classloader hashCode as the BDA ID.\n             * This breaks AnnotatedType serialization but that does not matter as these are non-contextual components.\n             */ final ClassLoader classLoader = WildFlySecurityManager . isChecking ( ) ? doPrivileged ( new GetClassLoaderAction ( componentClass ) ) : componentClass . getClassLoader ( ) ; final String bdaId = beanManager . getId ( ) + classLoader . hashCode ( ) ; type = transformer . getEnhancedAnnotatedType ( clazz , bdaId ) ; } if ( Beans . getBeanConstructor ( type ) == null ) { /*\n             * For example, AsyncListeners may be CDI-incompatible as long as the application never calls javax.servletAsyncContext#createListener(Class)\n             * and only instantiates the listener itself.\n             */ return beanManager . getInjectionTargetFactory ( type ) . createNonProducibleInjectionTarget ( ) ; } WeldInjectionTargetBuilder < T > builder = beanManager . createInjectionTargetBuilder ( type ) ; builder . setBean ( bean ) ; builder . setResourceInjectionEnabled ( false ) ; // because these are all EE components where resource injection is not handled by Weld if ( interceptionSupport ) { return builder . build ( ) ; } else { // suppress interception/decoration because this is a component for which WF provides interception support return builder . setInterceptionEnabled ( false ) . setTargetClassLifecycleCallbacksEnabled ( false ) . setDecorationEnabled ( false ) . build ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void getResourceValue ( final ResolutionContext resolutionContext , final ServiceBuilder < ? > serviceBuilder , final DeploymentPhaseContext phaseContext , final Injector < ManagedReferenceFactory > injector ) { injector . inject ( managedReferenceFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get or create a Transactional entity manager . Only call while a transaction is active in the current thread . [CODESPLIT] private EntityManager getOrCreateTransactionScopedEntityManager ( final EntityManagerFactory emf , final String scopedPuName , final Map properties , final SynchronizationType synchronizationType ) { EntityManager entityManager = TransactionUtil . getTransactionScopedEntityManager ( puScopedName , transactionSynchronizationRegistry ) ; if ( entityManager == null ) { entityManager = createEntityManager ( emf , properties , synchronizationType ) ; if ( ROOT_LOGGER . isDebugEnabled ( ) ) { ROOT_LOGGER . debugf ( \"%s: created entity manager session %s\" , TransactionUtil . getEntityManagerDetails ( entityManager , scopedPuName ) , TransactionUtil . getTransaction ( transactionManager ) . toString ( ) ) ; } TransactionUtil . registerSynchronization ( entityManager , scopedPuName , transactionSynchronizationRegistry , transactionManager ) ; TransactionUtil . putEntityManagerInTransactionRegistry ( scopedPuName , entityManager , transactionSynchronizationRegistry ) ; } else { testForMixedSynchronizationTypes ( emf , entityManager , puScopedName , synchronizationType , properties ) ; if ( ROOT_LOGGER . isDebugEnabled ( ) ) { ROOT_LOGGER . debugf ( \"%s: reuse entity manager session already in tx %s\" , TransactionUtil . getEntityManagerDetails ( entityManager , scopedPuName ) , TransactionUtil . getTransaction ( transactionManager ) . toString ( ) ) ; } } return entityManager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return true if non - tx invocations should defer detaching of entities until entity manager is closed . Note that this is an extension for compatibility with JBoss application server 5 . 0 / 6 . 0 ( see AS7 - 2781 ) [CODESPLIT] @ Override protected boolean deferEntityDetachUntilClose ( ) { if ( deferDetach == null ) deferDetach = ( true == Configuration . deferEntityDetachUntilClose ( emf . getProperties ( ) ) ? Boolean . TRUE : Boolean . FALSE ) ; return deferDetach . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <tt > true< / tt > if this map maps one or more keys to the specified value . Note : This method requires a full internal traversal of the hash table and so is much slower than method <tt > containsKey< / tt > . [CODESPLIT] public boolean containsValue ( Object value ) { if ( value == null ) throw new NullPointerException ( ) ; // See explanation of modCount use above final Segment < K , V > [ ] segments = this . segments ; int [ ] mc = new int [ segments . length ] ; // Try a few times without locking for ( int k = 0 ; k < RETRIES_BEFORE_LOCK ; ++ k ) { int mcsum = 0 ; for ( int i = 0 ; i < segments . length ; ++ i ) { mcsum += mc [ i ] = segments [ i ] . modCount ; if ( segments [ i ] . containsValue ( value ) ) return true ; } boolean cleanSweep = true ; if ( mcsum != 0 ) { for ( int i = 0 ; i < segments . length ; ++ i ) { if ( mc [ i ] != segments [ i ] . modCount ) { cleanSweep = false ; break ; } } } if ( cleanSweep ) return false ; } // Resort to locking all segments for ( int i = 0 ; i < segments . length ; ++ i ) segments [ i ] . lock ( ) ; boolean found = false ; try { for ( int i = 0 ; i < segments . length ; ++ i ) { if ( segments [ i ] . containsValue ( value ) ) { found = true ; break ; } } } finally { for ( int i = 0 ; i < segments . length ; ++ i ) segments [ i ] . unlock ( ) ; } return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the specified key to the specified value in this table . Neither the key nor the value can be null . [CODESPLIT] public V put ( K key , V value ) { if ( value == null ) throw new NullPointerException ( ) ; int hash = hashOf ( key ) ; return segmentFor ( hash ) . put ( key , hash , value , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all of the mappings from the specified map to this one . These mappings replace any mappings that this map had for any of the keys currently in the specified map . [CODESPLIT] public void putAll ( Map < ? extends K , ? extends V > m ) { for ( Map . Entry < ? extends K , ? extends V > e : m . entrySet ( ) ) put ( e . getKey ( ) , e . getValue ( ) ) ; } /**\n     * Removes the key (and its corresponding value) from this map.\n     * This method does nothing if the key is not in the map.\n     *\n     * @param  key the key that needs to be removed\n     * @return the previous value associated with <tt>key</tt>, or\n     *         <tt>null</tt> if there was no mapping for <tt>key</tt>\n     * @throws NullPointerException if the specified key is null\n     */ public V remove ( Object key ) { int hash = hashOf ( key ) ; return segmentFor ( hash ) . remove ( key , hash , null , false ) ; } /**\n     * {@inheritDoc}\n     *\n     * @throws NullPointerException if the specified key is null\n     */ public boolean remove ( Object key , Object value ) { int hash = hashOf ( key ) ; if ( value == null ) return false ; return segmentFor ( hash ) . remove ( key , hash , value , false ) != null ; } /**\n     * {@inheritDoc}\n     *\n     * @throws NullPointerException if any of the arguments are null\n     */ public boolean replace  ( K key , V oldValue , V newValue ) { if ( oldValue == null || newValue == null ) throw new NullPointerException ( ) ; int hash = hashOf ( key ) ; return segmentFor ( hash ) . replace ( key , hash , oldValue , newValue ) ; } /**\n     * {@inheritDoc}\n     *\n     * @return the previous value associated with the specified key,\n     *         or <tt>null</tt> if there was no mapping for the key\n     * @throws NullPointerException if the specified key or value is null\n     */ public V replace  ( K key , V value ) { if ( value == null ) throw new NullPointerException ( ) ; int hash = hashOf ( key ) ; return segmentFor ( hash ) . replace ( key , hash , value ) ; } /**\n     * Removes all of the mappings from this map.\n     */ public void clear  ( ) { for ( int i = 0 ; i < segments . length ; ++ i ) segments [ i ] . clear ( ) ; } /**\n     * Removes any stale entries whose keys have been finalized. Use of this\n     * method is normally not necessary since stale entries are automatically\n     * removed lazily, when blocking operations are required. However, there\n     * are some cases where this operation should be performed eagerly, such\n     * as cleaning up old references to a ClassLoader in a multi-classloader\n     * environment.\n     *\n     * Note: this method will acquire locks, one at a time, across all segments\n     * of this table, so if it is to be used, it should be used sparingly.\n     */ public void purgeStaleEntries  ( ) { for ( int i = 0 ; i < segments . length ; ++ i ) segments [ i ] . removeStale ( ) ; } /**\n     * Returns a {@link Set} view of the keys contained in this map.\n     * The set is backed by the map, so changes to the map are\n     * reflected in the set, and vice-versa.  The set supports element\n     * removal, which removes the corresponding mapping from this map,\n     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,\n     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>\n     * operations.  It does not support the <tt>add</tt> or\n     * <tt>addAll</tt> operations.\n     *\n     * <p>The view's <tt>iterator</tt> is a \"weakly consistent\" iterator\n     * that will never throw {@link java.util.ConcurrentModificationException},\n     * and guarantees to traverse elements as they existed upon\n     * construction of the iterator, and may (but is not guaranteed to)\n     * reflect any modifications subsequent to construction.\n     */ public Set < K > keySet  ( ) { Set < K > ks = keySet ; return ( ks != null ) ? ks : ( keySet = new KeySet ( ) ) ; } /**\n     * Returns a {@link Collection} view of the values contained in this map.\n     * The collection is backed by the map, so changes to the map are\n     * reflected in the collection, and vice-versa.  The collection\n     * supports element removal, which removes the corresponding\n     * mapping from this map, via the <tt>Iterator.remove</tt>,\n     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,\n     * <tt>retainAll</tt>, and <tt>clear</tt> operations.  It does not\n     * support the <tt>add</tt> or <tt>addAll</tt> operations.\n     *\n     * <p>The view's <tt>iterator</tt> is a \"weakly consistent\" iterator\n     * that will never throw {@link java.util.ConcurrentModificationException},\n     * and guarantees to traverse elements as they existed upon\n     * construction of the iterator, and may (but is not guaranteed to)\n     * reflect any modifications subsequent to construction.\n     */ public Collection < V > values  ( ) { Collection < V > vs = values ; return ( vs != null ) ? vs : ( values = new Values ( ) ) ; } /**\n     * Returns a {@link Set} view of the mappings contained in this map.\n     * The set is backed by the map, so changes to the map are\n     * reflected in the set, and vice-versa.  The set supports element\n     * removal, which removes the corresponding mapping from the map,\n     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,\n     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>\n     * operations.  It does not support the <tt>add</tt> or\n     * <tt>addAll</tt> operations.\n     *\n     * <p>The view's <tt>iterator</tt> is a \"weakly consistent\" iterator\n     * that will never throw {@link java.util.ConcurrentModificationException},\n     * and guarantees to traverse elements as they existed upon\n     * construction of the iterator, and may (but is not guaranteed to)\n     * reflect any modifications subsequent to construction.\n     */ public Set < Map . Entry < K , V > > entrySet  ( ) { Set < Map . Entry < K , V > > es = entrySet ; return ( es != null ) ? es : ( entrySet = new EntrySet ( ) ) ; } /**\n     * Returns an enumeration of the keys in this table.\n     *\n     * @return an enumeration of the keys in this table\n     * @see #keySet()\n     */ public Enumeration < K > keys  ( ) { return new KeyIterator ( ) ; } /**\n     * Returns an enumeration of the values in this table.\n     *\n     * @return an enumeration of the values in this table\n     * @see #values()\n     */ public Enumeration < V > elements  ( ) { return new ValueIterator ( ) ; } /* ---------------- Iterator Support -------------- */ abstract class HashIterator { int nextSegmentIndex ; int nextTableIndex ; HashEntry < K , V > [ ] currentTable ; HashEntry < K , V > nextEntry ; HashEntry < K , V > lastReturned ; K currentKey ; // Strong reference to weak key (prevents gc) HashIterator ( ) { nextSegmentIndex = segments . length - 1 ; nextTableIndex = - 1 ; advance ( ) ; } public boolean hasMoreElements ( ) { return hasNext ( ) ; } final void advance ( ) { if ( nextEntry != null && ( nextEntry = nextEntry . next ) != null ) return ; while ( nextTableIndex >= 0 ) { if ( ( nextEntry = currentTable [ nextTableIndex -- ] ) != null ) return ; } while ( nextSegmentIndex >= 0 ) { Segment < K , V > seg = segments [ nextSegmentIndex -- ] ; if ( seg . count != 0 ) { currentTable = seg . table ; for ( int j = currentTable . length - 1 ; j >= 0 ; -- j ) { if ( ( nextEntry = currentTable [ j ] ) != null ) { nextTableIndex = j - 1 ; return ; } } } } } public boolean hasNext ( ) { while ( nextEntry != null ) { if ( nextEntry . key ( ) != null ) return true ; advance ( ) ; } return false ; } HashEntry < K , V > nextEntry ( ) { do { if ( nextEntry == null ) throw new NoSuchElementException ( ) ; lastReturned = nextEntry ; currentKey = lastReturned . key ( ) ; advance ( ) ; } while ( currentKey == null ) ; // Skip GC'd keys return lastReturned ; } public void remove ( ) { if ( lastReturned == null ) throw new IllegalStateException ( ) ; ConcurrentReferenceHashMap . this . remove ( currentKey ) ; lastReturned = null ; } } final class KeyIterator extends HashIterator implements Iterator < K > , Enumeration < K > { public K next ( ) { return super . nextEntry ( ) . key ( ) ; } public K nextElement ( ) { return super . nextEntry ( ) . key ( ) ; } } final class ValueIterator extends HashIterator implements Iterator < V > , Enumeration < V > { public V next ( ) { return super . nextEntry ( ) . value ( ) ; } public V nextElement ( ) { return super . nextEntry ( ) . value ( ) ; } } /*\n      * This class is needed for JDK5 compatibility.\n      */ static class SimpleEntry < K , V > implements Entry < K , V > , java . io . Serializable { private static final long serialVersionUID = - 8499721149061103585L ; private final K key ; private V value ; public SimpleEntry ( K key , V value ) { this . key = key ; this . value = value ; } public SimpleEntry ( Entry < ? extends K , ? extends V > entry ) { this . key = entry . getKey ( ) ; this . value = entry . getValue ( ) ; } public K getKey ( ) { return key ; } public V getValue ( ) { return value ; } public V setValue ( V value ) { V oldValue = this . value ; this . value = value ; return oldValue ; } public boolean equals ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) return false ; Map . Entry < ? , ? > e = ( Map . Entry < ? , ? > ) o ; return eq ( key , e . getKey ( ) ) && eq ( value , e . getValue ( ) ) ; } public int hashCode ( ) { return ( key == null ? 0 : key . hashCode ( ) ) ^ ( value == null ? 0 : value . hashCode ( ) ) ; } public String toString ( ) { return key + \"=\" + value ; } private static boolean eq ( Object o1 , Object o2 ) { return o1 == null ? o2 == null : o1 . equals ( o2 ) ; } } /**\n     * Custom Entry class used by EntryIterator.next(), that relays setValue\n     * changes to the underlying map.\n     */ final class WriteThroughEntry extends SimpleEntry < K , V > { private static final long serialVersionUID = - 7900634345345313646L ; WriteThroughEntry ( K k , V v ) { super ( k , v ) ; } /**\n         * Set our entry's value and write through to the map. The\n         * value to return is somewhat arbitrary here. Since a\n         * WriteThroughEntry does not necessarily track asynchronous\n         * changes, the most recent \"previous\" value could be\n         * different from what we return (or could even have been\n         * removed in which case the put will re-establish). We do not\n         * and cannot guarantee more.\n         */ public V setValue ( V value ) { if ( value == null ) throw new NullPointerException ( ) ; V v = super . setValue ( value ) ; ConcurrentReferenceHashMap . this . put ( getKey ( ) , value ) ; return v ; } } final class EntryIterator extends HashIterator implements Iterator < Entry < K , V > > { public Map . Entry < K , V > next ( ) { HashEntry < K , V > e = super . nextEntry ( ) ; return new WriteThroughEntry ( e . key ( ) , e . value ( ) ) ; } } final class KeySet extends AbstractSet < K > { public Iterator < K > iterator ( ) { return new KeyIterator ( ) ; } public int size ( ) { return ConcurrentReferenceHashMap . this . size ( ) ; } public boolean isEmpty ( ) { return ConcurrentReferenceHashMap . this . isEmpty ( ) ; } public boolean contains ( Object o ) { return ConcurrentReferenceHashMap . this . containsKey ( o ) ; } public boolean remove ( Object o ) { return ConcurrentReferenceHashMap . this . remove ( o ) != null ; } public void clear ( ) { ConcurrentReferenceHashMap . this . clear ( ) ; } } final class Values extends AbstractCollection < V > { public Iterator < V > iterator ( ) { return new ValueIterator ( ) ; } public int size ( ) { return ConcurrentReferenceHashMap . this . size ( ) ; } public boolean isEmpty ( ) { return ConcurrentReferenceHashMap . this . isEmpty ( ) ; } public boolean contains ( Object o ) { return ConcurrentReferenceHashMap . this . containsValue ( o ) ; } public void clear ( ) { ConcurrentReferenceHashMap . this . clear ( ) ; } } final class EntrySet extends AbstractSet < Map . Entry < K , V > > { public Iterator < Map . Entry < K , V > > iterator ( ) { return new EntryIterator ( ) ; } public boolean contains ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) return false ; Map . Entry < ? , ? > e = ( Map . Entry < ? , ? > ) o ; V v = ConcurrentReferenceHashMap . this . get ( e . getKey ( ) ) ; return v != null && v . equals ( e . getValue ( ) ) ; } public boolean remove ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) return false ; Map . Entry < ? , ? > e = ( Map . Entry < ? , ? > ) o ; return ConcurrentReferenceHashMap . this . remove ( e . getKey ( ) , e . getValue ( ) ) ; } public int size ( ) { return ConcurrentReferenceHashMap . this . size ( ) ; } public boolean isEmpty ( ) { return ConcurrentReferenceHashMap . this . isEmpty ( ) ; } public void clear ( ) { ConcurrentReferenceHashMap . this . clear ( ) ; } } /* ---------------- Serialization Support -------------- */ /**\n     * Save the state of the <tt>ConcurrentReferenceHashMap</tt> instance to a\n     * stream (i.e., serialize it).\n     * @param s the stream\n     * @serialData\n     * the key (Object) and value (Object)\n     * for each key-value mapping, followed by a null pair.\n     * The key-value mappings are emitted in no particular order.\n     */ private void writeObject  ( java . io . ObjectOutputStream s ) throws IOException { s . defaultWriteObject ( ) ; for ( int k = 0 ; k < segments . length ; ++ k ) { Segment < K , V > seg = segments [ k ] ; seg . lock ( ) ; try { HashEntry < K , V > [ ] tab = seg . table ; for ( int i = 0 ; i < tab . length ; ++ i ) { for ( HashEntry < K , V > e = tab [ i ] ; e != null ; e = e . next ) { K key = e . key ( ) ; if ( key == null ) // Skip GC'd keys continue ; s . writeObject ( key ) ; s . writeObject ( e . value ( ) ) ; } } } finally { seg . unlock ( ) ; } } s . writeObject ( null ) ; s . writeObject ( null ) ; } /**\n     * Reconstitute the <tt>ConcurrentReferenceHashMap</tt> instance from a\n     * stream (i.e., deserialize it).\n     * @param s the stream\n     */ @ SuppressWarnings ( \"unchecked\" ) private void readObject  ( java . io . ObjectInputStream s ) throws IOException , ClassNotFoundException { s . defaultReadObject ( ) ; // Initialize each segment to be minimally sized, and let grow. for ( int i = 0 ; i < segments . length ; ++ i ) { segments [ i ] . setTable ( new HashEntry [ 1 ] ) ; } // Read the keys and values, and put the mappings in the table for ( ; ; ) { K key = ( K ) s . readObject ( ) ; V value = ( V ) s . readObject ( ) ; if ( key == null ) break ; put ( key , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility for converting camel case based ActiveMQ formats to WildFly standards . [CODESPLIT] static ModelNode convertSecurityRole ( final ModelNode camelCase ) { final ModelNode result = new ModelNode ( ) ; result . setEmptyList ( ) ; if ( camelCase . isDefined ( ) ) { for ( ModelNode role : camelCase . asList ( ) ) { final ModelNode roleNode = result . add ( ) ; for ( Property prop : role . asPropertyList ( ) ) { String key = prop . getName ( ) ; if ( \"createDurableQueue\" . equals ( key ) ) { key = SecurityRoleDefinition . CREATE_DURABLE_QUEUE . getName ( ) ; } else if ( \"deleteDurableQueue\" . equals ( key ) ) { key = SecurityRoleDefinition . DELETE_DURABLE_QUEUE . getName ( ) ; } else if ( \"createNonDurableQueue\" . equals ( key ) ) { key = SecurityRoleDefinition . CREATE_NON_DURABLE_QUEUE . getName ( ) ; } else if ( \"deleteNonDurableQueue\" . equals ( key ) ) { key = SecurityRoleDefinition . DELETE_NON_DURABLE_QUEUE . getName ( ) ; } roleNode . get ( key ) . set ( prop . getValue ( ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consider the uninstalls . <p / > This method is here to be able to override the behavior after installs failed . e . g . perhaps only running uninstalls from the index . <p / > By default we run all uninstalls in the case at least one install failed . [CODESPLIT] protected void considerUninstalls ( List < Joinpoint > uninstalls , int index ) { if ( uninstalls == null ) return ; for ( int j = Math . min ( index , uninstalls . size ( ) - 1 ) ; j >= 0 ; j -- ) { try { uninstalls . get ( j ) . dispatch ( ) ; } catch ( Throwable t ) { PojoLogger . ROOT_LOGGER . ignoreUninstallError ( uninstalls . get ( j ) , t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyze the given class and return the analysis . public static ClassAnalysis getClassAnalysis ( Class cls ) throws RMIIIOPViolationException { if ( cls == null ) throw new IllegalArgumentException ( Cannot analyze NULL class . ) ; if ( cls == java . lang . String . class || cls == java . lang . Object . class || cls == java . lang . Class . class || cls == java . io . Serializable . class || cls == java . io . Externalizable . class || cls == java . rmi . Remote . class ) throw new IllegalArgumentException ( Cannot analyze special class : + cls . getName () ) ; <p / > if ( cls . isPrimitive () ) return PrimitiveAnalysis . getPrimitiveAnalysis ( cls ) ; <p / > <p / > if ( cls . isInterface () && java . rmi . Remote . class . isAssignableFrom ( cls )) return InterfaceAnalysis . getInterfaceAnalysis ( cls ) ; // TODO throw new RuntimeException ( ClassAnalysis . getClassAnalysis () TODO ) ; } [CODESPLIT] private static String javaNameOfClass ( Class cls ) { if ( cls == null ) throw IIOPLogger . ROOT_LOGGER . cannotAnalyzeNullClass ( ) ; String s = cls . getName ( ) ; return s . substring ( s . lastIndexOf ( ' ' ) + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns either the loaded entity or the most recent version of the entity that has been persisted in this transaction . [CODESPLIT] private TimerImpl mostRecentEntityVersion ( final TimerImpl timerImpl ) { try { final int status = ContextTransactionManager . getInstance ( ) . getStatus ( ) ; if ( status == Status . STATUS_UNKNOWN || status == Status . STATUS_NO_TRANSACTION ) { return timerImpl ; } final String key = timerTransactionKey ( timerImpl ) ; TimerImpl existing = ( TimerImpl ) transactionSynchronizationRegistry . getValue ( ) . getResource ( key ) ; return existing != null ? existing : timerImpl ; } catch ( SystemException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the timer map loading from the persistent store if necessary . Should be called under lock [CODESPLIT] private Map < String , TimerImpl > getTimers ( final String timedObjectId , final TimerServiceImpl timerService ) { return loadTimersFromFile ( timedObjectId , timerService ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the directory for a given timed object making sure it exists . [CODESPLIT] private String getDirectory ( String timedObjectId ) { String dirName = directories . get ( timedObjectId ) ; if ( dirName == null ) { dirName = baseDir . getAbsolutePath ( ) + File . separator + timedObjectId . replace ( File . separator , \"-\" ) ; File file = new File ( dirName ) ; if ( ! file . exists ( ) ) { if ( ! file . mkdirs ( ) ) { EJB3_TIMER_LOGGER . failToCreateDirectoryForPersistTimers ( file ) ; } } directories . put ( timedObjectId , dirName ) ; } return dirName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for JbossService configuration . Will install a { @code JBossService } for each configured service . [CODESPLIT] @ Override public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final JBossServiceXmlDescriptor serviceXmlDescriptor = deploymentUnit . getAttachment ( JBossServiceXmlDescriptor . ATTACHMENT_KEY ) ; if ( serviceXmlDescriptor == null ) { // Skip deployments without a service xml descriptor return ; } // assert module final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; if ( module == null ) throw SarLogger . ROOT_LOGGER . failedToGetAttachment ( \"module\" , deploymentUnit ) ; // assert reflection index final DeploymentReflectionIndex reflectionIndex = deploymentUnit . getAttachment ( Attachments . REFLECTION_INDEX ) ; if ( reflectionIndex == null ) throw SarLogger . ROOT_LOGGER . failedToGetAttachment ( \"reflection index\" , deploymentUnit ) ; // install services final ClassLoader classLoader = module . getClassLoader ( ) ; final List < JBossServiceConfig > serviceConfigs = serviceXmlDescriptor . getServiceConfigs ( ) ; final ServiceTarget target = phaseContext . getServiceTarget ( ) ; final Map < String , ServiceComponentInstantiator > serviceComponents = deploymentUnit . getAttachment ( ServiceAttachments . SERVICE_COMPONENT_INSTANTIATORS ) ; for ( final JBossServiceConfig serviceConfig : serviceConfigs ) { addServices ( target , serviceConfig , classLoader , reflectionIndex , serviceComponents != null ? serviceComponents . get ( serviceConfig . getName ( ) ) : null , phaseContext ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates and returns a { @link Sanitizer } instance that only operates on files that end with a { @code . properties } suffix . [CODESPLIT] public static Sanitizer pattern ( String pattern , String replacement ) throws Exception { return new PatternSanitizer ( pattern , replacement , Filters . suffix ( \".properties\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void registerAttributes ( ManagementResourceRegistration resourceRegistration ) { ReloadRequiredWriteAttributeHandler reloadWrtiteHandler = new ReloadRequiredWriteAttributeHandler ( JNDI_NAME , CM_TABLE_NAME , CM_TABLE_BATCH_SIZE , CM_TABLE_IMMEDIATE_CLEANUP ) ; resourceRegistration . registerReadWriteAttribute ( CM_TABLE_NAME , null , reloadWrtiteHandler ) ; resourceRegistration . registerReadWriteAttribute ( CM_TABLE_BATCH_SIZE , null , reloadWrtiteHandler ) ; resourceRegistration . registerReadWriteAttribute ( CM_TABLE_IMMEDIATE_CLEANUP , null , reloadWrtiteHandler ) ; //This comes from the address resourceRegistration . registerReadOnlyAttribute ( JNDI_NAME , ReadResourceNameOperationStepHandler . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the passed <code > exceptionClass< / code > is an application exception . Else returns false . [CODESPLIT] private boolean isApplicationException ( final EJBComponent ejbComponent , final Class < ? > exceptionClass , final Method invokedMethod ) { return ejbComponent . getApplicationException ( exceptionClass , invokedMethod ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a listener to the coordinator with a given target name and event scope . This information is used when an event is fired to determine whether or not to fire this listener . [CODESPLIT] synchronized void addListener ( final String target , final int scope , final NamingListener namingListener ) { final TargetScope targetScope = new TargetScope ( target , scope ) ; // Do we have a holder for this listener ListenerHolder holder = holdersByListener . get ( namingListener ) ; if ( holder == null ) { holder = new ListenerHolder ( namingListener , targetScope ) ; final Map < NamingListener , ListenerHolder > byListenerCopy = new FastCopyHashMap < NamingListener , ListenerHolder > ( holdersByListener ) ; byListenerCopy . put ( namingListener , holder ) ; holdersByListener = byListenerCopy ; } else { holder . addTarget ( targetScope ) ; } List < ListenerHolder > holdersForTarget = holdersByTarget . get ( targetScope ) ; if ( holdersForTarget == null ) { holdersForTarget = new CopyOnWriteArrayList < ListenerHolder > ( ) ; final Map < TargetScope , List < ListenerHolder > > byTargetCopy = new FastCopyHashMap < TargetScope , List < ListenerHolder > > ( holdersByTarget ) ; byTargetCopy . put ( targetScope , holdersForTarget ) ; holdersByTarget = byTargetCopy ; } holdersForTarget . add ( holder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a listener . Will remove it from all target mappings . Once this method returns the listener will no longer receive any events . [CODESPLIT] synchronized void removeListener ( final NamingListener namingListener ) { // Do we have a holder for this listener final ListenerHolder holder = holdersByListener . get ( namingListener ) ; if ( holder == null ) { return ; } final Map < NamingListener , ListenerHolder > byListenerCopy = new FastCopyHashMap < NamingListener , ListenerHolder > ( holdersByListener ) ; byListenerCopy . remove ( namingListener ) ; holdersByListener = byListenerCopy ; final Map < TargetScope , List < ListenerHolder > > byTargetCopy = new FastCopyHashMap < TargetScope , List < ListenerHolder > > ( holdersByTarget ) ; for ( TargetScope targetScope : holder . targets ) { final List < ListenerHolder > holders = holdersByTarget . get ( targetScope ) ; holders . remove ( holder ) ; if ( holders . isEmpty ( ) ) { byTargetCopy . remove ( targetScope ) ; } } holdersByTarget = byTargetCopy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire a naming event . An event will be created with the provided information and sent to each listener that matches the target and scope information . [CODESPLIT] void fireEvent ( final EventContext context , final Name name , final Binding existingBinding , final Binding newBinding , int type , final String changeInfo , final Integer ... scopes ) { final String target = name . toString ( ) ; final Set < Integer > scopeSet = new HashSet < Integer > ( Arrays . asList ( scopes ) ) ; final NamingEvent event = new NamingEvent ( context , type , newBinding , existingBinding , changeInfo ) ; final Set < ListenerHolder > holdersToFire = new HashSet < ListenerHolder > ( ) ; // Check for OBJECT_SCOPE based listeners if ( scopeSet . contains ( EventContext . OBJECT_SCOPE ) ) { final TargetScope targetScope = new TargetScope ( target , EventContext . OBJECT_SCOPE ) ; final List < ListenerHolder > holders = holdersByTarget . get ( targetScope ) ; if ( holders != null ) { for ( ListenerHolder holder : holders ) { holdersToFire . add ( holder ) ; } } } // Check for ONELEVEL_SCOPE based listeners if ( scopeSet . contains ( EventContext . ONELEVEL_SCOPE ) && ! name . isEmpty ( ) ) { final TargetScope targetScope = new TargetScope ( name . getPrefix ( name . size ( ) - 1 ) . toString ( ) , EventContext . ONELEVEL_SCOPE ) ; final List < ListenerHolder > holders = holdersByTarget . get ( targetScope ) ; if ( holders != null ) { for ( ListenerHolder holder : holders ) { holdersToFire . add ( holder ) ; } } } // Check for SUBTREE_SCOPE based listeners if ( scopeSet . contains ( EventContext . SUBTREE_SCOPE ) && ! name . isEmpty ( ) ) { for ( int i = 1 ; i < name . size ( ) ; i ++ ) { final Name parentName = name . getPrefix ( i ) ; final TargetScope targetScope = new TargetScope ( parentName . toString ( ) , EventContext . SUBTREE_SCOPE ) ; final List < ListenerHolder > holders = holdersByTarget . get ( targetScope ) ; if ( holders != null ) { for ( ListenerHolder holder : holders ) { holdersToFire . add ( holder ) ; } } } } executor . execute ( new FireEventTask ( holdersToFire , event ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a consumer that closes its input . [CODESPLIT] public static < T extends AutoCloseable > Consumer < T > close ( ) { return value -> { try { value . close ( ) ; } catch ( Throwable e ) { ClusteringLogger . ROOT_LOGGER . failedToClose ( e , value ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Subject createSubject ( ) { // If a authenticationContext was defined on the subsystem use that context, otherwise use capture the current // configuration. final Subject subject = this . createSubject ( getAuthenticationContext ( ) ) ; if ( ROOT_LOGGER . isTraceEnabled ( ) ) { ROOT_LOGGER . subject ( subject , Integer . toHexString ( System . identityHashCode ( subject ) ) ) ; } return subject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Subject createSubject ( final String authenticationContextName ) { AuthenticationContext context ; if ( authenticationContextName != null && ! authenticationContextName . isEmpty ( ) ) { final ServiceContainer container = this . currentServiceContainer ( ) ; final ServiceName authContextServiceName = AUTHENTICATION_CONTEXT_RUNTIME_CAPABILITY . getCapabilityServiceName ( authenticationContextName ) ; context = ( AuthenticationContext ) container . getRequiredService ( authContextServiceName ) . getValue ( ) ; } else { context = getAuthenticationContext ( ) ; } final Subject subject = this . createSubject ( context ) ; if ( ROOT_LOGGER . isTraceEnabled ( ) ) { ROOT_LOGGER . subject ( subject , Integer . toHexString ( System . identityHashCode ( subject ) ) ) ; } return subject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Subject } with the principal and password credential obtained from the authentication configuration that matches the target { @link URI } . [CODESPLIT] private Subject createSubject ( final AuthenticationContext authenticationContext ) { final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT . getAuthenticationConfiguration ( this . targetURI , authenticationContext ) ; final CallbackHandler handler = AUTH_CONFIG_CLIENT . getCallbackHandler ( configuration ) ; final NameCallback nameCallback = new NameCallback ( \"Username: \" ) ; final PasswordCallback passwordCallback = new PasswordCallback ( \"Password: \" , false ) ; final CredentialCallback credentialCallback = new CredentialCallback ( GSSKerberosCredential . class ) ; try { handler . handle ( new Callback [ ] { nameCallback , passwordCallback , credentialCallback } ) ; Subject subject = new Subject ( ) ; // if a GSSKerberosCredential was found, add the enclosed GSSCredential and KerberosTicket to the private set in the Subject. if ( credentialCallback . getCredential ( ) != null ) { GSSKerberosCredential kerberosCredential = GSSKerberosCredential . class . cast ( credentialCallback . getCredential ( ) ) ; this . addPrivateCredential ( subject , kerberosCredential . getKerberosTicket ( ) ) ; this . addPrivateCredential ( subject , kerberosCredential . getGssCredential ( ) ) ; // use the GSSName to build a kerberos principal and set it in the Subject. GSSName gssName = kerberosCredential . getGssCredential ( ) . getName ( ) ; subject . getPrincipals ( ) . add ( new KerberosPrincipal ( gssName . toString ( ) ) ) ; } // use the name from the callback, if available, to build a principal and set it in the Subject. if ( nameCallback . getName ( ) != null ) { subject . getPrincipals ( ) . add ( new NamePrincipal ( nameCallback . getName ( ) ) ) ; } // use the password from the callback, if available, to build a credential and set it as a private credential in the Subject. if ( passwordCallback . getPassword ( ) != null ) { this . addPrivateCredential ( subject , new PasswordCredential ( nameCallback . getName ( ) , passwordCallback . getPassword ( ) ) ) ; } return subject ; } catch ( Exception e ) { throw new SecurityException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a reference to the current { @link ServiceContainer } . [CODESPLIT] private ServiceContainer currentServiceContainer ( ) { if ( WildFlySecurityManager . isChecking ( ) ) { return AccessController . doPrivileged ( CurrentServiceContainer . GET_ACTION ) ; } return CurrentServiceContainer . getServiceContainer ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the specified credential to the subject s private credentials set . [CODESPLIT] private void addPrivateCredential ( final Subject subject , final Object credential ) { if ( ! WildFlySecurityManager . isChecking ( ) ) { subject . getPrivateCredentials ( ) . add ( credential ) ; } else { AccessController . doPrivileged ( ( PrivilegedAction < Void > ) ( ) -> { subject . getPrivateCredentials ( ) . add ( credential ) ; return null ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- // [CODESPLIT] protected static AgroalConnectionFactoryConfigurationSupplier connectionFactoryConfiguration ( OperationContext context , ModelNode model ) throws OperationFailedException { AgroalConnectionFactoryConfigurationSupplier configuration = new AgroalConnectionFactoryConfigurationSupplier ( ) ; if ( AbstractDataSourceDefinition . URL_ATTRIBUTE . resolveModelAttribute ( context , model ) . isDefined ( ) ) { configuration . jdbcUrl ( AbstractDataSourceDefinition . URL_ATTRIBUTE . resolveModelAttribute ( context , model ) . asString ( ) ) ; } if ( AbstractDataSourceDefinition . NEW_CONNECTION_SQL_ATTRIBUTE . resolveModelAttribute ( context , model ) . isDefined ( ) ) { configuration . initialSql ( AbstractDataSourceDefinition . NEW_CONNECTION_SQL_ATTRIBUTE . resolveModelAttribute ( context , model ) . asString ( ) ) ; } if ( AbstractDataSourceDefinition . TRANSACTION_ISOLATION_ATTRIBUTE . resolveModelAttribute ( context , model ) . isDefined ( ) ) { configuration . jdbcTransactionIsolation ( TransactionIsolation . valueOf ( AbstractDataSourceDefinition . TRANSACTION_ISOLATION_ATTRIBUTE . resolveModelAttribute ( context , model ) . asString ( ) ) ) ; } if ( AbstractDataSourceDefinition . CONNECTION_PROPERTIES_ATTRIBUTE . resolveModelAttribute ( context , model ) . isDefined ( ) ) { for ( Property jdbcProperty : AbstractDataSourceDefinition . CONNECTION_PROPERTIES_ATTRIBUTE . resolveModelAttribute ( context , model ) . asPropertyList ( ) ) { configuration . jdbcProperty ( jdbcProperty . getName ( ) , jdbcProperty . getValue ( ) . asString ( ) ) ; } } if ( AbstractDataSourceDefinition . USERNAME_ATTRIBUTE . resolveModelAttribute ( context , model ) . isDefined ( ) ) { configuration . principal ( new NamePrincipal ( AbstractDataSourceDefinition . USERNAME_ATTRIBUTE . resolveModelAttribute ( context , model ) . asString ( ) ) ) ; } if ( AbstractDataSourceDefinition . PASSWORD_ATTRIBUTE . resolveModelAttribute ( context , model ) . isDefined ( ) ) { configuration . credential ( new SimplePassword ( AbstractDataSourceDefinition . PASSWORD_ATTRIBUTE . resolveModelAttribute ( context , model ) . asString ( ) ) ) ; } return configuration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- // [CODESPLIT] private static AgroalDataSource getDataSource ( OperationContext context ) throws OperationFailedException { ServiceRegistry registry = context . getServiceRegistry ( false ) ; String dataSourceName = context . getCurrentAddressValue ( ) ; switch ( context . getCurrentAddress ( ) . getLastElement ( ) . getKey ( ) ) { case DataSourceOperations . DATASOURCE_SERVICE_NAME : ServiceController < ? > controller = registry . getRequiredService ( AbstractDataSourceDefinition . DATA_SOURCE_CAPABILITY . getCapabilityServiceName ( dataSourceName ) ) ; return ( ( AgroalDataSource ) controller . getValue ( ) ) ; case XADataSourceOperations . XADATASOURCE_SERVICE_NAME : ServiceController < ? > xaController = registry . getRequiredService ( AbstractDataSourceDefinition . DATA_SOURCE_CAPABILITY . getCapabilityServiceName ( dataSourceName ) ) ; return ( ( AgroalDataSource ) xaController . getValue ( ) ) ; default : throw AgroalLogger . SERVICE_LOGGER . unknownDatasourceServiceType ( context . getCurrentAddress ( ) . getLastElement ( ) . getKey ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object processInvocation ( final InterceptorContext context ) throws Exception { try { return context . proceed ( ) ; } finally { final ManagedReference managedReference = ( ManagedReference ) context . getPrivateData ( ComponentInstance . class ) . getInstanceData ( contextKey ) ; if ( managedReference != null ) { managedReference . release ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an object factory . If the object parameter is a reference it will attempt to create an { @link javax . naming . spi . ObjectFactory } from the reference . If the parameter is not a reference or the reference does not create an { @link javax . naming . spi . ObjectFactory } it will return { @code this } as the { @link javax . naming . spi . ObjectFactory } to use . [CODESPLIT] public ObjectFactory createObjectFactory ( final Object obj , Hashtable < ? , ? > environment ) throws NamingException { try { if ( obj instanceof Reference ) { return factoryFromReference ( ( Reference ) obj , environment ) ; } } catch ( Throwable ignored ) { } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an object instance . [CODESPLIT] public Object getObjectInstance ( final Object ref , final Name name , final Context nameCtx , final Hashtable < ? , ? > environment ) throws Exception { final ClassLoader classLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; if ( classLoader == null ) { return ref ; } final String factoriesProp = ( String ) environment . get ( Context . OBJECT_FACTORIES ) ; if ( factoriesProp != null ) { final String [ ] classes = factoriesProp . split ( \":\" ) ; for ( String className : classes ) { try { final Class < ? > factoryClass = classLoader . loadClass ( className ) ; final ObjectFactory objectFactory = ObjectFactory . class . cast ( factoryClass . newInstance ( ) ) ; final Object result = objectFactory . getObjectInstance ( ref , name , nameCtx , environment ) ; if ( result != null ) { return result ; } } catch ( Throwable ignored ) { } } } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls to Hibernate ORM 5 . 3 getFlushMode () will not be changed as the desc will not match ( desc == () Ljavax . persistence . FlushModeType ; ) [CODESPLIT] @ Override public void visitMethodInsn ( int opcode , String owner , String name , String desc , boolean itf ) { if ( rewriteSessionImplementor && hasSessionImplementor ( desc ) && ( opcode == Opcodes . INVOKESPECIAL || opcode == Opcodes . INVOKEVIRTUAL ) ) { // if we have a user type calling a method from org.hibernate, we rewrite it to use SharedSessionContractImplementor logger . debugf ( \"Deprecated Hibernate51CompatibilityTransformer transformed application classes in '%s', \" + \"class '%s' is calling method %s.%s, which must be changed to use SharedSessionContractImplementor as parameter.\" , moduleName , className , owner , name ) ; mv . visitMethodInsn ( opcode , owner , name , replaceSessionImplementor ( desc ) , itf ) ; transformedState . setClassTransformed ( true ) ; } else if ( opcode == Opcodes . INVOKEINTERFACE && ( owner . equals ( \"org/hibernate/Session\" ) || owner . equals ( \"org/hibernate/BasicQueryContract\" ) ) && name . equals ( \"getFlushMode\" ) && desc . equals ( \"()Lorg/hibernate/FlushMode;\" ) ) { logger . debugf ( \"Deprecated Hibernate51CompatibilityTransformer transformed application classes in '%s', \" + \"class '%s' is calling %s.getFlushMode, which must be changed to call getHibernateFlushMode().\" , moduleName , className , owner ) ; name = \"getHibernateFlushMode\" ; mv . visitMethodInsn ( opcode , owner , name , desc , itf ) ; transformedState . setClassTransformed ( true ) ; } else if ( opcode == Opcodes . INVOKEINTERFACE && owner . equals ( \"org/hibernate/Query\" ) && name . equals ( \"getFirstResult\" ) && desc . equals ( \"()Ljava/lang/Integer;\" ) ) { logger . debugf ( \"Deprecated Hibernate51CompatibilityTransformer transformed application classes in '%s', \" + \"class '%s', is calling org.hibernate.Query.getFirstResult, which must be changed to call getHibernateFirstResult() \" + \"so null can be returned when the value is uninitialized. Please note that if a negative value was set using \" + \"org.hibernate.Query.setFirstResult, then getHibernateFirstResult() will return 0.\" , moduleName , className ) ; name = \"getHibernateFirstResult\" ; mv . visitMethodInsn ( opcode , owner , name , desc , itf ) ; transformedState . setClassTransformed ( true ) ; } else if ( opcode == Opcodes . INVOKEINTERFACE && owner . equals ( \"org/hibernate/Query\" ) && name . equals ( \"getMaxResults\" ) && desc . equals ( \"()Ljava/lang/Integer;\" ) ) { logger . debugf ( \"Deprecated Hibernate51CompatibilityTransformer transformed application classes in '%s', \" + \"class '%s', is calling org.hibernate.Query.getMaxResults, which must be changed to call getHibernateMaxResults() \" + \"so that null will be returned when the value is uninitialized or ORM 5.1 org.hibernate.Query#setMaxResults was \" + \"used to set a value <= 0\" , moduleName , className ) ; name = \"getHibernateMaxResults\" ; mv . visitMethodInsn ( opcode , owner , name , desc , itf ) ; transformedState . setClassTransformed ( true ) ; } else if ( ! disableAmbiguousChanges && opcode == Opcodes . INVOKEINTERFACE && owner . equals ( \"org/hibernate/Query\" ) && name . equals ( \"setFirstResult\" ) && desc . equals ( \"(I)Lorg/hibernate/Query;\" ) ) { logger . debugf ( \"Deprecated Hibernate51CompatibilityTransformer transformed application classes in '%s', \" + \"class '%s', is calling org.hibernate.Query.setFirstResult, which must be changed to call setHibernateFirstResult() \" + \"so setting a value < 0 results in pagination starting with the 0th row as was done in Hibernate ORM 5.1 \" + \"(instead of throwing IllegalArgumentException as specified by JPA).\" , moduleName , className ) ; name = \"setHibernateFirstResult\" ; mv . visitMethodInsn ( opcode , owner , name , desc , itf ) ; transformedState . setClassTransformed ( true ) ; } else if ( ! disableAmbiguousChanges && opcode == Opcodes . INVOKEINTERFACE && owner . equals ( \"org/hibernate/Query\" ) && name . equals ( \"setMaxResults\" ) && desc . equals ( \"(I)Lorg/hibernate/Query;\" ) ) { logger . debugf ( \"Deprecated Hibernate51CompatibilityTransformer transformed application classes in '%s', \" + \"class '%s', is calling org.hibernate.Query.setMaxResults, which must be changed to call setHibernateMaxResults() \" + \"so that values <= 0 are treated the same as uninitialized.  Review Hibernate ORM migration doc \" , moduleName , className ) ; name = \"setHibernateMaxResults\" ; mv . visitMethodInsn ( opcode , owner , name , desc , itf ) ; transformedState . setClassTransformed ( true ) ; } else { mv . visitMethodInsn ( opcode , owner , name , desc , itf ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up the transaction management interceptor for all methods of the passed view . [CODESPLIT] protected static void addTxManagementInterceptorForView ( ViewDescription view ) { // add a Tx configurator view . getConfigurators ( ) . add ( new ViewConfigurator ( ) { @ Override public void configure ( DeploymentPhaseContext context , ComponentConfiguration componentConfiguration , ViewDescription description , ViewConfiguration configuration ) throws DeploymentUnitProcessingException { EJBComponentDescription ejbComponentDescription = ( EJBComponentDescription ) componentConfiguration . getComponentDescription ( ) ; // Add CMT interceptor factory if ( TransactionManagementType . CONTAINER . equals ( ejbComponentDescription . getTransactionManagementType ( ) ) ) { configuration . addViewInterceptor ( CMTTxInterceptor . FACTORY , InterceptorOrder . View . CMT_TRANSACTION_INTERCEPTOR ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "First checks if <code > name< / code > is a primitive type . If yes then returns the corresponding { @link Class } for that primitive . If it s not a primitive then the { @link Class#forName ( String boolean ClassLoader ) } method is invoked passing it the <code > name< / code > false and the <code > cl< / code > classloader [CODESPLIT] public static Class < ? > loadClass ( String name , ClassLoader cl ) throws ClassNotFoundException { /*\n        * Handle Primitives\n        */ if ( name . equals ( void . class . getName ( ) ) ) { return void . class ; } if ( name . equals ( byte . class . getName ( ) ) ) { return byte . class ; } if ( name . equals ( short . class . getName ( ) ) ) { return short . class ; } if ( name . equals ( int . class . getName ( ) ) ) { return int . class ; } if ( name . equals ( long . class . getName ( ) ) ) { return long . class ; } if ( name . equals ( char . class . getName ( ) ) ) { return char . class ; } if ( name . equals ( boolean . class . getName ( ) ) ) { return boolean . class ; } if ( name . equals ( float . class . getName ( ) ) ) { return float . class ; } if ( name . equals ( double . class . getName ( ) ) ) { return double . class ; } // Now that we know its not a primitive, lets just allow // the passed classloader to handle the request. // Note that we are intentionally using Class.forName(name,boolean,cl) // to handle issues with loading array types in Java 6 http://bugs.sun.com/view_bug.do?bug_id=6434149 return Class . forName ( name , false , cl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transform a Hibernate HQL query into something that can be displayed / used for management operations [CODESPLIT] private String displayable ( String query ) { if ( query == null || query . length ( ) == 0 ) { return query ; } StringBuilder buff = new StringBuilder ( query ) ; // handle two character transforms first subst ( buff , SQL_NE , NOT_EQUAL__ ) ; subst ( buff , NE_BANG , BANG_NOT_EQUAL__ ) ; subst ( buff , NE_HAT , HAT_NOT_EQUAL__ ) ; subst ( buff , LE , LESS_THAN_EQUAL__ ) ; subst ( buff , GE , GREATER_THAN_EQUAL__ ) ; subst ( buff , CONCAT , CONCAT__ ) ; subst ( buff , LT , LESS_THAN__ ) ; subst ( buff , EQ , EQUAL__ ) ; subst ( buff , GT , GREATER__ ) ; subst ( buff , OPEN , LEFT_PAREN__ ) ; subst ( buff , CLOSE , RIGHT_PAREN__ ) ; subst ( buff , OPEN_BRACKET , LEFT_BRACKET__ ) ; subst ( buff , CLOSE_BRACKET , RIGHT_BRACKET__ ) ; subst ( buff , PLUS , PLUS__ ) ; subst ( buff , MINUS , MINUS__ ) ; subst ( buff , STAR , STAR__ ) ; subst ( buff , DIV , DIVIDE__ ) ; subst ( buff , MOD , MODULUS__ ) ; subst ( buff , COLON , COLON__ ) ; subst ( buff , PARAM , PARAM__ ) ; subst ( buff , COMMA , COMMA__ ) ; subst ( buff , SPACE , SPACE__ ) ; subst ( buff , TAB , TAB__ ) ; subst ( buff , NEWLINE , NEWLINE__ ) ; subst ( buff , LINEFEED , LINEFEED__ ) ; subst ( buff , QUOTE , QUOTE__ ) ; subst ( buff , DQUOTE , DQUOTE__ ) ; subst ( buff , TICK , TICK__ ) ; subst ( buff , OPEN_BRACE , OPEN_BRACE__ ) ; subst ( buff , CLOSE_BRACE , CLOSE_BRACE__ ) ; subst ( buff , HAT , HAT__ ) ; subst ( buff , AMPERSAND , AMPERSAND__ ) ; return buff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Substitute sub - strings inside of a string . [CODESPLIT] private static void subst ( final StringBuilder stringBuilder , final String from , final String to ) { int begin = 0 , end = 0 ; while ( ( end = stringBuilder . indexOf ( from , end ) ) != - 1 ) { stringBuilder . delete ( end , end + from . length ( ) ) ; stringBuilder . insert ( end , to ) ; // update positions begin = end + to . length ( ) ; end = begin ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void transformResource ( ResourceTransformationContext context , PathAddress address , Resource resource ) throws OperationFailedException { context . addTransformedResourceFromRoot ( this . addressTransformer . transform ( address ) , resource ) . processChildren ( resource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the actual work of stopping the service . Should be called by { [CODESPLIT] protected synchronized void stopService ( ) { if ( deploymentMD != null ) { if ( deploymentMD . getResourceAdapterKey ( ) != null ) { try { raRepository . getValue ( ) . unregisterResourceAdapter ( deploymentMD . getResourceAdapterKey ( ) ) ; } catch ( org . jboss . jca . core . spi . rar . NotFoundException nfe ) { ConnectorLogger . ROOT_LOGGER . exceptionDuringUnregistering ( nfe ) ; } } if ( deploymentMD . getResourceAdapter ( ) != null ) { deploymentMD . getResourceAdapter ( ) . stop ( ) ; if ( BootstrapContextCoordinator . getInstance ( ) != null && deploymentMD . getBootstrapContextIdentifier ( ) != null ) { BootstrapContextCoordinator . getInstance ( ) . removeBootstrapContext ( deploymentMD . getBootstrapContextIdentifier ( ) ) ; } } if ( deploymentMD . getDataSources ( ) != null && managementRepositoryValue . getValue ( ) != null ) { for ( org . jboss . jca . core . api . management . DataSource mgtDs : deploymentMD . getDataSources ( ) ) { managementRepositoryValue . getValue ( ) . getDataSources ( ) . remove ( mgtDs ) ; } } if ( deploymentMD . getConnectionManagers ( ) != null ) { for ( ConnectionManager cm : deploymentMD . getConnectionManagers ( ) ) { cm . shutdown ( ) ; } } } sqlDataSource = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The XmlDataImporter requires a connector to connect to the artemis broker . [CODESPLIT] private TransportConfiguration createInVMTransportConfiguration ( OperationContext context ) throws OperationFailedException { final Resource serverResource = context . readResource ( EMPTY_ADDRESS , false ) ; Set < Resource . ResourceEntry > invmConnectors = serverResource . getChildren ( CommonAttributes . IN_VM_CONNECTOR ) ; if ( invmConnectors . isEmpty ( ) ) { throw MessagingLogger . ROOT_LOGGER . noInVMConnector ( ) ; } Resource . ResourceEntry connectorEntry = invmConnectors . iterator ( ) . next ( ) ; Resource connectorResource = context . readResource ( PathAddress . pathAddress ( connectorEntry . getPathElement ( ) ) , false ) ; ModelNode model = connectorResource . getModel ( ) ; Map < String , Object > params = new HashMap <> ( CommonAttributes . PARAMS . unwrap ( context , model ) ) ; params . put ( InVMTransportDefinition . SERVER_ID . getName ( ) , InVMTransportDefinition . SERVER_ID . resolveModelAttribute ( context , model ) . asInt ( ) ) ; TransportConfiguration transportConfiguration = new TransportConfiguration ( InVMConnectorFactory . class . getName ( ) , params ) ; return transportConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds ear prefix to configured adapter name if it is specified in relative form [CODESPLIT] private String addEarPrefixIfRelativeName ( final String configuredName , final DeploymentUnit deploymentUnit , final Class < ? > componentClass ) throws DeploymentUnitProcessingException { if ( ! configuredName . startsWith ( \"#\" ) ) { return configuredName ; } final DeploymentUnit parent = deploymentUnit . getParent ( ) ; if ( parent == null ) { throw EjbLogger . ROOT_LOGGER . relativeResourceAdapterNameInStandaloneModule ( deploymentUnit . getName ( ) , componentClass . getName ( ) , configuredName ) ; } return new StringBuilder ( ) . append ( parent . getName ( ) ) . append ( configuredName ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the parent of the given deployment unit if such a parent exists . If the given deployment unit is the parent deployment unit it is returned . [CODESPLIT] public static DeploymentUnit getRootDeploymentUnit ( DeploymentUnit deploymentUnit ) { if ( deploymentUnit . getParent ( ) == null ) { return deploymentUnit ; } return deploymentUnit . getParent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the service name for this view . [CODESPLIT] public ServiceName getServiceName ( ) { //TODO: need to set viewNameParts somewhere if ( ! viewNameParts . isEmpty ( ) ) { return componentDescription . getServiceName ( ) . append ( \"VIEW\" ) . append ( viewNameParts . toArray ( new String [ viewNameParts . size ( ) ] ) ) ; } else { return componentDescription . getServiceName ( ) . append ( \"VIEW\" ) . append ( viewClassName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates view configuration . Allows for extensibility in EE sub components . [CODESPLIT] public ViewConfiguration createViewConfiguration ( final Class < ? > viewClass , final ComponentConfiguration componentConfiguration , final ProxyFactory < ? > proxyFactory ) { return new ViewConfiguration ( viewClass , componentConfiguration , getServiceName ( ) , proxyFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the injection source [CODESPLIT] protected InjectionSource createInjectionSource ( final ServiceName serviceName , Value < ClassLoader > viewClassLoader , boolean appclient ) { return new ViewBindingInjectionSource ( serviceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation --------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . SequenceDefHelper . narrow ( servantToReference ( new SequenceDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the view interceptors for a method . These interceptors are run sequentially on the server side of an invocation . The interceptor factories are used every time a new view instance is constructed called with a new factory context each time . The factory may return the same interceptor instance or a new interceptor instance as appropriate . [CODESPLIT] public List < InterceptorFactory > getViewInterceptors ( Method method ) { OrderedItemContainer < InterceptorFactory > container = viewInterceptors . get ( method ) ; if ( container == null ) { return Collections . emptyList ( ) ; } return container . getSortedItems ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an interceptor factory to all methods of a view [CODESPLIT] public void addViewInterceptor ( InterceptorFactory interceptorFactory , int priority ) { for ( Method method : proxyFactory . getCachedMethods ( ) ) { addViewInterceptor ( method , interceptorFactory , priority ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a view interceptor to the given method [CODESPLIT] public void addViewInterceptor ( Method method , InterceptorFactory interceptorFactory , int priority ) { OrderedItemContainer < InterceptorFactory > container = viewInterceptors . get ( method ) ; if ( container == null ) { viewInterceptors . put ( method , container = new OrderedItemContainer < InterceptorFactory > ( ) ) ; } container . add ( interceptorFactory , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the client interceptors for a method . These interceptors are run sequentially on the client side of an invocation . The interceptor factories are used every time a new client proxy instance is constructed called with a new factory context each time . The factory may return the same interceptor instance or a new interceptor instance as appropriate . [CODESPLIT] public List < InterceptorFactory > getClientInterceptors ( Method method ) { OrderedItemContainer < InterceptorFactory > container = clientInterceptors . get ( method ) ; if ( container == null ) { return Collections . emptyList ( ) ; } return container . getSortedItems ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a client interceptor factory to all methods of a view [CODESPLIT] public void addClientInterceptor ( InterceptorFactory interceptorFactory , int priority ) { for ( Method method : proxyFactory . getCachedMethods ( ) ) { addClientInterceptor ( method , interceptorFactory , priority ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a client interceptor to the given method [CODESPLIT] public void addClientInterceptor ( Method method , InterceptorFactory interceptorFactory , int priority ) { OrderedItemContainer < InterceptorFactory > container = clientInterceptors . get ( method ) ; if ( container == null ) { clientInterceptors . put ( method , container = new OrderedItemContainer < InterceptorFactory > ( ) ) ; } container . add ( interceptorFactory , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attaches arbitrary private data to this view instance [CODESPLIT] public < T > void putPrivateData ( final Class < T > type , T data ) { privateData . put ( type , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > ModuleClassLoaderLocator . CombinedClassLoader< / code > instance with consideration of security manager enabled [CODESPLIT] static ModuleClassLoaderLocator . CombinedClassLoader createCombinedClassLoader ( final List < ClassLoader > classLoaders ) { if ( WildFlySecurityManager . isChecking ( ) ) { return doPrivileged ( new PrivilegedAction < ModuleClassLoaderLocator . CombinedClassLoader > ( ) { @ Override public CombinedClassLoader run ( ) { return new ModuleClassLoaderLocator . CombinedClassLoader ( classLoaders ) ; } } ) ; } else { return new ModuleClassLoaderLocator . CombinedClassLoader ( classLoaders ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws a XMLStreamException for the unexpected element that was encountered during the parse [CODESPLIT] protected static void unexpectedElement ( final XMLExtendedStreamReader reader ) throws XMLStreamException { throw EeLogger . ROOT_LOGGER . unexpectedElement ( reader . getName ( ) , reader . getLocation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Determines whether resource removal happens in this step or a subsequent step [CODESPLIT] private static boolean removeInCurrentStep ( Resource resource ) { for ( String childType : resource . getChildTypes ( ) ) { for ( Resource . ResourceEntry entry : resource . getChildren ( childType ) ) { if ( ! entry . isRuntime ( ) && resource . hasChild ( entry . getPathElement ( ) ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the regular and pooled CF [CODESPLIT] private static ConnectionFactoryAttribute [ ] define ( ConnectionFactoryAttribute [ ] specific , ConnectionFactoryAttribute ... common ) { int size = common . length + specific . length ; ConnectionFactoryAttribute [ ] result = new ConnectionFactoryAttribute [ size ] ; arraycopy ( specific , 0 , result , 0 , specific . length ) ; for ( int i = 0 ; i < common . length ; i ++ ) { ConnectionFactoryAttribute attr = common [ i ] ; AttributeDefinition definition = attr . getDefinition ( ) ; ConnectionFactoryAttribute newAttr ; // replace the reconnect-attempts attribute to use a different default value for pooled CF if ( definition == Common . RECONNECT_ATTEMPTS ) { AttributeDefinition copy = copy ( Pooled . RECONNECT_ATTEMPTS , AttributeAccess . Flag . RESTART_ALL_SERVICES ) ; newAttr = ConnectionFactoryAttribute . create ( copy , Pooled . RECONNECT_ATTEMPTS_PROP_NAME , true ) ; } else if ( definition == Common . CONNECTORS ) { StringListAttributeDefinition copy = new StringListAttributeDefinition . Builder ( Common . CONNECTORS ) . setAlternatives ( CommonAttributes . DISCOVERY_GROUP ) . setRequired ( true ) . setAttributeParser ( AttributeParser . STRING_LIST ) . setAttributeMarshaller ( AttributeMarshaller . STRING_LIST ) . setCapabilityReference ( new AbstractTransportDefinition . TransportCapabilityReferenceRecorder ( CAPABILITY_NAME , CONNECTOR_CAPABILITY_NAME , false ) ) . setRestartAllServices ( ) . build ( ) ; newAttr = ConnectionFactoryAttribute . create ( copy , attr . getPropertyName ( ) , attr . isResourceAdapterProperty ( ) , attr . getConfigType ( ) ) ; } else { AttributeDefinition copy = copy ( definition , AttributeAccess . Flag . RESTART_ALL_SERVICES ) ; newAttr = ConnectionFactoryAttribute . create ( copy , attr . getPropertyName ( ) , attr . isResourceAdapterProperty ( ) , attr . getConfigType ( ) ) ; } result [ specific . length + i ] = newAttr ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets list of JAXWS EJBs meta data . [CODESPLIT] public static List < EJBEndpoint > getJaxwsEjbs ( final DeploymentUnit unit ) { final JAXWSDeployment jaxwsDeployment = getOptionalAttachment ( unit , WSAttachmentKeys . JAXWS_ENDPOINTS_KEY ) ; return jaxwsDeployment != null ? jaxwsDeployment . getEjbEndpoints ( ) : Collections . < EJBEndpoint > emptyList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets list of JAXWS POJOs meta data . [CODESPLIT] public static List < POJOEndpoint > getJaxwsPojos ( final DeploymentUnit unit ) { final JAXWSDeployment jaxwsDeployment = unit . getAttachment ( WSAttachmentKeys . JAXWS_ENDPOINTS_KEY ) ; return jaxwsDeployment != null ? jaxwsDeployment . getPojoEndpoints ( ) : Collections . < POJOEndpoint > emptyList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns endpoint name . [CODESPLIT] public static String getEndpointName ( final ServletMetaData servletMD ) { final String endpointName = servletMD . getName ( ) ; return endpointName != null ? endpointName . trim ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns endpoint class name . [CODESPLIT] public static String getEndpointClassName ( final ServletMetaData servletMD ) { final String endpointClass = servletMD . getServletClass ( ) ; return endpointClass != null ? endpointClass . trim ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns servlet meta data for requested servlet name . [CODESPLIT] public static ServletMetaData getServletForName ( final JBossWebMetaData jbossWebMD , final String servletName ) { for ( JBossServletMetaData servlet : jbossWebMD . getServlets ( ) ) { if ( servlet . getName ( ) . equals ( servletName ) ) { return servlet ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns required attachment value from deployment unit . [CODESPLIT] public static < A > A getRequiredAttachment ( final DeploymentUnit unit , final AttachmentKey < A > key ) { final A value = unit . getAttachment ( key ) ; if ( value == null ) { throw new IllegalStateException ( ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns optional attachment value from deployment unit or null if not bound . [CODESPLIT] public static < A > A getOptionalAttachment ( final DeploymentUnit unit , final AttachmentKey < A > key ) { return unit . getAttachment ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the JBossWebMetaData from the WarMetaData attached to the provided deployment unit if any . [CODESPLIT] public static JBossWebMetaData getJBossWebMetaData ( final DeploymentUnit unit ) { final WarMetaData warMetaData = getOptionalAttachment ( unit , WarMetaData . ATTACHMENT_KEY ) ; JBossWebMetaData result = null ; if ( warMetaData != null ) { result = warMetaData . getMergedJBossWebMetaData ( ) ; if ( result == null ) { result = warMetaData . getJBossWebMetaData ( ) ; } } else { result = getOptionalAttachment ( unit , WSAttachmentKeys . JBOSSWEB_METADATA_KEY ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a named port - component from the jboss - webservices . xml [CODESPLIT] public static JBossPortComponentMetaData getJBossWebserviceMetaDataPortComponent ( final DeploymentUnit unit , final String name ) { if ( name != null ) { final JBossWebservicesMetaData jbossWebserviceMetaData = unit . getAttachment ( JBOSS_WEBSERVICES_METADATA_KEY ) ; if ( jbossWebserviceMetaData != null ) { JBossPortComponentMetaData [ ] portComponent = jbossWebserviceMetaData . getPortComponents ( ) ; if ( portComponent != null ) { for ( JBossPortComponentMetaData component : portComponent ) { if ( name . equals ( component . getEjbName ( ) ) ) { return component ; } } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an EJBEndpoint based upon fully qualified classname . [CODESPLIT] public static EJBEndpoint getWebserviceMetadataEJBEndpoint ( final JAXWSDeployment jaxwsDeployment , final String className ) { java . util . List < EJBEndpoint > ejbEndpointList = jaxwsDeployment . getEjbEndpoints ( ) ; for ( EJBEndpoint ejbEndpoint : ejbEndpointList ) { if ( className . equals ( ejbEndpoint . getClassName ( ) ) ) { return ejbEndpoint ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns context root associated with webservice deployment . [CODESPLIT] public static String getContextRoot ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { final DeploymentUnit unit = WSHelper . getRequiredAttachment ( dep , DeploymentUnit . class ) ; final JBossAppMetaData jbossAppMD = unit . getParent ( ) == null ? null : ASHelper . getOptionalAttachment ( unit . getParent ( ) , WSAttachmentKeys . JBOSS_APP_METADATA_KEY ) ; String contextRoot = null ; // prefer context root defined in application.xml over one defined in jboss-web.xml if ( jbossAppMD != null ) { final ModuleMetaData moduleMD = jbossAppMD . getModules ( ) . get ( dep . getSimpleName ( ) ) ; if ( moduleMD != null ) { final WebModuleMetaData webModuleMD = ( WebModuleMetaData ) moduleMD . getValue ( ) ; contextRoot = webModuleMD . getContextRoot ( ) ; } } if ( contextRoot == null ) { contextRoot = jbossWebMD != null ? jbossWebMD . getContextRoot ( ) : null ; } return contextRoot ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TransformedOperation transformOperation ( TransformationContext context , PathAddress address , ModelNode originalOperation ) throws OperationFailedException { String originalName = Operations . getName ( originalOperation ) ; PathAddress originalAddress = Operations . getPathAddress ( originalOperation ) ; Deque < ModelNode > preSteps = new LinkedList <> ( ) ; Deque < ModelNode > postSteps = new LinkedList <> ( ) ; ModelNode operation = originalOperation ; for ( OperationTransformer transformer : this . transformers ) { operation = transformer . transformOperation ( context , address , operation ) . getTransformedOperation ( ) ; // If the transformed operation is a composite operation, locate the modified operation and record any pre/post operations if ( this . collate && operation . get ( ModelDescriptionConstants . OP ) . asString ( ) . equals ( ModelDescriptionConstants . COMPOSITE ) ) { List < ModelNode > stepList = operation . get ( ModelDescriptionConstants . STEPS ) . asList ( ) ; ListIterator < ModelNode > steps = stepList . listIterator ( ) ; while ( steps . hasNext ( ) ) { ModelNode step = steps . next ( ) ; String operationName = Operations . getName ( step ) ; PathAddress operationAddress = Operations . getPathAddress ( step ) ; if ( operationName . equals ( originalName ) && operationAddress . equals ( originalAddress ) ) { operation = step ; break ; } preSteps . addLast ( step ) ; } steps = stepList . listIterator ( stepList . size ( ) ) ; while ( steps . hasPrevious ( ) ) { ModelNode step = steps . previous ( ) ; String operationName = Operations . getName ( step ) ; PathAddress operationAddress = Operations . getPathAddress ( step ) ; if ( operationName . equals ( originalName ) && operationAddress . equals ( originalAddress ) ) { break ; } postSteps . addFirst ( step ) ; } } } if ( this . collate ) { int count = preSteps . size ( ) + postSteps . size ( ) + 1 ; // If there are any pre or post steps, we need a composite operation if ( count > 1 ) { List < ModelNode > steps = new ArrayList <> ( count ) ; steps . addAll ( preSteps ) ; steps . add ( operation ) ; steps . addAll ( postSteps ) ; operation = Operations . createCompositeOperation ( steps ) ; } } return new TransformedOperation ( operation , OperationResultTransformer . ORIGINAL_RESULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( StartContext context ) throws StartException { SecurityLogger . ROOT_LOGGER . debug ( \"Starting JaasConfigurationService\" ) ; // set new configuration synchronized ( Configuration . class ) { Configuration . setConfiguration ( configuration ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Obtains the subsystem configuration properties from the specified { @code ModelNode } using default values for undefined properties . If the property has a IIOP equivalent it is translated into its IIOP counterpart before being added to the returned { @code Properties } object . < / p > [CODESPLIT] protected Properties getConfigurationProperties ( OperationContext context , ModelNode model ) throws OperationFailedException { Properties props = new Properties ( ) ; getResourceProperties ( props , IIOPRootDefinition . INSTANCE , context , model ) ; // check if the node contains a list of generic properties. ModelNode configNode = model . get ( Constants . CONFIGURATION ) ; if ( configNode . hasDefined ( Constants . PROPERTIES ) ) { for ( Property property : configNode . get ( Constants . PROPERTIES ) . get ( Constants . PROPERTY ) . asPropertyList ( ) ) { String name = property . getName ( ) ; String value = property . getValue ( ) . get ( Constants . PROPERTY_VALUE ) . asString ( ) ; props . setProperty ( name , value ) ; } } return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets up the ORB initializers according to what has been configured in the subsystem . < / p > [CODESPLIT] private void setupInitializers ( Properties props ) { List < String > orbInitializers = new ArrayList < String > ( ) ; // check which groups of initializers are to be installed. String installSecurity = ( String ) props . remove ( Constants . ORB_INIT_SECURITY ) ; if ( installSecurity . equalsIgnoreCase ( Constants . CLIENT ) ) { orbInitializers . addAll ( Arrays . asList ( IIOPInitializer . SECURITY_CLIENT . getInitializerClasses ( ) ) ) ; } else if ( installSecurity . equalsIgnoreCase ( Constants . IDENTITY ) ) { orbInitializers . addAll ( Arrays . asList ( IIOPInitializer . SECURITY_IDENTITY . getInitializerClasses ( ) ) ) ; } else if ( installSecurity . equalsIgnoreCase ( Constants . ELYTRON ) ) { final String authContext = props . getProperty ( Constants . ORB_INIT_AUTH_CONTEXT ) ; ElytronSASClientInterceptor . setAuthenticationContextName ( authContext ) ; orbInitializers . addAll ( Arrays . asList ( IIOPInitializer . SECURITY_ELYTRON . getInitializerClasses ( ) ) ) ; } String installTransaction = ( String ) props . remove ( Constants . ORB_INIT_TRANSACTIONS ) ; if ( installTransaction . equalsIgnoreCase ( Constants . FULL ) ) { orbInitializers . addAll ( Arrays . asList ( IIOPInitializer . TRANSACTIONS . getInitializerClasses ( ) ) ) ; } else if ( installTransaction . equalsIgnoreCase ( Constants . SPEC ) ) { orbInitializers . addAll ( Arrays . asList ( IIOPInitializer . SPEC_TRANSACTIONS . getInitializerClasses ( ) ) ) ; } // add the standard opendk initializer plus all configured initializers. for ( String initializerClass : orbInitializers ) { props . setProperty ( Constants . ORB_INITIALIZER_PREFIX + initializerClass , \"\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets up the SSL domain socket factories if SSL support has been enabled . < / p > [CODESPLIT] private boolean setupSSLFactories ( final Properties props ) throws OperationFailedException { final boolean supportSSL = \"true\" . equalsIgnoreCase ( props . getProperty ( Constants . SECURITY_SUPPORT_SSL ) ) ; final boolean sslConfigured ; if ( supportSSL ) { // if the config is using Elytron supplied SSL contexts, install the SSLSocketFactory. final String serverSSLContextName = props . getProperty ( Constants . SERVER_SSL_CONTEXT ) ; final String clientSSLContextName = props . getProperty ( Constants . CLIENT_SSL_CONTEXT ) ; if ( serverSSLContextName != null && clientSSLContextName != null ) { SSLSocketFactory . setServerSSLContextName ( serverSSLContextName ) ; SSLSocketFactory . setClientSSLContextName ( clientSSLContextName ) ; props . setProperty ( ORBConstants . SOCKET_FACTORY_CLASS_PROPERTY , SSLSocketFactory . class . getName ( ) ) ; } else { // if the config only has a legacy JSSE domain reference, install the LegacySSLSocketFactory. final String securityDomain = props . getProperty ( Constants . SECURITY_SECURITY_DOMAIN ) ; LegacySSLSocketFactory . setSecurityDomain ( securityDomain ) ; props . setProperty ( ORBConstants . SOCKET_FACTORY_CLASS_PROPERTY , LegacySSLSocketFactory . class . getName ( ) ) ; } sslConfigured = true ; } else { props . setProperty ( ORBConstants . SOCKET_FACTORY_CLASS_PROPERTY , NoSSLSocketFactory . class . getName ( ) ) ; sslConfigured = false ; } return sslConfigured ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( StartContext context ) throws StartException { log . debugf ( \"Starting SecurityBootstrapService\" ) ; //Print out the current version of PicketBox SecurityLogger . ROOT_LOGGER . currentVersion ( org . picketbox . Version . VERSION ) ; initializeJacc ( ) ; setupPolicyRegistration ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) @ Override public void stop ( StopContext context ) { // remove handlers Set handlerKeys = PolicyContext . getHandlerKeys ( ) ; handlerKeys . remove ( SecurityConstants . CALLBACK_HANDLER_KEY ) ; handlerKeys . remove ( SecurityConstants . SUBJECT_CONTEXT_KEY ) ; // Install the policy provider that existed on startup if ( initializeJacc && jaccPolicy != null ) Policy . setPolicy ( oldPolicy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TransformedOperation transformOperation ( TransformationContext context , PathAddress address , ModelNode operation ) { ModelNode legacyOperation = Util . createRemoveOperation ( this . addressTransformer . transform ( address ) ) ; return new TransformedOperation ( legacyOperation , OperationResultTransformer . ORIGINAL_RESULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the class name is found in additionalClasses then return it . [CODESPLIT] @ Override public Class < ? > classForName ( String name ) { try { if ( classes . containsKey ( name ) ) { return classes . get ( name ) ; } final Class < ? > clazz = module . getClassLoader ( ) . loadClass ( name ) ; classes . put ( name , clazz ) ; return clazz ; } catch ( ClassNotFoundException | LinkageError e ) { throw new ResourceLoadingException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a resource from the module class loader [CODESPLIT] @ Override public URL getResource ( String name ) { try { return module . getClassLoader ( ) . getResource ( name ) ; } catch ( Exception e ) { throw new ResourceLoadingException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads resources from the module class loader [CODESPLIT] @ Override public Collection < URL > getResources ( String name ) { try { final HashSet < URL > resources = new HashSet < URL > ( ) ; Enumeration < URL > urls = module . getClassLoader ( ) . getResources ( name ) ; while ( urls . hasMoreElements ( ) ) { resources . add ( urls . nextElement ( ) ) ; } return resources ; } catch ( Exception e ) { throw new ResourceLoadingException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists all children of a particular path taking overlays into account [CODESPLIT] public List < Resource > list ( String path ) { try { final List < Resource > ret = new ArrayList <> ( ) ; Resource res = deploymentResourceManager . getResource ( path ) ; if ( res != null ) { for ( Resource child : res . list ( ) ) { ret . add ( new ServletResource ( this , child ) ) ; } } String p = path ; if ( p . startsWith ( \"/\" ) ) { p = p . substring ( 1 ) ; } if ( overlays != null ) { for ( VirtualFile overlay : overlays ) { VirtualFile child = overlay . getChild ( p ) ; if ( child . exists ( ) ) { VirtualFileResource vfsResource = new VirtualFileResource ( overlay . getPhysicalFile ( ) , child , path ) ; for ( Resource c : vfsResource . list ( ) ) { ret . add ( new ServletResource ( this , c ) ) ; } } } } return ret ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; //this method really should have thrown IOException } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add dependencies for modules required for ra deployments [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , RESOURCE_API_ID , false , false , false , false ) ) ; if ( phaseContext . getDeploymentUnit ( ) . getAttachment ( ConnectorXmlDescriptor . ATTACHMENT_KEY ) == null ) { return ; // Skip non ra deployments } //if a module depends on a rar it also needs a dep on all the rar's \"local dependencies\" moduleSpecification . setLocalDependenciesTransitive ( true ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , JMS_ID , false , false , false , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , VALIDATION_ID , false , false , false , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , IRON_JACAMAR_ID , false , false , false , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , IRON_JACAMAR_IMPL_ID , false , true , false , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , HIBERNATE_VALIDATOR_ID , false , false , true , false ) ) ; if ( ! appclient ) phaseContext . addDeploymentDependency ( ConnectorServices . RESOURCEADAPTERS_SUBSYSTEM_SERVICE , ResourceAdaptersSubsystemService . ATTACHMENT_KEY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "current session bean invocation is ending close any transactional entity managers created without a JTA transaction . [CODESPLIT] public static void popCall ( ) { Map < String , EntityManager > emStack = nonTxStack . pop ( ) ; if ( emStack != null ) { for ( EntityManager entityManager : emStack . values ( ) ) { try { if ( entityManager . isOpen ( ) ) { entityManager . close ( ) ; } } catch ( RuntimeException safeToIgnore ) { if ( ROOT_LOGGER . isTraceEnabled ( ) ) { ROOT_LOGGER . trace ( \"Could not close (non-transactional) container managed entity manager.\" + \"  This shouldn't impact application functionality (only read \" + \"operations occur in non-transactional mode)\" , safeToIgnore ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the transactional entity manager for the specified scoped persistence unit name [CODESPLIT] public static EntityManager get ( String puScopedName ) { Map < String , EntityManager > map = nonTxStack . peek ( ) ; if ( map != null ) { return map . get ( puScopedName ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closing of transaction scoped JMSContext is executed through Synchronization listener . This method registers listener which takes care of closing JMSContext . [CODESPLIT] void registerCleanUpListener ( TransactionSynchronizationRegistry transactionSynchronizationRegistry , JMSContext contextInstance ) { //to avoid registration of more listeners for one context, flag in transaction is used. Object alreadyRegistered = transactionSynchronizationRegistry . getResource ( contextInstance ) ; if ( alreadyRegistered == null ) { transactionSynchronizationRegistry . registerInterposedSynchronization ( new AfterCompletionSynchronization ( contextInstance ) ) ; transactionSynchronizationRegistry . putResource ( contextInstance , AfterCompletionSynchronization . class . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( final XMLExtendedStreamReader reader , final List < ModelNode > operations ) throws XMLStreamException { final ModelNode ejb3SubsystemAddOperation = Util . createAddOperation ( SUBSYSTEM_PATH ) ; operations . add ( ejb3SubsystemAddOperation ) ; readAttributes ( reader ) ; // elements final EnumSet < EJB3SubsystemXMLElement > encountered = EnumSet . noneOf ( EJB3SubsystemXMLElement . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != XMLStreamConstants . END_ELEMENT ) { if ( EJB3SubsystemNamespace . forUri ( reader . getNamespaceURI ( ) ) != getExpectedNamespace ( ) ) { throw unexpectedElement ( reader ) ; } final EJB3SubsystemXMLElement element = EJB3SubsystemXMLElement . forName ( reader . getLocalName ( ) ) ; if ( ! encountered . add ( element ) ) { throw unexpectedElement ( reader ) ; } readElement ( reader , element , operations , ejb3SubsystemAddOperation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process web annotations . [CODESPLIT] public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; if ( ! DeploymentTypeMarker . isType ( DeploymentType . WAR , deploymentUnit ) ) { return ; // Skip non web deployments } WarMetaData warMetaData = deploymentUnit . getAttachment ( WarMetaData . ATTACHMENT_KEY ) ; assert warMetaData != null ; Map < String , WebMetaData > annotationsMetaData = warMetaData . getAnnotationsMetaData ( ) ; if ( annotationsMetaData == null ) { annotationsMetaData = new HashMap < String , WebMetaData > ( ) ; warMetaData . setAnnotationsMetaData ( annotationsMetaData ) ; } Map < ResourceRoot , Index > indexes = AnnotationIndexUtils . getAnnotationIndexes ( deploymentUnit ) ; // Process lib/*.jar for ( final Entry < ResourceRoot , Index > entry : indexes . entrySet ( ) ) { final Index jarIndex = entry . getValue ( ) ; annotationsMetaData . put ( entry . getKey ( ) . getRootName ( ) , processAnnotations ( jarIndex ) ) ; } Map < ModuleIdentifier , CompositeIndex > additionalModelAnnotations = deploymentUnit . getAttachment ( Attachments . ADDITIONAL_ANNOTATION_INDEXES_BY_MODULE ) ; if ( additionalModelAnnotations != null ) { final List < WebMetaData > additional = new ArrayList < WebMetaData > ( ) ; for ( Entry < ModuleIdentifier , CompositeIndex > entry : additionalModelAnnotations . entrySet ( ) ) { for ( Index index : entry . getValue ( ) . getIndexes ( ) ) { additional . add ( processAnnotations ( index ) ) ; } } warMetaData . setAdditionalModuleAnnotationsMetadata ( additional ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a single index . [CODESPLIT] protected WebMetaData processAnnotations ( Index index ) throws DeploymentUnitProcessingException { WebMetaData metaData = new WebMetaData ( ) ; // @WebServlet final List < AnnotationInstance > webServletAnnotations = index . getAnnotations ( webServlet ) ; if ( webServletAnnotations != null && webServletAnnotations . size ( ) > 0 ) { ServletsMetaData servlets = new ServletsMetaData ( ) ; List < ServletMappingMetaData > servletMappings = new ArrayList < ServletMappingMetaData > ( ) ; for ( final AnnotationInstance annotation : webServletAnnotations ) { ServletMetaData servlet = new ServletMetaData ( ) ; AnnotationTarget target = annotation . target ( ) ; if ( ! ( target instanceof ClassInfo ) ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidWebServletAnnotation ( target ) ) ; } ClassInfo classInfo = ClassInfo . class . cast ( target ) ; servlet . setServletClass ( classInfo . toString ( ) ) ; AnnotationValue nameValue = annotation . value ( \"name\" ) ; if ( nameValue == null || nameValue . asString ( ) . isEmpty ( ) ) { servlet . setName ( classInfo . toString ( ) ) ; } else { servlet . setName ( nameValue . asString ( ) ) ; } AnnotationValue loadOnStartup = annotation . value ( \"loadOnStartup\" ) ; if ( loadOnStartup != null && loadOnStartup . asInt ( ) >= 0 ) { servlet . setLoadOnStartupInt ( loadOnStartup . asInt ( ) ) ; } AnnotationValue asyncSupported = annotation . value ( \"asyncSupported\" ) ; if ( asyncSupported != null ) { servlet . setAsyncSupported ( asyncSupported . asBoolean ( ) ) ; } AnnotationValue initParamsValue = annotation . value ( \"initParams\" ) ; if ( initParamsValue != null ) { AnnotationInstance [ ] initParamsAnnotations = initParamsValue . asNestedArray ( ) ; if ( initParamsAnnotations != null && initParamsAnnotations . length > 0 ) { List < ParamValueMetaData > initParams = new ArrayList < ParamValueMetaData > ( ) ; for ( AnnotationInstance initParamsAnnotation : initParamsAnnotations ) { ParamValueMetaData initParam = new ParamValueMetaData ( ) ; AnnotationValue initParamName = initParamsAnnotation . value ( \"name\" ) ; AnnotationValue initParamValue = initParamsAnnotation . value ( ) ; if ( initParamName == null || initParamValue == null ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidWebInitParamAnnotation ( target ) ) ; } AnnotationValue initParamDescription = initParamsAnnotation . value ( \"description\" ) ; initParam . setParamName ( initParamName . asString ( ) ) ; initParam . setParamValue ( initParamValue . asString ( ) ) ; if ( initParamDescription != null ) { Descriptions descriptions = getDescription ( initParamDescription . asString ( ) ) ; if ( descriptions != null ) { initParam . setDescriptions ( descriptions ) ; } } initParams . add ( initParam ) ; } servlet . setInitParam ( initParams ) ; } } AnnotationValue descriptionValue = annotation . value ( \"description\" ) ; AnnotationValue displayNameValue = annotation . value ( \"displayName\" ) ; AnnotationValue smallIconValue = annotation . value ( \"smallIcon\" ) ; AnnotationValue largeIconValue = annotation . value ( \"largeIcon\" ) ; DescriptionGroupMetaData descriptionGroup = getDescriptionGroup ( ( descriptionValue == null ) ? \"\" : descriptionValue . asString ( ) , ( displayNameValue == null ) ? \"\" : displayNameValue . asString ( ) , ( smallIconValue == null ) ? \"\" : smallIconValue . asString ( ) , ( largeIconValue == null ) ? \"\" : largeIconValue . asString ( ) ) ; if ( descriptionGroup != null ) { servlet . setDescriptionGroup ( descriptionGroup ) ; } ServletMappingMetaData servletMapping = new ServletMappingMetaData ( ) ; servletMapping . setServletName ( servlet . getName ( ) ) ; List < String > urlPatterns = new ArrayList < String > ( ) ; AnnotationValue urlPatternsValue = annotation . value ( \"urlPatterns\" ) ; if ( urlPatternsValue != null ) { for ( String urlPattern : urlPatternsValue . asStringArray ( ) ) { urlPatterns . add ( urlPattern ) ; } } urlPatternsValue = annotation . value ( ) ; if ( urlPatternsValue != null ) { for ( String urlPattern : urlPatternsValue . asStringArray ( ) ) { urlPatterns . add ( urlPattern ) ; } } if ( urlPatterns . size ( ) > 0 ) { servletMapping . setUrlPatterns ( urlPatterns ) ; servletMappings . add ( servletMapping ) ; } servlets . add ( servlet ) ; } metaData . setServlets ( servlets ) ; metaData . setServletMappings ( servletMappings ) ; } // @WebFilter final List < AnnotationInstance > webFilterAnnotations = index . getAnnotations ( webFilter ) ; if ( webFilterAnnotations != null && webFilterAnnotations . size ( ) > 0 ) { FiltersMetaData filters = new FiltersMetaData ( ) ; List < FilterMappingMetaData > filterMappings = new ArrayList < FilterMappingMetaData > ( ) ; for ( final AnnotationInstance annotation : webFilterAnnotations ) { FilterMetaData filter = new FilterMetaData ( ) ; AnnotationTarget target = annotation . target ( ) ; if ( ! ( target instanceof ClassInfo ) ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidWebFilterAnnotation ( target ) ) ; } ClassInfo classInfo = ClassInfo . class . cast ( target ) ; filter . setFilterClass ( classInfo . toString ( ) ) ; AnnotationValue nameValue = annotation . value ( \"filterName\" ) ; if ( nameValue == null || nameValue . asString ( ) . isEmpty ( ) ) { filter . setName ( classInfo . toString ( ) ) ; } else { filter . setName ( nameValue . asString ( ) ) ; } AnnotationValue asyncSupported = annotation . value ( \"asyncSupported\" ) ; if ( asyncSupported != null ) { filter . setAsyncSupported ( asyncSupported . asBoolean ( ) ) ; } AnnotationValue initParamsValue = annotation . value ( \"initParams\" ) ; if ( initParamsValue != null ) { AnnotationInstance [ ] initParamsAnnotations = initParamsValue . asNestedArray ( ) ; if ( initParamsAnnotations != null && initParamsAnnotations . length > 0 ) { List < ParamValueMetaData > initParams = new ArrayList < ParamValueMetaData > ( ) ; for ( AnnotationInstance initParamsAnnotation : initParamsAnnotations ) { ParamValueMetaData initParam = new ParamValueMetaData ( ) ; AnnotationValue initParamName = initParamsAnnotation . value ( \"name\" ) ; AnnotationValue initParamValue = initParamsAnnotation . value ( ) ; if ( initParamName == null || initParamValue == null ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidWebInitParamAnnotation ( target ) ) ; } AnnotationValue initParamDescription = initParamsAnnotation . value ( \"description\" ) ; initParam . setParamName ( initParamName . asString ( ) ) ; initParam . setParamValue ( initParamValue . asString ( ) ) ; if ( initParamDescription != null ) { Descriptions descriptions = getDescription ( initParamDescription . asString ( ) ) ; if ( descriptions != null ) { initParam . setDescriptions ( descriptions ) ; } } initParams . add ( initParam ) ; } filter . setInitParam ( initParams ) ; } } AnnotationValue descriptionValue = annotation . value ( \"description\" ) ; AnnotationValue displayNameValue = annotation . value ( \"displayName\" ) ; AnnotationValue smallIconValue = annotation . value ( \"smallIcon\" ) ; AnnotationValue largeIconValue = annotation . value ( \"largeIcon\" ) ; DescriptionGroupMetaData descriptionGroup = getDescriptionGroup ( ( descriptionValue == null ) ? \"\" : descriptionValue . asString ( ) , ( displayNameValue == null ) ? \"\" : displayNameValue . asString ( ) , ( smallIconValue == null ) ? \"\" : smallIconValue . asString ( ) , ( largeIconValue == null ) ? \"\" : largeIconValue . asString ( ) ) ; if ( descriptionGroup != null ) { filter . setDescriptionGroup ( descriptionGroup ) ; } filters . add ( filter ) ; FilterMappingMetaData filterMapping = new FilterMappingMetaData ( ) ; filterMapping . setFilterName ( filter . getName ( ) ) ; List < String > urlPatterns = new ArrayList < String > ( ) ; List < String > servletNames = new ArrayList < String > ( ) ; List < DispatcherType > dispatchers = new ArrayList < DispatcherType > ( ) ; AnnotationValue urlPatternsValue = annotation . value ( \"urlPatterns\" ) ; if ( urlPatternsValue != null ) { for ( String urlPattern : urlPatternsValue . asStringArray ( ) ) { urlPatterns . add ( urlPattern ) ; } } urlPatternsValue = annotation . value ( ) ; if ( urlPatternsValue != null ) { for ( String urlPattern : urlPatternsValue . asStringArray ( ) ) { urlPatterns . add ( urlPattern ) ; } } if ( urlPatterns . size ( ) > 0 ) { filterMapping . setUrlPatterns ( urlPatterns ) ; } AnnotationValue servletNamesValue = annotation . value ( \"servletNames\" ) ; if ( servletNamesValue != null ) { for ( String servletName : servletNamesValue . asStringArray ( ) ) { servletNames . add ( servletName ) ; } } if ( servletNames . size ( ) > 0 ) { filterMapping . setServletNames ( servletNames ) ; } AnnotationValue dispatcherTypesValue = annotation . value ( \"dispatcherTypes\" ) ; if ( dispatcherTypesValue != null ) { for ( String dispatcherValue : dispatcherTypesValue . asEnumArray ( ) ) { dispatchers . add ( DispatcherType . valueOf ( dispatcherValue ) ) ; } } if ( dispatchers . size ( ) > 0 ) { filterMapping . setDispatchers ( dispatchers ) ; } if ( urlPatterns . size ( ) > 0 || servletNames . size ( ) > 0 ) { filterMappings . add ( filterMapping ) ; } } metaData . setFilters ( filters ) ; metaData . setFilterMappings ( filterMappings ) ; } // @WebListener final List < AnnotationInstance > webListenerAnnotations = index . getAnnotations ( webListener ) ; if ( webListenerAnnotations != null && webListenerAnnotations . size ( ) > 0 ) { List < ListenerMetaData > listeners = new ArrayList < ListenerMetaData > ( ) ; for ( final AnnotationInstance annotation : webListenerAnnotations ) { ListenerMetaData listener = new ListenerMetaData ( ) ; AnnotationTarget target = annotation . target ( ) ; if ( ! ( target instanceof ClassInfo ) ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidWebListenerAnnotation ( target ) ) ; } ClassInfo classInfo = ClassInfo . class . cast ( target ) ; listener . setListenerClass ( classInfo . toString ( ) ) ; AnnotationValue descriptionValue = annotation . value ( ) ; if ( descriptionValue != null ) { DescriptionGroupMetaData descriptionGroup = getDescriptionGroup ( descriptionValue . asString ( ) ) ; if ( descriptionGroup != null ) { listener . setDescriptionGroup ( descriptionGroup ) ; } } listeners . add ( listener ) ; } metaData . setListeners ( listeners ) ; } // @RunAs final List < AnnotationInstance > runAsAnnotations = index . getAnnotations ( runAs ) ; if ( runAsAnnotations != null && runAsAnnotations . size ( ) > 0 ) { AnnotationsMetaData annotations = metaData . getAnnotations ( ) ; if ( annotations == null ) { annotations = new AnnotationsMetaData ( ) ; metaData . setAnnotations ( annotations ) ; } for ( final AnnotationInstance annotation : runAsAnnotations ) { AnnotationTarget target = annotation . target ( ) ; if ( ! ( target instanceof ClassInfo ) ) { continue ; } ClassInfo classInfo = ClassInfo . class . cast ( target ) ; AnnotationMetaData annotationMD = annotations . get ( classInfo . toString ( ) ) ; if ( annotationMD == null ) { annotationMD = new AnnotationMetaData ( ) ; annotationMD . setClassName ( classInfo . toString ( ) ) ; annotations . add ( annotationMD ) ; } if ( annotation . value ( ) == null ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidRunAsAnnotation ( target ) ) ; } RunAsMetaData runAs = new RunAsMetaData ( ) ; runAs . setRoleName ( annotation . value ( ) . asString ( ) ) ; annotationMD . setRunAs ( runAs ) ; } } // @DeclareRoles final List < AnnotationInstance > declareRolesAnnotations = index . getAnnotations ( declareRoles ) ; if ( declareRolesAnnotations != null && declareRolesAnnotations . size ( ) > 0 ) { SecurityRolesMetaData securityRoles = metaData . getSecurityRoles ( ) ; if ( securityRoles == null ) { securityRoles = new SecurityRolesMetaData ( ) ; metaData . setSecurityRoles ( securityRoles ) ; } for ( final AnnotationInstance annotation : declareRolesAnnotations ) { if ( annotation . value ( ) == null ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidDeclareRolesAnnotation ( annotation . target ( ) ) ) ; } for ( String role : annotation . value ( ) . asStringArray ( ) ) { SecurityRoleMetaData sr = new SecurityRoleMetaData ( ) ; sr . setRoleName ( role ) ; securityRoles . add ( sr ) ; } } } // @MultipartConfig final List < AnnotationInstance > multipartConfigAnnotations = index . getAnnotations ( multipartConfig ) ; if ( multipartConfigAnnotations != null && multipartConfigAnnotations . size ( ) > 0 ) { AnnotationsMetaData annotations = metaData . getAnnotations ( ) ; if ( annotations == null ) { annotations = new AnnotationsMetaData ( ) ; metaData . setAnnotations ( annotations ) ; } for ( final AnnotationInstance annotation : multipartConfigAnnotations ) { AnnotationTarget target = annotation . target ( ) ; if ( ! ( target instanceof ClassInfo ) ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidMultipartConfigAnnotation ( target ) ) ; } ClassInfo classInfo = ClassInfo . class . cast ( target ) ; AnnotationMetaData annotationMD = annotations . get ( classInfo . toString ( ) ) ; if ( annotationMD == null ) { annotationMD = new AnnotationMetaData ( ) ; annotationMD . setClassName ( classInfo . toString ( ) ) ; annotations . add ( annotationMD ) ; } MultipartConfigMetaData multipartConfig = new MultipartConfigMetaData ( ) ; AnnotationValue locationValue = annotation . value ( \"location\" ) ; if ( locationValue != null && locationValue . asString ( ) . length ( ) > 0 ) { multipartConfig . setLocation ( locationValue . asString ( ) ) ; } AnnotationValue maxFileSizeValue = annotation . value ( \"maxFileSize\" ) ; if ( maxFileSizeValue != null && maxFileSizeValue . asLong ( ) != - 1L ) { multipartConfig . setMaxFileSize ( maxFileSizeValue . asLong ( ) ) ; } AnnotationValue maxRequestSizeValue = annotation . value ( \"maxRequestSize\" ) ; if ( maxRequestSizeValue != null && maxRequestSizeValue . asLong ( ) != - 1L ) { multipartConfig . setMaxRequestSize ( maxRequestSizeValue . asLong ( ) ) ; } AnnotationValue fileSizeThresholdValue = annotation . value ( \"fileSizeThreshold\" ) ; if ( fileSizeThresholdValue != null && fileSizeThresholdValue . asInt ( ) != 0 ) { multipartConfig . setFileSizeThreshold ( fileSizeThresholdValue . asInt ( ) ) ; } annotationMD . setMultipartConfig ( multipartConfig ) ; } } // @ServletSecurity final List < AnnotationInstance > servletSecurityAnnotations = index . getAnnotations ( servletSecurity ) ; if ( servletSecurityAnnotations != null && servletSecurityAnnotations . size ( ) > 0 ) { AnnotationsMetaData annotations = metaData . getAnnotations ( ) ; if ( annotations == null ) { annotations = new AnnotationsMetaData ( ) ; metaData . setAnnotations ( annotations ) ; } for ( final AnnotationInstance annotation : servletSecurityAnnotations ) { AnnotationTarget target = annotation . target ( ) ; if ( ! ( target instanceof ClassInfo ) ) { throw new DeploymentUnitProcessingException ( UndertowLogger . ROOT_LOGGER . invalidServletSecurityAnnotation ( target ) ) ; } ClassInfo classInfo = ClassInfo . class . cast ( target ) ; AnnotationMetaData annotationMD = annotations . get ( classInfo . toString ( ) ) ; if ( annotationMD == null ) { annotationMD = new AnnotationMetaData ( ) ; annotationMD . setClassName ( classInfo . toString ( ) ) ; annotations . add ( annotationMD ) ; } ServletSecurityMetaData servletSecurity = new ServletSecurityMetaData ( ) ; AnnotationValue httpConstraintValue = annotation . value ( ) ; List < String > rolesAllowed = new ArrayList < String > ( ) ; if ( httpConstraintValue != null ) { AnnotationInstance httpConstraint = httpConstraintValue . asNested ( ) ; AnnotationValue httpConstraintERSValue = httpConstraint . value ( ) ; if ( httpConstraintERSValue != null ) { servletSecurity . setEmptyRoleSemantic ( EmptyRoleSemanticType . valueOf ( httpConstraintERSValue . asEnum ( ) ) ) ; } AnnotationValue httpConstraintTGValue = httpConstraint . value ( \"transportGuarantee\" ) ; if ( httpConstraintTGValue != null ) { servletSecurity . setTransportGuarantee ( TransportGuaranteeType . valueOf ( httpConstraintTGValue . asEnum ( ) ) ) ; } AnnotationValue rolesAllowedValue = httpConstraint . value ( \"rolesAllowed\" ) ; if ( rolesAllowedValue != null ) { for ( String role : rolesAllowedValue . asStringArray ( ) ) { rolesAllowed . add ( role ) ; } } } servletSecurity . setRolesAllowed ( rolesAllowed ) ; AnnotationValue httpMethodConstraintsValue = annotation . value ( \"httpMethodConstraints\" ) ; if ( httpMethodConstraintsValue != null ) { AnnotationInstance [ ] httpMethodConstraints = httpMethodConstraintsValue . asNestedArray ( ) ; if ( httpMethodConstraints . length > 0 ) { List < HttpMethodConstraintMetaData > methodConstraints = new ArrayList < HttpMethodConstraintMetaData > ( ) ; for ( AnnotationInstance httpMethodConstraint : httpMethodConstraints ) { HttpMethodConstraintMetaData methodConstraint = new HttpMethodConstraintMetaData ( ) ; AnnotationValue httpMethodConstraintValue = httpMethodConstraint . value ( ) ; if ( httpMethodConstraintValue != null ) { methodConstraint . setMethod ( httpMethodConstraintValue . asString ( ) ) ; } AnnotationValue httpMethodConstraintERSValue = httpMethodConstraint . value ( \"emptyRoleSemantic\" ) ; if ( httpMethodConstraintERSValue != null ) { methodConstraint . setEmptyRoleSemantic ( EmptyRoleSemanticType . valueOf ( httpMethodConstraintERSValue . asEnum ( ) ) ) ; } AnnotationValue httpMethodConstraintTGValue = httpMethodConstraint . value ( \"transportGuarantee\" ) ; if ( httpMethodConstraintTGValue != null ) { methodConstraint . setTransportGuarantee ( TransportGuaranteeType . valueOf ( httpMethodConstraintTGValue . asEnum ( ) ) ) ; } AnnotationValue rolesAllowedValue = httpMethodConstraint . value ( \"rolesAllowed\" ) ; rolesAllowed = new ArrayList < String > ( ) ; if ( rolesAllowedValue != null ) { for ( String role : rolesAllowedValue . asStringArray ( ) ) { rolesAllowed . add ( role ) ; } } methodConstraint . setRolesAllowed ( rolesAllowed ) ; methodConstraints . add ( methodConstraint ) ; } servletSecurity . setHttpMethodConstraints ( methodConstraints ) ; } } annotationMD . setServletSecurity ( servletSecurity ) ; } } return metaData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the update operation succeeds in modifying the runtime false otherwise . [CODESPLIT] private boolean updateServerConfig ( String attributeName , String value , boolean isRevert ) throws OperationFailedException , DisabledOperationException { final ServerConfigImpl config = ( ServerConfigImpl ) ServerConfigFactoryImpl . getConfig ( ) ; try { if ( MODIFY_WSDL_ADDRESS . equals ( attributeName ) ) { final boolean modifyWSDLAddress = value != null && Boolean . parseBoolean ( value ) ; config . setModifySOAPAddress ( modifyWSDLAddress , isRevert ) ; } else if ( WSDL_HOST . equals ( attributeName ) ) { final String host = value != null ? value : null ; try { config . setWebServiceHost ( host , isRevert ) ; } catch ( final UnknownHostException e ) { throw new OperationFailedException ( e . getMessage ( ) , e ) ; } } else if ( WSDL_PORT . equals ( attributeName ) ) { final int port = value != null ? Integer . parseInt ( value ) : - 1 ; config . setWebServicePort ( port , isRevert ) ; } else if ( WSDL_SECURE_PORT . equals ( attributeName ) ) { final int securePort = value != null ? Integer . parseInt ( value ) : - 1 ; config . setWebServiceSecurePort ( securePort , isRevert ) ; } else if ( WSDL_PATH_REWRITE_RULE . equals ( attributeName ) ) { final String path = value != null ? value : null ; config . setWebServicePathRewriteRule ( path , isRevert ) ; } else if ( WSDL_URI_SCHEME . equals ( attributeName ) ) { if ( value == null || value . equals ( \"http\" ) || value . equals ( \"https\" ) ) { config . setWebServiceUriScheme ( value , isRevert ) ; } else { throw new IllegalArgumentException ( attributeName + \" = \" + value ) ; } } else if ( STATISTICS_ENABLED . equals ( attributeName ) ) { final boolean enabled = value != null ? Boolean . parseBoolean ( value ) : false ; config . setStatisticsEnabled ( enabled ) ; } else { throw new IllegalArgumentException ( attributeName ) ; } } catch ( DisabledOperationException doe ) { // the WS stack rejected the runtime update if ( ! isRevert ) { return false ; } else { throw doe ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( ExtensionContext context ) { final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; // Register the root subsystem resource. final ManagementResourceRegistration rootResource = subsystem . registerSubsystemModel ( EeSubsystemRootResource . create ( ) ) ; // Mandatory describe operation rootResource . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; // register submodels rootResource . registerSubModel ( ContextServiceResourceDefinition . INSTANCE ) ; rootResource . registerSubModel ( ManagedThreadFactoryResourceDefinition . INSTANCE ) ; rootResource . registerSubModel ( ManagedExecutorServiceResourceDefinition . INSTANCE ) ; rootResource . registerSubModel ( ManagedScheduledExecutorServiceResourceDefinition . INSTANCE ) ; rootResource . registerSubModel ( new DefaultBindingsResourceDefinition ( new DefaultBindingsConfigurationProcessor ( ) ) ) ; subsystem . registerXMLElementWriter ( EESubsystemXmlPersister . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . EE_1_0 . getUriString ( ) , EESubsystemParser10 :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . EE_1_1 . getUriString ( ) , EESubsystemParser11 :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . EE_1_2 . getUriString ( ) , EESubsystemParser12 :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . EE_2_0 . getUriString ( ) , EESubsystemParser20 :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . EE_3_0 . getUriString ( ) , EESubsystemParser20 :: new ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , Namespace . EE_4_0 . getUriString ( ) , EESubsystemParser40 :: new ) ; context . setProfileParsingCompletionHandler ( new BeanValidationProfileParsingCompletionHandler ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object processInvocation ( final InterceptorContext context ) throws Exception { final ManagedReference reference = ( ManagedReference ) context . getPrivateData ( ComponentInstance . class ) . getInstanceData ( contextKey ) ; final Object instance = reference . getInstance ( ) ; try { return method . invoke ( instance , context . getParameters ( ) ) ; } catch ( IllegalAccessException e ) { final IllegalAccessError n = new IllegalAccessError ( e . getMessage ( ) ) ; n . setStackTrace ( e . getStackTrace ( ) ) ; throw n ; } catch ( InvocationTargetException e ) { throw Interceptors . rethrow ( e . getCause ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To workaround ActiveMQ s BindingRegistry limitation in { [CODESPLIT] private void startQueue ( final String queueName , final ServiceTarget serviceTarget , final ServiceName serverServiceName , final ServiceBuilder < ? > serviceBuilder , final DeploymentUnit deploymentUnit , final Injector < ManagedReferenceFactory > injector , final boolean external ) { final String selector = properties . containsKey ( SELECTOR . getName ( ) ) ? properties . get ( SELECTOR . getName ( ) ) : null ; final boolean durable = properties . containsKey ( DURABLE . getName ( ) ) ? Boolean . valueOf ( properties . get ( DURABLE . getName ( ) ) ) : DURABLE . getDefaultValue ( ) . asBoolean ( ) ; final String managementAddress = properties . containsKey ( MANAGEMENT_ADDRESS . getName ( ) ) ? properties . get ( MANAGEMENT_ADDRESS . getName ( ) ) : MANAGEMENT_ADDRESS . getDefaultValue ( ) . asString ( ) ; final String user = properties . containsKey ( \"management-user\" ) ? properties . get ( \"management-user\" ) : null ; final String password = properties . containsKey ( \"management-password\" ) ? properties . get ( \"\\\"management-password\" ) : null ; ModelNode destination = new ModelNode ( ) ; destination . get ( NAME ) . set ( queueName ) ; destination . get ( DURABLE . getName ( ) ) . set ( durable ) ; if ( selector != null ) { destination . get ( SELECTOR . getName ( ) ) . set ( selector ) ; } destination . get ( ENTRIES ) . add ( jndiName ) ; Service < Queue > queueService ; if ( external ) { ServiceName pcfName = JMSServices . getPooledConnectionFactoryBaseServiceName ( serverServiceName ) . append ( resourceAdapter ) ; final ServiceName jmsQueueServiceName = JMSServices . getJmsQueueBaseServiceName ( serverServiceName ) . append ( queueName ) ; queueService = ExternalJMSQueueService . installRuntimeQueueService ( DestinationConfiguration . Builder . getInstance ( ) . setResourceAdapter ( resourceAdapter ) . setName ( queueName ) . setManagementQueueAddress ( managementAddress ) . setDestinationServiceName ( jmsQueueServiceName ) . setDurable ( durable ) . setSelector ( selector ) . setManagementUsername ( user ) . setManagementPassword ( password ) . build ( ) , serviceTarget , pcfName ) ; } else { queueService = JMSQueueService . installService ( queueName , serviceTarget , serverServiceName , selector , durable ) ; } inject ( serviceBuilder , injector , queueService ) ; //create the management registration String serverName = null ; final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit . getAttachment ( Attachments . DEPLOYMENT_RESOURCE_SUPPORT ) ; PathAddress registration ; if ( external ) { final PathElement dest = PathElement . pathElement ( EXTERNAL_JMS_QUEUE , queueName ) ; deploymentResourceSupport . getDeploymentSubsystemModel ( MessagingExtension . SUBSYSTEM_NAME ) ; registration = PathAddress . pathAddress ( dest ) ; } else { serverName = getActiveMQServerName ( properties ) ; final PathElement dest = PathElement . pathElement ( JMS_QUEUE , queueName ) ; final PathElement serverElement = PathElement . pathElement ( SERVER , serverName ) ; deploymentResourceSupport . getDeploymentSubModel ( MessagingExtension . SUBSYSTEM_NAME , serverElement ) ; registration = PathAddress . pathAddress ( serverElement , dest ) ; } MessagingXmlInstallDeploymentUnitProcessor . createDeploymentSubModel ( registration , deploymentUnit ) ; JMSQueueConfigurationRuntimeHandler . INSTANCE . registerResource ( serverName , queueName , destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * checks if the method s throws clause includes java . rmi . RemoteException or a superclass of it . [CODESPLIT] public static boolean throwsRemoteException ( Method method ) { Class [ ] exception = method . getExceptionTypes ( ) ; for ( int i = 0 ; i < exception . length ; ++ i ) if ( exception [ i ] . isAssignableFrom ( java . rmi . RemoteException . class ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether all the fields in the class are declared as public . [CODESPLIT] public static boolean isAllFieldsPublic ( Class c ) { try { final Field [ ] list = c . getFields ( ) ; for ( int i = 0 ; i < list . length ; i ++ ) if ( ! Modifier . isPublic ( list [ i ] . getModifiers ( ) ) ) return false ; } catch ( Exception e ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation --------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . InterfaceDefHelper . narrow ( servantToReference ( new InterfaceDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainerOperations implementation ---------------------------- [CODESPLIT] public Contained lookup ( String search_name ) { Contained res = delegate . lookup ( search_name ) ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "InterfaceDefOperations implementation ------------------------- [CODESPLIT] public InterfaceDef [ ] base_interfaces ( ) { if ( base_interfaces_ref == null ) { base_interfaces_ref = new InterfaceDef [ base_interfaces . length ] ; for ( int i = 0 ; i < base_interfaces_ref . length ; ++ i ) { Contained c = repository . lookup_id ( base_interfaces [ i ] ) ; base_interfaces_ref [ i ] = InterfaceDefHelper . narrow ( c ) ; } } return base_interfaces_ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "IDLTypeOperations implementation ------------------------------ [CODESPLIT] public TypeCode type ( ) { if ( typeCode == null ) typeCode = getORB ( ) . create_interface_tc ( id , name ) ; return typeCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof org . omg . CORBA . ContainedOperations ) defined_in_id = ( ( org . omg . CORBA . ContainedOperations ) defined_in ) . id ( ) ; org . omg . CORBA . InterfaceDescription md = new InterfaceDescription ( name , id , defined_in_id , version , base_interfaces , false ) ; Any any = getORB ( ) . create_any ( ) ; InterfaceDescriptionHelper . insert ( any , md ) ; return new Description ( DefinitionKind . dk_Interface , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode a URI string ( according to RFC 2396 ) . [CODESPLIT] public static String decode ( String s ) throws MalformedURLException { try { return decode ( s , \"8859_1\" ) ; } catch ( UnsupportedEncodingException e ) { // ISO-Latin-1 should always be available? throw IIOPLogger . ROOT_LOGGER . unavailableISOLatin1Decoder ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode a URI string ( according to RFC 2396 ) . <p / > Three - character sequences %xy where xy is the two - digit hexadecimal representation of the lower 8 - bits of a character are decoded into the character itself . <p / > The string is subsequently converted using the specified encoding [CODESPLIT] public static String decode ( String s , String enc ) throws MalformedURLException , UnsupportedEncodingException { int length = s . length ( ) ; byte [ ] bytes = new byte [ length ] ; int j = 0 ; for ( int i = 0 ; i < length ; i ++ ) { if ( s . charAt ( i ) == ' ' ) { i ++ ; // skip % try { bytes [ j ++ ] = ( byte ) Integer . parseInt ( s . substring ( i , i + 2 ) , 16 ) ; } catch ( Exception e ) { throw IIOPLogger . ROOT_LOGGER . invalidURIEncoding ( s ) ; } i ++ ; // skip first hex char; for loop will skip second one } else { bytes [ j ++ ] = ( byte ) s . charAt ( i ) ; } } return new String ( bytes , 0 , j , enc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode a string for inclusion in a URI ( according to RFC 2396 ) . <p / > Unsafe characters are escaped by encoding them in three - character sequences %xy where xy is the two - digit hexadecimal representation of the lower 8 - bits of the character . <p / > The question mark ? character is also escaped as required by RFC 2255 . <p / > The string is first converted to the specified encoding . For LDAP ( 2255 ) the encoding must be UTF - 8 . [CODESPLIT] public static String encode ( String s , String enc ) throws UnsupportedEncodingException { byte [ ] bytes = s . getBytes ( enc ) ; int count = bytes . length ; /*\n         * From RFC 2396:\n         *\n         *     mark = \"-\" | \"_\" | \".\" | \"!\" | \"~\" | \"*\" | \"'\" | \"(\" | \")\"\n         * reserved = \";\" | \"/\" | \":\" | \"?\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\"\n         */ final String allowed = \"=,+;.'-@&/$_()!~*:\" ; // '?' is omitted char [ ] buf = new char [ 3 * count ] ; int j = 0 ; for ( int i = 0 ; i < count ; i ++ ) { if ( ( bytes [ i ] >= 0x61 && bytes [ i ] <= 0x7A ) || // a..z ( bytes [ i ] >= 0x41 && bytes [ i ] <= 0x5A ) || // A..Z ( bytes [ i ] >= 0x30 && bytes [ i ] <= 0x39 ) || // 0..9 ( allowed . indexOf ( bytes [ i ] ) >= 0 ) ) { buf [ j ++ ] = ( char ) bytes [ i ] ; } else { buf [ j ++ ] = ' ' ; buf [ j ++ ] = Character . forDigit ( 0xF & ( bytes [ i ] >>> 4 ) , 16 ) ; buf [ j ++ ] = Character . forDigit ( 0xF & bytes [ i ] , 16 ) ; } } return new String ( buf , 0 , j ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@see org . jboss . webservices . integration . deployers . deployment . DeploymentModelBuilder#newDeploymentModel ( DeploymentUnit ) [CODESPLIT] public final void newDeploymentModel ( final DeploymentUnit unit ) { final ArchiveDeployment dep ; if ( unit . hasAttachment ( DEPLOYMENT_KEY ) ) { dep = ( ArchiveDeployment ) unit . getAttachment ( DEPLOYMENT_KEY ) ; } else { dep = newDeployment ( unit ) ; propagateAttachments ( unit , dep ) ; } this . build ( dep , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Http Web Service endpoint . [CODESPLIT] protected final Endpoint newHttpEndpoint ( final String endpointClass , final String endpointName , final Deployment dep ) { if ( endpointName == null ) throw WSLogger . ROOT_LOGGER . nullEndpointName ( ) ; if ( endpointClass == null ) throw WSLogger . ROOT_LOGGER . nullEndpointClass ( ) ; final Endpoint endpoint = this . deploymentModelFactory . newHttpEndpoint ( endpointClass ) ; endpoint . setShortName ( endpointName ) ; endpoint . setType ( endpointType ) ; dep . getService ( ) . addEndpoint ( endpoint ) ; return endpoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new Web Service deployment . [CODESPLIT] private ArchiveDeployment newDeployment ( final DeploymentUnit unit ) { WSLogger . ROOT_LOGGER . tracef ( \"Creating new unified WS deployment model for %s\" , unit ) ; final ResourceRoot deploymentRoot = unit . getAttachment ( Attachments . DEPLOYMENT_ROOT ) ; final VirtualFile root = deploymentRoot != null ? deploymentRoot . getRoot ( ) : null ; final ClassLoader classLoader ; final Module module = unit . getAttachment ( Attachments . MODULE ) ; if ( module == null ) { classLoader = unit . getAttachment ( CLASSLOADER_KEY ) ; if ( classLoader == null ) { throw WSLogger . ROOT_LOGGER . classLoaderResolutionFailed ( unit ) ; } } else { classLoader = module . getClassLoader ( ) ; } ArchiveDeployment parentDep = null ; if ( unit . getParent ( ) != null ) { final Module parentModule = unit . getParent ( ) . getAttachment ( Attachments . MODULE ) ; if ( parentModule == null ) { throw WSLogger . ROOT_LOGGER . classLoaderResolutionFailed ( deploymentRoot ) ; } WSLogger . ROOT_LOGGER . tracef ( \"Creating new unified WS deployment model for %s\" , unit . getParent ( ) ) ; parentDep = this . newDeployment ( null , unit . getParent ( ) . getName ( ) , parentModule . getClassLoader ( ) , null ) ; } final UnifiedVirtualFile uvf = root != null ? new VirtualFileAdaptor ( root ) : new ResourceLoaderAdapter ( classLoader ) ; final ArchiveDeployment dep = this . newDeployment ( parentDep , unit . getName ( ) , classLoader , uvf ) ; //add an AnnotationInfo attachment that uses composite jandex index dep . addAttachment ( AnnotationsInfo . class , new JandexAnnotationsInfo ( unit ) ) ; return dep ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build an { @link URI } using the information extracted from the specified { @link ClientRequestInfo } . The format of the URI built by this method is iiop : // hostname : port . [CODESPLIT] private URI getURI ( final ClientRequestInfo clientRequestInfo ) throws URISyntaxException { final StringBuilder builder = new StringBuilder ( \"iiop:\" ) ; if ( clientRequestInfo instanceof ClientRequestInfoImpl ) { ClientRequestInfoImpl infoImpl = ( ClientRequestInfoImpl ) clientRequestInfo ; CorbaConnection connection = ( CorbaConnection ) infoImpl . connection ( ) ; if ( connection == null ) { return null ; } ContactInfo info = connection . getContactInfo ( ) ; if ( info instanceof SocketOrChannelContactInfoImpl ) { String hostname = ( ( SocketOrChannelContactInfoImpl ) info ) . getHost ( ) ; if ( hostname != null ) builder . append ( \"//\" ) . append ( hostname ) ; int port = ( ( SocketOrChannelContactInfoImpl ) info ) . getPort ( ) ; if ( port > 0 ) builder . append ( \":\" ) . append ( port ) ; } } else { return null ; } return new URI ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an encoded { @link InitialContextToken } with an username / password pair obtained from an Elytron client configuration matched by the specified { @link URI } . [CODESPLIT] private byte [ ] createInitialContextToken ( final URI uri , final CompoundSecMech secMech ) throws Exception { AuthenticationContext authContext = this . authContext == null ? AuthenticationContext . captureCurrent ( ) : this . authContext ; // obtain the configuration that matches the URI. final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT . getAuthenticationConfiguration ( uri , authContext , - 1 , null , null ) ; // get the callback handler from the configuration and use it to obtain a username/password pair. final CallbackHandler handler = AUTH_CONFIG_CLIENT . getCallbackHandler ( configuration ) ; final NameCallback nameCallback = new NameCallback ( \"Username: \" ) ; final PasswordCallback passwordCallback = new PasswordCallback ( \"Password: \" , false ) ; try { handler . handle ( new Callback [ ] { nameCallback , passwordCallback } ) ; } catch ( UnsupportedCallbackException e ) { return NO_AUTHENTICATION_TOKEN ; } // if the name callback contains a valid username we create the initial context token. if ( nameCallback . getName ( ) != null && ! nameCallback . getName ( ) . equals ( AnonymousPrincipal . getInstance ( ) . getName ( ) ) ) { byte [ ] encodedTargetName = secMech . as_context_mech . target_name ; String name = nameCallback . getName ( ) ; if ( name . indexOf ( ' ' ) < 0 ) { byte [ ] decodedTargetName = CSIv2Util . decodeGssExportedName ( encodedTargetName ) ; String targetName = new String ( decodedTargetName , StandardCharsets . UTF_8 ) ; name += \"@\" + targetName ; // \"@default\" } byte [ ] username = name . getBytes ( StandardCharsets . UTF_8 ) ; byte [ ] password = { } ; if ( passwordCallback . getPassword ( ) != null ) password = new String ( passwordCallback . getPassword ( ) ) . getBytes ( StandardCharsets . UTF_8 ) ; // create the initial context token and ASN.1-encode it, as defined in RFC 2743. InitialContextToken authenticationToken = new InitialContextToken ( username , password , encodedTargetName ) ; return CSIv2Util . encodeInitialContextToken ( authenticationToken , codec ) ; } return NO_AUTHENTICATION_TOKEN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JAX - RS annotations are found in the deployment especially if it s an EAR one ) [CODESPLIT] public static boolean isJaxrsDeployment ( DeploymentUnit deploymentUnit ) { DeploymentUnit deployment = deploymentUnit . getParent ( ) == null ? deploymentUnit : deploymentUnit . getParent ( ) ; Boolean val = deployment . getAttachment ( ATTACHMENT_KEY ) ; return val != null && val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void cancel ( ) throws IllegalStateException , EJBException { try { timerService . cancelTimer ( this ) ; } catch ( InterruptedException e ) { throw new EJBException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public TimerHandle getHandle ( ) throws IllegalStateException , EJBException { // make sure it's in correct state this . assertTimerState ( ) ; // for non-persistent timers throws an exception (mandated by EJB3 spec) if ( this . persistent == false ) { throw EjbLogger . EJB3_TIMER_LOGGER . invalidTimerHandlersForPersistentTimers ( \"EJB3.1 Spec 18.2.6\" ) ; } return this . handle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public Date getNextTimeout ( ) throws IllegalStateException , EJBException { // first check the validity of the timer state this . assertTimerState ( ) ; if ( this . nextExpiration == null ) { throw EjbLogger . EJB3_TIMER_LOGGER . noMoreTimeoutForTimer ( this ) ; } return this . nextExpiration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the next timeout of this timer [CODESPLIT] public void setNextTimeout ( Date next ) { if ( next == null ) { setTimerState ( TimerState . EXPIRED , null ) ; } this . nextExpiration = next ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public long getTimeRemaining ( ) throws IllegalStateException , EJBException { // TODO: Rethink this implementation // first check the validity of the timer state this . assertTimerState ( ) ; if ( this . nextExpiration == null ) { throw EjbLogger . EJB3_TIMER_LOGGER . noMoreTimeoutForTimer ( this ) ; } long currentTimeInMillis = System . currentTimeMillis ( ) ; long nextTimeoutInMillis = this . nextExpiration . getTime ( ) ; // if the next expiration is *not* in future and the repeat interval isn't // a positive number (i.e. no repeats) then there won't be any more timeouts. // So throw a NoMoreTimeoutsException. // NOTE: We check for intervalDuration and not just nextExpiration because, // it's a valid case where the nextExpiration is in past (maybe the server was // down when the timeout was expected) //      if (nextTimeoutInMillis < currentTimeInMillis && this.intervalDuration <= 0) //      { //         throw new NoMoreTimeoutsException(\"No more timeouts for timer \" + this); //      } return nextTimeoutInMillis - currentTimeInMillis ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this timer is active . Else returns false . <p > A timer is considered to be active if its { @link TimerState } is neither of the following : <ul > <li > { @link TimerState#CANCELED } < / li > <li > { @link TimerState#EXPIRED } < / li > <li > has not been suspended< / li > < / ul > <p / > And if the corresponding timer service is still up <p / > < / p > [CODESPLIT] public boolean isActive ( ) { return timerService . isStarted ( ) && ! isCanceled ( ) && ! isExpired ( ) && ( timerService . isScheduled ( getId ( ) ) || timerState == TimerState . CREATED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts that the timer is <i > not< / i > in any of the following states : <ul > <li > { @link TimerState#CANCELED } < / li > <li > { @link TimerState#EXPIRED } < / li > < / ul > [CODESPLIT] protected void assertTimerState ( ) { if ( timerState == TimerState . EXPIRED ) throw EjbLogger . EJB3_TIMER_LOGGER . timerHasExpired ( ) ; if ( timerState == TimerState . CANCELED ) throw EjbLogger . EJB3_TIMER_LOGGER . timerWasCanceled ( ) ; AllowedMethodsInformation . checkAllowed ( MethodType . TIMER_SERVICE_METHOD ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the state and timer task executing thread of this timer [CODESPLIT] protected void setTimerState ( TimerState state , Thread thread ) { assert ( ( state == TimerState . IN_TIMEOUT || state == TimerState . RETRY_TIMEOUT ) && thread != null ) || thread == null : \"Invalid to set timer state \" + state + \" with executing Thread \" + thread ; this . timerState = state ; this . executingThread = thread ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges a list of additional JAX - RS deployment data with this lot of deployment data . [CODESPLIT] public void merge ( final List < ResteasyDeploymentData > deploymentData ) throws DeploymentUnitProcessingException { for ( ResteasyDeploymentData data : deploymentData ) { scannedApplicationClasses . addAll ( data . getScannedApplicationClasses ( ) ) ; if ( scanResources ) { scannedResourceClasses . addAll ( data . getScannedResourceClasses ( ) ) ; scannedJndiComponentResources . addAll ( data . getScannedJndiComponentResources ( ) ) ; } if ( scanProviders ) { scannedProviderClasses . addAll ( data . getScannedProviderClasses ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the method roles as a set of { @code Principal } instances . All roles specified in the method - permissions or via { @code RolesAllowed } for this method are wrapped by a { @code SimplePrincipal } . If the method has been added to the exclude - list or annotated with { @code DenyAll } a NOBODY_PRINCIPAL is returned . If the method has been added to the unchecked list or annotated with { @code PermitAll } an ANYBODY_PRINCIPAL is returned . < / p > [CODESPLIT] protected Set < Principal > getMethodRolesAsPrincipals ( ) { Set < Principal > methodRoles = new HashSet < Principal > ( ) ; if ( this . ejbMethodSecurityMetaData . isDenyAll ( ) ) methodRoles . add ( NobodyPrincipal . NOBODY_PRINCIPAL ) ; else if ( this . ejbMethodSecurityMetaData . isPermitAll ( ) ) methodRoles . add ( AnybodyPrincipal . ANYBODY_PRINCIPAL ) ; else { for ( String role : this . ejbMethodSecurityMetaData . getRolesAllowed ( ) ) methodRoles . ( new SimplePrincipal ( role ) ) ; } return methodRoles ; } /**\n     * <p>\n     * Gets the {@code MethodInterfaceType} that corresponds to the specified {@code MethodIntf}.\n     * </p>\n     *\n     * @param viewType the {@code MethodIntf} type to be converted.\n     * @return the converted type or {@code null} if the type cannot be converted.\n     */ protected MethodInterfaceType getMethodInterfaceType ( MethodIntf viewType ) { switch ( viewType ) { case HOME : return MethodInterfaceType . Home ; case LOCAL_HOME : return MethodInterfaceType . LocalHome ; case SERVICE_ENDPOINT : return MethodInterfaceType . ServiceEndpoint ; case LOCAL : return MethodInterfaceType . Local ; case REMOTE : return MethodInterfaceType . Remote ; case TIMER : return MethodInterfaceType . Timer ; case MESSAGE_ENDPOINT : return MethodInterfaceType . MessageEndpoint ; default : return null ; } } /**\n     * <p>\n     * Sets the JACC contextID using a privileged action and returns the previousID from the {@code PolicyContext}.\n     * </p>\n     *\n     * @param contextID the JACC contextID to be set.\n     * @return the previous contextID as retrieved from the {@code PolicyContext}.\n     */ protected String setContextID ( final String contextID ) { if ( ! WildFlySecurityManager . isChecking ( ) ) { final String previousID = PolicyContext . getContextID ( ) ; PolicyContext . setContextID ( contextID ) ; return previousID ; } else { final PrivilegedAction < String > action = new SetContextIDAction ( contextID ) ; return AccessController . doPrivileged ( action ) ; } } /**\n     * PrivilegedAction that sets the {@code PolicyContext} id.\n     */ private static class SetContextIDAction implements PrivilegedAction < String > { private String contextID ; SetContextIDAction ( final String contextID ) { this . contextID = contextID ; } @ Override public String run ( ) { final String previousID = PolicyContext . getContextID ( ) ; PolicyContext . setContextID ( this . contextID ) ; return previousID ; } } } ", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation ---------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . ModuleDefHelper . narrow ( servantToReference ( new ModuleDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof ContainedOperations ) defined_in_id = ( ( ContainedOperations ) defined_in ) . id ( ) ; ModuleDescription md = new ModuleDescription ( name , id , defined_in_id , version ) ; Any any = getORB ( ) . create_any ( ) ; ModuleDescriptionHelper . insert ( any , md ) ; return new Description ( DefinitionKind . dk_Module , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the EE APIs as a dependency to all deployments [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; //add jboss-invocation classes needed by the proxies ModuleDependency invocation = new ModuleDependency ( moduleLoader , JBOSS_INVOCATION_ID , false , false , false , false ) ; invocation . addImportFilter ( PathFilters . is ( \"org/jboss/invocation/proxy/classloading\" ) , true ) ; invocation . addImportFilter ( PathFilters . acceptAll ( ) , false ) ; moduleSpecification . addSystemDependency ( invocation ) ; ModuleDependency ee = new ModuleDependency ( moduleLoader , JBOSS_AS_EE , false , false , false , false ) ; ee . addImportFilter ( PathFilters . is ( \"org/jboss/as/ee/component/serialization\" ) , true ) ; ee . addImportFilter ( PathFilters . is ( \"org/jboss/as/ee/concurrent\" ) , true ) ; ee . addImportFilter ( PathFilters . is ( \"org/jboss/as/ee/concurrent/handle\" ) , true ) ; ee . addImportFilter ( PathFilters . acceptAll ( ) , false ) ; moduleSpecification . addSystemDependency ( ee ) ; // add dep for naming permission moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , ModuleIdentifier . create ( WILDFLY_NAMING ) , false , false , false , false ) ) ; //we always add all Java EE API modules, as the platform spec requires them to always be available //we do not just add the javaee.api module, as this breaks excludes for ( final ModuleIdentifier moduleIdentifier : JAVA_EE_API_MODULES ) { moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , moduleIdentifier , true , false , true , false ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Adds to the deployment the { @link org . wildfly . extension . undertow . security . jaspi . JASPICAuthenticationMechanism } if necessary . The handler will be added if the security domain is configured with JASPI authentication . < / p > [CODESPLIT] private void handleJASPIMechanism ( final DeploymentInfo deploymentInfo ) { ApplicationPolicy applicationPolicy = SecurityConfiguration . getApplicationPolicy ( this . securityDomain ) ; if ( applicationPolicy != null && JASPIAuthenticationInfo . class . isInstance ( applicationPolicy . getAuthenticationInfo ( ) ) ) { String authMethod = null ; LoginConfig loginConfig = deploymentInfo . getLoginConfig ( ) ; if ( loginConfig != null && loginConfig . getAuthMethods ( ) . size ( ) > 0 ) { authMethod = loginConfig . getAuthMethods ( ) . get ( 0 ) . getName ( ) ; } deploymentInfo . setJaspiAuthenticationMechanism ( new JASPICAuthenticationMechanism ( securityDomain , authMethod ) ) ; deploymentInfo . setSecurityContextFactory ( new JASPICSecurityContextFactory ( this . securityDomain ) ) ; deploymentInfo . addOuterHandlerChainWrapper ( next -> new JASPICSecureResponseHandler ( next ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the { @link JACCAuthorizationManager } in the specified { @link DeploymentInfo } if the webapp security domain has defined a JACC authorization module . < / p > [CODESPLIT] private void handleJACCAuthorization ( final DeploymentInfo deploymentInfo ) { // TODO make the authorization manager implementation configurable in Undertow or jboss-web.xml ApplicationPolicy applicationPolicy = SecurityConfiguration . getApplicationPolicy ( this . securityDomain ) ; if ( applicationPolicy != null ) { AuthorizationInfo authzInfo = applicationPolicy . getAuthorizationInfo ( ) ; if ( authzInfo != null ) { for ( AuthorizationModuleEntry entry : authzInfo . getModuleEntries ( ) ) { if ( JACCAuthorizationModule . class . getName ( ) . equals ( entry . getPolicyModuleName ( ) ) ) { deploymentInfo . setAuthorizationManager ( JACCAuthorizationManager . INSTANCE ) ; break ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the authentication method name from the format specified in the web . xml to the format used by { @link javax . servlet . http . HttpServletRequest } . <p / > If the auth method is not recognised then it is returned as - is . [CODESPLIT] private static List < AuthMethodConfig > authMethod ( String configuredMethod ) { if ( configuredMethod == null ) { return Collections . singletonList ( new AuthMethodConfig ( HttpServletRequest . BASIC_AUTH ) ) ; } return AuthMethodParser . parse ( configuredMethod , Collections . singletonMap ( \"CLIENT-CERT\" , HttpServletRequest . CLIENT_CERT_AUTH ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a dependency for the ComponentConfiguration on the remote transaction service if the EJB exposes at least one remote view [CODESPLIT] protected void addRemoteTransactionsDependency ( ) { this . getConfigurators ( ) . add ( new ComponentConfigurator ( ) { @ Override public void configure ( DeploymentPhaseContext context , ComponentDescription description , ComponentConfiguration componentConfiguration ) throws DeploymentUnitProcessingException { if ( this . hasRemoteView ( ( EJBComponentDescription ) description ) ) { // add a dependency on local transaction service componentConfiguration . getCreateDependencies ( ) . add ( ( sb , cs ) -> sb . requires ( TxnServices . JBOSS_TXN_REMOTE_TRANSACTION_SERVICE ) ) ; } } /**\n             * Returns true if the passed EJB component description has at least one remote view\n             * @param ejbComponentDescription\n             * @return\n             */ private boolean hasRemoteView ( final EJBComponentDescription ejbComponentDescription ) { final Set < ViewDescription > views = ejbComponentDescription . getViews ( ) ; for ( final ViewDescription view : views ) { if ( ! ( view instanceof EJBViewDescription ) ) { continue ; } final MethodIntf viewType = ( ( EJBViewDescription ) view ) . getMethodIntf ( ) ; if ( viewType == MethodIntf . REMOTE || viewType == MethodIntf . HOME ) { return true ; } } return false ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up a { [CODESPLIT] protected void addTransactionManagerDependencies ( ) { this . getConfigurators ( ) . add ( new ComponentConfigurator ( ) { @ Override public void configure ( final DeploymentPhaseContext context , final ComponentDescription description , final ComponentConfiguration componentConfiguration ) throws DeploymentUnitProcessingException { componentConfiguration . getCreateDependencies ( ) . add ( new DependencyConfigurator < EJBComponentCreateService > ( ) { @ Override public void configureDependency ( final ServiceBuilder < ? > serviceBuilder , final EJBComponentCreateService ejbComponentCreateService ) throws DeploymentUnitProcessingException { CapabilityServiceSupport support = context . getDeploymentUnit ( ) . getAttachment ( org . jboss . as . server . deployment . Attachments . CAPABILITY_SERVICE_SUPPORT ) ; // add dependency on the local transaction provider serviceBuilder . requires ( support . getCapabilityServiceName ( \"org.wildfly.transactions.global-default-local-provider\" ) ) ; // add dependency on TransactionSynchronizationRegistry serviceBuilder . addDependency ( support . getCapabilityServiceName ( \"org.wildfly.transactions.transaction-synchronization-registry\" ) , TransactionSynchronizationRegistry . class , ejbComponentCreateService . getTransactionSynchronizationRegistryInjector ( ) ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up a { [CODESPLIT] protected void addEJBSuspendHandlerDependency ( ) { getConfigurators ( ) . add ( new ComponentConfigurator ( ) { @ Override public void configure ( final DeploymentPhaseContext context , final ComponentDescription description , final ComponentConfiguration componentConfiguration ) throws DeploymentUnitProcessingException { componentConfiguration . getCreateDependencies ( ) . add ( new DependencyConfigurator < EJBComponentCreateService > ( ) { @ Override public void configureDependency ( final ServiceBuilder < ? > serviceBuilder , final EJBComponentCreateService ejbComponentCreateService ) throws DeploymentUnitProcessingException { serviceBuilder . addDependency ( EJBSuspendHandlerService . SERVICE_NAME , EJBSuspendHandlerService . class , ejbComponentCreateService . getEJBSuspendHandlerInjector ( ) ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up a { [CODESPLIT] protected void addServerSecurityManagerDependency ( ) { getConfigurators ( ) . add ( new ComponentConfigurator ( ) { @ Override public void configure ( final DeploymentPhaseContext context , final ComponentDescription description , final ComponentConfiguration componentConfiguration ) throws DeploymentUnitProcessingException { if ( ! ( ( EJBComponentDescription ) description ) . isSecurityDomainKnown ( ) ) { final DeploymentUnit deploymentUnit = context . getDeploymentUnit ( ) ; final CapabilityServiceSupport support = deploymentUnit . getAttachment ( org . jboss . as . server . deployment . Attachments . CAPABILITY_SERVICE_SUPPORT ) ; componentConfiguration . getCreateDependencies ( ) . add ( new DependencyConfigurator < EJBComponentCreateService > ( ) { @ Override public void configureDependency ( final ServiceBuilder < ? > serviceBuilder , final EJBComponentCreateService ejbComponentCreateService ) throws DeploymentUnitProcessingException { serviceBuilder . addDependency ( support . getCapabilityServiceName ( \"org.wildfly.legacy-security.server-security-manager\" ) , ServerSecurityManager . class , ejbComponentCreateService . getServerSecurityManagerInjector ( ) ) ; } } ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this component description has any security metadata configured at the EJB level . Else returns false . Note that this method does * not * consider method level security metadata . [CODESPLIT] public boolean hasBeanLevelSecurityMetadata ( ) { // if an explicit security-domain is present, then we consider it the bean to be processed by security interceptors if ( securityDomain != null ) { return true ; } // if a run-as is present, then we consider it the bean to be processed by security interceptors if ( runAsRole != null ) { return true ; } // if a run-as-principal is present, then we consider it the bean to be processed by security interceptors if ( runAsPrincipal != null ) { return true ; } // if security roles are configured then we consider the bean to be processed by security interceptors if ( securityRoles != null && ! securityRoles . isEmpty ( ) ) { return true ; } // if security role links are configured then we consider the bean to be processed by security interceptors if ( securityRoleLinks != null && ! securityRoleLinks . isEmpty ( ) ) { return true ; } // if declared roles are configured then we consider the bean to be processed by security interceptors if ( declaredRoles != null && ! declaredRoles . isEmpty ( ) ) { return true ; } // no security metadata at bean level return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a combined map of class and method level container interceptors [CODESPLIT] public Set < InterceptorDescription > getAllContainerInterceptors ( ) { if ( this . allContainerInterceptors == null ) { this . allContainerInterceptors = new HashSet < InterceptorDescription > ( ) ; this . allContainerInterceptors . addAll ( this . classLevelContainerInterceptors ) ; if ( ! this . excludeDefaultContainerInterceptors ) { this . allContainerInterceptors . addAll ( this . defaultContainerInterceptors ) ; } for ( List < InterceptorDescription > interceptors : this . methodLevelContainerInterceptors . values ( ) ) { this . allContainerInterceptors . addAll ( interceptors ) ; } } return this . allContainerInterceptors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Style 1 ( 13 . 3 . 7 . 2 . 1 @1 ) [CODESPLIT] public void setAttribute ( MethodIntf methodIntf , String className , T attribute ) { if ( methodIntf != null && className != null ) throw EjbLogger . ROOT_LOGGER . bothMethodIntAndClassNameSet ( componentName ) ; if ( methodIntf == null ) { style1 . put ( className , attribute ) ; } else perViewStyle1 . put ( methodIntf , attribute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Style 2 ( 13 . 3 . 7 . 2 . 1 @2 ) [CODESPLIT] public void setAttribute ( MethodIntf methodIntf , T transactionAttribute , String methodName ) { if ( methodIntf == null ) style2 . put ( methodName , transactionAttribute ) ; else perViewStyle2 . pick ( methodIntf ) . put ( methodName , transactionAttribute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Style 3 ( 13 . 3 . 7 . 2 . 1 @3 ) [CODESPLIT] public void setAttribute ( MethodIntf methodIntf , T transactionAttribute , final String className , String methodName , String ... methodParams ) { ArrayKey methodParamsKey = new ArrayKey ( ( Object [ ] ) methodParams ) ; if ( methodIntf == null ) style3 . pick ( className ) . pick ( methodName ) . put ( methodParamsKey , transactionAttribute ) ; else perViewStyle3 . pick ( methodIntf ) . pick ( methodName ) . put ( methodParamsKey , transactionAttribute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given transaction specification was expliitly specified at a method level returns false if it was inherited from the default [CODESPLIT] public boolean isMethodLevel ( MethodIntf methodIntf , Method method , MethodIntf defaultMethodIntf ) { assert methodIntf != null : \"methodIntf is null\" ; assert method != null : \"method is null\" ; Method classMethod = resolveRealMethod ( method ) ; String [ ] methodParams = MethodInfoHelper . getCanonicalParameterTypes ( classMethod ) ; final String methodName = classMethod . getName ( ) ; final String className = classMethod . getDeclaringClass ( ) . getName ( ) ; ArrayKey methodParamsKey = new ArrayKey ( ( Object [ ] ) methodParams ) ; T attr = get ( get ( get ( perViewStyle3 , methodIntf ) , methodName ) , methodParamsKey ) ; if ( attr != null ) return true ; attr = get ( get ( perViewStyle2 , methodIntf ) , methodName ) ; if ( attr != null ) return true ; attr = get ( perViewStyle1 , methodIntf ) ; if ( attr != null ) return false ; attr = get ( get ( get ( style3 , className ) , methodName ) , methodParamsKey ) ; if ( attr != null ) return true ; attr = get ( style2 , methodName ) ; if ( attr != null ) return true ; attr = get ( style1 , className ) ; if ( attr != null ) return false ; if ( defaultMethodIntf == null ) { return false ; } else { return isMethodLevel ( defaultMethodIntf , method , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected JaccService < WarMetaData > createService ( String contextId , WarMetaData metaData , Boolean standalone ) { return new WarJACCService ( contextId , metaData , standalone ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo we need to handle cases when deployments reference listeners / server / host directly [CODESPLIT] @ Override public int getPort ( final String protocol , final boolean secure ) { Map < String , UndertowListener > listeners = getListenerMap ( ) ; UndertowListener listener = null ; for ( String p : listeners . keySet ( ) ) { if ( protocol . toLowerCase ( ) . contains ( p ) ) { listener = listeners . get ( p ) ; } } if ( listener != null && listener . getProtocol ( ) == HttpListenerService . PROTOCOL && secure ) { if ( listeners . containsKey ( HttpsListenerService . PROTOCOL ) ) { listener = listeners . get ( HttpsListenerService . PROTOCOL ) ; } else { UndertowLogger . ROOT_LOGGER . secureListenerNotAvailableForPort ( protocol ) ; } } if ( listener != null ) { SocketBinding binding = listener . getSocketBinding ( ) ; return binding . getAbsolutePort ( ) ; } throw UndertowLogger . ROOT_LOGGER . noPortListeningForProtocol ( protocol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link ServiceName } for the { @link EJBViewMethodSecurityAttributesService } [CODESPLIT] public static ServiceName getServiceName ( final String appName , final String moduleName , final String beanName , final String viewClassName ) { final ServiceName serviceName ; if ( appName != null ) { serviceName = BASE_SERVICE_NAME . append ( appName ) ; } else { serviceName = BASE_SERVICE_NAME ; } return serviceName . append ( moduleName ) . append ( beanName ) . append ( viewClassName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the abbreviated name of the marshaller for given <code > Class< / code > . <p / > <p > Abbreviated names of marshallers for basic types follow the usual Java convention : <br > <pre > type abbrev name boolean Z byte B char C double D float F int I long J short S void V < / pre > <p / > <p > The abbreviated names of marshallers for object types are : <br > <pre > java . lang . String G ( strinG ) RMI remote interface R + interfaceName RMI abstract interface A serializable E ( sErializablE ) valuetype L + className externalizable X ( eXternalizable ) org . omg . CORBA . Object M ( oMg ) IDL interface N + interfaceName java . lang . Object O < / pre > <p / > <p > As an example : the abbreviated name of a marshaller for a valuetype class named <code > Foo< / code > is the string <code > LFoo < / code > . [CODESPLIT] public static String abbrevFor ( Class clz ) { if ( clz == Boolean . TYPE ) { return \"Z\" ; } else if ( clz == Byte . TYPE ) { return \"B\" ; } else if ( clz == Character . TYPE ) { return \"C\" ; } else if ( clz == Double . TYPE ) { return \"D\" ; } else if ( clz == Float . TYPE ) { return \"F\" ; } else if ( clz == Integer . TYPE ) { return \"I\" ; } else if ( clz == Long . TYPE ) { return \"J\" ; } else if ( clz == Short . TYPE ) { return \"S\" ; } else if ( clz == Void . TYPE ) { return \"V\" ; } else if ( clz == String . class ) { return \"G\" ; // strinG } else if ( RmiIdlUtil . isRMIIDLRemoteInterface ( clz ) ) { return \"R\" + clz . getName ( ) ; // Remote interface } else if ( clz == org . omg . CORBA . Object . class ) { return \"M\" ; // oMg (CORBA Object) } else if ( org . omg . CORBA . Object . class . isAssignableFrom ( clz ) ) { return \"N\" + clz . getName ( ) ; // IDL iNterface } else if ( IDLEntity . class . isAssignableFrom ( clz ) ) { return \"L\" + clz . getName ( ) ; // vaLuetype } else if ( clz == Serializable . class ) { return \"E\" ; // sErializablE } else if ( RmiIdlUtil . isAbstractInterface ( clz ) ) { return \"A\" ; // Abstract interface } else if ( Serializable . class . isAssignableFrom ( clz ) ) { return \"L\" + clz . getName ( ) ; // vaLuetype } else if ( Externalizable . class . isAssignableFrom ( clz ) ) { return \"X\" ; // eXternalizable } else if ( clz == Object . class ) { return \"O\" ; // Object } else { return \"L\" + clz . getName ( ) ; // vaLuetype } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > CDRStreamReader< / code > given an abbreviated name and a <code > ClassLoader< / code > for valuetype classes . [CODESPLIT] public static CDRStreamReader readerFor ( String s , ClassLoader cl ) { switch ( s . charAt ( 0 ) ) { case ' ' : return AbstractInterfaceReader . instance ; case ' ' : return ByteReader . instance ; case ' ' : return CharReader . instance ; case ' ' : return DoubleReader . instance ; case ' ' : return SerializableReader . instance ; case ' ' : return FloatReader . instance ; case ' ' : return StringReader . instance ; case ' ' : return IntReader . instance ; case ' ' : return LongReader . instance ; case ' ' : try { // Use Class.forName() (rather than cl.loadClass()), because // Class.forName() loads Java array types (which are valuetypes). return new ValuetypeReader ( Class . forName ( s . substring ( 1 ) , true , cl ) ) ; } catch ( ClassNotFoundException e ) { throw IIOPLogger . ROOT_LOGGER . errorLoadingClass ( s . substring ( 1 ) , e ) ; } case ' ' : return CorbaObjectReader . instance ; case ' ' : try { return new IdlInterfaceReader ( cl . loadClass ( s . substring ( 1 ) ) ) ; } catch ( ClassNotFoundException e ) { throw IIOPLogger . ROOT_LOGGER . errorLoadingClass ( s . substring ( 1 ) , e ) ; } case ' ' : return ObjectReader . instance ; case ' ' : try { return new RemoteReader ( cl . loadClass ( s . substring ( 1 ) ) ) ; } catch ( ClassNotFoundException e ) { throw IIOPLogger . ROOT_LOGGER . errorLoadingClass ( s . substring ( 1 ) , e ) ; } case ' ' : return ShortReader . instance ; case ' ' : return null ; case ' ' : return ExternalizableReader . instance ; case ' ' : return BooleanReader . instance ; default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > CDRStreamWriter< / code > given an abbreviated name and a <code > ClassLoader< / code > for valuetype classes . [CODESPLIT] public static CDRStreamWriter writerFor ( String s , ClassLoader cl ) { switch ( s . charAt ( 0 ) ) { case ' ' : return AbstractInterfaceWriter . instance ; case ' ' : return ByteWriter . instance ; case ' ' : return CharWriter . instance ; case ' ' : return DoubleWriter . instance ; case ' ' : return SerializableWriter . instance ; case ' ' : return FloatWriter . instance ; case ' ' : return StringWriter . instance ; case ' ' : return IntWriter . instance ; case ' ' : return LongWriter . instance ; case ' ' : try { // Use Class.forName() (rather than cl.loadClass()), because // Class.forName() loads Java array types (which are valuetypes). return new ValuetypeWriter ( Class . forName ( s . substring ( 1 ) , true , cl ) ) ; } catch ( ClassNotFoundException e ) { throw IIOPLogger . ROOT_LOGGER . errorLoadingClass ( s . substring ( 1 ) , e ) ; } case ' ' : return CorbaObjectWriter . instance ; case ' ' : try { return new IdlInterfaceWriter ( cl . loadClass ( s . substring ( 1 ) ) ) ; } catch ( ClassNotFoundException e ) { throw IIOPLogger . ROOT_LOGGER . errorLoadingClass ( s . substring ( 1 ) , e ) ; } case ' ' : return ObjectWriter . instance ; case ' ' : return RemoteWriter . instance ; case ' ' : return ShortWriter . instance ; case ' ' : return null ; case ' ' : return ExternalizableWriter . instance ; case ' ' : return BooleanWriter . instance ; default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > CDRStreamReader< / code > for a given <code > Class< / code > . [CODESPLIT] public static CDRStreamReader readerFor ( Class clz ) { if ( clz == Boolean . TYPE ) { return BooleanReader . instance ; } else if ( clz == Byte . TYPE ) { return ByteReader . instance ; } else if ( clz == Character . TYPE ) { return CharReader . instance ; } else if ( clz == Double . TYPE ) { return DoubleReader . instance ; } else if ( clz == Float . TYPE ) { return FloatReader . instance ; } else if ( clz == Integer . TYPE ) { return IntReader . instance ; } else if ( clz == Long . TYPE ) { return LongReader . instance ; } else if ( clz == Short . TYPE ) { return ShortReader . instance ; } else if ( clz == Void . TYPE ) { return null ; } else if ( clz == String . class ) { return StringReader . instance ; } else if ( RmiIdlUtil . isRMIIDLRemoteInterface ( clz ) ) { return new RemoteReader ( clz ) ; } else if ( clz == org . omg . CORBA . Object . class ) { return CorbaObjectReader . instance ; } else if ( org . omg . CORBA . Object . class . isAssignableFrom ( clz ) ) { return new IdlInterfaceReader ( clz ) ; } else if ( IDLEntity . class . isAssignableFrom ( clz ) ) { return new ValuetypeReader ( clz ) ; } else if ( clz == Serializable . class ) { return SerializableReader . instance ; } else if ( RmiIdlUtil . isAbstractInterface ( clz ) ) { return AbstractInterfaceReader . instance ; } else if ( Serializable . class . isAssignableFrom ( clz ) ) { return new ValuetypeReader ( clz ) ; } else if ( Externalizable . class . isAssignableFrom ( clz ) ) { return ExternalizableReader . instance ; } else if ( clz == Object . class ) { return ObjectReader . instance ; } else { return new ValuetypeReader ( clz ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > CDRStreamWriter< / code > for a given <code > Class< / code > . [CODESPLIT] public static CDRStreamWriter writerFor ( Class clz ) { if ( clz == Boolean . TYPE ) { return BooleanWriter . instance ; } else if ( clz == Byte . TYPE ) { return ByteWriter . instance ; } else if ( clz == Character . TYPE ) { return CharWriter . instance ; } else if ( clz == Double . TYPE ) { return DoubleWriter . instance ; } else if ( clz == Float . TYPE ) { return FloatWriter . instance ; } else if ( clz == Integer . TYPE ) { return IntWriter . instance ; } else if ( clz == Long . TYPE ) { return LongWriter . instance ; } else if ( clz == Short . TYPE ) { return ShortWriter . instance ; } else if ( clz == String . class ) { return StringWriter . instance ; } else if ( clz == Void . TYPE ) { return null ; } else if ( RmiIdlUtil . isRMIIDLRemoteInterface ( clz ) ) { return RemoteWriter . instance ; } else if ( clz == org . omg . CORBA . Object . class ) { return CorbaObjectWriter . instance ; } else if ( org . omg . CORBA . Object . class . isAssignableFrom ( clz ) ) { return new IdlInterfaceWriter ( clz ) ; } else if ( IDLEntity . class . isAssignableFrom ( clz ) ) { return new ValuetypeWriter ( clz ) ; } else if ( clz == Serializable . class ) { return SerializableWriter . instance ; } else if ( RmiIdlUtil . isAbstractInterface ( clz ) ) { return AbstractInterfaceWriter . instance ; } else if ( Serializable . class . isAssignableFrom ( clz ) ) { return new ValuetypeWriter ( clz ) ; } else if ( Externalizable . class . isAssignableFrom ( clz ) ) { return ExternalizableWriter . instance ; } else if ( clz == Object . class ) { return ObjectWriter . instance ; } else { return new ValuetypeWriter ( clz ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up all resource injections for a class . This takes into account injections that have been specified in the module and component deployment descriptors <p / > Note that this does not take superclasses into consideration only injections on the current class [CODESPLIT] protected void mergeInjectionsForClass ( final Class < ? > clazz , final Class < ? > actualClass , final EEModuleClassDescription classDescription , final EEModuleDescription moduleDescription , final DeploymentReflectionIndex deploymentReflectionIndex , final ComponentDescription description , final ComponentConfiguration configuration , final DeploymentPhaseContext context , final Deque < InterceptorFactory > injectors , final Object instanceKey , final Deque < InterceptorFactory > uninjectors , boolean metadataComplete ) throws DeploymentUnitProcessingException { final Map < InjectionTarget , ResourceInjectionConfiguration > mergedInjections = new HashMap < InjectionTarget , ResourceInjectionConfiguration > ( ) ; if ( classDescription != null && ! metadataComplete ) { mergedInjections . putAll ( classDescription . getInjectionConfigurations ( ) ) ; } mergedInjections . putAll ( moduleDescription . getResourceInjections ( clazz . getName ( ) ) ) ; mergedInjections . putAll ( description . getResourceInjections ( clazz . getName ( ) ) ) ; for ( final ResourceInjectionConfiguration injectionConfiguration : mergedInjections . values ( ) ) { if ( ! moduleDescription . isAppClient ( ) && injectionConfiguration . getTarget ( ) . isStatic ( context . getDeploymentUnit ( ) ) ) { ROOT_LOGGER . debugf ( \"Injection for a member with static modifier is only acceptable on application clients, ignoring injection for target %s\" , injectionConfiguration . getTarget ( ) ) ; continue ; } if ( injectionConfiguration . getTarget ( ) instanceof MethodInjectionTarget ) { //we need to make sure that if this is a method injection it has not been overriden final MethodInjectionTarget mt = ( MethodInjectionTarget ) injectionConfiguration . getTarget ( ) ; Method method = mt . getMethod ( deploymentReflectionIndex , clazz ) ; if ( ! isNotOverriden ( clazz , method , actualClass , deploymentReflectionIndex ) ) { continue ; } } final Object valueContextKey = new Object ( ) ; final InjectedValue < ManagedReferenceFactory > managedReferenceFactoryValue = new InjectedValue < ManagedReferenceFactory > ( ) ; configuration . getStartDependencies ( ) . add ( new ComponentDescription . InjectedConfigurator ( injectionConfiguration , configuration , context , managedReferenceFactoryValue ) ) ; injectors . addFirst ( injectionConfiguration . getTarget ( ) . createInjectionInterceptorFactory ( instanceKey , valueContextKey , managedReferenceFactoryValue , context . getDeploymentUnit ( ) , injectionConfiguration . isOptional ( ) ) ) ; uninjectors . addLast ( new ImmediateInterceptorFactory ( new ManagedReferenceReleaseInterceptor ( valueContextKey ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check one and only one of the 2 elements has been defined [CODESPLIT] protected static void checkOnlyOneOfElements ( XMLExtendedStreamReader reader , Set < Element > seen , Element element1 , Element element2 ) throws XMLStreamException { if ( ! seen . contains ( element1 ) && ! seen . contains ( element2 ) ) { throw new XMLStreamException ( MessagingLogger . ROOT_LOGGER . required ( element1 . getLocalName ( ) , element2 . getLocalName ( ) ) , reader . getLocation ( ) ) ; } if ( seen . contains ( element1 ) && seen . contains ( element2 ) ) { throw new XMLStreamException ( MessagingLogger . ROOT_LOGGER . onlyOneRequired ( element1 . getLocalName ( ) , element2 . getLocalName ( ) ) , reader . getLocation ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note the access to the { [CODESPLIT] private void refreshChildren ( ) { final List < JobExecution > executions = new ArrayList <> ( ) ; // Casting to (Supplier<List<JobInstance>>) is done here on purpose as a workaround for a bug in 1.8.0_45 final List < JobInstance > instances = jobOperator . allowMissingJob ( ( Supplier < List < JobInstance > > ) ( ) -> jobOperator . getJobInstances ( jobName , 0 , jobOperator . getJobInstanceCount ( jobName ) ) , Collections . emptyList ( ) ) ; for ( JobInstance instance : instances ) { executions . addAll ( jobOperator . getJobExecutions ( instance ) ) ; } children . clear ( ) ; for ( JobExecution execution : executions ) { final String name = Long . toString ( execution . getExecutionId ( ) ) ; children . add ( name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ AS7 - 5850 ] Core queues created with ActiveMQ API does not create WildFly resources [CODESPLIT] static boolean forwardToRuntimeQueue ( OperationContext context , ModelNode operation , OperationStepHandler handler ) { PathAddress address = context . getCurrentAddress ( ) ; // do not forward if the current operation is for a runtime-queue already: if ( RUNTIME_QUEUE . equals ( address . getLastElement ( ) . getKey ( ) ) ) { return false ; } String queueName = address . getLastElement ( ) . getValue ( ) ; PathAddress activeMQPathAddress = MessagingServices . getActiveMQServerPathAddress ( address ) ; if ( context . readResourceFromRoot ( activeMQPathAddress , false ) . hasChild ( address . getLastElement ( ) ) ) { return false ; } else { // there is no registered queue resource, forward to the runtime-queue address instead ModelNode forwardOperation = operation . clone ( ) ; forwardOperation . get ( ModelDescriptionConstants . OP_ADDR ) . set ( activeMQPathAddress . append ( RUNTIME_QUEUE , queueName ) . toModelNode ( ) ) ; context . addStep ( forwardOperation , handler , OperationContext . Stage . RUNTIME , true ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* define the attributes in the * same order than the XSD * to write them to the XML configuration by simply iterating over the array [CODESPLIT] private static ConnectionFactoryAttribute [ ] define ( ConnectionFactoryAttribute [ ] specific , ConnectionFactoryAttribute ... common ) { int size = common . length + specific . length ; ConnectionFactoryAttribute [ ] result = new ConnectionFactoryAttribute [ size ] ; arraycopy ( specific , 0 , result , 0 , specific . length ) ; for ( int i = 0 ; i < common . length ; i ++ ) { ConnectionFactoryAttribute attr = common [ i ] ; AttributeDefinition definition = attr . getDefinition ( ) ; ConnectionFactoryAttribute newAttr ; // replace the reconnect-attempts attribute to use a different default value for pooled CF if ( definition == Common . RECONNECT_ATTEMPTS ) { AttributeDefinition copy = copy ( Pooled . RECONNECT_ATTEMPTS , AttributeAccess . Flag . RESTART_ALL_SERVICES ) ; newAttr = ConnectionFactoryAttribute . create ( copy , Pooled . RECONNECT_ATTEMPTS_PROP_NAME , true ) ; } else { AttributeDefinition copy = copy ( definition , AttributeAccess . Flag . RESTART_ALL_SERVICES ) ; newAttr = ConnectionFactoryAttribute . create ( copy , attr . getPropertyName ( ) , attr . isResourceAdapterProperty ( ) , attr . isInboundConfig ( ) ) ; } result [ specific . length + i ] = newAttr ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get temp bean info . [CODESPLIT] protected static BeanInfo getTempBeanInfo ( ConfigVisitor visitor , String className ) { return getTempBeanInfo ( visitor , getType ( visitor , className ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get temp bean info . [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" } ) protected static BeanInfo getTempBeanInfo ( ConfigVisitor visitor , Class < ? > clazz ) { return new DefaultBeanInfo ( visitor . getReflectionIndex ( ) , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load class . [CODESPLIT] protected static Class < ? > getType ( ConfigVisitor visitor , String className ) { if ( className != null ) { try { return visitor . getModule ( ) . getClassLoader ( ) . loadClass ( className ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get component type . [CODESPLIT] static Type getComponentType ( ParameterizedType type , int index ) { Type [ ] tp = type . getActualTypeArguments ( ) ; if ( index + 1 > tp . length ) return null ; return tp [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a resource that represents an Elytron - compatible realm that can be exported by the legacy security subsystem . The constructed { @code SecurityRealm } wraps a legacy { @code SecurityDomainContext } and delegates authentication decisions to that context . [CODESPLIT] public static ResourceDefinition getElytronRealmResourceDefinition ( ) { final AttributeDefinition [ ] attributes = new AttributeDefinition [ ] { LEGACY_JAAS_CONFIG , APPLY_ROLE_MAPPERS } ; final AbstractAddStepHandler addHandler = new BasicAddHandler < SecurityRealm > ( attributes , SECURITY_REALM_RUNTIME_CAPABILITY ) { @ Override protected BasicService . ValueSupplier < SecurityRealm > getValueSupplier ( ServiceBuilder < SecurityRealm > serviceBuilder , OperationContext context , ModelNode model ) throws OperationFailedException { final String legacyJAASConfig = asStringIfDefined ( context , LEGACY_JAAS_CONFIG , model ) ; final boolean applyRoleMappers = APPLY_ROLE_MAPPERS . resolveModelAttribute ( context , model ) . asBoolean ( ) ; final InjectedValue < SecurityDomainContext > securityDomainContextInjector = new InjectedValue <> ( ) ; if ( legacyJAASConfig != null ) { serviceBuilder . addDependency ( SecurityDomainService . SERVICE_NAME . append ( legacyJAASConfig ) , SecurityDomainContext . class , securityDomainContextInjector ) ; } return ( ) -> { final SecurityDomainContext domainContext = securityDomainContextInjector . getValue ( ) ; return new SecurityDomainContextRealm ( domainContext , applyRoleMappers ) ; } ; } } ; return new BasicResourceDefinition ( Constants . ELYTRON_REALM , addHandler , attributes , SECURITY_REALM_RUNTIME_CAPABILITY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a resource that represents an Elytron - compatible key store that can be exported by a JSSE - enabled domain in the legacy security subsystem . [CODESPLIT] public static ResourceDefinition getElytronKeyStoreResourceDefinition ( ) { final AttributeDefinition [ ] attributes = new AttributeDefinition [ ] { LEGACY_JSSE_CONFIG } ; final AbstractAddStepHandler addHandler = new BasicAddHandler < KeyStore > ( attributes , KEY_STORE_RUNTIME_CAPABILITY ) { @ Override protected BasicService . ValueSupplier < KeyStore > getValueSupplier ( ServiceBuilder < KeyStore > serviceBuilder , OperationContext context , ModelNode model ) throws OperationFailedException { final String legacyJSSEConfig = asStringIfDefined ( context , LEGACY_JSSE_CONFIG , model ) ; final InjectedValue < SecurityDomainContext > securityDomainContextInjector = new InjectedValue <> ( ) ; if ( legacyJSSEConfig != null ) { serviceBuilder . addDependency ( SecurityDomainService . SERVICE_NAME . append ( legacyJSSEConfig ) , SecurityDomainContext . class , securityDomainContextInjector ) ; } return ( ) -> { final SecurityDomainContext domainContext = securityDomainContextInjector . getValue ( ) ; final JSSESecurityDomain jsseDomain = domainContext . getJSSE ( ) ; if ( jsseDomain == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateJSSEConfig ( legacyJSSEConfig ) ; } final KeyStore keyStore = jsseDomain . getKeyStore ( ) ; if ( keyStore == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateComponentInJSSEDomain ( \"KeyStore\" , legacyJSSEConfig ) ; } return keyStore ; } ; } } ; return new BasicResourceDefinition ( Constants . ELYTRON_KEY_STORE , addHandler , attributes , KEY_STORE_RUNTIME_CAPABILITY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a resource that represents Elytron - compatible key managers that can be exported by a JSSE - enabled domain in the legacy security subsystem . [CODESPLIT] public static ResourceDefinition getElytronKeyManagersResourceDefinition ( ) { final AttributeDefinition [ ] attributes = new AttributeDefinition [ ] { LEGACY_JSSE_CONFIG } ; final AbstractAddStepHandler addHandler = new BasicAddHandler < KeyManager > ( attributes , KEY_MANAGER_RUNTIME_CAPABILITY ) { @ Override protected BasicService . ValueSupplier < KeyManager > getValueSupplier ( ServiceBuilder < KeyManager > serviceBuilder , OperationContext context , ModelNode model ) throws OperationFailedException { final String legacyJSSEConfig = asStringIfDefined ( context , LEGACY_JSSE_CONFIG , model ) ; final InjectedValue < SecurityDomainContext > securityDomainContextInjector = new InjectedValue <> ( ) ; if ( legacyJSSEConfig != null ) { serviceBuilder . addDependency ( SecurityDomainService . SERVICE_NAME . append ( legacyJSSEConfig ) , SecurityDomainContext . class , securityDomainContextInjector ) ; } return ( ) -> { final SecurityDomainContext domainContext = securityDomainContextInjector . getValue ( ) ; final JSSESecurityDomain jsseDomain = domainContext . getJSSE ( ) ; if ( jsseDomain == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateJSSEConfig ( legacyJSSEConfig ) ; } final KeyManager [ ] keyManagers = jsseDomain . getKeyManagers ( ) ; if ( keyManagers == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateComponentInJSSEDomain ( \"KeyManager\" , legacyJSSEConfig ) ; } for ( KeyManager keyManager : keyManagers ) { if ( keyManager instanceof X509ExtendedKeyManager ) { return keyManager ; } } throw SecurityLogger . ROOT_LOGGER . expectedManagerTypeNotFound ( \"KeyManager\" , X509ExtendedKeyManager . class . getSimpleName ( ) , legacyJSSEConfig ) ; } ; } } ; return new BasicResourceDefinition ( Constants . ELYTRON_KEY_MANAGER , addHandler , attributes , KEY_MANAGER_RUNTIME_CAPABILITY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a resource that represents Elytron - compatible trust managers that can be exported by a JSSE - enabled domain in the legacy security subsystem . [CODESPLIT] public static ResourceDefinition getElytronTrustManagersResourceDefinition ( ) { final AttributeDefinition [ ] attributes = new AttributeDefinition [ ] { LEGACY_JSSE_CONFIG } ; final AbstractAddStepHandler addHandler = new BasicAddHandler < TrustManager > ( attributes , TRUST_MANAGER_RUNTIME_CAPABILITY ) { @ Override protected BasicService . ValueSupplier < TrustManager > getValueSupplier ( ServiceBuilder < TrustManager > serviceBuilder , OperationContext context , ModelNode model ) throws OperationFailedException { final String legacyJSSEConfig = asStringIfDefined ( context , LEGACY_JSSE_CONFIG , model ) ; final InjectedValue < SecurityDomainContext > securityDomainContextInjector = new InjectedValue <> ( ) ; if ( legacyJSSEConfig != null ) { serviceBuilder . addDependency ( SecurityDomainService . SERVICE_NAME . append ( legacyJSSEConfig ) , SecurityDomainContext . class , securityDomainContextInjector ) ; } return ( ) -> { final SecurityDomainContext domainContext = securityDomainContextInjector . getValue ( ) ; final JSSESecurityDomain jsseDomain = domainContext . getJSSE ( ) ; if ( jsseDomain == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateJSSEConfig ( legacyJSSEConfig ) ; } final TrustManager [ ] trustManagers = jsseDomain . getTrustManagers ( ) ; if ( trustManagers == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateComponentInJSSEDomain ( \"TrustManager\" , legacyJSSEConfig ) ; } for ( TrustManager trustManager : trustManagers ) { if ( trustManager instanceof X509ExtendedTrustManager ) return trustManager ; } throw SecurityLogger . ROOT_LOGGER . expectedManagerTypeNotFound ( \"TrustManager\" , X509ExtendedTrustManager . class . getSimpleName ( ) , legacyJSSEConfig ) ; } ; } } ; return new BasicResourceDefinition ( Constants . ELYTRON_TRUST_MANAGER , addHandler , attributes , TRUST_MANAGER_RUNTIME_CAPABILITY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a CompoundName given a string in INS syntax . [CODESPLIT] public Name parse ( String name ) throws NamingException { Vector comps = insStringToStringifiedComps ( name ) ; return new CNCompoundName ( comps . elements ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a NameComponent [] from a Name structure . Used by CNCtx to convert the input Name arg into a NameComponent [] . [CODESPLIT] static NameComponent [ ] nameToCosName ( Name name ) throws InvalidNameException { int len = name . size ( ) ; if ( len == 0 ) { return new NameComponent [ 0 ] ; } NameComponent [ ] answer = new NameComponent [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { answer [ i ] = parseComponent ( name . get ( i ) ) ; } return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the INS stringified form of a NameComponent [] . Used by CNCtx . getNameInNamespace () CNCompoundName . toString () . [CODESPLIT] static String cosNameToInsString ( NameComponent [ ] cname ) { StringBuffer str = new StringBuffer ( ) ; for ( int i = 0 ; i < cname . length ; i ++ ) { if ( i > 0 ) { str . append ( compSeparator ) ; } str . append ( stringifyComponent ( cname [ i ] ) ) ; } return str . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a CompositeName from a NameComponent [] . Used by ExceptionMapper and CNBindingEnumeration to convert a NameComponent [] into a composite name . [CODESPLIT] static Name cosNameToName ( NameComponent [ ] cname ) { Name nm = new CompositeName ( ) ; for ( int i = 0 ; cname != null && i < cname . length ; i ++ ) { try { nm . add ( stringifyComponent ( cname [ i ] ) ) ; } catch ( InvalidNameException e ) { // ignore } } return nm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an INS - syntax string name into a Vector in which each element of the vector contains a stringified form of a NameComponent . [CODESPLIT] private static Vector insStringToStringifiedComps ( String str ) throws InvalidNameException { int len = str . length ( ) ; Vector components = new Vector ( 10 ) ; char [ ] id = new char [ len ] ; char [ ] kind = new char [ len ] ; int idCount , kindCount ; boolean idMode ; for ( int i = 0 ; i < len ; ) { idCount = kindCount = 0 ; // reset for new component idMode = true ; // always start off parsing id while ( i < len ) { if ( str . charAt ( i ) == compSeparator ) { break ; } else if ( str . charAt ( i ) == escapeChar ) { if ( i + 1 >= len ) { throw IIOPLogger . ROOT_LOGGER . unescapedCharacter ( str ) ; } else if ( isMeta ( str . charAt ( i + 1 ) ) ) { ++ i ; // skip escape and let meta through if ( idMode ) { id [ idCount ++ ] = str . charAt ( i ++ ) ; } else { kind [ kindCount ++ ] = str . charAt ( i ++ ) ; } } else { throw IIOPLogger . ROOT_LOGGER . invalidEscapedCharacter ( str ) ; } } else if ( idMode && str . charAt ( i ) == kindSeparator ) { // just look for the first kindSeparator ++ i ; // skip kind separator idMode = false ; } else { if ( idMode ) { id [ idCount ++ ] = str . charAt ( i ++ ) ; } else { kind [ kindCount ++ ] = str . charAt ( i ++ ) ; } } } components . addElement ( stringifyComponent ( new NameComponent ( new String ( id , 0 , idCount ) , new String ( kind , 0 , kindCount ) ) ) ) ; if ( i < len ) { ++ i ; // skip separator } } return components ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a NameComponent given its stringified form . [CODESPLIT] private static NameComponent parseComponent ( String compStr ) throws InvalidNameException { NameComponent comp = new NameComponent ( ) ; int kindSep = - 1 ; int len = compStr . length ( ) ; int j = 0 ; char [ ] newStr = new char [ len ] ; boolean escaped = false ; // Find the kind separator for ( int i = 0 ; i < len && kindSep < 0 ; i ++ ) { if ( escaped ) { newStr [ j ++ ] = compStr . charAt ( i ) ; escaped = false ; } else if ( compStr . charAt ( i ) == escapeChar ) { if ( i + 1 >= len ) { throw IIOPLogger . ROOT_LOGGER . unescapedCharacter ( compStr ) ; } else if ( isMeta ( compStr . charAt ( i + 1 ) ) ) { escaped = true ; } else { throw IIOPLogger . ROOT_LOGGER . invalidEscapedCharacter ( compStr ) ; } } else if ( compStr . charAt ( i ) == kindSeparator ) { kindSep = i ; } else { newStr [ j ++ ] = compStr . charAt ( i ) ; } } // Set id comp . id = new String ( newStr , 0 , j ) ; // Set kind if ( kindSep < 0 ) { comp . kind = \"\" ; // no kind separator } else { // unescape kind j = 0 ; escaped = false ; for ( int i = kindSep + 1 ; i < len ; i ++ ) { if ( escaped ) { newStr [ j ++ ] = compStr . charAt ( i ) ; escaped = false ; } else if ( compStr . charAt ( i ) == escapeChar ) { if ( i + 1 >= len ) { throw IIOPLogger . ROOT_LOGGER . unescapedCharacter ( compStr ) ; } else if ( isMeta ( compStr . charAt ( i + 1 ) ) ) { escaped = true ; } else { throw IIOPLogger . ROOT_LOGGER . invalidEscapedCharacter ( compStr ) ; } } else { newStr [ j ++ ] = compStr . charAt ( i ) ; } } comp . kind = new String ( newStr , 0 , j ) ; } return comp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string with . \\ / escaped . Used when stringifying the name into its INS stringified form . [CODESPLIT] private static String escape ( String str ) { if ( str . indexOf ( kindSeparator ) < 0 && str . indexOf ( compSeparator ) < 0 && str . indexOf ( escapeChar ) < 0 ) { return str ; // no meta characters to escape } else { int len = str . length ( ) ; int j = 0 ; char [ ] newStr = new char [ len + len ] ; for ( int i = 0 ; i < len ; i ++ ) { if ( isMeta ( str . charAt ( i ) ) ) { newStr [ j ++ ] = escapeChar ; // escape meta character } newStr [ j ++ ] = str . charAt ( i ) ; } return new String ( newStr , 0 , j ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TransformedOperation transformOperation ( TransformationContext context , PathAddress address , ModelNode operation ) { ModelNode legacyOperation = Operations . createDescribeOperation ( this . addressTransformer . transform ( address ) ) ; return new TransformedOperation ( legacyOperation , OperationResultTransformer . ORIGINAL_RESULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unexport this object . [CODESPLIT] public void shutdown ( ) { POA poa = getPOA ( ) ; try { poa . deactivate_object ( poa . reference_to_id ( getReference ( ) ) ) ; } catch ( UserException ex ) { IIOPLogger . ROOT_LOGGER . warnCouldNotDeactivateIRObject ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a servant to a reference . [CODESPLIT] protected org . omg . CORBA . Object servantToReference ( Servant servant ) { byte [ ] id = getObjectId ( ) ; try { repository . poa . activate_object_with_id ( id , servant ) ; org . omg . CORBA . Object ref = repository . poa . id_to_reference ( id ) ; return ref ; } catch ( WrongPolicy ex ) { IIOPLogger . ROOT_LOGGER . debug ( \"Exception converting CORBA servant to reference\" , ex ) ; } catch ( ServantAlreadyActive ex ) { IIOPLogger . ROOT_LOGGER . debug ( \"Exception converting CORBA servant to reference\" , ex ) ; } catch ( ObjectAlreadyActive ex ) { IIOPLogger . ROOT_LOGGER . debug ( \"Exception converting CORBA servant to reference\" , ex ) ; } catch ( ObjectNotActive ex ) { IIOPLogger . ROOT_LOGGER . debug ( \"Exception converting CORBA servant to reference\" , ex ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The stop () call doesn t do that so it s probably not needed [CODESPLIT] private void cleanupStartAsync ( final StartContext context , final String deploymentName , final Throwable cause , final ServiceName duServiceName , final ClassLoader toUse ) { ExecutorService executorService = getLifecycleExecutorService ( ) ; Runnable r = new Runnable ( ) { @ Override public void run ( ) { ClassLoader old = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; try { WritableServiceBasedNamingStore . pushOwner ( duServiceName ) ; WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( toUse ) ; unregisterAll ( deploymentName ) ; } finally { try { context . failed ( ConnectorLogger . ROOT_LOGGER . failedToStartRaDeployment ( cause , deploymentName ) ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( old ) ; WritableServiceBasedNamingStore . popOwner ( ) ; } } } } ; try { executorService . execute ( r ) ; } catch ( RejectedExecutionException e ) { r . run ( ) ; } finally { context . asynchronous ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to authenticate and authorize an username with the specified password evidence . [CODESPLIT] private SecurityIdentity authenticate ( final String username , final String password ) { ServerAuthenticationContext context = this . securityDomain . createNewAuthenticationContext ( ) ; PasswordGuessEvidence evidence = null ; try { if ( password == null ) { if ( username == null ) { if ( context . authorizeAnonymous ( ) ) { context . succeed ( ) ; return context . getAuthorizedIdentity ( ) ; } else { context . fail ( ) ; return null ; } } else { // treat a non-null user name with a null password as a auth failure context . fail ( ) ; return null ; } } context . setAuthenticationName ( username ) ; evidence = new PasswordGuessEvidence ( password . toCharArray ( ) ) ; if ( context . verifyEvidence ( evidence ) ) { if ( context . authorize ( ) ) { context . succeed ( ) ; return context . getAuthorizedIdentity ( ) ; } else { context . fail ( ) ; MessagingLogger . ROOT_LOGGER . failedAuthorization ( username ) ; } } else { context . fail ( ) ; MessagingLogger . ROOT_LOGGER . failedAuthentication ( username ) ; } } catch ( IllegalArgumentException | IllegalStateException | RealmUnavailableException e ) { context . fail ( ) ; MessagingLogger . ROOT_LOGGER . failedAuthenticationWithException ( e , username , e . getMessage ( ) ) ; } finally { if ( evidence != null ) { evidence . destroy ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the types that JCA Injection knows . [CODESPLIT] private static boolean isTypeMatched ( Class < ? > clz ) { if ( clz . equals ( String . class ) ) { return true ; } else if ( clz . equals ( byte . class ) || clz . equals ( Byte . class ) ) { return true ; } else if ( clz . equals ( short . class ) || clz . equals ( Short . class ) ) { return true ; } else if ( clz . equals ( int . class ) || clz . equals ( Integer . class ) ) { return true ; } else if ( clz . equals ( long . class ) || clz . equals ( Long . class ) ) { return true ; } else if ( clz . equals ( float . class ) || clz . equals ( Float . class ) ) { return true ; } else if ( clz . equals ( double . class ) || clz . equals ( Double . class ) ) { return true ; } else if ( clz . equals ( boolean . class ) || clz . equals ( Boolean . class ) ) { return true ; } else if ( clz . equals ( char . class ) || clz . equals ( Character . class ) ) { return true ; } else if ( clz . equals ( InetAddress . class ) ) { return true ; } else if ( clz . equals ( Class . class ) ) { return true ; } else if ( clz . equals ( Properties . class ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SPI contract for this method [CODESPLIT] @ Override public Object lookup ( String name ) { final ContextNames . BindInfo bindInfo = ContextNames . bindInfoFor ( name ) ; ServiceController < ? > bindingService = container . getService ( bindInfo . getBinderServiceName ( ) ) ; if ( bindingService == null ) { return null ; } ManagedReferenceFactory managedReferenceFactory = ManagedReferenceFactory . class . cast ( bindingService . getValue ( ) ) ; return managedReferenceFactory . getReference ( ) . getInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbind the resource and wait until the corresponding binding service is effectively removed . [CODESPLIT] @ Override public void unbind ( String name ) { if ( name == null || name . isEmpty ( ) ) { throw MessagingLogger . ROOT_LOGGER . cannotUnbindJndiName ( ) ; } final ContextNames . BindInfo bindInfo = ContextNames . bindInfoFor ( name ) ; ServiceController < ? > bindingService = container . getService ( bindInfo . getBinderServiceName ( ) ) ; if ( bindingService == null ) { ROOT_LOGGER . debugf ( \"Cannot unbind %s since no binding exists with that name\" , name ) ; return ; } // remove the binding service bindingService . setMode ( ServiceController . Mode . REMOVE ) ; final StabilityMonitor monitor = new StabilityMonitor ( ) ; monitor . addController ( bindingService ) ; try { monitor . awaitStability ( ) ; ROOT_LOGGER . unboundJndiName ( bindInfo . getAbsoluteJndiName ( ) ) ; } catch ( InterruptedException e ) { ROOT_LOGGER . failedToUnbindJndiName ( name , 5 , SECONDS . toString ( ) . toLowerCase ( Locale . US ) ) ; } finally { monitor . removeController ( bindingService ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiate bean . [CODESPLIT] public static Object instantiateBean ( BeanMetaDataConfig beanConfig , BeanInfo beanInfo , DeploymentReflectionIndex index , Module module ) throws Throwable { Joinpoint instantiateJoinpoint = null ; ValueConfig [ ] parameters = new ValueConfig [ 0 ] ; String [ ] types = Configurator . NO_PARAMS_TYPES ; ConstructorConfig ctorConfig = beanConfig . getConstructor ( ) ; if ( ctorConfig != null ) { parameters = ctorConfig . getParameters ( ) ; types = Configurator . getTypes ( parameters ) ; String factoryClass = ctorConfig . getFactoryClass ( ) ; FactoryConfig factory = ctorConfig . getFactory ( ) ; if ( factoryClass != null || factory != null ) { String factoryMethod = ctorConfig . getFactoryMethod ( ) ; if ( factoryMethod == null ) throw PojoLogger . ROOT_LOGGER . missingFactoryMethod ( beanConfig ) ; if ( factoryClass != null ) { // static factory Class < ? > factoryClazz = Class . forName ( factoryClass , false , module . getClassLoader ( ) ) ; Method method = Configurator . findMethod ( index , factoryClazz , factoryMethod , types , true , true , true ) ; MethodJoinpoint mj = new MethodJoinpoint ( method ) ; mj . setTarget ( new ImmediateValue < Object > ( null ) ) ; // null, since this is static call mj . setParameters ( parameters ) ; instantiateJoinpoint = mj ; } else if ( factory != null ) { ReflectionJoinpoint rj = new ReflectionJoinpoint ( factory . getBeanInfo ( ) , factoryMethod , types ) ; // null type is ok, as this should be plain injection rj . setTarget ( new ImmediateValue < Object > ( factory . getValue ( null ) ) ) ; rj . setParameters ( parameters ) ; instantiateJoinpoint = rj ; } } } // plain bean's ctor if ( instantiateJoinpoint == null ) { if ( beanInfo == null ) throw new StartException ( PojoLogger . ROOT_LOGGER . missingBeanInfo ( beanConfig ) ) ; Constructor ctor = ( types . length == 0 ) ? beanInfo . getConstructor ( ) : beanInfo . findConstructor ( types ) ; ConstructorJoinpoint constructorJoinpoint = new ConstructorJoinpoint ( ctor ) ; constructorJoinpoint . setParameters ( parameters ) ; instantiateJoinpoint = constructorJoinpoint ; } return instantiateJoinpoint . dispatch ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure bean . [CODESPLIT] public static void configure ( BeanMetaDataConfig beanConfig , BeanInfo beanInfo , Module module , Object bean , boolean nullify ) throws Throwable { Set < PropertyConfig > properties = beanConfig . getProperties ( ) ; if ( properties != null ) { List < PropertyConfig > used = new ArrayList < PropertyConfig > ( ) ; for ( PropertyConfig pc : properties ) { try { configure ( beanInfo , module , bean , pc , nullify ) ; used . add ( pc ) ; } catch ( Throwable t ) { if ( nullify == false ) { for ( PropertyConfig upc : used ) { try { configure ( beanInfo , module , bean , upc , true ) ; } catch ( Throwable ignored ) { } } throw new StartException ( t ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dispatch lifecycle joinpoint . [CODESPLIT] public static void dispatchLifecycleJoinpoint ( BeanInfo beanInfo , Object bean , LifecycleConfig config , String defaultMethod ) throws Throwable { if ( config != null && config . isIgnored ( ) ) return ; Joinpoint joinpoint = createJoinpoint ( beanInfo , bean , config , defaultMethod ) ; if ( joinpoint != null ) joinpoint . dispatch ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an outbound connection reference used by a remoting receiver in the client context represented by this { @link EJBClientDescriptorMetaData } [CODESPLIT] public RemotingReceiverConfiguration addRemotingReceiverConnectionRef ( final String outboundConnectionRef ) { if ( outboundConnectionRef == null || outboundConnectionRef . trim ( ) . isEmpty ( ) ) { throw new IllegalArgumentException ( \"Cannot add a remoting receiver which references a null/empty outbound connection\" ) ; } final RemotingReceiverConfiguration remotingReceiverConfiguration = new RemotingReceiverConfiguration ( outboundConnectionRef ) ; this . remotingReceiverConfigurations . put ( outboundConnectionRef , remotingReceiverConfiguration ) ; return remotingReceiverConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a reference to a sub class of { [CODESPLIT] public static Reference createReference ( final ServiceName service , Class < ? extends ServiceReferenceObjectFactory > factory ) { return ModularReference . create ( Context . class , new ServiceNameRefAdr ( \"srof\" , service ) , factory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the service reference . The parameters are the same as { [CODESPLIT] public Object getObjectInstance ( Object serviceValue , Object obj , Name name , Context nameCtx , Hashtable < ? , ? > environment ) throws Exception { return serviceValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current context selector for the current thread . [CODESPLIT] public static NamespaceContextSelector getCurrentSelector ( ) { NamespaceContextSelector selector = currentSelector . peek ( ) ; if ( selector != null ) { return selector ; } return defaultSelector ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get MC bean name . [CODESPLIT] public static ServiceName toBeanName ( String name , BeanState state ) { if ( state == null ) state = BeanState . INSTALLED ; return JBOSS_POJO . append ( name ) . append ( state . name ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To instances name . [CODESPLIT] public static ServiceName toInstancesName ( Class < ? > clazz , BeanState state ) { String clName ; ClassLoader classLoader = clazz . getClassLoader ( ) ; if ( classLoader != null ) clName = classLoader . toString ( ) ; else clName = \"SystemClassLoader\" ; if ( state == null ) state = BeanState . INSTALLED ; return JBOSS_POJO . append ( clName , clazz . getName ( ) , state . name ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines a list of classes the given annotation instances are defined on . If an annotation instance is not defined on a class ( e . g . on a member ) this annotation instance is not reflected anyhow in the resulting list . [CODESPLIT] public static List < ClassInfo > getAnnotatedClasses ( List < AnnotationInstance > instances ) { List < ClassInfo > result = new ArrayList < ClassInfo > ( ) ; for ( AnnotationInstance instance : instances ) { AnnotationTarget target = instance . target ( ) ; if ( target instanceof ClassInfo ) { result . add ( ( ClassInfo ) target ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look for a class description in all available modules . [CODESPLIT] public EEModuleClassDescription getClassByName ( String name ) { for ( EEModuleDescription module : availableModules ) { final EEModuleClassDescription desc = module . getClassDescription ( name ) ; if ( desc != null ) { return desc ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process annotations and merge any available metadata at the same time . [CODESPLIT] @ Override protected void processAnnotations ( final DeploymentUnit deploymentUnit , final CompositeIndex compositeIndex ) throws DeploymentUnitProcessingException { if ( MetadataCompleteMarker . isMetadataComplete ( deploymentUnit ) ) { return ; } // Find and process any @Stateless bean annotations final List < AnnotationInstance > slsbAnnotations = compositeIndex . getAnnotations ( STATELESS_ANNOTATION ) ; if ( ! slsbAnnotations . isEmpty ( ) ) { processSessionBeans ( deploymentUnit , slsbAnnotations , SessionBeanComponentDescription . SessionBeanType . STATELESS ) ; } // Find and process any @Stateful bean annotations final List < AnnotationInstance > sfsbAnnotations = compositeIndex . getAnnotations ( STATEFUL_ANNOTATION ) ; if ( ! sfsbAnnotations . isEmpty ( ) ) { processSessionBeans ( deploymentUnit , sfsbAnnotations , SessionBeanComponentDescription . SessionBeanType . STATEFUL ) ; } // Find and process any @Singleton bean annotations final List < AnnotationInstance > sbAnnotations = compositeIndex . getAnnotations ( SINGLETON_ANNOTATION ) ; if ( ! sbAnnotations . isEmpty ( ) ) { processSessionBeans ( deploymentUnit , sbAnnotations , SessionBeanComponentDescription . SessionBeanType . SINGLETON ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the passed <code > sessionBeanClass< / code > meets the requirements set by the EJB3 spec about bean implementation classes . The passed <code > sessionBeanClass< / code > must not be an interface and must be public and not final and not abstract . If it passes these requirements then this method returns true . Else it returns false . [CODESPLIT] private static boolean assertSessionBeanClassValidity ( final ClassInfo sessionBeanClass ) { final short flags = sessionBeanClass . flags ( ) ; final String className = sessionBeanClass . name ( ) . toString ( ) ; // must *not* be an interface if ( Modifier . isInterface ( flags ) ) { EjbLogger . DEPLOYMENT_LOGGER . sessionBeanClassCannotBeAnInterface ( className ) ; return false ; } // bean class must be public, must *not* be abstract or final if ( ! Modifier . isPublic ( flags ) || Modifier . isAbstract ( flags ) || Modifier . isFinal ( flags ) ) { EjbLogger . DEPLOYMENT_LOGGER . sessionBeanClassMustBePublicNonAbstractNonFinal ( className ) ; return false ; } // valid class return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final EEResourceReferenceProcessorRegistry registry = deploymentUnit . getAttachment ( Attachments . RESOURCE_REFERENCE_PROCESSOR_REGISTRY ) ; //setup ejb context jndi handlers registry . registerResourceReferenceProcessor ( new EjbContextResourceReferenceProcessor ( EJBContext . class ) ) ; registry . registerResourceReferenceProcessor ( new EjbContextResourceReferenceProcessor ( SessionContext . class ) ) ; registry . registerResourceReferenceProcessor ( new EjbContextResourceReferenceProcessor ( EntityContext . class ) ) ; registry . registerResourceReferenceProcessor ( new EjbContextResourceReferenceProcessor ( MessageDrivenContext . class ) ) ; final EEModuleDescription eeModuleDescription = deploymentUnit . getAttachment ( Attachments . EE_MODULE_DESCRIPTION ) ; final Collection < ComponentDescription > componentConfigurations = eeModuleDescription . getComponentDescriptions ( ) ; if ( componentConfigurations == null || componentConfigurations . isEmpty ( ) ) { return ; } for ( ComponentDescription componentConfiguration : componentConfigurations ) { final CompositeIndex index = deploymentUnit . getAttachment ( org . jboss . as . server . deployment . Attachments . COMPOSITE_ANNOTATION_INDEX ) ; if ( index != null ) { processComponentConfig ( componentConfiguration ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected JaccService < EarMetaData > createService ( String contextId , EarMetaData metaData , Boolean standalone ) { return new EarJaccService ( contextId , metaData , standalone ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some of this might need to move to the install phase [CODESPLIT] private void postParseSteps ( final VirtualFile persistence_xml , final PersistenceUnitMetadataHolder puHolder , final DeploymentUnit deploymentUnit ) { for ( PersistenceUnitMetadata pu : puHolder . getPersistenceUnits ( ) ) { // set URLs List < URL > jarfilesUrls = new ArrayList < URL > ( ) ; if ( pu . getJarFiles ( ) != null ) { for ( String jar : pu . getJarFiles ( ) ) { jarfilesUrls . add ( getRelativeURL ( persistence_xml , jar ) ) ; } } pu . setJarFileUrls ( jarfilesUrls ) ; URL url = getPersistenceUnitURL ( persistence_xml ) ; pu . setPersistenceUnitRootUrl ( url ) ; String scopedPersistenceUnitName ; /**\n             * WFLY-5478 allow custom scoped persistence unit name hint in persistence unit definition.\n             * Specified scoped persistence unit name needs to be unique across application server deployments.\n             * Application is responsible for picking a unique name.\n             * Currently, a non-unique name will result in a DuplicateServiceException deployment failure:\n             *   org.jboss.msc.service.DuplicateServiceException: Service jboss.persistenceunit.my2lccustom#test_pu.__FIRST_PHASE__ is already registered\n             */ scopedPersistenceUnitName = Configuration . getScopedPersistenceUnitName ( pu ) ; if ( scopedPersistenceUnitName == null ) { scopedPersistenceUnitName = createBeanName ( deploymentUnit , pu . getPersistenceUnitName ( ) ) ; } else { ROOT_LOGGER . tracef ( \"persistence unit '%s' specified a custom scoped persistence unit name hint \" + \"(jboss.as.jpa.scopedname=%s).  The specified name *must* be unique across all application server deployments.\" , pu . getPersistenceUnitName ( ) , scopedPersistenceUnitName ) ; if ( scopedPersistenceUnitName . indexOf ( ' ' ) != - 1 ) { throw JpaLogger . ROOT_LOGGER . invalidScopedName ( scopedPersistenceUnitName , ' ' ) ; } } pu . setScopedPersistenceUnitName ( scopedPersistenceUnitName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Eliminate duplicate PU definitions from clustering the deployment ( first definition will win ) <p / > JPA 8 . 2 A persistence unit must have a name . Only one persistence unit of any given name must be defined within a single EJB - JAR file within a single WAR file within a single application client jar or within an EAR . See Section 8 . 2 . 2 “Persistence Unit Scope” . [CODESPLIT] private PersistenceUnitMetadataHolder normalize ( List < PersistenceUnitMetadataHolder > listPUHolders ) { // eliminate duplicates (keeping the first instance of each PU by name) Map < String , PersistenceUnitMetadata > flattened = new HashMap < String , PersistenceUnitMetadata > ( ) ; for ( PersistenceUnitMetadataHolder puHolder : listPUHolders ) { for ( PersistenceUnitMetadata pu : puHolder . getPersistenceUnits ( ) ) { if ( ! flattened . containsKey ( pu . getPersistenceUnitName ( ) ) ) { flattened . put ( pu . getPersistenceUnitName ( ) , pu ) ; } else { PersistenceUnitMetadata first = flattened . get ( pu . getPersistenceUnitName ( ) ) ; PersistenceUnitMetadata duplicate = pu ; ROOT_LOGGER . duplicatePersistenceUnitDefinition ( duplicate . getPersistenceUnitName ( ) , first . getScopedPersistenceUnitName ( ) , duplicate . getScopedPersistenceUnitName ( ) ) ; } } } PersistenceUnitMetadataHolder holder = new PersistenceUnitMetadataHolder ( new ArrayList < PersistenceUnitMetadata > ( flattened . values ( ) ) ) ; return holder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "old as6 names looked like : persistence . unit : unitName = ejb3_ext_propagation . ear / lib / ejb3_ext_propagation . jar#CTS - EXT - UNIT [CODESPLIT] public static String createBeanName ( DeploymentUnit deploymentUnit , String persistenceUnitName ) { // persistenceUnitName must be a simple name if ( persistenceUnitName . indexOf ( ' ' ) != - 1 ) { throw JpaLogger . ROOT_LOGGER . invalidPersistenceUnitName ( persistenceUnitName , ' ' ) ; } if ( persistenceUnitName . indexOf ( ' ' ) != - 1 ) { throw JpaLogger . ROOT_LOGGER . invalidPersistenceUnitName ( persistenceUnitName , ' ' ) ; } String unitName = getScopedDeploymentUnitPath ( deploymentUnit ) + \"#\" + persistenceUnitName ; return unitName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the regular and pooled CF [CODESPLIT] private static ConnectionFactoryAttribute [ ] define ( ConnectionFactoryAttribute [ ] specific , ConnectionFactoryAttribute ... common ) { int size = common . length + specific . length ; ConnectionFactoryAttribute [ ] result = new ConnectionFactoryAttribute [ size ] ; for ( int i = 0 ; i < specific . length ; i ++ ) { ConnectionFactoryAttribute attr = specific [ i ] ; AttributeDefinition definition = attr . getDefinition ( ) ; if ( definition == ConnectionFactoryAttributes . Pooled . INITIAL_CONNECT_ATTEMPTS ) { result [ i ] = ConnectionFactoryAttribute . create ( SimpleAttributeDefinitionBuilder . create ( ConnectionFactoryAttributes . Pooled . INITIAL_CONNECT_ATTEMPTS ) . setDefaultValue ( new ModelNode ( - 1 ) ) . build ( ) , attr . getPropertyName ( ) , true ) ; } else { result [ i ] = attr ; } } for ( int i = 0 ; i < common . length ; i ++ ) { ConnectionFactoryAttribute attr = common [ i ] ; AttributeDefinition definition = attr . getDefinition ( ) ; ConnectionFactoryAttribute newAttr ; // replace the reconnect-attempts attribute to use a different default value for pooled CF if ( definition == Common . RECONNECT_ATTEMPTS ) { AttributeDefinition copy = copy ( Pooled . RECONNECT_ATTEMPTS , AttributeAccess . Flag . RESTART_ALL_SERVICES ) ; newAttr = ConnectionFactoryAttribute . create ( copy , Pooled . RECONNECT_ATTEMPTS_PROP_NAME , true ) ; } else if ( definition == CommonAttributes . HA ) { newAttr = ConnectionFactoryAttribute . create ( SimpleAttributeDefinitionBuilder . create ( CommonAttributes . HA ) . setDefaultValue ( ModelNode . TRUE ) . setFlags ( AttributeAccess . Flag . RESTART_ALL_SERVICES ) . build ( ) , attr . getPropertyName ( ) , true ) ; } else if ( definition == Common . CONNECTORS ) { StringListAttributeDefinition copy = new StringListAttributeDefinition . Builder ( Common . CONNECTORS ) . setAlternatives ( CommonAttributes . DISCOVERY_GROUP ) . setRequired ( true ) . setAttributeParser ( AttributeParser . STRING_LIST ) . setAttributeMarshaller ( AttributeMarshaller . STRING_LIST ) . setCapabilityReference ( new AbstractTransportDefinition . TransportCapabilityReferenceRecorder ( CAPABILITY_NAME , CONNECTOR_CAPABILITY_NAME , true ) ) . setRestartAllServices ( ) . build ( ) ; newAttr = ConnectionFactoryAttribute . create ( copy , attr . getPropertyName ( ) , attr . isResourceAdapterProperty ( ) , attr . getConfigType ( ) ) ; } else { AttributeDefinition copy = copy ( definition , AttributeAccess . Flag . RESTART_ALL_SERVICES ) ; newAttr = ConnectionFactoryAttribute . create ( copy , attr . getPropertyName ( ) , attr . isResourceAdapterProperty ( ) , attr . getConfigType ( ) ) ; } result [ specific . length + i ] = newAttr ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns an array of String representations of the parameter types . Primitives are returned as their native representations while classes are returned in the internal descriptor form e . g . Ljava / lang / Integer ; [CODESPLIT] public static String [ ] parameterDescriptors ( String methodDescriptor ) { int i = 1 ; // char 0 is a '(' List < String > ret = new ArrayList < String > ( ) ; int arrayStart = - 1 ; while ( methodDescriptor . charAt ( i ) != ' ' ) { String type = null ; if ( methodDescriptor . charAt ( i ) == ' ' ) { if ( arrayStart == - 1 ) { arrayStart = i ; } } else { if ( methodDescriptor . charAt ( i ) == ' ' ) { int start = i ; i ++ ; while ( methodDescriptor . charAt ( i ) != ' ' ) { ++ i ; } if ( arrayStart == - 1 ) { type = methodDescriptor . substring ( start , i ) ; } else { type = methodDescriptor . substring ( arrayStart , i ) ; } } else { if ( arrayStart == - 1 ) { type = methodDescriptor . charAt ( i ) + \"\" ; } else { type = methodDescriptor . substring ( arrayStart , i + 1 ) ; } } arrayStart = - 1 ; ret . add ( type ) ; } ++ i ; } String [ ] r = new String [ ret . size ( ) ] ; for ( int j = 0 ; j < ret . size ( ) ; ++ j ) { r [ j ] = ret . get ( j ) ; } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "performs basic validation on a descriptor [CODESPLIT] public static String validateDescriptor ( String descriptor ) { if ( descriptor . length ( ) == 0 ) { throw EeLogger . ROOT_LOGGER . cannotBeEmpty ( \"descriptors\" ) ; } if ( descriptor . length ( ) > 1 ) { if ( descriptor . startsWith ( \"L\" ) ) { if ( ! descriptor . endsWith ( \";\" ) ) { throw EeLogger . ROOT_LOGGER . invalidDescriptor ( descriptor ) ; } } else if ( descriptor . startsWith ( \"[\" ) ) { } else { throw EeLogger . ROOT_LOGGER . invalidDescriptor ( descriptor ) ; } } else { char type = descriptor . charAt ( 0 ) ; switch ( type ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : break ; default : throw EeLogger . ROOT_LOGGER . invalidDescriptor ( descriptor ) ; } } return descriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for KernelDeployment configuration . Will install a { @code POJO } for each configured bean . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext . getDeploymentUnit ( ) ; final List < KernelDeploymentXmlDescriptor > kdXmlDescriptors = unit . getAttachment ( KernelDeploymentXmlDescriptor . ATTACHMENT_KEY ) ; if ( kdXmlDescriptors == null || kdXmlDescriptors . isEmpty ( ) ) return ; final Module module = unit . getAttachment ( Attachments . MODULE ) ; if ( module == null ) throw PojoLogger . ROOT_LOGGER . noModuleFound ( unit ) ; final ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; final DeploymentReflectionIndex index = unit . getAttachment ( Attachments . REFLECTION_INDEX ) ; if ( index == null ) throw PojoLogger . ROOT_LOGGER . missingReflectionIndex ( unit ) ; for ( KernelDeploymentXmlDescriptor kdXmlDescriptor : kdXmlDescriptors ) { final List < BeanMetaDataConfig > beanConfigs = kdXmlDescriptor . getBeans ( ) ; for ( final BeanMetaDataConfig beanConfig : beanConfigs ) { describeBean ( module , serviceTarget , index , beanConfig ) ; } // TODO -- KD::classloader, KD::aliases } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public ManagedReference getReference ( ) { try { return view . createInstance ( ) ; } catch ( Exception e ) { throw EeLogger . ROOT_LOGGER . componentViewConstructionFailure ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates web meta data for EJB deployments . [CODESPLIT] void create ( final Deployment dep ) { final DeploymentUnit unit = WSHelper . getRequiredAttachment ( dep , DeploymentUnit . class ) ; WarMetaData warMD = ASHelper . getOptionalAttachment ( unit , WarMetaData . ATTACHMENT_KEY ) ; JBossWebMetaData jbossWebMD = warMD != null ? warMD . getMergedJBossWebMetaData ( ) : null ; if ( warMD == null ) { warMD = new WarMetaData ( ) ; } if ( jbossWebMD == null ) { jbossWebMD = new JBossWebMetaData ( ) ; warMD . setMergedJBossWebMetaData ( jbossWebMD ) ; unit . putAttachment ( WarMetaData . ATTACHMENT_KEY , warMD ) ; } createWebAppDescriptor ( dep , jbossWebMD ) ; createJBossWebAppDescriptor ( dep , jbossWebMD ) ; dep . addAttachment ( JBossWebMetaData . class , jbossWebMD ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates web . xml descriptor meta data . [CODESPLIT] private void createWebAppDescriptor ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { WSLogger . ROOT_LOGGER . trace ( \"Creating web.xml descriptor\" ) ; createServlets ( dep , jbossWebMD ) ; createServletMappings ( dep , jbossWebMD ) ; createSecurityConstraints ( dep , jbossWebMD ) ; createLoginConfig ( dep , jbossWebMD ) ; createSecurityRoles ( dep , jbossWebMD ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates jboss - web . xml descriptor meta data . <p / > <pre > &lt ; jboss - web&gt ; &lt ; security - domain&gt ; java : / jaas / custom - security - domain&lt ; / security - domain&gt ; &lt ; context - root&gt ; / custom - context - root&lt ; / context - root&gt ; &lt ; virtual - host&gt ; host1&lt ; / virtual - host&gt ; ... &lt ; virtual - host&gt ; hostN&lt ; / virtual - host&gt ; &lt ; / jboss - web&gt ; < / pre > [CODESPLIT] private void createJBossWebAppDescriptor ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { WSLogger . ROOT_LOGGER . trace ( \"Creating jboss-web.xml descriptor\" ) ; // Set security domain final String securityDomain = ejb3SecurityAccessor . getSecurityDomain ( dep ) ; final boolean hasSecurityDomain = securityDomain != null ; if ( hasSecurityDomain ) { WSLogger . ROOT_LOGGER . tracef ( \"Setting security domain: %s\" , securityDomain ) ; jbossWebMD . setSecurityDomain ( securityDomain ) ; } // Set virtual host final String virtualHost = dep . getService ( ) . getVirtualHost ( ) ; ServerHostInfo serverHostInfo = new ServerHostInfo ( virtualHost ) ; if ( serverHostInfo . getHost ( ) != null ) { WSLogger . ROOT_LOGGER . tracef ( \"Setting virtual host: %s\" , serverHostInfo . getHost ( ) ) ; jbossWebMD . setVirtualHosts ( Arrays . asList ( serverHostInfo . getHost ( ) ) ) ; if ( serverHostInfo . getServerInstanceName ( ) != null ) { jbossWebMD . setServerInstanceName ( serverHostInfo . getServerInstanceName ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates servlets part of web . xml descriptor . <p / > <pre > &lt ; servlet&gt ; &lt ; servlet - name&gt ; EJBEndpointShortName&lt ; / servlet - name&gt ; &lt ; servlet - class&gt ; EJBEndpointTargetBeanName&lt ; / servlet - class&gt ; &lt ; / servlet&gt ; < / pre > [CODESPLIT] private void createServlets ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { WSLogger . ROOT_LOGGER . trace ( \"Creating servlets\" ) ; final JBossServletsMetaData servlets = WebMetaDataHelper . getServlets ( jbossWebMD ) ; for ( final Endpoint endpoint : dep . getService ( ) . getEndpoints ( ) ) { final String endpointName = endpoint . getShortName ( ) ; final String endpointClassName = endpoint . getTargetBeanName ( ) ; WSLogger . ROOT_LOGGER . tracef ( \"Servlet name: %s, class: %s\" , endpointName , endpointClassName ) ; WebMetaDataHelper . newServlet ( endpointName , endpointClassName , servlets ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates servlet - mapping part of web . xml descriptor . <p / > <pre > &lt ; servlet - mapping&gt ; &lt ; servlet - name&gt ; EJBEndpointShortName&lt ; / servlet - name&gt ; &lt ; url - pattern&gt ; EJBEndpointURLPattern&lt ; / url - pattern&gt ; &lt ; / servlet - mapping&gt ; < / pre > [CODESPLIT] private void createServletMappings ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { WSLogger . ROOT_LOGGER . trace ( \"Creating servlet mappings\" ) ; final List < ServletMappingMetaData > servletMappings = WebMetaDataHelper . getServletMappings ( jbossWebMD ) ; for ( final Endpoint ep : dep . getService ( ) . getEndpoints ( ) ) { if ( ep instanceof HttpEndpoint ) { final String endpointName = ep . getShortName ( ) ; final List < String > urlPatterns = WebMetaDataHelper . getUrlPatterns ( ( ( HttpEndpoint ) ep ) . getURLPattern ( ) ) ; WSLogger . ROOT_LOGGER . tracef ( \"Servlet name: %s, URL patterns: %s\" , endpointName , urlPatterns ) ; WebMetaDataHelper . newServletMapping ( endpointName , urlPatterns , servletMappings ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates security constraints part of web . xml descriptor . <p / > <pre > &lt ; security - constraint&gt ; &lt ; web - resource - collection&gt ; &lt ; web - resource - name&gt ; EJBEndpointShortName&lt ; / web - resource - name&gt ; &lt ; url - pattern&gt ; EJBEndpointURLPattern&lt ; / url - pattern&gt ; &lt ; http - method&gt ; GET&lt ; / http - method&gt ; &lt ; http - method&gt ; POST&lt ; / http - method&gt ; &lt ; / web - resource - collection&gt ; &lt ; auth - constraint&gt ; &lt ; role - name&gt ; * &lt ; / role - name&gt ; &lt ; / auth - constraint&gt ; &lt ; user - data - constraint&gt ; &lt ; transport - guarantee&gt ; EjbTransportGuarantee&lt ; / transport - guarantee&gt ; &lt ; / user - data - constraint&gt ; &lt ; / security - constraint&gt ; < / pre > [CODESPLIT] private void createSecurityConstraints ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { WSLogger . ROOT_LOGGER . trace ( \"Creating security constraints\" ) ; for ( final Endpoint ejbEndpoint : dep . getService ( ) . getEndpoints ( ) ) { final boolean secureWsdlAccess = ejb3SecurityAccessor . isSecureWsdlAccess ( ejbEndpoint ) ; final String transportGuarantee = ejb3SecurityAccessor . getTransportGuarantee ( ejbEndpoint ) ; final boolean hasTransportGuarantee = transportGuarantee != null ; final String authMethod = ejb3SecurityAccessor . getAuthMethod ( ejbEndpoint ) ; final boolean hasAuthMethod = authMethod != null ; if ( ejbEndpoint instanceof HttpEndpoint && ( hasAuthMethod || hasTransportGuarantee ) ) { final List < SecurityConstraintMetaData > securityConstraints = WebMetaDataHelper . getSecurityConstraints ( jbossWebMD ) ; // security-constraint final SecurityConstraintMetaData securityConstraint = WebMetaDataHelper . newSecurityConstraint ( securityConstraints ) ; // web-resource-collection final WebResourceCollectionsMetaData webResourceCollections = WebMetaDataHelper . getWebResourceCollections ( securityConstraint ) ; final String endpointName = ejbEndpoint . getShortName ( ) ; final String urlPattern = ( ( HttpEndpoint ) ejbEndpoint ) . getURLPattern ( ) ; WSLogger . ROOT_LOGGER . tracef ( \"Creating web resource collection for endpoint: %s, URL pattern: %s\" , endpointName , urlPattern ) ; WebMetaDataHelper . newWebResourceCollection ( endpointName , urlPattern , secureWsdlAccess , webResourceCollections ) ; // auth-constraint if ( hasAuthMethod ) { WSLogger . ROOT_LOGGER . tracef ( \"Creating auth constraint for endpoint: %s\" , endpointName ) ; WebMetaDataHelper . newAuthConstraint ( WebMetaDataHelper . getAllRoles ( ) , securityConstraint ) ; } // user-data-constraint if ( hasTransportGuarantee ) { WSLogger . ROOT_LOGGER . tracef ( \"Creating new user data constraint for endpoint: %s, transport guarantee: %s\" , endpointName , transportGuarantee ) ; WebMetaDataHelper . newUserDataConstraint ( transportGuarantee , securityConstraint ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates login - config part of web . xml descriptor . <p / > <pre > &lt ; login - config&gt ; &lt ; auth - method&gt ; EjbDeploymentAuthMethod&lt ; / auth - method&gt ; &lt ; realm - name&gt ; EJBWebServiceEndpointServlet Realm&lt ; / realm - name&gt ; &lt ; / login - config&gt ; < / pre > [CODESPLIT] private void createLoginConfig ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { final String authMethod = getAuthMethod ( dep ) ; final boolean hasAuthMethod = authMethod != null ; final String realmName = getRealmName ( dep ) ; if ( hasAuthMethod ) { WSLogger . ROOT_LOGGER . tracef ( \"Creating new login config: %s, auth method: %s\" , EJB_WEBSERVICE_REALM , authMethod ) ; final LoginConfigMetaData loginConfig = WebMetaDataHelper . getLoginConfig ( jbossWebMD ) ; if ( realmName != null ) { loginConfig . setRealmName ( realmName ) ; } else { loginConfig . setRealmName ( WebMetaDataCreator . EJB_WEBSERVICE_REALM ) ; } loginConfig . setAuthMethod ( authMethod ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates security roles part of web . xml descriptor . <p / > <pre > &lt ; security - role&gt ; &lt ; role - name&gt ; role1&lt ; / role - name&gt ; ... &lt ; role - name&gt ; roleN&lt ; / role - name&gt ; &lt ; / security - role&gt ; < / pre > [CODESPLIT] private void createSecurityRoles ( final Deployment dep , final JBossWebMetaData jbossWebMD ) { final String authMethod = getAuthMethod ( dep ) ; final boolean hasAuthMethod = authMethod != null ; if ( hasAuthMethod ) { final SecurityRolesMetaData securityRolesMD = ejb3SecurityAccessor . getSecurityRoles ( dep ) ; final boolean hasSecurityRolesMD = securityRolesMD != null && ! securityRolesMD . isEmpty ( ) ; if ( hasSecurityRolesMD ) { WSLogger . ROOT_LOGGER . trace ( \"Setting security roles\" ) ; jbossWebMD . setSecurityRoles ( securityRolesMD ) ; } } //merge security roles from the ear //TODO: is there somewhere better to put this? final DeploymentUnit unit = dep . getAttachment ( DeploymentUnit . class ) ; DeploymentUnit parent = unit . getParent ( ) ; if ( parent != null ) { final EarMetaData earMetaData = parent . getAttachment ( org . jboss . as . ee . structure . Attachments . EAR_METADATA ) ; if ( earMetaData != null ) { if ( jbossWebMD . getSecurityRoles ( ) == null ) { jbossWebMD . setSecurityRoles ( new SecurityRolesMetaData ( ) ) ; } SecurityRolesMetaData earSecurityRolesMetaData = earMetaData . getSecurityRoles ( ) ; if ( earSecurityRolesMetaData != null ) { SecurityRolesMetaDataMerger . merge ( jbossWebMD . getSecurityRoles ( ) , jbossWebMD . getSecurityRoles ( ) , earSecurityRolesMetaData ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns deployment authentication method . [CODESPLIT] private String getAuthMethod ( final Deployment dep ) { for ( final Endpoint ejbEndpoint : dep . getService ( ) . getEndpoints ( ) ) { final String beanAuthMethod = ejb3SecurityAccessor . getAuthMethod ( ejbEndpoint ) ; final boolean hasBeanAuthMethod = beanAuthMethod != null ; if ( hasBeanAuthMethod ) { // First found auth-method defines war // login-config/auth-method return beanAuthMethod ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for jboss - service . xml files . Will parse the xml file and attach a configuration discovered during processing . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final VirtualFile deploymentRoot = phaseContext . getDeploymentUnit ( ) . getAttachment ( Attachments . DEPLOYMENT_ROOT ) . getRoot ( ) ; if ( deploymentRoot == null || ! deploymentRoot . exists ( ) ) return ; VirtualFile serviceXmlFile = null ; if ( deploymentRoot . isDirectory ( ) ) { serviceXmlFile = deploymentRoot . getChild ( SERVICE_DESCRIPTOR_PATH ) ; } else if ( deploymentRoot . getName ( ) . toLowerCase ( Locale . ENGLISH ) . endsWith ( SERVICE_DESCRIPTOR_SUFFIX ) ) { serviceXmlFile = deploymentRoot ; } if ( serviceXmlFile == null || ! serviceXmlFile . exists ( ) ) return ; final XMLMapper xmlMapper = XMLMapper . Factory . create ( ) ; final JBossServiceXmlDescriptorParser jBossServiceXmlDescriptorParser = new JBossServiceXmlDescriptorParser ( JBossDescriptorPropertyReplacement . propertyReplacer ( phaseContext . getDeploymentUnit ( ) ) ) ; xmlMapper . registerRootElement ( new QName ( \"urn:jboss:service:7.0\" , \"server\" ) , jBossServiceXmlDescriptorParser ) ; xmlMapper . registerRootElement ( new QName ( null , \"server\" ) , jBossServiceXmlDescriptorParser ) ; InputStream xmlStream = null ; try { xmlStream = serviceXmlFile . openStream ( ) ; final XMLStreamReader reader = inputFactory . createXMLStreamReader ( xmlStream ) ; final ParseResult < JBossServiceXmlDescriptor > result = new ParseResult < JBossServiceXmlDescriptor > ( ) ; xmlMapper . parseDocument ( result , reader ) ; final JBossServiceXmlDescriptor xmlDescriptor = result . getResult ( ) ; if ( xmlDescriptor != null ) phaseContext . getDeploymentUnit ( ) . putAttachment ( JBossServiceXmlDescriptor . ATTACHMENT_KEY , xmlDescriptor ) ; else throw SarLogger . ROOT_LOGGER . failedXmlParsing ( serviceXmlFile ) ; } catch ( Exception e ) { throw SarLogger . ROOT_LOGGER . failedXmlParsing ( e , serviceXmlFile ) ; } finally { VFSUtils . safeClose ( xmlStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles setting up the ejbCreate and ejbRemove methods for stateless session beans and MDB s [CODESPLIT] private void handleStatelessSessionBean ( final EJBComponentDescription component , final Module module , final DeploymentReflectionIndex reflectionIndex ) throws ClassNotFoundException , DeploymentUnitProcessingException { final Class < ? > componentClass = ClassLoadingUtils . loadClass ( component . getComponentClassName ( ) , module ) ; final MethodIdentifier ejbCreateId = MethodIdentifier . getIdentifier ( void . class , \"ejbCreate\" ) ; final Method ejbCreate = ClassReflectionIndexUtil . findMethod ( reflectionIndex , componentClass , ejbCreateId ) ; if ( ejbCreate != null ) { final InterceptorClassDescription . Builder builder = InterceptorClassDescription . builder ( ) ; builder . setPostConstruct ( ejbCreateId ) ; component . addInterceptorMethodOverride ( ejbCreate . getDeclaringClass ( ) . getName ( ) , builder . build ( ) ) ; } final MethodIdentifier ejbRemoveId = MethodIdentifier . getIdentifier ( void . class , \"ejbRemove\" ) ; final Method ejbRemove = ClassReflectionIndexUtil . findMethod ( reflectionIndex , componentClass , ejbRemoveId ) ; if ( ejbRemove != null ) { final InterceptorClassDescription . Builder builder = InterceptorClassDescription . builder ( ) ; builder . setPreDestroy ( ejbRemoveId ) ; component . addInterceptorMethodOverride ( ejbRemove . getDeclaringClass ( ) . getName ( ) , builder . build ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a dynamic stub class if it does not already exist . [CODESPLIT] public static Class < ? > makeStubClass ( final Class < ? > myClass ) { final String stubClassName = myClass + \"_Stub\" ; ClassLoader cl = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; if ( cl == null ) { cl = myClass . getClassLoader ( ) ; } if ( cl == null ) { throw EjbLogger . ROOT_LOGGER . couldNotFindClassLoaderForStub ( stubClassName ) ; } Class < ? > theClass ; try { theClass = cl . loadClass ( stubClassName ) ; } catch ( ClassNotFoundException e ) { try { final ClassFile clazz = IIOPStubCompiler . compile ( myClass , stubClassName ) ; theClass = clazz . define ( cl , myClass . getProtectionDomain ( ) ) ; } catch ( Throwable ex ) { //there is a possibility that another thread may have defined the same class in the meantime try { theClass = cl . loadClass ( stubClassName ) ; } catch ( ClassNotFoundException e1 ) { EjbLogger . ROOT_LOGGER . dynamicStubCreationFailed ( stubClassName , ex ) ; throw ex ; } } } return theClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repository implementation ------------------------------------- [CODESPLIT] public Contained lookup_id ( java . lang . String search_id ) { LocalContained c = _lookup_id ( search_id ) ; if ( c == null ) return null ; return ContainedHelper . narrow ( c . getReference ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the ID of the n - th anonymous object created in this IR . [CODESPLIT] protected byte [ ] getAnonymousObjectId ( long n ) { String s = anonOidPrefix + Long . toString ( n ) ; return s . getBytes ( StandardCharsets . UTF_8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a repository ID to an IDL scoped name . Returns <code > null< / code > if the ID cannot be understood . [CODESPLIT] private String scopedName ( String id ) { if ( id == null ) return null ; if ( id . startsWith ( \"IDL:\" ) ) { // OMG IDL format // Check for base types if ( \"IDL:omg.org/CORBA/Object:1.0\" . equals ( id ) || \"IDL:omg.org/CORBA/ValueBase:1.0\" . equals ( id ) ) return null ; // Get 2nd component of ID int idx2 = id . indexOf ( ' ' , 4 ) ; // 2nd colon if ( idx2 == - 1 ) return null ; // invalid ID, version part missing String base = id . substring ( 4 , id . indexOf ( ' ' , 4 ) ) ; // Check special prefixes if ( base . startsWith ( \"omg.org\" ) ) base = \"org/omg\" + base . substring ( 7 ) ; if ( base . startsWith ( \"w3c.org\" ) ) base = \"org/w3c\" + base . substring ( 7 ) ; // convert '/' to \"::\" StringBuffer b = new StringBuffer ( ) ; for ( int i = 0 ; i < base . length ( ) ; ++ i ) { char c = base . charAt ( i ) ; if ( c != ' ' ) b . append ( c ) ; else b . append ( \"::\" ) ; } return b . toString ( ) ; } else if ( id . startsWith ( \"RMI:\" ) ) { // RMI hashed format // Get 2nd component of ID int idx2 = id . indexOf ( ' ' , 4 ) ; // 2nd colon if ( idx2 == - 1 ) return null ; // invalid ID, version part missing String base = id . substring ( 4 , id . indexOf ( ' ' , 4 ) ) ; // convert '.' to \"::\" StringBuffer b = new StringBuffer ( ) ; for ( int i = 0 ; i < base . length ( ) ; ++ i ) { char c = base . charAt ( i ) ; if ( c != ' ' ) b . append ( c ) ; else b . append ( \"::\" ) ; } return b . toString ( ) ; } else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TransformedOperation transformOperation ( TransformationContext context , PathAddress address , ModelNode operation ) { return new TransformedOperation ( this . operationTransformer . transformOperation ( operation ) , this . resultTransformer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( final ExtensionContext context ) { WeldLogger . ROOT_LOGGER . debug ( \"Activating Weld Extension\" ) ; final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; final ManagementResourceRegistration registration = subsystem . registerSubsystemModel ( WeldResourceDefinition . INSTANCE ) ; registration . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; subsystem . registerXMLElementWriter ( WeldSubsystem40Parser . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( final ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , WeldSubsystem10Parser . NAMESPACE , ( ) -> WeldSubsystem10Parser . INSTANCE ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , WeldSubsystem20Parser . NAMESPACE , ( ) -> WeldSubsystem20Parser . INSTANCE ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , WeldSubsystem30Parser . NAMESPACE , ( ) -> WeldSubsystem30Parser . INSTANCE ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , WeldSubsystem40Parser . NAMESPACE , ( ) -> WeldSubsystem40Parser . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void start ( final StartContext context ) { super . start ( context ) ; if ( SarLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { SarLogger . ROOT_LOGGER . tracef ( \"Creating Service: %s\" , context . getController ( ) . getName ( ) ) ; } final Runnable task = new Runnable ( ) { @ Override public void run ( ) { try { injectDependencies ( ) ; invokeLifecycleMethod ( createMethod , context ) ; if ( componentInstantiator != null ) { managedReference = componentInstantiator . initializeInstance ( mBeanInstance ) ; } context . complete ( ) ; } catch ( Throwable e ) { uninjectDependencies ( ) ; context . failed ( new StartException ( SarLogger . ROOT_LOGGER . failedExecutingLegacyMethod ( \"create()\" ) , e ) ) ; } } } ; try { executorSupplier . get ( ) . submit ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Remove this method once WFCORE - 3055 and WFCORE - 3056 are fixed [CODESPLIT] @ Override protected void validateUpdatedModel ( OperationContext context , Resource model ) throws OperationFailedException { SecurityDomainResourceDefinition . CACHE_TYPE . validateOperation ( model . getModel ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void validateParameter ( String parameterName , ModelNode value ) throws OperationFailedException { super . validateParameter ( parameterName , value ) ; if ( value . isDefined ( ) && value . getType ( ) != ModelType . EXPRESSION ) { String val = value . asString ( ) ; try { PredicateParser . parse ( val , getClass ( ) . getClassLoader ( ) ) ; } catch ( Exception e ) { throw new OperationFailedException ( UndertowLogger . ROOT_LOGGER . predicateNotValid ( val , e . getMessage ( ) ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new instance of each persistence provider class [CODESPLIT] @ Override public List < PersistenceProvider > getPersistenceProviders ( ) { List < PersistenceProvider > providersCopy = new ArrayList <> ( providers . size ( ) ) ; /**\n         * Add the application specified providers first so they are found before the global providers\n         */ synchronized ( persistenceProviderPerClassLoader ) { if ( persistenceProviderPerClassLoader . size ( ) > 0 ) { // get the deployment or subdeployment classloader ClassLoader deploymentClassLoader = findParentModuleCl ( WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ) ; ROOT_LOGGER . tracef ( \"get application level Persistence Provider for classloader %s\" , deploymentClassLoader ) ; // collect persistence providers associated with deployment/each sub-deployment List < Class < ? extends PersistenceProvider > > deploymentSpecificPersistenceProviders = persistenceProviderPerClassLoader . get ( deploymentClassLoader ) ; ROOT_LOGGER . tracef ( \"got application level Persistence Provider list %s\" , deploymentSpecificPersistenceProviders ) ; if ( deploymentSpecificPersistenceProviders != null ) { for ( Class < ? extends PersistenceProvider > providerClass : deploymentSpecificPersistenceProviders ) { try { ROOT_LOGGER . tracef ( \"application has its own Persistence Provider %s\" , providerClass . getName ( ) ) ; providersCopy . add ( providerClass . newInstance ( ) ) ; } catch ( InstantiationException e ) { throw JpaLogger . ROOT_LOGGER . couldNotCreateInstanceProvider ( e , providerClass . getName ( ) ) ; } catch ( IllegalAccessException e ) { throw JpaLogger . ROOT_LOGGER . couldNotCreateInstanceProvider ( e , providerClass . getName ( ) ) ; } } } } } // add global persistence providers last (so application packaged providers have priority) for ( Class < ? > providerClass : providers ) { try { providersCopy . add ( ( PersistenceProvider ) providerClass . newInstance ( ) ) ; ROOT_LOGGER . tracef ( \"returning global (module) Persistence Provider %s\" , providerClass . getName ( ) ) ; } catch ( InstantiationException e ) { throw JpaLogger . ROOT_LOGGER . couldNotCreateInstanceProvider ( e , providerClass . getName ( ) ) ; } catch ( IllegalAccessException e ) { throw JpaLogger . ROOT_LOGGER . couldNotCreateInstanceProvider ( e , providerClass . getName ( ) ) ; } } return providersCopy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleared at application undeployment time to remove any persistence providers that were deployed with the application [CODESPLIT] public void clearCachedDeploymentSpecificProviders ( Set < ClassLoader > deploymentClassLoaders ) { synchronized ( persistenceProviderPerClassLoader ) { for ( ClassLoader deploymentClassLoader : deploymentClassLoaders ) { persistenceProviderPerClassLoader . remove ( deploymentClassLoader ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set at application deployment time to the persistence providers packaged in the application [CODESPLIT] public void addDeploymentSpecificPersistenceProvider ( PersistenceProvider persistenceProvider , Set < ClassLoader > deploymentClassLoaders ) { synchronized ( persistenceProviderPerClassLoader ) { for ( ClassLoader deploymentClassLoader : deploymentClassLoaders ) { List < Class < ? extends PersistenceProvider > > list = persistenceProviderPerClassLoader . get ( deploymentClassLoader ) ; ROOT_LOGGER . tracef ( \"getting persistence provider list (%s) for deployment (%s)\" , list , deploymentClassLoader ) ; if ( list == null ) { list = new ArrayList <> ( ) ; persistenceProviderPerClassLoader . put ( deploymentClassLoader , list ) ; ROOT_LOGGER . tracef ( \"saving new persistence provider list (%s) for deployment (%s)\" , list , deploymentClassLoader ) ; } list . add ( persistenceProvider . getClass ( ) ) ; ROOT_LOGGER . tracef ( \"added new persistence provider (%s) to provider list (%s)\" , persistenceProvider . getClass ( ) . getName ( ) , list ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a custom CL is in use we want to get the module CL it delegates to [CODESPLIT] private ClassLoader findParentModuleCl ( ClassLoader classLoader ) { ClassLoader c = classLoader ; while ( c != null && ! ( c instanceof ModuleClassLoader ) ) { c = c . getParent ( ) ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the JacORB subsystem configuration according to the XSD version 1 . 0 . < / p > [CODESPLIT] private void readElement_1_0 ( Namespace namespace , XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { // check the element namespace. if ( Namespace . JacORB_1_0 != Namespace . forUri ( reader . getNamespaceURI ( ) ) ) throw unexpectedElement ( reader ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; // there can be multiple property elements. if ( ! encountered . add ( element ) && element != Element . PROPERTY ) { throw duplicateNamedElement ( reader , element . getLocalName ( ) ) ; } switch ( element ) { case ORB : { this . parseORBConfig_1_0 ( reader , node ) ; break ; } case POA : { this . parsePOAConfig ( namespace , reader , node ) ; break ; } case INTEROP : { this . parseInteropConfig ( reader , node ) ; break ; } case SECURITY : { this . parseSecurityConfig_1_0 ( reader , node ) ; break ; } case PROPERTY : { ModelNode propertiesNode = node . get ( JacORBSubsystemConstants . PROPERTIES ) ; this . parseGenericProperty_1_0 ( reader , propertiesNode ) ; break ; } case ORB_INITIALIZERS : { this . parseORBInitializersConfig_1_0 ( reader , node ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the JacORB subsystem configuration according to the XSD version 1 . 1 or higher . < / p > [CODESPLIT] private void readElement_1_1 ( Namespace namespace , XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { // check the element namespace. if ( namespace != Namespace . forUri ( reader . getNamespaceURI ( ) ) ) throw unexpectedElement ( reader ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; if ( ! encountered . add ( element ) ) { throw duplicateNamedElement ( reader , element . getLocalName ( ) ) ; } switch ( element ) { case ORB : { this . parseORBConfig ( namespace , reader , node ) ; break ; } case POA : { this . parsePOAConfig ( namespace , reader , node ) ; break ; } case NAMING : { this . parseNamingConfig ( reader , node ) ; break ; } case INTEROP : { this . parseInteropConfig ( reader , node ) ; break ; } case SECURITY : { this . parseSecurityConfig ( reader , node ) ; break ; } case PROPERTIES : { this . parsePropertiesConfig ( namespace , reader , node ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code orb } section of the JacORB subsystem configuration according to the XSD version 1 . 0 . < / p > [CODESPLIT] private void parseORBConfig_1_0 ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse the orb config attributes. EnumSet < Attribute > expectedAttributes = EnumSet . of ( Attribute . NAME , Attribute . ORB_PRINT_VERSION , Attribute . ORB_GIOP_MINOR_VERSION , Attribute . ORB_USE_BOM , Attribute . ORB_USE_IMR , Attribute . ORB_CACHE_POA_NAMES , Attribute . ORB_CACHE_TYPECODES ) ; this . parseAttributes ( reader , node , expectedAttributes , null ) ; // parse the orb config elements. EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { // check the element namespace. if ( Namespace . JacORB_1_0 != Namespace . forUri ( reader . getNamespaceURI ( ) ) ) throw unexpectedElement ( reader ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; // check for duplicate elements. if ( ! encountered . add ( element ) ) { throw duplicateNamedElement ( reader , element . getLocalName ( ) ) ; } switch ( element ) { case ORB_CONNECTION : { this . parseORBConnectionConfig ( reader , node ) ; break ; } case NAMING : { this . parseNamingConfig ( reader , node ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code orb } section of the JacORB subsystem configuration according to the XSD version 1 . 1 or higher . < / p > [CODESPLIT] private void parseORBConfig ( Namespace namespace , XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse the orb config attributes. EnumSet < Attribute > expectedAttributes = EnumSet . of ( Attribute . NAME , Attribute . ORB_PRINT_VERSION , Attribute . ORB_GIOP_MINOR_VERSION , Attribute . ORB_USE_BOM , Attribute . ORB_USE_IMR , Attribute . ORB_CACHE_POA_NAMES , Attribute . ORB_CACHE_TYPECODES ) ; // version 1.2 of the schema allows for the configuration of the ORB socket bindings. if ( namespace . ordinal ( ) >= Namespace . JacORB_1_2 . ordinal ( ) ) { expectedAttributes . add ( Attribute . ORB_SOCKET_BINDING ) ; expectedAttributes . add ( Attribute . ORB_SSL_SOCKET_BINDING ) ; } if ( namespace . ordinal ( ) >= Namespace . JacORB_2_0 . ordinal ( ) ) { expectedAttributes . add ( Attribute . ORB_PERSISTENT_SERVER_ID ) ; } this . parseAttributes ( reader , node , expectedAttributes , null ) ; // parse the orb config elements. EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { // check the element namespace. if ( namespace != Namespace . forUri ( reader . getNamespaceURI ( ) ) ) throw unexpectedElement ( reader ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; // check for duplicate elements. if ( ! encountered . add ( element ) ) { throw duplicateNamedElement ( reader , element . getLocalName ( ) ) ; } switch ( element ) { case ORB_CONNECTION : { this . parseORBConnectionConfig ( reader , node ) ; break ; } case ORB_INITIALIZERS : { this . parseORBInitializersConfig ( reader , node ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the ORB { @code connection } section of the JacORB subsystem configuration . < / p > [CODESPLIT] private void parseORBConnectionConfig ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse the orb connection config attributes. EnumSet < Attribute > attributes = EnumSet . of ( Attribute . ORB_CONN_RETRIES , Attribute . ORB_CONN_RETRY_INTERVAL , Attribute . ORB_CONN_CLIENT_TIMEOUT , Attribute . ORB_CONN_SERVER_TIMEOUT , Attribute . ORB_CONN_MAX_SERVER_CONNECTIONS , Attribute . ORB_CONN_MAX_MANAGED_BUF_SIZE , Attribute . ORB_CONN_OUTBUF_SIZE , Attribute . ORB_CONN_OUTBUF_CACHE_TIMEOUT ) ; this . parseAttributes ( reader , node , attributes , null ) ; // the connection sub-element doesn't have child elements. requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the ORB { @code initializers } section of the JacORB subsystem configuration according to the XSD version 1 . 0 . < / p > [CODESPLIT] private void parseORBInitializersConfig_1_0 ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { requireNoAttributes ( reader ) ; // read the element text - a comma-separated list of initializers. String initializersList = reader . getElementText ( ) ; if ( initializersList != null ) { String [ ] initializers = initializersList . split ( \",\" ) ; // read each configured initializer and set the appropriate values in the model node. for ( String initializer : initializers ) { SimpleAttributeDefinition definition = ( SimpleAttributeDefinition ) JacORBSubsystemDefinitions . valueOf ( initializer ) ; if ( definition != null && JacORBSubsystemDefinitions . ORB_INIT_ATTRIBUTES . contains ( definition ) ) node . get ( definition . getName ( ) ) . set ( JacORBSubsystemConstants . ON ) ; else throw JacORBLogger . ROOT_LOGGER . invalidInitializerConfig ( initializer , reader . getLocation ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the ORB { @code initializers } section of the JacORB subsystem configuration according to the XSD version 1 . 1 or higher . < / p > [CODESPLIT] private void parseORBInitializersConfig ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse the initializers config attributes. EnumSet < Attribute > attributes = EnumSet . of ( Attribute . ORB_INIT_SECURITY , Attribute . ORB_INIT_TRANSACTIONS ) ; this . parseAttributes ( reader , node , attributes , null ) ; // the initializers element doesn't have child elements. requireNoContent ( reader ) ; //if security=\"on\" change it to security=\"identity\" if ( node . has ( SECURITY ) && node . get ( SECURITY ) . asString ( ) . equals ( JacORBSubsystemConstants . ON ) ) { node . get ( SECURITY ) . set ( SecurityAllowedValues . IDENTITY . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code poa } section of the JacORB subsystem configuration . < / p > [CODESPLIT] private void parsePOAConfig ( Namespace namespace , XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse the poa config attributes. EnumSet < Attribute > expectedAttributes = EnumSet . of ( Attribute . POA_MONITORING , Attribute . POA_QUEUE_WAIT , Attribute . POA_QUEUE_MIN , Attribute . POA_QUEUE_MAX ) ; this . parseAttributes ( reader , node , expectedAttributes , null ) ; // parse the poa config elements. EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { // check the element namespace. if ( namespace != Namespace . forUri ( reader . getNamespaceURI ( ) ) ) throw unexpectedElement ( reader ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; // check for duplicate elements. if ( ! encountered . add ( element ) ) { throw duplicateNamedElement ( reader , element . getLocalName ( ) ) ; } switch ( element ) { case POA_REQUEST_PROC : { // parse the poa request-processors config attributes. EnumSet < Attribute > attributes = EnumSet . of ( Attribute . POA_REQUEST_PROC_POOL_SIZE , Attribute . POA_REQUEST_PROC_MAX_THREADS ) ; this . parseAttributes ( reader , node , attributes , null ) ; // the request-processors element doesn't have child elements. requireNoContent ( reader ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code naming } section of the JacORB subsystem configuration . < / p > [CODESPLIT] private void parseNamingConfig ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse all naming attributes. EnumSet < Attribute > expectedAttributes = EnumSet . of ( Attribute . NAMING_ROOT_CONTEXT , Attribute . NAMING_EXPORT_CORBALOC ) ; this . parseAttributes ( reader , node , expectedAttributes , null ) ; // the naming element doesn't have child elements. requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code interop } section of the JacORB subsystem configuration . < / p > [CODESPLIT] private void parseInteropConfig ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse all interop attributes. EnumSet < Attribute > expectedAttributes = EnumSet . of ( Attribute . INTEROP_SUN , Attribute . INTEROP_COMET , Attribute . INTEROP_IONA , Attribute . INTEROP_CHUNK_RMI_VALUETYPES , Attribute . INTEROP_LAX_BOOLEAN_ENCODING , Attribute . INTEROP_INDIRECTION_ENCODING_DISABLE , Attribute . INTEROP_STRICT_CHECK_ON_TC_CREATION ) ; this . parseAttributes ( reader , node , expectedAttributes , null ) ; // the interop element doesn't have child elements. requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code security } section of the JacORB subsystem configuration according to the XSD version 1 . 0 . < / p > [CODESPLIT] private void parseSecurityConfig_1_0 ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse all security attributes. EnumSet < Attribute > expectedAttributes = EnumSet . of ( Attribute . SECURITY_SUPPORT_SSL , Attribute . SECURITY_ADD_COMPONENT_INTERCEPTOR , Attribute . SECURITY_CLIENT_SUPPORTS , Attribute . SECURITY_CLIENT_REQUIRES , Attribute . SECURITY_SERVER_SUPPORTS , Attribute . SECURITY_SERVER_REQUIRES , Attribute . SECURITY_USE_DOMAIN_SF , Attribute . SECURITY_USE_DOMAIN_SSF ) ; EnumSet < Attribute > parsedAttributes = EnumSet . noneOf ( Attribute . class ) ; for ( int i = 0 ; i < reader . getAttributeCount ( ) ; i ++ ) { requireNoNamespaceAttribute ( reader , i ) ; String attrValue = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; // check for unexpected attributes. if ( ! expectedAttributes . contains ( attribute ) ) throw unexpectedAttribute ( reader , i ) ; // check for duplicate attributes. if ( ! parsedAttributes . add ( attribute ) ) { throw duplicateAttribute ( reader , attribute . getLocalName ( ) ) ; } switch ( attribute ) { // check the attributes that need to be converted from int to string. case SECURITY_CLIENT_SUPPORTS : case SECURITY_CLIENT_REQUIRES : case SECURITY_SERVER_SUPPORTS : case SECURITY_SERVER_REQUIRES : SSLConfigValue value = SSLConfigValue . fromValue ( attrValue ) ; if ( value == null ) throw JacORBLogger . ROOT_LOGGER . invalidSSLConfig ( attrValue , reader . getLocation ( ) ) ; attrValue = value . toString ( ) ; default : SimpleAttributeDefinition definition = ( ( SimpleAttributeDefinition ) JacORBSubsystemDefinitions . valueOf ( attribute . getLocalName ( ) ) ) ; // a null definition represents an attribute that has been deprecated and is no longer used. if ( definition != null ) definition . parseAndSetParameter ( attrValue , node , reader ) ; } } // the security element doesn't have child elements. requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code security } section of the JacORB subsystem configuration according to the XSD version 1 . 1 or higher . < / p > [CODESPLIT] private void parseSecurityConfig ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // parse all security attributes. EnumSet < Attribute > expectedAttributes = EnumSet . of ( Attribute . SECURITY_SUPPORT_SSL , Attribute . SECURITY_SECURITY_DOMAIN , Attribute . SECURITY_ADD_COMPONENT_INTERCEPTOR , Attribute . SECURITY_CLIENT_SUPPORTS , Attribute . SECURITY_CLIENT_REQUIRES , Attribute . SECURITY_SERVER_SUPPORTS , Attribute . SECURITY_SERVER_REQUIRES ) ; this . parseAttributes ( reader , node , expectedAttributes , null ) ; // the security element doesn't have child elements. requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the { @code properties } section of the JacORB subsystem configuration . < / p > [CODESPLIT] private void parsePropertiesConfig ( Namespace namespace , XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { // the properties element doesn't define any attributes, just sub-elements. requireNoAttributes ( reader ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { // check the element namespace. if ( namespace != Namespace . forUri ( reader . getNamespaceURI ( ) ) ) throw unexpectedElement ( reader ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; switch ( element ) { case PROPERTY : { // parse the property element. this . parseGenericProperty ( reader , node . get ( JacORBSubsystemConstants . PROPERTIES ) ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses a { @code property } element according to the XSD version 1 . 0 and adds the key / value pair to the specified { @code ModelNode } . < / p > [CODESPLIT] private void parseGenericProperty_1_0 ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { String name = null ; String val = null ; EnumSet < Attribute > required = EnumSet . of ( Attribute . PROP_KEY , Attribute . PROP_VALUE ) ; final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { requireNoNamespaceAttribute ( reader , i ) ; final String value = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; required . remove ( attribute ) ; switch ( attribute ) { case PROP_KEY : { name = value ; break ; } case PROP_VALUE : { val = value ; break ; } default : throw unexpectedAttribute ( reader , i ) ; } } if ( ! required . isEmpty ( ) ) { throw missingRequired ( reader , required ) ; } node . get ( name ) . set ( val ) ; requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses a { @code property } element according to the XSD version 1 . 1 or higher and adds the name / value pair to the specified { @code ModelNode } . < / p > [CODESPLIT] private void parseGenericProperty ( XMLExtendedStreamReader reader , ModelNode node ) throws XMLStreamException { String name = null ; ModelNode val = null ; EnumSet < Attribute > required = EnumSet . of ( Attribute . NAME , Attribute . PROP_VALUE ) ; final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { requireNoNamespaceAttribute ( reader , i ) ; final String value = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; required . remove ( attribute ) ; switch ( attribute ) { case NAME : { name = value ; break ; } case PROP_VALUE : { val = JacORBSubsystemDefinitions . PROPERTIES . parse ( value , reader . getLocation ( ) ) ; break ; } default : throw unexpectedAttribute ( reader , i ) ; } } if ( ! required . isEmpty ( ) ) { throw missingRequired ( reader , required ) ; } node . get ( name ) . set ( val ) ; requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses all attributes from the current element and sets them in the specified { @code ModelNode } . < / p > [CODESPLIT] private void parseAttributes ( XMLExtendedStreamReader reader , ModelNode node , EnumSet < Attribute > expectedAttributes , EnumSet < Attribute > requiredAttributes ) throws XMLStreamException { EnumSet < Attribute > parsedAttributes = EnumSet . noneOf ( Attribute . class ) ; if ( requiredAttributes == null ) { requiredAttributes = EnumSet . noneOf ( Attribute . class ) ; } for ( int i = 0 ; i < reader . getAttributeCount ( ) ; i ++ ) { requireNoNamespaceAttribute ( reader , i ) ; final String attrValue = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; // check for unexpected attributes. if ( ! expectedAttributes . contains ( attribute ) ) throw unexpectedAttribute ( reader , i ) ; // check for duplicate attributes. if ( ! parsedAttributes . add ( attribute ) ) { throw duplicateAttribute ( reader , attribute . getLocalName ( ) ) ; } requiredAttributes . remove ( attribute ) ; ( ( SimpleAttributeDefinition ) JacORBSubsystemDefinitions . valueOf ( attribute . getLocalName ( ) ) ) . parseAndSetParameter ( attrValue , node , reader ) ; } // throw an exception if a required attribute wasn't found. if ( ! requiredAttributes . isEmpty ( ) ) { throw missingRequired ( reader , requiredAttributes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Writes the { @code orb } section of the JacORB subsystem configuration using the contents of the provided { @code ModelNode } . < / p > [CODESPLIT] private void writeORBConfig ( XMLExtendedStreamWriter writer , ModelNode node ) throws XMLStreamException { boolean writeORB = this . isWritable ( node , JacORBSubsystemDefinitions . ORB_ATTRIBUTES ) ; boolean writeORBConnection = this . isWritable ( node , JacORBSubsystemDefinitions . ORB_CONN_ATTRIBUTES ) ; boolean writeORBInitializer = this . isWritable ( node , JacORBSubsystemDefinitions . ORB_INIT_ATTRIBUTES ) ; // if no connection or initializers properties are available, just write the orb properties (if any) in an empty element. if ( ! writeORBConnection && ! writeORBInitializer ) { if ( writeORB ) { writer . writeEmptyElement ( JacORBSubsystemConstants . ORB ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . ORB_ATTRIBUTES ) ; } } // otherwise write the orb element with the appropriate sub-elements. else { writer . writeStartElement ( JacORBSubsystemConstants . ORB ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . ORB_ATTRIBUTES ) ; if ( writeORBConnection ) { writer . writeEmptyElement ( JacORBSubsystemConstants . ORB_CONN ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . ORB_CONN_ATTRIBUTES ) ; } if ( writeORBInitializer ) { writer . writeEmptyElement ( JacORBSubsystemConstants . ORB_INIT ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . ORB_INIT_ATTRIBUTES ) ; } writer . writeEndElement ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Writes the { @code poa } section of the JacORB subsystem configuration using the contents of the provided { @code ModelNode } . < / p > [CODESPLIT] private void writePOAConfig ( XMLExtendedStreamWriter writer , ModelNode node ) throws XMLStreamException { boolean writePOA = this . isWritable ( node , JacORBSubsystemDefinitions . POA_ATTRIBUTES ) ; boolean writePOARP = this . isWritable ( node , JacORBSubsystemDefinitions . POA_RP_ATTRIBUTES ) ; // if no request processor properties are available, just write the poa properties (if any) in an empty element. if ( ! writePOARP ) { if ( writePOA ) { writer . writeEmptyElement ( JacORBSubsystemConstants . POA ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . POA_ATTRIBUTES ) ; } } // otherwise write the poa element with the appropriate sub-elements. else { writer . writeStartElement ( JacORBSubsystemConstants . POA ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . POA_ATTRIBUTES ) ; writer . writeEmptyElement ( JacORBSubsystemConstants . POA_RP ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . POA_RP_ATTRIBUTES ) ; writer . writeEndElement ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Writes the { @code naming } section of the JacORB subsystem configuration using the contents of the provided { @code ModelNode } . < / p > [CODESPLIT] private void writeNamingConfig ( XMLExtendedStreamWriter writer , ModelNode node ) throws XMLStreamException { boolean writeNaming = this . isWritable ( node , JacORBSubsystemDefinitions . NAMING_ATTRIBUTES ) ; if ( writeNaming ) { writer . writeEmptyElement ( JacORBSubsystemConstants . NAMING ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . NAMING_ATTRIBUTES ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Writes the { @code interop } section of the JacORB subsystem configuration using the contents of the provided { @code ModelNode } . < / p > [CODESPLIT] private void writeInteropConfig ( XMLExtendedStreamWriter writer , ModelNode node ) throws XMLStreamException { boolean writeInterop = this . isWritable ( node , JacORBSubsystemDefinitions . INTEROP_ATTRIBUTES ) ; if ( writeInterop ) { writer . writeEmptyElement ( JacORBSubsystemConstants . INTEROP ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . INTEROP_ATTRIBUTES ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Writes the { @code security } section of the JacORB subsystem configuration using the contents of the provided { @code ModelNode } . < / p > [CODESPLIT] private void writeSecurityConfig ( XMLExtendedStreamWriter writer , ModelNode node ) throws XMLStreamException { boolean writeSecurity = this . isWritable ( node , JacORBSubsystemDefinitions . SECURITY_ATTRIBUTES ) ; if ( writeSecurity ) { writer . writeEmptyElement ( SECURITY ) ; this . writeAttributes ( writer , node , JacORBSubsystemDefinitions . SECURITY_ATTRIBUTES ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Writes a { @code property } element for each generic property contained in the specified { @code ModelNode } . < / p > [CODESPLIT] private void writeGenericProperties ( XMLExtendedStreamWriter writer , ModelNode node ) throws XMLStreamException { writer . writeStartElement ( JacORBSubsystemConstants . PROPERTIES ) ; for ( Property prop : node . asPropertyList ( ) ) { writer . writeEmptyElement ( JacORBSubsystemConstants . PROPERTY ) ; writer . writeAttribute ( JacORBSubsystemConstants . NAME , prop . getName ( ) ) ; writer . writeAttribute ( JacORBSubsystemConstants . PROPERTY_VALUE , prop . getValue ( ) . asString ( ) ) ; } writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Writes the attributes contained in the specified { @code ModelNode } to the current element . < / p > [CODESPLIT] private void writeAttributes ( XMLExtendedStreamWriter writer , ModelNode node , List < SimpleAttributeDefinition > attributes ) throws XMLStreamException { for ( SimpleAttributeDefinition definition : attributes ) definition . marshallAsAttribute ( node , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Iterates through the specified attribute definitions and checks if any of the attributes can be written to XML by verifying if the attribute has been defined in the supplied node . < / p > [CODESPLIT] private boolean isWritable ( ModelNode node , List < SimpleAttributeDefinition > attributeDefinitions ) { boolean isWritable = false ; for ( SimpleAttributeDefinition attributeDefinition : attributeDefinitions ) { if ( attributeDefinition . isMarshallable ( node ) ) { isWritable = true ; break ; } } return isWritable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a ContextService for this module . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; if ( DeploymentTypeMarker . isType ( DeploymentType . EAR , deploymentUnit ) ) { return ; } EEModuleDescription moduleDescription = deploymentUnit . getAttachment ( EE_MODULE_DESCRIPTION ) ; final ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; final ServiceName appContextServiceName = ContextNames . contextServiceNameOfApplication ( moduleDescription . getApplicationName ( ) ) ; final ServiceName moduleContextServiceName = ContextNames . contextServiceNameOfModule ( moduleDescription . getApplicationName ( ) , moduleDescription . getModuleName ( ) ) ; final NamingStoreService contextService = new NamingStoreService ( true ) ; serviceTarget . addService ( moduleContextServiceName , contextService ) . install ( ) ; final ServiceName moduleNameServiceName = moduleContextServiceName . append ( \"ModuleName\" ) ; final BinderService moduleNameBinder = new BinderService ( \"ModuleName\" ) ; moduleNameBinder . getManagedObjectInjector ( ) . inject ( new ValueManagedReferenceFactory ( Values . immediateValue ( moduleDescription . getModuleName ( ) ) ) ) ; serviceTarget . addService ( moduleNameServiceName , moduleNameBinder ) . addDependency ( moduleContextServiceName , ServiceBasedNamingStore . class , moduleNameBinder . getNamingStoreInjector ( ) ) . install ( ) ; deploymentUnit . addToAttachmentList ( org . jboss . as . server . deployment . Attachments . JNDI_DEPENDENCIES , moduleNameServiceName ) ; deploymentUnit . putAttachment ( MODULE_CONTEXT_CONFIG , moduleContextServiceName ) ; final InjectedEENamespaceContextSelector selector = new InjectedEENamespaceContextSelector ( ) ; phaseContext . addDependency ( appContextServiceName , NamingStore . class , selector . getAppContextInjector ( ) ) ; phaseContext . addDependency ( moduleContextServiceName , NamingStore . class , selector . getModuleContextInjector ( ) ) ; phaseContext . addDependency ( moduleContextServiceName , NamingStore . class , selector . getCompContextInjector ( ) ) ; phaseContext . addDependency ( ContextNames . JBOSS_CONTEXT_SERVICE_NAME , NamingStore . class , selector . getJbossContextInjector ( ) ) ; phaseContext . addDependency ( ContextNames . EXPORTED_CONTEXT_SERVICE_NAME , NamingStore . class , selector . getExportedContextInjector ( ) ) ; phaseContext . addDependency ( ContextNames . GLOBAL_CONTEXT_SERVICE_NAME , NamingStore . class , selector . getGlobalContextInjector ( ) ) ; moduleDescription . setNamespaceContextSelector ( selector ) ; final Set < ServiceName > serviceNames = new HashSet < ServiceName > ( ) ; serviceNames . add ( appContextServiceName ) ; serviceNames . add ( moduleContextServiceName ) ; serviceNames . add ( ContextNames . JBOSS_CONTEXT_SERVICE_NAME ) ; serviceNames . add ( ContextNames . GLOBAL_CONTEXT_SERVICE_NAME ) ; // add the arquillian setup action, so the module namespace is available in arquillian tests final JavaNamespaceSetup setupAction = new JavaNamespaceSetup ( selector , deploymentUnit . getServiceName ( ) ) ; deploymentUnit . addToAttachmentList ( SETUP_ACTIONS , setupAction ) ; deploymentUnit . addToAttachmentList ( org . jboss . as . ee . component . Attachments . WEB_SETUP_ACTIONS , setupAction ) ; deploymentUnit . putAttachment ( Attachments . JAVA_NAMESPACE_SETUP_ACTION , setupAction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves persistence - unit - ref [CODESPLIT] private List < BindingConfiguration > getPersistenceUnitRefs ( DeploymentUnit deploymentUnit , DeploymentDescriptorEnvironment environment , ClassLoader classLoader , DeploymentReflectionIndex deploymentReflectionIndex , ResourceInjectionTarget resourceInjectionTarget ) throws DeploymentUnitProcessingException { final List < BindingConfiguration > bindingConfigurations = new ArrayList < BindingConfiguration > ( ) ; if ( environment . getEnvironment ( ) == null ) { return bindingConfigurations ; } PersistenceUnitReferencesMetaData persistenceUnitRefs = environment . getEnvironment ( ) . getPersistenceUnitRefs ( ) ; if ( persistenceUnitRefs != null ) { if ( persistenceUnitRefs . size ( ) > 0 ) { JPADeploymentMarker . mark ( deploymentUnit ) ; } for ( PersistenceUnitReferenceMetaData puRef : persistenceUnitRefs ) { String name = puRef . getName ( ) ; String persistenceUnitName = puRef . getPersistenceUnitName ( ) ; String lookup = puRef . getLookupName ( ) ; if ( ! isEmpty ( lookup ) && ! isEmpty ( persistenceUnitName ) ) { throw JpaLogger . ROOT_LOGGER . cannotSpecifyBoth ( \"<lookup-name>\" , lookup , \"persistence-unit-name\" , persistenceUnitName , \"<persistence-unit-ref/>\" , resourceInjectionTarget ) ; } if ( ! name . startsWith ( \"java:\" ) ) { name = environment . getDefaultContext ( ) + name ; } // our injection (source) comes from the local (ENC) lookup, no matter what. LookupInjectionSource injectionSource = new LookupInjectionSource ( name ) ; //add any injection targets processInjectionTargets ( resourceInjectionTarget , injectionSource , classLoader , deploymentReflectionIndex , puRef , EntityManagerFactory . class ) ; BindingConfiguration bindingConfiguration = null ; if ( ! isEmpty ( lookup ) ) { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( lookup ) ) ; } else { InjectionSource puBindingSource = this . getPersistenceUnitBindingSource ( deploymentUnit , persistenceUnitName ) ; bindingConfiguration = new BindingConfiguration ( name , puBindingSource ) ; } bindingConfigurations . add ( bindingConfiguration ) ; } } return bindingConfigurations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves persistence - unit - ref [CODESPLIT] private List < BindingConfiguration > getPersistenceContextRefs ( DeploymentUnit deploymentUnit , DeploymentDescriptorEnvironment environment , ClassLoader classLoader , DeploymentReflectionIndex deploymentReflectionIndex , ResourceInjectionTarget resourceInjectionTarget ) throws DeploymentUnitProcessingException { List < BindingConfiguration > bindingConfigurations = new ArrayList < BindingConfiguration > ( ) ; final RemoteEnvironment remoteEnvironment = environment . getEnvironment ( ) ; if ( remoteEnvironment == null ) { return bindingConfigurations ; } if ( remoteEnvironment instanceof Environment ) { PersistenceContextReferencesMetaData persistenceUnitRefs = ( ( Environment ) remoteEnvironment ) . getPersistenceContextRefs ( ) ; if ( persistenceUnitRefs != null ) { for ( PersistenceContextReferenceMetaData puRef : persistenceUnitRefs ) { String name = puRef . getName ( ) ; String persistenceUnitName = puRef . getPersistenceUnitName ( ) ; String lookup = puRef . getLookupName ( ) ; if ( ! isEmpty ( lookup ) && ! isEmpty ( persistenceUnitName ) ) { throw JpaLogger . ROOT_LOGGER . cannotSpecifyBoth ( \"<lookup-name>\" , lookup , \"persistence-unit-name\" , persistenceUnitName , \"<persistence-context-ref/>\" , resourceInjectionTarget ) ; } if ( ! name . startsWith ( \"java:\" ) ) { name = environment . getDefaultContext ( ) + name ; } // our injection (source) comes from the local (ENC) lookup, no matter what. LookupInjectionSource injectionSource = new LookupInjectionSource ( name ) ; //add any injection targets processInjectionTargets ( resourceInjectionTarget , injectionSource , classLoader , deploymentReflectionIndex , puRef , EntityManager . class ) ; BindingConfiguration bindingConfiguration = null ; if ( ! isEmpty ( lookup ) ) { bindingConfiguration = new BindingConfiguration ( name , new LookupInjectionSource ( lookup ) ) ; } else { PropertiesMetaData properties = puRef . getProperties ( ) ; Map < String , String > map = new HashMap <> ( ) ; if ( properties != null ) { for ( PropertyMetaData prop : properties ) { map . put ( prop . getKey ( ) , prop . getValue ( ) ) ; } } PersistenceContextType type = ( puRef . getPersistenceContextType ( ) == null || puRef . getPersistenceContextType ( ) == PersistenceContextTypeDescription . TRANSACTION ) ? PersistenceContextType . TRANSACTION : PersistenceContextType . EXTENDED ; SynchronizationType synchronizationType = ( puRef . getPersistenceContextSynchronization ( ) == null || PersistenceContextSynchronizationType . Synchronized . equals ( puRef . getPersistenceContextSynchronization ( ) ) ) ? SynchronizationType . SYNCHRONIZED : SynchronizationType . UNSYNCHRONIZED ; InjectionSource pcBindingSource = this . getPersistenceContextBindingSource ( deploymentUnit , persistenceUnitName , type , synchronizationType , map ) ; bindingConfiguration = new BindingConfiguration ( name , pcBindingSource ) ; } bindingConfigurations . add ( bindingConfiguration ) ; } } } return bindingConfigurations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add dependencies for modules required for manged bean deployments if managed bean configurations are attached to the deployment . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final JBossServiceXmlDescriptor serviceXmlDescriptor = deploymentUnit . getAttachment ( JBossServiceXmlDescriptor . ATTACHMENT_KEY ) ; if ( serviceXmlDescriptor == null ) { return ; // Skip deployments with out a service xml descriptor } moduleSpecification . addSystemDependency ( new ModuleDependency ( Module . getBootModuleLoader ( ) , JBOSS_MODULES_ID , false , false , false , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( Module . getBootModuleLoader ( ) , JBOSS_AS_SYSTEM_JMX_ID , true , false , false , false ) ) ; // depend on Properties editor module which uses ServiceLoader approach to load the appropriate org.jboss.common.beans.property.finder.PropertyEditorFinder moduleSpecification . addSystemDependency ( new ModuleDependency ( Module . getBootModuleLoader ( ) , PROPERTIES_EDITOR_MODULE_ID , false , false , true , false ) ) ; // All SARs require the ability to register MBeans. moduleSpecification . addPermissionFactory ( REGISTER_PERMISSION_FACTORY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the work contained in { @param runnable } as an authenticated Identity . [CODESPLIT] public void runWork ( Runnable work ) { // if we have an authenticated subject we check if it contains a security identity and use the identity to run the work. if ( this . authenticatedSubject != null ) { Set < SecurityIdentity > authenticatedIdentities = this . getPrivateCredentials ( SecurityIdentity . class ) ; if ( ! authenticatedIdentities . isEmpty ( ) ) { SecurityIdentity identity = authenticatedIdentities . iterator ( ) . next ( ) ; identity . runAs ( work ) ; return ; } } // no authenticated subject found or the subject didn't have a security identity - just run the work. work . run ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( XMLExtendedStreamReader reader , List < ModelNode > list ) throws XMLStreamException { // no attributes if ( reader . getAttributeCount ( ) > 0 ) { throw unexpectedAttribute ( reader , 0 ) ; } final ModelNode address = new ModelNode ( ) ; address . add ( ModelDescriptionConstants . SUBSYSTEM , TransactionExtension . SUBSYSTEM_NAME ) ; address . protect ( ) ; final ModelNode subsystem = new ModelNode ( ) ; subsystem . get ( OP ) . set ( ADD ) ; subsystem . get ( OP_ADDR ) . set ( address ) ; list . add ( subsystem ) ; final ModelNode logStoreAddress = address . clone ( ) ; final ModelNode logStoreOperation = new ModelNode ( ) ; logStoreOperation . get ( OP ) . set ( ADD ) ; logStoreAddress . add ( LogStoreConstants . LOG_STORE , LogStoreConstants . LOG_STORE ) ; logStoreAddress . protect ( ) ; logStoreOperation . get ( OP_ADDR ) . set ( logStoreAddress ) ; list . add ( logStoreOperation ) ; // elements final EnumSet < Element > required = EnumSet . of ( Element . RECOVERY_ENVIRONMENT , Element . CORE_ENVIRONMENT ) ; final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; choiceObjectStoreEncountered = false ; needsDefaultRelativeTo = true ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { if ( Namespace . forUri ( reader . getNamespaceURI ( ) ) != getExpectedNamespace ( ) ) { throw unexpectedElement ( reader ) ; } final Element element = Element . forName ( reader . getLocalName ( ) ) ; required . remove ( element ) ; if ( ! encountered . add ( element ) ) { throw unexpectedElement ( reader ) ; } readElement ( reader , element , list , subsystem , logStoreOperation ) ; } if ( needsDefaultRelativeTo && relativeToHasDefaultValue ) { TransactionSubsystemRootResourceDefinition . OBJECT_STORE_RELATIVE_TO . parseAndSetParameter ( \"jboss.server.data.dir\" , subsystem , reader ) ; } if ( ! required . isEmpty ( ) ) { throw missingRequiredElement ( reader , required ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void execute ( OperationContext context , ModelNode operation ) throws OperationFailedException { if ( context . isNormalServer ( ) ) { context . addStep ( new OperationStepHandler ( ) { public void execute ( OperationContext context , ModelNode operation ) throws OperationFailedException { final ServiceRegistry registry = context . getServiceRegistry ( false ) ; if ( registry != null ) { try { context . getResult ( ) . set ( getEndpointMetricsFragment ( operation , registry ) ) ; } catch ( Exception e ) { throw new OperationFailedException ( getFallbackMessage ( ) + \": \" + e . getMessage ( ) ) ; } } else { context . getResult ( ) . set ( getFallbackMessage ( ) ) ; } } } , OperationContext . Stage . RUNTIME ) ; } else { context . getResult ( ) . set ( getFallbackMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the outgoing SAS reply to <code > ContextError< / code > with major status invalid evidence . < / p > [CODESPLIT] void rejectIncomingContext ( ) { CurrentRequestInfo threadLocal = threadLocalData . get ( ) ; if ( threadLocal . sasContextReceived ) { threadLocal . sasReply = ( threadLocal . contextId == 0 ) ? msgCtx0Rejected : createMsgCtxError ( threadLocal . contextId , 1 /* major status: invalid evidence */ ) ; threadLocal . sasReplyIsAccept = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add one PU service per top level deployment that represents [CODESPLIT] private static void addPuService ( final DeploymentPhaseContext phaseContext , final ArrayList < PersistenceUnitMetadataHolder > puList , final boolean startEarly , final Platform platform ) throws DeploymentUnitProcessingException { if ( puList . size ( ) > 0 ) { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; final EEModuleDescription eeModuleDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_MODULE_DESCRIPTION ) ; final ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; final ModuleClassLoader classLoader = module . getClassLoader ( ) ; for ( PersistenceUnitMetadataHolder holder : puList ) { setAnnotationIndexes ( holder , deploymentUnit ) ; for ( PersistenceUnitMetadata pu : holder . getPersistenceUnits ( ) ) { // only start the persistence unit if JPA_CONTAINER_MANAGED is true String jpaContainerManaged = pu . getProperties ( ) . getProperty ( Configuration . JPA_CONTAINER_MANAGED ) ; boolean deployPU = ( jpaContainerManaged == null ? true : Boolean . parseBoolean ( jpaContainerManaged ) ) ; if ( deployPU ) { final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder ( deploymentUnit ) ; final PersistenceProvider provider = lookupProvider ( pu , persistenceProviderDeploymentHolder , deploymentUnit ) ; final PersistenceProviderAdaptor adaptor = getPersistenceProviderAdaptor ( pu , persistenceProviderDeploymentHolder , deploymentUnit , provider , platform ) ; final boolean twoPhaseBootStrapCapable = ( adaptor instanceof TwoPhaseBootstrapCapable ) && Configuration . allowTwoPhaseBootstrap ( pu ) ; if ( startEarly ) { if ( twoPhaseBootStrapCapable ) { deployPersistenceUnitPhaseOne ( deploymentUnit , eeModuleDescription , serviceTarget , classLoader , pu , adaptor ) ; } else if ( false == Configuration . needClassFileTransformer ( pu ) ) { // will start later when startEarly == false ROOT_LOGGER . tracef ( \"persistence unit %s in deployment %s is configured to not need class transformer to be set, no class rewriting will be allowed\" , pu . getPersistenceUnitName ( ) , deploymentUnit . getName ( ) ) ; } else { // we need class file transformer to work, don't allow cdi bean manager to be access since that // could cause application classes to be loaded (workaround by setting jboss.as.jpa.classtransformer to false).  WFLY-1463 final boolean allowCdiBeanManagerAccess = false ; deployPersistenceUnit ( deploymentUnit , eeModuleDescription , serviceTarget , classLoader , pu , provider , adaptor , allowCdiBeanManagerAccess ) ; } } else { // !startEarly if ( twoPhaseBootStrapCapable ) { deployPersistenceUnitPhaseTwo ( deploymentUnit , eeModuleDescription , serviceTarget , classLoader , pu , provider , adaptor ) ; } else if ( false == Configuration . needClassFileTransformer ( pu ) ) { final boolean allowCdiBeanManagerAccess = true ; // PUs that have Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false will start during INSTALL phase deployPersistenceUnit ( deploymentUnit , eeModuleDescription , serviceTarget , classLoader , pu , provider , adaptor , allowCdiBeanManagerAccess ) ; } } } else { ROOT_LOGGER . tracef ( \"persistence unit %s in deployment %s is not container managed (%s is set to false)\" , pu . getPersistenceUnitName ( ) , deploymentUnit . getName ( ) , Configuration . JPA_CONTAINER_MANAGED ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start the persistence unit in one phase [CODESPLIT] private static void deployPersistenceUnit ( final DeploymentUnit deploymentUnit , final EEModuleDescription eeModuleDescription , final ServiceTarget serviceTarget , final ModuleClassLoader classLoader , final PersistenceUnitMetadata pu , final PersistenceProvider provider , final PersistenceProviderAdaptor adaptor , final boolean allowCdiBeanManagerAccess ) throws DeploymentUnitProcessingException { pu . setClassLoader ( classLoader ) ; TransactionManager transactionManager = ContextTransactionManager . getInstance ( ) ; TransactionSynchronizationRegistry transactionSynchronizationRegistry = deploymentUnit . getAttachment ( JpaAttachments . TRANSACTION_SYNCHRONIZATION_REGISTRY ) ; CapabilityServiceSupport capabilitySupport = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; try { ValidatorFactory validatorFactory = null ; final HashMap < String , ValidatorFactory > properties = new HashMap <> ( ) ; CapabilityServiceSupport css = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; if ( ! ValidationMode . NONE . equals ( pu . getValidationMode ( ) ) ) { if ( css . hasCapability ( \"org.wildfly.bean-validation\" ) ) { // Get the CDI-enabled ValidatorFactory validatorFactory = deploymentUnit . getAttachment ( BeanValidationAttachments . VALIDATOR_FACTORY ) ; } } BeanManagerAfterDeploymentValidation beanManagerAfterDeploymentValidation = registerJPAEntityListenerRegister ( deploymentUnit , capabilitySupport ) ; final PersistenceAdaptorRemoval persistenceAdaptorRemoval = new PersistenceAdaptorRemoval ( pu , adaptor ) ; deploymentUnit . addToAttachmentList ( REMOVAL_KEY , persistenceAdaptorRemoval ) ; // add persistence provider specific properties adaptor . addProviderProperties ( properties , pu ) ; final ServiceName puServiceName = PersistenceUnitServiceImpl . getPUServiceName ( pu ) ; deploymentUnit . putAttachment ( JpaAttachments . PERSISTENCE_UNIT_SERVICE_KEY , puServiceName ) ; deploymentUnit . addToAttachmentList ( Attachments . DEPLOYMENT_COMPLETE_SERVICES , puServiceName ) ; deploymentUnit . addToAttachmentList ( Attachments . WEB_DEPENDENCIES , puServiceName ) ; final PersistenceUnitServiceImpl service = new PersistenceUnitServiceImpl ( properties , classLoader , pu , adaptor , provider , PersistenceUnitRegistryImpl . INSTANCE , deploymentUnit . getServiceName ( ) , validatorFactory , deploymentUnit . getAttachment ( org . jboss . as . ee . naming . Attachments . JAVA_NAMESPACE_SETUP_ACTION ) , beanManagerAfterDeploymentValidation ) ; ServiceBuilder < PersistenceUnitService > builder = serviceTarget . addService ( puServiceName , service ) ; boolean useDefaultDataSource = Configuration . allowDefaultDataSourceUse ( pu ) ; final String jtaDataSource = adjustJndi ( pu . getJtaDataSourceName ( ) ) ; final String nonJtaDataSource = adjustJndi ( pu . getNonJtaDataSourceName ( ) ) ; if ( jtaDataSource != null && jtaDataSource . length ( ) > 0 ) { if ( jtaDataSource . equals ( EE_DEFAULT_DATASOURCE ) ) { // explicit use of default datasource useDefaultDataSource = true ; } else { builder . addDependency ( ContextNames . bindInfoForEnvEntry ( eeModuleDescription . getApplicationName ( ) , eeModuleDescription . getModuleName ( ) , eeModuleDescription . getModuleName ( ) , false , jtaDataSource ) . getBinderServiceName ( ) , ManagedReferenceFactory . class , new ManagedReferenceFactoryInjector ( service . getJtaDataSourceInjector ( ) ) ) ; useDefaultDataSource = false ; } } if ( nonJtaDataSource != null && nonJtaDataSource . length ( ) > 0 ) { builder . addDependency ( ContextNames . bindInfoForEnvEntry ( eeModuleDescription . getApplicationName ( ) , eeModuleDescription . getModuleName ( ) , eeModuleDescription . getModuleName ( ) , false , nonJtaDataSource ) . getBinderServiceName ( ) , ManagedReferenceFactory . class , new ManagedReferenceFactoryInjector ( service . getNonJtaDataSourceInjector ( ) ) ) ; useDefaultDataSource = false ; } // JPA 2.0 8.2.1.5, container provides default JTA datasource if ( useDefaultDataSource ) { // try the default datasource defined in the ee subsystem String defaultJtaDataSource = null ; if ( eeModuleDescription != null ) { defaultJtaDataSource = eeModuleDescription . getDefaultResourceJndiNames ( ) . getDataSource ( ) ; } if ( defaultJtaDataSource == null || defaultJtaDataSource . isEmpty ( ) ) { // try the datasource defined in the jpa subsystem defaultJtaDataSource = adjustJndi ( JPAService . getDefaultDataSourceName ( ) ) ; } if ( defaultJtaDataSource != null && ! defaultJtaDataSource . isEmpty ( ) ) { builder . addDependency ( ContextNames . bindInfoFor ( defaultJtaDataSource ) . getBinderServiceName ( ) , ManagedReferenceFactory . class , new ManagedReferenceFactoryInjector ( service . getJtaDataSourceInjector ( ) ) ) ; ROOT_LOGGER . tracef ( \"%s is using the default data source '%s'\" , puServiceName , defaultJtaDataSource ) ; } } // JPA 2.1 sections 3.5.1 + 9.1 require the CDI bean manager to be passed to the peristence provider // if the persistence unit is contained in a deployment that is a CDI bean archive (has beans.xml). final CapabilityServiceSupport support = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; if ( support . hasCapability ( WELD_CAPABILITY_NAME ) && allowCdiBeanManagerAccess ) { support . getOptionalCapabilityRuntimeAPI ( WELD_CAPABILITY_NAME , WeldCapability . class ) . get ( ) . addBeanManagerService ( deploymentUnit , builder , service . getBeanManagerInjector ( ) ) ; } try { // save a thread local reference to the builder for setting up the second level cache dependencies CacheDeploymentListener . setInternalDeploymentSupport ( builder , capabilitySupport ) ; adaptor . addProviderDependencies ( pu ) ; } finally { CacheDeploymentListener . clearInternalDeploymentSupport ( ) ; } /**\n             * handle extension that binds a transaction scoped entity manager to specified JNDI location\n             */ entityManagerBind ( eeModuleDescription , serviceTarget , pu , puServiceName , transactionManager , transactionSynchronizationRegistry ) ; /**\n             * handle extension that binds an entity manager factory to specified JNDI location\n             */ entityManagerFactoryBind ( eeModuleDescription , serviceTarget , pu , puServiceName ) ; // get async executor from Services.addServerExecutorDependency addServerExecutorDependency ( builder , service . getExecutorInjector ( ) ) ; builder . install ( ) ; ROOT_LOGGER . tracef ( \"added PersistenceUnitService for '%s'.  PU is ready for injector action.\" , puServiceName ) ; addManagementConsole ( deploymentUnit , pu , adaptor , persistenceAdaptorRemoval ) ; } catch ( ServiceRegistryException e ) { throw JpaLogger . ROOT_LOGGER . failedToAddPersistenceUnit ( e , pu . getPersistenceUnitName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "first phase of starting the persistence unit [CODESPLIT] private static void deployPersistenceUnitPhaseOne ( final DeploymentUnit deploymentUnit , final EEModuleDescription eeModuleDescription , final ServiceTarget serviceTarget , final ModuleClassLoader classLoader , final PersistenceUnitMetadata pu , final PersistenceProviderAdaptor adaptor ) throws DeploymentUnitProcessingException { CapabilityServiceSupport capabilitySupport = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; pu . setClassLoader ( classLoader ) ; try { final HashMap < String , ValidatorFactory > properties = new HashMap <> ( ) ; ProxyBeanManager proxyBeanManager = null ; // JPA 2.1 sections 3.5.1 + 9.1 require the CDI bean manager to be passed to the peristence provider // if the persistence unit is contained in a deployment that is a CDI bean archive (has beans.xml). final CapabilityServiceSupport support = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; boolean partOfWeldDeployment = false ; if ( support . hasCapability ( WELD_CAPABILITY_NAME ) ) { partOfWeldDeployment = support . getOptionalCapabilityRuntimeAPI ( WELD_CAPABILITY_NAME , WeldCapability . class ) . get ( ) . isPartOfWeldDeployment ( deploymentUnit ) ; } if ( partOfWeldDeployment ) { proxyBeanManager = new ProxyBeanManager ( ) ; registerJPAEntityListenerRegister ( deploymentUnit , support ) ; // register CDI extension before WeldDeploymentProcessor, which is important for // EAR deployments that contain a WAR that has persistence units defined. } deploymentUnit . addToAttachmentList ( REMOVAL_KEY , new PersistenceAdaptorRemoval ( pu , adaptor ) ) ; // add persistence provider specific properties adaptor . addProviderProperties ( properties , pu ) ; final ServiceName puServiceName = PersistenceUnitServiceImpl . getPUServiceName ( pu ) . append ( FIRST_PHASE ) ; deploymentUnit . putAttachment ( JpaAttachments . PERSISTENCE_UNIT_SERVICE_KEY , puServiceName ) ; deploymentUnit . addToAttachmentList ( Attachments . DEPLOYMENT_COMPLETE_SERVICES , puServiceName ) ; deploymentUnit . addToAttachmentList ( Attachments . WEB_DEPENDENCIES , puServiceName ) ; final PhaseOnePersistenceUnitServiceImpl service = new PhaseOnePersistenceUnitServiceImpl ( classLoader , pu , adaptor , deploymentUnit . getServiceName ( ) , proxyBeanManager ) ; service . getPropertiesInjector ( ) . inject ( properties ) ; ServiceBuilder < PhaseOnePersistenceUnitServiceImpl > builder = serviceTarget . addService ( puServiceName , service ) ; boolean useDefaultDataSource = Configuration . allowDefaultDataSourceUse ( pu ) ; final String jtaDataSource = adjustJndi ( pu . getJtaDataSourceName ( ) ) ; final String nonJtaDataSource = adjustJndi ( pu . getNonJtaDataSourceName ( ) ) ; if ( jtaDataSource != null && jtaDataSource . length ( ) > 0 ) { if ( jtaDataSource . equals ( EE_DEFAULT_DATASOURCE ) ) { // explicit use of default datasource useDefaultDataSource = true ; } else { builder . addDependency ( ContextNames . bindInfoForEnvEntry ( eeModuleDescription . getApplicationName ( ) , eeModuleDescription . getModuleName ( ) , eeModuleDescription . getModuleName ( ) , false , jtaDataSource ) . getBinderServiceName ( ) , ManagedReferenceFactory . class , new ManagedReferenceFactoryInjector ( service . getJtaDataSourceInjector ( ) ) ) ; useDefaultDataSource = false ; } } if ( nonJtaDataSource != null && nonJtaDataSource . length ( ) > 0 ) { builder . addDependency ( ContextNames . bindInfoForEnvEntry ( eeModuleDescription . getApplicationName ( ) , eeModuleDescription . getModuleName ( ) , eeModuleDescription . getModuleName ( ) , false , nonJtaDataSource ) . getBinderServiceName ( ) , ManagedReferenceFactory . class , new ManagedReferenceFactoryInjector ( service . getNonJtaDataSourceInjector ( ) ) ) ; useDefaultDataSource = false ; } // JPA 2.0 8.2.1.5, container provides default JTA datasource if ( useDefaultDataSource ) { // try the one defined in the jpa subsystem String defaultJtaDataSource = null ; if ( eeModuleDescription != null ) { defaultJtaDataSource = eeModuleDescription . getDefaultResourceJndiNames ( ) . getDataSource ( ) ; } if ( defaultJtaDataSource == null || defaultJtaDataSource . isEmpty ( ) ) { // try the datasource defined in the JPA subsystem defaultJtaDataSource = adjustJndi ( JPAService . getDefaultDataSourceName ( ) ) ; } if ( defaultJtaDataSource != null && ! defaultJtaDataSource . isEmpty ( ) ) { builder . addDependency ( ContextNames . bindInfoFor ( defaultJtaDataSource ) . getBinderServiceName ( ) , ManagedReferenceFactory . class , new ManagedReferenceFactoryInjector ( service . getJtaDataSourceInjector ( ) ) ) ; ROOT_LOGGER . tracef ( \"%s is using the default data source '%s'\" , puServiceName , defaultJtaDataSource ) ; } } try { // save a thread local reference to the builder for setting up the second level cache dependencies CacheDeploymentListener . setInternalDeploymentSupport ( builder , capabilitySupport ) ; adaptor . addProviderDependencies ( pu ) ; } finally { CacheDeploymentListener . clearInternalDeploymentSupport ( ) ; } // get async executor from Services.addServerExecutorDependency addServerExecutorDependency ( builder , service . getExecutorInjector ( ) ) ; builder . install ( ) ; ROOT_LOGGER . tracef ( \"added PersistenceUnitService (phase 1 of 2) for '%s'.  PU is ready for injector action.\" , puServiceName ) ; } catch ( ServiceRegistryException e ) { throw JpaLogger . ROOT_LOGGER . failedToAddPersistenceUnit ( e , pu . getPersistenceUnitName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup the annotation index map [CODESPLIT] private static void setAnnotationIndexes ( final PersistenceUnitMetadataHolder puHolder , DeploymentUnit deploymentUnit ) { final Map < URL , Index > annotationIndexes = new HashMap <> ( ) ; do { for ( ResourceRoot root : DeploymentUtils . allResourceRoots ( deploymentUnit ) ) { final Index index = root . getAttachment ( Attachments . ANNOTATION_INDEX ) ; if ( index != null ) { try { ROOT_LOGGER . tracef ( \"adding '%s' to annotation index map\" , root . getRoot ( ) . toURL ( ) ) ; annotationIndexes . put ( root . getRoot ( ) . toURL ( ) , index ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } deploymentUnit = deploymentUnit . getParent ( ) ; // get annotation indexes for top level also } while ( deploymentUnit != null ) ; for ( PersistenceUnitMetadata pu : puHolder . getPersistenceUnits ( ) ) { pu . setAnnotationIndex ( annotationIndexes ) ; // hold onto the annotation index for Persistence Provider use during deployment } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the persistence provider adaptor . Will load the adapter module if needed . [CODESPLIT] private static PersistenceProviderAdaptor getPersistenceProviderAdaptor ( final PersistenceUnitMetadata pu , final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder , final DeploymentUnit deploymentUnit , final PersistenceProvider provider , final Platform platform ) throws DeploymentUnitProcessingException { String adapterClass = pu . getProperties ( ) . getProperty ( Configuration . ADAPTER_CLASS ) ; /**\n         * use adapter packaged in application deployment.\n         */ if ( persistenceProviderDeploymentHolder != null && adapterClass != null ) { List < PersistenceProviderAdaptor > persistenceProviderAdaptors = persistenceProviderDeploymentHolder . getAdapters ( ) ; for ( PersistenceProviderAdaptor persistenceProviderAdaptor : persistenceProviderAdaptors ) { if ( adapterClass . equals ( persistenceProviderAdaptor . getClass ( ) . getName ( ) ) ) { return persistenceProviderAdaptor ; } } } String adaptorModule = pu . getProperties ( ) . getProperty ( Configuration . ADAPTER_MODULE ) ; PersistenceProviderAdaptor adaptor ; adaptor = getPerDeploymentSharedPersistenceProviderAdaptor ( deploymentUnit , adaptorModule , provider ) ; if ( adaptor == null ) { try { // will load the persistence provider adaptor (integration classes).  if adaptorModule is null // the noop adaptor is returned (can be used against any provider but the integration classes // are handled externally via properties or code in the persistence provider). if ( adaptorModule != null ) { // legacy way of loading adapter module adaptor = PersistenceProviderAdaptorLoader . loadPersistenceAdapterModule ( adaptorModule , platform , createManager ( deploymentUnit ) ) ; } else { adaptor = PersistenceProviderAdaptorLoader . loadPersistenceAdapter ( provider , platform , createManager ( deploymentUnit ) ) ; } } catch ( ModuleLoadException e ) { throw JpaLogger . ROOT_LOGGER . persistenceProviderAdaptorModuleLoadError ( e , adaptorModule ) ; } adaptor = savePerDeploymentSharedPersistenceProviderAdaptor ( deploymentUnit , adaptorModule , adaptor , provider ) ; } if ( adaptor == null ) { throw JpaLogger . ROOT_LOGGER . failedToGetAdapter ( pu . getPersistenceProviderClassName ( ) ) ; } return adaptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will save the PersistenceProviderAdaptor at the top level application deployment unit level for sharing with other persistence units [CODESPLIT] private static PersistenceProviderAdaptor savePerDeploymentSharedPersistenceProviderAdaptor ( DeploymentUnit deploymentUnit , String adaptorModule , PersistenceProviderAdaptor adaptor , PersistenceProvider provider ) { if ( deploymentUnit . getParent ( ) != null ) { deploymentUnit = deploymentUnit . getParent ( ) ; } synchronized ( deploymentUnit ) { Map < String , PersistenceProviderAdaptor > map = deploymentUnit . getAttachment ( providerAdaptorMapKey ) ; String key ; if ( adaptorModule != null ) { key = adaptorModule ; // handle legacy adapter module } else { key = provider . getClass ( ) . getName ( ) ; } PersistenceProviderAdaptor current = map . get ( key ) ; // saved if not already set by another thread if ( current == null ) { map . put ( key , adaptor ) ; current = adaptor ; } return current ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look up the persistence provider [CODESPLIT] private static PersistenceProvider lookupProvider ( PersistenceUnitMetadata pu , PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder , DeploymentUnit deploymentUnit ) throws DeploymentUnitProcessingException { /**\n         * check if the deployment is already associated with the specified persistence provider\n         */ Map < String , PersistenceProvider > providerMap = persistenceProviderDeploymentHolder != null ? persistenceProviderDeploymentHolder . getProviders ( ) : null ; if ( providerMap != null ) { synchronized ( providerMap ) { if ( providerMap . containsKey ( pu . getPersistenceProviderClassName ( ) ) ) { ROOT_LOGGER . tracef ( \"deployment %s is using %s\" , deploymentUnit . getName ( ) , pu . getPersistenceProviderClassName ( ) ) ; return providerMap . get ( pu . getPersistenceProviderClassName ( ) ) ; } } } String configuredPersistenceProviderModule = pu . getProperties ( ) . getProperty ( Configuration . PROVIDER_MODULE ) ; String persistenceProviderClassName = pu . getPersistenceProviderClassName ( ) ; if ( persistenceProviderClassName == null ) { persistenceProviderClassName = Configuration . PROVIDER_CLASS_DEFAULT ; } /**\n         * locate persistence provider in specified static module\n         */ if ( configuredPersistenceProviderModule != null ) { List < PersistenceProvider > providers ; if ( Configuration . PROVIDER_MODULE_APPLICATION_SUPPLIED . equals ( configuredPersistenceProviderModule ) ) { try { // load the persistence provider from the application deployment final ModuleClassLoader classLoader = deploymentUnit . getAttachment ( Attachments . MODULE ) . getClassLoader ( ) ; PersistenceProvider provider = PersistenceProviderLoader . loadProviderFromDeployment ( classLoader , persistenceProviderClassName ) ; providers = new ArrayList <> ( ) ; providers . add ( provider ) ; PersistenceProviderDeploymentHolder . savePersistenceProviderInDeploymentUnit ( deploymentUnit , providers , null ) ; return provider ; } catch ( ClassNotFoundException e ) { throw JpaLogger . ROOT_LOGGER . cannotDeployApp ( e , persistenceProviderClassName ) ; } catch ( InstantiationException e ) { throw JpaLogger . ROOT_LOGGER . cannotDeployApp ( e , persistenceProviderClassName ) ; } catch ( IllegalAccessException e ) { throw JpaLogger . ROOT_LOGGER . cannotDeployApp ( e , persistenceProviderClassName ) ; } } else { try { providers = PersistenceProviderLoader . loadProviderModuleByName ( configuredPersistenceProviderModule ) ; PersistenceProviderDeploymentHolder . savePersistenceProviderInDeploymentUnit ( deploymentUnit , providers , null ) ; PersistenceProvider provider = getProviderByName ( pu , providers ) ; if ( provider != null ) { return provider ; } } catch ( ModuleLoadException e ) { throw JpaLogger . ROOT_LOGGER . cannotLoadPersistenceProviderModule ( e , configuredPersistenceProviderModule , persistenceProviderClassName ) ; } } } // try to determine the static module name based on the persistence provider class name String providerNameDerivedFromClassName = Configuration . getProviderModuleNameFromProviderClassName ( persistenceProviderClassName ) ; // see if the providerNameDerivedFromClassName has been loaded yet PersistenceProvider provider = getProviderByName ( pu ) ; // if we haven't loaded the provider yet, try loading now if ( provider == null && providerNameDerivedFromClassName != null ) { try { List < PersistenceProvider > providers = PersistenceProviderLoader . loadProviderModuleByName ( providerNameDerivedFromClassName ) ; PersistenceProviderDeploymentHolder . savePersistenceProviderInDeploymentUnit ( deploymentUnit , providers , null ) ; provider = getProviderByName ( pu , providers ) ; } catch ( ModuleLoadException e ) { throw JpaLogger . ROOT_LOGGER . cannotLoadPersistenceProviderModule ( e , providerNameDerivedFromClassName , persistenceProviderClassName ) ; } } if ( provider == null ) throw JpaLogger . ROOT_LOGGER . persistenceProviderNotFound ( persistenceProviderClassName ) ; return provider ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The sub - deployment phases run in parallel ensure that no deployment / sub - deployment moves past Phase . FIRST_MODULE_USE until the applications persistence unit services are started . [CODESPLIT] private static void nextPhaseDependsOnPersistenceUnit ( final DeploymentPhaseContext phaseContext , final Platform platform ) throws DeploymentUnitProcessingException { final DeploymentUnit topDeploymentUnit = DeploymentUtils . getTopDeploymentUnit ( phaseContext . getDeploymentUnit ( ) ) ; final PersistenceUnitsInApplication persistenceUnitsInApplication = topDeploymentUnit . getAttachment ( PersistenceUnitsInApplication . PERSISTENCE_UNITS_IN_APPLICATION ) ; for ( final PersistenceUnitMetadataHolder holder : persistenceUnitsInApplication . getPersistenceUnitHolders ( ) ) { for ( final PersistenceUnitMetadata pu : holder . getPersistenceUnits ( ) ) { String jpaContainerManaged = pu . getProperties ( ) . getProperty ( Configuration . JPA_CONTAINER_MANAGED ) ; boolean deployPU = ( jpaContainerManaged == null ? true : Boolean . parseBoolean ( jpaContainerManaged ) ) ; if ( deployPU ) { final ServiceName puServiceName = PersistenceUnitServiceImpl . getPUServiceName ( pu ) ; final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder ( phaseContext . getDeploymentUnit ( ) ) ; final PersistenceProvider provider = lookupProvider ( pu , persistenceProviderDeploymentHolder , phaseContext . getDeploymentUnit ( ) ) ; final PersistenceProviderAdaptor adaptor = getPersistenceProviderAdaptor ( pu , persistenceProviderDeploymentHolder , phaseContext . getDeploymentUnit ( ) , provider , platform ) ; final boolean twoPhaseBootStrapCapable = ( adaptor instanceof TwoPhaseBootstrapCapable ) && Configuration . allowTwoPhaseBootstrap ( pu ) ; // only add the next phase dependency, if the persistence unit service is starting early. if ( Configuration . needClassFileTransformer ( pu ) ) { // wait until the persistence unit service is started before starting the next deployment phase phaseContext . addToAttachmentList ( Attachments . NEXT_PHASE_DEPS , twoPhaseBootStrapCapable ? puServiceName . append ( FIRST_PHASE ) : puServiceName ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add to management console ( if ManagementAdapter is supported for provider ) . <p / > full path to management data will be : <p / > / deployment = Deployment / subsystem = jpa / hibernate - persistence - unit = FullyAppQualifiedPath#PersistenceUnitName / cache = EntityClassName <p / > example of full path : <p / > / deployment = jpa_SecondLevelCacheTestCase . jar / subsystem = jpa / hibernate - persistence - unit = jpa_SecondLevelCacheTestCase . jar#mypc / cache = org . jboss . as . test . integration . jpa . hibernate . Employee [CODESPLIT] private static void addManagementConsole ( final DeploymentUnit deploymentUnit , final PersistenceUnitMetadata pu , final PersistenceProviderAdaptor adaptor , PersistenceAdaptorRemoval persistenceAdaptorRemoval ) { ManagementAdaptor managementAdaptor = adaptor . getManagementAdaptor ( ) ; // workaround for AS7-4441, if a custom hibernate.cache.region_prefix is specified, don't show the persistence // unit in management console. if ( managementAdaptor != null && adaptor . doesScopedPersistenceUnitNameIdentifyCacheRegionName ( pu ) ) { final String providerLabel = managementAdaptor . getIdentificationLabel ( ) ; final String scopedPersistenceUnitName = pu . getScopedPersistenceUnitName ( ) ; Resource providerResource = JPAService . createManagementStatisticsResource ( managementAdaptor , scopedPersistenceUnitName , deploymentUnit ) ; // Resource providerResource = managementAdaptor.createPersistenceUnitResource(scopedPersistenceUnitName, providerLabel); ModelNode perPuNode = providerResource . getModel ( ) ; perPuNode . get ( SCOPED_UNIT_NAME . getName ( ) ) . set ( pu . getScopedPersistenceUnitName ( ) ) ; // TODO this is a temporary hack into internals until DeploymentUnit exposes a proper Resource-based API final Resource deploymentResource = deploymentUnit . getAttachment ( DeploymentModelUtils . DEPLOYMENT_RESOURCE ) ; Resource subsystemResource ; synchronized ( deploymentResource ) { subsystemResource = getOrCreateResource ( deploymentResource , PathElement . pathElement ( ModelDescriptionConstants . SUBSYSTEM , \"jpa\" ) ) ; } synchronized ( subsystemResource ) { subsystemResource . registerChild ( PathElement . pathElement ( providerLabel , scopedPersistenceUnitName ) , providerResource ) ; // save the subsystemResource reference + path to scoped pu, so we can remove it during undeploy persistenceAdaptorRemoval . registerManagementConsoleChild ( subsystemResource , PathElement . pathElement ( providerLabel , scopedPersistenceUnitName ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO this is a temporary hack into internals until DeploymentUnit exposes a proper Resource - based API [CODESPLIT] private static Resource getOrCreateResource ( final Resource parent , final PathElement element ) { synchronized ( parent ) { if ( parent . hasChild ( element ) ) { return parent . requireChild ( element ) ; } else { final Resource resource = Resource . Factory . create ( ) ; parent . registerChild ( element , resource ) ; return resource ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "use a plain Set and it should work for both versions . [CODESPLIT] @ Override public Map < Class < ? extends Annotation > , Set < Class < ? > > > getAnnotatedClasses ( final Set uris ) { return annotations ; // TODO:  Should this be limited by URI }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds universal EJB meta data model that is AS agnostic . [CODESPLIT] final EJBArchiveMetaData create ( final Deployment dep ) { if ( WSLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { WSLogger . ROOT_LOGGER . tracef ( \"Building JBoss agnostic meta data for EJB webservice deployment: %s\" , dep . getSimpleName ( ) ) ; } final EJBArchiveMetaData . Builder ejbArchiveMDBuilder = new EJBArchiveMetaData . Builder ( ) ; this . buildEnterpriseBeansMetaData ( dep , ejbArchiveMDBuilder ) ; this . buildWebservicesMetaData ( dep , ejbArchiveMDBuilder ) ; return ejbArchiveMDBuilder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds webservices meta data . This methods sets : <ul > <li > context root< / li > <li > wsdl location resolver< / li > <li > config name< / li > <li > config file< / li > < / ul > [CODESPLIT] private void buildWebservicesMetaData ( final Deployment dep , final EJBArchiveMetaData . Builder ejbArchiveMDBuilder ) { final JBossWebservicesMetaData webservicesMD = WSHelper . getOptionalAttachment ( dep , JBossWebservicesMetaData . class ) ; if ( webservicesMD == null ) return ; // set context root final String contextRoot = webservicesMD . getContextRoot ( ) ; ejbArchiveMDBuilder . setWebServiceContextRoot ( contextRoot ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting context root: %s\" , contextRoot ) ; // set config name final String configName = webservicesMD . getConfigName ( ) ; ejbArchiveMDBuilder . setConfigName ( configName ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting config name: %s\" , configName ) ; // set config file final String configFile = webservicesMD . getConfigFile ( ) ; ejbArchiveMDBuilder . setConfigFile ( configFile ) ; WSLogger . ROOT_LOGGER . tracef ( \"Setting config file: %s\" , configFile ) ; // set wsdl location resolver final JBossWebserviceDescriptionMetaData [ ] wsDescriptionsMD = webservicesMD . getWebserviceDescriptions ( ) ; final PublishLocationAdapter resolver = new PublishLocationAdapterImpl ( wsDescriptionsMD ) ; ejbArchiveMDBuilder . setPublishLocationAdapter ( resolver ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds JBoss agnostic EJB meta data . [CODESPLIT] protected void buildEnterpriseBeanMetaData ( final List < EJBMetaData > wsEjbsMD , final EJBEndpoint ejbEndpoint , final JBossWebservicesMetaData jbossWebservicesMD ) { final SLSBMetaData . Builder wsEjbMDBuilder = new SLSBMetaData . Builder ( ) ; // set EJB name and class wsEjbMDBuilder . setEjbName ( ejbEndpoint . getName ( ) ) ; wsEjbMDBuilder . setEjbClass ( ejbEndpoint . getClassName ( ) ) ; final JBossPortComponentMetaData portComponentMD = getPortComponent ( ejbEndpoint . getName ( ) , jbossWebservicesMD ) ; if ( portComponentMD != null ) { // set port component meta data wsEjbMDBuilder . setPortComponentName ( portComponentMD . getPortComponentName ( ) ) ; wsEjbMDBuilder . setPortComponentURI ( portComponentMD . getPortComponentURI ( ) ) ; } // set security meta data // auth method final String authMethod = getAuthMethod ( ejbEndpoint , portComponentMD ) ; // transport guarantee final String transportGuarantee = getTransportGuarantee ( ejbEndpoint , portComponentMD ) ; // secure wsdl access final boolean secureWsdlAccess = isSecureWsdlAccess ( ejbEndpoint , portComponentMD ) ; final String realmName = getRealmName ( ejbEndpoint , portComponentMD ) ; // propagate wsEjbMDBuilder . setSecurityMetaData ( new EJBSecurityMetaData ( authMethod , realmName , transportGuarantee , secureWsdlAccess ) ) ; wsEjbsMD . add ( wsEjbMDBuilder . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that an updated address - settings still has resources bound corresponding to expiry - address and dead - letter - address ( if they are defined ) . [CODESPLIT] static void validateModel ( OperationContext context , ModelNode operation , Resource resource ) throws OperationFailedException { String addressSetting = PathAddress . pathAddress ( operation . require ( OP_ADDR ) ) . getLastElement ( ) . getValue ( ) ; PathAddress address = pathAddress ( operation . require ( ModelDescriptionConstants . OP_ADDR ) ) ; Resource activeMQServer = context . readResourceFromRoot ( MessagingServices . getActiveMQServerPathAddress ( address ) , true ) ; checkExpiryAddress ( context , resource . getModel ( ) , activeMQServer , addressSetting ) ; checkDeadLetterAddress ( context , resource . getModel ( ) , activeMQServer , addressSetting ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "refresh the attributes of this participant ( the status attribute should have changed to PREPARED [CODESPLIT] void refreshParticipant ( OperationContext context ) { context . addStep ( refreshHandler , OperationContext . Stage . MODEL , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the application name for the passed deployment . If the passed deployment isn t an . ear or doesn t belong to a . ear then this method returns null . Else it returns the application - name set in the application . xml of the . ear or if that s not set will return the . ear deployment unit name ( stripped off the . ear suffix ) . [CODESPLIT] private String getApplicationName ( DeploymentUnit deploymentUnit ) { final DeploymentUnit parentDU = deploymentUnit . getParent ( ) ; if ( parentDU == null ) { final EarMetaData earMetaData = deploymentUnit . getAttachment ( org . jboss . as . ee . structure . Attachments . EAR_METADATA ) ; if ( earMetaData != null ) { final String overriddenAppName = earMetaData . getApplicationName ( ) ; if ( overriddenAppName == null ) { return this . getEarName ( deploymentUnit ) ; } return overriddenAppName ; } else { return this . getEarName ( deploymentUnit ) ; } } // traverse to top level DU return this . getApplicationName ( parentDU ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name ( stripped off the . ear suffix ) of the passed <code > deploymentUnit< / code > . Returns null if the passed <code > deploymentUnit< / code > s name doesn t end with . ear suffix . [CODESPLIT] private String getEarName ( final DeploymentUnit deploymentUnit ) { final String duName = deploymentUnit . getName ( ) ; if ( duName . endsWith ( \".ear\" ) ) { return duName . substring ( 0 , duName . length ( ) - \".ear\" . length ( ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation ---------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . ExceptionDefHelper . narrow ( servantToReference ( new ExceptionDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof ContainedOperations ) defined_in_id = ( ( ContainedOperations ) defined_in ) . id ( ) ; ExceptionDescription ed = new ExceptionDescription ( name , id , defined_in_id , version , type ( ) ) ; Any any = getORB ( ) . create_any ( ) ; ExceptionDescriptionHelper . insert ( any , ed ) ; return new Description ( DefinitionKind . dk_Exception , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( final XMLExtendedStreamReader reader , final List < ModelNode > operations ) throws XMLStreamException { PathAddress address = PathAddress . pathAddress ( SUBSYSTEM_PATH ) ; final ModelNode ejb3SubsystemAddOperation = Util . createAddOperation ( address ) ; operations . add ( ejb3SubsystemAddOperation ) ; // elements final EnumSet < NamingSubsystemXMLElement > encountered = EnumSet . noneOf ( NamingSubsystemXMLElement . class ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != XMLStreamConstants . END_ELEMENT ) { if ( validNamespace == NamingSubsystemNamespace . forUri ( reader . getNamespaceURI ( ) ) ) { final NamingSubsystemXMLElement element = NamingSubsystemXMLElement . forName ( reader . getLocalName ( ) ) ; if ( ! encountered . add ( element ) ) { throw unexpectedElement ( reader ) ; } switch ( element ) { case BINDINGS : { parseBindings ( reader , operations , address ) ; break ; } case REMOTE_NAMING : { parseRemoteNaming ( reader , operations , address ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } else { throw unexpectedElement ( reader ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Parses the optional { @code ObjectFactory environment } . < / p > [CODESPLIT] private void parseObjectFactoryBindingEnvironment ( XMLExtendedStreamReader reader , ModelNode bindingAdd ) throws XMLStreamException { // no attributes expected requireNoAttributes ( reader ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != XMLStreamConstants . END_ELEMENT ) { switch ( NamingSubsystemXMLElement . forName ( reader . getLocalName ( ) ) ) { case ENVIRONMENT_PROPERTY : { final String [ ] array = requireAttributes ( reader , org . jboss . as . controller . parsing . Attribute . NAME . getLocalName ( ) , org . jboss . as . controller . parsing . Attribute . VALUE . getLocalName ( ) ) ; NamingBindingResourceDefinition . ENVIRONMENT . parseAndAddParameterElement ( array [ 0 ] , array [ 1 ] , bindingAdd , reader ) ; requireNoContent ( reader ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Helper methods [CODESPLIT] public static String virtualNodesToSegments ( String virtualNodesValue ) { int segments = SEGMENTS_DEFAULT ; try { segments = virtualNodesToSegments ( Integer . parseInt ( virtualNodesValue ) ) ; } catch ( NumberFormatException nfe ) { // in case of expression } return Integer . toString ( segments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the passed exception is an application exception . If yes then throws back the exception as - is . Else wraps the exception in a { @link javax . ejb . EJBException } and throws the EJBException [CODESPLIT] protected Exception handleException ( final InterceptorContext invocation , Throwable ex ) throws Exception { ApplicationExceptionDetails ae = component . getApplicationException ( ex . getClass ( ) , invocation . getMethod ( ) ) ; // it's an application exception, so just throw it back as-is if ( ae != null ) { throw ( Exception ) ex ; } if ( ex instanceof EJBException ) { throw ( EJBException ) ex ; } else if ( ex instanceof Exception ) { throw new EJBException ( ( Exception ) ex ) ; } else { throw new EJBException ( new RuntimeException ( ex ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds java : comp / ORB [CODESPLIT] private void bindService ( final ServiceTarget serviceTarget , final ServiceName contextServiceName , final Module module ) { final ServiceName orbServiceName = contextServiceName . append ( \"ORB\" ) ; final BinderService orbService = new BinderService ( \"ORB\" ) ; serviceTarget . addService ( orbServiceName , orbService ) . addDependency ( CorbaORBService . SERVICE_NAME , ORB . class , new ManagedReferenceInjector < ORB > ( orbService . getManagedObjectInjector ( ) ) ) . addDependency ( contextServiceName , ServiceBasedNamingStore . class , orbService . getNamingStoreInjector ( ) ) . install ( ) ; final ServiceName handleDelegateServiceName = contextServiceName . append ( \"HandleDelegate\" ) ; final BinderService handleDelegateBindingService = new BinderService ( \"HandleDelegate\" ) ; handleDelegateBindingService . getManagedObjectInjector ( ) . inject ( new ValueManagedReferenceFactory ( new ImmediateValue ( new HandleDelegateImpl ( module . getClassLoader ( ) ) ) ) ) ; serviceTarget . addService ( handleDelegateServiceName , handleDelegateBindingService ) . addDependency ( contextServiceName , ServiceBasedNamingStore . class , handleDelegateBindingService . getNamingStoreInjector ( ) ) . install ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void registerChildren ( ManagementResourceRegistration resourceRegistration ) { super . registerChildren ( resourceRegistration ) ; // /deployment=DU/**/subsystem=ejb3/*=EJBName/service=timer-service final AbstractEJBComponentRuntimeHandler < ? > handler = componentType . getRuntimeHandler ( ) ; resourceRegistration . registerSubModel ( new TimerServiceResourceDefinition ( handler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an analysis . If the calling thread is currently doing an analysis of this class an unfinished analysis is returned . [CODESPLIT] ContainerAnalysis getAnalysis ( final Class cls ) throws RMIIIOPViolationException { ContainerAnalysis ret = null ; boolean created = false ; try { synchronized ( this ) { ret = lookupDone ( cls ) ; if ( ret != null ) { return ret ; } // is it work-in-progress? final ContainerAnalysis inProgress = workInProgress . get ( new InProgressKey ( cls , Thread . currentThread ( ) ) ) ; if ( inProgress != null ) { return inProgress ; // return unfinished // Do not wait for the other thread: We may deadlock // Double work is better that deadlock... } ret = createWorkInProgress ( cls ) ; } created = true ; // Do the work doTheWork ( cls , ret ) ; } finally { // We did it synchronized ( this ) { if ( created ) { workInProgress . remove ( new InProgressKey ( cls , Thread . currentThread ( ) ) ) ; workDone . put ( cls , new SoftReference < ContainerAnalysis > ( ret ) ) ; ClassLoader classLoader = cls . getClassLoader ( ) ; if ( classLoader != null ) { Set < Class < ? > > classes = classesByLoader . get ( classLoader ) ; if ( classes == null ) { classesByLoader . put ( classLoader , classes = new HashSet < Class < ? > > ( ) ) ; } classes . add ( cls ) ; } } notifyAll ( ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup an analysis in the fully done map . [CODESPLIT] private ContainerAnalysis lookupDone ( Class cls ) { SoftReference ref = ( SoftReference ) workDone . get ( cls ) ; if ( ref == null ) return null ; ContainerAnalysis ret = ( ContainerAnalysis ) ref . get ( ) ; if ( ret == null ) workDone . remove ( cls ) ; // clear map entry if soft ref. was cleared. return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new work - in - progress . [CODESPLIT] private ContainerAnalysis createWorkInProgress ( final Class cls ) { final ContainerAnalysis analysis ; try { analysis = ( ContainerAnalysis ) constructor . newInstance ( cls ) ; } catch ( InstantiationException ex ) { throw new RuntimeException ( ex . toString ( ) ) ; } catch ( IllegalAccessException ex ) { throw new RuntimeException ( ex . toString ( ) ) ; } catch ( InvocationTargetException ex ) { throw new RuntimeException ( ex . toString ( ) ) ; } workInProgress . put ( new InProgressKey ( cls , Thread . currentThread ( ) ) , analysis ) ; return analysis ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the fully qualified IDL module name that this analysis should be placed in . [CODESPLIT] public String getIDLModuleName ( ) { if ( idlModuleName == null ) { String pkgName = cls . getPackage ( ) . getName ( ) ; StringBuffer b = new StringBuffer ( ) ; while ( ! \"\" . equals ( pkgName ) ) { int idx = pkgName . indexOf ( ' ' ) ; String n = ( idx == - 1 ) ? pkgName : pkgName . substring ( 0 , idx ) ; b . append ( \"::\" ) . append ( Util . javaToIDLName ( n ) ) ; pkgName = ( idx == - 1 ) ? \"\" : pkgName . substring ( idx + 1 ) ; } idlModuleName = b . toString ( ) ; } return idlModuleName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an integer to a 16 - digit hex string . [CODESPLIT] protected String toHexString ( int i ) { String s = Integer . toHexString ( i ) . toUpperCase ( Locale . ENGLISH ) ; if ( s . length ( ) < 8 ) return \"00000000\" . substring ( 0 , 8 - s . length ( ) ) + s ; else return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a long to a 16 - digit hex string . [CODESPLIT] protected String toHexString ( long l ) { String s = Long . toHexString ( l ) . toUpperCase ( Locale . ENGLISH ) ; if ( s . length ( ) < 16 ) return \"0000000000000000\" . substring ( 0 , 16 - s . length ( ) ) + s ; else return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a method is an accessor . [CODESPLIT] protected boolean isAccessor ( Method m ) { Class returnType = m . getReturnType ( ) ; // JBAS-4473, look for get<name>() String name = m . getName ( ) ; if ( ! ( name . startsWith ( \"get\" ) && name . length ( ) > \"get\" . length ( ) ) ) if ( ! ( name . startsWith ( \"is\" ) && name . length ( ) > \"is\" . length ( ) ) || ! ( returnType == Boolean . TYPE ) ) return false ; if ( returnType == Void . TYPE ) return false ; if ( m . getParameterTypes ( ) . length != 0 ) return false ; return hasNonAppExceptions ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a method is a mutator . [CODESPLIT] protected boolean isMutator ( Method m ) { // JBAS-4473, look for set<name>() String name = m . getName ( ) ; if ( ! ( name . startsWith ( \"set\" ) && name . length ( ) > \"set\" . length ( ) ) ) return false ; if ( m . getReturnType ( ) != Void . TYPE ) return false ; if ( m . getParameterTypes ( ) . length != 1 ) return false ; return hasNonAppExceptions ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a method throws anything checked other than java . rmi . RemoteException and its subclasses . [CODESPLIT] protected boolean hasNonAppExceptions ( Method m ) { Class [ ] ex = m . getExceptionTypes ( ) ; for ( int i = 0 ; i < ex . length ; ++ i ) if ( ! java . rmi . RemoteException . class . isAssignableFrom ( ex [ i ] ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyze the fields of the class . This will fill in the <code > fields< / code > and <code > f_flags< / code > arrays . [CODESPLIT] protected void analyzeFields ( ) { //fields = cls.getFields(); fields = cls . getDeclaredFields ( ) ; f_flags = new byte [ fields . length ] ; for ( int i = 0 ; i < fields . length ; ++ i ) { int mods = fields [ i ] . getModifiers ( ) ; if ( Modifier . isFinal ( mods ) && Modifier . isStatic ( mods ) && Modifier . isPublic ( mods ) ) f_flags [ i ] |= F_CONSTANT ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyze the interfaces of the class . This will fill in the <code > interfaces< / code > array . [CODESPLIT] protected void analyzeInterfaces ( ) throws RMIIIOPViolationException { Class [ ] intfs = cls . getInterfaces ( ) ; ArrayList a = new ArrayList ( ) ; ArrayList b = new ArrayList ( ) ; for ( int i = 0 ; i < intfs . length ; ++ i ) { // Ignore java.rmi.Remote if ( intfs [ i ] == java . rmi . Remote . class ) continue ; // Ignore java.io.Serializable if ( intfs [ i ] == java . io . Serializable . class ) continue ; // Ignore java.io.Externalizable if ( intfs [ i ] == java . io . Externalizable . class ) continue ; if ( ! RmiIdlUtil . isAbstractValueType ( intfs [ i ] ) ) { a . add ( InterfaceAnalysis . getInterfaceAnalysis ( intfs [ i ] ) ) ; } else { b . add ( ValueAnalysis . getValueAnalysis ( intfs [ i ] ) ) ; } } interfaces = new InterfaceAnalysis [ a . size ( ) ] ; interfaces = ( InterfaceAnalysis [ ] ) a . toArray ( interfaces ) ; abstractBaseValuetypes = new ValueAnalysis [ b . size ( ) ] ; abstractBaseValuetypes = ( ValueAnalysis [ ] ) b . toArray ( abstractBaseValuetypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyze the methods of the class . This will fill in the <code > methods< / code > and <code > m_flags< / code > arrays . [CODESPLIT] protected void analyzeMethods ( ) { // The dynamic stub and skeleton strategy generation mechanism // requires the inclusion of inherited methods in the analysis of // remote interfaces. To speed things up, inherited methods are // not considered in the analysis of a class or non-remote interface. if ( cls . isInterface ( ) && java . rmi . Remote . class . isAssignableFrom ( cls ) ) methods = cls . getMethods ( ) ; else methods = cls . getDeclaredMethods ( ) ; m_flags = new byte [ methods . length ] ; mutators = new int [ methods . length ] ; // Find read-write properties for ( int i = 0 ; i < methods . length ; ++ i ) mutators [ i ] = - 1 ; // no mutator here for ( int i = 0 ; i < methods . length ; ++ i ) { if ( isAccessor ( methods [ i ] ) && ( m_flags [ i ] & M_READ ) == 0 ) { String attrName = attributeReadName ( methods [ i ] . getName ( ) ) ; Class iReturn = methods [ i ] . getReturnType ( ) ; for ( int j = i + 1 ; j < methods . length ; ++ j ) { if ( isMutator ( methods [ j ] ) && ( m_flags [ j ] & M_WRITE ) == 0 && attrName . equals ( attributeWriteName ( methods [ j ] . getName ( ) ) ) ) { Class [ ] jParams = methods [ j ] . getParameterTypes ( ) ; if ( jParams . length == 1 && jParams [ 0 ] == iReturn ) { m_flags [ i ] |= M_READ ; m_flags [ j ] |= M_WRITE ; mutators [ i ] = j ; break ; } } } } else if ( isMutator ( methods [ i ] ) && ( m_flags [ i ] & M_WRITE ) == 0 ) { String attrName = attributeWriteName ( methods [ i ] . getName ( ) ) ; Class [ ] iParams = methods [ i ] . getParameterTypes ( ) ; for ( int j = i + 1 ; j < methods . length ; ++ j ) { if ( isAccessor ( methods [ j ] ) && ( m_flags [ j ] & M_READ ) == 0 && attrName . equals ( attributeReadName ( methods [ j ] . getName ( ) ) ) ) { Class jReturn = methods [ j ] . getReturnType ( ) ; if ( iParams . length == 1 && iParams [ 0 ] == jReturn ) { m_flags [ i ] |= M_WRITE ; m_flags [ j ] |= M_READ ; mutators [ j ] = i ; break ; } } } } } // Find read-only properties for ( int i = 0 ; i < methods . length ; ++ i ) if ( ( m_flags [ i ] & ( M_READ | M_WRITE ) ) == 0 && isAccessor ( methods [ i ] ) ) m_flags [ i ] |= M_READONLY ; // Check for overloaded and inherited methods for ( int i = 0 ; i < methods . length ; ++ i ) { if ( ( m_flags [ i ] & ( M_READ | M_WRITE | M_READONLY ) ) == 0 ) { String iName = methods [ i ] . getName ( ) ; for ( int j = i + 1 ; j < methods . length ; ++ j ) { if ( iName . equals ( methods [ j ] . getName ( ) ) ) { m_flags [ i ] |= M_OVERLOADED ; m_flags [ j ] |= M_OVERLOADED ; } } } if ( methods [ i ] . getDeclaringClass ( ) != cls ) m_flags [ i ] |= M_INHERITED ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an attribute read method name in Java format to an attribute name in Java format . [CODESPLIT] protected String attributeReadName ( String name ) { if ( name . startsWith ( \"get\" ) ) name = name . substring ( 3 ) ; else if ( name . startsWith ( \"is\" ) ) name = name . substring ( 2 ) ; else throw IIOPLogger . ROOT_LOGGER . notAnAccessor ( name ) ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an attribute write method name in Java format to an attribute name in Java format . [CODESPLIT] protected String attributeWriteName ( String name ) { if ( name . startsWith ( \"set\" ) ) name = name . substring ( 3 ) ; else throw IIOPLogger . ROOT_LOGGER . notAnAccessor ( name ) ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyse constants . This will fill in the <code > constants< / code > array . [CODESPLIT] protected void analyzeConstants ( ) throws RMIIIOPViolationException { ArrayList a = new ArrayList ( ) ; for ( int i = 0 ; i < fields . length ; ++ i ) { if ( ( f_flags [ i ] & F_CONSTANT ) == 0 ) continue ; Class type = fields [ i ] . getType ( ) ; // Only map primitives and java.lang.String if ( ! type . isPrimitive ( ) && type != java . lang . String . class ) { // It is an RMI/IIOP violation for interfaces. if ( cls . isInterface ( ) ) throw IIOPLogger . ROOT_LOGGER . badRMIIIOPConstantType ( fields [ i ] . getName ( ) , cls . getName ( ) , \"1.2.3\" ) ; continue ; } String name = fields [ i ] . getName ( ) ; Object value ; try { value = fields [ i ] . get ( null ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex . toString ( ) ) ; } a . add ( new ConstantAnalysis ( name , type , value ) ) ; } constants = new ConstantAnalysis [ a . size ( ) ] ; constants = ( ConstantAnalysis [ ] ) a . toArray ( constants ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyse attributes . This will fill in the <code > attributes< / code > array . [CODESPLIT] protected void analyzeAttributes ( ) throws RMIIIOPViolationException { ArrayList a = new ArrayList ( ) ; for ( int i = 0 ; i < methods . length ; ++ i ) { //if ((m_flags[i]&M_INHERITED) != 0) //  continue; if ( ( m_flags [ i ] & ( M_READ | M_READONLY ) ) != 0 ) { // Read method of an attribute. String name = attributeReadName ( methods [ i ] . getName ( ) ) ; if ( ( m_flags [ i ] & M_READONLY ) != 0 ) a . add ( new AttributeAnalysis ( name , methods [ i ] ) ) ; else a . add ( new AttributeAnalysis ( name , methods [ i ] , methods [ mutators [ i ] ] ) ) ; } } attributes = new AttributeAnalysis [ a . size ( ) ] ; attributes = ( AttributeAnalysis [ ] ) a . toArray ( attributes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fixup overloaded operation names . As specified in section 1 . 3 . 2 . 6 . [CODESPLIT] protected void fixupOverloadedOperationNames ( ) throws RMIIIOPViolationException { for ( int i = 0 ; i < methods . length ; ++ i ) { if ( ( m_flags [ i ] & M_OVERLOADED ) == 0 ) continue ; // Find the operation OperationAnalysis oa = null ; String javaName = methods [ i ] . getName ( ) ; for ( int opIdx = 0 ; oa == null && opIdx < operations . length ; ++ opIdx ) if ( operations [ opIdx ] . getMethod ( ) . equals ( methods [ i ] ) ) oa = operations [ opIdx ] ; if ( oa == null ) continue ; // This method is not mapped. // Calculate new IDL name ParameterAnalysis [ ] params = oa . getParameters ( ) ; StringBuffer b = new StringBuffer ( oa . getIDLName ( ) ) ; if ( params . length == 0 ) b . append ( \"__\" ) ; for ( int j = 0 ; j < params . length ; ++ j ) { String s = params [ j ] . getTypeIDLName ( ) ; if ( s . startsWith ( \"::\" ) ) s = s . substring ( 2 ) ; if ( s . startsWith ( \"_\" ) ) { // remove leading underscore in IDL escaped identifier s = s . substring ( 1 ) ; } b . append ( ' ' ) ; while ( ! \"\" . equals ( s ) ) { int idx = s . indexOf ( \"::\" ) ; b . append ( ' ' ) ; if ( idx == - 1 ) { b . append ( s ) ; s = \"\" ; } else { b . append ( s . substring ( 0 , idx ) ) ; if ( s . length ( ) > idx + 2 && s . charAt ( idx + 2 ) == ' ' ) { // remove leading underscore in IDL escaped identifier s = s . substring ( idx + 3 ) ; } else { s = s . substring ( idx + 2 ) ; } } } } // Set new IDL name oa . setIDLName ( b . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fixup names differing only in case . As specified in section 1 . 3 . 2 . 7 . [CODESPLIT] protected void fixupCaseNames ( ) throws RMIIIOPViolationException { ArrayList entries = getContainedEntries ( ) ; boolean [ ] clash = new boolean [ entries . size ( ) ] ; String [ ] upperNames = new String [ entries . size ( ) ] ; for ( int i = 0 ; i < entries . size ( ) ; ++ i ) { AbstractAnalysis aa = ( AbstractAnalysis ) entries . get ( i ) ; clash [ i ] = false ; upperNames [ i ] = aa . getIDLName ( ) . toUpperCase ( Locale . ENGLISH ) ; for ( int j = 0 ; j < i ; ++ j ) { if ( upperNames [ i ] . equals ( upperNames [ j ] ) ) { clash [ i ] = true ; clash [ j ] = true ; } } } for ( int i = 0 ; i < entries . size ( ) ; ++ i ) { if ( ! clash [ i ] ) continue ; AbstractAnalysis aa = ( AbstractAnalysis ) entries . get ( i ) ; boolean noUpper = true ; String name = aa . getIDLName ( ) ; StringBuffer b = new StringBuffer ( name ) ; b . append ( ' ' ) ; for ( int j = 0 ; j < name . length ( ) ; ++ j ) { if ( ! Character . isUpperCase ( name . charAt ( j ) ) ) continue ; if ( noUpper ) noUpper = false ; else b . append ( ' ' ) ; b . append ( j ) ; } aa . setIDLName ( b . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the class hash code as specified in The Common Object Request Broker : Architecture and Specification ( 01 - 02 - 33 ) section 10 . 6 . 2 . [CODESPLIT] protected void calculateClassHashCode ( ) { // The simple cases if ( cls . isInterface ( ) ) classHashCode = 0 ; else if ( ! Serializable . class . isAssignableFrom ( cls ) ) classHashCode = 0 ; else if ( Externalizable . class . isAssignableFrom ( cls ) ) classHashCode = 1 ; else // Go ask Util class for the hash code classHashCode = Util . getClassHashCode ( cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape non - ISO characters for an IR name . [CODESPLIT] protected String escapeIRName ( String name ) { StringBuffer b = new StringBuffer ( ) ; for ( int i = 0 ; i < name . length ( ) ; ++ i ) { char c = name . charAt ( i ) ; if ( c < 256 ) b . append ( c ) ; else b . append ( \"\\\\U\" ) . append ( toHexString ( ( int ) c ) ) ; } return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the IR global ID of the given class or interface . This is described in section 1 . 3 . 5 . 7 . The returned string is in the RMI hashed format like RMI : java . util . Hashtable : C03324C0EA357270 : 13BB0F25214AE4B8 . [CODESPLIT] protected void calculateRepositoryId ( ) { if ( cls . isArray ( ) || cls . isPrimitive ( ) ) throw IIOPLogger . ROOT_LOGGER . notAnClassOrInterface ( cls . getName ( ) ) ; if ( cls . isInterface ( ) && org . omg . CORBA . Object . class . isAssignableFrom ( cls ) && org . omg . CORBA . portable . IDLEntity . class . isAssignableFrom ( cls ) ) { StringBuffer b = new StringBuffer ( \"IDL:\" ) ; b . append ( cls . getPackage ( ) . getName ( ) . replace ( ' ' , ' ' ) ) ; b . append ( ' ' ) ; String base = cls . getName ( ) ; base = base . substring ( base . lastIndexOf ( ' ' ) + 1 ) ; b . append ( base ) . append ( \":1.0\" ) ; repositoryId = b . toString ( ) ; } else { StringBuffer b = new StringBuffer ( \"RMI:\" ) ; b . append ( escapeIRName ( cls . getName ( ) ) ) ; memberPrefix = b . toString ( ) + \".\" ; String hashStr = toHexString ( classHashCode ) ; b . append ( ' ' ) . append ( hashStr ) ; ObjectStreamClass osClass = ObjectStreamClass . lookup ( cls ) ; if ( osClass != null ) { long serialVersionUID = osClass . getSerialVersionUID ( ) ; String SVUID = toHexString ( serialVersionUID ) ; if ( classHashCode != serialVersionUID ) b . append ( ' ' ) . append ( SVUID ) ; memberPostfix = \":\" + hashStr + \":\" + SVUID ; } else memberPostfix = \":\" + hashStr ; repositoryId = b . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( XMLExtendedStreamReader reader , List < ModelNode > list ) throws XMLStreamException { // no attributes if ( reader . getAttributeCount ( ) > 0 ) { throw ParseUtils . unexpectedAttribute ( reader , 0 ) ; } final ModelNode subsystem = Util . getEmptyOperation ( ADD , PathAddress . pathAddress ( XTSExtension . SUBSYSTEM_PATH ) . toModelNode ( ) ) ; list . add ( subsystem ) ; final EnumSet < Element > encountered = EnumSet . noneOf ( Element . class ) ; final List < Element > expected = getExpectedElements ( reader ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { final Element element = Element . forName ( reader . getLocalName ( ) ) ; if ( ! expected . contains ( element ) || ! encountered . add ( element ) ) { throw ParseUtils . unexpectedElement ( reader ) ; } switch ( element ) { case HOST : { parseHostElement ( reader , subsystem ) ; break ; } case XTS_ENVIRONMENT : { parseXTSEnvironmentElement ( reader , subsystem ) ; break ; } case DEFAULT_CONTEXT_PROPAGATION : { parseDefaultContextPropagationElement ( reader , subsystem ) ; break ; } case ASYNC_REGISTRATION : { parseAsyncRegistrationElement ( reader , subsystem ) ; break ; } default : { throw ParseUtils . unexpectedElement ( reader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeContent ( XMLExtendedStreamWriter writer , SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( Namespace . CURRENT . getUriString ( ) , false ) ; ModelNode node = context . getModelNode ( ) ; if ( node . hasDefined ( HOST_NAME . getName ( ) ) ) { writer . writeStartElement ( Element . HOST . getLocalName ( ) ) ; HOST_NAME . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } if ( node . hasDefined ( ENVIRONMENT_URL . getName ( ) ) ) { writer . writeStartElement ( Element . XTS_ENVIRONMENT . getLocalName ( ) ) ; ENVIRONMENT_URL . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } if ( node . hasDefined ( DEFAULT_CONTEXT_PROPAGATION . getName ( ) ) ) { writer . writeStartElement ( Element . DEFAULT_CONTEXT_PROPAGATION . getLocalName ( ) ) ; DEFAULT_CONTEXT_PROPAGATION . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } if ( node . hasDefined ( ASYNC_REGISTRATION . getName ( ) ) ) { writer . writeStartElement ( Element . ASYNC_REGISTRATION . getLocalName ( ) ) ; ASYNC_REGISTRATION . marshallAsAttribute ( node , writer ) ; writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle the xts - environment element [CODESPLIT] private void parseXTSEnvironmentElement ( XMLExtendedStreamReader reader , ModelNode subsystem ) throws XMLStreamException { processAttributes ( reader , ( index , attribute ) -> { final String value = reader . getAttributeValue ( index ) ; switch ( attribute ) { case URL : ENVIRONMENT_URL . parseAndSetParameter ( value , subsystem , reader ) ; break ; default : throw ParseUtils . unexpectedAttribute ( reader , index ) ; } } ) ; // Handle elements ParseUtils . requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle the enable - client - handler element . [CODESPLIT] private void parseDefaultContextPropagationElement ( XMLExtendedStreamReader reader , ModelNode subsystem ) throws XMLStreamException { processAttributes ( reader , ( index , attribute ) -> { final String value = reader . getAttributeValue ( index ) ; switch ( attribute ) { case ENABLED : if ( value == null || ( ! value . toLowerCase ( ) . equals ( \"true\" ) && ! value . toLowerCase ( ) . equals ( \"false\" ) ) ) { throw ParseUtils . invalidAttributeValue ( reader , index ) ; } DEFAULT_CONTEXT_PROPAGATION . parseAndSetParameter ( value , subsystem , reader ) ; break ; default : throw ParseUtils . unexpectedAttribute ( reader , index ) ; } } ) ; // Handle elements ParseUtils . requireNoContent ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterating over all attributes got from the reader parameter . [CODESPLIT] private void processAttributes ( final XMLExtendedStreamReader reader , AttributeProcessor < Integer , Attribute > attributeProcessorCallback ) throws XMLStreamException { final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { ParseUtils . requireNoNamespaceAttribute ( reader , i ) ; // final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; attributeProcessorCallback . process ( i , attribute ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the specified JPA persistence provider module [CODESPLIT] public static List < PersistenceProvider > loadProviderModuleByName ( String moduleName ) throws ModuleLoadException { final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; Module module = moduleLoader . loadModule ( ModuleIdentifier . fromString ( moduleName ) ) ; final ServiceLoader < PersistenceProvider > serviceLoader = module . loadService ( PersistenceProvider . class ) ; List < PersistenceProvider > result = new ArrayList <> ( ) ; if ( serviceLoader != null ) { for ( PersistenceProvider provider1 : serviceLoader ) { // persistence provider jar may contain multiple provider service implementations // save each provider PersistenceProviderResolverImpl . getInstance ( ) . addPersistenceProvider ( provider1 ) ; result . add ( provider1 ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main method . [CODESPLIT] public static void main ( String [ ] args ) { if ( java . util . logging . LogManager . getLogManager ( ) . getClass ( ) . getName ( ) . equals ( \"org.jboss.logmanager.LogManager\" ) ) { // Make sure our original stdio is properly captured. try { Class . forName ( org . jboss . logmanager . handlers . ConsoleHandler . class . getName ( ) , true , org . jboss . logmanager . handlers . ConsoleHandler . class . getClassLoader ( ) ) ; } catch ( Throwable ignored ) { } // Install JBoss Stdio to avoid any nasty crosstalk, after command line arguments are processed. StdioContext . install ( ) ; final StdioContext context = StdioContext . create ( new NullInputStream ( ) , new LoggingOutputStream ( org . jboss . logmanager . Logger . getLogger ( \"stdout\" ) , org . jboss . logmanager . Level . INFO ) , new LoggingOutputStream ( org . jboss . logmanager . Logger . getLogger ( \"stderr\" ) , org . jboss . logmanager . Level . ERROR ) ) ; StdioContext . setStdioContextSelector ( new SimpleStdioContextSelector ( context ) ) ; } try { Module . registerURLStreamHandlerFactoryModule ( Module . getBootModuleLoader ( ) . loadModule ( ModuleIdentifier . create ( \"org.jboss.vfs\" ) ) ) ; final ParsedOptions options = determineEnvironment ( args , new Properties ( WildFlySecurityManager . getSystemPropertiesPrivileged ( ) ) , WildFlySecurityManager . getSystemEnvironmentPrivileged ( ) , ServerEnvironment . LaunchType . APPCLIENT ) ; if ( options == null ) { //this happens if --version was specified return ; } ServerEnvironment serverEnvironment = options . environment ; final List < String > clientArgs = options . clientArguments ; if ( clientArgs . isEmpty ( ) ) { STDERR . println ( AppClientLogger . ROOT_LOGGER . appClientNotSpecified ( ) ) ; usage ( ) ; abort ( null ) ; } else { final QName rootElement = new QName ( Namespace . CURRENT . getUriString ( ) , \"server\" ) ; final String file = clientArgs . get ( 0 ) ; final List < String > params = clientArgs . subList ( 1 , clientArgs . size ( ) ) ; final String deploymentName ; final String earPath ; int pos = file . lastIndexOf ( \"#\" ) ; if ( pos == - 1 ) { earPath = file ; deploymentName = null ; } else { deploymentName = file . substring ( pos + 1 ) ; earPath = file . substring ( 0 , pos ) ; } File realFile = new File ( earPath ) ; if ( ! realFile . exists ( ) ) { throw AppClientLogger . ROOT_LOGGER . cannotFindAppClientFile ( realFile . getAbsoluteFile ( ) ) ; } final Bootstrap bootstrap = Bootstrap . Factory . newInstance ( ) ; final Bootstrap . Configuration configuration = new Bootstrap . Configuration ( serverEnvironment ) ; configuration . setModuleLoader ( Module . getBootModuleLoader ( ) ) ; final ExtensionRegistry extensionRegistry = configuration . getExtensionRegistry ( ) ; final AppClientXml parser = new AppClientXml ( Module . getBootModuleLoader ( ) , extensionRegistry ) ; final Bootstrap . ConfigurationPersisterFactory configurationPersisterFactory = new Bootstrap . ConfigurationPersisterFactory ( ) { @ Override public ExtensibleConfigurationPersister createConfigurationPersister ( ServerEnvironment serverEnvironment , ExecutorService executorService ) { ApplicationClientConfigurationPersister persister = new ApplicationClientConfigurationPersister ( earPath , deploymentName , options . hostUrl , options . propertiesFile , params , serverEnvironment . getServerConfigurationFile ( ) . getBootFile ( ) , rootElement , parser ) ; for ( Namespace namespace : Namespace . domainValues ( ) ) { if ( ! namespace . equals ( Namespace . CURRENT ) ) { persister . registerAdditionalRootElement ( new QName ( namespace . getUriString ( ) , \"server\" ) , parser ) ; } } extensionRegistry . setWriterRegistry ( persister ) ; return persister ; } } ; configuration . setConfigurationPersisterFactory ( configurationPersisterFactory ) ; bootstrap . bootstrap ( configuration , Collections . < ServiceActivator > emptyList ( ) ) . get ( ) ; } } catch ( Throwable t ) { abort ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation --------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . AttributeDefHelper . narrow ( servantToReference ( new AttributeDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof ContainedOperations ) defined_in_id = ( ( ContainedOperations ) defined_in ) . id ( ) ; AttributeDescription d = new AttributeDescription ( name , id , defined_in_id , version , typeCode , mode ) ; Any any = getORB ( ) . create_any ( ) ; AttributeDescriptionHelper . insert ( any , d ) ; return new Description ( DefinitionKind . dk_Attribute , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ADD operation that can check that there is no other sibling when the resource is added . [CODESPLIT] static AbstractAddStepHandler createAddOperation ( final String childType , final boolean allowSibling , Collection < ? extends AttributeDefinition > attributes ) { return new ActiveMQReloadRequiredHandlers . AddStepHandler ( attributes ) { @ Override public void execute ( OperationContext context , ModelNode operation ) throws OperationFailedException { super . execute ( context , operation ) ; if ( ! allowSibling ) { context . addStep ( checkNoOtherSibling ( childType ) , MODEL ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start [CODESPLIT] @ Override public void start ( StartContext context ) throws StartException { try { Connector cmd = mdr . getValue ( ) . getResourceAdapter ( deployment ) ; File root = mdr . getValue ( ) . getRoot ( deployment ) ; Activation localRaXml = getRaxml ( ) ; cmd = ( new Merger ( ) ) . mergeConnectorWithCommonIronJacamar ( localRaXml , cmd ) ; String id = ( ( ModifiableResourceAdapter ) raxml ) . getId ( ) ; final ServiceName raServiceName ; if ( id == null || id . trim ( ) . isEmpty ( ) ) { raServiceName = ConnectorServices . getResourceAdapterServiceName ( raName ) ; this . connectorServicesRegistrationName = raName ; } else { raServiceName = ConnectorServices . getResourceAdapterServiceName ( id ) ; this . connectorServicesRegistrationName = id ; } final WildFlyRaXmlDeployer raDeployer = new WildFlyRaXmlDeployer ( context . getChildTarget ( ) , connectorXmlDescriptor . getUrl ( ) , raName , root , module . getClassLoader ( ) , cmd , localRaXml , deploymentServiceName ) ; raDeployer . setConfiguration ( config . getValue ( ) ) ; WritableServiceBasedNamingStore . pushOwner ( duServiceName ) ; ClassLoader old = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( module . getClassLoader ( ) ) ; raxmlDeployment = raDeployer . doDeploy ( ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( old ) ; WritableServiceBasedNamingStore . popOwner ( ) ; } value = new ResourceAdapterDeployment ( raxmlDeployment , raName , raServiceName ) ; managementRepository . getValue ( ) . getConnectors ( ) . add ( value . getDeployment ( ) . getConnector ( ) ) ; registry . getValue ( ) . registerResourceAdapterDeployment ( value ) ; final ServiceBuilder raServiceSB = context . getChildTarget ( ) . addService ( raServiceName , new ResourceAdapterService ( raServiceName , value . getDeployment ( ) . getResourceAdapter ( ) ) ) ; raServiceSB . requires ( deploymentServiceName ) ; raServiceSB . setInitialMode ( ServiceController . Mode . ACTIVE ) . install ( ) ; } catch ( Throwable t ) { cleanupStartAsync ( context , raName , deploymentServiceName , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds Java EE module as a dependency to any deployment unit which is an EJB deployment [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { // get hold of the deployment unit DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; //always add EE API moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , EJB_API , false , false , true , false ) ) ; // previously exported by EJB_API prior to WFLY-5922 TODO WFLY-5967 look into moving this to WS subsystem moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , JAX_RPC_API , false , false , true , false ) ) ; //we always give them the EJB client moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , EJB_CLIENT , false , false , true , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , EJB_NAMING_CLIENT , false , false , true , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , EJB_IIOP_CLIENT , false , false , false , false ) ) ; //we always have to add this, as even non-ejb deployments may still lookup IIOP ejb's moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , EJB_SUBSYSTEM , false , false , true , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , HTTP_EJB , false , false , true , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , HTTP_NAMING , false , false , true , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , HTTP_TRANSACTION , false , false , true , false ) ) ; if ( IIOPDeploymentMarker . isIIOPDeployment ( deploymentUnit ) ) { //needed for dynamic IIOP stubs moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , IIOP_OPENJDK , false , false , false , false ) ) ; } // fetch the EjbJarMetaData //TODO: remove the app client bit after the next EJB release if ( ! isEjbDeployment ( deploymentUnit ) && ! DeploymentTypeMarker . isType ( DeploymentType . APPLICATION_CLIENT , deploymentUnit ) ) { // nothing to do return ; } // FIXME: still not the best way to do it //this must be the first dep listed in the module if ( Boolean . getBoolean ( \"org.jboss.as.ejb3.EMBEDDED\" ) ) moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , ModuleIdentifier . CLASSPATH , false , false , false , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object getContext ( String key , Object data ) throws PolicyContextException { if ( ! key . equalsIgnoreCase ( SecurityConstants . WEB_REQUEST_KEY ) ) return null ; return SecurityContextAssociationHandler . getActiveRequest ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeContent ( XMLExtendedStreamWriter writer , SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( Namespace . CURRENT . getUriString ( ) , false ) ; ModelNode node = context . getModelNode ( ) ; WebDefinition . DEFAULT_VIRTUAL_SERVER . marshallAsAttribute ( node , true , writer ) ; WebDefinition . INSTANCE_ID . marshallAsAttribute ( node , false , writer ) ; WebDefinition . NATIVE . marshallAsAttribute ( node , true , writer ) ; WebDefinition . DEFAULT_SESSION_TIMEOUT . marshallAsAttribute ( node , false , writer ) ; if ( node . hasDefined ( CONFIGURATION ) ) { writeContainerConfig ( writer , node . get ( CONFIGURATION ) ) ; } if ( node . hasDefined ( CONNECTOR ) ) { for ( final Property connector : node . get ( CONNECTOR ) . asPropertyList ( ) ) { final ModelNode config = connector . getValue ( ) ; writer . writeStartElement ( Element . CONNECTOR . getLocalName ( ) ) ; writer . writeAttribute ( NAME , connector . getName ( ) ) ; List < AttributeDefinition > connectorAttributes = new ArrayList <> ( Arrays . asList ( WebConnectorDefinition . CONNECTOR_ATTRIBUTES ) ) ; if ( config . hasDefined ( Constants . PROXY_BINDING ) ) { connectorAttributes . remove ( WebConnectorDefinition . PROXY_PORT ) ; connectorAttributes . remove ( WebConnectorDefinition . PROXY_NAME ) ; } else { connectorAttributes . remove ( WebConnectorDefinition . PROXY_BINDING ) ; } if ( config . hasDefined ( Constants . REDIRECT_BINDING ) ) { connectorAttributes . remove ( WebConnectorDefinition . REDIRECT_PORT ) ; } else { connectorAttributes . remove ( WebConnectorDefinition . REDIRECT_BINDING ) ; } for ( AttributeDefinition attr : connectorAttributes ) { if ( attr instanceof SimpleAttributeDefinition ) { ( ( SimpleAttributeDefinition ) attr ) . marshallAsAttribute ( config , true , writer ) ; } } if ( config . get ( SSL_PATH . getKey ( ) , SSL_PATH . getValue ( ) ) . isDefined ( ) ) { ModelNode sslConfig = config . get ( SSL_PATH . getKey ( ) , SSL_PATH . getValue ( ) ) ; writer . writeStartElement ( Element . SSL . getLocalName ( ) ) ; WebSSLDefinition . NAME . marshallAsAttribute ( sslConfig , writer ) ; for ( SimpleAttributeDefinition attr : WebSSLDefinition . SSL_ATTRIBUTES ) { attr . marshallAsAttribute ( sslConfig , false , writer ) ; } writer . writeEndElement ( ) ; } if ( config . hasDefined ( VIRTUAL_SERVER ) ) { for ( final ModelNode virtualServer : config . get ( VIRTUAL_SERVER ) . asList ( ) ) { writer . writeEmptyElement ( VIRTUAL_SERVER ) ; writer . writeAttribute ( NAME , virtualServer . asString ( ) ) ; } } writer . writeEndElement ( ) ; } } if ( node . hasDefined ( VIRTUAL_SERVER ) ) { for ( final Property host : node . get ( VIRTUAL_SERVER ) . asPropertyList ( ) ) { final ModelNode config = host . getValue ( ) ; writer . writeStartElement ( Element . VIRTUAL_SERVER . getLocalName ( ) ) ; writer . writeAttribute ( NAME , host . getName ( ) ) ; WebVirtualHostDefinition . ENABLE_WELCOME_ROOT . marshallAsAttribute ( config , true , writer ) ; WebVirtualHostDefinition . DEFAULT_WEB_MODULE . marshallAsAttribute ( config , true , writer ) ; if ( config . hasDefined ( ALIAS ) ) { for ( final ModelNode alias : config . get ( ALIAS ) . asList ( ) ) { writer . writeEmptyElement ( ALIAS ) ; writer . writeAttribute ( NAME , alias . asString ( ) ) ; } } if ( config . get ( ACCESS_LOG_PATH . getKey ( ) , ACCESS_LOG_PATH . getValue ( ) ) . isDefined ( ) ) { ModelNode accessLog = config . get ( ACCESS_LOG_PATH . getKey ( ) , ACCESS_LOG_PATH . getValue ( ) ) ; writer . writeStartElement ( Element . ACCESS_LOG . getLocalName ( ) ) ; for ( SimpleAttributeDefinition attr : WebAccessLogDefinition . ACCESS_LOG_ATTRIBUTES ) { attr . marshallAsAttribute ( accessLog , false , writer ) ; } if ( accessLog . get ( DIRECTORY_PATH . getKey ( ) , DIRECTORY_PATH . getValue ( ) ) . isDefined ( ) ) { ModelNode directory = accessLog . get ( DIRECTORY_PATH . getKey ( ) , DIRECTORY_PATH . getValue ( ) ) ; String name = Element . DIRECTORY . getLocalName ( ) ; boolean startwritten = false ; startwritten = writeAttribute ( writer , WebAccessLogDirectoryDefinition . PATH , directory , startwritten , name ) ; startwritten = writeAttribute ( writer , WebAccessLogDirectoryDefinition . RELATIVE_TO , directory , startwritten , name ) ; if ( startwritten ) { writer . writeEndElement ( ) ; } } writer . writeEndElement ( ) ; } if ( config . hasDefined ( REWRITE ) ) { for ( final ModelNode rewritenode : config . get ( REWRITE ) . asList ( ) ) { Property prop = rewritenode . asProperty ( ) ; ModelNode rewrite = prop . getValue ( ) ; writer . writeStartElement ( REWRITE ) ; writer . writeAttribute ( NAME , prop . getName ( ) ) ; WebReWriteDefinition . PATTERN . marshallAsAttribute ( rewrite , false , writer ) ; WebReWriteDefinition . SUBSTITUTION . marshallAsAttribute ( rewrite , false , writer ) ; WebReWriteDefinition . FLAGS . marshallAsAttribute ( rewrite , false , writer ) ; if ( rewrite . hasDefined ( CONDITION ) ) { for ( final ModelNode conditionnode : rewrite . get ( CONDITION ) . asList ( ) ) { Property conditionProp = conditionnode . asProperty ( ) ; ModelNode condition = conditionProp . getValue ( ) ; writer . writeStartElement ( CONDITION ) ; writer . writeAttribute ( NAME , conditionProp . getName ( ) ) ; WebReWriteConditionDefinition . TEST . marshallAsAttribute ( condition , false , writer ) ; WebReWriteConditionDefinition . PATTERN . marshallAsAttribute ( condition , false , writer ) ; WebReWriteConditionDefinition . FLAGS . marshallAsAttribute ( condition , false , writer ) ; writer . writeEndElement ( ) ; } } writer . writeEndElement ( ) ; } } if ( config . get ( SSO_PATH . getKey ( ) , SSO_PATH . getValue ( ) ) . isDefined ( ) ) { final ModelNode sso ; sso = config . get ( SSO_PATH . getKey ( ) , SSO_PATH . getValue ( ) ) ; writer . writeStartElement ( SSO ) ; for ( SimpleAttributeDefinition attr : WebSSODefinition . SSO_ATTRIBUTES ) { attr . marshallAsAttribute ( sso , false , writer ) ; } writer . writeEndElement ( ) ; } // End of the VIRTUAL_SERVER writer . writeEndElement ( ) ; } if ( node . hasDefined ( VALVE ) ) { for ( final Property valve : node . get ( VALVE ) . asPropertyList ( ) ) { final ModelNode config = valve . getValue ( ) ; writer . writeStartElement ( Element . VALVE . getLocalName ( ) ) ; writer . writeAttribute ( NAME , valve . getName ( ) ) ; for ( AttributeDefinition attr : WebValveDefinition . ATTRIBUTES ) { if ( attr instanceof SimpleAttributeDefinition ) { ( ( SimpleAttributeDefinition ) attr ) . marshallAsAttribute ( config , false , writer ) ; } } if ( config . hasDefined ( PARAM ) ) { for ( final Property entry : config . get ( PARAM ) . asPropertyList ( ) ) { writer . writeEmptyElement ( Element . PARAM . getLocalName ( ) ) ; writer . writeAttribute ( Attribute . PARAM_NAME . getLocalName ( ) , entry . getName ( ) ) ; writer . writeAttribute ( Attribute . PARAM_VALUE . getLocalName ( ) , entry . getValue ( ) . asString ( ) ) ; } } writer . writeEndElement ( ) ; } } } writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( XMLExtendedStreamReader reader , List < ModelNode > list ) throws XMLStreamException { PathAddress address = PathAddress . pathAddress ( PathElement . pathElement ( SUBSYSTEM , WebExtension . SUBSYSTEM_NAME ) ) ; final ModelNode subsystem = new ModelNode ( ) ; subsystem . get ( OP ) . set ( ADD ) ; subsystem . get ( OP_ADDR ) . set ( address . toModelNode ( ) ) ; final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { requireNoNamespaceAttribute ( reader , i ) ; final String value = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; switch ( attribute ) { case NATIVE : WebDefinition . NATIVE . parseAndSetParameter ( value , subsystem , reader ) ; break ; case DEFAULT_VIRTUAL_SERVER : WebDefinition . DEFAULT_VIRTUAL_SERVER . parseAndSetParameter ( value , subsystem , reader ) ; break ; case INSTANCE_ID : WebDefinition . INSTANCE_ID . parseAndSetParameter ( value , subsystem , reader ) ; break ; case DEFAULT_SESSION_TIMEOUT : attributeSupportedSince ( Namespace . WEB_2_2 , reader , i ) ; WebDefinition . DEFAULT_SESSION_TIMEOUT . parseAndSetParameter ( value , subsystem , reader ) ; break ; default : throw unexpectedAttribute ( reader , i ) ; } } list . add ( subsystem ) ; boolean containerConfigDefined = false ; final Namespace namespace = Namespace . forUri ( reader . getNamespaceURI ( ) ) ; // elements while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { switch ( namespace ) { case WEB_1_0 : case WEB_1_1 : case WEB_1_2 : case WEB_1_3 : { final Element element = Element . forName ( reader . getLocalName ( ) ) ; switch ( element ) { case CONTAINER_CONFIG : { parseContainerConfig ( reader , address , list ) ; containerConfigDefined = true ; break ; } case CONNECTOR : { parseConnector ( reader , address , list ) ; break ; } case VIRTUAL_SERVER : { parseHost ( reader , address , list ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } break ; } case WEB_1_4 : case WEB_1_5 : case WEB_2_0 : case WEB_2_1 : case WEB_2_2 : { final Element element = Element . forName ( reader . getLocalName ( ) ) ; switch ( element ) { case CONTAINER_CONFIG : { parseContainerConfig ( reader , address , list ) ; containerConfigDefined = true ; break ; } case CONNECTOR : { parseConnector ( reader , address , list ) ; break ; } case VIRTUAL_SERVER : { parseHost ( reader , address , list ) ; break ; } case VALVE : { parseValve ( reader , address , list ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } break ; } default : { throw unexpectedElement ( reader ) ; } } } if ( ! containerConfigDefined ) { addDefaultContainerConfig ( address , list ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo attribute . marshallAsAttribute should return boolean [CODESPLIT] private boolean writeAttribute ( XMLExtendedStreamWriter writer , SimpleAttributeDefinition attribute , ModelNode node , boolean startWriten , String origin ) throws XMLStreamException { if ( attribute . isMarshallable ( node , false ) ) { if ( ! startWriten ) { startWriten = true ; writer . writeStartElement ( origin ) ; } attribute . marshallAsAttribute ( node , false , writer ) ; } return startWriten ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void registerOperations ( ManagementResourceRegistration registration ) { super . registerOperations ( registration ) ; registration . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void start ( final StartContext context ) throws StartException { final Runnable task = new Runnable ( ) { @ Override public void run ( ) { try { getValue ( ) . start ( ) ; context . complete ( ) ; } catch ( Throwable e ) { context . failed ( new StartException ( e ) ) ; } } } ; try { executor . getValue ( ) . submit ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receives IIOP requests to this servant s <code > EJBObject< / code > s and forwards them to the bean container through the JBoss <code > MBean< / code > server . [CODESPLIT] public OutputStream _invoke ( final String opName , final InputStream in , final ResponseHandler handler ) { EjbLogger . ROOT_LOGGER . tracef ( \"EJBObject invocation: %s\" , opName ) ; SkeletonStrategy op = methodInvokerMap . get ( opName ) ; if ( op == null ) { EjbLogger . ROOT_LOGGER . debugf ( \"Unable to find opname '%s' valid operations:%s\" , opName , methodInvokerMap . keySet ( ) ) ; throw new BAD_OPERATION ( opName ) ; } final NamespaceContextSelector selector = componentView . getComponent ( ) . getNamespaceContextSelector ( ) ; final ClassLoader oldCl = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; NamespaceContextSelector . pushCurrentSelector ( selector ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( classLoader ) ; org . omg . CORBA_2_3 . portable . OutputStream out ; try { Object retVal ; if ( ! home && opName . equals ( \"_get_handle\" ) ) { retVal = new HandleImplIIOP ( orb . object_to_string ( _this_object ( ) ) ) ; } else if ( home && opName . equals ( \"_get_homeHandle\" ) ) { retVal = homeHandle ; } else if ( home && opName . equals ( \"_get_EJBMetaData\" ) ) { retVal = ejbMetaData ; } else { Principal identityPrincipal = null ; Principal principal = null ; Object credential = null ; if ( this . sasCurrent != null ) { final byte [ ] incomingIdentity = this . sasCurrent . get_incoming_principal_name ( ) ; //we have an identity token, which is a trust based mechanism if ( incomingIdentity != null && incomingIdentity . length > 0 ) { String name = new String ( incomingIdentity , StandardCharsets . UTF_8 ) ; int domainIndex = name . indexOf ( ' ' ) ; if ( domainIndex > 0 ) name = name . substring ( 0 , domainIndex ) ; identityPrincipal = new NamePrincipal ( name ) ; } final byte [ ] incomingUsername = this . sasCurrent . get_incoming_username ( ) ; if ( incomingUsername != null && incomingUsername . length > 0 ) { final byte [ ] incomingPassword = this . sasCurrent . get_incoming_password ( ) ; String name = new String ( incomingUsername , StandardCharsets . UTF_8 ) ; int domainIndex = name . indexOf ( ' ' ) ; if ( domainIndex > 0 ) { name = name . substring ( 0 , domainIndex ) ; } principal = new NamePrincipal ( name ) ; credential = new String ( incomingPassword , StandardCharsets . UTF_8 ) . toCharArray ( ) ; } } final Object [ ] params = op . readParams ( ( org . omg . CORBA_2_3 . portable . InputStream ) in ) ; if ( ! this . home && opName . equals ( \"isIdentical\" ) && params . length == 1 ) { //handle isIdentical specially Object val = params [ 0 ] ; retVal = val instanceof org . omg . CORBA . Object && handleIsIdentical ( ( org . omg . CORBA . Object ) val ) ; } else { if ( this . securityDomain != null ) { // an elytron security domain is available: authenticate and authorize the client before invoking the component. SecurityIdentity identity = this . securityDomain . getAnonymousSecurityIdentity ( ) ; AuthenticationConfiguration authenticationConfiguration = AuthenticationConfiguration . EMPTY ; if ( identityPrincipal != null ) { // we have an identity token principal - check if the TLS identity, if available, // has permission to run as the identity token principal. // TODO use the TLS identity when that becomes available to us. // no TLS identity found, check if an initial context token was also sent. If it was, // authenticate the incoming username/password and check if the resulting identity has // permission to run as the identity token principal. if ( principal != null ) { char [ ] password = ( char [ ] ) credential ; authenticationConfiguration = authenticationConfiguration . useName ( principal . getName ( ) ) . usePassword ( password ) ; SecurityIdentity authenticatedIdentity = this . authenticate ( principal , password ) ; identity = authenticatedIdentity . createRunAsIdentity ( identityPrincipal . getName ( ) , true ) ; } else { // no TLS nor initial context token found - check if the anonymous identity has // permission to run as the identity principal. identity = this . securityDomain . getAnonymousSecurityIdentity ( ) . createRunAsIdentity ( identityPrincipal . getName ( ) , true ) ; } } else if ( principal != null ) { char [ ] password = ( char [ ] ) credential ; // we have an initial context token containing a username/password pair. authenticationConfiguration = authenticationConfiguration . useName ( principal . getName ( ) ) . usePassword ( password ) ; identity = this . authenticate ( principal , password ) ; } final InterceptorContext interceptorContext = new InterceptorContext ( ) ; this . prepareInterceptorContext ( op , params , interceptorContext ) ; try { final AuthenticationContext context = AuthenticationContext . captureCurrent ( ) . with ( MatchRule . ALL . matchProtocol ( \"iiop\" ) , authenticationConfiguration ) ; retVal = identity . runAs ( ( PrivilegedExceptionAction < Object > ) ( ) -> context . run ( ( PrivilegedExceptionAction < Object > ) ( ) -> this . componentView . invoke ( interceptorContext ) ) ) ; } catch ( PrivilegedActionException e ) { throw e . getCause ( ) ; } } else { // legacy security behavior: setup the security context if a SASCurrent is available and invoke the component. // One of the EJB security interceptors will authenticate and authorize the client. SecurityContext legacyContext = null ; if ( this . legacySecurityDomain != null && ( identityPrincipal != null || principal != null ) ) { // we don't have any real way to establish trust in identity based auth so we just use // the SASCurrent as a credential, and a custom legacy login module can make a decision for us. final Object finalCredential = identityPrincipal != null ? this . sasCurrent : credential ; final Principal finalPrincipal = identityPrincipal != null ? identityPrincipal : principal ; if ( WildFlySecurityManager . isChecking ( ) ) { legacyContext = AccessController . doPrivileged ( ( PrivilegedExceptionAction < SecurityContext > ) ( ) -> { SecurityContext sc = SecurityContextFactory . createSecurityContext ( this . legacySecurityDomain ) ; sc . getUtil ( ) . createSubjectInfo ( finalPrincipal , finalCredential , null ) ; return sc ; } ) ; } else { legacyContext = SecurityContextFactory . createSecurityContext ( this . legacySecurityDomain ) ; legacyContext . getUtil ( ) . createSubjectInfo ( finalPrincipal , finalCredential , null ) ; } } if ( legacyContext != null ) { setSecurityContextOnAssociation ( legacyContext ) ; } try { final InterceptorContext interceptorContext = new InterceptorContext ( ) ; if ( legacyContext != null ) { interceptorContext . putPrivateData ( SecurityContext . class , legacyContext ) ; } prepareInterceptorContext ( op , params , interceptorContext ) ; retVal = this . componentView . invoke ( interceptorContext ) ; } finally { if ( legacyContext != null ) { clearSecurityContextOnAssociation ( ) ; } } } } } out = ( org . omg . CORBA_2_3 . portable . OutputStream ) handler . createReply ( ) ; if ( op . isNonVoid ( ) ) { op . writeRetval ( out , retVal ) ; } } catch ( Throwable e ) { EjbLogger . ROOT_LOGGER . trace ( \"Exception in EJBObject invocation\" , e ) ; if ( e instanceof MBeanException ) { e = ( ( MBeanException ) e ) . getTargetException ( ) ; } RmiIdlUtil . rethrowIfCorbaSystemException ( e ) ; out = ( org . omg . CORBA_2_3 . portable . OutputStream ) handler . createExceptionReply ( ) ; op . writeException ( out , e ) ; } return out ; } finally { NamespaceContextSelector . popCurrentSelector ( ) ; WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( oldCl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receives intra - VM invocations on this servant s <code > EJBObject< / code > s and forwards them to the bean container through the JBoss <code > MBean< / code > server . [CODESPLIT] public Object invoke ( String opName , Object [ ] arguments , Transaction tx , Principal identity , Object credential ) throws Exception { EjbLogger . ROOT_LOGGER . tracef ( \"EJBObject local invocation: %s\" , opName ) ; SkeletonStrategy op = methodInvokerMap . get ( opName ) ; if ( op == null ) { throw new BAD_OPERATION ( opName ) ; } if ( tx != null ) { transactionManager . resume ( tx ) ; } try { final InterceptorContext interceptorContext = new InterceptorContext ( ) ; prepareInterceptorContext ( op , arguments , interceptorContext ) ; return componentView . invoke ( interceptorContext ) ; } finally { if ( tx != null ) { if ( transactionManager . getStatus ( ) != Status . STATUS_NO_TRANSACTION ) { transactionManager . suspend ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate the user with the given credential against the configured Elytron security domain . [CODESPLIT] private SecurityIdentity authenticate ( final Principal principal , final char [ ] credential ) throws Exception { final ServerAuthenticationContext context = this . securityDomain . createNewAuthenticationContext ( ) ; final PasswordGuessEvidence evidence = new PasswordGuessEvidence ( credential != null ? credential : null ) ; try { context . setAuthenticationPrincipal ( principal ) ; if ( context . verifyEvidence ( evidence ) ) { if ( context . authorize ( ) ) { context . succeed ( ) ; return context . getAuthorizedIdentity ( ) ; } else { context . fail ( ) ; throw new SecurityException ( \"Authorization failed\" ) ; } } else { context . fail ( ) ; throw new SecurityException ( \"Authentication failed\" ) ; } } catch ( IllegalArgumentException | IllegalStateException | RealmUnavailableException e ) { context . fail ( ) ; throw e ; } finally { evidence . destroy ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "centralize this hack [CODESPLIT] public static MethodIntf of ( final InterceptorContext invocation ) { //for timer invocations there is no view, so the methodInf is attached directly //to the context. Otherwise we retrieve it from the invoked view MethodIntf methodIntf = invocation . getPrivateData ( MethodIntf . class ) ; if ( methodIntf == null ) { final ComponentView componentView = invocation . getPrivateData ( ComponentView . class ) ; if ( componentView != null ) { methodIntf = componentView . getPrivateData ( MethodIntf . class ) ; } else { methodIntf = MethodIntf . BEAN ; } } return methodIntf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up jndi bindings for each of the views exposed by the passed <code > sessionBean< / code > [CODESPLIT] private void setupJNDIBindings ( EJBComponentDescription sessionBean , DeploymentUnit deploymentUnit ) throws DeploymentUnitProcessingException { final Collection < ViewDescription > views = sessionBean . getViews ( ) ; if ( views == null || views . isEmpty ( ) ) { EjbLogger . DEPLOYMENT_LOGGER . noJNDIBindingsForSessionBean ( sessionBean . getEJBName ( ) ) ; return ; } // In case of EJB bindings, appname == .ear file name/application-name set in the application.xml (if it's an .ear deployment) // NOTE: Do NOT use the app name from the EEModuleDescription.getApplicationName() because the Java EE spec has a different and conflicting meaning for app name // (where app name == module name in the absence of a .ear). Use EEModuleDescription.getEarApplicationName() instead final String applicationName = sessionBean . getModuleDescription ( ) . getEarApplicationName ( ) ; final String distinctName = sessionBean . getModuleDescription ( ) . getDistinctName ( ) ; // default to empty string final String globalJNDIBaseName = \"java:global/\" + ( applicationName != null ? applicationName + \"/\" : \"\" ) + sessionBean . getModuleName ( ) + \"/\" + sessionBean . getEJBName ( ) ; final String appJNDIBaseName = \"java:app/\" + sessionBean . getModuleName ( ) + \"/\" + sessionBean . getEJBName ( ) ; final String moduleJNDIBaseName = \"java:module/\" + sessionBean . getEJBName ( ) ; final String remoteExportedJNDIBaseName = \"java:jboss/exported/\" + ( applicationName != null ? applicationName + \"/\" : \"\" ) + sessionBean . getModuleName ( ) + \"/\" + sessionBean . getEJBName ( ) ; final String ejbNamespaceBindingBaseName = \"ejb:\" + ( applicationName != null ? applicationName : \"\" ) + \"/\" + sessionBean . getModuleName ( ) + \"/\" + ( distinctName != \"\" ? distinctName + \"/\" : \"\" ) + sessionBean . getEJBName ( ) ; // the base ServiceName which will be used to create the ServiceName(s) for each of the view bindings final StringBuilder jndiBindingsLogMessage = new StringBuilder ( ) ; jndiBindingsLogMessage . append ( System . lineSeparator ( ) ) . append ( System . lineSeparator ( ) ) ; // now create the bindings for each view under the java:global, java:app and java:module namespaces EJBViewDescription ejbViewDescription = null ; for ( ViewDescription viewDescription : views ) { ejbViewDescription = ( EJBViewDescription ) viewDescription ; if ( appclient && ejbViewDescription . getMethodIntf ( ) != MethodIntf . REMOTE && ejbViewDescription . getMethodIntf ( ) != MethodIntf . HOME ) { continue ; } if ( ! ejbViewDescription . hasJNDIBindings ( ) ) continue ; final String viewClassName = ejbViewDescription . getViewClassName ( ) ; // java:global bindings final String globalJNDIName = globalJNDIBaseName + \"!\" + viewClassName ; registerBinding ( sessionBean , viewDescription , globalJNDIName ) ; logBinding ( jndiBindingsLogMessage , globalJNDIName ) ; // java:app bindings final String appJNDIName = appJNDIBaseName + \"!\" + viewClassName ; registerBinding ( sessionBean , viewDescription , appJNDIName ) ; logBinding ( jndiBindingsLogMessage , appJNDIName ) ; // java:module bindings final String moduleJNDIName = moduleJNDIBaseName + \"!\" + viewClassName ; registerBinding ( sessionBean , viewDescription , moduleJNDIName ) ; logBinding ( jndiBindingsLogMessage , moduleJNDIName ) ; // If it a remote or (remote) home view then bind the java:jboss/exported jndi names for the view if ( ejbViewDescription . getMethodIntf ( ) == MethodIntf . REMOTE || ejbViewDescription . getMethodIntf ( ) == MethodIntf . HOME ) { final String remoteJNDIName = remoteExportedJNDIBaseName + \"!\" + viewClassName ; if ( RequestControllerActivationMarker . isRequestControllerEnabled ( deploymentUnit ) ) { registerControlPointBinding ( sessionBean , viewDescription , remoteJNDIName , deploymentUnit ) ; } else { registerBinding ( sessionBean , viewDescription , remoteJNDIName ) ; } logBinding ( jndiBindingsLogMessage , remoteJNDIName ) ; } // log EJB's ejb:/ namespace binding final String ejbNamespaceBindingName = sessionBean . isStateful ( ) ? ejbNamespaceBindingBaseName + \"!\" + viewClassName + \"?stateful\" : ejbNamespaceBindingBaseName + \"!\" + viewClassName ; logBinding ( jndiBindingsLogMessage , ejbNamespaceBindingName ) ; } // EJB3.1 spec, section 4.4.1 Global JNDI Access states: // In addition to the previous requirements, if the bean exposes only one of the // applicable client interfaces(or alternatively has only a no-interface view), the container // registers an entry for that view with the following syntax : // // java:global[/<app-name>]/<module-name>/<bean-name> // // Note that this also applies to java:app and java:module bindings // as can be seen by the examples in 4.4.2.1 if ( views . size ( ) == 1 ) { final EJBViewDescription viewDescription = ( EJBViewDescription ) views . iterator ( ) . next ( ) ; if ( ejbViewDescription . hasJNDIBindings ( ) ) { // java:global binding registerBinding ( sessionBean , viewDescription , globalJNDIBaseName ) ; logBinding ( jndiBindingsLogMessage , globalJNDIBaseName ) ; // java:app binding registerBinding ( sessionBean , viewDescription , appJNDIBaseName ) ; logBinding ( jndiBindingsLogMessage , appJNDIBaseName ) ; // java:module binding registerBinding ( sessionBean , viewDescription , moduleJNDIBaseName ) ; logBinding ( jndiBindingsLogMessage , moduleJNDIBaseName ) ; } } // log the jndi bindings EjbLogger . DEPLOYMENT_LOGGER . jndiBindings ( sessionBean . getEJBName ( ) , deploymentUnit , jndiBindingsLogMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a session using the global request controller . [CODESPLIT] public SessionID createSessionRemote ( ) { ControlPoint controlPoint = getControlPoint ( ) ; if ( controlPoint == null ) { return createSession ( ) ; } else { try { RunResult result = controlPoint . beginRequest ( ) ; if ( result == RunResult . REJECTED ) { throw EjbLogger . ROOT_LOGGER . containerSuspended ( ) ; } try { return createSession ( ) ; } finally { controlPoint . requestComplete ( ) ; } } catch ( EJBComponentUnavailableException | ComponentIsStoppedException e ) { throw e ; } catch ( Exception e ) { throw new EJBException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Infer the name of the JMS destination based on the queue s address . [CODESPLIT] private String inferDestinationName ( String address ) { if ( address . startsWith ( JMS_QUEUE_PREFIX ) ) { return address . substring ( JMS_QUEUE_PREFIX . length ( ) ) ; } else if ( address . startsWith ( JMS_TOPIC_PREFIX ) ) { return address . substring ( JMS_TOPIC_PREFIX . length ( ) ) ; } else { return address ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; AbstractSecurityDeployer < ? > deployer = null ; if ( DeploymentTypeMarker . isType ( DeploymentType . EAR , deploymentUnit ) ) { deployer = new EarSecurityDeployer ( ) ; JaccService < ? > service = deployer . deploy ( deploymentUnit ) ; if ( service != null ) { final ServiceName jaccServiceName = deploymentUnit . getServiceName ( ) . append ( JaccService . SERVICE_NAME ) ; final ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; ServiceBuilder < ? > builder = serviceTarget . addService ( jaccServiceName , service ) ; if ( deploymentUnit . getParent ( ) != null ) { // add dependency to parent policy final DeploymentUnit parentDU = deploymentUnit . getParent ( ) ; builder . addDependency ( parentDU . getServiceName ( ) . append ( JaccService . SERVICE_NAME ) , PolicyConfiguration . class , service . getParentPolicyInjector ( ) ) ; } builder . setInitialMode ( Mode . ACTIVE ) . install ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void undeploy ( DeploymentUnit context ) { AbstractSecurityDeployer < ? > deployer = null ; if ( DeploymentTypeMarker . isType ( DeploymentType . EAR , context ) ) { deployer = new EarSecurityDeployer ( ) ; deployer . undeploy ( context ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public synchronized void start ( final StartContext context ) throws StartException { final JMSServerManager jmsManager = jmsServer . getValue ( ) ; final Runnable task = new Runnable ( ) { @ Override public void run ( ) { try { jmsManager . createConnectionFactory ( false , configuration , configuration . getBindings ( ) ) ; context . complete ( ) ; } catch ( Throwable e ) { context . failed ( MessagingLogger . ROOT_LOGGER . failedToCreate ( e , \"connection-factory\" ) ) ; } } } ; try { executorInjector . getValue ( ) . execute ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public synchronized void stop ( final StopContext context ) { final JMSServerManager jmsManager = jmsServer . getValue ( ) ; final Runnable task = new Runnable ( ) { @ Override public void run ( ) { try { jmsManager . destroyConnectionFactory ( name ) ; } catch ( Throwable e ) { MessagingLogger . ROOT_LOGGER . failedToDestroy ( \"connection-factory\" , name ) ; } context . complete ( ) ; } } ; // JMS Server Manager uses locking which waits on service completion, use async to prevent starvation try { executorInjector . getValue ( ) . execute ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The <code > endTransaction< / code > method ends a transaction and translates any exceptions into TransactionRolledBack [ Local ] Exception or SystemException . [CODESPLIT] protected void endTransaction ( final Transaction tx ) { ContextTransactionManager tm = ContextTransactionManager . getInstance ( ) ; try { if ( ! tx . equals ( tm . getTransaction ( ) ) ) { throw EjbLogger . ROOT_LOGGER . wrongTxOnThread ( tx , tm . getTransaction ( ) ) ; } final int txStatus = tx . getStatus ( ) ; if ( txStatus == Status . STATUS_ACTIVE ) { // Commit tx // This will happen if // a) everything goes well // b) app. exception was thrown tm . commit ( ) ; } else if ( txStatus == Status . STATUS_MARKED_ROLLBACK ) { tm . rollback ( ) ; } else if ( txStatus == Status . STATUS_ROLLEDBACK || txStatus == Status . STATUS_ROLLING_BACK ) { // handle reaper canceled (rolled back) tx case (see WFLY-1346) // clear current tx state and throw RollbackException (EJBTransactionRolledbackException) tm . rollback ( ) ; throw EjbLogger . ROOT_LOGGER . transactionAlreadyRolledBack ( tx ) ; } else if ( txStatus == Status . STATUS_UNKNOWN ) { // STATUS_UNKNOWN isn't expected to be reached here but if it does, we need to clear current thread tx. // It is possible that calling tm.commit() could succeed but we call tm.rollback, since this is an unexpected // tx state that are are handling. tm . rollback ( ) ; // if the tm.rollback doesn't fail, we throw an EJBException to reflect the unexpected tx state. throw EjbLogger . ROOT_LOGGER . transactionInUnexpectedState ( tx , statusAsString ( txStatus ) ) ; } else { // logically, all of the following (unexpected) tx states are handled here: //  Status.STATUS_PREPARED //  Status.STATUS_PREPARING //  Status.STATUS_COMMITTING //  Status.STATUS_NO_TRANSACTION //  Status.STATUS_COMMITTED tm . suspend ( ) ; // clear current tx state and throw EJBException throw EjbLogger . ROOT_LOGGER . transactionInUnexpectedState ( tx , statusAsString ( txStatus ) ) ; } } catch ( RollbackException e ) { throw new EJBTransactionRolledbackException ( e . toString ( ) , e ) ; } catch ( HeuristicMixedException | SystemException | HeuristicRollbackException e ) { throw new EJBException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The <code > setRollbackOnly< / code > method calls setRollbackOnly () on the invocation s transaction and logs any exceptions than may occur . [CODESPLIT] protected void setRollbackOnly ( Transaction tx , final Throwable t ) { try { tx . setRollbackOnly ( ) ; } catch ( Throwable t2 ) { EjbLogger . ROOT_LOGGER . failedToSetRollbackOnly ( t2 ) ; if ( t != null ) { t . addSuppressed ( t2 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether this { @link Class } is configured to be used . [CODESPLIT] private boolean isMetricEnabled ( Class metricClass ) { for ( LoadMetric enabledMetric : enabledMetrics ) { if ( metricClass . isInstance ( enabledMetric ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers endpoint and its associated WS handlers . [CODESPLIT] public void registerEndpointHandlers ( final String endpointClass , final Set < String > endpointHandlers ) { if ( ( endpointClass == null ) || ( endpointHandlers == null ) ) { throw new IllegalArgumentException ( ) ; } endpointHandlersMap . put ( endpointClass , Collections . unmodifiableSet ( endpointHandlers ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This transformer does the following : - maps <passivation - store / > to <cluster - passivation - store / > - sets appropriate defaults for IDLE_TIMEOUT IDLE_TIMEOUT_UNIT PASSIVATE_EVENTS_ON_REPLICATE and CLIENT_MAPPINGS_CACHE [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) private static void registerPassivationStoreTransformers_1_2_1_and_1_3_0 ( ResourceTransformationDescriptionBuilder parent ) { ResourceTransformationDescriptionBuilder child = parent . addChildRedirection ( PassivationStoreResourceDefinition . INSTANCE . getPathElement ( ) , PathElement . pathElement ( EJB3SubsystemModel . CLUSTER_PASSIVATION_STORE ) ) ; child . getAttributeBuilder ( ) . setValueConverter ( AttributeConverter . Factory . createHardCoded ( new ModelNode ( true ) , true ) , EJB3SubsystemModel . PASSIVATE_EVENTS_ON_REPLICATE ) . setValueConverter ( AttributeConverter . Factory . createHardCoded ( new ModelNode ( \"default\" ) , true ) , EJB3SubsystemModel . CLIENT_MAPPINGS_CACHE ) . setValueConverter ( AttributeConverter . Factory . createHardCoded ( new ModelNode ( ) . set ( Long . valueOf ( Integer . MAX_VALUE ) ) , true ) , EJB3SubsystemModel . IDLE_TIMEOUT ) . setValueConverter ( AttributeConverter . Factory . createHardCoded ( new ModelNode ( ) . set ( TimeUnit . SECONDS . name ( ) ) , true ) , EJB3SubsystemModel . IDLE_TIMEOUT_UNIT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Create the { @code Policy } array containing the { @code POA } policies using the values specified in the constructor . When creating a { @code POA } the parent { @code POA } is responsible for generating the relevant policies beforehand . < / p > [CODESPLIT] private Policy [ ] createPolicies ( POA poa ) { List < Policy > policies = new ArrayList < Policy > ( ) ; if ( this . sslOnly ) policies . add ( ZeroPortPolicy . getPolicy ( ) ) ; if ( this . idAssignmentPolicyValue != null ) policies . add ( poa . create_id_assignment_policy ( this . idAssignmentPolicyValue ) ) ; if ( this . idUniquenessPolicyValue != null ) policies . add ( poa . create_id_uniqueness_policy ( this . idUniquenessPolicyValue ) ) ; if ( this . implicitActivationPolicyValue != null ) policies . add ( poa . create_implicit_activation_policy ( this . implicitActivationPolicyValue ) ) ; if ( this . lifespanPolicyValue != null ) policies . add ( poa . create_lifespan_policy ( this . lifespanPolicyValue ) ) ; if ( this . requestProcessingPolicyValue != null ) policies . add ( poa . create_request_processing_policy ( this . requestProcessingPolicyValue ) ) ; if ( this . servantRetentionPolicyValue != null ) policies . add ( poa . create_servant_retention_policy ( this . servantRetentionPolicyValue ) ) ; if ( this . threadPolicyValue != null ) policies . add ( poa . create_thread_policy ( this . threadPolicyValue ) ) ; return policies . toArray ( new Policy [ policies . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the code of a given method within a stub class . [CODESPLIT] private static void generateMethodCode ( ClassFile asm , Class < ? > superclass , Method m , String idlName , String strategyField , String initMethod ) { Class < ? > returnType = m . getReturnType ( ) ; Class < ? > [ ] paramTypes = m . getParameterTypes ( ) ; Class < ? > [ ] exceptions = m . getExceptionTypes ( ) ; // Generate a static field with the StubStrategy for the method asm . addField ( Modifier . PRIVATE + Modifier . STATIC , strategyField , StubStrategy . class ) ; // Generate the method code final CodeAttribute ca = asm . addMethod ( m ) . getCodeAttribute ( ) ; // The method code issues a call // super.invoke*(idlName, strategyField, args) ca . aload ( 0 ) ; ca . ldc ( idlName ) ; ca . getstatic ( asm . getName ( ) , strategyField , StubStrategy . class ) ; // Push args if ( paramTypes . length == 0 ) { ca . iconst ( 0 ) ; ca . anewarray ( Object . class . getName ( ) ) ; //asm.pushField(Util.class, \"NOARGS\"); } else { ca . iconst ( paramTypes . length ) ; ca . anewarray ( Object . class . getName ( ) ) ; int index = 1 ; for ( int j = 0 ; j < paramTypes . length ; j ++ ) { Class < ? > type = paramTypes [ j ] ; ca . dup ( ) ; ca . iconst ( j ) ; if ( ! type . isPrimitive ( ) ) { // object or array ca . aload ( index ) ; } else if ( type . equals ( double . class ) ) { ca . dload ( index ) ; Boxing . boxDouble ( ca ) ; index ++ ; } else if ( type . equals ( long . class ) ) { ca . lload ( index ) ; Boxing . boxLong ( ca ) ; index ++ ; } else if ( type . equals ( float . class ) ) { ca . fload ( index ) ; Boxing . boxFloat ( ca ) ; } else { ca . iload ( index ) ; Boxing . boxIfNessesary ( ca , DescriptorUtils . makeDescriptor ( type ) ) ; } index ++ ; ca . aastore ( ) ; } } // Generate the call to an invoke* method ot the superclass String invoke = \"invoke\" ; String ret = \"Ljava/lang/Object;\" ; if ( returnType . isPrimitive ( ) && returnType != Void . TYPE ) { String typeName = returnType . getName ( ) ; invoke += ( Character . toUpperCase ( typeName . charAt ( 0 ) ) + typeName . substring ( 1 ) ) ; ret = DescriptorUtils . makeDescriptor ( returnType ) ; } ca . invokevirtual ( superclass . getName ( ) , invoke , \"(Ljava/lang/String;Lorg/wildfly/iiop/openjdk/rmi/marshal/strategy/StubStrategy;[Ljava/lang/Object;)\" + ret ) ; if ( ! returnType . isPrimitive ( ) && returnType != Object . class ) { ca . checkcast ( returnType ) ; } ca . returnInstruction ( ) ; // Generate a static method that initializes the method's strategy field final CodeAttribute init = asm . addMethod ( Modifier . PRIVATE + Modifier . STATIC , initMethod , \"V\" ) . getCodeAttribute ( ) ; int i ; int len ; // Push first argument for StubStrategy constructor: // array with abbreviated names of the param marshallers len = paramTypes . length ; init . iconst ( len ) ; init . anewarray ( String . class . getName ( ) ) ; for ( i = 0 ; i < len ; i ++ ) { init . dup ( ) ; init . iconst ( i ) ; init . ldc ( CDRStream . abbrevFor ( paramTypes [ i ] ) ) ; init . aastore ( ) ; } // Push second argument for StubStrategy constructor: // array with exception repository ids len = exceptions . length ; int n = 0 ; for ( i = 0 ; i < len ; i ++ ) { if ( ! RemoteException . class . isAssignableFrom ( exceptions [ i ] ) ) { n ++ ; } } init . iconst ( n ) ; init . anewarray ( String . class . getName ( ) ) ; try { int j = 0 ; for ( i = 0 ; i < len ; i ++ ) { if ( ! RemoteException . class . isAssignableFrom ( exceptions [ i ] ) ) { init . dup ( ) ; init . iconst ( j ) ; init . ldc ( ExceptionAnalysis . getExceptionAnalysis ( exceptions [ i ] ) . getExceptionRepositoryId ( ) ) ; init . aastore ( ) ; j ++ ; } } } catch ( RMIIIOPViolationException e ) { throw EjbLogger . ROOT_LOGGER . exceptionRepositoryNotFound ( exceptions [ i ] . getName ( ) , e . getLocalizedMessage ( ) ) ; } // Push third argument for StubStrategy constructor: // array with exception class names init . iconst ( n ) ; init . anewarray ( String . class . getName ( ) ) ; int j = 0 ; for ( i = 0 ; i < len ; i ++ ) { if ( ! RemoteException . class . isAssignableFrom ( exceptions [ i ] ) ) { init . dup ( ) ; init . iconst ( j ) ; init . ldc ( exceptions [ i ] . getName ( ) ) ; init . aastore ( ) ; j ++ ; } } // Push fourth argument for StubStrategy constructor: // abbreviated name of the return value marshaller init . ldc ( CDRStream . abbrevFor ( returnType ) ) ; // Push fifth argument for StubStrategy constructor: // null (no ClassLoader specified) init . aconstNull ( ) ; // Constructs the StubStrategy init . invokestatic ( StubStrategy . class . getName ( ) , \"forMethod\" , \"([Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)Lorg/wildfly/iiop/openjdk/rmi/marshal/strategy/StubStrategy;\" ) ; // Set the strategy field of this stub class init . putstatic ( asm . getName ( ) , strategyField , StubStrategy . class ) ; init . returnInstruction ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the bytecodes of a stub class for a given interface . [CODESPLIT] private static ClassFile generateCode ( InterfaceAnalysis interfaceAnalysis , Class < ? > superclass , String stubClassName ) { final ClassFile asm = new ClassFile ( stubClassName , superclass . getName ( ) , null , ModuleClassFactory . INSTANCE , interfaceAnalysis . getCls ( ) . getName ( ) ) ; int methodIndex = 0 ; AttributeAnalysis [ ] attrs = interfaceAnalysis . getAttributes ( ) ; for ( int i = 0 ; i < attrs . length ; i ++ ) { OperationAnalysis op = attrs [ i ] . getAccessorAnalysis ( ) ; generateMethodCode ( asm , superclass , op . getMethod ( ) , op . getIDLName ( ) , strategy ( methodIndex ) , init ( methodIndex ) ) ; methodIndex ++ ; op = attrs [ i ] . getMutatorAnalysis ( ) ; if ( op != null ) { generateMethodCode ( asm , superclass , op . getMethod ( ) , op . getIDLName ( ) , strategy ( methodIndex ) , init ( methodIndex ) ) ; methodIndex ++ ; } } final OperationAnalysis [ ] ops = interfaceAnalysis . getOperations ( ) ; for ( int i = 0 ; i < ops . length ; i ++ ) { generateMethodCode ( asm , superclass , ops [ i ] . getMethod ( ) , ops [ i ] . getIDLName ( ) , strategy ( methodIndex ) , init ( methodIndex ) ) ; methodIndex ++ ; } // Generate the constructor final ClassMethod ctor = asm . addMethod ( Modifier . PUBLIC , \"<init>\" , \"V\" ) ; ctor . getCodeAttribute ( ) . aload ( 0 ) ; ctor . getCodeAttribute ( ) . invokespecial ( superclass . getName ( ) , \"<init>\" , \"()V\" ) ; ctor . getCodeAttribute ( ) . returnInstruction ( ) ; // Generate the method _ids(), declared as abstract in ObjectImpl final String [ ] ids = interfaceAnalysis . getAllTypeIds ( ) ; asm . addField ( Modifier . PRIVATE + Modifier . STATIC , ID_FIELD_NAME , String [ ] . class ) ; final CodeAttribute idMethod = asm . addMethod ( Modifier . PUBLIC + Modifier . FINAL , \"_ids\" , \"[Ljava/lang/String;\" ) . getCodeAttribute ( ) ; idMethod . getstatic ( stubClassName , ID_FIELD_NAME , \"[Ljava/lang/String;\" ) ; idMethod . returnInstruction ( ) ; // Generate the static initializer final CodeAttribute clinit = asm . addMethod ( Modifier . STATIC , \"<clinit>\" , \"V\" ) . getCodeAttribute ( ) ; clinit . iconst ( ids . length ) ; clinit . anewarray ( String . class . getName ( ) ) ; for ( int i = 0 ; i < ids . length ; i ++ ) { clinit . dup ( ) ; clinit . iconst ( i ) ; clinit . ldc ( ids [ i ] ) ; clinit . aastore ( ) ; } clinit . putstatic ( stubClassName , ID_FIELD_NAME , \"[Ljava/lang/String;\" ) ; int n = methodIndex ; // last methodIndex + 1 for ( methodIndex = 0 ; methodIndex < n ; methodIndex ++ ) { clinit . invokestatic ( stubClassName , init ( methodIndex ) , \"()V\" ) ; } clinit . returnInstruction ( ) ; return asm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the bytecodes of a stub class for a given interface . [CODESPLIT] private static ClassFile makeCode ( InterfaceAnalysis interfaceAnalysis , Class < ? > superclass , String stubClassName ) { ClassFile code = generateCode ( interfaceAnalysis , superclass , stubClassName ) ; //try { //   String fname = stubClassName; //   fname = fname.substring(1 + fname.lastIndexOf('.')) + \".class\"; //   fname = \"/tmp/\" + fname; //   java.io.OutputStream cf = new java.io.FileOutputStream(fname); //   cf.write(code); //   cf.close(); //   System.err.println(\"wrote \" + fname); //} //catch(java.io.IOException ee) { //} return code ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the bytecodes of a stub class for a given interface . [CODESPLIT] public static ClassFile compile ( Class < ? > intf , String stubClassName ) { InterfaceAnalysis interfaceAnalysis = null ; try { interfaceAnalysis = InterfaceAnalysis . getInterfaceAnalysis ( intf ) ; } catch ( RMIIIOPViolationException e ) { throw EjbLogger . ROOT_LOGGER . rmiIiopVoliation ( e . getLocalizedMessage ( ) ) ; } return makeCode ( interfaceAnalysis , DynamicIIOPStub . class , stubClassName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the { @linkplain JobXmlResolver resolver } for the deployment inheriting any visible resolvers and job XML files from dependencies . [CODESPLIT] public static WildFlyJobXmlResolver forDeployment ( final DeploymentUnit deploymentUnit ) throws DeploymentUnitProcessingException { // If this deployment unit already has a resolver, just use it if ( deploymentUnit . hasAttachment ( BatchAttachments . JOB_XML_RESOLVER ) ) { return deploymentUnit . getAttachment ( BatchAttachments . JOB_XML_RESOLVER ) ; } // Get the module for it's class loader final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; final ClassLoader classLoader = module . getClassLoader ( ) ; WildFlyJobXmlResolver resolver ; // If we're an EAR we need to skip sub-deployments as they'll be process later, however all sub-deployments have // access to the EAR/lib directory so those resources need to be processed if ( DeploymentTypeMarker . isType ( DeploymentType . EAR , deploymentUnit ) ) { // Create a new WildFlyJobXmlResolver without jobs from sub-deployments as they'll be processed later final List < ResourceRoot > resources = new ArrayList <> ( ) ; for ( ResourceRoot r : deploymentUnit . getAttachmentList ( Attachments . RESOURCE_ROOTS ) ) { if ( ! SubDeploymentMarker . isSubDeployment ( r ) ) { resources . add ( r ) ; } } resolver = create ( classLoader , resources ) ; deploymentUnit . putAttachment ( BatchAttachments . JOB_XML_RESOLVER , resolver ) ; } else { // Create a new resolver for this deployment if ( deploymentUnit . hasAttachment ( Attachments . RESOURCE_ROOTS ) ) { resolver = create ( classLoader , deploymentUnit . getAttachmentList ( Attachments . RESOURCE_ROOTS ) ) ; } else { resolver = create ( classLoader , Collections . singletonList ( deploymentUnit . getAttachment ( Attachments . DEPLOYMENT_ROOT ) ) ) ; } deploymentUnit . putAttachment ( BatchAttachments . JOB_XML_RESOLVER , resolver ) ; // Process all accessible sub-deployments final List < DeploymentUnit > accessibleDeployments = deploymentUnit . getAttachmentList ( Attachments . ACCESSIBLE_SUB_DEPLOYMENTS ) ; for ( DeploymentUnit subDeployment : accessibleDeployments ) { // Skip our self if ( deploymentUnit . equals ( subDeployment ) ) { continue ; } if ( subDeployment . hasAttachment ( BatchAttachments . JOB_XML_RESOLVER ) ) { final WildFlyJobXmlResolver toCopy = subDeployment . getAttachment ( BatchAttachments . JOB_XML_RESOLVER ) ; WildFlyJobXmlResolver . merge ( resolver , toCopy ) ; } else { // We need to create a resolver for the sub-deployment and merge the two final WildFlyJobXmlResolver toCopy = forDeployment ( subDeployment ) ; subDeployment . putAttachment ( BatchAttachments . JOB_XML_RESOLVER , toCopy ) ; WildFlyJobXmlResolver . merge ( resolver , toCopy ) ; } } } return resolver ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the job XML file names which contain the job name . [CODESPLIT] Set < String > getJobXmlNames ( final String jobName ) { if ( jobNames . containsKey ( jobName ) ) { return Collections . unmodifiableSet ( jobNames . get ( jobName ) ) ; } return Collections . emptySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the state of an instance [CODESPLIT] private void init ( final ClassLoader classLoader ) { // Load the user defined resolvers for ( JobXmlResolver resolver : ServiceLoader . load ( JobXmlResolver . class , classLoader ) ) { jobXmlResolvers . add ( resolver ) ; for ( String jobXml : resolver . getJobXmlNames ( classLoader ) ) { addJob ( jobXml , resolver . resolveJobName ( jobXml , classLoader ) ) ; } } // Load the default names for ( Map . Entry < String , VirtualFile > entry : jobXmlFiles . entrySet ( ) ) { try { // Parsing the entire job XML seems excessive to just get the job name. There are two reasons for this: //  1) If an error occurs during parsing there's no real need to consider this a valid job //  2) Using the implementation parser seems less error prone for future-proofing final Job job = JobParser . parseJob ( entry . getValue ( ) . openStream ( ) , classLoader , new XMLResolver ( ) { // this is essentially what JBeret does, but it's ugly. JBeret might need an API to handle this @ Override public Object resolveEntity ( final String publicID , final String systemID , final String baseURI , final String namespace ) throws XMLStreamException { try { return ( jobXmlFiles . containsKey ( systemID ) ? jobXmlFiles . get ( systemID ) . openStream ( ) : null ) ; } catch ( IOException e ) { throw new XMLStreamException ( e ) ; } } } ) ; addJob ( entry . getKey ( ) , job . getId ( ) ) ; } catch ( XMLStreamException | IOException e ) { // Report the possible error as we don't want to fail the deployment. The job may never be run. BatchLogger . LOGGER . invalidJobXmlFile ( entry . getKey ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the canonical request URI from the request mapping data requestPath [CODESPLIT] protected String requestURI ( HttpServerExchange request ) { String uri = request . getRelativePath ( ) ; if ( uri == null || uri . equals ( \"/\" ) ) { uri = \"\" ; } return uri ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used by the iiop and iiopname URL Context factories . [CODESPLIT] public static ResolveResult createUsingURL ( String url , Hashtable env ) throws NamingException { CNCtx ctx = new CNCtx ( ) ; if ( env != null ) { env = ( Hashtable ) env . clone ( ) ; } ctx . _env = env ; String rest = ctx . initUsingUrl ( env != null ? ( org . omg . CORBA . ORB ) env . get ( \"java.naming.corba.orb\" ) : null , url , env ) ; // rest is the INS name // Return the parsed form to prevent subsequent lookup // from parsing the string as a composite name // The caller should be aware that a toString() of the name // will yield its INS syntax, rather than a composite syntax return new ResolveResult ( ctx , parser . parse ( rest ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the COS Naming Service . This method initializes the three instance fields : _nc : The root naming context . _orb : The ORB to use for connecting RMI / IIOP stubs and for getting the naming context ( _nc ) if one was not specified explicitly via PROVIDER_URL . _name : The name of the root naming context . <p / > _orb is obtained from java . naming . corba . orb if it has been set . Otherwise _orb is created using the host / port from PROVIDER_URL ( if it contains an iiop or iiopname URL ) or from initialization properties specified in env . <p / > _nc is obtained from the IOR stored in PROVIDER_URL if it has been set and does not contain an iiop or iiopname URL . It can be a stringified IOR corbaloc URL corbaname URL or a URL ( such as file / http / ftp ) to a location containing a stringified IOR . If PROVIDER_URL has not been set in this way it is obtained from the result of ORB . resolve_initial_reference ( NameService ) ; <p / > _name is obtained from the iiop iiopname or corbaname URL . It is the empty name by default . [CODESPLIT] private void initOrbAndRootContext ( Hashtable env ) throws NamingException { org . omg . CORBA . ORB inOrb = null ; String ncIor = null ; if ( env != null ) { inOrb = ( org . omg . CORBA . ORB ) env . get ( \"java.naming.corba.orb\" ) ; } // Extract PROVIDER_URL from environment String provUrl = null ; if ( env != null ) { provUrl = ( String ) env . get ( javax . naming . Context . PROVIDER_URL ) ; } if ( provUrl != null && ! isCorbaUrl ( provUrl ) ) { // Initialize the root naming context by using the IOR supplied // in the PROVIDER_URL ncIor = getStringifiedIor ( provUrl ) ; if ( inOrb == null ) { // no ORB instance specified; create one using env and defaults inOrb = CorbaORBService . getCurrent ( ) ; } setOrbAndRootContext ( inOrb , ncIor ) ; } else if ( provUrl != null ) { // Initialize the root naming context by using the URL supplied // in the PROVIDER_URL String insName = initUsingUrl ( inOrb , provUrl , env ) ; // If name supplied in URL, resolve it to a NamingContext if ( insName . length ( ) > 0 ) { _name = parser . nameToCosName ( parser . parse ( insName ) ) ; try { org . omg . CORBA . Object obj = _nc . resolve ( _name ) ; _nc = NamingContextHelper . narrow ( obj ) ; if ( _nc == null ) { throw IIOPLogger . ROOT_LOGGER . notANamingContext ( insName ) ; } } catch ( org . omg . CORBA . BAD_PARAM e ) { throw IIOPLogger . ROOT_LOGGER . notANamingContext ( insName ) ; } catch ( Exception e ) { throw org . wildfly . iiop . openjdk . naming . jndi . ExceptionMapper . mapException ( e , this , _name ) ; } } } else { // No PROVIDER_URL supplied; initialize using defaults if ( inOrb == null ) { // No ORB instance specified; create one using env and defaults inOrb = CorbaORBService . getCurrent ( ) ; IIOPLogger . ROOT_LOGGER . debugf ( \"Getting default ORB %s\" , inOrb ) ; } setOrbAndRootContext ( inOrb , ( String ) null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles iiop and iiopname URLs ( INS 98 - 10 - 11 ) [CODESPLIT] private String initUsingIiopUrl ( ORB defOrb , String url , Hashtable env ) throws NamingException { try { IiopUrl parsedUrl = new IiopUrl ( url ) ; Vector addrs = parsedUrl . getAddresses ( ) ; IiopUrl . Address addr ; NamingException savedException = null ; for ( int i = 0 ; i < addrs . size ( ) ; i ++ ) { addr = ( IiopUrl . Address ) addrs . elementAt ( i ) ; try { if ( defOrb != null ) { try { String tmpUrl = \"corbaloc:iiop:\" + addr . host + \":\" + addr . port + \"/NameService\" ; org . omg . CORBA . Object rootCtx = defOrb . string_to_object ( tmpUrl ) ; setOrbAndRootContext ( defOrb , rootCtx ) ; return parsedUrl . getStringName ( ) ; } catch ( Exception e ) { } // keep going } // Get ORB ORB orb = CorbaUtils . getOrb ( addr . host , addr . port , env ) ; // Assign to fields setOrbAndRootContext ( orb , ( String ) null ) ; return parsedUrl . getStringName ( ) ; } catch ( NamingException ne ) { savedException = ne ; } } if ( savedException != null ) { throw savedException ; } else { throw IIOPLogger . ROOT_LOGGER . invalidURLOrIOR ( url ) ; } } catch ( MalformedURLException e ) { throw new ConfigurationException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes using corbaname URL ( INS 99 - 12 - 03 ) [CODESPLIT] private String initUsingCorbanameUrl ( ORB orb , String url , Hashtable env ) throws NamingException { try { org . wildfly . iiop . openjdk . naming . jndi . CorbanameUrl parsedUrl = new org . wildfly . iiop . openjdk . naming . jndi . CorbanameUrl ( url ) ; String corbaloc = parsedUrl . getLocation ( ) ; String cosName = parsedUrl . getStringName ( ) ; if ( orb == null ) { // No ORB instance specified; create one using env and defaults orb = CorbaORBService . getCurrent ( ) ; } setOrbAndRootContext ( orb , corbaloc ) ; return parsedUrl . getStringName ( ) ; } catch ( MalformedURLException e ) { throw new ConfigurationException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the job of calling the COS Naming API resolve and performs the exception mapping . If the resolved object is a COS Naming Context ( sub - context ) then this function returns a new JNDI naming context object . [CODESPLIT] java . lang . Object callResolve ( NameComponent [ ] path ) throws NamingException { try { org . omg . CORBA . Object obj = _nc . resolve ( path ) ; try { NamingContext nc = NamingContextHelper . narrow ( obj ) ; if ( nc != null ) { return new CNCtx ( _orb , nc , _env , makeFullName ( path ) ) ; } else { return obj ; } } catch ( org . omg . CORBA . SystemException e ) { return obj ; } } catch ( Exception e ) { throw org . wildfly . iiop . openjdk . naming . jndi . ExceptionMapper . mapException ( e , this , path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the String name into a CompositeName returns the object resolved by the COS Naming api resolve . Returns the current context if the name is empty . Returns either an org . omg . CORBA . Object or javax . naming . Context object . [CODESPLIT] public java . lang . Object lookup ( String name ) throws NamingException { return lookup ( new CompositeName ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the Name name into a NameComponent [] object and returns the object resolved by the COS Naming api resolve . Returns the current context if the name is empty . Returns either an org . omg . CORBA . Object or javax . naming . Context object . [CODESPLIT] public java . lang . Object lookup ( Name name ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( name . toString ( ) ) ; if ( name . size ( ) == 0 ) return this ; // %%% should clone() so that env can be changed NameComponent [ ] path = org . wildfly . iiop . openjdk . naming . jndi . CNNameParser . nameToCosName ( name ) ; try { java . lang . Object answer = callResolve ( path ) ; try { return NamingManager . getObjectInstance ( answer , name , this , _env ) ; } catch ( NamingException e ) { throw e ; } catch ( Exception e ) { NamingException ne = IIOPLogger . ROOT_LOGGER . errorGeneratingObjectViaFactory ( ) ; ne . setRootCause ( e ) ; throw ne ; } } catch ( CannotProceedException cpe ) { javax . naming . Context cctx = getContinuationContext ( cpe ) ; return cctx . lookup ( cpe . getRemainingName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs bind or rebind in the context depending on whether the flag rebind is set . The only objects allowed to be bound are of types org . omg . CORBA . Object org . omg . CosNaming . NamingContext . You can use a state factory to turn other objects ( such as Remote ) into these acceptable forms . <p / > Uses the COS Naming apis bind / rebind or bind_context / rebind_context . [CODESPLIT] private void callBindOrRebind ( NameComponent [ ] pth , Name name , java . lang . Object obj , boolean rebind ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( name . toString ( ) ) ; try { // Call state factories to convert obj = NamingManager . getStateToBind ( obj , name , this , _env ) ; if ( obj instanceof CNCtx ) { // Use naming context object reference obj = ( ( CNCtx ) obj ) . _nc ; } if ( obj instanceof org . omg . CosNaming . NamingContext ) { NamingContext nobj = NamingContextHelper . narrow ( ( org . omg . CORBA . Object ) obj ) ; if ( rebind ) _nc . rebind_context ( pth , nobj ) ; else _nc . bind_context ( pth , nobj ) ; } else if ( obj instanceof org . omg . CORBA . Object ) { if ( rebind ) _nc . rebind ( pth , ( org . omg . CORBA . Object ) obj ) ; else _nc . bind ( pth , ( org . omg . CORBA . Object ) obj ) ; } else throw IIOPLogger . ROOT_LOGGER . notACorbaObject ( ) ; } catch ( BAD_PARAM e ) { // probably narrow() failed? NamingException ne = new NotContextException ( name . toString ( ) ) ; ne . setRootCause ( e ) ; throw ne ; } catch ( Exception e ) { throw org . wildfly . iiop . openjdk . naming . jndi . ExceptionMapper . mapException ( e , this , pth ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the Name name into a NameComponent [] object and performs the bind operation . Uses callBindOrRebind . Throws an invalid name exception if the name is empty . We need a name to bind the object even when we work within the current context . [CODESPLIT] public void bind ( Name name , java . lang . Object obj ) throws NamingException { if ( name . size ( ) == 0 ) { throw IIOPLogger . ROOT_LOGGER . invalidEmptyName ( ) ; } NameComponent [ ] path = org . wildfly . iiop . openjdk . naming . jndi . CNNameParser . nameToCosName ( name ) ; try { callBindOrRebind ( path , name , obj , false ) ; } catch ( CannotProceedException e ) { javax . naming . Context cctx = getContinuationContext ( e ) ; cctx . bind ( e . getRemainingName ( ) , obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the String name into a CompositeName object and performs the bind operation . Uses callBindOrRebind . Throws an invalid name exception if the name is empty . [CODESPLIT] public void bind ( String name , java . lang . Object obj ) throws NamingException { bind ( new CompositeName ( name ) , obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the unbind api of COS Naming and uses the exception mapper class to map the exceptions [CODESPLIT] private void callUnbind ( NameComponent [ ] path ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( path . toString ( ) ) ; try { _nc . unbind ( path ) ; } catch ( NotFound e ) { // If leaf is the one missing, return success // as per JNDI spec if ( leafNotFound ( e , path [ path . length - 1 ] ) ) { // do nothing } else { throw org . wildfly . iiop . openjdk . naming . jndi . ExceptionMapper . mapException ( e , this , path ) ; } } catch ( Exception e ) { throw org . wildfly . iiop . openjdk . naming . jndi . ExceptionMapper . mapException ( e , this , path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the Name name into a NameComponent [] object and performs the unbind operation . Uses callUnbind . Throws an invalid name exception if the name is empty . [CODESPLIT] public void unbind ( Name name ) throws NamingException { if ( name . size ( ) == 0 ) throw IIOPLogger . ROOT_LOGGER . invalidEmptyName ( ) ; NameComponent [ ] path = org . wildfly . iiop . openjdk . naming . jndi . CNNameParser . nameToCosName ( name ) ; try { callUnbind ( path ) ; } catch ( CannotProceedException e ) { javax . naming . Context cctx = getContinuationContext ( e ) ; cctx . unbind ( e . getRemainingName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renames an object . Since COS Naming does not support a rename api this method unbinds the object with the oldName and creates a new binding . [CODESPLIT] public void rename ( String oldName , String newName ) throws NamingException { rename ( new CompositeName ( oldName ) , new CompositeName ( newName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renames an object . Since COS Naming does not support a rename api this method unbinds the object with the oldName and creates a new binding . [CODESPLIT] public void rename ( Name oldName , Name newName ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( oldName . toString ( ) ) ; if ( oldName . size ( ) == 0 || newName . size ( ) == 0 ) throw IIOPLogger . ROOT_LOGGER . invalidEmptyName ( ) ; java . lang . Object obj = lookup ( oldName ) ; bind ( newName , obj ) ; unbind ( oldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a BindingEnumeration object which has a list of name class pairs . Lists the current context if the name is empty . [CODESPLIT] public NamingEnumeration listBindings ( Name name ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( name . toString ( ) ) ; if ( name . size ( ) > 0 ) { try { java . lang . Object obj = lookup ( name ) ; if ( obj instanceof CNCtx ) { return new org . wildfly . iiop . openjdk . naming . jndi . CNBindingEnumeration ( ( CNCtx ) obj , true , _env ) ; } else { throw new NotContextException ( name . toString ( ) ) ; } } catch ( NamingException ne ) { throw ne ; } catch ( BAD_PARAM e ) { NamingException ne = new NotContextException ( name . toString ( ) ) ; ne . setRootCause ( e ) ; throw ne ; } } return new org . wildfly . iiop . openjdk . naming . jndi . CNBindingEnumeration ( this , false , _env ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the destroy on the COS Naming Server [CODESPLIT] private void callDestroy ( NamingContext nc ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( nc . toString ( ) ) ; try { nc . destroy ( ) ; } catch ( Exception e ) { throw org . wildfly . iiop . openjdk . naming . jndi . ExceptionMapper . mapException ( e , this , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the callDestroy function to destroy the context . Destroys the current context if name is empty . [CODESPLIT] public void destroySubcontext ( Name name ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( name . toString ( ) ) ; NamingContext the_nc = _nc ; NameComponent [ ] path = org . wildfly . iiop . openjdk . naming . jndi . CNNameParser . nameToCosName ( name ) ; if ( name . size ( ) > 0 ) { try { javax . naming . Context ctx = ( javax . naming . Context ) callResolve ( path ) ; CNCtx cnc = ( CNCtx ) ctx ; the_nc = cnc . _nc ; cnc . close ( ) ; //remove the reference to the context } catch ( ClassCastException e ) { throw new NotContextException ( name . toString ( ) ) ; } catch ( CannotProceedException e ) { javax . naming . Context cctx = getContinuationContext ( e ) ; cctx . destroySubcontext ( e . getRemainingName ( ) ) ; return ; } catch ( NameNotFoundException e ) { // If leaf is the one missing, return success // as per JNDI spec if ( e . getRootCause ( ) instanceof NotFound && leafNotFound ( ( NotFound ) e . getRootCause ( ) , path [ path . length - 1 ] ) ) { return ; // leaf missing OK } throw e ; } catch ( NamingException e ) { throw e ; } } callDestroy ( the_nc ) ; callUnbind ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the bind_new_context COS naming api to create a new subcontext . [CODESPLIT] private javax . naming . Context callBindNewContext ( NameComponent [ ] path ) throws NamingException { if ( _nc == null ) throw IIOPLogger . ROOT_LOGGER . notANamingContext ( path . toString ( ) ) ; try { NamingContext nctx = _nc . bind_new_context ( path ) ; return new CNCtx ( _orb , nctx , _env , makeFullName ( path ) ) ; } catch ( Exception e ) { throw org . wildfly . iiop . openjdk . naming . jndi . ExceptionMapper . mapException ( e , this , path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the callBindNewContext convenience function to create a new context . Throws an invalid name exception if the name is empty . [CODESPLIT] public javax . naming . Context createSubcontext ( String name ) throws NamingException { return createSubcontext ( new CompositeName ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is mapped to resolve in the COS Naming api . [CODESPLIT] public java . lang . Object lookupLink ( String name ) throws NamingException { return lookupLink ( new CompositeName ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds to the environment for the current context . Record change but do not reinitialize ORB . [CODESPLIT] public java . lang . Object addToEnvironment ( String propName , java . lang . Object propValue ) throws NamingException { if ( _env == null ) { _env = new Hashtable ( 7 , 0.75f ) ; } else { // copy-on-write _env = ( Hashtable ) _env . clone ( ) ; } return _env . put ( propName , propValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Record change but do not reinitialize ORB [CODESPLIT] public java . lang . Object removeFromEnvironment ( String propName ) throws NamingException { if ( _env != null && _env . get ( propName ) != null ) { // copy-on-write _env = ( Hashtable ) _env . clone ( ) ; return _env . remove ( propName ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds transformations common to both stack protocols and transport . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) static void addTransformations ( ModelVersion version , ResourceTransformationDescriptionBuilder builder ) { if ( JGroupsModel . VERSION_5_0_0 . requiresTransformation ( version ) ) { builder . getAttributeBuilder ( ) . setDiscard ( DiscardAttributeChecker . UNDEFINED , Attribute . STATISTICS_ENABLED . getDefinition ( ) ) . addRejectCheck ( RejectAttributeChecker . DEFINED , Attribute . STATISTICS_ENABLED . getDefinition ( ) ) . end ( ) ; } if ( JGroupsModel . VERSION_3_0_0 . requiresTransformation ( version ) ) { AttributeConverter typeConverter = new AttributeConverter . DefaultAttributeConverter ( ) { @ Override protected void convertAttribute ( PathAddress address , String name , ModelNode value , TransformationContext context ) { if ( ! value . isDefined ( ) ) { value . set ( address . getLastElement ( ) . getValue ( ) ) ; } } } ; builder . getAttributeBuilder ( ) . setDiscard ( new DiscardAttributeChecker . DiscardAttributeValueChecker ( Attribute . MODULE . getDefinition ( ) . getDefaultValue ( ) ) , Attribute . MODULE . getDefinition ( ) ) . addRejectCheck ( RejectAttributeChecker . DEFINED , Attribute . MODULE . getDefinition ( ) ) . setValueConverter ( typeConverter , DeprecatedAttribute . TYPE . getDefinition ( ) ) . end ( ) ; builder . addRawOperationTransformationOverride ( MapOperations . MAP_GET_DEFINITION . getName ( ) , new SimpleOperationTransformer ( new LegacyPropertyMapGetOperationTransformer ( ) ) ) ; for ( String opName : Operations . getAllWriteAttributeOperationNames ( ) ) { builder . addOperationTransformationOverride ( opName ) . inheritResourceAttributeDefinitions ( ) . setCustomOperationTransformer ( new LegacyPropertyWriteOperationTransformer ( ) ) ; } } PropertyResourceDefinition . buildTransformation ( version , builder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse security [CODESPLIT] @ Override protected DsSecurity parseDsSecurity ( XMLStreamReader reader ) throws XMLStreamException , ParserException , ValidateException { String userName = null ; String password = null ; String securityDomain = null ; boolean elytronEnabled = false ; String authenticationContext = null ; Extension reauthPlugin = null ; while ( reader . hasNext ( ) ) { switch ( reader . nextTag ( ) ) { case END_ELEMENT : { if ( DataSource . Tag . forName ( reader . getLocalName ( ) ) == DataSource . Tag . SECURITY ) { return new DsSecurityImpl ( userName , password , elytronEnabled ? authenticationContext : securityDomain , elytronEnabled , null , reauthPlugin ) ; } else { if ( DsSecurity . Tag . forName ( reader . getLocalName ( ) ) == DsSecurity . Tag . UNKNOWN ) { throw new ParserException ( bundle . unexpectedEndTag ( reader . getLocalName ( ) ) ) ; } } break ; } case START_ELEMENT : { DsSecurity . Tag tag = DsSecurity . Tag . forName ( reader . getLocalName ( ) ) ; switch ( tag ) { case PASSWORD : { password = elementAsString ( reader ) ; boolean resolved = false ; if ( propertyReplacer != null && password != null && password . trim ( ) . length ( ) != 0 ) { String resolvedPassword = propertyReplacer . replaceProperties ( password ) ; if ( resolvedPassword != null ) { password = resolvedPassword ; resolved = true ; } } // Previous releases directly passed the text into PropertyResolver, which would not // deal properly with ${ and }, :defaultValue etc. But it would resolve e.g. \"sys.prop.foo\" // to \"123\" if there was a system property \"sys.prop.foo\". So, to avoid breaking folks // who learned to use that behavior, pass any unresolved password in to the PropertyResolver if ( ! resolved && propertyResolver != null && password != null && password . trim ( ) . length ( ) != 0 ) { String resolvedPassword = propertyResolver . resolve ( password ) ; if ( resolvedPassword != null ) { password = resolvedPassword ; } } break ; } case USER_NAME : { userName = elementAsString ( reader ) ; break ; } case SECURITY_DOMAIN : { securityDomain = elementAsString ( reader ) ; break ; } case ELYTRON_ENABLED : { Boolean value = elementAsBoolean ( reader ) ; elytronEnabled = value == null ? true : value ; break ; } case AUTHENTICATION_CONTEXT : { authenticationContext = elementAsString ( reader ) ; break ; } case REAUTH_PLUGIN : { reauthPlugin = parseExtension ( reader , tag . getLocalName ( ) ) ; break ; } default : throw new ParserException ( bundle . unexpectedElement ( reader . getLocalName ( ) ) ) ; } break ; } } } throw new ParserException ( bundle . unexpectedEndOfDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse credential tag [CODESPLIT] @ Override protected Credential parseCredential ( XMLStreamReader reader ) throws XMLStreamException , ParserException , ValidateException { String userName = null ; String password = null ; String securityDomain = null ; boolean elytronEnabled = false ; String authenticationContext = null ; while ( reader . hasNext ( ) ) { switch ( reader . nextTag ( ) ) { case END_ELEMENT : { if ( DataSource . Tag . forName ( reader . getLocalName ( ) ) == DataSource . Tag . SECURITY || Recovery . Tag . forName ( reader . getLocalName ( ) ) == Recovery . Tag . RECOVER_CREDENTIAL ) { return new CredentialImpl ( userName , password , elytronEnabled ? authenticationContext : securityDomain , elytronEnabled , null ) ; } else { if ( Credential . Tag . forName ( reader . getLocalName ( ) ) == Credential . Tag . UNKNOWN ) { throw new ParserException ( bundle . unexpectedEndTag ( reader . getLocalName ( ) ) ) ; } } break ; } case START_ELEMENT : { switch ( Credential . Tag . forName ( reader . getLocalName ( ) ) ) { case PASSWORD : { password = elementAsString ( reader ) ; if ( propertyResolver != null && password != null ) { String resolvedPassword = propertyResolver . resolve ( password ) ; if ( resolvedPassword != null ) password = resolvedPassword ; } break ; } case USER_NAME : { userName = elementAsString ( reader ) ; break ; } case SECURITY_DOMAIN : { securityDomain = elementAsString ( reader ) ; break ; } case ELYTRON_ENABLED : { Boolean value = elementAsBoolean ( reader ) ; elytronEnabled = value == null ? true : value ; break ; } case AUTHENTICATION_CONTEXT : { authenticationContext = elementAsString ( reader ) ; break ; } default : throw new ParserException ( bundle . unexpectedElement ( reader . getLocalName ( ) ) ) ; } break ; } } } throw new ParserException ( bundle . unexpectedEndOfDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeContent ( final XMLExtendedStreamWriter writer , final SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( EJB3SubsystemNamespace . EJB3_5_0 . getUriString ( ) , false ) ; writeElements ( writer , context ) ; // write the subsystem end element writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes out the <mdb > element and its nested elements [CODESPLIT] private void writeMDB ( final XMLExtendedStreamWriter writer , final ModelNode mdbModelNode ) throws XMLStreamException { if ( mdbModelNode . hasDefined ( EJB3SubsystemModel . DEFAULT_RESOURCE_ADAPTER_NAME ) ) { // <resource-adapter-ref> writer . writeStartElement ( EJB3SubsystemXMLElement . RESOURCE_ADAPTER_REF . getLocalName ( ) ) ; final String resourceAdapterName = mdbModelNode . get ( EJB3SubsystemModel . DEFAULT_RESOURCE_ADAPTER_NAME ) . asString ( ) ; // write the value writer . writeAttribute ( EJB3SubsystemXMLAttribute . RESOURCE_ADAPTER_NAME . getLocalName ( ) , resourceAdapterName ) ; // </resource-adapter-ref> writer . writeEndElement ( ) ; } if ( mdbModelNode . hasDefined ( EJB3SubsystemModel . DEFAULT_MDB_INSTANCE_POOL ) ) { // <bean-instance-pool-ref> writer . writeStartElement ( EJB3SubsystemXMLElement . BEAN_INSTANCE_POOL_REF . getLocalName ( ) ) ; final String poolRefName = mdbModelNode . get ( EJB3SubsystemModel . DEFAULT_MDB_INSTANCE_POOL ) . asString ( ) ; // write the value writer . writeAttribute ( EJB3SubsystemXMLAttribute . POOL_NAME . getLocalName ( ) , poolRefName ) ; // </bean-instance-pool-ref> writer . writeEndElement ( ) ; } if ( mdbModelNode . hasDefined ( EJB3SubsystemModel . MDB_DELIVERY_GROUP ) ) { //<delivery-groups> writer . writeStartElement ( EJB3SubsystemXMLElement . DELIVERY_GROUPS . getLocalName ( ) ) ; for ( Property property : mdbModelNode . get ( EJB3SubsystemModel . MDB_DELIVERY_GROUP ) . asPropertyList ( ) ) { // <delivery-group writer . writeStartElement ( EJB3SubsystemXMLElement . DELIVERY_GROUP . getLocalName ( ) ) ; // name= writer . writeAttribute ( EJB3SubsystemXMLAttribute . NAME . getLocalName ( ) , property . getName ( ) ) ; // active= MdbDeliveryGroupResourceDefinition . ACTIVE . marshallAsAttribute ( mdbModelNode . get ( EJB3SubsystemModel . MDB_DELIVERY_GROUP , property . getName ( ) ) , writer ) ; // /> writer . writeEndElement ( ) ; } //</delivery-groups> writer . writeEndElement ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes out the <entity - bean > element and its nested elements [CODESPLIT] private void writeEntityBean ( final XMLExtendedStreamWriter writer , final ModelNode entityModelNode ) throws XMLStreamException { if ( entityModelNode . hasDefined ( EJB3SubsystemModel . DEFAULT_ENTITY_BEAN_INSTANCE_POOL ) ) { // <bean-instance-pool-ref> writer . writeStartElement ( EJB3SubsystemXMLElement . BEAN_INSTANCE_POOL_REF . getLocalName ( ) ) ; final String poolRefName = entityModelNode . get ( EJB3SubsystemModel . DEFAULT_ENTITY_BEAN_INSTANCE_POOL ) . asString ( ) ; // write the value writer . writeAttribute ( EJB3SubsystemXMLAttribute . POOL_NAME . getLocalName ( ) , poolRefName ) ; // </bean-instance-pool-ref> writer . writeEndElement ( ) ; } if ( entityModelNode . hasDefined ( EJB3SubsystemModel . DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING ) ) { // <optimistic-locking> writer . writeStartElement ( EJB3SubsystemXMLElement . OPTIMISTIC_LOCKING . getLocalName ( ) ) ; final Boolean locking = entityModelNode . get ( EJB3SubsystemModel . DEFAULT_ENTITY_BEAN_OPTIMISTIC_LOCKING ) . asBoolean ( ) ; // write the value writer . writeAttribute ( EJB3SubsystemXMLAttribute . ENABLED . getLocalName ( ) , locking . toString ( ) ) ; // <optimistic-locking> writer . writeEndElement ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persist as a passivation - store using relevant attributes [CODESPLIT] private void writeClusterPassivationStores ( XMLExtendedStreamWriter writer , ModelNode model ) throws XMLStreamException { if ( model . hasDefined ( EJB3SubsystemModel . CLUSTER_PASSIVATION_STORE ) ) { List < Property > caches = model . get ( EJB3SubsystemModel . CLUSTER_PASSIVATION_STORE ) . asPropertyList ( ) ; for ( Property property : caches ) { // <strict-max-pool> writer . writeStartElement ( EJB3SubsystemXMLElement . CLUSTER_PASSIVATION_STORE . getLocalName ( ) ) ; ModelNode store = property . getValue ( ) ; writer . writeAttribute ( EJB3SubsystemXMLAttribute . NAME . getLocalName ( ) , property . getName ( ) ) ; LegacyPassivationStoreResourceDefinition . IDLE_TIMEOUT . marshallAsAttribute ( store , writer ) ; LegacyPassivationStoreResourceDefinition . IDLE_TIMEOUT_UNIT . marshallAsAttribute ( store , writer ) ; ClusterPassivationStoreResourceDefinition . MAX_SIZE . marshallAsAttribute ( store , writer ) ; ClusterPassivationStoreResourceDefinition . CACHE_CONTAINER . marshallAsAttribute ( store , writer ) ; ClusterPassivationStoreResourceDefinition . BEAN_CACHE . marshallAsAttribute ( store , writer ) ; ClusterPassivationStoreResourceDefinition . CLIENT_MAPPINGS_CACHE . marshallAsAttribute ( store , writer ) ; ClusterPassivationStoreResourceDefinition . PASSIVATE_EVENTS_ON_REPLICATE . marshallAsAttribute ( store , writer ) ; writer . writeEndElement ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persist as a passivation - store using relevant attributes [CODESPLIT] private void writeFilePassivationStores ( XMLExtendedStreamWriter writer , ModelNode model ) throws XMLStreamException { if ( model . hasDefined ( EJB3SubsystemModel . FILE_PASSIVATION_STORE ) ) { List < Property > caches = model . get ( EJB3SubsystemModel . FILE_PASSIVATION_STORE ) . asPropertyList ( ) ; for ( Property property : caches ) { // <strict-max-pool> writer . writeStartElement ( EJB3SubsystemXMLElement . FILE_PASSIVATION_STORE . getLocalName ( ) ) ; ModelNode store = property . getValue ( ) ; writer . writeAttribute ( EJB3SubsystemXMLAttribute . NAME . getLocalName ( ) , property . getName ( ) ) ; LegacyPassivationStoreResourceDefinition . IDLE_TIMEOUT . marshallAsAttribute ( store , writer ) ; LegacyPassivationStoreResourceDefinition . IDLE_TIMEOUT_UNIT . marshallAsAttribute ( store , writer ) ; FilePassivationStoreResourceDefinition . MAX_SIZE . marshallAsAttribute ( store , writer ) ; FilePassivationStoreResourceDefinition . RELATIVE_TO . marshallAsAttribute ( store , writer ) ; FilePassivationStoreResourceDefinition . GROUPS_PATH . marshallAsAttribute ( store , writer ) ; FilePassivationStoreResourceDefinition . SESSIONS_PATH . marshallAsAttribute ( store , writer ) ; FilePassivationStoreResourceDefinition . SUBDIRECTORY_COUNT . marshallAsAttribute ( store , writer ) ; writer . writeEndElement ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public AuditManager getAuditManager ( String securityDomain ) { AuditManager am = null ; try { am = auditMgrMap . get ( securityDomain ) ; if ( am == null ) { am = ( AuditManager ) lookUpJNDI ( securityDomain + \"/auditMgr\" ) ; auditMgrMap . put ( securityDomain , am ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( e , \"Exception getting AuditManager for domain=%s\" , securityDomain ) ; } return am ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public AuthenticationManager getAuthenticationManager ( String securityDomain ) { AuthenticationManager am = null ; try { am = authMgrMap . get ( securityDomain ) ; if ( am == null ) { am = ( AuthenticationManager ) lookUpJNDI ( securityDomain + \"/authenticationMgr\" ) ; authMgrMap . put ( securityDomain , am ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( e , \"Exception getting AuthenticationManager for domain=%s\" , securityDomain ) ; } return am ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public AuthorizationManager getAuthorizationManager ( String securityDomain ) { AuthorizationManager am = null ; try { am = authzMgrMap . get ( securityDomain ) ; if ( am == null ) { am = ( AuthorizationManager ) lookUpJNDI ( securityDomain + \"/authorizationMgr\" ) ; authzMgrMap . put ( securityDomain , am ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( e , \"Exception getting AuthorizationManager for domain=%s\" , securityDomain ) ; } return am ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public IdentityTrustManager getIdentityTrustManager ( String securityDomain ) { IdentityTrustManager itm = null ; try { itm = idmMgrMap . get ( securityDomain ) ; if ( itm == null ) { itm = ( IdentityTrustManager ) lookUpJNDI ( securityDomain + \"/identityTrustMgr\" ) ; idmMgrMap . put ( securityDomain , itm ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( e , \"Exception getting IdentityTrustManager for domain=%s\" + securityDomain ) ; } return itm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public MappingManager getMappingManager ( String securityDomain ) { MappingManager mm = null ; try { mm = mappingMgrMap . get ( securityDomain ) ; if ( mm == null ) { mm = ( MappingManager ) lookUpJNDI ( securityDomain + \"/mappingMgr\" ) ; mappingMgrMap . put ( securityDomain , mm ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( e , \"Exception getting MappingManager for domain=%s\" , securityDomain ) ; } return mm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public JSSESecurityDomain getJSSE ( String securityDomain ) { JSSESecurityDomain jsse = null ; try { jsse = jsseMap . get ( securityDomain ) ; if ( jsse == null ) { jsse = ( JSSESecurityDomain ) lookUpJNDI ( securityDomain + \"/jsse\" ) ; jsseMap . put ( securityDomain , jsse ) ; } } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( e , \"Exception getting JSSESecurityDomain for domain=%s\" , securityDomain ) ; } return jsse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes one security domain from the maps [CODESPLIT] public void removeSecurityDomain ( String securityDomain ) { securityMgrMap . remove ( securityDomain ) ; auditMgrMap . remove ( securityDomain ) ; authMgrMap . remove ( securityDomain ) ; authzMgrMap . remove ( securityDomain ) ; idmMgrMap . remove ( securityDomain ) ; mappingMgrMap . remove ( securityDomain ) ; jsseMap . remove ( securityDomain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup a context in JNDI [CODESPLIT] private Object lookUpJNDI ( String contextName ) { Object result = null ; try { Context ctx = new InitialContext ( ) ; if ( contextName . startsWith ( SecurityConstants . JAAS_CONTEXT_ROOT ) ) result = ctx . lookup ( contextName ) ; else result = ctx . lookup ( SecurityConstants . JAAS_CONTEXT_ROOT + contextName ) ; } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( \"Look up of JNDI for %s failed with %s\" , contextName , e . getLocalizedMessage ( ) ) ; return null ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @code SecurityDomainContext } [CODESPLIT] public SecurityDomainContext createSecurityDomainContext ( String securityDomain , AuthenticationCacheFactory cacheFactory ) throws Exception { return createSecurityDomainContext ( securityDomain , cacheFactory , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @code SecurityDomainContext } optionally including a { @link JSSESecurityDomain } [CODESPLIT] public SecurityDomainContext createSecurityDomainContext ( String securityDomain , AuthenticationCacheFactory cacheFactory , JSSESecurityDomain jsseSecurityDomain ) throws Exception { SecurityLogger . ROOT_LOGGER . debugf ( \"Creating SDC for domain = %s\" , securityDomain ) ; AuthenticationManager am = createAuthenticationManager ( securityDomain ) ; if ( cacheFactory != null && am instanceof CacheableManager ) { // create authentication cache final Map < Principal , ? > cache = cacheFactory . getCache ( ) ; if ( cache != null ) { @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) CacheableManager < Map , Principal > cm = ( CacheableManager < Map , Principal > ) am ; cm . setCache ( cache ) ; } } // set DeepCopySubject option if supported if ( deepCopySubjectMode ) { setDeepCopySubjectMode ( am ) ; } return new SecurityDomainContext ( am , createAuthorizationManager ( securityDomain ) , createAuditManager ( securityDomain ) , createIdentityTrustManager ( securityDomain ) , createMappingManager ( securityDomain ) , jsseSecurityDomain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an { @code AuthenticationManager } [CODESPLIT] private AuthenticationManager createAuthenticationManager ( String securityDomain ) throws Exception { int i = callbackHandlerClassName . lastIndexOf ( \":\" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( \"default-callback-handler-class-name attribute\" ) ; String moduleSpec = callbackHandlerClassName . substring ( 0 , i ) ; String className = callbackHandlerClassName . substring ( i + 1 ) ; Class < ? > callbackHandlerClazz = SecurityActions . getModuleClassLoader ( loader , moduleSpec ) . loadClass ( className ) ; CallbackHandler ch = ( CallbackHandler ) callbackHandlerClazz . newInstance ( ) ; i = authenticationManagerClassName . lastIndexOf ( \":\" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( \"authentication-manager-class-name attribute\" ) ; moduleSpec = authenticationManagerClassName . substring ( 0 , i ) ; className = authenticationManagerClassName . substring ( i + 1 ) ; Class < ? > clazz = SecurityActions . getModuleClassLoader ( loader , moduleSpec ) . loadClass ( className ) ; Constructor < ? > ctr = clazz . getConstructor ( new Class [ ] { String . class , CallbackHandler . class } ) ; return ( AuthenticationManager ) ctr . newInstance ( new Object [ ] { securityDomain , ch } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an { @code AuthorizationManager } [CODESPLIT] private AuthorizationManager createAuthorizationManager ( String securityDomain ) throws Exception { int i = authorizationManagerClassName . lastIndexOf ( \":\" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( \"authorization manager class\" ) ; String moduleSpec = authorizationManagerClassName . substring ( 0 , i ) ; String className = authorizationManagerClassName . substring ( i + 1 ) ; Class < ? > clazz = SecurityActions . getModuleClassLoader ( loader , moduleSpec ) . loadClass ( className ) ; Constructor < ? > ctr = clazz . getConstructor ( new Class [ ] { String . class } ) ; return ( AuthorizationManager ) ctr . newInstance ( new Object [ ] { securityDomain } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an { @code AuditManager } [CODESPLIT] private AuditManager createAuditManager ( String securityDomain ) throws Exception { int i = auditManagerClassName . lastIndexOf ( \":\" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( \"audit manager class\" ) ; String moduleSpec = auditManagerClassName . substring ( 0 , i ) ; String className = auditManagerClassName . substring ( i + 1 ) ; Class < ? > clazz = SecurityActions . getModuleClassLoader ( loader , moduleSpec ) . loadClass ( className ) ; Constructor < ? > ctr = clazz . getConstructor ( new Class [ ] { String . class } ) ; return ( AuditManager ) ctr . newInstance ( new Object [ ] { securityDomain } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an { @code IdentityTrustManager } [CODESPLIT] private IdentityTrustManager createIdentityTrustManager ( String securityDomain ) throws Exception { int i = identityTrustManagerClassName . lastIndexOf ( \":\" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( \"identity trust manager class\" ) ; String moduleSpec = identityTrustManagerClassName . substring ( 0 , i ) ; String className = identityTrustManagerClassName . substring ( i + 1 ) ; Class < ? > clazz = SecurityActions . getModuleClassLoader ( loader , moduleSpec ) . loadClass ( className ) ; Constructor < ? > ctr = clazz . getConstructor ( new Class [ ] { String . class } ) ; return ( IdentityTrustManager ) ctr . newInstance ( new Object [ ] { securityDomain } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an { @code MappingManager } [CODESPLIT] private MappingManager createMappingManager ( String securityDomain ) throws Exception { int i = mappingManagerClassName . lastIndexOf ( \":\" ) ; if ( i == - 1 ) throw SecurityLogger . ROOT_LOGGER . missingModuleName ( \"mapping manager class\" ) ; String moduleSpec = mappingManagerClassName . substring ( 0 , i ) ; String className = mappingManagerClassName . substring ( i + 1 ) ; Class < ? > clazz = SecurityActions . getModuleClassLoader ( loader , moduleSpec ) . loadClass ( className ) ; Constructor < ? > ctr = clazz . getConstructor ( new Class [ ] { String . class } ) ; return ( MappingManager ) ctr . newInstance ( new Object [ ] { securityDomain } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use reflection to attempt to set the deep copy subject mode on the { @code AuthenticationManager } [CODESPLIT] private static void setDeepCopySubjectMode ( AuthenticationManager authenticationManager ) { try { Class < ? > [ ] argsType = { Boolean . class } ; Method m = authenticationManager . getClass ( ) . getMethod ( \"setDeepCopySubjectOption\" , argsType ) ; Object [ ] deepCopyArgs = { Boolean . TRUE } ; m . invoke ( authenticationManager , deepCopyArgs ) ; } catch ( Exception e ) { SecurityLogger . ROOT_LOGGER . tracef ( \"Optional setDeepCopySubjectMode failed: %s\" , e . getLocalizedMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the corresponding { @link org . jboss . as . ejb3 . timerservice . schedule . value . ScheduleExpressionType } for the passed value [CODESPLIT] public static ScheduleExpressionType getType ( String value ) { if ( value == null ) { throw EjbLogger . EJB3_TIMER_LOGGER . valueIsNull ( ) ; } // Order of check is important. // TODO: Explain why this order is important if ( value . trim ( ) . equals ( \"*\" ) ) { return ScheduleExpressionType . WILDCARD ; } if ( value . contains ( \",\" ) ) { return ScheduleExpressionType . LIST ; } if ( value . contains ( \"-\" ) && RangeValue . accepts ( value ) ) { return ScheduleExpressionType . RANGE ; } if ( value . contains ( \"/\" ) ) { return ScheduleExpressionType . INCREMENT ; } return ScheduleExpressionType . SINGLE_VALUE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ModuleReference from a target type and factory class . [CODESPLIT] public static ModularReference create ( final Class < ? > type , final Class < ? > factoryClass ) { return create ( type . getName ( ) , factoryClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ModuleReference from a target class name and factory class . [CODESPLIT] public static ModularReference create ( final String className , final Class < ? > factoryClass ) { return new ModularReference ( className , factoryClass . getName ( ) , Module . forClass ( factoryClass ) . getIdentifier ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ModuleReference from a target type reference address and factory class . [CODESPLIT] public static ModularReference create ( final Class < ? > type , final RefAddr addr , final Class < ? > factoryClass ) { return create ( type . getName ( ) , addr , factoryClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void start ( final StartContext context ) { super . start ( context ) ; if ( SarLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { SarLogger . ROOT_LOGGER . tracef ( \"Starting Service: %s\" , context . getController ( ) . getName ( ) ) ; } final Runnable task = new Runnable ( ) { @ Override public void run ( ) { try { invokeLifecycleMethod ( startMethod , context ) ; context . complete ( ) ; } catch ( Throwable e ) { context . failed ( new StartException ( SarLogger . ROOT_LOGGER . failedExecutingLegacyMethod ( \"start()\" ) , e ) ) ; } } } ; try { executorSupplier . get ( ) . submit ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void stop ( final StopContext context ) { super . stop ( context ) ; if ( SarLogger . ROOT_LOGGER . isTraceEnabled ( ) ) { SarLogger . ROOT_LOGGER . tracef ( \"Stopping Service: %s\" , context . getController ( ) . getName ( ) ) ; } final Runnable task = new Runnable ( ) { @ Override public void run ( ) { try { invokeLifecycleMethod ( stopMethod , context ) ; } catch ( Exception e ) { SarLogger . ROOT_LOGGER . error ( SarLogger . ROOT_LOGGER . failedExecutingLegacyMethod ( \"stop()\" ) , e ) ; } finally { context . complete ( ) ; } } } ; try { executorSupplier . get ( ) . submit ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a JBoss Diagnostic Reporter ( JDR ) Report . A JDR report response is printed to <code > System . out< / code > . [CODESPLIT] public static void main ( String [ ] args ) { int port = 9990 ; String host = \"localhost\" ; String protocol = \"remote+http\" ; String config = null ; try { CommandLine line = parser . parse ( options , args , false ) ; if ( line . hasOption ( \"help\" ) ) { formatter . printHelp ( usage , NEW_LINE + JdrLogger . ROOT_LOGGER . jdrDescriptionMessage ( ) , options , null ) ; return ; } if ( line . hasOption ( \"host\" ) ) { host = line . getOptionValue ( \"host\" ) ; } if ( line . hasOption ( \"port\" ) ) { port = Integer . parseInt ( line . getOptionValue ( \"port\" ) ) ; } if ( line . hasOption ( \"protocol\" ) ) { protocol = line . getOptionValue ( \"protocol\" ) ; } if ( line . hasOption ( \"config\" ) ) { config = line . getOptionValue ( \"config\" ) ; } } catch ( ParseException e ) { System . out . println ( e . getMessage ( ) ) ; formatter . printHelp ( usage , options ) ; return ; } catch ( NumberFormatException nfe ) { System . out . println ( nfe . getMessage ( ) ) ; formatter . printHelp ( usage , options ) ; return ; } System . out . println ( \"Initializing JBoss Diagnostic Reporter...\" ) ; // Try to run JDR on the Wildfly JVM CLI cli = CLI . newInstance ( ) ; boolean embedded = false ; JdrReport report = null ; try { System . out . println ( String . format ( \"Trying to connect to %s %s:%s\" , protocol , host , port ) ) ; cli . connect ( protocol , host , port , null , null ) ; } catch ( IllegalStateException ex ) { System . out . println ( \"Starting embedded server\" ) ; String startEmbeddedServer = \"embed-server --std-out=echo \" + ( ( config != null && ! config . isEmpty ( ) ) ? ( \" --server-config=\" + config ) : \"\" ) ; cli . getCommandContext ( ) . handleSafe ( startEmbeddedServer ) ; embedded = true ; } try { Result cmdResult = cli . cmd ( \"/subsystem=jdr:generate-jdr-report()\" ) ; ModelNode response = cmdResult . getResponse ( ) ; if ( Operations . isSuccessfulOutcome ( response ) || ! embedded ) { reportFailure ( response ) ; ModelNode result = response . get ( ClientConstants . RESULT ) ; report = new JdrReport ( result ) ; } else { report = standaloneCollect ( cli , protocol , host , port ) ; } } catch ( IllegalStateException ise ) { System . out . println ( ise . getMessage ( ) ) ; report = standaloneCollect ( cli , protocol , host , port ) ; } finally { if ( cli != null ) { try { if ( embedded ) cli . getCommandContext ( ) . handleSafe ( \"stop-embedded-server\" ) ; else cli . disconnect ( ) ; } catch ( Exception e ) { System . out . println ( \"Caught exception while disconnecting: \" + e . getMessage ( ) ) ; } } } printJdrReportInfo ( report ) ; System . exit ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "connectTimeout added [CODESPLIT] protected void parseRemotingReceiver ( final XMLExtendedStreamReader reader , final EJBClientDescriptorMetaData ejbClientDescriptorMetaData ) throws XMLStreamException { String outboundConnectionRef = null ; final Set < EJBClientDescriptorXMLAttribute > required = EnumSet . of ( EJBClientDescriptorXMLAttribute . OUTBOUND_CONNECTION_REF ) ; final int count = reader . getAttributeCount ( ) ; EJBClientDescriptorMetaData . RemotingReceiverConfiguration remotingReceiverConfiguration = null ; long connectTimeout = 5000 ; for ( int i = 0 ; i < count ; i ++ ) { final EJBClientDescriptorXMLAttribute attribute = EJBClientDescriptorXMLAttribute . forName ( reader . getAttributeLocalName ( i ) ) ; required . remove ( attribute ) ; final String value = readResolveValue ( reader , i ) ; switch ( attribute ) { case OUTBOUND_CONNECTION_REF : outboundConnectionRef = value ; remotingReceiverConfiguration = ejbClientDescriptorMetaData . addRemotingReceiverConnectionRef ( outboundConnectionRef ) ; break ; case CONNECT_TIMEOUT : connectTimeout = Long . parseLong ( value ) ; break ; default : unexpectedContent ( reader ) ; } } if ( ! required . isEmpty ( ) ) { missingAttributes ( reader . getLocation ( ) , required ) ; } // set the timeout remotingReceiverConfiguration . setConnectionTimeout ( connectTimeout ) ; while ( reader . hasNext ( ) ) { switch ( reader . nextTag ( ) ) { case END_ELEMENT : { return ; } case START_ELEMENT : { final EJBClientDescriptorXMLElement element = EJBClientDescriptorXMLElement . forName ( reader . getLocalName ( ) ) ; switch ( element ) { case CHANNEL_CREATION_OPTIONS : final Properties channelCreationOptions = this . parseChannelCreationOptions ( reader ) ; remotingReceiverConfiguration . setChannelCreationOptions ( channelCreationOptions ) ; break ; default : unexpectedElement ( reader ) ; } break ; } default : { unexpectedContent ( reader ) ; } } } unexpectedEndOfDocument ( reader . getLocation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the LocalIDLType for the given TypeCode . [CODESPLIT] static LocalIDLType getIDLType ( TypeCode typeCode , RepositoryImpl repository ) { TCKind tcKind = typeCode . kind ( ) ; if ( PrimitiveDefImpl . isPrimitiveTCKind ( tcKind ) ) return new PrimitiveDefImpl ( typeCode , repository ) ; if ( tcKind == TCKind . tk_sequence ) return repository . getSequenceImpl ( typeCode ) ; if ( tcKind == TCKind . tk_value || tcKind == TCKind . tk_value_box || tcKind == TCKind . tk_alias || tcKind == TCKind . tk_struct || tcKind == TCKind . tk_union || tcKind == TCKind . tk_enum || tcKind == TCKind . tk_objref ) { try { return ( LocalIDLType ) repository . _lookup_id ( typeCode . id ( ) ) ; } catch ( BadKind ex ) { throw IIOPLogger . ROOT_LOGGER . badKindForTypeCode ( tcKind . value ( ) ) ; } } throw IIOPLogger . ROOT_LOGGER . badKindForTypeCode ( tcKind . value ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait for the required service to start up and fail otherwise . This method is necessary when a runtime operation uses a service that might have been created within a composite operation . [CODESPLIT] private static void waitForService ( final ServiceController < ? > controller ) throws OperationFailedException { if ( controller . getState ( ) == ServiceController . State . UP ) return ; final StabilityMonitor monitor = new StabilityMonitor ( ) ; monitor . addController ( controller ) ; try { monitor . awaitStability ( 100 , MILLISECONDS ) ; } catch ( final InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw SecurityLogger . ROOT_LOGGER . interruptedWaitingForSecurityDomain ( controller . getName ( ) . getSimpleName ( ) ) ; } finally { monitor . removeController ( controller ) ; } if ( controller . getState ( ) != ServiceController . State . UP ) { throw SecurityLogger . ROOT_LOGGER . requiredSecurityDomainServiceNotAvailable ( controller . getName ( ) . getSimpleName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to compute masked password based on class attributes . [CODESPLIT] private String computeMaskedPassword ( ) throws Exception { // Create the PBE secret key SecretKeyFactory factory = SecretKeyFactory . getInstance ( VAULT_ENC_ALGORITHM ) ; char [ ] password = \"somearbitrarycrazystringthatdoesnotmatter\" . toCharArray ( ) ; PBEParameterSpec cipherSpec = new PBEParameterSpec ( salt . getBytes ( CHARSET ) , iterationCount ) ; PBEKeySpec keySpec = new PBEKeySpec ( password ) ; SecretKey cipherKey = factory . generateSecret ( keySpec ) ; String maskedPass = PBEUtils . encode64 ( keystorePassword . getBytes ( CHARSET ) , VAULT_ENC_ALGORITHM , cipherKey , cipherSpec ) ; return PicketBoxSecurityVault . PASS_MASK_PREFIX + maskedPass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the underlying vault . [CODESPLIT] private void initSecurityVault ( ) throws Exception { try { this . vault = SecurityVaultFactory . get ( ) ; this . vault . init ( getVaultOptionsMap ( ) ) ; handshake ( ) ; } catch ( SecurityVaultException e ) { throw SecurityLogger . ROOT_LOGGER . securityVaultException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the vault with given alias . [CODESPLIT] public void startVaultSession ( String vaultAlias ) throws Exception { if ( vaultAlias == null ) { throw SecurityLogger . ROOT_LOGGER . vaultAliasNotSpecified ( ) ; } this . keystoreMaskedPassword = ( org . jboss . security . Util . isPasswordCommand ( keystorePassword ) ) ? keystorePassword : computeMaskedPassword ( ) ; this . vaultAlias = vaultAlias ; initSecurityVault ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add secured attribute to specified vault block . This method can be called only after successful startVaultSession () call . [CODESPLIT] public String addSecuredAttribute ( String vaultBlock , String attributeName , char [ ] attributeValue ) throws Exception { vault . store ( vaultBlock , attributeName , attributeValue , null ) ; return securedAttributeConfigurationString ( vaultBlock , attributeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add secured attribute to specified vault block . This method can be called only after successful startVaultSession () call . After successful storage the secured attribute information will be displayed at standard output . For silent method @see addSecuredAttribute [CODESPLIT] public void addSecuredAttributeWithDisplay ( String vaultBlock , String attributeName , char [ ] attributeValue ) throws Exception { vault . store ( vaultBlock , attributeName , attributeValue , null ) ; attributeCreatedDisplay ( vaultBlock , attributeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether secured attribute is already set for given vault block and attribute name . This method can be called only after successful startVaultSession () call . [CODESPLIT] public boolean checkSecuredAttribute ( String vaultBlock , String attributeName ) throws Exception { return vault . exists ( vaultBlock , attributeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method removes secured attribute stored in { @link SecurityVault } . After successful remove operation returns true . Otherwise false . [CODESPLIT] public boolean removeSecuredAttribute ( String vaultBlock , String attributeName ) throws Exception { return vault . remove ( vaultBlock , attributeName , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves secured attribute from specified vault block with specified attribute name . This method can be called only after successful startVaultSession () call . [CODESPLIT] public char [ ] retrieveSecuredAttribute ( String vaultBlock , String attributeName ) throws Exception { return vault . retrieve ( vaultBlock , attributeName , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Display info about stored secured attribute . [CODESPLIT] private void attributeCreatedDisplay ( String vaultBlock , String attributeName ) { System . out . println ( SecurityLogger . ROOT_LOGGER . vaultAttributeCreateDisplay ( vaultBlock , attributeName , securedAttributeConfigurationString ( vaultBlock , attributeName ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Display info about vault itself in form of AS7 configuration file . [CODESPLIT] public void vaultConfigurationDisplay ( ) { final String configuration = vaultConfiguration ( ) ; System . out . println ( SecurityLogger . ROOT_LOGGER . vaultConfigurationTitle ( ) ) ; System . out . println ( \"********************************************\" ) ; System . out . println ( \"For standalone mode:\" ) ; System . out . println ( configuration ) ; System . out . println ( \"********************************************\" ) ; System . out . println ( \"For domain mode:\" ) ; System . out . println ( \"/host=the_host\" + configuration ) ; System . out . println ( \"********************************************\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns vault configuration string in user readable form . [CODESPLIT] public String vaultConfiguration ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( \"/core-service=vault:add(vault-options=[\" ) ; sb . append ( \"(\\\"KEYSTORE_URL\\\" => \\\"\" ) . append ( keystoreURL ) . append ( \"\\\")\" ) . append ( \",\" ) ; sb . append ( \"(\\\"KEYSTORE_PASSWORD\\\" => \\\"\" ) . append ( keystoreMaskedPassword ) . append ( \"\\\")\" ) . append ( \",\" ) ; sb . append ( \"(\\\"KEYSTORE_ALIAS\\\" => \\\"\" ) . append ( vaultAlias ) . append ( \"\\\")\" ) . append ( \",\" ) ; sb . append ( \"(\\\"SALT\\\" => \\\"\" ) . append ( salt ) . append ( \"\\\")\" ) . append ( \",\" ) ; sb . append ( \"(\\\"ITERATION_COUNT\\\" => \\\"\" ) . append ( iterationCount ) . append ( \"\\\")\" ) . append ( \",\" ) ; sb . append ( \"(\\\"ENC_FILE_DIR\\\" => \\\"\" ) . append ( encryptionDirectory ) . append ( \"\\\")\" ) ; sb . append ( \"])\" ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void getResourceValue ( final ResolutionContext resolutionContext , final ServiceBuilder < ? > serviceBuilder , final DeploymentPhaseContext phaseContext , final Injector < ManagedReferenceFactory > injector ) { serviceBuilder . addDependency ( serviceName , ComponentView . class , new ViewManagedReferenceFactory . Injector ( injector ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convenient method to check notNull of value [CODESPLIT] public static < T > T notNull ( T value ) { if ( value == null ) throw ConnectorLogger . ROOT_LOGGER . serviceNotStarted ( ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resource - adapter DMR resource [CODESPLIT] public static synchronized ServiceName getDeploymentServiceName ( final String raName , final Activation raxml ) { if ( raName == null ) throw ConnectorLogger . ROOT_LOGGER . undefinedVar ( \"RaName\" ) ; ServiceName serviceName = null ; ModifiableResourceAdapter ra = ( ModifiableResourceAdapter ) raxml ; if ( ra != null && ra . getId ( ) != null ) { serviceName = getDeploymentServiceName ( raName , ra . getId ( ) ) ; } else { serviceName = getDeploymentServiceName ( raName , ( String ) null ) ; } ROOT_LOGGER . tracef ( \"ConnectorServices: getDeploymentServiceName(%s,%s) -> %s\" , raName , raxml , serviceName ) ; return serviceName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a note of the resource adapter identifier with which a resource adapter named <code > raName< / code > is registered in the { @link org . jboss . jca . core . spi . rar . ResourceAdapterRepository } . <p / > Subsequent calls to { @link #getRegisteredResourceAdapterIdentifier ( String ) } with the passed <code > raName< / code > return the <code > raIdentifier< / code > [CODESPLIT] public static void registerResourceAdapterIdentifier ( final String raName , final String raIdentifier ) { synchronized ( resourceAdapterRepositoryIdentifiers ) { resourceAdapterRepositoryIdentifiers . put ( raName , raIdentifier ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert the constant value into the argument Any . [CODESPLIT] public void insertValue ( Any any ) { if ( type == String . class ) any . insert_wstring ( ( String ) value ) ; // 1.3.5.10 Map to wstring else Util . insertAnyPrimitive ( any , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for a Connector . Will install a { @Code JBossService } for this ResourceAdapter . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ManagementResourceRegistration baseRegistration = deploymentUnit . getAttachment ( DeploymentModelUtils . MUTABLE_REGISTRATION_ATTACHMENT ) ; final ManagementResourceRegistration registration ; final Resource deploymentResource = deploymentUnit . getAttachment ( DeploymentModelUtils . DEPLOYMENT_RESOURCE ) ; final ConnectorXmlDescriptor connectorXmlDescriptor = deploymentUnit . getAttachment ( ConnectorXmlDescriptor . ATTACHMENT_KEY ) ; final CapabilityServiceSupport support = deploymentUnit . getAttachment ( CAPABILITY_SERVICE_SUPPORT ) ; if ( connectorXmlDescriptor == null ) { return ; // Skip non ra deployments } if ( deploymentUnit . getParent ( ) != null ) { registration = baseRegistration . getSubModel ( PathAddress . pathAddress ( PathElement . pathElement ( \"subdeployment\" ) ) ) ; } else { registration = baseRegistration ; } ResourceAdaptersService . ModifiableResourceAdaptors raxmls = null ; final ServiceController < ? > raService = phaseContext . getServiceRegistry ( ) . getService ( ConnectorServices . RESOURCEADAPTERS_SERVICE ) ; if ( raService != null ) raxmls = ( ( ResourceAdaptersService . ModifiableResourceAdaptors ) raService . getValue ( ) ) ; ROOT_LOGGER . tracef ( \"processing Raxml\" ) ; Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; try { final ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; String deploymentUnitPrefix = \"\" ; if ( deploymentUnit . getParent ( ) != null ) { deploymentUnitPrefix = deploymentUnit . getParent ( ) . getName ( ) + \"#\" ; } final String deploymentUnitName = deploymentUnitPrefix + deploymentUnit . getName ( ) ; if ( raxmls != null ) { for ( Activation raxml : raxmls . getActivations ( ) ) { String rarName = raxml . getArchive ( ) ; if ( deploymentUnitName . equals ( rarName ) ) { RaServicesFactory . createDeploymentService ( registration , connectorXmlDescriptor , module , serviceTarget , deploymentUnitName , deploymentUnit . getServiceName ( ) , deploymentUnitName , raxml , deploymentResource , phaseContext . getServiceRegistry ( ) , support ) ; } } } //create service pointing to rar for other future activations ServiceName serviceName = ConnectorServices . INACTIVE_RESOURCE_ADAPTER_SERVICE . append ( deploymentUnitName ) ; InactiveResourceAdapterDeploymentService service = new InactiveResourceAdapterDeploymentService ( connectorXmlDescriptor , module , deploymentUnitName , deploymentUnitName , deploymentUnit . getServiceName ( ) , registration , serviceTarget , deploymentResource ) ; ServiceBuilder builder = serviceTarget . addService ( serviceName , service ) ; builder . setInitialMode ( Mode . ACTIVE ) . install ( ) ; } catch ( Throwable t ) { throw new DeploymentUnitProcessingException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this permission implies the other permission . [CODESPLIT] public boolean implies ( final JndiPermission permission ) { return permission != null && ( ( actionBits & permission . actionBits ) == permission . actionBits ) && impliesPath ( permission . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this permission implies the given { @code actionsBits } on the given { @code name } . [CODESPLIT] public boolean implies ( final String name , final int actionBits ) { Assert . checkNotNullParam ( \"name\" , name ) ; final int maskedBits = actionBits & ACTION_ALL ; return ( this . actionBits & maskedBits ) == maskedBits && impliesPath ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the actions string . The actions string will be a canonical version of the one passed in at construction . [CODESPLIT] public String getActions ( ) { final String actionString = this . actionString ; if ( actionString != null ) { return actionString ; } int actionBits = this . actionBits ; if ( actionBits == ACTION_ALL ) { return this . actionString = \"*\" ; } int m = Integer . lowestOneBit ( actionBits ) ; if ( m != 0 ) { StringBuilder b = new StringBuilder ( ) ; b . append ( getAction ( m ) ) ; actionBits &= ~ m ; while ( actionBits != 0 ) { m = Integer . lowestOneBit ( actionBits ) ; b . append ( ' ' ) . append ( getAction ( m ) ) ; actionBits &= ~ m ; } return this . actionString = b . toString ( ) ; } else { return this . actionString = \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a permission which is equal to this one except with its actions reset to { @code actionBits } . If the given { @code actionBits } equals the current bits of this permission then this permission instance is returned ; otherwise a new permission is constructed . Any action bits which fall outside of { @link #ACTION_ALL } are silently ignored . [CODESPLIT] public JndiPermission withNewActions ( int actionBits ) { actionBits &= ACTION_ALL ; if ( actionBits == this . actionBits ) { return this ; } else { return new JndiPermission ( getName ( ) , actionBits ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private [CODESPLIT] private boolean impliesPath0 ( final String yourName ) { // segment-by-segment comparison final String myName = getName ( ) ; final Iterator < String > myIter = JndiPermissionNameParser . nameIterator ( myName ) ; final Iterator < String > yourIter = JndiPermissionNameParser . nameIterator ( yourName ) ; // even if it's just \"\", there is always a first element assert myIter . hasNext ( ) && yourIter . hasNext ( ) ; String myNext ; String yourNext ; for ( ; ; ) { myNext = myIter . next ( ) ; yourNext = yourIter . next ( ) ; if ( myNext . equals ( \"-\" ) ) { // \"-\" implies everything including \"\" return true ; } if ( ! myNext . equals ( \"*\" ) && ! myNext . equals ( yourNext ) ) { // \"foo/bar\" does not imply \"foo/baz\" return false ; } if ( myIter . hasNext ( ) ) { if ( ! yourIter . hasNext ( ) ) { // \"foo/bar\" does not imply \"foo\" return false ; } } else { // if neither has next, \"foo/bar\" implies \"foo/bar\", else \"foo\" does not imply \"foo/bar\" return ! yourIter . hasNext ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the short class name as the default for the service name . [CODESPLIT] public String getName ( ) { final String s = log . getName ( ) ; final int i = s . lastIndexOf ( \".\" ) ; return i != - 1 ? s . substring ( i + 1 , s . length ( ) ) : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback method of { @link javax . management . MBeanRegistration } before the MBean is registered at the JMX Agent . [CODESPLIT] public ObjectName preRegister ( MBeanServer server , ObjectName name ) throws Exception { this . server = server ; serviceName = getObjectName ( server , name ) ; return serviceName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper for sending out state change notifications [CODESPLIT] private void sendStateChangeNotification ( int oldState , int newState , String msg , Throwable t ) { long now = System . currentTimeMillis ( ) ; AttributeChangeNotification stateChangeNotification = new AttributeChangeNotification ( this , getNextNotificationSequenceNumber ( ) , now , msg , \"State\" , \"java.lang.Integer\" , new Integer ( oldState ) , new Integer ( newState ) ) ; stateChangeNotification . setUserData ( t ) ; sendNotification ( stateChangeNotification ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for jboss - beans . xml files . Will parse the xml file and attach a configuration discovered during processing . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { DeploymentUnit unit = phaseContext . getDeploymentUnit ( ) ; final VirtualFile deploymentRoot = unit . getAttachment ( Attachments . DEPLOYMENT_ROOT ) . getRoot ( ) ; parseDescriptors ( unit , deploymentRoot ) ; final List < ResourceRoot > resourceRoots = unit . getAttachmentList ( Attachments . RESOURCE_ROOTS ) ; for ( ResourceRoot root : resourceRoots ) parseDescriptors ( unit , root . getRoot ( ) ) ; } /**\n     * Find and parse -jboss-beans.xml files.\n     *\n     * @param unit the deployment unit\n     * @param root the root\n     * @throws DeploymentUnitProcessingException\n     *          for any error\n     */ protected void parseDescriptors ( DeploymentUnit unit , VirtualFile root ) throws DeploymentUnitProcessingException { if ( root == null || root . exists ( ) == false ) return ; Collection < VirtualFile > beans ; final String name = root . getName ( ) ; if ( name . endsWith ( \"jboss-beans.xml\" ) ) { beans = Collections . singleton ( root ) ; } else { VirtualFileFilter filter = new SuffixMatchFilter ( \"jboss-beans.xml\" ) ; beans = new ArrayList < VirtualFile > ( ) ; try { // try plain .jar/META-INF VirtualFile metainf = root . getChild ( \"META-INF\" ) ; if ( metainf . exists ( ) ) beans . addAll ( metainf . getChildren ( filter ) ) ; // allow for WEB-INF/*-jboss-beans.xml VirtualFile webinf = root . getChild ( \"WEB-INF\" ) ; if ( webinf . exists ( ) ) { beans . addAll ( webinf . getChildren ( filter ) ) ; // allow WEB-INF/classes/META-INF metainf = webinf . getChild ( \"classes/META-INF\" ) ; if ( metainf . exists ( ) ) beans . addAll ( metainf . getChildren ( filter ) ) ; } } catch ( IOException e ) { throw new DeploymentUnitProcessingException ( e ) ; } } for ( VirtualFile beansXmlFile : beans ) parseDescriptor ( unit , beansXmlFile ) ; } /**\n     * Parse -jboss-beans.xml file.\n     *\n     * @param unit         the deployment unit\n     * @param beansXmlFile the beans xml file\n     * @throws DeploymentUnitProcessingException\n     *          for any error\n     */ protected void parseDescriptor ( DeploymentUnit unit , VirtualFile beansXmlFile ) throws DeploymentUnitProcessingException { if ( beansXmlFile == null || beansXmlFile . exists ( ) == false ) return ; InputStream xmlStream = null ; try { xmlStream = beansXmlFile . openStream ( ) ; final XMLStreamReader reader = inputFactory . createXMLStreamReader ( xmlStream ) ; final ParseResult < KernelDeploymentXmlDescriptor > result = new ParseResult < KernelDeploymentXmlDescriptor > ( ) ; xmlMapper . parseDocument ( result , reader ) ; final KernelDeploymentXmlDescriptor xmlDescriptor = result . getResult ( ) ; if ( xmlDescriptor != null ) unit . addToAttachmentList ( KernelDeploymentXmlDescriptor . ATTACHMENT_KEY , xmlDescriptor ) ; else throw PojoLogger . ROOT_LOGGER . failedToParse ( beansXmlFile ) ; } catch ( DeploymentUnitProcessingException e ) { throw e ; } catch ( Exception e ) { throw PojoLogger . ROOT_LOGGER . parsingException ( beansXmlFile , e ) ; } finally { VFSUtils . safeClose ( xmlStream ) ; } } @ Override public void undeploy  ( DeploymentUnit context ) { } } ", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeContent ( XMLExtendedStreamWriter writer , SubsystemMarshallingContext context ) throws XMLStreamException { ModelNode node = context . getModelNode ( ) ; boolean hasChildren = node . hasDefined ( RESOURCEADAPTER_NAME ) && node . get ( RESOURCEADAPTER_NAME ) . asPropertyList ( ) . size ( ) > 0 ; context . startSubsystemElement ( Namespace . CURRENT . getUriString ( ) , ! hasChildren ) ; if ( hasChildren ) { writer . writeStartElement ( Element . RESOURCE_ADAPTERS . getLocalName ( ) ) ; ModelNode ras = node . get ( RESOURCEADAPTER_NAME ) ; for ( String name : ras . keys ( ) ) { final ModelNode ra = ras . get ( name ) ; writeRaElement ( writer , ra , name ) ; } writer . writeEndElement ( ) ; // Close the subsystem element writer . writeEndElement ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns an { @link javax . persistence . EntityManager } associated with the actual { @link javax . transaction . Transaction } if present . < / p > [CODESPLIT] private EntityManager getOrCreateTransactionalEntityManager ( TransactionManager transactionManager ) { try { if ( transactionManager . getStatus ( ) == Status . STATUS_ACTIVE ) { EntityManager entityManager = this . transactionalEntityManagerHelper . getTransactionScopedEntityManager ( getPersistenceUnitName ( ) ) ; if ( entityManager == null ) { entityManager = createEntityManager ( transactionManager ) ; this . transactionalEntityManagerHelper . putEntityManagerInTransactionRegistry ( getPersistenceUnitName ( ) , entityManager ) ; } return entityManager ; } } catch ( Exception e ) { throw ROOT_LOGGER . idmJpaFailedCreateTransactionEntityManager ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a deployment for standard ra deployment files . Will parse the xml file and attach a configuration discovered during processing . [CODESPLIT] @ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ResourceRoot deploymentRoot = deploymentUnit . getAttachment ( Attachments . DEPLOYMENT_ROOT ) ; final boolean resolveProperties = Util . shouldResolveSpec ( deploymentUnit ) ; final VirtualFile file = deploymentRoot . getRoot ( ) ; if ( file == null || ! file . exists ( ) ) return ; final String deploymentRootName = file . getName ( ) . toLowerCase ( Locale . ENGLISH ) ; if ( ! deploymentRootName . endsWith ( \".rar\" ) ) { return ; } final VirtualFile alternateDescriptor = deploymentRoot . getAttachment ( org . jboss . as . ee . structure . Attachments . ALTERNATE_CONNECTOR_DEPLOYMENT_DESCRIPTOR ) ; String prefix = \"\" ; if ( deploymentUnit . getParent ( ) != null ) { prefix = deploymentUnit . getParent ( ) . getName ( ) + \"#\" ; } String deploymentName = prefix + file . getName ( ) ; ConnectorXmlDescriptor xmlDescriptor = process ( resolveProperties , file , alternateDescriptor , deploymentName ) ; phaseContext . getDeploymentUnit ( ) . putAttachment ( ConnectorXmlDescriptor . ATTACHMENT_KEY , xmlDescriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If any servlet / filter classes are declared then we probably don t want to scan . [CODESPLIT] protected boolean hasBootClasses ( JBossWebMetaData webdata ) throws DeploymentUnitProcessingException { if ( webdata . getServlets ( ) != null ) { for ( ServletMetaData servlet : webdata . getServlets ( ) ) { String servletClass = servlet . getServletClass ( ) ; if ( BOOT_CLASSES . contains ( servletClass ) ) return true ; } } if ( webdata . getFilters ( ) != null ) { for ( FilterMetaData filter : webdata . getFilters ( ) ) { if ( BOOT_CLASSES . contains ( filter . getFilterClass ( ) ) ) return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object invoke ( final Object proxy , final Method method , final Object [ ] args ) throws Throwable { final Interceptor interceptor = interceptors . get ( method ) ; if ( interceptor == null ) { throw new NoSuchMethodError ( method . toString ( ) ) ; } final InterceptorContext context = new InterceptorContext ( ) ; // special location for original proxy context . putPrivateData ( Object . class , proxy ) ; context . putPrivateData ( Component . class , componentView . getComponent ( ) ) ; context . putPrivateData ( ComponentView . class , componentView ) ; context . putPrivateData ( SecurityDomain . class , WildFlySecurityManager . isChecking ( ) ? AccessController . doPrivileged ( ( PrivilegedAction < SecurityDomain > ) SecurityDomain :: getCurrent ) : SecurityDomain . getCurrent ( ) ) ; instance . prepareInterceptorContext ( context ) ; context . setParameters ( args ) ; context . setMethod ( method ) ; // setup the public context data context . setContextData ( new HashMap < String , Object > ( ) ) ; context . setBlockingCaller ( true ) ; return interceptor . processInvocation ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the CORBA object for a Remote object . If input is not a Remote object or if Remote object uses JRMP return null . If the RMI - IIOP library is not available throw ConfigurationException . [CODESPLIT] public Object getStateToBind ( Object orig , Name name , Context ctx , Hashtable < ? , ? > env ) throws NamingException { if ( orig instanceof org . omg . CORBA . Object ) { // Already a CORBA object, just use it return null ; } if ( orig instanceof Remote ) { // Turn remote object into org.omg.CORBA.Object try { // Returns null if JRMP; let next factory try // CNCtx will eventually throw IllegalArgumentException if // no CORBA object gotten return CorbaUtils . remoteToCorba ( ( Remote ) orig , ( ( CNCtx ) ctx ) . _orb ) ; } catch ( ClassNotFoundException e ) { // RMI-IIOP library not available throw IIOPLogger . ROOT_LOGGER . unavailableRMIPackages ( ) ; } } return null ; // pass and let next state factory try }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get value . [CODESPLIT] public Object getValue ( Type type ) { if ( type == null || ( type instanceof Class ) ) { return getClassValue ( ( Class ) type ) ; } else if ( type instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) type ; return getPtValue ( pt ) ; } else { throw PojoLogger . ROOT_LOGGER . unknownType ( type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the context service name . [CODESPLIT] public ServiceName getContextServiceName ( ) { if ( contextServiceName != null ) return contextServiceName ; if ( getNamingMode ( ) == ComponentNamingMode . CREATE ) { return ContextNames . contextServiceNameOfComponent ( getApplicationName ( ) , getModuleName ( ) , getComponentName ( ) ) ; } else if ( getNamingMode ( ) == ComponentNamingMode . USE_MODULE ) { return ContextNames . contextServiceNameOfModule ( getApplicationName ( ) , getModuleName ( ) ) ; } else { throw new IllegalStateException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a combined map of class and method level interceptors [CODESPLIT] public Set < InterceptorDescription > getAllInterceptors ( ) { if ( allInterceptors == null ) { allInterceptors = new HashSet < InterceptorDescription > ( ) ; allInterceptors . addAll ( classInterceptors ) ; if ( ! excludeDefaultInterceptors ) { allInterceptors . addAll ( defaultInterceptors ) ; } for ( List < InterceptorDescription > interceptors : methodInterceptors . values ( ) ) { allInterceptors . addAll ( interceptors ) ; } } return allInterceptors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link InterceptorDescription } for the passed <code > interceptorClassName< / code > if such a class interceptor exists for this component description . Else returns null . [CODESPLIT] public InterceptorDescription getClassInterceptor ( String interceptorClassName ) { for ( InterceptorDescription interceptor : classInterceptors ) { if ( interceptor . getInterceptorClassName ( ) . equals ( interceptorClassName ) ) { return interceptor ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a method interceptor class name . [CODESPLIT] public void addMethodInterceptor ( MethodIdentifier method , InterceptorDescription description ) { //we do not add method level interceptors to the set of interceptor classes, //as their around invoke annotations List < InterceptorDescription > interceptors = methodInterceptors . get ( method ) ; if ( interceptors == null ) { methodInterceptors . put ( method , interceptors = new ArrayList < InterceptorDescription > ( ) ) ; } final String name = description . getInterceptorClassName ( ) ; // add the interceptor class to the EEModuleDescription interceptors . add ( description ) ; this . allInterceptors = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the method level interceptors for a method and marks it as exclude class and default level interceptors . <p / > This is used to set the final interceptor order after it has been modifier by the deployment descriptor [CODESPLIT] public void setMethodInterceptors ( MethodIdentifier identifier , List < InterceptorDescription > interceptorDescriptions ) { methodInterceptors . put ( identifier , interceptorDescriptions ) ; methodExcludeClassInterceptors . add ( identifier ) ; methodExcludeDefaultInterceptors . add ( identifier ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an interceptor class method override merging it with existing overrides ( if any ) [CODESPLIT] public void addInterceptorMethodOverride ( final String className , final InterceptorClassDescription override ) { interceptorClassOverrides . put ( className , InterceptorClassDescription . merge ( interceptorClassOverrides . get ( className ) , override ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the naming mode of this component . May not be { @code null } . [CODESPLIT] public void setNamingMode ( final ComponentNamingMode namingMode ) { if ( namingMode == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( \"namingMode\" , \"component\" , componentName ) ; } this . namingMode = namingMode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a dependency to this component . If the same dependency is added multiple times only the first will take effect . [CODESPLIT] public void addDependency ( ServiceName serviceName ) { if ( serviceName == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( \"serviceName\" , \"component\" , componentName ) ; } dependencies . add ( serviceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the interceptor list for a given method . This should not be called until all interceptors have been added . [CODESPLIT] public List < InterceptorFactory > getComponentInterceptors ( Method method ) { Map < Method , OrderedItemContainer < List < InterceptorFactory > > > map = componentInterceptors ; OrderedItemContainer < List < InterceptorFactory > > interceptors = map . get ( method ) ; if ( interceptors == null ) { return Collections . emptyList ( ) ; } List < List < InterceptorFactory > > sortedItems = interceptors . getSortedItems ( ) ; List < InterceptorFactory > ret = new ArrayList <> ( ) ; for ( List < InterceptorFactory > item : sortedItems ) { ret . addAll ( item ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the around timeout interceptor list for a given method . This should not be called until all interceptors have been added . [CODESPLIT] public List < InterceptorFactory > getAroundTimeoutInterceptors ( Method method ) { Map < Method , OrderedItemContainer < InterceptorFactory > > map = timeoutInterceptors ; OrderedItemContainer < InterceptorFactory > interceptors = map . get ( method ) ; if ( interceptors == null ) { return Collections . emptyList ( ) ; } return interceptors . getSortedItems ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an interceptor factory to every method on the component . [CODESPLIT] public void addComponentInterceptor ( InterceptorFactory factory , int priority , boolean publicOnly ) { addComponentInterceptors ( Collections . singletonList ( factory ) , priority , publicOnly ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an interceptor factory to every method on the component . [CODESPLIT] public void addComponentInterceptors ( List < InterceptorFactory > factory , int priority , boolean publicOnly ) { for ( Method method : ( Iterable < Method > ) classIndex . getClassMethods ( ) ) { if ( publicOnly && ! Modifier . isPublic ( method . getModifiers ( ) ) ) { continue ; } OrderedItemContainer < List < InterceptorFactory > > interceptors = componentInterceptors . get ( method ) ; if ( interceptors == null ) { componentInterceptors . put ( method , interceptors = new OrderedItemContainer < List < InterceptorFactory > > ( ) ) ; } interceptors . add ( factory , priority ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an interceptor factory to a given method . The method parameter * must * be retrived from either the { @link org . jboss . as . server . deployment . reflect . DeploymentReflectionIndex } or from { @link #getDefinedComponentMethods () } as the methods are stored in an identity hash map [CODESPLIT] public void addComponentInterceptor ( Method method , InterceptorFactory factory , int priority ) { addComponentInterceptors ( method , Collections . singletonList ( factory ) , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an interceptor factory to a given method . The method parameter * must * be retrived from either the { @link org . jboss . as . server . deployment . reflect . DeploymentReflectionIndex } or from { @link #getDefinedComponentMethods () } as the methods are stored in an identity hash map [CODESPLIT] public void addComponentInterceptors ( Method method , List < InterceptorFactory > factory , int priority ) { OrderedItemContainer < List < InterceptorFactory >> interceptors = componentInterceptors . get ( method ) ; if ( interceptors == null ) { componentInterceptors . put ( method , interceptors = new OrderedItemContainer < List < InterceptorFactory > > ( ) ) ; } interceptors . add ( factory , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a timeout interceptor factory to every method on the component . [CODESPLIT] public void addTimeoutViewInterceptor ( final Method method , InterceptorFactory factory , int priority ) { OrderedItemContainer < InterceptorFactory > interceptors = timeoutInterceptors . get ( method ) ; if ( interceptors == null ) { timeoutInterceptors . put ( method , interceptors = new OrderedItemContainer < InterceptorFactory > ( ) ) ; } interceptors . add ( factory , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the around - construct interceptors . <p / > This method should only be called after all interceptors have been added [CODESPLIT] public List < InterceptorFactory > getAroundConstructInterceptors ( ) { List < List < InterceptorFactory >> sortedItems = aroundConstructInterceptors . getSortedItems ( ) ; List < InterceptorFactory > interceptorFactories = new ArrayList <> ( ) ; for ( List < InterceptorFactory > i : sortedItems ) { interceptorFactories . addAll ( i ) ; } return interceptorFactories ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an around - construct interceptor [CODESPLIT] public void addAroundConstructInterceptor ( InterceptorFactory interceptorFactory , int priority ) { aroundConstructInterceptors . add ( Collections . singletonList ( interceptorFactory ) , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the post - construct interceptors . <p / > This method should only be called after all interceptors have been added [CODESPLIT] public List < InterceptorFactory > getPostConstructInterceptors ( ) { List < List < InterceptorFactory >> sortedItems = postConstructInterceptors . getSortedItems ( ) ; List < InterceptorFactory > interceptorFactories = new ArrayList <> ( ) ; for ( List < InterceptorFactory > i : sortedItems ) { interceptorFactories . addAll ( i ) ; } return interceptorFactories ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a post construct interceptor [CODESPLIT] public void addPostConstructInterceptor ( InterceptorFactory interceptorFactory , int priority ) { postConstructInterceptors . add ( Collections . singletonList ( interceptorFactory ) , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pre - destroy interceptors . <p / > This method should only be called after all interceptors have been added [CODESPLIT] public List < InterceptorFactory > getPreDestroyInterceptors ( ) { List < List < InterceptorFactory >> sortedItems = preDestroyInterceptors . getSortedItems ( ) ; List < InterceptorFactory > interceptorFactories = new ArrayList <> ( ) ; for ( List < InterceptorFactory > i : sortedItems ) { interceptorFactories . addAll ( i ) ; } return interceptorFactories ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a pre destroy interceptor [CODESPLIT] public void addPreDestroyInterceptor ( InterceptorFactory interceptorFactory , int priority ) { preDestroyInterceptors . add ( Collections . singletonList ( interceptorFactory ) , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pre - passivate interceptors . <p / > This method should only be called after all interceptors have been added [CODESPLIT] public List < InterceptorFactory > getPrePassivateInterceptors ( ) { List < List < InterceptorFactory >> sortedItems = prePassivateInterceptors . getSortedItems ( ) ; List < InterceptorFactory > interceptorFactories = new ArrayList <> ( ) ; for ( List < InterceptorFactory > i : sortedItems ) { interceptorFactories . addAll ( i ) ; } return interceptorFactories ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a pre passivate interceptor [CODESPLIT] public void addPrePassivateInterceptor ( InterceptorFactory interceptorFactory , int priority ) { prePassivateInterceptors . add ( Collections . singletonList ( interceptorFactory ) , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the post - activate interceptors . <p / > This method should only be called after all interceptors have been added [CODESPLIT] public List < InterceptorFactory > getPostActivateInterceptors ( ) { List < List < InterceptorFactory >> sortedItems = postActivateInterceptors . getSortedItems ( ) ; List < InterceptorFactory > interceptorFactories = new ArrayList <> ( ) ; for ( List < InterceptorFactory > i : sortedItems ) { interceptorFactories . addAll ( i ) ; } return interceptorFactories ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a post activate interceptor [CODESPLIT] public void addPostActivateInterceptor ( InterceptorFactory interceptorFactory , int priority ) { postActivateInterceptors . add ( Collections . singletonList ( interceptorFactory ) , priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the component create service factory for this component . [CODESPLIT] public void setComponentCreateServiceFactory ( final ComponentCreateServiceFactory componentCreateServiceFactory ) { if ( componentCreateServiceFactory == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( \"componentCreateServiceFactory\" , \"component\" , getComponentName ( ) ) ; } this . componentCreateServiceFactory = componentCreateServiceFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public synchronized Component getValue ( ) throws IllegalStateException , IllegalArgumentException { Component component = this . component ; if ( component == null ) { throw EeLogger . ROOT_LOGGER . serviceNotStarted ( ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method corresponds to the original { @code _getClassLoader () } method and returns { @link Module } based on original class . This module is then used when defining proxy classes . [CODESPLIT] private Module getModule ( Class < ? > originalClass ) { if ( originalClass . getName ( ) . startsWith ( \"java\" ) ) { return module ; } else { Module definingModule = Module . forClass ( originalClass ) ; Boolean hasWeldDependencies = processedStaticModules . get ( definingModule . getIdentifier ( ) ) ; boolean logWarning = false ; // only log for the first class in the module if ( hasWeldDependencies == null ) { hasWeldDependencies = canLoadWeldProxies ( definingModule ) ; // may be run multiple times but that does not matter logWarning = processedStaticModules . putIfAbsent ( definingModule . getIdentifier ( ) , hasWeldDependencies ) == null ; } if ( hasWeldDependencies ) { // this module declares Weld dependencies - we can use module's classloader to load the proxy class // pros: package-private members will work fine // cons: proxy classes will remain loaded by the module's classloader after undeployment (nothing else leaks) return definingModule ; } else { // no weld dependencies - we use deployment's classloader to load the proxy class // pros: proxy classes unloaded with undeployment // cons: package-private methods and constructors will yield IllegalAccessException if ( logWarning ) { WeldLogger . ROOT_LOGGER . loadingProxiesUsingDeploymentClassLoader ( definingModule . getIdentifier ( ) , Arrays . toString ( REQUIRED_WELD_DEPENDENCIES ) ) ; } return this . module ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "without ProtectionDomain [CODESPLIT] private ProtectionDomain getProtectionDomain ( final Class < ? > clazz ) { final SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { return doPrivileged ( ( PrivilegedAction < ProtectionDomain > ) clazz :: getProtectionDomain ) ; } else { return clazz . getProtectionDomain ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The entry key is bean . xml URL value is ( optional ) jandex index URL . [CODESPLIT] private Map < URL , URL > findExportedResources ( Module dependencyModule ) { Set < URL > beanXmls = findExportedResource ( dependencyModule , META_INF_BEANS_XML ) ; if ( beanXmls . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } Set < URL > indexes = findExportedResource ( dependencyModule , META_INF_JANDEX_IDX ) ; Map < URL , URL > ret = new HashMap <> ( ) ; for ( URL beansXml : beanXmls ) { String urlBase = beansXml . toString ( ) . substring ( 0 , beansXml . toString ( ) . length ( ) - META_INF_BEANS_XML . length ( ) ) ; URL idx = null ; for ( URL index : indexes ) { if ( index . toString ( ) . startsWith ( urlBase ) ) { idx = index ; break ; } } ret . put ( beansXml , idx ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove JNDI alias binder services . [CODESPLIT] protected void removeJNDIAliases ( OperationContext context , List < ModelNode > entries ) { if ( entries . size ( ) > 1 ) { for ( int i = 1 ; i < entries . size ( ) ; i ++ ) { ContextNames . BindInfo aliasBindInfo = ContextNames . bindInfoFor ( entries . get ( i ) . asString ( ) ) ; context . removeService ( aliasBindInfo . getBinderServiceName ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hibernate native applications cannot know when the TransactionManager + TransactionSynchronizationRegistry services are stopped but JPA container managed applications can and will call setTransactionSynchronizationRegistry with the new ( global ) TransactionSynchronizationRegistry to use . [CODESPLIT] public static void setTransactionSynchronizationRegistry ( TransactionSynchronizationRegistry tsr ) { if ( ( Assert . checkNotNullParam ( \"tsr\" , tsr ) ) != transactionSynchronizationRegistry ) { synchronized ( WildFlyCustomJtaPlatform . class ) { if ( tsr != transactionSynchronizationRegistry ) { transactionSynchronizationRegistry = tsr ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the configuration of the transport provider . [CODESPLIT] public void accept ( final EJBClientContext . Builder builder ) { final EJBTransportProvider remoteTransportProvider = this . remoteTransportProvider ; if ( remoteTransportProvider != null ) { builder . addTransportProvider ( remoteTransportProvider ) ; builder . addTransportProvider ( remoteHttpTransportProvider ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the base service name of a component s JNDI namespace . [CODESPLIT] public static ServiceName contextServiceNameOfComponent ( String app , String module , String comp ) { return COMPONENT_CONTEXT_SERVICE_NAME . append ( app , module , comp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the base service name of a module s JNDI namespace . [CODESPLIT] public static ServiceName contextServiceNameOfModule ( String app , String module ) { return MODULE_CONTEXT_SERVICE_NAME . append ( app , module ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the service name of a context or { @code null } if there is no service mapping for the context name . [CODESPLIT] public static BindInfo bindInfoFor ( String app , String module , String comp , String context ) { if ( context . startsWith ( \"java:\" ) ) { final String namespace ; final int i = context . indexOf ( ' ' ) ; if ( i == - 1 ) { namespace = context . substring ( 5 ) ; } else if ( i == 5 ) { // Absolute path return new BindInfo ( JAVA_CONTEXT_SERVICE_NAME , context . substring ( 6 ) ) ; } else { namespace = context . substring ( 5 , i ) ; } sanitazeNameSpace ( namespace , context ) ; if ( namespace . equals ( \"global\" ) ) { return new BindInfo ( GLOBAL_CONTEXT_SERVICE_NAME , context . substring ( 12 ) ) ; } else if ( namespace . equals ( \"jboss\" ) ) { String rest = context . substring ( i ) ; if ( rest . startsWith ( \"/exported/\" ) ) { return new BindInfo ( EXPORTED_CONTEXT_SERVICE_NAME , context . substring ( 20 ) ) ; } else { return new BindInfo ( JBOSS_CONTEXT_SERVICE_NAME , context . substring ( 11 ) ) ; } } else if ( namespace . equals ( \"app\" ) ) { return new BindInfo ( contextServiceNameOfApplication ( app ) , context . substring ( 9 ) ) ; } else if ( namespace . equals ( \"module\" ) ) { return new BindInfo ( contextServiceNameOfModule ( app , module ) , context . substring ( 12 ) ) ; } else if ( namespace . equals ( \"comp\" ) ) { return new BindInfo ( contextServiceNameOfComponent ( app , module , comp ) , context . substring ( 10 ) ) ; } else { return new BindInfo ( JBOSS_CONTEXT_SERVICE_NAME , context ) ; } } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the service name of an environment entry [CODESPLIT] public static BindInfo bindInfoForEnvEntry ( String app , String module , String comp , boolean useCompNamespace , final String envEntryName ) { if ( envEntryName . startsWith ( \"java:\" ) ) { if ( useCompNamespace ) { return bindInfoFor ( app , module , comp , envEntryName ) ; } else { if ( envEntryName . startsWith ( \"java:comp\" ) ) { return bindInfoFor ( app , module , module , \"java:module\" + envEntryName . substring ( \"java:comp\" . length ( ) ) ) ; } else { return bindInfoFor ( app , module , module , envEntryName ) ; } } } else { if ( useCompNamespace ) { return bindInfoFor ( app , module , comp , \"java:comp/env/\" + envEntryName ) ; } else { return bindInfoFor ( app , module , module , \"java:module/env/\" + envEntryName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the service name of a NamingStore [CODESPLIT] public static BindInfo bindInfoFor ( final String jndiName ) { // TODO: handle non java: schemes String bindName ; if ( jndiName . startsWith ( \"java:\" ) ) { bindName = jndiName . substring ( 5 ) ; } else if ( ! jndiName . startsWith ( \"jboss\" ) && ! jndiName . startsWith ( \"global\" ) && ! jndiName . startsWith ( \"/\" ) ) { bindName = \"/\" + jndiName ; } else { bindName = jndiName ; } final ServiceName parentContextName ; if ( bindName . startsWith ( \"jboss/exported/\" ) ) { parentContextName = EXPORTED_CONTEXT_SERVICE_NAME ; bindName = bindName . substring ( 15 ) ; } else if ( bindName . startsWith ( \"jboss/\" ) ) { parentContextName = JBOSS_CONTEXT_SERVICE_NAME ; bindName = bindName . substring ( 6 ) ; } else if ( bindName . startsWith ( \"global/\" ) ) { parentContextName = GLOBAL_CONTEXT_SERVICE_NAME ; bindName = bindName . substring ( 7 ) ; } else if ( bindName . startsWith ( \"/\" ) ) { parentContextName = JAVA_CONTEXT_SERVICE_NAME ; bindName = bindName . substring ( 1 ) ; } else { throw NamingLogger . ROOT_LOGGER . illegalContextInName ( jndiName ) ; } return new BindInfo ( parentContextName , bindName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the specified EntityManager in the local threads active transaction . The TransactionSynchronizationRegistry will clear the reference to the EntityManager when the transaction completes . [CODESPLIT] public void putEntityManagerInTransactionRegistry ( String scopedPuName , EntityManager entityManager ) { try { Transaction transaction = this . transactionManager . getTransaction ( ) ; transaction . registerSynchronization ( new TransactionalEntityManagerSynchronization ( entityManager ) ) ; this . transactionSynchronizationRegistry . putResource ( scopedPuName , entityManager ) ; } catch ( Exception e ) { throw PicketLinkLogger . ROOT_LOGGER . idmJpaFailedCreateTransactionEntityManager ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads and trims the text for the given attribute and returns it or { @code null } [CODESPLIT] public String rawAttributeText ( XMLStreamReader reader , String attributeName ) { return rawAttributeText ( reader , attributeName , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected JaccService < AttachmentList < EjbJaccConfig > > createService ( String contextId , AttachmentList < EjbJaccConfig > metaData , Boolean standalone ) { return new EjbJaccService ( contextId , metaData , standalone ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Adds a { @code BinderService } to the specified target . The service binds the specified value to JNDI under the { @code java : / jboss / contextName } context . < / p > [CODESPLIT] public static void bindObject ( final ServiceTarget target , final String contextName , final Object value ) { final BinderService binderService = new BinderService ( contextName ) ; binderService . getManagedObjectInjector ( ) . inject ( new ValueManagedReferenceFactory ( Values . immediateValue ( value ) ) ) ; target . addService ( ContextNames . buildServiceName ( ContextNames . JBOSS_CONTEXT_SERVICE_NAME , contextName ) , binderService ) . addDependency ( ContextNames . JBOSS_CONTEXT_SERVICE_NAME , ServiceBasedNamingStore . class , binderService . getNamingStoreInjector ( ) ) . install ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a default cache implementation [CODESPLIT] public ConcurrentMap < Principal , DomainInfo > getCache ( ) { return new LRUCache <> ( 1000 , ( key , value ) -> { if ( value != null ) { value . logout ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LocalIRObject implementation --------------------------------- [CODESPLIT] public IRObject getReference ( ) { if ( ref == null ) { ref = org . omg . CORBA . ValueDefHelper . narrow ( servantToReference ( new ValueDefPOATie ( this ) ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "IDLTypeOperations implementation ------------------------------ [CODESPLIT] public TypeCode type ( ) { if ( typeCode == null ) { short modifier = VM_NONE . value ; if ( is_custom ) modifier = VM_CUSTOM . value ; else if ( is_abstract ) modifier = VM_ABSTRACT . value ; typeCode = getORB ( ) . create_value_tc ( id , name , modifier , baseValueTypeCode , getValueMembersForTypeCode ( ) ) ; } return typeCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ContainedImpl implementation ---------------------------------- [CODESPLIT] public Description describe ( ) { String defined_in_id = \"IR\" ; if ( defined_in instanceof org . omg . CORBA . ContainedOperations ) defined_in_id = ( ( org . omg . CORBA . ContainedOperations ) defined_in ) . id ( ) ; ValueDescription md = new ValueDescription ( name , id , is_abstract , is_custom , defined_in_id , version , supported_interfaces , abstract_base_valuetypes , false , baseValue ) ; Any any = getORB ( ) . create_any ( ) ; ValueDescriptionHelper . insert ( any , md ) ; return new Description ( DefinitionKind . dk_Value , any ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the valueMembers array and return it . [CODESPLIT] private ValueMember [ ] getValueMembers ( ) { if ( valueMembers != null ) return valueMembers ; LocalContained [ ] c = _contents ( DefinitionKind . dk_ValueMember , false ) ; valueMembers = new ValueMember [ c . length ] ; for ( int i = 0 ; i < c . length ; ++ i ) { ValueMemberDefImpl vmdi = ( ValueMemberDefImpl ) c [ i ] ; valueMembers [ i ] = new ValueMember ( vmdi . name ( ) , vmdi . id ( ) , ( ( LocalContained ) vmdi . defined_in ) . id ( ) , vmdi . version ( ) , vmdi . type ( ) , vmdi . type_def ( ) , vmdi . access ( ) ) ; } return valueMembers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a valueMembers array for TypeCode creation only and return it . [CODESPLIT] private ValueMember [ ] getValueMembersForTypeCode ( ) { LocalContained [ ] c = _contents ( DefinitionKind . dk_ValueMember , false ) ; ValueMember [ ] vms = new ValueMember [ c . length ] ; for ( int i = 0 ; i < c . length ; ++ i ) { ValueMemberDefImpl vmdi = ( ValueMemberDefImpl ) c [ i ] ; vms [ i ] = new ValueMember ( vmdi . name ( ) , null , // ignore id null , // ignore defined_in null , // ignore version vmdi . type ( ) , null , // ignore type_def vmdi . access ( ) ) ; } return vms ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a ContextService for this module . [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; if ( deploymentUnit . getParent ( ) != null ) { return ; } EEModuleDescription moduleDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_MODULE_DESCRIPTION ) ; final ServiceTarget serviceTarget = phaseContext . getServiceTarget ( ) ; final ServiceName applicationContextServiceName = ContextNames . contextServiceNameOfApplication ( moduleDescription . getApplicationName ( ) ) ; final NamingStoreService contextService = new NamingStoreService ( true ) ; serviceTarget . addService ( applicationContextServiceName , contextService ) . install ( ) ; final ServiceName appNameServiceName = applicationContextServiceName . append ( \"AppName\" ) ; final BinderService applicationNameBinder = new BinderService ( \"AppName\" ) ; applicationNameBinder . getManagedObjectInjector ( ) . inject ( new ValueManagedReferenceFactory ( Values . immediateValue ( moduleDescription . getApplicationName ( ) ) ) ) ; serviceTarget . addService ( appNameServiceName , applicationNameBinder ) . addDependency ( applicationContextServiceName , ServiceBasedNamingStore . class , applicationNameBinder . getNamingStoreInjector ( ) ) . install ( ) ; deploymentUnit . addToAttachmentList ( org . jboss . as . server . deployment . Attachments . JNDI_DEPENDENCIES , appNameServiceName ) ; deploymentUnit . putAttachment ( Attachments . APPLICATION_CONTEXT_CONFIG , applicationContextServiceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the root subsystem s root address . [CODESPLIT] private ModelNode createSubsystemRoot ( ) { ModelNode subsystemAddress = new ModelNode ( ) ; subsystemAddress . add ( ModelDescriptionConstants . SUBSYSTEM , FederationExtension . SUBSYSTEM_NAME ) ; subsystemAddress . protect ( ) ; return Util . getEmptyOperation ( ADD , subsystemAddress ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a element from the stream considering the parameters . [CODESPLIT] protected ModelNode parseConfig ( XMLExtendedStreamReader reader , ModelElement xmlElement , String key , ModelNode lastNode , List < SimpleAttributeDefinition > attributes , List < ModelNode > addOperations ) throws XMLStreamException { if ( ! reader . getLocalName ( ) . equals ( xmlElement . getName ( ) ) ) { return null ; } ModelNode modelNode = Util . getEmptyOperation ( ADD , null ) ; int attributeCount = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < attributeCount ; i ++ ) { String attributeLocalName = reader . getAttributeLocalName ( i ) ; if ( ModelElement . forName ( attributeLocalName ) == null ) { throw unexpectedAttribute ( reader , i ) ; } } for ( SimpleAttributeDefinition simpleAttributeDefinition : attributes ) { String attributeValue = reader . getAttributeValue ( \"\" , simpleAttributeDefinition . getXmlName ( ) ) ; simpleAttributeDefinition . parseAndSetParameter ( attributeValue , modelNode , reader ) ; } String name = xmlElement . getName ( ) ; if ( key != null ) { name = key ; if ( modelNode . hasDefined ( key ) ) { name = modelNode . get ( key ) . asString ( ) ; } else { String attributeValue = reader . getAttributeValue ( \"\" , key ) ; if ( attributeValue != null ) { name = attributeValue ; } } } modelNode . get ( ModelDescriptionConstants . OP_ADDR ) . set ( lastNode . clone ( ) . get ( OP_ADDR ) . add ( xmlElement . getName ( ) , name ) ) ; addOperations . add ( modelNode ) ; return modelNode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeContent ( final XMLExtendedStreamWriter writer , final SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( NamingExtension . NAMESPACE_2_0 , false ) ; ModelNode model = context . getModelNode ( ) ; // bindings if ( model . hasDefined ( BINDING ) ) { writer . writeStartElement ( NamingSubsystemXMLElement . BINDINGS . getLocalName ( ) ) ; final ModelNode bindingModel = model . get ( BINDING ) ; this . writeBindings ( writer , bindingModel ) ; // </timer-service> writer . writeEndElement ( ) ; } if ( model . hasDefined ( SERVICE ) ) { final ModelNode service = model . get ( SERVICE ) ; if ( service . has ( REMOTE_NAMING ) ) { writer . writeEmptyElement ( REMOTE_NAMING ) ; } } // write the subsystem end element writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void populateModel ( ModelNode operation , ModelNode model ) throws OperationFailedException { String str = PathAddress . pathAddress ( operation . get ( OP_ADDR ) ) . getLastElement ( ) . getValue ( ) ; if ( ! str . startsWith ( \"java:/\" ) && ! str . startsWith ( \"java:jboss/\" ) ) { throw ROOT_LOGGER . jndiNameInvalidFormat ( ) ; } CMResourceResourceDefinition . CM_TABLE_NAME . validateAndSet ( operation , model ) ; CMResourceResourceDefinition . CM_TABLE_BATCH_SIZE . validateAndSet ( operation , model ) ; CMResourceResourceDefinition . CM_TABLE_IMMEDIATE_CLEANUP . validateAndSet ( operation , model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void performRuntime ( final OperationContext context , final ModelNode operation , final ModelNode model ) throws OperationFailedException { PathAddress address = PathAddress . pathAddress ( operation . get ( OP_ADDR ) ) ; final String jndiName = address . getLastElement ( ) . getValue ( ) ; final String tableName = CMResourceResourceDefinition . CM_TABLE_NAME . resolveModelAttribute ( context , model ) . asString ( ) ; final int batchSize = CMResourceResourceDefinition . CM_TABLE_BATCH_SIZE . resolveModelAttribute ( context , model ) . asInt ( ) ; final boolean immediateCleanup = CMResourceResourceDefinition . CM_TABLE_IMMEDIATE_CLEANUP . resolveModelAttribute ( context , model ) . asBoolean ( ) ; ROOT_LOGGER . debugf ( \"adding commit-markable-resource: jndi-name=%s, table-name=%s, batch-size=%d, immediate-cleanup=%b\" , jndiName , tableName , batchSize , immediateCleanup ) ; CMResourceService service = new CMResourceService ( jndiName , tableName , immediateCleanup , batchSize ) ; context . getServiceTarget ( ) . addService ( TxnServices . JBOSS_TXN_CMR . append ( jndiName ) , service ) . addDependency ( TxnServices . JBOSS_TXN_JTA_ENVIRONMENT , JTAEnvironmentBean . class , service . getJTAEnvironmentBeanInjector ( ) ) . setInitialMode ( ServiceController . Mode . ACTIVE ) . install ( ) ; if ( ! context . isBooting ( ) ) { context . reloadRequired ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new NamingServer and sets the naming context to use the naming server . [CODESPLIT] public void start ( StartContext context ) throws StartException { ROOT_LOGGER . startingService ( ) ; try { NamingContext . setActiveNamingStore ( namingStore . getValue ( ) ) ; } catch ( Throwable t ) { throw new StartException ( NamingLogger . ROOT_LOGGER . failedToStart ( \"naming service\" ) , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void readElement ( XMLExtendedStreamReader reader , List < ModelNode > list ) throws XMLStreamException { ParseUtils . requireNoAttributes ( reader ) ; ParseUtils . requireNoContent ( reader ) ; list . add ( Util . createAddOperation ( PathAddress . pathAddress ( NamingExtension . SUBSYSTEM_PATH ) ) ) ; if ( ! appclient ) { //we do not add remote naming to the application client //note that this is a bi list . add ( Util . createAddOperation ( PathAddress . pathAddress ( NamingExtension . SUBSYSTEM_PATH ) . append ( NamingSubsystemModel . SERVICE , NamingSubsystemModel . REMOTE_NAMING ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add dependencies for modules required for JPA deployments [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; setClassLoaderTransformer ( deploymentUnit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "As the weld based instantiator needs access to the bean manager it is installed as a service . [CODESPLIT] private void addWeldIntegration ( final Iterable < ComponentIntegrator > componentIntegrators , final ComponentInterceptorSupport componentInterceptorSupport , final ServiceTarget target , final ComponentConfiguration configuration , final ComponentDescription description , final Class < ? > componentClass , final String beanName , final ServiceName weldServiceName , final ServiceName weldStartService , final ServiceName beanManagerService , final Set < Class < ? > > interceptorClasses , final ClassLoader classLoader , final String beanDeploymentArchiveId ) { final ServiceName serviceName = configuration . getComponentDescription ( ) . getServiceName ( ) . append ( \"WeldInstantiator\" ) ; final ServiceBuilder < ? > builder = target . addService ( serviceName ) ; builder . requires ( weldStartService ) ; configuration . setInstanceFactory ( WeldManagedReferenceFactory . INSTANCE ) ; configuration . getStartDependencies ( ) . add ( new DependencyConfigurator < ComponentStartService > ( ) { @ Override public void configureDependency ( final ServiceBuilder < ? > serviceBuilder , ComponentStartService service ) throws DeploymentUnitProcessingException { serviceBuilder . requires ( serviceName ) ; } } ) ; boolean isComponentIntegrationPerformed = false ; for ( ComponentIntegrator componentIntegrator : componentIntegrators ) { Supplier < ServiceName > bindingServiceNameSupplier = ( ) -> { if ( componentInterceptorSupport == null ) { throw WeldLogger . DEPLOYMENT_LOGGER . componentInterceptorSupportNotAvailable ( componentClass ) ; } return addWeldInterceptorBindingService ( target , configuration , componentClass , beanName , weldServiceName , weldStartService , beanDeploymentArchiveId , componentInterceptorSupport ) ; } ; DefaultInterceptorIntegrationAction integrationAction = ( bindingServiceName ) - > { if ( componentInterceptorSupport == null )  { throw WeldLogger . DEPLOYMENT_LOGGER . componentInterceptorSupportNotAvailable ( componentClass ) ; } addJsr299BindingsCreateInterceptor ( configuration , description , beanName , weldServiceName , builder , bindingServiceName , componentInterceptorSupport ) ; addCommonLifecycleInterceptionSupport ( configuration , builder , bindingServiceName , beanManagerService , componentInterceptorSupport ) ; configuration . addComponentInterceptor ( new UserInterceptorFactory ( factory ( InterceptionType . AROUND_INVOKE , builder , bindingServiceName , componentInterceptorSupport ) , factory ( InterceptionType . AROUND_TIMEOUT , builder , bindingServiceName , componentInterceptorSupport ) ) , InterceptorOrder . Component . CDI_INTERCEPTORS , false ) ; } ; if ( componentIntegrator . integrate ( beanManagerService , configuration , description , builder , bindingServiceNameSupplier , integrationAction , componentInterceptorSupport ) ) { isComponentIntegrationPerformed = true ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the service name used for the job operator registered for the deployment . [CODESPLIT] public static ServiceName jobOperatorServiceName ( final String deploymentRuntimeName , final String subdeploymentName ) { return Services . deploymentUnitName ( deploymentRuntimeName , subdeploymentName ) . append ( \"batch\" ) . append ( \"job-operator\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a component to this application . [CODESPLIT] public void addComponent ( final ComponentDescription description , final VirtualFile deploymentRoot ) { for ( final ViewDescription viewDescription : description . getViews ( ) ) { List < ViewInformation > viewComponents = componentsByViewName . get ( viewDescription . getViewClassName ( ) ) ; if ( viewComponents == null ) { viewComponents = new ArrayList < ViewInformation > ( 1 ) ; componentsByViewName . put ( viewDescription . getViewClassName ( ) , viewComponents ) ; } viewComponents . add ( new ViewInformation ( viewDescription , deploymentRoot , description . getComponentName ( ) ) ) ; } List < Description > components = componentsByName . get ( description . getComponentName ( ) ) ; if ( components == null ) { componentsByName . put ( description . getComponentName ( ) , components = new ArrayList < Description > ( 1 ) ) ; } components . add ( new Description ( description , deploymentRoot ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a message destination to the application [CODESPLIT] public void addMessageDestination ( final String name , final String resolvedName , final VirtualFile deploymentRoot ) { List < MessageDestinationMapping > components = messageDestinationJndiMapping . get ( name ) ; if ( components == null ) { messageDestinationJndiMapping . put ( name , components = new ArrayList < MessageDestinationMapping > ( 1 ) ) ; } components . add ( new MessageDestinationMapping ( resolvedName , deploymentRoot ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all views that have the given type in the application [CODESPLIT] public Set < ViewDescription > getComponentsForViewName ( final String viewType , final VirtualFile deploymentRoot ) { final List < ViewInformation > info = componentsByViewName . get ( viewType ) ; if ( info == null ) { return Collections . < ViewDescription > emptySet ( ) ; } final Set < ViewDescription > ret = new HashSet < ViewDescription > ( ) ; final Set < ViewDescription > currentDep = new HashSet < ViewDescription > ( ) ; for ( ViewInformation i : info ) { if ( deploymentRoot . equals ( i . deploymentRoot ) ) { currentDep . add ( i . viewDescription ) ; } ret . add ( i . viewDescription ) ; } if ( ! currentDep . isEmpty ( ) ) { return currentDep ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all components in the application that have the given name [CODESPLIT] public Set < ComponentDescription > getComponents ( final String componentName , final VirtualFile deploymentRoot ) { if ( componentName . contains ( \"#\" ) ) { final String [ ] parts = componentName . split ( \"#\" ) ; String path = parts [ 0 ] ; if ( ! path . startsWith ( \"../\" ) ) { path = \"../\" + path ; } final VirtualFile virtualPath = deploymentRoot . getChild ( path ) ; final String name = parts [ 1 ] ; final List < Description > info = componentsByName . get ( name ) ; if ( info == null ) { return Collections . emptySet ( ) ; } final Set < ComponentDescription > ret = new HashSet < ComponentDescription > ( ) ; for ( Description i : info ) { //now we need to check the path if ( virtualPath . equals ( i . deploymentRoot ) ) { ret . add ( i . componentDescription ) ; } } return ret ; } else { final List < Description > info = componentsByName . get ( componentName ) ; if ( info == null ) { return Collections . emptySet ( ) ; } final Set < ComponentDescription > all = new HashSet < ComponentDescription > ( ) ; final Set < ComponentDescription > thisDeployment = new HashSet < ComponentDescription > ( ) ; for ( Description i : info ) { all . add ( i . componentDescription ) ; if ( i . deploymentRoot . equals ( deploymentRoot ) ) { thisDeployment . add ( i . componentDescription ) ; } } //if there are multiple e if ( all . size ( ) > 1 ) { return thisDeployment ; } return all ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all views in the application that have the given name and view type [CODESPLIT] public Set < ViewDescription > getComponents ( final String componentName , final String viewName , final VirtualFile deploymentRoot ) { final List < ViewInformation > info = componentsByViewName . get ( viewName ) ; if ( info == null ) { return Collections . < ViewDescription > emptySet ( ) ; } if ( componentName . contains ( \"#\" ) ) { final String [ ] parts = componentName . split ( \"#\" ) ; String path = parts [ 0 ] ; if ( ! path . startsWith ( \"../\" ) ) { path = \"../\" + path ; } final VirtualFile virtualPath = deploymentRoot . getChild ( path ) ; final String name = parts [ 1 ] ; final Set < ViewDescription > ret = new HashSet < ViewDescription > ( ) ; for ( ViewInformation i : info ) { if ( i . beanName . equals ( name ) ) { //now we need to check the path if ( virtualPath . equals ( i . deploymentRoot ) ) { ret . add ( i . viewDescription ) ; } } } return ret ; } else { final Set < ViewDescription > all = new HashSet < ViewDescription > ( ) ; final Set < ViewDescription > thisDeployment = new HashSet < ViewDescription > ( ) ; for ( ViewInformation i : info ) { if ( i . beanName . equals ( componentName ) ) { all . add ( i . viewDescription ) ; if ( i . deploymentRoot . equals ( deploymentRoot ) ) { thisDeployment . add ( i . viewDescription ) ; } } } if ( all . size ( ) > 1 ) { return thisDeployment ; } return all ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves a message destination name into a JNDI name [CODESPLIT] public Set < String > resolveMessageDestination ( final String messageDestName , final VirtualFile deploymentRoot ) { if ( messageDestName . contains ( \"#\" ) ) { final String [ ] parts = messageDestName . split ( \"#\" ) ; String path = parts [ 0 ] ; if ( ! path . startsWith ( \"../\" ) ) { path = \"../\" + path ; } final VirtualFile virtualPath = deploymentRoot . getChild ( path ) ; final String name = parts [ 1 ] ; final Set < String > ret = new HashSet < String > ( ) ; final List < MessageDestinationMapping > data = messageDestinationJndiMapping . get ( name ) ; if ( data != null ) { for ( final MessageDestinationMapping i : data ) { //now we need to check the path if ( virtualPath . equals ( i . deploymentRoot ) ) { ret . add ( i . jndiName ) ; } } } return ret ; } else { final Set < String > all = new HashSet < String > ( ) ; final Set < String > thisDeployment = new HashSet < String > ( ) ; final List < MessageDestinationMapping > data = messageDestinationJndiMapping . get ( messageDestName ) ; if ( data != null ) { for ( final MessageDestinationMapping i : data ) { all . add ( i . jndiName ) ; if ( i . deploymentRoot . equals ( deploymentRoot ) ) { thisDeployment . add ( i . jndiName ) ; } } } if ( all . size ( ) > 1 ) { return thisDeployment ; } return all ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transformation for WildFly 8 . 1 . 0 . Final [CODESPLIT] private static void buildTransformers2_1_0 ( ResourceTransformationDescriptionBuilder builder ) { ResourceTransformationDescriptionBuilder hornetqServer = builder . addChildResource ( pathElement ( HORNETQ_SERVER ) ) ; ResourceTransformationDescriptionBuilder addressSetting = hornetqServer . addChildResource ( AddressSettingDefinition . PATH ) ; rejectDefinedAttributeWithDefaultValue ( addressSetting , MAX_REDELIVERY_DELAY , REDELIVERY_MULTIPLIER ) ; ResourceTransformationDescriptionBuilder bridge = hornetqServer . addChildResource ( BridgeDefinition . PATH ) ; bridge . getAttributeBuilder ( ) . setValueConverter ( new DoubleToBigDecimalConverter ( ) , RETRY_INTERVAL_MULTIPLIER ) ; ResourceTransformationDescriptionBuilder clusterConnection = hornetqServer . addChildResource ( ClusterConnectionDefinition . PATH ) ; clusterConnection . getAttributeBuilder ( ) . setValueConverter ( new DoubleToBigDecimalConverter ( ) , RETRY_INTERVAL_MULTIPLIER ) ; ResourceTransformationDescriptionBuilder connectionFactory = hornetqServer . addChildResource ( ConnectionFactoryDefinition . PATH ) ; connectionFactory . getAttributeBuilder ( ) . setValueConverter ( new DoubleToBigDecimalConverter ( ) , RETRY_INTERVAL_MULTIPLIER ) ; ResourceTransformationDescriptionBuilder pooledConnectionFactory = hornetqServer . addChildResource ( PooledConnectionFactoryDefinition . PATH ) ; pooledConnectionFactory . getAttributeBuilder ( ) . setValueConverter ( new DoubleToBigDecimalConverter ( ) , RETRY_INTERVAL_MULTIPLIER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transformers for EAP 6 . 4 / AS7 7 . 5 . 0 [CODESPLIT] private static void buildTransformers1_4_0 ( ResourceTransformationDescriptionBuilder builder ) { ResourceTransformationDescriptionBuilder hornetqServer = builder . addChildResource ( pathElement ( HORNETQ_SERVER ) ) ; renameAttribute ( hornetqServer , CommonAttributes . STATISTICS_ENABLED , CommonAttributes . MESSAGE_COUNTER_ENABLED ) ; ResourceTransformationDescriptionBuilder bridge = hornetqServer . addChildResource ( BridgeDefinition . PATH ) ; rejectDefinedAttributeWithDefaultValue ( bridge , BridgeDefinition . RECONNECT_ATTEMPTS_ON_SAME_NODE , BridgeDefinition . INITIAL_CONNECT_ATTEMPTS ) ; ResourceTransformationDescriptionBuilder clusterConnection = hornetqServer . addChildResource ( ClusterConnectionDefinition . PATH ) ; rejectDefinedAttributeWithDefaultValue ( clusterConnection , ClusterConnectionDefinition . INITIAL_CONNECT_ATTEMPTS ) ; ResourceTransformationDescriptionBuilder addressSetting = hornetqServer . addChildResource ( AddressSettingDefinition . PATH ) ; rejectDefinedAttributeWithDefaultValue ( addressSetting , AddressSettingDefinition . EXPIRY_DELAY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transformation for EAP 6 . 2 . 0 / AS7 7 . 3 . 0 [CODESPLIT] private static void buildTransformers1_3_0 ( ResourceTransformationDescriptionBuilder builder ) { ResourceTransformationDescriptionBuilder hornetqServer = builder . addChildResource ( pathElement ( HORNETQ_SERVER ) ) ; rejectDefinedAttributeWithDefaultValue ( hornetqServer , OVERRIDE_IN_VM_SECURITY ) ; hornetqServer . rejectChildResource ( HTTPAcceptorDefinition . PATH ) ; hornetqServer . rejectChildResource ( pathElement ( CommonAttributes . HTTP_CONNECTOR ) ) ; ResourceTransformationDescriptionBuilder addressSetting = hornetqServer . addChildResource ( AddressSettingDefinition . PATH ) ; rejectDefinedAttributeWithDefaultValue ( addressSetting , SLOW_CONSUMER_CHECK_PERIOD , SLOW_CONSUMER_POLICY , SLOW_CONSUMER_THRESHOLD ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reject the attributes if they are defined or discard them if they are undefined or set to their default value . [CODESPLIT] private static void rejectDefinedAttributeWithDefaultValue ( ResourceTransformationDescriptionBuilder builder , AttributeDefinition ... attrs ) { for ( AttributeDefinition attr : attrs ) { builder . getAttributeBuilder ( ) . setDiscard ( new DiscardAttributeValueChecker ( attr . getDefaultValue ( ) ) , attr ) . addRejectCheck ( DEFINED , attr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename an attribute [CODESPLIT] private static void renameAttribute ( ResourceTransformationDescriptionBuilder builder , AttributeDefinition attribute , AttributeDefinition alias ) { builder . getAttributeBuilder ( ) . addRename ( attribute , alias . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a { @link Collection } containing the { @link Principal } instances for the user associated with the connection . [CODESPLIT] public static Collection < Principal > getConnectionPrincipals ( ) { RemoteConnection con = RemotingContext . getRemoteConnection ( ) ; if ( con != null ) { Collection < Principal > principals = new HashSet <> ( ) ; SecurityIdentity localIdentity = con . getSecurityIdentity ( ) ; if ( localIdentity != null ) { final Principal principal = localIdentity . getPrincipal ( ) ; final String realm = principal instanceof RealmPrincipal ? ( ( RealmPrincipal ) principal ) . getRealm ( ) : null ; principals . add ( new RealmUser ( realm , principal . getName ( ) ) ) ; for ( String role : localIdentity . getRoles ( ) ) { principals . add ( new RealmGroup ( role ) ) ; principals . add ( new RealmRole ( role ) ) ; } return principals ; } else { return Collections . emptySet ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push a new { @link Principal } and Credential pair . [CODESPLIT] public static ContextStateCache pushIdentity ( final Principal principal , final Object credential ) throws Exception { SecurityContext current = SecurityContextAssociation . getSecurityContext ( ) ; SecurityContext nextContext = SecurityContextFactory . createSecurityContext ( principal , credential , new Subject ( ) , \"USER_DELEGATION\" ) ; SecurityContextAssociation . setSecurityContext ( nextContext ) ; RemoteConnection con = RemotingContext . getRemoteConnection ( ) ; RemotingContext . clear ( ) ; return new ContextStateCache ( con , current ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pop the identity previously associated and restore internal state to it s previous value . [CODESPLIT] public static void popIdentity ( final ContextStateCache stateCache ) { RemotingContext . setConnection ( stateCache . getConnection ( ) ) ; SecurityContextAssociation . setSecurityContext ( stateCache . getSecurityContext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public ManagedReference getReference ( ) { final ClassLoader loader ; try { loader = SecurityActions . getModuleClassLoader ( ) ; } catch ( ModuleLoadException e ) { throw SecurityLogger . ROOT_LOGGER . unableToGetModuleClassLoader ( e ) ; } Class < ? > [ ] interfaces = { Context . class } ; return new ValueManagedReference ( new ImmediateValue < Object > ( Proxy . newProxyInstance ( loader , interfaces , this ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the InvocationHandler callback for the Context interface that was created by our getObjectInstance () method . We handle the java : jboss / jaas / domain level operations here . [CODESPLIT] public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { Context ctx = new InitialContext ( ) ; NameParser parser = ctx . getNameParser ( \"\" ) ; String securityDomain = null ; Name name = null ; final JNDIBasedSecurityManagement securityManagement = JNDIBasedSecurityManagement . class . cast ( securityManagementValue . getValue ( ) ) ; final ConcurrentHashMap < String , SecurityDomainContext > securityManagerMap = securityManagement . getSecurityManagerMap ( ) ; String methodName = method . getName ( ) ; if ( methodName . equals ( \"toString\" ) ) return SecurityConstants . JAAS_CONTEXT_ROOT + \" Context proxy\" ; if ( methodName . equals ( \"list\" ) ) return new DomainEnumeration ( securityManagerMap . keys ( ) , securityManagerMap ) ; if ( methodName . equals ( \"bind\" ) || methodName . equals ( \"rebind\" ) ) { if ( args [ 0 ] instanceof String ) name = parser . parse ( ( String ) args [ 0 ] ) ; else name = ( Name ) args [ 0 ] ; securityDomain = name . get ( 0 ) ; SecurityDomainContext val = ( SecurityDomainContext ) args [ 1 ] ; securityManagerMap . put ( securityDomain , val ) ; return proxy ; } if ( ! methodName . equals ( \"lookup\" ) ) throw SecurityLogger . ROOT_LOGGER . operationNotSupported ( method ) ; if ( args [ 0 ] instanceof String ) name = parser . parse ( ( String ) args [ 0 ] ) ; else name = ( Name ) args [ 0 ] ; securityDomain = name . get ( 0 ) ; SecurityDomainContext securityDomainCtx = lookupSecurityDomain ( securityManagement , securityManagerMap , securityDomain ) ; Object binding = securityDomainCtx . getAuthenticationManager ( ) ; // Look for requests against the security domain context if ( name . size ( ) == 2 ) { String request = name . get ( 1 ) ; binding = lookup ( securityDomainCtx , request ) ; } return binding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @code SecurityDomainContext } if one cannot be found in JNDI for a given security domain [CODESPLIT] private SecurityDomainContext lookupSecurityDomain ( final JNDIBasedSecurityManagement securityManagement , final ConcurrentHashMap < String , SecurityDomainContext > securityManagerMap , final String securityDomain ) throws Exception { SecurityDomainContext sdc = securityManagerMap . get ( securityDomain ) ; if ( sdc == null ) { sdc = securityManagement . createSecurityDomainContext ( securityDomain , new DefaultAuthenticationCacheFactory ( ) ) ; securityManagerMap . put ( securityDomain , sdc ) ; } return sdc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "just provide the default implementations [CODESPLIT] private void loadIdsManually ( ) { implIds . put ( \"main\" , ModuleIdentifier . create ( IMPL_MODULE ) ) ; apiIds . put ( \"main\" , ModuleIdentifier . create ( API_MODULE ) ) ; injectionIds . put ( \"main\" , ModuleIdentifier . create ( INJECTION_MODULE ) ) ; allVersions . add ( \"main\" ) ; activeVersions . add ( \"main\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make sure that each version has api impl and injection [CODESPLIT] private void checkVersionIntegrity ( ) { activeVersions . addAll ( allVersions ) ; for ( String version : allVersions ) { if ( ! apiIds . containsKey ( version ) ) { JSFLogger . ROOT_LOGGER . missingJSFModule ( version , API_MODULE ) ; activeVersions . remove ( version ) ; } if ( ! implIds . containsKey ( version ) ) { JSFLogger . ROOT_LOGGER . missingJSFModule ( version , IMPL_MODULE ) ; activeVersions . remove ( version ) ; } if ( ! injectionIds . containsKey ( version ) ) { JSFLogger . ROOT_LOGGER . missingJSFModule ( version , INJECTION_MODULE ) ; activeVersions . remove ( version ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If needed convert old JSFVersionMarker values to slot values . [CODESPLIT] String computeSlot ( String jsfVersion ) { if ( jsfVersion == null ) return defaultSlot ; if ( JsfVersionMarker . JSF_2_0 . equals ( jsfVersion ) ) return defaultSlot ; return jsfVersion ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( final ExtensionContext context ) { JSFLogger . ROOT_LOGGER . debug ( \"Activating JSF(Mojarra) Extension\" ) ; final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; subsystem . registerSubsystemModel ( JSFResourceDefinition . INSTANCE ) ; subsystem . registerXMLElementWriter ( JSFSubsystemParser_1_1 . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( final ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , JSFExtension . NAMESPACE_1_0 , ( ) -> JSFSubsystemParser_1_0 . INSTANCE ) ; context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , JSFExtension . NAMESPACE_1_1 , ( ) -> JSFSubsystemParser_1_1 . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( StartContext context ) throws StartException { SecurityLogger . ROOT_LOGGER . debugf ( \"Starting SecurityManagementService\" ) ; // set properties of JNDIBasedSecurityManagement JNDIBasedSecurityManagement securityManagement = new JNDIBasedSecurityManagement ( serviceModuleLoaderValue . getValue ( ) ) ; securityManagement . setAuthenticationManagerClassName ( authenticationManagerClassName ) ; securityManagement . setDeepCopySubjectMode ( deepCopySubjectMode ) ; securityManagement . setCallbackHandlerClassName ( callbackHandlerClassName ) ; securityManagement . setAuthorizationManagerClassName ( authorizationManagerClassName ) ; securityManagement . setAuditManagerClassName ( auditManagerClassName ) ; securityManagement . setIdentityTrustManagerClassName ( identityTrustManagerClassName ) ; securityManagement . setMappingManagerClassName ( mappingManagerClassName ) ; this . securityManagement = securityManagement ; previousSecurityManagement = SecurityFactory . getSecurityManagement ( ) ; SecurityFactory . setSecurityManagement ( securityManagement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object getInstance ( ) { ManagedReference managedReference = ( ManagedReference ) getInstanceData ( INSTANCE_KEY ) ; if ( managedReference == null ) { //can happen if around construct chain returns null return null ; } return managedReference . getInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Interceptor getInterceptor ( final Method method ) throws IllegalStateException { Interceptor interceptor = methodMap . get ( method ) ; if ( interceptor == null ) { throw EeLogger . ROOT_LOGGER . methodNotFound ( method ) ; } return interceptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void destroy ( ) { if ( doneUpdater . compareAndSet ( this , 0 , 1 ) ) try { preDestroy ( ) ; final Object instance = getInstance ( ) ; if ( instance != null ) { final InterceptorContext interceptorContext = prepareInterceptorContext ( ) ; interceptorContext . setTarget ( instance ) ; interceptorContext . putPrivateData ( InvocationType . class , InvocationType . PRE_DESTROY ) ; preDestroy . processInvocation ( interceptorContext ) ; } } catch ( Exception e ) { ROOT_LOGGER . componentDestroyFailure ( e , this ) ; } finally { component . finishDestroy ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure password from a credential - reference ( as an alternative to the password attribute ) and add it to the RA properties . [CODESPLIT] private void configureCredential ( List < ConfigProperty > properties ) { // if a credential-reference has been defined, get the password property from it if ( credentialSourceSupplier != null ) { try { CredentialSource credentialSource = credentialSourceSupplier . get ( ) ; if ( credentialSource != null ) { char [ ] password = credentialSource . getCredential ( PasswordCredential . class ) . getPassword ( ClearPassword . class ) . getPassword ( ) ; if ( password != null ) { // add the password property properties . add ( simpleProperty15 ( \"password\" , String . class . getName ( ) , new String ( password ) ) ) ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process SCIs . [CODESPLIT] public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; final ServiceModuleLoader loader = deploymentUnit . getAttachment ( Attachments . SERVICE_MODULE_LOADER ) ; if ( ! DeploymentTypeMarker . isType ( DeploymentType . WAR , deploymentUnit ) ) { return ; // Skip non web deployments } WarMetaData warMetaData = deploymentUnit . getAttachment ( WarMetaData . ATTACHMENT_KEY ) ; assert warMetaData != null ; final Module module = deploymentUnit . getAttachment ( Attachments . MODULE ) ; if ( module == null ) { throw UndertowLogger . ROOT_LOGGER . failedToResolveModule ( deploymentUnit ) ; } final ClassLoader classLoader = module . getClassLoader ( ) ; ScisMetaData scisMetaData = deploymentUnit . getAttachment ( ScisMetaData . ATTACHMENT_KEY ) ; if ( scisMetaData == null ) { scisMetaData = new ScisMetaData ( ) ; deploymentUnit . putAttachment ( ScisMetaData . ATTACHMENT_KEY , scisMetaData ) ; } Set < ServletContainerInitializer > scis = scisMetaData . getScis ( ) ; Set < Class < ? extends ServletContainerInitializer > > sciClasses = new HashSet <> ( ) ; if ( scis == null ) { scis = new LinkedHashSet <> ( ) ; scisMetaData . setScis ( scis ) ; } Map < ServletContainerInitializer , Set < Class < ? > > > handlesTypes = scisMetaData . getHandlesTypes ( ) ; if ( handlesTypes == null ) { handlesTypes = new HashMap < ServletContainerInitializer , Set < Class < ? > > > ( ) ; scisMetaData . setHandlesTypes ( handlesTypes ) ; } // Find the SCIs from shared modules for ( ModuleDependency dependency : moduleSpecification . getAllDependencies ( ) ) { // Should not include SCI if services is not included if ( ! dependency . isImportServices ( ) ) { continue ; } try { Module depModule = loader . loadModule ( dependency . getIdentifier ( ) ) ; ServiceLoader < ServletContainerInitializer > serviceLoader = depModule . loadService ( ServletContainerInitializer . class ) ; for ( ServletContainerInitializer service : serviceLoader ) { if ( sciClasses . add ( service . getClass ( ) ) ) { scis . add ( service ) ; } } } catch ( ModuleLoadException e ) { if ( ! dependency . isOptional ( ) ) { throw UndertowLogger . ROOT_LOGGER . errorLoadingSCIFromModule ( dependency . getIdentifier ( ) . toString ( ) , e ) ; } } } // Find local ServletContainerInitializer services List < String > order = warMetaData . getOrder ( ) ; Map < String , VirtualFile > localScis = warMetaData . getScis ( ) ; if ( order != null && localScis != null ) { for ( String jar : order ) { VirtualFile sci = localScis . get ( jar ) ; if ( sci != null ) { scis . addAll ( loadSci ( classLoader , sci , jar , true , sciClasses ) ) ; } } } //SCI's deployed in the war itself if ( localScis != null ) { VirtualFile warDeployedScis = localScis . get ( \"classes\" ) ; if ( warDeployedScis != null ) { scis . addAll ( loadSci ( classLoader , warDeployedScis , deploymentUnit . getName ( ) , true , sciClasses ) ) ; } } // Process HandlesTypes for ServletContainerInitializer Map < Class < ? > , Set < ServletContainerInitializer > > typesMap = new HashMap < Class < ? > , Set < ServletContainerInitializer > > ( ) ; for ( ServletContainerInitializer service : scis ) { if ( service . getClass ( ) . isAnnotationPresent ( HandlesTypes . class ) ) { HandlesTypes handlesTypesAnnotation = service . getClass ( ) . getAnnotation ( HandlesTypes . class ) ; Class < ? > [ ] typesArray = handlesTypesAnnotation . value ( ) ; if ( typesArray != null ) { for ( Class < ? > type : typesArray ) { Set < ServletContainerInitializer > servicesSet = typesMap . get ( type ) ; if ( servicesSet == null ) { servicesSet = new HashSet < ServletContainerInitializer > ( ) ; typesMap . put ( type , servicesSet ) ; } servicesSet . add ( service ) ; handlesTypes . put ( service , new HashSet < Class < ? > > ( ) ) ; } } } } Class < ? > [ ] typesArray = typesMap . keySet ( ) . toArray ( new Class < ? > [ 0 ] ) ; final CompositeIndex index = deploymentUnit . getAttachment ( Attachments . COMPOSITE_ANNOTATION_INDEX ) ; if ( index == null ) { throw UndertowLogger . ROOT_LOGGER . unableToResolveAnnotationIndex ( deploymentUnit ) ; } final CompositeIndex parent ; if ( deploymentUnit . getParent ( ) != null ) { parent = deploymentUnit . getParent ( ) . getAttachment ( Attachments . COMPOSITE_ANNOTATION_INDEX ) ; } else { parent = null ; } //WFLY-4205, look in the parent as well as the war CompositeIndex parentIndex = deploymentUnit . getParent ( ) == null ? null : deploymentUnit . getParent ( ) . getAttachment ( Attachments . COMPOSITE_ANNOTATION_INDEX ) ; // Find classes which extend, implement, or are annotated by HandlesTypes for ( Class < ? > type : typesArray ) { DotName className = DotName . createSimple ( type . getName ( ) ) ; Set < ClassInfo > classInfos = new HashSet <> ( ) ; classInfos . addAll ( processHandlesType ( className , type , index , parent ) ) ; if ( parentIndex != null ) { classInfos . addAll ( processHandlesType ( className , type , parentIndex , parent ) ) ; } Set < Class < ? > > classes = loadClassInfoSet ( classInfos , classLoader ) ; Set < ServletContainerInitializer > sciSet = typesMap . get ( type ) ; for ( ServletContainerInitializer sci : sciSet ) { handlesTypes . get ( sci ) . addAll ( classes ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the <code > timerService< / code > from the <code > operation< / code > [CODESPLIT] protected void populateModel ( ModelNode operation , ModelNode timerServiceModel ) throws OperationFailedException { for ( AttributeDefinition attr : TimerServiceResourceDefinition . ATTRIBUTES . values ( ) ) { attr . validateAndSet ( operation , timerServiceModel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the TypeCode suitable for an IDL constant . [CODESPLIT] private TypeCode getConstantTypeCode ( Class cls ) throws IRConstructionException { if ( cls == null ) throw IIOPLogger . ROOT_LOGGER . invalidNullClass ( ) ; TypeCode ret = constantTypeCodeMap . get ( cls ) ; if ( ret == null ) throw IIOPLogger . ROOT_LOGGER . badClassForConstant ( cls . getName ( ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the TypeCode IDL TypeCodes for parameter result attribute and value member types . This may provoke a mapping of the class argument . <p / > Exception classes map to both values and exceptions . For these this method returns the typecode for the value and you can use the <code > getExceptionTypeCode< / code > TODO method to get the typecode for the mapping to exception . [CODESPLIT] private TypeCode getTypeCode ( Class cls ) throws IRConstructionException , RMIIIOPViolationException { if ( cls == null ) throw IIOPLogger . ROOT_LOGGER . invalidNullClass ( ) ; TypeCode ret = ( TypeCode ) typeCodeMap . get ( cls ) ; if ( ret == null ) { if ( cls == java . lang . String . class ) ret = getJavaLangString ( ) . type ( ) ; else if ( cls == java . lang . Object . class ) ret = getJavaLang_Object ( ) . type ( ) ; else if ( cls == java . lang . Class . class ) ret = getJavaxRmiCORBAClassDesc ( ) . type ( ) ; else if ( cls == java . io . Serializable . class ) ret = getJavaIoSerializable ( ) . type ( ) ; else if ( cls == java . io . Externalizable . class ) ret = getJavaIoExternalizable ( ) . type ( ) ; else { // Try adding a mapping of the the class to the IR addClass ( cls ) ; // Lookup again, it should be there now. ret = ( TypeCode ) typeCodeMap . get ( cls ) ; if ( ret == null ) throw IIOPLogger . ROOT_LOGGER . unknownTypeCodeForClass ( cls . getName ( ) ) ; else return ret ; } typeCodeMap . put ( cls , ret ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new IDL TypeCode for a mapped class . [CODESPLIT] private void addTypeCode ( Class cls , TypeCode typeCode ) throws IRConstructionException { if ( cls == null ) throw IIOPLogger . ROOT_LOGGER . invalidNullClass ( ) ; TypeCode tc = ( TypeCode ) typeCodeMap . get ( cls ) ; if ( tc != null ) throw IIOPLogger . ROOT_LOGGER . duplicateTypeCodeForClass ( cls . getName ( ) ) ; typeCodeMap . put ( cls , typeCode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a reference to the special case mapping for java . lang . Object . This is according to Java ( TM ) Language to IDL Mapping Specification section 1 . 3 . 10 . 2 [CODESPLIT] private AliasDefImpl getJavaLang_Object ( ) throws IRConstructionException { if ( javaLang_Object == null ) { final String id = \"IDL:java/lang/_Object:1.0\" ; final String name = \"_Object\" ; final String version = \"1.0\" ; // Get module to add typedef to. ModuleDefImpl m = ensurePackageExists ( \"java.lang\" ) ; TypeCode typeCode = orb . create_alias_tc ( id , name , orb . get_primitive_tc ( TCKind . tk_any ) ) ; //         TypeCode typeCode = new TypeCodeImpl(TCKind._tk_alias, id, name, //                                            new TypeCodeImpl(TCKind.tk_any)); javaLang_Object = new AliasDefImpl ( id , name , version , m , typeCode , impl ) ; m . add ( name , javaLang_Object ) ; } return javaLang_Object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a reference to the special case mapping for java . lang . String . This is according to Java ( TM ) Language to IDL Mapping Specification section 1 . 3 . 5 . 10 [CODESPLIT] private ValueDefImpl getJavaLangString ( ) throws IRConstructionException { if ( javaLangString == null ) { ModuleDefImpl m = ensurePackageExists ( \"org.omg.CORBA\" ) ; ValueDefImpl val = new ValueDefImpl ( \"IDL:omg.org/CORBA/WStringValue:1.0\" , \"WStringValue\" , \"1.0\" , m , false , false , new String [ 0 ] , new String [ 0 ] , orb . get_primitive_tc ( TCKind . tk_null ) , impl ) ; ValueMemberDefImpl vmdi = new ValueMemberDefImpl ( \"IDL:omg.org/CORBA/WStringValue.data:1.0\" , \"data\" , \"1.0\" , orb . create_wstring_tc ( 0 ) , true , val , impl ) ; val . add ( \"data\" , vmdi ) ; m . add ( \"WStringValue\" , val ) ; javaLangString = val ; } return javaLangString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a reference to the special case mapping for java . lang . Class . This is according to Java ( TM ) Language to IDL Mapping Specification section 1 . 3 . 5 . 11 . [CODESPLIT] private ValueDefImpl getJavaxRmiCORBAClassDesc ( ) throws IRConstructionException , RMIIIOPViolationException { if ( javaxRmiCORBAClassDesc == null ) { // Just map the right value class ValueAnalysis va = ValueAnalysis . getValueAnalysis ( javax . rmi . CORBA . ClassDesc . class ) ; ValueDefImpl val = addValue ( va ) ; // Warn if it does not conform to the specification. if ( ! \"RMI:javax.rmi.CORBA.ClassDesc:B7C4E3FC9EBDC311:CFBF02CF5294176B\" . equals ( val . id ( ) ) ) IIOPLogger . ROOT_LOGGER . warnClassDescDoesNotConformToSpec ( ) ; javaxRmiCORBAClassDesc = val ; } return javaxRmiCORBAClassDesc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure that a package exists in the IR . This will create modules in the IR as needed . [CODESPLIT] private ModuleDefImpl ensurePackageExists ( LocalContainer c , String previous , String remainder ) throws IRConstructionException { if ( \"\" . equals ( remainder ) ) return ( ModuleDefImpl ) c ; // done int idx = remainder . indexOf ( ' ' ) ; String base ; if ( idx == - 1 ) base = remainder ; else base = remainder . substring ( 0 , idx ) ; base = Util . javaToIDLName ( base ) ; if ( previous . equals ( \"\" ) ) previous = base ; else previous = previous + \"/\" + base ; if ( idx == - 1 ) remainder = \"\" ; else remainder = remainder . substring ( idx + 1 ) ; LocalContainer next = null ; LocalContained contained = ( LocalContained ) c . _lookup ( base ) ; if ( contained instanceof LocalContainer ) next = ( LocalContainer ) contained ; else if ( contained != null ) throw IIOPLogger . ROOT_LOGGER . collisionWhileCreatingPackage ( ) ; if ( next == null ) { String id = \"IDL:\" + previous + \":1.0\" ; // Create module ModuleDefImpl m = new ModuleDefImpl ( id , base , \"1.0\" , c , impl ) ; c . add ( base , m ) ; if ( idx == - 1 ) return m ; // done next = ( LocalContainer ) c . _lookup ( base ) ; // Better be there now... } else // Check that next _is_ a module if ( next . def_kind ( ) != DefinitionKind . dk_Module ) throw IIOPLogger . ROOT_LOGGER . collisionWhileCreatingPackage ( ) ; return ensurePackageExists ( next , previous , remainder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a set of constants to a container ( interface or value class ) . [CODESPLIT] private void addConstants ( LocalContainer container , ContainerAnalysis ca ) throws RMIIIOPViolationException , IRConstructionException { ConstantAnalysis [ ] consts = ca . getConstants ( ) ; for ( int i = 0 ; i < consts . length ; ++ i ) { ConstantDefImpl cDef ; String cid = ca . getMemberRepositoryId ( consts [ i ] . getJavaName ( ) ) ; String cName = consts [ i ] . getIDLName ( ) ; Class cls = consts [ i ] . getType ( ) ; TypeCode typeCode = getConstantTypeCode ( cls ) ; Any value = orb . create_any ( ) ; consts [ i ] . insertValue ( value ) ; cDef = new ConstantDefImpl ( cid , cName , \"1.0\" , typeCode , value , container , impl ) ; container . add ( cName , cDef ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a set of attributes to a container ( interface or value class ) . [CODESPLIT] private void addAttributes ( LocalContainer container , ContainerAnalysis ca ) throws RMIIIOPViolationException , IRConstructionException { AttributeAnalysis [ ] attrs = ca . getAttributes ( ) ; for ( int i = 0 ; i < attrs . length ; ++ i ) { AttributeDefImpl aDef ; String aid = ca . getMemberRepositoryId ( attrs [ i ] . getJavaName ( ) ) ; String aName = attrs [ i ] . getIDLName ( ) ; Class cls = attrs [ i ] . getCls ( ) ; TypeCode typeCode = getTypeCode ( cls ) ; aDef = new AttributeDefImpl ( aid , aName , \"1.0\" , attrs [ i ] . getMode ( ) , typeCode , container , impl ) ; container . add ( aName , aDef ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a set of operations to a container ( interface or value class ) . [CODESPLIT] private void addOperations ( LocalContainer container , ContainerAnalysis ca ) throws RMIIIOPViolationException , IRConstructionException { OperationAnalysis [ ] ops = ca . getOperations ( ) ; for ( int i = 0 ; i < ops . length ; ++ i ) { OperationDefImpl oDef ; String oName = ops [ i ] . getIDLName ( ) ; String oid = ca . getMemberRepositoryId ( oName ) ; Class cls = ops [ i ] . getReturnType ( ) ; TypeCode typeCode = getTypeCode ( cls ) ; ParameterAnalysis [ ] ps = ops [ i ] . getParameters ( ) ; ParameterDescription [ ] params = new ParameterDescription [ ps . length ] ; for ( int j = 0 ; j < ps . length ; ++ j ) { params [ j ] = new ParameterDescription ( ps [ j ] . getIDLName ( ) , getTypeCode ( ps [ j ] . getCls ( ) ) , null , // filled in later ParameterMode . PARAM_IN ) ; } ExceptionAnalysis [ ] exc = ops [ i ] . getMappedExceptions ( ) ; ExceptionDef [ ] exceptions = new ExceptionDef [ exc . length ] ; for ( int j = 0 ; j < exc . length ; ++ j ) { ExceptionDefImpl e = addException ( exc [ j ] ) ; exceptions [ j ] = ExceptionDefHelper . narrow ( e . getReference ( ) ) ; } oDef = new OperationDefImpl ( oid , oName , \"1.0\" , container , typeCode , params , exceptions , impl ) ; container . add ( oName , oDef ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a set of interfaces to the IR . [CODESPLIT] private String [ ] addInterfaces ( ContainerAnalysis ca ) throws RMIIIOPViolationException , IRConstructionException { InterfaceAnalysis [ ] interfaces = ca . getInterfaces ( ) ; List base_interfaces = new ArrayList ( ) ; for ( int i = 0 ; i < interfaces . length ; ++ i ) { InterfaceDefImpl idi = addInterface ( interfaces [ i ] ) ; base_interfaces . add ( idi . id ( ) ) ; } String [ ] strArr = new String [ base_interfaces . size ( ) ] ; return ( String [ ] ) base_interfaces . toArray ( strArr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a set of abstract valuetypes to the IR . [CODESPLIT] private String [ ] addAbstractBaseValuetypes ( ContainerAnalysis ca ) throws RMIIIOPViolationException , IRConstructionException { ValueAnalysis [ ] abstractValuetypes = ca . getAbstractBaseValuetypes ( ) ; List abstract_base_valuetypes = new ArrayList ( ) ; for ( int i = 0 ; i < abstractValuetypes . length ; ++ i ) { ValueDefImpl vdi = addValue ( abstractValuetypes [ i ] ) ; abstract_base_valuetypes . add ( vdi . id ( ) ) ; } String [ ] strArr = new String [ abstract_base_valuetypes . size ( ) ] ; return ( String [ ] ) abstract_base_valuetypes . toArray ( strArr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the class and add its IIOP mapping to the repository . [CODESPLIT] private void addClass ( Class cls ) throws RMIIIOPViolationException , IRConstructionException { if ( cls . isPrimitive ( ) ) return ; // No need to add primitives. if ( cls . isArray ( ) ) { // Add array mapping addArray ( cls ) ; } else if ( cls . isInterface ( ) ) { if ( ! RmiIdlUtil . isAbstractValueType ( cls ) ) { // Analyse the interface InterfaceAnalysis ia = InterfaceAnalysis . getInterfaceAnalysis ( cls ) ; // Add analyzed interface (which may be abstract) addInterface ( ia ) ; } else { // Analyse the value ValueAnalysis va = ValueAnalysis . getValueAnalysis ( cls ) ; // Add analyzed value addValue ( va ) ; } } else if ( Exception . class . isAssignableFrom ( cls ) ) { // Exception type. // Analyse the exception ExceptionAnalysis ea = ExceptionAnalysis . getExceptionAnalysis ( cls ) ; // Add analyzed exception addException ( ea ) ; } else { // Got to be a value type. // Analyse the value ValueAnalysis va = ValueAnalysis . getValueAnalysis ( cls ) ; // Add analyzed value addValue ( va ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an array . [CODESPLIT] private ValueBoxDefImpl addArray ( Class cls ) throws RMIIIOPViolationException , IRConstructionException { if ( ! cls . isArray ( ) ) throw IIOPLogger . ROOT_LOGGER . classIsNotArray ( cls . getName ( ) ) ; ValueBoxDefImpl vbDef ; // Lookup: Has it already been added? vbDef = ( ValueBoxDefImpl ) arrayMap . get ( cls ) ; if ( vbDef != null ) return vbDef ; // Yes, just return it. int dimensions = 0 ; Class compType = cls ; do { compType = compType . getComponentType ( ) ; ++ dimensions ; } while ( compType . isArray ( ) ) ; String typeName ; String moduleName ; TypeCode typeCode ; if ( compType . isPrimitive ( ) ) { if ( compType == Boolean . TYPE ) { typeName = \"boolean\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_boolean ) ; } else if ( compType == Character . TYPE ) { typeName = \"wchar\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_wchar ) ; } else if ( compType == Byte . TYPE ) { typeName = \"octet\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_octet ) ; } else if ( compType == Short . TYPE ) { typeName = \"short\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_short ) ; } else if ( compType == Integer . TYPE ) { typeName = \"long\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_long ) ; } else if ( compType == Long . TYPE ) { typeName = \"long_long\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_longlong ) ; } else if ( compType == Float . TYPE ) { typeName = \"float\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_float ) ; } else if ( compType == Double . TYPE ) { typeName = \"double\" ; typeCode = orb . get_primitive_tc ( TCKind . tk_double ) ; } else { throw IIOPLogger . ROOT_LOGGER . unknownPrimitiveType ( compType . getName ( ) ) ; } moduleName = \"org.omg.boxedRMI\" ; } else { typeCode = getTypeCode ( compType ) ; // map the component type. if ( compType == java . lang . String . class ) typeName = getJavaLangString ( ) . name ( ) ; else if ( compType == java . lang . Object . class ) typeName = getJavaLang_Object ( ) . name ( ) ; else if ( compType == java . lang . Class . class ) typeName = getJavaxRmiCORBAClassDesc ( ) . name ( ) ; else if ( compType == java . io . Serializable . class ) typeName = getJavaIoSerializable ( ) . name ( ) ; else if ( compType == java . io . Externalizable . class ) typeName = getJavaIoExternalizable ( ) . name ( ) ; else if ( compType . isInterface ( ) && ! RmiIdlUtil . isAbstractValueType ( compType ) ) typeName = ( ( InterfaceDefImpl ) interfaceMap . get ( compType ) ) . name ( ) ; else if ( Exception . class . isAssignableFrom ( compType ) ) // exception type typeName = ( ( ExceptionDefImpl ) exceptionMap . get ( compType ) ) . name ( ) ; else // must be value type typeName = ( ( ValueDefImpl ) valueMap . get ( compType ) ) . name ( ) ; moduleName = \"org.omg.boxedRMI.\" + compType . getPackage ( ) . getName ( ) ; } // Get module to add array to. ModuleDefImpl m = ensurePackageExists ( moduleName ) ; // Create an array of the types for the dimensions Class [ ] types = new Class [ dimensions ] ; types [ dimensions - 1 ] = cls ; for ( int i = dimensions - 2 ; i >= 0 ; -- i ) types [ i ] = types [ i + 1 ] . getComponentType ( ) ; // Create boxed sequences for all dimensions. for ( int i = 0 ; i < dimensions ; ++ i ) { Class type = types [ i ] ; typeCode = orb . create_sequence_tc ( 0 , typeCode ) ; vbDef = ( ValueBoxDefImpl ) arrayMap . get ( type ) ; if ( vbDef == null ) { String id = Util . getIRIdentifierOfClass ( type ) ; SequenceDefImpl sdi = new SequenceDefImpl ( typeCode , impl ) ; String name = \"seq\" + ( i + 1 ) + \"_\" + typeName ; //            TypeCode boxTypeCode = new TypeCodeImpl(TCKind._tk_value_box, //                                                    id, name, typeCode); TypeCode boxTypeCode = orb . create_value_box_tc ( id , name , typeCode ) ; vbDef = new ValueBoxDefImpl ( id , name , \"1.0\" , m , boxTypeCode , impl ) ; addTypeCode ( type , vbDef . type ( ) ) ; m . add ( name , vbDef ) ; impl . putSequenceImpl ( id , typeCode , sdi , vbDef ) ; arrayMap . put ( type , vbDef ) ; // Remember we mapped this. typeCode = boxTypeCode ; } else typeCode = vbDef . type ( ) ; } // Return the box of highest dimension. return vbDef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an interface . [CODESPLIT] private InterfaceDefImpl addInterface ( InterfaceAnalysis ia ) throws RMIIIOPViolationException , IRConstructionException { InterfaceDefImpl iDef ; Class cls = ia . getCls ( ) ; // Lookup: Has it already been added? iDef = ( InterfaceDefImpl ) interfaceMap . get ( cls ) ; if ( iDef != null ) return iDef ; // Yes, just return it. // Get module to add interface to. ModuleDefImpl m = ensurePackageExists ( cls . getPackage ( ) . getName ( ) ) ; // Add superinterfaces String [ ] base_interfaces = addInterfaces ( ia ) ; // Create the interface String base = cls . getName ( ) ; base = base . substring ( base . lastIndexOf ( ' ' ) + 1 ) ; base = Util . javaToIDLName ( base ) ; iDef = new InterfaceDefImpl ( ia . getRepositoryId ( ) , base , \"1.0\" , m , base_interfaces , impl ) ; addTypeCode ( cls , iDef . type ( ) ) ; m . add ( base , iDef ) ; interfaceMap . put ( cls , iDef ) ; // Remember we mapped this. // Fill in constants addConstants ( iDef , ia ) ; // Add attributes addAttributes ( iDef , ia ) ; // Fill in operations addOperations ( iDef , ia ) ; return iDef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a value type . [CODESPLIT] private ValueDefImpl addValue ( ValueAnalysis va ) throws RMIIIOPViolationException , IRConstructionException { ValueDefImpl vDef ; Class cls = va . getCls ( ) ; // Lookup: Has it already been added? vDef = ( ValueDefImpl ) valueMap . get ( cls ) ; if ( vDef != null ) return vDef ; // Yes, just return it. // Get module to add value to. ModuleDefImpl m = ensurePackageExists ( cls . getPackage ( ) . getName ( ) ) ; // Add implemented interfaces String [ ] supported_interfaces = addInterfaces ( va ) ; // Add abstract base valuetypes String [ ] abstract_base_valuetypes = addAbstractBaseValuetypes ( va ) ; // Add superclass ValueDefImpl superValue = null ; ValueAnalysis superAnalysis = va . getSuperAnalysis ( ) ; if ( superAnalysis != null ) superValue = addValue ( superAnalysis ) ; // Create the value String base = cls . getName ( ) ; base = base . substring ( base . lastIndexOf ( ' ' ) + 1 ) ; base = Util . javaToIDLName ( base ) ; TypeCode baseTypeCode ; if ( superValue == null ) baseTypeCode = orb . get_primitive_tc ( TCKind . tk_null ) ; else baseTypeCode = superValue . type ( ) ; vDef = new ValueDefImpl ( va . getRepositoryId ( ) , base , \"1.0\" , m , va . isAbstractValue ( ) , va . isCustom ( ) , supported_interfaces , abstract_base_valuetypes , baseTypeCode , impl ) ; addTypeCode ( cls , vDef . type ( ) ) ; m . add ( base , vDef ) ; valueMap . put ( cls , vDef ) ; // Remember we mapped this. // Fill in constants. addConstants ( vDef , va ) ; // Add value members ValueMemberAnalysis [ ] vmas = va . getMembers ( ) ; for ( int i = 0 ; i < vmas . length ; ++ i ) { ValueMemberDefImpl vmDef ; String vmid = va . getMemberRepositoryId ( vmas [ i ] . getJavaName ( ) ) ; String vmName = vmas [ i ] . getIDLName ( ) ; Class vmCls = vmas [ i ] . getCls ( ) ; TypeCode typeCode = getTypeCode ( vmCls ) ; boolean vmPublic = vmas [ i ] . isPublic ( ) ; vmDef = new ValueMemberDefImpl ( vmid , vmName , \"1.0\" , typeCode , vmPublic , vDef , impl ) ; vDef . add ( vmName , vmDef ) ; } // Add attributes addAttributes ( vDef , va ) ; // TODO: Fill in operations. return vDef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an exception type . [CODESPLIT] private ExceptionDefImpl addException ( ExceptionAnalysis ea ) throws RMIIIOPViolationException , IRConstructionException { ExceptionDefImpl eDef ; Class cls = ea . getCls ( ) ; // Lookup: Has it already been added? eDef = ( ExceptionDefImpl ) exceptionMap . get ( cls ) ; if ( eDef != null ) return eDef ; // Yes, just return it. // 1.3.7.1: map to value ValueDefImpl vDef = addValue ( ea ) ; // 1.3.7.2: map to exception ModuleDefImpl m = ensurePackageExists ( cls . getPackage ( ) . getName ( ) ) ; String base = cls . getName ( ) ; base = base . substring ( base . lastIndexOf ( ' ' ) + 1 ) ; if ( base . endsWith ( \"Exception\" ) ) base = base . substring ( 0 , base . length ( ) - 9 ) ; base = Util . javaToIDLName ( base + \"Ex\" ) ; StructMember [ ] members = new StructMember [ 1 ] ; members [ 0 ] = new StructMember ( \"value\" , vDef . type ( ) , null /*ignored*/ ) ; TypeCode typeCode = orb . create_exception_tc ( ea . getExceptionRepositoryId ( ) , base , members ) ; eDef = new ExceptionDefImpl ( ea . getExceptionRepositoryId ( ) , base , \"1.0\" , typeCode , vDef , m , impl ) ; m . add ( base , eDef ) ; exceptionMap . put ( cls , eDef ) ; // Remember we mapped this. return eDef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on the the annotation type its either entitymanager or entitymanagerfactory [CODESPLIT] private String getClassLevelInjectionType ( final AnnotationInstance annotation ) { boolean isPC = annotation . name ( ) . local ( ) . equals ( \"PersistenceContext\" ) ; return isPC ? ENTITY_MANAGER_CLASS : ENTITY_MANAGERFACTORY_CLASS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO this could be moved to a separate DeploymentUnitProcessor operating on endpoints ( together with the rest of the config resolution mechanism ) [CODESPLIT] private void registerConfigMapping ( String endpointClassName , EndpointConfig config , DeploymentUnit unit ) { WSEndpointConfigMapping mapping = unit . getAttachment ( WSAttachmentKeys . WS_ENDPOINT_CONFIG_MAPPING_KEY ) ; if ( mapping == null ) { mapping = new WSEndpointConfigMapping ( ) ; unit . putAttachment ( WSAttachmentKeys . WS_ENDPOINT_CONFIG_MAPPING_KEY , mapping ) ; } mapping . registerEndpointConfig ( endpointClassName , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not necessary . [CODESPLIT] private boolean checkJtsEnabled ( final OperationContext context ) { try { final ModelNode jtsNode = context . readResourceFromRoot ( PathAddress . pathAddress ( \"subsystem\" , \"transactions\" ) , false ) . getModel ( ) . get ( \"jts\" ) ; return jtsNode . isDefined ( ) ? jtsNode . asBoolean ( ) : false ; } catch ( NoSuchResourceException ex ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the naming store if not provided by the constructor . [CODESPLIT] public void start ( final StartContext context ) throws StartException { if ( store == null ) { final ServiceRegistry serviceRegistry = context . getController ( ) . getServiceContainer ( ) ; final ServiceName serviceNameBase = context . getController ( ) . getName ( ) ; final ServiceTarget serviceTarget = context . getChildTarget ( ) ; store = readOnly ? new ServiceBasedNamingStore ( serviceRegistry , serviceNameBase ) : new WritableServiceBasedNamingStore ( serviceRegistry , serviceNameBase , serviceTarget ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroys the naming store . [CODESPLIT] public void stop ( StopContext context ) { if ( store != null ) { try { store . close ( ) ; store = null ; } catch ( NamingException e ) { throw NamingLogger . ROOT_LOGGER . failedToDestroyRootContext ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void validateParameter ( String parameterName , ModelNode value ) throws OperationFailedException { super . validateParameter ( parameterName , value ) ; if ( value . isDefined ( ) && value . getType ( ) != ModelType . EXPRESSION ) { String address = value . asString ( ) ; if ( address . startsWith ( \"[\" ) && address . endsWith ( \"]\" ) ) { address = address . substring ( 1 , address . length ( ) - 1 ) ; } if ( ! AddressUtils . isValidAddress ( address ) ) { throw new OperationFailedException ( Messages . MESSAGES . invalidAddressProvided ( address ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ModuleLoader moduleLoader = Module . getBootModuleLoader ( ) ; final ModuleSpecification moduleSpecification = deploymentUnit . getAttachment ( Attachments . MODULE_SPECIFICATION ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , PICKETBOX_ID , false , false , false , false ) ) ; //add the remoting login module final ModuleDependency remoting = new ModuleDependency ( moduleLoader , REMOTING_LOGIN_MODULE , false , false , false , false ) ; remoting . addImportFilter ( PathFilters . is ( RemotingLoginModule . class . getName ( ) . replace ( \".\" , \"/\" ) ) , true ) ; moduleSpecification . addSystemDependency ( remoting ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , JACC_API , false , false , true , false ) ) ; moduleSpecification . addSystemDependency ( new ModuleDependency ( moduleLoader , AUTH_MESSAGE_API , false , false , true , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Configure the STS Token Providers . < / p > [CODESPLIT] private void configureTokenProviders ( ) { STSType stsType = getFederationService ( ) . getValue ( ) . getStsType ( ) ; if ( stsType != null ) { int tokenTimeout = stsType . getTokenTimeout ( ) ; int clockSkew = stsType . getClockSkew ( ) ; STSType providerStsType = getPicketLinkType ( ) . getStsType ( ) ; providerStsType . setTokenTimeout ( tokenTimeout ) ; providerStsType . setClockSkew ( clockSkew ) ; List < TokenProviderType > tokenProviders = providerStsType . getTokenProviders ( ) . getTokenProvider ( ) ; for ( TokenProviderType tokenProviderType : tokenProviders ) { if ( tokenProviderType . getTokenType ( ) . equals ( JBossSAMLURIConstants . ASSERTION_NSURI . get ( ) ) ) { KeyValueType keyValueTypeTokenTimeout = new KeyValueType ( ) ; keyValueTypeTokenTimeout . setKey ( GeneralConstants . ASSERTIONS_VALIDITY ) ; keyValueTypeTokenTimeout . setValue ( String . valueOf ( tokenTimeout ) ) ; KeyValueType keyValueTypeClockSkew = new KeyValueType ( ) ; keyValueTypeClockSkew . setKey ( GeneralConstants . CLOCK_SKEW ) ; keyValueTypeClockSkew . setValue ( String . valueOf ( clockSkew ) ) ; tokenProviderType . add ( keyValueTypeTokenTimeout ) ; tokenProviderType . add ( keyValueTypeClockSkew ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Configure the SAML Handlers . < / p > [CODESPLIT] private void configureHandlers ( ) { Handlers actualHandlers = new Handlers ( ) ; actualHandlers . setHandlers ( new ArrayList < Handler > ( ) ) ; if ( this . handlers . isEmpty ( ) ) { for ( Class < ? extends SAML2Handler > commonHandlerClass : getDefaultHandlers ( ) ) { addHandler ( commonHandlerClass , actualHandlers ) ; } } else { for ( Handler handler : this . handlers ) { actualHandlers . add ( handler ) ; } } getPicketLinkType ( ) . setHandlers ( actualHandlers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the current method [CODESPLIT] public static void checkAllowed ( final MethodType methodType ) { final InterceptorContext context = CurrentInvocationContext . get ( ) ; if ( context == null ) { return ; } final Component component = context . getPrivateData ( Component . class ) ; if ( ! ( component instanceof EJBComponent ) ) { return ; } final InvocationType invocationType = context . getPrivateData ( InvocationType . class ) ; ( ( EJBComponent ) component ) . getAllowedMethodsInformation ( ) . realCheckPermission ( methodType , invocationType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transaction sync is not affected by the current invocation as multiple ejb methods may be invoked from afterCompletion [CODESPLIT] private void checkTransactionSync ( MethodType methodType ) { //first we have to check the synchronization status //as the sync is not affected by the current invocation final CurrentSynchronizationCallback . CallbackType currentSync = CurrentSynchronizationCallback . get ( ) ; if ( currentSync != null ) { if ( deniedSyncMethods . contains ( new DeniedSyncMethodKey ( currentSync , methodType ) ) ) { throwException ( methodType , currentSync ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "throw an exception when a method cannot be invoked [CODESPLIT] protected void throwException ( MethodType methodType , InvocationType invocationType ) { throw EjbLogger . ROOT_LOGGER . cannotCallMethod ( methodType . getLabel ( ) , invocationType . getLabel ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "throw an exception when a method cannot be invoked [CODESPLIT] protected void throwException ( MethodType methodType , CurrentSynchronizationCallback . CallbackType callback ) { throw EjbLogger . ROOT_LOGGER . cannotCallMethod ( methodType . getLabel ( ) , callback . name ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to obtain the security domain configured in jboss - app . xml at the ear level if available [CODESPLIT] private String getJBossAppSecurityDomain ( final DeploymentUnit deploymentUnit ) { String securityDomain = null ; DeploymentUnit parent = deploymentUnit . getParent ( ) ; if ( parent != null ) { final EarMetaData jbossAppMetaData = parent . getAttachment ( Attachments . EAR_METADATA ) ; if ( jbossAppMetaData instanceof JBossAppMetaData ) { securityDomain = ( ( JBossAppMetaData ) jbossAppMetaData ) . getSecurityDomain ( ) ; } } return securityDomain ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets all classes that are eligible for injection etc [CODESPLIT] private Set < String > getAllComponentClasses ( DeploymentUnit deploymentUnit , CompositeIndex index , WarMetaData metaData , TldsMetaData tldsMetaData ) { final Set < String > classes = new HashSet < String > ( ) ; getAllComponentClasses ( metaData . getMergedJBossWebMetaData ( ) , classes ) ; if ( tldsMetaData == null ) return classes ; if ( tldsMetaData . getSharedTlds ( deploymentUnit ) != null ) for ( TldMetaData tldMetaData : tldsMetaData . getSharedTlds ( deploymentUnit ) ) { getAllComponentClasses ( tldMetaData , classes ) ; } if ( tldsMetaData . getTlds ( ) != null ) for ( Map . Entry < String , TldMetaData > tldMetaData : tldsMetaData . getTlds ( ) . entrySet ( ) ) { getAllComponentClasses ( tldMetaData . getValue ( ) , classes ) ; } getAllAsyncListenerClasses ( index , classes ) ; return classes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createCalendarTimer ( ScheduleExpression schedule ) throws IllegalArgumentException , IllegalStateException , EJBException { return this . createCalendarTimer ( schedule , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createCalendarTimer ( ScheduleExpression schedule , TimerConfig timerConfig ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; Serializable info = timerConfig == null ? null : timerConfig . getInfo ( ) ; boolean persistent = timerConfig == null || timerConfig . isPersistent ( ) ; return this . createCalendarTimer ( schedule , info , persistent , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createIntervalTimer ( Date initialExpiration , long intervalDuration , TimerConfig timerConfig ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( initialExpiration == null ) { throw EJB3_TIMER_LOGGER . initialExpirationIsNullCreatingTimer ( ) ; } if ( initialExpiration . getTime ( ) < 0 ) { throw EJB3_TIMER_LOGGER . invalidInitialExpiration ( \"initialExpiration.getTime()\" ) ; } if ( intervalDuration < 0 ) { throw EJB3_TIMER_LOGGER . invalidInitialExpiration ( \"intervalDuration\" ) ; } return this . createTimer ( initialExpiration , intervalDuration , timerConfig . getInfo ( ) , timerConfig . isPersistent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createIntervalTimer ( long initialDuration , long intervalDuration , TimerConfig timerConfig ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( initialDuration < 0 ) { throw EJB3_TIMER_LOGGER . invalidInitialExpiration ( \"intervalDuration\" ) ; } if ( intervalDuration < 0 ) { throw EJB3_TIMER_LOGGER . invalidInitialExpiration ( \"intervalDuration\" ) ; } return this . createIntervalTimer ( new Date ( System . currentTimeMillis ( ) + initialDuration ) , intervalDuration , timerConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createSingleActionTimer ( Date expiration , TimerConfig timerConfig ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( expiration == null ) { throw EJB3_TIMER_LOGGER . expirationIsNull ( ) ; } if ( expiration . getTime ( ) < 0 ) { throw EJB3_TIMER_LOGGER . invalidExpirationActionTimer ( ) ; } return this . createTimer ( expiration , 0 , timerConfig . getInfo ( ) , timerConfig . isPersistent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createSingleActionTimer ( long duration , TimerConfig timerConfig ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( duration < 0 ) throw EJB3_TIMER_LOGGER . invalidDurationActionTimer ( ) ; return createTimer ( new Date ( System . currentTimeMillis ( ) + duration ) , 0 , timerConfig . getInfo ( ) , timerConfig . isPersistent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createTimer ( long duration , Serializable info ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( duration < 0 ) throw EJB3_TIMER_LOGGER . invalidDurationTimer ( ) ; return createTimer ( new Date ( System . currentTimeMillis ( ) + duration ) , 0 , info , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createTimer ( Date expiration , Serializable info ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( expiration == null ) { throw EJB3_TIMER_LOGGER . expirationDateIsNull ( ) ; } if ( expiration . getTime ( ) < 0 ) { throw EJB3_TIMER_LOGGER . invalidExpirationTimer ( ) ; } return this . createTimer ( expiration , 0 , info , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createTimer ( long initialDuration , long intervalDuration , Serializable info ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( initialDuration < 0 ) { throw EJB3_TIMER_LOGGER . invalidInitialDurationTimer ( ) ; } if ( intervalDuration < 0 ) { throw EJB3_TIMER_LOGGER . invalidIntervalTimer ( ) ; } return this . createTimer ( new Date ( System . currentTimeMillis ( ) + initialDuration ) , intervalDuration , info , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Timer createTimer ( Date initialExpiration , long intervalDuration , Serializable info ) throws IllegalArgumentException , IllegalStateException , EJBException { assertTimerServiceState ( ) ; if ( initialExpiration == null ) { throw EJB3_TIMER_LOGGER . initialExpirationDateIsNull ( ) ; } if ( initialExpiration . getTime ( ) < 0 ) { throw EJB3_TIMER_LOGGER . invalidExpirationTimer ( ) ; } if ( intervalDuration < 0 ) { throw EJB3_TIMER_LOGGER . invalidIntervalDurationTimer ( ) ; } return this . createTimer ( initialExpiration , intervalDuration , info , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Collection < Timer > getTimers ( ) throws IllegalStateException , EJBException { assertTimerServiceState ( ) ; Object pk = currentPrimaryKey ( ) ; final Set < Timer > activeTimers = new HashSet < Timer > ( ) ; // get all active timers for this timerservice synchronized ( this . timers ) { for ( final TimerImpl timer : this . timers . values ( ) ) { // Less disruptive way to get WFLY-8457 fixed. if ( timer . isActive ( ) || ( ! timer . isActive ( ) && timer . getState ( ) == TimerState . ACTIVE ) ) { if ( timer . getPrimaryKey ( ) == null || timer . getPrimaryKey ( ) . equals ( pk ) ) { activeTimers . add ( timer ) ; } } } } // get all active timers which are persistent, but haven't yet been // persisted (waiting for tx to complete) that are in the current transaction for ( final TimerImpl timer : getWaitingOnTxCompletionTimers ( ) . values ( ) ) { if ( timer . isActive ( ) ) { if ( timer . getPrimaryKey ( ) == null || timer . getPrimaryKey ( ) . equals ( pk ) ) { activeTimers . add ( timer ) ; } } } return activeTimers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Collection < Timer > getAllTimers ( ) throws IllegalStateException , EJBException { // query the registry if ( this . timerServiceRegistry != null ) { return this . timerServiceRegistry . getAllActiveTimers ( ) ; } // if we don't have the registry (shouldn't really happen) which stores the timer services applicable for the EJB module to which // this timer service belongs, then let's at least return the active timers that are applicable only for this timer service return this . getTimers ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link javax . ejb . Timer } [CODESPLIT] private Timer createTimer ( Date initialExpiration , long intervalDuration , Serializable info , boolean persistent ) { if ( this . isLifecycleCallbackInvocation ( ) && ! this . isSingletonBeanInvocation ( ) ) { throw EJB3_TIMER_LOGGER . failToCreateTimerDoLifecycle ( ) ; } if ( initialExpiration == null ) { throw EJB3_TIMER_LOGGER . initialExpirationIsNull ( ) ; } if ( intervalDuration < 0 ) { throw EJB3_TIMER_LOGGER . invalidIntervalDuration ( ) ; } // create an id for the new timer instance UUID uuid = UUID . randomUUID ( ) ; // create the timer TimerImpl timer = TimerImpl . builder ( ) . setNewTimer ( true ) . setId ( uuid . toString ( ) ) . setInitialDate ( initialExpiration ) . setRepeatInterval ( intervalDuration ) . setInfo ( info ) . setPersistent ( persistent ) . setPrimaryKey ( currentPrimaryKey ( ) ) . setTimerState ( TimerState . CREATED ) . setTimedObjectId ( getInvoker ( ) . getTimedObjectId ( ) ) . build ( this ) ; // now \"start\" the timer. This involves, moving the timer to an ACTIVE state // and scheduling the timer task this . persistTimer ( timer , true ) ; this . startTimer ( timer ) ; // return the newly created timer return timer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a calendar based { @link javax . ejb . Timer } [CODESPLIT] private TimerImpl createCalendarTimer ( ScheduleExpression schedule , Serializable info , boolean persistent , Method timeoutMethod ) { if ( this . isLifecycleCallbackInvocation ( ) && ! this . isSingletonBeanInvocation ( ) ) { throw EJB3_TIMER_LOGGER . failToCreateTimerDoLifecycle ( ) ; } if ( schedule == null ) { throw EJB3_TIMER_LOGGER . scheduleIsNull ( ) ; } // generate an id for the timer UUID uuid = UUID . randomUUID ( ) ; // create the timer TimerImpl timer = CalendarTimer . builder ( ) . setAutoTimer ( timeoutMethod != null ) . setScheduleExprSecond ( schedule . getSecond ( ) ) . setScheduleExprMinute ( schedule . getMinute ( ) ) . setScheduleExprHour ( schedule . getHour ( ) ) . setScheduleExprDayOfWeek ( schedule . getDayOfWeek ( ) ) . setScheduleExprDayOfMonth ( schedule . getDayOfMonth ( ) ) . setScheduleExprMonth ( schedule . getMonth ( ) ) . setScheduleExprYear ( schedule . getYear ( ) ) . setScheduleExprStartDate ( schedule . getStart ( ) ) . setScheduleExprEndDate ( schedule . getEnd ( ) ) . setScheduleExprTimezone ( schedule . getTimezone ( ) ) . setTimeoutMethod ( timeoutMethod ) . setTimerState ( TimerState . CREATED ) . setId ( uuid . toString ( ) ) . setPersistent ( persistent ) . setPrimaryKey ( currentPrimaryKey ( ) ) . setTimedObjectId ( getInvoker ( ) . getTimedObjectId ( ) ) . setInfo ( info ) . setNewTimer ( true ) . build ( this ) ; this . persistTimer ( timer , true ) ; // now \"start\" the timer. This involves, moving the timer to an ACTIVE state // and scheduling the timer task this . startTimer ( timer ) ; // return the timer return timer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link javax . ejb . Timer } corresponding to the passed { @link javax . ejb . TimerHandle } [CODESPLIT] public TimerImpl getTimer ( TimerHandle handle ) { TimerHandleImpl timerHandle = ( TimerHandleImpl ) handle ; TimerImpl timer = timers . get ( timerHandle . getId ( ) ) ; if ( timer != null ) { return timer ; } return getWaitingOnTxCompletionTimers ( ) . get ( timerHandle . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persists the passed <code > timer< / code > . <p / > <p > If the passed timer is null or is non - persistent ( i . e . { @link javax . ejb . Timer#isPersistent () } returns false ) then this method acts as a no - op < / p > [CODESPLIT] public void persistTimer ( final TimerImpl timer , boolean newTimer ) { if ( timer == null ) { return ; } if ( timer . isTimerPersistent ( ) ) { try { if ( timerPersistence . getOptionalValue ( ) == null ) { EJB3_TIMER_LOGGER . timerPersistenceNotEnable ( ) ; return ; } final ContextTransactionManager transactionManager = ContextTransactionManager . getInstance ( ) ; Transaction clientTX = transactionManager . getTransaction ( ) ; if ( newTimer || timer . isCanceled ( ) ) { if ( clientTX == null ) { transactionManager . begin ( ) ; } try { if ( newTimer ) timerPersistence . getValue ( ) . addTimer ( timer ) ; else timerPersistence . getValue ( ) . persistTimer ( timer ) ; if ( clientTX == null ) transactionManager . commit ( ) ; } catch ( Exception e ) { if ( clientTX == null ) { try { transactionManager . rollback ( ) ; } catch ( Exception ee ) { EjbLogger . EJB3_TIMER_LOGGER . timerUpdateFailedAndRollbackNotPossible ( ee ) ; } } throw e ; } } else { new TaskPostPersist ( timer ) . persistTimer ( ) ; } } catch ( Throwable t ) { this . setRollbackOnly ( ) ; throw new RuntimeException ( t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Suspends any currently scheduled tasks for { [CODESPLIT] public void suspendTimers ( ) { // get all active timers (persistent/non-persistent inclusive) Collection < Timer > timers = this . getTimers ( ) ; for ( Timer timer : timers ) { if ( ! ( timer instanceof TimerImpl ) ) { continue ; } // suspend the timer ( ( TimerImpl ) timer ) . suspend ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restores persisted timers corresponding to this timerservice which are eligible for any new timeouts . <p > This includes timers whose { @link TimerState } is <b > neither< / b > of the following : <ul > <li > { @link TimerState#CANCELED } < / li > <li > { @link TimerState#EXPIRED } < / li > < / ul > < / p > <p > All such restored timers will be schedule for their next timeouts . < / p > [CODESPLIT] public void restoreTimers ( final List < ScheduleTimer > autoTimers ) { // get the persisted timers which are considered active List < TimerImpl > restorableTimers = this . getActivePersistentTimers ( ) ; //timers are removed from the list as they are loaded final List < ScheduleTimer > newAutoTimers = new LinkedList < ScheduleTimer > ( autoTimers ) ; if ( EJB3_TIMER_LOGGER . isDebugEnabled ( ) ) { EJB3_TIMER_LOGGER . debug ( \"Found \" + restorableTimers . size ( ) + \" active persistentTimers for timedObjectId: \" + getInvoker ( ) . getTimedObjectId ( ) ) ; } // now \"start\" each of the restorable timer. This involves, moving the timer to an ACTIVE state // and scheduling the timer task for ( final TimerImpl activeTimer : restorableTimers ) { if ( activeTimer . isAutoTimer ( ) ) { CalendarTimer calendarTimer = ( CalendarTimer ) activeTimer ; boolean found = false ; //so we know we have an auto timer. We need to try and match it up with the auto timers. ListIterator < ScheduleTimer > it = newAutoTimers . listIterator ( ) ; while ( it . hasNext ( ) ) { ScheduleTimer timer = it . next ( ) ; final String methodName = timer . getMethod ( ) . getName ( ) ; final String [ ] params = new String [ timer . getMethod ( ) . getParameterTypes ( ) . length ] ; for ( int i = 0 ; i < timer . getMethod ( ) . getParameterTypes ( ) . length ; ++ i ) { params [ i ] = timer . getMethod ( ) . getParameterTypes ( ) [ i ] . getName ( ) ; } if ( doesTimeoutMethodMatch ( calendarTimer . getTimeoutMethod ( ) , methodName , params ) ) { //the timers have the same method. //now lets make sure the schedule is the same // and the timer does not change the persistence if ( this . doesScheduleMatch ( calendarTimer . getScheduleExpression ( ) , timer . getScheduleExpression ( ) ) && timer . getTimerConfig ( ) . isPersistent ( ) ) { it . remove ( ) ; found = true ; break ; } } } if ( ! found ) { activeTimer . setTimerState ( TimerState . CANCELED , null ) ; } else { // ensure state switch to active if was TIMEOUT in the DB // if the persistence is shared it must be ensured to not update // timers of other nodes in the cluster activeTimer . setTimerState ( TimerState . ACTIVE , null ) ; calendarTimer . handleRestorationCalculation ( ) ; } try { this . persistTimer ( activeTimer , false ) ; } catch ( Exception e ) { EJB3_TIMER_LOGGER . failedToPersistTimerOnStartup ( activeTimer , e ) ; } if ( found ) { startTimer ( activeTimer ) ; EJB3_TIMER_LOGGER . debugv ( \"Started existing auto timer: {0}\" , activeTimer ) ; } } else if ( ! ineligibleTimerStates . contains ( activeTimer . getState ( ) ) ) { startTimer ( activeTimer ) ; } EJB3_TIMER_LOGGER . debugv ( \"Started timer: {0}\" , activeTimer ) ; } for ( ScheduleTimer timer : newAutoTimers ) { this . loadAutoTimer ( timer . getScheduleExpression ( ) , timer . getTimerConfig ( ) , timer . getMethod ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a timer with a transaction ( if any in progress ) and then moves the timer to an active state so that it becomes eligible for timeouts [CODESPLIT] protected void startTimer ( TimerImpl timer ) { // if there's no transaction, then trigger a schedule immediately. // Else, the timer will be scheduled on tx synchronization callback if ( ! transactionActive ( ) ) { this . timers . put ( timer . getId ( ) , timer ) ; // set active if the timer is started if it was read // from persistence as current running to ensure correct schedule here timer . setTimerState ( TimerState . ACTIVE , null ) ; // create and schedule a timer task this . registerTimerResource ( timer . getId ( ) ) ; timer . scheduleTimeout ( true ) ; } else { addWaitingOnTxCompletionTimer ( timer ) ; registerSynchronization ( new TimerCreationTransactionSynchronization ( timer ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the { @link CurrentInvocationContext } represents a lifecycle callback invocation . Else returns false . <p > This method internally relies on { @link CurrentInvocationContext#get () } to obtain the current invocation context . <ul > <li > If the context is available then it looks for the method that was invoked . The absence of a method indicates a lifecycle callback . < / li > <li > If the context is <i > not< / i > available then this method returns false ( i . e . it doesn t consider the current invocation as a lifecycle callback ) . This is for convenience to allow the invocation of { @link javax . ejb . TimerService } methods in the absence of { @link CurrentInvocationContext } < / li > < / ul > <p / > < / p > [CODESPLIT] protected boolean isLifecycleCallbackInvocation ( ) { final InterceptorContext currentInvocationContext = CurrentInvocationContext . get ( ) ; if ( currentInvocationContext == null ) { return false ; } // If the method in current invocation context is null, // then it represents a lifecycle callback invocation Method invokedMethod = currentInvocationContext . getMethod ( ) ; if ( invokedMethod == null ) { // it's a lifecycle callback return true ; } // not a lifecycle callback return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and schedules a { [CODESPLIT] protected void scheduleTimeout ( TimerImpl timer , boolean newTimer ) { synchronized ( scheduledTimerFutures ) { if ( ! newTimer && ! scheduledTimerFutures . containsKey ( timer . getId ( ) ) ) { //this timer has been cancelled by another thread. We just return return ; } Date nextExpiration = timer . getNextExpiration ( ) ; if ( nextExpiration == null ) { EJB3_TIMER_LOGGER . nextExpirationIsNull ( timer ) ; return ; } // create the timer task final TimerTask < ? > timerTask = timer . getTimerTask ( ) ; // find out how long is it away from now long delay = nextExpiration . getTime ( ) - System . currentTimeMillis ( ) ; // if in past, then trigger immediately if ( delay < 0 ) { delay = 0 ; } long intervalDuration = timer . getInterval ( ) ; final Task task = new Task ( timerTask , ejbComponentInjectedValue . getValue ( ) . getControlPoint ( ) ) ; if ( intervalDuration > 0 ) { EJB3_TIMER_LOGGER . debugv ( \"Scheduling timer {0} at fixed rate, starting at {1} milliseconds from now with repeated interval={2}\" , timer , delay , intervalDuration ) ; // schedule the task this . timerInjectedValue . getValue ( ) . scheduleAtFixedRate ( task , delay , intervalDuration ) ; // maintain it in timerservice for future use (like cancellation) this . scheduledTimerFutures . put ( timer . getId ( ) , task ) ; } else { EJB3_TIMER_LOGGER . debugv ( \"Scheduling a single action timer {0} starting at {1} milliseconds from now\" , timer , delay ) ; // schedule the task this . timerInjectedValue . getValue ( ) . schedule ( task , delay ) ; // maintain it in timerservice for future use (like cancellation) this . scheduledTimerFutures . put ( timer . getId ( ) , task ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancels any scheduled { @link java . util . concurrent . Future } corresponding to the passed <code > timer< / code > [CODESPLIT] protected void cancelTimeout ( final TimerImpl timer ) { synchronized ( this . scheduledTimerFutures ) { java . util . TimerTask timerTask = this . scheduledTimerFutures . remove ( timer . getId ( ) ) ; if ( timerTask != null ) { timerTask . cancel ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an unmodifiable view of timers in the current transaction that are waiting for the transaction to finish [CODESPLIT] private Map < String , TimerImpl > getWaitingOnTxCompletionTimers ( ) { Map < String , TimerImpl > timers = null ; if ( getTransaction ( ) != null ) { timers = ( Map < String , TimerImpl > ) tsr . getResource ( waitingOnTxCompletionKey ) ; } return timers == null ? Collections . < String , TimerImpl > emptyMap ( ) : timers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marks the transaction for rollback NOTE : This method will soon be removed once this timer service implementation becomes managed [CODESPLIT] private void setRollbackOnly ( ) { try { Transaction tx = ContextTransactionManager . getInstance ( ) . getTransaction ( ) ; if ( tx != null ) { tx . setRollbackOnly ( ) ; } } catch ( IllegalStateException ise ) { EJB3_TIMER_LOGGER . ignoringException ( ise ) ; } catch ( SystemException se ) { EJB3_TIMER_LOGGER . ignoringException ( se ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a persistent timer is already executed from a different instance or should be executed . For non - persistent timer it always return <code > true< / code > . [CODESPLIT] public boolean shouldRun ( TimerImpl timer ) { // check peristent without further check to prevent from Exception (WFLY-6152) return ! timer . isTimerPersistent ( ) || timerPersistence . getValue ( ) . shouldRun ( timer , ContextTransactionManager . getInstance ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the passed <code > beanClass< / code > is eligible for implicit no - interface view . Else returns false . <p / > EJB3 . 1 spec section 4 . 9 . 8 states the rules for an implicit no - interface view on a bean class . If the implements clause of the bean class is empty then the bean is considered to be exposing a no - interface view . During this implements clause check the { @link java . io . Serializable } or { @link java . io . Externalizable } or any class from javax . ejb . * packages are excluded . [CODESPLIT] private boolean exposesNoInterfaceView ( Class < ? > beanClass ) { Class < ? > [ ] interfaces = beanClass . getInterfaces ( ) ; if ( interfaces . length == 0 ) { return true ; } // As per section 4.9.8 (bullet 1.3) of EJB3.1 spec // java.io.Serializable; java.io.Externalizable; any of the interfaces defined by the javax.ejb // are excluded from interface check List < Class < ? > > implementedInterfaces = new ArrayList < Class < ? > > ( Arrays . asList ( interfaces ) ) ; List < Class < ? > > filteredInterfaces = this . filterInterfaces ( implementedInterfaces ) ; // Now that we have removed the interfaces that should be excluded from the check, // if the filtered interfaces collection is empty then this bean can be considered for no-interface view return filteredInterfaces . isEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the default local view class of the { @link Class beanClass } if one is present . EJB3 . 1 spec section 4 . 9 . 7 specifies the rules for a default local view of a bean . If the bean implements just one interface then that interface is returned as the default local view by this method . If no such interface is found then this method returns null . [CODESPLIT] private Class < ? > getDefaultLocalView ( Class < ? > beanClass ) { Class < ? > [ ] interfaces = beanClass . getInterfaces ( ) ; if ( interfaces . length == 0 ) { return null ; } List < Class < ? > > implementedInterfaces = new ArrayList < Class < ? > > ( Arrays . asList ( interfaces ) ) ; List < Class < ? > > filteredInterfaces = this . filterInterfaces ( implementedInterfaces ) ; if ( filteredInterfaces . isEmpty ( ) || filteredInterfaces . size ( ) > 1 ) { return null ; } return filteredInterfaces . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a filtered list for the passed <code > interfaces< / code > list excluding the { @link java . io . Serializable } { @link java . io . Externalizable } and any interfaces belonging to <code > javax . ejb< / code > package . [CODESPLIT] private List < Class < ? > > filterInterfaces ( List < Class < ? > > interfaces ) { if ( interfaces == null ) { return null ; } List < Class < ? > > filteredInterfaces = new ArrayList < Class < ? > > ( ) ; for ( Class < ? > intf : interfaces ) { if ( intf . equals ( java . io . Serializable . class ) || intf . equals ( java . io . Externalizable . class ) || intf . getName ( ) . startsWith ( \"javax.ejb.\" ) ) { continue ; } filteredInterfaces . add ( intf ) ; } return filteredInterfaces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the acceptor information . [CODESPLIT] static void processAcceptors ( final OperationContext context , final Configuration configuration , final ModelNode params , final Set < String > bindings ) throws OperationFailedException { final Map < String , TransportConfiguration > acceptors = new HashMap <> ( ) ; if ( params . hasDefined ( ACCEPTOR ) ) { for ( final Property property : params . get ( ACCEPTOR ) . asPropertyList ( ) ) { final String acceptorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , ACCEPTOR_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( TransportConstants . ALLOWABLE_ACCEPTOR_KEYS , parameters ) ; final String clazz = config . get ( FACTORY_CLASS . getName ( ) ) . asString ( ) ; ModelNode socketBinding = GenericTransportDefinition . SOCKET_BINDING . resolveModelAttribute ( context , config ) ; if ( socketBinding . isDefined ( ) ) { bindings . add ( socketBinding . asString ( ) ) ; // uses the parameters to pass the socket binding name that will be read in ActiveMQServerService.start() parameters . put ( GenericTransportDefinition . SOCKET_BINDING . getName ( ) , socketBinding . asString ( ) ) ; } acceptors . put ( acceptorName , new TransportConfiguration ( clazz , parameters , acceptorName , extraParameters ) ) ; } } if ( params . hasDefined ( REMOTE_ACCEPTOR ) ) { for ( final Property property : params . get ( REMOTE_ACCEPTOR ) . asPropertyList ( ) ) { final String acceptorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , ACCEPTOR_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( TransportConstants . ALLOWABLE_ACCEPTOR_KEYS , parameters ) ; final String binding = config . get ( RemoteTransportDefinition . SOCKET_BINDING . getName ( ) ) . asString ( ) ; bindings . add ( binding ) ; // uses the parameters to pass the socket binding name that will be read in ActiveMQServerService.start() parameters . put ( RemoteTransportDefinition . SOCKET_BINDING . getName ( ) , binding ) ; acceptors . put ( acceptorName , new TransportConfiguration ( NettyAcceptorFactory . class . getName ( ) , parameters , acceptorName , extraParameters ) ) ; } } if ( params . hasDefined ( IN_VM_ACCEPTOR ) ) { for ( final Property property : params . get ( IN_VM_ACCEPTOR ) . asPropertyList ( ) ) { final String acceptorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , ACCEPTOR_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( IN_VM_ALLOWABLE_KEYS , parameters ) ; parameters . put ( SERVER_ID_PROP_NAME , InVMTransportDefinition . SERVER_ID . resolveModelAttribute ( context , config ) . asInt ( ) ) ; acceptors . put ( acceptorName , new TransportConfiguration ( InVMAcceptorFactory . class . getName ( ) , parameters , acceptorName , extraParameters ) ) ; } } if ( params . hasDefined ( HTTP_ACCEPTOR ) ) { for ( final Property property : params . get ( HTTP_ACCEPTOR ) . asPropertyList ( ) ) { final String acceptorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , ACCEPTOR_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( TransportConstants . ALLOWABLE_ACCEPTOR_KEYS , parameters ) ; parameters . put ( TransportConstants . HTTP_UPGRADE_ENABLED_PROP_NAME , true ) ; acceptors . put ( acceptorName , new TransportConfiguration ( NettyAcceptorFactory . class . getName ( ) , parameters , acceptorName , extraParameters ) ) ; } } configuration . setAcceptorConfigurations ( new HashSet <> ( acceptors . values ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract extra parameters from the map of parameters . [CODESPLIT] private static Map < String , Object > getExtraParameters ( final Set < String > allowedKeys , final Map < String , Object > parameters ) { Map < String , Object > extraParameters = new HashMap <> ( ) ; for ( Map . Entry < String , Object > parameter : parameters . entrySet ( ) ) { if ( ! allowedKeys . contains ( parameter . getKey ( ) ) ) { extraParameters . put ( parameter . getKey ( ) , parameter . getValue ( ) ) ; } } for ( String extraParam : extraParameters . keySet ( ) ) { parameters . remove ( extraParam ) ; } return extraParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the parameters . [CODESPLIT] public static Map < String , Object > getParameters ( final OperationContext context , final ModelNode config , final Map < String , String > mapping ) throws OperationFailedException { Map < String , String > fromModel = CommonAttributes . PARAMS . unwrap ( context , config ) ; Map < String , Object > parameters = new HashMap <> ( ) ; for ( Map . Entry < String , String > entry : fromModel . entrySet ( ) ) { parameters . put ( mapping . getOrDefault ( entry . getKey ( ) , entry . getKey ( ) ) , entry . getValue ( ) ) ; } return parameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the connector information . [CODESPLIT] static Map < String , TransportConfiguration > processConnectors ( final OperationContext context , final String configServerName , final ModelNode params , final Set < String > bindings ) throws OperationFailedException { final Map < String , TransportConfiguration > connectors = new HashMap < String , TransportConfiguration > ( ) ; if ( params . hasDefined ( CONNECTOR ) ) { for ( final Property property : params . get ( CONNECTOR ) . asPropertyList ( ) ) { final String connectorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , CONNECTORS_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( TransportConstants . ALLOWABLE_CONNECTOR_KEYS , parameters ) ; ModelNode socketBinding = GenericTransportDefinition . SOCKET_BINDING . resolveModelAttribute ( context , config ) ; if ( socketBinding . isDefined ( ) ) { bindings . add ( socketBinding . asString ( ) ) ; // uses the parameters to pass the socket binding name that will be read in ActiveMQServerService.start() parameters . put ( GenericTransportDefinition . SOCKET_BINDING . getName ( ) , socketBinding . asString ( ) ) ; } final String clazz = FACTORY_CLASS . resolveModelAttribute ( context , config ) . asString ( ) ; connectors . put ( connectorName , new TransportConfiguration ( clazz , parameters , connectorName , extraParameters ) ) ; } } if ( params . hasDefined ( REMOTE_CONNECTOR ) ) { for ( final Property property : params . get ( REMOTE_CONNECTOR ) . asPropertyList ( ) ) { final String connectorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , CONNECTORS_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( TransportConstants . ALLOWABLE_CONNECTOR_KEYS , parameters ) ; final String binding = config . get ( RemoteTransportDefinition . SOCKET_BINDING . getName ( ) ) . asString ( ) ; bindings . add ( binding ) ; // uses the parameters to pass the socket binding name that will be read in ActiveMQServerService.start() parameters . put ( RemoteTransportDefinition . SOCKET_BINDING . getName ( ) , binding ) ; connectors . put ( connectorName , new TransportConfiguration ( NettyConnectorFactory . class . getName ( ) , parameters , connectorName , extraParameters ) ) ; } } if ( params . hasDefined ( IN_VM_CONNECTOR ) ) { for ( final Property property : params . get ( IN_VM_CONNECTOR ) . asPropertyList ( ) ) { final String connectorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , CONNECTORS_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( IN_VM_ALLOWABLE_KEYS , parameters ) ; parameters . put ( CONNECTORS_KEYS_MAP . get ( InVMTransportDefinition . SERVER_ID . getName ( ) ) , InVMTransportDefinition . SERVER_ID . resolveModelAttribute ( context , config ) . asInt ( ) ) ; connectors . put ( connectorName , new TransportConfiguration ( InVMConnectorFactory . class . getName ( ) , parameters , connectorName , extraParameters ) ) ; } } if ( params . hasDefined ( HTTP_CONNECTOR ) ) { for ( final Property property : params . get ( HTTP_CONNECTOR ) . asPropertyList ( ) ) { final String connectorName = property . getName ( ) ; final ModelNode config = property . getValue ( ) ; final Map < String , Object > parameters = getParameters ( context , config , CONNECTORS_KEYS_MAP ) ; final Map < String , Object > extraParameters = getExtraParameters ( TransportConstants . ALLOWABLE_CONNECTOR_KEYS , parameters ) ; final String binding = HTTPConnectorDefinition . SOCKET_BINDING . resolveModelAttribute ( context , config ) . asString ( ) ; bindings . add ( binding ) ; // ARTEMIS-803 Artemis knows that is must not offset the HTTP port when it is used by colocated backups parameters . put ( TransportConstants . HTTP_UPGRADE_ENABLED_PROP_NAME , true ) ; parameters . put ( TransportConstants . HTTP_UPGRADE_ENDPOINT_PROP_NAME , HTTPConnectorDefinition . ENDPOINT . resolveModelAttribute ( context , config ) . asString ( ) ) ; // uses the parameters to pass the socket binding name that will be read in ActiveMQServerService.start() parameters . put ( HTTPConnectorDefinition . SOCKET_BINDING . getName ( ) , binding ) ; ModelNode serverNameModelNode = HTTPConnectorDefinition . SERVER_NAME . resolveModelAttribute ( context , config ) ; // use the name of this server if the server-name attribute is undefined String serverName = serverNameModelNode . isDefined ( ) ? serverNameModelNode . asString ( ) : configServerName ; parameters . put ( ACTIVEMQ_SERVER_NAME , serverName ) ; connectors . put ( connectorName , new TransportConfiguration ( NettyConnectorFactory . class . getName ( ) , parameters , connectorName , extraParameters ) ) ; } } return connectors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static Map < String , Boolean > listOutBoundSocketBinding ( OperationContext context , Collection < String > names ) throws OperationFailedException { Map < String , Boolean > result = new HashMap <> ( ) ; Resource root = context . readResourceFromRoot ( PathAddress . EMPTY_ADDRESS , false ) ; Set < String > groups = root . getChildrenNames ( ModelDescriptionConstants . SOCKET_BINDING_GROUP ) ; for ( String groupName : groups ) { Resource socketBindingGroup = context . readResourceFromRoot ( PathAddress . pathAddress ( ModelDescriptionConstants . SOCKET_BINDING_GROUP , groupName ) ) ; for ( String name : names ) { if ( socketBindingGroup . getChildrenNames ( ModelDescriptionConstants . SOCKET_BINDING ) . contains ( name ) ) { result . put ( name , Boolean . FALSE ) ; } else if ( socketBindingGroup . getChildrenNames ( ModelDescriptionConstants . LOCAL_DESTINATION_OUTBOUND_SOCKET_BINDING ) . contains ( name ) || socketBindingGroup . getChildrenNames ( ModelDescriptionConstants . REMOTE_DESTINATION_OUTBOUND_SOCKET_BINDING ) . contains ( name ) ) { result . put ( name , Boolean . TRUE ) ; } } } if ( result . size ( ) != names . size ( ) ) { for ( String name : names ) { if ( ! result . containsKey ( name ) ) { throw MessagingLogger . ROOT_LOGGER . noSocketBinding ( name ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The old deployment unit service name . This is still registered as an alias however {{ [CODESPLIT] @ Deprecated public static ServiceName deploymentServiceName ( final String serverName , final String virtualHost , final String contextPath ) { return WEB_DEPLOYMENT_BASE . append ( serverName ) . append ( virtualHost ) . append ( \"\" . equals ( contextPath ) ? \"/\" : contextPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turn type into class . [CODESPLIT] public static Class < ? > toClass ( Type type ) { if ( type instanceof Class ) { return ( Class ) type ; } else if ( type instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) type ; return toClass ( pt . getRawType ( ) ) ; } else { throw PojoLogger . ROOT_LOGGER . unknownType ( type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a value [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Object convertValue ( Class < ? > clazz , Object value , boolean replaceProperties , boolean trim ) throws Throwable { if ( clazz == null ) return value ; if ( value == null ) return null ; Class < ? > valueClass = value . getClass ( ) ; // If we have a string, trim and replace any system properties when requested if ( valueClass == String . class ) { String string = ( String ) value ; if ( trim ) string = string . trim ( ) ; if ( replaceProperties ) value = PropertiesValueResolver . replaceProperties ( string ) ; } if ( clazz . isAssignableFrom ( valueClass ) ) return value ; // First see if this is an Enum if ( clazz . isEnum ( ) ) { Class < ? extends Enum > eclazz = clazz . asSubclass ( Enum . class ) ; return Enum . valueOf ( eclazz , value . toString ( ) ) ; } // Next look for a property editor if ( valueClass == String . class ) { PropertyEditor editor = PropertyEditorManager . findEditor ( clazz ) ; if ( editor != null ) { editor . setAsText ( ( String ) value ) ; return editor . getValue ( ) ; } } // Try a static clazz.valueOf(value) try { Method method = clazz . getMethod ( \"valueOf\" , valueClass ) ; int modifiers = method . getModifiers ( ) ; if ( Modifier . isPublic ( modifiers ) && Modifier . isStatic ( modifiers ) && clazz . isAssignableFrom ( method . getReturnType ( ) ) ) return method . invoke ( null , value ) ; } catch ( Exception ignored ) { } if ( valueClass == String . class ) { try { Constructor constructor = clazz . getConstructor ( valueClass ) ; if ( Modifier . isPublic ( constructor . getModifiers ( ) ) ) return constructor . newInstance ( value ) ; } catch ( Exception ignored ) { } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get types from values . [CODESPLIT] public static String [ ] getTypes ( ValueConfig [ ] values ) { if ( values == null || values . length == 0 ) return NO_PARAMS_TYPES ; String [ ] types = new String [ values . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) types [ i ] = values [ i ] . getType ( ) ; return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find method info [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Method findMethod ( DeploymentReflectionIndex index , Class classInfo , String name , String [ ] paramTypes , boolean isStatic , boolean isPublic , boolean strict ) throws IllegalArgumentException { if ( name == null ) throw PojoLogger . ROOT_LOGGER . nullName ( ) ; if ( classInfo == null ) throw PojoLogger . ROOT_LOGGER . nullClassInfo ( ) ; if ( paramTypes == null ) paramTypes = NO_PARAMS_TYPES ; Class current = classInfo ; while ( current != null ) { ClassReflectionIndex cri = index . getClassIndex ( classInfo ) ; Method result = locateMethod ( cri , name , paramTypes , isStatic , isPublic , strict ) ; if ( result != null ) return result ; current = current . getSuperclass ( ) ; } throw PojoLogger . ROOT_LOGGER . methodNotFound ( name , Arrays . toString ( paramTypes ) , classInfo . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find method info [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static Method locateMethod ( ClassReflectionIndex classInfo , String name , String [ ] paramTypes , boolean isStatic , boolean isPublic , boolean strict ) { Collection < Method > methods = classInfo . getMethods ( ) ; if ( methods != null ) { for ( Method method : methods ) { if ( name . equals ( method . getName ( ) ) && equals ( paramTypes , method . getParameterTypes ( ) ) && ( strict == false || ( Modifier . isStatic ( method . getModifiers ( ) ) == isStatic && Modifier . isPublic ( method . getModifiers ( ) ) == isPublic ) ) ) return method ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A simple null and length check . [CODESPLIT] protected static boolean simpleCheck ( String [ ] typeNames , Class < ? > [ ] typeInfos ) { return typeNames != null && typeInfos != null && typeNames . length == typeInfos . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the persistence unit definitions based on persistence_2_0 . xsd . [CODESPLIT] private static PersistenceUnitMetadata parsePU ( XMLStreamReader reader , Version version , final PropertyReplacer propertyReplacer ) throws XMLStreamException { PersistenceUnitMetadata pu = new PersistenceUnitMetadataImpl ( ) ; List < String > classes = new ArrayList < String > ( 1 ) ; List < String > jarFiles = new ArrayList < String > ( 1 ) ; List < String > mappingFiles = new ArrayList < String > ( 1 ) ; Properties properties = new Properties ( ) ; // set defaults pu . setTransactionType ( PersistenceUnitTransactionType . JTA ) ; pu . setValidationMode ( ValidationMode . AUTO ) ; pu . setSharedCacheMode ( SharedCacheMode . UNSPECIFIED ) ; pu . setPersistenceProviderClassName ( Configuration . PROVIDER_CLASS_DEFAULT ) ; if ( version . equals ( Version . JPA_1_0 ) ) { pu . setPersistenceXMLSchemaVersion ( \"1.0\" ) ; } else if ( version . equals ( Version . JPA_2_0 ) ) { pu . setPersistenceXMLSchemaVersion ( \"2.0\" ) ; } else if ( version . equals ( Version . JPA_2_1 ) ) { pu . setPersistenceXMLSchemaVersion ( \"2.1\" ) ; } else { pu . setPersistenceXMLSchemaVersion ( \"2.2\" ) ; } final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { final String value = reader . getAttributeValue ( i ) ; if ( traceEnabled ) { ROOT_LOGGER . tracef ( \"parse persistence.xml: attribute value(%d) = %s\" , i , value ) ; } final String attributeNamespace = reader . getAttributeNamespace ( i ) ; if ( attributeNamespace != null && ! attributeNamespace . isEmpty ( ) ) { continue ; } final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; switch ( attribute ) { case NAME : pu . setPersistenceUnitName ( value ) ; break ; case TRANSACTIONTYPE : if ( value . equalsIgnoreCase ( \"RESOURCE_LOCAL\" ) ) pu . setTransactionType ( PersistenceUnitTransactionType . RESOURCE_LOCAL ) ; break ; default : throw unexpectedAttribute ( reader , i ) ; } } // until the ending PERSISTENCEUNIT tag while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { final Element element = Element . forName ( reader . getLocalName ( ) ) ; if ( traceEnabled ) { ROOT_LOGGER . tracef ( \"parse persistence.xml: element=%s\" , element . getLocalName ( ) ) ; } switch ( element ) { case CLASS : classes . add ( getElement ( reader , propertyReplacer ) ) ; break ; case DESCRIPTION : final String description = getElement ( reader , propertyReplacer ) ; break ; case EXCLUDEUNLISTEDCLASSES : String text = getElement ( reader , propertyReplacer ) ; if ( text == null || text . isEmpty ( ) ) { //the spec has examples where an empty //exclude-unlisted-classes element has the same //effect as setting it to true pu . setExcludeUnlistedClasses ( true ) ; } else { pu . setExcludeUnlistedClasses ( Boolean . valueOf ( text ) ) ; } break ; case JARFILE : String file = getElement ( reader , propertyReplacer ) ; jarFiles . add ( file ) ; break ; case JTADATASOURCE : pu . setJtaDataSourceName ( getElement ( reader , propertyReplacer ) ) ; break ; case NONJTADATASOURCE : pu . setNonJtaDataSourceName ( getElement ( reader , propertyReplacer ) ) ; break ; case MAPPINGFILE : mappingFiles . add ( getElement ( reader , propertyReplacer ) ) ; break ; case PROPERTIES : parseProperties ( reader , properties , propertyReplacer ) ; break ; case PROVIDER : pu . setPersistenceProviderClassName ( getElement ( reader , propertyReplacer ) ) ; break ; case SHAREDCACHEMODE : String cm = getElement ( reader , propertyReplacer ) ; pu . setSharedCacheMode ( SharedCacheMode . valueOf ( cm ) ) ; break ; case VALIDATIONMODE : String validationMode = getElement ( reader , propertyReplacer ) ; pu . setValidationMode ( ValidationMode . valueOf ( validationMode ) ) ; break ; default : throw unexpectedElement ( reader ) ; } } if ( traceEnabled ) { ROOT_LOGGER . trace ( \"parse persistence.xml: reached ending persistence-unit tag\" ) ; } pu . setManagedClassNames ( classes ) ; pu . setJarFiles ( jarFiles ) ; pu . setMappingFiles ( mappingFiles ) ; pu . setProperties ( properties ) ; return pu ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next binding in the list . [CODESPLIT] public java . lang . Object next ( ) throws NamingException { if ( more && counter >= _bindingList . value . length ) { getMore ( ) ; } if ( more && counter < _bindingList . value . length ) { org . omg . CosNaming . Binding bndg = _bindingList . value [ counter ] ; counter ++ ; return mapBinding ( bndg ) ; } else { throw new NoSuchElementException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the next batch using _bindingIter . Update the more field . [CODESPLIT] private boolean getMore ( ) throws NamingException { try { more = _bindingIter . next_n ( batchsize , _bindingList ) ; counter = 0 ; // reset } catch ( Exception e ) { more = false ; NamingException ne = IIOPLogger . ROOT_LOGGER . errorGettingBindingList ( ) ; ne . setRootCause ( e ) ; throw ne ; } return more ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a JNDI Binding object from the COS Naming binding object . [CODESPLIT] private javax . naming . Binding mapBinding ( org . omg . CosNaming . Binding bndg ) throws NamingException { java . lang . Object obj = _ctx . callResolve ( bndg . binding_name ) ; Name cname = org . wildfly . iiop . openjdk . naming . jndi . CNNameParser . cosNameToName ( bndg . binding_name ) ; try { obj = NamingManager . getObjectInstance ( obj , cname , _ctx , _env ) ; } catch ( NamingException e ) { throw e ; } catch ( Exception e ) { NamingException ne = IIOPLogger . ROOT_LOGGER . errorGeneratingObjectViaFactory ( ) ; ne . setRootCause ( e ) ; throw ne ; } // Use cname.toString() instead of bindingName because the name // in the binding should be a composite name String cnameStr = cname . toString ( ) ; javax . naming . Binding jbndg = new javax . naming . Binding ( cnameStr , obj ) ; NameComponent [ ] comps = _ctx . makeFullName ( bndg . binding_name ) ; String fullName = org . wildfly . iiop . openjdk . naming . jndi . CNNameParser . cosNameToInsString ( comps ) ; jbndg . setNameInNamespace ( fullName ) ; return jbndg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the specified properties . [CODESPLIT] public void addProperties ( final String [ ] annotationProperties , final PropertyReplacer propertyReplacer ) { if ( annotationProperties != null ) { for ( String annotationProperty : annotationProperties ) { if ( propertyReplacer != null ) { annotationProperty = propertyReplacer . replaceProperties ( annotationProperty ) ; } final int index = annotationProperty . indexOf ( ' ' ) ; String propertyName ; String propertyValue ; if ( index != - 1 ) { propertyName = annotationProperty . substring ( 0 , index ) ; propertyValue = annotationProperty . length ( ) > index ? annotationProperty . substring ( index + 1 , annotationProperty . length ( ) ) : \"\" ; } else { propertyName = annotationProperty ; propertyValue = \"\" ; } this . properties . put ( propertyName , propertyValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the specified properties . [CODESPLIT] public void addProperties ( final PropertiesMetaData descriptorProperties ) { if ( descriptorProperties != null ) { for ( PropertyMetaData descriptorProperty : descriptorProperties ) { this . properties . put ( descriptorProperty . getName ( ) , descriptorProperty . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discover all classes that implements HealthCheckProcedure [CODESPLIT] public void observeResources ( @ Observes @ WithAnnotations ( { Health . class } ) ProcessAnnotatedType < ? extends HealthCheck > event ) { AnnotatedType < ? extends HealthCheck > annotatedType = event . getAnnotatedType ( ) ; Class < ? extends HealthCheck > javaClass = annotatedType . getJavaClass ( ) ; MicroProfileHealthLogger . LOGGER . infof ( \"Discovered health check procedure %s\" , javaClass ) ; delegates . add ( annotatedType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates <em > unmanaged instances< / em > of HealthCheckProcedure and handle manually their CDI creation lifecycle . Add them to the { [CODESPLIT] private void afterDeploymentValidation ( @ Observes final AfterDeploymentValidation avd , BeanManager bm ) { for ( AnnotatedType delegate : delegates ) { try { Unmanaged < HealthCheck > unmanagedHealthCheck = new Unmanaged < HealthCheck > ( bm , delegate . getJavaClass ( ) ) ; UnmanagedInstance < HealthCheck > healthCheckInstance = unmanagedHealthCheck . newInstance ( ) ; HealthCheck healthCheck = healthCheckInstance . produce ( ) . inject ( ) . postConstruct ( ) . get ( ) ; healthCheckInstances . add ( healthCheckInstance ) ; healthReporter . addHealthCheck ( healthCheck ) ; } catch ( Exception e ) { throw new RuntimeException ( \"Failed to register health bean\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the deployment is undeployed . [CODESPLIT] public void close ( @ Observes final BeforeShutdown bs ) { healthCheckInstances . forEach ( healthCheck -> { healthReporter . removeHealthCheck ( healthCheck . get ( ) ) ; healthCheck . preDestroy ( ) . dispose ( ) ; } ) ; healthCheckInstances . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a corba reference for the given locator [CODESPLIT] public org . omg . CORBA . Object referenceForLocator ( final EJBLocator < ? > locator ) { final EJBComponent ejbComponent = ejbComponentInjectedValue . getValue ( ) ; try { final String earApplicationName = ejbComponent . getEarApplicationName ( ) == null ? \"\" : ejbComponent . getEarApplicationName ( ) ; if ( locator . getBeanName ( ) . equals ( ejbComponent . getComponentName ( ) ) && locator . getAppName ( ) . equals ( earApplicationName ) && locator . getModuleName ( ) . equals ( ejbComponent . getModuleName ( ) ) && locator . getDistinctName ( ) . equals ( ejbComponent . getDistinctName ( ) ) ) { if ( locator instanceof EJBHomeLocator ) { return ( org . omg . CORBA . Object ) ejbHome ; } else if ( locator instanceof StatelessEJBLocator ) { return beanReferenceFactory . createReference ( beanRepositoryIds [ 0 ] ) ; } else if ( locator instanceof StatefulEJBLocator ) { final Marshaller marshaller = factory . createMarshaller ( configuration ) ; final ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; marshaller . start ( new OutputStreamByteOutput ( stream ) ) ; marshaller . writeObject ( ( ( StatefulEJBLocator < ? > ) locator ) . getSessionId ( ) ) ; marshaller . finish ( ) ; return beanReferenceFactory . createReferenceWithId ( stream . toByteArray ( ) , beanRepositoryIds [ 0 ] ) ; } else if ( locator instanceof EntityEJBLocator ) { final Marshaller marshaller = factory . createMarshaller ( configuration ) ; final ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; marshaller . start ( new OutputStreamByteOutput ( stream ) ) ; marshaller . writeObject ( ( ( EntityEJBLocator < ? > ) locator ) . getPrimaryKey ( ) ) ; marshaller . finish ( ) ; return beanReferenceFactory . createReferenceWithId ( stream . toByteArray ( ) , beanRepositoryIds [ 0 ] ) ; } throw EjbLogger . ROOT_LOGGER . unknownEJBLocatorType ( locator ) ; } else { throw EjbLogger . ROOT_LOGGER . incorrectEJBLocatorForBean ( locator , ejbComponent . getComponentName ( ) ) ; } } catch ( Exception e ) { throw EjbLogger . ROOT_LOGGER . couldNotCreateCorbaObject ( e , locator ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a handle for the given ejb locator . [CODESPLIT] public Object handleForLocator ( final EJBLocator < ? > locator ) { final org . omg . CORBA . Object reference = referenceForLocator ( locator ) ; if ( locator instanceof EJBHomeLocator ) { return new HomeHandleImplIIOP ( orb . getValue ( ) . object_to_string ( reference ) ) ; } return new HandleImplIIOP ( orb . getValue ( ) . object_to_string ( reference ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Re ) binds an object to a name in a given CORBA naming context creating any non - existent intermediate contexts along the way . <p / > This method is synchronized on the class object if multiple services attempt to bind the same context name at once it will fail [CODESPLIT] public static synchronized void rebind ( final NamingContextExt ctx , final String strName , final org . omg . CORBA . Object obj ) throws Exception { final NameComponent [ ] name = ctx . to_name ( strName ) ; NamingContext intermediateCtx = ctx ; for ( int i = 0 ; i < name . length - 1 ; i ++ ) { final NameComponent [ ] relativeName = new NameComponent [ ] { name [ i ] } ; try { intermediateCtx = NamingContextHelper . narrow ( intermediateCtx . resolve ( relativeName ) ) ; } catch ( NotFound e ) { intermediateCtx = intermediateCtx . bind_new_context ( relativeName ) ; } } intermediateCtx . rebind ( new NameComponent [ ] { name [ name . length - 1 ] } , obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( StartContext context ) throws StartException { SecurityLogger . ROOT_LOGGER . debugf ( \"Starting SecurityDomainService(%s)\" , name ) ; if ( applicationPolicy != null ) { final ApplicationPolicyRegistration applicationPolicyRegistration = ( ApplicationPolicyRegistration ) configurationValue . getValue ( ) ; applicationPolicyRegistration . addApplicationPolicy ( applicationPolicy . getName ( ) , applicationPolicy ) ; } final JNDIBasedSecurityManagement securityManagement = ( JNDIBasedSecurityManagement ) securityManagementValue . getValue ( ) ; AuthenticationCacheFactory cacheFactory = null ; if ( \"infinispan\" . equals ( cacheType ) ) { cacheFactory = ( ) -> this . cacheValue . getValue ( ) ; } else if ( \"default\" . equals ( cacheType ) ) { cacheFactory = new DefaultAuthenticationCacheFactory ( ) ; } SecurityDomainContext sdc ; try { sdc = securityManagement . createSecurityDomainContext ( name , cacheFactory , jsseSecurityDomain ) ; } catch ( Exception e ) { throw SecurityLogger . ROOT_LOGGER . unableToStartException ( \"SecurityDomainService\" , e ) ; } if ( jsseSecurityDomain != null ) { try { jsseSecurityDomain . reloadKeyAndTrustStore ( ) ; } catch ( Exception e ) { throw SecurityLogger . ROOT_LOGGER . unableToStartException ( \"SecurityDomainService\" , e ) ; } } securityManagement . getSecurityManagerMap ( ) . put ( name , sdc ) ; this . securityDomainContext = sdc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void stop ( StopContext context ) { SecurityLogger . ROOT_LOGGER . debugf ( \"Stopping security domain service %s\" , name ) ; final JNDIBasedSecurityManagement securityManagement = ( JNDIBasedSecurityManagement ) securityManagementValue . getValue ( ) ; securityManagement . removeSecurityDomain ( name ) ; // TODO clear auth cache? final ApplicationPolicyRegistration applicationPolicyRegistration = ( ApplicationPolicyRegistration ) configurationValue . getValue ( ) ; applicationPolicyRegistration . removeApplicationPolicy ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of the node as an Enum value . [CODESPLIT] public static < E extends Enum < E > > E asEnum ( ModelNode value , Class < E > targetClass ) { return Enum . valueOf ( targetClass , value . asString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional boolean value of the specified { [CODESPLIT] public static Optional < Boolean > optionalBoolean ( ModelNode value ) { return value . isDefined ( ) ? Optional . of ( value . asBoolean ( ) ) : Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional double value of the specified { [CODESPLIT] public static OptionalDouble optionalDouble ( ModelNode value ) { return value . isDefined ( ) ? OptionalDouble . of ( value . asDouble ( ) ) : OptionalDouble . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional float value of the specified { [CODESPLIT] public static Optional < Float > optionalFloat ( ModelNode value ) { return value . isDefined ( ) ? Optional . of ( asFloat ( value ) ) : Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional int value of the specified { [CODESPLIT] public static OptionalInt optionalInt ( ModelNode value ) { return value . isDefined ( ) ? OptionalInt . of ( value . asInt ( ) ) : OptionalInt . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional long value of the specified { [CODESPLIT] public static OptionalLong optionalLong ( ModelNode value ) { return value . isDefined ( ) ? OptionalLong . of ( value . asInt ( ) ) : OptionalLong . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional string value of the specified { [CODESPLIT] public static Optional < String > optionalString ( ModelNode value ) { return value . isDefined ( ) ? Optional . of ( value . asString ( ) ) : Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional property value of the specified { [CODESPLIT] public static Optional < Property > optionalProperty ( ModelNode value ) { return value . isDefined ( ) ? Optional . of ( value . asProperty ( ) ) : Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional property list value of the specified { [CODESPLIT] public static Optional < List < Property > > optionalPropertyList ( ModelNode value ) { return value . isDefined ( ) ? Optional . of ( value . asPropertyList ( ) ) : Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional list value of the specified { [CODESPLIT] public static Optional < List < ModelNode > > optionalList ( ModelNode value ) { return value . isDefined ( ) ? Optional . of ( value . asList ( ) ) : Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the optional enum value of the specified { [CODESPLIT] public static < E extends Enum < E > > Optional < E > optionalEnum ( ModelNode value , Class < E > targetClass ) { return value . isDefined ( ) ? Optional . of ( asEnum ( value , targetClass ) ) : Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ResourceRoot } for the passed { @link VirtualFile file } and adds it to the list of { @link ResourceRoot } s in the { @link DeploymentUnit deploymentUnit } [CODESPLIT] private ResourceRoot createResourceRoot ( final DeploymentUnit deploymentUnit , final VirtualFile file , final boolean markAsSubDeployment , final boolean explodeDuringMount ) throws IOException { final boolean war = file . getName ( ) . toLowerCase ( Locale . ENGLISH ) . endsWith ( WAR_EXTENSION ) ; final Closeable closable = file . isFile ( ) ? mount ( file , explodeDuringMount ) : exportExplodedWar ( war , file , deploymentUnit ) ; final MountHandle mountHandle = new MountHandle ( closable ) ; final ResourceRoot resourceRoot = new ResourceRoot ( file , mountHandle ) ; deploymentUnit . addToAttachmentList ( Attachments . RESOURCE_ROOTS , resourceRoot ) ; if ( markAsSubDeployment ) { SubDeploymentMarker . mark ( resourceRoot ) ; } if ( war ) { resourceRoot . putAttachment ( Attachments . INDEX_RESOURCE_ROOT , false ) ; SubExplodedDeploymentMarker . mark ( resourceRoot ) ; } return resourceRoot ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] public static SimpleOperationDefinitionBuilder runtimeReadOnlyOperation ( String operationName , ResourceDescriptionResolver resolver ) { return new SimpleOperationDefinitionBuilder ( operationName , resolver ) . setRuntimeOnly ( ) . setReadOnly ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] public static SimpleOperationDefinitionBuilder runtimeOnlyOperation ( String operationName , ResourceDescriptionResolver resolver ) { return new SimpleOperationDefinitionBuilder ( operationName , resolver ) . setRuntimeOnly ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of { @link Principal } representing the roles associated with the identity invoking the EJB . This method will check performs checks against run as identities in order to resolve the correct set of roles to be granted . [CODESPLIT] public static Principal [ ] getGrantedRoles ( SecurityIdentity securityIdentity ) { Set < String > roles = new HashSet <> ( ) ; for ( String s : securityIdentity . getRoles ( \"ejb\" ) ) { roles . add ( s ) ; } List < Principal > list = new ArrayList <> ( ) ; Function < String , Principal > mapper = roleName -> ( Principal ) ( ) -> roleName ; for ( String role : roles ) { Principal principal = mapper . apply ( role ) ; list . add ( principal ) ; } return list . toArray ( NO_PRINCIPALS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure InputStream actually skips ahead the required number of bytes [CODESPLIT] public static void skip ( InputStream is , long amount ) throws IOException { long leftToSkip = amount ; long amountSkipped = 0 ; while ( leftToSkip > 0 && amountSkipped >= 0 ) { amountSkipped = is . skip ( leftToSkip ) ; leftToSkip -= amountSkipped ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "[ AS7 - 5808 ] Support space - separated roles names for backwards compatibility and comma - separated ones for compatibility with HornetQ configuration . [CODESPLIT] @ Override protected List < String > parseRolesAttribute ( XMLExtendedStreamReader reader , int index ) throws XMLStreamException { String roles = reader . getAttributeValue ( index ) ; return asList ( roles . split ( \"[,\\\\s]+\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that not both elements have been defined [CODESPLIT] protected static void checkNotBothElements ( XMLExtendedStreamReader reader , Set < Element > seen , Element element1 , Element element2 ) throws XMLStreamException { if ( seen . contains ( element1 ) && seen . contains ( element2 ) ) { throw new XMLStreamException ( MessagingLogger . ROOT_LOGGER . onlyOneRequired ( element1 . getLocalName ( ) , element2 . getLocalName ( ) ) , reader . getLocation ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns an <code > Object< / code > result to the caller . [CODESPLIT] public Object invoke ( String operationName , final StubStrategy stubStrategy , Object [ ] params ) throws Throwable { if ( operationName . equals ( \"_get_handle\" ) && this instanceof javax . ejb . EJBObject ) { if ( handle == null ) { handle = new HandleImplIIOP ( this ) ; } return handle ; } else if ( operationName . equals ( \"_get_homeHandle\" ) && this instanceof javax . ejb . EJBHome ) { if ( handle == null ) { handle = new HomeHandleImplIIOP ( this ) ; } return handle ; } else { //FIXME // all invocations are now made using remote invocation // local invocations between two different applications cause // ClassCastException between Stub and Interface // (two different modules are loading the classes) // problem was unnoticeable with JacORB because it uses // remote invocations to all stubs to which interceptors are // registered and a result all that JacORB always used // remote invocations // remote call path // To check whether this is a local stub or not we must call // org.omg.CORBA.portable.ObjectImpl._is_local(), and _not_ // javax.rmi.CORBA.Util.isLocal(Stub s), which in Sun's JDK // always return false. InputStream in = null ; try { try { OutputStream out = ( OutputStream ) _request ( operationName , true ) ; stubStrategy . writeParams ( out , params ) ; tracef ( \"sent request: %s\" , operationName ) ; in = ( InputStream ) _invoke ( out ) ; if ( stubStrategy . isNonVoid ( ) ) { trace ( \"received reply\" ) ; final InputStream finalIn = in ; return doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { return stubStrategy . readRetval ( finalIn ) ; } } ) ; } else { return null ; } } catch ( final ApplicationException ex ) { trace ( \"got application exception\" ) ; in = ( InputStream ) ex . getInputStream ( ) ; final InputStream finalIn1 = in ; throw doPrivileged ( new PrivilegedAction < Exception > ( ) { public Exception run ( ) { return stubStrategy . readException ( ex . getId ( ) , finalIn1 ) ; } } ) ; } catch ( RemarshalException ex ) { trace ( \"got remarshal exception\" ) ; return invoke ( operationName , stubStrategy , params ) ; } } catch ( SystemException ex ) { if ( EjbLogger . EJB3_INVOCATION_LOGGER . isTraceEnabled ( ) ) { EjbLogger . EJB3_INVOCATION_LOGGER . trace ( \"CORBA system exception in IIOP stub\" , ex ) ; } throw Util . mapSystemException ( ex ) ; } finally { _releaseReply ( in ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns a <code > boolean< / code > result to the caller . [CODESPLIT] public boolean invokeBoolean ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Boolean ) invoke ( operationName , stubStrategy , params ) ) . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns a <code > byte< / code > result to the caller . [CODESPLIT] public byte invokeByte ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Number ) invoke ( operationName , stubStrategy , params ) ) . byteValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns a <code > char< / code > result to the caller . [CODESPLIT] public char invokeChar ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Character ) invoke ( operationName , stubStrategy , params ) ) . charValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns a <code > short< / code > result to the caller . [CODESPLIT] public short invokeShort ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Number ) invoke ( operationName , stubStrategy , params ) ) . shortValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns an <code > int< / code > result to the caller . [CODESPLIT] public int invokeInt ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Number ) invoke ( operationName , stubStrategy , params ) ) . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns a <code > long< / code > result to the caller . [CODESPLIT] public long invokeLong ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Number ) invoke ( operationName , stubStrategy , params ) ) . longValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns a <code > float< / code > result to the caller . [CODESPLIT] public float invokeFloat ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Number ) invoke ( operationName , stubStrategy , params ) ) . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a request message to the server receives the reply from the server and returns a <code > double< / code > result to the caller . [CODESPLIT] public double invokeDouble ( String operationName , StubStrategy stubStrategy , Object [ ] params ) throws Throwable { return ( ( Number ) invoke ( operationName , stubStrategy , params ) ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a setting . [CODESPLIT] static AddressSettings createSettings ( final OperationContext context , final ModelNode config ) throws OperationFailedException { final AddressSettings settings = new AddressSettings ( ) ; if ( config . hasDefined ( AddressSettingDefinition . ADDRESS_FULL_MESSAGE_POLICY . getName ( ) ) ) { final AddressFullMessagePolicy addressPolicy = AddressFullMessagePolicy . valueOf ( AddressSettingDefinition . ADDRESS_FULL_MESSAGE_POLICY . resolveModelAttribute ( context , config ) . asString ( ) ) ; settings . setAddressFullMessagePolicy ( addressPolicy ) ; } if ( config . hasDefined ( DEAD_LETTER_ADDRESS . getName ( ) ) ) { settings . setDeadLetterAddress ( asSimpleString ( DEAD_LETTER_ADDRESS . resolveModelAttribute ( context , config ) , null ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . LAST_VALUE_QUEUE . getName ( ) ) ) { settings . setDefaultLastValueQueue ( AddressSettingDefinition . LAST_VALUE_QUEUE . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . MAX_DELIVERY_ATTEMPTS . getName ( ) ) ) { settings . setMaxDeliveryAttempts ( AddressSettingDefinition . MAX_DELIVERY_ATTEMPTS . resolveModelAttribute ( context , config ) . asInt ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . MAX_SIZE_BYTES . getName ( ) ) ) { settings . setMaxSizeBytes ( AddressSettingDefinition . MAX_SIZE_BYTES . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . MESSAGE_COUNTER_HISTORY_DAY_LIMIT . getName ( ) ) ) { settings . setMessageCounterHistoryDayLimit ( AddressSettingDefinition . MESSAGE_COUNTER_HISTORY_DAY_LIMIT . resolveModelAttribute ( context , config ) . asInt ( ) ) ; } if ( config . hasDefined ( CommonAttributes . EXPIRY_ADDRESS . getName ( ) ) ) { settings . setExpiryAddress ( asSimpleString ( EXPIRY_ADDRESS . resolveModelAttribute ( context , config ) , null ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . EXPIRY_DELAY . getName ( ) ) ) { settings . setExpiryDelay ( AddressSettingDefinition . EXPIRY_DELAY . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . REDELIVERY_DELAY . getName ( ) ) ) { settings . setRedeliveryDelay ( AddressSettingDefinition . REDELIVERY_DELAY . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . REDELIVERY_MULTIPLIER . getName ( ) ) ) { settings . setRedeliveryMultiplier ( AddressSettingDefinition . REDELIVERY_MULTIPLIER . resolveModelAttribute ( context , config ) . asDouble ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . MAX_REDELIVERY_DELAY . getName ( ) ) ) { settings . setMaxRedeliveryDelay ( AddressSettingDefinition . MAX_REDELIVERY_DELAY . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . REDISTRIBUTION_DELAY . getName ( ) ) ) { settings . setRedistributionDelay ( AddressSettingDefinition . REDISTRIBUTION_DELAY . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . PAGE_SIZE_BYTES . getName ( ) ) ) { settings . setPageSizeBytes ( AddressSettingDefinition . PAGE_SIZE_BYTES . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . PAGE_MAX_CACHE_SIZE . getName ( ) ) ) { settings . setPageCacheMaxSize ( AddressSettingDefinition . PAGE_MAX_CACHE_SIZE . resolveModelAttribute ( context , config ) . asInt ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . SEND_TO_DLA_ON_NO_ROUTE . getName ( ) ) ) { settings . setSendToDLAOnNoRoute ( AddressSettingDefinition . SEND_TO_DLA_ON_NO_ROUTE . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . SLOW_CONSUMER_CHECK_PERIOD . getName ( ) ) ) { settings . setSlowConsumerCheckPeriod ( AddressSettingDefinition . SLOW_CONSUMER_CHECK_PERIOD . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } if ( config . hasDefined ( AddressSettingDefinition . SLOW_CONSUMER_POLICY . getName ( ) ) ) { final SlowConsumerPolicy slowConsumerPolicy = SlowConsumerPolicy . valueOf ( AddressSettingDefinition . SLOW_CONSUMER_POLICY . resolveModelAttribute ( context , config ) . asString ( ) ) ; settings . setSlowConsumerPolicy ( slowConsumerPolicy ) ; } if ( config . hasDefined ( AddressSettingDefinition . SLOW_CONSUMER_THRESHOLD . getName ( ) ) ) { settings . setSlowConsumerThreshold ( AddressSettingDefinition . SLOW_CONSUMER_THRESHOLD . resolveModelAttribute ( context , config ) . asLong ( ) ) ; } // always set the auto-create|delete-jms-queues attributes as their default attribute values differ from Artemis defaults. settings . setAutoCreateJmsQueues ( AddressSettingDefinition . AUTO_CREATE_JMS_QUEUES . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; settings . setAutoDeleteJmsQueues ( AddressSettingDefinition . AUTO_DELETE_JMS_QUEUES . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; settings . setAutoCreateQueues ( AddressSettingDefinition . AUTO_CREATE_QUEUES . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; settings . setAutoDeleteQueues ( AddressSettingDefinition . AUTO_DELETE_QUEUES . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; settings . setAutoCreateAddresses ( AddressSettingDefinition . AUTO_CREATE_ADDRESSES . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; settings . setAutoDeleteAddresses ( AddressSettingDefinition . AUTO_DELETE_ADDRESSES . resolveModelAttribute ( context , config ) . asBoolean ( ) ) ; return settings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds or retrieves an existing EEModuleClassDescription for the local module . This method should only be used for classes that reside within the current deployment unit usually by annotation scanners that are attaching annotation information . <p / > This [CODESPLIT] public EEModuleClassDescription addOrGetLocalClassDescription ( final String className ) { if ( className == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( \"className\" , \"module\" , moduleName ) ; } EEModuleClassDescription ret = classDescriptions . get ( className ) ; if ( ret == null ) { classDescriptions . put ( className , ret = new EEModuleClassDescription ( className ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a component to this module . [CODESPLIT] public void addComponent ( ComponentDescription description ) { final String componentName = description . getComponentName ( ) ; final String componentClassName = description . getComponentClassName ( ) ; if ( componentName == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( \"componentName\" , \"module\" , moduleName ) ; } if ( componentClassName == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( \"componentClassName\" , \"module\" , moduleName ) ; } if ( componentsByName . containsKey ( componentName ) ) { throw EeLogger . ROOT_LOGGER . componentAlreadyDefined ( componentName ) ; } componentsByName . put ( componentName , description ) ; List < ComponentDescription > list = componentsByClassName . get ( componentClassName ) ; if ( list == null ) { componentsByClassName . put ( componentClassName , list = new ArrayList < ComponentDescription > ( 1 ) ) ; } list . add ( description ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a top level class loader to all CL s in the deployment [CODESPLIT] public static void addClassLoaders ( ClassLoader topLevel , Set < ClassLoader > allClassLoaders ) { deploymentClassLoaders . put ( topLevel , allClassLoaders ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TransformedOperation transformOperation ( TransformationContext context , PathAddress address , ModelNode operation ) { String name = Operations . getAttributeName ( operation ) ; ModelNode value = Operations . getAttributeValue ( operation ) ; ModelNode legacyOperation = org . jboss . as . controller . client . helpers . Operations . createWriteAttributeOperation ( this . addressTransformer . transform ( address ) . toModelNode ( ) , name , value ) ; return new TransformedOperation ( legacyOperation , OperationResultTransformer . ORIGINAL_RESULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void bind ( Name name , Object object ) throws NamingException { bind ( name , object , object . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void bind ( final Name name , final Object object , final Class < ? > bindType ) throws NamingException { if ( isLastComponentEmpty ( name ) ) { throw emptyNameException ( ) ; } writeLock . lock ( ) ; try { root . accept ( new BindVisitor ( true , name , object , bindType . getName ( ) ) ) ; } finally { writeLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void rebind ( Name name , Object object ) throws NamingException { rebind ( name , object , object . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void rebind ( final Name name , final Object object , final Class < ? > bindType ) throws NamingException { if ( isLastComponentEmpty ( name ) ) { throw emptyNameException ( ) ; } writeLock . lock ( ) ; try { root . accept ( new RebindVisitor ( name , object , bindType . getName ( ) ) ) ; } finally { writeLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbind the entry in the provided location . This will remove the node in the tree and no longer manage it . [CODESPLIT] public void unbind ( final Name name ) throws NamingException { if ( isLastComponentEmpty ( name ) ) { throw emptyNameException ( ) ; } writeLock . lock ( ) ; try { root . accept ( new UnbindVisitor ( name ) ) ; } finally { writeLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup the object value of a binding node in the tree . [CODESPLIT] public Object lookup ( final Name name ) throws NamingException { if ( isEmpty ( name ) ) { final Name emptyName = new CompositeName ( \"\" ) ; return new NamingContext ( emptyName , this , new Hashtable < String , Object > ( ) ) ; } return root . accept ( new LookupVisitor ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List all NameClassPair instances at a given location in the tree . [CODESPLIT] public List < NameClassPair > list ( final Name name ) throws NamingException { final Name nodeName = name . isEmpty ( ) ? new CompositeName ( \"\" ) : name ; return root . accept ( new ListVisitor ( nodeName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List all the Binding instances at a given location in the tree . [CODESPLIT] public List < Binding > listBindings ( final Name name ) throws NamingException { final Name nodeName = name . isEmpty ( ) ? new CompositeName ( \"\" ) : name ; return root . accept ( new ListBindingsVisitor ( nodeName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { @code NamingListener } to the naming event coordinator . [CODESPLIT] public void addNamingListener ( final Name target , final int scope , final NamingListener listener ) { final NamingEventCoordinator coordinator = eventCoordinator ; if ( coordinator != null ) { coordinator . addListener ( target . toString ( ) , scope , listener ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a { @code NamingListener } from the naming event coordinator . [CODESPLIT] public void removeNamingListener ( final NamingListener listener ) { final NamingEventCoordinator coordinator = eventCoordinator ; if ( coordinator != null ) { coordinator . removeListener ( listener ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Principal given the authenticated Subject . Currently the first principal that is not of type { @code Group } is considered or the single principal inside the CallerPrincipal group . [CODESPLIT] private Principal getPrincipal ( Subject subject ) { Principal principal = null ; Principal callerPrincipal = null ; if ( subject != null ) { Set < Principal > principals = subject . getPrincipals ( ) ; if ( principals != null && ! principals . isEmpty ( ) ) { for ( Principal p : principals ) { if ( ! ( p instanceof Group ) && principal == null ) { principal = p ; } if ( p instanceof Group ) { Group g = Group . class . cast ( p ) ; if ( g . getName ( ) . equals ( SecurityConstants . CALLER_PRINCIPAL_GROUP ) && callerPrincipal == null ) { Enumeration < ? extends Principal > e = g . members ( ) ; if ( e . hasMoreElements ( ) ) callerPrincipal = e . nextElement ( ) ; } } } } } return callerPrincipal == null ? principal : callerPrincipal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the <server / > element based on version 1 . 0 of the schema . [CODESPLIT] private void readServerElement_1_0 ( final XMLExtendedStreamReader reader , final ModelNode address , final List < ModelNode > list ) throws XMLStreamException { parseNamespaces ( reader , address , list ) ; String serverName = null ; // attributes final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { switch ( Namespace . forUri ( reader . getAttributeNamespace ( i ) ) ) { case NONE : { final String value = reader . getAttributeValue ( i ) ; final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; switch ( attribute ) { case NAME : { serverName = value ; break ; } default : throw unexpectedAttribute ( reader , i ) ; } break ; } case XML_SCHEMA_INSTANCE : { switch ( Attribute . forName ( reader . getAttributeLocalName ( i ) ) ) { case SCHEMA_LOCATION : { parseSchemaLocations ( reader , address , list , i ) ; break ; } case NO_NAMESPACE_SCHEMA_LOCATION : { // todo, jeez break ; } default : { throw unexpectedAttribute ( reader , i ) ; } } break ; } default : throw unexpectedAttribute ( reader , i ) ; } } setServerName ( address , list , serverName ) ; // elements - sequence Element element = nextElement ( reader , DOMAIN_1_0 ) ; if ( element == Element . EXTENSIONS ) { extensionXml . parseExtensions ( reader , address , DOMAIN_1_0 , list ) ; element = nextElement ( reader , DOMAIN_1_0 ) ; } // System properties if ( element == Element . SYSTEM_PROPERTIES ) { parseSystemProperties ( reader , address , DOMAIN_1_0 , list , true ) ; element = nextElement ( reader , DOMAIN_1_0 ) ; } if ( element == Element . PATHS ) { parsePaths ( reader , address , DOMAIN_1_0 , list , true ) ; element = nextElement ( reader , DOMAIN_1_0 ) ; } // Single profile if ( element == Element . PROFILE ) { parseServerProfile ( reader , address , list ) ; element = nextElement ( reader , DOMAIN_1_0 ) ; } // Interfaces final Set < String > interfaceNames = new HashSet < String > ( ) ; if ( element == Element . INTERFACES ) { parseInterfaces ( reader , interfaceNames , address , DOMAIN_1_0 , list , true ) ; element = nextElement ( reader , DOMAIN_1_0 ) ; } // Single socket binding group if ( element == Element . SOCKET_BINDING_GROUP ) { parseSocketBindingGroup ( reader , interfaceNames , address , DOMAIN_1_0 , list ) ; element = nextElement ( reader , DOMAIN_1_0 ) ; } if ( element != null ) { throw unexpectedElement ( reader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add dependencies for modules required for ra deployments [CODESPLIT] public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; if ( phaseContext . getDeploymentUnit ( ) . getAttachment ( ConnectorXmlDescriptor . ATTACHMENT_KEY ) == null ) { return ; // Skip non ra deployments } CopyOnWriteArrayListMultiMap < String , ServiceName > resourceAdaptersMap = phaseContext . getDeploymentUnit ( ) . getAttachment ( ResourceAdaptersSubsystemService . ATTACHMENT_KEY ) ; String deploymentUnitPrefix = \"\" ; if ( deploymentUnit . getParent ( ) != null ) { deploymentUnitPrefix = deploymentUnit . getParent ( ) . getName ( ) + \"#\" ; } final String deploymentUnitName = deploymentUnitPrefix + deploymentUnit . getName ( ) ; if ( resourceAdaptersMap != null && resourceAdaptersMap . get ( deploymentUnitName ) != null ) { for ( ServiceName serviceName : resourceAdaptersMap . get ( deploymentUnitName ) ) { phaseContext . addDeploymentDependency ( serviceName , AttachmentKey . create ( ModifiableResourceAdapter . class ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object writeReplace ( Object object ) { return EJBClient . isEJBProxy ( object ) ? new SerializableEJBProxy ( object ) : object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new factory . [CODESPLIT] public synchronized void addFactory ( ContextHandleFactory factory ) { final String factoryName = factory . getName ( ) ; if ( factoryMap . containsKey ( factoryName ) ) { throw EeLogger . ROOT_LOGGER . factoryAlreadyExists ( this , factoryName ) ; } factoryMap . put ( factoryName , factory ) ; final Comparator < ContextHandleFactory > comparator = new Comparator < ContextHandleFactory > ( ) { @ Override public int compare ( ContextHandleFactory o1 , ContextHandleFactory o2 ) { return Integer . compare ( o1 . getChainPriority ( ) , o2 . getChainPriority ( ) ) ; } } ; SortedSet < ContextHandleFactory > sortedSet = new TreeSet <> ( comparator ) ; sortedSet . addAll ( factoryMap . values ( ) ) ; factoryOrderedList = new ArrayList <> ( sortedSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves the current invocation context on a chained context handle . [CODESPLIT] public SetupContextHandle saveContext ( ContextService contextService , Map < String , String > contextObjectProperties ) { final List < SetupContextHandle > handles = new ArrayList <> ( factoryOrderedList . size ( ) ) ; for ( ContextHandleFactory factory : factoryOrderedList ) { handles . add ( factory . saveContext ( contextService , contextObjectProperties ) ) ; } return new ChainedSetupContextHandle ( this , handles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object getObjectInstance ( Object obj , Name name , Context nameCtx , Hashtable < ? , ? > environment ) throws Exception { return new NamingContext ( name != null ? name : new CompositeName ( \"\" ) , environment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds multiple accessible { [CODESPLIT] public void addBeanDeploymentArchives ( Collection < ? extends BeanDeploymentArchive > archives ) { for ( BeanDeploymentArchive bda : archives ) { if ( bda != this ) { beanDeploymentArchives . add ( bda ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if a class from this { @link BeanDeploymentArchiveImpl } instance can access a class in the { @link BeanDeploymentArchive } instance represented by the specified <code > BeanDeploymentArchive< / code > parameter according to the Java EE class accessibility requirements . [CODESPLIT] public boolean isAccessible ( BeanDeploymentArchive target ) { if ( this == target ) { return true ; } BeanDeploymentArchiveImpl that = ( BeanDeploymentArchiveImpl ) target ; if ( that . getModule ( ) == null ) { /*\n             * The target BDA is the bootstrap BDA - it bundles classes loaded by the bootstrap classloader.\n             * Everyone can see the bootstrap classloader.\n             */ return true ; } if ( module == null ) { /*\n             * This BDA is the bootstrap BDA - it bundles classes loaded by the bootstrap classloader. We assume that a\n             * bean whose class is loaded by the bootstrap classloader can only see other beans in the \"bootstrap BDA\".\n             */ return that . getModule ( ) == null ; } if ( module . equals ( that . getModule ( ) ) ) { return true ; } // basic check whether the module is our dependency for ( DependencySpec dependency : module . getDependencies ( ) ) { if ( dependency instanceof ModuleDependencySpec ) { ModuleDependencySpec moduleDependency = ( ModuleDependencySpec ) dependency ; if ( moduleDependency . getIdentifier ( ) . equals ( that . getModule ( ) . getIdentifier ( ) ) ) { return true ; } // moduleDependency might be an alias - try to load it to get lined module Module module = loadModule ( moduleDependency ) ; if ( module != null && module . getIdentifier ( ) . equals ( that . getModule ( ) . getIdentifier ( ) ) ) { return true ; } } } /*\n         * full check - we try to load a class from the target bean archive and check whether its module\n         * is the same as the one of the bean archive\n         * See WFLY-4250 for more info\n         */ Iterator < String > iterator = target . getBeanClasses ( ) . iterator ( ) ; if ( iterator . hasNext ( ) ) { Class < ? > clazz = Reflections . loadClass ( iterator . next ( ) , module . getClassLoader ( ) ) ; if ( clazz != null ) { Module classModule = Module . forClass ( clazz ) ; return classModule != null && classModule . equals ( that . getModule ( ) ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the security realm [CODESPLIT] private SSLInformation createSecurityRealm ( OperationContext context , Map < PathAddress , ModelNode > migrationOperations , ModelNode legacyModelAddOps , String connector , ModelNode legacyAddOp , List < String > warnings , boolean domainMode ) { //read all the info from the SSL definition ModelNode keyAlias = legacyAddOp . get ( WebSSLDefinition . KEY_ALIAS . getName ( ) ) ; ModelNode password = legacyAddOp . get ( WebSSLDefinition . PASSWORD . getName ( ) ) ; ModelNode certificateKeyFile = legacyAddOp . get ( WebSSLDefinition . CERTIFICATE_KEY_FILE . getName ( ) ) ; ModelNode cipherSuite = legacyAddOp . get ( WebSSLDefinition . CIPHER_SUITE . getName ( ) ) ; ModelNode protocol = legacyAddOp . get ( WebSSLDefinition . PROTOCOL . getName ( ) ) ; ModelNode verifyClient = legacyAddOp . get ( WebSSLDefinition . VERIFY_CLIENT . getName ( ) ) ; ModelNode verifyDepth = legacyAddOp . get ( WebSSLDefinition . VERIFY_DEPTH . getName ( ) ) ; ModelNode certificateFile = legacyAddOp . get ( WebSSLDefinition . CERTIFICATE_FILE . getName ( ) ) ; ModelNode caCertificateFile = legacyAddOp . get ( WebSSLDefinition . CA_CERTIFICATE_FILE . getName ( ) ) ; ModelNode caCertificatePassword = legacyAddOp . get ( WebSSLDefinition . CA_CERTIFICATE_PASSWORD . getName ( ) ) ; ModelNode csRevocationURL = legacyAddOp . get ( WebSSLDefinition . CA_REVOCATION_URL . getName ( ) ) ; ModelNode trustStoreType = legacyAddOp . get ( WebSSLDefinition . TRUSTSTORE_TYPE . getName ( ) ) ; ModelNode keystoreType = legacyAddOp . get ( WebSSLDefinition . KEYSTORE_TYPE . getName ( ) ) ; ModelNode sessionCacheSize = legacyAddOp . get ( WebSSLDefinition . SESSION_CACHE_SIZE . getName ( ) ) ; ModelNode sessionTimeout = legacyAddOp . get ( WebSSLDefinition . SESSION_TIMEOUT . getName ( ) ) ; ModelNode sslProvider = legacyAddOp . get ( WebSSLDefinition . SSL_PROTOCOL . getName ( ) ) ; if ( verifyDepth . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . VERIFY_DEPTH . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } if ( certificateFile . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . CERTIFICATE_FILE . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } if ( sslProvider . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . SSL_PROTOCOL . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } if ( csRevocationURL . isDefined ( ) ) { warnings . add ( WebLogger . ROOT_LOGGER . couldNotMigrateResource ( WebSSLDefinition . CA_REVOCATION_URL . getName ( ) , pathAddress ( legacyAddOp . get ( ADDRESS ) ) ) ) ; } String realmName ; PathAddress managementCoreService ; if ( domainMode ) { Set < String > hosts = new HashSet <> ( ) ; Resource hostResource = context . readResourceFromRoot ( pathAddress ( ) , false ) ; hosts . addAll ( hostResource . getChildrenNames ( HOST ) ) ; //now we need to find a unique name //in domain mode different profiles could have different SSL configurations //but the realms are not scoped to a profile //if we hard coded a name migration would fail when migrating domains with multiple profiles int counter = 1 ; realmName = REALM_NAME + counter ; while ( true ) { boolean hostOk = true ; for ( String host : hosts ) { Resource root = context . readResourceFromRoot ( pathAddress ( pathElement ( HOST , host ) , pathElement ( CORE_SERVICE , MANAGEMENT ) ) , false ) ; if ( root . getChildrenNames ( SECURITY_REALM ) . contains ( realmName ) ) { counter ++ ; realmName = REALM_NAME + counter ; hostOk = false ; break ; } } if ( hostOk ) { break ; } } for ( String host : hosts ) { createHostSSLConfig ( realmName , migrationOperations , keyAlias , password , certificateKeyFile , protocol , caCertificateFile , caCertificatePassword , trustStoreType , keystoreType , pathAddress ( pathElement ( HOST , host ) , pathElement ( CORE_SERVICE , MANAGEMENT ) ) ) ; } } else { managementCoreService = pathAddress ( CORE_SERVICE , MANAGEMENT ) ; //now we need to find a unique name //in domain mode different profiles could have different SSL configurations //but the realms are not scoped to a profile //if we hard coded a name migration would fail when migrating domains with multiple profiles int counter = 1 ; realmName = REALM_NAME + counter ; boolean ok = false ; do { Resource root = context . readResourceFromRoot ( managementCoreService , false ) ; if ( root . getChildrenNames ( SECURITY_REALM ) . contains ( realmName ) ) { counter ++ ; realmName = REALM_NAME + counter ; } else { ok = true ; } } while ( ! ok ) ; //we have a unique realm name createHostSSLConfig ( realmName , migrationOperations , keyAlias , password , certificateKeyFile , protocol , caCertificateFile , caCertificatePassword , trustStoreType , keystoreType , managementCoreService ) ; } return new SSLInformation ( realmName , verifyClient , sessionCacheSize , sessionTimeout , protocol , cipherSuite ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We need to create the IO subsystem if it does not already exist [CODESPLIT] private void createIoSubsystem ( OperationContext context , Map < PathAddress , ModelNode > migrationOperations , PathAddress baseAddress ) { Resource root = context . readResourceFromRoot ( baseAddress , false ) ; if ( root . getChildrenNames ( SUBSYSTEM ) . contains ( IOExtension . SUBSYSTEM_NAME ) ) { // subsystem is already added, do nothing return ; } //these addresses will be fixed later, no need to use the base address PathAddress address = pathAddress ( pathElement ( SUBSYSTEM , IOExtension . SUBSYSTEM_NAME ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; address = pathAddress ( pathElement ( SUBSYSTEM , IOExtension . SUBSYSTEM_NAME ) , pathElement ( \"worker\" , \"default\" ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; address = pathAddress ( pathElement ( SUBSYSTEM , IOExtension . SUBSYSTEM_NAME ) , pathElement ( \"buffer-pool\" , \"default\" ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a handler for serving welcome content [CODESPLIT] private void createWelcomeContentHandler ( Map < PathAddress , ModelNode > migrationOperations ) { PathAddress address = pathAddress ( pathElement ( SUBSYSTEM , UndertowExtension . SUBSYSTEM_NAME ) , pathElement ( Constants . CONFIGURATION , Constants . HANDLER ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; address = pathAddress ( pathElement ( SUBSYSTEM , UndertowExtension . SUBSYSTEM_NAME ) , pathElement ( Constants . CONFIGURATION , Constants . HANDLER ) , pathElement ( Constants . FILE , \"welcome-content\" ) ) ; final ModelNode add = createAddOperation ( address ) ; add . get ( Constants . PATH ) . set ( new ModelNode ( new ValueExpression ( \"${jboss.home.dir}/welcome-content\" ) ) ) ; migrationOperations . put ( address , add ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name of the resource adapter which will be used as the default RA for MDBs ( unless overridden by the MDBs ) . [CODESPLIT] private String getDefaultResourceAdapterName ( final ServiceRegistry serviceRegistry ) { if ( appclient ) { // we must report the MDB, but we can't use any MDB/JCA facilities return \"n/a\" ; } final ServiceController < DefaultResourceAdapterService > serviceController = ( ServiceController < DefaultResourceAdapterService > ) serviceRegistry . getRequiredService ( DefaultResourceAdapterService . DEFAULT_RA_NAME_SERVICE_NAME ) ; return serviceController . getValue ( ) . getDefaultResourceAdapterName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an instance without identity . Can be used by finders create - methods and activation [CODESPLIT] public T get ( ) { try { boolean acquired = semaphore . tryAcquire ( timeout , timeUnit ) ; if ( ! acquired ) throw EjbLogger . ROOT_LOGGER . failedToAcquirePermit ( timeout , timeUnit ) ; } catch ( InterruptedException e ) { throw EjbLogger . ROOT_LOGGER . acquireSemaphoreInterrupted ( ) ; } T bean = pool . poll ( ) ; if ( bean != null ) { //we found a bean instance in the pool, return it return bean ; } try { // Pool is empty, create an instance bean = create ( ) ; } finally { if ( bean == null ) { semaphore . release ( ) ; } } return bean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an instance after invocation . <p / > Called in 2 cases : a ) Done with finder method b ) Just removed [CODESPLIT] public void release ( T obj ) { if ( ROOT_LOGGER . isTraceEnabled ( ) ) { ROOT_LOGGER . tracef ( \"%s/%s Free instance: %s\" , pool . size ( ) , maxSize , this ) ; } pool . add ( obj ) ; semaphore . release ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a list of all the entries contained here . [CODESPLIT] protected ArrayList getContainedEntries ( ) { final ArrayList ret = new ArrayList ( constants . length + attributes . length + operations . length ) ; for ( int i = 0 ; i < constants . length ; ++ i ) ret . ( constants [ i ] ) ; for ( int i = 0 ; i < attributes . length ; ++ i ) ret . ( attributes [ i ] ) ; for ( int i = 0 ; i < operations . length ; ++ i ) ret . ( operations [ i ] ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyse operations . This will fill in the <code > operations< / code > array . [CODESPLIT] protected void analyzeOperations ( ) throws RMIIIOPViolationException { if ( ! cls . isInterface ( ) ) throw IIOPLogger . ROOT_LOGGER . notAnInterface ( cls . getName ( ) ) ; abstractInterface = RmiIdlUtil . isAbstractInterface ( cls ) ; calculateAllTypeIds ( ) ; int operationCount = 0 ; for ( int i = 0 ; i < methods . length ; ++ i ) if ( ( m_flags [ i ] & ( M_READ | M_WRITE | M_READONLY ) ) == 0 ) ++ operationCount ; operations = new OperationAnalysis [ operationCount ] ; operationCount = 0 ; for ( int i = 0 ; i < methods . length ; ++ i ) { if ( ( m_flags [ i ] & ( M_READ | M_WRITE | M_READONLY ) ) == 0 ) { operations [ operationCount ] = new OperationAnalysis ( methods [ i ] ) ; ++ operationCount ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the map that maps IDL operation names to operation analyses . Besides mapped operations this map also contains the attribute accessor and mutator operations . [CODESPLIT] protected void calculateOperationAnalysisMap ( ) { operationAnalysisMap = new HashMap ( ) ; OperationAnalysis oa ; // Map the operations for ( int i = 0 ; i < operations . length ; ++ i ) { oa = operations [ i ] ; operationAnalysisMap . put ( oa . getIDLName ( ) , oa ) ; } // Map the attributes for ( int i = 0 ; i < attributes . length ; ++ i ) { AttributeAnalysis attr = attributes [ i ] ; oa = attr . getAccessorAnalysis ( ) ; // Not having an accessor analysis means that // the attribute is not in a remote interface if ( oa != null ) { operationAnalysisMap . put ( oa . getIDLName ( ) , oa ) ; oa = attr . getMutatorAnalysis ( ) ; if ( oa != null ) operationAnalysisMap . put ( oa . getIDLName ( ) , oa ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the array containing all type ids of this interface in the format that org . omg . CORBA . portable . Servant . _all_interfaces () is expected to return . [CODESPLIT] protected void calculateAllTypeIds ( ) { if ( ! isRmiIdlRemoteInterface ( ) ) { allTypeIds = new String [ 0 ] ; } else { ArrayList a = new ArrayList ( ) ; InterfaceAnalysis [ ] intfs = getInterfaces ( ) ; for ( int i = 0 ; i < intfs . length ; ++ i ) { String [ ] ss = intfs [ i ] . getAllTypeIds ( ) ; for ( int j = 0 ; j < ss . length ; ++ j ) if ( ! a . contains ( ss [ j ] ) ) a . add ( ss [ j ] ) ; } allTypeIds = new String [ a . size ( ) + 1 ] ; allTypeIds [ 0 ] = getRepositoryId ( ) ; for ( int i = 1 ; i <= a . size ( ) ; ++ i ) allTypeIds [ i ] = ( String ) . get ( a . size ( ) - i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "collect metrics from the resources [CODESPLIT] public MetricRegistration collectResourceMetrics ( final Resource resource , ImmutableManagementResourceRegistration managementResourceRegistration , Function < PathAddress , PathAddress > resourceAddressResolver ) { MetricRegistration registration = new MetricRegistration ( ) ; collectResourceMetrics0 ( resource , managementResourceRegistration , EMPTY_ADDRESS , resourceAddressResolver , registration ) ; return registration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare the ws Deployment and return a DeploymentUnit containing it [CODESPLIT] protected DeploymentUnit doPrepare ( String context , ClassLoader loader , Map < String , String > urlPatternToClassNameMap , JBossWebMetaData jbwmd , WebservicesMetaData metadata , JBossWebservicesMetaData jbwsMetadata ) { ClassLoader origClassLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; WSEndpointDeploymentUnit unit = new WSEndpointDeploymentUnit ( loader , context , urlPatternToClassNameMap , jbwmd , metadata , jbwsMetadata ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( ClassLoaderProvider . getDefaultProvider ( ) . getServerIntegrationClassLoader ( ) ) ; WSDeploymentBuilder . getInstance ( ) . build ( unit ) ; return unit ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( origClassLoader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers the WS deployment aspects which process the deployment and install the endpoint services . [CODESPLIT] protected void doDeploy ( ServiceTarget target , DeploymentUnit unit ) { List < DeploymentAspect > aspects = getDeploymentAspects ( ) ; ClassLoader origClassLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; Deployment dep = null ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( ClassLoaderProvider . getDefaultProvider ( ) . getServerIntegrationClassLoader ( ) ) ; dep = unit . getAttachment ( WSAttachmentKeys . DEPLOYMENT_KEY ) ; dep . addAttachment ( ServiceTarget . class , target ) ; DeploymentAspectManager dam = new DeploymentAspectManagerImpl ( ) ; dam . setDeploymentAspects ( aspects ) ; dam . deploy ( dep ) ; } finally { if ( dep != null ) { dep . removeAttachment ( ServiceTarget . class ) ; } WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( origClassLoader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Publish the webapp for the WS deployment unit [CODESPLIT] protected Context doPublish ( ServiceTarget target , DeploymentUnit unit ) throws Exception { Deployment deployment = unit . getAttachment ( WSAttachmentKeys . DEPLOYMENT_KEY ) ; List < Endpoint > endpoints = deployment . getService ( ) . getEndpoints ( ) ; //If we're running in a Service, that will already have proper dependencies set on the installed endpoint services, //otherwise we need to explicitly wait for the endpoint services to be started before creating the webapp. if ( ! runningInService ) { final ServiceRegistry registry = unit . getServiceRegistry ( ) ; final StabilityMonitor monitor = new StabilityMonitor ( ) ; for ( Endpoint ep : endpoints ) { final ServiceName serviceName = EndpointService . getServiceName ( unit , ep . getShortName ( ) ) ; monitor . addController ( registry . getRequiredService ( serviceName ) ) ; } try { monitor . awaitStability ( ) ; } finally { monitor . clear ( ) ; } } deployment . addAttachment ( WebDeploymentController . class , startWebApp ( host , unit ) ) ; //TODO simplify and use findChild later in destroy()/stopWebApp() return new Context ( unit . getAttachment ( WSAttachmentKeys . JBOSSWEB_METADATA_KEY ) . getContextRoot ( ) , endpoints ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the webapp serving the provided ws deployment [CODESPLIT] protected void stopWebApp ( Deployment deployment ) throws Exception { WebDeploymentController context ; try { context = deployment . getAttachment ( WebDeploymentController . class ) ; context . stop ( ) ; } catch ( Exception e ) { throw WSLogger . ROOT_LOGGER . stopContextPhaseFailed ( e ) ; } try { context . destroy ( ) ; } catch ( Exception e ) { throw WSLogger . ROOT_LOGGER . destroyContextPhaseFailed ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the weld container [CODESPLIT] public synchronized void start ( final StartContext context ) { if ( started ) { throw WeldLogger . ROOT_LOGGER . alreadyRunning ( \"WeldContainer\" ) ; } started = true ; WeldLogger . DEPLOYMENT_LOGGER . startingWeldService ( deploymentName ) ; // set up injected services addWeldService ( SecurityServices . class , securityServicesSupplier . get ( ) ) ; TransactionServices transactionServices = weldTransactionServicesSupplier != null ? weldTransactionServicesSupplier . get ( ) : null ; if ( transactionServices != null ) { addWeldService ( TransactionServices . class , transactionServices ) ; } if ( ! deployment . getServices ( ) . contains ( ExecutorServices . class ) ) { addWeldService ( ExecutorServices . class , executorServicesSupplier . get ( ) ) ; } ModuleGroupSingletonProvider . addClassLoaders ( deployment . getModule ( ) . getClassLoader ( ) , deployment . getSubDeploymentClassLoaders ( ) ) ; ClassLoader oldTccl = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( deployment . getModule ( ) . getClassLoader ( ) ) ; bootstrap . startContainer ( deploymentName , environment , deployment ) ; WeldProvider . containerInitialized ( Container . instance ( deploymentName ) , getBeanManager ( ) , deployment ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( oldTccl ) ; } weldBootstrapServiceConsumer . accept ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a no - op if { [CODESPLIT] public synchronized void stop ( final StopContext context ) { weldBootstrapServiceConsumer . accept ( null ) ; if ( started ) { // WeldStartService#stop() not completed - attempt to perform the container cleanup final Container container = Container . instance ( deploymentName ) ; if ( container != null && ! ContainerState . SHUTDOWN . equals ( container . getState ( ) ) ) { final ExecutorService executorService = serverExecutorSupplier . get ( ) ; final Runnable task = new Runnable ( ) { @ Override public void run ( ) { WeldLogger . DEPLOYMENT_LOGGER . debugf ( \"Weld container cleanup for deployment %s\" , deploymentName ) ; ClassLoader oldTccl = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( deployment . getModule ( ) . getClassLoader ( ) ) ; WeldProvider . containerShutDown ( container ) ; container . setState ( ContainerState . SHUTDOWN ) ; container . cleanup ( ) ; setStarted ( false ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( oldTccl ) ; ModuleGroupSingletonProvider . removeClassLoader ( deployment . getModule ( ) . getClassLoader ( ) ) ; context . complete ( ) ; } } } ; try { executorService . execute ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { @link BeanManager } for a given bean deployment archive id . [CODESPLIT] public BeanManagerImpl getBeanManager ( String beanArchiveId ) { if ( ! started ) { throw WeldLogger . ROOT_LOGGER . notStarted ( \"WeldContainer\" ) ; } BeanDeploymentArchive beanDeploymentArchive = beanDeploymentArchives . get ( beanArchiveId ) ; if ( beanDeploymentArchive == null ) { throw WeldLogger . ROOT_LOGGER . beanDeploymentNotFound ( beanArchiveId ) ; } return bootstrap . getManager ( beanDeploymentArchive ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { [CODESPLIT] public < T extends org . jboss . weld . bootstrap . api . Service > void addWeldService ( Class < T > type , T service ) { deployment . addWeldService ( type , service ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers endpoint and its config . [CODESPLIT] public void registerEndpointConfig ( final String endpointClass , final EndpointConfig config ) { if ( ( endpointClass == null ) || ( config == null ) ) { throw new IllegalArgumentException ( ) ; } endpointConfigMap . put ( endpointClass , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an interceptor to invoke the { [CODESPLIT] private void addSetMessageDrivenContextMethodInvocationInterceptor ( ) { // add the setMessageDrivenContext(MessageDrivenContext) method invocation interceptor for MDB // implementing the javax.ejb.MessageDrivenBean interface this . getConfigurators ( ) . add ( new ComponentConfigurator ( ) { @ Override public void configure ( DeploymentPhaseContext context , ComponentDescription description , ComponentConfiguration configuration ) throws DeploymentUnitProcessingException { if ( MessageDrivenBean . class . isAssignableFrom ( configuration . getComponentClass ( ) ) ) { configuration . addPostConstructInterceptor ( new ImmediateInterceptorFactory ( MessageDrivenBeanSetMessageDrivenContextInterceptor . INSTANCE ) , InterceptorOrder . ComponentPostConstruct . EJB_SET_CONTEXT_METHOD_INVOCATION_INTERCEPTOR ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initializeParsers ( final ExtensionParsingContext context ) { context . setSubsystemXmlMapping ( SUBSYSTEM_NAME , EESecurityExtension . NAMESPACE , new Supplier < XMLElementReader < List < ModelNode > > > ( ) { @ Override public XMLElementReader < List < ModelNode > > get ( ) { return parser ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the timeout method through the { [CODESPLIT] @ Override public void run ( ) { ClassLoader old = WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( getClass ( ) ) ; try { final TimerImpl timer = timerService . getTimer ( timerId ) ; try { if ( cancelled ) { EJB3_TIMER_LOGGER . debugf ( \"Timer task was cancelled for %s\" , timer ) ; return ; } Date now = new Date ( ) ; EJB3_TIMER_LOGGER . debugf ( \"Timer task invoked at: %s for timer %s\" , now , timer ) ; //we lock the timer for this check, because if a cancel is in progress or a running timeout is about to finish //and try to update the timer state after finish the inTimeout method, //we do not want to do the isActive check, but wait for the other transaction to finish //one way or another timer . lock ( ) ; try { // If a retry thread is in progress, we don't want to allow another // interval to execute until the retry is complete. See JIRA-1926. if ( timer . isInRetry ( ) ) { EJB3_TIMER_LOGGER . skipInvokeTimeoutDuringRetry ( timer , now ) ; // compute the next timeout, See JIRA AS7-2995. timer . setNextTimeout ( calculateNextTimeout ( timer ) ) ; timerService . persistTimer ( timer , false ) ; scheduleTimeoutIfRequired ( timer ) ; return ; } // Check whether the timer is running local // If the recurring timer running longer than the interval is, we don't want to allow another // execution until it is complete. See JIRA AS7-3119 if ( timer . getState ( ) == TimerState . IN_TIMEOUT || timer . getState ( ) == TimerState . RETRY_TIMEOUT ) { EJB3_TIMER_LOGGER . skipOverlappingInvokeTimeout ( timer , now ) ; if ( EJB3_TIMER_LOGGER . isDebugEnabled ( ) ) { // WFLY-10542 log thread stack trace which is processing timer task in debug level to diagnose timer overlap Thread otherThread = timer . getExecutingThread ( ) ; // can be null for clustered timers if the timer is executing on another node. if ( otherThread != null ) { final StringBuilder debugMsg = new StringBuilder ( ) . append ( \"Thread: \" ) . append ( otherThread . getName ( ) ) . append ( \" Id: \" ) . append ( otherThread . getId ( ) ) . append ( \" of group \" ) . append ( otherThread . getThreadGroup ( ) ) . append ( \" is in state: \" ) . append ( otherThread . getState ( ) ) ; for ( StackTraceElement ste : otherThread . getStackTrace ( ) ) { debugMsg . append ( System . lineSeparator ( ) ) . append ( ste . toString ( ) ) ; } EJB3_TIMER_LOGGER . debugf ( debugMsg . toString ( ) ) ; } } Date newD = this . calculateNextTimeout ( timer ) ; timer . setNextTimeout ( newD ) ; timerService . persistTimer ( timer , false ) ; scheduleTimeoutIfRequired ( timer ) ; return ; } // Check whether we want to run the timer if ( ! timerService . shouldRun ( timer ) ) { EJB3_TIMER_LOGGER . debugf ( \"Skipping execution of timer for %s as it is being run on another node or the execution is suppressed by configuration\" , timer . getTimedObjectId ( ) ) ; timer . setNextTimeout ( calculateNextTimeout ( timer ) ) ; scheduleTimeoutIfRequired ( timer ) ; return ; } if ( ! timer . isActive ( ) ) { EJB3_TIMER_LOGGER . debug ( \"Timer is not active, skipping this scheduled execution at: \" + now + \"for \" + timer ) ; return ; } // set the current date as the \"previous run\" of the timer. timer . setPreviousRun ( new Date ( ) ) ; Date nextTimeout = this . calculateNextTimeout ( timer ) ; timer . setNextTimeout ( nextTimeout ) ; // change the state to mark it as in timeout method timer . setTimerState ( TimerState . IN_TIMEOUT , Thread . currentThread ( ) ) ; // persist changes timerService . persistTimer ( timer , false ) ; } finally { timer . unlock ( ) ; } try { // invoke timeout this . callTimeout ( timer ) ; } catch ( Exception e ) { EJB3_TIMER_LOGGER . errorInvokeTimeout ( timer , e ) ; try { EJB3_TIMER_LOGGER . timerRetried ( timer ) ; retryTimeout ( timer ) ; } catch ( Exception retryException ) { // that's it, we can't do anything more. Let's just log the exception // and return EJB3_TIMER_LOGGER . errorDuringRetryTimeout ( timer , retryException ) ; } } finally { this . postTimeoutProcessing ( timer ) ; } } catch ( Exception e ) { EJB3_TIMER_LOGGER . exceptionRunningTimerTask ( timer , timedObjectId , e ) ; } } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( old ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After a timeout failed the timer need to retried . The method must lock the timer for state check and update but not during callTimeout run . [CODESPLIT] protected void retryTimeout ( TimerImpl timer ) throws Exception { boolean callTimeout = false ; timer . lock ( ) ; try { if ( timer . isActive ( ) ) { EJB3_TIMER_LOGGER . retryingTimeout ( timer ) ; timer . setTimerState ( TimerState . RETRY_TIMEOUT , Thread . currentThread ( ) ) ; timerService . persistTimer ( timer , false ) ; callTimeout = true ; } else { EJB3_TIMER_LOGGER . timerNotActive ( timer ) ; } } finally { timer . unlock ( ) ; } if ( callTimeout ) { this . callTimeout ( timer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After running the timer calculate the new state or expire the timer and persist it if changed . The method must lock the timer for state check and updates if overridden . [CODESPLIT] protected void postTimeoutProcessing ( TimerImpl timer ) throws InterruptedException { timer . lock ( ) ; try { TimerState timerState = timer . getState ( ) ; if ( timerState != TimerState . CANCELED && timerState != TimerState . EXPIRED ) { if ( timer . getInterval ( ) == 0 ) { timerService . expireTimer ( timer ) ; } else { timer . setTimerState ( TimerState . ACTIVE , null ) ; } timerService . persistTimer ( timer , false ) ; } } finally { timer . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( ExtensionContext context ) { final SubsystemRegistration subsystem = context . registerSubsystem ( SUBSYSTEM_NAME , CURRENT_MODEL_VERSION ) ; // Register the root subsystem resource. final ManagementResourceRegistration rootResource = subsystem . registerSubsystemModel ( new JSR77ManagementRootResource ( context . getProcessType ( ) == ProcessType . APPLICATION_CLIENT ) ) ; // Mandatory describe operation rootResource . registerOperationHandler ( GenericSubsystemDescribeHandler . DEFINITION , GenericSubsystemDescribeHandler . INSTANCE ) ; subsystem . registerXMLElementWriter ( parser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the declared methods [CODESPLIT] static Method [ ] getDeclaredMethods ( final Class < ? > c ) { if ( System . getSecurityManager ( ) == null ) return c . getDeclaredMethods ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < Method [ ] > ( ) { public Method [ ] run ( ) { return c . getDeclaredMethods ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the declared fields [CODESPLIT] static Field [ ] getDeclaredFields ( final Class < ? > c ) { if ( System . getSecurityManager ( ) == null ) return c . getDeclaredFields ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < Field [ ] > ( ) { public Field [ ] run ( ) { return c . getDeclaredFields ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set accessibleo [CODESPLIT] static void setAccessible ( final AccessibleObject ao ) { if ( System . getSecurityManager ( ) == null ) ao . setAccessible ( true ) ; AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { ao . setAccessible ( true ) ; return null ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the constructor [CODESPLIT] static Constructor < ? > getConstructor ( final Class < ? > c , final Class < ? > ... params ) throws NoSuchMethodException { if ( System . getSecurityManager ( ) == null ) return c . getConstructor ( params ) ; Constructor < ? > result = AccessController . doPrivileged ( new PrivilegedAction < Constructor < ? > > ( ) { public Constructor < ? > run ( ) { try { return c . getConstructor ( params ) ; } catch ( NoSuchMethodException e ) { return null ; } } } ) ; if ( result != null ) return result ; throw new NoSuchMethodException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the method [CODESPLIT] static Method getMethod ( final Class < ? > c , final String name , final Class < ? > ... params ) throws NoSuchMethodException { if ( System . getSecurityManager ( ) == null ) return c . getMethod ( name , params ) ; Method result = AccessController . doPrivileged ( new PrivilegedAction < Method > ( ) { public Method run ( ) { try { return c . getMethod ( name , params ) ; } catch ( NoSuchMethodException e ) { return null ; } } } ) ; if ( result != null ) return result ; throw new NoSuchMethodException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In domain mode the subsystem are under / profile = XXX . This method fixes the address by prepending the addresses ( that start with / subsystem ) with the current operation parent so that is works both in standalone ( parent = EMPTY_ADDRESS ) and domain mode ( parent = / profile = XXX ) [CODESPLIT] private void fixAddressesForDomainMode ( PathAddress parentAddress , Map < PathAddress , ModelNode > migrationOperations ) { // in standalone mode, do nothing if ( parentAddress . size ( ) == 0 ) { return ; } // use a linked hash map to preserve operations order Map < PathAddress , ModelNode > fixedMigrationOperations = new LinkedHashMap <> ( migrationOperations ) ; migrationOperations . clear ( ) ; for ( Map . Entry < PathAddress , ModelNode > entry : fixedMigrationOperations . entrySet ( ) ) { PathAddress fixedAddress = parentAddress . append ( entry . getKey ( ) ) ; entry . getValue ( ) . get ( ADDRESS ) . set ( fixedAddress . toModelNode ( ) ) ; migrationOperations . put ( fixedAddress , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It s possible that the extension is already present . In that case this method does nothing . [CODESPLIT] private void addMessagingActiveMQExtension ( OperationContext context , Map < PathAddress , ModelNode > migrationOperations , boolean describe ) { Resource root = context . readResourceFromRoot ( PathAddress . EMPTY_ADDRESS , false ) ; if ( root . getChildrenNames ( EXTENSION ) . contains ( MESSAGING_ACTIVEMQ_EXTENSION ) ) { // extension is already added, do nothing return ; } PathAddress extensionAddress = pathAddress ( EXTENSION , MESSAGING_ACTIVEMQ_EXTENSION ) ; OperationEntry addEntry = context . getRootResourceRegistration ( ) . getOperationEntry ( extensionAddress , ADD ) ; ModelNode addOperation = createAddOperation ( extensionAddress ) ; addOperation . get ( MODULE ) . set ( MESSAGING_ACTIVEMQ_MODULE ) ; if ( describe ) { migrationOperations . put ( extensionAddress , addOperation ) ; } else { context . addStep ( context . getResult ( ) . get ( extensionAddress . toString ( ) ) , addOperation , addEntry . getOperationHandler ( ) , MODEL ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the name of the parameter is allowed for the given resourceType . [CODESPLIT] private boolean parameterIsAllowed ( String name , String resourceType ) { switch ( resourceType ) { case REMOTE_ACCEPTOR : case HTTP_ACCEPTOR : case REMOTE_CONNECTOR : case HTTP_CONNECTOR : // WFLY-5667 - for now remove only use-nio. Revisit this code when Artemis offers an API // to know which parameters are ignored. if ( \"use-nio\" . equals ( name ) ) { return false ; } else { return true ; } default : // accept any parameter for other resources. return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For generic acceptor and connectors migrate their factory - class attribute if they are using the default Netty ones . [CODESPLIT] private void migrateGenericTransport ( ModelNode addOperation ) { String factoryClass = addOperation . get ( FACTORY_CLASS . getName ( ) ) . asString ( ) ; final String newFactoryClass ; switch ( factoryClass ) { case HORNETQ_NETTY_ACCEPTOR_FACTORY : newFactoryClass = ARTEMIS_NETTY_ACCEPTOR_FACTORY ; break ; case HORNETQ_NETTY_CONNECTOR_FACTORY : newFactoryClass = ARTEMIS_NETTY_CONNECTOR_FACTORY ; break ; default : newFactoryClass = factoryClass ; } addOperation . get ( FACTORY_CLASS . getName ( ) ) . set ( newFactoryClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discard from a node and set it to a new node if the attribute is defined . Use the { [CODESPLIT] private void setAndDiscard ( ModelNode setNode , ModelNode discardNode , AttributeDefinition legacyAttributeDefinition , String newAttributeName ) { ModelNode attribute = discardNode . get ( legacyAttributeDefinition . getName ( ) ) ; if ( attribute . isDefined ( ) ) { setNode . get ( newAttributeName ) . set ( attribute ) ; discardNode . remove ( legacyAttributeDefinition . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void writeContent ( XMLExtendedStreamWriter writer , SubsystemMarshallingContext context ) throws XMLStreamException { context . startSubsystemElement ( Namespace . CURRENT . getUriString ( ) , false ) ; ModelNode eeSubSystem = context . getModelNode ( ) ; GlobalModulesDefinition . INSTANCE . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . EAR_SUBDEPLOYMENTS_ISOLATED . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . SPEC_DESCRIPTOR_PROPERTY_REPLACEMENT . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . JBOSS_DESCRIPTOR_PROPERTY_REPLACEMENT . marshallAsElement ( eeSubSystem , writer ) ; EeSubsystemRootResource . ANNOTATION_PROPERTY_REPLACEMENT . marshallAsElement ( eeSubSystem , writer ) ; writeConcurrentElement ( writer , eeSubSystem ) ; writeDefaultBindingsElement ( writer , eeSubSystem ) ; writer . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the passed { @link org . jboss . metadata . ejb . spec . SessionBeanMetaData } and creates appropriate { @link org . jboss . as . ejb3 . component . session . SessionBeanComponentDescription } out of it . The { @link org . jboss . as . ejb3 . component . session . SessionBeanComponentDescription } is then added to the { @link org . jboss . as . ee . component . EEModuleDescription module description } available in the deployment unit of the passed { @link DeploymentPhaseContext phaseContext } [CODESPLIT] @ Override protected void processBeanMetaData ( final SessionBeanMetaData sessionBean , final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; // get the module description final EEModuleDescription moduleDescription = deploymentUnit . getAttachment ( org . jboss . as . ee . component . Attachments . EE_MODULE_DESCRIPTION ) ; final String beanName = sessionBean . getName ( ) ; ComponentDescription bean = moduleDescription . getComponentByName ( beanName ) ; if ( appclient ) { if ( bean == null ) { for ( final ComponentDescription component : deploymentUnit . getAttachmentList ( Attachments . ADDITIONAL_RESOLVABLE_COMPONENTS ) ) { if ( component . getComponentName ( ) . equals ( beanName ) ) { bean = component ; break ; } } } } if ( ! ( bean instanceof SessionBeanComponentDescription ) ) { //TODO: this is a hack to deal with descriptor merging //if this is a GenericBeanMetadata it may actually represent an MDB return ; } SessionBeanComponentDescription sessionBeanDescription = ( SessionBeanComponentDescription ) bean ; sessionBeanDescription . setDeploymentDescriptorEnvironment ( new DeploymentDescriptorEnvironment ( \"java:comp/env/\" , sessionBean ) ) ; // mapped-name sessionBeanDescription . setMappedName ( sessionBean . getMappedName ( ) ) ; // local business interface views final BusinessLocalsMetaData businessLocals = sessionBean . getBusinessLocals ( ) ; if ( businessLocals != null && ! businessLocals . isEmpty ( ) ) { sessionBeanDescription . addLocalBusinessInterfaceViews ( businessLocals ) ; } final String local = sessionBean . getLocal ( ) ; if ( local != null ) { sessionBeanDescription . addEjbLocalObjectView ( local ) ; } final String remote = sessionBean . getRemote ( ) ; if ( remote != null ) { sessionBeanDescription . addEjbObjectView ( remote ) ; } // remote business interface views final BusinessRemotesMetaData businessRemotes = sessionBean . getBusinessRemotes ( ) ; if ( businessRemotes != null && ! businessRemotes . isEmpty ( ) ) { sessionBeanDescription . addRemoteBusinessInterfaceViews ( businessRemotes ) ; } // process EJB3.1 specific session bean description if ( sessionBean instanceof SessionBean31MetaData ) { this . processSessionBean31 ( ( SessionBean31MetaData ) sessionBean , sessionBeanDescription ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { // deploy any persistence providers found in deployment PersistenceProviderHandler . deploy ( phaseContext , platform ) ; // start each PU service (except the PUs with property Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false) PersistenceUnitServiceHandler . deploy ( phaseContext , true , platform ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to cancel the corresponding invocation . [CODESPLIT] public boolean cancel ( boolean setFlag ) { final AtomicInteger stateRef = this . stateRef ; int oldVal , newVal ; do { oldVal = stateRef . get ( ) ; if ( oldVal == ST_WAITING ) { newVal = ST_CANCELLED ; } else if ( oldVal == ST_CANCELLED ) { if ( ! setFlag ) { return true ; } newVal = ST_CANCELLED_FLAG_SET ; } else if ( oldVal == ST_CANCELLED_FLAG_SET ) { // do nothing return true ; } else if ( oldVal == ST_STARTED ) { if ( ! setFlag ) { return false ; } newVal = ST_STARTED_FLAG_SET ; } else { assert oldVal == ST_STARTED_FLAG_SET ; return false ; } } while ( ! stateRef . compareAndSet ( oldVal , newVal ) ) ; return newVal == ST_CANCELLED || newVal == ST_CANCELLED_FLAG_SET ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to determine whether the invocation should proceed or whether it should be cancelled . This method should only be called once per flag instance . [CODESPLIT] public boolean runIfNotCancelled ( ) { final AtomicInteger stateRef = this . stateRef ; int oldVal ; do { oldVal = stateRef . get ( ) ; if ( oldVal == ST_CANCELLED || oldVal == ST_CANCELLED_FLAG_SET ) { return false ; } else if ( oldVal != ST_WAITING ) { throw Assert . unreachableCode ( ) ; } } while ( ! stateRef . compareAndSet ( oldVal , ST_STARTED ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change the type . It checks for compatibility between the change of type . [CODESPLIT] protected void setTypeInternal ( final OType iType ) { getDatabase ( ) . checkSecurity ( ORule . ResourceGeneric . SCHEMA , ORole . PERMISSION_UPDATE ) ; acquireSchemaWriteLock ( ) ; try { if ( iType == globalRef . getType ( ) ) // NO CHANGES return ; if ( ! iType . getCastable ( ) . contains ( globalRef . getType ( ) ) ) throw new IllegalArgumentException ( \"Cannot change property type from \" + globalRef . getType ( ) + \" to \" + iType ) ; this . globalRef = owner . owner . findOrCreateGlobalProperty ( this . globalRef . getName ( ) , iType ) ; } finally { releaseSchemaWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DO NOT DELETE THIS METHOD IT IS USED IN ENTERPRISE STORAGE <p > Copies content of page into passed in byte array . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static void getPageData ( final ByteBuffer buffer , final byte [ ] data , final int offset , final int length ) { buffer . position ( 0 ) ; buffer . get ( data , offset , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DO NOT DELETE THIS METHOD IT IS USED IN ENTERPRISE STORAGE <p > Get value of LSN from the passed in offset in byte array . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static OLogSequenceNumber getLogSequenceNumber ( final int offset , final byte [ ] data ) { final long segment = OLongSerializer . INSTANCE . deserializeNative ( data , offset + WAL_SEGMENT_OFFSET ) ; final long position = OLongSerializer . INSTANCE . deserializeNative ( data , offset + WAL_POSITION_OFFSET ) ; return new OLogSequenceNumber ( segment , position ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Tries to clone any Java object by using 3 techniques : - instanceof ( most verbose but faster performance ) - reflection ( medium performance ) - serialization ( applies for any object type but has a performance overhead ) [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) public static Object cloneObject ( final Object objectToClone , final Object previousClone ) { // ***************************************************************************************************************************************\r // 1. Class by class cloning (only clones known types)\r // ***************************************************************************************************************************************\r // Clone any Map (shallow clone should be enough at this level)\r if ( objectToClone instanceof Map ) { Map recycledMap = ( Map ) previousClone ; if ( recycledMap == null ) recycledMap = new HashMap ( ) ; else recycledMap . clear ( ) ; recycledMap . putAll ( ( Map < ? , ? > ) objectToClone ) ; return recycledMap ; // Clone any collection (shallow clone should be enough at this level)\r } else if ( objectToClone instanceof Collection ) { Collection recycledCollection = ( Collection ) previousClone ; if ( recycledCollection == null ) recycledCollection = new ArrayList ( ) ; else recycledCollection . clear ( ) ; recycledCollection . addAll ( ( Collection < ? > ) objectToClone ) ; return recycledCollection ; // Clone String\r } else if ( objectToClone instanceof String ) { return objectToClone ; } else if ( objectToClone instanceof Number ) { return objectToClone ; // Clone Date\r } else if ( objectToClone instanceof Date ) { return ( Date ) ( ( Date ) objectToClone ) . clone ( ) ; } else { // ***************************************************************************************************************************************\r // 2. Polymorphic clone (by reflection, looks for a clone() method in hierarchy and invoke it)\r // ***************************************************************************************************************************************\r try { Object newClone ; for ( Class < ? > obj = objectToClone . getClass ( ) ; ! obj . equals ( Object . class ) ; obj = obj . getSuperclass ( ) ) { Method m [ ] = obj . getDeclaredMethods ( ) ; for ( int i = 0 ; i < m . length ; i ++ ) { if ( m [ i ] . getName ( ) . equals ( \"clone\" ) ) { m [ i ] . setAccessible ( true ) ; newClone = m [ i ] . invoke ( objectToClone ) ; System . out . println ( objectToClone . getClass ( ) + \" cloned by Reflection. Performance can be improved by adding the class to the list of known types\" ) ; return newClone ; } } } throw new Exception ( \"Method clone not found\" ) ; // ***************************************************************************************************************************************\r // 3. Polymorphic clone (Deep cloning by Serialization)\r // ***************************************************************************************************************************************\r } catch ( Exception e1 ) { try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream ( ) { public synchronized byte [ ] toByteArray ( ) { return buf ; } } ; final ObjectOutputStream out = new ObjectOutputStream ( bytes ) ; out . writeObject ( objectToClone ) ; out . close ( ) ; final ObjectInputStream in = new ObjectInputStream ( new ByteArrayInputStream ( bytes . toByteArray ( ) ) ) ; System . out . println ( objectToClone . getClass ( ) + \" cloned by Serialization. Performance can be improved by adding the class to the list of known types\" ) ; return in . readObject ( ) ; // ***************************************************************************************************************************************\r // 4. Impossible to clone\r // ***************************************************************************************************************************************\r } catch ( Exception e2 ) { OLogManager . instance ( ) . error ( null , \"[GremlinHelper] error on cloning object %s, previous %s\" , e2 , objectToClone , previousClone ) ; return null ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the JSON stream data into the graph . More control over how data is streamed is provided by this method . [CODESPLIT] public void inputGraph ( final String filename , int bufferSize , final Set < String > edgePropertyKeys , final Set < String > vertexPropertyKeys ) throws IOException { final File file = new File ( filename ) ; if ( ! file . exists ( ) ) throw new ODatabaseImportException ( \"File '\" + filename + \"' not found\" ) ; inputSize = file . length ( ) ; final FileInputStream fis = new FileInputStream ( filename ) ; try { inputGraph ( fis , bufferSize , edgePropertyKeys , vertexPropertyKeys ) ; } finally { fis . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the JSON stream data into the graph . More control over how data is streamed is provided by this method . [CODESPLIT] public void inputGraph ( final InputStream jsonInputStream , int bufferSize , final Set < String > edgePropertyKeys , final Set < String > vertexPropertyKeys ) throws IOException { final JsonParser jp = jsonFactory . createJsonParser ( jsonInputStream ) ; // if this is a transactional localGraph then we're buffering final BatchGraph batchGraph = BatchGraph . wrap ( graph , bufferSize ) ; final ElementFactory elementFactory = new GraphElementFactory ( batchGraph ) ; OGraphSONUtility graphson = new OGraphSONUtility ( GraphSONMode . NORMAL , elementFactory , vertexPropertyKeys , edgePropertyKeys ) ; long importedVertices = 0 ; long importedEdges = 0 ; while ( jp . nextToken ( ) != JsonToken . END_OBJECT ) { final String fieldname = jp . getCurrentName ( ) == null ? \"\" : jp . getCurrentName ( ) ; if ( fieldname . equals ( GraphSONTokens . MODE ) ) { jp . nextToken ( ) ; final GraphSONMode mode = GraphSONMode . valueOf ( jp . getText ( ) ) ; graphson = new OGraphSONUtility ( mode , elementFactory , vertexPropertyKeys , edgePropertyKeys ) ; } else if ( fieldname . equals ( GraphSONTokens . VERTICES ) ) { jp . nextToken ( ) ; while ( jp . nextToken ( ) != JsonToken . END_ARRAY ) { final JsonNode node = jp . readValueAsTree ( ) ; graphson . vertexFromJson ( node ) ; importedVertices ++ ; printStatus ( jp , importedVertices , importedEdges ) ; if ( importedVertices % 1000 == 0 ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getLocalCache ( ) . invalidate ( ) ; } } else if ( fieldname . equals ( GraphSONTokens . EDGES ) ) { jp . nextToken ( ) ; while ( jp . nextToken ( ) != JsonToken . END_ARRAY ) { final JsonNode node = jp . readValueAsTree ( ) ; final Vertex inV = batchGraph . getVertex ( OGraphSONUtility . getTypedValueFromJsonNode ( node . get ( GraphSONTokens . _IN_V ) ) ) ; final Vertex outV = batchGraph . getVertex ( OGraphSONUtility . getTypedValueFromJsonNode ( node . get ( GraphSONTokens . _OUT_V ) ) ) ; graphson . edgeFromJson ( node , outV , inV ) ; importedEdges ++ ; printStatus ( jp , importedVertices , importedEdges ) ; if ( importedEdges % 1000 == 0 ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getLocalCache ( ) . invalidate ( ) ; } } } jp . close ( ) ; batchGraph . commit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of { @link OIndexDefinition } for automatic index . [CODESPLIT] public static OIndexDefinition createIndexDefinition ( final OClass oClass , final List < String > fieldNames , final List < OType > types , List < OCollate > collates , String indexKind , String algorithm ) { checkTypes ( oClass , fieldNames , types ) ; if ( fieldNames . size ( ) == 1 ) return createSingleFieldIndexDefinition ( oClass , fieldNames . get ( 0 ) , types . get ( 0 ) , collates == null ? null : collates . get ( 0 ) , indexKind , algorithm ) ; else return createMultipleFieldIndexDefinition ( oClass , fieldNames , types , collates , indexKind , algorithm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract field name from <property > [ by key|value ] field format . [CODESPLIT] public static String extractFieldName ( final String fieldDefinition ) { String [ ] fieldNameParts = FILED_NAME_PATTERN . split ( fieldDefinition ) ; if ( fieldNameParts . length == 0 ) { throw new IllegalArgumentException ( \"Illegal field name format, should be '<property> [by key|value]' but was '\" + fieldDefinition + ' ' ) ; } if ( fieldNameParts . length == 3 && \"by\" . equalsIgnoreCase ( fieldNameParts [ 1 ] ) ) return fieldNameParts [ 0 ] ; if ( fieldNameParts . length == 1 ) return fieldDefinition ; StringBuilder result = new StringBuilder ( ) ; result . append ( fieldNameParts [ 0 ] ) ; for ( int i = 1 ; i < fieldNameParts . length ; i ++ ) { result . append ( \" \" ) ; result . append ( fieldNameParts [ i ] ) ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tests if current expression is an indexed funciton AND that function can also be executed without using the index [CODESPLIT] public boolean canExecuteIndexedFunctionWithoutIndex ( OFromClause target , OCommandContext context , OBinaryCompareOperator operator , Object right ) { if ( this . identifier == null ) { return false ; } return identifier . canExecuteIndexedFunctionWithoutIndex ( target , context , operator , right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "estimates how many items of this class will be returned applying this filter [CODESPLIT] public long estimate ( OClass oClass , long threshold , OCommandContext ctx ) { long count = oClass . count ( ) ; if ( count > 1 ) { count = count / 2 ; } if ( count < threshold ) { return count ; } long indexesCount = 0l ; List < OAndBlock > flattenedConditions = flatten ( ) ; Set < OIndex < ? > > indexes = oClass . getIndexes ( ) ; for ( OAndBlock condition : flattenedConditions ) { List < OBinaryCondition > indexedFunctConditions = condition . getIndexedFunctionConditions ( oClass , ( ODatabaseDocumentInternal ) ctx . getDatabase ( ) ) ; long conditionEstimation = Long . MAX_VALUE ; if ( indexedFunctConditions != null ) { for ( OBinaryCondition cond : indexedFunctConditions ) { OFromClause from = new OFromClause ( - 1 ) ; OFromItem item = new OFromItem ( - 1 ) ; from . item = item ; from . item . setIdentifier ( new OIdentifier ( oClass . getName ( ) ) ) ; long newCount = cond . estimateIndexed ( from , ctx ) ; if ( newCount < conditionEstimation ) { conditionEstimation = newCount ; } } } else { Map < String , Object > conditions = getEqualityOperations ( condition , ctx ) ; for ( OIndex index : indexes ) { if ( index . getType ( ) . equals ( OClass . INDEX_TYPE . FULLTEXT . name ( ) ) || index . getType ( ) . equals ( OClass . INDEX_TYPE . FULLTEXT_HASH_INDEX . name ( ) ) ) { continue ; } List < String > indexedFields = index . getDefinition ( ) . getFields ( ) ; int nMatchingKeys = 0 ; for ( String indexedField : indexedFields ) { if ( conditions . containsKey ( indexedField ) ) { nMatchingKeys ++ ; } else { break ; } } if ( nMatchingKeys > 0 ) { long newCount = estimateFromIndex ( index , conditions , nMatchingKeys ) ; if ( newCount < conditionEstimation ) { conditionEstimation = newCount ; } } } } if ( conditionEstimation > count ) { return count ; } indexesCount += conditionEstimation ; } return Math . min ( indexesCount , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive method used to find all classes in a given directory and subdirs . [CODESPLIT] private static List < Class < ? > > findClasses ( final File iDirectory , String iPackageName , ClassLoader iClassLoader ) throws ClassNotFoundException { final List < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; if ( ! iDirectory . exists ( ) ) return classes ; iPackageName += \".\" + iDirectory . getName ( ) ; String className ; final File [ ] files = iDirectory . listFiles ( ) ; if ( files != null ) for ( File file : files ) { if ( file . isDirectory ( ) ) { if ( file . getName ( ) . contains ( \".\" ) ) continue ; classes . addAll ( findClasses ( file , iPackageName , iClassLoader ) ) ; } else if ( file . getName ( ) . endsWith ( CLASS_EXTENSION ) ) { className = file . getName ( ) . substring ( 0 , file . getName ( ) . length ( ) - CLASS_EXTENSION . length ( ) ) ; classes . add ( Class . forName ( iPackageName + ' ' + className , true , iClassLoader ) ) ; } } return classes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters discovered classes to see if they implement a given interface . [CODESPLIT] public static List < Class < ? > > getClassessOfInterface ( String thePackage , Class < ? > theInterface , final ClassLoader iClassLoader ) { List < Class < ? > > classList = new ArrayList < Class < ? > > ( ) ; try { for ( Class < ? > discovered : getClassesFor ( thePackage , iClassLoader ) ) { if ( Arrays . asList ( discovered . getInterfaces ( ) ) . contains ( theInterface ) ) { classList . add ( discovered ) ; } } } catch ( ClassNotFoundException ex ) { OLogManager . instance ( ) . error ( null , \"Error finding classes\" , ex ) ; } return classList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the declared generic types of a class . [CODESPLIT] public static Type [ ] getGenericTypes ( final Class < ? > iClass ) { final Type genericType = iClass . getGenericInterfaces ( ) [ 0 ] ; if ( genericType != null && genericType instanceof ParameterizedType ) { final ParameterizedType pt = ( ParameterizedType ) genericType ; if ( pt . getActualTypeArguments ( ) != null && pt . getActualTypeArguments ( ) . length > 1 ) return pt . getActualTypeArguments ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the generic class of multi - value objects . [CODESPLIT] public static Class < ? > getGenericMultivalueType ( final Field p ) { if ( p . getType ( ) instanceof Class < ? > ) { final Type genericType = p . getGenericType ( ) ; if ( genericType != null && genericType instanceof ParameterizedType ) { final ParameterizedType pt = ( ParameterizedType ) genericType ; if ( pt . getActualTypeArguments ( ) != null && pt . getActualTypeArguments ( ) . length > 0 ) { if ( ( ( Class < ? > ) pt . getRawType ( ) ) . isAssignableFrom ( Map . class ) ) { if ( pt . getActualTypeArguments ( ) [ 1 ] instanceof Class < ? > ) { return ( Class < ? > ) pt . getActualTypeArguments ( ) [ 1 ] ; } else if ( pt . getActualTypeArguments ( ) [ 1 ] instanceof ParameterizedType ) return ( Class < ? > ) ( ( ParameterizedType ) pt . getActualTypeArguments ( ) [ 1 ] ) . getRawType ( ) ; } else if ( pt . getActualTypeArguments ( ) [ 0 ] instanceof Class < ? > ) { return ( Class < ? > ) pt . getActualTypeArguments ( ) [ 0 ] ; } else if ( pt . getActualTypeArguments ( ) [ 0 ] instanceof ParameterizedType ) return ( Class < ? > ) ( ( ParameterizedType ) pt . getActualTypeArguments ( ) [ 0 ] ) . getRawType ( ) ; } } else if ( p . getType ( ) . isArray ( ) ) return p . getType ( ) . getComponentType ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a class is a Java type : Map Collection arrays Number ( extensions and primitives ) String Boolean .. [CODESPLIT] public static boolean isJavaType ( Class < ? > clazz ) { if ( clazz . isPrimitive ( ) ) return true ; else if ( clazz . getName ( ) . startsWith ( \"java.lang\" ) ) return true ; else if ( clazz . getName ( ) . startsWith ( \"java.util\" ) ) return true ; else if ( clazz . isArray ( ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a method . [CODESPLIT] public Object execute ( final Object iThis , final OIdentifiable iCurrentRecord , final Object iCurrentResult , final OCommandContext iContext ) { if ( iThis == null ) return null ; if ( configuredParameters != null ) { // RESOLVE VALUES USING THE CURRENT RECORD for ( int i = 0 ; i < configuredParameters . length ; ++ i ) { runtimeParameters [ i ] = configuredParameters [ i ] ; if ( method . evaluateParameters ( ) ) { if ( configuredParameters [ i ] instanceof OSQLFilterItemField ) { runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; if ( runtimeParameters [ i ] == null && iCurrentResult instanceof OIdentifiable ) // LOOK INTO THE CURRENT RESULT runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( ( OIdentifiable ) iCurrentResult , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OSQLMethodRuntime ) runtimeParameters [ i ] = ( ( OSQLMethodRuntime ) configuredParameters [ i ] ) . execute ( iThis , iCurrentRecord , iCurrentResult , iContext ) ; else if ( configuredParameters [ i ] instanceof OSQLFunctionRuntime ) runtimeParameters [ i ] = ( ( OSQLFunctionRuntime ) configuredParameters [ i ] ) . execute ( iCurrentRecord , iCurrentRecord , iCurrentResult , iContext ) ; else if ( configuredParameters [ i ] instanceof OSQLFilterItemVariable ) { runtimeParameters [ i ] = ( ( OSQLFilterItemVariable ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; if ( runtimeParameters [ i ] == null && iCurrentResult instanceof OIdentifiable ) // LOOK INTO THE CURRENT RESULT runtimeParameters [ i ] = ( ( OSQLFilterItemVariable ) configuredParameters [ i ] ) . getValue ( ( OIdentifiable ) iCurrentResult , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OCommandSQL ) { try { runtimeParameters [ i ] = ( ( OCommandSQL ) configuredParameters [ i ] ) . setContext ( iContext ) . execute ( ) ; } catch ( OCommandExecutorNotFoundException ignore ) { // TRY WITH SIMPLE CONDITION final String text = ( ( OCommandSQL ) configuredParameters [ i ] ) . getText ( ) ; final OSQLPredicate pred = new OSQLPredicate ( text ) ; runtimeParameters [ i ] = pred . evaluate ( iCurrentRecord instanceof ORecord ? ( ORecord ) iCurrentRecord : null , ( ODocument ) iCurrentResult , iContext ) ; // REPLACE ORIGINAL PARAM configuredParameters [ i ] = pred ; } } else if ( configuredParameters [ i ] instanceof OSQLPredicate ) runtimeParameters [ i ] = ( ( OSQLPredicate ) configuredParameters [ i ] ) . evaluate ( iCurrentRecord . getRecord ( ) , ( iCurrentRecord instanceof ODocument ? ( ODocument ) iCurrentResult : null ) , iContext ) ; else if ( configuredParameters [ i ] instanceof String ) { if ( configuredParameters [ i ] . toString ( ) . startsWith ( \"\\\"\" ) || configuredParameters [ i ] . toString ( ) . startsWith ( \"'\" ) ) runtimeParameters [ i ] = OIOUtils . getStringContent ( configuredParameters [ i ] ) ; } } } if ( method . getMaxParams ( ) == - 1 || method . getMaxParams ( ) > 0 ) { if ( runtimeParameters . length < method . getMinParams ( ) || ( method . getMaxParams ( ) > - 1 && runtimeParameters . length > method . getMaxParams ( ) ) ) throw new OCommandExecutionException ( \"Syntax error: function '\" + method . getName ( ) + \"' needs \" + ( method . getMinParams ( ) == method . getMaxParams ( ) ? method . getMinParams ( ) : method . getMinParams ( ) + \"-\" + method . getMaxParams ( ) ) + \" argument(s) while has been received \" + runtimeParameters . length ) ; } } final Object functionResult = method . execute ( iThis , iCurrentRecord , iContext , iCurrentResult , runtimeParameters ) ; return transformValue ( iCurrentRecord , iContext , functionResult ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is executed on non - indexed fields . [CODESPLIT] @ Override public Object evaluateRecord ( final OIdentifiable iRecord , ODocument iCurrentResult , final OSQLFilterCondition iCondition , final Object iLeft , final Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { if ( iLeft == null || iRight == null ) return false ; return iLeft . toString ( ) . indexOf ( iRight . toString ( ) ) > - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Derives the type of a field in a document . [CODESPLIT] protected OType deriveFieldType ( ODocument iRecord , String fieldName , OType requestedFieldType ) { // Schema defined types can not be ignored if ( iRecord . getSchemaClass ( ) . existsProperty ( fieldName ) ) { return iRecord . getSchemaClass ( ) . getProperty ( fieldName ) . getType ( ) ; } // New type if ( requestedFieldType != null ) { return requestedFieldType ; } // Existing type (not fixed by the schema) return iRecord . fieldType ( fieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( role == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not yet been parsed\" ) ; role . revoke ( resource , privilege ) ; role . save ( ) ; return role ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes record to cache . Identifier of record used as access key [CODESPLIT] public void updateRecord ( final ORecord record ) { if ( record . getIdentity ( ) . getClusterId ( ) != excludedCluster && record . getIdentity ( ) . isValid ( ) && ! record . isDirty ( ) && ! ORecordVersionHelper . isTombstone ( record . getVersion ( ) ) ) { if ( underlying . get ( record . getIdentity ( ) ) != record ) underlying . put ( record ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up for record in cache by it s identifier . Optionally look up in secondary cache and update primary with found record [CODESPLIT] public ORecord findRecord ( final ORID rid ) { ORecord record ; record = underlying . get ( rid ) ; if ( record != null ) Orient . instance ( ) . getProfiler ( ) . updateCounter ( CACHE_HIT , \"Record found in Level1 Cache\" , 1L , \"db.*.cache.level1.cache.found\" ) ; else Orient . instance ( ) . getProfiler ( ) . updateCounter ( CACHE_MISS , \"Record not found in Level1 Cache\" , 1L , \"db.*.cache.level1.cache.notFound\" ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the REMOVE INDEX . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( name == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; if ( name . equals ( \"*\" ) ) { long totalIndexed = 0 ; for ( OIndex < ? > idx : getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndexes ( ) ) { getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( idx . getName ( ) ) ; totalIndexed ++ ; } return totalIndexed ; } else getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( name ) ; return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( T object , ByteBuffer buffer , Object ... hints ) { init ( object , hints ) ; buffer . put ( binarySerializer . getId ( ) ) ; binarySerializer . serializeInByteBufferObject ( object , buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public T deserializeFromByteBufferObject ( ByteBuffer buffer ) { final byte typeId = buffer . get ( ) ; init ( typeId ) ; return ( T ) binarySerializer . deserializeFromByteBufferObject ( buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { final byte serializerId = buffer . get ( ) ; init ( serializerId ) ; return OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + binarySerializer . getObjectSizeInByteBuffer ( buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public T deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final byte typeId = walChanges . getByteValue ( buffer , offset ++ ) ; init ( typeId ) ; return ( T ) binarySerializer . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + binarySerializer . getObjectSizeInByteBuffer ( buffer , walChanges , OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE + offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the database ( if it does not exist ) and initializes batch operations . Call this once before starting to create vertices and edges . [CODESPLIT] public void begin ( ) { walActive = OGlobalConfiguration . USE_WAL . getValueAsBoolean ( ) ; if ( walActive ) OGlobalConfiguration . USE_WAL . setValue ( false ) ; if ( averageEdgeNumberPerNode > 0 ) { OGlobalConfiguration . RID_BAG_EMBEDDED_DEFAULT_SIZE . setValue ( averageEdgeNumberPerNode ) ; OGlobalConfiguration . RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD . setValue ( bonsaiThreshold ) ; } db = new ODatabaseDocumentTx ( dbUrl ) ; if ( db . exists ( ) ) { db . open ( userName , password ) ; } else { db . create ( ) ; } if ( this . useLightWeigthEdges == null ) { final List < OStorageEntryConfiguration > custom = ( List < OStorageEntryConfiguration > ) db . get ( ODatabase . ATTRIBUTES . CUSTOM ) ; for ( OStorageEntryConfiguration c : custom ) { if ( c . name . equalsIgnoreCase ( \"useLightweightEdges\" ) ) { this . useLightWeigthEdges = Boolean . parseBoolean ( c . value ) ; break ; } } if ( this . useLightWeigthEdges == null ) { this . useLightWeigthEdges = true ; } } createBaseSchema ( ) ; out = estimatedEntries > 0 ? new HashMap < Long , List < Object > > ( estimatedEntries ) : new HashMap < Long , List < Object > > ( ) ; in = estimatedEntries > 0 ? new HashMap < Long , List < Object > > ( estimatedEntries ) : new HashMap < Long , List < Object > > ( ) ; OClass vClass = db . getMetadata ( ) . getSchema ( ) . getClass ( this . vertexClass ) ; int [ ] existingClusters = vClass . getClusterIds ( ) ; for ( int c = existingClusters . length ; c <= parallel ; c ++ ) { vClass . addCluster ( vClass . getName ( ) + \"_\" + c ) ; } clusterIds = vClass . getClusterIds ( ) ; lastClusterPositions = new long [ clusterIds . length ] ; nextVerticesToCreate = new long [ clusterIds . length ] ; for ( int i = 0 ; i < clusterIds . length ; i ++ ) { int clusterId = clusterIds [ i ] ; try { nextVerticesToCreate [ i ] = i ; //THERE IS NO PUBLIC API FOR RETRIEVE THE LAST CLUSTER POSITION lastClusterPositions [ i ] = ( ( ODatabaseDocumentInternal ) db ) . getStorage ( ) . getClusterById ( clusterId ) . getLastPosition ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new edge between two vertices . If vertices do not exist they will be created [CODESPLIT] public void createEdge ( final Long from , final Long to , Map < String , Object > properties ) { if ( settingProperties ) { throw new IllegalStateException ( \"Cannot create new edges when already set properties on vertices\" ) ; } if ( from < 0 ) { throw new IllegalArgumentException ( \" Invalid vertex id: \" + from ) ; } if ( to < 0 ) { throw new IllegalArgumentException ( \" Invalid vertex id: \" + to ) ; } if ( useLightWeigthEdges && ( properties == null || properties . size ( ) == 0 ) ) { last = last < from ? from : last ; last = last < to ? to : last ; putInList ( from , out , to ) ; putInList ( to , in , from ) ; } else { ODocument edgeDoc = new ODocument ( edgeClass ) ; edgeDoc . fromMap ( properties ) ; edgeDoc . field ( \"out\" , new ORecordId ( getClusterId ( from ) , getClusterPosition ( from ) ) ) ; edgeDoc . field ( \"in\" , new ORecordId ( getClusterId ( to ) , getClusterPosition ( to ) ) ) ; db . save ( edgeDoc ) ; ORecordId rid = ( ORecordId ) edgeDoc . getIdentity ( ) ; putInList ( from , out , rid ) ; putInList ( to , in , rid ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "based on the cluster / server map and the query target this method tries to find an optimal strategy to execute the query on the cluster . [CODESPLIT] private void calculateShardingStrategy ( QueryPlanningInfo info , OCommandContext ctx ) { ODatabaseDocumentInternal db = ( ODatabaseDocumentInternal ) ctx . getDatabase ( ) ; info . distributedFetchExecutionPlans = new LinkedHashMap <> ( ) ; Map < String , Set < String > > clusterMap = db . getActiveClusterMap ( ) ; Set < String > queryClusters = calculateTargetClusters ( info , ctx ) ; if ( queryClusters == null || queryClusters . size ( ) == 0 ) { //no target String localNode = db . getLocalNodeName ( ) ; info . serverToClusters = new LinkedHashMap <> ( ) ; info . serverToClusters . put ( localNode , clusterMap . get ( localNode ) ) ; info . distributedFetchExecutionPlans . put ( localNode , new OSelectExecutionPlan ( ctx ) ) ; return ; } //    Set<String> serversWithAllTheClusers = getServersThatHasAllClusters(clusterMap, queryClusters); //    if (serversWithAllTheClusers.isEmpty()) { // sharded query Map < String , Set < String > > minimalSetOfNodes = getMinimalSetOfNodesForShardedQuery ( db . getLocalNodeName ( ) , clusterMap , queryClusters ) ; if ( minimalSetOfNodes == null ) { throw new OCommandExecutionException ( \"Cannot execute sharded query\" ) ; } info . serverToClusters = minimalSetOfNodes ; for ( String node : info . serverToClusters . keySet ( ) ) { info . distributedFetchExecutionPlans . put ( node , new OSelectExecutionPlan ( ctx ) ) ; } //    } else { //      // all on a node //      String targetNode = serversWithAllTheClusers.contains(db.getLocalNodeName()) ? //          db.getLocalNodeName() : //          serversWithAllTheClusers.iterator().next(); //      info.serverToClusters = new HashMap<>(); //      info.serverToClusters.put(targetNode, queryClusters); //    } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a cluster map and a set of clusters involved in a query tries to calculate the minimum number of nodes that will have to be involved in the query execution with clusters involved for each node . [CODESPLIT] private Map < String , Set < String > > getMinimalSetOfNodesForShardedQuery ( String localNode , Map < String , Set < String > > clusterMap , Set < String > queryClusters ) { //approximate algorithm, the problem is NP-complete Map < String , Set < String > > result = new LinkedHashMap <> ( ) ; Set < String > uncovered = new HashSet <> ( ) ; uncovered . addAll ( queryClusters ) ; uncovered = uncovered . stream ( ) . filter ( x -> x != null ) . map ( x -> x . toLowerCase ( Locale . ENGLISH ) ) . collect ( Collectors . toSet ( ) ) ; //try local node first Set < String > nextNodeClusters = new HashSet <> ( ) ; Set < String > clustersForNode = clusterMap . get ( localNode ) ; if ( clustersForNode != null ) { nextNodeClusters . addAll ( clustersForNode ) ; } nextNodeClusters . retainAll ( uncovered ) ; if ( nextNodeClusters . size ( ) > 0 ) { result . put ( localNode , nextNodeClusters ) ; uncovered . removeAll ( nextNodeClusters ) ; } while ( uncovered . size ( ) > 0 ) { String nextNode = findItemThatCoversMore ( uncovered , clusterMap ) ; nextNodeClusters = new HashSet <> ( ) ; nextNodeClusters . addAll ( clusterMap . get ( nextNode ) ) ; nextNodeClusters . retainAll ( uncovered ) ; if ( nextNodeClusters . size ( ) == 0 ) { throw new OCommandExecutionException ( \"Cannot execute a sharded query: clusters [\" + uncovered . stream ( ) . collect ( Collectors . joining ( \", \" ) ) + \"] are not present on any node\" + \"\\n [\" + clusterMap . entrySet ( ) . stream ( ) . map ( x -> \"\" + x . getKey ( ) + \":(\" + x . getValue ( ) . stream ( ) . collect ( Collectors . joining ( \",\" ) ) + \")\" ) . collect ( Collectors . joining ( \", \" ) ) + \"]\" ) ; } result . put ( nextNode , nextNodeClusters ) ; uncovered . removeAll ( nextNodeClusters ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param clusterMap the cluster map for current sharding configuration @param queryClusters the clusters that are target of the query [CODESPLIT] private Set < String > getServersThatHasAllClusters ( Map < String , Set < String > > clusterMap , Set < String > queryClusters ) { Set < String > remainingServers = clusterMap . keySet ( ) ; for ( String cluster : queryClusters ) { for ( Map . Entry < String , Set < String > > serverConfig : clusterMap . entrySet ( ) ) { if ( ! serverConfig . getValue ( ) . contains ( cluster ) ) { remainingServers . remove ( serverConfig . getKey ( ) ) ; } } } return remainingServers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tries to calculate which clusters will be impacted by this query [CODESPLIT] private Set < String > calculateTargetClusters ( QueryPlanningInfo info , OCommandContext ctx ) { if ( info . target == null ) { return Collections . EMPTY_SET ; } Set < String > result = new HashSet <> ( ) ; ODatabase db = ctx . getDatabase ( ) ; OFromItem item = info . target . getItem ( ) ; if ( item . getRids ( ) != null && item . getRids ( ) . size ( ) > 0 ) { if ( item . getRids ( ) . size ( ) == 1 ) { OInteger cluster = item . getRids ( ) . get ( 0 ) . getCluster ( ) ; if ( cluster . getValue ( ) . longValue ( ) > ORID . CLUSTER_MAX ) { throw new OCommandExecutionException ( \"Invalid cluster Id:\" + cluster + \". Max allowed value = \" + ORID . CLUSTER_MAX ) ; } result . add ( db . getClusterNameById ( cluster . getValue ( ) . intValue ( ) ) ) ; } else { for ( ORid rid : item . getRids ( ) ) { OInteger cluster = rid . getCluster ( ) ; result . add ( db . getClusterNameById ( cluster . getValue ( ) . intValue ( ) ) ) ; } } return result ; } else if ( item . getInputParams ( ) != null && item . getInputParams ( ) . size ( ) > 0 ) { if ( ( ( ODatabaseInternal ) ctx . getDatabase ( ) ) . isSharded ( ) ) { throw new UnsupportedOperationException ( \"Sharded query with input parameter as a target is not supported yet\" ) ; } return null ; } else if ( item . getCluster ( ) != null ) { String name = item . getCluster ( ) . getClusterName ( ) ; if ( name == null ) { name = db . getClusterNameById ( item . getCluster ( ) . getClusterNumber ( ) ) ; } if ( name != null ) { result . add ( name ) ; return result ; } else { return null ; } } else if ( item . getClusterList ( ) != null ) { for ( OCluster cluster : item . getClusterList ( ) . toListOfClusters ( ) ) { String name = cluster . getClusterName ( ) ; if ( name == null ) { name = db . getClusterNameById ( cluster . getClusterNumber ( ) ) ; } if ( name != null ) { result . add ( name ) ; } } return result ; } else if ( item . getIndex ( ) != null ) { String indexName = item . getIndex ( ) . getIndexName ( ) ; OIndex < ? > idx = db . getMetadata ( ) . getIndexManager ( ) . getIndex ( indexName ) ; if ( idx == null ) { throw new OCommandExecutionException ( \"Index \" + indexName + \" does not exist\" ) ; } result . addAll ( idx . getClusters ( ) ) ; if ( result . isEmpty ( ) ) { return null ; } return result ; } else if ( item . getInputParam ( ) != null ) { if ( ( ( ODatabaseInternal ) ctx . getDatabase ( ) ) . isSharded ( ) ) { throw new UnsupportedOperationException ( \"Sharded query with input parameter as a target is not supported yet\" ) ; } return null ; } else if ( item . getIdentifier ( ) != null ) { String className = item . getIdentifier ( ) . getStringValue ( ) ; OClass clazz = getSchemaFromContext ( ctx ) . getClass ( className ) ; if ( clazz == null ) { clazz = getSchemaFromContext ( ctx ) . getView ( className ) ; } if ( clazz == null ) { return null ; } int [ ] clusterIds = clazz . getPolymorphicClusterIds ( ) ; for ( int clusterId : clusterIds ) { String clusterName = db . getClusterNameById ( clusterId ) ; if ( clusterName != null ) { result . add ( clusterName ) ; } } return result ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for backward compatibility translate distinct ( foo ) to DISTINCT foo . This method modifies the projection itself . [CODESPLIT] protected static OProjection translateDistinct ( OProjection projection ) { if ( projection != null && projection . getItems ( ) . size ( ) == 1 ) { if ( isDistinct ( projection . getItems ( ) . get ( 0 ) ) ) { projection = projection . copy ( ) ; OProjectionItem item = projection . getItems ( ) . get ( 0 ) ; OFunctionCall function = ( ( OBaseExpression ) item . getExpression ( ) . getMathExpression ( ) ) . getIdentifier ( ) . getLevelZero ( ) . getFunctionCall ( ) ; OExpression exp = function . getParams ( ) . get ( 0 ) ; OProjectionItem resultItem = new OProjectionItem ( - 1 ) ; resultItem . setAlias ( item . getAlias ( ) ) ; resultItem . setExpression ( exp . copy ( ) ) ; OProjection result = new OProjection ( - 1 ) ; result . setItems ( new ArrayList <> ( ) ) ; result . setDistinct ( true ) ; result . getItems ( ) . add ( resultItem ) ; return result ; } } return projection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks if a projection is a distinct ( expr ) . In new executor the distinct () function is not supported so distinct ( expr ) is translated to DISTINCT expr [CODESPLIT] private static boolean isDistinct ( OProjectionItem item ) { if ( item . getExpression ( ) == null ) { return false ; } if ( item . getExpression ( ) . getMathExpression ( ) == null ) { return false ; } if ( ! ( item . getExpression ( ) . getMathExpression ( ) instanceof OBaseExpression ) ) { return false ; } OBaseExpression base = ( OBaseExpression ) item . getExpression ( ) . getMathExpression ( ) ; if ( base . getIdentifier ( ) == null ) { return false ; } if ( base . getModifier ( ) != null ) { return false ; } if ( base . getIdentifier ( ) . getLevelZero ( ) == null ) { return false ; } OFunctionCall function = base . getIdentifier ( ) . getLevelZero ( ) . getFunctionCall ( ) ; if ( function == null ) { return false ; } return function . getName ( ) . getStringValue ( ) . equalsIgnoreCase ( \"distinct\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if the query is minimal ie . no WHERE condition no SKIP / LIMIT no UNWIND no GROUP / ORDER BY no LET [CODESPLIT] private boolean isMinimalQuery ( QueryPlanningInfo info ) { return info . projectionAfterOrderBy == null && info . globalLetClause == null && info . perRecordLetClause == null && info . whereClause == null && info . flattenedWhereClause == null && info . groupBy == null && info . orderBy == null && info . unwind == null && info . skip == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "splits LET clauses in global ( executed once ) and local ( executed once per record ) [CODESPLIT] private static void splitLet ( QueryPlanningInfo info , OCommandContext ctx ) { if ( info . perRecordLetClause != null && info . perRecordLetClause . getItems ( ) != null ) { Iterator < OLetItem > iterator = info . perRecordLetClause . getItems ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { OLetItem item = iterator . next ( ) ; if ( item . getExpression ( ) != null && item . getExpression ( ) . isEarlyCalculated ( ctx ) ) { iterator . remove ( ) ; addGlobalLet ( info , item . getVarName ( ) , item . getExpression ( ) ) ; } else if ( item . getQuery ( ) != null && ! item . getQuery ( ) . refersToParent ( ) ) { iterator . remove ( ) ; addGlobalLet ( info , item . getVarName ( ) , item . getQuery ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "re - writes a list of flat AND conditions moving left all the equality operations [CODESPLIT] private static List < OAndBlock > moveFlattededEqualitiesLeft ( List < OAndBlock > flattenedWhereClause ) { if ( flattenedWhereClause == null ) { return null ; } List < OAndBlock > result = new ArrayList <> ( ) ; for ( OAndBlock block : flattenedWhereClause ) { List < OBooleanExpression > equalityExpressions = new ArrayList <> ( ) ; List < OBooleanExpression > nonEqualityExpressions = new ArrayList <> ( ) ; OAndBlock newBlock = block . copy ( ) ; for ( OBooleanExpression exp : newBlock . getSubBlocks ( ) ) { if ( exp instanceof OBinaryCondition ) { if ( ( ( OBinaryCondition ) exp ) . getOperator ( ) instanceof OEqualsCompareOperator ) { equalityExpressions . add ( exp ) ; } else { nonEqualityExpressions . add ( exp ) ; } } else { nonEqualityExpressions . add ( exp ) ; } } OAndBlock newAnd = new OAndBlock ( - 1 ) ; newAnd . getSubBlocks ( ) . addAll ( equalityExpressions ) ; newAnd . getSubBlocks ( ) . addAll ( nonEqualityExpressions ) ; result . add ( newAnd ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates additional projections for ORDER BY [CODESPLIT] private static void addOrderByProjections ( QueryPlanningInfo info ) { if ( info . orderApplied || info . expand || info . unwind != null || info . orderBy == null || info . orderBy . getItems ( ) . size ( ) == 0 || info . projection == null || info . projection . getItems ( ) == null || ( info . projection . getItems ( ) . size ( ) == 1 && info . projection . getItems ( ) . get ( 0 ) . isAll ( ) ) ) { return ; } OOrderBy newOrderBy = info . orderBy == null ? null : info . orderBy . copy ( ) ; List < OProjectionItem > additionalOrderByProjections = calculateAdditionalOrderByProjections ( info . projection . getAllAliases ( ) , newOrderBy ) ; if ( additionalOrderByProjections . size ( ) > 0 ) { info . orderBy = newOrderBy ; //the ORDER BY has changed } if ( additionalOrderByProjections . size ( ) > 0 ) { info . projectionAfterOrderBy = new OProjection ( - 1 ) ; info . projectionAfterOrderBy . setItems ( new ArrayList <> ( ) ) ; for ( String alias : info . projection . getAllAliases ( ) ) { info . projectionAfterOrderBy . getItems ( ) . add ( projectionFromAlias ( new OIdentifier ( alias ) ) ) ; } for ( OProjectionItem item : additionalOrderByProjections ) { if ( info . preAggregateProjection != null ) { info . preAggregateProjection . getItems ( ) . add ( item ) ; info . aggregateProjection . getItems ( ) . add ( projectionFromAlias ( item . getAlias ( ) ) ) ; info . projection . getItems ( ) . add ( projectionFromAlias ( item . getAlias ( ) ) ) ; } else { info . projection . getItems ( ) . add ( item ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a list of aliases ( present in the existing projections ) calculates a list of additional projections to add to the existing projections to allow ORDER BY calculation . The sorting clause will be modified with new replaced aliases [CODESPLIT] private static List < OProjectionItem > calculateAdditionalOrderByProjections ( Set < String > allAliases , OOrderBy orderBy ) { List < OProjectionItem > result = new ArrayList <> ( ) ; int nextAliasCount = 0 ; if ( orderBy != null && orderBy . getItems ( ) != null || ! orderBy . getItems ( ) . isEmpty ( ) ) { for ( OOrderByItem item : orderBy . getItems ( ) ) { if ( ! allAliases . contains ( item . getAlias ( ) ) ) { OProjectionItem newProj = new OProjectionItem ( - 1 ) ; if ( item . getAlias ( ) != null ) { newProj . setExpression ( new OExpression ( new OIdentifier ( item . getAlias ( ) ) , item . getModifier ( ) ) ) ; } else if ( item . getRecordAttr ( ) != null ) { ORecordAttribute attr = new ORecordAttribute ( - 1 ) ; attr . setName ( item . getRecordAttr ( ) ) ; newProj . setExpression ( new OExpression ( attr , item . getModifier ( ) ) ) ; } else if ( item . getRid ( ) != null ) { OExpression exp = new OExpression ( - 1 ) ; exp . setRid ( item . getRid ( ) . copy ( ) ) ; newProj . setExpression ( exp ) ; } OIdentifier newAlias = new OIdentifier ( \"_$$$ORDER_BY_ALIAS$$$_\" + ( nextAliasCount ++ ) ) ; newProj . setAlias ( newAlias ) ; item . setAlias ( newAlias . getStringValue ( ) ) ; item . setModifier ( null ) ; result . add ( newProj ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "splits projections in three parts ( pre - aggregate aggregate and final ) to efficiently manage aggregations [CODESPLIT] private static void splitProjectionsForGroupBy ( QueryPlanningInfo info , OCommandContext ctx ) { if ( info . projection == null ) { return ; } OProjection preAggregate = new OProjection ( - 1 ) ; preAggregate . setItems ( new ArrayList <> ( ) ) ; OProjection aggregate = new OProjection ( - 1 ) ; aggregate . setItems ( new ArrayList <> ( ) ) ; OProjection postAggregate = new OProjection ( - 1 ) ; postAggregate . setItems ( new ArrayList <> ( ) ) ; boolean isSplitted = false ; //split for aggregate projections AggregateProjectionSplit result = new AggregateProjectionSplit ( ) ; for ( OProjectionItem item : info . projection . getItems ( ) ) { result . reset ( ) ; if ( isAggregate ( item ) ) { isSplitted = true ; OProjectionItem post = item . splitForAggregation ( result , ctx ) ; OIdentifier postAlias = item . getProjectionAlias ( ) ; postAlias = new OIdentifier ( postAlias , true ) ; post . setAlias ( postAlias ) ; postAggregate . getItems ( ) . add ( post ) ; aggregate . getItems ( ) . addAll ( result . getAggregate ( ) ) ; preAggregate . getItems ( ) . addAll ( result . getPreAggregate ( ) ) ; } else { preAggregate . getItems ( ) . add ( item ) ; //also push the alias forward in the chain OProjectionItem aggItem = new OProjectionItem ( - 1 ) ; aggItem . setExpression ( new OExpression ( item . getProjectionAlias ( ) ) ) ; aggregate . getItems ( ) . add ( aggItem ) ; postAggregate . getItems ( ) . add ( aggItem ) ; } } //bind split projections to the execution planner if ( isSplitted ) { info . preAggregateProjection = preAggregate ; if ( info . preAggregateProjection . getItems ( ) == null || info . preAggregateProjection . getItems ( ) . size ( ) == 0 ) { info . preAggregateProjection = null ; } info . aggregateProjection = aggregate ; if ( info . aggregateProjection . getItems ( ) == null || info . aggregateProjection . getItems ( ) . size ( ) == 0 ) { info . aggregateProjection = null ; } info . projection = postAggregate ; addGroupByExpressionsToProjections ( info ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if GROUP BY is performed on an expression that is not explicitly in the pre - aggregate projections then that expression has to be put in the pre - aggregate ( only here in subsequent steps it s removed ) [CODESPLIT] private static void addGroupByExpressionsToProjections ( QueryPlanningInfo info ) { if ( info . groupBy == null || info . groupBy . getItems ( ) == null || info . groupBy . getItems ( ) . size ( ) == 0 ) { return ; } OGroupBy newGroupBy = new OGroupBy ( - 1 ) ; int i = 0 ; for ( OExpression exp : info . groupBy . getItems ( ) ) { if ( exp . isAggregate ( ) ) { throw new OCommandExecutionException ( \"Cannot group by an aggregate function\" ) ; } boolean found = false ; if ( info . preAggregateProjection != null ) { for ( String alias : info . preAggregateProjection . getAllAliases ( ) ) { //if it's a simple identifier and it's the same as one of the projections in the query, //then the projection itself is used for GROUP BY without recalculating; in all the other cases, it is evaluated separately if ( alias . equals ( exp . getDefaultAlias ( ) . getStringValue ( ) ) && exp . isBaseIdentifier ( ) ) { found = true ; newGroupBy . getItems ( ) . add ( exp ) ; break ; } } } if ( ! found ) { OProjectionItem newItem = new OProjectionItem ( - 1 ) ; newItem . setExpression ( exp ) ; OIdentifier groupByAlias = new OIdentifier ( \"_$$$GROUP_BY_ALIAS$$$_\" + ( i ++ ) ) ; newItem . setAlias ( groupByAlias ) ; if ( info . preAggregateProjection == null ) { info . preAggregateProjection = new OProjection ( - 1 ) ; } if ( info . preAggregateProjection . getItems ( ) == null ) { info . preAggregateProjection . setItems ( new ArrayList <> ( ) ) ; } info . preAggregateProjection . getItems ( ) . add ( newItem ) ; newGroupBy . getItems ( ) . add ( new OExpression ( groupByAlias ) ) ; } info . groupBy = newGroupBy ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "translates subqueries to LET statements [CODESPLIT] private static void extractSubQueries ( QueryPlanningInfo info ) { SubQueryCollector collector = new SubQueryCollector ( ) ; if ( info . perRecordLetClause != null ) { info . perRecordLetClause . extractSubQueries ( collector ) ; } int i = 0 ; int j = 0 ; for ( Map . Entry < OIdentifier , OStatement > entry : collector . getSubQueries ( ) . entrySet ( ) ) { OIdentifier alias = entry . getKey ( ) ; OStatement query = entry . getValue ( ) ; if ( query . refersToParent ( ) ) { addRecordLevelLet ( info , alias , query , j ++ ) ; } else { addGlobalLet ( info , alias , query , i ++ ) ; } } collector . reset ( ) ; if ( info . whereClause != null ) { info . whereClause . extractSubQueries ( collector ) ; } if ( info . projection != null ) { info . projection . extractSubQueries ( collector ) ; } if ( info . orderBy != null ) { info . orderBy . extractSubQueries ( collector ) ; } if ( info . groupBy != null ) { info . groupBy . extractSubQueries ( collector ) ; } for ( Map . Entry < OIdentifier , OStatement > entry : collector . getSubQueries ( ) . entrySet ( ) ) { OIdentifier alias = entry . getKey ( ) ; OStatement query = entry . getValue ( ) ; if ( query . refersToParent ( ) ) { addRecordLevelLet ( info , alias , query ) ; } else { addGlobalLet ( info , alias , query ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks if this RID is from one of these clusters [CODESPLIT] private boolean isFromClusters ( ORid rid , Set < String > filterClusters , ODatabase database ) { if ( filterClusters == null ) { throw new IllegalArgumentException ( ) ; } String clusterName = database . getClusterNameById ( rid . getCluster ( ) . getValue ( ) . intValue ( ) ) ; return filterClusters . contains ( clusterName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tries to use an index for sorting only . Also adds the fetch step to the execution plan [CODESPLIT] private boolean handleClassWithIndexForSortOnly ( OSelectExecutionPlan plan , OIdentifier queryTarget , Set < String > filterClusters , QueryPlanningInfo info , OCommandContext ctx , boolean profilingEnabled ) { OSchema schema = getSchemaFromContext ( ctx ) ; OClass clazz = schema . getClass ( queryTarget . getStringValue ( ) ) ; if ( clazz == null ) { clazz = schema . getView ( queryTarget . getStringValue ( ) ) ; if ( clazz == null ) { throw new OCommandExecutionException ( \"Class not found: \" + queryTarget ) ; } } for ( OIndex idx : clazz . getIndexes ( ) . stream ( ) . filter ( i -> i . supportsOrderedIterations ( ) ) . filter ( i -> i . getDefinition ( ) != null ) . collect ( Collectors . toList ( ) ) ) { List < String > indexFields = idx . getDefinition ( ) . getFields ( ) ; if ( indexFields . size ( ) < info . orderBy . getItems ( ) . size ( ) ) { continue ; } boolean indexFound = true ; String orderType = null ; for ( int i = 0 ; i < info . orderBy . getItems ( ) . size ( ) ; i ++ ) { OOrderByItem orderItem = info . orderBy . getItems ( ) . get ( i ) ; if ( orderItem . getCollate ( ) != null ) { return false ; } String indexField = indexFields . get ( i ) ; if ( i == 0 ) { orderType = orderItem . getType ( ) ; } else { if ( orderType == null || ! orderType . equals ( orderItem . getType ( ) ) ) { indexFound = false ; break ; //ASC/DESC interleaved, cannot be used with index. } } if ( ! ( indexField . equals ( orderItem . getAlias ( ) ) || isInOriginalProjection ( indexField , orderItem . getAlias ( ) ) ) ) { indexFound = false ; break ; } } if ( indexFound && orderType != null ) { plan . chain ( new FetchFromIndexValuesStep ( idx , orderType . equals ( OOrderByItem . ASC ) , ctx , profilingEnabled ) ) ; int [ ] filterClusterIds = null ; if ( filterClusters != null ) { filterClusterIds = filterClusters . stream ( ) . map ( name -> ctx . getDatabase ( ) . getClusterIdByName ( name ) ) . mapToInt ( i -> i ) . toArray ( ) ; } plan . chain ( new GetValueFromIndexEntryStep ( ctx , filterClusterIds , profilingEnabled ) ) ; if ( info . serverToClusters . size ( ) == 1 ) { info . orderApplied = true ; } return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks if a class is the top of a diamond hierarchy [CODESPLIT] private boolean isDiamondHierarchy ( OClass clazz ) { Set < OClass > traversed = new HashSet <> ( ) ; List < OClass > stack = new ArrayList <> ( ) ; stack . add ( clazz ) ; while ( ! stack . isEmpty ( ) ) { OClass current = stack . remove ( 0 ) ; traversed . add ( current ) ; for ( OClass sub : current . getSubclasses ( ) ) { if ( traversed . contains ( sub ) ) { return true ; } stack . add ( sub ) ; traversed . add ( sub ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns TRUE if all the order clauses are ASC FALSE if all are DESC null otherwise [CODESPLIT] private Boolean getOrderDirection ( QueryPlanningInfo info ) { if ( info . orderBy == null ) { return null ; } String result = null ; for ( OOrderByItem item : info . orderBy . getItems ( ) ) { if ( result == null ) { result = item . getType ( ) == null ? OOrderByItem . ASC : item . getType ( ) ; } else { String newType = item . getType ( ) == null ? OOrderByItem . ASC : item . getType ( ) ; if ( ! newType . equals ( result ) ) { return null ; } } } return result == null || result . equals ( OOrderByItem . ASC ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks whether the condition has CONTAINSANY or similar expressions that require multiple index evaluations [CODESPLIT] private boolean requiresMultipleIndexLookups ( OAndBlock keyCondition ) { for ( OBooleanExpression oBooleanExpression : keyCondition . getSubBlocks ( ) ) { if ( ! ( oBooleanExpression instanceof OBinaryCondition ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a flat AND block and a set of indexes returns the best index to be used to process it with the complete description on how to use it [CODESPLIT] private IndexSearchDescriptor findBestIndexFor ( OCommandContext ctx , Set < OIndex < ? > > indexes , OAndBlock block , OClass clazz ) { //get all valid index descriptors List < IndexSearchDescriptor > descriptors = indexes . stream ( ) . filter ( x -> x . getInternal ( ) . canBeUsedInEqualityOperators ( ) ) . map ( index -> buildIndexSearchDescriptor ( ctx , index , block , clazz ) ) . filter ( Objects :: nonNull ) . filter ( x -> x . keyCondition != null ) . filter ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) > 0 ) . collect ( Collectors . toList ( ) ) ; List < IndexSearchDescriptor > fullTextIndexDescriptors = indexes . stream ( ) . filter ( idx -> idx . getType ( ) . equalsIgnoreCase ( \"FULLTEXT\" ) ) . filter ( idx -> ! idx . getAlgorithm ( ) . equalsIgnoreCase ( \"LUCENE\" ) ) . map ( idx -> buildIndexSearchDescriptorForFulltext ( ctx , idx , block , clazz ) ) . filter ( Objects :: nonNull ) . filter ( x -> x . keyCondition != null ) . filter ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) > 0 ) . collect ( Collectors . toList ( ) ) ; descriptors . addAll ( fullTextIndexDescriptors ) ; //remove the redundant descriptors (eg. if I have one on [a] and one on [a, b], the first one is redundant, just discard it) descriptors = removePrefixIndexes ( descriptors ) ; //sort by cost List < OPair < Integer , IndexSearchDescriptor > > sortedDescriptors = descriptors . stream ( ) . map ( x -> ( OPair < Integer , IndexSearchDescriptor > ) new OPair ( x . cost ( ctx ) , x ) ) . sorted ( ) . collect ( Collectors . toList ( ) ) ; //get only the descriptors with the lowest cost descriptors = sortedDescriptors . isEmpty ( ) ? Collections . emptyList ( ) : sortedDescriptors . stream ( ) . filter ( x -> x . key . equals ( sortedDescriptors . get ( 0 ) . key ) ) . map ( x -> x . value ) . collect ( Collectors . toList ( ) ) ; //sort remaining by the number of indexed fields descriptors = descriptors . stream ( ) . sorted ( Comparator . comparingInt ( x -> x . keyCondition . getSubBlocks ( ) . size ( ) ) ) . collect ( Collectors . toList ( ) ) ; //get the one that has more indexed fields return descriptors . isEmpty ( ) ? null : descriptors . get ( descriptors . size ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "finds prefix conditions for a given condition eg . if the condition is on [ a b ] and in the list there is another condition on [ a ] or on [ a b ] then that condition is returned . [CODESPLIT] private List < IndexSearchDescriptor > findPrefixes ( IndexSearchDescriptor desc , List < IndexSearchDescriptor > descriptors ) { List < IndexSearchDescriptor > result = new ArrayList <> ( ) ; for ( IndexSearchDescriptor item : descriptors ) { if ( isPrefixOf ( item , desc ) ) { result . add ( item ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if the first argument is a prefix for the second argument eg . if the first argument is [ a ] and the second argument is [ a b ] [CODESPLIT] private boolean isPrefixOf ( IndexSearchDescriptor item , IndexSearchDescriptor desc ) { List < OBooleanExpression > left = item . keyCondition . getSubBlocks ( ) ; List < OBooleanExpression > right = desc . keyCondition . getSubBlocks ( ) ; if ( left . size ( ) > right . size ( ) ) { return false ; } for ( int i = 0 ; i < left . size ( ) ; i ++ ) { if ( ! left . get ( i ) . equals ( right . get ( i ) ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given an index and a flat AND block returns a descriptor on how to process it with an index ( index index key and additional filters to apply after index fetch [CODESPLIT] private IndexSearchDescriptor buildIndexSearchDescriptor ( OCommandContext ctx , OIndex < ? > index , OAndBlock block , OClass clazz ) { List < String > indexFields = index . getDefinition ( ) . getFields ( ) ; OBinaryCondition keyCondition = new OBinaryCondition ( - 1 ) ; OIdentifier key = new OIdentifier ( \"key\" ) ; keyCondition . setLeft ( new OExpression ( key ) ) ; boolean allowsRange = allowsRangeQueries ( index ) ; boolean found = false ; OAndBlock blockCopy = block . copy ( ) ; Iterator < OBooleanExpression > blockIterator ; OAndBlock indexKeyValue = new OAndBlock ( - 1 ) ; IndexSearchDescriptor result = new IndexSearchDescriptor ( ) ; result . idx = index ; result . keyCondition = indexKeyValue ; for ( String indexField : indexFields ) { blockIterator = blockCopy . getSubBlocks ( ) . iterator ( ) ; boolean breakHere = false ; boolean indexFieldFound = false ; while ( blockIterator . hasNext ( ) ) { OBooleanExpression singleExp = blockIterator . next ( ) ; if ( singleExp instanceof OBinaryCondition ) { OExpression left = ( ( OBinaryCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { OBinaryCompareOperator operator = ( ( OBinaryCondition ) singleExp ) . getOperator ( ) ; if ( ! ( ( OBinaryCondition ) singleExp ) . getRight ( ) . isEarlyCalculated ( ctx ) ) { continue ; //this cannot be used because the value depends on single record } if ( operator instanceof OEqualsCompareOperator ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( operator instanceof OContainsKeyOperator && isMap ( clazz , indexField ) && isIndexByKey ( index , indexField ) ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( allowsRange && operator . isRangeOperator ( ) ) { found = true ; indexFieldFound = true ; breakHere = true ; //this is last element, no other fields can be added to the key because this is a range condition OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( operator ) ; condition . setRight ( ( ( OBinaryCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; //look for the opposite condition, on the same field, for range queries (the other side of the range) while ( blockIterator . hasNext ( ) ) { OBooleanExpression next = blockIterator . next ( ) ; if ( createsRangeWith ( ( OBinaryCondition ) singleExp , next ) ) { result . additionalRangeCondition = ( OBinaryCondition ) next ; blockIterator . remove ( ) ; break ; } } break ; } } } } else if ( singleExp instanceof OContainsValueCondition && ( ( OContainsValueCondition ) singleExp ) . getExpression ( ) != null && isMap ( clazz , indexField ) && isIndexByValue ( index , indexField ) ) { OExpression left = ( ( OContainsValueCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { found = true ; indexFieldFound = true ; OBinaryCondition condition = new OBinaryCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setOperator ( new OContainsValueOperator ( - 1 ) ) ; condition . setRight ( ( ( OContainsValueCondition ) singleExp ) . getExpression ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } else if ( singleExp instanceof OContainsAnyCondition ) { OExpression left = ( ( OContainsAnyCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { if ( ! ( ( OContainsAnyCondition ) singleExp ) . getRight ( ) . isEarlyCalculated ( ctx ) ) { continue ; //this cannot be used because the value depends on single record } found = true ; indexFieldFound = true ; OContainsAnyCondition condition = new OContainsAnyCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRight ( ( ( OContainsAnyCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } else if ( singleExp instanceof OInCondition ) { OExpression left = ( ( OInCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { if ( ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) != null ) { if ( ! ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) . isEarlyCalculated ( ctx ) ) { continue ; //this cannot be used because the value depends on single record } found = true ; indexFieldFound = true ; OInCondition condition = new OInCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRightMathExpression ( ( ( OInCondition ) singleExp ) . getRightMathExpression ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } else if ( ( ( OInCondition ) singleExp ) . getRightParam ( ) != null ) { found = true ; indexFieldFound = true ; OInCondition condition = new OInCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRightParam ( ( ( OInCondition ) singleExp ) . getRightParam ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } } } if ( breakHere || ! indexFieldFound ) { break ; } } if ( result . keyCondition . getSubBlocks ( ) . size ( ) < index . getDefinition ( ) . getFields ( ) . size ( ) && ! index . supportsOrderedIterations ( ) ) { //hash indexes do not support partial key match return null ; } if ( found ) { result . remainingCondition = blockCopy ; return result ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a full text index and a flat AND block returns a descriptor on how to process it with an index ( index index key and additional filters to apply after index fetch [CODESPLIT] private IndexSearchDescriptor buildIndexSearchDescriptorForFulltext ( OCommandContext ctx , OIndex < ? > index , OAndBlock block , OClass clazz ) { List < String > indexFields = index . getDefinition ( ) . getFields ( ) ; OBinaryCondition keyCondition = new OBinaryCondition ( - 1 ) ; OIdentifier key = new OIdentifier ( \"key\" ) ; keyCondition . setLeft ( new OExpression ( key ) ) ; boolean found = false ; OAndBlock blockCopy = block . copy ( ) ; Iterator < OBooleanExpression > blockIterator ; OAndBlock indexKeyValue = new OAndBlock ( - 1 ) ; IndexSearchDescriptor result = new IndexSearchDescriptor ( ) ; result . idx = index ; result . keyCondition = indexKeyValue ; for ( String indexField : indexFields ) { blockIterator = blockCopy . getSubBlocks ( ) . iterator ( ) ; boolean breakHere = false ; boolean indexFieldFound = false ; while ( blockIterator . hasNext ( ) ) { OBooleanExpression singleExp = blockIterator . next ( ) ; if ( singleExp instanceof OContainsTextCondition ) { OExpression left = ( ( OContainsTextCondition ) singleExp ) . getLeft ( ) ; if ( left . isBaseIdentifier ( ) ) { String fieldName = left . getDefaultAlias ( ) . getStringValue ( ) ; if ( indexField . equals ( fieldName ) ) { found = true ; indexFieldFound = true ; OContainsTextCondition condition = new OContainsTextCondition ( - 1 ) ; condition . setLeft ( left ) ; condition . setRight ( ( ( OContainsTextCondition ) singleExp ) . getRight ( ) . copy ( ) ) ; indexKeyValue . getSubBlocks ( ) . add ( condition ) ; blockIterator . remove ( ) ; break ; } } } } if ( breakHere || ! indexFieldFound ) { break ; } } if ( result . keyCondition . getSubBlocks ( ) . size ( ) < index . getDefinition ( ) . getFields ( ) . size ( ) && ! index . supportsOrderedIterations ( ) ) { //hash indexes do not support partial key match return null ; } if ( found ) { result . remainingCondition = blockCopy ; return result ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "aggregates multiple index conditions that refer to the same key search [CODESPLIT] private List < IndexSearchDescriptor > commonFactor ( List < IndexSearchDescriptor > indexSearchDescriptors ) { //index, key condition, additional filter (to aggregate in OR) Map < OIndex , Map < IndexCondPair , OOrBlock > > aggregation = new HashMap <> ( ) ; for ( IndexSearchDescriptor item : indexSearchDescriptors ) { Map < IndexCondPair , OOrBlock > filtersForIndex = aggregation . get ( item . idx ) ; if ( filtersForIndex == null ) { filtersForIndex = new HashMap <> ( ) ; aggregation . put ( item . idx , filtersForIndex ) ; } IndexCondPair extendedCond = new IndexCondPair ( item . keyCondition , item . additionalRangeCondition ) ; OOrBlock existingAdditionalConditions = filtersForIndex . get ( extendedCond ) ; if ( existingAdditionalConditions == null ) { existingAdditionalConditions = new OOrBlock ( - 1 ) ; filtersForIndex . put ( extendedCond , existingAdditionalConditions ) ; } existingAdditionalConditions . getSubBlocks ( ) . add ( item . remainingCondition ) ; } List < IndexSearchDescriptor > result = new ArrayList <> ( ) ; for ( Map . Entry < OIndex , Map < IndexCondPair , OOrBlock > > item : aggregation . entrySet ( ) ) { for ( Map . Entry < IndexCondPair , OOrBlock > filters : item . getValue ( ) . entrySet ( ) ) { result . add ( new IndexSearchDescriptor ( item . getKey ( ) , filters . getKey ( ) . mainCondition , filters . getKey ( ) . additionalRange , filters . getValue ( ) ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of the requested strategy . Since strategies are stateless if an existing instance already exists then it s returned . [CODESPLIT] public ODocumentFieldHandlingStrategy create ( int strategy ) { Optional < ODocumentFieldHandlingStrategy > registered = ODocumentFieldHandlingStrategyRegistry . getInstance ( ) . getStrategy ( strategy ) ; if ( registered . isPresent ( ) ) { return registered . get ( ) ; } Map < OType , ODocumentFieldOTypeHandlingStrategy > typeHandlingStrategies = new HashMap < OType , ODocumentFieldOTypeHandlingStrategy > ( ) ; switch ( strategy ) { case SINGLE_ORECORD_BYTES : typeHandlingStrategies . put ( OType . BINARY , new ODocumentSingleRecordBytesOTypeHandlingStrategy ( ) ) ; break ; case SPLIT_ORECORD_BYTES : typeHandlingStrategies . put ( OType . BINARY , new ODocumentSplitRecordBytesOTypeHandlingStrategy ( ) ) ; break ; case SIMPLE : default : break ; } ODocumentSmartFieldHandlingStrategy strategyInstance = new ODocumentSmartFieldHandlingStrategy ( typeHandlingStrategies ) ; ODocumentFieldHandlingStrategyRegistry . getInstance ( ) . registerStrategy ( strategy , strategyInstance ) ; return strategyInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - Create any object if the class has a public constructor that accepts a String as unique parameter . [CODESPLIT] public Object fromStream ( final String iStream ) { if ( iStream == null || iStream . length ( ) == 0 ) // NULL VALUE\r return null ; OSerializableStream instance = null ; int propertyPos = iStream . indexOf ( ' ' ) ; int pos = iStream . indexOf ( OStringSerializerEmbedded . SEPARATOR ) ; if ( pos < 0 || propertyPos > - 1 && pos > propertyPos ) { instance = new ODocument ( ) ; pos = - 1 ; } else { final String className = iStream . substring ( 0 , pos ) ; try { final Class < ? > clazz = Class . forName ( className ) ; instance = ( OSerializableStream ) clazz . newInstance ( ) ; } catch ( Exception e ) { final String message = \"Error on unmarshalling content. Class: \" + className ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new OSerializationException ( message ) , e ) ; } } instance . fromStream ( Base64 . getDecoder ( ) . decode ( iStream . substring ( pos + 1 ) ) ) ; return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the class name size + class name + object content [CODESPLIT] public StringBuilder toStream ( final StringBuilder iOutput , Object iValue ) { if ( iValue != null ) { if ( ! ( iValue instanceof OSerializableStream ) ) throw new OSerializationException ( \"Cannot serialize the object since it's not implements the OSerializableStream interface\" ) ; OSerializableStream stream = ( OSerializableStream ) iValue ; iOutput . append ( iValue . getClass ( ) . getName ( ) ) ; iOutput . append ( OStringSerializerEmbedded . SEPARATOR ) ; iOutput . append ( Base64 . getEncoder ( ) . encodeToString ( stream . toStream ( ) ) ) ; } return iOutput ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a function . [CODESPLIT] public Object execute ( final Object iThis , final OIdentifiable iCurrentRecord , final Object iCurrentResult , final OCommandContext iContext ) { // RESOLVE VALUES USING THE CURRENT RECORD for ( int i = 0 ; i < configuredParameters . length ; ++ i ) { runtimeParameters [ i ] = configuredParameters [ i ] ; if ( configuredParameters [ i ] instanceof OSQLFilterItemField ) { runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OSQLFunctionRuntime ) runtimeParameters [ i ] = ( ( OSQLFunctionRuntime ) configuredParameters [ i ] ) . execute ( iThis , iCurrentRecord , iCurrentResult , iContext ) ; else if ( configuredParameters [ i ] instanceof OSQLFilterItemVariable ) { runtimeParameters [ i ] = ( ( OSQLFilterItemVariable ) configuredParameters [ i ] ) . getValue ( iCurrentRecord , iCurrentResult , iContext ) ; } else if ( configuredParameters [ i ] instanceof OCommandSQL ) { try { runtimeParameters [ i ] = ( ( OCommandSQL ) configuredParameters [ i ] ) . setContext ( iContext ) . execute ( ) ; } catch ( OCommandExecutorNotFoundException ignore ) { // TRY WITH SIMPLE CONDITION final String text = ( ( OCommandSQL ) configuredParameters [ i ] ) . getText ( ) ; final OSQLPredicate pred = new OSQLPredicate ( text ) ; runtimeParameters [ i ] = pred . evaluate ( iCurrentRecord instanceof ORecord ? ( ORecord ) iCurrentRecord : null , ( ODocument ) iCurrentResult , iContext ) ; // REPLACE ORIGINAL PARAM configuredParameters [ i ] = pred ; } } else if ( configuredParameters [ i ] instanceof OSQLPredicate ) runtimeParameters [ i ] = ( ( OSQLPredicate ) configuredParameters [ i ] ) . evaluate ( iCurrentRecord . getRecord ( ) , ( iCurrentRecord instanceof ODocument ? ( ODocument ) iCurrentResult : null ) , iContext ) ; else if ( configuredParameters [ i ] instanceof String ) { if ( configuredParameters [ i ] . toString ( ) . startsWith ( \"\\\"\" ) || configuredParameters [ i ] . toString ( ) . startsWith ( \"'\" ) ) runtimeParameters [ i ] = OIOUtils . getStringContent ( configuredParameters [ i ] ) ; } } if ( function . getMaxParams ( ) == - 1 || function . getMaxParams ( ) > 0 ) { if ( runtimeParameters . length < function . getMinParams ( ) || ( function . getMaxParams ( ) > - 1 && runtimeParameters . length > function . getMaxParams ( ) ) ) throw new OCommandExecutionException ( \"Syntax error: function '\" + function . getName ( ) + \"' needs \" + ( function . getMinParams ( ) == function . getMaxParams ( ) ? function . getMinParams ( ) : function . getMinParams ( ) + \"-\" + function . getMaxParams ( ) ) + \" argument(s) while has been received \" + runtimeParameters . length ) ; } final Object functionResult = function . execute ( iThis , iCurrentRecord , iCurrentResult , runtimeParameters , iContext ) ; if ( functionResult instanceof OAutoConvertToRecord ) // FORCE AVOIDING TO CONVERT IN RECORD ( ( OAutoConvertToRecord ) functionResult ) . setAutoConvertToRecord ( false ) ; return transformValue ( iCurrentRecord , iContext , functionResult ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the user has the permission to access to the requested resource for the requested operation . [CODESPLIT] public ORole allow ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific , final int iOperation ) { if ( roles == null || roles . isEmpty ( ) ) { if ( document . field ( \"roles\" ) != null && ! ( ( Collection < OIdentifiable > ) document . field ( \"roles\" ) ) . isEmpty ( ) ) { final ODocument doc = document ; document = null ; fromStream ( doc ) ; } else throw new OSecurityAccessException ( document . getDatabase ( ) . getName ( ) , \"User '\" + document . field ( \"name\" ) + \"' has no role defined\" ) ; } final ORole role = checkIfAllowed ( resourceGeneric , resourceSpecific , iOperation ) ; if ( role == null ) throw new OSecurityAccessException ( document . getDatabase ( ) . getName ( ) , \"User '\" + document . field ( \"name\" ) + \"' does not have permission to execute the operation '\" + ORole . permissionToString ( iOperation ) + \"' against the resource: \" + resourceGeneric + \".\" + resourceSpecific ) ; return role ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a rule was defined for the user . [CODESPLIT] public boolean isRuleDefined ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific ) { for ( ORole r : roles ) if ( r == null ) OLogManager . instance ( ) . warn ( this , \"User '%s' has a null role, bypass it. Consider to fix this user roles before to continue\" , getName ( ) ) ; else if ( r . hasRule ( resourceGeneric , resourceSpecific ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a compact string with all the relevant information . [CODESPLIT] public static String getCompactServerStatus ( final ODistributedServerManager manager , final ODocument distribCfg ) { final StringBuilder buffer = new StringBuilder ( ) ; final Collection < ODocument > members = distribCfg . field ( \"members\" ) ; if ( members != null ) { buffer . append ( members . size ( ) ) ; buffer . append ( \":[\" ) ; int memberCount = 0 ; for ( ODocument m : members ) { if ( m == null ) continue ; if ( memberCount ++ > 0 ) buffer . append ( \",\" ) ; final String serverName = m . field ( \"name\" ) ; buffer . append ( serverName ) ; buffer . append ( ( Object ) m . field ( \"status\" ) ) ; final Collection < String > databases = m . field ( \"databases\" ) ; if ( databases != null ) { buffer . append ( \"{\" ) ; int dbCount = 0 ; for ( String dbName : databases ) { final ODistributedConfiguration dbCfg = manager . getDatabaseConfiguration ( dbName , false ) ; if ( dbCfg == null ) continue ; if ( dbCount ++ > 0 ) buffer . append ( \",\" ) ; buffer . append ( dbName ) ; buffer . append ( \"=\" ) ; buffer . append ( manager . getDatabaseStatus ( serverName , dbName ) ) ; buffer . append ( \" (\" ) ; buffer . append ( dbCfg . getServerRole ( serverName ) ) ; buffer . append ( \")\" ) ; } buffer . append ( \"}\" ) ; } } buffer . append ( \"]\" ) ; } return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Protecte system database from being replicated [CODESPLIT] protected void initSystemDatabase ( ) { final ODocument defaultCfg = getStorage ( OSystemDatabase . SYSTEM_DB_NAME ) . loadDatabaseConfiguration ( getDefaultDatabaseConfigFile ( ) ) ; defaultCfg . field ( \"autoDeploy\" , false ) ; final OModifiableDistributedConfiguration sysCfg = new OModifiableDistributedConfiguration ( defaultCfg ) ; sysCfg . removeServer ( \"<NEW_NODE>\" ) ; messageService . registerDatabase ( OSystemDatabase . SYSTEM_DB_NAME , sysCfg ) ; sysCfg . addNewNodeInServerList ( getLocalNodeName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes all the available server s databases as distributed . [CODESPLIT] protected void loadLocalDatabases ( ) { final List < String > dbs = new ArrayList < String > ( serverInstance . getAvailableStorageNames ( ) . keySet ( ) ) ; Collections . sort ( dbs ) ; for ( final String databaseName : dbs ) { if ( messageService . getDatabase ( databaseName ) == null ) { ODistributedServerLog . info ( this , nodeName , null , DIRECTION . NONE , \"Opening database '%s'...\" , databaseName ) ; // INIT THE STORAGE final ODistributedStorage stg = getStorage ( databaseName ) ; executeInDistributedDatabaseLock ( databaseName , 60000 , null , new OCallable < Object , OModifiableDistributedConfiguration > ( ) { @ Override public Object call ( OModifiableDistributedConfiguration cfg ) { ODistributedServerLog . info ( this , nodeName , null , DIRECTION . NONE , \"Current node started as %s for database '%s'\" , cfg . getServerRole ( nodeName ) , databaseName ) ; final ODistributedDatabaseImpl ddb = messageService . registerDatabase ( databaseName , cfg ) ; ddb . resume ( ) ; // 1ST NODE TO HAVE THE DATABASE cfg . addNewNodeInServerList ( nodeName ) ; // COLLECT ALL THE CLUSTERS WITH REMOVED NODE AS OWNER reassignClustersOwnership ( nodeName , databaseName , cfg , true ) ; try { ddb . getSyncConfiguration ( ) . setLastLSN ( nodeName , ( ( OAbstractPaginatedStorage ) stg . getUnderlying ( ) ) . getLSN ( ) , false ) ; } catch ( IOException e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , \"Error on saving distributed LSN for database '%s' (err=%s).\" , databaseName , e . getMessage ( ) ) ; } ddb . setOnline ( ) ; return null ; } } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the node map entry . [CODESPLIT] @ Override public void memberRemoved ( final MembershipEvent iEvent ) { try { updateLastClusterChange ( ) ; if ( iEvent . getMember ( ) == null ) return ; final String nodeLeftName = getNodeName ( iEvent . getMember ( ) ) ; if ( nodeLeftName == null ) return ; removeServer ( nodeLeftName , true ) ; } catch ( HazelcastInstanceNotActiveException | RetryableHazelcastException e ) { OLogManager . instance ( ) . error ( this , \"Hazelcast is not running\" , e ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error on removing the server '%s'\" , e , getNodeName ( iEvent . getMember ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Elects a new server as coordinator . The election browse the ordered server list . [CODESPLIT] @ Override public String electNewLockManager ( ) { if ( hazelcastInstance == null ) throw new HazelcastInstanceNotActiveException ( ) ; final ILock lock = hazelcastInstance . getLock ( \"orientdb.lockManagerElection\" ) ; lock . lock ( ) ; try { // TRY ALL THE SERVERS IN ORDER (ALL THE SERVERS HAVE THE SAME LIST) String lockManagerServer = getLockManagerRequester ( ) . getServer ( ) ; // PROTECT FROM DOUBLE LOCK MANAGER ELECTION IN CASE OF REMOVE OF LOCK MANAGER if ( lockManagerServer != null && getActiveServers ( ) . contains ( lockManagerServer ) ) return lockManagerServer ; final String originalLockManager = lockManagerServer ; ODistributedServerLog . debug ( this , nodeName , originalLockManager , DIRECTION . OUT , \"lock '%s' is unreachable, electing a new lock...\" , originalLockManager ) ; int lockManagerServerId = - 1 ; if ( lockManagerServer != null && registeredNodeByName . containsKey ( lockManagerServer ) ) lockManagerServerId = registeredNodeByName . get ( lockManagerServer ) ; String newServer = null ; int currIndex = lockManagerServerId ; for ( int i = 0 ; i < registeredNodeById . size ( ) ; ++ i ) { currIndex ++ ; if ( currIndex >= registeredNodeById . size ( ) ) // RESTART FROM THE FIRST currIndex = 0 ; newServer = registeredNodeById . get ( currIndex ) ; if ( newServer == null ) throw new OConfigurationException ( \"Found null server at index \" + currIndex + \" of server list \" + registeredNodeById ) ; if ( newServer . equalsIgnoreCase ( getLocalNodeName ( ) ) || activeNodes . containsKey ( newServer ) ) { // TODO: IMPROVE ELECTION BY CHECKING AL THE NODES AGREE ON IT ODistributedServerLog . debug ( this , nodeName , newServer , DIRECTION . OUT , \"Trying to elected server '%s' as new lock (old=%s)...\" , newServer , originalLockManager ) ; try { getLockManagerRequester ( ) . setServer ( newServer ) ; configurationMap . put ( CONFIG_LOCKMANAGER , getLockManagerRequester ( ) . getServer ( ) ) ; ODistributedServerLog . info ( this , nodeName , newServer , DIRECTION . OUT , \"Elected server '%s' as new lock (old=%s)\" , newServer , originalLockManager ) ; break ; } catch ( Exception e ) { // NO SERVER RESPONDED, THE SERVER COULD BE ISOLATED, GO AHEAD WITH THE NEXT IN THE LIST ODistributedServerLog . info ( this , nodeName , newServer , DIRECTION . OUT , \"Error on electing server '%s' as new lock (error: %s)\" , newServer , e ) ; } } } return newServer ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ASSIGN THE LOCK MANAGER AT STARTUP [CODESPLIT] private void assignLockManagerFromCluster ( ) { String lockManagerServer = null ; while ( lockManagerServer == null ) { if ( activeNodes . size ( ) == 1 ) { // ONLY CURRENT NODE ONLINE, SET IT AS INITIAL LOCK MANAGER lockManagerServer = nodeName ; if ( configurationMap . putIfAbsent ( CONFIG_LOCKMANAGER , lockManagerServer ) == null ) break ; } else { lockManagerServer = ( String ) configurationMap . get ( CONFIG_LOCKMANAGER ) ; if ( lockManagerServer != null && lockManagerServer . equals ( nodeName ) ) { // LAST LOCK MANAGER WAS CURRENT NODE? TRY TO FORCE A NEW ELECTION OLogManager . instance ( ) . info ( this , \"Found lock as current node, even if it was offline. Forcing a new election...\" ) ; getLockManagerRequester ( ) . setServer ( lockManagerServer ) ; lockManagerServer = electNewLockManager ( ) ; break ; } if ( lockManagerServer != null ) break ; } try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { break ; } } getLockManagerRequester ( ) . setServer ( lockManagerServer ) ; OLogManager . instance ( ) . info ( this , \"Distributed Lock Manager server is '%s'\" , lockManagerServer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Double object , ByteBuffer buffer , Object ... hints ) { buffer . putLong ( Double . doubleToLongBits ( object ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Double deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return Double . longBitsToDouble ( walChanges . getLongValue ( buffer , offset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( OIdentifiable object , ByteBuffer buffer , Object ... hints ) { OLinkSerializer . INSTANCE . serializeInByteBufferObject ( object , buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OIdentifiable deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return OLinkSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return OLinkSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer , walChanges , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commits the micro - transaction if it s a top - level micro - transaction . [CODESPLIT] public void commit ( ) { if ( ! active ) throw error ( \"Inactive micro-transaction on commit\" ) ; if ( level < 1 ) throw error ( \"Unbalanced micro-transaction, level = \" + level ) ; -- level ; if ( level == 0 ) { active = false ; doCommit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rollbacks the micro - transaction if it s a top - level micro - transaction . [CODESPLIT] public void rollback ( ) { if ( ! active ) throw error ( \"Inactive micro-transaction on rollback\" ) ; if ( level < 1 ) throw error ( \"Unbalanced micro-transaction, level = \" + level ) ; -- level ; if ( level == 0 ) { active = false ; doRollback ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the record identity after its successful commit . [CODESPLIT] public void updateIdentityAfterRecordCommit ( final ORID oldRid , final ORID newRid ) { if ( oldRid . equals ( newRid ) ) return ; // no change, ignore // XXX: Identity update may mutate the index keys, so we have to identify and reinsert potentially affected index keys to keep // the OTransactionIndexChanges.changesPerKey in a consistent state. final List < KeyChangesUpdateRecord > keyRecordsToReinsert = new ArrayList <> ( ) ; final OIndexManager indexManager = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) ; for ( Map . Entry < String , OTransactionIndexChanges > entry : indexOperations . entrySet ( ) ) { final OIndex < ? > index = indexManager . getIndex ( entry . getKey ( ) ) ; if ( index == null ) throw new OTransactionException ( \"Cannot find index '\" + entry . getValue ( ) + \"' while committing transaction\" ) ; final Dependency [ ] fieldRidDependencies = getIndexFieldRidDependencies ( index ) ; if ( ! isIndexMayDependOnRids ( fieldRidDependencies ) ) continue ; final OTransactionIndexChanges indexChanges = entry . getValue ( ) ; for ( final Iterator < OTransactionIndexChangesPerKey > iterator = indexChanges . changesPerKey . values ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { final OTransactionIndexChangesPerKey keyChanges = iterator . next ( ) ; if ( isIndexKeyMayDependOnRid ( keyChanges . key , oldRid , fieldRidDependencies ) ) { keyRecordsToReinsert . add ( new KeyChangesUpdateRecord ( keyChanges , indexChanges ) ) ; iterator . remove ( ) ; } } } // Update the identity. final ORecordOperation rec = resolveRecordOperation ( oldRid ) ; if ( rec != null ) { updatedRids . put ( newRid . copy ( ) , oldRid . copy ( ) ) ; if ( ! rec . getRecord ( ) . getIdentity ( ) . equals ( newRid ) ) { ORecordInternal . onBeforeIdentityChanged ( rec . getRecord ( ) ) ; final ORecordId recordId = ( ORecordId ) rec . getRecord ( ) . getIdentity ( ) ; if ( recordId == null ) { ORecordInternal . setIdentity ( rec . getRecord ( ) , new ORecordId ( newRid ) ) ; } else { recordId . setClusterPosition ( newRid . getClusterPosition ( ) ) ; recordId . setClusterId ( newRid . getClusterId ( ) ) ; } ORecordInternal . onAfterIdentityChanged ( rec . getRecord ( ) ) ; } } // Reinsert the potentially affected index keys. for ( KeyChangesUpdateRecord record : keyRecordsToReinsert ) record . indexChanges . changesPerKey . put ( record . keyChanges . key , record . keyChanges ) ; // Update the indexes. final List < OTransactionRecordIndexOperation > transactionIndexOperations = recordIndexOperations . get ( translateRid ( oldRid ) ) ; if ( transactionIndexOperations != null ) { for ( final OTransactionRecordIndexOperation indexOperation : transactionIndexOperations ) { OTransactionIndexChanges indexEntryChanges = indexOperations . get ( indexOperation . index ) ; if ( indexEntryChanges == null ) continue ; final OTransactionIndexChangesPerKey keyChanges ; if ( indexOperation . key == null ) { keyChanges = indexEntryChanges . nullKeyChanges ; } else { keyChanges = indexEntryChanges . changesPerKey . get ( indexOperation . key ) ; } if ( keyChanges != null ) updateChangesIdentity ( oldRid , newRid , keyChanges ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the record cache after unsuccessful micro - transaction commit . [CODESPLIT] public void updateRecordCacheAfterRollback ( ) { final OLocalRecordCache databaseLocalCache = database . getLocalCache ( ) ; for ( ORecordOperation recordOperation : recordOperations . values ( ) ) databaseLocalCache . deleteRecord ( recordOperation . getRecord ( ) . getIdentity ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the path for a file creation or replacement . If the file pointed by the path already exists it will be deleted a warning will be emitted to the log in this case . All absent directories along the path will be created . [CODESPLIT] public static void prepareForFileCreationOrReplacement ( Path path , Object requester , String operation ) throws IOException { if ( Files . deleteIfExists ( path ) ) OLogManager . instance ( ) . warn ( requester , \"'%s' deleted while %s\" , path , operation ) ; final Path parent = path . getParent ( ) ; if ( parent != null ) Files . createDirectories ( parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to move a file from the source to the target atomically . If atomic move is not possible falls back to regular move . [CODESPLIT] public static void atomicMoveWithFallback ( Path source , Path target , Object requester ) throws IOException { try { Files . move ( source , target , StandardCopyOption . ATOMIC_MOVE ) ; } catch ( AtomicMoveNotSupportedException ignore ) { OLogManager . instance ( ) . warn ( requester , \"atomic file move is not possible, falling back to regular move (moving '%s' to '%s')\" , source , target ) ; Files . move ( source , target ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "splits this pattern into multiple [CODESPLIT] public List < Pattern > getDisjointPatterns ( ) { Map < PatternNode , String > reverseMap = new IdentityHashMap <> ( ) ; reverseMap . putAll ( this . aliasToNode . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( x -> x . getValue ( ) , x -> x . getKey ( ) ) ) ) ; List < Pattern > result = new ArrayList <> ( ) ; while ( ! reverseMap . isEmpty ( ) ) { Pattern pattern = new Pattern ( ) ; result . add ( pattern ) ; Map . Entry < PatternNode , String > nextNode = reverseMap . entrySet ( ) . iterator ( ) . next ( ) ; Set < PatternNode > toVisit = new HashSet <> ( ) ; toVisit . add ( nextNode . getKey ( ) ) ; while ( toVisit . size ( ) > 0 ) { PatternNode currentNode = toVisit . iterator ( ) . next ( ) ; toVisit . remove ( currentNode ) ; if ( reverseMap . containsKey ( currentNode ) ) { pattern . aliasToNode . put ( reverseMap . get ( currentNode ) , currentNode ) ; reverseMap . remove ( currentNode ) ; for ( PatternEdge x : currentNode . out ) { toVisit . add ( x . in ) ; } for ( PatternEdge x : currentNode . in ) { toVisit . add ( x . out ) ; } } } pattern . recalculateNumOfEdges ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only idempotent commands that don t involve any other node can be executed locally . [CODESPLIT] protected boolean executeOnlyLocally ( final String localNodeName , final ODistributedConfiguration dbCfg , final OCommandExecutor exec , final Collection < String > involvedClusters , final Collection < String > nodes ) { boolean executeLocally = false ; if ( exec . isIdempotent ( ) ) { final int availableNodes = nodes . size ( ) ; // IDEMPOTENT: CHECK IF CAN WORK LOCALLY ONLY int maxReadQuorum ; if ( involvedClusters . isEmpty ( ) ) maxReadQuorum = dbCfg . getReadQuorum ( null , availableNodes , localNodeName ) ; else { maxReadQuorum = 0 ; for ( String cl : involvedClusters ) maxReadQuorum = Math . max ( maxReadQuorum , dbCfg . getReadQuorum ( cl , availableNodes , localNodeName ) ) ; } if ( nodes . contains ( localNodeName ) && maxReadQuorum <= 1 ) executeLocally = true ; } return executeLocally ; } public boolean isLocalEnv ( ) { return localDistributedDatabase == null || dManager == null || distributedConfiguration == null || OScenarioThreadLocal . INSTANCE . isRunModeDistributed ( ) ; } public OStorageOperationResult < ORawBuffer > readRecord  ( final ORecordId iRecordId , final String iFetchPlan , final boolean iIgnoreCache , final boolean prefetchRecords , final ORecordCallback < ORawBuffer > iCallback ) { if ( isLocalEnv ( ) ) { // ALREADY DISTRIBUTED return wrapped . readRecord ( iRecordId , iFetchPlan , iIgnoreCache , prefetchRecords , iCallback ) ; } final ORawBuffer memCopy = localDistributedDatabase . getRecordIfLocked ( iRecordId ) ; if ( memCopy != null ) return new OStorageOperationResult < ORawBuffer > ( memCopy ) ; try { final String clusterName = getClusterNameByRID ( iRecordId ) ; final ODistributedConfiguration dbCfg = distributedConfiguration ; final List < String > nodes = dbCfg . getServers ( clusterName , null ) ; final int availableNodes = nodes . size ( ) ; // CHECK IF LOCAL NODE OWNS THE DATA AND READ-QUORUM = 1: GET IT LOCALLY BECAUSE IT'S FASTER final String localNodeName = dManager . getLocalNodeName ( ) ; if ( nodes . isEmpty ( ) || nodes . contains ( dManager . getLocalNodeName ( ) ) && dbCfg . getReadQuorum ( clusterName , availableNodes , localNodeName ) <= 1 ) { // DON'T REPLICATE return ( OStorageOperationResult < ORawBuffer > ) OScenarioThreadLocal . executeAsDistributed ( new Callable ( ) { @ Override public Object call ( ) throws Exception { return wrapped . readRecord ( iRecordId , iFetchPlan , iIgnoreCache , prefetchRecords , iCallback ) ; } } ) ; } final OReadRecordTask task = ( ( OReadRecordTask ) dManager . getTaskFactoryManager ( ) . getFactoryByServerNames ( nodes ) . createTask ( OReadRecordTask . FACTORYID ) ) . init ( iRecordId ) ; // DISTRIBUTE IT final ODistributedResponse response = dManager . sendRequest ( getName ( ) , Collections . singleton ( clusterName ) , nodes , task , dManager . getNextMessageIdCounter ( ) , EXECUTION_MODE . RESPONSE , null , null , null ) ; final Object dResult = response != null ? response . getPayload ( ) : null ; if ( dResult instanceof ONeedRetryException ) throw ( ONeedRetryException ) dResult ; else if ( dResult instanceof Exception ) throw OException . wrapException ( new ODistributedException ( \"Error on execution distributed read record\" ) , ( Exception ) dResult ) ; return new OStorageOperationResult < ORawBuffer > ( ( ORawBuffer ) dResult ) ; } catch ( ONeedRetryException e ) { // PASS THROUGH throw e ; } catch ( Exception e ) { handleDistributedException ( \"Cannot route read record operation for %s to the distributed node\" , e , iRecordId ) ; // UNREACHABLE return null ; } } @ Override public OStorageOperationResult < ORawBuffer > readRecordIfVersionIsNotLatest  ( final ORecordId rid , final String fetchPlan , final boolean ignoreCache , final int recordVersion ) throws ORecordNotFoundException { if ( isLocalEnv ( ) ) { return wrapped . readRecordIfVersionIsNotLatest ( rid , fetchPlan , ignoreCache , recordVersion ) ; } final ORawBuffer memCopy = localDistributedDatabase . getRecordIfLocked ( rid ) ; if ( memCopy != null ) return new OStorageOperationResult < ORawBuffer > ( memCopy ) ; try { final String clusterName = getClusterNameByRID ( rid ) ; final ODistributedConfiguration dbCfg = distributedConfiguration ; final List < String > nodes = dbCfg . getServers ( clusterName , null ) ; final int availableNodes = nodes . size ( ) ; // CHECK IF LOCAL NODE OWNS THE DATA AND READ-QUORUM = 1: GET IT LOCALLY BECAUSE IT'S FASTER final String localNodeName = dManager . getLocalNodeName ( ) ; if ( nodes . isEmpty ( ) || nodes . contains ( dManager . getLocalNodeName ( ) ) && dbCfg . getReadQuorum ( clusterName , availableNodes , localNodeName ) <= 1 ) { // DON'T REPLICATE return ( OStorageOperationResult < ORawBuffer > ) OScenarioThreadLocal . executeAsDistributed ( new Callable ( ) { @ Override public Object call ( ) throws Exception { return wrapped . readRecordIfVersionIsNotLatest ( rid , fetchPlan , ignoreCache , recordVersion ) ; } } ) ; } final OReadRecordIfNotLatestTask task = ( OReadRecordIfNotLatestTask ) dManager . getTaskFactoryManager ( ) . getFactoryByServerNames ( nodes ) . createTask ( OReadRecordIfNotLatestTask . FACTORYID ) ; task . init ( rid , recordVersion ) ; // DISTRIBUTE IT final Object result = dManager . sendRequest ( getName ( ) , Collections . singleton ( clusterName ) , nodes , task , dManager . getNextMessageIdCounter ( ) , EXECUTION_MODE . RESPONSE , null , null , null ) . getPayload ( ) ; if ( result instanceof ONeedRetryException ) throw ( ONeedRetryException ) result ; else if ( result instanceof Exception ) throw OException . wrapException ( new ODistributedException ( \"Error on execution distributed read record\" ) , ( Exception ) result ) ; return new OStorageOperationResult < ORawBuffer > ( ( ORawBuffer ) result ) ; } catch ( ONeedRetryException e ) { // PASS THROUGH throw e ; } catch ( Exception e ) { handleDistributedException ( \"Cannot route read record operation for %s to the distributed node\" , e , rid ) ; // UNREACHABLE return null ; } } @ Override public OStorageOperationResult < Boolean > deleteRecord  ( final ORecordId iRecordId , final int iVersion , final int iMode , final ORecordCallback < Boolean > iCallback ) { // IF is a real delete should be with a tx return wrapped . deleteRecord ( iRecordId , iVersion , iMode , iCallback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect up the characters as element s characters may be split across multiple calls . Isn t SAX lovely ... [CODESPLIT] @ Override public void characters ( char [ ] ch , int start , int length ) throws SAXException { builder . append ( ch , start , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a string produced by <code > timeToString< / code > or <code > dateToString< / code > back to a time represented as a Date object . [CODESPLIT] public static Date stringToDate ( String dateString ) throws ParseException { try { SimpleDateFormat format = RESOLUTIONS [ dateString . length ( ) ] . format ( ) ; return format . parse ( dateString ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( OLuceneDateTools . class , \"Exception is suppressed, original exception is \" , e ) ; //noinspection ThrowInsideCatchBlockWhichIgnoresCaughtException throw new ParseException ( \"Input is not a valid date string: \" + dateString , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tells if the channel is connected . [CODESPLIT] public boolean isConnected ( ) { final Socket s = socket ; return s != null && ! s . isClosed ( ) && s . isConnected ( ) && ! s . isInputShutdown ( ) && ! s . isOutputShutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( name == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; if ( name . isEmpty ( ) ) throw new OCommandExecutionException ( \"Syntax Error. You must specify a function name: \" + getSyntax ( ) ) ; if ( code == null || code . isEmpty ( ) ) throw new OCommandExecutionException ( \"Syntax Error. You must specify the function code: \" + getSyntax ( ) ) ; ODatabaseDocument database = getDatabase ( ) ; final OFunction f = database . getMetadata ( ) . getFunctionLibrary ( ) . createFunction ( name ) ; f . setCode ( code ) ; f . setIdempotent ( idempotent ) ; if ( parameters != null ) f . setParameters ( parameters ) ; if ( language != null ) f . setLanguage ( language ) ; f . save ( ) ; return f . getId ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge short value from two byte buffer . First byte of short will be extracted from first byte buffer and second from second one . [CODESPLIT] public static short mergeShortFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { short result = 0 ; result = ( short ) ( result | ( buffer . get ( ) & MASK ) ) ; result = ( short ) ( result << SIZE_OF_BYTE_IN_BITS ) ; result = ( short ) ( result | ( buffer1 . get ( ) & MASK ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge int value from two byte buffer . First bytes of int will be extracted from first byte buffer and second from second one . How many bytes will be read from first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static int mergeIntFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { int result = 0 ; final int remaining = buffer . remaining ( ) ; for ( int i = 0 ; i < remaining ; ++ i ) { result = result | ( buffer . get ( ) & MASK ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } for ( int i = 0 ; i < SIZE_OF_INT - remaining - 1 ; ++ i ) { result = result | ( buffer1 . get ( ) & MASK ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } result = result | ( buffer1 . get ( ) & MASK ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge long value from two byte buffer . First bytes of long will be extracted from first byte buffer and second from second one . How many bytes will be read from first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static long mergeLongFromBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 ) { long result = 0 ; final int remaining = buffer . remaining ( ) ; for ( int i = 0 ; i < remaining ; ++ i ) { result = result | ( MASK & buffer . get ( ) ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } for ( int i = 0 ; i < SIZE_OF_LONG - remaining - 1 ; ++ i ) { result = result | ( MASK & buffer1 . get ( ) ) ; result = result << SIZE_OF_BYTE_IN_BITS ; } result = result | ( MASK & buffer1 . get ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split short value into two byte buffer . First byte of short will be written to first byte buffer and second to second one . [CODESPLIT] public static void splitShortToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final short iValue ) { buffer . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS ) ) ) ; buffer1 . put ( ( byte ) ( MASK & iValue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split int value into two byte buffer . First byte of int will be written to first byte buffer and second to second one . How many bytes will be written to first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static void splitIntToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final int iValue ) { final int remaining = buffer . remaining ( ) ; int i ; for ( i = 0 ; i < remaining ; ++ i ) { buffer . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_INT - i - 1 ) ) ) ) ; } for ( int j = 0 ; j < SIZE_OF_INT - remaining ; ++ j ) { buffer1 . put ( ( byte ) ( MASK & ( iValue >>> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_INT - i - j - 1 ) ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split long value into two byte buffer . First byte of long will be written to first byte buffer and second to second one . How many bytes will be written to first buffer determines based on <code > buffer . remaining () < / code > value [CODESPLIT] public static void splitLongToBuffers ( final ByteBuffer buffer , final ByteBuffer buffer1 , final long iValue ) { final int remaining = buffer . remaining ( ) ; int i ; for ( i = 0 ; i < remaining ; ++ i ) { buffer . put ( ( byte ) ( iValue >> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_LONG - i - 1 ) ) ) ; } for ( int j = 0 ; j < SIZE_OF_LONG - remaining ; ++ j ) { buffer1 . put ( ( byte ) ( iValue >> SIZE_OF_BYTE_IN_BITS * ( SIZE_OF_LONG - i - j - 1 ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the CREATE PROPERTY . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( type == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocument database = getDatabase ( ) ; final OClassEmbedded sourceClass = ( OClassEmbedded ) database . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( sourceClass == null ) throw new OCommandExecutionException ( \"Source class '\" + className + \"' not found\" ) ; OPropertyImpl prop = ( OPropertyImpl ) sourceClass . getProperty ( fieldName ) ; if ( prop != null ) { if ( ifNotExists ) { return sourceClass . properties ( ) . size ( ) ; } throw new OCommandExecutionException ( \"Property '\" + className + \".\" + fieldName + \"' already exists. Remove it before to retry.\" ) ; } // CREATE THE PROPERTY\r OClass linkedClass = null ; OType linkedType = null ; if ( linked != null ) { // FIRST SEARCH BETWEEN CLASSES\r linkedClass = database . getMetadata ( ) . getSchema ( ) . getClass ( linked ) ; if ( linkedClass == null ) // NOT FOUND: SEARCH BETWEEN TYPES\r linkedType = OType . valueOf ( linked . toUpperCase ( Locale . ENGLISH ) ) ; } // CREATE IT LOCALLY\r OPropertyImpl internalProp = sourceClass . addPropertyInternal ( fieldName , type , linkedType , linkedClass , unsafe ) ; if ( readonly ) { internalProp . setReadonly ( true ) ; } if ( mandatory ) { internalProp . setMandatory ( true ) ; } if ( notnull ) { internalProp . setNotNull ( true ) ; } if ( max != null ) { internalProp . setMax ( max ) ; } if ( min != null ) { internalProp . setMin ( min ) ; } if ( defaultValue != null ) { internalProp . setDefaultValue ( defaultValue ) ; } return sourceClass . properties ( ) . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the ALTER CLASS . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( attribute == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final List < OCluster > clusters = getClusters ( ) ; if ( clusters . isEmpty ( ) ) throw new OCommandExecutionException ( \"Cluster '\" + clusterName + \"' not found\" ) ; Object result = null ; for ( OCluster cluster : getClusters ( ) ) { if ( clusterId > - 1 && clusterName . equals ( String . valueOf ( clusterId ) ) ) { clusterName = cluster . getName ( ) ; } else { clusterId = cluster . getId ( ) ; } try { if ( attribute == ATTRIBUTES . STATUS && OStorageClusterConfiguration . STATUS . OFFLINE . toString ( ) . equalsIgnoreCase ( value ) ) // REMOVE CACHE OF COMMAND RESULTS IF ACTIVE\r getDatabase ( ) . getMetadata ( ) . getCommandCache ( ) . invalidateResultsOfCluster ( clusterName ) ; if ( attribute == ATTRIBUTES . NAME ) // REMOVE CACHE OF COMMAND RESULTS IF ACTIVE\r getDatabase ( ) . getMetadata ( ) . getCommandCache ( ) . invalidateResultsOfCluster ( clusterName ) ; result = cluster . set ( attribute , value ) ; } catch ( IOException ioe ) { throw OException . wrapException ( new OCommandExecutionException ( \"Error altering cluster '\" + clusterName + \"'\" ) , ioe ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indexes a value and save the index . Splits the value in single words and index each one . Save of the index is responsibility of the caller . [CODESPLIT] @ Override public OIndexFullText put ( Object key , final OIdentifiable singleValue ) { if ( key == null ) { return this ; } key = getCollatingValue ( key ) ; final Set < String > words = splitIntoWords ( key . toString ( ) ) ; // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT for ( final String word : words ) { acquireSharedLock ( ) ; try { if ( apiVersion == 0 ) { doPutV0 ( singleValue , word ) ; } else if ( apiVersion == 1 ) { doPutV1 ( singleValue , word ) ; } else { throw new IllegalStateException ( \"Invalid API version, \" + apiVersion ) ; } } finally { releaseSharedLock ( ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits passed in key on several words and remove records with keys equals to any item of split result and values equals to passed in value . [CODESPLIT] @ Override public boolean remove ( Object key , final OIdentifiable value ) { if ( key == null ) { return false ; } key = getCollatingValue ( key ) ; final Set < String > words = splitIntoWords ( key . toString ( ) ) ; final OModifiableBoolean removed = new OModifiableBoolean ( false ) ; for ( final String word : words ) { acquireSharedLock ( ) ; try { if ( apiVersion == 0 ) { removeV0 ( value , removed , word ) ; } else if ( apiVersion == 1 ) { removeV1 ( value , removed , word ) ; } else { throw new IllegalStateException ( \"Invalid API version, \" + apiVersion ) ; } } finally { releaseSharedLock ( ) ; } } return removed . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegates to the OQueryExecutor the query execution . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public List < T > run ( final Object ... iArgs ) { final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; if ( database == null ) throw new OQueryParsingException ( \"No database configured\" ) ; ( ( OMetadataInternal ) database . getMetadata ( ) ) . makeThreadLocalSchemaSnapshot ( ) ; try { setParameters ( iArgs ) ; Object o = database . getStorage ( ) . command ( this ) ; if ( o instanceof List ) { return ( List < T > ) o ; } else { return ( List < T > ) Collections . singletonList ( o ) ; } } finally { ( ( OMetadataInternal ) database . getMetadata ( ) ) . clearThreadLocalSchemaSnapshot ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns only the first record if any . [CODESPLIT] public T runFirst ( final Object ... iArgs ) { setLimit ( 1 ) ; final List < T > result = execute ( iArgs ) ; return result != null && ! result . isEmpty ( ) ? result . get ( 0 ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the value stored under the given entry index in this bucket . [CODESPLIT] public OSBTreeValue < V > getValue ( int entryIndex ) { assert isLeaf ; int entryPosition = getIntValue ( entryIndex * OIntegerSerializer . INT_SIZE + positionsArrayOffset ) ; // skip key if ( encryption == null ) { entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedSize = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE + encryptedSize ; } boolean isLinkValue = getByteValue ( entryPosition ) > 0 ; long link = - 1 ; V value = null ; if ( isLinkValue ) link = deserializeFromDirectMemory ( OLongSerializer . INSTANCE , entryPosition + OByteSerializer . BYTE_SIZE ) ; else value = deserializeFromDirectMemory ( valueSerializer , entryPosition + OByteSerializer . BYTE_SIZE ) ; return new OSBTreeValue <> ( link >= 0 , link , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shrink the file content ( filledUpTo attribute only ) [CODESPLIT] public void shrink ( final long size ) throws IOException { int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { //noinspection resource channel . truncate ( HEADER_SIZE + size ) ; this . size = size ; assert this . size >= 0 ; break ; } finally { releaseWriteLock ( ) ; attempts ++ ; } } catch ( final IOException e ) { OLogManager . instance ( ) . error ( this , \"Error during file shrink for file '\" + getName ( ) + \"' \" + attempts + \"-th attempt\" , e ) ; reopenFile ( attempts , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the file . [CODESPLIT] public void create ( ) throws IOException { acquireWriteLock ( ) ; try { acquireExclusiveAccess ( ) ; openChannel ( ) ; init ( ) ; setVersion ( OFileClassic . CURRENT_VERSION ) ; version = OFileClassic . CURRENT_VERSION ; initAllocationMode ( ) ; } finally { releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ALWAYS ADD THE HEADER SIZE BECAUSE ON THIS TYPE IS ALWAYS NEEDED [CODESPLIT] private long checkRegions ( final long iOffset , final long iLength ) { acquireReadLock ( ) ; try { if ( iOffset < 0 || iOffset + iLength > size ) { throw new OIOException ( \"You cannot access outside the file size (\" + size + \" bytes). You have requested portion \" + iOffset + \"-\" + ( iOffset + iLength ) + \" bytes. File: \" + this ) ; } return iOffset + HEADER_SIZE ; } finally { releaseReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void open ( ) { acquireWriteLock ( ) ; try { if ( ! Files . exists ( osFile ) ) { throw new FileNotFoundException ( \"File: \" + osFile ) ; } acquireExclusiveAccess ( ) ; openChannel ( ) ; init ( ) ; OLogManager . instance ( ) . debug ( this , \"Checking file integrity of \" + osFile . getFileName ( ) + \"...\" ) ; if ( version < CURRENT_VERSION ) { setVersion ( CURRENT_VERSION ) ; version = CURRENT_VERSION ; } initAllocationMode ( ) ; } catch ( final IOException e ) { throw OException . wrapException ( new OIOException ( \"Error during file open\" ) , e ) ; } finally { releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void close ( ) { int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { if ( channel != null && channel . isOpen ( ) ) { channel . close ( ) ; channel = null ; } if ( frnd != null ) { frnd . close ( ) ; frnd = null ; } closeFD ( ) ; } finally { releaseWriteLock ( ) ; attempts ++ ; } releaseExclusiveAccess ( ) ; break ; } catch ( final IOException ioe ) { OLogManager . instance ( ) . error ( this , \"Error during closing of file '\" + getName ( ) + \"' \" + attempts + \"-th attempt\" , ioe ) ; try { reopenFile ( attempts , ioe ) ; } catch ( final IOException e ) { throw OException . wrapException ( new OIOException ( \"Error during file close\" ) , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void delete ( ) throws IOException { int attempts = 0 ; while ( true ) { try { acquireWriteLock ( ) ; try { close ( ) ; if ( osFile != null ) { Files . deleteIfExists ( osFile ) ; } } finally { releaseWriteLock ( ) ; attempts ++ ; } break ; } catch ( final IOException ioe ) { OLogManager . instance ( ) . error ( this , \"Error during deletion of file '\" + getName ( ) + \"' \" + attempts + \"-th attempt\" , ioe ) ; reopenFile ( attempts , ioe ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the file content with the content of the provided file . [CODESPLIT] public void replaceContentWith ( final Path newContentFile ) throws IOException { acquireWriteLock ( ) ; try { close ( ) ; Files . copy ( newContentFile , osFile , StandardCopyOption . REPLACE_EXISTING ) ; open ( ) ; } finally { releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command remotely and get the results back . [CODESPLIT] public Object command ( final OCommandRequestText iCommand ) { final boolean live = iCommand instanceof OLiveQuery ; final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; final boolean asynch = iCommand instanceof OCommandRequestAsynch && ( ( OCommandRequestAsynch ) iCommand ) . isAsynchronous ( ) ; OCommandRequest request = new OCommandRequest ( database , asynch , iCommand , live ) ; OCommandResponse response = networkOperation ( request , \"Error on executing command: \" + iCommand ) ; return response . getResult ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ends the request and unlock the write lock [CODESPLIT] public void endRequest ( final OChannelBinaryAsynchClient iNetwork ) throws IOException { if ( iNetwork == null ) return ; iNetwork . flush ( ) ; iNetwork . releaseWriteLock ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the URLs . Multiple URLs must be separated by semicolon ( ; ) [CODESPLIT] protected void parseServerURLs ( ) { String lastHost = null ; int dbPos = url . indexOf ( ' ' ) ; if ( dbPos == - 1 ) { // SHORT FORM addHost ( url ) ; lastHost = url ; name = url ; } else { name = url . substring ( url . lastIndexOf ( \"/\" ) + 1 ) ; for ( String host : url . substring ( 0 , dbPos ) . split ( ADDRESS_SEPARATOR ) ) { lastHost = host ; addHost ( host ) ; } } synchronized ( serverURLs ) { if ( serverURLs . size ( ) == 1 && getClientConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . NETWORK_BINARY_DNS_LOADBALANCING_ENABLED ) ) { // LOOK FOR LOAD BALANCING DNS TXT RECORD final String primaryServer = lastHost ; OLogManager . instance ( ) . debug ( this , \"Retrieving URLs from DNS '%s' (timeout=%d)...\" , primaryServer , getClientConfiguration ( ) . getValueAsInteger ( OGlobalConfiguration . NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT ) ) ; try { final Hashtable < String , String > env = new Hashtable < String , String > ( ) ; env . put ( \"java.naming.factory.initial\" , \"com.sun.jndi.dns.DnsContextFactory\" ) ; env . put ( \"com.sun.jndi.ldap.connect.timeout\" , getClientConfiguration ( ) . getValueAsString ( OGlobalConfiguration . NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT ) ) ; final DirContext ictx = new InitialDirContext ( env ) ; final String hostName = ! primaryServer . contains ( \":\" ) ? primaryServer : primaryServer . substring ( 0 , primaryServer . indexOf ( \":\" ) ) ; final Attributes attrs = ictx . getAttributes ( hostName , new String [ ] { \"TXT\" } ) ; final Attribute attr = attrs . get ( \"TXT\" ) ; if ( attr != null ) { for ( int i = 0 ; i < attr . size ( ) ; ++ i ) { String configuration = ( String ) attr . get ( i ) ; if ( configuration . startsWith ( \"\\\"\" ) ) configuration = configuration . substring ( 1 , configuration . length ( ) - 1 ) ; if ( configuration != null ) { final String [ ] parts = configuration . split ( \" \" ) ; List < String > toAdd = new ArrayList <> ( ) ; for ( String part : parts ) { if ( part . startsWith ( \"s=\" ) ) { toAdd . add ( part . substring ( \"s=\" . length ( ) ) ) ; } } if ( toAdd . size ( ) > 0 ) { serverURLs . clear ( ) ; for ( String host : toAdd ) addHost ( host ) ; } } } } } catch ( NamingException ignore ) { } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the remote server with port . [CODESPLIT] protected String addHost ( String host ) { if ( host . startsWith ( LOCALHOST ) ) host = LOCAL_IP + host . substring ( \"localhost\" . length ( ) ) ; if ( host . contains ( \"/\" ) ) host = host . substring ( 0 , host . indexOf ( \"/\" ) ) ; // REGISTER THE REMOTE SERVER+PORT if ( ! host . contains ( \":\" ) ) host += \":\" + ( clientConfiguration . getValueAsBoolean ( OGlobalConfiguration . CLIENT_USE_SSL ) ? getDefaultSSLPort ( ) : getDefaultPort ( ) ) ; else if ( host . split ( \":\" ) . length < 2 || host . split ( \":\" ) [ 1 ] . trim ( ) . length ( ) == 0 ) host += ( clientConfiguration . getValueAsBoolean ( OGlobalConfiguration . CLIENT_USE_SSL ) ? getDefaultSSLPort ( ) : getDefaultPort ( ) ) ; // DISABLED BECAUSE THIS DID NOT ALLOW TO CONNECT TO LOCAL HOST ANYMORE IF THE SERVER IS BOUND TO 127.0.0.1 // CONVERT 127.0.0.1 TO THE PUBLIC IP IF POSSIBLE // if (host.startsWith(LOCAL_IP)) { // try { // final String publicIP = InetAddress.getLocalHost().getHostAddress(); // host = publicIP + host.substring(LOCAL_IP.length()); // } catch (UnknownHostException e) { // // IGNORE IT // } // } synchronized ( serverURLs ) { if ( ! serverURLs . contains ( host ) ) { serverURLs . add ( host ) ; OLogManager . instance ( ) . debug ( this , \"Registered the new available server '%s'\" , host ) ; } } return host ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquire a network channel from the pool . Don t lock the write stream since the connection usage is exclusive . [CODESPLIT] public OChannelBinaryAsynchClient beginRequest ( final OChannelBinaryAsynchClient network , final byte iCommand , OStorageRemoteSession session ) throws IOException { network . beginRequest ( iCommand , session ) ; return network ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Short object , ByteBuffer buffer , Object ... hints ) { buffer . putShort ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Short deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getShortValue ( buffer , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current thread database as a ODatabasePojoAbstract wrapping it where necessary . [CODESPLIT] protected static OObjectDatabaseTx getDatabase ( ) { ODatabaseInternal < ? > databaseOwner = ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getDatabaseOwner ( ) ; if ( databaseOwner instanceof OObjectDatabaseTx ) { return ( OObjectDatabaseTx ) databaseOwner ; } else if ( databaseOwner instanceof ODatabaseDocumentInternal ) { return new OObjectDatabaseTx ( ( ODatabaseDocumentInternal ) databaseOwner ) ; } throw new IllegalStateException ( \"Current database not of expected type\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public String toCreateIndexDDL ( final String indexName , final String indexType , final String engine ) { return createIndexDDLWithFieldType ( indexName , indexType , engine ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a OrientGraph instance passing a configuration . Supported configuration settings are : <table > <tr > <td > <b > Name< / b > < / td > <td > <b > Description< / b > < / td > <td > <b > Default value< / b > < / td > < / tr > <tr > <td > blueprints . orientdb . url< / td > <td > Database URL< / td > <td > - < / td > < / tr > <tr > <td > blueprints . orientdb . username< / td > <td > User name< / td > <td > admin< / td > < / tr > <tr > <td > blueprints . orientdb . password< / td > <td > User password< / td > <td > admin< / td > < / tr > <tr > <td > blueprints . orientdb . saveOriginalIds< / td > <td > Saves the original element IDs by using the property origId . This could be useful on import of graph to preserve original ids< / td > <td > false< / td > < / tr > <tr > <td > blueprints . orientdb . keepInMemoryReferences< / td > <td > Avoid to keep records in memory but only RIDs< / td > <td > false< / td > < / tr > <tr > <td > blueprints . orientdb . useCustomClassesForEdges< / td > <td > Use Edge s label as OrientDB class . If doesn t exist create it under the hood< / td > <td > true< / td > < / tr > <tr > <td > blueprints . orientdb . useCustomClassesForVertex< / td > <td > Use Vertex s label as OrientDB class . If doesn t exist create it under the hood< / td > <td > true< / td > < / tr > <tr > <td > blueprints . orientdb . useVertexFieldsForEdgeLabels< / td > <td > Store the edge relationships in vertex by using the Edge s class . This allow to use multiple fields and make faster traversal by edge s label ( class ) < / td > <td > true< / td > < / tr > <tr > <td > blueprints . orientdb . lightweightEdges< / td > <td > Uses lightweight edges . This avoid to create a physical document per edge . Documents are created only when they have properties< / td > <td > true< / td > < / tr > <tr > <td > blueprints . orientdb . autoScaleEdgeType< / td > <td > Set auto scale of edge type . True means one edge is managed as LINK 2 or more are managed with a LINKBAG< / td > <td > false< / td > < / tr > <tr > <td > blueprints . orientdb . edgeContainerEmbedded2TreeThreshold< / td > <td > Changes the minimum number of edges for edge containers to transform the underlying structure from embedded to tree . Use - 1 to disable transformation< / td > <td > - 1< / td > < / tr > <tr > <td > blueprints . orientdb . edgeContainerTree2EmbeddedThreshold< / td > <td > Changes the minimum number of edges for edge containers to transform the underlying structure from tree to embedded . Use - 1 to disable transformation< / td > <td > - 1< / td > < / tr > < / table > [CODESPLIT] protected void init ( final Configuration configuration ) { final Boolean saveOriginalIds = configuration . getBoolean ( \"blueprints.orientdb.saveOriginalIds\" , null ) ; if ( saveOriginalIds != null ) setSaveOriginalIds ( saveOriginalIds ) ; final Boolean keepInMemoryReferences = configuration . getBoolean ( \"blueprints.orientdb.keepInMemoryReferences\" , null ) ; if ( keepInMemoryReferences != null ) setKeepInMemoryReferences ( keepInMemoryReferences ) ; final Boolean useCustomClassesForEdges = configuration . getBoolean ( \"blueprints.orientdb.useCustomClassesForEdges\" , null ) ; if ( useCustomClassesForEdges != null ) setUseClassForEdgeLabel ( useCustomClassesForEdges ) ; final Boolean useCustomClassesForVertex = configuration . getBoolean ( \"blueprints.orientdb.useCustomClassesForVertex\" , null ) ; if ( useCustomClassesForVertex != null ) setUseClassForVertexLabel ( useCustomClassesForVertex ) ; final Boolean useVertexFieldsForEdgeLabels = configuration . getBoolean ( \"blueprints.orientdb.useVertexFieldsForEdgeLabels\" , null ) ; if ( useVertexFieldsForEdgeLabels != null ) setUseVertexFieldsForEdgeLabels ( useVertexFieldsForEdgeLabels ) ; final Boolean lightweightEdges = configuration . getBoolean ( \"blueprints.orientdb.lightweightEdges\" , null ) ; if ( lightweightEdges != null ) setUseLightweightEdges ( lightweightEdges ) ; final Boolean autoScaleEdgeType = configuration . getBoolean ( \"blueprints.orientdb.autoScaleEdgeType\" , null ) ; if ( autoScaleEdgeType != null ) setAutoScaleEdgeType ( autoScaleEdgeType ) ; final Boolean requireTransaction = configuration . getBoolean ( \"blueprints.orientdb.requireTransaction\" , null ) ; if ( requireTransaction != null ) setRequireTransaction ( requireTransaction ) ; final Boolean txRequiredForSQLGraphOperations = configuration . getBoolean ( \"blueprints.orientdb.txRequiredForSQLGraphOperations\" , null ) ; if ( txRequiredForSQLGraphOperations != null ) setTxRequiredForSQLGraphOperations ( txRequiredForSQLGraphOperations ) ; final Integer maxRetries = configuration . getInt ( \"blueprints.orientdb.maxRetries\" , 50 ) ; if ( maxRetries != null ) setMaxRetries ( maxRetries ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a connection . [CODESPLIT] public OClientConnection connect ( final ONetworkProtocol iProtocol ) { final OClientConnection connection ; connection = new OClientConnection ( connectionSerial . incrementAndGet ( ) , iProtocol ) ; connections . put ( connection . getId ( ) , connection ) ; OLogManager . instance ( ) . config ( this , \"Remote client connected from: \" + connection ) ; OServerPluginHelper . invokeHandlerCallbackOnClientConnection ( iProtocol . getServer ( ) , connection ) ; return connection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a connection . [CODESPLIT] public OClientConnection connect ( final ONetworkProtocol iProtocol , final OClientConnection connection , final byte [ ] tokenBytes , final OTokenHandler handler ) { final OToken token ; try { token = handler . parseBinaryToken ( tokenBytes ) ; } catch ( Exception e ) { throw OException . wrapException ( new OTokenSecurityException ( \"Error on token parsing\" ) , e ) ; } OClientSessions session ; synchronized ( sessions ) { session = new OClientSessions ( tokenBytes , token ) ; sessions . put ( new OHashToken ( tokenBytes ) , session ) ; } connection . setTokenBytes ( tokenBytes ) ; connection . setTokenBased ( true ) ; connection . setToken ( token ) ; session . addConnection ( connection ) ; OLogManager . instance ( ) . config ( this , \"Remote client connected from: \" + connection ) ; OServerPluginHelper . invokeHandlerCallbackOnClientConnection ( iProtocol . getServer ( ) , connection ) ; return connection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the connection by id . [CODESPLIT] public OClientConnection getConnection ( final int iChannelId , ONetworkProtocol protocol ) { // SEARCH THE CONNECTION BY ID OClientConnection connection = connections . get ( iChannelId ) ; if ( connection != null ) connection . setProtocol ( protocol ) ; return connection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the connection by address / port . [CODESPLIT] public OClientConnection getConnection ( final String iAddress ) { for ( OClientConnection conn : connections . values ( ) ) { if ( iAddress . equals ( conn . getRemoteAddress ( ) ) ) return conn ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disconnects and kill the associated network manager . [CODESPLIT] public void kill ( final OClientConnection connection ) { if ( connection != null ) { final ONetworkProtocol protocol = connection . getProtocol ( ) ; try { // INTERRUPT THE NEWTORK MANAGER TOO protocol . interrupt ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error during interruption of binary protocol\" , e ) ; } disconnect ( connection ) ; // KILL THE NETWORK MANAGER TOO protocol . sendShutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interrupt the associated network manager . [CODESPLIT] public void interrupt ( final int iChannelId ) { final OClientConnection connection = connections . get ( iChannelId ) ; if ( connection != null ) { final ONetworkProtocol protocol = connection . getProtocol ( ) ; if ( protocol != null ) // INTERRUPT THE NEWTORK MANAGER protocol . softShutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disconnects a client connections [CODESPLIT] public boolean disconnect ( final int iChannelId ) { OLogManager . instance ( ) . debug ( this , \"Disconnecting connection with id=%d\" , iChannelId ) ; final OClientConnection connection = connections . remove ( iChannelId ) ; if ( connection != null ) { OServerPluginHelper . invokeHandlerCallbackOnClientDisconnection ( server , connection ) ; connection . close ( ) ; removeConnectionFromSession ( connection ) ; // CHECK IF THERE ARE OTHER CONNECTIONS for ( Entry < Integer , OClientConnection > entry : connections . entrySet ( ) ) { if ( entry . getValue ( ) . getProtocol ( ) . equals ( connection . getProtocol ( ) ) ) { OLogManager . instance ( ) . debug ( this , \"Disconnected connection with id=%d but are present other active channels\" , iChannelId ) ; return false ; } } OLogManager . instance ( ) . debug ( this , \"Disconnected connection with id=%d, no other active channels found\" , iChannelId ) ; return true ; } OLogManager . instance ( ) . debug ( this , \"Cannot find connection with id=%d\" , iChannelId ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes the distributed configuration to all the connected clients . [CODESPLIT] public void pushDistribCfg2Clients ( final ODocument iConfig ) { if ( iConfig == null ) return ; final Set < String > pushed = new HashSet < String > ( ) ; for ( OClientConnection c : connections . values ( ) ) { if ( ! c . getData ( ) . supportsLegacyPushMessages ) continue ; try { final String remoteAddress = c . getRemoteAddress ( ) ; if ( pushed . contains ( remoteAddress ) ) // ALREADY SENT: JUMP IT continue ; } catch ( Exception e ) { // SOCKET EXCEPTION SKIP IT continue ; } if ( ! ( c . getProtocol ( ) instanceof ONetworkProtocolBinary ) || c . getData ( ) . getSerializationImpl ( ) == null ) // INVOLVE ONLY BINARY PROTOCOLS continue ; final ONetworkProtocolBinary p = ( ONetworkProtocolBinary ) c . getProtocol ( ) ; final OChannelBinary channel = p . getChannel ( ) ; final ORecordSerializer ser = ORecordSerializerFactory . instance ( ) . getFormat ( c . getData ( ) . getSerializationImpl ( ) ) ; if ( ser == null ) return ; final byte [ ] content = ser . toStream ( iConfig , false ) ; try { // TRY ACQUIRING THE LOCK FOR MAXIMUM 3 SECS TO AVOID TO FREEZE CURRENT THREAD if ( channel . tryAcquireWriteLock ( TIMEOUT_PUSH ) ) { try { channel . writeByte ( OChannelBinaryProtocol . PUSH_DATA ) ; channel . writeInt ( Integer . MIN_VALUE ) ; channel . writeByte ( OChannelBinaryProtocol . REQUEST_PUSH_DISTRIB_CONFIG ) ; channel . writeBytes ( content ) ; channel . flush ( ) ; pushed . add ( c . getRemoteAddress ( ) ) ; OLogManager . instance ( ) . debug ( this , \"Sent updated cluster configuration to the remote client %s\" , c . getRemoteAddress ( ) ) ; } finally { channel . releaseWriteLock ( ) ; } } else { OLogManager . instance ( ) . info ( this , \"Timeout on sending updated cluster configuration to the remote client %s\" , c . getRemoteAddress ( ) ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . warn ( this , \"Cannot push cluster configuration to the client %s\" , e , c . getRemoteAddress ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for internal use only [CODESPLIT] public boolean swap ( int index , OIdentifiable newValue ) { EntriesIterator iter = ( EntriesIterator ) rawIterator ( ) ; int currIndex = 0 ; while ( iter . hasNext ( ) ) { iter . next ( ) ; if ( index == currIndex ) { iter . swapValueOnCurrent ( newValue ) ; return true ; } currIndex ++ ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the transaction and releases all the acquired locks . [CODESPLIT] @ Override public void close ( ) { for ( Map . Entry < ORID , LockedRecordMetadata > lock : locks . entrySet ( ) ) { try { final LockedRecordMetadata lockedRecordMetadata = lock . getValue ( ) ; if ( lockedRecordMetadata . strategy . equals ( OStorage . LOCKING_STRATEGY . EXCLUSIVE_LOCK ) ) { ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) . getUnderlying ( ) ) . releaseWriteLock ( lock . getKey ( ) ) ; } else if ( lockedRecordMetadata . strategy . equals ( OStorage . LOCKING_STRATEGY . SHARED_LOCK ) ) { ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) . getUnderlying ( ) ) . releaseReadLock ( lock . getKey ( ) ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . debug ( this , \"Error on releasing lock against record \" + lock . getKey ( ) , e ) ; } } locks . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles vertex consistency after an UPDATE EDGE [CODESPLIT] private void handleUpdateEdge ( ODocument record ) { Object currentOut = record . field ( \"out\" ) ; Object currentIn = record . field ( \"in\" ) ; Object prevOut = record . getOriginalValue ( \"out\" ) ; Object prevIn = record . getOriginalValue ( \"in\" ) ; // to manage subqueries if ( currentOut instanceof Collection && ( ( Collection ) currentOut ) . size ( ) == 1 ) { currentOut = ( ( Collection ) currentOut ) . iterator ( ) . next ( ) ; record . setProperty ( \"out\" , currentOut ) ; } if ( currentIn instanceof Collection && ( ( Collection ) currentIn ) . size ( ) == 1 ) { currentIn = ( ( Collection ) currentIn ) . iterator ( ) . next ( ) ; record . setProperty ( \"in\" , currentIn ) ; } validateOutInForEdge ( record , currentOut , currentIn ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevIn , ( OIdentifiable ) currentIn , \"in\" ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevOut , ( OIdentifiable ) currentOut , \"out\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "updates old and new vertices connected to an edge after out / in update on the edge itself [CODESPLIT] private void changeVertexEdgePointer ( ODocument edge , OIdentifiable prevVertex , OIdentifiable currentVertex , String direction ) { if ( prevVertex != null && ! prevVertex . equals ( currentVertex ) ) { String edgeClassName = edge . getClassName ( ) ; if ( edgeClassName . equalsIgnoreCase ( \"E\" ) ) { edgeClassName = \"\" ; } String vertexFieldName = direction + \"_\" + edgeClassName ; ODocument prevOutDoc = ( ( OIdentifiable ) prevVertex ) . getRecord ( ) ; ORidBag prevBag = prevOutDoc . field ( vertexFieldName ) ; if ( prevBag != null ) { prevBag . remove ( edge ) ; prevOutDoc . save ( ) ; } ODocument currentVertexDoc = ( ( OIdentifiable ) currentVertex ) . getRecord ( ) ; ORidBag currentBag = currentVertexDoc . field ( vertexFieldName ) ; if ( currentBag == null ) { currentBag = new ORidBag ( ) ; currentVertexDoc . field ( vertexFieldName , currentBag ) ; } currentBag . add ( edge ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks if an object is an OIdentifiable and an instance of a particular ( schema ) class [CODESPLIT] private boolean isRecordInstanceOf ( Object iRecord , String orientClass ) { if ( iRecord == null ) { return false ; } if ( ! ( iRecord instanceof OIdentifiable ) ) { return false ; } ODocument record = ( ( OIdentifiable ) iRecord ) . getRecord ( ) ; if ( iRecord == null ) { return false ; } return ( record . getSchemaClass ( ) . isSubClassOf ( orientClass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Character object , ByteBuffer buffer , Object ... hints ) { buffer . putChar ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans all classes accessible from the context class loader which belong to the given package and subpackages . [CODESPLIT] public synchronized void generateSchema ( final String iPackageName , final ClassLoader iClassLoader ) { OLogManager . instance ( ) . debug ( this , \"Generating schema inside package: %s\" , iPackageName ) ; List < Class < ? > > classes = null ; try { classes = OReflectionHelper . getClassesFor ( iPackageName , iClassLoader ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( \"Classes cannot be loaded during schema generation\" ) , e ) ; } for ( Class < ? > c : classes ) { generateSchema ( c ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate / updates the SchemaClass and properties from given Class<? > . [CODESPLIT] public synchronized void generateSchema ( final Class < ? > iClass , ODatabaseDocument database ) { if ( iClass == null || iClass . isInterface ( ) || iClass . isPrimitive ( ) || iClass . isEnum ( ) || iClass . isAnonymousClass ( ) ) return ; OObjectEntitySerializer . registerClass ( iClass ) ; OClass schema = database . getMetadata ( ) . getSchema ( ) . getClass ( iClass ) ; if ( schema == null ) { generateOClass ( iClass , database ) ; } List < String > fields = OObjectEntitySerializer . getClassFields ( iClass ) ; if ( fields != null ) for ( String field : fields ) { if ( schema . existsProperty ( field ) ) continue ; if ( OObjectEntitySerializer . isVersionField ( iClass , field ) || OObjectEntitySerializer . isIdField ( iClass , field ) ) continue ; Field f = OObjectEntitySerializer . getField ( field , iClass ) ; if ( f . getType ( ) . equals ( Object . class ) || f . getType ( ) . equals ( ODocument . class ) || OBlob . class . isAssignableFrom ( f . getType ( ) ) ) { continue ; } OType t = OObjectEntitySerializer . getTypeByClass ( iClass , field , f ) ; if ( t == OType . CUSTOM ) { OEntityManager entityManager = OEntityManager . getEntityManagerByDatabaseURL ( database . getURL ( ) ) ; // if the target type is registered as entity, it should be linked instead of custom/serialized if ( entityManager . getEntityClass ( f . getType ( ) . getSimpleName ( ) ) != null ) { t = OType . LINK ; } } if ( t == null ) { if ( f . getType ( ) . isEnum ( ) ) t = OType . STRING ; else { t = OType . LINK ; } } switch ( t ) { case LINK : Class < ? > linkedClazz = OObjectEntitySerializer . getSpecifiedLinkedType ( f ) ; if ( linkedClazz == null ) linkedClazz = f . getType ( ) ; generateLinkProperty ( database , schema , field , t , linkedClazz ) ; break ; case LINKLIST : case LINKMAP : case LINKSET : linkedClazz = OObjectEntitySerializer . getSpecifiedMultiLinkedType ( f ) ; if ( linkedClazz == null ) linkedClazz = OReflectionHelper . getGenericMultivalueType ( f ) ; if ( linkedClazz != null ) generateLinkProperty ( database , schema , field , t , linkedClazz ) ; break ; case EMBEDDED : linkedClazz = f . getType ( ) ; if ( linkedClazz == null || linkedClazz . equals ( Object . class ) || linkedClazz . equals ( ODocument . class ) || OBlob . class . isAssignableFrom ( f . getType ( ) ) ) { continue ; } else { generateLinkProperty ( database , schema , field , t , linkedClazz ) ; } break ; case EMBEDDEDLIST : case EMBEDDEDSET : case EMBEDDEDMAP : linkedClazz = OReflectionHelper . getGenericMultivalueType ( f ) ; if ( linkedClazz == null || linkedClazz . equals ( Object . class ) || linkedClazz . equals ( ODocument . class ) || OBlob . class . isAssignableFrom ( f . getType ( ) ) ) { continue ; } else { if ( OReflectionHelper . isJavaType ( linkedClazz ) ) { schema . createProperty ( field , t , OType . getTypeByClass ( linkedClazz ) ) ; } else if ( linkedClazz . isEnum ( ) ) { schema . createProperty ( field , t , OType . STRING ) ; } else { generateLinkProperty ( database , schema , field , t , linkedClazz ) ; } } break ; default : schema . createProperty ( field , t ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if all registered entities has schema generated if not it generates it [CODESPLIT] public synchronized void synchronizeSchema ( ) { OObjectDatabaseTx database = ( ( OObjectDatabaseTx ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getDatabaseOwner ( ) ) ; Collection < Class < ? > > registeredEntities = database . getEntityManager ( ) . getRegisteredEntities ( ) ; boolean automaticSchemaGeneration = database . isAutomaticSchemaGeneration ( ) ; boolean reloadSchema = false ; for ( Class < ? > iClass : registeredEntities ) { if ( Proxy . class . isAssignableFrom ( iClass ) || iClass . isEnum ( ) || OReflectionHelper . isJavaType ( iClass ) || iClass . isAnonymousClass ( ) ) return ; if ( ! database . getMetadata ( ) . getSchema ( ) . existsClass ( iClass . getSimpleName ( ) ) ) { database . getMetadata ( ) . getSchema ( ) . createClass ( iClass . getSimpleName ( ) ) ; reloadSchema = true ; } for ( Class < ? > currentClass = iClass ; currentClass != Object . class ; ) { if ( automaticSchemaGeneration && ! currentClass . equals ( Object . class ) && ! currentClass . equals ( ODocument . class ) ) { ( ( OSchemaProxyObject ) database . getMetadata ( ) . getSchema ( ) ) . generateSchema ( currentClass , database . getUnderlying ( ) ) ; } String iClassName = currentClass . getSimpleName ( ) ; currentClass = currentClass . getSuperclass ( ) ; if ( currentClass == null || currentClass . equals ( ODocument . class ) ) // POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER // ODOCUMENT FIELDS currentClass = Object . class ; if ( database != null && ! database . isClosed ( ) && ! currentClass . equals ( Object . class ) ) { OClass oSuperClass ; OClass currentOClass = database . getMetadata ( ) . getSchema ( ) . getClass ( iClassName ) ; if ( ! database . getMetadata ( ) . getSchema ( ) . existsClass ( currentClass . getSimpleName ( ) ) ) { oSuperClass = database . getMetadata ( ) . getSchema ( ) . createClass ( currentClass . getSimpleName ( ) ) ; reloadSchema = true ; } else { oSuperClass = database . getMetadata ( ) . getSchema ( ) . getClass ( currentClass . getSimpleName ( ) ) ; reloadSchema = true ; } if ( ! currentOClass . getSuperClasses ( ) . contains ( oSuperClass ) ) { currentOClass . setSuperClasses ( Arrays . asList ( oSuperClass ) ) ; reloadSchema = true ; } } } } if ( database != null && ! database . isClosed ( ) && reloadSchema ) { database . getMetadata ( ) . getSchema ( ) . reload ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the metric metadata . [CODESPLIT] protected void updateMetadata ( final String iName , final String iDescription , final METRIC_TYPE iType ) { if ( iDescription != null && dictionary . putIfAbsent ( iName , iDescription ) == null ) types . put ( iName , iType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the element at the current position and move forward the cursor to the next position available . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public REC next ( ) { checkDirection ( true ) ; if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD\r return ( REC ) currentRecord ; } finally { currentRecord = null ; } ORecord record ; // MOVE FORWARD IN THE CURRENT CLUSTER\r while ( hasNext ( ) ) { if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD\r return ( REC ) currentRecord ; } finally { currentRecord = null ; } record = getTransactionEntry ( ) ; if ( record == null ) record = readCurrentRecord ( null , + 1 ) ; if ( record != null ) // FOUND\r if ( include ( record ) ) return ( REC ) record ; } record = getTransactionEntry ( ) ; if ( record != null ) return ( REC ) record ; throw new NoSuchElementException ( \"Direction: forward, last position was: \" + current + \", range: \" + beginRange + \"-\" + endRange ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the element at the current position and move backward the cursor to the previous position available . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public REC previous ( ) { checkDirection ( false ) ; if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD\r return ( REC ) currentRecord ; } finally { currentRecord = null ; } ORecord record = getRecord ( ) ; // MOVE BACKWARD IN THE CURRENT CLUSTER\r while ( hasPrevious ( ) ) { if ( currentRecord != null ) try { // RETURN LAST LOADED RECORD\r return ( REC ) currentRecord ; } finally { currentRecord = null ; } record = getTransactionEntry ( ) ; if ( record == null ) record = readCurrentRecord ( null , - 1 ) ; if ( record != null ) // FOUND\r if ( include ( record ) ) return ( REC ) record ; } record = getTransactionEntry ( ) ; if ( record != null ) return ( REC ) record ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move the iterator to the begin of the range . If no range was specified move to the first record of the cluster . [CODESPLIT] @ Override public ORecordIteratorClusters < REC > begin ( ) { if ( clusterIds . length == 0 ) return this ; browsedRecords = 0 ; currentClusterIdx = 0 ; current . setClusterId ( clusterIds [ currentClusterIdx ] ) ; updateClusterRange ( ) ; resetCurrentPosition ( ) ; nextPosition ( ) ; final ORecord record = getRecord ( ) ; currentRecord = readCurrentRecord ( record , 0 ) ; if ( currentRecord != null && ! include ( currentRecord ) ) { currentRecord = null ; hasNext ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move the iterator to the end of the range . If no range was specified move to the last record of the cluster . [CODESPLIT] @ Override public ORecordIteratorClusters < REC > last ( ) { if ( clusterIds . length == 0 ) return this ; browsedRecords = 0 ; currentClusterIdx = clusterIds . length - 1 ; updateClusterRange ( ) ; current . setClusterId ( clusterIds [ currentClusterIdx ] ) ; resetCurrentPosition ( ) ; prevPosition ( ) ; final ORecord record = getRecord ( ) ; currentRecord = readCurrentRecord ( record , 0 ) ; if ( currentRecord != null && ! include ( currentRecord ) ) { currentRecord = null ; hasPrevious ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell to the iterator that the upper limit must be checked at every cycle . Useful when concurrent deletes or additions change the size of the cluster while you re browsing it . Default is false . [CODESPLIT] @ Override public ORecordIteratorClusters < REC > setLiveUpdated ( boolean iLiveUpdated ) { super . setLiveUpdated ( iLiveUpdated ) ; if ( iLiveUpdated ) { firstClusterEntry = 0 ; lastClusterEntry = Long . MAX_VALUE ; } else { updateClusterRange ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clazz == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; return OGraphCommandExecutorSQLFactory . runInConfiguredTxMode ( new OGraphCommandExecutorSQLFactory . GraphCallBack < List < Object > > ( ) { @ Override public List < Object > call ( OrientBaseGraph graph ) { final Set < OIdentifiable > fromIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( graph . getRawGraph ( ) , from , context , iArgs ) ; final Set < OIdentifiable > toIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( graph . getRawGraph ( ) , to , context , iArgs ) ; // CREATE EDGES\r final List < Object > edges = new ArrayList < Object > ( ) ; for ( OIdentifiable from : fromIds ) { final OrientVertex fromVertex = graph . getVertex ( from ) ; if ( fromVertex == null ) throw new OCommandExecutionException ( \"Source vertex '\" + from + \"' not exists\" ) ; for ( OIdentifiable to : toIds ) { final OrientVertex toVertex ; if ( from . equals ( to ) ) { toVertex = fromVertex ; } else { toVertex = graph . getVertex ( to ) ; } if ( fields != null ) // EVALUATE FIELDS\r for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) { f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } else if ( f . getValue ( ) instanceof OSQLFilterItem ) { f . setValue ( ( ( OSQLFilterItem ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } } OrientEdge edge = null ; if ( content != null ) { if ( fields != null ) // MERGE CONTENT WITH FIELDS\r fields . addAll ( OPair . convertFromMap ( content . toMap ( ) ) ) ; else fields = OPair . convertFromMap ( content . toMap ( ) ) ; } edge = fromVertex . addEdge ( null , toVertex , edgeLabel , clusterName , fields ) ; if ( fields != null && ! fields . isEmpty ( ) ) { if ( edge . isLightweight ( ) ) edge . convertToDocument ( ) ; OSQLHelper . bindParameters ( edge . getRecord ( ) , fields , new OCommandParameters ( iArgs ) , context ) ; } edge . save ( clusterName ) ; edges . add ( edge ) ; if ( batch > 0 && edges . size ( ) % batch == 0 ) { graph . commit ( ) ; graph . begin ( ) ; } } } if ( edges . isEmpty ( ) ) { if ( fromIds . isEmpty ( ) ) throw new OCommandExecutionException ( \"No edge has been created because no source vertices\" ) ; else if ( toIds . isEmpty ( ) ) throw new OCommandExecutionException ( \"No edge has been created because no target vertices\" ) ; throw new OCommandExecutionException ( \"No edge has been created between \" + fromIds + \" and \" + toIds ) ; } return edges ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next character from the input stream . Handles Unicode decoding . [CODESPLIT] public int nextChar ( ) throws IOException { if ( missedChar != null ) { // RETURNS THE PREVIOUS PARSED CHAR\r c = missedChar . charValue ( ) ; missedChar = null ; } else { int read = in . read ( ) ; if ( read == - 1 ) return - 1 ; c = ( char ) read ; if ( c == ' ' ) { read = in . read ( ) ; if ( read == - 1 ) return - 1 ; char c2 = ( char ) read ; if ( c2 == ' ' ) { // DECODE UNICODE CHAR\r final StringBuilder buff = new StringBuilder ( 8 ) ; for ( int i = 0 ; i < 4 ; ++ i ) { read = in . read ( ) ; if ( read == - 1 ) return - 1 ; buff . append ( ( char ) read ) ; } cursor += 6 ; return ( char ) Integer . parseInt ( buff . toString ( ) , 16 ) ; } else { // REMEMBER THE CURRENT CHAR TO RETURN NEXT TIME\r missedChar = c2 ; } } } cursor ++ ; if ( c == NEW_LINE ) { ++ lineNumber ; columnNumber = 0 ; } else ++ columnNumber ; return ( char ) c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the FIND REFERENCES . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( recordIds . isEmpty ( ) && subQuery == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; if ( subQuery != null ) { final List < OIdentifiable > result = new OCommandSQL ( subQuery . toString ( ) ) . execute ( ) ; for ( OIdentifiable id : result ) recordIds . ( id . getIdentity ( ) ) ; } return OFindReferenceHelper . findReferences ( recordIds , classList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Legacy Protocol < 37 [CODESPLIT] private static OBinaryRequest < ? extends OBinaryResponse > createRequest ( int requestType ) { switch ( requestType ) { case OChannelBinaryProtocol . REQUEST_DB_OPEN : return new OOpenRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONNECT : return new OConnectRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_REOPEN : return new OReopenRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SHUTDOWN : return new OShutdownRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_LIST : return new OListDatabasesRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SERVER_INFO : return new OServerInfoRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELOAD : return new OReloadRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CREATE : return new OCreateDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CLOSE : return new OCloseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_EXIST : return new OExistsDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_DROP : return new ODropDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_SIZE : return new OGetSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_COUNTRECORDS : return new OCountRecordsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER : return new ODistributedStatusRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_COUNT : return new OCountRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DATARANGE : return new OGetClusterDataRangeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_ADD : return new OAddClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DROP : return new ODropClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_METADATA : return new OGetRecordMetadataRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD : return new OReadRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD_IF_VERSION_NOT_LATEST : return new OReadRecordIfVersionIsNotLatestRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CREATE : return new OCreateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_UPDATE : return new OUpdateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_DELETE : return new ODeleteRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_HIDE : return new OHideRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_HIGHER : return new OHigherPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_CEILING : return new OCeilingPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_LOWER : return new OLowerPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_FLOOR : return new OFloorPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_COMMAND : return new OCommandRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY : return new OQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLOSE_QUERY : return new OCloseQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY_NEXT_PAGE : return new OQueryNextPageRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_COMMIT : return new OCommitRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_GET : return new OGetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_SET : return new OSetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_LIST : return new OListGlobalConfigurationsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_FREEZE : return new OFreezeDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELEASE : return new OReleaseDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CLEAN_OUT : return new OCleanOutRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CREATE_SBTREE_BONSAI : return new OSBTCreateTreeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET : return new OSBTGetRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_FIRST_KEY : return new OSBTFirstKeyRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET_ENTRIES_MAJOR : return new OSBTFetchEntriesMajorRequest <> ( ) ; case OChannelBinaryProtocol . REQUEST_RIDBAG_GET_SIZE : return new OSBTGetRealBagSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_INCREMENTAL_BACKUP : return new OIncrementalBackupRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_IMPORT : return new OImportRequest ( ) ; case OChannelBinaryProtocol . DISTRIBUTED_CONNECT : return new ODistributedConnectRequest ( ) ; default : throw new ODatabaseException ( \"binary protocol command with code: \" + requestType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Protocol 37 [CODESPLIT] public static OBinaryRequest < ? extends OBinaryResponse > createRequest37 ( int requestType ) { switch ( requestType ) { case OChannelBinaryProtocol . SUBSCRIBE_PUSH : return new OSubscribeRequest ( ) ; case OChannelBinaryProtocol . EXPERIMENTAL : return new OExperimentalRequest ( ) ; case OChannelBinaryProtocol . UNSUBSCRIBE_PUSH : return new OUnsubscribeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_FETCH : return new OFetchTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_REBEGIN : return new ORebeginTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_BEGIN : return new OBeginTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_TX_COMMIT : return new OCommit37Request ( ) ; case OChannelBinaryProtocol . REQUEST_TX_ROLLBACK : return new ORollbackTransactionRequest ( ) ; case OChannelBinaryProtocol . REQUEST_BATCH_OPERATIONS : return new OBatchOperationsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_OPEN : return new OOpen37Request ( ) ; case OChannelBinaryProtocol . REQUEST_CONNECT : return new OConnect37Request ( ) ; case OChannelBinaryProtocol . REQUEST_DB_REOPEN : return new OReopenRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SHUTDOWN : return new OShutdownRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_LIST : return new OListDatabasesRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SERVER_INFO : return new OServerInfoRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELOAD : return new OReloadRequest37 ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CREATE : return new OCreateDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_CLOSE : return new OCloseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_EXIST : return new OExistsDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_DROP : return new ODropDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_SIZE : return new OGetSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_COUNTRECORDS : return new OCountRecordsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER : return new ODistributedStatusRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_COUNT : return new OCountRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DATARANGE : return new OGetClusterDataRangeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_ADD : return new OAddClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLUSTER_DROP : return new ODropClusterRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_METADATA : return new OGetRecordMetadataRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD : return new OReadRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_LOAD_IF_VERSION_NOT_LATEST : return new OReadRecordIfVersionIsNotLatestRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CREATE : return new OCreateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_UPDATE : return new OUpdateRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_DELETE : return new ODeleteRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_HIDE : return new OHideRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_HIGHER : return new OHigherPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_CEILING : return new OCeilingPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_LOWER : return new OLowerPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_POSITIONS_FLOOR : return new OFloorPhysicalPositionsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_COMMAND : return new OCommandRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY : return new OQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CLOSE_QUERY : return new OCloseQueryRequest ( ) ; case OChannelBinaryProtocol . REQUEST_QUERY_NEXT_PAGE : return new OQueryNextPageRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_GET : return new OGetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_SET : return new OSetGlobalConfigurationRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CONFIG_LIST : return new OListGlobalConfigurationsRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_FREEZE : return new OFreezeDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_RELEASE : return new OReleaseDatabaseRequest ( ) ; case OChannelBinaryProtocol . REQUEST_RECORD_CLEAN_OUT : return new OCleanOutRecordRequest ( ) ; case OChannelBinaryProtocol . REQUEST_CREATE_SBTREE_BONSAI : return new OSBTCreateTreeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET : return new OSBTGetRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_FIRST_KEY : return new OSBTFirstKeyRequest ( ) ; case OChannelBinaryProtocol . REQUEST_SBTREE_BONSAI_GET_ENTRIES_MAJOR : return new OSBTFetchEntriesMajorRequest <> ( ) ; case OChannelBinaryProtocol . REQUEST_RIDBAG_GET_SIZE : return new OSBTGetRealBagSizeRequest ( ) ; case OChannelBinaryProtocol . REQUEST_INCREMENTAL_BACKUP : return new OIncrementalBackupRequest ( ) ; case OChannelBinaryProtocol . REQUEST_DB_IMPORT : return new OImportRequest ( ) ; case OChannelBinaryProtocol . DISTRIBUTED_CONNECT : return new ODistributedConnectRequest ( ) ; default : throw new ODatabaseException ( \"binary protocol command with code: \" + requestType + \" for protocol version 37\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert fields from text to real value . Supports : String RID Boolean Float Integer and NULL . [CODESPLIT] public static Object parseValue ( String iValue , final OCommandContext iContext ) { return parseValue ( iValue , iContext , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a callback to call in case of error during the asynchronous replication . [CODESPLIT] @ Override public OCommandRequestAbstract onAsyncReplicationError ( final OAsyncReplicationError iCallback ) { if ( iCallback != null ) { onAsyncReplicationError = new OAsyncReplicationError ( ) { int retry = 0 ; @ Override public ACTION onAsyncReplicationError ( Throwable iException , final int iRetry ) { switch ( iCallback . onAsyncReplicationError ( iException , ++ retry ) ) { case RETRY : execute ( ) ; break ; case IGNORE : } return ACTION . IGNORE ; } } ; } else onAsyncReplicationError = null ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a stateless implementations the same instance will be shared on all the storages . [CODESPLIT] public void register ( final Class < ? extends OCompression > compression ) { try { final OCompression tempInstance = compression . newInstance ( ) ; final String name = tempInstance . name ( ) ; if ( compressions . containsKey ( name ) ) throw new IllegalArgumentException ( \"Compression with name '\" + name + \"' was already registered\" ) ; if ( compressionClasses . containsKey ( tempInstance . name ( ) ) ) throw new IllegalArgumentException ( \"Compression with name '\" + name + \"' was already registered\" ) ; compressionClasses . put ( name , compression ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Cannot register storage compression algorithm '%s'\" , e , compression ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects limit of limit of open files . [CODESPLIT] public int getOpenFilesLimit ( boolean verbose , int recommended , int defLimit ) { if ( Platform . isLinux ( ) ) { final OCLibrary . Rlimit rlimit = new OCLibrary . Rlimit ( ) ; final int result = C_LIBRARY . getrlimit ( OCLibrary . RLIMIT_NOFILE , rlimit ) ; if ( result == 0 && rlimit . rlim_cur > 0 ) { if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , \"Detected limit of amount of simultaneously open files is %d, \" + \" limit of open files for disk cache will be set to %d\" , rlimit . rlim_cur , rlimit . rlim_cur / 2 - 512 ) ; } if ( rlimit . rlim_cur < recommended ) { OLogManager . instance ( ) . warnNoDb ( this , \"Value of limit of simultaneously open files is too small, recommended value is %d\" , recommended ) ; } return ( int ) rlimit . rlim_cur / 2 - 512 ; } else { if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , \"Can not detect value of limit of open files.\" ) ; } } } else if ( Platform . isWindows ( ) ) { if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , \"Windows OS is detected, %d limit of open files will be set for the disk cache.\" , recommended ) ; } return recommended ; } if ( verbose ) { OLogManager . instance ( ) . infoNoDb ( this , \"Default limit of open files (%d) will be used.\" , defLimit ) ; } return defLimit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param printSteps Print all steps of discovering of memory limit in the log with { @code INFO } level . [CODESPLIT] public MemoryLimitResult getMemoryLimit ( final boolean printSteps ) { //Perform several steps here: //1. Fetch physical size available on machine //2. Fetch soft limit //3. Fetch cgroup soft limit //4. Fetch cgroup hard limit //5. Return the minimal value from the list of results long memoryLimit = getPhysicalMemorySize ( ) ; boolean insideContainer = false ; if ( printSteps ) { OLogManager . instance ( ) . infoNoDb ( this , \"%d B/%d MB/%d GB of physical memory were detected on machine\" , memoryLimit , convertToMB ( memoryLimit ) , convertToGB ( memoryLimit ) ) ; } if ( Platform . isLinux ( ) ) { final OCLibrary . Rlimit rlimit = new OCLibrary . Rlimit ( ) ; final int result = C_LIBRARY . getrlimit ( OCLibrary . RLIMIT_AS , rlimit ) ; //no errors during the call if ( result == 0 ) { if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , \"Soft memory limit for this process is set to %d B/%d MB/%d GB\" , rlimit . rlim_cur , convertToMB ( rlimit . rlim_cur ) , convertToGB ( rlimit . rlim_cur ) ) ; memoryLimit = updateMemoryLimit ( memoryLimit , rlimit . rlim_cur ) ; if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , \"Hard memory limit for this process is set to %d B/%d MB/%d GB\" , rlimit . rlim_max , convertToMB ( rlimit . rlim_max ) , convertToGB ( rlimit . rlim_max ) ) ; memoryLimit = updateMemoryLimit ( memoryLimit , rlimit . rlim_max ) ; } final String memoryCGroupPath = findMemoryGCGroupPath ( ) ; if ( memoryCGroupPath != null ) { if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , \"Path to 'memory' cgroup is '%s'\" , memoryCGroupPath ) ; final String memoryCGroupRoot = findMemoryGCRoot ( ) ; if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , \"Mounting path for memory cgroup controller is '%s'\" , memoryCGroupRoot ) ; File memoryCGroup = new File ( memoryCGroupRoot , memoryCGroupPath ) ; if ( ! memoryCGroup . exists ( ) ) { if ( printSteps ) OLogManager . instance ( ) . infoNoDb ( this , \"Can not find '%s' path for memory cgroup, it is supposed that \" + \"process is running in container, will try to read root '%s' memory cgroup data\" , memoryCGroup , memoryCGroupRoot ) ; memoryCGroup = new File ( memoryCGroupRoot ) ; insideContainer = true ; } final long softMemoryLimit = fetchCGroupSoftMemoryLimit ( memoryCGroup , printSteps ) ; memoryLimit = updateMemoryLimit ( memoryLimit , softMemoryLimit ) ; final long hardMemoryLimit = fetchCGroupHardMemoryLimit ( memoryCGroup , printSteps ) ; memoryLimit = updateMemoryLimit ( memoryLimit , hardMemoryLimit ) ; } } if ( printSteps ) { if ( memoryLimit > 0 ) OLogManager . instance ( ) . infoNoDb ( this , \"Detected memory limit for current process is %d B/%d MB/%d GB\" , memoryLimit , convertToMB ( memoryLimit ) , convertToGB ( memoryLimit ) ) ; else OLogManager . instance ( ) . infoNoDb ( this , \"Memory limit for current process is not set\" ) ; } if ( memoryLimit <= 0 ) return null ; return new MemoryLimitResult ( memoryLimit , insideContainer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the total size in bytes of the installed physical memory on this machine . Note that on some VMs it s impossible to obtain the physical memory size in this case the return value will { @code - 1 } . [CODESPLIT] private long getPhysicalMemorySize ( ) { long osMemory = - 1 ; try { final MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; final Object attribute = mBeanServer . getAttribute ( new ObjectName ( \"java.lang\" , \"type\" , \"OperatingSystem\" ) , \"TotalPhysicalMemorySize\" ) ; if ( attribute != null ) { if ( attribute instanceof Long ) { osMemory = ( Long ) attribute ; } else { try { osMemory = Long . parseLong ( attribute . toString ( ) ) ; } catch ( final NumberFormatException e ) { if ( ! OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , \"Unable to determine the amount of installed RAM.\" ) ; else OLogManager . instance ( ) . debugNoDb ( OMemory . class , \"Unable to determine the amount of installed RAM.\" , e ) ; } } } else { if ( ! OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , \"Unable to determine the amount of installed RAM.\" ) ; } } catch ( MalformedObjectNameException | AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException e ) { if ( ! OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , \"Unable to determine the amount of installed RAM.\" ) ; else OLogManager . instance ( ) . debugNoDb ( OMemory . class , \"Unable to determine the amount of installed RAM.\" , e ) ; } catch ( final RuntimeException e ) { OLogManager . instance ( ) . warnNoDb ( OMemory . class , \"Unable to determine the amount of installed RAM.\" , e ) ; } return osMemory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tests if current expression is an indexed function AND that function can be used on this target [CODESPLIT] public boolean allowsIndexedFunctionExecutionOnTarget ( OFromClause target , OCommandContext context , OBinaryCompareOperator operator , Object right ) { if ( this . childExpressions . size ( ) != 1 ) { return false ; } return this . childExpressions . get ( 0 ) . allowsIndexedFunctionExecutionOnTarget ( target , context , operator , right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clazz == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; // CREATE VERTEX DOES NOT HAVE TO BE IN TX\r return OGraphCommandExecutorSQLFactory . runWithAnyGraph ( new OGraphCommandExecutorSQLFactory . GraphCallBack < Object > ( ) { @ Override public Object call ( final OrientBaseGraph graph ) { final OrientVertex vertex = graph . addTemporaryVertex ( clazz . getName ( ) ) ; if ( fields != null ) // EVALUATE FIELDS\r for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( vertex . getRecord ( ) , null , context ) ) ; } OSQLHelper . bindParameters ( vertex . getRecord ( ) , fields , new OCommandParameters ( iArgs ) , context ) ; if ( content != null ) vertex . getRecord ( ) . merge ( content , true , false ) ; if ( clusterName != null ) vertex . save ( clusterName ) ; else vertex . save ( ) ; return vertex . getRecord ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static void writeOType ( BytesContainer bytes , int pos , OType type ) { bytes . bytes [ pos ] = ( byte ) type . getId ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move bytes left or right of an offset . [CODESPLIT] public void move ( final int iFrom , final int iPosition ) { if ( iPosition == 0 ) return ; final int to = iFrom + iPosition ; final int size = iPosition > 0 ? buffer . length - to : buffer . length - iFrom ; System . arraycopy ( buffer , iFrom , buffer , to , size ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the used buffer as byte [] . [CODESPLIT] public final byte [ ] toByteArray ( ) { if ( position == buffer . length - 1 ) // 100% USED, RETURN THE FULL BUFFER\r return buffer ; final int pos = position ; final byte [ ] destinBuffer = new byte [ pos ] ; final byte [ ] sourceBuffer = buffer ; if ( pos < NATIVE_COPY_THRESHOLD ) for ( int i = 0 ; i < pos ; ++ i ) destinBuffer [ i ] = sourceBuffer [ i ] ; else System . arraycopy ( sourceBuffer , 0 , destinBuffer , 0 , pos ) ; return destinBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append byte [] to the stream . [CODESPLIT] public int set ( final byte [ ] iContent ) { if ( iContent == null ) return - 1 ; final int begin = position ; assureSpaceFor ( OBinaryProtocol . SIZE_INT + iContent . length ) ; OBinaryProtocol . int2bytes ( iContent . length , buffer , position ) ; position += OBinaryProtocol . SIZE_INT ; write ( iContent , 0 , iContent . length ) ; return begin ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fills the stream from current position writing iLength times the iFiller byte [CODESPLIT] public void fill ( final int iLength , final byte iFiller ) { assureSpaceFor ( iLength ) ; Arrays . fill ( buffer , position , position + iLength , iFiller ) ; position += iLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "executes all the script and returns last statement execution step so that it can be executed from outside [CODESPLIT] public OExecutionStepInternal executeUntilReturn ( ) { if ( steps . size ( ) > 0 ) { lastStep = steps . get ( steps . size ( ) - 1 ) ; } for ( int i = 0 ; i < steps . size ( ) - 1 ; i ++ ) { ScriptLineStep step = steps . get ( i ) ; if ( step . containsReturn ( ) ) { OExecutionStepInternal returnStep = step . executeUntilReturn ( ctx ) ; if ( returnStep != null ) { lastStep = returnStep ; return lastStep ; } } OResultSet lastResult = step . syncPull ( ctx , 100 ) ; while ( lastResult . hasNext ( ) ) { while ( lastResult . hasNext ( ) ) { lastResult . next ( ) ; } lastResult = step . syncPull ( ctx , 100 ) ; } } this . lastStep = steps . get ( steps . size ( ) - 1 ) ; return lastStep ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "executes the whole script and returns last statement ONLY if it s a RETURN otherwise it returns null ; [CODESPLIT] public OExecutionStepInternal executeFull ( ) { for ( int i = 0 ; i < steps . size ( ) ; i ++ ) { ScriptLineStep step = steps . get ( i ) ; if ( step . containsReturn ( ) ) { OExecutionStepInternal returnStep = step . executeUntilReturn ( ctx ) ; if ( returnStep != null ) { return returnStep ; } } OResultSet lastResult = step . syncPull ( ctx , 100 ) ; while ( lastResult . hasNext ( ) ) { while ( lastResult . hasNext ( ) ) { lastResult . next ( ) ; } lastResult = step . syncPull ( ctx , 100 ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the user POJO to a ORecordDocument instance . [CODESPLIT] public static ODocument toStream ( final Object iPojo , final ODocument iRecord , final OEntityManager iEntityManager , final OClass schemaClass , final OUserObject2RecordHandler iObj2RecHandler , final ODatabaseObject db , final boolean iSaveOnlyDirty ) { if ( iSaveOnlyDirty && ! iRecord . isDirty ( ) ) return iRecord ; final long timer = Orient . instance ( ) . getProfiler ( ) . startChrono ( ) ; final Integer identityRecord = System . identityHashCode ( iRecord ) ; if ( OSerializationThreadLocal . INSTANCE . get ( ) . contains ( identityRecord ) ) return iRecord ; OSerializationThreadLocal . INSTANCE . get ( ) . add ( identityRecord ) ; OProperty schemaProperty ; final Class < ? > pojoClass = iPojo . getClass ( ) ; final List < Field > properties = getClassFields ( pojoClass ) ; // CHECK FOR ID BINDING\r final Field idField = fieldIds . get ( pojoClass ) ; if ( idField != null ) { Object id = getFieldValue ( iPojo , idField . getName ( ) ) ; if ( id != null ) { // FOUND\r if ( id instanceof ORecordId ) { ORecordInternal . setIdentity ( iRecord , ( ORecordId ) id ) ; } else if ( id instanceof Number ) { // TREATS AS CLUSTER POSITION\r ( ( ORecordId ) iRecord . getIdentity ( ) ) . setClusterId ( schemaClass . getDefaultClusterId ( ) ) ; ( ( ORecordId ) iRecord . getIdentity ( ) ) . setClusterPosition ( ( ( Number ) id ) . longValue ( ) ) ; } else if ( id instanceof String ) ( ( ORecordId ) iRecord . getIdentity ( ) ) . fromString ( ( String ) id ) ; else if ( id . getClass ( ) . equals ( Object . class ) ) ORecordInternal . setIdentity ( iRecord , ( ORecordId ) id ) ; else OLogManager . instance ( ) . warn ( OObjectSerializerHelper . class , \"@Id field has been declared as %s while the supported are: ORID, Number, String, Object\" , id . getClass ( ) ) ; } } // CHECK FOR VERSION BINDING\r final Field vField = fieldVersions . get ( pojoClass ) ; boolean versionConfigured = false ; if ( vField != null ) { versionConfigured = true ; Object ver = getFieldValue ( iPojo , vField . getName ( ) ) ; final int version = convertVersion ( ver ) ; ORecordInternal . setVersion ( iRecord , version ) ; } if ( db . isMVCC ( ) && ! versionConfigured && db . getTransaction ( ) instanceof OTransactionOptimistic ) throw new OTransactionException ( \"Cannot involve an object of class '\" + pojoClass + \"' in an Optimistic Transaction commit because it does not define @Version or @OVersion and therefore cannot handle MVCC\" ) ; // SET OBJECT CLASS\r iRecord . setClassName ( schemaClass != null ? schemaClass . getName ( ) : null ) ; String fieldName ; Object fieldValue ; // CALL BEFORE MARSHALLING\r invokeCallback ( iPojo , iRecord , OBeforeSerialization . class ) ; for ( Field p : properties ) { fieldName = p . getName ( ) ; if ( idField != null && fieldName . equals ( idField . getName ( ) ) ) continue ; if ( vField != null && fieldName . equals ( vField . getName ( ) ) ) continue ; fieldValue = serializeFieldValue ( getFieldType ( iPojo , fieldName ) , getFieldValue ( iPojo , fieldName ) ) ; schemaProperty = schemaClass != null ? schemaClass . getProperty ( fieldName ) : null ; if ( fieldValue != null ) { if ( isEmbeddedObject ( iPojo . getClass ( ) , fieldValue . getClass ( ) , fieldName , iEntityManager ) ) { // AUTO CREATE SCHEMA PROPERTY\r if ( schemaClass == null ) { db . getMetadata ( ) . getSchema ( ) . createClass ( iPojo . getClass ( ) ) ; iRecord . setClassNameIfExists ( iPojo . getClass ( ) . getSimpleName ( ) ) ; } if ( schemaProperty == null ) { OType t = OType . getTypeByClass ( fieldValue . getClass ( ) ) ; if ( t == null ) t = OType . EMBEDDED ; schemaProperty = iRecord . getSchemaClass ( ) . createProperty ( fieldName , t ) ; } } } fieldValue = typeToStream ( fieldValue , schemaProperty != null ? schemaProperty . getType ( ) : null , iEntityManager , iObj2RecHandler , db , iRecord , iSaveOnlyDirty ) ; iRecord . field ( fieldName , fieldValue ) ; } iObj2RecHandler . registerUserObject ( iPojo , iRecord ) ; // CALL AFTER MARSHALLING\r invokeCallback ( iPojo , iRecord , OAfterSerialization . class ) ; OSerializationThreadLocal . INSTANCE . get ( ) . remove ( identityRecord ) ; Orient . instance ( ) . getProfiler ( ) . stopChrono ( \"Object.toStream\" , \"Serialize object to stream\" , timer ) ; return iRecord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the declared generic types of a class . [CODESPLIT] public static Type [ ] getGenericTypes ( final Object iObject ) { if ( iObject instanceof OTrackedMultiValue ) { final Class < ? > cls = ( ( OTrackedMultiValue < ? , ? > ) iObject ) . getGenericClass ( ) ; if ( cls != null ) return new Type [ ] { cls } ; } return OReflectionHelper . getGenericTypes ( iObject . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "At run - time the evaluation per record must return always true since the recordset are filtered at the beginning unless an operator can work in both modes . In this case sub - class must extend it . [CODESPLIT] @ Override public Object evaluateRecord ( final OIdentifiable iRecord , ODocument iCurrentResult , final OSQLFilterCondition iCondition , final Object iLeft , final Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { ODatabaseDocumentInternal db = getDatabase ( ) ; db . begin ( ) ; if ( className == null && clusterName == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; OModifiableBoolean shutdownGraph = new OModifiableBoolean ( ) ; final boolean txAlreadyBegun = getDatabase ( ) . getTransaction ( ) . isActive ( ) ; try { final Set < OIdentifiable > sourceRIDs = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , source , context , iArgs ) ; // CREATE EDGES final List < ODocument > result = new ArrayList < ODocument > ( sourceRIDs . size ( ) ) ; for ( OIdentifiable from : sourceRIDs ) { final OVertex fromVertex = toVertex ( from ) ; if ( fromVertex == null ) continue ; final ORID oldVertex = fromVertex . getIdentity ( ) . copy ( ) ; final ORID newVertex = fromVertex . moveTo ( className , clusterName ) ; final ODocument newVertexDoc = newVertex . getRecord ( ) ; if ( fields != null ) { // EVALUATE FIELDS for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( newVertex . getRecord ( ) , null , context ) ) ; } OSQLHelper . bindParameters ( newVertexDoc , fields , new OCommandParameters ( iArgs ) , context ) ; } if ( merge != null ) newVertexDoc . merge ( merge , true , false ) ; // SAVE CHANGES newVertexDoc . save ( ) ; // PUT THE MOVE INTO THE RESULT result . add ( new ODocument ( ) . setTrackingChanges ( false ) . field ( \"old\" , oldVertex , OType . LINK ) . field ( \"new\" , newVertex , OType . LINK ) ) ; if ( batch > 0 && result . size ( ) % batch == 0 ) { db . commit ( ) ; db . begin ( ) ; } } db . commit ( ) ; return result ; } finally { //      if (!txAlreadyBegun) //        db.commit(); } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( String object , ByteBuffer buffer , Object ... hints ) { int length = object . length ( ) ; buffer . putInt ( length ) ; byte [ ] binaryData = new byte [ length * 2 ] ; char [ ] stringContent = new char [ length ] ; object . getChars ( 0 , length , stringContent , 0 ) ; int counter = 0 ; for ( char character : stringContent ) { binaryData [ counter ] = ( byte ) character ; counter ++ ; binaryData [ counter ] = ( byte ) ( character >>> 8 ) ; counter ++ ; } buffer . put ( binaryData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String deserializeFromByteBufferObject ( ByteBuffer buffer ) { int len = buffer . getInt ( ) ; final char [ ] chars = new char [ len ] ; final byte [ ] binaryData = new byte [ 2 * len ] ; buffer . get ( binaryData ) ; for ( int i = 0 ; i < len ; i ++ ) chars [ i ] = ( char ) ( ( 0xFF & binaryData [ i << 1 ] ) | ( ( 0xFF & binaryData [ ( i << 1 ) + 1 ] ) << 8 ) ) ; return new String ( chars ) ; } /**\n   * {@inheritDoc}\n   */ @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { return buffer . getInt ( ) * 2 + OIntegerSerializer . INT_SIZE ; } /**\n   * {@inheritDoc}\n   */ @ Override public String deserializeFromByteBufferObject  ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { int len = walChanges . getIntValue ( buffer , offset ) ; final char [ ] chars = new char [ len ] ; offset += OIntegerSerializer . INT_SIZE ; byte [ ] binaryData = walChanges . getBinaryValue ( buffer , offset , 2 * len ) ; for ( int i = 0 ; i < len ; i ++ ) chars [ i ] = ( char ) ( ( 0xFF & binaryData [ i << 1 ] ) | ( ( 0xFF & binaryData [ ( i << 1 ) + 1 ] ) << 8 ) ) ; return new String ( chars ) ; } /**\n   * {@inheritDoc}\n   */ @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getIntValue ( buffer , offset ) * 2 + OIntegerSerializer . INT_SIZE ; } } ", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a OIdentifiable instance using this format : <br > - 2 bytes : class id [ - 2 = no record - 3 = rid - 1 = no class id > - 1 = valid ] <br > - 1 byte : record type [ d b f ] <br > - 2 bytes : cluster id <br > - 8 bytes : position in cluster <br > - 4 bytes : record version <br > - x bytes : record content <br > [CODESPLIT] public static void writeIdentifiable ( OChannelBinary channel , OClientConnection connection , final OIdentifiable o ) throws IOException { if ( o == null ) channel . writeShort ( OChannelBinaryProtocol . RECORD_NULL ) ; else if ( o instanceof ORecordId ) { channel . writeShort ( OChannelBinaryProtocol . RECORD_RID ) ; channel . writeRID ( ( ORID ) o ) ; } else { writeRecord ( channel , connection , o . getRecord ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method load the record information by the internal cluster segment . It s for compatibility with older database than 0 . 9 . 25 . [CODESPLIT] public OStorageConfigurationImpl load ( final OContextConfiguration configuration ) throws OSerializationException { lock . acquireWriteLock ( ) ; try { initConfiguration ( configuration ) ; final byte [ ] record = storage . readRecord ( CONFIG_RID , null , false , false , null ) . getResult ( ) . buffer ; if ( record == null ) throw new OStorageException ( \"Cannot load database configuration. The database seems corrupted\" ) ; fromStream ( record , 0 , record . length , streamCharset ) ; } finally { lock . releaseWriteLock ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Added version used for managed Network Versioning . [CODESPLIT] public byte [ ] toStream ( final int iNetworkVersion , Charset charset ) throws OSerializationException { lock . acquireReadLock ( ) ; try { final StringBuilder buffer = new StringBuilder ( 8192 ) ; write ( buffer , CURRENT_VERSION ) ; write ( buffer , name ) ; write ( buffer , schemaRecordId ) ; write ( buffer , dictionaryRecordId ) ; write ( buffer , indexMgrRecordId ) ; write ( buffer , localeLanguage ) ; write ( buffer , localeCountry ) ; write ( buffer , dateFormat ) ; write ( buffer , dateTimeFormat ) ; write ( buffer , timeZone . getID ( ) ) ; write ( buffer , charset ) ; if ( iNetworkVersion > 24 ) write ( buffer , conflictStrategy ) ; phySegmentToStream ( buffer , fileTemplate ) ; write ( buffer , clusters . size ( ) ) ; for ( OStorageClusterConfiguration c : clusters ) { if ( c == null ) { write ( buffer , - 1 ) ; continue ; } write ( buffer , c . getId ( ) ) ; write ( buffer , c . getName ( ) ) ; write ( buffer , c . getDataSegmentId ( ) ) ; if ( c instanceof OStoragePaginatedClusterConfiguration ) { write ( buffer , \"d\" ) ; final OStoragePaginatedClusterConfiguration paginatedClusterConfiguration = ( OStoragePaginatedClusterConfiguration ) c ; write ( buffer , paginatedClusterConfiguration . useWal ) ; write ( buffer , paginatedClusterConfiguration . recordOverflowGrowFactor ) ; write ( buffer , paginatedClusterConfiguration . recordGrowFactor ) ; write ( buffer , paginatedClusterConfiguration . compression ) ; if ( iNetworkVersion >= 31 ) write ( buffer , paginatedClusterConfiguration . encryption ) ; if ( iNetworkVersion > 24 ) write ( buffer , paginatedClusterConfiguration . conflictStrategy ) ; if ( iNetworkVersion > 25 ) write ( buffer , paginatedClusterConfiguration . getStatus ( ) . name ( ) ) ; if ( iNetworkVersion >= Integer . MAX_VALUE ) { write ( buffer , paginatedClusterConfiguration . getBinaryVersion ( ) ) ; } } } if ( iNetworkVersion <= 25 ) { // dataSegment array write ( buffer , 0 ) ; // tx Segment File write ( buffer , \"\" ) ; write ( buffer , \"\" ) ; write ( buffer , 0 ) ; // tx segment flags write ( buffer , false ) ; write ( buffer , false ) ; } synchronized ( properties ) { write ( buffer , properties . size ( ) ) ; for ( OStorageEntryConfiguration e : properties ) entryToStream ( buffer , e ) ; } write ( buffer , binaryFormatVersion ) ; write ( buffer , clusterSelection ) ; write ( buffer , getMinimumClusters ( ) ) ; if ( iNetworkVersion > 24 ) { write ( buffer , recordSerializer ) ; write ( buffer , recordSerializerVersion ) ; // WRITE CONFIGURATION write ( buffer , configuration . getContextSize ( ) ) ; for ( String k : configuration . getContextKeys ( ) ) { final OGlobalConfiguration cfg = OGlobalConfiguration . findByKey ( k ) ; write ( buffer , k ) ; if ( cfg != null ) { write ( buffer , cfg . isHidden ( ) ? null : configuration . getValueAsString ( cfg ) ) ; } else { write ( buffer , null ) ; OLogManager . instance ( ) . warn ( this , \"Storing configuration for property:'\" + k + \"' not existing in current version\" ) ; } } } write ( buffer , indexEngines . size ( ) ) ; for ( IndexEngineData engineData : indexEngines . values ( ) ) { write ( buffer , engineData . getName ( ) ) ; write ( buffer , engineData . getAlgorithm ( ) ) ; write ( buffer , engineData . getIndexType ( ) == null ? \"\" : engineData . getIndexType ( ) ) ; write ( buffer , engineData . getValueSerializerId ( ) ) ; write ( buffer , engineData . getKeySerializedId ( ) ) ; write ( buffer , engineData . isAutomatic ( ) ) ; write ( buffer , engineData . getDurableInNonTxMode ( ) ) ; write ( buffer , engineData . getVersion ( ) ) ; write ( buffer , engineData . isNullValuesSupport ( ) ) ; write ( buffer , engineData . getKeySize ( ) ) ; write ( buffer , engineData . getEncryption ( ) ) ; write ( buffer , engineData . getEncryptionOptions ( ) ) ; if ( engineData . getKeyTypes ( ) != null ) { write ( buffer , engineData . getKeyTypes ( ) . length ) ; for ( OType type : engineData . getKeyTypes ( ) ) { write ( buffer , type . name ( ) ) ; } } else { write ( buffer , 0 ) ; } if ( engineData . getEngineProperties ( ) == null ) { write ( buffer , 0 ) ; } else { write ( buffer , engineData . getEngineProperties ( ) . size ( ) ) ; for ( Map . Entry < String , String > property : engineData . getEngineProperties ( ) . entrySet ( ) ) { write ( buffer , property . getKey ( ) ) ; write ( buffer , property . getValue ( ) ) ; } } write ( buffer , engineData . getApiVersion ( ) ) ; write ( buffer , engineData . isMultivalue ( ) ) ; } write ( buffer , createdAtVersion ) ; write ( buffer , pageSize ) ; write ( buffer , freeListBoundary ) ; write ( buffer , maxKeySize ) ; // PLAIN: ALLOCATE ENOUGH SPACE TO REUSE IT EVERY TIME buffer . append ( \"|\" ) ; return buffer . toString ( ) . getBytes ( charset ) ; } finally  { lock . releaseReadLock ( ) ; } } public void create ( ) throws IOException { lock . acquireWriteLock ( ) ; try { storage . createRecord ( CONFIG_RID , new byte [ ] { 0 , 0 , 0 , 0 } , 0 , OBlob . RECORD_TYPE , null ) ; } finally { lock . releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if an arrays contains a value otherwise false [CODESPLIT] public static boolean contains ( final int [ ] iArray , final int iToFind ) { if ( iArray == null || iArray . length == 0 ) return false ; for ( int e : iArray ) if ( e == iToFind ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if an arrays contains a value otherwise false [CODESPLIT] public static < T > boolean contains ( final T [ ] iArray , final T iToFind ) { if ( iArray == null || iArray . length == 0 ) return false ; for ( T e : iArray ) if ( e != null && e . equals ( iToFind ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method parses the statement [CODESPLIT] @ Override public < RET extends OCommandExecutor > RET parse ( OCommandRequest iRequest ) { final OCommandRequestText textRequest = ( OCommandRequestText ) iRequest ; if ( iRequest instanceof OSQLSynchQuery ) { request = ( OSQLSynchQuery < ODocument > ) iRequest ; } else if ( iRequest instanceof OSQLAsynchQuery ) { request = ( OSQLAsynchQuery < ODocument > ) iRequest ; } else { // BUILD A QUERY OBJECT FROM THE COMMAND REQUEST request = new OSQLSynchQuery < ODocument > ( textRequest . getText ( ) ) ; if ( textRequest . getResultListener ( ) != null ) { request . setResultListener ( textRequest . getResultListener ( ) ) ; } } String queryText = textRequest . getText ( ) ; // please, do not look at this... refactor this ASAP with new executor structure final InputStream is = new ByteArrayInputStream ( queryText . getBytes ( ) ) ; OrientSql osql = null ; try { ODatabaseDocumentInternal db = getDatabase ( ) ; if ( db == null ) { osql = new OrientSql ( is ) ; } else { osql = new OrientSql ( is , db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; } } catch ( UnsupportedEncodingException e ) { OLogManager . instance ( ) . warn ( this , \"Invalid charset for database \" + getDatabase ( ) + \" \" + getDatabase ( ) . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; osql = new OrientSql ( is ) ; } try { OMatchStatement result = ( OMatchStatement ) osql . parse ( ) ; this . matchExpressions = result . matchExpressions ; this . notMatchExpressions = result . notMatchExpressions ; this . returnItems = result . returnItems ; this . returnAliases = result . returnAliases ; this . limit = result . limit ; } catch ( ParseException e ) { OCommandSQLParsingException ex = new OCommandSQLParsingException ( e , queryText ) ; OErrorCode . QUERY_PARSE_ERROR . throwException ( ex . getMessage ( ) , ex ) ; } buildPatterns ( ) ; pattern . validate ( ) ; return ( RET ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rebinds filter ( where ) conditions to alias nodes after optimization [CODESPLIT] private void rebindFilters ( Map < String , OWhereClause > aliasFilters ) { for ( OMatchExpression expression : matchExpressions ) { OWhereClause newFilter = aliasFilters . get ( expression . origin . getAlias ( ) ) ; expression . origin . setFilter ( newFilter ) ; for ( OMatchPathItem item : expression . items ) { newFilter = aliasFilters . get ( item . filter . getAlias ( ) ) ; item . filter . setFilter ( newFilter ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assigns default aliases to pattern nodes that do not have an explicit alias [CODESPLIT] private void assignDefaultAliases ( List < OMatchExpression > matchExpressions ) { int counter = 0 ; for ( OMatchExpression expression : matchExpressions ) { if ( expression . origin . getAlias ( ) == null ) { expression . origin . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } for ( OMatchPathItem item : expression . items ) { if ( item . filter == null ) { item . filter = new OMatchFilter ( - 1 ) ; } if ( item . filter . getAlias ( ) == null ) { item . filter . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method works statefully using request and context variables from current Match statement . This method will be deprecated in next releases [CODESPLIT] @ Override public Object execute ( Map < Object , Object > iArgs ) { this . context . setInputParameters ( iArgs ) ; return execute ( this . request , this . context , this . progressListener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "executes the match statement . This is the preferred execute () method and it has to be used as the default one in the future . This method works in stateless mode [CODESPLIT] public Object execute ( OSQLAsynchQuery < ODocument > request , OCommandContext context , OProgressListener progressListener ) { if ( orderBy != null ) { throw new OCommandExecutionException ( \"ORDER BY is not supported in MATCH on the legacy API\" ) ; } if ( groupBy != null ) { throw new OCommandExecutionException ( \"GROUP BY is not supported in MATCH on the legacy API\" ) ; } if ( unwind != null ) { throw new OCommandExecutionException ( \"UNWIND is not supported in MATCH on the legacy API\" ) ; } if ( skip != null ) { throw new OCommandExecutionException ( \"SKIP is not supported in MATCH on the legacy API\" ) ; } Map < Object , Object > iArgs = context . getInputParameters ( ) ; try { Map < String , Long > estimatedRootEntries = estimateRootEntries ( aliasClasses , aliasFilters , context ) ; if ( estimatedRootEntries . values ( ) . contains ( 0l ) ) { return new OBasicLegacyResultSet ( ) ; // some aliases do not match on any classes } List < EdgeTraversal > sortedEdges = getTopologicalSortedSchedule ( estimatedRootEntries , pattern ) ; MatchExecutionPlan executionPlan = new MatchExecutionPlan ( ) ; executionPlan . sortedEdges = sortedEdges ; calculateMatch ( pattern , estimatedRootEntries , new MatchContext ( ) , aliasClasses , aliasFilters , context , request , executionPlan ) ; return getResult ( request ) ; } finally { if ( request . getResultListener ( ) != null ) { request . getResultListener ( ) . end ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start a depth - first traversal from the starting node adding all viable unscheduled edges and vertices . [CODESPLIT] private void updateScheduleStartingAt ( PatternNode startNode , Set < PatternNode > visitedNodes , Set < PatternEdge > visitedEdges , Map < String , Set < String > > remainingDependencies , List < EdgeTraversal > resultingSchedule ) { // OrientDB requires the schedule to contain all edges present in the query, which is a stronger condition // than simply visiting all nodes in the query. Consider the following example query: //     MATCH { //         class: A, //         as: foo //     }.in() { //         as: bar //     }, { //         class: B, //         as: bar //     }.out() { //         as: foo //     } RETURN $matches // The schedule for the above query must have two edges, even though there are only two nodes and they can both // be visited with the traversal of a single edge. // // To satisfy it, we obey the following for each non-optional node: // - ignore edges to neighboring nodes which have unsatisfied dependencies; // - for visited neighboring nodes, add their edge if it wasn't already present in the schedule, but do not //   recurse into the neighboring node; // - for unvisited neighboring nodes with satisfied dependencies, add their edge and recurse into them. visitedNodes . add ( startNode ) ; for ( Set < String > dependencies : remainingDependencies . values ( ) ) { dependencies . remove ( startNode . alias ) ; } Map < PatternEdge , Boolean > edges = new LinkedHashMap < PatternEdge , Boolean > ( ) ; for ( PatternEdge outEdge : startNode . out ) { edges . put ( outEdge , true ) ; } for ( PatternEdge inEdge : startNode . in ) { edges . put ( inEdge , false ) ; } for ( Map . Entry < PatternEdge , Boolean > edgeData : edges . entrySet ( ) ) { PatternEdge edge = edgeData . getKey ( ) ; boolean isOutbound = edgeData . getValue ( ) ; PatternNode neighboringNode = isOutbound ? edge . in : edge . out ; if ( ! remainingDependencies . get ( neighboringNode . alias ) . isEmpty ( ) ) { // Unsatisfied dependencies, ignore this neighboring node. continue ; } if ( visitedNodes . contains ( neighboringNode ) ) { if ( ! visitedEdges . contains ( edge ) ) { // If we are executing in this block, we are in the following situation: // - the startNode has not been visited yet; // - it has a neighboringNode that has already been visited; // - the edge between the startNode and the neighboringNode has not been scheduled yet. // // The isOutbound value shows us whether the edge is outbound from the point of view of the startNode. // However, if there are edges to the startNode, we must visit the startNode from an already-visited // neighbor, to preserve the validity of the traversal. Therefore, we negate the value of isOutbound // to ensure that the edge is always scheduled in the direction from the already-visited neighbor // toward the startNode. Notably, this is also the case when evaluating \"optional\" nodes -- we always // visit the optional node from its non-optional and already-visited neighbor. // // The only exception to the above is when we have edges with \"while\" conditions. We are not allowed // to flip their directionality, so we leave them as-is. boolean traversalDirection ; if ( startNode . optional || edge . item . isBidirectional ( ) ) { traversalDirection = ! isOutbound ; } else { traversalDirection = isOutbound ; } visitedEdges . add ( edge ) ; resultingSchedule . add ( new EdgeTraversal ( edge , traversalDirection ) ) ; } } else if ( ! startNode . optional ) { // If the neighboring node wasn't visited, we don't expand the optional node into it, hence the above check. // Instead, we'll allow the neighboring node to add the edge we failed to visit, via the above block. if ( visitedEdges . contains ( edge ) ) { // Should never happen. throw new AssertionError ( \"The edge was visited, but the neighboring vertex was not: \" + edge + \" \" + neighboringNode ) ; } visitedEdges . add ( edge ) ; resultingSchedule . add ( new EdgeTraversal ( edge , isOutbound ) ) ; updateScheduleStartingAt ( neighboringNode , visitedNodes , visitedEdges , remainingDependencies , resultingSchedule ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sort edges in the order they will be matched [CODESPLIT] private List < EdgeTraversal > getTopologicalSortedSchedule ( Map < String , Long > estimatedRootEntries , Pattern pattern ) { List < EdgeTraversal > resultingSchedule = new ArrayList < EdgeTraversal > ( ) ; Map < String , Set < String > > remainingDependencies = getDependencies ( pattern ) ; Set < PatternNode > visitedNodes = new HashSet < PatternNode > ( ) ; Set < PatternEdge > visitedEdges = new HashSet < PatternEdge > ( ) ; // Sort the possible root vertices in order of estimated size, since we want to start with a small vertex set. List < OPair < Long , String > > rootWeights = new ArrayList < OPair < Long , String > > ( ) ; for ( Map . Entry < String , Long > root : estimatedRootEntries . entrySet ( ) ) { rootWeights . add ( new OPair < Long , String > ( root . getValue ( ) , root . getKey ( ) ) ) ; } Collections . sort ( rootWeights ) ; // Add the starting vertices, in the correct order, to an ordered set. Set < String > remainingStarts = new LinkedHashSet < String > ( ) ; for ( OPair < Long , String > item : rootWeights ) { remainingStarts . add ( item . getValue ( ) ) ; } // Add all the remaining aliases after all the suggested start points. for ( String alias : pattern . aliasToNode . keySet ( ) ) { if ( ! remainingStarts . contains ( alias ) ) { remainingStarts . add ( alias ) ; } } while ( resultingSchedule . size ( ) < pattern . numOfEdges ) { // Start a new depth-first pass, adding all nodes with satisfied dependencies. // 1. Find a starting vertex for the depth-first pass. PatternNode startingNode = null ; List < String > startsToRemove = new ArrayList < String > ( ) ; for ( String currentAlias : remainingStarts ) { PatternNode currentNode = pattern . aliasToNode . get ( currentAlias ) ; if ( visitedNodes . contains ( currentNode ) ) { // If a previous traversal already visited this alias, remove it from further consideration. startsToRemove . add ( currentAlias ) ; } else if ( remainingDependencies . get ( currentAlias ) . isEmpty ( ) ) { // If it hasn't been visited, and has all dependencies satisfied, visit it. startsToRemove . add ( currentAlias ) ; startingNode = currentNode ; break ; } } remainingStarts . removeAll ( startsToRemove ) ; if ( startingNode == null ) { // We didn't manage to find a valid root, and yet we haven't constructed a complete schedule. // This means there must be a cycle in our dependency graph, or all dependency-free nodes are optional. // Therefore, the query is invalid. throw new OCommandExecutionException ( \"This query contains MATCH conditions that cannot be evaluated, \" + \"like an undefined alias or a circular dependency on a $matched condition.\" ) ; } // 2. Having found a starting vertex, traverse its neighbors depth-first, //    adding any non-visited ones with satisfied dependencies to our schedule. updateScheduleStartingAt ( startingNode , visitedNodes , visitedEdges , remainingDependencies , resultingSchedule ) ; } if ( resultingSchedule . size ( ) != pattern . numOfEdges ) { throw new AssertionError ( \"Incorrect number of edges: \" + resultingSchedule . size ( ) + \" vs \" + pattern . numOfEdges ) ; } return resultingSchedule ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param request @param ctx @param record [CODESPLIT] private boolean addSingleResult ( OSQLAsynchQuery < ODocument > request , OBasicCommandContext ctx , ORecord record ) { if ( ( ( OBasicCommandContext ) context ) . addToUniqueResult ( record ) ) { request . getResultListener ( ) . result ( record ) ; long currentCount = ctx . getResultsProcessed ( ) . incrementAndGet ( ) ; long limitValue = limitFromProtocol ; if ( limit != null ) { limitValue = limit . num . getValue ( ) . longValue ( ) ; } if ( limitValue > - 1 && limitValue <= currentCount ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private OSelectStatement buildSelectStatement ( String className , OWhereClause oWhereClause ) { OSelectStatement stm = new OSelectStatement ( - 1 ) ; stm . whereClause = oWhereClause ; stm . target = new OFromClause ( - 1 ) ; stm . target . item = new OFromItem ( - 1 ) ; stm . target . item . identifier = new OIdentifier ( className ) ; return stm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares if 2 field values are the same . [CODESPLIT] @ Override public boolean isEqual ( final OBinaryField iField1 , final OBinaryField iField2 ) { final BytesContainer fieldValue1 = iField1 . bytes ; final int offset1 = fieldValue1 . offset ; final BytesContainer fieldValue2 = iField2 . bytes ; final int offset2 = fieldValue2 . offset ; try { switch ( iField1 . type ) { case INTEGER : { final int value1 = OVarIntSerializer . readAsInteger ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 == value2 ; } case DATE : { final long value2 = ( OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ) ; return value1 == value2 ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 == value2 ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 == value2 ; } case STRING : { return Integer . parseInt ( readString ( fieldValue2 ) ) == value1 ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . intValue ( ) ; } } break ; } case LONG : { final long value1 = OVarIntSerializer . readAsLong ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 == value2 ; } case DATE : { final long value2 = ( OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ) ; return value1 == value2 ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 == value2 ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 == value2 ; } case STRING : { return Long . parseLong ( readString ( fieldValue2 ) ) == value1 ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . longValue ( ) ; } } break ; } case SHORT : { final short value1 = OVarIntSerializer . readAsShort ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 == value2 ; } case DATE : { final long value2 = ( OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ) ; return value1 == value2 ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 == value2 ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 == value2 ; } case STRING : { return Short . parseShort ( readString ( fieldValue2 ) ) == value1 ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . shortValue ( ) ; } } break ; } case STRING : { switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return Integer . parseInt ( readString ( fieldValue1 ) ) == value2 ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return Long . parseLong ( readString ( fieldValue1 ) ) == value2 ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return Long . parseLong ( readString ( fieldValue1 ) ) == value2 ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return Short . parseShort ( readString ( fieldValue1 ) ) == value2 ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return Byte . parseByte ( readString ( fieldValue1 ) ) == value2 ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return Float . parseFloat ( readString ( fieldValue1 ) ) == value2 ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return Double . parseDouble ( readString ( fieldValue1 ) ) == value2 ; } case STRING : { final int len1 = OVarIntSerializer . readAsInteger ( fieldValue1 ) ; final int len2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; if ( len1 != len2 ) return false ; final OCollate collate = ( iField1 . collate != null && ! ODefaultCollate . NAME . equals ( iField1 . collate . getName ( ) ) ) ? iField1 . collate : ( iField2 . collate != null && ! ODefaultCollate . NAME . equals ( iField2 . collate . getName ( ) ) ? iField2 . collate : null ) ; if ( collate != null ) { final String str1 = ( String ) collate . transform ( stringFromBytes ( fieldValue1 . bytes , fieldValue1 . offset , len1 ) ) ; final String str2 = ( String ) collate . transform ( stringFromBytes ( fieldValue2 . bytes , fieldValue2 . offset , len2 ) ) ; return str1 . equals ( str2 ) ; } else { for ( int i = 0 ; i < len1 ; ++ i ) { if ( fieldValue1 . bytes [ fieldValue1 . offset + i ] != fieldValue2 . bytes [ fieldValue2 . offset + i ] ) return false ; } } return true ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return new BigDecimal ( readString ( fieldValue1 ) ) . equals ( value2 ) ; } case BOOLEAN : { final boolean value2 = readByte ( fieldValue2 ) == 1 ; return Boolean . parseBoolean ( readString ( fieldValue1 ) ) == value2 ; } } break ; } case DOUBLE : { final long value1AsLong = readLong ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final double value1 = Double . longBitsToDouble ( value1AsLong ) ; final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { final double value1 = Double . longBitsToDouble ( value1AsLong ) ; final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 == value2 ; } case SHORT : { final double value1 = Double . longBitsToDouble ( value1AsLong ) ; final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case BYTE : { final double value1 = Double . longBitsToDouble ( value1AsLong ) ; final byte value2 = readByte ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final double value1 = Double . longBitsToDouble ( value1AsLong ) ; final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 == value2 ; } case DOUBLE : { final double value2AsLong = readLong ( fieldValue2 ) ; return value1AsLong == value2AsLong ; } case STRING : { final double value1 = Double . longBitsToDouble ( value1AsLong ) ; return Double . parseDouble ( readString ( fieldValue2 ) ) == value1 ; } case DECIMAL : { final double value1 = Double . longBitsToDouble ( value1AsLong ) ; final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . doubleValue ( ) ; } } break ; } case FLOAT : { final int value1AsInt = readInteger ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final float value1 = Float . intBitsToFloat ( value1AsInt ) ; final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { final float value1 = Float . intBitsToFloat ( value1AsInt ) ; final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 == value2 ; } case SHORT : { final float value1 = Float . intBitsToFloat ( value1AsInt ) ; final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case BYTE : { final float value1 = Float . intBitsToFloat ( value1AsInt ) ; final byte value2 = readByte ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final float value2AsInt = readInteger ( fieldValue2 ) ; return value1AsInt == value2AsInt ; } case DOUBLE : { final float value1 = Float . intBitsToFloat ( value1AsInt ) ; final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 == value2 ; } case STRING : { final float value1 = Float . intBitsToFloat ( value1AsInt ) ; return Float . parseFloat ( readString ( fieldValue2 ) ) == value1 ; } case DECIMAL : { final float value1 = Float . intBitsToFloat ( value1AsInt ) ; final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . floatValue ( ) ; } } break ; } case BYTE : { final byte value1 = readByte ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 == value2 ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 == value2 ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 == value2 ; } case STRING : { final byte value2 = Byte . parseByte ( ( readString ( fieldValue2 ) ) ) ; return value1 == value2 ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . byteValue ( ) ; } } break ; } case BOOLEAN : { final boolean value1 = readByte ( fieldValue1 ) == 1 ; switch ( iField2 . type ) { case BOOLEAN : { final boolean value2 = readByte ( fieldValue2 ) == 1 ; return value1 == value2 ; } case STRING : { final String str = readString ( fieldValue2 ) ; return Boolean . parseBoolean ( str ) == value1 ; } } break ; } case DATE : { final long value1 = OVarIntSerializer . readAsLong ( fieldValue1 ) * MILLISEC_PER_DAY ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; value2 = convertDayToTimezone ( ODateHelper . getDatabaseTimeZone ( ) , TimeZone . getTimeZone ( \"GMT\" ) , value2 ) ; return value1 == value2 ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return value1 == value2 ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 == value2 ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 == value2 ; } case STRING : { } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . longValue ( ) ; } } break ; } case DATETIME : { final long value1 = OVarIntSerializer . readAsLong ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 == value2 ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 == value2 ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return value1 == value2 ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 == value2 ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 == value2 ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 == value2 ; } case STRING : { final String value2AsString = readString ( fieldValue2 ) ; if ( OIOUtils . isLong ( value2AsString ) ) { final long value2 = Long . parseLong ( value2AsString ) ; return value1 == value2 ; } final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final SimpleDateFormat dateFormat = db != null ? db . getStorage ( ) . getConfiguration ( ) . getDateTimeFormatInstance ( ) : new SimpleDateFormat ( OStorageConfiguration . DEFAULT_DATETIME_FORMAT ) ; final Date value2AsDate = dateFormat . parse ( value2AsString ) ; final long value2 = value2AsDate . getTime ( ) ; return value1 == value2 ; } catch ( ParseException ignore ) { try { final SimpleDateFormat dateFormat = db != null ? db . getStorage ( ) . getConfiguration ( ) . getDateFormatInstance ( ) : new SimpleDateFormat ( OStorageConfiguration . DEFAULT_DATE_FORMAT ) ; final Date value2AsDate = dateFormat . parse ( value2AsString ) ; final long value2 = value2AsDate . getTime ( ) ; return value1 == value2 ; } catch ( ParseException ignored ) { return new Date ( value1 ) . toString ( ) . equals ( value2AsString ) ; } } } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 == value2 . longValue ( ) ; } } break ; } case BINARY : { switch ( iField2 . type ) { case BINARY : { final int length1 = OVarIntSerializer . readAsInteger ( fieldValue1 ) ; final int length2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; if ( length1 != length2 ) return false ; for ( int i = 0 ; i < length1 ; ++ i ) { if ( fieldValue1 . bytes [ fieldValue1 . offset + i ] != fieldValue2 . bytes [ fieldValue2 . offset + i ] ) return false ; } return true ; } } break ; } case LINK : { switch ( iField2 . type ) { case LINK : { final int clusterId1 = OVarIntSerializer . readAsInteger ( fieldValue1 ) ; final int clusterId2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; if ( clusterId1 != clusterId2 ) return false ; final long clusterPos1 = OVarIntSerializer . readAsLong ( fieldValue1 ) ; final long clusterPos2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; if ( clusterPos1 == clusterPos2 ) return true ; break ; } case STRING : { return readOptimizedLink ( fieldValue1 , false ) . toString ( ) . equals ( readString ( fieldValue2 ) ) ; } } break ; } case DECIMAL : { final BigDecimal value1 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue1 . bytes , fieldValue1 . offset ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 . equals ( new BigDecimal ( value2 ) ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 . equals ( new BigDecimal ( value2 ) ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 . equals ( new BigDecimal ( value2 ) ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 . equals ( new BigDecimal ( value2 ) ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 . equals ( new BigDecimal ( value2 ) ) ; } case STRING : { return value1 . toString ( ) . equals ( readString ( fieldValue2 ) ) ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 . equals ( value2 ) ; } } break ; } } } finally { fieldValue1 . offset = offset1 ; fieldValue2 . offset = offset2 ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two values executing also conversion between types . [CODESPLIT] @ Override public int compare ( final OBinaryField iField1 , final OBinaryField iField2 ) { final BytesContainer fieldValue1 = iField1 . bytes ; final int offset1 = fieldValue1 . offset ; final BytesContainer fieldValue2 = iField2 . bytes ; final int offset2 = fieldValue2 . offset ; try { switch ( iField1 . type ) { case INTEGER : { final int value1 = OVarIntSerializer . readAsInteger ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; return Integer . toString ( value1 ) . compareTo ( value2 ) ; } case DECIMAL : { final int value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) . intValue ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } } break ; } case LONG : { final long value1 = OVarIntSerializer . readAsLong ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; return Long . toString ( value1 ) . compareTo ( value2 ) ; } case DECIMAL : { final long value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) . longValue ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } } break ; } case SHORT : { final short value1 = OVarIntSerializer . readAsShort ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; return Short . toString ( value1 ) . compareTo ( value2 ) ; } case DECIMAL : { final short value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) . shortValue ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } } break ; } case STRING : { final String value1 = readString ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 . compareTo ( Integer . toString ( value2 ) ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 . compareTo ( Long . toString ( value2 ) ) ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return value1 . compareTo ( Long . toString ( value2 ) ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 . compareTo ( Short . toString ( value2 ) ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return value1 . compareTo ( Byte . toString ( value2 ) ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 . compareTo ( Float . toString ( value2 ) ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 . compareTo ( Double . toString ( value2 ) ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; final OCollate collate = ( iField1 . collate != null && ! ODefaultCollate . NAME . equals ( iField1 . collate . getName ( ) ) ) ? iField1 . collate : ( iField2 . collate != null && ! ODefaultCollate . NAME . equals ( iField2 . collate . getName ( ) ) ? iField2 . collate : null ) ; if ( collate != null ) { final String str1 = ( String ) collate . transform ( value1 ) ; final String str2 = ( String ) collate . transform ( value2 ) ; return str1 . compareTo ( str2 ) ; } return value1 . compareTo ( value2 ) ; } case BOOLEAN : { final boolean value2 = readByte ( fieldValue2 ) == 1 ; return value1 . compareTo ( Boolean . toString ( value2 ) ) ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return new BigDecimal ( value1 ) . compareTo ( value2 ) ; } } break ; } case DOUBLE : { final double value1 = Double . longBitsToDouble ( readLong ( fieldValue1 ) ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; return Double . toString ( value1 ) . compareTo ( value2 ) ; } case DECIMAL : { final double value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) . doubleValue ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } } break ; } case FLOAT : { final float value1 = Float . intBitsToFloat ( readInteger ( fieldValue1 ) ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; return Float . toString ( value1 ) . compareTo ( value2 ) ; } case DECIMAL : { final String value2 = readString ( fieldValue2 ) ; return Float . toString ( value1 ) . compareTo ( value2 ) ; } } break ; } case BYTE : { final byte value1 = readByte ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; return Byte . toString ( value1 ) . compareTo ( value2 ) ; } case DECIMAL : { final byte value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) . byteValue ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } } break ; } case BOOLEAN : { final boolean value1 = readByte ( fieldValue1 ) == 1 ; switch ( iField2 . type ) { case BOOLEAN : { final boolean value2 = readByte ( fieldValue2 ) == 1 ; return ( value1 == value2 ) ? 0 : value1 ? 1 : - 1 ; } case STRING : { final boolean value2 = Boolean . parseBoolean ( readString ( fieldValue2 ) ) ; return ( value1 == value2 ) ? 0 : value1 ? 1 : - 1 ; } } break ; } case DATETIME : { final long value1 = OVarIntSerializer . readAsLong ( fieldValue1 ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2AsString = readString ( fieldValue2 ) ; if ( OIOUtils . isLong ( value2AsString ) ) { final long value2 = Long . parseLong ( value2AsString ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final SimpleDateFormat dateFormat = db != null ? db . getStorage ( ) . getConfiguration ( ) . getDateTimeFormatInstance ( ) : new SimpleDateFormat ( OStorageConfiguration . DEFAULT_DATETIME_FORMAT ) ; final Date value2AsDate = dateFormat . parse ( value2AsString ) ; final long value2 = value2AsDate . getTime ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } catch ( ParseException ignored ) { try { final SimpleDateFormat dateFormat = db != null ? db . getStorage ( ) . getConfiguration ( ) . getDateFormatInstance ( ) : new SimpleDateFormat ( OStorageConfiguration . DEFAULT_DATE_FORMAT ) ; final Date value2AsDate = dateFormat . parse ( value2AsString ) ; final long value2 = value2AsDate . getTime ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } catch ( ParseException ignore ) { return new Date ( value1 ) . toString ( ) . compareTo ( value2AsString ) ; } } } case DECIMAL : { final long value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) . longValue ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } } break ; } case DATE : { final long value1 = OVarIntSerializer . readAsLong ( fieldValue1 ) * MILLISEC_PER_DAY ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DATE : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) * MILLISEC_PER_DAY ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } case STRING : { final String value2AsString = readString ( fieldValue2 ) ; if ( OIOUtils . isLong ( value2AsString ) ) { final long value2 = Long . parseLong ( value2AsString ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final SimpleDateFormat dateFormat = db != null ? db . getStorage ( ) . getConfiguration ( ) . getDateFormatInstance ( ) : new SimpleDateFormat ( OStorageConfiguration . DEFAULT_DATE_FORMAT ) ; final Date value2AsDate = dateFormat . parse ( value2AsString ) ; long value2 = value2AsDate . getTime ( ) ; value2 = convertDayToTimezone ( ODateHelper . getDatabaseTimeZone ( ) , TimeZone . getTimeZone ( \"GMT\" ) , value2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } catch ( ParseException ignore ) { try { final SimpleDateFormat dateFormat = db != null ? db . getStorage ( ) . getConfiguration ( ) . getDateFormatInstance ( ) : new SimpleDateFormat ( OStorageConfiguration . DEFAULT_DATETIME_FORMAT ) ; final Date value2AsDate = dateFormat . parse ( value2AsString ) ; long value2 = value2AsDate . getTime ( ) ; value2 = convertDayToTimezone ( ODateHelper . getDatabaseTimeZone ( ) , TimeZone . getTimeZone ( \"GMT\" ) , value2 ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } catch ( ParseException ignored ) { return new Date ( value1 ) . toString ( ) . compareTo ( value2AsString ) ; } } } case DECIMAL : { final long value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) . longValue ( ) ; return ( value1 < value2 ) ? - 1 : ( ( value1 == value2 ) ? 0 : 1 ) ; } } break ; } case BINARY : { switch ( iField2 . type ) { case BINARY : { final int length1 = OVarIntSerializer . readAsInteger ( fieldValue1 ) ; final int length2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; final int max = Math . min ( length1 , length2 ) ; for ( int i = 0 ; i < max ; ++ i ) { final byte b1 = fieldValue1 . bytes [ fieldValue1 . offset + i ] ; final byte b2 = fieldValue2 . bytes [ fieldValue2 . offset + i ] ; if ( b1 > b2 ) return 1 ; else if ( b2 > b1 ) return - 1 ; } if ( length1 > length2 ) return 1 ; else if ( length2 > length1 ) return - 1 ; // EQUALS return 0 ; } } break ; } case LINK : { switch ( iField2 . type ) { case LINK : { final int clusterId1 = OVarIntSerializer . readAsInteger ( fieldValue1 ) ; final int clusterId2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; if ( clusterId1 > clusterId2 ) return 1 ; else if ( clusterId1 < clusterId2 ) return - 1 ; else { final long clusterPos1 = OVarIntSerializer . readAsLong ( fieldValue1 ) ; final long clusterPos2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; if ( clusterPos1 > clusterPos2 ) return 1 ; else if ( clusterPos1 < clusterPos2 ) return - 1 ; return 0 ; } } case STRING : { return readOptimizedLink ( fieldValue1 , false ) . compareTo ( new ORecordId ( readString ( fieldValue2 ) ) ) ; } } break ; } case DECIMAL : { final BigDecimal value1 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue1 . bytes , fieldValue1 . offset ) ; switch ( iField2 . type ) { case INTEGER : { final int value2 = OVarIntSerializer . readAsInteger ( fieldValue2 ) ; return value1 . compareTo ( new BigDecimal ( value2 ) ) ; } case LONG : case DATETIME : { final long value2 = OVarIntSerializer . readAsLong ( fieldValue2 ) ; return value1 . compareTo ( new BigDecimal ( value2 ) ) ; } case SHORT : { final short value2 = OVarIntSerializer . readAsShort ( fieldValue2 ) ; return value1 . compareTo ( new BigDecimal ( value2 ) ) ; } case FLOAT : { final float value2 = Float . intBitsToFloat ( readInteger ( fieldValue2 ) ) ; return value1 . compareTo ( new BigDecimal ( value2 ) ) ; } case DOUBLE : { final double value2 = Double . longBitsToDouble ( readLong ( fieldValue2 ) ) ; return value1 . compareTo ( new BigDecimal ( value2 ) ) ; } case STRING : { final String value2 = readString ( fieldValue2 ) ; return value1 . toString ( ) . compareTo ( value2 ) ; } case DECIMAL : { final BigDecimal value2 = ODecimalSerializer . INSTANCE . deserialize ( fieldValue2 . bytes , fieldValue2 . offset ) ; return value1 . compareTo ( value2 ) ; } case BYTE : { final byte value2 = readByte ( fieldValue2 ) ; return value1 . compareTo ( new BigDecimal ( value2 ) ) ; } } break ; } } } finally { fieldValue1 . offset = offset1 ; fieldValue2 . offset = offset2 ; } // NO COMPARE SUPPORTED, RETURN NON EQUALS return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add new indexDefinition in current composite . [CODESPLIT] public void addIndex ( final OIndexDefinition indexDefinition ) { indexDefinitions . add ( indexDefinition ) ; if ( indexDefinition instanceof OIndexDefinitionMultiValue ) { if ( multiValueDefinitionIndex == - 1 ) multiValueDefinitionIndex = indexDefinitions . size ( ) - 1 ; else throw new OIndexException ( \"Composite key cannot contain more than one collection item\" ) ; } collate . addCollate ( indexDefinition . getCollate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public List < String > getFields ( ) { final List < String > fields = new LinkedList < String > ( ) ; for ( final OIndexDefinition indexDefinition : indexDefinitions ) { fields . addAll ( indexDefinition . getFields ( ) ) ; } return Collections . unmodifiableList ( fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object getDocumentValueToIndex ( final ODocument iDocument ) { final List < OCompositeKey > compositeKeys = new ArrayList < OCompositeKey > ( 10 ) ; final OCompositeKey firstKey = new OCompositeKey ( ) ; boolean containsCollection = false ; compositeKeys . add ( firstKey ) ; for ( final OIndexDefinition indexDefinition : indexDefinitions ) { final Object result = indexDefinition . getDocumentValueToIndex ( iDocument ) ; if ( result == null && isNullValuesIgnored ( ) ) return null ; //for empty collections we add null key in index\r if ( result instanceof Collection && ( ( Collection ) result ) . isEmpty ( ) && isNullValuesIgnored ( ) ) return null ; containsCollection = addKey ( firstKey , compositeKeys , containsCollection , result ) ; } if ( ! containsCollection ) return firstKey ; return compositeKeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Object createValue ( final Object ... params ) { if ( params . length == 1 && params [ 0 ] instanceof Collection ) return params [ 0 ] ; return createValue ( Arrays . asList ( params ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public OType [ ] getTypes ( ) { final List < OType > types = new LinkedList < OType > ( ) ; for ( final OIndexDefinition indexDefinition : indexDefinitions ) Collections . addAll ( types , indexDefinition . getTypes ( ) ) ; return types . toArray ( new OType [ types . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public ODocument toStream ( ) { document . setInternalStatus ( ORecordElement . STATUS . UNMARSHALLING ) ; try { serializeToStream ( ) ; } finally { document . setInternalStatus ( ORecordElement . STATUS . LOADED ) ; } return document ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String toCreateIndexDDL ( final String indexName , final String indexType , String engine ) { final StringBuilder ddl = new StringBuilder ( \"create index \" ) ; ddl . append ( indexName ) . append ( \" on \" ) . append ( className ) . append ( \" ( \" ) ; final Iterator < String > fieldIterator = getFieldsToIndex ( ) . iterator ( ) ; if ( fieldIterator . hasNext ( ) ) { ddl . append ( fieldIterator . next ( ) ) ; while ( fieldIterator . hasNext ( ) ) { ddl . append ( \", \" ) . append ( fieldIterator . next ( ) ) ; } } ddl . append ( \" ) \" ) . append ( indexType ) . append ( ' ' ) ; if ( engine != null ) ddl . append ( OCommandExecutorSQLCreateIndex . KEYWORD_ENGINE + \" \" + engine ) . append ( ' ' ) ; if ( multiValueDefinitionIndex == - 1 ) { boolean first = true ; for ( OType oType : getTypes ( ) ) { if ( first ) first = false ; else ddl . append ( \", \" ) ; ddl . append ( oType . name ( ) ) ; } } return ddl . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( records . isEmpty ( ) ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; int deleted = 0 ; final ODatabaseDocumentInternal database = getDatabase ( ) ; for ( String rec : records ) { try { final ORecordId rid = new ORecordId ( rec ) ; final OStorageOperationResult < Boolean > result = database . getStorage ( ) . deleteRecord ( rid , - 1 , 0 , null ) ; database . getLocalCache ( ) . deleteRecord ( rid ) ; if ( result . getResult ( ) ) deleted ++ ; } catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( \"Error on executing command\" ) , e ) ; } } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "INTERNAL USE ONLY this has to be invoked ONLY if the item is aggregate!!! [CODESPLIT] public OProjectionItem splitForAggregation ( AggregateProjectionSplit aggregateSplit , OCommandContext ctx ) { if ( isAggregate ( ) ) { OProjectionItem result = new OProjectionItem ( - 1 ) ; result . alias = getProjectionAlias ( ) ; result . expression = expression . splitForAggregation ( aggregateSplit , ctx ) ; result . nestedProjection = nestedProjection ; return result ; } else { return this ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "choosing return type is based on existence of [CODESPLIT] public Object toObjectDetermineType ( OResult source , OCommandContext ctx ) { String className = getClassNameForDocument ( ctx ) ; String type = getTypeForDocument ( ctx ) ; if ( className != null || ( type != null && \"d\" . equalsIgnoreCase ( type ) ) ) { return toDocument ( source , ctx , className ) ; } else { return toMap ( source , ctx ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether or not this filter item is chain of fields ( e . g . field1 . field2 . field3 ) . Return true if filter item contains only field projections operators if field item contains any other projection operator the method returns false . When filter item does not contains any chain operator it is also field chain consist of one field . [CODESPLIT] public boolean isFieldChain ( ) { if ( operationsChain == null ) { return true ; } for ( OPair < OSQLMethodRuntime , Object [ ] > pair : operationsChain ) { if ( ! pair . getKey ( ) . getMethod ( ) . getName ( ) . equals ( OSQLMethodField . NAME ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the collate of this expression based on the fully evaluated field chain starting from the passed object . [CODESPLIT] public OCollate getCollate ( Object doc ) { if ( collate != null || operationsChain == null || ! isFieldChain ( ) ) { return collate ; } if ( ! ( doc instanceof OIdentifiable ) ) { return null ; } FieldChain chain = getFieldChain ( ) ; ODocument lastDoc = ( ( OIdentifiable ) doc ) . getRecord ( ) ; for ( int i = 0 ; i < chain . getItemCount ( ) - 1 ; i ++ ) { if ( lastDoc == null ) { return null ; } Object nextDoc = lastDoc . field ( chain . getItemName ( i ) ) ; if ( nextDoc == null || ! ( nextDoc instanceof OIdentifiable ) ) { return null ; } lastDoc = ( ( OIdentifiable ) nextDoc ) . getRecord ( ) ; } if ( lastDoc == null ) { return null ; } OClass schemaClass = lastDoc . getSchemaClass ( ) ; if ( schemaClass == null ) { return null ; } OProperty property = schemaClass . getProperty ( chain . getItemName ( chain . getItemCount ( ) - 1 ) ) ; if ( property == null ) { return null ; } return property . getCollate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the plain string representation of this identifier with quoting removed from back - ticks [CODESPLIT] public String getStringValue ( ) { if ( value == null ) { return null ; } if ( value . contains ( \"`\" ) ) { return value . replaceAll ( \"\\\\\\\\`\" , \"`\" ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the value of the identifier . It can contain any values this method can manage back - ticks ( internally quote them ) so back - ticks have not to be quoted when passed as a parameter [CODESPLIT] private void setStringValue ( String s ) { if ( s == null ) { value = null ; } else if ( s . contains ( \"`\" ) ) { value = s . replaceAll ( \"`\" , \"\\\\\\\\`\" ) ; } else { value = s ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pseudo - randomly advances and records the given probe value for the given thread . [CODESPLIT] private int advanceProbe ( int probe ) { probe ^= probe << 13 ; // xorshift probe ^= probe >>> 17 ; probe ^= probe << 5 ; this . probe . get ( ) . set ( probe ) ; return probe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The transaction is reentrant . If { @code begin () } has been called several times the actual commit happens only after the same amount of { @code commit () } calls [CODESPLIT] @ Override public void commit ( final boolean force ) { checkTransaction ( ) ; if ( txStartCounter < 0 ) throw new OStorageException ( \"Invalid value of tx counter\" ) ; if ( force ) txStartCounter = 0 ; else txStartCounter -- ; if ( txStartCounter == 0 ) { doCommit ( ) ; } else if ( txStartCounter > 0 ) OLogManager . instance ( ) . debug ( this , \"Nested transaction was closed but transaction itself was not committed.\" ) ; else throw new OTransactionException ( \"Transaction was committed more times than it is started.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the DROP CLUSTER . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clusterName == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocumentInternal database = getDatabase ( ) ; // CHECK IF ANY CLASS IS USING IT\r final int clusterId = database . getStorage ( ) . getClusterIdByName ( clusterName ) ; for ( OClass iClass : database . getMetadata ( ) . getSchema ( ) . getClasses ( ) ) { for ( int i : iClass . getClusterIds ( ) ) { if ( i == clusterId ) // IN USE\r return false ; } } // REMOVE CACHE OF COMMAND RESULTS IF ACTIVE\r database . getMetadata ( ) . getCommandCache ( ) . invalidateResultsOfCluster ( clusterName ) ; database . dropCluster ( clusterId , true ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It returns a ODocument starting from a json file . [CODESPLIT] public static ODocument buildJsonFromFile ( String filePath ) throws IOException { if ( filePath == null ) { return null ; } File jsonFile = new File ( filePath ) ; if ( ! jsonFile . exists ( ) ) { return null ; } FileInputStream is = new FileInputStream ( jsonFile ) ; BufferedReader rd = new BufferedReader ( new InputStreamReader ( is , Charset . forName ( \"UTF-8\" ) ) ) ; ODocument json = new ODocument ( ) ; String jsonText = OFileManager . readAllTextFile ( rd ) ; json . fromJSON ( jsonText , \"noMap\" ) ; return json ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( rid == null && query == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; if ( ! returning . equalsIgnoreCase ( \"COUNT\" ) ) allDeletedRecords = new ArrayList < ORecord > ( ) ; txAlreadyBegun = getDatabase ( ) . getTransaction ( ) . isActive ( ) ; if ( rid != null ) { // REMOVE PUNCTUAL RID\r OGraphCommandExecutorSQLFactory . runInConfiguredTxMode ( new OGraphCommandExecutorSQLFactory . GraphCallBack < Object > ( ) { @ Override public Object call ( OrientBaseGraph graph ) { final OrientVertex v = graph . getVertex ( rid ) ; if ( v != null ) { v . remove ( ) ; removed = 1 ; } return null ; } } ) ; // CLOSE PENDING TX\r end ( ) ; } else if ( query != null ) { // TARGET IS A CLASS + OPTIONAL CONDITION\r OGraphCommandExecutorSQLFactory . runInConfiguredTxMode ( new OGraphCommandExecutorSQLFactory . GraphCallBack < OrientGraph > ( ) { @ Override public OrientGraph call ( final OrientBaseGraph iGraph ) { // TARGET IS A CLASS + OPTIONAL CONDITION\r currentGraph . set ( iGraph ) ; query . setContext ( getContext ( ) ) ; query . execute ( iArgs ) ; return null ; } } ) ; } else throw new OCommandExecutionException ( \"Invalid target\" ) ; if ( returning . equalsIgnoreCase ( \"COUNT\" ) ) // RETURNS ONLY THE COUNT\r return removed ; else // RETURNS ALL THE DELETED RECORDS\r return allDeletedRecords ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the current vertex . [CODESPLIT] public boolean result ( final Object iRecord ) { final OIdentifiable id = ( OIdentifiable ) iRecord ; if ( id . getIdentity ( ) . isValid ( ) ) { final ODocument record = id . getRecord ( ) ; final OrientBaseGraph g = currentGraph . get ( ) ; final OrientVertex v = g . getVertex ( record ) ; if ( v != null ) { v . remove ( ) ; if ( ! txAlreadyBegun && batch > 0 && removed % batch == 0 ) { if ( g instanceof OrientGraph ) { g . commit ( ) ; ( ( OrientGraph ) g ) . begin ( ) ; } } if ( returning . equalsIgnoreCase ( \"BEFORE\" ) ) allDeletedRecords . add ( record ) ; removed ++ ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the returning keyword if found . [CODESPLIT] protected String parseReturn ( ) throws OCommandSQLParsingException { final String returning = parserNextWord ( true ) ; if ( ! returning . equalsIgnoreCase ( \"COUNT\" ) && ! returning . equalsIgnoreCase ( \"BEFORE\" ) ) throwParsingException ( \"Invalid \" + KEYWORD_RETURN + \" value set to '\" + returning + \"' but it should be COUNT (default), BEFORE. Example: \" + KEYWORD_RETURN + \" BEFORE\" ) ; return returning ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if an hash string matches a password based on the algorithm found on hash string . [CODESPLIT] public boolean checkPassword ( final String iPassword , final String iHash ) { if ( iHash . startsWith ( HASH_ALGORITHM_PREFIX ) ) { final String s = iHash . substring ( HASH_ALGORITHM_PREFIX . length ( ) ) ; return createSHA256 ( iPassword ) . equals ( s ) ; } else if ( iHash . startsWith ( PBKDF2_ALGORITHM_PREFIX ) ) { final String s = iHash . substring ( PBKDF2_ALGORITHM_PREFIX . length ( ) ) ; return checkPasswordWithSalt ( iPassword , s , PBKDF2_ALGORITHM ) ; } else if ( iHash . startsWith ( PBKDF2_SHA256_ALGORITHM_PREFIX ) ) { final String s = iHash . substring ( PBKDF2_SHA256_ALGORITHM_PREFIX . length ( ) ) ; return checkPasswordWithSalt ( iPassword , s , PBKDF2_SHA256_ALGORITHM ) ; } // Do not compare raw strings against each other, to avoid timing attacks.\r // Instead, hash them both with a cryptographic hash function and\r // compare their hashes with a constant-time comparison method.\r return MessageDigest . isEqual ( digestSHA256 ( iPassword ) , digestSHA256 ( iHash ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hashes the input string . [CODESPLIT] public String createHash ( final String iInput , final String iAlgorithm , final boolean iIncludeAlgorithm ) { if ( iInput == null ) throw new IllegalArgumentException ( \"Input string is null\" ) ; if ( iAlgorithm == null ) throw new IllegalArgumentException ( \"Algorithm is null\" ) ; final StringBuilder buffer = new StringBuilder ( 128 ) ; final String algorithm = validateAlgorithm ( iAlgorithm ) ; if ( iIncludeAlgorithm ) { buffer . append ( ' ' ) ; buffer . append ( algorithm ) ; buffer . append ( ' ' ) ; } final String transformed ; if ( HASH_ALGORITHM . equalsIgnoreCase ( algorithm ) ) { transformed = createSHA256 ( iInput ) ; } else if ( PBKDF2_ALGORITHM . equalsIgnoreCase ( algorithm ) ) { transformed = createHashWithSalt ( iInput , OGlobalConfiguration . SECURITY_USER_PASSWORD_SALT_ITERATIONS . getValueAsInteger ( ) , algorithm ) ; } else if ( PBKDF2_SHA256_ALGORITHM . equalsIgnoreCase ( algorithm ) ) { transformed = createHashWithSalt ( iInput , OGlobalConfiguration . SECURITY_USER_PASSWORD_SALT_ITERATIONS . getValueAsInteger ( ) , algorithm ) ; } else throw new IllegalArgumentException ( \"Algorithm '\" + algorithm + \"' is not supported\" ) ; buffer . append ( transformed ) ; return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the algorithm is supported by the current version of Java [CODESPLIT] private static boolean isAlgorithmSupported ( final String algorithm ) { // Java 7 specific checks.\r if ( Runtime . class . getPackage ( ) != null && Runtime . class . getPackage ( ) . getImplementationVersion ( ) != null ) { if ( Runtime . class . getPackage ( ) . getImplementationVersion ( ) . startsWith ( \"1.7\" ) ) { // Java 7 does not support the PBKDF2_SHA256_ALGORITHM.\r if ( algorithm != null && algorithm . equals ( PBKDF2_SHA256_ALGORITHM ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the index . [CODESPLIT] public OIndexInternal < ? > create ( final OIndexDefinition indexDefinition , final String clusterIndexName , final Set < String > clustersToIndex , boolean rebuild , final OProgressListener progressListener , final OBinarySerializer valueSerializer ) { acquireExclusiveLock ( ) ; try { configuration = indexConfigurationInstance ( new ODocument ( ) . setTrackingChanges ( false ) ) ; this . indexDefinition = indexDefinition ; if ( clustersToIndex != null ) this . clustersToIndex = new HashSet <> ( clustersToIndex ) ; else this . clustersToIndex = new HashSet <> ( ) ; // do not remove this, it is needed to remove index garbage if such one exists try { if ( apiVersion == 0 ) { removeValuesContainer ( ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error during deletion of index '%s'\" , e , name ) ; } indexId = storage . addIndexEngine ( name , algorithm , type , indexDefinition , valueSerializer , isAutomatic ( ) , true , version , 1 , this instanceof OIndexMultiValues , getEngineProperties ( ) , clustersToIndex , metadata ) ; apiVersion = OAbstractPaginatedStorage . extractEngineAPIVersion ( indexId ) ; assert indexId >= 0 ; assert apiVersion >= 0 ; onIndexEngineChange ( indexId ) ; if ( rebuild ) fillIndex ( progressListener , false ) ; updateConfiguration ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Exception during index '%s' creation\" , e , name ) ; while ( true ) try { if ( indexId >= 0 ) storage . deleteIndexEngine ( indexId ) ; break ; } catch ( OInvalidIndexEngineIdException ignore ) { doReloadIndexEngine ( ) ; } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"Exception during index '%s' deletion\" , ex , name ) ; } if ( e instanceof OIndexException ) throw ( OIndexException ) e ; throw OException . wrapException ( new OIndexException ( \"Cannot create the index '\" + name + \"'\" ) , e ) ; } finally { releaseExclusiveLock ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public long rebuild ( final OProgressListener iProgressListener ) { long documentIndexed ; final boolean intentInstalled = getDatabase ( ) . declareIntent ( new OIntentMassiveInsert ( ) ) ; acquireExclusiveLock ( ) ; try { // DO NOT REORDER 2 assignments bellow // see #getRebuildVersion() rebuilding = true ; rebuildVersion . incrementAndGet ( ) ; try { if ( indexId >= 0 ) { storage . deleteIndexEngine ( indexId ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error during index '%s' delete\" , e , name ) ; } removeValuesContainer ( ) ; indexId = storage . addIndexEngine ( name , algorithm , type , indexDefinition , determineValueSerializer ( ) , isAutomatic ( ) , true , version , 1 , this instanceof OIndexMultiValues , getEngineProperties ( ) , clustersToIndex , metadata ) ; apiVersion = OAbstractPaginatedStorage . extractEngineAPIVersion ( indexId ) ; onIndexEngineChange ( indexId ) ; } catch ( Exception e ) { try { if ( indexId >= 0 ) storage . clearIndex ( indexId ) ; } catch ( Exception e2 ) { OLogManager . instance ( ) . error ( this , \"Error during index rebuild\" , e2 ) ; // IGNORE EXCEPTION: IF THE REBUILD WAS LAUNCHED IN CASE OF RID INVALID CLEAR ALWAYS GOES IN ERROR } rebuilding = false ; throw OException . wrapException ( new OIndexException ( \"Error on rebuilding the index for clusters: \" + clustersToIndex ) , e ) ; } finally { releaseExclusiveLock ( ) ; } acquireSharedLock ( ) ; try { documentIndexed = fillIndex ( iProgressListener , true ) ; } catch ( final Exception e ) { OLogManager . instance ( ) . error ( this , \"Error during index rebuild\" , e ) ; try { if ( indexId >= 0 ) storage . clearIndex ( indexId ) ; } catch ( Exception e2 ) { OLogManager . instance ( ) . error ( this , \"Error during index rebuild\" , e2 ) ; // IGNORE EXCEPTION: IF THE REBUILD WAS LAUNCHED IN CASE OF RID INVALID CLEAR ALWAYS GOES IN ERROR } throw OException . wrapException ( new OIndexException ( \"Error on rebuilding the index for clusters: \" + clustersToIndex ) , e ) ; } finally { rebuilding = false ; if ( intentInstalled ) getDatabase ( ) . declareIntent ( null ) ; releaseSharedLock ( ) ; } return documentIndexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Sets the order of results by a field in ascending ( asc ) or descending ( desc ) order based on dir parameter . This is translated on ORDER BY in the underlying SQL query . [CODESPLIT] public Query order ( final String props , final String dir ) { this . orderBy = props ; this . orderByDir = dir ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the result set of the query as iterable vertices . [CODESPLIT] @ Override public Iterable < Vertex > vertices ( ) { if ( limit == 0 ) return Collections . emptyList ( ) ; OTransaction transaction = ( ( OrientBaseGraph ) graph ) . getRawGraph ( ) . getTransaction ( ) ; if ( transaction . isActive ( ) && transaction . getEntryCount ( ) > 0 || hasCustomPredicate ( ) ) { // INSIDE TRANSACTION QUERY DOESN'T SEE IN MEMORY CHANGES, UNTIL // SUPPORTED USED THE BASIC IMPL String [ ] classes = allSubClassesLabels ( ) ; return new OrientGraphQueryIterable < Vertex > ( true , classes ) ; } final StringBuilder text = new StringBuilder ( 512 ) ; // GO DIRECTLY AGAINST E CLASS AND SUB-CLASSES text . append ( QUERY_SELECT_FROM ) ; if ( ( ( OrientBaseGraph ) graph ) . isUseClassForVertexLabel ( ) && labels != null && labels . length > 0 ) { // FILTER PER CLASS SAVING CHECKING OF LABEL PROPERTY if ( labels . length == 1 ) // USE THE CLASS NAME text . append ( OrientBaseGraph . encodeClassName ( labels [ 0 ] ) ) ; else { // MULTIPLE CLASSES NOT SUPPORTED DIRECTLY: CREATE A SUB-QUERY String [ ] classes = allSubClassesLabels ( ) ; return new OrientGraphQueryIterable < Vertex > ( true , classes ) ; } } else text . append ( OrientVertexType . CLASS_NAME ) ; final List < Object > queryParams = manageFilters ( text ) ; if ( ! ( ( OrientBaseGraph ) graph ) . isUseClassForVertexLabel ( ) ) manageLabels ( queryParams . size ( ) > 0 , text ) ; if ( orderBy . length ( ) > 1 ) { text . append ( ORDERBY ) ; text . append ( orderBy ) ; text . append ( \" \" ) . append ( orderByDir ) . append ( \" \" ) ; } if ( skip > 0 && skip < Integer . MAX_VALUE ) { text . append ( SKIP ) ; text . append ( skip ) ; } if ( limit > 0 && limit < Integer . MAX_VALUE ) { text . append ( LIMIT ) ; text . append ( limit ) ; } final OSQLSynchQuery < OIdentifiable > query = new OSQLSynchQuery < OIdentifiable > ( text . toString ( ) ) ; if ( fetchPlan != null ) query . setFetchPlan ( fetchPlan ) ; return new OrientElementIterable < Vertex > ( ( ( OrientBaseGraph ) graph ) , ( ( OrientBaseGraph ) graph ) . getRawGraph ( ) . query ( query , queryParams . toArray ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the result set of the query as iterable edges . [CODESPLIT] @ Override public Iterable < Edge > edges ( ) { if ( limit == 0 ) return Collections . emptyList ( ) ; if ( ( ( OrientBaseGraph ) graph ) . getRawGraph ( ) . getTransaction ( ) . isActive ( ) || hasCustomPredicate ( ) ) // INSIDE TRANSACTION QUERY DOESN'T SEE IN MEMORY CHANGES, UNTIL // SUPPORTED USED THE BASIC IMPL return new OrientGraphQueryIterable < Edge > ( false , labels ) ; if ( ( ( OrientBaseGraph ) graph ) . isUseLightweightEdges ( ) ) return new OrientGraphQueryIterable < Edge > ( false , labels ) ; final StringBuilder text = new StringBuilder ( 512 ) ; // GO DIRECTLY AGAINST E CLASS AND SUB-CLASSES text . append ( QUERY_SELECT_FROM ) ; if ( ( ( OrientBaseGraph ) graph ) . isUseClassForEdgeLabel ( ) && labels != null && labels . length > 0 ) { // FILTER PER CLASS SAVING CHECKING OF LABEL PROPERTY if ( labels . length == 1 ) // USE THE CLASS NAME text . append ( OrientBaseGraph . encodeClassName ( labels [ 0 ] ) ) ; else { // MULTIPLE CLASSES NOT SUPPORTED DIRECTLY: CREATE A SUB-QUERY return new OrientGraphQueryIterable < Edge > ( false , labels ) ; } } else text . append ( OrientEdgeType . CLASS_NAME ) ; List < Object > queryParams = manageFilters ( text ) ; if ( ! ( ( OrientBaseGraph ) graph ) . isUseClassForEdgeLabel ( ) ) manageLabels ( queryParams . size ( ) > 0 , text ) ; final OSQLSynchQuery < OIdentifiable > query = new OSQLSynchQuery < OIdentifiable > ( text . toString ( ) ) ; if ( fetchPlan != null ) query . setFetchPlan ( fetchPlan ) ; if ( limit > 0 && limit < Integer . MAX_VALUE ) query . setLimit ( limit ) ; return new OrientElementIterable < Edge > ( ( ( OrientBaseGraph ) graph ) , ( ( OrientBaseGraph ) graph ) . getRawGraph ( ) . query ( query , queryParams . toArray ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the partition keys of all the sub - tasks . [CODESPLIT] @ Override public int [ ] getPartitionKey ( ) { if ( tasks . size ( ) == 1 ) // ONE TASK, USE THE INNER TASK'S PARTITION KEY return tasks . get ( 0 ) . getPartitionKey ( ) ; // MULTIPLE PARTITIONS final int [ ] partitions = new int [ tasks . size ( ) ] ; for ( int i = 0 ; i < tasks . size ( ) ; ++ i ) { final OAbstractRecordReplicatedTask task = tasks . get ( i ) ; partitions [ i ] = task . getPartitionKey ( ) [ 0 ] ; } return partitions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the timeout according to the transaction size . [CODESPLIT] @ Override public long getDistributedTimeout ( ) { final long to = OGlobalConfiguration . DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT . getValueAsLong ( ) ; return to + ( ( to / 2 ) * tasks . size ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public String toCreateIndexDDL ( final String indexName , final String indexType , final String engine ) { final StringBuilder ddl = new StringBuilder ( \"create index `\" ) ; ddl . append ( indexName ) . append ( \"` \" ) . append ( indexType ) . append ( ' ' ) ; if ( keyTypes != null && keyTypes . length > 0 ) { ddl . append ( keyTypes [ 0 ] . toString ( ) ) ; for ( int i = 1 ; i < keyTypes . length ; i ++ ) { ddl . append ( \", \" ) . append ( keyTypes [ i ] . toString ( ) ) ; } } return ddl . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Added version used for managed Network Versioning . [CODESPLIT] public byte [ ] toStream ( final int iNetworkVersion , final Charset charset ) throws OSerializationException { lock . acquireReadLock ( ) ; try { final StringBuilder buffer = new StringBuilder ( 8192 ) ; write ( buffer , CURRENT_VERSION ) ; write ( buffer , null ) ; write ( buffer , getSchemaRecordId ( ) ) ; write ( buffer , \"\" ) ; write ( buffer , getIndexMgrRecordId ( ) ) ; write ( buffer , getLocaleLanguage ( ) ) ; write ( buffer , getLocaleCountry ( ) ) ; write ( buffer , getDateFormat ( ) ) ; write ( buffer , getDateFormat ( ) ) ; final TimeZone timeZone = getTimeZone ( ) ; assert timeZone != null ; write ( buffer , timeZone ) ; write ( buffer , charset ) ; if ( iNetworkVersion > 24 ) { write ( buffer , getConflictStrategy ( ) ) ; } phySegmentToStream ( buffer , new OStorageSegmentConfiguration ( ) ) ; final List < OStorageClusterConfiguration > clusters = getClusters ( ) ; write ( buffer , clusters . size ( ) ) ; for ( final OStorageClusterConfiguration c : clusters ) { if ( c == null ) { write ( buffer , - 1 ) ; continue ; } write ( buffer , c . getId ( ) ) ; write ( buffer , c . getName ( ) ) ; write ( buffer , c . getDataSegmentId ( ) ) ; if ( c instanceof OStoragePaginatedClusterConfiguration ) { write ( buffer , \"d\" ) ; final OStoragePaginatedClusterConfiguration paginatedClusterConfiguration = ( OStoragePaginatedClusterConfiguration ) c ; write ( buffer , paginatedClusterConfiguration . useWal ) ; write ( buffer , paginatedClusterConfiguration . recordOverflowGrowFactor ) ; write ( buffer , paginatedClusterConfiguration . recordGrowFactor ) ; write ( buffer , paginatedClusterConfiguration . compression ) ; if ( iNetworkVersion >= 31 ) { write ( buffer , paginatedClusterConfiguration . encryption ) ; } if ( iNetworkVersion > 24 ) { write ( buffer , paginatedClusterConfiguration . conflictStrategy ) ; } if ( iNetworkVersion > 25 ) { write ( buffer , paginatedClusterConfiguration . getStatus ( ) . name ( ) ) ; } if ( iNetworkVersion >= Integer . MAX_VALUE ) { write ( buffer , paginatedClusterConfiguration . getBinaryVersion ( ) ) ; } } } if ( iNetworkVersion <= 25 ) { // dataSegment array write ( buffer , 0 ) ; // tx Segment File write ( buffer , \"\" ) ; write ( buffer , \"\" ) ; write ( buffer , 0 ) ; // tx segment flags write ( buffer , false ) ; write ( buffer , false ) ; } final List < OStorageEntryConfiguration > properties = getProperties ( ) ; write ( buffer , properties . size ( ) ) ; for ( final OStorageEntryConfiguration e : properties ) { entryToStream ( buffer , e ) ; } write ( buffer , getBinaryFormatVersion ( ) ) ; write ( buffer , getClusterSelection ( ) ) ; write ( buffer , getMinimumClusters ( ) ) ; if ( iNetworkVersion > 24 ) { write ( buffer , getRecordSerializer ( ) ) ; write ( buffer , getRecordSerializerVersion ( ) ) ; // WRITE CONFIGURATION write ( buffer , configuration . getContextSize ( ) ) ; for ( final String k : configuration . getContextKeys ( ) ) { final OGlobalConfiguration cfg = OGlobalConfiguration . findByKey ( k ) ; write ( buffer , k ) ; if ( cfg != null ) { write ( buffer , cfg . isHidden ( ) ? null : configuration . getValueAsString ( cfg ) ) ; } else { write ( buffer , null ) ; OLogManager . instance ( ) . warn ( this , \"Storing configuration for property:'\" + k + \"' not existing in current version\" ) ; } } } final List < IndexEngineData > engines = loadIndexEngines ( ) ; write ( buffer , engines . size ( ) ) ; for ( final IndexEngineData engineData : engines ) { write ( buffer , engineData . getName ( ) ) ; write ( buffer , engineData . getAlgorithm ( ) ) ; write ( buffer , engineData . getIndexType ( ) == null ? \"\" : engineData . getIndexType ( ) ) ; write ( buffer , engineData . getValueSerializerId ( ) ) ; write ( buffer , engineData . getKeySerializedId ( ) ) ; write ( buffer , engineData . isAutomatic ( ) ) ; write ( buffer , engineData . getDurableInNonTxMode ( ) ) ; write ( buffer , engineData . getVersion ( ) ) ; write ( buffer , engineData . isNullValuesSupport ( ) ) ; write ( buffer , engineData . getKeySize ( ) ) ; write ( buffer , engineData . getEncryption ( ) ) ; write ( buffer , engineData . getEncryptionOptions ( ) ) ; if ( engineData . getKeyTypes ( ) != null ) { write ( buffer , engineData . getKeyTypes ( ) . length ) ; for ( final OType type : engineData . getKeyTypes ( ) ) { write ( buffer , type . name ( ) ) ; } } else { write ( buffer , 0 ) ; } if ( engineData . getEngineProperties ( ) == null ) { write ( buffer , 0 ) ; } else { write ( buffer , engineData . getEngineProperties ( ) . size ( ) ) ; for ( final Map . Entry < String , String > property : engineData . getEngineProperties ( ) . entrySet ( ) ) { write ( buffer , property . getKey ( ) ) ; write ( buffer , property . getValue ( ) ) ; } } write ( buffer , engineData . getApiVersion ( ) ) ; write ( buffer , engineData . isMultivalue ( ) ) ; } write ( buffer , getCreatedAtVersion ( ) ) ; write ( buffer , getPageSize ( ) ) ; write ( buffer , getFreeListBoundary ( ) ) ; write ( buffer , getMaxKeySize ( ) ) ; // PLAIN: ALLOCATE ENOUGH SPACE TO REUSE IT EVERY TIME buffer . append ( \"|\" ) ; return buffer . toString ( ) . getBytes ( charset ) ; } finally { lock . releaseReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current Graph settings . [CODESPLIT] public Features getFeatures ( ) { makeActive ( ) ; if ( ! featuresInitialized ) { FEATURES . supportsDuplicateEdges = true ; FEATURES . supportsSelfLoops = true ; FEATURES . isPersistent = true ; FEATURES . supportsVertexIteration = true ; FEATURES . supportsVertexIndex = true ; FEATURES . ignoresSuppliedIds = true ; FEATURES . supportsTransactions = true ; FEATURES . supportsVertexKeyIndex = true ; FEATURES . supportsKeyIndices = true ; FEATURES . isWrapper = false ; FEATURES . supportsIndices = true ; FEATURES . supportsVertexProperties = true ; FEATURES . supportsEdgeProperties = true ; // For more information on supported types, please see: // http://code.google.com/p/orient/wiki/Types FEATURES . supportsSerializableObjectProperty = true ; FEATURES . supportsBooleanProperty = true ; FEATURES . supportsDoubleProperty = true ; FEATURES . supportsFloatProperty = true ; FEATURES . supportsIntegerProperty = true ; FEATURES . supportsPrimitiveArrayProperty = true ; FEATURES . supportsUniformListProperty = true ; FEATURES . supportsMixedListProperty = true ; FEATURES . supportsLongProperty = true ; FEATURES . supportsMapProperty = true ; FEATURES . supportsStringProperty = true ; FEATURES . supportsThreadedTransactions = false ; FEATURES . supportsThreadIsolatedTransactions = false ; // DYNAMIC FEATURES BASED ON CONFIGURATION FEATURES . supportsEdgeIndex = ! isUseLightweightEdges ( ) ; FEATURES . supportsEdgeKeyIndex = ! isUseLightweightEdges ( ) ; FEATURES . supportsEdgeIteration = ! isUseLightweightEdges ( ) ; FEATURES . supportsEdgeRetrieval = ! isUseLightweightEdges ( ) ; featuresInitialized = true ; } return FEATURES ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the Edge from the Graph . Connected vertices aren t removed . [CODESPLIT] public void removeEdgeInternal ( final OrientEdge edge ) { // OUT VERTEX final OIdentifiable inVertexEdge = edge . vIn != null ? edge . vIn : edge . rawElement ; final String edgeClassName = OrientBaseGraph . encodeClassName ( edge . getLabel ( ) ) ; final boolean useVertexFieldsForEdgeLabels = settings . isUseVertexFieldsForEdgeLabels ( ) ; final OIdentifiable outVertex = edge . getOutVertex ( ) ; ODocument outVertexRecord = null ; boolean outVertexChanged = false ; if ( outVertex != null ) { outVertexRecord = outVertex . getRecord ( ) ; if ( outVertexRecord != null ) { final String outFieldName = OrientVertex . getConnectionFieldName ( Direction . OUT , edgeClassName , useVertexFieldsForEdgeLabels ) ; outVertexChanged = edge . dropEdgeFromVertex ( inVertexEdge , outVertexRecord , outFieldName , outVertexRecord . field ( outFieldName ) ) ; } } // IN VERTEX final OIdentifiable outVertexEdge = edge . vOut != null ? edge . vOut : edge . rawElement ; final OIdentifiable inVertex = edge . getInVertex ( ) ; ODocument inVertexRecord = null ; boolean inVertexChanged = false ; if ( inVertex != null ) { inVertexRecord = inVertex . getRecord ( ) ; if ( inVertexRecord != null ) { final String inFieldName = OrientVertex . getConnectionFieldName ( Direction . IN , edgeClassName , useVertexFieldsForEdgeLabels ) ; inVertexChanged = edge . dropEdgeFromVertex ( outVertexEdge , inVertexRecord , inFieldName , inVertexRecord . field ( inFieldName ) ) ; } } if ( outVertexChanged ) outVertexRecord . save ( ) ; if ( inVertexChanged ) inVertexRecord . save ( ) ; if ( edge . rawElement != null ) // NON-LIGHTWEIGHT EDGE edge . removeRecord ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the CREATE LINK . [CODESPLIT] private Object execute ( OCommandContext ctx ) { if ( destField == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocumentInternal database = getDatabase ( ) ; if ( ! ( database . getDatabaseOwner ( ) instanceof ODatabaseDocument ) ) throw new OCommandSQLParsingException ( \"This command supports only the database type ODatabaseDocumentTx and type '\" + database . getClass ( ) + \"' was found\" ) ; final ODatabaseDocument db = ( ODatabaseDocument ) database . getDatabaseOwner ( ) ; final OClass sourceClass = database . getMetadata ( ) . getSchema ( ) . getClass ( getSourceClass ( ) . getStringValue ( ) ) ; if ( sourceClass == null ) throw new OCommandExecutionException ( \"Source class '\" + getSourceClass ( ) . getStringValue ( ) + \"' not found\" ) ; final OClass destClass = database . getMetadata ( ) . getSchema ( ) . getClass ( getDestClass ( ) . getStringValue ( ) ) ; if ( destClass == null ) throw new OCommandExecutionException ( \"Destination class '\" + getDestClass ( ) . getStringValue ( ) + \"' not found\" ) ; Object value ; String cmd = \"select from \" ; if ( ! ODocumentHelper . ATTRIBUTE_RID . equals ( destField ) ) { cmd = \"select from \" + getDestClass ( ) + \" where \" + destField + \" = \" ; } List < ODocument > result ; ODocument target ; Object oldValue ; long total = 0 ; String linkName = name == null ? sourceField . getStringValue ( ) : name . getStringValue ( ) ; boolean multipleRelationship ; OType linkType = OType . valueOf ( type . getStringValue ( ) . toUpperCase ( Locale . ENGLISH ) ) ; if ( linkType != null ) // DETERMINE BASED ON FORCED TYPE multipleRelationship = linkType == OType . LINKSET || linkType == OType . LINKLIST ; else multipleRelationship = false ; long totRecords = db . countClass ( sourceClass . getName ( ) ) ; long currRecord = 0 ; database . declareIntent ( new OIntentMassiveInsert ( ) ) ; try { // BROWSE ALL THE RECORDS OF THE SOURCE CLASS for ( ODocument doc : db . browseClass ( sourceClass . getName ( ) ) ) { if ( breakExec ) { break ; } value = doc . getProperty ( sourceField . getStringValue ( ) ) ; if ( value != null ) { if ( value instanceof ODocument || value instanceof ORID ) { // ALREADY CONVERTED } else if ( value instanceof Collection < ? > ) { // TODO } else { // SEARCH THE DESTINATION RECORD target = null ; if ( ! ODocumentHelper . ATTRIBUTE_RID . equals ( destField ) && value instanceof String ) if ( ( ( String ) value ) . length ( ) == 0 ) value = null ; else value = \"'\" + value + \"'\" ; OResultSet rs = database . query ( cmd + value ) ; result = toList ( rs ) ; rs . close ( ) ; if ( result == null || result . size ( ) == 0 ) value = null ; else if ( result . size ( ) > 1 ) throw new OCommandExecutionException ( \"Cannot create link because multiple records was found in class '\" + destClass . getName ( ) + \"' with value \" + value + \" in field '\" + destField + \"'\" ) ; else { target = result . get ( 0 ) ; value = target ; } if ( target != null && inverse ) { // INVERSE RELATIONSHIP oldValue = target . getProperty ( linkName ) ; if ( oldValue != null ) { if ( ! multipleRelationship ) multipleRelationship = true ; Collection < ODocument > coll ; if ( oldValue instanceof Collection ) { // ADD IT IN THE EXISTENT COLLECTION coll = ( Collection < ODocument > ) oldValue ; target . setDirty ( ) ; } else { // CREATE A NEW COLLECTION FOR BOTH coll = new ArrayList < ODocument > ( 2 ) ; target . setProperty ( linkName , coll ) ; coll . add ( ( ODocument ) oldValue ) ; } coll . add ( doc ) ; } else { if ( linkType != null ) if ( linkType == OType . LINKSET ) { value = new ORecordLazySet ( target ) ; ( ( Set < OIdentifiable > ) value ) . add ( doc ) ; } else if ( linkType == OType . LINKLIST ) { value = new ORecordLazyList ( target ) ; ( ( ORecordLazyList ) value ) . add ( doc ) ; } else // IGNORE THE TYPE, SET IT AS LINK value = doc ; else value = doc ; target . setProperty ( linkName , value ) ; } target . save ( ) ; } else { // SET THE REFERENCE doc . setProperty ( linkName , value ) ; doc . save ( ) ; } total ++ ; } } } if ( total > 0 ) { if ( inverse ) { // REMOVE THE OLD PROPERTY IF ANY OProperty prop = destClass . getProperty ( linkName ) ; if ( prop != null ) destClass . dropProperty ( linkName ) ; if ( linkType == null ) linkType = multipleRelationship ? OType . LINKSET : OType . LINK ; // CREATE THE PROPERTY destClass . createProperty ( linkName , linkType , sourceClass ) ; } else { // REMOVE THE OLD PROPERTY IF ANY OProperty prop = sourceClass . getProperty ( linkName ) ; if ( prop != null ) sourceClass . dropProperty ( linkName ) ; // CREATE THE PROPERTY sourceClass . createProperty ( linkName , OType . LINK , destClass ) ; } } } catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( \"Error on creation of links\" ) , e ) ; } finally { database . declareIntent ( null ) ; } return total ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This check if a file was trimmed or trunked in the current atomic operation . [CODESPLIT] private static boolean checkChangesFilledUpTo ( final FileChanges changesContainer , final long pageIndex ) { if ( changesContainer == null ) { return true ; } else if ( changesContainer . isNew || changesContainer . maxNewPageIndex > - 2 ) { return pageIndex < changesContainer . maxNewPageIndex + 1 ; } else return ! changesContainer . truncate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OClass truncateCluster ( String clusterName ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_DELETE , name ) ; acquireSchemaReadLock ( ) ; try { final String cmd = String . format ( \"truncate cluster %s\" , clusterName ) ; database . command ( cmd ) . close ( ) ; } finally { releaseSchemaReadLock ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the timeout keyword if found . [CODESPLIT] protected boolean parseTimeout ( final String w ) throws OCommandSQLParsingException { if ( ! w . equals ( KEYWORD_TIMEOUT ) ) return false ; String word = parserNextWord ( true ) ; try { timeoutMs = Long . parseLong ( word ) ; } catch ( NumberFormatException ignore ) { throwParsingException ( \"Invalid \" + KEYWORD_TIMEOUT + \" value set to '\" + word + \"' but it should be a valid long. Example: \" + KEYWORD_TIMEOUT + \" 3000\" ) ; } if ( timeoutMs < 0 ) throwParsingException ( \"Invalid \" + KEYWORD_TIMEOUT + \": value set minor than ZERO. Example: \" + KEYWORD_TIMEOUT + \" 10000\" ) ; word = parserNextWord ( true ) ; if ( word != null ) if ( word . equals ( TIMEOUT_STRATEGY . EXCEPTION . toString ( ) ) ) timeoutStrategy = TIMEOUT_STRATEGY . EXCEPTION ; else if ( word . equals ( TIMEOUT_STRATEGY . RETURN . toString ( ) ) ) timeoutStrategy = TIMEOUT_STRATEGY . RETURN ; else parserGoBack ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the lock keyword if found . [CODESPLIT] protected String parseLock ( ) throws OCommandSQLParsingException { final String lockStrategy = parserNextWord ( true ) ; if ( ! lockStrategy . equalsIgnoreCase ( \"DEFAULT\" ) && ! lockStrategy . equalsIgnoreCase ( \"NONE\" ) && ! lockStrategy . equalsIgnoreCase ( \"RECORD\" ) ) throwParsingException ( \"Invalid \" + KEYWORD_LOCK + \" value set to '\" + lockStrategy + \"' but it should be NONE (default) or RECORD. Example: \" + KEYWORD_LOCK + \" RECORD\" ) ; return lockStrategy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO check PGIS [CODESPLIT] @ Override public OSpatialQueryContext build ( Map < String , Object > query ) throws Exception { Shape shape = parseShape ( query ) ; SpatialStrategy strategy = manager . strategy ( ) ; SpatialArgs args = new SpatialArgs ( SpatialOperation . Intersects , shape . getBoundingBox ( ) ) ; Query filterQuery = strategy . makeQuery ( args ) ; BooleanQuery q = new BooleanQuery . Builder ( ) . add ( filterQuery , BooleanClause . Occur . MUST ) . add ( new MatchAllDocsQuery ( ) , BooleanClause . Occur . SHOULD ) . build ( ) ; return new OSpatialQueryContext ( null , manager . searcher ( ) , q ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the ALTER DATABASE . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final StringBuilder result = new StringBuilder ( ) ; if ( optimizeEdges ) result . append ( optimizeEdges ( ) ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( fromExpr == null && toExpr == null && rids == null && query == null && compiledFilter == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; txAlreadyBegun = getDatabase ( ) . getTransaction ( ) . isActive ( ) ; if ( rids != null ) { // REMOVE PUNCTUAL RID\r OGraphCommandExecutorSQLFactory . runInConfiguredTxMode ( new OGraphCommandExecutorSQLFactory . GraphCallBack < Object > ( ) { @ Override public Object call ( OrientBaseGraph graph ) { for ( ORecordId rid : rids ) { final OrientEdge e = graph . getEdge ( rid ) ; if ( e != null ) { e . remove ( ) ; removed ++ ; } } return null ; } } ) ; // CLOSE PENDING TX\r end ( ) ; } else { // MULTIPLE EDGES\r final Set < OrientEdge > edges = new HashSet < OrientEdge > ( ) ; if ( query == null ) { OGraphCommandExecutorSQLFactory . runInConfiguredTxMode ( new OGraphCommandExecutorSQLFactory . GraphCallBack < Object > ( ) { @ Override public Object call ( OrientBaseGraph graph ) { Set < OIdentifiable > fromIds = null ; if ( fromExpr != null ) fromIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( graph . getRawGraph ( ) , fromExpr , context , iArgs ) ; Set < OIdentifiable > toIds = null ; if ( toExpr != null ) toIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( graph . getRawGraph ( ) , toExpr , context , iArgs ) ; if ( label == null ) label = OrientEdgeType . CLASS_NAME ; if ( fromIds != null && toIds != null ) { int fromCount = 0 ; int toCount = 0 ; for ( OIdentifiable fromId : fromIds ) { final OrientVertex v = graph . getVertex ( fromId ) ; if ( v != null ) fromCount += v . countEdges ( Direction . OUT , label ) ; } for ( OIdentifiable toId : toIds ) { final OrientVertex v = graph . getVertex ( toId ) ; if ( v != null ) toCount += v . countEdges ( Direction . IN , label ) ; } if ( fromCount <= toCount ) { // REMOVE ALL THE EDGES BETWEEN VERTICES\r for ( OIdentifiable fromId : fromIds ) { final OrientVertex v = graph . getVertex ( fromId ) ; if ( v != null ) for ( Edge e : v . getEdges ( Direction . OUT , label ) ) { final OIdentifiable inV = ( ( OrientEdge ) e ) . getInVertex ( ) ; if ( inV != null && toIds . contains ( inV . getIdentity ( ) ) ) edges . add ( ( OrientEdge ) e ) ; } } } else { for ( OIdentifiable toId : toIds ) { final OrientVertex v = graph . getVertex ( toId ) ; if ( v != null ) for ( Edge e : v . getEdges ( Direction . IN , label ) ) { final OIdentifiable outV = ( ( OrientEdge ) e ) . getOutVertex ( ) ; if ( outV != null && fromIds . contains ( outV . getIdentity ( ) ) ) edges . add ( ( OrientEdge ) e ) ; } } } } else if ( fromIds != null ) { // REMOVE ALL THE EDGES THAT START FROM A VERTEXES\r for ( OIdentifiable fromId : fromIds ) { final OrientVertex v = graph . getVertex ( fromId ) ; if ( v != null ) { for ( Edge e : v . getEdges ( Direction . OUT , label ) ) { edges . add ( ( OrientEdge ) e ) ; } } } } else if ( toIds != null ) { // REMOVE ALL THE EDGES THAT ARRIVE TO A VERTEXES\r for ( OIdentifiable toId : toIds ) { final OrientVertex v = graph . getVertex ( toId ) ; if ( v != null ) { for ( Edge e : v . getEdges ( Direction . IN , label ) ) { edges . add ( ( OrientEdge ) e ) ; } } } } else throw new OCommandExecutionException ( \"Invalid target: \" + toIds ) ; if ( compiledFilter != null ) { // ADDITIONAL FILTERING\r for ( Iterator < OrientEdge > it = edges . iterator ( ) ; it . hasNext ( ) ; ) { final OrientEdge edge = it . next ( ) ; if ( ! ( Boolean ) compiledFilter . evaluate ( edge . getRecord ( ) , null , context ) ) it . remove ( ) ; } } // DELETE THE FOUND EDGES\r removed = edges . size ( ) ; for ( OrientEdge edge : edges ) edge . remove ( ) ; return null ; } } ) ; // CLOSE PENDING TX\r end ( ) ; } else { OGraphCommandExecutorSQLFactory . runInConfiguredTxMode ( new OGraphCommandExecutorSQLFactory . GraphCallBack < OrientGraph > ( ) { @ Override public OrientGraph call ( final OrientBaseGraph iGraph ) { // TARGET IS A CLASS + OPTIONAL CONDITION\r currentGraph . set ( iGraph ) ; query . setContext ( getContext ( ) ) ; query . execute ( iArgs ) ; return null ; } } ) ; } } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the current edge . [CODESPLIT] public boolean result ( final Object iRecord ) { final OIdentifiable id = ( OIdentifiable ) iRecord ; if ( compiledFilter != null ) { // ADDITIONAL FILTERING\r if ( ! ( Boolean ) compiledFilter . evaluate ( id . getRecord ( ) , null , context ) ) return true ; } if ( id . getIdentity ( ) . isValid ( ) ) { final OrientBaseGraph g = currentGraph . get ( ) ; final OrientEdge e = g . getEdge ( id ) ; if ( e != null ) { e . remove ( ) ; if ( ! txAlreadyBegun && batch > 0 && ( removed + 1 ) % batch == 0 ) { if ( g instanceof OrientGraph ) { g . commit ( ) ; ( ( OrientGraph ) g ) . begin ( ) ; } } removed ++ ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combines two queries subset into one . This operation will be valid only if { @link #canBeMerged ( OIndexSearchResult ) } method will return <code > true< / code > for the same passed in parameter . [CODESPLIT] public OIndexSearchResult merge ( final OIndexSearchResult searchResult ) { // if (searchResult.lastOperator instanceof OQueryOperatorEquals) {\r if ( searchResult . lastOperator instanceof OQueryOperatorEquals ) { return mergeFields ( this , searchResult ) ; } if ( lastOperator instanceof OQueryOperatorEquals ) { return mergeFields ( searchResult , this ) ; } if ( isIndexEqualityOperator ( searchResult . lastOperator ) ) { return mergeFields ( this , searchResult ) ; } return mergeFields ( searchResult , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( schemaClass == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final long recs = schemaClass . count ( deep ) ; if ( recs > 0 && ! unsafe ) { if ( schemaClass . isSubClassOf ( \"V\" ) ) { throw new OCommandExecutionException ( \"'TRUNCATE CLASS' command cannot be used on not empty vertex classes. Apply the 'UNSAFE' keyword to force it (at your own risk)\" ) ; } else if ( schemaClass . isSubClassOf ( \"E\" ) ) { throw new OCommandExecutionException ( \"'TRUNCATE CLASS' command cannot be used on not empty edge classes. Apply the 'UNSAFE' keyword to force it (at your own risk)\" ) ; } } Collection < OClass > subclasses = schemaClass . getAllSubclasses ( ) ; if ( deep && ! unsafe ) { // for multiple inheritance\r for ( OClass subclass : subclasses ) { long subclassRecs = schemaClass . count ( ) ; if ( subclassRecs > 0 ) { if ( subclass . isSubClassOf ( \"V\" ) ) { throw new OCommandExecutionException ( \"'TRUNCATE CLASS' command cannot be used on not empty vertex classes (\" + subclass . getName ( ) + \"). Apply the 'UNSAFE' keyword to force it (at your own risk)\" ) ; } else if ( subclass . isSubClassOf ( \"E\" ) ) { throw new OCommandExecutionException ( \"'TRUNCATE CLASS' command cannot be used on not empty edge classes (\" + subclass . getName ( ) + \"). Apply the 'UNSAFE' keyword to force it (at your own risk)\" ) ; } } } } try { schemaClass . truncate ( ) ; invalidateCommandCache ( schemaClass ) ; if ( deep ) { for ( OClass subclass : subclasses ) { subclass . truncate ( ) ; invalidateCommandCache ( subclass ) ; } } } catch ( IOException e ) { throw OException . wrapException ( new OCommandExecutionException ( \"Error on executing command\" ) , e ) ; } return recs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the value stored under the given entry index in this bucket . [CODESPLIT] List < ORID > getValues ( final int entryIndex ) { assert isLeaf ; int entryPosition = getIntValue ( entryIndex * OIntegerSerializer . INT_SIZE + POSITIONS_ARRAY_OFFSET ) ; int nextItem = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE ; // skip key if ( encryption == null ) { entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedSize = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE + encryptedSize ; } int clusterId = getShortValue ( entryPosition ) ; long clusterPosition = getLongValue ( entryPosition + OShortSerializer . SHORT_SIZE ) ; final List < ORID > results = new ArrayList <> ( 8 ) ; results . add ( new ORecordId ( clusterId , clusterPosition ) ) ; while ( nextItem > 0 ) { final int nextNextItem = getIntValue ( nextItem ) ; final int nextItemSize = 0xFF & getByteValue ( nextItem + OIntegerSerializer . INT_SIZE ) ; for ( int i = 0 ; i < nextItemSize ; i ++ ) { clusterId = getShortValue ( nextItem + OIntegerSerializer . INT_SIZE + OByteSerializer . BYTE_SIZE + i * RID_SIZE ) ; clusterPosition = getLongValue ( nextItem + OIntegerSerializer . INT_SIZE + OShortSerializer . SHORT_SIZE + OByteSerializer . BYTE_SIZE + i * RID_SIZE ) ; results . add ( new ORecordId ( clusterId , clusterPosition ) ) ; } nextItem = nextNextItem ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified cluster to the class if it doesn t already exist . [CODESPLIT] public void createCluster ( final String className , final String clusterName ) { final ODatabaseDocumentInternal currentDB = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final ODatabaseDocumentInternal sysdb = openSystemDatabase ( ) ; try { if ( ! sysdb . existsCluster ( clusterName ) ) { OSchema schema = sysdb . getMetadata ( ) . getSchema ( ) ; OClass cls = schema . getClass ( className ) ; if ( cls != null ) { cls . addCluster ( clusterName ) ; } else { OLogManager . instance ( ) . error ( this , \"createCluster() Class name %s does not exist\" , null , className ) ; } } } finally { sysdb . close ( ) ; } } finally { if ( currentDB != null ) ODatabaseRecordThreadLocal . instance ( ) . set ( currentDB ) ; else ODatabaseRecordThreadLocal . instance ( ) . remove ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all records belonging to specified cluster [CODESPLIT] public void freeCluster ( final int cid ) { final Set < ORID > toRemove = new HashSet < ORID > ( underlying . size ( ) / 2 ) ; final Set < ORID > keys = new HashSet < ORID > ( underlying . keys ( ) ) ; for ( final ORID id : keys ) if ( id . getClusterId ( ) == cid ) toRemove . add ( id ) ; for ( final ORID ridToRemove : toRemove ) underlying . remove ( ridToRemove ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "All operations running at cache initialization stage [CODESPLIT] public void startup ( ) { underlying . startup ( ) ; Orient . instance ( ) . getProfiler ( ) . registerHookValue ( profilerPrefix + \"current\" , \"Number of entries in cache\" , METRIC_TYPE . SIZE , new OProfilerHookValue ( ) { public Object getValue ( ) { return getSize ( ) ; } } , profilerMetadataPrefix + \"current\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "All operations running at cache destruction stage [CODESPLIT] public void shutdown ( ) { underlying . shutdown ( ) ; if ( Orient . instance ( ) . getProfiler ( ) != null ) { Orient . instance ( ) . getProfiler ( ) . unregisterHookValue ( profilerPrefix + \"enabled\" ) ; Orient . instance ( ) . getProfiler ( ) . unregisterHookValue ( profilerPrefix + \"current\" ) ; Orient . instance ( ) . getProfiler ( ) . unregisterHookValue ( profilerPrefix + \"max\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Result set with a single result ; [CODESPLIT] public static OScriptResultSet singleton ( Object entity , OScriptTransformer transformer ) { return new OScriptResultSet ( Collections . singletonList ( entity ) . iterator ( ) , transformer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grant a permission to the resource . [CODESPLIT] public ORole grant ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific , final int iOperation ) { ORule rule = rules . get ( resourceGeneric ) ; if ( rule == null ) { rule = new ORule ( resourceGeneric , null , null ) ; rules . put ( resourceGeneric , rule ) ; } rule . grantAccess ( resourceSpecific , iOperation ) ; rules . put ( resourceGeneric , rule ) ; updateRolesDocumentContent ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Revoke a permission to the resource . [CODESPLIT] public ORole revoke ( final ORule . ResourceGeneric resourceGeneric , String resourceSpecific , final int iOperation ) { if ( iOperation == PERMISSION_NONE ) return this ; ORule rule = rules . get ( resourceGeneric ) ; if ( rule == null ) { rule = new ORule ( resourceGeneric , null , null ) ; rules . put ( resourceGeneric , rule ) ; } rule . revokeAccess ( resourceSpecific , iOperation ) ; rules . put ( resourceGeneric , rule ) ; updateRolesDocumentContent ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Float object , ByteBuffer buffer , Object ... hints ) { buffer . putInt ( Float . floatToIntBits ( object ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Float deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return Float . intBitsToFloat ( walChanges . getIntValue ( buffer , offset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the current record . [CODESPLIT] public boolean result ( final Object iRecord ) { final ORecordAbstract record = ( ( OIdentifiable ) iRecord ) . getRecord ( ) ; if ( record instanceof ODocument && compiledFilter != null && ! Boolean . TRUE . equals ( this . compiledFilter . evaluate ( record , ( ODocument ) record , getContext ( ) ) ) ) { return true ; } try { if ( record . getIdentity ( ) . isValid ( ) ) { if ( returning . equalsIgnoreCase ( \"BEFORE\" ) ) allDeletedRecords . add ( record ) ; // RESET VERSION TO DISABLE MVCC AVOIDING THE CONCURRENT EXCEPTION IF LOCAL CACHE IS NOT UPDATED\r //        ORecordInternal.setVersion(record, -1);\r if ( ! unsafe && record instanceof ODocument ) { // CHECK IF ARE VERTICES OR EDGES\r final OClass cls = ( ( ODocument ) record ) . getSchemaClass ( ) ; if ( cls != null ) { if ( cls . isSubClassOf ( \"V\" ) ) // FOUND VERTEX\r throw new OCommandExecutionException ( \"'DELETE' command cannot delete vertices. Use 'DELETE VERTEX' command instead, or apply the 'UNSAFE' keyword to force it\" ) ; else if ( cls . isSubClassOf ( \"E\" ) ) // FOUND EDGE\r throw new OCommandExecutionException ( \"'DELETE' command cannot delete edges. Use 'DELETE EDGE' command instead, or apply the 'UNSAFE' keyword to force it\" ) ; } } record . delete ( ) ; recordCount ++ ; return true ; } return false ; } finally { if ( lockStrategy . equalsIgnoreCase ( \"RECORD\" ) ) ( ( OAbstractPaginatedStorage ) getDatabase ( ) . getStorage ( ) ) . releaseWriteLock ( record . getIdentity ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a step that transforms a normal OResult in a specific object that under setProperty () updates the actual OIdentifiable [CODESPLIT] private void convertToModifiableResult ( OUpdateExecutionPlan plan , OCommandContext ctx , boolean profilingEnabled ) { plan . chain ( new ConvertToUpdatableResultStep ( ctx , profilingEnabled ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Integer object , ByteBuffer buffer , Object ... hints ) { buffer . putInt ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Integer deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getIntValue ( buffer , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds parameters . [CODESPLIT] public void bindParameters ( final Map < Object , Object > iArgs ) { if ( parameterItems == null || iArgs == null || iArgs . size ( ) == 0 ) return ; for ( int i = 0 ; i < parameterItems . size ( ) ; i ++ ) { OSQLFilterItemParameter value = parameterItems . get ( i ) ; if ( \"?\" . equals ( value . getName ( ) ) ) { value . setValue ( iArgs . get ( i ) ) ; } else { value . setValue ( iArgs . get ( value . getName ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the item requested . [CODESPLIT] private void convert ( final int iIndex ) { if ( converted ) return ; Object o = list . get ( iIndex ) ; if ( o == null ) { o = serializedList . get ( iIndex ) ; list . set ( iIndex , OObjectEntitySerializer . deserializeFieldValue ( deserializeClass , o ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO refactor this method to receive the item . [CODESPLIT] protected Iterable < OResultInternal > traversePatternEdge ( OIdentifiable startingPoint , OCommandContext iCommandContext ) { Iterable possibleResults = null ; if ( this . item . getFilter ( ) != null ) { String alias = getEndpointAlias ( ) ; Object matchedNodes = iCommandContext . getVariable ( MatchPrefetchStep . PREFETCHED_MATCH_ALIAS_PREFIX + alias ) ; if ( matchedNodes != null ) { if ( matchedNodes instanceof Iterable ) { possibleResults = ( Iterable ) matchedNodes ; } else { possibleResults = Collections . singleton ( matchedNodes ) ; } } } Object prevCurrent = iCommandContext . getVariable ( \"$current\" ) ; iCommandContext . setVariable ( \"$current\" , startingPoint ) ; Object qR ; try { qR = this . item . getMethod ( ) . execute ( startingPoint , possibleResults , iCommandContext ) ; } finally { iCommandContext . setVariable ( \"$current\" , prevCurrent ) ; } if ( qR == null ) { return Collections . EMPTY_LIST ; } if ( qR instanceof OIdentifiable ) { return Collections . singleton ( new OResultInternal ( ( OIdentifiable ) qR ) ) ; } if ( qR instanceof Iterable ) { final Iterator < Object > iter = ( ( Iterable ) qR ) . iterator ( ) ; Iterable < OResultInternal > result = ( ) -> new Iterator < OResultInternal > ( ) { private OResultInternal nextElement ; @ Override public boolean hasNext ( ) { if ( nextElement == null ) { fetchNext ( ) ; } return nextElement != null ; } @ Override public OResultInternal next ( ) { if ( nextElement == null ) { fetchNext ( ) ; } if ( nextElement == null ) { throw new IllegalStateException ( ) ; } OResultInternal res = nextElement ; nextElement = null ; return res ; } public void fetchNext ( ) { while ( iter . hasNext ( ) ) { Object o = iter . next ( ) ; if ( o instanceof OIdentifiable ) { nextElement = new OResultInternal ( ( OIdentifiable ) o ) ; break ; } else if ( o instanceof OResultInternal ) { nextElement = ( OResultInternal ) o ; break ; } else if ( o == null ) { continue ; } else { throw new UnsupportedOperationException ( ) ; } } } } ; return result ; } return Collections . EMPTY_LIST ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the item requested . [CODESPLIT] private void convert ( final int iIndex ) { if ( converted ) return ; Object o = list . get ( iIndex ) ; if ( o == null ) { o = serializedList . get ( iIndex ) ; if ( o instanceof Number ) o = enumClass . getEnumConstants ( ) [ ( ( Number ) o ) . intValue ( ) ] ; else o = Enum . valueOf ( enumClass , o . toString ( ) ) ; list . set ( iIndex , ( TYPE ) o ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a string returning the closer type . Numbers by default are INTEGER if haven t decimal separator otherwise FLOAT . To treat all the number types numbers are postponed with a character that tells the type : b = byte s = short l = long f = float d = double t = date . [CODESPLIT] public static OType getType ( final String iValue ) { if ( iValue . length ( ) == 0 ) return null ; final char firstChar = iValue . charAt ( 0 ) ; if ( firstChar == ORID . PREFIX ) // RID\r return OType . LINK ; else if ( firstChar == ' ' || firstChar == ' ' ) return OType . STRING ; else if ( firstChar == OStringSerializerHelper . BINARY_BEGINEND ) return OType . BINARY ; else if ( firstChar == OStringSerializerHelper . EMBEDDED_BEGIN ) return OType . EMBEDDED ; else if ( firstChar == OStringSerializerHelper . LIST_BEGIN ) return OType . EMBEDDEDLIST ; else if ( firstChar == OStringSerializerHelper . SET_BEGIN ) return OType . EMBEDDEDSET ; else if ( firstChar == OStringSerializerHelper . MAP_BEGIN ) return OType . EMBEDDEDMAP ; else if ( firstChar == OStringSerializerHelper . CUSTOM_TYPE ) return OType . CUSTOM ; // BOOLEAN?\r if ( iValue . equalsIgnoreCase ( \"true\" ) || iValue . equalsIgnoreCase ( \"false\" ) ) return OType . BOOLEAN ; // NUMBER OR STRING?\r boolean integer = true ; for ( int index = 0 ; index < iValue . length ( ) ; ++ index ) { final char c = iValue . charAt ( index ) ; if ( c < ' ' || c > ' ' ) if ( ( index == 0 && ( c == ' ' || c == ' ' ) ) ) continue ; else if ( c == DECIMAL_SEPARATOR ) integer = false ; else { if ( index > 0 ) if ( ! integer && c == ' ' ) { // CHECK FOR SCIENTIFIC NOTATION\r if ( index < iValue . length ( ) ) { if ( iValue . charAt ( index + 1 ) == ' ' ) // JUMP THE DASH IF ANY (NOT MANDATORY)\r index ++ ; continue ; } } else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . FLOAT ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DECIMAL ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . LONG ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DOUBLE ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . BYTE ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DATE ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . DATETIME ; else if ( c == ' ' ) return index != ( iValue . length ( ) - 1 ) ? OType . STRING : OType . SHORT ; else if ( c == ' ' ) { //eg. 1e-06\r try { Double . parseDouble ( iValue ) ; return OType . DOUBLE ; } catch ( Exception ignore ) { return OType . STRING ; } } return OType . STRING ; } } if ( integer ) { // AUTO CONVERT TO LONG IF THE INTEGER IS TOO BIG\r final int numberLength = iValue . length ( ) ; if ( numberLength > MAX_INTEGER_DIGITS || ( numberLength == MAX_INTEGER_DIGITS && iValue . compareTo ( MAX_INTEGER_AS_STRING ) > 0 ) ) return OType . LONG ; return OType . INTEGER ; } // CHECK IF THE DECIMAL NUMBER IS A FLOAT OR DOUBLE\r final double dou = Double . parseDouble ( iValue ) ; if ( dou <= Float . MAX_VALUE && dou >= Float . MIN_VALUE && Double . toString ( dou ) . equals ( Float . toString ( ( float ) dou ) ) && new Double ( new Double ( dou ) . floatValue ( ) ) . doubleValue ( ) == dou ) { return OType . FLOAT ; } else if ( ! new Double ( dou ) . toString ( ) . equals ( iValue ) ) { return OType . DECIMAL ; } return OType . DOUBLE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the field type char returning the closer type . Default is STRING . b = binary if iValue . length () > = 4 b = byte if iValue . length () < = 3 s = short l = long f = float d = double a = date t = datetime [CODESPLIT] public static OType getType ( final String iValue , final char iCharType ) { if ( iCharType == ' ' ) return OType . FLOAT ; else if ( iCharType == ' ' ) return OType . DECIMAL ; else if ( iCharType == ' ' ) return OType . LONG ; else if ( iCharType == ' ' ) return OType . DOUBLE ; else if ( iCharType == ' ' ) { if ( iValue . length ( ) >= 1 && iValue . length ( ) <= 3 ) return OType . BYTE ; else return OType . BINARY ; } else if ( iCharType == ' ' ) return OType . DATE ; else if ( iCharType == ' ' ) return OType . DATETIME ; else if ( iCharType == ' ' ) return OType . SHORT ; else if ( iCharType == ' ' ) return OType . EMBEDDEDSET ; else if ( iCharType == ' ' ) return OType . LINKBAG ; else if ( iCharType == ' ' ) return OType . LINKLIST ; else if ( iCharType == ' ' ) return OType . LINKMAP ; else if ( iCharType == ' ' ) return OType . LINK ; else if ( iCharType == ' ' ) return OType . LINKSET ; else if ( iCharType == ' ' ) return OType . LINK ; else if ( iCharType == ' ' ) return OType . CUSTOM ; return OType . STRING ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a string returning the value with the closer type . Numbers by default are INTEGER if haven t decimal separator otherwise FLOAT . To treat all the number types numbers are postponed with a character that tells the type : b = byte s = short l = long f = float d = double t = date . If starts with # it s a RecordID . Most of the code is equals to getType () but has been copied to speed - up it . [CODESPLIT] public static Object getTypeValue ( final String iValue ) { if ( iValue == null || iValue . equalsIgnoreCase ( \"NULL\" ) ) return null ; if ( iValue . length ( ) == 0 ) return \"\" ; if ( iValue . length ( ) > 1 ) if ( iValue . charAt ( 0 ) == ' ' && iValue . charAt ( iValue . length ( ) - 1 ) == ' ' ) // STRING\r return OStringSerializerHelper . decode ( iValue . substring ( 1 , iValue . length ( ) - 1 ) ) ; else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . BINARY_BEGINEND && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . BINARY_BEGINEND ) // STRING\r return OStringSerializerHelper . getBinaryContent ( iValue ) ; else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . LIST_BEGIN && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . LIST_END ) { // LIST\r final ArrayList < String > coll = new ArrayList < String > ( ) ; OStringSerializerHelper . getCollection ( iValue , 0 , coll , OStringSerializerHelper . LIST_BEGIN , OStringSerializerHelper . LIST_END , OStringSerializerHelper . COLLECTION_SEPARATOR ) ; return coll ; } else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . SET_BEGIN && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . SET_END ) { // SET\r final Set < String > coll = new HashSet < String > ( ) ; OStringSerializerHelper . getCollection ( iValue , 0 , coll , OStringSerializerHelper . SET_BEGIN , OStringSerializerHelper . SET_END , OStringSerializerHelper . COLLECTION_SEPARATOR ) ; return coll ; } else if ( iValue . charAt ( 0 ) == OStringSerializerHelper . MAP_BEGIN && iValue . charAt ( iValue . length ( ) - 1 ) == OStringSerializerHelper . MAP_END ) { // MAP\r return OStringSerializerHelper . getMap ( iValue ) ; } if ( iValue . charAt ( 0 ) == ORID . PREFIX ) // RID\r return new ORecordId ( iValue ) ; boolean integer = true ; char c ; boolean stringStarBySign = false ; for ( int index = 0 ; index < iValue . length ( ) ; ++ index ) { c = iValue . charAt ( index ) ; if ( c < ' ' || c > ' ' ) { if ( ( index == 0 && ( c == ' ' || c == ' ' ) ) ) { stringStarBySign = true ; continue ; } else if ( c == DECIMAL_SEPARATOR ) integer = false ; else { if ( index > 0 ) { if ( ! integer && c == ' ' ) { // CHECK FOR SCIENTIFIC NOTATION\r if ( index < iValue . length ( ) ) index ++ ; if ( iValue . charAt ( index ) == ' ' ) continue ; } final String v = iValue . substring ( 0 , index ) ; if ( c == ' ' ) return new Float ( v ) ; else if ( c == ' ' ) return new BigDecimal ( v ) ; else if ( c == ' ' ) return new Long ( v ) ; else if ( c == ' ' ) return new Double ( v ) ; else if ( c == ' ' ) return new Byte ( v ) ; else if ( c == ' ' || c == ' ' ) return new Date ( Long . parseLong ( v ) ) ; else if ( c == ' ' ) return new Short ( v ) ; } return iValue ; } } else if ( stringStarBySign ) { stringStarBySign = false ; } } if ( stringStarBySign ) return iValue ; if ( integer ) { try { return new Integer ( iValue ) ; } catch ( NumberFormatException ignore ) { return new Long ( iValue ) ; } } else if ( \"NaN\" . equals ( iValue ) || \"Infinity\" . equals ( iValue ) ) // NaN and Infinity CANNOT BE MANAGED BY BIG-DECIMAL TYPE\r return new Double ( iValue ) ; else return new BigDecimal ( iValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increments the popularity of the element if it does not exceed the maximum ( 15 ) . The popularity of all elements will be periodically down sampled when the observed events exceeds a threshold . This process provides a frequency aging to allow expired long term entries to fade away . [CODESPLIT] @ Override public void increment ( int hash ) { hash = spread ( hash ) ; final int start = ( hash & 3 ) << 2 ; // Loop unrolling improves throughput by 5m ops/s final int index0 = indexOf ( hash , 0 ) ; final int index1 = indexOf ( hash , 1 ) ; final int index2 = indexOf ( hash , 2 ) ; final int index3 = indexOf ( hash , 3 ) ; boolean added = incrementAt ( index0 , start ) ; added |= incrementAt ( index1 , start + 1 ) ; added |= incrementAt ( index2 , start + 2 ) ; added |= incrementAt ( index3 , start + 3 ) ; if ( added && ( ++ size == sampleSize ) ) { reset ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increments the specified counter by 1 if it is not already at the maximum value ( 15 ) . [CODESPLIT] private boolean incrementAt ( final int i , final int j ) { final int offset = j << 2 ; final long mask = ( 0xf L << offset ) ; if ( ( table [ i ] & mask ) != mask ) { table [ i ] += ( 1L << offset ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduces every counter by half of its original value . [CODESPLIT] private void reset ( ) { int count = 0 ; for ( int i = 0 ; i < table . length ; i ++ ) { count += Long . bitCount ( table [ i ] & ONE_MASK ) ; table [ i ] = ( table [ i ] >>> 1 ) & RESET_MASK ; } size = ( size >>> 1 ) - ( count >>> 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the table index for the counter at the specified depth . [CODESPLIT] private int indexOf ( final int item , final int i ) { long hash = SEED [ i ] * item ; hash += hash >> 32 ; return ( ( int ) hash ) & tableMask ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a supplemental hash function to a given hashCode which defends against poor quality hash functions . [CODESPLIT] private int spread ( int x ) { x = ( ( x >>> 16 ) ^ x ) * 0x45d9f3b ; x = ( ( x >>> 16 ) ^ x ) * randomSeed ; return ( x >>> 16 ) ^ x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an index on this property . Indexes speed up queries but slow down insert and update operations . For massive inserts we suggest to remove the index make the massive insert and recreate it . [CODESPLIT] public OIndex < ? > createIndex ( final String iType ) { acquireSchemaReadLock ( ) ; try { return owner . createIndex ( getFullName ( ) , iType , globalRef . getName ( ) ) ; } finally { releaseSchemaReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the index on property [CODESPLIT] @ Deprecated public OPropertyImpl dropIndexes ( ) { getDatabase ( ) . checkSecurity ( ORule . ResourceGeneric . SCHEMA , ORole . PERMISSION_DELETE ) ; acquireSchemaReadLock ( ) ; try { final OIndexManager indexManager = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) ; final ArrayList < OIndex < ? > > relatedIndexes = new ArrayList < OIndex < ? > > ( ) ; for ( final OIndex < ? > index : indexManager . getClassIndexes ( owner . getName ( ) ) ) { final OIndexDefinition definition = index . getDefinition ( ) ; if ( OCollections . indexOf ( definition . getFields ( ) , globalRef . getName ( ) , new OCaseInsentiveComparator ( ) ) > - 1 ) { if ( definition instanceof OPropertyIndexDefinition ) { relatedIndexes . add ( index ) ; } else { throw new IllegalArgumentException ( \"This operation applicable only for property indexes. \" + index . getName ( ) + \" is \" + index . getDefinition ( ) ) ; } } } for ( final OIndex < ? > index : relatedIndexes ) getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( index . getName ( ) ) ; return this ; } finally { releaseSchemaReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first index defined for the property . [CODESPLIT] @ Deprecated public OIndex < ? > getIndex ( ) { acquireSchemaReadLock ( ) ; try { Set < OIndex < ? > > indexes = owner . getInvolvedIndexes ( globalRef . getName ( ) ) ; if ( indexes != null && ! indexes . isEmpty ( ) ) return indexes . iterator ( ) . next ( ) ; return null ; } finally { releaseSchemaReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the linked class in lazy mode because while unmarshalling the class could be not loaded yet . [CODESPLIT] public OClass getLinkedClass ( ) { acquireSchemaReadLock ( ) ; try { if ( linkedClass == null && linkedClassName != null ) linkedClass = owner . owner . getClass ( linkedClassName ) ; return linkedClass ; } finally { releaseSchemaReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clazz == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; // CREATE VERTEX DOES NOT HAVE TO BE IN TX final OVertex vertex = getDatabase ( ) . newVertex ( clazz ) ; if ( fields != null ) // EVALUATE FIELDS for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( vertex . getRecord ( ) , null , context ) ) ; } OSQLHelper . bindParameters ( vertex . getRecord ( ) , fields , new OCommandParameters ( iArgs ) , context ) ; if ( content != null ) ( ( ODocument ) vertex . getRecord ( ) ) . merge ( content , true , false ) ; if ( clusterName != null ) vertex . save ( clusterName ) ; else vertex . save ( ) ; return vertex . getRecord ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add new key value to the list of already registered values . <p > If passed in value is { @link OCompositeKey } itself then its values will be copied in current index . But key itself will not be added . [CODESPLIT] public void addKey ( final Object key ) { if ( key instanceof OCompositeKey ) { final OCompositeKey compositeKey = ( OCompositeKey ) key ; for ( final Object inKey : compositeKey . keys ) { addKey ( inKey ) ; } } else { keys . add ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new index . <p > May require quite a long time if big amount of data should be indexed . [CODESPLIT] public OIndex < ? > createIndex ( ODatabaseDocumentInternal database , final String iName , String type , final OIndexDefinition indexDefinition , final int [ ] clusterIdsToIndex , OProgressListener progressListener , ODocument metadata , String algorithm ) { if ( database . getTransaction ( ) . isActive ( ) ) throw new IllegalStateException ( \"Cannot create a new index inside a transaction\" ) ; final Character c = OSchemaShared . checkFieldNameIfValid ( iName ) ; if ( c != null ) throw new IllegalArgumentException ( \"Invalid index name '\" + iName + \"'. Character '\" + c + \"' is invalid\" ) ; if ( indexDefinition == null ) { throw new IllegalArgumentException ( \"Index definition cannot be null\" ) ; } final Locale locale = getServerLocale ( ) ; type = type . toUpperCase ( locale ) ; if ( algorithm == null ) { algorithm = OIndexes . chooseDefaultIndexAlgorithm ( type ) ; } final String valueContainerAlgorithm = chooseContainerAlgorithm ( type ) ; final OIndexInternal < ? > index ; acquireExclusiveLock ( ) ; try { if ( indexes . containsKey ( iName ) ) throw new OIndexException ( \"Index with name \" + iName + \" already exists.\" ) ; // manual indexes are always durable if ( clusterIdsToIndex == null || clusterIdsToIndex . length == 0 ) { if ( metadata == null ) metadata = new ODocument ( ) . setTrackingChanges ( false ) ; final Object durable = metadata . field ( \"durableInNonTxMode\" ) ; if ( ! ( durable instanceof Boolean ) ) metadata . field ( \"durableInNonTxMode\" , true ) ; if ( metadata . field ( \"trackMode\" ) == null ) metadata . field ( \"trackMode\" , \"FULL\" ) ; } index = OIndexes . createIndex ( getStorage ( ) , iName , type , algorithm , valueContainerAlgorithm , metadata , - 1 ) ; if ( progressListener == null ) // ASSIGN DEFAULT PROGRESS LISTENER progressListener = new OIndexRebuildOutputListener ( index ) ; final Set < String > clustersToIndex = findClustersByIds ( clusterIdsToIndex , database ) ; Object ignoreNullValues = metadata == null ? null : metadata . field ( \"ignoreNullValues\" ) ; if ( Boolean . TRUE . equals ( ignoreNullValues ) ) { indexDefinition . setNullValuesIgnored ( true ) ; } else if ( Boolean . FALSE . equals ( ignoreNullValues ) ) { indexDefinition . setNullValuesIgnored ( false ) ; } else { indexDefinition . setNullValuesIgnored ( database . getConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . INDEX_IGNORE_NULL_VALUES_DEFAULT ) ) ; } // decide which cluster to use (\"index\" - for automatic and \"manindex\" for manual) final String clusterName = indexDefinition . getClassName ( ) != null ? defaultClusterName : manualClusterName ; index . create ( iName , indexDefinition , clusterName , clustersToIndex , true , progressListener ) ; addIndexInternal ( index ) ; if ( metadata != null ) { final ODocument config = index . getConfiguration ( ) ; config . field ( \"metadata\" , metadata , OType . EMBEDDED ) ; } setDirty ( ) ; save ( ) ; } finally { releaseExclusiveLock ( ) ; } notifyInvolvedClasses ( database , clusterIdsToIndex ) ; return preProcessBeforeReturn ( database , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds POJO to ODocument . [CODESPLIT] @ Override public ODocument toStream ( ) { internalAcquireExclusiveLock ( ) ; try { document . setInternalStatus ( ORecordElement . STATUS . UNMARSHALLING ) ; try { final OTrackedSet < ODocument > indexes = new OTrackedSet <> ( document ) ; for ( final OIndex < ? > i : this . indexes . values ( ) ) { indexes . add ( ( ( OIndexInternal < ? > ) i ) . updateConfiguration ( ) ) ; } document . field ( CONFIG_INDEXES , indexes , OType . EMBEDDEDSET ) ; } finally { document . setInternalStatus ( ORecordElement . STATUS . LOADED ) ; } document . setDirty ( ) ; return document ; } finally { internalReleaseExclusiveLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the server role between MASTER ( default ) and REPLICA . [CODESPLIT] public void setServerRole ( final String iServerName , final ROLES role ) { synchronized ( configuration ) { ODocument servers = configuration . field ( SERVERS ) ; if ( servers == null ) { servers = new ODocument ( ) ; configuration . field ( SERVERS , servers , OType . EMBEDDED ) ; } servers . field ( iServerName , role ) ; incrementVersion ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a server in the configuration . It replaces all the tags &lt ; NEW_NODE&gt ; with the new server name<br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public List < String > addNewNodeInServerList ( final String iNode ) { synchronized ( configuration ) { final List < String > changedPartitions = new ArrayList < String > ( ) ; // ADD THE NODE IN CONFIGURATION. LOOK FOR $newNode TAG for ( String clusterName : getClusterNames ( ) ) { final List < String > partitions = getClusterConfiguration ( clusterName ) . field ( SERVERS ) ; if ( partitions != null ) { final int newNodePos = partitions . indexOf ( OModifiableDistributedConfiguration . NEW_NODE_TAG ) ; if ( newNodePos > - 1 && ! partitions . contains ( iNode ) ) { partitions . add ( newNodePos , iNode ) ; changedPartitions . add ( clusterName ) ; } } } if ( ! changedPartitions . isEmpty ( ) ) { // INCREMENT VERSION incrementVersion ( ) ; if ( ! getRegisteredServers ( ) . contains ( iNode ) ) { if ( getNewNodeStrategy ( ) == NEW_NODE_STRATEGIES . STATIC ) { // REGISTER THE SERVER AS STATIC AND INCREMENT VERSION setServerRole ( iNode , getServerRole ( \"*\" ) ) ; } } return changedPartitions ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the server as owner for the given cluster . The owner server is the first in server list . <br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public void setServerOwner ( final String iClusterName , final String iServerName ) { if ( iClusterName == null ) throw new IllegalArgumentException ( \"cluster name cannot be null\" ) ; synchronized ( configuration ) { final ODocument clusters = configuration . field ( CLUSTERS ) ; ODocument cluster = clusters . field ( iClusterName ) ; if ( cluster == null ) // CREATE IT cluster = createCluster ( iClusterName ) ; else { // CHECK IF THE OWNER IS ALREADY CONFIGURED final String owner = cluster . field ( OWNER ) ; if ( owner != null && ! iServerName . equalsIgnoreCase ( owner ) ) throw new ODistributedException ( \"Cannot overwrite ownership of cluster '\" + iClusterName + \"' to the server '\" + iServerName + \"', because server '\" + owner + \"' was already configured as owner\" ) ; } List < String > serverList = getClusterConfiguration ( iClusterName ) . field ( SERVERS ) ; if ( serverList == null ) { serverList = initClusterServers ( cluster ) ; } if ( ! serverList . isEmpty ( ) && serverList . get ( 0 ) . equals ( iServerName ) ) // ALREADY OWNER return ; // REMOVE THE NODE IF ANY boolean removed = false ; for ( Iterator < String > it = serverList . iterator ( ) ; it . hasNext ( ) ; ) { if ( it . next ( ) . equals ( iServerName ) ) { it . remove ( ) ; removed = true ; break ; } } if ( ! removed ) throw new ODistributedException ( \"Cannot set ownership of cluster '\" + iClusterName + \"' to the server '\" + iServerName + \"', because the server has no that cluster (sharding)\" ) ; // ADD THE NODE AS FIRST OF THE LIST = MASTER serverList . add ( 0 , iServerName ) ; incrementVersion ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a server from the list . <br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public List < String > removeServer ( final String iNode ) { synchronized ( configuration ) { final List < String > changedPartitions = new ArrayList < String > ( ) ; for ( String clusterName : getClusterNames ( ) ) { final Collection < String > nodes = getClusterConfiguration ( clusterName ) . field ( SERVERS ) ; if ( nodes != null ) { for ( String node : nodes ) { if ( node . equals ( iNode ) ) { // FOUND: REMOVE IT nodes . remove ( node ) ; changedPartitions . add ( clusterName ) ; break ; } } } } if ( ! changedPartitions . isEmpty ( ) ) { incrementVersion ( ) ; return changedPartitions ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a server offline . It assures the offline server is never on top of the list . <br > NOTE : It must be executed in distributed database lock . [CODESPLIT] public List < String > setServerOffline ( final String iNode , final String newLockManagerServer ) { final List < String > changedPartitions = new ArrayList < String > ( ) ; final String [ ] clusters = getClusterNames ( ) ; synchronized ( configuration ) { for ( String clusterName : clusters ) { final List < String > nodes = getClusterConfiguration ( clusterName ) . field ( SERVERS ) ; if ( nodes != null && nodes . size ( ) > 1 ) { for ( String node : nodes ) { if ( node . equals ( iNode ) ) { // FOUND: PUT THE NODE AT THE END (BEFORE ANY TAG <NEW_NODE>) nodes . remove ( node ) ; final boolean newNodeRemoved = nodes . remove ( NEW_NODE_TAG ) ; nodes . add ( node ) ; if ( newNodeRemoved ) // REINSERT NEW NODE TAG AT THE END nodes . add ( NEW_NODE_TAG ) ; if ( newLockManagerServer != null ) { // ASSURE THE NEW LOCK MANAGER IS THE FIRST IN THE LIST if ( nodes . remove ( newLockManagerServer ) ) nodes . add ( 0 , newLockManagerServer ) ; } changedPartitions . add ( clusterName ) ; break ; } } } } if ( ! changedPartitions . isEmpty ( ) ) { incrementVersion ( ) ; return changedPartitions ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void configure ( OStorage iStorage , int iId , String iClusterName , Object ... iParameters ) { id = iId ; name = iClusterName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void configure ( OStorage iStorage , OStorageClusterConfiguration iConfig ) throws IOException { id = iConfig . getId ( ) ; name = iConfig . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the current event listener . [CODESPLIT] protected void removeListener ( final ORecordListener listener ) { if ( _listeners != null ) { _listeners . remove ( listener ) ; if ( _listeners . isEmpty ( ) ) _listeners = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a distributed database instance if not defined yet . [CODESPLIT] public ODistributedDatabaseImpl registerDatabase ( final String iDatabaseName , ODistributedConfiguration cfg ) { final ODistributedDatabaseImpl ddb = databases . get ( iDatabaseName ) ; if ( ddb != null ) return ddb ; return new ODistributedDatabaseImpl ( manager , this , iDatabaseName , cfg , manager . getServerInstance ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Not synchronized it s called when a message arrives [CODESPLIT] public void dispatchResponseToThread ( final ODistributedResponse response ) { try { final long msgId = response . getRequestId ( ) . getMessageId ( ) ; // GET ASYNCHRONOUS MSG MANAGER IF ANY final ODistributedResponseManager asynchMgr = responsesByRequestIds . get ( msgId ) ; if ( asynchMgr == null ) { if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , manager . getLocalNodeName ( ) , response . getExecutorNodeName ( ) , DIRECTION . IN , \"received response for message %d after the timeout (%dms)\" , msgId , OGlobalConfiguration . DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT . getValueAsLong ( ) ) ; } else if ( asynchMgr . collectResponse ( response ) ) { // ALL RESPONSE RECEIVED, REMOVE THE RESPONSE MANAGER WITHOUT WAITING THE PURGE THREAD REMOVE THEM FOR TIMEOUT responsesByRequestIds . remove ( msgId ) ; } } finally { Orient . instance ( ) . getProfiler ( ) . updateCounter ( \"distributed.node.msgReceived\" , \"Number of replication messages received in current node\" , + 1 , \"distributed.node.msgReceived\" ) ; Orient . instance ( ) . getProfiler ( ) . updateCounter ( \"distributed.node.\" + response . getExecutorNodeName ( ) + \".msgReceived\" , \"Number of replication messages received in current node from a node\" , + 1 , \"distributed.node.*.msgReceived\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a response manager because in timeout . [CODESPLIT] public void timeoutRequest ( final long msgId ) { final ODistributedResponseManager asynchMgr = responsesByRequestIds . remove ( msgId ) ; if ( asynchMgr != null ) asynchMgr . timeout ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void internalCreate ( OrientDBConfig config , OSharedContext ctx ) { this . sharedContext = ctx ; this . status = STATUS . OPEN ; // THIS IF SHOULDN'T BE NEEDED, CREATE HAPPEN ONLY IN EMBEDDED applyAttributes ( config ) ; applyListeners ( config ) ; metadata = new OMetadataDefault ( this ) ; installHooksEmbedded ( ) ; createMetadata ( ctx ) ; if ( this . getMetadata ( ) . getCommandCache ( ) . isEnabled ( ) ) registerHook ( new OCommandCacheHook ( this ) , ORecordHook . HOOK_POSITION . REGULAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of current database if it s open . The returned instance can be used by another thread without affecting current instance . The database copy is not set in thread local . [CODESPLIT] public ODatabaseDocumentInternal copy ( ) { ODatabaseDocumentEmbedded database = new ODatabaseDocumentEmbedded ( getSharedContext ( ) . getStorage ( ) ) ; database . init ( config , this . sharedContext ) ; String user ; if ( getUser ( ) != null ) { user = getUser ( ) . getName ( ) ; } else { user = null ; } database . internalOpen ( user , null , false ) ; database . callOnOpenListeners ( ) ; this . activateOnCurrentThread ( ) ; return database ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is internal it can be subject to signature change or be removed do not use . [CODESPLIT] public void executeDeleteRecord ( OIdentifiable record , final int iVersion , final boolean iRequired , final OPERATION_MODE iMode , boolean prohibitTombstones ) { checkOpenness ( ) ; checkIfActive ( ) ; final ORecordId rid = ( ORecordId ) record . getIdentity ( ) ; if ( rid == null ) throw new ODatabaseException ( \"Cannot delete record because it has no identity. Probably was created from scratch or contains projections of fields rather than a full record\" ) ; if ( ! rid . isValid ( ) ) return ; record = record . getRecord ( ) ; if ( record == null ) return ; final OMicroTransaction microTx = beginMicroTransaction ( ) ; try { microTx . deleteRecord ( record . getRecord ( ) , iMode ) ; } catch ( Exception e ) { endMicroTransaction ( false ) ; throw e ; } endMicroTransaction ( true ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is internal it can be subject to signature change or be removed do not use . [CODESPLIT] public < RET extends ORecord > RET executeReadRecord ( final ORecordId rid , ORecord iRecord , final int recordVersion , final String fetchPlan , final boolean ignoreCache , final boolean iUpdateCache , final boolean loadTombstones , final OStorage . LOCKING_STRATEGY lockingStrategy , RecordReader recordReader ) { checkOpenness ( ) ; checkIfActive ( ) ; getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; ORecordSerializationContext . pushContext ( ) ; try { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , getClusterNameById ( rid . getClusterId ( ) ) ) ; // either regular or micro tx must be active or both inactive assert ! ( getTransaction ( ) . isActive ( ) && ( microTransaction != null && microTransaction . isActive ( ) ) ) ; // SEARCH IN LOCAL TX ORecord record = getTransaction ( ) . getRecord ( rid ) ; if ( record == OBasicTransaction . DELETED_RECORD ) // DELETED IN TX return null ; if ( record == null ) { if ( microTransaction != null && microTransaction . isActive ( ) ) { record = microTransaction . getRecord ( rid ) ; if ( record == OBasicTransaction . DELETED_RECORD ) return null ; } } if ( record == null && ! ignoreCache ) // SEARCH INTO THE CACHE record = getLocalCache ( ) . findRecord ( rid ) ; if ( record != null ) { if ( iRecord != null ) { iRecord . fromStream ( record . toStream ( ) ) ; ORecordInternal . setVersion ( iRecord , record . getVersion ( ) ) ; record = iRecord ; } OFetchHelper . checkFetchPlanValid ( fetchPlan ) ; if ( beforeReadOperations ( record ) ) return null ; if ( record . getInternalStatus ( ) == ORecordElement . STATUS . NOT_LOADED ) record . reload ( ) ; if ( lockingStrategy == OStorage . LOCKING_STRATEGY . KEEP_SHARED_LOCK ) { OLogManager . instance ( ) . warn ( this , \"You use deprecated record locking strategy: %s it may lead to deadlocks \" + lockingStrategy ) ; record . lock ( false ) ; } else if ( lockingStrategy == OStorage . LOCKING_STRATEGY . KEEP_EXCLUSIVE_LOCK ) { OLogManager . instance ( ) . warn ( this , \"You use deprecated record locking strategy: %s it may lead to deadlocks \" + lockingStrategy ) ; record . lock ( true ) ; } afterReadOperations ( record ) ; if ( record instanceof ODocument ) ODocumentInternal . checkClass ( ( ODocument ) record , this ) ; return ( RET ) record ; } final ORawBuffer recordBuffer ; if ( ! rid . isValid ( ) ) recordBuffer = null ; else { OFetchHelper . checkFetchPlanValid ( fetchPlan ) ; int version ; if ( iRecord != null ) version = iRecord . getVersion ( ) ; else version = recordVersion ; recordBuffer = recordReader . readRecord ( getStorage ( ) , rid , fetchPlan , ignoreCache , version ) ; } if ( recordBuffer == null ) return null ; if ( iRecord == null || ORecordInternal . getRecordType ( iRecord ) != recordBuffer . recordType ) // NO SAME RECORD TYPE: CAN'T REUSE OLD ONE BUT CREATE A NEW ONE FOR IT iRecord = Orient . instance ( ) . getRecordFactoryManager ( ) . newInstance ( recordBuffer . recordType , rid . getClusterId ( ) , this ) ; ORecordInternal . setRecordSerializer ( iRecord , getSerializer ( ) ) ; ORecordInternal . fill ( iRecord , rid , recordBuffer . version , recordBuffer . buffer , false , this ) ; if ( iRecord instanceof ODocument ) ODocumentInternal . checkClass ( ( ODocument ) iRecord , this ) ; if ( ORecordVersionHelper . isTombstone ( iRecord . getVersion ( ) ) ) return ( RET ) iRecord ; if ( beforeReadOperations ( iRecord ) ) return null ; iRecord . fromStream ( recordBuffer . buffer ) ; afterReadOperations ( iRecord ) ; if ( iUpdateCache ) getLocalCache ( ) . updateRecord ( iRecord ) ; return ( RET ) iRecord ; } catch ( OOfflineClusterException t ) { throw t ; } catch ( ORecordNotFoundException t ) { throw t ; } catch ( Exception t ) { if ( rid . isTemporary ( ) ) throw OException . wrapException ( new ODatabaseException ( \"Error on retrieving record using temporary RID: \" + rid ) , t ) ; else throw OException . wrapException ( new ODatabaseException ( \"Error on retrieving record \" + rid + \" (cluster: \" + getStorage ( ) . getPhysicalClusterNameById ( rid . getClusterId ( ) ) + \")\" ) , t ) ; } finally { ORecordSerializationContext . pullContext ( ) ; getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Byte object , ByteBuffer buffer , Object ... hints ) { buffer . put ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify collection that changes has been saved . Converts to non embedded implementation if needed . <p > WARNING! Method is for internal usage . [CODESPLIT] public void notifySaved ( OBonsaiCollectionPointer newPointer ) { if ( newPointer . isValid ( ) ) { if ( isEmbedded ( ) ) { replaceWithSBTree ( newPointer ) ; } else { ( ( OSBTreeRidBag ) delegate ) . setCollectionPointer ( newPointer ) ; ( ( OSBTreeRidBag ) delegate ) . clearChanges ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "IMPORTANT! Only for internal usage . [CODESPLIT] public boolean tryMerge ( final ORidBag otherValue , boolean iMergeSingleItemsOfMultiValueFields ) { if ( ! isEmbedded ( ) && ! otherValue . isEmbedded ( ) ) { final OSBTreeRidBag thisTree = ( OSBTreeRidBag ) delegate ; final OSBTreeRidBag otherTree = ( OSBTreeRidBag ) otherValue . delegate ; if ( thisTree . getCollectionPointer ( ) . equals ( otherTree . getCollectionPointer ( ) ) ) { thisTree . mergeChanges ( otherTree ) ; uuid = otherValue . uuid ; return true ; } } else if ( iMergeSingleItemsOfMultiValueFields ) { final Iterator < OIdentifiable > iter = otherValue . rawIterator ( ) ; while ( iter . hasNext ( ) ) { final OIdentifiable value = iter . next ( ) ; if ( value != null ) { final Iterator < OIdentifiable > localIter = rawIterator ( ) ; boolean found = false ; while ( localIter . hasNext ( ) ) { final OIdentifiable v = localIter . next ( ) ; if ( value . equals ( v ) ) { found = true ; break ; } } if ( ! found ) add ( value ) ; } } return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Silently replace delegate by tree implementation . [CODESPLIT] private void replaceWithSBTree ( OBonsaiCollectionPointer pointer ) { delegate . requestDelete ( ) ; final OSBTreeRidBag treeBag = new OSBTreeRidBag ( ) ; treeBag . setCollectionPointer ( pointer ) ; treeBag . setOwner ( delegate . getOwner ( ) ) ; for ( OMultiValueChangeListener < OIdentifiable , OIdentifiable > listener : delegate . getChangeListeners ( ) ) treeBag . addChangeListener ( listener ) ; delegate = treeBag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manages cross compiler compatibility issues . [CODESPLIT] public static Object transformResult ( Object result ) { if ( java8MethodIsArray == null || ! ( result instanceof Map ) ) { return result ; } // PATCH BY MAT ABOUT NASHORN RETURNING VALUE FOR ARRAYS. try { if ( ( Boolean ) java8MethodIsArray . invoke ( result ) ) { List < ? > partial = new ArrayList ( ( ( Map ) result ) . values ( ) ) ; List < Object > finalResult = new ArrayList < Object > ( ) ; for ( Object o : partial ) { finalResult . add ( transformResult ( o ) ) ; } return finalResult ; } else { Map < Object , Object > mapResult = ( Map ) result ; List < Object > keys = new ArrayList < Object > ( mapResult . keySet ( ) ) ; for ( Object key : keys ) { mapResult . put ( key , transformResult ( mapResult . get ( key ) ) ) ; } return mapResult ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( OCommandExecutorUtility . class , \"\" , e ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the CREATE CLUSTER . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clusterName == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocument database = getDatabase ( ) ; final int clusterId = database . getClusterIdByName ( clusterName ) ; if ( clusterId > - 1 ) throw new OCommandSQLParsingException ( \"Cluster '\" + clusterName + \"' already exists\" ) ; if ( blob ) { if ( requestedId == - 1 ) { return database . addBlobCluster ( clusterName ) ; } else { throw new OCommandExecutionException ( \"Request id not supported by blob cluster creation.\" ) ; } } else { if ( requestedId == - 1 ) { return database . addCluster ( clusterName ) ; } else { return database . addCluster ( clusterName , requestedId , null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes all the databases . [CODESPLIT] public void close ( ) { lock ( ) ; try { if ( this . evictionTask != null ) { this . evictionTask . cancel ( ) ; } for ( Entry < String , OReentrantResourcePool < String , DB > > pool : pools . entrySet ( ) ) { for ( DB db : pool . getValue ( ) . getResources ( ) ) { pool . getValue ( ) . close ( ) ; try { OLogManager . instance ( ) . debug ( this , \"Closing pooled database '%s'...\" , db . getName ( ) ) ; ( ( ODatabasePooled ) db ) . forceClose ( ) ; OLogManager . instance ( ) . debug ( this , \"OK\" , db . getName ( ) ) ; } catch ( Exception e ) { OLogManager . instance ( ) . debug ( this , \"Error: %d\" , e . toString ( ) ) ; } } } } finally { unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes from memory the pool associated to the closed storage . This avoids pool open against closed storages . [CODESPLIT] public void onStorageUnregistered ( final OStorage iStorage ) { final String storageURL = iStorage . getURL ( ) ; lock ( ) ; try { Set < String > poolToClose = null ; for ( Entry < String , OReentrantResourcePool < String , DB > > e : pools . entrySet ( ) ) { final int pos = e . getKey ( ) . indexOf ( \"@\" ) ; final String dbName = e . getKey ( ) . substring ( pos + 1 ) ; if ( storageURL . equals ( dbName ) ) { if ( poolToClose == null ) poolToClose = new HashSet < String > ( ) ; poolToClose . add ( e . getKey ( ) ) ; } } if ( poolToClose != null ) for ( String pool : poolToClose ) remove ( pool ) ; } finally { unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates on all factories and append all function names . [CODESPLIT] public static Set < String > getFunctionNames ( ) { final Set < String > types = new HashSet < String > ( ) ; final Iterator < OSQLFunctionFactory > ite = getFunctionFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getFunctionNames ( ) ) ; } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates on all factories and append all collate names . [CODESPLIT] public static Set < String > getCollateNames ( ) { final Set < String > types = new HashSet < String > ( ) ; final Iterator < OCollateFactory > ite = getCollateFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getNames ( ) ) ; } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates on all factories and append all command names . [CODESPLIT] public static Set < String > getCommandNames ( ) { final Set < String > types = new HashSet < String > ( ) ; final Iterator < OCommandExecutorSQLFactory > ite = getCommandFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getCommandNames ( ) ) ; } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "use only for named fields [CODESPLIT] private Tuple < Integer , OType > getFieldSizeAndTypeFromCurrentPosition ( BytesContainer bytes ) { int fieldSize = OVarIntSerializer . readAsInteger ( bytes ) ; OType type = readOType ( bytes , false ) ; return new Tuple <> ( fieldSize , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the response s status as HTTP code and reason . [CODESPLIT] public OHttpResponseWrapper writeStatus ( final int iHttpCode , final String iReason ) throws IOException { response . writeStatus ( iHttpCode , iReason ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the response s headers specifying when using the keep - alive or not . [CODESPLIT] public OHttpResponseWrapper writeHeaders ( final String iContentType , final boolean iKeepAlive ) throws IOException { response . writeHeaders ( iContentType , iKeepAlive ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes records as response specifying a fetch - plan to serialize nested records . The records are serialized in JSON format . [CODESPLIT] public OHttpResponseWrapper writeRecords ( final Object iRecords , final String iFetchPlan ) throws IOException { response . writeRecords ( iRecords , iFetchPlan ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a record as response . The record is serialized in JSON format . [CODESPLIT] public OHttpResponseWrapper writeRecord ( final ORecord iRecord , final String iFetchPlan ) throws IOException { response . writeRecord ( iRecord , iFetchPlan , null ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends the complete HTTP response in one call . [CODESPLIT] public OHttpResponseWrapper send ( final int iCode , final String iReason , final String iContentType , final Object iContent ) throws IOException { response . send ( iCode , iReason , iContentType , iContent , null ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends the complete HTTP response in one call specifying a stream as content . [CODESPLIT] public OHttpResponseWrapper sendStream ( final int iCode , final String iReason , final String iContentType , final InputStream iContent , final long iSize ) throws IOException { response . sendStream ( iCode , iReason , iContentType , iContent , iSize ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the element at the current position and move backward the cursor to the previous position available . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public REC previous ( ) { checkDirection ( false ) ; if ( currentRecord != null ) { try { return ( REC ) currentRecord ; } finally { currentRecord = null ; } } // ITERATE UNTIL THE PREVIOUS GOOD RECORD\r while ( hasPrevious ( ) ) { try { return ( REC ) currentRecord ; } finally { currentRecord = null ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the element at the current position and move forward the cursor to the next position available . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public REC next ( ) { checkDirection ( true ) ; ORecord record ; // ITERATE UNTIL THE NEXT GOOD RECORD\r while ( hasNext ( ) ) { // FOUND\r if ( currentRecord != null ) { try { return ( REC ) currentRecord ; } finally { currentRecord = null ; } } record = getTransactionEntry ( ) ; if ( record != null ) return ( REC ) record ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move the iterator to the begin of the range . If no range was specified move to the first record of the cluster . [CODESPLIT] @ Override public ORecordIteratorCluster < REC > begin ( ) { browsedRecords = 0 ; updateRangesOnLiveUpdate ( ) ; resetCurrentPosition ( ) ; currentRecord = readCurrentRecord ( getRecord ( ) , + 1 ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell to the iterator that the upper limit must be checked at every cycle . Useful when concurrent deletes or additions change the size of the cluster while you re browsing it . Default is false . [CODESPLIT] @ Override public ORecordIteratorCluster < REC > setLiveUpdated ( boolean iLiveUpdated ) { super . setLiveUpdated ( iLiveUpdated ) ; // SET THE RANGE LIMITS\r if ( iLiveUpdated ) { firstClusterEntry = 0L ; lastClusterEntry = Long . MAX_VALUE ; } else { final long [ ] range = database . getStorage ( ) . getClusterDataRange ( current . getClusterId ( ) ) ; firstClusterEntry = range [ 0 ] ; lastClusterEntry = range [ 1 ] ; } totalAvailableRecords = database . countClusterElements ( current . getClusterId ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a database specified by name using the username and password if needed [CODESPLIT] public ODatabaseObject open ( String name , String user , String password ) { return new OObjectDatabaseTx ( ( ODatabaseDocumentInternal ) orientDB . open ( name , user , password ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new database [CODESPLIT] public void create ( String name , ODatabaseType type , OrientDBConfig config ) { orientDB . create ( name , type , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param target @param value @param ctx [CODESPLIT] public void setValue ( Object target , Object value , OCommandContext ctx ) { if ( target == null ) { return ; } if ( target . getClass ( ) . isArray ( ) ) { setArrayValue ( target , value , ctx ) ; } else if ( target instanceof List ) { setValue ( ( List ) target , value , ctx ) ; } else if ( OMultiValue . isMultiValue ( value ) ) { //TODO } //TODO }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Avoid to close it but rather release itself to the owner pool . [CODESPLIT] @ Override public void close ( ) { if ( isClosed ( ) ) return ; checkOpenness ( ) ; if ( ownerPool != null && ownerPool . getConnectionsInCurrentThread ( getURL ( ) , userName ) > 1 ) { ownerPool . release ( this ) ; return ; } try { commit ( true ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error on releasing database '%s' in pool\" , e , getName ( ) ) ; } try { callOnCloseListeners ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error on releasing database '%s' in pool\" , e , getName ( ) ) ; } getLocalCache ( ) . clear ( ) ; if ( ownerPool != null ) { final ODatabaseDocumentPool localCopy = ownerPool ; ownerPool = null ; localCopy . release ( this ) ; } ODatabaseRecordThreadLocal . instance ( ) . remove ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change UUID to null to prevent its serialization to disk . [CODESPLIT] @ Override public UUID listenForChanges ( ORidBag collection ) { UUID ownerUUID = collection . getTemporaryId ( ) ; if ( ownerUUID != null ) { final OBonsaiCollectionPointer pointer = collection . getPointer ( ) ; Map < UUID , OBonsaiCollectionPointer > changedPointers = collectionPointerChanges . get ( ) ; if ( pointer != null && pointer . isValid ( ) ) { changedPointers . put ( ownerUUID , pointer ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distributed requests against the available workers by using one queue per worker . This guarantee the sequence of the operations against the same record cluster . [CODESPLIT] public synchronized void processRequest ( final ODistributedRequest request , final boolean waitForAcceptingRequests ) { if ( ! running ) { throw new ODistributedException ( \"Server is going down or is removing the database:'\" + getDatabaseName ( ) + \"' discarding\" ) ; } final ORemoteTask task = request . getTask ( ) ; if ( waitForAcceptingRequests ) { waitIsReady ( task ) ; if ( ! running ) { throw new ODistributedException ( \"Server is going down or is removing the database:'\" + getDatabaseName ( ) + \"' discarding\" ) ; } } totalReceivedRequests . incrementAndGet ( ) ; // final ODistributedMomentum lastMomentum = filterByMomentum.get(); // if (lastMomentum != null && task instanceof OAbstractReplicatedTask) { // final OLogSequenceNumber taskLastLSN = ((OAbstractReplicatedTask) task).getLastLSN(); // // final String sourceServer = manager.getNodeNameById(request.getId().getNodeId()); // final OLogSequenceNumber lastLSNFromMomentum = lastMomentum.getLSN(sourceServer); // // if (taskLastLSN != null && lastLSNFromMomentum != null && taskLastLSN.compareTo(lastLSNFromMomentum) < 0) { // // SKIP REQUEST BECAUSE CONTAINS AN OLD LSN // final String msg = String.format(\"Skipped request %s on database '%s' because %s < current %s\", request, databaseName, // taskLastLSN, lastLSNFromMomentum); // ODistributedServerLog.info(this, localNodeName, null, DIRECTION.NONE, msg); // ODistributedWorker.sendResponseBack(this, manager, request, new ODistributedException(msg)); // return; // } // } final int [ ] partitionKeys = task . getPartitionKey ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , localNodeName , task . getNodeSource ( ) , DIRECTION . IN , \"Request %s on database '%s' partitionKeys=%s task=%s\" , request , databaseName , Arrays . toString ( partitionKeys ) , task ) ; if ( partitionKeys . length > 1 || partitionKeys [ 0 ] == - 1 ) { final Set < Integer > involvedWorkerQueues ; if ( partitionKeys . length > 1 ) involvedWorkerQueues = getInvolvedQueuesByPartitionKeys ( partitionKeys ) ; else // LOCK ALL THE QUEUES involvedWorkerQueues = ALL_QUEUES ; // if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , \"Request %s on database '%s' involvedQueues=%s\" , request , databaseName , involvedWorkerQueues ) ; if ( involvedWorkerQueues . size ( ) == 1 ) // JUST ONE QUEUE INVOLVED: PROCESS IT IMMEDIATELY processRequest ( involvedWorkerQueues . iterator ( ) . next ( ) , request ) ; else { // INVOLVING MULTIPLE QUEUES // if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , \"Request %s on database '%s' waiting for all the previous requests to be completed\" , request , databaseName ) ; CyclicBarrier started = new CyclicBarrier ( involvedWorkerQueues . size ( ) ) ; CyclicBarrier finished = new CyclicBarrier ( involvedWorkerQueues . size ( ) ) ; // WAIT ALL THE INVOLVED QUEUES ARE FREE AND SYNCHRONIZED for ( int queue : involvedWorkerQueues ) { ODistributedWorker worker = workerThreads . get ( queue ) ; OWaitPartitionsReadyTask waitRequest = new OWaitPartitionsReadyTask ( started , task , finished ) ; final ODistributedRequest syncRequest = new ODistributedRequest ( null , request . getId ( ) . getNodeId ( ) , request . getId ( ) . getMessageId ( ) , databaseName , waitRequest ) ; worker . processRequest ( syncRequest ) ; } } } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 2 ) { // ANY PARTITION: USE THE FIRST EMPTY IF ANY, OTHERWISE THE FIRST IN THE LIST boolean found = false ; for ( ODistributedWorker q : workerThreads ) { if ( q . isWaitingForNextRequest ( ) && q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // ALL THE THREADS ARE BUSY, SELECT THE FIRST EMPTY ONE for ( ODistributedWorker q : workerThreads ) { if ( q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // EXEC ON THE FIRST QUEUE workerThreads . get ( 0 ) . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 3 ) { // SERVICE - LOCK ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , \"Request %s on database '%s' dispatched to the lock worker\" , request , databaseName ) ; lockThread . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 4 ) { // SERVICE - FAST_NOLOCK ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , \"Request %s on database '%s' dispatched to the nowait worker\" , request , databaseName ) ; nowaitThread . processRequest ( request ) ; } else { processRequest ( partitionKeys [ 0 ] , request ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called inside of { @link com . orientechnologies . orient . core . storage . impl . local . paginated . base . ODurableComponent } to notify that component started to perform operation on data . After that all performance characteristic started to be gathered for this component till method { @link #completeComponentOperation () } will be called . <p > Components can be stacked so if components <code > c1< / code > and then <code > c2< / code > call this method than performance data for both components at once started to be gathered . [CODESPLIT] public void startComponentOperation ( String componentName , ComponentType type ) { final Component currentComponent = componentsStack . peek ( ) ; if ( currentComponent != null && componentName . equals ( currentComponent . name ) ) { currentComponent . operationCount ++ ; return ; } componentsStack . push ( new Component ( componentName , type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates that the most earliest component in stack of components has completed it s operation so performance data for this component is stopped to be gathered . [CODESPLIT] public void completeComponentOperation ( ) { final Component currentComponent = componentsStack . peek ( ) ; if ( currentComponent == null ) return ; currentComponent . operationCount -- ; if ( currentComponent . operationCount == 0 ) { final String componentName = currentComponent . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> currentComponent . type . newCountersHolder ( ) ) ; cHolder . operationsCount ++ ; componentsStack . pop ( ) ; makeSnapshotIfNeeded ( - 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read speed of data in pages per second on cache level for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getReadSpeedFromCacheInPages ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getReadSpeedFromCacheInPages ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getReadSpeedFromCacheInPages ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read speed of data from file system in pages for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getReadSpeedFromFileInPages ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getReadSpeedFromFileInPages ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getReadSpeedFromFileInPages ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Amount of pages read from cache for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesReadFromCache ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getAmountOfPagesReadFromCache ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesReadFromCache ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Amount of pages are read from file for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesReadFromFile ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getAmountOfPagesReadFromFile ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesReadFromFile ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write speed of data in pages per second on cache level for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getWriteSpeedInCacheInPages ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getWriteSpeedInCacheInPages ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getWriteSpeedInCacheInPages ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Amount of pages written to cache for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesWrittenInCache ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getAmountOfPagesWrittenInCache ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesWrittenInCache ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Percent of cache hits for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public int getCacheHits ( String componentName ) { if ( componentName == null ) return performanceCountersHolder . getCacheHits ( ) ; final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getCacheHits ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Average amount of pages which were read from cache for component with given name during single data operation . <p > If null value is passed or data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesPerOperation ( String componentName ) { if ( componentName == null ) { return - 1 ; } final PerformanceCountersHolder cHolder = countersByComponent . get ( componentName ) ; if ( cHolder != null ) return cHolder . getAmountOfPagesPerOperation ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes performance data are split by components from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data . [CODESPLIT] public void pushComponentCounters ( Map < String , PerformanceCountersHolder > counters ) { if ( snapshot == null ) return ; for ( Map . Entry < String , PerformanceCountersHolder > entry : snapshot . countersByComponent . entrySet ( ) ) { final String componentName = entry . getKey ( ) ; PerformanceCountersHolder holder = counters . computeIfAbsent ( componentName , k -> entry . getValue ( ) . newInstance ( ) ) ; entry . getValue ( ) . pushData ( holder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes write cache performance data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call . [CODESPLIT] public WritCacheCountersHolder pushWriteCacheCounters ( WritCacheCountersHolder holder ) { if ( snapshot == null ) return holder ; if ( snapshot . writCacheCountersHolder == null ) return holder ; if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; snapshot . writCacheCountersHolder . pushData ( holder ) ; return holder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes storage performance data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call . [CODESPLIT] public StorageCountersHolder pushStorageCounters ( StorageCountersHolder holder ) { if ( snapshot == null ) return holder ; if ( snapshot . storageCountersHolder == null ) return holder ; if ( holder == null ) holder = new StorageCountersHolder ( ) ; snapshot . storageCountersHolder . pushData ( holder ) ; return holder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes write ahead log data from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data and as result of this method call . [CODESPLIT] public WALCountersHolder pushWALCounters ( WALCountersHolder holder ) { if ( snapshot == null ) return holder ; if ( snapshot . walCountersHolder == null ) return holder ; if ( holder == null ) holder = new WALCountersHolder ( ) ; snapshot . walCountersHolder . pushData ( holder ) ; return holder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes performance data for component from last snapshot and aggregates them with data passed inside method as parameter . Result of aggregation of performance data is returned inside of passed in performance data . [CODESPLIT] public void pushComponentCounters ( String name , PerformanceCountersHolder holder ) { if ( snapshot == null ) return ; final PerformanceCountersHolder countersHolder = snapshot . countersByComponent . get ( name ) ; if ( countersHolder != null ) { countersHolder . pushData ( holder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts properties of given class into values of fields of returned document . Names of fields equal to names of properties . <p > All data related to separate components are stored in field <code > dataByComponent< / code > map which has type { @link OType#EMBEDDEDMAP } where key of map entry is name of component and value is document which contains the same fields as high level document but with values for single component not whole system . <p > Write ahead log performance data are stored inside of <code > walData< / code > field . [CODESPLIT] public ODocument toDocument ( ) { final ODocument document = performanceCountersHolder . toDocument ( ) ; document . field ( \"commitTime\" , getCommitTime ( ) , OType . LONG ) ; final Map < String , ODocument > countersMap = new HashMap <> ( ) ; for ( Map . Entry < String , PerformanceCountersHolder > entry : countersByComponent . entrySet ( ) ) { countersMap . put ( entry . getKey ( ) , entry . getValue ( ) . toDocument ( ) ) ; } document . field ( \"dataByComponent\" , countersMap , OType . EMBEDDEDMAP ) ; if ( walCountersHolder != null ) { final ODocument wal = walCountersHolder . toDocument ( ) ; document . field ( \"walData\" , wal , OType . EMBEDDED ) ; } return document ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increments counter of page accesses from cache . <p > If you wish to gather statistic for current durable component please call { [CODESPLIT] public void incrementPageAccessOnCacheLevel ( boolean cacheHit ) { performanceCountersHolder . cacheAccessCount ++ ; if ( cacheHit ) performanceCountersHolder . cacheHit ++ ; for ( Component component : componentsStack ) { final String componentName = component . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> component . type . newCountersHolder ( ) ) ; cHolder . cacheAccessCount ++ ; if ( cacheHit ) cHolder . cacheHit ++ ; } makeSnapshotIfNeeded ( - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and records results of timer which counts how much time was spent on operation of flush pages in write cache . [CODESPLIT] public void stopWriteCacheFlushTimer ( int pagesFlushed ) { // lazy initialization to prevent memory consumption if ( writCacheCountersHolder == null ) writCacheCountersHolder = new WritCacheCountersHolder ( ) ; final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; writCacheCountersHolder . flushOperationsCount ++ ; writCacheCountersHolder . amountOfPagesFlushed += pagesFlushed ; writCacheCountersHolder . flushOperationsTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and records results of timer which counts how much time was spent on fuzzy checkpoint operation . [CODESPLIT] public void stopFuzzyCheckpointTimer ( ) { if ( writCacheCountersHolder == null ) writCacheCountersHolder = new WritCacheCountersHolder ( ) ; final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; writCacheCountersHolder . fuzzyCheckpointCount ++ ; writCacheCountersHolder . fuzzyCheckpointTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and records results of timer which counts how much time was spent on read of page from disk cache . <p > If you wish to gather statistic for current durable component please call { [CODESPLIT] public void stopPageReadFromCacheTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; performanceCountersHolder . pageReadFromCacheTime += timeDiff ; performanceCountersHolder . pageReadFromCacheCount ++ ; for ( Component component : componentsStack ) { final String componentName = component . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> component . type . newCountersHolder ( ) ) ; cHolder . pageReadFromCacheTime += timeDiff ; cHolder . pageReadFromCacheCount ++ ; } final Component currentComponent = componentsStack . peek ( ) ; if ( currentComponent != null ) { PerformanceCountersHolder currentHolder = countersByComponent . get ( currentComponent . name ) ; if ( currentHolder . currentOperation != null ) { currentHolder . currentOperation . incrementOperationsCounter ( 1 , 0 ) ; } } makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and records results of timer which counts how much time was spent on full checkpoint operation . [CODESPLIT] public void stopFullCheckpointTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; if ( storageCountersHolder == null ) storageCountersHolder = new StorageCountersHolder ( ) ; storageCountersHolder . fullCheckpointOperationsCount ++ ; storageCountersHolder . fullCheckpointOperationsTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and records results of timer which counts how much time was spent to write page to disk cache . <p > If you wish to gather statistic for current durable component please call { [CODESPLIT] public void stopPageWriteInCacheTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; performanceCountersHolder . pageWriteToCacheTime += timeDiff ; performanceCountersHolder . pageWriteToCacheCount ++ ; for ( Component component : componentsStack ) { final String componentName = component . name ; PerformanceCountersHolder cHolder = countersByComponent . computeIfAbsent ( componentName , k -> component . type . newCountersHolder ( ) ) ; cHolder . pageWriteToCacheTime += timeDiff ; cHolder . pageWriteToCacheCount ++ ; } makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and records results of timer which counts how much time was spent on atomic operation commit . [CODESPLIT] public void stopCommitTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; performanceCountersHolder . commitTime += timeDiff ; performanceCountersHolder . commitCount ++ ; makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops and records results of timer which counts how much time was spent on logging of single write ahead log record . [CODESPLIT] public void stopWALRecordTimer ( boolean isStartRecord , boolean isStopRecord ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; if ( walCountersHolder == null ) walCountersHolder = new WALCountersHolder ( ) ; walCountersHolder . logRecordCount ++ ; walCountersHolder . logRecordTime += timeDiff ; if ( isStartRecord ) { walCountersHolder . startRecordCount ++ ; walCountersHolder . startRecordTime += timeDiff ; } else if ( isStopRecord ) { walCountersHolder . stopRecordCount ++ ; walCountersHolder . stopRecordTime += timeDiff ; } makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops timer and records how much time was spent on flushing of data from write ahead log cache . [CODESPLIT] public void stopWALFlushTimer ( ) { final long endTs = nanoTimer . getNano ( ) ; final long timeDiff = ( endTs - timeStamps . pop ( ) ) ; if ( walCountersHolder == null ) walCountersHolder = new WALCountersHolder ( ) ; walCountersHolder . flushCount ++ ; walCountersHolder . flushTime += timeDiff ; makeSnapshotIfNeeded ( endTs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes snapshot of data if time for next snapshot is passed . Also clear all data if { @link #cleanUpInterval } interval is over . [CODESPLIT] private void makeSnapshotIfNeeded ( long currentTime ) { if ( currentTime < 0 ) { currentTime = nanoTimer . getNano ( ) ; } if ( lastSnapshotTimestamp == - 1 ) lastSnapshotTimestamp = 0 ; if ( lastSnapshotTimestamp < 0 || currentTime - lastSnapshotTimestamp >= intervalBetweenSnapshots ) { snapshot = new PerformanceSnapshot ( performanceCountersHolder , countersByComponent , writCacheCountersHolder , storageCountersHolder , walCountersHolder ) ; lastSnapshotTimestamp = currentTime ; } if ( cleanUpInterval > 0 ) { if ( currentTime - lastCleanUpTimeStamp >= cleanUpInterval ) { performanceCountersHolder . clean ( ) ; for ( PerformanceCountersHolder pch : countersByComponent . values ( ) ) { pch . clean ( ) ; } if ( writCacheCountersHolder != null ) writCacheCountersHolder . clean ( ) ; if ( storageCountersHolder != null ) storageCountersHolder . clean ( ) ; if ( writCacheCountersHolder != null ) walCountersHolder . clean ( ) ; lastCleanUpTimeStamp = currentTime ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void shutdown ( ) { try { MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; if ( onProfiler != null ) if ( mBeanServer . isRegistered ( onProfiler ) ) mBeanServer . unregisterMBean ( onProfiler ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"OrientDB Server v\" + OConstants . getVersion ( ) + \" unregisterMBean error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns an already parsed SQL executor taking it from the cache if it exists or creating a new one ( parsing and then putting it into the cache ) if it doesn t [CODESPLIT] public static OStatement get ( String statement , ODatabaseDocumentInternal db ) { if ( db == null ) { return parse ( statement ) ; } OStatementCache resource = db . getSharedContext ( ) . getStatementCache ( ) ; return resource . get ( statement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param statement an SQL statement [CODESPLIT] public OStatement get ( String statement ) { OStatement result ; synchronized ( map ) { //LRU result = map . remove ( statement ) ; if ( result != null ) { map . put ( statement , result ) ; } } if ( result == null ) { result = parse ( statement ) ; synchronized ( map ) { map . put ( statement , result ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parses an SQL statement and returns the corresponding executor [CODESPLIT] protected static OStatement parse ( String statement ) throws OCommandSQLParsingException { try { ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; InputStream is ; if ( db == null ) { is = new ByteArrayInputStream ( statement . getBytes ( ) ) ; } else { try { is = new ByteArrayInputStream ( statement . getBytes ( db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ) ; } catch ( UnsupportedEncodingException e2 ) { OLogManager . instance ( ) . warn ( null , \"Unsupported charset for database \" + db + \" \" + db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; is = new ByteArrayInputStream ( statement . getBytes ( ) ) ; } } OrientSql osql = null ; if ( db == null ) { osql = new OrientSql ( is ) ; } else { try { osql = new OrientSql ( is , db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; } catch ( UnsupportedEncodingException e2 ) { OLogManager . instance ( ) . warn ( null , \"Unsupported charset for database \" + db + \" \" + db . getStorage ( ) . getConfiguration ( ) . getCharset ( ) ) ; osql = new OrientSql ( is ) ; } } OStatement result = osql . parse ( ) ; result . originalStatement = statement ; return result ; } catch ( ParseException e ) { throwParsingException ( e , statement ) ; } catch ( TokenMgrError e2 ) { throwParsingException ( e2 , statement ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * =============== START / STOP ================= [CODESPLIT] protected void start ( ) { try { initNetwork ( ) ; initReceiveMessages ( ) ; initDiscoveryPing ( ) ; initCheckLeader ( ) ; initCheckDisconnect ( ) ; } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"Cannot start distributed node discovery: \" + ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inits the procedure that listens to pings from other servers eg . that discovers other nodes in the network [CODESPLIT] protected void initReceiveMessages ( ) throws IOException { messageThread = new Thread ( ( ) -> { while ( ! Thread . interrupted ( ) ) { receiveMessages ( ) ; } } ) ; messageThread . setName ( \"OrientDB_DistributedDiscoveryThread\" ) ; messageThread . setDaemon ( true ) ; messageThread . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init the procedure that sends pings to other servers ie . that notifies that you are alive [CODESPLIT] protected void initDiscoveryPing ( ) { discoveryTimer = new TimerTask ( ) { @ Override public void run ( ) { try { sendPing ( ) ; if ( running ) { initDiscoveryPing ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; taskScheduler . scheduleOnce ( discoveryTimer , discoveryPingIntervalMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inits the procedure that checks if a server is no longer available ie . if he did not ping for a long time [CODESPLIT] protected void initCheckDisconnect ( ) { disconnectTimer = new TimerTask ( ) { public void run ( ) { try { checkIfKnownServersAreAlive ( ) ; if ( running ) { initCheckDisconnect ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; taskScheduler . scheduleOnce ( disconnectTimer , discoveryPingIntervalMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init the procedure that sends pings to other servers ie . that notifies that you are alive [CODESPLIT] private void initCheckLeader ( ) { checkerTimer = new TimerTask ( ) { @ Override public void run ( ) { try { if ( running ) { checkLeader ( ) ; initCheckLeader ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; taskScheduler . scheduleOnce ( checkerTimer , checkLeaderIntervalMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * =============== NETWORK UTILITIES ================= [CODESPLIT] protected byte [ ] serializeMessage ( OBroadcastMessage message ) throws Exception { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; message . write ( new DataOutputStream ( buffer ) ) ; return encrypt ( buffer . toByteArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * =============== ENCRYPTION ================= [CODESPLIT] private byte [ ] encrypt ( byte [ ] data ) throws Exception { if ( config . getGroupPassword ( ) == null ) { return data ; } Cipher cipher = Cipher . getInstance ( \"AES/CBC/PKCS5Padding\" ) ; byte [ ] iv = cipher . getParameters ( ) . getParameterSpec ( IvParameterSpec . class ) . getIV ( ) ; IvParameterSpec ivSpec = new IvParameterSpec ( iv ) ; SecretKeySpec keySpec = new SecretKeySpec ( paddedPassword ( config . getGroupPassword ( ) ) , \"AES\" ) ; cipher . init ( Cipher . ENCRYPT_MODE , keySpec , ivSpec ) ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; DataOutput output = new DataOutputStream ( stream ) ; output . writeInt ( iv . length ) ; output . write ( iv ) ; byte [ ] cypher = cipher . doFinal ( data ) ; output . writeInt ( cypher . length ) ; output . write ( cypher ) ; return stream . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the Element from the Graph . In case the element is a Vertex all the incoming and outgoing edges are automatically removed too . [CODESPLIT] void removeRecord ( ) { checkIfAttached ( ) ; final OrientBaseGraph graph = getGraph ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , \"The graph element with id \" + getIdentity ( ) + \" not found\" ) ; try { getRecord ( ) . load ( ) ; } catch ( ORecordNotFoundException e ) { graph . throwRecordNotFoundException ( getIdentity ( ) , e . getMessage ( ) ) ; } getRecord ( ) . delete ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Sets multiple properties in one shot against Vertices and Edges . This improves performance avoiding to save the graph element at every property set . <br > Example : <p > <code > vertex . setProperties ( name Jill age 33 city Rome born Victoria TX ) ; < / code > You can also pass a Map of values as first argument . In this case all the map entries will be set as element properties : <p > <code > Map<String Object > props = new HashMap<String Object > () ; props . put ( name Jill ) ; props . put ( age 33 ) ; props . put ( city Rome ) ; props . put ( born Victoria TX ) ; vertex . setProperties ( props ) ; < / code > [CODESPLIT] public < T extends OrientElement > T setProperties ( final Object ... fields ) { if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , \"The graph element \" + getIdentity ( ) + \" has been deleted\" ) ; setPropertiesInternal ( fields ) ; save ( ) ; return ( T ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a Property value . [CODESPLIT] @ Override public void setProperty ( final String key , final Object value ) { if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , \"The graph element \" + getIdentity ( ) + \" has been deleted\" ) ; validateProperty ( this , key , value ) ; final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) graph . autoStartTransaction ( ) ; getRecord ( ) . field ( key , value ) ; if ( graph != null ) save ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a Property . [CODESPLIT] @ Override public < T > T removeProperty ( final String key ) { if ( checkDeletedInTx ( ) ) throw new IllegalStateException ( \"The vertex \" + getIdentity ( ) + \" has been deleted\" ) ; final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) graph . autoStartTransaction ( ) ; final Object oldValue = getRecord ( ) . removeField ( key ) ; if ( graph != null ) save ( ) ; return ( T ) oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Property value . [CODESPLIT] @ Override public < T > T getProperty ( final String key ) { if ( key == null ) return null ; final OrientBaseGraph graph = getGraph ( ) ; if ( key . equals ( \"_class\" ) ) return ( T ) ODocumentInternal . getImmutableSchemaClass ( getRecord ( ) ) . getName ( ) ; else if ( key . equals ( \"_version\" ) ) return ( T ) new Integer ( getRecord ( ) . getVersion ( ) ) ; else if ( key . equals ( \"_rid\" ) ) return ( T ) rawElement . getIdentity ( ) . toString ( ) ; final ODocument record = getRecord ( ) ; if ( record == null ) // NO RECORD return null ; final Object fieldValue = record . field ( key ) ; if ( graph != null && fieldValue instanceof OIdentifiable && ! ( ( ( OIdentifiable ) fieldValue ) . getRecord ( ) instanceof OBlob ) ) { ODocument fieldRecord = ( ( OIdentifiable ) fieldValue ) . getRecord ( ) ; if ( fieldRecord != null ) { final OClass schemaClass = fieldRecord . getSchemaClass ( ) ; if ( schemaClass != null && ( schemaClass . isVertexType ( ) || schemaClass . isEdgeType ( ) ) ) { // CONVERT IT TO VERTEX/EDGE return ( T ) graph . getElement ( fieldValue ) ; } } return ( T ) fieldValue ; } else if ( ! ( fieldValue instanceof Map ) && OMultiValue . isMultiValue ( fieldValue ) && OMultiValue . getFirstValue ( fieldValue ) instanceof OIdentifiable ) { final OIdentifiable firstValue = ( OIdentifiable ) OMultiValue . getFirstValue ( fieldValue ) ; if ( firstValue instanceof ODocument ) { final ODocument document = ( ODocument ) firstValue ; /// clusterId -2 Is considered a projection so does not have a class but is a not embedded record if ( document . getIdentity ( ) . getClusterId ( ) != - 2 && ( document . isEmbedded ( ) || ODocumentInternal . getImmutableSchemaClass ( document ) == null ) ) return ( T ) fieldValue ; } if ( graph != null ) // CONVERT IT TO ITERABLE<VERTEX/EDGE> return ( T ) new OrientElementIterable < OrientElement > ( graph , OMultiValue . getMultiValueIterable ( fieldValue ) ) ; } return ( T ) fieldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Saves current element to a particular cluster . You don t need to call save () unless you re working against Temporary Vertices . [CODESPLIT] public void save ( final String iClusterName ) { final OrientBaseGraph graph = checkIfAttached ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; if ( rawElement instanceof ODocument ) if ( iClusterName != null ) rawElement = ( ( ODocument ) rawElement ) . save ( iClusterName ) ; else rawElement = ( ( ODocument ) rawElement ) . save ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Fills the Element from a byte [] [CODESPLIT] @ Override public OSerializableStream fromStream ( final byte [ ] stream ) throws OSerializationException { final ODocument record = getRecord ( ) ; ( ( ORecordId ) record . getIdentity ( ) ) . fromString ( new String ( stream ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the record s identity . [CODESPLIT] @ Override public ORID getIdentity ( ) { if ( rawElement == null ) return ORecordId . EMPTY_RECORD_ID ; final ORID rid = rawElement . getIdentity ( ) ; if ( ! rid . isValid ( ) ) { final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) { // SAVE THE RECORD TO OBTAIN A VALID RID graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; save ( ) ; } } return rid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the underlying record . [CODESPLIT] @ Override public ODocument getRecord ( ) { if ( rawElement == null ) return null ; if ( rawElement instanceof ODocument ) return ( ODocument ) rawElement ; final ODocument doc = rawElement . getRecord ( ) ; if ( doc == null ) return null ; // CHANGE THE RID -> DOCUMENT rawElement = doc ; return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Removes the reference to the current graph instance to let working offline . To reattach it use @attach . <p > This methods works only in classic detach / attach mode when dettachment / attachment is done manually by default it is done automatically and currently active graph connection will be used as graph elements owner . [CODESPLIT] public OrientElement detach ( ) { // EARLY UNMARSHALL FIELDS getRecord ( ) . setLazyLoad ( false ) ; getRecord ( ) . fieldNames ( ) ; // COPY GRAPH SETTINGS TO WORK OFFLINE if ( graph != null ) { settings = graph . settings . copy ( ) ; graph = null ; } classicDetachMode = true ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Replaces current graph instance with new one on @detach - ed elements . Use this method to pass elements between graphs or to switch between Tx and NoTx instances . <p > This methods works only in classic detach / attach mode when detachment / attachment is done manually by default it is done automatically and currently active graph connection will be used as graph elements owner . <p > To set classic detach / attach mode please set custom database parameter <code > classicDetachMode< / code > to <code > true< / code > . [CODESPLIT] public OrientElement attach ( final OrientBaseGraph iNewGraph ) { if ( iNewGraph == null ) throw new IllegalArgumentException ( \"Graph is null\" ) ; classicDetachMode = true ; graph = iNewGraph ; // LINK THE GRAPHS SETTINGS settings = graph . settings ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the Graph instance associated to the current element . On [CODESPLIT] public OrientBaseGraph getGraph ( ) { if ( classicDetachMode ) return graph ; OrientBaseGraph result = OrientBaseGraph . getActiveGraph ( ) ; if ( result == null && this . graph != null && ! graph . isClosed ( ) ) { result = graph ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Validates an Element property . [CODESPLIT] public final void validateProperty ( final Element element , final String key , final Object value ) throws IllegalArgumentException { if ( settings . isStandardElementConstraints ( ) && null == value ) throw ExceptionFactory . propertyValueCanNotBeNull ( ) ; if ( null == key ) throw ExceptionFactory . propertyKeyCanNotBeNull ( ) ; if ( settings . isStandardElementConstraints ( ) && key . equals ( StringFactory . ID ) ) throw ExceptionFactory . propertyKeyIdIsReserved ( ) ; if ( element instanceof Edge && key . equals ( StringFactory . LABEL ) ) throw ExceptionFactory . propertyKeyLabelIsReservedForEdges ( ) ; if ( key . isEmpty ( ) ) throw ExceptionFactory . propertyKeyCanNotBeEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a class already exists otherwise create it at the fly . If a transaction is running commit changes create the class and begin a new transaction . [CODESPLIT] protected String checkForClassInSchema ( final String className ) { if ( className == null ) return null ; OrientBaseGraph graph = getGraph ( ) ; if ( graph == null ) return className ; final OSchema schema = graph . getRawGraph ( ) . getMetadata ( ) . getSchema ( ) ; if ( ! schema . existsClass ( className ) ) { // CREATE A NEW CLASS AT THE FLY try { graph . executeOutsideTx ( new OCallable < OClass , OrientBaseGraph > ( ) { @ Override public OClass call ( final OrientBaseGraph g ) { return schema . createClass ( className , schema . getClass ( getBaseClassName ( ) ) ) ; } } , \"Committing the active transaction to create the new type '\" , className , \"' as subclass of '\" , getBaseClassName ( ) , \"'. The transaction will be reopen right after that. To avoid this behavior create the classes outside the transaction\" ) ; } catch ( OSchemaException e ) { if ( ! schema . existsClass ( className ) ) throw e ; } } else { // CHECK THE CLASS INHERITANCE final OClass cls = schema . getClass ( className ) ; if ( ! cls . isSubClassOf ( getBaseClassName ( ) ) ) throw new IllegalArgumentException ( \"Class '\" + className + \"' is not an instance of \" + getBaseClassName ( ) ) ; } return className ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Sets multiple properties in one shot against Vertices and Edges without saving the element . This improves performance avoiding to save the graph element at every property set . Example : <p > <code > vertex . setProperties ( name Jill age 33 city Rome born Victoria TX ) ; < / code > You can also pass a Map of values as first argument . In this case all the map entries will be set as element properties : <p > <code > Map<String Object > props = new HashMap<String Object > () ; props . put ( name Jill ) ; props . put ( age 33 ) ; props . put ( city Rome ) ; props . put ( born Victoria TX ) ; vertex . setProperties ( props ) ; < / code > [CODESPLIT] protected < T extends OrientElement > T setPropertiesInternal ( final Object ... fields ) { OrientBaseGraph graph = getGraph ( ) ; if ( fields != null && fields . length > 0 && fields [ 0 ] != null ) { if ( graph != null ) graph . autoStartTransaction ( ) ; if ( fields . length == 1 ) { Object f = fields [ 0 ] ; if ( f instanceof Map < ? , ? > ) { for ( Map . Entry < Object , Object > entry : ( ( Map < Object , Object > ) f ) . entrySet ( ) ) setPropertyInternal ( this , ( ODocument ) rawElement . getRecord ( ) , entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } else if ( f instanceof Collection ) { for ( Object o : ( Collection ) f ) { if ( ! ( o instanceof OPair ) ) throw new IllegalArgumentException ( \"Invalid fields: expecting a pairs of fields as String,Object, but found the item: \" + o ) ; final OPair entry = ( OPair ) o ; setPropertyInternal ( this , ( ODocument ) rawElement . getRecord ( ) , entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } } else throw new IllegalArgumentException ( \"Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: \" + f ) ; } else { if ( fields . length % 2 != 0 ) throw new IllegalArgumentException ( \"Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: \" + Arrays . toString ( fields ) ) ; // SET THE FIELDS for ( int i = 0 ; i < fields . length ; i += 2 ) setPropertyInternal ( this , ( ODocument ) rawElement . getRecord ( ) , fields [ i ] . toString ( ) , fields [ i + 1 ] ) ; } } return ( T ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param config Global configuration parameter . [CODESPLIT] public < T extends Enum < T > > T getValueAsEnum ( final OGlobalConfiguration config , Class < T > enumType ) { final Object value ; if ( this . config != null && this . config . containsKey ( config . getKey ( ) ) ) { value = this . config . get ( config . getKey ( ) ) ; } else { value = config . getValue ( ) ; } if ( value == null ) return null ; if ( enumType . isAssignableFrom ( value . getClass ( ) ) ) { return enumType . cast ( value ) ; } else if ( value instanceof String ) { final String presentation = value . toString ( ) ; return Enum . valueOf ( enumType , presentation ) ; } else { throw new ClassCastException ( \"Value \" + value + \" can not be cast to enumeration \" + enumType . getSimpleName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps courser only if it is not already wrapped . [CODESPLIT] public static OIndexCursor wrap ( OIndex < ? > source , OIndexCursor cursor , long indexRebuildVersion ) { if ( cursor instanceof OIndexChangesWrapper ) return cursor ; if ( cursor instanceof OSizeable ) { return new OIndexChangesSizeable ( source , cursor , indexRebuildVersion ) ; } return new OIndexChangesWrapper ( source , cursor , indexRebuildVersion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Map . Entry < Object , OIdentifiable > nextEntry ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Map . Entry < Object , OIdentifiable > entry = delegate . nextEntry ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Set < OIdentifiable > toValues ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Set < OIdentifiable > values = delegate . toValues ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Set < Map . Entry < Object , OIdentifiable > > toEntries ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Set < Map . Entry < Object , OIdentifiable > > entries = delegate . toEntries ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return entries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Set < Object > toKeys ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final Set < Object > keys = delegate . toKeys ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return keys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean hasNext ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final boolean isNext = delegate . hasNext ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return isNext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OIdentifiable next ( ) { if ( source . isRebuilding ( ) ) throwRebuildException ( ) ; final OIdentifiable next = delegate . next ( ) ; if ( source . getRebuildVersion ( ) != indexRebuildVersion ) throwRebuildException ( ) ; return next ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define custom strategy to use for vertex attribute . [CODESPLIT] public OGraphMLReader defineVertexAttributeStrategy ( final String iAttributeName , final OGraphMLImportStrategy iStrategy ) { vertexPropsStrategy . put ( iAttributeName , iStrategy ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define custom strategy to use for edge attribute . [CODESPLIT] public OGraphMLReader defineEdgeAttributeStrategy ( final String iAttributeName , final OGraphMLImportStrategy iStrategy ) { edgePropsStrategy . put ( iAttributeName , iStrategy ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the GraphML stream data into the graph . In practice usually the provided graph is empty . [CODESPLIT] public void inputGraph ( final Graph inputGraph , final InputStream graphMLInputStream ) throws IOException { inputGraph ( inputGraph , graphMLInputStream , batchSize , vertexIdKey , edgeIdKey , edgeLabelKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the GraphML stream data into the graph . In practice usually the provided graph is empty . [CODESPLIT] public void inputGraph ( final Graph inputGraph , final String filename ) throws IOException { inputGraph ( inputGraph , filename , batchSize , vertexIdKey , edgeIdKey , edgeLabelKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the GraphML stream data into the graph . More control over how data is streamed is provided by this method . [CODESPLIT] public OGraphMLReader inputGraph ( final Graph inputGraph , final String filename , int bufferSize , String vertexIdKey , String edgeIdKey , String edgeLabelKey ) throws IOException { FileInputStream fis = new FileInputStream ( filename ) ; try { return inputGraph ( inputGraph , fis , bufferSize , vertexIdKey , edgeIdKey , edgeLabelKey ) ; } finally { fis . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the GraphML stream data into the graph . More control over how data is streamed is provided by this method . [CODESPLIT] public OGraphMLReader inputGraph ( final Graph inputGraph , final InputStream graphMLInputStream , int bufferSize , String vertexIdKey , String edgeIdKey , String edgeLabelKey ) throws IOException { XMLInputFactory inputFactory = XMLInputFactory . newInstance ( ) ; try { XMLStreamReader reader = inputFactory . createXMLStreamReader ( graphMLInputStream ) ; final OrientBaseGraph graph = ( OrientBaseGraph ) inputGraph ; if ( storeVertexIds ) graph . setSaveOriginalIds ( storeVertexIds ) ; Map < String , String > keyIdMap = new HashMap < String , String > ( ) ; Map < String , String > keyTypesMaps = new HashMap < String , String > ( ) ; // <Mapped ID String, ID Object> // <Default ID String, Mapped ID String> Map < String , ORID > vertexMappedIdMap = new HashMap < String , ORID > ( ) ; // Buffered Vertex Data String vertexId = null ; Map < String , Object > vertexProps = null ; boolean inVertex = false ; // Buffered Edge Data String edgeId = null ; String edgeLabel = null ; String vertexLabel = null ; Vertex [ ] edgeEndVertices = null ; // [0] = outVertex , [1] = inVertex Map < String , Object > edgeProps = null ; boolean inEdge = false ; int bufferCounter = 0 ; long importedVertices = 0 ; long importedEdges = 0 ; while ( reader . hasNext ( ) ) { Integer eventType = reader . next ( ) ; if ( eventType . equals ( XMLEvent . START_ELEMENT ) ) { String elementName = reader . getName ( ) . getLocalPart ( ) ; if ( elementName . equals ( GraphMLTokens . KEY ) ) { String id = reader . getAttributeValue ( null , GraphMLTokens . ID ) ; String attributeName = reader . getAttributeValue ( null , GraphMLTokens . ATTR_NAME ) ; String attributeType = reader . getAttributeValue ( null , GraphMLTokens . ATTR_TYPE ) ; keyIdMap . put ( id , attributeName ) ; keyTypesMaps . put ( id , attributeType ) ; } else if ( elementName . equals ( GraphMLTokens . NODE ) ) { vertexId = reader . getAttributeValue ( null , GraphMLTokens . ID ) ; vertexLabel = reader . getAttributeValue ( null , LABELS ) ; if ( vertexLabel != null ) { if ( vertexLabel . startsWith ( \":\" ) ) // REMOVE : AS PREFIX vertexLabel = vertexLabel . substring ( 1 ) ; final String [ ] vertexLabels = vertexLabel . split ( \":\" ) ; // GET ONLY FIRST LABEL AS CLASS vertexLabel = vertexId + \",class:\" + vertexLabels [ vertexLabelIndex ] ; } else vertexLabel = vertexId ; inVertex = true ; vertexProps = new HashMap < String , Object > ( ) ; } else if ( elementName . equals ( GraphMLTokens . EDGE ) ) { edgeId = reader . getAttributeValue ( null , GraphMLTokens . ID ) ; edgeLabel = reader . getAttributeValue ( null , GraphMLTokens . LABEL ) ; edgeLabel = edgeLabel == null ? GraphMLTokens . _DEFAULT : edgeLabel ; String [ ] vertexIds = new String [ 2 ] ; vertexIds [ 0 ] = reader . getAttributeValue ( null , GraphMLTokens . SOURCE ) ; vertexIds [ 1 ] = reader . getAttributeValue ( null , GraphMLTokens . TARGET ) ; edgeEndVertices = new Vertex [ 2 ] ; for ( int i = 0 ; i < 2 ; i ++ ) { // i=0 => outVertex, i=1 => inVertex if ( vertexIdKey == null ) { edgeEndVertices [ i ] = null ; } else { final Object vId = vertexMappedIdMap . get ( vertexIds [ i ] ) ; edgeEndVertices [ i ] = vId != null ? graph . getVertex ( vId ) : null ; } if ( null == edgeEndVertices [ i ] ) { edgeEndVertices [ i ] = graph . addVertex ( vertexLabel ) ; if ( vertexIdKey != null ) { mapId ( vertexMappedIdMap , vertexIds [ i ] , ( ORID ) edgeEndVertices [ i ] . getId ( ) ) ; } bufferCounter ++ ; importedVertices ++ ; printStatus ( reader , importedVertices , importedEdges ) ; } } inEdge = true ; vertexLabel = null ; edgeProps = new HashMap < String , Object > ( ) ; } else if ( elementName . equals ( GraphMLTokens . DATA ) ) { String key = reader . getAttributeValue ( null , GraphMLTokens . KEY ) ; String attributeName = keyIdMap . get ( key ) ; if ( attributeName == null ) attributeName = key ; String value = reader . getElementText ( ) ; if ( inVertex ) { if ( ( vertexIdKey != null ) && ( key . equals ( vertexIdKey ) ) ) { // Should occur at most once per Vertex vertexId = value ; } else if ( attributeName . equalsIgnoreCase ( LABELS ) ) { // IGNORE LABELS } else { final Object attrValue = typeCastValue ( key , value , keyTypesMaps ) ; final OGraphMLImportStrategy strategy = vertexPropsStrategy . get ( attributeName ) ; if ( strategy != null ) { attributeName = strategy . transformAttribute ( attributeName , attrValue ) ; } if ( attributeName != null ) vertexProps . put ( attributeName , attrValue ) ; } } else if ( inEdge ) { if ( ( edgeLabelKey != null ) && ( key . equals ( edgeLabelKey ) ) ) edgeLabel = value ; else if ( ( edgeIdKey != null ) && ( key . equals ( edgeIdKey ) ) ) edgeId = value ; else { final Object attrValue = typeCastValue ( key , value , keyTypesMaps ) ; final OGraphMLImportStrategy strategy = edgePropsStrategy . get ( attributeName ) ; if ( strategy != null ) { attributeName = strategy . transformAttribute ( attributeName , attrValue ) ; } if ( attributeName != null ) edgeProps . put ( attributeName , attrValue ) ; } } } } else if ( eventType . equals ( XMLEvent . END_ELEMENT ) ) { String elementName = reader . getName ( ) . getLocalPart ( ) ; if ( elementName . equals ( GraphMLTokens . NODE ) ) { ORID currentVertex = null ; if ( vertexIdKey != null ) currentVertex = vertexMappedIdMap . get ( vertexId ) ; if ( currentVertex == null ) { final OrientVertex v = graph . addVertex ( vertexLabel , vertexProps ) ; if ( vertexIdKey != null ) mapId ( vertexMappedIdMap , vertexId , v . getIdentity ( ) ) ; bufferCounter ++ ; importedVertices ++ ; printStatus ( reader , importedVertices , importedEdges ) ; } else { // UPDATE IT final OrientVertex v = graph . getVertex ( currentVertex ) ; v . setProperties ( vertexProps ) ; } vertexId = null ; vertexLabel = null ; vertexProps = null ; inVertex = false ; } else if ( elementName . equals ( GraphMLTokens . EDGE ) ) { Edge currentEdge = ( ( OrientVertex ) edgeEndVertices [ 0 ] ) . addEdge ( null , ( OrientVertex ) edgeEndVertices [ 1 ] , edgeLabel , null , edgeProps ) ; bufferCounter ++ ; importedEdges ++ ; printStatus ( reader , importedVertices , importedEdges ) ; edgeId = null ; edgeLabel = null ; edgeEndVertices = null ; edgeProps = null ; inEdge = false ; } } if ( bufferCounter > bufferSize ) { graph . commit ( ) ; bufferCounter = 0 ; } } reader . close ( ) ; graph . commit ( ) ; } catch ( Exception xse ) { throw OException . wrapException ( new ODatabaseImportException ( \"Error on importing GraphML\" ) , xse ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the GraphML stream data into the graph . In practice usually the provided graph is empty . [CODESPLIT] public OGraphMLReader inputGraph ( final InputStream graphMLInputStream ) throws IOException { return inputGraph ( this . graph , graphMLInputStream , batchSize , this . vertexIdKey , this . edgeIdKey , this . edgeLabelKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Input the GraphML stream data into the graph . In practice usually the provided graph is empty . [CODESPLIT] public OGraphMLReader inputGraph ( final String filename ) throws IOException { return inputGraph ( this . graph , filename , batchSize , this . vertexIdKey , this . edgeIdKey , this . edgeLabelKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Date object , ByteBuffer buffer , Object ... hints ) { final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( object ) ; calendar . set ( Calendar . HOUR_OF_DAY , 0 ) ; calendar . set ( Calendar . MINUTE , 0 ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; final ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer . INSTANCE ; dateTimeSerializer . serializeInByteBufferObject ( calendar . getTime ( ) , buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Date deserializeFromByteBufferObject ( ByteBuffer buffer ) { final ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer . INSTANCE ; return dateTimeSerializer . deserializeFromByteBufferObject ( buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Date deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer . INSTANCE ; return dateTimeSerializer . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by class iterator . [CODESPLIT] public List < ORecordOperation > getNewRecordEntriesByClass ( final OClass iClass , final boolean iPolymorphic ) { final List < ORecordOperation > result = new ArrayList < ORecordOperation > ( ) ; if ( iClass == null ) // RETURN ALL THE RECORDS\r for ( ORecordOperation entry : allEntries . values ( ) ) { if ( entry . type == ORecordOperation . CREATED ) result . add ( entry ) ; } else { // FILTER RECORDS BY CLASSNAME\r for ( ORecordOperation entry : allEntries . values ( ) ) { if ( entry . type == ORecordOperation . CREATED ) if ( entry . getRecord ( ) != null && entry . getRecord ( ) instanceof ODocument ) { if ( iPolymorphic ) { if ( iClass . isSuperClassOf ( ( ( ODocument ) entry . getRecord ( ) ) . getSchemaClass ( ) ) ) result . add ( entry ) ; } else if ( iClass . getName ( ) . equals ( ( ( ODocument ) entry . getRecord ( ) ) . getClassName ( ) ) ) result . add ( entry ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by cluster iterator . [CODESPLIT] public List < ORecordOperation > getNewRecordEntriesByClusterIds ( final int [ ] iIds ) { final List < ORecordOperation > result = new ArrayList < ORecordOperation > ( ) ; if ( iIds == null ) // RETURN ALL THE RECORDS\r for ( ORecordOperation entry : allEntries . values ( ) ) { if ( entry . type == ORecordOperation . CREATED ) result . add ( entry ) ; } else // FILTER RECORDS BY ID\r for ( ORecordOperation entry : allEntries . values ( ) ) { for ( int id : iIds ) { if ( entry . getRecord ( ) != null && entry . getRecord ( ) . getIdentity ( ) . getClusterId ( ) == id && entry . type == ORecordOperation . CREATED ) { result . add ( entry ) ; break ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bufferizes index changes to be flushed at commit time . [CODESPLIT] public void addIndexEntry ( final OIndex < ? > delegate , final String iIndexName , final OTransactionIndexChanges . OPERATION iOperation , final Object key , final OIdentifiable iValue , boolean clientTrackOnly ) { OTransactionIndexChanges indexEntry = indexEntries . get ( iIndexName ) ; if ( indexEntry == null ) { indexEntry = new OTransactionIndexChanges ( ) ; indexEntries . put ( iIndexName , indexEntry ) ; } if ( iOperation == OPERATION . CLEAR ) indexEntry . setCleared ( ) ; else { OTransactionIndexChangesPerKey changes = indexEntry . getChangesPerKey ( key ) ; changes . clientTrackOnly = clientTrackOnly ; changes . add ( iValue , iOperation ) ; if ( iValue == null ) return ; List < OTransactionRecordIndexOperation > transactionIndexOperations = recordIndexOperations . get ( iValue . getIdentity ( ) ) ; if ( transactionIndexOperations == null ) { transactionIndexOperations = new ArrayList < OTransactionRecordIndexOperation > ( ) ; recordIndexOperations . put ( iValue . getIdentity ( ) . copy ( ) , transactionIndexOperations ) ; } transactionIndexOperations . add ( new OTransactionRecordIndexOperation ( iIndexName , key , iOperation ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the two set try to use the optimum case [CODESPLIT] private static Set < ORecord > mergeSet ( Set < ORecord > target , Set < ORecord > source ) { if ( source != null ) { if ( target == null ) { return source ; } else { if ( target . size ( ) > source . size ( ) ) { target . addAll ( source ) ; return target ; } else { source . addAll ( target ) ; return source ; } } } else { return target ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the actual username if successful null otherwise . [CODESPLIT] public String authenticate ( final String username , final String password ) { String principal = null ; try { if ( getServerConfig ( ) != null ) { OServerUserConfiguration userCfg = null ; // This will throw an IllegalArgumentException if username is null or empty. // However, a null or empty username is possible with some security implementations. if ( username != null && ! username . isEmpty ( ) ) userCfg = getServerConfig ( ) . getUser ( username ) ; if ( userCfg != null && userCfg . password != null ) { if ( OSecurityManager . instance ( ) . checkPassword ( password , userCfg . password ) ) { principal = userCfg . name ; } } } else { OLogManager . instance ( ) . error ( this , \"OServerConfigAuthenticator.authenticate() ServerConfig is null\" , null ) ; } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"OServerConfigAuthenticator.authenticate()\" , ex ) ; } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OSecurityAuthenticator [CODESPLIT] public void config ( final OServer oServer , final OServerConfigurationManager serverCfg , final ODocument jsonConfig ) { super . config ( oServer , serverCfg , jsonConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OSecurityAuthenticator [CODESPLIT] public OServerUserConfiguration getUser ( final String username ) { OServerUserConfiguration userCfg = null ; if ( getServerConfig ( ) != null ) { userCfg = getServerConfig ( ) . getUser ( username ) ; } return userCfg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If not supported by the authenticator return false . [CODESPLIT] public boolean isAuthorized ( final String username , final String resource ) { if ( username == null || resource == null ) return false ; if ( getServerConfig ( ) != null ) { // getUser() will throw an IllegalArgumentException if username is null or empty. // However, a null or empty username is possible with some security implementations. if ( ! username . isEmpty ( ) ) { OServerUserConfiguration userCfg = getServerConfig ( ) . getUser ( username ) ; if ( userCfg != null ) { // Total Access if ( userCfg . resources . equals ( \"*\" ) ) return true ; String [ ] resourceParts = userCfg . resources . split ( \",\" ) ; for ( String r : resourceParts ) { if ( r . equalsIgnoreCase ( resource ) ) return true ; } } } } else { OLogManager . instance ( ) . error ( this , \"OServerConfigAuthenticator.isAuthorized() ServerConfig is null\" , null ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update current record . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public boolean result ( final Object iRecord ) { final ODocument record = ( ( OIdentifiable ) iRecord ) . getRecord ( ) ; if ( isUpdateEdge ( ) && ! isRecordInstanceOf ( iRecord , \"E\" ) ) { throw new OCommandExecutionException ( \"Using UPDATE EDGE on a record that is not an instance of E\" ) ; } if ( compiledFilter != null ) { // ADDITIONAL FILTERING\r if ( ! ( Boolean ) compiledFilter . evaluate ( record , null , context ) ) return false ; } parameters . reset ( ) ; returnHandler . beforeUpdate ( record ) ; boolean updated = handleContent ( record ) ; updated |= handleMerge ( record ) ; updated |= handleSetEntries ( record ) ; updated |= handleIncrementEntries ( record ) ; updated |= handleAddEntries ( record ) ; updated |= handlePutEntries ( record ) ; updated |= handleRemoveEntries ( record ) ; if ( updated ) { handleUpdateEdge ( record ) ; record . setDirty ( ) ; record . save ( ) ; returnHandler . afterUpdate ( record ) ; this . updated = true ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles vertex consistency after an UPDATE EDGE [CODESPLIT] private void handleUpdateEdge ( ODocument record ) { if ( ! updateEdge ) { return ; } Object currentOut = record . field ( \"out\" ) ; Object currentIn = record . field ( \"in\" ) ; Object prevOut = record . getOriginalValue ( \"out\" ) ; Object prevIn = record . getOriginalValue ( \"in\" ) ; validateOutInForEdge ( record , currentOut , currentIn ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevIn , ( OIdentifiable ) currentIn , \"in\" ) ; changeVertexEdgePointer ( record , ( OIdentifiable ) prevOut , ( OIdentifiable ) currentOut , \"out\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the returning keyword if found . [CODESPLIT] protected void parseReturn ( ) throws OCommandSQLParsingException { parserNextWord ( false , \" \" ) ; String mode = parserGetLastWord ( ) . trim ( ) ; if ( mode . equalsIgnoreCase ( \"COUNT\" ) ) { returnHandler = new ORecordCountHandler ( ) ; } else if ( mode . equalsIgnoreCase ( \"BEFORE\" ) || mode . equalsIgnoreCase ( \"AFTER\" ) ) { parserNextWord ( false , \" \" ) ; String returning = parserGetLastWord ( ) . trim ( ) ; Object returnExpression = null ; if ( returning . equalsIgnoreCase ( KEYWORD_WHERE ) || returning . equalsIgnoreCase ( KEYWORD_TIMEOUT ) || returning . equalsIgnoreCase ( KEYWORD_LIMIT ) || returning . equalsIgnoreCase ( KEYWORD_UPSERT ) || returning . equalsIgnoreCase ( KEYWORD_LOCK ) || returning . length ( ) == 0 ) { parserGoBack ( ) ; } else { if ( returning . startsWith ( \"$\" ) || returning . startsWith ( \"@\" ) ) returnExpression = ( returning . length ( ) > 0 ) ? OSQLHelper . parseValue ( this , returning , this . getContext ( ) ) : null ; else throwSyntaxErrorException ( \"record attribute (@attributes) or functions with $current variable expected\" ) ; } if ( mode . equalsIgnoreCase ( \"BEFORE\" ) ) returnHandler = new OOriginalRecordsReturnHandler ( returnExpression , getContext ( ) ) ; else returnHandler = new OUpdatedRecordsReturnHandler ( returnExpression , getContext ( ) ) ; } else throwSyntaxErrorException ( \" COUNT | BEFORE | AFTER keywords expected\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see OIndexableSQLFunction . searchFromTarget () [CODESPLIT] public Iterable < OIdentifiable > executeIndexedFunction ( OFromClause target , OCommandContext ctx , OBinaryCompareOperator operator , Object rightValue ) { OSQLFunction function = OSQLEngine . getInstance ( ) . getFunction ( name . getStringValue ( ) ) ; if ( function instanceof OIndexableSQLFunction ) { return ( ( OIndexableSQLFunction ) function ) . searchFromTarget ( target , operator , rightValue , ctx , this . getParams ( ) . toArray ( new OExpression [ ] { } ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param target query target @param ctx execution context @param operator operator at the right of the function @param rightValue value to compare to funciton result [CODESPLIT] public long estimateIndexedFunction ( OFromClause target , OCommandContext ctx , OBinaryCompareOperator operator , Object rightValue ) { OSQLFunction function = OSQLEngine . getInstance ( ) . getFunction ( name . getStringValue ( ) ) ; if ( function instanceof OIndexableSQLFunction ) { return ( ( OIndexableSQLFunction ) function ) . estimate ( target , operator , rightValue , ctx , this . getParams ( ) . toArray ( new OExpression [ ] { } ) ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tests if current function is an indexed function AND that function can also be executed without using the index [CODESPLIT] public boolean canExecuteIndexedFunctionWithoutIndex ( OFromClause target , OCommandContext context , OBinaryCompareOperator operator , Object right ) { OSQLFunction function = OSQLEngine . getInstance ( ) . getFunction ( name . getStringValue ( ) ) ; if ( function instanceof OIndexableSQLFunction ) { return ( ( OIndexableSQLFunction ) function ) . canExecuteInline ( target , operator , right , context , this . getParams ( ) . toArray ( new OExpression [ ] { } ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( OIndexRIDContainer object , ByteBuffer buffer , Object ... hints ) { buffer . putLong ( object . getFileId ( ) ) ; final boolean embedded = object . isEmbedded ( ) ; final boolean durable = object . isDurableNonTxMode ( ) ; buffer . put ( ( byte ) ( embedded ? 1 : 0 ) ) ; buffer . put ( ( byte ) ( durable ? 1 : 0 ) ) ; if ( embedded ) { buffer . putInt ( object . size ( ) ) ; for ( OIdentifiable ids : object ) { LINK_SERIALIZER . serializeInByteBufferObject ( ids , buffer ) ; } } else { final OIndexRIDContainerSBTree underlying = ( OIndexRIDContainerSBTree ) object . getUnderlying ( ) ; final OBonsaiBucketPointer rootPointer = underlying . getRootPointer ( ) ; buffer . putLong ( rootPointer . getPageIndex ( ) ) ; buffer . putInt ( rootPointer . getPageOffset ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OIndexRIDContainer deserializeFromByteBufferObject ( ByteBuffer buffer ) { final long fileId = buffer . getLong ( ) ; final boolean embedded = buffer . get ( ) > 0 ; final boolean durable = buffer . get ( ) > 0 ; if ( embedded ) { final int size = buffer . getInt ( ) ; final Set < OIdentifiable > underlying = new HashSet < OIdentifiable > ( Math . max ( ( int ) ( size / .75f ) + 1 , 16 ) ) ; for ( int i = 0 ; i < size ; i ++ ) { underlying . add ( LINK_SERIALIZER . deserializeFromByteBufferObject ( buffer ) ) ; } return new OIndexRIDContainer ( fileId , underlying , durable ) ; } else { final long pageIndex = buffer . getLong ( ) ; final int pageOffset = buffer . getInt ( ) ; final OBonsaiBucketPointer rootPointer = new OBonsaiBucketPointer ( pageIndex , pageOffset ) ; final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; final OIndexRIDContainerSBTree underlying = new OIndexRIDContainerSBTree ( fileId , rootPointer , ( OAbstractPaginatedStorage ) db . getStorage ( ) . getUnderlying ( ) ) ; return new OIndexRIDContainer ( fileId , underlying , durable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { final int offset = buffer . position ( ) ; buffer . position ( ) ; if ( buffer . get ( offset + EMBEDDED_OFFSET ) > 0 ) { return embeddedObjectSerializedSize ( buffer . getInt ( offset + EMBEDDED_SIZE_OFFSET ) ) ; } else { return SBTREE_CONTAINER_SIZE ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OIndexRIDContainer deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final long fileId = walChanges . getLongValue ( buffer , offset + FILE_ID_OFFSET ) ; final boolean durable = walChanges . getByteValue ( buffer , offset + DURABLE_OFFSET ) > 0 ; if ( walChanges . getByteValue ( buffer , offset + EMBEDDED_OFFSET ) > 0 ) { final int size = walChanges . getIntValue ( buffer , offset + EMBEDDED_SIZE_OFFSET ) ; final Set < OIdentifiable > underlying = new HashSet < OIdentifiable > ( Math . max ( ( int ) ( size / .75f ) + 1 , 16 ) ) ; int p = offset + EMBEDDED_VALUES_OFFSET ; for ( int i = 0 ; i < size ; i ++ ) { underlying . add ( LINK_SERIALIZER . deserializeFromByteBufferObject ( buffer , walChanges , p ) ) ; p += RID_SIZE ; } return new OIndexRIDContainer ( fileId , underlying , durable ) ; } else { final long pageIndex = walChanges . getLongValue ( buffer , offset + SBTREE_ROOTINDEX_OFFSET ) ; final int pageOffset = walChanges . getIntValue ( buffer , offset + SBTREE_ROOTOFFSET_OFFSET ) ; final OBonsaiBucketPointer rootPointer = new OBonsaiBucketPointer ( pageIndex , pageOffset ) ; final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; final OIndexRIDContainerSBTree underlying = new OIndexRIDContainerSBTree ( fileId , rootPointer , ( OAbstractPaginatedStorage ) db . getStorage ( ) . getUnderlying ( ) ) ; return new OIndexRIDContainer ( fileId , underlying , durable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { if ( walChanges . getByteValue ( buffer , offset + EMBEDDED_OFFSET ) > 0 ) { return embeddedObjectSerializedSize ( walChanges . getIntValue ( buffer , offset + EMBEDDED_SIZE_OFFSET ) ) ; } else { return SBTREE_CONTAINER_SIZE ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a database [CODESPLIT] public ODatabaseSession open ( String database , String user , String password ) { return open ( database , user , password , OrientDBConfig . defaultConfig ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a database [CODESPLIT] public ODatabaseSession open ( String database , String user , String password , OrientDBConfig config ) { return internal . open ( database , user , password , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new database [CODESPLIT] public void create ( String database , ODatabaseType type ) { create ( database , type , OrientDBConfig . defaultConfig ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new database [CODESPLIT] public void create ( String database , ODatabaseType type , OrientDBConfig config ) { this . internal . create ( database , serverUser , serverPassword , type , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new database if not exists [CODESPLIT] public boolean createIfNotExists ( String database , ODatabaseType type ) { return createIfNotExists ( database , type , OrientDBConfig . defaultConfig ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new database if not exists [CODESPLIT] public boolean createIfNotExists ( String database , ODatabaseType type , OrientDBConfig config ) { if ( ! this . internal . exists ( database , serverUser , serverPassword ) ) { this . internal . create ( database , serverUser , serverPassword , type , config ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create proxies that support maximum number of different operations . In case when several different indexes which support different operations ( e . g . indexes of { @code UNIQUE } and { @code FULLTEXT } types ) are possible the creates the only one index of each type . [CODESPLIT] public static < T > Collection < OChainedIndexProxy < T > > createProxies ( OClass iSchemaClass , OSQLFilterItemField . FieldChain longChain ) { List < OChainedIndexProxy < T >> proxies = new ArrayList < OChainedIndexProxy < T > > ( ) ; for ( List < OIndex < ? > > indexChain : getIndexesForChain ( iSchemaClass , longChain ) ) { proxies . add ( new OChainedIndexProxy < T > ( indexChain ) ) ; } return proxies ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the index that fits better as a base index in chain . Requirements to the base index : <ul > <li > Should be unique or not unique . Other types cannot be used to get all documents with required links . < / li > <li > Should not be composite hash index . As soon as hash index does not support partial match search . < / li > <li > Composite index that ignores null values should not be used . < / li > <li > Hash index is better than tree based indexes . < / li > <li > Non composite indexes is better that composite . < / li > < / ul > [CODESPLIT] protected static OIndex < ? > findBestIndex ( Iterable < OIndex < ? > > indexes ) { OIndex < ? > bestIndex = null ; for ( OIndex < ? > index : indexes ) { if ( priorityOfUsage ( index ) > priorityOfUsage ( bestIndex ) ) bestIndex = index ; } return bestIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public long getRebuildVersion ( ) { long rebuildVersion = 0 ; for ( OIndex < ? > index : indexChain ) { rebuildVersion += index . getRebuildVersion ( ) ; } return rebuildVersion ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public T get ( Object iKey ) { final Object lastIndexResult = lastIndex . get ( iKey ) ; final Set < OIdentifiable > result = new HashSet < OIdentifiable > ( ) ; if ( lastIndexResult != null ) result . addAll ( applyTailIndexes ( lastIndexResult ) ) ; return ( T ) result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make type conversion of keys for specific index . [CODESPLIT] private Set < Comparable > prepareKeys ( OIndex < ? > index , Object keys ) { final OIndexDefinition indexDefinition = index . getDefinition ( ) ; if ( keys instanceof Collection ) { final Set < Comparable > newKeys = new TreeSet < Comparable > ( ) ; for ( Object o : ( ( Collection ) keys ) ) { newKeys . add ( ( Comparable ) indexDefinition . createValue ( o ) ) ; } return newKeys ; } else { return Collections . singleton ( ( Comparable ) indexDefinition . createValue ( keys ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register statistic information about usage of index in { @link OProfilerStub } . [CODESPLIT] private void updateStatistic ( OIndex < ? > index ) { final OProfiler profiler = Orient . instance ( ) . getProfiler ( ) ; if ( profiler . isRecording ( ) ) { Orient . instance ( ) . getProfiler ( ) . updateCounter ( profiler . getDatabaseMetric ( index . getDatabaseName ( ) , \"query.indexUsed\" ) , \"Used index in query\" , + 1 ) ; final int paramCount = index . getDefinition ( ) . getParamCount ( ) ; if ( paramCount > 1 ) { final String profiler_prefix = profiler . getDatabaseMetric ( index . getDatabaseName ( ) , \"query.compositeIndexUsed\" ) ; profiler . updateCounter ( profiler_prefix , \"Used composite index in query\" , + 1 ) ; profiler . updateCounter ( profiler_prefix + \".\" + paramCount , \"Used composite index in query with \" + paramCount + \" params\" , + 1 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes page with given page index to the cache and eventually writes it to the file . [CODESPLIT] void writePage ( ByteBuffer page , long pageIndex ) throws IOException { synchronized ( lockObject ) { lastAccessTime = System . nanoTime ( ) ; if ( pageIndex >= firstCachedPage && pageIndex <= firstCachedPage + pageCache . size ( ) ) { if ( pageIndex < firstCachedPage + pageCache . size ( ) ) { pageCache . set ( ( int ) ( pageIndex - firstCachedPage ) , page ) ; } else { pageCache . add ( page ) ; } } else if ( pageCache . isEmpty ( ) ) { pageCache . add ( page ) ; firstCachedPage = pageIndex ; } lastWrittenPage = page ; lastWrittenPageIndex = pageIndex ; if ( pageCache . size ( ) * OWALPage . PAGE_SIZE >= bufferSize + OWALPage . PAGE_SIZE ) { flushAllBufferPagesExceptLastOne ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read page content with given index from cache or file . [CODESPLIT] byte [ ] readPage ( long pageIndex ) throws IOException { synchronized ( lockObject ) { lastAccessTime = System . nanoTime ( ) ; if ( pageIndex == lastWrittenPageIndex ) { return lastWrittenPage . array ( ) ; } if ( pageIndex >= firstCachedPage && pageIndex < firstCachedPage + pageCache . size ( ) ) { final ByteBuffer buffer = pageCache . get ( ( int ) ( pageIndex - firstCachedPage ) ) ; return buffer . array ( ) ; } final ByteBuffer buffer = ByteBuffer . allocate ( OWALPage . PAGE_SIZE ) . order ( ByteOrder . nativeOrder ( ) ) ; initFile ( ) ; segChannel . position ( pageIndex * OWALPage . PAGE_SIZE ) ; readByteBuffer ( buffer , segChannel ) ; return buffer . array ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flushes all buffered pages and truncates file till passed in page index [CODESPLIT] void truncate ( long pageIndex ) throws IOException { synchronized ( lockObject ) { lastAccessTime = System . nanoTime ( ) ; flushBuffer ( ) ; lastWrittenPageIndex = - 1 ; lastWrittenPage = null ; segChannel . truncate ( pageIndex * OWALPage . PAGE_SIZE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads page content from the cache to the <code > ByteBuffer< / code > <code > ByteBuffer< / code > is not backed by the cache and can be freely changed [CODESPLIT] ByteBuffer readPageBuffer ( long pageIndex ) throws IOException { synchronized ( lockObject ) { lastAccessTime = System . nanoTime ( ) ; if ( pageIndex == lastWrittenPageIndex ) { final ByteBuffer copy = ByteBuffer . allocate ( OWALPage . PAGE_SIZE ) . order ( ByteOrder . nativeOrder ( ) ) ; lastWrittenPage . position ( 0 ) ; copy . put ( lastWrittenPage ) ; return copy ; } if ( pageIndex >= firstCachedPage && pageIndex < firstCachedPage + pageCache . size ( ) ) { final ByteBuffer buffer = pageCache . get ( ( int ) ( pageIndex - firstCachedPage ) ) ; final ByteBuffer copy = ByteBuffer . allocate ( OWALPage . PAGE_SIZE ) . order ( ByteOrder . nativeOrder ( ) ) ; buffer . position ( 0 ) ; copy . put ( buffer ) ; return copy ; } final ByteBuffer buffer = ByteBuffer . allocate ( OWALPage . PAGE_SIZE ) . order ( ByteOrder . nativeOrder ( ) ) ; initFile ( ) ; segChannel . position ( pageIndex * OWALPage . PAGE_SIZE ) ; readByteBuffer ( buffer , segChannel ) ; buffer . position ( 0 ) ; return buffer ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes cache content to the file and performs <code > fsync< / code > [CODESPLIT] public void sync ( ) throws IOException { synchronized ( lockObject ) { if ( segChannel != null ) { lastAccessTime = System . nanoTime ( ) ; flushBuffer ( ) ; segChannel . force ( false ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes cache content to the file and closes it . Calls <code > fsync< / code > if needed . [CODESPLIT] public void close ( boolean flush ) { closer . shutdown ( ) ; try { if ( ! closer . awaitTermination ( CLOSER_TIMEOUT_MIN , TimeUnit . MINUTES ) ) { OLogManager . instance ( ) . error ( this , \"Can not close file \" + path . getFileName ( ) , null ) ; } else { synchronized ( lockObject ) { try { if ( segChannel != null ) { closeFile ( flush ) ; } } catch ( IOException ioe ) { OLogManager . instance ( ) . error ( this , \"Can not close file \" + path . getFileName ( ) , ioe ) ; } } } } catch ( InterruptedException ie ) { OLogManager . instance ( ) . warn ( this , \"WAL file \" + path . getFileName ( ) + \" close was interrupted\" , ie ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes cache and opens underlying file . [CODESPLIT] public void open ( ) throws IOException { synchronized ( lockObject ) { lastAccessTime = System . nanoTime ( ) ; initFile ( ) ; long pagesCount = segChannel . size ( ) / OWALPage . PAGE_SIZE ; if ( segChannel . size ( ) % OWALPage . PAGE_SIZE > 0 ) { OLogManager . instance ( ) . error ( this , \"Last WAL page was written partially, auto fix\" , null ) ; segChannel . truncate ( OWALPage . PAGE_SIZE * pagesCount ) ; } firstCachedPage = - 1 ; pageCache . clear ( ) ; lastWrittenPage = null ; lastWrittenPageIndex = - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public byte [ ] getRecord ( int position ) { buffer . position ( position + 2 ) ; final int recordSize = buffer . getInt ( ) ; final byte [ ] record = new byte [ recordSize ] ; buffer . get ( record ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the replication is active otherwise false . [CODESPLIT] public boolean isReplicationActive ( final String iClusterName , final String iLocalNode ) { final Collection < String > servers = getClusterConfiguration ( iClusterName ) . field ( SERVERS ) ; if ( servers != null && ! servers . isEmpty ( ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the new node strategy between dynamic and static . If static the node is registered under the server tag . [CODESPLIT] public NEW_NODE_STRATEGIES getNewNodeStrategy ( ) { final String value = configuration . field ( NEW_NODE_STRATEGY ) ; if ( value != null ) return NEW_NODE_STRATEGIES . valueOf ( value . toUpperCase ( Locale . ENGLISH ) ) ; return NEW_NODE_STRATEGIES . STATIC ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the execution mode if synchronous . [CODESPLIT] public Boolean isExecutionModeSynchronous ( final String iClusterName ) { Object value = getClusterConfiguration ( iClusterName ) . field ( EXECUTION_MODE ) ; if ( value == null ) { value = configuration . field ( EXECUTION_MODE ) ; if ( value == null ) return null ; } if ( value . toString ( ) . equalsIgnoreCase ( \"undefined\" ) ) return null ; return value . toString ( ) . equalsIgnoreCase ( EXECUTION_MODE_SYNCHRONOUS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads your writes . [CODESPLIT] public Boolean isReadYourWrites ( final String iClusterName ) { Object value = getClusterConfiguration ( iClusterName ) . field ( READ_YOUR_WRITES ) ; if ( value == null ) { value = configuration . field ( READ_YOUR_WRITES ) ; if ( value == null ) { OLogManager . instance ( ) . warn ( this , \"%s setting not found for cluster=%s in distributed-config.json\" , READ_YOUR_WRITES , iClusterName ) ; return true ; } } return ( Boolean ) value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the list of servers that can manage a list of clusters . The algorithm makes its best to involve the less servers as it can . [CODESPLIT] public Map < String , Collection < String > > getServerClusterMap ( Collection < String > iClusterNames , final String iLocalNode , final boolean optimizeForLocalOnly ) { if ( iClusterNames == null || iClusterNames . isEmpty ( ) ) iClusterNames = DEFAULT_CLUSTER_NAME ; final Map < String , Collection < String > > servers = new HashMap < String , Collection < String > > ( iClusterNames . size ( ) ) ; // TRY TO SEE IF IT CAN BE EXECUTED ON LOCAL NODE ONLY boolean canUseLocalNode = true ; for ( String p : iClusterNames ) { final List < String > serverList = getClusterConfiguration ( p ) . field ( SERVERS ) ; if ( serverList != null && ! serverList . contains ( iLocalNode ) ) { canUseLocalNode = false ; break ; } } if ( optimizeForLocalOnly && canUseLocalNode ) { // USE LOCAL NODE ONLY (MUCH FASTER) servers . put ( iLocalNode , iClusterNames ) ; return servers ; } // GROUP BY SERVER WITH THE NUMBER OF CLUSTERS final Map < String , Collection < String > > serverMap = new HashMap < String , Collection < String > > ( ) ; for ( String p : iClusterNames ) { final List < String > serverList = getClusterConfiguration ( p ) . field ( SERVERS ) ; for ( String s : serverList ) { if ( NEW_NODE_TAG . equalsIgnoreCase ( s ) ) continue ; Collection < String > clustersInServer = serverMap . get ( s ) ; if ( clustersInServer == null ) { clustersInServer = new HashSet < String > ( ) ; serverMap . put ( s , clustersInServer ) ; } clustersInServer . add ( p ) ; } } if ( serverMap . size ( ) == 1 ) // RETURN THE ONLY SERVER INVOLVED return serverMap ; if ( ! optimizeForLocalOnly ) return serverMap ; // ORDER BY NUMBER OF CLUSTERS final List < String > orderedServers = new ArrayList < String > ( serverMap . keySet ( ) ) ; Collections . sort ( orderedServers , new Comparator < String > ( ) { @ Override public int compare ( final String o1 , final String o2 ) { return ( ( Integer ) serverMap . get ( o2 ) . size ( ) ) . compareTo ( ( Integer ) serverMap . get ( o1 ) . size ( ) ) ; } } ) ; // BROWSER ORDERED SERVER MAP PUTTING THE MINIMUM SERVER TO COVER ALL THE CLUSTERS final Set < String > remainingClusters = new HashSet < String > ( iClusterNames ) ; // KEEPS THE REMAINING CLUSTER TO ADD IN FINAL // RESULT final Set < String > includedClusters = new HashSet < String > ( iClusterNames . size ( ) ) ; // KEEPS THE COLLECTION OF ALREADY INCLUDED // CLUSTERS for ( String s : orderedServers ) { final Collection < String > clusters = serverMap . get ( s ) ; if ( ! servers . isEmpty ( ) ) { // FILTER CLUSTER LIST AVOIDING TO REPEAT CLUSTERS ALREADY INCLUDED ON PREVIOUS NODES clusters . removeAll ( includedClusters ) ; } servers . put ( s , clusters ) ; remainingClusters . removeAll ( clusters ) ; includedClusters . addAll ( clusters ) ; if ( remainingClusters . isEmpty ( ) ) // FOUND ALL CLUSTERS break ; } return servers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the clusters where a server is owner . This is used when a cluster must be selected : locality is always the best choice . [CODESPLIT] public List < String > getOwnedClustersByServer ( Collection < String > iClusterNames , final String iNode ) { if ( iClusterNames == null || iClusterNames . isEmpty ( ) ) iClusterNames = DEFAULT_CLUSTER_NAME ; final List < String > notDefinedClusters = new ArrayList < String > ( 5 ) ; final List < String > candidates = new ArrayList < String > ( 5 ) ; for ( String p : iClusterNames ) { if ( p == null ) continue ; final String ownerServer = getClusterOwner ( p ) ; if ( ownerServer == null ) notDefinedClusters . add ( p ) ; else if ( iNode . equals ( ownerServer ) ) { // COLLECT AS CANDIDATE candidates . add ( p ) ; } } if ( ! candidates . isEmpty ( ) ) // RETURN THE FIRST ONE return candidates ; final String owner = getClusterOwner ( ALL_WILDCARD ) ; if ( iNode . equals ( owner ) ) // CURRENT SERVER IS MASTER OF DEFAULT: RETURN ALL THE NON CONFIGURED CLUSTERS return notDefinedClusters ; // NO MASTER FOUND, RETURN EMPTY LIST return candidates ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the set of server names involved on the passed cluster collection . [CODESPLIT] public Set < String > getServers ( Collection < String > iClusterNames ) { if ( iClusterNames == null || iClusterNames . isEmpty ( ) ) return getAllConfiguredServers ( ) ; final Set < String > partitions = new HashSet < String > ( iClusterNames . size ( ) ) ; for ( String p : iClusterNames ) { final List < String > serverList = getClusterConfiguration ( p ) . field ( SERVERS ) ; if ( serverList != null ) { for ( String s : serverList ) if ( ! s . equals ( NEW_NODE_TAG ) ) partitions . add ( s ) ; } } return partitions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the local server has all the requested clusters . [CODESPLIT] public boolean isServerContainingAllClusters ( final String server , Collection < String > clusters ) { if ( clusters == null || clusters . isEmpty ( ) ) clusters = DEFAULT_CLUSTER_NAME ; for ( String cluster : clusters ) { final List < String > serverList = getClusterConfiguration ( cluster ) . field ( SERVERS ) ; if ( serverList != null ) { if ( ! serverList . contains ( server ) ) return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the local server has the requested cluster . [CODESPLIT] public boolean isServerContainingCluster ( final String server , String cluster ) { if ( cluster == null ) cluster = ALL_WILDCARD ; final List < String > serverList = getClusterConfiguration ( cluster ) . field ( SERVERS ) ; if ( serverList != null ) { return serverList . contains ( server ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the server list for the requested cluster cluster excluding any tags like <NEW_NODES > and iExclude if any . [CODESPLIT] public List < String > getServers ( final String iClusterName , final String iExclude ) { final List < String > serverList = getClusterConfiguration ( iClusterName ) . field ( SERVERS ) ; if ( serverList != null ) { // COPY AND REMOVE ANY NEW_NODE_TAG List < String > filteredServerList = new ArrayList < String > ( serverList . size ( ) ) ; for ( String s : serverList ) { if ( ! s . equals ( NEW_NODE_TAG ) && ( iExclude == null || ! iExclude . equals ( s ) ) ) filteredServerList . add ( s ) ; } return filteredServerList ; } return Collections . EMPTY_LIST ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an ordered list of master server . The first in the list is the first found in configuration . This is used to determine the cluster leader . [CODESPLIT] public List < String > getMasterServers ( ) { final List < String > serverList = getClusterConfiguration ( null ) . field ( SERVERS ) ; if ( serverList != null ) { // COPY AND REMOVE ANY NEW_NODE_TAG List < String > masters = new ArrayList < String > ( serverList . size ( ) ) ; for ( String s : serverList ) { if ( ! s . equals ( NEW_NODE_TAG ) ) masters . add ( s ) ; } final ROLES defRole = getDefaultServerRole ( ) ; final ODocument servers = configuration . field ( SERVERS ) ; if ( servers != null ) { for ( Iterator < String > it = masters . iterator ( ) ; it . hasNext ( ) ; ) { final String server = it . next ( ) ; final String roleAsString = servers . field ( server ) ; final ROLES role = roleAsString != null ? ROLES . valueOf ( roleAsString . toUpperCase ( Locale . ENGLISH ) ) : defRole ; if ( role != ROLES . MASTER ) it . remove ( ) ; } } return masters ; } return Collections . EMPTY_LIST ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the complete list of servers found in configuration . [CODESPLIT] public Set < String > getAllConfiguredServers ( ) { final Set < String > servers = new HashSet < String > ( ) ; for ( String p : getClusterNames ( ) ) { final List < String > serverList = getClusterConfiguration ( p ) . field ( SERVERS ) ; if ( serverList != null ) { for ( String s : serverList ) if ( ! s . equals ( NEW_NODE_TAG ) ) servers . add ( s ) ; } } return servers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the set of clusters managed by a server . [CODESPLIT] public Set < String > getClustersOnServer ( final String iNodeName ) { final Set < String > clusters = new HashSet < String > ( ) ; for ( String cl : getClusterNames ( ) ) { final List < String > servers = getServers ( cl , null ) ; if ( servers . contains ( iNodeName ) ) clusters . add ( cl ) ; } return clusters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the set of clusters where server is the owner . [CODESPLIT] public Set < String > getClustersOwnedByServer ( final String iNodeName ) { final Set < String > clusters = new HashSet < String > ( ) ; for ( String cl : getClusterNames ( ) ) { if ( iNodeName . equals ( getClusterOwner ( cl ) ) ) clusters . add ( cl ) ; } return clusters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the owner server for the given cluster excluding the passed node . The Owner server is the first in server list . [CODESPLIT] public String getClusterOwner ( final String iClusterName ) { String owner ; final ODocument clusters = getConfiguredClusters ( ) ; // GET THE CLUSTER CFG final ODocument cfg = iClusterName != null ? ( ODocument ) clusters . field ( iClusterName ) : null ; if ( cfg != null ) { owner = cfg . field ( OWNER ) ; if ( owner != null ) return owner ; final List < String > serverList = cfg . field ( SERVERS ) ; if ( serverList != null && ! serverList . isEmpty ( ) ) { // RETURN THE FIRST ONE owner = serverList . get ( 0 ) ; if ( NEW_NODE_TAG . equals ( owner ) && serverList . size ( ) > 1 ) // DON'T RETURN <NEW_NODE> owner = serverList . get ( 1 ) ; } } else // RETURN THE OWNER OF * return getClusterOwner ( ALL_WILDCARD ) ; return owner ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the static owner server for the given cluster . [CODESPLIT] public String getConfiguredClusterOwner ( final String iClusterName ) { String owner = null ; final ODocument clusters = getConfiguredClusters ( ) ; // GET THE CLUSTER CFG final ODocument cfg = clusters . field ( iClusterName ) ; if ( cfg != null ) owner = cfg . field ( OWNER ) ; return owner ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the configured server list for the requested cluster . [CODESPLIT] public List < String > getConfiguredServers ( final String iClusterName ) { final Collection < ? extends String > list = ( Collection < ? extends String > ) getClusterConfiguration ( iClusterName ) . field ( SERVERS ) ; return list != null ? new ArrayList < String > ( list ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the server role between MASTER ( default ) and REPLICA . [CODESPLIT] public ROLES getServerRole ( final String iServerName ) { final ODocument servers = configuration . field ( SERVERS ) ; if ( servers == null ) // DEFAULT: MASTER return ROLES . MASTER ; String role = servers . field ( iServerName ) ; if ( role == null ) { // DEFAULT: MASTER role = servers . field ( ALL_WILDCARD ) ; if ( role == null ) // DEFAULT: MASTER return ROLES . MASTER ; } return ROLES . valueOf ( role . toUpperCase ( Locale . ENGLISH ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the registered servers . [CODESPLIT] public Set < String > getRegisteredServers ( ) { final ODocument servers = configuration . field ( SERVERS ) ; final Set < String > result = new HashSet < String > ( ) ; if ( servers != null ) for ( String s : servers . fieldNames ( ) ) result . ( s ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the configured data centers names if any . [CODESPLIT] public Set < String > getDataCenters ( ) { final ODocument dcs = configuration . field ( DCS ) ; if ( dcs == null ) return Collections . EMPTY_SET ; final Set < String > result = new HashSet < String > ( ) ; for ( String dc : dcs . fieldNames ( ) ) { result . add ( dc ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the data center write quorum . [CODESPLIT] public int getDataCenterWriteQuorum ( final String dataCenter ) { final ODocument dc = getDataCenterConfiguration ( dataCenter ) ; Object wq = dc . field ( WRITE_QUORUM ) ; if ( wq instanceof String ) { if ( wq . toString ( ) . equalsIgnoreCase ( ODistributedConfiguration . QUORUM_MAJORITY ) ) { final List < String > servers = dc . field ( SERVERS ) ; wq = servers . size ( ) / 2 + 1 ; } else if ( wq . toString ( ) . equalsIgnoreCase ( ODistributedConfiguration . QUORUM_ALL ) ) { final List < String > servers = dc . field ( SERVERS ) ; wq = servers . size ( ) ; } } return ( Integer ) wq ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the database is sharded across servers . False if it s completely replicated . [CODESPLIT] public boolean isSharded ( ) { final ODocument allCluster = getClusterConfiguration ( ALL_WILDCARD ) ; if ( allCluster != null ) { final List < String > allServers = allCluster . field ( SERVERS ) ; if ( allServers != null && ! allServers . isEmpty ( ) ) { for ( String cl : getClusterNames ( ) ) { final List < String > servers = getServers ( cl , null ) ; if ( servers != null && ! servers . isEmpty ( ) && ! allServers . containsAll ( servers ) ) return false ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the list of servers in a data center . [CODESPLIT] public List < String > getDataCenterServers ( final String dataCenter ) { final ODocument dc = getDataCenterConfiguration ( dataCenter ) ; final List < String > servers = dc . field ( SERVERS ) ; if ( servers == null || servers . isEmpty ( ) ) throw new OConfigurationException ( \"Data center '\" + dataCenter + \"' does not contain any server in distributed database configuration\" ) ; return new ArrayList < String > ( servers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the data center where the server belongs . [CODESPLIT] public String getDataCenterOfServer ( final String server ) { final ODocument dcs = configuration . field ( DCS ) ; if ( dcs != null ) { for ( String dc : dcs . fieldNames ( ) ) { final ODocument dcConfig = dcs . field ( dc ) ; if ( dcConfig != null ) { final List < String > dcServers = dcConfig . field ( \"servers\" ) ; if ( dcServers != null && ! dcServers . isEmpty ( ) ) { if ( dcServers . contains ( server ) ) // FOUND return dc ; } } } } // NOT FOUND return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the global read quorum . [CODESPLIT] public Object getGlobalReadQuorum ( final String iClusterName ) { Object value = getClusterConfiguration ( iClusterName ) . field ( READ_QUORUM ) ; if ( value == null ) value = configuration . field ( READ_QUORUM ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the read quorum . [CODESPLIT] public int getReadQuorum ( final String clusterName , final int totalConfiguredServers , final String server ) { return getQuorum ( \"readQuorum\" , clusterName , totalConfiguredServers , DEFAULT_READ_QUORUM , server ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the write quorum . [CODESPLIT] public int getWriteQuorum ( final String clusterName , final int totalConfiguredMasterServers , final String server ) { Integer overWrite = overwriteWriteQuorum . get ( ) ; if ( overWrite != null ) return overWrite . intValue ( ) ; else return getQuorum ( \"writeQuorum\" , clusterName , totalConfiguredMasterServers , DEFAULT_WRITE_QUORUM , server ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the document representing the cluster configuration . [CODESPLIT] protected ODocument getClusterConfiguration ( String iClusterName ) { final ODocument clusters = getConfiguredClusters ( ) ; if ( iClusterName == null ) iClusterName = ALL_WILDCARD ; final ODocument cfg ; if ( ! clusters . containsField ( iClusterName ) ) // NO CLUSTER IN CFG: GET THE DEFAULT ONE cfg = clusters . field ( ALL_WILDCARD ) ; else // GET THE CLUSTER CFG cfg = clusters . field ( iClusterName ) ; if ( cfg == null ) return new ODocument ( ) ; return cfg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the document representing the dc configuration . [CODESPLIT] private ODocument getDataCenterConfiguration ( final String dataCenter ) { final ODocument dcs = configuration . field ( DCS ) ; if ( dcs != null ) return dcs . field ( dataCenter ) ; throw new OConfigurationException ( \"Cannot find the data center '\" + dataCenter + \"' in distributed database configuration\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the read quorum . [CODESPLIT] private int getQuorum ( final String quorumSetting , final String iClusterName , final int totalServers , final Object defaultValue , final String server ) { Object value = getClusterConfiguration ( iClusterName ) . field ( quorumSetting ) ; if ( value == null ) { value = configuration . field ( quorumSetting ) ; if ( value == null ) { OLogManager . instance ( ) . warn ( this , \"%s setting not found for cluster=%s in distributed-config.json\" , quorumSetting , iClusterName ) ; value = defaultValue ; } } if ( value instanceof String ) { if ( value . toString ( ) . equalsIgnoreCase ( QUORUM_MAJORITY ) ) value = totalServers / 2 + 1 ; else if ( value . toString ( ) . equalsIgnoreCase ( QUORUM_ALL ) ) value = totalServers ; else if ( value . toString ( ) . equalsIgnoreCase ( QUORUM_LOCAL_DC ) ) { final String dc = getDataCenterOfServer ( server ) ; if ( dc == null ) throw new OConfigurationException ( \"Data center not specified for server '\" + server + \"' in distributed configuration\" ) ; value = getDataCenterWriteQuorum ( dc ) ; } else throw new OConfigurationException ( \"The value '\" + value + \"' is not supported for \" + quorumSetting + \" in distributed configuration\" ) ; } return ( Integer ) value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal use only . [CODESPLIT] public static void clearInitStack ( ) { final ThreadLocal < Deque < OrientBaseGraph > > is = initializationStack ; if ( is != null ) is . get ( ) . clear ( ) ; final ThreadLocal < OrientBaseGraph > ag = activeGraph ; if ( ag != null ) ag . remove ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal ) [CODESPLIT] public static void encodeClassNames ( final String ... iLabels ) { if ( iLabels != null ) // ENCODE LABELS for ( int i = 0 ; i < iLabels . length ; ++ i ) iLabels [ i ] = encodeClassName ( iLabels [ i ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal ) Returns the case sensitive edge class names . [CODESPLIT] public static void getEdgeClassNames ( final OrientBaseGraph graph , final String ... iLabels ) { if ( iLabels != null && graph != null && graph . isUseClassForEdgeLabel ( ) ) { for ( int i = 0 ; i < iLabels . length ; ++ i ) { final OrientEdgeType edgeType = graph . getEdgeType ( iLabels [ i ] ) ; if ( edgeType != null ) // OVERWRITE CLASS NAME BECAUSE ATTRIBUTES ARE CASE SENSITIVE iLabels [ i ] = edgeType . getName ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal ) [CODESPLIT] public static String encodeClassName ( String iClassName ) { if ( iClassName == null ) return null ; if ( Character . isDigit ( iClassName . charAt ( 0 ) ) ) iClassName = \"-\" + iClassName ; try { return URLEncoder . encode ( iClassName , \"UTF-8\" ) . replaceAll ( \"\\\\.\" , \"%2E\" ) ; // encode invalid '.' } catch ( UnsupportedEncodingException e ) { OLogManager . instance ( ) . error ( null , \"Error on encoding class name using encoding '%s'\" , e , \"UTF-8\" ) ; return iClassName ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal ) [CODESPLIT] public static String decodeClassName ( String iClassName ) { if ( iClassName == null ) return null ; if ( iClassName . charAt ( 0 ) == ' ' ) iClassName = iClassName . substring ( 1 ) ; try { return URLDecoder . decode ( iClassName , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { OLogManager . instance ( ) . error ( null , \"Error on decoding class name using encoding '%s'\" , e , \"UTF-8\" ) ; return iClassName ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Configure the Graph instance . [CODESPLIT] public OrientBaseGraph configure ( final Settings iSetting ) { makeActive ( ) ; if ( iSetting != null ) { if ( settings == null ) { settings = iSetting ; } else { settings . copyFrom ( iSetting ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an index by name and class [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public < T extends Element > Index < T > getIndex ( final String indexName , final Class < T > indexClass ) { makeActive ( ) ; final OIndexManager indexManager = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) ; final OIndex idx = indexManager . getIndex ( indexName ) ; if ( idx == null || ! hasIndexClass ( idx ) ) return null ; final Index < ? extends Element > index = new OrientIndex ( this , idx ) ; if ( indexClass . isAssignableFrom ( index . getIndexClass ( ) ) ) return ( Index < T > ) index ; else throw ExceptionFactory . indexDoesNotSupportClass ( indexName , indexClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drops an index by name . [CODESPLIT] public void dropIndex ( final String indexName ) { makeActive ( ) ; executeOutsideTx ( new OCallable < Object , OrientBaseGraph > ( ) { @ Override public Object call ( OrientBaseGraph g ) { try { final OIndexManager indexManager = getRawGraph ( ) . getMetadata ( ) . getIndexManager ( ) ; final OIndex index = indexManager . getIndex ( indexName ) ; ODocument metadata = index . getConfiguration ( ) . field ( \"metadata\" ) ; String recordMapIndexName = null ; if ( metadata != null ) { recordMapIndexName = metadata . field ( OrientIndex . CONFIG_RECORD_MAP_NAME ) ; } indexManager . dropIndex ( indexName ) ; if ( recordMapIndexName != null ) getRawGraph ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( recordMapIndexName ) ; saveIndexConfiguration ( ) ; return null ; } catch ( Exception e ) { g . rollback ( ) ; throw new RuntimeException ( e . getMessage ( ) , e ) ; } } } , \"drop index '\" , indexName , \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new unconnected vertex with no fields in the Graph . [CODESPLIT] @ Override public OrientVertex addVertex ( final Object id ) { makeActive ( ) ; return addVertex ( id , ( Object [ ] ) null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Creates a new unconnected vertex in the Graph setting the initial field values . [CODESPLIT] public OrientVertex addVertex ( Object id , final Object ... prop ) { makeActive ( ) ; String className = null ; String clusterName = null ; Object [ ] fields = null ; if ( id != null ) { if ( id instanceof String ) { // PARSE ARGUMENTS final String [ ] args = ( ( String ) id ) . split ( \",\" ) ; for ( String s : args ) { if ( s . startsWith ( CLASS_PREFIX ) ) // GET THE CLASS NAME className = s . substring ( CLASS_PREFIX . length ( ) ) ; else if ( s . startsWith ( CLUSTER_PREFIX ) ) // GET THE CLASS NAME clusterName = s . substring ( CLUSTER_PREFIX . length ( ) ) ; else id = s ; } } if ( isSaveOriginalIds ( ) ) // SAVE THE ID TOO fields = new Object [ ] { OrientElement . DEF_ORIGINAL_ID_FIELDNAME , id } ; } setCurrentGraphInThreadLocal ( ) ; autoStartTransaction ( ) ; final OrientVertex vertex = getVertexInstance ( className , fields ) ; vertex . setPropertiesInternal ( prop ) ; // SAVE IT if ( clusterName != null ) vertex . save ( clusterName ) ; else vertex . save ( ) ; return vertex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Creates a new unconnected vertex with no fields of specific class in a cluster in the Graph . [CODESPLIT] public OrientVertex addVertex ( final String iClassName , final String iClusterName ) { makeActive ( ) ; setCurrentGraphInThreadLocal ( ) ; autoStartTransaction ( ) ; final OrientVertex vertex = getVertexInstance ( iClassName ) ; // SAVE IT if ( iClusterName != null ) vertex . save ( iClusterName ) ; else vertex . save ( ) ; return vertex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Creates a temporary vertex setting the initial field values . The vertex is not saved and the transaction is not started . [CODESPLIT] public OrientVertex addTemporaryVertex ( final String iClassName , final Object ... prop ) { makeActive ( ) ; setCurrentGraphInThreadLocal ( ) ; autoStartTransaction ( ) ; final OrientVertex vertex = getVertexInstance ( iClassName ) ; vertex . setPropertiesInternal ( prop ) ; return vertex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an edge between a source Vertex and a destination Vertex setting label as Edge s label . [CODESPLIT] @ Override public OrientEdge addEdge ( final Object id , Vertex outVertex , Vertex inVertex , final String label ) { makeActive ( ) ; String className = null ; String clusterName = null ; if ( id != null ) { if ( id instanceof String ) { // PARSE ARGUMENTS final String [ ] args = ( ( String ) id ) . split ( \",\" ) ; for ( String s : args ) { if ( s . startsWith ( CLASS_PREFIX ) ) // GET THE CLASS NAME className = s . substring ( CLASS_PREFIX . length ( ) ) ; else if ( s . startsWith ( CLUSTER_PREFIX ) ) // GET THE CLASS NAME clusterName = s . substring ( CLUSTER_PREFIX . length ( ) ) ; } } } // SAVE THE ID TOO? final Object [ ] fields = isSaveOriginalIds ( ) && id != null ? new Object [ ] { OrientElement . DEF_ORIGINAL_ID_FIELDNAME , id } : null ; if ( outVertex instanceof PartitionVertex ) // WRAPPED: GET THE BASE VERTEX outVertex = ( ( PartitionVertex ) outVertex ) . getBaseVertex ( ) ; if ( inVertex instanceof PartitionVertex ) // WRAPPED: GET THE BASE VERTEX inVertex = ( ( PartitionVertex ) inVertex ) . getBaseVertex ( ) ; return ( ( OrientVertex ) outVertex ) . addEdge ( label , ( OrientVertex ) inVertex , className , clusterName , fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a vertex by an ID . [CODESPLIT] public OrientVertex getVertex ( final Object id ) { makeActive ( ) ; if ( null == id ) throw ExceptionFactory . vertexIdCanNotBeNull ( ) ; if ( id instanceof OrientVertex ) return ( OrientVertex ) id ; else if ( id instanceof ODocument ) return getVertexInstance ( ( OIdentifiable ) id ) ; setCurrentGraphInThreadLocal ( ) ; ORID rid ; if ( id instanceof OIdentifiable ) rid = ( ( OIdentifiable ) id ) . getIdentity ( ) ; else { try { rid = new ORecordId ( id . toString ( ) ) ; } catch ( IllegalArgumentException iae ) { // orientdb throws IllegalArgumentException: Argument 'xxxx' is // not a RecordId in form of string. Format must be: // <cluster-id>:<cluster-position> return null ; } } if ( ! rid . isValid ( ) ) return null ; final ORecord rec = rid . getRecord ( ) ; if ( rec == null || ! ( rec instanceof ODocument ) ) return null ; final OClass cls = ( ( ODocument ) rec ) . getSchemaClass ( ) ; if ( cls != null && cls . isEdgeType ( ) ) throw new IllegalArgumentException ( \"Cannot retrieve a vertex with the RID \" + rid + \" because it is an edge\" ) ; return getVertexInstance ( rec ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the Vertices in Graph of a specific vertex class and all sub - classes only if iPolymorphic is true . [CODESPLIT] public Iterable < Vertex > getVerticesOfClass ( final String iClassName , final boolean iPolymorphic ) { makeActive ( ) ; final OClass cls = getRawGraph ( ) . getMetadata ( ) . getSchema ( ) . getClass ( iClassName ) ; if ( cls == null ) throw new IllegalArgumentException ( \"Cannot find class '\" + iClassName + \"' in database schema\" ) ; if ( ! cls . isSubClassOf ( OrientVertexType . CLASS_NAME ) ) throw new IllegalArgumentException ( \"Class '\" + iClassName + \"' is not a vertex class\" ) ; return new OrientElementScanIterable < Vertex > ( this , iClassName , iPolymorphic ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the Vertices in Graph filtering by field name and value . Example : <code > Iterable<Vertex > resultset = getVertices ( name Jay ) ; < / code > [CODESPLIT] public Iterable < Vertex > getVertices ( final String iKey , Object iValue ) { makeActive ( ) ; if ( iKey . equals ( \"@class\" ) ) return getVerticesOfClass ( iValue . toString ( ) ) ; int pos = iKey . indexOf ( ' ' ) ; final String className = pos > - 1 ? iKey . substring ( 0 , pos ) : OrientVertexType . CLASS_NAME ; final String key = pos > - 1 ? iKey . substring ( pos + 1 ) : iKey ; OClass clazz = getDatabase ( ) . getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( className ) ; if ( clazz == null ) { throw new IllegalArgumentException ( \"OClass not found in the schema: \" + className ) ; } OIndex < ? > idx = null ; final Collection < ? extends OIndex < ? > > indexes = clazz . getIndexes ( ) ; for ( OIndex < ? > index : indexes ) { OIndexDefinition indexDef = index . getDefinition ( ) ; if ( \"lucene\" . equalsIgnoreCase ( index . getAlgorithm ( ) ) ) { continue ; } List < String > indexedFields = indexDef . getFields ( ) ; if ( indexedFields != null && indexedFields . size ( ) > 0 && indexedFields . get ( 0 ) . equals ( key ) ) { idx = index ; break ; } } if ( idx == null ) { idx = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndex ( iKey ) ; } if ( idx != null ) { iValue = convertKey ( idx , iValue ) ; Object indexValue = idx . get ( iValue ) ; if ( indexValue != null && ! ( indexValue instanceof Iterable < ? > ) ) indexValue = Arrays . asList ( indexValue ) ; return new OrientElementIterable < Vertex > ( this , ( Iterable < ? > ) indexValue ) ; } else { // NO INDEX: EXECUTE A QUERY OrientGraphQuery query = ( OrientGraphQuery ) query ( ) ; query . labels ( clazz . getName ( ) ) ; return query . has ( key , iValue ) . vertices ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup for a vertex by id using an index . <br > This API relies on Unique index ( SBTREE / HASH ) but is deprecated . <br > Example : <code > Vertex v = getVertexByKey ( V . name name Jay ) ; < / code > [CODESPLIT] @ Deprecated public Vertex getVertexByKey ( final String iKey , Object iValue ) { makeActive ( ) ; String indexName ; if ( iKey . indexOf ( ' ' ) > - 1 ) indexName = iKey ; else indexName = OrientVertexType . CLASS_NAME + \".\" + iKey ; final OIndex < ? > idx = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndex ( indexName ) ; if ( idx != null ) { iValue = convertKey ( idx , iValue ) ; Object v = idx . get ( iValue ) ; if ( v != null ) return getVertex ( v ) ; return null ; } else throw new IllegalArgumentException ( \"Index '\" + indexName + \"' not found\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the Vertices in Graph filtering by field name and value . Example : <code > Iterable<Vertex > resultset = getVertices ( Person new String [] { name surname } new Object [] { Sherlock Holmes } ) ; < / code > [CODESPLIT] public Iterable < Vertex > getVertices ( final String label , final String [ ] iKey , Object [ ] iValue ) { if ( iKey . length != iValue . length ) { throw new IllegalArgumentException ( \"key names and values must be arrays of the same size\" ) ; } makeActive ( ) ; final OClass clazz = getDatabase ( ) . getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( label ) ; if ( clazz != null ) { Set < OIndex < ? > > indexes = clazz . getInvolvedIndexes ( Arrays . asList ( iKey ) ) ; Iterator < OIndex < ? > > iterator = indexes . iterator ( ) ; while ( iterator . hasNext ( ) ) { final OIndex < ? > idx = iterator . next ( ) ; if ( idx != null ) { if ( \"lucene\" . equalsIgnoreCase ( idx . getAlgorithm ( ) ) ) { continue ; } Object [ ] sortedParams = new Object [ iValue . length ] ; List < String > indexFields = idx . getDefinition ( ) . getFields ( ) ; for ( int i = 0 ; i < iKey . length ; i ++ ) { sortedParams [ indexFields . indexOf ( iKey [ i ] ) ] = iValue [ i ] ; } List < Object > keys = Arrays . asList ( convertKeys ( idx , sortedParams ) ) ; Object key ; if ( indexFields . size ( ) == 1 ) { key = keys . get ( 0 ) ; } else { key = new OCompositeKey ( keys ) ; } Object indexValue = idx . get ( key ) ; if ( indexValue != null && ! ( indexValue instanceof Iterable < ? > ) ) indexValue = Arrays . asList ( indexValue ) ; return new OrientClassVertexIterable ( this , ( Iterable < ? > ) indexValue , label ) ; } } } // NO INDEX: EXECUTE A QUERY OrientGraphQuery query = ( OrientGraphQuery ) query ( ) ; query . labels ( label ) ; for ( int i = 0 ; i < iKey . length ; i ++ ) { query . has ( iKey [ i ] , iValue [ i ] ) ; } return query . vertices ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the Edges in Graph of a specific edges class and all sub - classes only if iPolymorphic is true . [CODESPLIT] public Iterable < Edge > getEdgesOfClass ( final String iClassName , final boolean iPolymorphic ) { makeActive ( ) ; final OClass cls = getRawGraph ( ) . getMetadata ( ) . getSchema ( ) . getClass ( iClassName ) ; if ( cls == null ) throw new IllegalArgumentException ( \"Cannot find class '\" + iClassName + \"' in database schema\" ) ; if ( ! cls . isSubClassOf ( OrientEdgeType . CLASS_NAME ) ) throw new IllegalArgumentException ( \"Class '\" + iClassName + \"' is not an edge class\" ) ; return new OrientElementScanIterable < Edge > ( this , iClassName , iPolymorphic ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the Edges in Graph filtering by field name and value . Example : <code > Iterable<Edges > resultset = getEdges ( name Jay ) ; < / code > [CODESPLIT] public Iterable < Edge > getEdges ( final String iKey , Object iValue ) { makeActive ( ) ; if ( iKey . equals ( \"@class\" ) ) return getEdgesOfClass ( iValue . toString ( ) ) ; final String indexName ; final String key ; int pos = iKey . indexOf ( ' ' ) ; if ( pos > - 1 ) { indexName = iKey ; key = iKey . substring ( iKey . indexOf ( ' ' ) + 1 ) ; } else { indexName = OrientEdgeType . CLASS_NAME + \".\" + iKey ; key = iKey ; } final OIndex < ? > idx = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndex ( indexName ) ; if ( idx != null ) { iValue = convertKey ( idx , iValue ) ; Object indexValue = idx . get ( iValue ) ; if ( indexValue != null && ! ( indexValue instanceof Iterable < ? > ) ) indexValue = Arrays . asList ( indexValue ) ; return new OrientElementIterable < Edge > ( this , ( Iterable < ? > ) indexValue ) ; } // NO INDEX: EXECUTE A QUERY return query ( ) . has ( key , iValue ) . edges ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a edge by an ID . [CODESPLIT] public OrientEdge getEdge ( final Object id ) { makeActive ( ) ; if ( null == id ) throw ExceptionFactory . edgeIdCanNotBeNull ( ) ; if ( id instanceof OrientEdge ) return ( OrientEdge ) id ; else if ( id instanceof ODocument ) return new OrientEdge ( this , ( OIdentifiable ) id ) ; final OIdentifiable rec ; if ( id instanceof OIdentifiable ) rec = ( OIdentifiable ) id ; else { final String str = id . toString ( ) ; int pos = str . indexOf ( \"->\" ) ; if ( pos > - 1 ) { // DUMMY EDGE: CREATE IT IN MEMORY final String from = str . substring ( 0 , pos ) ; final String to = str . substring ( pos + 2 ) ; return getEdgeInstance ( new ORecordId ( from ) , new ORecordId ( to ) , null ) ; } try { rec = new ORecordId ( str ) ; } catch ( IllegalArgumentException iae ) { // orientdb throws IllegalArgumentException: Argument 'xxxx' is // not a RecordId in form of string. Format must be: // [#]<cluster-id>:<cluster-position> return null ; } } final ODocument doc = rec . getRecord ( ) ; if ( doc == null ) return null ; final OClass cls = doc . getSchemaClass ( ) ; if ( cls != null ) { if ( cls . isVertexType ( ) ) throw new IllegalArgumentException ( \"Cannot retrieve an edge with the RID \" + id + \" because it is a vertex\" ) ; if ( ! cls . isEdgeType ( ) ) throw new IllegalArgumentException ( \"Class '\" + doc . getClassName ( ) + \"' is not an edge class\" ) ; } return new OrientEdge ( this , rec ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reuses the underlying database avoiding to create and open it every time . [CODESPLIT] public OrientBaseGraph reuse ( final ODatabaseDocumentInternal iDatabase ) { ODatabaseRecordThreadLocal . instance ( ) . set ( iDatabase ) ; this . url = iDatabase . getURL ( ) ; database = iDatabase ; makeActive ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the Graph . After closing the Graph cannot be used . [CODESPLIT] public void shutdown ( boolean closeDb , boolean commitTx ) { makeActive ( ) ; try { if ( ! isClosed ( ) ) { if ( commitTx ) { final OStorage storage = getDatabase ( ) . getStorage ( ) . getUnderlying ( ) ; if ( storage instanceof OAbstractPaginatedStorage ) { if ( ( ( OAbstractPaginatedStorage ) storage ) . getWALInstance ( ) != null ) getDatabase ( ) . commit ( ) ; } else { getDatabase ( ) . commit ( ) ; } } else if ( closeDb ) { getDatabase ( ) . rollback ( ) ; } } } catch ( ONeedRetryException e ) { throw e ; } catch ( RuntimeException e ) { OLogManager . instance ( ) . error ( this , \"Error during context close for db \" + url , e ) ; throw e ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error during context close for db \" + url , e ) ; throw OException . wrapException ( new ODatabaseException ( \"Error during context close for db \" + url ) , e ) ; } finally { try { if ( closeDb ) { getDatabase ( ) . close ( ) ; if ( getDatabase ( ) . isPooled ( ) ) { database = null ; } } pollGraphFromStack ( closeDb ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Error during context close for db \" + url , e ) ; } } url = null ; username = null ; password = null ; if ( ! closeDb ) getDatabase ( ) . activateOnCurrentThread ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the V persistent class as OrientVertexType instance . [CODESPLIT] public OrientVertexType getVertexBaseType ( ) { makeActive ( ) ; return new OrientVertexType ( this , getRawGraph ( ) . getMetadata ( ) . getSchema ( ) . getClass ( OrientVertexType . CLASS_NAME ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the persistent class for type iTypeName as OrientVertexType instance . [CODESPLIT] public OrientVertexType getVertexType ( final String iTypeName ) { makeActive ( ) ; final OClass cls = getRawGraph ( ) . getMetadata ( ) . getSchema ( ) . getClass ( iTypeName ) ; if ( cls == null ) return null ; OrientVertexType . checkType ( cls ) ; return new OrientVertexType ( this , cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Vertex persistent class . [CODESPLIT] public OrientVertexType createVertexType ( final String iClassName , final int clusters ) { makeActive ( ) ; return createVertexType ( iClassName , ( String ) null , clusters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Vertex persistent class specifying the super class . [CODESPLIT] public OrientVertexType createVertexType ( final String iClassName , final String iSuperClassName ) { makeActive ( ) ; return createVertexType ( iClassName , iSuperClassName == null ? getVertexBaseType ( ) : getVertexType ( iSuperClassName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Vertex persistent class specifying the super class . [CODESPLIT] public OrientVertexType createVertexType ( final String iClassName , final OClass iSuperClass , final int clusters ) { makeActive ( ) ; OrientVertexType . checkType ( iSuperClass ) ; return executeOutsideTx ( new OCallable < OrientVertexType , OrientBaseGraph > ( ) { @ Override public OrientVertexType call ( final OrientBaseGraph g ) { return new OrientVertexType ( g , getRawGraph ( ) . getMetadata ( ) . getSchema ( ) . createClass ( iClassName , clusters , iSuperClass ) ) ; } } , \"create vertex type '\" , iClassName , \"' as subclass of '\" , iSuperClass . getName ( ) , \"' (clusters=\" + clusters + \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drop a vertex class . [CODESPLIT] public void dropVertexType ( final String iTypeName ) { makeActive ( ) ; if ( getDatabase ( ) . countClass ( iTypeName ) > 0 ) throw new OCommandExecutionException ( \"cannot drop vertex type '\" + iTypeName + \"' because it contains Vertices. Use 'DELETE VERTEX' command first to remove data\" ) ; executeOutsideTx ( new OCallable < OClass , OrientBaseGraph > ( ) { @ Override public OClass call ( final OrientBaseGraph g ) { ODatabaseDocument rawGraph = getRawGraph ( ) ; rawGraph . getMetadata ( ) . getSchema ( ) . dropClass ( iTypeName ) ; return null ; } } , \"drop vertex type '\" , iTypeName , \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the persistent class for type iTypeName as OrientEdgeType instance . [CODESPLIT] public OrientEdgeType getEdgeType ( final String iTypeName ) { makeActive ( ) ; final OClass cls = getRawGraph ( ) . getMetadata ( ) . getSchema ( ) . getClass ( iTypeName ) ; if ( cls == null ) return null ; OrientEdgeType . checkType ( cls ) ; return new OrientEdgeType ( this , cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Edge persistent class . [CODESPLIT] public OrientEdgeType createEdgeType ( final String iClassName , final int clusters ) { makeActive ( ) ; return createEdgeType ( iClassName , ( String ) null , clusters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Edge persistent class specifying the super class . [CODESPLIT] public OrientEdgeType createEdgeType ( final String iClassName , final String iSuperClassName ) { makeActive ( ) ; return createEdgeType ( iClassName , iSuperClassName == null ? getEdgeBaseType ( ) : getEdgeType ( iSuperClassName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Edge persistent class specifying the super class . [CODESPLIT] public OrientEdgeType createEdgeType ( final String iClassName , final OClass iSuperClass , final int clusters ) { makeActive ( ) ; OrientEdgeType . checkType ( iSuperClass ) ; return executeOutsideTx ( new OCallable < OrientEdgeType , OrientBaseGraph > ( ) { @ Override public OrientEdgeType call ( final OrientBaseGraph g ) { return new OrientEdgeType ( g , getRawGraph ( ) . getMetadata ( ) . getSchema ( ) . createClass ( iClassName , clusters , iSuperClass ) ) ; } } , \"create edge type '\" , iClassName , \"' as subclass of '\" , iSuperClass . getName ( ) , \"' (clusters=\" + clusters + \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a graph element vertex or edge starting from an ID . [CODESPLIT] public OrientElement getElement ( final Object id ) { makeActive ( ) ; if ( null == id ) throw new IllegalArgumentException ( \"id cannot be null\" ) ; if ( id instanceof OrientElement ) return ( OrientElement ) id ; OIdentifiable rec ; if ( id instanceof OIdentifiable ) rec = ( OIdentifiable ) id ; else try { rec = new ORecordId ( id . toString ( ) ) ; } catch ( IllegalArgumentException iae ) { // orientdb throws IllegalArgumentException: Argument 'xxxx' is // not a RecordId in form of string. Format must be: // <cluster-id>:<cluster-position> return null ; } final ODocument doc = rec . getRecord ( ) ; if ( doc != null ) { final OImmutableClass schemaClass = ODocumentInternal . getImmutableSchemaClass ( doc ) ; if ( schemaClass != null && schemaClass . isEdgeType ( ) ) return getEdge ( doc ) ; else return getVertexInstance ( doc ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drops the index against a field name . [CODESPLIT] public < T extends Element > void dropKeyIndex ( final String key , final Class < T > elementClass ) { makeActive ( ) ; if ( elementClass == null ) throw ExceptionFactory . classForElementCannotBeNull ( ) ; executeOutsideTx ( new OCallable < OClass , OrientBaseGraph > ( ) { @ Override public OClass call ( final OrientBaseGraph g ) { final String className = getClassName ( elementClass ) ; getRawGraph ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( className + \".\" + key ) ; return null ; } } , \"drop key index '\" , elementClass . getSimpleName ( ) , \".\" , key , \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an automatic indexing structure for indexing provided key for element class . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" } ) @ Override public < T extends Element > void createKeyIndex ( final String key , final Class < T > elementClass , final Parameter ... indexParameters ) { makeActive ( ) ; if ( elementClass == null ) throw ExceptionFactory . classForElementCannotBeNull ( ) ; executeOutsideTx ( new OCallable < OClass , OrientBaseGraph > ( ) { @ Override public OClass call ( final OrientBaseGraph g ) { String indexType = OClass . INDEX_TYPE . NOTUNIQUE . name ( ) ; OType keyType = OType . STRING ; String className = null ; String collate = null ; ODocument metadata = null ; final String ancestorClassName = getClassName ( elementClass ) ; // READ PARAMETERS for ( Parameter < ? , ? > p : indexParameters ) { if ( p . getKey ( ) . equals ( \"type\" ) ) indexType = p . getValue ( ) . toString ( ) . toUpperCase ( Locale . ENGLISH ) ; else if ( p . getKey ( ) . equals ( \"keytype\" ) ) keyType = OType . valueOf ( p . getValue ( ) . toString ( ) . toUpperCase ( Locale . ENGLISH ) ) ; else if ( p . getKey ( ) . equals ( \"class\" ) ) className = p . getValue ( ) . toString ( ) ; else if ( p . getKey ( ) . equals ( \"collate\" ) ) collate = p . getValue ( ) . toString ( ) ; else if ( p . getKey ( ) . toString ( ) . startsWith ( \"metadata.\" ) ) { if ( metadata == null ) metadata = new ODocument ( ) ; metadata . field ( p . getKey ( ) . toString ( ) . substring ( \"metadata.\" . length ( ) ) , p . getValue ( ) ) ; } } if ( className == null ) className = ancestorClassName ; final ODatabaseDocument db = getRawGraph ( ) ; final OSchema schema = db . getMetadata ( ) . getSchema ( ) ; final OClass cls = schema . getOrCreateClass ( className , schema . getClass ( ancestorClassName ) ) ; final OProperty property = cls . getProperty ( key ) ; if ( property != null ) keyType = property . getType ( ) ; OPropertyIndexDefinition indexDefinition = new OPropertyIndexDefinition ( className , key , keyType ) ; if ( collate != null ) indexDefinition . setCollate ( collate ) ; db . getMetadata ( ) . getIndexManager ( ) . createIndex ( className + \".\" + key , indexType , indexDefinition , cls . getPolymorphicClusterIds ( ) , null , metadata ) ; return null ; } } , \"create key index on '\" , elementClass . getSimpleName ( ) , \".\" , key , \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the indexed properties . [CODESPLIT] @ Override public < T extends Element > Set < String > getIndexedKeys ( final Class < T > elementClass ) { makeActive ( ) ; return getIndexedKeys ( elementClass , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the indexed properties . [CODESPLIT] public < T extends Element > Set < String > getIndexedKeys ( final Class < T > elementClass , final boolean includeClassNames ) { makeActive ( ) ; if ( elementClass == null ) throw ExceptionFactory . classForElementCannotBeNull ( ) ; final OSchema schema = getRawGraph ( ) . getMetadata ( ) . getImmutableSchemaSnapshot ( ) ; final String elementOClassName = getClassName ( elementClass ) ; Set < String > result = new HashSet < String > ( ) ; final Collection < ? extends OIndex < ? > > indexes = getRawGraph ( ) . getMetadata ( ) . getIndexManager ( ) . getIndexes ( ) ; for ( OIndex < ? > index : indexes ) { String indexName = index . getName ( ) ; int point = indexName . indexOf ( \".\" ) ; if ( point > 0 ) { String oClassName = indexName . substring ( 0 , point ) ; OClass oClass = schema . getClass ( oClassName ) ; if ( oClass != null ) { if ( oClass . isSubClassOf ( elementOClassName ) ) { if ( includeClassNames ) result . add ( index . getName ( ) ) ; else result . add ( index . getDefinition ( ) . getFields ( ) . get ( 0 ) ) ; } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) [CODESPLIT] protected static void removeEdges ( final OrientBaseGraph graph , final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove , final boolean iAlsoInverse , final boolean useVertexFieldsForEdgeLabels , final boolean autoScaleEdgeType , final boolean forceReload ) { if ( iVertex == null ) return ; final Object fieldValue = iVertexToRemove != null ? iVertex . field ( iFieldName ) : iVertex . removeField ( iFieldName ) ; if ( fieldValue == null ) return ; if ( fieldValue instanceof OIdentifiable ) { // SINGLE RECORD if ( iVertexToRemove != null ) { if ( ! fieldValue . equals ( iVertexToRemove ) ) // NOT FOUND return ; iVertex . removeField ( iFieldName ) ; deleteEdgeIfAny ( iVertexToRemove , forceReload ) ; } if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , ( OIdentifiable ) fieldValue , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; } else if ( fieldValue instanceof ORidBag ) { // COLLECTION OF RECORDS: REMOVE THE ENTRY final ORidBag bag = ( ORidBag ) fieldValue ; if ( iVertexToRemove != null ) { // SEARCH SEQUENTIALLY (SLOWER) for ( Iterator < OIdentifiable > it = bag . rawIterator ( ) ; it . hasNext ( ) ; ) { final ODocument curr = getDocument ( it . next ( ) , forceReload ) ; if ( curr == null ) { // EDGE REMOVED it . remove ( ) ; iVertex . save ( ) ; continue ; } if ( iVertexToRemove . equals ( curr ) ) { // FOUND AS VERTEX it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } else if ( ODocumentInternal . getImmutableSchemaClass ( curr ) . isEdgeType ( ) ) { final Direction direction = OrientVertex . getConnectionDirection ( iFieldName , useVertexFieldsForEdgeLabels ) ; // EDGE, REMOVE THE EDGE if ( iVertexToRemove . equals ( OrientEdge . getConnection ( curr , direction . opposite ( ) ) ) ) { it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } } } deleteEdgeIfAny ( iVertexToRemove , forceReload ) ; } else { // DELETE ALL THE EDGES for ( Iterator < OIdentifiable > it = bag . rawIterator ( ) ; it . hasNext ( ) ; ) { OIdentifiable edge = it . next ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , null , edge , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; deleteEdgeIfAny ( edge , forceReload ) ; } } if ( autoScaleEdgeType && bag . isEmpty ( ) ) // FORCE REMOVAL OF ENTIRE FIELD iVertex . removeField ( iFieldName ) ; } else if ( fieldValue instanceof Collection ) { final Collection col = ( Collection ) fieldValue ; if ( iVertexToRemove != null ) { // SEARCH SEQUENTIALLY (SLOWER) for ( Iterator < OIdentifiable > it = col . iterator ( ) ; it . hasNext ( ) ; ) { final ODocument curr = getDocument ( it . next ( ) , forceReload ) ; if ( curr == null ) // EDGE REMOVED continue ; if ( iVertexToRemove . equals ( curr ) ) { // FOUND AS VERTEX it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } else if ( ODocumentInternal . getImmutableSchemaClass ( curr ) . isVertexType ( ) ) { final Direction direction = OrientVertex . getConnectionDirection ( iFieldName , useVertexFieldsForEdgeLabels ) ; // EDGE, REMOVE THE EDGE if ( iVertexToRemove . equals ( OrientEdge . getConnection ( curr , direction . opposite ( ) ) ) ) { it . remove ( ) ; if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , iVertexToRemove , curr , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; break ; } } } deleteEdgeIfAny ( iVertexToRemove , forceReload ) ; } else { // DELETE ALL THE EDGES for ( OIdentifiable edge : ( Iterable < OIdentifiable > ) col ) { if ( iAlsoInverse ) removeInverseEdge ( graph , iVertex , iFieldName , null , edge , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; deleteEdgeIfAny ( edge , forceReload ) ; } } if ( autoScaleEdgeType && col . isEmpty ( ) ) // FORCE REMOVAL OF ENTIRE FIELD iVertex . removeField ( iFieldName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) [CODESPLIT] private static void removeInverseEdge ( final OrientBaseGraph graph , final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove , final OIdentifiable currentRecord , final boolean useVertexFieldsForEdgeLabels , final boolean autoScaleEdgeType , boolean forceReload ) { final ODocument r = getDocument ( currentRecord , forceReload ) ; if ( r == null ) return ; final String inverseFieldName = OrientVertex . getInverseConnectionFieldName ( iFieldName , useVertexFieldsForEdgeLabels ) ; OImmutableClass immutableClass = ODocumentInternal . getImmutableSchemaClass ( r ) ; OClass klass = ODocumentInternal . getImmutableSchemaClass ( r ) ; if ( klass == null ) { graph . getDatabase ( ) . getMetadata ( ) . reload ( ) ; klass = graph . getDatabase ( ) . getMetadata ( ) . getSchema ( ) . getClass ( inverseFieldName ) ; if ( klass == null ) { OLogManager . instance ( ) . warn ( null , \"Removing edge, schema class not found for \" + r ) ; return ; } } if ( klass . isVertexType ( ) ) { // DIRECT VERTEX removeEdges ( graph , r , inverseFieldName , iVertex , false , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; r . save ( ) ; } else if ( klass . isEdgeType ( ) ) { // EDGE, REMOVE THE EDGE final OIdentifiable otherVertex = OrientEdge . getConnection ( r , OrientVertex . getConnectionDirection ( inverseFieldName , useVertexFieldsForEdgeLabels ) ) ; if ( otherVertex != null ) { if ( iVertexToRemove == null || otherVertex . equals ( iVertexToRemove ) ) { final int maxRetries = graph . getMaxRetries ( ) ; for ( int retry = 0 ; retry < maxRetries ; ++ retry ) { try { final ODocument otherVertexRecord = getDocument ( otherVertex , forceReload ) ; // BIDIRECTIONAL EDGE removeEdges ( graph , otherVertexRecord , inverseFieldName , ( OIdentifiable ) currentRecord , false , useVertexFieldsForEdgeLabels , autoScaleEdgeType , forceReload ) ; if ( otherVertexRecord != null ) otherVertexRecord . save ( ) ; break ; } catch ( ONeedRetryException e ) { // RETRY } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) [CODESPLIT] protected static void deleteEdgeIfAny ( final OIdentifiable iRecord , boolean forceReload ) { if ( iRecord != null ) { final ODocument doc = getDocument ( iRecord , forceReload ) ; if ( doc != null ) { final OImmutableClass clazz = ODocumentInternal . getImmutableSchemaClass ( doc ) ; if ( clazz != null && clazz . isEdgeType ( ) ) // DELETE THE EDGE RECORD TOO doc . delete ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes listener which is triggered if exception is cast inside background flush data thread . [CODESPLIT] @ Override public void removeBackgroundExceptionListener ( final OBackgroundExceptionListener listener ) { final List < WeakReference < OBackgroundExceptionListener > > itemsToRemove = new ArrayList <> ( 1 ) ; for ( final WeakReference < OBackgroundExceptionListener > ref : backgroundExceptionListeners ) { final OBackgroundExceptionListener l = ref . get ( ) ; if ( l != null && l . equals ( listener ) ) { itemsToRemove . add ( ref ) ; } } backgroundExceptionListeners . removeAll ( itemsToRemove ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires event about exception is thrown in data flush thread [CODESPLIT] private void fireBackgroundDataFlushExceptionEvent ( final Throwable e ) { for ( final WeakReference < OBackgroundExceptionListener > ref : backgroundExceptionListeners ) { final OBackgroundExceptionListener listener = ref . get ( ) ; if ( listener != null ) { listener . onException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called once new pages are added to the disk inside of { [CODESPLIT] private void freeSpaceCheckAfterNewPageAdd ( ) throws IOException { final long newPagesAdded = amountOfNewPagesAdded . addAndGet ( 1 ) ; final long lastSpaceCheck = lastDiskSpaceCheck . get ( ) ; if ( newPagesAdded - lastSpaceCheck > diskSizeCheckInterval || lastSpaceCheck == 0 ) { //usable space may be less than free space final long freeSpace = Files . getFileStore ( storagePath ) . getUsableSpace ( ) ; if ( freeSpace < freeSpaceLimit ) { callLowSpaceListeners ( new OLowDiskSpaceInformation ( freeSpace , freeSpaceLimit ) ) ; } lastDiskSpaceCheck . lazySet ( newPagesAdded ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read information about files are registered inside of write cache / storage File consist of rows of variable length which contains following entries : <ol > <li > Internal file id may be positive or negative depends on whether file is removed or not< / li > <li > Name of file inside of write cache this name is case sensitive< / li > <li > Name of file which is used inside file system it can be different from name of file used inside write cache< / li > < / ol > [CODESPLIT] private void readNameIdMapV2 ( ) throws IOException , InterruptedException { nameIdMap . clear ( ) ; long localFileCounter = - 1 ; nameIdMapHolder . position ( 0 ) ; NameFileIdEntry nameFileIdEntry ; final Map < Integer , String > idFileNameMap = new HashMap <> ( 1_000 ) ; while ( ( nameFileIdEntry = readNextNameIdEntryV2 ( ) ) != null ) { final long absFileId = Math . abs ( nameFileIdEntry . fileId ) ; if ( localFileCounter < absFileId ) { localFileCounter = absFileId ; } nameIdMap . put ( nameFileIdEntry . name , nameFileIdEntry . fileId ) ; if ( nameFileIdEntry . fileId >= 0 ) { idNameMap . put ( nameFileIdEntry . fileId , nameFileIdEntry . name ) ; } idFileNameMap . put ( nameFileIdEntry . fileId , nameFileIdEntry . fileSystemName ) ; } if ( localFileCounter > 0 && nextInternalId < localFileCounter ) { nextInternalId = ( int ) localFileCounter ; } for ( final Map . Entry < String , Integer > nameIdEntry : nameIdMap . entrySet ( ) ) { final int fileId = nameIdEntry . getValue ( ) ; if ( fileId >= 0 ) { final long externalId = composeFileId ( id , nameIdEntry . getValue ( ) ) ; if ( files . get ( externalId ) == null ) { final Path path = storagePath . resolve ( idFileNameMap . get ( ( nameIdEntry . getValue ( ) ) ) ) ; final OFileClassic fileClassic = new OFileClassic ( path ) ; if ( fileClassic . exists ( ) ) { fileClassic . open ( ) ; files . add ( externalId , fileClassic ) ; } else { nameIdMap . put ( nameIdEntry . getKey ( ) , - fileId ) ; idNameMap . remove ( fileId ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a property name calculates if this property name matches this nested projection item eg . <ul > <li > this is a * so it matches any property name< / li > <li > the field name for this projection item is the same as the input property name< / li > <li > this item has a wildcard and the partial field is a prefix of the input property name< / li > < / ul > [CODESPLIT] public boolean matches ( String propertyName ) { if ( star ) { return true ; } if ( expression != null ) { String fieldString = expression . getDefaultAlias ( ) . getStringValue ( ) ; if ( fieldString . equals ( propertyName ) ) { return true ; } if ( rightWildcard && propertyName . startsWith ( fieldString ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clusterName == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocumentInternal database = getDatabase ( ) ; final int clusterId = database . getClusterIdByName ( clusterName ) ; if ( clusterId < 0 ) { throw new ODatabaseException ( \"Cluster with name \" + clusterName + \" does not exist\" ) ; } final OSchema schema = database . getMetadata ( ) . getSchema ( ) ; final OClass clazz = schema . getClassByClusterId ( clusterId ) ; if ( clazz == null ) { final OStorage storage = database . getStorage ( ) ; final OCluster cluster = storage . getClusterById ( clusterId ) ; if ( cluster == null ) { throw new ODatabaseException ( \"Cluster with name \" + clusterName + \" does not exist\" ) ; } try { database . checkForClusterPermissions ( cluster . getName ( ) ) ; cluster . truncate ( ) ; } catch ( IOException ioe ) { throw OException . wrapException ( new ODatabaseException ( \"Error during truncation of cluster with name \" + clusterName ) , ioe ) ; } } else { clazz . truncateCluster ( clusterName ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts performance monitoring only for single thread . After call of this method you can not start system wide monitoring till call of { [CODESPLIT] public void startThreadMonitoring ( ) { switchLock . acquireWriteLock ( ) ; try { if ( enabled ) throw new IllegalStateException ( \"Monitoring is already started on system level and can not be started on thread level\" ) ; enabledForCurrentThread . set ( true ) ; statistics . put ( Thread . currentThread ( ) , new OSessionStoragePerformanceStatistic ( intervalBetweenSnapshots , Long . MAX_VALUE ) ) ; } finally { switchLock . releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts performance monitoring only for whole system . After call of this method you can not start monitoring on thread level till call of { [CODESPLIT] public void startMonitoring ( ) { switchLock . acquireWriteLock ( ) ; try { if ( ! statistics . isEmpty ( ) && ! enabled ) throw new IllegalStateException ( \"Monitoring is already started on thread level and can not be started on system level\" ) ; deadThreadsStatistic = null ; postMeasurementStatistic = null ; enabled = true ; } finally { switchLock . releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops monitoring of performance statistic for whole system . [CODESPLIT] public void stopMonitoring ( ) { switchLock . acquireWriteLock ( ) ; try { enabled = false ; final PerformanceCountersHolder countersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; final Map < String , PerformanceCountersHolder > componentCountersHolder = new HashMap <> ( ) ; WritCacheCountersHolder writCacheCountersHolder = deadThreadsStatistic . writCacheCountersHolder ; StorageCountersHolder storageCountersHolder = deadThreadsStatistic . storageCountersHolder ; WALCountersHolder walCountersHolder = deadThreadsStatistic . walCountersHolder ; deadThreadsStatistic . countersHolder . pushData ( countersHolder ) ; componentCountersHolder . putAll ( deadThreadsStatistic . countersByComponents ) ; deadThreadsStatistic = null ; for ( OSessionStoragePerformanceStatistic statistic : statistics . values ( ) ) { statistic . pushSystemCounters ( countersHolder ) ; statistic . pushComponentCounters ( componentCountersHolder ) ; writCacheCountersHolder = statistic . pushWriteCacheCounters ( writCacheCountersHolder ) ; storageCountersHolder = statistic . pushStorageCounters ( storageCountersHolder ) ; walCountersHolder = statistic . pushWALCounters ( walCountersHolder ) ; } statistics . clear ( ) ; postMeasurementStatistic = new ImmutableStatistic ( countersHolder , componentCountersHolder , writCacheCountersHolder , storageCountersHolder , walCountersHolder ) ; } finally { switchLock . releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers JMX bean for current manager . [CODESPLIT] public void registerMBean ( String storageName , int storageId ) { if ( mbeanIsRegistered . compareAndSet ( false , true ) ) { try { final MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; final ObjectName mbeanName = new ObjectName ( getMBeanName ( storageName , storageId ) ) ; if ( ! server . isRegistered ( mbeanName ) ) { server . registerMBean ( new OPerformanceStatisticManagerMBean ( this ) , mbeanName ) ; } else { mbeanIsRegistered . set ( false ) ; OLogManager . instance ( ) . warn ( this , \"MBean with name %s has already registered. Probably your system was not shutdown correctly\" + \" or you have several running applications which use OrientDB engine inside\" , mbeanName . getCanonicalName ( ) ) ; } } catch ( MalformedObjectNameException | InstanceAlreadyExistsException | NotCompliantMBeanException | MBeanRegistrationException e ) { throw OException . wrapException ( new OStorageException ( \"Error during registration of profiler MBean\" ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deregisters JMX bean for current manager . [CODESPLIT] public void unregisterMBean ( String storageName , int storageId ) { if ( storageName == null ) { OLogManager . instance ( ) . warnNoDb ( this , \"Can not unregister MBean for performance statistics, storage name is null\" ) ; } if ( mbeanIsRegistered . compareAndSet ( true , false ) ) { try { final MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; final ObjectName mbeanName = new ObjectName ( getMBeanName ( storageName , storageId ) ) ; server . unregisterMBean ( mbeanName ) ; } catch ( MalformedObjectNameException | InstanceNotFoundException | MBeanRegistrationException e ) { throw OException . wrapException ( new OStorageException ( \"Error during unregistration of profiler MBean\" ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Average amount of pages which were read from cache for component with given name during single data operation . If null value is passed or data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public long getAmountOfPagesPerOperation ( String componentName ) { switchLock . acquireReadLock ( ) ; try { if ( enabled ) { final PerformanceCountersHolder componentCountersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; fetchComponentCounters ( componentName , componentCountersHolder ) ; return componentCountersHolder . getAmountOfPagesPerOperation ( ) ; } else { final ImmutableStatistic post = postMeasurementStatistic ; if ( post == null ) return - 1 ; final PerformanceCountersHolder holder = post . countersByComponents . get ( componentName ) ; if ( holder == null ) return - 1 ; return holder . getAmountOfPagesPerOperation ( ) ; } } finally { switchLock . releaseReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Percent of cache hits for component name of which is passed as method argument . If null value is passed then value for whole system will be returned . If data for component with passed in name does not exist then <code > - 1< / code > will be returned . [CODESPLIT] public int getCacheHits ( String componentName ) { switchLock . acquireReadLock ( ) ; try { if ( enabled ) { final PerformanceCountersHolder countersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; fetchComponentCounters ( componentName , countersHolder ) ; return countersHolder . getCacheHits ( ) ; } else { final ImmutableStatistic post = postMeasurementStatistic ; if ( post == null ) return - 1 ; final PerformanceCountersHolder holder = post . countersByComponents . get ( componentName ) ; if ( holder != null ) return holder . getCacheHits ( ) ; return - 1 ; } } finally { switchLock . releaseReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates over all live threads and accumulates write performance statics gathered form threads also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started . [CODESPLIT] private WritCacheCountersHolder fetchWriteCacheCounters ( ) { //go through all threads and accumulate statistic only for live threads //all dead threads will be removed and statistics from them will be //later accumulated in #deadThreadsStatistic field, then result statistic from this field //will be aggregated to countersHolder //To decrease inter thread communication delay we fetch snapshots first //and only after that we aggregate data from immutable snapshots final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList <> ( statistics . size ( ) ) ; final Collection < Thread > threadsToRemove = new ArrayList <> ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair <> ( thread , statistic . getSnapshot ( ) ) ) ; } WritCacheCountersHolder holder = null ; for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; if ( snapshot . writCacheCountersHolder != null ) { if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; snapshot . writCacheCountersHolder . pushData ( holder ) ; } } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final WritCacheCountersHolder wch = ds . writCacheCountersHolder ; if ( wch != null ) { if ( holder == null ) holder = new WritCacheCountersHolder ( ) ; wch . pushData ( holder ) ; } } return holder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates over all live threads and accumulates performance statics gathered form threads on system level also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started . [CODESPLIT] private void fetchSystemCounters ( PerformanceCountersHolder countersHolder ) { //go through all threads and accumulate statistic only for live threads //all dead threads will be removed and statistics from them will be //later accumulated in #deadThreadsStatistic field, then result statistic from this field //will be aggregated to countersHolder //To decrease inter thread communication delay we fetch snapshots first //and only after that we aggregate data from immutable snapshots final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList <> ( statistics . size ( ) ) ; final Collection < Thread > threadsToRemove = new ArrayList <> ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair <> ( thread , statistic . getSnapshot ( ) ) ) ; } for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; snapshot . performanceCountersHolder . pushData ( countersHolder ) ; } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final PerformanceCountersHolder dch = ds . countersHolder ; dch . pushData ( countersHolder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates over all live threads and accumulates performance statics gathered form threads for provided component also accumulates statistic from dead threads which were alive when when gathering of performance measurements is started . [CODESPLIT] private void fetchComponentCounters ( String componentName , PerformanceCountersHolder componentCountersHolder ) { //go through all threads and accumulate statistic only for live threads //all dead threads will be removed and statistics from them will be //later accumulated in #deadThreadsStatistic field, then result statistic from this field //will be aggregated to componentCountersHolder //To decrease inter thread communication delay we fetch snapshots first //and only after that we aggregate data from immutable snapshots final Collection < ORawPair < Thread , PerformanceSnapshot > > snapshots = new ArrayList <> ( statistics . size ( ) ) ; final List < Thread > threadsToRemove = new ArrayList <> ( ) ; for ( Map . Entry < Thread , OSessionStoragePerformanceStatistic > entry : statistics . entrySet ( ) ) { final Thread thread = entry . getKey ( ) ; final OSessionStoragePerformanceStatistic statistic = entry . getValue ( ) ; snapshots . add ( new ORawPair <> ( thread , statistic . getSnapshot ( ) ) ) ; } for ( ORawPair < Thread , PerformanceSnapshot > pair : snapshots ) { final Thread thread = pair . getFirst ( ) ; if ( thread . isAlive ( ) ) { final PerformanceSnapshot snapshot = pair . getSecond ( ) ; final PerformanceCountersHolder holder = snapshot . countersByComponent . get ( componentName ) ; if ( holder != null ) holder . pushData ( componentCountersHolder ) ; } else { threadsToRemove . add ( thread ) ; } } if ( ! threadsToRemove . isEmpty ( ) ) { updateDeadThreadsStatistic ( threadsToRemove ) ; } final ImmutableStatistic ds = deadThreadsStatistic ; if ( ds != null ) { final PerformanceCountersHolder dch = ds . countersByComponents . get ( componentName ) ; if ( dch != null ) { dch . pushData ( componentCountersHolder ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes provided dead threads from { @link #statistics } field and accumulates data from them in { @link #deadThreadsStatistic } . [CODESPLIT] private void updateDeadThreadsStatistic ( Collection < Thread > threadsToRemove ) { deadThreadsUpdateLock . lock ( ) ; try { //we accumulate all statistic in intermediate fields and only then put //results in #deadThreadsStatistic field to preserve thread safety features final ImmutableStatistic oldDS = deadThreadsStatistic ; final PerformanceCountersHolder countersHolder = ComponentType . GENERAL . newCountersHolder ( ) ; final Map < String , PerformanceCountersHolder > countersByComponents = new HashMap <> ( ) ; WritCacheCountersHolder writeCacheCountersHolder = null ; StorageCountersHolder storageCountersHolder = null ; WALCountersHolder walCountersHolder = null ; //fetch data from old statistic first if ( oldDS != null ) { oldDS . countersHolder . pushData ( countersHolder ) ; for ( Map . Entry < String , PerformanceCountersHolder > oldEntry : oldDS . countersByComponents . entrySet ( ) ) { final PerformanceCountersHolder holder = oldEntry . getValue ( ) . newInstance ( ) ; oldEntry . getValue ( ) . pushData ( holder ) ; countersByComponents . put ( oldEntry . getKey ( ) , holder ) ; } if ( oldDS . writCacheCountersHolder != null ) { writeCacheCountersHolder = new WritCacheCountersHolder ( ) ; oldDS . writCacheCountersHolder . pushData ( writeCacheCountersHolder ) ; } if ( oldDS . storageCountersHolder != null ) { storageCountersHolder = new StorageCountersHolder ( ) ; oldDS . storageCountersHolder . pushData ( storageCountersHolder ) ; } if ( oldDS . walCountersHolder != null ) { walCountersHolder = new WALCountersHolder ( ) ; oldDS . walCountersHolder . pushData ( walCountersHolder ) ; } } //remove all threads from active statistic and put all in #deadThreadsStatistic field for ( Thread deadThread : threadsToRemove ) { final OSessionStoragePerformanceStatistic sessionStoragePerformanceStatistic = statistics . remove ( deadThread ) ; if ( sessionStoragePerformanceStatistic != null ) { sessionStoragePerformanceStatistic . pushSystemCounters ( countersHolder ) ; sessionStoragePerformanceStatistic . pushComponentCounters ( countersByComponents ) ; writeCacheCountersHolder = sessionStoragePerformanceStatistic . pushWriteCacheCounters ( writeCacheCountersHolder ) ; storageCountersHolder = sessionStoragePerformanceStatistic . pushStorageCounters ( storageCountersHolder ) ; walCountersHolder = sessionStoragePerformanceStatistic . pushWALCounters ( walCountersHolder ) ; } } deadThreadsStatistic = new ImmutableStatistic ( countersHolder , countersByComponents , writeCacheCountersHolder , storageCountersHolder , walCountersHolder ) ; } finally { deadThreadsUpdateLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the value stored under the given entry index in this bucket . [CODESPLIT] public ORID getValue ( final int entryIndex ) { assert isLeaf ; int entryPosition = getIntValue ( entryIndex * OIntegerSerializer . INT_SIZE + POSITIONS_ARRAY_OFFSET ) ; // skip key if ( encryption == null ) { entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedSize = getIntValue ( entryPosition ) ; entryPosition += OIntegerSerializer . INT_SIZE + encryptedSize ; } final int clusterId = getShortValue ( entryPosition ) ; final long clusterPosition = getLongValue ( entryPosition + OShortSerializer . SHORT_SIZE ) ; return new ORecordId ( clusterId , clusterPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compress content string [CODESPLIT] public byte [ ] compress ( String jsonStr ) { if ( jsonStr == null || jsonStr . length ( ) == 0 ) { return null ; } GZIPOutputStream gout = null ; ByteArrayOutputStream baos = null ; try { byte [ ] incoming = jsonStr . getBytes ( \"UTF-8\" ) ; baos = new ByteArrayOutputStream ( ) ; gout = new GZIPOutputStream ( baos , 16384 ) ; // 16KB gout . write ( incoming ) ; gout . finish ( ) ; return baos . toByteArray ( ) ; } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"Error on compressing HTTP response\" , ex ) ; } finally { try { if ( gout != null ) { gout . close ( ) ; } if ( baos != null ) { baos . close ( ) ; } } catch ( Exception ex ) { } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the property value configured if any . [CODESPLIT] public String getProperty ( final String iName , final String iDefaultValue ) { if ( properties == null ) return null ; for ( OServerEntryConfiguration p : properties ) { if ( p . name . equals ( iName ) ) return p . value ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new POJO by its class name . Assure to have called the registerEntityClasses () declaring the packages that are part of entity classes . [CODESPLIT] public < RET extends Object > RET newInstance ( final String iClassName , final Object iEnclosingClass , Object ... iArgs ) { underlying . checkIfActive ( ) ; checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_CREATE , iClassName ) ; try { Class < ? > entityClass = entityManager . getEntityClass ( iClassName ) ; if ( entityClass != null ) { RET enhanced = ( RET ) OObjectEntityEnhancer . getInstance ( ) . getProxiedInstance ( entityManager . getEntityClass ( iClassName ) , iEnclosingClass , underlying . newInstance ( iClassName ) , null , iArgs ) ; return ( RET ) enhanced ; } else { throw new OSerializationException ( \"Type \" + iClassName + \" cannot be serialized because is not part of registered entities. To fix this error register this class\" ) ; } } catch ( Exception e ) { final String message = \"Error on creating object of class \" + iClassName ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new ODatabaseException ( message ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that detaches all fields contained in the document to the given object . [CODESPLIT] public < RET > RET detach ( final Object iPojo , boolean returnNonProxiedInstance ) { return ( RET ) OObjectEntitySerializer . detach ( iPojo , this , returnNonProxiedInstance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that detaches all fields contained in the document to the given object and recursively all object tree . This may throw a { @link StackOverflowError } with big objects tree . To avoid it set the stack size with - Xss java option [CODESPLIT] public < RET > RET detachAll ( final Object iPojo , boolean returnNonProxiedInstance ) { return detachAll ( iPojo , returnNonProxiedInstance , new HashMap < Object , Object > ( ) , new HashMap < Object , Object > ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an object to the database specifying the mode . First checks if the object is new or not . In case it s new a new ODocument is created and bound to the object otherwise the ODocument is retrieved and updated . The object is introspected using the Java Reflection to extract the field values . <br > If a multi value ( array collection or map of objects ) is passed then each single object is stored separately . [CODESPLIT] public < RET > RET save ( final Object iContent , OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { return ( RET ) save ( iContent , null , iMode , false , iRecordCreatedCallback , iRecordUpdatedCallback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an object in synchronous mode to the database forcing a record cluster where to store it . First checks if the object is new or not . In case it s new a new ODocument is created and bound to the object otherwise the ODocument is retrieved and updated . The object is introspected using the Java Reflection to extract the field values . <br > If a multi value ( array collection or map of objects ) is passed then each single object is stored separately . <p > Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid following the constraints declared in the schema . [CODESPLIT] public < RET > RET save ( final Object iPojo , final String iClusterName ) { return ( RET ) save ( iPojo , iClusterName , OPERATION_MODE . SYNCHRONOUS , false , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an object to the database forcing a record cluster where to store it . First checks if the object is new or not . In case it s new a new ODocument is created and bound to the object otherwise the ODocument is retrieved and updated . The object is introspected using the Java Reflection to extract the field values . <br > If a multi value ( array collection or map of objects ) is passed then each single object is stored separately . <p > Before to use the specified cluster a check is made to know if is allowed and figures in the configured and the record is valid following the constraints declared in the schema . [CODESPLIT] public < RET > RET save ( final Object iPojo , final String iClusterName , OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { checkOpenness ( ) ; if ( iPojo == null ) return ( RET ) iPojo ; else if ( OMultiValue . isMultiValue ( iPojo ) ) { // MULTI VALUE OBJECT: STORE SINGLE POJOS\r for ( Object pojo : OMultiValue . getMultiValueIterable ( iPojo ) ) { save ( pojo , iClusterName ) ; } return ( RET ) iPojo ; } else { OSerializationThreadLocal . INSTANCE . get ( ) . clear ( ) ; // GET THE ASSOCIATED DOCUMENT\r final Object proxiedObject = OObjectEntitySerializer . serializeObject ( iPojo , this ) ; final ODocument record = getRecordByUserObject ( proxiedObject , true ) ; try { record . setInternalStatus ( ORecordElement . STATUS . MARSHALLING ) ; if ( ! saveOnlyDirty || record . isDirty ( ) ) { // REGISTER BEFORE TO SERIALIZE TO AVOID PROBLEMS WITH CIRCULAR DEPENDENCY\r // registerUserObject(iPojo, record);\r deleteOrphans ( ( ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) ) ) ; ODocument savedRecord = underlying . save ( record , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) . setDoc ( savedRecord ) ; ( ( OObjectProxyMethodHandler ) ( ( ProxyObject ) proxiedObject ) . getHandler ( ) ) . updateLoadedFieldMap ( proxiedObject , false ) ; // RE-REGISTER FOR NEW RECORDS SINCE THE ID HAS CHANGED\r registerUserObject ( proxiedObject , record ) ; } } finally { record . setInternalStatus ( ORecordElement . STATUS . LOADED ) ; } return ( RET ) proxiedObject ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the version number of the object . Version starts from 0 assigned on creation . [CODESPLIT] public int getVersion ( final Object iPojo ) { checkOpenness ( ) ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record != null ) return record . getVersion ( ) ; return OObjectSerializerHelper . getObjectVersion ( iPojo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the static document binary mapping mode in the database context ( only if it s not already set ) [CODESPLIT] private void registerFieldMappingStrategy ( ) { if ( ! this . getConfiguration ( ) . getContextKeys ( ) . contains ( OGlobalConfiguration . DOCUMENT_BINARY_MAPPING . getKey ( ) ) ) { this . getConfiguration ( ) . setValue ( OGlobalConfiguration . DOCUMENT_BINARY_MAPPING , OGlobalConfiguration . DOCUMENT_BINARY_MAPPING . getValueAsInteger ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a wrapped OCommandRequest instance to catch the result - set by converting it before to return to the user application . [CODESPLIT] public < RET extends OCommandRequest > RET command ( final OCommandRequest iCommand ) { return ( RET ) new OCommandSQLPojoWrapper ( this , underlying . command ( iCommand ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of parameters : if a POJO is used then replace it with its record id . [CODESPLIT] protected void convertParameters ( final Object ... iArgs ) { if ( iArgs == null ) return ; // FILTER PARAMETERS\r for ( int i = 0 ; i < iArgs . length ; ++ i ) iArgs [ i ] = convertParameter ( iArgs [ i ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets as dirty a POJO . This is useful when you change the object and need to tell to the engine to treat as dirty . [CODESPLIT] public void setDirty ( final Object iPojo ) { if ( iPojo == null ) return ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record == null ) throw new OObjectNotManagedException ( \"The object \" + iPojo + \" is not managed by current database\" ) ; record . setDirty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets as not dirty a POJO . This is useful when you change some other object and need to tell to the engine to treat this one as not dirty . [CODESPLIT] public void unsetDirty ( final Object iPojo ) { if ( iPojo == null ) return ; final ODocument record = getRecordByUserObject ( iPojo , false ) ; if ( record == null ) return ; ORecordInternal . unsetDirty ( record ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a parameter : if a POJO is used then replace it with its record id . [CODESPLIT] protected Object convertParameter ( final Object iParameter ) { if ( iParameter != null ) // FILTER PARAMETERS\r if ( iParameter instanceof Map < ? , ? > ) { Map < String , Object > map = ( Map < String , Object > ) iParameter ; for ( Map . Entry < String , Object > e : map . entrySet ( ) ) { map . put ( e . getKey ( ) , convertParameter ( e . getValue ( ) ) ) ; } return map ; } else if ( iParameter instanceof Collection < ? > ) { List < Object > result = new ArrayList < Object > ( ) ; for ( Object object : ( Collection < Object > ) iParameter ) { result . add ( convertParameter ( object ) ) ; } return result ; } else if ( iParameter . getClass ( ) . isEnum ( ) ) { return ( ( Enum < ? > ) iParameter ) . name ( ) ; } else if ( ! OType . isSimpleType ( iParameter ) ) { final ORID rid = getIdentity ( iParameter ) ; if ( rid != null && rid . isValid ( ) ) // REPLACE OBJECT INSTANCE WITH ITS RECORD ID\r return rid ; } return iParameter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates on all factories and append all index types . [CODESPLIT] private static Set < String > getIndexTypes ( ) { final Set < String > types = new HashSet <> ( ) ; final Iterator < OIndexFactory > ite = getAllFactories ( ) ; while ( ite . hasNext ( ) ) { types . addAll ( ite . next ( ) . getTypes ( ) ) ; } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates on all factories and append all index engines . [CODESPLIT] public static Set < String > getIndexEngines ( ) { final Set < String > engines = new HashSet <> ( ) ; final Iterator < OIndexFactory > ite = getAllFactories ( ) ; while ( ite . hasNext ( ) ) { engines . addAll ( ite . next ( ) . getAlgorithms ( ) ) ; } return engines ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param storage TODO @param indexType index type [CODESPLIT] public static OIndexInternal < ? > createIndex ( OStorage storage , String name , String indexType , String algorithm , String valueContainerAlgorithm , ODocument metadata , int version ) throws OConfigurationException , OIndexException { if ( indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . UNIQUE_HASH_INDEX . name ( ) ) || indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . NOTUNIQUE_HASH_INDEX . name ( ) ) || indexType . equalsIgnoreCase ( OClass . INDEX_TYPE . DICTIONARY_HASH_INDEX . name ( ) ) ) { if ( ! algorithm . equalsIgnoreCase ( \"autosharding\" ) ) { algorithm = OHashIndexFactory . HASH_INDEX_ALGORITHM ; } } return findFactoryByAlgorithmAndType ( algorithm , indexType ) . createIndex ( name , storage , indexType , algorithm , valueContainerAlgorithm , metadata , version ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Not synchronized it s called when a message arrives [CODESPLIT] public boolean collectResponse ( final ODistributedResponse response ) { final String executorNode = response . getExecutorNodeName ( ) ; final String senderNode = response . getSenderNodeName ( ) ; response . setDistributedResponseManager ( this ) ; synchronousResponsesLock . lock ( ) ; try { if ( ! executorNode . equals ( dManager . getLocalNodeName ( ) ) && ! responses . containsKey ( executorNode ) ) { ODistributedServerLog . warn ( this , senderNode , executorNode , DIRECTION . IN , \"Received response for request (%s) from unexpected node. Expected are: %s\" , request , getExpectedNodes ( ) ) ; Orient . instance ( ) . getProfiler ( ) . updateCounter ( \"distributed.node.unexpectedNodeResponse\" , \"Number of responses from unexpected nodes\" , + 1 ) ; return false ; } dManager . getMessageService ( ) . updateLatency ( executorNode , sentOn ) ; responses . put ( executorNode , response ) ; receivedResponses ++ ; if ( waitForLocalNode && executorNode . equals ( senderNode ) ) receivedCurrentNode = true ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , senderNode , executorNode , DIRECTION . IN , \"Received response '%s' for request (%s) (receivedCurrentNode=%s receivedResponses=%d totalExpectedResponses=%d quorum=%d)\" , response , request , receivedCurrentNode , receivedResponses , totalExpectedResponses , quorum ) ; if ( groupResponsesByResult ) { // PUT THE RESPONSE IN THE RIGHT RESPONSE GROUP // TODO: AVOID TO KEEP ALL THE RESULT FOR THE SAME RESP GROUP, BUT RATHER THE FIRST ONE + COUNTER final Object responsePayload = response . getPayload ( ) ; boolean foundBucket = false ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { final List < ODistributedResponse > responseGroup = responseGroups . get ( i ) ; if ( responseGroup . isEmpty ( ) ) // ABSENT foundBucket = true ; else { final Object rgPayload = responseGroup . get ( 0 ) . getPayload ( ) ; if ( rgPayload == null && responsePayload == null ) // BOTH NULL foundBucket = true ; else if ( rgPayload != null ) { if ( rgPayload instanceof ODocument && responsePayload instanceof ODocument && ! ( ( ODocument ) rgPayload ) . getIdentity ( ) . isValid ( ) && ( ( ODocument ) rgPayload ) . hasSameContentOf ( ( ODocument ) responsePayload ) ) // SAME RESULT foundBucket = true ; else if ( rgPayload . equals ( responsePayload ) ) // SAME RESULT foundBucket = true ; else if ( rgPayload instanceof Collection && responsePayload instanceof Collection ) { if ( OMultiValue . equals ( ( Collection ) rgPayload , ( Collection ) responsePayload ) ) // COLLECTIONS WITH THE SAME VALUES foundBucket = true ; } } } if ( foundBucket ) { responseGroup . add ( response ) ; break ; } } if ( ! foundBucket ) { // CREATE A NEW BUCKET final ArrayList < ODistributedResponse > newBucket = new ArrayList < ODistributedResponse > ( ) ; responseGroups . add ( newBucket ) ; newBucket . add ( response ) ; } } // FOR EVERY RESPONSE COLLECTED, COMPUTE THE FINAL QUORUM RESPONSE IF POSSIBLE computeQuorumResponse ( false ) ; return checkForCompletion ( ) ; } finally { synchronousResponsesLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param localNodeName @param localResult [CODESPLIT] public boolean setLocalResult ( final String localNodeName , final Object localResult ) { localResponse = new ODistributedResponse ( this , request . getId ( ) , localNodeName , localNodeName , localResult ) ; receivedCurrentNode = true ; return collectResponse ( localResponse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits until the minimum responses are collected or timeout occurs . If waitForLocalNode wait also for local node . [CODESPLIT] public boolean waitForSynchronousResponses ( ) throws InterruptedException { final long beginTime = System . currentTimeMillis ( ) ; try { boolean reachedTimeout = false ; long currentTimeout = synchTimeout ; while ( currentTimeout > 0 ) { if ( currentTimeout > 10000 ) // CUT THE TIMEOUT IN BLOCKS OF 10S EACH TO ALLOW CHECKING FOR ANY SERVER IF UNREACHABLE currentTimeout = 10000 ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"Waiting max %dms for collecting all synchronous responses... (timeout=%d reqId=%s thread=%d)\" , currentTimeout , synchTimeout , request . getId ( ) , Thread . currentThread ( ) . getId ( ) ) ; // WAIT FOR THE RESPONSES if ( synchronousResponsesArrived . await ( currentTimeout , TimeUnit . MILLISECONDS ) ) { if ( canceled . get ( ) ) throw new ODistributedOperationException ( \"Request has been canceled\" ) ; // COMPLETED if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"All synchronous responses collected in %dms (reqId=%s thread=%d)\" , ( System . currentTimeMillis ( ) - beginTime ) , request . getId ( ) , Thread . currentThread ( ) . getId ( ) ) ; return true ; } if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"All synchronous responses not collected in %dms, waiting again... (reqId=%s thread=%d)\" , ( System . currentTimeMillis ( ) - beginTime ) , request . getId ( ) , Thread . currentThread ( ) . getId ( ) ) ; if ( Thread . currentThread ( ) . isInterrupted ( ) ) { // INTERRUPTED ODistributedServerLog . warn ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"Thread has been interrupted wait for request (%s)\" , request ) ; Thread . currentThread ( ) . interrupt ( ) ; break ; } synchronousResponsesLock . lock ( ) ; try { final long now = System . currentTimeMillis ( ) ; final long elapsed = now - beginTime ; if ( elapsed > synchTimeout ) reachedTimeout = true ; currentTimeout = synchTimeout - elapsed ; // CHECK IF ANY NODE ARE UNREACHABLE IN THE MEANWHILE int synchronizingNodes = 0 ; int missingActiveNodes = 0 ; Map < String , ODistributedServerManager . DB_STATUS > missingResponseNodeStatuses = new HashMap < String , ODistributedServerManager . DB_STATUS > ( responses . size ( ) ) ; int missingResponses = 0 ; for ( Iterator < Map . Entry < String , Object > > iter = responses . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { final Map . Entry < String , Object > curr = iter . next ( ) ; if ( curr . getValue ( ) == NO_RESPONSE ) { missingResponses ++ ; // ANALYZE THE NODE WITHOUT A RESPONSE final ODistributedServerManager . DB_STATUS dbStatus = dManager . getDatabaseStatus ( curr . getKey ( ) , getDatabaseName ( ) ) ; missingResponseNodeStatuses . put ( curr . getKey ( ) , dbStatus ) ; switch ( dbStatus ) { case BACKUP : case SYNCHRONIZING : synchronizingNodes ++ ; missingActiveNodes ++ ; break ; case ONLINE : missingActiveNodes ++ ; break ; } } } if ( missingResponses == 0 ) { // ALL RESPONSE COLLECTED, BUT NO QUORUM REACHED ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"All responses collected %s, but no quorum reached (reqId=%s)\" , responses , request . getId ( ) ) ; break ; } request . getTask ( ) . checkIsValid ( dManager ) ; if ( missingActiveNodes == 0 ) { // NO MORE ACTIVE NODES TO WAIT ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"No more active nodes to wait for request (%s): anticipate timeout (saved %d ms). Missing servers: %s\" , request , currentTimeout , missingResponseNodeStatuses ) ; break ; } final long lastClusterChange = dManager . getLastClusterChangeOn ( ) ; if ( lastClusterChange > 0 && now - lastClusterChange < ( synchTimeout + ADDITIONAL_TIMEOUT_CLUSTER_SHAPE ) ) { // CHANGED CLUSTER SHAPE DURING WAIT: ENLARGE TIMEOUT currentTimeout = synchTimeout ; ODistributedServerLog . debug ( this , dManager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"Cluster shape changed during request (%s): enlarge timeout +%dms, wait again for %dms\" , request , synchTimeout , currentTimeout ) ; continue ; } else if ( synchronizingNodes > 0 ) { // SOME NODE IS SYNCHRONIZING: WAIT FOR THEM // currentTimeout = synchTimeout; // ODistributedServerLog.debug(this, dManager.getLocalNodeName(), null, DIRECTION.NONE, // \"%d nodes are in synchronization mode during request (%s): enlarge timeout +%dms, wait again for %dms\", // synchronizingNodes, request, synchTimeout, currentTimeout); } } finally { synchronousResponsesLock . unlock ( ) ; } } if ( canceled . get ( ) ) throw new ODistributedOperationException ( \"Request has been canceled\" ) ; return isMinimumQuorumReached ( reachedTimeout ) ; } finally { Orient . instance ( ) . getProfiler ( ) . stopChrono ( \"distributed.synchResponses\" , \"Time to collect all the synchronous responses from distributed nodes\" , beginTime ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the list of node names that didn t provide a response . [CODESPLIT] public List < String > getMissingNodes ( ) { synchronousResponsesLock . lock ( ) ; try { final List < String > missingNodes = new ArrayList < String > ( ) ; for ( Map . Entry < String , Object > entry : responses . entrySet ( ) ) if ( entry . getValue ( ) == NO_RESPONSE ) missingNodes . add ( entry . getKey ( ) ) ; return missingNodes ; } finally { synchronousResponsesLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the responses in conflict . [CODESPLIT] protected List < ODistributedResponse > getConflictResponses ( ) { final List < ODistributedResponse > servers = new ArrayList < ODistributedResponse > ( ) ; int bestGroupSoFar = getBestResponsesGroup ( ) ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { if ( i != bestGroupSoFar ) { for ( ODistributedResponse r : responseGroups . get ( i ) ) servers . ( r ) ; } } return servers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the biggest response group . [CODESPLIT] protected int getBestResponsesGroup ( ) { int maxCoherentResponses = 0 ; int bestGroupSoFar = 0 ; for ( int i = 0 ; i < responseGroups . size ( ) ; ++ i ) { final int currentGroupSize = responseGroups . get ( i ) . size ( ) ; if ( currentGroupSize > maxCoherentResponses ) { maxCoherentResponses = currentGroupSize ; bestGroupSoFar = i ; } } return bestGroupSoFar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the quorum response if possible by returning true and setting the field quorumResponse with the ODistributedResponse . [CODESPLIT] private boolean computeQuorumResponse ( boolean reachedTimeout ) { if ( quorumResponse != null ) // ALREADY COMPUTED return true ; if ( groupResponsesByResult ) { for ( List < ODistributedResponse > group : responseGroups ) { if ( group . size ( ) >= quorum ) { int responsesForQuorum = 0 ; for ( ODistributedResponse r : group ) { if ( nodesConcurInQuorum . contains ( r . getExecutorNodeName ( ) ) ) { final Object payload = r . getPayload ( ) ; if ( payload instanceof Throwable ) { if ( payload instanceof ODistributedRecordLockedException ) // JUST ONE ODistributedRecordLockedException IS ENOUGH TO FAIL THE OPERATION BECAUSE RESOURCES CANNOT BE LOCKED break ; if ( payload instanceof OConcurrentCreateException ) // JUST ONE OConcurrentCreateException IS ENOUGH TO FAIL THE OPERATION BECAUSE RID ARE DIFFERENT break ; } else if ( ++ responsesForQuorum >= quorum ) { // QUORUM REACHED setQuorumResponse ( r ) ; return true ; } } } } } } else { if ( receivedResponses >= quorum ) { int responsesForQuorum = 0 ; for ( Map . Entry < String , Object > response : responses . entrySet ( ) ) { if ( response . getValue ( ) != NO_RESPONSE && nodesConcurInQuorum . contains ( response . getKey ( ) ) && ++ responsesForQuorum >= quorum ) { // QUORUM REACHED ODistributedResponse resp = ( ODistributedResponse ) response . getValue ( ) ; if ( resp != null && ! ( resp . getPayload ( ) instanceof Throwable ) ) setQuorumResponse ( resp ) ; return true ; } } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the received response objects . [CODESPLIT] protected List < ODistributedResponse > getReceivedResponses ( ) { final List < ODistributedResponse > parsed = new ArrayList < ODistributedResponse > ( ) ; for ( Object r : responses . values ( ) ) if ( r != NO_RESPONSE ) parsed . add ( ( ODistributedResponse ) r ) ; return parsed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns an already prepared SQL execution plan taking it from the cache if it exists or creating a new one if it doesn t [CODESPLIT] public static OExecutionPlan get ( String statement , OCommandContext ctx , ODatabaseDocumentInternal db ) { if ( db == null ) { throw new IllegalArgumentException ( \"DB cannot be null\" ) ; } if ( statement == null ) { return null ; } OExecutionPlanCache resource = db . getSharedContext ( ) . getExecutionPlanCache ( ) ; OExecutionPlan result = resource . getInternal ( statement , ctx , db ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param statement an SQL statement @param ctx [CODESPLIT] public OExecutionPlan getInternal ( String statement , OCommandContext ctx , ODatabaseDocumentInternal db ) { OInternalExecutionPlan result ; if ( statement == null ) { return null ; } synchronized ( map ) { //LRU result = map . remove ( statement ) ; if ( result != null ) { map . put ( statement , result ) ; result = result . copy ( ctx ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if the condition involved the current pattern ( MATCH statement eg . $matched . something = foo ) returns the name of involved pattern aliases ( something in this case ) [CODESPLIT] List < String > getMatchPatternInvolvedAliases ( ) { if ( mathExpression != null ) return mathExpression . getMatchPatternInvolvedAliases ( ) ; if ( arrayConcatExpression != null ) return arrayConcatExpression . getMatchPatternInvolvedAliases ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tests if current expression involves an indexed function AND that function can be used on this target [CODESPLIT] public boolean allowsIndexedFunctionExecutionOnTarget ( OFromClause target , OCommandContext context ) { return left . allowsIndexedFunctionExecutionOnTarget ( target , context , operator , right . execute ( ( OResult ) null , context ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats the library of functions for a language . [CODESPLIT] public String getLibrary ( final ODatabase < ? > db , final String iLanguage ) { if ( db == null ) // NO DB = NO LIBRARY\r return null ; final StringBuilder code = new StringBuilder ( ) ; final Set < String > functions = db . getMetadata ( ) . getFunctionLibrary ( ) . getFunctionNames ( ) ; for ( String fName : functions ) { final OFunction f = db . getMetadata ( ) . getFunctionLibrary ( ) . getFunction ( fName ) ; if ( f . getLanguage ( ) == null ) throw new OConfigurationException ( \"Database function '\" + fName + \"' has no language\" ) ; if ( f . getLanguage ( ) . equalsIgnoreCase ( iLanguage ) ) { final String def = getFunctionDefinition ( f ) ; if ( def != null ) { code . append ( def ) ; code . append ( \"\\n\" ) ; } } } return code . length ( ) == 0 ? null : code . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires a database engine from the pool . Once finished using it the instance MUST be returned in the pool by calling the method #releaseDatabaseEngine ( String ScriptEngine ) . [CODESPLIT] public OPartitionedObjectPool . PoolEntry < ScriptEngine > acquireDatabaseEngine ( final String databaseName , final String language ) { ODatabaseScriptManager dbManager = dbManagers . get ( databaseName ) ; if ( dbManager == null ) { // CREATE A NEW DATABASE SCRIPT MANAGER\r dbManager = new ODatabaseScriptManager ( this , databaseName ) ; final ODatabaseScriptManager prev = dbManagers . putIfAbsent ( databaseName , dbManager ) ; if ( prev != null ) { dbManager . close ( ) ; // GET PREVIOUS ONE\r dbManager = prev ; } } return dbManager . acquireEngine ( language ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires a database engine from the pool . Once finished using it the instance MUST be returned in the pool by calling the method [CODESPLIT] public void releaseDatabaseEngine ( final String iLanguage , final String iDatabaseName , final OPartitionedObjectPool . PoolEntry < ScriptEngine > poolEntry ) { final ODatabaseScriptManager dbManager = dbManagers . get ( iDatabaseName ) ; // We check if there is still a valid pool because it could be removed by the function reload\r if ( dbManager != null ) { dbManager . releaseEngine ( iLanguage , poolEntry ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbinds variables [CODESPLIT] public void unbind ( ScriptEngine scriptEngine , final Bindings binding , final OCommandContext iContext , final Map < Object , Object > iArgs ) { for ( OScriptInjection i : injections ) i . unbind ( scriptEngine , binding ) ; binding . put ( \"db\" , null ) ; binding . put ( \"orient\" , null ) ; binding . put ( \"util\" , null ) ; binding . put ( \"ctx\" , null ) ; if ( iContext != null ) { for ( Entry < String , Object > a : iContext . getVariables ( ) . entrySet ( ) ) binding . put ( a . getKey ( ) , null ) ; } if ( iArgs != null ) { for ( Entry < Object , Object > a : iArgs . entrySet ( ) ) binding . put ( a . getKey ( ) . toString ( ) , null ) ; } binding . put ( \"params\" , null ) ; } public void registerInjection ( final OScriptInjection iInj ) { if ( ! injections . contains ( iInj ) ) injections . add ( iInj ) ; } public void unregisterInjection  ( final OScriptInjection iInj ) { injections . remove ( iInj ) ; } public List < OScriptInjection > getInjections  ( ) { return injections ; } public OScriptManager registerEngine  ( final String iLanguage , final ScriptEngineFactory iEngine ) { engines . put ( iLanguage , iEngine ) ; return this ; } public OScriptManager registerFormatter  ( final String iLanguage , final OScriptFormatter iFormatterImpl ) { formatters . put ( iLanguage . toLowerCase ( Locale . ENGLISH ) , iFormatterImpl ) ; return this ; } public OScriptManager registerResultHandler  ( final String iLanguage , final OScriptResultHandler resultHandler ) { handlers . put ( iLanguage . toLowerCase ( Locale . ENGLISH ) , resultHandler ) ; return this ; } public Object handleResult  ( String language , Object result , ScriptEngine engine , Bindings binding , ODatabaseDocument database ) { OScriptResultHandler handler = handlers . get ( language ) ; if ( handler != null ) { return handler . handle ( result , engine , binding , database ) ; } else { return result ; } } /**\r\n   * Ask to the Script engine all the formatters\r\n   *\r\n   * @return Map containing all the formatters\r\n   */ public Map < String , OScriptFormatter > getFormatters  ( ) { return formatters ; } /**\r\n   * Closes the pool for a database. This is called at Orient shutdown and in case a function has been updated.\r\n   *\r\n   * @param iDatabaseName\r\n   */ public void close  ( final String iDatabaseName ) { final ODatabaseScriptManager dbPool = dbManagers . remove ( iDatabaseName ) ; if ( dbPool != null ) dbPool . close ( ) ; } }  ", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next position available . [CODESPLIT] long getNextPosition ( final OAtomicOperation atomicOperation ) throws IOException { final long filledUpTo = getFilledUpTo ( atomicOperation , fileId ) ; final long pageIndex = filledUpTo - 1 ; final OCacheEntry cacheEntry = loadPageForRead ( atomicOperation , fileId , pageIndex , false , 1 ) ; try { final OClusterPositionMapBucket bucket = new OClusterPositionMapBucket ( cacheEntry , false ) ; final int bucketSize = bucket . getSize ( ) ; return pageIndex * OClusterPositionMapBucket . MAX_ENTRIES + bucketSize ; } finally { releasePageFromRead ( atomicOperation , cacheEntry ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recalculates real bag size . [CODESPLIT] private int updateSize ( ) { int size = 0 ; if ( collectionPointer != null ) { final OSBTreeBonsai < OIdentifiable , Integer > tree = loadTree ( ) ; if ( tree == null ) { throw new IllegalStateException ( \"RidBag is not properly initialized, can not load tree implementation\" ) ; } try { size = tree . getRealBagSize ( changes ) ; } finally { releaseTree ( ) ; } } else { for ( Change change : changes . values ( ) ) { size += change . applyTo ( 0 ) ; } } for ( OModifiableInteger diff : newEntries . values ( ) ) { size += diff . getValue ( ) ; } this . size = size ; return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes entry with given key from { @link #newEntries } . [CODESPLIT] private boolean removeFromNewEntries ( final OIdentifiable identifiable ) { OModifiableInteger counter = newEntries . get ( identifiable ) ; if ( counter == null ) { return false ; } else { if ( counter . getValue ( ) == 1 ) { newEntries . remove ( identifiable ) ; } else { counter . decrement ( ) ; } return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "it s not key = [ ... ] but a real condition on field names already ordered ( field names will be ignored ) [CODESPLIT] private void processAndBlock ( ) { OCollection fromKey = indexKeyFrom ( ( OAndBlock ) condition , additionalRangeCondition ) ; OCollection toKey = indexKeyTo ( ( OAndBlock ) condition , additionalRangeCondition ) ; boolean fromKeyIncluded = indexKeyFromIncluded ( ( OAndBlock ) condition , additionalRangeCondition ) ; boolean toKeyIncluded = indexKeyToIncluded ( ( OAndBlock ) condition , additionalRangeCondition ) ; init ( fromKey , fromKeyIncluded , toKey , toKeyIncluded ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is for subqueries when a OResult is found <ul > <li > if it s a projection with a single column the value is returned< / li > <li > if it s a document the RID is returned< / li > < / ul > [CODESPLIT] private Object unboxOResult ( Object value ) { if ( value instanceof List ) { return ( ( List ) value ) . stream ( ) . map ( x -> unboxOResult ( x ) ) . collect ( Collectors . toList ( ) ) ; } if ( value instanceof OResult ) { if ( ( ( OResult ) value ) . isElement ( ) ) { return ( ( OResult ) value ) . getIdentity ( ) . orElse ( null ) ; } Set < String > props = ( ( OResult ) value ) . getPropertyNames ( ) ; if ( props . size ( ) == 1 ) { return ( ( OResult ) value ) . getProperty ( props . iterator ( ) . next ( ) ) ; } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the value stored under the given index in this bucket . [CODESPLIT] public V getValue ( int index ) { int entryPosition = getIntValue ( POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer . INT_SIZE ) ; // skip hash code entryPosition += OLongSerializer . LONG_SIZE ; if ( encryption == null ) { // skip key entryPosition += getObjectSizeInDirectMemory ( keySerializer , entryPosition ) ; } else { final int encryptedLength = getIntValue ( entryPosition ) ; entryPosition += encryptedLength + OIntegerSerializer . INT_SIZE ; } return deserializeFromDirectMemory ( valueSerializer , entryPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks if given a list of = conditions and a set of ORDER BY fields [CODESPLIT] boolean canBeUsedByOrderByAfterFilter ( OIndex < ? > index , List < String > equalsFilterFields , List < OPair < String , String > > orderedFields ) { if ( orderedFields . isEmpty ( ) ) return false ; if ( ! index . supportsOrderedIterations ( ) ) return false ; final OIndexDefinition definition = index . getDefinition ( ) ; final List < String > indexFields = definition . getFields ( ) ; int endIndex = Math . min ( indexFields . size ( ) , equalsFilterFields . size ( ) ) ; final String firstOrder = orderedFields . get ( 0 ) . getValue ( ) ; //check that all the \"equals\" clauses are a prefix for the index for ( int i = 0 ; i < endIndex ; i ++ ) { final String equalsFieldName = equalsFilterFields . get ( i ) ; final String indexFieldName = indexFields . get ( i ) ; if ( ! equalsFieldName . equals ( indexFieldName ) ) return false ; } endIndex = Math . min ( indexFields . size ( ) , orderedFields . size ( ) + equalsFilterFields . size ( ) ) ; if ( endIndex == equalsFilterFields . size ( ) ) { //the index is used only for filtering return false ; } //check that after that prefix there all the Order By fields in the right order for ( int i = equalsFilterFields . size ( ) ; i < endIndex ; i ++ ) { int fieldOrderInOrderByClause = i - equalsFilterFields . size ( ) ; final OPair < String , String > pair = orderedFields . get ( fieldOrderInOrderByClause ) ; if ( ! firstOrder . equals ( pair . getValue ( ) ) ) return false ; final String orderFieldName = pair . getKey ( ) ; final String indexFieldName = indexFields . get ( i ) ; if ( ! orderFieldName . equals ( indexFieldName ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a character inside a string specyfing the limits and direction . If iFrom is minor than iTo then it moves forward otherwise backward . [CODESPLIT] public static int indexOfOutsideStrings ( final String iText , final char iToFind , int iFrom , int iTo ) { if ( iTo == - 1 ) iTo = iText . length ( ) - 1 ; if ( iFrom == - 1 ) iFrom = iText . length ( ) - 1 ; char c ; char stringChar = ' ' ; boolean escape = false ; final StringBuilder buffer = new StringBuilder ( 1024 ) ; int i = iFrom ; while ( true ) { c = iText . charAt ( i ) ; if ( ! escape && c == ' ' && ( ( i + 1 ) < iText . length ( ) ) ) { if ( iText . charAt ( i + 1 ) == ' ' ) { i = readUnicode ( iText , i + 2 , buffer ) ; } else escape = true ; } else { if ( c == ' ' || c == ' ' ) { // BEGIN/END STRING if ( stringChar == ' ' ) { // BEGIN stringChar = c ; } else { // END if ( ! escape && c == stringChar ) stringChar = ' ' ; } } if ( c == iToFind && stringChar == ' ' ) return i ; if ( escape ) escape = false ; } if ( iFrom < iTo ) { // MOVE FORWARD if ( ++ i > iTo ) break ; } else { // MOVE BACKWARD if ( -- i < iFrom ) break ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Jump white spaces . [CODESPLIT] public static int jumpWhiteSpaces ( final CharSequence iText , final int iCurrentPosition , final int iMaxPosition ) { return jump ( iText , iCurrentPosition , iMaxPosition , COMMON_JUMP ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Jump some characters reading from an offset of a String . [CODESPLIT] public static int jump ( final CharSequence iText , int iCurrentPosition , final int iMaxPosition , final String iJumpChars ) { if ( iCurrentPosition < 0 ) return - 1 ; final int size = iMaxPosition > - 1 ? Math . min ( iMaxPosition , iText . length ( ) ) : iText . length ( ) ; final int jumpCharSize = iJumpChars . length ( ) ; boolean found = true ; char c ; for ( ; iCurrentPosition < size ; ++ iCurrentPosition ) { found = false ; c = iText . charAt ( iCurrentPosition ) ; for ( int jumpIndex = 0 ; jumpIndex < jumpCharSize ; ++ jumpIndex ) { if ( iJumpChars . charAt ( jumpIndex ) == c ) { found = true ; break ; } } if ( ! found ) break ; } return iCurrentPosition >= size ? - 1 : iCurrentPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like String . startsWith () but ignoring case [CODESPLIT] public static boolean startsWithIgnoreCase ( final String iText , final String iToFind ) { if ( iText . length ( ) < iToFind . length ( ) ) return false ; return iText . substring ( 0 , iToFind . length ( ) ) . equalsIgnoreCase ( iToFind ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the fetch plan to use . [CODESPLIT] public OQueryAbstract setFetchPlan ( final String fetchPlan ) { OFetchHelper . checkFetchPlanValid ( fetchPlan ) ; if ( fetchPlan != null && fetchPlan . length ( ) == 0 ) this . fetchPlan = null ; else this . fetchPlan = fetchPlan ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the record to repair int the map of records and cluster . The decision about repairing is taken by the timer task . [CODESPLIT] @ Override public void enqueueRepairRecord ( final ORecordId rid ) { if ( ! active ) return ; if ( rid == null || ! rid . isPersistent ( ) ) return ; if ( rid . getClusterPosition ( ) < - 1 ) // SKIP TRANSACTIONAL RIDS return ; recordProcessed . incrementAndGet ( ) ; // ADD RECORD TO REPAIR records . put ( rid , Boolean . TRUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancel the repair against a record because the update succeed . [CODESPLIT] @ Override public void cancelRepairRecord ( final ORecordId rid ) { if ( ! active ) return ; if ( rid . getClusterPosition ( ) < - 1 ) // SKIP TRANSACTIONAL RIDS return ; // REMOVE THE RECORD TO REPAIR if ( records . remove ( rid ) != null ) // REMOVED recordCanceled . incrementAndGet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enqueues the request to repair a cluster . The decision about repairing is taken by the timer task . [CODESPLIT] @ Override public void enqueueRepairCluster ( final int clusterId ) { if ( ! active ) return ; if ( clusterId < - 1 ) // SKIP TRANSACTIONAL RIDS return ; recordProcessed . incrementAndGet ( ) ; // ADD CLUSTER TO REPAIR clusters . put ( clusterId , Boolean . TRUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . SERVER , \"status\" , ORole . PERMISSION_READ ) ; if ( ! ( database instanceof ODatabaseDocumentDistributed ) ) { throw new OCommandExecutionException ( \"OrientDB is not started in distributed mode\" ) ; } final OHazelcastPlugin dManager = ( OHazelcastPlugin ) ( ( ODatabaseDocumentDistributed ) database ) . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( \"OrientDB is not started in distributed mode\" ) ; final String databaseName = database . getName ( ) ; final ODistributedConfiguration cfg = dManager . getDatabaseConfiguration ( databaseName ) ; if ( parsedStatement . outputText ) { final StringBuilder output = new StringBuilder ( ) ; if ( parsedStatement . servers ) output . append ( ODistributedOutput . formatServerStatus ( dManager , dManager . getClusterConfiguration ( ) ) ) ; if ( parsedStatement . db ) output . append ( ODistributedOutput . formatClusterTable ( dManager , databaseName , cfg , dManager . getTotalNodes ( databaseName ) ) ) ; if ( parsedStatement . latency ) output . append ( ODistributedOutput . formatLatency ( dManager , dManager . getClusterConfiguration ( ) ) ) ; if ( parsedStatement . messages ) output . append ( ODistributedOutput . formatMessages ( dManager , dManager . getClusterConfiguration ( ) ) ) ; return output . toString ( ) ; } final ODocument output = new ODocument ( ) ; if ( parsedStatement . servers ) output . field ( \"servers\" , dManager . getClusterConfiguration ( ) , OType . EMBEDDED ) ; if ( parsedStatement . db ) output . field ( \"database\" , cfg . getDocument ( ) , OType . EMBEDDED ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the set of dependency aliases for each alias in the pattern . [CODESPLIT] private Map < String , Set < String > > getDependencies ( Pattern pattern ) { Map < String , Set < String > > result = new HashMap < String , Set < String > > ( ) ; for ( PatternNode node : pattern . aliasToNode . values ( ) ) { Set < String > currentDependencies = new HashSet < String > ( ) ; OWhereClause filter = aliasFilters . get ( node . alias ) ; if ( filter != null && filter . getBaseExpression ( ) != null ) { List < String > involvedAliases = filter . getBaseExpression ( ) . getMatchPatternInvolvedAliases ( ) ; if ( involvedAliases != null ) { currentDependencies . addAll ( involvedAliases ) ; } } result . put ( node . alias , currentDependencies ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sort edges in the order they will be matched [CODESPLIT] private List < EdgeTraversal > sortEdges ( Map < String , Long > estimatedRootEntries , Pattern pattern , OCommandContext ctx ) { OQueryStats stats = null ; if ( ctx != null && ctx . getDatabase ( ) != null ) { stats = OQueryStats . get ( ( ODatabaseDocumentInternal ) ctx . getDatabase ( ) ) ; } //TODO use the stats List < EdgeTraversal > result = new ArrayList < EdgeTraversal > ( ) ; List < OPair < Long , String > > rootWeights = new ArrayList < OPair < Long , String > > ( ) ; for ( Map . Entry < String , Long > root : estimatedRootEntries . entrySet ( ) ) { rootWeights . add ( new OPair < Long , String > ( root . getValue ( ) , root . getKey ( ) ) ) ; } Collections . sort ( rootWeights ) ; Set < PatternEdge > traversedEdges = new HashSet < PatternEdge > ( ) ; Set < PatternNode > traversedNodes = new HashSet < PatternNode > ( ) ; List < PatternNode > nextNodes = new ArrayList < PatternNode > ( ) ; while ( result . size ( ) < pattern . getNumOfEdges ( ) ) { for ( OPair < Long , String > rootPair : rootWeights ) { PatternNode root = pattern . get ( rootPair . getValue ( ) ) ; if ( root . isOptionalNode ( ) ) { continue ; } if ( ! traversedNodes . contains ( root ) ) { nextNodes . add ( root ) ; break ; } } if ( nextNodes . isEmpty ( ) ) { break ; } while ( ! nextNodes . isEmpty ( ) ) { PatternNode node = nextNodes . remove ( 0 ) ; traversedNodes . add ( node ) ; for ( PatternEdge edge : node . out ) { if ( ! traversedEdges . contains ( edge ) ) { result . add ( new EdgeTraversal ( edge , true ) ) ; traversedEdges . add ( edge ) ; if ( ! traversedNodes . contains ( edge . in ) && ! nextNodes . contains ( edge . in ) ) { nextNodes . add ( edge . in ) ; } } } for ( PatternEdge edge : node . in ) { if ( ! traversedEdges . contains ( edge ) && edge . item . isBidirectional ( ) ) { result . add ( new EdgeTraversal ( edge , false ) ) ; traversedEdges . add ( edge ) ; if ( ! traversedNodes . contains ( edge . out ) && ! nextNodes . contains ( edge . out ) ) { nextNodes . add ( edge . out ) ; } } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assigns default aliases to pattern nodes that do not have an explicit alias [CODESPLIT] private void assignDefaultAliases ( List < OMatchExpression > matchExpressions ) { int counter = 0 ; for ( OMatchExpression expression : matchExpressions ) { if ( expression . getOrigin ( ) . getAlias ( ) == null ) { expression . getOrigin ( ) . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } for ( OMatchPathItem item : expression . getItems ( ) ) { if ( item . getFilter ( ) == null ) { item . setFilter ( new OMatchFilter ( - 1 ) ) ; } if ( item . getFilter ( ) . getAlias ( ) == null ) { item . getFilter ( ) . setAlias ( DEFAULT_ALIAS_PREFIX + ( counter ++ ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a POJO by its class name . [CODESPLIT] public synchronized Object createPojo ( final String iClassName ) throws OConfigurationException { if ( iClassName == null ) throw new IllegalArgumentException ( \"Cannot create the object: class name is empty\" ) ; final Class < ? > entityClass = classHandler . getEntityClass ( iClassName ) ; try { if ( entityClass != null ) return createInstance ( entityClass ) ; } catch ( Exception e ) { throw OException . wrapException ( new OConfigurationException ( \"Error while creating new pojo of class '\" + iClassName + \"'\" ) , e ) ; } try { // TRY TO INSTANTIATE THE CLASS DIRECTLY BY ITS NAME\r return createInstance ( Class . forName ( iClassName ) ) ; } catch ( Exception e ) { throw OException . wrapException ( new OConfigurationException ( \"The class '\" + iClassName + \"' was not found between the entity classes. Ensure registerEntityClasses(package) has been called first\" ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans all classes accessible from the context class loader which belong to the given package and subpackages . [CODESPLIT] public synchronized void deregisterEntityClasses ( final String iPackageName , final ClassLoader iClassLoader ) { OLogManager . instance ( ) . debug ( this , \"Discovering entity classes inside package: %s\" , iPackageName ) ; List < Class < ? > > classes = null ; try { classes = OReflectionHelper . getClassesFor ( iPackageName , iClassLoader ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( \"Class cannot be found in package \" + iPackageName ) , e ) ; } for ( Class < ? > c : classes ) { deregisterEntityClass ( c ) ; } if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) { for ( Entry < String , Class < ? > > entry : classHandler . getClassesEntrySet ( ) ) { OLogManager . instance ( ) . debug ( this , \"Unloaded entity class '%s' from: %s\" , entry . getKey ( ) , entry . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers provided classes [CODESPLIT] public synchronized void registerEntityClasses ( final Collection < String > iClassNames , final ClassLoader iClassLoader ) { OLogManager . instance ( ) . debug ( this , \"Discovering entity classes for class names: %s\" , iClassNames ) ; try { registerEntityClasses ( OReflectionHelper . getClassesFor ( iClassNames , iClassLoader ) ) ; } catch ( ClassNotFoundException e ) { throw OException . wrapException ( new ODatabaseException ( \"Entity class cannot be found\" ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans all classes accessible from the context class loader which belong to the given class and all it s attributes - classes . [CODESPLIT] public synchronized void registerEntityClasses ( Class < ? > aClass , boolean recursive ) { if ( recursive ) { classHandler . registerEntityClass ( aClass ) ; Field [ ] declaredFields = aClass . getDeclaredFields ( ) ; for ( Field declaredField : declaredFields ) { Class < ? > declaredFieldType = declaredField . getType ( ) ; if ( ! classHandler . containsEntityClass ( declaredFieldType ) ) { registerEntityClasses ( declaredFieldType , recursive ) ; } } } else { classHandler . registerEntityClass ( aClass ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the received handler as default and merges the classes all together . [CODESPLIT] public synchronized void setClassHandler ( final OEntityManagerClassHandler iClassHandler ) { Iterator < Entry < String , Class < ? > > > iterator = classHandler . getClassesEntrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Entry < String , Class < ? > > entry = iterator . next ( ) ; boolean forceSchemaReload = ! iterator . hasNext ( ) ; iClassHandler . registerEntityClass ( entry . getValue ( ) , forceSchemaReload ) ; } this . classHandler = iClassHandler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires a connection from the pool . If the pool is empty then the caller thread will wait for it . [CODESPLIT] public DB acquire ( final String iName , final String iUserName , final String iUserPassword ) { setup ( ) ; return dbPool . acquire ( iName , iUserName , iUserPassword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns amount of available connections which you can acquire for given source and user name . Source id is consist of source name and source user name . [CODESPLIT] public int getAvailableConnections ( final String name , final String userName ) { setup ( ) ; return dbPool . getAvailableConnections ( name , userName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires a connection from the pool specifying options . If the pool is empty then the caller thread will wait for it . [CODESPLIT] public DB acquire ( final String iName , final String iUserName , final String iUserPassword , final Map < String , Object > iOptionalParams ) { setup ( ) ; return dbPool . acquire ( iName , iUserName , iUserPassword , iOptionalParams ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the SYNC CLUSTER . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . CLUSTER , \"sync\" , ORole . PERMISSION_UPDATE ) ; if ( ! ( database instanceof ODatabaseDocumentDistributed ) ) { throw new OCommandExecutionException ( \"OrientDB is not started in distributed mode\" ) ; } final OHazelcastPlugin dManager = ( OHazelcastPlugin ) ( ( ODatabaseDocumentDistributed ) database ) . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( \"OrientDB is not started in distributed mode\" ) ; final String databaseName = database . getName ( ) ; try { if ( this . parsedStatement . modeFull ) { return replaceCluster ( dManager , database , dManager . getServerInstance ( ) , databaseName , this . parsedStatement . clusterName . getStringValue ( ) ) ; } // else { // int merged = 0; // return String.format(\"Merged %d records\", merged); // } } catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( \"Cannot execute synchronization of cluster\" ) , e ) ; } return \"Mode not supported\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes binary dump of this cluster page to the log . [CODESPLIT] public void dumpToLog ( ) { final StringBuilder text = new StringBuilder ( ) ; text . append ( \"Dump of \" ) . append ( this ) . append ( ' ' ) ; text . append ( \"Magic:\\t\\t\\t\" ) . append ( String . format ( \"%016X\" , getLongValue ( MAGIC_NUMBER_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"CRC32:\\t\\t\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( CRC32_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"WAL Segment:\\t\" ) . append ( String . format ( \"%016X\" , getLongValue ( WAL_SEGMENT_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"WAL Position:\\t\" ) . append ( String . format ( \"%016X\" , getLongValue ( WAL_POSITION_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"Next Page:\\t\\t\" ) . append ( String . format ( \"%016X\" , getLongValue ( NEXT_PAGE_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"Prev Page:\\t\\t\" ) . append ( String . format ( \"%016X\" , getLongValue ( PREV_PAGE_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"Free List:\\t\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( FREELIST_HEADER_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"Free Pointer:\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( FREE_POSITION_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"Free Space:\\t\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( FREE_SPACE_COUNTER_OFFSET ) ) ) . append ( ' ' ) ; text . append ( \"Entry Count:\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( ENTRIES_COUNT_OFFSET ) ) ) . append ( ' ' ) ; final int indexCount = getIntValue ( PAGE_INDEXES_LENGTH_OFFSET ) ; text . append ( \"Index Count:\\t\" ) . append ( String . format ( \"%08X\" , indexCount ) ) . append ( \"\\n\\n\" ) ; int foundEntries = 0 ; for ( int i = 0 ; i < indexCount ; ++ i ) { final int offset = getIntValue ( PAGE_INDEXES_OFFSET + i * INDEX_ITEM_SIZE ) ; text . append ( \"\\tOffset:\\t\\t\" ) . append ( String . format ( \"%08X\" , offset ) ) . append ( \" (\" ) . append ( i ) . append ( \")\\n\" ) ; text . append ( \"\\tVersion:\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( PAGE_INDEXES_OFFSET + i * INDEX_ITEM_SIZE + OIntegerSerializer . INT_SIZE ) ) ) . append ( ' ' ) ; if ( ( offset & MARKED_AS_DELETED_FLAG ) != 0 ) { continue ; } final int cleanOffset = offset & POSITION_MASK ; text . append ( \"\\t\\tEntry Size:\\t\" ) ; if ( cleanOffset + OIntegerSerializer . INT_SIZE <= MAX_PAGE_SIZE_BYTES ) { text . append ( String . format ( \"%08X\" , getIntValue ( cleanOffset ) ) ) . append ( \" (\" ) . append ( foundEntries ) . append ( \")\\n\" ) ; } else { text . append ( \"?\\n\" ) ; } if ( cleanOffset + OIntegerSerializer . INT_SIZE * 2 <= MAX_PAGE_SIZE_BYTES ) { text . append ( \"\\t\\tIndex:\\t\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( cleanOffset + OIntegerSerializer . INT_SIZE ) ) ) . append ( ' ' ) ; } else { text . append ( \"?\\n\" ) ; } if ( cleanOffset + OIntegerSerializer . INT_SIZE * 3 <= MAX_PAGE_SIZE_BYTES ) { text . append ( \"\\t\\tData Size:\\t\" ) . append ( String . format ( \"%08X\" , getIntValue ( cleanOffset + OIntegerSerializer . INT_SIZE * 2 ) ) ) . append ( ' ' ) ; } else { text . append ( \"?\\n\" ) ; } ++ foundEntries ; } OLogManager . instance ( ) . error ( this , \"%s\" , null , text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Switch to the OrientDb classloader before lookups on ServiceRegistry for implementation of the given Class . Useful under OSGI and generally under applications where jars are loaded by another class loader [CODESPLIT] public static synchronized < T extends Object > Iterator < T > lookupProviderWithOrientClassLoader ( Class < T > clazz ) { return lookupProviderWithOrientClassLoader ( clazz , OClassLoaderHelper . class . getClassLoader ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param unlimitedCap the upper limit on reported memory if JVM reports unlimited memory . [CODESPLIT] public static long getCappedRuntimeMaxMemory ( long unlimitedCap ) { final long jvmMaxMemory = Runtime . getRuntime ( ) . maxMemory ( ) ; return jvmMaxMemory == Long . MAX_VALUE ? unlimitedCap : jvmMaxMemory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the OrientDB cache memory configuration and emits a warning if configuration is invalid . [CODESPLIT] public static void checkCacheMemoryConfiguration ( ) { final long maxHeapSize = Runtime . getRuntime ( ) . maxMemory ( ) ; final long maxCacheSize = getMaxCacheMemorySize ( ) ; final ONative . MemoryLimitResult physicalMemory = ONative . instance ( ) . getMemoryLimit ( false ) ; if ( maxHeapSize != Long . MAX_VALUE && physicalMemory != null && maxHeapSize + maxCacheSize > physicalMemory . memoryLimit ) OLogManager . instance ( ) . warnNoDb ( OMemory . class , \"The sum of the configured JVM maximum heap size (\" + maxHeapSize + \" bytes) \" + \"and the OrientDB maximum cache size (\" + maxCacheSize + \" bytes) is larger than the available physical memory size \" + \"(\" + physicalMemory + \" bytes). That may cause out of memory errors, please tune the configuration up. Use the \" + \"-Xmx JVM option to lower the JVM maximum heap memory size or storage.diskCache.bufferSize OrientDB option to \" + \"lower memory requirements of the cache.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to fix some common cache / memory configuration problems : <ul > <li > Cache size is larger than direct memory size . < / li > <li > Memory chunk size is larger than cache size . < / li > <ul / > [CODESPLIT] public static void fixCommonConfigurationProblems ( ) { long diskCacheSize = OGlobalConfiguration . DISK_CACHE_SIZE . getValueAsLong ( ) ; final int max32BitCacheSize = 512 ; if ( getJavaBitWidth ( ) == 32 && diskCacheSize > max32BitCacheSize ) { OLogManager . instance ( ) . infoNoDb ( OGlobalConfiguration . class , \"32 bit JVM is detected. Lowering disk cache size from %,dMB to %,dMB.\" , diskCacheSize , max32BitCacheSize ) ; OGlobalConfiguration . DISK_CACHE_SIZE . setValue ( max32BitCacheSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a vertex from GraphSON using settings supplied in the constructor . [CODESPLIT] public Vertex vertexFromJson ( final InputStream json ) throws IOException { final JsonParser jp = jsonFactory . createParser ( json ) ; final JsonNode node = jp . readValueAsTree ( ) ; return this . vertexFromJson ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a vertex from GraphSON using settings supplied in the constructor . [CODESPLIT] public Vertex vertexFromJson ( final JsonNode json ) throws IOException { final Map < String , Object > props = readProperties ( json , true , this . hasEmbeddedTypes ) ; final Object vertexId = getTypedValueFromJsonNode ( json . get ( GraphSONTokens . _ID ) ) ; final Vertex v = factory . createVertex ( vertexId ) ; for ( Map . Entry < String , Object > entry : props . entrySet ( ) ) { // if (this.vertexPropertyKeys == null || vertexPropertyKeys.contains(entry.getKey())) { if ( includeKey ( entry . getKey ( ) , vertexPropertyKeys , this . vertexPropertiesRule ) ) { v . setProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an edge from GraphSON using settings supplied in the constructor . [CODESPLIT] public Edge edgeFromJson ( final JSONObject json , final Vertex out , final Vertex in ) throws IOException { return this . edgeFromJson ( json . toString ( ) , out , in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an edge from GraphSON using settings supplied in the constructor . [CODESPLIT] public Edge edgeFromJson ( final String json , final Vertex out , final Vertex in ) throws IOException { final JsonParser jp = jsonFactory . createParser ( json ) ; final JsonNode node = jp . readValueAsTree ( ) ; return this . edgeFromJson ( node , out , in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an edge from GraphSON using settings supplied in the constructor . [CODESPLIT] public Edge edgeFromJson ( final JsonNode json , final Vertex out , final Vertex in ) throws IOException { final Map < String , Object > props = OGraphSONUtility . readProperties ( json , true , this . hasEmbeddedTypes ) ; final Object edgeId = getTypedValueFromJsonNode ( json . get ( GraphSONTokens . _ID ) ) ; final JsonNode nodeLabel = json . get ( GraphSONTokens . _LABEL ) ; // assigned an empty string edge label in cases where one does not exist. this gets around the requirement // that blueprints graphs have a non-null label while ensuring that GraphSON can stay flexible in parsing // partial bits from the JSON. Not sure if there is any gotchas developing out of this. final String label = nodeLabel == null ? EMPTY_STRING : nodeLabel . textValue ( ) ; final Edge e = factory . createEdge ( edgeId , out , in , label ) ; for ( Map . Entry < String , Object > entry : props . entrySet ( ) ) { // if (this.edgePropertyKeys == null || this.edgePropertyKeys.contains(entry.getKey())) { if ( includeKey ( entry . getKey ( ) , edgePropertyKeys , this . edgePropertiesRule ) ) { e . setProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates GraphSON for a single graph element . [CODESPLIT] public JSONObject jsonFromElement ( final Element element ) throws JSONException { final ObjectNode objectNode = this . objectNodeFromElement ( element ) ; try { return new JSONObject ( new JSONTokener ( mapper . writeValueAsString ( objectNode ) ) ) ; } catch ( IOException ioe ) { // repackage this as a JSONException...seems sensible as the caller will only know about // the jettison object not being created throw new JSONException ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates GraphSON for a single graph element . [CODESPLIT] public ObjectNode objectNodeFromElement ( final Element element ) { final boolean isEdge = element instanceof Edge ; final boolean showTypes = mode == GraphSONMode . EXTENDED ; final List < String > propertyKeys = isEdge ? this . edgePropertyKeys : this . vertexPropertyKeys ; final ElementPropertiesRule elementPropertyConfig = isEdge ? this . edgePropertiesRule : this . vertexPropertiesRule ; final ObjectNode jsonElement = createJSONMap ( createPropertyMap ( element , propertyKeys , elementPropertyConfig , normalized ) , propertyKeys , showTypes ) ; if ( ( isEdge && this . includeReservedEdgeId ) || ( ! isEdge && this . includeReservedVertexId ) ) { putObject ( jsonElement , GraphSONTokens . _ID , element . getId ( ) ) ; } // it's important to keep the order of these straight. check Edge first and then Vertex because there // are graph implementations that have Edge extend from Vertex if ( element instanceof Edge ) { final Edge edge = ( Edge ) element ; if ( this . includeReservedEdgeId ) { putObject ( jsonElement , GraphSONTokens . _ID , element . getId ( ) ) ; } if ( this . includeReservedEdgeType ) { jsonElement . put ( GraphSONTokens . _TYPE , GraphSONTokens . EDGE ) ; } if ( this . includeReservedEdgeOutV ) { putObject ( jsonElement , GraphSONTokens . _OUT_V , edge . getVertex ( Direction . OUT ) . getId ( ) ) ; } if ( this . includeReservedEdgeInV ) { putObject ( jsonElement , GraphSONTokens . _IN_V , edge . getVertex ( Direction . IN ) . getId ( ) ) ; } if ( this . includeReservedEdgeLabel ) { jsonElement . put ( GraphSONTokens . _LABEL , edge . getLabel ( ) ) ; } } else if ( element instanceof Vertex ) { if ( this . includeReservedVertexId ) { putObject ( jsonElement , GraphSONTokens . _ID , element . getId ( ) ) ; } if ( this . includeReservedVertexType ) { jsonElement . put ( GraphSONTokens . _TYPE , GraphSONTokens . VERTEX ) ; } } return jsonElement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads an individual Vertex from JSON . The vertex must match the accepted GraphSON format . [CODESPLIT] public static Vertex vertexFromJson ( final JSONObject json , final ElementFactory factory , final GraphSONMode mode , final Set < String > propertyKeys ) throws IOException { final OGraphSONUtility graphson = new OGraphSONUtility ( mode , factory , propertyKeys , null ) ; return graphson . vertexFromJson ( json ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads an individual Edge from JSON . The edge must match the accepted GraphSON format . [CODESPLIT] public static Edge edgeFromJson ( final JSONObject json , final Vertex out , final Vertex in , final ElementFactory factory , final GraphSONMode mode , final Set < String > propertyKeys ) throws IOException { final OGraphSONUtility graphson = new OGraphSONUtility ( mode , factory , null , propertyKeys ) ; return graphson . edgeFromJson ( json , out , in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Jettison JSONObject from a graph element . [CODESPLIT] public static JSONObject jsonFromElement ( final Element element , final Set < String > propertyKeys , final GraphSONMode mode ) throws JSONException { final OGraphSONUtility graphson = element instanceof Edge ? new OGraphSONUtility ( mode , null , null , propertyKeys ) : new OGraphSONUtility ( mode , null , propertyKeys , null ) ; return graphson . jsonFromElement ( element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Jackson ObjectNode from a graph element . [CODESPLIT] public static ObjectNode objectNodeFromElement ( final Element element , final Set < String > propertyKeys , final GraphSONMode mode ) { final OGraphSONUtility graphson = element instanceof Edge ? new OGraphSONUtility ( mode , null , null , propertyKeys ) : new OGraphSONUtility ( mode , null , propertyKeys , null ) ; return graphson . objectNodeFromElement ( element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes import with configuration ; [CODESPLIT] public void executeImport ( ODocument cfg , OServer server ) { OETLJob job = new OETLJob ( cfg , server , new OETLListener ( ) { @ Override public void onEnd ( OETLJob etlJob ) { currentJob = null ; } } ) ; job . validate ( ) ; currentJob = job ; pool . execute ( job ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Status of the Running Jobs [CODESPLIT] public ODocument status ( ) { ODocument status = new ODocument ( ) ; Collection < ODocument > jobs = new ArrayList < ODocument > ( ) ; if ( currentJob != null ) { jobs . add ( currentJob . status ( ) ) ; } status . field ( \"jobs\" , jobs ) ; return status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( OIdentifiable object , ByteBuffer buffer , Object ... hints ) { final ORID r = object . getIdentity ( ) ; buffer . putShort ( ( short ) r . getClusterId ( ) ) ; // Wrong implementation but needed for binary compatibility\r byte [ ] stream = new byte [ OLongSerializer . LONG_SIZE ] ; OLongSerializer . INSTANCE . serialize ( r . getClusterPosition ( ) , stream , 0 ) ; buffer . put ( stream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OIdentifiable deserializeFromByteBufferObject ( ByteBuffer buffer ) { final int clusterId = buffer . getShort ( ) ; final byte [ ] stream = new byte [ OLongSerializer . LONG_SIZE ] ; buffer . get ( stream ) ; // Wrong implementation but needed for binary compatibility\r final long clusterPosition = OLongSerializer . INSTANCE . deserialize ( stream , 0 ) ; return new ORecordId ( clusterId , clusterPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OIdentifiable deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final int clusterId = walChanges . getShortValue ( buffer , offset ) ; // Wrong implementation but needed for binary compatibility\r final long clusterPosition = OLongSerializer . INSTANCE . deserialize ( walChanges . getBinaryValue ( buffer , offset + OShortSerializer . SHORT_SIZE , OLongSerializer . LONG_SIZE ) , 0 ) ; // final long clusterPosition = OLongSerializer.INSTANCE\r // .deserializeFromDirectMemory(pointer, offset + OShortSerializer.SHORT_SIZE);\r return new ORecordId ( clusterId , clusterPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @link Comparator } instance if applicable one exist or <code > null< / code > otherwise . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > Comparator < T > getComparator ( Class < T > clazz ) { boolean useUnsafe = OGlobalConfiguration . MEMORY_USE_UNSAFE . getValueAsBoolean ( ) ; if ( clazz . equals ( byte [ ] . class ) ) { if ( useUnsafe && unsafeWasDetected ) return ( Comparator < T > ) OUnsafeByteArrayComparator . INSTANCE ; return ( Comparator < T > ) OByteArrayComparator . INSTANCE ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the cluster map for current deploy . The keys of the map are node names the values contain names of clusters ( data files ) available on the single node . [CODESPLIT] public Map < String , Set < String > > getActiveClusterMap ( ) { if ( distributedManager . isOffline ( ) || ! distributedManager . isNodeOnline ( distributedManager . getLocalNodeName ( ) , getName ( ) ) || OScenarioThreadLocal . INSTANCE . isRunModeDistributed ( ) ) { return super . getActiveClusterMap ( ) ; } Map < String , Set < String > > result = new HashMap <> ( ) ; ODistributedConfiguration cfg = getDistributedConfiguration ( ) ; for ( String server : distributedManager . getActiveServers ( ) ) { if ( getClustersOnServer ( cfg , server ) . contains ( \"*\" ) ) { //TODO check this!!! result . put ( server , getStorage ( ) . getClusterNames ( ) ) ; } else { result . put ( server , getClustersOnServer ( cfg , server ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the data center map for current deploy . The keys are data center names the values are node names per data center [CODESPLIT] public Map < String , Set < String > > getActiveDataCenterMap ( ) { Map < String , Set < String > > result = new HashMap <> ( ) ; ODistributedConfiguration cfg = getDistributedConfiguration ( ) ; Set < String > servers = cfg . getRegisteredServers ( ) ; for ( String server : servers ) { String dc = cfg . getDataCenterOfServer ( server ) ; Set < String > dcConfig = result . get ( dc ) ; if ( dcConfig == null ) { dcConfig = new HashSet <> ( ) ; result . put ( dc , dcConfig ) ; } dcConfig . add ( server ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param transactionId [CODESPLIT] public boolean commit2pc ( ODistributedRequestId transactionId , boolean local ) { getStorageDistributed ( ) . resetLastValidBackup ( ) ; ODistributedDatabase localDistributedDatabase = getStorageDistributed ( ) . getLocalDistributedDatabase ( ) ; ONewDistributedTxContextImpl txContext = ( ONewDistributedTxContextImpl ) localDistributedDatabase . getTxContext ( transactionId ) ; if ( txContext != null ) { if ( SUCCESS . equals ( txContext . getStatus ( ) ) ) { try { txContext . commit ( this ) ; localDistributedDatabase . popTxContext ( transactionId ) ; OLiveQueryHook . notifyForTxChanges ( this ) ; OLiveQueryHookV2 . notifyForTxChanges ( this ) ; } finally { OLiveQueryHook . removePendingDatabaseOps ( this ) ; OLiveQueryHookV2 . removePendingDatabaseOps ( this ) ; } return true ; } else if ( TIMEDOUT . equals ( txContext . getStatus ( ) ) ) { int nretry = getConfiguration ( ) . getValueAsInteger ( DISTRIBUTED_CONCURRENT_TX_MAX_AUTORETRY ) ; int delay = getConfiguration ( ) . getValueAsInteger ( DISTRIBUTED_CONCURRENT_TX_AUTORETRY_DELAY ) ; for ( int i = 0 ; i < nretry ; i ++ ) { try { if ( i > 0 ) { try { Thread . sleep ( new Random ( ) . nextInt ( delay ) ) ; } catch ( InterruptedException e ) { OException . wrapException ( new OInterruptedException ( e . getMessage ( ) ) , e ) ; } } internalBegin2pc ( txContext , local ) ; txContext . setStatus ( SUCCESS ) ; break ; } catch ( ODistributedRecordLockedException | ODistributedKeyLockedException ex ) { // Just retry } catch ( Exception ex ) { OLogManager . instance ( ) . warn ( ODatabaseDocumentDistributed . this , \"Error beginning timed out transaction: %s \" , ex , transactionId ) ; break ; } } if ( ! SUCCESS . equals ( txContext . getStatus ( ) ) ) { txContext . destroy ( ) ; localDistributedDatabase . popTxContext ( transactionId ) ; Orient . instance ( ) . submit ( ( ) -> { OLogManager . instance ( ) . warn ( ODatabaseDocumentDistributed . this , \"Reached limit of retry for commit tx:%s forcing database re-install\" , transactionId ) ; distributedManager . installDatabase ( false , ODatabaseDocumentDistributed . this . getName ( ) , true , true ) ; } ) ; return true ; } try { txContext . commit ( this ) ; localDistributedDatabase . popTxContext ( transactionId ) ; OLiveQueryHook . notifyForTxChanges ( this ) ; OLiveQueryHookV2 . notifyForTxChanges ( this ) ; return true ; } finally { OLiveQueryHook . removePendingDatabaseOps ( this ) ; OLiveQueryHookV2 . removePendingDatabaseOps ( this ) ; } } else { txContext . destroy ( ) ; localDistributedDatabase . popTxContext ( transactionId ) ; Orient . instance ( ) . submit ( ( ) -> { OLogManager . instance ( ) . warn ( ODatabaseDocumentDistributed . this , \"Reached limit of retry for commit tx:%s forcing database re-install\" , transactionId ) ; distributedManager . installDatabase ( false , ODatabaseDocumentDistributed . this . getName ( ) , true , true ) ; } ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String toCreateIndexDDL ( final String indexName , final String indexType , String engine ) { return \"create index `\" + indexName + \"` \" + indexType + ' ' + \"runtime \" + serializer . getId ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the secret key algorithm portion of the cipher transformation . [CODESPLIT] protected static String separateAlgorithm ( final String cipherTransform ) { String [ ] array = cipherTransform . split ( \"/\" ) ; if ( array . length > 1 ) return array [ 0 ] ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an OSymmetricKey from an OSymmetricKeyConfig interface . [CODESPLIT] public static OSymmetricKey fromConfig ( final OSymmetricKeyConfig keyConfig ) { if ( keyConfig . usesKeyString ( ) ) { return fromString ( keyConfig . getKeyAlgorithm ( ) , keyConfig . getKeyString ( ) ) ; } else if ( keyConfig . usesKeyFile ( ) ) { return fromFile ( keyConfig . getKeyAlgorithm ( ) , keyConfig . getKeyFile ( ) ) ; } else if ( keyConfig . usesKeystore ( ) ) { return fromKeystore ( keyConfig . getKeystoreFile ( ) , keyConfig . getKeystorePassword ( ) , keyConfig . getKeystoreKeyAlias ( ) , keyConfig . getKeystoreKeyPassword ( ) ) ; } else { throw new OSecurityException ( \"OSymmetricKey(OSymmetricKeyConfig) Invalid configuration\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an OSymmetricKey from a file containing a Base64 key . [CODESPLIT] public static OSymmetricKey fromFile ( final String algorithm , final String path ) { String base64Key = null ; try { java . io . FileInputStream fis = null ; try { fis = new java . io . FileInputStream ( OSystemVariableResolver . resolveSystemVariables ( path ) ) ; return fromStream ( algorithm , fis ) ; } finally { if ( fis != null ) fis . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.fromFile() Exception: \" + ex . getMessage ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an OSymmetricKey from an InputStream containing a Base64 key . [CODESPLIT] public static OSymmetricKey fromStream ( final String algorithm , final InputStream is ) { String base64Key = null ; try { base64Key = OIOUtils . readStreamAsString ( is ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.fromStream() Exception: \" + ex . getMessage ( ) ) , ex ) ; } return new OSymmetricKey ( algorithm , base64Key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an OSymmetricKey from a Java JCEKS KeyStore . [CODESPLIT] public static OSymmetricKey fromKeystore ( final String path , final String password , final String keyAlias , final String keyPassword ) { OSymmetricKey sk = null ; try { KeyStore ks = KeyStore . getInstance ( \"JCEKS\" ) ; // JCEKS is required to hold SecretKey entries. java . io . FileInputStream fis = null ; try { fis = new java . io . FileInputStream ( OSystemVariableResolver . resolveSystemVariables ( path ) ) ; return fromKeystore ( fis , password , keyAlias , keyPassword ) ; } finally { if ( fis != null ) fis . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.fromKeystore() Exception: \" + ex . getMessage ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an OSymmetricKey from a Java JCEKS KeyStore . [CODESPLIT] public static OSymmetricKey fromKeystore ( final InputStream is , final String password , final String keyAlias , final String keyPassword ) { OSymmetricKey sk = null ; try { KeyStore ks = KeyStore . getInstance ( \"JCEKS\" ) ; // JCEKS is required to hold SecretKey entries. char [ ] ksPasswdChars = null ; if ( password != null ) ksPasswdChars = password . toCharArray ( ) ; ks . load ( is , ksPasswdChars ) ; // ksPasswdChars may be null. char [ ] ksKeyPasswdChars = null ; if ( keyPassword != null ) ksKeyPasswdChars = keyPassword . toCharArray ( ) ; KeyStore . ProtectionParameter protParam = new KeyStore . PasswordProtection ( ksKeyPasswdChars ) ; // ksKeyPasswdChars may be null. KeyStore . SecretKeyEntry skEntry = ( KeyStore . SecretKeyEntry ) ks . getEntry ( keyAlias , protParam ) ; if ( skEntry == null ) throw new OSecurityException ( \"SecretKeyEntry is null for key alias: \" + keyAlias ) ; SecretKey secretKey = skEntry . getSecretKey ( ) ; sk = new OSymmetricKey ( secretKey ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.fromKeystore() Exception: \" + ex . getMessage ( ) ) , ex ) ; } return sk ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a convenience method that takes a String argument encodes it as Base64 then calls encrypt ( byte [] ) . [CODESPLIT] public String encrypt ( final String value ) { try { return encrypt ( value . getBytes ( \"UTF8\" ) ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.encrypt() Exception: \" + ex . getMessage ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method encrypts an array of bytes . [CODESPLIT] public String encrypt ( final String transform , final byte [ ] bytes ) { String encodedJSON = null ; if ( secretKey == null ) throw new OSecurityException ( \"OSymmetricKey.encrypt() SecretKey is null\" ) ; if ( transform == null ) throw new OSecurityException ( \"OSymmetricKey.encrypt() Cannot determine cipher transformation\" ) ; try { // Throws NoSuchAlgorithmException and NoSuchPaddingException. Cipher cipher = Cipher . getInstance ( transform ) ; // If the cipher transformation requires an initialization vector then init() will create a random one. // (Use cipher.getIV() to retrieve the IV, if it exists.) cipher . init ( Cipher . ENCRYPT_MODE , secretKey ) ; // If the cipher does not use an IV, this will be null. byte [ ] initVector = cipher . getIV ( ) ; //      byte[] initVector = encCipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); byte [ ] encrypted = cipher . doFinal ( bytes ) ; encodedJSON = encodeJSON ( encrypted , initVector ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.encrypt() Exception: \" + ex . getMessage ( ) ) , ex ) ; } return encodedJSON ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method decrypts the Base64 - encoded JSON document using the specified algorithm and cipher transformation . [CODESPLIT] public String decryptAsString ( final String encodedJSON ) { try { byte [ ] decrypted = decrypt ( encodedJSON ) ; return new String ( decrypted , \"UTF8\" ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.decryptAsString() Exception: \" + ex . getMessage ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method decrypts the Base64 - encoded JSON document using the specified algorithm and cipher transformation . [CODESPLIT] public byte [ ] decrypt ( final String encodedJSON ) { byte [ ] result = null ; if ( encodedJSON == null ) throw new OSecurityException ( \"OSymmetricKey.decrypt(String) encodedJSON is null\" ) ; try { byte [ ] decoded = convertFromBase64 ( encodedJSON ) ; if ( decoded == null ) throw new OSecurityException ( \"OSymmetricKey.decrypt(String) encodedJSON could not be decoded\" ) ; String json = new String ( decoded , \"UTF8\" ) ; // Convert the JSON content to an ODocument to make parsing it easier. final ODocument doc = new ODocument ( ) . fromJSON ( json , \"noMap\" ) ; // Set a default in case the JSON document does not contain an \"algorithm\" property. String algorithm = secretKeyAlgorithm ; if ( doc . containsField ( \"algorithm\" ) ) algorithm = doc . field ( \"algorithm\" ) ; // Set a default in case the JSON document does not contain a \"transform\" property. String transform = defaultCipherTransformation ; if ( doc . containsField ( \"transform\" ) ) transform = doc . field ( \"transform\" ) ; String payloadBase64 = doc . field ( \"payload\" ) ; String ivBase64 = doc . field ( \"iv\" ) ; byte [ ] payload = null ; byte [ ] iv = null ; if ( payloadBase64 != null ) payload = convertFromBase64 ( payloadBase64 ) ; if ( ivBase64 != null ) iv = convertFromBase64 ( ivBase64 ) ; // Throws NoSuchAlgorithmException and NoSuchPaddingException. Cipher cipher = Cipher . getInstance ( transform ) ; if ( iv != null ) cipher . init ( Cipher . DECRYPT_MODE , secretKey , new IvParameterSpec ( iv ) ) ; else cipher . init ( Cipher . DECRYPT_MODE , secretKey ) ; result = cipher . doFinal ( payload ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.decrypt(String) Exception: \" + ex . getMessage ( ) ) , ex ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves the internal SecretKey to the specified OutputStream as a Base64 String . [CODESPLIT] public void saveToStream ( final OutputStream os ) { if ( os == null ) throw new OSecurityException ( \"OSymmetricKey.saveToStream() OutputStream is null\" ) ; try { final OutputStreamWriter osw = new OutputStreamWriter ( os ) ; try { final BufferedWriter writer = new BufferedWriter ( osw ) ; try { writer . write ( getBase64Key ( ) ) ; } finally { writer . close ( ) ; } } finally { os . close ( ) ; } } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.saveToStream() Exception: \" + ex . getMessage ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves the internal SecretKey as a KeyStore . [CODESPLIT] public void saveToKeystore ( final OutputStream os , final String ksPasswd , final String keyAlias , final String keyPasswd ) { if ( os == null ) throw new OSecurityException ( \"OSymmetricKey.saveToKeystore() OutputStream is null\" ) ; if ( ksPasswd == null ) throw new OSecurityException ( \"OSymmetricKey.saveToKeystore() Keystore Password is required\" ) ; if ( keyAlias == null ) throw new OSecurityException ( \"OSymmetricKey.saveToKeystore() Key Alias is required\" ) ; if ( keyPasswd == null ) throw new OSecurityException ( \"OSymmetricKey.saveToKeystore() Key Password is required\" ) ; try { KeyStore ks = KeyStore . getInstance ( \"JCEKS\" ) ; char [ ] ksPasswdCA = ksPasswd . toCharArray ( ) ; char [ ] keyPasswdCA = keyPasswd . toCharArray ( ) ; // Create a new KeyStore by passing null. ks . load ( null , ksPasswdCA ) ; KeyStore . ProtectionParameter protParam = new KeyStore . PasswordProtection ( keyPasswdCA ) ; KeyStore . SecretKeyEntry skEntry = new KeyStore . SecretKeyEntry ( secretKey ) ; ks . setEntry ( keyAlias , skEntry , protParam ) ; // Save the KeyStore ks . store ( os , ksPasswdCA ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKey.saveToKeystore() Exception: \" + ex . getMessage ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( UUID object , ByteBuffer buffer , Object ... hints ) { buffer . putLong ( object . getMostSignificantBits ( ) ) ; buffer . putLong ( object . getLeastSignificantBits ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public UUID deserializeFromByteBufferObject ( ByteBuffer buffer ) { final long mostSignificantBits = buffer . getLong ( ) ; final long leastSignificantBits = buffer . getLong ( ) ; return new UUID ( mostSignificantBits , leastSignificantBits ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public UUID deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final long mostSignificantBits = walChanges . getLongValue ( buffer , offset ) ; final long leastSignificantBits = walChanges . getLongValue ( buffer , offset + OLongSerializer . LONG_SIZE ) ; return new UUID ( mostSignificantBits , leastSignificantBits ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the inherited context avoiding to copy all the values every time . [CODESPLIT] public OCommandContext setChild ( final OCommandContext iContext ) { if ( iContext == null ) { if ( child != null ) { // REMOVE IT\r child . setParent ( null ) ; child = null ; } } else if ( child != iContext ) { // ADD IT\r child = iContext ; iContext . setParent ( this ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds an item to the unique result set [CODESPLIT] public synchronized boolean addToUniqueResult ( Object o ) { Object toAdd = o ; if ( o instanceof ODocument && ( ( ODocument ) o ) . getIdentity ( ) . isNew ( ) ) { toAdd = new ODocumentEqualityWrapper ( ( ODocument ) o ) ; } return this . uniqueResult . add ( toAdd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( BigDecimal object , ByteBuffer buffer , Object ... hints ) { buffer . putInt ( object . scale ( ) ) ; OBinaryTypeSerializer . INSTANCE . serializeInByteBufferObject ( object . unscaledValue ( ) . toByteArray ( ) , buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BigDecimal deserializeFromByteBufferObject ( ByteBuffer buffer ) { final int scale = buffer . getInt ( ) ; final byte [ ] unscaledValue = OBinaryTypeSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer ) ; return new BigDecimal ( new BigInteger ( unscaledValue ) , scale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer ) { buffer . position ( buffer . position ( ) + OIntegerSerializer . INT_SIZE ) ; return OIntegerSerializer . INT_SIZE + OBinaryTypeSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BigDecimal deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final int scale = walChanges . getIntValue ( buffer , offset ) ; offset += OIntegerSerializer . INT_SIZE ; final byte [ ] unscaledValue = OBinaryTypeSerializer . INSTANCE . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; return new BigDecimal ( new BigInteger ( unscaledValue ) , scale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return OIntegerSerializer . INT_SIZE + OBinaryTypeSerializer . INSTANCE . getObjectSizeInByteBuffer ( buffer , walChanges , offset + OIntegerSerializer . INT_SIZE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OBJECT OR MAP . CHECK THE TYPE ATTRIBUTE TO KNOW IT . [CODESPLIT] private Object getValueAsObjectOrMap ( ODocument iRecord , String iFieldValue , OType iType , OType iLinkedType , Map < String , Character > iFieldTypes , boolean iNoMap , String iOptions ) { final String [ ] fields = OStringParser . getWords ( iFieldValue . substring ( 1 , iFieldValue . length ( ) - 1 ) , \":,\" , true ) ; if ( fields == null || fields . length == 0 ) if ( iNoMap ) { ODocument res = new ODocument ( ) ; ODocumentInternal . addOwner ( res , iRecord ) ; return res ; } else return new HashMap < String , Object > ( ) ; if ( iNoMap || hasTypeField ( fields ) ) { return getValueAsRecord ( iRecord , iFieldValue , iType , iOptions , fields ) ; } else { return getValueAsMap ( iRecord , iFieldValue , iLinkedType , iFieldTypes , false , iOptions , fields ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "null is returned in all other cases and means authentication was unsuccessful . [CODESPLIT] protected String authenticate ( final String username , final String password , final String iDatabaseName ) throws IOException { ODatabaseDocument db = null ; String userRid = null ; try { db = ( ODatabaseDocument ) server . openDatabase ( iDatabaseName , username , password ) ; userRid = ( db . getUser ( ) == null ? \"<server user>\" : db . getUser ( ) . getDocument ( ) . getIdentity ( ) . toString ( ) ) ; } catch ( OSecurityAccessException e ) { // WRONG USER/PASSWD } catch ( OLockException e ) { OLogManager . instance ( ) . error ( this , \"Cannot access to the database '\" + iDatabaseName + \"'\" , e ) ; } finally { if ( db != null ) { db . close ( ) ; } } return userRid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the value crossing the map with the dotted notation [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Object getMapEntry ( final Map < String , ? > iMap , final Object iKey ) { if ( iMap == null || iKey == null ) return null ; if ( iKey instanceof String ) { String iName = ( String ) iKey ; int pos = iName . indexOf ( ' ' ) ; if ( pos > - 1 ) iName = iName . substring ( 0 , pos ) ; final Object value = iMap . get ( iName ) ; if ( value == null ) return null ; if ( pos > - 1 ) { final String restFieldName = iName . substring ( pos + 1 ) ; if ( value instanceof ODocument ) return getFieldValue ( value , restFieldName ) ; else if ( value instanceof Map < ? , ? > ) return getMapEntry ( ( Map < String , ? > ) value , restFieldName ) ; } return value ; } else return iMap . get ( iKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a deep comparison field by field to check if the passed ODocument instance is identical as identity and content to the current one . Instead equals () just checks if the RID are the same . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static boolean hasSameContentOf ( final ODocument iCurrent , final ODatabaseDocumentInternal iMyDb , final ODocument iOther , final ODatabaseDocumentInternal iOtherDb , RIDMapper ridMapper ) { return hasSameContentOf ( iCurrent , iMyDb , iOther , iOtherDb , ridMapper , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a deep comparison field by field to check if the passed ODocument instance is identical in the content to the current one . Instead equals () just checks if the RID are the same . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static boolean hasSameContentOf ( final ODocument iCurrent , final ODatabaseDocumentInternal iMyDb , final ODocument iOther , final ODatabaseDocumentInternal iOtherDb , RIDMapper ridMapper , final boolean iCheckAlsoIdentity ) { if ( iOther == null ) return false ; if ( iCheckAlsoIdentity && iCurrent . getIdentity ( ) . isValid ( ) && ! iCurrent . getIdentity ( ) . equals ( iOther . getIdentity ( ) ) ) return false ; if ( iMyDb != null ) makeDbCall ( iMyDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { if ( iCurrent . getInternalStatus ( ) == STATUS . NOT_LOADED ) iCurrent . reload ( ) ; return null ; } } ) ; if ( iOtherDb != null ) makeDbCall ( iOtherDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { if ( iOther . getInternalStatus ( ) == STATUS . NOT_LOADED ) iOther . reload ( ) ; return null ; } } ) ; if ( iMyDb != null ) makeDbCall ( iMyDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { iCurrent . checkForFields ( ) ; return null ; } } ) ; else iCurrent . checkForFields ( ) ; if ( iOtherDb != null ) makeDbCall ( iOtherDb , new ODbRelatedCall < Object > ( ) { public Object call ( ODatabaseDocumentInternal database ) { iOther . checkForFields ( ) ; return null ; } } ) ; else iOther . checkForFields ( ) ; if ( iCurrent . fields ( ) != iOther . fields ( ) ) return false ; // CHECK FIELD-BY-FIELD\r Object myFieldValue ; Object otherFieldValue ; for ( Entry < String , Object > f : iCurrent ) { myFieldValue = f . getValue ( ) ; otherFieldValue = iOther . _fields . get ( f . getKey ( ) ) . value ; if ( myFieldValue == otherFieldValue ) continue ; // CHECK FOR NULLS\r if ( myFieldValue == null ) { if ( otherFieldValue != null ) return false ; } else if ( otherFieldValue == null ) return false ; if ( myFieldValue != null ) if ( myFieldValue instanceof Set && otherFieldValue instanceof Set ) { if ( ! compareSets ( iMyDb , ( Set < ? > ) myFieldValue , iOtherDb , ( Set < ? > ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof Collection && otherFieldValue instanceof Collection ) { if ( ! compareCollections ( iMyDb , ( Collection < ? > ) myFieldValue , iOtherDb , ( Collection < ? > ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof ORidBag && otherFieldValue instanceof ORidBag ) { if ( ! compareBags ( iMyDb , ( ORidBag ) myFieldValue , iOtherDb , ( ORidBag ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof Map && otherFieldValue instanceof Map ) { if ( ! compareMaps ( iMyDb , ( Map < Object , Object > ) myFieldValue , iOtherDb , ( Map < Object , Object > ) otherFieldValue , ridMapper ) ) return false ; } else if ( myFieldValue instanceof ODocument && otherFieldValue instanceof ODocument ) { if ( ! hasSameContentOf ( ( ODocument ) myFieldValue , iMyDb , ( ODocument ) otherFieldValue , iOtherDb , ridMapper ) ) return false ; } else { if ( ! compareScalarValues ( myFieldValue , iMyDb , otherFieldValue , iOtherDb , ridMapper ) ) return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the remote network address in the format <ip > : <port > . [CODESPLIT] public String getRemoteAddress ( ) { Socket socket = null ; if ( getProtocol ( ) != null ) { socket = getProtocol ( ) . getChannel ( ) . socket ; } else { for ( ONetworkProtocol protocol : this . protocols ) { socket = protocol . getChannel ( ) . socket ; if ( socket != null ) break ; } } if ( socket != null ) { final InetSocketAddress remoteAddress = ( InetSocketAddress ) socket . getRemoteSocketAddress ( ) ; return remoteAddress . getAddress ( ) . getHostAddress ( ) + \":\" + remoteAddress . getPort ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the record to use for the operation . [CODESPLIT] protected ORecord getRecord ( ) { final ORecord record ; if ( reusedRecord != null ) { // REUSE THE SAME RECORD AFTER HAVING RESETTED IT\r record = reusedRecord ; record . reset ( ) ; } else record = null ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the current record and increment the counter if the record was found . [CODESPLIT] protected ORecord readCurrentRecord ( ORecord iRecord , final int iMovement ) { if ( limit > - 1 && browsedRecords >= limit ) // LIMIT REACHED\r return null ; do { final boolean moveResult ; switch ( iMovement ) { case 1 : moveResult = nextPosition ( ) ; break ; case - 1 : moveResult = prevPosition ( ) ; break ; case 0 : moveResult = checkCurrentPosition ( ) ; break ; default : throw new IllegalStateException ( \"Invalid movement value : \" + iMovement ) ; } if ( ! moveResult ) return null ; try { if ( iRecord != null ) { ORecordInternal . setIdentity ( iRecord , new ORecordId ( current . getClusterId ( ) , current . getClusterPosition ( ) ) ) ; iRecord = database . load ( iRecord , fetchPlan , false ) ; } else iRecord = database . load ( current , fetchPlan , false ) ; } catch ( ODatabaseException e ) { if ( Thread . interrupted ( ) || database . isClosed ( ) ) // THREAD INTERRUPTED: RETURN\r throw e ; if ( e . getCause ( ) instanceof OSecurityException ) throw e ; brokenRIDs . add ( current . copy ( ) ) ; OLogManager . instance ( ) . error ( this , \"Error on fetching record during browsing. The record has been skipped\" , e ) ; } if ( iRecord != null ) { browsedRecords ++ ; return iRecord ; } } while ( iMovement != 0 ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deleted records are written in output stream first then created / updated records . All records are sorted by record id . <p > Each record in output stream is written using following format : <ol > <li > Record s cluster id - 4 bytes< / li > <li > Record s cluster position - 8 bytes< / li > <li > Delete flag 1 if record is deleted - 1 byte< / li > <li > Record version only if record is not deleted - 4 bytes< / li > <li > Record type only if record is not deleted - 1 byte< / li > <li > Length of binary presentation of record only if record is not deleted - 4 bytes< / li > <li > Binary presentation of the record only if record is not deleted - length of content is provided in above entity< / li > < / ol > [CODESPLIT] public void importDelta ( final OServer serverInstance , final String databaseName , final FileInputStream in , final String iNode ) throws IOException { final String nodeName = serverInstance . getDistributedManager ( ) . getLocalNodeName ( ) ; final ODatabaseDocumentInternal db = serverInstance . openDatabase ( databaseName ) ; try { OScenarioThreadLocal . executeAsDistributed ( new Callable < Object > ( ) { @ Override public Object call ( ) throws Exception { db . activateOnCurrentThread ( ) ; long totalRecords = 0 ; long totalCreated = 0 ; long totalUpdated = 0 ; long totalDeleted = 0 ; long totalHoles = 0 ; long totalSkipped = 0 ; ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , \"Started import of delta for database '\" + db . getName ( ) + \"'\" ) ; long lastLap = System . currentTimeMillis ( ) ; // final GZIPInputStream gzipInput = new GZIPInputStream(in); try { final DataInputStream input = new DataInputStream ( in ) ; try { final long records = input . readLong ( ) ; for ( long i = 0 ; i < records ; ++ i ) { final int clusterId = input . readInt ( ) ; final long clusterPos = input . readLong ( ) ; final boolean deleted = input . readBoolean ( ) ; final ORecordId rid = new ORecordId ( clusterId , clusterPos ) ; totalRecords ++ ; final OPaginatedCluster cluster = ( OPaginatedCluster ) db . getStorage ( ) . getUnderlying ( ) . getClusterById ( rid . getClusterId ( ) ) ; final OPaginatedCluster . RECORD_STATUS recordStatus = cluster . getRecordStatus ( rid . getClusterPosition ( ) ) ; ORecord newRecord = null ; if ( deleted ) { ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , \"DELTA <- deleting %s\" , rid ) ; switch ( recordStatus ) { case REMOVED : // SKIP IT totalSkipped ++ ; continue ; case ALLOCATED : case PRESENT : // DELETE IT db . delete ( rid ) ; break ; case NOT_EXISTENT : totalSkipped ++ ; break ; } totalDeleted ++ ; } else { final int recordVersion = input . readInt ( ) ; final int recordType = input . readByte ( ) ; final int recordSize = input . readInt ( ) ; final byte [ ] recordContent = new byte [ recordSize ] ; input . read ( recordContent ) ; switch ( recordStatus ) { case REMOVED : // SKIP IT totalSkipped ++ ; continue ; case ALLOCATED : case PRESENT : // UPDATE IT newRecord = Orient . instance ( ) . getRecordFactoryManager ( ) . newInstance ( ( byte ) recordType , rid . getClusterId ( ) , null ) ; ORecordInternal . fill ( newRecord , rid , ORecordVersionHelper . setRollbackMode ( recordVersion ) , recordContent , true ) ; final ORecord loadedRecord = rid . getRecord ( ) ; if ( loadedRecord instanceof ODocument ) { // APPLY CHANGES FIELD BY FIELD TO MARK DIRTY FIELDS FOR INDEXES/HOOKS ODocument loadedDocument = ( ODocument ) loadedRecord ; loadedDocument . merge ( ( ODocument ) newRecord , false , false ) ; ORecordInternal . setVersion ( loadedRecord , ORecordVersionHelper . setRollbackMode ( recordVersion ) ) ; loadedDocument . setDirty ( ) ; newRecord = loadedDocument ; } // SAVE THE UPDATE RECORD newRecord . save ( ) ; ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , \"DELTA <- updating rid=%s type=%d size=%d v=%d content=%s\" , rid , recordType , recordSize , recordVersion , newRecord ) ; totalUpdated ++ ; break ; case NOT_EXISTENT : // CREATE AND DELETE RECORD IF NEEDED do { newRecord = Orient . instance ( ) . getRecordFactoryManager ( ) . newInstance ( ( byte ) recordType , rid . getClusterId ( ) , null ) ; ORecordInternal . fill ( newRecord , new ORecordId ( rid . getClusterId ( ) , - 1 ) , recordVersion , recordContent , true ) ; try { newRecord . save ( ) ; } catch ( ORecordNotFoundException e ) { ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , \"DELTA <- error on saving record (not found) rid=%s type=%d size=%d v=%d content=%s\" , rid , recordType , recordSize , recordVersion , newRecord ) ; } catch ( ORecordDuplicatedException e ) { ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , \"DELTA <- error on saving record (duplicated %s) rid=%s type=%d size=%d v=%d content=%s\" , e . getRid ( ) , rid , recordType , recordSize , recordVersion , newRecord ) ; // throw OException.wrapException( // new ODistributedDatabaseDeltaSyncException(\"Error on delta sync: found duplicated record \" + rid), e); final ORecord duplicatedRecord = db . load ( e . getRid ( ) , null , true ) ; if ( duplicatedRecord == null ) { // RECORD REMOVED: THE INDEX IS DIRTY, FIX THE DIRTY INDEX final ODocument doc = ( ODocument ) newRecord ; final OIndex < ? > index = db . getMetadata ( ) . getIndexManager ( ) . getIndex ( e . getIndexName ( ) ) ; final List < String > fields = index . getDefinition ( ) . getFields ( ) ; final List < Object > values = new ArrayList < Object > ( fields . size ( ) ) ; for ( String f : fields ) { values . add ( doc . field ( f ) ) ; } final Object keyValue = index . getDefinition ( ) . createValue ( values ) ; index . remove ( keyValue , e . getRid ( ) ) ; // RESAVE THE RECORD newRecord . save ( ) ; } else break ; } if ( newRecord . getIdentity ( ) . getClusterPosition ( ) < clusterPos ) { // DELETE THE RECORD TO CREATE A HOLE ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , \"DELTA <- creating hole rid=%s\" , newRecord . getIdentity ( ) ) ; newRecord . delete ( ) ; totalHoles ++ ; } } while ( newRecord . getIdentity ( ) . getClusterPosition ( ) < clusterPos ) ; ODistributedServerLog . debug ( this , nodeName , iNode , DIRECTION . IN , \"DELTA <- creating rid=%s type=%d size=%d v=%d content=%s\" , rid , recordType , recordSize , recordVersion , newRecord ) ; totalCreated ++ ; break ; } if ( newRecord . getIdentity ( ) . isPersistent ( ) && ! newRecord . getIdentity ( ) . equals ( rid ) ) throw new ODistributedDatabaseDeltaSyncException ( \"Error on synchronization of records, rids are different: saved \" + newRecord . getIdentity ( ) + \", but it should be \" + rid ) ; } final long now = System . currentTimeMillis ( ) ; if ( now - lastLap > 2000 ) { // DUMP STATS EVERY SECOND ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , \"- %,d total entries: %,d created, %,d updated, %,d deleted, %,d holes, %,d skipped...\" , totalRecords , totalCreated , totalUpdated , totalDeleted , totalHoles , totalSkipped ) ; lastLap = now ; } } db . getMetadata ( ) . reload ( ) ; } finally { input . close ( ) ; } } catch ( Exception e ) { ODistributedServerLog . error ( this , nodeName , iNode , DIRECTION . IN , \"Error on installing database delta '%s' on local server\" , e , db . getName ( ) ) ; throw OException . wrapException ( new ODistributedException ( \"Error on installing database delta '\" + db . getName ( ) + \"' on local server\" ) , e ) ; } finally { // gzipInput.close(); } ODistributedServerLog . info ( this , nodeName , iNode , DIRECTION . IN , \"Installed database delta for '%s'. %d total entries: %d created, %d updated, %d deleted, %d holes, %,d skipped\" , db . getName ( ) , totalRecords , totalCreated , totalUpdated , totalDeleted , totalHoles , totalSkipped ) ; return null ; } } ) ; db . activateOnCurrentThread ( ) ; } catch ( Exception e ) { // FORCE FULL DATABASE SYNC ODistributedServerLog . error ( this , nodeName , iNode , DIRECTION . IN , \"Error while applying changes of database delta sync on '%s': forcing full database sync...\" , e , db . getName ( ) ) ; throw OException . wrapException ( new ODistributedDatabaseDeltaSyncException ( \"Error while applying changes of database delta sync on '\" + db . getName ( ) + \"': forcing full database sync...\" ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtains from https : // github . com / enderceylan / CS - 314 -- Data - Structures / blob / master / HW10 - Graph . java [CODESPLIT] public double gcdist ( double lata , double longa , double latb , double longb ) { double midlat , psi , dist ; midlat = 0.5 * ( lata + latb ) ; psi = 0.0174532925 * Math . sqrt ( Math . pow ( lata - latb , 2 ) + Math . pow ( ( longa - longb ) * Math . cos ( 0.0174532925 * midlat ) , 2 ) ) ; dist = 6372.640112 * psi ; return dist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtains from http : // theory . stanford . edu / ~amitp / GameProgramming / Heuristics . html [CODESPLIT] protected double getSimpleHeuristicCost ( double x , double g , double dFactor ) { double dx = Math . abs ( x - g ) ; return dFactor * ( dx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtains from http : // theory . stanford . edu / ~amitp / GameProgramming / Heuristics . html [CODESPLIT] protected double getManhatanHeuristicCost ( double x , double y , double gx , double gy , double dFactor ) { double dx = Math . abs ( x - gx ) ; double dy = Math . abs ( y - gy ) ; return dFactor * ( dx + dy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtains from http : // theory . stanford . edu / ~amitp / GameProgramming / Heuristics . html [CODESPLIT] protected double getDiagonalHeuristicCost ( double x , double y , double gx , double gy , double dFactor ) { double dx = Math . abs ( x - gx ) ; double dy = Math . abs ( y - gy ) ; double h_diagonal = Math . min ( dx , dy ) ; double h_straight = dx + dy ; return ( dFactor * 2 ) * h_diagonal + dFactor * ( h_straight - 2 * h_diagonal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtains from http : // theory . stanford . edu / ~amitp / GameProgramming / Heuristics . html [CODESPLIT] protected double getEuclideanHeuristicCost ( double x , double y , double gx , double gy , double dFactor ) { double dx = Math . abs ( x - gx ) ; double dy = Math . abs ( y - gy ) ; return ( dFactor * Math . sqrt ( Math . pow ( dx , 2 ) + Math . pow ( dy , 2 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtains from http : // theory . stanford . edu / ~amitp / GameProgramming / Heuristics . html [CODESPLIT] protected double getTieBreakingHeuristicCost ( double x , double y , double sx , double sy , double gx , double gy , double heuristic ) { double dx1 = x - gx ; double dy1 = y - gy ; double dx2 = sx - gx ; double dy2 = sy - gy ; double cross = Math . abs ( dx1 * dy2 - dx2 * dy1 ) ; heuristic += ( cross * 0.0001 ) ; return heuristic ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets transactional graph with the database from pool if pool is configured . Otherwise creates a graph with new db instance . The Graph instance inherits the factory s configuration . [CODESPLIT] public OrientGraph getTx ( ) { final OrientGraph g ; if ( pool == null ) { g = ( OrientGraph ) getTxGraphImplFactory ( ) . getGraph ( getDatabase ( ) , user , password , settings ) ; } else { // USE THE POOL g = ( OrientGraph ) getTxGraphImplFactory ( ) . getGraph ( pool , settings ) ; } initGraph ( g ) ; return g ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets non transactional graph with the database from pool if pool is configured . Otherwise creates a graph with new db instance . The Graph instance inherits the factory s configuration . [CODESPLIT] public OrientGraphNoTx getNoTx ( ) { final OrientGraphNoTx g ; if ( pool == null ) { g = ( OrientGraphNoTx ) getNoTxGraphImplFactory ( ) . getGraph ( getDatabase ( ) , user , password , settings ) ; } else { // USE THE POOL g = ( OrientGraphNoTx ) getNoTxGraphImplFactory ( ) . getGraph ( pool , settings ) ; } initGraph ( g ) ; return g ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gives new connection to database . If current factory configured to use pool ( see { @link #setupPool ( int int ) } method ) retrieves connection from pool . Otherwise creates new connection each time . [CODESPLIT] public ODatabaseDocumentTx getDatabase ( final boolean iCreate , final boolean iOpen ) { if ( pool != null ) return pool . acquire ( ) ; final ODatabaseDocument db = new ODatabaseDocumentTx ( url ) ; if ( properties != null ) { properties . entrySet ( ) . forEach ( e -> db . setProperty ( e . getKey ( ) , e . getValue ( ) ) ) ; } if ( ! db . getURL ( ) . startsWith ( \"remote:\" ) && ! db . exists ( ) ) { if ( iCreate ) db . create ( ) ; else if ( iOpen ) throw new ODatabaseException ( \"Database '\" + url + \"' not found\" ) ; } else if ( iOpen ) db . open ( user , password ) ; return ( ODatabaseDocumentTx ) db ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the database with path given to the factory exists . <p > this api can be used only in embedded mode and has no need of authentication . [CODESPLIT] public boolean exists ( ) { final ODatabaseDocument db = getDatabase ( false , false ) ; try { return db . exists ( ) ; } finally { db . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setting up the factory to use database pool instead of creation a new instance of database connection each time . [CODESPLIT] public OrientGraphFactory setupPool ( final int iMin , final int iMax ) { if ( pool != null ) { pool . close ( ) ; } pool = new OPartitionedDatabasePool ( url , user , password , 8 , iMax ) . setAutoCreate ( true ) ; properties . entrySet ( ) . forEach ( p -> pool . setProperty ( p . getKey ( ) , p . getValue ( ) ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the property value . [CODESPLIT] public Object getProperty ( final String iName ) { return properties . get ( iName . toLowerCase ( Locale . ENGLISH ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes a transaction . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) @ Override public void stopTransaction ( final Conclusion conclusion ) { makeActive ( ) ; if ( getDatabase ( ) . isClosed ( ) || getDatabase ( ) . getTransaction ( ) instanceof OTransactionNoTx || getDatabase ( ) . getTransaction ( ) . getStatus ( ) != TXSTATUS . BEGUN ) return ; if ( Conclusion . SUCCESS == conclusion ) commit ( ) ; else rollback ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Root productions . [CODESPLIT] final public OStatement parse ( ) throws ParseException { /*@bgen(jjtree) parse */ Oparse jjtn000 = new Oparse ( JJTPARSE ) ; boolean jjtc000 = true ; jjtree . openNodeScope ( jjtn000 ) ; jjtn000 . jjtSetFirstToken ( getToken ( 1 ) ) ; OStatement result ; try { result = Statement ( ) ; jj_consume_token ( 0 ) ; jjtree . closeNodeScope ( jjtn000 , true ) ; jjtc000 = false ; jjtn000 . jjtSetLastToken ( getToken ( 0 ) ) ; { if ( true ) return result ; } } catch ( Throwable jjte000 ) { if ( jjtc000 ) { jjtree . clearNodeScope ( jjtn000 ) ; jjtc000 = false ; } else { jjtree . popNode ( ) ; } if ( jjte000 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte000 ; } } if ( jjte000 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte000 ; } } { if ( true ) throw ( Error ) jjte000 ; } } finally { if ( jjtc000 ) { jjtree . closeNodeScope ( jjtn000 , true ) ; jjtn000 . jjtSetLastToken ( getToken ( 0 ) ) ; } } throw new Error ( \"Missing return statement in function\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the next Token . [CODESPLIT] final public Token getNextToken ( ) { if ( token . next != null ) token = token . next ; else token = token . next = token_source . getNextToken ( ) ; jj_ntk = - 1 ; jj_gen ++ ; return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the specific Token . [CODESPLIT] final public Token getToken ( int index ) { Token t = token ; for ( int i = 0 ; i < index ; i ++ ) { if ( t . next != null ) t = t . next ; else t = t . next = token_source . getNextToken ( ) ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate ParseException . [CODESPLIT] public ParseException generateParseException ( ) { jj_expentries . clear ( ) ; boolean [ ] la1tokens = new boolean [ 279 ] ; if ( jj_kind >= 0 ) { la1tokens [ jj_kind ] = true ; jj_kind = - 1 ; } for ( int i = 0 ; i < 424 ; i ++ ) { if ( jj_la1 [ i ] == jj_gen ) { for ( int j = 0 ; j < 32 ; j ++ ) { if ( ( jj_la1_0 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ j ] = true ; } if ( ( jj_la1_1 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 32 + j ] = true ; } if ( ( jj_la1_2 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 64 + j ] = true ; } if ( ( jj_la1_3 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 96 + j ] = true ; } if ( ( jj_la1_4 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 128 + j ] = true ; } if ( ( jj_la1_5 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 160 + j ] = true ; } if ( ( jj_la1_6 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 192 + j ] = true ; } if ( ( jj_la1_7 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 224 + j ] = true ; } if ( ( jj_la1_8 [ i ] & ( 1 << j ) ) != 0 ) { la1tokens [ 256 + j ] = true ; } } } } for ( int i = 0 ; i < 279 ; i ++ ) { if ( la1tokens [ i ] ) { jj_expentry = new int [ 1 ] ; jj_expentry [ 0 ] = i ; jj_expentries . add ( jj_expentry ) ; } } jj_endpos = 0 ; jj_rescan_token ( ) ; jj_add_error_token ( 0 , 0 ) ; int [ ] [ ] exptokseq = new int [ jj_expentries . size ( ) ] [  ] ; for ( int i = 0 ; i < jj_expentries . size ( ) ; i ++ ) { exptokseq [ i ] = jj_expentries . get ( i ) ; } return new ParseException ( token , exptokseq , tokenImage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) Returns the field name used for the relationship . [CODESPLIT] public static String getConnectionFieldName ( final Direction iDirection , final String iClassName , final boolean useVertexFieldsForEdgeLabels ) { if ( iDirection == null || iDirection == Direction . BOTH ) throw new IllegalArgumentException ( \"Direction not valid\" ) ; if ( useVertexFieldsForEdgeLabels ) { // PREFIX \"out_\" or \"in_\" TO THE FIELD NAME final String prefix = iDirection == Direction . OUT ? CONNECTION_OUT_PREFIX : CONNECTION_IN_PREFIX ; if ( iClassName == null || iClassName . isEmpty ( ) || iClassName . equals ( OrientEdgeType . CLASS_NAME ) ) return prefix ; return prefix + iClassName ; } else // \"out\" or \"in\" return iDirection == Direction . OUT ? OrientBaseGraph . CONNECTION_OUT : OrientBaseGraph . CONNECTION_IN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) [CODESPLIT] public static String getInverseConnectionFieldName ( final String iFieldName , final boolean useVertexFieldsForEdgeLabels ) { if ( useVertexFieldsForEdgeLabels ) { if ( iFieldName . startsWith ( CONNECTION_OUT_PREFIX ) ) { if ( iFieldName . length ( ) == CONNECTION_OUT_PREFIX . length ( ) ) // \"OUT\" CASE return CONNECTION_IN_PREFIX ; return CONNECTION_IN_PREFIX + iFieldName . substring ( CONNECTION_OUT_PREFIX . length ( ) ) ; } else if ( iFieldName . startsWith ( CONNECTION_IN_PREFIX ) ) { if ( iFieldName . length ( ) == CONNECTION_IN_PREFIX . length ( ) ) // \"IN\" CASE return CONNECTION_OUT_PREFIX ; return CONNECTION_OUT_PREFIX + iFieldName . substring ( CONNECTION_IN_PREFIX . length ( ) ) ; } else throw new IllegalArgumentException ( \"Cannot find reverse connection name for field \" + iFieldName ) ; } if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_OUT ) ) return OrientBaseGraph . CONNECTION_IN ; else if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_IN ) ) return OrientBaseGraph . CONNECTION_OUT ; throw new IllegalArgumentException ( \"Cannot find reverse connection name for field \" + iFieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) [CODESPLIT] public static void replaceLinks ( final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove , final OIdentifiable iNewVertex ) { if ( iVertex == null ) return ; final Object fieldValue = iVertexToRemove != null ? iVertex . field ( iFieldName ) : iVertex . removeField ( iFieldName ) ; if ( fieldValue == null ) return ; if ( fieldValue instanceof OIdentifiable ) { // SINGLE RECORD if ( iVertexToRemove != null ) { if ( ! fieldValue . equals ( iVertexToRemove ) ) { return ; } iVertex . field ( iFieldName , iNewVertex ) ; } } else if ( fieldValue instanceof ORidBag ) { // COLLECTION OF RECORDS: REMOVE THE ENTRY final ORidBag bag = ( ORidBag ) fieldValue ; boolean found = false ; final Iterator < OIdentifiable > it = bag . rawIterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . equals ( iVertexToRemove ) ) { // REMOVE THE OLD ENTRY found = true ; it . remove ( ) ; } } if ( found ) // ADD THE NEW ONE bag . add ( iNewVertex ) ; } else if ( fieldValue instanceof Collection ) { final Collection col = ( Collection ) fieldValue ; if ( col . remove ( iVertexToRemove ) ) col . add ( iNewVertex ) ; } iVertex . save ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) [CODESPLIT] protected static OrientEdge getEdge ( final OrientBaseGraph graph , final ODocument doc , String fieldName , final OPair < Direction , String > connection , final Object fieldValue , final OIdentifiable iTargetVertex , final String [ ] iLabels ) { final OrientEdge toAdd ; final ODocument fieldRecord = ( ( OIdentifiable ) fieldValue ) . getRecord ( ) ; if ( fieldRecord == null ) return null ; OClass klass = ODocumentInternal . getImmutableSchemaClass ( fieldRecord ) ; if ( klass == null && ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) != null ) { ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) . getMetadata ( ) . reload ( ) ; klass = fieldRecord . getSchemaClass ( ) ; } if ( klass . isVertexType ( ) ) { if ( iTargetVertex != null && ! iTargetVertex . equals ( fieldValue ) ) return null ; // DIRECT VERTEX, CREATE A DUMMY EDGE BETWEEN VERTICES if ( connection . getKey ( ) == Direction . OUT ) toAdd = graph . getEdgeInstance ( doc , fieldRecord , connection . getValue ( ) ) ; else toAdd = graph . getEdgeInstance ( fieldRecord , doc , connection . getValue ( ) ) ; } else if ( klass . isEdgeType ( ) ) { // EDGE if ( iTargetVertex != null ) { Object targetVertex = OrientEdge . getConnection ( fieldRecord , connection . getKey ( ) . opposite ( ) ) ; if ( ! iTargetVertex . equals ( targetVertex ) ) return null ; } toAdd = graph . getEdge ( fieldRecord ) ; } else throw new IllegalStateException ( \"Invalid content found in \" + fieldName + \" field: \" + fieldRecord ) ; return toAdd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Executes the command predicate against current vertex . Use OSQLPredicate to execute SQL . Example : <code > Iterable<OrientVertex > friendsOfFriends = ( Iterable<OrientVertex > ) luca . execute ( new OSQLPredicate ( out () . out ( Friend ) . out ( Friend ) )) ; < / code > [CODESPLIT] public Object execute ( final OCommandPredicate iPredicate ) { final Object result = iPredicate . evaluate ( rawElement . getRecord ( ) , null , null ) ; if ( result instanceof OAutoConvertToRecord ) ( ( OAutoConvertToRecord ) result ) . setAutoConvertToRecord ( true ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the Property names as Set of String . out in and label are not returned as properties even if are part of the underlying document because are considered internal properties . [CODESPLIT] @ Override public Set < String > getPropertyKeys ( ) { final OrientBaseGraph graph = setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; final Set < String > result = new HashSet < String > ( ) ; for ( String field : doc . fieldNames ( ) ) if ( graph != null && settings . isUseVertexFieldsForEdgeLabels ( ) ) { if ( ! field . startsWith ( CONNECTION_OUT_PREFIX ) && ! field . startsWith ( CONNECTION_IN_PREFIX ) ) result . add ( field ) ; } else if ( ! field . equals ( OrientBaseGraph . CONNECTION_OUT ) && ! field . equals ( OrientBaseGraph . CONNECTION_IN ) ) result . add ( field ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a lazy iterable instance against vertices . [CODESPLIT] @ Override public Iterable < Vertex > getVertices ( final Direction iDirection , final String ... iLabels ) { setCurrentGraphInThreadLocal ( ) ; OrientBaseGraph . getEdgeClassNames ( getGraph ( ) , iLabels ) ; OrientBaseGraph . encodeClassNames ( iLabels ) ; final ODocument doc = getRecord ( ) ; final OMultiCollectionIterator < Vertex > iterable = new OMultiCollectionIterator < Vertex > ( ) ; for ( OTriple < String , Direction , String > connectionField : getConnectionFields ( iDirection , iLabels ) ) { String fieldName = connectionField . getKey ( ) ; OPair < Direction , String > connection = connectionField . getValue ( ) ; final Object fieldValue = doc . rawField ( fieldName ) ; if ( fieldValue != null ) if ( fieldValue instanceof OIdentifiable ) { addSingleVertex ( doc , iterable , fieldName , connection , fieldValue , iLabels ) ; } else if ( fieldValue instanceof Collection < ? > ) { Collection < ? > coll = ( Collection < ? > ) fieldValue ; if ( coll . size ( ) == 1 ) { // SINGLE ITEM: AVOID CALLING ITERATOR if ( coll instanceof ORecordLazyMultiValue ) addSingleVertex ( doc , iterable , fieldName , connection , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) . next ( ) , iLabels ) ; else if ( coll instanceof List < ? > ) addSingleVertex ( doc , iterable , fieldName , connection , ( ( List < ? > ) coll ) . get ( 0 ) , iLabels ) ; else addSingleVertex ( doc , iterable , fieldName , connection , coll . iterator ( ) . next ( ) , iLabels ) ; } else { // CREATE LAZY Iterable AGAINST COLLECTION FIELD if ( coll instanceof ORecordLazyMultiValue ) iterable . add ( new OrientVertexIterator ( this , coll , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) , connection , iLabels , coll . size ( ) ) ) ; else iterable . add ( new OrientVertexIterator ( this , coll , coll . iterator ( ) , connection , iLabels , - 1 ) ) ; } } else if ( fieldValue instanceof ORidBag ) { iterable . add ( new OrientVertexIterator ( this , fieldValue , ( ( ORidBag ) fieldValue ) . rawIterator ( ) , connection , iLabels , - 1 ) ) ; } } return iterable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the current Vertex from the Graph . all the incoming and outgoing edges are automatically removed too . [CODESPLIT] @ Override public void remove ( ) { checkClass ( ) ; final OrientBaseGraph graph = checkIfAttached ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; final ODocument doc = getRecord ( ) ; if ( doc == null ) throw ExceptionFactory . vertexWithIdDoesNotExist ( this . getId ( ) ) ; Map < String , List < ODocument > > treeRidbagEdgesToRemove = new HashMap < String , List < ODocument > > ( ) ; if ( ! graph . getRawGraph ( ) . getTransaction ( ) . isActive ( ) ) { for ( String fieldName : doc . fieldNames ( ) ) { final OPair < Direction , String > connection = getConnection ( Direction . BOTH , fieldName ) ; if ( connection == null ) // SKIP THIS FIELD continue ; Object fv = doc . field ( fieldName ) ; if ( fv instanceof ORidBag && ! ( ( ORidBag ) fv ) . isEmbedded ( ) ) { List < ODocument > docs = new ArrayList < ODocument > ( ) ; for ( OIdentifiable id : ( ORidBag ) fv ) docs . ( OrientBaseGraph . getDocument ( id , true ) ) ; treeRidbagEdgesToRemove . put ( fieldName , docs ) ; } } } // REMOVE THE VERTEX RECORD FIRST TO CATCH CME BEFORE EDGES ARE REMOVED super . removeRecord ( ) ; // REMOVE THE VERTEX FROM MANUAL INDEXES final Iterator < Index < ? extends Element > > it = graph . getIndices ( ) . iterator ( ) ; if ( it . hasNext ( ) ) { final Set < Edge > allEdges = new HashSet < Edge > ( ) ; for ( Edge e : getEdges ( Direction . BOTH ) ) allEdges . ( ) ; while ( it . hasNext ( ) ) { final Index < ? extends Element > index = it . next ( ) ; if ( Vertex . class . isAssignableFrom ( index . getIndexClass ( ) ) ) { OrientIndex < OrientVertex > idx = ( OrientIndex < OrientVertex > ) index ; idx . removeElement ( this ) ; } if ( Edge . class . isAssignableFrom ( index . getIndexClass ( ) ) ) { OrientIndex < OrientEdge > idx = ( OrientIndex < OrientEdge > ) index ; for ( Edge e : allEdges ) idx . removeElement ( ( OrientEdge ) ) ; } } } for ( Map . Entry < String , List < ODocument > > entry : treeRidbagEdgesToRemove . entrySet ( ) ) { doc . removeField ( entry . getKey ( ) ) ; Iterator < ODocument > iter = entry . getValue ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { ODocument docEdge = iter . next ( ) ; OrientBaseGraph . deleteEdgeIfAny ( docEdge , false ) ; } } graph . removeEdgesInternal ( this , doc , null , true , settings . isUseVertexFieldsForEdgeLabels ( ) , settings . isAutoScaleEdgeType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves current vertex to another class / cluster . All edges are updated automatically . [CODESPLIT] public ORID moveTo ( final String iClassName , final String iClusterName ) { final OrientBaseGraph graph = getGraph ( ) ; if ( checkDeletedInTx ( ) ) graph . throwRecordNotFoundException ( getIdentity ( ) , \"The vertex \" + getIdentity ( ) + \" has been deleted\" ) ; final ORID oldIdentity = getIdentity ( ) . copy ( ) ; final ORecord oldRecord = oldIdentity . getRecord ( ) ; if ( oldRecord == null ) graph . throwRecordNotFoundException ( getIdentity ( ) , \"The vertex \" + getIdentity ( ) + \" has been deleted\" ) ; final ODocument doc = ( ( ODocument ) rawElement . getRecord ( ) ) . copy ( ) ; final Iterable < Edge > outEdges = getEdges ( Direction . OUT ) ; final Iterable < Edge > inEdges = getEdges ( Direction . IN ) ; // DELETE THE OLD RECORD FIRST TO AVOID ISSUES WITH UNIQUE CONSTRAINTS copyRidBags ( oldRecord , doc ) ; removeEdgeLinks ( oldRecord ) ; oldRecord . delete ( ) ; if ( iClassName != null ) // OVERWRITE CLASS doc . setClassName ( iClassName ) ; // SAVE THE NEW VERTEX doc . setDirty ( ) ; // RESET IDENTITY ORecordInternal . setIdentity ( doc , new ORecordId ( ) ) ; if ( iClusterName != null ) doc . save ( iClusterName ) ; else doc . save ( ) ; final ORID newIdentity = doc . getIdentity ( ) ; // CONVERT OUT EDGES for ( Edge e : outEdges ) { final OrientEdge oe = ( OrientEdge ) e ; if ( oe . isLightweight ( ) ) { // REPLACE ALL REFS IN inVertex final OrientVertex inV = oe . getVertex ( Direction . IN ) ; final String inFieldName = OrientVertex . getConnectionFieldName ( Direction . IN , oe . getLabel ( ) , graph . isUseVertexFieldsForEdgeLabels ( ) ) ; replaceLinks ( inV . getRecord ( ) , inFieldName , oldIdentity , newIdentity ) ; } else { // REPLACE WITH NEW VERTEX oe . vOut = newIdentity ; oe . getRecord ( ) . field ( OrientBaseGraph . CONNECTION_OUT , newIdentity ) ; oe . save ( ) ; } } for ( Edge e : inEdges ) { final OrientEdge oe = ( OrientEdge ) e ; if ( oe . isLightweight ( ) ) { // REPLACE ALL REFS IN outVertex final OrientVertex outV = oe . getVertex ( Direction . OUT ) ; final String outFieldName = OrientVertex . getConnectionFieldName ( Direction . OUT , oe . getLabel ( ) , graph . isUseVertexFieldsForEdgeLabels ( ) ) ; replaceLinks ( outV . getRecord ( ) , outFieldName , oldIdentity , newIdentity ) ; } else { // REPLACE WITH NEW VERTEX oe . vIn = newIdentity ; oe . getRecord ( ) . field ( OrientBaseGraph . CONNECTION_IN , newIdentity ) ; oe . save ( ) ; } } // FINAL SAVE doc . save ( ) ; return newIdentity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an edge between current Vertex and a target Vertex setting label as Edge s label . [CODESPLIT] @ Override public Edge addEdge ( final String label , Vertex inVertex ) { if ( inVertex instanceof PartitionVertex ) // WRAPPED: GET THE BASE VERTEX inVertex = ( ( PartitionVertex ) inVertex ) . getBaseVertex ( ) ; return addEdge ( label , ( OrientVertex ) inVertex , null , null , ( Object [ ] ) null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an edge between current Vertex and a target Vertex setting label as Edge s label . iClassName is the Edge s class used if different by label . [CODESPLIT] public OrientEdge addEdge ( final String label , final OrientVertex inVertex , final String iClassName ) { return addEdge ( label , inVertex , iClassName , null , ( Object [ ] ) null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an edge between current Vertex and a target Vertex setting label as Edge s label . The fields parameter is an Array of fields to set on Edge upon creation . Fields must be a odd pairs of key / value or a single object as Map containing entries as key / value pairs . iClusterName is the name of the cluster where to store the new Edge . [CODESPLIT] public OrientEdge addEdge ( String label , final OrientVertex inVertex , final String iClassName , final String iClusterName , final Object ... fields ) { if ( inVertex == null ) throw new IllegalArgumentException ( \"destination vertex is null\" ) ; final OrientBaseGraph graph = getGraph ( ) ; if ( graph != null ) return graph . addEdgeInternal ( this , label , inVertex , iClassName , iClusterName , fields ) ; // IN MEMORY CHANGES ONLY: USE NOTX CLASS return OrientGraphNoTx . addEdgeInternal ( null , this , label , inVertex , iClassName , iClusterName , fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the number of edges connected to the current Vertex . [CODESPLIT] public long countEdges ( final Direction iDirection , final String ... iLabels ) { checkIfAttached ( ) ; long counter = 0 ; OrientBaseGraph . getEdgeClassNames ( getGraph ( ) , iLabels ) ; OrientBaseGraph . encodeClassNames ( iLabels ) ; if ( settings . isUseVertexFieldsForEdgeLabels ( ) || iLabels == null || iLabels . length == 0 ) { // VERY FAST final ODocument doc = getRecord ( ) ; for ( String fieldName : doc . fieldNames ( ) ) { final OPair < Direction , String > connection = getConnection ( iDirection , fieldName , iLabels ) ; if ( connection == null ) // SKIP THIS FIELD continue ; final Object fieldValue = doc . field ( fieldName ) ; if ( fieldValue != null ) if ( fieldValue instanceof Collection < ? > ) counter += ( ( Collection < ? > ) fieldValue ) . size ( ) ; else if ( fieldValue instanceof Map < ? , ? > ) counter += ( ( Map < ? , ? > ) fieldValue ) . size ( ) ; else if ( fieldValue instanceof ORidBag ) { counter += ( ( ORidBag ) fieldValue ) . size ( ) ; } else { counter ++ ; } } } else { // SLOWER: BROWSE & FILTER for ( Edge e : getEdges ( iDirection , iLabels ) ) if ( e != null ) counter ++ ; } return counter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the edges connected to the current Vertex . If you are interested on just counting the edges use @countEdges that it s more efficient for this use case . [CODESPLIT] @ Override public Iterable < Edge > getEdges ( final Direction iDirection , final String ... iLabels ) { return getEdges ( null , iDirection , iLabels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns all the edges from the current Vertex to another one . [CODESPLIT] public Iterable < Edge > getEdges ( final OrientVertex iDestination , final Direction iDirection , final String ... iLabels ) { setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; OrientBaseGraph . getEdgeClassNames ( getGraph ( ) , iLabels ) ; OrientBaseGraph . encodeClassNames ( iLabels ) ; final OMultiCollectionIterator < Edge > iterable = new OMultiCollectionIterator < Edge > ( ) . setEmbedded ( true ) ; for ( OTriple < String , Direction , String > connectionField : getConnectionFields ( iDirection , iLabels ) ) { String fieldName = connectionField . getKey ( ) ; OPair < Direction , String > connection = connectionField . getValue ( ) ; final Object fieldValue = doc . rawField ( fieldName ) ; if ( fieldValue != null ) { final OIdentifiable destinationVId = iDestination != null ? ( OIdentifiable ) iDestination . getId ( ) : null ; if ( fieldValue instanceof OIdentifiable ) { addSingleEdge ( doc , iterable , fieldName , connection , fieldValue , destinationVId , iLabels ) ; } else if ( fieldValue instanceof Collection < ? > ) { Collection < ? > coll = ( Collection < ? > ) fieldValue ; if ( coll . size ( ) == 1 ) { // SINGLE ITEM: AVOID CALLING ITERATOR if ( coll instanceof ORecordLazyMultiValue ) addSingleEdge ( doc , iterable , fieldName , connection , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) . next ( ) , destinationVId , iLabels ) ; else if ( coll instanceof List < ? > ) addSingleEdge ( doc , iterable , fieldName , connection , ( ( List < ? > ) coll ) . get ( 0 ) , destinationVId , iLabels ) ; else addSingleEdge ( doc , iterable , fieldName , connection , coll . iterator ( ) . next ( ) , destinationVId , iLabels ) ; } else { // CREATE LAZY Iterable AGAINST COLLECTION FIELD if ( coll instanceof ORecordLazyMultiValue ) { iterable . add ( new OrientEdgeIterator ( this , iDestination , coll , ( ( ORecordLazyMultiValue ) coll ) . rawIterator ( ) , connection , iLabels , coll . size ( ) ) ) ; } else iterable . add ( new OrientEdgeIterator ( this , iDestination , coll , coll . iterator ( ) , connection , iLabels , - 1 ) ) ; } } else if ( fieldValue instanceof ORidBag ) { iterable . add ( new OrientEdgeIterator ( this , iDestination , fieldValue , ( ( ORidBag ) fieldValue ) . rawIterator ( ) , connection , iLabels , ( ( ORidBag ) fieldValue ) . size ( ) ) ) ; } } } return iterable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the Vertex s label . By default OrientDB binds the Blueprints Label concept to Vertex Class . To disable this feature execute this at database level <code > alter database custom useClassForVertexLabel = false < / code > [CODESPLIT] @ Override public String getLabel ( ) { setCurrentGraphInThreadLocal ( ) ; if ( settings . isUseClassForVertexLabel ( ) ) { final String clsName = getRecord ( ) . getClassName ( ) ; if ( ! OrientVertexType . CLASS_NAME . equals ( clsName ) ) // RETURN THE CLASS NAME return clsName ; } return getRecord ( ) . field ( OrientElement . LABEL_FIELD_NAME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the Vertex type as OrientVertexType object . [CODESPLIT] @ Override public OrientVertexType getType ( ) { final OrientBaseGraph graph = getGraph ( ) ; return new OrientVertexType ( graph , getRecord ( ) . getSchemaClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to extract the class name from the vertex s field . [CODESPLIT] public String getConnectionClass ( final Direction iDirection , final String iFieldName ) { if ( iDirection == Direction . OUT ) { if ( iFieldName . length ( ) > CONNECTION_OUT_PREFIX . length ( ) ) return iFieldName . substring ( CONNECTION_OUT_PREFIX . length ( ) ) ; } else if ( iDirection == Direction . IN ) { if ( iFieldName . length ( ) > CONNECTION_IN_PREFIX . length ( ) ) return iFieldName . substring ( CONNECTION_IN_PREFIX . length ( ) ) ; } return OrientEdgeType . CLASS_NAME ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if a field is a connections or not . [CODESPLIT] protected OPair < Direction , String > getConnection ( final Direction iDirection , final String iFieldName , String ... iClassNames ) { if ( iClassNames != null && iClassNames . length == 1 && iClassNames [ 0 ] . equalsIgnoreCase ( \"E\" ) ) // DEFAULT CLASS, TREAT IT AS NO CLASS/LABEL iClassNames = null ; final OrientBaseGraph graph = getGraph ( ) ; if ( iDirection == Direction . OUT || iDirection == Direction . BOTH ) { if ( settings . isUseVertexFieldsForEdgeLabels ( ) ) { // FIELDS THAT STARTS WITH \"out_\" if ( iFieldName . startsWith ( CONNECTION_OUT_PREFIX ) ) { String connClass = getConnectionClass ( Direction . OUT , iFieldName ) ; if ( iClassNames == null || iClassNames . length == 0 ) return new OPair < Direction , String > ( Direction . OUT , connClass ) ; // CHECK AGAINST ALL THE CLASS NAMES OrientEdgeType edgeType = graph . getEdgeType ( connClass ) ; if ( edgeType != null ) { for ( String clsName : iClassNames ) { if ( edgeType . isSubClassOf ( clsName ) ) return new OPair < Direction , String > ( Direction . OUT , connClass ) ; } } } } else if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_OUT ) ) // CHECK FOR \"out\" return new OPair < Direction , String > ( Direction . OUT , null ) ; } if ( iDirection == Direction . IN || iDirection == Direction . BOTH ) { if ( settings . isUseVertexFieldsForEdgeLabels ( ) ) { // FIELDS THAT STARTS WITH \"in_\" if ( iFieldName . startsWith ( CONNECTION_IN_PREFIX ) ) { String connClass = getConnectionClass ( Direction . IN , iFieldName ) ; if ( iClassNames == null || iClassNames . length == 0 ) return new OPair < Direction , String > ( Direction . IN , connClass ) ; // CHECK AGAINST ALL THE CLASS NAMES OrientEdgeType edgeType = graph . getEdgeType ( connClass ) ; if ( edgeType != null ) { for ( String clsName : iClassNames ) { if ( edgeType . isSubClassOf ( clsName ) ) return new OPair < Direction , String > ( Direction . IN , connClass ) ; } } } } else if ( iFieldName . equals ( OrientBaseGraph . CONNECTION_IN ) ) // CHECK FOR \"in\" return new OPair < Direction , String > ( Direction . IN , null ) ; } // NOT FOUND return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the possible fields names to look for . [CODESPLIT] private List < OTriple < String , Direction , String > > getConnectionFields ( final Direction iDirection , String ... iClassNames ) { final ODocument doc = getRecord ( ) ; List < OTriple < String , Direction , String > > result = new ArrayList <> ( ) ; if ( settings . isUseVertexFieldsForEdgeLabels ( ) ) { if ( iClassNames == null || iClassNames . length == 0 || ( iClassNames . length == 1 && iClassNames [ 0 ] . equalsIgnoreCase ( \"E\" ) ) ) { for ( String fieldName : doc . fieldNames ( ) ) { final OPair < Direction , String > connection = getConnection ( iDirection , fieldName , iClassNames ) ; if ( connection != null ) result . add ( new OTriple < String , Direction , String > ( fieldName , connection . getKey ( ) , connection . getValue ( ) ) ) ; } } else { OSchema schema = getGraph ( ) . getRawGraph ( ) . getMetadata ( ) . getSchema ( ) ; Set < String > allClassNames = new HashSet < String > ( ) ; for ( String className : iClassNames ) { allClassNames . add ( className ) ; OClass clazz = schema . getClass ( className ) ; if ( clazz != null ) { Collection < OClass > subClasses = clazz . getAllSubclasses ( ) ; for ( OClass subClass : subClasses ) { allClassNames . add ( subClass . getName ( ) ) ; } } } for ( String className : allClassNames ) { switch ( iDirection ) { case OUT : result . add ( new OTriple < String , Direction , String > ( CONNECTION_OUT_PREFIX + className , Direction . OUT , className ) ) ; break ; case IN : result . add ( new OTriple < String , Direction , String > ( CONNECTION_IN_PREFIX + className , Direction . IN , className ) ) ; break ; case BOTH : result . add ( new OTriple < String , Direction , String > ( CONNECTION_OUT_PREFIX + className , Direction . OUT , className ) ) ; result . add ( new OTriple < String , Direction , String > ( CONNECTION_IN_PREFIX + className , Direction . IN , className ) ) ; break ; } } } } else { if ( iDirection == Direction . OUT ) result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_OUT , Direction . OUT , null ) ) ; else if ( iDirection == Direction . IN ) result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_IN , Direction . IN , null ) ) ; else { result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_OUT , Direction . OUT , null ) ) ; result . add ( new OTriple < String , Direction , String > ( OrientBaseGraph . CONNECTION_IN , Direction . IN , null ) ) ; } } // EARLY FETCH ALL THE FIELDS THAT MATTERS String [ ] fieldNames = new String [ result . size ( ) ] ; int i = 0 ; for ( OTriple < String , Direction , String > connectionField : result ) fieldNames [ i ++ ] = connectionField . getKey ( ) ; doc . deserializeFields ( fieldNames ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "just read collection so import process can continue [CODESPLIT] private void processBrokenRids ( Set < ORID > brokenRids ) throws IOException , ParseException { if ( exporterVersion >= 12 ) { listener . onMessage ( \"Reading of set of RIDs of records which were detected as broken during database export\\n\" ) ; jsonReader . readNext ( OJSONReader . BEGIN_COLLECTION ) ; while ( true ) { jsonReader . readNext ( OJSONReader . NEXT_IN_ARRAY ) ; final ORecordId recordId = new ORecordId ( jsonReader . getValue ( ) ) ; brokenRids . add ( recordId ) ; if ( jsonReader . lastChar ( ) == ' ' ) break ; } } if ( migrateLinks ) { if ( exporterVersion >= 12 ) listener . onMessage ( brokenRids . size ( ) + \" were detected as broken during database export, links on those records will be removed from\" + \" result database\" ) ; migrateLinksInImportedDocuments ( brokenRids ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( clazz == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; final List < Object > edges = new ArrayList < Object > ( ) ; Set < OIdentifiable > fromIds = null ; Set < OIdentifiable > toIds = null ; db . begin ( ) ; try { fromIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , from , context , iArgs ) ; toIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , to , context , iArgs ) ; // CREATE EDGES for ( OIdentifiable from : fromIds ) { final OVertex fromVertex = toVertex ( from ) ; if ( fromVertex == null ) throw new OCommandExecutionException ( \"Source vertex '\" + from + \"' does not exist\" ) ; for ( OIdentifiable to : toIds ) { final OVertex toVertex ; if ( from . equals ( to ) ) { toVertex = fromVertex ; } else { toVertex = toVertex ( to ) ; } if ( toVertex == null ) { throw new OCommandExecutionException ( \"Source vertex '\" + to + \"' does not exist\" ) ; } if ( fields != null ) // EVALUATE FIELDS for ( final OPair < String , Object > f : fields ) { if ( f . getValue ( ) instanceof OSQLFunctionRuntime ) { f . setValue ( ( ( OSQLFunctionRuntime ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } else if ( f . getValue ( ) instanceof OSQLFilterItem ) { f . setValue ( ( ( OSQLFilterItem ) f . getValue ( ) ) . getValue ( to , null , context ) ) ; } } OEdge edge = null ; if ( content != null ) { if ( fields != null ) // MERGE CONTENT WITH FIELDS fields . addAll ( OPair . convertFromMap ( content . toMap ( ) ) ) ; else fields = OPair . convertFromMap ( content . toMap ( ) ) ; } edge = fromVertex . addEdge ( toVertex , edgeLabel ) ; if ( fields != null && ! fields . isEmpty ( ) ) { OSQLHelper . bindParameters ( edge . getRecord ( ) , fields , new OCommandParameters ( iArgs ) , context ) ; } edge . save ( clusterName ) ; fromVertex . save ( ) ; toVertex . save ( ) ; edges . add ( edge ) ; if ( batch > 0 && edges . size ( ) % batch == 0 ) { db . commit ( ) ; db . begin ( ) ; } } } } finally { db . commit ( ) ; } if ( edges . isEmpty ( ) ) { if ( fromIds . isEmpty ( ) ) throw new OCommandExecutionException ( \"No edge has been created because no source vertices\" ) ; else if ( toIds . isEmpty ( ) ) throw new OCommandExecutionException ( \"No edge has been created because no target vertices\" ) ; throw new OCommandExecutionException ( \"No edge has been created between \" + fromIds + \" and \" + toIds ) ; } return edges ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a map of all console method and the object they can be called on . [CODESPLIT] protected Map < Method , Object > getConsoleMethods ( ) { if ( methods != null ) return methods ; // search for declared command collections final Iterator < OConsoleCommandCollection > ite = ServiceLoader . load ( OConsoleCommandCollection . class ) . iterator ( ) ; final Collection < Object > candidates = new ArrayList < Object > ( ) ; candidates . add ( this ) ; while ( ite . hasNext ( ) ) { try { // make a copy and set it's context final OConsoleCommandCollection cc = ite . next ( ) . getClass ( ) . newInstance ( ) ; cc . setContext ( this ) ; candidates . add ( cc ) ; } catch ( InstantiationException ex ) { Logger . getLogger ( OConsoleApplication . class . getName ( ) ) . log ( Level . WARNING , ex . getMessage ( ) ) ; } catch ( IllegalAccessException ex ) { Logger . getLogger ( OConsoleApplication . class . getName ( ) ) . log ( Level . WARNING , ex . getMessage ( ) ) ; } } methods = new TreeMap < Method , Object > ( new Comparator < Method > ( ) { public int compare ( Method o1 , Method o2 ) { final ConsoleCommand ann1 = o1 . getAnnotation ( ConsoleCommand . class ) ; final ConsoleCommand ann2 = o2 . getAnnotation ( ConsoleCommand . class ) ; if ( ann1 != null && ann2 != null ) { if ( ann1 . priority ( ) != ann2 . priority ( ) ) // PRIORITY WINS return ann1 . priority ( ) - ann2 . priority ( ) ; } int res = o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; if ( res == 0 ) res = o1 . toString ( ) . compareTo ( o2 . toString ( ) ) ; return res ; } } ) ; for ( final Object candidate : candidates ) { final Method [ ] classMethods = candidate . getClass ( ) . getMethods ( ) ; for ( Method m : classMethods ) { if ( Modifier . isAbstract ( m . getModifiers ( ) ) || Modifier . isStatic ( m . getModifiers ( ) ) || ! Modifier . isPublic ( m . getModifiers ( ) ) ) { continue ; } if ( m . getReturnType ( ) != Void . TYPE ) { continue ; } methods . put ( m , candidate ) ; } } return methods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the request on local node . In case of error returns the Exception itself [CODESPLIT] @ Override public Object executeOnLocalNode ( final ODistributedRequestId reqId , final ORemoteTask task , final ODatabaseDocumentInternal database ) { if ( database != null && ! ( database . getStorage ( ) instanceof ODistributedStorage ) ) throw new ODistributedException ( \"Distributed storage was not installed for database '\" + database . getName ( ) + \"'. Implementation found: \" + database . getStorage ( ) . getClass ( ) . getName ( ) ) ; final ODistributedAbstractPlugin manager = this ; return OScenarioThreadLocal . executeAsDistributed ( new Callable < Object > ( ) { @ Override public Object call ( ) throws Exception { try { final Object result = task . execute ( reqId , serverInstance , manager , database ) ; if ( result instanceof Throwable && ! ( result instanceof OException ) ) // EXCEPTION ODistributedServerLog . debug ( this , nodeName , getNodeNameById ( reqId . getNodeId ( ) ) , DIRECTION . IN , \"Error on executing request %d (%s) on local node: \" , ( Throwable ) result , reqId , task ) ; else { // OK final String sourceNodeName = task . getNodeSource ( ) ; if ( database != null ) { final ODistributedDatabaseImpl ddb = getMessageService ( ) . getDatabase ( database . getName ( ) ) ; if ( ddb != null && ! ( result instanceof Throwable ) && task instanceof OAbstractReplicatedTask && ! task . isIdempotent ( ) ) { // UPDATE LSN WITH LAST OPERATION ddb . setLSN ( sourceNodeName , ( ( OAbstractReplicatedTask ) task ) . getLastLSN ( ) , true ) ; // UPDATE LSN WITH LAST LOCAL OPERATION ddb . setLSN ( getLocalNodeName ( ) , ( ( OAbstractPaginatedStorage ) database . getStorage ( ) . getUnderlying ( ) ) . getLSN ( ) , true ) ; } } } return result ; } catch ( InterruptedException e ) { // IGNORE IT ODistributedServerLog . debug ( this , nodeName , getNodeNameById ( reqId . getNodeId ( ) ) , DIRECTION . IN , \"Interrupted execution on executing distributed request %s on local node: %s\" , e , reqId , task ) ; return e ; } catch ( Exception e ) { if ( ! ( e instanceof OException ) ) ODistributedServerLog . error ( this , nodeName , getNodeNameById ( reqId . getNodeId ( ) ) , DIRECTION . IN , \"Error on executing distributed request %s on local node: %s\" , e , reqId , task ) ; return e ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the available nodes ( not offline ) and clears the node list by removing the offline nodes . [CODESPLIT] @ Override public int getAvailableNodes ( final Collection < String > iNodes , final String databaseName ) { for ( Iterator < String > it = iNodes . iterator ( ) ; it . hasNext ( ) ; ) { final String node = it . next ( ) ; if ( ! isNodeAvailable ( node , databaseName ) ) it . remove ( ) ; } return iNodes . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the nodes with the requested status . [CODESPLIT] @ Override public int getNodesWithStatus ( final Collection < String > iNodes , final String databaseName , final DB_STATUS ... statuses ) { for ( Iterator < String > it = iNodes . iterator ( ) ; it . hasNext ( ) ; ) { final String node = it . next ( ) ; if ( ! isNodeStatusEqualsTo ( node , databaseName , statuses ) ) it . remove ( ) ; } return iNodes . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs a database from the network . [CODESPLIT] protected void installDatabaseFromNetwork ( final String dbPath , final String databaseName , final ODistributedDatabaseImpl distrDatabase , final String iNode , final ODistributedDatabaseChunk firstChunk , final boolean delta , final File uniqueClustersBackupDirectory , final OModifiableDistributedConfiguration cfg ) { final String fileName = Orient . getTempPath ( ) + \"install_\" + databaseName + \"_server\" + getLocalNodeId ( ) + \".zip\" ; final String localNodeName = nodeName ; ODistributedServerLog . info ( this , localNodeName , iNode , DIRECTION . IN , \"Copying remote database '%s' to: %s\" , databaseName , fileName ) ; final File file = new File ( fileName ) ; if ( file . exists ( ) ) file . delete ( ) ; try { file . getParentFile ( ) . mkdirs ( ) ; file . createNewFile ( ) ; } catch ( IOException e ) { throw OException . wrapException ( new ODistributedException ( \"Error on creating temp database file to install locally\" ) , e ) ; } // DELETE ANY PREVIOUS .COMPLETED FILE final File completedFile = new File ( file . getAbsolutePath ( ) + \".completed\" ) ; if ( completedFile . exists ( ) ) completedFile . delete ( ) ; final AtomicReference < ODistributedMomentum > momentum = new AtomicReference < ODistributedMomentum > ( ) ; OSyncReceiver receiver = new OSyncReceiver ( this , databaseName , firstChunk , momentum , fileName , iNode , dbPath , file ) ; try { Thread t = new Thread ( receiver ) ; t . setUncaughtExceptionHandler ( new OUncaughtExceptionHandler ( ) ) ; t . start ( ) ; } catch ( Exception e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , \"Error on transferring database '%s' to '%s'\" , e , databaseName , fileName ) ; throw OException . wrapException ( new ODistributedException ( \"Error on transferring database\" ) , e ) ; } final ODatabaseDocumentInternal db = installDatabaseOnLocalNode ( databaseName , dbPath , iNode , fileName , delta , uniqueClustersBackupDirectory , cfg , firstChunk . incremental , firstChunk . walSegment , firstChunk . walPosition , receiver ) ; if ( db == null ) return ; // OVERWRITE THE MOMENTUM FROM THE ORIGINAL SERVER AND ADD LAST LOCAL LSN try { distrDatabase . getSyncConfiguration ( ) . load ( ) ; distrDatabase . getSyncConfiguration ( ) . setLastLSN ( localNodeName , ( ( OLocalPaginatedStorage ) db . getStorage ( ) . getUnderlying ( ) ) . getLSN ( ) , false ) ; } catch ( IOException e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , \"Error on loading %s file for database '%s'\" , e , DISTRIBUTED_SYNC_JSON_FILENAME , databaseName ) ; } try { distrDatabase . setOnline ( ) ; } finally { db . activateOnCurrentThread ( ) ; db . close ( ) ; } try { rebalanceClusterOwnership ( nodeName , db , cfg , false ) ; } catch ( Exception e ) { // HANDLE IT AS WARNING ODistributedServerLog . warn ( this , nodeName , null , DIRECTION . NONE , \"Error on re-balancing the cluster for database '%s'\" , e , databaseName ) ; // NOT CRITICAL, CONTINUE } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a backup of the database . During the backup the database will be frozen in read - only mode . [CODESPLIT] @ Override public List < String > backup ( OutputStream out , Map < String , Object > options , Callable < Object > callable , final OCommandOutputListener iListener , int compressionLevel , int bufferSize ) throws IOException { return underlying . backup ( out , options , callable , iListener , compressionLevel , bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Derived classes can override createRole () to return an extended ORole implementation . [CODESPLIT] protected ORole createRole ( final ODocument roleDoc ) { ORole role = null ; // If databaseName is set, then only allow roles with the same databaseName. if ( databaseName != null && ! databaseName . isEmpty ( ) ) { if ( roleDoc != null && roleDoc . containsField ( OSystemRole . DB_FILTER ) && roleDoc . fieldType ( OSystemRole . DB_FILTER ) == OType . EMBEDDEDLIST ) { List < String > dbNames = roleDoc . field ( OSystemRole . DB_FILTER , OType . EMBEDDEDLIST ) ; for ( String dbName : dbNames ) { if ( dbName != null && ! dbName . isEmpty ( ) && ( dbName . equalsIgnoreCase ( databaseName ) || dbName . equals ( \"*\" ) ) ) { role = new OSystemRole ( roleDoc ) ; break ; } } } } // If databaseName is not set, only return roles without a OSystemRole.DB_FILTER property or if set to \"*\". else { if ( roleDoc != null ) { if ( ! roleDoc . containsField ( OSystemRole . DB_FILTER ) ) { role = new OSystemRole ( roleDoc ) ; } else { // It does use the dbFilter property. if ( roleDoc . fieldType ( OSystemRole . DB_FILTER ) == OType . EMBEDDEDLIST ) { List < String > dbNames = roleDoc . field ( OSystemRole . DB_FILTER , OType . EMBEDDEDLIST ) ; for ( String dbName : dbNames ) { if ( dbName != null && ! dbName . isEmpty ( ) && dbName . equals ( \"*\" ) ) { role = new OSystemRole ( roleDoc ) ; break ; } } } } } } return role ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the ALTER CLASS . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocument database = getDatabase ( ) ; if ( attribute == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final OClassImpl cls = ( OClassImpl ) database . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( cls == null ) throw new OCommandExecutionException ( \"Cannot alter class '\" + className + \"' because not found\" ) ; if ( ! unsafe && attribute == ATTRIBUTES . NAME && cls . isSubClassOf ( \"E\" ) ) throw new OCommandExecutionException ( \"Cannot alter class '\" + className + \"' because is an Edge class and could break vertices. Use UNSAFE if you want to force it\" ) ; // REMOVE CACHE OF COMMAND RESULTS\r for ( int clId : cls . getPolymorphicClusterIds ( ) ) getDatabase ( ) . getMetadata ( ) . getCommandCache ( ) . invalidateResultsOfCluster ( getDatabase ( ) . getClusterNameById ( clId ) ) ; if ( value != null && attribute == ATTRIBUTES . SUPERCLASS ) { checkClassExists ( database , className , decodeClassName ( value ) ) ; } if ( value != null && attribute == ATTRIBUTES . SUPERCLASSES ) { List < String > classes = Arrays . asList ( value . split ( \",\\\\s*\" ) ) ; for ( String cName : classes ) { checkClassExists ( database , className , decodeClassName ( cName ) ) ; } } if ( ! unsafe && value != null && attribute == ATTRIBUTES . NAME ) { if ( ! cls . getIndexes ( ) . isEmpty ( ) ) { throw new OCommandExecutionException ( \"Cannot rename class '\" + className + \"' because it has indexes defined on it. Drop indexes before or use UNSAFE (at your won risk)\" ) ; } } cls . set ( attribute , value ) ; return Boolean . TRUE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : CREATE A REGULAR JSR223 SCRIPT IMPL [CODESPLIT] protected Object executeSQL ( ) { ODatabaseDocument db = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { return executeSQLScript ( parserText , db ) ; } catch ( IOException e ) { throw OException . wrapException ( new OCommandExecutionException ( \"Error on executing command: \" + parserText ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait before to retry [CODESPLIT] protected void waitForNextRetry ( ) { try { Thread . sleep ( new Random ( ) . nextInt ( MAX_DELAY - 1 ) + 1 ) ; } catch ( InterruptedException e ) { OLogManager . instance ( ) . error ( this , \"Wait was interrupted\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the argument by position [CODESPLIT] public String getArgument ( final int iPosition ) { return args != null && args . length > iPosition ? args [ iPosition ] : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks how many parameters have been received . [CODESPLIT] public int hasParameters ( final String ... iNames ) { int found = 0 ; if ( iNames != null && request . parameters != null ) for ( String name : iNames ) found += request . parameters . containsKey ( name ) ? 1 : 0 ; return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to a remote server . [CODESPLIT] @ Deprecated public synchronized OServerAdmin connect ( final String iUserName , final String iUserPassword ) throws IOException { final String username ; final String password ; OCredentialInterceptor ci = OSecurityManager . instance ( ) . newCredentialInterceptor ( ) ; if ( ci != null ) { ci . intercept ( storage . getURL ( ) , iUserName , iUserPassword ) ; username = ci . getUsername ( ) ; password = ci . getPassword ( ) ; } else { username = iUserName ; password = iUserPassword ; } OConnect37Request request = new OConnect37Request ( username , password ) ; networkAdminOperation ( ( network , session ) -> { OStorageRemoteNodeSession nodeSession = session . getOrCreateServerSession ( network . getServerURL ( ) ) ; try { network . beginRequest ( request . getCommand ( ) , session ) ; request . write ( network , session ) ; } finally { network . endRequest ( ) ; } OConnectResponse response = request . createResponse ( ) ; try { network . beginResponse ( nodeSession . getSessionId ( ) , true ) ; response . read ( network , session ) ; } finally { storage . endResponse ( network ) ; } return null ; } , \"Cannot connect to the remote server/database '\" + storage . getURL ( ) + \"'\" ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the list of databases on the connected remote server . [CODESPLIT] @ Deprecated public synchronized Map < String , String > listDatabases ( ) throws IOException { OListDatabasesRequest request = new OListDatabasesRequest ( ) ; OListDatabasesResponse response = networkAdminOperation ( request , \"Cannot retrieve the configuration list\" ) ; return response . getDatabases ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the server information in form of document . [CODESPLIT] @ Deprecated public synchronized ODocument getServerInfo ( ) throws IOException { OServerInfoRequest request = new OServerInfoRequest ( ) ; OServerInfoResponse response = networkAdminOperation ( request , \"Cannot retrieve server information\" ) ; ODocument res = new ODocument ( ) ; res . fromJSON ( response . getResult ( ) ) ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a database in a remote server . [CODESPLIT] @ Deprecated public synchronized OServerAdmin createDatabase ( final String iDatabaseType , String iStorageMode ) throws IOException { return createDatabase ( storage . getName ( ) , iDatabaseType , iStorageMode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a database in a remote server . [CODESPLIT] public synchronized OServerAdmin createDatabase ( final String iDatabaseName , final String iDatabaseType , final String iStorageMode , final String backupPath ) throws IOException { if ( iDatabaseName == null || iDatabaseName . length ( ) <= 0 ) { final String message = \"Cannot create unnamed remote storage. Check your syntax\" ; OLogManager . instance ( ) . error ( this , message , null ) ; throw new OStorageException ( message ) ; } else { String storageMode ; if ( iStorageMode == null ) storageMode = \"plocal\" ; else storageMode = iStorageMode ; OCreateDatabaseRequest request = new OCreateDatabaseRequest ( iDatabaseName , iDatabaseName , storageMode , backupPath ) ; OCreateDatabaseResponse response = networkAdminOperation ( request , \"Cannot create the remote storage: \" + storage . getName ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a database exists in the remote server . [CODESPLIT] public synchronized boolean existsDatabase ( final String iDatabaseName , final String storageType ) throws IOException { OExistsDatabaseRequest request = new OExistsDatabaseRequest ( iDatabaseName , storageType ) ; OExistsDatabaseResponse response = networkAdminOperation ( request , \"Error on checking existence of the remote storage: \" + storage . getName ( ) ) ; return response . isExists ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drops a database from a remote server instance . [CODESPLIT] public synchronized OServerAdmin dropDatabase ( final String iDatabaseName , final String storageType ) throws IOException { ODropDatabaseRequest request = new ODropDatabaseRequest ( iDatabaseName , storageType ) ; ODropDatabaseResponse response = networkAdminOperation ( request , \"Cannot delete the remote storage: \" + storage . getName ( ) ) ; OURLConnection connection = OURLHelper . parse ( getURL ( ) ) ; OrientDBRemote remote = ( OrientDBRemote ) ODatabaseDocumentTxInternal . getOrCreateRemoteFactory ( connection . getPath ( ) ) ; remote . forceDatabaseClose ( iDatabaseName ) ; ODatabaseRecordThreadLocal . instance ( ) . remove ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Freezes the database by locking it in exclusive mode . [CODESPLIT] public synchronized OServerAdmin freezeDatabase ( final String storageType ) throws IOException { OFreezeDatabaseRequest request = new OFreezeDatabaseRequest ( storage . getName ( ) , storageType ) ; OFreezeDatabaseResponse response = networkAdminOperation ( request , \"Cannot freeze the remote storage: \" + storage . getName ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Releases a frozen database . [CODESPLIT] public synchronized OServerAdmin releaseDatabase ( final String storageType ) throws IOException { OReleaseDatabaseRequest request = new OReleaseDatabaseRequest ( storage . getName ( ) , storageType ) ; OReleaseDatabaseResponse response = networkAdminOperation ( request , \"Cannot release the remote storage: \" + storage . getName ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the cluster status . [CODESPLIT] public ODocument clusterStatus ( ) { ODistributedStatusRequest request = new ODistributedStatusRequest ( ) ; ODistributedStatusResponse response = storage . networkOperation ( request , \"Error on executing Cluster status \" ) ; OLogManager . instance ( ) . debug ( this , \"Cluster status %s\" , response . getClusterConfig ( ) . toJSON ( \"prettyPrint\" ) ) ; return response . getClusterConfig ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the CREATE INDEX . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public Object execute ( final Map < Object , Object > iArgs ) { if ( indexName == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocument database = getDatabase ( ) ; final OIndex < ? > idx ; List < OCollate > collatesList = null ; if ( collates != null ) { collatesList = new ArrayList < OCollate > ( ) ; for ( String collate : collates ) { if ( collate != null ) { final OCollate col = OSQLEngine . getCollate ( collate ) ; collatesList . add ( col ) ; } else collatesList . add ( null ) ; } } if ( fields == null || fields . length == 0 ) { OIndexFactory factory = OIndexes . getFactory ( indexType . toString ( ) , null ) ; if ( keyTypes != null ) idx = database . getMetadata ( ) . getIndexManager ( ) . createIndex ( indexName , indexType . toString ( ) , new OSimpleKeyIndexDefinition ( keyTypes , collatesList ) , null , null , metadataDoc , engine ) ; else if ( serializerKeyId != 0 ) { idx = database . getMetadata ( ) . getIndexManager ( ) . createIndex ( indexName , indexType . toString ( ) , new ORuntimeKeyIndexDefinition ( serializerKeyId ) , null , null , metadataDoc , engine ) ; } else { throw new ODatabaseException ( \"Impossible to create an index without specify the key type or the associated property\" ) ; } } else { if ( ( keyTypes == null || keyTypes . length == 0 ) && collates == null ) { idx = oClass . createIndex ( indexName , indexType . toString ( ) , null , metadataDoc , engine , fields ) ; } else { final List < OType > fieldTypeList ; if ( keyTypes == null ) { for ( final String fieldName : fields ) { if ( ! fieldName . equals ( \"@rid\" ) && ! oClass . existsProperty ( fieldName ) ) throw new OIndexException ( \"Index with name : '\" + indexName + \"' cannot be created on class : '\" + oClass . getName ( ) + \"' because field: '\" + fieldName + \"' is absent in class definition.\" ) ; } fieldTypeList = ( ( OClassImpl ) oClass ) . extractFieldTypes ( fields ) ; } else fieldTypeList = Arrays . asList ( keyTypes ) ; final OIndexDefinition idxDef = OIndexDefinitionFactory . createIndexDefinition ( oClass , Arrays . asList ( fields ) , fieldTypeList , collatesList , indexType . toString ( ) , null ) ; idx = database . getMetadata ( ) . getIndexManager ( ) . createIndex ( indexName , indexType . name ( ) , idxDef , oClass . getPolymorphicClusterIds ( ) , null , metadataDoc , engine ) ; } } if ( idx != null ) return idx . getSize ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Transactional OrientGraph implementation from the current database in thread local . [CODESPLIT] public static OrientGraph getGraph ( final boolean autoStartTx , OModifiableBoolean shouldBeShutDown ) { final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; final OrientBaseGraph result = OrientBaseGraph . getActiveGraph ( ) ; if ( result != null && ( result instanceof OrientGraph ) ) { final ODatabaseDocumentInternal graphDb = result . getRawGraph ( ) ; // CHECK IF THE DATABASE + USER IN TL IS THE SAME IN ORDER TO USE IT if ( canReuseActiveGraph ( graphDb , database ) ) { if ( ! graphDb . isClosed ( ) ) { ODatabaseRecordThreadLocal . instance ( ) . set ( graphDb ) ; if ( autoStartTx && autoTxStartRequired ( graphDb ) ) ( ( OrientGraph ) result ) . begin ( ) ; shouldBeShutDown . setValue ( false ) ; return ( OrientGraph ) result ; } } } // Set it again on ThreadLocal because the getRawGraph() may have set a closed db in the thread-local ODatabaseRecordThreadLocal . instance ( ) . set ( database ) ; shouldBeShutDown . setValue ( true ) ; final OrientGraph g = ( OrientGraph ) OrientGraphFactory . getTxGraphImplFactory ( ) . getGraph ( database , false ) ; if ( autoStartTx && autoTxStartRequired ( database ) ) g . begin ( ) ; return g ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the RETRY number of times [CODESPLIT] protected void parseRetry ( ) throws OCommandSQLParsingException { retry = Integer . parseInt ( parserNextWord ( true ) ) ; String temp = parseOptionalWord ( true ) ; if ( temp . equals ( \"WAIT\" ) ) { wait = Integer . parseInt ( parserNextWord ( true ) ) ; } else parserGoBack ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Resets the sequence value to it s initialized value . [CODESPLIT] long reset ( boolean executeViaDistributed ) throws ODatabaseException { long retVal ; if ( executeViaDistributed ) { try { retVal = sendSequenceActionOverCluster ( OSequenceAction . RESET , null ) ; } catch ( InterruptedException | ExecutionException exc ) { OLogManager . instance ( ) . error ( this , exc . getMessage ( ) , exc , ( Object [ ] ) null ) ; throw new ODatabaseException ( exc . getMessage ( ) ) ; } } else { retVal = resetWork ( ) ; } return retVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the record . [CODESPLIT] public ORecord saveRecord ( final ORecord iRecord , final String iClusterName , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { try { return database . saveAll ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; } catch ( Exception e ) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS\r final ORecordId rid = ( ORecordId ) iRecord . getIdentity ( ) ; if ( rid . isValid ( ) ) database . getLocalCache ( ) . freeRecord ( rid ) ; if ( e instanceof ONeedRetryException ) throw ( ONeedRetryException ) e ; throw OException . wrapException ( new ODatabaseException ( \"Error during saving of record\" + ( iRecord != null ? \" with rid \" + iRecord . getIdentity ( ) : \"\" ) ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the record . [CODESPLIT] public void deleteRecord ( final ORecord iRecord , final OPERATION_MODE iMode ) { if ( ! iRecord . getIdentity ( ) . isPersistent ( ) ) return ; try { database . executeDeleteRecord ( iRecord , iRecord . getVersion ( ) , true , iMode , false ) ; } catch ( Exception e ) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS\r final ORecordId rid = ( ORecordId ) iRecord . getIdentity ( ) ; if ( rid . isValid ( ) ) database . getLocalCache ( ) . freeRecord ( rid ) ; if ( e instanceof RuntimeException ) throw ( RuntimeException ) e ; throw OException . wrapException ( new ODatabaseException ( \"Error during deletion of record\" + ( iRecord != null ? \" with rid \" + iRecord . getIdentity ( ) : \"\" ) ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OSecurityComponent [CODESPLIT] public void config ( final OServer oServer , final OServerConfigurationManager serverCfg , final ODocument jsonConfig ) { server = oServer ; serverConfig = serverCfg ; if ( jsonConfig . containsField ( \"name\" ) ) { name = jsonConfig . field ( \"name\" ) ; } if ( jsonConfig . containsField ( \"debug\" ) ) { debug = jsonConfig . field ( \"debug\" ) ; } if ( jsonConfig . containsField ( \"enabled\" ) ) { enabled = jsonConfig . field ( \"enabled\" ) ; } if ( jsonConfig . containsField ( \"caseSensitive\" ) ) { caseSensitive = jsonConfig . field ( \"caseSensitive\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "databaseName may be null . [CODESPLIT] public String getAuthenticationHeader ( String databaseName ) { String header ; // Default to Basic. if ( databaseName != null ) header = \"WWW-Authenticate: Basic realm=\\\"OrientDB db-\" + databaseName + \"\\\"\" ; else header = \"WWW-Authenticate: Basic realm=\\\"OrientDB Server\\\"\" ; return header ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OSecurityComponent [CODESPLIT] public void config ( final OServer oServer , final OServerConfigurationManager serverCfg , final ODocument jsonConfig ) { super . config ( oServer , serverCfg , jsonConfig ) ; try { } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"config()\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will authenticate username using the system database . [CODESPLIT] public String authenticate ( final String username , final String password ) { String principal = null ; try { if ( getServer ( ) != null ) { // dbName parameter is null because we don't need to filter any roles for this. OUser user = getServer ( ) . getSecurity ( ) . getSystemUser ( username , null ) ; if ( user != null && user . getAccountStatus ( ) == OSecurityUser . STATUSES . ACTIVE ) { if ( user . checkPassword ( password ) ) principal = username ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"authenticate()\" , ex ) ; } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if a [CODESPLIT] public boolean isAuthorized ( final String username , final String resource ) { if ( username == null || resource == null ) return false ; try { if ( getServer ( ) != null ) { OUser user = getServer ( ) . getSecurity ( ) . getSystemUser ( username , null ) ; if ( user != null && user . getAccountStatus ( ) == OSecurityUser . STATUSES . ACTIVE ) { ORole role = null ; ORule . ResourceGeneric rg = ORule . mapLegacyResourceToGenericResource ( resource ) ; if ( rg != null ) { String specificResource = ORule . mapLegacyResourceToSpecificResource ( resource ) ; if ( specificResource == null || specificResource . equals ( \"*\" ) ) { specificResource = null ; } role = user . checkIfAllowed ( rg , specificResource , ORole . PERMISSION_EXECUTE ) ; } return role != null ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"isAuthorized()\" , ex ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OSecurityAuthenticator [CODESPLIT] public OServerUserConfiguration getUser ( final String username ) { OServerUserConfiguration userCfg = null ; try { if ( getServer ( ) != null ) { OUser user = getServer ( ) . getSecurity ( ) . getSystemUser ( username , null ) ; if ( user != null && user . getAccountStatus ( ) == OSecurityUser . STATUSES . ACTIVE ) { userCfg = new OServerUserConfiguration ( user . getName ( ) , \"\" , \"\" ) ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"getUser()\" , ex ) ; } return userCfg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Catch the JVM exit and assure to shutdown the Orient Server . [CODESPLIT] @ Override public void run ( ) { if ( server != null ) if ( ! server . shutdown ( ) ) { // ALREADY IN SHUTDOWN, WAIT FOR 5 SEC MORE\r try { Thread . sleep ( 5000 ) ; } catch ( InterruptedException e ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reinitialise . [CODESPLIT] public void ReInit ( java . io . Reader dstream , int startline , int startcolumn , int buffersize ) { inputStream = dstream ; line = startline ; column = startcolumn - 1 ; if ( buffer == null || buffersize != buffer . length ) { available = bufsize = buffersize ; buffer = new char [ buffersize ] ; bufline = new int [ buffersize ] ; bufcolumn = new int [ buffersize ] ; nextCharBuf = new char [ 4096 ] ; } prevCharIsLF = prevCharIsCR = false ; tokenBegin = inBuf = maxNextCharInd = 0 ; nextCharInd = bufpos = - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reinitialise . [CODESPLIT] public void ReInit ( java . io . Reader dstream , int startline , int startcolumn ) { ReInit ( dstream , startline , startcolumn , 4096 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reinitialise . [CODESPLIT] public void ReInit ( java . io . InputStream dstream , String encoding , int startline , int startcolumn , int buffersize ) throws java . io . UnsupportedEncodingException { ReInit ( encoding == null ? new java . io . InputStreamReader ( dstream ) : new java . io . InputStreamReader ( dstream , encoding ) , startline , startcolumn , buffersize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reinitialise . [CODESPLIT] public void ReInit ( java . io . InputStream dstream , int startline , int startcolumn , int buffersize ) { ReInit ( new java . io . InputStreamReader ( dstream ) , startline , startcolumn , buffersize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reinitialise . [CODESPLIT] public void ReInit ( java . io . InputStream dstream , String encoding , int startline , int startcolumn ) throws java . io . UnsupportedEncodingException { ReInit ( dstream , encoding , startline , startcolumn , 4096 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reinitialise . [CODESPLIT] public void ReInit ( java . io . InputStream dstream , int startline , int startcolumn ) { ReInit ( dstream , startline , startcolumn , 4096 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to adjust line and column numbers for the start of a token . [CODESPLIT] public void adjustBeginLineColumn ( int newLine , int newCol ) { int start = tokenBegin ; int len ; if ( bufpos >= tokenBegin ) { len = bufpos - tokenBegin + inBuf + 1 ; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf ; } int i = 0 , j = 0 , k = 0 ; int nextColDiff = 0 , columnDiff = 0 ; while ( i < len && bufline [ j = start % bufsize ] == bufline [ k = ++ start % bufsize ] ) { bufline [ j ] = newLine ; nextColDiff = columnDiff + bufcolumn [ k ] - bufcolumn [ j ] ; bufcolumn [ j ] = newCol + columnDiff ; columnDiff = nextColDiff ; i ++ ; } if ( i < len ) { bufline [ j ] = newLine ++ ; bufcolumn [ j ] = newCol + columnDiff ; while ( i ++ < len ) { if ( bufline [ j = start % bufsize ] != bufline [ ++ start % bufsize ] ) bufline [ j ] = newLine ++ ; else bufline [ j ] = newLine ; } } line = bufline [ j ] ; column = bufcolumn [ j ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( OCompositeKey object , ByteBuffer buffer , Object ... hints ) { final OType [ ] types = getKeyTypes ( hints ) ; final List < Object > keys = object . getKeys ( ) ; final int keysSize = keys . size ( ) ; final int oldStartOffset = buffer . position ( ) ; buffer . position ( oldStartOffset + OIntegerSerializer . INT_SIZE ) ; buffer . putInt ( keysSize ) ; final OBinarySerializerFactory factory = OBinarySerializerFactory . getInstance ( ) ; for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { final Object key = keys . get ( i ) ; OBinarySerializer < Object > binarySerializer ; if ( key != null ) { final OType type ; if ( types . length > i ) type = types [ i ] ; else type = OType . getTypeByClass ( key . getClass ( ) ) ; binarySerializer = factory . getObjectSerializer ( type ) ; } else binarySerializer = ONullSerializer . INSTANCE ; buffer . put ( binarySerializer . getId ( ) ) ; binarySerializer . serializeInByteBufferObject ( key , buffer ) ; } final int finalPosition = buffer . position ( ) ; final int serializedSize = buffer . position ( ) - oldStartOffset ; buffer . position ( oldStartOffset ) ; buffer . putInt ( serializedSize ) ; buffer . position ( finalPosition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OCompositeKey deserializeFromByteBufferObject ( ByteBuffer buffer ) { final OCompositeKey compositeKey = new OCompositeKey ( ) ; buffer . position ( buffer . position ( ) + OIntegerSerializer . INT_SIZE ) ; final int keysSize = buffer . getInt ( ) ; final OBinarySerializerFactory factory = OBinarySerializerFactory . getInstance ( ) ; for ( int i = 0 ; i < keysSize ; i ++ ) { final byte serializerId = buffer . get ( ) ; @ SuppressWarnings ( \"unchecked\" ) OBinarySerializer < Object > binarySerializer = ( OBinarySerializer < Object > ) factory . getObjectSerializer ( serializerId ) ; final Object key = binarySerializer . deserializeFromByteBufferObject ( buffer ) ; compositeKey . addKey ( key ) ; } return compositeKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OCompositeKey deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final OCompositeKey compositeKey = new OCompositeKey ( ) ; offset += OIntegerSerializer . INT_SIZE ; final int keysSize = walChanges . getIntValue ( buffer , offset ) ; offset += OIntegerSerializer . INT_SIZE ; final OBinarySerializerFactory factory = OBinarySerializerFactory . getInstance ( ) ; for ( int i = 0 ; i < keysSize ; i ++ ) { final byte serializerId = walChanges . getByteValue ( buffer , offset ) ; offset += OBinarySerializerFactory . TYPE_IDENTIFIER_SIZE ; @ SuppressWarnings ( \"unchecked\" ) OBinarySerializer < Object > binarySerializer = ( OBinarySerializer < Object > ) factory . getObjectSerializer ( serializerId ) ; final Object key = binarySerializer . deserializeFromByteBufferObject ( buffer , walChanges , offset ) ; compositeKey . addKey ( key ) ; offset += binarySerializer . getObjectSize ( key ) ; } return compositeKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a bucket pointer to specific location . [CODESPLIT] protected void setBucketPointer ( int pageOffset , OBonsaiBucketPointer value ) throws IOException { setLongValue ( pageOffset , value . getPageIndex ( ) ) ; setIntValue ( pageOffset + OLongSerializer . LONG_SIZE , value . getPageOffset ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read bucket pointer from page . [CODESPLIT] protected OBonsaiBucketPointer getBucketPointer ( int offset ) { final long pageIndex = getLongValue ( offset ) ; final int pageOffset = getIntValue ( offset + OLongSerializer . LONG_SIZE ) ; return new OBonsaiBucketPointer ( pageIndex , pageOffset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public OClass truncateCluster ( String clusterName ) { getDatabase ( ) . checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_DELETE , name ) ; acquireSchemaReadLock ( ) ; try { final ODatabaseDocumentInternal database = getDatabase ( ) ; truncateClusterInternal ( clusterName , database ) ; } finally { releaseSchemaReadLock ( ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts atomic operation inside of current thread . If atomic operation has been already started current atomic operation instance will be returned . All durable components have to call this method at the beginning of any data modification operation . <p > In current implementation of atomic operation each component which is participated in atomic operation is hold under exclusive lock till atomic operation will not be completed ( committed or rolled back ) . <p > If other thread is going to read data from component it has to acquire read lock inside of atomic operation manager { @link #acquireReadLock ( ODurableComponent ) } otherwise data consistency will be compromised . <p > Atomic operation may be delayed if start of atomic operations is prohibited by call of { @link #freezeAtomicOperations ( Class String ) } method . If mentioned above method is called then execution of current method will be stopped till call of { @link #releaseAtomicOperations ( long ) } method or exception will be thrown . Concrete behaviour depends on real values of parameters of { @link #freezeAtomicOperations ( Class String ) } method . [CODESPLIT] public OAtomicOperation startAtomicOperation ( String lockName , boolean trackNonTxOperations ) throws IOException { OAtomicOperation operation = currentOperation . get ( ) ; if ( operation != null ) { operation . incrementCounter ( ) ; if ( lockName != null ) { acquireExclusiveLockTillOperationComplete ( operation , lockName ) ; } return operation ; } atomicOperationsCount . increment ( ) ; while ( freezeRequests . get ( ) > 0 ) { assert freezeRequests . get ( ) >= 0 ; atomicOperationsCount . decrement ( ) ; throwFreezeExceptionIfNeeded ( ) ; final Thread thread = Thread . currentThread ( ) ; addThreadInWaitingList ( thread ) ; if ( freezeRequests . get ( ) > 0 ) { LockSupport . park ( this ) ; } atomicOperationsCount . increment ( ) ; } assert freezeRequests . get ( ) >= 0 ; final boolean useWal = useWal ( ) ; final OOperationUnitId unitId = OOperationUnitId . generateId ( ) ; final OLogSequenceNumber lsn = useWal ? writeAheadLog . logAtomicOperationStartRecord ( true , unitId ) : null ; operation = new OAtomicOperation ( lsn , unitId , readCache , writeCache , storage . getId ( ) ) ; currentOperation . set ( operation ) ; if ( trackAtomicOperations ) { final Thread thread = Thread . currentThread ( ) ; activeAtomicOperations . put ( unitId , new OPair <> ( thread . getName ( ) , thread . getStackTrace ( ) ) ) ; } if ( useWal && trackNonTxOperations && storage . getStorageTransaction ( ) == null ) { writeAheadLog . log ( new ONonTxOperationPerformedWALRecord ( ) ) ; } if ( lockName != null ) { acquireExclusiveLockTillOperationComplete ( operation , lockName ) ; } try { storage . checkReadOnlyConditions ( ) ; } catch ( RuntimeException | Error e ) { final Iterator < String > lockedObjectIterator = operation . lockedObjects ( ) . iterator ( ) ; while ( lockedObjectIterator . hasNext ( ) ) { final String lockedObject = lockedObjectIterator . next ( ) ; lockedObjectIterator . remove ( ) ; lockManager . releaseLock ( this , lockedObject , OOneEntryPerKeyLockManager . LOCK . EXCLUSIVE ) ; } throw e ; } return operation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ends the current atomic operation on this manager . [CODESPLIT] public OLogSequenceNumber endAtomicOperation ( boolean rollback ) throws IOException { final OAtomicOperation operation = currentOperation . get ( ) ; if ( operation == null ) { OLogManager . instance ( ) . error ( this , \"There is no atomic operation active\" , null ) ; throw new ODatabaseException ( \"There is no atomic operation active\" ) ; } int counter = operation . getCounter ( ) ; operation . decrementCounter ( ) ; assert counter > 0 ; final OLogSequenceNumber lsn ; try { if ( rollback ) { operation . rollback ( ) ; } if ( counter == 1 ) { try { final boolean useWal = useWal ( ) ; if ( ! operation . isRollback ( ) ) { lsn = operation . commitChanges ( useWal ? writeAheadLog : null ) ; } else { lsn = null ; } if ( trackAtomicOperations ) { activeAtomicOperations . remove ( operation . getOperationUnitId ( ) ) ; } } finally { final Iterator < String > lockedObjectIterator = operation . lockedObjects ( ) . iterator ( ) ; while ( lockedObjectIterator . hasNext ( ) ) { final String lockedObject = lockedObjectIterator . next ( ) ; lockedObjectIterator . remove ( ) ; lockManager . releaseLock ( this , lockedObject , OOneEntryPerKeyLockManager . LOCK . EXCLUSIVE ) ; } currentOperation . set ( null ) ; } } else { lsn = null ; } } catch ( Error e ) { final OAbstractPaginatedStorage st = storage ; if ( st != null ) { st . handleJVMError ( e ) ; } counter = 1 ; throw e ; } finally { if ( counter == 1 ) { atomicOperationsCount . decrement ( ) ; } } return lsn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires exclusive lock with the given lock name in the given atomic operation . [CODESPLIT] public void acquireExclusiveLockTillOperationComplete ( OAtomicOperation operation , String lockName ) { if ( operation . containsInLockedObjects ( lockName ) ) { return ; } lockManager . acquireLock ( lockName , OOneEntryPerKeyLockManager . LOCK . EXCLUSIVE ) ; operation . addLockedObject ( lockName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires exclusive lock in the active atomic operation running on the current thread for the { [CODESPLIT] public void acquireExclusiveLockTillOperationComplete ( ODurableComponent durableComponent ) { final OAtomicOperation operation = currentOperation . get ( ) ; assert operation != null ; acquireExclusiveLockTillOperationComplete ( operation , durableComponent . getLockName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes amount of memory which may be used by given cache . This method may consume many resources if amount of memory provided in parameter is much less than current amount of memory . [CODESPLIT] public void changeMaximumAmountOfMemory ( final long readCacheMaxMemory ) throws IllegalStateException { MemoryData memoryData ; MemoryData newMemoryData ; final int newMemorySize = normalizeMemory ( readCacheMaxMemory , pageSize ) ; do { memoryData = memoryDataContainer . get ( ) ; if ( memoryData . maxSize == newMemorySize ) { return ; } if ( ( 100 * memoryData . pinnedPages / newMemorySize ) > percentOfPinnedPages ) { throw new IllegalStateException ( \"Cannot decrease amount of memory used by disk cache \" + \"because limit of pinned pages will be more than allowed limit \" + percentOfPinnedPages ) ; } newMemoryData = new MemoryData ( newMemorySize , memoryData . pinnedPages ) ; } while ( ! memoryDataContainer . compareAndSet ( memoryData , newMemoryData ) ) ; //    if (newMemorySize < memoryData.maxSize) //      removeColdestPagesIfNeeded(); OLogManager . instance ( ) . info ( this , \"Disk cache size was changed from \" + memoryData . maxSize + \" pages to \" + newMemorySize + \" pages\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs following steps : <ol > <li > If flag { @link OGlobalConfiguration#STORAGE_KEEP_DISK_CACHE_STATE } is set to <code > true< / code > saves state of all queues of 2Q cache into file { @link #CACHE_STATE_FILE } . The only exception is pinned pages they need to pinned again . < / li > <li > Closes all files and flushes all data associated to them . < / li > < / ol > [CODESPLIT] @ Override public final void closeStorage ( final OWriteCache writeCache ) throws IOException { if ( writeCache == null ) { return ; } cacheLock . acquireWriteLock ( ) ; try { final long [ ] filesToClear = writeCache . close ( ) ; clearFiles ( writeCache , filesToClear ) ; } finally { cacheLock . releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores state of queues of 2Q cache inside of { @link #CACHE_STATE_FILE } file if flag { @link OGlobalConfiguration#STORAGE_KEEP_DISK_CACHE_STATE } is set to <code > true< / code > . Following format is used to store queue state : <ol > <li > Max cache size single item ( long ) < / li > <li > File id or - 1 if end of queue is reached ( int ) < / li > <li > Page index ( long ) is absent if end of the queue is reached< / li > < / ol > [CODESPLIT] @ Override public final void storeCacheState ( final OWriteCache writeCache ) { if ( ! OGlobalConfiguration . STORAGE_KEEP_DISK_CACHE_STATE . getValueAsBoolean ( ) ) { return ; } if ( writeCache == null ) { return ; } cacheLock . acquireWriteLock ( ) ; try { final Path rootDirectory = writeCache . getRootDirectory ( ) ; final Path stateFile = rootDirectory . resolve ( CACHE_STATE_FILE ) ; if ( Files . exists ( stateFile ) ) { Files . delete ( stateFile ) ; } final Set < Long > filesToStore = new HashSet <> ( writeCache . files ( ) . values ( ) ) ; try ( final FileChannel channel = FileChannel . open ( stateFile , StandardOpenOption . WRITE , StandardOpenOption . CREATE ) ) { final OutputStream channelStream = Channels . newOutputStream ( channel ) ; final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream ( channelStream , 64 * 1024 ) ; try ( final DataOutputStream dataOutputStream = new DataOutputStream ( bufferedOutputStream ) ) { dataOutputStream . writeLong ( memoryDataContainer . get ( ) . maxSize ) ; storeQueueState ( writeCache , filesToStore , dataOutputStream , am ) ; dataOutputStream . writeInt ( - 1 ) ; storeQueueState ( writeCache , filesToStore , dataOutputStream , a1in ) ; dataOutputStream . writeInt ( - 1 ) ; storeQueueState ( writeCache , filesToStore , dataOutputStream , a1out ) ; dataOutputStream . writeInt ( - 1 ) ; } } } catch ( final Exception e ) { OLogManager . instance ( ) . error ( this , \"Cannot store state of cache for storage placed under %s\" , e , writeCache . getRootDirectory ( ) ) ; } finally { cacheLock . releaseWriteLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores state of single queue to the { @link OutputStream } . Items are stored from least recently used to most recently used so in case of sequential read of data we will restore the same state of queue . Not all queue items are stored only ones which contains pages of selected files . Following format is used to store queue state : <ol > <li > File id or - 1 if end of queue is reached ( int ) < / li > <li > Page index ( long ) is absent if end of the queue is reached< / li > < / ol > [CODESPLIT] private static void storeQueueState ( final OWriteCache writeCache , final Set < Long > filesToStore , final DataOutputStream dataOutputStream , final LRUList queue ) throws IOException { final Iterator < OCacheEntry > queueIterator = queue . reverseIterator ( ) ; while ( queueIterator . hasNext ( ) ) { final OCacheEntry cacheEntry = queueIterator . next ( ) ; final long fileId = cacheEntry . getFileId ( ) ; if ( filesToStore . contains ( fileId ) ) { final int internalId = writeCache . internalFileId ( fileId ) ; dataOutputStream . writeInt ( internalId ) ; dataOutputStream . writeLong ( cacheEntry . getPageIndex ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a server socket for communicating with the client . [CODESPLIT] private void listen ( final String iHostName , final String iHostPortRange , final String iProtocolName , Class < ? extends ONetworkProtocol > protocolClass ) { for ( int port : getPorts ( iHostPortRange ) ) { inboundAddr = new InetSocketAddress ( iHostName , port ) ; try { serverSocket = socketFactory . createServerSocket ( port , 0 , InetAddress . getByName ( iHostName ) ) ; if ( serverSocket . isBound ( ) ) { OLogManager . instance ( ) . info ( this , \"Listening $ANSI{green \" + iProtocolName + \"} connections on $ANSI{green \" + inboundAddr . getAddress ( ) . getHostAddress ( ) + \":\" + inboundAddr . getPort ( ) + \"} (protocol v.\" + protocolVersion + \", socket=\" + socketFactory . getName ( ) + \")\" ) ; return ; } } catch ( BindException be ) { OLogManager . instance ( ) . warn ( this , \"Port %s:%d busy, trying the next available...\" , iHostName , port ) ; } catch ( SocketException se ) { OLogManager . instance ( ) . error ( this , \"Unable to create socket\" , se ) ; throw new RuntimeException ( se ) ; } catch ( IOException ioe ) { OLogManager . instance ( ) . error ( this , \"Unable to read data from an open socket\" , ioe ) ; System . err . println ( \"Unable to read data from an open socket.\" ) ; throw new RuntimeException ( ioe ) ; } } OLogManager . instance ( ) . error ( this , \"Unable to listen for connections using the configured ports '%s' on host '%s'\" , null , iHostPortRange , iHostName ) ; throw new OSystemException ( \"Unable to listen for connections using the configured ports '%s' on host '%s'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes connection parameters by the reading XML configuration . If not specified get the parameters defined as global configuration . [CODESPLIT] private void readParameters ( final OContextConfiguration iServerConfig , final OServerParameterConfiguration [ ] iParameters ) { configuration = new OContextConfiguration ( iServerConfig ) ; // SET PARAMETERS\r if ( iParameters != null && iParameters . length > 0 ) { // CONVERT PARAMETERS IN MAP TO INTIALIZE THE CONTEXT-CONFIGURATION\r for ( OServerParameterConfiguration param : iParameters ) configuration . setValue ( param . name , param . value ) ; } socketBufferSize = configuration . getValueAsInteger ( OGlobalConfiguration . NETWORK_SOCKET_BUFFER_SIZE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start filter out all messages which are logged using { [CODESPLIT] public void applyStorageFilter ( ) { final StorageFilter filter = new StorageFilter ( ) ; if ( storageFilterHolder . compareAndSet ( null , filter ) ) { for ( Logger logger : loggersCache . values ( ) ) { logger . setFilter ( filter ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdowns this log manager . [CODESPLIT] public void shutdown ( ) { if ( shutdownFlag . compareAndSet ( false , true ) ) { try { if ( LogManager . getLogManager ( ) instanceof ShutdownLogManager ) ( ( ShutdownLogManager ) LogManager . getLogManager ( ) ) . shutdown ( ) ; } catch ( NoClassDefFoundError ignore ) { // Om nom nom. Some custom class loaders, like Tomcat's one, cannot load classes while in shutdown hooks, since their // runtime is already shutdown. Ignoring the exception, if ShutdownLogManager is not loaded at this point there are no instances // of it anyway and we have nothing to shutdown. } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds item to the container . Item should be in open state . [CODESPLIT] public void add ( K key , V item ) throws InterruptedException { if ( ! item . isOpen ( ) ) throw new IllegalArgumentException ( \"All passed in items should be in open state\" ) ; checkOpenFilesLimit ( ) ; final OClosableEntry < K , V > closableEntry = new OClosableEntry < K , V > ( item ) ; final OClosableEntry < K , V > oldEntry = data . putIfAbsent ( key , closableEntry ) ; if ( oldEntry != null ) { throw new IllegalStateException ( \"Item with key \" + key + \" already exists\" ) ; } logAdd ( closableEntry ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes item associated with passed in key . [CODESPLIT] public V remove ( K key ) { final OClosableEntry < K , V > removed = data . remove ( key ) ; if ( removed != null ) { long preStatus = removed . makeRetired ( ) ; if ( OClosableEntry . isOpen ( preStatus ) ) { countClosedFiles ( ) ; } logRemoved ( removed ) ; return removed . get ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires item associated with passed in key in container . It is guarantied that item will not be closed if limit of open items will be exceeded and container will close rarely used items . [CODESPLIT] public OClosableEntry < K , V > acquire ( K key ) throws InterruptedException { checkOpenFilesLimit ( ) ; final OClosableEntry < K , V > entry = data . get ( key ) ; if ( entry == null ) return null ; boolean logOpen = false ; entry . acquireStateLock ( ) ; try { if ( entry . isRetired ( ) || entry . isDead ( ) ) { return null ; } else if ( entry . isClosed ( ) ) { entry . makeAcquiredFromClosed ( entry . get ( ) ) ; logOpen = true ; } else if ( entry . isOpen ( ) ) { entry . makeAcquiredFromOpen ( ) ; } else { entry . incrementAcquired ( ) ; } } finally { entry . releaseStateLock ( ) ; } if ( logOpen ) { logOpen ( entry ) ; } else { logAcquire ( entry ) ; } assert entry . get ( ) . isOpen ( ) ; return entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if containers limit of open files is reached . <p > In such case execution of threads which add or acquire items is stopped and they wait till buffers will be emptied and nubmer of open files will be inside limit . [CODESPLIT] private void checkOpenFilesLimit ( ) throws InterruptedException { CountDownLatch ol = openLatch . get ( ) ; if ( ol != null ) ol . await ( ) ; while ( openFiles . get ( ) > openLimit ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; //make other threads to wait till we evict entries and close evicted open files if ( openLatch . compareAndSet ( null , latch ) ) { while ( openFiles . get ( ) > openLimit ) { emptyBuffers ( ) ; } latch . countDown ( ) ; openLatch . set ( null ) ; } else { ol = openLatch . get ( ) ; if ( ol != null ) ol . await ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns item without acquiring it . State of item is not guarantied in such case . [CODESPLIT] public V get ( K key ) { final OClosableEntry < K , V > entry = data . get ( key ) ; if ( entry != null ) return entry . get ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears all content . [CODESPLIT] public void clear ( ) { lruLock . lock ( ) ; try { data . clear ( ) ; openFiles . set ( 0 ) ; for ( int n = 0 ; n < NUMBER_OF_READ_BUFFERS ; n ++ ) { final AtomicReference < OClosableEntry < K , V > > [ ] buffer = readBuffers [ n ] ; for ( int i = 0 ; i < READ_BUFFER_SIZE ; i ++ ) { buffer [ i ] . set ( null ) ; } readBufferReadCount [ n ] = 0 ; readBufferWriteCount [ n ] . set ( 0 ) ; readBufferDrainAtWriteCount [ n ] . set ( 0 ) ; } stateBuffer . clear ( ) ; while ( lruList . poll ( ) != null ) ; } finally { lruLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes item related to passed in key . Item will be closed if it exists and is not acquired . [CODESPLIT] public boolean close ( K key ) { emptyBuffers ( ) ; final OClosableEntry < K , V > entry = data . get ( key ) ; if ( entry == null ) return true ; if ( entry . makeClosed ( ) ) { countClosedFiles ( ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read content of write buffer and adds / removes LRU entries to update internal statistic . Method has to be wrapped by LRU lock . [CODESPLIT] private void emptyWriteBuffer ( ) { Runnable task = stateBuffer . poll ( ) ; while ( task != null ) { task . run ( ) ; task = stateBuffer . poll ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read content of all read buffers and reorder elements inside of LRU list to update internal statistic . Method has to be wrapped by LRU lock . [CODESPLIT] private void emptyReadBuffers ( ) { for ( int n = 0 ; n < NUMBER_OF_READ_BUFFERS ; n ++ ) { AtomicReference < OClosableEntry < K , V > > [ ] buffer = readBuffers [ n ] ; long writeCount = readBufferDrainAtWriteCount [ n ] . get ( ) ; long counter = readBufferReadCount [ n ] ; while ( true ) { final int bufferIndex = ( int ) ( counter & READ_BUFFER_INDEX_MASK ) ; final AtomicReference < OClosableEntry < K , V > > eref = buffer [ bufferIndex ] ; final OClosableEntry < K , V > entry = eref . get ( ) ; if ( entry == null ) break ; applyRead ( entry ) ; counter ++ ; eref . lazySet ( null ) ; } readBufferReadCount [ n ] = counter ; readBufferDrainAtWriteCount [ n ] . lazySet ( writeCount ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method is used to log operations which change content of the container . Such changes should be flushed immediately to update content of LRU list . [CODESPLIT] private void afterWrite ( Runnable task ) { stateBuffer . add ( task ) ; drainStatus . lazySet ( DrainStatus . REQUIRED ) ; tryToDrainBuffers ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method is used to log operations which do not change LRU list content but affect order of items inside of LRU list . Such changes may be delayed till buffer will be full . [CODESPLIT] private void afterRead ( OClosableEntry < K , V > entry ) { final int bufferIndex = readBufferIndex ( ) ; final long writeCount = putEntryInReadBuffer ( entry , bufferIndex ) ; drainReadBuffersIfNeeded ( bufferIndex , writeCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds entry to the read buffer with selected index and returns amount of writes to this buffer since creation of this container . [CODESPLIT] private long putEntryInReadBuffer ( OClosableEntry < K , V > entry , int bufferIndex ) { //next index to write for this buffer AtomicLong writeCounter = readBufferWriteCount [ bufferIndex ] ; final long counter = writeCounter . get ( ) ; //we do not use CAS operations to limit contention between threads //it is normal that because of duplications of indexes some of items will be lost writeCounter . lazySet ( counter + 1 ) ; final AtomicReference < OClosableEntry < K , V > > [ ] buffer = readBuffers [ bufferIndex ] ; AtomicReference < OClosableEntry < K , V > > bufferEntry = buffer [ ( int ) ( counter & READ_BUFFER_INDEX_MASK ) ] ; bufferEntry . lazySet ( entry ) ; return counter + 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds closest power of two for given integer value . Idea is simple duplicate the most significant bit to the lowest bits for the smallest number of iterations possible and then increment result value by 1 . [CODESPLIT] private static int closestPowerOfTwo ( int value ) { int n = value - 1 ; n |= n >>> 1 ; n |= n >>> 2 ; n |= n >>> 4 ; n |= n >>> 8 ; n |= n >>> 16 ; return ( n < 0 ) ? 1 : ( n >= ( 1 << 30 ) ) ? 1 << 30 : n + 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Long object , ByteBuffer buffer , Object ... hints ) { buffer . putLong ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Long deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getLongValue ( buffer , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the push request require an unregister [CODESPLIT] public boolean onEvent ( OLiveQueryPushRequest pushRequest ) { ODatabaseDocumentInternal old = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { database . activateOnCurrentThread ( ) ; if ( pushRequest . getStatus ( ) == OLiveQueryPushRequest . ERROR ) { onError ( pushRequest . getErrorCode ( ) . newException ( pushRequest . getErrorMessage ( ) , null ) ) ; return true ; } else { for ( OLiveQueryResult result : pushRequest . getEvents ( ) ) { switch ( result . getEventType ( ) ) { case OLiveQueryResult . CREATE_EVENT : listener . onCreate ( database , result . getCurrentValue ( ) ) ; break ; case OLiveQueryResult . UPDATE_EVENT : listener . onUpdate ( database , result . getOldValue ( ) , result . getCurrentValue ( ) ) ; break ; case OLiveQueryResult . DELETE_EVENT : listener . onDelete ( database , result . getCurrentValue ( ) ) ; break ; } } if ( pushRequest . getStatus ( ) == OLiveQueryPushRequest . END ) { onEnd ( ) ; return true ; } } return false ; } finally { ODatabaseRecordThreadLocal . instance ( ) . set ( old ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - Create any object if the class has a public constructor that accepts a String as unique parameter . [CODESPLIT] public OCommandRequestText fromStream ( final byte [ ] iStream , ORecordSerializer serializer ) throws IOException { if ( iStream == null || iStream . length == 0 ) // NULL VALUE\r return null ; final int classNameSize = OBinaryProtocol . bytes2int ( iStream ) ; if ( classNameSize <= 0 ) { final String message = \"Class signature not found in ANY element: \" + Arrays . toString ( iStream ) ; OLogManager . instance ( ) . error ( this , message , null ) ; throw new OSerializationException ( message ) ; } final String className = new String ( iStream , 4 , classNameSize , \"UTF-8\" ) ; try { final OCommandRequestText stream ; // CHECK FOR ALIASES\r if ( className . equalsIgnoreCase ( \"q\" ) ) // QUERY\r stream = new OSQLSynchQuery < Object > ( ) ; else if ( className . equalsIgnoreCase ( \"c\" ) ) // SQL COMMAND\r stream = new OCommandSQL ( ) ; else if ( className . equalsIgnoreCase ( \"s\" ) ) // SCRIPT COMMAND\r stream = new OCommandScript ( ) ; else // CREATE THE OBJECT BY INVOKING THE EMPTY CONSTRUCTOR\r stream = ( OCommandRequestText ) Class . forName ( className ) . newInstance ( ) ; return stream . fromStream ( OArrays . copyOfRange ( iStream , 4 + classNameSize , iStream . length ) , serializer ) ; } catch ( Exception e ) { final String message = \"Error on unmarshalling content. Class: \" + className ; OLogManager . instance ( ) . error ( this , message , e ) ; throw OException . wrapException ( new OSerializationException ( message ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the class name size + class name + object content [CODESPLIT] public byte [ ] toStream ( final OCommandRequestText iObject ) throws IOException { if ( iObject == null ) return null ; // SERIALIZE THE CLASS NAME\r final byte [ ] className ; if ( iObject instanceof OLiveQuery < ? > ) className = iObject . getClass ( ) . getName ( ) . getBytes ( \"UTF-8\" ) ; else if ( iObject instanceof OSQLSynchQuery < ? > ) className = QUERY_COMMAND_CLASS_ASBYTES ; else if ( iObject instanceof OCommandSQL ) className = SQL_COMMAND_CLASS_ASBYTES ; else if ( iObject instanceof OCommandScript ) className = SCRIPT_COMMAND_CLASS_ASBYTES ; else { if ( iObject == null ) className = null ; else className = iObject . getClass ( ) . getName ( ) . getBytes ( \"UTF-8\" ) ; } // SERIALIZE THE OBJECT CONTENT\r byte [ ] objectContent = iObject . toStream ( ) ; byte [ ] result = new byte [ 4 + className . length + objectContent . length ] ; // COPY THE CLASS NAME SIZE + CLASS NAME + OBJECT CONTENT\r System . arraycopy ( OBinaryProtocol . int2bytes ( className . length ) , 0 , result , 0 , 4 ) ; System . arraycopy ( className , 0 , result , 4 , className . length ) ; System . arraycopy ( objectContent , 0 , result , 4 + className . length , objectContent . length ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - Create any object if the class has a public constructor that accepts a String as unique parameter . [CODESPLIT] public Object fromStream ( final String iStream ) { if ( iStream == null || iStream . length ( ) == 0 ) // NULL VALUE\r return null ; final ODocument instance = new ODocument ( ) ; try { ORecordSerializerSchemaAware2CSV . INSTANCE . fromStream ( iStream . getBytes ( \"UTF-8\" ) , instance , null ) ; } catch ( UnsupportedEncodingException e ) { throw OException . wrapException ( new OSerializationException ( \"Error decoding string\" ) , e ) ; } final String className = instance . field ( ODocumentSerializable . CLASS_NAME ) ; if ( className == null ) return instance ; Class < ? > clazz = null ; try { clazz = Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { OLogManager . instance ( ) . debug ( this , \"Class name provided in embedded document \" + className + \" does not exist.\" , e ) ; } if ( clazz == null ) return instance ; if ( ODocumentSerializable . class . isAssignableFrom ( clazz ) ) { try { final ODocumentSerializable documentSerializable = ( ODocumentSerializable ) clazz . newInstance ( ) ; final ODocument docClone = new ODocument ( ) ; instance . copyTo ( docClone ) ; docClone . removeField ( ODocumentSerializable . CLASS_NAME ) ; documentSerializable . fromDocument ( docClone ) ; return documentSerializable ; } catch ( InstantiationException e ) { throw OException . wrapException ( new OSerializationException ( \"Cannot serialize the object\" ) , e ) ; } catch ( IllegalAccessException e ) { throw OException . wrapException ( new OSerializationException ( \"Cannot serialize the object\" ) , e ) ; } } return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the class name size + class name + object content [CODESPLIT] public StringBuilder toStream ( final StringBuilder iOutput , Object iValue ) { if ( iValue != null ) { if ( iValue instanceof ODocumentSerializable ) iValue = ( ( ODocumentSerializable ) iValue ) . toDocument ( ) ; if ( ! ( iValue instanceof OSerializableStream ) ) throw new OSerializationException ( \"Cannot serialize the object since it's not implements the OSerializableStream interface\" ) ; OSerializableStream stream = ( OSerializableStream ) iValue ; iOutput . append ( iValue . getClass ( ) . getName ( ) ) ; iOutput . append ( SEPARATOR ) ; try { iOutput . append ( new String ( stream . toStream ( ) , \"UTF-8\" ) ) ; } catch ( UnsupportedEncodingException e ) { throw OException . wrapException ( new OSerializationException ( \"Error serializing embedded object\" ) , e ) ; } } return iOutput ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assure that the requested key is converted . [CODESPLIT] private void convert ( final Object iKey ) { if ( converted ) return ; if ( super . containsKey ( iKey ) ) return ; Object o = underlying . get ( String . valueOf ( iKey ) ) ; if ( o instanceof Number ) super . put ( iKey , enumClass . getEnumConstants ( ) [ ( ( Number ) o ) . intValue ( ) ] ) ; else super . put ( iKey , Enum . valueOf ( enumClass , o . toString ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts all the items [CODESPLIT] protected void convertAll ( ) { if ( converted ) return ; for ( java . util . Map . Entry < Object , Object > e : underlying . entrySet ( ) ) { if ( e . getValue ( ) instanceof Number ) super . put ( e . getKey ( ) , enumClass . getEnumConstants ( ) [ ( ( Number ) e . getValue ( ) ) . intValue ( ) ] ) ; else super . put ( e . getKey ( ) , Enum . valueOf ( enumClass , e . getValue ( ) . toString ( ) ) ) ; } converted = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain OBinarySerializer realization for the OType [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > OBinarySerializer < T > getObjectSerializer ( final OType type ) { return ( OBinarySerializer < T > ) serializerTypeMap . get ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distributed requests against the available workers by using one queue per worker . This guarantee the sequence of the operations against the same record cluster . [CODESPLIT] public void processRequest ( final ODistributedRequest request , final boolean waitForAcceptingRequests ) { if ( ! running ) { throw new ODistributedException ( \"Server is going down or is removing the database:'\" + getDatabaseName ( ) + \"' discarding\" ) ; } final ORemoteTask task = request . getTask ( ) ; if ( waitForAcceptingRequests ) { waitIsReady ( task ) ; if ( ! running ) { throw new ODistributedException ( \"Server is going down or is removing the database:'\" + getDatabaseName ( ) + \"' discarding\" ) ; } } totalReceivedRequests . incrementAndGet ( ) ; // final ODistributedMomentum lastMomentum = filterByMomentum.get(); // if (lastMomentum != null && task instanceof OAbstractReplicatedTask) { // final OLogSequenceNumber taskLastLSN = ((OAbstractReplicatedTask) task).getLastLSN(); // // final String sourceServer = manager.getNodeNameById(request.getId().getNodeId()); // final OLogSequenceNumber lastLSNFromMomentum = lastMomentum.getLSN(sourceServer); // // if (taskLastLSN != null && lastLSNFromMomentum != null && taskLastLSN.compareTo(lastLSNFromMomentum) < 0) { // // SKIP REQUEST BECAUSE CONTAINS AN OLD LSN // final String msg = String.format(\"Skipped request %s on database '%s' because %s < current %s\", request, databaseName, // taskLastLSN, lastLSNFromMomentum); // ODistributedServerLog.info(this, localNodeName, null, DIRECTION.NONE, msg); // ODistributedWorker.sendResponseBack(this, manager, request, new ODistributedException(msg)); // return; // } // } final int [ ] partitionKeys = task . getPartitionKey ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , localNodeName , task . getNodeSource ( ) , DIRECTION . IN , \"Request %s on database '%s' partitionKeys=%s task=%s\" , request , databaseName , Arrays . toString ( partitionKeys ) , task ) ; if ( partitionKeys . length > 1 || partitionKeys [ 0 ] == - 1 ) { final Set < Integer > involvedWorkerQueues ; if ( partitionKeys . length > 1 ) involvedWorkerQueues = getInvolvedQueuesByPartitionKeys ( partitionKeys ) ; else // LOCK ALL THE QUEUES involvedWorkerQueues = ALL_QUEUES ; // if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , \"Request %s on database '%s' involvedQueues=%s\" , request , databaseName , involvedWorkerQueues ) ; if ( involvedWorkerQueues . size ( ) == 1 ) // JUST ONE QUEUE INVOLVED: PROCESS IT IMMEDIATELY processRequest ( involvedWorkerQueues . iterator ( ) . next ( ) , request ) ; else { // INVOLVING MULTIPLE QUEUES // if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog . debug ( this , localNodeName , null , DIRECTION . NONE , \"Request %s on database '%s' waiting for all the previous requests to be completed\" , request , databaseName ) ; // WAIT ALL THE INVOLVED QUEUES ARE FREE AND SYNCHRONIZED final CountDownLatch syncLatch = new CountDownLatch ( involvedWorkerQueues . size ( ) ) ; final ODistributedRequest syncRequest = new ODistributedRequest ( null , request . getId ( ) . getNodeId ( ) , - 1 , databaseName , new OSynchronizedTaskWrapper ( syncLatch ) ) ; for ( int queue : involvedWorkerQueues ) { ODistributedWorker worker = workerThreads . get ( queue ) ; worker . processRequest ( syncRequest ) ; } // Make infinite timeout everytime long taskTimeout = 0 ; try { if ( taskTimeout <= 0 ) syncLatch . await ( ) ; else { // WAIT FOR COMPLETION. THE TIMEOUT IS MANAGED IN SMALLER CYCLES TO PROPERLY RECOGNIZE WHEN THE DB IS REMOVED final long start = System . currentTimeMillis ( ) ; final long cycleTimeout = Math . min ( taskTimeout , 2000 ) ; boolean locked = false ; do { if ( syncLatch . await ( cycleTimeout , TimeUnit . MILLISECONDS ) ) { // DONE locked = true ; break ; } if ( this . workerThreads . size ( ) == 0 ) // DATABASE WAS SHUTDOWN break ; } while ( System . currentTimeMillis ( ) - start < taskTimeout ) ; if ( ! locked ) { final String msg = String . format ( \"Cannot execute distributed request (%s) because all worker threads (%d) are busy (pending=%d timeout=%d)\" , request , workerThreads . size ( ) , syncLatch . getCount ( ) , taskTimeout ) ; ODistributedWorker . sendResponseBack ( this , manager , request , new ODistributedOperationException ( msg ) ) ; return ; } } } catch ( InterruptedException e ) { // IGNORE Thread . currentThread ( ) . interrupt ( ) ; final String msg = String . format ( \"Cannot execute distributed request (%s) because all worker threads (%d) are busy\" , request , workerThreads . size ( ) ) ; ODistributedWorker . sendResponseBack ( this , manager , request , new ODistributedOperationException ( msg ) ) ; return ; } // PUT THE TASK TO EXECUTE ONLY IN THE FIRST QUEUE AND PUT WAIT-FOR TASKS IN THE OTHERS. WHEN THE REAL TASK IS EXECUTED, // ALL THE OTHER TASKS WILL RETURN, SO THE QUEUES WILL BE BUSY DURING THE EXECUTION OF THE TASK. THIS AVOID CONCURRENT // EXECUTION FOR THE SAME PARTITION final CountDownLatch queueLatch = new CountDownLatch ( 1 ) ; int i = 0 ; for ( int queue : involvedWorkerQueues ) { final ODistributedRequest req ; if ( i ++ == 0 ) { // USE THE FIRST QUEUE TO PROCESS THE REQUEST final String senderNodeName = manager . getNodeNameById ( request . getId ( ) . getNodeId ( ) ) ; request . setTask ( new OSynchronizedTaskWrapper ( queueLatch , senderNodeName , task ) ) ; req = request ; } else req = new ODistributedRequest ( manager , request . getId ( ) . getNodeId ( ) , - 1 , databaseName , new OWaitForTask ( queueLatch ) ) ; workerThreads . get ( queue ) . processRequest ( req ) ; } } } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 2 ) { // ANY PARTITION: USE THE FIRST EMPTY IF ANY, OTHERWISE THE FIRST IN THE LIST boolean found = false ; for ( ODistributedWorker q : workerThreads ) { if ( q . isWaitingForNextRequest ( ) && q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // ALL THE THREADS ARE BUSY, SELECT THE FIRST EMPTY ONE for ( ODistributedWorker q : workerThreads ) { if ( q . localQueue . isEmpty ( ) ) { q . processRequest ( request ) ; found = true ; break ; } } if ( ! found ) // EXEC ON THE FIRST QUEUE workerThreads . get ( 0 ) . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 3 ) { // SERVICE - LOCK ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , \"Request %s on database '%s' dispatched to the lock worker\" , request , databaseName ) ; lockThread . processRequest ( request ) ; } else if ( partitionKeys . length == 1 && partitionKeys [ 0 ] == - 4 ) { // SERVICE - FAST_NOLOCK ODistributedServerLog . debug ( this , localNodeName , request . getTask ( ) . getNodeSource ( ) , DIRECTION . IN , \"Request %s on database '%s' dispatched to the nowait worker\" , request , databaseName ) ; nowaitThread . processRequest ( request ) ; } else { processRequest ( partitionKeys [ 0 ] , request ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add handler which will be executed during { @link #shutdown () } call . [CODESPLIT] public void addShutdownHandler ( OShutdownHandler shutdownHandler ) { engineLock . writeLock ( ) . lock ( ) ; try { shutdownHandlers . add ( shutdownHandler ) ; } finally { engineLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds shutdown handlers in order which will be used during execution of shutdown . [CODESPLIT] private void initShutdownQueue ( ) { addShutdownHandler ( new OShutdownWorkersHandler ( ) ) ; addShutdownHandler ( new OShutdownOrientDBInstancesHandler ( ) ) ; addShutdownHandler ( new OShutdownPendingThreadsHandler ( ) ) ; addShutdownHandler ( new OShutdownProfilerHandler ( ) ) ; addShutdownHandler ( new OShutdownCallListenersHandler ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdown whole OrientDB ecosystem . Usually is called during JVM shutdown by JVM shutdown handler . During shutdown all handlers which were registered by the call of { @link #addShutdownHandler ( OShutdownHandler ) } are called together with pre - registered system shoutdown handlers according to their priority . [CODESPLIT] private void registerEngines ( ) { ClassLoader classLoader = Orient . class . getClassLoader ( ) ; Iterator < OEngine > engines = OClassLoaderHelper . lookupProviderWithOrientClassLoader ( OEngine . class , classLoader ) ; OEngine engine = null ; while ( engines . hasNext ( ) ) { try { engine = engines . next ( ) ; registerEngine ( engine ) ; } catch ( IllegalArgumentException e ) { if ( engine != null ) OLogManager . instance ( ) . debug ( this , \"Failed to replace engine \" + engine . getName ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the engine by its name . [CODESPLIT] public OEngine getEngine ( final String engineName ) { engineLock . readLock ( ) . lock ( ) ; try { return engines . get ( engineName ) ; } finally { engineLock . readLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains an { @link OEngine engine } instance with the given { @code engineName } if it is { @link OEngine#isRunning () running } . [CODESPLIT] public OEngine getEngineIfRunning ( final String engineName ) { engineLock . readLock ( ) . lock ( ) ; try { final OEngine engine = engines . get ( engineName ) ; return engine == null || ! engine . isRunning ( ) ? null : engine ; } finally { engineLock . readLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains a { @link OEngine#isRunning () running } { @link OEngine engine } instance with the given { @code engineName } . If engine is not running starts it . [CODESPLIT] public OEngine getRunningEngine ( final String engineName ) { engineLock . readLock ( ) . lock ( ) ; try { OEngine engine = engines . get ( engineName ) ; if ( engine == null ) throw new IllegalStateException ( \"Engine '\" + engineName + \"' is not found.\" ) ; if ( ! engine . isRunning ( ) && ! startEngine ( engine ) ) throw new IllegalStateException ( \"Engine '\" + engineName + \"' is failed to start.\" ) ; return engine ; } finally { engineLock . readLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "new execution logic [CODESPLIT] @ Override public OResultSet executeSimple ( OCommandContext ctx ) { OResultInternal result = new OResultInternal ( ) ; result . setProperty ( \"operation\" , \"optimize database\" ) ; OStorage storage = ( ( ODatabaseInternal ) ctx . getDatabase ( ) ) . getStorage ( ) ; if ( on ) { // activate the profiler ( ( OAbstractPaginatedStorage ) storage ) . startGatheringPerformanceStatisticForCurrentThread ( ) ; result . setProperty ( \"value\" , \"on\" ) ; } else { // stop the profiler and return the stats final OSessionStoragePerformanceStatistic performanceStatistic = ( ( OAbstractPaginatedStorage ) storage ) . completeGatheringPerformanceStatisticForCurrentThread ( ) ; result . setProperty ( \"value\" , \"off\" ) ; if ( performanceStatistic != null ) { result . setProperty ( \"result\" , performanceStatistic . toDocument ( ) ) ; } else { result . setProperty ( \"result\" , \"error\" ) ; result . setProperty ( \"errorMessage\" , \"profiling of storage was not started\" ) ; } } OInternalResultSet rs = new OInternalResultSet ( ) ; rs . add ( result ) ; return rs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "old execution logic [CODESPLIT] @ Override public Object execute ( OSQLAsynchQuery < ODocument > request , OCommandContext context , OProgressListener progressListener ) { try { ODatabaseDocumentInternal db = getDatabase ( ) ; final OStorage storage = db . getStorage ( ) ; if ( on ) { // activate the profiler ( ( OAbstractPaginatedStorage ) storage ) . startGatheringPerformanceStatisticForCurrentThread ( ) ; ODocument result = new ODocument ( ) ; result . field ( \"result\" , \"OK\" ) ; request . getResultListener ( ) . result ( result ) ; } else { // stop the profiler and return the stats final OSessionStoragePerformanceStatistic performanceStatistic = ( ( OAbstractPaginatedStorage ) storage ) . completeGatheringPerformanceStatisticForCurrentThread ( ) ; if ( performanceStatistic != null ) request . getResultListener ( ) . result ( performanceStatistic . toDocument ( ) ) ; else { ODocument result = new ODocument ( ) ; result . field ( \"result\" , \"Error: profiling of storage was not started.\" ) ; request . getResultListener ( ) . result ( result ) ; } } return getResult ( request ) ; } finally { if ( request . getResultListener ( ) != null ) { request . getResultListener ( ) . end ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function should be called only from ReadersEntry . finalize () [CODESPLIT] protected void removeState ( AtomicInteger state ) { readersStateList . remove ( state ) ; readersStateArrayRef . set ( null ) ; // Paranoia: just in case someone forgot to call sharedUnlock() // and there is a Writer waiting on that state state . set ( SRWL_STATE_NOT_READING ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new ReadersEntry instance for the current thread and its associated AtomicInteger to store the state of the Reader [CODESPLIT] private ReadersEntry addState ( ) { final AtomicInteger state = new AtomicInteger ( SRWL_STATE_NOT_READING ) ; final ReadersEntry newEntry = new ReadersEntry ( state ) ; entry . set ( newEntry ) ; readersStateList . add ( state ) ; readersStateArrayRef . set ( null ) ; return newEntry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires the read lock . <p > Acquires the read lock if the write lock is not held by another thread and returns immediately . <p > If the write lock is held by another thread then the current thread yields until the write lock is released . [CODESPLIT] public void sharedLock ( ) { ReadersEntry localEntry = entry . get ( ) ; // Initialize a new Reader-state for this thread if needed if ( localEntry == null ) { localEntry = addState ( ) ; } final AtomicInteger currentReadersState = localEntry . state ; // The \"optimistic\" code path takes only two synchronized calls: // a set() on a cache line that should be held in exclusive mode // by the current thread, and a get() on a cache line that is shared. while ( true ) { currentReadersState . set ( SRWL_STATE_READING ) ; if ( ! stampedLock . isWriteLocked ( ) ) { // Acquired lock in read-only mode return ; } else { // Go back to SRWL_STATE_NOT_READING to avoid blocking a Writer currentReadersState . set ( SRWL_STATE_NOT_READING ) ; // Some (other) thread is holding the write-lock, we must wait while ( stampedLock . isWriteLocked ( ) ) { Thread . yield ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to release the read lock . <p > If the current thread is the holder of this lock then the { @code reentrantReaderCount } is decremented . If the { @code reentrantReaderCount } is now zero then the lock is released . If the current thread is not the holder of this lock then { @link IllegalMonitorStateException } is thrown . [CODESPLIT] public void sharedUnlock ( ) { final ReadersEntry localEntry = entry . get ( ) ; if ( localEntry == null ) { // ERROR: Tried to unlock a non read-locked lock throw new IllegalMonitorStateException ( ) ; } else { localEntry . state . set ( SRWL_STATE_NOT_READING ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires the write lock . <p > Acquires the write lock if neither the read nor write lock are held by another thread and returns immediately setting the write lock { [CODESPLIT] public void exclusiveLock ( ) { // Try to acquire the lock in write-mode stampedLock . writeLock ( ) ; // We can only do this after writerOwner has been set to the current thread AtomicInteger [ ] localReadersStateArray = readersStateArrayRef . get ( ) ; if ( localReadersStateArray == null ) { // Set to dummyArray before scanning the readersStateList to impose // a linearizability condition readersStateArrayRef . set ( dummyArray ) ; // Copy readersStateList to an array localReadersStateArray = readersStateList . toArray ( new AtomicInteger [ readersStateList . size ( ) ] ) ; readersStateArrayRef . compareAndSet ( dummyArray , localReadersStateArray ) ; } // Scan the array of Reader states for ( AtomicInteger readerState : localReadersStateArray ) { while ( readerState != null && readerState . get ( ) == SRWL_STATE_READING ) { Thread . yield ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires the read lock only if the write lock is not held by another thread at the time of invocation . <p > Acquires the read lock if the write lock is not held by another thread and returns immediately with the value { @code true } . <p > If the write lock is held by another thread then this method will return immediately with the value { @code false } . [CODESPLIT] public boolean sharedTryLock ( ) { ReadersEntry localEntry = entry . get ( ) ; // Initialize a new Reader-state for this thread if needed if ( localEntry == null ) { localEntry = addState ( ) ; } final AtomicInteger currentReadersState = localEntry . state ; currentReadersState . set ( SRWL_STATE_READING ) ; if ( ! stampedLock . isWriteLocked ( ) ) { // Acquired lock in read-only mode return true ; } else { // Go back to SRWL_STATE_NOT_READING and quit currentReadersState . set ( SRWL_STATE_NOT_READING ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires the read lock if the write lock is not held by another thread within the given waiting time . <p > Acquires the read lock if the write lock is not held by another thread and returns immediately with the value { @code true } . <p > If the write lock is held by another thread then the current thread yields execution until one of two things happens : <ul > <li > The read lock is acquired by the current thread ; or <li > The specified waiting time elapses . < / ul > <p > If the read lock is acquired then the value { @code true } is returned . [CODESPLIT] public boolean sharedTryLockNanos ( long nanosTimeout ) { final long lastTime = System . nanoTime ( ) ; ReadersEntry localEntry = entry . get ( ) ; // Initialize a new Reader-state for this thread if needed if ( localEntry == null ) { localEntry = addState ( ) ; } final AtomicInteger currentReadersState = localEntry . state ; while ( true ) { currentReadersState . set ( SRWL_STATE_READING ) ; if ( ! stampedLock . isWriteLocked ( ) ) { // Acquired lock in read-only mode return true ; } else { // Go back to SRWL_STATE_NOT_READING to avoid blocking a Writer // and then check if this is a downgrade. currentReadersState . set ( SRWL_STATE_NOT_READING ) ; if ( nanosTimeout <= 0 ) return false ; if ( System . nanoTime ( ) - lastTime < nanosTimeout ) { Thread . yield ( ) ; } else { return false ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires the write lock only if it is not held by another thread at the time of invocation . <p > Acquires the write lock if the write lock is not held by another thread and returns immediately with the value { @code true } if and only if no other thread is attempting a read lock setting the write lock { @code writerLoop } count to one . <p > If the current thread already holds this lock then the { @code reentrantWriterCount } count is incremented by one and the method returns { @code true } . <p > If the write lock is held by another thread then this method will return immediately with the value { @code false } . [CODESPLIT] public boolean exclusiveTryLock ( ) { // Try to acquire the lock in write-mode if ( stampedLock . tryWriteLock ( ) == 0 ) { return false ; } // We can only do this after writerOwner has been set to the current thread AtomicInteger [ ] localReadersStateArray = readersStateArrayRef . get ( ) ; if ( localReadersStateArray == null ) { // Set to dummyArray before scanning the readersStateList to impose // a linearizability condition readersStateArrayRef . set ( dummyArray ) ; // Copy readersStateList to an array localReadersStateArray = readersStateList . toArray ( new AtomicInteger [ readersStateList . size ( ) ] ) ; readersStateArrayRef . compareAndSet ( dummyArray , localReadersStateArray ) ; } // Scan the array of Reader states for ( AtomicInteger readerState : localReadersStateArray ) { if ( readerState != null && readerState . get ( ) == SRWL_STATE_READING ) { // There is at least one ongoing Reader so give up stampedLock . asWriteLock ( ) . unlock ( ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires the write lock if it is not held by another thread within the given waiting time . <p > Acquires the write lock if the write lock is not held by another thread and returns immediately with the value { @code true } if and only if no other thread is attempting a read lock setting the write lock { @code reentrantWriterCount } to one . If another thread is attempting a read lock this function <b > may yield until the read lock is released< / b > . <p > If the current thread already holds this lock then the { @code reentrantWriterCount } is incremented by one and the method returns { @code true } . <p > If the write lock is held by another thread then the current thread yields and lies dormant until one of two things happens : <ul > <li > The write lock is acquired by the current thread ; or <li > The specified waiting time elapses < / ul > <p > If the write lock is acquired then the value { @code true } is returned and the write lock { @code reentrantWriterCount } is set to one . [CODESPLIT] public boolean exclusiveTryLockNanos ( long nanosTimeout ) throws InterruptedException { final long lastTime = System . nanoTime ( ) ; // Try to acquire the lock in write-mode if ( stampedLock . tryWriteLock ( nanosTimeout , TimeUnit . NANOSECONDS ) == 0 ) { return false ; } // We can only do this after writerOwner has been set to the current thread AtomicInteger [ ] localReadersStateArray = readersStateArrayRef . get ( ) ; if ( localReadersStateArray == null ) { // Set to dummyArray before scanning the readersStateList to impose // a linearizability condition readersStateArrayRef . set ( dummyArray ) ; // Copy readersStateList to an array localReadersStateArray = readersStateList . toArray ( new AtomicInteger [ readersStateList . size ( ) ] ) ; readersStateArrayRef . compareAndSet ( dummyArray , localReadersStateArray ) ; } // Scan the array of Reader states for ( AtomicInteger readerState : localReadersStateArray ) { while ( readerState != null && readerState . get ( ) == SRWL_STATE_READING ) { if ( System . nanoTime ( ) - lastTime < nanosTimeout ) { Thread . yield ( ) ; } else { // Time has expired and there is at least one ongoing Reader so give up stampedLock . asWriteLock ( ) . unlock ( ) ; return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Token MUST be validated before being passed to this method . [CODESPLIT] public OUser authenticate ( final OToken authToken ) { final String dbName = getDatabase ( ) . getName ( ) ; if ( authToken . getIsValid ( ) != true ) { throw new OSecurityAccessException ( dbName , \"Token not valid\" ) ; } OUser user = authToken . getUser ( getDatabase ( ) ) ; if ( user == null && authToken . getUserName ( ) != null ) { // Token handler may not support returning an OUser so let's get username (subject) and query: user = getUser ( authToken . getUserName ( ) ) ; } if ( user == null ) { throw new OSecurityAccessException ( dbName , \"Authentication failed, could not load user from token\" ) ; } if ( user . getAccountStatus ( ) != STATUSES . ACTIVE ) throw new OSecurityAccessException ( dbName , \"User '\" + user . getName ( ) + \"' is not active\" ) ; return user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repairs the security structure if broken by creating the ADMIN role and user with default password . [CODESPLIT] public OUser createMetadata ( ) { final ODatabaseDocument database = getDatabase ( ) ; OClass identityClass = database . getMetadata ( ) . getSchema ( ) . getClass ( OIdentity . CLASS_NAME ) ; // SINCE 1.2.0 if ( identityClass == null ) identityClass = database . getMetadata ( ) . getSchema ( ) . createAbstractClass ( OIdentity . CLASS_NAME ) ; OClass roleClass = createOrUpdateORoleClass ( database , identityClass ) ; createOrUpdateOUserClass ( database , identityClass , roleClass ) ; // CREATE ROLES AND USERS ORole adminRole = getRole ( ORole . ADMIN ) ; if ( adminRole == null ) { adminRole = createRole ( ORole . ADMIN , ORole . ALLOW_MODES . ALLOW_ALL_BUT ) ; adminRole . addRule ( ORule . ResourceGeneric . BYPASS_RESTRICTED , null , ORole . PERMISSION_ALL ) . save ( ) ; } OUser adminUser = getUser ( OUser . ADMIN ) ; if ( adminUser == null ) { // This will return the global value if a local storage context configuration value does not exist. boolean createDefUsers = getDatabase ( ) . getStorage ( ) . getConfiguration ( ) . getContextConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . CREATE_DEFAULT_USERS ) ; if ( createDefUsers ) { adminUser = createUser ( OUser . ADMIN , OUser . ADMIN , adminRole ) ; } } // SINCE 1.2.0 createOrUpdateORestrictedClass ( database ) ; return adminUser ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Executes a traverse collecting all the result in the returning List<OIdentifiable > . This could be memory expensive because for large results the list could be huge . it s always better to use it as an Iterable and lazy fetch each result on next () call . [CODESPLIT] public List < OIdentifiable > execute ( ) { final List < OIdentifiable > result = new ArrayList < OIdentifiable > ( ) ; while ( hasNext ( ) ) result . add ( next ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke { [CODESPLIT] public static void dumpHeap ( String fileName , boolean live ) { try { MBeanServer server = ManagementFactory . getPlatformMBeanServer ( ) ; server . invoke ( new ObjectName ( HOTSPOT_BEAN_NAME ) , \"dumpHeap\" , new Object [ ] { fileName , live } , new String [ ] { String . class . getName ( ) , Boolean . TYPE . getName ( ) } ) ; } catch ( RuntimeException re ) { throw re ; } catch ( Exception exp ) { throw new RuntimeException ( exp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to acquire lock during provided interval of time and returns either if provided time interval was passed or if lock was acquired . [CODESPLIT] public boolean tryAcquireReadLock ( long timeout ) { final OModifiableInteger lHolds = lockHolds . get ( ) ; final int holds = lHolds . intValue ( ) ; if ( holds > 0 ) { // we have already acquire read lock lHolds . increment ( ) ; return true ; } else if ( holds < 0 ) { // write lock is acquired before, do nothing return true ; } distributedCounter . increment ( ) ; WNode wNode = tail . get ( ) ; final long start = System . nanoTime ( ) ; while ( wNode . locked ) { distributedCounter . decrement ( ) ; while ( wNode . locked && wNode == tail . get ( ) ) { wNode . waitingReaders . put ( Thread . currentThread ( ) , Boolean . TRUE ) ; if ( wNode . locked && wNode == tail . get ( ) ) { final long parkTimeout = timeout - ( System . nanoTime ( ) - start ) ; if ( parkTimeout > 0 ) { LockSupport . parkNanos ( this , parkTimeout ) ; } else { return false ; } } wNode = tail . get ( ) ; if ( System . nanoTime ( ) - start > timeout ) { return false ; } } distributedCounter . increment ( ) ; wNode = tail . get ( ) ; if ( System . nanoTime ( ) - start > timeout ) { distributedCounter . decrement ( ) ; return false ; } } lHolds . increment ( ) ; assert lHolds . intValue ( ) == 1 ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns true if the edge is labeled with any of the passed strings . [CODESPLIT] public static boolean isLabeled ( final String iEdgeLabel , final String [ ] iLabels ) { if ( iLabels != null && iLabels . length > 0 ) { // FILTER LABEL if ( iEdgeLabel != null ) for ( String l : iLabels ) if ( l . equals ( iEdgeLabel ) ) // FOUND return true ; // NOT FOUND return false ; } // NO LABELS return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the record label if any otherwise NULL . [CODESPLIT] public static String getRecordLabel ( final OIdentifiable iEdge ) { if ( iEdge == null ) return null ; final ODocument edge = iEdge . getRecord ( ) ; if ( edge == null ) return null ; return edge . field ( OrientElement . LABEL_FIELD_NAME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) This method does not remove connection from opposite side . [CODESPLIT] private static void removeLightweightConnection ( final ODocument iVertex , final String iFieldName , final OIdentifiable iVertexToRemove ) { if ( iVertex == null || iVertexToRemove == null ) return ; final Object fieldValue = iVertex . field ( iFieldName ) ; if ( fieldValue instanceof OIdentifiable ) { if ( fieldValue . equals ( iVertexToRemove ) ) { iVertex . removeField ( iFieldName ) ; } } else if ( fieldValue instanceof ORidBag ) { ( ( ORidBag ) fieldValue ) . remove ( iVertexToRemove ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the connected incoming or outgoing vertex . [CODESPLIT] @ Override public OrientVertex getVertex ( final Direction direction ) { final OrientBaseGraph graph = setCurrentGraphInThreadLocal ( ) ; if ( direction . equals ( Direction . OUT ) ) return graph . getVertex ( getOutVertex ( ) ) ; else if ( direction . equals ( Direction . IN ) ) return graph . getVertex ( getInVertex ( ) ) ; else throw ExceptionFactory . bothIsNotSupported ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the outgoing vertex in form of record . [CODESPLIT] public OIdentifiable getOutVertex ( ) { if ( vOut != null ) // LIGHTWEIGHT EDGE return vOut ; setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; if ( doc == null ) return null ; if ( settings != null && settings . isKeepInMemoryReferences ( ) ) // AVOID LAZY RESOLVING+SETTING OF RECORD return doc . rawField ( OrientBaseGraph . CONNECTION_OUT ) ; else return doc . field ( OrientBaseGraph . CONNECTION_OUT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the incoming vertex in form of record . [CODESPLIT] public OIdentifiable getInVertex ( ) { if ( vIn != null ) // LIGHTWEIGHT EDGE return vIn ; setCurrentGraphInThreadLocal ( ) ; final ODocument doc = getRecord ( ) ; if ( doc == null ) return null ; if ( settings != null && settings . isKeepInMemoryReferences ( ) ) // AVOID LAZY RESOLVING+SETTING OF RECORD return doc . rawField ( OrientBaseGraph . CONNECTION_IN ) ; else return doc . field ( OrientBaseGraph . CONNECTION_IN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Edge s label . By default OrientDB binds the Blueprints Label concept to Edge Class . To disable this feature execute this at database level <code > alter database custom useClassForEdgeLabel = false < / code > [CODESPLIT] @ Override public String getLabel ( ) { if ( label != null ) // LIGHTWEIGHT EDGE return label ; else if ( rawElement != null ) { if ( settings != null && settings . isUseClassForEdgeLabel ( ) ) { final String clsName = getRecord ( ) . getClassName ( ) ; if ( ! OrientEdgeType . CLASS_NAME . equals ( clsName ) ) // RETURN THE CLASS NAME return OrientBaseGraph . decodeClassName ( clsName ) ; } setCurrentGraphInThreadLocal ( ) ; final ODocument doc = rawElement . getRecord ( ) ; if ( doc == null ) return null ; final String label = doc . field ( OrientElement . LABEL_FIELD_NAME ) ; if ( label != null ) return OrientBaseGraph . decodeClassName ( label ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Edge Id assuring to save it if it s transient yet . [CODESPLIT] @ Override public Object getId ( ) { if ( rawElement == null ) // CREATE A TEMPORARY ID return vOut . getIdentity ( ) + \"->\" + vIn . getIdentity ( ) ; setCurrentGraphInThreadLocal ( ) ; return super . getId ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Property value . [CODESPLIT] @ Override public < T > T getProperty ( final String key ) { setCurrentGraphInThreadLocal ( ) ; if ( rawElement == null ) // LIGHTWEIGHT EDGE return null ; return super . getProperty ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the Property names as Set of String . out in and label are not returned as properties even if are part of the underlying document because are considered internal properties . [CODESPLIT] @ Override public Set < String > getPropertyKeys ( ) { if ( rawElement == null ) // LIGHTWEIGHT EDGE return Collections . emptySet ( ) ; setCurrentGraphInThreadLocal ( ) ; final Set < String > result = new HashSet < String > ( ) ; for ( String field : getRecord ( ) . fieldNames ( ) ) if ( ! field . equals ( OrientBaseGraph . CONNECTION_OUT ) && ! field . equals ( OrientBaseGraph . CONNECTION_IN ) && ( settings . isUseClassForEdgeLabel ( ) || ! field . equals ( OrientElement . LABEL_FIELD_NAME ) ) ) result . add ( field ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a Property value . If the edge is lightweight it s transparently transformed into a regular edge . [CODESPLIT] @ Override public void setProperty ( final String key , final Object value ) { setCurrentGraphInThreadLocal ( ) ; if ( rawElement == null ) // LIGHTWEIGHT EDGE convertToDocument ( ) ; super . setProperty ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removed a Property . [CODESPLIT] @ Override public < T > T removeProperty ( String key ) { setCurrentGraphInThreadLocal ( ) ; if ( rawElement != null ) // NON LIGHTWEIGHT EDGE return super . removeProperty ( key ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the Edge from the Graph . Connected vertices aren t removed . [CODESPLIT] @ Override public void remove ( ) { final OrientBaseGraph graph = getGraph ( ) ; if ( ! isLightweight ( ) ) checkClass ( ) ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; for ( final Index < ? extends Element > index : graph . getIndices ( ) ) { if ( Edge . class . isAssignableFrom ( index . getIndexClass ( ) ) ) { OrientIndex < OrientEdge > idx = ( OrientIndex < OrientEdge > ) index ; idx . removeElement ( this ) ; } } if ( graph != null ) graph . removeEdgeInternal ( this ) ; else // IN MEMORY CHANGES ONLY: USE NOTX CLASS OrientGraphNoTx . removeEdgeInternal ( null , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the underlying record if it s a regular edge otherwise it created a document with no identity with the edge properties . [CODESPLIT] @ Override public ODocument getRecord ( ) { if ( rawElement == null ) { // CREATE AT THE FLY final ODocument tmp = new ODocument ( getClassName ( label ) ) . setTrackingChanges ( false ) ; tmp . field ( OrientBaseGraph . CONNECTION_IN , vIn . getIdentity ( ) ) ; tmp . field ( OrientBaseGraph . CONNECTION_OUT , vOut . getIdentity ( ) ) ; if ( label != null && settings != null && ! settings . isUseClassForEdgeLabel ( ) ) tmp . field ( OrientEdge . LABEL_FIELD_NAME , label ) ; return tmp ; } return super . getRecord ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Converts the lightweight edge to a regular edge creating the underlying document to store edge s properties . [CODESPLIT] public void convertToDocument ( ) { final OrientBaseGraph graph = checkIfAttached ( ) ; if ( rawElement != null ) // ALREADY CONVERTED return ; graph . setCurrentGraphInThreadLocal ( ) ; graph . autoStartTransaction ( ) ; final ODocument vOutRecord = vOut . getRecord ( ) ; final ODocument vInRecord = vIn . getRecord ( ) ; final ODocument doc = createDocument ( label ) ; doc . field ( OrientBaseGraph . CONNECTION_OUT , settings . isKeepInMemoryReferences ( ) ? vOutRecord . getIdentity ( ) : vOutRecord ) ; doc . field ( OrientBaseGraph . CONNECTION_IN , settings . isKeepInMemoryReferences ( ) ? vInRecord . getIdentity ( ) : vInRecord ) ; rawElement = doc ; final boolean useVertexFieldsForEdgeLabels = settings . isUseVertexFieldsForEdgeLabels ( ) ; final String outFieldName = OrientVertex . getConnectionFieldName ( Direction . OUT , label , useVertexFieldsForEdgeLabels ) ; removeLightweightConnection ( vOutRecord , outFieldName , vInRecord ) ; // OUT-VERTEX ---> IN-VERTEX/EDGE OrientVertex . createLink ( graph , vOutRecord , doc , outFieldName ) ; vOutRecord . save ( ) ; final String inFieldName = OrientVertex . getConnectionFieldName ( Direction . IN , label , useVertexFieldsForEdgeLabels ) ; removeLightweightConnection ( vInRecord , inFieldName , vOutRecord ) ; // IN-VERTEX ---> OUT-VERTEX/EDGE OrientVertex . createLink ( graph , vInRecord , doc , inFieldName ) ; vInRecord . save ( ) ; vOut = null ; vIn = null ; label = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Returns the class name based on graph settings . [CODESPLIT] public String getClassName ( final String iLabel ) { if ( iLabel != null && ( settings == null || settings . isUseClassForEdgeLabel ( ) ) ) // USE THE LABEL AS DOCUMENT CLASS return checkForClassInSchema ( iLabel ) ; return OrientEdgeType . CLASS_NAME ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the ALTER DATABASE . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( attribute == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . DATABASE , ORole . PERMISSION_UPDATE ) ; database . setInternal ( attribute , value ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Date object , ByteBuffer buffer , Object ... hints ) { final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( object ) ; buffer . putLong ( calendar . getTimeInMillis ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Date deserializeFromByteBufferObject ( ByteBuffer buffer ) { final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( buffer . getLong ( ) ) ; return calendar . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Date deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( walChanges . getLongValue ( buffer , offset ) ) ; return calendar . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . SERVER , \"remove\" , ORole . PERMISSION_EXECUTE ) ; if ( ! ( database instanceof ODatabaseDocumentDistributed ) ) { throw new OCommandExecutionException ( \"OrientDB is not started in distributed mode\" ) ; } final OHazelcastPlugin dManager = ( OHazelcastPlugin ) ( ( ODatabaseDocumentDistributed ) database ) . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( \"OrientDB is not started in distributed mode\" ) ; final String databaseName = database . getName ( ) ; // The last parameter (true) indicates to set the node's database status to OFFLINE. // If this is changed to false, the node will be set to NOT_AVAILABLE, and then the auto-repairer will // re-synchronize the database on the node, and then set it to ONLINE. return dManager . removeNodeFromConfiguration ( parsedStatement . serverName . getStringValue ( ) , databaseName , false , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all entries from bonsai tree . Put all but the root page to free list for further reuse . [CODESPLIT] @ Override public void clear ( ) throws IOException { boolean rollback = false ; final OAtomicOperation atomicOperation = startAtomicOperation ( true ) ; try { final Lock lock = FILE_LOCK_MANAGER . acquireExclusiveLock ( fileId ) ; try { final Queue < OBonsaiBucketPointer > subTreesToDelete = new LinkedList <> ( ) ; final OCacheEntry cacheEntry = loadPageForWrite ( atomicOperation , fileId , rootBucketPointer . getPageIndex ( ) , false , true ) ; try { OSBTreeBonsaiBucket < K , V > rootBucket = new OSBTreeBonsaiBucket <> ( cacheEntry , rootBucketPointer . getPageOffset ( ) , keySerializer , valueSerializer , this ) ; addChildrenToQueue ( subTreesToDelete , rootBucket ) ; rootBucket . shrink ( 0 ) ; rootBucket = new OSBTreeBonsaiBucket <> ( cacheEntry , rootBucketPointer . getPageOffset ( ) , true , keySerializer , valueSerializer , this ) ; rootBucket . setTreeSize ( 0 ) ; } finally { releasePageFromWrite ( atomicOperation , cacheEntry ) ; } recycleSubTrees ( subTreesToDelete , atomicOperation ) ; } finally { lock . unlock ( ) ; } } catch ( final Exception e ) { rollback = true ; throw e ; } finally { endAtomicOperation ( rollback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes a whole tree . Puts all its pages to free list for further reusage . [CODESPLIT] @ Override public void delete ( ) throws IOException { boolean rollback = false ; final OAtomicOperation atomicOperation = startAtomicOperation ( false ) ; try { final Lock lock = FILE_LOCK_MANAGER . acquireExclusiveLock ( fileId ) ; try { final Queue < OBonsaiBucketPointer > subTreesToDelete = new LinkedList <> ( ) ; subTreesToDelete . add ( rootBucketPointer ) ; recycleSubTrees ( subTreesToDelete , atomicOperation ) ; } finally { lock . unlock ( ) ; } } catch ( final Exception e ) { rollback = true ; throw e ; } finally { endAtomicOperation ( rollback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the database ( if it does not exist ) and initializes batch operations . Call this once before starting to create vertices and edges . [CODESPLIT] public void begin ( ) { walActive = OGlobalConfiguration . USE_WAL . getValueAsBoolean ( ) ; if ( walActive ) OGlobalConfiguration . USE_WAL . setValue ( false ) ; if ( averageEdgeNumberPerNode > 0 ) { OGlobalConfiguration . RID_BAG_EMBEDDED_DEFAULT_SIZE . setValue ( averageEdgeNumberPerNode ) ; OGlobalConfiguration . RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD . setValue ( bonsaiThreshold ) ; } db = new ODatabaseDocumentTx ( dbUrl ) ; if ( db . exists ( ) ) { db . open ( userName , password ) ; } else { db . create ( ) ; } createBaseSchema ( ) ; out = estimatedEntries > 0 ? new HashMap < Long , List < Long > > ( estimatedEntries ) : new HashMap < Long , List < Long > > ( ) ; in = estimatedEntries > 0 ? new HashMap < Long , List < Long > > ( estimatedEntries ) : new HashMap < Long , List < Long > > ( ) ; OClass vClass = db . getMetadata ( ) . getSchema ( ) . getClass ( this . vertexClass ) ; int [ ] existingClusters = vClass . getClusterIds ( ) ; for ( int c = existingClusters . length ; c <= parallel ; c ++ ) { vClass . addCluster ( vClass . getName ( ) + \"_\" + c ) ; } clusterIds = vClass . getClusterIds ( ) ; lastClusterPositions = new long [ clusterIds . length ] ; for ( int i = 0 ; i < clusterIds . length ; i ++ ) { int clusterId = clusterIds [ i ] ; try { lastClusterPositions [ i ] = db . getStorage ( ) . getClusterById ( clusterId ) . getLastPosition ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flushes data to db and closes the db . Call this once after vertices and edges creation . [CODESPLIT] public void end ( ) { final OClass vClass = db . getMetadata ( ) . getSchema ( ) . getClass ( vertexClass ) ; try { runningThreads = new AtomicInteger ( parallel ) ; for ( int i = 0 ; i < parallel - 1 ; i ++ ) { Thread t = new BatchImporterJob ( i , vClass ) ; t . start ( ) ; } Thread t = new BatchImporterJob ( parallel - 1 , vClass ) ; t . run ( ) ; if ( runningThreads . get ( ) > 0 ) { synchronized ( runningThreads ) { while ( runningThreads . get ( ) > 0 ) { try { runningThreads . wait ( ) ; } catch ( InterruptedException e ) { } } } } } finally { db . activateOnCurrentThread ( ) ; db . declareIntent ( null ) ; db . close ( ) ; if ( walActive ) OGlobalConfiguration . USE_WAL . setValue ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new vertex [CODESPLIT] public void createVertex ( final Long v ) { last = last < v ? v : last ; final List < Long > outList = out . get ( v ) ; if ( outList == null ) { out . put ( v , new ArrayList < Long > ( averageEdgeNumberPerNode <= 0 ? 4 : averageEdgeNumberPerNode ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new edge between two vertices . If vertices do not exist they will be created [CODESPLIT] public void createEdge ( final Long from , final Long to ) { if ( from < 0 ) { throw new IllegalArgumentException ( \" Invalid vertex id: \" + from ) ; } if ( to < 0 ) { throw new IllegalArgumentException ( \" Invalid vertex id: \" + to ) ; } last = last < from ? from : last ; last = last < to ? to : last ; putInList ( from , out , to ) ; putInList ( to , in , from ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( rid == null && query == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; if ( ! returning . equalsIgnoreCase ( \"COUNT\" ) ) allDeletedRecords = new ArrayList < ORecord > ( ) ; txAlreadyBegun = getDatabase ( ) . getTransaction ( ) . isActive ( ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; if ( rid != null ) { // REMOVE PUNCTUAL RID db . begin ( ) ; final OVertex v = toVertex ( rid ) ; if ( v != null ) { v . delete ( ) ; removed = 1 ; } db . commit ( ) ; } else if ( query != null ) { // TARGET IS A CLASS + OPTIONAL CONDITION db . begin ( ) ; // TARGET IS A CLASS + OPTIONAL CONDITION query . setContext ( getContext ( ) ) ; query . execute ( iArgs ) ; db . commit ( ) ; } else throw new OCommandExecutionException ( \"Invalid target\" ) ; if ( returning . equalsIgnoreCase ( \"COUNT\" ) ) // RETURNS ONLY THE COUNT return removed ; else // RETURNS ALL THE DELETED RECORDS return allDeletedRecords ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the current vertex . [CODESPLIT] public boolean result ( final Object iRecord ) { final OIdentifiable id = ( OIdentifiable ) iRecord ; if ( id . getIdentity ( ) . isValid ( ) ) { final ODocument record = id . getRecord ( ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; final OVertex v = toVertex ( record ) ; if ( v != null ) { v . delete ( ) ; if ( ! txAlreadyBegun && batch > 0 && removed % batch == 0 ) { db . commit ( ) ; db . begin ( ) ; } if ( returning . equalsIgnoreCase ( \"BEFORE\" ) ) allDeletedRecords . add ( record ) ; removed ++ ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile the filter conditions only the first time . [CODESPLIT] public OCommandExecutorSQLTraverse parse ( final OCommandRequest iRequest ) { final OCommandRequestText textRequest = ( OCommandRequestText ) iRequest ; String queryText = textRequest . getText ( ) ; String originalQuery = queryText ; try { // System.out.println(\"NEW PARSER FROM: \" + queryText);\r queryText = preParse ( queryText , iRequest ) ; // System.out.println(\"NEW PARSER TO: \" + queryText);\r textRequest . setText ( queryText ) ; super . parse ( iRequest ) ; final int pos = parseFields ( ) ; if ( pos == - 1 ) throw new OCommandSQLParsingException ( \"Traverse must have the field list. Use \" + getSyntax ( ) ) ; parserSetCurrentPosition ( pos ) ; int endPosition = parserText . length ( ) ; parsedTarget = OSQLEngine . getInstance ( ) . parseTarget ( parserText . substring ( pos , endPosition ) , getContext ( ) ) ; if ( parsedTarget . parserIsEnded ( ) ) parserSetCurrentPosition ( endPosition ) ; else parserMoveCurrentPosition ( parsedTarget . parserGetCurrentPosition ( ) ) ; if ( ! parserIsEnded ( ) ) { parserNextWord ( true ) ; if ( parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_WHERE ) ) // // TODO Remove the additional management of WHERE for TRAVERSE after a while\r warnDeprecatedWhere ( ) ; if ( parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_WHERE ) || parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_WHILE ) ) { compiledFilter = OSQLEngine . getInstance ( ) . parseCondition ( parserText . substring ( parserGetCurrentPosition ( ) , endPosition ) , getContext ( ) , KEYWORD_WHILE ) ; traverse . predicate ( compiledFilter ) ; optimize ( ) ; parserSetCurrentPosition ( compiledFilter . parserIsEnded ( ) ? endPosition : compiledFilter . parserGetCurrentPosition ( ) + parserGetCurrentPosition ( ) ) ; } else parserGoBack ( ) ; } parserSkipWhiteSpaces ( ) ; while ( ! parserIsEnded ( ) ) { if ( parserOptionalKeyword ( KEYWORD_LIMIT , KEYWORD_SKIP , KEYWORD_OFFSET , KEYWORD_TIMEOUT , KEYWORD_MAXDEPTH , KEYWORD_STRATEGY ) ) { final String w = parserGetLastWord ( ) ; if ( w . equals ( KEYWORD_LIMIT ) ) parseLimit ( w ) ; else if ( w . equals ( KEYWORD_SKIP ) || w . equals ( KEYWORD_OFFSET ) ) parseSkip ( w ) ; else if ( w . equals ( KEYWORD_TIMEOUT ) ) parseTimeout ( w ) ; else if ( w . equals ( KEYWORD_MAXDEPTH ) ) parseMaxDepth ( w ) ; else if ( w . equals ( KEYWORD_STRATEGY ) ) parseStrategy ( w ) ; } } if ( limit == 0 || limit < - 1 ) throw new IllegalArgumentException ( \"Limit must be > 0 or = -1 (no limit)\" ) ; else traverse . limit ( limit ) ; traverse . getContext ( ) . setParent ( iRequest . getContext ( ) ) ; } finally { textRequest . setText ( originalQuery ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the strategy keyword if found . [CODESPLIT] protected boolean parseStrategy ( final String w ) throws OCommandSQLParsingException { if ( ! w . equals ( KEYWORD_STRATEGY ) ) return false ; final String strategyWord = parserNextWord ( true ) ; try { traverse . setStrategy ( OTraverse . STRATEGY . valueOf ( strategyWord . toUpperCase ( Locale . ENGLISH ) ) ) ; } catch ( IllegalArgumentException ignore ) { throwParsingException ( \"Invalid \" + KEYWORD_STRATEGY + \". Use one between \" + Arrays . toString ( OTraverse . STRATEGY . values ( ) ) ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( byte [ ] object , ByteBuffer buffer , Object ... hints ) { final int len = object . length ; buffer . putInt ( len ) ; buffer . put ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public byte [ ] deserializeFromByteBufferObject ( ByteBuffer buffer ) { final int len = buffer . getInt ( ) ; final byte [ ] result = new byte [ len ] ; buffer . get ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public byte [ ] deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { final int len = walChanges . getIntValue ( buffer , offset ) ; offset += OIntegerSerializer . INT_SIZE ; return walChanges . getBinaryValue ( buffer , offset , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int getObjectSizeInByteBuffer ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getIntValue ( buffer , offset ) + OIntegerSerializer . INT_SIZE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns begin position and length for each value in embedded collection [CODESPLIT] private List < RecordInfo > getPositionsFromEmbeddedCollection ( final BytesContainer bytes , int serializerVersion ) { List < RecordInfo > retList = new ArrayList <> ( ) ; int numberOfElements = OVarIntSerializer . readAsInteger ( bytes ) ; //read collection type readByte ( bytes ) ; for ( int i = 0 ; i < numberOfElements ; i ++ ) { //read element //read data type       OType dataType = readOType ( bytes , false ) ; int fieldStart = bytes . offset ; RecordInfo fieldInfo = new RecordInfo ( ) ; fieldInfo . fieldStartOffset = fieldStart ; fieldInfo . fieldType = dataType ; //TODO find better way to skip data bytes; deserializeValue ( bytes , dataType , null , true , - 1 , serializerVersion , true ) ; fieldInfo . fieldLength = bytes . offset - fieldStart ; retList . add ( fieldInfo ) ; } return retList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the INSERT and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( newRecords == null && content == null && subQuery == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final OCommandParameters commandParameters = new OCommandParameters ( iArgs ) ; if ( indexName != null ) { if ( newRecords == null ) throw new OCommandExecutionException ( \"No key/value found\" ) ; final OIndex < ? > index = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . getIndex ( indexName ) ; if ( index == null ) throw new OCommandExecutionException ( \"Target index '\" + indexName + \"' not found\" ) ; // BIND VALUES Map < String , Object > result = new HashMap < String , Object > ( ) ; for ( Map < String , Object > candidate : newRecords ) { Object indexKey = getIndexKeyValue ( commandParameters , candidate ) ; OIdentifiable indexValue = getIndexValue ( commandParameters , candidate ) ; if ( index instanceof OIndexMultiValues ) { final Collection < ORID > rids = ( ( OIndexMultiValues ) index ) . get ( indexKey ) ; if ( ! rids . contains ( indexValue . getIdentity ( ) ) ) { index . put ( indexKey , indexValue ) ; } } else { index . put ( indexKey , indexValue ) ; } result . put ( KEYWORD_KEY , indexKey ) ; result . put ( KEYWORD_RID , indexValue ) ; } // RETURN LAST ENTRY return prepareReturnItem ( new ODocument ( result ) ) ; } else { // CREATE NEW DOCUMENTS final List < ODocument > docs = new ArrayList < ODocument > ( ) ; if ( newRecords != null ) { for ( Map < String , Object > candidate : newRecords ) { final ODocument doc = className != null ? new ODocument ( className ) : new ODocument ( ) ; OSQLHelper . bindParameters ( doc , candidate , commandParameters , context ) ; saveRecord ( doc ) ; docs . add ( doc ) ; } if ( docs . size ( ) == 1 ) return prepareReturnItem ( docs . get ( 0 ) ) ; else return prepareReturnResult ( docs ) ; } else if ( content != null ) { final ODocument doc = className != null ? new ODocument ( className ) : new ODocument ( ) ; doc . merge ( content , true , false ) ; saveRecord ( doc ) ; return prepareReturnItem ( doc ) ; } else if ( subQuery != null ) { subQuery . execute ( ) ; if ( queryResult != null ) return prepareReturnResult ( queryResult ) ; return saved . longValue ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the link must be fixed . [CODESPLIT] protected boolean fixLink ( final Object fieldValue ) { if ( fieldValue instanceof OIdentifiable ) { final ORID id = ( ( OIdentifiable ) fieldValue ) . getIdentity ( ) ; if ( id . getClusterId ( ) == 0 && id . getClusterPosition ( ) == 0 ) return true ; if ( id . isValid ( ) ) if ( id . isPersistent ( ) ) { final ORecord connected = ( ( OIdentifiable ) fieldValue ) . getRecord ( ) ; if ( connected == null ) return true ; } else return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : init default value In a Java EE environment if this element is not specified the default is JTA . In a Java SE environment if this element is not specified a default of RESOURCE_LOCAL may be assumed . [CODESPLIT] public static PersistenceUnitTransactionType initTransactionType ( String elementContent ) { if ( elementContent == null || elementContent . isEmpty ( ) ) { return null ; } try { return PersistenceUnitTransactionType . valueOf ( elementContent . toUpperCase ( Locale . ENGLISH ) ) ; } catch ( IllegalArgumentException ex ) { throw new PersistenceException ( \"Unknown TransactionType: \" + elementContent , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the REMOVE INDEX . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( name == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocument database = getDatabase ( ) ; if ( name . equals ( \"*\" ) ) { long totalIndexed = 0 ; for ( OIndex < ? > idx : database . getMetadata ( ) . getIndexManager ( ) . getIndexes ( ) ) { if ( idx . isAutomatic ( ) ) totalIndexed += idx . rebuild ( ) ; } return totalIndexed ; } else { final OIndex < ? > idx = database . getMetadata ( ) . getIndexManager ( ) . getIndex ( name ) ; if ( idx == null ) throw new OCommandExecutionException ( \"Index '\" + name + \"' not found\" ) ; if ( ! idx . isAutomatic ( ) ) throw new OCommandExecutionException ( \"Cannot rebuild index '\" + name + \"' because it's manual and there aren't indications of what to index\" ) ; return idx . rebuild ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The usual password field should be a JSON representation . [CODESPLIT] public void intercept ( final String url , final String username , final String password ) throws OSecurityException { if ( username == null || username . isEmpty ( ) ) throw new OSecurityException ( \"OSymmetricKeyCI username is not valid!\" ) ; if ( password == null || password . isEmpty ( ) ) throw new OSecurityException ( \"OSymmetricKeyCI password is not valid!\" ) ; this . username = username ; // These are all used as defaults if the JSON document is missing any fields. // Defaults to \"AES\". String algorithm = OGlobalConfiguration . CLIENT_CI_KEYALGORITHM . getValueAsString ( ) ; // Defaults to \"AES/CBC/PKCS5Padding\". String transform = OGlobalConfiguration . CLIENT_CI_CIPHERTRANSFORM . getValueAsString ( ) ; String keystoreFile = OGlobalConfiguration . CLIENT_CI_KEYSTORE_FILE . getValueAsString ( ) ; String keystorePassword = OGlobalConfiguration . CLIENT_CI_KEYSTORE_PASSWORD . getValueAsString ( ) ; ODocument jsonDoc = null ; try { jsonDoc = new ODocument ( ) . fromJSON ( password , \"noMap\" ) ; } catch ( Exception ex ) { throw OException . wrapException ( new OSecurityException ( \"OSymmetricKeyCI.intercept() Exception: \" + ex . getMessage ( ) ) , ex ) ; } // Override algorithm and transform, if they exist in the JSON document. if ( jsonDoc . containsField ( \"algorithm\" ) ) algorithm = jsonDoc . field ( \"algorithm\" ) ; if ( jsonDoc . containsField ( \"transform\" ) ) transform = jsonDoc . field ( \"transform\" ) ; // Just in case the default configuration gets changed, check it. if ( transform == null || transform . isEmpty ( ) ) throw new OSecurityException ( \"OSymmetricKeyCI.intercept() cipher transformation is required\" ) ; // If the algorithm is not set, either as a default in the global configuration or in the JSON document, // then determine the algorithm from the cipher transformation. if ( algorithm == null ) algorithm = OSymmetricKey . separateAlgorithm ( transform ) ; OSymmetricKey key = null ; // \"key\" has priority over \"keyFile\" and \"keyStore\". if ( jsonDoc . containsField ( \"key\" ) ) { final String base64Key = jsonDoc . field ( \"key\" ) ; key = OSymmetricKey . fromString ( algorithm , base64Key ) ; key . setDefaultCipherTransform ( transform ) ; } else // \"keyFile\" has priority over \"keyStore\". if ( jsonDoc . containsField ( \"keyFile\" ) ) { key = OSymmetricKey . fromFile ( algorithm , ( String ) jsonDoc . field ( \"keyFile\" ) ) ; key . setDefaultCipherTransform ( transform ) ; } else if ( jsonDoc . containsField ( \"keyStore\" ) ) { ODocument ksDoc = jsonDoc . field ( \"keyStore\" ) ; if ( ksDoc . containsField ( \"file\" ) ) keystoreFile = ksDoc . field ( \"file\" ) ; if ( keystoreFile == null || keystoreFile . isEmpty ( ) ) throw new OSecurityException ( \"OSymmetricKeyCI.intercept() keystore file is required\" ) ; // Specific to Keystore, but override if present in the JSON document. if ( ksDoc . containsField ( \"password\" ) ) keystorePassword = ksDoc . field ( \"password\" ) ; String keyAlias = ksDoc . field ( \"keyAlias\" ) ; if ( keyAlias == null || keyAlias . isEmpty ( ) ) throw new OSecurityException ( \"OSymmetricKeyCI.intercept() keystore key alias is required\" ) ; // keyPassword may be null. String keyPassword = ksDoc . field ( \"keyPassword\" ) ; // keystorePassword may be null. key = OSymmetricKey . fromKeystore ( keystoreFile , keystorePassword , keyAlias , keyPassword ) ; key . setDefaultCipherTransform ( transform ) ; } else { throw new OSecurityException ( \"OSymmetricKeyCI.intercept() No suitable symmetric key property exists\" ) ; } // This should never happen, but... if ( key == null ) throw new OSecurityException ( \"OSymmetricKeyCI.intercept() OSymmetricKey is null\" ) ; encodedJSON = key . encrypt ( transform , username ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal only . Fills in one shot the record . [CODESPLIT] public static ORecordAbstract fill ( final ORecord record , final ORID iRid , final int iVersion , final byte [ ] iBuffer , final boolean iDirty ) { final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . fill ( iRid , iVersion , iBuffer , iDirty ) ; return rec ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal only . Changes the identity of the record . [CODESPLIT] public static ORecordAbstract setIdentity ( final ORecord record , final int iClusterId , final long iClusterPosition ) { final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . setIdentity ( iClusterId , iClusterPosition ) ; return rec ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal only . Changes the identity of the record . [CODESPLIT] public static ORecordAbstract setIdentity ( final ORecord record , final ORecordId iIdentity ) { final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . setIdentity ( iIdentity ) ; return rec ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal only . Sets the version . [CODESPLIT] public static void setVersion ( final ORecord record , final int iVersion ) { final ORecordAbstract rec = ( ORecordAbstract ) record ; rec . setVersion ( iVersion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal only . Return the record type . [CODESPLIT] public static byte getRecordType ( final ORecord record ) { if ( record instanceof ORecordAbstract ) { return ( ( ORecordAbstract ) record ) . getRecordType ( ) ; } final ORecordAbstract rec = ( ORecordAbstract ) record . getRecord ( ) ; return rec . getRecordType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens the database . [CODESPLIT] public void initDatabaseInstance ( ) { if ( database == null ) { for ( int retry = 0 ; retry < 100 ; ++ retry ) { try { database = distributed . getDatabaseInstance ( ) ; // OK break ; } catch ( OStorageException e ) { // WAIT FOR A WHILE, THEN RETRY if ( ! dbNotAvailable ( retry ) ) return ; } catch ( OConfigurationException e ) { // WAIT FOR A WHILE, THEN RETRY if ( ! dbNotAvailable ( retry ) ) return ; } } if ( database == null ) { ODistributedServerLog . info ( this , manager . getLocalNodeName ( ) , null , DIRECTION . NONE , \"Database '%s' not present, shutting down database manager\" , databaseName ) ; distributed . shutdown ( ) ; throw new ODistributedException ( \"Cannot open database '\" + databaseName + \"'\" ) ; } } else if ( database . isClosed ( ) ) { // DATABASE CLOSED, REOPEN IT database . activateOnCurrentThread ( ) ; database . close ( ) ; database = distributed . getDatabaseInstance ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the remote call on the local node and send back the result [CODESPLIT] protected void onMessage ( final ODistributedRequest iRequest ) { String senderNodeName = null ; for ( int retry = 0 ; retry < 10 ; retry ++ ) { senderNodeName = manager . getNodeNameById ( iRequest . getId ( ) . getNodeId ( ) ) ; if ( senderNodeName != null ) break ; try { Thread . sleep ( 200 ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw OException . wrapException ( new ODistributedException ( \"Execution has been interrupted\" ) , e ) ; } } if ( senderNodeName == null ) { ODistributedServerLog . warn ( this , localNodeName , senderNodeName , DIRECTION . IN , \"Sender server id %d is not registered in the cluster configuration, discard the request: (%s) (worker=%d)\" , iRequest . getId ( ) . getNodeId ( ) , iRequest , id ) ; sendResponseBack ( iRequest , new ODistributedException ( \"Sender server id \" + iRequest . getId ( ) . getNodeId ( ) + \" is not registered in the cluster configuration, discard the request\" ) ) ; return ; } final ORemoteTask task = iRequest . getTask ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , localNodeName , senderNodeName , DIRECTION . IN , \"Received request: (%s) (worker=%d)\" , iRequest , id ) ; // EXECUTE IT LOCALLY Object responsePayload = null ; OSecurityUser origin = null ; try { waitNodeIsOnline ( ) ; distributed . waitIsReady ( task ) ; // EXECUTE THE TASK for ( int retry = 1 ; running ; ++ retry ) { if ( task . isUsingDatabase ( ) ) { initDatabaseInstance ( ) ; if ( database == null ) throw new ODistributedOperationException ( \"Error on executing remote request because the database '\" + databaseName + \"' is not available\" ) ; // keep original user in database, check the username passed in request and set new user in DB, after document saved, // reset to original user if ( database != null ) { database . activateOnCurrentThread ( ) ; origin = database . getUser ( ) ; try { if ( iRequest . getUserRID ( ) != null && iRequest . getUserRID ( ) . isValid ( ) && ( lastUser == null || ! ( lastUser . getIdentity ( ) ) . equals ( iRequest . getUserRID ( ) ) ) ) { lastUser = database . getMetadata ( ) . getSecurity ( ) . getUser ( iRequest . getUserRID ( ) ) ; database . setUser ( lastUser ) ; // set to new user } else origin = null ; } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"Failed on user switching database. \" , ex ) ; } } } responsePayload = manager . executeOnLocalNode ( iRequest . getId ( ) , iRequest . getTask ( ) , database ) ; if ( responsePayload instanceof OModificationOperationProhibitedException ) { // RETRY try { ODistributedServerLog . info ( this , localNodeName , senderNodeName , DIRECTION . IN , \"Database is frozen, waiting and retrying. Request %s (retry=%d, worker=%d)\" , iRequest , retry , id ) ; Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { } } else { // OPERATION EXECUTED (OK OR ERROR), NO RETRY NEEDED if ( retry > 1 ) ODistributedServerLog . info ( this , localNodeName , senderNodeName , DIRECTION . IN , \"Request %s succeed after retry=%d\" , iRequest , retry ) ; break ; } } } catch ( RuntimeException e ) { if ( task . hasResponse ( ) ) sendResponseBack ( iRequest , e ) ; throw e ; } finally { if ( database != null && ! database . isClosed ( ) ) { database . activateOnCurrentThread ( ) ; if ( ! database . isClosed ( ) ) { database . rollback ( ) ; database . getLocalCache ( ) . clear ( ) ; if ( origin != null ) database . setUser ( origin ) ; } } } if ( task . hasResponse ( ) ) { if ( ! sendResponseBack ( iRequest , responsePayload ) ) { handleError ( iRequest , responsePayload ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the error message for a caught exception according to a level passed as argument . It s composed of : - defined error message - exception message [CODESPLIT] public String printExceptionMessage ( Exception e , String message , String level ) { if ( e . getMessage ( ) != null ) message += \"\\n\" + e . getClass ( ) . getName ( ) + \" - \" + e . getMessage ( ) ; else message += \"\\n\" + e . getClass ( ) . getName ( ) ; switch ( level ) { case \"debug\" : this . messageHandler . debug ( this , message ) ; break ; case \"info\" : this . messageHandler . info ( this , message ) ; break ; case \"warn\" : this . messageHandler . warn ( this , message ) ; break ; case \"error\" : this . messageHandler . error ( this , message ) ; break ; } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the exception stack trace and prints it according to a level passed as argument . [CODESPLIT] public String printExceptionStackTrace ( Exception e , String level ) { // copying the exception stack trace in the string Writer writer = new StringWriter ( ) ; e . printStackTrace ( new PrintWriter ( writer ) ) ; String s = writer . toString ( ) ; switch ( level ) { case \"debug\" : this . messageHandler . debug ( this , \"\\n\" + s + \"\\n\" ) ; break ; case \"info\" : this . messageHandler . info ( this , \"\\n\" + s + \"\\n\" ) ; break ; case \"warn\" : this . messageHandler . warn ( this , \"\\n\" + s + \"\\n\" ) ; break ; case \"error\" : this . messageHandler . error ( this , \"\\n\" + s + \"\\n\" ) ; break ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs index query and returns index cursor which presents subset of index data which corresponds to result of execution of given operator . [CODESPLIT] public OIndexCursor executeIndexQuery ( OCommandContext iContext , OIndex < ? > index , final List < Object > keyParams , boolean ascSortOrder ) { return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the item with the received key to a record . [CODESPLIT] private void convertLink2Record ( final Object iKey ) { if ( status == MULTIVALUE_CONTENT_TYPE . ALL_RECORDS ) return ; final Object value ; if ( iKey instanceof ORID ) value = iKey ; else value = super . get ( iKey ) ; if ( value != null && value instanceof ORID ) { final ORID rid = ( ORID ) value ; marshalling = true ; try { try { // OVERWRITE IT\r ORecord record = rid . getRecord ( ) ; if ( record != null ) { ORecordInternal . unTrack ( sourceRecord , rid ) ; ORecordInternal . track ( sourceRecord , record ) ; } super . put ( iKey , record ) ; } catch ( ORecordNotFoundException ignore ) { // IGNORE THIS\r } } finally { marshalling = false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void serializeInByteBufferObject ( Boolean object , ByteBuffer buffer , Object ... hints ) { buffer . put ( object . booleanValue ( ) ? ( byte ) 1 : ( byte ) 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Boolean deserializeFromByteBufferObject ( ByteBuffer buffer , OWALChanges walChanges , int offset ) { return walChanges . getByteValue ( buffer , offset ) > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register all the names for the same instance . [CODESPLIT] public void registerCommand ( final OServerCommand iServerCommandInstance ) { for ( String name : iServerCommandInstance . getNames ( ) ) if ( OStringSerializerHelper . contains ( name , ' ' ) ) { restCommands . put ( name , iServerCommandInstance ) ; } else if ( OStringSerializerHelper . contains ( name , ' ' ) ) wildcardCommands . put ( name , iServerCommandInstance ) ; else exactCommands . put ( name , iServerCommandInstance ) ; iServerCommandInstance . configure ( server ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OSecurityComponent [CODESPLIT] public void config ( final OServer oServer , final OServerConfigurationManager serverCfg , final ODocument jsonConfig ) { super . config ( oServer , serverCfg , jsonConfig ) ; try { if ( jsonConfig . containsField ( \"users\" ) ) { List < ODocument > usersList = jsonConfig . field ( \"users\" ) ; for ( ODocument userDoc : usersList ) { OServerUserConfiguration userCfg = createServerUser ( userDoc ) ; if ( userCfg != null ) { String checkName = userCfg . name ; if ( ! isCaseSensitive ( ) ) checkName = checkName . toLowerCase ( Locale . ENGLISH ) ; usersMap . put ( checkName , userCfg ) ; } } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"config()\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Derived implementations can override this method to provide new server user implementations . [CODESPLIT] protected OServerUserConfiguration createServerUser ( final ODocument userDoc ) { OServerUserConfiguration userCfg = null ; if ( userDoc . containsField ( \"username\" ) && userDoc . containsField ( \"resources\" ) ) { final String user = userDoc . field ( \"username\" ) ; final String resources = userDoc . field ( \"resources\" ) ; String password = userDoc . field ( \"password\" ) ; if ( password == null ) password = \"\" ; userCfg = new OServerUserConfiguration ( user , password , resources ) ; } return userCfg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the actual username if successful null otherwise . [CODESPLIT] public String authenticate ( final String username , final String password ) { String principal = null ; try { OServerUserConfiguration user = getUser ( username ) ; if ( isPasswordValid ( user ) ) { if ( OSecurityManager . instance ( ) . checkPassword ( password , user . password ) ) { principal = user . name ; } } } catch ( Exception ex ) { OLogManager . instance ( ) . error ( this , \"ODefaultPasswordAuthenticator.authenticate()\" , ex ) ; } return principal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If not supported by the authenticator return false . [CODESPLIT] public boolean isAuthorized ( final String username , final String resource ) { if ( username == null || resource == null ) return false ; OServerUserConfiguration userCfg = getUser ( username ) ; if ( userCfg != null ) { // Total Access if ( userCfg . resources . equals ( \"*\" ) ) return true ; String [ ] resourceParts = userCfg . resources . split ( \",\" ) ; for ( String r : resourceParts ) { if ( r . equalsIgnoreCase ( resource ) ) return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OSecurityAuthenticator [CODESPLIT] public OServerUserConfiguration getUser ( final String username ) { OServerUserConfiguration userCfg = null ; synchronized ( usersMap ) { if ( username != null ) { String checkName = username ; if ( ! isCaseSensitive ( ) ) checkName = username . toLowerCase ( Locale . ENGLISH ) ; if ( usersMap . containsKey ( checkName ) ) { userCfg = usersMap . get ( checkName ) ; } } } return userCfg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyzes a query filter for a possible indexation options . The results are sorted by amount of fields . So the most specific items go first . [CODESPLIT] public List < OIndexSearchResult > analyzeCondition ( OSQLFilterCondition condition , final OClass schemaClass , OCommandContext context ) { final List < OIndexSearchResult > indexSearchResults = new ArrayList < OIndexSearchResult > ( ) ; OIndexSearchResult lastCondition = analyzeFilterBranch ( schemaClass , condition , indexSearchResults , context ) ; if ( indexSearchResults . isEmpty ( ) && lastCondition != null ) { indexSearchResults . add ( lastCondition ) ; } Collections . sort ( indexSearchResults , new Comparator < OIndexSearchResult > ( ) { public int compare ( final OIndexSearchResult searchResultOne , final OIndexSearchResult searchResultTwo ) { return searchResultTwo . getFieldCount ( ) - searchResultOne . getFieldCount ( ) ; } } ) ; return indexSearchResults ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add SQL filter field to the search candidate list . [CODESPLIT] private OIndexSearchResult createIndexedProperty ( final OSQLFilterCondition iCondition , final Object iItem , OCommandContext ctx ) { if ( iItem == null || ! ( iItem instanceof OSQLFilterItemField ) ) { return null ; } if ( iCondition . getLeft ( ) instanceof OSQLFilterItemField && iCondition . getRight ( ) instanceof OSQLFilterItemField ) { return null ; } final OSQLFilterItemField item = ( OSQLFilterItemField ) iItem ; if ( item . hasChainOperators ( ) && ! item . isFieldChain ( ) ) { return null ; } boolean inverted = iCondition . getRight ( ) == iItem ; final Object origValue = inverted ? iCondition . getLeft ( ) : iCondition . getRight ( ) ; OQueryOperator operator = iCondition . getOperator ( ) ; if ( inverted ) { if ( operator instanceof OQueryOperatorIn ) { operator = new OQueryOperatorContains ( ) ; } else if ( operator instanceof OQueryOperatorContains ) { operator = new OQueryOperatorIn ( ) ; } else if ( operator instanceof OQueryOperatorMajor ) { operator = new OQueryOperatorMinor ( ) ; } else if ( operator instanceof OQueryOperatorMinor ) { operator = new OQueryOperatorMajor ( ) ; } else if ( operator instanceof OQueryOperatorMajorEquals ) { operator = new OQueryOperatorMinorEquals ( ) ; } else if ( operator instanceof OQueryOperatorMinorEquals ) { operator = new OQueryOperatorMajorEquals ( ) ; } } if ( iCondition . getOperator ( ) instanceof OQueryOperatorBetween || operator instanceof OQueryOperatorIn ) { return new OIndexSearchResult ( operator , item . getFieldChain ( ) , origValue ) ; } final Object value = OSQLHelper . getValue ( origValue , null , ctx ) ; return new OIndexSearchResult ( operator , item . getFieldChain ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that detaches all fields contained in the document to the given object [CODESPLIT] public void detach ( final Object self , final boolean nonProxiedInstance ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { final Class < ? > selfClass = self . getClass ( ) ; for ( String fieldName : doc . fieldNames ( ) ) { Object value = getValue ( self , fieldName , false , null , true ) ; if ( value instanceof OObjectLazyMultivalueElement ) { ( ( OObjectLazyMultivalueElement < ? > ) value ) . detach ( nonProxiedInstance ) ; if ( nonProxiedInstance ) value = ( ( OObjectLazyMultivalueElement < ? > ) value ) . getNonOrientInstance ( ) ; } OObjectEntitySerializer . setFieldValue ( OObjectEntitySerializer . getField ( fieldName , selfClass ) , self , value ) ; } OObjectEntitySerializer . setIdField ( selfClass , self , doc . getIdentity ( ) ) ; OObjectEntitySerializer . setVersionField ( selfClass , self , doc . getVersion ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that detaches all fields contained in the document to the given object [CODESPLIT] public void detachAll ( final Object self , final boolean nonProxiedInstance , final Map < Object , Object > alreadyDetached , final Map < Object , Object > lazyObjects ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { final Class < ? > selfClass = self . getClass ( ) ; for ( String fieldName : doc . fieldNames ( ) ) { final Field field = OObjectEntitySerializer . getField ( fieldName , selfClass ) ; if ( field != null ) { Object value = getValue ( self , fieldName , false , null , true ) ; if ( value instanceof OObjectLazyMultivalueElement ) { ( ( OObjectLazyMultivalueElement < ? > ) value ) . detachAll ( nonProxiedInstance , alreadyDetached , lazyObjects ) ; if ( nonProxiedInstance ) value = ( ( OObjectLazyMultivalueElement < ? > ) value ) . getNonOrientInstance ( ) ; } else if ( value instanceof Proxy ) { OObjectProxyMethodHandler handler = ( OObjectProxyMethodHandler ) ( ( ProxyObject ) value ) . getHandler ( ) ; if ( nonProxiedInstance ) { value = OObjectEntitySerializer . getNonProxiedInstance ( value ) ; } if ( OObjectEntitySerializer . isFetchLazyField ( self . getClass ( ) , fieldName ) ) { // just make a placeholder with only the id, so it can be fetched later (but not by orient // internally) // do not use the already detached map for this, that might mix up lazy and non-lazy objects Object lazyValue = lazyObjects . get ( handler . doc . getIdentity ( ) ) ; if ( lazyValue != null ) { value = lazyValue ; } else { OObjectEntitySerializer . setIdField ( field . getType ( ) , value , handler . doc . getIdentity ( ) ) ; lazyObjects . put ( handler . doc . getIdentity ( ) , value ) ; } } else { Object detachedValue = alreadyDetached . get ( handler . doc . getIdentity ( ) ) ; if ( detachedValue != null ) { value = detachedValue ; } else { ORID identity = handler . doc . getIdentity ( ) ; if ( identity . isValid ( ) ) alreadyDetached . put ( identity , value ) ; handler . detachAll ( value , nonProxiedInstance , alreadyDetached , lazyObjects ) ; } } } else if ( value instanceof OTrackedMap && nonProxiedInstance ) { Map newValue = new LinkedHashMap <> ( ) ; newValue . putAll ( ( Map ) value ) ; value = newValue ; } else if ( value instanceof OTrackedList && nonProxiedInstance ) { List newValue = new ArrayList ( ) ; newValue . addAll ( ( Collection ) value ) ; value = newValue ; } else if ( value instanceof OTrackedSet && nonProxiedInstance ) { Set newValue = new LinkedHashSet ( ) ; newValue . addAll ( ( Collection ) value ) ; value = newValue ; } OObjectEntitySerializer . setFieldValue ( field , self , value ) ; } } OObjectEntitySerializer . setIdField ( selfClass , self , doc . getIdentity ( ) ) ; OObjectEntitySerializer . setVersionField ( selfClass , self , doc . getVersion ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that attaches all data contained in the object to the associated document [CODESPLIT] public void attach ( final Object self ) throws IllegalArgumentException , IllegalAccessException , NoSuchMethodException , InvocationTargetException { for ( Class < ? > currentClass = self . getClass ( ) ; currentClass != Object . class ; ) { if ( Proxy . class . isAssignableFrom ( currentClass ) ) { currentClass = currentClass . getSuperclass ( ) ; continue ; } for ( Field f : currentClass . getDeclaredFields ( ) ) { final String fieldName = f . getName ( ) ; final Class < ? > declaringClass = f . getDeclaringClass ( ) ; if ( OObjectEntitySerializer . isTransientField ( declaringClass , fieldName ) || OObjectEntitySerializer . isVersionField ( declaringClass , fieldName ) || OObjectEntitySerializer . isIdField ( declaringClass , fieldName ) ) continue ; Object value = OObjectEntitySerializer . getFieldValue ( f , self ) ; value = setValue ( self , fieldName , value ) ; OObjectEntitySerializer . setFieldValue ( f , self , value ) ; } currentClass = currentClass . getSuperclass ( ) ; if ( currentClass == null || currentClass . equals ( ODocument . class ) ) // POJO EXTENDS ODOCUMENT: SPECIAL CASE: AVOID TO CONSIDER // ODOCUMENT FIELDS currentClass = Object . class ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* returns the list of property names to be indexed [CODESPLIT] private String [ ] calculateProperties ( OCommandContext ctx ) { if ( propertyList == null ) { return null ; } return propertyList . stream ( ) . map ( x -> x . getCompleteKey ( ) ) . collect ( Collectors . toList ( ) ) . toArray ( new String [ ] { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "calculates the indexed class based on the class name [CODESPLIT] private OClass getIndexClass ( OCommandContext ctx ) { if ( className == null ) { return null ; } OClass result = ctx . getDatabase ( ) . getMetadata ( ) . getSchema ( ) . getClass ( className . getStringValue ( ) ) ; if ( result == null ) { throw new OCommandExecutionException ( \"Cannot find class \" + className ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns index metadata as an ODocuemnt ( as expected by Index API ) [CODESPLIT] private ODocument calculateMetadata ( OCommandContext ctx ) { if ( metadata == null ) { return null ; } return metadata . toDocument ( null , ctx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "first set new current value then call next [CODESPLIT] protected long nextWithNewCurrentValue ( long currentValue , boolean executeViaDistributed ) throws OSequenceLimitReachedException , ODatabaseException { if ( ! executeViaDistributed ) { //we don't want synchronization on whole method, because called with executeViaDistributed == true //will later call nextWithNewCurrentValue with parameter executeViaDistributed == false //and that will cause deadlock synchronized ( this ) { cacheStart = currentValue ; return nextWork ( ) ; } } else { try { return sendSequenceActionSetAndNext ( currentValue ) ; } catch ( InterruptedException | ExecutionException exc ) { OLogManager . instance ( ) . error ( this , exc . getMessage ( ) , exc , ( Object [ ] ) null ) ; throw new ODatabaseException ( exc . getMessage ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interprets this key changes using the given { @link Interpretation interpretation } . [CODESPLIT] public Iterable < OTransactionIndexEntry > interpret ( Interpretation interpretation ) { synchronized ( this ) { switch ( interpretation ) { case Unique : return interpretAsUnique ( ) ; case Dictionary : return interpretAsDictionary ( ) ; case NonUnique : return interpretAsNonUnique ( ) ; default : throw new IllegalStateException ( \"Unexpected interpretation '\" + interpretation + \"'\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the command and return the ODocument object created . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( fromExpr == null && toExpr == null && rids == null && query == null && compiledFilter == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; ODatabaseDocumentInternal db = getDatabase ( ) ; txAlreadyBegun = db . getTransaction ( ) . isActive ( ) ; if ( rids != null ) { // REMOVE PUNCTUAL RID db . begin ( ) ; for ( ORecordId rid : rids ) { final OEdge e = toEdge ( rid ) ; if ( e != null ) { e . delete ( ) ; removed ++ ; } } db . commit ( ) ; return removed ; } else { // MULTIPLE EDGES final Set < OEdge > edges = new HashSet < OEdge > ( ) ; if ( query == null ) { db . begin ( ) ; Set < OIdentifiable > fromIds = null ; if ( fromExpr != null ) fromIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , fromExpr , context , iArgs ) ; Set < OIdentifiable > toIds = null ; if ( toExpr != null ) toIds = OSQLEngine . getInstance ( ) . parseRIDTarget ( db , toExpr , context , iArgs ) ; if ( label == null ) label = \"E\" ; if ( fromIds != null && toIds != null ) { int fromCount = 0 ; int toCount = 0 ; for ( OIdentifiable fromId : fromIds ) { final OVertex v = toVertex ( fromId ) ; if ( v != null ) fromCount += count ( v . getEdges ( ODirection . OUT , label ) ) ; } for ( OIdentifiable toId : toIds ) { final OVertex v = toVertex ( toId ) ; if ( v != null ) toCount += count ( v . getEdges ( ODirection . IN , label ) ) ; } if ( fromCount <= toCount ) { // REMOVE ALL THE EDGES BETWEEN VERTICES for ( OIdentifiable fromId : fromIds ) { final OVertex v = toVertex ( fromId ) ; if ( v != null ) for ( OEdge e : v . getEdges ( ODirection . OUT , label ) ) { final OIdentifiable inV = ( ( OEdge ) e ) . getTo ( ) ; if ( inV != null && toIds . contains ( inV . getIdentity ( ) ) ) edges . add ( e ) ; } } } else { for ( OIdentifiable toId : toIds ) { final OVertex v = toVertex ( toId ) ; if ( v != null ) for ( OEdge e : v . getEdges ( ODirection . IN , label ) ) { final OIdentifiable outV = ( ( OEdge ) e ) . getFrom ( ) ; if ( outV != null && fromIds . contains ( outV . getIdentity ( ) ) ) edges . add ( e ) ; } } } } else if ( fromIds != null ) { // REMOVE ALL THE EDGES THAT START FROM A VERTEXES for ( OIdentifiable fromId : fromIds ) { final OVertex v = toVertex ( fromId ) ; if ( v != null ) { for ( OEdge e : v . getEdges ( ODirection . OUT , label ) ) { edges . add ( e ) ; } } } } else if ( toIds != null ) { // REMOVE ALL THE EDGES THAT ARRIVE TO A VERTEXES for ( OIdentifiable toId : toIds ) { final OVertex v = toVertex ( toId ) ; if ( v != null ) { for ( OEdge e : v . getEdges ( ODirection . IN , label ) ) { edges . add ( e ) ; } } } } else throw new OCommandExecutionException ( \"Invalid target: \" + toIds ) ; if ( compiledFilter != null ) { // ADDITIONAL FILTERING for ( Iterator < OEdge > it = edges . iterator ( ) ; it . hasNext ( ) ; ) { final OEdge edge = it . next ( ) ; if ( ! ( Boolean ) compiledFilter . evaluate ( edge . getRecord ( ) , null , context ) ) it . remove ( ) ; } } // DELETE THE FOUND EDGES removed = edges . size ( ) ; for ( OEdge edge : edges ) edge . delete ( ) ; db . commit ( ) ; return removed ; } else { db . begin ( ) ; // TARGET IS A CLASS + OPTIONAL CONDITION query . setContext ( getContext ( ) ) ; query . execute ( iArgs ) ; db . commit ( ) ; return removed ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the current edge . [CODESPLIT] public boolean result ( final Object iRecord ) { final OIdentifiable id = ( OIdentifiable ) iRecord ; if ( compiledFilter != null ) { // ADDITIONAL FILTERING if ( ! ( Boolean ) compiledFilter . evaluate ( id . getRecord ( ) , null , context ) ) return true ; } if ( id . getIdentity ( ) . isValid ( ) ) { final OEdge e = toEdge ( id ) ; if ( e != null ) { e . delete ( ) ; if ( ! txAlreadyBegun && batch > 0 && ( removed + 1 ) % batch == 0 ) { getDatabase ( ) . commit ( ) ; getDatabase ( ) . begin ( ) ; } removed ++ ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Truncates all the clusters the class uses . [CODESPLIT] public void truncate ( ) throws IOException { ODatabaseDocumentInternal db = getDatabase ( ) ; db . checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_UPDATE ) ; if ( isSubClassOf ( OSecurityShared . RESTRICTED_CLASSNAME ) ) { throw new OSecurityException ( \"Class '\" + getName ( ) + \"' cannot be truncated because has record level security enabled (extends '\" + OSecurityShared . RESTRICTED_CLASSNAME + \"')\" ) ; } final OStorage storage = db . getStorage ( ) ; acquireSchemaReadLock ( ) ; try { for ( int id : clusterIds ) { OCluster cl = storage . getClusterById ( id ) ; db . checkForClusterPermissions ( cl . getName ( ) ) ; cl . truncate ( ) ; } for ( OIndex < ? > index : getClassIndexes ( ) ) index . clear ( ) ; Set < OIndex < ? > > superclassIndexes = new HashSet < OIndex < ? > > ( ) ; superclassIndexes . addAll ( getIndexes ( ) ) ; superclassIndexes . removeAll ( getClassIndexes ( ) ) ; for ( OIndex index : superclassIndexes ) { index . rebuild ( ) ; } } finally { releaseSchemaReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the current instance extends specified schema class . [CODESPLIT] public boolean isSubClassOf ( final String iClassName ) { acquireSchemaReadLock ( ) ; try { if ( iClassName == null ) return false ; if ( iClassName . equalsIgnoreCase ( getName ( ) ) || iClassName . equalsIgnoreCase ( getShortName ( ) ) ) return true ; for ( OClassImpl superClass : superClasses ) { if ( superClass . isSubClassOf ( iClassName ) ) return true ; } return false ; } finally { releaseSchemaReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the current instance extends specified schema class . [CODESPLIT] public boolean isSubClassOf ( final OClass clazz ) { acquireSchemaReadLock ( ) ; try { if ( clazz == null ) return false ; if ( equals ( clazz ) ) return true ; for ( OClassImpl superClass : superClasses ) { if ( superClass . isSubClassOf ( clazz ) ) return true ; } return false ; } finally { releaseSchemaReadLock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a base class to the current one . It adds also the base class cluster ids to the polymorphic cluster ids array . [CODESPLIT] protected OClass addBaseClass ( final OClassImpl iBaseClass ) { checkRecursion ( iBaseClass ) ; if ( subclasses == null ) subclasses = new ArrayList < OClass > ( ) ; if ( subclasses . contains ( iBaseClass ) ) return this ; subclasses . add ( iBaseClass ) ; addPolymorphicClusterIdsWithInheritance ( iBaseClass ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add different cluster id to the polymorphic cluster ids array . [CODESPLIT] protected void addPolymorphicClusterIds ( final OClassImpl iBaseClass ) { Set < Integer > clusters = new TreeSet < Integer > ( ) ; for ( int clusterId : polymorphicClusterIds ) { clusters . add ( clusterId ) ; } for ( int clusterId : iBaseClass . polymorphicClusterIds ) { if ( clusters . add ( clusterId ) ) { try { addClusterIdToIndexes ( clusterId ) ; } catch ( RuntimeException e ) { OLogManager . instance ( ) . warn ( this , \"Error adding clusterId '%d' to index of class '%s'\" , e , clusterId , getName ( ) ) ; clusters . remove ( clusterId ) ; } } } polymorphicClusterIds = new int [ clusters . size ( ) ] ; int i = 0 ; for ( Integer cluster : clusters ) { polymorphicClusterIds [ i ] = cluster ; i ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO HANDLE EVALUATE RECORD [CODESPLIT] @ Override public Object evaluateRecord ( OIdentifiable iRecord , ODocument iCurrentResult , OSQLFilterCondition iCondition , Object iLeft , Object iRight , OCommandContext iContext , final ODocumentSerializer serializer ) { OSQLFunction function = OSQLEngine . getInstance ( ) . getFunction ( keyword ) ; return function . execute ( this , iRecord , iCurrentResult , new Object [ ] { iLeft , iCondition . getRight ( ) } , iContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the link . [CODESPLIT] private static OIdentifiable linkToStream ( final StringBuilder buffer , final ODocument iParentRecord , Object iLinked ) { if ( iLinked == null ) // NULL REFERENCE\r return null ; OIdentifiable resultRid = null ; ORID rid ; if ( iLinked instanceof ORID ) { // JUST THE REFERENCE\r rid = ( ORID ) iLinked ; assert rid . getIdentity ( ) . isValid ( ) || ( ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getStorage ( ) instanceof OStorageProxy ) : \"Impossible to serialize invalid link \" + rid . getIdentity ( ) ; resultRid = rid ; } else { if ( iLinked instanceof String ) iLinked = new ORecordId ( ( String ) iLinked ) ; if ( ! ( iLinked instanceof OIdentifiable ) ) throw new IllegalArgumentException ( \"Invalid object received. Expected a OIdentifiable but received type=\" + iLinked . getClass ( ) . getName ( ) + \" and value=\" + iLinked ) ; // RECORD\r ORecord iLinkedRecord = ( ( OIdentifiable ) iLinked ) . getRecord ( ) ; rid = iLinkedRecord . getIdentity ( ) ; assert rid . getIdentity ( ) . isValid ( ) || ( ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getStorage ( ) instanceof OStorageProxy ) : \"Impossible to serialize invalid link \" + rid . getIdentity ( ) ; final ODatabaseDocument database = ODatabaseRecordThreadLocal . instance ( ) . get ( ) ; if ( iParentRecord != null ) { if ( ! database . isRetainRecords ( ) ) // REPLACE CURRENT RECORD WITH ITS ID: THIS SAVES A LOT OF MEMORY\r resultRid = iLinkedRecord . getIdentity ( ) ; } } if ( rid . isValid ( ) ) rid . toString ( buffer ) ; return resultRid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a { @link SortField } from a configuration map . The map can contains up to three fields : field ( name ) reverse ( true / false ) and type { @link SortField . Type } . [CODESPLIT] public static SortField buildSortField ( Map < String , Object > conf ) { final String field = Optional . ofNullable ( ( String ) conf . get ( \"field\" ) ) . orElse ( null ) ; final String type = Optional . ofNullable ( ( ( String ) conf . get ( \"type\" ) ) . toUpperCase ( ) ) . orElse ( SortField . Type . STRING . name ( ) ) ; final Boolean reverse = Optional . ofNullable ( ( Boolean ) conf . get ( \"reverse\" ) ) . orElse ( false ) ; SortField sortField = new SortField ( field , SortField . Type . valueOf ( type ) , reverse ) ; return sortField ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the input stream in memory . This is less efficient than { @link #fromInputStream ( InputStream int ) } because allocation is made multiple times . If you already know the input size use { @link #fromInputStream ( InputStream int ) } . [CODESPLIT] public int fromInputStream ( final InputStream in ) throws IOException { final OMemoryStream out = new OMemoryStream ( ) ; try { final byte [ ] buffer = new byte [ OMemoryStream . DEF_SIZE ] ; int readBytesCount ; while ( true ) { readBytesCount = in . read ( buffer , 0 , buffer . length ) ; if ( readBytesCount == - 1 ) { break ; } out . write ( buffer , 0 , readBytesCount ) ; } out . flush ( ) ; _source = out . toByteArray ( ) ; } finally { out . close ( ) ; } _size = _source . length ; return _size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the input stream in memory specifying the maximum bytes to read . This is more efficient than { @link #fromInputStream ( InputStream ) } because allocation is made only once . [CODESPLIT] public int fromInputStream ( final InputStream in , final int maxSize ) throws IOException { final byte [ ] buffer = new byte [ maxSize ] ; int totalBytesCount = 0 ; int readBytesCount ; while ( totalBytesCount < maxSize ) { readBytesCount = in . read ( buffer , totalBytesCount , buffer . length - totalBytesCount ) ; if ( readBytesCount == - 1 ) { break ; } totalBytesCount += readBytesCount ; } if ( totalBytesCount == 0 ) { _source = EMPTY_SOURCE ; _size = 0 ; } else if ( totalBytesCount == maxSize ) { _source = buffer ; _size = maxSize ; } else { _source = Arrays . copyOf ( buffer , totalBytesCount ) ; _size = totalBytesCount ; } return _size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires direct memory buffer with native byte order . If there is free ( already released ) direct memory page we reuse it otherwise new memory chunk is allocated from direct memory . [CODESPLIT] public final OPointer acquireDirect ( boolean clear ) { OPointer pointer ; pointer = pointersPool . poll ( ) ; if ( pointer != null ) { pointersPoolSize . decrementAndGet ( ) ; } else { pointer = allocator . allocate ( pageSize , - 1 ) ; } if ( clear ) { pointer . clear ( ) ; } final ByteBuffer buffer = pointer . getNativeByteBuffer ( ) ; buffer . position ( 0 ) ; if ( TRACK ) { pointerMapping . put ( pointer , generatePointer ( ) ) ; } return pointer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put buffer which is not used any more back to the pool or frees direct memory if pool is full . [CODESPLIT] public final void release ( OPointer pointer ) { if ( TRACK ) { pointerMapping . remove ( pointer ) ; } long poolSize = pointersPoolSize . incrementAndGet ( ) ; if ( poolSize > this . poolSize ) { pointersPoolSize . decrementAndGet ( ) ; allocator . deallocate ( pointer ) ; } else { pointersPool . add ( pointer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether there are not released buffers in the pool [CODESPLIT] public void checkMemoryLeaks ( ) { boolean detected = false ; if ( TRACK ) { for ( Map . Entry < OPointer , PointerTracker > entry : pointerMapping . entrySet ( ) ) { OLogManager . instance ( ) . errorNoDb ( this , \"DIRECT-TRACK: unreleased direct memory pointer `%X` detected.\" , entry . getValue ( ) . allocation , System . identityHashCode ( entry . getKey ( ) ) ) ; detected = true ; } } assert ! detected ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears pool and dealocates memory . [CODESPLIT] public void clear ( ) { for ( OPointer pointer : pointersPool ) { allocator . deallocate ( pointer ) ; } pointersPool . clear ( ) ; pointersPoolSize . set ( 0 ) ; for ( OPointer pointer : pointerMapping . keySet ( ) ) { allocator . deallocate ( pointer ) ; } pointerMapping . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the byte array to an int starting from the given offset . [CODESPLIT] public static int bytes2int ( final byte [ ] b , final int offset ) { return ( b [ offset ] ) << 24 | ( 0xff & b [ offset + 1 ] ) << 16 | ( 0xff & b [ offset + 2 ] ) << 8 | ( ( 0xff & b [ offset + 3 ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the persistence . xml files referenced by the URLs in the collection [CODESPLIT] public static PersistenceUnitInfo findPersistenceUnit ( String unitName , Collection < ? extends PersistenceUnitInfo > units ) { if ( units == null || unitName == null ) { return null ; } for ( PersistenceUnitInfo unit : units ) { if ( unitName . equals ( unit . getPersistenceUnitName ( ) ) ) { return unit ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the persistence . xml files referenced by the URLs in the collection [CODESPLIT] public static Collection < ? extends PersistenceUnitInfo > parse ( URL persistenceXml ) { InputStream is = null ; try { // Buffer the InputStream so we can mark it, though we'll be in // trouble if we have to read more than 8192 characters before finding // the schema! is = new BufferedInputStream ( persistenceXml . openStream ( ) ) ; JPAVersion jpaVersion = getSchemaVersion ( is ) ; Schema schema = getSchema ( jpaVersion ) ; if ( schema == null ) { throw new PersistenceException ( \"Schema is unknown\" ) ; } // Get back to the beginning of the stream is = new BufferedInputStream ( persistenceXml . openStream ( ) ) ; parserFactory . setNamespaceAware ( true ) ; int endIndex = persistenceXml . getPath ( ) . length ( ) - PERSISTENCE_XML_BASE_NAME . length ( ) ; URL persistenceXmlRoot = new URL ( \"file://\" + persistenceXml . getFile ( ) . substring ( 0 , endIndex ) ) ; return getPersistenceUnits ( is , persistenceXmlRoot , jpaVersion ) ; } catch ( Exception e ) { throw new PersistenceException ( \"Something goes wrong while parsing persistence.xml\" , e ) ; } finally { if ( is != null ) try { is . close ( ) ; } catch ( IOException e ) { // No logging necessary, just consume } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fist tag of persistence . xml ( <persistence > ) have to have version attribute [CODESPLIT] @ Override public void startElement ( String uri , String localName , String name , Attributes attributes ) throws SAXException { PersistenceXml element = PersistenceXml . parse ( ( localName == null || localName . isEmpty ( ) ) ? name : localName ) ; schemaVersion = PersistenceXmlUtil . parseSchemaVersion ( uri , element , attributes ) ; // found, stop parsing if ( schemaVersion != null ) { throw new StopSAXParser ( ) ; } // This should never occurs, however check if contain known tag other than TAG_PERSISTENCE if ( TAG_PERSISTENCE != element && EnumSet . allOf ( PersistenceXml . class ) . contains ( element ) ) { throw new PersistenceException ( \"Cannot find schema version attribute in <persistence> tag\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a value using the variable - length encoding from <a href = http : // code . google . com / apis / protocolbuffers / docs / encoding . html > Google Protocol Buffers< / a > . Zig - zag is not used so input must not be negative . [CODESPLIT] public static void writeUnsignedVarLong ( long value , final BytesContainer bos ) { int pos ; while ( ( value & 0xFFFFFFFFFFFFFF80 L ) != 0L ) { // out.writeByte(((int) value & 0x7F) | 0x80); pos = bos . alloc ( ( short ) 1 ) ; bos . bytes [ pos ] = ( byte ) ( value & 0x7F | 0x80 ) ; value >>>= 7 ; } // out.writeByte((int) value & 0x7F); pos = bos . alloc ( ( short ) 1 ) ; bos . bytes [ pos ] = ( byte ) ( value & 0x7F ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param bytes to read bytes from [CODESPLIT] public static long readSignedVarLong ( final BytesContainer bytes ) { final long raw = readUnsignedVarLong ( bytes ) ; // This undoes the trick in writeSignedVarLong() final long temp = ( ( ( raw << 63 ) >> 63 ) ^ raw ) >> 1 ; // This extra step lets us deal with the largest signed values by // treating // negative results from read unsigned methods as like unsigned values // Must re-flip the top bit if the original read value had it set. return temp ^ ( raw & ( 1L << 63 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param bytes to read bytes from [CODESPLIT] public static long readUnsignedVarLong ( final BytesContainer bytes ) { long value = 0L ; int i = 0 ; long b ; while ( ( ( b = bytes . bytes [ bytes . offset ++ ] ) & 0x80 L ) != 0 ) { value |= ( b & 0x7F ) << i ; i += 7 ; if ( i > 63 ) throw new IllegalArgumentException ( \"Variable length quantity is too long (must be <= 63)\" ) ; } return value | ( b << i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Auto register myself as hook . [CODESPLIT] @ Override public void onOpen ( final ODatabaseInternal iDatabase ) { if ( ! isRelatedToLocalServer ( iDatabase ) ) return ; if ( isOffline ( ) && status != NODE_STATUS . STARTING ) return ; final ODatabaseDocumentInternal currDb = ODatabaseRecordThreadLocal . instance ( ) . getIfDefined ( ) ; try { final String dbName = iDatabase . getName ( ) ; final ODistributedConfiguration cfg = getDatabaseConfiguration ( dbName ) ; if ( cfg == null ) return ; } catch ( HazelcastException e ) { throw OException . wrapException ( new OOfflineNodeException ( \"Hazelcast instance is not available\" ) , e ) ; } catch ( HazelcastInstanceNotActiveException e ) { throw OException . wrapException ( new OOfflineNodeException ( \"Hazelcast instance is not available\" ) , e ) ; } finally { // RESTORE ORIGINAL DATABASE INSTANCE IN TL ODatabaseRecordThreadLocal . instance ( ) . set ( currDb ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs a database from the network . [CODESPLIT] protected void installDatabaseFromNetwork ( final String dbPath , final String databaseName , final ODistributedDatabaseImpl distrDatabase , final String iNode , final ODistributedDatabaseChunk firstChunk , final boolean delta , final File uniqueClustersBackupDirectory , final OModifiableDistributedConfiguration cfg ) { final String localNodeName = nodeName ; final AtomicReference < ODistributedMomentum > momentum = new AtomicReference < ODistributedMomentum > ( ) ; OSyncReceiver receiver = new OSyncReceiver ( this , databaseName , firstChunk , momentum , iNode , dbPath ) ; try { Thread t = new Thread ( receiver ) ; t . setUncaughtExceptionHandler ( new OUncaughtExceptionHandler ( ) ) ; t . start ( ) ; } catch ( Exception e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , \"Error on transferring database '%s' \" , e , databaseName ) ; throw OException . wrapException ( new ODistributedException ( \"Error on transferring database\" ) , e ) ; } final ODatabaseDocumentInternal db = installDatabaseOnLocalNode ( databaseName , dbPath , iNode , delta , uniqueClustersBackupDirectory , cfg , firstChunk . incremental , receiver ) ; if ( db == null ) return ; // OVERWRITE THE MOMENTUM FROM THE ORIGINAL SERVER AND ADD LAST LOCAL LSN try { distrDatabase . getSyncConfiguration ( ) . load ( ) ; distrDatabase . getSyncConfiguration ( ) . setLastLSN ( localNodeName , ( ( OLocalPaginatedStorage ) db . getStorage ( ) . getUnderlying ( ) ) . getLSN ( ) , false ) ; } catch ( IOException e ) { ODistributedServerLog . error ( this , nodeName , null , DIRECTION . NONE , \"Error on loading %s file for database '%s'\" , e , DISTRIBUTED_SYNC_JSON_FILENAME , databaseName ) ; } try { distrDatabase . setOnline ( ) ; } finally { db . activateOnCurrentThread ( ) ; db . close ( ) ; } // ASK FOR INDIVIDUAL CLUSTERS IN CASE OF SHARDING AND NO LOCAL COPY final Set < String > localManagedClusters = cfg . getClustersOnServer ( localNodeName ) ; final Set < String > sourceNodeClusters = cfg . getClustersOnServer ( iNode ) ; localManagedClusters . removeAll ( sourceNodeClusters ) ; final HashSet < String > toSynchClusters = new HashSet < String > ( ) ; for ( String cl : localManagedClusters ) { // FILTER CLUSTER CHECKING IF ANY NODE IS ACTIVE final List < String > servers = cfg . getServers ( cl , localNodeName ) ; getAvailableNodes ( servers , databaseName ) ; if ( ! servers . isEmpty ( ) ) toSynchClusters . add ( cl ) ; } // SYNC ALL THE CLUSTERS for ( String cl : toSynchClusters ) { // FILTER CLUSTER CHECKING IF ANY NODE IS ACTIVE OCommandExecutorSQLHASyncCluster . replaceCluster ( this , serverInstance , databaseName , cl ) ; } try { rebalanceClusterOwnership ( nodeName , db , cfg , false ) ; } catch ( Exception e ) { // HANDLE IT AS WARNING ODistributedServerLog . warn ( this , nodeName , null , DIRECTION . NONE , \"Error on re-balancing the cluster for database '%s'\" , e , databaseName ) ; // NOT CRITICAL, CONTINUE } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Guarantees that each class has own master cluster . [CODESPLIT] public boolean installClustersOfClass ( final ODatabaseInternal iDatabase , final OClass iClass , OModifiableDistributedConfiguration cfg ) { final String databaseName = iDatabase . getName ( ) ; if ( iClass . isAbstract ( ) ) return false ; // INIT THE DATABASE IF NEEDED getMessageService ( ) . registerDatabase ( databaseName , cfg ) ; return executeInDistributedDatabaseLock ( databaseName , 20000 , cfg , new OCallable < Boolean , OModifiableDistributedConfiguration > ( ) { @ Override public Boolean call ( final OModifiableDistributedConfiguration lastCfg ) { final Set < String > availableNodes = getAvailableNodeNames ( iDatabase . getName ( ) ) ; final List < String > cluster2Create = clusterAssignmentStrategy . assignClusterOwnershipOfClass ( iDatabase , lastCfg , iClass , availableNodes , true ) ; final Map < OClass , List < String > > cluster2CreateMap = new HashMap < OClass , List < String > > ( 1 ) ; cluster2CreateMap . put ( iClass , cluster2Create ) ; createClusters ( iDatabase , cluster2CreateMap , lastCfg ) ; return true ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes an operation protected by a distributed lock ( one per database ) . [CODESPLIT] public < T > T executeInDistributedDatabaseLock ( final String databaseName , final long timeoutLocking , OModifiableDistributedConfiguration lastCfg , final OCallable < T , OModifiableDistributedConfiguration > iCallback ) { boolean updated ; T result ; lockManagerRequester . acquireExclusiveLock ( databaseName , nodeName , timeoutLocking ) ; try { if ( lastCfg == null ) // ACQUIRE CFG INSIDE THE LOCK lastCfg = getDatabaseConfiguration ( databaseName ) . modify ( ) ; if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , nodeName , null , DIRECTION . NONE , \"Current distributed configuration for database '%s': %s\" , databaseName , lastCfg . getDocument ( ) . toJSON ( ) ) ; try { result = iCallback . call ( lastCfg ) ; } finally { if ( ODistributedServerLog . isDebugEnabled ( ) ) ODistributedServerLog . debug ( this , nodeName , null , DIRECTION . NONE , \"New distributed configuration for database '%s': %s\" , databaseName , lastCfg . getDocument ( ) . toJSON ( ) ) ; // CONFIGURATION CHANGED, UPDATE IT ON THE CLUSTER AND DISK updated = updateCachedDatabaseConfiguration ( databaseName , lastCfg , true ) ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { lockManagerRequester . releaseExclusiveLock ( databaseName , nodeName ) ; } if ( updated ) { // SEND NEW CFG TO ALL THE CONNECTED CLIENTS notifyClients ( databaseName ) ; serverInstance . getClientConnectionManager ( ) . pushDistribCfg2Clients ( getClusterConfiguration ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Avoids to dump the same configuration twice if it s unchanged since the last time . [CODESPLIT] protected void dumpServersStatus ( ) { final ODocument cfg = getClusterConfiguration ( ) ; final String compactStatus = ODistributedOutput . getCompactServerStatus ( this , cfg ) ; if ( ! lastServerDump . equals ( compactStatus ) ) { lastServerDump = compactStatus ; ODistributedServerLog . info ( this , getLocalNodeName ( ) , null , DIRECTION . NONE , \"Distributed servers status (*=current @=lockmgr[%s]):\\n%s\" , getLockManagerServer ( ) , ODistributedOutput . formatServerStatus ( this , cfg ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to find item in collection using passed in comparator . Only 0 value ( requested object is found ) returned by comparator is taken into account the rest is ignored . [CODESPLIT] public static < T > int indexOf ( final List < T > list , final T object , final Comparator < T > comparator ) { int i = 0 ; for ( final T item : list ) { if ( comparator . compare ( item , object ) == 0 ) return i ; i ++ ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to find an item in an array . [CODESPLIT] public static int indexOf ( final Object [ ] array , final Comparable object ) { for ( int i = 0 ; i < array . length ; ++ i ) { if ( object . compareTo ( array [ i ] ) == 0 ) // FOUND return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to find a number in an array . [CODESPLIT] public static int indexOf ( final int [ ] array , final int object ) { for ( int i = 0 ; i < array . length ; ++ i ) { if ( array [ i ] == object ) // FOUND return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile the filter conditions only the first time . [CODESPLIT] public OCommandExecutorSQLSelect parse ( final OCommandRequest iRequest ) { final OCommandRequestText textRequest = ( OCommandRequestText ) iRequest ; String queryText = textRequest . getText ( ) ; String originalQuery = queryText ; try { // System.out.println(\"NEW PARSER FROM: \" + queryText);\r queryText = preParse ( queryText , iRequest ) ; // System.out.println(\"NEW PARSER TO: \" + queryText);\r textRequest . setText ( queryText ) ; super . parse ( iRequest ) ; initContext ( ) ; final int pos = parseProjections ( ) ; if ( pos == - 1 ) { return this ; } final int endPosition = parserText . length ( ) ; parserNextWord ( true ) ; if ( parserGetLastWord ( ) . equalsIgnoreCase ( KEYWORD_FROM ) ) { // FROM\r parsedTarget = OSQLEngine . getInstance ( ) . parseTarget ( parserText . substring ( parserGetCurrentPosition ( ) , endPosition ) , getContext ( ) ) ; parserSetCurrentPosition ( parsedTarget . parserIsEnded ( ) ? endPosition : parsedTarget . parserGetCurrentPosition ( ) + parserGetCurrentPosition ( ) ) ; } else { parserGoBack ( ) ; } if ( ! parserIsEnded ( ) ) { parserSkipWhiteSpaces ( ) ; while ( ! parserIsEnded ( ) ) { final String w = parserNextWord ( true ) ; if ( ! w . isEmpty ( ) ) { if ( w . equals ( KEYWORD_WHERE ) ) { compiledFilter = OSQLEngine . getInstance ( ) . parseCondition ( parserText . substring ( parserGetCurrentPosition ( ) , endPosition ) , getContext ( ) , KEYWORD_WHERE ) ; optimize ( ) ; parserSetCurrentPosition ( compiledFilter . parserIsEnded ( ) ? endPosition : compiledFilter . parserGetCurrentPosition ( ) + parserGetCurrentPosition ( ) ) ; } else if ( w . equals ( KEYWORD_LET ) ) { parseLet ( ) ; } else if ( w . equals ( KEYWORD_GROUP ) ) { parseGroupBy ( ) ; } else if ( w . equals ( KEYWORD_ORDER ) ) { parseOrderBy ( ) ; } else if ( w . equals ( KEYWORD_UNWIND ) ) { parseUnwind ( ) ; } else if ( w . equals ( KEYWORD_LIMIT ) ) { parseLimit ( w ) ; } else if ( w . equals ( KEYWORD_SKIP ) || w . equals ( KEYWORD_OFFSET ) ) { parseSkip ( w ) ; } else if ( w . equals ( KEYWORD_FETCHPLAN ) ) { parseFetchplan ( w ) ; } else if ( w . equals ( KEYWORD_NOCACHE ) ) { parseNoCache ( w ) ; } else if ( w . equals ( KEYWORD_TIMEOUT ) ) { parseTimeout ( w ) ; } else if ( w . equals ( KEYWORD_LOCK ) ) { final String lock = parseLock ( ) ; if ( lock . equalsIgnoreCase ( \"DEFAULT\" ) ) { lockingStrategy = LOCKING_STRATEGY . DEFAULT ; } else if ( lock . equals ( \"NONE\" ) ) { lockingStrategy = LOCKING_STRATEGY . NONE ; } else if ( lock . equals ( \"RECORD\" ) ) { lockingStrategy = LOCKING_STRATEGY . EXCLUSIVE_LOCK ; } else if ( lock . equals ( \"SHARED\" ) ) { lockingStrategy = LOCKING_STRATEGY . SHARED_LOCK ; } } else if ( w . equals ( KEYWORD_PARALLEL ) ) { parallel = parseParallel ( w ) ; } else { if ( preParsedStatement == null ) { throwParsingException ( \"Invalid keyword '\" + w + \"'\" ) ; } //if the pre-parsed statement is OK, then you can go on with the rest, the SQL is valid and this is probably a space in a backtick\r } } } } if ( limit == 0 || limit < - 1 ) { throw new IllegalArgumentException ( \"Limit must be > 0 or = -1 (no limit)\" ) ; } validateQuery ( ) ; } finally { textRequest . setText ( originalQuery ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine clusters that are used in select operation [CODESPLIT] @ Override public Set < String > getInvolvedClusters ( ) { final Set < String > clusters = new HashSet < String > ( ) ; if ( parsedTarget != null ) { final ODatabaseDocument db = getDatabase ( ) ; if ( parsedTarget . getTargetQuery ( ) != null && parsedTarget . getTargetRecords ( ) instanceof OCommandExecutorSQLResultsetDelegate ) { // SUB-QUERY: EXECUTE IT LOCALLY\r // SUB QUERY, PROPAGATE THE CALL\r final Set < String > clIds = ( ( OCommandExecutorSQLResultsetDelegate ) parsedTarget . getTargetRecords ( ) ) . getInvolvedClusters ( ) ; for ( String c : clIds ) { // FILTER THE CLUSTER WHERE THE USER HAS THE RIGHT ACCESS\r if ( checkClusterAccess ( db , c ) ) { clusters . add ( c ) ; } } } else if ( parsedTarget . getTargetRecords ( ) != null ) { // SINGLE RECORDS: BROWSE ALL (COULD BE EXPENSIVE).\r for ( OIdentifiable identifiable : parsedTarget . getTargetRecords ( ) ) { final String c = db . getClusterNameById ( identifiable . getIdentity ( ) . getClusterId ( ) ) . toLowerCase ( Locale . ENGLISH ) ; // FILTER THE CLUSTER WHERE THE USER HAS THE RIGHT ACCESS\r if ( checkClusterAccess ( db , c ) ) { clusters . add ( c ) ; } } } if ( parsedTarget . getTargetClasses ( ) != null ) { return getInvolvedClustersOfClasses ( parsedTarget . getTargetClasses ( ) . values ( ) ) ; } if ( parsedTarget . getTargetClusters ( ) != null ) { return getInvolvedClustersOfClusters ( parsedTarget . getTargetClusters ( ) . keySet ( ) ) ; } if ( parsedTarget . getTargetIndex ( ) != null ) { // EXTRACT THE CLASS NAME -> CLUSTERS FROM THE INDEX DEFINITION\r return getInvolvedClustersOfIndex ( parsedTarget . getTargetIndex ( ) ) ; } } return clusters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the record in result . [CODESPLIT] @ Override protected boolean handleResult ( final OIdentifiable iRecord , final OCommandContext iContext ) { lastRecord = iRecord ; if ( ( orderedFields . isEmpty ( ) || fullySortedByIndex || isRidOnlySort ( ) ) && skip > 0 && this . unwindFields == null && this . expandTarget == null ) { lastRecord = null ; skip -- ; return true ; } if ( ! addResult ( lastRecord , iContext ) ) { return false ; } return continueSearching ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the temporary RID counter assuring it s unique per query tree . [CODESPLIT] public int getTemporaryRIDCounter ( final OCommandContext iContext ) { final OTemporaryRidGenerator parentQuery = ( OTemporaryRidGenerator ) iContext . getVariable ( \"parentQuery\" ) ; return parentQuery != null && parentQuery != this ? parentQuery . getTemporaryRIDCounter ( iContext ) : serialTempRID . getAndIncrement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in case of ORDER BY + SKIP + LIMIT this method applies ORDER BY operation on partial result and discards overflowing results ( results > skip + limit ) [CODESPLIT] private void applyPartialOrderBy ( ) { if ( expandTarget != null || ( unwindFields != null && unwindFields . size ( ) > 0 ) || orderedFields . isEmpty ( ) || fullySortedByIndex || isRidOnlySort ( ) ) { return ; } if ( limit > 0 ) { int sortBufferSize = limit + 1 ; if ( skip > 0 ) { sortBufferSize += skip ; } if ( tempResult instanceof List && ( ( List ) tempResult ) . size ( ) >= sortBufferSize + PARTIAL_SORT_BUFFER_THRESHOLD ) { applyOrderBy ( false ) ; tempResult = new ArrayList ( ( ( List ) tempResult ) . subList ( 0 , sortBufferSize ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Report the tip to the profiler and collect it in context to be reported by tools like Studio [CODESPLIT] protected void reportTip ( final String iMessage ) { Orient . instance ( ) . getProfiler ( ) . reportTip ( iMessage ) ; List < String > tips = ( List < String > ) context . getVariable ( \"tips\" ) ; if ( tips == null ) { tips = new ArrayList < String > ( 3 ) ; context . setVariable ( \"tips\" , tips ) ; } tips . add ( iMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the fetchplan keyword if found . [CODESPLIT] protected boolean parseFetchplan ( final String w ) throws OCommandSQLParsingException { if ( ! w . equals ( KEYWORD_FETCHPLAN ) ) { return false ; } parserSkipWhiteSpaces ( ) ; int start = parserGetCurrentPosition ( ) ; parserNextWord ( true ) ; int end = parserGetCurrentPosition ( ) ; parserSkipWhiteSpaces ( ) ; int position = parserGetCurrentPosition ( ) ; while ( ! parserIsEnded ( ) ) { final String word = OIOUtils . getStringContent ( parserNextWord ( true ) ) ; if ( ! OPatternConst . PATTERN_FETCH_PLAN . matcher ( word ) . matches ( ) ) { break ; } end = parserGetCurrentPosition ( ) ; parserSkipWhiteSpaces ( ) ; position = parserGetCurrentPosition ( ) ; } parserSetCurrentPosition ( position ) ; if ( end < 0 ) { fetchPlan = OIOUtils . getStringContent ( parserText . substring ( start ) ) ; } else { fetchPlan = OIOUtils . getStringContent ( parserText . substring ( start , end ) ) ; } request . setFetchPlan ( fetchPlan ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the NOCACHE keyword if found . [CODESPLIT] protected boolean parseNoCache ( final String w ) throws OCommandSQLParsingException { if ( ! w . equals ( KEYWORD_NOCACHE ) ) return false ; noCache = true ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use index to order documents by provided fields . [CODESPLIT] private boolean optimizeSort ( OClass iSchemaClass ) { OIndexCursor cursor = getOptimizedSortCursor ( iSchemaClass ) ; if ( cursor != null ) { fetchValuesFromIndexCursor ( cursor ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the content of collections and / or links and put it as result [CODESPLIT] private void applyExpand ( ) { if ( expandTarget == null ) { return ; } final long startExpand = System . currentTimeMillis ( ) ; try { if ( tempResult == null ) { tempResult = new ArrayList < OIdentifiable > ( ) ; if ( expandTarget instanceof OSQLFilterItemVariable ) { Object r = ( ( OSQLFilterItemVariable ) expandTarget ) . getValue ( null , null , context ) ; if ( r != null ) { if ( r instanceof OIdentifiable ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) r ) ; } else if ( r instanceof Iterator || OMultiValue . isMultiValue ( r ) ) { for ( Object o : OMultiValue . getMultiValueIterable ( r ) ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) o ) ; } } } } else if ( expandTarget instanceof OSQLFunctionRuntime && ! hasFieldItemParams ( ( OSQLFunctionRuntime ) expandTarget ) ) { if ( ( ( OSQLFunctionRuntime ) expandTarget ) . aggregateResults ( ) ) { throw new OCommandExecutionException ( \"Unsupported operation: aggregate function in expand(\" + expandTarget + \")\" ) ; } else { Object r = ( ( OSQLFunctionRuntime ) expandTarget ) . execute ( null , null , null , context ) ; if ( r instanceof OIdentifiable ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) r ) ; } else if ( r instanceof Iterator || OMultiValue . isMultiValue ( r ) ) { for ( Object o : OMultiValue . getMultiValueIterable ( r ) ) { ( ( Collection < OIdentifiable > ) tempResult ) . add ( ( OIdentifiable ) o ) ; } } } } } else { if ( tempResult == null ) { tempResult = new ArrayList < OIdentifiable > ( ) ; } final OMultiCollectionIterator < OIdentifiable > finalResult = new OMultiCollectionIterator < OIdentifiable > ( ) ; if ( orderedFields == null || orderedFields . size ( ) == 0 ) { // expand is applied before sorting, so limiting the result set here would give wrong results\r int iteratorLimit = 0 ; if ( limit < 0 ) { iteratorLimit = - 1 ; } else { iteratorLimit += limit ; } finalResult . setLimit ( iteratorLimit ) ; finalResult . setSkip ( skip ) ; } for ( OIdentifiable id : tempResult ) { Object fieldValue ; if ( expandTarget instanceof OSQLFilterItem ) { fieldValue = ( ( OSQLFilterItem ) expandTarget ) . getValue ( id . getRecord ( ) , null , context ) ; } else if ( expandTarget instanceof OSQLFunctionRuntime ) { fieldValue = ( ( OSQLFunctionRuntime ) expandTarget ) . getResult ( ) ; } else { fieldValue = expandTarget . toString ( ) ; } if ( fieldValue != null ) { if ( fieldValue instanceof Iterable && ! ( fieldValue instanceof OIdentifiable ) ) { fieldValue = ( ( Iterable ) fieldValue ) . iterator ( ) ; } if ( fieldValue instanceof ODocument ) { ArrayList < ODocument > partial = new ArrayList < ODocument > ( ) ; partial . add ( ( ODocument ) fieldValue ) ; finalResult . add ( partial ) ; } else if ( fieldValue instanceof Collection < ? > || fieldValue . getClass ( ) . isArray ( ) || fieldValue instanceof Iterator < ? > || fieldValue instanceof OIdentifiable || fieldValue instanceof ORidBag ) { finalResult . add ( fieldValue ) ; } else if ( fieldValue instanceof Map < ? , ? > ) { finalResult . add ( ( ( Map < ? , OIdentifiable > ) fieldValue ) . values ( ) ) ; } } } tempResult = finalResult ; } } finally { context . setVariable ( \"expandElapsed\" , ( System . currentTimeMillis ( ) - startExpand ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Single Job Status [CODESPLIT] public ODocument status ( ) { synchronized ( listener ) { ODocument status = new ODocument ( ) ; status . field ( \"cfg\" , cfg ) ; status . field ( \"status\" , this . status ) ; String lastBatchLog = \"\" ; if ( this . messageHandler != null ) { lastBatchLog = extractBatchLog ( ) ; } status . field ( \"log\" , lastBatchLog ) ; if ( this . status == Status . FINISHED ) { listener . notifyAll ( ) ; } return status ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegates the execution to the configured command executor . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < RET > RET execute ( final Object ... iArgs ) { setParameters ( iArgs ) ; OExecutionThreadLocal . INSTANCE . get ( ) . onAsyncReplicationOk = onAsyncReplicationOk ; OExecutionThreadLocal . INSTANCE . get ( ) . onAsyncReplicationError = onAsyncReplicationError ; return ( RET ) ODatabaseRecordThreadLocal . instance ( ) . get ( ) . getStorage ( ) . command ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Internal only ) Creates a link between a vertices and a Graph Element . [CODESPLIT] public static Object createLink ( final ODocument iFromVertex , final OIdentifiable iTo , final String iFieldName ) { final Object out ; OType outType = iFromVertex . fieldType ( iFieldName ) ; Object found = iFromVertex . field ( iFieldName ) ; final OClass linkClass = ODocumentInternal . getImmutableSchemaClass ( iFromVertex ) ; if ( linkClass == null ) throw new IllegalArgumentException ( \"Class not found in source vertex: \" + iFromVertex ) ; final OProperty prop = linkClass . getProperty ( iFieldName ) ; final OType propType = prop != null && prop . getType ( ) != OType . ANY ? prop . getType ( ) : null ; if ( found == null ) { if ( propType == OType . LINKLIST || ( prop != null && \"true\" . equalsIgnoreCase ( prop . getCustom ( \"ordered\" ) ) ) ) { //TODO constant final Collection coll = new ORecordLazyList ( iFromVertex ) ; coll . add ( iTo ) ; out = coll ; outType = OType . LINKLIST ; } else if ( propType == null || propType == OType . LINKBAG ) { final ORidBag bag = new ORidBag ( ) ; bag . add ( iTo ) ; out = bag ; outType = OType . LINKBAG ; } else if ( propType == OType . LINK ) { out = iTo ; outType = OType . LINK ; } else throw new ODatabaseException ( \"Type of field provided in schema '\" + prop . getType ( ) + \"' cannot be used for link creation.\" ) ; } else if ( found instanceof OIdentifiable ) { if ( prop != null && propType == OType . LINK ) throw new ODatabaseException ( \"Type of field provided in schema '\" + prop . getType ( ) + \"' cannot be used for creation to hold several links.\" ) ; if ( prop != null && \"true\" . equalsIgnoreCase ( prop . getCustom ( \"ordered\" ) ) ) { //TODO constant final Collection coll = new ORecordLazyList ( iFromVertex ) ; coll . add ( found ) ; coll . add ( iTo ) ; out = coll ; outType = OType . LINKLIST ; } else { final ORidBag bag = new ORidBag ( ) ; bag . add ( ( OIdentifiable ) found ) ; bag . add ( iTo ) ; out = bag ; outType = OType . LINKBAG ; } } else if ( found instanceof ORidBag ) { // ADD THE LINK TO THE COLLECTION out = null ; ( ( ORidBag ) found ) . add ( iTo . getRecord ( ) ) ; } else if ( found instanceof Collection < ? > ) { // USE THE FOUND COLLECTION out = null ; ( ( Collection < Object > ) found ) . add ( iTo ) ; } else throw new ODatabaseException ( \"Relationship content is invalid on field \" + iFieldName + \". Found: \" + found ) ; if ( out != null ) // OVERWRITE IT iFromVertex . field ( iFieldName , out , outType ) ; return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "That is internal method which is called once we encounter any error inside of JVM . In such case we need to restart JVM to avoid any data corruption . Till JVM is not restarted storage will be put in read - only state . [CODESPLIT] public final void handleJVMError ( final Error e ) { if ( jvmError . compareAndSet ( null , e ) ) { OLogManager . instance ( ) . errorNoDb ( this , \"JVM error was thrown\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method finds all the records which were updated starting from ( but not including ) current LSN and write result in provided output stream . In output stream will be included all thw records which were updated / deleted / created since passed in LSN till the current moment . Deleted records are written in output stream first then created / updated records . All records are sorted by record id . Data format : <ol > <li > Amount of records ( single entry ) - 8 bytes< / li > <li > Record s cluster id - 4 bytes< / li > <li > Record s cluster position - 8 bytes< / li > <li > Delete flag 1 if record is deleted - 1 byte< / li > <li > Record version only if record is not deleted - 4 bytes< / li > <li > Record type only if record is not deleted - 1 byte< / li > <li > Length of binary presentation of record only if record is not deleted - 4 bytes< / li > <li > Binary presentation of the record only if record is not deleted - length of content is provided in above entity< / li > < / ol > [CODESPLIT] public OBackgroundDelta recordsChangedAfterLSN ( final OLogSequenceNumber lsn , final OCommandOutputListener outputListener ) { final OLogSequenceNumber endLsn ; // container of rids of changed records final SortedSet < ORID > sortedRids = new TreeSet <> ( ) ; try { if ( ! configuration . getContextConfiguration ( ) . getValueAsBoolean ( OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL ) ) { throw new IllegalStateException ( \"Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, \" + \"to switch it on please set property \" + OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getKey ( ) + \" to the true value, please note that only records\" + \" which are stored after this property was set will be retrieved\" ) ; } stateLock . acquireReadLock ( ) ; try { if ( writeAheadLog == null ) { return null ; } // we iterate till the last record is contained in wal at the moment when we call this method endLsn = writeAheadLog . end ( ) ; if ( endLsn == null || lsn . compareTo ( endLsn ) > 0 ) { OLogManager . instance ( ) . warn ( this , \"Cannot find requested LSN=%s for database sync operation. Last available LSN is %s\" , lsn , endLsn ) ; return null ; } if ( lsn . equals ( endLsn ) ) { // nothing has changed return new OBackgroundDelta ( endLsn ) ; } List < OWriteableWALRecord > records = writeAheadLog . next ( lsn , 1 ) ; if ( records . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , \"Cannot find requested LSN=%s for database sync operation (last available LSN is %s)\" , lsn , endLsn ) ; return null ; } final OLogSequenceNumber freezeLsn = records . get ( 0 ) . getLsn ( ) ; writeAheadLog . addCutTillLimit ( freezeLsn ) ; try { records = writeAheadLog . next ( lsn , 1_000 ) ; if ( records . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , \"Cannot find requested LSN=%s for database sync operation (last available LSN is %s)\" , lsn , endLsn ) ; return null ; } // all information about changed records is contained in atomic operation metadata long read = 0 ; readLoop : while ( ! records . isEmpty ( ) ) { for ( final OWALRecord record : records ) { final OLogSequenceNumber recordLSN = record . getLsn ( ) ; if ( endLsn . compareTo ( recordLSN ) >= 0 ) { if ( record instanceof OFileCreatedWALRecord ) { throw new ODatabaseException ( \"Cannot execute delta-sync because a new file has been added. Filename: '\" + ( ( OFileCreatedWALRecord ) record ) . getFileName ( ) + \"' (id=\" + ( ( OFileCreatedWALRecord ) record ) . getFileId ( ) + \")\" ) ; } if ( record instanceof OFileDeletedWALRecord ) { throw new ODatabaseException ( \"Cannot execute delta-sync because a file has been deleted. File id: \" + ( ( OFileDeletedWALRecord ) record ) . getFileId ( ) ) ; } if ( record instanceof OAtomicUnitEndRecord ) { final OAtomicUnitEndRecord atomicUnitEndRecord = ( OAtomicUnitEndRecord ) record ; if ( atomicUnitEndRecord . getAtomicOperationMetadata ( ) . containsKey ( ORecordOperationMetadata . RID_METADATA_KEY ) ) { final ORecordOperationMetadata recordOperationMetadata = ( ORecordOperationMetadata ) atomicUnitEndRecord . getAtomicOperationMetadata ( ) . get ( ORecordOperationMetadata . RID_METADATA_KEY ) ; final Set < ORID > rids = recordOperationMetadata . getValue ( ) ; sortedRids . addAll ( rids ) ; } } read ++ ; if ( outputListener != null ) { outputListener . onMessage ( \"read \" + read + \" records from WAL and collected \" + sortedRids . size ( ) + \" records\" ) ; } } else { break readLoop ; } } records = writeAheadLog . next ( records . get ( records . size ( ) - 1 ) . getLsn ( ) , 1_000 ) ; } } finally { writeAheadLog . removeCutTillLimit ( freezeLsn ) ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( \"Error of reading of records changed after LSN \" + lsn ) , e ) ; } finally { stateLock . releaseReadLock ( ) ; } OBackgroundDelta b = new OBackgroundDelta ( this , outputListener , sortedRids , lsn , endLsn ) ; return b ; } catch ( final RuntimeException e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Error e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method finds all the records changed in the last X transactions . [CODESPLIT] public Set < ORecordId > recordsChangedRecently ( final int maxEntries ) { final SortedSet < ORecordId > result = new TreeSet <> ( ) ; try { if ( ! OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getValueAsBoolean ( ) ) { throw new IllegalStateException ( \"Cannot find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, \" + \"to switch it on please set property \" + OGlobalConfiguration . STORAGE_TRACK_CHANGED_RECORDS_IN_WAL . getKey ( ) + \" to the true value, please note that only records\" + \" which are stored after this property was set will be retrieved\" ) ; } stateLock . acquireReadLock ( ) ; try { if ( writeAheadLog == null ) { OLogManager . instance ( ) . warn ( this , \"No WAL found for database '%s'\" , name ) ; return null ; } OLogSequenceNumber startLsn = writeAheadLog . begin ( ) ; if ( startLsn == null ) { OLogManager . instance ( ) . warn ( this , \"The WAL is empty for database '%s'\" , name ) ; return result ; } final OLogSequenceNumber freezeLSN = startLsn ; writeAheadLog . addCutTillLimit ( freezeLSN ) ; try { //reread because log may be already truncated startLsn = writeAheadLog . begin ( ) ; if ( startLsn == null ) { OLogManager . instance ( ) . warn ( this , \"The WAL is empty for database '%s'\" , name ) ; return result ; } final OLogSequenceNumber endLsn = writeAheadLog . end ( ) ; if ( endLsn == null ) { OLogManager . instance ( ) . warn ( this , \"The WAL is empty for database '%s'\" , name ) ; return result ; } List < OWriteableWALRecord > walRecords = writeAheadLog . read ( startLsn , 1_000 ) ; if ( walRecords . isEmpty ( ) ) { OLogManager . instance ( ) . info ( this , \"Cannot find requested LSN=%s for database sync operation (record in WAL is absent)\" , startLsn ) ; return null ; } // KEEP LAST MAX-ENTRIES TRANSACTIONS' LSN final List < OAtomicUnitEndRecord > lastTx = new ArrayList <> ( 1024 ) ; readLoop : while ( ! walRecords . isEmpty ( ) ) { for ( final OWriteableWALRecord walRecord : walRecords ) { final OLogSequenceNumber recordLSN = walRecord . getLsn ( ) ; if ( endLsn . compareTo ( recordLSN ) >= 0 ) { if ( walRecord instanceof OAtomicUnitEndRecord ) { if ( lastTx . size ( ) >= maxEntries ) { lastTx . remove ( 0 ) ; } lastTx . add ( ( OAtomicUnitEndRecord ) walRecord ) ; } } else { break readLoop ; } } walRecords = writeAheadLog . next ( walRecords . get ( walRecords . size ( ) - 1 ) . getLsn ( ) , 1_000 ) ; } // COLLECT ALL THE MODIFIED RECORDS for ( final OAtomicUnitEndRecord atomicUnitEndRecord : lastTx ) { if ( atomicUnitEndRecord . getAtomicOperationMetadata ( ) . containsKey ( ORecordOperationMetadata . RID_METADATA_KEY ) ) { final ORecordOperationMetadata recordOperationMetadata = ( ORecordOperationMetadata ) atomicUnitEndRecord . getAtomicOperationMetadata ( ) . get ( ORecordOperationMetadata . RID_METADATA_KEY ) ; final Set < ORID > rids = recordOperationMetadata . getValue ( ) ; for ( final ORID rid : rids ) { result . add ( ( ORecordId ) rid ) ; } } } OLogManager . instance ( ) . info ( this , \"Found %d records changed in last %d operations\" , result . size ( ) , lastTx . size ( ) ) ; return result ; } finally { writeAheadLog . removeCutTillLimit ( freezeLSN ) ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( \"Error on reading last changed records\" ) , e ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Error e ) { throw logAndPrepareForRethrow ( e ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts to gather information about storage performance for current thread . Details which performance characteristics are gathered can be found at { @link OSessionStoragePerformanceStatistic } . [CODESPLIT] public void startGatheringPerformanceStatisticForCurrentThread ( ) { try { performanceStatisticManager . startThreadMonitoring ( ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completes gathering performance characteristics for current thread initiated by call of { @link #startGatheringPerformanceStatisticForCurrentThread () } [CODESPLIT] public OSessionStoragePerformanceStatistic completeGatheringPerformanceStatisticForCurrentThread ( ) { try { return performanceStatisticManager . stopThreadMonitoring ( ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan the given transaction for new record and allocate a record id for them the relative record id is inserted inside the transaction for future use . [CODESPLIT] public void preallocateRids ( final OTransactionInternal clientTx ) { try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; final Iterable < ORecordOperation > entries = clientTx . getRecordOperations ( ) ; final TreeMap < Integer , OCluster > clustersToLock = new TreeMap <> ( ) ; final Set < ORecordOperation > newRecords = new TreeSet <> ( COMMIT_RECORD_OPERATION_COMPARATOR ) ; for ( final ORecordOperation txEntry : entries ) { if ( txEntry . type == ORecordOperation . CREATED ) { newRecords . add ( txEntry ) ; final int clusterId = txEntry . getRID ( ) . getClusterId ( ) ; clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } } stateLock . acquireReadLock ( ) ; try { checkOpenness ( ) ; makeStorageDirty ( ) ; boolean rollback = false ; atomicOperationsManager . startAtomicOperation ( ( String ) null , true ) ; try { lockClusters ( clustersToLock ) ; for ( final ORecordOperation txEntry : newRecords ) { final ORecord rec = txEntry . getRecord ( ) ; if ( ! rec . getIdentity ( ) . isPersistent ( ) ) { if ( rec . isDirty ( ) ) { //This allocate a position for a new record final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) . copy ( ) ; final ORecordId oldRID = rid . copy ( ) ; final OCluster cluster = getClusterById ( rid . getClusterId ( ) ) ; final OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; rid . setClusterPosition ( ppos . clusterPosition ) ; clientTx . updateIdentityAfterCommit ( oldRID , rid ) ; } } else { //This allocate position starting from a valid rid, used in distributed for allocate the same position on other nodes final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) ; final OPaginatedCluster cluster = ( OPaginatedCluster ) getClusterById ( rid . getClusterId ( ) ) ; OPaginatedCluster . RECORD_STATUS recordStatus = cluster . getRecordStatus ( rid . getClusterPosition ( ) ) ; if ( recordStatus == OPaginatedCluster . RECORD_STATUS . NOT_EXISTENT ) { OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; while ( ppos . clusterPosition < rid . getClusterPosition ( ) ) { ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; } if ( ppos . clusterPosition != rid . getClusterPosition ( ) ) { throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , ppos . clusterPosition ) ) ; } } else if ( recordStatus == OPaginatedCluster . RECORD_STATUS . PRESENT || recordStatus == OPaginatedCluster . RECORD_STATUS . REMOVED ) { final OPhysicalPosition ppos = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , ppos . clusterPosition ) ) ; } } } } catch ( final Exception e ) { rollback = true ; throw e ; } finally { atomicOperationsManager . endAtomicOperation ( rollback ) ; } } catch ( final IOException | RuntimeException ioe ) { throw OException . wrapException ( new OStorageException ( \"Could not preallocate RIDs\" ) , ioe ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The commit operation can be run in 3 different conditions embedded commit pre - allocated commit other node commit . <bold > Embedded commit< / bold > is the basic commit where the operation is run in embedded or server side the transaction arrive with invalid rids that get allocated and committed . <bold > pre - allocated commit< / bold > is the commit that happen after an preAllocateRids call is done this is usually run by the coordinator of a tx in distributed . <bold > other node commit< / bold > is the commit that happen when a node execute a transaction of another node where all the rids are already allocated in the other node . [CODESPLIT] private List < ORecordOperation > commit ( final OTransactionInternal transaction , final boolean allocated ) { // XXX: At this moment, there are two implementations of the commit method. One for regular client transactions and one for // implicit micro-transactions. The implementations are quite identical, but operate on slightly different data. If you change // this method don't forget to change its counterpart: // //  OAbstractPaginatedStorage.commit(com.orientechnologies.orient.core.storage.impl.local.OMicroTransaction) try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; txBegun . incrementAndGet ( ) ; final ODatabaseDocumentInternal database = transaction . getDatabase ( ) ; final OIndexManager indexManager = database . getMetadata ( ) . getIndexManager ( ) ; final TreeMap < String , OTransactionIndexChanges > indexOperations = getSortedIndexOperations ( transaction ) ; database . getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; final Collection < ORecordOperation > recordOperations = transaction . getRecordOperations ( ) ; final TreeMap < Integer , OCluster > clustersToLock = new TreeMap <> ( ) ; final Map < ORecordOperation , Integer > clusterOverrides = new IdentityHashMap <> ( 8 ) ; final Set < ORecordOperation > newRecords = new TreeSet <> ( COMMIT_RECORD_OPERATION_COMPARATOR ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . CREATED || recordOperation . type == ORecordOperation . UPDATED ) { final ORecord record = recordOperation . getRecord ( ) ; if ( record instanceof ODocument ) { ( ( ODocument ) record ) . validate ( ) ; } } if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { final int clusterId = recordOperation . getRecord ( ) . getIdentity ( ) . getClusterId ( ) ; clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } else if ( recordOperation . type == ORecordOperation . CREATED ) { newRecords . add ( recordOperation ) ; final ORecord record = recordOperation . getRecord ( ) ; final ORID rid = record . getIdentity ( ) ; int clusterId = rid . getClusterId ( ) ; if ( record . isDirty ( ) && clusterId == ORID . CLUSTER_ID_INVALID && record instanceof ODocument ) { // TRY TO FIX CLUSTER ID TO THE DEFAULT CLUSTER ID DEFINED IN SCHEMA CLASS final OImmutableClass class_ = ODocumentInternal . getImmutableSchemaClass ( ( ( ODocument ) record ) ) ; if ( class_ != null ) { clusterId = class_ . getClusterForNewInstance ( ( ODocument ) record ) ; clusterOverrides . put ( recordOperation , clusterId ) ; } } clustersToLock . put ( clusterId , getClusterById ( clusterId ) ) ; } } final List < ORecordOperation > result = new ArrayList <> ( 8 ) ; stateLock . acquireReadLock ( ) ; try { if ( modificationLock ) { final List < ORID > recordLocks = new ArrayList <> ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { recordLocks . add ( recordOperation . getRID ( ) ) ; } } final Set < ORID > locked = transaction . getLockedRecords ( ) ; if ( locked != null ) { recordLocks . removeAll ( locked ) ; } Collections . sort ( recordLocks ) ; for ( final ORID rid : recordLocks ) { acquireWriteLock ( rid ) ; } } try { checkOpenness ( ) ; makeStorageDirty ( ) ; boolean rollback = false ; startStorageTx ( transaction ) ; try { final OAtomicOperation atomicOperation = OAtomicOperationsManager . getCurrentOperation ( ) ; lockClusters ( clustersToLock ) ; checkReadOnlyConditions ( ) ; final Map < ORecordOperation , OPhysicalPosition > positions = new IdentityHashMap <> ( 8 ) ; for ( final ORecordOperation recordOperation : newRecords ) { final ORecord rec = recordOperation . getRecord ( ) ; if ( allocated ) { if ( rec . getIdentity ( ) . isPersistent ( ) ) { positions . put ( recordOperation , new OPhysicalPosition ( rec . getIdentity ( ) . getClusterPosition ( ) ) ) ; } else { throw new OStorageException ( \"Impossible to commit a transaction with not valid rid in pre-allocated commit\" ) ; } } else if ( rec . isDirty ( ) && ! rec . getIdentity ( ) . isPersistent ( ) ) { final ORecordId rid = ( ORecordId ) rec . getIdentity ( ) . copy ( ) ; final ORecordId oldRID = rid . copy ( ) ; final Integer clusterOverride = clusterOverrides . get ( recordOperation ) ; final int clusterId = clusterOverride == null ? rid . getClusterId ( ) : clusterOverride ; final OCluster cluster = getClusterById ( clusterId ) ; assert atomicOperation . getCounter ( ) == 1 ; OPhysicalPosition physicalPosition = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; assert atomicOperation . getCounter ( ) == 1 ; rid . setClusterId ( cluster . getId ( ) ) ; if ( rid . getClusterPosition ( ) > - 1 ) { // CREATE EMPTY RECORDS UNTIL THE POSITION IS REACHED. THIS IS THE CASE WHEN A SERVER IS OUT OF SYNC // BECAUSE A TRANSACTION HAS BEEN ROLLED BACK BEFORE TO SEND THE REMOTE CREATES. SO THE OWNER NODE DELETED // RECORD HAVING A HIGHER CLUSTER POSITION while ( rid . getClusterPosition ( ) > physicalPosition . clusterPosition ) { assert atomicOperation . getCounter ( ) == 1 ; physicalPosition = cluster . allocatePosition ( ORecordInternal . getRecordType ( rec ) ) ; assert atomicOperation . getCounter ( ) == 1 ; } if ( rid . getClusterPosition ( ) != physicalPosition . clusterPosition ) { throw new OConcurrentCreateException ( rid , new ORecordId ( rid . getClusterId ( ) , physicalPosition . clusterPosition ) ) ; } } positions . put ( recordOperation , physicalPosition ) ; rid . setClusterPosition ( physicalPosition . clusterPosition ) ; transaction . updateIdentityAfterCommit ( oldRID , rid ) ; } } lockRidBags ( clustersToLock , indexOperations , indexManager ) ; checkReadOnlyConditions ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { assert atomicOperation . getCounter ( ) == 1 ; commitEntry ( recordOperation , positions . get ( recordOperation ) , database . getSerializer ( ) ) ; assert atomicOperation . getCounter ( ) == 1 ; result . add ( recordOperation ) ; } lockIndexes ( indexOperations ) ; checkReadOnlyConditions ( ) ; commitIndexes ( indexOperations , atomicOperation ) ; } catch ( final IOException | RuntimeException e ) { rollback = true ; if ( e instanceof RuntimeException ) { throw ( ( RuntimeException ) e ) ; } else { throw OException . wrapException ( new OStorageException ( \"Error during transaction commit\" ) , e ) ; } } finally { if ( rollback ) { rollback ( transaction ) ; } else { endStorageTx ( transaction , recordOperations ) ; } this . transaction . set ( null ) ; } } finally { atomicOperationsManager . ensureThatComponentsUnlocked ( ) ; database . getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; } } finally { try { if ( modificationLock ) { final List < ORID > recordLocks = new ArrayList <> ( ) ; for ( final ORecordOperation recordOperation : recordOperations ) { if ( recordOperation . type == ORecordOperation . UPDATED || recordOperation . type == ORecordOperation . DELETED ) { recordLocks . add ( recordOperation . getRID ( ) ) ; } } final Set < ORID > locked = transaction . getLockedRecords ( ) ; if ( locked != null ) { recordLocks . removeAll ( locked ) ; } for ( final ORID rid : recordLocks ) { releaseWriteLock ( rid ) ; } } } finally { stateLock . releaseReadLock ( ) ; } } if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) { OLogManager . instance ( ) . debug ( this , \"%d Committed transaction %d on database '%s' (result=%s)\" , Thread . currentThread ( ) . getId ( ) , transaction . getId ( ) , database . getName ( ) , result ) ; } return result ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { handleJVMError ( ee ) ; OAtomicOperationsManager . alarmClearOfAtomicOperation ( ) ; throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the given value under the given key into this storage for the index with the given index id . Validates the operation using the provided validator . [CODESPLIT] @ SuppressWarnings ( \"UnusedReturnValue\" ) public boolean validatedPutIndexValue ( int indexId , final Object key , final ORID value , final OBaseIndexEngine . Validator < Object , ORID > validator ) throws OInvalidIndexEngineIdException { indexId = extractInternalId ( indexId ) ; try { if ( transaction . get ( ) != null ) { return doValidatedPutIndexValue ( indexId , key , value , validator ) ; } checkOpenness ( ) ; stateLock . acquireReadLock ( ) ; try { checkOpenness ( ) ; checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) ; return doValidatedPutIndexValue ( indexId , key , value , validator ) ; } finally { stateLock . releaseReadLock ( ) ; } } catch ( final OInvalidIndexEngineIdException ie ) { throw logAndPrepareForRethrow ( ie ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rollbacks the given micro - transaction . [CODESPLIT] public void rollback ( final OMicroTransaction microTransaction ) { try { checkOpenness ( ) ; stateLock . acquireReadLock ( ) ; try { try { checkOpenness ( ) ; if ( transaction . get ( ) == null ) { return ; } if ( transaction . get ( ) . getMicroTransaction ( ) . getId ( ) != microTransaction . getId ( ) ) { throw new OStorageException ( \"Passed in and active micro-transaction are different micro-transactions. Passed in micro-transaction cannot be \" + \"rolled back.\" ) ; } makeStorageDirty ( ) ; rollbackStorageTx ( ) ; microTransaction . updateRecordCacheAfterRollback ( ) ; txRollback . incrementAndGet ( ) ; } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( \"Error during micro-transaction rollback\" ) , e ) ; } finally { transaction . set ( null ) ; } } finally { stateLock . releaseReadLock ( ) ; } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that completes the cluster rename operation . <strong > IT WILL NOT RENAME A CLUSTER IT JUST CHANGES THE NAME IN THE INTERNAL MAPPING< / strong > [CODESPLIT] public final void renameCluster ( final String oldName , final String newName ) { try { clusterMap . put ( newName . toLowerCase ( configuration . getLocaleInstance ( ) ) , clusterMap . remove ( oldName . toLowerCase ( configuration . getLocaleInstance ( ) ) ) ) ; } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the command request and return the result back . [CODESPLIT] @ Override public final Object command ( final OCommandRequestText iCommand ) { try { while ( true ) { try { final OCommandExecutor executor = OCommandManager . instance ( ) . getExecutor ( iCommand ) ; // COPY THE CONTEXT FROM THE REQUEST executor . setContext ( iCommand . getContext ( ) ) ; executor . setProgressListener ( iCommand . getProgressListener ( ) ) ; executor . parse ( iCommand ) ; return executeCommand ( iCommand , executor ) ; } catch ( final ORetryQueryException ignore ) { if ( iCommand instanceof OQueryAbstract ) { final OQueryAbstract query = ( OQueryAbstract ) iCommand ; query . reset ( ) ; } } } } catch ( final RuntimeException ee ) { throw logAndPrepareForRethrow ( ee ) ; } catch ( final Error ee ) { throw logAndPrepareForRethrow ( ee , false ) ; } catch ( final Throwable t ) { throw logAndPrepareForRethrow ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the cluster internally . [CODESPLIT] private int registerCluster ( final OCluster cluster ) { final int id ; if ( cluster != null ) { // CHECK FOR DUPLICATION OF NAMES if ( clusterMap . containsKey ( cluster . getName ( ) . toLowerCase ( configuration . getLocaleInstance ( ) ) ) ) { throw new OConfigurationException ( \"Cannot add cluster '\" + cluster . getName ( ) + \"' because it is already registered in database '\" + name + \"'\" ) ; } // CREATE AND ADD THE NEW REF SEGMENT clusterMap . put ( cluster . getName ( ) . toLowerCase ( configuration . getLocaleInstance ( ) ) , cluster ) ; id = cluster . getId ( ) ; } else { id = clusters . size ( ) ; } setCluster ( id , cluster ) ; return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method which is called before any data modification operation to check alarm conditions such as : <ol > <li > Low disk space< / li > <li > Exception during data flush in background threads< / li > <li > Broken files< / li > < / ol > If one of those conditions are satisfied data modification operation is aborted and storage is switched in read only mode . [CODESPLIT] private void checkLowDiskSpaceRequestsAndReadOnlyConditions ( ) { if ( transaction . get ( ) != null ) { return ; } if ( lowDiskSpace != null ) { if ( checkpointInProgress . compareAndSet ( false , true ) ) { try { if ( writeCache . checkLowDiskSpace ( ) ) { OLogManager . instance ( ) . error ( this , \"Not enough disk space, force sync will be called\" , null ) ; synch ( ) ; if ( writeCache . checkLowDiskSpace ( ) ) { throw new OLowDiskSpaceException ( \"Error occurred while executing a write operation to database '\" + name + \"' due to limited free space on the disk (\" + ( lowDiskSpace . freeSpace / ( 1024 * 1024 ) ) + \" MB). The database is now working in read-only mode.\" + \" Please close the database (or stop OrientDB), make room on your hard drive and then reopen the database. \" + \"The minimal required space is \" + ( lowDiskSpace . requiredSpace / ( 1024 * 1024 ) ) + \" MB. \" + \"Required space is now set to \" + configuration . getContextConfiguration ( ) . getValueAsInteger ( OGlobalConfiguration . DISK_CACHE_FREE_SPACE_LIMIT ) + \"MB (you can change it by setting parameter \" + OGlobalConfiguration . DISK_CACHE_FREE_SPACE_LIMIT . getKey ( ) + \") .\" ) ; } else { lowDiskSpace = null ; } } else { lowDiskSpace = null ; } } catch ( final IOException e ) { throw OException . wrapException ( new OStorageException ( \"Error during low disk space handling\" ) , e ) ; } finally { checkpointInProgress . set ( false ) ; } } } checkReadOnlyConditions ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a property value [CODESPLIT] public Object setProperty ( final String iName , final Object iValue ) { if ( iValue != null ) { return properties . put ( iName . toLowerCase ( Locale . ENGLISH ) , iValue ) ; } else { return properties . remove ( iName . toLowerCase ( Locale . ENGLISH ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the CREATE CLASS . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( className == null ) throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; final ODatabaseDocument database = getDatabase ( ) ; boolean alreadyExists = database . getMetadata ( ) . getSchema ( ) . existsClass ( className ) ; if ( ! alreadyExists || ! ifNotExists ) { if ( clusters != null ) database . getMetadata ( ) . getSchema ( ) . createClass ( className , clusters , superClasses . toArray ( new OClass [ 0 ] ) ) ; else database . getMetadata ( ) . getSchema ( ) . createClass ( className , clusterIds , superClasses . toArray ( new OClass [ 0 ] ) ) ; } return database . getMetadata ( ) . getSchema ( ) . getClasses ( ) . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Blueprints Extension ) Counts the total items found . This method is more efficient than executing the query and browse the returning Iterable . [CODESPLIT] @ Override public long count ( ) { if ( hasContainers . isEmpty ( ) ) { // NO CONDITIONS: USE THE FAST COUNT long counter = ( ( OrientVertex ) vertex ) . countEdges ( direction , labels ) ; if ( limit != Integer . MAX_VALUE && counter > limit ) return limit ; return counter ; } // ITERATE EDGES TO MATCH CONDITIONS return super . count ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the SYNC DATABASE . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { final ODatabaseDocumentInternal database = getDatabase ( ) ; database . checkSecurity ( ORule . ResourceGeneric . DATABASE , \"sync\" , ORole . PERMISSION_UPDATE ) ; final OStorage stg = database . getStorage ( ) ; if ( ! ( stg instanceof ODistributedStorage ) ) throw new ODistributedException ( \"SYNC DATABASE command cannot be executed against a non distributed server\" ) ; final ODistributedStorage dStg = ( ODistributedStorage ) stg ; final OHazelcastPlugin dManager = ( OHazelcastPlugin ) dStg . getDistributedManager ( ) ; if ( dManager == null || ! dManager . isEnabled ( ) ) throw new OCommandExecutionException ( \"OrientDB is not started in distributed mode\" ) ; final String databaseName = database . getName ( ) ; return dManager . installDatabase ( true , databaseName , parsedStatement . isForce ( ) , ! parsedStatement . isFull ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public OCommandExecutorSQLAbstract createCommand ( final String name ) throws OCommandExecutionException { final Class < ? extends OCommandExecutorSQLAbstract > clazz = COMMANDS . get ( name ) ; if ( clazz == null ) { throw new OCommandExecutionException ( \"Unknowned command name :\" + name ) ; } try { return clazz . newInstance ( ) ; } catch ( Exception e ) { throw OException . wrapException ( new OCommandExecutionException ( \"Error in creation of command \" + name + \"(). Probably there is not an empty constructor or the constructor generates errors\" ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < RET extends ORecord > RET load ( final ORID iRecordId , final String iFetchPlan , final boolean iIgnoreCache ) { return ( RET ) executeReadRecord ( ( ORecordId ) iRecordId , null , - 1 , iFetchPlan , iIgnoreCache , ! iIgnoreCache , false , OStorage . LOCKING_STRATEGY . DEFAULT , new SimpleRecordReader ( prefetchRecords ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the record checking the version . [CODESPLIT] public ODatabase < ORecord > delete ( final ORID iRecord , final int iVersion ) { ORecord record = load ( iRecord ) ; ORecordInternal . setVersion ( record , iVersion ) ; delete ( record ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override @ Deprecated public < REC extends ORecord > ORecordIteratorCluster < REC > browseCluster ( final String iClusterName , final Class < REC > iRecordClass , final long startClusterPosition , final long endClusterPosition , final boolean loadTombstones ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; checkIfActive ( ) ; final int clusterId = getClusterIdByName ( iClusterName ) ; return new ORecordIteratorCluster < REC > ( this , clusterId , startClusterPosition , endClusterPosition , OStorage . LOCKING_STRATEGY . DEFAULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public OCommandRequest command ( final OCommandRequest iCommand ) { checkSecurity ( ORule . ResourceGeneric . COMMAND , ORole . PERMISSION_READ ) ; checkIfActive ( ) ; final OCommandRequestInternal command = ( OCommandRequestInternal ) iCommand ; try { command . reset ( ) ; return command ; } catch ( Exception e ) { throw OException . wrapException ( new ODatabaseException ( \"Error on command execution\" ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < RET extends List < ? > > RET query ( final OQuery < ? > iCommand , final Object ... iArgs ) { checkIfActive ( ) ; iCommand . reset ( ) ; return ( RET ) iCommand . execute ( iArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public long countClusterElements ( int [ ] iClusterIds , boolean countTombstones ) { checkIfActive ( ) ; String name ; for ( int iClusterId : iClusterIds ) { name = getClusterNameById ( iClusterId ) ; checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , name ) ; } return getStorage ( ) . count ( iClusterIds , countTombstones ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public long countClusterElements ( final String iClusterName ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; checkIfActive ( ) ; final int clusterId = getClusterIdByName ( iClusterName ) ; if ( clusterId < 0 ) throw new IllegalArgumentException ( \"Cluster '\" + iClusterName + \"' was not found\" ) ; return getStorage ( ) . count ( clusterId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric resourceGeneric , final String resourceSpecific , final int iOperation ) { if ( user != null ) { try { user . allow ( resourceGeneric , resourceSpecific , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , \"User '%s' tried to access the reserved resource '%s.%s', operation '%s'\" , getUser ( ) , resourceGeneric , resourceSpecific , iOperation ) ; throw e ; } } return ( DB ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric iResourceGeneric , final int iOperation , final Object ... iResourcesSpecific ) { if ( user != null ) { try { if ( iResourcesSpecific . length != 0 ) { for ( Object target : iResourcesSpecific ) { if ( target != null ) { user . allow ( iResourceGeneric , target . toString ( ) , iOperation ) ; } else user . allow ( iResourceGeneric , null , iOperation ) ; } } else user . allow ( iResourceGeneric , null , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , \"[checkSecurity] User '%s' tried to access the reserved resource '%s', target(s) '%s', operation '%s'\" , getUser ( ) , iResourceGeneric , Arrays . toString ( iResourcesSpecific ) , iOperation ) ; throw e ; } } return ( DB ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabaseDocument > DB checkSecurity ( final ORule . ResourceGeneric iResourceGeneric , final int iOperation , final Object iResourceSpecific ) { checkOpenness ( ) ; if ( user != null ) { try { if ( iResourceSpecific != null ) user . allow ( iResourceGeneric , iResourceSpecific . toString ( ) , iOperation ) ; else user . allow ( iResourceGeneric , null , iOperation ) ; } catch ( OSecurityAccessException e ) { if ( OLogManager . instance ( ) . isDebugEnabled ( ) ) OLogManager . instance ( ) . debug ( this , \"[checkSecurity] User '%s' tried to access the reserved resource '%s', target '%s', operation '%s'\" , getUser ( ) , iResourceGeneric , iResourceSpecific , iOperation ) ; throw e ; } } return ( DB ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabase > DB setStatus ( final STATUS status ) { checkIfActive ( ) ; setStatusInternal ( status ) ; return ( DB ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setUser ( final OSecurityUser user ) { checkIfActive ( ) ; if ( user instanceof OUser ) { OMetadata metadata = getMetadata ( ) ; if ( metadata != null ) { final OSecurity security = metadata . getSecurity ( ) ; this . user = new OImmutableUser ( security . getVersion ( ) , ( OUser ) user ) ; } else this . user = new OImmutableUser ( - 1 , ( OUser ) user ) ; } else this . user = ( OImmutableUser ) user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabase < ? > > DB registerHook ( final ORecordHook iHookImpl , final ORecordHook . HOOK_POSITION iPosition ) { checkOpenness ( ) ; checkIfActive ( ) ; final Map < ORecordHook , ORecordHook . HOOK_POSITION > tmp = new LinkedHashMap < ORecordHook , ORecordHook . HOOK_POSITION > ( hooks ) ; tmp . put ( iHookImpl , iPosition ) ; hooks . clear ( ) ; for ( ORecordHook . HOOK_POSITION p : ORecordHook . HOOK_POSITION . values ( ) ) { for ( Map . Entry < ORecordHook , ORecordHook . HOOK_POSITION > e : tmp . entrySet ( ) ) { if ( e . getValue ( ) == p ) hooks . put ( e . getKey ( ) , e . getValue ( ) ) ; } } compileHooks ( ) ; return ( DB ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabase < ? > > DB registerHook ( final ORecordHook iHookImpl ) { return ( DB ) registerHook ( iHookImpl , ORecordHook . HOOK_POSITION . REGULAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabase < ? > > DB unregisterHook ( final ORecordHook iHookImpl ) { checkIfActive ( ) ; if ( iHookImpl != null ) { iHookImpl . onUnregister ( ) ; hooks . remove ( iHookImpl ) ; compileHooks ( ) ; } return ( DB ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback the registered hooks if any . [CODESPLIT] public ORecordHook . RESULT callbackHooks ( final ORecordHook . TYPE type , final OIdentifiable id ) { if ( id == null || hooks . isEmpty ( ) || id . getIdentity ( ) . getClusterId ( ) == 0 ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; final ORecordHook . SCOPE scope = ORecordHook . SCOPE . typeToScope ( type ) ; final int scopeOrdinal = scope . ordinal ( ) ; final ORID identity = id . getIdentity ( ) . copy ( ) ; if ( ! pushInHook ( identity ) ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; try { final ORecord rec = id . getRecord ( ) ; if ( rec == null ) return ORecordHook . RESULT . RECORD_NOT_CHANGED ; final OScenarioThreadLocal . RUN_MODE runMode = OScenarioThreadLocal . INSTANCE . getRunMode ( ) ; boolean recordChanged = false ; for ( ORecordHook hook : hooksByScope [ scopeOrdinal ] ) { switch ( runMode ) { case DEFAULT : // NON_DISTRIBUTED OR PROXIED DB if ( getStorage ( ) . isDistributed ( ) && hook . getDistributedExecutionMode ( ) == ORecordHook . DISTRIBUTED_EXECUTION_MODE . TARGET_NODE ) // SKIP continue ; break ; // TARGET NODE case RUNNING_DISTRIBUTED : if ( hook . getDistributedExecutionMode ( ) == ORecordHook . DISTRIBUTED_EXECUTION_MODE . SOURCE_NODE ) continue ; } final ORecordHook . RESULT res = hook . onTrigger ( type , rec ) ; if ( res == ORecordHook . RESULT . RECORD_CHANGED ) recordChanged = true ; else if ( res == ORecordHook . RESULT . SKIP_IO ) // SKIP IO OPERATION return res ; else if ( res == ORecordHook . RESULT . SKIP ) // SKIP NEXT HOOKS AND RETURN IT return res ; else if ( res == ORecordHook . RESULT . RECORD_REPLACED ) return res ; } return recordChanged ? ORecordHook . RESULT . RECORD_CHANGED : ORecordHook . RESULT . RECORD_NOT_CHANGED ; } finally { popInHook ( identity ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < DB extends ODatabaseDocument > DB setValidationEnabled ( final boolean iEnabled ) { set ( ATTRIBUTES . VALIDATION , iEnabled ) ; return ( DB ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the record without checking the version . [CODESPLIT] public ODatabaseDocument delete ( final ORID iRecord ) { checkOpenness ( ) ; checkIfActive ( ) ; final ORecord rec = load ( iRecord ) ; if ( rec != null ) delete ( rec ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public < RET extends ORecord > RET load ( final ORecord iRecord , final String iFetchPlan , final boolean iIgnoreCache ) { return ( RET ) executeReadRecord ( ( ORecordId ) iRecord . getIdentity ( ) , iRecord , - 1 , iFetchPlan , iIgnoreCache , ! iIgnoreCache , false , OStorage . LOCKING_STRATEGY . NONE , new SimpleRecordReader ( prefetchRecords ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is internal it can be subject to signature change or be removed do not use . [CODESPLIT] public boolean executeHideRecord ( OIdentifiable record , final OPERATION_MODE iMode ) { checkOpenness ( ) ; checkIfActive ( ) ; final ORecordId rid = ( ORecordId ) record . getIdentity ( ) ; if ( rid == null ) throw new ODatabaseException ( \"Cannot hide record because it has no identity. Probably was created from scratch or contains projections of fields rather than a full record\" ) ; if ( ! rid . isValid ( ) ) return false ; checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_DELETE , getClusterNameById ( rid . getClusterId ( ) ) ) ; getMetadata ( ) . makeThreadLocalSchemaSnapshot ( ) ; if ( record instanceof ODocument ) ODocumentInternal . checkClass ( ( ODocument ) record , this ) ; ORecordSerializationContext . pushContext ( ) ; try { final OStorageOperationResult < Boolean > operationResult ; operationResult = getStorage ( ) . hideRecord ( rid , iMode . ordinal ( ) , null ) ; // REMOVE THE RECORD FROM 1 AND 2 LEVEL CACHES if ( ! operationResult . isMoved ( ) ) getLocalCache ( ) . deleteRecord ( rid ) ; return operationResult . getResult ( ) ; } finally { ORecordSerializationContext . pullContext ( ) ; getMetadata ( ) . clearThreadLocalSchemaSnapshot ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void freeze ( final boolean throwException ) { checkOpenness ( ) ; if ( ! ( getStorage ( ) instanceof OFreezableStorageComponent ) ) { OLogManager . instance ( ) . error ( this , \"Only local paginated storage supports freeze. If you are using remote client please use OServerAdmin instead\" , null ) ; return ; } final long startTime = Orient . instance ( ) . getProfiler ( ) . startChrono ( ) ; final OFreezableStorageComponent storage = getFreezableStorage ( ) ; if ( storage != null ) { storage . freeze ( throwException ) ; } Orient . instance ( ) . getProfiler ( ) . stopChrono ( \"db.\" + getName ( ) + \".freeze\" , \"Time to freeze the database\" , startTime , \"db.*.freeze\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public ORecordIteratorClass < ODocument > browseClass ( final String iClassName , final boolean iPolymorphic ) { if ( getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( iClassName ) == null ) throw new IllegalArgumentException ( \"Class '\" + iClassName + \"' not found in current database\" ) ; checkSecurity ( ORule . ResourceGeneric . CLASS , ORole . PERMISSION_READ , iClassName ) ; return new ORecordIteratorClass < ODocument > ( this , iClassName , iPolymorphic , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public ORecordIteratorCluster < ODocument > browseCluster ( final String iClusterName ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; return new ORecordIteratorCluster < ODocument > ( this , getClusterIdByName ( iClusterName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override @ Deprecated public ORecordIteratorCluster < ODocument > browseCluster ( String iClusterName , long startClusterPosition , long endClusterPosition , boolean loadTombstones ) { checkSecurity ( ORule . ResourceGeneric . CLUSTER , ORole . PERMISSION_READ , iClusterName ) ; return new ORecordIteratorCluster < ODocument > ( this , getClusterIdByName ( iClusterName ) , startClusterPosition , endClusterPosition , OStorage . LOCKING_STRATEGY . DEFAULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves a document to the database . Behavior depends by the current running transaction if any . If no transaction is running then changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current transaction will continue to see the record as modified while others not . If a Pessimistic transaction is running then an exclusive lock is acquired against the record . Current transaction will continue to see the record as modified while others cannot access to it since it s locked . <p > If MVCC is enabled and the version of the document is different by the version stored in the database then a { @link OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @link ODocument#validate () } is called . [CODESPLIT] @ Override public < RET extends ORecord > RET save ( final ORecord iRecord ) { return ( RET ) save ( iRecord , null , OPERATION_MODE . SYNCHRONOUS , false , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves a document to the database . Behavior depends by the current running transaction if any . If no transaction is running then changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current transaction will continue to see the record as modified while others not . If a Pessimistic transaction is running then an exclusive lock is acquired against the record . Current transaction will continue to see the record as modified while others cannot access to it since it s locked . <p > If MVCC is enabled and the version of the document is different by the version stored in the database then a { @link OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @link ODocument#validate () } is called . [CODESPLIT] @ Override public < RET extends ORecord > RET save ( final ORecord iRecord , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { return save ( iRecord , null , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves a document specifying a cluster where to store the record . Behavior depends by the current running transaction if any . If no transaction is running then changes apply immediately . If an Optimistic transaction is running then the record will be changed at commit time . The current transaction will continue to see the record as modified while others not . If a Pessimistic transaction is running then an exclusive lock is acquired against the record . Current transaction will continue to see the record as modified while others cannot access to it since it s locked . <p > If MVCC is enabled and the version of the document is different by the version stored in the database then a { @link OConcurrentModificationException } exception is thrown . Before to save the document it must be valid following the constraints declared in the schema if any ( can work also in schema - less mode ) . To validate the document the { @link ODocument#validate () } is called . [CODESPLIT] @ Override public < RET extends ORecord > RET save ( ORecord iRecord , String iClusterName , final OPERATION_MODE iMode , boolean iForceCreate , final ORecordCallback < ? extends Number > iRecordCreatedCallback , ORecordCallback < Integer > iRecordUpdatedCallback ) { checkOpenness ( ) ; if ( iRecord instanceof OVertex ) { iRecord = iRecord . getRecord ( ) ; } if ( iRecord instanceof OEdge ) { if ( ( ( OEdge ) iRecord ) . isLightweight ( ) ) { iRecord = ( ( OEdge ) iRecord ) . getFrom ( ) ; } else { iRecord = iRecord . getRecord ( ) ; } } ODirtyManager dirtyManager = ORecordInternal . getDirtyManager ( iRecord ) ; if ( iRecord instanceof OElement && dirtyManager != null && dirtyManager . getReferences ( ) != null && ! dirtyManager . getReferences ( ) . isEmpty ( ) ) { if ( ( ( ( OElement ) iRecord ) . isVertex ( ) || ( ( OElement ) iRecord ) . isEdge ( ) ) && ! getTransaction ( ) . isActive ( ) && inHook . isEmpty ( ) ) { return saveGraph ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; } } return saveInternal ( iRecord , iClusterName , iMode , iForceCreate , iRecordCreatedCallback , iRecordUpdatedCallback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of the records of the class iClassName . [CODESPLIT] public long countView ( final String viewName ) { final OView cls = getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getView ( viewName ) ; if ( cls == null ) throw new IllegalArgumentException ( \"View '\" + cls + \"' not found in database\" ) ; return countClass ( cls , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of the records of the class iClassName considering also sub classes if polymorphic is true . [CODESPLIT] public long countClass ( final String iClassName , final boolean iPolymorphic ) { final OClass cls = getMetadata ( ) . getImmutableSchemaSnapshot ( ) . getClass ( iClassName ) ; if ( cls == null ) throw new IllegalArgumentException ( \"Class '\" + cls + \"' not found in database\" ) ; return countClass ( cls , iPolymorphic ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Activates current database instance on current thread . [CODESPLIT] @ Override public ODatabaseDocumentAbstract activateOnCurrentThread ( ) { final ODatabaseRecordThreadLocal tl = ODatabaseRecordThreadLocal . instance ( ) ; if ( tl != null ) tl . set ( this ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a stateful implementations a new instance will be created for each storage . [CODESPLIT] public void register ( final OEncryption iEncryption ) { try { final String name = iEncryption . name ( ) ; if ( instances . containsKey ( name ) ) throw new IllegalArgumentException ( \"Encryption with name '\" + name + \"' was already registered\" ) ; if ( classes . containsKey ( name ) ) throw new IllegalArgumentException ( \"Encryption with name '\" + name + \"' was already registered\" ) ; instances . put ( name , iEncryption ) ; } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , \"Cannot register storage encryption algorithm '%s'\" , e , iEncryption ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public byte [ ] getBytes ( long pos , int length ) throws SQLException { if ( pos < 1 ) throw new SQLException ( \"The position of the first byte in the BLOB value to be \" + \"extracted cannot be less than 1\" ) ; if ( length < 0 ) throw new SQLException ( \"The number of the consecutive bytes in the BLOB value to \" + \"be extracted cannot be a negative number\" ) ; int relativeIndex = this . getRelativeIndex ( pos ) ; ByteBuffer buffer = ByteBuffer . allocate ( length ) ; int j ; for ( j = 0 ; j < length ; j ++ ) { if ( relativeIndex == currentChunk . length ) { // go to the next chunk, if any...\r currentChunkIndex ++ ; if ( currentChunkIndex < binaryDataChunks . size ( ) ) { // the next chunk exists so we update the relative index and\r // the current chunk reference\r relativeIndex = 0 ; currentChunk = binaryDataChunks . get ( currentChunkIndex ) ; } else // exit from the loop: there are no more bytes to be read\r break ; } buffer . put ( currentChunk [ relativeIndex ] ) ; relativeIndex ++ ; } return buffer . array ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the index within a binary chunk corresponding to the given absolute position within this BLOB [CODESPLIT] private int getRelativeIndex ( long pos ) { int currentSize = 0 ; currentChunkIndex = 0 ; // loop until we find the chuks holding the given position\r while ( pos >= ( currentSize += binaryDataChunks . get ( currentChunkIndex ) . length ) ) currentChunkIndex ++ ; currentChunk = binaryDataChunks . get ( currentChunkIndex ) ; currentSize -= currentChunk . length ; // the position referred to the target binary chunk\r int relativePosition = ( int ) ( pos - currentSize ) ; // the index of the first byte to be returned\r return relativePosition - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the next word . It returns the word parsed if any . [CODESPLIT] protected String parserOptionalWord ( final boolean iUpperCase ) { parserPreviousPos = parserCurrentPos ; parserNextWord ( iUpperCase ) ; if ( parserLastWord . length ( ) == 0 ) return null ; return parserLastWord . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the next word . If no word is found or the parsed word is not present in the word array received as parameter then a SyntaxError exception with the custom message received as parameter is thrown . It returns the word parsed if any . [CODESPLIT] protected String parserRequiredWord ( final boolean iUpperCase , final String iCustomMessage , String iSeparators ) { if ( iSeparators == null ) iSeparators = \" ()=><,\\r\\n\" ; parserNextWord ( iUpperCase , iSeparators ) ; if ( parserLastWord . length ( ) == 0 ) throwSyntaxErrorException ( iCustomMessage ) ; if ( parserLastWord . charAt ( 0 ) == ' ' && parserLastWord . charAt ( parserLastWord . length ( ) - 1 ) == ' ' ) { return parserLastWord . substring ( 1 , parserLastWord . length ( ) - 1 ) ; } return parserLastWord . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the next sequence of chars . [CODESPLIT] protected int parserNextChars ( final boolean iUpperCase , final boolean iMandatory , final String ... iCandidateWords ) { parserPreviousPos = parserCurrentPos ; parserSkipWhiteSpaces ( ) ; parserEscapeSequenceCount = 0 ; parserLastWord . setLength ( 0 ) ; final String [ ] processedWords = Arrays . copyOf ( iCandidateWords , iCandidateWords . length ) ; // PARSE THE CHARS final String text2Use = iUpperCase ? parserTextUpperCase : parserText ; final int max = text2Use . length ( ) ; parserCurrentPos = parserCurrentPos + parserTextUpperCase . length ( ) - parserText . length ( ) ; // PARSE TILL 1 CHAR AFTER THE END TO SIMULATE A SEPARATOR AS EOF for ( int i = 0 ; parserCurrentPos <= max ; ++ i ) { final char ch = parserCurrentPos < max ? text2Use . charAt ( parserCurrentPos ) : ' ' ; final boolean separator = ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ; if ( ! separator ) parserLastWord . append ( ch ) ; // CLEAR CANDIDATES int candidatesWordsCount = 0 ; int candidatesWordsPos = - 1 ; for ( int c = 0 ; c < processedWords . length ; ++ c ) { final String w = processedWords [ c ] ; if ( w != null ) { final int wordSize = w . length ( ) ; if ( ( separator && wordSize > i ) || ( ! separator && ( i > wordSize - 1 || w . charAt ( i ) != ch ) ) ) // DISCARD IT processedWords [ c ] = null ; else { candidatesWordsCount ++ ; if ( candidatesWordsCount == 1 ) // REMEMBER THE POSITION candidatesWordsPos = c ; } } } if ( candidatesWordsCount == 1 ) { // ONE RESULT, CHECKING IF FOUND final String w = processedWords [ candidatesWordsPos ] ; if ( w . length ( ) == i + ( separator ? 0 : 1 ) && ! Character . isLetter ( ch ) ) // FOUND! return candidatesWordsPos ; } if ( candidatesWordsCount == 0 || separator ) break ; parserCurrentPos ++ ; } if ( iMandatory ) throwSyntaxErrorException ( \"Found unexpected keyword '\" + parserLastWord + \"' while it was expected '\" + Arrays . toString ( iCandidateWords ) + \"'\" ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses optional keywords between the iWords . If a keyword is found but doesn t match with iWords then a SyntaxError is raised . [CODESPLIT] protected boolean parserOptionalKeyword ( final String ... iWords ) { parserNextWord ( true , \" \\r\\n,\" ) ; if ( parserLastWord . length ( ) == 0 ) return false ; // FOUND: CHECK IF IT'S IN RANGE boolean found = iWords . length == 0 ; for ( String w : iWords ) { if ( parserLastWord . toString ( ) . equals ( w ) ) { found = true ; break ; } } if ( ! found ) throwSyntaxErrorException ( \"Found unexpected keyword '\" + parserLastWord + \"' while it was expected '\" + Arrays . toString ( iWords ) + \"'\" ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for a separator [CODESPLIT] private boolean parserCheckSeparator ( final char c , final String iSeparatorChars ) { for ( int sepIndex = 0 ; sepIndex < iSeparatorChars . length ( ) ; ++ sepIndex ) { if ( iSeparatorChars . charAt ( sepIndex ) == c ) { parserLastSeparator = c ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This method returns the path from the source to the selected target and NULL if no path exists [CODESPLIT] public LinkedList < OrientVertex > getPath ( ) { final LinkedList < OrientVertex > path = new LinkedList < OrientVertex > ( ) ; OrientVertex step = paramDestinationVertex ; // Check if a path exists if ( predecessors . get ( step . getIdentity ( ) ) == null ) return null ; path . add ( step ) ; while ( predecessors . get ( step . getIdentity ( ) ) != null ) { step = predecessors . get ( step . getIdentity ( ) ) ; path . add ( step ) ; } // Put it into the correct order Collections . reverse ( path ) ; return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the DROP CLASS . [CODESPLIT] public Object execute ( final Map < Object , Object > iArgs ) { if ( className == null ) { throw new OCommandExecutionException ( \"Cannot execute the command because it has not been parsed yet\" ) ; } final ODatabaseDocument database = getDatabase ( ) ; if ( ifExists && ! database . getMetadata ( ) . getSchema ( ) . existsClass ( className ) ) { return true ; } final OClass cls = database . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( cls == null ) { return null ; } final long records = cls . count ( true ) ; if ( records > 0 && ! unsafe ) { // NOT EMPTY, CHECK IF CLASS IS OF VERTEX OR EDGES\r if ( cls . isSubClassOf ( \"V\" ) ) { // FOUND VERTEX CLASS\r throw new OCommandExecutionException ( \"'DROP CLASS' command cannot drop class '\" + className + \"' because it contains Vertices. Use 'DELETE VERTEX' command first to avoid broken edges in a database, or apply the 'UNSAFE' keyword to force it\" ) ; } else if ( cls . isSubClassOf ( \"E\" ) ) { // FOUND EDGE CLASS\r throw new OCommandExecutionException ( \"'DROP CLASS' command cannot drop class '\" + className + \"' because it contains Edges. Use 'DELETE EDGE' command first to avoid broken vertices in a database, or apply the 'UNSAFE' keyword to force it\" ) ; } } database . getMetadata ( ) . getSchema ( ) . dropClass ( className ) ; if ( records > 0 && unsafe ) { // NOT EMPTY, CHECK IF CLASS IS OF VERTEX OR EDGES\r if ( cls . isSubClassOf ( \"V\" ) ) { // FOUND VERTICES\r if ( unsafe ) OLogManager . instance ( ) . warn ( this , \"Dropped class '%s' containing %d vertices using UNSAFE mode. Database could contain broken edges\" , className , records ) ; } else if ( cls . isSubClassOf ( \"E\" ) ) { // FOUND EDGES\r OLogManager . instance ( ) . warn ( this , \"Dropped class '%s' containing %d edges using UNSAFE mode. Database could contain broken vertices\" , className , records ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove both backup and primary configuration files on delete [CODESPLIT] private void clearConfigurationFiles ( ) throws IOException { final Path file = storagePath . resolve ( NAME ) ; Files . deleteIfExists ( file ) ; final Path backupFile = storagePath . resolve ( BACKUP_NAME ) ; Files . deleteIfExists ( backupFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the item requested . [CODESPLIT] private void convert ( final int iIndex ) { if ( converted || ! convertToRecord ) return ; Object o = super . get ( iIndex ) ; if ( o == null ) { final ODatabaseDocument database = getDatabase ( ) . getUnderlying ( ) ; o = recordList . get ( iIndex ) ; ODocument doc ; if ( o instanceof ORID ) { doc = database . load ( ( ORID ) o , fetchPlan ) ; } else { doc = ( ODocument ) o ; } if ( o == null ) { OLogManager . instance ( ) . warn ( this , \"Record \" + ( ( OObjectProxyMethodHandler ) sourceRecord . getHandler ( ) ) . getDoc ( ) . getIdentity ( ) + \" references a deleted instance\" ) ; return ; } super . set ( iIndex , ( TYPE ) OObjectEntityEnhancer . getInstance ( ) . getProxiedInstance ( doc . getClassName ( ) , getDatabase ( ) . getEntityManager ( ) , doc , sourceRecord ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Browse the stream but just return the begin of the byte array . This is used to lazy load the information only when needed . [CODESPLIT] public int getAsByteArrayOffset ( ) { if ( position >= length ) return - 1 ; final int begin = position ; final int size = OBinaryProtocol . bytes2int ( buffer , position ) ; position += OBinaryProtocol . SIZE_INT + size ; return begin ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the token extract id the access token exists or returning an empty extract if there is no one on the context it may occasionally causes Unauthorized response since the token extract is empty . [CODESPLIT] protected String extract ( String tokenType ) { OAuth2AccessToken accessToken = getToken ( ) ; return String . format ( \"%s %s\" , tokenType , accessToken . getValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the access token within the request or try to acquire a new one by delegating it to { [CODESPLIT] public OAuth2AccessToken getToken ( ) { OAuth2AccessToken accessToken = oAuth2ClientContext . getAccessToken ( ) ; if ( accessToken == null || accessToken . isExpired ( ) ) { try { accessToken = acquireAccessToken ( ) ; } catch ( UserRedirectRequiredException e ) { oAuth2ClientContext . setAccessToken ( null ) ; String stateKey = e . getStateKey ( ) ; if ( stateKey != null ) { Object stateToPreserve = e . getStateToPreserve ( ) ; if ( stateToPreserve == null ) { stateToPreserve = \"NONE\" ; } oAuth2ClientContext . setPreservedState ( stateKey , stateToPreserve ) ; } throw e ; } } return accessToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to acquire the token using a access token provider . [CODESPLIT] protected OAuth2AccessToken acquireAccessToken ( ) throws UserRedirectRequiredException { AccessTokenRequest tokenRequest = oAuth2ClientContext . getAccessTokenRequest ( ) ; if ( tokenRequest == null ) { throw new AccessTokenRequiredException ( \"Cannot find valid context on request for resource '\" + resource . getId ( ) + \"'.\" , resource ) ; } String stateKey = tokenRequest . getStateKey ( ) ; if ( stateKey != null ) { tokenRequest . setPreservedState ( oAuth2ClientContext . removePreservedState ( stateKey ) ) ; } OAuth2AccessToken existingToken = oAuth2ClientContext . getAccessToken ( ) ; if ( existingToken != null ) { oAuth2ClientContext . setAccessToken ( existingToken ) ; } OAuth2AccessToken obtainableAccessToken ; obtainableAccessToken = accessTokenProvider . obtainAccessToken ( resource , tokenRequest ) ; if ( obtainableAccessToken == null || obtainableAccessToken . getValue ( ) == null ) { throw new IllegalStateException ( \" Access token provider returned a null token, which is illegal according to the contract.\" ) ; } oAuth2ClientContext . setAccessToken ( obtainableAccessToken ) ; return obtainableAccessToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to copy an access token from the security context into the oauth2 context . [CODESPLIT] public boolean copyToken ( ) { if ( context . getAccessToken ( ) == null ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication != null ) { Object details = authentication . getDetails ( ) ; if ( details instanceof OAuth2AuthenticationDetails ) { OAuth2AuthenticationDetails holder = ( OAuth2AuthenticationDetails ) details ; String token = holder . getTokenValue ( ) ; DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken ( token ) ; String tokenType = holder . getTokenType ( ) ; if ( tokenType != null ) { accessToken . setTokenType ( tokenType ) ; } context . setAccessToken ( accessToken ) ; return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向spring添加bean的定义 [CODESPLIT] public void put ( String name , Class < ? > clazz ) { BeanDefinition definition = new RootBeanDefinition ( clazz ) ; beanFactory . registerBeanDefinition ( name , definition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "由于任务节点需要解析form、assignee属性，这里覆盖抽象类方法实现 [CODESPLIT] protected void parseNode ( NodeModel node , Element element ) { TaskModel task = ( TaskModel ) node ; task . setForm ( element . getAttribute ( ATTR_FORM ) ) ; task . setAssignee ( element . getAttribute ( ATTR_ASSIGNEE ) ) ; task . setExpireTime ( element . getAttribute ( ATTR_EXPIRETIME ) ) ; task . setAutoExecute ( element . getAttribute ( ATTR_AUTOEXECUTE ) ) ; task . setCallback ( element . getAttribute ( ATTR_CALLBACK ) ) ; task . setReminderTime ( element . getAttribute ( ATTR_REMINDERTIME ) ) ; task . setReminderRepeat ( element . getAttribute ( ATTR_REMINDERREPEAT ) ) ; task . setPerformType ( element . getAttribute ( ATTR_PERFORMTYPE ) ) ; task . setTaskType ( element . getAttribute ( ATTR_TASKTYPE ) ) ; task . setAssignmentHandler ( element . getAttribute ( ATTR_ASSIGNEE_HANDLER ) ) ; NodeList fieldList = element . getElementsByTagName ( ATTR_FIELD ) ; List < FieldModel > fields = new ArrayList < FieldModel > ( ) ; for ( int i = 0 ; i < fieldList . getLength ( ) ; i ++ ) { Element item = ( Element ) fieldList . item ( i ) ; FieldModel fieldModel = new FieldModel ( ) ; fieldModel . setName ( item . getAttribute ( ATTR_NAME ) ) ; fieldModel . setDisplayName ( item . getAttribute ( ATTR_DISPLAYNAME ) ) ; fieldModel . setType ( item . getAttribute ( ATTR_TYPE ) ) ; NodeList attrList = item . getElementsByTagName ( ATTR_ATTR ) ; for ( int j = 0 ; j < attrList . getLength ( ) ; j ++ ) { Node attr = attrList . item ( j ) ; fieldModel . addAttr ( ( ( Element ) attr ) . getAttribute ( ATTR_NAME ) , ( ( Element ) attr ) . getAttribute ( ATTR_VALUE ) ) ; } fields . add ( fieldModel ) ; } task . setFields ( fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析日期时间对象 [CODESPLIT] public static String parseTime ( Object date ) { if ( date == null ) return null ; if ( date instanceof Date ) { return new DateTime ( ( Date ) date ) . toString ( DATE_FORMAT_DEFAULT ) ; } else if ( date instanceof String ) { return String . valueOf ( date ) ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对时限数据进行处理 1、运行时设置的date型数据直接返回 2、模型设置的需要特殊转换成date类型 3、运行时设置的转换为date型 [CODESPLIT] public static Date processTime ( Map < String , Object > args , String parameter ) { if ( StringHelper . isEmpty ( parameter ) ) return null ; Object data = args . get ( parameter ) ; if ( data == null ) data = parameter ; Date result = null ; if ( data instanceof Date ) { return ( Date ) data ; } else if ( data instanceof Long ) { return new Date ( ( Long ) data ) ; } else if ( data instanceof String ) { //TODO 1.4-dev ignore } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从jfinal的threadlocal中获取数据库连接 [CODESPLIT] protected Connection getConnection ( ) throws SQLException { Config config = JfinalHelper . getConfig ( ) ; Connection conn = config . getThreadLocalConnection ( ) ; if ( conn == null ) { conn = config . getConnection ( ) ; conn . setAutoCommit ( true ) ; } return conn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "完成指定任务 [CODESPLIT] public Task complete ( String taskId , String operator ) { return complete ( taskId , operator , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "完成指定任务 该方法仅仅结束活动任务，并不能驱动流程继续执行 [CODESPLIT] public Task complete ( String taskId , String operator , Map < String , Object > args ) { Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , \"指定的任务[id=\" + taskId    ]不存在\")     task . setVariable ( JsonHelper . toJson ( args ) ) ; if ( ! isAllowed ( task , operator ) ) { throw new SnakerException ( \"当前参与者[\" + operato    \"]不允许执行 务 taskId=\" + taskId + \"]\");       } HistoryTask history = new HistoryTask ( task ) ; history . setFinishTime ( DateHelper . getTime ( ) ) ; history . setTaskState ( STATE_FINISH ) ; history . setOperator ( operator ) ; if ( history . getActorIds ( ) == null ) { List < TaskActor > actors = access ( ) . getTaskActorsByTaskId ( task . getId ( ) ) ; String [ ] actorIds = new String [ actors . size ( ) ] ; for ( int i = 0 ; i < actors . size ( ) ; i ++ ) { actorIds [ i ] = actors . get ( i ) . getActorId ( ) ; } history . setActorIds ( actorIds ) ; } access ( ) . saveHistory ( history ) ; access ( ) . deleteTask ( task ) ; Completion completion = getCompletion ( ) ; if ( completion != null ) { completion . complete ( history ) ; } return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "任务历史记录方法 [CODESPLIT] public HistoryTask history ( Execution execution , CustomModel model ) { HistoryTask historyTask = new HistoryTask ( ) ; historyTask . setId ( StringHelper . getPrimaryKey ( ) ) ; historyTask . setOrderId ( execution . getOrder ( ) . getId ( ) ) ; String currentTime = DateHelper . getTime ( ) ; historyTask . setCreateTime ( currentTime ) ; historyTask . setFinishTime ( currentTime ) ; historyTask . setDisplayName ( model . getDisplayName ( ) ) ; historyTask . setTaskName ( model . getName ( ) ) ; historyTask . setTaskState ( STATE_FINISH ) ; historyTask . setTaskType ( TaskType . Record . ordinal ( ) ) ; historyTask . setParentTaskId ( execution . getTask ( ) == null ? START : execution . getTask ( ) . getId ( ) ) ; historyTask . setVariable ( JsonHelper . toJson ( execution . getArgs ( ) ) ) ; access ( ) . saveHistory ( historyTask ) ; return historyTask ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "提取指定任务，设置完成时间及操作人，状态不改变 [CODESPLIT] public Task take ( String taskId , String operator ) { Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , \"指定的任务[id=\" + taskId    ]不存在\")     if ( ! isAllowed ( task , operator ) ) { throw new SnakerException ( \"当前参与者[\" + operato    \"]不允许提取 务 taskId=\" + taskId + \"]\");       } task . setOperator ( operator ) ; task . setFinishTime ( DateHelper . getTime ( ) ) ; access ( ) . updateTask ( task ) ; return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "唤醒指定的历史任务 [CODESPLIT] public Task resume ( String taskId , String operator ) { HistoryTask histTask = access ( ) . getHistTask ( taskId ) ; AssertHelper . notNull ( histTask , \"指定的历史任务[id=\" + taskId + \"] 存 \");     boolean isAllowed = true ; if ( StringHelper . isNotEmpty ( histTask . getOperator ( ) ) ) { isAllowed = histTask . getOperator ( ) . equals ( operator ) ; } if ( isAllowed ) { Task task = histTask . undoTask ( ) ; task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , task . getOperator ( ) ) ; return task ; } else { throw new SnakerException ( \"当前参与者[\" + operato    \"]不允许唤醒 史 务[taskId=\" + taskId + \"]\");       } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向指定任务添加参与者 该方法根据performType类型判断是否需要创建新的活动任务 [CODESPLIT] public void addTaskActor ( String taskId , Integer performType , String ... actors ) { Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , \"指定的任务[id=\" + taskId    ]不存在\")     if ( ! task . isMajor ( ) ) return ; if ( performType == null ) performType = task . getPerformType ( ) ; if ( performType == null ) performType = 0 ; switch ( performType ) { case 0 : assignTask ( task . getId ( ) , actors ) ; Map < String , Object > data = task . getVariableMap ( ) ; String oldActor = ( String ) data . get ( Task . KEY_ACTOR ) ; data . put ( Task . KEY_ACTOR , oldActor + \",\" + StringHelper . getStringByArray ( actors ) ) ; task . setVariable ( JsonHelper . toJson ( data ) ) ; access ( ) . updateTask ( task ) ; break ; case 1 : try { for ( String actor : actors ) { Task newTask = ( Task ) task . clone ( ) ; newTask . setId ( StringHelper . getPrimaryKey ( ) ) ; newTask . setCreateTime ( DateHelper . getTime ( ) ) ; newTask . setOperator ( actor ) ; Map < String , Object > taskData = task . getVariableMap ( ) ; taskData . put ( Task . KEY_ACTOR , actor ) ; task . setVariable ( JsonHelper . toJson ( taskData ) ) ; access ( ) . saveTask ( newTask ) ; assignTask ( newTask . getId ( ) , actor ) ; } } catch ( CloneNotSupportedException ex ) { throw new SnakerException ( \"任务对象不支持复制\", ex.getCause());         } break ; default : break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向指定任务移除参与者 [CODESPLIT] public void removeTaskActor ( String taskId , String ... actors ) { Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , \"指定的任务[id=\" + taskId    ]不存在\")     if ( actors == null || actors . length == 0 ) return ; if ( task . isMajor ( ) ) { access ( ) . removeTaskActor ( task . getId ( ) , actors ) ; Map < String , Object > taskData = task . getVariableMap ( ) ; String actorStr = ( String ) taskData . get ( Task . KEY_ACTOR ) ; if ( StringHelper . isNotEmpty ( actorStr ) ) { String [ ] actorArray = actorStr . split ( \",\" ) ; StringBuilder newActor = new StringBuilder ( actorStr . length ( ) ) ; boolean isMatch ; for ( String actor : actorArray ) { isMatch = false ; if ( StringHelper . isEmpty ( actor ) ) continue ; for ( String removeActor : actors ) { if ( actor . equals ( removeActor ) ) { isMatch = true ; break ; } } if ( isMatch ) continue ; newActor . append ( actor ) . append ( \",\" ) ; } newActor . deleteCharAt ( newActor . length ( ) - 1 ) ; taskData . put ( Task . KEY_ACTOR , newActor . toString ( ) ) ; task . setVariable ( JsonHelper . toJson ( taskData ) ) ; access ( ) . updateTask ( task ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "撤回指定的任务 [CODESPLIT] public Task withdrawTask ( String taskId , String operator ) { HistoryTask hist = access ( ) . getHistTask ( taskId ) ; AssertHelper . notNull ( hist , \"指定的历史任务[id=\" + taskId + \"] 存 \");     List < Task > tasks ; if ( hist . isPerformAny ( ) ) { tasks = access ( ) . getNextActiveTasks ( hist . getId ( ) ) ; } else { tasks = access ( ) . getNextActiveTasks ( hist . getOrderId ( ) , hist . getTaskName ( ) , hist . getParentTaskId ( ) ) ; } if ( tasks == null || tasks . isEmpty ( ) ) { throw new SnakerException ( \"后续活动任务已完成或不存在，无法撤回.\");   } for ( Task task : tasks ) { access ( ) . deleteTask ( task ) ; } Task task = hist . undoTask ( ) ; task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , task . getOperator ( ) ) ; return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "驳回任务 [CODESPLIT] public Task rejectTask ( ProcessModel model , Task currentTask ) { String parentTaskId = currentTask . getParentTaskId ( ) ; if ( StringHelper . isEmpty ( parentTaskId ) || parentTaskId . equals ( START ) ) { throw new SnakerException ( \"上一步任务ID为空，无法驳回至上一步处理\");   } NodeModel current = model . getNode ( currentTask . getTaskName ( ) ) ; HistoryTask history = access ( ) . getHistTask ( parentTaskId ) ; NodeModel parent = model . getNode ( history . getTaskName ( ) ) ; if ( ! NodeModel . canRejected ( current , parent ) ) { throw new SnakerException ( \"无法驳回至上一步处理，请确认上一步骤并非fork、join、suprocess以及会签任务\");   } Task task = history . undoTask ( ) ; task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; task . setOperator ( history . getOperator ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , task . getOperator ( ) ) ; return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对指定的任务分配参与者。参与者可以为用户、部门、角色 [CODESPLIT] private void assignTask ( String taskId , String ... actorIds ) { if ( actorIds == null || actorIds . length == 0 ) return ; for ( String actorId : actorIds ) { //修复当actorId为null的bug if ( StringHelper . isEmpty ( actorId ) ) continue ; TaskActor taskActor = new TaskActor ( ) ; taskActor . setTaskId ( taskId ) ; taskActor . setActorId ( actorId ) ; access ( ) . saveTaskActor ( taskActor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据已有任务、任务类型、参与者创建新的任务 适用于转派，动态协办处理 [CODESPLIT] public List < Task > createNewTask ( String taskId , int taskType , String ... actors ) { Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task , \"指定的任务[id=\" + taskId    ]不存在\")     List < Task > tasks = new ArrayList < Task > ( ) ; try { Task newTask = ( Task ) task . clone ( ) ; newTask . setTaskType ( taskType ) ; newTask . setCreateTime ( DateHelper . getTime ( ) ) ; newTask . setParentTaskId ( taskId ) ; tasks . add ( saveTask ( newTask , actors ) ) ; } catch ( CloneNotSupportedException e ) { throw new SnakerException ( \"任务对象不支持复制\", e.getCause());         } return tasks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取任务模型 [CODESPLIT] public TaskModel getTaskModel ( String taskId ) { Task task = access ( ) . getTask ( taskId ) ; AssertHelper . notNull ( task ) ; Order order = access ( ) . getOrder ( task . getOrderId ( ) ) ; AssertHelper . notNull ( order ) ; Process process = ServiceContext . getEngine ( ) . process ( ) . getProcessById ( order . getProcessId ( ) ) ; ProcessModel model = process . getModel ( ) ; NodeModel nodeModel = model . getNode ( task . getTaskName ( ) ) ; AssertHelper . notNull ( nodeModel , \"任务id无法找到节点模型.\");   if ( nodeModel instanceof TaskModel ) { return ( TaskModel ) nodeModel ; } else { throw new IllegalArgumentException ( \"任务id找到的节点模型不匹配\");   } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "由DBAccess实现类创建task，并根据model类型决定是否分配参与者 [CODESPLIT] public List < Task > createTask ( TaskModel taskModel , Execution execution ) { List < Task > tasks = new ArrayList < Task > ( ) ; Map < String , Object > args = execution . getArgs ( ) ; if ( args == null ) args = new HashMap < String , Object > ( ) ; Date expireDate = DateHelper . processTime ( args , taskModel . getExpireTime ( ) ) ; Date remindDate = DateHelper . processTime ( args , taskModel . getReminderTime ( ) ) ; String form = ( String ) args . get ( taskModel . getForm ( ) ) ; String actionUrl = StringHelper . isEmpty ( form ) ? taskModel . getForm ( ) : form ; String [ ] actors = getTaskActors ( taskModel , execution ) ; args . put ( Task . KEY_ACTOR , StringHelper . getStringByArray ( actors ) ) ; Task task = createTaskBase ( taskModel , execution ) ; task . setActionUrl ( actionUrl ) ; task . setExpireDate ( expireDate ) ; task . setExpireTime ( DateHelper . parseTime ( expireDate ) ) ; task . setVariable ( JsonHelper . toJson ( args ) ) ; if ( taskModel . isPerformAny ( ) ) { //任务执行方式为参与者中任何一个执行即可驱动流程继续流转，该方法只产生一个task task = saveTask ( task , actors ) ; task . setRemindDate ( remindDate ) ; tasks . add ( task ) ; } else if ( taskModel . isPerformAll ( ) ) { //任务执行方式为参与者中每个都要执行完才可驱动流程继续流转，该方法根据参与者个数产生对应的task数量 for ( String actor : actors ) { Task singleTask ; try { singleTask = ( Task ) task . clone ( ) ; } catch ( CloneNotSupportedException e ) { singleTask = task ; } singleTask = saveTask ( singleTask , actor ) ; singleTask . setRemindDate ( remindDate ) ; tasks . add ( singleTask ) ; } } return tasks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据模型、执行对象、任务类型构建基本的task对象 [CODESPLIT] private Task createTaskBase ( TaskModel model , Execution execution ) { Task task = new Task ( ) ; task . setOrderId ( execution . getOrder ( ) . getId ( ) ) ; task . setTaskName ( model . getName ( ) ) ; task . setDisplayName ( model . getDisplayName ( ) ) ; task . setCreateTime ( DateHelper . getTime ( ) ) ; if ( model . isMajor ( ) ) { task . setTaskType ( TaskType . Major . ordinal ( ) ) ; } else { task . setTaskType ( TaskType . Aidant . ordinal ( ) ) ; } task . setParentTaskId ( execution . getTask ( ) == null ? START : execution . getTask ( ) . getId ( ) ) ; task . setModel ( model ) ; return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "由DBAccess实现类持久化task对象 [CODESPLIT] private Task saveTask ( Task task , String ... actors ) { task . setId ( StringHelper . getPrimaryKey ( ) ) ; task . setPerformType ( PerformType . ANY . ordinal ( ) ) ; access ( ) . saveTask ( task ) ; assignTask ( task . getId ( ) , actors ) ; task . setActorIds ( actors ) ; return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据Task模型的assignee、assignmentHandler属性以及运行时数据，确定参与者 [CODESPLIT] private String [ ] getTaskActors ( TaskModel model , Execution execution ) { Object assigneeObject = null ; AssignmentHandler handler = model . getAssignmentHandlerObject ( ) ; if ( StringHelper . isNotEmpty ( model . getAssignee ( ) ) ) { assigneeObject = execution . getArgs ( ) . get ( model . getAssignee ( ) ) ; } else if ( handler != null ) { if ( handler instanceof Assignment ) { assigneeObject = ( ( Assignment ) handler ) . assign ( model , execution ) ; } else { assigneeObject = handler . assign ( execution ) ; } } return getTaskActors ( assigneeObject == null ? model . getAssignee ( ) : assigneeObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据taskmodel指定的assignee属性，从args中取值 将取到的值处理为String [] 类型。 [CODESPLIT] private String [ ] getTaskActors ( Object actors ) { if ( actors == null ) return null ; String [ ] results ; if ( actors instanceof String ) { //如果值为字符串类型，则使用逗号,分隔 return ( ( String ) actors ) . split ( \",\" ) ; } else if ( actors instanceof List ) { //jackson会把stirng[]转成arraylist，此处增加arraylist的逻辑判断,by 红豆冰沙2014.11.21 List < ? > list = ( List ) actors ; results = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { results [ i ] = ( String ) list . get ( i ) ; } return results ; } else if ( actors instanceof Long ) { //如果为Long类型，则返回1个元素的String[] results = new String [ 1 ] ; results [ 0 ] = String . valueOf ( ( Long ) actors ) ; return results ; } else if ( actors instanceof Integer ) { //如果为Integer类型，则返回1个元素的String[] results = new String [ 1 ] ; results [ 0 ] = String . valueOf ( ( Integer ) actors ) ; return results ; } else if ( actors instanceof String [ ] ) { //如果为String[]类型，则直接返回 return ( String [ ] ) actors ; } else { //其它类型，抛出不支持的类型异常 throw new SnakerException ( \"任务参与者对象[\" + actors + \"] 型 支持.\"   + \"合法参数示例:Long,Integer,new String[]{},'10000,20000',List<String>\");   } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断当前操作人operator是否允许执行taskId指定的任务 [CODESPLIT] public boolean isAllowed ( Task task , String operator ) { if ( StringHelper . isNotEmpty ( operator ) ) { if ( SnakerEngine . ADMIN . equalsIgnoreCase ( operator ) || SnakerEngine . AUTO . equalsIgnoreCase ( operator ) ) { return true ; } if ( StringHelper . isNotEmpty ( task . getOperator ( ) ) ) { return operator . equals ( task . getOperator ( ) ) ; } } List < TaskActor > actors = access ( ) . getTaskActorsByTaskId ( task . getId ( ) ) ; if ( actors == null || actors . isEmpty ( ) ) return true ; return ! StringHelper . isEmpty ( operator ) && getStrategy ( ) . isAllowed ( operator , actors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据文件名称resource打开输入流，并返回 [CODESPLIT] public static InputStream openStream ( String resource ) { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; InputStream stream = classLoader . getResourceAsStream ( resource ) ; if ( stream == null ) { stream = StreamHelper . class . getClassLoader ( ) . getResourceAsStream ( resource ) ; } return stream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "input - > output字节流copy [CODESPLIT] public static long copy ( InputStream inputStream , OutputStream outputStream ) throws IOException { return copy ( inputStream , outputStream , DEFAULT_CHUNK_SIZE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "input - > output字节流copy [CODESPLIT] public static long copy ( InputStream inputStream , OutputStream outputStream , int bufferSize ) throws IOException { byte [ ] buffer = new byte [ bufferSize ] ; long count = 0 ; int n ; while ( - 1 != ( n = inputStream . read ( buffer ) ) ) { outputStream . write ( buffer , 0 , n ) ; count += n ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "在没有任何sqlSessionFactory注入的情况下，默认使用mybatis . cfg . xml配置初始化 [CODESPLIT] public static void initialize ( ) { InputStream in ; try { in = Resources . getResourceAsStream ( \"mybatis.cfg.xml\" ) ; sqlSessionFactory = new SqlSessionFactoryBuilder ( ) . build ( in , ConfigHelper . getProperties ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用DataSource初始化SqlSessionFactory [CODESPLIT] public static void initialize ( DataSource ds ) { TransactionFactory transactionFactory = new MybatisTransactionFactory ( ) ; Environment environment = new Environment ( \"snaker\" , transactionFactory , ds ) ; Configuration configuration = new Configuration ( environment ) ; configuration . getTypeAliasRegistry ( ) . registerAliases ( SCAN_PACKAGE , Object . class ) ; if ( log . isInfoEnabled ( ) ) { Map < String , Class < ? > > typeAliases = configuration . getTypeAliasRegistry ( ) . getTypeAliases ( ) ; for ( Entry < String , Class < ? > > entry : typeAliases . entrySet ( ) ) { log . info ( \"Scanned class:[name=\" + entry . getKey ( ) + \",class=\" + entry . getValue ( ) . getName ( ) + \"]\" ) ; } } try { for ( String resource : resources ) { InputStream in = Resources . getResourceAsStream ( resource ) ; XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder ( in , configuration , resource , configuration . getSqlFragments ( ) ) ; xmlMapperBuilder . parse ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { ErrorContext . instance ( ) . reset ( ) ; } sqlSessionFactory = new SqlSessionFactoryBuilder ( ) . build ( configuration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Postgresql分页通过limit实现 [CODESPLIT] public String getPageSql ( String sql , Page < ? > page ) { StringBuffer pageSql = new StringBuffer ( sql . length ( ) + 100 ) ; pageSql . append ( getPageBefore ( sql , page ) ) ; pageSql . append ( sql ) ; pageSql . append ( getPageAfter ( sql , page ) ) ; return pageSql . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "如果操作人id所属的组只要有一项存在于参与者集合中，则表示可访问 [CODESPLIT] public boolean isAllowed ( String operator , List < TaskActor > actors ) { List < String > assignees = ensureGroup ( operator ) ; if ( assignees == null ) assignees = new ArrayList < String > ( ) ; assignees . add ( operator ) ; boolean isAllowed = false ; for ( TaskActor actor : actors ) { for ( String assignee : assignees ) { if ( actor . getActorId ( ) . equals ( assignee ) ) { isAllowed = true ; break ; } } } return isAllowed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "实现NodeParser接口的parse函数 由子类产生各自的模型对象，设置常用的名称属性，并且解析子节点transition，构造TransitionModel模型对象 [CODESPLIT] public void parse ( Element element ) { model = newModel ( ) ; model . setName ( element . getAttribute ( ATTR_NAME ) ) ; model . setDisplayName ( element . getAttribute ( ATTR_DISPLAYNAME ) ) ; model . setLayout ( element . getAttribute ( ATTR_LAYOUT ) ) ; model . setPreInterceptors ( element . getAttribute ( ATTR_PREINTERCEPTORS ) ) ; model . setPostInterceptors ( element . getAttribute ( ATTR_POSTINTERCEPTORS ) ) ; List < Element > transitions = XmlHelper . elements ( element , NODE_TRANSITION ) ; for ( Element te : transitions ) { TransitionModel transition = new TransitionModel ( ) ; transition . setName ( te . getAttribute ( ATTR_NAME ) ) ; transition . setDisplayName ( te . getAttribute ( ATTR_DISPLAYNAME ) ) ; transition . setTo ( te . getAttribute ( ATTR_TO ) ) ; transition . setExpr ( te . getAttribute ( ATTR_EXPR ) ) ; transition . setG ( te . getAttribute ( ATTR_G ) ) ; transition . setOffset ( te . getAttribute ( ATTR_OFFSET ) ) ; transition . setSource ( model ) ; model . getOutputs ( ) . add ( transition ) ; } parseNode ( model , element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "在没有任何dataSource注入的情况下，默认使用dbcp数据源 [CODESPLIT] private static void initialize ( ) { String driver = ConfigHelper . getProperty ( \"jdbc.driver\" ) ; String url = ConfigHelper . getProperty ( \"jdbc.url\" ) ; String username = ConfigHelper . getProperty ( \"jdbc.username\" ) ; String password = ConfigHelper . getProperty ( \"jdbc.password\" ) ; int maxActive = ConfigHelper . getNumerProperty ( \"jdbc.max.active\" ) ; int maxIdle = ConfigHelper . getNumerProperty ( \"jdbc.max.idle\" ) ; AssertHelper . notNull ( driver ) ; AssertHelper . notNull ( url ) ; AssertHelper . notNull ( username ) ; AssertHelper . notNull ( password ) ; //初始化DBCP数据源 BasicDataSource ds = new BasicDataSource ( ) ; ds . setDriverClassName ( driver ) ; ds . setUrl ( url ) ; ds . setUsername ( username ) ; ds . setPassword ( password ) ; if ( maxActive != 0 ) { ds . setMaxActive ( maxActive ) ; } if ( maxIdle != 0 ) { ds . setMaxIdle ( maxIdle ) ; } dataSource = ds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回数据源dataSource [CODESPLIT] public static DataSource getDataSource ( ) { if ( dataSource == null ) { synchronized ( JdbcHelper . class ) { if ( dataSource == null ) { initialize ( ) ; } } } AssertHelper . notNull ( dataSource ) ; return dataSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回数据库连接对象 [CODESPLIT] public static Connection getConnection ( DataSource ds ) throws SQLException { //通过ThreadLocale中获取Connection，如果为空，则通过dataSource返回新的连接对象 Connection conn = ( Connection ) TransactionObjectHolder . get ( ) ; if ( conn != null ) return conn ; if ( ds != null ) return ds . getConnection ( ) ; return getDataSource ( ) . getConnection ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据返回的对象集合判断是否为单条记录，并返回 如果返回无记录，或者超过1条记录，则抛出异常 [CODESPLIT] public static < T > T requiredSingleResult ( Collection < T > results ) { int size = ( results != null ? results . size ( ) : 0 ) ; if ( size == 0 ) { return null ; } return results . iterator ( ) . next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据元数据ResultSetMetaData、列索引columIndex获取列名称 [CODESPLIT] public static String lookupColumnName ( ResultSetMetaData resultSetMetaData , int columnIndex ) throws SQLException { String name = resultSetMetaData . getColumnLabel ( columnIndex ) ; if ( name == null || name . length ( ) < 1 ) { name = resultSetMetaData . getColumnName ( columnIndex ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据ResultSet结果集、index列索引、字段类型requiredType获取指定类型的对象值 [CODESPLIT] public static Object getResultSetValue ( ResultSet rs , int index , Class < ? > requiredType ) throws SQLException { if ( requiredType == null ) { return getResultSetValue ( rs , index ) ; } Object value = null ; boolean wasNullCheck = false ; if ( String . class . equals ( requiredType ) ) { value = rs . getString ( index ) ; } else if ( boolean . class . equals ( requiredType ) || Boolean . class . equals ( requiredType ) ) { value = rs . getBoolean ( index ) ; wasNullCheck = true ; } else if ( byte . class . equals ( requiredType ) || Byte . class . equals ( requiredType ) ) { value = rs . getByte ( index ) ; wasNullCheck = true ; } else if ( short . class . equals ( requiredType ) || Short . class . equals ( requiredType ) ) { value = rs . getShort ( index ) ; wasNullCheck = true ; } else if ( int . class . equals ( requiredType ) || Integer . class . equals ( requiredType ) ) { value = rs . getInt ( index ) ; wasNullCheck = true ; } else if ( long . class . equals ( requiredType ) || Long . class . equals ( requiredType ) ) { value = rs . getLong ( index ) ; wasNullCheck = true ; } else if ( float . class . equals ( requiredType ) || Float . class . equals ( requiredType ) ) { value = rs . getFloat ( index ) ; wasNullCheck = true ; } else if ( double . class . equals ( requiredType ) || Double . class . equals ( requiredType ) || Number . class . equals ( requiredType ) ) { value = rs . getDouble ( index ) ; wasNullCheck = true ; } else if ( byte [ ] . class . equals ( requiredType ) ) { value = rs . getBytes ( index ) ; } else if ( java . sql . Date . class . equals ( requiredType ) ) { value = rs . getDate ( index ) ; } else if ( java . sql . Time . class . equals ( requiredType ) ) { value = rs . getTime ( index ) ; } else if ( java . sql . Timestamp . class . equals ( requiredType ) || java . util . Date . class . equals ( requiredType ) ) { value = rs . getTimestamp ( index ) ; } else if ( BigDecimal . class . equals ( requiredType ) ) { value = rs . getBigDecimal ( index ) ; } else if ( Blob . class . equals ( requiredType ) ) { value = rs . getBlob ( index ) ; } else if ( Clob . class . equals ( requiredType ) ) { value = rs . getClob ( index ) ; } else { value = getResultSetValue ( rs , index ) ; } if ( wasNullCheck && value != null && rs . wasNull ( ) ) { value = null ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对于特殊字段类型做特殊处理 [CODESPLIT] public static Object getResultSetValue ( ResultSet rs , int index ) throws SQLException { Object obj = rs . getObject ( index ) ; String className = null ; if ( obj != null ) { className = obj . getClass ( ) . getName ( ) ; } if ( obj instanceof Blob ) { obj = rs . getBytes ( index ) ; } else if ( obj instanceof Clob ) { obj = rs . getString ( index ) ; } else if ( className != null && ( \"oracle.sql.TIMESTAMP\" . equals ( className ) || \"oracle.sql.TIMESTAMPTZ\" . equals ( className ) ) ) { obj = rs . getTimestamp ( index ) ; } else if ( className != null && className . startsWith ( \"oracle.sql.DATE\" ) ) { String metaDataClassName = rs . getMetaData ( ) . getColumnClassName ( index ) ; if ( \"java.sql.Timestamp\" . equals ( metaDataClassName ) || \"oracle.sql.TIMESTAMP\" . equals ( metaDataClassName ) ) { obj = rs . getTimestamp ( index ) ; } else { obj = rs . getDate ( index ) ; } } else if ( obj != null && obj instanceof java . sql . Date ) { if ( \"java.sql.Timestamp\" . equals ( rs . getMetaData ( ) . getColumnClassName ( index ) ) ) { obj = rs . getTimestamp ( index ) ; } } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据连接对象获取数据库类型 [CODESPLIT] public static String getDatabaseType ( Connection conn ) throws Exception { DatabaseMetaData databaseMetaData = conn . getMetaData ( ) ; String databaseProductName = databaseMetaData . getDatabaseProductName ( ) ; return databaseTypeMappings . getProperty ( databaseProductName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据连接对象获取数据库方言 [CODESPLIT] public static Dialect getDialect ( Connection conn ) throws Exception { DatabaseMetaData databaseMetaData = conn . getMetaData ( ) ; String databaseProductName = databaseMetaData . getDatabaseProductName ( ) ; String dbType = databaseTypeMappings . getProperty ( databaseProductName ) ; if ( StringHelper . isEmpty ( dbType ) ) return null ; if ( dbType . equalsIgnoreCase ( \"mysql\" ) ) return new MySqlDialect ( ) ; else if ( dbType . equalsIgnoreCase ( \"oracle\" ) ) return new OracleDialect ( ) ; else if ( dbType . equalsIgnoreCase ( \"postgres\" ) ) return new PostgresqlDialect ( ) ; else if ( dbType . equalsIgnoreCase ( \"mssql\" ) ) return new SQLServerDialect ( ) ; else if ( dbType . equalsIgnoreCase ( \"db2\" ) ) return new Db2Dialect ( ) ; else if ( dbType . equalsIgnoreCase ( \"h2\" ) ) return new H2Dialect ( ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断是否已经执行过脚本 [ 暂时根据wf_process表是否有数据 ] [CODESPLIT] public static boolean isExec ( Connection conn ) { Statement stmt = null ; try { String sql = ConfigHelper . getProperty ( \"schema.test\" ) ; if ( StringHelper . isEmpty ( sql ) ) { sql = \"select * from wf_process\" ; } stmt = conn . createStatement ( ) ; stmt . execute ( sql ) ; return true ; } catch ( Exception e ) { return false ; } finally { try { JdbcHelper . close ( stmt ) ; } catch ( SQLException e ) { //ignore } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据传递的执行参数、模型的参数列表返回实际的参数对象数组 [CODESPLIT] private Object [ ] getArgs ( Map < String , Object > execArgs , String args ) { Object [ ] objects = null ; if ( StringHelper . isNotEmpty ( args ) ) { String [ ] argArray = args . split ( \",\" ) ; objects = new Object [ argArray . length ] ; for ( int i = 0 ; i < argArray . length ; i ++ ) { objects [ i ] = execArgs . get ( argArray [ i ] ) ; } } return objects ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据serviceContext上下文，查找processService、orderService、taskService服务 [CODESPLIT] public SnakerEngine configure ( Configuration config ) { this . configuration = config ; processService = ServiceContext . find ( IProcessService . class ) ; queryService = ServiceContext . find ( IQueryService . class ) ; orderService = ServiceContext . find ( IOrderService . class ) ; taskService = ServiceContext . find ( ITaskService . class ) ; managerService = ServiceContext . find ( IManagerService . class ) ; /*\n\t\t * 无spring环境，DBAccess的实现类通过服务上下文获取\n\t\t */ if ( ! this . configuration . isCMB ( ) ) { DBAccess access = ServiceContext . find ( DBAccess . class ) ; AssertHelper . notNull ( access ) ; TransactionInterceptor interceptor = ServiceContext . find ( TransactionInterceptor . class ) ; //如果初始化配置时提供了访问对象，就对DBAccess进行初始化 Object accessObject = this . configuration . getAccessDBObject ( ) ; if ( accessObject != null ) { if ( interceptor != null ) { interceptor . initialize ( accessObject ) ; } access . initialize ( accessObject ) ; } setDBAccess ( access ) ; access . runScript ( ) ; } CacheManager cacheManager = ServiceContext . find ( CacheManager . class ) ; if ( cacheManager == null ) { //默认使用内存缓存管理器 cacheManager = new MemoryCacheManager ( ) ; } List < CacheManagerAware > cacheServices = ServiceContext . findList ( CacheManagerAware . class ) ; for ( CacheManagerAware cacheService : cacheServices ) { cacheService . setCacheManager ( cacheManager ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "注入dbAccess [CODESPLIT] protected void setDBAccess ( DBAccess access ) { List < AccessService > services = ServiceContext . findList ( AccessService . class ) ; for ( AccessService service : services ) { service . setAccess ( access ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据流程定义ID，操作人ID启动流程实例 [CODESPLIT] public Order startInstanceById ( String id , String operator ) { return startInstanceById ( id , operator , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据流程定义ID，操作人ID，参数列表启动流程实例 [CODESPLIT] public Order startInstanceById ( String id , String operator , Map < String , Object > args ) { if ( args == null ) args = new HashMap < String , Object > ( ) ; Process process = process ( ) . getProcessById ( id ) ; process ( ) . check ( process , id ) ; return startProcess ( process , operator , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据流程名称、版本号启动流程实例 [CODESPLIT] public Order startInstanceByName ( String name , Integer version ) { return startInstanceByName ( name , version , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据流程名称、版本号、操作人、参数列表启动流程实例 [CODESPLIT] public Order startInstanceByName ( String name , Integer version , String operator , Map < String , Object > args ) { if ( args == null ) args = new HashMap < String , Object > ( ) ; Process process = process ( ) . getProcessByVersion ( name , version ) ; process ( ) . check ( process , name ) ; return startProcess ( process , operator , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据父执行对象启动子流程实例（用于启动子流程） [CODESPLIT] public Order startInstanceByExecution ( Execution execution ) { Process process = execution . getProcess ( ) ; StartModel start = process . getModel ( ) . getStart ( ) ; AssertHelper . notNull ( start , \"流程定义[id=\" + proce s getId()   + \"]没 有 开 节 \");   Execution current = execute ( process , execution . getOperator ( ) , execution . getArgs ( ) , execution . getParentOrder ( ) . getId ( ) , execution . getParentNodeName ( ) ) ; start . execute ( current ) ; return current . getOrder ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建流程实例，并返回执行对象 [CODESPLIT] private Execution execute ( Process process , String operator , Map < String , Object > args , String parentId , String parentNodeName ) { Order order = order ( ) . createOrder ( process , operator , args , parentId , parentNodeName ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"创建流程实例对象:\" + order);     } Execution current = new Execution ( this , process , order , args ) ; current . setOperator ( operator ) ; return current ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据任务主键ID，操作人ID执行任务 [CODESPLIT] public List < Task > executeTask ( String taskId , String operator ) { return executeTask ( taskId , operator , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据任务主键ID，操作人ID，参数列表执行任务 [CODESPLIT] public List < Task > executeTask ( String taskId , String operator , Map < String , Object > args ) { //完成任务，并且构造执行对象 Execution execution = execute ( taskId , operator , args ) ; if ( execution == null ) return Collections . emptyList ( ) ; ProcessModel model = execution . getProcess ( ) . getModel ( ) ; if ( model != null ) { NodeModel nodeModel = model . getNode ( execution . getTask ( ) . getTaskName ( ) ) ; //将执行对象交给该任务对应的节点模型执行 nodeModel . execute ( execution ) ; } return execution . getTasks ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据任务主键ID，操作人ID，参数列表执行任务，并且根据nodeName跳转到任意节点 1、nodeName为null时，则驳回至上一步处理 2、nodeName不为null时，则任意跳转，即动态创建转移 [CODESPLIT] public List < Task > executeAndJumpTask ( String taskId , String operator , Map < String , Object > args , String nodeName ) { Execution execution = execute ( taskId , operator , args ) ; if ( execution == null ) return Collections . emptyList ( ) ; ProcessModel model = execution . getProcess ( ) . getModel ( ) ; AssertHelper . notNull ( model , \"当前任务未找到流程定义模型\");   if ( StringHelper . isEmpty ( nodeName ) ) { Task newTask = task ( ) . rejectTask ( model , execution . getTask ( ) ) ; execution . addTask ( newTask ) ; } else { NodeModel nodeModel = model . getNode ( nodeName ) ; AssertHelper . notNull ( nodeModel , \"根据节点名称[\" + nodeName    ]无法找到节点模 \" ;   //动态创建转移对象，由转移对象执行execution实例 TransitionModel tm = new TransitionModel ( ) ; tm . setTarget ( nodeModel ) ; tm . setEnabled ( true ) ; tm . execute ( execution ) ; } return execution . getTasks ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据流程实例ID，操作人ID，参数列表按照节点模型model创建新的自由任务 [CODESPLIT] public List < Task > createFreeTask ( String orderId , String operator , Map < String , Object > args , TaskModel model ) { Order order = query ( ) . getOrder ( orderId ) ; AssertHelper . notNull ( order , \"指定的流程实例[id=\" + orderId + \" 已 成或不存在\")     order . setLastUpdator ( operator ) ; order . setLastUpdateTime ( DateHelper . getTime ( ) ) ; Process process = process ( ) . getProcessById ( order . getProcessId ( ) ) ; Execution execution = new Execution ( this , process , order , args ) ; execution . setOperator ( operator ) ; return task ( ) . createTask ( model , execution ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据任务主键ID，操作人ID，参数列表完成任务，并且构造执行对象 [CODESPLIT] private Execution execute ( String taskId , String operator , Map < String , Object > args ) { if ( args == null ) args = new HashMap < String , Object > ( ) ; Task task = task ( ) . complete ( taskId , operator , args ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"任务[taskId=\" + t s Id + \" 已 成\");   } Order order = query ( ) . getOrder ( task . getOrderId ( ) ) ; AssertHelper . notNull ( order , \"指定的流程实例[id=\" + task.getOrd r d()  +  \"]已完成或不存在 \" )     order . setLastUpdator ( operator ) ; order . setLastUpdateTime ( DateHelper . getTime ( ) ) ; order ( ) . updateOrder ( order ) ; //协办任务完成不产生执行对象 if ( ! task . isMajor ( ) ) { return null ; } Map < String , Object > orderMaps = order . getVariableMap ( ) ; if ( orderMaps != null ) { for ( Map . Entry < String , Object > entry : orderMaps . entrySet ( ) ) { if ( args . containsKey ( entry . getKey ( ) ) ) { continue ; } args . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } Process process = process ( ) . getProcessById ( order . getProcessId ( ) ) ; Execution execution = new Execution ( this , process , order , args ) ; execution . setOperator ( operator ) ; execution . setTask ( task ) ; return execution ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "结束当前流程实例，如果存在父流程，则触发父流程继续执行 [CODESPLIT] public void handle ( Execution execution ) { SnakerEngine engine = execution . getEngine ( ) ; Order order = execution . getOrder ( ) ; List < Task > tasks = engine . query ( ) . getActiveTasks ( new QueryFilter ( ) . setOrderId ( order . getId ( ) ) ) ; for ( Task task : tasks ) { if ( task . isMajor ( ) ) throw new SnakerException ( \"存在未完成的主办任务,请确认.\");   engine . task ( ) . complete ( task . getId ( ) , SnakerEngine . AUTO ) ; } /**\n\t\t * 结束当前流程实例\n\t\t */ engine . order ( ) . complete ( order . getId ( ) ) ; /**\n\t\t * 如果存在父流程，则重新构造Execution执行对象，交给父流程的SubProcessModel模型execute\n\t\t */ if ( StringHelper . isNotEmpty ( order . getParentId ( ) ) ) { Order parentOrder = engine . query ( ) . getOrder ( order . getParentId ( ) ) ; if ( parentOrder == null ) return ; Process process = engine . process ( ) . getProcessById ( parentOrder . getProcessId ( ) ) ; ProcessModel pm = process . getModel ( ) ; if ( pm == null ) return ; SubProcessModel spm = ( SubProcessModel ) pm . getNode ( order . getParentNodeName ( ) ) ; Execution newExecution = new Execution ( engine , process , parentOrder , execution . getArgs ( ) ) ; newExecution . setChildOrderId ( order . getId ( ) ) ; newExecution . setTask ( execution . getTask ( ) ) ; spm . execute ( newExecution ) ; /**\n\t\t\t * SubProcessModel执行结果的tasks合并到当前执行对象execution的tasks列表中\n\t\t\t */ execution . addTasks ( newExecution . getTasks ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据reader读取sql脚本，并运行 [CODESPLIT] public void runScript ( Reader reader ) throws IOException , SQLException { AssertHelper . notNull ( connection ) ; try { boolean originalAutoCommit = connection . getAutoCommit ( ) ; try { if ( originalAutoCommit != this . autoCommit ) { connection . setAutoCommit ( this . autoCommit ) ; } runScript ( connection , reader ) ; } finally { connection . setAutoCommit ( originalAutoCommit ) ; } } catch ( IOException e ) { throw e ; } catch ( SQLException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( \"Error running script.  Cause: \" + e , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据给定的sql脚本资源、数据库连接对象，执行sql脚本 [CODESPLIT] private void runScript ( Connection conn , Reader reader ) throws IOException , SQLException { StringBuffer command = null ; try { LineNumberReader lineReader = new LineNumberReader ( reader ) ; String line = null ; while ( ( line = lineReader . readLine ( ) ) != null ) { if ( command == null ) { command = new StringBuffer ( ) ; } String trimmedLine = line . trim ( ) ; if ( trimmedLine . startsWith ( \"--\" ) ) { log . info ( trimmedLine ) ; } else if ( trimmedLine . length ( ) < 1 || trimmedLine . startsWith ( \"//\" ) ) { //Do nothing } else if ( trimmedLine . length ( ) < 1 || trimmedLine . startsWith ( \"--\" ) ) { //Do nothing } else if ( trimmedLine . equals ( getDelimiter ( ) ) || trimmedLine . endsWith ( getDelimiter ( ) ) ) { command . append ( line . substring ( 0 , line . lastIndexOf ( getDelimiter ( ) ) ) ) ; command . append ( \" \" ) ; Statement statement = conn . createStatement ( ) ; log . info ( command . toString ( ) ) ; try { statement . execute ( command . toString ( ) ) ; } catch ( SQLException e ) { e . fillInStackTrace ( ) ; log . error ( \"Error executing: \" + command ) ; } if ( autoCommit && ! conn . getAutoCommit ( ) ) { conn . commit ( ) ; } command = null ; try { statement . close ( ) ; } catch ( Exception e ) { //ignore } Thread . yield ( ) ; } else { command . append ( line ) ; command . append ( \" \" ) ; } } if ( ! autoCommit ) { conn . commit ( ) ; } } catch ( SQLException e ) { e . fillInStackTrace ( ) ; throw e ; } catch ( IOException e ) { e . fillInStackTrace ( ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "oracle分页通过rownum实现 [CODESPLIT] public String getPageSql ( String sql , Page < ? > page ) { StringBuffer pageSql = new StringBuffer ( sql . length ( ) + 100 ) ; pageSql . append ( \"select * from ( select row_.*, rownum rownum_ from ( \" ) ; pageSql . append ( sql ) ; long start = ( page . getPageNo ( ) - 1 ) * page . getPageSize ( ) + 1 ; pageSql . append ( \" ) row_ where rownum < \" ) ; pageSql . append ( start + page . getPageSize ( ) ) ; pageSql . append ( \" ) where rownum_ >= \" ) ; pageSql . append ( start ) ; return pageSql . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置排序类型 . [CODESPLIT] public void setOrder ( String order ) { String lowcaseOrder = StringUtils . lowerCase ( order ) ; //检查order字符串的合法值 String [ ] orders = StringUtils . split ( lowcaseOrder , ' ' ) ; for ( String orderStr : orders ) { if ( ! StringUtils . equals ( DESC , orderStr ) && ! StringUtils . equals ( ASC , orderStr ) ) { throw new IllegalArgumentException ( \"排序类型[\" + order t  + \"]不是合 值 );   } } this . order = lowcaseOrder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从element元素查找所有tagName指定的子节点元素集合 [CODESPLIT] public static List < Element > elements ( Element element , String tagName ) { if ( element == null || ! element . hasChildNodes ( ) ) { return Collections . emptyList ( ) ; } List < Element > elements = new ArrayList < Element > ( ) ; for ( Node child = element . getFirstChild ( ) ; child != null ; child = child . getNextSibling ( ) ) { if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) { Element childElement = ( Element ) child ; String childTagName = childElement . getNodeName ( ) ; if ( tagName . equals ( childTagName ) ) elements . add ( childElement ) ; } } return elements ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据字符串数组返回逗号分隔的字符串值 [CODESPLIT] public static String getStringByArray ( String ... strArray ) { if ( strArray == null ) return \"\" ; StringBuilder buffer = new StringBuilder ( strArray . length * 10 ) ; for ( String str : strArray ) { buffer . append ( str ) . append ( \",\" ) ; } buffer . deleteCharAt ( buffer . length ( ) - 1 ) ; return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "xml内容特殊符号替换 [CODESPLIT] public static String textXML ( String xml ) { if ( xml == null ) return \"\" ; String content = xml ; content = content . replaceAll ( \"<\" , \"&lt;\" ) ; content = content . replaceAll ( \">\" , \"&gt;\" ) ; content = content . replaceAll ( \"\\\"\" , \"&quot;\" ) ; content = content . replaceAll ( \"\\n\" , \"</br>\" ) ; return content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "构造排序条件 [CODESPLIT] public static String buildPageOrder ( String order , String orderby ) { if ( isEmpty ( orderby ) || isEmpty ( order ) ) return \"\" ; String [ ] orderByArray = StringUtils . split ( orderby , ' ' ) ; String [ ] orderArray = StringUtils . split ( order , ' ' ) ; if ( orderArray . length != orderByArray . length ) throw new SnakerException ( \"分页多重排序参数中,排序字段与排序方向的个数不相等\");   StringBuilder orderStr = new StringBuilder ( 30 ) ; orderStr . append ( \" order by \" ) ; for ( int i = 0 ; i < orderByArray . length ; i ++ ) { orderStr . append ( orderByArray [ i ] ) . append ( \" \" ) . append ( orderArray [ i ] ) . append ( \" ,\" ) ; } orderStr . deleteCharAt ( orderStr . length ( ) - 1 ) ; return orderStr . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "断言给定的字符串为非空 [CODESPLIT] public static void notEmpty ( String str , String message ) { if ( str == null || str . length ( ) == 0 ) { throw new IllegalArgumentException ( message ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "拦截产生的任务对象，打印日志 [CODESPLIT] public void intercept ( Execution execution ) { if ( log . isInfoEnabled ( ) ) { for ( Task task : execution . getTasks ( ) ) { StringBuffer buffer = new StringBuffer ( 100 ) ; buffer . append ( \"创建任务[标识=\").append(tas k . getId( ) );       buffer . append ( \",名称=\").ap p e nd(tas k .get D isplayName());     buffer . append ( \",创建时间=\").append ( t ask.ge t Crea t eTime());     buffer . append ( \",参与者={\");   if ( task . getActorIds ( ) != null ) { for ( String actor : task . getActorIds ( ) ) { buffer . append ( actor ) . append ( \";\" ) ; } } buffer . append ( \"}]\" ) ; log . info ( buffer . toString ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据历史任务产生撤回的任务对象 [CODESPLIT] public Task undoTask ( ) { Task task = new Task ( ) ; task . setOrderId ( this . getOrderId ( ) ) ; ; task . setTaskName ( this . getTaskName ( ) ) ; task . setDisplayName ( this . getDisplayName ( ) ) ; task . setTaskType ( this . getTaskType ( ) ) ; task . setExpireTime ( this . getExpireTime ( ) ) ; task . setActionUrl ( this . getActionUrl ( ) ) ; task . setParentTaskId ( this . getParentTaskId ( ) ) ; task . setVariable ( this . getVariable ( ) ) ; task . setPerformType ( this . getPerformType ( ) ) ; task . setOperator ( this . getOperator ( ) ) ; return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对join节点的所有输入变迁进行递归，查找join至fork节点的所有中间task元素 [CODESPLIT] private void findForkTaskNames ( NodeModel node , StringBuilder buffer ) { if ( node instanceof ForkModel ) return ; List < TransitionModel > inputs = node . getInputs ( ) ; for ( TransitionModel tm : inputs ) { if ( tm . getSource ( ) instanceof WorkModel ) { buffer . append ( tm . getSource ( ) . getName ( ) ) . append ( \",\" ) ; } findForkTaskNames ( tm . getSource ( ) , buffer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对join节点的所有输入变迁进行递归，查找join至fork节点的所有中间task元素 [CODESPLIT] protected String [ ] findActiveNodes ( ) { StringBuilder buffer = new StringBuilder ( 20 ) ; findForkTaskNames ( model , buffer ) ; String [ ] taskNames = buffer . toString ( ) . split ( \",\" ) ; return taskNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据历史实例撤回活动实例 [CODESPLIT] public Order undo ( ) { Order order = new Order ( ) ; order . setId ( this . id ) ; order . setProcessId ( this . processId ) ; order . setParentId ( this . parentId ) ; order . setCreator ( this . creator ) ; order . setCreateTime ( this . createTime ) ; order . setLastUpdator ( this . creator ) ; order . setLastUpdateTime ( this . endTime ) ; order . setExpireTime ( this . expireTime ) ; order . setOrderNo ( this . orderNo ) ; order . setPriority ( this . priority ) ; order . setVariable ( this . variable ) ; order . setVersion ( 0 ) ; return order ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取注册的引擎实例 [CODESPLIT] public static SnakerEngine getEngine ( ) { AssertHelper . notNull ( context , \"未注册服务上下文\");   if ( engine == null ) { engine = context . find ( SnakerEngine . class ) ; } return engine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向上下文添加服务实例 [CODESPLIT] public static void put ( String name , Object object ) { AssertHelper . notNull ( context , \"未注册服务上下文\");   if ( log . isInfoEnabled ( ) ) { log . info ( \"put new instance[name=\" + name + \"][object=\" + object + \"]\" ) ; } context . put ( name , object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向上下文添加服务实例 [CODESPLIT] public static void put ( String name , Class < ? > clazz ) { AssertHelper . notNull ( context , \"未注册服务上下文\");   if ( log . isInfoEnabled ( ) ) { log . info ( \"put new instance[name=\" + name + \"][clazz=\" + clazz . getName ( ) + \"]\" ) ; } context . put ( name , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对外部提供的查找对象方法，根据class类型查找 [CODESPLIT] public static < T > T find ( Class < T > clazz ) { AssertHelper . notNull ( context , \"未注册服务上下文\");   return context . find ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对外部提供的查找对象实例列表方法，根据class类型查找集合 [CODESPLIT] public static < T > List < T > findList ( Class < T > clazz ) { AssertHelper . notNull ( context , \"未注册服务上下文\");   return context . findList ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对外部提供的查找对象方法，根据名称、class类型查找 [CODESPLIT] public static < T > T findByName ( String name , Class < T > clazz ) { AssertHelper . notNull ( context , \"未注册服务上下文\");   return context . findByName ( name , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据任务模型、执行对象，创建下一个任务，并添加到execution对象的tasks集合中 [CODESPLIT] public void handle ( Execution execution ) { List < Task > tasks = execution . getEngine ( ) . task ( ) . createTask ( model , execution ) ; execution . addTasks ( tasks ) ; /**\n\t\t * 从服务上下文中查找任务拦截器列表，依次对task集合进行拦截处理\n\t\t */ List < SnakerInterceptor > interceptors = ServiceContext . getContext ( ) . findList ( SnakerInterceptor . class ) ; try { for ( SnakerInterceptor interceptor : interceptors ) { interceptor . intercept ( execution ) ; } } catch ( Exception e ) { log . error ( \"拦截器执行失败=\" + e.getMessag ( ) ;      throw new SnakerException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据传递的执行参数，自动执行任务 [CODESPLIT] public void exec ( Process process , String orderId , String taskId , NodeModel nodeModel , Map < String , Object > data ) throws JobExecutionException { log . info ( \"ExecutorJob execute taskId:{}\" , taskId ) ; if ( nodeModel == null || ! ( nodeModel instanceof TaskModel ) ) { log . debug ( \"节点模型为空，或不是任务模型，则不满足执行条件\");   return ; } TaskModel tm = ( TaskModel ) nodeModel ; List < Task > tasks = null ; if ( StringHelper . isNotEmpty ( tm . getAutoExecute ( ) ) && tm . getAutoExecute ( ) . equalsIgnoreCase ( \"Y\" ) ) { tasks = engine . executeTask ( taskId , SnakerEngine . AUTO , data ) ; schedule ( ) . delete ( IScheduler . TYPE_REMINDER + taskId ) ; } callback ( tm . getCallbackObject ( ) , taskId , tasks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "回调类执行 [CODESPLIT] private void callback ( JobCallback jobCallback , String taskId , List < Task > tasks ) { if ( jobCallback == null ) return ; jobCallback . callback ( taskId , tasks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "在没有任何SessionFactory注入的情况下，默认加载hibernate . cfg . xml初始化sessionFactory 这里只设置了常用的属性，建议调用Configuration . initAccessDBObject方法注入sessionfactory 或者使用ioc容器注入 [CODESPLIT] private static void initialize ( ) { String driver = ConfigHelper . getProperty ( \"jdbc.driver\" ) ; String url = ConfigHelper . getProperty ( \"jdbc.url\" ) ; String username = ConfigHelper . getProperty ( \"jdbc.username\" ) ; String password = ConfigHelper . getProperty ( \"jdbc.password\" ) ; String dialect = ConfigHelper . getProperty ( \"hibernate.dialect\" ) ; AssertHelper . notNull ( driver ) ; AssertHelper . notNull ( url ) ; AssertHelper . notNull ( username ) ; AssertHelper . notNull ( password ) ; AssertHelper . notNull ( dialect ) ; String formatSql = ConfigHelper . getProperty ( \"hibernate.format_sql\" ) ; String showSql = ConfigHelper . getProperty ( \"hibernate.show_sql\" ) ; Configuration configuration = new Configuration ( ) ; if ( StringHelper . isNotEmpty ( driver ) ) { configuration . setProperty ( \"hibernate.connection.driver_class\" , driver ) ; } if ( StringHelper . isNotEmpty ( url ) ) { configuration . setProperty ( \"hibernate.connection.url\" , url ) ; } if ( StringHelper . isNotEmpty ( username ) ) { configuration . setProperty ( \"hibernate.connection.username\" , username ) ; } if ( StringHelper . isNotEmpty ( password ) ) { configuration . setProperty ( \"hibernate.connection.password\" , password ) ; } if ( StringHelper . isNotEmpty ( dialect ) ) { configuration . setProperty ( \"hibernate.dialect\" , dialect ) ; } if ( StringHelper . isNotEmpty ( formatSql ) ) { configuration . setProperty ( \"hibernate.format_sql\" , formatSql ) ; } if ( StringHelper . isNotEmpty ( showSql ) ) { configuration . setProperty ( \"hibernate.show_sql\" , showSql ) ; } sessionFactory = configuration . configure ( ) . buildSessionFactory ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查询结果总记录数的类型转换 [CODESPLIT] public static long castLong ( Object count ) { if ( count == null ) return - 1L ; if ( count instanceof Long ) { return ( Long ) count ; } else if ( count instanceof BigDecimal ) { return ( ( BigDecimal ) count ) . longValue ( ) ; } else if ( count instanceof Integer ) { return ( ( Integer ) count ) . longValue ( ) ; } else if ( count instanceof BigInteger ) { return ( ( BigInteger ) count ) . longValue ( ) ; } else if ( count instanceof Byte ) { return ( ( Byte ) count ) . longValue ( ) ; } else if ( count instanceof Short ) { return ( ( Short ) count ) . longValue ( ) ; } else { return - 1L ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定的类名称加载类 [CODESPLIT] public static Class < ? > loadClass ( String className ) throws ClassNotFoundException { try { return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException ex ) { try { return ClassLoader . class . getClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException exc ) { throw exc ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "实例化指定的类名称（全路径） [CODESPLIT] public static Object newInstance ( String clazzStr ) { try { log . debug ( \"loading class:\" + clazzStr ) ; Class < ? > clazz = loadClass ( clazzStr ) ; return instantiate ( clazz ) ; } catch ( ClassNotFoundException e ) { log . error ( \"Class not found.\" , e ) ; } catch ( Exception ex ) { log . error ( \"类型实例化失败[class=\" + clazzStr +  ] n\" + ex. e Messa e )) ;      } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据类的class实例化对象 [CODESPLIT] public static < T > T instantiate ( Class < T > clazz ) { if ( clazz . isInterface ( ) ) { log . error ( \"所传递的class类型参数为接口，无法实例化\");   return null ; } try { return clazz . newInstance ( ) ; } catch ( Exception ex ) { log . error ( \"检查传递的class类型参数是否为抽象类?\", ex.getCause());         } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回当前流程定义的所有工作任务节点模型 [CODESPLIT] public List < WorkModel > getWorkModels ( ) { List < WorkModel > models = new ArrayList < WorkModel > ( ) ; for ( NodeModel node : nodes ) { if ( node instanceof WorkModel ) { models . add ( ( WorkModel ) node ) ; } } return models ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取所有的有序任务模型集合 [CODESPLIT] public List < TaskModel > getTaskModels ( ) { if ( taskModels . isEmpty ( ) ) { synchronized ( lock ) { if ( taskModels . isEmpty ( ) ) buildModels ( taskModels , getStart ( ) . getNextModels ( TaskModel . class ) , TaskModel . class ) ; } } return taskModels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定的节点类型返回流程定义中所有模型对象 [CODESPLIT] public < T > List < T > getModels ( Class < T > clazz ) { List < T > models = new ArrayList < T > ( ) ; buildModels ( models , getStart ( ) . getNextModels ( clazz ) , clazz ) ; return models ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取process定义的start节点模型 [CODESPLIT] public StartModel getStart ( ) { for ( NodeModel node : nodes ) { if ( node instanceof StartModel ) { return ( StartModel ) node ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取process定义的指定节点名称的节点模型 [CODESPLIT] public NodeModel getNode ( String nodeName ) { for ( NodeModel node : nodes ) { if ( node . getName ( ) . equals ( nodeName ) ) { return node ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断当前模型的节点是否包含给定的节点名称参数 [CODESPLIT] public < T > boolean containsNodeNames ( Class < T > T , String ... nodeNames ) { for ( NodeModel node : nodes ) { if ( ! T . isInstance ( node ) ) { continue ; } for ( String nodeName : nodeNames ) { if ( node . getName ( ) . equals ( nodeName ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对外部提供的查找对象方法，根据class类型查找 [CODESPLIT] public < T > T find ( Class < T > clazz ) { for ( Entry < String , Object > entry : contextMap . entrySet ( ) ) { if ( clazz . isInstance ( entry . getValue ( ) ) ) { return clazz . cast ( entry . getValue ( ) ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对外部提供的查找对象实例列表方法，根据class类型查找 [CODESPLIT] public < T > List < T > findList ( Class < T > clazz ) { List < T > list = new ArrayList < T > ( ) ; for ( Entry < String , Object > entry : contextMap . entrySet ( ) ) { if ( clazz . isInstance ( entry . getValue ( ) ) ) { list . add ( clazz . cast ( entry . getValue ( ) ) ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对外部提供的查找对象方法，根据名称、class类型查找 [CODESPLIT] public < T > T findByName ( String name , Class < T > clazz ) { for ( Entry < String , Object > entry : contextMap . entrySet ( ) ) { if ( entry . getKey ( ) . equals ( name ) && clazz . isInstance ( entry . getValue ( ) ) ) { return clazz . cast ( entry . getValue ( ) ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对外部提供的put方法 [CODESPLIT] public void put ( String name , Class < ? > clazz ) { contextMap . put ( name , ClassHelper . instantiate ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "构造SnakerEngine对象，用于api集成 通过SpringHelper调用 [CODESPLIT] public SnakerEngine buildSnakerEngine ( ) throws SnakerException { if ( log . isInfoEnabled ( ) ) { log . info ( \"SnakerEngine start......\" ) ; } parser ( ) ; /**\n\t\t * 由服务上下文返回流程引擎\n\t\t */ SnakerEngine configEngine = ServiceContext . getEngine ( ) ; if ( configEngine == null ) { throw new SnakerException ( \"配置无法发现SnakerEngine的实现类\");   } if ( log . isInfoEnabled ( ) ) { log . info ( \"SnakerEngine be found:\" + configEngine . getClass ( ) ) ; } return configEngine . configure ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "依次解析框架固定的配置及用户自定义的配置 固定配置文件 : base . config . xml 扩展配置文件 : ext . config . xml 用户自定义配置文件 : snaker . xml [CODESPLIT] protected void parser ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Service parsing start......\" ) ; } //默认使用snaker.xml配置自定义的bean String config = ConfigHelper . getProperty ( \"config\" ) ; if ( StringHelper . isEmpty ( config ) ) { config = USER_CONFIG_FILE ; } parser ( config ) ; parser ( BASE_CONFIG_FILE ) ; if ( ! isCMB ( ) ) { parser ( EXT_CONFIG_FILE ) ; for ( Entry < String , Class < ? > > entry : txClass . entrySet ( ) ) { if ( interceptor != null ) { Object instance = interceptor . getProxy ( entry . getValue ( ) ) ; ServiceContext . put ( entry . getKey ( ) , instance ) ; } else { ServiceContext . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } } if ( log . isDebugEnabled ( ) ) { log . debug ( \"Service parsing finish......\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析给定resource配置，并注册到ServiceContext上下文中 [CODESPLIT] private void parser ( String resource ) { //解析所有配置节点，并实例化class指定的类 DocumentBuilder documentBuilder = XmlHelper . createDocumentBuilder ( ) ; try { if ( documentBuilder != null ) { InputStream input = StreamHelper . openStream ( resource ) ; if ( input == null ) return ; Document doc = documentBuilder . parse ( input ) ; Element configElement = doc . getDocumentElement ( ) ; NodeList nodeList = configElement . getChildNodes ( ) ; int nodeSize = nodeList . getLength ( ) ; for ( int i = 0 ; i < nodeSize ; i ++ ) { Node node = nodeList . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element element = ( Element ) node ; String name = element . getAttribute ( \"name\" ) ; String className = element . getAttribute ( \"class\" ) ; String proxy = element . getAttribute ( \"proxy\" ) ; if ( StringHelper . isEmpty ( name ) ) { name = className ; } if ( ServiceContext . exist ( name ) ) { log . warn ( \"Duplicate name is:\" + name ) ; continue ; } Class < ? > clazz = ClassHelper . loadClass ( className ) ; if ( TransactionInterceptor . class . isAssignableFrom ( clazz ) ) { interceptor = ( TransactionInterceptor ) ClassHelper . instantiate ( clazz ) ; ServiceContext . put ( name , interceptor ) ; continue ; } if ( proxy != null && proxy . equalsIgnoreCase ( \"transaction\" ) ) { txClass . put ( name , clazz ) ; } else { ServiceContext . put ( name , clazz ) ; } } } } } catch ( Exception e ) { e . printStackTrace ( ) ; throw new SnakerException ( \"资源解析失败，请检查配置文件[\" + resource + \"]\", e.getCaus ( );           } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "利用反射获取指定对象的指定属性 [CODESPLIT] public static Object getFieldValue ( Object obj , String fieldName ) { Object result = null ; Field field = getField ( obj , fieldName ) ; if ( field != null ) { field . setAccessible ( true ) ; try { result = field . get ( obj ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "利用反射设置指定对象的指定属性为指定的值 [CODESPLIT] public static void setFieldValue ( Object obj , String fieldName , Object fieldValue ) { Field field = getField ( obj , fieldName ) ; if ( field != null ) { try { field . setAccessible ( true ) ; field . set ( obj , fieldValue ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定的对象、方法、参数反射调用，并返回调用结果 [CODESPLIT] public static Object invoke ( Method method , Object target , Object [ ] args ) { if ( method == null ) { throw new SnakerException ( \"方法不能为空\");   } try { if ( ! method . isAccessible ( ) ) { method . setAccessible ( true ) ; } return method . invoke ( target , args ) ; } catch ( InvocationTargetException e ) { Throwable targetException = e . getTargetException ( ) ; throw new SnakerException ( \"不能调用 '\" + metho . etName ( ) + \"'  w i h \" + Arrays . toString ( args ) + \" on \" + target + \": \" + targetException . getMessage ( ) , targetException ) ; } catch ( Exception e ) { throw new SnakerException ( \"不能调用 '\" + metho . etName ( ) + \"'  w i h \" + Arrays . toString ( args ) + \" on \" + target + \": \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据class类型、methodName方法名称，返回Method对象。 注意：这里不检查参数类型，所以自定义的java类应该避免使用重载方法 [CODESPLIT] public static Method findMethod ( Class < ? > clazz , String methodName ) { Method [ ] candidates = clazz . getDeclaredMethods ( ) ; for ( int i = 0 ; i < candidates . length ; i ++ ) { Method candidate = candidates [ i ] ; if ( candidate . getName ( ) . equals ( methodName ) ) { return candidate ; } } if ( clazz . getSuperclass ( ) != null ) { return findMethod ( clazz . getSuperclass ( ) , methodName ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据job实体调度具体的任务 [CODESPLIT] public void schedule ( JobEntity entity ) { AssertHelper . notNull ( entity ) ; JobDataMap data = new JobDataMap ( entity . getArgs ( ) ) ; data . put ( KEY , entity . getId ( ) ) ; data . put ( MODEL , entity . getModelName ( ) ) ; Class < ? extends Job > jobClazz = null ; String jobId = \"\" ; switch ( entity . getJobType ( ) ) { case 0 : jobClazz = ExecutorJob . class ; jobId = TYPE_EXECUTOR + entity . getTask ( ) . getId ( ) ; break ; case 1 : jobClazz = ReminderJob . class ; jobId = TYPE_REMINDER + entity . getTask ( ) . getId ( ) ; break ; } if ( jobClazz == null ) { log . error ( \"Quartz不支持的JOB类型:{}\", entity.get J bType( ) );     return ; } JobDetail job = JobBuilder . newJob ( jobClazz ) . usingJobData ( data ) . withIdentity ( jobId , GROUP ) . build ( ) ; Trigger trigger = null ; TriggerBuilder < Trigger > builder = TriggerBuilder . newTrigger ( ) . withIdentity ( StringHelper . getPrimaryKey ( ) , GROUP ) . startAt ( entity . getStartTime ( ) ) ; if ( jobClazz == ReminderJob . class && entity . getPeriod ( ) > 0 ) { int count = ConfigHelper . getNumerProperty ( CONFIG_REPEAT ) ; if ( count <= 0 ) count = 1 ; builder . withSchedule ( SimpleScheduleBuilder . repeatMinutelyForTotalCount ( count , entity . getPeriod ( ) ) ) ; if ( isUseCalendar ) { builder . modifiedByCalendar ( CALENDAR_NAME ) ; } } trigger = builder . build ( ) ; try { log . info ( \"jobId:{} class:{} starting......\" , jobId , jobClazz ) ; getScheduler ( ) . scheduleJob ( job , trigger ) ; } catch ( SchedulerException e ) { log . error ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "启动插件 [CODESPLIT] public boolean start ( ) { if ( isStarted ) return true ; if ( dataSourceProvider != null ) dataSource = dataSourceProvider . getDataSource ( ) ; if ( dataSource == null ) throw new RuntimeException ( \"SnakerPlugin start error: SnakerPlugin need DataSource\" ) ; Configuration config = new Configuration ( ) . initAccessDBObject ( dataSource ) ; if ( properties != null ) config . initProperties ( properties ) ; engine = config . buildSnakerEngine ( ) ; isStarted = true ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter name / displayName / instanceUrl [CODESPLIT] public void setModel ( ProcessModel processModel ) { this . model = processModel ; this . name = processModel . getName ( ) ; this . displayName = processModel . getDisplayName ( ) ; this . instanceUrl = processModel . getInstanceUrl ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "时限控制拦截方法 [CODESPLIT] public void intercept ( Execution execution ) { if ( ! isScheduled ) return ; for ( Task task : execution . getTasks ( ) ) { String id = execution . getProcess ( ) . getId ( ) + \"-\" + execution . getOrder ( ) . getId ( ) + \"-\" + task . getId ( ) ; Date expireDate = task . getExpireDate ( ) ; if ( expireDate != null ) { schedule ( id , task , expireDate , JobType . EXECUTER . ordinal ( ) , execution . getArgs ( ) ) ; } Date remindDate = task . getRemindDate ( ) ; if ( remindDate != null ) { schedule ( id , task , remindDate , JobType . REMINDER . ordinal ( ) , execution . getArgs ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "子流程执行的处理 [CODESPLIT] public void handle ( Execution execution ) { //根据子流程模型名称获取子流程定义对象 SnakerEngine engine = execution . getEngine ( ) ; Process process = engine . process ( ) . getProcessByVersion ( model . getProcessName ( ) , model . getVersion ( ) ) ; Execution child = execution . createSubExecution ( execution , process , model . getName ( ) ) ; Order order = null ; if ( isFutureRunning ) { //创建单个线程执行器来执行启动子流程的任务 ExecutorService es = Executors . newSingleThreadExecutor ( ) ; //提交执行任务，并返回future Future < Order > future = es . submit ( new ExecuteTask ( execution , process , model . getName ( ) ) ) ; try { es . shutdown ( ) ; order = future . get ( ) ; } catch ( InterruptedException e ) { throw new SnakerException ( \"创建子流程线程被强制终止执行\", e.getCause());         } catch ( ExecutionException e ) { throw new SnakerException ( \"创建子流程线程执行异常.\", e.getCause());         } } else { order = engine . startInstanceByExecution ( child ) ; } AssertHelper . notNull ( order , \"子流程创建失败\");   execution . addTasks ( engine . query ( ) . getActiveTasks ( new QueryFilter ( ) . setOrderId ( order . getId ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析decisition节点的特有属性expr [CODESPLIT] protected void parseNode ( NodeModel node , Element element ) { DecisionModel decision = ( DecisionModel ) node ; decision . setExpr ( element . getAttribute ( ATTR_EXPR ) ) ; decision . setHandleClass ( element . getAttribute ( ATTR_HANDLECLASS ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取调度器接口 [CODESPLIT] protected IScheduler schedule ( ) { if ( scheduler == null ) { scheduler = ServiceContext . getContext ( ) . find ( IScheduler . class ) ; } return scheduler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ResultSet结果集处理 [CODESPLIT] protected T handleRow ( ResultSet rs ) throws SQLException { /**\n\t\t * 根据bean的class类型实例化为对象\n\t\t */ T mappedObject = ClassHelper . instantiate ( mappedClass ) ; ResultSetMetaData rsmd = rs . getMetaData ( ) ; int columnCount = rsmd . getColumnCount ( ) ; /**\n\t\t * 对ResultSet结果集字段进行循环\n\t\t */ for ( int index = 1 ; index <= columnCount ; index ++ ) { /**\n\t\t\t * 根据字段索引index获取字段名称\n\t\t\t */ String column = JdbcHelper . lookupColumnName ( rsmd , index ) ; /**\n\t\t\t * 根据映射字段集合返回字段名称对应的属性描述符对象\n\t\t\t */ PropertyDescriptor pd = this . mappedFields . get ( column . replaceAll ( \" \" , \"\" ) . toLowerCase ( ) ) ; if ( pd != null ) { try { /**\n\t\t\t\t\t * 根据字段index、属性类型返回字段值\n\t\t\t\t\t */ Object value = JdbcHelper . getResultSetValue ( rs , index , pd . getPropertyType ( ) ) ; try { /**\n\t\t\t\t\t\t * 使用apache-beanutils设置对象的属性\n\t\t\t\t\t\t */ BeanUtils . setProperty ( mappedObject , pd . getName ( ) , value ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } return mappedObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据bean对象的class初始化字段映射集合 [CODESPLIT] protected void initialize ( Class < T > mappedClass ) { this . mappedClass = mappedClass ; this . mappedFields = new HashMap < String , PropertyDescriptor > ( ) ; PropertyDescriptor [ ] pds = null ; try { /**\n\t\t\t * 返回bean的属性描述对象数组\n\t\t\t */ pds = propertyDescriptors ( mappedClass ) ; } catch ( SQLException e ) { throw new SnakerException ( e . getMessage ( ) , e . getCause ( ) ) ; } for ( PropertyDescriptor pd : pds ) { if ( pd . getWriteMethod ( ) != null ) { this . mappedFields . put ( pd . getName ( ) . toLowerCase ( ) , pd ) ; String underscoredName = underscoreName ( pd . getName ( ) ) ; if ( ! pd . getName ( ) . toLowerCase ( ) . equals ( underscoredName ) ) { this . mappedFields . put ( underscoredName , pd ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "属性名称转换为下划线，如taskId - > task_id [CODESPLIT] private static String underscoreName ( String name ) { StringBuilder result = new StringBuilder ( ) ; if ( name != null && name . length ( ) > 0 ) { result . append ( name . substring ( 0 , 1 ) . toLowerCase ( ) ) ; for ( int i = 1 ; i < name . length ( ) ; i ++ ) { String s = name . substring ( i , i + 1 ) ; if ( s . equals ( s . toUpperCase ( ) ) ) { result . append ( \"_\" ) ; result . append ( s . toLowerCase ( ) ) ; } else { result . append ( s ) ; } } } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "由Introspector返回指定类型的BeanInfo对象，再返回需要的属性描述对象数组PropertyDescriptor [] [CODESPLIT] private PropertyDescriptor [ ] propertyDescriptors ( Class < ? > c ) throws SQLException { BeanInfo beanInfo = null ; try { beanInfo = Introspector . getBeanInfo ( c ) ; } catch ( IntrospectionException e ) { throw new SQLException ( \"Bean introspection failed: \" + e . getMessage ( ) ) ; } return beanInfo . getPropertyDescriptors ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "更新process的类别 [CODESPLIT] public void updateType ( String id , String type ) { Process entity = getProcessById ( id ) ; entity . setType ( type ) ; access ( ) . updateProcessType ( id , type ) ; cache ( entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据id获取process对象 先通过cache获取，如果返回空，就从数据库读取并put [CODESPLIT] public Process getProcessById ( String id ) { AssertHelper . notEmpty ( id ) ; Process entity = null ; String processName ; Cache < String , String > nameCache = ensureAvailableNameCache ( ) ; Cache < String , Process > entityCache = ensureAvailableEntityCache ( ) ; if ( nameCache != null && entityCache != null ) { processName = nameCache . get ( id ) ; if ( StringHelper . isNotEmpty ( processName ) ) { entity = entityCache . get ( processName ) ; } } if ( entity != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"obtain process[id={}] from cache.\" , id ) ; } return entity ; } entity = access ( ) . getProcess ( id ) ; if ( entity != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"obtain process[id={}] from database.\" , id ) ; } cache ( entity ) ; } return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据name获取process对象 先通过cache获取，如果返回空，就从数据库读取并put [CODESPLIT] public Process getProcessByVersion ( String name , Integer version ) { AssertHelper . notEmpty ( name ) ; if ( version == null ) { version = access ( ) . getLatestProcessVersion ( name ) ; } if ( version == null ) { version = 0 ; } Process entity = null ; String processName = name + DEFAULT_SEPARATOR + version ; Cache < String , Process > entityCache = ensureAvailableEntityCache ( ) ; if ( entityCache != null ) { entity = entityCache . get ( processName ) ; } if ( entity != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"obtain process[name={}] from cache.\" , processName ) ; } return entity ; } List < Process > processs = access ( ) . getProcesss ( null , new QueryFilter ( ) . setName ( name ) . setVersion ( version ) ) ; if ( processs != null && ! processs . isEmpty ( ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"obtain process[name={}] from database.\" , processName ) ; } entity = processs . get ( 0 ) ; cache ( entity ) ; } return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据流程定义xml的输入流解析为字节数组，保存至数据库中，并且put到缓存中 [CODESPLIT] public String deploy ( InputStream input , String creator ) { AssertHelper . notNull ( input ) ; try { byte [ ] bytes = StreamHelper . readBytes ( input ) ; ProcessModel model = ModelParser . parse ( bytes ) ; Integer version = access ( ) . getLatestProcessVersion ( model . getName ( ) ) ; Process entity = new Process ( ) ; entity . setId ( StringHelper . getPrimaryKey ( ) ) ; if ( version == null || version < 0 ) { entity . setVersion ( 0 ) ; } else { entity . setVersion ( version + 1 ) ; } entity . setState ( STATE_ACTIVE ) ; entity . setModel ( model ) ; entity . setBytes ( bytes ) ; entity . setCreateTime ( DateHelper . getTime ( ) ) ; entity . setCreator ( creator ) ; saveProcess ( entity ) ; cache ( entity ) ; return entity . getId ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; log . error ( e . getMessage ( ) ) ; throw new SnakerException ( e . getMessage ( ) , e . getCause ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据流程定义id、xml的输入流解析为字节数组，保存至数据库中，并且重新put到缓存中 [CODESPLIT] public void redeploy ( String id , InputStream input ) { AssertHelper . notNull ( input ) ; Process entity = access ( ) . getProcess ( id ) ; AssertHelper . notNull ( entity ) ; try { byte [ ] bytes = StreamHelper . readBytes ( input ) ; ProcessModel model = ModelParser . parse ( bytes ) ; String oldProcessName = entity . getName ( ) ; entity . setModel ( model ) ; entity . setBytes ( bytes ) ; access ( ) . updateProcess ( entity ) ; if ( ! oldProcessName . equalsIgnoreCase ( entity . getName ( ) ) ) { Cache < String , Process > entityCache = ensureAvailableEntityCache ( ) ; if ( entityCache != null ) { entityCache . remove ( oldProcessName + DEFAULT_SEPARATOR + entity . getVersion ( ) ) ; } } cache ( entity ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; log . error ( e . getMessage ( ) ) ; throw new SnakerException ( e . getMessage ( ) , e . getCause ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据processId卸载流程 [CODESPLIT] public void undeploy ( String id ) { Process entity = access ( ) . getProcess ( id ) ; entity . setState ( STATE_FINISH ) ; access ( ) . updateProcess ( entity ) ; cache ( entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "级联删除指定流程定义的所有数据 [CODESPLIT] public void cascadeRemove ( String id ) { Process entity = access ( ) . getProcess ( id ) ; List < HistoryOrder > historyOrders = access ( ) . getHistoryOrders ( null , new QueryFilter ( ) . setProcessId ( id ) ) ; for ( HistoryOrder historyOrder : historyOrders ) { ServiceContext . getEngine ( ) . order ( ) . cascadeRemove ( historyOrder . getId ( ) ) ; } access ( ) . deleteProcess ( entity ) ; clear ( entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查询流程定义 [CODESPLIT] public List < Process > getProcesss ( QueryFilter filter ) { if ( filter == null ) filter = new QueryFilter ( ) ; return access ( ) . getProcesss ( null , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分页查询流程定义 [CODESPLIT] public List < Process > getProcesss ( Page < Process > page , QueryFilter filter ) { AssertHelper . notNull ( filter ) ; return access ( ) . getProcesss ( page , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "缓存实体 [CODESPLIT] private void cache ( Process entity ) { Cache < String , String > nameCache = ensureAvailableNameCache ( ) ; Cache < String , Process > entityCache = ensureAvailableEntityCache ( ) ; if ( entity . getModel ( ) == null && entity . getDBContent ( ) != null ) { entity . setModel ( ModelParser . parse ( entity . getDBContent ( ) ) ) ; } String processName = entity . getName ( ) + DEFAULT_SEPARATOR + entity . getVersion ( ) ; if ( nameCache != null && entityCache != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"cache process id is[{}],name is[{}]\" , entity . getId ( ) , processName ) ; } entityCache . put ( processName , entity ) ; nameCache . put ( entity . getId ( ) , processName ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( \"no cache implementation class\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "清除实体 [CODESPLIT] private void clear ( Process entity ) { Cache < String , String > nameCache = ensureAvailableNameCache ( ) ; Cache < String , Process > entityCache = ensureAvailableEntityCache ( ) ; String processName = entity . getName ( ) + DEFAULT_SEPARATOR + entity . getVersion ( ) ; if ( nameCache != null && entityCache != null ) { nameCache . remove ( entity . getId ( ) ) ; entityCache . remove ( processName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析流程定义文件，并将解析后的对象放入模型容器中 [CODESPLIT] public static ProcessModel parse ( byte [ ] bytes ) { DocumentBuilder documentBuilder = XmlHelper . createDocumentBuilder ( ) ; if ( documentBuilder != null ) { Document doc = null ; try { doc = documentBuilder . parse ( new ByteArrayInputStream ( bytes ) ) ; Element processE = doc . getDocumentElement ( ) ; ProcessModel process = new ProcessModel ( ) ; process . setName ( processE . getAttribute ( NodeParser . ATTR_NAME ) ) ; process . setDisplayName ( processE . getAttribute ( NodeParser . ATTR_DISPLAYNAME ) ) ; process . setExpireTime ( processE . getAttribute ( NodeParser . ATTR_EXPIRETIME ) ) ; process . setInstanceUrl ( processE . getAttribute ( NodeParser . ATTR_INSTANCEURL ) ) ; process . setInstanceNoClass ( processE . getAttribute ( NodeParser . ATTR_INSTANCENOCLASS ) ) ; NodeList nodeList = processE . getChildNodes ( ) ; int nodeSize = nodeList . getLength ( ) ; for ( int i = 0 ; i < nodeSize ; i ++ ) { Node node = nodeList . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { NodeModel model = parseModel ( node ) ; process . getNodes ( ) . add ( model ) ; } } //循环节点模型，构造变迁输入、输出的source、target for ( NodeModel node : process . getNodes ( ) ) { for ( TransitionModel transition : node . getOutputs ( ) ) { String to = transition . getTo ( ) ; for ( NodeModel node2 : process . getNodes ( ) ) { if ( to . equalsIgnoreCase ( node2 . getName ( ) ) ) { node2 . getInputs ( ) . add ( transition ) ; transition . setTarget ( node2 ) ; } } } } return process ; } catch ( SAXException e ) { e . printStackTrace ( ) ; throw new SnakerException ( e ) ; } catch ( IOException e ) { throw new SnakerException ( e ) ; } } else { throw new SnakerException ( \"documentBuilder is null\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对流程定义xml的节点，根据其节点对应的解析器解析节点内容 [CODESPLIT] private static NodeModel parseModel ( Node node ) { String nodeName = node . getNodeName ( ) ; Element element = ( Element ) node ; NodeParser nodeParser = null ; try { nodeParser = ServiceContext . getContext ( ) . findByName ( nodeName , NodeParser . class ) ; nodeParser . parse ( element ) ; return nodeParser . getModel ( ) ; } catch ( RuntimeException e ) { throw new SnakerException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析decisition节点的特有属性expr [CODESPLIT] protected void parseNode ( NodeModel node , Element element ) { SubProcessModel model = ( SubProcessModel ) node ; model . setProcessName ( element . getAttribute ( ATTR_PROCESSNAME ) ) ; String version = element . getAttribute ( ATTR_VERSION ) ; int ver = 0 ; if ( NumberUtils . isNumber ( version ) ) { ver = Integer . parseInt ( version ) ; } model . setVersion ( ver ) ; String form = element . getAttribute ( ATTR_FORM ) ; if ( StringHelper . isNotEmpty ( form ) ) { model . setForm ( form ) ; } else { model . setForm ( ConfigHelper . getProperty ( \"subprocessurl\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取后续任务模型集合（方便预处理） [CODESPLIT] public List < TaskModel > getNextTaskModels ( ) { List < TaskModel > models = new ArrayList < TaskModel > ( ) ; for ( TransitionModel tm : this . getOutputs ( ) ) { addNextModels ( models , tm , TaskModel . class ) ; } return models ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据当前执行对象execution、子流程定义process、当前节点名称产生子流程的执行对象 [CODESPLIT] public Execution createSubExecution ( Execution execution , Process process , String parentNodeName ) { return new Execution ( execution , process , parentNodeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对执行逻辑增加前置、后置拦截处理 [CODESPLIT] public void execute ( Execution execution ) { intercept ( preInterceptorList , execution ) ; exec ( execution ) ; intercept ( postInterceptorList , execution ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "运行变迁继续执行 [CODESPLIT] protected void runOutTransition ( Execution execution ) { for ( TransitionModel tm : getOutputs ( ) ) { tm . setEnabled ( true ) ; tm . execute ( execution ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "拦截方法 [CODESPLIT] private void intercept ( List < SnakerInterceptor > interceptorList , Execution execution ) { try { for ( SnakerInterceptor interceptor : interceptorList ) { interceptor . intercept ( execution ) ; } } catch ( Exception e ) { log . error ( \"拦截器执行失败=\" + e.getMessag ( ) ;      throw new SnakerException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据父节点模型、当前节点模型判断是否可退回。可退回条件： 1、满足中间无fork、join、subprocess模型 2、满足父节点模型如果为任务模型时，参与类型为any [CODESPLIT] public static boolean canRejected ( NodeModel current , NodeModel parent ) { if ( parent instanceof TaskModel && ! ( ( TaskModel ) parent ) . isPerformAny ( ) ) { return false ; } boolean result = false ; for ( TransitionModel tm : current . getInputs ( ) ) { NodeModel source = tm . getSource ( ) ; if ( source == parent ) { return true ; } if ( source instanceof ForkModel || source instanceof JoinModel || source instanceof SubProcessModel || source instanceof StartModel ) { continue ; } result = result || canRejected ( source , parent ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用原生JDBC操作BLOB字段 [CODESPLIT] public void saveProcess ( Process process ) { super . saveProcess ( process ) ; if ( process . getBytes ( ) != null ) { Connection conn = null ; PreparedStatement pstmt = null ; try { conn = getConnection ( ) ; pstmt = conn . prepareStatement ( PROCESS_UPDATE_BLOB ) ; pstmt . setBytes ( 1 , process . getBytes ( ) ) ; pstmt . setString ( 2 , process . getId ( ) ) ; pstmt . execute ( ) ; } catch ( Exception e ) { throw new SnakerException ( e . getMessage ( ) , e . getCause ( ) ) ; } finally { try { JdbcHelper . close ( pstmt ) ; } catch ( SQLException e ) { throw new SnakerException ( e . getMessage ( ) , e . getCause ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查询指定列 [CODESPLIT] public Object query ( int column , String sql , Object ... params ) { Object result ; try { if ( log . isDebugEnabled ( ) ) { log . debug ( \"查询单列数据=\\n\" + sql);     } result = runner . query ( getConnection ( ) , sql , new ScalarHandler ( column ) , params ) ; } catch ( SQLException e ) { log . error ( e . getMessage ( ) , e ) ; throw new RuntimeException ( e . getMessage ( ) , e ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取得hibernate的connection对象 [CODESPLIT] protected Connection getConnection ( ) throws SQLException { if ( sessionFactory instanceof SessionFactoryImpl ) { SessionFactoryImpl sessionFactoryImpl = ( SessionFactoryImpl ) sessionFactory ; ConnectionProvider provider = sessionFactoryImpl . getServiceRegistry ( ) . getService ( ConnectionProvider . class ) ; if ( provider != null ) return provider . getConnection ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用Cglib产生业务类的代理 [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T getProxy ( Class < T > clazz ) { return ( T ) Enhancer . create ( clazz , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "方法执行的拦截器，拦截条件为： 1、数据库访问类是DBTransaction的实现类 2、方法名称匹配初始化的事务方法列表 [CODESPLIT] public Object intercept ( Object obj , Method method , Object [ ] args , MethodProxy proxy ) throws Throwable { Object result = null ; TransactionStatus status = null ; if ( isMatch ( method . getName ( ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"intercept method is[name=\" + method . getName ( ) + \"]\" ) ; } try { status = getTransaction ( ) ; AssertHelper . notNull ( status ) ; //调用具体无事务支持的业务逻辑 result = proxy . invokeSuper ( obj , args ) ; //如果整个执行过程无异常抛出，则提交TransactionStatus持有的transaction对象 if ( status . isNewTransaction ( ) ) { commit ( status ) ; } } catch ( Exception e ) { rollback ( status ) ; throw new SnakerException ( e ) ; } } else { if ( log . isDebugEnabled ( ) ) { log . debug ( \"****don't intercept method is[name=\" + method . getName ( ) + \"]\" ) ; } result = proxy . invokeSuper ( obj , args ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据方法名称，匹配所有初始化的需要事务拦截的方法 [CODESPLIT] private boolean isMatch ( String methodName ) { for ( String pattern : txMethods ) { if ( StringHelper . simpleMatch ( pattern , methodName ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建活动实例 [CODESPLIT] public Order createOrder ( Process process , String operator , Map < String , Object > args ) { return createOrder ( process , operator , args , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建活动实例 [CODESPLIT] public Order createOrder ( Process process , String operator , Map < String , Object > args , String parentId , String parentNodeName ) { Order order = new Order ( ) ; order . setId ( StringHelper . getPrimaryKey ( ) ) ; order . setParentId ( parentId ) ; order . setParentNodeName ( parentNodeName ) ; order . setCreateTime ( DateHelper . getTime ( ) ) ; order . setLastUpdateTime ( order . getCreateTime ( ) ) ; order . setCreator ( operator ) ; order . setLastUpdator ( order . getCreator ( ) ) ; order . setProcessId ( process . getId ( ) ) ; ProcessModel model = process . getModel ( ) ; if ( model != null && args != null ) { if ( StringHelper . isNotEmpty ( model . getExpireTime ( ) ) ) { String expireTime = DateHelper . parseTime ( args . get ( model . getExpireTime ( ) ) ) ; order . setExpireTime ( expireTime ) ; } String orderNo = ( String ) args . get ( SnakerEngine . ID ) ; if ( StringHelper . isNotEmpty ( orderNo ) ) { order . setOrderNo ( orderNo ) ; } else { order . setOrderNo ( model . getGenerator ( ) . generate ( model ) ) ; } } order . setVariable ( JsonHelper . toJson ( args ) ) ; saveOrder ( order ) ; return order ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向活动实例临时添加全局变量数据 [CODESPLIT] public void addVariable ( String orderId , Map < String , Object > args ) { Order order = access ( ) . getOrder ( orderId ) ; Map < String , Object > data = order . getVariableMap ( ) ; data . putAll ( args ) ; order . setVariable ( JsonHelper . toJson ( data ) ) ; access ( ) . updateOrderVariable ( order ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建实例的抄送 [CODESPLIT] public void createCCOrder ( String orderId , String creator , String ... actorIds ) { for ( String actorId : actorIds ) { CCOrder ccorder = new CCOrder ( ) ; ccorder . setOrderId ( orderId ) ; ccorder . setActorId ( actorId ) ; ccorder . setCreator ( creator ) ; ccorder . setStatus ( STATE_ACTIVE ) ; ccorder . setCreateTime ( DateHelper . getTime ( ) ) ; access ( ) . saveCCOrder ( ccorder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "流程实例数据会保存至活动实例表、历史实例表 [CODESPLIT] public void saveOrder ( Order order ) { HistoryOrder history = new HistoryOrder ( order ) ; history . setOrderState ( STATE_ACTIVE ) ; access ( ) . saveOrder ( order ) ; access ( ) . saveHistory ( history ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "更新抄送记录状态为已阅 [CODESPLIT] public void updateCCStatus ( String orderId , String ... actorIds ) { List < CCOrder > ccorders = access ( ) . getCCOrder ( orderId , actorIds ) ; AssertHelper . notNull ( ccorders ) ; for ( CCOrder ccorder : ccorders ) { ccorder . setStatus ( STATE_FINISH ) ; ccorder . setFinishTime ( DateHelper . getTime ( ) ) ; access ( ) . updateCCOrder ( ccorder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "删除指定的抄送记录 [CODESPLIT] public void deleteCCOrder ( String orderId , String actorId ) { List < CCOrder > ccorders = access ( ) . getCCOrder ( orderId , actorId ) ; AssertHelper . notNull ( ccorders ) ; for ( CCOrder ccorder : ccorders ) { access ( ) . deleteCCOrder ( ccorder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "删除活动流程实例数据，更新历史流程实例的状态、结束时间 [CODESPLIT] public void complete ( String orderId ) { Order order = access ( ) . getOrder ( orderId ) ; HistoryOrder history = access ( ) . getHistOrder ( orderId ) ; history . setOrderState ( STATE_FINISH ) ; history . setEndTime ( DateHelper . getTime ( ) ) ; access ( ) . updateHistory ( history ) ; access ( ) . deleteOrder ( order ) ; Completion completion = getCompletion ( ) ; if ( completion != null ) { completion . complete ( history ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "强制中止活动实例 并强制完成活动任务 [CODESPLIT] public void terminate ( String orderId , String operator ) { SnakerEngine engine = ServiceContext . getEngine ( ) ; List < Task > tasks = engine . query ( ) . getActiveTasks ( new QueryFilter ( ) . setOrderId ( orderId ) ) ; for ( Task task : tasks ) { engine . task ( ) . complete ( task . getId ( ) , operator ) ; } Order order = access ( ) . getOrder ( orderId ) ; HistoryOrder history = new HistoryOrder ( order ) ; history . setOrderState ( STATE_TERMINATION ) ; history . setEndTime ( DateHelper . getTime ( ) ) ; access ( ) . updateHistory ( history ) ; access ( ) . deleteOrder ( order ) ; Completion completion = getCompletion ( ) ; if ( completion != null ) { completion . complete ( history ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "激活已完成的历史流程实例 [CODESPLIT] public Order resume ( String orderId ) { HistoryOrder historyOrder = access ( ) . getHistOrder ( orderId ) ; Order order = historyOrder . undo ( ) ; access ( ) . saveOrder ( order ) ; historyOrder . setOrderState ( STATE_ACTIVE ) ; access ( ) . updateHistory ( historyOrder ) ; SnakerEngine engine = ServiceContext . getEngine ( ) ; List < HistoryTask > histTasks = access ( ) . getHistoryTasks ( null , new QueryFilter ( ) . setOrderId ( orderId ) ) ; if ( histTasks != null && ! histTasks . isEmpty ( ) ) { HistoryTask histTask = histTasks . get ( 0 ) ; engine . task ( ) . resume ( histTask . getId ( ) , histTask . getOperator ( ) ) ; } return order ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "级联删除指定流程实例的所有数据： 1 . wf_order wf_hist_order 2 . wf_task wf_hist_task 3 . wf_task_actor wf_hist_task_actor 4 . wf_cc_order [CODESPLIT] public void cascadeRemove ( String id ) { HistoryOrder historyOrder = access ( ) . getHistOrder ( id ) ; AssertHelper . notNull ( historyOrder ) ; List < Task > activeTasks = access ( ) . getActiveTasks ( null , new QueryFilter ( ) . setOrderId ( id ) ) ; List < HistoryTask > historyTasks = access ( ) . getHistoryTasks ( null , new QueryFilter ( ) . setOrderId ( id ) ) ; for ( Task task : activeTasks ) { access ( ) . deleteTask ( task ) ; } for ( HistoryTask historyTask : historyTasks ) { access ( ) . deleteHistoryTask ( historyTask ) ; } List < CCOrder > ccOrders = access ( ) . getCCOrder ( id ) ; for ( CCOrder ccOrder : ccOrders ) { access ( ) . deleteCCOrder ( ccOrder ) ; } Order order = access ( ) . getOrder ( id ) ; access ( ) . deleteHistoryOrder ( historyOrder ) ; if ( order != null ) { access ( ) . deleteOrder ( order ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "isORM为false，需要构造map传递给实现类 [CODESPLIT] private Map < String , Object > buildMap ( String sql , Object [ ] args , int [ ] type ) { Map < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( KEY_SQL , sql ) ; map . put ( KEY_ARGS , args ) ; map . put ( KEY_TYPE , type ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "isORM为true，只存放对象传递给orm框架 [CODESPLIT] private Map < String , Object > buildMap ( Object entity , String su ) { Map < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( KEY_ENTITY , entity ) ; map . put ( KEY_SU , su ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取数据库方言 根据数据库连接的DatabaseMetaData获取数据库厂商，自动适配具体的方言 当数据库类型未提供支持时无法自动获取方言，建议通过配置完成 [CODESPLIT] protected Dialect getDialect ( ) { if ( dialect != null ) return dialect ; dialect = ServiceContext . getContext ( ) . find ( Dialect . class ) ; if ( dialect == null ) { try { dialect = JdbcHelper . getDialect ( getConnection ( ) ) ; } catch ( Exception e ) { log . error ( \"Unable to find the available dialect.Please configure dialect to snaker.xml\" ) ; } } return dialect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "由于process中涉及blob字段，未对各种框架统一，所以process操作交给具体的实现类处理 [CODESPLIT] public void saveProcess ( Process process ) { if ( isORM ( ) ) { saveOrUpdate ( buildMap ( process , SAVE ) ) ; } else { Object [ ] args = new Object [ ] { process . getId ( ) , process . getName ( ) , process . getDisplayName ( ) , process . getType ( ) , process . getInstanceUrl ( ) , process . getState ( ) , process . getVersion ( ) , process . getCreateTime ( ) , process . getCreator ( ) } ; int [ ] type = new int [ ] { Types . VARCHAR , Types . VARCHAR , Types . VARCHAR , Types . INTEGER , Types . VARCHAR , Types . INTEGER , Types . INTEGER , Types . VARCHAR , Types . VARCHAR } ; saveOrUpdate ( buildMap ( PROCESS_INSERT , args , type ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "由于process中涉及blob字段，未对各种框架统一，所以process操作交给具体的实现类处理 [CODESPLIT] public void updateProcess ( Process process ) { if ( isORM ( ) ) { saveOrUpdate ( buildMap ( process , UPDATE ) ) ; } else { Object [ ] args = new Object [ ] { process . getName ( ) , process . getDisplayName ( ) , process . getState ( ) , process . getInstanceUrl ( ) , process . getCreateTime ( ) , process . getCreator ( ) , process . getId ( ) } ; int [ ] type = new int [ ] { Types . VARCHAR , Types . VARCHAR , Types . INTEGER , Types . VARCHAR , Types . VARCHAR , Types . VARCHAR , Types . VARCHAR } ; saveOrUpdate ( buildMap ( PROCESS_UPDATE , args , type ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "运行脚本 [CODESPLIT] public void runScript ( ) { String autoStr = ConfigHelper . getProperty ( \"schema.auto\" ) ; if ( autoStr == null || ! autoStr . equalsIgnoreCase ( \"true\" ) ) { return ; } Connection conn = null ; try { conn = getConnection ( ) ; if ( JdbcHelper . isExec ( conn ) ) { log . info ( \"script has completed execution.skip this step\" ) ; return ; } String databaseType = JdbcHelper . getDatabaseType ( conn ) ; String schema = \"db/core/schema-\" + databaseType + \".sql\" ; ScriptRunner runner = new ScriptRunner ( conn , true ) ; runner . runScript ( schema ) ; } catch ( Exception e ) { throw new SnakerException ( e ) ; } finally { try { JdbcHelper . close ( conn ) ; } catch ( SQLException e ) { //ignore } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定类型解析json字符串，并返回该类型的对象 [CODESPLIT] public static < T > T fromJson ( String jsonString , Class < T > clazz ) { if ( StringHelper . isEmpty ( jsonString ) ) { return null ; } try { return mapper . readValue ( jsonString , clazz ) ; } catch ( Exception e ) { log . warn ( \"parse json string error:\" + jsonString , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据key获取配置的字符串value值 [CODESPLIT] public static String getProperty ( String key ) { if ( key == null ) { return null ; } return getProperties ( ) . getProperty ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据key获取配置的数字value值 [CODESPLIT] public static int getNumerProperty ( String key ) { String value = getProperties ( ) . getProperty ( key ) ; if ( NumberUtils . isNumber ( value ) ) { return Integer . parseInt ( value ) ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定的文件名称，从类路径中加载属性文件，构造Properties对象 [CODESPLIT] public static void loadProperties ( String filename ) { InputStream in = null ; ClassLoader threadContextClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; properties = new Properties ( ) ; if ( threadContextClassLoader != null ) { in = threadContextClassLoader . getResourceAsStream ( filename ) ; } if ( in == null ) { in = ConfigHelper . class . getResourceAsStream ( filename ) ; if ( in == null ) { log . warn ( \"No properties file found in the classpath by filename \" + filename ) ; } } else { try { properties . load ( in ) ; log . info ( \"Properties read \" + properties ) ; } catch ( Exception e ) { log . error ( \"Error reading from \" + filename , e ) ; } finally { try { in . close ( ) ; } catch ( IOException e ) { log . warn ( \"IOException while closing InputStream: \" + e . getMessage ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether no more bytes will be returned . [CODESPLIT] protected boolean noMoreCharacters ( ) throws IOException { if ( avail == 0 ) { avail = is . read ( buffer ) ; if ( avail <= 0 ) { avail = 0 ; return true ; } pos = 0 ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a line into the given byte array . [CODESPLIT] public int readLine ( final byte [ ] array , final EnumSet < LineTerminator > terminators ) throws IOException { return readLine ( array , 0 , array . length , terminators ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a line into the given byte - array fragment using { @linkplain #ALL_TERMINATORS all terminators } . [CODESPLIT] public int readLine ( final byte [ ] array , final int off , final int len ) throws IOException { return readLine ( array , off , len , ALL_TERMINATORS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a line into the given byte - array fragment . [CODESPLIT] public int readLine ( final byte [ ] array , final int off , final int len , final EnumSet < LineTerminator > terminators ) throws IOException { ByteArrays . ensureOffsetLength ( array , off , len ) ; if ( len == 0 ) return 0 ; // 0-length reads always return 0 if ( noMoreCharacters ( ) ) return - 1 ; int i , k = 0 , remaining = len , read = 0 ; // The number of bytes still to be read for ( ; ; ) { for ( i = 0 ; i < avail && i < remaining && ( k = buffer [ pos + i ] ) != ' ' && k != ' ' ; i ++ ) ; System . arraycopy ( buffer , pos , array , off + read , i ) ; pos += i ; avail -= i ; read += i ; remaining -= i ; if ( remaining == 0 ) { readBytes += read ; return read ; // We did not stop because of a terminator } if ( avail > 0 ) { // We met a terminator if ( k == ' ' ) { // LF first pos ++ ; avail -- ; if ( terminators . contains ( LineTerminator . LF ) ) { readBytes += read + 1 ; return read ; } else { array [ off + read ++ ] = ' ' ; remaining -- ; } } else if ( k == ' ' ) { // CR first pos ++ ; avail -- ; if ( terminators . contains ( LineTerminator . CR_LF ) ) { if ( avail > 0 ) { if ( buffer [ pos ] == ' ' ) { // CR/LF with LF already in the buffer. pos ++ ; avail -- ; readBytes += read + 2 ; return read ; } } else { // We must search for the LF. if ( noMoreCharacters ( ) ) { // Not found a matching LF because of end of file, will return CR in buffer if not a terminator if ( ! terminators . contains ( LineTerminator . CR ) ) { array [ off + read ++ ] = ' ' ; remaining -- ; readBytes += read ; } else readBytes += read + 1 ; return read ; } if ( buffer [ 0 ] == ' ' ) { // Found matching LF, won't return terminators in the buffer pos ++ ; avail -- ; readBytes += read + 2 ; return read ; } } } if ( terminators . contains ( LineTerminator . CR ) ) { readBytes += read + 1 ; return read ; } array [ off + read ++ ] = ' ' ; remaining -- ; } } else if ( noMoreCharacters ( ) ) { readBytes += read ; return read ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the length of the underlying input stream if it is { @linkplain MeasurableStream measurable } . [CODESPLIT] @ Override public long length ( ) throws IOException { if ( measurableStream != null ) return measurableStream . length ( ) ; if ( fileChannel != null ) return fileChannel . size ( ) ; throw new UnsupportedOperationException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips the given amount of bytes by repeated reads . [CODESPLIT] private long skipByReading ( final long n ) throws IOException { long toSkip = n ; int len ; while ( toSkip > 0 ) { len = is . read ( buffer , 0 , ( int ) Math . min ( buffer . length , toSkip ) ) ; if ( len > 0 ) toSkip -= len ; else break ; } return n - toSkip ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips over and discards the given number of bytes of data from this fast buffered input stream . [CODESPLIT] @ Override public long skip ( final long n ) throws IOException { if ( n <= avail ) { final int m = ( int ) n ; pos += m ; avail -= m ; readBytes += n ; return n ; } long toSkip = n - avail , result = 0 ; avail = 0 ; while ( toSkip != 0 && ( result = is == System . in ? skipByReading ( toSkip ) : is . skip ( toSkip ) ) < toSkip ) { if ( result == 0 ) { if ( is . read ( ) == - 1 ) break ; toSkip -- ; } else toSkip -= result ; } final long t = n - ( toSkip - result ) ; readBytes += t ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that a range given by its first ( inclusive ) and last ( exclusive ) elements fits an array of given length . [CODESPLIT] public static void ensureFromTo ( final int arrayLength , final int from , final int to ) { if ( from < 0 ) throw new ArrayIndexOutOfBoundsException ( \"Start index (\" + from + \") is negative\" ) ; if ( from > to ) throw new IllegalArgumentException ( \"Start index (\" + from + \") is greater than end index (\" + to + \")\" ) ; if ( to > arrayLength ) throw new ArrayIndexOutOfBoundsException ( \"End index (\" + to + \") is greater than array length (\" + arrayLength + \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that a range given by an offset and a length fits an array of given length . [CODESPLIT] public static void ensureOffsetLength ( final int arrayLength , final int offset , final int length ) { if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException ( \"Offset (\" + offset + \") is negative\" ) ; if ( length < 0 ) throw new IllegalArgumentException ( \"Length (\" + length + \") is negative\" ) ; if ( offset + length > arrayLength ) throw new ArrayIndexOutOfBoundsException ( \"Last index (\" + ( offset + length ) + \") is greater than array length (\" + arrayLength + \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms two consecutive sorted ranges into a single sorted range . The initial ranges are { [CODESPLIT] private static void inPlaceMerge ( final int from , int mid , final int to , final IntComparator comp , final Swapper swapper ) { if ( from >= mid || mid >= to ) return ; if ( to - from == 2 ) { if ( comp . compare ( mid , from ) < 0 ) swapper . swap ( from , mid ) ; return ; } int firstCut ; int secondCut ; if ( mid - from > to - mid ) { firstCut = from + ( mid - from ) / 2 ; secondCut = lowerBound ( mid , to , firstCut , comp ) ; } else { secondCut = mid + ( to - mid ) / 2 ; firstCut = upperBound ( from , mid , secondCut , comp ) ; } int first2 = firstCut ; int middle2 = mid ; int last2 = secondCut ; if ( middle2 != first2 && middle2 != last2 ) { int first1 = first2 ; int last1 = middle2 ; while ( first1 < -- last1 ) swapper . swap ( first1 ++ , last1 ) ; first1 = middle2 ; last1 = last2 ; while ( first1 < -- last1 ) swapper . swap ( first1 ++ , last1 ) ; first1 = first2 ; last1 = last2 ; while ( first1 < -- last1 ) swapper . swap ( first1 ++ , last1 ) ; } mid = firstCut + ( secondCut - mid ) ; inPlaceMerge ( from , firstCut , mid , comp , swapper ) ; inPlaceMerge ( mid , secondCut , to , comp , swapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a binary search on an already - sorted range : finds the first position where an element can be inserted without violating the ordering . Sorting is by a user - supplied comparison function . [CODESPLIT] private static int lowerBound ( int from , final int to , final int pos , final IntComparator comp ) { // if (comp==null) throw new NullPointerException(); int len = to - from ; while ( len > 0 ) { int half = len / 2 ; int middle = from + half ; if ( comp . compare ( middle , pos ) < 0 ) { from = middle + 1 ; len -= half + 1 ; } else { len = half ; } } return from ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a binary search on an already sorted range : finds the last position where an element can be inserted without violating the ordering . Sorting is by a user - supplied comparison function . [CODESPLIT] private static int upperBound ( int from , final int mid , final int pos , final IntComparator comp ) { // if (comp==null) throw new NullPointerException(); int len = mid - from ; while ( len > 0 ) { int half = len / 2 ; int middle = from + half ; if ( comp . compare ( pos , middle ) < 0 ) { len = half ; } else { from = middle + 1 ; len -= half + 1 ; } } return from ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the specified range of elements using the specified swapper and according to the order induced by the specified comparator using mergesort . [CODESPLIT] public static void mergeSort ( final int from , final int to , final IntComparator c , final Swapper swapper ) { /*\n\t\t * We retain the same method signature as quickSort. Given only a comparator and swapper we\n\t\t * do not know how to copy and move elements from/to temporary arrays. Hence, in contrast to\n\t\t * the JDK mergesorts this is an \"in-place\" mergesort, i.e. does not allocate any temporary\n\t\t * arrays. A non-inplace mergesort would perhaps be faster in most cases, but would require\n\t\t * non-intuitive delegate objects...\n\t\t */ final int length = to - from ; // Insertion sort on smallest arrays if ( length < MERGESORT_NO_REC ) { for ( int i = from ; i < to ; i ++ ) { for ( int j = i ; j > from && ( c . compare ( j - 1 , j ) > 0 ) ; j -- ) { swapper . swap ( j , j - 1 ) ; } } return ; } // Recursively sort halves int mid = ( from + to ) >>> 1 ; mergeSort ( from , mid , c , swapper ) ; mergeSort ( mid , to , c , swapper ) ; // If list is already sorted, nothing left to do. This is an // optimization that results in faster sorts for nearly ordered lists. if ( c . compare ( mid - 1 , mid ) <= 0 ) return ; // Merge sorted halves inPlaceMerge ( from , mid , to , c , swapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swaps two sequences of elements using a provided swapper . [CODESPLIT] protected static void swap ( final Swapper swapper , int a , int b , final int n ) { for ( int i = 0 ; i < n ; i ++ , a ++ , b ++ ) swapper . swap ( , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the specified range of elements using the specified swapper and according to the order induced by the specified comparator using a parallel quicksort . [CODESPLIT] public static void parallelQuickSort ( final int from , final int to , final IntComparator comp , final Swapper swapper ) { final ForkJoinPool pool = new ForkJoinPool ( Runtime . getRuntime ( ) . availableProcessors ( ) ) ; pool . invoke ( new ForkJoinGenericQuickSort ( from , to , comp , swapper ) ) ; pool . shutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the specified range of elements using the specified swapper and according to the order induced by the specified comparator using parallel quicksort . [CODESPLIT] public static void quickSort ( final int from , final int to , final IntComparator comp , final Swapper swapper ) { final int len = to - from ; // Insertion sort on smallest arrays if ( len < QUICKSORT_NO_REC ) { for ( int i = from ; i < to ; i ++ ) for ( int j = i ; j > from && ( comp . compare ( j - 1 , j ) > 0 ) ; j -- ) { swapper . swap ( j , j - 1 ) ; } return ; } // Choose a partition element, v int m = from + len / 2 ; // Small arrays, middle element int l = from ; int n = to - 1 ; if ( len > QUICKSORT_MEDIAN_OF_9 ) { // Big arrays, pseudomedian of 9 int s = len / 8 ; l = med3 ( l , l + s , l + 2 * s , comp ) ; m = med3 ( m - s , m , m + s , comp ) ; n = med3 ( n - 2 * s , n - s , n , comp ) ; } m = med3 ( l , m , n , comp ) ; // Mid-size, med of 3 // int v = x[m]; int a = from ; int b = a ; int c = to - 1 ; // Establish Invariant: v* (<v)* (>v)* v* int d = c ; while ( true ) { int comparison ; while ( b <= c && ( ( comparison = comp . compare ( b , m ) ) <= 0 ) ) { if ( comparison == 0 ) { // Fix reference to pivot if necessary if ( a == m ) m = b ; else if ( b == m ) m = a ; swapper . swap ( a ++ , b ) ; } b ++ ; } while ( c >= b && ( ( comparison = comp . compare ( c , m ) ) >= 0 ) ) { if ( comparison == 0 ) { // Fix reference to pivot if necessary if ( c == m ) m = d ; else if ( d == m ) m = c ; swapper . swap ( c , d -- ) ; } c -- ; } if ( b > c ) break ; // Fix reference to pivot if necessary if ( b == m ) m = d ; else if ( c == m ) m = c ; swapper . swap ( b ++ , c -- ) ; } // Swap partition elements back to middle int s ; s = Math . min ( a - from , b - a ) ; swap ( swapper , from , b - s , s ) ; s = Math . min ( d - c , to - d - 1 ) ; swap ( swapper , b , to - s , s ) ; // Recursively sort non-partition-elements if ( ( s = b - a ) > 1 ) quickSort ( from , from + s , comp , swapper ) ; if ( ( s = d - c ) > 1 ) quickSort ( to - s , to , comp , swapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Avalanches the bits of an integer by applying the finalisation step of MurmurHash3 . [CODESPLIT] public static int murmurHash3 ( int x ) { x ^= x >>> 16 ; x *= 0x85ebca6b ; x ^= x >>> 13 ; x *= 0xc2b2ae35 ; x ^= x >>> 16 ; return x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Avalanches the bits of a long integer by applying the finalisation step of MurmurHash3 . [CODESPLIT] public static long murmurHash3 ( long x ) { x ^= x >>> 33 ; x *= 0xff51afd7ed558ccd  L ; x ^= x >>> 33 ; x *= 0xc4ceb9fe1a85ec53  L ; x ^= x >>> 33 ; return x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the content of this { [CODESPLIT] public void clear ( ) throws IOException { if ( ! fileChannel . isOpen ( ) ) throw new IOException ( \"This \" + getClass ( ) . getSimpleName ( ) + \" is closed\" ) ; writePosition = position = inspectable = 0 ; mark = - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the content of a specified buffer to the end of the currently represented stream . [CODESPLIT] @ Override public int write ( final ByteBuffer byteBuffer ) throws IOException { ensureOpen ( ) ; final int remaining = byteBuffer . remaining ( ) ; if ( inspectable < buffer . length ) { // Still some space in the inspectable buffer. final int toBuffer = Math . min ( buffer . length - inspectable , remaining ) ; byteBuffer . get ( buffer , inspectable , toBuffer ) ; inspectable += toBuffer ; } if ( byteBuffer . hasRemaining ( ) ) { fileChannel . position ( writePosition ) ; writePosition += fileChannel . write ( byteBuffer ) ; } return remaining ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Truncates the overflow file to a given size if possible . [CODESPLIT] public void truncate ( final long size ) throws FileNotFoundException , IOException { fileChannel . truncate ( Math . max ( size , writePosition ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads bytes from this byte - array input stream as specified in { [CODESPLIT] @ Override public int read ( final byte b [ ] , final int offset , final int length ) { if ( this . length == this . position ) return length == 0 ? 0 : - 1 ; final int n = Math . min ( length , this . length - this . position ) ; System . arraycopy ( array , this . offset + this . position , b , offset , n ) ; this . position += n ; return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repositions the stream . [CODESPLIT] @ Override public void position ( final long newPosition ) throws IOException { flush ( ) ; if ( repositionableStream != null ) repositionableStream . position ( newPosition ) ; else if ( fileChannel != null ) fileChannel . position ( newPosition ) ; else throw new UnsupportedOperationException ( \"position() can only be called if the underlying byte stream implements the RepositionableStream interface or if the getChannel() method of the underlying byte stream exists and returns a FileChannel\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method acquires details of individual transitions that comprise a larger refresh . <p > Details of transitions in a refresh such as count and type can be useful to understand consumer performance and to troubleshoot issues relating to refresh failure . < / p > [CODESPLIT] @ Override public final void transitionsPlanned ( long beforeVersion , long desiredVersion , boolean isSnapshotPlan , List < HollowConsumer . Blob . BlobType > transitionSequence ) { updatePlanDetails . beforeVersion = beforeVersion ; updatePlanDetails . desiredVersion = desiredVersion ; updatePlanDetails . transitionSequence = transitionSequence ; if ( isSnapshotPlan ) { overallRefreshType = BlobType . SNAPSHOT ; } else { overallRefreshType = desiredVersion > beforeVersion ? BlobType . DELTA : BlobType . REVERSE_DELTA ; } refreshMetricsBuilder . setOverallRefreshType ( overallRefreshType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Metrics reporting implementation is provided by the extending subclass . If exceptions are not gracefully handled in the extending subclass then an exception there can fail the consumer refresh even though metrics reporting might not be mission critical . This method protects against that scenario by catching all exceptions logging that there was an exception and continuing with the consumer refresh . [CODESPLIT] private final void noFailRefreshEndMetricsReporting ( ConsumerRefreshMetrics refreshMetrics ) { try { refreshEndMetricsReporting ( refreshMetrics ) ; } catch ( Exception e ) { // Metric reporting is not considered critical to consumer refresh. Log exceptions and continue. log . log ( Level . SEVERE , \"Encountered an exception in reporting consumer refresh metrics, ignoring exception and continuing with consumer refresh\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Await successful completion of all previously submitted tasks . Throw exception of the first failed task if 1 or more tasks failed . [CODESPLIT] public void awaitSuccessfulCompletionOfCurrentTasks ( ) throws InterruptedException , ExecutionException { for ( Future < ? > f : futures ) { f . get ( ) ; } futures . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the building of a { @link HashIndex } . [CODESPLIT] public static < T extends HollowRecord > Builder < T > from ( HollowConsumer consumer , Class < T > rootType ) { Objects . requireNonNull ( consumer ) ; Objects . requireNonNull ( rootType ) ; return new Builder <> ( consumer , rootType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds matches for a given query . [CODESPLIT] public Stream < S > findMatches ( Q query ) { Object [ ] queryArray = matchFields . stream ( ) . map ( mf -> mf . extract ( query ) ) . toArray ( ) ; HollowHashIndexResult matches = hhi . findMatches ( queryArray ) ; if ( matches == null ) { return Stream . empty ( ) ; } return matches . stream ( ) . mapToObj ( i -> selectField . extract ( api , i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a compaction . It is expected that : [CODESPLIT] public void compact ( ) { Set < String > compactionTargets = findCompactionTargets ( ) ; Map < String , BitSet > relocatedOrdinals = new HashMap < String , BitSet > ( ) ; PartialOrdinalRemapper remapper = new PartialOrdinalRemapper ( ) ; for ( String compactionTarget : compactionTargets ) { HollowTypeReadState typeState = readEngine . getTypeState ( compactionTarget ) ; HollowTypeWriteState writeState = writeEngine . getTypeState ( compactionTarget ) ; BitSet populatedOrdinals = typeState . getListener ( PopulatedOrdinalListener . class ) . getPopulatedOrdinals ( ) ; BitSet typeRelocatedOrdinals = new BitSet ( populatedOrdinals . length ( ) ) ; int populatedCardinality = populatedOrdinals . cardinality ( ) ; writeState . addAllObjectsFromPreviousCycle ( ) ; int numRelocations = 0 ; int ordinalToRelocate = populatedOrdinals . nextSetBit ( populatedCardinality ) ; while ( ordinalToRelocate != - 1 ) { numRelocations ++ ; ordinalToRelocate = populatedOrdinals . nextSetBit ( ordinalToRelocate + 1 ) ; } HollowRecordCopier copier = HollowRecordCopier . createCopier ( typeState ) ; IntMap remappedOrdinals = new IntMap ( numRelocations ) ; ordinalToRelocate = populatedOrdinals . length ( ) ; int relocatePosition = - 1 ; try { for ( int i = 0 ; i < numRelocations ; i ++ ) { while ( ! populatedOrdinals . get ( -- ordinalToRelocate ) ) ; relocatePosition = populatedOrdinals . nextClearBit ( relocatePosition + 1 ) ; typeRelocatedOrdinals . set ( ordinalToRelocate ) ; writeState . removeOrdinalFromThisCycle ( ordinalToRelocate ) ; HollowWriteRecord rec = copier . copy ( ordinalToRelocate ) ; writeState . mapOrdinal ( rec , relocatePosition , false , true ) ; remappedOrdinals . put ( ordinalToRelocate , relocatePosition ) ; } } finally { writeState . recalculateFreeOrdinals ( ) ; } remapper . addOrdinalRemapping ( compactionTarget , remappedOrdinals ) ; relocatedOrdinals . put ( compactionTarget , typeRelocatedOrdinals ) ; } /// find the referencing dependents TransitiveSetTraverser . addReferencingOutsideClosure ( readEngine , relocatedOrdinals ) ; /// copy all forward except remapped and transitive dependents of remapped for ( HollowSchema schema : HollowSchemaSorter . dependencyOrderedSchemaList ( writeEngine . getSchemas ( ) ) ) { if ( ! compactionTargets . contains ( schema . getName ( ) ) ) { HollowTypeWriteState writeState = writeEngine . getTypeState ( schema . getName ( ) ) ; writeState . addAllObjectsFromPreviousCycle ( ) ; BitSet typeRelocatedOrdinals = relocatedOrdinals . get ( schema . getName ( ) ) ; if ( typeRelocatedOrdinals != null ) { HollowTypeReadState readState = readEngine . getTypeState ( schema . getName ( ) ) ; IntMap remappedOrdinals = new IntMap ( typeRelocatedOrdinals . cardinality ( ) ) ; boolean preserveHashPositions = shouldPreserveHashPositions ( schema ) ; HollowRecordCopier copier = HollowRecordCopier . createCopier ( readState , remapper , preserveHashPositions ) ; int remapOrdinal = typeRelocatedOrdinals . nextSetBit ( 0 ) ; while ( remapOrdinal != - 1 ) { HollowWriteRecord rec = copier . copy ( remapOrdinal ) ; int newOrdinal = writeState . add ( rec ) ; remappedOrdinals . put ( remapOrdinal , newOrdinal ) ; writeState . removeOrdinalFromThisCycle ( remapOrdinal ) ; remapOrdinal = typeRelocatedOrdinals . nextSetBit ( remapOrdinal + 1 ) ; } remapper . addOrdinalRemapping ( schema . getName ( ) , remappedOrdinals ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find candidate types for compaction . No two types in the returned set will have a dependency relationship either directly or transitively . [CODESPLIT] private Set < String > findCompactionTargets ( ) { List < HollowSchema > schemas = HollowSchemaSorter . dependencyOrderedSchemaList ( readEngine . getSchemas ( ) ) ; Set < String > typesToCompact = new HashSet < String > ( ) ; for ( HollowSchema schema : schemas ) { if ( isCompactionCandidate ( schema . getName ( ) ) ) { if ( ! candidateIsDependentOnAnyTargetedType ( schema . getName ( ) , typesToCompact ) ) typesToCompact . add ( schema . getName ( ) ) ; } } return typesToCompact ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query an index with a single specified field . The returned value with be the ordinal of the matching record . <p > Use a generated API or the Generic Object API to use the returned ordinal . [CODESPLIT] public int getMatchingOrdinal ( Object key ) { PrimaryKeyIndexHashTable hashTable = hashTableVolatile ; if ( fieldPathIndexes . length != 1 || hashTable . bitsPerElement == 0 ) return - 1 ; int hashCode = keyHashCode ( key , 0 ) ; int ordinal = - 1 ; do { hashTable = this . hashTableVolatile ; int bucket = hashCode & hashTable . hashMask ; ordinal = readOrdinal ( hashTable , bucket ) ; while ( ordinal != - 1 ) { if ( keyDeriver . keyMatches ( key , ordinal , 0 ) ) break ; bucket ++ ; bucket &= hashTable . hashMask ; ordinal = readOrdinal ( hashTable , bucket ) ; } } while ( hashTableVolatile != hashTable ) ; return ordinal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query an index with four or more specified fields . The returned value with be the ordinal of the matching record . <p > Use a generated API or the Generic Object API to use the returned ordinal . [CODESPLIT] public int getMatchingOrdinal ( Object ... keys ) { PrimaryKeyIndexHashTable hashTable = hashTableVolatile ; if ( fieldPathIndexes . length != keys . length || hashTable . bitsPerElement == 0 ) return - 1 ; int hashCode = 0 ; for ( int i = 0 ; i < keys . length ; i ++ ) hashCode ^= keyHashCode ( keys [ i ] , i ) ; int ordinal = - 1 ; do { hashTable = this . hashTableVolatile ; int bucket = hashCode & hashTable . hashMask ; ordinal = readOrdinal ( hashTable , bucket ) ; while ( ordinal != - 1 ) { if ( keyDeriver . keyMatches ( ordinal , keys ) ) break ; bucket ++ ; bucket &= hashTable . hashMask ; ordinal = readOrdinal ( hashTable , bucket ) ; } } while ( hashTableVolatile != hashTable ) ; return ordinal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the byte at the given index to the specified value [CODESPLIT] public void set ( long index , long value ) { int segmentIndex = ( int ) ( index >> log2OfSegmentSize ) ; int longInSegment = ( int ) ( index & bitmask ) ; unsafe . putOrderedLong ( segments [ segmentIndex ] , ( long ) Unsafe . ARRAY_LONG_BASE_OFFSET + ( 8 * longInSegment ) , value ) ; /// duplicate the longs here so that we can read faster. if ( longInSegment == 0 && segmentIndex != 0 ) unsafe . putOrderedLong ( segments [ segmentIndex - 1 ] , ( long ) Unsafe . ARRAY_LONG_BASE_OFFSET + ( 8 * ( 1 << log2OfSegmentSize ) ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans snapshot to keep the last n snapshots . Defaults to 5 . [CODESPLIT] @ Override public void cleanSnapshots ( ) { File [ ] files = getFilesByType ( HollowProducer . Blob . Type . SNAPSHOT . prefix ) ; if ( files == null || files . length <= numOfSnapshotsToKeep ) { return ; } sortByLastModified ( files ) ; for ( int i = numOfSnapshotsToKeep ; i < files . length ; i ++ ) { File file = files [ i ] ; boolean deleted = file . delete ( ) ; if ( ! deleted ) { log . warning ( \"Could not delete snapshot \" + file . getPath ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hash a field in an OBJECT record . [CODESPLIT] public static int fieldHashCode ( HollowObjectTypeDataAccess typeAccess , int ordinal , int fieldPosition ) { HollowObjectSchema schema = typeAccess . getSchema ( ) ; switch ( schema . getFieldType ( fieldPosition ) ) { case BOOLEAN : Boolean bool = typeAccess . readBoolean ( ordinal , fieldPosition ) ; return booleanHashCode ( bool ) ; case BYTES : case STRING : return typeAccess . findVarLengthFieldHashCode ( ordinal , fieldPosition ) ; case DOUBLE : double d = typeAccess . readDouble ( ordinal , fieldPosition ) ; return doubleHashCode ( d ) ; case FLOAT : float f = typeAccess . readFloat ( ordinal , fieldPosition ) ; return floatHashCode ( f ) ; case INT : return intHashCode ( typeAccess . readInt ( ordinal , fieldPosition ) ) ; case LONG : long l = typeAccess . readLong ( ordinal , fieldPosition ) ; return longHashCode ( l ) ; case REFERENCE : return typeAccess . readOrdinal ( ordinal , fieldPosition ) ; } throw new IllegalStateException ( \"I don't know how to hash a \" + schema . getFieldType ( fieldPosition ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether two OBJECT field records are exactly equal . [CODESPLIT] public static boolean fieldsAreEqual ( HollowObjectTypeDataAccess typeAccess1 , int ordinal1 , int fieldPosition1 , HollowObjectTypeDataAccess typeAccess2 , int ordinal2 , int fieldPosition2 ) { HollowObjectSchema schema1 = typeAccess1 . getSchema ( ) ; switch ( schema1 . getFieldType ( fieldPosition1 ) ) { case BOOLEAN : Boolean bool1 = typeAccess1 . readBoolean ( ordinal1 , fieldPosition1 ) ; Boolean bool2 = typeAccess2 . readBoolean ( ordinal2 , fieldPosition2 ) ; return bool1 == bool2 ; case BYTES : byte [ ] data1 = typeAccess1 . readBytes ( ordinal1 , fieldPosition1 ) ; byte [ ] data2 = typeAccess2 . readBytes ( ordinal2 , fieldPosition2 ) ; return Arrays . equals ( data1 , data2 ) ; case DOUBLE : double d1 = typeAccess1 . readDouble ( ordinal1 , fieldPosition1 ) ; double d2 = typeAccess2 . readDouble ( ordinal2 , fieldPosition2 ) ; return Double . compare ( d1 , d2 ) == 0 ; case FLOAT : float f1 = typeAccess1 . readFloat ( ordinal1 , fieldPosition1 ) ; float f2 = typeAccess2 . readFloat ( ordinal2 , fieldPosition2 ) ; return Float . compare ( f1 , f2 ) == 0 ; case INT : int i1 = typeAccess1 . readInt ( ordinal1 , fieldPosition1 ) ; int i2 = typeAccess2 . readInt ( ordinal2 , fieldPosition2 ) ; return i1 == i2 ; case LONG : long l1 = typeAccess1 . readLong ( ordinal1 , fieldPosition1 ) ; long l2 = typeAccess2 . readLong ( ordinal2 , fieldPosition2 ) ; return l1 == l2 ; case STRING : String s1 = typeAccess1 . readString ( ordinal1 , fieldPosition1 ) ; return typeAccess2 . isStringFieldEqual ( ordinal2 , fieldPosition2 , s1 ) ; case REFERENCE : if ( typeAccess1 == typeAccess2 && fieldPosition1 == fieldPosition2 ) return typeAccess1 . readOrdinal ( ordinal1 , fieldPosition1 ) == typeAccess2 . readOrdinal ( ordinal2 , fieldPosition2 ) ; default : } throw new IllegalStateException ( \"I don't know how to test equality for a \" + schema1 . getFieldType ( fieldPosition1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Augment the given selection by adding the references and the <i > transitive< / i > references of our selection . [CODESPLIT] public static void addTransitiveMatches ( HollowReadStateEngine stateEngine , Map < String , BitSet > matches ) { List < HollowSchema > schemaList = HollowSchemaSorter . dependencyOrderedSchemaList ( stateEngine ) ; Collections . reverse ( schemaList ) ; for ( HollowSchema schema : schemaList ) { BitSet currentMatches = matches . get ( schema . getName ( ) ) ; if ( currentMatches != null ) { addTransitiveMatches ( stateEngine , schema . getName ( ) , matches ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove any records from the given selection which are referenced by other records not in the selection . [CODESPLIT] public static void removeReferencedOutsideClosure ( HollowReadStateEngine stateEngine , Map < String , BitSet > matches ) { List < HollowSchema > orderedSchemas = HollowSchemaSorter . dependencyOrderedSchemaList ( stateEngine ) ; Collections . reverse ( orderedSchemas ) ; for ( HollowSchema referencedSchema : orderedSchemas ) { if ( matches . containsKey ( referencedSchema . getName ( ) ) ) { for ( HollowSchema referencerSchema : orderedSchemas ) { if ( referencerSchema == referencedSchema ) break ; if ( matches . containsKey ( referencedSchema . getName ( ) ) && matches . get ( referencedSchema . getName ( ) ) . cardinality ( ) > 0 ) traverseReferencesOutsideClosure ( stateEngine , referencerSchema . getName ( ) , referencedSchema . getName ( ) , matches , REMOVE_REFERENCED_OUTSIDE_CLOSURE ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Augment the given selection with any records outside the selection which reference ( or transitively reference ) any records in the selection . [CODESPLIT] public static void addReferencingOutsideClosure ( HollowReadStateEngine stateEngine , Map < String , BitSet > matches ) { List < HollowSchema > orderedSchemas = HollowSchemaSorter . dependencyOrderedSchemaList ( stateEngine ) ; for ( HollowSchema referencerSchema : orderedSchemas ) { for ( HollowSchema referencedSchema : orderedSchemas ) { if ( referencedSchema == referencerSchema ) break ; if ( matches . containsKey ( referencedSchema . getName ( ) ) && matches . get ( referencedSchema . getName ( ) ) . cardinality ( ) > 0 ) traverseReferencesOutsideClosure ( stateEngine , referencerSchema . getName ( ) , referencedSchema . getName ( ) , matches , ADD_REFERENCING_OUTSIDE_CLOSURE ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Note that this method is synchronized and it is the only method that modifies the { [CODESPLIT] public synchronized boolean updateTo ( long requestedVersion ) throws Throwable { if ( requestedVersion == getCurrentVersionId ( ) ) { if ( requestedVersion == HollowConstants . VERSION_NONE && hollowDataHolderVolatile == null ) { LOG . warning ( \"No versions to update to, initializing to empty state\" ) ; // attempting to refresh, but no available versions - initialize to empty state hollowDataHolderVolatile = newHollowDataHolder ( ) ; forceDoubleSnapshotNextUpdate ( ) ; // intentionally ignore doubleSnapshotConfig } return true ; } // Take a snapshot of the listeners to ensure additions or removals may occur concurrently // but will not take effect until a subsequent refresh final HollowConsumer . RefreshListener [ ] localListeners = refreshListeners . toArray ( new HollowConsumer . RefreshListener [ 0 ] ) ; long beforeVersion = getCurrentVersionId ( ) ; for ( HollowConsumer . RefreshListener listener : localListeners ) listener . refreshStarted ( beforeVersion , requestedVersion ) ; try { HollowUpdatePlan updatePlan = shouldCreateSnapshotPlan ( ) ? planner . planInitializingUpdate ( requestedVersion ) : planner . planUpdate ( hollowDataHolderVolatile . getCurrentVersion ( ) , requestedVersion , doubleSnapshotConfig . allowDoubleSnapshot ( ) ) ; for ( HollowConsumer . RefreshListener listener : localListeners ) if ( listener instanceof HollowConsumer . TransitionAwareRefreshListener ) ( ( HollowConsumer . TransitionAwareRefreshListener ) listener ) . transitionsPlanned ( beforeVersion , requestedVersion , updatePlan . isSnapshotPlan ( ) , updatePlan . getTransitionSequence ( ) ) ; if ( updatePlan . destinationVersion ( ) == HollowConstants . VERSION_NONE && requestedVersion != HollowConstants . VERSION_LATEST ) throw new IllegalArgumentException ( String . format ( \"Could not create an update plan for version %s, because that version or any previous versions could not be retrieved.\" , requestedVersion ) ) ; if ( updatePlan . equals ( HollowUpdatePlan . DO_NOTHING ) && requestedVersion == HollowConstants . VERSION_LATEST ) throw new IllegalArgumentException ( \"Could not create an update plan, because no existing versions could be retrieved.\" ) ; if ( updatePlan . destinationVersion ( requestedVersion ) == getCurrentVersionId ( ) ) return true ; if ( updatePlan . isSnapshotPlan ( ) ) { if ( hollowDataHolderVolatile == null || doubleSnapshotConfig . allowDoubleSnapshot ( ) ) { hollowDataHolderVolatile = newHollowDataHolder ( ) ; hollowDataHolderVolatile . update ( updatePlan , localListeners ) ; forceDoubleSnapshot = false ; } } else { hollowDataHolderVolatile . update ( updatePlan , localListeners ) ; } for ( HollowConsumer . RefreshListener refreshListener : localListeners ) refreshListener . refreshSuccessful ( beforeVersion , getCurrentVersionId ( ) , requestedVersion ) ; metrics . updateTypeStateMetrics ( getStateEngine ( ) , requestedVersion ) ; if ( metricsCollector != null ) metricsCollector . collect ( metrics ) ; initialLoad . complete ( getCurrentVersionId ( ) ) ; // only set the first time return getCurrentVersionId ( ) == requestedVersion ; } catch ( Throwable th ) { forceDoubleSnapshotNextUpdate ( ) ; metrics . updateRefreshFailed ( ) ; if ( metricsCollector != null ) metricsCollector . collect ( metrics ) ; for ( HollowConsumer . RefreshListener refreshListener : localListeners ) refreshListener . refreshFailed ( beforeVersion , getCurrentVersionId ( ) , requestedVersion , th ) ; // intentionally omitting a call to initialLoad.completeExceptionally(th), for producers // that write often a consumer has a chance to try another snapshot that might succeed throw th ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports metrics for when cycle is skipped due to reasons such as the producer not being the leader in a multiple - producer setting . In a multiple producer setting leader election typically favors long - lived leaders to avoid producer runs from frequently requiring to reload the full state before publishing data . When a cycle is skipped because the producer wasn t primary the current value of no . of consecutive failures and most recent cycle success time are retained and no cycle status ( success or fail ) is reported . [CODESPLIT] @ Override public void onCycleSkip ( CycleSkipReason reason ) { cycleMetricsBuilder . setConsecutiveFailures ( consecutiveFailures ) ; lastCycleSuccessTimeNanoOptional . ifPresent ( cycleMetricsBuilder :: setLastCycleSuccessTimeNano ) ; // isCycleSuccess and cycleDurationMillis are not set for skipped cycles cycleMetricsBuilder . setConsecutiveFailures ( consecutiveFailures ) ; cycleMetricsReporting ( cycleMetricsBuilder . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports announcement - related metrics . [CODESPLIT] @ Override public void onAnnouncementComplete ( com . netflix . hollow . api . producer . Status status , HollowProducer . ReadState readState , long version , Duration elapsed ) { boolean isAnnouncementSuccess = false ; long dataSizeBytes = 0l ; if ( status . getType ( ) == com . netflix . hollow . api . producer . Status . StatusType . SUCCESS ) { isAnnouncementSuccess = true ; lastAnnouncementSuccessTimeNanoOptional = OptionalLong . of ( System . nanoTime ( ) ) ; } HollowReadStateEngine stateEngine = readState . getStateEngine ( ) ; dataSizeBytes = stateEngine . calcApproxDataSize ( ) ; announcementMetricsBuilder . setDataSizeBytes ( dataSizeBytes ) . setIsAnnouncementSuccess ( isAnnouncementSuccess ) . setAnnouncementDurationMillis ( elapsed . toMillis ( ) ) ; lastAnnouncementSuccessTimeNanoOptional . ifPresent ( announcementMetricsBuilder :: setLastAnnouncementSuccessTimeNano ) ; announcementMetricsReporting ( announcementMetricsBuilder . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On cycle completion this method reports cycle metrics . [CODESPLIT] @ Override public void onCycleComplete ( com . netflix . hollow . api . producer . Status status , HollowProducer . ReadState readState , long version , Duration elapsed ) { boolean isCycleSuccess ; long cycleEndTimeNano = System . nanoTime ( ) ; if ( status . getType ( ) == com . netflix . hollow . api . producer . Status . StatusType . SUCCESS ) { isCycleSuccess = true ; consecutiveFailures = 0l ; lastCycleSuccessTimeNanoOptional = OptionalLong . of ( cycleEndTimeNano ) ; } else { isCycleSuccess = false ; consecutiveFailures ++ ; } cycleMetricsBuilder . setConsecutiveFailures ( consecutiveFailures ) . setCycleDurationMillis ( elapsed . toMillis ( ) ) . setIsCycleSuccess ( isCycleSuccess ) ; lastCycleSuccessTimeNanoOptional . ifPresent ( cycleMetricsBuilder :: setLastCycleSuccessTimeNano ) ; cycleMetricsReporting ( cycleMetricsBuilder . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map of string header tags reading . [CODESPLIT] private Map < String , String > readHeaderTags ( DataInputStream dis ) throws IOException { int numHeaderTags = dis . readShort ( ) ; Map < String , String > headerTags = new HashMap < String , String > ( ) ; for ( int i = 0 ; i < numHeaderTags ; i ++ ) { headerTags . put ( dis . readUTF ( ) , dis . readUTF ( ) ) ; } return headerTags ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified POJO to the state engine . <p > Unless previously initialized with { @link #initializeTypeState ( Class ) } the first time an instance of a particular type is added its schema is derived and added to the data model . [CODESPLIT] public int add ( Object o ) { HollowTypeMapper typeMapper = getTypeMapper ( o . getClass ( ) , null , null ) ; return typeMapper . write ( o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warning : Experimental . the FlatRecord feature is subject to breaking changes . [CODESPLIT] @ Deprecated public void writeFlat ( Object o , FlatRecordWriter flatRecordWriter ) { HollowTypeMapper typeMapper = getTypeMapper ( o . getClass ( ) , null , null ) ; typeMapper . writeFlat ( o , flatRecordWriter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the primary key from the specified POJO . [CODESPLIT] public RecordPrimaryKey extractPrimaryKey ( Object o ) { HollowObjectTypeMapper typeMapper = ( HollowObjectTypeMapper ) getTypeMapper ( o . getClass ( ) , null , null ) ; return new RecordPrimaryKey ( typeMapper . getTypeName ( ) , typeMapper . extractPrimaryKey ( o ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the schema for the specified type in the data model . <p > The schema will be derived from the field and type names in <code > clazz< / code > and added to the state engine s data model ; schemas of types referenced from <code > clazz< / code > will also be added . This can be used to add a type s schema to the state engine without having to add any data for that type . [CODESPLIT] public void initializeTypeState ( Class < ? > clazz ) { Objects . requireNonNull ( clazz ) ; getTypeMapper ( clazz , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear all bits to 0 . [CODESPLIT] public void clearAll ( ) { ThreadSafeBitSetSegments segments = this . segments . get ( ) ; for ( int i = 0 ; i < segments . numSegments ( ) ; i ++ ) { AtomicLongArray segment = segments . getSegment ( i ) ; for ( int j = 0 ; j < segment . length ( ) ; j ++ ) { segment . set ( j , 0L ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new bit set which contains all bits which are contained in this bit set and which are NOT contained in the <code > other< / code > bit set . <p > [CODESPLIT] public ThreadSafeBitSet andNot ( ThreadSafeBitSet other ) { if ( other . log2SegmentSize != log2SegmentSize ) throw new IllegalArgumentException ( \"Segment sizes must be the same\" ) ; ThreadSafeBitSetSegments thisSegments = this . segments . get ( ) ; ThreadSafeBitSetSegments otherSegments = other . segments . get ( ) ; ThreadSafeBitSetSegments newSegments = new ThreadSafeBitSetSegments ( thisSegments . numSegments ( ) , numLongsPerSegment ) ; for ( int i = 0 ; i < thisSegments . numSegments ( ) ; i ++ ) { AtomicLongArray thisArray = thisSegments . getSegment ( i ) ; AtomicLongArray otherArray = ( i < otherSegments . numSegments ( ) ) ? otherSegments . getSegment ( i ) : null ; AtomicLongArray newArray = newSegments . getSegment ( i ) ; for ( int j = 0 ; j < thisArray . length ( ) ; j ++ ) { long thisLong = thisArray . get ( j ) ; long otherLong = ( otherArray == null ) ? 0 : otherArray . get ( j ) ; newArray . set ( j , thisLong & ~ otherLong ) ; } } ThreadSafeBitSet andNot = new ThreadSafeBitSet ( log2SegmentSize ) ; andNot . segments . set ( newSegments ) ; return andNot ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new bit set which contains all bits which are contained in * any * of the specified bit sets . [CODESPLIT] public static ThreadSafeBitSet orAll ( ThreadSafeBitSet ... bitSets ) { if ( bitSets . length == 0 ) return new ThreadSafeBitSet ( ) ; int log2SegmentSize = bitSets [ 0 ] . log2SegmentSize ; int numLongsPerSegment = bitSets [ 0 ] . numLongsPerSegment ; ThreadSafeBitSetSegments segments [ ] = new ThreadSafeBitSetSegments [ bitSets . length ] ; int maxNumSegments = 0 ; for ( int i = 0 ; i < bitSets . length ; i ++ ) { if ( bitSets [ i ] . log2SegmentSize != log2SegmentSize ) throw new IllegalArgumentException ( \"Segment sizes must be the same\" ) ; segments [ i ] = bitSets [ i ] . segments . get ( ) ; if ( segments [ i ] . numSegments ( ) > maxNumSegments ) maxNumSegments = segments [ i ] . numSegments ( ) ; } ThreadSafeBitSetSegments newSegments = new ThreadSafeBitSetSegments ( maxNumSegments , numLongsPerSegment ) ; AtomicLongArray segment [ ] = new AtomicLongArray [ segments . length ] ; for ( int i = 0 ; i < maxNumSegments ; i ++ ) { for ( int j = 0 ; j < segments . length ; j ++ ) { segment [ j ] = i < segments [ j ] . numSegments ( ) ? segments [ j ] . getSegment ( i ) : null ; } AtomicLongArray newSegment = newSegments . getSegment ( i ) ; for ( int j = 0 ; j < numLongsPerSegment ; j ++ ) { long value = 0 ; for ( int k = 0 ; k < segments . length ; k ++ ) { if ( segment [ k ] != null ) value |= segment [ k ] . get ( j ) ; } newSegment . set ( j , value ) ; } } ThreadSafeBitSet or = new ThreadSafeBitSet ( log2SegmentSize ) ; or . segments . set ( newSegments ) ; return or ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the segment at <code > segmentIndex< / code > . If this segment does not yet exist create it . [CODESPLIT] private AtomicLongArray getSegment ( int segmentIndex ) { ThreadSafeBitSetSegments visibleSegments = segments . get ( ) ; while ( visibleSegments . numSegments ( ) <= segmentIndex ) { /// Thread safety:  newVisibleSegments contains all of the segments from the currently visible segments, plus extra. /// all of the segments in the currently visible segments are canonical and will not change. ThreadSafeBitSetSegments newVisibleSegments = new ThreadSafeBitSetSegments ( visibleSegments , segmentIndex + 1 , numLongsPerSegment ) ; /// because we are using a compareAndSet, if this thread \"wins the race\" and successfully sets this variable, then the segments /// which are newly defined in newVisibleSegments become canonical. if ( segments . compareAndSet ( visibleSegments , newVisibleSegments ) ) { visibleSegments = newVisibleSegments ; } else { /// If we \"lose the race\" and are growing the ThreadSafeBitSet segments larger, /// then we will gather the new canonical sets from the update which we missed on the next iteration of this loop. /// Newly defined segments in newVisibleSegments will be discarded, they do not get to become canonical. visibleSegments = segments . get ( ) ; } } return visibleSegments . getSegment ( segmentIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the producer metrics : cycles completed version and type s footprint and ordinals . [CODESPLIT] public void updateCycleMetrics ( HollowProducerListener . ProducerStatus producerStatus ) { Status . StatusType st = producerStatus . getStatus ( ) == HollowProducerListener . Status . SUCCESS ? Status . StatusType . SUCCESS : Status . StatusType . FAIL ; updateCycleMetrics ( new Status ( st , producerStatus . getCause ( ) ) , producerStatus . getReadState ( ) , producerStatus . getVersion ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the producer metrics : cycles completed version and type s footprint and ordinals . [CODESPLIT] public void updateCycleMetrics ( Status status , HollowProducer . ReadState readState , long version ) { cyclesCompleted ++ ; if ( status . getType ( ) == Status . StatusType . FAIL ) { cycleFailed ++ ; return ; } cyclesSucceeded ++ ; if ( readState != null ) { HollowReadStateEngine hollowReadStateEngine = readState . getStateEngine ( ) ; super . update ( hollowReadStateEngine , version ) ; } else { super . update ( version ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : java HollowPOJOGenerator -- argName1 = argValue1 -- argName2 == argValue2 . See { [CODESPLIT] public static void main ( String [ ] args ) throws IOException , ClassNotFoundException { if ( args . length == 0 ) { System . out . println ( \"Usage:\\n\" + \"java \" + HollowPOJOGenerator . class . getName ( ) + \" --arg1=value1 --arg2=value2\\n\" + \"see \" + GeneratorArguments . class . getName ( ) + \" for available arguments.\" ) ; return ; } HollowWriteStateEngine engine = new HollowWriteStateEngine ( ) ; String packageName = null ; String pojoClassNameSuffix = null ; String pathToGeneratedFiles = null ; HollowObjectMapper mapper = new HollowObjectMapper ( engine ) ; ArgumentParser < GeneratorArguments > argumentParser = new ArgumentParser ( GeneratorArguments . class , args ) ; for ( ArgumentParser < GeneratorArguments > . ParsedArgument arg : argumentParser . getParsedArguments ( ) ) { switch ( arg . getKey ( ) ) { case addToDataModel : mapper . initializeTypeState ( HollowPOJOGenerator . class . getClassLoader ( ) . loadClass ( arg . getValue ( ) ) ) ; break ; case addSchemaFileToDataModel : HollowWriteStateCreator . readSchemaFileIntoWriteState ( arg . getValue ( ) , engine ) ; break ; case pathToGeneratedFiles : pathToGeneratedFiles = arg . getValue ( ) ; break ; case packageName : packageName = arg . getValue ( ) ; break ; case pojoClassNameSuffix : pojoClassNameSuffix = arg . getValue ( ) ; break ; default : throw new IllegalArgumentException ( \"Unhandled argument \" + arg . getKey ( ) ) ; } } new HollowPOJOGenerator ( packageName , pojoClassNameSuffix , engine ) . generateFiles ( pathToGeneratedFiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read populated ordinals as a bit set from a stream and notify a listener for each populated ordinal . [CODESPLIT] public static void readOrdinals ( DataInputStream dis , HollowTypeStateListener [ ] listeners ) throws IOException { int numLongs = dis . readInt ( ) ; int currentOrdinal = 0 ; for ( int i = 0 ; i < numLongs ; i ++ ) { long l = dis . readLong ( ) ; notifyPopulatedOrdinals ( l , currentOrdinal , listeners ) ; currentOrdinal += 64 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given value is contained in the set ( or if the given value satisfies the predicate condition . ) [CODESPLIT] public boolean get ( int i ) { SparseBitSet current ; boolean result ; do { current = sparseBitSetVolatile ; result = current . get ( i ) ; } while ( current != sparseBitSetVolatile ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Estimate the total number of bits used to represent the integer set . [CODESPLIT] public long size ( ) { SparseBitSet current ; long size ; do { current = sparseBitSetVolatile ; size = current . estimateBitsUsed ( ) ; } while ( current != sparseBitSetVolatile ) ; return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the state engine using a snapshot blob from the provided InputStream . <p > Apply the provided { @link HollowFilterConfig } to the state . [CODESPLIT] public void readSnapshot ( InputStream is , HollowFilterConfig filter ) throws IOException { HollowBlobHeader header = readHeader ( is , false ) ; notifyBeginUpdate ( ) ; long startTime = System . currentTimeMillis ( ) ; DataInputStream dis = new DataInputStream ( is ) ; int numStates = VarInt . readVInt ( dis ) ; Collection < String > typeNames = new TreeSet < String > ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { String typeName = readTypeStateSnapshot ( dis , header , filter ) ; typeNames . add ( typeName ) ; } stateEngine . wireTypeStatesToSchemas ( ) ; long endTime = System . currentTimeMillis ( ) ; log . info ( \"SNAPSHOT COMPLETED IN \" + ( endTime - startTime ) + \"ms\" ) ; log . info ( \"TYPES: \" + typeNames ) ; notifyEndUpdate ( ) ; stateEngine . afterInitialization ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the state engine using a delta ( or reverse delta ) blob from the provided InputStream . <p > If a { @link HollowFilterConfig } was applied at the time the { @link HollowReadStateEngine } was initialized with a snapshot it will continue to be in effect after the state is updated . [CODESPLIT] public void applyDelta ( InputStream is ) throws IOException { HollowBlobHeader header = readHeader ( is , true ) ; notifyBeginUpdate ( ) ; long startTime = System . currentTimeMillis ( ) ; DataInputStream dis = new DataInputStream ( is ) ; int numStates = VarInt . readVInt ( dis ) ; Collection < String > typeNames = new TreeSet < String > ( ) ; for ( int i = 0 ; i < numStates ; i ++ ) { String typeName = readTypeStateDelta ( dis , header ) ; typeNames . add ( typeName ) ; stateEngine . getMemoryRecycler ( ) . swap ( ) ; } long endTime = System . currentTimeMillis ( ) ; log . info ( \"DELTA COMPLETED IN \" + ( endTime - startTime ) + \"ms\" ) ; log . info ( \"TYPES: \" + typeNames ) ; notifyEndUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String representation of the provided row s field value . If useFrom is true this will use the from value from the pair otherwise this will use the to value . [CODESPLIT] private static String getFieldValue ( HollowDiffViewRow row , boolean useFrom ) { Field field = useFrom ? row . getFieldPair ( ) . getFrom ( ) : row . getFieldPair ( ) . getTo ( ) ; if ( row . getFieldPair ( ) . isLeafNode ( ) ) { return field . getValue ( ) == null ? \"null\" : field . getValue ( ) . toString ( ) . replace ( \"|\" , \"&#x2502\" ) ; } else { String suffix = field . getValue ( ) == null ? \" [null]\" : \"\" ; return \"(\" + field . getTypeName ( ) + \")\" + suffix ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the byte at the given index to the specified value [CODESPLIT] public void set ( long index , byte value ) { int segmentIndex = ( int ) ( index >> log2OfSegmentSize ) ; ensureCapacity ( segmentIndex ) ; segments [ segmentIndex ] [ ( int ) ( index & bitmask ) ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy bytes from another ByteData to this array . [CODESPLIT] public void copy ( ByteData src , long srcPos , long destPos , long length ) { for ( long i = 0 ; i < length ; i ++ ) { set ( destPos ++ , src . get ( srcPos ++ ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copies exactly data . length bytes from this SegmentedByteArray into the provided byte array [CODESPLIT] public int copy ( long srcPos , byte [ ] data , int destPos , int length ) { int segmentSize = 1 << log2OfSegmentSize ; int remainingBytesInSegment = ( int ) ( segmentSize - ( srcPos & bitmask ) ) ; int dataPosition = destPos ; while ( length > 0 ) { byte [ ] segment = segments [ ( int ) ( srcPos >>> log2OfSegmentSize ) ] ; int bytesToCopyFromSegment = Math . min ( remainingBytesInSegment , length ) ; System . arraycopy ( segment , ( int ) ( srcPos & bitmask ) , data , dataPosition , bytesToCopyFromSegment ) ; dataPosition += bytesToCopyFromSegment ; srcPos += bytesToCopyFromSegment ; remainingBytesInSegment = segmentSize - ( int ) ( srcPos & bitmask ) ; length -= bytesToCopyFromSegment ; } return dataPosition - destPos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks equality for a specified range of bytes in two arrays [CODESPLIT] public boolean rangeEquals ( long rangeStart , SegmentedByteArray compareTo , long cmpStart , int length ) { for ( int i = 0 ; i < length ; i ++ ) if ( get ( rangeStart + i ) != compareTo . get ( cmpStart + i ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the data from the provided source array into this array guaranteeing that if the update is seen by another thread then all other writes prior to this call are also visible to that thread . [CODESPLIT] public void orderedCopy ( SegmentedByteArray src , long srcPos , long destPos , long length ) { int segmentLength = 1 << log2OfSegmentSize ; int currentSegment = ( int ) ( destPos >>> log2OfSegmentSize ) ; int segmentStartPos = ( int ) ( destPos & bitmask ) ; int remainingBytesInSegment = segmentLength - segmentStartPos ; while ( length > 0 ) { int bytesToCopyFromSegment = ( int ) Math . min ( remainingBytesInSegment , length ) ; ensureCapacity ( currentSegment ) ; int copiedBytes = src . orderedCopy ( srcPos , segments [ currentSegment ] , segmentStartPos , bytesToCopyFromSegment ) ; srcPos += copiedBytes ; length -= copiedBytes ; segmentStartPos = 0 ; remainingBytesInSegment = segmentLength ; currentSegment ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copies exactly data . length bytes from this SegmentedByteArray into the provided byte array guaranteeing that if the update is seen by another thread then all other writes prior to this call are also visible to that thread . [CODESPLIT] public int orderedCopy ( long srcPos , byte [ ] data , int destPos , int length ) { int segmentSize = 1 << log2OfSegmentSize ; int remainingBytesInSegment = ( int ) ( segmentSize - ( srcPos & bitmask ) ) ; int dataPosition = destPos ; while ( length > 0 ) { byte [ ] segment = segments [ ( int ) ( srcPos >>> log2OfSegmentSize ) ] ; int bytesToCopyFromSegment = Math . min ( remainingBytesInSegment , length ) ; orderedCopy ( segment , ( int ) ( srcPos & bitmask ) , data , dataPosition , bytesToCopyFromSegment ) ; dataPosition += bytesToCopyFromSegment ; srcPos += bytesToCopyFromSegment ; remainingBytesInSegment = segmentSize - ( int ) ( srcPos & bitmask ) ; length -= bytesToCopyFromSegment ; } return dataPosition - destPos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy bytes from the supplied InputStream into this array . [CODESPLIT] public void readFrom ( InputStream is , long length ) throws IOException { int segmentSize = 1 << log2OfSegmentSize ; int segment = 0 ; byte scratch [ ] = new byte [ segmentSize ] ; while ( length > 0 ) { ensureCapacity ( segment ) ; long bytesToCopy = Math . min ( segmentSize , length ) ; long bytesCopied = 0 ; while ( bytesCopied < bytesToCopy ) { bytesCopied += is . read ( scratch , ( int ) bytesCopied , ( int ) ( bytesToCopy - bytesCopied ) ) ; } orderedCopy ( scratch , 0 , segments [ segment ++ ] , 0 , ( int ) bytesCopied ) ; length -= bytesCopied ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a portion of this data to an OutputStream . [CODESPLIT] public void writeTo ( OutputStream os , long startPosition , long len ) throws IOException { int segmentSize = 1 << log2OfSegmentSize ; int remainingBytesInSegment = segmentSize - ( int ) ( startPosition & bitmask ) ; long remainingBytesInCopy = len ; while ( remainingBytesInCopy > 0 ) { long bytesToCopyFromSegment = Math . min ( remainingBytesInSegment , remainingBytesInCopy ) ; os . write ( segments [ ( int ) ( startPosition >>> log2OfSegmentSize ) ] , ( int ) ( startPosition & bitmask ) , ( int ) bytesToCopyFromSegment ) ; startPosition += bytesToCopyFromSegment ; remainingBytesInSegment = segmentSize - ( int ) ( startPosition & bitmask ) ; remainingBytesInCopy -= bytesToCopyFromSegment ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the segment at segmentIndex exists [CODESPLIT] private void ensureCapacity ( int segmentIndex ) { while ( segmentIndex >= segments . length ) { segments = Arrays . copyOf ( segments , segments . length * 3 / 2 ) ; } if ( segments [ segmentIndex ] == null ) { segments [ segmentIndex ] = memoryRecycler . getByteArray ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the position of a field previously added to the map or - 1 if the field has not been added to the map . [CODESPLIT] public int getPosition ( String fieldName ) { Integer index = nameFieldIndexLookup . get ( fieldName ) ; if ( index == null ) { return - 1 ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called after initial pass . Returns the sum total number of select buckets in the low 7 bytes and the bits required for the max set size in the high 1 byte . [CODESPLIT] private long calculateDedupedSizesAndTotalNumberOfSelectBuckets ( MultiLinkedElementArray elementArray , GrowingSegmentedLongArray matchIndexHashAndSizeArray ) { long totalBuckets = 0 ; long maxSize = 0 ; int [ ] selectArray = new int [ 8 ] ; for ( int i = 0 ; i < elementArray . numLists ( ) ; i ++ ) { int listSize = elementArray . listSize ( i ) ; int setSize = 0 ; int predictedBuckets = HashCodes . hashTableSize ( listSize ) ; int hashMask = predictedBuckets - 1 ; if ( predictedBuckets > selectArray . length ) selectArray = new int [ predictedBuckets ] ; for ( int j = 0 ; j < predictedBuckets ; j ++ ) selectArray [ j ] = - 1 ; HollowOrdinalIterator iter = elementArray . iterator ( i ) ; int selectOrdinal = iter . next ( ) ; while ( selectOrdinal != HollowOrdinalIterator . NO_MORE_ORDINALS ) { int hash = HashCodes . hashInt ( selectOrdinal ) ; int bucket = hash & hashMask ; while ( true ) { if ( selectArray [ bucket ] == selectOrdinal ) break ; if ( selectArray [ bucket ] == - 1 ) { selectArray [ bucket ] = selectOrdinal ; setSize ++ ; break ; } bucket = ( bucket + 1 ) & hashMask ; } selectOrdinal = iter . next ( ) ; } long matchIndexHashAndSize = matchIndexHashAndSizeArray . get ( i ) ; matchIndexHashAndSize |= ( long ) setSize << 32 ; matchIndexHashAndSizeArray . set ( i , matchIndexHashAndSize ) ; totalBuckets += HashCodes . hashTableSize ( setSize ) ; if ( setSize > maxSize ) maxSize = setSize ; } return totalBuckets | ( long ) bitsRequiredToRepresentValue ( maxSize ) << 56 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage : java HollowAPIGenerator -- argName1 = argValue1 -- argName2 == argValue2 . See { [CODESPLIT] public static void main ( String [ ] args ) throws IOException , ClassNotFoundException { if ( args . length == 0 ) { System . out . println ( \"Usage:\\n\" + \"java \" + HollowAPIGenerator . class . getName ( ) + \" --arg1=value1 --arg2=value2\\n\" + \"see \" + GeneratorArguments . class . getName ( ) + \" for available arguments.\" ) ; return ; } HollowWriteStateEngine engine = new HollowWriteStateEngine ( ) ; HollowAPIGenerator . Builder builder = new HollowAPIGenerator . Builder ( ) ; HollowObjectMapper mapper = new HollowObjectMapper ( engine ) ; ArgumentParser < GeneratorArguments > argumentParser = new ArgumentParser ( GeneratorArguments . class , args ) ; for ( ArgumentParser < GeneratorArguments > . ParsedArgument arg : argumentParser . getParsedArguments ( ) ) { switch ( arg . getKey ( ) ) { case addToDataModel : mapper . initializeTypeState ( HollowAPIGenerator . class . getClassLoader ( ) . loadClass ( arg . getValue ( ) ) ) ; break ; case addSchemaFileToDataModel : HollowWriteStateCreator . readSchemaFileIntoWriteState ( arg . getValue ( ) , engine ) ; break ; case apiClassName : builder . withAPIClassname ( arg . getValue ( ) ) ; break ; case classPostfix : builder . withClassPostfix ( arg . getValue ( ) ) ; break ; case getterPrefix : builder . withGetterPrefix ( arg . getValue ( ) ) ; break ; case packageName : builder . withPackageName ( arg . getValue ( ) ) ; break ; case pathToGeneratedFiles : builder . withDestination ( arg . getValue ( ) ) ; break ; case parameterizeAllClassNames : builder . withParameterizeAllClassNames ( Boolean . valueOf ( arg . getValue ( ) ) ) ; break ; default : throw new IllegalArgumentException ( \"Unhandled argument \" + arg . getKey ( ) ) ; } } builder . withDataModel ( engine ) . build ( ) . generateSourceFiles ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether DataSet contains any collections schema [CODESPLIT] protected static boolean hasCollectionsInDataSet ( HollowDataset dataset ) { for ( HollowSchema schema : dataset . getSchemas ( ) ) { if ( ( schema instanceof HollowListSchema ) || ( schema instanceof HollowSetSchema ) || ( schema instanceof HollowMapSchema ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate files under the specified directory [CODESPLIT] public void generateFiles ( File directory ) throws IOException { if ( packageName != null && ! packageName . trim ( ) . isEmpty ( ) ) { String packageDir = packageName . replace ( \".\" , File . separator ) ; if ( ! directory . getAbsolutePath ( ) . endsWith ( packageDir ) ) { directory = new File ( directory , packageDir ) ; } } directory . mkdirs ( ) ; HollowAPIClassJavaGenerator apiClassGenerator = new HollowAPIClassJavaGenerator ( packageName , apiClassname , dataset , parameterizeClassNames , config ) ; HollowAPIFactoryJavaGenerator apiFactoryGenerator = new HollowAPIFactoryJavaGenerator ( packageName , apiClassname , dataset , config ) ; HollowHashIndexGenerator hashIndexGenerator = new HollowHashIndexGenerator ( packageName , apiClassname , dataset , config ) ; generateFile ( directory , apiClassGenerator ) ; generateFile ( directory , apiFactoryGenerator ) ; generateFile ( directory , hashIndexGenerator ) ; generateFilesForHollowSchemas ( directory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate files based on dataset schemas under the specified directory [CODESPLIT] protected void generateFilesForHollowSchemas ( File directory ) throws IOException { for ( HollowSchema schema : dataset . getSchemas ( ) ) { String type = schema . getName ( ) ; if ( config . isUseHollowPrimitiveTypes ( ) && HollowCodeGenerationUtils . isPrimitiveType ( type ) ) continue ; // skip if using hollow primitive type generateFile ( directory , getStaticAPIGenerator ( schema ) ) ; generateFile ( directory , getHollowObjectGenerator ( schema ) ) ; generateFile ( directory , getHollowFactoryGenerator ( schema ) ) ; if ( schema . getSchemaType ( ) == SchemaType . OBJECT ) { HollowObjectSchema objSchema = ( HollowObjectSchema ) schema ; generateFile ( directory , new HollowObjectDelegateInterfaceGenerator ( packageName , objSchema , ergonomicShortcuts , dataset , config ) ) ; generateFile ( directory , new HollowObjectDelegateCachedImplGenerator ( packageName , objSchema , ergonomicShortcuts , dataset , config ) ) ; generateFile ( directory , new HollowObjectDelegateLookupImplGenerator ( packageName , objSchema , ergonomicShortcuts , dataset , config ) ) ; generateFile ( directory , new HollowDataAccessorGenerator ( packageName , apiClassname , objSchema , dataset , config ) ) ; if ( ! config . isReservePrimaryKeyIndexForTypeWithPrimaryKey ( ) ) { generateFile ( directory , new LegacyHollowPrimaryKeyIndexGenerator ( packageName , apiClassname , objSchema , dataset , config ) ) ; } else if ( ( objSchema ) . getPrimaryKey ( ) != null ) { generateFile ( directory , new HollowPrimaryKeyIndexGenerator ( dataset , packageName , apiClassname , objSchema , config ) ) ; generateFile ( directory , new HollowUniqueKeyIndexGenerator ( packageName , apiClassname , objSchema , dataset , config ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether or not the specified ordinal contains the provided primary key value . [CODESPLIT] public boolean keyMatches ( int ordinal , Object ... keys ) { if ( keys . length != fieldPathIndexes . length ) return false ; for ( int i = 0 ; i < keys . length ; i ++ ) { if ( ! keyMatches ( keys [ i ] , ordinal , i ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the primary key value for the specified ordinal . [CODESPLIT] public Object [ ] getRecordKey ( int ordinal ) { Object [ ] results = new Object [ fieldPathIndexes . length ] ; for ( int i = 0 ; i < fieldPathIndexes . length ; i ++ ) { results [ i ] = readValue ( ordinal , i ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the data model for the given classes . <p > Data model initialization is required prior to { @link #restore ( long HollowConsumer . BlobRetriever ) restoring } the producer . This ensures that restoration can correctly compare the producer s current data model with the data model of the restored data state and manage any differences in those models ( such as not restoring state for any types in the restoring data model not present in the producer s current data model ) . <p > After initialization a data model initialization event will be emitted to all registered data model initialization listeners { @link com . netflix . hollow . api . producer . listener . DataModelInitializationListener listeners } . [CODESPLIT] public void initializeDataModel ( Class < ? > ... classes ) { Objects . requireNonNull ( classes ) ; if ( classes . length == 0 ) { throw new IllegalArgumentException ( \"classes is empty\" ) ; } long start = currentTimeMillis ( ) ; for ( Class < ? > c : classes ) { objectMapper . initializeTypeState ( c ) ; } listeners . listeners ( ) . fireProducerInit ( currentTimeMillis ( ) - start ) ; isInitialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the producer data model for the given schemas . <p > Data model initialization is required prior to { @link #restore ( long HollowConsumer . BlobRetriever ) restoring } the producer . This ensures that restoration can correctly compare the producer s current data model with the data model of the restored data state and manage any differences in those models ( such as not restoring state for any types in the restoring data model not present in the producer s current data model ) . <p > After initialization a data model initialization event will be emitted to all registered data model initialization listeners { @link com . netflix . hollow . api . producer . listener . DataModelInitializationListener listeners } . [CODESPLIT] public void initializeDataModel ( HollowSchema ... schemas ) { Objects . requireNonNull ( schemas ) ; if ( schemas . length == 0 ) { throw new IllegalArgumentException ( \"classes is empty\" ) ; } long start = currentTimeMillis ( ) ; HollowWriteStateCreator . populateStateEngineWithTypeWriteStates ( getWriteEngine ( ) , Arrays . asList ( schemas ) ) ; listeners . listeners ( ) . fireProducerInit ( currentTimeMillis ( ) - start ) ; isInitialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restores the data state to a desired version . <p > Data model { @link #initializeDataModel ( Class [] ) initialization } is required prior to restoring the producer . This ensures that restoration can correctly compare the producer s current data model with the data model of the restored data state and manage any differences in those models ( such as not restoring state for any types in the restoring data model not present in the producer s current data model ) [CODESPLIT] public HollowProducer . ReadState restore ( long versionDesired , HollowConsumer . BlobRetriever blobRetriever ) { return restore ( versionDesired , blobRetriever , ( restoreFrom , restoreTo ) -> restoreTo . restoreFrom ( restoreFrom ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke this method to alter runCycle behavior . If this Producer is not primary runCycle is a no - op . Note that by default SingleProducerEnforcer is instantiated as BasicSingleProducerEnforcer which is initialized to return true for isPrimary () [CODESPLIT] public boolean enablePrimaryProducer ( boolean doEnable ) { if ( doEnable ) { singleProducerEnforcer . enable ( ) ; } else { singleProducerEnforcer . disable ( ) ; } return ( singleProducerEnforcer . isPrimary ( ) == doEnable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Publish the write state storing the artifacts in the provided object . Visible for testing . [CODESPLIT] void publish ( ListenerSupport . Listeners listeners , long toVersion , Artifacts artifacts ) throws IOException { Status . StageBuilder psb = listeners . firePublishStart ( toVersion ) ; try { artifacts . snapshot = stageBlob ( listeners , blobStager . openSnapshot ( toVersion ) ) ; if ( readStates . hasCurrent ( ) ) { artifacts . delta = stageBlob ( listeners , blobStager . openDelta ( readStates . current ( ) . getVersion ( ) , toVersion ) ) ; artifacts . reverseDelta = stageBlob ( listeners , blobStager . openReverseDelta ( toVersion , readStates . current ( ) . getVersion ( ) ) ) ; publishBlob ( listeners , artifacts . delta ) ; publishBlob ( listeners , artifacts . reverseDelta ) ; if ( -- numStatesUntilNextSnapshot < 0 ) { if ( snapshotPublishExecutor == null ) { publishBlob ( listeners , artifacts . snapshot ) ; artifacts . markSnapshotPublishComplete ( ) ; } else { // Submit the publish blob task to the executor publishSnapshotBlobAsync ( listeners , artifacts ) ; } numStatesUntilNextSnapshot = numStatesBetweenSnapshots ; } else { artifacts . markSnapshotPublishComplete ( ) ; } } else { publishBlob ( listeners , artifacts . snapshot ) ; artifacts . markSnapshotPublishComplete ( ) ; numStatesUntilNextSnapshot = numStatesBetweenSnapshots ; } psb . success ( ) ; } catch ( Throwable throwable ) { psb . fail ( throwable ) ; throw throwable ; } finally { listeners . firePublishComplete ( psb ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given these read states <p > * S ( cur ) at the currently announced version * S ( pnd ) at the pending version <p > Ensure that : <p > S ( cur ) . apply ( forwardDelta ) . checksum == S ( pnd ) . checksum S ( pnd ) . apply ( reverseDelta ) . checksum == S ( cur ) . checksum [CODESPLIT] private ReadStateHelper checkIntegrity ( ListenerSupport . Listeners listeners , ReadStateHelper readStates , Artifacts artifacts ) throws Exception { Status . StageWithStateBuilder status = listeners . fireIntegrityCheckStart ( readStates . pending ( ) ) ; try { ReadStateHelper result = readStates ; HollowReadStateEngine pending = readStates . pending ( ) . getStateEngine ( ) ; readSnapshot ( artifacts . snapshot , pending ) ; if ( readStates . hasCurrent ( ) ) { HollowReadStateEngine current = readStates . current ( ) . getStateEngine ( ) ; log . info ( \"CHECKSUMS\" ) ; HollowChecksum currentChecksum = HollowChecksum . forStateEngineWithCommonSchemas ( current , pending ) ; log . info ( \"  CUR        \" + currentChecksum ) ; HollowChecksum pendingChecksum = HollowChecksum . forStateEngineWithCommonSchemas ( pending , current ) ; log . info ( \"         PND \" + pendingChecksum ) ; if ( artifacts . hasDelta ( ) ) { if ( ! artifacts . hasReverseDelta ( ) ) { throw new IllegalStateException ( \"Both a delta and reverse delta are required\" ) ; } // FIXME: timt: future cycles will fail unless both deltas validate applyDelta ( artifacts . delta , current ) ; HollowChecksum forwardChecksum = HollowChecksum . forStateEngineWithCommonSchemas ( current , pending ) ; //out.format(\"  CUR => PND %s\\n\", forwardChecksum); if ( ! forwardChecksum . equals ( pendingChecksum ) ) { throw new HollowProducer . ChecksumValidationException ( HollowProducer . Blob . Type . DELTA ) ; } applyDelta ( artifacts . reverseDelta , pending ) ; HollowChecksum reverseChecksum = HollowChecksum . forStateEngineWithCommonSchemas ( pending , current ) ; //out.format(\"  CUR <= PND %s\\n\", reverseChecksum); if ( ! reverseChecksum . equals ( currentChecksum ) ) { throw new HollowProducer . ChecksumValidationException ( HollowProducer . Blob . Type . REVERSE_DELTA ) ; } result = readStates . swap ( ) ; } } status . success ( ) ; return result ; } catch ( Throwable th ) { status . fail ( th ) ; throw th ; } finally { listeners . fireIntegrityCheckComplete ( status ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { @link HollowTypeStateListener } to a type . [CODESPLIT] public void addTypeListener ( String typeName , HollowTypeStateListener listener ) { List < HollowTypeStateListener > list = listeners . get ( typeName ) ; if ( list == null ) { list = new ArrayList < HollowTypeStateListener > ( ) ; listeners . put ( typeName , list ) ; } list . add ( listener ) ; HollowTypeReadState typeState = typeStates . get ( typeName ) ; if ( typeState != null ) typeState . addListener ( listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object - based field path given a data set and the field path in symbolic form conforming to paths associated with a primary key . [CODESPLIT] public static FieldPath < ObjectFieldSegment > createFieldPathForPrimaryKey ( HollowDataset dataset , String type , String path ) { boolean autoExpand = ! path . endsWith ( \"!\" ) ; path = autoExpand ? path : path . substring ( 0 , path . length ( ) - 1 ) ; FieldPath < FieldSegment > fp = createFieldPath ( dataset , type , path , autoExpand , false , false ) ; // Erasure trick to avoid copying when it is known the list only contains // instances of ObjectFieldSegment assert fp . segments . stream ( ) . allMatch ( o -> o instanceof ObjectFieldSegment ) ; @ SuppressWarnings ( { \"unchecked\" , \"raw\" } ) FieldPath < ObjectFieldSegment > result = ( FieldPath < ObjectFieldSegment > ) ( FieldPath ) fp ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a field path given a data set and the field path in symbolic form conforming to paths associated with a hash index . [CODESPLIT] public static FieldPath < FieldSegment > createFieldPathForHashIndex ( HollowDataset dataset , String type , String path ) { return createFieldPath ( dataset , type , path , false , false , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a field path given a data set and the field path in symbolic form conforming to paths associated with a prefix index . [CODESPLIT] public static FieldPath < FieldSegment > createFieldPathForPrefixIndex ( HollowDataset dataset , String type , String path , boolean autoExpand ) { // If autoExpand is false then requireFullPath must be true boolean requireFullPath = ! autoExpand ; return createFieldPath ( dataset , type , path , autoExpand , requireFullPath , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a field path given a data set and the field path in symbolic form . [CODESPLIT] static FieldPath < FieldSegment > createFieldPath ( HollowDataset dataset , String type , String path , boolean autoExpand , boolean requireFullPath , boolean traverseSequences ) { Objects . requireNonNull ( dataset ) ; Objects . requireNonNull ( type ) ; Objects . requireNonNull ( path ) ; String [ ] segments = path . isEmpty ( ) ? new String [ 0 ] : path . split ( \"\\\\.\" ) ; List < FieldSegment > fieldSegments = new ArrayList <> ( ) ; String segmentType = type ; for ( int i = 0 ; i < segments . length ; i ++ ) { HollowSchema schema = dataset . getSchema ( segmentType ) ; // @@@ Can this only occur for anything other than the root `type`? if ( schema == null ) { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_BINDABLE , dataset , type , segments , fieldSegments , null , i ) ; } String segment = segments [ i ] ; HollowSchema . SchemaType schemaType = schema . getSchemaType ( ) ; if ( schemaType == HollowSchema . SchemaType . OBJECT ) { HollowObjectSchema objectSchema = ( HollowObjectSchema ) schema ; int index = objectSchema . getPosition ( segment ) ; if ( index == - 1 ) { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_FOUND , dataset , type , segments , fieldSegments , schema , i ) ; } segmentType = objectSchema . getReferencedType ( index ) ; fieldSegments . add ( new ObjectFieldSegment ( objectSchema , segment , segmentType , index ) ) ; } else if ( traverseSequences && ( schemaType == HollowSchema . SchemaType . SET || schemaType == HollowSchema . SchemaType . LIST ) ) { HollowCollectionSchema collectionSchema = ( HollowCollectionSchema ) schema ; if ( ! segment . equals ( \"element\" ) ) { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_FOUND , dataset , type , segments , fieldSegments , schema , i ) ; } segmentType = collectionSchema . getElementType ( ) ; fieldSegments . add ( new FieldSegment ( collectionSchema , segment , segmentType ) ) ; } else if ( traverseSequences && schemaType == HollowSchema . SchemaType . MAP ) { HollowMapSchema mapSchema = ( HollowMapSchema ) schema ; if ( segment . equals ( \"key\" ) ) { segmentType = mapSchema . getKeyType ( ) ; } else if ( segment . equals ( \"value\" ) ) { segmentType = mapSchema . getValueType ( ) ; } else { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_FOUND , dataset , type , segments , fieldSegments , schema , i ) ; } fieldSegments . add ( new FieldSegment ( mapSchema , segment , segmentType ) ) ; } else if ( ! traverseSequences ) { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_TRAVERSABLE , dataset , type , segments , fieldSegments , schema , i ) ; } if ( i < segments . length - 1 && segmentType == null ) { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_TRAVERSABLE , dataset , type , segments , fieldSegments , schema , i ) ; } } if ( autoExpand ) { while ( segmentType != null ) { HollowSchema schema = dataset . getSchema ( segmentType ) ; if ( schema . getSchemaType ( ) == HollowSchema . SchemaType . OBJECT ) { HollowObjectSchema objectSchema = ( HollowObjectSchema ) schema ; if ( objectSchema . numFields ( ) == 1 ) { segmentType = objectSchema . getReferencedType ( 0 ) ; fieldSegments . add ( new ObjectFieldSegment ( objectSchema , objectSchema . getFieldName ( 0 ) , segmentType , 0 ) ) ; } else if ( objectSchema . getPrimaryKey ( ) != null && objectSchema . getPrimaryKey ( ) . numFields ( ) == 1 ) { PrimaryKey key = objectSchema . getPrimaryKey ( ) ; FieldPath < ObjectFieldSegment > expandedFieldSegments ; try { expandedFieldSegments = createFieldPathForPrimaryKey ( dataset , key . getType ( ) , key . getFieldPaths ( ) [ 0 ] ) ; } catch ( FieldPathException cause ) { FieldPathException e = new FieldPathException ( FieldPathException . ErrorKind . NOT_EXPANDABLE , dataset , type , segments , fieldSegments , objectSchema ) ; e . initCause ( cause ) ; throw e ; } fieldSegments . addAll ( expandedFieldSegments . segments ) ; break ; } else { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_EXPANDABLE , dataset , type , segments , fieldSegments , objectSchema ) ; } } else { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_EXPANDABLE , dataset , type , segments , fieldSegments , schema ) ; } } } else if ( requireFullPath && segmentType != null ) { throw new FieldPathException ( FieldPathException . ErrorKind . NOT_FULL , dataset , type , segments , fieldSegments ) ; } return new FieldPath <> ( type , fieldSegments , ! autoExpand ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associating the obj with an ordinal [CODESPLIT] public void put ( Object obj , int ordinal ) { int hashCode = System . identityHashCode ( obj ) ; int segment = segment ( hashCode ) ; segments [ segment ] . put ( obj , hashCode , ordinal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an update plan that if executed will update the client to a version that is either equal to or as close to but less than the desired version as possible . This plan normally contains one snapshot transition and zero or more delta transitions but if no previous versions were found then an empty plan { @code HollowUpdatePlan . DO_NOTHING } is returned . [CODESPLIT] private HollowUpdatePlan snapshotPlan ( long desiredVersion ) { HollowUpdatePlan plan = new HollowUpdatePlan ( ) ; long nearestPreviousSnapshotVersion = includeNearestSnapshot ( plan , desiredVersion ) ; // The includeNearestSnapshot function returns a snapshot version that is less than or equal to the desired version if ( nearestPreviousSnapshotVersion > desiredVersion ) return HollowUpdatePlan . DO_NOTHING ; // If the nearest snapshot version is {@code HollowConstants.VERSION_LATEST} then no past snapshots were found, so // skip the delta planning and the update plan does nothing if ( nearestPreviousSnapshotVersion == HollowConstants . VERSION_LATEST ) return HollowUpdatePlan . DO_NOTHING ; plan . appendPlan ( deltaPlan ( nearestPreviousSnapshotVersion , desiredVersion , Integer . MAX_VALUE ) ) ; return plan ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Includes the next delta only if it will not take us * after * the desired version [CODESPLIT] private long includeNextDelta ( HollowUpdatePlan plan , long currentVersion , long desiredVersion ) { HollowConsumer . Blob transition = transitionCreator . retrieveDeltaBlob ( currentVersion ) ; if ( transition != null ) { if ( transition . getToVersion ( ) <= desiredVersion ) { plan . add ( transition ) ; } return transition . getToVersion ( ) ; } return HollowConstants . VERSION_LATEST ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize field positions and field paths . [CODESPLIT] private void initialize ( ) { String lastRefType = this . fieldPath . getLastRefTypeInPath ( ) ; // get all cardinality to estimate size of array bits needed. totalWords = readStateEngine . getTypeState ( lastRefType ) . getPopulatedOrdinals ( ) . cardinality ( ) ; averageWordLen = 0 ; double avg = 0 ; HollowObjectTypeReadState objectTypeReadState = ( HollowObjectTypeReadState ) readStateEngine . getTypeState ( lastRefType ) ; BitSet keyBitSet = objectTypeReadState . getPopulatedOrdinals ( ) ; int ordinal = keyBitSet . nextSetBit ( 0 ) ; while ( ordinal != - 1 ) { avg += ( ( double ) objectTypeReadState . readString ( ordinal , 0 ) . length ( ) ) / ( ( double ) objectTypeReadState . maxOrdinal ( ) ) ; ordinal = keyBitSet . nextSetBit ( ordinal + 1 ) ; } averageWordLen = ( int ) Math . ceil ( avg ) ; HollowObjectTypeReadState valueState = ( HollowObjectTypeReadState ) readStateEngine . getTypeDataAccess ( type ) ; maxOrdinalOfType = valueState . maxOrdinal ( ) ; // initialize the prefix index. build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the key to index in prefix index . Override this method to support tokens for the key . By default keys are indexed as lower case characters . <pre > { @code String [] keys = super . getKey ( ordinal ) ; String [] tokens = keys [ 0 ] . split ( ) return tokens ; } < / pre > [CODESPLIT] protected String [ ] getKeys ( int ordinal ) { Object [ ] values = fieldPath . findValues ( ordinal ) ; String [ ] stringValues = new String [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) { stringValues [ i ] = ( ( String ) values [ i ] ) . toLowerCase ( ) ; } return stringValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query the index to find all the ordinals that match the given prefix . Example - <pre > { @code HollowOrdinalIterator iterator = index . findKeysWithPrefix ( a ) ; int ordinal = iterator . next () ; while ( ordinal ! = HollowOrdinalIterator . NO_MORE_ORDINAL ) { // print the result using API } } < / pre > <p > For larger data sets querying smaller prefixes will be longer than querying for prefixes that are longer . [CODESPLIT] @ SuppressWarnings ( \"WeakerAccess\" ) public HollowOrdinalIterator findKeysWithPrefix ( String prefix ) { TST current ; HollowOrdinalIterator it ; do { current = prefixIndexVolatile ; it = current . findKeysWithPrefix ( prefix ) ; } while ( current != this . prefixIndexVolatile ) ; return it ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given key exists in the index . [CODESPLIT] public boolean contains ( String key ) { if ( key == null ) throw new IllegalArgumentException ( \"key cannot be null\" ) ; TST current ; boolean result ; do { current = prefixIndexVolatile ; result = current . contains ( key ) ; } while ( current != this . prefixIndexVolatile ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "protected for tests [CODESPLIT] float getChangePercent ( int latestCardinality , int previousCardinality ) { int diff = Math . abs ( latestCardinality - previousCardinality ) ; return ( 100.0f * diff ) / previousCardinality ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a type plus recursively add any directly or transitively referenced types . [CODESPLIT] public void addTypeRecursive ( String type , Collection < HollowSchema > schemas ) { addTypeRecursive ( type , mapSchemas ( schemas ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a type plus recursively add any directly or transitively referenced types . [CODESPLIT] public void addTypeRecursive ( String type , Map < String , HollowSchema > schemas ) { addType ( type ) ; HollowSchema schema = schemas . get ( type ) ; switch ( schema . getSchemaType ( ) ) { case OBJECT : HollowObjectSchema objSchema = ( HollowObjectSchema ) schema ; for ( int i = 0 ; i < objSchema . numFields ( ) ; i ++ ) { if ( objSchema . getFieldType ( i ) == FieldType . REFERENCE ) addTypeRecursive ( objSchema . getReferencedType ( i ) , schemas ) ; } break ; case MAP : addTypeRecursive ( ( ( HollowMapSchema ) schema ) . getKeyType ( ) , schemas ) ; addTypeRecursive ( ( ( HollowMapSchema ) schema ) . getValueType ( ) , schemas ) ; break ; case LIST : case SET : addTypeRecursive ( ( ( HollowCollectionSchema ) schema ) . getElementType ( ) , schemas ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an individual field from an OBJECT schema . This field will be either excluded or included depending on whether this is an exclude or include filter respectively . [CODESPLIT] public void addField ( String type , String objectField ) { ObjectFilterConfig typeConfig = specifiedFieldConfigs . get ( type ) ; if ( typeConfig == null ) { typeConfig = new ObjectFilterConfig ( ) ; specifiedFieldConfigs . put ( type , typeConfig ) ; } typeConfig . addField ( objectField ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an individual field from an OBJECT schema plus recursively add any directly or transitively referenced types . This field will be either excluded or included depending on whether this is an exclude or include filter respectively . [CODESPLIT] public void addFieldRecursive ( String type , String objectField , Collection < HollowSchema > schemas ) { addFieldRecursive ( type , objectField , mapSchemas ( schemas ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an individual field from an OBJECT schema plus recursively add any directly or transitively referenced types . This field will be either excluded or included depending on whether this is an exclude or include filter respectively . [CODESPLIT] public void addFieldRecursive ( String type , String objectField , Map < String , HollowSchema > schemas ) { addField ( type , objectField ) ; HollowObjectSchema schema = ( HollowObjectSchema ) schemas . get ( type ) ; if ( schema . getFieldType ( objectField ) == FieldType . REFERENCE ) { addTypeRecursive ( schema . getReferencedType ( objectField ) , schemas ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a HollowFilterConfig from the specified String . The String should contain multiple lines . The first line should be either EXCLUDE or INCLUDE . Subsequent lines should be one of the following : <ul > <li > &lt ; typeName&gt ; < / li > <li > &lt ; typeName&gt ; . &lt ; fieldName&gt ; < / li > < / ul > [CODESPLIT] public static HollowFilterConfig fromString ( String conf ) { String lines [ ] = conf . split ( \"\\n\" ) ; HollowFilterConfig config = new HollowFilterConfig ( \"EXCLUDE\" . equals ( lines [ 0 ] ) ) ; for ( int i = 1 ; i < lines . length ; i ++ ) { int delimiterIdx = lines [ i ] . indexOf ( ' ' ) ; if ( delimiterIdx == - 1 ) { config . addType ( lines [ i ] ) ; } else { String type = lines [ i ] . substring ( 0 , delimiterIdx ) ; String field = lines [ i ] . substring ( delimiterIdx + 1 ) ; config . addField ( type , field ) ; } } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { [CODESPLIT] public void addListener ( HollowTypeStateListener listener ) { HollowTypeStateListener [ ] newListeners = Arrays . copyOf ( stateListeners , stateListeners . length + 1 ) ; newListeners [ newListeners . length - 1 ] = listener ; stateListeners = newListeners ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a specific { [CODESPLIT] public void removeListener ( HollowTypeStateListener listener ) { if ( stateListeners . length == 0 ) return ; stateListeners = Stream . of ( stateListeners ) . filter ( l -> l != listener ) . toArray ( HollowTypeStateListener [ ] :: new ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dependency types come before dependent types [CODESPLIT] public static List < HollowSchema > dependencyOrderedSchemaList ( Collection < HollowSchema > schemas ) { DependencyIndex idx = new DependencyIndex ( ) ; Map < String , HollowSchema > schemaMap = new HashMap < String , HollowSchema > ( ) ; for ( HollowSchema schema : schemas ) { schemaMap . put ( schema . getName ( ) , schema ) ; idx . indexSchema ( schema , schemas ) ; } List < HollowSchema > orderedSchemas = new ArrayList < HollowSchema > ( ) ; while ( idx . hasMoreTypes ( ) ) orderedSchemas . add ( schemaMap . get ( idx . getNextType ( ) ) ) ; return orderedSchemas ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make it easier to automatically use defaults for next major version [CODESPLIT] public void initWithNextMajorVersionDefaults_V3 ( ) { usePackageGrouping = true ; useBooleanFieldErgonomics = true ; reservePrimaryKeyIndexForTypeWithPrimaryKey = true ; useHollowPrimitiveTypes = true ; restrictApiToFieldType = true ; useVerboseToString = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the byte at the given index to the specified value [CODESPLIT] public void set ( long index , long value ) { int segmentIndex = ( int ) ( index >> log2OfSegmentSize ) ; if ( segmentIndex >= segments . length ) { int nextPowerOfTwo = 1 << ( 32 - Integer . numberOfLeadingZeros ( segmentIndex ) ) ; segments = Arrays . copyOf ( segments , nextPowerOfTwo ) ; } if ( segments [ segmentIndex ] == null ) { segments [ segmentIndex ] = memoryRecycler . getLongArray ( ) ; } int longInSegment = ( int ) ( index & bitmask ) ; segments [ segmentIndex ] [ longInSegment ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of the byte at the specified index . [CODESPLIT] public long get ( long index ) { int segmentIndex = ( int ) ( index >> log2OfSegmentSize ) ; if ( segmentIndex >= segments . length || segments [ segmentIndex ] == null ) return 0 ; int longInSegment = ( int ) ( index & bitmask ) ; return segments [ segmentIndex ] [ longInSegment ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match any records which include a field with the provided fieldName and value . [CODESPLIT] public Map < String , BitSet > findMatchingRecords ( String fieldName , String fieldValue ) { Map < String , BitSet > matches = new HashMap < String , BitSet > ( ) ; for ( HollowTypeReadState typeState : readEngine . getTypeStates ( ) ) { augmentMatchingRecords ( typeState , fieldName , fieldValue , matches ) ; } return matches ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match any records of the specified type which have the specified field set to the specified value . [CODESPLIT] public Map < String , BitSet > findMatchingRecords ( String typeName , String fieldName , String fieldValue ) { Map < String , BitSet > matches = new HashMap < String , BitSet > ( ) ; HollowTypeReadState typeState = readEngine . getTypeState ( typeName ) ; if ( typeState != null ) augmentMatchingRecords ( typeState , fieldName , fieldValue , matches ) ; return matches ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the paths for which we will inspect differences across the two states [CODESPLIT] public void setElementMatchPaths ( String ... paths ) { resetResults ( ) ; this . elementPaths = paths ; this . elementKeyPaths = null ; this . elementNonKeyPaths = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Optionally specify paths for which we will match records within an individual type s hierarchy [CODESPLIT] public void setElementKeyPaths ( String ... paths ) { resetResults ( ) ; elementKeyPaths = new BitSet ( elementPaths . length ) ; for ( int i = 0 ; i < paths . length ; i ++ ) { int elementPathIdx = getElementPathIdx ( paths [ i ] ) ; if ( elementPathIdx == - 1 ) throw new IllegalArgumentException ( \"Key path must have been specified as an element match path.  Offending path: \" + paths [ i ] ) ; elementKeyPaths . set ( elementPathIdx ) ; } elementNonKeyPaths = new BitSet ( elementPaths . length ) ; elementNonKeyPaths . set ( 0 , elementPaths . length ) ; elementNonKeyPaths . andNot ( elementKeyPaths ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the differences [CODESPLIT] public void calculate ( ) { resetResults ( ) ; SimultaneousExecutor executor = new SimultaneousExecutor ( getClass ( ) , \"calculate\" ) ; final int numThreads = executor . getCorePoolSize ( ) ; for ( int i = 0 ; i < numThreads ; i ++ ) { final int threadNumber = i ; executor . execute ( new Runnable ( ) { public void run ( ) { HollowIndexerValueTraverser fromTraverser = new HollowIndexerValueTraverser ( from , type , elementPaths ) ; HollowIndexerValueTraverser toTraverser = new HollowIndexerValueTraverser ( to , type , elementPaths ) ; int hashedResults [ ] = new int [ 16 ] ; for ( int i = threadNumber ; i < matcher . getMatchedOrdinals ( ) . size ( ) ; i += numThreads ) { long ordinalPair = matcher . getMatchedOrdinals ( ) . get ( i ) ; int fromOrdinal = ( int ) ( ordinalPair >>> 32 ) ; int toOrdinal = ( int ) ordinalPair ; fromTraverser . traverse ( fromOrdinal ) ; toTraverser . traverse ( toOrdinal ) ; if ( fromTraverser . getNumMatches ( ) * 2 > hashedResults . length ) hashedResults = new int [ hashTableSize ( fromTraverser . getNumMatches ( ) ) ] ; populateHashTable ( fromTraverser , hashedResults ) ; countMatches ( fromTraverser , toTraverser , hashedResults ) ; } for ( int i = threadNumber ; i < matcher . getExtraInFrom ( ) . size ( ) ; i += numThreads ) { fromTraverser . traverse ( matcher . getExtraInFrom ( ) . get ( i ) ) ; totalUnmatchedFromElements . addAndGet ( fromTraverser . getNumMatches ( ) ) ; } for ( int i = threadNumber ; i < matcher . getExtraInTo ( ) . size ( ) ; i += numThreads ) { toTraverser . traverse ( matcher . getExtraInTo ( ) . get ( i ) ) ; totalUnmatchedToElements . addAndGet ( toTraverser . getNumMatches ( ) ) ; } } } ) ; } try { executor . awaitSuccessfulCompletion ( ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should be called exclusively from the { @link HollowDiff } -- not intended for external consumption [CODESPLIT] public void addDiff ( int fromOrdinal , int toOrdinal , int score ) { if ( isSameDiffAsLastAdd ( fromOrdinal , toOrdinal ) ) { int scoreIdx = diffPairScores . size ( ) - 1 ; diffPairScores . set ( scoreIdx , diffPairScores . get ( scoreIdx ) + score ) ; } else { diffFromOrdinals . add ( fromOrdinal ) ; diffToOrdinals . add ( toOrdinal ) ; diffPairScores . add ( score ) ; } totalDiffScore += score ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This should be called exclusively from the { [CODESPLIT] public void addResults ( HollowFieldDiff otherFieldDiff ) { for ( int i = 0 ; i < otherFieldDiff . getNumDiffs ( ) ; i ++ ) { addDiff ( otherFieldDiff . getFromOrdinal ( i ) , otherFieldDiff . getToOrdinal ( i ) , otherFieldDiff . getPairScore ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comparison is based on the totalDiffScore () . [CODESPLIT] @ Override public int compareTo ( HollowFieldDiff o ) { if ( o . getTotalDiffScore ( ) > totalDiffScore ) return 1 ; else if ( o . getTotalDiffScore ( ) < totalDiffScore ) return - 1 ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a refresh to the latest version specified by the { [CODESPLIT] public void triggerRefresh ( ) { refreshLock . writeLock ( ) . lock ( ) ; try { updater . updateTo ( announcementWatcher == null ? Long . MAX_VALUE : announcementWatcher . getLatestVersion ( ) ) ; } catch ( Error | RuntimeException e ) { throw e ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } finally { refreshLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers async refresh after the specified number of milliseconds has passed . <p > Any subsequent calls for async refresh will not begin until after the specified delay has completed . [CODESPLIT] public void triggerAsyncRefreshWithDelay ( int delayMillis ) { final long targetBeginTime = System . currentTimeMillis ( ) + delayMillis ; refreshExecutor . execute ( ( ) -> { try { long delay = targetBeginTime - System . currentTimeMillis ( ) ; if ( delay > 0 ) Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { // Interrupting, such as shutting down the executor pool, // cancels the trigger LOG . log ( Level . INFO , \"Async refresh interrupted before trigger, refresh cancelled\" , e ) ; return ; } try { triggerRefresh ( ) ; } catch ( Error | RuntimeException e ) { // Ensure exceptions are propagated to the executor LOG . log ( Level . SEVERE , \"Async refresh failed\" , e ) ; throw e ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a { @link HollowConsumer . AnnouncementWatcher } is not specified then this method will attempt to update to the specified version and if the specified version does not exist then to a different version as specified by functionality in the { @code BlobRetriever } . <p > Otherwise an UnsupportedOperationException will be thrown . <p > This is a blocking call . [CODESPLIT] public void triggerRefreshTo ( long version ) { if ( announcementWatcher != null ) throw new UnsupportedOperationException ( \"Cannot trigger refresh to specified version when a HollowConsumer.AnnouncementWatcher is present\" ) ; try { updater . updateTo ( version ) ; } catch ( Error | RuntimeException e ) { throw e ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Equivalent to calling { @link #getAPI () } and casting to the specified API . [CODESPLIT] public < T extends HollowAPI > T getAPI ( Class < T > apiClass ) { return apiClass . cast ( updater . getAPI ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the provided { @link HollowReadStateEngine } with the dataset currently in the provided { @link HollowWriteStateEngine } [CODESPLIT] public static void roundTripSnapshot ( HollowWriteStateEngine writeEngine , HollowReadStateEngine readEngine ) throws IOException { roundTripSnapshot ( writeEngine , readEngine , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the provided { @link HollowReadStateEngine } with the dataset currently in the provided { @link HollowWriteStateEngine } . <p > Apply the provided { @link HollowFilterConfig } . [CODESPLIT] public static void roundTripSnapshot ( HollowWriteStateEngine writeEngine , HollowReadStateEngine readEngine , HollowFilterConfig filter ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; HollowBlobWriter writer = new HollowBlobWriter ( writeEngine ) ; writer . writeSnapshot ( baos ) ; writeEngine . prepareForNextCycle ( ) ; HollowBlobReader reader = new HollowBlobReader ( readEngine ) ; InputStream is = new ByteArrayInputStream ( baos . toByteArray ( ) ) ; if ( filter == null ) reader . readSnapshot ( is ) ; else reader . readSnapshot ( is , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the provided { @link HollowReadStateEngine } with the new state currently available in the { @link HollowWriteStateEngine } . <p > It is assumed that the readEngine is currently populated with the prior state from the writeEngine . [CODESPLIT] public static void roundTripDelta ( HollowWriteStateEngine writeEngine , HollowReadStateEngine readEngine ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; HollowBlobWriter writer = new HollowBlobWriter ( writeEngine ) ; writer . writeDelta ( baos ) ; HollowBlobReader reader = new HollowBlobReader ( readEngine ) ; reader . applyDelta ( new ByteArrayInputStream ( baos . toByteArray ( ) ) ) ; writeEngine . prepareForNextCycle ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link HollowDataAccess } for the prior state of the supplied { @link HollowReadStateEngine } after a delta has been applied . [CODESPLIT] public HollowHistoricalStateDataAccess createBasedOnNewDelta ( long version , HollowReadStateEngine stateEngine ) { IntMapOrdinalRemapper typeRemovedOrdinalMapping = new IntMapOrdinalRemapper ( ) ; List < HollowTypeReadState > historicalTypeStates = new ArrayList < HollowTypeReadState > ( stateEngine . getTypeStates ( ) . size ( ) ) ; for ( HollowTypeReadState typeState : stateEngine . getTypeStates ( ) ) { createDeltaHistoricalTypeState ( typeRemovedOrdinalMapping , historicalTypeStates , typeState ) ; } HollowHistoricalStateDataAccess dataAccess = new HollowHistoricalStateDataAccess ( totalHistory , version , stateEngine , historicalTypeStates , typeRemovedOrdinalMapping , Collections . < String , HollowHistoricalSchemaChange > emptyMap ( ) ) ; dataAccess . setNextState ( stateEngine ) ; return dataAccess ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link HollowDataAccess } for a { @link HollowHistory } . Remap ordinal spaces for all prior historical versions in the { @link HollowHistory } for consistency . [CODESPLIT] public HollowHistoricalStateDataAccess createConsistentOrdinalHistoricalStateFromDoubleSnapshot ( long version , HollowReadStateEngine previous ) { return new HollowHistoricalStateDataAccess ( totalHistory , version , previous , IdentityOrdinalRemapper . INSTANCE , Collections . < String , HollowHistoricalSchemaChange > emptyMap ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link HollowDataAccess } for a historical state after a double snapshot occurs without a { @link HollowHistory } . [CODESPLIT] public HollowHistoricalStateDataAccess createHistoricalStateFromDoubleSnapshot ( long version , HollowReadStateEngine previous , HollowReadStateEngine current , DiffEqualityMappingOrdinalRemapper ordinalRemapper ) { HollowWriteStateEngine writeEngine = HollowWriteStateCreator . createWithSchemas ( schemasWithoutKeys ( previous . getSchemas ( ) ) ) ; IntMapOrdinalRemapper typeRemovedOrdinalLookupMaps = new IntMapOrdinalRemapper ( ) ; for ( HollowSchema previousSchema : HollowSchemaSorter . dependencyOrderedSchemaList ( previous ) ) { HollowTypeReadState previousTypeState = previous . getTypeState ( previousSchema . getName ( ) ) ; String typeName = previousTypeState . getSchema ( ) . getName ( ) ; IntMap ordinalLookupMap ; if ( current . getTypeState ( typeName ) == null ) { ordinalLookupMap = copyAllRecords ( previousTypeState , ordinalRemapper , writeEngine ) ; } else { HollowTypeReadState currentTypeState = current . getTypeState ( typeName ) ; BitSet currentlyPopulatedOrdinals = currentTypeState . getListener ( PopulatedOrdinalListener . class ) . getPopulatedOrdinals ( ) ; ordinalLookupMap = copyUnmatchedRecords ( previousTypeState , ordinalRemapper , currentlyPopulatedOrdinals , writeEngine ) ; } typeRemovedOrdinalLookupMaps . addOrdinalRemapping ( typeName , ordinalLookupMap ) ; } Map < String , HollowHistoricalSchemaChange > schemaChanges = calculateSchemaChanges ( previous , current , ordinalRemapper . getDiffEqualityMapping ( ) ) ; return new HollowHistoricalStateDataAccess ( totalHistory , version , roundTripStateEngine ( writeEngine ) , typeRemovedOrdinalLookupMaps , schemaChanges ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the data model and restores from existing state . [CODESPLIT] public void restoreFromLastState ( ) { producer . initializeDataModel ( dataModel ) ; long latestAnnouncedVersion = announcementWatcher . getLatestVersion ( ) ; if ( latestAnnouncedVersion == HollowFilesystemAnnouncementWatcher . NO_ANNOUNCEMENT_AVAILABLE || latestAnnouncedVersion < 0 ) { return ; } restore ( latestAnnouncedVersion , blobRetriever ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a Hollow Cycle if successful cleans the mutations map . [CODESPLIT] public long runCycle ( ) { long recordsRemoved = countRecordsToRemove ( ) ; long recordsAddedOrModified = this . mutations . values ( ) . size ( ) - recordsRemoved ; try { long version = producer . runCycle ( populator ) ; if ( version == lastSucessfulCycle ) { return version ; } listeners . fireIncrementalCycleComplete ( version , recordsAddedOrModified , recordsRemoved , new HashMap < String , Object > ( cycleMetadata ) ) ; //Only clean changes when the version is new. clearChanges ( ) ; lastSucessfulCycle = version ; return version ; } catch ( Exception e ) { listeners . fireIncrementalCycleFail ( e , recordsAddedOrModified , recordsRemoved , new HashMap < String , Object > ( cycleMetadata ) ) ; return FAILED_VERSION ; } finally { clearCycleMetadata ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parallel execution . Modifies the mutation ConcurrentHashMap in parallel based on a Callback . <p > Note : This could be replaced with Java 8 parallelStream and lambadas instead of Callback interface < / p > [CODESPLIT] private void executeInParallel ( Collection < Object > objList , String description , final Callback callback ) { SimultaneousExecutor executor = new SimultaneousExecutor ( threadsPerCpu , getClass ( ) , description ) ; for ( final Object obj : objList ) { executor . execute ( ( ) -> callback . call ( obj ) ) ; } try { executor . awaitSuccessfulCompletion ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exclude the record which matches the specified key . [CODESPLIT] public void excludeKey ( HollowPrimaryKeyIndex idx , Object ... key ) { int excludeOrdinal = idx . getMatchingOrdinal ( key ) ; if ( excludeOrdinal >= 0 ) { BitSet excludedOrdinals = this . excludedOrdinals . get ( idx . getTypeState ( ) ) ; if ( excludedOrdinals == null ) { excludedOrdinals = new BitSet ( idx . getTypeState ( ) . maxOrdinal ( ) + 1 ) ; this . excludedOrdinals . put ( idx . getTypeState ( ) , excludedOrdinals ) ; } excludedOrdinals . set ( excludeOrdinal ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exclude any objects which are referenced by excluded objects . [CODESPLIT] public void excludeReferencedObjects ( ) { Set < HollowReadStateEngine > stateEngines = new HashSet < HollowReadStateEngine > ( ) ; for ( Map . Entry < HollowTypeReadState , BitSet > entry : excludedOrdinals . entrySet ( ) ) stateEngines . ( entry . getKey ( ) . getStateEngine ( ) ) ; for ( HollowReadStateEngine stateEngine : stateEngines ) { Map < String , BitSet > typeBitSetsForStateEngine = new HashMap < String , BitSet > ( ) ; for ( Map . Entry < HollowTypeReadState , BitSet > entry : excludedOrdinals . entrySet ( ) ) { if ( entry . getKey ( ) . getStateEngine ( ) == stateEngine ) { String type = entry . getKey ( ) . getSchema ( ) . getName ( ) ; typeBitSetsForStateEngine . put ( type , BitSet . valueOf ( entry . getValue ( ) . toLongArray ( ) ) ) ; } } TransitiveSetTraverser . addTransitiveMatches ( stateEngine , typeBitSetsForStateEngine ) ; for ( Map . Entry < String , BitSet > entry : typeBitSetsForStateEngine . entrySet ( ) ) excludedOrdinals . put ( stateEngine . getTypeState ( entry . getKey ( ) ) , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the header to the data output stream [CODESPLIT] public void writeHeader ( HollowBlobHeader header , DataOutputStream dos ) throws IOException { /// save 4 bytes to indicate FastBlob version header.  This will be changed to indicate backwards incompatibility. dos . writeInt ( HollowBlobHeader . HOLLOW_BLOB_VERSION_HEADER ) ; /// Write randomized tag data -- every state gets a random 64-bit tag. /// When attempting to apply a delta, the originating state's random 64-bit tag is compared against the current 64-bit tag. /// This prevents deltas from being applied to incorrect states. dos . writeLong ( header . getOriginRandomizedTag ( ) ) ; dos . writeLong ( header . getDestinationRandomizedTag ( ) ) ; /// write the schemas contained in this blob to the stream in the pre v2.2.0 backwards compatibility envelope ByteArrayOutputStream schemasStream = new ByteArrayOutputStream ( ) ; VarInt . writeVInt ( schemasStream , header . getSchemas ( ) . size ( ) ) ; for ( HollowSchema schema : header . getSchemas ( ) ) schema . writeTo ( schemasStream ) ; byte [ ] schemasData = schemasStream . toByteArray ( ) ; VarInt . writeVInt ( dos , schemasData . length + 1 ) ; // plus one byte for new backwards compatibility envelope. dos . write ( schemasData ) ; ///backwards compatibility -- new data can be added here by first indicating number of bytes used, will be skipped by existing readers. VarInt . writeVInt ( dos , 0 ) ; /// write the header tags -- intended to include input source data versions dos . writeShort ( header . getHeaderTags ( ) . size ( ) ) ; for ( Map . Entry < String , String > headerTag : header . getHeaderTags ( ) . entrySet ( ) ) { dos . writeUTF ( headerTag . getKey ( ) ) ; dos . writeUTF ( headerTag . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warning : Not thread - safe . Should only be called within the update thread . [CODESPLIT] public int bitsRequiredForField ( String fieldName ) { int fieldIndex = schema . getPosition ( fieldName ) ; return fieldIndex == - 1 ? 0 : currentDataVolatile . bitsPerField [ fieldIndex ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the memory heap footprint and populated ordinals per type and total [CODESPLIT] void calculateTypeMetrics ( HollowReadStateEngine hollowReadStateEngine ) { Collection < HollowTypeReadState > typeStates = hollowReadStateEngine . getTypeStates ( ) ; if ( typeStates == null ) return ; totalHeapFootprint = 0L ; totalPopulatedOrdinals = 0 ; for ( HollowTypeReadState typeState : typeStates ) { long heapCost = typeState . getApproximateHeapFootprintInBytes ( ) ; totalHeapFootprint += heapCost ; int populatedOrdinals = typeState . getPopulatedOrdinals ( ) . cardinality ( ) ; totalPopulatedOrdinals += populatedOrdinals ; String type = typeState . getSchema ( ) . getName ( ) ; typeHeapFootprint . put ( type , heapCost ) ; typePopulatedOrdinals . put ( type , populatedOrdinals ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When provided a set of { @link PrimaryKey } will ensure that no duplicate records are added to the destination state . [CODESPLIT] public void setPrimaryKeys ( PrimaryKey ... newKeys ) { Objects . requireNonNull ( newKeys ) ; if ( newKeys . length == 0 ) { return ; } if ( inputs . length == 1 ) { return ; } /// deduplicate new keys with existing keys //process existing ones first Map < String , PrimaryKey > keysByType = new HashMap <> ( ) ; for ( PrimaryKey primaryKey : primaryKeys ) { keysByType . put ( primaryKey . getType ( ) , primaryKey ) ; } // allow override for ( PrimaryKey primaryKey : newKeys ) { keysByType . put ( primaryKey . getType ( ) , primaryKey ) ; } this . primaryKeys = sortPrimaryKeys ( new ArrayList <> ( keysByType . values ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the combine operation . [CODESPLIT] public void combine ( ) { SimultaneousExecutor executor = new SimultaneousExecutor ( getClass ( ) , \"combine\" ) ; final int numThreads = executor . getCorePoolSize ( ) ; createOrdinalRemappers ( ) ; createHashOrderIndependentOrdinalMaps ( ) ; final Set < String > processedTypes = new HashSet <> ( ) ; final Set < PrimaryKey > processedPrimaryKeys = new HashSet <> ( ) ; final Set < PrimaryKey > selectedPrimaryKeys = new HashSet <> ( ) ; while ( processedTypes . size ( ) < output . getOrderedTypeStates ( ) . size ( ) ) { /// find the next primary keys for ( PrimaryKey key : primaryKeys ) { if ( ! processedPrimaryKeys . contains ( key ) && ! ignoredTypes . contains ( key . getType ( ) ) ) { if ( ! isAnySelectedPrimaryKeyADependencyOf ( key . getType ( ) , selectedPrimaryKeys ) ) { selectedPrimaryKeys . add ( key ) ; } } } final Set < String > typesToProcessThisIteration = new HashSet <> ( ) ; final Map < String , HollowPrimaryKeyIndex [ ] > primaryKeyIndexes = new HashMap <> ( ) ; final HollowCombinerExcludePrimaryKeysCopyDirector primaryKeyCopyDirector = new HollowCombinerExcludePrimaryKeysCopyDirector ( copyDirector ) ; for ( HollowSchema schema : output . getSchemas ( ) ) { if ( ! processedTypes . contains ( schema . getName ( ) ) && ! ignoredTypes . contains ( schema . getName ( ) ) ) { if ( selectedPrimaryKeys . isEmpty ( ) || isAnySelectedPrimaryKeyDependentOn ( schema . getName ( ) , selectedPrimaryKeys ) ) { for ( PrimaryKey pk : selectedPrimaryKeys ) { if ( pk . getType ( ) . equals ( schema . getName ( ) ) ) { HollowPrimaryKeyIndex [ ] indexes = new HollowPrimaryKeyIndex [ inputs . length ] ; for ( int i = 0 ; i < indexes . length ; i ++ ) { if ( inputs [ i ] . getTypeState ( pk . getType ( ) ) != null ) indexes [ i ] = new HollowPrimaryKeyIndex ( inputs [ i ] , pk ) ; } for ( int i = 0 ; i < indexes . length ; i ++ ) { HollowTypeReadState typeState = inputs [ i ] . getTypeState ( pk . getType ( ) ) ; if ( typeState != null ) { BitSet populatedOrdinals = typeState . getListener ( PopulatedOrdinalListener . class ) . getPopulatedOrdinals ( ) ; int ordinal = populatedOrdinals . nextSetBit ( 0 ) ; while ( ordinal != - 1 ) { if ( primaryKeyCopyDirector . shouldCopy ( typeState , ordinal ) ) { Object [ ] recordKey = indexes [ i ] . getRecordKey ( ordinal ) ; for ( int j = i + 1 ; j < indexes . length ; j ++ ) { primaryKeyCopyDirector . excludeKey ( indexes [ j ] , recordKey ) ; } } ordinal = populatedOrdinals . nextSetBit ( ordinal + 1 ) ; } } } primaryKeyIndexes . put ( pk . getType ( ) , indexes ) ; } } typesToProcessThisIteration . add ( schema . getName ( ) ) ; } } } if ( typesToProcessThisIteration . isEmpty ( ) ) break ; for ( int i = 0 ; i < numThreads ; i ++ ) { final int threadNumber = i ; executor . execute ( ( ) -> { for ( int i1 = 0 ; i1 < inputs . length ; i1 ++ ) { HollowCombinerCopyDirector copyDirector = selectedPrimaryKeys . isEmpty ( ) ? HollowCombiner . this . copyDirector : primaryKeyCopyDirector ; HollowReadStateEngine inputEngine = inputs [ i1 ] ; OrdinalRemapper ordinalRemapper = selectedPrimaryKeys . isEmpty ( ) ? ordinalRemappers [ i1 ] : new HollowCombinerPrimaryKeyOrdinalRemapper ( ordinalRemappers , primaryKeyIndexes , i1 ) ; Map < String , HollowCombinerCopier > copierMap = new HashMap <> ( ) ; List < HollowCombinerCopier > copierList = new ArrayList <> ( ) ; for ( String typeName : typesToProcessThisIteration ) { HollowTypeReadState readState = inputEngine . getTypeState ( typeName ) ; HollowTypeWriteState writeState = output . getTypeState ( typeName ) ; if ( readState != null && writeState != null ) { HollowCombinerCopier copier = new HollowCombinerCopier ( readState , writeState , ordinalRemapper ) ; copierList . add ( copier ) ; copierMap . put ( typeName , copier ) ; } } for ( String typeName : processedTypes ) { HollowTypeReadState readState = inputEngine . getTypeState ( typeName ) ; HollowTypeWriteState writeState = output . getTypeState ( typeName ) ; if ( readState != null && writeState != null ) { HollowCombinerCopier copier = new HollowCombinerCopier ( readState , writeState , ordinalRemappers [ i1 ] ) ; copierMap . put ( typeName , copier ) ; } } copiersPerType . set ( copierMap ) ; int currentOrdinal = threadNumber ; while ( ! copierList . isEmpty ( ) ) { copyOrdinalForAllStates ( currentOrdinal , copierList , ordinalRemapper , copyDirector ) ; currentOrdinal += numThreads ; } } } ) ; } try { executor . awaitSuccessfulCompletionOfCurrentTasks ( ) ; } catch ( Throwable th ) { throw new RuntimeException ( th ) ; } processedTypes . addAll ( typesToProcessThisIteration ) ; processedPrimaryKeys . addAll ( selectedPrimaryKeys ) ; selectedPrimaryKeys . clear ( ) ; } executor . shutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates all fields in order to the ByteDataBuffer supplied . This concatenation is the verbatim serialized representation in the FastBlob . [CODESPLIT] public void writeDataTo ( ByteDataBuffer buf ) { for ( int i = 0 ; i < fieldData . length ; i ++ ) { writeField ( buf , i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the buffer which should be used to serialize the data for the field at the given position in the schema . <p > [CODESPLIT] private ByteDataBuffer getFieldBuffer ( int fieldPosition ) { isNonNull [ fieldPosition ] = true ; fieldData [ fieldPosition ] . reset ( ) ; return fieldData [ fieldPosition ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write 4 consecutive bytes [CODESPLIT] private static void writeFixedLengthInt ( ByteDataBuffer fieldBuffer , int intBits ) { fieldBuffer . write ( ( byte ) ( intBits >>> 24 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 16 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 8 ) ) ; fieldBuffer . write ( ( byte ) ( intBits ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write 8 consecutive bytes [CODESPLIT] private static void writeFixedLengthLong ( ByteDataBuffer fieldBuffer , long intBits ) { fieldBuffer . write ( ( byte ) ( intBits >>> 56 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 48 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 40 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 32 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 24 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 16 ) ) ; fieldBuffer . write ( ( byte ) ( intBits >>> 8 ) ) ; fieldBuffer . write ( ( byte ) ( intBits ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a stream of matching ordinals . <p > The ordinals may be used with a generated API or the Generic Object API to inspect the matched records . [CODESPLIT] public IntStream stream ( ) { Spliterator . OfInt si = new Spliterator . OfInt ( ) { final long endBucket = selectTableStartPointer + selectTableBuckets ; long currentBucket = selectTableStartPointer ; @ Override public OfInt trySplit ( ) { // @@@ Supporting splitting and therefore enable parallelism return null ; } @ Override public boolean tryAdvance ( IntConsumer action ) { while ( currentBucket < endBucket ) { int selectOrdinal = ( int ) hashIndexState . getSelectHashArray ( ) . getElementValue ( ( currentBucket ++ ) * hashIndexState . getBitsPerSelectHashEntry ( ) , hashIndexState . getBitsPerSelectHashEntry ( ) ) - 1 ; if ( selectOrdinal != - 1 ) { action . accept ( selectOrdinal ) ; return true ; } } return false ; } @ Override public long estimateSize ( ) { // @@@ return 0 ; } @ Override public int characteristics ( ) { // @@@ ordinals are distinct? return 0 ; } } ; return StreamSupport . intStream ( si , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an ordinal to the pool after the object to which it was assigned is discarded . [CODESPLIT] public void returnOrdinalToPool ( int ordinal ) { if ( size == freeOrdinals . length ) { freeOrdinals = Arrays . copyOf ( freeOrdinals , freeOrdinals . length * 3 / 2 ) ; } freeOrdinals [ size ] = ordinal ; size ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure that all future ordinals are returned in ascending order . [CODESPLIT] public void sort ( ) { Arrays . sort ( freeOrdinals , 0 , size ) ; /// reverse the ordering int midpoint = size / 2 ; for ( int i = 0 ; i < midpoint ; i ++ ) { int temp = freeOrdinals [ i ] ; freeOrdinals [ i ] = freeOrdinals [ size - i - 1 ] ; freeOrdinals [ size - i - 1 ] = temp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hash a key [CODESPLIT] public static int hash ( Object key [ ] , FieldType fieldType [ ] ) { int hash = 0 ; for ( int i = 0 ; i < key . length ; i ++ ) { hash *= 31 ; hash ^= hash ( key [ i ] , fieldType [ i ] ) ; } return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hash a single key field [CODESPLIT] public static int hash ( Object key , FieldType fieldType ) { switch ( fieldType ) { case INT : return HashCodes . hashInt ( ( ( Integer ) key ) . intValue ( ) ) ; case LONG : long longVal = ( ( Long ) key ) . longValue ( ) ; return HashCodes . hashInt ( ( int ) ( longVal ^ ( longVal >>> 32 ) ) ) ; case REFERENCE : return HashCodes . hashInt ( ( ( Integer ) key ) . intValue ( ) ) ; case BYTES : return HashCodes . hashInt ( HashCodes . hashCode ( ( byte [ ] ) key ) ) ; case STRING : return HashCodes . hashInt ( key . hashCode ( ) ) ; case BOOLEAN : return HashCodes . hashInt ( ( ( Boolean ) key ) . booleanValue ( ) ? 1231 : 1237 ) ; case DOUBLE : long longBits = Double . doubleToRawLongBits ( ( ( Double ) key ) . doubleValue ( ) ) ; return HashCodes . hashInt ( ( int ) ( longBits ^ ( longBits >>> 32 ) ) ) ; case FLOAT : return HashCodes . hashInt ( Float . floatToRawIntBits ( ( ( Float ) key ) . floatValue ( ) ) ) ; default : throw new IllegalArgumentException ( \"Unknown field type: \" + fieldType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method adds an element at nodeIndex . Note that this does not check for duplicates ; if the element already exists another instance of it will be added . This method is not thread - safe - you cannot call this method concurrently with itself or with { @link #getElements } . [CODESPLIT] public void addElement ( long nodeIndex , long element ) { if ( element > elementMask ) { throw new IllegalArgumentException ( \"Element \" + element + \" does not fit in \" + bitsPerElement + \" bits\" ) ; } if ( nodeIndex >= numNodes ) { throw new IllegalArgumentException ( \"Provided nodeIndex  \" + nodeIndex + \" greater then numNodes \" + numNodes ) ; } if ( element == NO_ELEMENT ) { // we use 0 to indicate an \"empty\" element, so we have to store ordinal zero here nodesWithOrdinalZero . setElementValue ( nodeIndex , 1 , 1 ) ; return ; } long bucketStart = nodeIndex * maxElementsPerNode * bitsPerElement ; long currentIndex ; int offset = 0 ; do { currentIndex = bucketStart + offset * bitsPerElement ; offset ++ ; } while ( storage . getElementValue ( currentIndex , bitsPerElement , elementMask ) != NO_ELEMENT && offset < maxElementsPerNode ) ; if ( storage . getElementValue ( currentIndex , bitsPerElement , elementMask ) != NO_ELEMENT ) { // we're full at this index - resize, then figure out the new current index resizeStorage ( ) ; currentIndex = nodeIndex * maxElementsPerNode * bitsPerElement + offset * bitsPerElement ; } /* we're adding to the first empty spot from the beginning of the bucket - this is\n         * preferable to adding at the end because we want our getElements method to be fast, and\n         * it's okay for addElement to be comparatively slow */ storage . setElementValue ( currentIndex , bitsPerElement , element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a list of elements at the specified node index . The returned list may contain duplicates . This method not thread - safe - the caller must ensure that no one calls { @link #addElement } concurrently with this method but calling this method concurrently with itself is safe . [CODESPLIT] public List < Long > getElements ( long nodeIndex ) { long bucketStart = nodeIndex * maxElementsPerNode * bitsPerElement ; List < Long > ret = new ArrayList <> ( ) ; if ( nodesWithOrdinalZero . getElementValue ( nodeIndex , 1 , 1 ) != NO_ELEMENT ) { // 0 indicates an \"empty\" element, so we fetch ordinal zeros from nodesWithOrdinalZero ret . add ( NO_ELEMENT ) ; } for ( int offset = 0 ; offset < maxElementsPerNode ; offset ++ ) { long element = storage . getElementValue ( bucketStart + offset * bitsPerElement , bitsPerElement , elementMask ) ; if ( element == NO_ELEMENT ) { break ; // we have exhausted the elements at this index } ret . add ( element ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resize the underlying storage to a multiple of what it currently is . This method is not thread - safe . [CODESPLIT] private void resizeStorage ( ) { int currentElementsPerNode = maxElementsPerNode ; int newElementsPerNode = ( int ) ( currentElementsPerNode * RESIZE_MULTIPLE ) ; if ( newElementsPerNode <= currentElementsPerNode ) { throw new IllegalStateException ( \"cannot resize fixed length array from \" + currentElementsPerNode + \" to \" + newElementsPerNode ) ; } FixedLengthElementArray newStorage = new FixedLengthElementArray ( memoryRecycler , numNodes * bitsPerElement * newElementsPerNode ) ; LongStream . range ( 0 , numNodes ) . forEach ( nodeIndex -> { long currentBucketStart = nodeIndex * currentElementsPerNode * bitsPerElement ; long newBucketStart = nodeIndex * newElementsPerNode * bitsPerElement ; for ( int offset = 0 ; offset < currentElementsPerNode ; offset ++ ) { long element = storage . getElementValue ( currentBucketStart + offset * bitsPerElement , bitsPerElement , elementMask ) ; if ( element == NO_ELEMENT ) { break ; // we have exhausted the elements at this index } newStorage . setElementValue ( newBucketStart + offset * bitsPerElement , bitsPerElement , element ) ; } } ) ; storage . destroy ( memoryRecycler ) ; storage = newStorage ; maxElementsPerNode = newElementsPerNode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ TODO : Many parse failures can cause out of memory errors . [CODESPLIT] protected void processFile ( Reader r , int maxSample ) throws Exception { JsonArrayChunker chunker = new JsonArrayChunker ( r , executor ) ; chunker . initialize ( ) ; int counter = 0 ; Reader jsonObj = chunker . nextChunk ( ) ; while ( jsonObj != null && counter < maxSample ) { final Reader currentObject = jsonObj ; executor . execute ( new Runnable ( ) { public void run ( ) { try { JsonFactory factory = new JsonFactory ( ) ; JsonParser parser = factory . createParser ( currentObject ) ; processRecord ( parser ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ) ; while ( executor . getQueue ( ) . size ( ) > maxWorkQueue ) { Thread . sleep ( 5 ) ; } counter ++ ; jsonObj . close ( ) ; jsonObj = chunker . nextChunk ( ) ; } executor . awaitSuccessfulCompletion ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a sequence of bytes to this map . If the sequence of bytes has previously been added to this map then its assigned ordinal is returned . If the sequence of bytes has not been added to this map then a new ordinal is assigned and returned . <p > This operation is thread - safe . [CODESPLIT] public int getOrAssignOrdinal ( ByteDataBuffer serializedRepresentation , int preferredOrdinal ) { int hash = HashCodes . hashCode ( serializedRepresentation ) ; int ordinal = get ( serializedRepresentation , hash ) ; return ordinal != - 1 ? ordinal : assignOrdinal ( serializedRepresentation , hash , preferredOrdinal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ acquire the lock before writing . [CODESPLIT] private synchronized int assignOrdinal ( ByteDataBuffer serializedRepresentation , int hash , int preferredOrdinal ) { if ( preferredOrdinal < - 1 || preferredOrdinal > ORDINAL_MASK ) { throw new IllegalArgumentException ( String . format ( \"The given preferred ordinal %s is out of bounds and not within the closed interval [-1, %s]\" , preferredOrdinal , ORDINAL_MASK ) ) ; } if ( size > sizeBeforeGrow ) { growKeyArray ( ) ; } /// check to make sure that after acquiring the lock, the element still does not exist. /// this operation is akin to double-checked locking which is 'fixed' with the JSR 133 memory model in JVM >= 1.5. /// Note that this also requires pointersAndOrdinals be volatile so resizes are also visible AtomicLongArray pao = pointersAndOrdinals ; int modBitmask = pao . length ( ) - 1 ; int bucket = hash & modBitmask ; long key = pao . get ( bucket ) ; while ( key != EMPTY_BUCKET_VALUE ) { if ( compare ( serializedRepresentation , key ) ) { return ( int ) ( key >>> BITS_PER_POINTER ) ; } bucket = ( bucket + 1 ) & modBitmask ; key = pao . get ( bucket ) ; } /// the ordinal for this object still does not exist in the list, even after the lock has been acquired. /// it is up to this thread to add it at the current bucket position. int ordinal = findFreeOrdinal ( preferredOrdinal ) ; if ( ordinal > ORDINAL_MASK ) { throw new IllegalStateException ( String . format ( \"Ordinal cannot be assigned. The to be assigned ordinal, %s, is greater than the maximum supported ordinal value of %s\" , ordinal , ORDINAL_MASK ) ) ; } long pointer = byteData . length ( ) ; VarInt . writeVInt ( byteData , ( int ) serializedRepresentation . length ( ) ) ; /// Copying might cause a resize to the segmented array held by byteData /// A reading thread may observe a null value for a segment during the creation /// of a new segments array (see SegmentedByteArray.ensureCapacity). serializedRepresentation . copyTo ( byteData ) ; if ( byteData . length ( ) > MAX_BYTE_DATA_LENGTH ) { throw new IllegalStateException ( String . format ( \"The number of bytes for the serialized representations, %s, is too large and is greater than the maximum of %s bytes\" , byteData . length ( ) , MAX_BYTE_DATA_LENGTH ) ) ; } key = ( ( long ) ordinal << BITS_PER_POINTER ) | pointer ; size ++ ; /// this set on the AtomicLongArray has volatile semantics (i.e. behaves like a monitor release). /// Any other thread reading this element in the AtomicLongArray will have visibility to all memory writes this thread has made up to this point. /// This means the entire byte sequence is guaranteed to be visible to any thread which reads the pointer to that data. pao . set ( bucket , key ) ; return ordinal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the preferredOrdinal has not already been used mark it and use it . Otherwise delegate to the FreeOrdinalTracker . [CODESPLIT] private int findFreeOrdinal ( int preferredOrdinal ) { if ( preferredOrdinal != - 1 && unusedPreviousOrdinals . get ( preferredOrdinal ) ) { unusedPreviousOrdinals . clear ( preferredOrdinal ) ; return preferredOrdinal ; } return freeOrdinalTracker . getFreeOrdinal ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an array mapping the ordinals to pointers so that they can be easily looked up when writing to blob streams . [CODESPLIT] public void prepareForWrite ( ) { int maxOrdinal = 0 ; AtomicLongArray pao = pointersAndOrdinals ; for ( int i = 0 ; i < pao . length ( ) ; i ++ ) { long key = pao . get ( i ) ; if ( key != EMPTY_BUCKET_VALUE ) { int ordinal = ( int ) ( key >>> BITS_PER_POINTER ) ; if ( ordinal > maxOrdinal ) { maxOrdinal = ordinal ; } } } long [ ] pbo = new long [ maxOrdinal + 1 ] ; Arrays . fill ( pbo , - 1 ) ; for ( int i = 0 ; i < pao . length ( ) ; i ++ ) { long key = pao . get ( i ) ; if ( key != EMPTY_BUCKET_VALUE ) { int ordinal = ( int ) ( key >>> BITS_PER_POINTER ) ; pbo [ ordinal ] = key & POINTER_MASK ; } } pointersByOrdinal = pbo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reclaim space in the byte array used in the previous cycle but not referenced in this cycle . <p > <p > This is achieved by shifting all used byte sequences down in the byte array then updating the key array to reflect the new pointers and exclude the removed entries . This is also where ordinals which are unused are returned to the pool . <p > [CODESPLIT] public void compact ( ThreadSafeBitSet usedOrdinals ) { long [ ] populatedReverseKeys = new long [ size ] ; int counter = 0 ; AtomicLongArray pao = pointersAndOrdinals ; for ( int i = 0 ; i < pao . length ( ) ; i ++ ) { long key = pao . get ( i ) ; if ( key != EMPTY_BUCKET_VALUE ) { populatedReverseKeys [ counter ++ ] = key << BITS_PER_ORDINAL | key >>> BITS_PER_POINTER ; } } Arrays . sort ( populatedReverseKeys ) ; SegmentedByteArray arr = byteData . getUnderlyingArray ( ) ; long currentCopyPointer = 0 ; for ( int i = 0 ; i < populatedReverseKeys . length ; i ++ ) { int ordinal = ( int ) ( populatedReverseKeys [ i ] & ORDINAL_MASK ) ; if ( usedOrdinals . get ( ordinal ) ) { long pointer = populatedReverseKeys [ i ] >>> BITS_PER_ORDINAL ; int length = VarInt . readVInt ( arr , pointer ) ; length += VarInt . sizeOfVInt ( length ) ; if ( currentCopyPointer != pointer ) { arr . copy ( arr , pointer , currentCopyPointer , length ) ; } populatedReverseKeys [ i ] = populatedReverseKeys [ i ] << BITS_PER_POINTER | currentCopyPointer ; currentCopyPointer += length ; } else { freeOrdinalTracker . returnOrdinalToPool ( ordinal ) ; populatedReverseKeys [ i ] = EMPTY_BUCKET_VALUE ; } } byteData . setPosition ( currentCopyPointer ) ; freeOrdinalTracker . sort ( ) ; // Reset the array then fill with compacted values // Volatile store not required, could use plain store // See VarHandles for JDK >= 9 for ( int i = 0 ; i < pao . length ( ) ; i ++ ) { pao . lazySet ( i , EMPTY_BUCKET_VALUE ) ; } populateNewHashArray ( pao , populatedReverseKeys ) ; size = usedOrdinals . cardinality ( ) ; pointersByOrdinal = null ; unusedPreviousOrdinals = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare the byte sequence contained in the supplied ByteDataBuffer with the sequence contained in the map pointed to by the specified key byte by byte . [CODESPLIT] private boolean compare ( ByteDataBuffer serializedRepresentation , long key ) { long position = key & POINTER_MASK ; int sizeOfData = VarInt . readVInt ( byteData . getUnderlyingArray ( ) , position ) ; if ( sizeOfData != serializedRepresentation . length ( ) ) { return false ; } position += VarInt . sizeOfVInt ( sizeOfData ) ; for ( int i = 0 ; i < sizeOfData ; i ++ ) { if ( serializedRepresentation . get ( i ) != byteData . get ( position ++ ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resize the ordinal map by increasing its capacity . <p > No action is take if the current capacity is sufficient for the given size . <p > WARNING : THIS OPERATION IS NOT THREAD - SAFE . [CODESPLIT] public void resize ( int size ) { size = bucketSize ( size ) ; if ( pointersAndOrdinals . length ( ) < size ) { growKeyArray ( size ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grow the key array . All of the values in the current array must be re - hashed and added to the new array . [CODESPLIT] private void growKeyArray ( ) { int newSize = pointersAndOrdinals . length ( ) << 1 ; if ( newSize < 0 ) { throw new IllegalStateException ( \"New size computed to grow the underlying array for the map is negative. \" + \"This is most likely due to the total number of keys added to map has exceeded the max capacity of the keys map can hold. \" + \"Current array size :\" + pointersAndOrdinals . length ( ) + \" and size to grow :\" + newSize ) ; } growKeyArray ( newSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the hash code for the byte array pointed to by the specified key . [CODESPLIT] private int rehashPreviouslyAddedData ( long key ) { long position = key & POINTER_MASK ; int sizeOfData = VarInt . readVInt ( byteData . getUnderlyingArray ( ) , position ) ; position += VarInt . sizeOfVInt ( sizeOfData ) ; return HashCodes . hashCode ( byteData . getUnderlyingArray ( ) , position , sizeOfData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an AtomicLongArray of the specified size each value in the array will be EMPTY_BUCKET_VALUE [CODESPLIT] private AtomicLongArray emptyKeyArray ( int size ) { AtomicLongArray arr = new AtomicLongArray ( size ) ; // Volatile store not required, could use plain store // See VarHandles for JDK >= 9 for ( int i = 0 ; i < arr . length ( ) ; i ++ ) { arr . lazySet ( i , EMPTY_BUCKET_VALUE ) ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method assumes the other traverser has the same match fields specified in the same order . [CODESPLIT] public boolean isMatchEqual ( int matchIdx , HollowIndexerValueTraverser otherTraverser , int otherMatchIdx ) { for ( int i = 0 ; i < getNumFieldPaths ( ) ; i ++ ) { if ( ! HollowReadFieldUtils . fieldsAreEqual ( ( HollowObjectTypeDataAccess ) fieldTypeDataAccess [ i ] , fieldMatchLists [ i ] . get ( matchIdx ) , fieldSchemaPosition [ i ] , ( HollowObjectTypeDataAccess ) otherTraverser . fieldTypeDataAccess [ i ] , otherTraverser . fieldMatchLists [ i ] . get ( otherMatchIdx ) , otherTraverser . fieldSchemaPosition [ i ] ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warning : Not thread - safe . Should only be called within the update thread . [CODESPLIT] public int bitsRequiredForField ( String fieldName ) { int maxBitsRequiredForField = shards [ 0 ] . bitsRequiredForField ( fieldName ) ; for ( int i = 1 ; i < shards . length ; i ++ ) { int shardRequiredBits = shards [ i ] . bitsRequiredForField ( fieldName ) ; if ( shardRequiredBits > maxBitsRequiredForField ) maxBitsRequiredForField = shardRequiredBits ; } return maxBitsRequiredForField ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the unique object an instance of the unique type for a given key . [CODESPLIT] public T findMatch ( Q key ) { Object [ ] keyArray = matchFields . stream ( ) . map ( mf -> mf . extract ( key ) ) . toArray ( ) ; int ordinal = hpki . getMatchingOrdinal ( keyArray ) ; if ( ordinal == - 1 ) { return null ; } return uniqueTypeExtractor . extract ( api , ordinal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the building of a { @link UniqueKeyIndex } . [CODESPLIT] public static < T extends HollowObject > Builder < T > from ( HollowConsumer consumer , Class < T > uniqueType ) { Objects . requireNonNull ( consumer ) ; Objects . requireNonNull ( uniqueType ) ; return new Builder <> ( consumer , uniqueType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swap underlying state engines between current and pending while keeping the versions consistent ; used after delta integrity checks have altered the underlying state engines . [CODESPLIT] ReadStateHelper swap ( ) { return new ReadStateHelper ( newReadState ( current . getVersion ( ) , pending . getStateEngine ( ) ) , newReadState ( pending . getVersion ( ) , current . getStateEngine ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a collection of { @link HollowSchema } s from the provided Reader . [CODESPLIT] public static List < HollowSchema > parseCollectionOfSchemas ( Reader reader ) throws IOException { StreamTokenizer tokenizer = new StreamTokenizer ( reader ) ; configureTokenizer ( tokenizer ) ; List < HollowSchema > schemaList = new ArrayList < HollowSchema > ( ) ; HollowSchema schema = parseSchema ( tokenizer ) ; while ( schema != null ) { schemaList . add ( schema ) ; schema = parseSchema ( tokenizer ) ; } return schemaList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a single { @link HollowSchema } from the provided String . [CODESPLIT] public static HollowSchema parseSchema ( String schema ) throws IOException { StreamTokenizer tokenizer = new StreamTokenizer ( new StringReader ( schema ) ) ; configureTokenizer ( tokenizer ) ; return parseSchema ( tokenizer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the type name from a given type . <p > If the type is annotated with { @link HollowTypeName } then the type name is the value of the { @code HollowTypeName . name } attribute . Otherwise the type name is derived from the type itself . If the type is a { @code Class } then the type name is the simple name of that class . If the type is a parameterized type and is assignable to a class of { @code List } { @code Set } or { @code Map } then the type name begins with the simple class name of the parameterized type s raw type followed by Of followed by the result of calling this method with the associated parameterized types ( in order in - fixed by To ) . Otherwise the type name is the simple class name of the parameterized type s raw type . <p > The translation from type to type name is lossy since the simple class name of a class is used . This means that no two types from different packages but with the same simple name can be utilized . [CODESPLIT] public static String getDefaultTypeName ( Type type ) { if ( type instanceof Class ) { Class < ? > clazz = ( Class < ? > ) type ; HollowTypeName explicitTypeName = clazz . getAnnotation ( HollowTypeName . class ) ; if ( explicitTypeName != null ) return explicitTypeName . name ( ) ; return clazz . getSimpleName ( ) ; } ParameterizedType parameterizedType = ( ParameterizedType ) type ; Class < ? > clazz = ( Class < ? > ) parameterizedType . getRawType ( ) ; if ( List . class . isAssignableFrom ( clazz ) ) return \"ListOf\" + getDefaultTypeName ( parameterizedType . getActualTypeArguments ( ) [ 0 ] ) ; if ( Set . class . isAssignableFrom ( clazz ) ) return \"SetOf\" + getDefaultTypeName ( parameterizedType . getActualTypeArguments ( ) [ 0 ] ) ; if ( Map . class . isAssignableFrom ( clazz ) ) return \"MapOf\" + getDefaultTypeName ( parameterizedType . getActualTypeArguments ( ) [ 0 ] ) + \"To\" + getDefaultTypeName ( parameterizedType . getActualTypeArguments ( ) [ 1 ] ) ; return clazz . getSimpleName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine size of hash table capable of storing the specified number of elements with a load factor applied . [CODESPLIT] public static int hashTableSize ( int numElements ) throws IllegalArgumentException { if ( numElements < 0 ) { throw new IllegalArgumentException ( \"cannot be negative; numElements=\" + numElements ) ; } else if ( numElements > HASH_TABLE_MAX_SIZE ) { throw new IllegalArgumentException ( \"exceeds maximum number of buckets; numElements=\" + numElements ) ; } if ( numElements == 0 ) return 1 ; if ( numElements < 3 ) return numElements * 2 ; // Apply load factor to number of elements and determine next // largest power of 2 that fits in an int int sizeAfterLoadFactor = ( int ) ( ( long ) numElements * 10 / 7 ) ; int bits = 32 - Integer . numberOfLeadingZeros ( sizeAfterLoadFactor - 1 ) ; return 1 << bits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restores the data state to a desired version . <p > Data model { @link #initializeDataModel ( Class [] ) initialization } is required prior to restoring the producer . This ensures that restoration can correctly compare the producer s current data model with the data model of the restored data state and manage any differences in those models ( such as not restoring state for any types in the restoring data model not present in the producer s current data model ) [CODESPLIT] @ Override public HollowProducer . ReadState restore ( long versionDesired , HollowConsumer . BlobRetriever blobRetriever ) { return super . restore ( versionDesired , blobRetriever ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run a compaction cycle will produce a data state with exactly the same data as currently but reorganized so that ordinal holes are filled . This may need to be run multiple times to arrive at an optimal state . [CODESPLIT] public long runCompactionCycle ( HollowCompactor . CompactionConfig config ) { if ( config != null && readStates . hasCurrent ( ) ) { final HollowCompactor compactor = new HollowCompactor ( getWriteEngine ( ) , readStates . current ( ) . getStateEngine ( ) , config ) ; if ( compactor . needsCompaction ( ) ) { return runCycle ( newState -> compactor . compact ( ) ) ; } } return NO_ANNOUNCEMENT_AVAILABLE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the current state as a snapshot blob . [CODESPLIT] public void writeSnapshot ( OutputStream os ) throws IOException { stateEngine . prepareForWrite ( ) ; DataOutputStream dos = new DataOutputStream ( os ) ; writeHeader ( dos , stateEngine . getSchemas ( ) , false ) ; VarInt . writeVInt ( dos , stateEngine . getOrderedTypeStates ( ) . size ( ) ) ; SimultaneousExecutor executor = new SimultaneousExecutor ( getClass ( ) , \"write-snapshot\" ) ; for ( final HollowTypeWriteState typeState : stateEngine . getOrderedTypeStates ( ) ) { executor . execute ( new Runnable ( ) { public void run ( ) { typeState . calculateSnapshot ( ) ; } } ) ; } try { executor . awaitSuccessfulCompletion ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } for ( HollowTypeWriteState typeState : stateEngine . getOrderedTypeStates ( ) ) { HollowSchema schema = typeState . getSchema ( ) ; schema . writeTo ( dos ) ; writeNumShards ( dos , typeState . getNumShards ( ) ) ; typeState . writeSnapshot ( dos ) ; } os . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the changes necessary to transition a consumer from the previous state to the current state as a delta blob . [CODESPLIT] public void writeDelta ( OutputStream os ) throws IOException { stateEngine . prepareForWrite ( ) ; if ( stateEngine . isRestored ( ) ) stateEngine . ensureAllNecessaryStatesRestored ( ) ; List < HollowSchema > changedTypes = changedTypes ( ) ; DataOutputStream dos = new DataOutputStream ( os ) ; writeHeader ( dos , changedTypes , false ) ; VarInt . writeVInt ( dos , changedTypes . size ( ) ) ; SimultaneousExecutor executor = new SimultaneousExecutor ( getClass ( ) , \"write-delta\" ) ; for ( final HollowTypeWriteState typeState : stateEngine . getOrderedTypeStates ( ) ) { executor . execute ( new Runnable ( ) { public void run ( ) { if ( typeState . hasChangedSinceLastCycle ( ) ) typeState . calculateDelta ( ) ; } } ) ; } try { executor . awaitSuccessfulCompletion ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } for ( HollowTypeWriteState typeState : stateEngine . getOrderedTypeStates ( ) ) { if ( typeState . hasChangedSinceLastCycle ( ) ) { HollowSchema schema = typeState . getSchema ( ) ; schema . writeTo ( dos ) ; writeNumShards ( dos , typeState . getNumShards ( ) ) ; typeState . writeDelta ( dos ) ; } } os . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the schema name to the set if the schema name doesn t correspond to a Hollow primitive type . Factored out to prevent bloat in the switch statement it is called from . [CODESPLIT] private void addToSetIfNotPrimitiveOrCollection ( Set < String > schemaNameSet , String ... schemaNames ) { for ( String schemaName : schemaNames ) { // collections schemas get brought in by a star import if ( ! HollowCodeGenerationUtils . isCollectionType ( schemaName , dataset ) && ! HollowCodeGenerationUtils . isPrimitiveType ( schemaName ) ) { schemaNameSet . add ( schemaName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new state version . <p > [CODESPLIT] public long mint ( ) { SimpleDateFormat dateFormat = new SimpleDateFormat ( \"yyyyMMddHHmmss\" ) ; dateFormat . setTimeZone ( TimeZone . getTimeZone ( \"UTC\" ) ) ; String formattedDate = dateFormat . format ( new Date ( ) ) ; String versionStr = formattedDate + String . format ( \"%03d\" , versionCounter . incrementAndGet ( ) % 1000 ) ; return Long . parseLong ( versionStr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers { @code DuplicateDataDetectionValidator } validators with the given { @link HollowProducer producer } for all object schema declared with a primary key . <p > This requires that the producer s data model has been initialized ( see { @link HollowProducer#initializeDataModel ( Class [] ) } or a prior run cycle has implicitly initialized the data model . <p > For each { @link HollowTypeWriteState write state } that has a { @link HollowObjectSchema object schema } declared with a { @link PrimaryKey primary key } a { @code DuplicateDataDetectionValidator } validator is instantiated with the primary key type name and registered with the given producer ( if a { @code DuplicateDataDetectionValidator } validator is not already registered for the same primary key type name ) . [CODESPLIT] public static void addValidatorsForSchemaWithPrimaryKey ( HollowProducer producer ) { producer . getWriteEngine ( ) . getOrderedTypeStates ( ) . stream ( ) . filter ( ts -> ts . getSchema ( ) . getSchemaType ( ) == SchemaType . OBJECT ) . map ( ts -> ( HollowObjectSchema ) ts . getSchema ( ) ) . filter ( hos -> hos . getPrimaryKey ( ) != null ) . map ( HollowObjectSchema :: getPrimaryKey ) . forEach ( k -> producer . addListener ( new DuplicateDataDetectionValidator ( k . getType ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rules : prepend get / is + upper case first char of field name [CODESPLIT] public static String generateAccessortMethodName ( String fieldName , Class < ? > clazz ) { String prefix = \"get\" ; if ( boolean . class . equals ( clazz ) || Boolean . class . equals ( clazz ) ) { for ( String booleanPrefix : booleanMethodPrefixes ) { if ( fieldName . startsWith ( booleanPrefix ) && fieldName . length ( ) > booleanPrefix . length ( ) ) { char firstCharAfterBooleanPrefix = fieldName . charAt ( booleanPrefix . length ( ) ) ; if ( Character . isUpperCase ( firstCharAfterBooleanPrefix ) ) { return fieldName ; } } } } return substituteInvalidChars ( prefix + uppercase ( fieldName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert field path into Param name [CODESPLIT] public static String normalizeFieldPathToParamName ( String fieldPath ) { String result = null ; if ( fieldPath . contains ( \".\" ) ) { String [ ] parts = fieldPath . split ( \"\\\\.\" ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( lowercase ( parts [ 0 ] ) ) ; for ( int i = 1 ; i < parts . length ; i ++ ) { sb . append ( uppercase ( parts [ i ] ) ) ; } result = sb . toString ( ) ; } else { result = lowercase ( fieldPath ) ; } if ( result . endsWith ( \"!\" ) ) { return result . substring ( 0 , result . length ( ) - 1 ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recreate the hash index entirely [CODESPLIT] private void reindexHashIndex ( ) { HollowHashIndexBuilder builder = new HollowHashIndexBuilder ( stateEngine , type , selectField , matchFields ) ; builder . buildIndex ( ) ; this . hashStateVolatile = new HollowHashIndexState ( builder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query the index . [CODESPLIT] public HollowHashIndexResult findMatches ( Object ... query ) { int hashCode = 0 ; for ( int i = 0 ; i < query . length ; i ++ ) { if ( query [ i ] == null ) throw new IllegalArgumentException ( \"querying by null unsupported; i=\" + i ) ; hashCode ^= HashCodes . hashInt ( keyHashCode ( query [ i ] , i ) ) ; } HollowHashIndexResult result ; HollowHashIndexState hashState ; do { result = null ; hashState = hashStateVolatile ; long bucket = hashCode & hashState . getMatchHashMask ( ) ; long hashBucketBit = bucket * hashState . getBitsPerMatchHashEntry ( ) ; boolean bucketIsEmpty = hashState . getMatchHashTable ( ) . getElementValue ( hashBucketBit , hashState . getBitsPerTraverserField ( ) [ 0 ] ) == 0 ; while ( ! bucketIsEmpty ) { if ( matchIsEqual ( hashState . getMatchHashTable ( ) , hashBucketBit , query ) ) { int selectSize = ( int ) hashState . getMatchHashTable ( ) . getElementValue ( hashBucketBit + hashState . getBitsPerMatchHashKey ( ) , hashState . getBitsPerSelectTableSize ( ) ) ; long selectBucketPointer = hashState . getMatchHashTable ( ) . getElementValue ( hashBucketBit + hashState . getBitsPerMatchHashKey ( ) + hashState . getBitsPerSelectTableSize ( ) , hashState . getBitsPerSelectTablePointer ( ) ) ; result = new HollowHashIndexResult ( hashState , selectBucketPointer , selectSize ) ; break ; } bucket = ( bucket + 1 ) & hashState . getMatchHashMask ( ) ; hashBucketBit = bucket * hashState . getBitsPerMatchHashEntry ( ) ; bucketIsEmpty = hashState . getMatchHashTable ( ) . getElementValue ( hashBucketBit , hashState . getBitsPerTraverserField ( ) [ 0 ] ) == 0 ; } } while ( hashState != hashStateVolatile ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers async refresh after some random number of milliseconds have passed between now and the specified maximum number of milliseconds . [CODESPLIT] public void triggerAsyncRefreshWithRandomDelay ( int maxDelayMillis ) { Random rand = new Random ( ) ; int delayMillis = maxDelayMillis > 0 ? rand . nextInt ( maxDelayMillis ) : 0 ; triggerAsyncRefreshWithDelay ( delayMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers async refresh after the specified number of milliseconds has passed . [CODESPLIT] public void triggerAsyncRefreshWithDelay ( int delayMillis ) { final HollowClient client = this . client ; final long targetBeginTime = System . currentTimeMillis ( ) + delayMillis ; refreshExecutor . execute ( new Runnable ( ) { public void run ( ) { try { long delay = targetBeginTime - System . currentTimeMillis ( ) ; if ( delay > 0 ) Thread . sleep ( delay ) ; client . triggerRefresh ( ) ; } catch ( Throwable th ) { log . log ( Level . SEVERE , \"Async refresh failed\" , th ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a type to be included in the diff report [CODESPLIT] public HollowTypeDiff addTypeDiff ( String type , String ... primaryKeyPaths ) { HollowTypeDiff typeDiff = new HollowTypeDiff ( this , type , primaryKeyPaths ) ; if ( typeDiff . hasAnyData ( ) ) typeDiffs . put ( type , typeDiff ) ; return typeDiff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the diff [CODESPLIT] public void calculateDiffs ( ) { long startTime = System . currentTimeMillis ( ) ; prepareForDiffCalculation ( ) ; long endTime = System . currentTimeMillis ( ) ; log . info ( \"PREPARED IN \" + ( endTime - startTime ) + \"ms\" ) ; for ( HollowTypeDiff typeDiff : typeDiffs . values ( ) ) { typeDiff . calculateDiffs ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this method after each time a delta occurs in the backing { @link HollowReadStateEngine } . This is how the HollowHistory knows how to create a new { @link HollowHistoricalState } . [CODESPLIT] public void deltaOccurred ( long newVersion ) { keyIndex . update ( latestHollowReadStateEngine , true ) ; HollowHistoricalStateDataAccess historicalDataAccess = creator . createBasedOnNewDelta ( latestVersion , latestHollowReadStateEngine ) ; historicalDataAccess . setNextState ( latestHollowReadStateEngine ) ; HollowHistoricalStateKeyOrdinalMapping keyOrdinalMapping = createKeyOrdinalMappingFromDelta ( ) ; HollowHistoricalState historicalState = new HollowHistoricalState ( newVersion , keyOrdinalMapping , historicalDataAccess , latestHeaderEntries ) ; addHistoricalState ( historicalState ) ; this . latestVersion = newVersion ; this . latestHeaderEntries = latestHollowReadStateEngine . getHeaderTags ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this method after each time a double snapshot occurs . <p > This method will replace the previous backing { @link HollowReadStateEngine } with the newly supplied one stitch together all of the existing history with the new state currently in the new { @link HollowReadStateEngine } and create a new { @link HollowHistoricalState } to represent the transition . [CODESPLIT] public void doubleSnapshotOccurred ( HollowReadStateEngine newHollowStateEngine , long newVersion ) { if ( ! keyIndex . isInitialized ( ) ) keyIndex . update ( latestHollowReadStateEngine , false ) ; keyIndex . update ( newHollowStateEngine , false ) ; HollowHistoricalStateDataAccess historicalDataAccess ; DiffEqualityMapping mapping = new DiffEqualityMapping ( latestHollowReadStateEngine , newHollowStateEngine , true , ! ignoreListOrderingOnDoubleSnapshot ) ; DiffEqualityMappingOrdinalRemapper remapper = new DiffEqualityMappingOrdinalRemapper ( mapping ) ; historicalDataAccess = creator . createHistoricalStateFromDoubleSnapshot ( latestVersion , latestHollowReadStateEngine , newHollowStateEngine , remapper ) ; HollowHistoricalStateDataAccess nextRemappedDataAccess = historicalDataAccess ; HollowHistoricalState nextRemappedState = null ; HollowHistoricalStateDataAccess [ ] remappedDataAccesses = new HollowHistoricalStateDataAccess [ historicalStates . size ( ) ] ; HollowHistoricalStateKeyOrdinalMapping [ ] remappedKeyOrdinalMappings = new HollowHistoricalStateKeyOrdinalMapping [ historicalStates . size ( ) ] ; remapHistoricalStateOrdinals ( remapper , remappedDataAccesses , remappedKeyOrdinalMappings ) ; for ( int i = 0 ; i < historicalStates . size ( ) ; i ++ ) { HollowHistoricalState historicalStateToRemap = historicalStates . get ( i ) ; HollowHistoricalStateDataAccess remappedDataAccess = remappedDataAccesses [ i ] ; HollowHistoricalStateKeyOrdinalMapping remappedKeyOrdinalMapping = remappedKeyOrdinalMappings [ i ] ; remappedDataAccess . setNextState ( nextRemappedDataAccess ) ; nextRemappedDataAccess = remappedDataAccess ; HollowHistoricalState remappedState = new HollowHistoricalState ( historicalStateToRemap . getVersion ( ) , remappedKeyOrdinalMapping , remappedDataAccess , historicalStateToRemap . getHeaderEntries ( ) ) ; remappedState . setNextState ( nextRemappedState ) ; nextRemappedState = remappedState ; historicalStates . set ( i , remappedState ) ; historicalStateLookupMap . put ( remappedState . getVersion ( ) , remappedState ) ; } historicalDataAccess . setNextState ( newHollowStateEngine ) ; HollowHistoricalStateKeyOrdinalMapping keyOrdinalMapping = createKeyOrdinalMappingFromDoubleSnapshot ( newHollowStateEngine , remapper ) ; HollowHistoricalState historicalState = new HollowHistoricalState ( newVersion , keyOrdinalMapping , historicalDataAccess , latestHeaderEntries ) ; addHistoricalState ( historicalState ) ; this . latestVersion = newVersion ; this . latestHollowReadStateEngine = newHollowStateEngine ; this . latestHeaderEntries = latestHollowReadStateEngine . getHeaderTags ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the last { @code n } historical states . [CODESPLIT] public void removeHistoricalStates ( int n ) { if ( n < 0 ) { throw new IllegalArgumentException ( String . format ( \"Number of states to remove is negative: %d\" , n ) ) ; } if ( n > historicalStates . size ( ) ) { throw new IllegalArgumentException ( String . format ( \"Number of states to remove, %d, is greater than the number of states. %d\" , n , historicalStates . size ( ) ) ) ; } while ( n -- > 0 ) { HollowHistoricalState removedState = historicalStates . remove ( historicalStates . size ( ) - 1 ) ; historicalStateLookupMap . remove ( removedState . getVersion ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the specified long as a variable length integer into the supplied { @link ByteDataBuffer } [CODESPLIT] public static void writeVLong ( ByteDataBuffer buf , long value ) { if ( value < 0 ) buf . write ( ( byte ) 0x81 ) ; if ( value > 0xFFFFFFFFFFFFFF L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 56 ) & 0x7F L ) ) ) ; if ( value > 0x1FFFFFFFFFFFF L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 49 ) & 0x7F L ) ) ) ; if ( value > 0x3FFFFFFFFFF L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 42 ) & 0x7F L ) ) ) ; if ( value > 0x7FFFFFFFF L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 35 ) & 0x7F L ) ) ) ; if ( value > 0xFFFFFFF L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 28 ) & 0x7F L ) ) ) ; if ( value > 0x1FFFFF L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 21 ) & 0x7F L ) ) ) ; if ( value > 0x3FFF L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 14 ) & 0x7F L ) ) ) ; if ( value > 0x7F L || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 7 ) & 0x7F L ) ) ) ; buf . write ( ( byte ) ( value & 0x7F L ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the specified long as a variable length integer into the supplied OuputStream [CODESPLIT] public static void writeVLong ( OutputStream out , long value ) throws IOException { if ( value < 0 ) out . write ( ( byte ) 0x81 ) ; if ( value > 0xFFFFFFFFFFFFFF L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 56 ) & 0x7F L ) ) ) ; if ( value > 0x1FFFFFFFFFFFF L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 49 ) & 0x7F L ) ) ) ; if ( value > 0x3FFFFFFFFFF L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 42 ) & 0x7F L ) ) ) ; if ( value > 0x7FFFFFFFF L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 35 ) & 0x7F L ) ) ) ; if ( value > 0xFFFFFFF L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 28 ) & 0x7F L ) ) ) ; if ( value > 0x1FFFFF L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 21 ) & 0x7F L ) ) ) ; if ( value > 0x3FFF L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 14 ) & 0x7F L ) ) ) ; if ( value > 0x7F L || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 7 ) & 0x7F L ) ) ) ; out . write ( ( byte ) ( value & 0x7F L ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the specified int as a variable length integer into the supplied { @link ByteDataBuffer } [CODESPLIT] public static void writeVInt ( ByteDataBuffer buf , int value ) { if ( value > 0x0FFFFFFF || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 28 ) ) ) ) ; if ( value > 0x1FFFFF || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 21 ) & 0x7F ) ) ) ; if ( value > 0x3FFF || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 14 ) & 0x7F ) ) ) ; if ( value > 0x7F || value < 0 ) buf . write ( ( byte ) ( 0x80 | ( ( value >>> 7 ) & 0x7F ) ) ) ; buf . write ( ( byte ) ( value & 0x7F ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the specified int as a variable length integer into the supplied OutputStream [CODESPLIT] public static void writeVInt ( OutputStream out , int value ) throws IOException { if ( value > 0x0FFFFFFF || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 28 ) ) ) ) ; if ( value > 0x1FFFFF || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 21 ) & 0x7F ) ) ) ; if ( value > 0x3FFF || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 14 ) & 0x7F ) ) ) ; if ( value > 0x7F || value < 0 ) out . write ( ( byte ) ( 0x80 | ( ( value >>> 7 ) & 0x7F ) ) ) ; out . write ( ( byte ) ( value & 0x7F ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the value as a VarInt into the array starting at the specified position . [CODESPLIT] public static int writeVInt ( byte data [ ] , int pos , int value ) { if ( value > 0x0FFFFFFF || value < 0 ) data [ pos ++ ] = ( ( byte ) ( 0x80 | ( ( value >>> 28 ) ) ) ) ; if ( value > 0x1FFFFF || value < 0 ) data [ pos ++ ] = ( ( byte ) ( 0x80 | ( ( value >>> 21 ) & 0x7F ) ) ) ; if ( value > 0x3FFF || value < 0 ) data [ pos ++ ] = ( ( byte ) ( 0x80 | ( ( value >>> 14 ) & 0x7F ) ) ) ; if ( value > 0x7F || value < 0 ) data [ pos ++ ] = ( ( byte ) ( 0x80 | ( ( value >>> 7 ) & 0x7F ) ) ) ; data [ pos ++ ] = ( byte ) ( value & 0x7F ) ; return pos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a variable length integer from the supplied { [CODESPLIT] public static int readVInt ( ByteData arr , long position ) { byte b = arr . get ( position ++ ) ; if ( b == ( byte ) 0x80 ) throw new RuntimeException ( \"Attempting to read null value as int\" ) ; int value = b & 0x7F ; while ( ( b & 0x80 ) != 0 ) { b = arr . get ( position ++ ) ; value <<= 7 ; value |= ( b & 0x7F ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a variable length integer from the supplied InputStream [CODESPLIT] public static int readVInt ( InputStream in ) throws IOException { byte b = ( byte ) in . read ( ) ; if ( b == ( byte ) 0x80 ) throw new RuntimeException ( \"Attempting to read null value as int\" ) ; int value = b & 0x7F ; while ( ( b & 0x80 ) != 0 ) { b = ( byte ) in . read ( ) ; value <<= 7 ; value |= ( b & 0x7F ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a variable length long from the supplied { [CODESPLIT] public static long readVLong ( ByteData arr , long position ) { byte b = arr . get ( position ++ ) ; if ( b == ( byte ) 0x80 ) throw new RuntimeException ( \"Attempting to read null value as long\" ) ; long value = b & 0x7F ; while ( ( b & 0x80 ) != 0 ) { b = arr . get ( position ++ ) ; value <<= 7 ; value |= ( b & 0x7F ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the size ( in bytes ) of the variable length long in the supplied { [CODESPLIT] public static int nextVLongSize ( ByteData arr , long position ) { byte b = arr . get ( position ++ ) ; if ( b == ( byte ) 0x80 ) return 1 ; int length = 1 ; while ( ( b & 0x80 ) != 0 ) { b = arr . get ( position ++ ) ; length ++ ; } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a variable length long from the supplied InputStream . [CODESPLIT] public static long readVLong ( InputStream in ) throws IOException { byte b = ( byte ) in . read ( ) ; if ( b == ( byte ) 0x80 ) throw new RuntimeException ( \"Attempting to read null value as long\" ) ; long value = b & 0x7F ; while ( ( b & 0x80 ) != 0 ) { b = ( byte ) in . read ( ) ; value <<= 7 ; value |= ( b & 0x7F ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the size ( in bytes ) of the specified value when encoded as a variable length integer . [CODESPLIT] public static int sizeOfVLong ( long value ) { if ( value < 0L ) return 10 ; if ( value < 0x80 L ) return 1 ; if ( value < 0x4000 L ) return 2 ; if ( value < 0x200000 L ) return 3 ; if ( value < 0x10000000 L ) return 4 ; if ( value < 0x800000000 L ) return 5 ; if ( value < 0x40000000000 L ) return 6 ; if ( value < 0x2000000000000 L ) return 7 ; if ( value < 0x100000000000000 L ) return 8 ; return 9 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the number of variable length integers encoded in the supplied { [CODESPLIT] public static int countVarIntsInRange ( ByteData byteData , long fieldPosition , int length ) { int numInts = 0 ; boolean insideInt = false ; for ( int i = 0 ; i < length ; i ++ ) { byte b = byteData . get ( fieldPosition + i ) ; if ( ( b & 0x80 ) == 0 ) { numInts ++ ; insideInt = false ; } else if ( ! insideInt && b == ( byte ) 0x80 ) { numInts ++ ; } else { insideInt = true ; } } return numInts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_expandable_list ) ; mPullRefreshListView = ( PullToRefreshExpandableListView ) findViewById ( R . id . pull_refresh_expandable_list ) ; // Set a listener to be invoked when the list should be refreshed. mPullRefreshListView . setOnRefreshListener ( new OnRefreshListener < ExpandableListView > ( ) { @ Override public void onRefresh ( PullToRefreshBase < ExpandableListView > refreshView ) { // Do work to refresh the list here. new GetDataTask ( ) . execute ( ) ; } } ) ; for ( String group : mGroupStrings ) { Map < String , String > groupMap1 = new HashMap < String , String > ( ) ; groupData . add ( groupMap1 ) ; groupMap1 . put ( KEY , group ) ; List < Map < String , String > > childList = new ArrayList < Map < String , String > > ( ) ; for ( String string : mChildStrings ) { Map < String , String > childMap = new HashMap < String , String > ( ) ; childList . add ( childMap ) ; childMap . put ( KEY , string ) ; } childData . add ( childList ) ; } mAdapter = new SimpleExpandableListAdapter ( this , groupData , android . R . layout . simple_expandable_list_item_1 , new String [ ] { KEY } , new int [ ] { android . R . id . text1 } , childData , android . R . layout . simple_expandable_list_item_2 , new String [ ] { KEY } , new int [ ] { android . R . id . text1 } ) ; setListAdapter ( mAdapter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used internally for adding view . Need because we override addView to pass - through to the Refreshable View [CODESPLIT] protected final void addViewInternal ( View child , int index , ViewGroup . LayoutParams params ) { super . addView ( child , index , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used internally for { [CODESPLIT] protected LoadingLayoutProxy createLoadingLayoutProxy ( final boolean includeStart , final boolean includeEnd ) { LoadingLayoutProxy proxy = new LoadingLayoutProxy ( ) ; if ( includeStart && mMode . showHeaderLoadingLayout ( ) ) { proxy . addLayout ( mHeaderLayout ) ; } if ( includeEnd && mMode . showFooterLoadingLayout ( ) ) { proxy . addLayout ( mFooterLayout ) ; } return proxy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the UI has been to be updated to be in the { @link State#REFRESHING } or { @link State#MANUAL_REFRESHING } state . [CODESPLIT] protected void onRefreshing ( final boolean doScroll ) { if ( mMode . showHeaderLoadingLayout ( ) ) { mHeaderLayout . refreshing ( ) ; } if ( mMode . showFooterLoadingLayout ( ) ) { mFooterLayout . refreshing ( ) ; } if ( doScroll ) { if ( mShowViewWhileRefreshing ) { // Call Refresh Listener when the Scroll has finished OnSmoothScrollFinishedListener listener = new OnSmoothScrollFinishedListener ( ) { @ Override public void onSmoothScrollFinished ( ) { callRefreshListener ( ) ; } } ; switch ( mCurrentMode ) { case MANUAL_REFRESH_ONLY : case PULL_FROM_END : smoothScrollTo ( getFooterSize ( ) , listener ) ; break ; default : case PULL_FROM_START : smoothScrollTo ( - getHeaderSize ( ) , listener ) ; break ; } } else { smoothScrollTo ( 0 ) ; } } else { // We're not scrolling, so just call Refresh Listener now callRefreshListener ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the UI has been to be updated to be in the { [CODESPLIT] protected void onReset ( ) { mIsBeingDragged = false ; mLayoutVisibilityChangesEnabled = true ; // Always reset both layouts, just in case... mHeaderLayout . reset ( ) ; mFooterLayout . reset ( ) ; smoothScrollTo ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - measure the Loading Views height and adjust internal padding as necessary [CODESPLIT] protected final void refreshLoadingViewsSize ( ) { final int maximumPullScroll = ( int ) ( getMaximumPullScroll ( ) * 1.2f ) ; int pLeft = getPaddingLeft ( ) ; int pTop = getPaddingTop ( ) ; int pRight = getPaddingRight ( ) ; int pBottom = getPaddingBottom ( ) ; switch ( getPullToRefreshScrollDirection ( ) ) { case HORIZONTAL : if ( mMode . showHeaderLoadingLayout ( ) ) { mHeaderLayout . setWidth ( maximumPullScroll ) ; pLeft = - maximumPullScroll ; } else { pLeft = 0 ; } if ( mMode . showFooterLoadingLayout ( ) ) { mFooterLayout . setWidth ( maximumPullScroll ) ; pRight = - maximumPullScroll ; } else { pRight = 0 ; } break ; case VERTICAL : if ( mMode . showHeaderLoadingLayout ( ) ) { mHeaderLayout . setHeight ( maximumPullScroll ) ; pTop = - maximumPullScroll ; } else { pTop = 0 ; } if ( mMode . showFooterLoadingLayout ( ) ) { mFooterLayout . setHeight ( maximumPullScroll ) ; pBottom = - maximumPullScroll ; } else { pBottom = 0 ; } break ; } if ( DEBUG ) { Log . d ( LOG_TAG , String . format ( \"Setting Padding. L: %d, T: %d, R: %d, B: %d\" , pLeft , pTop , pRight , pBottom ) ) ; } setPadding ( pLeft , pTop , pRight , pBottom ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method which just calls scrollTo () in the correct scrolling direction . [CODESPLIT] protected final void setHeaderScroll ( int value ) { if ( DEBUG ) { Log . d ( LOG_TAG , \"setHeaderScroll: \" + value ) ; } // Clamp value to with pull scroll range final int maximumPullScroll = getMaximumPullScroll ( ) ; value = Math . min ( maximumPullScroll , Math . max ( - maximumPullScroll , value ) ) ; if ( mLayoutVisibilityChangesEnabled ) { if ( value < 0 ) { mHeaderLayout . setVisibility ( View . VISIBLE ) ; } else if ( value > 0 ) { mFooterLayout . setVisibility ( View . VISIBLE ) ; } else { mHeaderLayout . setVisibility ( View . INVISIBLE ) ; mFooterLayout . setVisibility ( View . INVISIBLE ) ; } } if ( USE_HW_LAYERS ) { /**\n\t\t\t * Use a Hardware Layer on the Refreshable View if we've scrolled at\n\t\t\t * all. We don't use them on the Header/Footer Views as they change\n\t\t\t * often, which would negate any HW layer performance boost.\n\t\t\t */ ViewCompat . setLayerType ( mRefreshableViewWrapper , value != 0 ? View . LAYER_TYPE_HARDWARE : View . LAYER_TYPE_NONE ) ; } switch ( getPullToRefreshScrollDirection ( ) ) { case VERTICAL : scrollTo ( 0 , value ) ; break ; case HORIZONTAL : scrollTo ( value , 0 ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the View State when the mode has been set . This does not do any checking that the mode is different to current state so always updates . [CODESPLIT] protected void updateUIForMode ( ) { // We need to use the correct LayoutParam values, based on scroll // direction final LinearLayout . LayoutParams lp = getLoadingLayoutLayoutParams ( ) ; // Remove Header, and then add Header Loading View again if needed if ( this == mHeaderLayout . getParent ( ) ) { removeView ( mHeaderLayout ) ; } if ( mMode . showHeaderLoadingLayout ( ) ) { addViewInternal ( mHeaderLayout , 0 , lp ) ; } // Remove Footer, and then add Footer Loading View again if needed if ( this == mFooterLayout . getParent ( ) ) { removeView ( mFooterLayout ) ; } if ( mMode . showFooterLoadingLayout ( ) ) { addViewInternal ( mFooterLayout , lp ) ; } // Hide Loading Views refreshLoadingViewsSize ( ) ; // If we're not using Mode.BOTH, set mCurrentMode to mMode, otherwise // set it to pull down mCurrentMode = ( mMode != Mode . BOTH ) ? mMode : Mode . PULL_FROM_START ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actions a Pull Event [CODESPLIT] private void pullEvent ( ) { final int newScrollValue ; final int itemDimension ; final float initialMotionValue , lastMotionValue ; switch ( getPullToRefreshScrollDirection ( ) ) { case HORIZONTAL : initialMotionValue = mInitialMotionX ; lastMotionValue = mLastMotionX ; break ; case VERTICAL : default : initialMotionValue = mInitialMotionY ; lastMotionValue = mLastMotionY ; break ; } switch ( mCurrentMode ) { case PULL_FROM_END : newScrollValue = Math . round ( Math . max ( initialMotionValue - lastMotionValue , 0 ) / FRICTION ) ; itemDimension = getFooterSize ( ) ; break ; case PULL_FROM_START : default : newScrollValue = Math . round ( Math . min ( initialMotionValue - lastMotionValue , 0 ) / FRICTION ) ; itemDimension = getHeaderSize ( ) ; break ; } setHeaderScroll ( newScrollValue ) ; if ( newScrollValue != 0 && ! isRefreshing ( ) ) { float scale = Math . abs ( newScrollValue ) / ( float ) itemDimension ; switch ( mCurrentMode ) { case PULL_FROM_END : mFooterLayout . onPull ( scale ) ; break ; case PULL_FROM_START : default : mHeaderLayout . onPull ( scale ) ; break ; } if ( mState != State . PULL_TO_REFRESH && itemDimension >= Math . abs ( newScrollValue ) ) { setState ( State . PULL_TO_REFRESH ) ; } else if ( mState == State . PULL_TO_REFRESH && itemDimension < Math . abs ( newScrollValue ) ) { setState ( State . RELEASE_TO_REFRESH ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_horizontalscrollview ) ; mPullRefreshScrollView = ( PullToRefreshHorizontalScrollView ) findViewById ( R . id . pull_refresh_horizontalscrollview ) ; mPullRefreshScrollView . setOnRefreshListener ( new OnRefreshListener < HorizontalScrollView > ( ) { @ Override public void onRefresh ( PullToRefreshBase < HorizontalScrollView > refreshView ) { new GetDataTask ( ) . execute ( ) ; } } ) ; mScrollView = mPullRefreshScrollView . getRefreshableView ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_list_fragment ) ; mPullRefreshListFragment = ( PullToRefreshListFragment ) getSupportFragmentManager ( ) . findFragmentById ( R . id . frag_ptr_list ) ; // Get PullToRefreshListView from Fragment mPullRefreshListView = mPullRefreshListFragment . getPullToRefreshListView ( ) ; // Set a listener to be invoked when the list should be refreshed. mPullRefreshListView . setOnRefreshListener ( this ) ; // You can also just use mPullRefreshListFragment.getListView() ListView actualListView = mPullRefreshListView . getRefreshableView ( ) ; mListItems = new LinkedList < String > ( ) ; mListItems . addAll ( Arrays . asList ( mStrings ) ) ; mAdapter = new ArrayAdapter < String > ( this , android . R . layout . simple_list_item_1 , mListItems ) ; // You can also just use setListAdapter(mAdapter) or // mPullRefreshListView.setAdapter(mAdapter) actualListView . setAdapter ( mAdapter ) ; mPullRefreshListFragment . setListShown ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_webview2 ) ; PullToRefreshWebView2 pullRefreshWebView = ( PullToRefreshWebView2 ) findViewById ( R . id . pull_refresh_webview2 ) ; pullRefreshWebView . setOnRefreshListener ( this ) ; WebView webView = pullRefreshWebView . getRefreshableView ( ) ; webView . getSettings ( ) . setJavaScriptEnabled ( true ) ; webView . setWebViewClient ( new SampleWebViewClient ( ) ) ; // We just load a prepared HTML page from the assets folder for this // sample, see that file for the Javascript implementation webView . loadUrl ( \"file:///android_asset/ptr_webview2_sample.html\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_list ) ; mPullRefreshListView = ( PullToRefreshListView ) findViewById ( R . id . pull_refresh_list ) ; // Set a listener to be invoked when the list should be refreshed. mPullRefreshListView . setOnRefreshListener ( new OnRefreshListener < ListView > ( ) { @ Override public void onRefresh ( PullToRefreshBase < ListView > refreshView ) { String label = DateUtils . formatDateTime ( getApplicationContext ( ) , System . currentTimeMillis ( ) , DateUtils . FORMAT_SHOW_TIME | DateUtils . FORMAT_SHOW_DATE | DateUtils . FORMAT_ABBREV_ALL ) ; // Update the LastUpdatedLabel refreshView . getLoadingLayoutProxy ( ) . setLastUpdatedLabel ( label ) ; // Do work to refresh the list here. new GetDataTask ( ) . execute ( ) ; } } ) ; // Add an end-of-list listener mPullRefreshListView . setOnLastItemVisibleListener ( new OnLastItemVisibleListener ( ) { @ Override public void onLastItemVisible ( ) { Toast . makeText ( PullToRefreshListActivity . this , \"End of List!\" , Toast . LENGTH_SHORT ) . show ( ) ; } } ) ; ListView actualListView = mPullRefreshListView . getRefreshableView ( ) ; // Need to use the Actual ListView when registering for Context Menu registerForContextMenu ( actualListView ) ; mListItems = new LinkedList < String > ( ) ; mListItems . addAll ( Arrays . asList ( mStrings ) ) ; mAdapter = new ArrayAdapter < String > ( this , android . R . layout . simple_list_item_1 , mListItems ) ; /**\n\t\t * Add Sound Event Listener\n\t\t */ SoundPullEventListener < ListView > soundListener = new SoundPullEventListener < ListView > ( this ) ; soundListener . addSoundEvent ( State . PULL_TO_REFRESH , R . raw . pull_event ) ; soundListener . addSoundEvent ( State . RESET , R . raw . reset_sound ) ; soundListener . addSoundEvent ( State . REFRESHING , R . raw . refreshing_sound ) ; mPullRefreshListView . setOnPullEventListener ( soundListener ) ; // You can also just use setListAdapter(mAdapter) or // mPullRefreshListView.setAdapter(mAdapter) actualListView . setAdapter ( mAdapter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_webview ) ; mPullRefreshWebView = ( PullToRefreshWebView ) findViewById ( R . id . pull_refresh_webview ) ; mWebView = mPullRefreshWebView . getRefreshableView ( ) ; mWebView . getSettings ( ) . setJavaScriptEnabled ( true ) ; mWebView . setWebViewClient ( new SampleWebViewClient ( ) ) ; mWebView . loadUrl ( \"http://www.google.com\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_scrollview ) ; mPullRefreshScrollView = ( PullToRefreshScrollView ) findViewById ( R . id . pull_refresh_scrollview ) ; mPullRefreshScrollView . setOnRefreshListener ( new OnRefreshListener < ScrollView > ( ) { @ Override public void onRefresh ( PullToRefreshBase < ScrollView > refreshView ) { new GetDataTask ( ) . execute ( ) ; } } ) ; mScrollView = mPullRefreshScrollView . getRefreshableView ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for Overscrolling that encapsulates all of the necessary function . <p / > This should only be used on AdapterView s such as ListView as it just calls through to overScrollBy () with the scrollRange = 0 . AdapterView s do not have a scroll range ( i . e . getScrollY () doesn t work ) . [CODESPLIT] public static void overScrollBy ( final PullToRefreshBase < ? > view , final int deltaX , final int scrollX , final int deltaY , final int scrollY , final boolean isTouchEvent ) { overScrollBy ( view , deltaX , scrollX , deltaY , scrollY , 0 , isTouchEvent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for Overscrolling that encapsulates all of the necessary function . This is the advanced version of the call . [CODESPLIT] public static void overScrollBy ( final PullToRefreshBase < ? > view , final int deltaX , final int scrollX , final int deltaY , final int scrollY , final int scrollRange , final int fuzzyThreshold , final float scaleFactor , final boolean isTouchEvent ) { final int deltaValue , currentScrollValue , scrollValue ; switch ( view . getPullToRefreshScrollDirection ( ) ) { case HORIZONTAL : deltaValue = deltaX ; scrollValue = scrollX ; currentScrollValue = view . getScrollX ( ) ; break ; case VERTICAL : default : deltaValue = deltaY ; scrollValue = scrollY ; currentScrollValue = view . getScrollY ( ) ; break ; } // Check that OverScroll is enabled and that we're not currently // refreshing. if ( view . isPullToRefreshOverScrollEnabled ( ) && ! view . isRefreshing ( ) ) { final Mode mode = view . getMode ( ) ; // Check that Pull-to-Refresh is enabled, and the event isn't from // touch if ( mode . permitsPullToRefresh ( ) && ! isTouchEvent && deltaValue != 0 ) { final int newScrollValue = ( deltaValue + scrollValue ) ; if ( PullToRefreshBase . DEBUG ) { Log . d ( LOG_TAG , \"OverScroll. DeltaX: \" + deltaX + \", ScrollX: \" + scrollX + \", DeltaY: \" + deltaY + \", ScrollY: \" + scrollY + \", NewY: \" + newScrollValue + \", ScrollRange: \" + scrollRange + \", CurrentScroll: \" + currentScrollValue ) ; } if ( newScrollValue < ( 0 - fuzzyThreshold ) ) { // Check the mode supports the overscroll direction, and // then move scroll if ( mode . showHeaderLoadingLayout ( ) ) { // If we're currently at zero, we're about to start // overscrolling, so change the state if ( currentScrollValue == 0 ) { view . setState ( State . OVERSCROLLING ) ; } view . setHeaderScroll ( ( int ) ( scaleFactor * ( currentScrollValue + newScrollValue ) ) ) ; } } else if ( newScrollValue > ( scrollRange + fuzzyThreshold ) ) { // Check the mode supports the overscroll direction, and // then move scroll if ( mode . showFooterLoadingLayout ( ) ) { // If we're currently at zero, we're about to start // overscrolling, so change the state if ( currentScrollValue == 0 ) { view . setState ( State . OVERSCROLLING ) ; } view . setHeaderScroll ( ( int ) ( scaleFactor * ( currentScrollValue + newScrollValue - scrollRange ) ) ) ; } } else if ( Math . abs ( newScrollValue ) <= fuzzyThreshold || Math . abs ( newScrollValue - scrollRange ) <= fuzzyThreshold ) { // Means we've stopped overscrolling, so scroll back to 0 view . setState ( State . RESET ) ; } } else if ( isTouchEvent && State . OVERSCROLLING == view . getState ( ) ) { // This condition means that we were overscrolling from a fling, // but the user has touched the View and is now overscrolling // from touch instead. We need to just reset. view . setState ( State . RESET ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_ptr_grid ) ; mPullRefreshGridView = ( PullToRefreshGridView ) findViewById ( R . id . pull_refresh_grid ) ; mGridView = mPullRefreshGridView . getRefreshableView ( ) ; // Set a listener to be invoked when the list should be refreshed. mPullRefreshGridView . setOnRefreshListener ( new OnRefreshListener2 < GridView > ( ) { @ Override public void onPullDownToRefresh ( PullToRefreshBase < GridView > refreshView ) { Toast . makeText ( PullToRefreshGridActivity . this , \"Pull Down!\" , Toast . LENGTH_SHORT ) . show ( ) ; new GetDataTask ( ) . execute ( ) ; } @ Override public void onPullUpToRefresh ( PullToRefreshBase < GridView > refreshView ) { Toast . makeText ( PullToRefreshGridActivity . this , \"Pull Up!\" , Toast . LENGTH_SHORT ) . show ( ) ; new GetDataTask ( ) . execute ( ) ; } } ) ; mListItems = new LinkedList < String > ( ) ; TextView tv = new TextView ( this ) ; tv . setGravity ( Gravity . CENTER ) ; tv . setText ( \"Empty View, Pull Down/Up to Add Items\" ) ; mPullRefreshGridView . setEmptyView ( tv ) ; mAdapter = new ArrayAdapter < String > ( this , android . R . layout . simple_list_item_1 , mListItems ) ; mGridView . setAdapter ( mAdapter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the Empty View to be used by the Adapter View . <p / > We need it handle it ourselves so that we can Pull - to - Refresh when the Empty View is shown . <p / > Please note you do <strong > not< / strong > usually need to call this method yourself . Calling setEmptyView on the AdapterView will automatically call this method and set everything up . This includes when the Android Framework automatically sets the Empty View based on it s ID . [CODESPLIT] public final void setEmptyView ( View newEmptyView ) { FrameLayout refreshableViewWrapper = getRefreshableViewWrapper ( ) ; if ( null != newEmptyView ) { // New view needs to be clickable so that Android recognizes it as a // target for Touch Events newEmptyView . setClickable ( true ) ; ViewParent newEmptyViewParent = newEmptyView . getParent ( ) ; if ( null != newEmptyViewParent && newEmptyViewParent instanceof ViewGroup ) { ( ( ViewGroup ) newEmptyViewParent ) . removeView ( newEmptyView ) ; } // We need to convert any LayoutParams so that it works in our // FrameLayout FrameLayout . LayoutParams lp = convertEmptyViewLayoutParams ( newEmptyView . getLayoutParams ( ) ) ; if ( null != lp ) { refreshableViewWrapper . addView ( newEmptyView , lp ) ; } else { refreshableViewWrapper . addView ( newEmptyView ) ; } } if ( mRefreshableView instanceof EmptyViewMethodAccessor ) { ( ( EmptyViewMethodAccessor ) mRefreshableView ) . setEmptyViewInternal ( newEmptyView ) ; } else { mRefreshableView . setEmptyView ( newEmptyView ) ; } mEmptyView = newEmptyView ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the condition for the Rule . [CODESPLIT] public WhenRuleBuilder < T , U > when ( Predicate < NameValueReferableTypeConvertibleMap < T > > condition ) { return new WhenRuleBuilder <> ( _rule , condition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the current Rule s action and then moves down the chain to the successor if the RuleState of the current Rule is next or the action ( s ) was not executed . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public void handleRequest ( Object obj ) { boolean actionResult = _rule . invoke ( ( NameValueReferableMap ) obj ) ; if ( ! actionResult || _rule . getRuleState ( ) == RuleState . NEXT ) { getSuccessor ( ) . ifPresent ( handler -> { _rule . getResult ( ) . ifPresent ( result -> handler . getDelegate ( ) . setResult ( ( Result ) result ) ) ; handler . handleRequest ( obj ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method getOne () gets the value of the single Fact in the FactMap . [CODESPLIT] @ Override public T getOne ( ) { if ( _facts . size ( ) == 1 ) { return _facts . values ( ) . iterator ( ) . next ( ) . getValue ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method getValue () returns the value of the Fact associated with the name passed in . [CODESPLIT] @ Override public T getValue ( String name ) { return Optional . ofNullable ( _facts . get ( name ) ) . map ( NameValueReferable :: getValue ) . orElse ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getStrVal () gets the String value of a Fact in the FactMap . [CODESPLIT] @ Deprecated public String getStrVal ( String name ) { if ( getValue ( name ) instanceof String ) { return ( String ) getValue ( name ) ; } return String . valueOf ( getValue ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getIntVal () gets the Integer value of a Fact in the FactMap . [CODESPLIT] @ Deprecated public Integer getIntVal ( String name ) { Object value = getValue ( name ) ; if ( value != null ) { if ( Integer . class == value . getClass ( ) ) { return ( Integer ) value ; } if ( value . getClass ( ) == String . class ) { return Integer . valueOf ( ( String ) value ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getDblVal () gets the Double value of a Fact in the FactMap . [CODESPLIT] @ Deprecated public Double getDblVal ( String name ) { Object value = getValue ( name ) ; if ( value != null ) { if ( Float . class == value . getClass ( ) ) { return Double . valueOf ( ( Float ) value ) ; } if ( Double . class == value . getClass ( ) ) { return ( Double ) value ; } if ( Integer . class == value . getClass ( ) ) { return Double . valueOf ( ( Integer ) value ) ; } if ( Long . class == value . getClass ( ) ) { return Double . valueOf ( ( Long ) value ) ; } if ( String . class == value . getClass ( ) ) { return Double . parseDouble ( ( String ) value ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method setValue sets the value of the Fact by its name . <br / > If no Fact exists with the associated name a new fact is created with the specified name and value . <br / > [CODESPLIT] public void setValue ( String name , T value ) { NameValueReferable < T > fact = _facts . get ( name ) ; if ( fact == null ) { fact = new Fact <> ( name , value ) ; _facts . put ( name , fact ) ; return ; } fact . setValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This put () method is a convenience method for adding a Fact to a FactMap . <br / > It uses the name of the Fact as the key and the Fact as the value . [CODESPLIT] @ Override public Fact < T > put ( NameValueReferable < T > fact ) { return put ( fact . getName ( ) , fact ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a fact to the Rule . [CODESPLIT] GivenRuleBuilder < T , U > given ( String name , T value ) { return given ( new Fact < T > ( name , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds one or more facts into the Rule . [CODESPLIT] @ SafeVarargs public final GivenRuleBuilder < T , U > given ( NameValueReferable ... facts ) { _rule . addFacts ( facts ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a using constraint in the Rule that restricts the facts supplied to the subsequent then action . [CODESPLIT] public UsingRuleBuilder < T , U > using ( String ... factNames ) { return new UsingRuleBuilder < T , U > ( _rule , factNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new RuleBuilder for the specified Rule class . [CODESPLIT] public static RuleBuilder < Object , Object > create ( Class < ? extends Rule > ruleClass , RuleChainActionType actionType ) { return new RuleBuilder <> ( ruleClass , actionType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new RuleBuilder for the default Rule type . [CODESPLIT] public static RuleBuilder < Object , Object > create ( ) { RuleBuilder < Object , Object > rule = new RuleBuilder <> ( GoldenRule . class ) ; rule . _factType = Object . class ; return rule ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the fact type for the Rule being built . [CODESPLIT] public < S > RuleBuilder < S , U > withFactType ( Class < S > factType ) { RuleBuilder < S , U > builder = new RuleBuilder <> ( _ruleClass ) ; builder . _factType = factType ; builder . _resultType = _resultType ; builder . _actionType = _actionType ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the Result type for the Rule being built . [CODESPLIT] public < S > RuleBuilder < T , S > withResultType ( Class < S > resultType ) { RuleBuilder < T , S > builder = new RuleBuilder <> ( _ruleClass ) ; builder . _factType = _factType ; builder . _resultType = resultType ; builder . _actionType = _actionType ; builder . _name = _name ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a fact to the Rule using a name value pair to specify a new fact . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public GivenRuleBuilder < T , U > given ( String name , T value ) { Rule < T , U > rule = _name . map ( ruleName -> ( Rule < T , U > ) new AuditableRule < T , U > ( newRule ( ) , ruleName ) ) . orElse ( newRule ( ) ) ; if ( rule == null ) { throw new IllegalStateException ( \"No Rule is instantiated; An invalid Rule class may have been provided\" ) ; } return new GivenRuleBuilder < T , U > ( rule , new Fact < T > ( name , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds one or more facts to the Rule . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ SafeVarargs public final GivenRuleBuilder < T , U > given ( NameValueReferable ... facts ) { Rule < T , U > rule = _name . map ( name -> ( Rule < T , U > ) new AuditableRule < T , U > ( newRule ( ) , name ) ) . orElse ( newRule ( ) ) ; if ( rule == null ) { throw new IllegalStateException ( \"No Rule is instantiated; An invalid Rule class may have been provided\" ) ; } return new GivenRuleBuilder < T , U > ( rule , facts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the condition for the Rule . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public WhenRuleBuilder < T , U > when ( Predicate < NameValueReferableTypeConvertibleMap < T > > condition ) { Rule < T , U > rule = _name . map ( name -> ( Rule < T , U > ) new AuditableRule < T , U > ( newRule ( ) , name ) ) . orElse ( newRule ( ) ) ; if ( rule == null ) { throw new IllegalStateException ( \"No Rule is instantiated; An invalid Rule class may have been provided\" ) ; } return new WhenRuleBuilder < T , U > ( rule , condition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a using constraint in the Rule that restricts the facts supplied to the subsequent then action . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public UsingRuleBuilder < T , U > using ( String ... factNames ) { Rule < T , U > rule = _name . map ( name -> ( Rule < T , U > ) new AuditableRule < T , U > ( newRule ( ) , name ) ) . orElse ( newRule ( ) ) ; if ( rule == null ) { throw new IllegalStateException ( \"No Rule is instantiated; An invalid Rule class may have been provided\" ) ; } return new UsingRuleBuilder < T , U > ( rule , factNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an action as a Consumer to the Rule . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public ThenRuleBuilder < T , U > then ( Consumer < NameValueReferableTypeConvertibleMap < T > > action ) { Rule < T , U > rule = _name . map ( name -> ( Rule < T , U > ) new AuditableRule < T , U > ( newRule ( ) , name ) ) . orElse ( newRule ( ) ) ; if ( rule == null ) { throw new IllegalStateException ( \"No Rule is instantiated; An invalid Rule class may have been provided\" ) ; } return new ThenRuleBuilder < T , U > ( rule , action ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the Facts to properties with the [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void mapFactsToProperties ( NameValueReferableMap facts ) { for ( Field field : getAnnotatedFields ( Given . class , _pojoRule . getClass ( ) ) ) { Given given = field . getAnnotation ( Given . class ) ; try { field . setAccessible ( true ) ; if ( NameValueReferable . class . isAssignableFrom ( field . getType ( ) ) ) { field . set ( _pojoRule , facts . get ( given . value ( ) ) ) ; } else { Object value = facts . getValue ( given . value ( ) ) ; if ( value != null ) { //set the field to the Fact that has the name of the @Given value field . set ( _pojoRule , value ) ; } else if ( NameValueReferableMap . class . isAssignableFrom ( field . getType ( ) ) ) { //if the field is a FactMap then give it the FactMap field . set ( _pojoRule , facts ) ; } else if ( Collection . class . isAssignableFrom ( field . getType ( ) ) ) { //set a Collection of Fact object values Stream stream = facts . values ( ) . stream ( ) . filter ( fact -> { //filter on only facts that contain objects matching the generic type ParameterizedType paramType = ( ParameterizedType ) field . getGenericType ( ) ; Class < ? > genericType = ( Class < ? > ) paramType . getActualTypeArguments ( ) [ 0 ] ; return genericType . equals ( ( ( NameValueReferable ) fact ) . getValue ( ) . getClass ( ) ) ; } ) . map ( fact -> { ParameterizedType paramType = ( ParameterizedType ) field . getGenericType ( ) ; Class < ? > genericType = ( Class < ? > ) paramType . getActualTypeArguments ( ) [ 0 ] ; return genericType . cast ( ( ( NameValueReferable ) fact ) . getValue ( ) ) ; } ) ; if ( List . class == field . getType ( ) ) { //map List of Fact values to field field . set ( _pojoRule , stream . collect ( Collectors . toList ( ) ) ) ; } else if ( Set . class == field . getType ( ) ) { //map Set of Fact values to field field . set ( _pojoRule , stream . collect ( Collectors . toSet ( ) ) ) ; } } else if ( Map . class == field . getType ( ) ) { //map Map of Fact values to field Map map = ( Map ) facts . keySet ( ) . stream ( ) . filter ( key -> { ParameterizedType paramType = ( ParameterizedType ) field . getGenericType ( ) ; Class < ? > genericType = ( Class < ? > ) paramType . getActualTypeArguments ( ) [ 1 ] ; return genericType . equals ( facts . getValue ( ( String ) key ) . getClass ( ) ) ; } ) . collect ( Collectors . toMap ( key -> key , key -> facts . getValue ( ( String ) key ) ) ) ; field . set ( _pojoRule , map ) ; } } } catch ( Exception ex ) { LOGGER . error ( \"Unable to update field '\" + field . getName ( ) + \"' in rule object '\" + _pojoRule . getClass ( ) + \"'\" , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a rule instance [CODESPLIT] protected Object getRuleInstance ( Class < ? > rule ) { try { return rule . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException ex ) { LOGGER . warn ( \"Unable to create instance of rule using '\" + rule + \"'\" , ex ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The run () method adds the rules [ via defineRules () ] and runs the rules as long as at least one rule was added . [CODESPLIT] public final void run ( ) { if ( _headRule . isPresent ( ) == false ) { defineRules ( ) ; } _headRule . ifPresent ( rule -> rule . given ( _facts ) ) ; _headRule . ifPresent ( Rule :: run ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given () method accepts the Facts for this RuleBook . The facts passed in will also be applied to all rules added to this RuleBook . [CODESPLIT] @ SafeVarargs public final RuleBook < T > given ( Fact < T > ... facts ) { Arrays . stream ( facts ) . forEach ( _facts :: add ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given () method accepts a key / value pair as a Fact for this RuleBook . [CODESPLIT] public RuleBook < T > given ( String name , T value ) { _facts . add ( new Fact < T > ( name , value ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The addRule () method adds a rule to the end of the Rules chain . [CODESPLIT] public void addRule ( Rule < T > rule ) { if ( rule == null ) { return ; } if ( ! _headRule . isPresent ( ) ) { _headRule = Optional . of ( rule ) ; // this rule is the head if there was no head _tailRule = rule ; } else { _tailRule . setNextRule ( rule ) ; _tailRule = rule ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getAnnotatedFields gets the fields annotated of a specific type from the class and its parent classes . <br / > The List is in order of closest parent = > current obj fields parent obj fields etc . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static List < Field > getAnnotatedFields ( Class annotation , Class clazz ) { if ( clazz == Object . class ) { return new ArrayList <> ( ) ; } List < Field > fields = ( List < Field > ) Arrays . stream ( clazz . getDeclaredFields ( ) ) . filter ( field -> field . getAnnotation ( annotation ) != null ) . collect ( Collectors . toList ( ) ) ; if ( clazz . getSuperclass ( ) != null ) { fields . addAll ( getAnnotatedFields ( annotation , clazz . getSuperclass ( ) ) ) ; } return fields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getAnnotatedField gets the first annotated field of the type of annotation specified . [CODESPLIT] public static Optional < Field > getAnnotatedField ( Class annotation , Class clazz ) { List < Field > fields = getAnnotatedFields ( annotation , clazz ) ; return Optional . ofNullable ( fields . size ( ) > 0 ? fields . get ( 0 ) : null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getAnnotatedMethods gets the methods annotated of a specific type from the class and its parent classes . <br / > The List is in order of closest parent = > current obj methods parent obj methods etc . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static List < Method > getAnnotatedMethods ( Class annotation , Class clazz ) { List < Method > methods = new ArrayList <> ( ) ; if ( clazz == Object . class ) { return methods ; } methods . addAll ( ( List < Method > ) Arrays . stream ( clazz . getDeclaredMethods ( ) ) . filter ( field -> field . getAnnotation ( annotation ) != null ) . collect ( Collectors . toList ( ) ) ) ; methods . addAll ( getAnnotatedMethods ( annotation , clazz . getSuperclass ( ) ) ) ; return methods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getAnnotatedMethod the first annotated method of the type of annotation specified . [CODESPLIT] public static Optional < Method > getAnnotatedMethod ( Class annotation , Class clazz ) { List < Method > methods = getAnnotatedMethods ( annotation , clazz ) ; return Optional . ofNullable ( methods . size ( ) > 0 ? methods . get ( 0 ) : null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method getAnnotation returns the annotation on a class or its parent annotation . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < A extends Annotation > A getAnnotation ( Class < A > annotation , Class < ? > clazz ) { return Optional . ofNullable ( clazz . getAnnotation ( annotation ) ) . orElse ( ( A ) Arrays . stream ( clazz . getDeclaredAnnotations ( ) ) . flatMap ( anno -> Arrays . stream ( anno . getClass ( ) . getInterfaces ( ) ) . flatMap ( iface -> Arrays . stream ( iface . getDeclaredAnnotations ( ) ) ) ) . filter ( annotation :: isInstance ) . findFirst ( ) . orElse ( null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This create () method is a convenience method to avoid using new and generic syntax . [CODESPLIT] public static < T , U > StandardDecision < T , U > create ( Class < T > factType , Class < U > resultType ) { return new StandardDecision < T , U > ( factType , resultType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given () method accepts a name / value pair to be used as a Fact . [CODESPLIT] @ Override public Decision < T , U > given ( String name , T value ) { _rule . given ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given () method accepts Facts for the StandardDecision . [CODESPLIT] @ Override public Decision < T , U > given ( Fact < T > ... facts ) { _rule . given ( facts ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given () method accepts Facts for the StandardDecision . [CODESPLIT] @ Override public Decision < T , U > given ( FactMap < T > facts ) { _rule . given ( facts ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The when () method accepts a { [CODESPLIT] @ Override public Decision < T , U > when ( Predicate < FactMap < T > > test ) { _rule . when ( test ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The then () method accepts a { [CODESPLIT] @ Override public Decision < T , U > then ( BiConsumer < FactMap < T > , Result < U > > action ) { _rule . getThen ( ) . add ( action ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The then () method accepts a { [CODESPLIT] @ Override public Decision < T , U > then ( Consumer < FactMap < T > > action ) { _rule . then ( action ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The using () method reduces the facts to those specifically named here . The using () method only applies to the then () method immediately following it . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public Decision < T , U > using ( String ... factNames ) { _rule . using ( factNames ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a rule to be audited . [CODESPLIT] public void registerRule ( Auditable rule ) { _lock . writeLock ( ) . lock ( ) ; try { _auditMap . put ( rule . getName ( ) , new HashMap <> ( ) ) ; } finally { _lock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the status of the rule & stores the status with the Auditor . [CODESPLIT] public void updateRuleStatus ( Auditable rule , RuleStatus status ) { _lock . readLock ( ) . lock ( ) ; try { if ( _auditMap . containsKey ( rule . getName ( ) ) ) { _lock . readLock ( ) . unlock ( ) ; _lock . writeLock ( ) . lock ( ) ; try { _auditMap . get ( rule . getName ( ) ) . put ( Thread . currentThread ( ) . getId ( ) , status ) ; _lock . readLock ( ) . lock ( ) ; } finally { _lock . writeLock ( ) . unlock ( ) ; } } } finally { _lock . readLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a map of each rule name with its associated status . [CODESPLIT] public Map < String , RuleStatus > getRuleStatusMap ( ) { _lock . readLock ( ) . lock ( ) ; try { return _auditMap . keySet ( ) . stream ( ) . collect ( Collectors . toMap ( key -> key , key -> _auditMap . get ( key ) . getOrDefault ( Thread . currentThread ( ) . getId ( ) , RuleStatus . PENDING ) ) ) ; } finally { _lock . readLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the Result type for the RuleBook . [CODESPLIT] public < U > RuleBookWithResultTypeBuilder < U > withResultType ( Class < U > resultType ) { _resultType = resultType ; return new RuleBookWithResultTypeBuilder < U > ( ( new RuleBookBuilder < U > ( this ) ) . newRuleBook ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a rule to the RuleBook . [CODESPLIT] public RuleBookAddRuleBuilder < T > addRule ( Consumer < RuleBookRuleBuilder < T > > consumer ) { return new RuleBookAddRuleBuilder <> ( newRuleBook ( ) , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a rule to the RuleBook . [CODESPLIT] public < U > RuleBookAddRuleBuilder < T > addRule ( Rule < U , T > rule ) { return new RuleBookAddRuleBuilder <> ( newRuleBook ( ) , rule ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The run ( Object [] ) method runs the { [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public void run ( Object ... otherArgs ) { try { //only use facts of the specified type FactMap < T > typeFilteredFacts = new FactMap < T > ( ( Map < String , NameValueReferable < T > > ) _facts . values ( ) . stream ( ) . filter ( ( Object fact ) -> _factType . isAssignableFrom ( ( ( Fact ) fact ) . getValue ( ) . getClass ( ) ) ) . collect ( Collectors . toMap ( fact -> ( ( Fact ) fact ) . getName ( ) , fact -> ( Fact < T > ) fact ) ) ) ; //invoke then() action(s) if when() is true or if when() was never specified if ( getWhen ( ) == null || getWhen ( ) . test ( typeFilteredFacts ) ) { //iterate through the then() actions specified List < Object > actionList = getThen ( ) ; for ( int i = 0 ; i < ( getThen ( ) ) . size ( ) ; i ++ ) { Object action = actionList . get ( i ) ; List < String > factNames = _factNameMap . get ( i ) ; //if using() fact names were specified for the specific then(), use only those facts specified FactMap < T > usingFacts ; if ( factNames != null ) { usingFacts = new FactMap < T > ( factNames . stream ( ) . filter ( typeFilteredFacts :: containsKey ) . collect ( Collectors . toMap ( name -> name , name -> _facts . get ( name ) ) ) ) ; } else { usingFacts = typeFilteredFacts ; } //invoke the action Stream . of ( action . getClass ( ) . getMethods ( ) ) . filter ( method -> method . getName ( ) . equals ( \"accept\" ) ) . findFirst ( ) . ifPresent ( method -> { try { method . setAccessible ( true ) ; method . invoke ( action , ArrayUtils . combine ( new Object [ ] { usingFacts } , otherArgs , method . getParameterCount ( ) ) ) ; } catch ( IllegalAccessException | InvocationTargetException err ) { LOGGER . error ( \"Error invoking action on \" + action . getClass ( ) , err ) ; } } ) ; } //if stop() was invoked, stop the rule chain after then is finished executing if ( _ruleState == BREAK ) { return ; } } } catch ( Exception ex ) { //catch errors in case something like one rule was chained expecting a Fact that doesn't exist //eventually, we'll have to resolve that kind of issue ahead of time LOGGER . error ( \"Error occurred when trying to evaluate rule!\" , ex ) ; } //continue down the rule chain _nextRule . ifPresent ( rule -> rule . given ( _facts ) ) ; _nextRule . ifPresent ( Rule :: run ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given () method accepts a name / value pair to be used as a Fact . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public Rule < T > given ( String name , T value ) { _facts . put ( name , new Fact < T > ( name , value ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given () method accepts Facts to be evaluated in the Rule . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public Rule < T > given ( Fact < T > ... facts ) { for ( Fact f : facts ) { _facts . put ( f . getName ( ) , f ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The when () method accepts a { [CODESPLIT] @ Override public Rule < T > when ( Predicate < FactMap < T > > test ) { _test = test ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The then () method accepts a { @link Consumer } that performs an action based on Facts . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public Rule < T > then ( Consumer < FactMap < T > > action ) { _actionChain . add ( action ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The using () method reduces the facts to those specifically named here . The using () method only applies to the then () method immediately following it . [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public StandardRule < T > using ( String ... factNames ) { List < String > factNameList = Stream . of ( factNames ) . filter ( name -> _factType . isInstance ( _facts . getValue ( name ) ) ) . collect ( Collectors . toList ( ) ) ; if ( _factNameMap . containsKey ( ( getThen ( ) ) . size ( ) ) ) { List < String > existingFactNames = _factNameMap . get ( ( getThen ( ) ) . size ( ) ) ; existingFactNames . addAll ( factNameList ) ; return this ; } _factNameMap . put ( ( getThen ( ) ) . size ( ) , factNameList ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The addRule () method allows a rule to be added to the DecisionBook in the abstract defineRules method . [CODESPLIT] public void addRule ( Decision < T , U > rule ) { if ( rule == null ) { return ; } super . addRule ( rule ) ; rule . setResult ( _result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a then action into the Rule . [CODESPLIT] public ThenRuleBuilder < T , U > then ( Consumer < NameValueReferableTypeConvertibleMap < T > > action ) { _rule . addAction ( action ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Addds a then action into the Rule . [CODESPLIT] public ThenRuleBuilder < T , U > then ( BiConsumer < NameValueReferableTypeConvertibleMap < T > , Result < U > > action ) { _rule . addAction ( action ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the default Result value . Note : RuleBooks that return a single Result must have a default Result value set . [CODESPLIT] public RuleBookDefaultResultBuilder < T > withDefaultResult ( T result ) { _ruleBook . setDefaultResult ( result ) ; return new RuleBookDefaultResultBuilder <> ( _ruleBook ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the value of the Result to its default value . [CODESPLIT] public void reset ( ) { _lock . readLock ( ) . lock ( ) ; try { if ( _defaultValue == null ) { return ; } } finally { _lock . readLock ( ) . unlock ( ) ; } setValue ( _defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method getValue () returns the object contained in the Result object . [CODESPLIT] @ Override public T getValue ( ) { _lock . readLock ( ) . lock ( ) ; try { long key = Thread . currentThread ( ) . getId ( ) ; if ( _valueMap . containsKey ( key ) ) { return _valueMap . get ( Thread . currentThread ( ) . getId ( ) ) ; } return _defaultValue ; } finally { _lock . readLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method setValue () sets the object to be contained in the Result object . [CODESPLIT] @ Override public void setValue ( T value ) { _lock . writeLock ( ) . lock ( ) ; try { _valueMap . put ( Thread . currentThread ( ) . getId ( ) , value ) ; } finally { _lock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a rule to the RuleBook . [CODESPLIT] public RuleBookAddRuleBuilder < T > addRule ( Consumer < RuleBookRuleBuilder < T > > consumer ) { return new RuleBookAddRuleBuilder <> ( _ruleBook , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a rule to the RuleBook . [CODESPLIT] public < U > RuleBookAddRuleBuilder < T > addRule ( Rule < U , T > rule ) { return new RuleBookAddRuleBuilder <> ( _ruleBook , rule ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the fact type [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > RuleBookRuleWithFactTypeBuilder < T , U > withFactType ( Class < T > factType ) { Rule < T , U > rule = ( Rule < T , U > ) RuleBuilder . create ( _ruleClass ) . withFactType ( factType ) . build ( ) ; _ruleBook . addRule ( rule ) ; return new RuleBookRuleWithFactTypeBuilder <> ( rule ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the POJO Rules to be used by the RuleBook via reflection of the specified package . [CODESPLIT] protected List < Class < ? > > getPojoRules ( ) { Reflections reflections = new Reflections ( _package ) ; List < Class < ? > > rules = reflections . getTypesAnnotatedWith ( com . deliveredtechnologies . rulebook . annotation . Rule . class ) . stream ( ) . filter ( rule -> rule . getAnnotatedSuperclass ( ) != null ) // Include classes only, exclude interfaces, etc. . filter ( rule -> _subPkgMatch . test ( rule . getPackage ( ) . getName ( ) ) ) . collect ( Collectors . toList ( ) ) ; rules . sort ( comparingInt ( aClass -> getAnnotation ( com . deliveredtechnologies . rulebook . annotation . Rule . class , aClass ) . order ( ) ) ) ; return rules ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The combine () static method combines the contents of two arrays into a single array of the same type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T [ ] combine ( T [ ] array1 , T [ ] array2 ) { return combine ( array1 , array2 , array1 . length + array2 . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The combine () static method combines the contents of two arrays into a single array of the same type that contains no more than the maxElements number of elements . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T [ ] combine ( T [ ] array1 , T [ ] array2 , int maxElements ) { if ( array1 . length == maxElements ) { return array1 ; } else if ( array1 . length > maxElements ) { T [ ] combinedArray = ( T [ ] ) Array . newInstance ( array1 . getClass ( ) . getComponentType ( ) , maxElements ) ; System . arraycopy ( array1 , 0 , combinedArray , 0 , maxElements ) ; return combinedArray ; } maxElements = array1 . length + array2 . length >= maxElements ? maxElements : array1 . length + array2 . length ; T [ ] combinedArray = ( T [ ] ) Array . newInstance ( array1 . getClass ( ) . getComponentType ( ) , maxElements ) ; System . arraycopy ( array1 , 0 , combinedArray , 0 , array1 . length ) ; System . arraycopy ( array2 , 0 , combinedArray , array1 . length , maxElements - array1 . length ) ; return combinedArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads empty line or throw an exception if a none empty line was found . [CODESPLIT] private String readEmptyLineOrEndTable ( final BufferedReader tableContent ) throws IOException { final String column = tableContent . readLine ( ) ; if ( column != null && column . startsWith ( END_TABLE ) ) { return END_TABLE ; } if ( column == null || ! column . isEmpty ( ) ) { throw new IllegalArgumentException ( String . format ( \"Trying to read an empty line for end of row, but content %s was found or EOF\" , column ) ) ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves buffer until it finds the first content column ( skipping headers ) . [CODESPLIT] private void skipUntilColumns ( final BufferedReader tableContent ) throws IOException { String line ; while ( ( line = tableContent . readLine ( ) ) != null ) { if ( line . trim ( ) . isEmpty ( ) ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=========================================================== [CODESPLIT] private ObjectMeta createDeploymentConfigMetaData ( ResourceConfig config ) { return new ObjectMetaBuilder ( ) . withName ( KubernetesHelper . validateKubernetesId ( config . getControllerName ( ) , \"controller name\" ) ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================================= [CODESPLIT] private void addServices ( KubernetesListBuilder builder ) { ResourceConfig resources = new ResourceConfig ( ) ; if ( resources != null && resources . getServices ( ) != null ) { List < ServiceConfig > serviceConfig = resources . getServices ( ) ; ServiceHandler serviceHandler = new ServiceHandler ( ) ; builder . addToServiceItems ( toArray ( serviceHandler . getServices ( serviceConfig ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert list to array never returns null . [CODESPLIT] private Service [ ] toArray ( List < Service > services ) { if ( services == null ) { return new Service [ 0 ] ; } if ( services instanceof ArrayList ) { return ( ( ArrayList < Service > ) services ) . toArray ( new Service [ services . size ( ) ] ) ; } else { Service [ ] ret = new Service [ services . size ( ) ] ; for ( int i = 0 ; i < services . size ( ) ; i ++ ) { ret [ i ] = services . get ( i ) ; } return ret ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ".................................................................................... [CODESPLIT] private Map < String , String > extractLabels ( ) { Map < String , String > labels = new HashMap <> ( ) ; if ( Configs . asBoolean ( getConfig ( Config . expose ) ) ) { labels . put ( \"expose\" , \"true\" ) ; } return labels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Port handling [CODESPLIT] private List < ServicePort > extractPorts ( List < ImageConfiguration > images ) { List < ServicePort > ret = new ArrayList <> ( ) ; boolean isMultiPort = Boolean . parseBoolean ( getConfig ( Config . multiPort ) ) ; List < ServicePort > configuredPorts = extractPortsFromConfig ( ) ; for ( ImageConfiguration image : images ) { Map < String , String > labels = extractLabelsFromConfig ( image ) ; List < String > podPorts = getPortsFromBuildConfiguration ( image ) ; List < String > portsFromImageLabels = getLabelWithService ( labels ) ; if ( podPorts . isEmpty ( ) ) { continue ; } // Extract first port and remove first element if ( portsFromImageLabels == null || portsFromImageLabels . isEmpty ( ) ) { addPortIfNotNull ( ret , extractPortsFromImageSpec ( image . getName ( ) , podPorts . remove ( 0 ) , shiftOrNull ( configuredPorts ) , null ) ) ; } else { for ( String imageLabelPort : portsFromImageLabels ) { addPortIfNotNull ( ret , extractPortsFromImageSpec ( image . getName ( ) , podPorts . remove ( 0 ) , shiftOrNull ( configuredPorts ) , imageLabelPort ) ) ; } } // Remaining port specs if multi-port is selected if ( isMultiPort ) { for ( String port : podPorts ) { addPortIfNotNull ( ret , extractPortsFromImageSpec ( image . getName ( ) , port , shiftOrNull ( configuredPorts ) , null ) ) ; } } } // If there are still ports configured add them directly if ( isMultiPort ) { ret . addAll ( mirrorMissingTargetPorts ( configuredPorts ) ) ; } else if ( ret . isEmpty ( ) && ! configuredPorts . isEmpty ( ) ) { ret . addAll ( mirrorMissingTargetPorts ( Collections . singletonList ( configuredPorts . get ( 0 ) ) ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Examine images for build configuration and extract all ports [CODESPLIT] private List < String > getPortsFromBuildConfiguration ( ImageConfiguration image ) { // No build, no default service (doesn't make much sense to have no build config, though) BuildImageConfiguration buildConfig = image . getBuildConfiguration ( ) ; if ( buildConfig == null ) { return Collections . emptyList ( ) ; } return buildConfig . getPorts ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Config can override ports [CODESPLIT] private List < ServicePort > extractPortsFromConfig ( ) { List < ServicePort > ret = new LinkedList <> ( ) ; String ports = getConfig ( Config . port ) ; if ( ports != null ) { for ( String port : StringUtils . split ( ports , \",\" ) ) { ret . add ( parsePortMapping ( port ) ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse config specified ports [CODESPLIT] private ServicePort parsePortMapping ( String port ) { Matcher matcher = PORT_MAPPING_PATTERN . matcher ( port ) ; if ( ! matcher . matches ( ) ) { log . error ( \"Invalid 'port' configuration '%s'. Must match <port>(:<targetPort>)?,<port2>?,...\" , port ) ; throw new IllegalArgumentException ( \"Invalid port mapping specification \" + port ) ; } int servicePort = Integer . parseInt ( matcher . group ( \"port\" ) ) ; String optionalTargetPort = matcher . group ( \"targetPort\" ) ; String protocol = getProtocol ( matcher . group ( \"protocol\" ) ) ; ServicePortBuilder builder = new ServicePortBuilder ( ) . withPort ( servicePort ) . withProtocol ( protocol ) . withName ( getDefaultPortName ( servicePort , protocol ) ) ; // leave empty if not set. will be filled up with the port from the image config if ( optionalTargetPort != null ) { builder . withNewTargetPort ( Integer . parseInt ( optionalTargetPort ) ) ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "null ports can happen for ignored mappings [CODESPLIT] private void addPortIfNotNull ( List < ServicePort > ret , ServicePort port ) { if ( port != null ) { ret . add ( port ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove first element of list or null if list is empty [CODESPLIT] private ServicePort shiftOrNull ( List < ServicePort > ports ) { if ( ! ports . isEmpty ( ) ) { return ports . remove ( 0 ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------- [CODESPLIT] private String getDefaultServiceName ( Service defaultService ) { String defaultServiceName = KubernetesHelper . getName ( defaultService ) ; if ( StringUtils . isBlank ( defaultServiceName ) ) { defaultServiceName = getContext ( ) . getGav ( ) . getSanitizedArtifactId ( ) ; } return defaultServiceName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge services of same name with the default service [CODESPLIT] private void addMissingServiceParts ( ServiceBuilder service , Service defaultService ) { // If service has no spec -> take over the complete spec from default service if ( ! service . hasSpec ( ) ) { service . withNewSpecLike ( defaultService . getSpec ( ) ) . endSpec ( ) ; return ; } // If service has no ports -> take over ports from default service List < ServicePort > ports = service . buildSpec ( ) . getPorts ( ) ; if ( ports == null || ports . isEmpty ( ) ) { service . editSpec ( ) . withPorts ( defaultService . getSpec ( ) . getPorts ( ) ) . endSpec ( ) ; return ; } // Complete missing parts: service . editSpec ( ) . withPorts ( addMissingDefaultPorts ( ports , defaultService ) ) . endSpec ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the images stream to a file [CODESPLIT] public void appendImageStreamResource ( ImageName imageName , File target ) throws MojoExecutionException { String tag = StringUtils . isBlank ( imageName . getTag ( ) ) ? \"latest\" : imageName . getTag ( ) ; try { ImageStream is = new ImageStreamBuilder ( ) . withNewMetadata ( ) . withName ( imageName . getSimpleName ( ) ) . endMetadata ( ) . withNewSpec ( ) . addNewTag ( ) . withName ( tag ) . withNewFrom ( ) . withKind ( \"ImageStreamImage\" ) . endFrom ( ) . endTag ( ) . endSpec ( ) . build ( ) ; createOrUpdateImageStreamTag ( client , imageName , is ) ; appendImageStreamToFile ( is , target ) ; log . info ( \"ImageStream %s written to %s\" , imageName . getSimpleName ( ) , target ) ; } catch ( KubernetesClientException e ) { KubernetesResourceUtil . handleKubernetesClientException ( e , this . log ) ; } catch ( IOException e ) { throw new MojoExecutionException ( String . format ( \"Cannot write ImageStream descriptor for %s to %s : %s\" , imageName . getFullName ( ) , target . getAbsoluteFile ( ) , e . getMessage ( ) ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the URL to access the service ; using the environment variables routes or service clusterIP address [CODESPLIT] public static String getServiceURL ( KubernetesClient client , String serviceName , String serviceNamespace , String serviceProtocol , boolean serviceExternal ) { Service srv = null ; String serviceHost = serviceToHostOrBlank ( serviceName ) ; String servicePort = serviceToPortOrBlank ( serviceName ) ; String serviceProto = serviceProtocol != null ? serviceProtocol : serviceToProtocol ( serviceName , servicePort ) ; //Use specified or fallback namespace. String actualNamespace = StringUtils . isNotBlank ( serviceNamespace ) ? serviceNamespace : client . getNamespace ( ) ; //1. Inside Kubernetes: Services as ENV vars if ( ! serviceExternal && StringUtils . isNotBlank ( serviceHost ) && StringUtils . isNotBlank ( servicePort ) && StringUtils . isNotBlank ( serviceProtocol ) ) { return serviceProtocol + \"://\" + serviceHost + \":\" + servicePort ; //2. Anywhere: When namespace is passed System / Env var. Mostly needed for integration tests. } else if ( StringUtils . isNotBlank ( actualNamespace ) ) { srv = client . services ( ) . inNamespace ( actualNamespace ) . withName ( serviceName ) . get ( ) ; } if ( srv == null ) { // lets try use environment variables String hostAndPort = getServiceHostAndPort ( serviceName , \"\" , \"\" ) ; if ( ! hostAndPort . startsWith ( \":\" ) ) { return serviceProto + \"://\" + hostAndPort ; } } if ( srv == null ) { throw new IllegalArgumentException ( \"No kubernetes service could be found for name: \" + serviceName + \" in namespace: \" + actualNamespace ) ; } String answer = KubernetesHelper . getOrCreateAnnotations ( srv ) . get ( Fabric8Annotations . SERVICE_EXPOSE_URL . toString ( ) ) ; if ( StringUtils . isNotBlank ( answer ) ) { return answer ; } if ( OpenshiftHelper . isOpenShift ( client ) ) { OpenShiftClient openShiftClient = client . adapt ( OpenShiftClient . class ) ; Route route = openShiftClient . routes ( ) . inNamespace ( actualNamespace ) . withName ( serviceName ) . get ( ) ; if ( route != null ) { return ( serviceProto + \"://\" + route . getSpec ( ) . getHost ( ) ) . toLowerCase ( ) ; } } ServicePort port = findServicePortByName ( srv , null ) ; if ( port == null ) { throw new RuntimeException ( \"Couldn't find port: \" + null + \" for service:\" + serviceName ) ; } String clusterIP = srv . getSpec ( ) . getClusterIP ( ) ; if ( \"None\" . equals ( clusterIP ) ) { throw new IllegalStateException ( \"Service: \" + serviceName + \" in namespace:\" + serviceNamespace + \"is head-less. Search for endpoints instead.\" ) ; } Integer portNumber = port . getPort ( ) ; if ( StringUtils . isBlank ( clusterIP ) ) { IngressList ingresses = client . extensions ( ) . ingresses ( ) . inNamespace ( serviceNamespace ) . list ( ) ; if ( ingresses != null ) { List < Ingress > items = ingresses . getItems ( ) ; if ( items != null ) { for ( Ingress item : items ) { String ns = KubernetesHelper . getNamespace ( item ) ; if ( Objects . equal ( serviceNamespace , ns ) ) { IngressSpec spec = item . getSpec ( ) ; if ( spec != null ) { List < IngressRule > rules = spec . getRules ( ) ; List < IngressTLS > tls = spec . getTls ( ) ; if ( rules != null ) { for ( IngressRule rule : rules ) { HTTPIngressRuleValue http = rule . getHttp ( ) ; if ( http != null ) { List < HTTPIngressPath > paths = http . getPaths ( ) ; if ( paths != null ) { for ( HTTPIngressPath path : paths ) { IngressBackend backend = path . getBackend ( ) ; if ( backend != null ) { String backendServiceName = backend . getServiceName ( ) ; if ( serviceName . equals ( backendServiceName ) && portsMatch ( port , backend . getServicePort ( ) ) ) { String pathPostfix = path . getPath ( ) ; if ( tls != null ) { for ( IngressTLS tlsHost : tls ) { List < String > hosts = tlsHost . getHosts ( ) ; if ( hosts != null ) { for ( String host : hosts ) { if ( StringUtils . isNotBlank ( host ) ) { return String . format ( \"https://%s/%s\" , host , preparePath ( pathPostfix ) ) ; } } } } } answer = rule . getHost ( ) ; if ( StringUtils . isNotBlank ( answer ) ) { return String . format ( \"http://%s/%s\" , answer , preparePath ( pathPostfix ) ) ; } } } } } } } } } } } } } // lets try use the status on GKE ServiceStatus status = srv . getStatus ( ) ; if ( status != null ) { LoadBalancerStatus loadBalancerStatus = status . getLoadBalancer ( ) ; if ( loadBalancerStatus != null ) { List < LoadBalancerIngress > loadBalancerIngresses = loadBalancerStatus . getIngress ( ) ; if ( loadBalancerIngresses != null ) { for ( LoadBalancerIngress loadBalancerIngress : loadBalancerIngresses ) { String ip = loadBalancerIngress . getIp ( ) ; if ( StringUtils . isNotBlank ( ip ) ) { clusterIP = ip ; break ; } } } } } } if ( StringUtils . isBlank ( clusterIP ) ) { // on vanilla kubernetes we can use nodePort to access things externally boolean found = false ; Integer nodePort = port . getNodePort ( ) ; if ( nodePort != null ) { NodeList nodeList = client . nodes ( ) . list ( ) ; if ( nodeList != null ) { List < Node > items = nodeList . getItems ( ) ; if ( items != null ) { for ( Node item : items ) { NodeStatus status = item . getStatus ( ) ; if ( ! found && status != null ) { List < NodeAddress > addresses = status . getAddresses ( ) ; if ( addresses != null ) { for ( NodeAddress address : addresses ) { String ip = address . getAddress ( ) ; if ( StringUtils . isNotBlank ( ip ) ) { clusterIP = ip ; portNumber = nodePort ; found = true ; break ; } } } } if ( ! found ) { NodeSpec spec = item . getSpec ( ) ; if ( spec != null ) { clusterIP = spec . getExternalID ( ) ; if ( StringUtils . isNotBlank ( clusterIP ) ) { portNumber = nodePort ; break ; } } } } } } } } return ( serviceProto + \"://\" + clusterIP + \":\" + portNumber ) . toLowerCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the given servicePort matches the intOrString value [CODESPLIT] private static boolean portsMatch ( ServicePort servicePort , IntOrString intOrString ) { if ( intOrString != null ) { Integer port = servicePort . getPort ( ) ; Integer intVal = intOrString . getIntVal ( ) ; String strVal = intOrString . getStrVal ( ) ; if ( intVal != null ) { if ( port != null ) { return port . intValue ( ) == intVal . intValue ( ) ; } else { /// should we find the port by name now? } } else if ( strVal != null ) { return Objects . equal ( strVal , servicePort . getName ( ) ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the named port for the given service name or blank [CODESPLIT] private static String serviceToPortOrBlank ( String serviceName ) { String envVarName = toServicePortEnvironmentVariable ( serviceName ) ; return getEnvVarOrSystemProperty ( envVarName , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the service host and port for the given environment variable name . [CODESPLIT] private static String getServiceHostAndPort ( String serviceName , String defaultHost , String defaultPort ) { String serviceEnvVarPrefix = getServiceEnvVarPrefix ( serviceName ) ; String hostEnvVar = serviceEnvVarPrefix + \"_HOST\" ; String portEnvVar = serviceEnvVarPrefix + \"_PORT\" ; String host = getEnvVarOrSystemProperty ( hostEnvVar , hostEnvVar , defaultHost ) ; String port = getEnvVarOrSystemProperty ( portEnvVar , portEnvVar , defaultPort ) ; String answer = host + \":\" + port ; return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given key and value pair into the map if the map does not already contain a value for that key [CODESPLIT] public static void putIfAbsent ( Map < String , String > map , String name , String value ) { if ( ! map . containsKey ( name ) ) { map . put ( name , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all values of a map to another map but onlfy if not already existing . [CODESPLIT] public static void mergeIfAbsent ( Map < String , String > map , Map < String , String > toMerge ) { for ( Map . Entry < String , String > entry : toMerge . entrySet ( ) ) { putIfAbsent ( map , entry . getKey ( ) , entry . getValue ( ) ) ; ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new map with all the entries of map1 and any from map2 which don t override map1 . [CODESPLIT] public static < K , V > Map < K , V > mergeMaps ( Map < K , V > map1 , Map < K , V > map2 ) { Map < K , V > answer = new HashMap <> ( ) ; if ( map2 != null ) { answer . putAll ( map2 ) ; } if ( map1 != null ) { answer . putAll ( map1 ) ; } return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all of the elements i . e . the mappings from toPut map into ret if toPut isn t null . [CODESPLIT] public static void putAllIfNotNull ( Map < String , String > ret , Map < String , String > toPut ) { if ( toPut != null ) { ret . putAll ( toPut ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============================================================================================================ [CODESPLIT] private void ensureTemplateSpecs ( KubernetesListBuilder builder ) { ensureTemplateSpecsInReplicationControllers ( builder ) ; ensureTemplateSpecsInRelicaSet ( builder ) ; ensureTemplateSpecsInDeployments ( builder ) ; ensureTemplateSpecsInDaemonSet ( builder ) ; ensureTemplateSpecsInStatefulSet ( builder ) ; ensureTemplateSpecsInDeploymentConfig ( builder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============================================================================================================ [CODESPLIT] private void updateContainers ( KubernetesListBuilder builder ) { builder . accept ( new TypedVisitor < PodTemplateSpecBuilder > ( ) { @ Override public void visit ( PodTemplateSpecBuilder templateBuilder ) { PodTemplateSpecFluent . SpecNested < PodTemplateSpecBuilder > podSpec = templateBuilder . getSpec ( ) == null ? templateBuilder . withNewSpec ( ) : templateBuilder . editSpec ( ) ; List < Container > containers = podSpec . getContainers ( ) ; if ( containers == null ) { containers = new ArrayList < Container > ( ) ; } mergeImageConfigurationWithContainerSpec ( containers ) ; podSpec . withContainers ( containers ) . endSpec ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "configured [CODESPLIT] private void mergeImageConfigurationWithContainerSpec ( List < Container > containers ) { getImages ( ) . ifPresent ( images -> { int idx = 0 ; for ( ImageConfiguration image : images ) { Container container = getContainer ( idx , containers ) ; mergeImagePullPolicy ( image , container ) ; mergeImage ( image , container ) ; mergeContainerName ( image , container ) ; mergeEnvVariables ( container ) ; idx ++ ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A Simple utility function to watch over pod until it gets ready [CODESPLIT] private void waitUntilPodIsReady ( String podName , int nAwaitTimeout , final Logger log ) throws InterruptedException { final CountDownLatch readyLatch = new CountDownLatch ( 1 ) ; try ( Watch watch = client . pods ( ) . withName ( podName ) . watch ( new Watcher < Pod > ( ) { @ Override public void eventReceived ( Action action , Pod aPod ) { if ( KubernetesHelper . isPodReady ( aPod ) ) { readyLatch . countDown ( ) ; } } @ Override public void onClose ( KubernetesClientException e ) { // Ignore } } ) ) { readyLatch . await ( nAwaitTimeout , TimeUnit . SECONDS ) ; } catch ( KubernetesClientException | InterruptedException e ) { log . error ( \"Could not watch pod\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "== Utility methods ========================== [CODESPLIT] private String getS2IBuildName ( BuildServiceConfig config , ImageName imageName ) { return imageName . getSimpleName ( ) + config . getS2iBuildNameSuffix ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "================= [CODESPLIT] private static EntityPatcher < BuildConfig > bcPatcher ( ) { return ( KubernetesClient client , String namespace , BuildConfig newObj , BuildConfig oldObj ) -> { if ( UserConfigurationCompare . configEqual ( newObj , oldObj ) ) { return oldObj ; } OpenShiftClient openShiftClient = OpenshiftHelper . asOpenShiftClient ( client ) ; if ( openShiftClient == null ) { throw new IllegalArgumentException ( \"BuildConfig can only be patched when connected to an OpenShift cluster\" ) ; } DoneableBuildConfig entity = openShiftClient . buildConfigs ( ) . inNamespace ( namespace ) . withName ( oldObj . getMetadata ( ) . getName ( ) ) . edit ( ) ; if ( ! UserConfigurationCompare . configEqual ( newObj . getMetadata ( ) , oldObj . getMetadata ( ) ) ) { entity . withMetadata ( newObj . getMetadata ( ) ) ; } if ( ! UserConfigurationCompare . configEqual ( newObj . getSpec ( ) , oldObj . getSpec ( ) ) ) { entity . withSpec ( newObj . getSpec ( ) ) ; } return entity . done ( ) ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates that the given value is valid according to the kubernetes ID parsing rules throwing an exception if not . [CODESPLIT] public static String validateKubernetesId ( String currentValue , String description ) throws IllegalArgumentException { if ( StringUtils . isBlank ( currentValue ) ) { throw new IllegalArgumentException ( \"No \" + description + \" is specified!\" ) ; } int size = currentValue . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { char ch = currentValue . charAt ( i ) ; if ( Character . isUpperCase ( ch ) ) { throw new IllegalArgumentException ( \"Invalid upper case letter '\" + ch + \"' at index \" + i + \" for \" + description + \" value: \" + currentValue ) ; } } return currentValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the Kubernetes JSON and converts it to a list of entities [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static List < HasMetadata > toItemList ( Object entity ) throws IOException { if ( entity instanceof List ) { return ( List < HasMetadata > ) entity ; } else if ( entity instanceof HasMetadata [ ] ) { HasMetadata [ ] array = ( HasMetadata [ ] ) entity ; return Arrays . asList ( array ) ; } else if ( entity instanceof KubernetesList ) { KubernetesList config = ( KubernetesList ) entity ; return config . getItems ( ) ; } else if ( entity instanceof Template ) { Template objects = ( Template ) entity ; return objects . getObjects ( ) ; } else { List < HasMetadata > answer = new ArrayList <> ( ) ; if ( entity instanceof HasMetadata ) { answer . add ( ( HasMetadata ) entity ) ; } return answer ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the resource version for the entity or null if it does not have one [CODESPLIT] public static String getResourceVersion ( HasMetadata entity ) { if ( entity != null ) { ObjectMeta metadata = entity . getMetadata ( ) ; if ( metadata != null ) { String resourceVersion = metadata . getResourceVersion ( ) ; if ( StringUtils . isNotBlank ( resourceVersion ) ) { return resourceVersion ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an IntOrString from the given string which could be a number or a name [CODESPLIT] public static IntOrString createIntOrString ( int intVal ) { IntOrString answer = new IntOrString ( ) ; answer . setIntVal ( intVal ) ; answer . setKind ( 0 ) ; return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an IntOrString from the given string which could be a number or a name [CODESPLIT] public static IntOrString createIntOrString ( String nameOrNumber ) { if ( StringUtils . isBlank ( nameOrNumber ) ) { return null ; } else { IntOrString answer = new IntOrString ( ) ; Integer intVal = null ; try { intVal = Integer . parseInt ( nameOrNumber ) ; } catch ( Exception e ) { // ignore invalid number } if ( intVal != null ) { answer . setIntVal ( intVal ) ; answer . setKind ( 0 ) ; } else { answer . setStrVal ( nameOrNumber ) ; answer . setKind ( 1 ) ; } return answer ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the pod is running and ready [CODESPLIT] public static boolean isPodReady ( Pod pod ) { if ( ! isPodRunning ( pod ) ) { return false ; } PodStatus podStatus = pod . getStatus ( ) ; if ( podStatus == null ) { return true ; } List < PodCondition > conditions = podStatus . getConditions ( ) ; if ( conditions == null || conditions . isEmpty ( ) ) { return true ; } // Check \"ready\" condition for ( PodCondition condition : conditions ) { if ( \"ready\" . equalsIgnoreCase ( condition . getType ( ) ) ) { return Boolean . parseBoolean ( condition . getStatus ( ) ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current context in the given config [CODESPLIT] private static Context getCurrentContext ( Config config ) { String contextName = config . getCurrentContext ( ) ; if ( contextName != null ) { List < NamedContext > contexts = config . getContexts ( ) ; if ( contexts != null ) { for ( NamedContext context : contexts ) { if ( Objects . equals ( contextName , context . getName ( ) ) ) { return context . getContext ( ) ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if we already have a route created for the given name [CODESPLIT] private boolean hasRoute ( final KubernetesListBuilder listBuilder , final String name ) { final AtomicBoolean answer = new AtomicBoolean ( false ) ; listBuilder . accept ( new TypedVisitor < RouteBuilder > ( ) { @ Override public void visit ( RouteBuilder builder ) { ObjectMeta metadata = builder . getMetadata ( ) ; if ( metadata != null && name . equals ( metadata . getName ( ) ) ) { answer . set ( true ) ; } } } ) ; return answer . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces all text of the form <code > $ { foo } < / code > with the value in the properties object [CODESPLIT] protected static String replaceProperties ( String text , Properties properties ) { Set < Map . Entry < Object , Object > > entries = properties . entrySet ( ) ; for ( Map . Entry < Object , Object > entry : entries ) { Object key = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( key != null && value != null ) { String pattern = \"${\" + key + \"}\" ; text = StringUtils . replace ( text , pattern , value . toString ( ) ) ; } } return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "========================================================================================================== [CODESPLIT] private static void addShutdownHook ( final Logger log , final Process process , final File command ) { Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( command . getName ( ) ) { @ Override public void run ( ) { if ( process != null ) { // Trying to determine if the process is alive boolean alive = false ; try { process . exitValue ( ) ; } catch ( IllegalThreadStateException e ) { alive = true ; } if ( alive ) { log . info ( \"Terminating process %s\" , command ) ; try { process . destroy ( ) ; } catch ( Exception e ) { log . error ( \"Failed to terminate process %s\" , command ) ; } /* Only available in Java 8: So disabled for now until we switch to Java 8\n                        try {\n                            if (process != null && process.isAlive()) {\n                                process.destroyForcibly();\n                            }\n                        } catch (Exception e) {\n                            log.error(\"Failed to forcibly terminate process %s\", command);\n                        }\n                        */ } } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forwards a port to the newest pod matching the given selector . If another pod is created it forwards connections to the new pod once it s ready . [CODESPLIT] public Closeable forwardPortAsync ( final Logger externalProcessLogger , final LabelSelector podSelector , final int remotePort , final int localPort ) throws Fabric8ServiceException { final Lock monitor = new ReentrantLock ( true ) ; final Condition podChanged = monitor . newCondition ( ) ; final Pod [ ] nextForwardedPod = new Pod [ 1 ] ; final Thread forwarderThread = new Thread ( ) { @ Override public void run ( ) { Pod currentPod = null ; Closeable currentPortForward = null ; try { monitor . lock ( ) ; while ( true ) { if ( podEquals ( currentPod , nextForwardedPod [ 0 ] ) ) { podChanged . await ( ) ; } else { Pod nextPod = nextForwardedPod [ 0 ] ; // may be null try { monitor . unlock ( ) ; // out of critical section if ( currentPortForward != null ) { log . info ( \"Closing port-forward from pod %s\" , KubernetesHelper . getName ( currentPod ) ) ; currentPortForward . close ( ) ; currentPortForward = null ; } if ( nextPod != null ) { log . info ( \"Starting port-forward to pod %s\" , KubernetesHelper . getName ( nextPod ) ) ; currentPortForward = forwardPortAsync ( externalProcessLogger , KubernetesHelper . getName ( nextPod ) , remotePort , localPort ) ; } else { log . info ( \"Waiting for a pod to become ready before starting port-forward\" ) ; } currentPod = nextPod ; } finally { monitor . lock ( ) ; } } } } catch ( InterruptedException e ) { log . debug ( \"Port-forwarding thread interrupted\" , e ) ; Thread . currentThread ( ) . interrupt ( ) ; } catch ( Exception e ) { log . warn ( \"Error while port-forwarding to pod\" , e ) ; } finally { monitor . unlock ( ) ; if ( currentPortForward != null ) { try { currentPortForward . close ( ) ; } catch ( Exception e ) { } } } } } ; // Switching forward to the current pod if present Pod newPod = getNewestPod ( podSelector ) ; nextForwardedPod [ 0 ] = newPod ; final Watch watch = KubernetesClientUtil . withSelector ( kubernetes . pods ( ) , podSelector , log ) . watch ( new Watcher < Pod > ( ) { @ Override public void eventReceived ( Action action , Pod pod ) { monitor . lock ( ) ; try { List < Pod > candidatePods ; if ( nextForwardedPod [ 0 ] != null ) { candidatePods = new LinkedList <> ( ) ; candidatePods . add ( nextForwardedPod [ 0 ] ) ; candidatePods . add ( pod ) ; } else { candidatePods = Collections . singletonList ( pod ) ; } Pod newPod = getNewestPod ( candidatePods ) ; // may be null if ( ! podEquals ( nextForwardedPod [ 0 ] , newPod ) ) { nextForwardedPod [ 0 ] = newPod ; podChanged . signal ( ) ; } } finally { monitor . unlock ( ) ; } } @ Override public void onClose ( KubernetesClientException e ) { // don't care } } ) ; forwarderThread . start ( ) ; final Closeable handle = ( ) -> { try { watch . close ( ) ; } catch ( Exception e ) { } try { forwarderThread . interrupt ( ) ; forwarderThread . join ( 15000 ) ; } catch ( Exception e ) { } } ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { try { handle . close ( ) ; } catch ( Exception e ) { // suppress } } } ) ; return handle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================================================== [CODESPLIT] private static URLClassLoader createClassLoader ( List < String > classpathElements , String ... paths ) { List < URL > urls = new ArrayList <> ( ) ; for ( String path : paths ) { URL url = pathToUrl ( path ) ; urls . add ( url ) ; } for ( Object object : classpathElements ) { if ( object != null ) { String path = object . toString ( ) ; URL url = pathToUrl ( path ) ; urls . add ( url ) ; } } return createURLClassLoader ( urls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the maven project has a dependency with the given groupId and artifactId ( if not null ) [CODESPLIT] public static boolean hasDependency ( MavenProject project , String groupId , String artifactId ) { return getDependencyVersion ( project , groupId , artifactId ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the version associated to the dependency dependency with the given groupId and artifactId ( if present ) [CODESPLIT] public static String getDependencyVersion ( MavenProject project , String groupId , String artifactId ) { Set < Artifact > artifacts = project . getArtifacts ( ) ; if ( artifacts != null ) { for ( Artifact artifact : artifacts ) { String scope = artifact . getScope ( ) ; if ( Objects . equal ( \"test\" , scope ) ) { continue ; } if ( artifactId != null && ! Objects . equal ( artifactId , artifact . getArtifactId ( ) ) ) { continue ; } if ( Objects . equal ( groupId , artifact . getGroupId ( ) ) ) { return artifact . getVersion ( ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the plugin with the given groupId ( if present ) and artifactId . [CODESPLIT] public static Plugin getPlugin ( MavenProject project , String groupId , String artifactId ) { if ( artifactId == null ) { throw new IllegalArgumentException ( \"artifactId cannot be null\" ) ; } List < Plugin > plugins = project . getBuildPlugins ( ) ; if ( plugins != null ) { for ( Plugin plugin : plugins ) { boolean matchesArtifactId = artifactId . equals ( plugin . getArtifactId ( ) ) ; boolean matchesGroupId = groupId == null || groupId . equals ( plugin . getGroupId ( ) ) ; if ( matchesGroupId && matchesArtifactId ) { return plugin ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if any of the given resources could be found on the given class loader [CODESPLIT] public static boolean hasResource ( MavenProject project , String ... paths ) { URLClassLoader compileClassLoader = getCompileClassLoader ( project ) ; for ( String path : paths ) { try { if ( compileClassLoader . getResource ( path ) != null ) { return true ; } } catch ( Throwable e ) { // ignore } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the version from the list of pre - configured versions of common groupId / artifact pairs [CODESPLIT] public static String getVersion ( String groupId , String artifactId ) throws IOException { String path = \"META-INF/maven/\" + groupId + \"/\" + artifactId + \"/pom.properties\" ; InputStream in = MavenUtil . class . getClassLoader ( ) . getResourceAsStream ( path ) ; if ( in == null ) { throw new IOException ( \"Could not find \" + path + \" on classath!\" ) ; } Properties properties = new Properties ( ) ; try { properties . load ( in ) ; } catch ( IOException e ) { throw new IOException ( \"Failed to load \" + path + \". \" + e , e ) ; } String version = properties . getProperty ( \"version\" ) ; if ( StringUtils . isBlank ( version ) ) { throw new IOException ( \"No version property in \" + path ) ; } return version ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this cluster is a traditional OpenShift cluster with the <code > / oapi< / code > REST API or supports the new <code > / apis / image . openshift . io< / code > API Group [CODESPLIT] public boolean isOpenShiftImageStream ( Logger log ) { if ( isOpenShift ( log ) ) { OpenShiftClient openShiftClient = null ; if ( this . client == null ) { openShiftClient = createOpenShiftClient ( ) ; } else if ( this . client instanceof OpenShiftClient ) { openShiftClient = ( OpenShiftClient ) this . client ; } else if ( this . client . isAdaptable ( OpenShiftClient . class ) ) { openShiftClient = client . adapt ( OpenShiftClient . class ) ; } else { return false ; } return openShiftClient . supportsOpenShiftAPIGroup ( OpenShiftAPIGroups . IMAGE ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all Kubernetes resource fragments from a directory and create a { @link KubernetesListBuilder } which can be adapted later . [CODESPLIT] public static KubernetesListBuilder readResourceFragmentsFrom ( PlatformMode platformMode , ResourceVersioning apiVersions , String defaultName , File [ ] resourceFiles ) throws IOException { KubernetesListBuilder builder = new KubernetesListBuilder ( ) ; if ( resourceFiles != null ) { for ( File file : resourceFiles ) { HasMetadata resource = getResource ( platformMode , apiVersions , file , defaultName ) ; builder . addToItems ( resource ) ; } } return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a Kubernetes resource fragment and add meta information extracted from the filename to the resource descriptor . I . e . the following elements are added if not provided in the fragment : [CODESPLIT] public static HasMetadata getResource ( PlatformMode platformMode , ResourceVersioning apiVersions , File file , String appName ) throws IOException { Map < String , Object > fragment = readAndEnrichFragment ( platformMode , apiVersions , file , appName ) ; ObjectMapper mapper = new ObjectMapper ( ) ; try { return mapper . convertValue ( fragment , HasMetadata . class ) ; } catch ( ClassCastException exp ) { throw new IllegalArgumentException ( String . format ( \"Resource fragment %s has an invalid syntax (%s)\" , file . getPath ( ) , exp . getMessage ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read fragment and add default values [CODESPLIT] private static Map < String , Object > readAndEnrichFragment ( PlatformMode platformMode , ResourceVersioning apiVersions , File file , String appName ) throws IOException { Pattern pattern = Pattern . compile ( FILENAME_PATTERN , Pattern . CASE_INSENSITIVE ) ; Matcher matcher = pattern . matcher ( file . getName ( ) ) ; if ( ! matcher . matches ( ) ) { throw new IllegalArgumentException ( String . format ( \"Resource file name '%s' does not match pattern <name>-<type>.(yaml|yml|json)\" , file . getName ( ) ) ) ; } String name = matcher . group ( \"name\" ) ; String type = matcher . group ( \"type\" ) ; String ext = matcher . group ( \"ext\" ) . toLowerCase ( ) ; String kind ; Map < String , Object > fragment = readFragment ( file , ext ) ; if ( type != null ) { kind = getAndValidateKindFromType ( file , type ) ; } else { // Try name as type kind = FILENAME_TO_KIND_MAPPER . get ( name . toLowerCase ( ) ) ; if ( kind != null ) { // Name is in fact the type, so lets erase the name. name = null ; } } addKind ( fragment , kind , file . getName ( ) ) ; String apiVersion = apiVersions . getCoreVersion ( ) ; if ( Objects . equals ( kind , \"Ingress\" ) ) { apiVersion = apiVersions . getExtensionsVersion ( ) ; } else if ( Objects . equals ( kind , \"StatefulSet\" ) || Objects . equals ( kind , \"Deployment\" ) ) { apiVersion = apiVersions . getAppsVersion ( ) ; } else if ( Objects . equals ( kind , \"Job\" ) ) { apiVersion = apiVersions . getJobVersion ( ) ; } else if ( Objects . equals ( kind , \"DeploymentConfig\" ) && platformMode == PlatformMode . openshift ) { apiVersion = apiVersions . getOpenshiftV1version ( ) ; } addIfNotExistent ( fragment , \"apiVersion\" , apiVersion ) ; Map < String , Object > metaMap = getMetadata ( fragment ) ; // No name means: generated app name should be taken as resource name addIfNotExistent ( metaMap , \"name\" , StringUtils . isNotBlank ( name ) ? name : appName ) ; return fragment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=============================================================================================== [CODESPLIT] private static Map < String , Object > getMetadata ( Map < String , Object > fragment ) { Object mo = fragment . get ( \"metadata\" ) ; Map < String , Object > meta ; if ( mo == null ) { meta = new HashMap <> ( ) ; fragment . put ( \"metadata\" , meta ) ; return meta ; } else if ( mo instanceof Map ) { return ( Map < String , Object > ) mo ; } else { throw new IllegalArgumentException ( \"Metadata is expected to be a Map, not a \" + mo . getClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a map of env vars to a list of K8s EnvVar objects . [CODESPLIT] public static List < EnvVar > convertToEnvVarList ( Map < String , String > envVars ) { List < EnvVar > envList = new LinkedList <> ( ) ; for ( Map . Entry < String , String > entry : envVars . entrySet ( ) ) { String name = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( name != null ) { EnvVar env = new EnvVarBuilder ( ) . withName ( name ) . withValue ( value ) . build ( ) ; envList . add ( env ) ; } } return envList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses reflection to copy over default values from the defaultValues object to the targetValues object similar to the following : [CODESPLIT] public static void mergeSimpleFields ( Object targetValues , Object defaultValues ) { Class < ? > tc = targetValues . getClass ( ) ; Class < ? > sc = defaultValues . getClass ( ) ; for ( Method targetGetMethod : tc . getMethods ( ) ) { if ( ! targetGetMethod . getName ( ) . startsWith ( \"get\" ) ) { continue ; } Class < ? > fieldType = targetGetMethod . getReturnType ( ) ; if ( ! SIMPLE_FIELD_TYPES . contains ( fieldType ) ) { continue ; } String fieldName = targetGetMethod . getName ( ) . substring ( 3 ) ; Method withMethod = null ; try { withMethod = tc . getMethod ( \"with\" + fieldName , fieldType ) ; } catch ( NoSuchMethodException e ) { try { withMethod = tc . getMethod ( \"set\" + fieldName , fieldType ) ; } catch ( NoSuchMethodException e2 ) { continue ; } } Method sourceGetMethod = null ; try { sourceGetMethod = sc . getMethod ( \"get\" + fieldName ) ; } catch ( NoSuchMethodException e ) { continue ; } try { if ( targetGetMethod . invoke ( targetValues ) == null ) { withMethod . invoke ( targetValues , sourceGetMethod . invoke ( defaultValues ) ) ; } } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e . getCause ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the given resources together into a single resource . [CODESPLIT] public static HasMetadata mergeResources ( HasMetadata item1 , HasMetadata item2 , Logger log , boolean switchOnLocalCustomisation ) { if ( item1 instanceof Deployment && item2 instanceof Deployment ) { return mergeDeployments ( ( Deployment ) item1 , ( Deployment ) item2 , log , switchOnLocalCustomisation ) ; } if ( item1 instanceof ConfigMap && item2 instanceof ConfigMap ) { ConfigMap cm1 = ( ConfigMap ) item1 ; ConfigMap cm2 = ( ConfigMap ) item2 ; return mergeConfigMaps ( cm1 , cm2 , log , switchOnLocalCustomisation ) ; } mergeMetadata ( item1 , item2 ) ; return item1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a merge of the given maps and then removes any resulting empty string values ( which is the way to remove say a label or annotation when overriding [CODESPLIT] private static Map < String , String > mergeMapsAndRemoveEmptyStrings ( Map < String , String > overrideMap , Map < String , String > originalMap ) { Map < String , String > answer = MapUtil . mergeMaps ( overrideMap , originalMap ) ; Set < Map . Entry < String , String > > entries = overrideMap . entrySet ( ) ; for ( Map . Entry < String , String > entry : entries ) { String value = entry . getValue ( ) ; if ( value == null || value . isEmpty ( ) ) { String key = entry . getKey ( ) ; answer . remove ( key ) ; } } return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we could also use an annotation? [CODESPLIT] private static boolean isLocalCustomisation ( PodSpec podSpec ) { List < Container > containers = podSpec . getContainers ( ) != null ? podSpec . getContainers ( ) : Collections . < Container > emptyList ( ) ; for ( Container container : containers ) { if ( StringUtils . isNotBlank ( container . getImage ( ) ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the configuration from the file . [CODESPLIT] private Map < String , String > readConfig ( File f ) throws IOException { Map < String , String > map ; if ( f . getName ( ) . endsWith ( JSON_EXTENSION ) ) { map = flatten ( JSON_MAPPER . readValue ( f , Map . class ) ) ; } else if ( f . getName ( ) . endsWith ( YAML_EXTENSION ) || f . getName ( ) . endsWith ( YML_EXTENSION ) ) { map = flatten ( YAML_MAPPER . readValue ( f , Map . class ) ) ; } else if ( f . getName ( ) . endsWith ( PROPERTIES_EXTENSION ) ) { Properties properties = new Properties ( ) ; properties . load ( new FileInputStream ( f ) ) ; map = propertiesToMap ( properties ) ; } else { throw new IllegalArgumentException ( \"Can't read configuration from: [\" + f . getName ( ) + \"]. Unknown file extension.\" ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens a nested map into a Map<String String > . [CODESPLIT] private Map < String , String > flatten ( Map map ) { Map < String , String > flat = new HashMap <> ( ) ; for ( Object key : map . keySet ( ) ) { String stringKey = String . valueOf ( key ) ; Object value = map . get ( key ) ; if ( value instanceof String ) { flat . put ( stringKey , ( String ) value ) ; } else if ( value instanceof Map ) { for ( Map . Entry < String , String > entry : flatten ( ( Map ) value ) . entrySet ( ) ) { flat . put ( new StringBuilder ( stringKey ) . append ( DOT ) . append ( entry . getKey ( ) ) . toString ( ) , entry . getValue ( ) ) ; } } else { flat . put ( stringKey , String . valueOf ( value ) ) ; } } return flat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { [CODESPLIT] private Map < String , String > propertiesToMap ( Properties properties ) { Map < String , String > map = new HashMap <> ( ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { map . put ( String . valueOf ( entry . getKey ( ) ) , String . valueOf ( entry . getValue ( ) ) ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a port to the list . [CODESPLIT] private void addPortIfValid ( Map < String , Integer > map , String key , String port ) { if ( StringUtils . isNotBlank ( port ) ) { String t = port . trim ( ) ; if ( t . matches ( NUMBER_REGEX ) ) { map . put ( key , Integer . parseInt ( t ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "======================================================================================== [CODESPLIT] private HTTPGetAction getHTTPGetAction ( String getUrl ) { if ( getUrl == null || ! getUrl . subSequence ( 0 , 4 ) . toString ( ) . equalsIgnoreCase ( \"http\" ) ) { return null ; } try { URL url = new URL ( getUrl ) ; return new HTTPGetAction ( url . getHost ( ) , null /* headers */ , url . getPath ( ) , new IntOrString ( url . getPort ( ) ) , url . getProtocol ( ) . toUpperCase ( ) ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( \"Invalid URL \" + getUrl + \" given for HTTP GET readiness check\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method used in MOJO [CODESPLIT] public String getDockerJsonConfigString ( final Settings settings , final String serverId ) { Server server = getServer ( settings , serverId ) ; if ( server == null ) { return \"\" ; } JsonObject auth = new JsonObject ( ) ; auth . add ( \"username\" , new JsonPrimitive ( server . getUsername ( ) ) ) ; auth . add ( \"password\" , new JsonPrimitive ( server . getPassword ( ) ) ) ; String mail = getConfigurationValue ( server , \"email\" ) ; if ( ! StringUtils . isBlank ( mail ) ) { auth . add ( \"email\" , new JsonPrimitive ( mail ) ) ; } JsonObject json = new JsonObject ( ) ; json . add ( serverId , auth ) ; return json . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets plugin configuration values . Since there can be inner values it returns a Map of Objects where an Object can be a simple type List or another Map . [CODESPLIT] public Optional < Map < String , Object > > getPluginConfiguration ( String system , String id ) { return pluginConfigLookup . apply ( system , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets configuration values . Since there can be inner values it returns a Map of Objects where an Object can be a simple type List or another Map . [CODESPLIT] public Optional < Map < String , Object > > getSecretConfiguration ( String id ) { return secretConfigLookup . apply ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Download with showing the progress a given URL and store it in a file [CODESPLIT] public static void download ( Logger log , URL downloadUrl , File target ) throws MojoExecutionException { log . progressStart ( ) ; try { OkHttpClient client = new OkHttpClient . Builder ( ) . readTimeout ( 30 , TimeUnit . MINUTES ) . build ( ) ; Request request = new Request . Builder ( ) . url ( downloadUrl ) . build ( ) ; Response response = client . newCall ( request ) . execute ( ) ; try ( OutputStream out = new FileOutputStream ( target ) ; InputStream im = response . body ( ) . byteStream ( ) ) { long length = response . body ( ) . contentLength ( ) ; InputStream in = response . body ( ) . byteStream ( ) ; byte [ ] buffer = new byte [ 8192 ] ; long readBytes = 0 ; while ( true ) { int len = in . read ( buffer ) ; readBytes += len ; log . progressUpdate ( target . getName ( ) , \"Downloading\" , getProgressBar ( readBytes , length ) ) ; if ( len <= 0 ) { out . flush ( ) ; break ; } out . write ( buffer , 0 , len ) ; } } } catch ( IOException e ) { throw new MojoExecutionException ( \"Failed to download URL \" + downloadUrl + \" to  \" + target + \": \" + e , e ) ; } finally { log . progressFinished ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a free ( on localhost ) random port in the specified range after the given number of attempts . [CODESPLIT] public static int getFreeRandomPort ( int min , int max , int attempts ) { Random random = new Random ( ) ; for ( int i = 0 ; i < attempts ; i ++ ) { int port = min + random . nextInt ( max - min + 1 ) ; try ( Socket socket = new Socket ( \"localhost\" , port ) ) { } catch ( ConnectException e ) { return port ; } catch ( IOException e ) { throw new IllegalStateException ( \"Error while trying to check open ports\" , e ) ; } } throw new IllegalStateException ( \"Cannot find a free random port in the range [\" + min + \", \" + max + \"] after \" + attempts + \" attempts\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two version strings such that 1 . 10 . 1 > 1 . 4 etc [CODESPLIT] public static int compareVersions ( String v1 , String v2 ) { String [ ] components1 = split ( v1 ) ; String [ ] components2 = split ( v2 ) ; int diff ; int length = Math . min ( components1 . length , components2 . length ) ; for ( int i = 0 ; i < length ; i ++ ) { String s1 = components1 [ i ] ; String s2 = components2 [ i ] ; Integer i1 = tryParseInteger ( s1 ) ; Integer i2 = tryParseInteger ( s2 ) ; if ( i1 != null && i2 != null ) { diff = i1 . compareTo ( i2 ) ; } else { // lets assume strings instead diff = s1 . compareTo ( s2 ) ; } if ( diff != 0 ) { return diff ; } } diff = Integer . compare ( components1 . length , components2 . length ) ; if ( diff == 0 ) { if ( v1 == v2 ) { return 0 ; } /* if v1 == null then v2 can't be null here (see 'if' above).\n               So for v1 == null its always smaller than v2 */ ; return v1 != null ? v1 . compareTo ( v2 ) : - 1 ; } return diff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a profile . Profiles are looked up at various locations : [CODESPLIT] public static Profile findProfile ( String profileArg , File resourceDir ) throws IOException { try { String profile = profileArg == null ? DEFAULT_PROFILE : profileArg ; Profile profileFound = lookup ( profile , resourceDir ) ; if ( profileFound != null ) { if ( profileFound . getParentProfile ( ) != null ) { profileFound = inheritFromParentProfile ( profileFound , resourceDir ) ; log . info ( profileFound + \" inheriting resources from \" + profileFound . getParentProfile ( ) ) ; } return profileFound ; } else { throw new IllegalArgumentException ( \"No profile '\" + profile + \"' defined\" ) ; } } catch ( IOException e ) { throw new IOException ( \"Error while looking up profile \" + profileArg + \": \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an enricher or generator config possibly via a profile and merge it with a given configuration . [CODESPLIT] public static ProcessorConfig blendProfileWithConfiguration ( ProcessorConfigurationExtractor configExtractor , String profile , File resourceDir , ProcessorConfig config ) throws IOException { // Get specified profile or the default profile ProcessorConfig profileConfig = extractProcesssorConfiguration ( configExtractor , profile , resourceDir ) ; return ProcessorConfig . mergeProcessorConfigs ( config , profileConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup profiles from a given directory and merge it with a profile of the same name found in the classpath [CODESPLIT] public static Profile lookup ( String name , File directory ) throws IOException { // First check from the classpath, these profiles are used as a basis List < Profile > profiles = readProfileFromClasspath ( name ) ; File profileFile = findProfileYaml ( directory ) ; if ( profileFile != null ) { List < Profile > fileProfiles = fromYaml ( new FileInputStream ( profileFile ) ) ; for ( Profile profile : fileProfiles ) { if ( profile . getName ( ) . equals ( name ) ) { profiles . add ( profile ) ; break ; } } } // \"larger\" orders are \"earlier\" in the list Collections . sort ( profiles , Collections . < Profile > reverseOrder ( ) ) ; return mergeProfiles ( profiles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all default profiles first then merge in custom profiles found on the classpath [CODESPLIT] private static List < Profile > readProfileFromClasspath ( String name ) throws IOException { List < Profile > ret = new ArrayList <> ( ) ; ret . addAll ( readAllFromClasspath ( name , \"default\" ) ) ; ret . addAll ( readAllFromClasspath ( name , \"\" ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all profiles found in the classpath . [CODESPLIT] public static List < Profile > readAllFromClasspath ( String name , String ext ) throws IOException { List < Profile > ret = new ArrayList <> ( ) ; for ( String location : getMetaInfProfilePaths ( ext ) ) { for ( String url : ClassUtil . getResources ( location ) ) { for ( Profile profile : fromYaml ( new URL ( url ) . openStream ( ) ) ) { if ( name . equals ( profile . getName ( ) ) ) { ret . add ( profile ) ; } } } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check for various variations of profile files [CODESPLIT] private static File findProfileYaml ( File directory ) { for ( String profileFile : PROFILE_FILENAMES ) { File ret = new File ( directory , String . format ( profileFile , \"\" ) ) ; if ( ret . exists ( ) ) { return ret ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prepend meta - inf location [CODESPLIT] private static List < String > getMetaInfProfilePaths ( String ext ) { List < String > ret = new ArrayList <> ( PROFILE_FILENAMES . length ) ; for ( String p : PROFILE_FILENAMES ) { ret . add ( \"META-INF/fabric8/\" + getProfileFileName ( p , ext ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a profile from an input stream . This must be in YAML format [CODESPLIT] public static List < Profile > fromYaml ( InputStream is ) throws IOException { TypeReference < List < Profile >> typeRef = new TypeReference < List < Profile > > ( ) { } ; return mapper . readValue ( is , typeRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all classes below a certain directory which contain main () classes [CODESPLIT] public static List < String > findMainClasses ( File rootDir ) throws IOException { List < String > ret = new ArrayList <> ( ) ; if ( ! rootDir . exists ( ) ) { return ret ; } if ( ! rootDir . isDirectory ( ) ) { throw new IllegalArgumentException ( String . format ( \"Path %s is not a directory\" , rootDir . getPath ( ) ) ) ; } findClasses ( ret , rootDir , rootDir . getAbsolutePath ( ) + \"/\" ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "================================= [CODESPLIT] private void addGitServiceUrl ( Map < String , String > annotations , String repoName , String gitCommitId ) { String username = getGitUserName ( ) ; // this requires online access to kubernetes so we should silently fail if no connection String gogsUrl = getExternalServiceURL ( getConfig ( Config . gitService ) , \"http\" ) ; String rootGitUrl = String . format ( \"%s/%s/%s\" , gogsUrl , username , repoName ) ; rootGitUrl = String . format ( \"%s/%s/%s\" , rootGitUrl , \"commit\" , gitCommitId ) ; if ( StringUtils . isNotBlank ( rootGitUrl ) ) { annotations . put ( Fabric8Annotations . GIT_URL . value ( ) , rootGitUrl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method overrides the ImagePullPolicy value by the value provided in XML config . [CODESPLIT] private String getImagePullPolicy ( ResourceConfig resourceConfig , String defaultValue ) { if ( resourceConfig != null ) { return resourceConfig . getImagePullPolicy ( ) != null ? resourceConfig . getImagePullPolicy ( ) : defaultValue ; } return defaultValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if we are in OpenShift S2I binary building mode [CODESPLIT] protected boolean isOpenShiftMode ( ) { Properties properties = getContext ( ) . getConfiguration ( ) . getProperties ( ) ; if ( properties != null ) { return RuntimeMode . isOpenShiftMode ( properties ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method just makes sure that the replica count provided in XML config overrides the default option ; and resource fragments are always given topmost priority . [CODESPLIT] protected int getReplicaCount ( KubernetesListBuilder builder , ResourceConfig xmlResourceConfig , int defaultValue ) { if ( xmlResourceConfig != null ) { List < HasMetadata > items = builder . buildItems ( ) ; for ( HasMetadata item : items ) { if ( item instanceof Deployment ) { if ( ( ( Deployment ) item ) . getSpec ( ) . getReplicas ( ) != null ) { return ( ( Deployment ) item ) . getSpec ( ) . getReplicas ( ) ; } } if ( item instanceof DeploymentConfig ) { if ( ( ( DeploymentConfig ) item ) . getSpec ( ) . getReplicas ( ) != null ) { return ( ( DeploymentConfig ) item ) . getSpec ( ) . getReplicas ( ) ; } } } return xmlResourceConfig . getReplicas ( ) > 0 ? xmlResourceConfig . getReplicas ( ) : defaultValue ; } return defaultValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first child element for the given name [CODESPLIT] public static Element firstChild ( Element element , String name ) { NodeList nodes = element . getChildNodes ( ) ; if ( nodes != null ) { for ( int i = 0 , size = nodes . getLength ( ) ; i < size ; i ++ ) { Node item = nodes . item ( i ) ; if ( item instanceof Element ) { Element childElement = ( Element ) item ; if ( name . equals ( childElement . getTagName ( ) ) ) { return childElement ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "================================================================================================ [CODESPLIT] private static String getTextContent ( final Node node ) { switch ( node . getNodeType ( ) ) { case Node . ELEMENT_NODE : case Node . ATTRIBUTE_NODE : case Node . ENTITY_NODE : case Node . ENTITY_REFERENCE_NODE : case Node . DOCUMENT_FRAGMENT_NODE : return mergeTextContent ( node . getChildNodes ( ) ) ; case Node . TEXT_NODE : case Node . CDATA_SECTION_NODE : case Node . COMMENT_NODE : case Node . PROCESSING_INSTRUCTION_NODE : return node . getNodeValue ( ) ; case Node . DOCUMENT_NODE : case Node . DOCUMENT_TYPE_NODE : case Node . NOTATION_NODE : default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the given DTOs onto the Kubernetes master [CODESPLIT] public void apply ( Object dto , String sourceName ) throws Exception { if ( dto instanceof List ) { List list = ( List ) dto ; for ( Object element : list ) { if ( dto == element ) { log . warn ( \"Found recursive nested object for \" + dto + \" of class: \" + dto . getClass ( ) . getName ( ) ) ; continue ; } apply ( element , sourceName ) ; } } else if ( dto instanceof KubernetesList ) { applyList ( ( KubernetesList ) dto , sourceName ) ; } else if ( dto != null ) { applyEntity ( dto , sourceName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the given DTOs onto the Kubernetes master [CODESPLIT] private void applyEntity ( Object dto , String sourceName ) throws Exception { if ( dto instanceof Pod ) { applyPod ( ( Pod ) dto , sourceName ) ; } else if ( dto instanceof ReplicationController ) { applyReplicationController ( ( ReplicationController ) dto , sourceName ) ; } else if ( dto instanceof Service ) { applyService ( ( Service ) dto , sourceName ) ; } else if ( dto instanceof Route ) { applyRoute ( ( Route ) dto , sourceName ) ; } else if ( dto instanceof BuildConfig ) { applyBuildConfig ( ( BuildConfig ) dto , sourceName ) ; } else if ( dto instanceof DeploymentConfig ) { DeploymentConfig resource = ( DeploymentConfig ) dto ; OpenShiftClient openShiftClient = getOpenShiftClient ( ) ; if ( openShiftClient != null ) { applyResource ( resource , sourceName , openShiftClient . deploymentConfigs ( ) ) ; } else { log . warn ( \"Not connected to OpenShift cluster so cannot apply entity \" + dto ) ; } } else if ( dto instanceof RoleBinding ) { applyRoleBinding ( ( RoleBinding ) dto , sourceName ) ; } else if ( dto instanceof Role ) { Role resource = ( Role ) dto ; OpenShiftClient openShiftClient = getOpenShiftClient ( ) ; if ( openShiftClient != null ) { applyResource ( resource , sourceName , openShiftClient . rbac ( ) . roles ( ) ) ; } else { log . warn ( \"Not connected to OpenShift cluster so cannot apply entity \" + dto ) ; } } else if ( dto instanceof ImageStream ) { applyImageStream ( ( ImageStream ) dto , sourceName ) ; } else if ( dto instanceof OAuthClient ) { applyOAuthClient ( ( OAuthClient ) dto , sourceName ) ; } else if ( dto instanceof Template ) { applyTemplate ( ( Template ) dto , sourceName ) ; } else if ( dto instanceof ServiceAccount ) { applyServiceAccount ( ( ServiceAccount ) dto , sourceName ) ; } else if ( dto instanceof Secret ) { applySecret ( ( Secret ) dto , sourceName ) ; } else if ( dto instanceof ConfigMap ) { applyResource ( ( ConfigMap ) dto , sourceName , kubernetesClient . configMaps ( ) ) ; } else if ( dto instanceof DaemonSet ) { applyResource ( ( DaemonSet ) dto , sourceName , kubernetesClient . extensions ( ) . daemonSets ( ) ) ; } else if ( dto instanceof Deployment ) { applyResource ( ( Deployment ) dto , sourceName , kubernetesClient . extensions ( ) . deployments ( ) ) ; } else if ( dto instanceof ReplicaSet ) { applyResource ( ( ReplicaSet ) dto , sourceName , kubernetesClient . extensions ( ) . replicaSets ( ) ) ; } else if ( dto instanceof StatefulSet ) { applyResource ( ( StatefulSet ) dto , sourceName , kubernetesClient . apps ( ) . statefulSets ( ) ) ; } else if ( dto instanceof Ingress ) { applyResource ( ( Ingress ) dto , sourceName , kubernetesClient . extensions ( ) . ingresses ( ) ) ; } else if ( dto instanceof PersistentVolumeClaim ) { applyPersistentVolumeClaim ( ( PersistentVolumeClaim ) dto , sourceName ) ; } else if ( dto instanceof HasMetadata ) { HasMetadata entity = ( HasMetadata ) dto ; try { log . info ( \"Applying \" + getKind ( entity ) + \" \" + getName ( entity ) + \" from \" + sourceName ) ; kubernetesClient . resource ( entity ) . inNamespace ( getNamespace ( ) ) . createOrReplace ( ) ; } catch ( Exception e ) { onApplyError ( \"Failed to create \" + getKind ( entity ) + \" from \" + sourceName + \". \" + e , e ) ; } } else { throw new IllegalArgumentException ( \"Unknown entity type \" + dto ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates / updates the template and processes it returning the processed DTOs [CODESPLIT] public Object applyTemplate ( Template entity , String sourceName ) throws Exception { installTemplate ( entity , sourceName ) ; return processTemplate ( entity , sourceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs the template into the namespace without processing it [CODESPLIT] public void installTemplate ( Template entity , String sourceName ) { OpenShiftClient openShiftClient = getOpenShiftClient ( ) ; if ( openShiftClient == null ) { // lets not install the template on Kubernetes! return ; } if ( ! isProcessTemplatesLocally ( ) ) { String namespace = getNamespace ( ) ; String id = getName ( entity ) ; Objects . requireNonNull ( id , \"No name for \" + entity + \" \" + sourceName ) ; Template old = openShiftClient . templates ( ) . inNamespace ( namespace ) . withName ( id ) . get ( ) ; if ( isRunning ( old ) ) { if ( UserConfigurationCompare . configEqual ( entity , old ) ) { log . info ( \"Template has not changed so not doing anything\" ) ; } else { boolean recreateMode = isRecreateMode ( ) ; // TODO seems you can't update templates right now recreateMode = true ; if ( recreateMode ) { openShiftClient . templates ( ) . inNamespace ( namespace ) . withName ( id ) . delete ( ) ; doCreateTemplate ( entity , namespace , sourceName ) ; } else { log . info ( \"Updating a Template from \" + sourceName ) ; try { Object answer = openShiftClient . templates ( ) . inNamespace ( namespace ) . withName ( id ) . replace ( entity ) ; log . info ( \"Updated Template: \" + answer ) ; } catch ( Exception e ) { onApplyError ( \"Failed to update Template from \" + sourceName + \". \" + e + \". \" + entity , e ) ; } } } } else { if ( ! isAllowCreate ( ) ) { log . warn ( \"Creation disabled so not creating a Template from \" + sourceName + \" namespace \" + namespace + \" name \" + getName ( entity ) ) ; } else { doCreateTemplate ( entity , namespace , sourceName ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates / updates a service account and processes it returning the processed DTOs [CODESPLIT] public void applyServiceAccount ( ServiceAccount serviceAccount , String sourceName ) throws Exception { String namespace = getNamespace ( ) ; String id = getName ( serviceAccount ) ; Objects . requireNonNull ( id , \"No name for \" + serviceAccount + \" \" + sourceName ) ; if ( isServicesOnlyMode ( ) ) { log . debug ( \"Only processing Services right now so ignoring ServiceAccount: \" + id ) ; return ; } ServiceAccount old = kubernetesClient . serviceAccounts ( ) . inNamespace ( namespace ) . withName ( id ) . get ( ) ; if ( isRunning ( old ) ) { if ( UserConfigurationCompare . configEqual ( serviceAccount , old ) ) { log . info ( \"ServiceAccount has not changed so not doing anything\" ) ; } else { if ( isRecreateMode ( ) ) { kubernetesClient . serviceAccounts ( ) . inNamespace ( namespace ) . withName ( id ) . delete ( ) ; doCreateServiceAccount ( serviceAccount , namespace , sourceName ) ; } else { log . info ( \"Updating a ServiceAccount from \" + sourceName ) ; try { Object answer = kubernetesClient . serviceAccounts ( ) . inNamespace ( namespace ) . withName ( id ) . replace ( serviceAccount ) ; logGeneratedEntity ( \"Updated ServiceAccount: \" , namespace , serviceAccount , answer ) ; } catch ( Exception e ) { onApplyError ( \"Failed to update ServiceAccount from \" + sourceName + \". \" + e + \". \" + serviceAccount , e ) ; } } } } else { if ( ! isAllowCreate ( ) ) { log . warn ( \"Creation disabled so not creating a ServiceAccount from \" + sourceName + \" namespace \" + namespace + \" name \" + getName ( serviceAccount ) ) ; } else { doCreateServiceAccount ( serviceAccount , namespace , sourceName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all the tags with the given name [CODESPLIT] private int removeTagByName ( List < TagReference > tags , String tagName ) { List < TagReference > removeTags = new ArrayList <> ( ) ; for ( TagReference tag : tags ) { if ( Objects . equals ( tagName , tag . getName ( ) ) ) { removeTags . add ( tag ) ; } } tags . removeAll ( removeTags ) ; return removeTags . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the namespace is created [CODESPLIT] public boolean applyNamespace ( Namespace entity ) { String namespace = getOrCreateMetadata ( entity ) . getName ( ) ; log . info ( \"Using namespace: \" + namespace ) ; String name = getName ( entity ) ; Objects . requireNonNull ( name , \"No name for \" + entity ) ; Namespace old = kubernetesClient . namespaces ( ) . withName ( name ) . get ( ) ; if ( ! isRunning ( old ) ) { try { Object answer = kubernetesClient . namespaces ( ) . create ( entity ) ; logGeneratedEntity ( \"Created namespace: \" , namespace , entity , answer ) ; return true ; } catch ( Exception e ) { onApplyError ( \"Failed to create namespace: \" + name + \" due \" + e . getMessage ( ) , e ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and return a project in openshift [CODESPLIT] public boolean applyProject ( Project project ) { return applyProjectRequest ( new ProjectRequestBuilder ( ) . withDisplayName ( project . getMetadata ( ) . getName ( ) ) . withMetadata ( project . getMetadata ( ) ) . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the ProjectRequest is created [CODESPLIT] public boolean applyProjectRequest ( ProjectRequest entity ) { String namespace = getOrCreateMetadata ( entity ) . getName ( ) ; log . info ( \"Using project: \" + namespace ) ; String name = getName ( entity ) ; Objects . requireNonNull ( name , \"No name for \" + entity ) ; OpenShiftClient openshiftClient = getOpenShiftClient ( ) ; if ( openshiftClient == null ) { log . warn ( \"Cannot check for Project \" + namespace + \" as not running against OpenShift!\" ) ; return false ; } boolean exists = checkNamespace ( name ) ; // We may want to be more fine-grained on the phase of the project if ( ! exists ) { try { Object answer = openshiftClient . projectrequests ( ) . create ( entity ) ; logGeneratedEntity ( \"Created ProjectRequest: \" , namespace , entity , answer ) ; return true ; } catch ( Exception e ) { onApplyError ( \"Failed to create ProjectRequest: \" + name + \" due \" + e . getMessage ( ) , e ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the namespace defined in the entity or the configured namespace [CODESPLIT] protected String getNamespace ( HasMetadata entity ) { String answer = KubernetesHelper . getNamespace ( entity ) ; if ( StringUtils . isBlank ( answer ) ) { answer = getNamespace ( ) ; } // lest make sure the namespace exists applyNamespace ( answer ) ; return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs an error applying some JSON to Kubernetes and optionally throws an exception [CODESPLIT] protected void onApplyError ( String message , Exception e ) { log . error ( message , e ) ; throw new RuntimeException ( message , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================================================================================== [CODESPLIT] @ GET @ Produces ( \"text/plain\" ) public String peng ( @ PathParam ( \"id\" ) String id ) { Stroke stroke = Stroke . play ( strength ) ; return pengId + \" \" + stroke . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============================================================================= [CODESPLIT] private void ensureSpringDevToolSecretToken ( ) throws MojoExecutionException { Properties properties = SpringBootUtil . getSpringBootApplicationProperties ( MavenUtil . getCompileClassLoader ( getProject ( ) ) ) ; String remoteSecret = properties . getProperty ( DEV_TOOLS_REMOTE_SECRET ) ; if ( Strings . isNullOrEmpty ( remoteSecret ) ) { addSecretTokenToApplicationProperties ( ) ; throw new MojoExecutionException ( \"No spring.devtools.remote.secret found in application.properties. Plugin has added it, please re-run goals\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will create a default Namespace or Project if a namespace property is specified in the xml resourceConfig or as a parameter to a mojo . [CODESPLIT] @ Override public void create ( PlatformMode platformMode , KubernetesListBuilder builder ) { final String name = config . getNamespace ( ) ; if ( name == null || name . isEmpty ( ) ) { return ; } if ( ! KubernetesResourceUtil . checkForKind ( builder , NAMESPACE_KINDS ) ) { String type = getConfig ( Config . type ) ; if ( \"project\" . equalsIgnoreCase ( type ) || \"namespace\" . equalsIgnoreCase ( type ) ) { if ( platformMode == PlatformMode . kubernetes ) { log . info ( \"Adding a default Namespace:\" + config . getNamespace ( ) ) ; Namespace namespace = handlerHub . getNamespaceHandler ( ) . getNamespace ( config . getNamespace ( ) ) ; builder . addToNamespaceItems ( namespace ) ; } else { log . info ( \"Adding a default Project\" + config . getNamespace ( ) ) ; Project project = handlerHub . getProjectHandler ( ) . getProject ( config . getNamespace ( ) ) ; builder . addToProjectItems ( project ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will annotate all the items in the KubernetesListBuilder with the created new namespace or project . [CODESPLIT] @ Override public void enrich ( PlatformMode platformMode , KubernetesListBuilder builder ) { builder . accept ( new TypedVisitor < ObjectMetaBuilder > ( ) { private String getNamespaceName ( ) { String name = null ; if ( config . getNamespace ( ) != null && ! config . getNamespace ( ) . isEmpty ( ) ) { name = config . getNamespace ( ) ; } name = builder . getItems ( ) . stream ( ) . filter ( item -> Arrays . asList ( NAMESPACE_KINDS ) . contains ( item . getKind ( ) ) ) . findFirst ( ) . get ( ) . getMetadata ( ) . getName ( ) ; return name ; } @ Override public void visit ( ObjectMetaBuilder metaBuilder ) { if ( ! KubernetesResourceUtil . checkForKind ( builder , NAMESPACE_KINDS ) ) { return ; } String name = getNamespaceName ( ) ; if ( name == null || name . isEmpty ( ) ) { return ; } metaBuilder . withNamespace ( name ) . build ( ) ; } } ) ; // Removing namespace annotation from the namespace and project objects being generated. // to avoid unncessary trouble while applying these resources. builder . accept ( new TypedVisitor < NamespaceBuilder > ( ) { @ Override public void visit ( NamespaceBuilder builder ) { builder . withNewStatus ( \"active\" ) . editMetadata ( ) . withNamespace ( null ) . endMetadata ( ) . build ( ) ; } } ) ; builder . accept ( new TypedVisitor < ProjectBuilder > ( ) { @ Override public void visit ( ProjectBuilder builder ) { builder . withNewStatus ( \"active\" ) . editMetadata ( ) . withNamespace ( null ) . endMetadata ( ) . build ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the Dom object into a Map . This Map can contain pairs key / value where value can be a simple type another Map ( Inner objects ) and a list of simple types . [CODESPLIT] public static Map < String , Object > extract ( Xpp3Dom root ) { if ( root == null ) { return new HashMap <> ( ) ; } return getElement ( root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hook for adding extra environment vars [CODESPLIT] protected Map < String , String > getEnv ( boolean prePackagePhase ) throws MojoExecutionException { Map < String , String > ret = new HashMap <> ( ) ; if ( ! isFatJar ( ) ) { String mainClass = getConfig ( Config . mainClass ) ; if ( mainClass == null ) { mainClass = mainClassDetector . getMainClass ( ) ; if ( mainClass == null ) { if ( ! prePackagePhase ) { throw new MojoExecutionException ( \"Cannot extract main class to startup\" ) ; } } } if ( mainClass != null ) { log . verbose ( \"Detected main class %s\" , mainClass ) ; ret . put ( JAVA_MAIN_CLASS_ENV_VAR , mainClass ) ; } } List < String > javaOptions = getExtraJavaOptions ( ) ; if ( javaOptions . size ( ) > 0 ) { ret . put ( JAVA_OPTIONS , StringUtils . join ( javaOptions . iterator ( ) , \" \" ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a duration string anr returns its value in seconds . [CODESPLIT] public static Integer durationSeconds ( String duration ) { BigDecimal ns = durationNs ( duration ) ; if ( ns == null ) { return null ; } BigDecimal sec = ns . divide ( new BigDecimal ( 1_000_000_000 ) ) ; if ( sec . compareTo ( new BigDecimal ( Integer . MAX_VALUE ) ) > 0 ) { throw new IllegalArgumentException ( \"Integer Overflow\" ) ; } return sec . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a duration string anr returns its value in nanoseconds . [CODESPLIT] public static BigDecimal durationNs ( String durationP ) { if ( durationP == null ) { return null ; } String duration = durationP . trim ( ) ; if ( duration . length ( ) == 0 ) { return null ; } int unitPos = 1 ; while ( unitPos < duration . length ( ) && ( Character . isDigit ( duration . charAt ( unitPos ) ) || duration . charAt ( unitPos ) == ' ' ) ) { unitPos ++ ; } if ( unitPos >= duration . length ( ) ) { throw new IllegalArgumentException ( \"Time unit not found in string: \" + duration ) ; } String tail = duration . substring ( unitPos ) ; Long multiplier = null ; Integer unitEnd = null ; for ( int i = 0 ; i < TIME_UNITS . length ; i ++ ) { if ( tail . startsWith ( TIME_UNITS [ i ] ) ) { multiplier = UNIT_MULTIPLIERS [ i ] ; unitEnd = unitPos + TIME_UNITS [ i ] . length ( ) ; break ; } } if ( multiplier == null ) { throw new IllegalArgumentException ( \"Unknown time unit in string: \" + duration ) ; } BigDecimal value = new BigDecimal ( duration . substring ( 0 , unitPos ) ) ; value = value . multiply ( BigDecimal . valueOf ( multiplier ) ) ; String remaining = duration . substring ( unitEnd ) ; BigDecimal remainingValue = durationNs ( remaining ) ; if ( remainingValue != null ) { value = value . add ( remainingValue ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan the project s output directory for certain files . [CODESPLIT] protected String [ ] scanFiles ( String ... patterns ) { String buildOutputDir = project . getBuild ( ) . getDirectory ( ) ; if ( buildOutputDir != null && new File ( buildOutputDir ) . exists ( ) ) { DirectoryScanner directoryScanner = new DirectoryScanner ( ) ; directoryScanner . setBasedir ( buildOutputDir ) ; directoryScanner . setIncludes ( patterns ) ; directoryScanner . scan ( ) ; return directoryScanner . getIncludedFiles ( ) ; } else { return new String [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should we try to create an external URL for the given service? <p / > By default lets ignore the kubernetes services and any service which does not expose ports 80 and 443 [CODESPLIT] private boolean shouldCreateExternalURLForService ( Service service , String id ) { if ( \"kubernetes\" . equals ( id ) || \"kubernetes-ro\" . equals ( id ) ) { return false ; } Set < Integer > ports = getPorts ( service ) ; log . debug ( \"Service \" + id + \" has ports: \" + ports ) ; if ( ports . size ( ) == 1 ) { String type = null ; ServiceSpec spec = service . getSpec ( ) ; if ( spec != null ) { type = spec . getType ( ) ; if ( Objects . equals ( type , \"LoadBalancer\" ) ) { return true ; } } log . info ( \"Not generating route for service \" + id + \" type is not LoadBalancer: \" + type ) ; return false ; } else { log . info ( \"Not generating route for service \" + id + \" as only single port services are supported. Has ports: \" + ports ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lets disable OpenShift - only features if we are not running on OpenShift [CODESPLIT] protected void disableOpenShiftFeatures ( ApplyService applyService ) { // TODO we could check if the Templates service is running and if so we could still support templates? this . processTemplatesLocally = true ; applyService . setSupportOAuthClients ( false ) ; applyService . setProcessTemplatesLocally ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if there is an existing ingress rule for the given service [CODESPLIT] private boolean serviceHasIngressRule ( List < Ingress > ingresses , Service service ) { String serviceName = KubernetesHelper . getName ( service ) ; for ( Ingress ingress : ingresses ) { IngressSpec spec = ingress . getSpec ( ) ; if ( spec == null ) { break ; } List < IngressRule > rules = spec . getRules ( ) ; if ( rules == null ) { break ; } for ( IngressRule rule : rules ) { HTTPIngressRuleValue http = rule . getHttp ( ) ; if ( http == null ) { break ; } List < HTTPIngressPath > paths = http . getPaths ( ) ; if ( paths == null ) { break ; } for ( HTTPIngressPath path : paths ) { IngressBackend backend = path . getBackend ( ) ; if ( backend == null ) { break ; } if ( Objects . equals ( serviceName , backend . getServiceName ( ) ) ) { return true ; } } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the root project folder [CODESPLIT] protected File getRootProjectFolder ( ) { File answer = null ; MavenProject project = getProject ( ) ; while ( project != null ) { File basedir = project . getBasedir ( ) ; if ( basedir != null ) { answer = basedir ; } project = project . getParent ( ) ; } return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the root project folder [CODESPLIT] protected MavenProject getRootProject ( ) { MavenProject project = getProject ( ) ; while ( project != null ) { MavenProject parent = project . getParent ( ) ; if ( parent == null ) { break ; } project = parent ; } return project ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Customization hook called by the base plugin . [CODESPLIT] @ Override public List < ImageConfiguration > customizeConfig ( List < ImageConfiguration > configs ) { try { ProcessorConfig generatorConfig = ProfileUtil . blendProfileWithConfiguration ( ProfileUtil . GENERATOR_CONFIG , profile , ResourceDirCreator . getFinalResourceDir ( resourceDir , environment ) , generator ) ; GeneratorContext ctx = new GeneratorContext . Builder ( ) . config ( generatorConfig ) . project ( project ) . logger ( log ) . runtimeMode ( mode ) . strategy ( buildStrategy ) . useProjectClasspath ( false ) . build ( ) ; return GeneratorManager . generate ( configs , ctx , true ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Cannot extract generator config: \" + e , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method reads properties file to load custom mapping between kinds and filenames . [CODESPLIT] public Map < String , List < String > > parse ( final InputStream mapping ) { final Properties mappingProperties = new Properties ( ) ; try { mappingProperties . load ( mapping ) ; final Map < String , List < String > > serializedContent = new HashMap <> ( ) ; final Set < String > kinds = mappingProperties . stringPropertyNames ( ) ; for ( String kind : kinds ) { final String filenames = mappingProperties . getProperty ( kind ) ; final String [ ] filenameTypes = filenames . split ( \",\" ) ; final List < String > scannedFiletypes = new ArrayList <> ( ) ; for ( final String filenameType : filenameTypes ) { scannedFiletypes . add ( filenameType . trim ( ) ) ; } serializedContent . put ( kind , scannedFiletypes ) ; } return serializedContent ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Customization hook called by the base plugin . [CODESPLIT] @ Override public List < ImageConfiguration > customizeConfig ( List < ImageConfiguration > configs ) { runtimeMode = clusterAccess . resolveRuntimeMode ( mode , log ) ; log . info ( \"Running in [[B]]%s[[B]] mode\" , runtimeMode . getLabel ( ) ) ; if ( runtimeMode == RuntimeMode . openshift ) { log . info ( \"Using [[B]]OpenShift[[B]] build with strategy [[B]]%s[[B]]\" , buildStrategy . getLabel ( ) ) ; } else { log . info ( \"Building Docker image in [[B]]Kubernetes[[B]] mode\" ) ; } if ( runtimeMode . equals ( PlatformMode . openshift ) ) { Properties properties = project . getProperties ( ) ; if ( ! properties . contains ( RuntimeMode . FABRIC8_EFFECTIVE_PLATFORM_MODE ) ) { properties . setProperty ( RuntimeMode . FABRIC8_EFFECTIVE_PLATFORM_MODE , runtimeMode . toString ( ) ) ; } } try { return GeneratorManager . generate ( configs , getGeneratorContext ( ) , false ) ; } catch ( MojoExecutionException e ) { throw new IllegalArgumentException ( \"Cannot extract generator config: \" + e , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get generator context [CODESPLIT] private GeneratorContext getGeneratorContext ( ) { return new GeneratorContext . Builder ( ) . config ( extractGeneratorConfig ( ) ) . project ( project ) . logger ( log ) . runtimeMode ( runtimeMode ) . strategy ( buildStrategy ) . useProjectClasspath ( useProjectClasspath ) . artifactResolver ( getFabric8ServiceHub ( ) . getArtifactResolverService ( ) ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get generator config [CODESPLIT] private ProcessorConfig extractGeneratorConfig ( ) { try { return ProfileUtil . blendProfileWithConfiguration ( ProfileUtil . GENERATOR_CONFIG , profile , ResourceDirCreator . getFinalResourceDir ( resourceDir , environment ) , generator ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( \"Cannot extract generator config: \" + e , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get enricher context [CODESPLIT] public EnricherContext getEnricherContext ( ) { return new MavenEnricherContext . Builder ( ) . project ( project ) . properties ( project . getProperties ( ) ) . session ( session ) . config ( extractEnricherConfig ( ) ) . images ( getResolvedImages ( ) ) . resources ( resources ) . log ( log ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get enricher config [CODESPLIT] private ProcessorConfig extractEnricherConfig ( ) { try { return ProfileUtil . blendProfileWithConfiguration ( ProfileUtil . ENRICHER_CONFIG , profile , ResourceDirCreator . getFinalResourceDir ( resourceDir , environment ) , enricher ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( \"Cannot extract enricher config: \" + e , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================================================================================================== [CODESPLIT] private String extractIconRef ( ) { String iconRef = getConfig ( Config . ref ) ; if ( StringUtils . isBlank ( iconRef ) ) { iconRef = getDefaultIconRef ( ) ; } return iconRef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lets use the project and its classpath to try figure out what default icon to use [CODESPLIT] private String getDefaultIconRef ( ) { ProjectClassLoaders cls = getContext ( ) . getProjectClassLoaders ( ) ; if ( cls . isClassInCompileClasspath ( false , \"io.fabric8.funktion.runtime.Main\" ) || getContext ( ) . hasDependency ( \"io.fabric8.funktion\" , null ) ) { return \"funktion\" ; } if ( cls . isClassInCompileClasspath ( false , \"org.apache.camel.CamelContext\" ) ) { return \"camel\" ; } if ( getContext ( ) . hasPlugin ( null , SpringBootConfigurationHelper . SPRING_BOOT_MAVEN_PLUGIN_ARTIFACT_ID ) || cls . isClassInCompileClasspath ( false , \"org.springframework.boot.SpringApplication\" ) ) { return \"spring-boot\" ; } if ( cls . isClassInCompileClasspath ( false , \"org.springframework.core.Constants\" ) ) { return \"spring\" ; } if ( cls . isClassInCompileClasspath ( false , \"org.vertx.java.core.Handler\" , \"io.vertx.core.Handler\" ) ) { return \"vertx\" ; } if ( getContext ( ) . hasPlugin ( \"org.wildfly.swarm\" , \"wildfly-swarm-plugin\" ) || getContext ( ) . hasDependency ( \"org.wildfly.swarm\" , null ) ) { return \"wildfly-swarm\" ; } if ( getContext ( ) . hasPlugin ( \"io.thorntail\" , \"thorntail-maven-plugin\" ) || getContext ( ) . hasDependency ( \"io.thorntail\" , null ) ) { // use the WildFly Swarm icon until there's a dedicated Thorntail icon // Thorntail is a new name of WildFly Swarm return \"wildfly-swarm\" ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies any local configuration files into the app directory [CODESPLIT] private void copyAppConfigFiles ( File appBuildDir , File appConfigDir ) throws IOException { File [ ] files = appConfigDir . listFiles ( ) ; if ( files != null ) { appBuildDir . mkdirs ( ) ; for ( File file : files ) { File outFile = new File ( appBuildDir , file . getName ( ) ) ; if ( file . isDirectory ( ) ) { copyAppConfigFiles ( outFile , file ) ; } else { Files . copy ( file , outFile ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To use embedded icons provided by the fabric8 - console [CODESPLIT] protected String embeddedIconsInConsole ( String iconRef , String prefix ) { if ( iconRef == null ) { return null ; } if ( iconRef . startsWith ( \"icons/\" ) ) { iconRef = iconRef . substring ( 6 ) ; } // special for fabric8 as its in a different dir if ( iconRef . contains ( \"META-INF/fabric8\" ) ) { return \"img/fabric8_icon.svg\" ; } if ( iconRef . contains ( \"activemq\" ) ) { return prefix + \"activemq.svg\" ; } else if ( iconRef . contains ( \"apiman\" ) ) { return prefix + \"apiman.png\" ; } else if ( iconRef . contains ( \"api-registry\" ) ) { return prefix + \"api-registry.svg\" ; } else if ( iconRef . contains ( \"brackets\" ) ) { return prefix + \"brackets.svg\" ; } else if ( iconRef . contains ( \"camel\" ) ) { return prefix + \"camel.svg\" ; } else if ( iconRef . contains ( \"chaos-monkey\" ) ) { return prefix + \"chaos-monkey.png\" ; } else if ( iconRef . contains ( \"docker-registry\" ) ) { return prefix + \"docker-registry.png\" ; } else if ( iconRef . contains ( \"elasticsearch\" ) ) { return prefix + \"elasticsearch.png\" ; } else if ( iconRef . contains ( \"fluentd\" ) ) { return prefix + \"fluentd.png\" ; } else if ( iconRef . contains ( \"forge\" ) ) { return prefix + \"forge.svg\" ; } else if ( iconRef . contains ( \"funktion\" ) ) { return prefix + \"funktion.png\" ; } else if ( iconRef . contains ( \"gerrit\" ) ) { return prefix + \"gerrit.png\" ; } else if ( iconRef . contains ( \"gitlab\" ) ) { return prefix + \"gitlab.svg\" ; } else if ( iconRef . contains ( \"gogs\" ) ) { return prefix + \"gogs.png\" ; } else if ( iconRef . contains ( \"grafana\" ) ) { return prefix + \"grafana.png\" ; } else if ( iconRef . contains ( \"hubot-irc\" ) ) { return prefix + \"hubot-irc.png\" ; } else if ( iconRef . contains ( \"hubot-letschat\" ) ) { return prefix + \"hubot-letschat.png\" ; } else if ( iconRef . contains ( \"hubot-notifier\" ) ) { return prefix + \"hubot-notifier.png\" ; } else if ( iconRef . contains ( \"hubot-slack\" ) ) { return prefix + \"hubot-slack.png\" ; } else if ( iconRef . contains ( \"image-linker\" ) ) { return prefix + \"image-linker.svg\" ; } else if ( iconRef . contains ( \"javascript\" ) ) { return prefix + \"javascript.png\" ; } else if ( iconRef . contains ( \"java\" ) ) { return prefix + \"java.svg\" ; } else if ( iconRef . contains ( \"jenkins\" ) ) { return prefix + \"jenkins.svg\" ; } else if ( iconRef . contains ( \"jetty\" ) ) { return prefix + \"jetty.svg\" ; } else if ( iconRef . contains ( \"karaf\" ) ) { return prefix + \"karaf.svg\" ; } else if ( iconRef . contains ( \"keycloak\" ) ) { return prefix + \"keycloak.svg\" ; } else if ( iconRef . contains ( \"kibana\" ) ) { return prefix + \"kibana.svg\" ; } else if ( iconRef . contains ( \"kiwiirc\" ) ) { return prefix + \"kiwiirc.png\" ; } else if ( iconRef . contains ( \"letschat\" ) ) { return prefix + \"letschat.png\" ; } else if ( iconRef . contains ( \"mule\" ) ) { return prefix + \"mule.svg\" ; } else if ( iconRef . contains ( \"nexus\" ) ) { return prefix + \"nexus.png\" ; } else if ( iconRef . contains ( \"node\" ) ) { return prefix + \"node.svg\" ; } else if ( iconRef . contains ( \"orion\" ) ) { return prefix + \"orion.png\" ; } else if ( iconRef . contains ( \"prometheus\" ) ) { return prefix + \"prometheus.png\" ; } else if ( iconRef . contains ( \"django\" ) || iconRef . contains ( \"python\" ) ) { return prefix + \"python.png\" ; } else if ( iconRef . contains ( \"spring-boot\" ) ) { return prefix + \"spring-boot.svg\" ; } else if ( iconRef . contains ( \"taiga\" ) ) { return prefix + \"taiga.png\" ; } else if ( iconRef . contains ( \"tomcat\" ) ) { return prefix + \"tomcat.svg\" ; } else if ( iconRef . contains ( \"tomee\" ) ) { return prefix + \"tomee.svg\" ; } else if ( iconRef . contains ( \"vertx\" ) ) { return prefix + \"vertx.svg\" ; } else if ( iconRef . contains ( \"wildfly\" ) ) { return prefix + \"wildfly.svg\" ; } else if ( iconRef . contains ( \"wildfly-swarm\" ) ) { return prefix + \"wildfly-swarm.png\" ; } else if ( iconRef . contains ( \"weld\" ) ) { return prefix + \"weld.svg\" ; } else if ( iconRef . contains ( \"zipkin\" ) ) { return prefix + \"zipkin.png\" ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the spring boot configuration ( supports application . properties and application . yml ) or an empty properties object if not found [CODESPLIT] public static Properties getSpringBootApplicationProperties ( URLClassLoader compileClassLoader ) { URL ymlResource = compileClassLoader . findResource ( \"application.yml\" ) ; URL propertiesResource = compileClassLoader . findResource ( \"application.properties\" ) ; Properties props = YamlUtil . getPropertiesFromYamlResource ( ymlResource ) ; props . putAll ( getPropertiesResource ( propertiesResource ) ) ; return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the given properties resource on the project classpath if found or an empty properties object if not [CODESPLIT] protected static Properties getPropertiesResource ( URL resource ) { Properties answer = new Properties ( ) ; if ( resource != null ) { try ( InputStream stream = resource . openStream ( ) ) { answer . load ( stream ) ; } catch ( IOException e ) { throw new IllegalStateException ( \"Error while reading resource from URL \" + resource , e ) ; } } return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the spring - boot major version for the current project [CODESPLIT] public static Optional < String > getSpringBootVersion ( MavenProject mavenProject ) { return Optional . ofNullable ( MavenUtil . getDependencyVersion ( mavenProject , SpringBootConfigurationHelper . SPRING_BOOT_GROUP_ID , SpringBootConfigurationHelper . SPRING_BOOT_ARTIFACT_ID ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a list of services ordered according to the ordering given in the service descriptor files . Note that the descriptor will be looked up in the whole classpath space which can result in reading in multiple descriptors with a single path . Note that the reading order for multiple resources with the same name is not defined . [CODESPLIT] public < T > List < T > createServiceObjects ( String ... descriptorPaths ) { try { ServiceEntry . initDefaultOrder ( ) ; TreeMap < ServiceEntry , T > serviceMap = new TreeMap < ServiceEntry , T > ( ) ; for ( String descriptor : descriptorPaths ) { readServiceDefinitions ( serviceMap , descriptor ) ; } ArrayList < T > ret = new ArrayList < T > ( ) ; for ( T service : serviceMap . values ( ) ) { ret . add ( service ) ; } return ret ; } finally { ServiceEntry . removeDefaultOrder ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow enricher to add Metadata to the resources . [CODESPLIT] private void enrich ( PlatformMode platformMode , final ProcessorConfig enricherConfig , final KubernetesListBuilder builder , final List < Enricher > enricherList ) { loop ( enricherConfig , enricher -> { enricher . enrich ( platformMode , builder ) ; return null ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============================================================================================= [CODESPLIT] private void logEnrichers ( List < Enricher > enrichers ) { log . verbose ( \"Enrichers:\" ) ; for ( Enricher enricher : enrichers ) { log . verbose ( \"- %s\" , enricher . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the thorntail configuration ( supports project - defaults . yml ) or an empty properties object if not found [CODESPLIT] public static Properties getThorntailProperties ( URLClassLoader compileClassLoader ) { URL ymlResource = compileClassLoader . findResource ( \"project-defaults.yml\" ) ; Properties props = YamlUtil . getPropertiesFromYamlResource ( ymlResource ) ; return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the raw untyped configuration or an empty map [CODESPLIT] public Map < String , String > getRawConfig ( ) { return configuration . getProcessorConfig ( ) . orElse ( ProcessorConfig . EMPTY ) . getConfigMap ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a config value with a default . If no value is given as a last resort project properties are looked up . [CODESPLIT] public String get ( Configs . Key key , String defaultVal ) { String val = configuration . getProcessorConfig ( ) . orElse ( ProcessorConfig . EMPTY ) . getConfig ( name , key . name ( ) ) ; if ( val == null ) { String fullKey = ENRICHER_PROP_PREFIX + \".\" + name + \".\" + key ; val = configuration . getPropertyWithSystemOverride ( fullKey ) ; } return val != null ? val : defaultVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add exception rules to ignore validation constraint from JSON schema for OpenShift / Kubernetes resources . Some fields in JSON schema which are marked as required but in reality it s not required to provide values for those fields while creating the resources . e . g . In DeploymentConfig ( https : // docs . openshift . com / container - platform / 3 . 6 / rest_api / openshift_v1 . html#v1 - deploymentconfig ) model status field is marked as required . [CODESPLIT] private void setupIgnoreRules ( ResourceClassifier target ) { ignoreValidationRules . add ( new IgnorePortValidationRule ( IgnorePortValidationRule . TYPE ) ) ; ignoreValidationRules . add ( new IgnoreResourceMemoryLimitRule ( IgnoreResourceMemoryLimitRule . TYPE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the resource descriptors as per JSON schema . If any resource is invalid it throws @ { @link ConstraintViolationException } with all violated constraints [CODESPLIT] public int validate ( ) throws ConstraintViolationException , IOException { for ( File resource : resources ) { if ( resource . isFile ( ) && resource . exists ( ) ) { try { log . info ( \"validating %s resource\" , resource . toString ( ) ) ; JsonNode inputSpecNode = geFileContent ( resource ) ; String kind = inputSpecNode . get ( \"kind\" ) . toString ( ) ; JsonSchema schema = getJsonSchema ( prepareSchemaUrl ( SCHEMA_JSON ) , kind ) ; Set < ValidationMessage > errors = schema . validate ( inputSpecNode ) ; processErrors ( errors , resource ) ; } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } } } return resources . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a flattened representation of the Yaml tree . The conversion is compliant with the thorntail spring - boot rules . [CODESPLIT] private static Map < String , Object > getFlattenedMap ( Map < String , Object > source ) { Map < String , Object > result = new LinkedHashMap <> ( ) ; buildFlattenedMap ( result , source , null ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ArtifactId is used for setting a resource name ( service pod ... ) in Kubernetes resource . The problem is that a Kubernetes resource name must start by a char . This method returns a valid string to be used as Kubernetes name . [CODESPLIT] public String getSanitizedArtifactId ( ) { if ( this . artifactId != null && ! this . artifactId . isEmpty ( ) && Character . isDigit ( this . artifactId . charAt ( 0 ) ) ) { return PREFIX + this . artifactId ; } return this . artifactId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get watcher config [CODESPLIT] private ProcessorConfig extractWatcherConfig ( ) { try { return ProfileUtil . blendProfileWithConfiguration ( ProfileUtil . WATCHER_CONFIG , profile , ResourceDirCreator . getFinalResourceDir ( resourceDir , environment ) , watcher ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( \"Cannot extract watcher config: \" + e , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Template if the list contains a single Template only otherwise returns null [CODESPLIT] protected static Template getSingletonTemplate ( KubernetesList resources ) { // if the list contains a single Template lets unwrap it if ( resources != null ) { List < HasMetadata > items = resources . getItems ( ) ; if ( items != null && items . size ( ) == 1 ) { HasMetadata singleEntity = items . get ( 0 ) ; if ( singleEntity instanceof Template ) { return ( Template ) singleEntity ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "================================================================================== [CODESPLIT] private List < ImageConfiguration > getResolvedImages ( List < ImageConfiguration > images , final Logger log ) throws MojoExecutionException { List < ImageConfiguration > ret ; ret = ConfigHelper . resolveImages ( log , images , ( ImageConfiguration image ) -> imageConfigResolver . resolve ( image , project , session ) , null , // no filter on image name yet (TODO: Maybe add this, too ?) ( List < ImageConfiguration > configs ) -> { try { GeneratorContext ctx = new GeneratorContext . Builder ( ) . config ( extractGeneratorConfig ( ) ) . project ( project ) . runtimeMode ( runtimeMode ) . logger ( log ) . strategy ( buildStrategy ) . useProjectClasspath ( useProjectClasspath ) . build ( ) ; return GeneratorManager . generate ( configs , ctx , true ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Cannot extract generator: \" + e , e ) ; } } ) ; Date now = getBuildReferenceDate ( ) ; storeReferenceDateInPluginContext ( now ) ; String minimalApiVersion = ConfigHelper . initAndValidate ( ret , null /* no minimal api version */ , new ImageNameFormatter ( project , now ) , log ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a reference date [CODESPLIT] private Date getBuildReferenceDate ( ) throws MojoExecutionException { // Pick up an existing build date created by fabric8:build previously File tsFile = new File ( project . getBuild ( ) . getDirectory ( ) , AbstractDockerMojo . DOCKER_BUILD_TIMESTAMP ) ; if ( ! tsFile . exists ( ) ) { return new Date ( ) ; } try { return EnvUtil . loadTimestamp ( tsFile ) ; } catch ( IOException e ) { throw new MojoExecutionException ( \"Cannot read timestamp from \" + tsFile , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method detects if the user has changed the configuration of an entity . <p / > It compares the <b > user< / b > configuration of 2 object trees ignoring any runtime status or timestamp information . [CODESPLIT] public static boolean configEqual ( Object entity1 , Object entity2 ) { if ( entity1 == entity2 ) { return true ; } else if ( entity1 == null || entity2 == null ) { return false ; } else if ( entity1 instanceof Map ) { return configEqualMap ( ( Map ) entity1 , castTo ( Map . class , entity2 ) ) ; } else if ( entity2 instanceof Map ) { return configEqualMap ( ( Map ) entity1 , castTo ( Map . class , entity2 ) ) ; } else if ( entity2 instanceof ObjectMeta ) { return configEqualObjectMeta ( ( ObjectMeta ) entity1 , castTo ( ObjectMeta . class , entity2 ) ) ; } else if ( entity1 instanceof Collection && entity2 instanceof Collection ) { return collectionsEqual ( ( Collection ) entity1 , ( Collection ) entity2 ) ; } else { Class < ? > aClass = getCommonDenominator ( entity1 . getClass ( ) , entity2 . getClass ( ) ) ; if ( aClass != null ) { Object castEntity2 = castTo ( aClass , entity2 ) ; if ( castEntity2 == null ) { return false ; } else if ( aClass . getPackage ( ) . getName ( ) . startsWith ( \"io.fabric8\" ) ) { return configEqualKubernetesDTO ( entity1 , entity2 , aClass ) ; } } return java . util . Objects . equals ( entity1 , entity2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares 2 instances of the given Kubernetes DTO class to see if the user has changed their configuration . <p / > This method will ignore properties { [CODESPLIT] protected static boolean configEqualKubernetesDTO ( @ NotNull Object entity1 , @ NotNull Object entity2 , @ NotNull Class < ? > clazz ) { // lets iterate through the objects making sure we've not BeanInfo beanInfo = null ; try { beanInfo = Introspector . getBeanInfo ( clazz ) ; } catch ( IntrospectionException e ) { LOG . warn ( \"Failed to get beanInfo for \" + clazz . getName ( ) + \". \" + e , e ) ; return false ; } try { PropertyDescriptor [ ] propertyDescriptors = beanInfo . getPropertyDescriptors ( ) ; for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { String name = propertyDescriptor . getName ( ) ; if ( ignoredProperties . contains ( name ) ) { continue ; } Method readMethod = propertyDescriptor . getReadMethod ( ) ; if ( readMethod != null ) { Object value1 = invokeMethod ( entity1 , readMethod ) ; Object value2 = invokeMethod ( entity2 , readMethod ) ; if ( value1 != null && value2 != null && ! configEqual ( value1 , value2 ) ) { return false ; } } } return true ; } catch ( Exception e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============================================================================================= [CODESPLIT] private static void combineParameters ( List < Parameter > parameters , List < Parameter > otherParameters ) { if ( otherParameters != null && otherParameters . size ( ) > 0 ) { Map < String , Parameter > map = new HashMap <> ( ) ; for ( Parameter parameter : parameters ) { map . put ( parameter . getName ( ) , parameter ) ; } for ( Parameter otherParameter : otherParameters ) { String name = otherParameter . getName ( ) ; Parameter original = map . get ( name ) ; if ( original == null ) { parameters . add ( otherParameter ) ; } else { if ( StringUtils . isNotBlank ( original . getValue ( ) ) ) { original . setValue ( otherParameter . getValue ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a config value with a default [CODESPLIT] public String get ( Configs . Key key , String defaultVal ) { String keyVal = key != null ? key . name ( ) : \"\" ; String val = config != null ? config . getConfig ( name , key . name ( ) ) : null ; if ( val == null ) { String fullKey = GENERATOR_PROP_PREFIX + \".\" + name + \".\" + key ; val = Configs . getSystemPropertyWithMavenPropertyAsFallback ( properties , fullKey ) ; } return val != null ? val : defaultVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a config value with a default . If no value is given as a last resort project properties are looked up . [CODESPLIT] public String get ( Configs . Key key , String defaultVal ) { String val = config != null ? config . getConfig ( name , key . name ( ) ) : null ; if ( val == null ) { String fullKey = WATCHER_PROP_PREFIX + \".\" + name + \".\" + key ; val = Configs . getSystemPropertyWithMavenPropertyAsFallback ( projectProperties , fullKey ) ; } return val != null ? val : defaultVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return full configuration as raw string - string values [CODESPLIT] public Map < String , String > getConfigMap ( String name ) { return config . containsKey ( name ) ? Collections . unmodifiableMap ( config . get ( name ) ) : Collections . < String , String > emptyMap ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Order elements according to the order provided by the include statements . If no includes has been configured return the given list unaltered . Otherwise arrange the elements from the list in to the include order and return a new list . [CODESPLIT] public < T extends Named > List < T > prepareProcessors ( List < T > namedList , String type ) { List < T > ret = new ArrayList <> ( ) ; Map < String , T > lookup = new HashMap <> ( ) ; for ( T named : namedList ) { lookup . put ( named . getName ( ) , named ) ; } for ( String inc : includes ) { if ( use ( inc ) ) { T named = lookup . get ( inc ) ; if ( named == null ) { List < String > keys = new ArrayList <> ( lookup . keySet ( ) ) ; Collections . sort ( keys ) ; throw new IllegalArgumentException ( \"No \" + type + \" with name '\" + inc + \"' found to include. \" + \"Please check spelling in your profile / config and your project dependencies. Included \" + type + \"s: \" + StringUtils . join ( keys , \", \" ) ) ; } ret . add ( named ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge in another processor configuration with a lower priority . I . e . the latter a config is in the argument list the less priority it has . This means : [CODESPLIT] public static ProcessorConfig mergeProcessorConfigs ( ProcessorConfig ... processorConfigs ) { // Merge the configuration Map < String , TreeMap > configs = mergeConfig ( processorConfigs ) ; // Get all includes Set < String > excludes = mergeExcludes ( processorConfigs ) ; // Find the set of includes, which are the ones from the profile + the ones configured List < String > includes = mergeIncludes ( processorConfigs ) ; return new ProcessorConfig ( includes , excludes , configs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only good for small list ( that s what we expect for enrichers and generators ) [CODESPLIT] private static List < String > removeDups ( List < String > list ) { List < String > ret = new ArrayList <> ( ) ; for ( String el : list ) { if ( ! ret . contains ( el ) ) { ret . add ( el ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the base image either from configuration or from a given selector [CODESPLIT] protected void addFrom ( BuildImageConfiguration . Builder builder ) { String fromMode = getConfigWithFallback ( Config . fromMode , \"fabric8.generator.fromMode\" , getFromModeDefault ( context . getRuntimeMode ( ) ) ) ; String from = getConfigWithFallback ( Config . from , \"fabric8.generator.from\" , null ) ; if ( \"docker\" . equalsIgnoreCase ( fromMode ) ) { String fromImage = from ; if ( fromImage == null ) { fromImage = fromSelector != null ? fromSelector . getFrom ( ) : null ; } builder . from ( fromImage ) ; log . info ( \"Using Docker image %s as base / builder\" , fromImage ) ; } else if ( \"istag\" . equalsIgnoreCase ( fromMode ) ) { Map < String , String > fromExt = new HashMap <> ( ) ; if ( from != null ) { ImageName iName = new ImageName ( from ) ; // user/project is considered to be the namespace String tag = iName . getTag ( ) ; if ( StringUtils . isBlank ( tag ) ) { tag = \"latest\" ; } fromExt . put ( OpenShiftBuildStrategy . SourceStrategy . name . key ( ) , iName . getSimpleName ( ) + \":\" + tag ) ; if ( iName . getUser ( ) != null ) { fromExt . put ( OpenShiftBuildStrategy . SourceStrategy . namespace . key ( ) , iName . getUser ( ) ) ; } fromExt . put ( OpenShiftBuildStrategy . SourceStrategy . kind . key ( ) , \"ImageStreamTag\" ) ; } else { fromExt = fromSelector != null ? fromSelector . getImageStreamTagFromExt ( ) : null ; } if ( fromExt != null ) { String namespace = fromExt . get ( OpenShiftBuildStrategy . SourceStrategy . namespace . key ( ) ) ; if ( namespace != null ) { log . info ( \"Using ImageStreamTag '%s' from namespace '%s' as builder image\" , fromExt . get ( OpenShiftBuildStrategy . SourceStrategy . name . key ( ) ) , namespace ) ; } else { log . info ( \"Using ImageStreamTag '%s' as builder image\" , fromExt . get ( OpenShiftBuildStrategy . SourceStrategy . name . key ( ) ) ) ; } builder . fromExt ( fromExt ) ; } } else { throw new IllegalArgumentException ( String . format ( \"Invalid 'fromMode' in generator configuration for '%s'\" , getName ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use istag as default for redhat versions of this plugin [CODESPLIT] private String getFromModeDefault ( RuntimeMode mode ) { if ( mode == RuntimeMode . openshift && fromSelector != null && fromSelector . isRedHat ( ) ) { return \"istag\" ; } else { return \"docker\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Image name with a standard default [CODESPLIT] protected String getImageName ( ) { if ( RuntimeMode . isOpenShiftMode ( getProject ( ) . getProperties ( ) ) ) { return getConfigWithFallback ( Config . name , \"fabric8.generator.name\" , \"%a:%l\" ) ; } else { return getConfigWithFallback ( Config . name , \"fabric8.generator.name\" , \"%g/%a:%l\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the docker registry where the image should be located . It returns null in Openshift mode . [CODESPLIT] protected String getRegistry ( ) { if ( ! RuntimeMode . isOpenShiftMode ( getProject ( ) . getProperties ( ) ) ) { return getConfigWithFallback ( Config . registry , \"fabric8.generator.registry\" , null ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute path to a resource addressed by the given <code > url< / code > [CODESPLIT] public static String getAbsolutePath ( URL url ) { try { return url != null ? Paths . get ( url . toURI ( ) ) . toAbsolutePath ( ) . toString ( ) : null ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if in offline mode false if not speciied . Can be overriden by [CODESPLIT] boolean isOnline ( ) { String isOnline = getConfig ( Config . online ) ; if ( isOnline != null ) { return Configs . asBoolean ( isOnline ) ; } Boolean ret = asBooleanFromGlobalProp ( \"fabric8.online\" ) ; return ret != null ? ret : getDefaultOnline ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the external access to the given service name [CODESPLIT] protected String getExternalServiceURL ( String serviceName , String protocol ) { if ( ! isOnline ( ) ) { getLog ( ) . info ( \"Not looking for service \" + serviceName + \" as we are in offline mode\" ) ; return null ; } else { try { KubernetesClient kubernetes = getKubernetes ( ) ; String ns = kubernetes . getNamespace ( ) ; if ( StringUtils . isBlank ( ns ) ) { ns = getNamespace ( ) ; } Service service = kubernetes . services ( ) . inNamespace ( ns ) . withName ( serviceName ) . get ( ) ; return service != null ? ServiceUrlUtil . getServiceURL ( kubernetes , serviceName , ns , protocol , true ) : null ; } catch ( Throwable e ) { Throwable cause = e ; boolean notFound = false ; boolean connectError = false ; Stack < Throwable > stack = unfoldExceptions ( e ) ; while ( ! stack . isEmpty ( ) ) { Throwable t = stack . pop ( ) ; if ( t instanceof ConnectException || \"No route to host\" . equals ( t . getMessage ( ) ) ) { getLog ( ) . warn ( \"Cannot connect to Kubernetes to find URL for service %s : %s\" , serviceName , cause . getMessage ( ) ) ; return null ; } else if ( t instanceof IllegalArgumentException || t . getMessage ( ) != null && t . getMessage ( ) . matches ( \"^No.*found.*$\" ) ) { getLog ( ) . warn ( \"%s\" , cause . getMessage ( ) ) ; return null ; } ; } getLog ( ) . warn ( \"Cannot find URL for service %s : %s\" , serviceName , cause . getMessage ( ) ) ; return null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an Iterable to walk the exception from the bottom up ( the last caused by going upwards to the root exception ) . [CODESPLIT] protected Stack < Throwable > unfoldExceptions ( Throwable exception ) { Stack < Throwable > throwables = new Stack <> ( ) ; Throwable current = exception ; // spool to the bottom of the caused by tree while ( current != null ) { throwables . push ( current ) ; current = current . getCause ( ) ; } return throwables ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check a global prop from the project or system props [CODESPLIT] protected Boolean asBooleanFromGlobalProp ( String prop ) { String value = getContext ( ) . getConfiguration ( ) . getProperty ( prop ) ; if ( value == null ) { value = System . getProperty ( prop ) ; } return value != null ? Boolean . valueOf ( value ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- default [CODESPLIT] private String getNamespace ( ) { String namespace = getConfig ( Config . namespace ) ; if ( StringUtils . isNotBlank ( namespace ) ) { return namespace ; } namespace = getContext ( ) . getConfiguration ( ) . getProperty ( \"fabric8.namespace\" ) ; if ( StringUtils . isNotBlank ( namespace ) ) { return namespace ; } namespace = System . getProperty ( \"fabric8.namespace\" ) ; if ( StringUtils . isNotBlank ( namespace ) ) { return namespace ; } return KubernetesHelper . getDefaultNamespace ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create Jest client with URI [CODESPLIT] private JestClient createJestClient ( String uri ) { HttpClientConfig . Builder builder = new HttpClientConfig . Builder ( uri ) . maxTotalConnection ( properties . getMaxTotalConnection ( ) ) . defaultMaxTotalConnectionPerRoute ( properties . getDefaultMaxTotalConnectionPerRoute ( ) ) . maxConnectionIdleTime ( properties . getMaxConnectionIdleTime ( ) , TimeUnit . MILLISECONDS ) . readTimeout ( properties . getReadTimeout ( ) ) . multiThreaded ( properties . getMultiThreaded ( ) ) ; if ( StringUtils . hasText ( this . properties . getUsername ( ) ) ) { builder . defaultCredentials ( this . properties . getUsername ( ) , this . properties . getPassword ( ) ) ; } String proxyHost = this . properties . getProxy ( ) . getHost ( ) ; if ( StringUtils . hasText ( proxyHost ) ) { Integer proxyPort = this . properties . getProxy ( ) . getPort ( ) ; Assert . notNull ( proxyPort , \"Proxy port must not be null\" ) ; builder . proxy ( new HttpHost ( proxyHost , proxyPort ) ) ; } List < HttpClientConfigBuilderCustomizer > configBuilderCustomizers = builderCustomizers != null ? builderCustomizers . getIfAvailable ( ) : new ArrayList <> ( ) ; if ( ! CollectionUtils . isEmpty ( configBuilderCustomizers ) ) { logger . info ( \"Custom HttpClientConfigBuilderCustomizers detected. Applying these to the HttpClientConfig builder.\" ) ; configBuilderCustomizers . stream ( ) . forEach ( customizer -> customizer . customize ( builder ) ) ; logger . info ( \"Custom HttpClientConfigBuilderCustomizers applied.\" ) ; } JestClientFactory factory = jestClientFactory != null ? jestClientFactory : new JestClientFactory ( ) ; factory . setHttpClientConfig ( builder . build ( ) ) ; return factory . getObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create internal Elasticsearch node . [CODESPLIT] private int createInternalNode ( ) throws NodeValidationException { if ( logger . isInfoEnabled ( ) ) { logger . info ( \"Create test ES node\" ) ; } int port = SocketUtils . findAvailableTcpPort ( ) ; String clusterName = INTERNAL_TEST_CLUSTER_NAME + UUID . randomUUID ( ) ; Settings . Builder settingsBuilder = Settings . builder ( ) . put ( \"cluster.name\" , clusterName ) . put ( \"http.type\" , \"netty4\" ) . put ( \"http.port\" , String . valueOf ( port ) ) ; if ( this . esNodeproperties != null ) { this . esNodeproperties . getProperties ( ) . forEach ( settingsBuilder :: put ) ; } Collection < Class < ? extends Plugin > > plugins = scanPlugins ( ) ; plugins . add ( Netty4Plugin . class ) ; this . node = new InternalNode ( settingsBuilder . build ( ) , plugins ) . start ( ) ; return Integer . parseInt ( settingsBuilder . get ( \"http.port\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List all official ES plugins available on ClassPath . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static Collection < Class < ? extends Plugin > > scanPlugins ( ) { ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider ( false ) ; componentProvider . addIncludeFilter ( new AssignableTypeFilter ( Plugin . class ) ) ; return componentProvider . findCandidateComponents ( \"org.elasticsearch.plugin\" ) . stream ( ) . map ( BeanDefinition :: getBeanClassName ) . map ( name -> { try { return ( Class < ? extends Plugin > ) Class . forName ( name ) ; } catch ( ClassNotFoundException e ) { logger . warn ( \"Cannot load class on plugin detection\" , e ) ; return null ; } } ) . collect ( Collectors . toSet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extract the distance string from a { @link org . springframework . data . geo . Distance } object . [CODESPLIT] private void extractDistanceString ( Distance distance , StringBuilder sb ) { // handle Distance object sb . append ( ( int ) distance . getValue ( ) ) ; Metrics metric = ( Metrics ) distance . getMetric ( ) ; switch ( metric ) { case KILOMETERS : sb . append ( \"km\" ) ; break ; case MILES : sb . append ( \"mi\" ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add mapping for @Field annotation [CODESPLIT] private static void addSingleFieldMapping ( XContentBuilder builder , java . lang . reflect . Field field , Field annotation , boolean nestedOrObjectField ) throws IOException { builder . startObject ( field . getName ( ) ) ; addFieldMappingParameters ( builder , annotation , nestedOrObjectField ) ; builder . endObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add mapping for @MultiField annotation [CODESPLIT] private static void addMultiFieldMapping ( XContentBuilder builder , java . lang . reflect . Field field , MultiField annotation , boolean nestedOrObjectField ) throws IOException { // main field builder . startObject ( field . getName ( ) ) ; addFieldMappingParameters ( builder , annotation . mainField ( ) , nestedOrObjectField ) ; // inner fields builder . startObject ( \"fields\" ) ; for ( InnerField innerField : annotation . otherFields ( ) ) { builder . startObject ( innerField . suffix ( ) ) ; addFieldMappingParameters ( builder , innerField , false ) ; builder . endObject ( ) ; } builder . endObject ( ) ; builder . endObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a { @link GraphQLConfiguration } from json . [CODESPLIT] public static GraphQLConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } GraphQLConfiguration graphQLConfiguration = new GraphQLConfiguration ( ) ; graphQLConfiguration . mUrl = Json . optString ( json , Keys . URL , \"\" ) ; graphQLConfiguration . mFeatures = parseJsonFeatures ( json . optJSONArray ( Keys . FEATURES ) ) ; return graphQLConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a Client Metadata ID at the time of payment activity . Once a user initiates a PayPal payment from their device PayPal uses the Client Metadata ID to verify that the payment is originating from a valid user - consented device and application . This helps reduce fraud and decrease declines . This method MUST be called prior to initiating a pre - consented payment ( a future payment ) from a mobile device . Pass the result to your server to include in the payment request sent to PayPal . Do not otherwise cache or store this value . [CODESPLIT] @ MainThread public static String getClientMetadataId ( Context context ) { PayPalDataCollectorRequest request = new PayPalDataCollectorRequest ( ) . setApplicationGuid ( InstallationIdentifier . getInstallationGUID ( context ) ) ; return getClientMetadataId ( context , request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a Client Metadata ID at the time of payment activity . Once a user initiates a PayPal payment from their device PayPal uses the Client Metadata ID to verify that the payment is originating from a valid user - consented device and application . This helps reduce fraud and decrease declines . This method MUST be called prior to initiating a pre - consented payment ( a future payment ) from a mobile device . Pass the result to your server to include in the payment request sent to PayPal . Do not otherwise cache or store this value . [CODESPLIT] @ MainThread public static String getClientMetadataId ( Context context , PayPalDataCollectorRequest request ) { if ( context == null ) { return \"\" ; } MagnesSDK magnesInstance = MagnesSDK . getInstance ( ) ; MagnesSettings . Builder magnesSettingsBuilder = new MagnesSettings . Builder ( context ) . setMagnesSource ( MagnesSource . BRAINTREE ) . disableBeacon ( request . isDisableBeacon ( ) ) . setMagnesEnvironment ( Environment . LIVE ) . setAppGuid ( request . getApplicationGuid ( ) ) ; magnesInstance . setUp ( magnesSettingsBuilder . build ( ) ) ; MagnesResult result = magnesInstance . collectAndSubmit ( context , request . getClientMetadataId ( ) , request . getAdditionalData ( ) ) ; return result . getPaypalClientMetaDataId ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to parse a response from the Braintree Gateway to be used for American Express rewards balance . [CODESPLIT] public static AmericanExpressRewardsBalance fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; AmericanExpressRewardsBalance rewardsBalance = new AmericanExpressRewardsBalance ( ) ; if ( json . has ( ERROR_KEY ) ) { JSONObject errorJson = json . getJSONObject ( ERROR_KEY ) ; rewardsBalance . mErrorMessage = errorJson . getString ( ERROR_MESSAGE_KEY ) ; rewardsBalance . mErrorCode = errorJson . getString ( ERROR_CODE_KEY ) ; } rewardsBalance . mConversionRate = Json . optString ( json , CONVERSION_RATE_KEY , null ) ; rewardsBalance . mCurrencyAmount = Json . optString ( json , CURRENCY_AMOUNT_KEY , null ) ; rewardsBalance . mCurrencyIsoCode = Json . optString ( json , CURRENCY_ISO_CODE_KEY , null ) ; rewardsBalance . mRequestId = Json . optString ( json , REQUEST_ID_KEY , null ) ; rewardsBalance . mRewardsAmount = Json . optString ( json , REWARDS_AMOUNT_KEY , null ) ; rewardsBalance . mRewardsUnit = Json . optString ( json , REWARDS_UNIT_KEY , null ) ; return rewardsBalance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an API response to an { @link VenmoAccountNonce } . [CODESPLIT] public static VenmoAccountNonce fromJson ( String json ) throws JSONException { VenmoAccountNonce venmoAccountNonce = new VenmoAccountNonce ( ) ; venmoAccountNonce . fromJson ( VenmoAccountNonce . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return venmoAccountNonce ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches the capabilities of a card . If the card needs to be enrolled use { @link UnionPay#enroll ( BraintreeFragment UnionPayCardBuilder ) } . <p / > On completion returns the { @link UnionPayCapabilities } to { @link com . braintreepayments . api . interfaces . UnionPayListener#onCapabilitiesFetched ( UnionPayCapabilities ) } <p / > On error an exception will be passed back to { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } [CODESPLIT] public static void fetchCapabilities ( final BraintreeFragment fragment , final String cardNumber ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( ! configuration . getUnionPay ( ) . isEnabled ( ) ) { fragment . postCallback ( new ConfigurationException ( \"UnionPay is not enabled\" ) ) ; return ; } String fetchCapabilitiesUrl = Uri . parse ( UNIONPAY_CAPABILITIES_PATH ) . buildUpon ( ) . appendQueryParameter ( \"creditCard[number]\" , cardNumber ) . build ( ) . toString ( ) ; fragment . getHttpClient ( ) . get ( fetchCapabilitiesUrl , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { fragment . postCallback ( UnionPayCapabilities . fromJson ( responseBody ) ) ; fragment . sendAnalyticsEvent ( \"union-pay.capabilities-received\" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( \"union-pay.capabilities-failed\" ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enrolls a Union Pay card . Only call this method if the card needs to be enrolled . Check { @link UnionPay#fetchCapabilities ( BraintreeFragment String ) } if your card needs to be enrolled . <p / > On completion returns a enrollmentId to { @link com . braintreepayments . api . interfaces . UnionPayListener#onSmsCodeSent ( String boolean ) } This enrollmentId needs to be applied to { @link UnionPayCardBuilder } along with the SMS code collected from the merchant before invoking { @link UnionPay#tokenize ( BraintreeFragment UnionPayCardBuilder ) } <p / > On error an exception will be passed back to { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } [CODESPLIT] public static void enroll ( final BraintreeFragment fragment , final UnionPayCardBuilder unionPayCardBuilder ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { UnionPayConfiguration unionPayConfiguration = configuration . getUnionPay ( ) ; if ( ! unionPayConfiguration . isEnabled ( ) ) { fragment . postCallback ( new ConfigurationException ( \"UnionPay is not enabled\" ) ) ; return ; } try { JSONObject enrollmentPayloadJson = unionPayCardBuilder . buildEnrollment ( ) ; fragment . getHttpClient ( ) . post ( UNIONPAY_ENROLLMENT_PATH , enrollmentPayloadJson . toString ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { JSONObject response = new JSONObject ( responseBody ) ; String enrollmentId = response . getString ( UNIONPAY_ENROLLMENT_ID_KEY ) ; boolean smsCodeRequired = response . getBoolean ( UNIONPAY_SMS_REQUIRED_KEY ) ; fragment . postUnionPayCallback ( enrollmentId , smsCodeRequired ) ; fragment . sendAnalyticsEvent ( \"union-pay.enrollment-succeeded\" ) ; } catch ( JSONException e ) { failure ( e ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( \"union-pay.enrollment-failed\" ) ; } } ) ; } catch ( JSONException exception ) { fragment . postCallback ( exception ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link com . braintreepayments . api . models . CardNonce } . Note that if the card is a UnionPay card { @link UnionPayCardBuilder#enrollmentId ( String ) } and { @link UnionPayCardBuilder#smsCode ( String ) } need to be set for tokenization to succeed . <p / > On completion returns the { @link com . braintreepayments . api . models . PaymentMethodNonce } to { @link com . braintreepayments . api . interfaces . PaymentMethodNonceCreatedListener } . <p / > If creation fails validation { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the resulting { @link com . braintreepayments . api . exceptions . ErrorWithResponse } . <p / > If an error not due to validation ( server error network issue etc . ) occurs { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the { @link Exception } that occurred . [CODESPLIT] public static void tokenize ( final BraintreeFragment fragment , final UnionPayCardBuilder unionPayCardBuilder ) { TokenizationClient . tokenize ( fragment , unionPayCardBuilder , new PaymentMethodNonceCallback ( ) { @ Override public void success ( PaymentMethodNonce paymentMethodNonce ) { fragment . postCallback ( paymentMethodNonce ) ; fragment . sendAnalyticsEvent ( \"union-pay.nonce-received\" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( \"union-pay.nonce-failed\" ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an API response to a { @link LocalPaymentResult } . [CODESPLIT] public static LocalPaymentResult fromJson ( String json ) throws JSONException { LocalPaymentResult localPaymentResult = new LocalPaymentResult ( ) ; localPaymentResult . fromJson ( LocalPaymentResult . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return localPaymentResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a { @link LocalPaymentResult } from the { @link JSONObject } . [CODESPLIT] protected void fromJson ( JSONObject json ) throws JSONException { super . fromJson ( json ) ; JSONObject details = json . getJSONObject ( DETAILS_KEY ) ; mEmail = Json . optString ( details , EMAIL_KEY , null ) ; mClientMetadataId = Json . optString ( details , CLIENT_METADATA_ID_KEY , null ) ; mType = Json . optString ( json , TYPE_KEY , \"PayPalAccount\" ) ; try { JSONObject payerInfo = details . getJSONObject ( PAYER_INFO_KEY ) ; JSONObject billingAddress ; if ( payerInfo . has ( ACCOUNT_ADDRESS_KEY ) ) { billingAddress = payerInfo . optJSONObject ( ACCOUNT_ADDRESS_KEY ) ; } else { billingAddress = payerInfo . optJSONObject ( BILLING_ADDRESS_KEY ) ; } JSONObject shippingAddress = payerInfo . optJSONObject ( SHIPPING_ADDRESS_KEY ) ; mBillingAddress = PostalAddressParser . fromJson ( billingAddress ) ; mShippingAddress = PostalAddressParser . fromJson ( shippingAddress ) ; mGivenName = Json . optString ( payerInfo , FIRST_NAME_KEY , \"\" ) ; mSurname = Json . optString ( payerInfo , LAST_NAME_KEY , \"\" ) ; mPhone = Json . optString ( payerInfo , PHONE_KEY , \"\" ) ; mPayerId = Json . optString ( payerInfo , PAYER_ID_KEY , \"\" ) ; if ( mEmail == null ) { mEmail = Json . optString ( payerInfo , EMAIL_KEY , null ) ; } } catch ( JSONException e ) { mBillingAddress = new PostalAddress ( ) ; mShippingAddress = new PostalAddress ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launches an { @link Intent } pointing to the Venmo app on the Google Play Store [CODESPLIT] public static void openVenmoAppPageInGooglePlay ( BraintreeFragment fragment ) { fragment . sendAnalyticsEvent ( \"android.pay-with-venmo.app-store.invoked\" ) ; Intent intent = new Intent ( Intent . ACTION_VIEW ) ; intent . setData ( Uri . parse ( \"https://play.google.com/store/apps/details?id=\" + PACKAGE_NAME ) ) ; fragment . startActivity ( intent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the Pay With Venmo flow . This will app switch to the Venmo app . <p / > If the Venmo app is not available { @link AppSwitchNotAvailableException } will be sent to { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } . [CODESPLIT] public static void authorizeAccount ( final BraintreeFragment fragment , final boolean vault , final String profileId ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { fragment . sendAnalyticsEvent ( \"pay-with-venmo.selected\" ) ; String venmoProfileId = profileId ; if ( TextUtils . isEmpty ( venmoProfileId ) ) { venmoProfileId = configuration . getPayWithVenmo ( ) . getMerchantId ( ) ; } String exceptionMessage = \"\" ; if ( ! configuration . getPayWithVenmo ( ) . isAccessTokenValid ( ) ) { exceptionMessage = \"Venmo is not enabled\" ; } else if ( ! Venmo . isVenmoInstalled ( fragment . getApplicationContext ( ) ) ) { exceptionMessage = \"Venmo is not installed\" ; } if ( ! TextUtils . isEmpty ( exceptionMessage ) ) { fragment . postCallback ( new AppSwitchNotAvailableException ( exceptionMessage ) ) ; fragment . sendAnalyticsEvent ( \"pay-with-venmo.app-switch.failed\" ) ; } else { persistVenmoVaultOption ( vault && fragment . getAuthorization ( ) instanceof ClientToken , fragment . getApplicationContext ( ) ) ; fragment . startActivityForResult ( getLaunchIntent ( configuration . getPayWithVenmo ( ) , venmoProfileId , fragment ) , BraintreeRequestCodes . VENMO ) ; fragment . sendAnalyticsEvent ( \"pay-with-venmo.app-switch.started\" ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a { @link CardConfiguration } from json . [CODESPLIT] public static CardConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } CardConfiguration cardConfiguration = new CardConfiguration ( ) ; JSONArray jsonArray = json . optJSONArray ( SUPPORTED_CARD_TYPES_KEY ) ; if ( jsonArray != null ) { for ( int i = 0 ; i < jsonArray . length ( ) ; i ++ ) { cardConfiguration . mSupportedCardTypes . add ( jsonArray . optString ( i , \"\" ) ) ; } } cardConfiguration . mCollectFraudData = json . optBoolean ( COLLECT_DEVICE_DATA_KEY , false ) ; return cardConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the rewards balance associated with a Braintree nonce . Only for American Express cards . [CODESPLIT] public static void getRewardsBalance ( final BraintreeFragment fragment , final String nonce , final String currencyIsoCode ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { String getRewardsBalanceUrl = Uri . parse ( AMEX_REWARDS_BALANCE_PATH ) . buildUpon ( ) . appendQueryParameter ( \"paymentMethodNonce\" , nonce ) . appendQueryParameter ( \"currencyIsoCode\" , currencyIsoCode ) . build ( ) . toString ( ) ; fragment . sendAnalyticsEvent ( \"amex.rewards-balance.start\" ) ; fragment . getHttpClient ( ) . get ( getRewardsBalanceUrl , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { fragment . sendAnalyticsEvent ( \"amex.rewards-balance.success\" ) ; try { fragment . postAmericanExpressCallback ( AmericanExpressRewardsBalance . fromJson ( responseBody ) ) ; } catch ( JSONException e ) { fragment . sendAnalyticsEvent ( \"amex.rewards-balance.parse.failed\" ) ; fragment . postCallback ( e ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( \"amex.rewards-balance.error\" ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a PayPalPaymentResource from a jsonString . Checks for keys associated with Single Payment and Billing Agreement flows . [CODESPLIT] public static PayPalPaymentResource fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; PayPalPaymentResource payPalPaymentResource = new PayPalPaymentResource ( ) ; JSONObject redirectJson = json . optJSONObject ( PAYMENT_RESOURCE_KEY ) ; if ( redirectJson != null ) { payPalPaymentResource . redirectUrl ( Json . optString ( redirectJson , REDIRECT_URL_KEY , \"\" ) ) ; } else { redirectJson = json . optJSONObject ( AGREEMENT_SETUP_KEY ) ; payPalPaymentResource . redirectUrl ( Json . optString ( redirectJson , APPROVAL_URL_KEY , \"\" ) ) ; } return payPalPaymentResource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a HTTP GET request to Braintree using the base url path and authorization provided . If the path is a full url it will be used instead of the previously provided url . [CODESPLIT] @ Override public void get ( String path , HttpResponseCallback callback ) { if ( path == null ) { postCallbackOnMainThread ( callback , new IllegalArgumentException ( \"Path cannot be null\" ) ) ; return ; } Uri uri ; if ( path . startsWith ( \"http\" ) ) { uri = Uri . parse ( path ) ; } else { uri = Uri . parse ( mBaseUrl + path ) ; } if ( mAuthorization instanceof ClientToken ) { uri = uri . buildUpon ( ) . appendQueryParameter ( AUTHORIZATION_FINGERPRINT_KEY , ( ( ClientToken ) mAuthorization ) . getAuthorizationFingerprint ( ) ) . build ( ) ; } super . get ( uri . toString ( ) , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a HTTP POST request to Braintree using the base url path and authorization provided . If the path is a full url it will be used instead of the previously provided url . [CODESPLIT] @ Override public void post ( String path , String data , HttpResponseCallback callback ) { try { if ( mAuthorization instanceof ClientToken ) { data = new JSONObject ( data ) . put ( AUTHORIZATION_FINGERPRINT_KEY , ( ( ClientToken ) mAuthorization ) . getAuthorizationFingerprint ( ) ) . toString ( ) ; } super . post ( path , data , callback ) ; } catch ( JSONException e ) { postCallbackOnMainThread ( callback , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a synchronous HTTP POST request to Braintree using the base url path and authorization provided . @see BraintreeHttpClient#post ( String String HttpResponseCallback ) [CODESPLIT] public String post ( String path , String data ) throws Exception { if ( mAuthorization instanceof ClientToken ) { data = new JSONObject ( data ) . put ( AUTHORIZATION_FINGERPRINT_KEY , ( ( ClientToken ) mAuthorization ) . getAuthorizationFingerprint ( ) ) . toString ( ) ; } return super . post ( path , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the Venmo configuration from json . [CODESPLIT] static VenmoConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } VenmoConfiguration venmoConfiguration = new VenmoConfiguration ( ) ; venmoConfiguration . mAccessToken = Json . optString ( json , ACCESS_TOKEN_KEY , \"\" ) ; venmoConfiguration . mEnvironment = Json . optString ( json , ENVIRONMENT_KEY , \"\" ) ; venmoConfiguration . mMerchantId = Json . optString ( json , MERCHANT_ID_KEY , \"\" ) ; return venmoConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to parse a response from the Braintree Gateway to be used for 3D Secure . [CODESPLIT] public static ThreeDSecureAuthenticationResponse fromJson ( String jsonString ) { ThreeDSecureAuthenticationResponse authenticationResponse = new ThreeDSecureAuthenticationResponse ( ) ; try { JSONObject json = new JSONObject ( jsonString ) ; JSONObject cardJson = json . optJSONObject ( PAYMENT_METHOD_KEY ) ; if ( cardJson != null ) { CardNonce cardNonce = new CardNonce ( ) ; cardNonce . fromJson ( cardJson ) ; authenticationResponse . mCardNonce = cardNonce ; } authenticationResponse . mSuccess = json . getBoolean ( SUCCESS_KEY ) ; if ( ! authenticationResponse . mSuccess ) { authenticationResponse . mErrors = jsonString ; } } catch ( JSONException e ) { authenticationResponse . mSuccess = false ; } return authenticationResponse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect device information for fraud identification purposes . [CODESPLIT] public static void collectDeviceData ( BraintreeFragment fragment , BraintreeResponseListener < String > listener ) { collectDeviceData ( fragment , null , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect device information for fraud identification purposes . This should be used in conjunction with a non - aggregate fraud id . [CODESPLIT] public static void collectDeviceData ( final BraintreeFragment fragment , final String merchantId , final BraintreeResponseListener < String > listener ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { final JSONObject deviceData = new JSONObject ( ) ; try { String clientMetadataId = getPayPalClientMetadataId ( fragment . getApplicationContext ( ) ) ; if ( ! TextUtils . isEmpty ( clientMetadataId ) ) { deviceData . put ( CORRELATION_ID_KEY , clientMetadataId ) ; } } catch ( JSONException ignored ) { } if ( configuration . getKount ( ) . isEnabled ( ) ) { final String id ; if ( merchantId != null ) { id = merchantId ; } else { id = configuration . getKount ( ) . getKountMerchantId ( ) ; } try { final String deviceSessionId = UUIDHelper . getFormattedUUID ( ) ; startDeviceCollector ( fragment , id , deviceSessionId , new BraintreeResponseListener < String > ( ) { @ Override public void onResponse ( String sessionId ) { try { deviceData . put ( DEVICE_SESSION_ID_KEY , deviceSessionId ) ; deviceData . put ( FRAUD_MERCHANT_ID_KEY , id ) ; } catch ( JSONException ignored ) { } listener . onResponse ( deviceData . toString ( ) ) ; } } ) ; } catch ( ClassNotFoundException | NoClassDefFoundError | NumberFormatException ignored ) { listener . onResponse ( deviceData . toString ( ) ) ; } } else { listener . onResponse ( deviceData . toString ( ) ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect PayPal device information for fraud identification purposes . [CODESPLIT] public static void collectPayPalDeviceData ( final BraintreeFragment fragment , final BraintreeResponseListener < String > listener ) { final JSONObject deviceData = new JSONObject ( ) ; try { String clientMetadataId = getPayPalClientMetadataId ( fragment . getApplicationContext ( ) ) ; if ( ! TextUtils . isEmpty ( clientMetadataId ) ) { deviceData . put ( CORRELATION_ID_KEY , clientMetadataId ) ; } } catch ( JSONException ignored ) { } listener . onResponse ( deviceData . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect device information for fraud identification purposes from PayPal only . [CODESPLIT] public static String getPayPalClientMetadataId ( Context context ) { try { return PayPalOneTouchCore . getClientMetadataId ( context ) ; } catch ( NoClassDefFoundError ignored ) { } try { return PayPalDataCollector . getClientMetadataId ( context ) ; } catch ( NoClassDefFoundError ignored ) { } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if an app has the correct matching signature . Used to prevent malicious apps from impersonating other apps . [CODESPLIT] @ SuppressLint ( \"PackageManagerGetSignatures\" ) public static boolean isSignatureValid ( Context context , String packageName , String certificateSubject , String certificateIssuer , int publicKeyHashCode ) { if ( ! sEnableSignatureVerification ) { return true ; } PackageManager packageManager = context . getPackageManager ( ) ; Signature [ ] signatures ; try { signatures = packageManager . getPackageInfo ( packageName , PackageManager . GET_SIGNATURES ) . signatures ; } catch ( NameNotFoundException e ) { return false ; } InputStream certStream = null ; boolean validated = ( signatures . length != 0 ) ; for ( Signature signature : signatures ) { try { certStream = new ByteArrayInputStream ( signature . toByteArray ( ) ) ; X509Certificate x509Cert = ( X509Certificate ) CertificateFactory . getInstance ( \"X509\" ) . generateCertificate ( certStream ) ; String subject = x509Cert . getSubjectX500Principal ( ) . getName ( ) ; String issuer = x509Cert . getIssuerX500Principal ( ) . getName ( ) ; int actualPublicKeyHashCode = x509Cert . getPublicKey ( ) . hashCode ( ) ; validated &= ( certificateSubject . equals ( subject ) && certificateIssuer . equals ( issuer ) && publicKeyHashCode == actualPublicKeyHashCode ) ; if ( ! validated ) { return false ; } } catch ( CertificateException e ) { return false ; } finally { try { if ( certStream != null ) { certStream . close ( ) ; } } catch ( IOException ignored ) { } } } return validated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the current list of { @link PaymentMethodNonce } s for the current customer . <p / > When finished the { @link java . util . List } of { @link PaymentMethodNonce } s will be sent to { @link PaymentMethodNoncesUpdatedListener#onPaymentMethodNoncesUpdated ( List ) } . [CODESPLIT] public static void getPaymentMethodNonces ( final BraintreeFragment fragment , boolean defaultFirst ) { final Uri uri = Uri . parse ( TokenizationClient . versionedPath ( TokenizationClient . PAYMENT_METHOD_ENDPOINT ) ) . buildUpon ( ) . appendQueryParameter ( \"default_first\" , String . valueOf ( defaultFirst ) ) . appendQueryParameter ( \"session_id\" , fragment . getSessionId ( ) ) . build ( ) ; fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { fragment . getHttpClient ( ) . get ( uri . toString ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { fragment . postCallback ( PaymentMethodNonce . parsePaymentMethodNonces ( responseBody ) ) ; fragment . sendAnalyticsEvent ( \"get-payment-methods.succeeded\" ) ; } catch ( JSONException e ) { fragment . postCallback ( e ) ; fragment . sendAnalyticsEvent ( \"get-payment-methods.failed\" ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( \"get-payment-methods.failed\" ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes a payment method owned by the customer whose id was used to generate the { @link ClientToken } used to create the { @link BraintreeFragment } . <p / > Note : This method only works with Android Lollipop ( > = 21 ) and above . This will invoke { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } when <ul > <li > A { @link com . braintreepayments . api . models . TokenizationKey } is used . < / li > <li > The device is below Lollipop . < / li > <li > If the request fails . < / li > <ul / > [CODESPLIT] public static void deletePaymentMethod ( final BraintreeFragment fragment , final PaymentMethodNonce paymentMethodNonce ) { boolean usesClientToken = fragment . getAuthorization ( ) instanceof ClientToken ; if ( ! usesClientToken ) { fragment . postCallback ( new BraintreeException ( \"A client token with a customer id must be used to delete a payment method nonce.\" ) ) ; return ; } JSONObject base = new JSONObject ( ) ; JSONObject variables = new JSONObject ( ) ; JSONObject input = new JSONObject ( ) ; try { base . put ( CLIENT_SDK_META_DATA , new MetadataBuilder ( ) . sessionId ( fragment . getSessionId ( ) ) . source ( \"client\" ) . integration ( fragment . getIntegrationType ( ) ) . build ( ) ) ; base . put ( GraphQLConstants . Keys . QUERY , GraphQLQueryHelper . getQuery ( fragment . getApplicationContext ( ) , R . raw . delete_payment_method_mutation ) ) ; input . put ( SINGLE_USE_TOKEN_ID , paymentMethodNonce . getNonce ( ) ) ; variables . put ( INPUT , input ) ; base . put ( VARIABLES , variables ) ; base . put ( GraphQLConstants . Keys . OPERATION_NAME , \"DeletePaymentMethodFromSingleUseToken\" ) ; } catch ( Resources . NotFoundException | IOException | JSONException e ) { fragment . postCallback ( new BraintreeException ( \"Unable to read GraphQL query\" ) ) ; } fragment . getGraphQLHttpClient ( ) . post ( base . toString ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { fragment . postPaymentMethodDeletedCallback ( paymentMethodNonce ) ; fragment . sendAnalyticsEvent ( \"delete-payment-methods.succeeded\" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( new PaymentMethodDeleteException ( paymentMethodNonce , exception ) ) ; fragment . sendAnalyticsEvent ( \"delete-payment-methods.failed\" ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a { @link PendingRequest } containing an { @link Intent } used to start a PayPal authentication request using the best possible authentication mechanism : wallet or browser . [CODESPLIT] public static PendingRequest getStartIntent ( Context context , Request request ) { initService ( context ) ; // calling this method functionally does nothing, but ensures that we send off FPTI data about wallet installs. isWalletAppInstalled ( context ) ; Recipe recipe = request . getRecipeToExecute ( context , sConfigManager . getConfig ( ) ) ; if ( recipe == null ) { return new PendingRequest ( false , null , null , null ) ; } if ( RequestTarget . wallet == recipe . getTarget ( ) ) { request . trackFpti ( context , TrackingPoint . SwitchToWallet , recipe . getProtocol ( ) ) ; return new PendingRequest ( true , RequestTarget . wallet , request . getClientMetadataId ( ) , AppSwitchHelper . getAppSwitchIntent ( sContextInspector , sConfigManager , request , recipe ) ) ; } else { Intent intent = BrowserSwitchHelper . getBrowserSwitchIntent ( sContextInspector , sConfigManager , request ) ; if ( intent != null ) { return new PendingRequest ( true , RequestTarget . browser , request . getClientMetadataId ( ) , intent ) ; } else { return new PendingRequest ( false , RequestTarget . browser , request . getClientMetadataId ( ) , null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a { @link Result } from an { @link Intent } returned by either the PayPal Wallet app or the browser . [CODESPLIT] public static Result parseResponse ( Context context , Request request , Intent data ) { initService ( context ) ; if ( data != null && data . getData ( ) != null ) { return BrowserSwitchHelper . parseBrowserSwitchResponse ( sContextInspector , request , data . getData ( ) ) ; } else if ( data != null && data . getExtras ( ) != null && ! data . getExtras ( ) . isEmpty ( ) ) { return AppSwitchHelper . parseAppSwitchResponse ( sContextInspector , request , data ) ; } else { request . trackFpti ( context , TrackingPoint . Cancel , null ) ; return new Result ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a Client Metadata ID at the time of payment activity . Once a user initiates a PayPal payment from their device PayPal uses the Client Metadata ID to verify that the payment is originating from a valid user - consented device and application . This helps reduce fraud and decrease declines . This method MUST be called prior to initiating a pre - consented payment ( a future payment ) from a mobile device . Pass the result to your server to include in the payment request sent to PayPal . Do not otherwise cache or store this value . [CODESPLIT] @ MainThread public static String getClientMetadataId ( Context context , String pairingId ) { return PayPalDataCollector . getClientMetadataId ( context , pairingId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verification is associated with a transaction amount and your merchant account . To specify a different merchant account ( or in turn currency ) you will need to specify the merchant account id when <a href = https : // developers . braintreepayments . com / android / sdk / overview / generate - client - token > generating a client token< / a > [CODESPLIT] public static void performVerification ( final BraintreeFragment fragment , final CardBuilder cardBuilder , final String amount ) { TokenizationClient . tokenize ( fragment , cardBuilder , new PaymentMethodNonceCallback ( ) { @ Override public void success ( PaymentMethodNonce paymentMethodNonce ) { performVerification ( fragment , paymentMethodNonce . getNonce ( ) , amount ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verification is associated with a transaction amount and your merchant account . To specify a different merchant account ( or in turn currency ) you will need to specify the merchant account id when <a href = https : // developers . braintreepayments . com / android / sdk / overview / generate - client - token > generating a client token< / a > [CODESPLIT] public static void performVerification ( final BraintreeFragment fragment , final String nonce , final String amount ) { ThreeDSecureRequest request = new ThreeDSecureRequest ( ) . nonce ( nonce ) . amount ( amount ) ; performVerification ( fragment , request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verification is associated with a transaction amount and your merchant account . To specify a different merchant account ( or in turn currency ) you will need to specify the merchant account id when <a href = https : // developers . braintreepayments . com / android / sdk / overview / generate - client - token > generating a client token< / a > [CODESPLIT] public static void performVerification ( final BraintreeFragment fragment , final ThreeDSecureRequest request ) { if ( request . getAmount ( ) == null || request . getNonce ( ) == null ) { fragment . postCallback ( new InvalidArgumentException ( \"The ThreeDSecureRequest nonce and amount cannot be null\" ) ) ; return ; } fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( ! configuration . isThreeDSecureEnabled ( ) ) { fragment . postCallback ( new BraintreeException ( \"Three D Secure is not enabled in the control panel\" ) ) ; return ; } final boolean supportsBrowserSwitch = ManifestValidator . isUrlSchemeDeclaredInAndroidManifest ( fragment . getApplicationContext ( ) , fragment . getReturnUrlScheme ( ) , BraintreeBrowserSwitchActivity . class ) ; if ( ! supportsBrowserSwitch ) { fragment . sendAnalyticsEvent ( \"three-d-secure.invalid-manifest\" ) ; fragment . postCallback ( new BraintreeException ( \"BraintreeBrowserSwitchActivity missing, \" + \"incorrectly configured in AndroidManifest.xml or another app defines the same browser \" + \"switch url as this app. See \" + \"https://developers.braintreepayments.com/guides/client-sdk/android/v2#browser-switch \" + \"for the correct configuration\" ) ) ; return ; } fragment . getHttpClient ( ) . post ( TokenizationClient . versionedPath ( TokenizationClient . PAYMENT_METHOD_ENDPOINT + \"/\" + request . getNonce ( ) + \"/three_d_secure/lookup\" ) , request . build ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { ThreeDSecureLookup threeDSecureLookup = ThreeDSecureLookup . fromJson ( responseBody ) ; if ( threeDSecureLookup . getAcsUrl ( ) != null ) { launchBrowserSwitch ( fragment , threeDSecureLookup ) ; } else { fragment . postCallback ( threeDSecureLookup . getCardNonce ( ) ) ; } } catch ( JSONException e ) { fragment . postCallback ( e ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a { @link KountConfiguration } from json . [CODESPLIT] public static KountConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } KountConfiguration kountConfiguration = new KountConfiguration ( ) ; kountConfiguration . mKountMerchantId = Json . optString ( json , KOUNT_MERCHANT_ID_KEY , \"\" ) ; return kountConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link com . braintreepayments . api . models . CardNonce } . <p / > On completion returns the { @link com . braintreepayments . api . models . PaymentMethodNonce } to { @link com . braintreepayments . api . interfaces . PaymentMethodNonceCreatedListener } . <p / > If creation fails validation { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the resulting { @link com . braintreepayments . api . exceptions . ErrorWithResponse } . <p / > If an error not due to validation ( server error network issue etc . ) occurs { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the { @link Exception } that occurred . [CODESPLIT] public static void tokenize ( final BraintreeFragment fragment , final CardBuilder cardBuilder ) { TokenizationClient . tokenize ( fragment , cardBuilder , new PaymentMethodNonceCallback ( ) { @ Override public void success ( PaymentMethodNonce paymentMethodNonce ) { DataCollector . collectRiskData ( fragment , paymentMethodNonce ) ; fragment . postCallback ( paymentMethodNonce ) ; fragment . sendAnalyticsEvent ( \"card.nonce-received\" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( \"card.nonce-failed\" ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value mapped by name if it exists coercing it if necessary or fallback if no such mapping exists . [CODESPLIT] public static String optString ( JSONObject json , String name , String fallback ) { if ( json . isNull ( name ) ) { return fallback ; } else { return json . optString ( name , fallback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a response from the Braintree gateway for a list of payment method nonces . [CODESPLIT] public static List < PaymentMethodNonce > parsePaymentMethodNonces ( String jsonBody ) throws JSONException { JSONArray paymentMethods = new JSONObject ( jsonBody ) . getJSONArray ( PAYMENT_METHOD_NONCE_COLLECTION_KEY ) ; if ( paymentMethods == null ) { return Collections . emptyList ( ) ; } List < PaymentMethodNonce > paymentMethodsNonces = new ArrayList <> ( ) ; JSONObject json ; PaymentMethodNonce paymentMethodNonce ; for ( int i = 0 ; i < paymentMethods . length ( ) ; i ++ ) { json = paymentMethods . getJSONObject ( i ) ; paymentMethodNonce = parsePaymentMethodNonces ( json , json . getString ( PAYMENT_METHOD_TYPE_KEY ) ) ; if ( paymentMethodNonce != null ) { paymentMethodsNonces . add ( paymentMethodNonce ) ; } } return paymentMethodsNonces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a { @link PaymentMethodNonce } from json . [CODESPLIT] @ Nullable public static PaymentMethodNonce parsePaymentMethodNonces ( String json , String type ) throws JSONException { return parsePaymentMethodNonces ( new JSONObject ( json ) , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a { @link PaymentMethodNonce } from json . [CODESPLIT] @ Nullable public static PaymentMethodNonce parsePaymentMethodNonces ( JSONObject json , String type ) throws JSONException { switch ( type ) { case CardNonce . TYPE : if ( json . has ( CardNonce . API_RESOURCE_KEY ) || json . has ( CardNonce . DATA_KEY ) ) { return CardNonce . fromJson ( json . toString ( ) ) ; } else { CardNonce cardNonce = new CardNonce ( ) ; cardNonce . fromJson ( json ) ; return cardNonce ; } case PayPalAccountNonce . TYPE : if ( json . has ( PayPalAccountNonce . API_RESOURCE_KEY ) ) { return PayPalAccountNonce . fromJson ( json . toString ( ) ) ; } else { PayPalAccountNonce payPalAccountNonce = new PayPalAccountNonce ( ) ; payPalAccountNonce . fromJson ( json ) ; return payPalAccountNonce ; } case VenmoAccountNonce . TYPE : if ( json . has ( VenmoAccountNonce . API_RESOURCE_KEY ) ) { return VenmoAccountNonce . fromJson ( json . toString ( ) ) ; } else { VenmoAccountNonce venmoAccountNonce = new VenmoAccountNonce ( ) ; venmoAccountNonce . fromJson ( json ) ; return venmoAccountNonce ; } case VisaCheckoutNonce . TYPE : if ( json . has ( VisaCheckoutNonce . API_RESOURCE_KEY ) ) { return VisaCheckoutNonce . fromJson ( json . toString ( ) ) ; } else { VisaCheckoutNonce visaCheckoutNonce = new VisaCheckoutNonce ( ) ; visaCheckoutNonce . fromJson ( json ) ; return visaCheckoutNonce ; } default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "1 . Look for exact match of environment . ( Could be mock live or a particular host : port . ) 2 . If environment is anything other than mock or live then look for develop . 3 . Look for live . ( There should always be a live endpoint specified in any v3 browser - switch recipe . ) [CODESPLIT] public ConfigEndpoint getEndpoint ( String environment ) { ConfigEndpoint configEndpoint ; if ( mEndpoints . containsKey ( environment ) ) { configEndpoint = mEndpoints . get ( environment ) ; } else if ( mEndpoints . containsKey ( DEVELOP ) ) { configEndpoint = mEndpoints . get ( DEVELOP ) ; } else { // default to live as fallback configEndpoint = mEndpoints . get ( EnvironmentManager . LIVE ) ; } return configEndpoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines the host to be used in the cancellation url for browser switch ( the package name will be used as the scheme ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public T cancelUrl ( String scheme , String host ) { mCancelUrl = scheme + \"://\" + redirectURLHostAndPath ( ) + host ; return ( T ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines the host to be used in the success url for browser switch ( the package name will be used as the scheme ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public T successUrl ( String scheme , String host ) { mSuccessUrl = scheme + \"://\" + redirectURLHostAndPath ( ) + host ; return ( T ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the browser recipe that can handle checkout or null if there is none . [CODESPLIT] public CheckoutRecipe getBrowserCheckoutConfig ( ) { for ( CheckoutRecipe recipe : mCheckoutRecipesInDecreasingPriorityOrder ) { if ( recipe . getTarget ( ) == RequestTarget . browser ) { return recipe ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the browser recipe that can handle billing agreement or null if there is none . [CODESPLIT] public BillingAgreementRecipe getBrowserBillingAgreementConfig ( ) { for ( BillingAgreementRecipe recipe : mBillingAgreementRecipesInDecreasingPriorityOrder ) { if ( recipe . getTarget ( ) == RequestTarget . browser ) { return recipe ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an API response to a { @link CardNonce } . [CODESPLIT] public static CardNonce fromJson ( String json ) throws JSONException { CardNonce cardNonce = new CardNonce ( ) ; JSONObject jsonObject = new JSONObject ( json ) ; if ( jsonObject . has ( DATA_KEY ) ) { cardNonce . fromGraphQLJson ( jsonObject ) ; } else { cardNonce . fromJson ( CardNonce . getJsonObjectForType ( API_RESOURCE_KEY , jsonObject ) ) ; } return cardNonce ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate properties with values from a { @link JSONObject } . [CODESPLIT] protected void fromJson ( JSONObject json ) throws JSONException { super . fromJson ( json ) ; JSONObject details = json . getJSONObject ( CARD_DETAILS_KEY ) ; mLastTwo = details . getString ( LAST_TWO_KEY ) ; mLastFour = details . getString ( LAST_FOUR_KEY ) ; mCardType = details . getString ( CARD_TYPE_KEY ) ; mThreeDSecureInfo = ThreeDSecureInfo . fromJson ( json . optJSONObject ( THREE_D_SECURE_INFO_KEY ) ) ; mBinData = BinData . fromJson ( json . optJSONObject ( BIN_DATA_KEY ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an { @link AnalyticsConfiguration } from json . [CODESPLIT] public static AnalyticsConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } AnalyticsConfiguration analyticsConfiguration = new AnalyticsConfiguration ( ) ; analyticsConfiguration . mUrl = Json . optString ( json , URL_KEY , null ) ; return analyticsConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link PaymentMethodNonce } in the Braintree Gateway . <p / > On completion returns the { @link PaymentMethodNonce } to { @link PaymentMethodNonceCallback } . <p / > If creation fails validation { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the resulting { @link ErrorWithResponse } . <p / > If an error not due to validation ( server error network issue etc . ) occurs { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } ( Throwable ) } will be called with the { @link Exception } that occurred . [CODESPLIT] static void tokenize ( final BraintreeFragment fragment , final PaymentMethodBuilder paymentMethodBuilder , final PaymentMethodNonceCallback callback ) { paymentMethodBuilder . setSessionId ( fragment . getSessionId ( ) ) ; fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( paymentMethodBuilder instanceof CardBuilder && configuration . getGraphQL ( ) . isFeatureEnabled ( Features . TOKENIZE_CREDIT_CARDS ) ) { tokenizeGraphQL ( fragment , ( CardBuilder ) paymentMethodBuilder , callback ) ; } else { tokenizeRest ( fragment , paymentMethodBuilder , callback ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a HTTP GET request to using the base url and path provided . If the path is a full url it will be used instead of the previously provided base url . [CODESPLIT] public void get ( final String path , final HttpResponseCallback callback ) { if ( path == null ) { postCallbackOnMainThread ( callback , new IllegalArgumentException ( \"Path cannot be null\" ) ) ; return ; } final String url ; if ( path . startsWith ( \"http\" ) ) { url = path ; } else { url = mBaseUrl + path ; } mThreadPool . submit ( new Runnable ( ) { @ Override public void run ( ) { HttpURLConnection connection = null ; try { connection = init ( url ) ; connection . setRequestMethod ( METHOD_GET ) ; postCallbackOnMainThread ( callback , parseResponse ( connection ) ) ; } catch ( Exception e ) { postCallbackOnMainThread ( callback , e ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a HTTP POST request using the base url and path provided . If the path is a full url it will be used instead of the previously provided url . [CODESPLIT] public void post ( final String path , final String data , final HttpResponseCallback callback ) { if ( path == null ) { postCallbackOnMainThread ( callback , new IllegalArgumentException ( \"Path cannot be null\" ) ) ; return ; } mThreadPool . submit ( new Runnable ( ) { @ Override public void run ( ) { try { postCallbackOnMainThread ( callback , post ( path , data ) ) ; } catch ( Exception e ) { postCallbackOnMainThread ( callback , e ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a synchronous post request . [CODESPLIT] public String post ( String path , String data ) throws Exception { HttpURLConnection connection = null ; try { if ( path . startsWith ( \"http\" ) ) { connection = init ( path ) ; } else { connection = init ( mBaseUrl + path ) ; } connection . setRequestProperty ( \"Content-Type\" , \"application/json\" ) ; connection . setRequestMethod ( METHOD_POST ) ; connection . setDoOutput ( true ) ; writeOutputStream ( connection . getOutputStream ( ) , data ) ; return parseResponse ( connection ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an API response to a { @link VisaCheckoutNonce } . [CODESPLIT] public static VisaCheckoutNonce fromJson ( String json ) throws JSONException { VisaCheckoutNonce visaCheckoutNonce = new VisaCheckoutNonce ( ) ; visaCheckoutNonce . fromJson ( PaymentMethodNonce . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return visaCheckoutNonce ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the payment flow for a specific type of local payment . [CODESPLIT] public static void startPayment ( final BraintreeFragment fragment , final LocalPaymentRequest request , final BraintreeResponseListener < LocalPaymentRequest > listener ) { if ( request == null ) { fragment . postCallback ( new BraintreeException ( \"A LocalPaymentRequest is required.\" ) ) ; return ; } else if ( request . getApprovalUrl ( ) != null || request . getPaymentId ( ) != null ) { fragment . postCallback ( new BraintreeException ( \"LocalPaymentRequest is invalid, \" + \"appovalUrl and paymentId should not be set.\" ) ) ; return ; } else if ( request . getPaymentType ( ) == null || request . getAmount ( ) == null ) { fragment . postCallback ( new BraintreeException ( \"LocalPaymentRequest is invalid, \" + \"paymentType and amount are required.\" ) ) ; return ; } else if ( listener == null ) { fragment . postCallback ( new BraintreeException ( \"BraintreeResponseListener<LocalPaymentRequest> \" + \"is required.\" ) ) ; return ; } fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( ! configuration . getPayPal ( ) . isEnabled ( ) ) { fragment . postCallback ( new ConfigurationException ( \"Local payments are not enabled for this merchant.\" ) ) ; return ; } sMerchantAccountId = request . getMerchantAccountId ( ) ; sPaymentType = request . getPaymentType ( ) ; String returnUrl = fragment . getReturnUrlScheme ( ) + \"://\" + LOCAL_PAYMENT_SUCCESSS ; String cancel = fragment . getReturnUrlScheme ( ) + \"://\" + LOCAL_PAYMENT_CANCEL ; fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + \".local-payment.start-payment.selected\" ) ; fragment . getHttpClient ( ) . post ( \"/v1/paypal_hermes/create_payment_resource\" , request . build ( returnUrl , cancel ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { JSONObject responseJson = new JSONObject ( responseBody ) ; request . approvalUrl ( responseJson . getJSONObject ( \"paymentResource\" ) . getString ( \"redirectUrl\" ) ) ; request . paymentId ( responseJson . getJSONObject ( \"paymentResource\" ) . getString ( \"paymentToken\" ) ) ; fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + \".local-payment.create.succeeded\" ) ; listener . onResponse ( request ) ; } catch ( JSONException jsonException ) { failure ( jsonException ) ; } } @ Override public void failure ( Exception exception ) { fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + \".local-payment.webswitch.initiate.failed\" ) ; fragment . postCallback ( exception ) ; } } ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiates the browser switch for a payment flow by opening a browser where the customer can authenticate with their bank . [CODESPLIT] public static void approvePayment ( BraintreeFragment fragment , LocalPaymentRequest request ) { fragment . browserSwitch ( BraintreeRequestCodes . LOCAL_PAYMENT , request . getApprovalUrl ( ) ) ; fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + \".local-payment.webswitch.initiate.succeeded\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @link Authorization } of the correct type for a given { @link String } . [CODESPLIT] public static Authorization fromString ( @ Nullable String authorizationString ) throws InvalidArgumentException { if ( isTokenizationKey ( authorizationString ) ) { return new TokenizationKey ( authorizationString ) ; } else { return new ClientToken ( authorizationString ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to extract an error for an individual field e . g . creditCard customer etc . [CODESPLIT] @ Nullable public BraintreeError errorFor ( String field ) { BraintreeError returnError ; if ( mFieldErrors != null ) { for ( BraintreeError error : mFieldErrors ) { if ( error . getField ( ) . equals ( field ) ) { return error ; } else if ( error . getFieldErrors ( ) != null ) { returnError = error . errorFor ( field ) ; if ( returnError != null ) { return returnError ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an API response to a { @link PayPalAccountNonce } . [CODESPLIT] public static PayPalAccountNonce fromJson ( String jsonString ) throws JSONException { JSONObject jsonObj = new JSONObject ( jsonString ) ; PayPalAccountNonce payPalAccountNonce = new PayPalAccountNonce ( ) ; if ( jsonObj . has ( PayPalAccountNonce . API_RESOURCE_KEY ) ) { payPalAccountNonce . fromJson ( PayPalAccountNonce . getJsonObjectForType ( API_RESOURCE_KEY , jsonObj ) ) ; } else if ( jsonObj . has ( PayPalAccountNonce . PAYMENT_METHOD_DATA_KEY ) ) { JSONObject tokenObj = new JSONObject ( new JSONObject ( jsonString ) . getJSONObject ( PayPalAccountNonce . PAYMENT_METHOD_DATA_KEY ) . getJSONObject ( PayPalAccountNonce . TOKENIZATION_DATA_KEY ) . getString ( PayPalAccountNonce . TOKEN_KEY ) ) ; payPalAccountNonce . fromJson ( PayPalAccountNonce . getJsonObjectForType ( API_RESOURCE_KEY , tokenObj ) ) ; JSONObject shippingAddress = jsonObj . optJSONObject ( SHIPPING_ADDRESS_KEY ) ; if ( shippingAddress != null ) { payPalAccountNonce . mShippingAddress = PostalAddressParser . fromJson ( shippingAddress ) ; } } else { throw new JSONException ( \"Could not parse JSON for a payment method nonce\" ) ; } return payPalAccountNonce ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a { @link PayPalAccountNonce } from the { @link JSONObject } . [CODESPLIT] protected void fromJson ( JSONObject json ) throws JSONException { super . fromJson ( json ) ; JSONObject details = json . getJSONObject ( DETAILS_KEY ) ; mEmail = Json . optString ( details , EMAIL_KEY , null ) ; mClientMetadataId = Json . optString ( details , CLIENT_METADATA_ID_KEY , null ) ; try { if ( details . has ( CREDIT_FINANCING_KEY ) ) { JSONObject creditFinancing = details . getJSONObject ( CREDIT_FINANCING_KEY ) ; mCreditFinancing = PayPalCreditFinancing . fromJson ( creditFinancing ) ; } JSONObject payerInfo = details . getJSONObject ( PAYER_INFO_KEY ) ; JSONObject billingAddress = payerInfo . optJSONObject ( BILLING_ADDRESS_KEY ) ; if ( payerInfo . has ( ACCOUNT_ADDRESS_KEY ) ) { billingAddress = payerInfo . optJSONObject ( ACCOUNT_ADDRESS_KEY ) ; } mShippingAddress = PostalAddressParser . fromJson ( payerInfo . optJSONObject ( SHIPPING_ADDRESS_KEY ) ) ; mBillingAddress = PostalAddressParser . fromJson ( billingAddress ) ; mFirstName = Json . optString ( payerInfo , FIRST_NAME_KEY , \"\" ) ; mLastName = Json . optString ( payerInfo , LAST_NAME_KEY , \"\" ) ; mPhone = Json . optString ( payerInfo , PHONE_KEY , \"\" ) ; mPayerId = Json . optString ( payerInfo , PAYER_ID_KEY , \"\" ) ; if ( mEmail == null ) { mEmail = Json . optString ( payerInfo , EMAIL_KEY , null ) ; } } catch ( JSONException e ) { mBillingAddress = new PostalAddress ( ) ; mShippingAddress = new PostalAddress ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance of { @link BraintreeFragment } using the client token and add it to the { @link AppCompatActivity } s { @link FragmentManager } . [CODESPLIT] public static BraintreeFragment newInstance ( AppCompatActivity activity , String authorization ) throws InvalidArgumentException { if ( activity == null ) { throw new InvalidArgumentException ( \"Activity is null\" ) ; } FragmentManager fm = activity . getSupportFragmentManager ( ) ; BraintreeFragment braintreeFragment = ( BraintreeFragment ) fm . findFragmentByTag ( TAG ) ; if ( braintreeFragment == null ) { braintreeFragment = new BraintreeFragment ( ) ; Bundle bundle = new Bundle ( ) ; try { Authorization auth = Authorization . fromString ( authorization ) ; bundle . putParcelable ( EXTRA_AUTHORIZATION_TOKEN , auth ) ; } catch ( InvalidArgumentException e ) { throw new InvalidArgumentException ( \"Tokenization Key or client token was invalid.\" ) ; } bundle . putString ( EXTRA_SESSION_ID , UUIDHelper . getFormattedUUID ( ) ) ; bundle . putString ( EXTRA_INTEGRATION_TYPE , IntegrationType . get ( activity ) ) ; braintreeFragment . setArguments ( bundle ) ; try { if ( VERSION . SDK_INT >= VERSION_CODES . N ) { try { fm . beginTransaction ( ) . add ( braintreeFragment , TAG ) . commitNow ( ) ; } catch ( IllegalStateException | NullPointerException e ) { fm . beginTransaction ( ) . add ( braintreeFragment , TAG ) . commit ( ) ; try { fm . executePendingTransactions ( ) ; } catch ( IllegalStateException ignored ) { } } } else { fm . beginTransaction ( ) . add ( braintreeFragment , TAG ) . commit ( ) ; try { fm . executePendingTransactions ( ) ; } catch ( IllegalStateException ignored ) { } } } catch ( IllegalStateException e ) { throw new InvalidArgumentException ( e . getMessage ( ) ) ; } } braintreeFragment . mContext = activity . getApplicationContext ( ) ; return braintreeFragment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a listener . [CODESPLIT] public < T extends BraintreeListener > void addListener ( T listener ) { if ( listener instanceof ConfigurationListener ) { mConfigurationListener = ( ConfigurationListener ) listener ; } if ( listener instanceof BraintreeCancelListener ) { mCancelListener = ( BraintreeCancelListener ) listener ; } if ( listener instanceof PaymentMethodNoncesUpdatedListener ) { mPaymentMethodNoncesUpdatedListener = ( PaymentMethodNoncesUpdatedListener ) listener ; } if ( listener instanceof PaymentMethodNonceCreatedListener ) { mPaymentMethodNonceCreatedListener = ( PaymentMethodNonceCreatedListener ) listener ; } if ( listener instanceof PaymentMethodNonceDeletedListener ) { mPaymentMethodNonceDeletedListener = ( PaymentMethodNonceDeletedListener ) listener ; } if ( listener instanceof BraintreePaymentResultListener ) { mBraintreePaymentResultListener = ( BraintreePaymentResultListener ) listener ; } if ( listener instanceof BraintreeErrorListener ) { mErrorListener = ( BraintreeErrorListener ) listener ; } if ( listener instanceof UnionPayListener ) { mUnionPayListener = ( UnionPayListener ) listener ; } if ( listener instanceof AmericanExpressListener ) { mAmericanExpressListener = ( AmericanExpressListener ) listener ; } flushCallbacks ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a previously added listener . [CODESPLIT] public < T extends BraintreeListener > void removeListener ( T listener ) { if ( listener instanceof ConfigurationListener ) { mConfigurationListener = null ; } if ( listener instanceof BraintreeCancelListener ) { mCancelListener = null ; } if ( listener instanceof PaymentMethodNoncesUpdatedListener ) { mPaymentMethodNoncesUpdatedListener = null ; } if ( listener instanceof PaymentMethodNonceCreatedListener ) { mPaymentMethodNonceCreatedListener = null ; } if ( listener instanceof PaymentMethodNonceDeletedListener ) { mPaymentMethodNonceDeletedListener = null ; } if ( listener instanceof BraintreePaymentResultListener ) { mBraintreePaymentResultListener = null ; } if ( listener instanceof BraintreeErrorListener ) { mErrorListener = null ; } if ( listener instanceof UnionPayListener ) { mUnionPayListener = null ; } if ( listener instanceof AmericanExpressListener ) { mAmericanExpressListener = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain an instance of a { @link GoogleApiClient } that is connected or connecting to be used for Android Pay . This instance will be automatically disconnected in { @link BraintreeFragment#onStop () } and automatically connected in { @link BraintreeFragment#onResume () } . <p / > Connection failed and connection suspended errors will be sent to { @link BraintreeErrorListener#onError ( Exception ) } . [CODESPLIT] public void getGoogleApiClient ( final BraintreeResponseListener < GoogleApiClient > listener ) { waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { GoogleApiClient googleApiClient = getGoogleApiClient ( ) ; if ( googleApiClient != null ) { listener . onResponse ( googleApiClient ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an { @link GooglePaymentConfiguration } from json . [CODESPLIT] public static GooglePaymentConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } GooglePaymentConfiguration googlePaymentConfiguration = new GooglePaymentConfiguration ( ) ; googlePaymentConfiguration . mEnabled = json . optBoolean ( ENABLED_KEY , false ) ; googlePaymentConfiguration . mGoogleAuthorizationFingerprint = Json . optString ( json , GOOGLE_AUTHORIZATION_FINGERPRINT_KEY , null ) ; googlePaymentConfiguration . mEnvironment = Json . optString ( json , ENVIRONMENT_KEY , null ) ; googlePaymentConfiguration . mDisplayName = Json . optString ( json , DISPLAY_NAME_KEY , \"\" ) ; JSONArray supportedNetworks = json . optJSONArray ( SUPPORTED_NETWORKS_KEY ) ; if ( supportedNetworks != null ) { googlePaymentConfiguration . mSupportedNetworks = new String [ supportedNetworks . length ( ) ] ; for ( int i = 0 ; i < supportedNetworks . length ( ) ; i ++ ) { try { googlePaymentConfiguration . mSupportedNetworks [ i ] = supportedNetworks . getString ( i ) ; } catch ( JSONException ignored ) { } } } else { googlePaymentConfiguration . mSupportedNetworks = new String [ 0 ] ; } return googlePaymentConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the Billing Agreement flow for PayPal with custom PayPal approval handler . [CODESPLIT] public static void requestBillingAgreement ( BraintreeFragment fragment , PayPalRequest request , PayPalApprovalHandler handler ) { if ( request . getAmount ( ) == null ) { fragment . sendAnalyticsEvent ( \"paypal.billing-agreement.selected\" ) ; if ( request . shouldOfferCredit ( ) ) { fragment . sendAnalyticsEvent ( \"paypal.billing-agreement.credit.offered\" ) ; } requestOneTimePayment ( fragment , request , true , handler ) ; } else { fragment . postCallback ( new BraintreeException ( \"There must be no amount specified for the Billing Agreement flow\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a PayPalPaymentResource on behalf of the merchant . To be used in the PayPal Checkout flows for Single Payment and Billing Agreement . [CODESPLIT] private static void createPaymentResource ( BraintreeFragment fragment , PayPalRequest request , boolean isBillingAgreement , HttpResponseCallback callback ) throws JSONException , ErrorWithResponse , BraintreeException { String currencyCode = request . getCurrencyCode ( ) ; if ( currencyCode == null ) { currencyCode = fragment . getConfiguration ( ) . getPayPal ( ) . getCurrencyIsoCode ( ) ; } CheckoutRequest checkoutRequest = getCheckoutRequest ( fragment , null ) ; JSONObject parameters = new JSONObject ( ) . put ( RETURN_URL_KEY , checkoutRequest . getSuccessUrl ( ) ) . put ( CANCEL_URL_KEY , checkoutRequest . getCancelUrl ( ) ) . put ( OFFER_CREDIT_KEY , request . shouldOfferCredit ( ) ) ; if ( fragment . getAuthorization ( ) instanceof ClientToken ) { parameters . put ( AUTHORIZATION_FINGERPRINT_KEY , fragment . getAuthorization ( ) . getBearer ( ) ) ; } else { parameters . put ( TOKENIZATION_KEY , fragment . getAuthorization ( ) . getBearer ( ) ) ; } if ( ! isBillingAgreement ) { parameters . put ( AMOUNT_KEY , request . getAmount ( ) ) . put ( CURRENCY_ISO_CODE_KEY , currencyCode ) . put ( INTENT_KEY , request . getIntent ( ) ) ; } else { if ( ! TextUtils . isEmpty ( request . getBillingAgreementDescription ( ) ) ) { parameters . put ( DESCRIPTION_KEY , request . getBillingAgreementDescription ( ) ) ; } } JSONObject experienceProfile = new JSONObject ( ) ; experienceProfile . put ( NO_SHIPPING_KEY , ! request . isShippingAddressRequired ( ) ) ; experienceProfile . put ( LANDING_PAGE_TYPE_KEY , request . getLandingPageType ( ) ) ; String displayName = request . getDisplayName ( ) ; if ( TextUtils . isEmpty ( displayName ) ) { displayName = fragment . getConfiguration ( ) . getPayPal ( ) . getDisplayName ( ) ; } experienceProfile . put ( DISPLAY_NAME_KEY , displayName ) ; if ( request . getLocaleCode ( ) != null ) { experienceProfile . put ( LOCALE_CODE_KEY , request . getLocaleCode ( ) ) ; } if ( request . getShippingAddressOverride ( ) != null ) { experienceProfile . put ( ADDRESS_OVERRIDE_KEY , ! request . isShippingAddressEditable ( ) ) ; JSONObject shippingAddressJson ; if ( isBillingAgreement ) { shippingAddressJson = new JSONObject ( ) ; parameters . put ( SHIPPING_ADDRESS_KEY , shippingAddressJson ) ; } else { shippingAddressJson = parameters ; } PostalAddress shippingAddress = request . getShippingAddressOverride ( ) ; shippingAddressJson . put ( PostalAddressParser . LINE_1_KEY , shippingAddress . getStreetAddress ( ) ) ; shippingAddressJson . put ( PostalAddressParser . LINE_2_KEY , shippingAddress . getExtendedAddress ( ) ) ; shippingAddressJson . put ( PostalAddressParser . LOCALITY_KEY , shippingAddress . getLocality ( ) ) ; shippingAddressJson . put ( PostalAddressParser . REGION_KEY , shippingAddress . getRegion ( ) ) ; shippingAddressJson . put ( PostalAddressParser . POSTAL_CODE_UNDERSCORE_KEY , shippingAddress . getPostalCode ( ) ) ; shippingAddressJson . put ( PostalAddressParser . COUNTRY_CODE_UNDERSCORE_KEY , shippingAddress . getCountryCodeAlpha2 ( ) ) ; shippingAddressJson . put ( PostalAddressParser . RECIPIENT_NAME_UNDERSCORE_KEY , shippingAddress . getRecipientName ( ) ) ; } else { experienceProfile . put ( ADDRESS_OVERRIDE_KEY , false ) ; } if ( request . getMerchantAccountId ( ) != null ) { parameters . put ( MERCHANT_ACCOUNT_ID , request . getMerchantAccountId ( ) ) ; } parameters . put ( EXPERIENCE_PROFILE_KEY , experienceProfile ) ; String apiUrl = isBillingAgreement ? SETUP_BILLING_AGREEMENT_ENDPOINT : CREATE_SINGLE_PAYMENT_ENDPOINT ; String versionedPath = \"/v1/\" + apiUrl ; fragment . getHttpClient ( ) . post ( versionedPath , parameters . toString ( ) , callback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The result from PayPal s request . [CODESPLIT] protected static void onActivityResult ( final BraintreeFragment fragment , int resultCode , Intent data ) { Request request = getPersistedRequest ( fragment . getApplicationContext ( ) ) ; String paymentType = paymentTypeForRequest ( request ) ; String switchType = switchTypeForIntent ( data ) ; String eventPrefix = paymentType + \".\" + switchType ; if ( resultCode == AppCompatActivity . RESULT_OK && data != null && request != null ) { Result result = PayPalOneTouchCore . parseResponse ( fragment . getApplicationContext ( ) , request , data ) ; switch ( result . getResultType ( ) ) { case Error : fragment . postCallback ( new BrowserSwitchException ( result . getError ( ) . getMessage ( ) ) ) ; fragment . sendAnalyticsEvent ( eventPrefix + \".failed\" ) ; break ; case Cancel : fragment . postCancelCallback ( BraintreeRequestCodes . PAYPAL ) ; fragment . sendAnalyticsEvent ( eventPrefix + \".canceled\" ) ; break ; case Success : onSuccess ( fragment , data , request , result ) ; fragment . sendAnalyticsEvent ( eventPrefix + \".succeeded\" ) ; break ; } } else { fragment . sendAnalyticsEvent ( eventPrefix + \".canceled\" ) ; if ( resultCode != AppCompatActivity . RESULT_CANCELED ) { fragment . postCancelCallback ( BraintreeRequestCodes . PAYPAL ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the PayPal response URL using OneTouchCore . [CODESPLIT] private static PayPalAccountBuilder parseResponse ( PayPalRequest paypalRequest , Request request , Result result , Intent intent ) { PayPalAccountBuilder paypalAccountBuilder = new PayPalAccountBuilder ( ) . clientMetadataId ( request . getClientMetadataId ( ) ) ; if ( paypalRequest != null && paypalRequest . getMerchantAccountId ( ) != null ) { paypalAccountBuilder . merchantAccountId ( paypalRequest . getMerchantAccountId ( ) ) ; } if ( request instanceof CheckoutRequest && paypalRequest != null ) { paypalAccountBuilder . intent ( paypalRequest . getIntent ( ) ) ; } if ( isAppSwitch ( intent ) ) { paypalAccountBuilder . source ( \"paypal-app\" ) ; } else { paypalAccountBuilder . source ( \"paypal-browser\" ) ; } paypalAccountBuilder . oneTouchCoreData ( result . getResponse ( ) ) ; return paypalAccountBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to parse a response from the Braintree Gateway to be used for 3D Secure . [CODESPLIT] public static ThreeDSecureLookup fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; ThreeDSecureLookup lookup = new ThreeDSecureLookup ( ) ; CardNonce cardNonce = new CardNonce ( ) ; cardNonce . fromJson ( json . getJSONObject ( CARD_NONCE_KEY ) ) ; lookup . mCardNonce = cardNonce ; JSONObject lookupJson = json . getJSONObject ( LOOKUP_KEY ) ; if ( lookupJson . isNull ( ACS_URL_KEY ) ) { lookup . mAcsUrl = null ; } else { lookup . mAcsUrl = lookupJson . getString ( ACS_URL_KEY ) ; } lookup . mMd = lookupJson . getString ( MD_KEY ) ; lookup . mTermUrl = lookupJson . getString ( TERM_URL_KEY ) ; lookup . mPareq = lookupJson . getString ( PA_REQ_KEY ) ; return lookup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an { @link PayPalConfiguration } from json . [CODESPLIT] public static PayPalConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } PayPalConfiguration payPalConfiguration = new PayPalConfiguration ( ) ; payPalConfiguration . mDisplayName = Json . optString ( json , DISPLAY_NAME_KEY , null ) ; payPalConfiguration . mClientId = Json . optString ( json , CLIENT_ID_KEY , null ) ; payPalConfiguration . mPrivacyUrl = Json . optString ( json , PRIVACY_URL_KEY , null ) ; payPalConfiguration . mUserAgreementUrl = Json . optString ( json , USER_AGREEMENT_URL_KEY , null ) ; payPalConfiguration . mDirectBaseUrl = Json . optString ( json , DIRECT_BASE_URL_KEY , null ) ; payPalConfiguration . mEnvironment = Json . optString ( json , ENVIRONMENT_KEY , null ) ; payPalConfiguration . mTouchDisabled = json . optBoolean ( TOUCH_DISABLED_KEY , true ) ; payPalConfiguration . mCurrencyIsoCode = Json . optString ( json , CURRENCY_ISO_CODE_KEY , null ) ; return payPalConfiguration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add user - defined words to the noun dictionary . Spaced words are ignored . [CODESPLIT] public static void addNounsToDictionary ( List < String > words ) { OpenKoreanTextProcessor . addNounsToDictionary ( JavaConverters . asScalaBufferConverter ( words ) . asScala ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove user - defined word List from the dictionary for the specified KoreanPos . [CODESPLIT] public static void removeWordFromDictionary ( KoreanPosJava pos , List < String > words ) { OpenKoreanTextProcessor . removeWordsFromDictionary ( KoreanPos . withName ( pos . toString ( ) ) , JavaConverters . asScalaBufferConverter ( words ) . asScala ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the tokenization output to List<KoreanTokenJava > [CODESPLIT] public static List < KoreanTokenJava > tokensToJavaKoreanTokenList ( Seq < KoreanToken > tokens , boolean keepSpace ) { Iterator < KoreanToken > tokenized = tokens . iterator ( ) ; List < KoreanTokenJava > output = new LinkedList <> ( ) ; while ( tokenized . hasNext ( ) ) { KoreanToken token = tokenized . next ( ) ; String stem = \"\" ; if ( token . stem ( ) . nonEmpty ( ) ) { stem += token . stem ( ) . get ( ) ; } if ( keepSpace || token . pos ( ) != KoreanPos . Space ( ) ) { output . add ( new KoreanTokenJava ( token . text ( ) , KoreanPosJava . valueOf ( token . pos ( ) . toString ( ) ) , token . offset ( ) , token . length ( ) , token . unknown ( ) , stem ) ) ; } } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tokenize with the builder options into a String Iterable . [CODESPLIT] public static List < String > tokensToJavaStringList ( Seq < KoreanToken > tokens , boolean keepSpace ) { Iterator < KoreanToken > tokenized = tokens . iterator ( ) ; List < String > output = new LinkedList <> ( ) ; while ( tokenized . hasNext ( ) ) { final KoreanToken token = tokenized . next ( ) ; if ( keepSpace || token . pos ( ) != KoreanPos . Space ( ) ) { output . add ( token . text ( ) ) ; } } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract phrases from Korean input text [CODESPLIT] public static List < KoreanPhraseExtractor . KoreanPhrase > extractPhrases ( Seq < KoreanToken > tokens , boolean filterSpam , boolean includeHashtags ) { Seq < KoreanPhraseExtractor . KoreanPhrase > seq = OpenKoreanTextProcessor . extractPhrases ( tokens , filterSpam , includeHashtags ) ; return toJavaList ( seq ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detokenize the input list of words . [CODESPLIT] public static String detokenize ( List < String > tokens ) { return OpenKoreanTextProcessor . detokenize ( JavaConverters . asScalaBufferConverter ( tokens ) . asScala ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an unmodifiable { @link CharArraySet } . This allows to provide unmodifiable views of internal sets for read - only use . [CODESPLIT] public static CharArraySet unmodifiableSet ( CharArraySet set ) { if ( set == null ) throw new NullPointerException ( \"Given set is null\" ) ; if ( set == EMPTY_SET ) return EMPTY_SET ; if ( set . map instanceof CharArrayMap . UnmodifiableCharArrayMap ) return set ; return new CharArraySet ( CharArrayMap . unmodifiableMap ( set . map ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads size amount of bytes from ch into a new ByteBuffer allocated from a buffer buf [CODESPLIT] public static ByteBuffer fetchFrom ( ByteBuffer buf , ReadableByteChannel ch , int size ) throws IOException { ByteBuffer result = buf . duplicate ( ) ; result . limit ( size ) ; NIOUtils . readFromChannel ( ch , result ) ; result . flip ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [ 0 .. 1 ] [CODESPLIT] public static float calc_Q_div ( SBR sbr , int ch , int m , int l ) { if ( sbr . bs_coupling ) { /* left channel */ if ( ( sbr . Q [ 0 ] [ m ] [ l ] < 0 || sbr . Q [ 0 ] [ m ] [ l ] > 30 ) || ( sbr . Q [ 1 ] [ m ] [ l ] < 0 || sbr . Q [ 1 ] [ m ] [ l ] > 24 /* 2*panOffset(1) */ ) ) { return 0 ; } else { /* the pan parameter is always even */ if ( ch == 0 ) { return Q_div_tab_left [ sbr . Q [ 0 ] [ m ] [ l ] ] [ sbr . Q [ 1 ] [ m ] [ l ] >> 1 ] ; } else { return Q_div_tab_right [ sbr . Q [ 0 ] [ m ] [ l ] ] [ sbr . Q [ 1 ] [ m ] [ l ] >> 1 ] ; } } } else { /* no coupling */ if ( sbr . Q [ ch ] [ m ] [ l ] < 0 || sbr . Q [ ch ] [ m ] [ l ] > 30 ) { return 0 ; } else { return Q_div_tab [ sbr . Q [ ch ] [ m ] [ l ] ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [ 0 .. 1 ] [CODESPLIT] public static float calc_Q_div2 ( SBR sbr , int ch , int m , int l ) { if ( sbr . bs_coupling ) { if ( ( sbr . Q [ 0 ] [ m ] [ l ] < 0 || sbr . Q [ 0 ] [ m ] [ l ] > 30 ) || ( sbr . Q [ 1 ] [ m ] [ l ] < 0 || sbr . Q [ 1 ] [ m ] [ l ] > 24 /* 2*panOffset(1) */ ) ) { return 0 ; } else { /* the pan parameter is always even */ if ( ch == 0 ) { return Q_div2_tab_left [ sbr . Q [ 0 ] [ m ] [ l ] ] [ sbr . Q [ 1 ] [ m ] [ l ] >> 1 ] ; } else { return Q_div2_tab_right [ sbr . Q [ 0 ] [ m ] [ l ] ] [ sbr . Q [ 1 ] [ m ] [ l ] >> 1 ] ; } } } else { /* no coupling */ if ( sbr . Q [ ch ] [ m ] [ l ] < 0 || sbr . Q [ ch ] [ m ] [ l ] > 30 ) { return 0 ; } else { return Q_div2_tab [ sbr . Q [ ch ] [ m ] [ l ] ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds next Nth H . 264 bitstream NAL unit ( 0x00000001 ) and returns the data that preceeds it as a ByteBuffer slice [CODESPLIT] public static final ByteBuffer gotoNALUnit ( ByteBuffer buf ) { if ( ! buf . hasRemaining ( ) ) return null ; int from = buf . position ( ) ; ByteBuffer result = buf . slice ( ) ; result . order ( ByteOrder . BIG_ENDIAN ) ; int val = 0xffffffff ; while ( buf . hasRemaining ( ) ) { val <<= 8 ; val |= ( buf . get ( ) & 0xff ) ; if ( ( val & 0xffffff ) == 1 ) { buf . position ( buf . position ( ) - ( val == 1 ? 4 : 3 ) ) ; result . limit ( buf . position ( ) - from ) ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds next Nth H . 264 bitstream NAL unit ( 0x00000001 ) and returns the data that preceeds it as a ByteBuffer slice [CODESPLIT] public static final ByteBuffer gotoNALUnitWithArray ( ByteBuffer buf ) { if ( ! buf . hasRemaining ( ) ) return null ; int from = buf . position ( ) ; ByteBuffer result = buf . slice ( ) ; result . order ( ByteOrder . BIG_ENDIAN ) ; byte [ ] arr = buf . array ( ) ; int pos = from + buf . arrayOffset ( ) ; int posFrom = pos ; int lim = buf . limit ( ) + buf . arrayOffset ( ) ; while ( pos < lim ) { byte b = arr [ pos ] ; if ( ( b & 254 ) == 0 ) { while ( b == 0 && ++ pos < lim ) b = arr [ pos ] ; if ( b == 1 ) { if ( pos - posFrom >= 2 && arr [ pos - 1 ] == 0 && arr [ pos - 2 ] == 0 ) { int lenSize = ( pos - posFrom >= 3 && arr [ pos - 3 ] == 0 ) ? 4 : 3 ; buf . position ( pos + 1 - buf . arrayOffset ( ) - lenSize ) ; result . limit ( buf . position ( ) - from ) ; return result ; } } } pos += 3 ; } buf . position ( buf . limit ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes AVC frame in ISO BMF format . Takes Annex B format . [CODESPLIT] public static void encodeMOVPacketInplace ( ByteBuffer avcFrame ) { ByteBuffer dup = avcFrame . duplicate ( ) ; ByteBuffer d1 = avcFrame . duplicate ( ) ; for ( int tot = d1 . position ( ) ; ; ) { ByteBuffer buf = H264Utils . nextNALUnit ( dup ) ; if ( buf == null ) break ; d1 . position ( tot ) ; d1 . putInt ( buf . remaining ( ) ) ; tot += buf . remaining ( ) + 4 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes AVC frame in ISO BMF format . Takes Annex B format . [CODESPLIT] public static ByteBuffer encodeMOVPacket ( ByteBuffer avcFrame ) { ByteBuffer dup = avcFrame . duplicate ( ) ; List < ByteBuffer > list = new ArrayList < ByteBuffer > ( ) ; ByteBuffer buf ; int totalLen = 0 ; while ( ( buf = H264Utils . nextNALUnit ( dup ) ) != null ) { list . add ( buf ) ; totalLen += buf . remaining ( ) ; } ByteBuffer result = ByteBuffer . allocate ( list . size ( ) * 4 + totalLen ) ; for ( ByteBuffer byteBuffer : list ) { result . putInt ( byteBuffer . remaining ( ) ) ; result . put ( byteBuffer ) ; } result . flip ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes AVC packet in ISO BMF format into Annex B format . [CODESPLIT] public static ByteBuffer decodeMOVPacket ( ByteBuffer result , AvcCBox avcC ) { if ( avcC . getNalLengthSize ( ) == 4 ) { decodeMOVPacketInplace ( result , avcC ) ; return result ; } return joinNALUnits ( splitMOVPacket ( result , avcC ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes AVC packet in ISO BMF format into Annex B format . [CODESPLIT] public static void decodeMOVPacketInplace ( ByteBuffer result , AvcCBox avcC ) { if ( avcC . getNalLengthSize ( ) != 4 ) throw new IllegalArgumentException ( \"Can only inplace decode AVC MOV packet with nal_length_size = 4.\" ) ; ByteBuffer dup = result . duplicate ( ) ; while ( dup . remaining ( ) >= 4 ) { int size = dup . getInt ( ) ; dup . position ( dup . position ( ) - 4 ) ; dup . putInt ( 1 ) ; dup . position ( dup . position ( ) + size ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wipes AVC parameter sets ( SPS / PPS ) from the packet [CODESPLIT] public static void wipePS ( ByteBuffer _in , ByteBuffer out , List < ByteBuffer > spsList , List < ByteBuffer > ppsList ) { ByteBuffer dup = _in . duplicate ( ) ; while ( dup . hasRemaining ( ) ) { ByteBuffer buf = H264Utils . nextNALUnit ( dup ) ; if ( buf == null ) break ; NALUnit nu = NALUnit . read ( buf . duplicate ( ) ) ; if ( nu . type == NALUnitType . PPS ) { if ( ppsList != null ) ppsList . add ( NIOUtils . duplicate ( buf ) ) ; } else if ( nu . type == NALUnitType . SPS ) { if ( spsList != null ) spsList . add ( NIOUtils . duplicate ( buf ) ) ; } else if ( out != null ) { out . putInt ( 1 ) ; out . put ( buf ) ; } } if ( out != null ) out . flip ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wipes AVC parameter sets ( SPS / PPS ) from the packet ( inplace operation ) [CODESPLIT] public static void wipePSinplace ( ByteBuffer _in , Collection < ByteBuffer > spsList , Collection < ByteBuffer > ppsList ) { ByteBuffer dup = _in . duplicate ( ) ; while ( dup . hasRemaining ( ) ) { ByteBuffer buf = H264Utils . nextNALUnit ( dup ) ; if ( buf == null ) break ; NALUnit nu = NALUnit . read ( buf ) ; if ( nu . type == NALUnitType . PPS ) { if ( ppsList != null ) ppsList . add ( NIOUtils . duplicate ( buf ) ) ; _in . position ( dup . position ( ) ) ; } else if ( nu . type == NALUnitType . SPS ) { if ( spsList != null ) spsList . add ( NIOUtils . duplicate ( buf ) ) ; _in . position ( dup . position ( ) ) ; } else if ( nu . type == NALUnitType . IDR_SLICE || nu . type == NALUnitType . NON_IDR_SLICE ) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a MP4 sample entry given AVC / H . 264 codec private . [CODESPLIT] public static SampleEntry createMOVSampleEntryFromBytes ( ByteBuffer codecPrivate ) { List < ByteBuffer > rawSPS = getRawSPS ( codecPrivate . duplicate ( ) ) ; List < ByteBuffer > rawPPS = getRawPPS ( codecPrivate . duplicate ( ) ) ; return createMOVSampleEntryFromSpsPpsList ( rawSPS , rawPPS , 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a MP4 sample entry given AVC / H . 264 codec private . [CODESPLIT] public static AvcCBox createAvcCFromBytes ( ByteBuffer codecPrivate ) { List < ByteBuffer > rawSPS = getRawSPS ( codecPrivate . duplicate ( ) ) ; List < ByteBuffer > rawPPS = getRawPPS ( codecPrivate . duplicate ( ) ) ; return createAvcCFromPS ( rawSPS , rawPPS , 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins buffers containing individual NAL units into a single AnnexB delimited buffer . Each NAL unit will be separated with 00 00 00 01 markers . Allocates a new byte buffer and writes data into it . [CODESPLIT] public static ByteBuffer joinNALUnits ( List < ByteBuffer > nalUnits ) { int size = 0 ; for ( ByteBuffer nal : nalUnits ) { size += 4 + nal . remaining ( ) ; } ByteBuffer allocate = ByteBuffer . allocate ( size ) ; joinNALUnitsToBuffer ( nalUnits , allocate ) ; return allocate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins buffers containing individual NAL units into a single AnnexB delimited buffer . Each NAL unit will be separated with 00 00 00 01 markers . [CODESPLIT] public static void joinNALUnitsToBuffer ( List < ByteBuffer > nalUnits , ByteBuffer out ) { for ( ByteBuffer nal : nalUnits ) { out . putInt ( 1 ) ; out . put ( nal . duplicate ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get block of ( possibly interpolated ) luma pixels [CODESPLIT] public void getBlockLuma ( Picture pic , Picture out , int off , int x , int y , int w , int h ) { int xInd = x & 0x3 ; int yInd = y & 0x3 ; int xFp = x >> 2 ; int yFp = y >> 2 ; if ( xFp < 2 || yFp < 2 || xFp > pic . getWidth ( ) - w - 5 || yFp > pic . getHeight ( ) - h - 5 ) { unsafe [ ( yInd << 2 ) + xInd ] . getLuma ( pic . getData ( ) [ 0 ] , pic . getWidth ( ) , pic . getHeight ( ) , out . getPlaneData ( 0 ) , off , out . getPlaneWidth ( 0 ) , xFp , yFp , w , h ) ; } else { safe [ ( yInd << 2 ) + xInd ] . getLuma ( pic . getData ( ) [ 0 ] , pic . getWidth ( ) , pic . getHeight ( ) , out . getPlaneData ( 0 ) , off , out . getPlaneWidth ( 0 ) , xFp , yFp , w , h ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fullpel ( 0 0 ) unsafe [CODESPLIT] static void getLuma00Unsafe ( byte [ ] pic , int picW , int picH , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { int maxH = picH - 1 ; int maxW = picW - 1 ; for ( int j = 0 ; j < blkH ; j ++ ) { int lineStart = clip ( j + y , 0 , maxH ) * picW ; for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = pic [ lineStart + clip ( x + i , 0 , maxW ) ] ; } blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Halfpel ( 2 0 ) horizontal int argument version [CODESPLIT] static void getLuma20NoRoundInt ( int [ ] pic , int picW , int [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { int off = y * picW + x ; for ( int j = 0 ; j < blkH ; j ++ ) { int off1 = - 2 ; for ( int i = 0 ; i < blkW ; i ++ ) { int a = pic [ off + off1 ] + pic [ off + off1 + 5 ] ; int b = pic [ off + off1 + 1 ] + pic [ off + off1 + 4 ] ; int c = pic [ off + off1 + 2 ] + pic [ off + off1 + 3 ] ; blk [ blkOff + i ] = a + 5 * ( ( c << 2 ) - b ) ; ++ off1 ; } off += picW ; blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Halfpel ( 2 0 ) horizontal unsafe [CODESPLIT] static void getLuma20UnsafeNoRound ( byte [ ] pic , int picW , int picH , int [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { int maxW = picW - 1 ; int maxH = picH - 1 ; for ( int i = 0 ; i < blkW ; i ++ ) { int ipos_m2 = clip ( x + i - 2 , 0 , maxW ) ; int ipos_m1 = clip ( x + i - 1 , 0 , maxW ) ; int ipos = clip ( x + i , 0 , maxW ) ; int ipos_p1 = clip ( x + i + 1 , 0 , maxW ) ; int ipos_p2 = clip ( x + i + 2 , 0 , maxW ) ; int ipos_p3 = clip ( x + i + 3 , 0 , maxW ) ; int boff = blkOff ; for ( int j = 0 ; j < blkH ; j ++ ) { int lineStart = clip ( j + y , 0 , maxH ) * picW ; int a = pic [ lineStart + ipos_m2 ] + pic [ lineStart + ipos_p3 ] ; int b = pic [ lineStart + ipos_m1 ] + pic [ lineStart + ipos_p2 ] ; int c = pic [ lineStart + ipos ] + pic [ lineStart + ipos_p1 ] ; blk [ boff + i ] = a + 5 * ( ( c << 2 ) - b ) ; boff += blkStride ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hpel ( 0 2 ) vertical unsafe [CODESPLIT] static void getLuma02UnsafeNoRound ( byte [ ] pic , int picW , int picH , int [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { int maxH = picH - 1 ; int maxW = picW - 1 ; for ( int j = 0 ; j < blkH ; j ++ ) { int offP0 = clip ( y + j - 2 , 0 , maxH ) * picW ; int offP1 = clip ( y + j - 1 , 0 , maxH ) * picW ; int offP2 = clip ( y + j , 0 , maxH ) * picW ; int offP3 = clip ( y + j + 1 , 0 , maxH ) * picW ; int offP4 = clip ( y + j + 2 , 0 , maxH ) * picW ; int offP5 = clip ( y + j + 3 , 0 , maxH ) * picW ; for ( int i = 0 ; i < blkW ; i ++ ) { int pres_x = clip ( x + i , 0 , maxW ) ; int a = pic [ pres_x + offP0 ] + pic [ pres_x + offP5 ] ; int b = pic [ pres_x + offP1 ] + pic [ pres_x + offP4 ] ; int c = pic [ pres_x + offP2 ] + pic [ pres_x + offP3 ] ; blk [ blkOff + i ] = a + 5 * ( ( c << 2 ) - b ) ; } blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel : ( 1 0 ) horizontal [CODESPLIT] static void getLuma10 ( byte [ ] pic , int picW , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20 ( pic , picW , blk , blkOff , blkStride , x , y , blkW , blkH ) ; int off = y * picW + x ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = ( byte ) ( ( blk [ blkOff + i ] + pic [ off + i ] + 1 ) >> 1 ) ; } off += picW ; blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel vertical ( 0 3 ) [CODESPLIT] static void getLuma03 ( byte [ ] pic , int picW , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma02 ( pic , picW , blk , blkOff , blkStride , x , y , blkW , blkH ) ; int off = y * picW + x ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = ( byte ) ( ( blk [ blkOff + i ] + pic [ off + i + picW ] + 1 ) >> 1 ) ; } off += picW ; blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hpel horizontal Qpel vertical ( 2 1 ) [CODESPLIT] void getLuma21 ( byte [ ] pic , int picW , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20NoRound ( pic , picW , tmp1 , 0 , blkW , x , y - 2 , blkW , blkH + 7 ) ; getLuma02NoRoundInt ( tmp1 , blkW , tmp2 , blkOff , blkStride , 0 , 2 , blkW , blkH ) ; int off = blkW << 1 ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { int rounded = clip ( ( tmp2 [ blkOff + i ] + 512 ) >> 10 , - 128 , 127 ) ; int rounded2 = clip ( ( tmp1 [ off + i ] + 16 ) >> 5 , - 128 , 127 ) ; blk [ blkOff + i ] = ( byte ) ( ( rounded + rounded2 + 1 ) >> 1 ) ; } blkOff += blkStride ; off += blkW ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hpel horizontal Hpel vertical ( 2 2 ) [CODESPLIT] void getLuma22 ( byte [ ] pic , int picW , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20NoRound ( pic , picW , tmp1 , 0 , blkW , x , y - 2 , blkW , blkH + 7 ) ; getLuma02NoRoundInt ( tmp1 , blkW , tmp2 , blkOff , blkStride , 0 , 2 , blkW , blkH ) ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = ( byte ) ( clip ( ( tmp2 [ blkOff + i ] + 512 ) >> 10 , - 128 , 127 ) ) ; } blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hpel ( 2 2 ) unsafe [CODESPLIT] void getLuma22Unsafe ( byte [ ] pic , int picW , int imgH , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20UnsafeNoRound ( pic , picW , imgH , tmp1 , 0 , blkW , x , y - 2 , blkW , blkH + 7 ) ; getLuma02NoRoundInt ( tmp1 , blkW , tmp2 , blkOff , blkStride , 0 , 2 , blkW , blkH ) ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = ( byte ) clip ( ( tmp2 [ blkOff + i ] + 512 ) >> 10 , - 128 , 127 ) ; } blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel ( 2 3 ) unsafe [CODESPLIT] void getLuma23Unsafe ( byte [ ] pic , int picW , int imgH , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20UnsafeNoRound ( pic , picW , imgH , tmp1 , 0 , blkW , x , y - 2 , blkW , blkH + 7 ) ; getLuma02NoRoundInt ( tmp1 , blkW , tmp2 , blkOff , blkStride , 0 , 2 , blkW , blkH ) ; int off = blkW << 1 ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { int rounded = clip ( ( tmp2 [ blkOff + i ] + 512 ) >> 10 , - 128 , 127 ) ; int rounded2 = clip ( ( tmp1 [ off + i + blkW ] + 16 ) >> 5 , - 128 , 127 ) ; blk [ blkOff + i ] = ( byte ) ( ( rounded + rounded2 + 1 ) >> 1 ) ; } blkOff += blkStride ; off += blkW ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel horizontal Hpel vertical ( 1 2 ) [CODESPLIT] void getLuma12 ( byte [ ] pic , int picW , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { int tmpW = blkW + 7 ; getLuma02NoRound ( pic , picW , tmp1 , 0 , tmpW , x - 2 , y , tmpW , blkH ) ; getLuma20NoRoundInt ( tmp1 , tmpW , tmp2 , blkOff , blkStride , 2 , 0 , blkW , blkH ) ; int off = 2 ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { int rounded = clip ( ( tmp2 [ blkOff + i ] + 512 ) >> 10 , - 128 , 127 ) ; int rounded2 = clip ( ( tmp1 [ off + i ] + 16 ) >> 5 , - 128 , 127 ) ; blk [ blkOff + i ] = ( byte ) ( ( rounded + rounded2 + 1 ) >> 1 ) ; } blkOff += blkStride ; off += tmpW ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel ( 1 2 ) unsafe [CODESPLIT] void getLuma12Unsafe ( byte [ ] pic , int picW , int imgH , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { int tmpW = blkW + 7 ; getLuma02UnsafeNoRound ( pic , picW , imgH , tmp1 , 0 , tmpW , x - 2 , y , tmpW , blkH ) ; getLuma20NoRoundInt ( tmp1 , tmpW , tmp2 , blkOff , blkStride , 2 , 0 , blkW , blkH ) ; int off = 2 ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { int rounded = clip ( ( tmp2 [ blkOff + i ] + 512 ) >> 10 , - 128 , 127 ) ; int rounded2 = clip ( ( tmp1 [ off + i ] + 16 ) >> 5 , - 128 , 127 ) ; blk [ blkOff + i ] = ( byte ) ( ( rounded + rounded2 + 1 ) >> 1 ) ; } blkOff += blkStride ; off += tmpW ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel ( 1 1 ) unsafe [CODESPLIT] void getLuma11Unsafe ( byte [ ] pic , int picW , int imgH , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20Unsafe ( pic , picW , imgH , blk , blkOff , blkStride , x , y , blkW , blkH ) ; getLuma02Unsafe ( pic , picW , imgH , tmp3 , 0 , blkW , x , y , blkW , blkH ) ; merge ( blk , tmp3 , blkOff , blkStride , blkW , blkH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel horizontal Qpel vertical ( 1 3 ) [CODESPLIT] void getLuma13 ( byte [ ] pic , int picW , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20 ( pic , picW , blk , blkOff , blkStride , x , y + 1 , blkW , blkH ) ; getLuma02 ( pic , picW , tmp3 , 0 , blkW , x , y , blkW , blkH ) ; merge ( blk , tmp3 , blkOff , blkStride , blkW , blkH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel horizontal Qpel vertical ( 3 1 ) [CODESPLIT] void getLuma31 ( byte [ ] pels , int picW , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20 ( pels , picW , blk , blkOff , blkStride , x , y , blkW , blkH ) ; getLuma02 ( pels , picW , tmp3 , 0 , blkW , x + 1 , y , blkW , blkH ) ; merge ( blk , tmp3 , blkOff , blkStride , blkW , blkH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Qpel ( 3 1 ) unsafe [CODESPLIT] void getLuma31Unsafe ( byte [ ] pels , int picW , int imgH , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { getLuma20Unsafe ( pels , picW , imgH , blk , blkOff , blkStride , x , y , blkW , blkH ) ; getLuma02Unsafe ( pels , picW , imgH , tmp3 , 0 , blkW , x + 1 , y , blkW , blkH ) ; merge ( blk , tmp3 , blkOff , blkStride , blkW , blkH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Chroma ( 0 0 ) [CODESPLIT] private static void getChroma00 ( byte [ ] pic , int picW , int picH , byte [ ] blk , int blkOff , int blkStride , int x , int y , int blkW , int blkH ) { int off = y * picW + x ; for ( int j = 0 ; j < blkH ; j ++ ) { arraycopy ( pic , off , blk , blkOff , blkW ) ; off += picW ; blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Chroma ( X 0 ) [CODESPLIT] private static void getChroma0X ( byte [ ] pels , int picW , int picH , byte [ ] blk , int blkOff , int blkStride , int fullX , int fullY , int fracY , int blkW , int blkH ) { int w00 = fullY * picW + fullX ; int w01 = w00 + ( fullY < picH - 1 ? picW : 0 ) ; int eMy = 8 - fracY ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = ( byte ) ( ( eMy * pels [ w00 + i ] + fracY * pels [ w01 + i ] + 4 ) >> 3 ) ; } w00 += picW ; w01 += picW ; blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Chroma ( X 0 ) [CODESPLIT] private static void getChromaX0 ( byte [ ] pels , int picW , int imgH , byte [ ] blk , int blkOff , int blkStride , int fullX , int fullY , int fracX , int blkW , int blkH ) { int w00 = fullY * picW + fullX ; int w10 = w00 + ( fullX < picW - 1 ? 1 : 0 ) ; int eMx = 8 - fracX ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = ( byte ) ( ( eMx * pels [ w00 + i ] + fracX * pels [ w10 + i ] + 4 ) >> 3 ) ; } w00 += picW ; w10 += picW ; blkOff += blkStride ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Chroma ( X X ) [CODESPLIT] private static void getChromaXX ( byte [ ] pels , int picW , int picH , byte [ ] blk , int blkOff , int blkStride , int fullX , int fullY , int fracX , int fracY , int blkW , int blkH ) { int w00 = fullY * picW + fullX ; int w01 = w00 + ( fullY < picH - 1 ? picW : 0 ) ; int w10 = w00 + ( fullX < picW - 1 ? 1 : 0 ) ; int w11 = w10 + w01 - w00 ; int eMx = 8 - fracX ; int eMy = 8 - fracY ; for ( int j = 0 ; j < blkH ; j ++ ) { for ( int i = 0 ; i < blkW ; i ++ ) { blk [ blkOff + i ] = ( byte ) ( ( eMx * eMy * pels [ w00 + i ] + fracX * eMy * pels [ w10 + i ] + eMx * fracY * pels [ w01 + i ] + fracX * fracY * pels [ w11 + i ] + 32 ) >> 6 ) ; } blkOff += blkStride ; w00 += picW ; w01 += picW ; w10 += picW ; w11 += picW ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode an array of 4 bit element IDs optionally interleaved with a stereo / mono switching bit . [CODESPLIT] private void decodeChannelMap ( ChannelMapping layout_map [ ] , int offset , ChannelPosition type , BitReader _in , int n ) { while ( n -- > 0 ) { RawDataBlockType syn_ele = null ; switch ( type ) { case AAC_CHANNEL_FRONT : case AAC_CHANNEL_BACK : case AAC_CHANNEL_SIDE : syn_ele = RawDataBlockType . values ( ) [ _in . read1Bit ( ) ] ; break ; case AAC_CHANNEL_CC : _in . read1Bit ( ) ; syn_ele = RawDataBlockType . TYPE_CCE ; break ; case AAC_CHANNEL_LFE : syn_ele = RawDataBlockType . TYPE_LFE ; break ; } layout_map [ offset ] . syn_ele = syn_ele ; layout_map [ offset ] . someInt = ( int ) _in . readNBit ( 4 ) ; layout_map [ offset ] . position = type ; offset ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a profile instance for the given index . If the index is not between 1 and 23 inclusive UNKNOWN is returned . [CODESPLIT] public static Profile forInt ( int i ) { Profile p ; if ( i <= 0 || i > ALL . length ) p = UNKNOWN ; else p = ALL [ i - 1 ] ; return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts floating point taps to fixed precision taps . [CODESPLIT] public static void normalizeAndGenerateFixedPrecision ( double [ ] taps , int precBits , short [ ] out ) { double sum = 0 ; for ( int i = 0 ; i < taps . length ; i ++ ) { sum += taps [ i ] ; } int sumFix = 0 ; int precNum = 1 << precBits ; for ( int i = 0 ; i < taps . length ; i ++ ) { double d = ( taps [ i ] * precNum ) / sum + precNum ; int s = ( int ) d ; taps [ i ] = d - s ; out [ i ] = ( short ) ( s - precNum ) ; sumFix += out [ i ] ; } long tapsTaken = 0 ; while ( sumFix < precNum ) { int maxI = - 1 ; for ( int i = 0 ; i < taps . length ; i ++ ) { if ( ( tapsTaken & ( 1 << i ) ) == 0 && ( maxI == - 1 || taps [ i ] > taps [ maxI ] ) ) maxI = i ; } out [ maxI ] ++ ; sumFix ++ ; tapsTaken |= ( 1 << maxI ) ; } for ( int i = 0 ; i < taps . length ; i ++ ) { taps [ i ] += out [ i ] ; if ( ( tapsTaken & ( 1 << i ) ) != 0 ) taps [ i ] -= 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] public void resample ( Picture src , Picture dst ) { int [ ] temp = tempBuffers . get ( ) ; int taps = nTaps ( ) ; if ( temp == null ) { temp = new int [ toSize . getWidth ( ) * ( fromSize . getHeight ( ) + taps ) ] ; tempBuffers . set ( temp ) ; } for ( int p = 0 ; p < src . getColor ( ) . nComp ; p ++ ) { // Horizontal pass for ( int y = 0 ; y < src . getPlaneHeight ( p ) + taps ; y ++ ) { for ( int x = 0 ; x < dst . getPlaneWidth ( p ) ; x ++ ) { short [ ] tapsXs = getTapsX ( x ) ; int srcX = ( int ) ( scaleFactorX * x ) - taps / 2 + 1 ; int sum = 0 ; for ( int i = 0 ; i < taps ; i ++ ) { sum += ( getPel ( src , p , srcX + i , y - taps / 2 + 1 ) + 128 ) * tapsXs [ i ] ; } temp [ y * toSize . getWidth ( ) + x ] = sum ; } } // Vertical pass for ( int y = 0 ; y < dst . getPlaneHeight ( p ) ; y ++ ) { for ( int x = 0 ; x < dst . getPlaneWidth ( p ) ; x ++ ) { short [ ] tapsYs = getTapsY ( y ) ; int srcY = ( int ) ( scaleFactorY * y ) ; int sum = 0 ; for ( int i = 0 ; i < taps ; i ++ ) { sum += temp [ x + ( srcY + i ) * toSize . getWidth ( ) ] * tapsYs [ i ] ; } dst . getPlaneData ( p ) [ y * dst . getPlaneWidth ( p ) + x ] = ( byte ) ( MathUtil . clip ( ( sum + 8192 ) >> 14 , 0 , 255 ) - 128 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * parameter is also called k0 [CODESPLIT] public static int qmf_start_channel ( int bs_start_freq , int bs_samplerate_mode , SampleFrequency sample_rate ) { int startMin = startMinTable [ sample_rate . getIndex ( ) ] ; int offsetIndex = offsetIndexTable [ sample_rate . getIndex ( ) ] ; if ( bs_samplerate_mode != 0 ) { return startMin + OFFSET [ offsetIndex ] [ bs_start_freq ] ; } else { return startMin + OFFSET [ 6 ] [ bs_start_freq ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * parameter is also called k2 [CODESPLIT] public static int qmf_stop_channel ( int bs_stop_freq , SampleFrequency sample_rate , int k0 ) { if ( bs_stop_freq == 15 ) { return Math . min ( 64 , k0 * 3 ) ; } else if ( bs_stop_freq == 14 ) { return Math . min ( 64 , k0 * 2 ) ; } else { int stopMin = stopMinTable [ sample_rate . getIndex ( ) ] ; /* bs_stop_freq <= 13 */ return Math . min ( 64 , stopMin + STOP_OFFSET_TABLE [ sample_rate . getIndex ( ) ] [ Math . min ( bs_stop_freq , 13 ) ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * calculate the master frequency table from k0 k2 bs_freq_scale and bs_alter_scale [CODESPLIT] public static int master_frequency_table_fs0 ( SBR sbr , int k0 , int k2 , boolean bs_alter_scale ) { int incr ; int k ; int dk ; int nrBands , k2Achieved ; int k2Diff ; int [ ] vDk = new int [ 64 ] ; /* mft only defined for k2 > k0 */ if ( k2 <= k0 ) { sbr . N_master = 0 ; return 1 ; } dk = bs_alter_scale ? 2 : 1 ; if ( bs_alter_scale ) { nrBands = ( ( ( k2 - k0 + 2 ) >> 2 ) << 1 ) ; } else { nrBands = ( ( ( k2 - k0 ) >> 1 ) << 1 ) ; } nrBands = Math . min ( nrBands , 63 ) ; if ( nrBands <= 0 ) return 1 ; k2Achieved = k0 + nrBands * dk ; k2Diff = k2 - k2Achieved ; for ( k = 0 ; k < nrBands ; k ++ ) { vDk [ k ] = dk ; } if ( k2Diff != 0 ) { incr = ( k2Diff > 0 ) ? - 1 : 1 ; k = ( ( k2Diff > 0 ) ? ( nrBands - 1 ) : 0 ) ; while ( k2Diff != 0 ) { vDk [ k ] -= incr ; k += incr ; k2Diff += incr ; } } sbr . f_master [ 0 ] = k0 ; for ( k = 1 ; k <= nrBands ; k ++ ) { sbr . f_master [ k ] = ( sbr . f_master [ k - 1 ] + vDk [ k - 1 ] ) ; } sbr . N_master = nrBands ; sbr . N_master = Math . min ( sbr . N_master , 64 ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This function finds the number of bands using this formula : bands * log ( a1 / a0 ) / log ( 2 . 0 ) + 0 . 5 [CODESPLIT] public static int find_bands ( int warp , int bands , int a0 , int a1 ) { float div = ( float ) Math . log ( 2.0 ) ; if ( warp != 0 ) div *= 1.3f ; return ( int ) ( bands * Math . log ( ( float ) a1 / ( float ) a0 ) / div + 0.5 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * version for bs_freq_scale > 0 [CODESPLIT] public static int master_frequency_table ( SBR sbr , int k0 , int k2 , int bs_freq_scale , boolean bs_alter_scale ) { int k , bands ; boolean twoRegions ; int k1 ; int nrBand0 , nrBand1 ; int [ ] vDk0 = new int [ 64 ] , vDk1 = new int [ 64 ] ; int [ ] vk0 = new int [ 64 ] , vk1 = new int [ 64 ] ; int [ ] temp1 = { 6 , 5 , 4 } ; float q , qk ; int A_1 ; /* mft only defined for k2 > k0 */ if ( k2 <= k0 ) { sbr . N_master = 0 ; return 1 ; } bands = temp1 [ bs_freq_scale - 1 ] ; if ( ( float ) k2 / ( float ) k0 > 2.2449 ) { twoRegions = true ; k1 = k0 << 1 ; } else { twoRegions = false ; k1 = k2 ; } nrBand0 = ( 2 * find_bands ( 0 , bands , k0 , k1 ) ) ; nrBand0 = Math . min ( nrBand0 , 63 ) ; if ( nrBand0 <= 0 ) return 1 ; q = find_initial_power ( nrBand0 , k0 , k1 ) ; qk = k0 ; A_1 = ( int ) ( qk + 0.5f ) ; for ( k = 0 ; k <= nrBand0 ; k ++ ) { int A_0 = A_1 ; qk *= q ; A_1 = ( int ) ( qk + 0.5f ) ; vDk0 [ k ] = A_1 - A_0 ; } /* needed? */ //qsort(vDk0, nrBand0, sizeof(vDk0[0]), longcmp); Arrays . sort ( vDk0 , 0 , nrBand0 ) ; vk0 [ 0 ] = k0 ; for ( k = 1 ; k <= nrBand0 ; k ++ ) { vk0 [ k ] = vk0 [ k - 1 ] + vDk0 [ k - 1 ] ; if ( vDk0 [ k - 1 ] == 0 ) return 1 ; } if ( ! twoRegions ) { for ( k = 0 ; k <= nrBand0 ; k ++ ) { sbr . f_master [ k ] = vk0 [ k ] ; } sbr . N_master = nrBand0 ; sbr . N_master = Math . min ( sbr . N_master , 64 ) ; return 0 ; } nrBand1 = ( 2 * find_bands ( 1 /* warped */ , bands , k1 , k2 ) ) ; nrBand1 = Math . min ( nrBand1 , 63 ) ; q = find_initial_power ( nrBand1 , k1 , k2 ) ; qk = k1 ; A_1 = ( int ) ( qk + 0.5f ) ; for ( k = 0 ; k <= nrBand1 - 1 ; k ++ ) { int A_0 = A_1 ; qk *= q ; A_1 = ( int ) ( qk + 0.5f ) ; vDk1 [ k ] = A_1 - A_0 ; } if ( vDk1 [ 0 ] < vDk0 [ nrBand0 - 1 ] ) { int change ; /* needed? */ //qsort(vDk1, nrBand1+1, sizeof(vDk1[0]), longcmp); Arrays . sort ( vDk1 , 0 , nrBand1 + 1 ) ; change = vDk0 [ nrBand0 - 1 ] - vDk1 [ 0 ] ; vDk1 [ 0 ] = vDk0 [ nrBand0 - 1 ] ; vDk1 [ nrBand1 - 1 ] = vDk1 [ nrBand1 - 1 ] - change ; } /* needed? */ //qsort(vDk1, nrBand1, sizeof(vDk1[0]), longcmp); Arrays . sort ( vDk1 , 0 , nrBand1 ) ; vk1 [ 0 ] = k1 ; for ( k = 1 ; k <= nrBand1 ; k ++ ) { vk1 [ k ] = vk1 [ k - 1 ] + vDk1 [ k - 1 ] ; if ( vDk1 [ k - 1 ] == 0 ) return 1 ; } sbr . N_master = nrBand0 + nrBand1 ; sbr . N_master = Math . min ( sbr . N_master , 64 ) ; for ( k = 0 ; k <= nrBand0 ; k ++ ) { sbr . f_master [ k ] = vk0 [ k ] ; } for ( k = nrBand0 + 1 ; k <= sbr . N_master ; k ++ ) { sbr . f_master [ k ] = vk1 [ k - nrBand0 ] ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * calculate the derived frequency border tables from f_master [CODESPLIT] public static int derived_frequency_table ( SBR sbr , int bs_xover_band , int k2 ) { int k , i = 0 ; int minus ; /* The following relation shall be satisfied: bs_xover_band < N_Master */ if ( sbr . N_master <= bs_xover_band ) return 1 ; sbr . N_high = sbr . N_master - bs_xover_band ; sbr . N_low = ( sbr . N_high >> 1 ) + ( sbr . N_high - ( ( sbr . N_high >> 1 ) << 1 ) ) ; sbr . n [ 0 ] = sbr . N_low ; sbr . n [ 1 ] = sbr . N_high ; for ( k = 0 ; k <= sbr . N_high ; k ++ ) { sbr . f_table_res [ HI_RES ] [ k ] = sbr . f_master [ k + bs_xover_band ] ; } sbr . M = sbr . f_table_res [ HI_RES ] [ sbr . N_high ] - sbr . f_table_res [ HI_RES ] [ 0 ] ; sbr . kx = sbr . f_table_res [ HI_RES ] [ 0 ] ; if ( sbr . kx > 32 ) return 1 ; if ( sbr . kx + sbr . M > 64 ) return 1 ; minus = ( ( sbr . N_high & 1 ) != 0 ) ? 1 : 0 ; for ( k = 0 ; k <= sbr . N_low ; k ++ ) { if ( k == 0 ) i = 0 ; else i = ( 2 * k - minus ) ; sbr . f_table_res [ LO_RES ] [ k ] = sbr . f_table_res [ HI_RES ] [ i ] ; } sbr . N_Q = 0 ; if ( sbr . bs_noise_bands == 0 ) { sbr . N_Q = 1 ; } else { sbr . N_Q = ( Math . max ( 1 , find_bands ( 0 , sbr . bs_noise_bands , sbr . kx , k2 ) ) ) ; sbr . N_Q = Math . min ( 5 , sbr . N_Q ) ; } for ( k = 0 ; k <= sbr . N_Q ; k ++ ) { if ( k == 0 ) { i = 0 ; } else { /* i = i + (int32_t)((sbr.N_low - i)/(sbr.N_Q + 1 - k)); */ i += ( sbr . N_low - i ) / ( sbr . N_Q + 1 - k ) ; } sbr . f_table_noise [ k ] = sbr . f_table_res [ LO_RES ] [ i ] ; } /* build table for mapping k to g in hf patching */ for ( k = 0 ; k < 64 ; k ++ ) { int g ; for ( g = 0 ; g < sbr . N_Q ; g ++ ) { if ( ( sbr . f_table_noise [ g ] <= k ) && ( k < sbr . f_table_noise [ g + 1 ] ) ) { sbr . table_map_k_to_g [ k ] = g ; break ; } } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads one full segment till the next marker . Will read as much data as the provided buffer fits if the provided buffer doesn t fit all data will return MORE_DATA . [CODESPLIT] public final State readToNextMarkerPartial ( ByteBuffer out ) throws IOException { if ( done ) return State . STOP ; int skipOneMarker = curMarker >= 0x100 && curMarker <= 0x1ff ? 1 : 0 ; int written = out . position ( ) ; do { while ( buf . hasRemaining ( ) ) { if ( curMarker >= 0x100 && curMarker <= 0x1ff ) { if ( skipOneMarker == 0 ) { return State . DONE ; } -- skipOneMarker ; } if ( ! out . hasRemaining ( ) ) return State . MORE_DATA ; out . put ( ( byte ) ( curMarker >>> 24 ) ) ; curMarker = ( curMarker << 8 ) | ( buf . get ( ) & 0xff ) ; } buf = NIOUtils . fetchFromChannel ( channel , fetchSize ) ; pos += buf . remaining ( ) ; } while ( buf . hasRemaining ( ) ) ; written = out . position ( ) - written ; if ( written > 0 && curMarker >= 0x100 && curMarker <= 0x1ff ) return State . DONE ; for ( ; bytesInMarker > 0 && out . hasRemaining ( ) ; ) { out . put ( ( byte ) ( curMarker >>> 24 ) ) ; curMarker = ( curMarker << 8 ) ; -- bytesInMarker ; if ( curMarker >= 0x100 && curMarker <= 0x1ff ) return State . DONE ; } if ( bytesInMarker == 0 ) { done = true ; return State . STOP ; } else { return State . MORE_DATA ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads one full segment till the next marker . Will allocate the necessary buffer to hold the full segment . Internally uses a growing collection of smaller buffers since the segment size is intitially unkwnown . [CODESPLIT] public ByteBuffer readToNextMarkerNewBuffer ( ) throws IOException { if ( done ) return null ; List < ByteBuffer > buffers = new ArrayList < ByteBuffer > ( ) ; readToNextMarkerBuffers ( buffers ) ; return NIOUtils . combineBuffers ( buffers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There is a method in the class ( or one of its parents ) having the same name with the method named [ readTree ] but is less generic [CODESPLIT] public int readTree3 ( int [ ] tree , int prob0 , int prob1 ) { int i = 0 ; if ( ( i = tree [ i + readBit ( prob0 ) ] ) > 0 ) { while ( ( i = tree [ i + readBit ( prob1 ) ] ) > 0 ) ; } return - i ; /* negate the return value */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds maximum frame of a sequence by bisecting the range . [CODESPLIT] public int getMaxAvailableFrame ( ) { if ( maxAvailableFrame == - 1 ) { int firstPoint = 0 ; for ( int i = MAX_MAX ; i > 0 ; i /= 2 ) { if ( new File ( String . format ( namePattern , i ) ) . exists ( ) ) { firstPoint = i ; break ; } } int pos = firstPoint ; for ( int interv = firstPoint / 2 ; interv > 1 ; interv /= 2 ) { if ( new File ( String . format ( namePattern , pos + interv ) ) . exists ( ) ) { pos += interv ; } } maxAvailableFrame = pos ; Logger . info ( \"Max frame found: \" + maxAvailableFrame ) ; } return Math . min ( maxAvailableFrame , maxFrames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pass 2 : process rows from work array store into output array . [CODESPLIT] private static void pass2 ( IntBuffer outptr , IntBuffer wsptr ) { for ( int ctr = 0 ; ctr < DCTSIZE ; ctr ++ ) { /* Even part: reverse the even part of the forward DCT. */ /* The rotator is sqrt(2)c(-6). */ int z2 = wsptr . get ( 2 ) ; int z3 = wsptr . get ( 6 ) ; int z1 = MULTIPLY ( z2 + z3 , FIX_0_541196100 ) ; int tmp2 = z1 + MULTIPLY ( z3 , - FIX_1_847759065 ) ; int tmp3 = z1 + MULTIPLY ( z2 , FIX_0_765366865 ) ; int tmp0 = ( ( int ) wsptr . get ( 0 ) + ( int ) wsptr . get ( 4 ) ) << CONST_BITS ; int tmp1 = ( ( int ) wsptr . get ( 0 ) - ( int ) wsptr . get ( 4 ) ) << CONST_BITS ; int tmp10 = tmp0 + tmp3 ; int tmp13 = tmp0 - tmp3 ; int tmp11 = tmp1 + tmp2 ; int tmp12 = tmp1 - tmp2 ; /*\n             * Odd part per figure 8; the matrix is unitary and hence its\n             * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.\n             */ tmp0 = ( int ) wsptr . get ( 7 ) ; tmp1 = ( int ) wsptr . get ( 5 ) ; tmp2 = ( int ) wsptr . get ( 3 ) ; tmp3 = ( int ) wsptr . get ( 1 ) ; z1 = tmp0 + tmp3 ; z2 = tmp1 + tmp2 ; z3 = tmp0 + tmp2 ; int z4 = tmp1 + tmp3 ; int z5 = MULTIPLY ( z3 + z4 , FIX_1_175875602 ) ; /* sqrt(2) c3 */ tmp0 = MULTIPLY ( tmp0 , FIX_0_298631336 ) ; /* sqrt(2) (-c1+c3+c5-c7) */ tmp1 = MULTIPLY ( tmp1 , FIX_2_053119869 ) ; /* sqrt(2) ( c1+c3-c5+c7) */ tmp2 = MULTIPLY ( tmp2 , FIX_3_072711026 ) ; /* sqrt(2) ( c1+c3+c5-c7) */ tmp3 = MULTIPLY ( tmp3 , FIX_1_501321110 ) ; /* sqrt(2) ( c1+c3-c5-c7) */ z1 = MULTIPLY ( z1 , - FIX_0_899976223 ) ; /* sqrt(2) (c7-c3) */ z2 = MULTIPLY ( z2 , - FIX_2_562915447 ) ; /* sqrt(2) (-c1-c3) */ z3 = MULTIPLY ( z3 , - FIX_1_961570560 ) ; /* sqrt(2) (-c3-c5) */ z4 = MULTIPLY ( z4 , - FIX_0_390180644 ) ; /* sqrt(2) (c5-c3) */ z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 += z2 + z4 ; tmp2 += z2 + z3 ; tmp3 += z1 + z4 ; /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ int D = CONST_BITS + PASS1_BITS + 3 ; outptr . put ( range_limit ( DESCALE ( tmp10 + tmp3 , D ) & RANGE_MASK ) ) ; outptr . put ( range_limit ( DESCALE ( tmp11 + tmp2 , D ) & RANGE_MASK ) ) ; outptr . put ( range_limit ( DESCALE ( tmp12 + tmp1 , D ) & RANGE_MASK ) ) ; outptr . put ( range_limit ( DESCALE ( tmp13 + tmp0 , D ) & RANGE_MASK ) ) ; outptr . put ( range_limit ( DESCALE ( tmp13 - tmp0 , D ) & RANGE_MASK ) ) ; outptr . put ( range_limit ( DESCALE ( tmp12 - tmp1 , D ) & RANGE_MASK ) ) ; outptr . put ( range_limit ( DESCALE ( tmp11 - tmp2 , D ) & RANGE_MASK ) ) ; outptr . put ( range_limit ( DESCALE ( tmp10 - tmp3 , D ) & RANGE_MASK ) ) ; wsptr = doAdvance ( wsptr , DCTSIZE ) ; /* advance pointer to next row */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Allocate and fill in the sample_range_limit table [CODESPLIT] private static void prepare_range_limit_table ( ) { sample_range_limit . position ( 256 ) ; for ( int i = 0 ; i < 128 ; i ++ ) { sample_range_limit . put ( i ) ; } for ( int i = - 128 ; i < 0 ; i ++ ) { sample_range_limit . put ( i ) ; } for ( int i = 0 ; i < 256 + 128 ; i ++ ) { sample_range_limit . put ( - 1 ) ; } for ( int i = 0 ; i < 256 + 128 ; i ++ ) { sample_range_limit . put ( 0 ) ; } for ( int i = 0 ; i < 128 ; i ++ ) { sample_range_limit . put ( i ) ; } for ( int i = 0 ; i < idct_sample_range_limit . capacity ( ) ; i ++ ) { idct_sample_range_limit . put ( sample_range_limit . get ( i + 128 ) & 0xff ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to modify movie header in place according to what s implemented in the edit the file gets pysically modified if the operation is successful . No temporary file is created . [CODESPLIT] public boolean modify ( File file , MP4Edit edit ) throws IOException { SeekableByteChannel fi = null ; try { fi = NIOUtils . rwChannel ( file ) ; List < Tuple . _2 < Atom , ByteBuffer > > fragments = doTheFix ( fi , edit ) ; if ( fragments == null ) return false ; // If everything is clean, only then actually writing stuff to the // file for ( Tuple . _2 < Atom , ByteBuffer > fragment : fragments ) { replaceBox ( fi , fragment . v0 , fragment . v1 ) ; } return true ; } finally { NIOUtils . closeQuietly ( fi ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to modify movie header in place according to what s implemented in the edit . Copies modified contents to a new file . [CODESPLIT] public boolean copy ( File src , File dst , MP4Edit edit ) throws IOException { SeekableByteChannel fi = null ; SeekableByteChannel fo = null ; try { fi = NIOUtils . readableChannel ( src ) ; fo = NIOUtils . writableChannel ( dst ) ; List < Tuple . _2 < Atom , ByteBuffer > > fragments = doTheFix ( fi , edit ) ; if ( fragments == null ) return false ; List < _2 < Long , ByteBuffer > > fragOffsets = Tuple . _2map0 ( fragments , new Tuple . Mapper < Atom , Long > ( ) { public Long map ( Atom t ) { return t . getOffset ( ) ; } } ) ; // If everything is clean, only then actually start writing file Map < Long , ByteBuffer > rewrite = Tuple . asMap ( fragOffsets ) ; for ( Atom atom : MP4Util . getRootAtoms ( fi ) ) { ByteBuffer byteBuffer = rewrite . get ( atom . getOffset ( ) ) ; if ( byteBuffer != null ) fo . write ( byteBuffer ) ; else atom . copy ( fi , fo ) ; } return true ; } finally { NIOUtils . closeQuietly ( fi ) ; NIOUtils . closeQuietly ( fo ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * calculate linear prediction coefficients using the covariance method [CODESPLIT] private static void calc_prediction_coef ( SBR sbr , float [ ] [ ] [ ] Xlow , float [ ] [ ] alpha_0 , float [ ] [ ] alpha_1 , int k ) { float tmp ; acorr_coef ac = new acorr_coef ( ) ; auto_correlation ( sbr , ac , Xlow , k , sbr . numTimeSlotsRate + 6 ) ; if ( ac . det == 0 ) { alpha_1 [ k ] [ 0 ] = 0 ; alpha_1 [ k ] [ 1 ] = 0 ; } else { tmp = 1.0f / ac . det ; alpha_1 [ k ] [ 0 ] = ( ( ac . r01 [ 0 ] * ac . r12 [ 0 ] ) - ( ac . r01 [ 1 ] * ac . r12 [ 1 ] ) - ( ac . r02 [ 0 ] * ac . r11 [ 0 ] ) ) * tmp ; alpha_1 [ k ] [ 1 ] = ( ( ac . r01 [ 1 ] * ac . r12 [ 0 ] ) + ( ac . r01 [ 0 ] * ac . r12 [ 1 ] ) - ( ac . r02 [ 1 ] * ac . r11 [ 0 ] ) ) * tmp ; } if ( ac . r11 [ 0 ] == 0 ) { alpha_0 [ k ] [ 0 ] = 0 ; alpha_0 [ k ] [ 1 ] = 0 ; } else { tmp = 1.0f / ac . r11 [ 0 ] ; alpha_0 [ k ] [ 0 ] = - ( ac . r01 [ 0 ] + ( alpha_1 [ k ] [ 0 ] * ac . r12 [ 0 ] ) + ( alpha_1 [ k ] [ 1 ] * ac . r12 [ 1 ] ) ) * tmp ; alpha_0 [ k ] [ 1 ] = - ( ac . r01 [ 1 ] + ( alpha_1 [ k ] [ 1 ] * ac . r12 [ 0 ] ) - ( alpha_1 [ k ] [ 0 ] * ac . r12 [ 1 ] ) ) * tmp ; } if ( ( ( alpha_0 [ k ] [ 0 ] * alpha_0 [ k ] [ 0 ] ) + ( alpha_0 [ k ] [ 1 ] * alpha_0 [ k ] [ 1 ] ) >= 16.0f ) || ( ( alpha_1 [ k ] [ 0 ] * alpha_1 [ k ] [ 0 ] ) + ( alpha_1 [ k ] [ 1 ] * alpha_1 [ k ] [ 1 ] ) >= 16.0f ) ) { alpha_0 [ k ] [ 0 ] = 0 ; alpha_0 [ k ] [ 1 ] = 0 ; alpha_1 [ k ] [ 0 ] = 0 ; alpha_1 [ k ] [ 1 ] = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * FIXED POINT : bwArray = COEF [CODESPLIT] private static void calc_chirp_factors ( SBR sbr , int ch ) { int i ; for ( i = 0 ; i < sbr . N_Q ; i ++ ) { sbr . bwArray [ ch ] [ i ] = mapNewBw ( sbr . bs_invf_mode [ ch ] [ i ] , sbr . bs_invf_mode_prev [ ch ] [ i ] ) ; if ( sbr . bwArray [ ch ] [ i ] < sbr . bwArray_prev [ ch ] [ i ] ) sbr . bwArray [ ch ] [ i ] = ( sbr . bwArray [ ch ] [ i ] * 0.75f ) + ( sbr . bwArray_prev [ ch ] [ i ] * 0.25f ) ; else sbr . bwArray [ ch ] [ i ] = ( sbr . bwArray [ ch ] [ i ] * 0.90625f ) + ( sbr . bwArray_prev [ ch ] [ i ] * 0.09375f ) ; if ( sbr . bwArray [ ch ] [ i ] < 0.015625f ) sbr . bwArray [ ch ] [ i ] = 0.0f ; if ( sbr . bwArray [ ch ] [ i ] >= 0.99609375f ) sbr . bwArray [ ch ] [ i ] = 0.99609375f ; sbr . bwArray_prev [ ch ] [ i ] = sbr . bwArray [ ch ] [ i ] ; sbr . bs_invf_mode_prev [ ch ] [ i ] = sbr . bs_invf_mode [ ch ] [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ========== decoding ========== [CODESPLIT] public void decode ( IBitStream _in , AACDecoderConfig conf , boolean commonWindow ) throws AACException { final SampleFrequency sf = conf . getSampleFrequency ( ) ; if ( sf . equals ( SampleFrequency . SAMPLE_FREQUENCY_NONE ) ) throw new AACException ( \"invalid sample frequency\" ) ; _in . skipBit ( ) ; //reserved windowSequence = windowSequenceFromInt ( _in . readBits ( 2 ) ) ; windowShape [ PREVIOUS ] = windowShape [ CURRENT ] ; windowShape [ CURRENT ] = _in . readBit ( ) ; windowGroupCount = 1 ; windowGroupLength [ 0 ] = 1 ; if ( windowSequence . equals ( WindowSequence . EIGHT_SHORT_SEQUENCE ) ) { maxSFB = _in . readBits ( 4 ) ; int i ; for ( i = 0 ; i < 7 ; i ++ ) { if ( _in . readBool ( ) ) windowGroupLength [ windowGroupCount - 1 ] ++ ; else { windowGroupCount ++ ; windowGroupLength [ windowGroupCount - 1 ] = 1 ; } } windowCount = 8 ; swbOffsets = SWB_OFFSET_SHORT_WINDOW [ sf . getIndex ( ) ] ; swbCount = SWB_SHORT_WINDOW_COUNT [ sf . getIndex ( ) ] ; predictionDataPresent = false ; } else { maxSFB = _in . readBits ( 6 ) ; windowCount = 1 ; swbOffsets = SWB_OFFSET_LONG_WINDOW [ sf . getIndex ( ) ] ; swbCount = SWB_LONG_WINDOW_COUNT [ sf . getIndex ( ) ] ; predictionDataPresent = _in . readBool ( ) ; if ( predictionDataPresent ) readPredictionData ( _in , conf . getProfile ( ) , sf , commonWindow ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates track duration considering edits [CODESPLIT] public static long getEditedDuration ( TrakBox track ) { List < Edit > edits = track . getEdits ( ) ; if ( edits == null ) return track . getDuration ( ) ; long duration = 0 ; for ( Edit edit : edits ) { duration += edit . getDuration ( ) ; } return duration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds timevalue of a frame number [CODESPLIT] public static long frameToTimevalue ( TrakBox trak , int frameNumber ) { TimeToSampleBox stts = NodeBox . findFirstPath ( trak , TimeToSampleBox . class , Box . path ( \"mdia.minf.stbl.stts\" ) ) ; TimeToSampleEntry [ ] timeToSamples = stts . getEntries ( ) ; long pts = 0 ; int sttsInd = 0 , sttsSubInd = frameNumber ; while ( sttsSubInd >= timeToSamples [ sttsInd ] . getSampleCount ( ) ) { sttsSubInd -= timeToSamples [ sttsInd ] . getSampleCount ( ) ; pts += timeToSamples [ sttsInd ] . getSampleCount ( ) * timeToSamples [ sttsInd ] . getSampleDuration ( ) ; sttsInd ++ ; } return pts + timeToSamples [ sttsInd ] . getSampleDuration ( ) * sttsSubInd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds frame by timevalue [CODESPLIT] public static int timevalueToFrame ( TrakBox trak , long tv ) { TimeToSampleEntry [ ] tts = NodeBox . findFirstPath ( trak , TimeToSampleBox . class , Box . path ( \"mdia.minf.stbl.stts\" ) ) . getEntries ( ) ; int frame = 0 ; for ( int i = 0 ; tv > 0 && i < tts . length ; i ++ ) { long rem = tv / tts [ i ] . getSampleDuration ( ) ; tv -= tts [ i ] . getSampleCount ( ) * tts [ i ] . getSampleDuration ( ) ; frame += tv > 0 ? tts [ i ] . getSampleCount ( ) : rem ; } return frame ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts media timevalue to edited timevalue [CODESPLIT] public static long mediaToEdited ( TrakBox trak , long mediaTv , int movieTimescale ) { if ( trak . getEdits ( ) == null ) return mediaTv ; long accum = 0 ; for ( Edit edit : trak . getEdits ( ) ) { if ( mediaTv < edit . getMediaTime ( ) ) return accum ; long duration = trak . rescale ( edit . getDuration ( ) , movieTimescale ) ; if ( edit . getMediaTime ( ) != - 1 && ( mediaTv >= edit . getMediaTime ( ) && mediaTv < edit . getMediaTime ( ) + duration ) ) { accum += mediaTv - edit . getMediaTime ( ) ; break ; } accum += duration ; } return accum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts edited timevalue to media timevalue [CODESPLIT] public static long editedToMedia ( TrakBox trak , long editedTv , int movieTimescale ) { if ( trak . getEdits ( ) == null ) return editedTv ; long accum = 0 ; for ( Edit edit : trak . getEdits ( ) ) { long duration = trak . rescale ( edit . getDuration ( ) , movieTimescale ) ; if ( accum + duration > editedTv ) { return edit . getMediaTime ( ) + editedTv - accum ; } accum += duration ; } return accum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates frame number as it shows in quicktime player [CODESPLIT] public static int qtPlayerFrameNo ( MovieBox movie , int mediaFrameNo ) { TrakBox videoTrack = movie . getVideoTrack ( ) ; long editedTv = mediaToEdited ( videoTrack , frameToTimevalue ( videoTrack , mediaFrameNo ) , movie . getTimescale ( ) ) ; return tv2QTFrameNo ( movie , editedTv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates and formats standard time as in Quicktime player [CODESPLIT] public static String qtPlayerTime ( MovieBox movie , int mediaFrameNo ) { TrakBox videoTrack = movie . getVideoTrack ( ) ; long editedTv = mediaToEdited ( videoTrack , frameToTimevalue ( videoTrack , mediaFrameNo ) , movie . getTimescale ( ) ) ; int sec = ( int ) ( editedTv / videoTrack . getTimescale ( ) ) ; return String . format ( \"%02d\" , sec / 3600 ) + \"_\" + String . format ( \"%02d\" , ( sec % 3600 ) / 60 ) + \"_\" + String . format ( \"%02d\" , sec % 60 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates and formats tape timecode as in Quicktime player [CODESPLIT] public static String qtPlayerTimecodeFromMovie ( MovieBox movie , TimecodeMP4DemuxerTrack timecodeTrack , int mediaFrameNo ) throws IOException { TrakBox videoTrack = movie . getVideoTrack ( ) ; long editedTv = mediaToEdited ( videoTrack , frameToTimevalue ( videoTrack , mediaFrameNo ) , movie . getTimescale ( ) ) ; TrakBox tt = timecodeTrack . getBox ( ) ; int ttTimescale = tt . getTimescale ( ) ; long ttTv = editedToMedia ( tt , editedTv * ttTimescale / videoTrack . getTimescale ( ) , movie . getTimescale ( ) ) ; return formatTimecode ( timecodeTrack . getBox ( ) , timecodeTrack . getStartTimecode ( ) + timevalueToTimecodeFrame ( timecodeTrack . getBox ( ) , new RationalLarge ( ttTv , ttTimescale ) , movie . getTimescale ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates and formats tape timecode as in Quicktime player [CODESPLIT] public static String qtPlayerTimecode ( TimecodeMP4DemuxerTrack timecodeTrack , RationalLarge tv , int movieTimescale ) throws IOException { TrakBox tt = timecodeTrack . getBox ( ) ; int ttTimescale = tt . getTimescale ( ) ; long ttTv = editedToMedia ( tt , tv . multiplyS ( ttTimescale ) , movieTimescale ) ; return formatTimecode ( timecodeTrack . getBox ( ) , timecodeTrack . getStartTimecode ( ) + timevalueToTimecodeFrame ( timecodeTrack . getBox ( ) , new RationalLarge ( ttTv , ttTimescale ) , movieTimescale ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts timevalue to frame number based on timecode track [CODESPLIT] public static int timevalueToTimecodeFrame ( TrakBox timecodeTrack , RationalLarge tv , int movieTimescale ) { TimecodeSampleEntry se = ( TimecodeSampleEntry ) timecodeTrack . getSampleEntries ( ) [ 0 ] ; return ( int ) ( ( 2 * tv . multiplyS ( se . getTimescale ( ) ) / se . getFrameDuration ( ) ) + 1 ) / 2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats tape timecode based on frame counter [CODESPLIT] public static String formatTimecode ( TrakBox timecodeTrack , int counter ) { TimecodeSampleEntry tmcd = NodeBox . findFirstPath ( timecodeTrack , TimecodeSampleEntry . class , Box . path ( \"mdia.minf.stbl.stsd.tmcd\" ) ) ; byte nf = tmcd . getNumFrames ( ) ; String tc = String . format ( \"%02d\" , counter % nf ) ; counter /= nf ; tc = String . format ( \"%02d\" , counter % 60 ) + \":\" + tc ; counter /= 60 ; tc = String . format ( \"%02d\" , counter % 60 ) + \":\" + tc ; counter /= 60 ; tc = String . format ( \"%02d\" , counter ) + \":\" + tc ; return tc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates packed 4bit list with 7 values in it [CODESPLIT] public static int _7 ( int val0 , int val1 , int val2 , int val3 , int val4 , int val5 , int val6 ) { return ( 7 << 28 ) | ( ( val0 & 0xf ) << 24 ) | ( ( val1 & 0xf ) << 20 ) | ( ( val2 & 0xf ) << 16 ) | ( ( val3 & 0xf ) << 12 ) | ( ( val4 & 0xf ) << 8 ) | ( ( val5 & 0xf ) << 4 ) | ( ( val6 & 0xf ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a 4 bit value into the list [CODESPLIT] public static int set ( int list , int val , int n ) { int cnt = ( list >> 28 ) & 0xf ; int newc = n + 1 ; cnt = newc > cnt ? newc : cnt ; return ( list & CLEAR_MASK [ n ] ) | ( ( val & 0xff ) << ( n << 2 ) ) | ( cnt << 28 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if two colors match . Aside from simply comparing the objects this function also takes into account lables ANY ANY_INTERLEAVED ANY PLANAR . [CODESPLIT] public boolean matches ( ColorSpace inputColor ) { if ( inputColor == this ) return true ; if ( inputColor == ANY || this == ANY ) return true ; if ( ( inputColor == ANY_INTERLEAVED || this == ANY_INTERLEAVED || inputColor == ANY_PLANAR || this == ANY_PLANAR ) && inputColor . planar == this . planar ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the component size based on the fullt size and color subsampling of the given component index . [CODESPLIT] public Size compSize ( Size size , int comp ) { if ( compWidth [ comp ] == 0 && compHeight [ comp ] == 0 ) return size ; return new Size ( size . getWidth ( ) >> compWidth [ comp ] , size . getHeight ( ) >> compHeight [ comp ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at current position in JCodec native image [CODESPLIT] public PictureWithMetadata getNativeFrameWithMetadata ( ) throws IOException { Packet frame = videoTrack . nextFrame ( ) ; if ( frame == null ) return null ; Picture picture = decoder . decodeFrame ( frame , getBuffer ( ) ) ; return new PictureWithMetadata ( picture , frame . getPtsD ( ) , frame . getDurationD ( ) , videoTrack . getMeta ( ) . getOrientation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at current position in JCodec native image [CODESPLIT] public Picture getNativeFrame ( ) throws IOException { Packet frame = videoTrack . nextFrame ( ) ; if ( frame == null ) return null ; return decoder . decodeFrame ( frame , getBuffer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified second as JCodec image [CODESPLIT] public static Picture getFrameAtSec ( File file , double second ) throws IOException , JCodecException { FileChannelWrapper ch = null ; try { ch = NIOUtils . readableChannel ( file ) ; return createFrameGrab ( ch ) . seekToSecondPrecise ( second ) . getNativeFrame ( ) ; } finally { NIOUtils . closeQuietly ( ch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified second as JCodec image [CODESPLIT] public static Picture getFrameFromChannelAtSec ( SeekableByteChannel file , double second ) throws JCodecException , IOException { return createFrameGrab ( file ) . seekToSecondPrecise ( second ) . getNativeFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified frame number as JCodec image [CODESPLIT] public static Picture getFrameFromFile ( File file , int frameNumber ) throws IOException , JCodecException { FileChannelWrapper ch = null ; try { ch = NIOUtils . readableChannel ( file ) ; return createFrameGrab ( ch ) . seekToFramePrecise ( frameNumber ) . getNativeFrame ( ) ; } finally { NIOUtils . closeQuietly ( ch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified frame number as JCodec image [CODESPLIT] public static Picture getFrameFromChannel ( SeekableByteChannel file , int frameNumber ) throws JCodecException , IOException { return createFrameGrab ( file ) . seekToFramePrecise ( frameNumber ) . getNativeFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by number from an already open demuxer track [CODESPLIT] public static Picture getNativeFrameAtFrame ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , int frameNumber ) throws IOException , JCodecException { return new FrameGrab ( vt , decoder ) . seekToFramePrecise ( frameNumber ) . getNativeFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by second from an already open demuxer track [CODESPLIT] public static Picture getNativeFrameAtSec ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , double second ) throws IOException , JCodecException { return new FrameGrab ( vt , decoder ) . seekToSecondPrecise ( second ) . getNativeFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by number from an already open demuxer track ( sloppy mode i . e . nearest keyframe ) [CODESPLIT] public static Picture getNativeFrameSloppy ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , int frameNumber ) throws IOException , JCodecException { return new FrameGrab ( vt , decoder ) . seekToFrameSloppy ( frameNumber ) . getNativeFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by second from an already open demuxer track ( sloppy mode i . e . nearest keyframe ) [CODESPLIT] public static Picture getNativeFrameAtSecSloppy ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , double second ) throws IOException , JCodecException { return new FrameGrab ( vt , decoder ) . seekToSecondSloppy ( second ) . getNativeFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "does not modify packets [CODESPLIT] public static MP4Demuxer createRawMP4Demuxer ( SeekableByteChannel input ) throws IOException { return new MP4Demuxer ( input ) { @ Override protected AbstractMP4DemuxerTrack newTrack ( TrakBox trak ) { return new MP4DemuxerTrack ( movie , trak , this . input ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only for LTP : no overlapping no short blocks [CODESPLIT] public void processLTP ( WindowSequence windowSequence , int windowShape , int windowShapePrev , float [ ] _in , float [ ] out ) { int i ; switch ( windowSequence ) { case ONLY_LONG_SEQUENCE : for ( i = length - 1 ; i >= 0 ; i -- ) { buf [ i ] = _in [ i ] * LONG_WINDOWS [ windowShapePrev ] [ i ] ; buf [ i + length ] = _in [ i + length ] * LONG_WINDOWS [ windowShape ] [ length - 1 - i ] ; } break ; case LONG_START_SEQUENCE : for ( i = 0 ; i < length ; i ++ ) { buf [ i ] = _in [ i ] * LONG_WINDOWS [ windowShapePrev ] [ i ] ; } for ( i = 0 ; i < mid ; i ++ ) { buf [ i + length ] = _in [ i + length ] ; } for ( i = 0 ; i < shortLen ; i ++ ) { buf [ i + length + mid ] = _in [ i + length + mid ] * SHORT_WINDOWS [ windowShape ] [ shortLen - 1 - i ] ; } for ( i = 0 ; i < mid ; i ++ ) { buf [ i + length + mid + shortLen ] = 0 ; } break ; case LONG_STOP_SEQUENCE : for ( i = 0 ; i < mid ; i ++ ) { buf [ i ] = 0 ; } for ( i = 0 ; i < shortLen ; i ++ ) { buf [ i + mid ] = _in [ i + mid ] * SHORT_WINDOWS [ windowShapePrev ] [ i ] ; } for ( i = 0 ; i < mid ; i ++ ) { buf [ i + mid + shortLen ] = _in [ i + mid + shortLen ] ; } for ( i = 0 ; i < length ; i ++ ) { buf [ i + length ] = _in [ i + length ] * LONG_WINDOWS [ windowShape ] [ length - 1 - i ] ; } break ; } mdctLong . processForward ( buf , out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final void setData ( byte [ ] data ) { //make the buffer size an integer number of words final int size = WORD_BYTES * ( ( data . length + WORD_BYTES - 1 ) / WORD_BYTES ) ; //only reallocate if needed if ( buffer == null || buffer . length != size ) buffer = new byte [ size ] ; arraycopy ( data , 0 , buffer , 0 , data . length ) ; reset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the next four bytes . [CODESPLIT] protected int readCache ( boolean peek ) throws AACException { int i ; if ( pos > buffer . length - WORD_BYTES ) throw AACException . endOfStream ( ) ; else i = ( ( buffer [ pos ] & BYTE_MASK ) << 24 ) | ( ( buffer [ pos + 1 ] & BYTE_MASK ) << 16 ) | ( ( buffer [ pos + 2 ] & BYTE_MASK ) << 8 ) | ( buffer [ pos + 3 ] & BYTE_MASK ) ; if ( ! peek ) pos += WORD_BYTES ; return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public int readBits ( int n ) throws AACException { int result ; if ( bitsCached >= n ) { bitsCached -= n ; result = ( cache >> bitsCached ) & maskBits ( n ) ; position += n ; } else { position += n ; final int c = cache & maskBits ( bitsCached ) ; final int left = n - bitsCached ; cache = readCache ( false ) ; bitsCached = WORD_BITS - left ; result = ( ( cache >> bitsCached ) & maskBits ( left ) ) | ( c << left ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public int readBit ( ) throws AACException { int i ; if ( bitsCached > 0 ) { bitsCached -- ; i = ( cache >> ( bitsCached ) ) & 1 ; position ++ ; } else { cache = readCache ( false ) ; bitsCached = WORD_BITS - 1 ; position ++ ; i = ( cache >> bitsCached ) & 1 ; } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public int peekBits ( int n ) throws AACException { int ret ; if ( bitsCached >= n ) { ret = ( cache >> ( bitsCached - n ) ) & maskBits ( n ) ; } else { //old cache final int c = cache & maskBits ( bitsCached ) ; n -= bitsCached ; //read next & combine ret = ( ( readCache ( true ) >> WORD_BITS - n ) & maskBits ( n ) ) | ( c << n ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public int peekBit ( ) throws AACException { int ret ; if ( bitsCached > 0 ) { ret = ( cache >> ( bitsCached - 1 ) ) & 1 ; } else { final int word = readCache ( true ) ; ret = ( word >> WORD_BITS - 1 ) & 1 ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void skipBits ( int n ) throws AACException { position += n ; if ( n <= bitsCached ) { bitsCached -= n ; } else { n -= bitsCached ; while ( n >= WORD_BITS ) { n -= WORD_BITS ; readCache ( false ) ; } if ( n > 0 ) { cache = readCache ( false ) ; bitsCached = WORD_BITS - n ; } else { cache = 0 ; bitsCached = 0 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void skipBit ( ) throws AACException { position ++ ; if ( bitsCached > 0 ) { bitsCached -- ; } else { cache = readCache ( false ) ; bitsCached = WORD_BITS - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a cropped clone of this picture . [CODESPLIT] public Frame cloneCropped ( ) { if ( cropNeeded ( ) ) { return cropped ( ) ; } else { Frame clone = createFrame ( this ) ; clone . copyFrom ( this ) ; return clone ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "6 * 16 * 2 + 10 * 8 + 4 * 16 * 2 = 192 + 80 + 128 = 400 additions [CODESPLIT] private static void fft_dif ( float [ ] Real , float [ ] Imag ) { float w_real , w_imag ; // For faster access float point1_real , point1_imag , point2_real , point2_imag ; // For faster access int j , i , i2 , w_index ; // Counters // First 2 stages of 32 point FFT decimation in frequency // 4*16*2=64*2=128 multiplications // 6*16*2=96*2=192 additions // Stage 1 of 32 point FFT decimation in frequency for ( i = 0 ; i < 16 ; i ++ ) { point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; i2 = i + 16 ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; w_real = w_array_real [ i ] ; w_imag = w_array_imag [ i ] ; // temp1 = x[i] - x[i2] point1_real -= point2_real ; point1_imag -= point2_imag ; // x[i1] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = (x[i] - x[i2]) * w Real [ i2 ] = ( ( point1_real * w_real ) - ( point1_imag * w_imag ) ) ; Imag [ i2 ] = ( ( point1_real * w_imag ) + ( point1_imag * w_real ) ) ; } // Stage 2 of 32 point FFT decimation in frequency for ( j = 0 , w_index = 0 ; j < 8 ; j ++ , w_index += 2 ) { w_real = w_array_real [ w_index ] ; w_imag = w_array_imag [ w_index ] ; i = j ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; i2 = i + 8 ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // temp1 = x[i] - x[i2] point1_real -= point2_real ; point1_imag -= point2_imag ; // x[i1] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = (x[i] - x[i2]) * w Real [ i2 ] = ( ( point1_real * w_real ) - ( point1_imag * w_imag ) ) ; Imag [ i2 ] = ( ( point1_real * w_imag ) + ( point1_imag * w_real ) ) ; i = j + 16 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; i2 = i + 8 ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // temp1 = x[i] - x[i2] point1_real -= point2_real ; point1_imag -= point2_imag ; // x[i1] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = (x[i] - x[i2]) * w Real [ i2 ] = ( ( point1_real * w_real ) - ( point1_imag * w_imag ) ) ; Imag [ i2 ] = ( ( point1_real * w_imag ) + ( point1_imag * w_real ) ) ; } // Stage 3 of 32 point FFT decimation in frequency // 2*4*2=16 multiplications // 4*4*2+6*4*2=10*8=80 additions for ( i = 0 ; i < n ; i += 8 ) { i2 = i + 4 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // out[i1] = point1 + point2 Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // out[i2] = point1 - point2 Real [ i2 ] = point1_real - point2_real ; Imag [ i2 ] = point1_imag - point2_imag ; } w_real = w_array_real [ 4 ] ; // = sqrt(2)/2 // w_imag = -w_real; // = w_array_imag[4]; // = -sqrt(2)/2 for ( i = 1 ; i < n ; i += 8 ) { i2 = i + 4 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // temp1 = x[i] - x[i2] point1_real -= point2_real ; point1_imag -= point2_imag ; // x[i1] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = (x[i] - x[i2]) * w Real [ i2 ] = ( point1_real + point1_imag ) * w_real ; Imag [ i2 ] = ( point1_imag - point1_real ) * w_real ; } for ( i = 2 ; i < n ; i += 8 ) { i2 = i + 4 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // x[i] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = (x[i] - x[i2]) * (-i) Real [ i2 ] = point1_imag - point2_imag ; Imag [ i2 ] = point2_real - point1_real ; } w_real = w_array_real [ 12 ] ; // = -sqrt(2)/2 // w_imag = w_real; // = w_array_imag[12]; // = -sqrt(2)/2 for ( i = 3 ; i < n ; i += 8 ) { i2 = i + 4 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // temp1 = x[i] - x[i2] point1_real -= point2_real ; point1_imag -= point2_imag ; // x[i1] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = (x[i] - x[i2]) * w Real [ i2 ] = ( point1_real - point1_imag ) * w_real ; Imag [ i2 ] = ( point1_real + point1_imag ) * w_real ; } // Stage 4 of 32 point FFT decimation in frequency (no multiplications) // 16*4=64 additions for ( i = 0 ; i < n ; i += 4 ) { i2 = i + 2 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // x[i1] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = x[i] - x[i2] Real [ i2 ] = point1_real - point2_real ; Imag [ i2 ] = point1_imag - point2_imag ; } for ( i = 1 ; i < n ; i += 4 ) { i2 = i + 2 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // x[i] = x[i] + x[i2] Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // x[i2] = (x[i] - x[i2]) * (-i) Real [ i2 ] = point1_imag - point2_imag ; Imag [ i2 ] = point2_real - point1_real ; } // Stage 5 of 32 point FFT decimation in frequency (no multiplications) // 16*4=64 additions for ( i = 0 ; i < n ; i += 2 ) { i2 = i + 1 ; point1_real = Real [ i ] ; point1_imag = Imag [ i ] ; point2_real = Real [ i2 ] ; point2_imag = Imag [ i2 ] ; // out[i1] = point1 + point2 Real [ i ] += point2_real ; Imag [ i ] += point2_imag ; // out[i2] = point1 - point2 Real [ i2 ] = point1_real - point2_real ; Imag [ i2 ] = point1_imag - point2_imag ; } //FFTReorder(Real, Imag); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * size 64 only! [CODESPLIT] public static void dct4_kernel ( float [ ] in_real , float [ ] in_imag , float [ ] out_real , float [ ] out_imag ) { // Tables with bit reverse values for 5 bits, bit reverse of i at i-th position int i , i_rev ; /* Step 2: modulate */ // 3*32=96 multiplications // 3*32=96 additions for ( i = 0 ; i < 32 ; i ++ ) { float x_re , x_im , tmp ; x_re = in_real [ i ] ; x_im = in_imag [ i ] ; tmp = ( x_re + x_im ) * dct4_64_tab [ i ] ; in_real [ i ] = ( x_im * dct4_64_tab [ i + 64 ] ) + tmp ; in_imag [ i ] = ( x_re * dct4_64_tab [ i + 32 ] ) + tmp ; } /* Step 3: FFT, but with output in bit reverse order */ fft_dif ( in_real , in_imag ) ; /* Step 4: modulate + bitreverse reordering */ // 3*31+2=95 multiplications // 3*31+2=95 additions for ( i = 0 ; i < 16 ; i ++ ) { float x_re , x_im , tmp ; i_rev = bit_rev_tab [ i ] ; x_re = in_real [ i_rev ] ; x_im = in_imag [ i_rev ] ; tmp = ( x_re + x_im ) * dct4_64_tab [ i + 3 * 32 ] ; out_real [ i ] = ( x_im * dct4_64_tab [ i + 5 * 32 ] ) + tmp ; out_imag [ i ] = ( x_re * dct4_64_tab [ i + 4 * 32 ] ) + tmp ; } // i = 16, i_rev = 1 = rev(16); out_imag [ 16 ] = ( in_imag [ 1 ] - in_real [ 1 ] ) * dct4_64_tab [ 16 + 3 * 32 ] ; out_real [ 16 ] = ( in_real [ 1 ] + in_imag [ 1 ] ) * dct4_64_tab [ 16 + 3 * 32 ] ; for ( i = 17 ; i < 32 ; i ++ ) { float x_re , x_im , tmp ; i_rev = bit_rev_tab [ i ] ; x_re = in_real [ i_rev ] ; x_im = in_imag [ i_rev ] ; tmp = ( x_re + x_im ) * dct4_64_tab [ i + 3 * 32 ] ; out_real [ i ] = ( x_im * dct4_64_tab [ i + 5 * 32 ] ) + tmp ; out_imag [ i ] = ( x_re * dct4_64_tab [ i + 4 * 32 ] ) + tmp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates wav header for the specified audio format [CODESPLIT] public static WavHeader createWavHeader ( AudioFormat format , int samples ) { WavHeader w = new WavHeader ( \"RIFF\" , 40 , \"WAVE\" , new FmtChunk ( ( short ) 1 , ( short ) format . getChannels ( ) , format . getSampleRate ( ) , format . getSampleRate ( ) * format . getChannels ( ) * ( format . getSampleSizeInBits ( ) >> 3 ) , ( short ) ( format . getChannels ( ) * ( format . getSampleSizeInBits ( ) >> 3 ) ) , ( short ) format . getSampleSizeInBits ( ) ) , 44 , calcDataSize ( format . getChannels ( ) , format . getSampleSizeInBits ( ) >> 3 , samples ) ) ; return w ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes single channel wavs as input produces multi channel wav [CODESPLIT] public static WavHeader multiChannelWav ( WavHeader [ ] headers ) { WavHeader w = emptyWavHeader ( ) ; int totalSize = 0 ; for ( int i = 0 ; i < headers . length ; i ++ ) { WavHeader wavHeader = headers [ i ] ; totalSize += wavHeader . dataSize ; } w . dataSize = totalSize ; FmtChunk fmt = headers [ 0 ] . fmt ; int bitsPerSample = fmt . bitsPerSample ; int bytesPerSample = bitsPerSample / 8 ; int sampleRate = ( int ) fmt . sampleRate ; w . fmt . bitsPerSample = ( short ) bitsPerSample ; w . fmt . blockAlign = ( short ) ( headers . length * bytesPerSample ) ; w . fmt . byteRate = headers . length * bytesPerSample * sampleRate ; w . fmt . numChannels = ( short ) headers . length ; w . fmt . sampleRate = sampleRate ; return w ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int readNBit ( int n ) throws IOException { if ( n > 32 ) throw new IllegalArgumentException ( \"Can not read more then 32 bit\" ) ; int val = 0 ; for ( int i = 0 ; i < n ; i ++ ) { val <<= 1 ; val |= read1BitInt ( ) ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean moreRBSPData ( ) throws IOException { if ( nBit == 8 ) { advance ( ) ; } int tail = 1 << ( 8 - nBit - 1 ) ; int mask = ( ( tail << 1 ) - 1 ) ; boolean hasTail = ( curByte & mask ) == tail ; return ! ( curByte == - 1 || ( nextByte == - 1 && hasTail ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int peakNextBits ( int n ) throws IOException { if ( n > 8 ) throw new IllegalArgumentException ( \"N should be less then 8\" ) ; if ( nBit == 8 ) { advance ( ) ; if ( curByte == - 1 ) { return - 1 ; } } int [ ] bits = new int [ 16 - nBit ] ; int cnt = 0 ; for ( int i = nBit ; i < 8 ; i ++ ) { bits [ cnt ++ ] = ( curByte >> ( 7 - i ) ) & 0x1 ; } for ( int i = 0 ; i < 8 ; i ++ ) { bits [ cnt ++ ] = ( nextByte >> ( 7 - i ) ) & 0x1 ; } int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { result <<= 1 ; result |= bits [ i ] ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] static MP3SideInfo readSideInfo ( MpaHeader header , ByteBuffer src , int channels ) { MP3SideInfo si = new MP3SideInfo ( ) ; BitReader stream = BitReader . createBitReader ( src ) ; if ( header . version == MPEG1 ) { si . mainDataBegin = stream . readNBit ( 9 ) ; if ( channels == 1 ) si . privateBits = stream . readNBit ( 5 ) ; else si . privateBits = stream . readNBit ( 3 ) ; for ( int ch = 0 ; ch < channels ; ch ++ ) { si . scfsi [ ch ] [ 0 ] = stream . read1Bit ( ) == 0 ; si . scfsi [ ch ] [ 1 ] = stream . read1Bit ( ) == 0 ; si . scfsi [ ch ] [ 2 ] = stream . read1Bit ( ) == 0 ; si . scfsi [ ch ] [ 3 ] = stream . read1Bit ( ) == 0 ; } for ( int gr = 0 ; gr < 2 ; gr ++ ) { for ( int ch = 0 ; ch < channels ; ch ++ ) { Granule granule = si . granule [ ch ] [ gr ] ; granule . part23Length = stream . readNBit ( 12 ) ; granule . bigValues = stream . readNBit ( 9 ) ; granule . globalGain = stream . readNBit ( 8 ) ; granule . scalefacCompress = stream . readNBit ( 4 ) ; granule . windowSwitchingFlag = stream . readNBit ( 1 ) != 0 ; if ( granule . windowSwitchingFlag ) { granule . blockType = stream . readNBit ( 2 ) ; granule . mixedBlockFlag = stream . readNBit ( 1 ) != 0 ; granule . tableSelect [ 0 ] = stream . readNBit ( 5 ) ; granule . tableSelect [ 1 ] = stream . readNBit ( 5 ) ; granule . subblockGain [ 0 ] = stream . readNBit ( 3 ) ; granule . subblockGain [ 1 ] = stream . readNBit ( 3 ) ; granule . subblockGain [ 2 ] = stream . readNBit ( 3 ) ; if ( granule . blockType == 0 ) { return null ; } else if ( granule . blockType == 2 && ! granule . mixedBlockFlag ) { granule . region0Count = 8 ; } else { granule . region0Count = 7 ; } granule . region1Count = 20 - granule . region0Count ; } else { granule . tableSelect [ 0 ] = stream . readNBit ( 5 ) ; granule . tableSelect [ 1 ] = stream . readNBit ( 5 ) ; granule . tableSelect [ 2 ] = stream . readNBit ( 5 ) ; granule . region0Count = stream . readNBit ( 4 ) ; granule . region1Count = stream . readNBit ( 3 ) ; granule . blockType = 0 ; } granule . preflag = stream . readNBit ( 1 ) != 0 ; granule . scalefacScale = stream . readNBit ( 1 ) ; granule . count1tableSelect = stream . readNBit ( 1 ) ; } } } else { si . mainDataBegin = stream . readNBit ( 8 ) ; if ( channels == 1 ) si . privateBits = stream . readNBit ( 1 ) ; else si . privateBits = stream . readNBit ( 2 ) ; for ( int ch = 0 ; ch < channels ; ch ++ ) { Granule granule = si . granule [ ch ] [ 0 ] ; granule . part23Length = stream . readNBit ( 12 ) ; granule . bigValues = stream . readNBit ( 9 ) ; granule . globalGain = stream . readNBit ( 8 ) ; granule . scalefacCompress = stream . readNBit ( 9 ) ; granule . windowSwitchingFlag = stream . readNBit ( 1 ) != 0 ; if ( granule . windowSwitchingFlag ) { granule . blockType = stream . readNBit ( 2 ) ; granule . mixedBlockFlag = stream . readNBit ( 1 ) != 0 ; granule . tableSelect [ 0 ] = stream . readNBit ( 5 ) ; granule . tableSelect [ 1 ] = stream . readNBit ( 5 ) ; granule . subblockGain [ 0 ] = stream . readNBit ( 3 ) ; granule . subblockGain [ 1 ] = stream . readNBit ( 3 ) ; granule . subblockGain [ 2 ] = stream . readNBit ( 3 ) ; if ( granule . blockType == 0 ) { return null ; } else if ( granule . blockType == 2 && ! granule . mixedBlockFlag ) { granule . region0Count = 8 ; } else { granule . region0Count = 7 ; granule . region1Count = 20 - granule . region0Count ; } } else { granule . tableSelect [ 0 ] = stream . readNBit ( 5 ) ; granule . tableSelect [ 1 ] = stream . readNBit ( 5 ) ; granule . tableSelect [ 2 ] = stream . readNBit ( 5 ) ; granule . region0Count = stream . readNBit ( 4 ) ; granule . region1Count = stream . readNBit ( 3 ) ; granule . blockType = 0 ; } granule . scalefacScale = stream . readNBit ( 1 ) ; granule . count1tableSelect = stream . readNBit ( 1 ) ; } } stream . terminate ( ) ; return si ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads one MPEG1 / 2 video frame from MPEG1 / 2 elementary stream into a provided buffer . [CODESPLIT] public MPEGPacket frame ( ByteBuffer buffer ) throws IOException { ByteBuffer dup = buffer . duplicate ( ) ; while ( curMarker != 0x100 && curMarker != 0x1b3 && skipToMarker ( ) ) ; while ( curMarker != 0x100 && readToNextMarker ( dup ) ) ; readToNextMarker ( dup ) ; while ( curMarker != 0x100 && curMarker != 0x1b3 && readToNextMarker ( dup ) ) ; dup . flip ( ) ; PictureHeader ph = MPEGDecoder . getPictureHeader ( dup . duplicate ( ) ) ; return dup . hasRemaining ( ) ? new MPEGPacket ( dup , 0 , 90000 , 0 , frameNo ++ , ph . picture_coding_type <= MPEGConst . IntraCoded ? FrameType . KEY : FrameType . INTER , null ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads one MPEG1 / 2 video frame from MPEG1 / 2 elementary stream . [CODESPLIT] public MPEGPacket getFrame ( ) throws IOException { while ( curMarker != 0x100 && curMarker != 0x1b3 && skipToMarker ( ) ) ; List < ByteBuffer > buffers = new ArrayList < ByteBuffer > ( ) ; // Reading to the frame header, sequence header, sequence header // extensions and group header go in here while ( curMarker != 0x100 && ! done ) readToNextMarkerBuffers ( buffers ) ; // Reading the frame header readToNextMarkerBuffers ( buffers ) ; // Reading the slices, will stop on encounter of a frame header of the // next frame or a sequence header while ( curMarker != 0x100 && curMarker != 0x1b3 && ! done ) readToNextMarkerBuffers ( buffers ) ; ByteBuffer dup = NIOUtils . combineBuffers ( buffers ) ; PictureHeader ph = MPEGDecoder . getPictureHeader ( dup . duplicate ( ) ) ; return dup . hasRemaining ( ) ? new MPEGPacket ( dup , 0 , 90000 , 0 , frameNo ++ , ph . picture_coding_type <= MPEGConst . IntraCoded ? FrameType . KEY : FrameType . INTER , null ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the input arrays as a DecoderSpecificInfo as used in MP4 containers . [CODESPLIT] public static AACDecoderConfig parseMP4DecoderSpecificInfo ( byte [ ] data ) throws AACException { final IBitStream _in = BitStream . createBitStream ( data ) ; final AACDecoderConfig config = new AACDecoderConfig ( ) ; try { config . profile = readProfile ( _in ) ; int sf = _in . readBits ( 4 ) ; if ( sf == 0xF ) config . sampleFrequency = SampleFrequency . forFrequency ( _in . readBits ( 24 ) ) ; else config . sampleFrequency = SampleFrequency . forInt ( sf ) ; config . channelConfiguration = ChannelConfiguration . forInt ( _in . readBits ( 4 ) ) ; Profile cp = config . profile ; if ( AAC_SBR == cp ) { config . extProfile = cp ; config . sbrPresent = true ; sf = _in . readBits ( 4 ) ; //TODO: 24 bits already read; read again? //if(sf==0xF) config.sampleFrequency = SampleFrequency.forFrequency(_in.readBits(24)); //if sample frequencies are the same: downsample SBR config . downSampledSBR = config . sampleFrequency . getIndex ( ) == sf ; config . sampleFrequency = SampleFrequency . forInt ( sf ) ; config . profile = readProfile ( _in ) ; } else if ( AAC_MAIN == cp || AAC_LC == cp || AAC_SSR == cp || AAC_LTP == cp || ER_AAC_LC == cp || ER_AAC_LTP == cp || ER_AAC_LD == cp ) { //ga-specific info: config . frameLengthFlag = _in . readBool ( ) ; if ( config . frameLengthFlag ) throw new AACException ( \"config uses 960-sample frames, not yet supported\" ) ; //TODO: are 960-frames working yet? config . dependsOnCoreCoder = _in . readBool ( ) ; if ( config . dependsOnCoreCoder ) config . coreCoderDelay = _in . readBits ( 14 ) ; else config . coreCoderDelay = 0 ; config . extensionFlag = _in . readBool ( ) ; if ( config . extensionFlag ) { if ( cp . isErrorResilientProfile ( ) ) { config . sectionDataResilience = _in . readBool ( ) ; config . scalefactorResilience = _in . readBool ( ) ; config . spectralDataResilience = _in . readBool ( ) ; } //extensionFlag3 _in . skipBit ( ) ; } if ( config . channelConfiguration == ChannelConfiguration . CHANNEL_CONFIG_NONE ) { //TODO: is this working correct? -> ISO 14496-3 part 1: 1.A.4.3 _in . skipBits ( 3 ) ; //PCE PCE pce = new PCE ( ) ; pce . decode ( _in ) ; config . profile = pce . getProfile ( ) ; config . sampleFrequency = pce . getSampleFrequency ( ) ; config . channelConfiguration = ChannelConfiguration . forInt ( pce . getChannelCount ( ) ) ; } if ( _in . getBitsLeft ( ) > 10 ) readSyncExtension ( _in , config ) ; } else { throw new AACException ( \"profile not supported: \" + cp . getIndex ( ) ) ; } return config ; } finally { _in . destroy ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes one symbol either 0 or 1 [CODESPLIT] public void encode ( int symbol , Context cm ) throws IOException { int rangeLps = MQConst . pLps [ cm . getState ( ) ] ; if ( symbol == cm . getMps ( ) ) { range -= rangeLps ; offset += rangeLps ; if ( range < 0x8000 ) { while ( range < 0x8000 ) renormalize ( ) ; cm . setState ( MQConst . transitMPS [ cm . getState ( ) ] ) ; } } else { range = rangeLps ; while ( range < 0x8000 ) renormalize ( ) ; if ( MQConst . mpsSwitch [ cm . getState ( ) ] != 0 ) cm . setMps ( 1 - cm . getMps ( ) ) ; cm . setState ( MQConst . transitLPS [ cm . getState ( ) ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "static int i = 0 ; [CODESPLIT] private static void readDecoderPicMarking ( NALUnit nalUnit , SliceHeader sh , BitReader _in ) { if ( nalUnit . type == NALUnitType . IDR_SLICE ) { boolean noOutputOfPriorPicsFlag = readBool ( _in , \"SH: no_output_of_prior_pics_flag\" ) ; boolean longTermReferenceFlag = readBool ( _in , \"SH: long_term_reference_flag\" ) ; sh . refPicMarkingIDR = new RefPicMarkingIDR ( noOutputOfPriorPicsFlag , longTermReferenceFlag ) ; } else { boolean adaptiveRefPicMarkingModeFlag = readBool ( _in , \"SH: adaptive_ref_pic_marking_mode_flag\" ) ; if ( adaptiveRefPicMarkingModeFlag ) { ArrayList < Instruction > mmops = new ArrayList < Instruction > ( ) ; int memoryManagementControlOperation ; do { memoryManagementControlOperation = readUEtrace ( _in , \"SH: memory_management_control_operation\" ) ; Instruction instr = null ; switch ( memoryManagementControlOperation ) { case 1 : instr = new RefPicMarking . Instruction ( InstrType . REMOVE_SHORT , readUEtrace ( _in , \"SH: difference_of_pic_nums_minus1\" ) + 1 , 0 ) ; break ; case 2 : instr = new RefPicMarking . Instruction ( InstrType . REMOVE_LONG , readUEtrace ( _in , \"SH: long_term_pic_num\" ) , 0 ) ; break ; case 3 : instr = new RefPicMarking . Instruction ( InstrType . CONVERT_INTO_LONG , readUEtrace ( _in , \"SH: difference_of_pic_nums_minus1\" ) + 1 , readUEtrace ( _in , \"SH: long_term_frame_idx\" ) ) ; break ; case 4 : instr = new RefPicMarking . Instruction ( InstrType . TRUNK_LONG , readUEtrace ( _in , \"SH: max_long_term_frame_idx_plus1\" ) - 1 , 0 ) ; break ; case 5 : instr = new RefPicMarking . Instruction ( InstrType . CLEAR , 0 , 0 ) ; break ; case 6 : instr = new RefPicMarking . Instruction ( InstrType . MARK_LONG , readUEtrace ( _in , \"SH: long_term_frame_idx\" ) , 0 ) ; break ; } if ( instr != null ) mmops . add ( instr ) ; } while ( memoryManagementControlOperation != 0 ) ; sh . refPicMarkingNonIDR = new RefPicMarking ( mmops . toArray ( new Instruction [ ] { } ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private void show ( Frame frame ) { pts = frame . getPts ( ) ; fireTimeEvent ( frame ) ; Picture src = frame . getPic ( ) ; if ( src . getColor ( ) != vo . getColorSpace ( ) ) { if ( dst == null || dst . getWidth ( ) != src . getWidth ( ) || dst . getHeight ( ) != src . getHeight ( ) ) dst = Picture . create ( src . getWidth ( ) , src . getHeight ( ) , vo . getColorSpace ( ) ) ; ColorUtil . getTransform ( src . getColor ( ) , vo . getColorSpace ( ) ) . transform ( src , dst ) ; vo . show ( dst , frame . getPixelAspect ( ) ) ; } else { vo . show ( src , frame . getPixelAspect ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits track on the timevalue specified [CODESPLIT] public static Pair < List < Edit > > split ( MovieBox movie , TrakBox track , long tvMv ) { return splitEdits ( track . getEdits ( ) , new Rational ( track . getTimescale ( ) , movie . getTimescale ( ) ) , tvMv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes one frame of AAC data in frame mode and returns the raw PCM data . [CODESPLIT] public void decodeFrame ( byte [ ] frame , SampleBuffer buffer ) throws AACException { if ( frame != null ) _in . setData ( frame ) ; Logger . debug ( \"bits left \" + _in . getBitsLeft ( ) ) ; try { decode ( buffer ) ; } catch ( AACException e ) { if ( ! e . isEndOfStream ( ) ) throw e ; else Logger . warn ( \"unexpected end of frame\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the endianness for the data . [CODESPLIT] public void setBigEndian ( boolean bigEndian ) { if ( bigEndian != this . bigEndian ) { byte tmp ; for ( int i = 0 ; i < data . length ; i += 2 ) { tmp = data [ i ] ; data [ i ] = data [ i + 1 ] ; data [ i + 1 ] = tmp ; } this . bigEndian = bigEndian ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deblocks bottom edge of topOutMB right edge of leftOutMB and left / top and inner block edges of outMB [CODESPLIT] public void deblockMBGeneric ( EncodedMB curMB , EncodedMB leftMB , EncodedMB topMB , int [ ] [ ] vertStrength , int horizStrength [ ] [ ] ) { Picture curPix = curMB . getPixels ( ) ; if ( leftMB != null ) { Picture leftPix = leftMB . getPixels ( ) ; int avgQp = MathUtil . clip ( ( leftMB . getQp ( ) + curMB . getQp ( ) + 1 ) >> 1 , 0 , 51 ) ; deblockBorder ( vertStrength [ 0 ] , avgQp , leftPix . getPlaneData ( 0 ) , 3 , curPix . getPlaneData ( 0 ) , 0 , P_POS_V , Q_POS_V , false ) ; deblockBorderChroma ( vertStrength [ 0 ] , avgQp , leftPix . getPlaneData ( 1 ) , 3 , curPix . getPlaneData ( 1 ) , 0 , P_POS_V_CHR , Q_POS_V_CHR , false ) ; deblockBorderChroma ( vertStrength [ 0 ] , avgQp , leftPix . getPlaneData ( 2 ) , 3 , curPix . getPlaneData ( 2 ) , 0 , P_POS_V_CHR , Q_POS_V_CHR , false ) ; } for ( int i = 0 ; i < 3 ; i ++ ) { deblockBorder ( vertStrength [ i + 1 ] , curMB . getQp ( ) , curPix . getPlaneData ( 0 ) , i , curPix . getPlaneData ( 0 ) , i + 1 , P_POS_V , Q_POS_V , false ) ; deblockBorderChroma ( vertStrength [ i + 1 ] , curMB . getQp ( ) , curPix . getPlaneData ( 1 ) , i , curPix . getPlaneData ( 1 ) , i + 1 , P_POS_V_CHR , Q_POS_V_CHR , false ) ; deblockBorderChroma ( vertStrength [ i + 1 ] , curMB . getQp ( ) , curPix . getPlaneData ( 2 ) , i , curPix . getPlaneData ( 2 ) , i + 1 , P_POS_V_CHR , Q_POS_V_CHR , false ) ; } if ( topMB != null ) { Picture topPix = topMB . getPixels ( ) ; int avgQp = MathUtil . clip ( ( topMB . getQp ( ) + curMB . getQp ( ) + 1 ) >> 1 , 0 , 51 ) ; deblockBorder ( horizStrength [ 0 ] , avgQp , topPix . getPlaneData ( 0 ) , 3 , curPix . getPlaneData ( 0 ) , 0 , P_POS_H , Q_POS_H , true ) ; deblockBorderChroma ( horizStrength [ 0 ] , avgQp , topPix . getPlaneData ( 1 ) , 3 , curPix . getPlaneData ( 1 ) , 0 , P_POS_H_CHR , Q_POS_H_CHR , true ) ; deblockBorderChroma ( horizStrength [ 0 ] , avgQp , topPix . getPlaneData ( 2 ) , 3 , curPix . getPlaneData ( 2 ) , 0 , P_POS_H_CHR , Q_POS_H_CHR , true ) ; } for ( int i = 0 ; i < 3 ; i ++ ) { deblockBorder ( horizStrength [ i + 1 ] , curMB . getQp ( ) , curPix . getPlaneData ( 0 ) , i , curPix . getPlaneData ( 0 ) , i + 1 , P_POS_H , Q_POS_H , true ) ; deblockBorderChroma ( horizStrength [ i + 1 ] , curMB . getQp ( ) , curPix . getPlaneData ( 1 ) , i , curPix . getPlaneData ( 1 ) , i + 1 , P_POS_H_CHR , Q_POS_H_CHR , true ) ; deblockBorderChroma ( horizStrength [ i + 1 ] , curMB . getQp ( ) , curPix . getPlaneData ( 2 ) , i , curPix . getPlaneData ( 2 ) , i + 1 , P_POS_H_CHR , Q_POS_H_CHR , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deblocks P - macroblock [CODESPLIT] public void deblockMBP ( EncodedMB cur , EncodedMB left , EncodedMB top ) { int [ ] [ ] vertStrength = new int [ 4 ] [ 4 ] ; int [ ] [ ] horizStrength = new int [ 4 ] [ 4 ] ; calcStrengthForBlocks ( cur , left , vertStrength , LOOKUP_IDX_P_V , LOOKUP_IDX_Q_V ) ; calcStrengthForBlocks ( cur , top , horizStrength , LOOKUP_IDX_P_H , LOOKUP_IDX_Q_H ) ; deblockMBGeneric ( cur , left , top , vertStrength , horizStrength ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a frame into a movie . [CODESPLIT] public void encodeNativeFrame ( Picture pic ) throws IOException { if ( pic . getColor ( ) != ColorSpace . RGB ) throw new IllegalArgumentException ( \"The input images is expected in RGB color.\" ) ; ColorSpace sinkColor = sink . getInputColor ( ) ; LoanerPicture toEncode ; if ( sinkColor != null ) { toEncode = pixelStore . getPicture ( pic . getWidth ( ) , pic . getHeight ( ) , sinkColor ) ; transform . transform ( pic , toEncode . getPicture ( ) ) ; } else { toEncode = new LoanerPicture ( pic , 0 ) ; } Packet pkt = Packet . createPacket ( null , timestamp , fps . getNum ( ) , fps . getDen ( ) , frameNo , FrameType . KEY , null ) ; sink . outputVideoFrame ( new VideoFrameWithPacket ( pkt , toEncode ) ) ; if ( sinkColor != null ) pixelStore . putBack ( toEncode ) ; timestamp += fps . getDen ( ) ; frameNo ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes unsigned integer with given length [CODESPLIT] public static byte [ ] ebmlEncodeLen ( long value , int length ) { byte [ ] b = new byte [ length ] ; for ( int idx = 0 ; idx < length ; idx ++ ) { // Rightmost bytes should go to end of array to preserve big-endian notation b [ length - idx - 1 ] = ( byte ) ( ( value >>> ( 8 * idx ) ) & 0xFF L ) ; } b [ 0 ] |= 0x80 >>> ( length - 1 ) ; return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used mostly during reading EBML bitstream . It asnwers the question What is the length of an integer ( signed / unsigned ) encountered in the bitstream [CODESPLIT] static public int computeLength ( byte b ) { if ( b == 0x00 ) throw new RuntimeException ( \"Invalid head element for ebml sequence\" ) ; int i = 1 ; while ( ( b & lengthOptions [ i ] ) == 0 ) i ++ ; return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used mostly during writing EBML bitstream . It answers the following question How many bytes should be used to encode unsigned integer value [CODESPLIT] public static int ebmlLength ( long v ) { if ( v == 0 ) return 1 ; int length = 8 ; while ( length > 0 && ( v & ebmlLengthMasks [ length ] ) == 0 ) length -- ; return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] static void oneLong ( float [ ] src , float [ ] dst ) { for ( int i = 17 ; i > 0 ; i -- ) src [ i ] += src [ i - 1 ] ; for ( int i = 17 ; i > 2 ; i -= 2 ) src [ i ] += src [ i - 2 ] ; for ( int i = 0 , k = 0 ; i < 2 ; i ++ , k += 8 ) { float tmp0 = src [ i ] + src [ i ] ; float tmp1 = tmp0 + src [ 12 + i ] ; float tmp2 = src [ 6 + i ] * factor36pt3 ; tmp [ k + 0 ] = tmp1 + src [ 4 + i ] * factor36pt2 + src [ 8 + i ] * factor36pt1 + src [ 16 + i ] * factor36pt0 ; tmp [ k + 1 ] = tmp0 + src [ 4 + i ] - src [ 8 + i ] - src [ 12 + i ] - src [ 12 + i ] - src [ 16 + i ] ; tmp [ k + 2 ] = tmp1 - src [ 4 + i ] * factor36pt0 - src [ 8 + i ] * factor36pt2 + src [ 16 + i ] * factor36pt1 ; tmp [ k + 3 ] = tmp1 - src [ 4 + i ] * factor36pt1 + src [ 8 + i ] * factor36pt0 - src [ 16 + i ] * factor36pt2 ; tmp [ k + 4 ] = src [ 2 + i ] * factor36pt4 + tmp2 + src [ 10 + i ] * factor36pt5 + src [ 14 + i ] * factor36pt6 ; tmp [ k + 5 ] = ( src [ 2 + i ] - src [ 10 + i ] - src [ 14 + i ] ) * factor36pt3 ; tmp [ k + 6 ] = src [ 2 + i ] * factor36pt5 - tmp2 - src [ 10 + i ] * factor36pt6 + src [ 14 + i ] * factor36pt4 ; tmp [ k + 7 ] = src [ 2 + i ] * factor36pt6 - tmp2 + src [ 10 + i ] * factor36pt4 - src [ 14 + i ] * factor36pt5 ; } for ( int i = 0 , j = 4 , k = 8 , l = 12 ; i < 4 ; i ++ , j ++ , k ++ , l ++ ) { float q1 = tmp [ i ] ; float q2 = tmp [ k ] ; tmp [ i ] += tmp [ j ] ; tmp [ j ] = q1 - tmp [ j ] ; tmp [ k ] = ( tmp [ k ] + tmp [ l ] ) * factor36 [ i ] ; tmp [ l ] = ( q2 - tmp [ l ] ) * factor36 [ 7 - i ] ; } for ( int i = 0 ; i < 4 ; i ++ ) { dst [ 26 - i ] = tmp [ i ] + tmp [ 8 + i ] ; dst [ 8 - i ] = tmp [ 8 + i ] - tmp [ i ] ; dst [ 27 + i ] = dst [ 26 - i ] ; dst [ 9 + i ] = - dst [ 8 - i ] ; } for ( int i = 0 ; i < 4 ; i ++ ) { dst [ 21 - i ] = tmp [ 7 - i ] + tmp [ 15 - i ] ; dst [ 3 - i ] = tmp [ 15 - i ] - tmp [ 7 - i ] ; dst [ 32 + i ] = dst [ 21 - i ] ; dst [ 14 + i ] = - dst [ 3 - i ] ; } float tmp0 = src [ 0 ] - src [ 4 ] + src [ 8 ] - src [ 12 ] + src [ 16 ] ; float tmp1 = ( src [ 1 ] - src [ 5 ] + src [ 9 ] - src [ 13 ] + src [ 17 ] ) * cos450 ; dst [ 4 ] = tmp1 - tmp0 ; dst [ 13 ] = - dst [ 4 ] ; dst [ 31 ] = dst [ 22 ] = tmp0 + tmp1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] static void threeShort ( float [ ] src , float [ ] dst ) { Arrays . fill ( dst , 0.0f ) ; for ( int i = 0 , outOff = 0 ; i < 3 ; i ++ , outOff += 6 ) { imdct12 ( src , dst , outOff , i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] private static void imdct12 ( float [ ] src , float [ ] dst , int outOff , int wndIdx ) { for ( int j = 15 + wndIdx , k = 12 + wndIdx ; j >= 3 + wndIdx ; j -= 3 , k -= 3 ) src [ j ] += src [ k ] ; src [ 15 + wndIdx ] += src [ 9 + wndIdx ] ; src [ 9 + wndIdx ] += src [ 3 + wndIdx ] ; float pp2 = src [ 12 + wndIdx ] * cos600 ; float pp1 = src [ 6 + wndIdx ] * cos300 ; float sum = src [ 0 + wndIdx ] + pp2 ; tmp [ 1 ] = src [ wndIdx ] - src [ 12 + wndIdx ] ; tmp [ 0 ] = sum + pp1 ; tmp [ 2 ] = sum - pp1 ; pp2 = src [ 15 + wndIdx ] * cos600 ; pp1 = src [ 9 + wndIdx ] * cos300 ; sum = src [ 3 + wndIdx ] + pp2 ; tmp [ 4 ] = src [ 3 + wndIdx ] - src [ 15 + wndIdx ] ; tmp [ 5 ] = sum + pp1 ; tmp [ 3 ] = sum - pp1 ; tmp [ 3 ] *= factor12pt0 ; tmp [ 4 ] *= cos450 ; tmp [ 5 ] *= factor12pt1 ; float t = tmp [ 0 ] ; tmp [ 0 ] += tmp [ 5 ] ; tmp [ 5 ] = t - tmp [ 5 ] ; t = tmp [ 1 ] ; tmp [ 1 ] += tmp [ 4 ] ; tmp [ 4 ] = t - tmp [ 4 ] ; t = tmp [ 2 ] ; tmp [ 2 ] += tmp [ 3 ] ; tmp [ 3 ] = t - tmp [ 3 ] ; for ( int j = 0 ; j < 6 ; j ++ ) tmp [ j ] *= factor12 [ j ] ; tmp [ 8 ] = - tmp [ 0 ] * cos375 ; tmp [ 9 ] = - tmp [ 0 ] * cos525 ; tmp [ 7 ] = - tmp [ 1 ] * cos225 ; tmp [ 10 ] = - tmp [ 1 ] * cos675 ; tmp [ 6 ] = - tmp [ 2 ] * cos075 ; tmp [ 11 ] = - tmp [ 2 ] * cos825 ; tmp [ 0 ] = tmp [ 3 ] ; tmp [ 1 ] = tmp [ 4 ] * cos675 ; tmp [ 2 ] = tmp [ 5 ] * cos525 ; tmp [ 3 ] = - tmp [ 5 ] * cos375 ; tmp [ 4 ] = - tmp [ 4 ] * cos225 ; tmp [ 5 ] = - tmp [ 0 ] * cos075 ; tmp [ 0 ] *= cos825 ; for ( int i = 0 , j = outOff + 6 ; i < 12 ; i ++ , j ++ ) { dst [ j ] += tmp [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 2 [CODESPLIT] public int decode ( IBitStream ld , int cnt ) throws AACException { int result = 0 ; int num_align_bits = 0 ; long num_sbr_bits1 = ld . getPosition ( ) ; int num_sbr_bits2 ; int saved_start_freq , saved_samplerate_mode ; int saved_stop_freq , saved_freq_scale ; int saved_xover_band ; boolean saved_alter_scale ; int bs_extension_type = ld . readBits ( 4 ) ; if ( bs_extension_type == EXT_SBR_DATA_CRC ) { this . bs_sbr_crc_bits = ld . readBits ( 10 ) ; } /* save old header values, in case the new ones are corrupted */ saved_start_freq = this . bs_start_freq ; saved_samplerate_mode = this . bs_samplerate_mode ; saved_stop_freq = this . bs_stop_freq ; saved_freq_scale = this . bs_freq_scale ; saved_alter_scale = this . bs_alter_scale ; saved_xover_band = this . bs_xover_band ; this . bs_header_flag = ld . readBool ( ) ; if ( this . bs_header_flag ) sbr_header ( ld ) ; /* Reset? */ sbr_reset ( ) ; /* first frame should have a header */ //if (!(sbr.frame == 0 && sbr.bs_header_flag == 0)) if ( this . header_count != 0 ) { if ( this . Reset || ( this . bs_header_flag && this . just_seeked ) ) { int rt = calc_sbr_tables ( this . bs_start_freq , this . bs_stop_freq , this . bs_samplerate_mode , this . bs_freq_scale , this . bs_alter_scale , this . bs_xover_band ) ; /* if an error occured with the new header values revert to the old ones */ if ( rt > 0 ) { calc_sbr_tables ( saved_start_freq , saved_stop_freq , saved_samplerate_mode , saved_freq_scale , saved_alter_scale , saved_xover_band ) ; } } if ( result == 0 ) { result = sbr_data ( ld ) ; /* sbr_data() returning an error means that there was an error in\n\t\t\t\t envelope_time_border_vector().\n\t\t\t\t In this case the old time border vector is saved and all the previous\n\t\t\t\t data normally read after sbr_grid() is saved.\n\t\t\t\t */ /* to be on the safe side, calculate old sbr tables in case of error */ if ( ( result > 0 ) && ( this . Reset || ( this . bs_header_flag && this . just_seeked ) ) ) { calc_sbr_tables ( saved_start_freq , saved_stop_freq , saved_samplerate_mode , saved_freq_scale , saved_alter_scale , saved_xover_band ) ; } /* we should be able to safely set result to 0 now, */ /* but practise indicates this doesn't work well */ } } else { result = 1 ; } num_sbr_bits2 = ( int ) ( ld . getPosition ( ) - num_sbr_bits1 ) ; /* check if we read more bits then were available for sbr */ if ( 8 * cnt < num_sbr_bits2 ) { throw new AACException ( \"frame overread\" ) ; //faad_resetbits(ld, num_sbr_bits1+8*cnt); //num_sbr_bits2 = 8*cnt; /* turn off PS for the unfortunate case that we randomly read some\n\t\t\t * PS data that looks correct */ //this.ps_used = 0; /* Make sure it doesn't decode SBR in this frame, or we'll get glitches */ //return 1; } { /* -4 does not apply, bs_extension_type is re-read in this function */ num_align_bits = 8 * cnt /*- 4*/ - num_sbr_bits2 ; while ( num_align_bits > 7 ) { ld . readBits ( 8 ) ; num_align_bits -= 8 ; } ld . readBits ( num_align_bits ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 3 [CODESPLIT] private void sbr_header ( IBitStream ld ) throws AACException { boolean bs_header_extra_1 , bs_header_extra_2 ; this . header_count ++ ; this . bs_amp_res = ld . readBool ( ) ; /* bs_start_freq and bs_stop_freq must define a fequency band that does\n\t\t not exceed 48 channels */ this . bs_start_freq = ld . readBits ( 4 ) ; this . bs_stop_freq = ld . readBits ( 4 ) ; this . bs_xover_band = ld . readBits ( 3 ) ; ld . readBits ( 2 ) ; //reserved bs_header_extra_1 = ld . readBool ( ) ; bs_header_extra_2 = ld . readBool ( ) ; if ( bs_header_extra_1 ) { this . bs_freq_scale = ld . readBits ( 2 ) ; this . bs_alter_scale = ld . readBool ( ) ; this . bs_noise_bands = ld . readBits ( 2 ) ; } else { /* Default values */ this . bs_freq_scale = 2 ; this . bs_alter_scale = true ; this . bs_noise_bands = 2 ; } if ( bs_header_extra_2 ) { this . bs_limiter_bands = ld . readBits ( 2 ) ; this . bs_limiter_gains = ld . readBits ( 2 ) ; this . bs_interpol_freq = ld . readBool ( ) ; this . bs_smoothing_mode = ld . readBool ( ) ; } else { /* Default values */ this . bs_limiter_bands = 2 ; this . bs_limiter_gains = 2 ; this . bs_interpol_freq = true ; this . bs_smoothing_mode = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 4 [CODESPLIT] private int sbr_data ( IBitStream ld ) throws AACException { int result ; this . rate = ( this . bs_samplerate_mode != 0 ) ? 2 : 1 ; if ( stereo ) { if ( ( result = sbr_channel_pair_element ( ld ) ) > 0 ) return result ; } else { if ( ( result = sbr_single_channel_element ( ld ) ) > 0 ) return result ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 5 [CODESPLIT] private int sbr_single_channel_element ( IBitStream ld ) throws AACException { int result ; if ( ld . readBool ( ) ) { ld . readBits ( 4 ) ; //reserved } if ( ( result = sbr_grid ( ld , 0 ) ) > 0 ) return result ; sbr_dtdf ( ld , 0 ) ; invf_mode ( ld , 0 ) ; sbr_envelope ( ld , 0 ) ; sbr_noise ( ld , 0 ) ; NoiseEnvelope . dequantChannel ( this , 0 ) ; Arrays . fill ( bs_add_harmonic [ 0 ] , 0 , 64 , 0 ) ; Arrays . fill ( bs_add_harmonic [ 1 ] , 0 , 64 , 0 ) ; this . bs_add_harmonic_flag [ 0 ] = ld . readBool ( ) ; if ( this . bs_add_harmonic_flag [ 0 ] ) sinusoidal_coding ( ld , 0 ) ; this . bs_extended_data = ld . readBool ( ) ; if ( this . bs_extended_data ) { int nr_bits_left ; int ps_ext_read = 0 ; int cnt = ld . readBits ( 4 ) ; if ( cnt == 15 ) { cnt += ld . readBits ( 8 ) ; } nr_bits_left = 8 * cnt ; while ( nr_bits_left > 7 ) { int tmp_nr_bits = 0 ; this . bs_extension_id = ld . readBits ( 2 ) ; tmp_nr_bits += 2 ; /* allow only 1 PS extension element per extension data */ if ( this . bs_extension_id == EXTENSION_ID_PS ) { if ( ps_ext_read == 0 ) { ps_ext_read = 1 ; } else { /* to be safe make it 3, will switch to \"default\"\n\t\t\t\t\t\t * in sbr_extension() */ this . bs_extension_id = 3 ; } } tmp_nr_bits += sbr_extension ( ld , this . bs_extension_id , nr_bits_left ) ; /* check if the data read is bigger than the number of available bits */ if ( tmp_nr_bits > nr_bits_left ) return 1 ; nr_bits_left -= tmp_nr_bits ; } /* Corrigendum */ if ( nr_bits_left > 0 ) { ld . readBits ( nr_bits_left ) ; } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 6 [CODESPLIT] private int sbr_channel_pair_element ( IBitStream ld ) throws AACException { int n , result ; if ( ld . readBool ( ) ) { //reserved ld . readBits ( 4 ) ; ld . readBits ( 4 ) ; } this . bs_coupling = ld . readBool ( ) ; if ( this . bs_coupling ) { if ( ( result = sbr_grid ( ld , 0 ) ) > 0 ) return result ; /* need to copy some data from left to right */ this . bs_frame_class [ 1 ] = this . bs_frame_class [ 0 ] ; this . L_E [ 1 ] = this . L_E [ 0 ] ; this . L_Q [ 1 ] = this . L_Q [ 0 ] ; this . bs_pointer [ 1 ] = this . bs_pointer [ 0 ] ; for ( n = 0 ; n <= this . L_E [ 0 ] ; n ++ ) { this . t_E [ 1 ] [ n ] = this . t_E [ 0 ] [ n ] ; this . f [ 1 ] [ n ] = this . f [ 0 ] [ n ] ; } for ( n = 0 ; n <= this . L_Q [ 0 ] ; n ++ ) { this . t_Q [ 1 ] [ n ] = this . t_Q [ 0 ] [ n ] ; } sbr_dtdf ( ld , 0 ) ; sbr_dtdf ( ld , 1 ) ; invf_mode ( ld , 0 ) ; /* more copying */ for ( n = 0 ; n < this . N_Q ; n ++ ) { this . bs_invf_mode [ 1 ] [ n ] = this . bs_invf_mode [ 0 ] [ n ] ; } sbr_envelope ( ld , 0 ) ; sbr_noise ( ld , 0 ) ; sbr_envelope ( ld , 1 ) ; sbr_noise ( ld , 1 ) ; Arrays . fill ( bs_add_harmonic [ 0 ] , 0 , 64 , 0 ) ; Arrays . fill ( bs_add_harmonic [ 1 ] , 0 , 64 , 0 ) ; this . bs_add_harmonic_flag [ 0 ] = ld . readBool ( ) ; if ( this . bs_add_harmonic_flag [ 0 ] ) sinusoidal_coding ( ld , 0 ) ; this . bs_add_harmonic_flag [ 1 ] = ld . readBool ( ) ; if ( this . bs_add_harmonic_flag [ 1 ] ) sinusoidal_coding ( ld , 1 ) ; } else { int [ ] saved_t_E = new int [ 6 ] , saved_t_Q = new int [ 3 ] ; int saved_L_E = this . L_E [ 0 ] ; int saved_L_Q = this . L_Q [ 0 ] ; int saved_frame_class = this . bs_frame_class [ 0 ] ; for ( n = 0 ; n < saved_L_E ; n ++ ) { saved_t_E [ n ] = this . t_E [ 0 ] [ n ] ; } for ( n = 0 ; n < saved_L_Q ; n ++ ) { saved_t_Q [ n ] = this . t_Q [ 0 ] [ n ] ; } if ( ( result = sbr_grid ( ld , 0 ) ) > 0 ) return result ; if ( ( result = sbr_grid ( ld , 1 ) ) > 0 ) { /* restore first channel data as well */ this . bs_frame_class [ 0 ] = saved_frame_class ; this . L_E [ 0 ] = saved_L_E ; this . L_Q [ 0 ] = saved_L_Q ; for ( n = 0 ; n < 6 ; n ++ ) { this . t_E [ 0 ] [ n ] = saved_t_E [ n ] ; } for ( n = 0 ; n < 3 ; n ++ ) { this . t_Q [ 0 ] [ n ] = saved_t_Q [ n ] ; } return result ; } sbr_dtdf ( ld , 0 ) ; sbr_dtdf ( ld , 1 ) ; invf_mode ( ld , 0 ) ; invf_mode ( ld , 1 ) ; sbr_envelope ( ld , 0 ) ; sbr_envelope ( ld , 1 ) ; sbr_noise ( ld , 0 ) ; sbr_noise ( ld , 1 ) ; Arrays . fill ( bs_add_harmonic [ 0 ] , 0 , 64 , 0 ) ; Arrays . fill ( bs_add_harmonic [ 1 ] , 0 , 64 , 0 ) ; this . bs_add_harmonic_flag [ 0 ] = ld . readBool ( ) ; if ( this . bs_add_harmonic_flag [ 0 ] ) sinusoidal_coding ( ld , 0 ) ; this . bs_add_harmonic_flag [ 1 ] = ld . readBool ( ) ; if ( this . bs_add_harmonic_flag [ 1 ] ) sinusoidal_coding ( ld , 1 ) ; } NoiseEnvelope . dequantChannel ( this , 0 ) ; NoiseEnvelope . dequantChannel ( this , 1 ) ; if ( this . bs_coupling ) NoiseEnvelope . unmap ( this ) ; this . bs_extended_data = ld . readBool ( ) ; if ( this . bs_extended_data ) { int nr_bits_left ; int cnt = ld . readBits ( 4 ) ; if ( cnt == 15 ) { cnt += ld . readBits ( 8 ) ; } nr_bits_left = 8 * cnt ; while ( nr_bits_left > 7 ) { int tmp_nr_bits = 0 ; this . bs_extension_id = ld . readBits ( 2 ) ; tmp_nr_bits += 2 ; tmp_nr_bits += sbr_extension ( ld , this . bs_extension_id , nr_bits_left ) ; /* check if the data read is bigger than the number of available bits */ if ( tmp_nr_bits > nr_bits_left ) return 1 ; nr_bits_left -= tmp_nr_bits ; } /* Corrigendum */ if ( nr_bits_left > 0 ) { ld . readBits ( nr_bits_left ) ; } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 7 [CODESPLIT] private int sbr_grid ( IBitStream ld , int ch ) throws AACException { int i , env , rel , result ; int bs_abs_bord , bs_abs_bord_1 ; int bs_num_env = 0 ; int saved_L_E = this . L_E [ ch ] ; int saved_L_Q = this . L_Q [ ch ] ; int saved_frame_class = this . bs_frame_class [ ch ] ; this . bs_frame_class [ ch ] = ld . readBits ( 2 ) ; switch ( this . bs_frame_class [ ch ] ) { case FIXFIX : i = ld . readBits ( 2 ) ; bs_num_env = Math . min ( 1 << i , 5 ) ; i = ld . readBit ( ) ; for ( env = 0 ; env < bs_num_env ; env ++ ) { this . f [ ch ] [ env ] = i ; } this . abs_bord_lead [ ch ] = 0 ; this . abs_bord_trail [ ch ] = this . numTimeSlots ; this . n_rel_lead [ ch ] = bs_num_env - 1 ; this . n_rel_trail [ ch ] = 0 ; break ; case FIXVAR : bs_abs_bord = ld . readBits ( 2 ) + this . numTimeSlots ; bs_num_env = ld . readBits ( 2 ) + 1 ; for ( rel = 0 ; rel < bs_num_env - 1 ; rel ++ ) { this . bs_rel_bord [ ch ] [ rel ] = 2 * ld . readBits ( 2 ) + 2 ; } i = sbr_log2 ( bs_num_env + 1 ) ; this . bs_pointer [ ch ] = ld . readBits ( i ) ; for ( env = 0 ; env < bs_num_env ; env ++ ) { this . f [ ch ] [ bs_num_env - env - 1 ] = ld . readBit ( ) ; } this . abs_bord_lead [ ch ] = 0 ; this . abs_bord_trail [ ch ] = bs_abs_bord ; this . n_rel_lead [ ch ] = 0 ; this . n_rel_trail [ ch ] = bs_num_env - 1 ; break ; case VARFIX : bs_abs_bord = ld . readBits ( 2 ) ; bs_num_env = ld . readBits ( 2 ) + 1 ; for ( rel = 0 ; rel < bs_num_env - 1 ; rel ++ ) { this . bs_rel_bord [ ch ] [ rel ] = 2 * ld . readBits ( 2 ) + 2 ; } i = sbr_log2 ( bs_num_env + 1 ) ; this . bs_pointer [ ch ] = ld . readBits ( i ) ; for ( env = 0 ; env < bs_num_env ; env ++ ) { this . f [ ch ] [ env ] = ld . readBit ( ) ; } this . abs_bord_lead [ ch ] = bs_abs_bord ; this . abs_bord_trail [ ch ] = this . numTimeSlots ; this . n_rel_lead [ ch ] = bs_num_env - 1 ; this . n_rel_trail [ ch ] = 0 ; break ; case VARVAR : bs_abs_bord = ld . readBits ( 2 ) ; bs_abs_bord_1 = ld . readBits ( 2 ) + this . numTimeSlots ; this . bs_num_rel_0 [ ch ] = ld . readBits ( 2 ) ; this . bs_num_rel_1 [ ch ] = ld . readBits ( 2 ) ; bs_num_env = Math . min ( 5 , this . bs_num_rel_0 [ ch ] + this . bs_num_rel_1 [ ch ] + 1 ) ; for ( rel = 0 ; rel < this . bs_num_rel_0 [ ch ] ; rel ++ ) { this . bs_rel_bord_0 [ ch ] [ rel ] = 2 * ld . readBits ( 2 ) + 2 ; } for ( rel = 0 ; rel < this . bs_num_rel_1 [ ch ] ; rel ++ ) { this . bs_rel_bord_1 [ ch ] [ rel ] = 2 * ld . readBits ( 2 ) + 2 ; } i = sbr_log2 ( this . bs_num_rel_0 [ ch ] + this . bs_num_rel_1 [ ch ] + 2 ) ; this . bs_pointer [ ch ] = ld . readBits ( i ) ; for ( env = 0 ; env < bs_num_env ; env ++ ) { this . f [ ch ] [ env ] = ld . readBit ( ) ; } this . abs_bord_lead [ ch ] = bs_abs_bord ; this . abs_bord_trail [ ch ] = bs_abs_bord_1 ; this . n_rel_lead [ ch ] = this . bs_num_rel_0 [ ch ] ; this . n_rel_trail [ ch ] = this . bs_num_rel_1 [ ch ] ; break ; } if ( this . bs_frame_class [ ch ] == VARVAR ) this . L_E [ ch ] = Math . min ( bs_num_env , 5 ) ; else this . L_E [ ch ] = Math . min ( bs_num_env , 4 ) ; if ( this . L_E [ ch ] <= 0 ) return 1 ; if ( this . L_E [ ch ] > 1 ) this . L_Q [ ch ] = 2 ; else this . L_Q [ ch ] = 1 ; /* TODO: this code can probably be integrated into the code above! */ if ( ( result = TFGrid . envelope_time_border_vector ( this , ch ) ) > 0 ) { this . bs_frame_class [ ch ] = saved_frame_class ; this . L_E [ ch ] = saved_L_E ; this . L_Q [ ch ] = saved_L_Q ; return result ; } TFGrid . noise_floor_time_border_vector ( this , ch ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 8 [CODESPLIT] private void sbr_dtdf ( IBitStream ld , int ch ) throws AACException { int i ; for ( i = 0 ; i < this . L_E [ ch ] ; i ++ ) { this . bs_df_env [ ch ] [ i ] = ld . readBit ( ) ; } for ( i = 0 ; i < this . L_Q [ ch ] ; i ++ ) { this . bs_df_noise [ ch ] [ i ] = ld . readBit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 9 [CODESPLIT] private void invf_mode ( IBitStream ld , int ch ) throws AACException { int n ; for ( n = 0 ; n < this . N_Q ; n ++ ) { this . bs_invf_mode [ ch ] [ n ] = ld . readBits ( 2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 12 [CODESPLIT] private void sinusoidal_coding ( IBitStream ld , int ch ) throws AACException { int n ; for ( n = 0 ; n < this . N_high ; n ++ ) { this . bs_add_harmonic [ ch ] [ n ] = ld . readBit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 10 [CODESPLIT] private void sbr_envelope ( IBitStream ld , int ch ) throws AACException { int env , band ; int delta = 0 ; int [ ] [ ] t_huff , f_huff ; if ( ( this . L_E [ ch ] == 1 ) && ( this . bs_frame_class [ ch ] == FIXFIX ) ) this . amp_res [ ch ] = false ; else this . amp_res [ ch ] = this . bs_amp_res ; if ( ( this . bs_coupling ) && ( ch == 1 ) ) { delta = 1 ; if ( this . amp_res [ ch ] ) { t_huff = T_HUFFMAN_ENV_BAL_3_0DB ; f_huff = F_HUFFMAN_ENV_BAL_3_0DB ; } else { t_huff = T_HUFFMAN_ENV_BAL_1_5DB ; f_huff = F_HUFFMAN_ENV_BAL_1_5DB ; } } else { delta = 0 ; if ( this . amp_res [ ch ] ) { t_huff = T_HUFFMAN_ENV_3_0DB ; f_huff = F_HUFFMAN_ENV_3_0DB ; } else { t_huff = T_HUFFMAN_ENV_1_5DB ; f_huff = F_HUFFMAN_ENV_1_5DB ; } } for ( env = 0 ; env < this . L_E [ ch ] ; env ++ ) { if ( this . bs_df_env [ ch ] [ env ] == 0 ) { if ( this . bs_coupling && ( ch == 1 ) ) { if ( this . amp_res [ ch ] ) { this . E [ ch ] [ 0 ] [ env ] = ld . readBits ( 5 ) << delta ; } else { this . E [ ch ] [ 0 ] [ env ] = ld . readBits ( 6 ) << delta ; } } else { if ( this . amp_res [ ch ] ) { this . E [ ch ] [ 0 ] [ env ] = ld . readBits ( 6 ) << delta ; } else { this . E [ ch ] [ 0 ] [ env ] = ld . readBits ( 7 ) << delta ; } } for ( band = 1 ; band < this . n [ this . f [ ch ] [ env ] ] ; band ++ ) { this . E [ ch ] [ band ] [ env ] = ( decodeHuffman ( ld , f_huff ) << delta ) ; } } else { for ( band = 0 ; band < this . n [ this . f [ ch ] [ env ] ] ; band ++ ) { this . E [ ch ] [ band ] [ env ] = ( decodeHuffman ( ld , t_huff ) << delta ) ; } } } NoiseEnvelope . extract_envelope_data ( this , ch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * table 11 [CODESPLIT] private void sbr_noise ( IBitStream ld , int ch ) throws AACException { int noise , band ; int delta = 0 ; int [ ] [ ] t_huff , f_huff ; if ( this . bs_coupling && ( ch == 1 ) ) { delta = 1 ; t_huff = T_HUFFMAN_NOISE_BAL_3_0DB ; f_huff = F_HUFFMAN_ENV_BAL_3_0DB ; } else { delta = 0 ; t_huff = T_HUFFMAN_NOISE_3_0DB ; f_huff = F_HUFFMAN_ENV_3_0DB ; } for ( noise = 0 ; noise < this . L_Q [ ch ] ; noise ++ ) { if ( this . bs_df_noise [ ch ] [ noise ] == 0 ) { if ( this . bs_coupling && ( ch == 1 ) ) { this . Q [ ch ] [ 0 ] [ noise ] = ld . readBits ( 5 ) << delta ; } else { this . Q [ ch ] [ 0 ] [ noise ] = ld . readBits ( 5 ) << delta ; } for ( band = 1 ; band < this . N_Q ; band ++ ) { this . Q [ ch ] [ band ] [ noise ] = ( decodeHuffman ( ld , f_huff ) << delta ) ; } } else { for ( band = 0 ; band < this . N_Q ; band ++ ) { this . Q [ ch ] [ band ] [ noise ] = ( decodeHuffman ( ld , t_huff ) << delta ) ; } } } NoiseEnvelope . extract_noise_floor_data ( this , ch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses PAT ( Program Association Table ) [CODESPLIT] @ Deprecated public static int parsePAT ( ByteBuffer data ) { PATSection pat = PATSection . parsePAT ( data ) ; if ( pat . getPrograms ( ) . size ( ) > 0 ) return pat . getPrograms ( ) . values ( ) [ 0 ] ; else return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a packet to the underlying file [CODESPLIT] public void addPacket ( FLVTag pkt ) throws IOException { if ( ! writePacket ( writeBuf , pkt ) ) { writeBuf . flip ( ) ; startOfLastPacket -= out . write ( writeBuf ) ; writeBuf . clear ( ) ; if ( ! writePacket ( writeBuf , pkt ) ) throw new RuntimeException ( \"Unexpected\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads an EBML id from the channel . EBML ids have length encoded inside of them For instance all one - byte ids have first byte set to 1 like 0xA3 or 0xE7 whereas the two - byte ids have first byte set to 0 and second byte set to 1 thus : 0x42 0x86 or 0x42 0xF7 [CODESPLIT] static public byte [ ] readEbmlId ( SeekableByteChannel source ) throws IOException { if ( source . position ( ) == source . size ( ) ) return null ; ByteBuffer buffer = ByteBuffer . allocate ( 8 ) ; buffer . limit ( 1 ) ; source . read ( buffer ) ; buffer . flip ( ) ; byte firstByte = buffer . get ( ) ; int numBytes = EbmlUtil . computeLength ( firstByte ) ; if ( numBytes == 0 ) return null ; if ( numBytes > 1 ) { buffer . limit ( numBytes ) ; source . read ( buffer ) ; } buffer . flip ( ) ; ByteBuffer val = ByteBuffer . allocate ( buffer . remaining ( ) ) ; val . put ( buffer ) ; return val . array ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searching for the next tag in a file after corrupt segment [CODESPLIT] public boolean repositionFile ( ) throws IOException { int payloadSize = 0 ; for ( int i = 0 ; i < REPOSITION_BUFFER_READS ; i ++ ) { while ( readBuf . hasRemaining ( ) ) { payloadSize = ( ( payloadSize & 0xffff ) << 8 ) | ( readBuf . get ( ) & 0xff ) ; int pointerPos = readBuf . position ( ) + 7 + payloadSize ; if ( readBuf . position ( ) >= 8 && pointerPos < readBuf . limit ( ) - 4 && readBuf . getInt ( pointerPos ) - payloadSize == 11 ) { readBuf . position ( readBuf . position ( ) - 8 ) ; return true ; } } initialRead ( ch ) ; if ( ! readBuf . hasRemaining ( ) ) break ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * furthermore we scale the results by 2PASS1_BITS . [CODESPLIT] private final static void pass1 ( ShortBuffer data ) { int z1 ; int tmp2 ; int tmp3 ; int tmp0 ; int tmp1 ; int tmp10 ; int tmp13 ; int tmp11 ; int tmp12 ; int z2 ; int z3 ; int z4 ; int z5 ; ShortBuffer dataptr = data . duplicate ( ) ; for ( int rowctr = DCTSIZE - 1 ; rowctr >= 0 ; rowctr -- ) { /*\n             * Due to quantization, we will usually find that many of the input\n             * coefficients are zero, especially the AC terms. We can exploit\n             * this by short-circuiting the IDCT calculation for any row in\n             * which all the AC terms are zero. In that case each output is\n             * equal to the DC coefficient (with scale factor as needed). With\n             * typical images and quantization tables, half or more of the row\n             * DCT calculations can be simplified this way.\n             */ // register int *idataptr = (int*)dataptr; /*\n             * WARNING: we do the same permutation as MMX idct to simplify the\n             * video core\n             */ int d0 = dataptr . get ( 0 ) ; int d2 = dataptr . get ( 1 ) ; int d4 = dataptr . get ( 2 ) ; int d6 = dataptr . get ( 3 ) ; int d1 = dataptr . get ( 4 ) ; int d3 = dataptr . get ( 5 ) ; int d5 = dataptr . get ( 6 ) ; int d7 = dataptr . get ( 7 ) ; if ( ( d1 | d2 | d3 | d4 | d5 | d6 | d7 ) == 0 ) { /* AC terms all zero */ if ( d0 != 0 ) { /* Compute a 32 bit value to assign. */ int dcval = ( int ) ( d0 << PASS1_BITS ) ; for ( int i = 0 ; i < 8 ; i ++ ) { dataptr . put ( i , ( short ) dcval ) ; } } /*\n                 * advance pointer to next row\n                 */ dataptr = advance ( dataptr , DCTSIZE ) ; continue ; } /* Even part: reverse the even part of the forward DCT. */ /* The rotator is sqrt(2)c(-6). */ if ( d6 != 0 ) { if ( d2 != 0 ) { /* d0 != 0, d2 != 0, d4 != 0, d6 != 0 */ z1 = MULTIPLY ( d2 + d6 , FIX_0_541196100 ) ; tmp2 = z1 + MULTIPLY ( - d6 , FIX_1_847759065 ) ; tmp3 = z1 + MULTIPLY ( d2 , FIX_0_765366865 ) ; tmp0 = ( d0 + d4 ) << CONST_BITS ; tmp1 = ( d0 - d4 ) << CONST_BITS ; tmp10 = tmp0 + tmp3 ; tmp13 = tmp0 - tmp3 ; tmp11 = tmp1 + tmp2 ; tmp12 = tmp1 - tmp2 ; } else { /* d0 != 0, d2 == 0, d4 != 0, d6 != 0 */ tmp2 = MULTIPLY ( - d6 , FIX_1_306562965 ) ; tmp3 = MULTIPLY ( d6 , FIX_0_541196100 ) ; tmp0 = ( d0 + d4 ) << CONST_BITS ; tmp1 = ( d0 - d4 ) << CONST_BITS ; tmp10 = tmp0 + tmp3 ; tmp13 = tmp0 - tmp3 ; tmp11 = tmp1 + tmp2 ; tmp12 = tmp1 - tmp2 ; } } else { if ( d2 != 0 ) { /* d0 != 0, d2 != 0, d4 != 0, d6 == 0 */ tmp2 = MULTIPLY ( d2 , FIX_0_541196100 ) ; tmp3 = MULTIPLY ( d2 , FIX_1_306562965 ) ; tmp0 = ( d0 + d4 ) << CONST_BITS ; tmp1 = ( d0 - d4 ) << CONST_BITS ; tmp10 = tmp0 + tmp3 ; tmp13 = tmp0 - tmp3 ; tmp11 = tmp1 + tmp2 ; tmp12 = tmp1 - tmp2 ; } else { /* d0 != 0, d2 == 0, d4 != 0, d6 == 0 */ tmp10 = tmp13 = ( d0 + d4 ) << CONST_BITS ; tmp11 = tmp12 = ( d0 - d4 ) << CONST_BITS ; } } /*\n             * Odd part per figure 8; the matrix is unitary and hence its\n             * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.\n             */ if ( d7 != 0 ) { if ( d5 != 0 ) { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 != 0, d7 != 0 */ z1 = d7 + d1 ; z2 = d5 + d3 ; z3 = d7 + d3 ; z4 = d5 + d1 ; z5 = MULTIPLY ( z3 + z4 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - z1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - z2 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - z3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - z4 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 += z2 + z4 ; tmp2 += z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 != 0, d5 != 0, d7 != 0 */ z2 = d5 + d3 ; z3 = d7 + d3 ; z5 = MULTIPLY ( z3 + d5 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; z1 = MULTIPLY ( - d7 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - z2 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - z3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - d5 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 += z2 + z4 ; tmp2 += z2 + z3 ; tmp3 = z1 + z4 ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 != 0, d7 != 0 */ z1 = d7 + d1 ; z4 = d5 + d1 ; z5 = MULTIPLY ( d7 + z4 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - z1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - d5 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - d7 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - z4 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 += z2 + z4 ; tmp2 = z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 == 0, d5 != 0, d7 != 0 */ tmp0 = MULTIPLY ( - d7 , FIX_0_601344887 ) ; z1 = MULTIPLY ( - d7 , FIX_0_899976223 ) ; z3 = MULTIPLY ( - d7 , FIX_1_961570560 ) ; tmp1 = MULTIPLY ( - d5 , FIX_0_509795579 ) ; z2 = MULTIPLY ( - d5 , FIX_2_562915447 ) ; z4 = MULTIPLY ( - d5 , FIX_0_390180644 ) ; z5 = MULTIPLY ( d5 + d7 , FIX_1_175875602 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z3 ; tmp1 += z4 ; tmp2 = z2 + z3 ; tmp3 = z1 + z4 ; } } } else { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 == 0, d7 != 0 */ z1 = d7 + d1 ; z3 = d7 + d3 ; z5 = MULTIPLY ( z3 + d1 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - z1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - d3 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - z3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - d1 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 = z2 + z4 ; tmp2 += z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 != 0, d5 == 0, d7 != 0 */ z3 = d7 + d3 ; tmp0 = MULTIPLY ( - d7 , FIX_0_601344887 ) ; z1 = MULTIPLY ( - d7 , FIX_0_899976223 ) ; tmp2 = MULTIPLY ( d3 , FIX_0_509795579 ) ; z2 = MULTIPLY ( - d3 , FIX_2_562915447 ) ; z5 = MULTIPLY ( z3 , FIX_1_175875602 ) ; z3 = MULTIPLY ( - z3 , FIX_0_785694958 ) ; tmp0 += z3 ; tmp1 = z2 + z5 ; tmp2 += z3 ; tmp3 = z1 + z5 ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 == 0, d7 != 0 */ z1 = d7 + d1 ; z5 = MULTIPLY ( z1 , FIX_1_175875602 ) ; z1 = MULTIPLY ( z1 , FIX_0_275899380 ) ; z3 = MULTIPLY ( - d7 , FIX_1_961570560 ) ; tmp0 = MULTIPLY ( - d7 , FIX_1_662939225 ) ; z4 = MULTIPLY ( - d1 , FIX_0_390180644 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_111140466 ) ; tmp0 += z1 ; tmp1 = z4 + z5 ; tmp2 = z3 + z5 ; tmp3 += z1 ; } else { /* d1 == 0, d3 == 0, d5 == 0, d7 != 0 */ tmp0 = MULTIPLY ( - d7 , FIX_1_387039845 ) ; tmp1 = MULTIPLY ( d7 , FIX_1_175875602 ) ; tmp2 = MULTIPLY ( - d7 , FIX_0_785694958 ) ; tmp3 = MULTIPLY ( d7 , FIX_0_275899380 ) ; } } } } else { if ( d5 != 0 ) { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 != 0, d7 == 0 */ z2 = d5 + d3 ; z4 = d5 + d1 ; z5 = MULTIPLY ( d3 + z4 , FIX_1_175875602 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - d1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - z2 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - d3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - z4 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 = z1 + z3 ; tmp1 += z2 + z4 ; tmp2 += z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 != 0, d5 != 0, d7 == 0 */ z2 = d5 + d3 ; z5 = MULTIPLY ( z2 , FIX_1_175875602 ) ; tmp1 = MULTIPLY ( d5 , FIX_1_662939225 ) ; z4 = MULTIPLY ( - d5 , FIX_0_390180644 ) ; z2 = MULTIPLY ( - z2 , FIX_1_387039845 ) ; tmp2 = MULTIPLY ( d3 , FIX_1_111140466 ) ; z3 = MULTIPLY ( - d3 , FIX_1_961570560 ) ; tmp0 = z3 + z5 ; tmp1 += z2 ; tmp2 += z2 ; tmp3 = z4 + z5 ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 != 0, d7 == 0 */ z4 = d5 + d1 ; z5 = MULTIPLY ( z4 , FIX_1_175875602 ) ; z1 = MULTIPLY ( - d1 , FIX_0_899976223 ) ; tmp3 = MULTIPLY ( d1 , FIX_0_601344887 ) ; tmp1 = MULTIPLY ( - d5 , FIX_0_509795579 ) ; z2 = MULTIPLY ( - d5 , FIX_2_562915447 ) ; z4 = MULTIPLY ( z4 , FIX_0_785694958 ) ; tmp0 = z1 + z5 ; tmp1 += z4 ; tmp2 = z2 + z5 ; tmp3 += z4 ; } else { /* d1 == 0, d3 == 0, d5 != 0, d7 == 0 */ tmp0 = MULTIPLY ( d5 , FIX_1_175875602 ) ; tmp1 = MULTIPLY ( d5 , FIX_0_275899380 ) ; tmp2 = MULTIPLY ( - d5 , FIX_1_387039845 ) ; tmp3 = MULTIPLY ( d5 , FIX_0_785694958 ) ; } } } else { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 == 0, d7 == 0 */ z5 = d1 + d3 ; tmp3 = MULTIPLY ( d1 , FIX_0_211164243 ) ; tmp2 = MULTIPLY ( - d3 , FIX_1_451774981 ) ; z1 = MULTIPLY ( d1 , FIX_1_061594337 ) ; z2 = MULTIPLY ( - d3 , FIX_2_172734803 ) ; z4 = MULTIPLY ( z5 , FIX_0_785694958 ) ; z5 = MULTIPLY ( z5 , FIX_1_175875602 ) ; tmp0 = z1 - z4 ; tmp1 = z2 + z4 ; tmp2 += z5 ; tmp3 += z5 ; } else { /* d1 == 0, d3 != 0, d5 == 0, d7 == 0 */ tmp0 = MULTIPLY ( - d3 , FIX_0_785694958 ) ; tmp1 = MULTIPLY ( - d3 , FIX_1_387039845 ) ; tmp2 = MULTIPLY ( - d3 , FIX_0_275899380 ) ; tmp3 = MULTIPLY ( d3 , FIX_1_175875602 ) ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 == 0, d7 == 0 */ tmp0 = MULTIPLY ( d1 , FIX_0_275899380 ) ; tmp1 = MULTIPLY ( d1 , FIX_0_785694958 ) ; tmp2 = MULTIPLY ( d1 , FIX_1_175875602 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_387039845 ) ; } else { /* d1 == 0, d3 == 0, d5 == 0, d7 == 0 */ tmp0 = tmp1 = tmp2 = tmp3 = 0 ; } } } } /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ dataptr . put ( 0 , DESCALE11 ( tmp10 + tmp3 ) ) ; dataptr . put ( 7 , DESCALE11 ( tmp10 - tmp3 ) ) ; dataptr . put ( 1 , DESCALE11 ( tmp11 + tmp2 ) ) ; dataptr . put ( 6 , DESCALE11 ( tmp11 - tmp2 ) ) ; dataptr . put ( 2 , DESCALE11 ( tmp12 + tmp1 ) ) ; dataptr . put ( 5 , DESCALE11 ( tmp12 - tmp1 ) ) ; dataptr . put ( 3 , DESCALE11 ( tmp13 + tmp0 ) ) ; dataptr . put ( 4 , DESCALE11 ( tmp13 - tmp0 ) ) ; dataptr = advance ( dataptr , DCTSIZE ) ; /* advance pointer to next row */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the inverse DCT on one block of coefficients . [CODESPLIT] private final static void pass2 ( ShortBuffer data ) { int tmp0 , tmp1 , tmp2 , tmp3 ; int tmp10 , tmp11 , tmp12 , tmp13 ; int z1 , z2 , z3 , z4 , z5 ; int d0 , d1 , d2 , d3 , d4 , d5 , d6 , d7 ; ShortBuffer dataptr = data . duplicate ( ) ; /* Pass 2: process columns. */ /* Note that we must descale the results by a factor of 8 == 23, */ /* and also undo the PASS1_BITS scaling. */ for ( int rowctr = DCTSIZE - 1 ; rowctr >= 0 ; rowctr -- ) { /*\n             * Columns of zeroes can be exploited in the same way as we did with\n             * rows. However, the row calculation has created many nonzero AC\n             * terms, so the simplification applies less often (typically 5% to\n             * 10% of the time). On machines with very fast multiplication, it's\n             * possible that the test takes more time than it's worth. In that\n             * case this section may be commented out.\n             */ d0 = dataptr . get ( DCTSIZE_0 ) ; d1 = dataptr . get ( DCTSIZE_1 ) ; d2 = dataptr . get ( DCTSIZE_2 ) ; d3 = dataptr . get ( DCTSIZE_3 ) ; d4 = dataptr . get ( DCTSIZE_4 ) ; d5 = dataptr . get ( DCTSIZE_5 ) ; d6 = dataptr . get ( DCTSIZE_6 ) ; d7 = dataptr . get ( DCTSIZE_7 ) ; /* Even part: reverse the even part of the forward DCT. */ /* The rotator is sqrt(2)c(-6). */ if ( d6 != 0 ) { if ( d2 != 0 ) { /* d0 != 0, d2 != 0, d4 != 0, d6 != 0 */ z1 = MULTIPLY ( d2 + d6 , FIX_0_541196100 ) ; tmp2 = z1 + MULTIPLY ( - d6 , FIX_1_847759065 ) ; tmp3 = z1 + MULTIPLY ( d2 , FIX_0_765366865 ) ; tmp0 = ( d0 + d4 ) << CONST_BITS ; tmp1 = ( d0 - d4 ) << CONST_BITS ; tmp10 = tmp0 + tmp3 ; tmp13 = tmp0 - tmp3 ; tmp11 = tmp1 + tmp2 ; tmp12 = tmp1 - tmp2 ; } else { /* d0 != 0, d2 == 0, d4 != 0, d6 != 0 */ tmp2 = MULTIPLY ( - d6 , FIX_1_306562965 ) ; tmp3 = MULTIPLY ( d6 , FIX_0_541196100 ) ; tmp0 = ( d0 + d4 ) << CONST_BITS ; tmp1 = ( d0 - d4 ) << CONST_BITS ; tmp10 = tmp0 + tmp3 ; tmp13 = tmp0 - tmp3 ; tmp11 = tmp1 + tmp2 ; tmp12 = tmp1 - tmp2 ; } } else { if ( d2 != 0 ) { /* d0 != 0, d2 != 0, d4 != 0, d6 == 0 */ tmp2 = MULTIPLY ( d2 , FIX_0_541196100 ) ; tmp3 = MULTIPLY ( d2 , FIX_1_306562965 ) ; tmp0 = ( d0 + d4 ) << CONST_BITS ; tmp1 = ( d0 - d4 ) << CONST_BITS ; tmp10 = tmp0 + tmp3 ; tmp13 = tmp0 - tmp3 ; tmp11 = tmp1 + tmp2 ; tmp12 = tmp1 - tmp2 ; } else { /* d0 != 0, d2 == 0, d4 != 0, d6 == 0 */ tmp10 = tmp13 = ( d0 + d4 ) << CONST_BITS ; tmp11 = tmp12 = ( d0 - d4 ) << CONST_BITS ; } } /*\n             * Odd part per figure 8; the matrix is unitary and hence its\n             * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.\n             */ if ( d7 != 0 ) { if ( d5 != 0 ) { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 != 0, d7 != 0 */ z1 = d7 + d1 ; z2 = d5 + d3 ; z3 = d7 + d3 ; z4 = d5 + d1 ; z5 = MULTIPLY ( z3 + z4 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - z1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - z2 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - z3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - z4 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 += z2 + z4 ; tmp2 += z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 != 0, d5 != 0, d7 != 0 */ z1 = d7 ; z2 = d5 + d3 ; z3 = d7 + d3 ; z5 = MULTIPLY ( z3 + d5 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; z1 = MULTIPLY ( - d7 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - z2 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - z3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - d5 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 += z2 + z4 ; tmp2 += z2 + z3 ; tmp3 = z1 + z4 ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 != 0, d7 != 0 */ z1 = d7 + d1 ; z2 = d5 ; z3 = d7 ; z4 = d5 + d1 ; z5 = MULTIPLY ( z3 + z4 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - z1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - d5 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - d7 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - z4 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 += z2 + z4 ; tmp2 = z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 == 0, d5 != 0, d7 != 0 */ tmp0 = MULTIPLY ( - d7 , FIX_0_601344887 ) ; z1 = MULTIPLY ( - d7 , FIX_0_899976223 ) ; z3 = MULTIPLY ( - d7 , FIX_1_961570560 ) ; tmp1 = MULTIPLY ( - d5 , FIX_0_509795579 ) ; z2 = MULTIPLY ( - d5 , FIX_2_562915447 ) ; z4 = MULTIPLY ( - d5 , FIX_0_390180644 ) ; z5 = MULTIPLY ( d5 + d7 , FIX_1_175875602 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z3 ; tmp1 += z4 ; tmp2 = z2 + z3 ; tmp3 = z1 + z4 ; } } } else { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 == 0, d7 != 0 */ z1 = d7 + d1 ; z3 = d7 + d3 ; z5 = MULTIPLY ( z3 + d1 , FIX_1_175875602 ) ; tmp0 = MULTIPLY ( d7 , FIX_0_298631336 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - z1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - d3 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - z3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - d1 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 += z1 + z3 ; tmp1 = z2 + z4 ; tmp2 += z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 != 0, d5 == 0, d7 != 0 */ z3 = d7 + d3 ; tmp0 = MULTIPLY ( - d7 , FIX_0_601344887 ) ; z1 = MULTIPLY ( - d7 , FIX_0_899976223 ) ; tmp2 = MULTIPLY ( d3 , FIX_0_509795579 ) ; z2 = MULTIPLY ( - d3 , FIX_2_562915447 ) ; z5 = MULTIPLY ( z3 , FIX_1_175875602 ) ; z3 = MULTIPLY ( - z3 , FIX_0_785694958 ) ; tmp0 += z3 ; tmp1 = z2 + z5 ; tmp2 += z3 ; tmp3 = z1 + z5 ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 == 0, d7 != 0 */ z1 = d7 + d1 ; z5 = MULTIPLY ( z1 , FIX_1_175875602 ) ; z1 = MULTIPLY ( z1 , FIX_0_275899380 ) ; z3 = MULTIPLY ( - d7 , FIX_1_961570560 ) ; tmp0 = MULTIPLY ( - d7 , FIX_1_662939225 ) ; z4 = MULTIPLY ( - d1 , FIX_0_390180644 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_111140466 ) ; tmp0 += z1 ; tmp1 = z4 + z5 ; tmp2 = z3 + z5 ; tmp3 += z1 ; } else { /* d1 == 0, d3 == 0, d5 == 0, d7 != 0 */ tmp0 = MULTIPLY ( - d7 , FIX_1_387039845 ) ; tmp1 = MULTIPLY ( d7 , FIX_1_175875602 ) ; tmp2 = MULTIPLY ( - d7 , FIX_0_785694958 ) ; tmp3 = MULTIPLY ( d7 , FIX_0_275899380 ) ; } } } } else { if ( d5 != 0 ) { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 != 0, d7 == 0 */ z2 = d5 + d3 ; z4 = d5 + d1 ; z5 = MULTIPLY ( d3 + z4 , FIX_1_175875602 ) ; tmp1 = MULTIPLY ( d5 , FIX_2_053119869 ) ; tmp2 = MULTIPLY ( d3 , FIX_3_072711026 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_501321110 ) ; z1 = MULTIPLY ( - d1 , FIX_0_899976223 ) ; z2 = MULTIPLY ( - z2 , FIX_2_562915447 ) ; z3 = MULTIPLY ( - d3 , FIX_1_961570560 ) ; z4 = MULTIPLY ( - z4 , FIX_0_390180644 ) ; z3 += z5 ; z4 += z5 ; tmp0 = z1 + z3 ; tmp1 += z2 + z4 ; tmp2 += z2 + z3 ; tmp3 += z1 + z4 ; } else { /* d1 == 0, d3 != 0, d5 != 0, d7 == 0 */ z2 = d5 + d3 ; z5 = MULTIPLY ( z2 , FIX_1_175875602 ) ; tmp1 = MULTIPLY ( d5 , FIX_1_662939225 ) ; z4 = MULTIPLY ( - d5 , FIX_0_390180644 ) ; z2 = MULTIPLY ( - z2 , FIX_1_387039845 ) ; tmp2 = MULTIPLY ( d3 , FIX_1_111140466 ) ; z3 = MULTIPLY ( - d3 , FIX_1_961570560 ) ; tmp0 = z3 + z5 ; tmp1 += z2 ; tmp2 += z2 ; tmp3 = z4 + z5 ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 != 0, d7 == 0 */ z4 = d5 + d1 ; z5 = MULTIPLY ( z4 , FIX_1_175875602 ) ; z1 = MULTIPLY ( - d1 , FIX_0_899976223 ) ; tmp3 = MULTIPLY ( d1 , FIX_0_601344887 ) ; tmp1 = MULTIPLY ( - d5 , FIX_0_509795579 ) ; z2 = MULTIPLY ( - d5 , FIX_2_562915447 ) ; z4 = MULTIPLY ( z4 , FIX_0_785694958 ) ; tmp0 = z1 + z5 ; tmp1 += z4 ; tmp2 = z2 + z5 ; tmp3 += z4 ; } else { /* d1 == 0, d3 == 0, d5 != 0, d7 == 0 */ tmp0 = MULTIPLY ( d5 , FIX_1_175875602 ) ; tmp1 = MULTIPLY ( d5 , FIX_0_275899380 ) ; tmp2 = MULTIPLY ( - d5 , FIX_1_387039845 ) ; tmp3 = MULTIPLY ( d5 , FIX_0_785694958 ) ; } } } else { if ( d3 != 0 ) { if ( d1 != 0 ) { /* d1 != 0, d3 != 0, d5 == 0, d7 == 0 */ z5 = d1 + d3 ; tmp3 = MULTIPLY ( d1 , FIX_0_211164243 ) ; tmp2 = MULTIPLY ( - d3 , FIX_1_451774981 ) ; z1 = MULTIPLY ( d1 , FIX_1_061594337 ) ; z2 = MULTIPLY ( - d3 , FIX_2_172734803 ) ; z4 = MULTIPLY ( z5 , FIX_0_785694958 ) ; z5 = MULTIPLY ( z5 , FIX_1_175875602 ) ; tmp0 = z1 - z4 ; tmp1 = z2 + z4 ; tmp2 += z5 ; tmp3 += z5 ; } else { /* d1 == 0, d3 != 0, d5 == 0, d7 == 0 */ tmp0 = MULTIPLY ( - d3 , FIX_0_785694958 ) ; tmp1 = MULTIPLY ( - d3 , FIX_1_387039845 ) ; tmp2 = MULTIPLY ( - d3 , FIX_0_275899380 ) ; tmp3 = MULTIPLY ( d3 , FIX_1_175875602 ) ; } } else { if ( d1 != 0 ) { /* d1 != 0, d3 == 0, d5 == 0, d7 == 0 */ tmp0 = MULTIPLY ( d1 , FIX_0_275899380 ) ; tmp1 = MULTIPLY ( d1 , FIX_0_785694958 ) ; tmp2 = MULTIPLY ( d1 , FIX_1_175875602 ) ; tmp3 = MULTIPLY ( d1 , FIX_1_387039845 ) ; } else { /* d1 == 0, d3 == 0, d5 == 0, d7 == 0 */ tmp0 = tmp1 = tmp2 = tmp3 = 0 ; } } } } /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ dataptr . put ( DCTSIZE_0 , DESCALE18 ( tmp10 + tmp3 ) ) ; dataptr . put ( DCTSIZE_7 , DESCALE18 ( tmp10 - tmp3 ) ) ; dataptr . put ( DCTSIZE_1 , DESCALE18 ( tmp11 + tmp2 ) ) ; dataptr . put ( DCTSIZE_6 , DESCALE18 ( tmp11 - tmp2 ) ) ; dataptr . put ( DCTSIZE_2 , DESCALE18 ( tmp12 + tmp1 ) ) ; dataptr . put ( DCTSIZE_5 , DESCALE18 ( tmp12 - tmp1 ) ) ; dataptr . put ( DCTSIZE_3 , DESCALE18 ( tmp13 + tmp0 ) ) ; dataptr . put ( DCTSIZE_4 , DESCALE18 ( tmp13 - tmp0 ) ) ; dataptr = advance ( dataptr , 1 ) ; /* advance pointer to next column */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes one bin from arithmetice code word [CODESPLIT] public int decodeBin ( int m ) { int bin ; int qIdx = ( range >> 6 ) & 0x3 ; int rLPS = MConst . rangeLPS [ qIdx ] [ cm [ 0 ] [ m ] ] ; range -= rLPS ; int rs8 = range << 8 ; if ( code < rs8 ) { // MPS if ( cm [ 0 ] [ m ] < 62 ) cm [ 0 ] [ m ] ++ ; renormalize ( ) ; bin = cm [ 1 ] [ m ] ; } else { // LPS range = rLPS ; code -= rs8 ; renormalize ( ) ; bin = 1 - cm [ 1 ] [ m ] ; if ( cm [ 0 ] [ m ] == 0 ) cm [ 1 ] [ m ] = 1 - cm [ 1 ] [ m ] ; cm [ 0 ] [ m ] = MConst . transitLPS [ cm [ 0 ] [ m ] ] ; } //        System.out.println(\"CABAC BIT [\" + m + \"]: \" + bin); return bin ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special decoding process for symbols with uniform distribution [CODESPLIT] public int decodeBinBypass ( ) { code <<= 1 ; -- nBitsPending ; if ( nBitsPending <= 0 ) readOneByte ( ) ; int tmp = code - ( range << 8 ) ; if ( tmp < 0 ) { //            System.out.println(\"CABAC BIT [-1]: 0\"); return 0 ; } else { //            System.out.println(\"CABAC BIT [-1]: 1\"); code = tmp ; return 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds next Nth MPEG bitstream marker 0x000001xx and returns the data that preceeds it as a ByteBuffer slice [CODESPLIT] public static final ByteBuffer gotoMarker ( ByteBuffer buf , int n , int mmin , int mmax ) { if ( ! buf . hasRemaining ( ) ) return null ; int from = buf . position ( ) ; ByteBuffer result = buf . slice ( ) ; result . order ( ByteOrder . BIG_ENDIAN ) ; int val = 0xffffffff ; while ( buf . hasRemaining ( ) ) { val = ( val << 8 ) | ( buf . get ( ) & 0xff ) ; if ( val >= mmin && val <= mmax ) { if ( n == 0 ) { buf . position ( buf . position ( ) - 4 ) ; result . limit ( buf . position ( ) - from ) ; break ; } -- n ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * first build into temp vector to be able to use previous vector on error [CODESPLIT] public static int envelope_time_border_vector ( SBR sbr , int ch ) { int l , border , temp ; int [ ] t_E_temp = new int [ 6 ] ; t_E_temp [ 0 ] = sbr . rate * sbr . abs_bord_lead [ ch ] ; t_E_temp [ sbr . L_E [ ch ] ] = sbr . rate * sbr . abs_bord_trail [ ch ] ; switch ( sbr . bs_frame_class [ ch ] ) { case FIXFIX : switch ( sbr . L_E [ ch ] ) { case 4 : temp = ( sbr . numTimeSlots / 4 ) ; t_E_temp [ 3 ] = sbr . rate * 3 * temp ; t_E_temp [ 2 ] = sbr . rate * 2 * temp ; t_E_temp [ 1 ] = sbr . rate * temp ; break ; case 2 : t_E_temp [ 1 ] = sbr . rate * ( sbr . numTimeSlots / 2 ) ; break ; default : break ; } break ; case FIXVAR : if ( sbr . L_E [ ch ] > 1 ) { int i = sbr . L_E [ ch ] ; border = sbr . abs_bord_trail [ ch ] ; for ( l = 0 ; l < ( sbr . L_E [ ch ] - 1 ) ; l ++ ) { if ( border < sbr . bs_rel_bord [ ch ] [ l ] ) return 1 ; border -= sbr . bs_rel_bord [ ch ] [ l ] ; t_E_temp [ -- i ] = sbr . rate * border ; } } break ; case VARFIX : if ( sbr . L_E [ ch ] > 1 ) { int i = 1 ; border = sbr . abs_bord_lead [ ch ] ; for ( l = 0 ; l < ( sbr . L_E [ ch ] - 1 ) ; l ++ ) { border += sbr . bs_rel_bord [ ch ] [ l ] ; if ( sbr . rate * border + sbr . tHFAdj > sbr . numTimeSlotsRate + sbr . tHFGen ) return 1 ; t_E_temp [ i ++ ] = sbr . rate * border ; } } break ; case VARVAR : if ( sbr . bs_num_rel_0 [ ch ] != 0 ) { int i = 1 ; border = sbr . abs_bord_lead [ ch ] ; for ( l = 0 ; l < sbr . bs_num_rel_0 [ ch ] ; l ++ ) { border += sbr . bs_rel_bord_0 [ ch ] [ l ] ; if ( sbr . rate * border + sbr . tHFAdj > sbr . numTimeSlotsRate + sbr . tHFGen ) return 1 ; t_E_temp [ i ++ ] = sbr . rate * border ; } } if ( sbr . bs_num_rel_1 [ ch ] != 0 ) { int i = sbr . L_E [ ch ] ; border = sbr . abs_bord_trail [ ch ] ; for ( l = 0 ; l < sbr . bs_num_rel_1 [ ch ] ; l ++ ) { if ( border < sbr . bs_rel_bord_1 [ ch ] [ l ] ) return 1 ; border -= sbr . bs_rel_bord_1 [ ch ] [ l ] ; t_E_temp [ -- i ] = sbr . rate * border ; } } break ; } /* no error occured, we can safely use this t_E vector */ for ( l = 0 ; l < 6 ; l ++ ) { sbr . t_E [ ch ] [ l ] = t_E_temp [ l ] ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * real filter size 2 [CODESPLIT] static void channel_filter2 ( int frame_len , float [ ] filter , float [ ] [ ] buffer , float [ ] [ ] [ ] X_hybrid ) { int i ; for ( i = 0 ; i < frame_len ; i ++ ) { float r0 = ( filter [ 0 ] * ( buffer [ 0 + i ] [ 0 ] + buffer [ 12 + i ] [ 0 ] ) ) ; float r1 = ( filter [ 1 ] * ( buffer [ 1 + i ] [ 0 ] + buffer [ 11 + i ] [ 0 ] ) ) ; float r2 = ( filter [ 2 ] * ( buffer [ 2 + i ] [ 0 ] + buffer [ 10 + i ] [ 0 ] ) ) ; float r3 = ( filter [ 3 ] * ( buffer [ 3 + i ] [ 0 ] + buffer [ 9 + i ] [ 0 ] ) ) ; float r4 = ( filter [ 4 ] * ( buffer [ 4 + i ] [ 0 ] + buffer [ 8 + i ] [ 0 ] ) ) ; float r5 = ( filter [ 5 ] * ( buffer [ 5 + i ] [ 0 ] + buffer [ 7 + i ] [ 0 ] ) ) ; float r6 = ( filter [ 6 ] * buffer [ 6 + i ] [ 0 ] ) ; float i0 = ( filter [ 0 ] * ( buffer [ 0 + i ] [ 1 ] + buffer [ 12 + i ] [ 1 ] ) ) ; float i1 = ( filter [ 1 ] * ( buffer [ 1 + i ] [ 1 ] + buffer [ 11 + i ] [ 1 ] ) ) ; float i2 = ( filter [ 2 ] * ( buffer [ 2 + i ] [ 1 ] + buffer [ 10 + i ] [ 1 ] ) ) ; float i3 = ( filter [ 3 ] * ( buffer [ 3 + i ] [ 1 ] + buffer [ 9 + i ] [ 1 ] ) ) ; float i4 = ( filter [ 4 ] * ( buffer [ 4 + i ] [ 1 ] + buffer [ 8 + i ] [ 1 ] ) ) ; float i5 = ( filter [ 5 ] * ( buffer [ 5 + i ] [ 1 ] + buffer [ 7 + i ] [ 1 ] ) ) ; float i6 = ( filter [ 6 ] * buffer [ 6 + i ] [ 1 ] ) ; /* q = 0 */ X_hybrid [ i ] [ 0 ] [ 0 ] = r0 + r1 + r2 + r3 + r4 + r5 + r6 ; X_hybrid [ i ] [ 0 ] [ 1 ] = i0 + i1 + i2 + i3 + i4 + i5 + i6 ; /* q = 1 */ X_hybrid [ i ] [ 1 ] [ 0 ] = r0 - r1 + r2 - r3 + r4 - r5 + r6 ; X_hybrid [ i ] [ 1 ] [ 1 ] = i0 - i1 + i2 - i3 + i4 - i5 + i6 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * complex filter size 4 [CODESPLIT] static void channel_filter4 ( int frame_len , float [ ] filter , float [ ] [ ] buffer , float [ ] [ ] [ ] X_hybrid ) { int i ; float [ ] input_re1 = new float [ 2 ] , input_re2 = new float [ 2 ] ; float [ ] input_im1 = new float [ 2 ] , input_im2 = new float [ 2 ] ; for ( i = 0 ; i < frame_len ; i ++ ) { input_re1 [ 0 ] = - ( filter [ 2 ] * ( buffer [ i + 2 ] [ 0 ] + buffer [ i + 10 ] [ 0 ] ) ) + ( filter [ 6 ] * buffer [ i + 6 ] [ 0 ] ) ; input_re1 [ 1 ] = ( - 0.70710678118655f * ( ( filter [ 1 ] * ( buffer [ i + 1 ] [ 0 ] + buffer [ i + 11 ] [ 0 ] ) ) + ( filter [ 3 ] * ( buffer [ i + 3 ] [ 0 ] + buffer [ i + 9 ] [ 0 ] ) ) - ( filter [ 5 ] * ( buffer [ i + 5 ] [ 0 ] + buffer [ i + 7 ] [ 0 ] ) ) ) ) ; input_im1 [ 0 ] = ( filter [ 0 ] * ( buffer [ i + 0 ] [ 1 ] - buffer [ i + 12 ] [ 1 ] ) ) - ( filter [ 4 ] * ( buffer [ i + 4 ] [ 1 ] - buffer [ i + 8 ] [ 1 ] ) ) ; input_im1 [ 1 ] = ( 0.70710678118655f * ( ( filter [ 1 ] * ( buffer [ i + 1 ] [ 1 ] - buffer [ i + 11 ] [ 1 ] ) ) - ( filter [ 3 ] * ( buffer [ i + 3 ] [ 1 ] - buffer [ i + 9 ] [ 1 ] ) ) - ( filter [ 5 ] * ( buffer [ i + 5 ] [ 1 ] - buffer [ i + 7 ] [ 1 ] ) ) ) ) ; input_re2 [ 0 ] = ( filter [ 0 ] * ( buffer [ i + 0 ] [ 0 ] - buffer [ i + 12 ] [ 0 ] ) ) - ( filter [ 4 ] * ( buffer [ i + 4 ] [ 0 ] - buffer [ i + 8 ] [ 0 ] ) ) ; input_re2 [ 1 ] = ( 0.70710678118655f * ( ( filter [ 1 ] * ( buffer [ i + 1 ] [ 0 ] - buffer [ i + 11 ] [ 0 ] ) ) - ( filter [ 3 ] * ( buffer [ i + 3 ] [ 0 ] - buffer [ i + 9 ] [ 0 ] ) ) - ( filter [ 5 ] * ( buffer [ i + 5 ] [ 0 ] - buffer [ i + 7 ] [ 0 ] ) ) ) ) ; input_im2 [ 0 ] = - ( filter [ 2 ] * ( buffer [ i + 2 ] [ 1 ] + buffer [ i + 10 ] [ 1 ] ) ) + ( filter [ 6 ] * buffer [ i + 6 ] [ 1 ] ) ; input_im2 [ 1 ] = ( - 0.70710678118655f * ( ( filter [ 1 ] * ( buffer [ i + 1 ] [ 1 ] + buffer [ i + 11 ] [ 1 ] ) ) + ( filter [ 3 ] * ( buffer [ i + 3 ] [ 1 ] + buffer [ i + 9 ] [ 1 ] ) ) - ( filter [ 5 ] * ( buffer [ i + 5 ] [ 1 ] + buffer [ i + 7 ] [ 1 ] ) ) ) ) ; /* q == 0 */ X_hybrid [ i ] [ 0 ] [ 0 ] = input_re1 [ 0 ] + input_re1 [ 1 ] + input_im1 [ 0 ] + input_im1 [ 1 ] ; X_hybrid [ i ] [ 0 ] [ 1 ] = - input_re2 [ 0 ] - input_re2 [ 1 ] + input_im2 [ 0 ] + input_im2 [ 1 ] ; /* q == 1 */ X_hybrid [ i ] [ 1 ] [ 0 ] = input_re1 [ 0 ] - input_re1 [ 1 ] - input_im1 [ 0 ] + input_im1 [ 1 ] ; X_hybrid [ i ] [ 1 ] [ 1 ] = input_re2 [ 0 ] - input_re2 [ 1 ] + input_im2 [ 0 ] - input_im2 [ 1 ] ; /* q == 2 */ X_hybrid [ i ] [ 2 ] [ 0 ] = input_re1 [ 0 ] - input_re1 [ 1 ] + input_im1 [ 0 ] - input_im1 [ 1 ] ; X_hybrid [ i ] [ 2 ] [ 1 ] = - input_re2 [ 0 ] + input_re2 [ 1 ] + input_im2 [ 0 ] - input_im2 [ 1 ] ; /* q == 3 */ X_hybrid [ i ] [ 3 ] [ 0 ] = input_re1 [ 0 ] + input_re1 [ 1 ] - input_im1 [ 0 ] - input_im1 [ 1 ] ; X_hybrid [ i ] [ 3 ] [ 1 ] = input_re2 [ 0 ] + input_re2 [ 1 ] + input_im2 [ 0 ] + input_im2 [ 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * complex filter size 8 [CODESPLIT] void channel_filter8 ( int frame_len , float [ ] filter , float [ ] [ ] buffer , float [ ] [ ] [ ] X_hybrid ) { int i , n ; float [ ] input_re1 = new float [ 4 ] , input_re2 = new float [ 4 ] ; float [ ] input_im1 = new float [ 4 ] , input_im2 = new float [ 4 ] ; float [ ] x = new float [ 4 ] ; for ( i = 0 ; i < frame_len ; i ++ ) { input_re1 [ 0 ] = ( filter [ 6 ] * buffer [ 6 + i ] [ 0 ] ) ; input_re1 [ 1 ] = ( filter [ 5 ] * ( buffer [ 5 + i ] [ 0 ] + buffer [ 7 + i ] [ 0 ] ) ) ; input_re1 [ 2 ] = - ( filter [ 0 ] * ( buffer [ 0 + i ] [ 0 ] + buffer [ 12 + i ] [ 0 ] ) ) + ( filter [ 4 ] * ( buffer [ 4 + i ] [ 0 ] + buffer [ 8 + i ] [ 0 ] ) ) ; input_re1 [ 3 ] = - ( filter [ 1 ] * ( buffer [ 1 + i ] [ 0 ] + buffer [ 11 + i ] [ 0 ] ) ) + ( filter [ 3 ] * ( buffer [ 3 + i ] [ 0 ] + buffer [ 9 + i ] [ 0 ] ) ) ; input_im1 [ 0 ] = ( filter [ 5 ] * ( buffer [ 7 + i ] [ 1 ] - buffer [ 5 + i ] [ 1 ] ) ) ; input_im1 [ 1 ] = ( filter [ 0 ] * ( buffer [ 12 + i ] [ 1 ] - buffer [ 0 + i ] [ 1 ] ) ) + ( filter [ 4 ] * ( buffer [ 8 + i ] [ 1 ] - buffer [ 4 + i ] [ 1 ] ) ) ; input_im1 [ 2 ] = ( filter [ 1 ] * ( buffer [ 11 + i ] [ 1 ] - buffer [ 1 + i ] [ 1 ] ) ) + ( filter [ 3 ] * ( buffer [ 9 + i ] [ 1 ] - buffer [ 3 + i ] [ 1 ] ) ) ; input_im1 [ 3 ] = ( filter [ 2 ] * ( buffer [ 10 + i ] [ 1 ] - buffer [ 2 + i ] [ 1 ] ) ) ; for ( n = 0 ; n < 4 ; n ++ ) { x [ n ] = input_re1 [ n ] - input_im1 [ 3 - n ] ; } DCT3_4_unscaled ( x , x ) ; X_hybrid [ i ] [ 7 ] [ 0 ] = x [ 0 ] ; X_hybrid [ i ] [ 5 ] [ 0 ] = x [ 2 ] ; X_hybrid [ i ] [ 3 ] [ 0 ] = x [ 3 ] ; X_hybrid [ i ] [ 1 ] [ 0 ] = x [ 1 ] ; for ( n = 0 ; n < 4 ; n ++ ) { x [ n ] = input_re1 [ n ] + input_im1 [ 3 - n ] ; } DCT3_4_unscaled ( x , x ) ; X_hybrid [ i ] [ 6 ] [ 0 ] = x [ 1 ] ; X_hybrid [ i ] [ 4 ] [ 0 ] = x [ 3 ] ; X_hybrid [ i ] [ 2 ] [ 0 ] = x [ 2 ] ; X_hybrid [ i ] [ 0 ] [ 0 ] = x [ 0 ] ; input_im2 [ 0 ] = ( filter [ 6 ] * buffer [ 6 + i ] [ 1 ] ) ; input_im2 [ 1 ] = ( filter [ 5 ] * ( buffer [ 5 + i ] [ 1 ] + buffer [ 7 + i ] [ 1 ] ) ) ; input_im2 [ 2 ] = - ( filter [ 0 ] * ( buffer [ 0 + i ] [ 1 ] + buffer [ 12 + i ] [ 1 ] ) ) + ( filter [ 4 ] * ( buffer [ 4 + i ] [ 1 ] + buffer [ 8 + i ] [ 1 ] ) ) ; input_im2 [ 3 ] = - ( filter [ 1 ] * ( buffer [ 1 + i ] [ 1 ] + buffer [ 11 + i ] [ 1 ] ) ) + ( filter [ 3 ] * ( buffer [ 3 + i ] [ 1 ] + buffer [ 9 + i ] [ 1 ] ) ) ; input_re2 [ 0 ] = ( filter [ 5 ] * ( buffer [ 7 + i ] [ 0 ] - buffer [ 5 + i ] [ 0 ] ) ) ; input_re2 [ 1 ] = ( filter [ 0 ] * ( buffer [ 12 + i ] [ 0 ] - buffer [ 0 + i ] [ 0 ] ) ) + ( filter [ 4 ] * ( buffer [ 8 + i ] [ 0 ] - buffer [ 4 + i ] [ 0 ] ) ) ; input_re2 [ 2 ] = ( filter [ 1 ] * ( buffer [ 11 + i ] [ 0 ] - buffer [ 1 + i ] [ 0 ] ) ) + ( filter [ 3 ] * ( buffer [ 9 + i ] [ 0 ] - buffer [ 3 + i ] [ 0 ] ) ) ; input_re2 [ 3 ] = ( filter [ 2 ] * ( buffer [ 10 + i ] [ 0 ] - buffer [ 2 + i ] [ 0 ] ) ) ; for ( n = 0 ; n < 4 ; n ++ ) { x [ n ] = input_im2 [ n ] + input_re2 [ 3 - n ] ; } DCT3_4_unscaled ( x , x ) ; X_hybrid [ i ] [ 7 ] [ 1 ] = x [ 0 ] ; X_hybrid [ i ] [ 5 ] [ 1 ] = x [ 2 ] ; X_hybrid [ i ] [ 3 ] [ 1 ] = x [ 3 ] ; X_hybrid [ i ] [ 1 ] [ 1 ] = x [ 1 ] ; for ( n = 0 ; n < 4 ; n ++ ) { x [ n ] = input_im2 [ n ] - input_re2 [ 3 - n ] ; } DCT3_4_unscaled ( x , x ) ; X_hybrid [ i ] [ 6 ] [ 1 ] = x [ 1 ] ; X_hybrid [ i ] [ 4 ] [ 1 ] = x [ 3 ] ; X_hybrid [ i ] [ 2 ] [ 1 ] = x [ 2 ] ; X_hybrid [ i ] [ 0 ] [ 1 ] = x [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * complex filter size 12 [CODESPLIT] void channel_filter12 ( int frame_len , float [ ] filter , float [ ] [ ] buffer , float [ ] [ ] [ ] X_hybrid ) { int i , n ; float [ ] input_re1 = new float [ 6 ] , input_re2 = new float [ 6 ] ; float [ ] input_im1 = new float [ 6 ] , input_im2 = new float [ 6 ] ; float [ ] out_re1 = new float [ 6 ] , out_re2 = new float [ 6 ] ; float [ ] out_im1 = new float [ 6 ] , out_im2 = new float [ 6 ] ; for ( i = 0 ; i < frame_len ; i ++ ) { for ( n = 0 ; n < 6 ; n ++ ) { if ( n == 0 ) { input_re1 [ 0 ] = ( buffer [ 6 + i ] [ 0 ] * filter [ 6 ] ) ; input_re2 [ 0 ] = ( buffer [ 6 + i ] [ 1 ] * filter [ 6 ] ) ; } else { input_re1 [ 6 - n ] = ( ( buffer [ n + i ] [ 0 ] + buffer [ 12 - n + i ] [ 0 ] ) * filter [ n ] ) ; input_re2 [ 6 - n ] = ( ( buffer [ n + i ] [ 1 ] + buffer [ 12 - n + i ] [ 1 ] ) * filter [ n ] ) ; } input_im2 [ n ] = ( ( buffer [ n + i ] [ 0 ] - buffer [ 12 - n + i ] [ 0 ] ) * filter [ n ] ) ; input_im1 [ n ] = ( ( buffer [ n + i ] [ 1 ] - buffer [ 12 - n + i ] [ 1 ] ) * filter [ n ] ) ; } DCT3_6_unscaled ( out_re1 , input_re1 ) ; DCT3_6_unscaled ( out_re2 , input_re2 ) ; DCT3_6_unscaled ( out_im1 , input_im1 ) ; DCT3_6_unscaled ( out_im2 , input_im2 ) ; for ( n = 0 ; n < 6 ; n += 2 ) { X_hybrid [ i ] [ n ] [ 0 ] = out_re1 [ n ] - out_im1 [ n ] ; X_hybrid [ i ] [ n ] [ 1 ] = out_re2 [ n ] + out_im2 [ n ] ; X_hybrid [ i ] [ n + 1 ] [ 0 ] = out_re1 [ n + 1 ] + out_im1 [ n + 1 ] ; X_hybrid [ i ] [ n + 1 ] [ 1 ] = out_re2 [ n + 1 ] - out_im2 [ n + 1 ] ; X_hybrid [ i ] [ 10 - n ] [ 0 ] = out_re1 [ n + 1 ] - out_im1 [ n + 1 ] ; X_hybrid [ i ] [ 10 - n ] [ 1 ] = out_re2 [ n + 1 ] + out_im2 [ n + 1 ] ; X_hybrid [ i ] [ 11 - n ] [ 0 ] = out_re1 [ n ] + out_im1 [ n ] ; X_hybrid [ i ] [ 11 - n ] [ 1 ] = out_re2 [ n ] - out_im2 [ n ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * read huffman data coded in either the frequency or the time direction [CODESPLIT] private void huff_data ( IBitStream ld , boolean dt , int nr_par , int [ ] [ ] t_huff , int [ ] [ ] f_huff , int [ ] par ) throws AACException { int n ; if ( dt ) { /* coded in time direction */ for ( n = 0 ; n < nr_par ; n ++ ) { par [ n ] = ps_huff_dec ( ld , t_huff ) ; } } else { /* coded in frequency direction */ par [ 0 ] = ps_huff_dec ( ld , f_huff ) ; for ( n = 1 ; n < nr_par ; n ++ ) { par [ n ] = ps_huff_dec ( ld , f_huff ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * binary search huffman decoding [CODESPLIT] private int ps_huff_dec ( IBitStream ld , int [ ] [ ] t_huff ) throws AACException { int bit ; int index = 0 ; while ( index >= 0 ) { bit = ld . readBit ( ) ; index = t_huff [ index ] [ bit ] ; } return index + 31 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * limits the value i to the range [ min max ] [CODESPLIT] private int delta_clip ( int i , int min , int max ) { if ( i < min ) return min ; else if ( i > max ) return max ; else return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * delta decode array [CODESPLIT] private void delta_decode ( boolean enable , int [ ] index , int [ ] index_prev , boolean dt_flag , int nr_par , int stride , int min_index , int max_index ) { int i ; if ( enable ) { if ( ! dt_flag ) { /* delta coded in frequency direction */ index [ 0 ] = 0 + index [ 0 ] ; index [ 0 ] = delta_clip ( index [ 0 ] , min_index , max_index ) ; for ( i = 1 ; i < nr_par ; i ++ ) { index [ i ] = index [ i - 1 ] + index [ i ] ; index [ i ] = delta_clip ( index [ i ] , min_index , max_index ) ; } } else { /* delta coded in time direction */ for ( i = 0 ; i < nr_par ; i ++ ) { //int8_t tmp2; //int8_t tmp = index[i]; //printf(\"%d %d\\n\", index_prev[i*stride], index[i]); //printf(\"%d\\n\", index[i]); index [ i ] = index_prev [ i * stride ] + index [ i ] ; //tmp2 = index[i]; index [ i ] = delta_clip ( index [ i ] , min_index , max_index ) ; //if (iid) //{ //    if (index[i] == 7) //    { //        printf(\"%d %d %d\\n\", index_prev[i*stride], tmp, tmp2); //    } //} } } } else { /* set indices to zero */ for ( i = 0 ; i < nr_par ; i ++ ) { index [ i ] = 0 ; } } /* coarse */ if ( stride == 2 ) { for ( i = ( nr_par << 1 ) - 1 ; i > 0 ; i -- ) { index [ i ] = index [ i >> 1 ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * in : log2 value of the modulo value to allow using AND instead of MOD [CODESPLIT] private void delta_modulo_decode ( boolean enable , int [ ] index , int [ ] index_prev , boolean dt_flag , int nr_par , int stride , int and_modulo ) { int i ; if ( enable ) { if ( ! dt_flag ) { /* delta coded in frequency direction */ index [ 0 ] = 0 + index [ 0 ] ; index [ 0 ] &= and_modulo ; for ( i = 1 ; i < nr_par ; i ++ ) { index [ i ] = index [ i - 1 ] + index [ i ] ; index [ i ] &= and_modulo ; } } else { /* delta coded in time direction */ for ( i = 0 ; i < nr_par ; i ++ ) { index [ i ] = index_prev [ i * stride ] + index [ i ] ; index [ i ] &= and_modulo ; } } } else { /* set indices to zero */ for ( i = 0 ; i < nr_par ; i ++ ) { index [ i ] = 0 ; } } /* coarse */ if ( stride == 2 ) { index [ 0 ] = 0 ; for ( i = ( nr_par << 1 ) - 1 ; i > 0 ; i -- ) { index [ i ] = index [ i >> 1 ] ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * parse the bitstream data decoded in ps_data () [CODESPLIT] private void ps_data_decode ( ) { int env , bin ; /* ps data not available, use data from previous frame */ if ( this . ps_data_available == 0 ) { this . num_env = 0 ; } for ( env = 0 ; env < this . num_env ; env ++ ) { int [ ] iid_index_prev ; int [ ] icc_index_prev ; int [ ] ipd_index_prev ; int [ ] opd_index_prev ; int num_iid_steps = ( this . iid_mode < 3 ) ? 7 : 15 /*fine quant*/ ; if ( env == 0 ) { /* take last envelope from previous frame */ iid_index_prev = this . iid_index_prev ; icc_index_prev = this . icc_index_prev ; ipd_index_prev = this . ipd_index_prev ; opd_index_prev = this . opd_index_prev ; } else { /* take index values from previous envelope */ iid_index_prev = this . iid_index [ env - 1 ] ; icc_index_prev = this . icc_index [ env - 1 ] ; ipd_index_prev = this . ipd_index [ env - 1 ] ; opd_index_prev = this . opd_index [ env - 1 ] ; } //        iid = 1; /* delta decode iid parameters */ delta_decode ( this . enable_iid , this . iid_index [ env ] , iid_index_prev , this . iid_dt [ env ] , this . nr_iid_par , ( this . iid_mode == 0 || this . iid_mode == 3 ) ? 2 : 1 , - num_iid_steps , num_iid_steps ) ; //        iid = 0; /* delta decode icc parameters */ delta_decode ( this . enable_icc , this . icc_index [ env ] , icc_index_prev , this . icc_dt [ env ] , this . nr_icc_par , ( this . icc_mode == 0 || this . icc_mode == 3 ) ? 2 : 1 , 0 , 7 ) ; /* delta modulo decode ipd parameters */ delta_modulo_decode ( this . enable_ipdopd , this . ipd_index [ env ] , ipd_index_prev , this . ipd_dt [ env ] , this . nr_ipdopd_par , 1 , 7 ) ; /* delta modulo decode opd parameters */ delta_modulo_decode ( this . enable_ipdopd , this . opd_index [ env ] , opd_index_prev , this . opd_dt [ env ] , this . nr_ipdopd_par , 1 , 7 ) ; } /* handle error case */ if ( this . num_env == 0 ) { /* force to 1 */ this . num_env = 1 ; if ( this . enable_iid ) { for ( bin = 0 ; bin < 34 ; bin ++ ) { this . iid_index [ 0 ] [ bin ] = this . iid_index_prev [ bin ] ; } } else { for ( bin = 0 ; bin < 34 ; bin ++ ) { this . iid_index [ 0 ] [ bin ] = 0 ; } } if ( this . enable_icc ) { for ( bin = 0 ; bin < 34 ; bin ++ ) { this . icc_index [ 0 ] [ bin ] = this . icc_index_prev [ bin ] ; } } else { for ( bin = 0 ; bin < 34 ; bin ++ ) { this . icc_index [ 0 ] [ bin ] = 0 ; } } if ( this . enable_ipdopd ) { for ( bin = 0 ; bin < 17 ; bin ++ ) { this . ipd_index [ 0 ] [ bin ] = this . ipd_index_prev [ bin ] ; this . opd_index [ 0 ] [ bin ] = this . opd_index_prev [ bin ] ; } } else { for ( bin = 0 ; bin < 17 ; bin ++ ) { this . ipd_index [ 0 ] [ bin ] = 0 ; this . opd_index [ 0 ] [ bin ] = 0 ; } } } /* update previous indices */ for ( bin = 0 ; bin < 34 ; bin ++ ) { this . iid_index_prev [ bin ] = this . iid_index [ this . num_env - 1 ] [ bin ] ; } for ( bin = 0 ; bin < 34 ; bin ++ ) { this . icc_index_prev [ bin ] = this . icc_index [ this . num_env - 1 ] [ bin ] ; } for ( bin = 0 ; bin < 17 ; bin ++ ) { this . ipd_index_prev [ bin ] = this . ipd_index [ this . num_env - 1 ] [ bin ] ; this . opd_index_prev [ bin ] = this . opd_index [ this . num_env - 1 ] [ bin ] ; } this . ps_data_available = 0 ; if ( this . frame_class == 0 ) { this . border_position [ 0 ] = 0 ; for ( env = 1 ; env < this . num_env ; env ++ ) { this . border_position [ env ] = ( env * this . numTimeSlotsRate ) / this . num_env ; } this . border_position [ this . num_env ] = this . numTimeSlotsRate ; } else { this . border_position [ 0 ] = 0 ; if ( this . border_position [ this . num_env ] < this . numTimeSlotsRate ) { for ( bin = 0 ; bin < 34 ; bin ++ ) { this . iid_index [ this . num_env ] [ bin ] = this . iid_index [ this . num_env - 1 ] [ bin ] ; this . icc_index [ this . num_env ] [ bin ] = this . icc_index [ this . num_env - 1 ] [ bin ] ; } for ( bin = 0 ; bin < 17 ; bin ++ ) { this . ipd_index [ this . num_env ] [ bin ] = this . ipd_index [ this . num_env - 1 ] [ bin ] ; this . opd_index [ this . num_env ] [ bin ] = this . opd_index [ this . num_env - 1 ] [ bin ] ; } this . num_env ++ ; this . border_position [ this . num_env ] = this . numTimeSlotsRate ; } for ( env = 1 ; env < this . num_env ; env ++ ) { int thr = this . numTimeSlotsRate - ( this . num_env - env ) ; if ( this . border_position [ env ] > thr ) { this . border_position [ env ] = thr ; } else { thr = this . border_position [ env - 1 ] + 1 ; if ( this . border_position [ env ] < thr ) { this . border_position [ env ] = thr ; } } } } /* make sure that the indices of all parameters can be mapped\n\t\t * to the same hybrid synthesis filterbank\n\t\t */ if ( this . use34hybrid_bands ) { for ( env = 0 ; env < this . num_env ; env ++ ) { if ( this . iid_mode != 2 && this . iid_mode != 5 ) map20indexto34 ( this . iid_index [ env ] , 34 ) ; if ( this . icc_mode != 2 && this . icc_mode != 5 ) map20indexto34 ( this . icc_index [ env ] , 34 ) ; if ( this . ipd_mode != 2 && this . ipd_mode != 5 ) { map20indexto34 ( this . ipd_index [ env ] , 17 ) ; map20indexto34 ( this . opd_index [ env ] , 17 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * decorrelate the mono signal using an allpass filter [CODESPLIT] private void ps_decorrelate ( float [ ] [ ] [ ] X_left , float [ ] [ ] [ ] X_right , float [ ] [ ] [ ] X_hybrid_left , float [ ] [ ] [ ] X_hybrid_right ) { int gr , n , m , bk ; int temp_delay = 0 ; int sb , maxsb ; int [ ] temp_delay_ser = new int [ NO_ALLPASS_LINKS ] ; float P_SmoothPeakDecayDiffNrg , nrg ; float [ ] [ ] P = new float [ 32 ] [ 34 ] ; float [ ] [ ] G_TransientRatio = new float [ 32 ] [ 34 ] ; float [ ] inputLeft = new float [ 2 ] ; /* chose hybrid filterbank: 20 or 34 band case */ float [ ] [ ] Phi_Fract_SubQmf ; if ( this . use34hybrid_bands ) { Phi_Fract_SubQmf = Phi_Fract_SubQmf34 ; } else { Phi_Fract_SubQmf = Phi_Fract_SubQmf20 ; } /* clear the energy values */ for ( n = 0 ; n < 32 ; n ++ ) { for ( bk = 0 ; bk < 34 ; bk ++ ) { P [ n ] [ bk ] = 0 ; } } /* calculate the energy in each parameter band b(k) */ for ( gr = 0 ; gr < this . num_groups ; gr ++ ) { /* select the parameter index b(k) to which this group belongs */ bk = ( ~ NEGATE_IPD_MASK ) & this . map_group2bk [ gr ] ; /* select the upper subband border for this group */ maxsb = ( gr < this . num_hybrid_groups ) ? this . group_border [ gr ] + 1 : this . group_border [ gr + 1 ] ; for ( sb = this . group_border [ gr ] ; sb < maxsb ; sb ++ ) { for ( n = this . border_position [ 0 ] ; n < this . border_position [ this . num_env ] ; n ++ ) { /* input from hybrid subbands or QMF subbands */ if ( gr < this . num_hybrid_groups ) { inputLeft [ 0 ] = X_hybrid_left [ n ] [ sb ] [ 0 ] ; inputLeft [ 1 ] = X_hybrid_left [ n ] [ sb ] [ 1 ] ; } else { inputLeft [ 0 ] = X_left [ n ] [ sb ] [ 0 ] ; inputLeft [ 1 ] = X_left [ n ] [ sb ] [ 1 ] ; } /* accumulate energy */ P [ n ] [ bk ] += ( inputLeft [ 0 ] * inputLeft [ 0 ] ) + ( inputLeft [ 1 ] * inputLeft [ 1 ] ) ; } } } /* calculate transient reduction ratio for each parameter band b(k) */ for ( bk = 0 ; bk < this . nr_par_bands ; bk ++ ) { for ( n = this . border_position [ 0 ] ; n < this . border_position [ this . num_env ] ; n ++ ) { float gamma = 1.5f ; this . P_PeakDecayNrg [ bk ] = ( this . P_PeakDecayNrg [ bk ] * this . alpha_decay ) ; if ( this . P_PeakDecayNrg [ bk ] < P [ n ] [ bk ] ) this . P_PeakDecayNrg [ bk ] = P [ n ] [ bk ] ; /* apply smoothing filter to peak decay energy */ P_SmoothPeakDecayDiffNrg = this . P_SmoothPeakDecayDiffNrg_prev [ bk ] ; P_SmoothPeakDecayDiffNrg += ( ( this . P_PeakDecayNrg [ bk ] - P [ n ] [ bk ] - this . P_SmoothPeakDecayDiffNrg_prev [ bk ] ) * alpha_smooth ) ; this . P_SmoothPeakDecayDiffNrg_prev [ bk ] = P_SmoothPeakDecayDiffNrg ; /* apply smoothing filter to energy */ nrg = this . P_prev [ bk ] ; nrg += ( ( P [ n ] [ bk ] - this . P_prev [ bk ] ) * this . alpha_smooth ) ; this . P_prev [ bk ] = nrg ; /* calculate transient ratio */ if ( ( P_SmoothPeakDecayDiffNrg * gamma ) <= nrg ) { G_TransientRatio [ n ] [ bk ] = 1.0f ; } else { G_TransientRatio [ n ] [ bk ] = ( nrg / ( P_SmoothPeakDecayDiffNrg * gamma ) ) ; } } } /* apply stereo decorrelation filter to the signal */ for ( gr = 0 ; gr < this . num_groups ; gr ++ ) { if ( gr < this . num_hybrid_groups ) maxsb = this . group_border [ gr ] + 1 ; else maxsb = this . group_border [ gr + 1 ] ; /* QMF channel */ for ( sb = this . group_border [ gr ] ; sb < maxsb ; sb ++ ) { float g_DecaySlope ; float [ ] g_DecaySlope_filt = new float [ NO_ALLPASS_LINKS ] ; /* g_DecaySlope: [0..1] */ if ( gr < this . num_hybrid_groups || sb <= this . decay_cutoff ) { g_DecaySlope = 1.0f ; } else { int decay = this . decay_cutoff - sb ; if ( decay <= - 20 /* -1/DECAY_SLOPE */ ) { g_DecaySlope = 0 ; } else { /* decay(int)*decay_slope(frac) = g_DecaySlope(frac) */ g_DecaySlope = 1.0f + DECAY_SLOPE * decay ; } } /* calculate g_DecaySlope_filt for every m multiplied by filter_a[m] */ for ( m = 0 ; m < NO_ALLPASS_LINKS ; m ++ ) { g_DecaySlope_filt [ m ] = g_DecaySlope * filter_a [ m ] ; } /* set delay indices */ temp_delay = this . saved_delay ; for ( n = 0 ; n < NO_ALLPASS_LINKS ; n ++ ) { temp_delay_ser [ n ] = this . delay_buf_index_ser [ n ] ; } for ( n = this . border_position [ 0 ] ; n < this . border_position [ this . num_env ] ; n ++ ) { float [ ] tmp = new float [ 2 ] , tmp0 = new float [ 2 ] , R0 = new float [ 2 ] ; if ( gr < this . num_hybrid_groups ) { /* hybrid filterbank input */ inputLeft [ 0 ] = X_hybrid_left [ n ] [ sb ] [ 0 ] ; inputLeft [ 1 ] = X_hybrid_left [ n ] [ sb ] [ 1 ] ; } else { /* QMF filterbank input */ inputLeft [ 0 ] = X_left [ n ] [ sb ] [ 0 ] ; inputLeft [ 1 ] = X_left [ n ] [ sb ] [ 1 ] ; } if ( sb > this . nr_allpass_bands && gr >= this . num_hybrid_groups ) { /* delay */ /* never hybrid subbands here, always QMF subbands */ tmp [ 0 ] = this . delay_Qmf [ this . delay_buf_index_delay [ sb ] ] [ sb ] [ 0 ] ; tmp [ 1 ] = this . delay_Qmf [ this . delay_buf_index_delay [ sb ] ] [ sb ] [ 1 ] ; R0 [ 0 ] = tmp [ 0 ] ; R0 [ 1 ] = tmp [ 1 ] ; this . delay_Qmf [ this . delay_buf_index_delay [ sb ] ] [ sb ] [ 0 ] = inputLeft [ 0 ] ; this . delay_Qmf [ this . delay_buf_index_delay [ sb ] ] [ sb ] [ 1 ] = inputLeft [ 1 ] ; } else { /* allpass filter */ //int m; float [ ] Phi_Fract = new float [ 2 ] ; /* fetch parameters */ if ( gr < this . num_hybrid_groups ) { /* select data from the hybrid subbands */ tmp0 [ 0 ] = this . delay_SubQmf [ temp_delay ] [ sb ] [ 0 ] ; tmp0 [ 1 ] = this . delay_SubQmf [ temp_delay ] [ sb ] [ 1 ] ; this . delay_SubQmf [ temp_delay ] [ sb ] [ 0 ] = inputLeft [ 0 ] ; this . delay_SubQmf [ temp_delay ] [ sb ] [ 1 ] = inputLeft [ 1 ] ; Phi_Fract [ 0 ] = Phi_Fract_SubQmf [ sb ] [ 0 ] ; Phi_Fract [ 1 ] = Phi_Fract_SubQmf [ sb ] [ 1 ] ; } else { /* select data from the QMF subbands */ tmp0 [ 0 ] = this . delay_Qmf [ temp_delay ] [ sb ] [ 0 ] ; tmp0 [ 1 ] = this . delay_Qmf [ temp_delay ] [ sb ] [ 1 ] ; this . delay_Qmf [ temp_delay ] [ sb ] [ 0 ] = inputLeft [ 0 ] ; this . delay_Qmf [ temp_delay ] [ sb ] [ 1 ] = inputLeft [ 1 ] ; Phi_Fract [ 0 ] = Phi_Fract_Qmf [ sb ] [ 0 ] ; Phi_Fract [ 1 ] = Phi_Fract_Qmf [ sb ] [ 1 ] ; } /* z^(-2) * Phi_Fract[k] */ tmp [ 0 ] = ( tmp [ 0 ] * Phi_Fract [ 0 ] ) + ( tmp0 [ 1 ] * Phi_Fract [ 1 ] ) ; tmp [ 1 ] = ( tmp0 [ 1 ] * Phi_Fract [ 0 ] ) - ( tmp0 [ 0 ] * Phi_Fract [ 1 ] ) ; R0 [ 0 ] = tmp [ 0 ] ; R0 [ 1 ] = tmp [ 1 ] ; for ( m = 0 ; m < NO_ALLPASS_LINKS ; m ++ ) { float [ ] Q_Fract_allpass = new float [ 2 ] , tmp2 = new float [ 2 ] ; /* fetch parameters */ if ( gr < this . num_hybrid_groups ) { /* select data from the hybrid subbands */ tmp0 [ 0 ] = this . delay_SubQmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 0 ] ; tmp0 [ 1 ] = this . delay_SubQmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 1 ] ; if ( this . use34hybrid_bands ) { Q_Fract_allpass [ 0 ] = Q_Fract_allpass_SubQmf34 [ sb ] [ m ] [ 0 ] ; Q_Fract_allpass [ 1 ] = Q_Fract_allpass_SubQmf34 [ sb ] [ m ] [ 1 ] ; } else { Q_Fract_allpass [ 0 ] = Q_Fract_allpass_SubQmf20 [ sb ] [ m ] [ 0 ] ; Q_Fract_allpass [ 1 ] = Q_Fract_allpass_SubQmf20 [ sb ] [ m ] [ 1 ] ; } } else { /* select data from the QMF subbands */ tmp0 [ 0 ] = this . delay_Qmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 0 ] ; tmp0 [ 1 ] = this . delay_Qmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 1 ] ; Q_Fract_allpass [ 0 ] = Q_Fract_allpass_Qmf [ sb ] [ m ] [ 0 ] ; Q_Fract_allpass [ 1 ] = Q_Fract_allpass_Qmf [ sb ] [ m ] [ 1 ] ; } /* delay by a fraction */ /* z^(-d(m)) * Q_Fract_allpass[k,m] */ tmp [ 0 ] = ( tmp0 [ 0 ] * Q_Fract_allpass [ 0 ] ) + ( tmp0 [ 1 ] * Q_Fract_allpass [ 1 ] ) ; tmp [ 1 ] = ( tmp0 [ 1 ] * Q_Fract_allpass [ 0 ] ) - ( tmp0 [ 0 ] * Q_Fract_allpass [ 1 ] ) ; /* -a(m) * g_DecaySlope[k] */ tmp [ 0 ] += - ( g_DecaySlope_filt [ m ] * R0 [ 0 ] ) ; tmp [ 1 ] += - ( g_DecaySlope_filt [ m ] * R0 [ 1 ] ) ; /* -a(m) * g_DecaySlope[k] * Q_Fract_allpass[k,m] * z^(-d(m)) */ tmp2 [ 0 ] = R0 [ 0 ] + ( g_DecaySlope_filt [ m ] * tmp [ 0 ] ) ; tmp2 [ 1 ] = R0 [ 1 ] + ( g_DecaySlope_filt [ m ] * tmp [ 1 ] ) ; /* store sample */ if ( gr < this . num_hybrid_groups ) { this . delay_SubQmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 0 ] = tmp2 [ 0 ] ; this . delay_SubQmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 1 ] = tmp2 [ 1 ] ; } else { this . delay_Qmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 0 ] = tmp2 [ 0 ] ; this . delay_Qmf_ser [ m ] [ temp_delay_ser [ m ] ] [ sb ] [ 1 ] = tmp2 [ 1 ] ; } /* store for next iteration (or as output value if last iteration) */ R0 [ 0 ] = tmp [ 0 ] ; R0 [ 1 ] = tmp [ 1 ] ; } } /* select b(k) for reading the transient ratio */ bk = ( ~ NEGATE_IPD_MASK ) & this . map_group2bk [ gr ] ; /* duck if a past transient is found */ R0 [ 0 ] = ( G_TransientRatio [ n ] [ bk ] * R0 [ 0 ] ) ; R0 [ 1 ] = ( G_TransientRatio [ n ] [ bk ] * R0 [ 1 ] ) ; if ( gr < this . num_hybrid_groups ) { /* hybrid */ X_hybrid_right [ n ] [ sb ] [ 0 ] = R0 [ 0 ] ; X_hybrid_right [ n ] [ sb ] [ 1 ] = R0 [ 1 ] ; } else { /* QMF */ X_right [ n ] [ sb ] [ 0 ] = R0 [ 0 ] ; X_right [ n ] [ sb ] [ 1 ] = R0 [ 1 ] ; } /* Update delay buffer index */ if ( ++ temp_delay >= 2 ) { temp_delay = 0 ; } /* update delay indices */ if ( sb > this . nr_allpass_bands && gr >= this . num_hybrid_groups ) { /* delay_D depends on the samplerate, it can hold the values 14 and 1 */ if ( ++ this . delay_buf_index_delay [ sb ] >= this . delay_D [ sb ] ) { this . delay_buf_index_delay [ sb ] = 0 ; } } for ( m = 0 ; m < NO_ALLPASS_LINKS ; m ++ ) { if ( ++ temp_delay_ser [ m ] >= this . num_sample_delay_ser [ m ] ) { temp_delay_ser [ m ] = 0 ; } } } } } /* update delay indices */ this . saved_delay = temp_delay ; for ( m = 0 ; m < NO_ALLPASS_LINKS ; m ++ ) { this . delay_buf_index_ser [ m ] = temp_delay_ser [ m ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * main Parametric Stereo decoding function [CODESPLIT] public int process ( float [ ] [ ] [ ] X_left , float [ ] [ ] [ ] X_right ) { float [ ] [ ] [ ] X_hybrid_left = new float [ 32 ] [ 32 ] [ 2 ] ; float [ ] [ ] [ ] X_hybrid_right = new float [ 32 ] [ 32 ] [ 2 ] ; /* delta decoding of the bitstream data */ ps_data_decode ( ) ; /* set up some parameters depending on filterbank type */ if ( this . use34hybrid_bands ) { this . group_border = group_border34 ; this . map_group2bk = map_group2bk34 ; this . num_groups = 32 + 18 ; this . num_hybrid_groups = 32 ; this . nr_par_bands = 34 ; this . decay_cutoff = 5 ; } else { this . group_border = group_border20 ; this . map_group2bk = map_group2bk20 ; this . num_groups = 10 + 12 ; this . num_hybrid_groups = 10 ; this . nr_par_bands = 20 ; this . decay_cutoff = 3 ; } /* Perform further analysis on the lowest subbands to get a higher\n\t\t * frequency resolution\n\t\t */ hyb . hybrid_analysis ( X_left , X_hybrid_left , this . use34hybrid_bands , this . numTimeSlotsRate ) ; /* decorrelate mono signal */ ps_decorrelate ( X_left , X_right , X_hybrid_left , X_hybrid_right ) ; /* apply mixing and phase parameters */ ps_mix_phase ( X_left , X_right , X_hybrid_left , X_hybrid_right ) ; /* hybrid synthesis, to rebuild the SBR QMF matrices */ hyb . hybrid_synthesis ( X_left , X_hybrid_left , this . use34hybrid_bands , this . numTimeSlotsRate ) ; hyb . hybrid_synthesis ( X_right , X_hybrid_right , this . use34hybrid_bands , this . numTimeSlotsRate ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a sample frequency instance for the given index . If the index is not between 0 and 11 inclusive SAMPLE_FREQUENCY_NONE is returned . [CODESPLIT] public static SampleFrequency forInt ( int i ) { final SampleFrequency freq ; if ( i >= 0 && i < 12 ) freq = values ( ) [ i ] ; else freq = SAMPLE_FREQUENCY_NONE ; return freq ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this may be a result of color greening out in long GOPs . [CODESPLIT] @ Override public void predictPlane ( byte [ ] ref , int refX , int refY , int refW , int refH , int refVertStep , int refVertOff , int [ ] tgt , int tgtY , int tgtW , int tgtH , int tgtVertStep ) { super . predictPlane ( ref , refX << 1 , refY << 1 , refW , refH , refVertStep , refVertOff , tgt , tgtY , tgtW << 2 , tgtH << 2 , tgtVertStep ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a cropped clone of this picture . [CODESPLIT] public Picture cloneCropped ( ) { if ( cropNeeded ( ) ) { return cropped ( ) ; } else { Picture clone = createCompatible ( ) ; clone . copyFrom ( this ) ; return clone ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sectionDataResilience = hDecoder - > aacSectionDataResilienceFlag [CODESPLIT] public static void decodeReorderedSpectralData ( ICStream ics , IBitStream _in , short [ ] spectralData , boolean sectionDataResilience ) throws AACException { final ICSInfo info = ics . getInfo ( ) ; final int windowGroupCount = info . getWindowGroupCount ( ) ; final int maxSFB = info . getMaxSFB ( ) ; final int [ ] swbOffsets = info . getSWBOffsets ( ) ; final int swbOffsetMax = info . getSWBOffsetMax ( ) ; //TODO: //final SectionData sectData = ics.getSectionData(); final int [ ] [ ] sectStart = new int [ 0 ] [ 0 ] ; //sectData.getSectStart(); final int [ ] [ ] sectEnd = new int [ 0 ] [ 0 ] ; //sectData.getSectEnd(); final int [ ] numSec = new int [ 0 ] ; //sectData.getNumSec(); final int [ ] [ ] sectCB = new int [ 0 ] [ 0 ] ; //sectData.getSectCB(); final int [ ] [ ] sectSFBOffsets = new int [ 0 ] [ 0 ] ; //info.getSectSFBOffsets(); //check parameter final int spDataLen = ics . getReorderedSpectralDataLength ( ) ; if ( spDataLen == 0 ) return ; final int longestLen = ics . getLongestCodewordLength ( ) ; if ( longestLen == 0 || longestLen >= spDataLen ) throw new AACException ( \"length of longest HCR codeword out of range\" ) ; //create spOffsets final int [ ] spOffsets = new int [ 8 ] ; final int shortFrameLen = spectralData . length / 8 ; spOffsets [ 0 ] = 0 ; int g ; for ( g = 1 ; g < windowGroupCount ; g ++ ) { spOffsets [ g ] = spOffsets [ g - 1 ] + shortFrameLen * info . getWindowGroupLength ( g - 1 ) ; } final Codeword [ ] codeword = new Codeword [ 512 ] ; final BitsBuffer [ ] segment = new BitsBuffer [ 512 ] ; int lastCB ; int [ ] preSortCB ; if ( sectionDataResilience ) { preSortCB = PRE_SORT_CB_ER ; lastCB = NUM_CB_ER ; } else { preSortCB = PRE_SORT_CB_STD ; lastCB = NUM_CB ; } int PCWs_done = 0 ; int segmentsCount = 0 ; int numberOfCodewords = 0 ; int bitsread = 0 ; int sfb , w_idx , i , thisCB , thisSectCB , cws ; //step 1: decode PCW's (set 0), and stuff data in easier-to-use format for ( int sortloop = 0 ; sortloop < lastCB ; sortloop ++ ) { //select codebook to process this pass thisCB = preSortCB [ sortloop ] ; for ( sfb = 0 ; sfb < maxSFB ; sfb ++ ) { for ( w_idx = 0 ; 4 * w_idx < ( Math . min ( swbOffsets [ sfb + 1 ] , swbOffsetMax ) - swbOffsets [ sfb ] ) ; w_idx ++ ) { for ( g = 0 ; g < windowGroupCount ; g ++ ) { for ( i = 0 ; i < numSec [ g ] ; i ++ ) { if ( ( sectStart [ g ] [ i ] <= sfb ) && ( sectEnd [ g ] [ i ] > sfb ) ) { /* check whether codebook used here is the one we want to process */ thisSectCB = sectCB [ g ] [ i ] ; if ( isGoodCB ( thisCB , thisSectCB ) ) { //precalculation int sect_sfb_size = sectSFBOffsets [ g ] [ sfb + 1 ] - sectSFBOffsets [ g ] [ sfb ] ; int inc = ( thisSectCB < HCB . FIRST_PAIR_HCB ) ? 4 : 2 ; int group_cws_count = ( 4 * info . getWindowGroupLength ( g ) ) / inc ; int segwidth = Math . min ( MAX_CW_LEN [ thisSectCB ] , longestLen ) ; //read codewords until end of sfb or end of window group for ( cws = 0 ; ( cws < group_cws_count ) && ( ( cws + w_idx * group_cws_count ) < sect_sfb_size ) ; cws ++ ) { int sp = spOffsets [ g ] + sectSFBOffsets [ g ] [ sfb ] + inc * ( cws + w_idx * group_cws_count ) ; //read and decode PCW if ( PCWs_done == 0 ) { //read in normal segments if ( bitsread + segwidth <= spDataLen ) { segment [ segmentsCount ] . readSegment ( segwidth , _in ) ; bitsread += segwidth ; //Huffman.decodeSpectralDataER(segment[segmentsCount], thisSectCB, spectralData, sp); //keep leftover bits segment [ segmentsCount ] . rewindReverse ( ) ; segmentsCount ++ ; } else { //remaining after last segment if ( bitsread < spDataLen ) { int additional_bits = spDataLen - bitsread ; segment [ segmentsCount ] . readSegment ( additional_bits , _in ) ; segment [ segmentsCount ] . len += segment [ segmentsCount - 1 ] . len ; segment [ segmentsCount ] . rewindReverse ( ) ; if ( segment [ segmentsCount - 1 ] . len > 32 ) { segment [ segmentsCount - 1 ] . bufb = segment [ segmentsCount ] . bufb + segment [ segmentsCount - 1 ] . showBits ( segment [ segmentsCount - 1 ] . len - 32 ) ; segment [ segmentsCount - 1 ] . bufa = segment [ segmentsCount ] . bufa + segment [ segmentsCount - 1 ] . showBits ( 32 ) ; } else { segment [ segmentsCount - 1 ] . bufa = segment [ segmentsCount ] . bufa + segment [ segmentsCount - 1 ] . showBits ( segment [ segmentsCount - 1 ] . len ) ; segment [ segmentsCount - 1 ] . bufb = segment [ segmentsCount ] . bufb ; } segment [ segmentsCount - 1 ] . len += additional_bits ; } bitsread = spDataLen ; PCWs_done = 1 ; codeword [ 0 ] . fill ( sp , thisSectCB ) ; } } else { codeword [ numberOfCodewords - segmentsCount ] . fill ( sp , thisSectCB ) ; } numberOfCodewords ++ ; } } } } } } } } if ( segmentsCount == 0 ) throw new AACException ( \"no segments _in HCR\" ) ; final int numberOfSets = numberOfCodewords / segmentsCount ; //step 2: decode nonPCWs int trial , codewordBase , segmentID , codewordID ; for ( int set = 1 ; set <= numberOfSets ; set ++ ) { for ( trial = 0 ; trial < segmentsCount ; trial ++ ) { for ( codewordBase = 0 ; codewordBase < segmentsCount ; codewordBase ++ ) { segmentID = ( trial + codewordBase ) % segmentsCount ; codewordID = codewordBase + set * segmentsCount - segmentsCount ; //data up if ( codewordID >= numberOfCodewords - segmentsCount ) break ; if ( ( codeword [ codewordID ] . decoded == 0 ) && ( segment [ segmentID ] . len > 0 ) ) { if ( codeword [ codewordID ] . bits . len != 0 ) segment [ segmentID ] . concatBits ( codeword [ codewordID ] . bits ) ; int tmplen = segment [ segmentID ] . len ; /*int ret = Huffman.decodeSpectralDataER(segment[segmentID], codeword[codewordID].cb,\n\t\t\t\t\t\t\t\tspectralData, codeword[codewordID].sp_offset);\n\n\t\t\t\t\t\tif(ret>=0) codeword[codewordID].decoded = 1;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcodeword[codewordID].bits = segment[segmentID];\n\t\t\t\t\t\t\tcodeword[codewordID].bits.len = tmplen;\n\t\t\t\t\t\t}*/ } } } for ( i = 0 ; i < segmentsCount ; i ++ ) { segment [ i ] . rewindReverse ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts DCT reconstruction [CODESPLIT] public static final void start ( int [ ] block , int dc ) { dc <<= DC_SHIFT ; for ( int i = 0 ; i < 64 ; i += 4 ) { block [ i + 0 ] = dc ; block [ i + 1 ] = dc ; block [ i + 2 ] = dc ; block [ i + 3 ] = dc ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recalculates image based on new DCT coefficient [CODESPLIT] public static final void coeff ( int [ ] block , int ind , int level ) { for ( int i = 0 ; i < 64 ; i += 4 ) { block [ i ] += COEFF [ ind ] [ i ] * level ; block [ i + 1 ] += COEFF [ ind ] [ i + 1 ] * level ; block [ i + 2 ] += COEFF [ ind ] [ i + 2 ] * level ; block [ i + 3 ] += COEFF [ ind ] [ i + 3 ] * level ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finalizes DCT calculation [CODESPLIT] public static final void finish ( int block [ ] ) { for ( int i = 0 ; i < 64 ; i += 4 ) { block [ i ] = div ( block [ i ] ) ; block [ i + 1 ] = div ( block [ i + 1 ] ) ; block [ i + 2 ] = div ( block [ i + 2 ] ) ; block [ i + 3 ] = div ( block [ i + 3 ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs this decoder from a portion of a stream that contains AnnexB delimited ( 00 00 00 01 ) SPS / PPS NAL units . SPS / PPS NAL units are 0x67 and 0x68 respectfully . [CODESPLIT] public static H264Decoder createH264DecoderFromCodecPrivate ( ByteBuffer codecPrivate ) { H264Decoder d = new H264Decoder ( ) ; for ( ByteBuffer bb : H264Utils . splitFrame ( codecPrivate . duplicate ( ) ) ) { NALUnit nu = NALUnit . read ( bb ) ; if ( nu . type == NALUnitType . SPS ) { d . reader . addSps ( bb ) ; } else if ( nu . type == NALUnitType . PPS ) { d . reader . addPps ( bb ) ; } } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : this may be optimized of - course if it turns out to be a frequently called method [CODESPLIT] public static MKVType getParent ( MKVType t ) { for ( Entry < MKVType , Set < MKVType > > ent : children . entrySet ( ) ) { if ( ent . getValue ( ) . contains ( t ) ) return ent . getKey ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge bits of a to b [CODESPLIT] public void concatBits ( BitsBuffer a ) { if ( a . len == 0 ) return ; int al = a . bufa ; int ah = a . bufb ; int bl , bh ; if ( len > 32 ) { //mask off superfluous high b bits bl = bufa ; bh = bufb & ( ( 1 << ( len - 32 ) ) - 1 ) ; //left shift a len bits ah = al << ( len - 32 ) ; al = 0 ; } else { bl = bufa & ( ( 1 << ( len ) ) - 1 ) ; bh = 0 ; ah = ( ah << ( len ) ) | ( al >> ( 32 - len ) ) ; al = al << len ; } //merge bufa = bl | al ; bufb = bh | ah ; len += a . len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "32 bit rewind and reverse [CODESPLIT] static int rewindReverse32 ( int v , int len ) { v = ( ( v >> S [ 0 ] ) & B [ 0 ] ) | ( ( v << S [ 0 ] ) & ~ B [ 0 ] ) ; v = ( ( v >> S [ 1 ] ) & B [ 1 ] ) | ( ( v << S [ 1 ] ) & ~ B [ 1 ] ) ; v = ( ( v >> S [ 2 ] ) & B [ 2 ] ) | ( ( v << S [ 2 ] ) & ~ B [ 2 ] ) ; v = ( ( v >> S [ 3 ] ) & B [ 3 ] ) | ( ( v << S [ 3 ] ) & ~ B [ 3 ] ) ; v = ( ( v >> S [ 4 ] ) & B [ 4 ] ) | ( ( v << S [ 4 ] ) & ~ B [ 4 ] ) ; //shift off low bits v >>= ( 32 - len ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "64 bit rewind and reverse [CODESPLIT] static int [ ] rewindReverse64 ( int hi , int lo , int len ) { int [ ] i = new int [ 2 ] ; if ( len <= 32 ) { i [ 0 ] = 0 ; i [ 1 ] = rewindReverse32 ( lo , len ) ; } else { lo = ( ( lo >> S [ 0 ] ) & B [ 0 ] ) | ( ( lo << S [ 0 ] ) & ~ B [ 0 ] ) ; hi = ( ( hi >> S [ 0 ] ) & B [ 0 ] ) | ( ( hi << S [ 0 ] ) & ~ B [ 0 ] ) ; lo = ( ( lo >> S [ 1 ] ) & B [ 1 ] ) | ( ( lo << S [ 1 ] ) & ~ B [ 1 ] ) ; hi = ( ( hi >> S [ 1 ] ) & B [ 1 ] ) | ( ( hi << S [ 1 ] ) & ~ B [ 1 ] ) ; lo = ( ( lo >> S [ 2 ] ) & B [ 2 ] ) | ( ( lo << S [ 2 ] ) & ~ B [ 2 ] ) ; hi = ( ( hi >> S [ 2 ] ) & B [ 2 ] ) | ( ( hi << S [ 2 ] ) & ~ B [ 2 ] ) ; lo = ( ( lo >> S [ 3 ] ) & B [ 3 ] ) | ( ( lo << S [ 3 ] ) & ~ B [ 3 ] ) ; hi = ( ( hi >> S [ 3 ] ) & B [ 3 ] ) | ( ( hi << S [ 3 ] ) & ~ B [ 3 ] ) ; lo = ( ( lo >> S [ 4 ] ) & B [ 4 ] ) | ( ( lo << S [ 4 ] ) & ~ B [ 4 ] ) ; hi = ( ( hi >> S [ 4 ] ) & B [ 4 ] ) | ( ( hi << S [ 4 ] ) & ~ B [ 4 ] ) ; //shift off low bits i [ 1 ] = ( hi >> ( 64 - len ) ) | ( lo << ( len - 32 ) ) ; i [ 1 ] = lo >> ( 64 - len ) ; } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ========= decoding ========== [CODESPLIT] public void decode ( IBitStream _in , boolean commonWindow , AACDecoderConfig conf ) throws AACException { if ( conf . isScalefactorResilienceUsed ( ) && rvlc == null ) rvlc = new RVLC ( ) ; final boolean er = conf . getProfile ( ) . isErrorResilientProfile ( ) ; globalGain = _in . readBits ( 8 ) ; if ( ! commonWindow ) info . decode ( _in , conf , commonWindow ) ; decodeSectionData ( _in , conf . isSectionDataResilienceUsed ( ) ) ; //if(conf.isScalefactorResilienceUsed()) rvlc.decode(_in, this, scaleFactors); /*else*/ decodeScaleFactors ( _in ) ; pulseDataPresent = _in . readBool ( ) ; if ( pulseDataPresent ) { if ( info . isEightShortFrame ( ) ) throw new AACException ( \"pulse data not allowed for short frames\" ) ; Logger . debug ( \"PULSE\" ) ; decodePulseData ( _in ) ; } tnsDataPresent = _in . readBool ( ) ; if ( tnsDataPresent && ! er ) { if ( tns == null ) tns = new TNS ( ) ; tns . decode ( _in , info ) ; } gainControlPresent = _in . readBool ( ) ; if ( gainControlPresent ) { if ( gainControl == null ) gainControl = new GainControl ( frameLength ) ; Logger . debug ( \"GAIN\" ) ; gainControl . decode ( _in , info . getWindowSequence ( ) ) ; } //RVLC spectral data //if(conf.isScalefactorResilienceUsed()) rvlc.decodeScalefactors(this, _in, scaleFactors); if ( conf . isSpectralDataResilienceUsed ( ) ) { int max = ( conf . getChannelConfiguration ( ) == ChannelConfiguration . CHANNEL_CONFIG_STEREO ) ? 6144 : 12288 ; reorderedSpectralDataLen = Math . max ( _in . readBits ( 14 ) , max ) ; longestCodewordLen = Math . max ( _in . readBits ( 6 ) , 49 ) ; //HCR.decodeReorderedSpectralData(this, _in, data, conf.isSectionDataResilienceUsed()); } else decodeSpectralData ( _in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private void scheduleClose ( ) { if ( task != null ) task . cancel ( ) ; task = new TimerTask ( ) { public void run ( ) { state = State . HIDING ; } } ; timer . schedule ( task , 1000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified second as AWT image [CODESPLIT] public static Bitmap getFrame ( File file , double second ) throws IOException , JCodecException { FileChannelWrapper ch = null ; try { ch = NIOUtils . readableChannel ( file ) ; return ( ( AndroidFrameGrab ) createAndroidFrameGrab ( ch ) . seekToSecondPrecise ( second ) ) . getFrame ( ) ; } finally { NIOUtils . closeQuietly ( ch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified second as AWT image [CODESPLIT] public static Bitmap getFrame ( SeekableByteChannel file , double second ) throws JCodecException , IOException { return ( ( AndroidFrameGrab ) createAndroidFrameGrab ( file ) . seekToSecondPrecise ( second ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at current position in AWT image [CODESPLIT] public BitmapWithMetadata getFrameWithMetadata ( ) throws IOException { PictureWithMetadata pictureWithMeta = getNativeFrameWithMetadata ( ) ; if ( pictureWithMeta == null ) return null ; Bitmap bitmap = AndroidUtil . toBitmap ( pictureWithMeta . getPicture ( ) ) ; return new BitmapWithMetadata ( bitmap , pictureWithMeta . getTimestamp ( ) , pictureWithMeta . getDuration ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at current position in AWT image [CODESPLIT] public void getFrame ( Bitmap bmp ) throws IOException { Picture picture = getNativeFrame ( ) ; AndroidUtil . toBitmap ( picture , bmp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at current position in AWT image [CODESPLIT] public BitmapWithMetadata getFrameWithMetadata ( Bitmap bmp ) throws IOException { PictureWithMetadata pictureWithMetadata = getNativeFrameWithMetadata ( ) ; if ( pictureWithMetadata == null ) return null ; AndroidUtil . toBitmap ( pictureWithMetadata . getPicture ( ) , bmp ) ; return new BitmapWithMetadata ( bmp , pictureWithMetadata . getTimestamp ( ) , pictureWithMetadata . getDuration ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified frame number as AWT image [CODESPLIT] public static Bitmap getFrame ( File file , int frameNumber ) throws IOException , JCodecException { FileChannelWrapper ch = null ; try { ch = NIOUtils . readableChannel ( file ) ; return ( ( AndroidFrameGrab ) createAndroidFrameGrab ( ch ) . seekToFramePrecise ( frameNumber ) ) . getFrame ( ) ; } finally { NIOUtils . closeQuietly ( ch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified frame number as AWT image [CODESPLIT] public static Bitmap getFrame ( SeekableByteChannel file , int frameNumber ) throws JCodecException , IOException { return ( ( AndroidFrameGrab ) createAndroidFrameGrab ( file ) . seekToFramePrecise ( frameNumber ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by number from an already open demuxer track [CODESPLIT] public static Bitmap getFrame ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , int frameNumber ) throws IOException , JCodecException { return ( ( AndroidFrameGrab ) new AndroidFrameGrab ( vt , decoder ) . seekToFramePrecise ( frameNumber ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by second from an already open demuxer track [CODESPLIT] public static Bitmap getFrame ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , double second ) throws IOException , JCodecException { return ( ( AndroidFrameGrab ) new AndroidFrameGrab ( vt , decoder ) . seekToSecondPrecise ( second ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by number from an already open demuxer track ( sloppy mode i . e . nearest keyframe ) [CODESPLIT] public static Bitmap getFrameSloppy ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , int frameNumber ) throws IOException , JCodecException { return ( ( AndroidFrameGrab ) new AndroidFrameGrab ( vt , decoder ) . seekToFrameSloppy ( frameNumber ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by second from an already open demuxer track ( sloppy mode i . e . nearest keyframe ) [CODESPLIT] public static Bitmap getFrameSloppy ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , double second ) throws IOException , JCodecException { return ( ( AndroidFrameGrab ) new AndroidFrameGrab ( vt , decoder ) . seekToSecondSloppy ( second ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Seeks to a previous key frame prior or on the given frame if the track is not seekable returns 0 . [CODESPLIT] protected int seekToKeyFrame ( int frame ) throws IOException { if ( videoInputTrack instanceof SeekableDemuxerTrack ) { SeekableDemuxerTrack seekable = ( SeekableDemuxerTrack ) videoInputTrack ; seekable . gotoSyncFrame ( frame ) ; return ( int ) seekable . getCurFrame ( ) ; } else { Logger . warn ( \"Can not seek in \" + videoInputTrack + \" container.\" ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a pixel buffer of a suitable size to hold the given video frame . The video size is taken either from the video metadata or by analyzing the incoming video packet . [CODESPLIT] protected LoanerPicture getPixelBuffer ( ByteBuffer firstFrame ) { VideoCodecMeta videoMeta = getVideoCodecMeta ( ) ; Size size = videoMeta . getSize ( ) ; return pixelStore . getPicture ( ( size . getWidth ( ) + 15 ) & ~ 0xf , ( size . getHeight ( ) + 15 ) & ~ 0xf , videoMeta . getColor ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] private void dctOnePlane ( int blocksPerSlice , byte [ ] src , byte [ ] hibd , int [ ] dst ) { for ( int i = 0 ; i < src . length ; i ++ ) { dst [ i ] = ( ( src [ i ] + 128 ) << 2 ) ; } if ( hibd != null ) { for ( int i = 0 ; i < src . length ; i ++ ) { dst [ i ] += hibd [ i ] ; } } for ( int i = 0 ; i < blocksPerSlice ; i ++ ) { fdctProres10 ( dst , i << 6 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] private void split ( Picture src , Picture dst , int mbX , int mbY , int sliceMbCount , int vStep , int vOffset ) { byte [ ] [ ] inData = src . getData ( ) ; byte [ ] [ ] inhbdData = src . getLowBits ( ) ; byte [ ] [ ] outData = dst . getData ( ) ; byte [ ] [ ] outhbdData = dst . getLowBits ( ) ; doSplit ( inData [ 0 ] , outData [ 0 ] , src . getPlaneWidth ( 0 ) , mbX , mbY , sliceMbCount , 0 , vStep , vOffset ) ; doSplit ( inData [ 1 ] , outData [ 1 ] , src . getPlaneWidth ( 1 ) , mbX , mbY , sliceMbCount , 1 , vStep , vOffset ) ; doSplit ( inData [ 2 ] , outData [ 2 ] , src . getPlaneWidth ( 2 ) , mbX , mbY , sliceMbCount , 1 , vStep , vOffset ) ; if ( src . getLowBits ( ) != null ) { doSplit ( inhbdData [ 0 ] , outhbdData [ 0 ] , src . getPlaneWidth ( 0 ) , mbX , mbY , sliceMbCount , 0 , vStep , vOffset ) ; doSplit ( inhbdData [ 1 ] , outhbdData [ 1 ] , src . getPlaneWidth ( 1 ) , mbX , mbY , sliceMbCount , 1 , vStep , vOffset ) ; doSplit ( inhbdData [ 2 ] , outhbdData [ 2 ] , src . getPlaneWidth ( 2 ) , mbX , mbY , sliceMbCount , 1 , vStep , vOffset ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gain compensation and overlap - add : - the gain control function is calculated - the gain control function applies to IMDCT output samples as a another IMDCT window - the reconstructed time domain signal produces by overlap - add [CODESPLIT] private void compensate ( float [ ] _in , float [ ] [ ] out , WindowSequence winSeq , int band ) { int j ; if ( winSeq . equals ( WindowSequence . EIGHT_SHORT_SEQUENCE ) ) { int a , b ; for ( int k = 0 ; k < 8 ; k ++ ) { //calculation calculateFunctionData ( lbShort * 2 , band , winSeq , k ) ; //applying for ( j = 0 ; j < lbShort * 2 ; j ++ ) { a = band * lbLong * 2 + k * lbShort * 2 + j ; _in [ a ] *= _function [ j ] ; } //overlapping for ( j = 0 ; j < lbShort ; j ++ ) { a = j + lbLong * 7 / 16 + lbShort * k ; b = band * lbLong * 2 + k * lbShort * 2 + j ; overlap [ band ] [ a ] += _in [ b ] ; } //store for next frame for ( j = 0 ; j < lbShort ; j ++ ) { a = j + lbLong * 7 / 16 + lbShort * ( k + 1 ) ; b = band * lbLong * 2 + k * lbShort * 2 + lbShort + j ; overlap [ band ] [ a ] = _in [ b ] ; } locationPrev [ band ] [ 0 ] = Platform . copyOfInt ( location [ band ] [ k ] , location [ band ] [ k ] . length ) ; levelPrev [ band ] [ 0 ] = Platform . copyOfInt ( level [ band ] [ k ] , level [ band ] [ k ] . length ) ; } arraycopy ( overlap [ band ] , 0 , out [ band ] , 0 , lbLong ) ; arraycopy ( overlap [ band ] , lbLong , overlap [ band ] , 0 , lbLong ) ; } else { //calculation calculateFunctionData ( lbLong * 2 , band , winSeq , 0 ) ; //applying for ( j = 0 ; j < lbLong * 2 ; j ++ ) { _in [ band * lbLong * 2 + j ] *= _function [ j ] ; } //overlapping for ( j = 0 ; j < lbLong ; j ++ ) { out [ band ] [ j ] = overlap [ band ] [ j ] + _in [ band * lbLong * 2 + j ] ; } //store for next frame for ( j = 0 ; j < lbLong ; j ++ ) { overlap [ band ] [ j ] = _in [ band * lbLong * 2 + lbLong + j ] ; } final int lastBlock = winSeq . equals ( WindowSequence . ONLY_LONG_SEQUENCE ) ? 1 : 0 ; locationPrev [ band ] [ 0 ] = Platform . copyOfInt ( location [ band ] [ lastBlock ] , location [ band ] [ lastBlock ] . length ) ; levelPrev [ band ] [ 0 ] = Platform . copyOfInt ( level [ band ] [ lastBlock ] , level [ band ] [ lastBlock ] . length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "produces gain control function data stores it in function array [CODESPLIT] private void calculateFunctionData ( int samples , int band , WindowSequence winSeq , int blockID ) { final int [ ] locA = new int [ 10 ] ; final float [ ] levA = new float [ 10 ] ; final float [ ] modFunc = new float [ samples ] ; final float [ ] buf1 = new float [ samples / 2 ] ; final float [ ] buf2 = new float [ samples / 2 ] ; final float [ ] buf3 = new float [ samples / 2 ] ; int maxLocGain0 = 0 , maxLocGain1 = 0 , maxLocGain2 = 0 ; switch ( winSeq ) { case ONLY_LONG_SEQUENCE : case EIGHT_SHORT_SEQUENCE : maxLocGain0 = maxLocGain1 = samples / 2 ; maxLocGain2 = 0 ; break ; case LONG_START_SEQUENCE : maxLocGain0 = samples / 2 ; maxLocGain1 = samples * 7 / 32 ; maxLocGain2 = samples / 16 ; break ; case LONG_STOP_SEQUENCE : maxLocGain0 = samples / 16 ; maxLocGain1 = samples * 7 / 32 ; maxLocGain2 = samples / 2 ; break ; } //calculate the fragment modification functions //for the first half region calculateFMD ( band , 0 , true , maxLocGain0 , samples , locA , levA , buf1 ) ; //for the latter half region int block = ( winSeq . equals ( WindowSequence . EIGHT_SHORT_SEQUENCE ) ) ? blockID : 0 ; float secLevel = calculateFMD ( band , block , false , maxLocGain1 , samples , locA , levA , buf2 ) ; //for the non-overlapped region if ( winSeq . equals ( WindowSequence . LONG_START_SEQUENCE ) || winSeq . equals ( WindowSequence . LONG_STOP_SEQUENCE ) ) { calculateFMD ( band , 1 , false , maxLocGain2 , samples , locA , levA , buf3 ) ; } //calculate a gain modification function int i ; int flatLen = 0 ; if ( winSeq . equals ( WindowSequence . LONG_STOP_SEQUENCE ) ) { flatLen = samples / 2 - maxLocGain0 - maxLocGain1 ; for ( i = 0 ; i < flatLen ; i ++ ) { modFunc [ i ] = 1.0f ; } } if ( winSeq . equals ( WindowSequence . ONLY_LONG_SEQUENCE ) || winSeq . equals ( WindowSequence . EIGHT_SHORT_SEQUENCE ) ) levA [ 0 ] = 1.0f ; for ( i = 0 ; i < maxLocGain0 ; i ++ ) { modFunc [ i + flatLen ] = levA [ 0 ] * secLevel * buf1 [ i ] ; } for ( i = 0 ; i < maxLocGain1 ; i ++ ) { modFunc [ i + flatLen + maxLocGain0 ] = levA [ 0 ] * buf2 [ i ] ; } if ( winSeq . equals ( WindowSequence . LONG_START_SEQUENCE ) ) { for ( i = 0 ; i < maxLocGain2 ; i ++ ) { modFunc [ i + maxLocGain0 + maxLocGain1 ] = buf3 [ i ] ; } flatLen = samples / 2 - maxLocGain1 - maxLocGain2 ; for ( i = 0 ; i < flatLen ; i ++ ) { modFunc [ i + maxLocGain0 + maxLocGain1 + maxLocGain2 ] = 1.0f ; } } else if ( winSeq . equals ( WindowSequence . LONG_STOP_SEQUENCE ) ) { for ( i = 0 ; i < maxLocGain2 ; i ++ ) { modFunc [ i + flatLen + maxLocGain0 + maxLocGain1 ] = buf3 [ i ] ; } } //calculate a gain control function for ( i = 0 ; i < samples ; i ++ ) { _function [ i ] = 1.0f / modFunc [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * calculates a fragment modification function by interpolating the gain values of the gain change positions [CODESPLIT] private float calculateFMD ( int bd , int wd , boolean prev , int maxLocGain , int samples , int [ ] loc , float [ ] lev , float [ ] fmd ) { final int [ ] m = new int [ samples / 2 ] ; final int [ ] lct = prev ? locationPrev [ bd ] [ wd ] : location [ bd ] [ wd ] ; final int [ ] lvl = prev ? levelPrev [ bd ] [ wd ] : level [ bd ] [ wd ] ; final int length = lct . length ; int lngain ; int i ; for ( i = 0 ; i < length ; i ++ ) { loc [ i + 1 ] = 8 * lct [ i ] ; //gainc lngain = getGainChangePointID ( lvl [ i ] ) ; //gainc if ( lngain < 0 ) lev [ i + 1 ] = 1.0f / ( float ) Math . pow ( 2 , - lngain ) ; else lev [ i + 1 ] = ( float ) Math . pow ( 2 , lngain ) ; } //set start point values loc [ 0 ] = 0 ; if ( length == 0 ) lev [ 0 ] = 1.0f ; else lev [ 0 ] = lev [ 1 ] ; float secLevel = lev [ 0 ] ; //set end point values loc [ length + 1 ] = maxLocGain ; lev [ length + 1 ] = 1.0f ; int j ; for ( i = 0 ; i < maxLocGain ; i ++ ) { m [ i ] = 0 ; for ( j = 0 ; j <= length + 1 ; j ++ ) { if ( loc [ j ] <= i ) m [ i ] = j ; } } for ( i = 0 ; i < maxLocGain ; i ++ ) { if ( ( i >= loc [ m [ i ] ] ) && ( i <= loc [ m [ i ] ] + 7 ) ) fmd [ i ] = interpolateGain ( lev [ m [ i ] ] , lev [ m [ i ] + 1 ] , i - loc [ m [ i ] ] ) ; else fmd [ i ] = lev [ m [ i ] + 1 ] ; } return secLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transformes the exponent value of the gain to the id of the gain change point [CODESPLIT] private int getGainChangePointID ( int lngain ) { for ( int i = 0 ; i < ID_GAIN ; i ++ ) { if ( lngain == LN_GAIN [ i ] ) return i ; } return 0 ; //shouldn't happen }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "calculates a fragment modification function the interpolated gain value between the gain values of two gain change positions is calculated by the formula : f ( a b j ) = 2^ ((( 8 - j ) log2 ( a ) + j * log2 ( b )) / 8 ) [CODESPLIT] private float interpolateGain ( float alev0 , float alev1 , int iloc ) { final float a0 = ( float ) ( Math . log ( alev0 ) / Math . log ( 2 ) ) ; final float a1 = ( float ) ( Math . log ( alev1 ) / Math . log ( 2 ) ) ; return ( float ) Math . pow ( 2.0f , ( ( ( 8 - iloc ) * a0 + iloc * a1 ) / 8 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic byte - array to integer - array conversion [CODESPLIT] public static int [ ] fromByte ( byte [ ] b , int depth , boolean isBe ) { if ( depth == 24 ) if ( isBe ) return from24BE ( b ) ; else return from24LE ( b ) ; else if ( depth == 16 ) if ( isBe ) return from16BE ( b ) ; else return from16LE ( b ) ; throw new NotSupportedException ( \"Conversion from \" + depth + \"bit \" + ( isBe ? \"big endian\" : \"little endian\" ) + \" is not supported.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic integer - array to byte - array conversion [CODESPLIT] public static byte [ ] toByte ( int [ ] ia , int depth , boolean isBe ) { if ( depth == 24 ) if ( isBe ) return to24BE ( ia ) ; else return to24LE ( ia ) ; else if ( depth == 16 ) if ( isBe ) return to16BE ( ia ) ; else return to16LE ( ia ) ; throw new NotSupportedException ( \"Conversion to \" + depth + \"bit \" + ( isBe ? \"big endian\" : \"little endian\" ) + \" is not supported.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts PCM samples stored in buf and described with format to float array representation [CODESPLIT] public static void toFloat ( AudioFormat format , ByteBuffer buf , FloatBuffer floatBuf ) { if ( ! format . isSigned ( ) ) throw new NotSupportedException ( \"Unsigned PCM is not supported ( yet? ).\" ) ; if ( format . getSampleSizeInBits ( ) != 16 && format . getSampleSizeInBits ( ) != 24 ) throw new NotSupportedException ( format . getSampleSizeInBits ( ) + \" bit PCM is not supported ( yet? ).\" ) ; if ( format . isBigEndian ( ) ) { if ( format . getSampleSizeInBits ( ) == 16 ) { toFloat16BE ( buf , floatBuf ) ; } else { toFloat24BE ( buf , floatBuf ) ; } } else { if ( format . getSampleSizeInBits ( ) == 16 ) { toFloat16LE ( buf , floatBuf ) ; } else { toFloat24LE ( buf , floatBuf ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts float PCM samples stored in floatBuf to integer representation according to format and stores them in buf [CODESPLIT] public static void fromFloat ( FloatBuffer floatBuf , AudioFormat format , ByteBuffer buf ) { if ( ! format . isSigned ( ) ) throw new NotSupportedException ( \"Unsigned PCM is not supported ( yet? ).\" ) ; if ( format . getSampleSizeInBits ( ) != 16 && format . getSampleSizeInBits ( ) != 24 ) throw new NotSupportedException ( format . getSampleSizeInBits ( ) + \" bit PCM is not supported ( yet? ).\" ) ; if ( format . isBigEndian ( ) ) { if ( format . getSampleSizeInBits ( ) == 16 ) { fromFloat16BE ( buf , floatBuf ) ; } else { fromFloat24BE ( buf , floatBuf ) ; } } else { if ( format . getSampleSizeInBits ( ) == 16 ) { fromFloat16LE ( buf , floatBuf ) ; } else { fromFloat24LE ( buf , floatBuf ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interleaves audio samples in ins into outb using sample size from the format [CODESPLIT] public static void interleave ( AudioFormat format , ByteBuffer [ ] ins , ByteBuffer outb ) { int bytesPerSample = format . getSampleSizeInBits ( ) >> 3 ; int bytesPerFrame = bytesPerSample * ins . length ; int max = 0 ; for ( int i = 0 ; i < ins . length ; i ++ ) if ( ins [ i ] . remaining ( ) > max ) max = ins [ i ] . remaining ( ) ; for ( int frames = 0 ; frames < max && outb . remaining ( ) >= bytesPerFrame ; frames ++ ) { for ( int j = 0 ; j < ins . length ; j ++ ) { if ( ins [ j ] . remaining ( ) < bytesPerSample ) { for ( int i = 0 ; i < bytesPerSample ; i ++ ) outb . put ( ( byte ) 0 ) ; } else { for ( int i = 0 ; i < bytesPerSample ; i ++ ) { outb . put ( ins [ j ] . get ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deinterleaves audio samples from inb into outs using sample size from format [CODESPLIT] public static void deinterleave ( AudioFormat format , ByteBuffer inb , ByteBuffer [ ] outs ) { int bytesPerSample = format . getSampleSizeInBits ( ) >> 3 ; int bytesPerFrame = bytesPerSample * outs . length ; while ( inb . remaining ( ) >= bytesPerFrame ) { for ( int j = 0 ; j < outs . length ; j ++ ) { for ( int i = 0 ; i < bytesPerSample ; i ++ ) { outs [ j ] . put ( inb . get ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves coded size of this video track . [CODESPLIT] public Size getCodedSize ( ) { SampleEntry se = getSampleEntries ( ) [ 0 ] ; if ( ! ( se instanceof VideoSampleEntry ) ) throw new IllegalArgumentException ( \"Not a video track\" ) ; VideoSampleEntry vse = ( VideoSampleEntry ) se ; return new Size ( vse . getWidth ( ) , vse . getHeight ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A dispersed map . Every odd line starts from the ( N / 2 ) th group [CODESPLIT] public static int [ ] buildDispersedMap ( int picWidthInMbs , int picHeightInMbs , int numSliceGroups ) { int picSizeInMbs = picWidthInMbs * picHeightInMbs ; int [ ] groups = new int [ picSizeInMbs ] ; for ( int i = 0 ; i < picSizeInMbs ; i ++ ) { int group = ( ( i % picWidthInMbs ) + ( ( ( i / picWidthInMbs ) * numSliceGroups ) / 2 ) ) % numSliceGroups ; groups [ i ] = group ; } return groups ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A boxout macroblock to slice group mapping . Only applicable when there s exactly 2 slice groups . Slice group 1 is a background while slice group 0 is a box in the middle of the frame . [CODESPLIT] public static int [ ] buildBoxOutMap ( int picWidthInMbs , int picHeightInMbs , boolean changeDirection , int numberOfMbsInBox ) { int picSizeInMbs = picWidthInMbs * picHeightInMbs ; int [ ] groups = new int [ picSizeInMbs ] ; int changeDirectionInt = changeDirection ? 1 : 0 ; for ( int i = 0 ; i < picSizeInMbs ; i ++ ) groups [ i ] = 1 ; int x = ( picWidthInMbs - changeDirectionInt ) / 2 ; int y = ( picHeightInMbs - changeDirectionInt ) / 2 ; int leftBound = x ; int topBound = y ; int rightBound = x ; int bottomBound = y ; int xDir = changeDirectionInt - 1 ; int yDir = changeDirectionInt ; boolean mapUnitVacant = false ; for ( int k = 0 ; k < numberOfMbsInBox ; k += ( mapUnitVacant ? 1 : 0 ) ) { int mbAddr = y * picWidthInMbs + x ; mapUnitVacant = ( groups [ mbAddr ] == 1 ) ; if ( mapUnitVacant ) { groups [ mbAddr ] = 0 ; } if ( xDir == - 1 && x == leftBound ) { leftBound = Max ( leftBound - 1 , 0 ) ; x = leftBound ; xDir = 0 ; yDir = 2 * changeDirectionInt - 1 ; } else if ( xDir == 1 && x == rightBound ) { rightBound = Min ( rightBound + 1 , picWidthInMbs - 1 ) ; x = rightBound ; xDir = 0 ; yDir = 1 - 2 * changeDirectionInt ; } else if ( yDir == - 1 && y == topBound ) { topBound = Max ( topBound - 1 , 0 ) ; y = topBound ; xDir = 1 - 2 * changeDirectionInt ; yDir = 0 ; } else if ( yDir == 1 && y == bottomBound ) { bottomBound = Min ( bottomBound + 1 , picHeightInMbs - 1 ) ; y = bottomBound ; xDir = 2 * changeDirectionInt - 1 ; yDir = 0 ; } else { x += xDir ; y += yDir ; } } return groups ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A macroblock to slice group map that fills frame column by column [CODESPLIT] public static int [ ] buildWipeMap ( int picWidthInMbs , int picHeightInMbs , int sizeOfUpperLeftGroup , boolean changeDirection ) { int picSizeInMbs = picWidthInMbs * picHeightInMbs ; int [ ] groups = new int [ picSizeInMbs ] ; int changeDirectionInt = changeDirection ? 1 : 0 ; int k = 0 ; for ( int j = 0 ; j < picWidthInMbs ; j ++ ) { for ( int i = 0 ; i < picHeightInMbs ; i ++ ) { int mbAddr = i * picWidthInMbs + j ; if ( k ++ < sizeOfUpperLeftGroup ) { groups [ mbAddr ] = changeDirectionInt ; } else { groups [ mbAddr ] = 1 - changeDirectionInt ; } } } return groups ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to read a batch of ULS [CODESPLIT] protected static UL [ ] readULBatch ( ByteBuffer _bb ) { int count = _bb . getInt ( ) ; _bb . getInt ( ) ; UL [ ] result = new UL [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { result [ i ] = UL . read ( _bb ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to read a batch of int32 [CODESPLIT] protected static int [ ] readInt32Batch ( ByteBuffer _bb ) { int count = _bb . getInt ( ) ; _bb . getInt ( ) ; int [ ] result = new int [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { result [ i ] = _bb . getInt ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified second as AWT image [CODESPLIT] public static BufferedImage getFrame ( File file , double second ) throws IOException , JCodecException { FileChannelWrapper ch = null ; try { ch = NIOUtils . readableChannel ( file ) ; return ( ( AWTFrameGrab ) createAWTFrameGrab ( ch ) . seekToSecondPrecise ( second ) ) . getFrameWithOrientation ( ) ; } finally { NIOUtils . closeQuietly ( ch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified second as AWT image [CODESPLIT] public static BufferedImage getFrame ( SeekableByteChannel file , double second ) throws JCodecException , IOException { return ( ( AWTFrameGrab ) createAWTFrameGrab ( file ) . seekToSecondPrecise ( second ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at current position in AWT image [CODESPLIT] public BufferedImage getFrame ( ) throws IOException { Picture nativeFrame = getNativeFrame ( ) ; return nativeFrame == null ? null : AWTUtil . toBufferedImage ( nativeFrame ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified frame number as AWT image [CODESPLIT] public static BufferedImage getFrame ( File file , int frameNumber ) throws IOException , JCodecException { FileChannelWrapper ch = null ; try { ch = NIOUtils . readableChannel ( file ) ; return ( ( AWTFrameGrab ) createAWTFrameGrab ( ch ) . seekToFramePrecise ( frameNumber ) ) . getFrame ( ) ; } finally { NIOUtils . closeQuietly ( ch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get frame at a specified frame number as AWT image [CODESPLIT] public static BufferedImage getFrame ( SeekableByteChannel file , int frameNumber ) throws JCodecException , IOException { return ( ( AWTFrameGrab ) createAWTFrameGrab ( file ) . seekToFramePrecise ( frameNumber ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by number from an already open demuxer track [CODESPLIT] public static BufferedImage getFrame ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , int frameNumber ) throws IOException , JCodecException { return ( ( AWTFrameGrab ) new AWTFrameGrab ( vt , decoder ) . seekToFramePrecise ( frameNumber ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by second from an already open demuxer track [CODESPLIT] public static BufferedImage getFrame ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , double second ) throws IOException , JCodecException { return ( ( AWTFrameGrab ) new AWTFrameGrab ( vt , decoder ) . seekToSecondPrecise ( second ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by number from an already open demuxer track ( sloppy mode i . e . nearest keyframe ) [CODESPLIT] public static BufferedImage getFrameSloppy ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , int frameNumber ) throws IOException , JCodecException { return ( ( AWTFrameGrab ) new AWTFrameGrab ( vt , decoder ) . seekToFrameSloppy ( frameNumber ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specified frame by second from an already open demuxer track ( sloppy mode i . e . nearest keyframe ) [CODESPLIT] public static BufferedImage getFrameSloppy ( SeekableDemuxerTrack vt , ContainerAdaptor decoder , double second ) throws IOException , JCodecException { return ( ( AWTFrameGrab ) new AWTFrameGrab ( vt , decoder ) . seekToSecondSloppy ( second ) ) . getFrame ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to auto - detect MPEG Audio ( MP3 ) files [CODESPLIT] @ UsedViaReflection public static int probe ( final ByteBuffer b ) { ByteBuffer fork = b . duplicate ( ) ; int valid = 0 , total = 0 ; int header = fork . getInt ( ) ; do { if ( ! validHeader ( header ) ) header = skipJunkBB ( header , fork ) ; int size = calcFrameSize ( header ) ; if ( fork . remaining ( ) < size ) break ; ++ total ; if ( size > 0 ) NIOUtils . skip ( fork , size - 4 ) ; else header = skipJunkBB ( header , fork ) ; if ( fork . remaining ( ) >= 4 ) { header = fork . getInt ( ) ; if ( size >= MIN_FRAME_SIZE && size <= MAX_FRAME_SIZE && validHeader ( header ) ) valid ++ ; } } while ( fork . remaining ( ) >= 4 ) ; return ( 100 * valid ) / total ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates median prediction [CODESPLIT] public static int calcMVPredictionMedian ( int a , int b , int c , int d , boolean aAvb , boolean bAvb , boolean cAvb , boolean dAvb , int ref , int comp ) { if ( ! cAvb ) { c = d ; cAvb = dAvb ; } if ( aAvb && ! bAvb && ! cAvb ) { b = c = a ; bAvb = cAvb = aAvb ; } a = aAvb ? a : NULL_VECTOR ; b = bAvb ? b : NULL_VECTOR ; c = cAvb ? c : NULL_VECTOR ; if ( mvRef ( a ) == ref && mvRef ( b ) != ref && mvRef ( c ) != ref ) return mvC ( a , comp ) ; else if ( mvRef ( b ) == ref && mvRef ( a ) != ref && mvRef ( c ) != ref ) return mvC ( b , comp ) ; else if ( mvRef ( c ) == ref && mvRef ( a ) != ref && mvRef ( b ) != ref ) return mvC ( c , comp ) ; return mvC ( a , comp ) + mvC ( b , comp ) + mvC ( c , comp ) - min ( mvC ( a , comp ) , mvC ( b , comp ) , mvC ( c , comp ) ) - max ( mvC ( a , comp ) , mvC ( b , comp ) , mvC ( c , comp ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes DCT / WHT coefficients into the provided instance of a boolean encoder [CODESPLIT] public void encodeCoeffs ( VPXBooleanEncoder bc , int [ ] coeffs , int firstCoeff , int nCoeff , int blkType , int ctx ) { boolean prevZero = false ; int i ; for ( i = firstCoeff ; i < nCoeff ; i ++ ) { int [ ] probs = tokenBinProbs [ blkType ] [ coeffBandMapping [ i ] ] [ ctx ] ; int coeffAbs = MathUtil . abs ( coeffs [ i ] ) ; if ( ! prevZero ) bc . writeBit ( probs [ 0 ] , 1 ) ; if ( coeffAbs == 0 ) { bc . writeBit ( probs [ 1 ] , 0 ) ; ctx = 0 ; } else { bc . writeBit ( probs [ 1 ] , 1 ) ; if ( coeffAbs == 1 ) { bc . writeBit ( probs [ 2 ] , 0 ) ; ctx = 1 ; } else { ctx = 2 ; bc . writeBit ( probs [ 2 ] , 1 ) ; if ( coeffAbs <= 4 ) { bc . writeBit ( probs [ 3 ] , 0 ) ; if ( coeffAbs == 2 ) bc . writeBit ( probs [ 4 ] , 0 ) ; else { bc . writeBit ( probs [ 4 ] , 1 ) ; bc . writeBit ( probs [ 5 ] , coeffAbs - 3 ) ; } } else { bc . writeBit ( probs [ 3 ] , 1 ) ; if ( coeffAbs <= 10 ) { bc . writeBit ( probs [ 6 ] , 0 ) ; if ( coeffAbs <= 6 ) { bc . writeBit ( probs [ 7 ] , 0 ) ; bc . writeBit ( 159 , coeffAbs - 5 ) ; } else { bc . writeBit ( probs [ 7 ] , 1 ) ; int d = coeffAbs - 7 ; bc . writeBit ( 165 , d >> 1 ) ; bc . writeBit ( 145 , d & 1 ) ; } } else { bc . writeBit ( probs [ 6 ] , 1 ) ; if ( coeffAbs <= 34 ) { bc . writeBit ( probs [ 8 ] , 0 ) ; if ( coeffAbs <= 18 ) { bc . writeBit ( probs [ 9 ] , 0 ) ; writeCat3Ext ( bc , coeffAbs ) ; } else { bc . writeBit ( probs [ 9 ] , 1 ) ; writeCat4Ext ( bc , coeffAbs ) ; } } else { bc . writeBit ( probs [ 8 ] , 1 ) ; if ( coeffAbs <= 66 ) { bc . writeBit ( probs [ 10 ] , 0 ) ; writeCatExt ( bc , coeffAbs , 35 , VPXConst . probCoeffExtCat5 ) ; } else { bc . writeBit ( probs [ 10 ] , 1 ) ; writeCatExt ( bc , coeffAbs , 67 , VPXConst . probCoeffExtCat6 ) ; } } } } } bc . writeBit ( 128 , MathUtil . sign ( coeffs [ i ] ) ) ; } prevZero = coeffAbs == 0 ; } if ( nCoeff < 16 ) { int [ ] probs = tokenBinProbs [ blkType ] [ coeffBandMapping [ i ] ] [ ctx ] ; bc . writeBit ( probs [ 0 ] , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] public static int [ ] readScalingList ( BitReader src , int sizeOfScalingList ) { int [ ] scalingList = new int [ sizeOfScalingList ] ; int lastScale = 8 ; int nextScale = 8 ; for ( int j = 0 ; j < sizeOfScalingList ; j ++ ) { if ( nextScale != 0 ) { int deltaScale = readSE ( src , \"deltaScale\" ) ; nextScale = ( lastScale + deltaScale + 256 ) % 256 ; if ( j == 0 && nextScale == 0 ) return null ; } scalingList [ j ] = nextScale == 0 ? lastScale : nextScale ; lastScale = scalingList [ j ] ; } return scalingList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrong usage of Javascript keyword : in [CODESPLIT] private static void readScalingListMatrix ( BitReader src , SeqParameterSet sps ) { sps . scalingMatrix = new int [ 8 ] [  ] ; for ( int i = 0 ; i < 8 ; i ++ ) { boolean seqScalingListPresentFlag = readBool ( src , \"SPS: seqScalingListPresentFlag\" ) ; if ( seqScalingListPresentFlag ) { int scalingListSize = i < 6 ? 16 : 64 ; sps . scalingMatrix [ i ] = readScalingList ( src , scalingListSize ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode this picture into h . 264 frame . Frame type will be selected by encoder . [CODESPLIT] public EncodedFrame encodeFrame ( Picture pic , ByteBuffer _out ) { if ( pic . getColor ( ) != ColorSpace . YUV420J ) throw new IllegalArgumentException ( \"Input picture color is not supported: \" + pic . getColor ( ) ) ; if ( frameNumber >= keyInterval ) { frameNumber = 0 ; } SliceType sliceType = frameNumber == 0 ? SliceType . I : SliceType . P ; boolean idr = frameNumber == 0 ; ByteBuffer data = doEncodeFrame ( pic , _out , idr , frameNumber ++ , sliceType ) ; return new EncodedFrame ( data , idr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode this picture as an IDR frame . IDR frame starts a new independently decodeable video sequence [CODESPLIT] public ByteBuffer encodeIDRFrame ( Picture pic , ByteBuffer _out ) { frameNumber = 0 ; return doEncodeFrame ( pic , _out , true , frameNumber , SliceType . I ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode this picture as a P - frame . P - frame is an frame predicted from one or more of the previosly decoded frame and is usually 10x less in size then the IDR frame . [CODESPLIT] public ByteBuffer encodePFrame ( Picture pic , ByteBuffer _out ) { frameNumber ++ ; return doEncodeFrame ( pic , _out , true , frameNumber , SliceType . P ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name of the numbered property . <br > <br > [CODESPLIT] public Property getPropertyMetaData ( int propertyNo ) { long cPtr = VideoJNI . Configurable_getPropertyMetaData__SWIG_0 ( swigCPtr , this , propertyNo ) ; return ( cPtr == 0 ) ? null : new Property ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name of the named property . <br > <br > [CODESPLIT] public Property getPropertyMetaData ( String name ) { long cPtr = VideoJNI . Configurable_getPropertyMetaData__SWIG_1 ( swigCPtr , this , name ) ; return ( cPtr == 0 ) ? null : new Property ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a property on this Object . <br > <br > All AVOptions supported by the underlying AVClass are supported . <br > <br > [CODESPLIT] public void setProperty ( String name , String value ) { VideoJNI . Configurable_setProperty__SWIG_0 ( swigCPtr , this , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up the property name and sets the<br > value of the property to value . <br > <br > [CODESPLIT] public void setProperty ( String name , Rational value ) { VideoJNI . Configurable_setProperty__SWIG_4 ( swigCPtr , this , name , Rational . getCPtr ( value ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of this property and returns as an Rational ; <br > <br > [CODESPLIT] public Rational getPropertyAsRational ( String name ) { long cPtr = VideoJNI . Configurable_getPropertyAsRational ( swigCPtr , this , name ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets all properties in valuesToSet on this Configurable object . <br > <br > [CODESPLIT] public void setProperty ( KeyValueBag valuesToSet , KeyValueBag valuesNotFound ) { VideoJNI . Configurable_setProperty__SWIG_5 ( swigCPtr , this , KeyValueBag . getCPtr ( valuesToSet ) , valuesToSet , KeyValueBag . getCPtr ( valuesNotFound ) , valuesNotFound ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of all codecs supported for this Object . [CODESPLIT] public java . util . Collection < Codec . ID > getSupportedCodecs ( ) { final java . util . List < Codec . ID > retval = new java . util . LinkedList < Codec . ID > ( ) ; final java . util . Set < Codec . ID > uniqueSet = new java . util . HashSet < Codec . ID > ( ) ; int numCodecs = getNumSupportedCodecs ( ) ; for ( int i = 0 ; i < numCodecs ; i ++ ) { Codec . ID id = getSupportedCodecId ( i ) ; // remove duplicate IDs if ( id != Codec . ID . CODEC_ID_NONE && ! uniqueSet . contains ( id ) ) retval . add ( id ) ; uniqueSet . add ( id ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of all codec tags supported for this container . [CODESPLIT] public java . util . Collection < Long > getSupportedTags ( ) { final java . util . List < Long > retval = new java . util . LinkedList < Long > ( ) ; final java . util . Set < Long > uniqueSet = new java . util . HashSet < Long > ( ) ; int numCodecs = getNumSupportedCodecs ( ) ; for ( int i = 0 ; i < numCodecs ; i ++ ) { long tag = getSupportedCodecTag ( i ) ; Codec . ID id = getSupportedCodecId ( i ) ; // remove duplicate tags if ( id != Codec . ID . CODEC_ID_NONE && ! uniqueSet . contains ( tag ) ) retval . add ( tag ) ; uniqueSet . add ( tag ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Codec . ID for the n th codec supported by this container . <br > <br > [CODESPLIT] protected Codec . ID getSupportedCodecId ( int n ) { return Codec . ID . swigToEnum ( VideoJNI . ContainerFormat_getSupportedCodecId ( swigCPtr , this , n ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the number of Ferry objects we believe are still in use . <p > This may be different than what you think because the Java garbage collector may not have collected all objects yet . < / p > <p > Also this method needs to walk the entire ferry reference heap so it can be expensive and not accurate ( as the value may change even before this method returns ) . Use only for debugging . < / p > [CODESPLIT] public long getNumPinnedObjects ( ) { long numPinnedObjects = 0 ; blockingLock ( ) ; try { int numItems = mNextAvailableReferenceSlot ; for ( int i = 0 ; i < numItems ; i ++ ) { JNIReference ref = mValidReferences [ i ] ; if ( ref != null && ! ref . isDeleted ( ) ) ++ numPinnedObjects ; } } finally { blockingUnlock ( ) ; } return numPinnedObjects ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump the contents of our memory cache to the log . <p > This method requires a global lock in order to run so only use for debugging . < / p > [CODESPLIT] public void dumpMemoryLog ( ) { blockingLock ( ) ; try { int numItems = mNextAvailableReferenceSlot ; log . debug ( \"Memory slots in use: {}\" , numItems ) ; for ( int i = 0 ; i < numItems ; i ++ ) { JNIReference ref = mValidReferences [ i ] ; if ( ref != null ) log . debug ( \"Slot: {}; Ref: {}\" , i , ref ) ; } } finally { blockingUnlock ( ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a reference to the set of references we ll collect . [CODESPLIT] final boolean addReference ( final JNIReference ref ) { /* Implementation note: This method is extremely\n     * hot, and so I've unrolled the lock and unlock\n     * methods from above.  Take care if you change\n     * them to change the unrolled versions here.\n     * \n     */ // First try to grab the non blocking lock boolean gotNonblockingLock = false ; gotNonblockingLock = mSpinLock . compareAndSet ( false , true ) ; if ( gotNonblockingLock ) { final int slot = mNextAvailableReferenceSlot ++ ; if ( slot < mMaxValidReference ) { mValidReferences [ slot ] = ref ; // unlock the non-blocking lock, and progress to a full lock. final boolean result = mSpinLock . compareAndSet ( true , false ) ; assert result : \"Should never be unlocked here\" ; return true ; } // try the big lock without blocking if ( ! mLock . tryLock ( ) ) { // we couldn't get the big lock, so release the spin lock // and try getting the bit lock while blocking gotNonblockingLock = false ; mSpinLock . compareAndSet ( true , false ) ; } } // The above code needs to make sure that we never // have gotNonblockingLock set, unless we have both // the spin lock and the big lock. if ( ! gotNonblockingLock ) { mLock . lock ( ) ; while ( ! mSpinLock . compareAndSet ( false , true ) ) ; // grab the spin lock } try { int slot = mNextAvailableReferenceSlot ++ ; if ( slot >= mMaxValidReference ) { sweepAndCollect ( ) ; slot = mNextAvailableReferenceSlot ++ ; } mValidReferences [ slot ] = ref ; } finally { final boolean result = mSpinLock . compareAndSet ( true , false ) ; assert result : \"Should never ever be unlocked here\" ; mLock . unlock ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The actual GC ; [CODESPLIT] void gcInternal ( ) { JNIReference ref = null ; while ( ( ref = ( JNIReference ) mRefQueue . poll ( ) ) != null ) { ref . delete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts a new Ferry collection thread that will wake up whenever a memory reference needs clean - up from native code . <p > This thread is not started by default as Ferry calls { [CODESPLIT] public void startCollectionThread ( ) { synchronized ( this ) { if ( mCollectionThread != null ) throw new RuntimeException ( \"Thread already running\" ) ; mCollectionThread = new Thread ( new Runnable ( ) { public void run ( ) { JNIReference ref = null ; try { while ( true ) { ref = ( JNIReference ) mRefQueue . remove ( ) ; if ( ref != null ) ref . delete ( ) ; } } catch ( InterruptedException ex ) { synchronized ( JNIMemoryManager . this ) { mCollectionThread = null ; // reset the interruption Thread . currentThread ( ) . interrupt ( ) ; } return ; } } } , \"Humble Ferry Collection Thread\" ) ; mCollectionThread . setDaemon ( true ) ; mCollectionThread . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal Only . [CODESPLIT] final public void flush ( ) { blockingLock ( ) ; try { int numSurvivors = sweepAndCollect ( ) ; for ( int i = 0 ; i < numSurvivors ; i ++ ) { final JNIReference ref = mValidReferences [ i ] ; if ( ref != null ) ref . delete ( ) ; } sweepAndCollect ( ) ; // finally, reset the valid references to the minimum mValidReferences = new JNIReference [ mMinimumReferencesToCache ] ; mNextAvailableReferenceSlot = 0 ; mMaxValidReference = mMinimumReferencesToCache ; } finally { blockingUnlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal Only . Allocate a new block of bytes . Called from native code . <p > Will retry many times if it can t get memory backing off in timeouts to get there . < / p > <p > Callers must eventually call { [CODESPLIT] public byte [ ] malloc ( int size ) { byte [ ] retval = null ; // first check the parachute JNIMemoryParachute . getParachute ( ) . packChute ( ) ; try { if ( SHOULD_RETRY_FAILED_ALLOCS ) { int allocationAttempts = 0 ; int backoffTimeout = 10 ; // start at 10 milliseconds while ( true ) { try { // log.debug(\"attempting malloc of size: {}\", size); retval = new byte [ size ] ; // log.debug(\"malloced block of size: {}\", size); // we succeed, so break out break ; } catch ( final OutOfMemoryError e ) { // try clearing our queue now and do it again. Why? // because the first failure may have allowed us to // catch a RefCounted no longer in use, and the second // attempt may have freed that memory. // do a JNI collect before the alloc ++ allocationAttempts ; if ( allocationAttempts >= MAX_ALLOCATION_ATTEMPTS ) { // try pulling our rip cord JNIMemoryParachute . getParachute ( ) . pullCord ( ) ; // do one last \"hope gc\" to free our own memory JNIReference . getMgr ( ) . gcInternal ( ) ; // and throw the error back to the native code throw e ; } log . debug ( \"retrying ({}) allocation of {} bytes\" , allocationAttempts , size ) ; try { // give the finalizer a chance if ( allocationAttempts <= 1 ) { // first just yield Thread . yield ( ) ; } else { Thread . sleep ( backoffTimeout ) ; // and slowly get longer... backoffTimeout = ( int ) ( backoffTimeout * FALLBACK_TIME_DECAY ) ; } } catch ( InterruptedException e1 ) { // reset the interruption so underlying // code can also interrupt Thread . currentThread ( ) . interrupt ( ) ; // and throw the error condition throw e ; } // do a JNI collect before the alloc JNIReference . getMgr ( ) . gcInternal ( ) ; } } } else { retval = new byte [ size ] ; } addToBuffer ( retval ) ; retval [ retval . length - 1 ] = 0 ; //      log.debug(\"malloc: {}({}:{})\", new Object[] //      { //          retval.hashCode(), retval.length, size //      }); } catch ( Throwable t ) { // do not let an exception leak out since we go back to native code. retval = null ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a picture to this source . NOTE : If you add a picture to a FilterSource<br > be careful with re - using or rewriting the underlying data . Filters will<br > try hard to avoid copying data so if you change the data out from under<br > them unexpected results can occur . <br > [CODESPLIT] public void addPicture ( MediaPicture picture ) { VideoJNI . FilterPictureSource_addPicture ( swigCPtr , this , MediaPicture . getCPtr ( picture ) , picture ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the given library into the given application . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) public static void load ( String appname , JNILibrary library ) { // we force ALL work on all libraries to be synchronized synchronized ( mLock ) { deleteTemporaryFiles ( ) ; try { library . load ( appname ) ; } catch ( UnsatisfiedLinkError e ) { // failed; faill back to old way JNILibraryLoader . loadLibrary ( library . getName ( ) , library . getVersion ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks for a URL in a classpath and if found unpacks it [CODESPLIT] private boolean unpackLibrary ( String path ) { boolean retval = false ; try { final Enumeration < URL > c = JNILibrary . class . getClassLoader ( ) . getResources ( path ) ; while ( c . hasMoreElements ( ) ) { final URL url = c . nextElement ( ) ; log . trace ( \"path: {}; url: {}\" , path , url ) ; if ( url == null ) return false ; boolean unpacked = false ; File lib ; if ( url . getProtocol ( ) . toLowerCase ( ) . equals ( \"file\" ) ) { // it SHOULD already exist on the disk. let's look for it. try { lib = new File ( new URI ( url . toString ( ) ) ) ; } catch ( URISyntaxException e ) { lib = new File ( url . getPath ( ) ) ; } if ( ! lib . exists ( ) ) { log . error ( \"Unpacked library not unpacked correctedly;  url: {}\" , url ) ; continue ; } } else if ( url . getProtocol ( ) . toLowerCase ( ) . equals ( \"jar\" ) ) { // sucktastic -- we cannot in a JVM load a shared library // directly from a JAR, so we need to unpack to a temp // directory and load from there. InputStream stream = url . openStream ( ) ; if ( stream == null ) { log . error ( \"could not get stream for resource: {}\" , url . getPath ( ) ) ; continue ; } FileOutputStream out = null ; try { File dir = getTmpDir ( ) ; // did you know windows REQUIRES .dll. Sigh. lib = File . createTempFile ( \"humble\" , JNIEnv . getEnv ( ) . getOSFamily ( ) == JNIEnv . OSFamily . WINDOWS ? \".dll\" : null , dir ) ; lib . deleteOnExit ( ) ; out = new FileOutputStream ( lib ) ; int bytesRead = 0 ; final byte [ ] buffer = new byte [ 2048 ] ; while ( ( bytesRead = stream . read ( buffer , 0 , buffer . length ) ) > 0 ) { out . write ( buffer , 0 , bytesRead ) ; } unpacked = true ; } catch ( IOException e ) { log . error ( \"could not create temp file: {}\" , e ) ; continue ; } finally { try { stream . close ( ) ; } catch ( IOException e ) { } if ( out != null ) try { out . close ( ) ; } catch ( IOException e ) { } } try { doJNILoad ( lib . getAbsolutePath ( ) ) ; retval = true ; break ; } catch ( UnsatisfiedLinkError e ) { // expected in some cases, try the next case. } finally { if ( unpacked ) { // Well let's try to clean up after ourselves since // we had ot unpack. deleteUnpackedFile ( lib . getAbsolutePath ( ) ) ; } } } } } catch ( IOException e1 ) { retval = false ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all . humble temp files in the temp directory and nukes them . [CODESPLIT] private static void deleteTemporaryFiles ( ) { final File dir = getTmpDir ( ) ; final FilenameFilter filter = new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( HUMBLE_TEMP_EXTENSION ) ; } } ; final File markers [ ] = dir . listFiles ( filter ) ; for ( File marker : markers ) { final String markerName = marker . getName ( ) ; final String libName = markerName . substring ( 0 , markerName . length ( ) - HUMBLE_TEMP_EXTENSION . length ( ) ) ; final File lib = new File ( marker . getParentFile ( ) , libName ) ; if ( ! lib . exists ( ) || lib . delete ( ) ) marker . delete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return default channel layout for a given number of channels . [CODESPLIT] public static AudioChannel . Layout getDefaultLayout ( int numChannels ) { return AudioChannel . Layout . swigToEnum ( VideoJNI . AudioChannel_getDefaultLayout ( numChannels ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the index of a channel in channel_layout . <br > <br > <p > <br > Use this method to find out which index into channel data corresponds<br > to the channel you care about . The way you use this differs depending<br > on whether your audio is packed or planar . To illustrate let s assume<br > you have CH_LAYOUT_STEREO audio and you ask for the index of CH_FRONT_LEFT <br > and we return 1 ( indexes are zero based ) . <br > < / p > <p > <br > If packed then audio is laid out in one big buffer as RLRLRLRLRLRLRLRL audio <br > and every 2nd ( 1 + 1 ) sample is the left channel<br > < / p > <p > <br > If planar then audio is out in two buffer as RRRRRRRR and LLLLLLLL and the<br > second plan ( 1 + 1 ) is the left channel . <br > < / p > <br > <br > [CODESPLIT] public static int getIndexOfChannelInLayout ( AudioChannel . Layout layout , AudioChannel . Type channel ) { return VideoJNI . AudioChannel_getIndexOfChannelInLayout ( layout . swigValue ( ) , channel . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the channel with the given index in channel_layout . [CODESPLIT] public static AudioChannel . Type getChannelFromLayoutAtIndex ( AudioChannel . Layout layout , int index ) { return AudioChannel . Type . swigToEnum ( VideoJNI . AudioChannel_getChannelFromLayoutAtIndex ( layout . swigValue ( ) , index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the pixel format corresponding to name . <br > <br > If there is no pixel format with name name then looks for a<br > pixel format with the name corresponding to the native endian<br > format of name . <br > For example in a little - endian system first looks for gray16 <br > then for gray16le . <br > <br > Finally if no pixel format has been found returns AV_PIX_FMT_NONE . [CODESPLIT] public static PixelFormat . Type getFormat ( String name ) { return PixelFormat . Type . swigToEnum ( VideoJNI . PixelFormat_getFormat ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the i th pixel format descriptor that is known to humble video<br > <br > [CODESPLIT] public static PixelFormatDescriptor getInstalledFormatDescriptor ( int i ) { long cPtr = VideoJNI . PixelFormat_getInstalledFormatDescriptor ( i ) ; return ( cPtr == 0 ) ? null : new PixelFormatDescriptor ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility function to swap the endianness of a pixel format . <br > <br > pix_fmt the pixel format<br > <br > [CODESPLIT] public static PixelFormat . Type swapEndianness ( PixelFormat . Type pix_fmt ) { return PixelFormat . Type . swigToEnum ( VideoJNI . PixelFormat_swapEndianness ( pix_fmt . swigValue ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the buffer size that would be necessary to store an image<br > with the given qualities . [CODESPLIT] public static int getBufferSizeNeeded ( int width , int height , PixelFormat . Type pix_fmt ) { return VideoJNI . PixelFormat_getBufferSizeNeeded ( width , height , pix_fmt . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Packet [CODESPLIT] public static MediaPacket make ( ) { long cPtr = VideoJNI . MediaPacket_make__SWIG_0 ( ) ; return ( cPtr == 0 ) ? null : new MediaPacket ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a new packet that wraps an existing Buffer . <br > <br > NOTE : At least 16 bytes of the passed in buffer will be used<br > for header information so the resulting Packet . getSize () <br > will be smaller than Buffer . getBufferSize () . <br > <br > [CODESPLIT] public static MediaPacket make ( Buffer buffer ) { long cPtr = VideoJNI . MediaPacket_make__SWIG_1 ( Buffer . getCPtr ( buffer ) , buffer ) ; return ( cPtr == 0 ) ? null : new MediaPacket ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a new packet wrapping the existing contents of<br > a passed in packet . Callers can then modify<br > #getPts () <br > #getDts () and other get / set methods without<br > modifying the original packet . <br > <br > [CODESPLIT] public static MediaPacket make ( MediaPacket packet , boolean copyData ) { long cPtr = VideoJNI . MediaPacket_make__SWIG_2 ( MediaPacket . getCPtr ( packet ) , packet , copyData ) ; return ( cPtr == 0 ) ? null : new MediaPacket ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a new packet . <br > <p > <br > Note that any buffers this packet needs will be<br > lazily allocated ( i . e . we won t actually grab all<br > the memory until we need it ) . <br > < / p > <br > [CODESPLIT] public static MediaPacket make ( int size ) { long cPtr = VideoJNI . MediaPacket_make__SWIG_3 ( size ) ; return ( cPtr == 0 ) ? null : new MediaPacket ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get any underlying raw data available for this packet . <br > <br > [CODESPLIT] public Buffer getData ( ) { long cPtr = VideoJNI . MediaPacket_getData ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Buffer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the n th item of SideData . <br > <p > <br > WARNING : Callers must ensure that the the packet object<br > this is called form is NOT reset or destroyed while using this buffer <br > as unfortunately we cannot ensure this buffer survives the<br > underlying packet data . <br > < / p > <br > <br > [CODESPLIT] public Buffer getSideData ( int n ) { long cPtr = VideoJNI . MediaPacket_getSideData ( swigCPtr , this , n ) ; return ( cPtr == 0 ) ? null : new Buffer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the n th item of SideData . <br > <br > [CODESPLIT] public MediaPacket . SideDataType getSideDataType ( int n ) { return MediaPacket . SideDataType . swigToEnum ( VideoJNI . MediaPacket_getSideDataType ( swigCPtr , this , n ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a given filter by name . <br > <br > [CODESPLIT] public static FilterType findFilterType ( String name ) { long cPtr = VideoJNI . FilterType_findFilterType ( name ) ; return ( cPtr == 0 ) ? null : new FilterType ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int open ( String url , int flags ) { if ( mOpenStream != null ) { log . debug ( \"attempting to open already open handler: {}\" , mOpenStream ) ; return - 1 ; } switch ( flags ) { case URL_RDWR : if ( mDataInput != null && mDataOutput != null && mDataInput == mDataOutput && mDataInput instanceof RandomAccessFile ) { mOpenStream = mDataInput ; } else { log . debug ( \"do not support read/write mode for Java IO Handlers\" ) ; return - 1 ; } break ; case URL_WRONLY_MODE : mOpenStream = mDataOutput ; if ( mOpenStream == null ) { log . error ( \"No OutputStream specified for writing: {}\" , url ) ; return - 1 ; } break ; case URL_RDONLY_MODE : mOpenStream = mDataInput ; if ( mOpenStream == null ) { log . error ( \"No InputStream specified for reading: {}\" , url ) ; return - 1 ; } break ; default : log . error ( \"Invalid flag passed to open: {}\" , url ) ; return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int read ( byte [ ] buf , int size ) { int ret = - 1 ; if ( mOpenStream == null || ! ( mOpenStream instanceof DataInput ) ) return - 1 ; try { if ( mOpenStream instanceof RandomAccessFile ) { RandomAccessFile file = ( RandomAccessFile ) mOpenStream ; return file . read ( buf , 0 , size ) ; } else if ( mOpenStream instanceof DataInputStream ) { DataInputStream stream = ( DataInputStream ) mOpenStream ; return stream . read ( buf , 0 , size ) ; } else { DataInput input = ( DataInput ) mOpenStream ; try { input . readFully ( buf , 0 , size ) ; ret = size ; } catch ( EOFException e ) { // man; we have no idea how many bytes were actually // read now... so we truncate the data // what a sucky interface! ret = - 1 ; } return ret ; } } catch ( IOException e ) { log . error ( \"Got IO exception reading from channel: {}; {}\" , mOpenStream , e ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public long seek ( long offset , int whence ) { if ( mOpenStream == null ) return - 1 ; if ( ! ( mOpenStream instanceof RandomAccessFile ) ) return - 1 ; final RandomAccessFile file = ( RandomAccessFile ) mOpenStream ; try { final long seek ; if ( whence == SEEK_SET ) seek = offset ; else if ( whence == SEEK_CUR ) seek = file . getFilePointer ( ) + offset ; else if ( whence == SEEK_END ) seek = file . length ( ) + offset ; else if ( whence == SEEK_SIZE ) // odd feature of the protocol handler; this request // just returns the file size without actually seeking return ( int ) file . length ( ) ; else { log . error ( \"invalid seek value \\\"{}\\\" for file: {}\" , whence , file ) ; return - 1 ; } file . seek ( seek ) ; return seek ; } catch ( IOException e ) { log . debug ( \"got io exception \\\"{}\\\" while seeking in: {}\" , e . getMessage ( ) , file ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int write ( byte [ ] buf , int size ) { if ( mOpenStream == null || ! ( mOpenStream instanceof DataOutput ) ) return - 1 ; try { DataOutput output = ( DataOutput ) mOpenStream ; output . write ( buf , 0 , size ) ; return size ; } catch ( IOException e ) { log . error ( \"Got error writing to file: {}; {}\" , mOpenStream , e ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean isStreamed ( String url , int flags ) { if ( mDataInput != null && mDataInput instanceof RandomAccessFile ) return false ; if ( mDataOutput != null && mDataOutput instanceof RandomAccessFile ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parameters that describe how pixels are packed . <br > If the format has 2 or 4 components then alpha is last . <br > If the format has 1 or 2 components then luma is 0 . <br > If the format has 3 or 4 components <br > if the RGB flag is set then 0 is red 1 is green and 2 is blue ; <br > otherwise 0 is luma 1 is chroma - U and 2 is chroma - V . [CODESPLIT] public PixelComponentDescriptor getComponentDescriptor ( int component ) { long cPtr = VideoJNI . PixelFormatDescriptor_getComponentDescriptor ( swigCPtr , this , component ) ; return ( cPtr == 0 ) ? null : new PixelComponentDescriptor ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the version of this library to System . out along with some information on what this jar is . [CODESPLIT] public static String getVersionInfo ( ) { final Class < ? > c = Version . class ; final StringBuilder b = new StringBuilder ( ) ; final Package p = c . getPackage ( ) ; b . append ( \"Class: \" + c . getCanonicalName ( ) + \"; \" ) ; b . append ( \"Specification Vendor: \" + p . getSpecificationVendor ( ) + \"; \" ) ; b . append ( \"Specification Title: \" + p . getSpecificationTitle ( ) + \"; \" ) ; b . append ( \"Specification Version: \" + p . getSpecificationVersion ( ) + \"; \" ) ; b . append ( \"Implementation Vendor: \" + p . getImplementationVendor ( ) + \"; \" ) ; b . append ( \"Implementation Title: \" + p . getImplementationTitle ( ) + \"; \" ) ; b . append ( \"Implementation Version: \" + p . getImplementationVersion ( ) + \";\" ) ; return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default timebase used by media if not otherwise specified . [CODESPLIT] public static Rational getDefaultTimeBase ( ) { long cPtr = VideoJNI . Global_getDefaultTimeBase ( ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this IProperty is of the type Type#PROPERTY_FLAGS this method will<br > give you another IProperty representing a constant setting for that flag . <br > <br > [CODESPLIT] public Property getFlagConstant ( int position ) { long cPtr = VideoJNI . Property_getFlagConstant__SWIG_0 ( swigCPtr , this , position ) ; return ( cPtr == 0 ) ? null : new Property ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this IProperty is of the type Type#PROPERTY_FLAGS this method will<br > give you another IProperty representing a constant setting for that flag . <br > <br > [CODESPLIT] public Property getFlagConstant ( String name ) { long cPtr = VideoJNI . Property_getFlagConstant__SWIG_1 ( swigCPtr , this , name ) ; return ( cPtr == 0 ) ? null : new Property ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Demuxer [CODESPLIT] public static Demuxer make ( ) { long cPtr = VideoJNI . Demuxer_make ( ) ; return ( cPtr == 0 ) ? null : new Demuxer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the DemuxerFormat associated with this Demuxer<br > or null if unknown . [CODESPLIT] public DemuxerFormat getFormat ( ) { long cPtr = VideoJNI . Demuxer_getFormat ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new DemuxerFormat ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open this container and make it ready for reading optionally<br > reading as far into the container as necessary to find all streams . <br > <p > The caller must call #close () when done but if not the<br > Demuxer will eventually close<br > them later but warn to the logging system . <br > <br > [CODESPLIT] public void open ( String url , DemuxerFormat format , boolean streamsCanBeAddedDynamically , boolean queryStreamMetaData , KeyValueBag options , KeyValueBag optionsNotSet ) throws java . lang . InterruptedException , java . io . IOException { VideoJNI . Demuxer_open ( swigCPtr , this , url , DemuxerFormat . getCPtr ( format ) , format , streamsCanBeAddedDynamically , queryStreamMetaData , KeyValueBag . getCPtr ( options ) , options , KeyValueBag . getCPtr ( optionsNotSet ) , optionsNotSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the container . open () must have been called first or<br > else an error is returned . <br > <p > <br > If this method exits because of an interruption <br > all resources will be closed anyway . <br > < / p > [CODESPLIT] public void close ( ) throws java . lang . InterruptedException , java . io . IOException { VideoJNI . Demuxer_close ( swigCPtr , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the stream at the given position . <br > <br > [CODESPLIT] public DemuxerStream getStream ( int streamIndex ) throws java . lang . InterruptedException , java . io . IOException { long cPtr = VideoJNI . Demuxer_getStream ( swigCPtr , this , streamIndex ) ; return ( cPtr == 0 ) ? null : new DemuxerStream ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the next packet in the Demuxer into the Packet . This method will<br > release any buffers currently held by this packet and allocate<br > new ones . <br > <p > <br > For non - blocking IO data sources it is possible for this method<br > to return as successful but with no complete packet . In that case<br > the caller should retry again later ( think EAGAIN ) semantics . <br > < / p > <br > <br > [CODESPLIT] public int read ( MediaPacket packet ) throws java . lang . InterruptedException , java . io . IOException { return VideoJNI . Demuxer_read ( swigCPtr , this , MediaPacket . getCPtr ( packet ) , packet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to read all the meta data in this stream potentially by reading ahead<br > and decoding packets . <br > <p > <br > Any packets this method reads ahead will be cached and correctly returned when you<br > read packets but this method can be non - blocking potentially until end of container<br > to get all meta data . Take care when you call it . <br > < / p > <p > After this method is called other meta data methods like #getDuration () should<br > work . < / p > [CODESPLIT] public void queryStreamMetaData ( ) throws java . lang . InterruptedException , java . io . IOException { VideoJNI . Demuxer_queryStreamMetaData ( swigCPtr , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the flag . <br > <br > [CODESPLIT] public void setFlag ( Container . Flag flag , boolean value ) { VideoJNI . Demuxer_setFlag ( swigCPtr , this , flag . swigValue ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the KeyValueBag of media MetaData for this object <br > or null if none . <br > <p > <br > If the Demuxer or IStream object<br > that this KeyValueBag came from was opened<br > for reading then changes via KeyValueBag#setValue ( String String ) <br > will have no effect on the underlying media . <br > < / p > <br > <p > <br > If the Demuxer or IStream object<br > that this KeyValueBag came from was opened<br > for writing then changes via KeyValueBag#setValue ( String String ) <br > will have no effect after Demuxer#writeHeader () <br > is called . <br > < / p > <br > [CODESPLIT] public KeyValueBag getMetaData ( ) { long cPtr = VideoJNI . Demuxer_getMetaData ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new KeyValueBag ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Seek to timestamp ts . <br > <br > Seeking will be done so that the point from which all active streams<br > can be presented successfully will be closest to ts and within min / max_ts . <br > Active streams are all streams that have Stream . getDiscardSetting &lt ; <br > Codec . DISCARD_ALL . <br > <br > If flags contain SeekFlags . SEEK_BYTE then all timestamps are in bytes and<br > are the file position ( this may not be supported by all demuxers ) . <br > If flags contain SeekFlags . SEEK_FRAME then all timestamps are in frames<br > in the stream with stream_index ( this may not be supported by all demuxers ) . <br > Otherwise all timestamps are in units of the stream selected by stream_index<br > or if stream_index is - 1 in ( 1 / Global . DEFAULT_PTS_MICROSECONDS } units . <br > If flags contain SeekFlags . SEEK_ANY then non - keyframes are treated as<br > keyframes ( this may not be supported by all demuxers ) . <br > <br > [CODESPLIT] public int seek ( int stream_index , long min_ts , long ts , long max_ts , int flags ) throws java . lang . InterruptedException , java . io . IOException { return VideoJNI . Demuxer_seek ( swigCPtr , this , stream_index , min_ts , ts , max_ts , flags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start playing a network source . Call #pause () to pause . [CODESPLIT] public void play ( ) throws java . lang . InterruptedException , java . io . IOException { VideoJNI . Demuxer_play ( swigCPtr , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pause a playing network source . Call #play () to unpause . <br > <br > [CODESPLIT] public void pause ( ) throws java . lang . InterruptedException , java . io . IOException { VideoJNI . Demuxer_pause ( swigCPtr , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new IRational object by copying ( by value ) this object . <br > <br > [CODESPLIT] public Rational copy ( ) { long cPtr = VideoJNI . Rational_copy ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare a rational to this rational<br > [CODESPLIT] public int compareTo ( Rational other ) { return VideoJNI . Rational_compareTo ( swigCPtr , this , Rational . getCPtr ( other ) , other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare two rationals<br > [CODESPLIT] public static int sCompareTo ( Rational a , Rational b ) { return VideoJNI . Rational_sCompareTo ( Rational . getCPtr ( a ) , a , Rational . getCPtr ( b ) , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduce a fraction to it s lowest common denominators . <br > This is useful for framerate calculations . <br > [CODESPLIT] public int reduce ( long num , long den , long max ) { return VideoJNI . Rational_reduce ( swigCPtr , this , num , den , max ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduce a fraction to it s lowest common denominators . <br > This is useful for framerate calculations . <br > [CODESPLIT] public static int sReduce ( Rational dst , long num , long den , long max ) { return VideoJNI . Rational_sReduce ( Rational . getCPtr ( dst ) , dst , num , den , max ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiplies this number by arg<br > [CODESPLIT] public Rational multiply ( Rational arg ) { long cPtr = VideoJNI . Rational_multiply ( swigCPtr , this , Rational . getCPtr ( arg ) , arg ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiples a by b . <br > [CODESPLIT] public static Rational sMultiply ( Rational a , Rational b ) { long cPtr = VideoJNI . Rational_sMultiply ( Rational . getCPtr ( a ) , a , Rational . getCPtr ( b ) , b ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divides this rational by arg . <br > [CODESPLIT] public Rational divide ( Rational arg ) { long cPtr = VideoJNI . Rational_divide ( swigCPtr , this , Rational . getCPtr ( arg ) , arg ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divides a by b . <br > [CODESPLIT] public static Rational sDivide ( Rational a , Rational b ) { long cPtr = VideoJNI . Rational_sDivide ( Rational . getCPtr ( a ) , a , Rational . getCPtr ( b ) , b ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtracts arg from this rational<br > [CODESPLIT] public Rational subtract ( Rational arg ) { long cPtr = VideoJNI . Rational_subtract ( swigCPtr , this , Rational . getCPtr ( arg ) , arg ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtracts a from b . <br > [CODESPLIT] public static Rational sSubtract ( Rational a , Rational b ) { long cPtr = VideoJNI . Rational_sSubtract ( Rational . getCPtr ( a ) , a , Rational . getCPtr ( b ) , b ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds arg to this rational<br > [CODESPLIT] public Rational add ( Rational arg ) { long cPtr = VideoJNI . Rational_add ( swigCPtr , this , Rational . getCPtr ( arg ) , arg ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a to b . <br > [CODESPLIT] public static Rational sAdd ( Rational a , Rational b ) { long cPtr = VideoJNI . Rational_sAdd ( Rational . getCPtr ( a ) , a , Rational . getCPtr ( b ) , b ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a value scaled in increments of origBase and gives the<br > equivalent value scaled in terms of this Rational . <br > <br > [CODESPLIT] public long rescale ( long origValue , Rational origBase ) { return VideoJNI . Rational_rescale__SWIG_0 ( swigCPtr , this , origValue , Rational . getCPtr ( origBase ) , origBase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a value scaled in increments of origBase and gives the<br > equivalent value scaled in terms of this Rational . <br > <br > [CODESPLIT] public static long sRescale ( long origValue , Rational origBase , Rational newBase ) { return VideoJNI . Rational_sRescale__SWIG_0 ( origValue , Rational . getCPtr ( origBase ) , origBase , Rational . getCPtr ( newBase ) , newBase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a new rational that will be set to 0 / 1 . <br > The rational will not have #init () called<br > and hence will be modifiable by #setValue ( double ) <br > until #init () is called . <br > [CODESPLIT] public static Rational make ( ) { long cPtr = VideoJNI . Rational_make__SWIG_0 ( ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a double precision floating point number to a rational . <br > [CODESPLIT] public static Rational make ( double d ) { long cPtr = VideoJNI . Rational_make__SWIG_1 ( d ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates deep copy of a Rational from another Rational . <br > <br > [CODESPLIT] public static Rational make ( Rational src ) { long cPtr = VideoJNI . Rational_make__SWIG_2 ( Rational . getCPtr ( src ) , src ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a rational from a numerator and denominator . <br > <br > We will always reduce this to the lowest num / den pair<br > we can but never having den exceed what was passed in . <br > <br > [CODESPLIT] public static Rational make ( int num , int den ) { long cPtr = VideoJNI . Rational_make__SWIG_3 ( num , den ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a value scaled in increments of origBase and gives the<br > equivalent value scaled in terms of this Rational . <br > <br > [CODESPLIT] public long rescale ( long origValue , Rational origBase , Rational . Rounding rounding ) { return VideoJNI . Rational_rescale__SWIG_1 ( swigCPtr , this , origValue , Rational . getCPtr ( origBase ) , origBase , rounding . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a value scaled in increments of origBase and gives the<br > equivalent value scaled in terms of this Rational . <br > <br > [CODESPLIT] public static long sRescale ( long origValue , Rational origBase , Rational newBase , Rational . Rounding rounding ) { return VideoJNI . Rational_sRescale__SWIG_1 ( origValue , Rational . getCPtr ( origBase ) , origBase , Rational . getCPtr ( newBase ) , newBase , rounding . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rescales a long value to another long value . <br > <p > <br > This method doesn t use IRational values but<br > instead uses numerators and denominators<br > passed in by the caller . It will not result<br > in any memory allocations . <br > < / p > <br > <br > [CODESPLIT] public static long rescale ( long srcValue , int dstNumerator , int dstDenominator , int srcNumerator , int srcDenominator , Rational . Rounding rounding ) { return VideoJNI . Rational_rescale__SWIG_2 ( srcValue , dstNumerator , dstDenominator , srcNumerator , srcDenominator , rounding . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a file and plays the video from it on a screen at the right rate . [CODESPLIT] private static void playVideo ( String filename ) throws InterruptedException , IOException { /*\n     * Start by creating a container object, in this case a demuxer since\n     * we are reading, to get video data from.\n     */ Demuxer demuxer = Demuxer . make ( ) ; /*\n     * Open the demuxer with the filename passed on.\n     */ demuxer . open ( filename , null , false , true , null , null ) ; /*\n     * Query how many streams the call to open found\n     */ int numStreams = demuxer . getNumStreams ( ) ; /*\n     * Iterate through the streams to find the first video stream\n     */ int videoStreamId = - 1 ; long streamStartTime = Global . NO_PTS ; Decoder videoDecoder = null ; for ( int i = 0 ; i < numStreams ; i ++ ) { final DemuxerStream stream = demuxer . getStream ( i ) ; streamStartTime = stream . getStartTime ( ) ; final Decoder decoder = stream . getDecoder ( ) ; if ( decoder != null && decoder . getCodecType ( ) == MediaDescriptor . Type . MEDIA_VIDEO ) { videoStreamId = i ; videoDecoder = decoder ; // stop at the first one. break ; } } if ( videoStreamId == - 1 ) throw new RuntimeException ( \"could not find video stream in container: \" + filename ) ; /*\n     * Now we have found the audio stream in this file.  Let's open up our decoder so it can\n     * do work.\n     */ videoDecoder . open ( null , null ) ; final MediaPicture picture = MediaPicture . make ( videoDecoder . getWidth ( ) , videoDecoder . getHeight ( ) , videoDecoder . getPixelFormat ( ) ) ; /** A converter object we'll use to convert the picture in the video to a BGR_24 format that Java Swing\n     * can work with. You can still access the data directly in the MediaPicture if you prefer, but this\n     * abstracts away from this demo most of that byte-conversion work. Go read the source code for the\n     * converters if you're a glutton for punishment.\n     */ final MediaPictureConverter converter = MediaPictureConverterFactory . createConverter ( MediaPictureConverterFactory . HUMBLE_BGR_24 , picture ) ; BufferedImage image = null ; /**\n     * This is the Window we will display in. See the code for this if you're curious, but to keep this demo clean\n     * we're 'simplifying' Java AWT UI updating code. This method just creates a single window on the UI thread, and blocks\n     * until it is displayed.\n     */ final ImageFrame window = ImageFrame . make ( ) ; if ( window == null ) { throw new RuntimeException ( \"Attempting this demo on a headless machine, and that will not work. Sad day for you.\" ) ; } /**\n     * Media playback, like comedy, is all about timing. Here we're going to introduce <b>very very basic</b>\n     * timing. This code is deliberately kept simple (i.e. doesn't worry about A/V drift, garbage collection pause time, etc.)\n     * because that will quickly make things more complicated. \n     * \n     * But the basic idea is there are two clocks:\n     * <ul>\n     * <li>Player Clock: The time that the player sees (relative to the system clock).</li>\n     * <li>Stream Clock: Each stream has its own clock, and the ticks are measured in units of time-bases</li>\n     * </ul>\n     * \n     * And we need to convert between the two units of time. Each MediaPicture and MediaAudio object have associated\n     * time stamps, and much of the complexity in video players goes into making sure the right picture (or sound) is\n     * seen (or heard) at the right time. This is actually very tricky and many folks get it wrong -- watch enough\n     * Netflix and you'll see what I mean -- audio and video slightly out of sync. But for this demo, we're erring for\n     * 'simplicity' of code, not correctness. It is beyond the scope of this demo to make a full fledged video player.\n     */ // Calculate the time BEFORE we start playing. long systemStartTime = System . nanoTime ( ) ; // Set units for the system time, which because we used System.nanoTime will be in nanoseconds. final Rational systemTimeBase = Rational . make ( 1 , 1000000000 ) ; // All the MediaPicture objects decoded from the videoDecoder will share this timebase. final Rational streamTimebase = videoDecoder . getTimeBase ( ) ; /**\n     * Now, we start walking through the container looking at each packet. This\n     * is a decoding loop, and as you work with Humble you'll write a lot\n     * of these.\n     * \n     * Notice how in this loop we reuse all of our objects to avoid\n     * reallocating them. Each call to Humble resets objects to avoid\n     * unnecessary reallocation.\n     */ final MediaPacket packet = MediaPacket . make ( ) ; while ( demuxer . read ( packet ) >= 0 ) { /**\n       * Now we have a packet, let's see if it belongs to our video stream\n       */ if ( packet . getStreamIndex ( ) == videoStreamId ) { /**\n         * A packet can actually contain multiple sets of samples (or frames of samples\n         * in decoding speak).  So, we may need to call decode  multiple\n         * times at different offsets in the packet's data.  We capture that here.\n         */ int offset = 0 ; int bytesRead = 0 ; do { bytesRead += videoDecoder . decode ( picture , packet , offset ) ; if ( picture . isComplete ( ) ) { image = displayVideoAtCorrectTime ( streamStartTime , picture , converter , image , window , systemStartTime , systemTimeBase , streamTimebase ) ; } offset += bytesRead ; } while ( offset < packet . getSize ( ) ) ; } } // Some video decoders (especially advanced ones) will cache // video data before they begin decoding, so when you are done you need // to flush them. The convention to flush Encoders or Decoders in Humble Video // is to keep passing in null until incomplete samples or packets are returned. do { videoDecoder . decode ( picture , null , 0 ) ; if ( picture . isComplete ( ) ) { image = displayVideoAtCorrectTime ( streamStartTime , picture , converter , image , window , systemStartTime , systemTimeBase , streamTimebase ) ; } } while ( picture . isComplete ( ) ) ; // It is good practice to close demuxers when you're done to free // up file handles. Humble will EVENTUALLY detect if nothing else // references this demuxer and close it then, but get in the habit // of cleaning up after yourself, and your future girlfriend/boyfriend // will appreciate it. demuxer . close ( ) ; // similar with the demuxer, for the windowing system, clean up after yourself. window . dispose ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes the video picture and displays it at the right time . [CODESPLIT] private static BufferedImage displayVideoAtCorrectTime ( long streamStartTime , final MediaPicture picture , final MediaPictureConverter converter , BufferedImage image , final ImageFrame window , long systemStartTime , final Rational systemTimeBase , final Rational streamTimebase ) throws InterruptedException { long streamTimestamp = picture . getTimeStamp ( ) ; // convert streamTimestamp into system units (i.e. nano-seconds) streamTimestamp = systemTimeBase . rescale ( streamTimestamp - streamStartTime , streamTimebase ) ; // get the current clock time, with our most accurate clock long systemTimestamp = System . nanoTime ( ) ; // loop in a sleeping loop until we're within 1 ms of the time for that video frame. // a real video player needs to be much more sophisticated than this. while ( streamTimestamp > ( systemTimestamp - systemStartTime + 1000000 ) ) { Thread . sleep ( 1 ) ; systemTimestamp = System . nanoTime ( ) ; } // finally, convert the image from Humble format into Java images. image = converter . toImage ( image , picture ) ; // And ask the UI thread to repaint with the new image. window . setImage ( image ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a collection of ALL codecs installed on this system . [CODESPLIT] public static java . util . Collection < BitStreamFilterType > getInstalledBitStreamFilterTypes ( ) { java . util . Collection < BitStreamFilterType > retval = new java . util . HashSet < BitStreamFilterType > ( ) ; int count = getNumBitStreamFilterTypes ( ) ; for ( int i = 0 ; i < count ; i ++ ) { BitStreamFilterType t = getBitStreamFilterType ( i ) ; if ( t != null ) retval . add ( t ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a converter . [CODESPLIT] public static MediaAudioConverter createConverter ( String description , MediaAudio protoAudio ) { return createConverter ( description , protoAudio . getSampleRate ( ) , protoAudio . getChannelLayout ( ) , protoAudio . getFormat ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a converter . [CODESPLIT] public static MediaAudioConverter createConverter ( String description , int sampleRate , Layout layout , Type format ) { if ( description != DEFAULT_JAVA_AUDIO ) throw new RuntimeException ( \"Unsupported converter type\" ) ; return new StereoS16AudioConverter ( sampleRate , layout , format ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Encoder that will use the given Codec . <br > <br > [CODESPLIT] public static Encoder make ( Codec codec ) { long cPtr = VideoJNI . Encoder_make__SWIG_0 ( Codec . getCPtr ( codec ) , codec ) ; return ( cPtr == 0 ) ? null : new Encoder ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Encoder from a given Encoder<br > [CODESPLIT] public static Encoder make ( Coder src ) { long cPtr = VideoJNI . Encoder_make__SWIG_1 ( Coder . getCPtr ( src ) , src ) ; return ( cPtr == 0 ) ? null : new Encoder ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open this Coder using the given bag of Codec - specific options . <br > <br > [CODESPLIT] public void open ( KeyValueBag inputOptions , KeyValueBag unsetOptions ) { VideoJNI . Encoder_open ( swigCPtr , this , KeyValueBag . getCPtr ( inputOptions ) , inputOptions , KeyValueBag . getCPtr ( unsetOptions ) , unsetOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the given MediaPicture using this encoder . <br > <br > The MediaPicture will allocate a buffer to use internally for this and<br > will free it when the frame destroys itself . <br > <br > Also when done in order to flush the encoder caller should call<br > this method passing in 0 ( null ) for frame to tell the encoder<br > to flush any data it was keeping a hold of . <br > <br > [CODESPLIT] public void encodeVideo ( MediaPacket output , MediaPicture picture ) { VideoJNI . Encoder_encodeVideo ( swigCPtr , this , MediaPacket . getCPtr ( output ) , output , MediaPicture . getCPtr ( picture ) , picture ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the given MediaAudio using this encoder . <br > <br > Callers should call this repeatedly on a set of samples until<br > we consume all the samples . <br > <br > Also when done in order to flush the encoder caller should call<br > this method passing in 0 ( null ) for samples to tell the encoder<br > to flush any data it was keeping a hold of . <br > <br > [CODESPLIT] public void encodeAudio ( MediaPacket output , MediaAudio samples ) { VideoJNI . Encoder_encodeAudio ( swigCPtr , this , MediaPacket . getCPtr ( output ) , output , MediaAudio . getCPtr ( samples ) , samples ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode the given Media using this encoder . <br > <br > Callers should call this repeatedly on a media object ntil<br > we consume all the media . <br > <br > Also when done in order to flush the encoder caller should call<br > this method passing in 0 ( null ) for media to tell the encoder<br > to flush any data it was keeping a hold of . <br > <br > [CODESPLIT] public void encode ( MediaPacket output , MediaSampled media ) { VideoJNI . Encoder_encode ( swigCPtr , this , MediaPacket . getCPtr ( output ) , output , MediaSampled . getCPtr ( media ) , media ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public MediaPicture toPicture ( MediaPicture output , final BufferedImage input , long timestamp ) { // validate the image validateImage ( input ) ; if ( output == null ) { output = MediaPicture . make ( mPictureWidth , mPictureHeight , getPictureType ( ) ) ; } // get the image byte buffer buffer DataBuffer imageBuffer = input . getRaster ( ) . getDataBuffer ( ) ; byte [ ] imageBytes = null ; int [ ] imageInts = null ; // handle byte buffer case if ( imageBuffer instanceof DataBufferByte ) { imageBytes = ( ( DataBufferByte ) imageBuffer ) . getData ( ) ; } // handle integer buffer case else if ( imageBuffer instanceof DataBufferInt ) { imageInts = ( ( DataBufferInt ) imageBuffer ) . getData ( ) ; } // if it's some other type, throw else { throw new IllegalArgumentException ( \"Unsupported BufferedImage data buffer type: \" + imageBuffer . getDataType ( ) ) ; } // create the video picture and get it's underlying buffer final AtomicReference < JNIReference > ref = new AtomicReference < JNIReference > ( null ) ; final MediaPicture picture = willResample ( ) ? mResampleMediaPicture : output ; try { Buffer buffer = picture . getData ( 0 ) ; int size = picture . getDataPlaneSize ( 0 ) ; ByteBuffer pictureByteBuffer = buffer . getByteBuffer ( 0 , size , ref ) ; buffer . delete ( ) ; buffer = null ; if ( imageInts != null ) { pictureByteBuffer . order ( ByteOrder . BIG_ENDIAN ) ; IntBuffer pictureIntBuffer = pictureByteBuffer . asIntBuffer ( ) ; pictureIntBuffer . put ( imageInts ) ; } else { pictureByteBuffer . put ( imageBytes ) ; } pictureByteBuffer = null ; picture . setTimeStamp ( timestamp ) ; picture . setComplete ( true ) ; // resample as needed if ( willResample ( ) ) { resample ( output , picture , mToPictureResampler ) ; } return output ; } finally { if ( ref . get ( ) != null ) ref . get ( ) . delete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BufferedImage toImage ( BufferedImage output , final MediaPicture input ) { validatePicture ( input ) ; // test that the picture is valid if ( output == null ) { final byte [ ] bytes = new byte [ willResample ( ) ? mResampleMediaPicture . getDataPlaneSize ( 0 ) : input . getDataPlaneSize ( 0 ) ] ; // create the data buffer from the bytes final DataBufferByte db = new DataBufferByte ( bytes , bytes . length ) ; // create an a sample model which matches the byte layout of the // image data and raster which contains the data which now can be // properly interpreted int w = mImageWidth ; int h = mImageHeight ; final SampleModel sm = new PixelInterleavedSampleModel ( db . getDataType ( ) , w , h , 3 , 3 * w , mBandOffsets ) ; final WritableRaster wr = Raster . createWritableRaster ( sm , db , null ) ; // create a color model final ColorModel colorModel = new ComponentColorModel ( mColorSpace , false , false , ColorModel . OPAQUE , db . getDataType ( ) ) ; // return a new image created from the color model and raster output = new BufferedImage ( colorModel , wr , false , null ) ; } MediaPicture picture ; // resample as needed AtomicReference < JNIReference > ref = new AtomicReference < JNIReference > ( null ) ; try { if ( willResample ( ) ) { picture = resample ( mResampleMediaPicture , input , mToImageResampler ) ; } else { picture = input ; } final Buffer buffer = picture . getData ( 0 ) ; final int size = picture . getDataPlaneSize ( 0 ) ; final ByteBuffer byteBuf = buffer . getByteBuffer ( 0 , size , ref ) ; buffer . delete ( ) ; // get the bytes out of the image final DataBufferByte db = ( DataBufferByte ) output . getRaster ( ) . getDataBuffer ( ) ; final byte [ ] bytes = db . getData ( ) ; // and copy them in. byteBuf . get ( bytes , 0 , size ) ; // return a new image created from the color model and raster return output ; } finally { if ( ref . get ( ) != null ) ref . get ( ) . delete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the descriptor for the given id . [CODESPLIT] public static CodecDescriptor make ( Codec . ID id ) { long cPtr = VideoJNI . CodecDescriptor_make ( id . swigValue ( ) ) ; return ( cPtr == 0 ) ? null : new CodecDescriptor ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out all configurable options on the { @link Configurable } object . [CODESPLIT] public static void printConfigurable ( java . io . PrintStream stream , Configurable configObj ) { stream . println ( \"=======================================\" ) ; stream . println ( \"  \" + configObj . getClass ( ) . getName ( ) + \" Properties\" ) ; stream . println ( \"=======================================\" ) ; int numOptions = configObj . getNumProperties ( ) ; for ( int i = 0 ; i < numOptions ; i ++ ) { Property prop = configObj . getPropertyMetaData ( i ) ; printOption ( stream , configObj , prop ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print information about the property on the configurable object . [CODESPLIT] public static void printOption ( java . io . PrintStream stream , Configurable configObj , Property prop ) { if ( prop . getType ( ) != Property . Type . PROPERTY_FLAGS ) { stream . printf ( \"  %s; default= %s; type=%s;\\n\" , prop . getName ( ) , configObj . getPropertyAsString ( prop . getName ( ) ) , prop . getType ( ) ) ; } else { // it's a flag stream . printf ( \"  %s; default= %d; valid values=(\" , prop . getName ( ) , configObj . getPropertyAsLong ( prop . getName ( ) ) ) ; int numSettings = prop . getNumFlagSettings ( ) ; long value = configObj . getPropertyAsLong ( prop . getName ( ) ) ; for ( int i = 0 ; i < numSettings ; i ++ ) { Property fprop = prop . getFlagConstant ( i ) ; long flagMask = fprop . getDefault ( ) ; boolean isSet = ( value & flagMask ) > 0 ; stream . printf ( \"%s%s; \" , isSet ? \"+\" : \"-\" , fprop . getName ( ) ) ; } stream . printf ( \"); type=%s;\\n\" , prop . getType ( ) ) ; } stream . printf ( \"    help for %s: %s\\n\" , prop . getName ( ) , prop . getHelp ( ) == null ? \"no help available\" : prop . getHelp ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures an { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static void configure ( final Properties properties , final Configurable config ) { for ( final Enumeration < String > names = ( Enumeration < String > ) properties . propertyNames ( ) ; names . hasMoreElements ( ) ; ) { final String name = names . nextElement ( ) ; final String value = properties . getProperty ( name ) ; if ( value != null ) { try { config . setProperty ( name , value ) ; } catch ( PropertyNotFoundException e ) { log . warn ( \"Could not find property on object {}; name=\\\"{}\\\"; value=\\\"{}\\\"\" , new Object [ ] { config , name , value } ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures an { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static void configure ( final String file , final Configurable config ) throws FileNotFoundException , IOException { Properties props = new Properties ( ) ; props . load ( new FileInputStream ( file ) ) ; Configuration . configure ( props , config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the time base that time stamps of this object are represented in . <br > <br > [CODESPLIT] public void setTimeBase ( Rational aBase ) { VideoJNI . MediaEncoded_setTimeBase ( swigCPtr , this , Rational . getCPtr ( aBase ) , aBase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a descriptor given a { @link BufferedImage } . [CODESPLIT] public static String findDescriptor ( BufferedImage image ) { for ( Type converterType : getRegisteredConverters ( ) ) if ( converterType . getImageType ( ) == image . getType ( ) ) return converterType . getDescriptor ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a converter which translates betewen { @link BufferedImage } and { @link MediaPicture } types . The { @link io . humble . video . PixelFormat . Type } and size are extracted from the passed in picture . This factory will attempt to create a converter which can perform the translation . If no converter can be created a descriptive { @link UnsupportedOperationException } is thrown . [CODESPLIT] public static MediaPictureConverter createConverter ( String converterDescriptor , MediaPicture picture ) { if ( picture == null ) throw new IllegalArgumentException ( \"The picture is NULL.\" ) ; return createConverter ( converterDescriptor , picture . getFormat ( ) , picture . getWidth ( ) , picture . getHeight ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a converter which translates between { @link BufferedImage } and { @link MediaPicture } . This factory will attempt to create a converter which can perform the translation . If no converter can be created a descriptive { @link UnsupportedOperationException } is thrown . [CODESPLIT] public static MediaPictureConverter createConverter ( BufferedImage image , MediaPicture picture ) { if ( image == null ) throw new IllegalArgumentException ( \"cannot pass null image\" ) ; if ( picture == null ) throw new IllegalArgumentException ( \"cannot pass null picture\" ) ; return createConverter ( image , picture . getFormat ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a converter which translates between { @link BufferedImage } and { @link MediaPicture } types . The { @link BufferedImage } type and size are extracted from the passed in image . This factory will attempt to create a converter which can perform the translation . If no converter can be created a descriptive { @link UnsupportedOperationException } is thrown . [CODESPLIT] public static MediaPictureConverter createConverter ( BufferedImage image , PixelFormat . Type pictureType ) { if ( image == null ) throw new IllegalArgumentException ( \"The image is NULL.\" ) ; // find the converter type based in image type String converterDescriptor = findDescriptor ( image ) ; if ( converterDescriptor == null ) throw new UnsupportedOperationException ( \"No converter found for BufferedImage type #\" + image . getType ( ) ) ; // create and return the converter return createConverter ( converterDescriptor , pictureType , image . getWidth ( ) , image . getHeight ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a converter which translates between { @link BufferedImage } and { @link MediaPicture } types . This factory will attempt to create a converter which can perform the translation . If no converter can be created a descriptive { @link UnsupportedOperationException } is thrown . [CODESPLIT] public static MediaPictureConverter createConverter ( String converterDescriptor , PixelFormat . Type pictureType , int width , int height ) { return createConverter ( converterDescriptor , pictureType , width , height , width , height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a converter which translates betewen { @link BufferedImage } and { @link MediaPicture } types . This factory will attempt to create a converter which can perform the translation . If different image and pictures sizes are passed the converter will resize during translation . If no converter can be created a descriptive { @link UnsupportedOperationException } is thrown . [CODESPLIT] public static MediaPictureConverter createConverter ( String converterDescriptor , PixelFormat . Type pictureType , int pictureWidth , int pictureHeight , int imageWidth , int imageHeight ) { MediaPictureConverter converter = null ; // establish the converter type Type converterType = findRegisteredConverter ( converterDescriptor ) ; if ( null == converterType ) throw new UnsupportedOperationException ( \"No converter \\\"\" + converterDescriptor + \"\\\" found.\" ) ; // create the converter try { // establish the constructor  Constructor < ? extends MediaPictureConverter > converterConstructor = converterType . getConverterClass ( ) . getConstructor ( PixelFormat . Type . class , int . class , int . class , int . class , int . class ) ; // create the converter converter = converterConstructor . newInstance ( pictureType , pictureWidth , pictureHeight , imageWidth , imageHeight ) ; } catch ( NoSuchMethodException e ) { throw new UnsupportedOperationException ( \"Converter \" + converterType . getConverterClass ( ) + \" requries a constructor of the form \" + \"(PixelFormat.Type, int, int, int, int)\" ) ; } catch ( InvocationTargetException e ) { Throwable cause = e . getCause ( ) ; if ( cause != null && cause instanceof OutOfMemoryError ) { throw ( OutOfMemoryError ) cause ; } else { throw new UnsupportedOperationException ( \"Converter \" + converterType . getConverterClass ( ) + \" constructor failed with: \" + e . getCause ( ) ) ; } } catch ( IllegalAccessException e ) { Throwable cause = e . getCause ( ) ; if ( cause != null && cause instanceof OutOfMemoryError ) { throw ( OutOfMemoryError ) cause ; } else { throw new UnsupportedOperationException ( \"Converter \" + converterType . getConverterClass ( ) + \" constructor failed with: \" + e . getCause ( ) ) ; } } catch ( InstantiationException e ) { Throwable cause = e . getCause ( ) ; if ( cause != null && cause instanceof OutOfMemoryError ) { throw ( OutOfMemoryError ) cause ; } else { throw new UnsupportedOperationException ( \"Converter \" + converterType . getConverterClass ( ) + \" constructor failed with: \" + e . getCause ( ) ) ; } } // return the newly created converter return converter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a { @link BufferedImage } of any type to { @link BufferedImage } of a specified type . If the source image is the same type as the target type then original image is returned otherwise new image of the correct type is created and the content of the source image is copied into the new image . [CODESPLIT] public static BufferedImage convertToType ( BufferedImage sourceImage , int targetType ) { BufferedImage image ; // if the source image is already the target type, return the source image if ( sourceImage . getType ( ) == targetType ) image = sourceImage ; // otherwise create a new image of the target type and draw the new // image  else { image = new BufferedImage ( sourceImage . getWidth ( ) , sourceImage . getHeight ( ) , targetType ) ; image . getGraphics ( ) . drawImage ( sourceImage , 0 , 0 , null ) ; } return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the current parachute and recreates ( reloads ) our payload if needed . [CODESPLIT] boolean packChute ( ) throws OutOfMemoryError { if ( mPayload != null ) return true ; // otherwise the payload is null synchronized ( this ) { if ( mPayload != null ) return true ; try { //System.out.println(\"Packing the parachute! this=\" + this); mPayload = new byte [ PAYLOAD_BYTES ] ; mPayload [ 0 ] = ' ' ; mPayload [ 1 ] = ' ' ; mPayload [ 2 ] = ' ' ; mPayload [ 3 ] = ' ' ; mPayload [ 4 ] = ' ' ; mPayload [ 5 ] = ' ' ; mPayload [ 6 ] = ' ' ; mPayload [ 7 ] = ' ' ; mPayload [ 8 ] = ' ' ; mPayload [ 9 ] = ' ' ; return true ; } catch ( OutOfMemoryError e ) { // we failed to create the parachute.  Also known as bad. // forward it on. throw e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int close ( ) { int retval = 0 ; try { if ( mOpenStream != null && mCloseStreamOnClose ) { mOpenStream . close ( ) ; } } catch ( IOException e ) { log . error ( \"could not close stream {}: {}\" , mOpenStream , e ) ; retval = - 1 ; } mOpenStream = null ; return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int open ( String url , int flags ) { if ( mOpenStream != null ) { log . debug ( \"attempting to open already open handler: {}\" , mOpenStream ) ; return - 1 ; } switch ( flags ) { case URL_RDWR : log . debug ( \"do not support read/write mode for Java IO Handlers\" ) ; return - 1 ; case URL_WRONLY_MODE : mOpenStream = mWriteChannel ; if ( mOpenStream == null ) { log . error ( \"No OutputStream specified for writing: {}\" , url ) ; return - 1 ; } break ; case URL_RDONLY_MODE : mOpenStream = mReadChannel ; if ( mOpenStream == null ) { log . error ( \"No InputStream specified for reading: {}\" , url ) ; return - 1 ; } break ; default : log . error ( \"Invalid flag passed to open: {}\" , url ) ; return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int read ( byte [ ] buf , int size ) { int ret = - 1 ; if ( mOpenStream == null || ! ( mOpenStream instanceof ReadableByteChannel ) ) return - 1 ; try { ReadableByteChannel channel = ( ReadableByteChannel ) mOpenStream ; ByteBuffer buffer = ByteBuffer . allocate ( size ) ; ret = channel . read ( buffer ) ; if ( ret > 0 ) { buffer . flip ( ) ; buffer . get ( buf , 0 , ret ) ; } return ret ; } catch ( IOException e ) { log . error ( \"Got IO exception reading from channel: {}; {}\" , mOpenStream , e ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int write ( byte [ ] buf , int size ) { if ( mOpenStream == null || ! ( mOpenStream instanceof WritableByteChannel ) ) return - 1 ; try { WritableByteChannel channel = ( WritableByteChannel ) mOpenStream ; ByteBuffer buffer = ByteBuffer . allocate ( size ) ; buffer . put ( buf , 0 , size ) ; buffer . flip ( ) ; return channel . write ( buffer ) ; } catch ( IOException e ) { log . error ( \"Got error writing to file: {}; {}\" , mOpenStream , e ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a new protocol name for this factory that Humble . IO will use for the given protocol . [CODESPLIT] static HumbleIO registerFactory ( String protocolPrefix ) { URLProtocolManager manager = URLProtocolManager . getManager ( ) ; manager . registerFactory ( protocolPrefix , mFactory ) ; return mFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a unique name suitable for using in the map methods for the URL parameter . [CODESPLIT] static public String generateUniqueName ( Object src , String extension ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( UUID . randomUUID ( ) . toString ( ) ) ; if ( src != null ) { builder . append ( \"-\" ) ; builder . append ( src . getClass ( ) . getName ( ) ) ; builder . append ( \"-\" ) ; builder . append ( Integer . toHexString ( src . hashCode ( ) ) ) ; } if ( extension != null ) { builder . append ( extension ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link IURLProtocolHandler } to a url that Humble can open . [CODESPLIT] public static String map ( String url , IURLProtocolHandler handler ) { return map ( url , handler , DEFAULT_UNMAP_URL_ON_OPEN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link DataInput } object to a URL for use by Humble . [CODESPLIT] public static String map ( DataInput input ) { return map ( generateUniqueName ( input ) , input , null , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link DataInput } object to a URL for use by Humble . [CODESPLIT] public static String map ( String url , DataInput input ) { return map ( url , input , null , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link DataOutput } object to a URL for use by Humble . [CODESPLIT] public static String map ( DataOutput output ) { return map ( generateUniqueName ( output ) , null , output , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link DataOutput } object to a URL for use by Humble . [CODESPLIT] public static String map ( String url , DataOutput output ) { return map ( url , null , output , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link RandomAccessFile } object to a URL for use by Humble . [CODESPLIT] public static String map ( RandomAccessFile file ) { return map ( generateUniqueName ( file ) , file , file , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link RandomAccessFile } object to a URL for use by Humble . [CODESPLIT] public static String map ( String url , RandomAccessFile file ) { return map ( url , file , file , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link ReadableByteChannel } to a URL for use by Humble . [CODESPLIT] public static String map ( ReadableByteChannel channel ) { return map ( generateUniqueName ( channel ) , channel , null , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link ReadableByteChannel } to a URL for use by Humble . [CODESPLIT] public static String map ( String url , ReadableByteChannel channel ) { return map ( url , channel , null , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link WritableByteChannel } to a URL for use by Humble . [CODESPLIT] public static String map ( WritableByteChannel channel ) { return map ( generateUniqueName ( channel ) , null , channel , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link WritableByteChannel } to a URL for use by Humble . [CODESPLIT] public static String map ( String url , WritableByteChannel channel ) { return map ( url , null , channel , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link ByteChannel } to a URL for use by Humble . [CODESPLIT] public static String map ( ByteChannel channel ) { return map ( generateUniqueName ( channel ) , channel , channel , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link ByteChannel } to a URL for use by Humble . [CODESPLIT] public static String map ( String url , ByteChannel channel ) { return map ( url , channel , channel , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an { @link InputStream } to a URL for use by Humble . [CODESPLIT] public static String map ( InputStream in ) { return map ( generateUniqueName ( in ) , in , null , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an { @link InputStream } to a URL for use by Humble . [CODESPLIT] public static String map ( String url , InputStream in ) { return map ( url , in , null , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an { @link OutputStream } to a URL for use by Humble . [CODESPLIT] public static String map ( OutputStream out ) { return map ( generateUniqueName ( out ) , null , out , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an { @link OutputStream } to a URL for use by Humble . [CODESPLIT] public static String map ( String url , OutputStream out ) { return map ( url , null , out , DEFAULT_UNMAP_URL_ON_OPEN , DEFAULT_CLOSE_STREAM_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link DataInput } or { @link DataOutput } object to a URL for use by Humble . [CODESPLIT] public static String map ( String url , DataInput in , DataOutput out , boolean unmapOnOpen , boolean closeOnClose ) { return map ( url , new DataInputOutputHandler ( in , out , closeOnClose ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an { @link ReadableByteChannel } or { @link WritableByteChannel } to a URL for use by Humble . [CODESPLIT] public static String map ( String url , ReadableByteChannel in , WritableByteChannel out , boolean unmapOnOpen , boolean closeOnClose ) { return map ( url , new ReadableWritableChannelHandler ( in , out , closeOnClose ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an { @link InputStream } or { @link OutputStream } to a URL for use by Humble . [CODESPLIT] public static String map ( String url , InputStream in , OutputStream out , boolean unmapOnOpen , boolean closeOnClose ) { return map ( url , new InputOutputStreamHandler ( in , out , closeOnClose ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @link IURLProtocolHandler } to a url that Humble can open . [CODESPLIT] public static String map ( String url , IURLProtocolHandler handler , boolean unmapUrlOnOpen ) { if ( mFactory . mapIO ( url , handler , unmapUrlOnOpen ) != null ) throw new RuntimeException ( \"url is already mapped: \" + url ) ; return DEFAULT_PROTOCOL + \":\" + URLProtocolManager . getResourceFromURL ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the given url or file name to the given { @link IURLProtocolHandler } or so that Humble calls to open the URL it will call back to the handler . [CODESPLIT] public IURLProtocolHandler mapIO ( String url , IURLProtocolHandler handler , boolean unmapUrlOnOpen ) { { if ( url == null || url . length ( ) <= 0 ) throw new IllegalArgumentException ( \"must pass in non-zero url\" ) ; if ( handler == null ) { throw new IllegalArgumentException ( \"must pass in a non null handler\" ) ; } String streamName = URLProtocolManager . getResourceFromURL ( url ) ; RegistrationInformation tuple = new RegistrationInformation ( streamName , handler , unmapUrlOnOpen ) ; RegistrationInformation oldTuple = mURLs . putIfAbsent ( streamName , tuple ) ; return oldTuple == null ? null : oldTuple . getHandler ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unmaps a registration between a URL and the underlying i / o objects . <p > If URL contains a protocol it is ignored when trying to find the matching IO stream . < / p > [CODESPLIT] public IURLProtocolHandler unmapIO ( String url ) { if ( url == null || url . length ( ) <= 0 ) throw new IllegalArgumentException ( \"must pass in non-zero url\" ) ; String streamName = URLProtocolManager . getResourceFromURL ( url ) ; RegistrationInformation oldTuple = mURLs . remove ( streamName ) ; return oldTuple == null ? null : oldTuple . getHandler ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public IURLProtocolHandler getHandler ( String protocol , String url , int flags ) { // Note: We need to remove any protocol markers from the url String streamName = URLProtocolManager . getResourceFromURL ( url ) ; RegistrationInformation tuple = mURLs . get ( streamName ) ; if ( tuple != null ) { IURLProtocolHandler handler = tuple . getHandler ( ) ; if ( tuple . isUnmappingOnOpen ( ) ) { IURLProtocolHandler oldHandler = unmapIO ( tuple . getName ( ) ) ; // the unmapIO is an atomic operation if ( handler != null && ! handler . equals ( oldHandler ) ) { // someone already unmapped this stream log . error ( \"stream {} already unmapped; it was likely already opened\" , tuple . getName ( ) ) ; return null ; } } return handler ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new Logger object for this loggerName . <br > <br > [CODESPLIT] public static Logger getLogger ( String aLoggerName ) { long cPtr = FerryJNI . Logger_getLogger ( aLoggerName ) ; return ( cPtr == 0 ) ? null : new Logger ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Logger object but ask the Logger code to<br > free it up once the JavaVM shuts down . Use at your<br > own risk . <br > <br > [CODESPLIT] public static Logger getStaticLogger ( String aLoggerName ) { long cPtr = FerryJNI . Logger_getStaticLogger ( aLoggerName ) ; return ( cPtr == 0 ) ? null : new Logger ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the message to the logger using sprintf () format<br > strings . <br > <br > [CODESPLIT] public boolean log ( String filename , int lineNo , Logger . Level level , String format ) { return FerryJNI . Logger_log ( swigCPtr , this , filename , lineNo , level . swigValue ( ) , format ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new MediaAudioResampler . [CODESPLIT] public static MediaAudioResampler make ( AudioChannel . Layout outLayout , int outSampleRate , AudioFormat . Type outFormat , AudioChannel . Layout inLayout , int inSampleRate , AudioFormat . Type inFormat ) { long cPtr = VideoJNI . MediaAudioResampler_make ( outLayout . swigValue ( ) , outSampleRate , outFormat . swigValue ( ) , inLayout . swigValue ( ) , inSampleRate , inFormat . swigValue ( ) ) ; return ( cPtr == 0 ) ? null : new MediaAudioResampler ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert audio . <br > <br > in can be set to null to flush the last few samples out at the<br > end . <br > <br > If more input is provided than output space then the input will be buffered . <br > You can avoid this buffering by providing more output space than input . <br > Conversion will run directly without copying whenever possible . <br > <br > [CODESPLIT] public int resample ( MediaSampled out , MediaSampled in ) { return VideoJNI . MediaAudioResampler_resample ( swigCPtr , this , MediaSampled . getCPtr ( out ) , out , MediaSampled . getCPtr ( in ) , in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the timebase used when outputting time stamps for audio . <br > <br > Defaults to 1 / ( the lowest common multiple of getInputSampleRate () <br > and getOutputSampleRate () ) in order to ensure that no rounding<br > of time stamps occur . <br > <br > For example if the input sample rate is 22050 and the output sample<br > rate is 44100 then the output time base will be ( 1 / 44100 ) . But if the<br > input sample rate is 48000 and the output sample rate is 22050 then<br > the output time base will be ( 1 / lcm ( 48000 22050 )) which will be 1 / 7056000<br > ( trust me ) . This is done so that timestamp values do not get rounded ( and<br > therefore introduce drift ) . [CODESPLIT] public Rational getTimeBase ( ) { long cPtr = VideoJNI . MediaAudioResampler_getTimeBase ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the timebase to use for timestamps on output audio . <br > <br > [CODESPLIT] public void setTimeBase ( Rational rational ) { VideoJNI . MediaAudioResampler_setTimeBase ( swigCPtr , this , Rational . getCPtr ( rational ) , rational ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an ordered sequence of index entries in this { @link Stream } . [CODESPLIT] public java . util . List < IndexEntry > getIndexEntries ( ) { final int numEntries = getNumIndexEntries ( ) ; java . util . List < IndexEntry > retval = new java . util . ArrayList < IndexEntry > ( Math . max ( numEntries , 10 ) ) ; for ( int i = 0 ; i < numEntries ; i ++ ) { final IndexEntry entry = getIndexEntry ( i ) ; if ( entry != null ) { retval . add ( entry ) ; } } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the ( sometimes estimated ) average frame rate of this container . <br > For variable frame - rate containers ( they do exist ) this is just<br > an approximation . Better to use getTimeBase () . <br > <br > For contant frame - rate containers this will be 1 / ( getTimeBase () ) <br > <br > [CODESPLIT] public Rational getFrameRate ( ) { long cPtr = VideoJNI . ContainerStream_getFrameRate ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The time base in which all timestamps ( e . g . Presentation Time Stamp ( PTS ) <br > and Decompression Time Stamp ( DTS )) are represented . For example<br > if the time base is 1 / 1000 then the difference between a PTS of 1 and<br > a PTS of 2 is 1 millisecond . If the timebase is 1 / 1 then the difference<br > between a PTS of 1 and a PTS of 2 is 1 second . <br > <br > [CODESPLIT] public Rational getTimeBase ( ) { long cPtr = VideoJNI . ContainerStream_getTimeBase ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the sample aspect ratio . <br > <br > [CODESPLIT] public Rational getSampleAspectRatio ( ) { long cPtr = VideoJNI . ContainerStream_getSampleAspectRatio ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the underlying container for this stream or null if Humble Video<br > doesn t know . <br > <br > [CODESPLIT] public Container getContainer ( ) { long cPtr = VideoJNI . ContainerStream_getContainer ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Container ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the KeyValueBag for this object <br > or null if none . <br > <p > <br > If the Container or Stream object<br > that this KeyValueBag came from was opened<br > for reading then changes via KeyValueBag#setValue ( String String ) <br > will have no effect on the underlying media . <br > < / p > <br > <p > <br > If the Container or Stream object<br > that this KeyValueBag came from was opened<br > for writing then changes via KeyValueBag#setValue ( String String ) <br > will have no effect after Container#writeHeader () <br > is called . <br > < / p > <br > [CODESPLIT] public KeyValueBag getMetaData ( ) { long cPtr = VideoJNI . ContainerStream_getMetaData ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new KeyValueBag ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for the given time stamp in the key - frame index for this Stream . <br > <p > <br > Not all ContainerFormat implementations<br > maintain key frame indexes but if they have one <br > then this method searches in the Stream index<br > to quickly find the byte - offset of the nearest key - frame to<br > the given time stamp . <br > < / p > <br > [CODESPLIT] public IndexEntry findTimeStampEntryInIndex ( long wantedTimeStamp , int flags ) { long cPtr = VideoJNI . ContainerStream_findTimeStampEntryInIndex ( swigCPtr , this , wantedTimeStamp , flags ) ; return ( cPtr == 0 ) ? null : new IndexEntry ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the IndexEntry at the given position in this<br > Stream object s index . <br > <p > <br > Not all ContainerFormat types maintain<br > Stream indexes but if they do <br > this method can return those entries . <br > < / p > <br > <p > <br > Do not modify the Container this stream<br > is from between calls to this method and<br > #getNumIndexEntries () as indexes may<br > be compacted while processing . <br > < / p > <br > [CODESPLIT] public IndexEntry getIndexEntry ( int position ) { long cPtr = VideoJNI . ContainerStream_getIndexEntry ( swigCPtr , this , position ) ; return ( cPtr == 0 ) ? null : new IndexEntry ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For containers with Stream . Disposition . DISPOSITION_ATTACHED_PIC <br > this returns a read - only copy of the packet containing the<br > picture ( needs to be decoded separately ) . [CODESPLIT] public MediaPacket getAttachedPic ( ) { long cPtr = VideoJNI . ContainerStream_getAttachedPic ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new MediaPacket ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a collection of ALL codecs installed on this system . [CODESPLIT] public static java . util . Collection < Codec > getInstalledCodecs ( ) { java . util . Collection < Codec > retval = new java . util . HashSet < Codec > ( ) ; int count = getNumInstalledCodecs ( ) ; for ( int i = 0 ; i < count ; i ++ ) { Codec codec = getInstalledCodec ( i ) ; if ( codec != null ) retval . add ( codec ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of supported frame - rates this codec can encode video to . [CODESPLIT] public java . util . Collection < Rational > getSupportedVideoFrameRates ( ) { java . util . List < Rational > retval = new java . util . LinkedList < Rational > ( ) ; int count = getNumSupportedVideoFrameRates ( ) ; for ( int i = 0 ; i < count ; i ++ ) { Rational rate = getSupportedVideoFrameRate ( i ) ; if ( rate != null ) retval . add ( rate ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of supported pixel formats this codec can encode video in . [CODESPLIT] public java . util . Collection < PixelFormat . Type > getSupportedVideoPixelFormats ( ) { java . util . List < PixelFormat . Type > retval = new java . util . LinkedList < PixelFormat . Type > ( ) ; int count = getNumSupportedVideoPixelFormats ( ) ; for ( int i = 0 ; i < count ; i ++ ) { PixelFormat . Type type = getSupportedVideoPixelFormat ( i ) ; if ( type != null && type != PixelFormat . Type . PIX_FMT_NONE ) retval . add ( type ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of supported audio sample rates this codec can encode audio in . [CODESPLIT] public java . util . Collection < Integer > getSupportedAudioSampleRates ( ) { java . util . List < Integer > retval = new java . util . LinkedList < Integer > ( ) ; int count = getNumSupportedAudioSampleRates ( ) ; for ( int i = 0 ; i < count ; i ++ ) { int rate = getSupportedAudioSampleRate ( i ) ; if ( rate != 0 ) retval . add ( rate ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of supported audio sample formats this codec can encode audio in . [CODESPLIT] public java . util . Collection < AudioFormat . Type > getSupportedAudioFormats ( ) { java . util . List < AudioFormat . Type > retval = new java . util . LinkedList < AudioFormat . Type > ( ) ; int count = getNumSupportedAudioFormats ( ) ; for ( int i = 0 ; i < count ; i ++ ) { AudioFormat . Type fmt = getSupportedAudioFormat ( i ) ; if ( fmt != null && fmt != AudioFormat . Type . SAMPLE_FMT_NONE ) retval . add ( fmt ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of supported audio channel layouts this codec can encode audio in . [CODESPLIT] public java . util . Collection < AudioChannel . Layout > getSupportedAudioChannelLayouts ( ) { java . util . List < AudioChannel . Layout > retval = new java . util . LinkedList < AudioChannel . Layout > ( ) ; int count = getNumSupportedAudioChannelLayouts ( ) ; for ( int i = 0 ; i < count ; i ++ ) { AudioChannel . Layout layout = getSupportedAudioChannelLayout ( i ) ; if ( layout != AudioChannel . Layout . CH_LAYOUT_UNKNOWN ) retval . add ( layout ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a codec that can be used for encoding . <br > [CODESPLIT] public static Codec findEncodingCodec ( Codec . ID id ) { long cPtr = VideoJNI . Codec_findEncodingCodec ( id . swigValue ( ) ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a codec that can be used for encoding . <br > [CODESPLIT] public static Codec findEncodingCodecByIntID ( int id ) { long cPtr = VideoJNI . Codec_findEncodingCodecByIntID ( id ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a codec that can be used for encoding . <br > [CODESPLIT] public static Codec findEncodingCodecByName ( String id ) { long cPtr = VideoJNI . Codec_findEncodingCodecByName ( id ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a codec that can be used for decoding . <br > [CODESPLIT] public static Codec findDecodingCodec ( Codec . ID id ) { long cPtr = VideoJNI . Codec_findDecodingCodec ( id . swigValue ( ) ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a codec that can be used for decoding . <br > [CODESPLIT] public static Codec findDecodingCodecByIntID ( int id ) { long cPtr = VideoJNI . Codec_findDecodingCodecByIntID ( id ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a codec that can be used for decoding . <br > [CODESPLIT] public static Codec findDecodingCodecByName ( String id ) { long cPtr = VideoJNI . Codec_findDecodingCodecByName ( id ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ask us to guess an encoding codec based on the inputs<br > passed in . <br > <p > <br > You must pass in at least one non null fmt shortName <br > url or mime_type . <br > < / p > <br > [CODESPLIT] public static Codec guessEncodingCodec ( MuxerFormat fmt , String shortName , String url , String mimeType , MediaDescriptor . Type type ) { long cPtr = VideoJNI . Codec_guessEncodingCodec ( MuxerFormat . getCPtr ( fmt ) , fmt , shortName , url , mimeType , type . swigValue ( ) ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the ICodec at the given index . <br > <br > [CODESPLIT] public static Codec getInstalledCodec ( int index ) { long cPtr = VideoJNI . Codec_getInstalledCodec ( index ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the supported frame rate at the given index . <br > <br > [CODESPLIT] public Rational getSupportedVideoFrameRate ( int index ) { long cPtr = VideoJNI . Codec_getSupportedVideoFrameRate ( swigCPtr , this , index ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the supported video pixel format at the given index . <br > <br > [CODESPLIT] public PixelFormat . Type getSupportedVideoPixelFormat ( int index ) { return PixelFormat . Type . swigToEnum ( VideoJNI . Codec_getSupportedVideoPixelFormat ( swigCPtr , this , index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supported sample format at this index . <br > <br > [CODESPLIT] public AudioFormat . Type getSupportedAudioFormat ( int index ) { return AudioFormat . Type . swigToEnum ( VideoJNI . Codec_getSupportedAudioFormat ( swigCPtr , this , index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supported audio channel layout at this index . <br > <br > The value returned is a bit flag representing the different<br > types of audio layout this codec can support . Test the values<br > by bit - comparing them to the AudioChannel . Layout<br > enum types . <br > <br > [CODESPLIT] public AudioChannel . Layout getSupportedAudioChannelLayout ( int index ) { return AudioChannel . Layout . swigToEnum ( VideoJNI . Codec_getSupportedAudioChannelLayout ( swigCPtr , this , index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the supported CodecProfile at this index . <br > <br > [CODESPLIT] public CodecProfile getSupportedProfile ( int index ) { long cPtr = VideoJNI . Codec_getSupportedProfile ( swigCPtr , this , index ) ; return ( cPtr == 0 ) ? null : new CodecProfile ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resample in to out based on the resampler parameters . <br > <br > Resamples the in picture based on the parameters set when<br > this resampler was constructed . <br > <br > [CODESPLIT] public int resample ( MediaSampled out , MediaSampled in ) { return VideoJNI . MediaPictureResampler_resample ( swigCPtr , this , MediaSampled . getCPtr ( out ) , out , MediaSampled . getCPtr ( in ) , in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A more precisely typed way to call #resample [CODESPLIT] public int resamplePicture ( MediaPicture out , MediaPicture in ) { return VideoJNI . MediaPictureResampler_resamplePicture ( swigCPtr , this , MediaPicture . getCPtr ( out ) , out , MediaPicture . getCPtr ( in ) , in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a new picture resampler . <br > <br > [CODESPLIT] public static MediaPictureResampler make ( int outputWidth , int outputHeight , PixelFormat . Type outputFmt , int inputWidth , int inputHeight , PixelFormat . Type inputFmt , int flags ) { long cPtr = VideoJNI . MediaPictureResampler_make ( outputWidth , outputHeight , outputFmt . swigValue ( ) , inputWidth , inputHeight , inputFmt . swigValue ( ) , flags ) ; return ( cPtr == 0 ) ? null : new MediaPictureResampler ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int open ( String url , int flags ) { if ( mOpenStream != null ) { log . debug ( \"attempting to open already open handler: {}\" , mOpenStream ) ; return - 1 ; } switch ( flags ) { case URL_RDWR : log . debug ( \"do not support read/write mode for Java IO Handlers\" ) ; return - 1 ; case URL_WRONLY_MODE : mOpenStream = mOutputStream ; if ( mOpenStream == null ) { log . error ( \"No OutputStream specified for writing: {}\" , url ) ; return - 1 ; } break ; case URL_RDONLY_MODE : mOpenStream = mInputStream ; if ( mOpenStream == null ) { log . error ( \"No InputStream specified for reading: {}\" , url ) ; return - 1 ; } break ; default : log . error ( \"Invalid flag passed to open: {}\" , url ) ; return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int read ( byte [ ] buf , int size ) { int ret = - 1 ; if ( mOpenStream == null || ! ( mOpenStream instanceof InputStream ) ) return - 1 ; try { InputStream stream = ( InputStream ) mOpenStream ; ret = stream . read ( buf , 0 , size ) ; return ret ; } catch ( IOException e ) { log . error ( \"Got IO exception reading from stream: {}; {}\" , mOpenStream , e ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int write ( byte [ ] buf , int size ) { if ( mOpenStream == null || ! ( mOpenStream instanceof OutputStream ) ) return - 1 ; try { OutputStream stream = ( OutputStream ) mOpenStream ; stream . write ( buf , 0 , size ) ; return size ; } catch ( IOException e ) { log . error ( \"Got error writing to file: {}; {}\" , mOpenStream , e ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the set of keys currently in this { [CODESPLIT] public java . util . Collection < String > getKeys ( ) { int numKeys = getNumKeys ( ) ; java . util . List < String > retval = new java . util . ArrayList < String > ( numKeys ) ; for ( int i = 0 ; i < getNumKeys ( ) ; i ++ ) { String key = getKey ( i ) ; if ( key != null && key . length ( ) > 0 ) retval . add ( key ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value for the given key . <br > <br > [CODESPLIT] public String getValue ( String key , KeyValueBag . Flags flag ) { return VideoJNI . KeyValueBag_getValue ( swigCPtr , this , key , flag . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value for the given key to value . This overrides<br > any prior setting for key or adds key to the meta - data<br > if appropriate . <br > <br > [CODESPLIT] public int setValue ( String key , String value ) { return VideoJNI . KeyValueBag_setValue__SWIG_0 ( swigCPtr , this , key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new KeyValueBag bag of properties with<br > no values set . [CODESPLIT] public static KeyValueBag make ( ) { long cPtr = VideoJNI . KeyValueBag_make ( ) ; return ( cPtr == 0 ) ? null : new KeyValueBag ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value for the given key to value . This overrides<br > any prior setting for key or adds key to the meta - data<br > if appropriate . <br > <br > [CODESPLIT] public int setValue ( String key , String value , KeyValueBag . Flags flag ) { return VideoJNI . KeyValueBag_setValue__SWIG_1 ( swigCPtr , this , key , value , flag . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open this Coder using the given bag of Codec - specific options . <br > <br > [CODESPLIT] public void open ( KeyValueBag inputOptions , KeyValueBag unsetOptions ) { VideoJNI . Coder_open ( swigCPtr , this , KeyValueBag . getCPtr ( inputOptions ) , inputOptions , KeyValueBag . getCPtr ( unsetOptions ) , unsetOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Codec this StreamCoder will use . <br > <br > [CODESPLIT] public Codec getCodec ( ) { long cPtr = VideoJNI . Coder_getCodec ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Codec ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the time base this stream will ENCODE in or the time base we<br > detect while DECODING . <br > <br > [CODESPLIT] public Rational getTimeBase ( ) { long cPtr = VideoJNI . Coder_getTimeBase ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the time base we ll use to ENCODE with . A no - op when DECODING . <br > <br > As a convenience we forward this call to the Stream#setTimeBase () <br > method . <br > <br > [CODESPLIT] public void setTimeBase ( Rational newTimeBase ) { VideoJNI . Coder_setTimeBase ( swigCPtr , this , Rational . getCPtr ( newTimeBase ) , newTimeBase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a flag to true or false . [CODESPLIT] public void setFlag ( Coder . Flag flag , boolean value ) { VideoJNI . Coder_setFlag ( swigCPtr , this , flag . swigValue ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a flag2 to true or false . [CODESPLIT] public void setFlag2 ( Coder . Flag2 flag , boolean value ) { VideoJNI . Coder_setFlag2 ( swigCPtr , this , flag . swigValue ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the decoder that can decode the information in this Demuxer stream . [CODESPLIT] public Decoder getDecoder ( ) { long cPtr = VideoJNI . DemuxerStream_getDecoder ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Decoder ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Demuxer this DemuxerStream belongs to . [CODESPLIT] public Demuxer getDemuxer ( ) { long cPtr = VideoJNI . DemuxerStream_getDemuxer ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Demuxer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a collection of all output formats installed on this system . [CODESPLIT] public static java . util . Collection < MuxerFormat > getFormats ( ) { java . util . Collection < MuxerFormat > retval = new java . util . HashSet < MuxerFormat > ( ) ; int count = getNumFormats ( ) ; for ( int i = 0 ; i < count ; ++ i ) { MuxerFormat fmt = getFormat ( i ) ; if ( fmt != null ) retval . add ( fmt ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the sink format in the list of registered sink formats<br > which best matches the provided parameters or return NULL if<br > there is no match . <br > <br > [CODESPLIT] public static MuxerFormat guessFormat ( String shortName , String filename , String mimeType ) { long cPtr = VideoJNI . MuxerFormat_guessFormat ( shortName , filename , mimeType ) ; return ( cPtr == 0 ) ? null : new MuxerFormat ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Codec . ID for the n th codec supported by this container . <br > <br > [CODESPLIT] protected Codec . ID getSupportedCodecId ( int n ) { return Codec . ID . swigToEnum ( VideoJNI . MuxerFormat_getSupportedCodecId ( swigCPtr , this , n ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an object for the input format at the given index . <br > <br > [CODESPLIT] public static MuxerFormat getFormat ( int index ) { long cPtr = VideoJNI . MuxerFormat_getFormat ( index ) ; return ( cPtr == 0 ) ? null : new MuxerFormat ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new FilterGraph . [CODESPLIT] public static FilterGraph make ( ) { long cPtr = VideoJNI . FilterGraph_make ( ) ; return ( cPtr == 0 ) ? null : new FilterGraph ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a filter with the given name to the graph . <br > [CODESPLIT] public Filter addFilter ( FilterType type , String name ) { long cPtr = VideoJNI . FilterGraph_addFilter ( swigCPtr , this , FilterType . getCPtr ( type ) , type , name ) ; return ( cPtr == 0 ) ? null : new Filter ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a FilterAudioSource . <br > [CODESPLIT] public FilterAudioSource addAudioSource ( String name , int sampleRate , AudioChannel . Layout channelLayout , AudioFormat . Type format , Rational timeBase ) { long cPtr = VideoJNI . FilterGraph_addAudioSource ( swigCPtr , this , name , sampleRate , channelLayout . swigValue ( ) , format . swigValue ( ) , Rational . getCPtr ( timeBase ) , timeBase ) ; return ( cPtr == 0 ) ? null : new FilterAudioSource ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a FilterPictureSource . <br > [CODESPLIT] public FilterPictureSource addPictureSource ( String name , int width , int height , PixelFormat . Type format , Rational timeBase , Rational pixelAspectRatio ) { long cPtr = VideoJNI . FilterGraph_addPictureSource ( swigCPtr , this , name , width , height , format . swigValue ( ) , Rational . getCPtr ( timeBase ) , timeBase , Rational . getCPtr ( pixelAspectRatio ) , pixelAspectRatio ) ; return ( cPtr == 0 ) ? null : new FilterPictureSource ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a FilterAudioSink . <br > [CODESPLIT] public FilterAudioSink addAudioSink ( String name , int sampleRate , AudioChannel . Layout channelLayout , AudioFormat . Type format ) { long cPtr = VideoJNI . FilterGraph_addAudioSink ( swigCPtr , this , name , sampleRate , channelLayout . swigValue ( ) , format . swigValue ( ) ) ; return ( cPtr == 0 ) ? null : new FilterAudioSink ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a FilterPictureSink . <br > [CODESPLIT] public FilterPictureSink addPictureSink ( String name , PixelFormat . Type format ) { long cPtr = VideoJNI . FilterGraph_addPictureSink ( swigCPtr , this , name , format . swigValue ( ) ) ; return ( cPtr == 0 ) ? null : new FilterPictureSink ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue a command for one or more filter instances . <br > <br > [CODESPLIT] public void queueCommand ( String target , String command , String arguments , int flags , double ts ) { VideoJNI . FilterGraph_queueCommand ( swigCPtr , this , target , command , arguments , flags , ts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new IndexEntry with the specified<br > values . <br > <br > [CODESPLIT] public static IndexEntry make ( long position , long timeStamp , int flags , int size , int minDistance ) { long cPtr = VideoJNI . IndexEntry_make ( position , timeStamp , flags , size , minDistance ) ; return ( cPtr == 0 ) ? null : new IndexEntry ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a filter given the name . <br > <br > [CODESPLIT] public static BitStreamFilter make ( String filtername ) { long cPtr = VideoJNI . BitStreamFilter_make__SWIG_0 ( filtername ) ; return ( cPtr == 0 ) ? null : new BitStreamFilter ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a filter given the type . <br > <br > [CODESPLIT] public static BitStreamFilter make ( BitStreamFilterType type ) { long cPtr = VideoJNI . BitStreamFilter_make__SWIG_1 ( BitStreamFilterType . getCPtr ( type ) , type ) ; return ( cPtr == 0 ) ? null : new BitStreamFilter ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the type of this filter . [CODESPLIT] public BitStreamFilterType getType ( ) { long cPtr = VideoJNI . BitStreamFilter_getType ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new BitStreamFilterType ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter the input buffer into the output buffer . <br > <br > [CODESPLIT] public int filter ( Buffer output , int outputOffset , Buffer input , int inputOffset , int inputSize , Coder coder , String args , boolean isKey ) { return VideoJNI . BitStreamFilter_filter__SWIG_0 ( swigCPtr , this , Buffer . getCPtr ( output ) , output , outputOffset , Buffer . getCPtr ( input ) , input , inputOffset , inputSize , Coder . getCPtr ( coder ) , coder , args , isKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters a packet in place ( i . e . the prior contents will be replaced<br > with the filtered data ) . <br > <br > This method assumes packet . getCoder () is the coder that is being used<br > for outputting the packet to a stream . If this is not the case use<br > the other filter mechanism and construct packets yourself . <br > <br > [CODESPLIT] public void filter ( MediaPacket packet , String args ) { VideoJNI . BitStreamFilter_filter__SWIG_1 ( swigCPtr , this , MediaPacket . getCPtr ( packet ) , packet , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Absolute bulk put method . <p > This method transfers bytes into this buffer from the given source array . If there are more bytes to be copied from the array than there is space remaining at the specified destination offset then no bytes are transferred and a java . nio . BufferOverflowException is thrown . < / p > <p > This method is equivalent to calling { @link #getByteBuffer ( int int ) } yourself and copying the bytes over but is more efficient in the { @link JNIMemoryManager . MemoryModel#NATIVE_BUFFERS } memory model . < / p > [CODESPLIT] public void put ( byte [ ] src , int srcPos , int destPos , int length ) { java . util . concurrent . atomic . AtomicReference < JNIReference > ref = new java . util . concurrent . atomic . AtomicReference < JNIReference > ( ) ; java . nio . ByteBuffer buffer = this . getByteBuffer ( 0 , this . getBufferSize ( ) , ref ) ; try { if ( buffer == null ) return ; buffer . clear ( ) ; validateArgs ( src , src . length , srcPos , buffer . limit ( ) , destPos , length ) ; buffer . position ( destPos ) ; buffer . put ( src , srcPos , length ) ; return ; } finally { if ( ref . get ( ) != null ) ref . get ( ) . delete ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns up to length bytes starting at offset in the underlying buffer we re managing . [CODESPLIT] public java . nio . ByteBuffer getByteBuffer ( int offset , int length ) { return getByteBuffer ( offset , length , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns up to length bytes starting at offset in the underlying buffer we re managing and also passed back a { @link JNIReference } that can optionally be used by the caller to free the underlying native memory . [CODESPLIT] public java . nio . ByteBuffer getByteBuffer ( int offset , int length , java . util . concurrent . atomic . AtomicReference < JNIReference > referenceReturn ) { java . nio . ByteBuffer retval = this . java_getByteBuffer ( offset , length ) ; if ( retval != null ) { // increment the ref count of this class to reflect the // byte buffer java . util . concurrent . atomic . AtomicLong refCount = this . getJavaRefCount ( ) ; refCount . incrementAndGet ( ) ; // and use the byte buffer as the reference to track JNIReference ref = JNIReference . createNonFerryReference ( this , retval , swigCPtr , refCount ) ; if ( referenceReturn != null ) referenceReturn . set ( ref ) ; // and tell Java this byte buffer is in native order retval . order ( java . nio . ByteOrder . nativeOrder ( ) ) ; retval . position ( 0 ) ; retval . mark ( ) ; retval . limit ( this . getBufferSize ( ) ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a new buffer of at least bufferSize . <br > <br > [CODESPLIT] public static Buffer make ( RefCounted requestor , int bufferSize ) { long cPtr = FerryJNI . Buffer_make__SWIG_0 ( RefCounted . getCPtr ( requestor ) , requestor , bufferSize ) ; return ( cPtr == 0 ) ? null : new Buffer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a new buffer of at least bufferSize . <br > <br > [CODESPLIT] public static Buffer make ( RefCounted requestor , Buffer . Type type , int numElements , boolean zero ) { long cPtr = FerryJNI . Buffer_make__SWIG_1 ( RefCounted . getCPtr ( requestor ) , requestor , type . swigValue ( ) , numElements , zero ) ; return ( cPtr == 0 ) ? null : new Buffer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate a new Buffer and copy the data in buffer into<br > the new Buffer object . <br > <br > [CODESPLIT] public static Buffer make ( RefCounted requestor , byte [ ] buffer , int offset , int length ) { long cPtr = FerryJNI . Buffer_make__SWIG_2 ( RefCounted . getCPtr ( requestor ) , requestor , buffer , offset , length ) ; return ( cPtr == 0 ) ? null : new Buffer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Buffer object that uses the direct byte buffer<br > passed in by reference ( i . e . it directly uses the bytes in<br > the direct byte buffer ) . <br > <br > [CODESPLIT] public static Buffer make ( RefCounted requestor , java . nio . ByteBuffer directByteBuffer , int offset , int length ) { long cPtr = FerryJNI . Buffer_make__SWIG_3 ( RefCounted . getCPtr ( requestor ) , requestor , directByteBuffer , offset , length ) ; return ( cPtr == 0 ) ? null : new Buffer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a connection to the speaker if available . [CODESPLIT] public static AudioFrame make ( final AudioFormat audioFormat ) { try { return new AudioFrame ( audioFormat ) ; } catch ( LineUnavailableException e ) { log . error ( \"Could not get audio data line: {}\" , e . getMessage ( ) ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Play the given bytes ( in { [CODESPLIT] public void play ( ByteBuffer rawAudio ) { byte [ ] data = rawAudio . array ( ) ; mLine . write ( data , rawAudio . position ( ) , rawAudio . limit ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - sample a picture . [CODESPLIT] protected static MediaPicture resample ( MediaPicture input , MediaPictureResampler resampler ) { // create new picture object MediaPicture output = MediaPicture . make ( resampler . getOutputWidth ( ) , resampler . getOutputHeight ( ) , resampler . getOutputFormat ( ) ) ; return resample ( output , input , resampler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test that the passed image is valid and conforms to the converters specifications . [CODESPLIT] protected void validateImage ( BufferedImage image ) { // if the image is NULL, throw up if ( image == null ) throw new IllegalArgumentException ( \"The passed image is NULL.\" ) ; // if image is not the correct type, throw up if ( image . getType ( ) != getImageType ( ) ) throw new IllegalArgumentException ( \"The passed image is of type #\" + image . getType ( ) + \" but is required to be of BufferedImage type #\" + getImageType ( ) + \".\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test that the passed picture is valid and conforms to the converters specifications . [CODESPLIT] protected void validatePicture ( MediaPicture picture ) { // if the picture is NULL, throw up if ( picture == null ) throw new IllegalArgumentException ( \"The picture is NULL.\" ) ; // if the picture is not complete, throw up if ( ! picture . isComplete ( ) ) throw new IllegalArgumentException ( \"The picture is not complete.\" ) ; // if the picture is an invalid type throw up PixelFormat . Type type = picture . getFormat ( ) ; if ( ( type != getPictureType ( ) ) && ( willResample ( ) && type != mToImageResampler . getOutputFormat ( ) ) ) throw new IllegalArgumentException ( \"Picture is of type: \" + type + \", but must be \" + getPictureType ( ) + ( willResample ( ) ? \" or \" + mToImageResampler . getOutputFormat ( ) : \"\" ) + \".\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean isInterrupted ( ) { final Thread thread = mThreads . get ( ) . mThread ; final Interruptable handler = getGlobalInterruptHandler ( ) ; boolean retval = false ; if ( handler != null ) { retval = handler . preInterruptCheck ( ) ; if ( ! retval ) return retval ; } retval = thread . isInterrupted ( ) ; if ( handler != null ) { retval = handler . postInterruptCheck ( retval ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void interrupt ( ) { final Thread thread = mThreads . get ( ) . mThread ; log . trace ( \"interrupt (thread {})\" , thread ) ; thread . interrupt ( ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the FilterGraph this FilterLink belongs to . [CODESPLIT] public FilterGraph getFilterGraph ( ) { long cPtr = VideoJNI . FilterLink_getFilterGraph ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new FilterGraph ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the time base used by the PTS of the frames / samples<br > which will pass through this link . <br > During the configuration stage each filter is supposed to<br > change only the output timebase while the timebase of the<br > input link is assumed to be an unchangeable property . <br > <br > [CODESPLIT] public Rational getTimeBase ( ) { long cPtr = VideoJNI . FilterLink_getTimeBase ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a filter into this link between the current input and output . <br > [CODESPLIT] public void insertFilter ( Filter filter , int srcPadIndex , int dstPadIndex ) { VideoJNI . FilterLink_insertFilter ( swigCPtr , this , Filter . getCPtr ( filter ) , filter , srcPadIndex , dstPadIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the time base that time stamps of this object are represented in . <br > <br > [CODESPLIT] public Rational getTimeBase ( ) { long cPtr = VideoJNI . MediaRaw_getTimeBase ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get any meta - data associated with this media item [CODESPLIT] public KeyValueBag getMetaData ( ) { long cPtr = VideoJNI . MediaRaw_getMetaData ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new KeyValueBag ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the timebase on this object . <br > <br > Note : This will NOT automatically rescale the timestamp set -- so if you change<br > the timebase you almost definitely want to change the timestamp as well . [CODESPLIT] public void setTimeBase ( Rational timeBase ) { VideoJNI . MediaRaw_setTimeBase ( swigCPtr , this , Rational . getCPtr ( timeBase ) , timeBase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a new factory for IURLProtocolHandlers for a given protocol . <p > FFMPEG is very picky ; protocols must be only alpha characters ( no numbers ) . < / p > [CODESPLIT] public IURLProtocolHandlerFactory registerFactory ( String protocol , IURLProtocolHandlerFactory factory ) { if ( protocol == null ) throw new IllegalArgumentException ( \"protocol required\" ) ; IURLProtocolHandlerFactory oldFactory ; if ( factory == null ) oldFactory = mProtocols . remove ( protocol ) ; else oldFactory = mProtocols . put ( protocol , factory ) ; log . trace ( \"Registering factory for URLProtocol: {}\" , protocol ) ; if ( oldFactory == null ) { // we previously didn't have something registered for this factory // so tell FFMPEG we're now the protocol manager for this protocol. log . trace ( \"Letting FFMPEG know about an additional protocol: {}\" , protocol ) ; FfmpegIO . registerProtocolHandler ( protocol , this ) ; } return oldFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get a IURLProtocolHandler for this url . <p > IMPORTANT : This function is called from native code and so the name and signature cannot change without changing the native code . < / p > <p > This function is eventually invoked whenever someone tries to call url_open ( yourprotocol : ... flags ) from FFMPEG native code . It returns a protocol handler which will then have open ( ... ) called on it . < / p > @param url The URL we want to handle . @param flags Any flags that the url_open () function will want to pass . [CODESPLIT] public IURLProtocolHandler getHandler ( String url , int flags ) { IURLProtocolHandler result = null ; log . trace ( \"looking for protocol handler for: {}\" , url ) ; if ( url == null || url . length ( ) == 0 ) throw new IllegalArgumentException ( \"expected valid URL\" ) ; int colonIndex = url . indexOf ( \":\" ) ; String protocol = null ; if ( colonIndex > 0 ) { protocol = url . substring ( 0 , colonIndex ) ; } else { protocol = DEFAULT_PROTOCOL ; } IURLProtocolHandlerFactory factory = mProtocols . get ( protocol ) ; if ( factory != null ) { result = factory . getHandler ( protocol , url , flags ) ; } else { log . error ( \"asked to get handler for unsupported protocol: {}\" , protocol ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the resource portion of a url . For example for the URL <pre > http : // www . humble . io / video < / pre > The protocol string is <code > http< / code > and the resource string is <code > www . humble . io / video< / code > [CODESPLIT] public static String getResourceFromURL ( String url ) { String retval = url ; if ( url != null && url . length ( ) > 0 ) { int colonIndex ; colonIndex = url . indexOf ( \"://\" ) ; if ( colonIndex > 0 ) retval = url . substring ( colonIndex + 3 ) ; else { colonIndex = url . indexOf ( \":\" ) ; if ( colonIndex > 1 ) // handle windows drive letters. { // remove the URL prefix retval = url . substring ( colonIndex + 1 ) ; } } } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the protocol portion of a url . For example for the URL <pre > http : // www . humble . io / video < / pre > The protocol string is <code > http< / code > and the resource string is <code > // www . humble . io / video< / code > [CODESPLIT] public static String getProtocolFromURL ( String url ) { String retval = null ; if ( url != null && url . length ( ) > 0 ) { int colonIndex = url . indexOf ( \":\" ) ; if ( colonIndex > 0 ) { // remove the URL suffix retval = url . substring ( 0 , colonIndex ) ; } } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the CPU architecture based on the passed in javaCPUArch specifier . [CODESPLIT] public static CPUArch getCPUArch ( String javaCPU ) { final CPUArch javaArch ; final String javaCPUArch = javaCPU != null ? javaCPU . toLowerCase ( ) : \"\" ; // first parse the java arch if ( javaCPUArch . startsWith ( \"x86_64\" ) || javaCPUArch . startsWith ( \"amd64\" ) || javaCPUArch . startsWith ( \"ia64\" ) ) { javaArch = CPUArch . X86_64 ; } else if ( javaCPUArch . startsWith ( \"ppc64\" ) || javaCPUArch . startsWith ( \"powerpc64\" ) ) { javaArch = CPUArch . PPC64 ; } else if ( javaCPUArch . startsWith ( \"ppc\" ) || javaCPUArch . startsWith ( \"powerpc\" ) ) { javaArch = CPUArch . PPC ; } else if ( javaCPUArch . contains ( \"86\" ) ) { javaArch = CPUArch . X86 ; } else { javaArch = CPUArch . UNKNOWN ; } return javaArch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a CPUArch from parsing a GNU autoconf triple . [CODESPLIT] public static CPUArch getCPUArchFromGNUString ( String gnuString ) { final String nativeCpu = gnuString . toLowerCase ( ) ; final CPUArch nativeArch ; // then the native arch if ( nativeCpu . startsWith ( \"x86_64\" ) || nativeCpu . startsWith ( \"amd64\" ) || nativeCpu . startsWith ( \"ia64\" ) ) nativeArch = CPUArch . X86_64 ; else if ( nativeCpu . startsWith ( \"ppc64\" ) || nativeCpu . startsWith ( \"powerpc64\" ) ) nativeArch = CPUArch . PPC64 ; else if ( nativeCpu . startsWith ( \"ppc\" ) || nativeCpu . startsWith ( \"powerpc\" ) ) nativeArch = CPUArch . PPC ; else if ( nativeCpu . contains ( \"86\" ) ) nativeArch = CPUArch . X86 ; else nativeArch = CPUArch . UNKNOWN ; return nativeArch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the OSFamily based on the passed in osName specifier . [CODESPLIT] public static OSFamily getOSFamily ( String osName ) { final OSFamily retval ; if ( osName != null && osName . length ( ) > 0 ) { if ( osName . startsWith ( \"Windows\" ) ) retval = OSFamily . WINDOWS ; else if ( osName . startsWith ( \"Mac\" ) ) retval = OSFamily . MAC ; else if ( osName . startsWith ( \"Linux\" ) ) retval = OSFamily . LINUX ; else retval = OSFamily . UNKNOWN ; } else retval = OSFamily . UNKNOWN ; return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an OS Family from parsing a GNU autoconf triple . [CODESPLIT] public static OSFamily getOSFamilyFromGNUString ( String gnuString ) { final String nativeOs = ( gnuString != null ? gnuString . toLowerCase ( ) : \"\" ) ; final OSFamily retval ; if ( nativeOs . startsWith ( \"mingw\" ) || nativeOs . startsWith ( \"cygwin\" ) ) retval = OSFamily . WINDOWS ; else if ( nativeOs . startsWith ( \"darwin\" ) ) retval = OSFamily . MAC ; else if ( nativeOs . startsWith ( \"linux\" ) ) retval = OSFamily . LINUX ; else retval = OSFamily . UNKNOWN ; return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a string representation of the time stamp for this { @link Media } . The format of the resulting string is specified by the format parameter . See { @link java . util . Formatter } for details on how to specify formats however a good place to start is with the following format : <b > %1$tH : %1$tM : %1$tS . %1$tL< / b > [CODESPLIT] public String getFormattedTimeStamp ( String format ) { String retval = null ; java . util . Formatter formatter = new java . util . Formatter ( ) ; try { Rational timeBase = getTimeBase ( ) ; if ( timeBase == null ) timeBase = Rational . make ( 1 , ( int ) Global . DEFAULT_PTS_PER_SECOND ) ; retval = formatter . format ( format , ( long ) ( getTimeStamp ( ) * timeBase . getDouble ( ) * 1000 ) + TIME_OFFSET ) . toString ( ) ; timeBase . delete ( ) ; } finally { formatter . close ( ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the time base that time stamps of this object are represented in . <br > <br > Caller must release the returned value . <br > <br > [CODESPLIT] public Rational getTimeBase ( ) { long cPtr = VideoJNI . Media_getTimeBase ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Rational ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a file and plays the audio from it on the speakers . [CODESPLIT] private static void playSound ( String filename ) throws InterruptedException , IOException , LineUnavailableException { /*\n     * Start by creating a container object, in this case a demuxer since\n     * we are reading, to get audio data from.\n     */ Demuxer demuxer = Demuxer . make ( ) ; /*\n     * Open the demuxer with the filename passed on.\n     */ demuxer . open ( filename , null , false , true , null , null ) ; /*\n     * Query how many streams the call to open found\n     */ int numStreams = demuxer . getNumStreams ( ) ; /*\n     * Iterate through the streams to find the first audio stream\n     */ int audioStreamId = - 1 ; Decoder audioDecoder = null ; for ( int i = 0 ; i < numStreams ; i ++ ) { final DemuxerStream stream = demuxer . getStream ( i ) ; final Decoder decoder = stream . getDecoder ( ) ; if ( decoder != null && decoder . getCodecType ( ) == MediaDescriptor . Type . MEDIA_AUDIO ) { audioStreamId = i ; audioDecoder = decoder ; // stop at the first one. break ; } } if ( audioStreamId == - 1 ) throw new RuntimeException ( \"could not find audio stream in container: \" + filename ) ; /*\n     * Now we have found the audio stream in this file.  Let's open up our decoder so it can\n     * do work.\n     */ audioDecoder . open ( null , null ) ; /*\n     * We allocate a set of samples with the same number of channels as the\n     * coder tells us is in this buffer.\n     */ final MediaAudio samples = MediaAudio . make ( audioDecoder . getFrameSize ( ) , audioDecoder . getSampleRate ( ) , audioDecoder . getChannels ( ) , audioDecoder . getChannelLayout ( ) , audioDecoder . getSampleFormat ( ) ) ; /*\n     * A converter object we'll use to convert Humble Audio to a format that\n     * Java Audio can actually play. The details are complicated, but essentially\n     * this converts any audio format (represented in the samples object) into\n     * a default audio format suitable for Java's speaker system (which will\n     * be signed 16-bit audio, stereo (2-channels), resampled to 22,050 samples\n     * per second).\n     */ final MediaAudioConverter converter = MediaAudioConverterFactory . createConverter ( MediaAudioConverterFactory . DEFAULT_JAVA_AUDIO , samples ) ; /*\n     * An AudioFrame is a wrapper for the Java Sound system that abstracts away\n     * some stuff. Go read the source code if you want -- it's not very complicated.\n     */ final AudioFrame audioFrame = AudioFrame . make ( converter . getJavaFormat ( ) ) ; if ( audioFrame == null ) throw new LineUnavailableException ( ) ; /* We will use this to cache the raw-audio we pass to and from\n     * the java sound system.\n     */ ByteBuffer rawAudio = null ; /*\n     * Now, we start walking through the container looking at each packet. This\n     * is a decoding loop, and as you work with Humble you'll write a lot\n     * of these.\n     * \n     * Notice how in this loop we reuse all of our objects to avoid\n     * reallocating them. Each call to Humble resets objects to avoid\n     * unnecessary reallocation.\n     */ final MediaPacket packet = MediaPacket . make ( ) ; while ( demuxer . read ( packet ) >= 0 ) { /*\n       * Now we have a packet, let's see if it belongs to our audio stream\n       */ if ( packet . getStreamIndex ( ) == audioStreamId ) { /*\n         * A packet can actually contain multiple sets of samples (or frames of samples\n         * in audio-decoding speak).  So, we may need to call decode audio multiple\n         * times at different offsets in the packet's data.  We capture that here.\n         */ int offset = 0 ; int bytesRead = 0 ; do { bytesRead += audioDecoder . decode ( samples , packet , offset ) ; if ( samples . isComplete ( ) ) { rawAudio = converter . toJavaAudio ( rawAudio , samples ) ; audioFrame . play ( rawAudio ) ; } offset += bytesRead ; } while ( offset < packet . getSize ( ) ) ; } } // Some audio decoders (especially advanced ones) will cache // audio data before they begin decoding, so when you are done you need // to flush them. The convention to flush Encoders or Decoders in Humble Video // is to keep passing in null until incomplete samples or packets are returned. do { audioDecoder . decode ( samples , null , 0 ) ; if ( samples . isComplete ( ) ) { rawAudio = converter . toJavaAudio ( rawAudio , samples ) ; audioFrame . play ( rawAudio ) ; } } while ( samples . isComplete ( ) ) ; // It is good practice to close demuxers when you're done to free // up file handles. Humble will EVENTUALLY detect if nothing else // references this demuxer and close it then, but get in the habit // of cleaning up after yourself, and your future girlfriend/boyfriend // will appreciate it. demuxer . close ( ) ; // similar with the demuxer, for the audio playback stuff, clean up after yourself. audioFrame . dispose ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a media container ( file ) as the first argument opens it opens up the default audio device on your system and plays back the audio . [CODESPLIT] public static void main ( String [ ] args ) throws InterruptedException , IOException , LineUnavailableException { final Options options = new Options ( ) ; options . addOption ( \"h\" , \"help\" , false , \"displays help\" ) ; options . addOption ( \"v\" , \"version\" , false , \"version of this library\" ) ; final CommandLineParser parser = new org . apache . commons . cli . BasicParser ( ) ; try { final CommandLine cmd = parser . parse ( options , args ) ; if ( cmd . hasOption ( \"version\" ) ) { // let's find what version of the library we're running final String version = io . humble . video_native . Version . getVersionInfo ( ) ; System . out . println ( \"Humble Version: \" + version ) ; } else if ( cmd . hasOption ( \"help\" ) || args . length == 0 ) { final HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( DecodeAndPlayAudio . class . getCanonicalName ( ) + \" <filename>\" , options ) ; } else { final String [ ] parsedArgs = cmd . getArgs ( ) ; for ( String arg : parsedArgs ) playSound ( arg ) ; } } catch ( ParseException e ) { System . err . println ( \"Exception parsing command line: \" + e . getLocalizedMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Releases any underlying native memory and marks this object as invalid . <p > Normally Ferry manages when to release native memory . < / p > <p > In the unlikely event you want to control EXACTLY when a native object is released each Humble object has a { [CODESPLIT] public void delete ( ) { if ( swigCPtr != 0 ) { // assigning to an object removes an incorrect java // compiler warning for some // generated files Object object = this ; if ( object instanceof RefCounted && mRefCounter != null ) { mRefCounter . delete ( ) ; } else if ( swigCMemOwn ) { swigCMemOwn = false ; } } mJavaRefCount = null ; mRefCounter = null ; mObjectToForceFinalize = null ; mLifecycleReference = null ; swigCPtr = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@deprecated Use { @link JNILibrary } instead . [CODESPLIT] @ Deprecated public static void loadLibrary ( String aLibraryName , Long aMajorVersion ) { getInstance ( ) . loadLibrary0 ( aLibraryName , aMajorVersion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the method that actually loads the library . It maintains an object level lock and since this class only allows a singleton object that is a class - level lock . That means if you re loading a library on one thread other threads will block until it finishes . [CODESPLIT] synchronized void loadLibrary0 ( String aLibraryName , Long aMajorVersion ) { if ( alreadyLoadedLibrary ( aLibraryName , aMajorVersion ) ) // our work is done. return ; List < String > libCandidates = getLibraryCandidates ( aLibraryName , aMajorVersion ) ; if ( libCandidates != null && libCandidates . size ( ) > 0 && ! loadCandidateLibrary ( aLibraryName , aMajorVersion , libCandidates ) ) { // finally, try the System.loadLibrary call try { System . loadLibrary ( aLibraryName ) ; } catch ( UnsatisfiedLinkError e ) { log . error ( \"Could not load library: {}; version: {}.\" , aLibraryName , aMajorVersion == null ? \"\" : aMajorVersion ) ; throw e ; } // and if we get here it means we successfully loaded since no // exception was thrown. Add our library to the cache. setLoadedLibrary ( aLibraryName , aMajorVersion ) ; } log . trace ( \"Successfully Loaded library: {}; Version: {}\" , aLibraryName , aMajorVersion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the cache that we ve loaded this version . [CODESPLIT] void setLoadedLibrary ( String aLibraryName , Long aMajorVersion ) { Set < Long > foundVersions = mLoadedLibraries . get ( aLibraryName ) ; if ( foundVersions == null ) { foundVersions = new HashSet < Long > ( ) ; mLoadedLibraries . put ( aLibraryName , foundVersions ) ; } foundVersions . add ( aMajorVersion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates through the set of aLibCandidates until it succeeds in loading a library . If it succeeds it lets the cache know . [CODESPLIT] boolean loadCandidateLibrary ( String aLibraryName , Long aMajorVersion , List < String > aLibCandidates ) { boolean retval = false ; for ( String candidate : aLibCandidates ) { log . trace ( \"Attempt: library load of library: {}; version: {}: relative path: {}\" , new Object [ ] { aLibraryName , aMajorVersion == null ? \"<unspecified>\" : aMajorVersion . longValue ( ) , candidate } ) ; File candidateFile = new File ( candidate ) ; if ( candidateFile . exists ( ) ) { String absPath = candidateFile . getAbsolutePath ( ) ; try { log . trace ( \"Attempt: library load of library: {}; version: {}: absolute path: {}\" , new Object [ ] { aLibraryName , aMajorVersion == null ? \"<unspecified>\" : aMajorVersion . longValue ( ) , absPath } ) ; // Here's where we attempt the actual load. System . load ( absPath ) ; log . trace ( \"Success: library load of library: {}; version: {}: absolute path: {}\" , new Object [ ] { aLibraryName , aMajorVersion == null ? \"<unspecified>\" : aMajorVersion . longValue ( ) , absPath } ) ; // if we got here, we loaded successfully setLoadedLibrary ( aLibraryName , aMajorVersion ) ; retval = true ; break ; } catch ( UnsatisfiedLinkError e ) { log . warn ( \"Failure: library load of library: {}; version: {}: absolute path: {}; error: {}\" , new Object [ ] { aLibraryName , aMajorVersion == null ? \"<unspecified>\" : aMajorVersion . longValue ( ) , absPath , e } ) ; } catch ( SecurityException e ) { log . warn ( \"Failure: library load of library: {}; version: {}: absolute path: {}; error: {}\" , new Object [ ] { aLibraryName , aMajorVersion == null ? \"<unspecified>\" : aMajorVersion . longValue ( ) , absPath , e } ) ; } } } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given library and the OS we re running on this method generates a list of potential absolute file paths that { @link #loadCandidateLibrary ( String Long String [] ) } should attempt ( in order ) to load . This method will not check for existence and readability of the file we re attempting to load . [CODESPLIT] List < String > getLibraryCandidates ( String aLibraryName , Long aMajorVersion ) { final List < String > retval = new LinkedList < String > ( ) ; // Note: when done each of these variables must be set to a non-null, non // empty string array final String [ ] prefixes ; final String [ ] suffixes ; final String [ ] preSuffixVersions ; final String [ ] postSuffixVersions ; switch ( getOS ( ) ) { case Unknown : case Linux : prefixes = new String [ ] { \"lib\" , \"\" } ; suffixes = new String [ ] { \".so\" } ; preSuffixVersions = new String [ ] { \"\" } ; postSuffixVersions = ( aMajorVersion == null ? new String [ ] { \"\" } : new String [ ] { \".\" + aMajorVersion . longValue ( ) } ) ; break ; case Windows : prefixes = new String [ ] { \"lib\" , \"\" , \"cyg\" } ; suffixes = new String [ ] { \".dll\" } ; preSuffixVersions = ( aMajorVersion == null ? new String [ ] { \"\" } : new String [ ] { \"-\" + aMajorVersion . longValue ( ) } ) ; postSuffixVersions = new String [ ] { \"\" } ; break ; case MacOSX : prefixes = new String [ ] { \"lib\" , \"\" } ; suffixes = new String [ ] { \".dylib\" } ; preSuffixVersions = ( aMajorVersion == null ? new String [ ] { \"\" } : new String [ ] { \".\" + aMajorVersion . longValue ( ) } ) ; postSuffixVersions = new String [ ] { \"\" } ; break ; default : // really no cases should get here prefixes = null ; suffixes = null ; preSuffixVersions = null ; postSuffixVersions = null ; break ; } initializeSearchPaths ( ) ; // First check the versioned paths if ( aMajorVersion != null ) { for ( String directory : mJavaPropPaths ) { generateFileNames ( retval , directory , aLibraryName , prefixes , suffixes , preSuffixVersions , postSuffixVersions , true ) ; } for ( String directory : mJavaEnvPaths ) { generateFileNames ( retval , directory , aLibraryName , prefixes , suffixes , preSuffixVersions , postSuffixVersions , true ) ; } } for ( String directory : mJavaPropPaths ) { generateFileNames ( retval , directory , aLibraryName , prefixes , suffixes , preSuffixVersions , postSuffixVersions , false ) ; } for ( String directory : mJavaEnvPaths ) { generateFileNames ( retval , directory , aLibraryName , prefixes , suffixes , preSuffixVersions , postSuffixVersions , false ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the paths we ll search for libraries in . [CODESPLIT] private void initializeSearchPaths ( ) { String pathVar = null ; if ( mJavaPropPaths == null ) { pathVar = System . getProperty ( \"java.library.path\" , \"\" ) ; log . trace ( \"property java.library.path: {}\" , pathVar ) ; mJavaPropPaths = getEntitiesFromPath ( pathVar ) ; } if ( mJavaEnvPaths == null ) { String envVar = getSystemRuntimeLibraryPathVar ( ) ; pathVar = System . getenv ( envVar ) ; log . trace ( \"OS environment runtime shared library path ({}): {}\" , envVar , pathVar ) ; mJavaEnvPaths = getEntitiesFromPath ( pathVar ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks our cache to see if we ve already loaded this library . [CODESPLIT] boolean alreadyLoadedLibrary ( String aLibraryName , Long aMajorVersion ) { boolean retval = false ; Set < Long > foundVersions = mLoadedLibraries . get ( aLibraryName ) ; if ( foundVersions != null ) { // we found at least some versions if ( aMajorVersion == null || foundVersions . contains ( aMajorVersion ) ) { retval = true ; } else { log . warn ( \"Attempting load of {}, version {}, but already loaded verions: {}.\" + \"  We will attempt to load the specified version but behavior is undefined\" , new Object [ ] { aLibraryName , aMajorVersion , foundVersions . toArray ( ) } ) ; } } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Decoder that will use the given Codec . <br > <br > [CODESPLIT] public static Decoder make ( Codec codec ) { long cPtr = VideoJNI . Decoder_make__SWIG_0 ( Codec . getCPtr ( codec ) , codec ) ; return ( cPtr == 0 ) ? null : new Decoder ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Decoder from a given Coder ( either an encoder or a decoder ) . <br > [CODESPLIT] public static Decoder make ( Coder src ) { long cPtr = VideoJNI . Decoder_make__SWIG_1 ( Coder . getCPtr ( src ) , src ) ; return ( cPtr == 0 ) ? null : new Decoder ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode this packet into output . It will<br > try to fill up the audio samples object starting<br > from the byteOffset inside this packet . <br > <p > <br > The caller is responsible for allocating the<br > MediaAudio object . This function will overwrite<br > any data in the samples object . <br > < / p > <br > [CODESPLIT] public int decodeAudio ( MediaAudio output , MediaPacket packet , int byteOffset ) { return VideoJNI . Decoder_decodeAudio ( swigCPtr , this , MediaAudio . getCPtr ( output ) , output , MediaPacket . getCPtr ( packet ) , packet , byteOffset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode this packet into output . <br > <br > The caller is responsible for allocating the<br > MediaPicture object . This function will potentially<br > overwrite any data in the frame object but<br > you should pass the same MediaPicture into this function<br > repeatedly until Media . isComplete () is true . <br > <p > <br > Note on memory for MediaPicture : For a multitude of reasons <br > if you created MediaPicture from a buffer decodeVideo will discard<br > it and replace it with a buffer that is aligned correctly for different<br > CPUs and different codecs . If you must have a copy of the image data<br > in memory managed by you then pass in a MediaPicture allocated without<br > a buffer to DecodeVideo and then copy that into your own media picture . <br > < / p > <br > <br > [CODESPLIT] public int decodeVideo ( MediaPicture output , MediaPacket packet , int byteOffset ) { return VideoJNI . Decoder_decodeVideo ( swigCPtr , this , MediaPicture . getCPtr ( output ) , output , MediaPacket . getCPtr ( packet ) , packet , byteOffset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode this packet into output . It will<br > try to fill up the media object starting<br > from the byteOffset inside this packet . <br > <p > <br > The caller is responsible for allocating the<br > correct underlying Media object . This function will overwrite<br > any data in the samples object . <br > < / p > <br > [CODESPLIT] public int decode ( MediaSampled output , MediaPacket packet , int byteOffset ) { return VideoJNI . Decoder_decode ( swigCPtr , this , MediaSampled . getCPtr ( output ) , output , MediaPacket . getCPtr ( packet ) , packet , byteOffset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records the screen [CODESPLIT] private static void recordScreen ( String filename , String formatname , String codecname , int duration , int snapsPerSecond ) throws AWTException , InterruptedException , IOException { /**\n     * Set up the AWT infrastructure to take screenshots of the desktop.\n     */ final Robot robot = new Robot ( ) ; final Toolkit toolkit = Toolkit . getDefaultToolkit ( ) ; final Rectangle screenbounds = new Rectangle ( toolkit . getScreenSize ( ) ) ; final Rational framerate = Rational . make ( 1 , snapsPerSecond ) ; /** First we create a muxer using the passed in filename and formatname if given. */ final Muxer muxer = Muxer . make ( filename , null , formatname ) ; /** Now, we need to decide what type of codec to use to encode video. Muxers\n     * have limited sets of codecs they can use. We're going to pick the first one that\n     * works, or if the user supplied a codec name, we're going to force-fit that\n     * in instead.\n     */ final MuxerFormat format = muxer . getFormat ( ) ; final Codec codec ; if ( codecname != null ) { codec = Codec . findEncodingCodecByName ( codecname ) ; } else { codec = Codec . findEncodingCodec ( format . getDefaultVideoCodecId ( ) ) ; } /**\n     * Now that we know what codec, we need to create an encoder\n     */ Encoder encoder = Encoder . make ( codec ) ; /**\n     * Video encoders need to know at a minimum:\n     *   width\n     *   height\n     *   pixel format\n     * Some also need to know frame-rate (older codecs that had a fixed rate at which video files could\n     * be written needed this). There are many other options you can set on an encoder, but we're\n     * going to keep it simpler here.\n     */ encoder . setWidth ( screenbounds . width ) ; encoder . setHeight ( screenbounds . height ) ; // We are going to use 420P as the format because that's what most video formats these days use final PixelFormat . Type pixelformat = PixelFormat . Type . PIX_FMT_YUV420P ; encoder . setPixelFormat ( pixelformat ) ; encoder . setTimeBase ( framerate ) ; /** An annoynace of some formats is that they need global (rather than per-stream) headers,\n     * and in that case you have to tell the encoder. And since Encoders are decoupled from\n     * Muxers, there is no easy way to know this beyond \n     */ if ( format . getFlag ( MuxerFormat . Flag . GLOBAL_HEADER ) ) encoder . setFlag ( Encoder . Flag . FLAG_GLOBAL_HEADER , true ) ; /** Open the encoder. */ encoder . open ( null , null ) ; /** Add this stream to the muxer. */ muxer . addNewStream ( encoder ) ; /** And open the muxer for business. */ muxer . open ( null , null ) ; /** Next, we need to make sure we have the right MediaPicture format objects\n     * to encode data with. Java (and most on-screen graphics programs) use some\n     * variant of Red-Green-Blue image encoding (a.k.a. RGB or BGR). Most video\n     * codecs use some variant of YCrCb formatting. So we're going to have to\n     * convert. To do that, we'll introduce a MediaPictureConverter object later. object.\n     */ MediaPictureConverter converter = null ; final MediaPicture picture = MediaPicture . make ( encoder . getWidth ( ) , encoder . getHeight ( ) , pixelformat ) ; picture . setTimeBase ( framerate ) ; /** Now begin our main loop of taking screen snaps.\n     * We're going to encode and then write out any resulting packets. */ final MediaPacket packet = MediaPacket . make ( ) ; for ( int i = 0 ; i < duration / framerate . getDouble ( ) ; i ++ ) { /** Make the screen capture && convert image to TYPE_3BYTE_BGR */ final BufferedImage screen = convertToType ( robot . createScreenCapture ( screenbounds ) , BufferedImage . TYPE_3BYTE_BGR ) ; /** This is LIKELY not in YUV420P format, so we're going to convert it using some handy utilities. */ if ( converter == null ) converter = MediaPictureConverterFactory . createConverter ( screen , picture ) ; converter . toPicture ( picture , screen , i ) ; do { encoder . encode ( packet , picture ) ; if ( packet . isComplete ( ) ) muxer . write ( packet , false ) ; } while ( packet . isComplete ( ) ) ; /** now we'll sleep until it's time to take the next snapshot. */ Thread . sleep ( ( long ) ( 1000 * framerate . getDouble ( ) ) ) ; } /** Encoders, like decoders, sometimes cache pictures so it can do the right key-frame optimizations.\n     * So, they need to be flushed as well. As with the decoders, the convention is to pass in a null\n     * input until the output is not complete.\n     */ do { encoder . encode ( packet , null ) ; if ( packet . isComplete ( ) ) muxer . write ( packet , false ) ; } while ( packet . isComplete ( ) ) ; /** Finally, let's clean up after ourselves. */ muxer . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Explicitly deletes the underlying native storage used by the object this object references . The underlying native object is now no long valid and attempts to use it could cause unspecified behavior . [CODESPLIT] public void delete ( ) { // acquire lock for minimum time final long swigPtr = mSwigCPtr . getAndSet ( 0 ) ; if ( swigPtr != 0 ) { if ( mJavaRefCount . decrementAndGet ( ) == 0 ) { // log.debug(\"deleting: {}; {}\", this, mSwigCPtr); FerryJNI . RefCounted_release ( swigPtr , null ) ; } // Free the memory manager we use mMemAllocator = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds audio to this source . NOTE : If you had audio to a FilterSource<br > be careful with re - using or rewriting the underlying data . Filters will<br > try hard to avoid copying data so if you change the data out from under<br > them unexpected results can occur . <br > [CODESPLIT] public void addAudio ( MediaAudio audio ) { VideoJNI . FilterAudioSource_addAudio ( swigCPtr , this , MediaAudio . getCPtr ( audio ) , audio ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resample in to out based on the resampler parameters . <br > <br > Resamples the in media based on the parameters set when<br > this resampler was constructed . <br > <br > [CODESPLIT] public int resample ( MediaSampled out , MediaSampled in ) { return VideoJNI . MediaResampler_resample ( swigCPtr , this , MediaSampled . getCPtr ( out ) , out , MediaSampled . getCPtr ( in ) , in ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a sample format corresponding to name or SAMPLE_FMT_NONE<br > on error . [CODESPLIT] public static AudioFormat . Type getFormat ( String name ) { return AudioFormat . Type . swigToEnum ( VideoJNI . AudioFormat_getFormat ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the planar&lt ; - &gt ; packed alternative form of the given sample format or<br > SAMPLE_FMT_NONE on error . If the passed sample_fmt is already in the<br > requested planar / packed format the format returned is the same as the<br > input . [CODESPLIT] public static AudioFormat . Type getAlternateSampleFormat ( AudioFormat . Type sample_fmt , boolean planar ) { return AudioFormat . Type . swigToEnum ( VideoJNI . AudioFormat_getAlternateSampleFormat ( sample_fmt . swigValue ( ) , planar ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the packed alternative form of the given sample format . <br > <br > If the passed sample_fmt is already in packed format the format returned is<br > the same as the input . <br > <br > [CODESPLIT] public static AudioFormat . Type getPackedSampleFormat ( AudioFormat . Type sample_fmt ) { return AudioFormat . Type . swigToEnum ( VideoJNI . AudioFormat_getPackedSampleFormat ( sample_fmt . swigValue ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the planar alternative form of the given sample format . <br > <br > If the passed sample_fmt is already in planar format the format returned is<br > the same as the input . <br > <br > [CODESPLIT] public static AudioFormat . Type getPlanarSampleFormat ( AudioFormat . Type sample_fmt ) { return AudioFormat . Type . swigToEnum ( VideoJNI . AudioFormat_getPlanarSampleFormat ( sample_fmt . swigValue ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the size of a buffer in bytes that would be required to hold the<br > number of samples of audio in the given format and with the given number of channels . [CODESPLIT] public static int getBufferSizeNeeded ( int numSamples , int numChannels , AudioFormat . Type format ) { return VideoJNI . AudioFormat_getBufferSizeNeeded ( numSamples , numChannels , format . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the size of a plane of audio bytes that would be required to hold the<br > number of samples of audio in the given format and with the given number of channels . <br > <p > <br > If format is packed then this method returns the same number as #getBufferSizeNeeded ( int int Type ) . <br > < / p > [CODESPLIT] public static int getDataPlaneSizeNeeded ( int numSamples , int numChannels , AudioFormat . Type format ) { return VideoJNI . AudioFormat_getDataPlaneSizeNeeded ( numSamples , numChannels , format . swigValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new muxer . <br > <br > One of the three passed in parameter must be non - null . If the muxer requires a URL to write to <br > then that must be specified . <br > <br > [CODESPLIT] public static Muxer make ( String filename , MuxerFormat format , String formatName ) { long cPtr = VideoJNI . Muxer_make ( filename , MuxerFormat . getCPtr ( format ) , format , formatName ) ; return ( cPtr == 0 ) ? null : new Muxer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the MuxerFormat associated with this Muxer<br > or null if unknown . [CODESPLIT] public MuxerFormat getFormat ( ) { long cPtr = VideoJNI . Muxer_getFormat ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new MuxerFormat ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the Muxer and write any headers . <br > <br > [CODESPLIT] public void open ( KeyValueBag inputOptions , KeyValueBag outputOptions ) throws java . lang . InterruptedException , java . io . IOException { VideoJNI . Muxer_open ( swigCPtr , this , KeyValueBag . getCPtr ( inputOptions ) , inputOptions , KeyValueBag . getCPtr ( outputOptions ) , outputOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new stream that will have packets written to it . <br > <br > Note on thread safety : Callers must ensure that the coder is not encoding or decoding<br > packets at the same time that Muxer#open or Muxer#close is being called . <br > <br > [CODESPLIT] public MuxerStream addNewStream ( Coder coder ) { long cPtr = VideoJNI . Muxer_addNewStream ( swigCPtr , this , Coder . getCPtr ( coder ) , coder ) ; return ( cPtr == 0 ) ? null : new MuxerStream ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the MuxerStream at the given position . [CODESPLIT] public MuxerStream getStream ( int position ) throws java . lang . InterruptedException , java . io . IOException { long cPtr = VideoJNI . Muxer_getStream ( swigCPtr , this , position ) ; return ( cPtr == 0 ) ? null : new MuxerStream ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the given packet to the Muxer . <br > <br > [CODESPLIT] public boolean write ( MediaPacket packet , boolean forceInterleave ) { return VideoJNI . Muxer_write ( swigCPtr , this , MediaPacket . getCPtr ( packet ) , packet , forceInterleave ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JNIHelper . swg : End generated code [CODESPLIT] public static Mutex make ( ) { long cPtr = FerryJNI . Mutex_make ( ) ; return ( cPtr == 0 ) ? null : new Mutex ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the CodecId for the n th codec supported by this container . <br > <br > [CODESPLIT] protected Codec . ID getSupportedCodecId ( int n ) { return Codec . ID . swigToEnum ( VideoJNI . DemuxerFormat_getSupportedCodecId ( swigCPtr , this , n ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find DemuxerFormat based on the short name of the input format . <br > [CODESPLIT] public static DemuxerFormat findFormat ( String shortName ) { long cPtr = VideoJNI . DemuxerFormat_findFormat ( shortName ) ; return ( cPtr == 0 ) ? null : new DemuxerFormat ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an object for the DemuxerFormats at the given index . <br > <br > [CODESPLIT] protected static DemuxerFormat getFormat ( int index ) { long cPtr = VideoJNI . DemuxerFormat_getFormat ( index ) ; return ( cPtr == 0 ) ? null : new DemuxerFormat ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The number of streams in this container . <br > <p > If this container is a Source this will query the stream and find out<br > how many streams are in it . < / p > <p > If the current thread is interrupted while this blocking method<br > is running the method will return with a negative value . <br > To check if the method exited because of an interruption<br > pass the return value to Error#make ( int ) and then<br > check Error#getType () to see if it is<br > Error . Type#ERROR_INTERRUPTED . <br > < / p > <br > <br > [CODESPLIT] public int getNumStreams ( ) throws java . lang . InterruptedException , java . io . IOException { return VideoJNI . Container_getNumStreams ( swigCPtr , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Coder that this stream was created with . <br > Note : this can be either an Encoder or a Decoder . [CODESPLIT] public Coder getCoder ( ) { long cPtr = VideoJNI . MuxerStream_getCoder ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Coder ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Muxer that this stream belongs to . [CODESPLIT] public Muxer getMuxer ( ) { long cPtr = VideoJNI . MuxerStream_getMuxer ( swigCPtr , this ) ; return ( cPtr == 0 ) ? null : new Muxer ( cPtr , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a signed SetScript object . [CODESPLIT] public static SetScriptTransaction makeScriptTx ( PrivateKeyAccount sender , String script , byte chainId , long fee , long timestamp ) { return new SetScriptTransaction ( sender , script , chainId , fee , timestamp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the given base58 string into the original data bytes . [CODESPLIT] public static byte [ ] decode ( String input ) throws IllegalArgumentException { if ( input . startsWith ( \"base58:\" ) ) input = input . substring ( 7 ) ; if ( input . length ( ) == 0 ) return new byte [ 0 ] ; // Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits). byte [ ] input58 = new byte [ input . length ( ) ] ; for ( int i = 0 ; i < input . length ( ) ; ++ i ) { char c = input . charAt ( i ) ; int digit = c < 128 ? INDEXES [ c ] : - 1 ; if ( digit < 0 ) { throw new IllegalArgumentException ( \"Illegal character \" + c + \" at position \" + i ) ; } input58 [ i ] = ( byte ) digit ; } // Count leading zeros. int zeros = 0 ; while ( zeros < input58 . length && input58 [ zeros ] == 0 ) { ++ zeros ; } // Convert base-58 digits to base-256 digits. byte [ ] decoded = new byte [ input . length ( ) ] ; int outputStart = decoded . length ; for ( int inputStart = zeros ; inputStart < input58 . length ; ) { decoded [ -- outputStart ] = divmod ( input58 , inputStart , 58 , 256 ) ; if ( input58 [ inputStart ] == 0 ) { ++ inputStart ; // optimization - skip leading zeros } } // Ignore extra leading zeroes that were added during the calculation. while ( outputStart < decoded . length && decoded [ outputStart ] == 0 ) { ++ outputStart ; } // Return decoded data (including original number of leading zeros). return Arrays . copyOfRange ( decoded , outputStart - zeros , decoded . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a 15 - word random seed . This method implements the BIP - 39 algorithm with 160 bits of entropy . [CODESPLIT] public static String generateSeed ( ) { byte [ ] bytes = new byte [ 21 ] ; new SecureRandom ( ) . nextBytes ( bytes ) ; byte [ ] rhash = hash ( bytes , 0 , 20 , SHA256 ) ; bytes [ 20 ] = rhash [ 0 ] ; BigInteger rand = new BigInteger ( bytes ) ; BigInteger mask = new BigInteger ( new byte [ ] { 0 , 0 , 7 , - 1 } ) ; // 11 lower bits StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < 15 ; i ++ ) { sb . append ( i > 0 ? ' ' : \"\" ) . append ( SEED_WORDS [ rand . and ( mask ) . intValue ( ) ] ) ; rand = rand . shiftRight ( 11 ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns object by its ID . [CODESPLIT] public Transaction getTransaction ( String txId ) throws IOException { return wavesJsonMapper . convertValue ( send ( \"/transactions/info/\" + txId ) , Transaction . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns transactions by address with limit . [CODESPLIT] public List < Transaction > getAddressTransactions ( String address , int limit ) throws IOException { return getAddressTransactions ( address , limit , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns transactions by address with limit after passed transaction id . [CODESPLIT] public List < Transaction > getAddressTransactions ( String address , int limit , String after ) throws IOException { String requestUrl = String . format ( \"/transactions/address/%s/limit/%d\" , address , limit ) ; if ( after != null ) { requestUrl += String . format ( \"?after=%s\" , after ) ; } return wavesJsonMapper . < List < List < Transaction > > > convertValue ( send ( requestUrl ) , new TypeReference < List < List < Transaction > > > ( ) { } ) . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns seq of block headers [CODESPLIT] public List < BlockHeader > getBlockHeaderSeq ( int from , int to ) throws IOException { String path = String . format ( \"/blocks/headers/seq/%s/%s\" , from , to ) ; HttpResponse r = exec ( request ( path ) ) ; return parse ( r , BLOCK_HEADER_LIST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns block by its signature . [CODESPLIT] public Block getBlock ( String signature ) throws IOException { return wavesJsonMapper . convertValue ( send ( \"/blocks/signature/\" + signature ) , Block . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a signed object and returns its ID . [CODESPLIT] public String send ( Transaction tx ) throws IOException { return parse ( exec ( request ( tx ) ) , \"id\" ) . asText ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a validating script for an account . [CODESPLIT] public String setScript ( PrivateKeyAccount from , String script , byte chainId , long fee ) throws IOException { return send ( Transactions . makeScriptTx ( from , compileScript ( script ) , chainId , fee ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles a script . [CODESPLIT] public String compileScript ( String script ) throws IOException { if ( script == null || script . isEmpty ( ) ) { return null ; } HttpPost request = new HttpPost ( uri . resolve ( \"/utils/script/compile\" ) ) ; request . setEntity ( new StringEntity ( script ) ) ; return parse ( exec ( request ) , \"script\" ) . asText ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write the contents of a given object [CODESPLIT] @ Override public void writeObject ( FSTObjectOutput out , Object toWrite , FSTClazzInfo clzInfo , FSTClazzInfo . FSTFieldInfo referencedBy , int streamPosition ) throws IOException { FSTStruct str = ( FSTStruct ) toWrite ; if ( ! str . isOffHeap ( ) ) { str = str . toOffHeap ( ) ; } int byteSize = str . getByteSize ( ) ; out . writeInt ( byteSize ) ; if ( COMPRESS ) { long base = str . ___offset ; int intsiz = byteSize / 4 ; for ( int i = 0 ; i < intsiz ; i ++ ) { int value = str . getInt ( ) ; value = ( value << 1 ) ^ ( value >> 31 ) ; str . ___offset += 4 ; while ( ( value & 0xFFFFFF80 ) != 0L ) { out . writeByte ( ( value & 0x7F ) | 0x80 ) ; value >>>= 7 ; } out . writeByte ( value & 0x7F ) ; } int remainder = byteSize & 3 ; for ( int i = 0 ; i < remainder ; i ++ ) { byte aByte = str . getByte ( ) ; out . writeByte ( aByte ) ; str . ___offset ++ ; } str . ___offset = base ; } else { byte b [ ] = new byte [ byteSize ] ; // fixme: cache threadlocal str . getBase ( ) . getArr ( str . getOffset ( ) , b , 0 , byteSize ) ; out . write ( b , 0 , byteSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "len < 127 !!!!! [CODESPLIT] @ Override public String readStringAsc ( ) throws IOException { int len = readFInt ( ) ; if ( ascStringCache == null || ascStringCache . length < len ) ascStringCache = new byte [ len ] ; input . ensureReadAhead ( len ) ; System . arraycopy ( input . buf , input . pos , ascStringCache , 0 , len ) ; input . pos += len ; return new String ( ascStringCache , 0 , 0 , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assumes class header + len already read [CODESPLIT] @ Override public Object readFPrimitiveArray ( Object array , Class componentType , int len ) { try { if ( componentType == byte . class ) { byte [ ] arr = ( byte [ ] ) array ; ensureReadAhead ( arr . length ) ; // fixme: move this stuff to the stream ! System . arraycopy ( input . buf , input . pos , arr , 0 , len ) ; input . pos += len ; return arr ; } else if ( componentType == int . class ) { final int [ ] arr = ( int [ ] ) array ; readFIntArr ( len , arr ) ; return arr ; } else if ( componentType == long . class ) { long [ ] arr = ( long [ ] ) array ; readFLongArr ( len , arr ) ; return arr ; } else if ( componentType == char . class ) { char [ ] arr = ( char [ ] ) array ; for ( int j = 0 ; j < len ; j ++ ) { arr [ j ] = readFChar ( ) ; } return arr ; } else if ( componentType == double . class ) { double [ ] arr = ( double [ ] ) array ; ensureReadAhead ( arr . length * 8 ) ; for ( int j = 0 ; j < len ; j ++ ) { arr [ j ] = readFDouble ( ) ; } return arr ; } else if ( componentType == short . class ) { short [ ] arr = ( short [ ] ) array ; ensureReadAhead ( arr . length * 2 ) ; for ( int j = 0 ; j < len ; j ++ ) { arr [ j ] = readFShort ( ) ; } return arr ; } else if ( componentType == float . class ) { float [ ] arr = ( float [ ] ) array ; ensureReadAhead ( arr . length * 4 ) ; for ( int j = 0 ; j < len ; j ++ ) { arr [ j ] = readFFloat ( ) ; } return arr ; } else if ( componentType == boolean . class ) { boolean [ ] arr = ( boolean [ ] ) array ; ensureReadAhead ( arr . length ) ; for ( int j = 0 ; j < len ; j ++ ) { arr [ j ] = readFByte ( ) == 0 ? false : true ; } return arr ; } else { throw new RuntimeException ( \"unexpected primitive type \" + componentType . getName ( ) ) ; } } catch ( IOException e ) { LOGGER . log ( FSTLogger . Level . ERROR , \"Failed to read primitive array\" , e ) ; FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compressed version [CODESPLIT] public void _readFIntArr ( int len , int [ ] arr ) throws IOException { ensureReadAhead ( 5 * len ) ; final byte buf [ ] = input . buf ; int count = input . pos ; for ( int j = 0 ; j < len ; j ++ ) { final byte head = buf [ count ++ ] ; // -128 = short byte, -127 == 4 byte if ( head > - 127 && head <= 127 ) { arr [ j ] = head ; continue ; } if ( head == - 128 ) { final int ch1 = ( buf [ count ++ ] + 256 ) & 0xff ; final int ch2 = ( buf [ count ++ ] + 256 ) & 0xff ; arr [ j ] = ( short ) ( ( ch1 << 8 ) + ( ch2 << 0 ) ) ; continue ; } else { int ch1 = ( buf [ count ++ ] + 256 ) & 0xff ; int ch2 = ( buf [ count ++ ] + 256 ) & 0xff ; int ch3 = ( buf [ count ++ ] + 256 ) & 0xff ; int ch4 = ( buf [ count ++ ] + 256 ) & 0xff ; arr [ j ] = ( ( ch1 << 24 ) + ( ch2 << 16 ) + ( ch3 << 8 ) + ( ch4 << 0 ) ) ; } } input . pos = count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write prim array no len no tag [CODESPLIT] public void writePrimitiveArray ( Object array , int off , int len ) throws IOException { Class < ? > componentType = array . getClass ( ) . getComponentType ( ) ; if ( componentType == byte . class ) { writeRawBytes ( ( byte [ ] ) array , off , len ) ; } else if ( componentType == char . class ) { writeFCharArr ( ( char [ ] ) array , off , len ) ; } else if ( componentType == short . class ) { writeFShortArr ( ( short [ ] ) array , off , len ) ; } else if ( componentType == int . class ) { writeFIntArr ( ( int [ ] ) array , off , len ) ; } else if ( componentType == double . class ) { writeFDoubleArr ( ( double [ ] ) array , off , len ) ; } else if ( componentType == float . class ) { writeFFloatArr ( ( float [ ] ) array , off , len ) ; } else if ( componentType == long . class ) { writeFLongArr ( ( long [ ] ) array , off , len ) ; } else if ( componentType == boolean . class ) { writeFBooleanArr ( ( boolean [ ] ) array , off , len ) ; } else { throw new RuntimeException ( \"expected primitive array\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "does not write length just plain bytes [CODESPLIT] public void writeRawBytes ( byte [ ] array , int start , int length ) throws IOException { ensureFree ( ( int ) ( pos + length ) ) ; buffout . set ( pos , array , start , length ) ; pos += length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used to write uncompressed int ( guaranteed length = 4 ) at a ( eventually recent ) position [CODESPLIT] @ Override public void writeInt32At ( int position , int v ) { try { ensureFree ( position + 4 ) ; } catch ( IOException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } buffout . putInt ( position , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes current buffer to underlying output and resets buffer . [CODESPLIT] @ Override public void flush ( ) throws IOException { if ( outStream != null ) outStream . write ( getBuffer ( ) , 0 , ( int ) pos ) ; pos = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "throws FSTBufferTooSmallException in case object does not fit into given range [CODESPLIT] public int toMemory ( Object o , long address , int availableSize ) throws IOException { out . resetForReUse ( ) ; writeTarget . setBase ( address , availableSize ) ; out . writeObject ( o ) ; int written = out . getWritten ( ) ; return written ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "determines classname tagging . Overrifing can enforce class tags always or ( JSon ) write as special attribute [CODESPLIT] protected void writeClazzTag ( Class expectedClass , Object o ) { if ( expectedClass == o . getClass ( ) ) { out . writeString ( \"{\" ) ; } else { String stringForType = mapper . getStringForType ( o . getClass ( ) ) ; out . writeString ( stringForType + \" {\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in case readClass already reads full minbin value [CODESPLIT] @ Override public FSTClazzInfo readClass ( ) throws IOException , ClassNotFoundException { if ( lastDirectClass != null ) { FSTClazzInfo clInfo = conf . getCLInfoRegistry ( ) . getCLInfo ( lastDirectClass , conf ) ; lastDirectClass = null ; return clInfo ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "will throw an FSTBufferTooSmallException if buffer is too small . [CODESPLIT] public int toByteArray ( Object obj , byte result [ ] , int resultOffset , int avaiableSize ) { output . resetForReUse ( ) ; try { output . writeObject ( obj ) ; } catch ( IOException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } int written = output . getWritten ( ) ; if ( written > avaiableSize ) { throw FSTBufferTooSmallException . Instance ; } System . arraycopy ( output . getBuffer ( ) , 0 , result , resultOffset , written ) ; return written ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "len < 127 !!!!! [CODESPLIT] @ Override public String readStringAsc ( ) throws IOException { int len = readFInt ( ) ; if ( ascStringCache == null || ascStringCache . length ( ) < len ) ascStringCache = new HeapBytez ( new byte [ len ] ) ; ensureReadAhead ( len ) ; //        System.arraycopy(input.buf, input.pos, ascStringCache, 0, len); input . copyTo ( ascStringCache , 0 , pos , len ) ; pos += len ; return new String ( ascStringCache . getBase ( ) , 0 , 0 , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assumes class header + len already read [CODESPLIT] @ Override public Object readFPrimitiveArray ( Object array , Class componentType , int len ) { // FIXME: if else chaining could be avoided if ( componentType == byte . class ) { ensureReadAhead ( len ) ; byte arr [ ] = ( byte [ ] ) array ; input . getArr ( pos , arr , 0 , len ) ; pos += len ; return arr ; } else if ( componentType == char . class ) { ensureReadAhead ( len * 2 ) ; char [ ] arr = ( char [ ] ) array ; input . getCharArr ( pos , arr , 0 , len ) ; pos += len * 2 ; return arr ; } else if ( componentType == short . class ) { ensureReadAhead ( len * 2 ) ; short [ ] arr = ( short [ ] ) array ; input . getShortArr ( pos , arr , 0 , len ) ; pos += len * 2 ; return arr ; } else if ( componentType == int . class ) { ensureReadAhead ( len * 4 ) ; int [ ] arr = ( int [ ] ) array ; input . getIntArr ( pos , arr , 0 , len ) ; pos += len * 4 ; return arr ; } else if ( componentType == float . class ) { ensureReadAhead ( len * 4 ) ; float [ ] arr = ( float [ ] ) array ; input . getFloatArr ( pos , arr , 0 , len ) ; pos += len * 4 ; return arr ; } else if ( componentType == double . class ) { ensureReadAhead ( len * 8 ) ; double [ ] arr = ( double [ ] ) array ; input . getDoubleArr ( pos , arr , 0 , len ) ; pos += len * 8 ; return arr ; } else if ( componentType == long . class ) { ensureReadAhead ( len * 8 ) ; long [ ] arr = ( long [ ] ) array ; input . getLongArr ( pos , arr , 0 , len ) ; pos += len * 8 ; return arr ; } else if ( componentType == boolean . class ) { ensureReadAhead ( len ) ; boolean [ ] arr = ( boolean [ ] ) array ; input . getBooleanArr ( pos , arr , 0 , len ) ; pos += len ; return arr ; } else { throw new RuntimeException ( \"unexpected primitive type \" + componentType . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obsolete [CODESPLIT] public static String getPackage ( Class clazz ) { String s = clazz . getName ( ) ; int i = s . lastIndexOf ( ' ' ) ; if ( i >= 0 ) { s = s . substring ( i + 2 ) ; } i = s . lastIndexOf ( ' ' ) ; if ( i >= 0 ) { return s . substring ( 0 , i ) ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hack to update underlying file in slices handed out to app [CODESPLIT] public void _setMMFData ( File file , FileChannel fileChannel , Cleaner cleaner ) { this . file = file ; this . fileChannel = fileChannel ; this . cleaner = cleaner ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the specificity of the specified class as defined above . [CODESPLIT] public static int getSpecificity ( final Class < ? > clazz ) { if ( clazz == null ) return 0 ; final LineageInfo lineageInfo = FSTClazzLineageInfo . getLineageInfo ( clazz ) ; return lineageInfo == null ? 0 : lineageInfo . specificity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the lineage of the specified class ordered by specificity ( the class itself is at position 0 since it is most specific in its lineage ) . [CODESPLIT] public static Class < ? > [ ] getLineage ( final Class < ? > clazz ) { final LineageInfo lineageInfo = getLineageInfo ( clazz ) ; return lineageInfo == null ? EMPTY_CLASS_ARRAY : lineageInfo . lineage . toArray ( new Class < ? > [ lineageInfo . lineage . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PRIVILEGED method . You gotta know what your doing here .. [CODESPLIT] public void resizeStore ( long required , long maxgrowbytes ) { if ( mappedFile == null ) throw new RuntimeException ( \"store is full. Required: \" + required ) ; if ( required <= memory . length ( ) ) return ; mutationCount ++ ; System . out . println ( \"resizing underlying \" + mappedFile + \" to \" + required + \" numElem:\" + numElem ) ; long tim = System . currentTimeMillis ( ) ; ( ( MMFBytez ) memory ) . freeAndClose ( ) ; memory = null ; try { File mf = new File ( mappedFile ) ; FileOutputStream f = new FileOutputStream ( mf , true ) ; long len = mf . length ( ) ; required = required + Math . min ( required , maxgrowbytes ) ; byte [ ] toWrite = new byte [ 1000 ] ; long max = ( required - len ) / 1000 ; for ( long i = 0 ; i < max + 2 ; i ++ ) { f . write ( toWrite ) ; } f . flush ( ) ; f . close ( ) ; resetMem ( mappedFile , mf . length ( ) ) ; System . out . println ( \"resizing done in \" + ( System . currentTimeMillis ( ) - tim ) + \" numElemAfter:\" + numElem ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get an entry . the returned ByteSource must be processed immediately as it will be reused internally on next get Warning : Concurrent Modification ( e . g . add remove elements during iteration ) is NOT SUPPORTED and NOT CHECKED . Collect keys to change inside iteration and perform changes after iteration is finished . [CODESPLIT] public BytezByteSource getBinary ( ByteSource key ) { checkThread ( ) ; if ( key . length ( ) != keyLen ) throw new RuntimeException ( \"key must have length \" + keyLen ) ; long aLong = index . get ( key ) ; if ( aLong == 0 ) { return null ; } long off = aLong ; int len = getContentLenFromHeader ( off ) ; off += getHeaderLen ( ) ; tmpValueBytez . setLen ( len ) ; tmpValueBytez . setOff ( off ) ; return tmpValueBytez ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove the key from the binary map [CODESPLIT] public void removeBinary ( ByteSource key ) { checkThread ( ) ; if ( key . length ( ) != keyLen ) throw new RuntimeException ( \"key must have length \" + keyLen ) ; mutationCount ++ ; long rem = index . get ( key ) ; if ( rem != 0 ) { index . remove ( key ) ; decElems ( ) ; removeEntry ( rem ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public void writeFShortArr ( short [ ] arr , int off , int len ) throws IOException { buffout . ensureFree ( len * 3 ) ; for ( int i = off ; i < off + len ; i ++ ) { short c = arr [ i ] ; if ( c < 255 && c >= 0 ) { buffout . buf [ buffout . pos ++ ] = ( byte ) c ; } else { buffout . buf [ buffout . pos ] = ( byte ) 255 ; buffout . buf [ buffout . pos + 1 ] = ( byte ) ( c >>> 0 ) ; buffout . buf [ buffout . pos + 2 ] = ( byte ) ( c >>> 8 ) ; buffout . pos += 3 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uncompressed version [CODESPLIT] public void writeFIntArr ( int [ ] arr , int off , int len ) throws IOException { int byteLen = arr . length * 4 ; buffout . ensureFree ( byteLen ) ; byte buf [ ] = buffout . buf ; int count = buffout . pos ; int max = off + len ; for ( int i = off ; i < max ; i ++ ) { long anInt = arr [ i ] ; buf [ count ] = ( byte ) ( anInt >>> 0 ) ; buf [ count + 1 ] = ( byte ) ( anInt >>> 8 ) ; buf [ count + 2 ] = ( byte ) ( anInt >>> 16 ) ; buf [ count + 3 ] = ( byte ) ( anInt >>> 24 ) ; count += 4 ; } buffout . pos += byteLen ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compressed version [CODESPLIT] public void _writeFIntArr ( int v [ ] , int off , int len ) throws IOException { final int free = 5 * len ; buffout . ensureFree ( free ) ; final byte [ ] buf = buffout . buf ; int count = buffout . pos ; for ( int i = off ; i < off + len ; i ++ ) { final int anInt = v [ i ] ; if ( anInt > - 127 && anInt <= 127 ) { buffout . buf [ count ++ ] = ( byte ) anInt ; } else if ( anInt >= Short . MIN_VALUE && anInt <= Short . MAX_VALUE ) { buf [ count ++ ] = - 128 ; buf [ count ++ ] = ( byte ) ( ( anInt >>> 0 ) & 0xFF ) ; buf [ count ++ ] = ( byte ) ( ( anInt >>> 8 ) & 0xFF ) ; } else { buf [ count ++ ] = - 127 ; buf [ count ++ ] = ( byte ) ( ( anInt >>> 0 ) & 0xFF ) ; buf [ count ++ ] = ( byte ) ( ( anInt >>> 8 ) & 0xFF ) ; buf [ count ++ ] = ( byte ) ( ( anInt >>> 16 ) & 0xFF ) ; buf [ count ++ ] = ( byte ) ( ( anInt >>> 24 ) & 0xFF ) ; } } buffout . pos = count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "does not write length just plain bytes [CODESPLIT] public void writeRawBytes ( byte [ ] array , int start , int length ) throws IOException { buffout . ensureFree ( length ) ; System . arraycopy ( array , start , buffout . buf , buffout . pos , length ) ; buffout . pos += length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "length < 127 !!!!! [CODESPLIT] void writeStringAsc ( String name ) throws IOException { int len = name . length ( ) ; if ( len >= 127 ) { throw new RuntimeException ( \"Ascii String too long\" ) ; } writeFByte ( ( byte ) len ) ; buffout . ensureFree ( len ) ; if ( ascStringCache == null || ascStringCache . length < len ) ascStringCache = new byte [ len ] ; name . getBytes ( 0 , len , ascStringCache , 0 ) ; writeRawBytes ( ascStringCache , 0 , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used to write uncompressed int ( guaranteed length = 4 ) at a ( eventually recent ) position [CODESPLIT] @ Override public void writeInt32At ( int position , int v ) { buffout . buf [ position ] = ( byte ) ( v >>> 0 ) ; buffout . buf [ position + 1 ] = ( byte ) ( v >>> 8 ) ; buffout . buf [ position + 2 ] = ( byte ) ( v >>> 16 ) ; buffout . buf [ position + 3 ] = ( byte ) ( v >>> 24 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if output stream is null just encode into a byte array [CODESPLIT] @ Override public void setOutstream ( OutputStream outstream ) { if ( buffout == null ) { // try reuse buffout = ( FSTOutputStream ) conf . getCachedObject ( FSTOutputStream . class ) ; if ( buffout == null ) // if fail, alloc buffout = new FSTOutputStream ( 1000 , outstream ) ; else buffout . reset ( ) ; // reset resued fstoutput } if ( outstream == null ) buffout . setOutstream ( buffout ) ; else buffout . setOutstream ( outstream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "allocates a StructAccessor ( pointer ) matching the struct data expected in the byte array at given position . The resulting pointer object is not volatile ( not a cached instance ) [CODESPLIT] public FSTStruct createStructWrapper ( Bytez b , long index ) { int clzId = b . getInt ( index + 4 ) ; return createStructPointer ( b , index , clzId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "allocates a StructAccessor ( pointer ) matching the struct data expected in the byte array at given position with given classId . The resulting pointer object is not volatile ( not a cached instance ) . The class id should match the Struct stored in the byte array . ( classId must be the correct struct or a superclass of it ) [CODESPLIT] public FSTStruct createStructPointer ( Bytez b , long index , int clzId ) { //        synchronized (this) // FIXME FIXME FIXME: contention point // desynced expecting class registering happens on startup { Class clazz = mIntToClz . get ( clzId ) ; if ( clazz == null ) throw new RuntimeException ( \"unregistered class \" + clzId ) ; try { return ( FSTStruct ) createWrapper ( clazz , b , index ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a json conf with given attributes . Note that shared refs = true for jason might be not as stable as for binary encodings as fst relies on stream positions to identify objects within a given input so any inbetween formatting will break proper reference resolution . [CODESPLIT] public static FSTConfiguration createJsonConfiguration ( boolean prettyPrint , boolean shareReferences ) { if ( shareReferences && prettyPrint ) { throw new RuntimeException ( \"unsupported flag combination\" ) ; } return createJsonConfiguration ( prettyPrint , shareReferences , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug only very slow ( creates config with each call ) . Creates new conf so custom serializers are ignored . [CODESPLIT] public static void prettyPrintJson ( Object o ) { FSTConfiguration conf = constructJsonConf ( true , true , null ) ; System . out . println ( conf . asJsonString ( o ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "register a custom serializer for a given class or the class and all of its subclasses . Serializers must be configured identical on read / write side and should be set before actually making use of the Configuration . [CODESPLIT] public void registerSerializer ( Class clazz , FSTObjectSerializer ser , boolean alsoForAllSubclasses ) { serializationInfoRegistry . getSerializerRegistry ( ) . putSerializer ( clazz , ser , alsoForAllSubclasses ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "special configuration used internally for struct emulation [CODESPLIT] public static FSTConfiguration createStructConfiguration ( ) { FSTConfiguration conf = new FSTConfiguration ( null ) ; conf . setStructMode ( true ) ; return conf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reuse heavy weight objects . If a FSTStream is closed objects are returned and can be reused by new stream instances . the objects are held in soft references so there should be no memory issues . FIXME : point of contention ! [CODESPLIT] public void returnObject ( Object cached ) { try { while ( ! cacheLock . compareAndSet ( false , true ) ) { // empty } List < SoftReference > li = cachedObjects . get ( cached . getClass ( ) ) ; if ( li == null ) { li = new ArrayList < SoftReference > ( ) ; cachedObjects . put ( cached . getClass ( ) , li ) ; } if ( li . size ( ) < 5 ) li . add ( new SoftReference ( cached ) ) ; } finally { cacheLock . set ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for optimization purposes do not use to benchmark processing time or in a regular program as this methods creates a temporary binaryoutputstream and serializes the object in order to measure the size . [CODESPLIT] public int calcObjectSizeBytesNotAUtility ( Object obj ) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream ( 10000 ) ; FSTObjectOutput ou = new FSTObjectOutput ( bout , this ) ; ou . writeObject ( obj , obj . getClass ( ) ) ; ou . close ( ) ; return bout . toByteArray ( ) . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clear cached softref s and ThreadLocal . [CODESPLIT] public void clearCaches ( ) { try { FSTInputStream . cachedBuffer . set ( null ) ; while ( ! cacheLock . compareAndSet ( false , true ) ) { // empty } cachedObjects . clear ( ) ; } finally { cacheLock . set ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "utility for thread safety and reuse . Do not close the resulting stream . However you should close the given InputStream in [CODESPLIT] public FSTObjectInput getObjectInput ( InputStream in ) { FSTObjectInput fstObjectInput = getIn ( ) ; try { fstObjectInput . resetForReuse ( in ) ; return fstObjectInput ; } catch ( IOException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "take the given array as input . the array is NOT copied . [CODESPLIT] public FSTObjectInput getObjectInput ( byte arr [ ] , int len ) { FSTObjectInput fstObjectInput = getIn ( ) ; try { fstObjectInput . resetForReuseUseArray ( arr , len ) ; return fstObjectInput ; } catch ( IOException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "take the given array and copy it to input . the array IS copied [CODESPLIT] public FSTObjectInput getObjectInputCopyFrom ( byte arr [ ] , int off , int len ) { FSTObjectInput fstObjectInput = getIn ( ) ; try { fstObjectInput . resetForReuseCopyArray ( arr , off , len ) ; return fstObjectInput ; } catch ( IOException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "utility for thread safety and reuse . Do not close the resulting stream . However you should close the given OutputStream out [CODESPLIT] public FSTObjectOutput getObjectOutput ( OutputStream out ) { FSTObjectOutput fstObjectOutput = getOut ( ) ; fstObjectOutput . resetForReUse ( out ) ; return fstObjectOutput ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init right after creation of configuration not during operation as it is not threadsafe regarding mutation currently only for minbin serialization [CODESPLIT] public FSTConfiguration registerCrossPlatformClassMapping ( String [ ] [ ] keysAndVals ) { for ( int i = 0 ; i < keysAndVals . length ; i ++ ) { String [ ] keysAndVal = keysAndVals [ i ] ; registerCrossPlatformClassMapping ( keysAndVal [ 0 ] , keysAndVal [ 1 ] ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "shorthand for registerCrossPlatformClassMapping ( _ _ ) [CODESPLIT] public FSTConfiguration cpMap ( String shortName , Class clz ) { return registerCrossPlatformClassMapping ( shortName , clz . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get cross platform symbolic class identifier [CODESPLIT] public String getCPNameForClass ( Class cl ) { String res = minbinNamesReverse . get ( cl . getName ( ) ) ; if ( res == null ) { if ( cl . isAnonymousClass ( ) ) { return getCPNameForClass ( cl . getSuperclass ( ) ) ; } return cl . getName ( ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convenience [CODESPLIT] public Object asObject ( byte b [ ] ) { try { return getObjectInput ( b ) . readObject ( ) ; } catch ( Exception e ) { System . out . println ( \"unable to decode:\" + new String ( b , 0 , 0 , Math . min ( b . length , 100 ) ) ) ; try { String debug = new String ( b , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e1 ) { // } try { getObjectInput ( b ) . readObject ( ) ; } catch ( Exception e1 ) { // debug hook } FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convenience . ( object must be serializable ) [CODESPLIT] public byte [ ] asByteArray ( Object object ) { FSTObjectOutput objectOutput = getObjectOutput ( ) ; try { objectOutput . writeObject ( object ) ; return objectOutput . getCopyOfWrittenBuffer ( ) ; } catch ( IOException e ) { try { //                FSTConfiguration.prettyPrintJson(object); endless cycle ! } catch ( Exception ee ) { // } FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warning : avoids allocation + copying . The returned byteArray is a direct pointer to underlying buffer . the int length [] is expected to have at least on element . The buffer can be larger than written data therefore length [ 0 ] will contain written length . [CODESPLIT] public byte [ ] asSharedByteArray ( Object object , int length [ ] ) { FSTObjectOutput objectOutput = getObjectOutput ( ) ; try { objectOutput . writeObject ( object ) ; length [ 0 ] = objectOutput . getWritten ( ) ; return objectOutput . getBuffer ( ) ; } catch ( IOException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "utility / debug method . Use asByteArray for programmatic use as the byte array will already by UTF - 8 and ready to be sent on network . [CODESPLIT] public String asJsonString ( Object o ) { if ( getCoderSpecific ( ) instanceof JsonFactory == false ) { return \"can be called on JsonConfiguration only\" ; } else { return new String ( asByteArray ( o ) , StandardCharsets . UTF_8 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper to write series of objects to streams / files > Integer . MAX_VALUE . it - serializes the object - writes the length of the serialized object to the stream - the writes the serialized object data [CODESPLIT] public void encodeToStream ( OutputStream out , Object toSerialize ) throws IOException { FSTObjectOutput objectOutput = getObjectOutput ( ) ; // could also do new with minor perf impact objectOutput . writeObject ( toSerialize ) ; int written = objectOutput . getWritten ( ) ; out . write ( ( written >>> 0 ) & 0xFF ) ; out . write ( ( written >>> 8 ) & 0xFF ) ; out . write ( ( written >>> 16 ) & 0xFF ) ; out . write ( ( written >>> 24 ) & 0xFF ) ; // copy internal buffer to bufferedoutput out . write ( objectOutput . getBuffer ( ) , 0 , written ) ; objectOutput . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@see encodeToStream [CODESPLIT] public Object decodeFromStream ( InputStream in ) throws Exception { int read = in . read ( ) ; if ( read < 0 ) throw new EOFException ( \"stream is closed\" ) ; int ch1 = ( read + 256 ) & 0xff ; int ch2 = ( in . read ( ) + 256 ) & 0xff ; int ch3 = ( in . read ( ) + 256 ) & 0xff ; int ch4 = ( in . read ( ) + 256 ) & 0xff ; int len = ( ch4 << 24 ) + ( ch3 << 16 ) + ( ch2 << 8 ) + ( ch1 << 0 ) ; if ( len <= 0 ) throw new EOFException ( \"stream is corrupted\" ) ; byte buffer [ ] = new byte [ len ] ; // this could be reused ! while ( len > 0 ) { len -= in . read ( buffer , buffer . length - len , len ) ; } return getObjectInput ( buffer ) . readObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sideeffecting : if no ser is found next lookup will return null immediate [CODESPLIT] public FSTObjectSerializer getSer ( ) { if ( ser == null ) { if ( clazz == null ) { return null ; } ser = getSerNoStore ( ) ; if ( ser == null ) { ser = FSTSerializerRegistry . NULL ; } } if ( ser == FSTSerializerRegistry . NULL ) { return null ; } return ser ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write an int type with header [CODESPLIT] public void writeInt ( byte type , long data ) { if ( ! MinBin . isPrimitive ( type ) || MinBin . isArray ( type ) ) throw new RuntimeException ( \"illegal type code\" ) ; writeOut ( type ) ; writeRawInt ( type , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "encode int without header tag [CODESPLIT] protected void writeRawInt ( byte type , long data ) { int numBytes = MinBin . extractNumBytes ( type ) ; for ( int i = 0 ; i < numBytes ; i ++ ) { writeOut ( ( byte ) ( data & 0xff ) ) ; data = data >>> 8 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "encode int using only as much bytes as needed to represent it [CODESPLIT] public void writeIntPacked ( long data ) { if ( data <= Byte . MAX_VALUE && data >= Byte . MIN_VALUE ) writeInt ( MinBin . INT_8 , data ) ; else if ( data <= Short . MAX_VALUE && data >= Short . MIN_VALUE ) writeInt ( MinBin . INT_16 , data ) ; else if ( data <= Integer . MAX_VALUE && data >= Integer . MIN_VALUE ) writeInt ( MinBin . INT_32 , data ) ; else if ( data <= Long . MAX_VALUE && data >= Long . MIN_VALUE ) writeInt ( MinBin . INT_64 , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write primitive array + header . no floating point or object array allowed . Just int based types [CODESPLIT] public void writeArray ( Object primitiveArray , int start , int len ) { byte type = MinBin . ARRAY_MASK ; Class < ? > componentType = primitiveArray . getClass ( ) . getComponentType ( ) ; if ( componentType == boolean . class ) type |= MinBin . INT_8 ; else if ( componentType == byte . class ) type |= MinBin . INT_8 ; else if ( componentType == short . class ) type |= MinBin . INT_16 ; else if ( componentType == char . class ) type |= MinBin . INT_16 | MinBin . UNSIGN_MASK ; else if ( componentType == int . class ) type |= MinBin . INT_32 ; else if ( componentType == long . class ) type |= MinBin . INT_64 ; else throw new RuntimeException ( \"unsupported type \" + componentType . getName ( ) ) ; writeOut ( type ) ; writeIntPacked ( len ) ; switch ( type ) { case MinBin . INT_8 | MinBin . ARRAY_MASK : { if ( componentType == boolean . class ) { boolean [ ] arr = ( boolean [ ] ) primitiveArray ; for ( int i = start ; i < start + len ; i ++ ) { writeRawInt ( type , arr [ i ] ? 1 : 0 ) ; } } else { byte [ ] arr = ( byte [ ] ) primitiveArray ; for ( int i = start ; i < start + len ; i ++ ) { writeRawInt ( type , arr [ i ] ) ; } } } break ; case MinBin . CHAR | MinBin . ARRAY_MASK : { char [ ] charArr = ( char [ ] ) primitiveArray ; for ( int i = start ; i < start + len ; i ++ ) { writeRawInt ( type , charArr [ i ] ) ; } } break ; case MinBin . INT_32 | MinBin . ARRAY_MASK : { int [ ] arr = ( int [ ] ) primitiveArray ; for ( int i = start ; i < start + len ; i ++ ) { writeRawInt ( type , arr [ i ] ) ; } } break ; case MinBin . INT_64 | MinBin . ARRAY_MASK : { long [ ] arr = ( long [ ] ) primitiveArray ; for ( int i = start ; i < start + len ; i ++ ) { writeRawInt ( type , arr [ i ] ) ; } } break ; default : { for ( int i = start ; i < start + len ; i ++ ) { if ( componentType == boolean . class ) writeRawInt ( type , Array . getBoolean ( primitiveArray , i ) ? 1 : 0 ) ; else writeRawInt ( type , Array . getLong ( primitiveArray , i ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "allow write through to underlying byte for performance reasons [CODESPLIT] public void writeRaw ( byte [ ] bufferedName , int i , int length ) { if ( pos + length >= bytez . length - 1 ) { resize ( ) ; } System . arraycopy ( bufferedName , i , bytez , pos , length ) ; pos += length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read into preallocated array allows to write to different type ( e . g . boolean [] from byte [] ) [CODESPLIT] public Object readArrayRaw ( byte type , int len , Object resultingArray ) { Class componentType = resultingArray . getClass ( ) . getComponentType ( ) ; if ( componentType == byte . class ) { byte [ ] barr = ( byte [ ] ) resultingArray ; for ( int i = 0 ; i < len ; i ++ ) { barr [ i ] = ( byte ) readRawInt ( type ) ; } } else if ( componentType == short . class ) { short [ ] sArr = ( short [ ] ) resultingArray ; for ( int i = 0 ; i < len ; i ++ ) { sArr [ i ] = ( short ) readRawInt ( type ) ; } } else if ( componentType == char . class ) { char [ ] cArr = ( char [ ] ) resultingArray ; for ( int i = 0 ; i < len ; i ++ ) { cArr [ i ] = ( char ) readRawInt ( type ) ; } } else if ( componentType == int . class ) { int [ ] iArr = ( int [ ] ) resultingArray ; for ( int i = 0 ; i < len ; i ++ ) { iArr [ i ] = ( int ) readRawInt ( type ) ; } } else if ( componentType == long . class ) { long [ ] lArr = ( long [ ] ) resultingArray ; for ( int i = 0 ; i < len ; i ++ ) { lArr [ i ] = readRawInt ( type ) ; } } else if ( componentType == boolean . class ) { boolean [ ] boolArr = ( boolean [ ] ) resultingArray ; for ( int i = 0 ; i < len ; i ++ ) { boolArr [ i ] = readRawInt ( MinBin . INT_8 ) != 0 ; } } else throw new RuntimeException ( \"unsupported array type \" + resultingArray . getClass ( ) . getName ( ) ) ; return resultingArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////// [CODESPLIT] public void writeObject ( Object obj , Class ... possibles ) throws IOException { if ( isCrossPlatform ) { writeObjectInternal ( obj , null ) ; // not supported cross platform return ; } if ( possibles != null && possibles . length > 1 ) { for ( int i = 0 ; i < possibles . length ; i ++ ) { Class possible = possibles [ i ] ; getCodec ( ) . registerClass ( possible ) ; } } writeObjectInternal ( obj , null , possibles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "avoid creation of dummy ref [CODESPLIT] protected FSTClazzInfo . FSTFieldInfo getCachedFI ( Class ... possibles ) { if ( refs == null ) { refs = refsLocal . get ( ) ; } if ( curDepth >= refs . length ) { return new FSTClazzInfo . FSTFieldInfo ( possibles , null , true ) ; } else { FSTClazzInfo . FSTFieldInfo inf = refs [ curDepth ] ; if ( inf == null ) { inf = new FSTClazzInfo . FSTFieldInfo ( possibles , null , true ) ; refs [ curDepth ] = inf ; return inf ; } inf . setPossibleClasses ( possibles ) ; return inf ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hook for debugging profiling . register a FSTSerialisationListener to use [CODESPLIT] protected void objectWillBeWritten ( Object obj , int streamPosition ) { if ( listener != null ) { listener . objectWillBeWritten ( obj , streamPosition ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hook for debugging profiling . empty impl you need to subclass to make use of this hook [CODESPLIT] protected void objectHasBeenWritten ( Object obj , int oldStreamPosition , int streamPosition ) { if ( listener != null ) { listener . objectHasBeenWritten ( obj , oldStreamPosition , streamPosition ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "splitting this slows down ... [CODESPLIT] protected FSTClazzInfo writeObjectWithContext ( FSTClazzInfo . FSTFieldInfo referencee , Object toWrite , FSTClazzInfo ci ) throws IOException { int startPosition = 0 ; try { if ( toWrite == null ) { getCodec ( ) . writeTag ( NULL , null , 0 , toWrite , this ) ; return null ; } startPosition = getCodec ( ) . getWritten ( ) ; objectWillBeWritten ( toWrite , startPosition ) ; final Class clazz = toWrite . getClass ( ) ; if ( clazz == String . class ) { String [ ] oneOf = referencee . getOneOf ( ) ; if ( oneOf != null ) { for ( int i = 0 ; i < oneOf . length ; i ++ ) { String s = oneOf [ i ] ; if ( s . equals ( toWrite ) ) { getCodec ( ) . writeTag ( ONE_OF , oneOf , i , toWrite , this ) ; getCodec ( ) . writeFByte ( i ) ; return null ; } } } // shortpath if ( ! dontShare && writeHandleIfApplicable ( toWrite , stringInfo ) ) return stringInfo ; getCodec ( ) . writeTag ( STRING , toWrite , 0 , toWrite , this ) ; getCodec ( ) . writeStringUTF ( ( String ) toWrite ) ; return null ; } else if ( clazz == Integer . class ) { getCodec ( ) . writeTag ( BIG_INT , null , 0 , toWrite , this ) ; getCodec ( ) . writeFInt ( ( ( Integer ) toWrite ) . intValue ( ) ) ; return null ; } else if ( clazz == Long . class ) { getCodec ( ) . writeTag ( BIG_LONG , null , 0 , toWrite , this ) ; getCodec ( ) . writeFLong ( ( ( Long ) toWrite ) . longValue ( ) ) ; return null ; } else if ( clazz == Boolean . class ) { getCodec ( ) . writeTag ( ( ( Boolean ) toWrite ) . booleanValue ( ) ? BIG_BOOLEAN_TRUE : BIG_BOOLEAN_FALSE , null , 0 , toWrite , this ) ; return null ; } else if ( ( referencee . getType ( ) != null && referencee . getType ( ) . isEnum ( ) ) || toWrite instanceof Enum ) { return writeEnum ( referencee , toWrite ) ; } FSTClazzInfo serializationInfo = ci == null ? getFstClazzInfo ( referencee , clazz ) : ci ; // check for identical / equal objects FSTObjectSerializer ser = serializationInfo . getSer ( ) ; if ( ! dontShare && ! referencee . isFlat ( ) && ! serializationInfo . isFlat ( ) && ( ser == null || ! ser . alwaysCopy ( ) ) ) { if ( writeHandleIfApplicable ( toWrite , serializationInfo ) ) return serializationInfo ; } if ( clazz . isArray ( ) ) { if ( getCodec ( ) . writeTag ( ARRAY , toWrite , 0 , toWrite , this ) ) return serializationInfo ; // some codecs handle primitive arrays like an primitive type writeArray ( referencee , toWrite ) ; getCodec ( ) . writeArrayEnd ( ) ; } else if ( ser == null ) { // default write object wihtout custom serializer // handle write replace //if ( ! dontShare ) GIT ISSUE 80 FSTClazzInfo originalInfo = serializationInfo ; { if ( serializationInfo . getWriteReplaceMethod ( ) != null ) { Object replaced = null ; try { replaced = serializationInfo . getWriteReplaceMethod ( ) . invoke ( toWrite ) ; } catch ( Exception e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } if ( replaced != toWrite ) { toWrite = replaced ; serializationInfo = getClassInfoRegistry ( ) . getCLInfo ( toWrite . getClass ( ) , conf ) ; // fixme: update object map ? } } // clazz uses some JDK special stuff (frequently slow) if ( serializationInfo . useCompatibleMode ( ) && ! serializationInfo . isExternalizable ( ) ) { writeObjectCompatible ( referencee , toWrite , serializationInfo ) ; return originalInfo ; } } if ( ! writeObjectHeader ( serializationInfo , referencee , toWrite ) ) { // skip in case codec can write object as primitive ser = serializationInfo . getSer ( ) ; if ( ser == null ) { defaultWriteObject ( toWrite , serializationInfo ) ; if ( serializationInfo . isExternalizable ( ) ) getCodec ( ) . externalEnd ( serializationInfo ) ; } else { // handle edge case: there is a serializer registered for replaced class // copied from below :( int pos = getCodec ( ) . getWritten ( ) ; // write object depending on type (custom, externalizable, serializable/java, default) ser . writeObject ( this , toWrite , serializationInfo , referencee , pos ) ; getCodec ( ) . externalEnd ( serializationInfo ) ; } } return originalInfo ; } else { // object has custom serializer // Object header (nothing written till here) if ( ! writeObjectHeader ( serializationInfo , referencee , toWrite ) ) { // skip in case code can write object as primitive int pos = getCodec ( ) . getWritten ( ) ; // write object depending on type (custom, externalizable, serializable/java, default) ser . writeObject ( this , toWrite , serializationInfo , referencee , pos ) ; getCodec ( ) . externalEnd ( serializationInfo ) ; } } return serializationInfo ; } finally { objectHasBeenWritten ( toWrite , startPosition , getCodec ( ) . getWritten ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if class is same as last referenced returned cached clzinfo else do a lookup [CODESPLIT] protected FSTClazzInfo getFstClazzInfo ( FSTClazzInfo . FSTFieldInfo referencee , Class clazz ) { FSTClazzInfo serializationInfo = null ; FSTClazzInfo lastInfo = referencee . lastInfo ; if ( lastInfo != null && lastInfo . getClazz ( ) == clazz && lastInfo . conf == conf ) { serializationInfo = lastInfo ; } else { serializationInfo = getClassInfoRegistry ( ) . getCLInfo ( clazz , conf ) ; referencee . lastInfo = serializationInfo ; } return serializationInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write identical to other version but take field values from hashmap ( because of annoying putField / getField feature ) [CODESPLIT] protected void writeCompatibleObjectFields ( Object toWrite , Map fields , FSTClazzInfo . FSTFieldInfo [ ] fieldInfo ) throws IOException { int booleanMask = 0 ; int boolcount = 0 ; for ( int i = 0 ; i < fieldInfo . length ; i ++ ) { try { FSTClazzInfo . FSTFieldInfo subInfo = fieldInfo [ i ] ; boolean isarr = subInfo . isArray ( ) ; Class subInfType = subInfo . getType ( ) ; if ( subInfType != boolean . class || isarr ) { if ( boolcount > 0 ) { getCodec ( ) . writeFByte ( booleanMask << ( 8 - boolcount ) ) ; boolcount = 0 ; booleanMask = 0 ; } } if ( subInfo . isIntegral ( ) && ! isarr ) { if ( subInfType == boolean . class ) { if ( boolcount == 8 ) { getCodec ( ) . writeFByte ( booleanMask << ( 8 - boolcount ) ) ; boolcount = 0 ; booleanMask = 0 ; } boolean booleanValue = ( ( Boolean ) fields . get ( subInfo . getName ( ) ) ) . booleanValue ( ) ; booleanMask = booleanMask << 1 ; booleanMask = ( booleanMask | ( booleanValue ? 1 : 0 ) ) ; boolcount ++ ; } else if ( subInfType == int . class ) { getCodec ( ) . writeFInt ( ( ( Number ) fields . get ( subInfo . getName ( ) ) ) . intValue ( ) ) ; } else if ( subInfType == long . class ) { getCodec ( ) . writeFLong ( ( ( Number ) fields . get ( subInfo . getName ( ) ) ) . longValue ( ) ) ; } else if ( subInfType == byte . class ) { getCodec ( ) . writeFByte ( ( ( Number ) fields . get ( subInfo . getName ( ) ) ) . byteValue ( ) ) ; } else if ( subInfType == char . class ) { getCodec ( ) . writeFChar ( ( char ) ( ( Number ) fields . get ( subInfo . getName ( ) ) ) . intValue ( ) ) ; } else if ( subInfType == short . class ) { getCodec ( ) . writeFShort ( ( ( Number ) fields . get ( subInfo . getName ( ) ) ) . shortValue ( ) ) ; } else if ( subInfType == float . class ) { getCodec ( ) . writeFFloat ( ( ( Number ) fields . get ( subInfo . getName ( ) ) ) . floatValue ( ) ) ; } else if ( subInfType == double . class ) { getCodec ( ) . writeFDouble ( ( ( Number ) fields . get ( subInfo . getName ( ) ) ) . doubleValue ( ) ) ; } } else { // object Object subObject = fields . get ( subInfo . getName ( ) ) ; writeObjectWithContext ( subInfo , subObject ) ; } } catch ( Exception ex ) { FSTUtil . < RuntimeException > rethrow ( ex ) ; } } if ( boolcount > 0 ) { getCodec ( ) . writeFByte ( booleanMask << ( 8 - boolcount ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "incoming array is already registered [CODESPLIT] protected void writeArray ( FSTClazzInfo . FSTFieldInfo referencee , Object array ) throws IOException { if ( array == null ) { getCodec ( ) . writeClass ( Object . class ) ; getCodec ( ) . writeFInt ( - 1 ) ; return ; } final int len = Array . getLength ( array ) ; Class < ? > componentType = array . getClass ( ) . getComponentType ( ) ; getCodec ( ) . writeClass ( array . getClass ( ) ) ; getCodec ( ) . writeFInt ( len ) ; if ( ! componentType . isArray ( ) ) { if ( getCodec ( ) . isPrimitiveArray ( array , componentType ) ) { getCodec ( ) . writePrimitiveArray ( array , 0 , len ) ; } else { // objects Object arr [ ] = ( Object [ ] ) array ; Class lastClz = null ; FSTClazzInfo lastInfo = null ; for ( int i = 0 ; i < len ; i ++ ) { Object toWrite = arr [ i ] ; if ( toWrite != null ) { lastInfo = writeObjectWithContext ( referencee , toWrite , lastClz == toWrite . getClass ( ) ? lastInfo : null ) ; lastClz = toWrite . getClass ( ) ; } else writeObjectWithContext ( referencee , toWrite , null ) ; } } } else { // multidim array. FIXME shared refs to subarrays are not tested !!! Object [ ] arr = ( Object [ ] ) array ; FSTClazzInfo . FSTFieldInfo ref1 = new FSTClazzInfo . FSTFieldInfo ( referencee . getPossibleClasses ( ) , null , conf . getCLInfoRegistry ( ) . isIgnoreAnnotations ( ) ) ; for ( int i = 0 ; i < len ; i ++ ) { Object subArr = arr [ i ] ; boolean needsWrite = true ; if ( getCodec ( ) . isTagMultiDimSubArrays ( ) ) { if ( subArr == null ) { needsWrite = ! getCodec ( ) . writeTag ( NULL , null , 0 , null , this ) ; } else { needsWrite = ! getCodec ( ) . writeTag ( ARRAY , subArr , 0 , subArr , this ) ; } } if ( needsWrite ) { writeArray ( ref1 , subArr ) ; getCodec ( ) . writeArrayEnd ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if out == null = > automatically create / reuse a bytebuffer [CODESPLIT] public void resetForReUse ( OutputStream out ) { if ( closed ) throw new RuntimeException ( \"Can't reuse closed stream\" ) ; getCodec ( ) . reset ( null ) ; if ( out != null ) { getCodec ( ) . setOutstream ( out ) ; } objects . clearForWrite ( conf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return a copy of written bytes . Warning : if the stream has been flushed this will fail with an exception . a flush is triggered after each 1st level writeObject . [CODESPLIT] public byte [ ] getCopyOfWrittenBuffer ( ) { if ( ! getCodec ( ) . isByteArrayBased ( ) ) { return getBuffer ( ) ; } byte res [ ] = new byte [ getCodec ( ) . getWritten ( ) ] ; byte [ ] buffer = getBuffer ( ) ; System . arraycopy ( buffer , 0 , res , 0 , getCodec ( ) . getWritten ( ) ) ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "some jdk classes hash for ObjectStream so provide the same instance always [CODESPLIT] protected ObjectInputStream getObjectInputStream ( final Class cl , final FSTClazzInfo clInfo , final FSTClazzInfo . FSTFieldInfo referencee , final Object toRead ) throws IOException { ObjectInputStream wrapped = new ObjectInputStream ( ) { @ Override public Object readObjectOverride ( ) throws IOException , ClassNotFoundException { try { byte b = FSTObjectInput . this . readByte ( ) ; if ( b != FSTObjectOutput . SPECIAL_COMPATIBILITY_OBJECT_TAG ) { Constructor < ? > [ ] constructors = OptionalDataException . class . getDeclaredConstructors ( ) ; FSTObjectInput . this . pushBack ( 1 ) ; for ( int i = 0 ; i < constructors . length ; i ++ ) { Constructor constructor = constructors [ i ] ; Class [ ] typeParameters = constructor . getParameterTypes ( ) ; if ( typeParameters != null && typeParameters . length == 1 && typeParameters [ 0 ] == int . class ) { constructor . setAccessible ( true ) ; OptionalDataException ode ; try { ode = ( OptionalDataException ) constructor . newInstance ( 0 ) ; throw ode ; } catch ( InvocationTargetException e ) { break ; } } } throw new EOFException ( \"if your code relies on this, think\" ) ; } return FSTObjectInput . this . readObjectInternal ( referencee . getPossibleClasses ( ) ) ; } catch ( IllegalAccessException e ) { throw new IOException ( e ) ; } catch ( InstantiationException e ) { throw new IOException ( e ) ; } } @ Override public Object readUnshared ( ) throws IOException , ClassNotFoundException { try { return FSTObjectInput . this . readObjectInternal ( referencee . getPossibleClasses ( ) ) ; // fixme } catch ( IllegalAccessException e ) { throw new IOException ( e ) ; } catch ( InstantiationException e ) { throw new IOException ( e ) ; } } @ Override public void defaultReadObject ( ) throws IOException , ClassNotFoundException { try { int tag = readByte ( ) ; if ( tag == 77 ) // came from writeFields { fieldMap = ( HashMap < String , Object > ) FSTObjectInput . this . readObjectInternal ( HashMap . class ) ; // object has been written with writeFields, is no read with defaultReadObjects, // need to autoapply map to object vars. // this might be redundant in case readObject() pulls a getFields() .. (see bitset testcase) for ( Iterator < String > iterator = fieldMap . keySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { String key = iterator . next ( ) ; FSTClazzInfo . FSTFieldInfo fieldInfo = clInfo . getFieldInfo ( key , null ) ; // in case fieldName is not unique => cannot recover/fix if ( fieldInfo != null ) { fieldInfo . setObjectValue ( toRead , fieldMap . get ( key ) ) ; } } } else { FSTObjectInput . this . readObjectFields ( referencee , clInfo , clInfo . getCompInfo ( ) . get ( cl ) . getFieldArray ( ) , toRead , 0 , 0 ) ; // FIXME: only fields of current class } } catch ( Exception e ) { throw new IOException ( e ) ; } } HashMap < String , Object > fieldMap ; @ Override public GetField readFields ( ) throws IOException , ClassNotFoundException { int tag = readByte ( ) ; try { FSTClazzInfo . FSTCompatibilityInfo fstCompatibilityInfo = clInfo . getCompInfo ( ) . get ( cl ) ; if ( tag == 99 ) { // came from defaultwriteobject // Note: in case number and names of instance fields of reader/writer are different, // this fails as code below implicitely assumes, fields of writer == fields of reader // unfortunately one can use defaultWriteObject at writer side but use getFields at reader side // in readObject(). if then fields differ, code below reads BS and fails. // Its impossible to fix that except by always using putField + getField for // JDK compatibility classes, however this will waste lots of performance. As // it would be necessary to *always* write full metainformation (a map of fieldName => value pairs) // see #53 fieldMap = new HashMap < String , Object > ( ) ; FSTObjectInput . this . readCompatibleObjectFields ( referencee , clInfo , fstCompatibilityInfo . getFieldArray ( ) , fieldMap ) ; getCodec ( ) . readVersionTag ( ) ; // consume dummy version tag as created by defaultWriteObject } else if ( tag == 66 ) { // has been written from writeObjectCompatible without writeMethod fieldMap = new HashMap < String , Object > ( ) ; FSTObjectInput . this . readCompatibleObjectFields ( referencee , clInfo , fstCompatibilityInfo . getFieldArray ( ) , fieldMap ) ; getCodec ( ) . readVersionTag ( ) ; // consume dummy version tag as created by defaultWriteObject } else { fieldMap = ( HashMap < String , Object > ) FSTObjectInput . this . readObjectInternal ( HashMap . class ) ; } } catch ( Exception e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } return new GetField ( ) { @ Override public ObjectStreamClass getObjectStreamClass ( ) { return ObjectStreamClass . lookup ( cl ) ; } @ Override public boolean defaulted ( String name ) throws IOException { return fieldMap . get ( name ) == null ; } @ Override public boolean get ( String name , boolean val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Boolean ) fieldMap . get ( name ) ) . booleanValue ( ) ; } @ Override public byte get ( String name , byte val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Byte ) fieldMap . get ( name ) ) . byteValue ( ) ; } @ Override public char get ( String name , char val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Character ) fieldMap . get ( name ) ) . charValue ( ) ; } @ Override public short get ( String name , short val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Short ) fieldMap . get ( name ) ) . shortValue ( ) ; } @ Override public int get ( String name , int val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Integer ) fieldMap . get ( name ) ) . intValue ( ) ; } @ Override public long get ( String name , long val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Long ) fieldMap . get ( name ) ) . longValue ( ) ; } @ Override public float get ( String name , float val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Float ) fieldMap . get ( name ) ) . floatValue ( ) ; } @ Override public double get ( String name , double val ) throws IOException { if ( fieldMap . get ( name ) == null ) { return val ; } return ( ( Double ) fieldMap . get ( name ) ) . doubleValue ( ) ; } @ Override public Object get ( String name , Object val ) throws IOException { Object res = fieldMap . get ( name ) ; if ( res == null ) { return val ; } return res ; } } ; } @ Override public void registerValidation ( ObjectInputValidation obj , int prio ) throws NotActiveException , InvalidObjectException { if ( callbacks == null ) { callbacks = new ArrayList < CallbackEntry > ( ) ; } callbacks . add ( new CallbackEntry ( obj , prio ) ) ; } @ Override public int read ( ) throws IOException { return getCodec ( ) . readFByte ( ) ; } @ Override public int read ( byte [ ] buf , int off , int len ) throws IOException { return FSTObjectInput . this . read ( buf , off , len ) ; } @ Override public int available ( ) throws IOException { return FSTObjectInput . this . available ( ) ; } @ Override public void close ( ) throws IOException { } @ Override public boolean readBoolean ( ) throws IOException { return FSTObjectInput . this . readBoolean ( ) ; } @ Override public byte readByte ( ) throws IOException { return getCodec ( ) . readFByte ( ) ; } @ Override public int readUnsignedByte ( ) throws IOException { return FSTObjectInput . this . readUnsignedByte ( ) ; } @ Override public char readChar ( ) throws IOException { return getCodec ( ) . readFChar ( ) ; } @ Override public short readShort ( ) throws IOException { return getCodec ( ) . readFShort ( ) ; } @ Override public int readUnsignedShort ( ) throws IOException { return FSTObjectInput . this . readUnsignedShort ( ) ; } @ Override public int readInt ( ) throws IOException { return getCodec ( ) . readFInt ( ) ; } @ Override public long readLong ( ) throws IOException { return getCodec ( ) . readFLong ( ) ; } @ Override public float readFloat ( ) throws IOException { return getCodec ( ) . readFFloat ( ) ; } @ Override public double readDouble ( ) throws IOException { return getCodec ( ) . readFDouble ( ) ; } @ Override public void readFully ( byte [ ] buf ) throws IOException { FSTObjectInput . this . readFully ( buf ) ; } @ Override public void readFully ( byte [ ] buf , int off , int len ) throws IOException { FSTObjectInput . this . readFully ( buf , off , len ) ; } @ Override public int skipBytes ( int len ) throws IOException { return FSTObjectInput . this . skipBytes ( len ) ; } @ Override public String readUTF ( ) throws IOException { return getCodec ( ) . readStringUTF ( ) ; } @ Override public String readLine ( ) throws IOException { return FSTObjectInput . this . readLine ( ) ; } @ Override public int read ( byte [ ] b ) throws IOException { return FSTObjectInput . this . read ( b ) ; } @ Override public long skip ( long n ) throws IOException { return FSTObjectInput . this . skip ( n ) ; } @ Override public void mark ( int readlimit ) { throw new RuntimeException ( \"not implemented\" ) ; } @ Override public void reset ( ) throws IOException { FSTObjectInput . this . reset ( ) ; } @ Override public boolean markSupported ( ) { return false ; } } ; if ( fakeWrapper == null ) { fakeWrapper = new MyObjectStream ( ) ; } fakeWrapper . push ( wrapped ) ; return fakeWrapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "modify content of this StructString . The length of the new String must not exceed the length of internal char array [CODESPLIT] public void setString ( String s ) { if ( s == null ) { setLen ( 0 ) ; return ; } if ( s . length ( ) > charsLen ( ) ) { throw new RuntimeException ( \"String length exceeds buffer size. String len \" + s . length ( ) + \" charsLen:\" + charsLen ( ) ) ; } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { chars ( i , s . charAt ( i ) ) ; } len = s . length ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "does not write class tag and length [CODESPLIT] @ Override public void writePrimitiveArray ( Object array , int start , int length ) throws IOException { out . writeArray ( array , start , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resets stream ( positions are lost ) [CODESPLIT] @ Override public void flush ( ) throws IOException { if ( outputStream != null ) { outputStream . write ( out . getBytez ( ) , 0 , out . getWritten ( ) ) ; offset = out . getWritten ( ) ; out . resetPosition ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set this struct pointer to base array at given offset ( = bufoff + index ) [CODESPLIT] public void baseOn ( byte base [ ] , long offset , FSTStructFactory fac ) { ___bytes = new HeapBytez ( base ) ; ___offset = offset ; ___fac = fac ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set this struct pointer to base array at given index [CODESPLIT] public void baseOn ( byte base [ ] , int index ) { ___bytes = new HeapBytez ( base ) ; ___offset = index ; if ( ___fac == null ) ___fac = FSTStructFactory . getInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "move offsets and memorybase to given pointer and return the pointer . Eases dereferencing of nested structs without object creation . If the given pointer is null a new one will be created ( alloc ) <pre > MyStruct st = FSTStructFactory . getInstance () . createEmptyStructPointer ( FSTStruct . class ) ; otherStruct . getEmbeddedMyStruct () . to ( st ) ; < / pre > [CODESPLIT] public < T extends FSTStruct > T detachTo ( T pointer ) { if ( pointer == null ) { return detach ( ) ; } if ( isOffHeap ( ) ) { pointer . ___fac = ___fac ; pointer . ___bytes = ___bytes ; pointer . ___elementSize = ___elementSize ; pointer . ___offset = ___offset ; return pointer ; } return ( T ) this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a complete copy of this object allocating a new Bytez capable of holding the data . [CODESPLIT] public FSTStruct createCopy ( ) { if ( ! isOffHeap ( ) ) { throw new RuntimeException ( \"must be offheap to call this\" ) ; } byte b [ ] = new byte [ getByteSize ( ) ] ; HeapBytez res = new HeapBytez ( b ) ; getBytes ( res , 0 ) ; return ___fac . createStructWrapper ( res , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "works only if change tracking is enabled [CODESPLIT] public FSTStructChange finishChangeTracking ( ) { tracker . snapshotChanges ( ( int ) getOffset ( ) , getBase ( ) ) ; FSTStructChange res = tracker ; tracker = null ; return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return a temporary per thread instance of ByteBuffer pointing to this structs data . The length of the buffer is same as the length of this struct . [CODESPLIT] public ByteBuffer asByteBufferTemporary ( ) { if ( getBase ( ) instanceof MallocBytez ) { MallocBytez base = ( MallocBytez ) getBase ( ) ; ByteBuffer bb = tmpBuf . get ( ) ; try { address . setLong ( bb , base . getBaseAdress ( ) + getOffset ( ) ) ; capacity . setInt ( bb , getByteSize ( ) ) ; } catch ( IllegalAccessException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } bb . limit ( ( int ) ( getOffset ( ) + getByteSize ( ) ) ) ; bb . position ( ( int ) getOffset ( ) ) ; return tmpBuf . get ( ) ; } else { // assume HeapBytez. Allocates return ByteBuffer . wrap ( getBase ( ) . asByteArray ( ) , ( int ) getOffset ( ) , getByteSize ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new struct array of same type as template [CODESPLIT] public < X extends FSTStruct > StructArray < X > newArray ( int size , X templ ) { return newArray ( size , templ , alloc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new struct array of same type as template [CODESPLIT] public < X extends FSTStruct > StructArray < X > newArray ( int size , X templ , BytezAllocator alloc ) { StructArray < X > aTemplate = new StructArray < X > ( size , templ ) ; int siz = getFactory ( ) . calcStructSize ( aTemplate ) ; try { if ( siz < chunkSize ) return newStruct ( aTemplate ) ; else { return getFactory ( ) . toStruct ( aTemplate , alloc ) ; } } catch ( Throwable e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "collects all changes and rebases . [CODESPLIT] public void snapshotChanges ( int originBase , Bytez origin ) { int sumLen = 0 ; for ( int i = 0 ; i < curIndex ; i ++ ) { sumLen += changeLength [ i ] ; } snapshot = new byte [ sumLen ] ; int targetIdx = 0 ; for ( int i = 0 ; i < curIndex ; i ++ ) { int changeOffset = changeOffsets [ i ] ; int len = changeLength [ i ] ; for ( int ii = 0 ; ii < len ; ii ++ ) { snapshot [ targetIdx ++ ] = origin . get ( changeOffset + ii ) ; } } rebase ( originBase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add an object to the register return handle if already present . Called during write only [CODESPLIT] public int registerObjectForWrite ( Object o , int streamPosition , FSTClazzInfo clzInfo , int reUseType [ ] ) { if ( disabled ) { return Integer . MIN_VALUE ; } //        System.out.println(\"REGISTER AT WRITE:\"+streamPosition+\" \"+o.getClass().getSimpleName()); //        final Class clazz = o.getClass(); if ( clzInfo == null ) { // array oder enum oder primitive // unused ? //            clzInfo = reg.getCLInfo(clazz); } else if ( clzInfo . isFlat ( ) ) { return Integer . MIN_VALUE ; } int handle = objects . putOrGet ( o , streamPosition ) ; if ( handle >= 0 ) { //            if ( idToObject.get(handle) == null ) { // (*) (can get improved) //                idToObject.add(handle, o); //            } reUseType [ 0 ] = 0 ; return handle ; } return Integer . MIN_VALUE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Warning : Concurrent Modification ( e . g . add remove elements during iteration ) is NOT SUPPORTED and NOT CHECKED . Collect keys to change inside an iteration and perform changes on the map after iteration is finished . [CODESPLIT] public Iterator < V > values ( ) { final Iterator < ByteSource > iter = binaryValues ( ) ; return new Iterator ( ) { @ Override public boolean hasNext ( ) { return iter . hasNext ( ) ; } @ Override public V next ( ) { BytezByteSource next = ( BytezByteSource ) iter . next ( ) ; return decodeValue ( next ) ; } @ Override public void remove ( ) { throw new RuntimeException ( \"unimplemented\" ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "throws FSTBufferTooSmallExcpetion in case object does not fit into given range Zero Copy method [CODESPLIT] @ Override public int toByteArray ( Object o , byte arr [ ] , int startIndex , int availableSize ) { out . resetForReUse ( ) ; writeTarget . setBase ( arr , startIndex , availableSize ) ; try { out . writeObject ( o ) ; } catch ( IOException e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } int written = out . getWritten ( ) ; return written ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "throws FSTBufferTooSmallExcpetion in case object does not fit into given range [CODESPLIT] @ Override public Object toObject ( byte arr [ ] , int startIndex , int availableSize ) { try { in . resetForReuse ( null ) ; readTarget . setBase ( arr , startIndex , availableSize ) ; Object o = in . readObject ( ) ; return o ; } catch ( Exception e ) { FSTUtil . < RuntimeException > rethrow ( e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "map given Object to a target type . ( needs support in coerceWriting also ) Note one could add a pluggable Serializer / Coercer pattern here if required . Skipped for now for simplicity . [CODESPLIT] public Object coerceReading ( Class type , Object readObject ) { if ( type == null ) return readObject ; // make hashmaps from arrays. warning: for optimal performance, use direct arrays[] only in your serialized classes if ( Map . class . isAssignableFrom ( type ) && readObject . getClass ( ) . isArray ( ) ) { try { Map c = ( Map ) type . newInstance ( ) ; int len = Array . getLength ( readObject ) ; for ( int i = 0 ; i < len ; i += 2 ) { c . put ( Array . get ( readObject , i ) , Array . get ( readObject , i + 1 ) ) ; } return c ; } catch ( Exception e ) { logger . log ( FSTLogger . Level . INFO , \"Exception thrown by newInstance\" , e ) ; } } else // make collections from arrays. warning: for optimal performance, use direct arrays[] only in your serialized classes if ( Collection . class . isAssignableFrom ( type ) && readObject . getClass ( ) . isArray ( ) ) { try { if ( type . isInterface ( ) ) { if ( List . class . isAssignableFrom ( type ) ) { type = ArrayList . class ; } else if ( Map . class . isAssignableFrom ( type ) ) { type = HashMap . class ; } } Collection c = ( Collection ) type . newInstance ( ) ; int len = Array . getLength ( readObject ) ; for ( int i = 0 ; i < len ; i ++ ) { c . add ( Array . get ( readObject , i ) ) ; } return c ; } catch ( Exception e ) { logger . log ( FSTLogger . Level . ERROR , \"Exception thrown by newInstance\" , e ) ; } } else if ( Date . class . isAssignableFrom ( type ) && readObject instanceof String ) { try { return dateTimeInstance . parse ( ( String ) readObject ) ; } catch ( ParseException pe ) { logger . log ( FSTLogger . Level . ERROR , \"Failed to parse date\" , pe ) ; } } else if ( ( type == char . class || Character . class . isAssignableFrom ( type ) ) && readObject instanceof String ) { return ( ( String ) readObject ) . charAt ( 0 ) ; } return readObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add bytes to the queue . Again by using ( reusable ) Wrapper classes any kind of memory ( offheap byte arrays nio bytebuffer memory mapped ) can be added . [CODESPLIT] public void add ( ByteSource source , long sourceoff , long sourcelen ) { if ( sourcelen >= remaining ( ) ) { grow ( sourcelen + 1 ) ; //issue85 add ( source , sourceoff , sourcelen ) ; return ; } for ( int i = 0 ; i < sourcelen ; i ++ ) { storage . put ( addIndex ++ , source . get ( i + sourceoff ) ) ; if ( addIndex >= storage . length ( ) ) addIndex -= storage . length ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read up to destlen bytes ( if available ) . Note you can use HeapBytez ( implements ByteSink ) in order to read to a regular byte array . HeapBytez wrapper can be reused to avoid unnecessary allocation . Also possible is ByteBufferBasicBytes to read into a ByteBuffer and MallocBytes or MMFBytes to read into Unsafe alloc ed off heap memory or persistent mem mapped memory regions . [CODESPLIT] public long poll ( ByteSink destination , long destoff , long destlen ) { long count = 0 ; try { while ( pollIndex != addIndex && count < destlen ) { destination . put ( destoff + count ++ , storage . get ( pollIndex ++ ) ) ; if ( pollIndex >= storage . length ( ) ) { pollIndex = 0 ; } } } catch ( Exception e ) { logger . log ( FSTLogger . Level . ERROR , \"Failed to poll\" , e ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convenience method to read len byte array . Throws an excpetion if not enough data is present [CODESPLIT] public byte [ ] readByteArray ( int len ) { if ( available ( ) < len ) { throw new RuntimeException ( \"not enough data available, check available() > len before calling\" ) ; } byte b [ ] = new byte [ len ] ; int count = 0 ; while ( pollIndex != addIndex && count < len ) { b [ count ++ ] = storage . get ( pollIndex ++ ) ; if ( pollIndex >= storage . length ( ) ) { pollIndex = 0 ; } } return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read an int . throws an exception if not enough data is present [CODESPLIT] public int readInt ( ) { if ( available ( ) < 4 ) { throw new RuntimeException ( \"not enough data available, check available() > 4 before calling\" ) ; } int ch1 = poll ( ) ; int ch2 = poll ( ) ; int ch3 = poll ( ) ; int ch4 = poll ( ) ; return ( ch4 << 24 ) + ( ch3 << 16 ) + ( ch2 << 8 ) + ( ch1 << 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unread len bytes [CODESPLIT] public void back ( int len ) { if ( pollIndex >= len ) pollIndex -= len ; else pollIndex = pollIndex + capacity ( ) - len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for read = > always increase handle ( wg . replaceObject ) [CODESPLIT] public void registerClass ( Class c , FSTConfiguration conf ) { if ( getIdFromClazz ( c ) != Integer . MIN_VALUE ) { return ; } registerClassNoLookup ( c , null , conf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set thread pool enabled . This thread pool is not for the service threads it is for the user service method . If your service method takes a long time or will be blocked please set this property to be true . [CODESPLIT] public void setThreadPoolEnabled ( boolean value ) { if ( value && ( threadPool == null ) ) { threadPool = Executors . newCachedThreadPool ( ) ; } threadPoolEnabled = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set embedded cassandra up and spawn it in a new thread . [CODESPLIT] public static void startEmbeddedCassandra ( File file , String tmpDir , long timeout ) throws IOException , ConfigurationException { if ( cassandraDaemon != null ) { /* nothing to do Cassandra is already started */ return ; } checkConfigNameForRestart ( file . getAbsolutePath ( ) ) ; log . debug ( \"Starting cassandra...\" ) ; log . debug ( \"Initialization needed\" ) ; System . setProperty ( \"cassandra.config\" , \"file:\" + file . getAbsolutePath ( ) ) ; System . setProperty ( \"cassandra-foreground\" , \"true\" ) ; System . setProperty ( \"cassandra.native.epoll.enabled\" , \"false\" ) ; // JNA doesnt cope with relocated netty System . setProperty ( \"cassandra.unsafesystem\" , \"true\" ) ; // disable fsync for a massive speedup on old platters // If there is no log4j config set already, set the default config if ( System . getProperty ( \"log4j.configuration\" ) == null ) { copy ( DEFAULT_LOG4J_CONFIG_FILE , tmpDir ) ; System . setProperty ( \"log4j.configuration\" , \"file:\" + tmpDir + DEFAULT_LOG4J_CONFIG_FILE ) ; } DatabaseDescriptor . daemonInitialization ( ) ; cleanupAndLeaveDirs ( ) ; final CountDownLatch startupLatch = new CountDownLatch ( 1 ) ; ExecutorService executor = Executors . newSingleThreadExecutor ( ) ; executor . execute ( ( ) -> { cassandraDaemon = new CassandraDaemon ( ) ; cassandraDaemon . activate ( ) ; startupLatch . countDown ( ) ; } ) ; try { if ( ! startupLatch . await ( timeout , MILLISECONDS ) ) { log . error ( \"Cassandra daemon did not start after \" + timeout + \" ms. Consider increasing the timeout\" ) ; throw new AssertionError ( \"Cassandra daemon did not start within timeout\" ) ; } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ( ) -> { if ( session != null ) session . close ( ) ; if ( cluster != null ) cluster . close ( ) ; } ) ) ; } catch ( InterruptedException e ) { log . error ( \"Interrupted waiting for Cassandra daemon to start:\" , e ) ; throw new AssertionError ( e ) ; } finally { executor . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "truncate data in keyspace except specified tables [CODESPLIT] public static void cleanDataEmbeddedCassandra ( String keyspace , String ... excludedTables ) { if ( session != null ) { cleanDataWithNativeDriver ( keyspace , excludedTables ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies a resource from within the jar to a directory . [CODESPLIT] private static Path copy ( String resource , String directory ) throws IOException { mkdir ( directory ) ; String fileName = resource . substring ( resource . lastIndexOf ( \"/\" ) + 1 ) ; InputStream from = EmbeddedCassandraServerHelper . class . getResourceAsStream ( resource ) ; Path copyName = Paths . get ( directory , fileName ) ; Files . copy ( from , copyName ) ; return copyName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print all of the thread s information and stack traces . [CODESPLIT] public static void printThreadInfo ( PrintWriter stream , String title ) { final int STACK_DEPTH = 20 ; boolean contention = threadBean . isThreadContentionMonitoringEnabled ( ) ; long [ ] threadIds = threadBean . getAllThreadIds ( ) ; stream . println ( \"Process Thread Dump: \" + title ) ; stream . println ( threadIds . length + \" active threads\" ) ; for ( long tid : threadIds ) { ThreadInfo info = threadBean . getThreadInfo ( tid , STACK_DEPTH ) ; if ( info == null ) { stream . println ( \"  Inactive\" ) ; continue ; } stream . println ( \"Thread \" + getTaskName ( info . getThreadId ( ) , info . getThreadName ( ) ) + \":\" ) ; Thread . State state = info . getThreadState ( ) ; stream . println ( \"  State: \" + state ) ; stream . println ( \"  Blocked count: \" + info . getBlockedCount ( ) ) ; stream . println ( \"  Waited count: \" + info . getWaitedCount ( ) ) ; if ( contention ) { stream . println ( \"  Blocked time: \" + info . getBlockedTime ( ) ) ; stream . println ( \"  Waited time: \" + info . getWaitedTime ( ) ) ; } if ( state == Thread . State . WAITING ) { stream . println ( \"  Waiting on \" + info . getLockName ( ) ) ; } else if ( state == Thread . State . BLOCKED ) { stream . println ( \"  Blocked on \" + info . getLockName ( ) ) ; stream . println ( \"  Blocked by \" + getTaskName ( info . getLockOwnerId ( ) , info . getLockOwnerName ( ) ) ) ; } stream . println ( \"  Stack:\" ) ; for ( StackTraceElement frame : info . getStackTrace ( ) ) { stream . println ( \"    \" + frame . toString ( ) ) ; } } stream . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the correctly - typed { @link Class } of the given object . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > Class < T > getClass ( T o ) { return ( Class < T > ) o . getClass ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a remote port is taken [CODESPLIT] public static boolean remotePortTaken ( String node , int port , int timeout ) { Socket s = null ; try { s = new Socket ( ) ; s . setReuseAddress ( true ) ; SocketAddress sa = new InetSocketAddress ( node , port ) ; s . connect ( sa , timeout * 1000 ) ; } catch ( IOException e ) { if ( e . getMessage ( ) . equals ( \"Connection refused\" ) ) { return false ; } if ( e instanceof SocketTimeoutException || e instanceof UnknownHostException ) { throw e ; } } finally { if ( s != null ) { if ( s . isConnected ( ) ) { return true ; } else { } try { s . close ( ) ; } catch ( IOException e ) { } } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an empty subscriber state with - 1 as total updates master as false and server state as empty [CODESPLIT] public static SubscriberState empty ( ) { return SubscriberState . builder ( ) . serverState ( \"empty\" ) . streamId ( - 1 ) . parameterUpdaterStatus ( Collections . emptyMap ( ) ) . totalUpdates ( - 1 ) . isMaster ( false ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gemm performs a matrix - matrix operation c : = alpha * op ( a ) * op ( b ) + beta * c where c is an m - by - n matrix op ( a ) is an m - by - k matrix op ( b ) is a k - by - n matrix . [CODESPLIT] @ Override public void gemm ( char Order , char TransA , char TransB , double alpha , INDArray A , INDArray B , double beta , INDArray C ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( true , A , B , C ) ; GemmParams params = new GemmParams ( A , B , C ) ; int charOder = Order ; if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , params . getA ( ) , params . getB ( ) , params . getC ( ) ) ; dgemm ( Order , params . getTransA ( ) , params . getTransB ( ) , params . getM ( ) , params . getN ( ) , params . getK ( ) , 1.0 , params . getA ( ) , params . getLda ( ) , params . getB ( ) , params . getLdb ( ) , 0 , C , params . getLdc ( ) ) ; } else if ( A . data ( ) . dataType ( ) == DataBuffer . Type . FLOAT ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , params . getA ( ) , params . getB ( ) , params . getC ( ) ) ; sgemm ( Order , params . getTransA ( ) , params . getTransB ( ) , params . getM ( ) , params . getN ( ) , params . getK ( ) , 1.0f , params . getA ( ) , params . getLda ( ) , params . getB ( ) , params . getLdb ( ) , 0 , C , params . getLdc ( ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . HALF , params . getA ( ) , params . getB ( ) , params . getC ( ) ) ; hgemm ( Order , params . getTransA ( ) , params . getTransB ( ) , params . getM ( ) , params . getN ( ) , params . getK ( ) , 1.0f , params . getA ( ) , params . getLda ( ) , params . getB ( ) , params . getLdb ( ) , 0 , C , params . getLdc ( ) ) ; } OpExecutionerUtil . checkForAny ( C ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "her2k performs a rank - 2k update of an n - by - n Hermitian matrix c that is one of the following operations : c : = alpha * a * conjg ( b ) + conjg ( alpha ) * b * conjg ( a ) + beta * c for trans = N or n c : = alpha * conjg ( b ) * a + conjg ( alpha ) * conjg ( a ) * b + beta * c for trans = C or c where c is an n - by - n Hermitian matrix ; a and b are n - by - k matrices if trans = N or n a and b are k - by - n matrices if trans = C or c . [CODESPLIT] @ Override public void symm ( char Order , char Side , char Uplo , double alpha , INDArray A , INDArray B , double beta , INDArray C ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , A , B , C ) ; // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , A , B , C ) ; dsymm ( Order , Side , Uplo , ( int ) C . rows ( ) , ( int ) C . columns ( ) , alpha , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , beta , C , ( int ) C . size ( 0 ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , A , B , C ) ; ssymm ( Order , Side , Uplo , ( int ) C . rows ( ) , ( int ) C . columns ( ) , ( float ) alpha , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , ( float ) beta , C , ( int ) C . size ( 0 ) ) ; } OpExecutionerUtil . checkForAny ( C ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "syrk performs a rank - n update of an n - by - n symmetric matrix c that is one of the following operations : c : = alpha * a * a + beta * c for trans = N or n c : = alpha * a * a + beta * c for trans = T or t C or c where c is an n - by - n symmetric matrix ; a is an n - by - k matrix if trans = N or n a is a k - by - n matrix if trans = T or t C or c . [CODESPLIT] @ Override public void syrk ( char Order , char Uplo , char Trans , double alpha , INDArray A , double beta , INDArray C ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , A , C ) ; // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , A , C ) ; dsyrk ( Order , Uplo , Trans , ( int ) C . rows ( ) , 1 , alpha , A , ( int ) A . size ( 0 ) , beta , C , ( int ) C . size ( 0 ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , A , C ) ; ssyrk ( Order , Uplo , Trans , ( int ) C . rows ( ) , 1 , ( float ) alpha , A , ( int ) A . size ( 0 ) , ( float ) beta , C , ( int ) C . size ( 0 ) ) ; } OpExecutionerUtil . checkForAny ( C ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gemm performs a matrix - matrix operation c : = alpha * op ( a ) * op ( b ) + beta * c where c is an m - by - n matrix op ( a ) is an m - by - k matrix op ( b ) is a k - by - n matrix . [CODESPLIT] @ Override public void gemm ( char Order , char TransA , char TransB , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray B , IComplexNumber beta , IComplexNDArray C ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( true , A , B , C ) ; GemmParams params = new GemmParams ( A , B , C ) ; if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { zgemm ( Order , TransA , TransB , params . getM ( ) , params . getN ( ) , params . getK ( ) , alpha . asDouble ( ) , A . ordering ( ) == NDArrayFactory . C ? B : A , params . getLda ( ) , B . ordering ( ) == NDArrayFactory . C ? A : B , params . getLdb ( ) , beta . asDouble ( ) , C , params . getLdc ( ) ) ; } else cgemm ( Order , TransA , TransB , params . getM ( ) , params . getN ( ) , params . getK ( ) , alpha . asFloat ( ) , A . ordering ( ) == NDArrayFactory . C ? B : A , params . getLda ( ) , B . ordering ( ) == NDArrayFactory . C ? A : B , params . getLdb ( ) , beta . asFloat ( ) , C , params . getLdc ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hemm performs one of the following matrix - matrix operations : c : = alpha * a * b + beta * c for side = L or l c : = alpha * b * a + beta * c for side = R or r where a is a Hermitian matrix b and c are m - by - n matrices . [CODESPLIT] @ Override public void hemm ( char Order , char Side , char Uplo , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray B , IComplexNumber beta , IComplexNDArray C ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zhemm ( Order , Side , Uplo , ( int ) B . rows ( ) , ( int ) B . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , beta . asDouble ( ) , C , ( int ) C . size ( 0 ) ) ; else chemm ( Order , Side , Uplo , ( int ) B . rows ( ) , ( int ) B . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , beta . asFloat ( ) , C , ( int ) C . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "herk performs a rank - n update of a Hermitian matrix that is one of the following operations : c : = alpha * a * conjug ( a ) + beta * c for trans = N or n c : = alpha * conjug ( a ) * a + beta * c for trans = C or c where c is an n - by - n Hermitian matrix ; a is an n - by - k matrix if trans = N or n a is a k - by - n matrix if trans = C or c . [CODESPLIT] @ Override public void herk ( char Order , char Uplo , char Trans , IComplexNumber alpha , IComplexNDArray A , IComplexNumber beta , IComplexNDArray C ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zherk ( Order , Uplo , Trans , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , beta . asDouble ( ) , C , ( int ) C . size ( 0 ) ) ; else cherk ( Order , Uplo , Trans , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , beta . asFloat ( ) , C , ( int ) C . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "her2k performs a rank - 2k update of an n - by - n Hermitian matrix c that is one of the following operations : c : = alpha * a * conjg ( b ) + conjg ( alpha ) * b * conjg ( a ) + beta * c for trans = N or n c : = alpha * conjg ( b ) * a + conjg ( alpha ) * conjg ( a ) * b + beta * c for trans = C or c where c is an n - by - n Hermitian matrix ; a and b are n - by - k matrices if trans = N or n a and b are k - by - n matrices if trans = C or c . [CODESPLIT] @ Override public void symm ( char Order , char Side , char Uplo , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray B , IComplexNumber beta , IComplexNDArray C ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zsymm ( Order , Side , Uplo , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , beta . asDouble ( ) , C , ( int ) C . size ( 0 ) ) ; else csymm ( Order , Side , Uplo , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , beta . asFloat ( ) , C , ( int ) C . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "syrk performs a rank - n update of an n - by - n symmetric matrix c that is one of the following operations : c : = alpha * a * a + beta * c for trans = N or n c : = alpha * a * a + beta * c for trans = T or t C or c where c is an n - by - n symmetric matrix ; a is an n - by - k matrix if trans = N or n a is a k - by - n matrix if trans = T or t C or c . [CODESPLIT] @ Override public void syrk ( char Order , char Uplo , char Trans , IComplexNumber alpha , IComplexNDArray A , IComplexNumber beta , IComplexNDArray C ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zsyrk ( Order , Uplo , Trans , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , beta . asDouble ( ) , C , ( int ) C . size ( 0 ) ) ; else csyrk ( Order , Uplo , Trans , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , beta . asFloat ( ) , C , ( int ) C . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "yr2k performs a rank - 2k update of an n - by - n symmetric matrix c that is one of the following operations : c : = alpha * a * b + alpha * b * a + beta * c for trans = N or n c : = alpha * a * b + alpha * b * a + beta * c for trans = T or t where c is an n - by - n symmetric matrix ; a and b are n - by - k matrices if trans = N or n a and b are k - by - n matrices if trans = T or t . [CODESPLIT] @ Override public void syr2k ( char Order , char Uplo , char Trans , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray B , IComplexNumber beta , IComplexNDArray C ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zsyr2k ( Order , Uplo , Trans , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , beta . asDouble ( ) , C , ( int ) C . size ( 0 ) ) ; else csyr2k ( Order , Uplo , Trans , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , beta . asFloat ( ) , C , ( int ) C . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "syr2k performs a rank - 2k update of an n - by - n symmetric matrix c that is one of the following operations : c : = alpha * a * b + alpha * b * a + beta * c for trans = N or n c : = alpha * a * b + alpha * b * a + beta * c for trans = T or t where c is an n - by - n symmetric matrix ; a and b are n - by - k matrices if trans = N or n a and b are k - by - n matrices if trans = T or t . [CODESPLIT] @ Override public void trmm ( char Order , char Side , char Uplo , char TransA , char Diag , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray B , IComplexNDArray C ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) ztrmm ( Order , Side , Uplo , TransA , Diag , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , C , ( int ) C . size ( 0 ) ) ; else ctrmm ( Order , Side , Uplo , TransA , Diag , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) , C , ( int ) C . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "?trsm solves one of the following matrix equations : op ( a ) * x = alpha * b or x * op ( a ) = alpha * b where x and b are m - by - n general matrices and a is triangular ; op ( a ) must be an m - by - m matrix if side = L or l op ( a ) must be an n - by - n matrix if side = R or r . For the definition of op ( a ) see Matrix Arguments . The routine overwrites x on b . [CODESPLIT] @ Override public void trsm ( char Order , char Side , char Uplo , char TransA , char Diag , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray B ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) ztrsm ( Order , Side , Uplo , TransA , Diag , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) ) ; else ctrsm ( Order , Side , Uplo , TransA , Diag , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , B , ( int ) B . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the onnx op descriptors by name [CODESPLIT] public static Map < String , OpDescriptor > onnxOpDescriptors ( ) throws Exception { try ( InputStream is = new ClassPathResource ( \"onnxops.json\" ) . getInputStream ( ) ) { ObjectMapper objectMapper = new ObjectMapper ( ) ; OnnxDescriptor opDescriptor = objectMapper . readValue ( is , OnnxDescriptor . class ) ; Map < String , OpDescriptor > descriptorMap = new HashMap <> ( ) ; for ( OpDescriptor descriptor : opDescriptor . getDescriptors ( ) ) { descriptorMap . put ( descriptor . getName ( ) , descriptor ) ; } return descriptorMap ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the allocation mode from the context [CODESPLIT] public static DataBuffer . AllocationMode getAllocationModeFromContext ( String allocMode ) { switch ( allocMode ) { case \"heap\" : return DataBuffer . AllocationMode . HEAP ; case \"javacpp\" : return DataBuffer . AllocationMode . JAVACPP ; case \"direct\" : return DataBuffer . AllocationMode . DIRECT ; default : return DataBuffer . AllocationMode . JAVACPP ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the allocation mode for the nd4j context The value must be one of : heap java cpp or direct or an [CODESPLIT] public static void setAllocationModeForContext ( String allocationModeForContext ) { if ( ! allocationModeForContext . equals ( \"heap\" ) && ! allocationModeForContext . equals ( \"javacpp\" ) && ! allocationModeForContext . equals ( \"direct\" ) ) throw new IllegalArgumentException ( \"Allocation mode must be one of: heap,javacpp, or direct\" ) ; Nd4jContext . getInstance ( ) . getConf ( ) . put ( \"alloc\" , allocationModeForContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method releases previously allocated memory chunk [CODESPLIT] @ Override public void release ( @ NonNull Pointer pointer , MemoryKind kind ) { Pointer . free ( pointer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the output shape for this op [CODESPLIT] public List < long [ ] > calculateOutputShape ( ) { List < long [ ] > ret = new ArrayList <> ( ) ; if ( larg ( ) . getShape ( ) != null && rarg ( ) . getShape ( ) != null ) ret . add ( Shape . broadcastOutputShape ( larg ( ) . getShape ( ) , rarg ( ) . getShape ( ) ) ) ; else if ( larg ( ) . getShape ( ) != null ) ret . add ( larg ( ) . getShape ( ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public double cumulativeProbability ( double x ) { if ( x <= lower ) { return 0 ; } if ( x >= upper ) { return 1 ; } return ( x - lower ) / ( upper - lower ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes given graph and returns results [CODESPLIT] @ Override public INDArray [ ] executeGraph ( SameDiff sd , ExecutorConfiguration configuration ) { Map < Integer , Node > intermediate = new HashMap <> ( ) ; ByteBuffer buffer = convertToFlatBuffers ( sd , configuration , intermediate ) ; BytePointer bPtr = new BytePointer ( buffer ) ; log . info ( \"Buffer length: {}\" , buffer . limit ( ) ) ; Pointer res = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . executeFlatGraphFloat ( null , bPtr ) ; if ( res == null ) throw new ND4JIllegalStateException ( \"Graph execution failed\" ) ; // FIXME: this is BAD PagedPointer pagedPointer = new PagedPointer ( res , 1024 * 1024L ) ; FlatResult fr = FlatResult . getRootAsFlatResult ( pagedPointer . asBytePointer ( ) . asByteBuffer ( ) ) ; log . info ( \"VarMap: {}\" , sd . variableMap ( ) ) ; INDArray [ ] results = new INDArray [ fr . variablesLength ( ) ] ; for ( int e = 0 ; e < fr . variablesLength ( ) ; e ++ ) { FlatVariable var = fr . variables ( e ) ; log . info ( \"Var received: id: [{}:{}/<{}>];\" , var . id ( ) . first ( ) , var . id ( ) . second ( ) , var . name ( ) ) ; FlatArray ndarray = var . ndarray ( ) ; INDArray val = Nd4j . createFromFlatArray ( ndarray ) ; results [ e ] = val ; if ( var . name ( ) != null && sd . variableMap ( ) . containsKey ( var . name ( ) ) ) { //log.info(\"VarName: {}; Exists: {}; NDArrayInfo: {};\", var.opName(), sd.variableMap().containsKey(var.opName()), sd.getVertexToArray().containsKey(var.opName())); //              log.info(\"storing: {}; array: {}\", var.name(), val); sd . associateArrayWithVariable ( val , sd . variableMap ( ) . get ( var . name ( ) ) ) ; } else { //log.info(\"Original id: {}; out: {}; out2: {}\", original, sd.getVertexIdxToInfo().get(original), graph.getVariableForVertex(original)); if ( sd . variableMap ( ) . get ( var . name ( ) ) != null ) { sd . associateArrayWithVariable ( val , sd . getVariable ( var . name ( ) ) ) ; } else { //                log.info(\"BAD\"); //sd.var(\"\",val); throw new ND4JIllegalStateException ( \"Unknown variable received as result: [\" + var . name ( ) + \"]\" ) ; } } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "And [CODESPLIT] public static boolean and ( IComplexNDArray n , Condition cond ) { boolean ret = true ; IComplexNDArray linear = n . linearView ( ) ; for ( int i = 0 ; i < linear . length ( ) ; i ++ ) { ret = ret && cond . apply ( linear . getComplex ( i ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Or over the whole ndarray given some condition [CODESPLIT] public static boolean or ( IComplexNDArray n , Condition cond ) { boolean ret = false ; IComplexNDArray linear = n . linearView ( ) ; for ( int i = 0 ; i < linear . length ( ) ; i ++ ) { ret = ret || cond . apply ( linear . getComplex ( i ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "And over the whole ndarray given some condition [CODESPLIT] public static boolean and ( final INDArray n , final Condition cond ) { if ( cond instanceof BaseCondition ) { long val = ( long ) Nd4j . getExecutioner ( ) . exec ( new MatchCondition ( n , cond ) , Integer . MAX_VALUE ) . getDouble ( 0 ) ; if ( val == n . lengthLong ( ) ) return true ; else return false ; } else { boolean ret = true ; final AtomicBoolean a = new AtomicBoolean ( ret ) ; Shape . iterate ( n , new CoordinateFunction ( ) { @ Override public void process ( long [ ] ... coord ) { if ( a . get ( ) ) a . compareAndSet ( true , a . get ( ) && cond . apply ( n . getDouble ( coord [ 0 ] ) ) ) ; } } ) ; return a . get ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "And over the whole ndarray given some condition with respect to dimensions [CODESPLIT] public static boolean [ ] and ( final INDArray n , final Condition condition , int ... dimension ) { if ( ! ( condition instanceof BaseCondition ) ) throw new UnsupportedOperationException ( \"Only static Conditions are supported\" ) ; MatchCondition op = new MatchCondition ( n , condition ) ; INDArray arr = Nd4j . getExecutioner ( ) . exec ( op , dimension ) ; boolean [ ] result = new boolean [ ( int ) arr . length ( ) ] ; long tadLength = Shape . getTADLength ( n . shape ( ) , dimension ) ; for ( int i = 0 ; i < arr . length ( ) ; i ++ ) { if ( arr . getDouble ( i ) == tadLength ) result [ i ] = true ; else result [ i ] = false ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Or over the whole ndarray given some condition with respect to dimensions [CODESPLIT] public static boolean [ ] or ( final INDArray n , final Condition condition , int ... dimension ) { if ( ! ( condition instanceof BaseCondition ) ) throw new UnsupportedOperationException ( \"Only static Conditions are supported\" ) ; MatchCondition op = new MatchCondition ( n , condition ) ; INDArray arr = Nd4j . getExecutioner ( ) . exec ( op , dimension ) ; // FIXME: int cast boolean [ ] result = new boolean [ ( int ) arr . length ( ) ] ; for ( int i = 0 ; i < arr . length ( ) ; i ++ ) { if ( arr . getDouble ( i ) > 0 ) result [ i ] = true ; else result [ i ] = false ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on the matching elements op to based on condition to with function function [CODESPLIT] public static void applyWhere ( final INDArray to , final Condition condition , final Function < Number , Number > function ) { // keep original java implementation for dynamic Shape . iterate ( to , new CoordinateFunction ( ) { @ Override public void process ( long [ ] ... coord ) { if ( condition . apply ( to . getDouble ( coord [ 0 ] ) ) ) to . putScalar ( coord [ 0 ] , function . apply ( to . getDouble ( coord [ 0 ] ) ) . doubleValue ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method sets provided number to all elements which match specified condition [CODESPLIT] public static void applyWhere ( final INDArray to , final Condition condition , final Number number ) { if ( condition instanceof BaseCondition ) { // for all static conditions we go native Nd4j . getExecutioner ( ) . exec ( new CompareAndSet ( to , number . doubleValue ( ) , condition ) ) ; } else { final double value = number . doubleValue ( ) ; final Function < Number , Number > dynamic = new Function < Number , Number > ( ) { @ Override public Number apply ( Number number ) { return value ; } } ; Shape . iterate ( to , new CoordinateFunction ( ) { @ Override public void process ( long [ ] ... coord ) { if ( condition . apply ( to . getDouble ( coord [ 0 ] ) ) ) to . putScalar ( coord [ 0 ] , dynamic . apply ( to . getDouble ( coord [ 0 ] ) ) . doubleValue ( ) ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Choose from the inputs based on the given condition . This returns a row vector of all elements fulfilling the condition listed within the array for input [CODESPLIT] public static INDArray chooseFrom ( @ NonNull INDArray [ ] input , @ NonNull Condition condition ) { Choose choose = new Choose ( input , condition ) ; Nd4j . getExecutioner ( ) . exec ( choose ) ; int secondOutput = choose . getOutputArgument ( 1 ) . getInt ( 0 ) ; if ( secondOutput < 1 ) { return null ; } return choose . getOutputArgument ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Choose from the inputs based on the given condition . This returns a row vector of all elements fulfilling the condition listed within the array for input . The double and integer arguments are only relevant for scalar operations ( like when you have a scalar you are trying to compare each element in your input against ) [CODESPLIT] public static INDArray chooseFrom ( @ NonNull INDArray [ ] input , @ NonNull List < Double > tArgs , @ NonNull List < Integer > iArgs , @ NonNull Condition condition ) { Choose choose = new Choose ( input , iArgs , tArgs , condition ) ; Nd4j . getExecutioner ( ) . exec ( choose ) ; int secondOutput = choose . getOutputArgument ( 1 ) . getInt ( 0 ) ; if ( secondOutput < 1 ) { return null ; } INDArray ret = choose . getOutputArgument ( 0 ) . get ( NDArrayIndex . interval ( 0 , secondOutput ) ) ; ret = ret . reshape ( ret . length ( ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on the matching elements op to based on condition to with function function [CODESPLIT] public static void applyWhere ( final INDArray to , final Condition condition , final Function < Number , Number > function , final Function < Number , Number > alternativeFunction ) { Shape . iterate ( to , new CoordinateFunction ( ) { @ Override public void process ( long [ ] ... coord ) { if ( condition . apply ( to . getDouble ( coord [ 0 ] ) ) ) { to . putScalar ( coord [ 0 ] , function . apply ( to . getDouble ( coord [ 0 ] ) ) . doubleValue ( ) ) ; } else { to . putScalar ( coord [ 0 ] , alternativeFunction . apply ( to . getDouble ( coord [ 0 ] ) ) . doubleValue ( ) ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on the matching elements op to based on condition to with function function [CODESPLIT] public static void applyWhere ( IComplexNDArray to , Condition condition , Function < IComplexNumber , IComplexNumber > function ) { IComplexNDArray linear = to . linearView ( ) ; for ( int i = 0 ; i < linear . linearView ( ) . length ( ) ; i ++ ) { if ( condition . apply ( linear . getDouble ( i ) ) ) { linear . putScalar ( i , function . apply ( linear . getComplex ( i ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns first index matching given condition [CODESPLIT] public static INDArray firstIndex ( INDArray array , Condition condition ) { if ( ! ( condition instanceof BaseCondition ) ) throw new UnsupportedOperationException ( \"Only static Conditions are supported\" ) ; FirstIndex idx = new FirstIndex ( array , condition ) ; Nd4j . getExecutioner ( ) . exec ( idx ) ; return Nd4j . scalar ( ( double ) idx . getFinalResult ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method converts this FunctionProperties instance to FlatBuffers representation [CODESPLIT] public int asFlatProperties ( FlatBufferBuilder bufferBuilder ) { int iname = bufferBuilder . createString ( name ) ; int ii = FlatProperties . createIVector ( bufferBuilder , Ints . toArray ( i ) ) ; int il = FlatProperties . createLVector ( bufferBuilder , Longs . toArray ( l ) ) ; int id = FlatProperties . createDVector ( bufferBuilder , Doubles . toArray ( d ) ) ; int arrays [ ] = new int [ a . size ( ) ] ; int cnt = 0 ; for ( val array : a ) { int off = array . toFlatArray ( bufferBuilder ) ; arrays [ cnt ++ ] = off ; } int ia = FlatProperties . createAVector ( bufferBuilder , arrays ) ; return FlatProperties . createFlatProperties ( bufferBuilder , iname , ii , il , id , ia ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method creates new FunctionProperties instance from FlatBuffers representation [CODESPLIT] public static FunctionProperties fromFlatProperties ( FlatProperties properties ) { val props = new FunctionProperties ( ) ; for ( int e = 0 ; e < properties . iLength ( ) ; e ++ ) props . getI ( ) . ( properties . i ( ) ) ; for ( int e = 0 ; e < properties . lLength ( ) ; e ++ ) props . getL ( ) . ( properties . l ( ) ) ; for ( int e = 0 ; e < properties . dLength ( ) ; e ++ ) props . getD ( ) . ( properties . ( e ) ) ; for ( int e = 0 ; e < properties . iLength ( ) ; e ++ ) props . getA ( ) . ( Nd4j . createFromFlatArray ( properties . ( ) ) ) ; return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method converts multiple FunctionProperties to FlatBuffers representation [CODESPLIT] public static int asFlatProperties ( FlatBufferBuilder bufferBuilder , Collection < FunctionProperties > properties ) { int props [ ] = new int [ properties . size ( ) ] ; int cnt = 0 ; for ( val p : properties ) props [ cnt ++ ] = p . asFlatProperties ( bufferBuilder ) ; return FlatNode . createPropertiesVector ( bufferBuilder , props ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method updates state with given Throwable [CODESPLIT] public void set ( Throwable t ) { try { lock . writeLock ( ) . lock ( ) ; this . t = t ; } finally { lock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method updates state only if it wasn t set before [CODESPLIT] public void setIfFirst ( Throwable t ) { try { lock . writeLock ( ) . lock ( ) ; if ( this . t == null ) this . t = t ; } finally { lock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize a value ( val - min ) / ( max - min ) [CODESPLIT] public static double normalize ( double val , double min , double max ) { if ( max < min ) throw new IllegalArgumentException ( \"Max must be greather than min\" ) ; return ( val - min ) / ( max - min ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will merge the coordinates of the given coordinate system . [CODESPLIT] public static List < Double > mergeCoords ( List < Double > x , List < Double > y ) { if ( x . size ( ) != y . size ( ) ) throw new IllegalArgumentException ( \"Sample sizes must be the same for each data applyTransformToDestination.\" ) ; List < Double > ret = new ArrayList < Double > ( ) ; for ( int i = 0 ; i < x . size ( ) ; i ++ ) { ret . add ( x . get ( i ) ) ; ret . add ( y . get ( i ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This returns the coordinate split in a list of coordinates such that the values for ret [ 0 ] are the x values and ret [ 1 ] are the y values [CODESPLIT] public static List < double [ ] > coordSplit ( double [ ] vector ) { if ( vector == null ) return null ; List < double [ ] > ret = new ArrayList < double [ ] > ( ) ; /* x coordinates */ double [ ] xVals = new double [ vector . length / 2 ] ; /* y coordinates */ double [ ] yVals = new double [ vector . length / 2 ] ; /* current points */ int xTracker = 0 ; int yTracker = 0 ; for ( int i = 0 ; i < vector . length ; i ++ ) { //even value, x coordinate if ( i % 2 == 0 ) xVals [ xTracker ++ ] = vector [ i ] ; //y coordinate else yVals [ yTracker ++ ] = vector [ i ] ; } ret . add ( xVals ) ; ret . add ( yVals ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will partition the given whole variable data applyTransformToDestination in to the specified chunk number . [CODESPLIT] public static List < List < Double > > partitionVariable ( List < Double > arr , int chunk ) { int count = 0 ; List < List < Double > > ret = new ArrayList < List < Double > > ( ) ; while ( count < arr . size ( ) ) { List < Double > sublist = arr . subList ( count , count + chunk ) ; count += chunk ; ret . add ( sublist ) ; } //All data sets must be same size for ( List < Double > lists : ret ) { if ( lists . size ( ) < chunk ) ret . remove ( lists ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This returns the coordinate split in a list of coordinates such that the values for ret [ 0 ] are the x values and ret [ 1 ] are the y values [CODESPLIT] public static List < double [ ] > coordSplit ( List < Double > vector ) { if ( vector == null ) return null ; List < double [ ] > ret = new ArrayList < double [ ] > ( ) ; /* x coordinates */ double [ ] xVals = new double [ vector . size ( ) / 2 ] ; /* y coordinates */ double [ ] yVals = new double [ vector . size ( ) / 2 ] ; /* current points */ int xTracker = 0 ; int yTracker = 0 ; for ( int i = 0 ; i < vector . size ( ) ; i ++ ) { //even value, x coordinate if ( i % 2 == 0 ) xVals [ xTracker ++ ] = vector . get ( i ) ; //y coordinate else yVals [ yTracker ++ ] = vector . get ( i ) ; } ret . add ( xVals ) ; ret . add ( yVals ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an onnx type to the proper nd4j type [CODESPLIT] public DataBuffer . Type nd4jTypeFromOnnxType ( OnnxProto3 . TensorProto . DataType dataType ) { switch ( dataType ) { case DOUBLE : return DataBuffer . Type . DOUBLE ; case FLOAT : return DataBuffer . Type . FLOAT ; case FLOAT16 : return DataBuffer . Type . HALF ; case INT32 : case INT64 : return DataBuffer . Type . INT ; default : return DataBuffer . Type . UNKNOWN ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method initiates shutdown sequence for this instance . [CODESPLIT] public void shutdown ( ) { /**\n         * Probably we don't need this method in practice\n         */ if ( initLocker . get ( ) && shutdownLocker . compareAndSet ( false , true ) ) { // do shutdown log . info ( \"Shutting down transport...\" ) ; // we just sending out ShutdownRequestMessage //transport.sendMessage(new ShutdownRequestMessage()); transport . shutdown ( ) ; executor . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns titles line as string appointed by title index ( 0 .. 5 ) . <br > Columns are separated with char | . <br > If title index is < 0 returns ? . <br > If title index is > 5 returns ? . <br > [CODESPLIT] public String getTitleLine ( int mtLv , int title_I ) { // String info = \"\" ; // if ( title_I < 0 ) return \"?\" ; if ( title_I > 5 ) return \"?\" ; // info = \"\" ; info += BTools . getMtLvESS ( mtLv ) ; info += BTools . getMtLvISS ( ) ; info += \"|\" ; // InfoValues i_IV ; // String i_ValuesS = \"\" ; // int i_VSLen = - 1 ; // String i_TitleS = \"\" ; // for ( int i = 0 ; i < ivL . size ( ) ; i ++ ) { // i_IV = ivL . get ( i ) ; // i_ValuesS = i_IV . getValues ( ) ; // i_VSLen = i_ValuesS . length ( ) ; // i_TitleS = ( title_I < i_IV . titleA . length ) ? i_IV . titleA [ title_I ] : \"\" ; // i_TitleS = i_TitleS + BTools . getSpaces ( i_VSLen ) ; // info += i_TitleS . substring ( 0 , i_VSLen - 1 ) ; // info += \"|\" ; } // return info ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns values line as string . <br > Columns are separated with char | . <br > [CODESPLIT] public String getValuesLine ( int mtLv ) { // String info = \"\" ; // info += BTools . getMtLvESS ( mtLv ) ; info += BTools . getMtLvISS ( ) ; info += \"|\" ; // InfoValues i_IV ; // for ( int i = 0 ; i < ivL . size ( ) ; i ++ ) { // i_IV = ivL . get ( i ) ; // info += i_IV . getValues ( ) ; } // return info ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current device architecture [CODESPLIT] public int getCurrentDeviceArchitecture ( ) { int deviceId = Nd4j . getAffinityManager ( ) . getDeviceForCurrentThread ( ) ; if ( ! arch . containsKey ( deviceId ) ) { int major = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . getDeviceMajor ( new CudaPointer ( deviceId ) ) ; int minor = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . getDeviceMinor ( new CudaPointer ( deviceId ) ) ; Integer cc = Integer . parseInt ( new String ( \"\" + major + minor ) ) ; arch . put ( deviceId , cc ) ; return cc ; } return arch . get ( deviceId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a subset of this array based on the specified indexes [CODESPLIT] @ Override public INDArray get ( INDArrayIndex ... indexes ) { sort ( ) ; if ( indexes . length == 1 && indexes [ 0 ] instanceof NDArrayIndexAll || ( indexes . length == 2 && ( isRowVector ( ) && indexes [ 0 ] instanceof PointIndex && indexes [ 0 ] . offset ( ) == 0 && indexes [ 1 ] instanceof NDArrayIndexAll || isColumnVector ( ) && indexes [ 1 ] instanceof PointIndex && indexes [ 0 ] . offset ( ) == 0 && indexes [ 0 ] instanceof NDArrayIndexAll ) ) ) return this ; indexes = NDArrayIndex . resolve ( shapeInfoDataBuffer ( ) , indexes ) ; ShapeOffsetResolution resolution = new ShapeOffsetResolution ( this ) ; resolution . exec ( indexes ) ; if ( indexes . length < 1 ) throw new IllegalStateException ( \"Invalid index found of zero length\" ) ; // FIXME: LONG int [ ] shape = LongUtils . toInts ( resolution . getShapes ( ) ) ; int numSpecifiedIndex = 0 ; for ( int i = 0 ; i < indexes . length ; i ++ ) if ( indexes [ i ] instanceof SpecifiedIndex ) numSpecifiedIndex ++ ; if ( shape != null && numSpecifiedIndex > 0 ) { Generator < List < List < Long >>> gen = SpecifiedIndex . iterateOverSparse ( indexes ) ; INDArray ret = Nd4j . createSparseCOO ( new double [ ] { } , new int [ ] [ ] { } , shape ) ; int count = 0 ; int maxValue = ArrayUtil . prod ( shape ( ) ) ; while ( count < maxValue ) { try { List < List < Long >> next = gen . next ( ) ; List < Integer > coordsCombo = new ArrayList <> ( ) ; List < Integer > cooIdx = new ArrayList <> ( ) ; for ( int i = 0 ; i < next . size ( ) ; i ++ ) { if ( next . get ( i ) . size ( ) != 2 ) throw new IllegalStateException ( \"Illegal entry returned\" ) ; coordsCombo . add ( next . get ( i ) . get ( 0 ) . intValue ( ) ) ; cooIdx . add ( next . get ( i ) . get ( 1 ) . intValue ( ) ) ; } count ++ ; /*\n                    * if the coordinates are in the original array\n                    *   -> add it in the new sparse ndarray\n                    * else\n                    *   -> do nothing\n                    * */ int [ ] idx = Ints . toArray ( coordsCombo ) ; if ( ! isZero ( idx ) ) { double val = getDouble ( idx ) ; ret . putScalar ( filterOutFixedDimensions ( resolution . getFixed ( ) , cooIdx ) , val ) ; } } catch ( NoSuchElementException e ) { break ; } } return ret ; } int numNewAxis = 0 ; for ( int i = 0 ; i < indexes . length ; i ++ ) if ( indexes [ i ] instanceof NewAxis ) numNewAxis ++ ; if ( numNewAxis != 0 ) { } INDArray ret = subArray ( resolution ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adjust the flags array according on the current context : - In case of a vector or a scalar we need to keep flags to 0 - There must always be at least 2 non - flags dimensions - We must keep the flags dimensions of the original array [CODESPLIT] private int [ ] updateFlags ( int [ ] viewFlags , int [ ] newShape ) { // Check if flags is well-formed int count = 0 ; for ( int i = 0 ; i < viewFlags . length ; i ++ ) { if ( viewFlags [ i ] == 0 ) { count ++ ; } } for ( int dim = 0 ; dim < viewFlags . length ; dim ++ ) { if ( viewFlags [ dim ] == 1 ) { if ( newShape [ dim ] == 1 && count < 2 ) { viewFlags [ dim ] = 0 ; } } } // Take the original Fixed into account int [ ] extendedFlags = new int [ underlyingRank ( ) ] ; int notFixedDim = 0 ; for ( int dim = 0 ; dim < underlyingRank ( ) ; dim ++ ) { int [ ] temp = flags ( ) ; if ( flags ( ) [ dim ] == 0 ) { extendedFlags [ dim ] = viewFlags [ notFixedDim ] ; notFixedDim ++ ; } else { extendedFlags [ dim ] = 1 ; } } return extendedFlags ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rearrange matrix columns into blocks [CODESPLIT] public static INDArray col2im ( INDArray col , int sy , int sx , int ph , int pw , int h , int w ) { if ( col . rank ( ) != 6 ) throw new IllegalArgumentException ( \"col2im input array must be rank 6\" ) ; INDArray output = Nd4j . create ( new long [ ] { col . size ( 0 ) , col . size ( 1 ) , h , w } ) ; Col2Im col2Im = Col2Im . builder ( ) . inputArrays ( new INDArray [ ] { col } ) . outputs ( new INDArray [ ] { output } ) . conv2DConfig ( Conv2DConfig . builder ( ) . sy ( sy ) . sx ( sx ) . dw ( 1 ) . dh ( 1 ) . kh ( h ) . kw ( w ) . ph ( ph ) . pw ( pw ) . build ( ) ) . build ( ) ; Nd4j . getExecutioner ( ) . exec ( col2Im ) ; return col2Im . outputArguments ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pooling 2d implementation [CODESPLIT] public static INDArray pooling2D ( INDArray img , int kh , int kw , int sy , int sx , int ph , int pw , int dh , int dw , boolean isSameMode , Pooling2D . Pooling2DType type , Pooling2D . Divisor divisor , double extra , int virtualHeight , int virtualWidth , INDArray out ) { Pooling2D pooling = Pooling2D . builder ( ) . arrayInputs ( new INDArray [ ] { img } ) . arrayOutputs ( new INDArray [ ] { out } ) . config ( Pooling2DConfig . builder ( ) . dh ( dh ) . dw ( dw ) . extra ( extra ) . kh ( kh ) . kw ( kw ) . ph ( ph ) . pw ( pw ) . isSameMode ( isSameMode ) . sx ( sx ) . sy ( sy ) . virtualHeight ( virtualHeight ) . virtualWidth ( virtualWidth ) . type ( type ) . divisor ( divisor ) . build ( ) ) . build ( ) ; Nd4j . getExecutioner ( ) . exec ( pooling ) ; return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implement column formatted images @param img the image to process @param kh the kernel height @param kw the kernel width @param sy the stride along y @param sx the stride along x @param ph the padding width @param pw the padding height @param pval the padding value ( not used ) @param isSameMode whether padding mode is same @return the column formatted image [CODESPLIT] public static INDArray im2col ( INDArray img , int kh , int kw , int sy , int sx , int ph , int pw , int pval , boolean isSameMode ) { INDArray output = null ; if ( isSameMode ) { int oH = ( int ) Math . ceil ( img . size ( 2 ) * 1.f / sy ) ; int oW = ( int ) Math . ceil ( img . size ( 3 ) * 1.f / sx ) ; output = Nd4j . createUninitialized ( new long [ ] { img . size ( 0 ) , img . size ( 1 ) , kh , kw , oH , oW } , ' ' ) ; } else { // FIXME: int cast int oH = ( ( int ) img . size ( 2 ) - ( kh + ( kh - 1 ) * ( 1 - 1 ) ) + 2 * ph ) / sy + 1 ; int oW = ( ( int ) img . size ( 3 ) - ( kw + ( kw - 1 ) * ( 1 - 1 ) ) + 2 * pw ) / sx + 1 ; output = Nd4j . createUninitialized ( new long [ ] { img . size ( 0 ) , img . size ( 1 ) , kh , kw , oH , oW } , ' ' ) ; } Im2col im2col = Im2col . builder ( ) . inputArrays ( new INDArray [ ] { img } ) . outputs ( new INDArray [ ] { output } ) . conv2DConfig ( Conv2DConfig . builder ( ) . kh ( kh ) . pw ( pw ) . ph ( ph ) . sy ( sy ) . sx ( sx ) . kw ( kw ) . kh ( kh ) . dw ( 1 ) . dh ( 1 ) . isSameMode ( isSameMode ) . build ( ) ) . build ( ) ; Nd4j . getExecutioner ( ) . exec ( im2col ) ; return im2col . outputArguments ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ND Convolution [CODESPLIT] public static IComplexNDArray convn ( IComplexNDArray input , IComplexNDArray kernel , Type type , int [ ] axes ) { return Nd4j . getConvolution ( ) . convn ( input , kernel , type , axes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiate a compression descriptor from the given bytebuffer [CODESPLIT] public static CompressionDescriptor fromByteBuffer ( ByteBuffer byteBuffer ) { CompressionDescriptor compressionDescriptor = new CompressionDescriptor ( ) ; //compression opType int compressionTypeOrdinal = byteBuffer . getInt ( ) ; CompressionType compressionType = CompressionType . values ( ) [ compressionTypeOrdinal ] ; compressionDescriptor . setCompressionType ( compressionType ) ; //compression algo int compressionAlgoOrdinal = byteBuffer . getInt ( ) ; CompressionAlgorithm compressionAlgorithm = CompressionAlgorithm . values ( ) [ compressionAlgoOrdinal ] ; compressionDescriptor . setCompressionAlgorithm ( compressionAlgorithm . name ( ) ) ; //from here everything is longs compressionDescriptor . setOriginalLength ( byteBuffer . getLong ( ) ) ; compressionDescriptor . setCompressedLength ( byteBuffer . getLong ( ) ) ; compressionDescriptor . setNumberOfElements ( byteBuffer . getLong ( ) ) ; compressionDescriptor . setOriginalElementSize ( byteBuffer . getLong ( ) ) ; return compressionDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a direct allocated bytebuffer from the compression codec . The size of the bytebuffer is calculated to be : 40 : 8 + 32 two ints representing their enum values for the compression algorithm and opType [CODESPLIT] public ByteBuffer toByteBuffer ( ) { //2 ints  at 4 bytes a piece, this includes the compression algorithm //that we convert to enum int enumSize = 2 * 4 ; //4 longs at 8 bytes a piece int sizesLength = 4 * 8 ; ByteBuffer directAlloc = ByteBuffer . allocateDirect ( enumSize + sizesLength ) . order ( ByteOrder . nativeOrder ( ) ) ; directAlloc . putInt ( compressionType . ordinal ( ) ) ; directAlloc . putInt ( CompressionAlgorithm . valueOf ( compressionAlgorithm ) . ordinal ( ) ) ; directAlloc . putLong ( originalLength ) ; directAlloc . putLong ( compressedLength ) ; directAlloc . putLong ( numberOfElements ) ; directAlloc . putLong ( originalElementSize ) ; directAlloc . rewind ( ) ; return directAlloc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create batch from list of aggregates for cases when list of aggregates is higher then batchLimit [CODESPLIT] public static < U extends Aggregate > List < Batch < U > > getBatches ( List < U > list , int partitionSize ) { List < List < U >> partitions = Lists . partition ( list , partitionSize ) ; List < Batch < U > > split = new ArrayList <> ( ) ; for ( List < U > partition : partitions ) { split . add ( new Batch < U > ( partition ) ) ; } return split ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the update based on the given gradient [CODESPLIT] @ Override public void applyUpdater ( INDArray gradient , int iteration , int epoch ) { if ( m == null || u == null ) throw new IllegalStateException ( \"Updater has not been initialized with view state\" ) ; //m = B_1 * m + (1-B_1)*grad m . muli ( config . getBeta1 ( ) ) . addi ( gradient . mul ( 1 - config . getBeta1 ( ) ) ) ; //u = max(B_2 * u, |grad|) u . muli ( config . getBeta2 ( ) ) ; Transforms . abs ( gradient , false ) ; //In-place should be OK here, original gradient values aren't used again later Nd4j . getExecutioner ( ) . exec ( new OldMax ( u , gradient , u , u . length ( ) ) ) ; double beta1t = FastMath . pow ( config . getBeta1 ( ) , iteration + 1 ) ; double learningRate = config . getLearningRate ( iteration , epoch ) ; double alphat = learningRate / ( 1.0 - beta1t ) ; if ( Double . isNaN ( alphat ) || Double . isInfinite ( alphat ) || alphat == 0.0 ) { alphat = config . getEpsilon ( ) ; } u . addi ( 1e-32 ) ; // prevent NaNs in params gradient . assign ( m ) . muli ( alphat ) . divi ( u ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "input arrays must have same number of dimensions [CODESPLIT] protected static void validateConcat ( int dimension , INDArray ... arrs ) { if ( arrs [ 0 ] . isScalar ( ) ) { for ( int i = 1 ; i < arrs . length ; i ++ ) if ( ! arrs [ i ] . isScalar ( ) ) throw new IllegalArgumentException ( \"All arrays must have same dimensions\" ) ; } else { int dims = arrs [ 0 ] . shape ( ) . length ; long [ ] shape = ArrayUtil . removeIndex ( arrs [ 0 ] . shape ( ) , dimension ) ; for ( int i = 1 ; i < arrs . length ; i ++ ) { assert Arrays . equals ( shape , ArrayUtil . removeIndex ( arrs [ i ] . shape ( ) , dimension ) ) ; assert arrs [ i ] . shape ( ) . length == dims ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the data opType [CODESPLIT] @ Override public void setDType ( DataBuffer . Type dtype ) { assert dtype == DataBuffer . Type . DOUBLE || dtype == DataBuffer . Type . FLOAT || dtype == DataBuffer . Type . INT : \"Invalid opType passed, must be float or double\" ; // this.dtype = dtype; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a linearly spaced vector [CODESPLIT] @ Override public INDArray linspace ( int lower , int upper , int num ) { double [ ] data = new double [ num ] ; for ( int i = 0 ; i < num ; i ++ ) { double t = ( double ) i / ( num - 1 ) ; data [ i ] = lower * ( 1 - t ) + t * upper ; } //edge case for scalars INDArray ret = Nd4j . create ( data . length ) ; if ( ret . isScalar ( ) ) return ret ; for ( int i = 0 ; i < ret . length ( ) ; i ++ ) ret . putScalar ( i , data [ i ] ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a vector with all of the elements in every nd array equal to the sum of the lengths of the ndarrays [CODESPLIT] @ Override public INDArray toFlattened ( Collection < INDArray > matrices ) { int length = 0 ; for ( INDArray m : matrices ) length += m . length ( ) ; INDArray ret = Nd4j . create ( 1 , length ) ; int linearIndex = 0 ; for ( INDArray d : matrices ) { ret . put ( new INDArrayIndex [ ] { NDArrayIndex . interval ( linearIndex , linearIndex + d . length ( ) ) } , d ) ; linearIndex += d . length ( ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a column vector where each entry is the nth bilinear product of the nth slices of the two tensors . [CODESPLIT] @ Override public INDArray bilinearProducts ( INDArray curr , INDArray in ) { assert curr . shape ( ) . length == 3 ; if ( in . columns ( ) != 1 ) { throw new AssertionError ( \"Expected a column vector\" ) ; } if ( in . rows ( ) != curr . size ( curr . shape ( ) . length - 1 ) ) { throw new AssertionError ( \"Number of rows in the input does not match number of columns in tensor\" ) ; } if ( curr . size ( curr . shape ( ) . length - 2 ) != curr . size ( curr . shape ( ) . length - 1 ) ) { throw new AssertionError ( \"Can only perform this operation on a SimpleTensor with square slices\" ) ; } INDArray ret = Nd4j . create ( curr . slices ( ) , 1 ) ; INDArray inT = in . transpose ( ) ; for ( int i = 0 ; i < curr . slices ( ) ; i ++ ) { INDArray slice = curr . slice ( i ) ; INDArray inTTimesSlice = inT . mmul ( slice ) ; ret . putScalar ( i , Nd4j . getBlasWrapper ( ) . dot ( inTTimesSlice , in ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverses the passed in matrix such that m [ 0 ] becomes m [ m . length - 1 ] etc [CODESPLIT] @ Override public INDArray reverse ( INDArray reverse ) { // FIXME: native method should be used instead INDArray rev = reverse . linearView ( ) ; INDArray ret = Nd4j . create ( rev . shape ( ) ) ; int count = 0 ; for ( long i = rev . length ( ) - 1 ; i >= 0 ; i -- ) { ret . putScalar ( count ++ , rev . getFloat ( i ) ) ; } return ret . reshape ( reverse . shape ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the vectors and append a bias . Each vector must be either row or column vectors . An exception is thrown for inconsistency ( mixed row and column vectors ) [CODESPLIT] @ Override public INDArray appendBias ( INDArray ... vectors ) { int size = 0 ; for ( INDArray vector : vectors ) { size += vector . rows ( ) ; } INDArray result = Nd4j . create ( size + 1 , vectors [ 0 ] . columns ( ) ) ; int index = 0 ; for ( INDArray vector : vectors ) { INDArray put = toFlattened ( vector , Nd4j . ones ( 1 ) ) ; result . put ( new INDArrayIndex [ ] { NDArrayIndex . interval ( index , index + vector . rows ( ) + 1 ) , NDArrayIndex . interval ( 0 , vectors [ 0 ] . columns ( ) ) } , put ) ; index += vector . rows ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a random ( uniform 0 - 1 ) NDArray with the specified shape and order [CODESPLIT] @ Override public INDArray rand ( char order , long rows , long columns ) { return Nd4j . getRandom ( ) . nextDouble ( order , new long [ ] { rows , columns } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a random normal N ( 0 1 ) with the specified order and shape [CODESPLIT] @ Override public INDArray randn ( char order , long rows , long columns ) { return Nd4j . getRandom ( ) . nextGaussian ( order , new long [ ] { rows , columns } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an ndarray with the specified data [CODESPLIT] @ Override public IComplexNDArray createComplex ( double [ ] data ) { assert data . length % 2 == 0 : \"Length of data must be even. A complex ndarray is made up of pairs of real and imaginary components\" ; return createComplex ( data , new int [ ] { 1 , data . length / 2 } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an 1 x num ndarray with the specified value [CODESPLIT] @ Override public IComplexNDArray complexValueOf ( int num , double value ) { IComplexNDArray ones = complexOnes ( num ) ; ones . assign ( Nd4j . createDouble ( value , 0.0 ) ) ; return ones ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an shape ndarray with the specified value [CODESPLIT] @ Override public IComplexNDArray complexValueOf ( int [ ] shape , double value ) { IComplexNDArray ones = complexOnes ( shape ) ; ones . assign ( Nd4j . scalar ( value ) ) ; return ones ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "concatenate ndarrays along a dimension [CODESPLIT] @ Override public INDArray concat ( int dimension , INDArray ... toConcat ) { if ( toConcat . length == 1 ) return toConcat [ 0 ] ; int sumAlongDim = 0 ; boolean allC = toConcat [ 0 ] . ordering ( ) == ' ' ; long [ ] outputShape = ArrayUtil . copy ( toConcat [ 0 ] . shape ( ) ) ; outputShape [ dimension ] = sumAlongDim ; for ( int i = 0 ; i < toConcat . length ; i ++ ) { sumAlongDim += toConcat [ i ] . size ( dimension ) ; allC = allC && toConcat [ i ] . ordering ( ) == ' ' ; for ( int j = 0 ; j < toConcat [ i ] . rank ( ) ; j ++ ) { if ( j != dimension && toConcat [ i ] . size ( j ) != outputShape [ j ] && ! toConcat [ i ] . isVector ( ) ) { throw new IllegalArgumentException ( \"Illegal concatenation at array \" + i + \" and shape element \" + j ) ; } } } long [ ] sortedStrides = Nd4j . getStrides ( outputShape ) ; INDArray ret = Nd4j . create ( outputShape , sortedStrides ) ; allC &= ( ret . ordering ( ) == ' ' ) ; if ( toConcat [ 0 ] . isScalar ( ) ) { INDArray retLinear = ret . linearView ( ) ; for ( int i = 0 ; i < retLinear . length ( ) ; i ++ ) retLinear . putScalar ( i , toConcat [ i ] . getDouble ( 0 ) ) ; return ret ; } if ( dimension == 0 && allC ) { int currBuffer = 0 ; int currBufferOffset = 0 ; for ( int i = 0 ; i < ret . length ( ) ; i ++ ) { ret . data ( ) . put ( i , toConcat [ currBuffer ] . data ( ) . getDouble ( toConcat [ currBuffer ] . offset ( ) + currBufferOffset ++ ) ) ; if ( currBufferOffset >= toConcat [ currBuffer ] . length ( ) ) { currBuffer ++ ; currBufferOffset = 0 ; } } return ret ; } int arrOffset = 0 ; // FIXME: int cast INDArray [ ] retAlongDimensionArrays = new INDArray [ ( int ) ret . tensorssAlongDimension ( dimension ) ] ; for ( int i = 0 ; i < retAlongDimensionArrays . length ; i ++ ) retAlongDimensionArrays [ i ] = ret . tensorAlongDimension ( i , dimension ) ; for ( INDArray arr : toConcat ) { long arrTensorLength = - 1 ; if ( arr . tensorssAlongDimension ( dimension ) != ret . tensorssAlongDimension ( dimension ) ) throw new IllegalStateException ( \"Illegal concatenate. Tensors along dimension must be same length.\" ) ; for ( int i = 0 ; i < arr . tensorssAlongDimension ( dimension ) ; i ++ ) { INDArray retLinear = retAlongDimensionArrays [ i ] ; INDArray arrTensor = arr . tensorAlongDimension ( i , dimension ) ; arrTensorLength = arrTensor . length ( ) ; for ( int j = 0 ; j < arrTensor . length ( ) ; j ++ ) { int idx = j + arrOffset ; retLinear . putScalar ( idx , arrTensor . getDouble ( j ) ) ; } } //bump the sliding window arrOffset += arrTensorLength ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ndarray of ones [CODESPLIT] @ Override public INDArray ones ( int [ ] shape ) { //ensure shapes that wind up being scalar end up with the write shape if ( shape . length == 1 && shape [ 0 ] == 0 ) { shape = new int [ ] { 1 , 1 } ; } INDArray ret = create ( shape ) ; ret . assign ( 1 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ndarray of ones [CODESPLIT] @ Override public IComplexNDArray complexOnes ( int [ ] shape ) { IComplexNDArray ret = createComplex ( shape ) ; ret . assign ( 1 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a complex ndarray with the specified shape [CODESPLIT] public IComplexNDArray createComplex ( float [ ] data , int [ ] shape , int [ ] stride , long offset ) { //ensure shapes that wind up being scalar end up with the write shape if ( shape . length == 1 && shape [ 0 ] == 0 ) { shape = new int [ ] { 1 , 1 } ; } return createComplex ( Nd4j . createBuffer ( data ) , shape , stride , offset , Nd4j . order ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ndrray with the specified shape [CODESPLIT] @ Override public INDArray create ( float [ ] data , int [ ] shape ) { //ensure shapes that wind up being scalar end up with the write shape if ( shape . length == 1 && shape [ 0 ] == 0 ) { shape = new int [ ] { 1 , 1 } ; } return create ( data , shape , Nd4j . getStrides ( shape ) , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ndrray with the specified shape [CODESPLIT] @ Override public IComplexNDArray createComplex ( double [ ] data , int [ ] shape ) { //ensure shapes that wind up being scalar end up with the write shape if ( shape . length == 1 && shape [ 0 ] == 0 ) { shape = new int [ ] { 1 , 1 } ; } return createComplex ( data , shape , Nd4j . getComplexStrides ( shape ) , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ndrray with the specified shape [CODESPLIT] @ Override public IComplexNDArray createComplex ( float [ ] data , int [ ] shape , int [ ] stride ) { return createComplex ( data , shape , stride , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a complex ndarray with the specified shape [CODESPLIT] public IComplexNDArray createComplex ( int [ ] shape , int [ ] stride , long offset ) { if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) return createComplex ( new double [ ArrayUtil . prod ( shape ) * 2 ] , shape , stride , offset ) ; if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT || Nd4j . dataType ( ) == DataBuffer . Type . HALF ) return createComplex ( new float [ ArrayUtil . prod ( shape ) * 2 ] , shape , stride , offset ) ; throw new IllegalStateException ( \"Illegal data opType \" + Nd4j . dataType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a scalar ndarray with the specified offset [CODESPLIT] @ Override public IComplexNDArray complexScalar ( Number value , long offset ) { if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) return scalar ( createDouble ( value . doubleValue ( ) , 0 ) , offset ) ; if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT || Nd4j . dataType ( ) == DataBuffer . Type . INT || Nd4j . dataType ( ) == DataBuffer . Type . HALF ) return scalar ( createFloat ( value . floatValue ( ) , 0 ) , offset ) ; throw new IllegalStateException ( \"Illegal data opType \" + Nd4j . dataType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a scalar nd array with the specified value and offset [CODESPLIT] @ Override public INDArray scalar ( float value ) { if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT || Nd4j . dataType ( ) == DataBuffer . Type . HALF ) return create ( new float [ ] { value } , new int [ ] { 1 , 1 } , new int [ ] { 1 , 1 } , 0 ) ; else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) return scalar ( ( double ) value ) ; else return scalar ( ( int ) value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a scalar nd array with the specified value and offset [CODESPLIT] @ Override public INDArray scalar ( double value ) { if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) return create ( new double [ ] { value } , new int [ ] { 1 , 1 } , new int [ ] { 1 , 1 } , 0 ) ; else return scalar ( ( float ) value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a scalar ndarray with the specified offset [CODESPLIT] @ Override public IComplexNDArray scalar ( IComplexNumber value , long offset ) { if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) return scalar ( value . asDouble ( ) , offset ) ; if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT || Nd4j . dataType ( ) == DataBuffer . Type . HALF ) return scalar ( value . asFloat ( ) , offset ) ; throw new IllegalStateException ( \"Illegal data opType \" + Nd4j . dataType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a scalar nd array with the specified value and offset [CODESPLIT] @ Override public IComplexNDArray scalar ( IComplexFloat value ) { return createComplex ( new float [ ] { value . realComponent ( ) , value . imaginaryComponent ( ) } , new int [ ] { 1 } , new int [ ] { 1 } , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the updater has accumulated enough ndarrays to replicate to the workers [CODESPLIT] @ Override public boolean shouldReplicate ( ) { long now = System . currentTimeMillis ( ) ; long diff = Math . abs ( now - lastSynced ) ; return diff > syncTime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtract two complex numbers in - place [CODESPLIT] @ Override public IComplexNumber subi ( IComplexNumber c , IComplexNumber result ) { return result . set ( realComponent ( ) . doubleValue ( ) - c . realComponent ( ) . doubleValue ( ) , imaginaryComponent ( ) . doubleValue ( ) - c . imaginaryComponent ( ) . doubleValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply two complex numbers inplace [CODESPLIT] @ Override public IComplexNumber muli ( IComplexNumber c , IComplexNumber result ) { double newR = real * c . realComponent ( ) . doubleValue ( ) - imag * c . imaginaryComponent ( ) . doubleValue ( ) ; double newI = real * c . imaginaryComponent ( ) . doubleValue ( ) + imag * c . realComponent ( ) . doubleValue ( ) ; result . set ( newR , newI ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide two complex numbers in - place [CODESPLIT] @ Override public IComplexNumber divi ( IComplexNumber c , IComplexNumber result ) { double d = c . realComponent ( ) . doubleValue ( ) * c . realComponent ( ) . doubleValue ( ) + c . imaginaryComponent ( ) . doubleValue ( ) * c . imaginaryComponent ( ) . doubleValue ( ) ; double newR = ( realComponent ( ) * c . realComponent ( ) . doubleValue ( ) + imaginaryComponent ( ) * c . imaginaryComponent ( ) . doubleValue ( ) ) / d ; double newI = ( imaginaryComponent ( ) * c . realComponent ( ) . doubleValue ( ) - realComponent ( ) * c . imaginaryComponent ( ) . doubleValue ( ) ) / d ; result . set ( newR , newI ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create complex number where the [CODESPLIT] public static IComplexNumber [ ] [ ] complexNumbersFor ( float [ ] [ ] realComponents ) { IComplexNumber [ ] [ ] ret = new IComplexNumber [ realComponents . length ] [ realComponents [ 0 ] . length ] ; for ( int i = 0 ; i < realComponents . length ; i ++ ) for ( int j = 0 ; j < realComponents [ i ] . length ; j ++ ) ret [ i ] [ j ] = Nd4j . createComplexNumber ( realComponents [ i ] [ j ] , 0 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create complex number where the [CODESPLIT] public static IComplexNumber [ ] complexNumbersFor ( float [ ] realComponents ) { IComplexNumber [ ] ret = new IComplexNumber [ realComponents . length ] ; for ( int i = 0 ; i < realComponents . length ; i ++ ) ret [ i ] = Nd4j . createComplexNumber ( realComponents [ i ] , 0 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the sin value of the given complex number [CODESPLIT] public static IComplexNumber atan ( IComplexNumber num ) { Complex c = new Complex ( num . realComponent ( ) . doubleValue ( ) , num . imaginaryComponent ( ) . doubleValue ( ) ) . atan ( ) ; return Nd4j . createDouble ( c . getReal ( ) , c . getImaginary ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ceiling value of the given complex number [CODESPLIT] public static IComplexNumber ceil ( IComplexNumber num ) { Complex c = new Complex ( FastMath . ceil ( num . realComponent ( ) . doubleValue ( ) ) , FastMath . ceil ( num . imaginaryComponent ( ) . doubleValue ( ) ) ) ; return Nd4j . createDouble ( c . getReal ( ) , c . getImaginary ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the log value of the given complex number [CODESPLIT] public static IComplexNumber neg ( IComplexNumber num ) { Complex c = new Complex ( num . realComponent ( ) . doubleValue ( ) , num . imaginaryComponent ( ) . doubleValue ( ) ) . negate ( ) ; return Nd4j . createDouble ( c . getReal ( ) , c . getImaginary ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the absolute value of the given complex number [CODESPLIT] public static IComplexNumber abs ( IComplexNumber num ) { double c = new Complex ( num . realComponent ( ) . doubleValue ( ) , num . imaginaryComponent ( ) . doubleValue ( ) ) . abs ( ) ; return Nd4j . createDouble ( c , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Raise a complex number to a power [CODESPLIT] public static IComplexNumber pow ( IComplexNumber num , IComplexNumber power ) { Complex c = new Complex ( num . realComponent ( ) . doubleValue ( ) , num . imaginaryComponent ( ) . doubleValue ( ) ) . pow ( new Complex ( power . realComponent ( ) . doubleValue ( ) , power . imaginaryComponent ( ) . doubleValue ( ) ) ) ; if ( c . isNaN ( ) ) c = new Complex ( Nd4j . EPS_THRESHOLD , 0.0 ) ; return Nd4j . createDouble ( c . getReal ( ) , c . getImaginary ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the exp of a complex number : Let r be the realComponent component and i be the imaginary Let ret be the complex number returned ret - > exp ( r ) * cos ( i ) exp ( r ) * sin ( i ) where the first number is the realComponent component and the second number is the imaginary component [CODESPLIT] public static IComplexNumber exp ( IComplexNumber d ) { if ( d instanceof IComplexFloat ) return exp ( ( IComplexFloat ) d ) ; return exp ( ( IComplexDouble ) d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the exp of a complex number : Let r be the realComponent component and i be the imaginary Let ret be the complex number returned ret - > exp ( r ) * cos ( i ) exp ( r ) * sin ( i ) where the first number is the realComponent component and the second number is the imaginary component [CODESPLIT] public static IComplexDouble exp ( IComplexDouble d ) { return Nd4j . createDouble ( FastMath . exp ( d . realComponent ( ) ) * FastMath . cos ( d . imaginaryComponent ( ) ) , FastMath . exp ( d . realComponent ( ) ) * FastMath . sin ( d . imaginaryComponent ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the exp of a complex number : Let r be the realComponent component and i be the imaginary Let ret be the complex number returned ret - > exp ( r ) * cos ( i ) exp ( r ) * sin ( i ) where the first number is the realComponent component and the second number is the imaginary component [CODESPLIT] public static IComplexFloat exp ( IComplexFloat d ) { return Nd4j . createFloat ( ( float ) FastMath . exp ( d . realComponent ( ) ) * ( float ) FastMath . cos ( d . imaginaryComponent ( ) ) , ( float ) FastMath . exp ( d . realComponent ( ) ) * ( float ) FastMath . sin ( d . imaginaryComponent ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a context [CODESPLIT] public Aeron . Context getContext ( ) { Aeron . Context ctx = new Aeron . Context ( ) . publicationConnectionTimeout ( - 1 ) . availableImageHandler ( AeronUtil :: printAvailableImage ) . unavailableImageHandler ( AeronUtil :: printUnavailableImage ) . aeronDirectoryName ( mediaDriverDirectoryName ) . keepAliveInterval ( 100000 ) . errorHandler ( e -> log . error ( e . toString ( ) , e ) ) ; return ctx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method frees specific chunk of memory described by AllocationPoint passed in [CODESPLIT] @ Override public void free ( AllocationPoint point ) { if ( point . getAllocationStatus ( ) == AllocationStatus . DEVICE ) { if ( point . isConstant ( ) ) return ; AllocationShape shape = point . getShape ( ) ; int deviceId = point . getDeviceId ( ) ; long address = point . getDevicePointer ( ) . address ( ) ; long reqMemory = AllocationUtils . getRequiredMemory ( shape ) ; // we don't cache too big objects if ( reqMemory > CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getMaximumDeviceCacheableLength ( ) || deviceCachedAmount . get ( deviceId ) . get ( ) >= CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getMaximumHostCache ( ) ) { //log.info(\"DEVICE_{} memory purging: {} bytes; MS: {}; MT: {}\", deviceId, reqMemory, MAX_GPU_ALLOCATION, MAX_GPU_CACHE); super . free ( point ) ; return ; } //            log.info(\"Saving HOST memory into cache...\"); ensureDeviceCacheHolder ( deviceId , shape ) ; CacheHolder cache = deviceCache . get ( deviceId ) . get ( shape ) ; if ( point . getDeviceId ( ) != deviceId ) throw new RuntimeException ( \"deviceId changed!\" ) ; // memory chunks < threshold will be cached no matter what if ( reqMemory <= FORCED_CACHE_THRESHOLD ) { cache . put ( new CudaPointer ( point . getDevicePointer ( ) . address ( ) ) ) ; return ; } else { long cacheEntries = cache . size ( ) ; long cacheHeight = deviceCache . get ( deviceId ) . size ( ) ; // total memory allocated within this bucket long cacheDepth = cacheEntries * reqMemory ; //if (cacheDepth < MAX_CACHED_MEMORY / cacheHeight) { cache . put ( new CudaPointer ( point . getDevicePointer ( ) . address ( ) ) ) ; return ; //} else { //    super.free(point); // } } } super . free ( point ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a subset of this array based on the specified indexes [CODESPLIT] @ Override public INDArray get ( INDArrayIndex ... indexes ) { //check for row/column vector and point index being 0 if ( indexes . length == 1 && indexes [ 0 ] instanceof NDArrayIndexAll || ( indexes . length == 2 && ( isRowVector ( ) && indexes [ 0 ] instanceof PointIndex && indexes [ 0 ] . offset ( ) == 0 && indexes [ 1 ] instanceof NDArrayIndexAll || isColumnVector ( ) && indexes [ 1 ] instanceof PointIndex && indexes [ 0 ] . offset ( ) == 0 && indexes [ 0 ] instanceof NDArrayIndexAll ) ) ) return this ; indexes = NDArrayIndex . resolve ( shapeInfoDataBuffer ( ) , indexes ) ; ShapeOffsetResolution resolution = new ShapeOffsetResolution ( this ) ; resolution . exec ( indexes ) ; if ( indexes . length < 1 ) throw new IllegalStateException ( \"Invalid index found of zero length\" ) ; // FIXME: LONG int [ ] shape = LongUtils . toInts ( resolution . getShapes ( ) ) ; int numSpecifiedIndex = 0 ; for ( int i = 0 ; i < indexes . length ; i ++ ) if ( indexes [ i ] instanceof SpecifiedIndex ) numSpecifiedIndex ++ ; if ( shape != null && numSpecifiedIndex > 0 ) { // TODO create a new ndarray with the specified indexes return null ; } INDArray ret = subArray ( resolution ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the list of datasets in to one list . All the rows are merged in to one dataset [CODESPLIT] public static DataSet merge ( List < DataSet > data ) { if ( data . isEmpty ( ) ) throw new IllegalArgumentException ( \"Unable to merge empty dataset\" ) ; int nonEmpty = 0 ; boolean anyFeaturesPreset = false ; boolean anyLabelsPreset = false ; boolean first = true ; for ( DataSet ds : data ) { if ( ds . isEmpty ( ) ) { continue ; } nonEmpty ++ ; if ( anyFeaturesPreset && ds . getFeatures ( ) == null || ( ! first && ! anyFeaturesPreset && ds . getFeatures ( ) != null ) ) { throw new IllegalStateException ( \"Cannot merge features: encountered null features in one or more DataSets\" ) ; } if ( anyLabelsPreset && ds . getLabels ( ) == null || ( ! first && ! anyLabelsPreset && ds . getLabels ( ) != null ) ) { throw new IllegalStateException ( \"Cannot merge labels: enountered null labels in one or more DataSets\" ) ; } anyFeaturesPreset |= ds . getFeatures ( ) != null ; anyLabelsPreset |= ds . getLabels ( ) != null ; first = false ; } INDArray [ ] featuresToMerge = new INDArray [ nonEmpty ] ; INDArray [ ] labelsToMerge = new INDArray [ nonEmpty ] ; INDArray [ ] featuresMasksToMerge = null ; INDArray [ ] labelsMasksToMerge = null ; int count = 0 ; for ( DataSet ds : data ) { if ( ds . isEmpty ( ) ) continue ; featuresToMerge [ count ] = ds . getFeatureMatrix ( ) ; labelsToMerge [ count ] = ds . getLabels ( ) ; if ( ds . getFeaturesMaskArray ( ) != null ) { if ( featuresMasksToMerge == null ) { featuresMasksToMerge = new INDArray [ data . size ( ) ] ; } featuresMasksToMerge [ count ] = ds . getFeaturesMaskArray ( ) ; } if ( ds . getLabelsMaskArray ( ) != null ) { if ( labelsMasksToMerge == null ) { labelsMasksToMerge = new INDArray [ data . size ( ) ] ; } labelsMasksToMerge [ count ] = ds . getLabelsMaskArray ( ) ; } count ++ ; } INDArray featuresOut ; INDArray labelsOut ; INDArray featuresMaskOut ; INDArray labelsMaskOut ; Pair < INDArray , INDArray > fp = DataSetUtil . mergeFeatures ( featuresToMerge , featuresMasksToMerge ) ; featuresOut = fp . getFirst ( ) ; featuresMaskOut = fp . getSecond ( ) ; Pair < INDArray , INDArray > lp = DataSetUtil . mergeLabels ( labelsToMerge , labelsMasksToMerge ) ; labelsOut = lp . getFirst ( ) ; labelsMaskOut = lp . getSecond ( ) ; DataSet dataset = new DataSet ( featuresOut , labelsOut , featuresMaskOut , labelsMaskOut ) ; List < Serializable > meta = null ; for ( DataSet ds : data ) { if ( ds . getExampleMetaData ( ) == null || ds . getExampleMetaData ( ) . size ( ) != ds . numExamples ( ) ) { meta = null ; break ; } if ( meta == null ) meta = new ArrayList <> ( ) ; meta . addAll ( ds . getExampleMetaData ( ) ) ; } if ( meta != null ) { dataset . setExampleMetaData ( meta ) ; } return dataset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binarizes the dataset such that any number greater than cutoff is 1 otherwise zero [CODESPLIT] @ Override public void binarize ( double cutoff ) { INDArray linear = getFeatureMatrix ( ) . linearView ( ) ; for ( int i = 0 ; i < getFeatures ( ) . length ( ) ; i ++ ) { double curr = linear . getDouble ( i ) ; if ( curr > cutoff ) getFeatures ( ) . putScalar ( i , 1 ) ; else getFeatures ( ) . putScalar ( i , 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a copy of example i [CODESPLIT] @ Override public DataSet get ( int i ) { if ( i > numExamples ( ) || i < 0 ) throw new IllegalArgumentException ( \"invalid example number\" ) ; if ( i == 0 && numExamples ( ) == 1 ) return this ; if ( getFeatureMatrix ( ) . rank ( ) == 4 ) { //ensure rank is preserved INDArray slice = getFeatureMatrix ( ) . slice ( i ) ; return new DataSet ( slice . reshape ( ArrayUtil . combine ( new long [ ] { 1 } , slice . shape ( ) ) ) , getLabels ( ) . slice ( i ) ) ; } return new DataSet ( getFeatures ( ) . slice ( i ) , getLabels ( ) . slice ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a copy of example i [CODESPLIT] @ Override public DataSet get ( int [ ] i ) { return new DataSet ( getFeatures ( ) . getRows ( i ) , getLabels ( ) . getRows ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sample a dataset [CODESPLIT] @ Override public DataSet sample ( int numSamples , org . nd4j . linalg . api . rng . Random rng , boolean withReplacement ) { INDArray examples = Nd4j . create ( numSamples , getFeatures ( ) . columns ( ) ) ; INDArray outcomes = Nd4j . create ( numSamples , numOutcomes ( ) ) ; Set < Integer > added = new HashSet <> ( ) ; for ( int i = 0 ; i < numSamples ; i ++ ) { int picked = rng . nextInt ( numExamples ( ) ) ; if ( ! withReplacement ) while ( added . contains ( picked ) ) picked = rng . nextInt ( numExamples ( ) ) ; examples . putRow ( i , get ( picked ) . getFeatures ( ) ) ; outcomes . putRow ( i , get ( picked ) . getLabels ( ) ) ; } return new DataSet ( examples , outcomes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns memory used by this DataSet [CODESPLIT] @ Override public long getMemoryFootprint ( ) { long reqMem = features . lengthLong ( ) * Nd4j . sizeOfDataType ( ) ; reqMem += labels == null ? 0 : labels . lengthLong ( ) * Nd4j . sizeOfDataType ( ) ; reqMem += featuresMask == null ? 0 : featuresMask . lengthLong ( ) * Nd4j . sizeOfDataType ( ) ; reqMem += labelsMask == null ? 0 : labelsMask . lengthLong ( ) * Nd4j . sizeOfDataType ( ) ; return reqMem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a string representation of the exception . [CODESPLIT] public static String stringifyException ( Throwable e ) { StringWriter stm = new StringWriter ( ) ; PrintWriter wrt = new PrintWriter ( stm ) ; e . printStackTrace ( wrt ) ; wrt . close ( ) ; return stm . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a full hostname return the word upto the first dot . [CODESPLIT] public static String simpleHostname ( String fullHostname ) { if ( InetAddresses . isInetAddress ( fullHostname ) ) { return fullHostname ; } int offset = fullHostname . indexOf ( ' ' ) ; if ( offset != - 1 ) { return fullHostname . substring ( 0 , offset ) ; } return fullHostname ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The same as String . format ( Locale . ENGLISH format objects ) . [CODESPLIT] public static String format ( final String format , final Object ... objects ) { return String . format ( Locale . ENGLISH , format , objects ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an array of strings return a comma - separated list of its elements . [CODESPLIT] public static String arrayToString ( String [ ] strs ) { if ( strs . length == 0 ) { return \"\" ; } StringBuilder sbuf = new StringBuilder ( ) ; sbuf . append ( strs [ 0 ] ) ; for ( int idx = 1 ; idx < strs . length ; idx ++ ) { sbuf . append ( \",\" ) ; sbuf . append ( strs [ idx ] ) ; } return sbuf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an array of bytes it will convert the bytes to a hex string representation of the bytes [CODESPLIT] public static String byteToHexString ( byte [ ] bytes , int start , int end ) { if ( bytes == null ) { throw new IllegalArgumentException ( \"bytes == null\" ) ; } StringBuilder s = new StringBuilder ( ) ; for ( int i = start ; i < end ; i ++ ) { s . append ( format ( \"%02x\" , bytes [ i ] ) ) ; } return s . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats time in ms and appends difference ( finishTime - startTime ) as returned by formatTimeDiff () . If finish time is 0 empty string is returned if start time is 0 then difference is not appended to return value . [CODESPLIT] public static String getFormattedTimeWithDiff ( String formattedFinishTime , long finishTime , long startTime ) { StringBuilder buf = new StringBuilder ( ) ; if ( 0 != finishTime ) { buf . append ( formattedFinishTime ) ; if ( 0 != startTime ) { buf . append ( \" (\" + formatTimeDiff ( finishTime , startTime ) + \")\" ) ; } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an arraylist of strings . [CODESPLIT] public static String [ ] getStrings ( String str , String delim ) { Collection < String > values = getStringCollection ( str , delim ) ; if ( values . size ( ) == 0 ) { return null ; } return values . toArray ( new String [ values . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection of strings . [CODESPLIT] public static Collection < String > getStringCollection ( String str ) { String delim = \",\" ; return getStringCollection ( str , delim ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection of strings . [CODESPLIT] public static Collection < String > getStringCollection ( String str , String delim ) { List < String > values = new ArrayList < String > ( ) ; if ( str == null ) return values ; StringTokenizer tokenizer = new StringTokenizer ( str , delim ) ; while ( tokenizer . hasMoreTokens ( ) ) { values . add ( tokenizer . nextToken ( ) ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a comma separated value <code > String< / code > trimming leading and trailing whitespace on each value . Duplicate and empty values are removed . [CODESPLIT] public static Collection < String > getTrimmedStringCollection ( String str ) { Set < String > set = new LinkedHashSet < String > ( Arrays . asList ( getTrimmedStrings ( str ) ) ) ; set . remove ( \"\" ) ; return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a comma or newline separated value <code > String< / code > trimming leading and trailing whitespace on each value . [CODESPLIT] public static String [ ] getTrimmedStrings ( String str ) { if ( null == str || str . trim ( ) . isEmpty ( ) ) { return emptyStringArray ; } return str . trim ( ) . split ( \"\\\\s*[,\\n]\\\\s*\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string using the given separator [CODESPLIT] public static String [ ] split ( String str , char escapeChar , char separator ) { if ( str == null ) { return null ; } ArrayList < String > strList = new ArrayList < String > ( ) ; StringBuilder split = new StringBuilder ( ) ; int index = 0 ; while ( ( index = findNext ( str , separator , escapeChar , index , split ) ) >= 0 ) { ++ index ; // move over the separator for next search strList . add ( split . toString ( ) ) ; split . setLength ( 0 ) ; // reset the buffer } strList . add ( split . toString ( ) ) ; // remove trailing empty split(s) int last = strList . size ( ) ; // last split while ( -- last >= 0 && \"\" . equals ( strList . get ( last ) ) ) { strList . remove ( last ) ; } return strList . toArray ( new String [ strList . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string using the given separator with no escaping performed . [CODESPLIT] public static String [ ] split ( String str , char separator ) { // String.split returns a single empty result for splitting the empty // string. if ( str . isEmpty ( ) ) { return new String [ ] { \"\" } ; } ArrayList < String > strList = new ArrayList < String > ( ) ; int startIndex = 0 ; int nextIndex = 0 ; while ( ( nextIndex = str . indexOf ( separator , startIndex ) ) != - 1 ) { strList . add ( str . substring ( startIndex , nextIndex ) ) ; startIndex = nextIndex + 1 ; } strList . add ( str . substring ( startIndex ) ) ; // remove trailing empty split(s) int last = strList . size ( ) ; // last split while ( -- last >= 0 && \"\" . equals ( strList . get ( last ) ) ) { strList . remove ( last ) ; } return strList . toArray ( new String [ strList . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence of the separator character ignoring the escaped separators starting from the index . Note the substring between the index and the position of the separator is passed . [CODESPLIT] public static int findNext ( String str , char separator , char escapeChar , int start , StringBuilder split ) { int numPreEscapes = 0 ; for ( int i = start ; i < str . length ( ) ; i ++ ) { char curChar = str . charAt ( i ) ; if ( numPreEscapes == 0 && curChar == separator ) { // separator return i ; } else { split . append ( curChar ) ; numPreEscapes = ( curChar == escapeChar ) ? ( ++ numPreEscapes ) % 2 : 0 ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape <code > charToEscape< / code > in the string with the escape char <code > escapeChar< / code > [CODESPLIT] public static String escapeString ( String str , char escapeChar , char charToEscape ) { return escapeString ( str , escapeChar , new char [ ] { charToEscape } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unescape <code > charToEscape< / code > in the string with the escape char <code > escapeChar< / code > [CODESPLIT] public static String unEscapeString ( String str , char escapeChar , char charToEscape ) { return unEscapeString ( str , escapeChar , new char [ ] { charToEscape } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escapes HTML Special characters present in the string . [CODESPLIT] public static String escapeHTML ( String string ) { if ( string == null ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; boolean lastCharacterWasSpace = false ; char [ ] chars = string . toCharArray ( ) ; for ( char c : chars ) { if ( c == ' ' ) { if ( lastCharacterWasSpace ) { lastCharacterWasSpace = false ; sb . append ( \"&nbsp;\" ) ; } else { lastCharacterWasSpace = true ; sb . append ( \" \" ) ; } } else { lastCharacterWasSpace = false ; switch ( c ) { case ' ' : sb . append ( \"&lt;\" ) ; break ; case ' ' : sb . append ( \"&gt;\" ) ; break ; case ' ' : sb . append ( \"&amp;\" ) ; break ; case ' ' : sb . append ( \"&quot;\" ) ; break ; default : sb . append ( c ) ; break ; } } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates strings using a separator . [CODESPLIT] public static String join ( CharSequence separator , Iterable < ? > strings ) { Iterator < ? > i = strings . iterator ( ) ; if ( ! i . hasNext ( ) ) { return \"\" ; } StringBuilder sb = new StringBuilder ( i . next ( ) . toString ( ) ) ; while ( i . hasNext ( ) ) { sb . append ( separator ) ; sb . append ( i . next ( ) . toString ( ) ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert SOME_STUFF to SomeStuff [CODESPLIT] public static String camelize ( String s ) { StringBuilder sb = new StringBuilder ( ) ; String [ ] words = split ( StringUtils . toLowerCase ( s ) , ESCAPE_CHAR , ' ' ) ; for ( String word : words ) sb . append ( org . apache . commons . lang3 . StringUtils . capitalize ( word ) ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches a template string against a pattern replaces matched tokens with the supplied replacements and returns the result . The regular expression must use a capturing group . The value of the first capturing group is used to look up the replacement . If no replacement is found for the token then it is replaced with the empty string . [CODESPLIT] public static String replaceTokens ( String template , Pattern pattern , Map < String , String > replacements ) { StringBuffer sb = new StringBuffer ( ) ; Matcher matcher = pattern . matcher ( template ) ; while ( matcher . find ( ) ) { String replacement = replacements . get ( matcher . group ( 1 ) ) ; if ( replacement == null ) { replacement = \"\" ; } matcher . appendReplacement ( sb , Matcher . quoteReplacement ( replacement ) ) ; } matcher . appendTail ( sb ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get stack trace for a given thread . [CODESPLIT] public static String getStackTrace ( Thread t ) { final StackTraceElement [ ] stackTrace = t . getStackTrace ( ) ; StringBuilder str = new StringBuilder ( ) ; for ( StackTraceElement e : stackTrace ) { str . append ( e . toString ( ) + \"\\n\" ) ; } return str . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare strings locale - freely by using String#equalsIgnoreCase . [CODESPLIT] public static boolean equalsIgnoreCase ( String s1 , String s2 ) { Preconditions . checkNotNull ( s1 ) ; // don't check non-null against s2 to make the semantics same as // s1.equals(s2) return s1 . equalsIgnoreCase ( s2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Checks if the String contains only unicode letters . < / p > [CODESPLIT] public static boolean isAlpha ( String str ) { if ( str == null ) { return false ; } int sz = str . length ( ) ; for ( int i = 0 ; i < sz ; i ++ ) { if ( ! Character . isLetter ( str . charAt ( i ) ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inverts a matrix [CODESPLIT] public static INDArray invert ( INDArray arr , boolean inPlace ) { if ( ! arr . isSquare ( ) ) { throw new IllegalArgumentException ( \"invalid array: must be square matrix\" ) ; } //FIX ME: Please /* int[] IPIV = new int[arr.length() + 1];\n        int LWORK = arr.length() * arr.length();\n        INDArray WORK = Nd4j.create(new double[LWORK]);\n        INDArray inverse = inPlace ? arr : arr.dup();\n        Nd4j.getBlasWrapper().lapack().getrf(arr);\n        Nd4j.getBlasWrapper().lapack().getri(arr.size(0),inverse,arr.size(0),IPIV,WORK,LWORK,0);*/ RealMatrix rm = CheckUtil . convertToApacheMatrix ( arr ) ; RealMatrix rmInverse = new LUDecomposition ( rm ) . getSolver ( ) . getInverse ( ) ; INDArray inverse = CheckUtil . convertFromApacheMatrix ( rmInverse ) ; if ( inPlace ) arr . assign ( inverse ) ; return inverse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the factorial of the non - negative integer . [CODESPLIT] public BigInteger at ( int n ) { while ( a . size ( ) <= n ) { final int lastn = a . size ( ) - 1 ; final BigInteger nextn = BigInteger . valueOf ( lastn + 1 ) ; a . add ( a . get ( lastn ) . multiply ( nextn ) ) ; } return a . get ( n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns if host side has actual copy of data [CODESPLIT] public boolean isActualOnHostSide ( ) { //log.info(\"isActuialOnHostSide() -> Host side: [{}], Device side: [{}]\", accessHostRead.get(), accessDeviceRead.get()); boolean result = accessHostWrite . get ( ) >= accessDeviceWrite . get ( ) || accessHostRead . get ( ) >= accessDeviceWrite . get ( ) ; //log.info(\"isActuialOnHostSide() -> {}, shape: {}\", result, shape); return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns if device side has actual copy of data [CODESPLIT] public boolean isActualOnDeviceSide ( ) { //log.info(\"isActuialOnDeviceSide() -> Host side: [{}], Device side: [{}]\", accessHostWrite.get(), accessDeviceWrite.get()); boolean result = accessDeviceWrite . get ( ) >= accessHostWrite . get ( ) || accessDeviceRead . get ( ) >= accessHostWrite . get ( ) ; //accessHostWrite.get() <= getDeviceAccessTime(); //        log.info(\"isActuialOnDeviceSide() -> {} ({}), Shape: {}\", result, objectId, shape); return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method creates shapeInformation buffer based on shape being passed in [CODESPLIT] @ Override public Pair < DataBuffer , long [ ] > createShapeInformation ( int [ ] shape ) { char order = Nd4j . order ( ) ; return createShapeInformation ( shape , order ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method creates shapeInformation buffer based on shape & order being passed in [CODESPLIT] @ Override public Pair < DataBuffer , long [ ] > createShapeInformation ( long [ ] shape , char order ) { long [ ] stride = Nd4j . getStrides ( shape , order ) ; // this won't be view, so ews is 1 int ews = 1 ; return createShapeInformation ( shape , stride , 0 , ews , order ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given shape is a vector [CODESPLIT] public static boolean isVector ( DataBuffer shapeInfo ) { int rank = Shape . rank ( shapeInfo ) ; if ( rank > 2 || rank < 1 ) return false ; else { int len = Shape . length ( shapeInfo ) ; DataBuffer shape = Shape . shapeOf ( shapeInfo ) ; return shape . getInt ( 0 ) == len || shape . getInt ( 1 ) == len ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A port of numpy s reshaping algorithm that leverages no copy where possible and returns null if the reshape couldn t happen without copying [CODESPLIT] public static INDArray newShapeNoCopy ( INDArray arr , long [ ] newShape , boolean isFOrder ) { int oldnd ; long [ ] olddims = ArrayUtil . copy ( arr . shape ( ) ) ; long [ ] oldstrides = ArrayUtil . copy ( arr . stride ( ) ) ; long np , op , last_stride ; int oi , oj , ok , ni , nj , nk ; long [ ] newStrides = new long [ newShape . length ] ; oldnd = 0 ; /*\n         * Remove axes with dimension 1 from the old array. They have no effect\n         * but would need special cases since their strides do not matter.\n         */ for ( oi = 0 ; oi < arr . rank ( ) ; oi ++ ) { if ( arr . size ( oi ) != 1 ) { olddims [ oldnd ] = arr . size ( oi ) ; oldstrides [ oldnd ] = arr . stride ( oi ) ; oldnd ++ ; } } np = 1 ; for ( ni = 0 ; ni < newShape . length ; ni ++ ) { np *= newShape [ ni ] ; } op = 1 ; for ( oi = 0 ; oi < oldnd ; oi ++ ) { op *= olddims [ oi ] ; } if ( np != op ) { /* different total sizes; no hope */ return null ; } if ( np == 0 ) { /* the current code does not handle 0-sized arrays, so give up */ return null ; } /* oi to oj and ni to nj give the axis ranges currently worked with */ oi = 0 ; oj = 1 ; ni = 0 ; nj = 1 ; while ( ni < newShape . length && oi < oldnd ) { np = newShape [ ni ] ; op = olddims [ oi ] ; while ( np != op ) { if ( np < op ) { /* Misses trailing 1s, these are handled later */ np *= newShape [ nj ++ ] ; } else { op *= olddims [ oj ++ ] ; } } /* Check whether the original axes can be combined */ for ( ok = oi ; ok < oj - 1 ; ok ++ ) { if ( isFOrder ) { if ( oldstrides [ ok + 1 ] != olddims [ ok ] * oldstrides [ ok ] ) { /* not contiguous enough */ return null ; } } else { /* C order */ if ( oldstrides [ ok ] != olddims [ ok + 1 ] * oldstrides [ ok + 1 ] ) { /* not contiguous enough */ return null ; } } } /* Calculate new strides for all axes currently worked with */ if ( isFOrder ) { newStrides [ ni ] = oldstrides [ oi ] ; for ( nk = ni + 1 ; nk < nj ; nk ++ ) { newStrides [ nk ] = newStrides [ nk - 1 ] * newShape [ nk - 1 ] ; } } else { /* C order */ newStrides [ nj - 1 ] = oldstrides [ oj - 1 ] ; for ( nk = nj - 1 ; nk > ni ; nk -- ) { newStrides [ nk - 1 ] = newStrides [ nk ] * newShape [ nk ] ; } } ni = nj ++ ; oi = oj ++ ; } /*\n         * Set strides corresponding to trailing 1s of the new shape.\n         */ if ( ni >= 1 ) { last_stride = newStrides [ ni - 1 ] ; } else { last_stride = arr . elementStride ( ) ; } if ( isFOrder && ni >= 1 ) { last_stride *= newShape [ ni - 1 ] ; } for ( nk = ni ; nk < newShape . length ; nk ++ ) { newStrides [ nk ] = last_stride ; } if ( arr instanceof IComplexNDArray ) //return Nd4j.createComplex(arr.data(), newShape, newStrides, arr.offset()); throw new UnsupportedOperationException ( ) ; INDArray ret = Nd4j . create ( arr . data ( ) , newShape , newStrides , arr . offset ( ) , isFOrder ? ' ' : ' ' ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Infer the order for the ndarray based on the array s strides [CODESPLIT] public static char getOrder ( INDArray arr ) { return getOrder ( arr . shape ( ) , arr . stride ( ) , arr . elementStride ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the offset for the given array given the indices [CODESPLIT] public static long offsetFor ( INDArray arr , int [ ] indexes ) { ShapeOffsetResolution resolution = new ShapeOffsetResolution ( arr ) ; resolution . exec ( Shape . toIndexes ( indexes ) ) ; return resolution . getOffset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the given int indexes to nd array indexes [CODESPLIT] public static INDArrayIndex [ ] toIndexes ( int [ ] indices ) { INDArrayIndex [ ] ret = new INDArrayIndex [ indices . length ] ; for ( int i = 0 ; i < ret . length ; i ++ ) ret [ i ] = new NDArrayIndex ( indices [ i ] ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get array shape from an int [] [CODESPLIT] public static int [ ] shape ( int [ ] buffer ) { int [ ] ret = new int [ rank ( buffer ) ] ; for ( int i = 0 ; i < ret . length ; i ++ ) ret [ i ] = buffer [ 1 + i ] ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts files to the specified destination [CODESPLIT] public static void unzipFileTo ( String file , String dest ) throws IOException { File target = new File ( file ) ; if ( ! target . exists ( ) ) throw new IllegalArgumentException ( \"Archive doesnt exist\" ) ; FileInputStream fin = new FileInputStream ( target ) ; int BUFFER = 2048 ; byte data [ ] = new byte [ BUFFER ] ; if ( file . endsWith ( \".zip\" ) || file . endsWith ( \".jar\" ) ) { try ( ZipInputStream zis = new ZipInputStream ( fin ) ) { //get the zipped file list entry ZipEntry ze = zis . getNextEntry ( ) ; while ( ze != null ) { String fileName = ze . getName ( ) ; File newFile = new File ( dest + File . separator + fileName ) ; if ( ze . isDirectory ( ) ) { newFile . mkdirs ( ) ; zis . closeEntry ( ) ; ze = zis . getNextEntry ( ) ; continue ; } FileOutputStream fos = new FileOutputStream ( newFile ) ; int len ; while ( ( len = zis . read ( data ) ) > 0 ) { fos . write ( data , 0 , len ) ; } fos . close ( ) ; ze = zis . getNextEntry ( ) ; log . debug ( \"File extracted: \" + newFile . getAbsoluteFile ( ) ) ; } zis . closeEntry ( ) ; } } else if ( file . endsWith ( \".tar.gz\" ) || file . endsWith ( \".tgz\" ) ) { BufferedInputStream in = new BufferedInputStream ( fin ) ; GzipCompressorInputStream gzIn = new GzipCompressorInputStream ( in ) ; TarArchiveInputStream tarIn = new TarArchiveInputStream ( gzIn ) ; TarArchiveEntry entry ; /* Read the tar entries using the getNextEntry method **/ while ( ( entry = ( TarArchiveEntry ) tarIn . getNextEntry ( ) ) != null ) { log . info ( \"Extracting: \" + entry . getName ( ) ) ; /* If the entry is a directory, create the directory. */ if ( entry . isDirectory ( ) ) { File f = new File ( dest + File . separator + entry . getName ( ) ) ; f . mkdirs ( ) ; } /*\n                 * If the entry is a file,write the decompressed file to the disk\n                 * and close destination stream.\n                 */ else { int count ; try ( FileOutputStream fos = new FileOutputStream ( dest + File . separator + entry . getName ( ) ) ; BufferedOutputStream destStream = new BufferedOutputStream ( fos , BUFFER ) ; ) { while ( ( count = tarIn . read ( data , 0 , BUFFER ) ) != - 1 ) { destStream . write ( data , 0 , count ) ; } destStream . flush ( ) ; IOUtils . closeQuietly ( destStream ) ; } } } // Close the input stream tarIn . close ( ) ; } else if ( file . endsWith ( \".gz\" ) ) { File extracted = new File ( target . getParent ( ) , target . getName ( ) . replace ( \".gz\" , \"\" ) ) ; if ( extracted . exists ( ) ) extracted . delete ( ) ; extracted . createNewFile ( ) ; try ( GZIPInputStream is2 = new GZIPInputStream ( fin ) ; OutputStream fos = FileUtils . openOutputStream ( extracted ) ) { IOUtils . copyLarge ( is2 , fos ) ; fos . flush ( ) ; } } else { throw new IllegalStateException ( \"Unable to infer file type (compression format) from source file name: \" + file ) ; } target . delete ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special method for [CODESPLIT] protected short getShort ( long i ) { if ( dataType ( ) != Type . HALF ) throw new UnsupportedOperationException ( \"getShort() is supported for Half-precision buffers only\" ) ; return fromFloat ( ( ( HalfIndexer ) indexer ) . get ( offset ( ) + i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reallocate the native memory of the buffer [CODESPLIT] @ Override public DataBuffer reallocate ( long length ) { Pointer oldPointer = pointer ; if ( isAttached ( ) ) { long capacity = length * getElementSize ( ) ; switch ( dataType ( ) ) { case DOUBLE : pointer = getParentWorkspace ( ) . alloc ( capacity , Type . DOUBLE , false ) . asDoublePointer ( ) ; indexer = DoubleIndexer . create ( ( DoublePointer ) pointer ) ; break ; case FLOAT : pointer = getParentWorkspace ( ) . alloc ( capacity , Type . FLOAT , false ) . asFloatPointer ( ) ; indexer = FloatIndexer . create ( ( FloatPointer ) pointer ) ; break ; case INT : pointer = getParentWorkspace ( ) . alloc ( capacity , Type . INT , false ) . asIntPointer ( ) ; indexer = IntIndexer . create ( ( IntPointer ) pointer ) ; break ; } workspaceGenerationId = getParentWorkspace ( ) . getGenerationId ( ) ; } else { switch ( dataType ( ) ) { case INT : pointer = new IntPointer ( length ) ; indexer = IntIndexer . create ( ( IntPointer ) pointer ) ; break ; case DOUBLE : pointer = new DoublePointer ( length ) ; indexer = DoubleIndexer . create ( ( DoublePointer ) pointer ) ; break ; case FLOAT : pointer = new FloatPointer ( length ) ; indexer = FloatIndexer . create ( ( FloatPointer ) pointer ) ; break ; } } Pointer . memcpy ( pointer , oldPointer , this . length ( ) * getElementSize ( ) ) ; //this.underlyingLength = length; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes given CustomOp [CODESPLIT] public void exec ( CustomOp op ) { Nd4j . getExecutioner ( ) . commit ( ) ; if ( op . opName ( ) . equalsIgnoreCase ( \"im2col\" ) ) { val dtype = Nd4j . dataType ( ) ; val xArr = op . inputArguments ( ) [ 0 ] ; val zArr = op . outputArguments ( ) [ 0 ] ; CudaContext context = AtomicAllocator . getInstance ( ) . getFlowController ( ) . prepareAction ( zArr , xArr ) ; if ( extraz . get ( ) == null ) extraz . set ( new PointerPointer ( 32 ) ) ; PointerPointer xShapeHost = extraz . get ( ) . put ( AddressRetriever . retrieveHostPointer ( xArr . shapeInfoDataBuffer ( ) ) , // 0 context . getOldStream ( ) , // 1 AtomicAllocator . getInstance ( ) . getDeviceIdPointer ( ) , // 2 context . getBufferAllocation ( ) , // 3 context . getBufferReduction ( ) , // 4 context . getBufferScalar ( ) , // 5 context . getBufferSpecial ( ) , null , AddressRetriever . retrieveHostPointer ( zArr . shapeInfoDataBuffer ( ) ) ) ; val x = AtomicAllocator . getInstance ( ) . getPointer ( xArr , context ) ; val z = AtomicAllocator . getInstance ( ) . getPointer ( zArr , context ) ; val xShape = AtomicAllocator . getInstance ( ) . getPointer ( xArr . shapeInfoDataBuffer ( ) , context ) ; val zShape = AtomicAllocator . getInstance ( ) . getPointer ( zArr . shapeInfoDataBuffer ( ) , context ) ; double zeroPad = 0.0 ; if ( op . tArgs ( ) != null && op . tArgs ( ) . length > 0 ) { zeroPad = op . tArgs ( ) [ 0 ] ; } val extrass = new double [ ] { op . iArgs ( ) [ 0 ] , op . iArgs ( ) [ 1 ] , op . iArgs ( ) [ 2 ] , op . iArgs ( ) [ 3 ] , op . iArgs ( ) [ 4 ] , op . iArgs ( ) [ 5 ] , op . iArgs ( ) [ 6 ] , op . iArgs ( ) [ 7 ] , op . iArgs ( ) [ 8 ] , zeroPad } ; val extraArgsBuff = Nd4j . getConstantHandler ( ) . getConstantBuffer ( extrass ) ; val extraArgs = AtomicAllocator . getInstance ( ) . getPointer ( extraArgsBuff , context ) ; if ( dtype == DataBuffer . Type . DOUBLE ) { nativeOps . execTransformDouble ( xShapeHost , 37 , ( DoublePointer ) x , ( LongPointer ) xShape , ( DoublePointer ) z , ( LongPointer ) zShape , ( DoublePointer ) extraArgs ) ; } else if ( dtype == DataBuffer . Type . FLOAT ) { nativeOps . execTransformFloat ( xShapeHost , 37 , ( FloatPointer ) x , ( LongPointer ) xShape , ( FloatPointer ) z , ( LongPointer ) zShape , ( FloatPointer ) extraArgs ) ; } else if ( dtype == DataBuffer . Type . HALF ) { nativeOps . execTransformHalf ( xShapeHost , 37 , ( ShortPointer ) x , ( LongPointer ) xShape , ( ShortPointer ) z , ( LongPointer ) zShape , ( ShortPointer ) extraArgs ) ; } //AtomicAllocator.getInstance().getAllocationPoint(zArr).tickDeviceWrite(); AtomicAllocator . getInstance ( ) . getFlowController ( ) . registerAction ( context , zArr , xArr ) ; //Nd4j.getExecutioner().commit(); return ; } else if ( op . opName ( ) . equalsIgnoreCase ( \"col2im\" ) ) { val dtype = Nd4j . dataType ( ) ; val xArr = op . inputArguments ( ) [ 0 ] ; val zArr = op . outputArguments ( ) [ 0 ] ; CudaContext context = AtomicAllocator . getInstance ( ) . getFlowController ( ) . prepareAction ( zArr , xArr ) ; if ( extraz . get ( ) == null ) extraz . set ( new PointerPointer ( 32 ) ) ; PointerPointer xShapeHost = extraz . get ( ) . put ( AddressRetriever . retrieveHostPointer ( xArr . shapeInfoDataBuffer ( ) ) , // 0 context . getOldStream ( ) , // 1 AtomicAllocator . getInstance ( ) . getDeviceIdPointer ( ) , // 2 context . getBufferAllocation ( ) , // 3 context . getBufferReduction ( ) , // 4 context . getBufferScalar ( ) , // 5 context . getBufferSpecial ( ) , null , AddressRetriever . retrieveHostPointer ( zArr . shapeInfoDataBuffer ( ) ) ) ; val x = AtomicAllocator . getInstance ( ) . getPointer ( xArr , context ) ; val z = AtomicAllocator . getInstance ( ) . getPointer ( zArr , context ) ; val xShape = AtomicAllocator . getInstance ( ) . getPointer ( xArr . shapeInfoDataBuffer ( ) , context ) ; val zShape = AtomicAllocator . getInstance ( ) . getPointer ( zArr . shapeInfoDataBuffer ( ) , context ) ; val extrass = new double [ ] { op . iArgs ( ) [ 0 ] , op . iArgs ( ) [ 1 ] , op . iArgs ( ) [ 2 ] , op . iArgs ( ) [ 3 ] , op . iArgs ( ) [ 4 ] , op . iArgs ( ) [ 5 ] , op . iArgs ( ) [ 6 ] , op . iArgs ( ) [ 7 ] } ; val extraArgsBuff = Nd4j . getConstantHandler ( ) . getConstantBuffer ( extrass ) ; val extraArgs = AtomicAllocator . getInstance ( ) . getPointer ( extraArgsBuff , context ) ; if ( dtype == DataBuffer . Type . DOUBLE ) { nativeOps . execTransformDouble ( xShapeHost , 36 , ( DoublePointer ) x , ( LongPointer ) xShape , ( DoublePointer ) z , ( LongPointer ) zShape , ( DoublePointer ) extraArgs ) ; } else if ( dtype == DataBuffer . Type . FLOAT ) { nativeOps . execTransformFloat ( xShapeHost , 36 , ( FloatPointer ) x , ( LongPointer ) xShape , ( FloatPointer ) z , ( LongPointer ) zShape , ( FloatPointer ) extraArgs ) ; } else if ( dtype == DataBuffer . Type . HALF ) { nativeOps . execTransformHalf ( xShapeHost , 36 , ( ShortPointer ) x , ( LongPointer ) xShape , ( ShortPointer ) z , ( LongPointer ) zShape , ( ShortPointer ) extraArgs ) ; } //AtomicAllocator.getInstance().getAllocationPoint(zArr).tickDeviceWrite(); AtomicAllocator . getInstance ( ) . getFlowController ( ) . registerAction ( context , zArr , xArr ) ; //Nd4j.getExecutioner().commit(); return ; } else if ( op . opName ( ) . equalsIgnoreCase ( \"pooling2d\" ) ) { val dtype = Nd4j . dataType ( ) ; val xArr = op . inputArguments ( ) [ 0 ] ; val zArr = op . outputArguments ( ) [ 0 ] ; CudaContext context = AtomicAllocator . getInstance ( ) . getFlowController ( ) . prepareAction ( zArr , xArr ) ; if ( extraz . get ( ) == null ) extraz . set ( new PointerPointer ( 32 ) ) ; PointerPointer xShapeHost = extraz . get ( ) . put ( AddressRetriever . retrieveHostPointer ( xArr . shapeInfoDataBuffer ( ) ) , // 0 context . getOldStream ( ) , // 1 AtomicAllocator . getInstance ( ) . getDeviceIdPointer ( ) , // 2 context . getBufferAllocation ( ) , // 3 context . getBufferReduction ( ) , // 4 context . getBufferScalar ( ) , // 5 context . getBufferSpecial ( ) , null , AddressRetriever . retrieveHostPointer ( zArr . shapeInfoDataBuffer ( ) ) ) ; val x = AtomicAllocator . getInstance ( ) . getPointer ( xArr , context ) ; val z = AtomicAllocator . getInstance ( ) . getPointer ( zArr , context ) ; val xShape = AtomicAllocator . getInstance ( ) . getPointer ( xArr . shapeInfoDataBuffer ( ) , context ) ; val zShape = AtomicAllocator . getInstance ( ) . getPointer ( zArr . shapeInfoDataBuffer ( ) , context ) ; val extrass = new double [ ] { op . iArgs ( ) [ 0 ] , op . iArgs ( ) [ 1 ] , op . iArgs ( ) [ 2 ] , op . iArgs ( ) [ 3 ] , op . iArgs ( ) [ 4 ] , op . iArgs ( ) [ 5 ] , op . iArgs ( ) [ 6 ] , op . iArgs ( ) [ 7 ] , op . iArgs ( ) [ 8 ] } ; val extraArgsBuff = Nd4j . getConstantHandler ( ) . getConstantBuffer ( extrass ) ; val extraArgs = AtomicAllocator . getInstance ( ) . getPointer ( extraArgsBuff , context ) ; if ( dtype == DataBuffer . Type . DOUBLE ) { nativeOps . execTransformDouble ( xShapeHost , 71 , ( DoublePointer ) x , ( LongPointer ) xShape , ( DoublePointer ) z , ( LongPointer ) zShape , ( DoublePointer ) extraArgs ) ; } else if ( dtype == DataBuffer . Type . FLOAT ) { nativeOps . execTransformFloat ( xShapeHost , 71 , ( FloatPointer ) x , ( LongPointer ) xShape , ( FloatPointer ) z , ( LongPointer ) zShape , ( FloatPointer ) extraArgs ) ; } else if ( dtype == DataBuffer . Type . HALF ) { nativeOps . execTransformHalf ( xShapeHost , 71 , ( ShortPointer ) x , ( LongPointer ) xShape , ( ShortPointer ) z , ( LongPointer ) zShape , ( ShortPointer ) extraArgs ) ; } // AtomicAllocator.getInstance().getAllocationPoint(zArr).tickDeviceWrite(); AtomicAllocator . getInstance ( ) . getFlowController ( ) . registerAction ( context , zArr , xArr ) ; //Nd4j.getExecutioner().commit(); return ; } Nd4j . getExecutioner ( ) . commit ( ) ; long st = profilingHookIn ( op ) ; CudaContext context = ( CudaContext ) AtomicAllocator . getInstance ( ) . getDeviceContext ( ) . getContext ( ) ; //AtomicAllocator.getInstance().getFlowController().prepareActionAllWrite(op.outputArguments()); if ( extraz . get ( ) == null ) extraz . set ( new PointerPointer ( 32 ) ) ; PointerPointer extras = extraz . get ( ) . put ( new CudaPointer ( 1 ) , context . getOldStream ( ) , context . getBufferScalar ( ) , context . getBufferReduction ( ) ) ; val outputArgs = op . outputArguments ( ) ; val inputArgs = op . inputArguments ( ) ; if ( outputArgs . length == 0 && ! op . isInplaceCall ( ) ) throw new ND4JIllegalStateException ( \"You can't execute non-inplace CustomOp without outputs being specified\" ) ; val lc = op . opName ( ) . toLowerCase ( ) ; val hash = op . opHash ( ) ; val inputShapes = new PointerPointer <> ( inputArgs . length * 2 ) ; val inputBuffers = new PointerPointer <> ( inputArgs . length * 2 ) ; int cnt = 0 ; for ( val in : inputArgs ) { val hp = AtomicAllocator . getInstance ( ) . getHostPointer ( in . shapeInfoDataBuffer ( ) ) ; inputBuffers . put ( cnt , AtomicAllocator . getInstance ( ) . getHostPointer ( in ) ) ; inputShapes . put ( cnt , hp ) ; val dp = AtomicAllocator . getInstance ( ) . getPointer ( in . shapeInfoDataBuffer ( ) , context ) ; inputBuffers . put ( cnt + inputArgs . length , AtomicAllocator . getInstance ( ) . getPointer ( in , context ) ) ; inputShapes . put ( cnt + inputArgs . length , dp ) ; if ( op . isInplaceCall ( ) ) AtomicAllocator . getInstance ( ) . getAllocationPoint ( in ) . tickHostWrite ( ) ; cnt ++ ; } val outputShapes = new PointerPointer <> ( outputArgs . length * 2 ) ; val outputBuffers = new PointerPointer <> ( outputArgs . length * 2 ) ; cnt = 0 ; for ( val out : outputArgs ) { outputBuffers . put ( cnt , AtomicAllocator . getInstance ( ) . getHostPointer ( out ) ) ; outputShapes . put ( cnt , AtomicAllocator . getInstance ( ) . getHostPointer ( out . shapeInfoDataBuffer ( ) ) ) ; outputBuffers . put ( cnt + outputArgs . length , AtomicAllocator . getInstance ( ) . getPointer ( out , context ) ) ; outputShapes . put ( cnt + outputArgs . length , AtomicAllocator . getInstance ( ) . getPointer ( out . shapeInfoDataBuffer ( ) , context ) ) ; AtomicAllocator . getInstance ( ) . getAllocationPoint ( out ) . tickHostWrite ( ) ; cnt ++ ; } if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) { val tArgs = op . tArgs ( ) . length > 0 ? new FloatPointer ( op . tArgs ( ) . length ) : null ; val iArgs = op . iArgs ( ) . length > 0 ? new LongPointer ( op . iArgs ( ) . length ) : null ; cnt = 0 ; for ( val t : op . tArgs ( ) ) tArgs . put ( cnt ++ , ( float ) t ) ; cnt = 0 ; for ( val i : op . iArgs ( ) ) iArgs . put ( cnt ++ , i ) ; val status = OpStatus . byNumber ( nativeOps . execCustomOpFloat ( extras , hash , inputBuffers , inputShapes , inputArgs . length , outputBuffers , outputShapes , outputArgs . length , tArgs , op . tArgs ( ) . length , iArgs , op . iArgs ( ) . length , op . isInplaceCall ( ) ) ) ; if ( status != OpStatus . ND4J_STATUS_OK ) throw new ND4JIllegalStateException ( \"Op execution failed: \" + status ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) { val tArgs = op . tArgs ( ) . length > 0 ? new DoublePointer ( op . tArgs ( ) . length ) : null ; val iArgs = op . iArgs ( ) . length > 0 ? new LongPointer ( op . iArgs ( ) . length ) : null ; cnt = 0 ; for ( val t : op . tArgs ( ) ) tArgs . put ( cnt ++ , t ) ; for ( val i : op . iArgs ( ) ) iArgs . put ( cnt ++ , i ) ; val status = OpStatus . byNumber ( nativeOps . execCustomOpDouble ( extras , hash , inputBuffers , inputShapes , inputArgs . length , outputBuffers , outputShapes , outputArgs . length , tArgs , op . tArgs ( ) . length , iArgs , op . iArgs ( ) . length , op . isInplaceCall ( ) ) ) ; if ( status != OpStatus . ND4J_STATUS_OK ) throw new ND4JIllegalStateException ( \"Op execution failed: \" + status ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . HALF ) { val tArgs = op . tArgs ( ) . length > 0 ? new ShortPointer ( op . tArgs ( ) . length ) : null ; val iArgs = op . iArgs ( ) . length > 0 ? new LongPointer ( op . iArgs ( ) . length ) : null ; cnt = 0 ; for ( val t : op . tArgs ( ) ) tArgs . put ( cnt ++ , ArrayUtil . toHalf ( ( float ) t ) ) ; cnt = 0 ; for ( val i : op . iArgs ( ) ) iArgs . put ( cnt ++ , i ) ; val status = OpStatus . byNumber ( nativeOps . execCustomOpHalf ( extras , hash , inputBuffers , inputShapes , inputArgs . length , outputBuffers , outputShapes , outputArgs . length , tArgs , op . tArgs ( ) . length , iArgs , op . iArgs ( ) . length , op . isInplaceCall ( ) ) ) ; if ( status != OpStatus . ND4J_STATUS_OK ) throw new ND4JIllegalStateException ( \"Op execution failed: \" + status ) ; } //AtomicAllocator.getInstance().getFlowController().prepareActionAllWrite(op.outputArguments()); profilingHookOut ( op , st ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy from the given from buffer to the to buffer at the specified offsets and strides [CODESPLIT] public static void copyAtStride ( int n , BufferType bufferType , ByteBuffer from , int fromOffset , int fromStride , ByteBuffer to , int toOffset , int toStride ) { // TODO: implement shape copy for cases where stride == 1 ByteBuffer fromView = from ; ByteBuffer toView = to ; fromView . order ( ByteOrder . nativeOrder ( ) ) ; toView . order ( ByteOrder . nativeOrder ( ) ) ; switch ( bufferType ) { case INT : IntBuffer fromInt = fromView . asIntBuffer ( ) ; IntBuffer toInt = toView . asIntBuffer ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int put = fromInt . get ( fromOffset + i * fromStride ) ; toInt . put ( toOffset + i * toStride , put ) ; } break ; case FLOAT : FloatBuffer fromFloat = fromView . asFloatBuffer ( ) ; FloatBuffer toFloat = toView . asFloatBuffer ( ) ; for ( int i = 0 ; i < n ; i ++ ) { float put = fromFloat . get ( fromOffset + i * fromStride ) ; toFloat . put ( toOffset + i * toStride , put ) ; } break ; case DOUBLE : DoubleBuffer fromDouble = fromView . asDoubleBuffer ( ) ; DoubleBuffer toDouble = toView . asDoubleBuffer ( ) ; for ( int i = 0 ; i < n ; i ++ ) { toDouble . put ( toOffset + i * toStride , fromDouble . get ( fromOffset + i * fromStride ) ) ; } break ; default : throw new IllegalArgumentException ( \"Only floats and double supported\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start a server based on the given subscriber . Note that for the port to start the server on you should set the statusServerPortField on the subscriber either manually or via command line . The server defaults to port 9000 . [CODESPLIT] public static Server startServer ( StatusStorage statusStorage , int statusServerPort ) { log . info ( \"Starting server on port \" + statusServerPort ) ; RoutingDsl dsl = new RoutingDsl ( ) ; dsl . GET ( \"/ids/\" ) . routeTo ( new F . Function0 < Result > ( ) { @ Override public Result apply ( ) throws Throwable { List < Integer > ids = statusStorage . ids ( ) ; return ok ( toJson ( ids ) ) ; } } ) ; dsl . GET ( \"/state/:id\" ) . routeTo ( new F . Function < String , Result > ( ) { @ Override public Result apply ( String id ) throws Throwable { return ok ( toJson ( statusStorage . getState ( Integer . parseInt ( id ) ) ) ) ; } } ) ; dsl . GET ( \"/opType/:id\" ) . routeTo ( new F . Function < String , Result > ( ) { @ Override public Result apply ( String id ) throws Throwable { return ok ( toJson ( ServerTypeJson . builder ( ) . type ( statusStorage . getState ( Integer . parseInt ( id ) ) . serverType ( ) ) ) ) ; } } ) ; dsl . GET ( \"/started/:id\" ) . routeTo ( new F . Function < String , Result > ( ) { @ Override public Result apply ( String id ) throws Throwable { return statusStorage . getState ( Integer . parseInt ( id ) ) . isMaster ( ) ? ok ( toJson ( MasterStatus . builder ( ) . master ( statusStorage . getState ( Integer . parseInt ( id ) ) . getServerState ( ) ) //note here that a responder is is + 1 . responder ( statusStorage . getState ( Integer . parseInt ( id ) + 1 ) . getServerState ( ) ) . responderN ( statusStorage . getState ( Integer . parseInt ( id ) ) . getTotalUpdates ( ) ) . build ( ) ) ) : ok ( toJson ( SlaveStatus . builder ( ) . slave ( statusStorage . getState ( Integer . parseInt ( id ) ) . serverType ( ) ) . build ( ) ) ) ; } } ) ; dsl . GET ( \"/connectioninfo/:id\" ) . routeTo ( new F . Function < String , Result > ( ) { @ Override public Result apply ( String id ) throws Throwable { return ok ( toJson ( statusStorage . getState ( Integer . parseInt ( id ) ) . getConnectionInfo ( ) ) ) ; } } ) ; dsl . POST ( \"/updatestatus/:id\" ) . routeTo ( new F . Function < String , Result > ( ) { @ Override public Result apply ( String id ) throws Throwable { SubscriberState subscriberState = Json . fromJson ( request ( ) . body ( ) . asJson ( ) , SubscriberState . class ) ; statusStorage . updateState ( subscriberState ) ; return ok ( toJson ( subscriberState ) ) ; } } ) ; Server server = Server . forRouter ( dsl . build ( ) , Mode . PROD , statusServerPort ) ; return server ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method moves specified dataBuffer to CUDA constant memory space . [CODESPLIT] @ Override public synchronized long moveToConstantSpace ( DataBuffer dataBuffer ) { // now, we move things to constant memory Integer deviceId = AtomicAllocator . getInstance ( ) . getDeviceId ( ) ; ensureMaps ( deviceId ) ; AllocationPoint point = AtomicAllocator . getInstance ( ) . getAllocationPoint ( dataBuffer ) ; long requiredMemoryBytes = AllocationUtils . getRequiredMemory ( point . getShape ( ) ) ; //logger.info(\"shape: \" + point.getShape()); // and release device memory :) long currentOffset = constantOffsets . get ( deviceId ) . get ( ) ; CudaContext context = ( CudaContext ) AtomicAllocator . getInstance ( ) . getDeviceContext ( ) . getContext ( ) ; if ( currentOffset + requiredMemoryBytes >= MAX_CONSTANT_LENGTH || requiredMemoryBytes > MAX_BUFFER_LENGTH ) { if ( point . getAllocationStatus ( ) == AllocationStatus . HOST && CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getMemoryModel ( ) == Configuration . MemoryModel . DELAYED ) { AtomicAllocator . getInstance ( ) . getMemoryHandler ( ) . alloc ( AllocationStatus . DEVICE , point , point . getShape ( ) , false ) ; } val profD = PerformanceTracker . getInstance ( ) . helperStartTransaction ( ) ; if ( NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . memcpyAsync ( point . getPointers ( ) . getDevicePointer ( ) , point . getPointers ( ) . getHostPointer ( ) , requiredMemoryBytes , 1 , context . getSpecialStream ( ) ) == 0 ) { throw new ND4JIllegalStateException ( \"memcpyAsync failed\" ) ; } flowController . commitTransfer ( context . getSpecialStream ( ) ) ; PerformanceTracker . getInstance ( ) . helperRegisterTransaction ( point . getDeviceId ( ) , profD , point . getNumberOfBytes ( ) , MemcpyDirection . HOST_TO_DEVICE ) ; point . setConstant ( true ) ; point . tickDeviceWrite ( ) ; point . tickHostRead ( ) ; point . setDeviceId ( deviceId ) ; protector . persistDataBuffer ( dataBuffer ) ; return 0 ; } long bytes = requiredMemoryBytes ; // hack for misalignment avoidance for 16bit data opType if ( dataBuffer . dataType ( ) == DataBuffer . Type . HALF ) { if ( bytes % 4 != 0 ) { bytes += 2 ; } } else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE || dataBuffer . dataType ( ) == DataBuffer . Type . LONG ) { // for double data opType, we must be assured, that all DOUBLE pointers are starting from even addresses, to avoid banks spills long div = bytes / 4 ; if ( div % 2 != 0 ) bytes += 4 ; // for possible changes of dtype in the same jvm, we skip few bytes in constant memory div = currentOffset / 4 ; while ( div % 2 != 0 ) { currentOffset = constantOffsets . get ( deviceId ) . addAndGet ( 4 ) ; div = currentOffset / 4 ; // just break out, if we're stepped beyond constant memory space if ( currentOffset > MAX_CONSTANT_LENGTH ) break ; } } currentOffset = constantOffsets . get ( deviceId ) . getAndAdd ( bytes ) ; if ( currentOffset >= MAX_CONSTANT_LENGTH ) { if ( point . getAllocationStatus ( ) == AllocationStatus . HOST && CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getMemoryModel ( ) == Configuration . MemoryModel . DELAYED ) { AtomicAllocator . getInstance ( ) . getMemoryHandler ( ) . alloc ( AllocationStatus . DEVICE , point , point . getShape ( ) , false ) ; } val profD = PerformanceTracker . getInstance ( ) . helperStartTransaction ( ) ; if ( NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . memcpyAsync ( point . getPointers ( ) . getDevicePointer ( ) , point . getPointers ( ) . getHostPointer ( ) , requiredMemoryBytes , 1 , context . getSpecialStream ( ) ) == 0 ) { throw new ND4JIllegalStateException ( \"memcpyAsync failed\" ) ; } flowController . commitTransfer ( context . getSpecialStream ( ) ) ; PerformanceTracker . getInstance ( ) . helperRegisterTransaction ( point . getDeviceId ( ) , profD , point . getNumberOfBytes ( ) , MemcpyDirection . HOST_TO_DEVICE ) ; point . setConstant ( true ) ; point . tickDeviceWrite ( ) ; point . tickHostRead ( ) ; point . setDeviceId ( deviceId ) ; protector . persistDataBuffer ( dataBuffer ) ; return 0 ; } NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . memcpyConstantAsync ( currentOffset , point . getPointers ( ) . getHostPointer ( ) , requiredMemoryBytes , 1 , context . getSpecialStream ( ) ) ; flowController . commitTransfer ( context . getSpecialStream ( ) ) ; long cAddr = deviceAddresses . get ( deviceId ) . address ( ) + currentOffset ; //if (resetHappened) //    logger.info(\"copying to constant: {}, bufferLength: {}, bufferDtype: {}, currentOffset: {}, currentAddres: {}\", requiredMemoryBytes, dataBuffer.length(), dataBuffer.dataType(), currentOffset, cAddr); point . setAllocationStatus ( AllocationStatus . CONSTANT ) ; point . getPointers ( ) . setDevicePointer ( new CudaPointer ( cAddr ) ) ; point . setConstant ( true ) ; point . tickDeviceWrite ( ) ; point . setDeviceId ( deviceId ) ; point . tickHostRead ( ) ; protector . persistDataBuffer ( dataBuffer ) ; return cAddr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PLEASE NOTE : This method implementation is hardware - dependant . PLEASE NOTE : This method does NOT allow concurrent use of any array [CODESPLIT] @ Override public DataBuffer relocateConstantSpace ( DataBuffer dataBuffer ) { // we always assume that data is sync, and valid on host side Integer deviceId = AtomicAllocator . getInstance ( ) . getDeviceId ( ) ; ensureMaps ( deviceId ) ; if ( dataBuffer instanceof CudaIntDataBuffer ) { int [ ] data = dataBuffer . asInt ( ) ; return getConstantBuffer ( data ) ; } else if ( dataBuffer instanceof CudaFloatDataBuffer ) { float [ ] data = dataBuffer . asFloat ( ) ; return getConstantBuffer ( data ) ; } else if ( dataBuffer instanceof CudaDoubleDataBuffer ) { double [ ] data = dataBuffer . asDouble ( ) ; return getConstantBuffer ( data ) ; } else if ( dataBuffer instanceof CudaHalfDataBuffer ) { float [ ] data = dataBuffer . asFloat ( ) ; return getConstantBuffer ( data ) ; } else if ( dataBuffer instanceof CudaLongDataBuffer ) { long [ ] data = dataBuffer . asLong ( ) ; return getConstantBuffer ( data ) ; } throw new IllegalStateException ( \"Unknown CudaDataBuffer opType\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns DataBuffer with contant equal to input array . [CODESPLIT] @ Override public DataBuffer getConstantBuffer ( float [ ] array ) { //   logger.info(\"getConstantBuffer(float[]) called\"); ArrayDescriptor descriptor = new ArrayDescriptor ( array ) ; Integer deviceId = AtomicAllocator . getInstance ( ) . getDeviceId ( ) ; ensureMaps ( deviceId ) ; if ( ! buffersCache . get ( deviceId ) . containsKey ( descriptor ) ) { // we create new databuffer //logger.info(\"Creating new constant buffer...\"); DataBuffer buffer = Nd4j . createBufferDetached ( array ) ; if ( constantOffsets . get ( deviceId ) . get ( ) + ( array . length * Nd4j . sizeOfDataType ( ) ) < MAX_CONSTANT_LENGTH ) { buffer . setConstant ( true ) ; // now we move data to constant memory, and keep happy moveToConstantSpace ( buffer ) ; buffersCache . get ( deviceId ) . put ( descriptor , buffer ) ; bytes . addAndGet ( array . length * Nd4j . sizeOfDataType ( ) ) ; } return buffer ; } // else logger.info(\"Reusing constant buffer...\"); return buffersCache . get ( deviceId ) . get ( descriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on the passed in array compute the shape offsets and strides for the given indexes @param indexes the indexes to compute this based on [CODESPLIT] public void exec ( INDArrayIndex ... indexes ) { val shape = arr . shape ( ) ; if ( arr . isSparse ( ) ) { resolveFixedDimensionsCOO ( indexes ) ; } // Check that given point indexes are not out of bounds for ( int i = 0 ; i < indexes . length ; i ++ ) { INDArrayIndex idx = indexes [ i ] ; // On vectors, the first dimension can be ignored when indexing them with a single point index if ( idx instanceof PointIndex && ( arr . isVector ( ) && indexes . length == 1 ? idx . current ( ) >= shape [ i + 1 ] : idx . current ( ) >= shape [ i ] ) ) { throw new IllegalArgumentException ( \"INDArrayIndex[\" + i + \"] is out of bounds (value: \" + idx . current ( ) + \")\" ) ; } } indexes = NDArrayIndex . resolve ( arr . shapeInfoDataBuffer ( ) , indexes ) ; if ( tryShortCircuit ( indexes ) ) { return ; } int numIntervals = 0 ; //number of new axes dimensions to prepend to the beginning int newAxesPrepend = 0 ; //whether we have encountered an all so far boolean encounteredAll = false ; int lastPrependIndex = - 1 ; List < Integer > oneDimensionWithAllEncountered = new ArrayList <> ( ) ; //accumulate the results List < Long > accumShape = new ArrayList <> ( ) ; List < Long > accumStrides = new ArrayList <> ( ) ; List < Long > accumOffsets = new ArrayList <> ( ) ; List < Long > intervalStrides = new ArrayList <> ( ) ; //collect the indexes of the points that get removed //for point purposes //this will be used to compute the offset //for the new array List < Long > pointStrides = new ArrayList <> ( ) ; List < Long > pointOffsets = new ArrayList <> ( ) ; int numPointIndexes = 0 ; //bump number to read from the shape int shapeIndex = 0 ; //stride index to read strides from the array int strideIndex = 0 ; //list of indexes to prepend to for new axes //if all is encountered List < Integer > prependNewAxes = new ArrayList <> ( ) ; for ( int i = 0 ; i < indexes . length ; i ++ ) { INDArrayIndex idx = indexes [ i ] ; if ( idx instanceof NDArrayIndexAll ) { encounteredAll = true ; if ( i < arr . rank ( ) && arr . size ( i ) == 1 ) oneDimensionWithAllEncountered . add ( i ) ; //different dimension from new axis (look for new axis dimensions //at at the beginning. track when the last new axis is encountered. if ( newAxesPrepend > 0 && lastPrependIndex < 0 ) { lastPrependIndex = i - 1 ; } } //point: do nothing but move the shape counter //also move the stride counter if ( idx instanceof PointIndex ) { pointOffsets . add ( idx . offset ( ) ) ; pointStrides . add ( ( long ) arr . stride ( strideIndex ) ) ; numPointIndexes ++ ; shapeIndex ++ ; strideIndex ++ ; //different dimension from new axis (look for new axis dimensions //at at the beginning. track when the last new axis is encountered. if ( newAxesPrepend > 0 && lastPrependIndex < 0 ) { lastPrependIndex = i - 1 ; } continue ; } //new axes encountered, need to track whether to prepend or //to set the new axis in the middle else if ( idx instanceof NewAxis ) { //prepend the new axes at different indexes accumShape . add ( 1L ) ; accumOffsets . add ( 0L ) ; accumStrides . add ( 0L ) ; prependNewAxes . add ( i ) ; continue ; } //points and intervals both have a direct desired length else if ( idx instanceof IntervalIndex && ! ( idx instanceof NDArrayIndexAll ) || idx instanceof SpecifiedIndex ) { if ( idx instanceof IntervalIndex ) { accumStrides . add ( arr . stride ( strideIndex ) * idx . stride ( ) ) ; //used in computing an adjusted offset for the augmented strides intervalStrides . add ( idx . stride ( ) ) ; numIntervals ++ ; } else accumStrides . add ( ( long ) arr . stride ( strideIndex ) ) ; accumShape . add ( idx . length ( ) ) ; //the stride stays the same //add the offset for the index if ( idx instanceof IntervalIndex ) { accumOffsets . add ( idx . offset ( ) ) ; } else accumOffsets . add ( idx . offset ( ) ) ; shapeIndex ++ ; strideIndex ++ ; //different dimension from new axis (look for new axis dimensions //at at the beginning. track when the last new axis is encountered. if ( newAxesPrepend > 0 && lastPrependIndex < 0 ) { lastPrependIndex = i - 1 ; } continue ; } //add the shape and stride //based on the original stride/shape accumShape . add ( ( long ) shape [ shapeIndex ++ ] ) ; //account for erroneous strides from dimensions of size 1 //move the stride index if its one and fill it in at the bottom accumStrides . add ( ( long ) arr . stride ( strideIndex ++ ) ) ; //default offsets are zero accumOffsets . add ( idx . offset ( ) ) ; } //fill in missing strides and shapes while ( shapeIndex < shape . length ) { //scalar, should be 1 x 1 rather than the number of columns in the vector if ( Shape . isVector ( shape ) ) { accumShape . add ( 1L ) ; shapeIndex ++ ; } else accumShape . add ( ( long ) shape [ shapeIndex ++ ] ) ; } //fill in the rest of the offsets with zero int delta = ( shape . length <= 2 ? shape . length : shape . length - numPointIndexes ) ; boolean needsFilledIn = accumShape . size ( ) != accumStrides . size ( ) && accumOffsets . size ( ) != accumShape . size ( ) ; while ( accumOffsets . size ( ) < delta && needsFilledIn ) accumOffsets . add ( 0L ) ; while ( accumShape . size ( ) < 2 ) { if ( Shape . isRowVectorShape ( arr . shape ( ) ) ) accumShape . add ( 0 , 1L ) ; else accumShape . add ( 1L ) ; } while ( strideIndex < accumShape . size ( ) ) { accumStrides . add ( ( long ) arr . stride ( strideIndex ++ ) ) ; } /**\n         * For each dimension\n         * where we want to prepend a dimension\n         * we need to add it at the index such that\n         * we account for the offset of the number of indexes\n         * added up to that point.\n         *\n         * We do this by doing an offset\n         * for each item added \"so far\"\n         *\n         * Note that we also have an offset of - 1\n         * because we want to prepend to the given index.\n         *\n         * When prepend new axes for in the middle is triggered\n         * i is already > 0\n         */ /* int numAdded = 0;\n        for (int i = 0; i < prependNewAxes.size(); i++) {\n            accumShape.add(prependNewAxes.get(i) - numAdded, 1L);\n            //stride for the new axis is zero\n            accumStrides.add(prependNewAxes.get(i) - numAdded, 0L);\n            numAdded++;\n        }\n        for (int i = 0; i < newAxesPrepend; i++) {\n            prependNewAxes.add(0, i);\n        }\n\n        prependAxis = Ints.toArray(prependNewAxes);\n*/ /**\n         * Need to post process strides and offsets\n         * for trailing ones here\n         */ //prune off extra zeros for trailing and leading ones int trailingZeroRemove = accumOffsets . size ( ) - 1 ; while ( accumOffsets . size ( ) > accumShape . size ( ) ) { if ( accumOffsets . get ( trailingZeroRemove ) == 0 ) accumOffsets . remove ( accumOffsets . size ( ) - 1 ) ; trailingZeroRemove -- ; } if ( accumStrides . size ( ) < accumOffsets . size ( ) ) accumStrides . addAll ( pointStrides ) ; while ( accumOffsets . size ( ) < accumShape . size ( ) ) { if ( Shape . isRowVectorShape ( arr . shape ( ) ) ) accumOffsets . add ( 0 , 0L ) ; else accumOffsets . add ( 0L ) ; } if ( Shape . isMatrix ( shape ) && indexes [ 0 ] instanceof PointIndex && indexes [ 1 ] instanceof NDArrayIndexAll ) { Collections . reverse ( accumShape ) ; } if ( arr . isMatrix ( ) && indexes [ 0 ] instanceof PointIndex && indexes [ 1 ] instanceof IntervalIndex ) { this . shapes = new long [ 2 ] ; shapes [ 0 ] = 1 ; IntervalIndex idx = ( IntervalIndex ) indexes [ 1 ] ; shapes [ 1 ] = idx . length ( ) ; } else this . shapes = Longs . toArray ( accumShape ) ; boolean isColumnVector = Shape . isColumnVectorShape ( this . shapes ) ; //finally fill in teh rest of the strides if any are left over while ( accumStrides . size ( ) < accumOffsets . size ( ) ) { if ( ! isColumnVector ) accumStrides . add ( 0 , ( long ) arr . elementStride ( ) ) ; else accumStrides . add ( ( long ) arr . elementStride ( ) ) ; } this . strides = Longs . toArray ( accumStrides ) ; this . offsets = Longs . toArray ( accumOffsets ) ; //compute point offsets differently /**\n         * We need to prepend the strides for the point indexes\n         * such that the point index offsets are counted.\n         * Note here that we only use point strides\n         * when points strides isn't empty.\n         * When point strides is empty, this is\n         * because a point index was encountered\n         * but it was the lead index and therefore should\n         * not be counted with the offset.\n         *\n         *\n         * Another thing of note here is that the strides\n         * and offsets should line up such that the point\n         * and stride match up.\n         */ if ( numPointIndexes > 0 && ! pointStrides . isEmpty ( ) ) { //append to the end for tensors if ( newAxesPrepend >= 1 ) { while ( pointStrides . size ( ) < accumOffsets . size ( ) ) { pointStrides . add ( 1L ) ; } //identify in the original accumulate strides //where zero was set and emulate the //same structure in the point strides for ( int i = 0 ; i < accumStrides . size ( ) ; i ++ ) { if ( accumStrides . get ( i ) == 0 && ! ( indexes [ i ] instanceof NewAxis ) && lastPrependIndex <= 0 ) pointStrides . set ( i , 0L ) ; } } //prepend any missing offsets where relevant for the dot product //note here we are using the point offsets and strides //for computing the offset //the point of a point index is to drop a dimension //and index in to a particular offset while ( pointOffsets . size ( ) < pointStrides . size ( ) ) { pointOffsets . add ( 0L ) ; } //special case where offsets aren't caught if ( arr . isRowVector ( ) && ! intervalStrides . isEmpty ( ) && pointOffsets . get ( 0 ) == 0 && ! ( indexes [ 1 ] instanceof IntervalIndex ) ) this . offset = indexes [ 1 ] . offset ( ) ; else this . offset = ArrayUtil . dotProductLong2 ( pointOffsets , pointStrides ) ; } else { this . offset = 0 ; } if ( numIntervals > 0 && arr . rank ( ) > 2 ) { if ( encounteredAll && arr . size ( 0 ) != 1 || indexes [ 0 ] instanceof PointIndex ) // FIXME: LONG this . offset += ArrayUtil . dotProductLong2 ( accumOffsets , accumStrides ) ; else // FIXME: LONG this . offset += ArrayUtil . dotProductLong2 ( accumOffsets , accumStrides ) ; } else if ( numIntervals > 0 && anyHaveStrideOne ( indexes ) ) this . offset += ArrayUtil . calcOffsetLong2 ( accumShape , accumOffsets , accumStrides ) ; else this . offset += ArrayUtil . calcOffsetLong2 ( accumShape , accumOffsets , accumStrides ) / Math . max ( 1 , numIntervals ) ; //collapse singular dimensions with specified index List < Integer > removeShape = new ArrayList <> ( ) ; for ( int i = 0 ; i < Math . min ( this . shapes . length , indexes . length ) ; i ++ ) { if ( this . shapes [ i ] == 1 && indexes [ i ] instanceof SpecifiedIndex ) { removeShape . add ( i ) ; } } if ( ! removeShape . isEmpty ( ) ) { List < Long > newShape = new ArrayList <> ( ) ; List < Long > newStrides = new ArrayList <> ( ) ; for ( int i = 0 ; i < this . shapes . length ; i ++ ) { if ( ! removeShape . contains ( i ) ) { newShape . add ( this . shapes [ i ] ) ; newStrides . add ( this . strides [ i ] ) ; } } this . shapes = Longs . toArray ( newShape ) ; this . strides = Longs . toArray ( newStrides ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a kafka connection uri [CODESPLIT] public String kafkaUri ( ) { return String . format ( \"kafka://%s?topic=%s&groupId=%s&zookeeperHost=%s&zookeeperPort=%d&serializerClass=%s&keySerializerClass=%s\" , kafkaBrokerList , topicName , groupId , zookeeperHost , zookeeperPort , StringEncoder . class . getName ( ) , StringEncoder . class . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cosine similarity [CODESPLIT] public static double cosineSim ( @ NonNull INDArray d1 , @ NonNull INDArray d2 ) { return Nd4j . getExecutioner ( ) . execAndReturn ( new CosineSimilarity ( d1 , d2 , d1 . length ( ) ) ) . getFinalResult ( ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atan2 operation new INDArray instance will be returned Note the order of x and y parameters is opposite to that of java . lang . Math . atan2 [CODESPLIT] public static INDArray atan2 ( @ NonNull INDArray x , @ NonNull INDArray y ) { return Nd4j . getExecutioner ( ) . execAndReturn ( new OldAtan2Op ( x , y , Nd4j . createUninitialized ( x . shape ( ) , x . ordering ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ceiling function [CODESPLIT] public static INDArray ceiling ( INDArray ndArray , boolean copyOnOps ) { return exec ( copyOnOps ? new Ceil ( ndArray , ndArray . dup ( ) ) : new Ceil ( ndArray , ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sin function [CODESPLIT] public static INDArray sin ( INDArray in , boolean copy ) { return Nd4j . getExecutioner ( ) . execAndReturn ( new Sin ( ( copy ? in . dup ( ) : in ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sin function [CODESPLIT] public static INDArray atanh ( INDArray in , boolean copy ) { return Nd4j . getExecutioner ( ) . execAndReturn ( new ATanh ( ( copy ? in . dup ( ) : in ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sinh function [CODESPLIT] public static INDArray sinh ( INDArray in , boolean copy ) { return Nd4j . getExecutioner ( ) . execAndReturn ( new Sinh ( ( copy ? in . dup ( ) : in ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hard tanh [CODESPLIT] public static INDArray hardTanh ( INDArray ndArray , boolean dup ) { return exec ( dup ? new HardTanh ( ndArray , ndArray . dup ( ) ) : new HardTanh ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hard tanh [CODESPLIT] public static INDArray hardTanhDerivative ( INDArray ndArray , boolean dup ) { return exec ( dup ? new HardTanhDerivative ( ndArray , ndArray . dup ( ) ) : new HardTanhDerivative ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Element - wise power function - x^y performed element - wise [CODESPLIT] public static INDArray pow ( INDArray ndArray , INDArray power , boolean dup ) { INDArray result = ( dup ? Nd4j . create ( ndArray . shape ( ) , ndArray . ordering ( ) ) : ndArray ) ; return exec ( new Pow ( ndArray , power , result , ndArray . length ( ) , 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log on arbitrary base [CODESPLIT] public static INDArray log ( INDArray ndArray , double base , boolean duplicate ) { return Nd4j . getExecutioner ( ) . exec ( new LogX ( duplicate ? ndArray . dup ( ndArray . ordering ( ) ) : ndArray , base ) ) . z ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Eps function [CODESPLIT] public static INDArray lessThanOrEqual ( INDArray first , INDArray ndArray , boolean dup ) { return exec ( dup ? new OldLessThanOrEqual ( first . dup ( ) , ndArray ) : new OldLessThanOrEqual ( first , ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Eps function [CODESPLIT] public static INDArray greaterThanOrEqual ( INDArray first , INDArray ndArray , boolean dup ) { return exec ( dup ? new OldGreaterThanOrEqual ( first . dup ( ) , ndArray ) : new OldGreaterThanOrEqual ( first , ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Eps function [CODESPLIT] public static INDArray eps ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Eps ( ndArray . dup ( ) ) : new Eps ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maximum function with a scalar [CODESPLIT] public static INDArray max ( INDArray ndArray , double k , boolean dup ) { return exec ( dup ? new ScalarMax ( ndArray . dup ( ) , k ) : new ScalarMax ( ndArray , k ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Element wise maximum function between 2 INDArrays [CODESPLIT] public static INDArray max ( INDArray first , INDArray second , boolean dup ) { if ( dup ) { first = first . dup ( ) ; } return exec ( new OldMax ( second , first , first , first . length ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Minimum function with a scalar [CODESPLIT] public static INDArray min ( INDArray ndArray , double k , boolean dup ) { return exec ( dup ? new ScalarMin ( ndArray . dup ( ) , k ) : new ScalarMin ( ndArray , k ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Element wise minimum function between 2 INDArrays [CODESPLIT] public static INDArray min ( INDArray first , INDArray second , boolean dup ) { if ( dup ) { first = first . dup ( ) ; } return exec ( new OldMin ( second , first , first , first . length ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stabilize to be within a range of k [CODESPLIT] public static INDArray stabilize ( INDArray ndArray , double k , boolean dup ) { return exec ( dup ? new Stabilize ( ndArray , ndArray . dup ( ) , k ) : new Stabilize ( ndArray , k ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Abs function [CODESPLIT] public static INDArray abs ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Abs ( ndArray , ndArray . dup ( ) ) : new Abs ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exp function [CODESPLIT] public static INDArray exp ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Exp ( ndArray , ndArray . dup ( ) ) : new Exp ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Elementwise exponential - 1 function [CODESPLIT] public static INDArray expm1 ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Expm1 ( ndArray , ndArray . dup ( ) ) : new Expm1 ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identity function [CODESPLIT] public static INDArray identity ( INDArray ndArray , boolean dup ) { return exec ( dup ? new OldIdentity ( ndArray , ndArray . dup ( ) ) : new OldIdentity ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sqrt function [CODESPLIT] public static INDArray sqrt ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Sqrt ( ndArray , ndArray . dup ( ) ) : new Sqrt ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tanh function [CODESPLIT] public static INDArray tanh ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Tanh ( ndArray , ndArray . dup ( ) ) : new Tanh ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log function [CODESPLIT] public static INDArray log ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Log ( ndArray , ndArray . dup ( ) ) : new Log ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log of x + 1 function [CODESPLIT] public static INDArray log1p ( INDArray ndArray , boolean dup ) { return exec ( dup ? new Log1p ( ndArray , ndArray . dup ( ) ) : new Log1p ( ndArray ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply the given elementwise op [CODESPLIT] private static INDArray exec ( ScalarOp op ) { if ( op . x ( ) . isCleanedUp ( ) ) throw new IllegalStateException ( \"NDArray already freed\" ) ; return Nd4j . getExecutioner ( ) . exec ( op ) . z ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply the given elementwise op [CODESPLIT] private static INDArray exec ( TransformOp op ) { if ( op . x ( ) . isCleanedUp ( ) ) throw new IllegalStateException ( \"NDArray already freed\" ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( op ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Raises a square matrix to a power <i > n< / i > which can be positive negative or zero . The behavior is similar to the numpy matrix_power () function . The algorithm uses repeated squarings to minimize the number of mmul () operations needed <p > If <i > n< / i > is zero the identity matrix is returned . < / p > <p > If <i > n< / i > is negative the matrix is inverted and raised to the abs ( n ) power . < / p > [CODESPLIT] public static INDArray mpow ( INDArray in , int n , boolean dup ) { assert in . rows ( ) == in . columns ( ) ; if ( n == 0 ) { if ( dup ) return Nd4j . eye ( in . rows ( ) ) ; else return in . assign ( Nd4j . eye ( in . rows ( ) ) ) ; } INDArray temp ; if ( n < 0 ) { temp = InvertMatrix . invert ( in , ! dup ) ; n = - n ; } else temp = in . dup ( ) ; INDArray result = temp . dup ( ) ; if ( n < 4 ) { for ( int i = 1 ; i < n ; i ++ ) { result . mmuli ( temp ) ; } if ( dup ) return result ; else return in . assign ( result ) ; } else { // lets try to optimize by squaring itself a bunch of times int squares = ( int ) ( Math . log ( n ) / Math . log ( 2.0 ) ) ; for ( int i = 0 ; i < squares ; i ++ ) result = result . mmul ( result ) ; int diff = ( int ) Math . round ( n - Math . pow ( 2.0 , squares ) ) ; for ( int i = 0 ; i < diff ; i ++ ) result . mmuli ( temp ) ; if ( dup ) return result ; else return in . assign ( result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare the boundaries for processing [CODESPLIT] public static INDArray [ ] prepareBounds ( INDArray bounds , INDArray x ) { return new INDArray [ ] { Nd4j . valueArrayOf ( x . shape ( ) , bounds . getDouble ( 0 ) ) , Nd4j . valueArrayOf ( x . shape ( ) , bounds . getDouble ( 1 ) ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adjust final scheme to presence of bounds [CODESPLIT] public static INDArray [ ] adjustSchemeToBounds ( INDArray x , INDArray h , int numSteps , INDArray lowerBound , INDArray upperBound ) { INDArray oneSided = Nd4j . onesLike ( h ) ; if ( and ( lowerBound . eq ( Double . NEGATIVE_INFINITY ) , upperBound . eq ( Double . POSITIVE_INFINITY ) ) . sumNumber ( ) . doubleValue ( ) > 0 ) { return new INDArray [ ] { h , oneSided } ; } INDArray hTotal = h . mul ( numSteps ) ; INDArray hAdjusted = h . dup ( ) ; INDArray lowerDist = x . sub ( lowerBound ) ; INDArray upperBound2 = upperBound . sub ( x ) ; INDArray central = and ( greaterThanOrEqual ( lowerDist , hTotal ) , greaterThanOrEqual ( upperBound2 , hTotal ) ) ; INDArray forward = and ( greaterThanOrEqual ( upperBound , lowerDist ) , not ( central ) ) ; hAdjusted . put ( forward , min ( h . get ( forward ) , upperBound2 . get ( forward ) . mul ( 0.5 ) . divi ( numSteps ) ) ) ; oneSided . put ( forward , Nd4j . scalar ( 1.0 ) ) ; INDArray backward = and ( upperBound2 . lt ( lowerBound ) , not ( central ) ) ; hAdjusted . put ( backward , min ( h . get ( backward ) , lowerDist . get ( backward ) . mul ( 0.5 ) . divi ( numSteps ) ) ) ; oneSided . put ( backward , Nd4j . scalar ( 1.0 ) ) ; INDArray minDist = min ( upperBound2 , lowerDist ) . divi ( numSteps ) ; INDArray adjustedCentral = and ( not ( central ) , lessThanOrEqual ( abs ( hAdjusted ) , minDist ) ) ; hAdjusted . put ( adjustedCentral , minDist . get ( adjustedCentral ) ) ; oneSided . put ( adjustedCentral , Nd4j . scalar ( 0.0 ) ) ; return new INDArray [ ] { hAdjusted , oneSided } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next element in the iteration . [CODESPLIT] @ Override public DataSet next ( ) { if ( ! iter . hasNext ( ) && passes < numPasses ) { passes ++ ; batch = 0 ; log . info ( \"Epoch \" + passes + \" batch \" + batch ) ; iter . reset ( ) ; } batch ++ ; DataSet next = iter . next ( ) ; if ( preProcessor != null ) preProcessor . preProcess ( next ) ; return next ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ND Convolution [CODESPLIT] @ Override public IComplexNDArray convn ( IComplexNDArray input , IComplexNDArray kernel , Convolution . Type type ) { return convn ( input , kernel , type , ArrayUtil . range ( 0 , input . shape ( ) . length ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CHOLESKY DECOMP [CODESPLIT] @ Override public void spotrf ( byte uplo , int N , INDArray A , INDArray INFO ) { INDArray a = A ; if ( Nd4j . dataType ( ) != DataBuffer . Type . FLOAT ) log . warn ( \"DOUBLE potrf called in FLOAT environment\" ) ; if ( A . ordering ( ) == ' ' ) a = A . dup ( ' ' ) ; if ( Nd4j . getExecutioner ( ) instanceof GridExecutioner ) ( ( GridExecutioner ) Nd4j . getExecutioner ( ) ) . flushQueue ( ) ; // Get context for current thread CudaContext ctx = ( CudaContext ) allocator . getDeviceContext ( ) . getContext ( ) ; // setup the solver handles for cuSolver calls cusolverDnHandle_t handle = ctx . getSolverHandle ( ) ; cusolverDnContext solverDn = new cusolverDnContext ( handle ) ; // synchronized on the solver synchronized ( handle ) { int result = cusolverDnSetStream ( new cusolverDnContext ( handle ) , new CUstream_st ( ctx . getOldStream ( ) ) ) ; if ( result != 0 ) throw new BlasException ( \"solverSetStream failed\" ) ; // transfer the INDArray into GPU memory CublasPointer xAPointer = new CublasPointer ( a , ctx ) ; // this output - indicates how much memory we'll need for the real operation DataBuffer worksizeBuffer = Nd4j . getDataBufferFactory ( ) . createInt ( 1 ) ; int stat = cusolverDnSpotrf_bufferSize ( solverDn , uplo , N , ( FloatPointer ) xAPointer . getDevicePointer ( ) , N , ( IntPointer ) worksizeBuffer . addressPointer ( ) // we intentionally use host pointer here ) ; if ( stat != CUSOLVER_STATUS_SUCCESS ) { throw new BlasException ( \"cusolverDnSpotrf_bufferSize failed\" , stat ) ; } int worksize = worksizeBuffer . getInt ( 0 ) ; // Now allocate memory for the workspace, the permutation matrix and a return code Pointer workspace = new Workspace ( worksize * Nd4j . sizeOfDataType ( ) ) ; // Do the actual decomp stat = cusolverDnSpotrf ( solverDn , uplo , N , ( FloatPointer ) xAPointer . getDevicePointer ( ) , N , new CudaPointer ( workspace ) . asFloatPointer ( ) , worksize , new CudaPointer ( allocator . getPointer ( INFO , ctx ) ) . asIntPointer ( ) ) ; if ( stat != CUSOLVER_STATUS_SUCCESS ) { throw new BlasException ( \"cusolverDnSpotrf failed\" , stat ) ; } } allocator . registerAction ( ctx , a ) ; allocator . registerAction ( ctx , INFO ) ; if ( a != A ) A . assign ( a ) ; if ( uplo == ' ' ) { A . assign ( A . transpose ( ) ) ; INDArrayIndex ix [ ] = new INDArrayIndex [ 2 ] ; for ( int i = 1 ; i < Math . min ( A . rows ( ) , A . columns ( ) ) ; i ++ ) { ix [ 0 ] = NDArrayIndex . point ( i ) ; ix [ 1 ] = NDArrayIndex . interval ( 0 , i ) ; A . put ( ix , 0 ) ; } } else { INDArrayIndex ix [ ] = new INDArrayIndex [ 2 ] ; for ( int i = 0 ; i < Math . min ( A . rows ( ) , A . columns ( ) - 1 ) ; i ++ ) { ix [ 0 ] = NDArrayIndex . point ( i ) ; ix [ 1 ] = NDArrayIndex . interval ( i + 1 , A . columns ( ) ) ; A . put ( ix , 0 ) ; } } log . info ( \"A: {}\" , A ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Q R DECOMP [CODESPLIT] @ Override public void sgeqrf ( int M , int N , INDArray A , INDArray R , INDArray INFO ) { INDArray tau = Nd4j . create ( N ) ; int status = LAPACKE_sgeqrf ( getColumnOrder ( A ) , M , N , ( FloatPointer ) A . data ( ) . addressPointer ( ) , getLda ( A ) , ( FloatPointer ) tau . data ( ) . addressPointer ( ) ) ; if ( status != 0 ) { throw new BlasException ( \"Failed to execute sgeqrf\" , status ) ; } // Copy R ( upper part of Q ) into result if ( R != null ) { R . assign ( A . get ( NDArrayIndex . interval ( 0 , A . columns ( ) ) , NDArrayIndex . all ( ) ) ) ; INDArrayIndex ix [ ] = new INDArrayIndex [ 2 ] ; for ( int i = 1 ; i < Math . min ( A . rows ( ) , A . columns ( ) ) ; i ++ ) { ix [ 0 ] = NDArrayIndex . point ( i ) ; ix [ 1 ] = NDArrayIndex . interval ( 0 , i ) ; R . put ( ix , 0 ) ; } } status = LAPACKE_sorgqr ( getColumnOrder ( A ) , M , N , N , ( FloatPointer ) A . data ( ) . addressPointer ( ) , getLda ( A ) , ( FloatPointer ) tau . data ( ) . addressPointer ( ) ) ; if ( status != 0 ) { throw new BlasException ( \"Failed to execute sorgqr\" , status ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns AllocationShape for specific array that takes in account its real shape : offset length etc [CODESPLIT] public static AllocationShape buildAllocationShape ( INDArray array ) { AllocationShape shape = new AllocationShape ( ) ; shape . setStride ( array . elementWiseStride ( ) ) ; shape . setOffset ( array . originalOffset ( ) ) ; shape . setDataType ( array . data ( ) . dataType ( ) ) ; shape . setLength ( array . length ( ) ) ; shape . setDataType ( array . data ( ) . dataType ( ) ) ; return shape ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns AllocationShape for the whole DataBuffer . [CODESPLIT] public static AllocationShape buildAllocationShape ( DataBuffer buffer ) { AllocationShape shape = new AllocationShape ( ) ; shape . setStride ( 1 ) ; shape . setOffset ( buffer . originalOffset ( ) ) ; shape . setDataType ( buffer . dataType ( ) ) ; shape . setLength ( buffer . length ( ) ) ; return shape ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a file exists in the path [CODESPLIT] public static boolean nameExistsInPath ( String name ) { String path = System . getenv ( PATH_ENV_VARIABLE ) ; String [ ] dirs = path . split ( File . pathSeparator ) ; for ( String dir : dirs ) { File dirFile = new File ( dir ) ; if ( ! dirFile . exists ( ) ) continue ; if ( dirFile . isFile ( ) && dirFile . getName ( ) . equals ( name ) ) return true ; else { Iterator < File > files = FileUtils . iterateFiles ( dirFile , null , false ) ; while ( files . hasNext ( ) ) { File curr = files . next ( ) ; if ( curr . getName ( ) . equals ( name ) ) return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Custom deserialization for Java serialization [CODESPLIT] protected void read ( ObjectInputStream s ) throws IOException , ClassNotFoundException { data = Nd4j . createBuffer ( length , false ) ; data . read ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method ensures the events in the beginning of FIFO queues are finished [CODESPLIT] protected void sweepTail ( ) { Integer deviceId = allocator . getDeviceId ( ) ; int cnt = 0 ; // we get number of issued commands for specific device long lastCommandId = deviceClocks . get ( deviceId ) . get ( ) ; for ( int l = 0 ; l < configuration . getCommandLanesNumber ( ) ; l ++ ) { Queue < cudaEvent_t > queue = eventsBarrier . get ( deviceId ) . get ( l ) ; if ( queue . size ( ) >= MAX_EXECUTION_QUEUE || laneClocks . get ( deviceId ) . get ( l ) . get ( ) < lastCommandId - MAX_EXECUTION_QUEUE ) { cudaEvent_t event = queue . poll ( ) ; if ( event != null && ! event . isDestroyed ( ) ) { event . synchronize ( ) ; event . destroy ( ) ; cnt ++ ; } } } deviceClocks . get ( deviceId ) . incrementAndGet ( ) ; //  log.info(\"Events sweeped: [{}]\", cnt); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a complex ndarray from the passed in indarray [CODESPLIT] @ Override public IComplexNDArray createComplex ( IComplexNumber [ ] data , int [ ] shape ) { return new JCublasComplexNDArray ( data , shape , Nd4j . getComplexStrides ( shape , Nd4j . order ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a complex ndarray from the passed in indarray [CODESPLIT] @ Override public IComplexNDArray createComplex ( List < IComplexNDArray > arrs , int [ ] shape ) { return new JCublasComplexNDArray ( arrs , shape ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Symmetric in place shuffle of an ndarray along a specified set of dimensions . Each array in list should have it s own dimension at the same index of dimensions array [CODESPLIT] @ Override public void shuffle ( List < INDArray > arrays , Random rnd , List < int [ ] > dimensions ) { // no dimension - no shuffle if ( dimensions == null || dimensions . size ( ) == 0 ) throw new RuntimeException ( \"Dimension can't be null or 0-length\" ) ; if ( arrays == null || arrays . size ( ) == 0 ) throw new RuntimeException ( \"No input arrays provided\" ) ; if ( dimensions . size ( ) > 1 && arrays . size ( ) != dimensions . size ( ) ) throw new IllegalStateException ( \"Number of dimensions do not match number of arrays to shuffle\" ) ; Nd4j . getExecutioner ( ) . push ( ) ; // first we build TAD for input array and dimensions AtomicAllocator allocator = AtomicAllocator . getInstance ( ) ; CudaContext context = null ; for ( int x = 0 ; x < arrays . size ( ) ; x ++ ) { context = allocator . getFlowController ( ) . prepareAction ( arrays . get ( x ) ) ; } int tadLength = 1 ; for ( int i = 0 ; i < dimensions . get ( 0 ) . length ; i ++ ) { tadLength *= arrays . get ( 0 ) . shape ( ) [ dimensions . get ( 0 ) [ i ] ] ; } val numTads = arrays . get ( 0 ) . length ( ) / tadLength ; val map = ArrayUtil . buildInterleavedVector ( rnd , ( int ) numTads ) ; val shuffle = new CudaIntDataBuffer ( map ) ; Pointer shuffleMap = allocator . getPointer ( shuffle , context ) ; PointerPointer extras = new PointerPointer ( null , // not used context . getOldStream ( ) , allocator . getDeviceIdPointer ( ) ) ; long [ ] xPointers = new long [ arrays . size ( ) ] ; long [ ] xShapes = new long [ arrays . size ( ) ] ; long [ ] tadShapes = new long [ arrays . size ( ) ] ; long [ ] tadOffsets = new long [ arrays . size ( ) ] ; for ( int i = 0 ; i < arrays . size ( ) ; i ++ ) { INDArray array = arrays . get ( i ) ; Pointer x = AtomicAllocator . getInstance ( ) . getPointer ( array , context ) ; Pointer xShapeInfo = AtomicAllocator . getInstance ( ) . getPointer ( array . shapeInfoDataBuffer ( ) , context ) ; TADManager tadManager = Nd4j . getExecutioner ( ) . getTADManager ( ) ; int [ ] dimension = dimensions . size ( ) > 1 ? dimensions . get ( i ) : dimensions . get ( 0 ) ; Pair < DataBuffer , DataBuffer > tadBuffers = tadManager . getTADOnlyShapeInfo ( array , dimension ) ; //            log.info(\"Original shape: {}; dimension: {}; TAD shape: {}\", array.shapeInfoDataBuffer().asInt(), dimension, tadBuffers.getFirst().asInt()); Pointer tadShapeInfo = AtomicAllocator . getInstance ( ) . getPointer ( tadBuffers . getFirst ( ) , context ) ; DataBuffer offsets = tadBuffers . getSecond ( ) ; if ( offsets . length ( ) != numTads ) throw new ND4JIllegalStateException ( \"Can't symmetrically shuffle arrays with non-equal number of TADs\" ) ; Pointer tadOffset = AtomicAllocator . getInstance ( ) . getPointer ( offsets , context ) ; xPointers [ i ] = x . address ( ) ; xShapes [ i ] = xShapeInfo . address ( ) ; tadShapes [ i ] = tadShapeInfo . address ( ) ; tadOffsets [ i ] = tadOffset . address ( ) ; } CudaDoubleDataBuffer tempX = new CudaDoubleDataBuffer ( arrays . size ( ) ) ; CudaDoubleDataBuffer tempShapes = new CudaDoubleDataBuffer ( arrays . size ( ) ) ; CudaDoubleDataBuffer tempTAD = new CudaDoubleDataBuffer ( arrays . size ( ) ) ; CudaDoubleDataBuffer tempOffsets = new CudaDoubleDataBuffer ( arrays . size ( ) ) ; AtomicAllocator . getInstance ( ) . memcpyBlocking ( tempX , new LongPointer ( xPointers ) , xPointers . length * 8 , 0 ) ; AtomicAllocator . getInstance ( ) . memcpyBlocking ( tempShapes , new LongPointer ( xShapes ) , xPointers . length * 8 , 0 ) ; AtomicAllocator . getInstance ( ) . memcpyBlocking ( tempTAD , new LongPointer ( tadShapes ) , xPointers . length * 8 , 0 ) ; AtomicAllocator . getInstance ( ) . memcpyBlocking ( tempOffsets , new LongPointer ( tadOffsets ) , xPointers . length * 8 , 0 ) ; if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) { nativeOps . shuffleDouble ( extras , new PointerPointer ( allocator . getPointer ( tempX , context ) ) , new PointerPointer ( allocator . getPointer ( tempShapes , context ) ) , new PointerPointer ( allocator . getPointer ( tempX , context ) ) , new PointerPointer ( allocator . getPointer ( tempShapes , context ) ) , arrays . size ( ) , ( IntPointer ) shuffleMap , new PointerPointer ( allocator . getPointer ( tempTAD , context ) ) , new PointerPointer ( allocator . getPointer ( tempOffsets , context ) ) ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) { nativeOps . shuffleFloat ( extras , new PointerPointer ( allocator . getPointer ( tempX , context ) ) , new PointerPointer ( allocator . getPointer ( tempShapes , context ) ) , new PointerPointer ( allocator . getPointer ( tempX , context ) ) , new PointerPointer ( allocator . getPointer ( tempShapes , context ) ) , arrays . size ( ) , ( IntPointer ) shuffleMap , new PointerPointer ( allocator . getPointer ( tempTAD , context ) ) , new PointerPointer ( allocator . getPointer ( tempOffsets , context ) ) ) ; } else { // HALFs nativeOps . shuffleHalf ( extras , new PointerPointer ( allocator . getPointer ( tempX , context ) ) , new PointerPointer ( allocator . getPointer ( tempShapes , context ) ) , new PointerPointer ( allocator . getPointer ( tempX , context ) ) , new PointerPointer ( allocator . getPointer ( tempShapes , context ) ) , arrays . size ( ) , ( IntPointer ) shuffleMap , new PointerPointer ( allocator . getPointer ( tempTAD , context ) ) , new PointerPointer ( allocator . getPointer ( tempOffsets , context ) ) ) ; } for ( int f = 0 ; f < arrays . size ( ) ; f ++ ) { allocator . getFlowController ( ) . registerAction ( context , arrays . get ( f ) ) ; } // just to keep reference shuffle . address ( ) ; tempX . dataType ( ) ; tempShapes . dataType ( ) ; tempOffsets . dataType ( ) ; tempTAD . dataType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create from an in memory numpy pointer [CODESPLIT] @ Override public INDArray createFromNpyPointer ( Pointer pointer ) { Pointer dataPointer = nativeOps . dataPointForNumpy ( pointer ) ; int dataBufferElementSize = nativeOps . elementSizeForNpyArray ( pointer ) ; DataBuffer data = null ; Pointer shapeBufferPointer = nativeOps . shapeBufferForNumpy ( pointer ) ; int length = nativeOps . lengthForShapeBufferPointer ( shapeBufferPointer ) ; shapeBufferPointer . capacity ( 4 * length ) ; shapeBufferPointer . limit ( 4 * length ) ; shapeBufferPointer . position ( 0 ) ; val intPointer = new LongPointer ( shapeBufferPointer ) ; DataBuffer shapeBuffer = Nd4j . createBuffer ( shapeBufferPointer , DataBuffer . Type . LONG , length , LongRawIndexer . create ( intPointer ) ) ; dataPointer . position ( 0 ) ; dataPointer . limit ( dataBufferElementSize * Shape . length ( shapeBuffer ) ) ; dataPointer . capacity ( dataBufferElementSize * Shape . length ( shapeBuffer ) ) ; // we don't care about pointers here, they will be copied in BaseCudaDataBuffer method, and indexer will be recreated if ( dataBufferElementSize == ( Float . SIZE / 8 ) ) { data = Nd4j . createBuffer ( dataPointer , DataBuffer . Type . FLOAT , Shape . length ( shapeBuffer ) , FloatIndexer . create ( new FloatPointer ( dataPointer ) ) ) ; } else if ( dataBufferElementSize == ( Double . SIZE / 8 ) ) { data = Nd4j . createBuffer ( dataPointer , DataBuffer . Type . DOUBLE , Shape . length ( shapeBuffer ) , DoubleIndexer . create ( new DoublePointer ( dataPointer ) ) ) ; } INDArray ret = Nd4j . create ( data , Shape . shape ( shapeBuffer ) , Shape . strideArr ( shapeBuffer ) , Shape . offset ( shapeBuffer ) , Shape . order ( shapeBuffer ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create from a given numpy file . [CODESPLIT] @ Override public INDArray createFromNpyFile ( File file ) { /*Pointer pointer = nativeOps.numpyFromFile(new BytePointer(file.getAbsolutePath().getBytes()));\n        log.info(\"Pointer here: {}\", pointer.address());\n        return createFromNpyPointer(pointer);\n\n        */ byte [ ] pathBytes = file . getAbsolutePath ( ) . getBytes ( Charset . forName ( \"UTF-8\" ) ) ; String otherBytes = new String ( pathBytes ) ; System . out . println ( otherBytes ) ; ByteBuffer directBuffer = ByteBuffer . allocateDirect ( pathBytes . length ) . order ( ByteOrder . nativeOrder ( ) ) ; directBuffer . put ( pathBytes ) ; directBuffer . rewind ( ) ; directBuffer . position ( 0 ) ; Pointer pointer = nativeOps . numpyFromFile ( new BytePointer ( directBuffer ) ) ; INDArray result = createFromNpyPointer ( pointer ) ; // releasing original pointer here nativeOps . releaseNumpy ( pointer ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method provides PointersPair to memory chunk specified by AllocationShape [CODESPLIT] @ Override public PointersPair malloc ( AllocationShape shape , AllocationPoint point , AllocationStatus location ) { long reqMemory = AllocationUtils . getRequiredMemory ( shape ) ; if ( location == AllocationStatus . HOST && reqMemory < CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getMaximumHostCacheableLength ( ) ) { CacheHolder cache = zeroCache . get ( shape ) ; if ( cache != null ) { Pointer pointer = cache . poll ( ) ; if ( pointer != null ) { cacheZeroHit . incrementAndGet ( ) ; // since this memory chunk is going to be used now, remove it's amount from zeroCachedAmount . addAndGet ( - 1 * reqMemory ) ; PointersPair pair = new PointersPair ( ) ; pair . setDevicePointer ( new CudaPointer ( pointer . address ( ) ) ) ; pair . setHostPointer ( new CudaPointer ( pointer . address ( ) ) ) ; point . setAllocationStatus ( AllocationStatus . HOST ) ; return pair ; } } cacheZeroMiss . incrementAndGet ( ) ; if ( CudaEnvironment . getInstance ( ) . getConfiguration ( ) . isUsePreallocation ( ) && zeroCachedAmount . get ( ) < CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getMaximumHostCache ( ) / 10 && reqMemory < 16 * 1024 * 1024L ) { CachePreallocator preallocator = new CachePreallocator ( shape , location , CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getPreallocationCalls ( ) ) ; preallocator . start ( ) ; } cacheZeroMiss . incrementAndGet ( ) ; return super . malloc ( shape , point , location ) ; } return super . malloc ( shape , point , location ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method does allocation from a given Workspace [CODESPLIT] @ Override public PagedPointer alloc ( long requiredMemory , MemoryKind kind , DataBuffer . Type dataType , boolean initialize ) { throw new UnsupportedOperationException ( \"DummyWorkspace shouldn't be used for allocation\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method notifies locker that specific object was added to tracking list [CODESPLIT] @ Override public void attachObject ( Object object ) { if ( ! objectLocks . containsKey ( object ) ) objectLocks . put ( object , new ReentrantReadWriteLock ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the update based on the given gradient [CODESPLIT] @ Override public void applyUpdater ( INDArray gradient , int iteration , int epoch ) { if ( m == null || v == null ) throw new IllegalStateException ( \"Updater has not been initialized with view state\" ) ; double beta1 = config . getBeta1 ( ) ; double beta2 = config . getBeta2 ( ) ; double learningRate = config . getLearningRate ( iteration , epoch ) ; double epsilon = config . getEpsilon ( ) ; INDArray oneMinusBeta1Grad = gradient . mul ( 1.0 - beta1 ) ; m . muli ( beta1 ) . addi ( oneMinusBeta1Grad ) ; INDArray oneMinusBeta2GradSquared = gradient . mul ( gradient ) . muli ( 1 - beta2 ) ; v . muli ( beta2 ) . addi ( oneMinusBeta2GradSquared ) ; double beta1t = FastMath . pow ( beta1 , iteration + 1 ) ; double beta2t = FastMath . pow ( beta2 , iteration + 1 ) ; double alphat = learningRate * FastMath . sqrt ( 1 - beta2t ) / ( 1 - beta1t ) ; if ( Double . isNaN ( alphat ) || alphat == 0.0 ) alphat = epsilon ; INDArray sqrtV = Transforms . sqrt ( v . dup ( gradientReshapeOrder ) , false ) . addi ( epsilon ) ; gradient . assign ( m ) . muli ( alphat ) . divi ( sqrtV ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the bytes for the object to the output . <p > This method should not be called directly instead this serializer can be passed to { @link Kryo } write methods that accept a serialier . [CODESPLIT] @ Override public void write ( Kryo kryo , Output output , INDArray object ) { DataOutputStream dos = new DataOutputStream ( output ) ; try { Nd4j . write ( object , dos ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } //Note: output should NOT be closed manually here - may be needed elsewhere (and closing here will cause serialization to fail) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads bytes and returns a new object of the specified concrete opType . <p > Before Kryo can be used to read child objects { @link Kryo#reference ( Object ) } must be called with the parent object to ensure it can be referenced by the child objects . Any serializer that uses { @link Kryo } to read a child object may need to be reentrant . <p > This method should not be called directly instead this serializer can be passed to { @link Kryo } read methods that accept a serialier . [CODESPLIT] @ Override public INDArray read ( Kryo kryo , Input input , Class < INDArray > type ) { DataInputStream dis = new DataInputStream ( input ) ; try { return Nd4j . read ( dis ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } //Note: input should NOT be closed manually here - may be needed elsewhere (and closing here will cause serialization to fail) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if bth the master and responder are started . [CODESPLIT] public boolean started ( ) { return master . equals ( ServerState . STARTED . name ( ) . toLowerCase ( ) ) && responder . equals ( ServerState . STARTED . name ( ) . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is one of the main entry points for ops that are executed without respect to dimension . [CODESPLIT] @ Override public Op exec ( Op op ) { /*\n            We pass this op to GridProcessor through check for possible MetaOp concatenation\n            Also, it's the GriOp entry point\n         */ checkForCompression ( op ) ; invokeWatchdog ( op ) ; if ( op instanceof Accumulation ) { exec ( ( Accumulation ) op , new int [ ] { Integer . MAX_VALUE } ) ; } else if ( op instanceof IndexAccumulation ) { exec ( ( IndexAccumulation ) op , new int [ ] { Integer . MAX_VALUE } ) ; } else if ( op instanceof ScalarOp || op instanceof TransformOp ) { // the only entry place for TADless ops processAsGridOp ( op ) ; } else if ( op instanceof BroadcastOp ) { invoke ( ( BroadcastOp ) op ) ; } else { //logger.info(\"Random op: {}\", op.getClass().getSimpleName()); pushToGrid ( new OpDescriptor ( op ) ) ; } return op ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FIXME : remove CudaContext return opType . We just don t need it [CODESPLIT] @ Override protected CudaContext invoke ( TransformOp op ) { if ( op . isExecSpecial ( ) ) { flushQueue ( ) ; super . invoke ( op ) ; } else { processAsGridOp ( op , null ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method forces all currently enqueued ops to be executed immediately [CODESPLIT] @ Override public void flushQueueBlocking ( ) { flushQueue ( ) ; //    logger.info(\"Blocking flush\");n ( ( CudaContext ) AtomicAllocator . getInstance ( ) . getDeviceContext ( ) . getContext ( ) ) . syncOldStream ( ) ; ( ( CudaContext ) AtomicAllocator . getInstance ( ) . getDeviceContext ( ) . getContext ( ) ) . syncSpecialStream ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the device pointer for the given data buffer [CODESPLIT] public static long retrieveDeviceAddress ( DataBuffer buffer , CudaContext context ) { return allocator . getPointer ( buffer , context ) . address ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the device pointer for the given data buffer [CODESPLIT] public static Pointer retrieveDevicePointer ( DataBuffer buffer , CudaContext context ) { return allocator . getPointer ( buffer , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PLEASE NOTE : Specific implementation on systems without special devices can return HostPointer here [CODESPLIT] @ Override public org . bytedeco . javacpp . Pointer getDevicePointer ( DataBuffer buffer , CudaContext context ) { // TODO: It would be awesome to get rid of typecasting here //getCudaContext().syncOldStream(); AllocationPoint dstPoint = ( ( BaseCudaDataBuffer ) buffer ) . getAllocationPoint ( ) ; //log.info(\"getDevicePointer called\"); /*\n        if (configuration.getMemoryModel() == Configuration.MemoryModel.DELAYED && dstPoint.getAllocationStatus() == AllocationStatus.HOST) {\n        \n            // if we have constant buffer (aka shapeInfo or other constant stuff)\n            if (buffer.isConstant()) {\n                Nd4j.getConstantHandler().moveToConstantSpace(buffer);\n            } else {\n                PointersPair pair = memoryProvider.malloc(dstPoint.getShape(), dstPoint, AllocationStatus.DEVICE);\n        \n                if (pair != null) {\n                    Integer deviceId = getDeviceId();\n        \n                    dstPoint.getPointers().setDevicePointer(pair.getDevicePointer());\n                    dstPoint.setAllocationStatus(AllocationStatus.DEVICE);\n        \n                    deviceAllocations.get(deviceId).put(dstPoint.getObjectId(), dstPoint.getObjectId());\n        \n                    zeroAllocations.get(dstPoint.getBucketId()).remove(dstPoint.getObjectId());\n                    deviceMemoryTracker.addToAllocation(Thread.currentThread().getId(), deviceId, AllocationUtils.getRequiredMemory(dstPoint.getShape()));\n        \n        \n                    dstPoint.tickHostWrite();\n                }\n            }\n        }\n        */ // here's the place, where we do care about promotion. but we only care about promotion of original  buffers if ( dstPoint . getAllocationStatus ( ) == AllocationStatus . HOST && buffer . offset ( ) == 0 && 1 < 0 ) { if ( dstPoint . getDeviceTicks ( ) > configuration . getMinimumRelocationThreshold ( ) ) { // at this point we know, that this request is done withing some existent context long requiredMemory = AllocationUtils . getRequiredMemory ( dstPoint . getShape ( ) ) ; if ( deviceMemoryTracker . reserveAllocationIfPossible ( Thread . currentThread ( ) . getId ( ) , getDeviceId ( ) , requiredMemory ) && pingDeviceForFreeMemory ( getDeviceId ( ) , requiredMemory ) ) { // so, memory is reserved promoteObject ( buffer ) ; } } } // if that's device state, we probably might want to update device memory state if ( dstPoint . getAllocationStatus ( ) == AllocationStatus . DEVICE ) { if ( ! dstPoint . isActualOnDeviceSide ( ) ) { //                log.info(\"Relocating to GPU\"); relocate ( AllocationStatus . HOST , AllocationStatus . DEVICE , dstPoint , dstPoint . getShape ( ) , context ) ; } else { //  log.info(\"Buffer is actual on device side: \" + dstPoint.getShape()); } } //else log.info(\"Not on [DEVICE]\"); //  we update memory use counter, to announce that it's somehow used on device dstPoint . tickDeviceRead ( ) ; // return pointer with offset if needed. length is specified for constructor compatibility purposes CudaPointer p = new CudaPointer ( dstPoint . getPointers ( ) . getDevicePointer ( ) , buffer . length ( ) , ( buffer . offset ( ) * buffer . getElementSize ( ) ) ) ; switch ( buffer . dataType ( ) ) { case DOUBLE : return p . asDoublePointer ( ) ; case FLOAT : return p . asFloatPointer ( ) ; case INT : return p . asIntPointer ( ) ; case HALF : return p . asShortPointer ( ) ; case LONG : return p . asLongPointer ( ) ; default : return p ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns requested ClassPathResource as InputStream object [CODESPLIT] public InputStream getInputStream ( ) throws FileNotFoundException { URL url = this . getUrl ( ) ; if ( isJarURL ( url ) ) { try { url = extractActualUrl ( url ) ; ZipFile zipFile = new ZipFile ( url . getFile ( ) ) ; ZipEntry entry = zipFile . getEntry ( this . resourceName ) ; InputStream stream = zipFile . getInputStream ( entry ) ; return stream ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else { File srcFile = this . getFile ( ) ; return new FileInputStream ( srcFile ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns deviceId for given thread identified by threadId [CODESPLIT] @ Override public Integer getDeviceForThread ( long threadId ) { if ( getNumberOfDevices ( ) == 1 ) return 0 ; Integer aff = affinityMap . get ( threadId ) ; if ( aff == null ) { Integer deviceId = getNextDevice ( threadId ) ; affinityMap . put ( threadId , deviceId ) ; affiliated . set ( new AtomicBoolean ( false ) ) ; if ( threadId == Thread . currentThread ( ) . getId ( ) ) { NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . setDevice ( new CudaPointer ( deviceId ) ) ; //logger.error(\"setDevice({}) called for thread {}\", deviceId, Thread.currentThread().getName()); affiliated . get ( ) . set ( true ) ; } return deviceId ; } else { if ( threadId == Thread . currentThread ( ) . getId ( ) ) { if ( affiliated . get ( ) == null ) affiliated . set ( new AtomicBoolean ( false ) ) ; if ( ! affiliated . get ( ) . get ( ) ) { NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . setDevice ( new CudaPointer ( aff ) ) ; //logger.error(\"SCARY setDevice({}) called for thread {}\", aff, threadId); affiliated . get ( ) . set ( true ) ; return aff ; } } return aff ; } /*\n\n\n        return affinityMap.get(threadId);\n*/ //return 0; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method pairs specified thread & device [CODESPLIT] @ Override public void attachThreadToDevice ( long threadId , Integer deviceId ) { List < Integer > devices = new ArrayList <> ( CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) ) ; logger . debug ( \"Manually mapping thread [{}] to device [{}], out of [{}] devices...\" , threadId , deviceId , devices . size ( ) ) ; affinityMap . put ( threadId , deviceId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns device id available . Round - robin balancing used here . [CODESPLIT] protected Integer getNextDevice ( long threadId ) { Integer device = null ; if ( ! CudaEnvironment . getInstance ( ) . getConfiguration ( ) . isForcedSingleGPU ( ) && getNumberOfDevices ( ) > 0 ) { // simple round-robin here synchronized ( this ) { device = CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . get ( devPtr . getAndIncrement ( ) ) ; // We check only for number of entries here, not their actual values if ( devPtr . get ( ) >= CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . size ( ) ) devPtr . set ( 0 ) ; logger . debug ( \"Mapping thread [{}] to device [{}], out of [{}] devices...\" , threadId , device , CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . size ( ) ) ; } } else { device = CudaEnvironment . getInstance ( ) . getConfiguration ( ) . getAvailableDevices ( ) . get ( 0 ) ; logger . debug ( \"Single device is forced, mapping to device [{}]\" , device ) ; } return device ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the specified library . The full name of the library is created by calling { @link LibUtils#createLibName ( String ) } with the given argument . The method will attempt to load the library as a as a resource ( for usage within a JAR ) and if this fails using the usual System . loadLibrary call . [CODESPLIT] public static void loadLibrary ( String baseName ) { String libName = LibUtils . createLibName ( baseName ) ; Throwable throwable = null ; try { loadLibraryResource ( libName ) ; return ; } catch ( Throwable t ) { throwable = t ; } try { System . loadLibrary ( libName ) ; return ; } catch ( Throwable t ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; pw . println ( \"Error while loading native library \\\"\" + libName + \"\\\" with base name \\\"\" + baseName + \"\\\"\" ) ; pw . println ( \"Operating system name: \" + System . getProperty ( \"os.name\" ) ) ; pw . println ( \"Architecture         : \" + System . getProperty ( \"os.arch\" ) ) ; pw . println ( \"Architecture bit size: \" + System . getProperty ( \"sun.arch.data.model\" ) ) ; if ( throwable != null ) { pw . println ( \"Stack trace from the attempt to \" + \"load the library as a resource:\" ) ; throwable . printStackTrace ( pw ) ; } pw . println ( \"Stack trace from the attempt to \" + \"load the library as a file:\" ) ; t . printStackTrace ( pw ) ; pw . flush ( ) ; pw . close ( ) ; throw new UnsatisfiedLinkError ( \"Could not load the native library.\\n\" + sw . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the library with the given name from a resource . The extension for the current OS will be appended . [CODESPLIT] public static void loadTempBinaryFile ( String libName ) throws Exception { String libPrefix = createLibPrefix ( ) ; String libExtension = createLibExtension ( ) ; String fullName = libPrefix + libName ; String resourceName = fullName + \".\" + libExtension ; ClassPathResource resource = new ClassPathResource ( resourceName ) ; InputStream inputStream = resource . getInputStream ( ) ; if ( inputStream == null ) { throw new NullPointerException ( \"No resource found with name '\" + resourceName + \"'\" ) ; } File tempFile = new File ( System . getProperty ( \"java.io.tmpdir\" ) , fullName + \".\" + libExtension ) ; tempFile . deleteOnExit ( ) ; OutputStream outputStream = null ; try { outputStream = new FileOutputStream ( tempFile ) ; byte [ ] buffer = new byte [ 8192 ] ; while ( true ) { int read = inputStream . read ( buffer ) ; if ( read < 0 ) { break ; } outputStream . write ( buffer , 0 , read ) ; } outputStream . flush ( ) ; outputStream . close ( ) ; outputStream = null ; System . load ( tempFile . getAbsolutePath ( ) ) ; } finally { if ( outputStream != null ) { outputStream . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the library with the given name from a resource . The extension for the current OS will be appended . [CODESPLIT] public static void loadTempBinaryFile ( Class < ? > libName ) throws Exception { String os = getOsName ( ) ; String arch = getArchName ( ) ; String resourceFolder = os + \"-\" + arch ; String libPrefix = createLibPrefix ( ) ; String libExtension = createLibExtension ( ) ; StringBuilder sb = new StringBuilder ( ) . append ( libName . getPackage ( ) . getName ( ) . replace ( \".\" , \"/\" ) + \"/\" ) . append ( resourceFolder ) . append ( \"/\" ) . append ( libPrefix ) . append ( \"jni\" + libName . getSimpleName ( ) + \".\" ) . append ( libExtension ) ; String resourceName = sb . toString ( ) ; ClassPathResource resource = new ClassPathResource ( resourceName ) ; InputStream inputStream = resource . getInputStream ( ) ; if ( inputStream == null ) { throw new NullPointerException ( \"No resource found with name '\" + resourceName + \"'\" ) ; } String fullName = libPrefix + \"jni\" + libName . getSimpleName ( ) + \".\" + libExtension ; File tempFile = new File ( System . getProperty ( \"java.io.tmpdir\" ) , fullName ) ; tempFile . deleteOnExit ( ) ; OutputStream outputStream = null ; try { outputStream = new FileOutputStream ( tempFile ) ; byte [ ] buffer = new byte [ 8192 ] ; while ( true ) { int read = inputStream . read ( buffer ) ; if ( read < 0 ) { break ; } outputStream . write ( buffer , 0 , read ) ; } outputStream . flush ( ) ; outputStream . close ( ) ; outputStream = null ; System . load ( tempFile . getAbsolutePath ( ) ) ; } finally { if ( outputStream != null ) { outputStream . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the library with the given name from a resource . The extension for the current OS will be appended . [CODESPLIT] public static void loadJavaCppResource ( String libName ) throws Throwable { String libPrefix = createLibPrefix ( ) ; String libExtension = createLibExtension ( ) ; String fullName = libPrefix + libName ; String resourceName = fullName + \".\" + libExtension ; ClassPathResource resource = new ClassPathResource ( resourceName ) ; InputStream inputStream = resource . getInputStream ( ) ; if ( inputStream == null ) { throw new NullPointerException ( \"No resource found with name '\" + resourceName + \"'\" ) ; } File tempFile = File . createTempFile ( fullName , \".\" + libExtension ) ; tempFile . deleteOnExit ( ) ; OutputStream outputStream = null ; try { outputStream = new FileOutputStream ( tempFile ) ; byte [ ] buffer = new byte [ 8192 ] ; while ( true ) { int read = inputStream . read ( buffer ) ; if ( read < 0 ) { break ; } outputStream . write ( buffer , 0 , read ) ; } outputStream . flush ( ) ; outputStream . close ( ) ; outputStream = null ; System . load ( tempFile . toString ( ) ) ; } finally { if ( outputStream != null ) { outputStream . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the name of the os for libary discovery on the classpath [CODESPLIT] public static String getOsName ( ) { OSType osType = calculateOS ( ) ; switch ( osType ) { case APPLE : return \"macosx\" ; case LINUX : return \"linux\" ; case SUN : return \"sun\" ; case WINDOWS : return \"windows\" ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the name for the native library with the given base name for the current operating system and architecture . The resulting name will be of the form<br / > baseName - OSType - ARCHType<br / > where OSType and ARCHType are the <strong > lower case< / strong > Strings of the respective enum constants . Example : <br / > jcuda - windows - x86<br / > [CODESPLIT] public static String createLibName ( String baseName ) { OSType osType = calculateOS ( ) ; ARCHType archType = calculateArch ( ) ; String libName = baseName ; libName += \"-\" + osType . toString ( ) . toLowerCase ( Locale . ENGLISH ) ; libName += \"-\" + archType . toString ( ) . toLowerCase ( Locale . ENGLISH ) ; return libName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the current ARCHType [CODESPLIT] public static ARCHType calculateArch ( ) { String osArch = System . getProperty ( \"os.arch\" ) ; osArch = osArch . toLowerCase ( Locale . ENGLISH ) ; if ( osArch . equals ( \"i386\" ) || osArch . equals ( \"x86\" ) || osArch . equals ( \"i686\" ) ) { return ARCHType . X86 ; } if ( osArch . startsWith ( \"amd64\" ) || osArch . startsWith ( \"x86_64\" ) ) { return ARCHType . X86_64 ; } if ( osArch . equals ( \"ppc\" ) || osArch . equals ( \"powerpc\" ) ) { return ARCHType . PPC ; } if ( osArch . startsWith ( \"ppc\" ) ) { return ARCHType . PPC_64 ; } if ( osArch . startsWith ( \"sparc\" ) ) { return ARCHType . SPARC ; } if ( osArch . startsWith ( \"arm\" ) ) { return ARCHType . ARM ; } if ( osArch . startsWith ( \"mips\" ) ) { return ARCHType . MIPS ; } if ( osArch . contains ( \"risc\" ) ) { return ARCHType . RISC ; } return ARCHType . UNKNOWN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Publish to a kafka topic based on the connection information [CODESPLIT] public void publish ( INDArray arr ) { if ( producerTemplate == null ) producerTemplate = camelContext . createProducerTemplate ( ) ; producerTemplate . sendBody ( \"direct:start\" , arr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the server [CODESPLIT] public void start ( ) { try { InputStream is = new ClassPathResource ( resourcePath , InstrumentationApplication . class . getClassLoader ( ) ) . getInputStream ( ) ; File tmpConfig = new File ( resourcePath ) ; if ( ! tmpConfig . getParentFile ( ) . exists ( ) ) tmpConfig . getParentFile ( ) . mkdirs ( ) ; BufferedOutputStream bos = new BufferedOutputStream ( new FileOutputStream ( tmpConfig ) ) ; IOUtils . copy ( is , bos ) ; bos . flush ( ) ; run ( new String [ ] { \"server\" , tmpConfig . getAbsolutePath ( ) } ) ; tmpConfig . deleteOnExit ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a data buffer based on the given pointer data buffer opType and length of the buffer [CODESPLIT] @ Override public DataBuffer create ( Pointer pointer , DataBuffer . Type type , long length , Indexer indexer ) { switch ( type ) { case INT : return new IntBuffer ( pointer , indexer , length ) ; case DOUBLE : return new DoubleBuffer ( pointer , indexer , length ) ; case FLOAT : return new FloatBuffer ( pointer , indexer , length ) ; case LONG : return new LongBuffer ( pointer , indexer , length ) ; } throw new IllegalArgumentException ( \"Invalid opType \" + type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method checks if any Op operand has data opType of INT and throws exception if any . [CODESPLIT] protected void interceptIntDataType ( Op op ) { // FIXME: Remove this method, after we'll add support for <int> dtype operations if ( op . x ( ) != null && op . x ( ) . data ( ) . dataType ( ) == DataBuffer . Type . INT ) throw new ND4JIllegalStateException ( \"Op.X contains INT data. Operations on INT dataType are not supported yet\" ) ; if ( op . z ( ) != null && op . z ( ) . data ( ) . dataType ( ) == DataBuffer . Type . INT ) throw new ND4JIllegalStateException ( \"Op.Z contains INT data. Operations on INT dataType are not supported yet\" ) ; if ( op . y ( ) != null && op . y ( ) . data ( ) . dataType ( ) == DataBuffer . Type . INT ) throw new ND4JIllegalStateException ( \"Op.Y contains INT data. Operations on INT dataType are not supported yet.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add two complex numbers in - place [CODESPLIT] @ Override public IComplexNumber addi ( IComplexNumber c , IComplexNumber result ) { return result . set ( result . realComponent ( ) . floatValue ( ) + c . realComponent ( ) . floatValue ( ) , result . imaginaryComponent ( ) . floatValue ( ) + c . imaginaryComponent ( ) . floatValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply two complex numbers inplace [CODESPLIT] @ Override public IComplexNumber muli ( IComplexNumber c , IComplexNumber result ) { float newR = realComponent ( ) * c . realComponent ( ) . floatValue ( ) - imaginaryComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) ; float newI = realComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) + imaginaryComponent ( ) * c . realComponent ( ) . floatValue ( ) ; return result . set ( newR , newI ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide two complex numbers in - place [CODESPLIT] @ Override public IComplexNumber divi ( IComplexNumber c , IComplexNumber result ) { float d = c . realComponent ( ) . floatValue ( ) * c . realComponent ( ) . floatValue ( ) + c . imaginaryComponent ( ) . floatValue ( ) * c . imaginaryComponent ( ) . floatValue ( ) ; float newR = ( realComponent ( ) * c . realComponent ( ) . floatValue ( ) + imaginaryComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) ) / d ; float newI = ( imaginaryComponent ( ) * c . realComponent ( ) . floatValue ( ) - realComponent ( ) * c . imaginaryComponent ( ) . floatValue ( ) ) / d ; return result . set ( newR , newI ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drop - in replacement wrapper for BaseDataBuffer . read () method aware of CompressedDataBuffer [CODESPLIT] public static DataBuffer readUnknown ( DataInputStream s , long length ) { DataBuffer buffer = Nd4j . createBuffer ( length ) ; buffer . read ( s ) ; // if buffer is uncompressed, it'll be valid buffer, so we'll just return it if ( buffer . dataType ( ) != Type . COMPRESSED ) return buffer ; else { try { // if buffer is compressed one, we''ll restore it here String compressionAlgorithm = s . readUTF ( ) ; long compressedLength = s . readLong ( ) ; long originalLength = s . readLong ( ) ; long numberOfElements = s . readLong ( ) ; byte [ ] temp = new byte [ ( int ) compressedLength ] ; for ( int i = 0 ; i < compressedLength ; i ++ ) { temp [ i ] = s . readByte ( ) ; } Pointer pointer = new BytePointer ( temp ) ; CompressionDescriptor descriptor = new CompressionDescriptor ( ) ; descriptor . setCompressedLength ( compressedLength ) ; descriptor . setCompressionAlgorithm ( compressionAlgorithm ) ; descriptor . setOriginalLength ( originalLength ) ; descriptor . setNumberOfElements ( numberOfElements ) ; return new CompressedDataBuffer ( pointer , descriptor ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method assigns specific value to either specific row or whole array . Array is identified by key [CODESPLIT] @ Override public void processMessage ( ) { if ( payload != null ) { // we're assigning array if ( storage . arrayExists ( key ) && storage . getArray ( key ) . length ( ) == payload . length ( ) ) storage . getArray ( key ) . assign ( payload ) ; else storage . setArray ( key , payload ) ; } else { // we're assigning number to row if ( index >= 0 ) { if ( storage . getArray ( key ) == null ) throw new RuntimeException ( \"Init wasn't called before for key [\" + key + \"]\" ) ; storage . getArray ( key ) . getRow ( index ) . assign ( value ) ; } else storage . getArray ( key ) . assign ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Local response normalization operation . [CODESPLIT] public SDVariable localResponseNormalization ( SDVariable inputs , LocalResponseNormalizationConfig lrnConfig ) { LocalResponseNormalization lrn = LocalResponseNormalization . builder ( ) . inputFunctions ( new SDVariable [ ] { inputs } ) . sameDiff ( sameDiff ( ) ) . config ( lrnConfig ) . build ( ) ; return lrn . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conv1d operation . [CODESPLIT] public SDVariable conv1d ( SDVariable [ ] inputs , Conv1DConfig conv1DConfig ) { Conv1D conv1D = Conv1D . builder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( conv1DConfig ) . build ( ) ; return conv1D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conv2d operation . [CODESPLIT] public SDVariable conv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { Conv2D conv2D = Conv2D . builder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( conv2DConfig ) . build ( ) ; return conv2D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Average pooling 2d operation . [CODESPLIT] public SDVariable avgPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { AvgPooling2D avgPooling2D = AvgPooling2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( pooling2DConfig ) . build ( ) ; return avgPooling2D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max pooling 2d operation . [CODESPLIT] public SDVariable maxPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { MaxPooling2D maxPooling2D = MaxPooling2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( pooling2DConfig ) . build ( ) ; return maxPooling2D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Avg pooling 3d operation . [CODESPLIT] public SDVariable avgPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { Pooling3D maxPooling3D = Pooling3D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . pooling3DConfig ( pooling3DConfig ) . type ( Pooling3D . Pooling3DType . AVG ) . build ( ) ; return maxPooling3D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max pooling 3d operation . [CODESPLIT] public SDVariable maxPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { Pooling3D maxPooling3D = Pooling3D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . pooling3DConfig ( pooling3DConfig ) . type ( Pooling3D . Pooling3DType . MAX ) . build ( ) ; return maxPooling3D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Separable Conv2d operation . [CODESPLIT] public SDVariable sconv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { SConv2D sconv2D = SConv2D . sBuilder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . conv2DConfig ( conv2DConfig ) . build ( ) ; return sconv2D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Depthwise Conv2d operation . This is just separable convolution with only the depth - wise weights specified . [CODESPLIT] public SDVariable depthWiseConv2d ( SDVariable [ ] inputs , Conv2DConfig depthConv2DConfig ) { SConv2D depthWiseConv2D = SConv2D . sBuilder ( ) . inputFunctions ( inputs ) . sameDiff ( sameDiff ( ) ) . conv2DConfig ( depthConv2DConfig ) . build ( ) ; return depthWiseConv2D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deconv2d operation . [CODESPLIT] public SDVariable deconv2d ( SDVariable [ ] inputs , DeConv2DConfig deconv2DConfig ) { DeConv2D deconv2D = DeConv2D . builder ( ) . inputs ( inputs ) . sameDiff ( sameDiff ( ) ) . config ( deconv2DConfig ) . build ( ) ; return deconv2D . outputVariables ( ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the covariance matrix of a data set of many records each with N features . It also returns the average values which are usually going to be important since in this version all modes are centered around the mean . It s a matrix that has elements that are expressed as average dx_i * dx_j ( used in procedure ) or average x_i * x_j - average x_i * average x_j [CODESPLIT] public static INDArray [ ] covarianceMatrix ( INDArray in ) { long dlength = in . rows ( ) ; long vlength = in . columns ( ) ; INDArray sum = Nd4j . create ( vlength ) ; INDArray product = Nd4j . create ( vlength , vlength ) ; for ( int i = 0 ; i < vlength ; i ++ ) sum . getColumn ( i ) . assign ( in . getColumn ( i ) . sumNumber ( ) . doubleValue ( ) / dlength ) ; for ( int i = 0 ; i < dlength ; i ++ ) { INDArray dx1 = in . getRow ( i ) . sub ( sum ) ; product . addi ( dx1 . reshape ( vlength , 1 ) . mmul ( dx1 . reshape ( 1 , vlength ) ) ) ; } product . divi ( dlength ) ; return new INDArray [ ] { product , sum } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the principal component vectors and their eigenvalues ( lambda ) for the covariance matrix . The result includes two things : the eigenvectors ( modes ) as result [ 0 ] and the eigenvalues ( lambda ) as result [ 1 ] . [CODESPLIT] public static INDArray [ ] principalComponents ( INDArray cov ) { assert cov . rows ( ) == cov . columns ( ) ; INDArray [ ] result = new INDArray [ 2 ] ; result [ 0 ] = Nd4j . eye ( cov . rows ( ) ) ; result [ 1 ] = Eigen . symmetricGeneralizedEigenvalues ( result [ 0 ] , cov , true ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method resets all counters [CODESPLIT] public void reset ( ) { invocationsCount . set ( 0 ) ; classAggergator . reset ( ) ; longAggergator . reset ( ) ; classCounter . reset ( ) ; opCounter . reset ( ) ; classPairsCounter . reset ( ) ; opPairsCounter . reset ( ) ; matchingCounter . reset ( ) ; matchingCounterDetailed . reset ( ) ; matchingCounterInverted . reset ( ) ; methodsAggregator . reset ( ) ; scalarAggregator . reset ( ) ; nonEwsAggregator . reset ( ) ; stridedAggregator . reset ( ) ; tadNonEwsAggregator . reset ( ) ; tadStridedAggregator . reset ( ) ; mixedOrderAggregator . reset ( ) ; blasAggregator . reset ( ) ; blasOrderCounter . reset ( ) ; orderCounter . reset ( ) ; listeners . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns op class opName [CODESPLIT] protected String getOpClass ( Op op ) { if ( op instanceof ScalarOp ) { return \"ScalarOp\" ; } else if ( op instanceof MetaOp ) { return \"MetaOp\" ; } else if ( op instanceof GridOp ) { return \"GridOp\" ; } else if ( op instanceof BroadcastOp ) { return \"BroadcastOp\" ; } else if ( op instanceof RandomOp ) { return \"RandomOp\" ; } else if ( op instanceof Accumulation ) { return \"AccumulationOp\" ; } else if ( op instanceof TransformOp ) { if ( op . y ( ) == null ) { return \"TransformOp\" ; } else return \"PairWiseTransformOp\" ; } else if ( op instanceof IndexAccumulation ) { return \"IndexAccumulationOp\" ; } else if ( op instanceof CustomOp ) { return \"CustomOp\" ; } else return \"Unknown Op calls\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a complex ndarray from the passed in indarray [CODESPLIT] @ Override public IComplexNDArray createComplex ( List < IComplexNDArray > arrs , int [ ] shape ) { return new ComplexNDArray ( arrs , shape ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate and return a new array based on the vertex id and weight initialization . [CODESPLIT] public INDArray storeAndAllocateNewArray ( ) { val shape = sameDiff . getShapeForVarName ( getVarName ( ) ) ; if ( getArr ( ) != null && Arrays . equals ( getArr ( ) . shape ( ) , shape ) ) return getArr ( ) ; if ( varName == null ) throw new ND4JIllegalStateException ( \"Unable to store array for null variable name!\" ) ; if ( shape == null ) { throw new ND4JIllegalStateException ( \"Unable to allocate new array. No shape found for variable \" + varName ) ; } val arr = getWeightInitScheme ( ) . create ( shape ) ; sameDiff . putArrayForVarName ( getVarName ( ) , arr ) ; return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A getter for the allocated ndarray with this { @link SDVariable } . [CODESPLIT] public INDArray getArr ( ) { if ( sameDiff . arrayAlreadyExistsForVarName ( getVarName ( ) ) ) return sameDiff . getArrForVarName ( getVarName ( ) ) ; //initialize value if it's actually a scalar constant (zero or 1 typically...) if ( getScalarValue ( ) != null && ArrayUtil . prod ( getShape ( ) ) == 1 ) { INDArray arr = Nd4j . valueArrayOf ( getShape ( ) , getScalarValue ( ) . doubleValue ( ) ) ; sameDiff . associateArrayWithVariable ( arr , this ) ; } else if ( sameDiff . getShapeForVarName ( getVarName ( ) ) == null ) return null ; else { INDArray newAlloc = getWeightInitScheme ( ) . create ( sameDiff . getShapeForVarName ( getVarName ( ) ) ) ; sameDiff . associateArrayWithVariable ( newAlloc , this ) ; } return sameDiff . getArrForVarName ( getVarName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the shape of this variable [CODESPLIT] public long [ ] getShape ( ) { long [ ] initialShape = sameDiff . getShapeForVarName ( getVarName ( ) ) ; if ( initialShape == null ) { val arr = getArr ( ) ; if ( arr != null ) return arr . shape ( ) ; } return initialShape ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate the result of this variable [CODESPLIT] public INDArray eval ( ) { SameDiff exec = sameDiff . dup ( ) ; exec . defineFunction ( \"output\" , new SameDiff . SameDiffFunctionDefinition ( ) { @ Override public SDVariable [ ] define ( SameDiff sameDiff , Map < String , INDArray > inputs , SDVariable [ ] variableInputs ) { return new SDVariable [ ] { SDVariable . this } ; } } ) ; SDVariable output = exec . invokeFunctionOn ( \"output\" , exec ) ; return output . getSameDiff ( ) . execAndEndResult ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method creates compressed INDArray from Java double array skipping usual INDArray instantiation routines [CODESPLIT] @ Override public INDArray compress ( double [ ] data , int [ ] shape , char order ) { DoublePointer pointer = new DoublePointer ( data ) ; DataBuffer shapeInfo = Nd4j . getShapeInfoProvider ( ) . createShapeInformation ( shape , order ) . getFirst ( ) ; DataBuffer buffer = compressPointer ( DataBuffer . TypeEx . DOUBLE , pointer , data . length , 8 ) ; return Nd4j . createArrayFromShapeBuffer ( buffer , shapeInfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the exponential of a complex ndarray [CODESPLIT] public static IComplexNDArray expi ( IComplexNDArray toExp ) { IComplexNDArray flattened = toExp . ravel ( ) ; for ( int i = 0 ; i < flattened . length ( ) ; i ++ ) { IComplexNumber n = flattened . getComplex ( i ) ; flattened . put ( i , Nd4j . scalar ( ComplexUtil . exp ( n ) ) ) ; } return flattened . reshape ( toExp . shape ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Center an array [CODESPLIT] public static IComplexNDArray center ( IComplexNDArray arr , long [ ] shape ) { if ( arr . length ( ) < ArrayUtil . prod ( shape ) ) return arr ; for ( int i = 0 ; i < shape . length ; i ++ ) if ( shape [ i ] < 1 ) shape [ i ] = 1 ; INDArray shapeMatrix = NDArrayUtil . toNDArray ( shape ) ; INDArray currShape = NDArrayUtil . toNDArray ( arr . shape ( ) ) ; INDArray startIndex = Transforms . floor ( currShape . sub ( shapeMatrix ) . divi ( Nd4j . scalar ( 2 ) ) ) ; INDArray endIndex = startIndex . add ( shapeMatrix ) ; INDArrayIndex [ ] indexes = Indices . createFromStartAndEnd ( startIndex , endIndex ) ; if ( shapeMatrix . length ( ) > 1 ) return arr . get ( indexes ) ; else { IComplexNDArray ret = Nd4j . createComplex ( new int [ ] { ( int ) shapeMatrix . getDouble ( 0 ) } ) ; int start = ( int ) startIndex . getDouble ( 0 ) ; int end = ( int ) endIndex . getDouble ( 0 ) ; int count = 0 ; for ( int i = start ; i < end ; i ++ ) { ret . putScalar ( count ++ , arr . getComplex ( i ) ) ; } return ret ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Truncates an ndarray to the specified shape . If the shape is the same or greater it just returns the original array [CODESPLIT] public static IComplexNDArray truncate ( IComplexNDArray nd , int n , int dimension ) { if ( nd . isVector ( ) ) { IComplexNDArray truncated = Nd4j . createComplex ( new int [ ] { 1 , n } ) ; for ( int i = 0 ; i < n ; i ++ ) truncated . putScalar ( i , nd . getComplex ( i ) ) ; return truncated ; } if ( nd . size ( dimension ) > n ) { long [ ] shape = ArrayUtil . copy ( nd . shape ( ) ) ; shape [ dimension ] = n ; IComplexNDArray ret = Nd4j . createComplex ( shape ) ; IComplexNDArray ndLinear = nd . linearView ( ) ; IComplexNDArray retLinear = ret . linearView ( ) ; for ( int i = 0 ; i < ret . length ( ) ; i ++ ) retLinear . putScalar ( i , ndLinear . getComplex ( i ) ) ; return ret ; } return nd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pads an ndarray with zeros [CODESPLIT] public static IComplexNDArray padWithZeros ( IComplexNDArray nd , long [ ] targetShape ) { if ( Arrays . equals ( nd . shape ( ) , targetShape ) ) return nd ; //no padding required if ( ArrayUtil . prod ( nd . shape ( ) ) >= ArrayUtil . prod ( targetShape ) ) return nd ; IComplexNDArray ret = Nd4j . createComplex ( targetShape ) ; INDArrayIndex [ ] targetShapeIndex = NDArrayIndex . createCoveringShape ( nd . shape ( ) ) ; ret . put ( targetShapeIndex , nd ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the index of the element with maximum absolute value [CODESPLIT] @ Override public int iamax ( INDArray arr ) { switch ( arr . data ( ) . dataType ( ) ) { case DOUBLE : DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , arr ) ; return idamax ( arr . length ( ) , arr , 1 ) ; case FLOAT : DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , arr ) ; return isamax ( arr . length ( ) , arr , 1 ) ; case HALF : DefaultOpExecutioner . validateDataType ( DataBuffer . Type . HALF , arr ) ; return ihamax ( arr . length ( ) , arr , 1 ) ; default : } throw new UnsupportedOperationException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method duplicates array and stores it to all devices [CODESPLIT] public void broadcast ( INDArray array ) { if ( array == null ) return ; Nd4j . getExecutioner ( ) . commit ( ) ; int numDevices = Nd4j . getAffinityManager ( ) . getNumberOfDevices ( ) ; for ( int i = 0 ; i < numDevices ; i ++ ) { // if current thread equal to this device - we just save it, without duplication if ( Nd4j . getAffinityManager ( ) . getDeviceForCurrentThread ( ) == i ) { set ( i , array ) ; } else { set ( i , Nd4j . getAffinityManager ( ) . replicateToDevice ( i , array ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will be started in context of executor either Shard Client or Backup node [CODESPLIT] @ Override public void processMessage ( ) { VectorAggregation aggregation = new VectorAggregation ( rowIndex , ( short ) voidConfiguration . getNumberOfShards ( ) , shardIndex , storage . getArray ( key ) . getRow ( rowIndex ) . dup ( ) ) ; aggregation . setOriginatorId ( this . getOriginatorId ( ) ) ; transport . sendMessage ( aggregation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Euler’s constant . [CODESPLIT] static public BigDecimal pi ( final MathContext mc ) { /* look it up if possible */ if ( mc . getPrecision ( ) < PI . precision ( ) ) { return PI . round ( mc ) ; } else { /* Broadhurst \\protect\\vrule width0pt\\protect\\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}\n             */ int [ ] a = { 1 , 0 , 0 , - 1 , - 1 , - 1 , 0 , 0 } ; BigDecimal S = broadhurstBBP ( 1 , 1 , a , mc ) ; return multiplyRound ( S , 8 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Euler - Mascheroni constant . [CODESPLIT] static public BigDecimal gamma ( MathContext mc ) { /* look it up if possible */ if ( mc . getPrecision ( ) < GAMMA . precision ( ) ) { return GAMMA . round ( mc ) ; } else { double eps = prec2err ( 0.577 , mc . getPrecision ( ) ) ; /* Euler-Stieltjes as shown in Dilcher, Aequat Math 48 (1) (1994) 55-85\n            14\n             */ MathContext mcloc = new MathContext ( 2 + mc . getPrecision ( ) ) ; BigDecimal resul = BigDecimal . ONE ; resul = resul . add ( log ( 2 , mcloc ) ) ; resul = resul . subtract ( log ( 3 , mcloc ) ) ; /* how many terms: zeta-1 falls as 1/2^(2n+1), so the\n             * terms drop faster than 1/2^(4n+2). Set 1/2^(4kmax+2) < eps.\n             * Leading term zeta(3)/(4^1*3) is 0.017. Leading zeta(3) is 1.2. Log(2) is 0.7\n             */ int kmax = ( int ) ( ( Math . log ( eps / 0.7 ) - 2. ) / 4. ) ; mcloc = new MathContext ( 1 + err2prec ( 1.2 , eps / kmax ) ) ; for ( int n = 1 ; ; n ++ ) { /* zeta is close to 1. Division of zeta-1 through\n                 * 4^n*(2n+1) means divion through roughly 2^(2n+1)\n                 */ BigDecimal c = zeta ( 2 * n + 1 , mcloc ) . subtract ( BigDecimal . ONE ) ; BigInteger fourn = BigInteger . valueOf ( 2 * n + 1 ) ; fourn = fourn . shiftLeft ( 2 * n ) ; c = divideRound ( c , fourn ) ; resul = resul . subtract ( c ) ; if ( c . doubleValue ( ) < 0.1 * eps ) { break ; } } return resul . round ( mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The square root . [CODESPLIT] static public BigDecimal sqrt ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( \"negative argument \" + x . toString ( ) + \" of square root\" ) ; } return root ( 2 , x ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The cube root . [CODESPLIT] static public BigDecimal cbrt ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return root ( 3 , x . negate ( ) ) . negate ( ) ; } else { return root ( 3 , x ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The integer root . [CODESPLIT] static public BigDecimal root ( final int n , final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( \"negative argument \" + x . toString ( ) + \" of root\" ) ; } if ( n <= 0 ) { throw new ArithmeticException ( \"negative power \" + n + \" of root\" ) ; } if ( n == 1 ) { return x ; } /* start the computation from a double precision estimate */ BigDecimal s = new BigDecimal ( Math . pow ( x . doubleValue ( ) , 1.0 / n ) ) ; /* this creates nth with nominal precision of 1 digit\n         */ final BigDecimal nth = new BigDecimal ( n ) ; /* Specify an internal accuracy within the loop which is\n         * slightly larger than what is demanded by ’eps’ below.\n         */ final BigDecimal xhighpr = scalePrec ( x , 2 ) ; MathContext mc = new MathContext ( 2 + x . precision ( ) ) ; /* Relative accuracy of the result is eps.\n         */ final double eps = x . ulp ( ) . doubleValue ( ) / ( 2 * n * x . doubleValue ( ) ) ; for ( ; ; ) { /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being\n             * smaller than the precision requested. The relative correction is (1-x/s^n)/n,\n             */ BigDecimal c = xhighpr . divide ( s . pow ( n - 1 ) , mc ) ; c = s . subtract ( c ) ; MathContext locmc = new MathContext ( c . precision ( ) ) ; c = c . divide ( nth , locmc ) ; s = s . subtract ( c ) ; if ( Math . abs ( c . doubleValue ( ) / s . doubleValue ( ) ) < eps ) { break ; } } return s . round ( new MathContext ( err2prec ( eps ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The hypotenuse . [CODESPLIT] static public BigDecimal hypot ( final BigDecimal x , final BigDecimal y ) { /* compute x^2+y^2\n         */ BigDecimal z = x . pow ( 2 ) . add ( y . pow ( 2 ) ) ; /* truncate to the precision set by x and y. Absolute error = 2*x*xerr+2*y*yerr,\n         * where the two errors are 1/2 of the ulp’s. Two intermediate protectio digits.\n         */ BigDecimal zerr = x . abs ( ) . multiply ( x . ulp ( ) ) . add ( y . abs ( ) . multiply ( y . ulp ( ) ) ) ; MathContext mc = new MathContext ( 2 + err2prec ( z , zerr ) ) ; /* Pull square root */ z = sqrt ( z . round ( mc ) ) ; /* Final rounding. Absolute error in the square root is (y*yerr+x*xerr)/z, where zerr holds 2*(x*xerr+y*yerr).\n         */ mc = new MathContext ( err2prec ( z . doubleValue ( ) , 0.5 * zerr . doubleValue ( ) / z . doubleValue ( ) ) ) ; return z . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The hypotenuse . [CODESPLIT] static public BigDecimal hypot ( final int n , final BigDecimal x ) { /* compute n^2+x^2 in infinite precision\n         */ BigDecimal z = ( new BigDecimal ( n ) ) . pow ( 2 ) . add ( x . pow ( 2 ) ) ; /* Truncate to the precision set by x. Absolute error = in z (square of the result) is |2*x*xerr|,\n         * where the error is 1/2 of the ulp. Two intermediate protection digits.\n         * zerr is a signed value, but used only in conjunction with err2prec(), so this feature does not harm.\n         */ double zerr = x . doubleValue ( ) * x . ulp ( ) . doubleValue ( ) ; MathContext mc = new MathContext ( 2 + err2prec ( z . doubleValue ( ) , zerr ) ) ; /* Pull square root */ z = sqrt ( z . round ( mc ) ) ; /* Final rounding. Absolute error in the square root is x*xerr/z, where zerr holds 2*x*xerr.\n         */ mc = new MathContext ( err2prec ( z . doubleValue ( ) , 0.5 * zerr / z . doubleValue ( ) ) ) ; return z . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The exponential function . [CODESPLIT] static public BigDecimal exp ( BigDecimal x ) { /* To calculate the value if x is negative, use exp(-x) = 1/exp(x)\n         */ if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { final BigDecimal invx = exp ( x . negate ( ) ) ; /* Relative error in inverse of invx is the same as the relative errror in invx.\n             * This is used to define the precision of the result.\n             */ MathContext mc = new MathContext ( invx . precision ( ) ) ; return BigDecimal . ONE . divide ( invx , mc ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { /* recover the valid number of digits from x.ulp(), if x hits the\n             * zero. The x.precision() is 1 then, and does not provide this information.\n             */ return scalePrec ( BigDecimal . ONE , - ( int ) ( Math . log10 ( x . ulp ( ) . doubleValue ( ) ) ) ) ; } else { /* Push the number in the Taylor expansion down to a small\n             * value where TAYLOR_NTERM terms will do. If x<1, the n-th term is of the order\n             * x^n/n!, and equal to both the absolute and relative error of the result\n             * since the result is close to 1. The x.ulp() sets the relative and absolute error\n             * of the result, as estimated from the first Taylor term.\n             * We want x^TAYLOR_NTERM/TAYLOR_NTERM! < x.ulp, which is guaranteed if\n             * x^TAYLOR_NTERM < TAYLOR_NTERM*(TAYLOR_NTERM-1)*...*x.ulp.\n             */ final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; if ( Math . pow ( xDbl , TAYLOR_NTERM ) < TAYLOR_NTERM * ( TAYLOR_NTERM - 1.0 ) * ( TAYLOR_NTERM - 2.0 ) * xUlpDbl ) { /* Add TAYLOR_NTERM terms of the Taylor expansion (Euler’s sum formula)\n                 */ BigDecimal resul = BigDecimal . ONE ; /* x^i */ BigDecimal xpowi = BigDecimal . ONE ; /* i factorial */ BigInteger ifac = BigInteger . ONE ; /* TAYLOR_NTERM terms to be added means we move x.ulp() to the right\n                 * for each power of 10 in TAYLOR_NTERM, so the addition won’t add noise beyond\n                 * what’s already in x.\n                 */ MathContext mcTay = new MathContext ( err2prec ( 1. , xUlpDbl / TAYLOR_NTERM ) ) ; for ( int i = 1 ; i <= TAYLOR_NTERM ; i ++ ) { ifac = ifac . multiply ( BigInteger . valueOf ( i ) ) ; xpowi = xpowi . multiply ( x ) ; final BigDecimal c = xpowi . divide ( new BigDecimal ( ifac ) , mcTay ) ; resul = resul . add ( c ) ; if ( Math . abs ( xpowi . doubleValue ( ) ) < i && Math . abs ( c . doubleValue ( ) ) < 0.5 * xUlpDbl ) { break ; } } /* exp(x+deltax) = exp(x)(1+deltax) if deltax is <<1. So the relative error\n                 * in the result equals the absolute error in the argument.\n                 */ MathContext mc = new MathContext ( err2prec ( xUlpDbl / 2. ) ) ; return resul . round ( mc ) ; } else { /* Compute exp(x) = (exp(0.1*x))^10. Division by 10 does not lead\n                 * to loss of accuracy.\n                 */ int exSc = ( int ) ( 1.0 - Math . log10 ( TAYLOR_NTERM * ( TAYLOR_NTERM - 1.0 ) * ( TAYLOR_NTERM - 2.0 ) * xUlpDbl / Math . pow ( xDbl , TAYLOR_NTERM ) ) / ( TAYLOR_NTERM - 1.0 ) ) ; BigDecimal xby10 = x . scaleByPowerOfTen ( - exSc ) ; BigDecimal expxby10 = exp ( xby10 ) ; /* Final powering by 10 means that the relative error of the result\n                 * is 10 times the relative error of the base (First order binomial expansion).\n                 * This looses one digit.\n                 */ MathContext mc = new MathContext ( expxby10 . precision ( ) - exSc ) ; /* Rescaling the powers of 10 is done in chunks of a maximum of 8 to avoid an invalid operation\n                17\n                 * response by the BigDecimal.pow library or integer overflow.\n                 */ while ( exSc > 0 ) { int exsub = Math . min ( 8 , exSc ) ; exSc -= exsub ; MathContext mctmp = new MathContext ( expxby10 . precision ( ) - exsub + 2 ) ; int pex = 1 ; while ( exsub -- > 0 ) { pex *= 10 ; } expxby10 = expxby10 . pow ( pex , mctmp ) ; } return expxby10 . round ( mc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The base of the natural logarithm . [CODESPLIT] static public BigDecimal exp ( final MathContext mc ) { /* look it up if possible */ if ( mc . getPrecision ( ) < E . precision ( ) ) { return E . round ( mc ) ; } else { /* Instantiate a 1.0 with the requested pseudo-accuracy\n             * and delegate the computation to the public method above.\n             */ BigDecimal uni = scalePrec ( BigDecimal . ONE , mc . getPrecision ( ) ) ; return exp ( uni ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The natural logarithm . [CODESPLIT] static public BigDecimal log ( BigDecimal x ) { /* the value is undefined if x is negative.\n         */ if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( \"Cannot take log of negative \" + x . toString ( ) ) ; } else if ( x . compareTo ( BigDecimal . ONE ) == 0 ) { /* log 1. = 0. */ return scalePrec ( BigDecimal . ZERO , x . precision ( ) - 1 ) ; } else if ( Math . abs ( x . doubleValue ( ) - 1.0 ) <= 0.3 ) { /* The standard Taylor series around x=1, z=0, z=x-1. Abramowitz-Stegun 4.124.\n             * The absolute error is err(z)/(1+z) = err(x)/x.\n             */ BigDecimal z = scalePrec ( x . subtract ( BigDecimal . ONE ) , 2 ) ; BigDecimal zpown = z ; double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . abs ( x . doubleValue ( ) ) ; BigDecimal resul = z ; for ( int k = 2 ; ; k ++ ) { zpown = multiplyRound ( zpown , z ) ; BigDecimal c = divideRound ( zpown , k ) ; if ( k % 2 == 0 ) { resul = resul . subtract ( c ) ; } else { resul = resul . add ( c ) ; } if ( Math . abs ( c . doubleValue ( ) ) < eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } else { final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; /* Map log(x) = log root[r](x)^r = r*log( root[r](x)) with the aim\n             * to move roor[r](x) near to 1.2 (that is, below the 0.3 appearing above), where log(1.2) is roughly 0.2.\n             */ int r = ( int ) ( Math . log ( xDbl ) / 0.2 ) ; /* Since the actual requirement is a function of the value 0.3 appearing above,\n             * we avoid the hypothetical case of endless recurrence by ensuring that r >= 2.\n             */ r = Math . max ( 2 , r ) ; /* Compute r-th root with 2 additional digits of precision\n             */ BigDecimal xhighpr = scalePrec ( x , 2 ) ; BigDecimal resul = root ( r , xhighpr ) ; resul = log ( resul ) . multiply ( new BigDecimal ( r ) ) ; /* error propagation: log(x+errx) = log(x)+errx/x, so the absolute error\n             * in the result equals the relative error in the input, xUlpDbl/xDbl .\n             */ MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , xUlpDbl / xDbl ) ) ; return resul . round ( mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The natural logarithm . [CODESPLIT] static public BigDecimal log ( int n , final MathContext mc ) { /* the value is undefined if x is negative.\n         */ if ( n <= 0 ) { throw new ArithmeticException ( \"Cannot take log of negative \" + n ) ; } else if ( n == 1 ) { return BigDecimal . ZERO ; } else if ( n == 2 ) { if ( mc . getPrecision ( ) < LOG2 . precision ( ) ) { return LOG2 . round ( mc ) ; } else { /* Broadhurst \\protect\\vrule width0pt\\protect\\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}\n                 * Error propagation: the error in log(2) is twice the error in S(2,-5,...).\n                 */ int [ ] a = { 2 , - 5 , - 2 , - 7 , - 2 , - 5 , 2 , - 3 } ; BigDecimal S = broadhurstBBP ( 2 , 1 , a , new MathContext ( 1 + mc . getPrecision ( ) ) ) ; S = S . multiply ( new BigDecimal ( 8 ) ) ; S = sqrt ( divideRound ( S , 3 ) ) ; return S . round ( mc ) ; } } else if ( n == 3 ) { /* summation of a series roughly proportional to (7/500)^k. Estimate count\n             * of terms to estimate the precision (drop the favorable additional\n             * 1/k here): 0.013^k <= 10^(-precision), so k*log10(0.013) <= -precision\n             * so k>= precision/1.87.\n             */ int kmax = ( int ) ( mc . getPrecision ( ) / 1.87 ) ; MathContext mcloc = new MathContext ( mc . getPrecision ( ) + 1 + ( int ) ( Math . log10 ( kmax * 0.693 / 1.098 ) ) ) ; BigDecimal log3 = multiplyRound ( log ( 2 , mcloc ) , 19 ) ; /* log3 is roughly 1, so absolute and relative error are the same. The\n             * result will be divided by 12, so a conservative error is the one\n             * already found in mc\n             */ double eps = prec2err ( 1.098 , mc . getPrecision ( ) ) / kmax ; Rational r = new Rational ( 7153 , 524288 ) ; Rational pk = new Rational ( 7153 , 524288 ) ; for ( int k = 1 ; ; k ++ ) { Rational tmp = pk . divide ( k ) ; if ( tmp . doubleValue ( ) < eps ) { break ; } /* how many digits of tmp do we need in the sum?\n                 */ mcloc = new MathContext ( err2prec ( tmp . doubleValue ( ) , eps ) ) ; BigDecimal c = pk . divide ( k ) . BigDecimalValue ( mcloc ) ; if ( k % 2 != 0 ) { log3 = log3 . add ( c ) ; } else { log3 = log3 . subtract ( c ) ; } pk = pk . multiply ( r ) ; } log3 = divideRound ( log3 , 12 ) ; return log3 . round ( mc ) ; } else if ( n == 5 ) { /* summation of a series roughly proportional to (7/160)^k. Estimate count\n             * of terms to estimate the precision (drop the favorable additional\n             * 1/k here): 0.046^k <= 10^(-precision), so k*log10(0.046) <= -precision\n             * so k>= precision/1.33.\n             */ int kmax = ( int ) ( mc . getPrecision ( ) / 1.33 ) ; MathContext mcloc = new MathContext ( mc . getPrecision ( ) + 1 + ( int ) ( Math . log10 ( kmax * 0.693 / 1.609 ) ) ) ; BigDecimal log5 = multiplyRound ( log ( 2 , mcloc ) , 14 ) ; /* log5 is roughly 1.6, so absolute and relative error are the same. The\n             * result will be divided by 6, so a conservative error is the one\n             * already found in mc\n             */ double eps = prec2err ( 1.6 , mc . getPrecision ( ) ) / kmax ; Rational r = new Rational ( 759 , 16384 ) ; Rational pk = new Rational ( 759 , 16384 ) ; for ( int k = 1 ; ; k ++ ) { Rational tmp = pk . divide ( k ) ; if ( tmp . doubleValue ( ) < eps ) { break ; } /* how many digits of tmp do we need in the sum?\n                 */ mcloc = new MathContext ( err2prec ( tmp . doubleValue ( ) , eps ) ) ; BigDecimal c = pk . divide ( k ) . BigDecimalValue ( mcloc ) ; log5 = log5 . subtract ( c ) ; pk = pk . multiply ( r ) ; } log5 = divideRound ( log5 , 6 ) ; return log5 . round ( mc ) ; } else if ( n == 7 ) { /* summation of a series roughly proportional to (1/8)^k. Estimate count\n             * of terms to estimate the precision (drop the favorable additional\n             * 1/k here): 0.125^k <= 10^(-precision), so k*log10(0.125) <= -precision\n             * so k>= precision/0.903.\n             */ int kmax = ( int ) ( mc . getPrecision ( ) / 0.903 ) ; MathContext mcloc = new MathContext ( mc . getPrecision ( ) + 1 + ( int ) ( Math . log10 ( kmax * 3 * 0.693 / 1.098 ) ) ) ; BigDecimal log7 = multiplyRound ( log ( 2 , mcloc ) , 3 ) ; /* log7 is roughly 1.9, so absolute and relative error are the same.\n             */ double eps = prec2err ( 1.9 , mc . getPrecision ( ) ) / kmax ; Rational r = new Rational ( 1 , 8 ) ; Rational pk = new Rational ( 1 , 8 ) ; for ( int k = 1 ; ; k ++ ) { Rational tmp = pk . divide ( k ) ; if ( tmp . doubleValue ( ) < eps ) { break ; } /* how many digits of tmp do we need in the sum?\n                 */ mcloc = new MathContext ( err2prec ( tmp . doubleValue ( ) , eps ) ) ; BigDecimal c = pk . divide ( k ) . BigDecimalValue ( mcloc ) ; log7 = log7 . subtract ( c ) ; pk = pk . multiply ( r ) ; } return log7 . round ( mc ) ; } else { /* At this point one could either forward to the log(BigDecimal) signature (implemented)\n             * or decompose n into Ifactors and use an implemenation of all the prime bases.\n             * Estimate of the result; convert the mc argument to an absolute error eps\n             * log(n+errn) = log(n)+errn/n = log(n)+eps\n             */ double res = Math . log ( ( double ) n ) ; double eps = prec2err ( res , mc . getPrecision ( ) ) ; /* errn = eps*n, convert absolute error in result to requirement on absolute error in input\n             */ eps *= n ; /* Convert this absolute requirement of error in n to a relative error in n\n             */ final MathContext mcloc = new MathContext ( 1 + err2prec ( ( double ) n , eps ) ) ; /* Padd n with a number of zeros to trigger the required accuracy in\n             * the standard signature method\n             */ BigDecimal nb = scalePrec ( new BigDecimal ( n ) , mcloc ) ; return log ( nb ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The natural logarithm . [CODESPLIT] static public BigDecimal log ( final Rational r , final MathContext mc ) { /* the value is undefined if x is negative.\n         */ if ( r . compareTo ( Rational . ZERO ) <= 0 ) { throw new ArithmeticException ( \"Cannot take log of negative \" + r . toString ( ) ) ; } else if ( r . compareTo ( Rational . ONE ) == 0 ) { return BigDecimal . ZERO ; } else { /* log(r+epsr) = log(r)+epsr/r. Convert the precision to an absolute error in the result.\n             * eps contains the required absolute error of the result, epsr/r.\n             */ double eps = prec2err ( Math . log ( r . doubleValue ( ) ) , mc . getPrecision ( ) ) ; /* Convert this further into a requirement of the relative precision in r, given that\n             * epsr/r is also the relative precision of r. Add one safety digit.\n             */ MathContext mcloc = new MathContext ( 1 + err2prec ( eps ) ) ; final BigDecimal resul = log ( r . BigDecimalValue ( mcloc ) ) ; return resul . round ( mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Power function . [CODESPLIT] static public BigDecimal pow ( final BigDecimal x , final BigDecimal y ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { throw new ArithmeticException ( \"Cannot power negative \" + x . toString ( ) ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { /* return x^y = exp(y*log(x)) ;\n             */ BigDecimal logx = log ( x ) ; BigDecimal ylogx = y . multiply ( logx ) ; BigDecimal resul = exp ( ylogx ) ; /* The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x|\n             */ double errR = Math . abs ( logx . doubleValue ( ) * y . ulp ( ) . doubleValue ( ) / 2. ) + Math . abs ( y . doubleValue ( ) * x . ulp ( ) . doubleValue ( ) / 2. / x . doubleValue ( ) ) ; MathContext mcR = new MathContext ( err2prec ( 1.0 , errR ) ) ; return resul . round ( mcR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Raise to an integer power and round . [CODESPLIT] static public BigDecimal powRound ( final BigDecimal x , final int n ) { /* The relative error in the result is n times the relative error in the input.\n         * The estimation is slightly optimistic due to the integer rounding of the logarithm.\n         */ MathContext mc = new MathContext ( x . precision ( ) - ( int ) Math . log10 ( ( double ) ( Math . abs ( n ) ) ) ) ; return x . pow ( n , mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trigonometric sine . [CODESPLIT] static public BigDecimal sin ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return sin ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { /* reduce modulo 2pi\n             */ BigDecimal res = mod2pi ( x ) ; double errpi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) ) ; int val = 2 + err2prec ( FastMath . PI , errpi ) ; MathContext mc = new MathContext ( val ) ; BigDecimal p = pi ( mc ) ; mc = new MathContext ( x . precision ( ) ) ; if ( res . compareTo ( p ) > 0 ) { /* pi<x<=2pi: sin(x)= - sin(x-pi)\n                 */ return sin ( subtractRound ( res , p ) ) . negate ( ) ; } else if ( res . multiply ( new BigDecimal ( 2 ) ) . compareTo ( p ) > 0 ) { /* pi/2<x<=pi: sin(x)= sin(pi-x)\n                 */ return sin ( subtractRound ( p , res ) ) ; } else { /* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x)\n                 * to split this further. Here, use the sine up to pi/4 and the cosine higher up.\n                 */ if ( res . multiply ( new BigDecimal ( 4 ) ) . compareTo ( p ) > 0 ) { /* x>pi/4: sin(x) = cos(pi/2-x)\n                     */ return cos ( subtractRound ( p . divide ( new BigDecimal ( 2 ) ) , res ) ) ; } else { /* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */ BigDecimal resul = res ; /* x^i */ BigDecimal xpowi = res ; /* 2i+1 factorial */ BigInteger ifac = BigInteger . ONE ; /* The error in the result is set by the error in x itself.\n                     */ double xUlpDbl = res . ulp ( ) . doubleValue ( ) ; /* The error in the result is set by the error in x itself.\n                     * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.\n                     * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;\n                     * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision\n                     */ int k = ( int ) ( res . precision ( ) / Math . log10 ( 1.0 / res . doubleValue ( ) ) ) / 2 ; MathContext mcTay = new MathContext ( err2prec ( res . doubleValue ( ) , xUlpDbl / k ) ) ; for ( int i = 1 ; ; i ++ ) { /* TBD: at which precision will 2*i or 2*i+1 overflow?\n                         */ ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i ) ) ; ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i + 1 ) ) ; xpowi = xpowi . multiply ( res ) . multiply ( res ) . negate ( ) ; BigDecimal corr = xpowi . divide ( new BigDecimal ( ifac ) , mcTay ) ; resul = resul . add ( corr ) ; if ( corr . abs ( ) . doubleValue ( ) < 0.5 * xUlpDbl ) { break ; } } /* The error in the result is set by the error in x itself.\n                     */ mc = new MathContext ( res . precision ( ) ) ; return resul . round ( mc ) ; } } } /* sin */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The trigonometric tangent . [CODESPLIT] static public BigDecimal tan ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return tan ( x . negate ( ) ) . negate ( ) ; } else { /* reduce modulo pi\n             */ BigDecimal res = modpi ( x ) ; /* absolute error in the result is err(x)/cos^2(x) to lowest order\n             */ final double xDbl = res . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) / 2. ; final double eps = xUlpDbl / 2. / Math . pow ( Math . cos ( xDbl ) , 2. ) ; if ( xDbl > 0.8 ) { /* tan(x) = 1/cot(x) */ BigDecimal co = cot ( x ) ; MathContext mc = new MathContext ( err2prec ( 1. / co . doubleValue ( ) , eps ) ) ; return BigDecimal . ONE . divide ( co , mc ) ; } else { final BigDecimal xhighpr = scalePrec ( res , 2 ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) ; BigDecimal result = xhighpr . plus ( ) ; /* x^(2i+1) */ BigDecimal xpowi = xhighpr ; Bernoulli b = new Bernoulli ( ) ; /* 2^(2i) */ BigInteger fourn = BigInteger . valueOf ( 4 ) ; /* (2i)! */ BigInteger fac = BigInteger . valueOf ( 2 ) ; for ( int i = 2 ; ; i ++ ) { Rational f = b . at ( 2 * i ) . abs ( ) ; fourn = fourn . shiftLeft ( 2 ) ; fac = fac . multiply ( BigInteger . valueOf ( 2 * i ) ) . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; f = f . multiply ( fourn ) . multiply ( fourn . subtract ( BigInteger . ONE ) ) . divide ( fac ) ; xpowi = multiplyRound ( xpowi , xhighprSq ) ; BigDecimal c = multiplyRound ( xpowi , f ) ; result = result . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( result . doubleValue ( ) , eps ) ) ; return result . round ( mc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The inverse trigonometric sine . [CODESPLIT] static public BigDecimal asin ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ONE ) > 0 || x . compareTo ( BigDecimal . ONE . negate ( ) ) < 0 ) { throw new ArithmeticException ( \"Out of range argument \" + x . toString ( ) + \" of asin\" ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else if ( x . compareTo ( BigDecimal . ONE ) == 0 ) { /* arcsin(1) = pi/2\n             */ double errpi = Math . sqrt ( x . ulp ( ) . doubleValue ( ) ) ; MathContext mc = new MathContext ( err2prec ( 3.14159 , errpi ) ) ; return pi ( mc ) . divide ( new BigDecimal ( 2 ) ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return asin ( x . negate ( ) ) . negate ( ) ; } else if ( x . doubleValue ( ) > 0.7 ) { final BigDecimal xCompl = BigDecimal . ONE . subtract ( x ) ; final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) / 2. ; final double eps = xUlpDbl / 2. / Math . sqrt ( 1. - Math . pow ( xDbl , 2. ) ) ; final BigDecimal xhighpr = scalePrec ( xCompl , 3 ) ; final BigDecimal xhighprV = divideRound ( xhighpr , 4 ) ; BigDecimal resul = BigDecimal . ONE ; /* x^(2i+1) */ BigDecimal xpowi = BigDecimal . ONE ; /* i factorial */ BigInteger ifacN = BigInteger . ONE ; BigInteger ifacD = BigInteger . ONE ; for ( int i = 1 ; ; i ++ ) { ifacN = ifacN . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; ifacD = ifacD . multiply ( BigInteger . valueOf ( i ) ) ; if ( i == 1 ) { xpowi = xhighprV ; } else { xpowi = multiplyRound ( xpowi , xhighprV ) ; } BigDecimal c = divideRound ( multiplyRound ( xpowi , ifacN ) , ifacD . multiply ( BigInteger . valueOf ( 2 * i + 1 ) ) ) ; resul = resul . add ( c ) ; /* series started 1+x/12+... which yields an estimate of the sum’s error\n                 */ if ( Math . abs ( c . doubleValue ( ) ) < xUlpDbl / 120. ) { break ; } } /* sqrt(2*z)*(1+...)\n             */ xpowi = sqrt ( xhighpr . multiply ( new BigDecimal ( 2 ) ) ) ; resul = multiplyRound ( xpowi , resul ) ; MathContext mc = new MathContext ( resul . precision ( ) ) ; BigDecimal pihalf = pi ( mc ) . divide ( new BigDecimal ( 2 ) ) ; mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return pihalf . subtract ( resul , mc ) ; } else { /* absolute error in the result is err(x)/sqrt(1-x^2) to lowest order\n             */ final double xDbl = x . doubleValue ( ) ; final double xUlpDbl = x . ulp ( ) . doubleValue ( ) / 2. ; final double eps = xUlpDbl / 2. / Math . sqrt ( 1. - Math . pow ( xDbl , 2. ) ) ; final BigDecimal xhighpr = scalePrec ( x , 2 ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) ; BigDecimal resul = xhighpr . plus ( ) ; /* x^(2i+1) */ BigDecimal xpowi = xhighpr ; /* i factorial */ BigInteger ifacN = BigInteger . ONE ; BigInteger ifacD = BigInteger . ONE ; for ( int i = 1 ; ; i ++ ) { ifacN = ifacN . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; ifacD = ifacD . multiply ( BigInteger . valueOf ( 2 * i ) ) ; xpowi = multiplyRound ( xpowi , xhighprSq ) ; BigDecimal c = divideRound ( multiplyRound ( xpowi , ifacN ) , ifacD . multiply ( BigInteger . valueOf ( 2 * i + 1 ) ) ) ; resul = resul . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The inverse trigonometric tangent . [CODESPLIT] static public BigDecimal atan ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return atan ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else if ( x . doubleValue ( ) > 0.7 && x . doubleValue ( ) < 3.0 ) { /* Abramowitz-Stegun 4.4.34 convergence acceleration\n             * 2*arctan(x) = arctan(2x/(1-x^2)) = arctan(y). x=(sqrt(1+y^2)-1)/y\n             * This maps 0<=y<=3 to 0<=x<=0.73 roughly. Temporarily with 2 protectionist digits.\n             */ BigDecimal y = scalePrec ( x , 2 ) ; BigDecimal newx = divideRound ( hypot ( 1 , y ) . subtract ( BigDecimal . ONE ) , y ) ; /* intermediate result with too optimistic error estimate*/ BigDecimal resul = multiplyRound ( atan ( newx ) , 2 ) ; /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp. */ double eps = x . ulp ( ) . doubleValue ( ) / ( 2.0 * Math . hypot ( 1.0 , x . doubleValue ( ) ) ) ; MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } else if ( x . doubleValue ( ) < 0.71 ) { /* Taylor expansion around x=0; Abramowitz-Stegun 4.4.42 */ final BigDecimal xhighpr = scalePrec ( x , 2 ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) . negate ( ) ; BigDecimal resul = xhighpr . plus ( ) ; /* signed x^(2i+1) */ BigDecimal xpowi = xhighpr ; /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp.\n             */ double eps = x . ulp ( ) . doubleValue ( ) / ( 2.0 * Math . hypot ( 1.0 , x . doubleValue ( ) ) ) ; for ( int i = 1 ; ; i ++ ) { xpowi = multiplyRound ( xpowi , xhighprSq ) ; BigDecimal c = divideRound ( xpowi , 2 * i + 1 ) ; resul = resul . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } } MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } else { /* Taylor expansion around x=infinity; Abramowitz-Stegun 4.4.42 */ /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp.\n             */ double eps = x . ulp ( ) . doubleValue ( ) / ( 2.0 * Math . hypot ( 1.0 , x . doubleValue ( ) ) ) ; /* start with the term pi/2; gather its precision relative to the expected result\n             */ MathContext mc = new MathContext ( 2 + err2prec ( 3.1416 , eps ) ) ; BigDecimal onepi = pi ( mc ) ; BigDecimal resul = onepi . divide ( new BigDecimal ( 2 ) ) ; final BigDecimal xhighpr = divideRound ( - 1 , scalePrec ( x , 2 ) ) ; final BigDecimal xhighprSq = multiplyRound ( xhighpr , xhighpr ) . negate ( ) ; /* signed x^(2i+1) */ BigDecimal xpowi = xhighpr ; for ( int i = 0 ; ; i ++ ) { BigDecimal c = divideRound ( xpowi , 2 * i + 1 ) ; resul = resul . add ( c ) ; if ( Math . abs ( c . doubleValue ( ) ) < 0.1 * eps ) { break ; } xpowi = multiplyRound ( xpowi , xhighprSq ) ; } mc = new MathContext ( err2prec ( resul . doubleValue ( ) , eps ) ) ; return resul . round ( mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The hyperbolic cosine . [CODESPLIT] static public BigDecimal cosh ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return cos ( x . negate ( ) ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ONE ; } else { if ( x . doubleValue ( ) > 1.5 ) { /* cosh^2(x) = 1+ sinh^2(x).\n                 */ return hypot ( 1 , sinh ( x ) ) ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */ BigDecimal resul = BigDecimal . ONE ; /* x^i */ BigDecimal xpowi = BigDecimal . ONE ; /* 2i factorial */ BigInteger ifac = BigInteger . ONE ; /* The absolute error in the result is the error in x^2/2 which is x times the error in x.\n                 */ double xUlpDbl = 0.5 * x . ulp ( ) . doubleValue ( ) * x . doubleValue ( ) ; /* The error in the result is set by the error in x^2/2 itself, xUlpDbl.\n                 * We need at most k terms to push x^(2k)/(2k)! below this value.\n                 * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl);\n                 */ int k = ( int ) ( Math . log ( xUlpDbl ) / Math . log ( x . doubleValue ( ) ) ) / 2 ; /* The individual terms are all smaller than 1, so an estimate of 1.0 for\n                 * the absolute value will give a safe relative error estimate for the indivdual terms\n                 */ MathContext mcTay = new MathContext ( err2prec ( 1. , xUlpDbl / k ) ) ; for ( int i = 1 ; ; i ++ ) { /* TBD: at which precision will 2*i-1 or 2*i overflow?\n                     */ ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i - 1 ) ) ; ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i ) ) ; xpowi = xpowi . multiply ( xhighpr ) . multiply ( xhighpr ) ; BigDecimal corr = xpowi . divide ( new BigDecimal ( ifac ) , mcTay ) ; resul = resul . add ( corr ) ; if ( corr . abs ( ) . doubleValue ( ) < 0.5 * xUlpDbl ) { break ; } } /* The error in the result is governed by the error in x itself.\n                  */ MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , xUlpDbl ) ) ; return resul . round ( mc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The hyperbolic sine . [CODESPLIT] static public BigDecimal sinh ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return sinh ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { if ( x . doubleValue ( ) > 2.4 ) { /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x).\n                 */ BigDecimal two = new BigDecimal ( 2 ) ; BigDecimal xhalf = x . divide ( two ) ; BigDecimal resul = sinh ( xhalf ) . multiply ( cosh ( xhalf ) ) . multiply ( two ) ; /* The error in the result is set by the error in x itself.\n                 * The first derivative of sinh(x) is cosh(x), so the absolute error\n                 * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x)\n                 */ double eps = Math . tanh ( x . doubleValue ( ) ) ; MathContext mc = new MathContext ( err2prec ( 0.5 * x . ulp ( ) . doubleValue ( ) / eps ) ) ; return resul . round ( mc ) ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */ BigDecimal resul = xhighpr ; /* x^i */ BigDecimal xpowi = xhighpr ; /* 2i+1 factorial */ BigInteger ifac = BigInteger . ONE ; /* The error in the result is set by the error in x itself.\n                 */ double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; /* The error in the result is set by the error in x itself.\n                 * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.\n                 * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;\n                 * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision\n                 */ int k = ( int ) ( x . precision ( ) / Math . log10 ( 1.0 / xhighpr . doubleValue ( ) ) ) / 2 ; MathContext mcTay = new MathContext ( err2prec ( x . doubleValue ( ) , xUlpDbl / k ) ) ; for ( int i = 1 ; ; i ++ ) { /* TBD: at which precision will 2*i or 2*i+1 overflow?\n                     */ ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i ) ) ; ifac = ifac . multiply ( BigInteger . valueOf ( 2 * i + 1 ) ) ; xpowi = xpowi . multiply ( xhighpr ) . multiply ( xhighpr ) ; BigDecimal corr = xpowi . divide ( new BigDecimal ( ifac ) , mcTay ) ; resul = resul . add ( corr ) ; if ( corr . abs ( ) . doubleValue ( ) < 0.5 * xUlpDbl ) { break ; } } /* The error in the result is set by the error in x itself.\n                  */ MathContext mc = new MathContext ( x . precision ( ) ) ; return resul . round ( mc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The hyperbolic tangent . [CODESPLIT] static public BigDecimal tanh ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return tanh ( x . negate ( ) ) . negate ( ) ; } else if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) .\n             */ BigDecimal exp2x = exp ( xhighpr . multiply ( new BigDecimal ( - 2 ) ) ) ; /* The error in tanh x is err(x)/cosh^2(x).\n             */ double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . pow ( Math . cosh ( x . doubleValue ( ) ) , 2.0 ) ; MathContext mc = new MathContext ( err2prec ( Math . tanh ( x . doubleValue ( ) ) , eps ) ) ; return BigDecimal . ONE . subtract ( exp2x ) . divide ( BigDecimal . ONE . add ( exp2x ) , mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The inverse hyperbolic sine . [CODESPLIT] static public BigDecimal asinh ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* arcsinh(x) = log(x+hypot(1,x))\n             */ BigDecimal logx = log ( hypot ( 1 , xhighpr ) . add ( xhighpr ) ) ; /* The absolute error in arcsinh x is err(x)/sqrt(1+x^2)\n             */ double xDbl = x . doubleValue ( ) ; double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . hypot ( 1. , xDbl ) ; MathContext mc = new MathContext ( err2prec ( logx . doubleValue ( ) , eps ) ) ; return logx . round ( mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The inverse hyperbolic cosine . [CODESPLIT] static public BigDecimal acosh ( final BigDecimal x ) { if ( x . compareTo ( BigDecimal . ONE ) < 0 ) { throw new ArithmeticException ( \"Out of range argument cosh \" + x . toString ( ) ) ; } else if ( x . compareTo ( BigDecimal . ONE ) == 0 ) { return BigDecimal . ZERO ; } else { BigDecimal xhighpr = scalePrec ( x , 2 ) ; /* arccosh(x) = log(x+sqrt(x^2-1))\n             */ BigDecimal logx = log ( sqrt ( xhighpr . pow ( 2 ) . subtract ( BigDecimal . ONE ) ) . add ( xhighpr ) ) ; /* The absolute error in arcsinh x is err(x)/sqrt(x^2-1)\n             */ double xDbl = x . doubleValue ( ) ; double eps = 0.5 * x . ulp ( ) . doubleValue ( ) / Math . sqrt ( xDbl * xDbl - 1. ) ; MathContext mc = new MathContext ( err2prec ( logx . doubleValue ( ) , eps ) ) ; return logx . round ( mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Gamma function . [CODESPLIT] static public BigDecimal Gamma ( final BigDecimal x ) { /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33\n         */ if ( x . compareTo ( BigDecimal . ZERO ) < 0 ) { return divideRound ( Gamma ( x . add ( BigDecimal . ONE ) ) , x ) ; } else if ( x . doubleValue ( ) > 1.5 ) { /* Gamma(x) = Gamma(xmin+n) = Gamma(xmin)*Pochhammer(xmin,n).\n             */ int n = ( int ) ( x . doubleValue ( ) - 0.5 ) ; BigDecimal xmin1 = x . subtract ( new BigDecimal ( n ) ) ; return multiplyRound ( Gamma ( xmin1 ) , pochhammer ( xmin1 , n ) ) ; } else { /* apply Abramowitz-Stegun 6.1.33\n             */ BigDecimal z = x . subtract ( BigDecimal . ONE ) ; /* add intermediately 2 digits to the partial sum accumulation\n             */ z = scalePrec ( z , 2 ) ; MathContext mcloc = new MathContext ( z . precision ( ) ) ; /* measure of the absolute error is the relative error in the first, logarithmic term\n             */ double eps = x . ulp ( ) . doubleValue ( ) / x . doubleValue ( ) ; BigDecimal resul = log ( scalePrec ( x , 2 ) ) . negate ( ) ; if ( x . compareTo ( BigDecimal . ONE ) != 0 ) { BigDecimal gammCompl = BigDecimal . ONE . subtract ( gamma ( mcloc ) ) ; resul = resul . add ( multiplyRound ( z , gammCompl ) ) ; for ( int n = 2 ; ; n ++ ) { /* multiplying z^n/n by zeta(n-1) means that the two relative errors add.\n                     * so the requirement in the relative error of zeta(n)-1 is that this is somewhat\n                     * smaller than the relative error in z^n/n (the absolute error of thelatter is the\n                     * absolute error in z)\n                     */ BigDecimal c = divideRound ( z . pow ( n , mcloc ) , n ) ; MathContext m = new MathContext ( err2prec ( n * z . ulp ( ) . doubleValue ( ) / 2. / z . doubleValue ( ) ) ) ; c = c . round ( m ) ; /* At larger n, zeta(n)-1 is roughly 1/2^n. The product is c/2^n.\n                     * The relative error in c is c.ulp/2/c . The error in the product should be small versus eps/10.\n                     * Error from 1/2^n is c*err(sigma-1).\n                     * We need a relative error of zeta-1 of the order of c.ulp/50/c. This is an absolute\n                     * error in zeta-1 of c.ulp/50/c/2^n, and also the absolute error in zeta, because zeta is\n                     * of the order of 1.\n                     */ if ( eps / 100. / c . doubleValue ( ) < 0.01 ) { m = new MathContext ( err2prec ( eps / 100. / c . doubleValue ( ) ) ) ; } else { m = new MathContext ( 2 ) ; } /* zeta(n) -1 */ BigDecimal zetm1 = zeta ( n , m ) . subtract ( BigDecimal . ONE ) ; c = multiplyRound ( c , zetm1 ) ; if ( n % 2 == 0 ) { resul = resul . add ( c ) ; } else { resul = resul . subtract ( c ) ; } /* alternating sum, so truncating as eps is reached suffices\n                     */ if ( Math . abs ( c . doubleValue ( ) ) < eps ) { break ; } } } /* The relative error in the result is the absolute error in the\n             * input variable times the digamma (psi) value at that point.\n             */ double psi = 0.5772156649 ; double zdbl = z . doubleValue ( ) ; for ( int n = 1 ; n < 5 ; n ++ ) { psi += zdbl / n / ( n + zdbl ) ; } eps = psi * x . ulp ( ) . doubleValue ( ) / 2. ; mcloc = new MathContext ( err2prec ( eps ) ) ; return exp ( resul ) . round ( mcloc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pochhammer’s function . [CODESPLIT] static public BigDecimal pochhammer ( final BigDecimal x , final int n ) { /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33\n         */ if ( n < 0 ) { throw new ProviderException ( \"Unimplemented pochhammer with negative index \" + n ) ; } else if ( n == 0 ) { return BigDecimal . ONE ; } else { /* internally two safety digits\n             */ BigDecimal xhighpr = scalePrec ( x , 2 ) ; BigDecimal resul = xhighpr ; double xUlpDbl = x . ulp ( ) . doubleValue ( ) ; double xDbl = x . doubleValue ( ) ; /* relative error of the result is the sum of the relative errors of the factors\n             */ double eps = 0.5 * xUlpDbl / Math . abs ( xDbl ) ; for ( int i = 1 ; i < n ; i ++ ) { eps += 0.5 * xUlpDbl / Math . abs ( xDbl + i ) ; resul = resul . multiply ( xhighpr . add ( new BigDecimal ( i ) ) ) ; final MathContext mcloc = new MathContext ( 4 + err2prec ( eps ) ) ; resul = resul . round ( mcloc ) ; } return resul . round ( new MathContext ( err2prec ( eps ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduce value to the interval [ 0 2 * Pi ] . [CODESPLIT] static public BigDecimal mod2pi ( BigDecimal x ) { /* write x= 2*pi*k+r with the precision in r defined by the precision of x and not\n         * compromised by the precision of 2*pi, so the ulp of 2*pi*k should match the ulp of x.\n         * First getFloat a guess of k to figure out how many digits of 2*pi are needed.\n         */ int k = ( int ) ( 0.5 * x . doubleValue ( ) / Math . PI ) ; /* want to have err(2*pi*k)< err(x)=0.5*x.ulp, so err(pi) = err(x)/(4k) with two safety digits\n         */ double err2pi ; if ( k != 0 ) { err2pi = 0.25 * Math . abs ( x . ulp ( ) . doubleValue ( ) / k ) ; } else { err2pi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) ) ; } MathContext mc = new MathContext ( 2 + err2prec ( 6.283 , err2pi ) ) ; BigDecimal twopi = pi ( mc ) . multiply ( new BigDecimal ( 2 ) ) ; /* Delegate the actual operation to the BigDecimal class, which may return\n         * a negative value of x was negative .\n         */ BigDecimal res = x . remainder ( twopi ) ; if ( res . compareTo ( BigDecimal . ZERO ) < 0 ) { res = res . add ( twopi ) ; } /* The actual precision is set by the input value, its absolute value of x.ulp()/2.\n         */ mc = new MathContext ( err2prec ( res . doubleValue ( ) , x . ulp ( ) . doubleValue ( ) / 2. ) ) ; return res . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduce value to the interval [ - Pi / 2 Pi / 2 ] . [CODESPLIT] static public BigDecimal modpi ( BigDecimal x ) { /* write x= pi*k+r with the precision in r defined by the precision of x and not\n         * compromised by the precision of pi, so the ulp of pi*k should match the ulp of x.\n         * First getFloat a guess of k to figure out how many digits of pi are needed.\n         */ int k = ( int ) ( x . doubleValue ( ) / Math . PI ) ; /* want to have err(pi*k)< err(x)=x.ulp/2, so err(pi) = err(x)/(2k) with two safety digits\n         */ double errpi ; if ( k != 0 ) { errpi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) / k ) ; } else { errpi = 0.5 * Math . abs ( x . ulp ( ) . doubleValue ( ) ) ; } MathContext mc = new MathContext ( 2 + err2prec ( 3.1416 , errpi ) ) ; BigDecimal onepi = pi ( mc ) ; BigDecimal pihalf = onepi . divide ( new BigDecimal ( 2 ) ) ; /* Delegate the actual operation to the BigDecimal class, which may return\n         * a negative value of x was negative .\n         */ BigDecimal res = x . remainder ( onepi ) ; if ( res . compareTo ( pihalf ) > 0 ) { res = res . subtract ( onepi ) ; } else if ( res . compareTo ( pihalf . negate ( ) ) < 0 ) { res = res . add ( onepi ) ; } /* The actual precision is set by the input value, its absolute value of x.ulp()/2.\n         */ mc = new MathContext ( err2prec ( res . doubleValue ( ) , x . ulp ( ) . doubleValue ( ) / 2. ) ) ; return res . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Riemann zeta function . [CODESPLIT] static public BigDecimal zeta ( final int n , final MathContext mc ) { if ( n <= 0 ) { throw new ProviderException ( \"Unimplemented zeta at negative argument \" + n ) ; } if ( n == 1 ) { throw new ArithmeticException ( \"Pole at zeta(1) \" ) ; } if ( n % 2 == 0 ) { /* Even indices. Abramowitz-Stegun 23.2.16. Start with 2^(n-1)*B(n)/n!\n             */ Rational b = ( new Bernoulli ( ) ) . at ( n ) . abs ( ) ; b = b . divide ( ( new Factorial ( ) ) . at ( n ) ) ; b = b . multiply ( BigInteger . ONE . shiftLeft ( n - 1 ) ) ; /* to be multiplied by pi^n. Absolute error in the result of pi^n is n times\n             * error in pi times pi^(n-1). Relative error is n*error(pi)/pi, requested by mc.\n             * Need one more digit in pi if n=10, two digits if n=100 etc, and add one extra digit.\n             */ MathContext mcpi = new MathContext ( mc . getPrecision ( ) + ( int ) ( Math . log10 ( 10.0 * n ) ) ) ; final BigDecimal piton = pi ( mcpi ) . pow ( n , mc ) ; return multiplyRound ( piton , b ) ; } else if ( n == 3 ) { /* Broadhurst BBP \\protect\\vrule width0pt\\protect\\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}\n             * Error propagation: S31 is roughly 0.087, S33 roughly 0.131\n             */ int [ ] a31 = { 1 , - 7 , - 1 , 10 , - 1 , - 7 , 1 , 0 } ; int [ ] a33 = { 1 , 1 , - 1 , - 2 , - 1 , 1 , 1 , 0 } ; BigDecimal S31 = broadhurstBBP ( 3 , 1 , a31 , mc ) ; BigDecimal S33 = broadhurstBBP ( 3 , 3 , a33 , mc ) ; S31 = S31 . multiply ( new BigDecimal ( 48 ) ) ; S33 = S33 . multiply ( new BigDecimal ( 32 ) ) ; return S31 . add ( S33 ) . divide ( new BigDecimal ( 7 ) , mc ) ; } else if ( n == 5 ) { /* Broadhurst BBP \\protect\\vrule width0pt\\protect\\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}\n             * Error propagation: S51 is roughly -11.15, S53 roughly 22.165, S55 is roughly 0.031\n             * 9*2048*S51/6265 = -3.28. 7*2038*S53/61651= 5.07. 738*2048*S55/61651= 0.747.\n             * The result is of the order 1.03, so we add 2 digits to S51 and S52 and one digit to S55.\n             */ int [ ] a51 = { 31 , - 1614 , - 31 , - 6212 , - 31 , - 1614 , 31 , 74552 } ; int [ ] a53 = { 173 , 284 , - 173 , - 457 , - 173 , 284 , 173 , - 111 } ; int [ ] a55 = { 1 , 0 , - 1 , - 1 , - 1 , 0 , 1 , 1 } ; BigDecimal S51 = broadhurstBBP ( 5 , 1 , a51 , new MathContext ( 2 + mc . getPrecision ( ) ) ) ; BigDecimal S53 = broadhurstBBP ( 5 , 3 , a53 , new MathContext ( 2 + mc . getPrecision ( ) ) ) ; BigDecimal S55 = broadhurstBBP ( 5 , 5 , a55 , new MathContext ( 1 + mc . getPrecision ( ) ) ) ; S51 = S51 . multiply ( new BigDecimal ( 18432 ) ) ; S53 = S53 . multiply ( new BigDecimal ( 14336 ) ) ; S55 = S55 . multiply ( new BigDecimal ( 1511424 ) ) ; return S51 . add ( S53 ) . subtract ( S55 ) . divide ( new BigDecimal ( 62651 ) , mc ) ; } else { /* Cohen et al Exp Math 1 (1) (1992) 25\n             */ Rational betsum = new Rational ( ) ; Bernoulli bern = new Bernoulli ( ) ; Factorial fact = new Factorial ( ) ; for ( int npr = 0 ; npr <= ( n + 1 ) / 2 ; npr ++ ) { Rational b = bern . at ( 2 * npr ) . multiply ( bern . at ( n + 1 - 2 * npr ) ) ; b = b . divide ( fact . at ( 2 * npr ) ) . divide ( fact . at ( n + 1 - 2 * npr ) ) ; b = b . multiply ( 1 - 2 * npr ) ; if ( npr % 2 == 0 ) { betsum = betsum . add ( b ) ; } else { betsum = betsum . subtract ( b ) ; } } betsum = betsum . divide ( n - 1 ) ; /* The first term, including the facor (2pi)^n, is essentially most\n             * of the result, near one. The second term below is roughly in the range 0.003 to 0.009.\n             * So the precision here is matching the precisionn requested by mc, and the precision\n             * requested for 2*pi is in absolute terms adjusted.\n             */ MathContext mcloc = new MathContext ( 2 + mc . getPrecision ( ) + ( int ) ( Math . log10 ( ( double ) ( n ) ) ) ) ; BigDecimal ftrm = pi ( mcloc ) . multiply ( new BigDecimal ( 2 ) ) ; ftrm = ftrm . pow ( n ) ; ftrm = multiplyRound ( ftrm , betsum . BigDecimalValue ( mcloc ) ) ; BigDecimal exps = new BigDecimal ( 0 ) ; /* the basic accuracy of the accumulated terms before multiplication with 2\n             */ double eps = Math . pow ( 10. , - mc . getPrecision ( ) ) ; if ( n % 4 == 3 ) { /* since the argument n is at least 7 here, the drop\n                 * of the terms is at rather constant pace at least 10^-3, for example\n                 * 0.0018, 0.2e-7, 0.29e-11, 0.74e-15 etc for npr=1,2,3.... We want 2 times these terms\n                 * fall below eps/10.\n                 */ int kmax = mc . getPrecision ( ) / 3 ; eps /= kmax ; /* need an error of eps for 2/(exp(2pi)-1) = 0.0037\n                 * The absolute error is 4*exp(2pi)*err(pi)/(exp(2pi)-1)^2=0.0075*err(pi)\n                 */ BigDecimal exp2p = pi ( new MathContext ( 3 + err2prec ( 3.14 , eps / 0.0075 ) ) ) ; exp2p = exp ( exp2p . multiply ( new BigDecimal ( 2 ) ) ) ; BigDecimal c = exp2p . subtract ( BigDecimal . ONE ) ; exps = divideRound ( 1 , c ) ; for ( int npr = 2 ; npr <= kmax ; npr ++ ) { /* the error estimate above for npr=1 is the worst case of\n                     * the absolute error created by an error in 2pi. So we can\n                     * safely re-use the exp2p value computed above without\n                     * reassessment of its error.\n                     */ c = powRound ( exp2p , npr ) . subtract ( BigDecimal . ONE ) ; c = multiplyRound ( c , ( BigInteger . valueOf ( npr ) ) . pow ( n ) ) ; c = divideRound ( 1 , c ) ; exps = exps . add ( c ) ; } } else { /* since the argument n is at least 9 here, the drop\n                 * of the terms is at rather constant pace at least 10^-3, for example\n                 * 0.0096, 0.5e-7, 0.3e-11, 0.6e-15 etc. We want these terms\n                 * fall below eps/10.\n                 */ int kmax = ( 1 + mc . getPrecision ( ) ) / 3 ; eps /= kmax ; /* need an error of eps for 2/(exp(2pi)-1)*(1+4*Pi/8/(1-exp(-2pi)) = 0.0096\n                 * at k=7 or = 0.00766 at k=13 for example.\n                 * The absolute error is 0.017*err(pi) at k=9, 0.013*err(pi) at k=13, 0.012 at k=17\n                 */ BigDecimal twop = pi ( new MathContext ( 3 + err2prec ( 3.14 , eps / 0.017 ) ) ) ; twop = twop . multiply ( new BigDecimal ( 2 ) ) ; BigDecimal exp2p = exp ( twop ) ; BigDecimal c = exp2p . subtract ( BigDecimal . ONE ) ; exps = divideRound ( 1 , c ) ; c = BigDecimal . ONE . subtract ( divideRound ( 1 , exp2p ) ) ; c = divideRound ( twop , c ) . multiply ( new BigDecimal ( 2 ) ) ; c = divideRound ( c , n - 1 ) . add ( BigDecimal . ONE ) ; exps = multiplyRound ( exps , c ) ; for ( int npr = 2 ; npr <= kmax ; npr ++ ) { c = powRound ( exp2p , npr ) . subtract ( BigDecimal . ONE ) ; c = multiplyRound ( c , ( BigInteger . valueOf ( npr ) ) . pow ( n ) ) ; BigDecimal d = divideRound ( 1 , exp2p . pow ( npr ) ) ; d = BigDecimal . ONE . subtract ( d ) ; d = divideRound ( twop , d ) . multiply ( new BigDecimal ( 2 * npr ) ) ; d = divideRound ( d , n - 1 ) . add ( BigDecimal . ONE ) ; d = divideRound ( d , c ) ; exps = exps . add ( d ) ; } } exps = exps . multiply ( new BigDecimal ( 2 ) ) ; return ftrm . subtract ( exps , mc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Riemann zeta function . [CODESPLIT] static public double zeta1 ( final int n ) { /* precomputed static table in double precision\n         */ final double [ ] zmin1 = { 0. , 0. , 6.449340668482264364724151666e-01 , 2.020569031595942853997381615e-01 , 8.232323371113819151600369654e-02 , 3.692775514336992633136548646e-02 , 1.734306198444913971451792979e-02 , 8.349277381922826839797549850e-03 , 4.077356197944339378685238509e-03 , 2.008392826082214417852769232e-03 , 9.945751278180853371459589003e-04 , 4.941886041194645587022825265e-04 , 2.460865533080482986379980477e-04 , 1.227133475784891467518365264e-04 , 6.124813505870482925854510514e-05 , 3.058823630702049355172851064e-05 , 1.528225940865187173257148764e-05 , 7.637197637899762273600293563e-06 , 3.817293264999839856461644622e-06 , 1.908212716553938925656957795e-06 , 9.539620338727961131520386834e-07 , 4.769329867878064631167196044e-07 , 2.384505027277329900036481868e-07 , 1.192199259653110730677887189e-07 , 5.960818905125947961244020794e-08 , 2.980350351465228018606370507e-08 , 1.490155482836504123465850663e-08 , 7.450711789835429491981004171e-09 , 3.725334024788457054819204018e-09 , 1.862659723513049006403909945e-09 , 9.313274324196681828717647350e-10 , 4.656629065033784072989233251e-10 , 2.328311833676505492001455976e-10 , 1.164155017270051977592973835e-10 , 5.820772087902700889243685989e-11 , 2.910385044497099686929425228e-11 , 1.455192189104198423592963225e-11 , 7.275959835057481014520869012e-12 , 3.637979547378651190237236356e-12 , 1.818989650307065947584832101e-12 , 9.094947840263889282533118387e-13 , 4.547473783042154026799112029e-13 , 2.273736845824652515226821578e-13 , 1.136868407680227849349104838e-13 , 5.684341987627585609277182968e-14 , 2.842170976889301855455073705e-14 , 1.421085482803160676983430714e-14 , 7.105427395210852712877354480e-15 , 3.552713691337113673298469534e-15 , 1.776356843579120327473349014e-15 , 8.881784210930815903096091386e-16 , 4.440892103143813364197770940e-16 , 2.220446050798041983999320094e-16 , 1.110223025141066133720544570e-16 , 5.551115124845481243723736590e-17 , 2.775557562136124172581632454e-17 , 1.387778780972523276283909491e-17 , 6.938893904544153697446085326e-18 , 3.469446952165922624744271496e-18 , 1.734723476047576572048972970e-18 , 8.673617380119933728342055067e-19 , 4.336808690020650487497023566e-19 , 2.168404344997219785013910168e-19 , 1.084202172494241406301271117e-19 , 5.421010862456645410918700404e-20 , 2.710505431223468831954621312e-20 , 1.355252715610116458148523400e-20 , 6.776263578045189097995298742e-21 , 3.388131789020796818085703100e-21 , 1.694065894509799165406492747e-21 , 8.470329472546998348246992609e-22 , 4.235164736272833347862270483e-22 , 2.117582368136194731844209440e-22 , 1.058791184068023385226500154e-22 , 5.293955920339870323813912303e-23 , 2.646977960169852961134116684e-23 , 1.323488980084899080309451025e-23 , 6.617444900424404067355245332e-24 , 3.308722450212171588946956384e-24 , 1.654361225106075646229923677e-24 , 8.271806125530344403671105617e-25 , 4.135903062765160926009382456e-25 , 2.067951531382576704395967919e-25 , 1.033975765691287099328409559e-25 , 5.169878828456431320410133217e-26 , 2.584939414228214268127761771e-26 , 1.292469707114106670038112612e-26 , 6.462348535570531803438002161e-27 , 3.231174267785265386134814118e-27 , 1.615587133892632521206011406e-27 , 8.077935669463162033158738186e-28 , 4.038967834731580825622262813e-28 , 2.019483917365790349158762647e-28 , 1.009741958682895153361925070e-28 , 5.048709793414475696084771173e-29 , 2.524354896707237824467434194e-29 , 1.262177448353618904375399966e-29 , 6.310887241768094495682609390e-30 , 3.155443620884047239109841220e-30 , 1.577721810442023616644432780e-30 , 7.888609052210118073520537800e-31 } ; if ( n <= 0 ) { throw new ProviderException ( \"Unimplemented zeta at negative argument \" + n ) ; } if ( n == 1 ) { throw new ArithmeticException ( \"Pole at zeta(1) \" ) ; } if ( n < zmin1 . length ) /* look it up if available */ { return zmin1 [ n ] ; } else { /* Result is roughly 2^(-n), desired accuracy 18 digits. If zeta(n) is computed, the equivalent accuracy\n             * in relative units is higher, because zeta is around 1.\n             */ double eps = 1.e-18 * Math . pow ( 2. , ( double ) ( - n ) ) ; MathContext mc = new MathContext ( err2prec ( eps ) ) ; return zeta ( n , mc ) . subtract ( BigDecimal . ONE ) . doubleValue ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadhurst ladder sequence . [CODESPLIT] static protected BigDecimal broadhurstBBP ( final int n , final int p , final int a [ ] , MathContext mc ) { /* Explore the actual magnitude of the result first with a quick estimate.\n        */ double x = 0.0 ; for ( int k = 1 ; k < 10 ; k ++ ) { x += a [ ( k - 1 ) % 8 ] / Math . pow ( 2. , p * ( k + 1 ) / 2 ) / Math . pow ( ( double ) k , n ) ; } /* Convert the relative precision and estimate of the result into an absolute precision.\n         */ double eps = prec2err ( x , mc . getPrecision ( ) ) ; /* Divide this through the number of terms in the sum to account for error accumulation\n         * The divisor 2^(p(k+1)/2) means that on the average each 8th term in k has shrunk by\n         * relative to the 8th predecessor by 1/2^(4p). 1/2^(4pc) = 10^(-precision) with c the 8term\n         * cycles yields c=log_2( 10^precision)/4p = 3.3*precision/4p with k=8c\n         */ int kmax = ( int ) ( 6.6 * mc . getPrecision ( ) / p ) ; /* Now eps is the absolute error in each term */ eps /= kmax ; BigDecimal res = BigDecimal . ZERO ; for ( int c = 0 ; ; c ++ ) { Rational r = new Rational ( ) ; for ( int k = 0 ; k < 8 ; k ++ ) { Rational tmp = new Rational ( BigInteger . valueOf ( a [ k ] ) , BigInteger . valueOf ( ( 1 + 8 * c + k ) ) . pow ( n ) ) ; /* floor( (pk+p)/2)\n                 */ int pk1h = p * ( 2 + 8 * c + k ) / 2 ; tmp = tmp . divide ( BigInteger . ONE . shiftLeft ( pk1h ) ) ; r = r . add ( tmp ) ; } if ( Math . abs ( r . doubleValue ( ) ) < eps ) { break ; } MathContext mcloc = new MathContext ( 1 + err2prec ( r . doubleValue ( ) , eps ) ) ; res = res . add ( r . BigDecimalValue ( mcloc ) ) ; } return res . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add and round according to the larger of the two ulp’s . [CODESPLIT] static public BigDecimal addRound ( final BigDecimal x , final BigDecimal y ) { BigDecimal resul = x . add ( y ) ; /* The estimation of the absolute error in the result is |err(y)|+|err(x)|\n         */ double errR = Math . abs ( y . ulp ( ) . doubleValue ( ) / 2. ) + Math . abs ( x . ulp ( ) . doubleValue ( ) / 2. ) ; MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , errR ) ) ; return resul . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtract and round according to the larger of the two ulp’s . [CODESPLIT] static public BigDecimal subtractRound ( final BigDecimal x , final BigDecimal y ) { BigDecimal resul = x . subtract ( y ) ; /* The estimation of the absolute error in the result is |err(y)|+|err(x)|\n         */ double errR = Math . abs ( y . ulp ( ) . doubleValue ( ) / 2. ) + Math . abs ( x . ulp ( ) . doubleValue ( ) / 2. ) ; MathContext mc = new MathContext ( err2prec ( resul . doubleValue ( ) , errR ) ) ; return resul . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final BigDecimal y ) { BigDecimal resul = x . multiply ( y ) ; /* The estimation of the relative error in the result is the sum of the relative\n         * errors |err(y)/y|+|err(x)/x|\n         */ MathContext mc = new MathContext ( Math . min ( x . precision ( ) , y . precision ( ) ) ) ; return resul . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final Rational f ) { if ( f . compareTo ( BigInteger . ZERO ) == 0 ) { return BigDecimal . ZERO ; } else { /* Convert the rational value with two digits of extra precision\n             */ MathContext mc = new MathContext ( 2 + x . precision ( ) ) ; BigDecimal fbd = f . BigDecimalValue ( mc ) ; /* and the precision of the product is then dominated by the precision in x\n             */ return multiplyRound ( x , fbd ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final int n ) { BigDecimal resul = x . multiply ( new BigDecimal ( n ) ) ; /* The estimation of the absolute error in the result is |n*err(x)|\n         */ MathContext mc = new MathContext ( n != 0 ? x . precision ( ) : 0 ) ; return resul . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply and round . [CODESPLIT] static public BigDecimal multiplyRound ( final BigDecimal x , final BigInteger n ) { BigDecimal resul = x . multiply ( new BigDecimal ( n ) ) ; /* The estimation of the absolute error in the result is |n*err(x)|\n         */ MathContext mc = new MathContext ( n . compareTo ( BigInteger . ZERO ) != 0 ? x . precision ( ) : 0 ) ; return resul . round ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide and round . [CODESPLIT] static public BigDecimal divideRound ( final BigDecimal x , final BigDecimal y ) { /* The estimation of the relative error in the result is |err(y)/y|+|err(x)/x|\n         */ MathContext mc = new MathContext ( Math . min ( x . precision ( ) , y . precision ( ) ) ) ; return x . divide ( y , mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide and round . [CODESPLIT] static public BigDecimal divideRound ( final int n , final BigDecimal x ) { /* The estimation of the relative error in the result is |err(x)/x|\n         */ MathContext mc = new MathContext ( x . precision ( ) ) ; return new BigDecimal ( n ) . divide ( x , mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append decimal zeros to the value . This returns a value which appears to have a higher precision than the input . [CODESPLIT] static public BigDecimal scalePrec ( final BigDecimal x , int d ) { return x . setScale ( d + x . scale ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Boost the precision by appending decimal zeros to the value . This returns a value which appears to have a higher precision than the input . [CODESPLIT] static public BigDecimal scalePrec ( final BigDecimal x , final MathContext mc ) { final int diffPr = mc . getPrecision ( ) - x . precision ( ) ; if ( diffPr > 0 ) { return scalePrec ( x , diffPr ) ; } else { return x ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an absolute error to a precision . [CODESPLIT] static public int err2prec ( BigDecimal x , BigDecimal xerr ) { return err2prec ( xerr . divide ( x , MathContext . DECIMAL64 ) . doubleValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the opName for the variable with the given vertex id [CODESPLIT] public void updateVariableName ( String varName , String withName ) { SDVariable oldVarNameRef = getVariable ( varName ) ; variableMap . remove ( oldVarNameRef . getVarName ( ) ) ; val oldVarName = varName ; oldVarNameRef . setVarName ( withName ) ; variableMap . put ( withName , oldVarNameRef ) ; for ( val reverseValues : outgoingArgsReverse . entrySet ( ) ) { for ( int i = 0 ; i < reverseValues . getValue ( ) . length ; i ++ ) { if ( reverseValues . getValue ( ) [ i ] . equals ( oldVarName ) ) { reverseValues . getValue ( ) [ i ] = withName ; } } } for ( val reverseValues : incomingArgsReverse . entrySet ( ) ) { for ( int i = 0 ; i < reverseValues . getValue ( ) . length ; i ++ ) { if ( reverseValues . getValue ( ) [ i ] . equals ( oldVarName ) ) { reverseValues . getValue ( ) [ i ] = withName ; } } } if ( variableNameToArr . containsKey ( oldVarName ) ) { val arr = variableNameToArr . remove ( oldVarName ) ; variableNameToArr . put ( withName , arr ) ; } if ( variableNameToShape . containsKey ( oldVarName ) ) { val shape = variableNameToShape . remove ( oldVarName ) ; variableNameToShape . put ( withName , shape ) ; } if ( gradients . containsKey ( oldVarName ) ) { val grad = gradients . remove ( oldVarName ) ; gradients . put ( withName , grad ) ; } if ( forwardVarForGrad . containsKey ( oldVarName ) ) { val forwardGrad = forwardVarForGrad . remove ( oldVarName ) ; forwardVarForGrad . put ( withName , forwardGrad ) ; } if ( placeHolderMap . containsKey ( oldVarName ) ) { val placeholders = placeHolderMap . remove ( oldVarName ) ; placeHolderMap . put ( withName , placeholders ) ; } if ( functionsArgsFor . containsKey ( oldVarName ) ) { val funcs = functionsArgsFor . remove ( oldVarName ) ; for ( val func : funcs ) { if ( func instanceof BaseOp ) { BaseOp baseOp = ( BaseOp ) func ; if ( baseOp . getXVertexId ( ) != null && baseOp . getXVertexId ( ) . equals ( oldVarName ) ) { baseOp . setXVertexId ( withName ) ; } if ( baseOp . getYVertexId ( ) != null && baseOp . getYVertexId ( ) . equals ( oldVarName ) ) { baseOp . setYVertexId ( withName ) ; } if ( baseOp . getZVertexId ( ) != null && baseOp . getZVertexId ( ) . equals ( oldVarName ) ) { baseOp . setZVertexId ( withName ) ; } } } functionsArgsFor . put ( withName , funcs ) ; } if ( functionOutputFor . containsKey ( oldVarName ) ) { val funcs = functionOutputFor . remove ( oldVarName ) ; for ( val func : funcs ) { if ( func instanceof BaseOp ) { BaseOp baseOp = ( BaseOp ) func ; if ( baseOp . getXVertexId ( ) != null && baseOp . getXVertexId ( ) . equals ( oldVarName ) ) { baseOp . setXVertexId ( withName ) ; } if ( baseOp . getYVertexId ( ) != null && baseOp . getYVertexId ( ) . equals ( oldVarName ) ) { baseOp . setYVertexId ( withName ) ; } if ( baseOp . getZVertexId ( ) != null && baseOp . getZVertexId ( ) . equals ( oldVarName ) ) { baseOp . setZVertexId ( withName ) ; } } } functionOutputFor . put ( withName , funcs ) ; } variableMap . remove ( oldVarName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the function by the { @link DifferentialFunction#getOwnName () } [CODESPLIT] public DifferentialFunction getFunctionById ( String id ) { if ( ! functionInstancesById . containsKey ( id ) ) { throw new ND4JIllegalStateException ( \"No function with id \" + id + \" found!\" ) ; } return functionInstancesById . get ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put the function for id [CODESPLIT] public void putFunctionForId ( String id , DifferentialFunction function ) { if ( functionInstancesById . containsKey ( id ) ) { throw new ND4JIllegalStateException ( \"Function by id already exists!\" ) ; } else if ( function instanceof SDVariable ) { throw new ND4JIllegalStateException ( \"Function must not be a variable!\" ) ; } functionInstancesById . put ( id , function ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the inputs for the given function [CODESPLIT] public String [ ] getInputsForFunction ( DifferentialFunction function ) { if ( ! incomingArgsReverse . containsKey ( function . getOwnName ( ) ) ) throw new ND4JIllegalStateException ( \"Illegal function instance id found \" + function . getOwnName ( ) ) ; return incomingArgsReverse . get ( function . getOwnName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the ndarray for the given vertex id . [CODESPLIT] public void updateArrayForVarName ( String varName , INDArray arr ) { if ( ! variableNameToArr . containsKey ( varName ) ) { throw new ND4JIllegalStateException ( \"Array for \" + varName + \" does not exist. Please use putArrayForVertexId instead.\" ) ; } variableNameToArr . put ( varName , arr ) ; reverseArrayLookup . put ( arr , getVariable ( varName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an ndarray for a given vertex id . Use { @link #updateArrayForVarName ( String INDArray ) } if the array already exists . [CODESPLIT] public void putArrayForVarName ( String varName , INDArray arr ) { if ( varName == null ) throw new ND4JIllegalStateException ( \"No null names allowed!\" ) ; if ( variableNameToArr . containsKey ( varName ) ) { throw new ND4JIllegalStateException ( \"Array for \" + varName + \" already exists!\" ) ; } variableNameToArr . put ( varName , arr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the shape for the given vertex id . Note that if an array is defined it will use that shape instead . <p > A shape * and * an array should not be defined at the same time . This wastes memory . The internal map used for tracking shapes for particular vertex ids should also delete redundant shapes stored to avoid redundant sources of information . [CODESPLIT] public long [ ] getShapeForVarName ( String varName ) { if ( variableNameToArr . containsKey ( varName ) ) { return variableNameToArr . get ( varName ) . shape ( ) ; } return variableNameToShape . get ( varName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update a vertex id with the given shape . Note that you should use { @link #putShapeForVarName ( String int [] ) } if you want to add a new shape . Update is meant to be an in place replacement of the shape for the vertex id * only * . [CODESPLIT] public void updateShapeForVarName ( String varName , long [ ] shape ) { if ( shape == null ) { throw new ND4JIllegalStateException ( \"Null shapes not allowed!\" ) ; } if ( variableNameToArr . containsKey ( varName ) && ! Arrays . equals ( variableNameToArr . get ( varName ) . shape ( ) , shape ) ) { throw new ND4JIllegalStateException ( \"Already found an existing array!\" ) ; } for ( int i = 0 ; i < shape . length ; i ++ ) { if ( shape [ i ] < 1 ) { addAsPlaceHolder ( varName ) ; placeHolderOriginalShapes . put ( varName , shape ) ; return ; } } variableNameToShape . put ( varName , shape ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associate a vertex id with the given shape . [CODESPLIT] public void putShapeForVarName ( String varName , long [ ] shape ) { if ( shape == null ) { throw new ND4JIllegalStateException ( \"Shape must not be null!\" ) ; } if ( variableNameToShape . containsKey ( varName ) ) { throw new ND4JIllegalStateException ( \"Shape for \" + varName + \" already exists!\" ) ; } for ( int i = 0 ; i < shape . length ; i ++ ) { if ( shape [ i ] < 1 ) { addAsPlaceHolder ( varName ) ; placeHolderOriginalShapes . put ( varName , shape ) ; return ; } } variableNameToShape . put ( varName , shape ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associate the array with the given variable . [CODESPLIT] public void associateArrayWithVariable ( INDArray arr , SDVariable variable ) { if ( variable == null ) { throw new ND4JIllegalArgumentException ( \"Variable must not be null!\" ) ; } if ( arr == null ) { throw new ND4JIllegalArgumentException ( \"Array must not be null\" ) ; } reverseArrayLookup . put ( arr , variable ) ; variableNameToArr . put ( variable . getVarName ( ) , arr ) ; if ( ! shapeAlreadyExistsForVarName ( variable . getVarName ( ) ) ) putShapeForVarName ( variable . getVarName ( ) , arr . shape ( ) ) ; else { updateShapeForVarName ( variable . getVarName ( ) , arr . shape ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the property for a given function [CODESPLIT] public < T > T getPropertyForFunction ( DifferentialFunction functionInstance , String propertyName ) { if ( ! propertiesForFunction . containsKey ( functionInstance . getOwnName ( ) ) ) { return null ; } else { val map = propertiesForFunction . get ( functionInstance . getOwnName ( ) ) ; return ( T ) map . get ( propertyName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a property for the given function [CODESPLIT] public void addPropertyForFunction ( DifferentialFunction functionFor , String propertyName , INDArray property ) { addPropertyForFunction ( functionFor , propertyName , ( Object ) property ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds outgoing arguments to the graph . Also checks for input arguments and updates the graph adding an appropriate edge when the full graph is declared . [CODESPLIT] public void addOutgoingFor ( String [ ] varNames , DifferentialFunction function ) { if ( function . getOwnName ( ) == null ) throw new ND4JIllegalStateException ( \"Instance id can not be null. Function not initialized properly\" ) ; if ( outgoingArgsReverse . containsKey ( function . getOwnName ( ) ) ) { throw new ND4JIllegalStateException ( \"Outgoing arguments already declared for \" + function ) ; } if ( varNames == null ) throw new ND4JIllegalStateException ( \"Var names can not be null!\" ) ; for ( int i = 0 ; i < varNames . length ; i ++ ) { if ( varNames [ i ] == null ) throw new ND4JIllegalStateException ( \"Variable name elements can not be null!\" ) ; } outgoingArgsReverse . put ( function . getOwnName ( ) , varNames ) ; outgoingArgs . put ( varNames , function ) ; for ( val resultName : varNames ) { List < DifferentialFunction > funcs = functionOutputFor . get ( resultName ) ; if ( funcs == null ) { funcs = new ArrayList <> ( ) ; functionOutputFor . put ( resultName , funcs ) ; } funcs . add ( function ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds incoming args to the graph [CODESPLIT] public void addArgsFor ( String [ ] variables , DifferentialFunction function ) { if ( function . getOwnName ( ) == null ) throw new ND4JIllegalStateException ( \"Instance id can not be null. Function not initialized properly\" ) ; //double check if function contains placeholder args for ( val varName : variables ) { if ( isPlaceHolder ( varName ) ) { placeHolderFunctions . add ( function . getOwnName ( ) ) ; } } incomingArgs . put ( variables , function ) ; incomingArgsReverse . put ( function . getOwnName ( ) , variables ) ; for ( val variableName : variables ) { List < DifferentialFunction > funcs = functionsArgsFor . get ( variableName ) ; if ( funcs == null ) { funcs = new ArrayList <> ( ) ; functionsArgsFor . put ( variableName , funcs ) ; } funcs . add ( function ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this function already has defined arguments [CODESPLIT] public boolean hasArgs ( DifferentialFunction function ) { val vertexIdArgs = incomingArgsReverse . get ( function . getOwnName ( ) ) ; if ( vertexIdArgs != null ) { val args = incomingArgs . get ( vertexIdArgs ) ; if ( args != null ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate the given inputs based on the current graph [CODESPLIT] public INDArray [ ] eval ( Map < String , INDArray > inputs ) { SameDiff execPipeline = dup ( ) ; List < DifferentialFunction > opExecAction = execPipeline . exec ( ) . getRight ( ) ; if ( opExecAction . isEmpty ( ) ) throw new IllegalStateException ( \"No ops found to execute.\" ) ; INDArray [ ] ret = new INDArray [ opExecAction . size ( ) ] ; for ( int i = 0 ; i < ret . length ; i ++ ) { val varName = opExecAction . get ( i ) . outputVariables ( ) [ 0 ] . getVarName ( ) ; ret [ i ] = execPipeline . getArrForVarName ( varName ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Variable initialization with 1 . 0 [CODESPLIT] public SDVariable one ( String name , int [ ] shape ) { return var ( name , ArrayUtil . toLongArray ( shape ) , new ConstantInitScheme ( ' ' , 1.0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a variable of all 1s with the same shape as the input [CODESPLIT] public SDVariable onesLike ( String name , SDVariable input ) { return f ( ) . onesLike ( name , input ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a variable of all 0s with the same shape as the input [CODESPLIT] public SDVariable zerosLike ( String name , SDVariable input ) { return f ( ) . zerosLike ( name , input ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Variable initialization with a specified { @link WeightInitScheme } [CODESPLIT] public SDVariable var ( String name , long [ ] shape , WeightInitScheme weightInitScheme ) { if ( variableMap . containsKey ( name ) && variableMap . get ( name ) . getArr ( ) != null ) return variableMap . get ( name ) ; if ( name == null || name . length ( ) < 1 ) throw new IllegalArgumentException ( \"Name for variable must be defined\" ) ; if ( workspace == null ) initWorkspace ( ) ; SDVariable ret = SDVariable . builder ( ) . sameDiff ( this ) . shape ( shape ) . weightInitScheme ( weightInitScheme ) . varName ( name ) . build ( ) ; addVariable ( ret ) ; variableMap . put ( name , ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a { @link SDVariable } reference tying this variable to this samediff instance . <p > { @link NDArraySupplierInitScheme } is used to ensure that if the array is allocated anywhere and { @link SameDiff } instance to exist as a copy of the variable . [CODESPLIT] public SDVariable var ( final SDVariable arr ) { if ( variableMap . containsKey ( arr . getVarName ( ) ) && variableMap . get ( arr . getVarName ( ) ) . getArr ( ) != null ) return variableMap . get ( arr . getVarName ( ) ) ; if ( arr . getVarName ( ) == null || arr . getVarName ( ) . length ( ) < 1 ) throw new IllegalArgumentException ( \"Name for variable must be defined\" ) ; if ( arr == null ) throw new IllegalArgumentException ( \"Array for \" + arr . getVarName ( ) + \" must not be null\" ) ; if ( workspace == null ) initWorkspace ( ) ; final SDVariable ret = SDVariable . builder ( ) . sameDiff ( this ) . shape ( arr . getShape ( ) ) . varName ( arr . getVarName ( ) ) . weightInitScheme ( new NDArraySupplierInitScheme ( new NDArraySupplierInitScheme . NDArraySupplier ( ) { @ Override public INDArray getArr ( ) { /**\n                         * Pre allocate the array if it doesn't already exist.\n                         * The reason we do this is to avoid race conditions with\n                         * {@link #allocate()}\n                         */ if ( arr . getArr ( ) == null ) { INDArray retArr = arr . getWeightInitScheme ( ) . create ( arr . getShape ( ) ) ; associateArrayWithVariable ( retArr , arr ) ; } return arr . getArr ( ) ; } } ) ) . build ( ) ; variableMap . put ( arr . getVarName ( ) , ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an argument for a function . Note that if this function does not contain the argument it will just be a no op . [CODESPLIT] public void removeArgFromFunction ( String varName , DifferentialFunction function ) { val args = function . args ( ) ; for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . getVarName ( ) . equals ( varName ) ) { /**\n                 * Since we are removing the variable reference\n                 * from the arguments we need to  update both\n                 * the reverse and forward arguments.\n                 */ val reverseArgs = incomingArgsReverse . get ( function . getOwnName ( ) ) ; incomingArgs . remove ( reverseArgs ) ; incomingArgsReverse . remove ( function . getOwnName ( ) ) ; val newArgs = new ArrayList < String > ( args . length - 1 ) ; for ( int arg = 0 ; arg < args . length ; arg ++ ) { if ( ! reverseArgs [ arg ] . equals ( varName ) ) { newArgs . add ( reverseArgs [ arg ] ) ; } } val newArgsArr = newArgs . toArray ( new String [ newArgs . size ( ) ] ) ; incomingArgs . put ( newArgsArr , function ) ; incomingArgsReverse . put ( function . getOwnName ( ) , newArgsArr ) ; //no further need to scan break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign a vertex id to a gradient [CODESPLIT] public void setGradientForVariableName ( String variableName , SDVariable variable ) { if ( variable == null ) { throw new ND4JIllegalStateException ( \"Unable to set null gradient for variable name \" + variableName ) ; } gradients . put ( variableName , variable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Average pooling 2d operation . [CODESPLIT] public SDVariable avgPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { return avgPooling2d ( null , inputs , pooling2DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Average pooling 2d operation . [CODESPLIT] public SDVariable avgPooling2d ( String name , SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { SDVariable ret = f ( ) . avgPooling2d ( inputs , pooling2DConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max pooling 2d operation . [CODESPLIT] public SDVariable maxPooling2d ( SDVariable [ ] inputs , Pooling2DConfig pooling2DConfig ) { return maxPooling2d ( null , inputs , pooling2DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Average pooling 3d operation . [CODESPLIT] public SDVariable avgPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { return avgPooling3d ( null , inputs , pooling3DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max pooling 3d operation . [CODESPLIT] public SDVariable maxPooling3d ( SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { return maxPooling3d ( null , inputs , pooling3DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max pooling 3d operation . [CODESPLIT] public SDVariable maxPooling3d ( String name , SDVariable [ ] inputs , Pooling3DConfig pooling3DConfig ) { SDVariable ret = f ( ) . maxPooling3d ( inputs , pooling3DConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conv1d operation . [CODESPLIT] public SDVariable conv1d ( SDVariable [ ] inputs , Conv1DConfig conv1DConfig ) { return conv1d ( null , inputs , conv1DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conv1d operation . [CODESPLIT] public SDVariable conv1d ( String name , SDVariable [ ] inputs , Conv1DConfig conv1DConfig ) { SDVariable ret = f ( ) . conv1d ( inputs , conv1DConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Local response normalization operation . [CODESPLIT] public SDVariable localResponseNormalization ( SDVariable inputs , LocalResponseNormalizationConfig lrnConfig ) { return localResponseNormalization ( null , inputs , lrnConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Local response normalization operation . [CODESPLIT] public SDVariable localResponseNormalization ( String name , SDVariable inputs , LocalResponseNormalizationConfig lrnConfig ) { SDVariable ret = f ( ) . localResponseNormalization ( inputs , lrnConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conv2d operation . [CODESPLIT] public SDVariable conv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { return conv2d ( null , inputs , conv2DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Depth - wise Conv2d operation . [CODESPLIT] public SDVariable depthWiseConv2d ( SDVariable [ ] inputs , Conv2DConfig depthConv2DConfig ) { return depthWiseConv2d ( null , inputs , depthConv2DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Depth - wise Conv2d operation . [CODESPLIT] public SDVariable depthWiseConv2d ( String name , SDVariable [ ] inputs , Conv2DConfig depthConv2DConfig ) { SDVariable ret = f ( ) . depthWiseConv2d ( inputs , depthConv2DConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Separable Conv2d operation . [CODESPLIT] public SDVariable sconv2d ( SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { return sconv2d ( null , inputs , conv2DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Separable Conv2d operation . [CODESPLIT] public SDVariable sconv2d ( String name , SDVariable [ ] inputs , Conv2DConfig conv2DConfig ) { SDVariable ret = f ( ) . sconv2d ( inputs , conv2DConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deconv2d operation . [CODESPLIT] public SDVariable deconv2d ( SDVariable [ ] inputs , DeConv2DConfig deconv2DConfig ) { return deconv2d ( null , inputs , deconv2DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deconv2d operation . [CODESPLIT] public SDVariable deconv2d ( String name , SDVariable [ ] inputs , DeConv2DConfig deconv2DConfig ) { SDVariable ret = f ( ) . deconv2d ( inputs , deconv2DConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conv3d operation . [CODESPLIT] public SDVariable conv3d ( SDVariable [ ] inputs , Conv3DConfig conv3DConfig ) { return conv3d ( null , inputs , conv3DConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conv3d operation . [CODESPLIT] public SDVariable conv3d ( String name , SDVariable [ ] inputs , Conv3DConfig conv3DConfig ) { SDVariable ret = f ( ) . conv3d ( inputs , conv3DConfig ) ; return updateVariableNameAndReference ( ret , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch norm operation . [CODESPLIT] public SDVariable batchNorm ( SDVariable input , SDVariable mean , SDVariable variance , SDVariable gamma , SDVariable beta , boolean applyGamma , boolean applyBeta , double epsilon ) { return batchNorm ( null , input , mean , variance , gamma , beta , applyGamma , applyBeta , epsilon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch norm operation . [CODESPLIT] public SDVariable batchNorm ( String name , SDVariable input , SDVariable mean , SDVariable variance , SDVariable gamma , SDVariable beta , boolean applyGamma , boolean applyBeta , double epsilon ) { SDVariable res = f ( ) . batchNorm ( input , mean , variance , gamma , beta , applyGamma , applyBeta , epsilon ) ; return updateVariableNameAndReference ( res , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LSTM unit [CODESPLIT] public SDVariable lstm ( String baseName , LSTMCellConfiguration configuration ) { return new LSTMCell ( this , configuration ) . outputVariables ( baseName ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The gru cell [CODESPLIT] public SDVariable gru ( String baseName , GRUCellConfiguration configuration ) { return new GRUCell ( this , configuration ) . outputVariables ( baseName ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the variables based on the given input op and return the output variable names . [CODESPLIT] public SDVariable [ ] generateOutputVariableForOp ( DifferentialFunction function , String baseName ) { //xyz ops only have 1 output //if there is already a base name defined, use that if ( baseName == null || baseName . isEmpty ( ) && getBaseNameForFunction ( function ) != null ) baseName = getBaseNameForFunction ( function ) ; if ( baseName == null ) baseName = function . opName ( ) ; val outputShape = function . calculateOutputShape ( ) ; if ( outputShape == null || outputShape . isEmpty ( ) ) { if ( function instanceof CustomOp ) { CustomOp customOp = ( CustomOp ) function ; val descriptor = customOp . getDescriptor ( ) ; //can't guess number of outputs, variable if ( descriptor == null || descriptor . getNumOutputs ( ) <= 0 ) { throw new ND4JIllegalStateException ( \"No output variables found!\" ) ; } else { char ordering = ' ' ; if ( function . args ( ) [ 0 ] . getArr ( ) != null ) { ordering = function . args ( ) [ 0 ] . getArr ( ) . ordering ( ) ; } SDVariable [ ] ret = new SDVariable [ descriptor . getNumOutputs ( ) ] ; //dynamic shapes for ( int i = 0 ; i < ret . length ; i ++ ) { SDVariable checkGet = getVariable ( baseName ) ; if ( checkGet == null ) { checkGet = var ( generateNewVarName ( baseName , i ) , null , new ZeroInitScheme ( ordering ) ) ; } else if ( i > 0 && ! importedVarName . contains ( baseName ) ) { //need to find a new name String newName = generateNewVarName ( baseName , i ) ; checkGet = getVariable ( newName ) ; } if ( checkGet == null ) { String newName = generateNewVarName ( baseName , i ) ; checkGet = var ( newName , null , new ZeroInitScheme ( ordering ) ) ; } ret [ i ] = checkGet ; } return ret ; } } //this is for unresolved shapes, we know xyz is always 1 output else if ( function instanceof BaseOp && outputShape . isEmpty ( ) ) { SDVariable [ ] ret = new SDVariable [ 1 ] ; SDVariable checkGet = getVariable ( baseName ) ; char ordering = ' ' ; if ( function . args ( ) [ 0 ] . getArr ( ) != null ) { ordering = function . args ( ) [ 0 ] . getArr ( ) . ordering ( ) ; } if ( checkGet == null ) { checkGet = var ( baseName , null , new ZeroInitScheme ( ordering ) ) ; } else if ( ! importedVarName . contains ( baseName ) ) { //need to find a new name String newName = generateNewVarName ( baseName , 0 ) ; checkGet = var ( newName , null , new ZeroInitScheme ( ordering ) ) ; } if ( checkGet == null ) { checkGet = var ( baseName , null , new ZeroInitScheme ( ordering ) ) ; } ret [ 0 ] = checkGet ; return ret ; } } char ordering = ' ' ; if ( function . args ( ) [ 0 ] . getArr ( ) != null ) { ordering = function . args ( ) [ 0 ] . getArr ( ) . ordering ( ) ; } SDVariable [ ] ret = new SDVariable [ outputShape . size ( ) ] ; // ownName/baseName will be used to get variables names val ownName = function . getOwnName ( ) ; val rootName = baseName ; for ( int i = 0 ; i < ret . length ; i ++ ) { val shape = outputShape . get ( i ) ; // it should be: rootName:index. i.e.: split:1, split:2, split:3, split:4 etc baseName = rootName + ( i > 0 ? \":\" + i : \"\" ) ; SDVariable checkGet = getVariable ( baseName ) ; if ( checkGet == null ) { // obviously - there's no such var, just add it checkGet = var ( baseName , shape , new ZeroInitScheme ( ordering ) ) ; } else if ( shape != null && ! shapeAlreadyExistsForVarName ( checkGet . getVarName ( ) ) ) { // var exists, let's update its shape putShapeForVarName ( checkGet . getVarName ( ) , shape ) ; } else if ( shape != null && shapeAlreadyExistsForVarName ( checkGet . getVarName ( ) ) ) { // no-op. // TODO: maybe we should check shapes equality here? // it's either var that already exist, or something bad happening } else if ( ! importedVarName . contains ( baseName ) ) { // FIXME: dead end.  it's impossible to get here with null as shape //need to find a new name int count = 1 ; String name = baseName + \"_\" + count + ( i > 0 ? \":\" + i : \"\" ) ; while ( getVariable ( name ) != null ) { count ++ ; name = baseName + \"_\" + count + ( i > 0 ? \":\" + i : \"\" ) ; } if ( getVariable ( name ) != null ) { throw new ND4JIllegalStateException ( \"Converged on already generated variable!\" ) ; } checkGet = var ( name , shape , new ZeroInitScheme ( ordering ) ) ; } if ( checkGet == null ) { checkGet = var ( baseName + ( i > 0 ? \":\" + i : \"\" ) , shape , new ZeroInitScheme ( ordering ) ) ; } ret [ i ] = checkGet ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "u [CODESPLIT] public INDArray execAndEndResult ( List < DifferentialFunction > ops ) { List < DifferentialFunction > exec = exec ( ops ) ; Op op = ( Op ) exec . get ( exec . size ( ) - 1 ) ; return op . z ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the list of operations . This exec method is for only invoking operations rather than creating them [CODESPLIT] public List < DifferentialFunction > exec ( List < DifferentialFunction > ops ) { for ( int i = 0 ; i < ops . size ( ) ; i ++ ) { Op op = ( Op ) ops . get ( i ) ; Nd4j . getExecutioner ( ) . exec ( op ) ; } return ops ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a while statement [CODESPLIT] public While whileStatement ( SameDiffConditional sameDiffConditional , SameDiffFunctionDefinition conditionBody , SameDiff . SameDiffFunctionDefinition loopBody , SDVariable [ ] inputVars ) { return While . builder ( ) . inputVars ( inputVars ) . condition ( conditionBody ) . predicate ( sameDiffConditional ) . trueBody ( loopBody ) . parent ( this ) . blockName ( \"while-\" + UUID . randomUUID ( ) . toString ( ) ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exec a given function [CODESPLIT] public Pair < Map < SDVariable , DifferentialFunction > , List < DifferentialFunction > > exec ( String functionName ) { if ( debugMode ) { return sameDiffFunctionInstances . get ( functionName ) . enableDebugMode ( ) . exec ( ) ; } else return sameDiffFunctionInstances . get ( functionName ) . exec ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exec the given function given the ops [CODESPLIT] public List < DifferentialFunction > exec ( String functionName , List < DifferentialFunction > cachedOps ) { return sameDiffFunctionInstances . get ( functionName ) . exec ( cachedOps ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a backwards graph and executes the operations on that graph . [CODESPLIT] public Pair < Map < SDVariable , DifferentialFunction > , List < DifferentialFunction > > execBackwards ( ) { final SameDiff outer = this ; if ( getFunction ( \"grad\" ) == null ) defineFunction ( \"grad\" , new SameDiffFunctionDefinition ( ) { @ Override public SDVariable [ ] define ( SameDiff sameDiff , Map < String , INDArray > inputs , SDVariable [ ] variableInputs ) { //propagate graph to this samediff instance //which will also contain the backward if ( SameDiff . this . debugMode ) { sameDiff . enableDebugMode ( ) ; } outer . invokeGraphOn ( sameDiff ) ; List < DifferentialFunction > allFunctions = new ArrayList <> ( sameDiff . functionInstancesById . values ( ) ) ; if ( allFunctions . isEmpty ( ) ) { throw new ND4JIllegalStateException ( \"No ops found!\" ) ; } for ( val func : allFunctions ) { if ( func instanceof SDVariable ) { continue ; } val args = func . args ( ) ; for ( val arg : args ) arg . setSameDiff ( sameDiff ) ; val outputs = func . outputVariables ( ) ; for ( val output : outputs ) output . setSameDiff ( sameDiff ) ; func . setSameDiff ( sameDiff ) ; } val initialOuts = allFunctions . get ( allFunctions . size ( ) - 1 ) . outputVariables ( ) ; val firstBackward = initialOuts [ 0 ] ; //start with scalar backprop SDVariable initialGrad = sameDiff . var ( \"one-var\" , Nd4j . scalar ( 1.0 ) ) ; sameDiff . forwardVarForGrad . put ( firstBackward . getVarName ( ) , initialGrad ) ; sameDiff . gradients . put ( firstBackward . getVarName ( ) , initialGrad ) ; SDVariable gradientBackwardsMarker = sameDiff . gradientBackwardsMarker ( firstBackward ) ; //reinitialize list with all declared variables allFunctions = new ArrayList < DifferentialFunction > ( sameDiff . functionInstancesById . values ( ) ) ; Collections . reverse ( allFunctions ) ; for ( DifferentialFunction action : allFunctions ) { if ( action instanceof GradientBackwardsMarker ) { log . warn ( \"Action op state is null for \" + action . opName ( ) ) ; continue ; } DifferentialFunction currFunction = action ; Preconditions . checkState ( currFunction . getSameDiff ( ) == sameDiff , \"Wrong samediff instance found!\" ) ; //Preconditions.checkNotNull(\"Gradient for \" + currFunction.opName() + \" was null ! \" + sameDiff.getVariableForVertexId(currFunction.getVertexId()).getGradient()); val args = currFunction . outputVariables ( ) ; for ( val arg : args ) { if ( arg . getSameDiff ( ) != sameDiff ) { arg . setSameDiff ( sameDiff ) ; } } List < SDVariable > grads = new ArrayList <> ( ) ; for ( val varToGrad : args ) { val grad = varToGrad . gradient ( ) ; if ( grad == null ) throw new ND4JIllegalStateException ( \"No gradient found for \" + varToGrad . getVarName ( ) ) ; grads . add ( grad ) ; } List < SDVariable > currFnGrads = currFunction . diff ( grads ) ; } if ( sameDiff . isDebugMode ( ) ) { //ensure all gradients are present for all variables for ( SDVariable sdVariable : variables ( ) ) { sdVariable . gradient ( ) ; } } return new SDVariable [ ] { sameDiff . var ( \"grad\" , new int [ ] { 1 , 1 } ) } ; } } ) ; Pair < Map < SDVariable , DifferentialFunction > , List < DifferentialFunction > > forward = exec ( \"grad\" ) ; SameDiff grad = getFunction ( \"grad\" ) ; if ( grad . isDebugMode ( ) ) { //ensure all gradients are present for all variables for ( SDVariable sdVariable : grad . variables ( ) ) { sdVariable . gradient ( ) ; } } return forward ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exec a backwards operation and return the end result [CODESPLIT] public INDArray execBackwardAndEndResult ( ) { List < DifferentialFunction > backwards = execBackwards ( ) . getRight ( ) ; DifferentialFunction df = backwards . get ( backwards . size ( ) - 1 ) ; if ( df instanceof Op ) { return ( ( Op ) df ) . z ( ) ; } else if ( df instanceof DynamicCustomOp ) { return ( ( DynamicCustomOp ) df ) . getOutputArgument ( 0 ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add this vertex id as a place holder [CODESPLIT] public void addAsPlaceHolder ( String varName ) { placeHolderVarNames . add ( varName ) ; if ( getVariable ( varName ) != null && getVariable ( varName ) . getShape ( ) != null ) { placeHolderOriginalShapes . put ( varName , getVariable ( varName ) . getShape ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve all ndarrays by updating the variables for each array specified in the given map . An { @link IllegalStateException } will be thrown if not all arrays are specified for resolution . [CODESPLIT] public void resolveVariablesWith ( Map < String , INDArray > arrays ) { for ( val arrayEntry : arrays . entrySet ( ) ) { val varForName = getVariable ( arrayEntry . getKey ( ) ) ; if ( varForName == null ) { throw new ND4JIllegalStateException ( \"No variable name found for \" + arrayEntry . getKey ( ) ) ; } if ( placeHolderOriginalShapes . containsKey ( arrayEntry . getKey ( ) ) ) { val originalShape = placeHolderOriginalShapes . get ( arrayEntry . getKey ( ) ) ; if ( originalShape . length == arrayEntry . getValue ( ) . rank ( ) ) { for ( int i = 0 ; i < originalShape . length ; i ++ ) { if ( originalShape [ i ] != arrayEntry . getValue ( ) . shape ( ) [ i ] && originalShape [ i ] >= 1 ) { throw new ND4JIllegalStateException ( \"Incompatible shape passed for variable. \" + Arrays . toString ( arrayEntry . getValue ( ) . shape ( ) ) ) ; } } } } } for ( val entry : arrays . entrySet ( ) ) { if ( ! placeHolderVarNames . contains ( entry . getKey ( ) ) ) { throw new ND4JIllegalStateException ( \"Illegal variable \" + entry . getKey ( ) + \" passed in. Variable found not to be a place holder variable\" ) ; } val specifiedShape = getOriginalShapeForPlaceHolder ( entry . getKey ( ) ) ; //whole shape was specified: validate whether the input array shape is equal if ( ! Shape . isPlaceholderShape ( specifiedShape ) ) { if ( ! Shape . shapeEquals ( specifiedShape , entry . getValue ( ) . shape ( ) ) ) { throw new ND4JIllegalStateException ( \"Place holder shape specified was \" + Arrays . toString ( specifiedShape ) + \" but array shape was \" + Arrays . toString ( entry . getValue ( ) . shape ( ) ) ) ; } } updateShapeForVarName ( entry . getKey ( ) , entry . getValue ( ) . shape ( ) ) ; associateArrayWithVariable ( entry . getValue ( ) , getVariable ( entry . getKey ( ) ) ) ; updateArrayForVarName ( entry . getKey ( ) , entry . getValue ( ) ) ; } for ( val funcName : propertiesToResolve . keySet ( ) ) { val func = functionInstancesById . get ( funcName ) ; if ( ! functionInstancesById . containsKey ( funcName ) ) { throw new ND4JIllegalStateException ( \"Unable to resolve function name \" + funcName ) ; } if ( func instanceof CustomOp ) { CustomOp customOp = ( CustomOp ) func ; customOp . populateInputsAndOutputsFromSameDiff ( ) ; } } //declare resolved resolvedVariables = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if all place holder variables are resolved . A place holder variable is resolved when { @link #getVariable ( String ) } getArr () does not return null and the shape is properly resolved . [CODESPLIT] public boolean allPlaceHolderVariablesResolved ( ) { for ( val vertexId : placeHolderVarNames ) { val var = getVariable ( vertexId ) ; if ( var . getArr ( ) == null ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add one or or more place holder variables for the given vertex id . <p > Note that if a vertex id in placeHolderVariables isn t present in this samediff instance anyways an { @link ND4JIllegalStateException } is thrown [CODESPLIT] public void putPlaceHolderForVariable ( String varName , String ... placeHolderVariables ) { for ( val placeHolderVariable : placeHolderVariables ) { if ( ! variableMap . containsKey ( placeHolderVariable ) ) { throw new ND4JIllegalStateException ( \"No variable found for \" + placeHolderVariable ) ; } } List < String [ ] > placeHolders = placeHolderMap . get ( varName ) ; if ( placeHolders == null ) { placeHolders = new ArrayList <> ( ) ; placeHolderMap . put ( varName , placeHolders ) ; } placeHolders . add ( placeHolderVariables ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and executes a list of operations based on the given variables passed in . { @link #resolveVariablesWith ( Map ) } is called [CODESPLIT] public Pair < Map < SDVariable , DifferentialFunction > , List < DifferentialFunction > > execWithPlaceHolder ( Map < String , INDArray > inputs ) { resolveVariablesWith ( inputs ) ; return exec ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { @link SDVariable } associated with each function based on the { @link DifferentialFunction#outputVariables () } () } [CODESPLIT] public List < SDVariable > getVariablesAssociatedWithFunctions ( List < DifferentialFunction > functions ) { List < SDVariable > ret = new ArrayList <> ( functions . size ( ) ) ; for ( DifferentialFunction function : functions ) { ret . addAll ( Arrays . asList ( function . outputVariables ( ) ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the variable name property on the passed in variable the reference in samediff and returns the variable . <p > Note that if null for the new variable is passed in it will just return the original input variable . [CODESPLIT] public SDVariable updateVariableNameAndReference ( SDVariable varToUpdate , String newVarName ) { if ( varToUpdate == null ) { throw new NullPointerException ( \"Null input: No variable found for updating!\" ) ; } if ( newVarName == null && variableMap . containsKey ( varToUpdate . getVarName ( ) ) ) { //Edge case: suppose we do m1=sd.mean(in), m2=sd.mean(m1) -> both initially have the name // \"mean\" and consequently a new variable name needs to be generated newVarName = generateNewVarName ( varToUpdate . getVarName ( ) , 0 ) ; } if ( newVarName == null || varToUpdate . getVarName ( ) . equals ( newVarName ) ) { return varToUpdate ; } val oldVarName = varToUpdate . getVarName ( ) ; varToUpdate . setVarName ( newVarName ) ; updateVariableName ( oldVarName , newVarName ) ; return varToUpdate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and executes a list of operations [CODESPLIT] public Pair < Map < SDVariable , DifferentialFunction > , List < DifferentialFunction > > exec ( ) { if ( ! resolvedVariables ) resolveVariablesWith ( new LinkedHashMap < String , INDArray > ( ) ) ; List < DifferentialFunction > ops = new ArrayList <> ( ) ; // we don't care if this thread had any other FlowPath objects attached. we'll just create new one localFlowPath . set ( new FlowPath ( ) ) ; val flowPath = localFlowPath . get ( ) ; Map < SDVariable , DifferentialFunction > opMap = new HashMap <> ( ) ; val funcs = new ArrayList < DifferentialFunction > ( functionInstancesById . values ( ) ) ; boolean onBackward = false ; // dequeue for Frames (nested, probably) val frames = new ArrayDeque < String > ( ) ; // simple flag, set true if within frame boolean inFrame = false ; // yet another flag, to remove LastFrame once we really left last frame boolean frameLeft = false ; int i = 0 ; int exec_counter = 0 ; for ( ; i < funcs . size ( ) ; i ++ ) { ++ exec_counter ; val opName = funcs . get ( i ) . opName ( ) ; if ( ! onBackward && opName . equals ( new GradientBackwardsMarker ( ) . opName ( ) ) ) { onBackward = true ; } if ( opName . equals ( new GradientBackwardsMarker ( ) . opName ( ) ) ) continue ; DifferentialFunction differentialFunction = funcs . get ( i ) ; val ownName = differentialFunction . getOwnName ( ) ; // just registering function for this pass flowPath . ensureNodeStateExists ( differentialFunction . getOwnName ( ) ) ; if ( differentialFunction instanceof SDVariable ) { continue ; } val args = getInputsForFunction ( differentialFunction ) ; log . debug ( \"Step: {}; Executing op {} for node [{}]\" , exec_counter , opName , ownName ) ; // check if inputs are active nodes. skip step otherwise // please note: Exit node can't be skipped, because it's either rewind point or exit loop point boolean shouldSkip = false ; if ( differentialFunction instanceof Merge ) { val arg0 = args [ 0 ] ; val arg1 = args [ 1 ] ; if ( ! flowPath . isActive ( arg0 ) && ! flowPath . isActive ( arg1 ) ) shouldSkip = true ; } else { if ( ! ( differentialFunction instanceof Exit ) ) { // if we've left Exit nodes, we can finally delete last frame name if ( frameLeft ) { frameLeft = false ; val frame_name = frames . removeLast ( ) ; flowPath . activateFrame ( frame_name , false ) ; flowPath . forgetFrame ( frame_name ) ; } // we must check, if there's inactive nodes used as inputs for this node for ( val input : args ) { if ( ! flowPath . isActive ( input ) ) { // propagate inactivity flowPath . markActive ( differentialFunction . getOwnName ( ) , false ) ; shouldSkip = true ; break ; } } } } if ( shouldSkip ) continue ; differentialFunction . resolvePropertiesFromSameDiffBeforeExecution ( ) ; flowPath . markActive ( differentialFunction . getOwnName ( ) , true ) ; /**\n             * This set of operations (Enter/Exit/NextIteration/Exit/Switch) are special snowflakes: they modify graph execution order, and basically used here to replicate TF logic.\n             * Since SameDiff itself has own logic for loops and conditionals using Scopes\n             */ if ( differentialFunction instanceof LoopCond ) { // this node just passes single input forward, for future evaluation val inputs = getInputVariablesForFunction ( differentialFunction ) ; val array = inputs [ 0 ] . getArr ( ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) , array . dup ( array . ordering ( ) ) ) ; flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; if ( ( int ) array . getDouble ( 0 ) == 1 ) { val frameName = frames . getLast ( ) ; // incrementing number of cycles for THIS frame, only if LoopCond is true flowPath . incrementNumberOfCycles ( frameName ) ; } } else if ( differentialFunction instanceof Enter ) { //  if (flowPath.wasExecuted(differentialFunction.getOwnName())) //      continue; val inputs = getInputVariablesForFunction ( differentialFunction ) ; val array = inputs [ 0 ] . getArr ( ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) , array . dup ( array . ordering ( ) ) ) ; flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; // frame_name MUST be non-null here val frame_name = ( ( Enter ) differentialFunction ) . getFrameName ( ) ; if ( ! flowPath . isRegisteredFrame ( frame_name ) ) { flowPath . registerFrame ( frame_name ) ; frames . addLast ( frame_name ) ; inFrame = true ; } } else if ( differentialFunction instanceof Exit ) { // this is just exit point of graph: it maps own input to own output or rewinds graph to specific position planned at first NextIteration node val frame_name = frames . getLast ( ) ; // saving frame_name for backward pass ( ( Exit ) differentialFunction ) . setFrameName ( frame_name ) ; if ( ! flowPath . isFrameActive ( frame_name ) ) { flowPath . markActive ( differentialFunction . getOwnName ( ) , false ) ; // if frame is inactive, lets remove it from queue as well frameLeft = true ; continue ; } // Exit node is called in any way, doesn't matters if body was executed or not // so, we're checking if rewind was planned (so, NextIteration was executed before Exit) // and if it's TRUE - we're setting applying rewind by setting loop idx and calling continue if ( flowPath . isRewindPlanned ( frame_name ) ) { // just reset loop flowPath . planRewind ( frame_name , false ) ; val currentPosition = i ; i = flowPath . getRewindPosition ( frame_name ) ; val startPosition = i + 1 ; flowPath . setRewindPosition ( frame_name , - 1 ) ; continue ; } val inputs = getInputVariablesForFunction ( differentialFunction ) ; val array = inputs [ 0 ] . getArr ( ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) , array . dup ( array . ordering ( ) ) ) ; flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; // now it's safe to remove LastFrame frameLeft = true ; } else if ( differentialFunction instanceof NextIteration ) { // this operations merges own input, and schedules rewind to specific Merge node val inputs = getInputVariablesForFunction ( differentialFunction ) ; val frame_name = frames . getLast ( ) ; val array = inputs [ 0 ] . getArr ( ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) , array . dup ( array . ordering ( ) ) ) ; flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; // if NextIteration wasn't skipped with inactive branch, we'll plan rewind for this frame. obviously, only once if ( ! flowPath . isRewindPlanned ( frame_name ) ) { flowPath . planRewind ( frame_name , true ) ; continue ; } } else if ( differentialFunction instanceof Merge ) { // merge operation takes two inputs, and saves one of them as own output. // if SDVariable exists for second input - we use it. First input used otherwise val inputs = getInputVariablesForFunction ( differentialFunction ) ; val frame_name = frames . size ( ) > 0 ? frames . getLast ( ) : null ; if ( frame_name != null ) flowPath . activateFrame ( frame_name , true ) ; // frame_name can be null if this merge node is used for something that's not loop. i.e. switch/merge pair if ( frame_name != null ) flowPath . setRewindPositionOnce ( frame_name , i - 1 ) ; // NextIteration can have NO frame_name defined. so let's propagate it if ( inputs . length == 2 ) { val secondArg = functionInstancesById . get ( inputs [ 1 ] . getVarName ( ) ) ; if ( secondArg != null && secondArg instanceof NextIteration ) { ( ( NextIteration ) secondArg ) . setFrameName ( frame_name ) ; } } // we must check second input first here if ( flowPath . wasExecuted ( inputs [ 1 ] . getVarName ( ) ) ) { // propagate second input val array = inputs [ 1 ] . getArr ( ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) , array . dup ( array . ordering ( ) ) ) ; // nullify executed mark flowPath . markExecuted ( inputs [ 1 ] . getVarName ( ) , false ) ; } else { // propagate first input val array = inputs [ 0 ] . getArr ( ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) , array . dup ( array . ordering ( ) ) ) ; } flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; } else if ( differentialFunction instanceof Switch ) { // switch takes 2 inputs: actual input and boolean scalar. If scalar is false, input is saved as output:0, if scalar is true, input is saved as output:1 ( ( CustomOp ) differentialFunction ) . populateInputsAndOutputsFromSameDiff ( ) ; val inputs = getInputVariablesForFunction ( differentialFunction ) ; val input = inputs [ 0 ] . getArr ( ) ; val bool = inputs [ 1 ] . getArr ( ) ; // basically we're setting one of the graph branches inactive. branch 0 for false, branch 1 for true if ( ( int ) bool . getDouble ( 0 ) == 0 ) { // false step, we'll propagate output:0 here flowPath . setActiveBranch ( differentialFunction . getOwnName ( ) , 0 ) ; flowPath . markActive ( differentialFunction . getOwnName ( ) , true ) ; flowPath . markActive ( differentialFunction . getOwnName ( ) + \":1\" , false ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) , input . dup ( input . ordering ( ) ) ) ; } else { // true step, we'll propagate output:1 here flowPath . setActiveBranch ( differentialFunction . getOwnName ( ) , 1 ) ; variableNameToArr . put ( differentialFunction . getOwnName ( ) + \":1\" , input . dup ( input . ordering ( ) ) ) ; flowPath . markActive ( differentialFunction . getOwnName ( ) , false ) ; flowPath . markActive ( differentialFunction . getOwnName ( ) + \":1\" , true ) ; } flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; } else if ( differentialFunction instanceof If ) { If ifOp = ( If ) differentialFunction ; if ( ! onBackward ) { ifOp . getPredicateExecution ( ) . exec ( ) ; //depending on the block add the proper graph body to this for persistence //and possible later processing. if ( ifOp . getTargetBoolean ( ) . getArr ( ) . sumNumber ( ) . doubleValue ( ) > 0 ) { ifOp . getLoopBodyExecution ( ) . exec ( ) ; ifOp . exectedTrueOrFalse ( true ) ; } else { ifOp . getFalseBodyExecution ( ) . exec ( ) ; ifOp . exectedTrueOrFalse ( false ) ; } } else { if ( ifOp . getTrueBodyExecuted ( ) != null ) { Pair < Map < SDVariable , DifferentialFunction > , List < DifferentialFunction > > execBackwards = null ; List < SDVariable > variablesForFunctions = null ; if ( ifOp . getTrueBodyExecuted ( ) ) { execBackwards = ifOp . getLoopBodyExecution ( ) . execBackwards ( ) ; variablesForFunctions = ifOp . getLoopBodyExecution ( ) . getVariablesAssociatedWithFunctions ( execBackwards . getRight ( ) ) ; } else { execBackwards = ifOp . getFalseBodyExecution ( ) . execBackwards ( ) ; variablesForFunctions = ifOp . getFalseBodyExecution ( ) . getVariablesAssociatedWithFunctions ( execBackwards . getRight ( ) ) ; } /**\n                         * Maps the variables from the child namespace body to\n                         * the parent. This allows access to the underlying ndarray\n                         * and returning a valid variable reference for autodiff.\n                         */ for ( SDVariable variable : variablesForFunctions ) { SDVariable proxyVar = var ( variable ) ; } } else throw new ND4JIllegalStateException ( \"No body was run.\" ) ; } flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; ops . add ( differentialFunction ) ; } else if ( differentialFunction instanceof While ) { While whileOp = ( While ) differentialFunction ; if ( ! onBackward ) { SameDiff execBody = whileOp . getLoopBodyExecution ( ) ; //depending on the block add the proper graph body to this for persistence //and possible later processing. //note that we need to update the graph predicate by running the execution whileOp . getPredicateExecution ( ) . exec ( ) ; while ( whileOp . getTargetBoolean ( ) . getArr ( ) . sumNumber ( ) . doubleValue ( ) > 0 ) { //run the body execBody . exec ( ) ; //update the predicate whileOp . getPredicateExecution ( ) . exec ( ) ; whileOp . incrementLoopCounter ( ) ; } List < SDVariable > outputs = new ArrayList <> ( ) ; val outputFuncArgs = new ArrayList <> ( execBody . functionInstancesById . values ( ) ) . get ( execBody . functionInstancesById . values ( ) . size ( ) - 1 ) . outputVariables ( ) ; outputs . addAll ( Arrays . asList ( outputFuncArgs ) ) ; whileOp . setOutputVars ( outputs . toArray ( new SDVariable [ outputs . size ( ) ] ) ) ; ops . add ( differentialFunction ) ; } else { /**\n                     * Note: Need to accumulate gradients.\n                     * Multiply each value by the number of times looped.\n                     * This approximates accumulating the gradient\n                     * across a number of loop cycles.\n                     * We only compute the gradient for the internal loop once\n                     * and from that we multiply the gradient by 5.\n                     *\n                     */ Pair < Map < SDVariable , DifferentialFunction > , List < DifferentialFunction > > mapListPair = whileOp . getLoopBodyExecution ( ) . execBackwards ( ) ; for ( SDVariable variable : mapListPair . getFirst ( ) . keySet ( ) ) { variable . getArr ( ) . muli ( whileOp . getNumLooped ( ) ) ; } } flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; } else if ( differentialFunction instanceof CustomOp ) { DynamicCustomOp customOp = ( DynamicCustomOp ) differentialFunction ; customOp . populateInputsAndOutputsFromSameDiff ( ) ; customOp . assertValidForExecution ( ) ; customOp . updateInputsFromSameDiff ( ) ; Nd4j . getExecutioner ( ) . exec ( customOp ) ; /*\n                if (customOp instanceof LessThanOrEqual) {\n                    log.info(\"Step: {}; InnerCondition: {} <= {} = {}\", exec_counter, customOp.getInputArgument(0), customOp.getInputArgument(1), customOp.getOutputArgument(0));\n                } else if (customOp instanceof LessThan) {\n                    log.info(\"Step: {}; OuterCondition: {} <= {} = {}\", exec_counter, customOp.getInputArgument(0), customOp.getInputArgument(1), customOp.getOutputArgument(0));\n                }\n                */ flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; ops . add ( customOp ) ; } else if ( differentialFunction instanceof Op ) { val inputs = getInputVariablesForFunction ( differentialFunction ) ; Op op = ( Op ) differentialFunction ; // ops in differential function might have stale NDArrays used. we should renew them op . setX ( inputs [ 0 ] . getArr ( ) ) ; if ( inputs . length == 2 ) op . setY ( inputs [ 1 ] . getArr ( ) ) ; if ( differentialFunction . getDimensions ( ) == null ) Nd4j . getExecutioner ( ) . exec ( op ) ; else if ( op . isExecSpecial ( ) ) { op . exec ( ) ; } else { int [ ] axes = differentialFunction . getDimensions ( ) ; if ( differentialFunction instanceof Accumulation ) { Accumulation accumulation = ( Accumulation ) differentialFunction ; Nd4j . getExecutioner ( ) . exec ( accumulation , axes ) ; if ( differentialFunction . outputVariables ( ) [ 0 ] . getArr ( ) == null ) { val var = differentialFunction . outputVariables ( ) [ 0 ] ; updateArrayForVarName ( var . getVarName ( ) , accumulation . z ( ) ) ; updateShapeForVarName ( var . getVarName ( ) , accumulation . z ( ) . shape ( ) ) ; } } else if ( differentialFunction instanceof BroadcastOp ) { BroadcastOp broadcastOp = ( BroadcastOp ) differentialFunction ; Nd4j . getExecutioner ( ) . exec ( broadcastOp , axes ) ; } else if ( differentialFunction instanceof GradientOp ) { Nd4j . getExecutioner ( ) . exec ( op ) ; } else if ( differentialFunction instanceof IndexAccumulation ) { IndexAccumulation indexAccumulation = ( IndexAccumulation ) differentialFunction ; Nd4j . getExecutioner ( ) . exec ( indexAccumulation , axes ) ; } else if ( differentialFunction instanceof TransformOp ) { TransformOp t = ( TransformOp ) differentialFunction ; Nd4j . getExecutioner ( ) . exec ( t , axes ) ; } } flowPath . markExecuted ( differentialFunction . getOwnName ( ) , true ) ; ops . add ( differentialFunction ) ; } //debug // printFunction(differentialFunction); } return new Pair <> ( opMap , ops ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the given function for debugging ( will not print functions ) [CODESPLIT] public void printFunction ( DifferentialFunction differentialFunction ) { if ( ! logExecution ) return ; if ( differentialFunction instanceof SDVariable ) return ; StringBuilder argShapes = new StringBuilder ( ) ; for ( val arg : differentialFunction . args ( ) ) { argShapes . append ( \" Variable \" + arg . getVarName ( ) + \" Shape for \" + Arrays . toString ( arg . getShape ( ) ) ) ; } for ( val func : differentialFunction . outputVariables ( ) ) { argShapes . append ( \"  Output variable \" + func . getVarName ( ) + \" is \" + Arrays . toString ( func . getShape ( ) ) ) ; } StringBuilder realShapes = new StringBuilder ( ) ; for ( val arg : differentialFunction . args ( ) ) { realShapes . append ( \" Input shape for \" + arg . getVarName ( ) + \" is  \" + Arrays . toString ( getShapeForVarName ( arg . getVarName ( ) ) ) ) ; } for ( val arg : differentialFunction . outputVariables ( ) ) { realShapes . append ( \" Output shape for \" + arg . getVarName ( ) + \" is  \" + Arrays . toString ( getShapeForVarName ( arg . getVarName ( ) ) ) ) ; } //        log.info(realShapes.toString()); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Permute indices for the samediff / dl4j format . Due to the dl4j format being NCHW this is a simple routine for returning permute indices . This is typically used for model import . [CODESPLIT] public static int [ ] permuteDataFormatForSameDiff ( String dataFormat , boolean weights ) { val dl4jFormat = \"NCHW\" ; dataFormat = dataFormat . toUpperCase ( ) ; //TF: filter_height, filter_width, in_channels, out_channels /**\n         * N: filter_height\n         * H: filter_width\n         * W: in_channels\n         * C: out_channels\n         */ /**\n         *\n         *\n         */ //DL4J: filter_height,out_channels,filter_width,in_channels // Weights should be: out channels, in channels, height,width int [ ] ret = new int [ 4 ] ; if ( weights ) { ret [ 0 ] = dataFormat . indexOf ( ' ' ) ; ret [ 1 ] = dataFormat . indexOf ( ' ' ) ; ret [ 2 ] = dataFormat . indexOf ( ' ' ) ; ret [ 3 ] = dataFormat . indexOf ( ' ' ) ; return ret ; } //NHWC //DL4J: NCHW for ( int i = 0 ; i < dataFormat . length ( ) ; i ++ ) { if ( dl4jFormat . indexOf ( dataFormat . charAt ( i ) ) < 0 ) { throw new ND4JIllegalStateException ( \"Illegal convolution data format string passed in \" + dataFormat + \" must be some variant of NCHW\" ) ; } } for ( int i = 0 ; i < dl4jFormat . length ( ) ; i ++ ) { ret [ i ] = dl4jFormat . indexOf ( dataFormat . charAt ( i ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the { @link INDArray } ndarray for the given variable name [CODESPLIT] public void updateVariable ( String variableName , INDArray arr ) { if ( ! variableNameToArr . containsKey ( variableName ) ) putArrayForVarName ( variableName , arr ) ; else updateArrayForVarName ( variableName , arr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method exports given SameDiff instance into FlatBuffers [CODESPLIT] public ByteBuffer asFlatBuffers ( @ NonNull ExecutorConfiguration configuration ) { Nd4j . getExecutioner ( ) . commit ( ) ; FlatBufferBuilder bufferBuilder = new FlatBufferBuilder ( 1024 ) ; val idCounter = new AtomicInteger ( 0 ) ; val flatVariables = new ArrayList < Integer > ( ) ; val flatOffsets = new ArrayList < Integer > ( ) ; val flatNodes = new ArrayList < Integer > ( ) ; // first of all we build VariableSpace dump List < SDVariable > variableList = new ArrayList <> ( variables ( ) ) ; val reverseMap = new LinkedHashMap < String , Integer > ( ) ; val forwardMap = new LinkedHashMap < String , Integer > ( ) ; val framesMap = new LinkedHashMap < String , Integer > ( ) ; int idx = 0 ; for ( val variable : variables ( ) ) { log . debug ( \"Exporting variable: [{}]\" , variable . getVarName ( ) ) ; if ( variable . getArr ( ) == null || variable . getShape ( ) == null ) { //putArrayForVarName(variable.getVarName(), Nd4j.scalar(1.0)); //addAsPlaceHolder(variable.getVarName()); continue ; } val pair = parseVariable ( variable . getVarName ( ) ) ; reverseMap . put ( pair . getFirst ( ) , idCounter . incrementAndGet ( ) ) ; log . debug ( \"Adding [{}] as [{}]\" , pair . getFirst ( ) , idCounter . get ( ) ) ; val arr = variable . getArr ( ) ; int name = bufferBuilder . createString ( variable . getVarName ( ) ) ; int array = arr . toFlatArray ( bufferBuilder ) ; int id = IntPair . createIntPair ( bufferBuilder , idCounter . get ( ) , 0 ) ; int flatVariable = FlatVariable . createFlatVariable ( bufferBuilder , id , name , 0 , array , - 1 ) ; flatVariables . add ( flatVariable ) ; } //add functions for ( val func : functionInstancesById . values ( ) ) { flatNodes . add ( asFlatNode ( func , bufferBuilder , variableList , reverseMap , forwardMap , framesMap , idCounter ) ) ; } // we're dumping scopes now for ( val scope : sameDiffFunctionInstances . entrySet ( ) ) { flatNodes . add ( asFlatNode ( scope . getKey ( ) , scope . getValue ( ) , bufferBuilder ) ) ; val currVarList = new ArrayList < SDVariable > ( scope . getValue ( ) . variables ( ) ) ; // converting all ops from node for ( val node : scope . getValue ( ) . variables ( ) ) { INDArray arr = node . getArr ( ) ; if ( arr == null ) { //val otherArr = Nd4j.scalar(1.0); //scope.getValue().putArrayForVarName(node.getVarName(), otherArr); //log.warn(\"Adding placeholder for export for var name {}\", node.getVarName()); //arr = otherArr; continue ; } int name = bufferBuilder . createString ( node . getVarName ( ) ) ; int array = arr . toFlatArray ( bufferBuilder ) ; int id = IntPair . createIntPair ( bufferBuilder , ++ idx , 0 ) ; val pair = parseVariable ( node . getVarName ( ) ) ; reverseMap . put ( pair . getFirst ( ) , idx ) ; log . debug ( \"Adding [{}] as [{}]\" , pair . getFirst ( ) , idx ) ; int flatVariable = FlatVariable . createFlatVariable ( bufferBuilder , id , name , 0 , array , - 1 ) ; flatVariables . add ( flatVariable ) ; } //add functions for ( val func : scope . getValue ( ) . functionInstancesById . values ( ) ) { flatNodes . add ( asFlatNode ( func , bufferBuilder , currVarList , reverseMap , forwardMap , framesMap , idCounter ) ) ; } } int outputsOffset = FlatGraph . createVariablesVector ( bufferBuilder , Ints . toArray ( flatOffsets ) ) ; int variablesOffset = FlatGraph . createVariablesVector ( bufferBuilder , Ints . toArray ( flatVariables ) ) ; int nodesOffset = FlatGraph . createNodesVector ( bufferBuilder , Ints . toArray ( flatNodes ) ) ; int fg = FlatGraph . createFlatGraph ( bufferBuilder , 119 , variablesOffset , nodesOffset , outputsOffset , configuration . getFlatConfiguration ( bufferBuilder ) ) ; bufferBuilder . finish ( fg ) ; return bufferBuilder . dataBuffer ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns flattened graph . [CODESPLIT] public String asFlatPrint ( ) { val sb = new StringBuilder ( ) ; val fb = asFlatBuffers ( ) ; val graph = FlatGraph . getRootAsFlatGraph ( fb ) ; sb . append ( \"\\nExternal variables:\\n\\n\" ) ; for ( int e = 0 ; e < graph . variablesLength ( ) ; e ++ ) { val var = graph . variables ( e ) ; val ndarray = Nd4j . createFromFlatArray ( var . ndarray ( ) ) ; sb . append ( var . id ( ) . first ( ) ) . append ( \":<\" ) . append ( var . name ( ) ) . append ( \"> \" ) . append ( Arrays . toString ( ndarray . shapeInfoDataBuffer ( ) . asInt ( ) ) ) . append ( \"; Values: \" ) . append ( Arrays . toString ( ndarray . data ( ) . asFloat ( ) ) ) . append ( \";\\n\" ) ; } val map = Nd4j . getExecutioner ( ) . getCustomOperations ( ) ; sb . append ( \"\\nOps sequence:\\n\\n\" ) ; for ( int e = 0 ; e < graph . nodesLength ( ) ; e ++ ) { val node = graph . nodes ( e ) ; log . info ( \"{}:<{}>\" , node . id ( ) , node . name ( ) ) ; sb . append ( node . id ( ) ) . append ( \":<\" ) . append ( node . name ( ) ) . append ( \"> \" ) . append ( SameDiff . getTypeFromByte ( node . opType ( ) ) ) ; if ( SameDiff . getTypeFromByte ( node . opType ( ) ) != Op . Type . CUSTOM ) sb . append ( \": \" ) . append ( node . opNum ( ) ) ; else { val keys = map . keySet ( ) ; String opName = null ; for ( val k : keys ) { val d = map . get ( k ) ; if ( d . getHash ( ) == node . opNum ( ) ) opName = k ; } if ( opName == null ) opName = \"unknown\" ; sb . append ( \": \" ) . append ( opName ) ; } sb . append ( \"; Inputs: {\" ) ; for ( int i = 0 ; i < node . inputPairedLength ( ) ; i ++ ) { val pair = node . inputPaired ( i ) ; sb . append ( \"[\" ) . append ( pair . first ( ) ) . append ( \":\" ) . append ( pair . second ( ) ) . append ( \"]\" ) ; if ( i < node . inputPairedLength ( ) - 1 ) sb . append ( \", \" ) ; } sb . append ( \"};\" ) ; sb . append ( \" OpNum: {\" ) . append ( node . opNum ( ) ) . append ( \"};\" ) ; sb . append ( \"\\n\" ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method converts enums for DataType [CODESPLIT] public static DataBuffer . Type getDataTypeFromByte ( byte val ) { if ( val == DataType . FLOAT ) return DataBuffer . Type . FLOAT ; else if ( val == DataType . DOUBLE ) return DataBuffer . Type . DOUBLE ; else if ( val == DataType . HALF ) return DataBuffer . Type . HALF ; throw new UnsupportedOperationException ( \"Unsupported DataType: [\" + val + \"]\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method converts enums for DataType [CODESPLIT] public static byte getDataTypeAsByte ( DataBuffer . Type type ) { switch ( type ) { case FLOAT : return DataType . FLOAT ; case DOUBLE : return DataType . DOUBLE ; case HALF : return DataType . HALF ; case INT : return DataType . INT32 ; case LONG : return DataType . INT64 ; default : throw new ND4JIllegalStateException ( \"Unknown or unsupported DataType used: [\" + type + \"]\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method return operation ID for given op name / type pair . [CODESPLIT] public static long getOpNum ( String name , Op . Type type ) { if ( type == Op . Type . LOOP ) { return 0 ; } else if ( type == Op . Type . RETURN ) { return 40 ; } else if ( type == Op . Type . IF ) { return 30 ; } else if ( type == Op . Type . CONDITIONAL ) { return 10 ; } else if ( type == Op . Type . MERGE ) { return 60L ; } else if ( type == Op . Type . LOOP_COND ) { return 70L ; } else if ( type == Op . Type . NEXT_ITERATION ) { return 80L ; } else if ( type == Op . Type . EXIT ) { return 90L ; } else if ( type == Op . Type . ENTER ) { return 100L ; } else if ( type == Op . Type . CUSTOM ) { val name2 = Nd4j . getExecutioner ( ) . getCustomOperations ( ) . get ( name . toLowerCase ( ) ) ; if ( name2 == null ) return 0 ; return Nd4j . getExecutioner ( ) . getCustomOperations ( ) . get ( name . toLowerCase ( ) ) . getHash ( ) ; } else return ( long ) Nd4j . getOpFactory ( ) . getOpNumByName ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method converts enums for DataType [CODESPLIT] public static Op . Type getTypeFromByte ( byte type ) { switch ( type ) { case OpType . SCALAR : return Op . Type . SCALAR ; case OpType . BROADCAST : return Op . Type . BROADCAST ; case OpType . TRANSFORM : return Op . Type . TRANSFORM ; case OpType . ACCUMULATION : return Op . Type . REDUCE ; case OpType . ACCUMULATION3 : return Op . Type . REDUCE3 ; case OpType . INDEX_ACCUMULATION : return Op . Type . INDEXREDUCE ; case OpType . RANDOM : return Op . Type . RANDOM ; case OpType . LOGIC : return Op . Type . META ; case OpType . CUSTOM : return Op . Type . CUSTOM ; case OpType . SHAPE : return Op . Type . SHAPE ; case OpType . PAIRWISE : return Op . Type . PAIRWISE ; case OpType . SUMMARYSTATS : return Op . Type . SUMMARYSTATS ; default : throw new UnsupportedOperationException ( \"Unknown op type passed in: \" + type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method converts enums for DataType [CODESPLIT] public static byte getFlatOpType ( Op . Type type ) { switch ( type ) { case SCALAR : return OpType . SCALAR ; case BROADCAST : return OpType . BROADCAST ; case TRANSFORM : case SPECIAL : return OpType . TRANSFORM ; case REDUCE : return OpType . ACCUMULATION ; case REDUCE3 : return OpType . ACCUMULATION3 ; case INDEXREDUCE : return OpType . INDEX_ACCUMULATION ; case RANDOM : return OpType . RANDOM ; case MERGE : case CONDITIONAL : case LOOP : case RETURN : case ENTER : case EXIT : case NEXT_ITERATION : case LOOP_COND : case IF : return OpType . LOGIC ; case CUSTOM : return OpType . CUSTOM ; case SHAPE : return OpType . SHAPE ; case PAIRWISE : return OpType . PAIRWISE ; case SUMMARYSTATS : return OpType . SUMMARYSTATS ; default : throw new UnsupportedOperationException ( \"Unknown op type passed in: \" + type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns Pointer to allocated memory chunk [CODESPLIT] @ Override public Pointer allocate ( long bytes , MemoryKind kind , boolean initialize ) { AtomicAllocator allocator = AtomicAllocator . getInstance ( ) ; //log.info(\"Allocating {} bytes in {} memory...\", bytes, kind); if ( kind == MemoryKind . HOST ) { Pointer ptr = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . mallocHost ( bytes , 0 ) ; if ( ptr == null ) throw new RuntimeException ( \"Failed to allocate \" + bytes + \" bytes from HOST memory\" ) ; if ( initialize ) Pointer . memset ( ptr , 0 , bytes ) ; return ptr ; //allocator.getMemoryHandler().alloc(AllocationStatus.HOST, null, null, initialize).getHostPointer(); } else if ( kind == MemoryKind . DEVICE ) { Pointer ptr = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . mallocDevice ( bytes , null , 0 ) ; //log.info(\"Allocating {} bytes for device_{}\", bytes, Nd4j.getAffinityManager().getDeviceForCurrentThread()); if ( ptr == null ) throw new RuntimeException ( \"Failed to allocate \" + bytes + \" bytes from DEVICE [\" + Nd4j . getAffinityManager ( ) . getDeviceForCurrentThread ( ) + \"] memory\" ) ; if ( initialize ) { CudaContext context = ( CudaContext ) AtomicAllocator . getInstance ( ) . getDeviceContext ( ) . getContext ( ) ; int i = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) . memsetAsync ( ptr , 0 , bytes , 0 , context . getSpecialStream ( ) ) ; if ( i == 0 ) throw new ND4JIllegalStateException ( \"memset failed on device_\" + Nd4j . getAffinityManager ( ) . getDeviceForCurrentThread ( ) ) ; context . getSpecialStream ( ) . synchronize ( ) ; } return ptr ; //allocator.getMemoryHandler().alloc(AllocationStatus.HOST, null, null, initialize).getDevicePointer(); } else throw new RuntimeException ( \"Unknown MemoryKind requested: \" + kind ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data for the underlying array . If the underlying buffer s array is equivalent to this array it returns ( avoiding an unneccessary copy ) [CODESPLIT] public static void setData ( float [ ] data , INDArray toSet ) { if ( toSet . data ( ) . dataType ( ) != DataBuffer . Type . FLOAT ) { throw new IllegalArgumentException ( \"Unable to set double data for opType \" + toSet . data ( ) . dataType ( ) ) ; } if ( toSet . data ( ) . allocationMode ( ) == DataBuffer . AllocationMode . HEAP ) { Object array = toSet . data ( ) . array ( ) ; //data is assumed to have already been updated if ( array == data ) return ; else { //copy the data over directly to the underlying array float [ ] d = ( float [ ] ) array ; if ( toSet . offset ( ) == 0 && toSet . length ( ) == data . length ) System . arraycopy ( data , 0 , d , 0 , d . length ) ; else { int count = 0 ; //need to do strided access with offset for ( int i = 0 ; i < data . length ; i ++ ) { // FIXME: LONG int dIndex = ( int ) toSet . offset ( ) + ( i * toSet . majorStride ( ) ) ; d [ dIndex ] = data [ count ++ ] ; } } } } else { //assumes the underlying data is in the right order DataBuffer underlyingData = toSet . data ( ) ; if ( data . length == toSet . length ( ) && toSet . offset ( ) == 0 ) { for ( int i = 0 ; i < toSet . length ( ) ; i ++ ) { underlyingData . put ( i , data [ i ] ) ; } } else { int count = 0 ; //need to do strided access with offset for ( int i = 0 ; i < data . length ; i ++ ) { // FIXME: LONG int dIndex = ( int ) toSet . offset ( ) + ( i * toSet . majorStride ( ) ) ; underlyingData . put ( dIndex , data [ count ++ ] ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the length for the given data opType [CODESPLIT] public static int lengthForDtype ( DataBuffer . Type type ) { switch ( type ) { case DOUBLE : return 8 ; case FLOAT : return 4 ; case INT : return 4 ; case HALF : return 2 ; case LONG : return 8 ; case COMPRESSED : default : throw new IllegalArgumentException ( \"Illegal opType for length\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the allocation mode from the context [CODESPLIT] public static DataBuffer . Type getDtypeFromContext ( String dType ) { switch ( dType ) { case \"double\" : return DataBuffer . Type . DOUBLE ; case \"float\" : return DataBuffer . Type . FLOAT ; case \"int\" : return DataBuffer . Type . INT ; case \"half\" : return DataBuffer . Type . HALF ; default : return DataBuffer . Type . FLOAT ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the name of the alocation mode [CODESPLIT] public static String getDTypeForName ( DataBuffer . Type allocationMode ) { switch ( allocationMode ) { case DOUBLE : return \"double\" ; case FLOAT : return \"float\" ; case INT : return \"int\" ; case HALF : return \"half\" ; default : return \"float\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the allocation mode from the context [CODESPLIT] public static DataBuffer . Type getDtypeFromContext ( ) { try { lock . readLock ( ) . lock ( ) ; if ( dtype == null ) { lock . readLock ( ) . unlock ( ) ; lock . writeLock ( ) . lock ( ) ; if ( dtype == null ) dtype = getDtypeFromContext ( Nd4jContext . getInstance ( ) . getConf ( ) . getProperty ( \"dtype\" ) ) ; lock . writeLock ( ) . unlock ( ) ; lock . readLock ( ) . lock ( ) ; } return dtype ; } finally { lock . readLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the allocation mode for the nd4j context The value must be one of : heap java cpp or direct or an [CODESPLIT] public static void setDTypeForContext ( DataBuffer . Type allocationModeForContext ) { try { lock . writeLock ( ) . lock ( ) ; dtype = allocationModeForContext ; setDTypeForContext ( getDTypeForName ( allocationModeForContext ) ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns op id number for given opName [CODESPLIT] @ Override public int getOpNumByName ( String opName ) { try { DifferentialFunction op = DifferentialFunctionClassHolder . getInstance ( ) . getInstance ( opName ) ; return op . opNum ( ) ; } catch ( Exception e ) { throw new RuntimeException ( \"OpName failed: [\" + opName + \"]\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * @Override public MemoryWorkspace getWorkspaceForCurrentThread ( @NonNull WorkspaceConfiguration configuration @NonNull String id ) { ensureThreadExistense () ; [CODESPLIT] protected void pickReference ( MemoryWorkspace workspace ) { Nd4jWorkspace . GarbageWorkspaceReference reference = new Nd4jWorkspace . GarbageWorkspaceReference ( workspace , queue ) ; referenceMap . put ( reference . getKey ( ) , reference ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method destroys all workspaces allocated in current thread [CODESPLIT] @ Override public void destroyAllWorkspacesForCurrentThread ( ) { ensureThreadExistense ( ) ; List < MemoryWorkspace > workspaces = new ArrayList <> ( ) ; workspaces . addAll ( backingMap . get ( ) . values ( ) ) ; for ( MemoryWorkspace workspace : workspaces ) { destroyWorkspace ( workspace ) ; } System . gc ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method prints out basic statistics for workspaces allocated in current thread [CODESPLIT] public synchronized void printAllocationStatisticsForCurrentThread ( ) { ensureThreadExistense ( ) ; Map < String , MemoryWorkspace > map = backingMap . get ( ) ; log . info ( \"Workspace statistics: ---------------------------------\" ) ; log . info ( \"Number of workspaces in current thread: {}\" , map . size ( ) ) ; log . info ( \"Workspace name: Allocated / external (spilled) / external (pinned)\" ) ; for ( String key : map . keySet ( ) ) { long current = ( ( Nd4jWorkspace ) map . get ( key ) ) . getCurrentSize ( ) ; long spilled = ( ( Nd4jWorkspace ) map . get ( key ) ) . getSpilledSize ( ) ; long pinned = ( ( Nd4jWorkspace ) map . get ( key ) ) . getPinnedSize ( ) ; log . info ( String . format ( \"%-26s %8s / %8s / %8s (%11d / %11d / %11d)\" , ( key + \":\" ) , StringUtils . TraditionalBinaryPrefix . long2String ( current , \"\" , 2 ) , StringUtils . TraditionalBinaryPrefix . long2String ( spilled , \"\" , 2 ) , StringUtils . TraditionalBinaryPrefix . long2String ( pinned , \"\" , 2 ) , current , spilled , pinned ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gemv computes a matrix - vector product using a general matrix and performs one of the following matrix - vector operations : y : = alpha * a * x + beta * y for trans = N or n ; y : = alpha * a * x + beta * y for trans = T or t ; y : = alpha * conjg ( a ) * x + beta * y for trans = C or c . Here a is an m - by - n band matrix x and y are vectors alpha and beta are scalars . [CODESPLIT] @ Override public void gemv ( char order , char transA , double alpha , INDArray A , INDArray X , double beta , INDArray Y ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , A , X , Y ) ; if ( A . isSparse ( ) && ! X . isSparse ( ) ) { Nd4j . getSparseBlasWrapper ( ) . level2 ( ) . gemv ( order , transA , alpha , A , X , beta , Y ) ; return ; } GemvParameters parameters = new GemvParameters ( A , X , Y ) ; if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , parameters . getA ( ) , parameters . getX ( ) , parameters . getY ( ) ) ; dgemv ( order , parameters . getAOrdering ( ) , parameters . getM ( ) , parameters . getN ( ) , alpha , parameters . getA ( ) , parameters . getLda ( ) , parameters . getX ( ) , parameters . getIncx ( ) , beta , parameters . getY ( ) , parameters . getIncy ( ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , parameters . getA ( ) , parameters . getX ( ) , parameters . getY ( ) ) ; sgemv ( order , parameters . getAOrdering ( ) , parameters . getM ( ) , parameters . getN ( ) , ( float ) alpha , parameters . getA ( ) , parameters . getLda ( ) , parameters . getX ( ) , parameters . getIncx ( ) , ( float ) beta , parameters . getY ( ) , parameters . getIncy ( ) ) ; } OpExecutionerUtil . checkForAny ( Y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gemv computes a matrix - vector product using a general matrix and performs one of the following matrix - vector operations : y : = alpha * a * x + beta * y for trans = N or n ; y : = alpha * a * x + beta * y for trans = T or t ; y : = alpha * conjg ( a ) * x + beta * y for trans = C or c . Here a is an m - by - n band matrix x and y are vectors alpha and beta are scalars . [CODESPLIT] @ Override public void gemv ( char order , char transA , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray X , IComplexNumber beta , IComplexNDArray Y ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , A , X , Y ) ; GemvParameters parameters = new GemvParameters ( A , X , Y ) ; if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zgemv ( order , transA , parameters . getM ( ) , parameters . getN ( ) , alpha . asDouble ( ) , A , parameters . getLda ( ) , X , parameters . getIncx ( ) , beta . asDouble ( ) , Y , parameters . getIncy ( ) ) ; else cgemv ( order , transA , parameters . getM ( ) , parameters . getN ( ) , alpha . asFloat ( ) , A , parameters . getLda ( ) , X , parameters . getIncx ( ) , beta . asFloat ( ) , Y , parameters . getIncy ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gbmv computes a matrix - vector product using a general band matrix and performs one of the following matrix - vector operations : y : = alpha * a * x + beta * y for trans = N or n ; y : = alpha * a * x + beta * y for trans = T or t ; y : = alpha * conjg ( a ) * x + beta * y for trans = C or c . Here a is an m - by - n band matrix with ku superdiagonals and kl subdiagonals x and y are vectors alpha and beta are scalars . [CODESPLIT] @ Override public void gbmv ( char order , char TransA , int KL , int KU , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray X , IComplexNumber beta , IComplexNDArray Y ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { zgbmv ( order , TransA , ( int ) A . rows ( ) , ( int ) A . columns ( ) , KL , KU , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) / 2 , beta . asDouble ( ) , Y , Y . majorStride ( ) / 2 ) ; } else { cgbmv ( order , TransA , ( int ) A . rows ( ) , ( int ) A . columns ( ) , KL , KU , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) / 2 , beta . asFloat ( ) , Y , Y . majorStride ( ) / 2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "performs a rank - 1 update of a general m - by - n matrix a without conjugation : a : = alpha * x * y + a . [CODESPLIT] @ Override public void geru ( char order , IComplexNumber alpha , IComplexNDArray X , IComplexNDArray Y , IComplexNDArray A ) { // FIXME: int cast if ( X . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zgeru ( order , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , X , X . majorStride ( ) / 2 , Y , Y . majorStride ( ) / 2 , A , ( int ) A . size ( 0 ) ) ; else cgeru ( order , ( int ) A . rows ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , X , X . majorStride ( ) / 2 , Y , Y . majorStride ( ) / 2 , A , ( int ) A . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "performs a rank - 1 update of a general m - by - n matrix a without conjugation : a : = alpha * x * y + a . [CODESPLIT] @ Override public void hbmv ( char order , char Uplo , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray X , IComplexNumber beta , IComplexNDArray Y ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zhbmv ( order , Uplo , ( int ) X . length ( ) , ( int ) A . columns ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) / 2 , beta . asDouble ( ) , Y , Y . majorStride ( ) / 2 ) ; else chbmv ( order , Uplo , ( int ) X . length ( ) , ( int ) A . columns ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) / 2 , beta . asFloat ( ) , Y , Y . majorStride ( ) / 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hemv computes a matrix - vector product using a Hermitian matrix : y : = alpha * a * x + beta * y . Here a is an n - by - n Hermitian band matrix with k superdiagonals x and y are n - element vectors alpha and beta are scalars . [CODESPLIT] @ Override public void hemv ( char order , char Uplo , IComplexNumber alpha , IComplexNDArray A , IComplexNDArray X , IComplexNumber beta , IComplexNDArray Y ) { // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zhemv ( order , Uplo , ( int ) A . rows ( ) , alpha . asDouble ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) / 2 , beta . asDouble ( ) , Y , Y . majorStride ( ) / 2 ) ; else chemv ( order , Uplo , ( int ) A . rows ( ) , alpha . asFloat ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) / 2 , beta . asFloat ( ) , Y , Y . majorStride ( ) / 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "?her2 performs a rank - 2 update of an n - by - n Hermitian matrix a : a : = alpha * x * conjg ( y ) + conjg ( alpha ) * y * conjg ( x ) + a . [CODESPLIT] @ Override public void her2 ( char order , char Uplo , IComplexNumber alpha , IComplexNDArray X , IComplexNDArray Y , IComplexNDArray A ) { // FIXME: int cast if ( X . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zher2 ( order , Uplo , ( int ) A . rows ( ) , alpha . asDouble ( ) , X , X . majorStride ( ) / 2 , Y , Y . majorStride ( ) / 2 , A , ( int ) A . size ( 0 ) ) ; else cher2 ( order , Uplo , ( int ) A . rows ( ) , alpha . asFloat ( ) , X , X . majorStride ( ) / 2 , Y , Y . majorStride ( ) / 2 , A , ( int ) A . size ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "?hpmv computes a matrix - vector product using a Hermitian packed matrix : y : = alpha * a * x + beta * y . Here a is an n - by - n packed Hermitian matrix x and y are n - element vectors alpha and beta are scalars . [CODESPLIT] @ Override public void hpmv ( char order , char Uplo , int N , IComplexNumber alpha , IComplexNDArray Ap , IComplexNDArray X , IComplexNumber beta , IComplexNDArray Y ) { // FIXME: int cast if ( Ap . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zhpmv ( order , Uplo , ( int ) Ap . rows ( ) , alpha . asDouble ( ) , Ap , X , X . majorStride ( ) / 2 , beta . asDouble ( ) , Y , Y . majorStride ( ) / 2 ) ; else chpmv ( order , Uplo , ( int ) Ap . rows ( ) , alpha . asFloat ( ) , Ap , X , X . majorStride ( ) / 2 , beta . asFloat ( ) , Y , Y . majorStride ( ) / 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hpr2 performs a rank - 2 update of an n - by - n packed Hermitian matrix a : a : = alpha * x * conjg ( y ) + conjg ( alpha ) * y * conjg ( x ) + a . [CODESPLIT] @ Override public void hpr2 ( char order , char Uplo , IComplexNumber alpha , IComplexNDArray X , IComplexNDArray Y , IComplexNDArray Ap ) { // FIXME: int cast if ( X . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zhpr2 ( order , Uplo , ( int ) Ap . rows ( ) , alpha . asDouble ( ) , X , X . majorStride ( ) / 2 , Y , Y . majorStride ( ) / 2 , Ap ) ; else chpr2 ( order , Uplo , ( int ) Ap . rows ( ) , alpha . asFloat ( ) , X , X . majorStride ( ) / 2 , Y , Y . majorStride ( ) / 2 , Ap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sbmv computes a matrix - vector product using a symmetric band matrix : y : = alpha * a * x + beta * y . Here a is an n - by - n symmetric band matrix with k superdiagonals x and y are n - element vectors alpha and beta are scalars . [CODESPLIT] @ Override public void sbmv ( char order , char Uplo , double alpha , INDArray A , INDArray X , double beta , INDArray Y ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , A , X , Y ) ; // FIXME: int cast if ( X . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , A , X , Y ) ; dsbmv ( order , Uplo , ( int ) X . length ( ) , ( int ) A . columns ( ) , alpha , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) , beta , Y , ( int ) Y . majorStride ( ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , A , X , Y ) ; ssbmv ( order , Uplo , ( int ) X . length ( ) , ( int ) A . columns ( ) , ( float ) alpha , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) , ( float ) beta , Y , Y . majorStride ( ) ) ; } OpExecutionerUtil . checkForAny ( Y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "syr2 performs a rank - 2 update of an n - by - n symmetric matrix a : a : = alpha * x * y + alpha * y * x + a . [CODESPLIT] @ Override public void tbmv ( char order , char Uplo , char TransA , char Diag , INDArray A , INDArray X ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , A , X ) ; // FIXME: int cast if ( X . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , A , X ) ; dtbmv ( order , Uplo , TransA , Diag , ( int ) X . length ( ) , ( int ) A . columns ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , A , X ) ; stbmv ( order , Uplo , TransA , Diag , ( int ) X . length ( ) , ( int ) A . columns ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "trmv computes a matrix - vector product using a triangular matrix . [CODESPLIT] @ Override public void trmv ( char order , char Uplo , char TransA , char Diag , INDArray A , INDArray X ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , A , X ) ; // FIXME: int cast if ( A . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , A , X ) ; dtrmv ( order , Uplo , TransA , Diag , ( int ) X . length ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , A , X ) ; strmv ( order , Uplo , TransA , Diag , ( int ) X . length ( ) , A , ( int ) A . size ( 0 ) , X , X . majorStride ( ) ) ; } OpExecutionerUtil . checkForAny ( X ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive an ndarray [CODESPLIT] public INDArray receive ( ) { if ( consumerTemplate == null ) consumerTemplate = camelContext . createConsumerTemplate ( ) ; return consumerTemplate . receiveBody ( \"direct:receive\" , INDArray . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Given a list of labels return the bernoulli prob that the masks will be sampled at to meet the target minority label distribution [CODESPLIT] private INDArray calculateBernoulli ( INDArray minorityLabels , INDArray labelMask , double targetMinorityDist ) { INDArray minorityClass = minorityLabels . dup ( ) . muli ( labelMask ) ; INDArray majorityClass = Transforms . not ( minorityLabels ) . muli ( labelMask ) ; //all minorityLabel class, keep masks as is //presence of minoriy class and donotmask minority windows set to true return label as is if ( majorityClass . sumNumber ( ) . intValue ( ) == 0 || ( minorityClass . sumNumber ( ) . intValue ( ) > 0 && donotMaskMinorityWindows ) ) return labelMask ; //all majority class and set to not mask all majority windows sample majority class by 1-targetMinorityDist if ( minorityClass . sumNumber ( ) . intValue ( ) == 0 && ! maskAllMajorityWindows ) return labelMask . muli ( 1 - targetMinorityDist ) ; //Probabilities to be used for bernoulli sampling INDArray minoritymajorityRatio = minorityClass . sum ( 1 ) . div ( majorityClass . sum ( 1 ) ) ; INDArray majorityBernoulliP = minoritymajorityRatio . muli ( 1 - targetMinorityDist ) . divi ( targetMinorityDist ) ; BooleanIndexing . replaceWhere ( majorityBernoulliP , 1.0 , Conditions . greaterThan ( 1.0 ) ) ; //if minority ratio is already met round down to 1.0 return majorityClass . muliColumnVector ( majorityBernoulliP ) . addi ( minorityClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute an accumulation along one or more dimensions [CODESPLIT] @ Override public INDArray exec ( Variance accumulation , boolean biasCorrected , int ... dimension ) { return processOp ( accumulation ) . z ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes specific RandomOp against specified RNG [CODESPLIT] @ Override public INDArray exec ( RandomOp op , Random rng ) { return processOp ( op ) . z ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method encodes array as thresholds updating input array at the same time [CODESPLIT] @ Override public INDArray thresholdEncode ( INDArray input , double threshold ) { return backendExecutioner . thresholdEncode ( input , threshold ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method encodes array as thresholds updating input array at the same time [CODESPLIT] @ Override public INDArray thresholdEncode ( INDArray input , double threshold , Integer boundary ) { return backendExecutioner . thresholdEncode ( input , threshold , boundary ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method decodes thresholds array and puts it into target array [CODESPLIT] @ Override public INDArray thresholdDecode ( INDArray encoded , INDArray target ) { return backendExecutioner . thresholdDecode ( encoded , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize a data array [CODESPLIT] @ Override public void preProcess ( INDArray array , INDArray maskArray , DistributionStats stats ) { if ( array . rank ( ) <= 2 ) { array . subiRowVector ( stats . getMean ( ) ) ; array . diviRowVector ( filteredStd ( stats ) ) ; } // if array Rank is 3 (time series) samplesxfeaturesxtimesteps // if array Rank is 4 (images) samplesxchannelsxrowsxcols // both cases operations should be carried out in dimension 1 else { Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastSubOp ( array , stats . getMean ( ) , array , 1 ) ) ; Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastDivOp ( array , filteredStd ( stats ) , array , 1 ) ) ; } if ( maskArray != null ) { DataSetUtil . setMaskedValuesToZero ( array , maskArray ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Denormalize a data array [CODESPLIT] @ Override public void revert ( INDArray array , INDArray maskArray , DistributionStats stats ) { if ( array . rank ( ) <= 2 ) { array . muliRowVector ( filteredStd ( stats ) ) ; array . addiRowVector ( stats . getMean ( ) ) ; } else { Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastMulOp ( array , filteredStd ( stats ) , array , 1 ) ) ; Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastAddOp ( array , stats . getMean ( ) , array , 1 ) ) ; } if ( maskArray != null ) { DataSetUtil . setMaskedValuesToZero ( array , maskArray ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map a tensorflow node name to the samediff equivalent for import [CODESPLIT] public String getNodeName ( String name ) { //tensorflow adds colons to the end of variables representing input index, this strips those off String ret = name ; if ( ret . startsWith ( \"^\" ) ) ret = ret . substring ( 1 ) ; if ( ret . endsWith ( \"/read\" ) ) { ret = ret . replace ( \"/read\" , \"\" ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ScalarOp along dimension [CODESPLIT] private void invoke ( ScalarOp op , int [ ] dimension ) { dimension = Shape . normalizeAxis ( op . x ( ) . rank ( ) , dimension ) ; // do tad magic /**\n         * Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}\n         * and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}\n         * The first item is the shape information. The second one is the offsets.\n         */ Pair < DataBuffer , DataBuffer > tadBuffers = tadManager . getTADOnlyShapeInfo ( op . x ( ) , dimension ) ; Pointer hostTadShapeInfo = tadBuffers . getFirst ( ) . addressPointer ( ) ; Pointer hostTadOffsets = tadBuffers . getSecond ( ) . addressPointer ( ) ; Pointer devTadShapeInfoZ = null ; Pointer devTadOffsetsZ = null ; /**\n         * Returns the {@link Shape#createShapeInformation(int[], int[], int, int, char)}\n         * and the associated offsets for each {@link INDArray#tensorAlongDimension(int, int...)}\n         * The first item is the shape information. The second one is the offsets.\n         *\n         * Note that this is the *result* TAD information. An op is always input (x) and output (z)\n         * for result.\n         * This is for assigning the result to of the operation along\n         * the proper dimension.\n         */ Pair < DataBuffer , DataBuffer > tadBuffersZ = tadManager . getTADOnlyShapeInfo ( op . z ( ) , dimension ) ; devTadShapeInfoZ = tadBuffersZ . getFirst ( ) . addressPointer ( ) ; devTadOffsetsZ = tadBuffersZ . getSecond ( ) . addressPointer ( ) ; if ( extraz . get ( ) == null ) extraz . set ( new PointerPointer ( 32 ) ) ; PointerPointer dummy = extraz . get ( ) . put ( hostTadShapeInfo , hostTadOffsets , devTadShapeInfoZ , devTadOffsetsZ ) ; if ( op . x ( ) . data ( ) . dataType ( ) == DataBuffer . Type . FLOAT ) { loop . execScalarFloat ( dummy , op . opNum ( ) , ( FloatPointer ) op . x ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . x ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . y ( ) . data ( ) . addressPointer ( ) , ( FloatPointer ) getPointerForExtraArgs ( op ) , ( IntPointer ) Nd4j . getConstantHandler ( ) . getConstantBuffer ( dimension ) . addressPointer ( ) , dimension . length ) ; } else if ( op . x ( ) . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { loop . execScalarDouble ( dummy , op . opNum ( ) , ( DoublePointer ) op . x ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . x ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . y ( ) . data ( ) . addressPointer ( ) , ( DoublePointer ) getPointerForExtraArgs ( op ) , ( IntPointer ) Nd4j . getConstantHandler ( ) . getConstantBuffer ( dimension ) . addressPointer ( ) , dimension . length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method takes arbitrary sized list of { [CODESPLIT] @ Override public void exec ( Aggregate op ) { // long st = profilingHookIn(op); if ( memoryBlocks . get ( ) == null ) memoryBlocks . set ( new HashMap < Integer , AggregateMemoryBlock > ( ) ) ; if ( memoryBlocks . get ( ) . get ( op . opNum ( ) ) == null ) memoryBlocks . get ( ) . put ( op . opNum ( ) , new AggregateMemoryBlock ( op ) ) ; AggregateMemoryBlock block = memoryBlocks . get ( ) . get ( op . opNum ( ) ) ; int numArguments = op . getArguments ( ) . size ( ) ; int numIndexArguments = op . getIndexingArguments ( ) . size ( ) ; int numRealArguments = op . getRealArguments ( ) . size ( ) ; int numShapes = op . getShapes ( ) . size ( ) ; int numIntArrays = op . getIntArrayArguments ( ) . size ( ) ; PointerPointer arguments = block . getArgumentsPointer ( ) ; //new PointerPointer(numArguments); List < IntPointer > pointers = new ArrayList <> ( ) ; PointerPointer intArrays = block . getArraysPointer ( ) ; //new PointerPointer(numIntArrays); for ( int x = 0 ; x < numArguments ; x ++ ) { arguments . put ( x , op . getArguments ( ) . get ( x ) == null ? null : op . getArguments ( ) . get ( x ) . data ( ) . addressPointer ( ) ) ; } PointerPointer shapes = block . getShapesPointer ( ) ; //new PointerPointer(numShapes); for ( int x = 0 ; x < numShapes ; x ++ ) { if ( op . getShapes ( ) . get ( x ) . dataType ( ) != DataBuffer . Type . INT ) throw new RuntimeException ( \"ShapeBuffers should have INT data opType\" ) ; shapes . put ( x , op . getShapes ( ) . get ( x ) == null ? null : op . getShapes ( ) . get ( x ) . addressPointer ( ) ) ; } //int[] indexes = new int[numIndexArguments]; IntPointer pointer = block . getIndexingPointer ( ) ; for ( int x = 0 ; x < numIndexArguments ; x ++ ) { pointer . put ( x , op . getIndexingArguments ( ) . get ( x ) ) ; } //IntPointer pointer = new IntPointer(indexes); double [ ] reals = new double [ numRealArguments ] ; for ( int x = 0 ; x < numRealArguments ; x ++ ) { //reals[x] = op.getRealArguments().get(x).doubleValue(); if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) ( ( FloatPointer ) block . getRealArgumentsPointer ( ) ) . put ( x , op . getRealArguments ( ) . get ( x ) . floatValue ( ) ) ; else ( ( DoublePointer ) block . getRealArgumentsPointer ( ) ) . put ( x , op . getRealArguments ( ) . get ( x ) . doubleValue ( ) ) ; } for ( int x = 0 ; x < numIntArrays ; x ++ ) { IntPointer intPtr = block . getIntArrays ( ) . get ( x ) ; //new IntPointer(op.getIntArrayArguments().get(x)); intPtr . put ( op . getIntArrayArguments ( ) . get ( x ) , 0 , op . getIntArrayArguments ( ) . get ( x ) . length ) ; intArrays . put ( x , intPtr ) ; pointers . add ( intPtr ) ; } //INDArray realsBuffer = Nd4j.create(reals); if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) { loop . execAggregateFloat ( null , op . opNum ( ) , arguments , numArguments , shapes , numShapes , pointer , numIndexArguments , intArrays , numIntArrays , ( FloatPointer ) block . getRealArgumentsPointer ( ) , numRealArguments ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) { loop . execAggregateDouble ( null , op . opNum ( ) , arguments , numArguments , shapes , numShapes , pointer , numIndexArguments , intArrays , numIntArrays , ( DoublePointer ) block . getRealArgumentsPointer ( ) , numRealArguments ) ; } else { throw new UnsupportedOperationException ( \"Half precision isn't supported on CPU\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method return set of key / value and key / key / value objects describing current environment [CODESPLIT] @ Override public Properties getEnvironmentInformation ( ) { Properties properties = super . getEnvironmentInformation ( ) ; properties . put ( Nd4jEnvironment . BACKEND_KEY , \"CPU\" ) ; properties . put ( Nd4jEnvironment . OMP_THREADS_KEY , loop . ompGetMaxThreads ( ) ) ; properties . put ( Nd4jEnvironment . BLAS_THREADS_KEY , Nd4j . factory ( ) . blas ( ) . getMaxThreads ( ) ) ; properties . put ( Nd4jEnvironment . BLAS_VENDOR_KEY , ( Nd4j . factory ( ) . blas ( ) ) . getBlasVendor ( ) . toString ( ) ) ; properties . put ( Nd4jEnvironment . HOST_FREE_MEMORY_KEY , Pointer . maxBytes ( ) - Pointer . totalBytes ( ) ) ; // fill bandwidth information properties . put ( Nd4jEnvironment . MEMORY_BANDWIDTH_KEY , PerformanceTracker . getInstance ( ) . getCurrentBandwidth ( ) ) ; return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes specific RandomOp against specified RNG [CODESPLIT] @ Override public INDArray exec ( RandomOp op , Random rng ) { if ( rng . getStateBuffer ( ) == null ) throw new IllegalStateException ( \"You should use one of NativeRandom classes for NativeOperations execution\" ) ; long st = profilingHookIn ( op ) ; validateDataType ( Nd4j . dataType ( ) , op ) ; if ( op . x ( ) != null && op . y ( ) != null && op . z ( ) != null ) { // triple arg call if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) { loop . execRandomFloat ( null , op . opNum ( ) , rng . getStatePointer ( ) , // rng state ptr ( FloatPointer ) op . x ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . x ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . y ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . y ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . extraArgsDataBuff ( ) . addressPointer ( ) ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) { loop . execRandomDouble ( null , op . opNum ( ) , rng . getStatePointer ( ) , // rng state ptr ( DoublePointer ) op . x ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . x ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . y ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . y ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . extraArgsDataBuff ( ) . addressPointer ( ) ) ; } } else if ( op . x ( ) != null && op . z ( ) != null ) { //double arg call if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) { loop . execRandomFloat ( null , op . opNum ( ) , rng . getStatePointer ( ) , // rng state ptr ( FloatPointer ) op . x ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . x ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . extraArgsDataBuff ( ) . addressPointer ( ) ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) { loop . execRandomDouble ( null , op . opNum ( ) , rng . getStatePointer ( ) , // rng state ptr ( DoublePointer ) op . x ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . x ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . extraArgsDataBuff ( ) . addressPointer ( ) ) ; } } else { // single arg call if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) { loop . execRandomFloat ( null , op . opNum ( ) , rng . getStatePointer ( ) , // rng state ptr ( FloatPointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( FloatPointer ) op . extraArgsDataBuff ( ) . addressPointer ( ) ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) { loop . execRandomDouble ( null , op . opNum ( ) , rng . getStatePointer ( ) , // rng state ptr ( DoublePointer ) op . z ( ) . data ( ) . addressPointer ( ) , ( LongPointer ) op . z ( ) . shapeInfoDataBuffer ( ) . addressPointer ( ) , ( DoublePointer ) op . extraArgsDataBuff ( ) . addressPointer ( ) ) ; } } profilingHookOut ( op , st ) ; return op . z ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes given CustomOp [CODESPLIT] public void exec ( @ NonNull CustomOp op ) { long st = profilingHookIn ( op ) ; if ( op . numOutputArguments ( ) == 0 && ! op . isInplaceCall ( ) ) throw new ND4JIllegalStateException ( \"Op name \" + op . opName ( ) + \" failed to execute. You can't execute non-inplace CustomOp without outputs being specified\" ) ; val name = op . opName ( ) . toLowerCase ( ) ; val hash = op . opHash ( ) ; val inputShapes = getInputShapes ( op . numInputArguments ( ) ) ; val inputBuffers = getInputBuffers ( op . numInputArguments ( ) ) ; int cnt = 0 ; val inputArgs = op . inputArguments ( ) ; for ( val in : inputArgs ) { if ( in == null ) { throw new NullPointerException ( \"Input argument is null\" ) ; } inputBuffers . put ( cnt , in . data ( ) . addressPointer ( ) ) ; inputShapes . put ( cnt ++ , in . shapeInfoDataBuffer ( ) . addressPointer ( ) ) ; } val outputArgs = op . outputArguments ( ) ; for ( int i = 0 ; i < outputArgs . length ; i ++ ) { if ( outputArgs [ i ] == null ) throw new ND4JIllegalStateException ( \"Op output arguments must not be null!\" ) ; } val outputShapes = getOutputShapes ( op . numOutputArguments ( ) ) ; val outputBuffers = getOutputBuffers ( op . numOutputArguments ( ) ) ; cnt = 0 ; for ( val out : outputArgs ) { outputBuffers . put ( cnt , out . data ( ) . addressPointer ( ) ) ; outputShapes . put ( cnt ++ , out . shapeInfoDataBuffer ( ) . addressPointer ( ) ) ; } val iArgs = op . numIArguments ( ) > 0 ? new LongPointer ( op . numIArguments ( ) ) : null ; cnt = 0 ; val iArgs1 = op . iArgs ( ) ; for ( val i : iArgs1 ) iArgs . put ( cnt ++ , i ) ; if ( Nd4j . dataType ( ) == DataBuffer . Type . FLOAT ) { val tArgs = op . numTArguments ( ) > 0 ? new FloatPointer ( op . numTArguments ( ) ) : null ; val tArgs1 = op . tArgs ( ) ; cnt = 0 ; for ( val t : tArgs1 ) tArgs . put ( cnt ++ , ( float ) t ) ; OpStatus status = OpStatus . byNumber ( loop . execCustomOpFloat ( null , hash , inputBuffers , inputShapes , op . numInputArguments ( ) , outputBuffers , outputShapes , op . numOutputArguments ( ) , tArgs , op . numTArguments ( ) , iArgs , op . numIArguments ( ) , op . isInplaceCall ( ) ) ) ; if ( status != OpStatus . ND4J_STATUS_OK ) throw new ND4JIllegalStateException ( \"Op execution failed: \" + status ) ; } else if ( Nd4j . dataType ( ) == DataBuffer . Type . DOUBLE ) { val tArgs = op . numTArguments ( ) > 0 ? getDoublePointerFrom ( tArgsPointer , op . numTArguments ( ) ) : null ; val tArgs1 = op . tArgs ( ) ; cnt = 0 ; for ( val t : tArgs1 ) tArgs . put ( cnt ++ , t ) ; val t = op . numInputArguments ( ) ; OpStatus status = OpStatus . ND4J_STATUS_OK ; try { status = OpStatus . byNumber ( loop . execCustomOpDouble ( null , hash , inputBuffers , inputShapes , op . numInputArguments ( ) , outputBuffers , outputShapes , op . numOutputArguments ( ) , tArgs , op . numTArguments ( ) , iArgs , op . numIArguments ( ) , op . isInplaceCall ( ) ) ) ; } catch ( Exception e ) { log . error ( \"Failed to execute. Please see above message (printed out from c++) for a possible cause of error.\" ) ; throw e ; } } else if ( Nd4j . dataType ( ) == DataBuffer . Type . HALF ) { val tArgs = op . numTArguments ( ) > 0 ? getShortPointerFrom ( halfArgsPointer , op . numTArguments ( ) ) : null ; cnt = 0 ; val tArgs1 = op . tArgs ( ) ; for ( val t : tArgs1 ) tArgs . put ( cnt ++ , ArrayUtil . toHalf ( t ) ) ; OpStatus status = OpStatus . byNumber ( loop . execCustomOpHalf ( null , hash , inputBuffers , inputShapes , op . numInputArguments ( ) , outputBuffers , outputShapes , op . numOutputArguments ( ) , tArgs , op . numTArguments ( ) , iArgs , op . numIArguments ( ) , op . isInplaceCall ( ) ) ) ; if ( status != OpStatus . ND4J_STATUS_OK ) throw new ND4JIllegalStateException ( \"Op execution failed: \" + status ) ; } profilingHookOut ( op , st ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This command is possible to issue only from Shard [CODESPLIT] @ Override protected synchronized void sendCoordinationCommand ( VoidMessage message ) { if ( nodeRole == NodeRole . SHARD && voidConfiguration . getNumberOfShards ( ) == 1 ) { message . setTargetId ( ( short ) - 1 ) ; messages . add ( message ) ; return ; } //log.info(\"Sending CC: {}\", message.getClass().getCanonicalName()); message . setTargetId ( ( short ) - 1 ) ; publicationForShards . offer ( message . asUnsafeBuffer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This command is possible to issue only from Shard [CODESPLIT] @ Override protected synchronized void sendFeedbackToClient ( VoidMessage message ) { if ( nodeRole == NodeRole . SHARD && voidConfiguration . getNumberOfShards ( ) == 1 && message instanceof MeaningfulMessage ) { message . setTargetId ( ( short ) - 1 ) ; completed . put ( message . getTaskId ( ) , ( MeaningfulMessage ) message ) ; return ; } //log.info(\"Sending FC: {}\", message.getClass().getCanonicalName()); message . setTargetId ( ( short ) - 1 ) ; publicationForClients . offer ( message . asUnsafeBuffer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assert that no workspaces are currently open [CODESPLIT] public static void assertNoWorkspacesOpen ( String msg ) throws ND4JWorkspaceException { if ( Nd4j . getWorkspaceManager ( ) . anyWorkspaceActiveForCurrentThread ( ) ) { List < MemoryWorkspace > l = Nd4j . getWorkspaceManager ( ) . getAllWorkspacesForCurrentThread ( ) ; List < String > workspaces = new ArrayList <> ( l . size ( ) ) ; for ( MemoryWorkspace ws : l ) { if ( ws . isScopeActive ( ) ) { workspaces . add ( ws . getId ( ) ) ; } } throw new ND4JWorkspaceException ( msg + \" - Open/active workspaces: \" + workspaces ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ND Convolution [CODESPLIT] @ Override public IComplexNDArray convn ( IComplexNDArray input , IComplexNDArray kernel , Convolution . Type type , int [ ] axes ) { throw new UnsupportedOperationException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns an array consisting of each of the training samples for each label in each sample the negative log likelihood of that value falling within the given gaussian mixtures . [CODESPLIT] private INDArray negativeLogLikelihood ( INDArray labels , INDArray alpha , INDArray mu , INDArray sigma ) { INDArray labelsMinusMu = labelsMinusMu ( labels , mu ) ; INDArray diffsquared = labelsMinusMu . mul ( labelsMinusMu ) . sum ( 2 ) ; INDArray phitimesalphasum = phi ( diffsquared , sigma ) . muli ( alpha ) . sum ( 1 ) ; // result = See Bishop(28,29) INDArray result = Transforms . log ( phitimesalphasum ) . negi ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method requests to change state to Tick . [CODESPLIT] public void requestTick ( long time , TimeUnit timeUnit ) { long timeframeMs = TimeUnit . MILLISECONDS . convert ( time , timeUnit ) ; long currentTime = System . currentTimeMillis ( ) ; boolean isWaiting = false ; // if we have Toe request queued - we' have to wait till it finishes. try { while ( isToeScheduled . get ( ) || isToeWaiting . get ( ) || getCurrentState ( ) == AccessState . TOE ) { if ( ! isWaiting ) { isWaiting = true ; waitingTicks . incrementAndGet ( ) ; } Thread . sleep ( 50 ) ; } currentState . set ( AccessState . TICK . ordinal ( ) ) ; waitingTicks . decrementAndGet ( ) ; tickRequests . incrementAndGet ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method requests to change state to Toe [CODESPLIT] public boolean tryRequestToe ( ) { scheduleToe ( ) ; if ( isToeWaiting . get ( ) || getCurrentState ( ) == AccessState . TOE ) { //System.out.println(\"discarding TOE\"); discardScheduledToe ( ) ; return false ; } else { //System.out.println(\"requesting TOE\"); discardScheduledToe ( ) ; requestToe ( ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method requests release Toe status back to Tack . [CODESPLIT] public void releaseToe ( ) { if ( getCurrentState ( ) == AccessState . TOE ) { if ( 1 > 0 ) { //if (toeThread.get() == Thread.currentThread().getId()) { if ( toeRequests . decrementAndGet ( ) == 0 ) { tickRequests . set ( 0 ) ; tackRequests . set ( 0 ) ; currentState . set ( AccessState . TACK . ordinal ( ) ) ; } } else throw new IllegalStateException ( \"releaseToe() is called from different thread.\" ) ; } else throw new IllegalStateException ( \"Object is NOT in Toe state!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the current memory state [CODESPLIT] public AccessState getCurrentState ( ) { if ( AccessState . values ( ) [ currentState . get ( ) ] == AccessState . TOE ) { return AccessState . TOE ; } else { if ( tickRequests . get ( ) <= tackRequests . get ( ) ) { // TODO: looks like this piece of code should be locked :/ tickRequests . set ( 0 ) ; tackRequests . set ( 0 ) ; return AccessState . TACK ; } else return AccessState . TICK ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method build [CODESPLIT] public static Environment buildEnvironment ( ) { Environment environment = new Environment ( ) ; environment . setJavaVersion ( System . getProperty ( \"java.specification.version\" ) ) ; environment . setNumCores ( Runtime . getRuntime ( ) . availableProcessors ( ) ) ; environment . setAvailableMemory ( Runtime . getRuntime ( ) . maxMemory ( ) ) ; environment . setOsArch ( System . getProperty ( \"os.arch\" ) ) ; environment . setOsName ( System . getProperty ( \"os.opName\" ) ) ; environment . setBackendUsed ( Nd4j . getExecutioner ( ) . getClass ( ) . getSimpleName ( ) ) ; return environment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Vector aggregations are saved only by Shards started aggregation process . All other Shards are ignoring this meesage [CODESPLIT] @ Override public void processMessage ( ) { if ( clipboard . isTracking ( this . originatorId , this . getTaskId ( ) ) ) { clipboard . pin ( this ) ; if ( clipboard . isReady ( this . originatorId , taskId ) ) { VoidAggregation aggregation = clipboard . unpin ( this . originatorId , taskId ) ; // FIXME: probably there's better solution, then \"screw-and-forget\" one if ( aggregation == null ) return ; VectorCompleteMessage msg = new VectorCompleteMessage ( taskId , aggregation . getAccumulatedResult ( ) ) ; msg . setOriginatorId ( aggregation . getOriginatorId ( ) ) ; transport . sendMessage ( msg ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes this data transform fetcher from the passed in datasets [CODESPLIT] protected void initializeCurrFromList ( List < DataSet > examples ) { if ( examples . isEmpty ( ) ) log . warn ( \"Warning: empty dataset from the fetcher\" ) ; INDArray inputs = createInputMatrix ( examples . size ( ) ) ; INDArray labels = createOutputMatrix ( examples . size ( ) ) ; for ( int i = 0 ; i < examples . size ( ) ; i ++ ) { inputs . putRow ( i , examples . get ( i ) . getFeatureMatrix ( ) ) ; labels . putRow ( i , examples . get ( i ) . getLabels ( ) ) ; } curr = new DataSet ( inputs , labels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value for this function . Note that if value is null an { @link ND4JIllegalStateException } will be thrown . [CODESPLIT] public void setValueFor ( Field target , Object value ) { if ( value == null ) { throw new ND4JIllegalStateException ( \"Unable to set field \" + target + \" using null value!\" ) ; } value = ensureProperType ( target , value ) ; try { target . set ( this , value ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes preconfigured number of host memory garbage collectors [CODESPLIT] protected void initHostCollectors ( ) { for ( int i = 0 ; i < configuration . getNumberOfGcThreads ( ) ; i ++ ) { ReferenceQueue < BaseDataBuffer > queue = new ReferenceQueue <> ( ) ; UnifiedGarbageCollectorThread uThread = new UnifiedGarbageCollectorThread ( i , queue ) ; // all GC threads should be attached to default device Nd4j . getAffinityManager ( ) . attachThreadToDevice ( uThread , getDeviceId ( ) ) ; queueMap . put ( i , queue ) ; uThread . start ( ) ; collectorsUnified . put ( i , uThread ) ; /*\n            ZeroGarbageCollectorThread zThread = new ZeroGarbageCollectorThread((long) i, shouldStop);\n            zThread.start();\n            \n            collectorsZero.put((long) i, zThread);\n            */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns actual device pointer valid for current object [CODESPLIT] @ Override public Pointer getPointer ( DataBuffer buffer , CudaContext context ) { return memoryHandler . getDevicePointer ( buffer , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method should be called to make sure that data on host side is actualized [CODESPLIT] @ Override public void synchronizeHostData ( DataBuffer buffer ) { // we don't want non-committed ops left behind //Nd4j.getExecutioner().push(); // we don't synchronize constant buffers, since we assume they are always valid on host side if ( buffer . isConstant ( ) ) { return ; } // we actually need synchronization only in device-dependant environment. no-op otherwise if ( memoryHandler . isDeviceDependant ( ) ) { AllocationPoint point = getAllocationPoint ( buffer . getTrackingPoint ( ) ) ; if ( point == null ) throw new RuntimeException ( \"AllocationPoint is NULL\" ) ; memoryHandler . synchronizeThreadDevice ( Thread . currentThread ( ) . getId ( ) , memoryHandler . getDeviceId ( ) , point ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method allocates required chunk of memory in specific location <p > PLEASE NOTE : Do not use this method unless you re 100% sure what you re doing [CODESPLIT] @ Override public AllocationPoint allocateMemory ( DataBuffer buffer , AllocationShape requiredMemory , AllocationStatus location , boolean initialize ) { AllocationPoint point = new AllocationPoint ( ) ; useTracker . set ( System . currentTimeMillis ( ) ) ; // we use these longs as tracking codes for memory tracking Long allocId = objectsTracker . getAndIncrement ( ) ; //point.attachBuffer(buffer); point . setObjectId ( allocId ) ; point . setShape ( requiredMemory ) ; /*\n        if (buffer instanceof CudaIntDataBuffer) {\n            buffer.setConstant(true);\n            point.setConstant(true);\n        }\n        */ int numBuckets = configuration . getNumberOfGcThreads ( ) ; int bucketId = RandomUtils . nextInt ( 0 , numBuckets ) ; GarbageBufferReference reference = new GarbageBufferReference ( ( BaseDataBuffer ) buffer , queueMap . get ( bucketId ) , point ) ; point . attachReference ( reference ) ; point . setDeviceId ( - 1 ) ; if ( buffer . isAttached ( ) ) { long reqMem = AllocationUtils . getRequiredMemory ( requiredMemory ) ; //log.info(\"Allocating {} bytes from attached memory...\", reqMem); // workaround for init order getMemoryHandler ( ) . getCudaContext ( ) ; point . setDeviceId ( Nd4j . getAffinityManager ( ) . getDeviceForCurrentThread ( ) ) ; CudaWorkspace workspace = ( CudaWorkspace ) Nd4j . getMemoryManager ( ) . getCurrentWorkspace ( ) ; PointersPair pair = new PointersPair ( ) ; PagedPointer ptrDev = workspace . alloc ( reqMem , MemoryKind . DEVICE , requiredMemory . getDataType ( ) , initialize ) ; PagedPointer ptrHost = workspace . alloc ( reqMem , MemoryKind . HOST , requiredMemory . getDataType ( ) , initialize ) ; pair . setHostPointer ( ptrHost ) ; if ( ptrDev != null ) { pair . setDevicePointer ( ptrDev ) ; point . setAllocationStatus ( AllocationStatus . DEVICE ) ; } else { pair . setDevicePointer ( ptrHost ) ; point . setAllocationStatus ( AllocationStatus . HOST ) ; } //if (!ptrDev.isLeaked()) point . setAttached ( true ) ; point . setPointers ( pair ) ; } else { // we stay naive on PointersPair, we just don't know on this level, which pointers are set. MemoryHandler will be used for that PointersPair pair = memoryHandler . alloc ( location , point , requiredMemory , initialize ) ; point . setPointers ( pair ) ; } allocationsMap . put ( allocId , point ) ; point . tickHostRead ( ) ; point . tickDeviceWrite ( ) ; return point ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a { [CODESPLIT] public static INDArray fromTensor ( Tensor tensor ) { byte b = tensor . typeType ( ) ; int [ ] shape = new int [ tensor . shapeLength ( ) ] ; int [ ] stride = new int [ tensor . stridesLength ( ) ] ; for ( int i = 0 ; i < shape . length ; i ++ ) { shape [ i ] = ( int ) tensor . shape ( i ) . size ( ) ; stride [ i ] = ( int ) tensor . strides ( i ) ; } int length = ArrayUtil . prod ( shape ) ; Buffer buffer = tensor . data ( ) ; if ( buffer == null ) { throw new ND4JIllegalStateException ( \"Buffer was not serialized properly.\" ) ; } //deduce element size int elementSize = ( int ) buffer . length ( ) / length ; //nd4j strides aren't  based on element size for ( int i = 0 ; i < stride . length ; i ++ ) { stride [ i ] /= elementSize ; } DataBuffer . Type type = typeFromTensorType ( b , elementSize ) ; DataBuffer dataBuffer = DataBufferStruct . createFromByteBuffer ( tensor . getByteBuffer ( ) , ( int ) tensor . data ( ) . offset ( ) , type , length , elementSize ) ; INDArray arr = Nd4j . create ( dataBuffer , shape ) ; arr . setShapeAndStride ( shape , stride ) ; return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] public static int addDataForArr ( FlatBufferBuilder bufferBuilder , INDArray arr ) { int offset = DataBufferStruct . createDataBufferStruct ( bufferBuilder , arr . data ( ) ) ; int ret = Buffer . createBuffer ( bufferBuilder , offset , arr . data ( ) . length ( ) * arr . data ( ) . getElementSize ( ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create thee databuffer type frm the given type relative to the bytes in arrow in class : { [CODESPLIT] public static DataBuffer . Type typeFromTensorType ( byte type , int elementSize ) { if ( type == Type . Decimal || type == Type . FloatingPoint ) { if ( elementSize == 4 ) { return DataBuffer . Type . FLOAT ; } else if ( elementSize == 8 ) { return DataBuffer . Type . DOUBLE ; } } else if ( type == Type . Int ) { if ( elementSize == 4 ) { return DataBuffer . Type . INT ; } else if ( elementSize == 8 ) { return DataBuffer . Type . LONG ; } } else { throw new IllegalArgumentException ( \"Only valid types are Type.Decimal and Type.Int\" ) ; } throw new IllegalArgumentException ( \"Unable to determine data type\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method provides PointersPair to memory chunk specified by AllocationShape [CODESPLIT] @ Override public PointersPair malloc ( AllocationShape shape , AllocationPoint point , AllocationStatus location ) { //log.info(\"shape onCreate: {}, target: {}\", shape, location); switch ( location ) { case HOST : { Pointer devicePointer = new Pointer ( ) ; long reqMem = AllocationUtils . getRequiredMemory ( shape ) ; // FIXME: this is WRONG, and directly leads to memleak if ( reqMem < 1 ) reqMem = 1 ; Pointer pointer = nativeOps . mallocHost ( reqMem , 0 ) ; if ( pointer == null ) throw new RuntimeException ( \"Can't allocate [HOST] memory: \" + reqMem + \"; threadId: \" + Thread . currentThread ( ) . getId ( ) ) ; //                log.info(\"Host allocation, Thread id: {}, ReqMem: {}, Pointer: {}\", Thread.currentThread().getId(), reqMem, pointer != null ? pointer.address() : null); Pointer hostPointer = new CudaPointer ( pointer ) ; PointersPair devicePointerInfo = new PointersPair ( ) ; devicePointerInfo . setDevicePointer ( new CudaPointer ( hostPointer , reqMem ) ) ; devicePointerInfo . setHostPointer ( new CudaPointer ( hostPointer , reqMem ) ) ; point . setPointers ( devicePointerInfo ) ; point . setAllocationStatus ( AllocationStatus . HOST ) ; return devicePointerInfo ; } case DEVICE : { // cudaMalloc call int deviceId = AtomicAllocator . getInstance ( ) . getDeviceId ( ) ; long reqMem = AllocationUtils . getRequiredMemory ( shape ) ; // FIXME: this is WRONG, and directly leads to memleak if ( reqMem < 1 ) reqMem = 1 ; //                if (CudaEnvironment.getInstance().getConfiguration().getDebugTriggered() == 119) //                    throw new RuntimeException(\"Device allocation happened\"); Pointer pointer = nativeOps . mallocDevice ( reqMem , null , 0 ) ; //log.info(\"Device [{}] allocation, Thread id: {}, ReqMem: {}, Pointer: {}\", AtomicAllocator.getInstance().getDeviceId(), Thread.currentThread().getId(), reqMem, pointer != null ? pointer.address() : null); if ( pointer == null ) return null ; //throw new RuntimeException(\"Can't allocate [DEVICE] memory!\"); Pointer devicePointer = new CudaPointer ( pointer ) ; PointersPair devicePointerInfo = point . getPointers ( ) ; if ( devicePointerInfo == null ) devicePointerInfo = new PointersPair ( ) ; devicePointerInfo . setDevicePointer ( new CudaPointer ( devicePointer , reqMem ) ) ; point . setAllocationStatus ( AllocationStatus . DEVICE ) ; point . setDeviceId ( deviceId ) ; return devicePointerInfo ; } default : throw new IllegalStateException ( \"Unsupported location for malloc: [\" + location + \"]\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method frees specific chunk of memory described by AllocationPoint passed in [CODESPLIT] @ Override public void free ( AllocationPoint point ) { switch ( point . getAllocationStatus ( ) ) { case HOST : { // cudaFreeHost call here // FIXME: it would be nice to get rid of typecasting here long reqMem = AllocationUtils . getRequiredMemory ( point . getShape ( ) ) ; //  log.info(\"Deallocating {} bytes on [HOST]\", reqMem); NativeOps nativeOps = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) ; long result = nativeOps . freeHost ( point . getPointers ( ) . getHostPointer ( ) ) ; //JCuda.cudaFreeHost(new Pointer(point.getPointers().getHostPointer())); if ( result == 0 ) throw new RuntimeException ( \"Can't deallocate [HOST] memory...\" ) ; } break ; case DEVICE : { // cudaFree call //JCuda.cudaFree(new Pointer(point.getPointers().getDevicePointer().address())); if ( point . isConstant ( ) ) return ; long reqMem = AllocationUtils . getRequiredMemory ( point . getShape ( ) ) ; //       log.info(\"Deallocating {} bytes on [DEVICE]\", reqMem); NativeOps nativeOps = NativeOpsHolder . getInstance ( ) . getDeviceNativeOps ( ) ; long result = nativeOps . freeDevice ( point . getPointers ( ) . getDevicePointer ( ) , new CudaPointer ( 0 ) ) ; if ( result == 0 ) throw new RuntimeException ( \"Can't deallocate [DEVICE] memory...\" ) ; } break ; default : throw new IllegalStateException ( \"Can't free memory on target [\" + point . getAllocationStatus ( ) + \"]\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets feature specific learning rates Adagrad keeps a history of gradients being passed in . Note that each gradient passed in becomes adapted over time hence the opName adagrad [CODESPLIT] @ Override public void applyUpdater ( INDArray gradient , int iteration , int epoch ) { if ( historicalGradient == null ) throw new IllegalStateException ( \"Updater has not been initialized with view state\" ) ; double learningRate = config . getLearningRate ( iteration , epoch ) ; double epsilon = config . getEpsilon ( ) ; historicalGradient . addi ( gradient . mul ( gradient ) ) ; INDArray sqrtHistory = sqrt ( historicalGradient . dup ( gradientReshapeOrder ) , false ) . addi ( epsilon ) ; // lr * gradient / (sqrt(sumSquaredGradients) + epsilon) gradient . muli ( sqrtHistory . rdivi ( learningRate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method makes sure HOST memory contains latest data from GPU [CODESPLIT] @ Override public void synchronizeToHost ( AllocationPoint point ) { if ( ! point . isConstant ( ) && point . isEnqueued ( ) ) { waitTillFinished ( point ) ; } super . synchronizeToHost ( point ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create from a matrix . The rows are the indices The columns are the individual element in each ndarrayindex [CODESPLIT] public static INDArrayIndex [ ] create ( INDArray index ) { if ( index . isMatrix ( ) ) { if ( index . rows ( ) > Integer . MAX_VALUE ) throw new ND4JArraySizeException ( ) ; NDArrayIndex [ ] ret = new NDArrayIndex [ ( int ) index . rows ( ) ] ; for ( int i = 0 ; i < index . rows ( ) ; i ++ ) { INDArray row = index . getRow ( i ) ; val nums = new long [ ( int ) index . getRow ( i ) . columns ( ) ] ; for ( int j = 0 ; j < row . columns ( ) ; j ++ ) { nums [ j ] = ( int ) row . getFloat ( j ) ; } NDArrayIndex idx = new NDArrayIndex ( nums ) ; ret [ i ] = idx ; } return ret ; } else if ( index . isVector ( ) ) { long [ ] indices = NDArrayUtil . toLongs ( index ) ; return new NDArrayIndex [ ] { new NDArrayIndex ( indices ) } ; } throw new IllegalArgumentException ( \"Passed in ndarray must be a matrix or a vector\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast add op . See : { [CODESPLIT] public static INDArray add ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldAddOp ( x , y , z ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastAddOp ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast copy op . See : { [CODESPLIT] public static INDArray copy ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new CopyOp ( x , y , z ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastCopyOp ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast divide op . See : { [CODESPLIT] public static INDArray div ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldDivOp ( x , y , z ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastDivOp ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast equal to op . See : { [CODESPLIT] public static INDArray eq ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldEqualTo ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastEqualTo ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast greater than op . See : { [CODESPLIT] public static INDArray gt ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldGreaterThan ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastGreaterThan ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast greater than or equal to op . See : { [CODESPLIT] public static INDArray gte ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldGreaterThanOrEqual ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastGreaterThanOrEqual ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast less than op . See : { [CODESPLIT] public static INDArray lt ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldLessThan ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastLessThan ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast less than or equal to op . See : { [CODESPLIT] public static INDArray lte ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldLessThanOrEqual ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastLessThanOrEqual ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast not equal to op . See : { [CODESPLIT] public static INDArray neq ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldNotEqualTo ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastNotEqual ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast reverse division op . See : { [CODESPLIT] public static INDArray rdiv ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldRDivOp ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastRDivOp ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast reverse subtraction op . See : { [CODESPLIT] public static INDArray rsub ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldSubOp ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastRSubOp ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast max op . See : { [CODESPLIT] public static INDArray max ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldMax ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastMax ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast min op . See : { [CODESPLIT] public static INDArray min ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new OldMin ( x , y , z , x . length ( ) ) ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastMin ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast absolute max op . See : { [CODESPLIT] public static INDArray amax ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new AMax ( x , y , z , x . length ( ) ) ) . z ( ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastAMax ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Broadcast absolute min op . See : { [CODESPLIT] public static INDArray amin ( INDArray x , INDArray y , INDArray z , int ... dimensions ) { if ( dimensions == null ) { Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , y . shape ( ) ) , getFormattedShapeErrorMessageXy ( x , y ) ) ; Preconditions . checkArgument ( Arrays . equals ( x . shape ( ) , z . shape ( ) ) , getFormattedShapeErrorMessageXResult ( x , z ) ) ; return Nd4j . getExecutioner ( ) . execAndReturn ( new AMin ( x , y , z , x . length ( ) ) ) . z ( ) ; } return Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastAMin ( x , y , z , dimensions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the properties for a given function [CODESPLIT] public Map < String , Object > propertiesForFunction ( ) { val fields = DifferentialFunctionClassHolder . getInstance ( ) . getFieldsForFunction ( this ) ; Map < String , Object > ret = new LinkedHashMap <> ( ) ; for ( val entry : fields . entrySet ( ) ) { try { ret . put ( entry . getKey ( ) , fields . get ( entry . getKey ( ) ) . get ( this ) ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this function has place holder inputs [CODESPLIT] public boolean hasPlaceHolderInputs ( ) { val args = args ( ) ; for ( val arg : args ) if ( sameDiff . hasPlaceHolderVariables ( arg ( ) . getVarName ( ) ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform automatic differentiation wrt the input variables [CODESPLIT] public List < SDVariable > diff ( List < SDVariable > i_v1 ) { List < SDVariable > vals = doDiff ( i_v1 ) ; if ( vals == null ) { throw new IllegalStateException ( \"Error executing diff operation: doDiff returned null for op: \" + this . opName ( ) ) ; } val outputVars = args ( ) ; for ( int i = 0 ; i < vals . size ( ) ; i ++ ) { SDVariable var = outputVars [ i ] ; SDVariable grad = var . getGradient ( ) ; if ( grad != null ) { SDVariable gradVar = f ( ) . add ( grad , vals . get ( i ) ) ; try { vals . set ( i , gradVar ) ; } catch ( UnsupportedOperationException e ) { throw new UnsupportedOperationException ( \"Use a mutable list when returning values from \" + this . getClass ( ) . getSimpleName ( ) + \".doDiff (e.g. Arrays.asList instead of Collections.singletonList)\" , e ) ; } sameDiff . setGradientForVariableName ( var . getVarName ( ) , gradVar ) ; } else { SDVariable gradVar = vals . get ( i ) ; sameDiff . updateVariableNameAndReference ( gradVar , var . getVarName ( ) + \"-grad\" ) ; sameDiff . setGradientForVariableName ( var . getVarName ( ) , gradVar ) ; sameDiff . setForwardVariableForVarName ( gradVar . getVarName ( ) , var ) ; } } return vals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The offsets ( begin index ) for each index [CODESPLIT] public static long [ ] offsets ( long [ ] shape , INDArrayIndex ... indices ) { //offset of zero for every new axes long [ ] ret = new long [ shape . length ] ; if ( indices . length == shape . length ) { for ( int i = 0 ; i < indices . length ; i ++ ) { if ( indices [ i ] instanceof NDArrayIndexEmpty ) ret [ i ] = 0 ; else { ret [ i ] = indices [ i ] . offset ( ) ; } } if ( ret . length == 1 ) { ret = new long [ ] { ret [ 0 ] , 0 } ; } } else { int numPoints = NDArrayIndex . numPoints ( indices ) ; if ( numPoints > 0 ) { List < Long > nonZeros = new ArrayList <> ( ) ; for ( int i = 0 ; i < indices . length ; i ++ ) if ( indices [ i ] . offset ( ) > 0 ) nonZeros . add ( indices [ i ] . offset ( ) ) ; if ( nonZeros . size ( ) > shape . length ) throw new IllegalStateException ( \"Non zeros greater than shape unable to continue\" ) ; else { //push all zeros to the back for ( int i = 0 ; i < nonZeros . size ( ) ; i ++ ) ret [ i ] = nonZeros . get ( i ) ; } } else { int shapeIndex = 0 ; for ( int i = 0 ; i < indices . length ; i ++ ) { if ( indices [ i ] instanceof NDArrayIndexEmpty ) ret [ i ] = 0 ; else { ret [ i ] = indices [ shapeIndex ++ ] . offset ( ) ; } } } if ( ret . length == 1 ) { ret = new long [ ] { ret [ 0 ] , 0 } ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format the given ndarray as a string [CODESPLIT] public String format ( INDArray arr , boolean summarize ) { this . scientificFormat = \"0.\" ; int addPrecision = this . precision ; while ( addPrecision > 0 ) { this . scientificFormat += \"#\" ; addPrecision -= 1 ; } this . scientificFormat = this . scientificFormat + \"E0\" ; if ( this . scientificFormat . length ( ) + 2 > this . padding ) this . padding = this . scientificFormat . length ( ) + 2 ; this . maxToPrintWithoutSwitching = Math . pow ( 10 , this . precision ) ; this . minToPrintWithoutSwitching = 1.0 / ( this . maxToPrintWithoutSwitching ) ; if ( summarize && arr . length ( ) > 1000 ) return format ( arr , 0 , true ) ; return format ( arr , 0 , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method converts given TF [CODESPLIT] @ Override public SameDiff importGraph ( GRAPH_TYPE tfGraph ) { SameDiff diff = SameDiff . create ( ) ; ImportState < GRAPH_TYPE , TENSOR_TYPE > importState = new ImportState <> ( ) ; importState . setSameDiff ( diff ) ; importState . setGraph ( tfGraph ) ; val variablesForGraph = variablesForGraph ( tfGraph ) ; importState . setVariables ( variablesForGraph ) ; //map the names of the nodes while accumulating the vertex ids //for each variable for ( Map . Entry < String , TENSOR_TYPE > entry : variablesForGraph . entrySet ( ) ) { if ( dataTypeForTensor ( entry . getValue ( ) ) == DataBuffer . Type . UNKNOWN ) { val var = importState . getSameDiff ( ) . var ( entry . getKey ( ) , null , new ZeroInitScheme ( ' ' ) ) ; //mark as place holder for validating resolution later. if ( isPlaceHolder ( entry . getValue ( ) ) ) { importState . getSameDiff ( ) . addAsPlaceHolder ( var . getVarName ( ) ) ; if ( var . getShape ( ) != null ) importState . getSameDiff ( ) . setOriginalPlaceHolderShape ( var . getVarName ( ) , var . getShape ( ) ) ; } continue ; } val arr = getNDArrayFromTensor ( entry . getKey ( ) , entry . getValue ( ) , tfGraph ) ; if ( arr != null ) { val var = importState . getSameDiff ( ) . var ( entry . getKey ( ) , arr ) ; //ensure the array is made available for later processing diff . associateArrayWithVariable ( arr , var ) ; } else if ( getShapeFromTensor ( entry . getValue ( ) ) == null ) { val var = importState . getSameDiff ( ) . var ( entry . getKey ( ) , null , new ZeroInitScheme ( ' ' ) ) ; //mark as place holder for validating resolution later. //note that this vertex id can still be a place holder //with a -1 shape. Just because a shape is \"known\" doesn't mean //that it isn't  a place holder. if ( isPlaceHolder ( entry . getValue ( ) ) ) { val originalShape = getShapeFromTensor ( entry . getValue ( ) ) ; importState . getSameDiff ( ) . addAsPlaceHolder ( var . getVarName ( ) ) ; if ( var . getShape ( ) != null ) importState . getSameDiff ( ) . setOriginalPlaceHolderShape ( var . getVarName ( ) , originalShape ) ; } } else { val originalShape = getShapeFromTensor ( entry . getValue ( ) ) ; val var = importState . getSameDiff ( ) . var ( entry . getKey ( ) , originalShape ) ; //mark as place holder for validating resolution later. //note that this vertex id can still be a place holder //with a -1 shape. Just because a shape is \"known\" doesn't mean //that it isn't  a place holder. if ( isPlaceHolder ( entry . getValue ( ) ) ) { importState . getSameDiff ( ) . addAsPlaceHolder ( var . getVarName ( ) ) ; importState . getSameDiff ( ) . setOriginalPlaceHolderShape ( var . getVarName ( ) , originalShape ) ; } } } //setup vertex ids for  names //handle mapping vertex ids properly val tfNodesList = getNodeList ( tfGraph ) ; for ( NODE_TYPE tfNode : tfNodesList ) { if ( ! opsToIgnore ( ) . contains ( getOpType ( tfNode ) ) || isOpIgnoreException ( tfNode ) ) mapNodeType ( tfNode , importState ) ; } return diff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an ndarray to a blob [CODESPLIT] @ Override public Blob convert ( IComplexNDArray toConvert ) throws IOException , SQLException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( bos ) ; Nd4j . writeComplex ( toConvert , dos ) ; byte [ ] bytes = bos . toByteArray ( ) ; Connection c = dataSource . getConnection ( ) ; Blob b = c . createBlob ( ) ; b . setBytes ( 1 , bytes ) ; return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a complex ndarray from a blob [CODESPLIT] @ Override public IComplexNDArray loadComplex ( Blob blob ) throws SQLException , IOException { DataInputStream dis = new DataInputStream ( blob . getBinaryStream ( ) ) ; return Nd4j . readComplex ( dis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the ndarray [CODESPLIT] @ Override public void save ( IComplexNDArray save , String id ) throws IOException , SQLException { doSave ( save , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy real numbers to arr [CODESPLIT] protected void copyRealTo ( INDArray arr ) { INDArray linear = arr . linearView ( ) ; IComplexNDArray thisLinear = linearView ( ) ; if ( arr . isScalar ( ) ) arr . putScalar ( 0 , getReal ( 0 ) ) ; else for ( int i = 0 ; i < linear . length ( ) ; i ++ ) { arr . putScalar ( i , thisLinear . getReal ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy imaginary numbers to the given ndarray [CODESPLIT] protected void copyImagTo ( INDArray arr ) { INDArray linear = arr . linearView ( ) ; IComplexNDArray thisLinear = linearView ( ) ; if ( arr . isScalar ( ) ) arr . putScalar ( 0 , getReal ( 0 ) ) ; else for ( int i = 0 ; i < linear . length ( ) ; i ++ ) { arr . putScalar ( i , thisLinear . getImag ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an ndarray with 1 if the element is epsilon equals [CODESPLIT] @ Override public IComplexNDArray epsi ( Number other ) { IComplexNDArray linear = linearView ( ) ; double otherVal = other . doubleValue ( ) ; for ( int i = 0 ; i < linearView ( ) . length ( ) ; i ++ ) { IComplexNumber n = linear . getComplex ( i ) ; double real = n . realComponent ( ) . doubleValue ( ) ; double diff = Math . abs ( real - otherVal ) ; if ( diff <= Nd4j . EPS_THRESHOLD ) linear . putScalar ( i , Nd4j . createDouble ( 1 , 0 ) ) ; else linear . putScalar ( i , Nd4j . createDouble ( 0 , 0 ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place epsilon equals than comparison : If the given number is less than the comparison number the item is 0 otherwise 1 [CODESPLIT] @ Override public IComplexNDArray epsi ( INDArray other ) { IComplexNDArray linear = linearView ( ) ; if ( other instanceof IComplexNDArray ) { IComplexNDArray otherComplex = ( IComplexNDArray ) other ; IComplexNDArray otherComplexLinear = otherComplex . linearView ( ) ; for ( int i = 0 ; i < linearView ( ) . length ( ) ; i ++ ) { IComplexNumber n = linear . getComplex ( i ) ; IComplexNumber otherComplexNumber = otherComplexLinear . getComplex ( i ) ; double real = n . absoluteValue ( ) . doubleValue ( ) ; double otherAbs = otherComplexNumber . absoluteValue ( ) . doubleValue ( ) ; double diff = Math . abs ( real - otherAbs ) ; if ( diff <= Nd4j . EPS_THRESHOLD ) linear . putScalar ( i , Nd4j . createDouble ( 1 , 0 ) ) ; else linear . putScalar ( i , Nd4j . createDouble ( 0 , 0 ) ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the squared ( Euclidean ) distance . [CODESPLIT] @ Override public double squaredDistance ( INDArray other ) { double sd = 0.0 ; if ( other instanceof IComplexNDArray ) { IComplexNDArray n = ( IComplexNDArray ) other ; IComplexNDArray nLinear = n . linearView ( ) ; for ( int i = 0 ; i < length ( ) ; i ++ ) { IComplexNumber diff = linearView ( ) . getComplex ( i ) . sub ( nLinear . getComplex ( i ) ) ; double d = diff . absoluteValue ( ) . doubleValue ( ) ; sd += d * d ; } return sd ; } for ( int i = 0 ; i < length ( ) ; i ++ ) { INDArray linear = other . linearView ( ) ; IComplexNumber diff = linearView ( ) . getComplex ( i ) . sub ( linear . getDouble ( i ) ) ; double d = diff . absoluteValue ( ) . doubleValue ( ) ; sd += d * d ; } return sd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the ( 1 - norm ) distance . [CODESPLIT] @ Override public double distance1 ( INDArray other ) { float d = 0.0f ; if ( other instanceof IComplexNDArray ) { IComplexNDArray n2 = ( IComplexNDArray ) other ; IComplexNDArray n2Linear = n2 . linearView ( ) ; for ( int i = 0 ; i < length ( ) ; i ++ ) { IComplexNumber n = getComplex ( i ) . sub ( n2Linear . getComplex ( i ) ) ; d += n . absoluteValue ( ) . doubleValue ( ) ; } return d ; } INDArray linear = other . linearView ( ) ; for ( int i = 0 ; i < length ( ) ; i ++ ) { IComplexNumber n = linearView ( ) . getComplex ( i ) . sub ( linear . getDouble ( i ) ) ; d += n . absoluteValue ( ) . doubleValue ( ) ; } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the element at the specified index [CODESPLIT] @ Override public IComplexNDArray put ( int i , int j , Number element ) { return ( IComplexNDArray ) super . put ( i , j , Nd4j . scalar ( element ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assigns the given matrix ( put ) to the specified slice [CODESPLIT] @ Override public IComplexNDArray putSlice ( int slice , IComplexNDArray put ) { if ( isScalar ( ) ) { assert put . isScalar ( ) : \"Invalid dimension. Can only insert a scalar in to another scalar\" ; put ( 0 , put . getScalar ( 0 ) ) ; return this ; } else if ( isVector ( ) ) { assert put . isScalar ( ) || put . isVector ( ) && put . length ( ) == length ( ) : \"Invalid dimension on insertion. Can only insert scalars input vectors\" ; if ( put . isScalar ( ) ) putScalar ( slice , put . getComplex ( 0 ) ) ; else for ( int i = 0 ; i < length ( ) ; i ++ ) putScalar ( i , put . getComplex ( i ) ) ; return this ; } assertSlice ( put , slice ) ; IComplexNDArray view = slice ( slice ) ; if ( put . length ( ) == 1 ) putScalar ( slice , put . getComplex ( 0 ) ) ; else if ( put . isVector ( ) ) for ( int i = 0 ; i < put . length ( ) ; i ++ ) view . putScalar ( i , put . getComplex ( i ) ) ; else { assert Shape . shapeEquals ( view . shape ( ) , put . shape ( ) ) ; IComplexNDArray linear = view . linearView ( ) ; IComplexNDArray putLinearView = put . linearView ( ) ; for ( int i = 0 ; i < linear . length ( ) ; i ++ ) { linear . putScalar ( i , putLinearView . getComplex ( i ) ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute complex conj ( in - place ) . [CODESPLIT] @ Override public IComplexNDArray conji ( ) { IComplexNDArray reshaped = linearView ( ) ; IComplexDouble c = Nd4j . createDouble ( 0.0 , 0 ) ; for ( int i = 0 ; i < length ( ) ; i ++ ) { IComplexNumber conj = reshaped . getComplex ( i , c ) . conj ( ) ; reshaped . putScalar ( i , conj ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the element at the specified index [CODESPLIT] @ Override public IComplexNDArray put ( int i , IComplexNDArray element ) { if ( element == null ) throw new IllegalArgumentException ( \"Unable to insert null element\" ) ; assert element . isScalar ( ) : \"Unable to insert non scalar element\" ; long idx = linearIndex ( i ) ; IComplexNumber n = element . getComplex ( 0 ) ; data . put ( idx , n . realComponent ( ) . doubleValue ( ) ) ; data . put ( idx + 1 , n . imaginaryComponent ( ) . doubleValue ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assigns the given matrix ( put ) to the specified slice [CODESPLIT] @ Override public IComplexNDArray putSlice ( int slice , INDArray put ) { return putSlice ( slice , Nd4j . createComplex ( put ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the element at the specified index [CODESPLIT] @ Override public IComplexNDArray put ( int i , int j , INDArray element ) { return put ( new int [ ] { i , j } , element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign all of the elements in the given ndarray to this ndarray [CODESPLIT] @ Override public IComplexNDArray assign ( IComplexNDArray arr ) { if ( ! arr . isScalar ( ) ) LinAlgExceptions . assertSameLength ( this , arr ) ; IComplexNDArray linear = linearView ( ) ; IComplexNDArray otherLinear = arr . linearView ( ) ; for ( int i = 0 ; i < linear . length ( ) ; i ++ ) { linear . putScalar ( i , otherLinear . getComplex ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get whole rows from the passed indices . [CODESPLIT] @ Override public IComplexNDArray getRows ( int [ ] rindices ) { INDArray rows = Nd4j . create ( rindices . length , columns ( ) ) ; for ( int i = 0 ; i < rindices . length ; i ++ ) { rows . putRow ( i , getRow ( rindices [ i ] ) ) ; } return ( IComplexNDArray ) rows ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dimshuffle : an extension of permute that adds the ability to broadcast various dimensions . <p / > See theano for more examples . This will only accept integers and xs . <p / > An x indicates a dimension should be broadcasted rather than permuted . [CODESPLIT] @ Override public IComplexNDArray dimShuffle ( Object [ ] rearrange , int [ ] newOrder , boolean [ ] broadCastable ) { return ( IComplexNDArray ) super . dimShuffle ( rearrange , newOrder , broadCastable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a row in to this array Will throw an exception if this ndarray is not a matrix [CODESPLIT] @ Override public IComplexNDArray putRow ( long row , INDArray toPut ) { return ( IComplexNDArray ) super . putRow ( row , toPut ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a column in to this array Will throw an exception if this ndarray is not a matrix [CODESPLIT] @ Override public IComplexNDArray putColumn ( int column , INDArray toPut ) { assert toPut . isVector ( ) && toPut . length ( ) == rows ( ) : \"Illegal length for row \" + toPut . length ( ) + \" should have been \" + columns ( ) ; IComplexNDArray r = getColumn ( column ) ; if ( toPut instanceof IComplexNDArray ) { IComplexNDArray putComplex = ( IComplexNDArray ) toPut ; for ( int i = 0 ; i < r . length ( ) ; i ++ ) { IComplexNumber n = putComplex . getComplex ( i ) ; r . putScalar ( i , n ) ; } } else { for ( int i = 0 ; i < r . length ( ) ; i ++ ) r . putScalar ( i , Nd4j . createDouble ( toPut . getDouble ( i ) , 0 ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the element at the specified index [CODESPLIT] @ Override public IComplexNDArray put ( int i , INDArray element ) { if ( element == null ) throw new IllegalArgumentException ( \"Unable to insert null element\" ) ; assert element . isScalar ( ) : \"Unable to insert non scalar element\" ; if ( element instanceof IComplexNDArray ) { IComplexNDArray n1 = ( IComplexNDArray ) element ; IComplexNumber n = n1 . getComplex ( 0 ) ; put ( i , n ) ; } else putScalar ( i , Nd4j . createDouble ( element . getDouble ( 0 ) , 0.0 ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray diviColumnVector ( INDArray columnVector ) { for ( int i = 0 ; i < columns ( ) ; i ++ ) { getColumn ( i ) . divi ( columnVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray diviRowVector ( INDArray rowVector ) { for ( int i = 0 ; i < rows ( ) ; i ++ ) { getRow ( i ) . divi ( rowVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray muliColumnVector ( INDArray columnVector ) { for ( int i = 0 ; i < columns ( ) ; i ++ ) { getColumn ( i ) . muli ( columnVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray muliRowVector ( INDArray rowVector ) { for ( int i = 0 ; i < rows ( ) ; i ++ ) { getRow ( i ) . muli ( rowVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray subiColumnVector ( INDArray columnVector ) { for ( int i = 0 ; i < columns ( ) ; i ++ ) { getColumn ( i ) . subi ( columnVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray subiRowVector ( INDArray rowVector ) { for ( int i = 0 ; i < rows ( ) ; i ++ ) { getRow ( i ) . subi ( rowVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray addiColumnVector ( INDArray columnVector ) { for ( int i = 0 ; i < columns ( ) ; i ++ ) { getColumn ( i ) . addi ( columnVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In place addition of a column vector [CODESPLIT] @ Override public IComplexNDArray addiRowVector ( INDArray rowVector ) { for ( int i = 0 ; i < rows ( ) ; i ++ ) { getRow ( i ) . addi ( rowVector . getScalar ( i ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform an copy matrix multiplication [CODESPLIT] @ Override public IComplexNDArray mmul ( INDArray other , INDArray result ) { return dup ( ) . mmuli ( other , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy ( element wise ) division of two matrices [CODESPLIT] @ Override public IComplexNDArray div ( INDArray other , INDArray result ) { return dup ( ) . divi ( other , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy ( element wise ) multiplication of two matrices [CODESPLIT] @ Override public IComplexNDArray mul ( INDArray other , INDArray result ) { return dup ( ) . muli ( other , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy subtraction of two matrices [CODESPLIT] @ Override public IComplexNDArray sub ( INDArray other , INDArray result ) { return dup ( ) . subi ( other , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy addition of two matrices [CODESPLIT] @ Override public IComplexNDArray add ( INDArray other , INDArray result ) { return dup ( ) . addi ( other , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform an copy matrix multiplication [CODESPLIT] @ Override public IComplexNDArray mmuli ( INDArray other , INDArray result ) { IComplexNDArray otherArray = ( IComplexNDArray ) other ; IComplexNDArray resultArray = ( IComplexNDArray ) result ; if ( other . shape ( ) . length > 2 ) { for ( int i = 0 ; i < other . slices ( ) ; i ++ ) { resultArray . putSlice ( i , slice ( i ) . mmul ( otherArray . slice ( i ) ) ) ; } return resultArray ; } LinAlgExceptions . assertMultiplies ( this , other ) ; if ( other . isScalar ( ) ) { return muli ( otherArray . getComplex ( 0 ) , resultArray ) ; } if ( isScalar ( ) ) { return otherArray . muli ( getComplex ( 0 ) , resultArray ) ; } /* check sizes and resize if necessary */ //assertMultipliesWith(other); if ( result == this || result == other ) { /* actually, blas cannot do multiplications in-place. Therefore, we will fake by\n             * allocating a temporary object on the side and copy the result later.\n             */ IComplexNDArray temp = Nd4j . createComplex ( resultArray . shape ( ) ) ; if ( otherArray . columns ( ) == 1 ) { Nd4j . getBlasWrapper ( ) . level2 ( ) . gemv ( BlasBufferUtil . getCharForTranspose ( temp ) , BlasBufferUtil . getCharForTranspose ( this ) , Nd4j . UNIT , this , otherArray , Nd4j . ZERO , temp ) ; } else { Nd4j . getBlasWrapper ( ) . level3 ( ) . gemm ( BlasBufferUtil . getCharForTranspose ( temp ) , BlasBufferUtil . getCharForTranspose ( this ) , BlasBufferUtil . getCharForTranspose ( other ) , Nd4j . UNIT , this , otherArray , Nd4j . ZERO , temp ) ; } Nd4j . getBlasWrapper ( ) . copy ( temp , resultArray ) ; } else { if ( otherArray . columns ( ) == 1 ) { Nd4j . getBlasWrapper ( ) . level2 ( ) . gemv ( BlasBufferUtil . getCharForTranspose ( resultArray ) , BlasBufferUtil . getCharForTranspose ( this ) , Nd4j . UNIT , this , otherArray , Nd4j . ZERO , resultArray ) ; } else { Nd4j . getBlasWrapper ( ) . level3 ( ) . gemm ( BlasBufferUtil . getCharForTranspose ( resultArray ) , BlasBufferUtil . getCharForTranspose ( this ) , BlasBufferUtil . getCharForTranspose ( other ) , Nd4j . UNIT , this , otherArray , Nd4j . ZERO , resultArray ) ; } } return resultArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in place ( element wise ) multiplication of two matrices [CODESPLIT] @ Override public IComplexNDArray muli ( INDArray other , INDArray result ) { IComplexNDArray cOther = ( IComplexNDArray ) other ; IComplexNDArray cResult = ( IComplexNDArray ) result ; IComplexNDArray linear = linearView ( ) ; IComplexNDArray cOtherLinear = cOther . linearView ( ) ; IComplexNDArray cResultLinear = cResult . linearView ( ) ; if ( other . isScalar ( ) ) return muli ( cOther . getComplex ( 0 ) , result ) ; IComplexNumber c = Nd4j . createComplexNumber ( 0 , 0 ) ; IComplexNumber d = Nd4j . createComplexNumber ( 0 , 0 ) ; for ( int i = 0 ; i < length ( ) ; i ++ ) cResultLinear . putScalar ( i , linear . getComplex ( i , c ) . muli ( cOtherLinear . getComplex ( i , d ) ) ) ; return cResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in place subtraction of two matrices [CODESPLIT] @ Override public IComplexNDArray subi ( INDArray other , INDArray result ) { IComplexNDArray cOther = ( IComplexNDArray ) other ; IComplexNDArray cResult = ( IComplexNDArray ) result ; if ( other . isScalar ( ) ) return subi ( cOther . getComplex ( 0 ) , result ) ; if ( result == this ) Nd4j . getBlasWrapper ( ) . axpy ( Nd4j . NEG_UNIT , cOther , cResult ) ; else if ( result == other ) { if ( data . dataType ( ) == ( DataBuffer . Type . DOUBLE ) ) { Nd4j . getBlasWrapper ( ) . scal ( Nd4j . NEG_UNIT . asDouble ( ) , cResult ) ; Nd4j . getBlasWrapper ( ) . axpy ( Nd4j . UNIT , this , cResult ) ; } else { Nd4j . getBlasWrapper ( ) . scal ( Nd4j . NEG_UNIT . asFloat ( ) , cResult ) ; Nd4j . getBlasWrapper ( ) . axpy ( Nd4j . UNIT , this , cResult ) ; } } else { Nd4j . getBlasWrapper ( ) . copy ( this , result ) ; Nd4j . getBlasWrapper ( ) . axpy ( Nd4j . NEG_UNIT , cOther , cResult ) ; } return cResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "in place addition of two matrices [CODESPLIT] @ Override public IComplexNDArray addi ( INDArray other , INDArray result ) { IComplexNDArray cOther = ( IComplexNDArray ) other ; IComplexNDArray cResult = ( IComplexNDArray ) result ; if ( cOther . isScalar ( ) ) { return cResult . addi ( cOther . getComplex ( 0 ) , result ) ; } if ( isScalar ( ) ) { return cOther . addi ( getComplex ( 0 ) , result ) ; } if ( result == this ) { Nd4j . getBlasWrapper ( ) . axpy ( Nd4j . UNIT , cOther , cResult ) ; } else if ( result == other ) { Nd4j . getBlasWrapper ( ) . axpy ( Nd4j . UNIT , this , cResult ) ; } else { INDArray resultLinear = result . linearView ( ) ; INDArray otherLinear = other . linearView ( ) ; INDArray linear = linearView ( ) ; for ( int i = 0 ; i < resultLinear . length ( ) ; i ++ ) { resultLinear . putScalar ( i , otherLinear . getDouble ( i ) + linear . getDouble ( i ) ) ; } } return ( IComplexNDArray ) result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value of the ndarray to the specified value [CODESPLIT] @ Override public IComplexNDArray assign ( Number value ) { IComplexNDArray one = linearView ( ) ; for ( int i = 0 ; i < one . length ( ) ; i ++ ) one . putScalar ( i , Nd4j . createDouble ( value . doubleValue ( ) , 0 ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverse division [CODESPLIT] @ Override public IComplexNDArray rdiv ( INDArray other , INDArray result ) { return dup ( ) . rdivi ( other , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverse division ( in - place ) [CODESPLIT] @ Override public IComplexNDArray rdivi ( INDArray other , INDArray result ) { return ( IComplexNDArray ) other . divi ( this , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverse subtraction [CODESPLIT] @ Override public IComplexNDArray rsub ( INDArray other , INDArray result ) { return dup ( ) . rsubi ( other , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverse subtraction ( in - place ) [CODESPLIT] @ Override public IComplexNDArray rsubi ( INDArray other , INDArray result ) { return ( IComplexNDArray ) other . subi ( this , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a scalar ( individual element ) of a scalar ndarray [CODESPLIT] @ Override public Object element ( ) { if ( ! isScalar ( ) ) throw new IllegalStateException ( \"Unable to getScalar the element of a non scalar\" ) ; long idx = linearIndex ( 0 ) ; return Nd4j . createDouble ( data . getDouble ( idx ) , data . getDouble ( idx + 1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens the array for linear indexing [CODESPLIT] @ Override public IComplexNDArray ravel ( ) { if ( length ( ) >= Integer . MAX_VALUE ) throw new IllegalArgumentException ( \"length() can not be >= Integer.MAX_VALUE\" ) ; IComplexNDArray ret = Nd4j . createComplex ( ( int ) length ( ) , ordering ( ) ) ; IComplexNDArray linear = linearView ( ) ; for ( int i = 0 ; i < length ( ) ; i ++ ) { ret . putScalar ( i , linear . getComplex ( i ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the eigenvalues of a general matrix . [CODESPLIT] public static IComplexNDArray eigenvalues ( INDArray A ) { assert A . rows ( ) == A . columns ( ) ; INDArray WR = Nd4j . create ( A . rows ( ) , A . rows ( ) ) ; INDArray WI = WR . dup ( ) ; Nd4j . getBlasWrapper ( ) . geev ( ' ' , ' ' , A . dup ( ) , WR , WI , dummy , dummy ) ; return Nd4j . createComplex ( WR , WI ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the eigenvalues and eigenvectors of a general matrix . <p / > For matlab users note the following from their documentation : The columns of V present eigenvectors of A . The diagonal matrix D contains eigenvalues . <p / > This is in reverse order of the matlab eig ( A ) call . [CODESPLIT] public static IComplexNDArray [ ] eigenvectors ( INDArray A ) { assert A . columns ( ) == A . rows ( ) ; // setting up result arrays INDArray WR = Nd4j . create ( A . rows ( ) ) ; INDArray WI = WR . dup ( ) ; INDArray VR = Nd4j . create ( A . rows ( ) , A . rows ( ) ) ; INDArray VL = Nd4j . create ( A . rows ( ) , A . rows ( ) ) ; Nd4j . getBlasWrapper ( ) . geev ( ' ' , ' ' , A . dup ( ) , WR , WI , VL , VR ) ; // transferring the result IComplexNDArray E = Nd4j . createComplex ( WR , WI ) ; IComplexNDArray V = Nd4j . createComplex ( ( int ) A . rows ( ) , ( int ) A . rows ( ) ) ; for ( int i = 0 ; i < A . rows ( ) ; i ++ ) { if ( E . getComplex ( i ) . isReal ( ) ) { IComplexNDArray column = Nd4j . createComplex ( VR . getColumn ( i ) ) ; V . putColumn ( i , column ) ; } else { IComplexNDArray v = Nd4j . createComplex ( VR . getColumn ( i ) , VR . getColumn ( i + 1 ) ) ; V . putColumn ( i , v ) ; V . putColumn ( i + 1 , v . conji ( ) ) ; i += 1 ; } } return new IComplexNDArray [ ] { Nd4j . diag ( E ) , V } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute generalized eigenvalues of the problem A x = L B x . The data will be unchanged no eigenvectors returned . [CODESPLIT] public static INDArray symmetricGeneralizedEigenvalues ( INDArray A , INDArray B ) { assert A . rows ( ) == A . columns ( ) ; assert B . rows ( ) == B . columns ( ) ; INDArray W = Nd4j . create ( A . rows ( ) ) ; A = InvertMatrix . invert ( B , false ) . mmuli ( A ) ; Nd4j . getBlasWrapper ( ) . syev ( ' ' , ' ' , A , W ) ; return W ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public double probability ( int x ) { double ret ; if ( x < 0 || x > numberOfTrials ) { ret = 0.0 ; } else { ret = FastMath . exp ( SaddlePointExpansion . logBinomialProbability ( x , numberOfTrials , probabilityOfSuccess , 1.0 - probabilityOfSuccess ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "finds the element of a vector that has the largest absolute value . [CODESPLIT] @ Override public int iamax ( IComplexNDArray arr ) { if ( arr . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) return izamax ( arr . length ( ) , arr , BlasBufferUtil . getBlasStride ( arr ) ) ; return icamax ( arr . length ( ) , arr , BlasBufferUtil . getBlasStride ( arr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy a vector to another vector . [CODESPLIT] @ Override public void copy ( IComplexNDArray x , IComplexNDArray y ) { if ( x . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zcopy ( x . length ( ) , x , BlasBufferUtil . getBlasStride ( x ) , y , BlasBufferUtil . getBlasStride ( y ) ) ; else ccopy ( x . length ( ) , x , BlasBufferUtil . getBlasStride ( x ) , y , BlasBufferUtil . getBlasStride ( y ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "computes a vector - scalar product and adds the result to a vector . [CODESPLIT] @ Override public void axpy ( long n , double alpha , INDArray x , INDArray y ) { if ( Nd4j . getExecutioner ( ) . getProfilingMode ( ) == OpExecutioner . ProfilingMode . ALL ) OpProfiler . getInstance ( ) . processBlasCall ( false , x , y ) ; if ( x . isSparse ( ) && ! y . isSparse ( ) ) { Nd4j . getSparseBlasWrapper ( ) . level1 ( ) . axpy ( n , alpha , x , y ) ; } else if ( x . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . DOUBLE , x , y ) ; daxpy ( n , alpha , x , BlasBufferUtil . getBlasStride ( x ) , y , BlasBufferUtil . getBlasStride ( y ) ) ; } else if ( x . data ( ) . dataType ( ) == DataBuffer . Type . FLOAT ) { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . FLOAT , x , y ) ; saxpy ( n , ( float ) alpha , x , BlasBufferUtil . getBlasStride ( x ) , y , BlasBufferUtil . getBlasStride ( y ) ) ; } else { DefaultOpExecutioner . validateDataType ( DataBuffer . Type . HALF , x , y ) ; haxpy ( n , ( float ) alpha , x , BlasBufferUtil . getBlasStride ( x ) , y , BlasBufferUtil . getBlasStride ( y ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "computes a vector - scalar product and adds the result to a vector . [CODESPLIT] @ Override public void axpy ( long n , IComplexNumber alpha , IComplexNDArray x , IComplexNDArray y ) { if ( x . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zaxpy ( n , alpha . asDouble ( ) , x , BlasBufferUtil . getBlasStride ( x ) , y , BlasBufferUtil . getBlasStride ( y ) ) ; else caxpy ( n , alpha . asFloat ( ) , x , BlasBufferUtil . getBlasStride ( x ) , y , BlasBufferUtil . getBlasStride ( y ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "computes a vector by a scalar product . [CODESPLIT] @ Override public void scal ( long N , IComplexNumber alpha , IComplexNDArray X ) { if ( X . data ( ) . dataType ( ) == DataBuffer . Type . DOUBLE ) zscal ( N , alpha . asDouble ( ) , X , BlasBufferUtil . getBlasStride ( X ) ) ; else cscal ( N , alpha . asFloat ( ) , X , BlasBufferUtil . getBlasStride ( X ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize a data array [CODESPLIT] @ Override public void preProcess ( INDArray array , INDArray maskArray , MinMaxStats stats ) { if ( array . rank ( ) <= 2 ) { array . subiRowVector ( stats . getLower ( ) ) ; array . diviRowVector ( stats . getRange ( ) ) ; } // if feature Rank is 3 (time series) samplesxfeaturesxtimesteps // if feature Rank is 4 (images) samplesxchannelsxrowsxcols // both cases operations should be carried out in dimension 1 else { Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastSubOp ( array , stats . getLower ( ) , array , 1 ) ) ; Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastDivOp ( array , stats . getRange ( ) , array , 1 ) ) ; } // Scale by target range array . muli ( maxRange - minRange ) ; // Add target range minimum values array . addi ( minRange ) ; if ( maskArray != null ) { DataSetUtil . setMaskedValuesToZero ( array , maskArray ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Denormalize a data array [CODESPLIT] @ Override public void revert ( INDArray array , INDArray maskArray , MinMaxStats stats ) { // Subtract target range minimum value array . subi ( minRange ) ; // Scale by target range array . divi ( maxRange - minRange ) ; if ( array . rank ( ) <= 2 ) { array . muliRowVector ( stats . getRange ( ) ) ; array . addiRowVector ( stats . getLower ( ) ) ; } else { Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastMulOp ( array , stats . getRange ( ) , array , 1 ) ) ; Nd4j . getExecutioner ( ) . execAndReturn ( new BroadcastAddOp ( array , stats . getLower ( ) , array , 1 ) ) ; } if ( maskArray != null ) { DataSetUtil . setMaskedValuesToZero ( array , maskArray ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the specified labels and label mask arrays ( i . e . concatenate the examples ) [CODESPLIT] public static Pair < INDArray , INDArray > mergeLabels ( INDArray [ ] labelsToMerge , INDArray [ ] labelMasksToMerge ) { int rankFeatures = labelsToMerge [ 0 ] . rank ( ) ; switch ( rankFeatures ) { case 2 : return DataSetUtil . merge2d ( labelsToMerge , labelMasksToMerge ) ; case 3 : return DataSetUtil . mergeTimeSeries ( labelsToMerge , labelMasksToMerge ) ; case 4 : return DataSetUtil . merge4d ( labelsToMerge , labelMasksToMerge ) ; default : throw new ND4JIllegalStateException ( \"Cannot merge examples: labels rank must be in range 2 to 4\" + \" inclusive. First example features shape: \" + Arrays . toString ( labelsToMerge [ 0 ] . shape ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the specified 2d arrays and masks . See { @link #mergeFeatures ( INDArray [] INDArray [] ) } and { @link #mergeLabels ( INDArray [] INDArray [] ) } [CODESPLIT] public static Pair < INDArray , INDArray > merge2d ( INDArray [ ] arrays , INDArray [ ] masks ) { long cols = arrays [ 0 ] . columns ( ) ; INDArray [ ] temp = new INDArray [ arrays . length ] ; boolean hasMasks = false ; for ( int i = 0 ; i < arrays . length ; i ++ ) { if ( arrays [ i ] . columns ( ) != cols ) { throw new IllegalStateException ( \"Cannot merge 2d arrays with different numbers of columns (firstNCols=\" + cols + \", ithNCols=\" + arrays [ i ] . columns ( ) + \")\" ) ; } temp [ i ] = arrays [ i ] ; if ( masks != null && masks [ i ] != null && masks [ i ] != null ) { hasMasks = true ; } } INDArray out = Nd4j . specialConcat ( 0 , temp ) ; INDArray outMask = null ; if ( hasMasks ) { outMask = DataSetUtil . mergePerOutputMasks2d ( out . shape ( ) , arrays , masks ) ; } return new Pair <> ( out , outMask ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the specified 4d arrays and masks . See { @link #mergeFeatures ( INDArray [] INDArray [] ) } and { @link #mergeLabels ( INDArray [] INDArray [] ) } [CODESPLIT] public static Pair < INDArray , INDArray > merge4d ( INDArray [ ] arrays , INDArray [ ] masks ) { //4d -> images. In principle: could have 2d mask arrays (per-example masks) int nExamples = 0 ; long [ ] shape = arrays [ 0 ] . shape ( ) ; INDArray [ ] temp = new INDArray [ arrays . length ] ; boolean hasMasks = false ; for ( int i = 0 ; i < arrays . length ; i ++ ) { nExamples += arrays [ i ] . size ( 0 ) ; long [ ] thisShape = arrays [ i ] . shape ( ) ; if ( thisShape . length != 4 ) { throw new IllegalStateException ( \"Cannot merge 4d arrays with non 4d arrays\" ) ; } for ( int j = 1 ; j < 4 ; j ++ ) { if ( thisShape [ j ] != shape [ j ] ) throw new IllegalStateException ( \"Cannot merge 4d arrays with different shape (other than # examples): \" + \" data[0].shape = \" + Arrays . toString ( shape ) + \", data[\" + i + \"].shape = \" + Arrays . toString ( thisShape ) ) ; } temp [ i ] = arrays [ i ] ; if ( masks != null && masks [ i ] != null && masks [ i ] != null ) { hasMasks = true ; if ( masks [ i ] . rank ( ) != 2 ) { throw new UnsupportedOperationException ( \"Cannot merged 4d arrays with masks that are not rank 2.\" + \" Got mask array with rank: \" + masks [ i ] . rank ( ) ) ; } } } INDArray out = Nd4j . specialConcat ( 0 , temp ) ; INDArray outMask = null ; if ( hasMasks ) { outMask = DataSetUtil . mergePerOutputMasks2d ( out . shape ( ) , arrays , masks ) ; } return new Pair <> ( out , outMask ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes given graph and returns results [CODESPLIT] @ Override public INDArray [ ] executeGraph ( SameDiff graph , ExecutorConfiguration configuration ) { return new INDArray [ ] { graph . execAndEndResult ( ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Can we do the op ( X = Op ( X )) directly on the arrays without breaking X up into 1d tensors first? In general this is possible if the elements of X are contiguous in the buffer OR if every element of X is at position offset + i * elementWiseStride in the buffer [CODESPLIT] public static boolean canDoOpDirectly ( INDArray x ) { if ( x . elementWiseStride ( ) < 1 ) return false ; if ( x . isVector ( ) ) return true ; //For a single NDArray all we require is that the elements are contiguous in the buffer or every nth element //Full buffer -> implies all elements are contiguous (and match) long l1 = x . lengthLong ( ) ; long dl1 = x . data ( ) . length ( ) ; if ( l1 == dl1 ) return true ; //Strides are same as a zero offset NDArray -> all elements are contiguous (even if not offset 0) long [ ] shape1 = x . shape ( ) ; long [ ] stridesAsInit = ( x . ordering ( ) == ' ' ? ArrayUtil . calcStrides ( shape1 ) : ArrayUtil . calcStridesFortran ( shape1 ) ) ; boolean stridesSameAsInit = Arrays . equals ( x . stride ( ) , stridesAsInit ) ; return stridesSameAsInit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Can we do the transform op ( X = Op ( X Y )) directly on the arrays without breaking them up into 1d tensors first? [CODESPLIT] public static boolean canDoOpDirectly ( INDArray x , INDArray y ) { if ( x . isVector ( ) ) return true ; if ( x . ordering ( ) != y . ordering ( ) ) return false ; //other than vectors, elements in f vs. c NDArrays will never line up if ( x . elementWiseStride ( ) < 1 || y . elementWiseStride ( ) < 1 ) return false ; //Full buffer + matching strides -> implies all elements are contiguous (and match) //Need strides to match, otherwise elements in buffer won't line up (i.e., c vs. f order arrays) long l1 = x . lengthLong ( ) ; long dl1 = x . data ( ) . length ( ) ; long l2 = y . lengthLong ( ) ; long dl2 = y . data ( ) . length ( ) ; long [ ] strides1 = x . stride ( ) ; long [ ] strides2 = y . stride ( ) ; boolean equalStrides = Arrays . equals ( strides1 , strides2 ) ; if ( l1 == dl1 && l2 == dl2 && equalStrides ) return true ; //Strides match + are same as a zero offset NDArray -> all elements are contiguous (and match) if ( equalStrides ) { long [ ] shape1 = x . shape ( ) ; long [ ] stridesAsInit = ( x . ordering ( ) == ' ' ? ArrayUtil . calcStrides ( shape1 ) : ArrayUtil . calcStridesFortran ( shape1 ) ) ; boolean stridesSameAsInit = Arrays . equals ( strides1 , stridesAsInit ) ; return stridesSameAsInit ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tensor1DStats used to efficiently iterate through tensors on a matrix ( 2d NDArray ) for element - wise ops For example the offset of each 1d tensor can be calculated using only a single tensorAlongDimension method call hence is potentially faster than approaches requiring multiple tensorAlongDimension calls . <br > Note that this can only ( generally ) be used for 2d NDArrays . For certain 3 + d NDArrays the tensor starts may not be in increasing order [CODESPLIT] public static Tensor1DStats get1DTensorStats ( INDArray array , int ... dimension ) { long tensorLength = array . size ( dimension [ 0 ] ) ; //As per tensorssAlongDimension: long numTensors = array . tensorssAlongDimension ( dimension ) ; //First tensor always starts with the first element in the NDArray, regardless of dimension long firstTensorOffset = array . offset ( ) ; //Next: Need to work out the separation between the start (first element) of each 1d tensor long tensorStartSeparation ; int elementWiseStride ; //Separation in buffer between elements in the tensor if ( numTensors == 1 ) { tensorStartSeparation = - 1 ; //Not applicable elementWiseStride = array . elementWiseStride ( ) ; } else { INDArray secondTensor = array . tensorAlongDimension ( 1 , dimension ) ; tensorStartSeparation = secondTensor . offset ( ) - firstTensorOffset ; elementWiseStride = secondTensor . elementWiseStride ( ) ; } return new Tensor1DStats ( firstTensorOffset , tensorStartSeparation , numTensors , tensorLength , elementWiseStride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method calculates dot of gives rows [CODESPLIT] @ Override public void processMessage ( ) { // this only picks up new training round //log.info(\"sI_{} Processing DistributedSgDotMessage taskId: {}\", transport.getShardIndex(), getTaskId()); SkipGramRequestMessage sgrm = new SkipGramRequestMessage ( w1 , w2 , rowsB , codes , negSamples , alpha , 119 ) ; if ( negSamples > 0 ) { // unfortunately we have to get copy of negSamples here int negatives [ ] = Arrays . copyOfRange ( rowsB , codes . length , rowsB . length ) ; sgrm . setNegatives ( negatives ) ; } sgrm . setTaskId ( this . taskId ) ; sgrm . setOriginatorId ( this . getOriginatorId ( ) ) ; // FIXME: get rid of THAT SkipGramTrainer sgt = ( SkipGramTrainer ) trainer ; sgt . pickTraining ( sgrm ) ; //TODO: make this thing a single op, even specialOp is ok // we calculate dot for all involved rows int resultLength = codes . length + ( negSamples > 0 ? ( negSamples + 1 ) : 0 ) ; INDArray result = Nd4j . createUninitialized ( resultLength , 1 ) ; int e = 0 ; for ( ; e < codes . length ; e ++ ) { double dot = Nd4j . getBlasWrapper ( ) . dot ( storage . getArray ( WordVectorStorage . SYN_0 ) . getRow ( w2 ) , storage . getArray ( WordVectorStorage . SYN_1 ) . getRow ( rowsB [ e ] ) ) ; result . putScalar ( e , dot ) ; } // negSampling round for ( ; e < resultLength ; e ++ ) { double dot = Nd4j . getBlasWrapper ( ) . dot ( storage . getArray ( WordVectorStorage . SYN_0 ) . getRow ( w2 ) , storage . getArray ( WordVectorStorage . SYN_1_NEGATIVE ) . getRow ( rowsB [ e ] ) ) ; result . putScalar ( e , dot ) ; } if ( voidConfiguration . getExecutionMode ( ) == ExecutionMode . AVERAGING ) { // just local bypass DotAggregation dot = new DotAggregation ( taskId , ( short ) 1 , shardIndex , result ) ; dot . setTargetId ( ( short ) - 1 ) ; dot . setOriginatorId ( getOriginatorId ( ) ) ; transport . putMessage ( dot ) ; } else if ( voidConfiguration . getExecutionMode ( ) == ExecutionMode . SHARDED ) { // send this message to everyone DotAggregation dot = new DotAggregation ( taskId , ( short ) voidConfiguration . getNumberOfShards ( ) , shardIndex , result ) ; dot . setTargetId ( ( short ) - 1 ) ; dot . setOriginatorId ( getOriginatorId ( ) ) ; transport . sendMessage ( dot ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mean squared error : L = mean ( ( predicted - label ) ^2 ) [CODESPLIT] public static LossInfo mse ( String outputName , SDVariable predictions , SDVariable label , SDVariable weights , Reduction reduction , int ... dimensions ) { LossInfo . Builder b = validate ( \"mse\" , predictions , label , reduction ) ; SameDiff sd = predictions . getSameDiff ( ) ; if ( weights == null ) { weights = sd . one ( \"mse_loss_weights\" , SCALAR ) ; } SDVariable diff = predictions . sub ( label ) ; String name = ( reduction == Reduction . NONE ? outputName : null ) ; SDVariable preReduceLoss = sd . square ( diff ) . mul ( name , weights ) ; return doReduce ( sd , outputName , true , b , reduction , preReduceLoss , label , weights , dimensions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multi - Class Cross Entropy loss function : <br > L = sum_i actual_i * log ( predicted_i ) [CODESPLIT] public static LossInfo mcxent ( String outputName , SDVariable predictions , SDVariable label , SDVariable weights , Reduction reduction , int ... dimensions ) { LossInfo . Builder b = validate ( \"mcxent\" , predictions , label , reduction ) ; SameDiff sd = predictions . getSameDiff ( ) ; if ( weights == null ) { weights = sd . one ( \"mcxent_loss_weights\" , SCALAR ) ; } String name = ( reduction == Reduction . NONE ? outputName : null ) ; SDVariable weightedLogProd = sd . log ( predictions ) . mul ( label ) . mul ( name , weights ) ; return doReduce ( sd , outputName , false , b , reduction , weightedLogProd , label , weights , dimensions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the number of weight entries that are non - zero after broadcasting [CODESPLIT] private static SDVariable nonZeroCount ( SDVariable weights , SDVariable labels ) { SameDiff sd = weights . getSameDiff ( ) ; SDVariable present = sd . neq ( weights , 0.0 ) ; SDVariable presentBroadcast = sd . zerosLike ( labels ) . add ( present ) ; return sd . sum ( presentBroadcast ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the final reduction on the loss function [CODESPLIT] private static LossInfo doReduce ( SameDiff sd , String outputName , boolean isMean , LossInfo . Builder b , Reduction reduction , SDVariable preReduceLoss , SDVariable label , SDVariable weights , int [ ] dimensions ) { switch ( reduction ) { case NONE : //Return same shape as predictions/labels b . loss ( preReduceLoss ) ; break ; case SPECIFIED_DIMS : //Reduce along specified dimensions if ( isMean ) { //Example: MSE + mean along examples b . loss ( sd . mean ( outputName , preReduceLoss , dimensions ) ) ; } else { //Example: L1 loss (sum) + mean along examples b . loss ( sd . sum ( outputName , preReduceLoss , dimensions ) ) ; } case SUM : if ( isMean ) { //Example: MSE (mean) + sum along examples SDVariable m = sd . mean ( preReduceLoss , dimensions ) ; b . loss ( sd . sum ( outputName , m ) ) ; } else { //Example: L1 loss (sum) + sum along examples -> sum along all dimensions b . loss ( sd . sum ( outputName , preReduceLoss ) ) ; } break ; case MEAN_BY_WEIGHT : SDVariable weightSum = sd . sum ( weights ) ; if ( isMean ) { //Example: MSE (mean) + mean by weights over examples //reduce along dims + reduce along remaining dims == reduce along *all* dims SDVariable m2 = sd . mean ( preReduceLoss ) ; b . loss ( m2 . div ( outputName , weightSum ) ) ; } else { //Example: L1 (sum) + mean by weights over examples SDVariable sum = sd . sum ( preReduceLoss , dimensions ) ; b . loss ( sum . div ( outputName , weightSum ) ) ; } break ; case MEAN_BY_COUNT : SDVariable nonZeroWeights = nonZeroCount ( weights , label ) ; SDVariable r ; if ( isMean ) { //Example: MSE (mean) + mean by count over examples r = sd . sum ( preReduceLoss ) ; } else { //Example: L1 (sum) + mean by count over examples SDVariable sum = sd . sum ( preReduceLoss , dimensions ) ; r = sd . mean ( sum ) ; } b . loss ( r . div ( outputName , nonZeroWeights ) ) ; break ; default : throw new RuntimeException ( \"Unknown reduction: \" + reduction ) ; } return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize this CaptureTypeImpl . This is needed for type variable bounds referring to each other : we need the capture of the argument . [CODESPLIT] void init ( VarMap varMap ) { ArrayList < Type > upperBoundsList = new ArrayList <> ( ) ; upperBoundsList . addAll ( Arrays . asList ( varMap . map ( variable . getBounds ( ) ) ) ) ; List < Type > wildcardUpperBounds = Arrays . asList ( wildcard . getUpperBounds ( ) ) ; if ( wildcardUpperBounds . size ( ) > 0 && wildcardUpperBounds . get ( 0 ) == Object . class ) { // skip the Object bound, we already have a first upper bound from 'variable' upperBoundsList . addAll ( wildcardUpperBounds . subList ( 1 , wildcardUpperBounds . size ( ) ) ) ; } else { upperBoundsList . addAll ( wildcardUpperBounds ) ; } upperBounds = new Type [ upperBoundsList . size ( ) ] ; upperBoundsList . toArray ( upperBounds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throw an IllegalStateException if the class does not have a no - arg constructor . [CODESPLIT] public static < T > Constructor < T > getNoArgConstructor ( Class < T > clazz ) { try { Constructor < T > ctor = clazz . getDeclaredConstructor ( new Class [ 0 ] ) ; ctor . setAccessible ( true ) ; return ctor ; } catch ( NoSuchMethodException e ) { // lame there is no way to tell if the class is a nonstatic inner class if ( clazz . isMemberClass ( ) || clazz . isAnonymousClass ( ) || clazz . isLocalClass ( ) ) throw new IllegalStateException ( clazz . getName ( ) + \" must be static and must have a no-arg constructor\" , e ) ; else throw new IllegalStateException ( clazz . getName ( ) + \" must have a no-arg constructor\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a constructor that has the specified types of arguments . Throw an IllegalStateException if the class does not have such a constructor . [CODESPLIT] public static MethodHandle getConstructor ( Class < ? > clazz , Class < ? > ... args ) { try { // We use unreflect so that we can make the constructor accessible Constructor < ? > ctor = clazz . getDeclaredConstructor ( args ) ; ctor . setAccessible ( true ) ; return MethodHandles . lookup ( ) . unreflectConstructor ( ctor ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( clazz . getName ( ) + \" has no constructor with args \" + Arrays . toString ( args ) , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( \"Problem getting constructor for \" + clazz . getName ( ) + \" with args \" + Arrays . toString ( args ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps any non - runtime exceptions with a runtime exception [CODESPLIT] public static < T > T invoke ( MethodHandle methodHandle , Object ... params ) { try { return ( T ) methodHandle . invokeWithArguments ( params ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Throwable throwable ) { throw new RuntimeException ( throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checked exceptions are LAME . [CODESPLIT] public static < T > T newInstance ( Constructor < T > ctor , Object ... params ) { try { return ctor . newInstance ( params ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checked exceptions are LAME . [CODESPLIT] public static Object field_get ( Field field , Object obj ) { try { return field . get ( obj ) ; } catch ( IllegalArgumentException | IllegalAccessException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Just like Class . isAssignableFrom () but does the right thing when considering autoboxing . [CODESPLIT] public static boolean isAssignableFrom ( Class < ? > to , Class < ? > from ) { Class < ? > notPrimitiveTo = to . isPrimitive ( ) ? PRIMITIVE_TO_WRAPPER . get ( to ) : to ; Class < ? > notPrimitiveFrom = from . isPrimitive ( ) ? PRIMITIVE_TO_WRAPPER . get ( from ) : from ; return notPrimitiveTo . isAssignableFrom ( notPrimitiveFrom ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the annotation that has the specified type or null if there isn t one [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < A extends Annotation > A getAnnotation ( Annotation [ ] annotations , Class < A > annotationType ) { for ( Annotation anno : annotations ) if ( annotationType . isAssignableFrom ( anno . getClass ( ) ) ) return ( A ) anno ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the declared annotation ignoring any inherited annotations [CODESPLIT] public static < A extends Annotation > A getDeclaredAnnotation ( Class < ? > onClass , Class < A > annotationType ) { return getAnnotation ( onClass . getDeclaredAnnotations ( ) , annotationType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is the declared annotation present ignoring any inherited annotations [CODESPLIT] public static < A extends Annotation > boolean isDeclaredAnnotationPresent ( Class < ? > onClass , Class < A > annotationType ) { return getDeclaredAnnotation ( onClass , annotationType ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ResultProxy for the given interface . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < S > S create ( Class < ? super S > interf , Result < S > result ) { return ( S ) Proxy . newProxyInstance ( result . getClass ( ) . getClassLoader ( ) , new Class [ ] { interf } , new ResultProxy <> ( result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Response commit ( ) { // Complete any enlisted operations so that the session becomes consistent. Note that some of the // enlisted load operations might result in further enlistment... so we have to do this in a loop // that protects against concurrent modification exceptions while ( ! enlisted . isEmpty ( ) ) { final List < Result < ? > > last = enlisted ; enlisted = new ArrayList <> ( ) ; for ( final Result < ? > result : last ) result . now ( ) ; } final Response response = transaction . commit ( ) ; afterCommit . run ( ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an entity to an object of the appropriate type for this metadata structure . Does not check that the entity is appropriate ; that should be done when choosing which EntityMetadata to call . [CODESPLIT] public P load ( final BaseEntity < ? > ent , final LoadContext ctx ) { try { // The context needs to know the root entity for any given point ctx . setCurrentRoot ( Key . create ( ( com . google . cloud . datastore . Key ) ent . getKey ( ) ) ) ; final EntityValue entityValue = makeLoadEntityValue ( ent ) ; return translator . load ( entityValue , ctx , Path . root ( ) ) ; } catch ( LoadException ex ) { throw ex ; } catch ( Exception ex ) { throw new LoadException ( ent , ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The problem is ProjectionEntity ; there s no way to create an EntityValue with a ProjectionEntity so we can t use the standard translation system for { [CODESPLIT] private EntityValue makeLoadEntityValue ( final BaseEntity < ? > ent ) { if ( ent instanceof FullEntity < ? > ) { return EntityValue . of ( ( FullEntity < ? > ) ent ) ; } else { // Sadly there's no more graceful way of doing this final Builder < ? > builder = FullEntity . newBuilder ( ent . getKey ( ) ) ; for ( final String name : ent . getNames ( ) ) { final Value < ? > value = ent . getValue ( name ) ; builder . set ( name , value ) ; } return EntityValue . of ( builder . build ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an object to a datastore Entity with the appropriate Key type . [CODESPLIT] public FullEntity < ? > save ( final P pojo , final SaveContext ctx ) { try { return translator . save ( pojo , false , ctx , Path . root ( ) ) . get ( ) ; } catch ( SaveException ex ) { throw ex ; } catch ( Exception ex ) { throw new SaveException ( pojo , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > filter ( final String condition , final Object value ) { final QueryImpl < T > q = createQuery ( ) ; q . addFilter ( condition , value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the instance [CODESPLIT] void addFilter ( final String condition , final Object value ) { final String [ ] parts = condition . trim ( ) . split ( \" \" ) ; if ( parts . length < 1 || parts . length > 2 ) throw new IllegalArgumentException ( \"'\" + condition + \"' is not a legal filter condition\" ) ; final String prop = parts [ 0 ] . trim ( ) ; final FilterOperator op = ( parts . length == 2 ) ? this . translate ( parts [ 1 ] ) : FilterOperator . EQUAL ; // If we have a class restriction, check to see if the property is the @Parent or @Id. We used to try to convert\r // filtering on the id field to a __key__ query, but that tended to confuse users about the real capabilities\r // of GAE and Objectify. So let's force users to use filterKey() instead.\r if ( this . classRestriction != null ) { final KeyMetadata < ? > meta = loader . ofy . factory ( ) . keys ( ) . getMetadataSafe ( this . classRestriction ) ; if ( prop . equals ( meta . getParentFieldName ( ) ) ) { throw new IllegalArgumentException ( \"@Parent fields cannot be filtered on. Perhaps you wish to use filterKey() or ancestor() instead?\" ) ; } else if ( prop . equals ( meta . getIdFieldName ( ) ) ) { throw new IllegalArgumentException ( \"@Id fields cannot be filtered on. Perhaps you wish to use filterKey() instead?\" ) ; } } // Convert to something filterable, possibly extracting/converting keys\r final Value < ? > translated = loader . getObjectifyImpl ( ) . makeFilterable ( value ) ; addFilter ( op . of ( prop , translated ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the textual operator ( > < = etc ) into a FilterOperator . Forgiving about the syntax ; ! = and < > are NOT_EQUAL = and == are EQUAL . [CODESPLIT] protected FilterOperator translate ( String operator ) { operator = operator . trim ( ) ; if ( operator . equals ( \"=\" ) || operator . equals ( \"==\" ) ) return FilterOperator . EQUAL ; else if ( operator . equals ( \">\" ) ) return FilterOperator . GREATER_THAN ; else if ( operator . equals ( \">=\" ) ) return FilterOperator . GREATER_THAN_OR_EQUAL ; else if ( operator . equals ( \"<\" ) ) return FilterOperator . LESS_THAN ; else if ( operator . equals ( \"<=\" ) ) return FilterOperator . LESS_THAN_OR_EQUAL ; else if ( operator . equals ( \"!=\" ) || operator . equals ( \"<>\" ) ) //return FilterOperator.NOT_EQUAL;\r throw new UnsupportedOperationException ( \"The Cloud Datastore SDK does not currently support 'NOT EQUAL' filters\" ) ; else if ( operator . toLowerCase ( ) . equals ( \"in\" ) ) //return FilterOperator.IN;\r throw new UnsupportedOperationException ( \"The Cloud Datastore SDK does not currently support 'IN' filters\" ) ; else throw new IllegalArgumentException ( \"Unknown operator '\" + operator + \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the instance [CODESPLIT] void addOrder ( String condition ) { condition = condition . trim ( ) ; boolean descending = false ; if ( condition . startsWith ( \"-\" ) ) { descending = true ; condition = condition . substring ( 1 ) . trim ( ) ; } // Prevent ordering by @Id or @Parent fields, which are really part of the key\r if ( this . classRestriction != null ) { final KeyMetadata < ? > meta = loader . ofy . factory ( ) . keys ( ) . getMetadataSafe ( this . classRestriction ) ; if ( condition . equals ( meta . getParentFieldName ( ) ) ) throw new IllegalArgumentException ( \"You cannot order by @Parent field. Perhaps you wish to order by __key__ instead?\" ) ; if ( condition . equals ( meta . getIdFieldName ( ) ) ) { throw new IllegalArgumentException ( \"You cannot order by @Id field. Perhaps you wish to order by __key__ instead?\" ) ; } } this . actual = actual . orderBy ( descending ? OrderBy . desc ( condition ) : OrderBy . asc ( condition ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the instance [CODESPLIT] void setAncestor ( final Object keyOrEntity ) { final com . google . cloud . datastore . Key key = loader . ofy . factory ( ) . keys ( ) . anythingToRawKey ( keyOrEntity ) ; this . actual = this . actual . andFilter ( PropertyFilter . hasAncestor ( key ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the instance [CODESPLIT] void setLimit ( final int value ) { this . actual = this . actual . limit ( value ) ; if ( this . chunk == null ) this . chunk = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the instance [CODESPLIT] void addProjection ( final String ... fields ) { if ( this . hybrid != null && this . hybrid ) throw new IllegalStateException ( \"You cannot ask for both hybrid and projections in the same query. That makes no sense!\" ) ; for ( final String field : fields ) { this . actual = this . actual . project ( field ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public LoadResult < T > first ( ) { // By the way, this is the same thing that PreparedQuery.asSingleEntity() does internally\r final Iterator < T > it = this . limit ( 1 ) . iterator ( ) ; return new LoadResult <> ( null , new IteratorFirstResult <> ( it ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryResults < T > iterator ( ) { if ( ! actual . getProjection ( ) . isEmpty ( ) ) return loader . createQueryEngine ( ) . queryProjection ( this . actual . newProjectionQuery ( ) ) ; else if ( shouldHybridize ( ) ) return loader . createQueryEngine ( ) . queryHybrid ( this . actual . newKeyQuery ( ) , chunk == null ? Integer . MAX_VALUE : chunk ) ; else return loader . createQueryEngine ( ) . queryNormal ( this . actual . newEntityQuery ( ) , chunk == null ? Integer . MAX_VALUE : chunk ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public List < T > list ( ) { return ResultProxy . create ( List . class , new MakeListResult <> ( this . chunk ( Integer . MAX_VALUE ) . iterator ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an iterator over the keys . Not part of the public api but used by QueryKeysImpl . Assumes that setKeysOnly () has already been set . [CODESPLIT] QueryResults < Key < T > > keysIterator ( ) { final QueryEngine queryEngine = loader . createQueryEngine ( ) ; final KeyQuery query = this . actual . newKeyQuery ( ) ; return queryEngine . queryKeysOnly ( query ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Builder api is programmer - hostile [CODESPLIT] public static void addOrderBy ( final StructuredQuery . Builder < ? > builder , final List < OrderBy > orderBy ) { if ( ! orderBy . isEmpty ( ) ) { builder . addOrderBy ( orderBy . get ( 0 ) , orderBy . subList ( 1 , orderBy . size ( ) ) . toArray ( new OrderBy [ orderBy . size ( ) - 1 ] ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Builder api is programmer - hostile [CODESPLIT] public static void addProjection ( final ProjectionEntityQuery . Builder builder , final List < String > projection ) { if ( ! projection . isEmpty ( ) ) { builder . addProjection ( projection . get ( 0 ) , projection . subList ( 1 , projection . size ( ) ) . toArray ( new String [ projection . size ( ) - 1 ] ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Builder api is programmer - hostile [CODESPLIT] public static void addDistinctOn ( final ProjectionEntityQuery . Builder builder , final List < String > distinctOn ) { if ( ! distinctOn . isEmpty ( ) ) { builder . addDistinctOn ( distinctOn . get ( 0 ) , distinctOn . subList ( 1 , distinctOn . size ( ) ) . toArray ( new String [ distinctOn . size ( ) - 1 ] ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the proxy that does retries . Adds a strict error handler to the service . [CODESPLIT] public static MemcacheService createProxy ( final MemcacheService raw , final int retryCount ) { return ( MemcacheService ) java . lang . reflect . Proxy . newProxyInstance ( raw . getClass ( ) . getClassLoader ( ) , raw . getClass ( ) . getInterfaces ( ) , new MemcacheServiceRetryProxy ( raw , retryCount ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Object invoke ( Object proxy , Method meth , Object [ ] args ) throws Throwable { for ( int i = 0 ; i < this . tries ; i ++ ) { try { return meth . invoke ( this . raw , args ) ; } catch ( InvocationTargetException ex ) { if ( i == ( this . tries - 1 ) ) log . error ( \"Memcache operation failed, giving up\" , ex ) ; else log . warn ( \"Error performing memcache operation, retrying: \" + meth , ex ) ; } } // Will reach this point when we have exhausted our retries.\r return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public Translator < Object , Object > create ( final TypeKey < Object > tk , final CreateContext createCtx , final Path path ) { if ( tk . getTypeAsClass ( ) != Object . class ) return null ; return new NullSafeTranslator < Object , Object > ( ) { @ Override protected Object loadSafe ( final Value < Object > value , final LoadContext ctx , final Path path ) throws SkipException { return value . get ( ) ; } @ Override protected Value < Object > saveSafe ( final Object pojo , final boolean index , final SaveContext saveCtx , final Path path ) throws SkipException { final TypeKey < Object > runtimeTypeKey = new TypeKey <> ( pojo . getClass ( ) ) ; // We really only need the createctx so that the translators can get a factory. final Translator < Object , Object > realTranslator = translators . get ( runtimeTypeKey , createCtx , path ) ; return realTranslator . save ( pojo , index , saveCtx , path ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate through all pending futures and get () them forcing any callbacks to be called . This is used only by the AsyncCacheFilter ( if using cache without Objectify ) or ObjectifyFilter ( if using Objectify normally ) because we don t have a proper hook otherwise . [CODESPLIT] public static void completeAllPendingFutures ( ) { // This will cause done Futures to fire callbacks and remove themselves\r for ( Future < ? > fut : pending . get ( ) . keySet ( ) ) { try { fut . get ( ) ; } catch ( Exception e ) { log . error ( \"Error cleaning up pending Future: \" + fut , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > All @Entity and @Subclass classes ( for both entity and embedded classes ) must be registered before using Objectify to load or save data . This method must be called in a single - threaded mode sometime around application initialization . < / p > [CODESPLIT] public < T > void register ( Class < T > clazz ) { // There are two possible cases\r // 1) This might be a simple class with @Entity\r // 2) This might be a class annotated with @Subclass\r // @Entity is inherited, but we only create entity metadata for the class with the @Entity declaration\r if ( TypeUtils . isDeclaredAnnotationPresent ( clazz , Entity . class ) ) { String kind = Key . getKind ( clazz ) ; // If we are already registered, ignore\r if ( this . byKind . containsKey ( kind ) ) return ; EntityMetadata < T > cmeta = new EntityMetadata <> ( this . fact , clazz ) ; this . byKind . put ( kind , cmeta ) ; if ( cmeta . getCacheExpirySeconds ( ) != null ) this . cacheEnabled = true ; } else if ( clazz . isAnnotationPresent ( Subclass . class ) ) { // We just need to make sure that a translator was created\r fact . getTranslators ( ) . getRoot ( clazz ) ; } else { throw new IllegalArgumentException ( clazz + \" must be annotated with either @Entity or @Subclass\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets metadata for the specified kind [CODESPLIT] public < T > EntityMetadata < T > getMetadataSafe ( String kind ) throws IllegalArgumentException { EntityMetadata < T > metadata = this . getMetadata ( kind ) ; if ( metadata == null ) throw new IllegalArgumentException ( \"No entity class has been registered which matches kind '\" + kind + \"'\" ) ; else return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a keys - only query . [CODESPLIT] public < T > QueryResults < Key < T > > queryKeysOnly ( final KeyQuery query ) { log . trace ( \"Starting keys-only query\" ) ; return new KeyQueryResults <> ( ds . run ( query ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a keys - only plus batch gets . [CODESPLIT] public < T > QueryResults < T > queryHybrid ( final KeyQuery query , final int chunkSize ) { log . trace ( \"Starting hybrid query\" ) ; final QueryResults < Key < T > > results = new KeyQueryResults <> ( ds . run ( query ) ) ; return new HybridQueryResults <> ( loader . createLoadEngine ( ) , results , chunkSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A normal non - hybrid query [CODESPLIT] public < T > QueryResults < T > queryNormal ( final EntityQuery query , final int chunkSize ) { log . trace ( \"Starting normal query\" ) ; // Normal queries are actually more complex than hybrid queries because we need the fetched entities to\r // be stuffed back into the engine to satisfy @Load instructions without extra fetching. Even though\r // this looks like we're doing hybrid load-by-key operations, the data is pulled from the stuffed values.\r final LoadEngine loadEngine = loader . createLoadEngine ( ) ; final QueryResults < Entity > entityResults = ds . run ( query ) ; final QueryResults < com . google . cloud . datastore . Key > stuffed = new StuffingQueryResults ( loadEngine , entityResults ) ; final QueryResults < Key < T > > keyResults = new KeyQueryResults <> ( stuffed ) ; return new HybridQueryResults <> ( loadEngine , keyResults , chunkSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A projection query . Bypasses the session entirely . [CODESPLIT] public < T > QueryResults < T > queryProjection ( final ProjectionEntityQuery query ) { log . trace ( \"Starting projection query\" ) ; final LoadEngine loadEngine = loader . createLoadEngine ( ) ; return new ProjectionQueryResults <> ( ds . run ( query ) , loadEngine ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The fundamental query count operation . This doesn t appear to be implemented in the new SDK so we simulate with a keys - only query . [CODESPLIT] public int queryCount ( final KeyQuery query ) { log . trace ( \"Starting count query\" ) ; final QueryResults < com . google . cloud . datastore . Key > results = ds . run ( query ) ; return Iterators . size ( results ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects Integer . MAX_VALUE and prevents OOM exceptions [CODESPLIT] private < T > Iterator < Iterator < T > > safePartition ( final Iterator < T > input , int chunkSize ) { // Cloud Datastore library errors if you try to fetch more than 1000 keys at a time if ( chunkSize > 1000 ) { chunkSize = 1000 ; } return Iterators . transform ( Iterators . partition ( input , chunkSize ) , IterateFunction . instance ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads them ; note that it s possible for some loaded results to be null [CODESPLIT] private Iterator < ResultWithCursor < T > > load ( final Iterator < ResultWithCursor < Key < T > > > keys ) { final List < Entry < ResultWithCursor < Key < T > > , Result < T > > > results = Lists . newArrayList ( ) ; while ( keys . hasNext ( ) ) { final ResultWithCursor < Key < T > > next = keys . next ( ) ; results . add ( Maps . immutableEntry ( next , loadEngine . load ( next . getResult ( ) ) ) ) ; } loadEngine . execute ( ) ; return Iterators . transform ( results . iterator ( ) , entry -> new ResultWithCursor <> ( entry . getValue ( ) . now ( ) , entry . getKey ( ) . getCursorAfter ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies an array of primitive longs while boxing them at the same time and then converting into a list . Can t use { @link Arrays#asList ( Object [] ) } directly as that will create a list of arrays instead . [CODESPLIT] public static List < Long > asList ( long ... elements ) { Objects . requireNonNull ( elements ) ; Long [ ] copy = new Long [ elements . length ] ; for ( int index = 0 ; index < elements . length ; index ++ ) { copy [ index ] = elements [ index ] ; } return Arrays . asList ( copy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like now () but throws NotFoundException instead of returning null . [CODESPLIT] public final T safe ( ) throws NotFoundException { T t = now ( ) ; if ( t == null ) throw new NotFoundException ( key ) ; else return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a log a message for a given path [CODESPLIT] public static String msg ( Path path , String msg ) { StringBuilder bld = new StringBuilder ( ) ; bld . append ( \"\\t.\" ) ; bld . append ( path . toPathString ( ) ) ; if ( bld . length ( ) < PATH_PADDING ) while ( bld . length ( ) < PATH_PADDING ) bld . append ( ' ' ) ; else bld . append ( ' ' ) ; bld . append ( msg ) ; return bld . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Key . create ( key ) is easier to type than new Key<Blah > ( key ) [CODESPLIT] public static < T > Key < T > create ( final com . google . cloud . datastore . Key raw ) { if ( raw == null ) throw new NullPointerException ( \"Cannot create a Key<?> from a null datastore Key\" ) ; return new Key <> ( raw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Key . create ( Blah . class id ) is easier to type than new Key<Blah > ( Blah . class id ) [CODESPLIT] public static < T > Key < T > create ( final Class < ? extends T > kindClass , final long id ) { return new Key <> ( kindClass , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Key . create ( Blah . class name ) is easier to type than new Key<Blah > ( Blah . class name ) [CODESPLIT] public static < T > Key < T > create ( final Class < ? extends T > kindClass , final String name ) { return new Key <> ( kindClass , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Key . create ( urlSafeString ) is easier to type than new Key<Blah > ( urlSafeString ) [CODESPLIT] public static < T > Key < T > create ( final String urlSafeString ) { if ( urlSafeString == null ) throw new NullPointerException ( \"Cannot create a Key<?> from a null String\" ) ; return new Key <> ( urlSafeString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a key from a registered POJO entity . [CODESPLIT] public static < T > Key < T > create ( final T pojo ) { return ObjectifyService . factory ( ) . keys ( ) . keyOf ( pojo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > The new cloud sdk Key doesn t have compareTo () so we reimplement the logic from the old GAE SDK . < / p > [CODESPLIT] @ Override public int compareTo ( final Key < ? > other ) { if ( this . raw == other . raw ) { return 0 ; } { final int result = this . raw . getProjectId ( ) . compareTo ( other . raw . getProjectId ( ) ) ; if ( result != 0 ) return result ; } { final int result = this . raw . getNamespace ( ) . compareTo ( other . raw . getNamespace ( ) ) ; if ( result != 0 ) return result ; } { final int result = this . compareAncestors ( other ) ; if ( result != 0 ) return result ; } { // Too bad PathElement and Key don't share any kind of interface grrr\r final int result = this . getRaw ( ) . getKind ( ) . compareTo ( other . getRaw ( ) . getKind ( ) ) ; if ( result != 0 ) { return result ; } else if ( this . raw . getNameOrId ( ) == null && other . raw . getNameOrId ( ) == null ) { return compareToWithIdentityHash ( this . raw , other . raw ) ; } else if ( this . raw . hasId ( ) ) { return other . raw . hasId ( ) ? Long . compare ( this . raw . getId ( ) , other . raw . getId ( ) ) : - 1 ; } else { return other . raw . hasId ( ) ? 1 : this . raw . getName ( ) . compareTo ( other . raw . getName ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "I have no idea what this is about it was in the old logic [CODESPLIT] private int compareToWithIdentityHash ( final Object k1 , final Object k2 ) { return Integer . compare ( System . identityHashCode ( k1 ) , System . identityHashCode ( k2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Easy null - safe conversion of the raw key . [CODESPLIT] public static < V > Key < V > key ( final com . google . cloud . datastore . Key raw ) { if ( raw == null ) return null ; else return new Key <> ( raw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Easy null - safe conversion of the typed key . [CODESPLIT] public static com . google . cloud . datastore . Key key ( final Key < ? > typed ) { if ( typed == null ) return null ; else return typed . getRaw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Determines the kind for a Class as understood by the datastore . The first class in a hierarchy that has @Entity defines the kind ( either explicitly or as that class simplename ) . < / p > [CODESPLIT] public static String getKind ( final Class < ? > clazz ) { final String kind = getKindRecursive ( clazz ) ; if ( kind == null ) return clazz . getSimpleName ( ) ; else return kind ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Recursively looks for the @Entity annotation . < / p > [CODESPLIT] private static String getKindRecursive ( final Class < ? > clazz ) { if ( clazz == Object . class ) return null ; final String kind = getKindHere ( clazz ) ; if ( kind != null ) return kind ; else return getKindRecursive ( clazz . getSuperclass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the kind from the class if the class has an [CODESPLIT] private static String getKindHere ( final Class < ? > clazz ) { // @Entity is inherited so we have to be explicit about the declared annotations\r final Entity ourAnn = TypeUtils . getDeclaredAnnotation ( clazz , Entity . class ) ; if ( ourAnn != null ) if ( ourAnn . name ( ) . length ( ) != 0 ) return ourAnn . name ( ) ; else return clazz . getSimpleName ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the given type is a class that is supposed to have type parameters but doesn t . In other words if it s a really raw type . [CODESPLIT] static boolean isMissingTypeParameters ( Type type ) { if ( type instanceof Class ) { for ( Class < ? > clazz = ( Class < ? > ) type ; clazz != null ; clazz = clazz . getEnclosingClass ( ) ) { if ( clazz . getTypeParameters ( ) . length != 0 ) return true ; } return false ; } else if ( type instanceof ParameterizedType ) { return false ; } else { throw new AssertionError ( \"Unexpected type \" + type . getClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the capture of subType is a subtype of superType [CODESPLIT] public static boolean isSuperType ( Type superType , Type subType ) { if ( superType instanceof ParameterizedType || superType instanceof Class || superType instanceof GenericArrayType ) { Class < ? > superClass = erase ( superType ) ; Type mappedSubType = getExactSuperType ( capture ( subType ) , superClass ) ; if ( mappedSubType == null ) { return false ; } else if ( superType instanceof Class < ? > ) { return true ; } else if ( mappedSubType instanceof Class < ? > ) { // TODO treat supertype by being raw type differently (\"supertype, but with warnings\") return true ; // class has no parameters, or it's a raw type } else if ( mappedSubType instanceof GenericArrayType ) { Type superComponentType = getArrayComponentType ( superType ) ; assert superComponentType != null ; Type mappedSubComponentType = getArrayComponentType ( mappedSubType ) ; assert mappedSubComponentType != null ; return isSuperType ( superComponentType , mappedSubComponentType ) ; } else { assert mappedSubType instanceof ParameterizedType ; ParameterizedType pMappedSubType = ( ParameterizedType ) mappedSubType ; assert pMappedSubType . getRawType ( ) == superClass ; ParameterizedType pSuperType = ( ParameterizedType ) superType ; Type [ ] superTypeArgs = pSuperType . getActualTypeArguments ( ) ; Type [ ] subTypeArgs = pMappedSubType . getActualTypeArguments ( ) ; assert superTypeArgs . length == subTypeArgs . length ; for ( int i = 0 ; i < superTypeArgs . length ; i ++ ) { if ( ! contains ( superTypeArgs [ i ] , subTypeArgs [ i ] ) ) { return false ; } } // params of the class itself match, so if the owner types are supertypes too, it's a supertype. return pSuperType . getOwnerType ( ) == null || isSuperType ( pSuperType . getOwnerType ( ) , pMappedSubType . getOwnerType ( ) ) ; } } else if ( superType instanceof CaptureType ) { if ( superType . equals ( subType ) ) return true ; for ( Type lowerBound : ( ( CaptureType ) superType ) . getLowerBounds ( ) ) { if ( isSuperType ( lowerBound , subType ) ) { return true ; } } return false ; } else if ( superType instanceof GenericArrayType ) { return isArraySupertype ( superType , subType ) ; } else { throw new RuntimeException ( \"not implemented: \" + superType . getClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the direct supertypes of the given type . Resolves type parameters . [CODESPLIT] private static Type [ ] getExactDirectSuperTypes ( Type type ) { if ( type instanceof ParameterizedType || type instanceof Class ) { Class < ? > clazz ; if ( type instanceof ParameterizedType ) { clazz = ( Class < ? > ) ( ( ParameterizedType ) type ) . getRawType ( ) ; } else { // TODO primitive types? clazz = ( Class < ? > ) type ; if ( clazz . isArray ( ) ) return getArrayExactDirectSuperTypes ( clazz ) ; } Type [ ] superInterfaces = clazz . getGenericInterfaces ( ) ; Type superClass = clazz . getGenericSuperclass ( ) ; // the only supertype of an interface without superinterfaces is Object if ( superClass == null && superInterfaces . length == 0 && clazz . isInterface ( ) ) { return new Type [ ] { Object . class } ; } Type [ ] result ; int resultIndex ; if ( superClass == null ) { result = new Type [ superInterfaces . length ] ; resultIndex = 0 ; } else { result = new Type [ superInterfaces . length + 1 ] ; resultIndex = 1 ; result [ 0 ] = mapTypeParameters ( superClass , type ) ; } for ( Type superInterface : superInterfaces ) { result [ resultIndex ++ ] = mapTypeParameters ( superInterface , type ) ; } return result ; } else if ( type instanceof TypeVariable ) { TypeVariable < ? > tv = ( TypeVariable < ? > ) type ; return tv . getBounds ( ) ; } else if ( type instanceof WildcardType ) { // This should be a rare case: normally this wildcard is already captured. // But it does happen if the upper bound of a type variable contains a wildcard // TODO shouldn't upper bound of type variable have been captured too? (making this case impossible?) return ( ( WildcardType ) type ) . getUpperBounds ( ) ; } else if ( type instanceof CaptureType ) { return ( ( CaptureType ) type ) . getUpperBounds ( ) ; } else if ( type instanceof GenericArrayType ) { return getArrayExactDirectSuperTypes ( type ) ; } else if ( type == null ) { throw new NullPointerException ( ) ; } else { throw new RuntimeException ( \"not implemented type: \" + type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the exact type of the given field in the given type . This may be different from <tt > f . getGenericType () < / tt > when the field was declared in a superclass or <tt > type< / tt > has a type parameter that is used in the type of the field or <tt > type< / tt > is a raw type . [CODESPLIT] public static Type getExactFieldType ( Field f , Type type ) { Type returnType = f . getGenericType ( ) ; Type exactDeclaringType = getExactSuperType ( capture ( type ) , f . getDeclaringClass ( ) ) ; if ( exactDeclaringType == null ) { // capture(type) is not a subtype of f.getDeclaringClass() throw new IllegalArgumentException ( \"The field \" + f + \" is not a member of type \" + type ) ; } return mapTypeParameters ( returnType , exactDeclaringType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies capture conversion to the given type . [CODESPLIT] public static Type capture ( Type type ) { if ( type instanceof ParameterizedType ) { return capture ( ( ParameterizedType ) type ) ; } else { return type ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the relevant translator creating it if necessary . [CODESPLIT] public < P , D > Translator < P , D > getTranslator ( final TypeKey < P > tk , final CreateContext ctx , final Path path ) { return factory . getTranslators ( ) . get ( tk , ctx , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the populator for the specified class . This requires looking up the translator for that class and then getting the populator from it . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < P > Populator < P > getPopulator ( final Class < P > clazz , final Path path ) { if ( clazz == null || clazz . equals ( Object . class ) ) { return ( Populator < P > ) NullPopulator . INSTANCE ; } else { final ClassTranslator < P > classTranslator = ( ClassTranslator < P > ) this . < P , FullEntity < ? > > getTranslator ( new TypeKey <> ( clazz ) , this , path ) ; return classTranslator . getPopulator ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public void load ( FullEntity < ? > node , LoadContext ctx , Path path , final P into ) { superPopulator . load ( node , ctx , path , into ) ; ctx . enterContainerContext ( into ) ; try { for ( final Populator < Object > prop : props ) { prop . load ( node , ctx , path , into ) ; } } finally { ctx . exitContainerContext ( into ) ; } // If there are any @OnLoad methods, call them after everything else if ( ! onLoadMethods . isEmpty ( ) ) { ctx . defer ( new Runnable ( ) { @ Override public void run ( ) { for ( LifecycleMethod method : onLoadMethods ) method . execute ( into ) ; } @ Override public String toString ( ) { return \"(deferred invoke \" + clazz + \" @OnLoad callbacks on \" + into + \")\" ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public void save ( P pojo , boolean index , SaveContext ctx , Path path , FullEntity . Builder < ? > into ) { superPopulator . save ( pojo , index , ctx , path , into ) ; // Must do @OnSave methods after superclass but before actual population if ( ! ctx . skipLifecycle ( ) && ! onSaveMethods . isEmpty ( ) ) for ( LifecycleMethod method : onSaveMethods ) method . execute ( pojo ) ; if ( indexInstruction != null ) index = indexInstruction ; for ( final Populator < Object > prop : props ) { prop . save ( pojo , index , ctx , path , into ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Figure out if there is an index instruction for the whole class . [CODESPLIT] private Boolean getIndexInstruction ( Class < P > clazz ) { Index ind = clazz . getAnnotation ( Index . class ) ; Unindex unind = clazz . getAnnotation ( Unindex . class ) ; if ( ind != null && unind != null ) throw new IllegalStateException ( \"You cannot have @Index and @Unindex on the same class: \" + clazz ) ; if ( ind != null ) return true ; else if ( unind != null ) return false ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if we should create a Property for the field . Things we ignore : static final [CODESPLIT] private boolean isOfInterest ( Field field ) { return ! field . isAnnotationPresent ( Ignore . class ) && ( ( field . getModifiers ( ) & NOT_SAVEABLE_MODIFIERS ) == 0 ) && ! field . isSynthetic ( ) && ! field . getName ( ) . startsWith ( \"bitmap$init\" ) ; // Scala adds a field bitmap$init$0 and bitmap$init$1 etc }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if we should create a Property for the method ( ie [CODESPLIT] private boolean isOfInterest ( Method method ) { for ( Annotation [ ] annos : method . getParameterAnnotations ( ) ) if ( TypeUtils . getAnnotation ( annos , AlsoLoad . class ) != null ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the persistable fields and methods declared on a class . Ignores superclasses . [CODESPLIT] private List < Property > getDeclaredProperties ( ObjectifyFactory fact , Class < ? > clazz ) { List < Property > good = new ArrayList <> ( ) ; for ( Field field : clazz . getDeclaredFields ( ) ) if ( isOfInterest ( field ) ) good . add ( new FieldProperty ( fact , clazz , field ) ) ; for ( Method method : clazz . getDeclaredMethods ( ) ) if ( isOfInterest ( method ) ) good . add ( new MethodProperty ( method ) ) ; return good ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the key metadata but only if this was an [CODESPLIT] public KeyMetadata < P > getKeyMetadata ( ) { final Populator < Object > populator = props . get ( 0 ) ; Preconditions . checkState ( populator instanceof KeyPopulator , \"Cannot get KeyMetadata for non-@Entity class \" + this . clazz ) ; return ( ( KeyPopulator < P > ) populator ) . getKeyMetadata ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a result using the session cache if possible . [CODESPLIT] public < T > Result < T > get ( final Key < T > key ) { assert ! isExecuted ( ) ; SessionValue < T > sv = getSession ( ) . get ( key ) ; if ( sv == null ) { log . trace ( \"Adding to round (session miss): {}\" , key ) ; this . pending . add ( key . getRaw ( ) ) ; Result < T > result = new ResultCache < T > ( ) { @ Override @ SuppressWarnings ( \"unchecked\" ) public T nowUncached ( ) { // Because clients could conceivably get() in the middle of our operations (see LoadCollectionRefsTest.specialListWorks()), // we need to check for early execution. This will perform poorly, but at least it will work. //assert Round.this.isExecuted(); loadEngine . execute ( ) ; return ( T ) translated . now ( ) . get ( key ) ; } @ Override public String toString ( ) { return \"(Fetch result for \" + key + \")\" ; } } ; sv = new SessionValue <> ( result , getLoadArrangement ( ) ) ; getSession ( ) . add ( key , sv ) ; } else { log . trace ( \"Adding to round (session hit): {}\" , key ) ; if ( sv . loadWith ( getLoadArrangement ( ) ) ) { log . trace ( \"New load group arrangement, checking for upgrades: {}\" , getLoadArrangement ( ) ) ; // We are looking at a brand-new arrangement for something that already existed in the session. // We need to go through any Ref<?>s that might be in need of loading. We find those refs by // actually saving the entity into a custom SaveContext. T thing = sv . getResult ( ) . now ( ) ; if ( thing != null ) { SaveContext saveCtx = new SaveContext ( ) { @ Override public boolean skipLifecycle ( ) { return true ; } @ Override public com . google . cloud . datastore . Key saveRef ( Ref < ? > value , LoadConditions loadConditions ) { com . google . cloud . datastore . Key key = super . saveRef ( value , loadConditions ) ; if ( loadEngine . shouldLoad ( loadConditions ) ) { log . trace ( \"Upgrading key {}\" , key ) ; loadEngine . load ( value . key ( ) ) ; } return key ; } } ; // We throw away the saved entity and we are done loadEngine . ofy . factory ( ) . getMetadataForEntity ( thing ) . save ( thing , saveCtx ) ; } } } return sv . getResult ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turn this into a result set [CODESPLIT] public void execute ( ) { if ( needsExecution ( ) ) { log . trace ( \"Executing round: {}\" , pending ) ; Result < Map < com . google . cloud . datastore . Key , Entity > > fetched = fetchPending ( ) ; translated = loadEngine . translate ( fetched ) ; // If we're in a transaction (and beyond the first round), force all subsequent rounds to complete. // This effectively means that only the first round can be asynchronous; all other rounds are // materialized immediately. The reason for this is that there are some nasty edge cases with @Load // annotations in transactions getting called after the transaction closes. This is possibly not the // best solution to the problem, but it solves the problem now. if ( loadEngine . ofy . getTransaction ( ) != null && depth > 0 ) translated . now ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Possibly pulls some values from the stuffed collection [CODESPLIT] private Result < Map < com . google . cloud . datastore . Key , Entity > > fetchPending ( ) { // We don't need to fetch anything that has been stuffed final Map < com . google . cloud . datastore . Key , Entity > combined = new HashMap <> ( ) ; Set < com . google . cloud . datastore . Key > fetch = new HashSet <> ( ) ; for ( com . google . cloud . datastore . Key key : pending ) { Entity ent = stuffed . get ( key ) ; if ( ent == null ) fetch . add ( key ) ; else combined . put ( key , ent ) ; } if ( fetch . isEmpty ( ) ) { return new ResultNow <> ( combined ) ; } else { final Result < Map < com . google . cloud . datastore . Key , Entity > > fetched = loadEngine . fetch ( fetch ) ; return ( ) -> { combined . putAll ( fetched . now ( ) ) ; return combined ; } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public P loadSafe ( final Value < FullEntity < ? > > container , final LoadContext ctx , final Path path ) throws SkipException { // check if we need to redirect to a different translator final String containerDiscriminator = container . get ( ) . contains ( DISCRIMINATOR_PROPERTY ) ? container . get ( ) . getString ( DISCRIMINATOR_PROPERTY ) : null ; // wow no Optional or nullable get if ( ! Objects . equals ( discriminator , containerDiscriminator ) ) { final ClassTranslator < ? extends P > translator = byDiscriminator . get ( containerDiscriminator ) ; if ( translator == null ) { throw new IllegalStateException ( \"Datastore object has discriminator value '\" + containerDiscriminator + \"' but no relevant @Subclass is registered\" ) ; } else { // This fixes alsoLoad names in discriminators by changing the discriminator to what the // translator expects for loading that subclass. Otherwise we'll get the error above since the // translator discriminator and the container discriminator won't match. final StringValue discriminatorValue = StringValue . newBuilder ( translator . getDiscriminator ( ) ) . setExcludeFromIndexes ( true ) . build ( ) ; final FullEntity < ? > updatedEntity = FullEntity . newBuilder ( container . get ( ) ) . set ( DISCRIMINATOR_PROPERTY , discriminatorValue ) . build ( ) ; return translator . load ( EntityValue . of ( updatedEntity ) , ctx , path ) ; } } else { // This is a normal load if ( log . isTraceEnabled ( ) ) log . trace ( LogUtils . msg ( path , \"Instantiating a \" + declaredClass . getName ( ) ) ) ; final P into = forge . construct ( declaredClass ) ; populator . load ( container . get ( ) , ctx , path , into ) ; return into ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public Value < FullEntity < ? > > saveSafe ( final P pojo , final boolean index , final SaveContext ctx , final Path path ) throws SkipException { // check if we need to redirect to a different translator if ( pojo . getClass ( ) != declaredClass ) { // Sometimes generics are more of a hindrance than a help @ SuppressWarnings ( \"unchecked\" ) final ClassTranslator < P > translator = ( ClassTranslator < P > ) byClass . get ( pojo . getClass ( ) ) ; if ( translator == null ) throw new IllegalStateException ( \"Class '\" + pojo . getClass ( ) + \"' is not a registered @Subclass\" ) ; else return translator . save ( pojo , index , ctx , path ) ; } else { // This is a normal save final FullEntity . Builder < IncompleteKey > into = FullEntity . newBuilder ( ) ; populator . save ( pojo , index , ctx , path , into ) ; if ( discriminator != null ) { into . set ( DISCRIMINATOR_PROPERTY , StringValue . newBuilder ( discriminator ) . setExcludeFromIndexes ( true ) . build ( ) ) ; if ( ! indexedDiscriminators . isEmpty ( ) ) into . set ( DISCRIMINATOR_INDEX_PROPERTY , ListValue . of ( indexedDiscriminators ) ) ; } // The question of whether to index this is weird. In order for subthings to be indexed, the entity needs // to be indexed. But then lists with index-heterogeous values (say, nulls) get reordered (!) // by the datastore. So we always index EntityValues and force all the list translators homogenize their lists. // Gross but seems to be the only way. return EntityValue . of ( into . build ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively go through the class hierarchy adding any discriminators that are indexed [CODESPLIT] private void addIndexedDiscriminators ( final Class < ? > clazz ) { if ( clazz == Object . class ) return ; this . addIndexedDiscriminators ( clazz . getSuperclass ( ) ) ; final Subclass sub = clazz . getAnnotation ( Subclass . class ) ; if ( sub != null && sub . index ( ) ) { final String disc = ( sub . name ( ) . length ( ) > 0 ) ? sub . name ( ) : clazz . getSimpleName ( ) ; this . indexedDiscriminators . add ( StringValue . of ( disc ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a subclass translator with this class translator . That way if we get called upon to translate an instance of the subclass we will forward to the correct translator . [CODESPLIT] public void registerSubclass ( ClassTranslator < ? extends P > translator ) { byDiscriminator . put ( translator . getDiscriminator ( ) , translator ) ; Subclass sub = translator . getDeclaredClass ( ) . getAnnotation ( Subclass . class ) ; for ( String alsoLoad : sub . alsoLoad ( ) ) byDiscriminator . put ( alsoLoad , translator ) ; byClass . put ( translator . getDeclaredClass ( ) , translator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the component type of a Collection . [CODESPLIT] public static Type getCollectionComponentType ( Type collectionType ) { Type componentType = GenericTypeReflector . getTypeParameter ( collectionType , Collection . class . getTypeParameters ( ) [ 0 ] ) ; if ( componentType == null ) // if it was a raw type, just assume Object return Object . class ; else return componentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the key type of a Map . [CODESPLIT] public static Type getMapKeyType ( Type mapType ) { Type componentType = GenericTypeReflector . getTypeParameter ( mapType , Map . class . getTypeParameters ( ) [ 0 ] ) ; if ( componentType == null ) // if it was a raw type, just assume Object return Object . class ; else return componentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive method which reverses the path into a ForwardPath . [CODESPLIT] public static ForwardPath of ( Path path ) { ForwardPath next = new ForwardPath ( path ) ; if ( path . getPrevious ( ) == Path . root ( ) ) return next ; ForwardPath previous = of ( path . getPrevious ( ) ) ; previous . next = next ; return previous ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the complete path in this chain typically for error messages or debugging [CODESPLIT] public Path getFinalPath ( ) { ForwardPath here = this ; while ( here . next != null ) here = here . next ; return here . getPath ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the full x . y . z string [CODESPLIT] public String toPathString ( ) { if ( this == ROOT ) { return \"\" ; } else { StringBuilder builder = new StringBuilder ( ) ; toPathString ( builder ) ; return builder . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ROOT is 0 top level Entity properties are 1 embedded things are higher . [CODESPLIT] public int depth ( ) { int depth = 0 ; Path here = this ; while ( here != ROOT ) { depth ++ ; here = here . previous ; } return depth ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < E > Result < Key < E > > entity ( final E entity ) { final Result < Map < Key < E > , E > > base = this . < E > entities ( Collections . singleton ( entity ) ) ; return new ResultWrapper < Map < Key < E > , E > , Key < E > > ( base ) { private static final long serialVersionUID = 1L ; @ Override protected Key < E > wrap ( final Map < Key < E > , E > base ) { return base . keySet ( ) . iterator ( ) . next ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < E > Result < Map < Key < E > , E > > entities ( final E ... entities ) { return this . entities ( Arrays . asList ( entities ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < E > Result < Map < Key < E > , E > > entities ( final Iterable < E > entities ) { return ofy . createWriteEngine ( ) . save ( entities ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public FullEntity < ? > toEntity ( final Object pojo ) { if ( pojo instanceof FullEntity < ? > ) { return ( FullEntity < ? > ) pojo ; } else { @ SuppressWarnings ( \"unchecked\" ) final EntityMetadata < Object > meta = ( EntityMetadata < Object > ) ofy . factory ( ) . getMetadata ( pojo . getClass ( ) ) ; return meta . save ( pojo , new SaveContext ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the Buckets for the specified keys . A bucket is built around an IdentifiableValue so you can putAll () them without the risk of overwriting other threads changes . Buckets also hide the underlying details of storage for negative empty and uncacheable results . < / p > [CODESPLIT] public Map < Key , Bucket > getAll ( final Iterable < Key > keys ) { final Map < Key , Bucket > result = new HashMap <> ( ) ; // Sort out the ones that are uncacheable\r final Set < Key > potentials = new HashSet <> ( ) ; for ( final Key key : keys ) { if ( ! cacheControl . isCacheable ( key ) ) result . put ( key , new Bucket ( key ) ) ; else potentials . add ( key ) ; } Map < Key , IdentifiableValue > casValues ; try { casValues = this . memcache . getIdentifiables ( potentials ) ; } catch ( Exception ex ) { // This should really only be a problem if the serialization format for an Entity changes,\r // or someone put a badly-serializing object in the cache underneath us.\r log . warn ( \"Error obtaining cache for \" + potentials , ex ) ; casValues = new HashMap <> ( ) ; } // Now create the remaining buckets\r for ( final Key key : keys ) { final IdentifiableValue casValue = casValues . get ( key ) ; // Might be null, which means uncacheable\r final Bucket buck = new Bucket ( key , casValue ) ; result . put ( key , buck ) ; if ( buck . isEmpty ( ) ) this . stats . recordMiss ( buck . getKey ( ) ) ; else this . stats . recordHit ( buck . getKey ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update a set of buckets with new values . If collisions occur resets the memcache value to null . [CODESPLIT] public void putAll ( final Collection < Bucket > updates ) { final Set < Key > good = this . cachePutIfUntouched ( updates ) ; if ( good . size ( ) == updates . size ( ) ) return ; // Figure out which ones were bad\r final List < Key > bad = updates . stream ( ) . map ( Bucket :: getKey ) . filter ( key -> ! good . contains ( key ) ) . collect ( Collectors . toList ( ) ) ; if ( ! bad . isEmpty ( ) ) { // So we had some collisions.  We need to reset these back to null, but do it in a safe way - if we\r // blindly set null something already null, it will break any putIfUntouched() which saw the first null.\r // This could result in write contention starving out a real write.  The solution is to only reset things\r // that are not already null.\r final Map < Key , Object > cached = this . cacheGetAll ( bad ) ; // Remove the stuff we don't care about\r cached . values ( ) . removeIf ( Objects :: isNull ) ; this . empty ( cached . keySet ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Revert a set of keys to the empty state . Will loop on this several times just in case the memcache write fails - we don t want to leave the cache in a nasty state . [CODESPLIT] public void empty ( final Iterable < Key > keys ) { final Map < Key , Object > updates = new HashMap <> ( ) ; for ( final Key key : keys ) if ( cacheControl . isCacheable ( key ) ) updates . put ( key , null ) ; this . memcacheWithRetry . putAll ( updates ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put buckets in the cache checking for cacheability and collisions . [CODESPLIT] private Set < Key > cachePutIfUntouched ( final Iterable < Bucket > buckets ) { final Map < Key , CasPut > payload = new HashMap <> ( ) ; final Set < Key > successes = new HashSet <> ( ) ; for ( final Bucket buck : buckets ) { if ( ! buck . isCacheable ( ) ) { successes . add ( buck . getKey ( ) ) ; continue ; } final Integer expirySeconds = cacheControl . getExpirySeconds ( buck . getKey ( ) ) ; if ( expirySeconds == null ) { successes . add ( buck . getKey ( ) ) ; continue ; } payload . put ( buck . getKey ( ) , new CasPut ( buck . identifiableValue , buck . getNextToStore ( ) , expirySeconds ) ) ; } successes . addAll ( this . memcache . putIfUntouched ( payload ) ) ; return successes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bulk get on keys getting the raw objects [CODESPLIT] private Map < Key , Object > cacheGetAll ( final Collection < Key > keys ) { try { return this . memcache . getAll ( keys ) ; } catch ( Exception ex ) { // Some sort of serialization error, just wipe out the values\r log . warn ( \"Error fetching values from memcache, deleting keys\" , ex ) ; this . memcache . deleteAll ( keys ) ; return new HashMap <> ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Basically a list comprehension of the keys for convenience . [CODESPLIT] public static Set < Key > keysOf ( final Collection < Bucket > buckets ) { return buckets . stream ( ) . map ( Bucket :: getKey ) . collect ( Collectors . toSet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively go through the class hierarchy looking for the idMeta and parentMeta fields . [CODESPLIT] private void findKeyFields ( Class < ? > inspect , CreateContext ctx , Path path ) { if ( inspect == Object . class ) return ; findKeyFields ( inspect . getSuperclass ( ) , ctx , path ) ; for ( Field field : inspect . getDeclaredFields ( ) ) { if ( field . getAnnotation ( Id . class ) != null ) { if ( this . idMeta != null ) throw new IllegalStateException ( \"Multiple @Id fields in the class hierarchy of \" + clazz . getName ( ) ) ; if ( ( field . getType ( ) != Long . class ) && ( field . getType ( ) != long . class ) && ( field . getType ( ) != String . class ) ) throw new IllegalStateException ( \"@Id field '\" + field . getName ( ) + \"' in \" + inspect . getName ( ) + \" must be of type Long, long, or String\" ) ; Property prop = new FieldProperty ( ctx . getFactory ( ) , clazz , field ) ; Translator < Object , Object > translator = ctx . getTranslator ( new TypeKey <> ( prop ) , ctx , path . extend ( prop . getName ( ) ) ) ; this . idMeta = new PropertyPopulator <> ( prop , translator ) ; } else if ( field . getAnnotation ( Parent . class ) != null ) { if ( this . parentMeta != null ) throw new IllegalStateException ( \"Multiple @Parent fields in the class hierarchy of \" + clazz . getName ( ) ) ; if ( ! isAllowedParentFieldType ( field . getType ( ) ) ) throw new IllegalStateException ( \"@Parent fields must be Ref<?>, Key<?>, or datastore Key. Illegal parent: \" + field ) ; Property prop = new FieldProperty ( ctx . getFactory ( ) , clazz , field ) ; Translator < Object , Object > translator = ctx . getTranslator ( new TypeKey <> ( prop ) , ctx , path . extend ( prop . getName ( ) ) ) ; this . parentMeta = new PropertyPopulator <> ( prop , translator ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the key ( from the container ) onto the POJO id / parent fields . Also doublechecks to make sure that the key fields aren t present in the container which means we re in a very bad state . [CODESPLIT] public void setKey ( final P pojo , final FullEntity < ? > container , final LoadContext ctx , final Path containerPath ) { if ( container . contains ( idMeta . getProperty ( ) . getName ( ) ) ) throw new IllegalStateException ( \"Datastore has a property present for the id field \" + idMeta . getProperty ( ) + \" which would conflict with the key: \" + container ) ; if ( parentMeta != null && container . contains ( parentMeta . getProperty ( ) . getName ( ) ) ) throw new IllegalStateException ( \"Datastore has a property present for the parent field \" + parentMeta . getProperty ( ) + \" which would conflict with the key: \" + container ) ; this . setKey ( pojo , container . getKey ( ) , ctx , containerPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the key onto the POJO id / parent fields [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void setKey ( final P pojo , final IncompleteKey key , final LoadContext ctx , final Path containerPath ) { if ( ! clazz . isAssignableFrom ( pojo . getClass ( ) ) ) throw new IllegalArgumentException ( \"Trying to use metadata for \" + clazz . getName ( ) + \" to set key of \" + pojo . getClass ( ) . getName ( ) ) ; // If no key, don't need to do anything if ( key == null ) return ; idMeta . setValue ( pojo , Keys . getIdValue ( key ) , ctx , containerPath ) ; final com . google . cloud . datastore . Key parentKey = key . getParent ( ) ; if ( parentKey != null ) { if ( this . parentMeta == null ) throw new IllegalStateException ( \"Loaded Entity has parent but \" + clazz . getName ( ) + \" has no @Parent\" ) ; parentMeta . setValue ( pojo , ( Value ) KeyValue . of ( parentKey ) , ctx , containerPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the key on a container from the POJO . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < K extends IncompleteKey > void setKey ( final FullEntity . Builder < K > container , final P pojo ) { final IncompleteKey rawKey = getIncompleteKey ( pojo ) ; if ( ! ( rawKey instanceof com . google . cloud . datastore . Key ) ) { // it's incomplete, make sure we can save it Preconditions . checkState ( isIdNumeric ( ) , \"Cannot save an entity with a null String @Id: %s\" , pojo ) ; } container . setKey ( ( K ) rawKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key composed of the relevant id and parent fields in the object . [CODESPLIT] public IncompleteKey getIncompleteKey ( final P pojo ) { log . trace ( \"Getting key from {}\" , pojo ) ; if ( ! clazz . isAssignableFrom ( pojo . getClass ( ) ) ) throw new IllegalArgumentException ( \"Trying to use metadata for \" + clazz . getName ( ) + \" to get key of \" + pojo . getClass ( ) . getName ( ) ) ; final Object id = getId ( pojo ) ; final com . google . cloud . datastore . Key parent = getParentRaw ( pojo ) ; if ( id == null ) return factory . keys ( ) . createRawIncomplete ( parent , kind ) ; else return factory . keys ( ) . createRawAny ( parent , kind , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a key composed of the relevant id and parent fields in the object . [CODESPLIT] public com . google . cloud . datastore . Key getCompleteKey ( final P pojo ) { final com . google . cloud . datastore . IncompleteKey key = getIncompleteKey ( pojo ) ; if ( key instanceof com . google . cloud . datastore . Key ) return ( com . google . cloud . datastore . Key ) key ; else throw new IllegalArgumentException ( \"You cannot create a Key for an object with a null @Id. Object was \" + pojo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the numeric id field [CODESPLIT] public void setLongId ( P pojo , Long id ) { if ( ! clazz . isAssignableFrom ( pojo . getClass ( ) ) ) throw new IllegalArgumentException ( \"Trying to use metadata for \" + clazz . getName ( ) + \" to set key of \" + pojo . getClass ( ) . getName ( ) ) ; this . idMeta . getProperty ( ) . set ( pojo , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of the [CODESPLIT] private com . google . cloud . datastore . Key getParentRaw ( P pojo ) { if ( parentMeta == null ) return null ; final Value < Object > value = parentMeta . getValue ( pojo , new SaveContext ( ) , Path . root ( ) ) ; return ( value == null || value . getType ( ) == ValueType . NULL ) ? null : ( com . google . cloud . datastore . Key ) value . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively register this subclass with all the superclass translators . This works because we cache translators uniquely in the factory . [CODESPLIT] private void registerSubclass ( final ClassTranslator < P > translator , final TypeKey < ? super P > superclassTypeKey , final CreateContext ctx , final Path path ) { if ( superclassTypeKey . getTypeAsClass ( ) == Object . class ) return ; @ SuppressWarnings ( \"unchecked\" ) final ClassTranslator < ? super P > superTranslator = create ( ( TypeKey ) superclassTypeKey , ctx , path ) ; superTranslator . registerSubclass ( translator ) ; registerSubclass ( translator , new TypeKey <> ( superclassTypeKey . getTypeAsClass ( ) . getSuperclass ( ) ) , ctx , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a type of class <tt > clazz< / tt > with <tt > arguments< / tt > as type arguments . <p > For example : <tt > parameterizedClass ( Map . class Integer . class String . class ) < / tt > returns the type <tt > Map&lt ; Integer String&gt ; < / tt > . [CODESPLIT] public static Type parameterizedClass ( Class < ? > clazz , Type ... arguments ) { return parameterizedInnerClass ( null , clazz , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a type of <tt > clazz< / tt > nested in <tt > owner< / tt > . [CODESPLIT] public static Type innerClass ( Type owner , Class < ? > clazz ) { return parameterizedInnerClass ( owner , clazz , ( Type [ ] ) null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a type of <tt > clazz< / tt > with <tt > arguments< / tt > as type arguments nested in <tt > owner< / tt > . <p > In the ideal case this returns a { @link ParameterizedType } with all generic information in it . If some type arguments are missing or if the resulting type simply doesn t need any type parameters it returns the raw <tt > clazz< / tt > . Note that types with some parameters specified and others not don t exist in Java . <p > If the caller does not know the exact <tt > owner< / tt > type or <tt > arguments< / tt > <tt > null< / tt > should be given ( or { @link #parameterizedClass ( Class Type ... ) } or { @link #innerClass ( Type Class ) } could be used ) . If they are not needed ( non - generic owner and / or <tt > clazz< / tt > has no type parameters ) they will be filled in automatically . If they are needed but are not given the raw <tt > clazz< / tt > is returned . <p > The specified <tt > owner< / tt > may be any subtype of <tt > clazz . getDeclaringClass () < / tt > . It is automatically converted into the right parameterized version of the declaring class . If <tt > clazz< / tt > is a <tt > static< / tt > ( nested ) class the owner is not used . [CODESPLIT] public static Type parameterizedInnerClass ( Type owner , Class < ? > clazz , Type ... arguments ) { // never allow an owner on a class that doesn't have one if ( clazz . getDeclaringClass ( ) == null && owner != null ) { throw new IllegalArgumentException ( \"Cannot specify an owner type for a top level class\" ) ; } Type realOwner = transformOwner ( owner , clazz ) ; if ( arguments == null ) { if ( clazz . getTypeParameters ( ) . length == 0 ) { // no arguments known, but no needed so just use an empty argument list. // (we can still end up with a generic type if the owner is generic) arguments = new Type [ 0 ] ; } else { // missing type arguments, return the raw type return clazz ; } } else { if ( arguments . length != clazz . getTypeParameters ( ) . length ) { throw new IllegalArgumentException ( \"Incorrect number of type arguments for [\" + clazz + \"]: \" + \"expected \" + clazz . getTypeParameters ( ) . length + \", but got \" + arguments . length ) ; } } // if the class and its owner simply have no parameters at all, this is not a parameterized type if ( ! GenericTypeReflector . isMissingTypeParameters ( clazz ) ) { return clazz ; } // if the owner type is missing type parameters and clazz is non-static, this is a raw type if ( realOwner != null && ! Modifier . isStatic ( clazz . getModifiers ( ) ) && GenericTypeReflector . isMissingTypeParameters ( realOwner ) ) { return clazz ; } ParameterizedType result = new ParameterizedTypeImpl ( clazz , arguments , realOwner ) ; checkParametersWithinBound ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the type arguments of the given type are within the bounds declared on the type parameters . Only the type arguments of the type itself are checked the possible owner type is assumed to be valid . <p > It does not follow the checks defined in the <a href = http : // java . sun . com / docs / books / jls / third_edition / html / typesValues . html#4 . 5 > JLS< / a > because there are several problems with those ( see http : // stackoverflow . com / questions / 7003009 for one ) . Instead this applies some intuition and follows what Java compilers seem to do . [CODESPLIT] private static void checkParametersWithinBound ( ParameterizedType type ) { Type [ ] arguments = type . getActualTypeArguments ( ) ; TypeVariable < ? > [ ] typeParameters = ( ( Class < ? > ) type . getRawType ( ) ) . getTypeParameters ( ) ; // a map of type arguments in the type, to fill in variables in the bounds  VarMap varMap = new VarMap ( type ) ; // for every bound on every parameter for ( int i = 0 ; i < arguments . length ; i ++ ) { for ( Type bound : typeParameters [ i ] . getBounds ( ) ) { // replace type variables in the bound by their value Type replacedBound = varMap . map ( bound ) ; if ( arguments [ i ] instanceof WildcardType ) { WildcardType wildcardTypeParameter = ( WildcardType ) arguments [ i ] ; // Check if a type satisfying both the bounds of the variable and of the wildcard could exist // upper bounds must not be mutually exclusive for ( Type wildcardUpperBound : wildcardTypeParameter . getUpperBounds ( ) ) { if ( ! couldHaveCommonSubtype ( replacedBound , wildcardUpperBound ) ) { throw new TypeArgumentNotInBoundException ( arguments [ i ] , typeParameters [ i ] , bound ) ; } } // a lowerbound in the wildcard must satisfy every upperbound  for ( Type wildcardLowerBound : wildcardTypeParameter . getLowerBounds ( ) ) { if ( ! GenericTypeReflector . isSuperType ( replacedBound , wildcardLowerBound ) ) { throw new TypeArgumentNotInBoundException ( arguments [ i ] , typeParameters [ i ] , bound ) ; } } } else { if ( ! GenericTypeReflector . isSuperType ( replacedBound , arguments [ i ] ) ) { throw new TypeArgumentNotInBoundException ( arguments [ i ] , typeParameters [ i ] , bound ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the intersection of two types is not empty . [CODESPLIT] private static boolean couldHaveCommonSubtype ( Type type1 , Type type2 ) { // this is an optimistically naive implementation. // if they are parameterized types their parameters need to be checked,... // so we're just a bit too lenient here Class < ? > erased1 = GenericTypeReflector . erase ( type1 ) ; Class < ? > erased2 = GenericTypeReflector . erase ( type2 ) ; // if they are both classes if ( ! erased1 . isInterface ( ) && ! erased2 . isInterface ( ) ) { // then one needs to be a subclass of another if ( ! erased1 . isAssignableFrom ( erased2 ) && ! erased2 . isAssignableFrom ( erased1 ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the given owner type into an appropriate one when constructing a parameterized type . [CODESPLIT] private static Type transformOwner ( Type givenOwner , Class < ? > clazz ) { if ( givenOwner == null ) { // be lenient: if this is an inner class but no owner was specified, assume a raw owner type // (or if there is no owner just return null) return clazz . getDeclaringClass ( ) ; } else { // If the specified owner is not of the declaring class' type, but instead a subtype, // transform it into the declaring class with the exact type parameters. // For example with \"class StringOuter extends GenericOuter<String>\", transform // \"StringOuter.Inner\" into \"GenericOuter<String>.Inner\", just like the Java compiler does. Type transformedOwner = GenericTypeReflector . getExactSuperType ( givenOwner , clazz . getDeclaringClass ( ) ) ; if ( transformedOwner == null ) { // null means it's not a supertype throw new IllegalArgumentException ( \"Given owner type [\" + givenOwner + \"] is not appropriate for [\" + clazz + \"]: it should be a subtype of \" + clazz . getDeclaringClass ( ) ) ; } if ( Modifier . isStatic ( clazz . getModifiers ( ) ) ) { // for a static inner class, the owner shouldn't have type parameters return GenericTypeReflector . erase ( transformedOwner ) ; } else { return transformedOwner ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a wildcard type with an upper bound . <p > For example <tt > wildcardExtends ( String . class ) < / tt > returns the type <tt > ? extends String< / tt > . [CODESPLIT] public static WildcardType wildcardExtends ( Type upperBound ) { if ( upperBound == null ) { throw new NullPointerException ( ) ; } return new WildcardTypeImpl ( new Type [ ] { upperBound } , new Type [ ] { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a wildcard type with a lower bound . <p > For example <tt > wildcardSuper ( String . class ) < / tt > returns the type <tt > ? super String< / tt > . [CODESPLIT] public static WildcardType wildcardSuper ( Type lowerBound ) { if ( lowerBound == null ) { throw new NullPointerException ( ) ; } return new WildcardTypeImpl ( new Type [ ] { Object . class } , new Type [ ] { lowerBound } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks not only the listed annotations but also annotations on the class . [CODESPLIT] public < A extends Annotation > A getAnnotationAnywhere ( Class < A > annotationType ) { A anno = getAnnotation ( annotationType ) ; if ( anno == null ) { Class < ? > clazz = ( Class < ? > ) GenericTypeReflector . erase ( type ) ; return clazz . getAnnotation ( annotationType ) ; } else { return anno ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add / overwrite a SV . [CODESPLIT] public void add ( final Key < ? > key , final SessionValue < ? > value ) { if ( log . isTraceEnabled ( ) ) log . trace ( \"Adding to session: {} -> {}\" , key , value . getResult ( ) ) ; map . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method [CODESPLIT] public void addValue ( final Key < ? > key , final Object value ) { add ( key , new SessionValue <> ( new ResultNow <> ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all entries in the other session to this one [CODESPLIT] public void addAll ( final Session other ) { if ( log . isTraceEnabled ( ) ) log . trace ( \"Adding all values to session: {}\" , other . map . keySet ( ) ) ; map . putAll ( other . map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Eliminate any deferred operations against the entity . Used when an explicit save ( or delete ) was executed against the key so we no longer need the deferred operation . [CODESPLIT] public void undefer ( final Object keyOrEntity ) { if ( keyOrEntity instanceof Key < ? > ) { operations . remove ( ( Key < ? > ) keyOrEntity ) ; } else if ( keyOrEntity instanceof com . google . cloud . datastore . Key ) { operations . remove ( Key . create ( ( com . google . cloud . datastore . Key ) keyOrEntity ) ) ; } else if ( factory ( ) . keys ( ) . requiresAutogeneratedId ( keyOrEntity ) ) { // note might be FullEntity without complete key autogeneratedIdSaves . remove ( keyOrEntity ) ; } else { final Key < ? > key = factory ( ) . keys ( ) . keyOf ( keyOrEntity ) ; operations . remove ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the result possibly from the session putting it in the session if necessary . Also will recursively prepare the session with [CODESPLIT] public < T > Result < T > load ( final Key < T > key ) { if ( key == null ) throw new NullPointerException ( \"You tried to load a null key!\" ) ; final Result < T > result = round . get ( key ) ; // If we are running a transaction, enlist the result so that it gets processed on commit even\r // if the client never materializes the result.\r if ( ofy . getTransaction ( ) != null ) ( ( PrivateAsyncTransaction ) ofy . getTransaction ( ) ) . enlist ( result ) ; // Now check to see if we need to recurse and add our parent(s) to the round\r if ( key . getParent ( ) != null ) { final KeyMetadata < ? > meta = ofy . factory ( ) . keys ( ) . getMetadata ( key ) ; // Is it really possible for this to be null?\r if ( meta != null ) { if ( meta . shouldLoadParent ( loadArrangement ) ) { load ( key . getParent ( ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts asychronous fetching of the batch . [CODESPLIT] public void execute ( ) { if ( round . needsExecution ( ) ) { Round old = round ; round = old . next ( ) ; old . execute ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Ref for the key and maybe start a load operation depending on current load groups . [CODESPLIT] public < T > Ref < T > makeRef ( final Key < ? > rootEntity , final LoadConditions loadConditions , final Key < T > key ) { final Ref < T > ref = new LiveRef <> ( key , ofy ) ; if ( shouldLoad ( loadConditions ) ) { load ( key ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously translate raw to processed ; might produce successive load operations as refs are filled in [CODESPLIT] public Result < Map < Key < ? > , Object > > translate ( final Result < Map < com . google . cloud . datastore . Key , Entity > > raw ) { return new ResultCache < Map < Key < ? > , Object > > ( ) { /** */ private LoadContext ctx ; /** */ @ Override public Map < Key < ? > , Object > nowUncached ( ) { final Map < Key < ? > , Object > result = new HashMap <> ( raw . now ( ) . size ( ) * 2 ) ; ctx = new LoadContext ( LoadEngine . this ) ; for ( final Entity ent : raw . now ( ) . values ( ) ) { final Key < ? > key = Key . create ( ent . getKey ( ) ) ; final Object entity = load ( ent , ctx ) ; result . put ( key , entity ) ; } return result ; } /**\r\n\t\t\t * We need to execute the done() after the translated value has been set, otherwise we\r\n\t\t\t * can produce an infinite recursion problem.\r\n\t\t\t */ @ Override protected void postExecuteHook ( ) { ctx . done ( ) ; ctx = null ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the keys from the async datastore using the current transaction context [CODESPLIT] public Result < Map < com . google . cloud . datastore . Key , Entity > > fetch ( Set < com . google . cloud . datastore . Key > keys ) { log . debug ( \"Fetching {} keys: {}\" , keys . size ( ) , keys ) ; final Future < Map < com . google . cloud . datastore . Key , Entity > > fut = datastore . get ( keys , readOptions . toArray ( new ReadOption [ readOptions . size ( ) ] ) ) ; return ResultAdapter . create ( fut ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a datastore entity into a typed pojo object [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T load ( final BaseEntity < com . google . cloud . datastore . Key > ent , final LoadContext ctx ) { if ( ent == null ) return null ; final EntityMetadata < T > meta = ofy . factory ( ) . getMetadata ( ent . getKey ( ) . getKind ( ) ) ; if ( meta == null ) return ( T ) ent ; else return meta . load ( ent , ctx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenince method that creates a composite filter with any existing filter ( if present ) [CODESPLIT] public QueryDef andFilter ( final Filter addFilter ) { return filter ( this . filter == null ? addFilter : CompositeFilter . and ( this . filter , addFilter ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public DeleteIds parent ( final Object keyOrEntity ) { final Key < ? > parentKey = factory ( ) . keys ( ) . anythingToKey ( keyOrEntity ) ; return new DeleteTypeImpl ( deleter , type , parentKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Result < Void > id ( final String id ) { return ids ( Collections . singleton ( id ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Result < Void > ids ( final String ... ids ) { return ids ( Arrays . asList ( ids ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < S > Result < Void > ids ( final Iterable < S > ids ) { return this . deleter . keys ( factory ( ) . keys ( ) . createKeys ( parent , type , ids ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Map < K , V > get ( ) throws InterruptedException , ExecutionException { if ( this . pending != null ) { this . loaded . putAll ( this . pending . get ( ) ) ; this . pending = null ; } return this . loaded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Map < K , V > get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { if ( this . pending != null ) { this . loaded . putAll ( this . pending . get ( timeout , unit ) ) ; this . pending = null ; } return this . loaded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the Key<T > given an object that might be a Key Key<T > or entity . < / p > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > Key < T > anythingToKey ( final Object keyOrEntity ) { if ( keyOrEntity instanceof Key < ? > ) return ( Key < T > ) keyOrEntity ; else if ( keyOrEntity instanceof com . google . cloud . datastore . Key ) return Key . create ( ( com . google . cloud . datastore . Key ) keyOrEntity ) ; else if ( keyOrEntity instanceof Ref ) return ( ( Ref < T > ) keyOrEntity ) . key ( ) ; else if ( keyOrEntity instanceof FullEntity < ? > ) return Key . create ( getKey ( ( FullEntity < ? > ) keyOrEntity ) ) ; else return keyOf ( ( T ) keyOrEntity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the raw datstore Key given an object that might be a Key Key<T > or entity . < / p > [CODESPLIT] public com . google . cloud . datastore . Key anythingToRawKey ( final Object keyOrEntity ) { if ( keyOrEntity instanceof com . google . cloud . datastore . Key ) return ( com . google . cloud . datastore . Key ) keyOrEntity ; else if ( keyOrEntity instanceof Key < ? > ) return ( ( Key < ? > ) keyOrEntity ) . getRaw ( ) ; else if ( keyOrEntity instanceof Ref ) return ( ( Ref < ? > ) keyOrEntity ) . key ( ) . getRaw ( ) ; else if ( keyOrEntity instanceof FullEntity < ? > ) return getKey ( ( FullEntity < ? > ) keyOrEntity ) ; else return rawKeyOf ( keyOrEntity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Key from a Long or String id [CODESPLIT] public com . google . cloud . datastore . Key createRawAny ( final com . google . cloud . datastore . Key parent , final String kind , final Object id ) { if ( id instanceof String ) return createRaw ( parent , kind , ( String ) id ) ; else if ( id instanceof Long ) return createRaw ( parent , kind , ( Long ) id ) ; else throw new IllegalArgumentException ( \"id '\" + id + \"' must be String or Long\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Key<? > from a Long or String id [CODESPLIT] public < T > Key < T > createKeyAny ( final Key < ? > parent , final Class < T > kind , final Object id ) { if ( id instanceof String ) return createKey ( parent , kind , ( String ) id ) ; else if ( id instanceof Long ) return createKey ( parent , kind , ( Long ) id ) ; else throw new IllegalArgumentException ( \"id '\" + id + \"' must be String or Long\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Null - safe extraction of the raw key [CODESPLIT] public static com . google . cloud . datastore . Key raw ( final Key < ? > key ) { return key == null ? null : key . getRaw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a list of Key<? > s [CODESPLIT] public < T > List < Key < T > > createKeys ( final Key < ? > parent , final Class < T > kind , final Iterable < ? > ids ) { return StreamSupport . stream ( ids . spliterator ( ) , false ) . map ( id -> createKeyAny ( parent , kind , id ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the String or Long id from the key as a Value or null if incomplete [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < S > Value < S > getIdValue ( final IncompleteKey key ) { if ( key instanceof com . google . cloud . datastore . Key ) { final com . google . cloud . datastore . Key completeKey = ( com . google . cloud . datastore . Key ) key ; if ( completeKey . hasId ( ) ) return ( Value < S > ) LongValue . of ( completeKey . getId ( ) ) ; else return ( Value < S > ) StringValue . of ( completeKey . getName ( ) ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Understands both the legacy format ag1zfnZvb2Rvb2R5bmUwcgcLEgFCGAEM and new format providing the key either way . [CODESPLIT] @ SneakyThrows public static com . google . cloud . datastore . Key fromUrlSafe ( final String urlSafeKey ) { if ( urlSafeKey . startsWith ( \"a\" ) ) { return KeyFormat . INSTANCE . parseOldStyleAppEngineKey ( urlSafeKey ) ; } else { return com . google . cloud . datastore . Key . fromUrlSafe ( urlSafeKey ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This version goes back to life without a transaction but preserves current options . We use the session from the parent ie life before transactions . [CODESPLIT] @ Override public ObjectifyImpl transactionless ( final ObjectifyImpl parent ) { return parent . makeNew ( next -> new TransactorNo ( next , parentTransactor . getSession ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < R > R execute ( final ObjectifyImpl parent , final TxnType txnType , final Work < R > work ) { switch ( txnType ) { case MANDATORY : case REQUIRED : case SUPPORTS : return work . run ( ) ; case NOT_SUPPORTED : return transactionless ( parent , work ) ; case NEVER : throw new IllegalStateException ( \"MANDATORY transaction but no transaction present\" ) ; case REQUIRES_NEW : return transactNew ( parent , Transactor . DEFAULT_TRY_LIMIT , work ) ; default : throw new IllegalStateException ( \"Impossible, some unknown txn type\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < R > R transact ( final ObjectifyImpl parent , final Work < R > work ) { return work . run ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We need to make sure the parentSession is the transactionless session not the session for our transaction . This gives proper transaction isolation . [CODESPLIT] @ Override public < R > R transactNew ( final ObjectifyImpl parent , final int limitTries , final Work < R > work ) { return transactionless ( parent ) . transactNew ( limitTries , work ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public Query < T > filter ( final Filter filter ) { final QueryImpl < T > q = createQuery ( ) ; q . addFilter ( filter ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Query < T > order ( String condition ) { QueryImpl < T > q = createQuery ( ) ; q . addOrder ( condition ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public LoadResult < T > id ( final String id ) { return loader . key ( this . makeKey ( id ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Map < Long , T > ids ( final Long ... ids ) { return ids ( Arrays . asList ( ids ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Map < String , T > ids ( final String ... ids ) { return ids ( Arrays . asList ( ids ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < S > Map < S , T > ids ( final Iterable < S > ids ) { final Map < Key < T > , S > keymap = new LinkedHashMap <> ( ) ; for ( final S id : ids ) keymap . put ( this . makeKey ( id ) , id ) ; final Map < Key < T > , T > loaded = loader . keys ( keymap . keySet ( ) ) ; return ResultProxy . create ( Map . class , new ResultCache < Map < S , T > > ( ) { @ Override protected Map < S , T > nowUncached ( ) { final Map < S , T > proper = new LinkedHashMap <> ( loaded . size ( ) * 2 ) ; for ( final Map . Entry < Key < T > , T > entry : loaded . entrySet ( ) ) proper . put ( keymap . get ( entry . getKey ( ) ) , entry . getValue ( ) ) ; return proper ; } } ) ; } /**\r\n\t * Make a key for the given id, which could be either string or long\r\n\t */ private < T > Key < T > makeKey ( final Object id ) { final com . google . cloud . datastore . Key key = factory ( ) . keys ( ) . createRawAny ( Keys . raw ( this . parent ) , kind , id ) ; return Key . create ( key ) ; } /* (non-Javadoc)\r\n\t * @see com.googlecode.objectify.cmd.LoadType#parent(java.lang.Object)\r\n\t */ @ Override public LoadIds < T > parent  ( final Object keyOrEntity ) { final Key < T > parentKey = factory ( ) . keys ( ) . anythingToKey ( keyOrEntity ) ; return new LoadTypeImpl <> ( loader , kind , type , parentKey ) ; } /** */ private ObjectifyFactory factory  ( ) { return loader . getObjectifyImpl ( ) . factory ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < R > R execute ( final ObjectifyImpl parent , final TxnType txnType , final Work < R > work ) { switch ( txnType ) { case MANDATORY : throw new IllegalStateException ( \"MANDATORY transaction but no transaction present\" ) ; case NOT_SUPPORTED : case NEVER : case SUPPORTS : return work . run ( ) ; case REQUIRED : case REQUIRES_NEW : return transact ( parent , work ) ; default : throw new IllegalStateException ( \"Impossible, some unknown txn type\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < R > R transact ( final ObjectifyImpl parent , final Work < R > work ) { return this . transactNew ( parent , DEFAULT_TRY_LIMIT , work ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public < R > R transactNew ( final ObjectifyImpl parent , int limitTries , final Work < R > work ) { Preconditions . checkArgument ( limitTries >= 1 ) ; final int ORIGINAL_TRIES = limitTries ; while ( true ) { try { return transactOnce ( parent , work ) ; } catch ( DatastoreException ex ) { // This doesn't work because the SDK considers all transactions to be non-retryable. Objectify has always\r // assumed that transactions are idempotent and retries accordingly. So we have to explicitly check against\r // code 10, which is ABORTED. https://cloud.google.com/datastore/docs/concepts/errors\r //\t\t\t\tif (!ex.isRetryable())\r //\t\t\t\t\tthrow ex;\r // I hate this so much. Sometimes the transaction gets closed by the datastore during contention and\r // then it proceeds to freak out and 503.\r if ( Code . ABORTED . getNumber ( ) == ex . getCode ( ) || ( Code . INVALID_ARGUMENT . getNumber ( ) == ex . getCode ( ) && ex . getMessage ( ) . contains ( \"transaction closed\" ) ) ) { // Continue to retry logic\r } else { throw ex ; } if ( -- limitTries > 0 ) { log . warn ( \"Retrying {} failure for {}: {}\" , ex . getReason ( ) , work , ex ) ; log . trace ( \"Details of transaction failure\" , ex ) ; try { // Do increasing backoffs with randomness\r Thread . sleep ( Math . min ( 10000 , ( long ) ( 0.5 * Math . random ( ) + 0.5 ) * 200 * ( ORIGINAL_TRIES - limitTries + 2 ) ) ) ; } catch ( InterruptedException ignored ) { } } else { throw new DatastoreException ( ex . getCode ( ) , \"Failed retrying datastore \" + ORIGINAL_TRIES + \" times \" , ex . getReason ( ) , ex ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One attempt at executing a transaction [CODESPLIT] private < R > R transactOnce ( final ObjectifyImpl parent , final Work < R > work ) { final ObjectifyImpl txnOfy = factory . open ( parent . getOptions ( ) , next -> new TransactorYes ( next , this ) ) ; boolean committedSuccessfully = false ; try { final R result = work . run ( ) ; txnOfy . flush ( ) ; txnOfy . getTransaction ( ) . commit ( ) ; committedSuccessfully = true ; return result ; } finally { if ( txnOfy . getTransaction ( ) . isActive ( ) ) { try { txnOfy . getTransaction ( ) . rollback ( ) ; } catch ( RuntimeException ex ) { log . error ( \"Rollback failed, suppressing error\" , ex ) ; } } txnOfy . close ( ) ; if ( committedSuccessfully ) { ( ( PrivateAsyncTransaction ) txnOfy . getTransaction ( ) ) . runCommitListeners ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests whether a set of conditions match . [CODESPLIT] private boolean matches ( Object onPojo , If < ? , ? > [ ] conditions ) { if ( conditions == null ) return false ; Object value = this . get ( onPojo ) ; for ( If < ? , ? > condition : conditions ) { @ SuppressWarnings ( \"unchecked\" ) If < Object , Object > cond = ( If < Object , Object > ) condition ; if ( cond . matchesValue ( value ) ) return true ; if ( cond . matchesPojo ( onPojo ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current objectify instance associated with this ref [CODESPLIT] private Objectify ofy ( ) { // If we have an expired transaction context, we need a new context\r if ( ofy == null || ( ofy . getTransaction ( ) != null && ! ofy . getTransaction ( ) . isActive ( ) ) ) ofy = ObjectifyService . ofy ( ) ; return ofy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Might produce a caching version if caching is enabled . [CODESPLIT] public AsyncDatastore asyncDatastore ( final boolean enableGlobalCache ) { if ( this . entityMemcache != null && enableGlobalCache && this . registrar . isCacheEnabled ( ) ) return new CachingAsyncDatastore ( asyncDatastore ( ) , this . entityMemcache ) ; else return asyncDatastore ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Construct an instance of the specified type . Objectify uses this method whenever possible to create instances of entities condition classes or other types ; by overriding this method you can substitute Guice or other dependency injection mechanisms . By default it constructs with a simple no - args constructor . < / p > [CODESPLIT] @ Override public < T > T construct ( final Class < T > type ) { // We do this instead of calling newInstance directly because this lets us work around accessiblity\r final Constructor < T > ctor = TypeUtils . getNoArgConstructor ( type ) ; return TypeUtils . newInstance ( ctor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Construct a collection of the specified type and the specified size for use on a POJO field . You can override this with Guice or whatnot . < / p > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T extends Collection < ? > > T constructCollection ( final Class < T > type , final int size ) { if ( ( Class < ? > ) type == List . class || ( Class < ? > ) type == Collection . class ) return ( T ) new ArrayList <> ( size ) ; else if ( ( Class < ? > ) type == Set . class ) return ( T ) new HashSet <> ( ( int ) ( size * 1.5 ) ) ; else if ( ( Class < ? > ) type == SortedSet . class ) return ( T ) new TreeSet <> ( ) ; else return construct ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Construct a map of the specified type for use on a POJO field . You can override this with Guice or whatnot . < / p > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T extends Map < ? , ? > > T constructMap ( final Class < T > type ) { if ( ( Class < ? > ) type == Map . class ) return ( T ) new HashMap <> ( ) ; else if ( ( Class < ? > ) type == SortedMap . class ) return ( T ) new TreeMap <> ( ) ; else return construct ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Named differently so you don t accidentally use the Object form [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > EntityMetadata < T > getMetadataForEntity ( final T obj ) throws IllegalArgumentException { // Type erasure sucks\r return ( EntityMetadata < T > ) this . getMetadata ( obj . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocates a single id from the allocator for the specified kind . Safe to use in concert with the automatic generator . This is just a convenience method for allocateIds () . [CODESPLIT] public < T > Key < T > allocateId ( final Class < T > clazz ) { return allocateIds ( clazz , 1 ) . iterator ( ) . next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Preallocate multiple unique ids within the namespace of the specified entity class . These ids can be used in concert with the normal automatic allocation of ids when save () ing entities with null Long id fields . < / p > [CODESPLIT] public < T > KeyRange < T > allocateIds ( final Class < T > clazz , final int num ) { final String kind = Key . getKind ( clazz ) ; final IncompleteKey incompleteKey = datastore ( ) . newKeyFactory ( ) . setKind ( kind ) . newKey ( ) ; return allocate ( incompleteKey , num ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Preallocate a contiguous range of unique ids within the namespace of the specified entity class and the parent key . These ids can be used in concert with the normal automatic allocation of ids when put () ing entities with null Long id fields . [CODESPLIT] public < T > KeyRange < T > allocateIds ( final Object parentKeyOrEntity , final Class < T > clazz , final int num ) { final Key < ? > parent = keys ( ) . anythingToKey ( parentKeyOrEntity ) ; final String kind = Key . getKind ( clazz ) ; final IncompleteKey incompleteKey = com . google . cloud . datastore . Key . newBuilder ( parent . getRaw ( ) , kind ) . build ( ) ; return allocate ( incompleteKey , num ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocate num copies of the incompleteKey [CODESPLIT] private < T > KeyRange < T > allocate ( final IncompleteKey incompleteKey , final int num ) { final IncompleteKey [ ] allocations = new IncompleteKey [ num ] ; Arrays . fill ( allocations , incompleteKey ) ; final List < Key < T > > typedKeys = datastore ( ) . allocateId ( allocations ) . stream ( ) . map ( Key :: < T > create ) . collect ( Collectors . toList ( ) ) ; return new KeyRange <> ( typedKeys ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method to call at any time to get the current Objectify which may change depending on txn context . Normally you should use the static { [CODESPLIT] public Objectify ofy ( ) { final Deque < Objectify > stack = stacks . get ( ) ; if ( stack . isEmpty ( ) ) throw new IllegalStateException ( \"You have not started an Objectify context. You are probably missing the \" + \"ObjectifyFilter. If you are not running in the context of an http request, see the \" + \"ObjectifyService.run() method.\" ) ; return stack . getLast ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Start a scope of work . This is the outermost scope of work typically created by the ObjectifyFilter or by one of the methods on ObjectifyService . You need one of these to do anything at all . < / p > [CODESPLIT] public ObjectifyImpl open ( ) { final ObjectifyImpl objectify = new ObjectifyImpl ( this ) ; stacks . get ( ) . add ( objectify ) ; return objectify ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is only public because it is used from the impl package ; don t use this as a public API [CODESPLIT] public ObjectifyImpl open ( final ObjectifyOptions opts , final TransactorSupplier transactorSupplier ) { final ObjectifyImpl objectify = new ObjectifyImpl ( this , opts , transactorSupplier ) ; stacks . get ( ) . add ( objectify ) ; return objectify ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops context off of stack after a transaction completes . For internal housekeeping only . [CODESPLIT] public void close ( final Objectify ofy ) { final Deque < Objectify > stack = stacks . get ( ) ; if ( stack . isEmpty ( ) ) throw new IllegalStateException ( \"You have already destroyed the Objectify context.\" ) ; final Objectify popped = stack . removeLast ( ) ; assert popped == ofy : \"Mismatched objectify instances; somehow the stack was corrupted\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public Translator < Value < Object > , Object > create ( final TypeKey < Value < Object > > tk , final CreateContext ctx , final Path path ) { if ( ! tk . isAssignableTo ( Value . class ) ) return null ; return new NullSafeTranslator < Value < Object > , Object > ( ) { @ Override protected Value < Object > loadSafe ( final Value < Object > value , final LoadContext ctx , final Path path ) throws SkipException { return value ; } @ Override protected Value < Object > saveSafe ( final Value < Object > pojo , final boolean index , final SaveContext ctx , final Path path ) throws SkipException { return pojo ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Runs one unit of work making the root Objectify context available . This does not start a transaction but it makes the static ofy () method return an appropriate object . < / p > [CODESPLIT] public static < R > R run ( final Work < R > work ) { try ( Closeable closeable = begin ( ) ) { return work . run ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The datastore has a weird behavior of reordering values in a list so that indexed ones come before nonindexed ones . This can really mess up ordered lists . So if we find a heterogeneous list we need to force index everything . [CODESPLIT] public static void homogenizeIndexes ( final List < Value < ? > > list ) { if ( isIndexHomogeneous ( list ) ) return ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { final Value < ? > value = list . get ( i ) ; if ( value . excludeFromIndexes ( ) ) list . set ( i , index ( value , true ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coerces the value to be a number of the specified type ; needed because all numbers come back from the datastore as Long / Double and this screws up any type that expects something smaller . We don t need to worry about primitive types because we wrapped the class earlier . [CODESPLIT] private Number coerceNumber ( final Number value , final Class < ? > type ) { if ( type == Byte . class ) return value . byteValue ( ) ; else if ( type == Short . class ) return value . shortValue ( ) ; else if ( type == Integer . class ) return value . intValue ( ) ; else if ( type == Long . class ) return value . longValue ( ) ; else throw new IllegalArgumentException ( ) ; // should be impossible }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > filterKey ( String condition , Object value ) { QueryImpl < T > q = createQuery ( ) ; q . addFilter ( KEY_RESERVED_PROPERTY + \" \" + condition . trim ( ) , value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > ancestor ( Object keyOrEntity ) { QueryImpl < T > q = createQuery ( ) ; q . setAncestor ( keyOrEntity ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > limit ( int value ) { QueryImpl < T > q = createQuery ( ) ; q . setLimit ( value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > offset ( int value ) { QueryImpl < T > q = createQuery ( ) ; q . setOffset ( value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > startAt ( Cursor value ) { QueryImpl < T > q = createQuery ( ) ; q . setStartCursor ( value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > endAt ( Cursor value ) { QueryImpl < T > q = createQuery ( ) ; q . setEndCursor ( value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > chunk ( int value ) { QueryImpl < T > q = createQuery ( ) ; q . setChunk ( value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > hybrid ( boolean force ) { QueryImpl < T > q = createQuery ( ) ; q . setHybrid ( force ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryKeys < T > keys ( ) { QueryImpl < T > q = createQuery ( ) ; q . checkKeysOnlyOk ( ) ; return new QueryKeysImpl <> ( q ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > distinct ( boolean value ) { QueryImpl < T > q = createQuery ( ) ; q . setDistinct ( value ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public QueryImpl < T > project ( String ... fields ) { QueryImpl < T > q = createQuery ( ) ; q . addProjection ( fields ) ; return q ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Key . create ( Blah . class id ) is easier to type than new Key<Blah > ( Blah . class id ) [CODESPLIT] public static < T > Ref < T > create ( Key < T > key ) { if ( key == null ) throw new NullPointerException ( \"Cannot create a Ref from a null key\" ) ; return new LiveRef <> ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Ref from a registered pojo entity [CODESPLIT] public static < T > Ref < T > create ( T value ) { Key < T > key = Key . create ( value ) ; return create ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the entity value throwing an exception if the entity was not found . [CODESPLIT] final public T safe ( ) throws NotFoundException { T t = this . get ( ) ; if ( t == null ) throw new NotFoundException ( key ( ) ) ; else return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a value to the set associated with the key . [CODESPLIT] public boolean add ( K key , V value ) { List < V > list = this . get ( key ) ; if ( list == null ) { list = new ArrayList <> ( ) ; this . put ( key , list ) ; } return list . add ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This version also checks to see if we are done and we still need to call the trigger . If so it calls it . [CODESPLIT] @ Override public boolean isDone ( ) { boolean done = this . raw . isDone ( ) ; if ( ! triggered && done ) { this . triggered = true ; PendingFutures . removePending ( this ) ; this . trigger ( ) ; } return done ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clever enough to recognize that an empty set of conditions means Always . [CODESPLIT] public If < ? , ? > [ ] generateIfConditions ( Class < ? extends If < ? , ? > > [ ] ifClasses , Field field ) { if ( ifClasses . length == 0 ) return ALWAYS ; If < ? , ? > [ ] result = new If < ? , ? > [ ifClasses . length ] ; for ( int i = 0 ; i < ifClasses . length ; i ++ ) { Class < ? extends If < ? , ? > > ifClass = ifClasses [ i ] ; result [ i ] = this . createIf ( ifClass , field ) ; // Sanity check the generic If class types to ensure that they match the actual types of the field & entity. Type valueType = GenericTypeReflector . getTypeParameter ( ifClass , If . class . getTypeParameters ( ) [ 0 ] ) ; Class < ? > valueClass = GenericTypeReflector . erase ( valueType ) ; Type pojoType = GenericTypeReflector . getTypeParameter ( ifClass , If . class . getTypeParameters ( ) [ 1 ] ) ; Class < ? > pojoClass = GenericTypeReflector . erase ( pojoType ) ; if ( ! TypeUtils . isAssignableFrom ( valueClass , field . getType ( ) ) ) throw new IllegalStateException ( \"Cannot use If class \" + ifClass . getName ( ) + \" on \" + field + \" because you cannot assign \" + field . getType ( ) . getName ( ) + \" to \" + valueClass . getName ( ) ) ; if ( ! TypeUtils . isAssignableFrom ( pojoClass , field . getDeclaringClass ( ) ) ) throw new IllegalStateException ( \"Cannot use If class \" + ifClass . getName ( ) + \" on \" + field + \" because the containing class \" + field . getDeclaringClass ( ) . getName ( ) + \" is not compatible with \" + pojoClass . getName ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this when a load process completes . Executes anything in the batch and then executes any delayed operations . [CODESPLIT] public void done ( ) { engine . execute ( ) ; while ( deferred != null ) { final List < Runnable > runme = deferred ; deferred = null ; // reset this because it might get filled with more for ( final Runnable run : runme ) { log . trace ( \"Executing {}\" , run ) ; run . run ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Ref for the key and maybe start a load operation depending on current load groups . [CODESPLIT] public < T > Ref < T > loadRef ( Key < T > key , LoadConditions loadConditions ) { return engine . makeRef ( currentRoot , loadConditions , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delays an operation until the context is done () . Typically this is for lifecycle methods . [CODESPLIT] public void defer ( Runnable runnable ) { if ( this . deferred == null ) this . deferred = new ArrayList <> ( ) ; log . trace ( \"Deferring: {}\" , runnable ) ; this . deferred . add ( runnable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the container object which is appropriate for the specified property . Go up the chain looking for a compatible type ; the first one found is the container . If nothing found throw an exception . [CODESPLIT] public Object getContainer ( Type containerType , Path path ) { Class < ? > containerClass = GenericTypeReflector . erase ( containerType ) ; Iterator < Object > containersIt = containers . descendingIterator ( ) ; // We have always entered the current 'this' context when processing properties, so the first thing // we get will always be 'this'. So skip that and the first matching owner should be what we want. containersIt . next ( ) ; while ( containersIt . hasNext ( ) ) { Object potentialContainer = containersIt . next ( ) ; if ( containerClass . isAssignableFrom ( potentialContainer . getClass ( ) ) ) return potentialContainer ; } throw new IllegalStateException ( \"No container matching \" + containerType + \" in \" + containers + \" at path \" + path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We re just tracking statistics so we don t really need to worry about these stepping on each other ; if there s a hit or miss lost no big deal . [CODESPLIT] private Stat getStat ( String kind ) { Stat stat = this . stats . get ( kind ) ; if ( stat == null ) { stat = new Stat ( ) ; this . stats . put ( kind , stat ) ; } return stat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Quietly perform the get () on a future [CODESPLIT] public static < T > T quietGet ( Future < T > future ) { try { return future . get ( ) ; } catch ( Exception ex ) { unwrapAndThrow ( ex ) ; return null ; // just to make the compiler happy\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Properly unwraps ExecutionException throwing the relevant original cause . Otherwise RuntimeExceptions get thrown and checked exceptions get wrapped in a RuntimeException . [CODESPLIT] public static void unwrapAndThrow ( Throwable ex ) { if ( ex instanceof RuntimeException ) throw ( RuntimeException ) ex ; else if ( ex instanceof Error ) throw ( Error ) ex ; else if ( ex instanceof ExecutionException ) unwrapAndThrow ( ex . getCause ( ) ) ; else throw new UndeclaredThrowableException ( ex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coerces the value to be a number of the specified type ; needed because all numbers come back from the datastore as Long / Double and this screws up any type that expects something smaller . We don t need to worry about primitive types because we wrapped the class earlier . [CODESPLIT] private Number coerceNumber ( final Number value , final Class < ? > type ) { if ( type == Float . class ) return value . floatValue ( ) ; else if ( type == Double . class ) return value . doubleValue ( ) ; else throw new IllegalArgumentException ( ) ; // should be impossible }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the Translator appropriate for this type and annotations . May be a cached translator ; if not one will be discovered and cached . [CODESPLIT] public < P , D > Translator < P , D > get ( final TypeKey tk , final CreateContext ctx , final Path path ) { Translator < ? , ? > translator = translators . get ( tk ) ; if ( translator == null ) { translator = create ( tk , ctx , path ) ; translators . put ( tk , translator ) ; } //noinspection unchecked return ( Translator < P , D > ) translator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the translator for a root entity class [CODESPLIT] public < P > Translator < P , FullEntity < ? > > getRoot ( final Class < P > clazz ) { return get ( new TypeKey ( clazz ) , new CreateContext ( fact ) , Path . root ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a translator from scratch by going through the discovery process . [CODESPLIT] private Translator < ? , ? > create ( final TypeKey tk , final CreateContext ctx , final Path path ) { for ( final TranslatorFactory < ? , ? > trans : this . translatorFactories ) { @ SuppressWarnings ( \"unchecked\" ) final Translator < ? , ? > soFar = trans . create ( tk , ctx , path ) ; if ( soFar != null ) return soFar ; } throw new IllegalArgumentException ( \"Don't know how to translate \" + tk . getType ( ) + \" with annotations \" + Arrays . toString ( tk . getAnnotations ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the appropriate value from the container and sets it on the appropriate field of the pojo . [CODESPLIT] @ Override public void load ( final FullEntity < ? > container , final LoadContext ctx , final Path containerPath , final P intoPojo ) { try { if ( translator instanceof Recycles ) ctx . recycle ( property . get ( intoPojo ) ) ; final Value < D > value = ( translator instanceof Synthetic ) ? null : getPropertyFromContainer ( container , containerPath ) ; // will throw SkipException if property not present setValue ( intoPojo , value , ctx , containerPath ) ; } catch ( SkipException ex ) { // Irrelevant } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the relevant property from the container detecting alsoload collisions . [CODESPLIT] private Value < D > getPropertyFromContainer ( final FullEntity < ? > container , final Path containerPath ) { String foundName = null ; Value < D > value = null ; for ( String name : property . getLoadNames ( ) ) { if ( container . contains ( name ) ) { if ( foundName != null ) throw new IllegalStateException ( \"Collision trying to load field; multiple name matches for '\" + property . getName ( ) + \"' at '\" + containerPath . extend ( foundName ) + \"' and '\" + containerPath . extend ( name ) + \"'\" ) ; //noinspection unchecked value = container . getValue ( name ) ; foundName = name ; } } if ( foundName == null ) throw new SkipException ( ) ; else return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this raw datastore value on the relevant property of the pojo doing whatever translations are necessary . [CODESPLIT] public void setValue ( final Object pojo , final Value < D > value , final LoadContext ctx , final Path containerPath ) throws SkipException { final Path propertyPath = containerPath . extend ( property . getName ( ) ) ; final P loaded = translator . load ( value , ctx , propertyPath ) ; setOnPojo ( pojo , loaded , ctx , propertyPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the property on the pojo to the value . The value should already be translated . TODO : Sensitive to the value possibly being a Result<? > wrapper in which case it enqueues the set operation until the loadcontext is done . [CODESPLIT] private void setOnPojo ( final Object pojo , final P value , final LoadContext ctx , final Path path ) { if ( log . isTraceEnabled ( ) ) log . trace ( LogUtils . msg ( path , \"Setting property \" + property . getName ( ) + \" to \" + value ) ) ; property . set ( pojo , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the appropriate field value from the pojo and puts it in the container at the appropriate prop name and with the appropriate indexing . [CODESPLIT] @ Override public void save ( final P onPojo , boolean index , final SaveContext ctx , final Path containerPath , final FullEntity . Builder < ? > into ) { if ( property . isSaved ( onPojo ) ) { // Look for an override on indexing final Boolean propertyIndexInstruction = property . getIndexInstruction ( onPojo ) ; if ( propertyIndexInstruction != null ) index = propertyIndexInstruction ; @ SuppressWarnings ( \"unchecked\" ) final P value = ( P ) property . get ( onPojo ) ; try { final Path propPath = containerPath . extend ( property . getName ( ) ) ; final Value < D > propValue = translator . save ( value , index , ctx , propPath ) ; into . set ( property . getName ( ) , propValue ) ; } catch ( SkipException ex ) { // No problem, do nothing } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value for the property and translate it into datastore format . [CODESPLIT] public Value < D > getValue ( final Object pojo , final SaveContext ctx , final Path containerPath ) { @ SuppressWarnings ( \"unchecked\" ) final P value = ( P ) property . get ( pojo ) ; return translator . save ( value , false , ctx , containerPath . extend ( property . getName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write any extensions that may exist in a message . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected final < EM extends ExtendableMessage < EM > > void writeExtensions ( EM msg , JsonGenerator gen ) throws IOException { boolean openExt = false ; for ( Map . Entry < FieldDescriptor , Object > field : msg . getAllFields ( ) . entrySet ( ) ) { FieldDescriptor fd = field . getKey ( ) ; if ( fd . isExtension ( ) ) { if ( fd . isRepeated ( ) ) { List < Object > extValue = ( List < Object > ) field . getValue ( ) ; if ( ! extValue . isEmpty ( ) ) { OpenRtbJsonExtWriter < Object > extWriter = factory . getWriter ( msg . getClass ( ) , extValue . get ( 0 ) . getClass ( ) , fd . getName ( ) ) ; if ( extWriter != null ) { openExt = openExt ( gen , openExt ) ; extWriter . writeRepeated ( extValue , gen ) ; } } } else { Object extValue = field . getValue ( ) ; OpenRtbJsonExtWriter < Object > extWriter = factory . getWriter ( msg . getClass ( ) , extValue . getClass ( ) , fd . getName ( ) ) ; if ( extWriter != null ) { openExt = openExt ( gen , openExt ) ; extWriter . writeSingle ( extValue , gen ) ; } } } } if ( openExt ) { gen . writeEndObject ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a string that represents a ContentCategory s JSON name returning success status . If the factory is in strict mode the category name is validated . [CODESPLIT] protected final boolean writeContentCategory ( String cat , JsonGenerator gen ) throws IOException { if ( ! factory . isStrict ( ) || OpenRtbUtils . categoryFromName ( cat ) != null ) { gen . writeString ( cat ) ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an array of ContentCategory if not empty . [CODESPLIT] protected final void writeContentCategories ( String fieldName , List < String > cats , JsonGenerator gen ) throws IOException { if ( ! cats . isEmpty ( ) ) { gen . writeArrayFieldStart ( fieldName ) ; for ( String cat : cats ) { writeContentCategory ( cat , gen ) ; } gen . writeEndArray ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the raw snippet that was set by the bid making any transformations necessary . [CODESPLIT] public String process ( SnippetProcessorContext ctx , String snippet ) { checkNotNull ( ctx ) ; StringBuilder sb = ctx . builder ( ) ; sb . setLength ( 0 ) ; String currSnippet = snippet ; boolean processedMacros = false ; int snippetPos = 0 ; int macroPos = currSnippet . indexOf ( \"${\" ) ; while ( macroPos != - 1 ) { sb . append ( currSnippet . substring ( snippetPos , macroPos ) ) ; int macroEnd = processMacroAt ( ctx , currSnippet , macroPos ) ; if ( macroEnd == - 1 ) { sb . append ( \"${\" ) ; snippetPos = macroPos + 2 ; } else { snippetPos = macroEnd ; processedMacros = true ; } macroPos = currSnippet . indexOf ( \"${\" , snippetPos ) ; } if ( processedMacros ) { sb . append ( currSnippet , snippetPos , currSnippet . length ( ) ) ; currSnippet = sb . toString ( ) ; } sb . setLength ( 0 ) ; String ret = urlEncode ( ctx , currSnippet ) ; sb . setLength ( 0 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public String writeBidRequest ( BidRequest req ) throws IOException { try ( StringWriter writer = new StringWriter ( ) ) { writeBidRequest ( req , writer ) ; return writer . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link BidRequest } to JSON streamed into an { @link Writer } . [CODESPLIT] public void writeBidRequest ( BidRequest req , Writer writer ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( writer ) ; writeBidRequest ( req , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link BidRequest } to JSON streamed into an { @link OutputStream } . [CODESPLIT] public void writeBidRequest ( BidRequest req , OutputStream os ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( os ) ; writeBidRequest ( req , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public final void writeBidRequest ( BidRequest req , JsonGenerator gen ) throws IOException { gen . writeStartObject ( ) ; writeBidRequestFields ( req , gen ) ; writeExtensions ( req , gen ) ; gen . writeEndObject ( ) ; gen . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public String writeBidResponse ( BidResponse resp ) throws IOException { try ( StringWriter writer = new StringWriter ( ) ) { writeBidResponse ( resp , writer ) ; return writer . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link BidResponse } to JSON streamed to a { @link OutputStream } . [CODESPLIT] public void writeBidResponse ( BidResponse resp , OutputStream os ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( os ) ; writeBidResponse ( resp , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link BidResponse } to JSON streamed to a { @link Writer } . [CODESPLIT] public void writeBidResponse ( BidResponse resp , Writer writer ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( writer ) ; writeBidResponse ( resp , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public final void writeBidResponse ( BidResponse resp , JsonGenerator gen ) throws IOException { gen . writeStartObject ( ) ; writeBidResponseFields ( resp , gen ) ; writeExtensions ( resp , gen ) ; gen . writeEndObject ( ) ; gen . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return The OpenRTB SeatBid with the specified ID ; will be created if not existent . The ID should be present in the request s wseat . [CODESPLIT] public static SeatBid . Builder seatBid ( BidResponse . Builder response , String seat ) { checkNotNull ( seat ) ; for ( SeatBid . Builder seatbid : response . getSeatbidBuilderList ( ) ) { if ( seatbid . hasSeat ( ) && seat . equals ( seatbid . getSeat ( ) ) ) { return seatbid ; } } return response . addSeatbidBuilder ( ) . setSeat ( seat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates all bids . [CODESPLIT] public static Iterable < Bid . Builder > bids ( BidResponse . Builder response ) { return new ResponseBidsIterator ( response , SEAT_ANY , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterates all bids from a specific seat . [CODESPLIT] public static List < Bid . Builder > bids ( BidResponse . Builder response , @ Nullable String seatFilter ) { for ( SeatBid . Builder seatbid : response . getSeatbidBuilderList ( ) ) { if ( filterSeat ( seatbid , seatFilter ) ) { return seatbid . getBidBuilderList ( ) ; } } return ImmutableList . of ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a bid by ID . [CODESPLIT] @ Nullable public static Bid . Builder bidWithId ( BidResponse . Builder response , String id ) { checkNotNull ( id ) ; for ( SeatBid . Builder seatbid : response . getSeatbidBuilderList ( ) ) { for ( Bid . Builder bid : seatbid . getBidBuilderList ( ) ) { if ( id . equals ( bid . getId ( ) ) ) { return bid ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds bids by a custom criteria . [CODESPLIT] public static Stream < Bid . Builder > bidStreamWith ( BidResponse . Builder response , @ Nullable String seatFilter , @ Nullable Predicate < Bid . Builder > bidFilter ) { return StreamSupport . stream ( new ResponseBidsIterator ( response , seatFilter , bidFilter ) . spliterator ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds bids by a custom criteria . [CODESPLIT] public static Iterable < Bid . Builder > bidsWith ( BidResponse . Builder response , @ Nullable String seatFilter , @ Nullable Predicate < Bid . Builder > bidFilter ) { return new ResponseBidsIterator ( response , seatFilter , bidFilter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates bids from all seats . [CODESPLIT] public static boolean updateBids ( BidResponse . Builder response , Function < Bid . Builder , Boolean > updater ) { checkNotNull ( updater ) ; boolean updated = false ; for ( SeatBid . Builder seatbid : response . getSeatbidBuilderList ( ) ) { updated |= ProtoUtils . update ( seatbid . getBidBuilderList ( ) , updater ) ; } return updated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates bids from a given seat . [CODESPLIT] public static boolean updateBids ( BidResponse . Builder response , @ Nullable String seatFilter , Function < Bid . Builder , Boolean > updater ) { checkNotNull ( updater ) ; for ( SeatBid . Builder seatbid : response . getSeatbidBuilderList ( ) ) { if ( filterSeat ( seatbid , seatFilter ) ) { return ProtoUtils . update ( seatbid . getBidBuilderList ( ) , updater ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove bids by bid . [CODESPLIT] public static boolean removeBids ( BidResponse . Builder response , Predicate < Bid . Builder > filter ) { checkNotNull ( filter ) ; boolean updated = false ; for ( SeatBid . Builder seatbid : response . getSeatbidBuilderList ( ) ) { updated |= removeBids ( seatbid , filter ) ; } return updated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove bids by seat and bid . [CODESPLIT] public static boolean removeBids ( BidResponse . Builder response , @ Nullable String seatFilter , Predicate < Bid . Builder > bidFilter ) { checkNotNull ( bidFilter ) ; boolean updated = false ; for ( SeatBid . Builder seatbid : response . getSeatbidBuilderList ( ) ) { if ( filterSeat ( seatbid , seatFilter ) ) { updated |= removeBids ( seatbid , bidFilter ) ; } } return updated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds an { @link Imp } by ID . [CODESPLIT] @ Nullable public static Imp impWithId ( BidRequest request , String id ) { checkNotNull ( id ) ; for ( Imp imp : request . getImpList ( ) ) { if ( imp . getId ( ) . equals ( id ) ) { return imp ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an { @link Imp } by its ID and its { @link Banner } s ID . [CODESPLIT] @ Nullable public static Imp bannerImpWithId ( BidRequest request , @ Nullable String impId , String bannerId ) { checkNotNull ( bannerId ) ; for ( Imp imp : request . getImpList ( ) ) { if ( ( impId == null || imp . getId ( ) . equals ( impId ) ) && imp . hasBanner ( ) && imp . getBanner ( ) . getId ( ) . equals ( bannerId ) ) { return imp ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Optimized code for most filtered lookups . This is worth the effort because bidder code may invoke these lookup methods intensely ; common cases like everything - filtered or nothing - filtered are very dominant ; and simpler code previously used needed lots of temporary collections . [CODESPLIT] public static Iterable < Imp > impsWith ( BidRequest request , Predicate < Imp > impFilter ) { checkNotNull ( impFilter ) ; List < Imp > imps = request . getImpList ( ) ; if ( imps . isEmpty ( ) || impFilter == IMP_ALL ) { return imps ; } else if ( impFilter == IMP_NONE ) { return ImmutableList . of ( ) ; } boolean included = impFilter . test ( imps . get ( 0 ) ) ; int size = imps . size ( ) , i ; for ( i = 1 ; i < size ; ++ i ) { if ( impFilter . test ( imps . get ( i ) ) != included ) { break ; } } if ( i == size ) { return included ? imps // Unmodifiable, comes from protobuf : ImmutableList . < Imp > of ( ) ; } int headingSize = i ; return new FluentIterable < Imp > ( ) { @ Override public Iterator < Imp > iterator ( ) { Iterator < Imp > unfiltered = imps . iterator ( ) ; return new AbstractIterator < Imp > ( ) { private int heading = 0 ; @ Override protected Imp computeNext ( ) { while ( unfiltered . hasNext ( ) ) { Imp imp = unfiltered . next ( ) ; if ( ( heading ++ < headingSize ) ? included : impFilter . test ( imp ) ) { return imp ; } } return endOfData ( ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds impression type subfilters to a base filter to further restricts impressions that contain a banner video and / or native object . [CODESPLIT] public static Predicate < Imp > addFilters ( Predicate < Imp > baseFilter , boolean banner , boolean video , boolean nativ ) { int orCount = ( banner ? 1 : 0 ) + ( video ? 1 : 0 ) + ( nativ ? 1 : 0 ) ; if ( baseFilter == IMP_NONE || orCount == 0 ) { return baseFilter ; } Predicate < Imp > typeFilter = null ; if ( banner ) { typeFilter = Imp :: hasBanner ; } if ( video ) { typeFilter = typeFilter == null ? Imp :: hasVideo : typeFilter . or ( Imp :: hasVideo ) ; } if ( nativ ) { typeFilter = typeFilter == null ? Imp :: hasNative : typeFilter . or ( Imp :: hasNative ) ; } return baseFilter == IMP_ALL ? typeFilter : baseFilter . and ( typeFilter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a filter by seat . [CODESPLIT] public static boolean filterSeat ( SeatBidOrBuilder seatbid , @ Nullable String seatFilter ) { return seatFilter == null ? ! seatbid . hasSeat ( ) : seatFilter == SEAT_ANY || seatFilter . equals ( seatbid . getSeat ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public String writeNativeRequest ( NativeRequest req ) throws IOException { try ( StringWriter writer = new StringWriter ( ) ) { writeNativeRequest ( req , writer ) ; return writer . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link NativeRequest } to JSON streamed into an { @link Writer } . [CODESPLIT] public void writeNativeRequest ( NativeRequest req , Writer writer ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( writer ) ; writeNativeRequest ( req , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link NativeRequest } to JSON streamed into an { @link OutputStream } . [CODESPLIT] public void writeNativeRequest ( NativeRequest req , OutputStream os ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( os ) ; writeNativeRequest ( req , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public final void writeNativeRequest ( NativeRequest req , JsonGenerator gen ) throws IOException { gen . writeStartObject ( ) ; if ( factory ( ) . isRootNativeField ( ) ) { gen . writeObjectFieldStart ( \"native\" ) ; } writeNativeRequestFields ( req , gen ) ; writeExtensions ( req , gen ) ; if ( factory ( ) . isRootNativeField ( ) ) { gen . writeEndObject ( ) ; } gen . writeEndObject ( ) ; gen . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public String writeNativeResponse ( NativeResponse resp ) throws IOException { try ( StringWriter writer = new StringWriter ( ) ) { writeNativeResponse ( resp , writer ) ; return writer . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link NativeResponse } to JSON streamed to a { @link OutputStream } . [CODESPLIT] public void writeNativeResponse ( NativeResponse resp , OutputStream os ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( os ) ; writeNativeResponse ( resp , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { @link NativeResponse } to JSON streamed to a { @link Writer } . [CODESPLIT] public void writeNativeResponse ( NativeResponse resp , Writer writer ) throws IOException { JsonGenerator gen = factory ( ) . getJsonFactory ( ) . createGenerator ( writer ) ; writeNativeResponse ( resp , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes a { [CODESPLIT] public final void writeNativeResponse ( NativeResponse resp , JsonGenerator gen ) throws IOException { gen . writeStartObject ( ) ; if ( factory ( ) . isRootNativeField ( ) ) { gen . writeObjectFieldStart ( \"native\" ) ; } writeNativeResponseFields ( resp , gen ) ; writeExtensions ( resp , gen ) ; if ( factory ( ) . isRootNativeField ( ) ) { gen . writeEndObject ( ) ; } gen . writeEndObject ( ) ; gen . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read any extensions that may exist in a message . [CODESPLIT] protected final < EB extends ExtendableBuilder < ? , EB > > void readExtensions ( EB msg , JsonParser par ) throws IOException { @ SuppressWarnings ( \"unchecked\" ) Set < OpenRtbJsonExtReader < EB > > extReaders = factory . getReaders ( ( Class < EB > ) msg . getClass ( ) ) ; if ( extReaders . isEmpty ( ) ) { par . skipChildren ( ) ; return ; } startObject ( par ) ; JsonToken tokLast = par . getCurrentToken ( ) ; JsonLocation locLast = par . getCurrentLocation ( ) ; while ( true ) { boolean extRead = false ; for ( OpenRtbJsonExtReader < EB > extReader : extReaders ) { if ( extReader . filter ( par ) ) { extReader . read ( msg , par ) ; JsonToken tokNew = par . getCurrentToken ( ) ; JsonLocation locNew = par . getCurrentLocation ( ) ; boolean advanced = tokNew != tokLast || ! locNew . equals ( locLast ) ; extRead |= advanced ; if ( ! endObject ( par ) ) { return ; } else if ( advanced && par . getCurrentToken ( ) != JsonToken . FIELD_NAME ) { tokLast = par . nextToken ( ) ; locLast = par . getCurrentLocation ( ) ; } else { tokLast = tokNew ; locLast = locNew ; } } } if ( ! endObject ( par ) ) { // Can't rely on this exit condition inside the for loop because no readers may filter. return ; } if ( ! extRead ) { // No field was consumed by any reader, so we need to skip the field to make progress. if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Extension field not consumed by any reader, skipping: {} @{}:{}\" , par . getCurrentName ( ) , locLast . getLineNr ( ) , locLast . getCharOffset ( ) ) ; } par . nextToken ( ) ; par . skipChildren ( ) ; tokLast = par . nextToken ( ) ; locLast = par . getCurrentLocation ( ) ; } // Else loop, try all readers again } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special case for empty - string input . Returning null in non - [CODESPLIT] protected final boolean emptyToNull ( JsonParser par ) throws IOException { JsonToken token = par . getCurrentToken ( ) ; if ( token == null ) { token = par . nextToken ( ) ; } return ! factory ( ) . isStrict ( ) && token == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an extension reader . [CODESPLIT] public final < EB extends ExtendableBuilder < ? , EB > > OpenRtbJsonFactory register ( OpenRtbJsonExtReader < EB > extReader , Class < EB > msgKlass ) { extReaders . put ( msgKlass . getName ( ) , extReader ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an extension writer bound to a specific field name . This writer will be used in preference to a non - field - specific writer that may exist for the same class . [CODESPLIT] public final < T > OpenRtbJsonFactory register ( OpenRtbJsonExtWriter < T > extWriter , Class < T > extKlass , Class < ? extends Message > msgKlass , String fieldName ) { Map < String , Map < String , OpenRtbJsonExtWriter < ? > > > mapMsg = extWriters . get ( msgKlass . getName ( ) ) ; if ( mapMsg == null ) { extWriters . put ( msgKlass . getName ( ) , mapMsg = new LinkedHashMap <> ( ) ) ; } Map < String , OpenRtbJsonExtWriter < ? > > mapKlass = mapMsg . get ( extKlass . getName ( ) ) ; if ( mapKlass == null ) { mapMsg . put ( extKlass . getName ( ) , mapKlass = new LinkedHashMap <> ( ) ) ; } mapKlass . put ( fieldName == null ? FIELDNAME_ALL : fieldName , extWriter ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an extension writer not bound to any a field name ( so this serializer can be used for any extension of the provided class ) . [CODESPLIT] public final < T > OpenRtbJsonFactory register ( OpenRtbJsonExtWriter < T > extWriter , Class < T > extKlass , Class < ? extends Message > msgKlass ) { return register ( extWriter , extKlass , msgKlass , FIELDNAME_ALL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public NativeRequest readNativeRequest ( CharSequence chars ) throws IOException { return readNativeRequest ( CharSource . wrap ( chars ) . openStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public NativeRequest readNativeRequest ( Reader reader ) throws IOException { return ProtoUtils . built ( readNativeRequest ( factory ( ) . getJsonFactory ( ) . createParser ( reader ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public NativeRequest readNativeRequest ( InputStream is ) throws IOException { try { return ProtoUtils . built ( readNativeRequest ( factory ( ) . getJsonFactory ( ) . createParser ( is ) ) ) ; } finally { Closeables . closeQuietly ( is ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public final NativeRequest . Builder readNativeRequest ( JsonParser par ) throws IOException { if ( emptyToNull ( par ) ) { return null ; } NativeRequest . Builder req = NativeRequest . newBuilder ( ) ; boolean rootNativeField = false ; boolean firstField = true ; for ( startObject ( par ) ; endObject ( par ) ; par . nextToken ( ) ) { String fieldName = getCurrentName ( par ) ; if ( par . nextToken ( ) != JsonToken . VALUE_NULL ) { if ( firstField ) { firstField = false ; if ( ( rootNativeField = \"native\" . equals ( fieldName ) ) == true ) { startObject ( par ) ; fieldName = getCurrentName ( par ) ; par . nextToken ( ) ; } } if ( par . getCurrentToken ( ) != JsonToken . VALUE_NULL ) { readNativeRequestField ( par , req , fieldName ) ; } } } if ( rootNativeField && ! endObject ( par ) ) { par . nextToken ( ) ; } return req ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public NativeResponse readNativeResponse ( CharSequence chars ) throws IOException { return readNativeResponse ( CharSource . wrap ( chars ) . openStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public NativeResponse readNativeResponse ( Reader reader ) throws IOException { return ProtoUtils . built ( readNativeResponse ( factory ( ) . getJsonFactory ( ) . createParser ( reader ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public NativeResponse readNativeResponse ( InputStream is ) throws IOException { try { return ProtoUtils . built ( readNativeResponse ( factory ( ) . getJsonFactory ( ) . createParser ( is ) ) ) ; } finally { Closeables . closeQuietly ( is ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public final NativeResponse . Builder readNativeResponse ( JsonParser par ) throws IOException { if ( emptyToNull ( par ) ) { return null ; } NativeResponse . Builder resp = NativeResponse . newBuilder ( ) ; boolean rootNativeField = false ; boolean firstField = true ; for ( startObject ( par ) ; endObject ( par ) ; par . nextToken ( ) ) { String fieldName = getCurrentName ( par ) ; if ( par . nextToken ( ) != JsonToken . VALUE_NULL ) { if ( firstField ) { firstField = false ; if ( ( rootNativeField = \"native\" . equals ( fieldName ) ) == true ) { startObject ( par ) ; fieldName = getCurrentName ( par ) ; par . nextToken ( ) ; } } if ( par . getCurrentToken ( ) != JsonToken . VALUE_NULL ) { readNativeResponseField ( par , resp , fieldName ) ; } } } if ( rootNativeField && ! endObject ( par ) ) { par . nextToken ( ) ; } return resp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the context s response in - place modifying properties that may contain macros . [CODESPLIT] public void process ( SnippetProcessorContext bidCtx ) { for ( SeatBid . Builder seat : bidCtx . response ( ) . getSeatbidBuilderList ( ) ) { for ( Bid . Builder bid : seat . getBidBuilderList ( ) ) { bidCtx . setBid ( bid ) ; processFields ( bidCtx ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes all fields of a bid that should support macro expansion . [CODESPLIT] protected void processFields ( SnippetProcessorContext bidCtx ) { Bid . Builder bid = bidCtx . getBid ( ) ; // Properties that can also be in the RHS of macros used by other properties. if ( extendedFields ) { if ( bid . hasAdid ( ) ) { bid . setAdid ( process ( bidCtx , bid . getAdid ( ) ) ) ; } bid . setId ( process ( bidCtx , bid . getId ( ) ) ) ; } // Properties that are NOT the RHS of any macro. if ( bid . hasAdm ( ) ) { bid . setAdm ( process ( bidCtx , bid . getAdm ( ) ) ) ; } if ( extendedFields ) { if ( bid . hasBurl ( ) ) { bid . setBurl ( process ( bidCtx , bid . getBurl ( ) ) ) ; } if ( bid . hasCid ( ) ) { bid . setCid ( process ( bidCtx , bid . getCid ( ) ) ) ; } if ( bid . hasCrid ( ) ) { bid . setCrid ( process ( bidCtx , bid . getCrid ( ) ) ) ; } if ( bid . hasDealid ( ) ) { bid . setDealid ( process ( bidCtx , bid . getDealid ( ) ) ) ; } bid . setImpid ( process ( bidCtx , bid . getImpid ( ) ) ) ; if ( bid . hasIurl ( ) ) { bid . setIurl ( process ( bidCtx , bid . getIurl ( ) ) ) ; } if ( bid . hasLurl ( ) ) { bid . setIurl ( process ( bidCtx , bid . getLurl ( ) ) ) ; } if ( bid . hasNurl ( ) ) { bid . setNurl ( process ( bidCtx , bid . getNurl ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public BidRequest readBidRequest ( CharSequence chars ) throws IOException { return readBidRequest ( CharSource . wrap ( chars ) . openStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public BidRequest readBidRequest ( Reader reader ) throws IOException { return ProtoUtils . built ( readBidRequest ( factory ( ) . getJsonFactory ( ) . createParser ( reader ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public BidRequest readBidRequest ( InputStream is ) throws IOException { try { return ProtoUtils . built ( readBidRequest ( factory ( ) . getJsonFactory ( ) . createParser ( is ) ) ) ; } finally { Closeables . closeQuietly ( is ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public final BidRequest . Builder readBidRequest ( JsonParser par ) throws IOException { if ( emptyToNull ( par ) ) { return null ; } BidRequest . Builder req = BidRequest . newBuilder ( ) ; for ( startObject ( par ) ; endObject ( par ) ; par . nextToken ( ) ) { String fieldName = getCurrentName ( par ) ; if ( par . nextToken ( ) != JsonToken . VALUE_NULL ) { readBidRequestField ( par , req , fieldName ) ; } } return req ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public BidResponse readBidResponse ( CharSequence chars ) throws IOException { return readBidResponse ( CharSource . wrap ( chars ) . openStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public BidResponse readBidResponse ( Reader reader ) throws IOException { return ProtoUtils . built ( readBidResponse ( factory ( ) . getJsonFactory ( ) . createParser ( reader ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public BidResponse readBidResponse ( InputStream is ) throws IOException { try { return ProtoUtils . built ( readBidResponse ( factory ( ) . getJsonFactory ( ) . createParser ( is ) ) ) ; } finally { Closeables . closeQuietly ( is ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Desserializes a { [CODESPLIT] public final BidResponse . Builder readBidResponse ( JsonParser par ) throws IOException { if ( emptyToNull ( par ) ) { return null ; } BidResponse . Builder resp = BidResponse . newBuilder ( ) ; for ( startObject ( par ) ; endObject ( par ) ; par . nextToken ( ) ) { String fieldName = getCurrentName ( par ) ; if ( par . nextToken ( ) != JsonToken . VALUE_NULL ) { readBidResponseField ( par , resp , fieldName ) ; } } return resp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a message - or - builder returns a message invoking the builder if necessary . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < I extends MessageLiteOrBuilder , O extends MessageLite > O built ( @ Nullable I msg ) { return msg instanceof MessageLite . Builder ? ( O ) ( ( MessageLite . Builder ) msg ) . build ( ) : ( O ) msg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a message - or - builder return a builder invoking toBuilder () if necessary . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < I extends MessageLiteOrBuilder , O extends MessageLite . Builder > O builder ( @ Nullable I msg ) { return msg instanceof MessageLite ? ( O ) ( ( MessageLite ) msg ) . toBuilder ( ) : ( O ) msg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates every builder from a sequence . [CODESPLIT] public static < B extends MessageLite . Builder > boolean update ( Iterable < B > objs , Function < B , Boolean > updater ) { checkNotNull ( updater ) ; boolean updated = false ; for ( B obj : objs ) { updated |= updater . apply ( obj ) ; } return updated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a filter through a sequence of objects . [CODESPLIT] public static < M extends MessageLiteOrBuilder > List < M > filter ( List < M > objs , Predicate < M > filter ) { checkNotNull ( filter ) ; for ( int i = 0 ; i < objs . size ( ) ; ++ i ) { if ( ! filter . test ( objs . get ( i ) ) ) { // At least one discarded object, go to slow-path. return filterFrom ( objs , filter , i ) ; } } // Optimized common case: all items filtered, return the input sequence. return objs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of a { @link Message } that contains only fields that pass a filter . This will be executed recursively for fields which are child messages . [CODESPLIT] @ Nullable public static < M extends Message > M filter ( M msg , boolean clearEmpty , Predicate < FieldDescriptor > filter ) { checkNotNull ( filter ) ; int i = 0 ; for ( Map . Entry < FieldDescriptor , Object > entry : msg . getAllFields ( ) . entrySet ( ) ) { FieldDescriptor fd = entry . getKey ( ) ; if ( ! filter . test ( fd ) ) { // At least one field discarded, go to slow-path. return filterFrom ( msg , clearEmpty , filter , i , true ) ; } else if ( fd . getType ( ) == FieldDescriptor . Type . MESSAGE ) { // At least one field may have children, go to slow-path. return filterFrom ( msg , clearEmpty , filter , i , false ) ; } ++ i ; } // Optimized common case: all items filtered, return the input sequence. return msg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current field name or empty string if none . [CODESPLIT] public static String getCurrentName ( JsonParser par ) throws IOException { String name = par . getCurrentName ( ) ; return name == null ? \"\" : name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts an Object skipping the { token and if necessary a field name before it . [CODESPLIT] public static void startObject ( JsonParser par ) throws IOException { JsonToken token = par . getCurrentToken ( ) ; if ( token == null || token == JsonToken . FIELD_NAME ) { token = par . nextToken ( ) ; } if ( token == JsonToken . START_OBJECT ) { par . nextToken ( ) ; } else { throw new JsonParseException ( par , \"Expected start of object\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public static boolean endObject ( JsonParser par ) { JsonToken token = par . getCurrentToken ( ) ; return token != null && token != JsonToken . END_OBJECT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts an Array skipping the [ token and if necessary a field name before it . [CODESPLIT] public static void startArray ( JsonParser par ) throws IOException { JsonToken token = par . getCurrentToken ( ) ; if ( token == null || token == JsonToken . FIELD_NAME ) { token = par . nextToken ( ) ; } if ( token == JsonToken . START_ARRAY ) { par . nextToken ( ) ; } else { throw new JsonParseException ( par , \"Expected start of array\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] public static boolean endArray ( JsonParser par ) { JsonToken token = par . getCurrentToken ( ) ; return token != null && token != JsonToken . END_ARRAY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips a field name if necessary returning the current token then . [CODESPLIT] public static JsonToken peekToken ( JsonParser par ) throws IOException { JsonToken token = par . getCurrentToken ( ) ; if ( token == null || token == JsonToken . FIELD_NAME ) { token = par . nextToken ( ) ; } return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips a field name if necessary returning the current token then which must be the start of an Array or Object : { or [ . [CODESPLIT] public static JsonToken peekStructStart ( JsonParser par ) throws IOException { JsonToken token = peekToken ( par ) ; if ( token . isStructStart ( ) ) { return token ; } else { throw new JsonParseException ( par , \"Expected start of array or object\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a boolean as int where false = 0 and true = 1 . [CODESPLIT] public static void writeIntBoolField ( String fieldName , boolean data , JsonGenerator gen ) throws IOException { gen . writeNumberField ( fieldName , data ? 1 : 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a string array if not empty . [CODESPLIT] public static void writeStrings ( String fieldName , List < String > data , JsonGenerator gen ) throws IOException { if ( ! data . isEmpty ( ) ) { gen . writeArrayFieldStart ( fieldName ) ; for ( String d : data ) { gen . writeString ( d ) ; } gen . writeEndArray ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an int array if not empty . [CODESPLIT] public static void writeInts ( String fieldName , List < Integer > data , JsonGenerator gen ) throws IOException { if ( ! data . isEmpty ( ) ) { gen . writeArrayFieldStart ( fieldName ) ; for ( Integer d : data ) { gen . writeNumber ( d ) ; } gen . writeEndArray ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a long using quotes only if it s too big ( over 53 - bit mantissa ) . [CODESPLIT] public static void writeLong ( long data , JsonGenerator gen ) throws IOException { if ( data > MAX_JSON_INT || data < - MAX_JSON_INT ) { gen . writeString ( Long . toString ( data ) ) ; } else { gen . writeNumber ( data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a long using quotes only if it s too big ( over 53 - bit mantissa ) . [CODESPLIT] public static void writeLongField ( String fieldName , long data , JsonGenerator gen ) throws IOException { gen . writeFieldName ( fieldName ) ; writeLong ( data , gen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a long array if not empty using quotes for values that are too big . [CODESPLIT] public static void writeLongs ( String fieldName , List < Long > data , JsonGenerator gen ) throws IOException { if ( ! data . isEmpty ( ) ) { gen . writeArrayFieldStart ( fieldName ) ; for ( long d : data ) { writeLong ( d , gen ) ; } gen . writeEndArray ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a enum value as an int using its Protobuf number . [CODESPLIT] public static void writeEnum ( ProtocolMessageEnum e , JsonGenerator gen ) throws IOException { gen . writeNumber ( e . getNumber ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a enum value as an int using its Protobuf number . [CODESPLIT] public static void writeEnumField ( String fieldName , ProtocolMessageEnum e , JsonGenerator gen ) throws IOException { gen . writeNumberField ( fieldName , e . getNumber ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a enum array if not empty . [CODESPLIT] public static void writeEnums ( String fieldName , List < ? extends ProtocolMessageEnum > enums , JsonGenerator gen ) throws IOException { if ( ! enums . isEmpty ( ) ) { gen . writeArrayFieldStart ( fieldName ) ; for ( ProtocolMessageEnum e : enums ) { writeEnum ( e , gen ) ; } gen . writeEndArray ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads from either a JSON Value String ( containing CSV ) or a JSON Array . The dual input format is needed because some fields ( e . g . keywords ) were allowed to be of either type in OpenRTB 2 . 2 ; now in 2 . 3 they are all CSV strings only . TODO : Simplify this to only accept CSV strings after 2 . 2 compatibility is dropped . [CODESPLIT] public static String readCsvString ( JsonParser par ) throws IOException { JsonToken currentToken = par . getCurrentToken ( ) ; if ( currentToken == JsonToken . START_ARRAY ) { StringBuilder keywords = new StringBuilder ( ) ; for ( startArray ( par ) ; endArray ( par ) ; par . nextToken ( ) ) { if ( keywords . length ( ) != 0 ) { keywords . append ( ' ' ) ; } keywords . append ( par . getText ( ) ) ; } return keywords . toString ( ) ; } else if ( currentToken == JsonToken . VALUE_STRING ) { return par . getText ( ) ; } else { throw new JsonParseException ( par , \"Expected string or array\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve relative URL - s and fix a few java . net . URL errors in handling of URLs with embedded params and pure query targets . [CODESPLIT] public static URL resolveURL ( URL base , String target ) throws MalformedURLException { target = target . trim ( ) ; if ( target . startsWith ( \"?\" ) ) { return fixPureQueryTargets ( base , target ) ; } return new URL ( base , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle the case in RFC3986 section 5 . 4 . 1 example 7 and similar . [CODESPLIT] static URL fixPureQueryTargets ( URL base , String target ) throws MalformedURLException { if ( ! target . startsWith ( \"?\" ) ) return new URL ( base , target ) ; String basePath = base . getPath ( ) ; String baseRightMost = \"\" ; int baseRightMostIdx = basePath . lastIndexOf ( \"/\" ) ; if ( baseRightMostIdx != - 1 ) { baseRightMost = basePath . substring ( baseRightMostIdx + 1 ) ; } if ( target . startsWith ( \"?\" ) ) target = baseRightMost + target ; return new URL ( base , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles cases where the url param information is encoded into the base url as opposed to the target . <p > If the taget contains params ( i . e . ; xxxx ) information then the target params information is assumed to be correct and any base params information is ignored . If the base contains params information but the tareget does not then the params information is moved to the target allowing it to be correctly determined by the java . net . URL class . [CODESPLIT] private static URL fixEmbeddedParams ( URL base , String target ) throws MalformedURLException { // the target contains params information or the base doesn't then no // conversion necessary, return regular URL if ( target . indexOf ( ' ' ) >= 0 || base . toString ( ) . indexOf ( ' ' ) == - 1 ) { return new URL ( base , target ) ; } // get the base url and it params information String baseURL = base . toString ( ) ; int startParams = baseURL . indexOf ( ' ' ) ; String params = baseURL . substring ( startParams ) ; // if the target has a query string then put the params information // after // any path but before the query string, otherwise just append to the // path int startQS = target . indexOf ( ' ' ) ; if ( startQS >= 0 ) { target = target . substring ( 0 , startQS ) + params + target . substring ( startQS ) ; } else { target += params ; } return new URL ( base , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Partitions of the hostname of the url by . [CODESPLIT] public static String [ ] getHostSegments ( URL url ) { String host = url . getHost ( ) ; // return whole hostname, if it is an ipv4 // TODO : handle ipv6 if ( IP_PATTERN . matcher ( host ) . matches ( ) ) return new String [ ] { host } ; return host . split ( \"\\\\.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the lowercased hostname for the url or null if the url is not well formed . [CODESPLIT] public static String getHost ( String url ) { try { return new URL ( url ) . getHost ( ) . toLowerCase ( Locale . ROOT ) ; } catch ( MalformedURLException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the page for the url . The page consists of the protocol host and path but does not include the query string . The host is lowercased but the path is not . [CODESPLIT] public static String getPage ( String url ) { try { // get the full url, and replace the query string with and empty // string url = url . toLowerCase ( Locale . ROOT ) ; String queryStr = new URL ( url ) . getQuery ( ) ; return ( queryStr != null ) ? url . replace ( \"?\" + queryStr , \"\" ) : url ; } catch ( MalformedURLException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return one or more Strings regardless of whether they are represented as a single String or a list in the config or an empty List if no value could be found for that key . [CODESPLIT] public static List < String > loadListFromConf ( String paramKey , Map stormConf ) { Object obj = stormConf . get ( paramKey ) ; List < String > list = new LinkedList <> ( ) ; if ( obj == null ) return list ; if ( obj instanceof PersistentVector ) { list . addAll ( ( PersistentVector ) obj ) ; } else { // single value? list . add ( obj . toString ( ) ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the config consists of a single key config its values are used instead [CODESPLIT] public static Map extractConfigElement ( Map conf ) { if ( conf . size ( ) == 1 ) { Object confNode = conf . get ( \"config\" ) ; if ( confNode != null && confNode instanceof Map ) { conf = ( Map ) confNode ; } } return conf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance of the protocol to use for a given URL [CODESPLIT] public synchronized Protocol getProtocol ( URL url ) { // get the protocol String protocol = url . getProtocol ( ) ; return cache . get ( protocol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used for redirections or when discovering sitemap URLs . The custom key / values are added to the target metadata post - filtering . [CODESPLIT] protected void emitOutlink ( Tuple t , URL sURL , String newUrl , Metadata sourceMetadata , String ... customKeyVals ) { Outlink ol = filterOutlink ( sURL , newUrl , sourceMetadata , customKeyVals ) ; if ( ol == null ) return ; collector . emit ( com . digitalpebble . stormcrawler . Constants . StatusStreamName , t , new Values ( ol . getTargetURL ( ) , ol . getMetadata ( ) , Status . DISCOVERED ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a WARC info entry which can be stored at the beginning of each WARC file . [CODESPLIT] public static byte [ ] generateWARCInfo ( Map < String , String > fields ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( WARC_VERSION ) ; buffer . append ( CRLF ) ; buffer . append ( \"WARC-Type: warcinfo\" ) . append ( CRLF ) ; String mainID = UUID . randomUUID ( ) . toString ( ) ; // retrieve the date and filename from the map String date = fields . get ( \"WARC-Date\" ) ; buffer . append ( \"WARC-Date: \" ) . append ( date ) . append ( CRLF ) ; String filename = fields . get ( \"WARC-Filename\" ) ; buffer . append ( \"WARC-Filename: \" ) . append ( filename ) . append ( CRLF ) ; buffer . append ( \"WARC-Record-ID\" ) . append ( \": \" ) . append ( \"<urn:uuid:\" ) . append ( mainID ) . append ( \">\" ) . append ( CRLF ) ; buffer . append ( \"Content-Type\" ) . append ( \": \" ) . append ( \"application/warc-fields\" ) . append ( CRLF ) ; StringBuilder fieldsBuffer = new StringBuilder ( ) ; // add WARC fields // http://bibnum.bnf.fr/warc/WARC_ISO_28500_version1_latestdraft.pdf Iterator < Entry < String , String > > iter = fields . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Entry < String , String > entry = iter . next ( ) ; String key = entry . getKey ( ) ; if ( key . startsWith ( \"WARC-\" ) ) continue ; fieldsBuffer . append ( key ) . append ( \": \" ) . append ( entry . getValue ( ) ) . append ( CRLF ) ; } buffer . append ( \"Content-Length\" ) . append ( \": \" ) . append ( fieldsBuffer . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) . length ) . append ( CRLF ) ; buffer . append ( CRLF ) ; buffer . append ( fieldsBuffer . toString ( ) ) ; buffer . append ( CRLF ) ; buffer . append ( CRLF ) ; return buffer . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modify verbatim HTTP response headers : remove or replace headers <code > Content - Length< / code > <code > Content - Encoding< / code > and <code > Transfer - Encoding< / code > which may confuse WARC readers . Ensure that the header end with a single empty line ( <code > \\ r \\ n \\ r \\ n< / code > ) . [CODESPLIT] public static String fixHttpHeaders ( String headers , int contentLength ) { int start = 0 , lineEnd = 0 , last = 0 , trailingCrLf = 0 ; StringBuilder replace = new StringBuilder ( ) ; while ( start < headers . length ( ) ) { lineEnd = headers . indexOf ( CRLF , start ) ; trailingCrLf = 1 ; if ( lineEnd == - 1 ) { lineEnd = headers . length ( ) ; trailingCrLf = 0 ; } int colonPos = - 1 ; for ( int i = start ; i < lineEnd ; i ++ ) { if ( headers . charAt ( i ) == ' ' ) { colonPos = i ; break ; } } if ( colonPos == - 1 ) { boolean valid = true ; if ( start == 0 ) { // status line (without colon) } else if ( ( lineEnd + 4 ) == headers . length ( ) && headers . endsWith ( CRLF + CRLF ) ) { // ok, trailing empty line trailingCrLf = 2 ; } else if ( start == lineEnd ) { // skip/remove empty line valid = false ; } else { LOG . warn ( \"Invalid header line: {}\" , headers . substring ( start , lineEnd ) ) ; valid = false ; } if ( ! valid ) { if ( last < start ) { replace . append ( headers . substring ( last , start ) ) ; } last = lineEnd + 2 * trailingCrLf ; } start = lineEnd + 2 * trailingCrLf ; /*\n                 * skip over invalid header line, no further check for\n                 * problematic headers required\n                 */ continue ; } String name = headers . substring ( start , colonPos ) ; if ( PROBLEMATIC_HEADERS . matcher ( name ) . matches ( ) ) { boolean needsFix = true ; if ( name . equalsIgnoreCase ( \"content-length\" ) ) { String value = headers . substring ( colonPos + 1 , lineEnd ) . trim ( ) ; try { int l = Integer . parseInt ( value ) ; if ( l == contentLength ) { needsFix = false ; } } catch ( NumberFormatException e ) { // needs to be fixed } } if ( needsFix ) { if ( last < start ) { replace . append ( headers . substring ( last , start ) ) ; } last = lineEnd + 2 * trailingCrLf ; replace . append ( X_HIDE_HEADER ) . append ( headers . substring ( start , lineEnd + 2 * trailingCrLf ) ) ; if ( trailingCrLf == 0 ) { replace . append ( CRLF ) ; trailingCrLf = 1 ; } if ( name . equalsIgnoreCase ( \"content-length\" ) ) { // add effective uncompressed and unchunked length of // content replace . append ( \"Content-Length\" ) . append ( \": \" ) . append ( contentLength ) . append ( CRLF ) ; } } } start = lineEnd + 2 * trailingCrLf ; } if ( last > 0 || trailingCrLf != 2 ) { if ( last < headers . length ( ) ) { // append trailing headers replace . append ( headers . substring ( last ) ) ; } while ( trailingCrLf < 2 ) { replace . append ( CRLF ) ; trailingCrLf ++ ; } return replace . toString ( ) ; } return headers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the actual fetch time from metadata and format it as required by the WARC - Date field . If no fetch time is found in metadata ( key { [CODESPLIT] protected static String getCaptureTime ( Metadata metadata ) { String captureTimeMillis = metadata . getFirstValue ( REQUEST_TIME_KEY ) ; Instant capturedAt = Instant . now ( ) ; if ( captureTimeMillis != null ) { try { long millis = Long . parseLong ( captureTimeMillis ) ; capturedAt = Instant . ofEpochMilli ( millis ) ; } catch ( NumberFormatException | DateTimeException e ) { LOG . warn ( \"Failed to parse capture time:\" , e ) ; } } return WARC_DF . format ( capturedAt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a normalised value of the content attribute for the refresh tag [CODESPLIT] public static String extractRefreshURL ( String value ) { if ( StringUtils . isBlank ( value ) ) return null ; // 0;URL=http://www.apollocolors.com/site try { if ( matcher . reset ( value ) . matches ( ) ) { return matcher . group ( 1 ) ; } } catch ( Exception e ) { } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine which metadata should be transfered to an outlink . Adds additional metadata like the URL path . [CODESPLIT] public Metadata getMetaForOutlink ( String targetURL , String sourceURL , Metadata parentMD ) { Metadata md = _filter ( parentMD , mdToTransfer ) ; // keep the path? if ( trackPath ) { md . addValue ( urlPathKeyName , sourceURL ) ; } // track depth if ( trackDepth ) { String existingDepth = md . getFirstValue ( depthKeyName ) ; int depth ; try { depth = Integer . parseInt ( existingDepth ) ; } catch ( Exception e ) { depth = 0 ; } md . setValue ( depthKeyName , Integer . toString ( ++ depth ) ) ; } return md ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine which metadata should be persisted for a given document including those which are not necessarily transferred to the outlinks [CODESPLIT] public Metadata filter ( Metadata metadata ) { Metadata filtered_md = _filter ( metadata , mdToTransfer ) ; // add the features that are only persisted but // not transfered like __redirTo_ filtered_md . putAll ( _filter ( metadata , mdToPersistOnly ) ) ; return filtered_md ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates a List of Rules off of JsonNode . [CODESPLIT] private List < RegexRule > readRules ( ArrayNode rulesList ) { List < RegexRule > rules = new ArrayList <> ( ) ; for ( JsonNode urlFilterNode : rulesList ) { try { RegexRule rule = createRule ( urlFilterNode . asText ( ) ) ; if ( rule != null ) { rules . add ( rule ) ; } } catch ( IOException e ) { LOG . error ( \"There was an error reading regex filter {}\" , urlFilterNode . asText ( ) , e ) ; } } return rules ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -------------------------- * <implementation : URLFilter > * -------------------------- [CODESPLIT] @ Override public String filter ( URL pageUrl , Metadata sourceMetadata , String url ) { for ( RegexRule rule : rules ) { if ( rule . match ( url ) ) { return rule . accept ( ) ? url : null ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the key value to the metadata object for a given URL * [CODESPLIT] public void put ( String URL , String key , String value ) { get ( URL ) . getMetadata ( ) . addValue ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new URL [CODESPLIT] public static void add ( String url , Metadata md , Date nextFetch ) { LOG . debug ( \"Adding {} with md {} and nextFetch {}\" , url , md , nextFetch ) ; ScheduledURL tuple = new ScheduledURL ( url , md , nextFetch ) ; synchronized ( queue ) { queue . add ( tuple ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a normalised doc ID based on the URL of a document * [CODESPLIT] public static String getID ( String url ) { // the document needs an ID // see // http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html#creating-document-batches // A unique ID for the document. A document ID can contain any // letter or number and the following characters: _ - = # ; : / ? @ // &. Document IDs must be at least 1 and no more than 128 // characters long. byte [ ] dig = digester . digest ( url . getBytes ( StandardCharsets . UTF_8 ) ) ; String ID = Hex . encodeHexString ( dig ) ; // is that even possible? if ( ID . length ( ) > 128 ) { throw new RuntimeException ( \"ID larger than max 128 chars\" ) ; } return ID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the non - cloudSearch - legal characters . Note that this might convert two fields to the same name . [CODESPLIT] public static String cleanFieldName ( String name ) { String lowercase = name . toLowerCase ( ) ; lowercase = lowercase . replaceAll ( \"[^a-z_0-9]\" , \"_\" ) ; if ( lowercase . length ( ) < 3 || lowercase . length ( ) > 64 ) throw new RuntimeException ( \"Field name must be between 3 and 64 chars : \" + lowercase ) ; if ( lowercase . equals ( \"score\" ) ) throw new RuntimeException ( \"Field name must be score\" ) ; return lowercase ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a connection with a default listener . The values for bolt type are [ indexer status metrics ] [CODESPLIT] public static ElasticSearchConnection getConnection ( Map stormConf , String boltType ) { BulkProcessor . Listener listener = new BulkProcessor . Listener ( ) { @ Override public void afterBulk ( long arg0 , BulkRequest arg1 , BulkResponse arg2 ) { } @ Override public void afterBulk ( long arg0 , BulkRequest arg1 , Throwable arg2 ) { } @ Override public void beforeBulk ( long arg0 , BulkRequest arg1 ) { } } ; return getConnection ( stormConf , boltType , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identifies the charset of a document based on the following logic : guess from the ByteOrderMark - else if the same charset is specified in the http headers and the html metadata then use it - otherwise use ICU s charset detector to make an educated guess and if that fails too returns UTF - 8 . [CODESPLIT] public static String getCharset ( Metadata metadata , byte [ ] content , int maxLengthCharsetDetection ) { // let's look at the BOM first String BOMCharset = getCharsetFromBOM ( content ) ; if ( BOMCharset != null ) { return BOMCharset ; } // then look at what we get from HTTP headers and HTML content String httpCharset = getCharsetFromHTTP ( metadata ) ; String htmlCharset = getCharsetFromMeta ( content , maxLengthCharsetDetection ) ; // both exist and agree if ( httpCharset != null && htmlCharset != null && httpCharset . equalsIgnoreCase ( htmlCharset ) ) { return httpCharset ; } // let's guess from the text - using a hint or not String hintCharset = null ; if ( httpCharset != null && htmlCharset == null ) { hintCharset = httpCharset ; } else if ( httpCharset == null && htmlCharset != null ) { hintCharset = htmlCharset ; } String textCharset = getCharsetFromText ( content , hintCharset , maxLengthCharsetDetection ) ; if ( textCharset != null ) { return textCharset ; } // return the default charset return DEFAULT_CHARSET . name ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects any BOMs and returns the corresponding charset [CODESPLIT] private static String getCharsetFromBOM ( final byte [ ] byteData ) { BOMInputStream bomIn = new BOMInputStream ( new ByteArrayInputStream ( byteData ) ) ; try { ByteOrderMark bom = bomIn . getBOM ( ) ; if ( bom != null ) { return bom . getCharsetName ( ) ; } } catch ( IOException e ) { return null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use a third party library as last resort to guess the charset from the bytes . [CODESPLIT] private static String getCharsetFromText ( byte [ ] content , String declaredCharset , int maxLengthCharsetDetection ) { String charset = null ; // filter HTML tags CharsetDetector charsetDetector = new CharsetDetector ( ) ; charsetDetector . enableInputFilter ( true ) ; // give it a hint if ( declaredCharset != null ) charsetDetector . setDeclaredEncoding ( declaredCharset ) ; // trim the content of the text for the detection byte [ ] subContent = content ; if ( maxLengthCharsetDetection != - 1 && content . length > maxLengthCharsetDetection ) { subContent = Arrays . copyOfRange ( content , 0 , maxLengthCharsetDetection ) ; } charsetDetector . setText ( subContent ) ; try { CharsetMatch charsetMatch = charsetDetector . detect ( ) ; charset = validateCharset ( charsetMatch . getName ( ) ) ; } catch ( Exception e ) { charset = null ; } return charset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to find a META tag in the HTML that hints at the character set used to write the document . [CODESPLIT] private static String getCharsetFromMeta ( byte buffer [ ] , int maxlength ) { // convert to UTF-8 String -- which hopefully will not mess up the // characters we're interested in... int len = buffer . length ; if ( maxlength > 0 && maxlength < len ) { len = maxlength ; } String html = new String ( buffer , 0 , len , DEFAULT_CHARSET ) ; Document doc = Parser . htmlParser ( ) . parseInput ( html , \"dummy\" ) ; // look for <meta http-equiv=\"Content-Type\" // content=\"text/html;charset=gb2312\"> or HTML5 <meta charset=\"gb2312\"> Elements metaElements = doc . select ( \"meta[http-equiv=content-type], meta[charset]\" ) ; String foundCharset = null ; for ( Element meta : metaElements ) { if ( meta . hasAttr ( \"http-equiv\" ) ) foundCharset = getCharsetFromContentType ( meta . attr ( \"content\" ) ) ; if ( foundCharset == null && meta . hasAttr ( \"charset\" ) ) foundCharset = meta . attr ( \"charset\" ) ; if ( foundCharset != null ) return foundCharset ; } return foundCharset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Examines the first bytes of the content for a clue of whether this document is a sitemap based on namespaces . Works for XML and non - compressed documents only . [CODESPLIT] private final boolean sniff ( byte [ ] content ) { byte [ ] beginning = content ; if ( content . length > maxOffsetGuess && maxOffsetGuess > 0 ) { beginning = Arrays . copyOfRange ( content , 0 , maxOffsetGuess ) ; } int position = Bytes . indexOf ( beginning , clue ) ; if ( position != - 1 ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the host domain IP of a URL so that it can be partitioned for politeness depending on the value of the config <i > partition . url . mode< / i > . [CODESPLIT] public String getPartition ( String url , Metadata metadata ) { String partitionKey = null ; String host = \"\" ; // IP in metadata? if ( mode . equalsIgnoreCase ( Constants . PARTITION_MODE_IP ) ) { String ip_provided = metadata . getFirstValue ( \"ip\" ) ; if ( StringUtils . isNotBlank ( ip_provided ) ) { partitionKey = ip_provided ; } } if ( partitionKey == null ) { URL u ; try { u = new URL ( url ) ; host = u . getHost ( ) ; } catch ( MalformedURLException e1 ) { LOG . warn ( \"Invalid URL: {}\" , url ) ; return null ; } } // partition by hostname if ( mode . equalsIgnoreCase ( Constants . PARTITION_MODE_HOST ) ) partitionKey = host ; // partition by domain : needs fixing else if ( mode . equalsIgnoreCase ( Constants . PARTITION_MODE_DOMAIN ) ) { partitionKey = PaidLevelDomain . getPLD ( host ) ; } // partition by IP if ( mode . equalsIgnoreCase ( Constants . PARTITION_MODE_IP ) && partitionKey == null ) { try { long start = System . currentTimeMillis ( ) ; final InetAddress addr = InetAddress . getByName ( host ) ; partitionKey = addr . getHostAddress ( ) ; long end = System . currentTimeMillis ( ) ; LOG . debug ( \"Resolved IP {} in {} msec for : {}\" , partitionKey , end - start , url ) ; } catch ( final Exception e ) { LOG . warn ( \"Unable to resolve IP for: {}\" , host ) ; return null ; } } LOG . debug ( \"Partition Key for: {} > {}\" , url , partitionKey ) ; return partitionKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value for a given key . The value can be null . [CODESPLIT] public void setValue ( String key , String value ) { md . put ( key , new String [ ] { value } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first non empty value found for the keys or null if none found . [CODESPLIT] public static String getFirstValue ( Metadata md , String ... keys ) { for ( String key : keys ) { String val = md . getFirstValue ( key ) ; if ( StringUtils . isBlank ( val ) ) continue ; return val ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first available driver * [CODESPLIT] private final RemoteWebDriver getDriver ( ) { try { return drivers . take ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by extensions of this class * [CODESPLIT] protected static void main ( AbstractHttpProtocol protocol , String args [ ] ) throws Exception { Config conf = new Config ( ) ; // loads the default configuration file Map defaultSCConfig = Utils . findAndReadConfigFile ( \"crawler-default.yaml\" , false ) ; conf . putAll ( ConfUtils . extractConfigElement ( defaultSCConfig ) ) ; Options options = new Options ( ) ; options . addOption ( \"c\" , true , \"configuration file\" ) ; CommandLineParser parser = new DefaultParser ( ) ; CommandLine cmd = parser . parse ( options , args ) ; if ( cmd . hasOption ( \"c\" ) ) { String confFile = cmd . getOptionValue ( \"c\" ) ; ConfUtils . loadConf ( confFile , conf ) ; } protocol . configure ( conf ) ; Set < Runnable > threads = new HashSet <> ( ) ; class Fetchable implements Runnable { String url ; Metadata md ; Fetchable ( String line ) { StringTabScheme scheme = new StringTabScheme ( ) ; List < Object > tuple = scheme . deserialize ( ByteBuffer . wrap ( line . getBytes ( StandardCharsets . UTF_8 ) ) ) ; this . url = ( String ) tuple . get ( 0 ) ; this . md = ( Metadata ) tuple . get ( 1 ) ; } public void run ( ) { StringBuilder stringB = new StringBuilder ( ) ; stringB . append ( url ) . append ( \"\\n\" ) ; if ( ! protocol . skipRobots ) { BaseRobotRules rules = protocol . getRobotRules ( url ) ; stringB . append ( \"robots allowed: \" ) . append ( rules . isAllowed ( url ) ) . append ( \"\\n\" ) ; if ( rules instanceof RobotRules ) { stringB . append ( \"robots requests: \" ) . append ( ( ( RobotRules ) rules ) . getContentLengthFetched ( ) . length ) . append ( \"\\n\" ) ; } stringB . append ( \"sitemaps identified: \" ) . append ( rules . getSitemaps ( ) . size ( ) ) . append ( \"\\n\" ) ; } long start = System . currentTimeMillis ( ) ; ProtocolResponse response ; try { response = protocol . getProtocolOutput ( url , md ) ; stringB . append ( response . getMetadata ( ) ) . append ( \"\\n\" ) ; stringB . append ( \"status code: \" ) . append ( response . getStatusCode ( ) ) . append ( \"\\n\" ) ; stringB . append ( \"content length: \" ) . append ( response . getContent ( ) . length ) . append ( \"\\n\" ) ; long timeFetching = System . currentTimeMillis ( ) - start ; stringB . append ( \"fetched in : \" ) . append ( timeFetching ) . append ( \" msec\" ) ; System . out . println ( stringB ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { threads . remove ( this ) ; } } } for ( String arg : cmd . getArgs ( ) ) { Fetchable p = new Fetchable ( arg ) ; threads . add ( p ) ; new Thread ( p ) . start ( ) ; } while ( threads . size ( ) > 0 ) { Thread . sleep ( 1000 ) ; } protocol . cleanup ( ) ; System . exit ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a list of cookies based on the cookies string taken from response header and the target url . [CODESPLIT] public static List < Cookie > getCookies ( String [ ] cookiesStrings , URL targetURL ) { ArrayList < Cookie > list = new ArrayList < Cookie > ( ) ; for ( String cs : cookiesStrings ) { String name = null ; String value = null ; String expires = null ; String domain = null ; String path = null ; boolean secure = false ; String [ ] tokens = cs . split ( \";\" ) ; int equals = tokens [ 0 ] . indexOf ( \"=\" ) ; name = tokens [ 0 ] . substring ( 0 , equals ) ; value = tokens [ 0 ] . substring ( equals + 1 ) ; for ( int i = 1 ; i < tokens . length ; i ++ ) { String ti = tokens [ i ] . trim ( ) ; if ( ti . equalsIgnoreCase ( \"secure\" ) ) secure = true ; if ( ti . toLowerCase ( ) . startsWith ( \"path=\" ) ) { path = ti . substring ( 5 ) ; } if ( ti . toLowerCase ( ) . startsWith ( \"domain=\" ) ) { domain = ti . substring ( 7 ) ; } if ( ti . toLowerCase ( ) . startsWith ( \"expires=\" ) ) { expires = ti . substring ( 8 ) ; } } BasicClientCookie cookie = new BasicClientCookie ( name , value ) ; // check domain if ( domain != null ) { cookie . setDomain ( domain ) ; if ( ! checkDomainMatchToUrl ( domain , targetURL . getHost ( ) ) ) continue ; } // check path if ( path != null ) { cookie . setPath ( path ) ; if ( ! path . equals ( \"\" ) && ! path . equals ( \"/\" ) && ! targetURL . getPath ( ) . startsWith ( path ) ) continue ; } // check secure if ( secure ) { cookie . setSecure ( secure ) ; if ( ! targetURL . getProtocol ( ) . equalsIgnoreCase ( \"https\" ) ) continue ; } // check expiration if ( expires != null ) { try { Date expirationDate = DATE_FORMAT . parse ( expires ) ; cookie . setExpiryDate ( expirationDate ) ; // check that it hasn't expired? if ( cookie . isExpired ( new Date ( ) ) ) continue ; cookie . setExpiryDate ( expirationDate ) ; } catch ( ParseException e ) { // ignore exceptions } } // attach additional infos to cookie list . add ( cookie ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to check if url matches a cookie domain . [CODESPLIT] public static boolean checkDomainMatchToUrl ( String cookieDomain , String urlHostName ) { try { if ( cookieDomain . startsWith ( \".\" ) ) { cookieDomain = cookieDomain . substring ( 1 ) ; } String [ ] domainTokens = cookieDomain . split ( \"\\\\.\" ) ; String [ ] hostTokens = urlHostName . split ( \"\\\\.\" ) ; int tokenDif = hostTokens . length - domainTokens . length ; if ( tokenDif < 0 ) { return false ; } for ( int i = domainTokens . length - 1 ; i >= 0 ; i -- ) { if ( ! domainTokens [ i ] . equalsIgnoreCase ( hostTokens [ i + tokenDif ] ) ) { return false ; } } return true ; } catch ( Exception e ) { return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compose unique key to store and access robot rules in cache for given URL [CODESPLIT] protected static String getCacheKey ( URL url ) { String protocol = url . getProtocol ( ) . toLowerCase ( Locale . ROOT ) ; String host = url . getHost ( ) . toLowerCase ( Locale . ROOT ) ; int port = url . getPort ( ) ; if ( port == - 1 ) { port = url . getDefaultPort ( ) ; } /*\n         * Robot rules apply only to host, protocol, and port where robots.txt\n         * is hosted (cf. NUTCH-1752). Consequently\n         */ return protocol + \":\" + host + \":\" + port ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the robots rules from the cache or empty rules if not found [CODESPLIT] public BaseRobotRules getRobotRulesSetFromCache ( URL url ) { String cacheKey = getCacheKey ( url ) ; BaseRobotRules robotRules = CACHE . getIfPresent ( cacheKey ) ; if ( robotRules != null ) { return robotRules ; } return EMPTY_RULES ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the rules from robots . txt which applies for the given { @code url } . Robot rules are cached for a unique combination of host protocol and port . If no rules are found in the cache a HTTP request is send to fetch {{ protocol : // host : port / robots . txt }} . The robots . txt is then parsed and the rules are cached to avoid re - fetching and re - parsing it again . [CODESPLIT] @ Override public BaseRobotRules getRobotRulesSet ( Protocol http , URL url ) { String cacheKey = getCacheKey ( url ) ; // check in the error cache first BaseRobotRules robotRules = ERRORCACHE . getIfPresent ( cacheKey ) ; if ( robotRules != null ) { return robotRules ; } // now try the proper cache robotRules = CACHE . getIfPresent ( cacheKey ) ; if ( robotRules != null ) { return robotRules ; } boolean cacheRule = true ; URL redir = null ; String keyredir = null ; LOG . debug ( \"Cache miss {} for {}\" , cacheKey , url ) ; List < Integer > bytesFetched = new LinkedList <> ( ) ; try { ProtocolResponse response = http . getProtocolOutput ( new URL ( url , \"/robots.txt\" ) . toString ( ) , Metadata . empty ) ; int code = response . getStatusCode ( ) ; bytesFetched . add ( response . getContent ( ) != null ? response . getContent ( ) . length : 0 ) ; // try one level of redirection ? if ( code == 301 || code == 302 || code == 307 || code == 308 ) { String redirection = response . getMetadata ( ) . getFirstValue ( HttpHeaders . LOCATION ) ; if ( StringUtils . isNotBlank ( redirection ) ) { if ( ! redirection . startsWith ( \"http\" ) ) { // RFC says it should be absolute, but apparently it // isn't redir = new URL ( url , redirection ) ; } else { redir = new URL ( redirection ) ; } // try from the cache keyredir = getCacheKey ( redir ) ; if ( cacheKey . equalsIgnoreCase ( keyredir ) ) { keyredir = null ; } else { RobotRules cachedRediRobotRules = CACHE . getIfPresent ( keyredir ) ; if ( cachedRediRobotRules != null ) { // cache also for the redirected host // but only if the robots.txt file is at the root if ( redir . getPath ( ) . equals ( \"/robots.txt\" ) ) { LOG . debug ( \"Caching robots for {} under key {} in cache\" , redir , keyredir ) ; CACHE . put ( keyredir , cachedRediRobotRules ) ; } return cachedRediRobotRules ; } } response = http . getProtocolOutput ( redir . toString ( ) , Metadata . empty ) ; code = response . getStatusCode ( ) ; bytesFetched . add ( response . getContent ( ) != null ? response . getContent ( ) . length : 0 ) ; } } if ( code == 200 ) // found rules: parse them { String ct = response . getMetadata ( ) . getFirstValue ( HttpHeaders . CONTENT_TYPE ) ; robotRules = parseRules ( url . toString ( ) , response . getContent ( ) , ct , agentNames ) ; } else if ( ( code == 403 ) && ( ! allowForbidden ) ) { robotRules = FORBID_ALL_RULES ; // use forbid all } else if ( code >= 500 ) { cacheRule = false ; robotRules = EMPTY_RULES ; } else robotRules = EMPTY_RULES ; // use default rules } catch ( Throwable t ) { LOG . info ( \"Couldn't get robots.txt for {} : {}\" , url , t . toString ( ) ) ; cacheRule = false ; robotRules = EMPTY_RULES ; } Cache < String , RobotRules > cacheToUse = CACHE ; String cacheName = \"success\" ; if ( ! cacheRule ) { cacheToUse = ERRORCACHE ; cacheName = \"error\" ; } RobotRules cached = new RobotRules ( robotRules ) ; LOG . debug ( \"Caching robots for {} under key {} in cache {}\" , url , cacheKey , cacheName ) ; cacheToUse . put ( cacheKey , cached ) ; // cache robot for redirections // get here only if the target has not been found in the cache if ( keyredir != null ) { // cache also for the redirected host // but only if the robots.txt file is at the root if ( redir . getPath ( ) . equals ( \"/robots.txt\" ) ) { LOG . debug ( \"Caching robots for {} under key {} in cache {}\" , redir , keyredir , cacheName ) ; cacheToUse . put ( keyredir , cached ) ; } } RobotRules live = new RobotRules ( robotRules ) ; live . setContentLengthFetched ( Ints . toArray ( bytesFetched ) ) ; return live ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called by the parser bolts [CODESPLIT] public void extractMetaTags ( DocumentFragment doc ) throws XPathExpressionException { NodeList nodes = ( NodeList ) expression . evaluate ( doc , XPathConstants . NODESET ) ; if ( nodes == null ) return ; int numNodes = nodes . getLength ( ) ; for ( int i = 0 ; i < numNodes ; i ++ ) { Node n = ( Node ) nodes . item ( i ) ; // iterate on the attributes // and check that it has name=robots and content // whatever the case is boolean isRobots = false ; String content = null ; NamedNodeMap attrs = n . getAttributes ( ) ; for ( int att = 0 ; att < attrs . getLength ( ) ; att ++ ) { Node keyval = attrs . item ( att ) ; if ( \"name\" . equalsIgnoreCase ( keyval . getNodeName ( ) ) && \"robots\" . equalsIgnoreCase ( keyval . getNodeValue ( ) ) ) { isRobots = true ; continue ; } if ( \"content\" . equalsIgnoreCase ( keyval . getNodeName ( ) ) ) { content = keyval . getNodeValue ( ) ; continue ; } } if ( isRobots && content != null ) { // got a value - split it String [ ] vals = content . split ( \" *, *\" ) ; parseValues ( vals ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts meta tags based on the value of the content attribute * [CODESPLIT] public void extractMetaTags ( String content ) { if ( content == null ) return ; String [ ] vals = content . split ( \" *, *\" ) ; parseValues ( vals ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a normalised representation of the directives in the metadata * [CODESPLIT] public void normaliseToMetadata ( Metadata metadata ) { metadata . setValue ( ROBOTS_NO_INDEX , Boolean . toString ( noIndex ) ) ; metadata . setValue ( ROBOTS_NO_CACHE , Boolean . toString ( noCache ) ) ; metadata . setValue ( ROBOTS_NO_FOLLOW , Boolean . toString ( noFollow ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Must be called by extending classes to store and collect in one go [CODESPLIT] protected final void ack ( Tuple t , String url ) { // keep the URL in the cache if ( useCache ) { cache . put ( url , \"\" ) ; } _collector . ack ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try the rules from the hostname domain name metadata and global scopes in this order . Returns true if the URL should be removed false otherwise . The value returns the value of the first matching rule be it positive or negative . [CODESPLIT] public boolean filter ( String url , Metadata metadata ) throws MalformedURLException { URL u = new URL ( url ) ; // first try the full hostname String hostname = u . getHost ( ) ; if ( checkScope ( hostNameRules . get ( hostname ) , u ) ) { return true ; } // then on the various components of the domain String [ ] domainParts = hostname . split ( \"\\\\.\" ) ; String domain = null ; for ( int i = domainParts . length - 1 ; i >= 0 ; i -- ) { domain = domainParts [ i ] + ( domain == null ? \"\" : \".\" + domain ) ; if ( checkScope ( domainRules . get ( domain ) , u ) ) { return true ; } } // check on parent's URL metadata for ( MDScope scope : metadataRules ) { String [ ] vals = metadata . getValues ( scope . getKey ( ) ) ; if ( vals == null ) { continue ; } for ( String v : vals ) { if ( v . equalsIgnoreCase ( scope . getValue ( ) ) ) { FastURLFilter . LOG . debug ( \"Filtering {} matching metadata {}:{}\" , url , scope . getKey ( ) , scope . getValue ( ) ) ; if ( checkScope ( scope , u ) ) { return true ; } } } } if ( checkScope ( globalRules , u ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function does the replacements by iterating through all the regex patterns . It accepts a string url as input and returns the altered string . If the normalized url is an empty string the function will return null . [CODESPLIT] @ Override public String filter ( URL sourceUrl , Metadata sourceMetadata , String urlString ) { Iterator < Rule > i = rules . iterator ( ) ; while ( i . hasNext ( ) ) { Rule r = i . next ( ) ; Matcher matcher = r . pattern . matcher ( urlString ) ; urlString = matcher . replaceAll ( r . substitution ) ; } if ( urlString . equals ( \"\" ) ) { urlString = null ; } return urlString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates a List of Rules off of JsonNode . [CODESPLIT] private List < Rule > readRules ( ArrayNode rulesList ) { List < Rule > rules = new ArrayList <> ( ) ; for ( JsonNode regexNode : rulesList ) { if ( regexNode == null || regexNode . isNull ( ) ) { LOG . warn ( \"bad config: 'regex' element is null\" ) ; continue ; } JsonNode patternNode = regexNode . get ( \"pattern\" ) ; JsonNode substitutionNode = regexNode . get ( \"substitution\" ) ; String substitutionValue = \"\" ; if ( substitutionNode != null ) { substitutionValue = substitutionNode . asText ( ) ; } if ( patternNode != null && StringUtils . isNotBlank ( patternNode . asText ( ) ) ) { Rule rule = createRule ( patternNode . asText ( ) , substitutionValue ) ; if ( rule != null ) { rules . add ( rule ) ; } } } if ( rules . size ( ) == 0 ) { rules = EMPTY_RULES ; } return rules ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the configuration file and populates a List of Rules . [CODESPLIT] private List < Rule > readRules ( String rulesFile ) { try { InputStream regexStream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( rulesFile ) ; Reader reader = new InputStreamReader ( regexStream , StandardCharsets . UTF_8 ) ; return readConfiguration ( reader ) ; } catch ( Exception e ) { LOG . error ( \"Error loading rules from file: {}\" , e ) ; return EMPTY_RULES ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Basic filter to remove query parameters from urls so parameters that don t change the content of the page can be removed . An example would be a google analytics query parameter like utm_campaign which might have several different values for a url that points to the same content . This is also called when removing attributes where the value is a hash . [CODESPLIT] private String processQueryElements ( String urlToFilter ) { try { // Handle illegal characters by making a url first // this will clean illegal characters like | URL url = new URL ( urlToFilter ) ; String query = url . getQuery ( ) ; String path = url . getPath ( ) ; // check if the last element of the path contains parameters // if so convert them to query elements if ( path . contains ( \";\" ) ) { String [ ] pathElements = path . split ( \"/\" ) ; String last = pathElements [ pathElements . length - 1 ] ; // replace last value by part without params int semicolon = last . indexOf ( \";\" ) ; if ( semicolon != - 1 ) { pathElements [ pathElements . length - 1 ] = last . substring ( 0 , semicolon ) ; String params = last . substring ( semicolon + 1 ) . replaceAll ( \";\" , \"&\" ) ; if ( query == null ) { query = params ; } else { query += \"&\" + params ; } // rebuild the path StringBuilder newPath = new StringBuilder ( ) ; for ( String p : pathElements ) { if ( StringUtils . isNotBlank ( p ) ) { newPath . append ( \"/\" ) . append ( p ) ; } } path = newPath . toString ( ) ; } } if ( StringUtils . isEmpty ( query ) ) { return urlToFilter ; } List < NameValuePair > pairs = URLEncodedUtils . parse ( query , StandardCharsets . UTF_8 ) ; Iterator < NameValuePair > pairsIterator = pairs . iterator ( ) ; while ( pairsIterator . hasNext ( ) ) { NameValuePair param = pairsIterator . next ( ) ; if ( queryElementsToRemove . contains ( param . getName ( ) ) ) { pairsIterator . remove ( ) ; } else if ( removeHashes && param . getValue ( ) != null ) { Matcher m = thirtytwobithash . matcher ( param . getValue ( ) ) ; if ( m . matches ( ) ) { pairsIterator . remove ( ) ; } } } StringBuilder newFile = new StringBuilder ( ) ; if ( StringUtils . isNotBlank ( path ) ) { newFile . append ( path ) ; } if ( ! pairs . isEmpty ( ) ) { Collections . sort ( pairs , comp ) ; String newQueryString = URLEncodedUtils . format ( pairs , StandardCharsets . UTF_8 ) ; newFile . append ( ' ' ) . append ( newQueryString ) ; } if ( url . getRef ( ) != null ) { newFile . append ( ' ' ) . append ( url . getRef ( ) ) ; } return new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , newFile . toString ( ) ) . toString ( ) ; } catch ( MalformedURLException e ) { LOG . warn ( \"Invalid urlToFilter {}. {}\" , urlToFilter , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A common error to find is a query string that starts with an & instead of a ? This will fix that error . So http : // foo . com&a = b will be changed to http : // foo . com?a = b . [CODESPLIT] private String unmangleQueryString ( String urlToFilter ) { int firstAmp = urlToFilter . indexOf ( ' ' ) ; if ( firstAmp > 0 ) { int firstQuestionMark = urlToFilter . indexOf ( ' ' ) ; if ( firstQuestionMark == - 1 ) { return urlToFilter . replaceFirst ( \"&\" , \"?\" ) ; } } return urlToFilter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove % encoding from path segment in URL for characters which should be unescaped according to <a href = https : // tools . ietf . org / html / rfc3986#section - 2 . 2 > RFC3986< / a > as well as non - standard implementations of percent encoding see <https : // en . wikipedia . org / wiki / Percent - encoding#Non - standard_implementations > . [CODESPLIT] private String unescapePath ( String path ) { Matcher matcher = illegalEscapePattern . matcher ( path ) ; StringBuilder sb = null ; int end = 0 ; while ( matcher . find ( ) ) { if ( sb == null ) { sb = new StringBuilder ( ) ; } // Append everything up to this group sb . append ( path . substring ( end , matcher . start ( ) ) ) ; String group = matcher . group ( 1 ) ; int letter = Integer . valueOf ( group , 16 ) ; sb . append ( ( char ) letter ) ; end = matcher . end ( ) ; } // we got a replacement if ( sb != null ) { // append whatever is left sb . append ( path . substring ( end ) ) ; path = sb . toString ( ) ; end = 0 ; } matcher = unescapeRulePattern . matcher ( path ) ; if ( ! matcher . find ( ) ) { return path ; } sb = new StringBuilder ( ) ; // Traverse over all encoded groups do { // Append everything up to this group sb . append ( path . substring ( end , matcher . start ( ) ) ) ; // Get the integer representation of this hexadecimal encoded // character int letter = Integer . valueOf ( matcher . group ( 1 ) , 16 ) ; if ( letter < 128 && unescapedCharacters [ letter ] ) { // character should be unescaped in URLs sb . append ( ( char ) letter ) ; } else { // Append the whole sequence as uppercase sb . append ( matcher . group ( ) . toUpperCase ( Locale . ROOT ) ) ; } end = matcher . end ( ) ; } while ( matcher . find ( ) ) ; // Append the rest if there's anything left sb . append ( path . substring ( end ) ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert path segment of URL from Unicode to UTF - 8 and escape all characters which should be escaped according to <a href = https : // tools . ietf . org / html / rfc3986#section - 2 . 2 > RFC3986< / a > .. [CODESPLIT] private String escapePath ( String path ) { StringBuilder sb = new StringBuilder ( path . length ( ) ) ; // Traverse over all bytes in this URL for ( byte b : path . getBytes ( utf8 ) ) { // Is this a control character? if ( b < 33 || b == 91 || b == 92 || b == 93 || b == 124 ) { // Start escape sequence sb . append ( ' ' ) ; // Get this byte's hexadecimal representation String hex = Integer . toHexString ( b & 0xFF ) . toUpperCase ( Locale . ROOT ) ; // Do we need to prepend a zero? if ( hex . length ( ) % 2 != 0 ) { sb . append ( ' ' ) ; sb . append ( hex ) ; } else { // No, append this hexadecimal representation sb . append ( hex ) ; } } else { // No, just append this character as-is sb . append ( ( char ) b ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an S3 client given the configuration * [CODESPLIT] public static AmazonS3Client getS3Client ( Map conf ) { AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain ( ) ; AWSCredentials credentials = provider . getCredentials ( ) ; ClientConfiguration config = new ClientConfiguration ( ) ; AmazonS3Client client = new AmazonS3Client ( credentials , config ) ; String regionName = ConfUtils . getString ( conf , REGION ) ; if ( StringUtils . isNotBlank ( regionName ) ) { client . setRegion ( RegionUtils . getRegion ( regionName ) ) ; } String endpoint = ConfUtils . getString ( conf , ENDPOINT ) ; if ( StringUtils . isNotBlank ( endpoint ) ) { client . setEndpoint ( endpoint ) ; } return client ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads and configure the NavigationFilters based on the storm config if there is one otherwise returns an emptyNavigationFilters . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static NavigationFilters fromConf ( Map stormConf ) { String configfile = ConfUtils . getString ( stormConf , \"navigationfilters.config.file\" ) ; if ( StringUtils . isNotBlank ( configfile ) ) { try { return new NavigationFilters ( stormConf , configfile ) ; } catch ( IOException e ) { String message = \"Exception caught while loading the NavigationFilters from \" + configfile ; LOG . error ( message ) ; throw new RuntimeException ( message , e ) ; } } return NavigationFilters . emptyNavigationFilters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an additional record format at given position [CODESPLIT] public GzipHdfsBolt addRecordFormat ( RecordFormat format , int position ) { MultipleRecordFormat formats ; if ( this . format == null ) { formats = new MultipleRecordFormat ( format ) ; this . format = formats ; } else { if ( this . format instanceof MultipleRecordFormat ) { formats = ( MultipleRecordFormat ) this . format ; } else { formats = new MultipleRecordFormat ( this . format ) ; this . format = formats ; } formats . addFormat ( new GzippedRecordFormat ( format ) , position ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the amount of time to wait if the backend was queried too recently and needs throttling or - 1 if the backend can be queried straight away . [CODESPLIT] private long throttleQueries ( ) { if ( timeLastQuerySent != 0 ) { // check that we allowed some time between queries long difference = System . currentTimeMillis ( ) - timeLastQuerySent ; if ( difference < minDelayBetweenQueries ) { return minDelayBetweenQueries - difference ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates whether enough time has elapsed since receiving the results of the previous query so that a new one can be sent even if the buffer is not empty . Applies to asynchronous clients only . [CODESPLIT] private boolean triggerQueries ( ) { if ( timeLastQueryReceived != 0 && maxDelayBetweenQueries > 0 ) { // check that we allowed some time between queries long difference = System . currentTimeMillis ( ) - timeLastQueryReceived ; if ( difference > maxDelayBetweenQueries ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads and configure the ParseFilters based on the storm config if there is one otherwise returns an emptyParseFilter . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static ParseFilters fromConf ( Map stormConf ) { String parseconfigfile = ConfUtils . getString ( stormConf , \"parsefilters.config.file\" ) ; if ( StringUtils . isNotBlank ( parseconfigfile ) ) { try { return new ParseFilters ( stormConf , parseconfigfile ) ; } catch ( IOException e ) { String message = \"Exception caught while loading the ParseFilters from \" + parseconfigfile ; LOG . error ( message ) ; throw new RuntimeException ( message , e ) ; } } return ParseFilters . emptyParseFilter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a node to the current container . [CODESPLIT] protected void append ( Node newNode ) throws org . xml . sax . SAXException { Node currentNode = m_currentNode ; if ( null != currentNode ) { currentNode . appendChild ( newNode ) ; // System.out.println(newNode.getNodeName()); } else if ( null != m_docFrag ) { m_docFrag . appendChild ( newNode ) ; } else { boolean ok = true ; short type = newNode . getNodeType ( ) ; if ( type == Node . TEXT_NODE ) { String data = newNode . getNodeValue ( ) ; if ( ( null != data ) && ( data . trim ( ) . length ( ) > 0 ) ) { throw new org . xml . sax . SAXException ( \"Warning: can't output text before document element!  Ignoring...\" ) ; } ok = false ; } else if ( type == Node . ELEMENT_NODE ) { if ( m_doc . getDocumentElement ( ) != null ) { throw new org . xml . sax . SAXException ( \"Can't have more than one root on a DOM!\" ) ; } } if ( ok ) { m_doc . appendChild ( newNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive notification of ignorable whitespace in element content . [CODESPLIT] @ Override public void ignorableWhitespace ( char ch [ ] , int start , int length ) throws org . xml . sax . SAXException { if ( isOutsideDocElem ( ) ) { return ; // avoid DOM006 Hierarchy request error } String s = new String ( ch , start , length ) ; append ( m_doc . createTextNode ( s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive notification of a processing instruction . [CODESPLIT] @ Override public void processingInstruction ( String target , String data ) throws org . xml . sax . SAXException { append ( m_doc . createProcessingInstruction ( target , data ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Report an XML comment anywhere in the document . [CODESPLIT] @ Override public void comment ( char ch [ ] , int start , int length ) throws org . xml . sax . SAXException { // tagsoup sometimes submits invalid values here if ( ch == null || start < 0 || length >= ( ch . length - start ) || length < 0 ) { return ; } append ( m_doc . createComment ( new String ( ch , start , length ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive notification of cdata . [CODESPLIT] public void cdata ( char ch [ ] , int start , int length ) { if ( isOutsideDocElem ( ) && XMLCharacterRecognizer . isWhiteSpace ( ch , start , length ) ) { return ; // avoid DOM006 Hierarchy request error } String s = new String ( ch , start , length ) ; // XXX ab@apache.org: modified from the original, to accomodate TagSoup. Node n = m_currentNode . getLastChild ( ) ; if ( n instanceof CDATASection ) { ( ( CDATASection ) n ) . appendData ( s ) ; } else if ( n instanceof Comment ) { ( ( Comment ) n ) . appendData ( s ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Report the start of DTD declarations if any . [CODESPLIT] @ Override public void startDTD ( String name , String publicId , String systemId ) throws org . xml . sax . SAXException { // Do nothing for now. }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Begin the scope of a prefix - URI Namespace mapping . [CODESPLIT] @ Override public void startPrefixMapping ( String prefix , String uri ) throws org . xml . sax . SAXException { /*\n         * // Not sure if this is needed or wanted // Also, it fails in the\n         * stree. if((null != m_currentNode) && (m_currentNode.getNodeType() ==\n         * Node.ELEMENT_NODE)) { String qname; if(((null != prefix) &&\n         * (prefix.length() == 0)) || (null == prefix)) qname = \"xmlns\"; else\n         * qname = \"xmlns:\"+prefix;\n         * \n         * Element elem = (Element)m_currentNode; String val =\n         * elem.getAttribute(qname); // Obsolete, should be DOM2...? if(val ==\n         * null) { elem.setAttributeNS(\"http://www.w3.org/XML/1998/namespace\",\n         * qname, uri); } }\n         */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the { [CODESPLIT] public void setConf ( Config conf ) { // Grab the agent names we advertise to robots files. String agentName = ConfUtils . getString ( conf , \"http.agent.name\" ) ; if ( null == agentName ) { throw new RuntimeException ( \"Agent name not configured!\" ) ; } String configuredAgentNames = ConfUtils . getString ( conf , \"http.robots.agents\" , \"\" ) ; StringTokenizer tok = new StringTokenizer ( configuredAgentNames , \",\" ) ; ArrayList < String > agents = new ArrayList <> ( ) ; while ( tok . hasMoreTokens ( ) ) { agents . add ( tok . nextToken ( ) . trim ( ) ) ; } /**\n         * If there are no agents for robots-parsing, use the default\n         * agent-string. If both are present, our agent-string should be the\n         * first one we advertise to robots-parsing.\n         */ if ( agents . isEmpty ( ) ) { LOG . info ( \"No agents listed in 'http.robots.agents' property! Using http.agent.name [{}]\" , agentName ) ; this . agentNames = agentName ; } else { int index = 0 ; if ( ( agents . get ( 0 ) ) . equalsIgnoreCase ( agentName ) ) { index ++ ; } else { LOG . info ( \"Agent we advertise ({}) not listed first in 'http.robots.agents' property!\" , agentName ) ; } StringBuilder combinedAgentsString = new StringBuilder ( agentName ) ; // append all the agents from the http.robots.agents property for ( ; index < agents . size ( ) ; index ++ ) { combinedAgentsString . append ( \", \" ) . append ( agents . get ( index ) ) ; } this . agentNames = combinedAgentsString . toString ( ) ; } String spec = ConfUtils . getString ( conf , cacheConfigParamName , \"maximumSize=10000,expireAfterWrite=6h\" ) ; CACHE = CacheBuilder . from ( spec ) . build ( ) ; spec = ConfUtils . getString ( conf , errorcacheConfigParamName , \"maximumSize=10000,expireAfterWrite=1h\" ) ; ERRORCACHE = CacheBuilder . from ( spec ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the robots content using the { @link SimpleRobotRulesParser } from crawler commons [CODESPLIT] public BaseRobotRules parseRules ( String url , byte [ ] content , String contentType , String robotName ) { return robotParser . parseContent ( url , content , contentType , robotName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether a document should be indexed based on the presence of a given key / value or the RobotsTags . ROBOTS_NO_INDEX directive . [CODESPLIT] protected boolean filterDocument ( Metadata meta ) { String noindexVal = meta . getFirstValue ( RobotsTags . ROBOTS_NO_INDEX ) ; if ( \"true\" . equalsIgnoreCase ( noindexVal ) ) return false ; if ( filterKeyValue == null ) return true ; String [ ] values = meta . getValues ( filterKeyValue [ 0 ] ) ; // key not found if ( values == null ) return false ; return ArrayUtils . contains ( values , filterKeyValue [ 1 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a mapping field name / values for the metadata to index * [CODESPLIT] protected Map < String , String [ ] > filterMetadata ( Metadata meta ) { Pattern indexValuePattern = Pattern . compile ( \"\\\\[(\\\\d+)\\\\]\" ) ; Map < String , String [ ] > fieldVals = new HashMap <> ( ) ; Iterator < Entry < String , String > > iter = metadata2field . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Entry < String , String > entry = iter . next ( ) ; // check whether we want a specific value or all of them? int index = - 1 ; String key = entry . getKey ( ) ; Matcher match = indexValuePattern . matcher ( key ) ; if ( match . find ( ) ) { index = Integer . parseInt ( match . group ( 1 ) ) ; key = key . substring ( 0 , match . start ( ) ) ; } String [ ] values = meta . getValues ( key ) ; // not found if ( values == null || values . length == 0 ) continue ; // want a value index that it outside the range given if ( index >= values . length ) continue ; // store all values available if ( index == - 1 ) fieldVals . put ( entry . getValue ( ) , values ) ; // or only the one we want else fieldVals . put ( entry . getValue ( ) , new String [ ] { values [ index ] } ) ; } return fieldVals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to be used as the URL for indexing purposes if present the canonical value is used instead [CODESPLIT] protected String valueForURL ( Tuple tuple ) { String url = tuple . getStringByField ( \"url\" ) ; Metadata metadata = ( Metadata ) tuple . getValueByField ( \"metadata\" ) ; // functionality deactivated if ( StringUtils . isBlank ( canonicalMetadataParamName ) ) { return url ; } String canonicalValue = metadata . getFirstValue ( canonicalMetadataName ) ; // no value found? if ( StringUtils . isBlank ( canonicalValue ) ) { return url ; } try { URL sURL = new URL ( url ) ; URL canonical = URLUtil . resolveURL ( sURL , canonicalValue ) ; String sDomain = PaidLevelDomain . getPLD ( sURL . getHost ( ) ) ; String canonicalDomain = PaidLevelDomain . getPLD ( canonical . getHost ( ) ) ; // check that the domain is the same if ( sDomain . equalsIgnoreCase ( canonicalDomain ) ) { return canonical . toExternalForm ( ) ; } else { LOG . info ( \"Canonical URL references a different domain, ignoring in {} \" , url ) ; } } catch ( MalformedURLException e ) { LOG . error ( \"Malformed canonical URL {} was found in {} \" , canonicalValue , url ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a trimmed string or the original one if it is below the threshold set in the configuration . [CODESPLIT] protected String trimText ( String text ) { if ( maxLengthText == - 1 ) return text ; if ( text == null ) return text ; if ( text . length ( ) <= maxLengthText ) return text ; return text . substring ( 0 , maxLengthText ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) @ Override public void init ( Map stormConf ) { defaultfetchInterval = ConfUtils . getInt ( stormConf , Constants . defaultFetchIntervalParamName , 1440 ) ; fetchErrorFetchInterval = ConfUtils . getInt ( stormConf , Constants . fetchErrorFetchIntervalParamName , 120 ) ; errorFetchInterval = ConfUtils . getInt ( stormConf , Constants . errorFetchIntervalParamName , 44640 ) ; // loads any custom key values // must be of form fetchInterval(.STATUS)?.keyname=value // e.g. fetchInterval.isFeed=true // e.g. fetchInterval.FETCH_ERROR.isFeed=true Map < String , CustomInterval > intervals = new HashMap <> ( ) ; Pattern pattern = Pattern . compile ( \"^fetchInterval(\\\\..+?)?\\\\.(.+)=(.+)\" ) ; Iterator < String > keyIter = stormConf . keySet ( ) . iterator ( ) ; while ( keyIter . hasNext ( ) ) { String key = keyIter . next ( ) ; Matcher m = pattern . matcher ( key ) ; if ( ! m . matches ( ) ) { continue ; } Status status = null ; // was a status specified? if ( m . group ( 1 ) != null ) { status = Status . valueOf ( m . group ( 1 ) . substring ( 1 ) ) ; } String mdname = m . group ( 2 ) ; String mdvalue = m . group ( 3 ) ; int customInterval = ConfUtils . getInt ( stormConf , key , - 1 ) ; if ( customInterval != - 1 ) { CustomInterval interval = intervals . get ( mdname + mdvalue ) ; if ( interval == null ) { interval = new CustomInterval ( mdname , mdvalue , status , customInterval ) ; } else { interval . setDurationForStatus ( status , customInterval ) ; } // specify particular interval for this status intervals . put ( mdname + mdvalue , interval ) ; } } customIntervals = intervals . values ( ) . toArray ( new CustomInterval [ intervals . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Date schedule ( Status status , Metadata metadata ) { int minutesIncrement = 0 ; Optional < Integer > customInterval = Optional . empty ( ) ; // try with a value set in the metadata String customInMetadata = metadata . getFirstValue ( DELAY_METADATA ) ; if ( customInMetadata != null ) { customInterval = Optional . of ( Integer . parseInt ( customInMetadata ) ) ; } // try with the rules from the configuration if ( ! customInterval . isPresent ( ) ) { customInterval = checkCustomInterval ( metadata , status ) ; } if ( customInterval . isPresent ( ) ) { minutesIncrement = customInterval . get ( ) ; } else { switch ( status ) { case FETCHED : minutesIncrement = defaultfetchInterval ; break ; case FETCH_ERROR : minutesIncrement = fetchErrorFetchInterval ; break ; case ERROR : minutesIncrement = errorFetchInterval ; break ; case REDIRECTION : minutesIncrement = defaultfetchInterval ; break ; default : // leave it to now e.g. DISCOVERED } } // a value of -1 means never fetch // we use a conventional value if ( minutesIncrement == - 1 ) { return NEVER ; } Calendar cal = Calendar . getInstance ( ) ; cal . add ( Calendar . MINUTE , minutesIncrement ) ; return cal . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first matching custom interval [CODESPLIT] protected final Optional < Integer > checkCustomInterval ( Metadata metadata , Status s ) { if ( customIntervals == null ) return Optional . empty ( ) ; for ( CustomInterval customInterval : customIntervals ) { String [ ] values = metadata . getValues ( customInterval . key ) ; if ( values == null ) { continue ; } for ( String v : values ) { if ( v . equals ( customInterval . value ) ) { return customInterval . getDurationForStatus ( s ) ; } } } return Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads and configure the URLFilters based on the storm config if there is one otherwise returns an empty URLFilter . [CODESPLIT] public static URLFilters fromConf ( Map stormConf ) { String configFile = ConfUtils . getString ( stormConf , \"urlfilters.config.file\" ) ; if ( StringUtils . isNotBlank ( configFile ) ) { try { return new URLFilters ( stormConf , configFile ) ; } catch ( IOException e ) { String message = \"Exception caught while loading the URLFilters from \" + configFile ; LOG . error ( message ) ; throw new RuntimeException ( message , e ) ; } } return URLFilters . emptyURLFilters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Scheduler instance based on the configuration * [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) public static Scheduler getInstance ( Map stormConf ) { Scheduler scheduler ; String className = ConfUtils . getString ( stormConf , schedulerClassParamName ) ; if ( StringUtils . isBlank ( className ) ) { throw new RuntimeException ( \"Missing value for config  \" + schedulerClassParamName ) ; } try { Class < ? > schedulerc = Class . forName ( className ) ; boolean interfaceOK = Scheduler . class . isAssignableFrom ( schedulerc ) ; if ( ! interfaceOK ) { throw new RuntimeException ( \"Class \" + className + \" must extend Scheduler\" ) ; } scheduler = ( Scheduler ) schedulerc . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( \"Can't instanciate \" + className ) ; } scheduler . init ( stormConf ) ; return scheduler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submits the topology with the name taken from the configuration * [CODESPLIT] protected int submit ( Config conf , TopologyBuilder builder ) { String name = ConfUtils . getString ( conf , Config . TOPOLOGY_NAME ) ; if ( StringUtils . isBlank ( name ) ) throw new RuntimeException ( \"No value found for \" + Config . TOPOLOGY_NAME ) ; return submit ( name , conf , builder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submits the topology under a specific name * [CODESPLIT] protected int submit ( String name , Config conf , TopologyBuilder builder ) { // register Metadata for serialization with FieldsSerializer Config . registerSerialization ( conf , Metadata . class ) ; if ( isLocal ) { LocalCluster cluster = new LocalCluster ( ) ; cluster . submitTopology ( name , conf , builder . createTopology ( ) ) ; if ( ttl != - 1 ) { Utils . sleep ( ttl * 1000 ) ; cluster . shutdown ( ) ; } } else { try { StormSubmitter . submitTopology ( name , conf , builder . createTopology ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return - 1 ; } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts excel rows into a list of objects [CODESPLIT] public static synchronized < T > List < T > fromExcel ( final File file , final Class < T > type ) { final ArrayList < T > list = new ArrayList <> ( ) ; fromExcel ( file , type , list :: add ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts excel rows into a list of objects [CODESPLIT] public static synchronized < T > void fromExcel ( final File file , final Class < T > type , final Consumer < ? super T > consumer ) { final Unmarshaller unmarshaller = deserializer ( file , PoijiOptionsBuilder . settings ( ) . build ( ) ) ; unmarshaller . unmarshal ( type , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts excel rows into a list of objects [CODESPLIT] public static synchronized < T > List < T > fromExcel ( final InputStream inputStream , PoijiExcelType excelType , final Class < T > type ) { final ArrayList < T > list = new ArrayList <> ( ) ; fromExcel ( inputStream , excelType , type , list :: add ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts excel rows into a list of objects [CODESPLIT] public static synchronized < T > void fromExcel ( final InputStream inputStream , PoijiExcelType excelType , final Class < T > type , final Consumer < ? super T > consumer ) { Objects . requireNonNull ( excelType ) ; final Unmarshaller unmarshaller = deserializer ( inputStream , excelType , PoijiOptionsBuilder . settings ( ) . build ( ) ) ; unmarshaller . unmarshal ( type , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts excel rows into a list of objects [CODESPLIT] public static synchronized < T > void fromExcel ( final File file , final Class < T > type , final PoijiOptions options , final Consumer < ? super T > consumer ) { final Unmarshaller unmarshaller = deserializer ( file , options ) ; unmarshaller . unmarshal ( type , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts excel rows into a list of objects [CODESPLIT] public static synchronized < T > List < T > fromExcel ( final InputStream inputStream , final PoijiExcelType excelType , final Class < T > type , final PoijiOptions options ) { Objects . requireNonNull ( excelType ) ; final ArrayList < T > list = new ArrayList <> ( ) ; fromExcel ( inputStream , excelType , type , options , list :: add ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "converts excel rows into a list of objects [CODESPLIT] public static synchronized < T > void fromExcel ( final InputStream inputStream , final PoijiExcelType excelType , final Class < T > type , final PoijiOptions options , final Consumer < ? super T > consumer ) { Objects . requireNonNull ( excelType ) ; final Unmarshaller unmarshaller = deserializer ( inputStream , excelType , options ) ; unmarshaller . unmarshal ( type , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Using this to hold inner objects that will be mapped to the main object * [CODESPLIT] private Object getInstance ( Field field ) { Object ins = null ; try { if ( fieldInstances . containsKey ( field . getName ( ) ) ) { ins = fieldInstances . get ( field . getName ( ) ) ; } else { ins = field . getType ( ) . getDeclaredConstructor ( ) . newInstance ( ) ; fieldInstances . put ( field . getName ( ) , ins ) ; } } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e ) { throw new PoijiInstantiationException ( \"Cannot create a new instance of \" + type . getName ( ) ) ; } return ins ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Modified this method so that for each time it reads a cell it doesn t need to check all fields even after it as found the matching field [CODESPLIT] private boolean setValue ( String content , Class < ? super T > type , int column ) { // For ExcelRow annotation if ( columnToField . containsKey ( - 1 ) ) { Field field = columnToField . get ( - 1 ) ; Object o = casting . castValue ( field . getType ( ) , valueOf ( internalCount ) , options ) ; setFieldData ( field , o , instance ) ; } if ( columnToField . containsKey ( column ) ) { Field field = columnToField . get ( column ) ; if ( columnToSuperClassField . containsKey ( column ) ) { Object ins = null ; ins = getInstance ( columnToSuperClassField . get ( column ) ) ; if ( setValue ( field , column , content , ins ) ) { setFieldData ( columnToSuperClassField . get ( column ) , ins , instance ) ; return true ; } else { return false ; } } return setValue ( field , column , content , instance ) ; } for ( Field field : type . getDeclaredFields ( ) ) { ExcelRow excelRow = field . getAnnotation ( ExcelRow . class ) ; if ( excelRow != null ) { Object o = casting . castValue ( field . getType ( ) , valueOf ( internalCount ) , options ) ; setFieldData ( field , o , instance ) ; columnToField . put ( - 1 , field ) ; } ExcelCellRange range = field . getAnnotation ( ExcelCellRange . class ) ; if ( range != null ) { Object ins = null ; ins = getInstance ( field ) ; for ( Field f : field . getType ( ) . getDeclaredFields ( ) ) { if ( setValue ( f , column , content , ins ) ) { setFieldData ( field , ins , instance ) ; columnToField . put ( column , f ) ; columnToSuperClassField . put ( column , field ) ; return true ; } } } else { if ( setValue ( field , column , content , instance ) ) { columnToField . put ( column , field ) ; return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the number of items to be displayed on the wheel . [CODESPLIT] public void setWheelItemCount ( int count ) { mItemCount = count ; mItemAngle = calculateItemAngle ( count ) ; if ( mWheelBounds != null ) { invalidate ( ) ; //TODO ? } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Taken and modified from Android Source for API < 11 [CODESPLIT] public static int resolveSizeAndState ( int size , int measureSpec ) { int result = size ; int specMode = MeasureSpec . getMode ( measureSpec ) ; int specSize = MeasureSpec . getSize ( measureSpec ) ; switch ( specMode ) { case MeasureSpec . UNSPECIFIED : result = size ; break ; case MeasureSpec . AT_MOST : if ( specSize < size ) { result = specSize ; } else { result = size ; } break ; case MeasureSpec . EXACTLY : result = specSize ; break ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the wheel s drawable that can also rotate with the items . < / p > <p > Note if the drawable has infinite lines of symmetry then you should set the wheel drawable to not rotate see { @link #setWheelDrawableRotatable ( boolean ) } . In other words if the drawable doesn t look any different whilst it is rotating you should improve the performance by disabling the drawable from rotating . < / p > [CODESPLIT] public void setWheelDrawable ( Drawable drawable ) { mWheelDrawable = drawable ; if ( mWheelBounds != null ) { mWheelDrawable . setBounds ( mWheelBounds . getBoundingRect ( ) ) ; invalidate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the empty item drawable that is drawn when outside of the adapter range . [CODESPLIT] public void setEmptyItemDrawable ( Drawable drawable ) { mEmptyItemDrawable = drawable ; EMPTY_CACHE_ITEM . mDrawable = drawable ; if ( mWheelBounds != null ) { invalidate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the angle of the wheel instantaneously . Note this does not animate to the provided angle . [CODESPLIT] public void setAngle ( float angle ) { mAngle = angle ; updateSelectedPosition ( ) ; if ( mOnAngleChangeListener != null ) { mOnAngleChangeListener . onWheelAngleChange ( mAngle ) ; } invalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the selectedPosition has changed . [CODESPLIT] private void updateSelectedPosition ( ) { int position = ( int ) ( ( - mAngle + - 0.5 * Math . signum ( mAngle ) * mItemAngle ) / mItemAngle ) ; setSelectedPosition ( position ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invalidate the drawable at the specific position so that the next Draw call will refresh the Drawable at this given position in the adapter . [CODESPLIT] public void invalidateWheelItemDrawable ( int position ) { int adapterPos = rawPositionToAdapterPosition ( position ) ; if ( isEmptyItemPosition ( adapterPos ) ) return ; CacheItem cacheItem = mItemCacheArray [ adapterPos ] ; if ( cacheItem != null ) cacheItem . mDirty = true ; invalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the raw position to a position within the wheel item bounds . [CODESPLIT] public int rawPositionToWheelPosition ( int position , int adapterPosition ) { int circularOffset = mIsRepeatable ? ( ( int ) Math . floor ( ( position / ( float ) mAdapterItemCount ) ) * ( mAdapterItemCount - mItemCount ) ) : 0 ; return Circle . clamp ( adapterPosition + circularOffset , mItemCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Estimates the wheel s new angle and angular velocity [CODESPLIT] private void update ( float deltaTime ) { float vel = mAngularVelocity ; float velSqr = vel * vel ; if ( vel > 0f ) { //TODO the damping is not based on time mAngularVelocity -= velSqr * VELOCITY_FRICTION_COEFFICIENT + CONSTANT_FRICTION_COEFFICIENT ; if ( mAngularVelocity < 0f ) mAngularVelocity = 0f ; } else if ( vel < 0f ) { mAngularVelocity -= velSqr * - VELOCITY_FRICTION_COEFFICIENT - CONSTANT_FRICTION_COEFFICIENT ; if ( mAngularVelocity > 0f ) mAngularVelocity = 0f ; } if ( mAngularVelocity != 0f ) { addAngle ( mAngularVelocity * deltaTime ) ; } else { mRequiresUpdate = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the materials darker contrast [CODESPLIT] private int getContrastColor ( Map . Entry < String , Integer > entry ) { String colorName = MaterialColor . getColorName ( entry ) ; return MaterialColor . getContrastColor ( colorName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clamps the value to a number between 0 and the upperLimit [CODESPLIT] static int clamp ( int value , int upperLimit ) { if ( value < 0 ) { return value + ( - 1 * ( int ) Math . floor ( value / ( float ) upperLimit ) ) * upperLimit ; } else { return value % upperLimit ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches text against a wildcard pattern where ? is single letter and * is zero or more letters . [CODESPLIT] public static boolean matches ( final String text , final String wildcard ) { String pattern = wildcard . replace ( \"?\" , \"\\\\w\" ) . replace ( \"*\" , \"\\\\w*\" ) ; return ( text != null && text . matches ( pattern ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return source loader that extracts source files [CODESPLIT] protected SourceLoader createSourceLoader ( final Job job ) { return new SourceLoaderFactory ( job . getGit ( ) . getBaseDir ( ) , project , sourceEncoding ) . withSourceDirectories ( sourceDirectories ) . withScanForSources ( scanForSources ) . createSourceLoader ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes coverage data to JSON file . [CODESPLIT] protected void writeCoveralls ( final JsonWriter writer , final SourceCallback sourceCallback , final List < CoverageParser > parsers ) throws ProcessingException , IOException { try { getLog ( ) . info ( \"Writing Coveralls data to \" + writer . getCoverallsFile ( ) . getAbsolutePath ( ) + \"...\" ) ; long now = System . currentTimeMillis ( ) ; sourceCallback . onBegin ( ) ; for ( CoverageParser parser : parsers ) { getLog ( ) . info ( \"Processing coverage report from \" + parser . getCoverageFile ( ) . getAbsolutePath ( ) ) ; parser . parse ( sourceCallback ) ; } sourceCallback . onComplete ( ) ; long duration = System . currentTimeMillis ( ) - now ; getLog ( ) . info ( \"Successfully wrote Coveralls data in \" + duration + \"ms\" ) ; } finally { writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * create new ArrayChar with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayChar factory ( Index index , char [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayChar . D0 ( index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayChar . D1 ( index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayChar . D2 ( index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayChar . D3 ( index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayChar . D4 ( index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayChar . D5 ( index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayChar . D6 ( index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayChar . D7 ( index , storage ) ; } else { return new ArrayChar ( index , storage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { char [ ] ja = ( char [ ] ) javaArray ; for ( char aJa : ja ) iter . setCharNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trasfer data to a ByteBuffer . Note we cast char to byte discarding top byte if any . This is because CDM char is really a byte not a java char . [CODESPLIT] @ Override public ByteBuffer getDataAsByteBuffer ( ) { ByteBuffer bb = ByteBuffer . allocate ( ( int ) getSize ( ) ) ; resetLocalIterator ( ) ; while ( hasNext ( ) ) bb . put ( nextByte ( ) ) ; return bb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a String out of this rank one ArrayChar object . If there is a null ( 0 ) value in the ArrayChar array the String will end there . The null is not returned as part of the String . [CODESPLIT] public String getString ( ) { int rank = getRank ( ) ; if ( rank == 0 ) { return new String ( storage ) ; } if ( rank != 1 ) throw new IllegalArgumentException ( \"ArayChar.getString rank must be 1\" ) ; int strLen = indexCalc . getShape ( 0 ) ; int count = 0 ; for ( int k = 0 ; k < strLen ; k ++ ) { if ( 0 == storage [ k ] ) break ; count ++ ; } return new String ( storage , 0 , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a String out of this rank two ArrayChar object . This treats the ArrayChar as a 1D array of Strings . If there is a null ( 0 ) value in the ArrayChar array the String will end there . The null is not returned as part of the String . [CODESPLIT] public String getString ( int index ) { Index ima = getIndex ( ) ; return getString ( ima . set ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a String out of this ArrayChar object . The rank must be 1 or greater . If there is a null ( 0 ) value in the ArrayChar array the String will end there . The null is not returned as part of the String . <p / > If rank = 1 then this will make a string out of the entire CharArray ignoring ima . If rank is greater than 1 then make a String out of the characters of the last dimension indexed by ima . This method treats the CharArray like an array of Strings and allows you to iterate over them eg for a 2D ArrayChar : <p > <code > ArrayChar ca ; Index ima = ca . getIndex () ; for ( int i = 0 ; i<ca . getShape () [ 0 ] ; i ++ ) String s = ca . getString ( ima . set0 ( i )) ; < / code > [CODESPLIT] public String getString ( Index ima ) { int rank = getRank ( ) ; if ( rank == 0 ) throw new IllegalArgumentException ( \"ArayChar.getString rank must not be 0\" ) ; if ( rank == 1 ) return getString ( ) ; int strLen = indexCalc . getShape ( rank - 1 ) ; char [ ] carray = new char [ strLen ] ; int count = 0 ; for ( int k = 0 ; k < strLen ; k ++ ) { ima . setDim ( rank - 1 , k ) ; carray [ k ] = getChar ( ima ) ; if ( 0 == carray [ k ] ) break ; count ++ ; } return new String ( carray , 0 , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the ArrayChar values from the characters in the String . Rank must be 1 . If String longer than ArrayChar ignore extra chars ; if shorter fill with 0 . [CODESPLIT] public void setString ( String val ) { int rank = getRank ( ) ; if ( rank != 1 ) throw new IllegalArgumentException ( \"ArayChar.setString rank must be 1\" ) ; int arrayLen = indexCalc . getShape ( 0 ) ; int strLen = Math . min ( val . length ( ) , arrayLen ) ; for ( int k = 0 ; k < strLen ; k ++ ) storage [ k ] = val . charAt ( k ) ; char c = 0 ; for ( int k = strLen ; k < arrayLen ; k ++ ) storage [ k ] = ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the ArrayChar values from the characters in the String . Rank must be 2 . This treats the ArrayChar as a 1D array of Strings . If String val longer than ArrayChar ignore extra chars ; if shorter fill with 0 . <p / > <p > <code > String [] val = new String [ n ] ; ArrayChar ca ; Index ima = ca . getIndex () ; for ( int i = 0 ; i<n ; i ++ ) ca . setString ( i val [ i ] ) ; < / code > [CODESPLIT] public void setString ( int index , String val ) { int rank = getRank ( ) ; if ( rank != 2 ) throw new IllegalArgumentException ( \"ArrayChar.setString rank must be 2\" ) ; Index ima = getIndex ( ) ; setString ( ima . set ( index ) , val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the ArrayChar values from the characters in the String . Rank must be 1 or greater . If String longer than ArrayChar ignore extra chars ; if shorter fill with 0 . If rank 1 set entire ArrayChar ignoring ima . If rank > 1 treat the ArrayChar like an array of Strings of rank - 1 and set the row indexed by ima . For example rank 3 : <p > <code > String [] [] val ; ArrayChar ca ; Index ima = ca . getIndex () ; int rank0 = ca . getShape () [ 0 ] ; int rank1 = ca . getShape () [ 1 ] ; <p / > for ( int i = 0 ; i<rank0 ; i ++ ) for ( int j = 0 ; j<rank1 ; j ++ ) { ima . set ( i j ) ; ca . setString ( ima val [ i ] [ j ] ) ; } < / code > [CODESPLIT] public void setString ( Index ima , String val ) { int rank = getRank ( ) ; if ( rank == 0 ) throw new IllegalArgumentException ( \"ArrayChar.setString rank must not be 0\" ) ; int arrayLen = indexCalc . getShape ( rank - 1 ) ; int strLen = Math . min ( val . length ( ) , arrayLen ) ; int count = 0 ; for ( int k = 0 ; k < strLen ; k ++ ) { ima . setDim ( rank - 1 , k ) ; setChar ( ima , val . charAt ( k ) ) ; count ++ ; } char c = 0 ; for ( int k = count ; k < arrayLen ; k ++ ) { ima . setDim ( rank - 1 , k ) ; setChar ( ima , c ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make this into the equivilent 1D ArrayObject of Strings . [CODESPLIT] public ArrayObject make1DStringArray ( ) { int nelems = ( getRank ( ) == 0 ) ? 1 : ( int ) getSize ( ) / indexCalc . getShape ( getRank ( ) - 1 ) ; Array sarr = Array . factory ( DataType . STRING , new int [ ] { nelems } ) ; IndexIterator newsiter = sarr . getIndexIterator ( ) ; ArrayChar . StringIterator siter = getStringIterator ( ) ; while ( siter . hasNext ( ) ) { newsiter . setObjectNext ( siter . next ( ) ) ; } return ( ArrayObject ) sarr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ArrayChar from a String [CODESPLIT] public static ArrayChar makeFromString ( String s , int max ) { ArrayChar result = new ArrayChar . D1 ( max ) ; for ( int i = 0 ; i < max && i < s . length ( ) ; i ++ ) result . setChar ( i , s . charAt ( i ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ArrayChar from an ArrayObject of Strings . [CODESPLIT] public static ArrayChar makeFromStringArray ( ArrayObject values ) { // find longest string\r IndexIterator ii = values . getIndexIterator ( ) ; int strlen = 0 ; while ( ii . hasNext ( ) ) { String s = ( String ) ii . next ( ) ; strlen = Math . max ( s . length ( ) , strlen ) ; } return makeFromStringArray ( values , strlen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ArrayChar from an ArrayObject of Strings . Inverse of make1DStringArray . Copies the data . [CODESPLIT] public static ArrayChar makeFromStringArray ( ArrayObject values , int strlen ) { // create shape for equivilent charArray\r try { Section section = new Section ( values . getShape ( ) ) ; section . appendRange ( strlen ) ; int [ ] shape = section . getShape ( ) ; long size = section . computeSize ( ) ; // populate char array\r char [ ] cdata = new char [ ( int ) size ] ; int start = 0 ; IndexIterator ii = values . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) { String s = ( String ) ii . next ( ) ; for ( int k = 0 ; k < s . length ( ) && k < strlen ; k ++ ) cdata [ start + k ] = s . charAt ( k ) ; start += strlen ; } // ready to create the char Array\r Array carr = Array . factory ( DataType . CHAR , shape , cdata ) ; return ( ArrayChar ) carr ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; // cant happen.\r return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dot product of matrix and vector : return M dot v [CODESPLIT] public MAVector dot ( MAVector v ) { if ( ncols != v . getNelems ( ) ) throw new IllegalArgumentException ( \"MAMatrix.dot \" + ncols + \" != \" + v . getNelems ( ) ) ; ArrayDouble . D1 result = new ArrayDouble . D1 ( nrows ) ; Index imr = result . getIndex ( ) ; for ( int i = 0 ; i < nrows ; i ++ ) { double sum = 0.0 ; for ( int k = 0 ; k < ncols ; k ++ ) sum += getDouble ( i , k ) * v . getDouble ( k ) ; result . setDouble ( imr . set ( i ) , sum ) ; } return new MAVector ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matrix multiply : return m1 * m2 . [CODESPLIT] static public MAMatrix multiply ( MAMatrix m1 , MAMatrix m2 ) { if ( m1 . getNcols ( ) != m2 . getNrows ( ) ) throw new IllegalArgumentException ( \"MAMatrix.multiply \" + m1 . getNcols ( ) + \" != \" + m2 . getNrows ( ) ) ; int kdims = m1 . getNcols ( ) ; ArrayDouble . D2 result = new ArrayDouble . D2 ( m1 . getNrows ( ) , m2 . getNcols ( ) ) ; Index imr = result . getIndex ( ) ; for ( int i = 0 ; i < m1 . getNrows ( ) ; i ++ ) { for ( int j = 0 ; j < m2 . getNcols ( ) ; j ++ ) { double sum = 0.0 ; for ( int k = 0 ; k < kdims ; k ++ ) sum += m1 . getDouble ( i , k ) * m2 . getDouble ( k , j ) ; result . setDouble ( imr . set ( i , j ) , sum ) ; } } return new MAMatrix ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matrix multiply by a diagonal matrix store result in this : this = this * diag [CODESPLIT] public void postMultiplyDiagonal ( MAVector diag ) { if ( ncols != diag . getNelems ( ) ) throw new IllegalArgumentException ( \"MAMatrix.postMultiplyDiagonal \" + ncols + \" != \" + diag . getNelems ( ) ) ; for ( int i = 0 ; i < nrows ; i ++ ) { for ( int j = 0 ; j < ncols ; j ++ ) { double val = a . getDouble ( ima . set ( i , j ) ) * diag . getDouble ( j ) ; a . setDouble ( ima , val ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reference time is the start time of the first forecast other forecasts at 6 - hour intervals . Number in Ave = number of forecast used [CODESPLIT] @ Override public int [ ] getForecastTimeIntervalOffset ( Grib2Record gr ) { Grib2Pds pds = gr . getPDS ( ) ; if ( ! pds . isTimeInterval ( ) ) { return null ; } // LOOK this is hack for CFSR monthly combobulation // see http://rda.ucar.edu/datasets/ds093.2/#docs/time_ranges.html int statType = pds . getOctet ( 47 ) ; int n = pds . getInt4StartingAtOctet ( 50 ) ; int p2 = pds . getInt4StartingAtOctet ( 55 ) ; int p2mp1 = pds . getInt4StartingAtOctet ( 62 ) ; int p1 = p2 - p2mp1 ; int start , end ; switch ( statType ) { case 193 : start = p1 ; end = p1 + n * p2 ; break ; case 194 : start = 0 ; end = n * p2 ; break ; case 195 : case 204 : case 205 : start = p1 ; end = p2 ; break ; default : throw new IllegalArgumentException ( \"unknown statType \" + statType ) ; } return new int [ ] { start , end } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see http : // www . nco . ncep . noaa . gov / pmb / docs / grib2 / grib2_doc . shtml [CODESPLIT] private void initLocalTable ( ) { String tableName = config . getPath ( ) ; ClassLoader cl = this . getClass ( ) . getClassLoader ( ) ; try ( InputStream is = cl . getResourceAsStream ( tableName ) ) { if ( is == null ) { throw new IllegalStateException ( \"Cant find \" + tableName ) ; } try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( is , CDM . utf8Charset ) ) ) { while ( true ) { String line = br . readLine ( ) ; if ( line == null ) { break ; } if ( ( line . length ( ) == 0 ) || line . startsWith ( \"#\" ) ) { continue ; } String [ ] flds = StringUtil2 . splitString ( line ) ; int p1 = Integer . parseInt ( flds [ 0 ] . trim ( ) ) ; // must have a number int p2 = Integer . parseInt ( flds [ 1 ] . trim ( ) ) ; // must have a number int p3 = Integer . parseInt ( flds [ 2 ] . trim ( ) ) ; // must have a number StringBuilder b = new StringBuilder ( ) ; int count = 3 ; while ( count < flds . length && ! flds [ count ] . equals ( \".\" ) ) { b . append ( flds [ count ++ ] ) . append ( ' ' ) ; } String abbrev = b . toString ( ) . trim ( ) ; b . setLength ( 0 ) ; count ++ ; while ( count < flds . length && ! flds [ count ] . equals ( \".\" ) ) { b . append ( flds [ count ++ ] ) . append ( ' ' ) ; } String name = b . toString ( ) . trim ( ) ; b . setLength ( 0 ) ; count ++ ; while ( count < flds . length && ! flds [ count ] . equals ( \".\" ) ) { b . append ( flds [ count ++ ] ) . append ( ' ' ) ; } String unit = b . toString ( ) . trim ( ) ; Grib2Parameter s = new Grib2Parameter ( p1 , p2 , p3 , name , unit , abbrev , null ) ; local . put ( makeParamId ( p1 , p2 , p3 ) , s ) ; } } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overrides the GisFeatureRenderer draw () method to draw contours and with contour labels . [CODESPLIT] public void draw ( java . awt . Graphics2D g , AffineTransform deviceFromNormalAT ) { /* OLD WAY\n  // make & set desired font for contour label.\n  // contour label size in \"points\" is last arg\n  Font font1 = new Font(\"Helvetica\", Font.PLAIN, 25);\n  // make a transform to un-flip the font\n  AffineTransform unflip = AffineTransform.getScaleInstance(1, -1);\n  Font font = font1.deriveFont(unflip);\n  g.setFont(font);  */ /* from original GisFeatureRenderer method draw: */ g . setColor ( Color . black ) ; g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; g . setStroke ( new java . awt . BasicStroke ( 0.0f ) ) ; Rectangle2D clipRect = ( Rectangle2D ) g . getClip ( ) ; Iterator siter = getShapes ( g , deviceFromNormalAT ) ; // draw the contours while ( siter . hasNext ( ) ) { Shape s = ( Shape ) siter . next ( ) ; Rectangle2D shapeBounds = s . getBounds2D ( ) ; if ( shapeBounds . intersects ( clipRect ) ) g . draw ( s ) ; } // additional code beyond GisFeatureRenderer method draw(): // render contour value for this contour line. */ if ( ShowLabels ) { Font f = FontUtil . getStandardFont ( 10 ) . getFont ( ) ; Font saveFont = g . getFont ( ) ; // use world coordinates for position, but draw in \"normal\" coordinates // so that the symbols stay the same size AffineTransform deviceFromWorldAT = g . getTransform ( ) ; AffineTransform normalFromWorldAT ; // transform World to Normal coords: //    normalFromWorldAT = deviceFromNormalAT-1 * deviceFromWorldAT try { normalFromWorldAT = deviceFromNormalAT . createInverse ( ) ; normalFromWorldAT . concatenate ( deviceFromWorldAT ) ; } catch ( java . awt . geom . NoninvertibleTransformException e ) { System . out . println ( \" ContourFeatureRenderer: NoninvertibleTransformException on \" + deviceFromNormalAT ) ; return ; } g . setTransform ( deviceFromNormalAT ) ; // so g now wants \"normal coords\" g . setFont ( f ) ; siter = getShapes ( g , deviceFromNormalAT ) ; Iterator CViter = contourList . iterator ( ) ; Point2D worldPt = new Point2D . Double ( ) ; Point2D normalPt = new Point2D . Double ( ) ; float [ ] coords = new float [ 6 ] ; while ( siter . hasNext ( ) ) { Shape s = ( Shape ) siter . next ( ) ; double contValue = ( ( ContourFeature ) CViter . next ( ) ) . getContourValue ( ) ; // get position xpos,ypos on this contour where to put label // in current world coordinates in the current Shape s. PathIterator piter = s . getPathIterator ( null ) ; //int cs, count=-1;  original int cs , count = 12 ; while ( ! piter . isDone ( ) ) { count ++ ; if ( count % 25 == 0 ) { // for every 25th position on this path cs = piter . currentSegment ( coords ) ; if ( cs == PathIterator . SEG_MOVETO || cs == PathIterator . SEG_LINETO ) { worldPt . setLocation ( coords [ 0 ] , coords [ 1 ] ) ; normalFromWorldAT . transform ( worldPt , normalPt ) ; // convert to normal // render the contour value to the screen g . drawString ( Format . d ( contValue , 4 ) , ( int ) normalPt . getX ( ) , ( int ) normalPt . getY ( ) ) ; } } piter . next ( ) ; } // while not done } // end while shape.hasNext() // restore original transform and font g . setTransform ( deviceFromWorldAT ) ; g . setFont ( saveFont ) ; } // end if ShowLabels == true if ( Debug . isSet ( \"contour/doLabels\" ) ) { // get iterator to the class member ArrayList of GisFeature-s for ( Object aContourList : contourList ) { //ContourFeature cf = iter.next(); System . out . println ( \" ContourFeatureRenderer: contour value = \" + ( ( ContourFeature ) aContourList ) . getContourValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "show the window . [CODESPLIT] public void show ( ) { setState ( Frame . NORMAL ) ; // deiconify if needed\r super . toFront ( ) ; // need to put on event thread\r SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { IndependentWindow . super . show ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "show if not iconified [CODESPLIT] public void showIfNotIconified ( ) { if ( getState ( ) == Frame . ICONIFIED ) return ; // need to put on event thread\r SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { IndependentWindow . super . show ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all the work is here so can be called recursively [CODESPLIT] private Array readData ( ucar . nc2 . Variable v2 , long dataPos , List < Range > ranges , int [ ] levels ) throws IOException , InvalidRangeException { // Get to the proper offset and read in the data raf . seek ( dataPos ) ; int data_size = ( int ) ( raf . length ( ) - dataPos ) ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; // Turn it into an array Array array = makeArray ( data , levels , v2 . getShape ( ) ) ; return array . sectionNoReduce ( ranges ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for the compressed data read all out into a array and then parse into requested [CODESPLIT] private Array readCompressedData ( ucar . nc2 . Variable v2 , long dataPos , List < Range > ranges , int [ ] levels ) throws IOException , InvalidRangeException { // Get to the proper offset and read in the rest of the compressed data raf . seek ( dataPos ) ; int data_size = ( int ) ( raf . length ( ) - dataPos ) ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; // Send the compressed data to ImageIO (to handle PNG) ByteArrayInputStream ios = new ByteArrayInputStream ( data ) ; BufferedImage image = javax . imageio . ImageIO . read ( ios ) ; // LOOK why ImageIO ?? DataBuffer db = image . getData ( ) . getDataBuffer ( ) ; // If the image had byte data, turn into an array if ( db instanceof DataBufferByte ) { DataBufferByte dbb = ( DataBufferByte ) db ; Array array = makeArray ( dbb . getData ( ) , levels , v2 . getShape ( ) ) ; if ( levels == null ) v2 . setCachedData ( array , false ) ; return array . sectionNoReduce ( ranges ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the size of the file without writing [CODESPLIT] static public long makeSizeEstimate ( ucar . nc2 . dt . GridDataset gds , List < String > gridList , LatLonRect llbb , ProjectionRect projRect , int horizStride , Range zRange , CalendarDateRange dateRange , int stride_time , boolean addLatLon ) throws IOException , InvalidRangeException { CFGridWriter2 writer2 = new CFGridWriter2 ( ) ; return writer2 . writeOrTestSize ( gds , gridList , llbb , projRect , horizStride , zRange , dateRange , stride_time , addLatLon , true , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a netcdf / CF file from a GridDataset [CODESPLIT] static public long writeFile ( ucar . nc2 . dt . GridDataset gds , List < String > gridList , LatLonRect llbb , ProjectionRect projRect , int horizStride , Range zRange , CalendarDateRange dateRange , int stride_time , boolean addLatLon , NetcdfFileWriter writer ) throws IOException , InvalidRangeException { CFGridWriter2 writer2 = new CFGridWriter2 ( ) ; return writer2 . writeOrTestSize ( gds , gridList , llbb , projRect , horizStride , zRange , dateRange , stride_time , addLatLon , false , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write equivilent uncompressed version of the file . [CODESPLIT] private RandomAccessFile uncompress ( RandomAccessFile inputRaf , String ufilename ) throws IOException { RandomAccessFile outputRaf = new RandomAccessFile ( ufilename , \"rw\" ) ; FileLock lock ; while ( true ) { // loop waiting for the lock try { lock = outputRaf . getRandomAccessFile ( ) . getChannel ( ) . lock ( 0 , 1 , false ) ; break ; } catch ( OverlappingFileLockException oe ) { // not sure why lock() doesnt block try { Thread . sleep ( 100 ) ; // msecs } catch ( InterruptedException e1 ) { } } catch ( IOException e ) { outputRaf . close ( ) ; throw e ; } } try { inputRaf . seek ( 0 ) ; byte [ ] header = new byte [ Level2Record . FILE_HEADER_SIZE ] ; int bytesRead = inputRaf . read ( header ) ; if ( bytesRead != header . length ) { throw new IOException ( \"Error reading NEXRAD2 header -- got \" + bytesRead + \" rather than\" + header . length ) ; } outputRaf . write ( header ) ; boolean eof = false ; int numCompBytes ; byte [ ] ubuff = new byte [ 40000 ] ; byte [ ] obuff = new byte [ 40000 ] ; CBZip2InputStream cbzip2 = new CBZip2InputStream ( ) ; while ( ! eof ) { try { numCompBytes = inputRaf . readInt ( ) ; if ( numCompBytes == - 1 ) { if ( log . isDebugEnabled ( ) ) log . debug ( \"  done: numCompBytes=-1 \" ) ; break ; } } catch ( EOFException ee ) { log . debug ( \"got EOFException\" ) ; break ; // assume this is ok } if ( log . isDebugEnabled ( ) ) { log . debug ( \"reading compressed bytes \" + numCompBytes + \" input starts at \" + inputRaf . getFilePointer ( ) + \"; output starts at \" + outputRaf . getFilePointer ( ) ) ; } /*\n          * For some stupid reason, the last block seems to\n          * have the number of bytes negated.  So, we just\n          * assume that any negative number (other than -1)\n          * is the last block and go on our merry little way.\n          */ if ( numCompBytes < 0 ) { if ( log . isDebugEnabled ( ) ) log . debug ( \"last block?\" + numCompBytes ) ; numCompBytes = - numCompBytes ; eof = true ; } byte [ ] buf = new byte [ numCompBytes ] ; inputRaf . readFully ( buf ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( buf , 2 , numCompBytes - 2 ) ; //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis); cbzip2 . setStream ( bis ) ; int total = 0 ; int nread ; /*\n          while ((nread = cbzip2.read(ubuff)) != -1) {\n            dout2.write(ubuff, 0, nread);\n            total += nread;\n          }\n          */ try { while ( ( nread = cbzip2 . read ( ubuff ) ) != - 1 ) { if ( total + nread > obuff . length ) { byte [ ] temp = obuff ; obuff = new byte [ temp . length * 2 ] ; System . arraycopy ( temp , 0 , obuff , 0 , temp . length ) ; } System . arraycopy ( ubuff , 0 , obuff , total , nread ) ; total += nread ; } if ( obuff . length >= 0 ) outputRaf . write ( obuff , 0 , total ) ; } catch ( BZip2ReadException ioe ) { log . warn ( \"Nexrad2IOSP.uncompress \" , ioe ) ; } float nrecords = ( float ) ( total / 2432.0 ) ; if ( log . isDebugEnabled ( ) ) log . debug ( \"  unpacked \" + total + \" num bytes \" + nrecords + \" records; ouput ends at \" + outputRaf . getFilePointer ( ) ) ; } outputRaf . flush ( ) ; } catch ( IOException e ) { if ( outputRaf != null ) outputRaf . close ( ) ; // dont leave bad files around File ufile = new File ( ufilename ) ; if ( ufile . exists ( ) ) { if ( ! ufile . delete ( ) ) log . warn ( \"failed to delete uncompressed file (IOException)\" + ufilename ) ; } throw e ; } finally { try { if ( lock != null ) lock . release ( ) ; } catch ( IOException e ) { if ( outputRaf != null ) outputRaf . close ( ) ; throw e ; } } return outputRaf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the number of records in a grib1 file . [CODESPLIT] public static void main ( String [ ] args ) throws IOException { int count = 0 ; String file = ( args . length > 0 ) ? args [ 0 ] : \"Q:/cdmUnitTest/formats/grib1/ECMWF.hybrid.grib1\" ; RandomAccessFile raf = new RandomAccessFile ( file , \"r\" ) ; System . out . printf ( \"Read %s%n\" , raf . getLocation ( ) ) ; Grib1RecordScanner scan = new Grib1RecordScanner ( raf ) ; while ( scan . hasNext ( ) ) { scan . next ( ) ; count ++ ; } raf . close ( ) ; System . out . printf ( \"count=%d%n\" , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for constructing a UnitName from a name and a plural form of the name . [CODESPLIT] public static UnitName newUnitName ( final String name , final String plural ) throws NameException { return newUnitName ( name , plural , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for constructing a UnitName from a name a plural form of the name and a symbol . [CODESPLIT] public static UnitName newUnitName ( final String name , final String plural , final String symbol ) throws NameException { return new UnitName ( name , plural , symbol ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the plural form of a name . Regular rules are used to generate the plural form . [CODESPLIT] protected String makePlural ( final String name ) { String plural ; final int length = name . length ( ) ; final char lastChar = name . charAt ( length - 1 ) ; if ( lastChar != ' ' ) { plural = name + ( lastChar == ' ' || lastChar == ' ' || lastChar == ' ' || name . endsWith ( \"ch\" ) ? \"es\" : \"s\" ) ; } else { if ( length == 1 ) { plural = name + \"s\" ; } else { final char penultimateChar = name . charAt ( length - 2 ) ; plural = ( penultimateChar == ' ' || penultimateChar == ' ' || penultimateChar == ' ' || penultimateChar == ' ' || penultimateChar == ' ' ) ? name + \"s\" : name . substring ( 0 , length - 1 ) + \"ies\" ; } } return plural ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "choose a resolution based on # seconds [CODESPLIT] private String chooseResolution ( double time ) { if ( time < 180 ) // 3 minutes return \"secs\" ; time /= 60 ; // minutes if ( time < 180 ) // 3 hours return \"minutes\" ; time /= 60 ; // hours if ( time < 72 ) // 3 days return \"hours\" ; time /= 24 ; // days if ( time < 90 ) // 3 months return \"days\" ; time /= 30 ; // months if ( time < 36 ) // 3 years return \"months\" ; return \"years\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given date is included in this date range . The date range includes the start and end dates . [CODESPLIT] public boolean included ( Date d ) { if ( isEmpty ) return false ; if ( getStart ( ) . after ( d ) ) return false ; if ( getEnd ( ) . before ( d ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given range intersects this date range . [CODESPLIT] public boolean intersects ( Date start_want , Date end_want ) { if ( isEmpty ) return false ; if ( getStart ( ) . after ( end_want ) ) return false ; if ( getEnd ( ) . before ( start_want ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given range intersects this date range . [CODESPLIT] public boolean intersects ( DateRange other ) { return intersects ( other . getStart ( ) . getDate ( ) , other . getEnd ( ) . getDate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Intersect with another date range [CODESPLIT] public DateRange intersect ( DateRange clip ) { if ( isEmpty ) return this ; if ( clip . isEmpty ) return clip ; DateType ss = getStart ( ) ; DateType s = ss . before ( clip . getStart ( ) ) ? clip . getStart ( ) : ss ; DateType ee = getEnd ( ) ; DateType e = ee . before ( clip . getEnd ( ) ) ? ee : clip . getEnd ( ) ; return new DateRange ( s , e , null , resolution ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend this date range by the given one . [CODESPLIT] public void extend ( DateRange dr ) { boolean localEmpty = isEmpty ; if ( localEmpty || dr . getStart ( ) . before ( getStart ( ) ) ) setStart ( dr . getStart ( ) ) ; if ( localEmpty || getEnd ( ) . before ( dr . getEnd ( ) ) ) setEnd ( dr . getEnd ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend this date range by the given Date . [CODESPLIT] public void extend ( Date d ) { if ( d . before ( getStart ( ) . getDate ( ) ) ) setStart ( new DateType ( false , d ) ) ; if ( getEnd ( ) . before ( d ) ) setEnd ( new DateType ( false , d ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the starting Date . Makes useStart true . If useEnd recalculate the duration else recalculate end . [CODESPLIT] public void setStart ( DateType start ) { this . start = start ; useStart = true ; if ( useEnd ) { this . isMoving = this . start . isPresent ( ) || this . end . isPresent ( ) ; useDuration = false ; recalcDuration ( ) ; } else { this . isMoving = this . start . isPresent ( ) ; this . end = this . start . add ( duration ) ; } checkIfEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the ending Date . Makes useEnd true . If useStart recalculate the duration else recalculate start . [CODESPLIT] public void setEnd ( DateType end ) { this . end = end ; useEnd = true ; if ( useStart ) { this . isMoving = this . start . isPresent ( ) || this . end . isPresent ( ) ; useDuration = false ; recalcDuration ( ) ; } else { this . isMoving = this . end . isPresent ( ) ; this . start = this . end . subtract ( duration ) ; } checkIfEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the duration of the interval . Makes useDuration true . If useStart recalculate end else recalculate start . [CODESPLIT] public void setDuration ( TimeDuration duration ) { this . duration = duration ; useDuration = true ; if ( useStart ) { this . isMoving = this . start . isPresent ( ) ; this . end = this . start . add ( duration ) ; useEnd = false ; } else { this . isMoving = this . end . isPresent ( ) ; this . start = this . end . subtract ( duration ) ; } checkIfEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assumes not moving [CODESPLIT] private void recalcDuration ( ) { long min = getStart ( ) . getDate ( ) . getTime ( ) ; long max = getEnd ( ) . getDate ( ) . getTime ( ) ; double secs = .001 * ( max - min ) ; if ( secs < 0 ) secs = 0 ; if ( duration == null ) { try { duration = new TimeDuration ( chooseResolution ( secs ) ) ; } catch ( ParseException e ) { // cant happen throw new RuntimeException ( e ) ; } } if ( resolution == null ) { duration . setValueInSeconds ( secs ) ; } else { // make it a multiple of resolution double resSecs = resolution . getValueInSeconds ( ) ; double closest = Math . round ( secs / resSecs ) ; secs = closest * resSecs ; duration . setValueInSeconds ( secs ) ; } hashCode = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save all data in the PersistentStore [CODESPLIT] public void storePersistentData ( ) { store . putInt ( \"vertSplit\" , splitDraw . getDividerLocation ( ) ) ; store . putBoolean ( \"navToolbarAction\" , ( ( Boolean ) navToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( \"moveToolbarAction\" , ( ( Boolean ) moveToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; if ( projManager != null ) projManager . storePersistentData ( ) ; /* if (csManager != null)\r\n      csManager.storePersistentData();\r\n    if (sysConfigDialog != null)\r\n      sysConfigDialog.storePersistentData(); */ dsTable . save ( ) ; dsTable . getPrefs ( ) . putBeanObject ( \"DialogBounds\" , dsDialog . getBounds ( ) ) ; store . put ( GEOTIFF_FILECHOOSER_DEFAULTDIR , geotiffFileChooser . getCurrentDirectory ( ) ) ; controller . storePersistentData ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a MapBean to the User Interface [CODESPLIT] public void addMapBean ( MapBean mb ) { mapBeanMenu . addAction ( mb . getActionDesc ( ) , mb . getIcon ( ) , mb . getAction ( ) ) ; // first one is the \"default\"\r if ( mapBeanCount == 0 ) { setMapRenderer ( mb . getRenderer ( ) ) ; } mapBeanCount ++ ; mb . addPropertyChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( java . beans . PropertyChangeEvent e ) { if ( e . getPropertyName ( ) . equals ( \"Renderer\" ) ) { setMapRenderer ( ( Renderer ) e . getNewValue ( ) ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "actions that control the dataset [CODESPLIT] private void makeActionsDataset ( ) { // choose local dataset\r AbstractAction chooseLocalDatasetAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { String filename = fileChooser . chooseFilename ( ) ; if ( filename == null ) return ; Dataset invDs ; try { invDs = Dataset . makeStandalone ( filename , FeatureType . GRID . toString ( ) , \"\" , ServiceType . File . toString ( ) ) ; } catch ( Exception ue ) { JOptionPane . showMessageDialog ( GridUI . this , \"Invalid filename = <\" + filename + \">\\n\" + ue . getMessage ( ) ) ; ue . printStackTrace ( ) ; return ; } setDataset ( invDs ) ; } } ; BAMutil . setActionProperties ( chooseLocalDatasetAction , \"FileChooser\" , \"open Local dataset...\" , false , ' ' , - 1 ) ; /* saveDatasetAction = new AbstractAction() {\r\n      public void actionPerformed(ActionEvent e) {\r\n        String fname = controller.getDatasetName();\r\n        if (fname != null) {\r\n          savedDatasetList.add( fname);\r\n          BAMutil.addActionToMenu( savedDatasetMenu, new DatasetAction( fname), 0);\r\n        }\r\n      }\r\n    };\r\n    BAMutil.setActionProperties( saveDatasetAction, null, \"save dataset\", false, 'S', 0);\r\n    */ // Configure\r chooseProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) . setVisible ( ) ; } } ; BAMutil . setActionProperties ( chooseProjectionAction , null , \"Projection Manager...\" , false , ' ' , 0 ) ; saveCurrentProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) ; // set the bounding box\r ProjectionImpl proj = panz . getProjectionImpl ( ) . constructCopy ( ) ; proj . setDefaultMapArea ( panz . getMapArea ( ) ) ; //if (debug) System.out.println(\" GV save projection \"+ proj);\r // projManage.setMap(renderAll.get(\"Map\"));   LOOK!\r //projManager.saveProjection( proj);\r } } ; BAMutil . setActionProperties ( saveCurrentProjectionAction , null , \"save Current Projection\" , false , ' ' , 0 ) ; /* chooseColorScaleAction = new AbstractAction() {\r\n      public void actionPerformed(ActionEvent e) {\r\n        if (null == csManager) // lazy instantiation\r\n          makeColorScaleManager();\r\n        csManager.show();\r\n      }\r\n    };\r\n    BAMutil.setActionProperties( chooseColorScaleAction, null, \"ColorScale Manager...\", false, 'C', 0);\r\n\r\n    */ // redraw\r redrawAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { repaint ( ) ; controller . start ( true ) ; controller . draw ( true ) ; } } ; BAMutil . setActionProperties ( redrawAction , \"alien\" , \"RedRaw\" , false , ' ' , 0 ) ; showDatasetInfoAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( infoWindow == null ) { datasetInfoTA = new TextHistoryPane ( ) ; infoWindow = new IndependentWindow ( \"Dataset Information\" , BAMutil . getImage ( \"GDVs\" ) , datasetInfoTA ) ; infoWindow . setSize ( 700 , 700 ) ; infoWindow . setLocation ( 100 , 100 ) ; } datasetInfoTA . clear ( ) ; datasetInfoTA . appendLine ( controller . getDatasetInfo ( ) ) ; datasetInfoTA . gotoTop ( ) ; infoWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showDatasetInfoAction , \"Information\" , \"Show info...\" , false , ' ' , - 1 ) ; showNcMLAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( ncmlWindow == null ) { ncmlTA = new TextHistoryPane ( ) ; ncmlWindow = new IndependentWindow ( \"Dataset NcML\" , BAMutil . getImage ( \"GDVs\" ) , ncmlTA ) ; ncmlWindow . setSize ( 700 , 700 ) ; ncmlWindow . setLocation ( 200 , 70 ) ; } ncmlTA . clear ( ) ; //datasetInfoTA.appendLine( \"GeoGrid XML for \"+ controller.getDatasetName()+\"\\n\");\r ncmlTA . appendLine ( controller . getNcML ( ) ) ; ncmlTA . gotoTop ( ) ; ncmlWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showNcMLAction , null , \"Show NcML...\" , false , ' ' , - 1 ) ; showGridDatasetInfoAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( ncmlWindow == null ) { ncmlTA = new TextHistoryPane ( ) ; ncmlWindow = new IndependentWindow ( \"Dataset NcML\" , BAMutil . getImage ( \"GDVs\" ) , ncmlTA ) ; ncmlWindow . setSize ( 700 , 700 ) ; ncmlWindow . setLocation ( 200 , 70 ) ; } ncmlTA . clear ( ) ; //datasetInfoTA.appendLine( \"GeoGrid XML for \"+ controller.getDatasetName()+\"\\n\");\r ncmlTA . appendLine ( controller . getDatasetXML ( ) ) ; ncmlTA . gotoTop ( ) ; ncmlWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showGridDatasetInfoAction , null , \"Show GridDataset Info XML...\" , false , ' ' , - 1 ) ; // show gridTable\r showGridTableAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { gtWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showGridTableAction , \"Table\" , \"grid Table...\" , false , ' ' , - 1 ) ; // show netcdf dataset Table\r showNetcdfDatasetAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { NetcdfDataset netcdfDataset = controller . getNetcdfDataset ( ) ; if ( null != netcdfDataset ) { try { dsTable . setDataset ( netcdfDataset , null ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; return ; } dsDialog . show ( ) ; } } } ; BAMutil . setActionProperties ( showNetcdfDatasetAction , \"netcdf\" , \"NetcdfDataset Table Info...\" , false , ' ' , - 1 ) ; /* write geotiff file\r\n    geotiffAction = new AbstractAction() {\r\n      public void actionPerformed(ActionEvent e) {\r\n        GeoGrid grid = controller.getCurrentField();\r\n        ucar.ma2.Array data = controller.getCurrentHorizDataSlice();\r\n        if ((grid == null) || (data == null)) return;\r\n\r\n        String filename = geotiffFileChooser.chooseFilename();\r\n        if (filename == null) return;\r\n\r\n        GeoTiff geotiff = null;\r\n        try {\r\n          /* System.out.println(\"write to= \"+filename);\r\n          ucar.nc2.geotiff.Writer.write2D(grid, data, filename+\".tfw\");\r\n          geotiff = new GeoTiff(filename); // read back in\r\n          geotiff.read();\r\n          System.out.println( geotiff.showInfo());\r\n          //geotiff.testReadData();\r\n          geotiff.close(); * /\r\n\r\n          // write two\r\n          ucar.nc2.geotiff.GeotiffWriter writer = new ucar.nc2.geotiff.GeotiffWriter(filename);\r\n          writer.writeGrid(grid, data, false);\r\n          geotiff = new GeoTiff(filename); // read back in\r\n          geotiff.read();\r\n          System.out.println( \"*************************************\");\r\n          System.out.println( geotiff.showInfo());\r\n          //geotiff.testReadData();\r\n          geotiff.close();\r\n\r\n\r\n        } catch (IOException ioe) {\r\n          ioe.printStackTrace();\r\n\r\n        } finally {\r\n          try {\r\n            if (geotiff != null) geotiff.close();\r\n          } catch (IOException ioe) { }\r\n        }\r\n\r\n      }\r\n    };\r\n    BAMutil.setActionProperties( geotiffAction, \"Geotiff\", \"Write Geotiff file\", false, 'G', -1);\r\n    */ minmaxHorizAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . horiz ) ; controller . setDataMinMaxType ( ColorScale . MinMaxType . horiz ) ; } } ; BAMutil . setActionProperties ( minmaxHorizAction , null , \"Horizontal plane\" , false , ' ' , 0 ) ; minmaxLogAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . log ) ; controller . setDataMinMaxType ( ColorScale . MinMaxType . log ) ; } } ; BAMutil . setActionProperties ( minmaxLogAction , null , \"log horiz plane\" , false , ' ' , 0 ) ; /* minmaxVolAction =  new AbstractAction() {\r\n      public void actionPerformed(ActionEvent e) {\r\n        csDataMinMax.setSelectedIndex(GridRenderer.VOL_MinMaxType);\r\n        controller.setDataMinMaxType(GridRenderer.MinMaxType.vert;\r\n      }\r\n    };\r\n    BAMutil.setActionProperties( minmaxVolAction, null, \"Grid volume\", false, 'G', 0); */ minmaxHoldAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . hold ) ; controller . setDataMinMaxType ( ColorScale . MinMaxType . hold ) ; } } ; BAMutil . setActionProperties ( minmaxHoldAction , null , \"Hold scale constant\" , false , ' ' , 0 ) ; fieldLoopAction = new LoopControlAction ( fieldChooser ) ; levelLoopAction = new LoopControlAction ( levelChooser ) ; timeLoopAction = new LoopControlAction ( timeChooser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; Array cArray = readArray ( cVar , timeIndex ) ; depth_c = depthCVar . readScalarDouble ( ) ; return makeHeight ( etaArray , sArray , depthArray , cArray , depth_c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and the specified X Y index for Lat - Lon point . [CODESPLIT] public ArrayDouble . D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; Array cArray = readArray ( cVar , timeIndex ) ; depth_c = depthCVar . readScalarDouble ( ) ; return makeHeight1D ( etaArray , sArray , depthArray , cArray , depth_c , xIndex , yIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////// [CODESPLIT] private long getFilePos ( long elem ) { long segno = elem / innerNelems ; long offset = elem % innerNelems ; return startPos + segno * recSize + offset * elemSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entry point for the scanner . Returns the token identifier corresponding to the next token and prepares to return the semantic value of the token . [CODESPLIT] public int yylex ( ) throws ParseException { int token ; int c = 0 ; token = 0 ; yytext . setLength ( 0 ) ; text . mark ( ) ; token = - 1 ; while ( token < 0 && ( c = text . read ( ) ) != EOS ) { if ( c <= ' ' || c == ' ' ) { /* whitespace: ignore */ } else if ( c == ' ' || c == ' ' ) { int delim = c ; boolean more = true ; /* We have a string token; will be reported as STRINGCONST */ while ( more && ( c = text . read ( ) ) > 0 ) { switch ( c ) { case EOS : throw new ParseException ( \"Unterminated character or string constant\" ) ; case ' ' : more = ( delim != c ) ; break ; case ' ' : more = ( delim != c ) ; break ; case ESCAPE : /* Suppress for now\n            if(c >= '0' && c <= '9') {\n\t\t\tint decimal = 0;\n\t\t        do {\n                            decimal = decimal * 10 + (c - '0');\n                            c = text.read();\n                        } while(c >= '0' && c <= '9');\n                        c = decimal;\n\t\t\ttext.backup();\n                        break;\n\t\t    } else\n*/ switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; default : break ; } break ; default : break ; } if ( more ) yytext . append ( ( char ) c ) ; } token = CEParserImpl . Lexer . STRING ; } else if ( DELIMS . indexOf ( c ) >= 0 ) { // Single char delimiter yytext . append ( ( char ) c ) ; token = c ; } else { // Assume we have a word or integer yytext . append ( ( char ) c ) ; while ( ( c = text . read ( ) ) > 0 ) { if ( c <= ' ' || c == ' ' ) break ; // whitespace if ( DELIMS . indexOf ( c ) >= 0 ) break ; if ( c == ESCAPE ) { c = text . read ( ) ; if ( c == EOS ) throw new ParseException ( \"Unterminated backslash escape\" ) ; } yytext . append ( ( char ) c ) ; } // pushback the delimiter if ( c != EOS ) text . backup ( ) ; try { // See if this looks like an integer long num = Long . parseLong ( yytext . toString ( ) ) ; token = CEParserImpl . Lexer . LONG ; } catch ( NumberFormatException nfe ) { token = CEParserImpl . Lexer . NAME ; } } } if ( c == EOS && token < 0 ) { token = 0 ; lval = null ; } else { lval = ( yytext . length ( ) == 0 ? ( String ) null : yytext . toString ( ) ) ; } if ( parsestate . getDebugLevel ( ) > 0 ) dumptoken ( token , ( String ) lval ) ; return token ; // Return the type of the token }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entry point for error reporting . Emits an error in a user - defined way . Part of Lexer interface . [CODESPLIT] public void yyerror ( String s ) { System . err . println ( \"CEParserImpl.yyerror: \" + s + \"; parse failed at char: \" + charno + \"; near: \" ) ; String context = getInput ( ) ; int show = ( context . length ( ) < CONTEXTLEN ? context . length ( ) : CONTEXTLEN ) ; System . err . println ( context . substring ( context . length ( ) - show ) + \"^\" ) ; new Exception ( ) . printStackTrace ( System . err ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a netcdf dataset using NetcdfDataset . defaultEnhanceMode plus CoordSystems and turn into a DtCoverageDataset . [CODESPLIT] static public DtCoverageDataset open ( String location ) throws java . io . IOException { DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; return open ( durl , NetcdfDataset . getDefaultEnhanceMode ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a netcdf dataset using NetcdfDataset . defaultEnhanceMode plus CoordSystems and turn into a DtCoverageDataset . [CODESPLIT] static public DtCoverageDataset open ( DatasetUrl durl , Set < NetcdfDataset . Enhance > enhanceMode ) throws java . io . IOException { NetcdfDataset ds = ucar . nc2 . dataset . NetcdfDataset . acquireDataset ( null , durl , enhanceMode , - 1 , null , null ) ; return new DtCoverageDataset ( ds , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the name of the dataset is the last part of the location [CODESPLIT] public String getName ( ) { String loc = ncd . getLocation ( ) ; int pos = loc . lastIndexOf ( ' ' ) ; if ( pos < 0 ) pos = loc . lastIndexOf ( ' ' ) ; return ( pos < 0 ) ? loc : loc . substring ( pos + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the named GeoGrid . [CODESPLIT] public DtCoverage findGridByName ( String fullName ) { for ( DtCoverage ggi : grids ) { if ( fullName . equals ( ggi . getFullName ( ) ) ) return ggi ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the named GeoGrid . [CODESPLIT] public DtCoverage findGridByShortName ( String shortName ) { for ( DtCoverage ggi : grids ) { if ( shortName . equals ( ggi . getShortName ( ) ) ) return ggi ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a String of the parameters . [CODESPLIT] public String paramsToString ( ) { Formatter f = new Formatter ( ) ; f . format ( \"origin lat,lon=%f,%f parellels=%f,%f earth=%s\" , lat0deg , lon0deg , par1deg , par2deg , earth ) ; return f . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This returns true when the line between pt1 and pt2 crosses the seam . When the cone is flattened the seam is lon0 + - 180 . [CODESPLIT] public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { if ( ProjectionPointImpl . isInfinite ( pt1 ) || ProjectionPointImpl . isInfinite ( pt2 ) ) { return true ; } return false ; /* opposite signed X values, larger then 5000 km  LOOK ????\r\n    return (pt1.getX() * pt2.getX() < 0)\r\n            && (Math.abs(pt1.getX() - pt2.getX()) > 5000.0); */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public ProjectionPoint latLonToProj ( LatLonPoint latLon ProjectionPointImpl result ) { double toX toY ; double fromLat = latLon . getLatitude () ; double fromLon = latLon . getLongitude () ; [CODESPLIT] private double computeTheta ( double lon ) { double dlon = LatLonPointImpl . lonNormal ( lon - lon0deg ) ; return n * Math . toRadians ( dlon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "also see Snyder p 101 [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double fromLat = Math . toRadians ( latLon . getLatitude ( ) ) ; double theta = computeTheta ( latLon . getLongitude ( ) ) ; double rho = 0.0 ; if ( Math . abs ( Math . abs ( fromLat ) - MapMath . HALFPI ) >= TOL ) { double term ; if ( isSpherical ) term = Math . pow ( Math . tan ( MapMath . QUARTERPI + .5 * fromLat ) , - n ) ; else term = Math . pow ( MapMath . tsfn ( fromLat , Math . sin ( fromLat ) , e ) , n ) ; rho = c * term ; } double toX = ( rho * Math . sin ( theta ) ) ; double toY = ( rho0 - rho * Math . cos ( theta ) ) ; result . setLocation ( totalScale * toX + falseEasting , totalScale * toY + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public LatLonPoint projToLatLon ( ProjectionPoint world LatLonPointImpl result ) { double toLat toLon ; double fromX = world . getX () - falseEasting ; double fromY = world . getY () - falseNorthing ; double rhop = rho ; [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = ( world . getX ( ) - falseEasting ) / totalScale ; // assumes cartesion coords in km\r double fromY = ( world . getY ( ) - falseNorthing ) / totalScale ; fromY = rho0 - fromY ; double rho = MapMath . distance ( fromX , fromY ) ; if ( rho != 0 ) { if ( n < 0.0 ) { rho = - rho ; fromX = - fromX ; fromY = - fromY ; } if ( isSpherical ) toLat = 2.0 * Math . atan ( Math . pow ( c / rho , 1.0 / n ) ) - MapMath . HALFPI ; else toLat = MapMath . phi2 ( Math . pow ( rho / c , 1.0 / n ) , e ) ; toLon = Math . atan2 ( fromX , fromY ) / n ; //coverity[swapped_arguments]\r } else { toLon = 0.0 ; toLat = n > 0.0 ? MapMath . HALFPI : - MapMath . HALFPI ; } result . setLatitude ( Math . toDegrees ( toLat ) ) ; result . setLongitude ( Math . toDegrees ( toLon ) + lon0deg ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * proj + inv + proj = aea + lat_0 = 23 . 0 + lat_1 = 29 . 5 + lat_2 = 45 . 5 + a = 6378137 . 0 + rf = 298 . 257222101 + b = 6356752 . 31414 + lon_0 = - 96 . 0 [CODESPLIT] private static void toProj ( ProjectionImpl p , double lat , double lon ) { System . out . printf ( \"lon,lat = %f %f%n\" , lon , lat ) ; ProjectionPoint pt = p . latLonToProj ( lat , lon ) ; System . out . printf ( \"x,y     = %f %f%n\" , pt . getX ( ) , pt . getY ( ) ) ; LatLonPoint ll = p . projToLatLon ( pt ) ; System . out . printf ( \"lon,lat = %f %f%n%n\" , ll . getLongitude ( ) , ll . getLatitude ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A path is file if it has no base protocol or is file : [CODESPLIT] public boolean dspMatch ( String location , DapContext context ) { try { XURI xuri = new XURI ( location ) ; if ( xuri . isFile ( ) ) { String path = xuri . getPath ( ) ; for ( String ext : EXTENSIONS ) { if ( path . endsWith ( ext ) ) return true ; } } } catch ( URISyntaxException use ) { return false ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extension to access a raw byte stream [CODESPLIT] public FileDSP open ( byte [ ] rawdata ) throws DapException { try { this . raw = rawdata ; ByteArrayInputStream stream = new ByteArrayInputStream ( this . raw ) ; ChunkInputStream rdr = new ChunkInputStream ( stream , RequestMode . DAP ) ; String document = rdr . readDMR ( ) ; byte [ ] serialdata = DapUtil . readbinaryfile ( rdr ) ; super . build ( document , serialdata , rdr . getRemoteByteOrder ( ) ) ; return this ; } catch ( IOException ioe ) { throw new DapException ( ioe ) . setCode ( DapCodes . SC_INTERNAL_SERVER_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Alias< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { Alias a = ( Alias ) super . cloneDAG ( map ) ; a . aliasedToAttributeNamed = this . aliasedToAttributeNamed ; a . targetAttribute = ( Attribute ) cloneDAG ( map , this . targetAttribute ) ; a . targetVariable = ( BaseType ) cloneDAG ( map , this . targetVariable ) ; return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapted from the package - private BasicDayOfMonthDateTimeField [CODESPLIT] @ Override public int getMaximumValue ( ReadablePartial partial ) { if ( partial . isSupported ( DateTimeFieldType . monthOfYear ( ) ) ) { int month = partial . get ( DateTimeFieldType . monthOfYear ( ) ) ; return this . daysInMonth [ month - 1 ] ; // Months are 1-based\r } return this . getMaximumValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapted from the package - private BasicDayOfMonthDateTimeField [CODESPLIT] @ Override public int getMaximumValue ( ReadablePartial partial , int [ ] values ) { int size = partial . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( partial . getFieldType ( i ) == DateTimeFieldType . monthOfYear ( ) ) { int month = values [ i ] ; return this . daysInMonth [ month - 1 ] ; } } return this . getMaximumValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return y x ranges [CODESPLIT] private Optional < List < RangeIterator > > computeBounds ( LatLonRect llbb , int horizStride ) { synchronized ( this ) { if ( edges == null ) edges = new Edges ( ) ; } return edges . computeBoundsExhaustive ( llbb , horizStride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection [CODESPLIT] public static CollectionType initCollection ( CollectionType collection , FeatureDatasetPoint fdPoint , List < VariableSimpleIF > dataVars ) throws IOException { // @gml:id String id = MarshallingUtil . createIdForType ( CollectionType . class ) ; collection . setId ( id ) ; // wml2:metadata NcDocumentMetadataPropertyType . initMetadata ( collection . addNewMetadata ( ) ) ; // wml2:observationMember[0..*] StationTimeSeriesFeatureCollection stationFeatColl = getStationFeatures ( fdPoint ) ; try { while ( stationFeatColl . hasNext ( ) ) { StationTimeSeriesFeature stationFeat = stationFeatColl . next ( ) ; for ( VariableSimpleIF dataVar : dataVars ) { if ( dataVar . getDataType ( ) . isNumeric ( ) ) { // wml2:observationMember NcOMObservationPropertyType . initObservationMember ( collection . addNewObservationMember ( ) , stationFeat , dataVar ) ; } } } } finally { stationFeatColl . finish ( ) ; } return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation [CODESPLIT] public static OMObservationType initOmObservation ( OMObservationType omObservation , StationTimeSeriesFeature stationFeat , VariableSimpleIF dataVar ) throws IOException { // @gml:id String id = MarshallingUtil . createIdForType ( OMObservationType . class ) ; omObservation . setId ( id ) ; // om:phenomenonTime NcTimeObjectPropertyType . initPhenomenonTime ( omObservation . addNewPhenomenonTime ( ) , stationFeat ) ; // om:resultTime NcTimeInstantPropertyType . initResultTime ( omObservation . addNewResultTime ( ) ) ; // om:observedProperty NcReferenceType . initObservedProperty ( omObservation . addNewObservedProperty ( ) , dataVar ) ; // om:procedure NcOMProcessPropertyType . initProcedure ( omObservation . addNewProcedure ( ) ) ; // om:featureOfInterest NcFeaturePropertyType . initFeatureOfInterest ( omObservation . addNewFeatureOfInterest ( ) , stationFeat ) ; // om:result MeasurementTimeseriesDocument measurementTimeseriesDoc = MeasurementTimeseriesDocument . Factory . newInstance ( ) ; NcMeasurementTimeseriesType . initMeasurementTimeseries ( measurementTimeseriesDoc . addNewMeasurementTimeseries ( ) , stationFeat , dataVar ) ; omObservation . setResult ( measurementTimeseriesDoc ) ; return omObservation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doCheckHash ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"Check Files for hash consistency%n\" ) ; int [ ] accum = new int [ 4 ] ; TrackMessageTypes all = new TrackMessageTypes ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; if ( path . endsWith ( \".ncx\" ) ) continue ; f . format ( \"%n %s%n\" , path ) ; try { doCheckHash ( mfile , f , all , accum ) ; } catch ( Throwable t ) { System . out . printf ( \"FAIL on %s%n\" , mfile . getPath ( ) ) ; t . printStackTrace ( ) ; } } f . format ( \"%n================%nTotals countMess=%d countObs = %d%n\" , accum [ 0 ] , accum [ 1 ] ) ; show ( all , f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doBufrSplitter ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { long start = System . currentTimeMillis ( ) ; String dirName = dcm . getRoot ( ) + \"/split\" ; // LOOK temp kludge f . format ( \"BufrSplitter on files in collection %s, write to %s%n\" , dcm , dirName ) ; BufrSplitter2 splitter = new BufrSplitter2 ( dirName , f ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; if ( path . endsWith ( \".ncx\" ) ) continue ; f . format ( \"%n %s%n\" , path ) ; System . out . printf ( \" BufrSplitter on %s%n\" , path ) ; long start2 = System . currentTimeMillis ( ) ; try { splitter . execute ( path ) ; long took2 = System . currentTimeMillis ( ) - start2 ; System . out . printf ( \"  %s took %s msecs%n\" , path , took2 ) ; } catch ( Throwable t ) { System . out . printf ( \"FAIL on %s%n\" , mfile . getPath ( ) ) ; t . printStackTrace ( ) ; } } splitter . exit ( ) ; long took = ( System . currentTimeMillis ( ) - start ) / 1000 ; System . out . printf ( \"That took %s secs%n\" , took ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "2006 - 10 - 23T17 : 59 : 39 18 . 415434 - 93 . 480526 - 26 . 8 1 [CODESPLIT] int readAllData ( RandomAccessFile raf ) throws IOException , NumberFormatException , ParseException { ArrayList records = new ArrayList ( ) ; java . text . SimpleDateFormat isoDateTimeFormat = new java . text . SimpleDateFormat ( \"yyyy-MM-dd'T'HH:mm:ss\" ) ; isoDateTimeFormat . setTimeZone ( java . util . TimeZone . getTimeZone ( \"GMT\" ) ) ; //java.io.RandomAccessFile jraf = raf.getRandomAccessFile(); raf . seek ( 0 ) ; int count = 0 ; while ( true ) { String line = raf . readLine ( ) ; if ( line == null ) break ; if ( line . startsWith ( MAGIC ) ) continue ; StringTokenizer stoker = new StringTokenizer ( line , \",\\r\\n\" ) ; while ( stoker . hasMoreTokens ( ) ) { Date d = isoDateTimeFormat . parse ( stoker . nextToken ( ) ) ; double lat = Double . parseDouble ( stoker . nextToken ( ) ) ; double lon = Double . parseDouble ( stoker . nextToken ( ) ) ; double amp = Double . parseDouble ( stoker . nextToken ( ) ) ; String tok = stoker . nextToken ( ) ; int nstrikes = Integer . parseInt ( tok ) ; Strike s = new Strike ( d , lat , lon , amp , nstrikes ) ; records . add ( s ) ; if ( count < 10 ) System . out . println ( count + \" \" + isoDateTimeFormat . format ( d ) + \" \" + s ) ; } count ++ ; } System . out . println ( \"processed \" + count + \" records\" ) ; int n = records . size ( ) ; int [ ] shape = new int [ ] { n } ; dateArray = ( ArrayInt . D1 ) Array . factory ( DataType . INT , shape ) ; latArray = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , shape ) ; lonArray = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , shape ) ; ampArray = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , shape ) ; nstrokesArray = ( ArrayInt . D1 ) Array . factory ( DataType . INT , shape ) ; for ( int i = 0 ; i < records . size ( ) ; i ++ ) { Strike strike = ( Strike ) records . get ( i ) ; dateArray . set ( i , strike . d ) ; latArray . set ( i , strike . lat ) ; lonArray . set ( i , strike . lon ) ; ampArray . set ( i , strike . amp ) ; nstrokesArray . set ( i , strike . n ) ; } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set values on the UI [CODESPLIT] private void synchUI ( boolean slidersOK ) { eventOK = false ; if ( slidersOK ) minSlider . setValue ( scale . world2slider ( dateRange . getStart ( ) ) ) ; minField . setValue ( dateRange . getStart ( ) ) ; if ( maxField != null ) { if ( slidersOK ) maxSlider . setValue ( scale . world2slider ( dateRange . getEnd ( ) ) ) ; maxField . setValue ( dateRange . getEnd ( ) ) ; } if ( durationField != null ) durationField . setValue ( dateRange . getDuration ( ) ) ; eventOK = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make it easy to test by using dimension list [CODESPLIT] public int [ ] computeUnlimitedChunking ( List < Dimension > dims , int elemSize ) { int maxElements = defaultChunkSize / elemSize ; int [ ] result = fillRightmost ( convertUnlimitedShape ( dims ) , maxElements ) ; long resultSize = new Section ( result ) . computeSize ( ) ; if ( resultSize < minChunksize ) { maxElements = minChunksize / elemSize ; result = incrUnlimitedShape ( dims , result , maxElements ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the given directory with the WatchService [CODESPLIT] public void register ( Path dir ) throws IOException { if ( ! enable ) return ; WatchKey key = dir . register ( watcher , ENTRY_CREATE , ENTRY_DELETE , ENTRY_MODIFY ) ; if ( trace ) { Path prev = keys . get ( key ) ; if ( prev == null ) { System . out . format ( \"CatalogWatcher register: %s%n\" , dir ) ; } else { if ( ! dir . equals ( prev ) ) { System . out . format ( \"update: %s -> %s%n\" , prev , dir ) ; } } } keys . put ( key , dir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all events for keys queued to the watcher [CODESPLIT] public void processEvents ( ) { if ( ! enable ) return ; for ( ; ; ) { // wait for key to be signalled WatchKey key ; try { key = watcher . take ( ) ; } catch ( InterruptedException x ) { return ; } Path dir = keys . get ( key ) ; if ( dir == null ) { System . err . println ( \"WatchKey not recognized!!\" ) ; continue ; } for ( WatchEvent < ? > event : key . pollEvents ( ) ) { WatchEvent . Kind kind = event . kind ( ) ; // TBD - provide example of how OVERFLOW event is handled if ( kind == OVERFLOW ) { continue ; } // Context for directory entry event is the file name of entry WatchEvent < Path > ev = cast ( event ) ; Path name = ev . context ( ) ; Path child = dir . resolve ( name ) ; // print out event System . out . format ( \"%s: %s%n\" , event . kind ( ) . name ( ) , child ) ; // if directory is created, and watching recursively, then // register it and its sub-directories if ( recursive && ( kind == ENTRY_CREATE ) ) { try { if ( Files . isDirectory ( child , NOFOLLOW_LINKS ) ) { registerAll ( child ) ; } } catch ( IOException x ) { // ignore to keep sample readbale } } } // reset key and remove from set if directory no longer accessible boolean valid = key . reset ( ) ; if ( ! valid ) { keys . remove ( key ) ; // all directories are inaccessible if ( keys . isEmpty ( ) ) { break ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy on modify [CODESPLIT] public TimeHelper setReferenceDate ( CalendarDate refDate ) { CalendarDateUnit cdUnit = CalendarDateUnit . of ( dateUnit . getCalendar ( ) , dateUnit . getCalendarField ( ) , refDate ) ; return new TimeHelper ( cdUnit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a FeatureDatasetFactory . [CODESPLIT] static public boolean registerFactory ( FeatureType datatype , String className ) { try { Class c = Class . forName ( className ) ; registerFactory ( datatype , c ) ; return true ; } catch ( ClassNotFoundException e ) { // ok - these are optional\r return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a FeatureDatasetFactory . [CODESPLIT] static public void registerFactory ( String className ) throws ClassNotFoundException { Class c = Class . forName ( className ) ; registerFactory ( c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a FeatureDatasetFactory . Find out which type by calling getFeatureType () . [CODESPLIT] static public void registerFactory ( Class c ) { if ( ! ( FeatureDatasetFactory . class . isAssignableFrom ( c ) ) ) throw new IllegalArgumentException ( \"Class \" + c . getName ( ) + \" must implement FeatureDatasetFactory\" ) ; // fail fast - get Instance\r Object instance ; try { instance = c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( \"FeatureDatasetFactoryManager Class \" + c . getName ( ) + \" cannot instantiate, probably need default Constructor\" ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"FeatureDatasetFactoryManager Class \" + c . getName ( ) + \" is not accessible\" ) ; } // find out what type of Features\r try { Method m = c . getMethod ( \"getFeatureTypes\" , new Class [ 0 ] ) ; FeatureType [ ] result = ( FeatureType [ ] ) m . invoke ( instance , new Object [ 0 ] ) ; for ( FeatureType ft : result ) { if ( userMode ) factoryList . add ( 0 , new Factory ( ft , c , ( FeatureDatasetFactory ) instance ) ) ; else factoryList . add ( new Factory ( ft , c , ( FeatureDatasetFactory ) instance ) ) ; } } catch ( Exception ex ) { throw new IllegalArgumentException ( \"FeatureDatasetFactoryManager Class \" + c . getName ( ) + \" failed invoking getFeatureType()\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a dataset as a FeatureDataset . [CODESPLIT] static public FeatureDataset open ( FeatureType wantFeatureType , String location , ucar . nc2 . util . CancelTask task , Formatter errlog ) throws IOException { // special processing for thredds: datasets\r if ( location . startsWith ( DataFactory . SCHEME ) ) { DataFactory . Result result = new DataFactory ( ) . openFeatureDataset ( wantFeatureType , location , task ) ; errlog . format ( \"%s\" , result . errLog ) ; if ( ! featureTypeOk ( wantFeatureType , result . featureType ) ) { errlog . format ( \"wanted %s but dataset is of type %s%n\" , wantFeatureType , result . featureType ) ; result . close ( ) ; return null ; } return result . featureDataset ; // special processing for cdmrFeature: datasets\r } else if ( location . startsWith ( CdmrFeatureDataset . SCHEME ) ) { Optional < FeatureDataset > opt = CdmrFeatureDataset . factory ( wantFeatureType , location ) ; if ( opt . isPresent ( ) ) return opt . get ( ) ; errlog . format ( \"%s\" , opt . getErrorMessage ( ) ) ; return null ; // special processing for collection: datasets\r } else if ( location . startsWith ( ucar . nc2 . ft . point . collection . CompositeDatasetFactory . SCHEME ) ) { String spec = location . substring ( CompositeDatasetFactory . SCHEME . length ( ) ) ; MFileCollectionManager dcm = MFileCollectionManager . open ( spec , spec , null , errlog ) ; // LOOK we dont have a name\r return CompositeDatasetFactory . factory ( location , wantFeatureType , dcm , errlog ) ; } DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; // Cache ServiceType so we don't have to keep figuring it out\r if ( durl . serviceType == null ) { // skip GRIB check for anything not a plain ole file\r // check if its GRIB, may not have to go through NetcdfDataset\r Optional < FeatureDatasetCoverage > opt = CoverageDatasetFactory . openGrib ( location ) ; if ( opt . isPresent ( ) ) { // its a GRIB file\r return opt . get ( ) ; } else if ( ! opt . getErrorMessage ( ) . startsWith ( CoverageDatasetFactory . NOT_GRIB_FILE ) && ! opt . getErrorMessage ( ) . startsWith ( CoverageDatasetFactory . NO_GRIB_CLASS ) ) { errlog . format ( \"%s%n\" , opt . getErrorMessage ( ) ) ; // its a GRIB file with an error\r return null ; } } // otherwise open as NetcdfDataset and run it through the FeatureDatasetFactories\r NetcdfDataset ncd = NetcdfDataset . acquireDataset ( durl , true , task ) ; FeatureDataset fd = wrap ( wantFeatureType , ncd , task , errlog ) ; if ( fd == null ) ncd . close ( ) ; return fd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a NetcdfDataset as a FeatureDataset . [CODESPLIT] static public FeatureDataset wrap ( FeatureType wantFeatureType , NetcdfDataset ncd , ucar . nc2 . util . CancelTask task , Formatter errlog ) throws IOException { if ( debug ) System . out . println ( \"wrap \" + ncd . getLocation ( ) + \" want = \" + wantFeatureType ) ; // the case where we dont know what type it is\r if ( ( wantFeatureType == null ) || ( wantFeatureType == FeatureType . ANY ) ) { return wrapUnknown ( ncd , task , errlog ) ; } // find a Factory that claims this dataset by passing back an \"analysis result\" object\r Object analysis = null ; FeatureDatasetFactory useFactory = null ; for ( Factory fac : factoryList ) { if ( ! featureTypeOk ( wantFeatureType , fac . featureType ) ) continue ; if ( debug ) System . out . println ( \" wrap try factory \" + fac . factory . getClass ( ) . getName ( ) ) ; analysis = fac . factory . isMine ( wantFeatureType , ncd , errlog ) ; if ( analysis != null ) { useFactory = fac . factory ; break ; } } if ( null == useFactory ) { errlog . format ( \"**Failed to find FeatureDatasetFactory for= %s datatype=%s%n\" , ncd . getLocation ( ) , wantFeatureType ) ; return null ; } // this call must be thread safe - done by implementation\r return useFactory . open ( wantFeatureType , ncd , analysis , task , errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if factory type matches wanted feature type . [CODESPLIT] static public boolean featureTypeOk ( FeatureType want , FeatureType facType ) { if ( want == null ) return true ; if ( want == facType ) return true ; if ( want == FeatureType . ANY_POINT ) { return facType . isPointFeatureType ( ) ; } if ( facType == FeatureType . ANY_POINT ) { return want . isPointFeatureType ( ) ; } if ( want == FeatureType . COVERAGE ) { return facType . isCoverageFeatureType ( ) ; } if ( want == FeatureType . GRID ) { // for backwards compatibility\r return facType . isCoverageFeatureType ( ) ; } if ( want == FeatureType . SIMPLE_GEOMETRY ) { return facType . isCoverageFeatureType ( ) ; } if ( want == FeatureType . UGRID ) { return facType . isUnstructuredGridFeatureType ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to determine the feature type of the dataset by examining its metadata . [CODESPLIT] static public FeatureType findFeatureType ( NetcdfFile ncd ) { // search for explicit featureType global attribute\r String cdm_datatype = ncd . findAttValueIgnoreCase ( null , CF . FEATURE_TYPE , null ) ; if ( cdm_datatype == null ) cdm_datatype = ncd . findAttValueIgnoreCase ( null , \"cdm_data_type\" , null ) ; if ( cdm_datatype == null ) cdm_datatype = ncd . findAttValueIgnoreCase ( null , \"cdm_datatype\" , null ) ; if ( cdm_datatype == null ) cdm_datatype = ncd . findAttValueIgnoreCase ( null , \"thredds_data_type\" , null ) ; if ( cdm_datatype != null ) { for ( FeatureType ft : FeatureType . values ( ) ) if ( cdm_datatype . equalsIgnoreCase ( ft . name ( ) ) ) { if ( debug ) System . out . println ( \" wrapUnknown found cdm_datatype \" + cdm_datatype ) ; return ft ; } } CF . FeatureType cff = CF . FeatureType . getFeatureTypeFromGlobalAttribute ( ncd ) ; if ( cff != null ) return CF . FeatureType . convert ( cff ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read directly from file without going through the buffer . All reading goes through here or readToByteChannel ; [CODESPLIT] @ Override protected int read_ ( long pos , byte [ ] buff , int offset , int len ) throws IOException { long end = pos + len - 1 ; if ( end >= total_length ) end = total_length - 1 ; if ( debug ) System . out . println ( \" HTTPRandomAccessFile bytes=\" + pos + \"-\" + end + \": \" ) ; try ( HTTPMethod method = HTTPFactory . Get ( session , url ) ) { method . setFollowRedirects ( true ) ; method . setRange ( pos , end ) ; doConnect ( method ) ; int code = method . getStatusCode ( ) ; if ( code != 206 ) throw new IOException ( \"Server does not support Range requests, code= \" + code ) ; String s = method . getResponseHeader ( \"Content-Length\" ) . getValue ( ) ; if ( s == null ) throw new IOException ( \"Server does not send Content-Length header\" ) ; int readLen = Integer . parseInt ( s ) ; readLen = Math . min ( len , readLen ) ; InputStream is = method . getResponseAsStream ( ) ; readLen = copy ( is , buff , offset , readLen ) ; return readLen ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an Catalog to the HttpServletResponse return the size in bytes of the catalog written to the response . [CODESPLIT] public int writeCatalog ( HttpServletRequest req , HttpServletResponse res , Catalog cat , boolean isLocalCatalog ) throws IOException { String catHtmlAsString = convertCatalogToHtml ( cat , isLocalCatalog ) ; // Once this header is set, we know the encoding, and thus the actual // number of *bytes*, not characters, to encode res . setContentType ( ContentType . html . getContentHeader ( ) ) ; int len = ServletUtil . setResponseContentLength ( res , catHtmlAsString ) ; if ( ! req . getMethod ( ) . equals ( \"HEAD\" ) ) { PrintWriter writer = res . getWriter ( ) ; writer . write ( catHtmlAsString ) ; writer . flush ( ) ; } return len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a catalog in HTML make it look like a file directory . [CODESPLIT] String convertCatalogToHtml ( Catalog cat , boolean isLocalCatalog ) { StringBuilder sb = new StringBuilder ( 10000 ) ; String uri = cat . getUriString ( ) ; if ( uri == null ) uri = cat . getName ( ) ; if ( uri == null ) uri = \"unknown\" ; String catname = Escape . html ( uri ) ; // Render the page header sb . append ( getHtmlDoctypeAndOpenTag ( ) ) ; // \"<html>\\n\" ); sb . append ( \"<head>\\r\\n\" ) ; sb . append ( \"<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>\" ) ; sb . append ( \"<title>\" ) ; //if (cat.isStatic()) //  sb.append(\"TdsStaticCatalog \").append(catname); // for searching //else sb . append ( \"Catalog \" ) . append ( catname ) ; sb . append ( \"</title>\\r\\n\" ) ; sb . append ( getTdsCatalogCssLink ( ) ) . append ( \"\\n\" ) ; sb . append ( this . getGoogleTrackingContent ( ) ) ; sb . append ( \"</head>\\r\\n\" ) ; sb . append ( \"<body>\" ) ; sb . append ( \"<h1>\" ) ; // Logo //String logoUrl = this.htmlConfig.getInstallLogoUrl(); String logoUrl = htmlConfig . prepareUrlStringForHtml ( htmlConfig . getInstallLogoUrl ( ) ) ; if ( logoUrl != null ) { sb . append ( \"<img src='\" ) . append ( logoUrl ) ; String logoAlt = htmlConfig . getInstallLogoAlt ( ) ; if ( logoAlt != null ) sb . append ( \"' alt='\" ) . append ( logoAlt ) ; sb . append ( \"' align='left' valign='top'\" ) . append ( \">\\n\" ) ; } sb . append ( \" Catalog \" ) . append ( catname ) ; sb . append ( \"</h1>\" ) ; sb . append ( \"<HR size='1' noshade='noshade'>\" ) ; sb . append ( \"<table width='100%' cellspacing='0' cellpadding='5' align='center'>\\r\\n\" ) ; // Render the column headings sb . append ( \"<tr>\\r\\n\" ) ; sb . append ( \"<th align='left'><font size='+1'>\" ) ; sb . append ( \"Dataset\" ) ; sb . append ( \"</font></th>\\r\\n\" ) ; sb . append ( \"<th align='center'><font size='+1'>\" ) ; sb . append ( \"Size\" ) ; sb . append ( \"</font></th>\\r\\n\" ) ; sb . append ( \"<th align='right'><font size='+1'>\" ) ; sb . append ( \"Last Modified\" ) ; sb . append ( \"</font></th>\\r\\n\" ) ; sb . append ( \"</tr>\" ) ; // Recursively render the datasets doDatasets ( cat , cat . getDatasetsLocal ( ) , sb , false , 0 , isLocalCatalog ) ; // Render the page footer sb . append ( \"</table>\\r\\n\" ) ; sb . append ( \"<HR size='1' noshade='noshade'>\" ) ; appendSimpleFooter ( sb ) ; sb . append ( \"</body>\\r\\n\" ) ; sb . append ( \"</html>\\r\\n\" ) ; return ( sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public static final String UNIDATA_CSS [CODESPLIT] public String getUserCSS ( ) { return new StringBuilder ( ) . append ( \"<link rel='stylesheet' href='\" ) . append ( this . htmlConfig . prepareUrlStringForHtml ( this . htmlConfig . getPageCssUrl ( ) ) ) . append ( \"' type='text/css' >\" ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public static final String UNIDATA_HEAD [CODESPLIT] public String getUserHead ( ) { return new StringBuilder ( ) . append ( \"<table width='100%'><tr><td>\\n\" ) . append ( \"  <img src='\" ) . append ( this . htmlConfig . prepareUrlStringForHtml ( this . htmlConfig . getHostInstLogoUrl ( ) ) ) . append ( \"'\\n\" ) . append ( \"       alt='\" ) . append ( this . htmlConfig . getHostInstLogoAlt ( ) ) . append ( \"'\\n\" ) . append ( \"       align='left' valign='top'\\n\" ) . append ( \"       hspace='10' vspace='2'>\\n\" ) . append ( \"  <h3><strong>\" ) . append ( this . tdsContext . getWebappDisplayName ( ) ) . append ( \"</strong></h3>\\n\" ) . append ( \"</td></tr></table>\\n\" ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a catalog exists and is allowed ( not filtered out ) for the given path return the catalog as an Catalog . Otherwise return null . <p > The validity of the returned catalog is not guaranteed . Use Catalog . check () to check that the catalog is valid . [CODESPLIT] public Catalog getCatalog ( String path , URI baseURI ) throws IOException { if ( path == null ) return null ; String workPath = path ; if ( workPath . startsWith ( \"/\" ) ) workPath = workPath . substring ( 1 ) ; // Check if its a CatalogBuilder or ConfigCatalog Object dyno = makeDynamicCatalog ( workPath , baseURI ) ; if ( dyno != null ) { CatalogBuilder catBuilder ; if ( dyno instanceof CatalogBuilder ) { catBuilder = ( CatalogBuilder ) dyno ; } else { ConfigCatalog configCatalog = ( ConfigCatalog ) dyno ; catBuilder = configCatalog . makeCatalogBuilder ( ) ; // turn it back into mutable object } addGlobalServices ( catBuilder ) ; return catBuilder . makeCatalog ( ) ; } // check cache and read if needed ConfigCatalog configCatalog = ccc . get ( workPath ) ; if ( configCatalog == null ) return null ; CatalogBuilder catBuilder = configCatalog . makeCatalogBuilder ( ) ; addGlobalServices ( catBuilder ) ; return catBuilder . makeCatalog ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "barfola on the return type [CODESPLIT] private Object makeDynamicCatalog ( String path , URI baseURI ) throws IOException { boolean isLatest = path . endsWith ( \"/latest.xml\" ) ; // strip off the filename int pos = path . lastIndexOf ( \"/\" ) ; String workPath = ( pos >= 0 ) ? path . substring ( 0 , pos ) : path ; String filename = ( pos > 0 ) ? path . substring ( pos + 1 ) : path ; // now look through the data roots for a maximal match DataRootManager . DataRootMatch match = dataRootManager . findDataRootMatch ( workPath ) ; if ( match == null ) return null ; // Feature Collection if ( match . dataRoot . getFeatureCollection ( ) != null ) { InvDatasetFeatureCollection fc = featureCollectionCache . get ( match . dataRoot . getFeatureCollection ( ) ) ; if ( isLatest ) return fc . makeLatest ( match . remaining , path , baseURI ) ; else return fc . makeCatalog ( match . remaining , path , baseURI ) ; } // DatasetScan DatasetScan dscan = match . dataRoot . getDatasetScan ( ) ; if ( dscan != null ) { if ( log . isDebugEnabled ( ) ) log . debug ( \"makeDynamicCatalog(): Calling DatasetScan.makeCatalogForDirectory( \" + baseURI + \", \" + path + \").\" ) ; CatalogBuilder cat ; if ( isLatest ) cat = dscan . makeCatalogForLatest ( workPath , baseURI ) ; else cat = dscan . makeCatalogForDirectory ( workPath , baseURI ) ; if ( null == cat ) log . error ( \"makeDynamicCatalog(): DatasetScan.makeCatalogForDirectory failed = \" + workPath ) ; return cat ; } // CatalogScan CatalogScan catScan = match . dataRoot . getCatalogScan ( ) ; if ( catScan != null ) { if ( ! filename . equalsIgnoreCase ( CatalogScan . CATSCAN ) ) { // its an actual catalog return catScan . getCatalog ( tdsContext . getThreddsDirectory ( ) , match . remaining , filename , ccc ) ; } if ( log . isDebugEnabled ( ) ) log . debug ( \"makeDynamicCatalog(): Calling CatalogScan.makeCatalogForDirectory( \" + baseURI + \", \" + path + \").\" ) ; CatalogBuilder cat = catScan . makeCatalogFromDirectory ( tdsContext . getThreddsDirectory ( ) , match . remaining , baseURI ) ; if ( null == cat ) log . error ( \"makeDynamicCatalog(): CatalogScan.makeCatalogForDirectory failed = \" + workPath ) ; return cat ; } log . warn ( \"makeDynamicCatalog() failed for =\" + workPath + \" request path= \" + path ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rigamorole to modify invariant catalogs ; we may need to add global services [CODESPLIT] private void addGlobalServices ( CatalogBuilder cat ) { // look for datasets that want to use global services Set < String > allServiceNames = new HashSet <> ( ) ; findServices ( cat . getDatasets ( ) , allServiceNames ) ; // all services used if ( ! allServiceNames . isEmpty ( ) ) { List < Service > servicesMissing = new ArrayList <> ( ) ; // all services missing for ( String name : allServiceNames ) { if ( cat . hasServiceInDataset ( name ) ) continue ; Service s = globalServices . findGlobalService ( name ) ; if ( s != null ) servicesMissing . add ( s ) ; } servicesMissing . forEach ( cat :: addService ) ; } // look for datasets that want to use standard services for ( DatasetBuilder node : cat . getDatasets ( ) ) { String sname = ( String ) node . getFldOrInherited ( Dataset . ServiceName ) ; String urlPath = ( String ) node . get ( Dataset . UrlPath ) ; String ftypeS = ( String ) node . getFldOrInherited ( Dataset . FeatureType ) ; if ( sname == null && urlPath != null && ftypeS != null ) { Service s = globalServices . getStandardServices ( ftypeS ) ; if ( s != null ) { node . put ( Dataset . ServiceName , s . getName ( ) ) ; cat . addService ( s ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize the HttpClient layer . [CODESPLIT] static public void init ( CredentialsProvider provider , String userAgent ) { if ( provider != null ) try { HTTPSession . setGlobalCredentialsProvider ( provider ) ; } catch ( HTTPException e ) { throw new IllegalArgumentException ( e ) ; } if ( userAgent != null ) HTTPSession . setGlobalUserAgent ( userAgent + \"/NetcdfJava/HttpClient\" ) ; else HTTPSession . setGlobalUserAgent ( \"NetcdfJava/HttpClient\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the content from a url . For large returns its better to use getResponseAsStream . [CODESPLIT] @ Urlencoded @ Deprecated public static String getContentAsString ( HTTPSession session , String urlencoded ) throws IOException { HTTPSession useSession = session ; try { if ( useSession == null ) useSession = HTTPFactory . newSession ( urlencoded ) ; try ( HTTPMethod m = HTTPFactory . Get ( useSession , urlencoded ) ) { m . execute ( ) ; return m . getResponseAsString ( ) ; } } finally { if ( ( session == null ) && ( useSession != null ) ) useSession . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put content to a url using HTTP PUT . Handles one level of 302 redirection . [CODESPLIT] public static int putContent ( String urlencoded , String content ) throws IOException { try ( HTTPMethod m = HTTPFactory . Put ( urlencoded ) ) { m . setRequestContent ( new StringEntity ( content , \"application/text\" , \"UTF-8\" ) ) ; m . execute ( ) ; int resultCode = m . getStatusCode ( ) ; // followRedirect wont work for PUT if ( resultCode == 302 ) { String redirectLocation ; Header locationHeader = m . getResponseHeader ( \"location\" ) ; if ( locationHeader != null ) { redirectLocation = locationHeader . getValue ( ) ; resultCode = putContent ( redirectLocation , content ) ; } } return resultCode ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////// [CODESPLIT] static public String getUrlContentsAsString ( String urlencoded , int maxKbytes ) throws IOException { return getUrlContentsAsString ( null , urlencoded , maxKbytes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the Relatove Operation ( RelOp ) indicated by the parameter <code > oprtr< / code > on the 2 passed BaseTypes if appropriate . <p / > Obviously some type don t compare logically such as asking if String is less than a Float . For these non sensical operations and <code > InvalidOperatorException< / code > is thrown . [CODESPLIT] public static boolean op ( int oprtr , BaseType lop , BaseType rop ) throws InvalidOperatorException , RegExpException , SBHException { if ( lop instanceof DByte ) return ( op ( oprtr , ( DByte ) lop , rop ) ) ; else if ( lop instanceof DFloat32 ) return ( op ( oprtr , ( DFloat32 ) lop , rop ) ) ; else if ( lop instanceof DFloat64 ) return ( op ( oprtr , ( DFloat64 ) lop , rop ) ) ; else if ( lop instanceof DInt16 ) return ( op ( oprtr , ( DInt16 ) lop , rop ) ) ; else if ( lop instanceof DInt32 ) return ( op ( oprtr , ( DInt32 ) lop , rop ) ) ; else if ( lop instanceof DString ) return ( op ( oprtr , ( DString ) lop , rop ) ) ; else if ( lop instanceof DUInt16 ) return ( op ( oprtr , ( DUInt16 ) lop , rop ) ) ; else if ( lop instanceof DUInt32 ) return ( op ( oprtr , ( DUInt32 ) lop , rop ) ) ; else if ( lop instanceof DURL ) return ( op ( oprtr , ( DURL ) lop , rop ) ) ; else throw new InvalidOperatorException ( \"Binary operations not supported for the type:\" + lop . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************************************************************** [CODESPLIT] private static String opErrorMsg ( int oprtr , String lop , String rop ) { switch ( oprtr ) { case LESS : return ( \"Less Than (<) Operator not valid between types\" + lop + \"and\" + rop + \".\" ) ; case LESS_EQL : return ( \"Less Than Equal To (<=) Operator not valid between types\" + lop + \"and\" + rop + \".\" ) ; case GREATER : return ( \"Greater Than (>) Operator not valid between types\" + lop + \"and\" + rop + \".\" ) ; case GREATER_EQL : return ( \"Greater Than Equal To (>=) Operator not valid between types\" + lop + \"and\" + rop + \".\" ) ; case EQUAL : return ( \"Equal To (==) Operator not valid between types\" + lop + \"and\" + rop + \".\" ) ; case NOT_EQUAL : return ( \"Not Equal To (!=) Operator not valid between types\" + lop + \"and\" + rop + \".\" ) ; case REGEXP : return ( \"Regular Expression cannot beevaluated between types\" + lop + \"and\" + rop + \".\" ) ; default : return ( \"Unknown Operator Requested! RTFM!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------------------------ [CODESPLIT] private static boolean op ( int oprtr , DFloat32 lop , DByte rop ) throws InvalidOperatorException { switch ( oprtr ) { case LESS : return ( lop . getValue ( ) < rop . getValue ( ) ) ; case LESS_EQL : return ( lop . getValue ( ) <= rop . getValue ( ) ) ; case GREATER : return ( lop . getValue ( ) > rop . getValue ( ) ) ; case GREATER_EQL : return ( lop . getValue ( ) >= rop . getValue ( ) ) ; case EQUAL : return ( lop . getValue ( ) == rop . getValue ( ) ) ; case NOT_EQUAL : return ( lop . getValue ( ) != rop . getValue ( ) ) ; case REGEXP : throw new InvalidOperatorException ( opErrorMsg ( oprtr , lop . getTypeName ( ) , rop . getTypeName ( ) ) ) ; default : throw new InvalidOperatorException ( \"Unknown Operator Requested! RTFM!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------------------------ [CODESPLIT] private static boolean op ( int oprtr , DUInt16 lop , DByte rop ) throws InvalidOperatorException { int lval = ( ( int ) lop . getValue ( ) ) & 0xFFFF ; switch ( oprtr ) { case LESS : return ( lval < rop . getValue ( ) ) ; case LESS_EQL : return ( lval <= rop . getValue ( ) ) ; case GREATER : return ( lval > rop . getValue ( ) ) ; case GREATER_EQL : return ( lval >= rop . getValue ( ) ) ; case EQUAL : return ( lval == rop . getValue ( ) ) ; case NOT_EQUAL : return ( lval != rop . getValue ( ) ) ; case REGEXP : throw new InvalidOperatorException ( opErrorMsg ( oprtr , lop . getTypeName ( ) , rop . getTypeName ( ) ) ) ; default : throw new InvalidOperatorException ( \"Unknown Operator Requested! RTFM!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capabilities processors [CODESPLIT] @ Override protected void doFavicon ( String icopath , DapContext cxt ) throws IOException { DapRequest drq = ( DapRequest ) cxt . get ( DapRequest . class ) ; String favfile = getResourcePath ( drq , icopath ) ; if ( favfile != null ) { try ( FileInputStream fav = new FileInputStream ( favfile ) ; ) { byte [ ] content = DapUtil . readbinaryfile ( fav ) ; OutputStream out = drq . getOutputStream ( ) ; out . write ( content ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Isolate front page builder so we can override if desired for testing . [CODESPLIT] protected FrontPage getFrontPage ( DapRequest drq , DapContext cxt ) throws DapException { if ( this . defaultroots == null ) { // Figure out the directory containing // the files to display. String pageroot ; pageroot = getResourcePath ( drq , \"\" ) ; if ( pageroot == null ) throw new DapException ( \"Cannot locate resources directory\" ) ; this . defaultroots = new ArrayList <> ( ) ; this . defaultroots . add ( new Root ( \"testfiles\" , pageroot ) ) ; } return new FrontPage ( this . defaultroots , drq ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////// [CODESPLIT] private String makeCollectionShortName ( String collectionName ) { String topCollectionName = config . collectionName ; if ( collectionName . equals ( topCollectionName ) ) return topCollectionName ; if ( collectionName . startsWith ( topCollectionName ) ) { return name + collectionName . substring ( topCollectionName . length ( ) ) ; } return collectionName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this catalog lists the individual files comprising the collection . [CODESPLIT] protected void addFileDatasets ( DatasetBuilder parent , String parentPath , GribCollectionImmutable fromGc ) throws IOException { DatasetBuilder filesParent = new DatasetBuilder ( parent ) ; filesParent . setName ( \"Raw Files\" ) ; filesParent . addServiceToCatalog ( downloadService ) ; ThreddsMetadata tmi = filesParent . getInheritableMetadata ( ) ; tmi . set ( Dataset . ServiceName , downloadService . getName ( ) ) ; parent . addDataset ( filesParent ) ; List < MFile > mfiles = new ArrayList <> ( fromGc . getFiles ( ) ) ; Collections . sort ( mfiles ) ; // if not increasing (i.e. we WANT newest file listed first), reverse sort if ( ! this . config . getSortFilesAscending ( ) ) { Collections . reverse ( mfiles ) ; } for ( MFile mfile : mfiles ) { DatasetBuilder ds = new DatasetBuilder ( parent ) ; ds . setName ( mfile . getName ( ) ) ; String lpath = parentPath + \"/\" + FILES + \"/\" + mfile . getName ( ) ; ds . put ( Dataset . UrlPath , lpath ) ; ds . put ( Dataset . Id , lpath ) ; ds . put ( Dataset . DataSize , mfile . getLength ( ) ) ; if ( mfile . getLastModified ( ) > 0 ) { CalendarDate cdate = CalendarDate . of ( mfile . getLastModified ( ) ) ; ds . put ( Dataset . Dates , new DateType ( cdate ) . setType ( \"modified\" ) ) ; } filesParent . addDataset ( ds ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see top javadoc for possible URLs [CODESPLIT] @ Override public CatalogBuilder makeCatalog ( String match , String reqPath , URI catURI ) throws IOException { StateGrib localState = ( StateGrib ) checkState ( ) ; if ( localState == null ) return null ; // not ready yet maybe if ( localState . gribCollection == null ) return null ; // not ready yet maybe try { // case 0 if ( ( match == null ) || ( match . length ( ) == 0 ) ) { return makeCatalogTop ( catURI , localState ) ; // top catalog : uses state.top previously made in checkState() } // case 1 if ( localState . gribCollection instanceof PartitionCollectionImmutable ) { String [ ] paths = match . split ( \"/\" ) ; PartitionCollectionImmutable pc = ( PartitionCollectionImmutable ) localState . gribCollection ; return makeCatalogFromPartition ( pc , paths , 0 , catURI ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; logger . error ( \"Error making catalog for \" + configPath , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////// [CODESPLIT] @ Override protected DatasetBuilder makeDatasetTop ( URI catURI , State state ) throws IOException { StateGrib localState = ( StateGrib ) state ; return makeDatasetFromCollection ( catURI , true , null , null , localState . gribCollection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK how come we arent using MetadataExtractor ?? [CODESPLIT] private ThreddsMetadata . GeospatialCoverage extractGeospatial ( GribCollectionImmutable . GroupGC group ) { GdsHorizCoordSys gdsCoordSys = group . getGdsHorizCoordSys ( ) ; LatLonRect llbb = GridCoordSys . getLatLonBoundingBox ( gdsCoordSys . proj , gdsCoordSys . getStartX ( ) , gdsCoordSys . getStartY ( ) , gdsCoordSys . getEndX ( ) , gdsCoordSys . getEndY ( ) ) ; double dx = 0.0 , dy = 0.0 ; if ( gdsCoordSys . isLatLon ( ) ) { dx = Math . abs ( gdsCoordSys . dx ) ; dy = Math . abs ( gdsCoordSys . dy ) ; } return new ThreddsMetadata . GeospatialCoverage ( llbb , null , dx , dy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns visitor . obtain () either a GridDataset or a NetcdfDataset [CODESPLIT] private Object findDataset ( String matchPath , GribCollectionImmutable topCollection , DatasetCreator visit ) throws IOException { String [ ] paths = matchPath . split ( \"/\" ) ; List < String > pathList = ( paths . length < 1 ) ? new ArrayList <> ( ) : Arrays . asList ( paths ) ; DatasetAndGroup dg = findDatasetAndGroup ( pathList , topCollection ) ; if ( dg != null ) return visit . obtain ( topCollection , dg . ds , dg . group ) ; if ( ! ( topCollection instanceof PartitionCollectionImmutable ) ) return null ; PartitionCollectionImmutable pc = ( PartitionCollectionImmutable ) topCollection ; return findDatasetPartition ( visit , pc , pathList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * case 0 : path / dataset ( dataset = ) // single dataset case 1 : path / dataset ( dataset = BEST TWOD TP ) // single group case 2 : path / dataset / groupName // dataset with group case 3 : path / groupName // single dataset not sure this is actually used ?? [CODESPLIT] private DatasetAndGroup findDatasetAndGroup ( List < String > paths , GribCollectionImmutable gc ) { if ( paths . size ( ) < 1 || paths . get ( 0 ) . length ( ) == 0 ) { // case 0: use first dataset,group in the collection GribCollectionImmutable . Dataset ds = gc . getDataset ( 0 ) ; GribCollectionImmutable . GroupGC dg = ds . getGroup ( 0 ) ; return new DatasetAndGroup ( ds , dg ) ; } GribCollectionImmutable . Dataset ds = getSingleDatasetOrByTypeName ( gc , paths . get ( 0 ) ) ; if ( ds == null ) return null ; boolean isSingleGroup = ds . getGroupsSize ( ) == 1 ; if ( isSingleGroup ) { GribCollectionImmutable . GroupGC g = ds . getGroup ( 0 ) ; // case 1 return new DatasetAndGroup ( ds , g ) ; } // otherwise last component is group name String groupName = ( paths . size ( ) == 1 ) ? paths . get ( 0 ) : paths . get ( 1 ) ; // case 3 else case 2 GribCollectionImmutable . GroupGC g = ds . findGroupById ( groupName ) ; if ( g != null ) return new DatasetAndGroup ( ds , g ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "kinda kludgey but trying not keep URLs stable [CODESPLIT] public GribCollectionImmutable . Dataset getSingleDatasetOrByTypeName ( GribCollectionImmutable gc , String typeName ) { if ( gc . getDatasets ( ) . size ( ) == 1 ) return gc . getDataset ( 0 ) ; for ( GribCollectionImmutable . Dataset ds : gc . getDatasets ( ) ) if ( ds . getType ( ) . toString ( ) . equalsIgnoreCase ( typeName ) ) return ds ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cannot do approx equals and be consistent with hashCode so make seperate call [CODESPLIT] public boolean nearlyEquals ( VertCoordValue other ) { return Misc . nearlyEquals ( value1 , other . value1 ) && Misc . nearlyEquals ( value2 , other . value2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for constructing an identifier from a name plural and symbol . [CODESPLIT] public static UnitID newUnitID ( final String name , final String plural , final String symbol ) { UnitID id ; try { id = name == null ? new UnitSymbol ( symbol ) : UnitName . newUnitName ( name , plural , symbol ) ; } catch ( final NameException e ) { id = null ; // can't happen } return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an attribute spec [CODESPLIT] public static GradsAttribute parseAttribute ( String attrSpec ) { String [ ] toks = attrSpec . split ( \"\\\\s+\" ) ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = 4 ; i < toks . length ; i ++ ) { buf . append ( toks [ i ] ) ; buf . append ( \" \" ) ; } // toks[0] is \"@\" return new GradsAttribute ( toks [ 1 ] , toks [ 2 ] , toks [ 3 ] , buf . toString ( ) . trim ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read the header of input file and parsing the NOWRAD part [CODESPLIT] int readTop ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { int pos = 0 ; // long     actualSize = 0;\r raf . seek ( pos ) ; int readLen = 35 ; // Read in the contents of the NEXRAD Level III product head\r byte [ ] b = new byte [ readLen ] ; int rc = raf . read ( b ) ; if ( rc != readLen ) { return 0 ; } // check\r if ( ( convertunsignedByte2Short ( b [ 0 ] ) != 0x00 ) || ( convertunsignedByte2Short ( b [ 1 ] ) != 0xF0 ) || ( convertunsignedByte2Short ( b [ 2 ] ) != 0x09 ) ) { return 0 ; } String pidd = new String ( b , 15 , 5 , CDM . utf8Charset ) ; if ( pidd . contains ( \"NOWRA\" ) || pidd . contains ( \"USRAD\" ) || pidd . contains ( \"NEX\" ) ) { return 1 ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read and parse the header of the nids / tdwr file [CODESPLIT] void read ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile ) throws Exception { this . raf = raf ; int rc ; /* function return status */ int hoffset ; int readLen = 250 ; this . ncfile = ncfile ; int pos = 0 ; raf . seek ( pos ) ; byte [ ] b = new byte [ readLen ] ; rc = raf . read ( b ) ; if ( rc != readLen ) { log . warn ( \" error reading nids product header \" + raf . getLocation ( ) ) ; } int hsize = b [ 3 ] ; String product = new String ( b , 15 , 8 , CDM . utf8Charset ) ; // image lines\r //byte[] bt   = new byte[] { (byte) 0xF0, (byte) 0x0A };\r int t1 = 0 ; int ii = 0 ; for ( int i = 0 ; i < readLen ; i ++ ) { if ( convertunsignedByte2Short ( b [ i + hsize ] ) == 0xF0 && convertunsignedByte2Short ( b [ i + 1 + hsize ] ) == 0x0A ) { t1 = i + hsize ; ii = i ; break ; } } if ( t1 == 0 ) return ; // if(convertunsignedByte2Short(b[6+hsize]) != 0xF0 ||\r // convertunsignedByte2Short(b[7+hsize]) != 0x0A )\r // return;\r String lstr = trim ( new String ( b , t1 + 2 , 4 , CDM . utf8Charset ) ) ; numY = Integer . parseInt ( lstr ) ; String estr = trim ( new String ( b , t1 + 6 , 5 , CDM . utf8Charset ) ) ; numX = Integer . parseInt ( estr ) ; //bt   = new byte[] { (byte) 0xF0, (byte) 0x03 };\r t1 = 0 ; for ( int i = ii ; i < readLen ; i ++ ) { if ( convertunsignedByte2Short ( b [ i + hsize ] ) == 0xF0 && convertunsignedByte2Short ( b [ i + 1 + hsize ] ) == 0x03 ) { t1 = i + hsize ; ii = i ; break ; } } if ( t1 == 0 ) return ; // if((lstr.length()+estr.length() < 8))\r // hsize = hsize -2;\r // if(convertunsignedByte2Short(b[18+hsize]) != 0xF0 ||\r // convertunsignedByte2Short(b[19+hsize]) != 0x03 )\r // return;\r int off = 0 ; if ( product . contains ( \"USRADHF\" ) ) { off = 3 ; } // Image time, HHMMSS.  The time will be in the form HH:MM, so look :\r String ts = new String ( b , t1 + 22 + off , 2 , CDM . utf8Charset ) ; int hr = Integer . parseInt ( ts ) ; ts = new String ( b , t1 + 25 + off , 2 , CDM . utf8Charset ) ; int min = Integer . parseInt ( ts ) ; ts = new String ( b , t1 + 28 + off , 2 , CDM . utf8Charset ) ; int dd = Integer . parseInt ( ts ) ; ts = new String ( b , t1 + 31 + off , 3 , CDM . utf8Charset ) ; String mon = ts ; int month = getMonth ( mon ) ; ts = new String ( b , t1 + 35 + off , 2 , CDM . utf8Charset ) ; int year = Integer . parseInt ( ts ) ; SimpleDateFormat sdf = new SimpleDateFormat ( ) ; sdf . setTimeZone ( TimeZone . getTimeZone ( \"GMT\" ) ) ; sdf . applyPattern ( \"yyyy/MM/dd HH:mm\" ) ; Date date = sdf . parse ( year + \"/\" + month + \"/\" + dd + \" \" + hr + \":\" + min ) ; //bt = new byte[] { (byte) 0xF0, (byte) 0x0b };\r t1 = 0 ; for ( int i = ii ; i < readLen ; i ++ ) { if ( convertunsignedByte2Short ( b [ i + hsize ] ) == 0xF0 && convertunsignedByte2Short ( b [ i + 1 + hsize ] ) == 0x0b ) { t1 = i + hsize ; break ; } } if ( t1 == 0 ) return ; // if( convertunsignedByte2Short(b[101 + hsize]) != 0xF0 ||\r // convertunsignedByte2Short(b[102 + hsize]) != 0x0b )\r // return;\r if ( product . contains ( \"NOWRAD\" ) ) { String ot = new String ( b , t1 + 2 , 68 , CDM . utf8Charset ) ; //List<String> toks = StringUtil.split(ot, \" \", true, true);\r String [ ] toks = StringUtil2 . splitString ( ot ) ; double nav1 = Math . toDegrees ( Double . parseDouble ( toks [ 1 ] ) ) ; // lon\r double nav2 = Math . toDegrees ( Double . parseDouble ( toks [ 2 ] ) ) ; // lat\r double nav3 = Math . toDegrees ( Double . parseDouble ( toks [ 3 ] ) ) ; double nav4 = Math . toDegrees ( Double . parseDouble ( toks [ 4 ] ) ) ; // lat sp\r double nav5 = Math . toDegrees ( Double . parseDouble ( toks [ 5 ] ) ) ; // lon sp\r // lower left and upper right corner\r float rlat1 ; float rlon1 ; float rlat2 ; float rlon2 ; rlat1 = ( float ) ( nav2 - ( numY - 1 ) * nav4 ) ; rlon1 = ( float ) ( nav1 + nav3 ) ; rlat2 = ( float ) nav2 ; rlon2 = ( float ) ( nav1 - nav3 ) ; hoffset = t1 + 71 ; // 172 + hsize;\r // start of the image sequence\r if ( ( convertunsignedByte2Short ( b [ 172 + hsize ] ) != 0xF0 ) || ( convertunsignedByte2Short ( b [ 173 + hsize ] ) != 0x0c ) ) { return ; } // hoffset = 174 + hsize;\r // Set product-dependent information\r setProductInfo ( product , date ) ; // data struct\r nowrad ( hoffset , rlat1 , rlon1 , rlat2 , rlon2 , ( float ) nav4 , ( float ) nav5 , date ) ; } else if ( product . contains ( \"USRADHF\" ) ) { String ot = new String ( b , t1 + 2 , 107 , CDM . utf8Charset ) ; String [ ] toks = StringUtil2 . splitString ( ot ) ; double nav1 = Math . toDegrees ( Double . parseDouble ( toks [ 1 ] ) ) ; // standard lat 1\r double nav2 = Math . toDegrees ( Double . parseDouble ( toks [ 2 ] ) ) ; // standard lat 2\r double nav3 = Math . toDegrees ( Double . parseDouble ( toks [ 3 ] ) ) ; // lat. center of proj\r double nav4 = Math . toDegrees ( Double . parseDouble ( toks [ 4 ] ) ) ; // lon. center of proj\r double nav5 = Math . toDegrees ( Double . parseDouble ( toks [ 5 ] ) ) ; // upper left lat\r double nav6 = Math . toDegrees ( Double . parseDouble ( toks [ 6 ] ) ) ; // upper left lon\r /* List<String> toks = StringUtil.split(ot, \" \", true, true);\r\n            String       pj   = toks.get(0);\r\n            double       nav1 = Math.toDegrees(Double.parseDouble(toks.get(1)));    // standard lat 1\r\n            double       nav2 = Math.toDegrees(Double.parseDouble(toks.get(2)));    // standard lat 2\r\n            double       nav3 = Math.toDegrees(Double.parseDouble(toks.get(3)));    // lat. center of proj\r\n            double       nav4 = Math.toDegrees(Double.parseDouble(toks.get(4)));    // lon. center of proj\r\n            double       nav5 = Math.toDegrees(Double.parseDouble(toks.get(5)));    // upper left lat\r\n            double       nav6 = Math.toDegrees(Double.parseDouble(toks.get(6)));    // upper left lon\r\n            double       nav7 = Math.toDegrees(Double.parseDouble(toks.get(7)));    // lat sp\r\n            double       nav8 = Math.toDegrees(Double.parseDouble(toks.get(8)));    // lon sp  */ // lower left and upper right corner\r // int offh = 39;\r hoffset = t1 + 110 ; // 172 + hsize+ offh;\r // start of the image sequence\r if ( ( convertunsignedByte2Short ( b [ t1 + 110 ] ) != 0xF0 ) || ( convertunsignedByte2Short ( b [ t1 + 111 ] ) != 0x0c ) ) { return ; } // Set product-dependent information\r setProductInfo ( product , date ) ; // data struct\r nowradL ( hoffset , ( float ) nav1 , ( float ) nav2 , ( float ) nav3 , ( float ) nav4 , ( float ) nav5 , ( float ) nav6 , date ) ; } ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a raster dataset for NIDS raster products ; [CODESPLIT] ProjectionImpl nowrad ( int hoff , float rlat1 , float rlon1 , float rlat2 , float rlon2 , float dlat , float dlon , Date dd ) { List < Dimension > dims = new ArrayList <> ( ) ; Dimension dimT = new Dimension ( \"time\" , 1 , true , false , false ) ; ncfile . addDimension ( null , dimT ) ; String timeCoordName = \"time\" ; Variable taxis = new Variable ( ncfile , null , null , timeCoordName ) ; taxis . setDataType ( DataType . DOUBLE ) ; taxis . setDimensions ( \"time\" ) ; taxis . addAttribute ( new Attribute ( CDM . LONG_NAME , \"time since base date\" ) ) ; taxis . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ) ; double [ ] tdata = new double [ 1 ] ; tdata [ 0 ] = dd . getTime ( ) ; Array dataT = Array . factory ( DataType . DOUBLE , new int [ ] { 1 } , tdata ) ; taxis . setCachedData ( dataT , false ) ; DateFormatter formatter = new DateFormatter ( ) ; taxis . addAttribute ( new Attribute ( CDM . UNITS , \"msecs since \" + formatter . toDateTimeStringISO ( new Date ( 0 ) ) ) ) ; ncfile . addVariable ( null , taxis ) ; dims . add ( dimT ) ; Dimension jDim = new Dimension ( \"lat\" , numY , true , false , false ) ; Dimension iDim = new Dimension ( \"lon\" , numX , true , false , false ) ; dims . add ( jDim ) ; dims . add ( iDim ) ; ncfile . addDimension ( null , iDim ) ; ncfile . addDimension ( null , jDim ) ; ncfile . addAttribute ( null , new Attribute ( \"cdm_data_type\" , FeatureType . GRID . toString ( ) ) ) ; String coordinates = \"time lat lon\" ; Variable v = new Variable ( ncfile , null , null , cname ) ; v . setDataType ( DataType . BYTE ) ; v . setDimensions ( dims ) ; ncfile . addVariable ( null , v ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , ctitle ) ) ; v . addAttribute ( new Attribute ( CDM . SCALE_FACTOR , 5.0f ) ) ; v . addAttribute ( new Attribute ( CDM . MISSING_VALUE , 0 ) ) ; v . addAttribute ( new Attribute ( CDM . UNITS , cunit ) ) ; v . setSPobject ( new Vinfo ( numX , numY , hoff ) ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; // create coordinate variables\r Variable xaxis = new Variable ( ncfile , null , null , \"lon\" ) ; xaxis . setDataType ( DataType . DOUBLE ) ; xaxis . setDimensions ( \"lon\" ) ; xaxis . addAttribute ( new Attribute ( CDM . LONG_NAME , \"longitude\" ) ) ; xaxis . addAttribute ( new Attribute ( CDM . UNITS , \"degree\" ) ) ; xaxis . addAttribute ( new Attribute ( _Coordinate . AxisType , \"Lon\" ) ) ; double [ ] data1 = new double [ numX ] ; for ( int i = 0 ; i < numX ; i ++ ) { data1 [ i ] = ( double ) ( rlon1 + i * dlon ) ; } Array dataA = Array . factory ( DataType . DOUBLE , new int [ ] { numX } , data1 ) ; xaxis . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , xaxis ) ; Variable yaxis = new Variable ( ncfile , null , null , \"lat\" ) ; yaxis . setDataType ( DataType . DOUBLE ) ; yaxis . setDimensions ( \"lat\" ) ; yaxis . addAttribute ( new Attribute ( CDM . LONG_NAME , \"latitude\" ) ) ; yaxis . addAttribute ( new Attribute ( CDM . UNITS , \"degree\" ) ) ; yaxis . addAttribute ( new Attribute ( _Coordinate . AxisType , \"Lat\" ) ) ; data1 = new double [ numY ] ; for ( int i = 0 ; i < numY ; i ++ ) { data1 [ i ] = rlat1 + i * dlat ; } dataA = Array . factory ( DataType . DOUBLE , new int [ ] { numY } , data1 ) ; yaxis . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , yaxis ) ; // projection\r // lower left and upper right corner lat/lons\r // modified cylind. equidistant or  CED with lat/lon ration != 1\r /*    LatLonProjection llproj = new LatLonProjection(\"LatitudeLongitudeProjection\",\r\n                                  new ProjectionRect(rlat1, rlon1, rlat2, rlon2));\r\n        Variable ct = new Variable(ncfile, null, null, llproj.getClassName());\r\n\r\n        ct.setDataType(DataType.CHAR);\r\n        ct.setDimensions(\"\");\r\n\r\n        List params = llproj.getProjectionParameters();\r\n\r\n        for (int i = 0; i < params.size(); i++) {\r\n            Parameter p = (Parameter) params.get(i);\r\n\r\n            ct.addAttribute(new Attribute(p));\r\n        }\r\n\r\n        ct.addAttribute(new Attribute(_Coordinate.TransformType, \"Projection\"));\r\n        ct.addAttribute(new Attribute(_Coordinate.Axes, \"lat lon\"));\r\n\r\n        // fake data\r\n        dataA = Array.factory(DataType.CHAR, new int[] {});\r\n        dataA.setChar(dataA.getIndex(), ' ');\r\n        ct.setCachedData(dataA, false);\r\n        ncfile.addVariable(null, ct);\r\n      */ return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parsing the product information into netcdf dataset [CODESPLIT] void setProductInfo ( String prod , Date dd ) { String summary = null ; if ( prod . contains ( \"NOWRADHF\" ) ) { cmemo = \"NOWRAD  Base Reflectivity at Tilt 1\" ; ctitle = \"BREF: Base Reflectivity [dBZ]\" ; cunit = \"dBZ\" ; cname = \"Reflectivity\" ; summary = \"NOWRAD Product\" ; } else if ( prod . contains ( \"USRADHF\" ) ) { cmemo = \"NOWRAD  Base Reflectivity at Tilt 1\" ; ctitle = \"BREF: Base Reflectivity [dBZ]\" ; cunit = \"dBZ\" ; cname = \"Reflectivity\" ; summary = \"NOWRAD Product\" ; } else if ( prod . contains ( \"NEXET\" ) ) { cmemo = \"NOWRAD Echo Tops\" ; ctitle = \"Echo Tops Composite\" ; cunit = \"K FT\" ; cname = \"EchoTopsComposite\" ; summary = \"NOWRAD Product\" ; } else if ( prod . contains ( \"NEXLL\" ) ) { cmemo = \"NOWRAD Layer Comp. Reflectivity - Low\" ; ctitle = \"LayerReflectivityLow\" ; cunit = \"dBZ\" ; cname = \"Reflectivity\" ; summary = \"NOWRAD Product\" ; } else if ( prod . contains ( \"NEXLM\" ) ) { cmemo = \"NOWRAD Layer Comp. Reflectivity - Mid\" ; ctitle = \"LayerReflectivityMid\" ; cunit = \"dBZ\" ; cname = \"Reflectivity\" ; summary = \"NOWRAD Product\" ; } else if ( prod . contains ( \"NEXLH\" ) ) { cmemo = \"NOWRAD Layer Comp. Reflectivity - High\" ; ctitle = \"LayerReflectivityHigh\" ; cunit = \"dBZ\" ; cname = \"ReflectivityHigh\" ; summary = \"NOWRAD Product\" ; } else if ( prod . contains ( \"NEXVI\" ) ) { cmemo = \"NOWRAD \" ; ctitle = \"Vert. Integrated Liquid Water\" ; cunit = \"Knots\" ; cname = \"VILwater\" ; summary = \"NOWRAD \" ; } else { ctilt = \"error\" ; ctitle = \"error\" ; cunit = \"error\" ; cname = \"error\" ; } /* add geo global att */ ncfile . addAttribute ( null , new Attribute ( \"summary\" , \"NOWRAD radar composite products.\" + summary ) ) ; ncfile . addAttribute ( null , new Attribute ( \"title\" , \"NOWRAD\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"keywords\" , \"NOWRAD\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"creator_name\" , \"NOAA/NWS\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"creator_url\" , \"http://www.ncdc.noaa.gov/oa/radar/radarproducts.html\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"naming_authority\" , \"NOAA/NCDC\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"base_date\" , formatter . toDateOnlyString ( dd ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"conventions\" , _Coordinate . Convention ) ) ; ncfile . addAttribute ( null , new Attribute ( \"cdm_data_type\" , FeatureType . GRID . toString ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert two short into a integer [CODESPLIT] public static int shortsToInt ( short s1 , short s2 , boolean swapBytes ) { byte [ ] b = new byte [ 4 ] ; b [ 0 ] = ( byte ) ( s1 >>> 8 ) ; b [ 1 ] = ( byte ) ( s1 >>> 0 ) ; b [ 2 ] = ( byte ) ( s2 >>> 8 ) ; b [ 3 ] = ( byte ) ( s2 >>> 0 ) ; return bytesToInt ( b , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert bytes into integer [CODESPLIT] public static int bytesToInt ( byte [ ] bytes , boolean swapBytes ) { byte a = bytes [ 0 ] ; byte b = bytes [ 1 ] ; byte c = bytes [ 2 ] ; byte d = bytes [ 3 ] ; if ( swapBytes ) { return ( ( a & 0xff ) ) + ( ( b & 0xff ) << 8 ) + ( ( c & 0xff ) << 16 ) + ( ( d & 0xff ) << 24 ) ; } else { return ( ( a & 0xff ) << 24 ) + ( ( b & 0xff ) << 16 ) + ( ( c & 0xff ) << 8 ) + ( ( d & 0xff ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get jave date [CODESPLIT] static public java . util . Date getDate ( int julianDays , int msecs ) { long total = ( ( long ) ( julianDays - 1 ) ) * 24 * 3600 * 1000 + msecs ; return new Date ( total ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a static property . Supported static properties : <ul > <li > syncExtendOnly = true : assume all file changes are syncExtend only . < / ul > [CODESPLIT] static public void setProperty ( String name , String value ) { if ( name . equalsIgnoreCase ( \"syncExtendOnly\" ) ) syncExtendOnly = value . equalsIgnoreCase ( \"true\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should match makeValidNetcdfObjectName () [CODESPLIT] public static boolean isValidNetcdfObjectName ( String name ) { if ( name == null || name . isEmpty ( ) ) { // Null and empty names disallowed return false ; } int cp = name . codePointAt ( 0 ) ; // First char must be [a-z][A-Z][0-9]_ | UTF8 if ( cp <= 0x7f ) { if ( ! ( ' ' <= cp && cp <= ' ' ) && ! ( ' ' <= cp && cp <= ' ' ) && ! ( ' ' <= cp && cp <= ' ' ) && cp != ' ' ) { return false ; } } for ( int i = 1 ; i < name . length ( ) ; ++ i ) { cp = name . codePointAt ( i ) ; // handle simple 0x00-0x7f characters here if ( cp <= 0x7f ) { if ( cp < ' ' || cp > 0x7E || cp == ' ' ) { // control char, DEL, or forward-slash return false ; } } } if ( cp <= 0x7f && Character . isWhitespace ( cp ) ) { // trailing spaces disallowed return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a name to a legal netcdf - 3 name . [CODESPLIT] public static String makeValidNetcdfObjectName ( String name ) { StringBuilder sb = new StringBuilder ( name ) ; while ( sb . length ( ) > 0 ) { int cp = sb . codePointAt ( 0 ) ; // First char must be [a-z][A-Z][0-9]_ | UTF8 if ( cp <= 0x7f ) { if ( ! ( ' ' <= cp && cp <= ' ' ) && ! ( ' ' <= cp && cp <= ' ' ) && ! ( ' ' <= cp && cp <= ' ' ) && cp != ' ' ) { sb . deleteCharAt ( 0 ) ; continue ; } } break ; } for ( int pos = 1 ; pos < sb . length ( ) ; ++ pos ) { int cp = sb . codePointAt ( pos ) ; // handle simple 0x00-0x7F characters here if ( cp <= 0x7F ) { if ( cp < ' ' || cp > 0x7E || cp == ' ' ) { // control char, DEL, or forward-slash sb . deleteCharAt ( pos ) ; -- pos ; } } } while ( sb . length ( ) > 0 ) { int cp = sb . codePointAt ( sb . length ( ) - 1 ) ; if ( cp <= 0x7f && Character . isWhitespace ( cp ) ) { sb . deleteCharAt ( sb . length ( ) - 1 ) ; } else { break ; } } if ( sb . length ( ) == 0 ) { throw new IllegalArgumentException ( String . format ( \"Illegal NetCDF object name: '%s'\" , name ) ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given name can be used for a Dimension Attribute or Variable name . Should match makeValidNetcdf3ObjectName . [CODESPLIT] static public boolean isValidNetcdf3ObjectName ( String name ) { Matcher m = objectNamePatternOld . matcher ( name ) ; return m . matches ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read existing file [CODESPLIT] @ Override public void openForWriting ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { open ( raf , ncfile , cancelTask ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "data reading [CODESPLIT] @ Override public Array readData ( ucar . nc2 . Variable v2 , Section section ) throws IOException , InvalidRangeException { /* if (debugRead) {\n      System.out.printf(\"debugRead %s %s%n\", v2.toStringDebug(), section);\n      if (v2.getShortName().equals(\"cref\"))\n        System.out.println(\"HEY\");\n    } */ if ( v2 instanceof Structure ) return readRecordData ( ( Structure ) v2 , section ) ; N3header . Vinfo vinfo = ( N3header . Vinfo ) v2 . getSPobject ( ) ; DataType dataType = v2 . getDataType ( ) ; Layout layout = ( ! v2 . isUnlimited ( ) ) ? new LayoutRegular ( vinfo . begin , v2 . getElementSize ( ) , v2 . getShape ( ) , section ) : new LayoutRegularSegmented ( vinfo . begin , v2 . getElementSize ( ) , header . recsize , v2 . getShape ( ) , section ) ; if ( layout . getTotalNelems ( ) == 0 ) { return Array . factory ( dataType , section . getShape ( ) ) ; } Object data = readData ( layout , dataType ) ; return Array . factory ( dataType , section . getShape ( ) , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from record structure . For N3 this is the only possible structure and there can be no nesting . Read all variables for each record put in ByteBuffer . [CODESPLIT] private ucar . ma2 . Array readRecordData ( ucar . nc2 . Structure s , Section section ) throws java . io . IOException { //if (s.isSubset()) //  return readRecordDataSubset(s, section); // has to be 1D Range recordRange = section . getRange ( 0 ) ; // create the ArrayStructure StructureMembers members = s . makeStructureMembers ( ) ; for ( StructureMembers . Member m : members . getMembers ( ) ) { Variable v2 = s . findVariable ( m . getName ( ) ) ; N3header . Vinfo vinfo = ( N3header . Vinfo ) v2 . getSPobject ( ) ; m . setDataParam ( ( int ) ( vinfo . begin - header . recStart ) ) ; } // protect agains too large of reads if ( header . recsize > Integer . MAX_VALUE ) throw new IllegalArgumentException ( \"Cant read records when recsize > \" + Integer . MAX_VALUE ) ; long nrecs = section . computeSize ( ) ; if ( nrecs * header . recsize > Integer . MAX_VALUE ) throw new IllegalArgumentException ( \"Too large read: nrecs * recsize= \" + ( nrecs * header . recsize ) + \"bytes exceeds \" + Integer . MAX_VALUE ) ; members . setStructureSize ( ( int ) header . recsize ) ; ArrayStructureBB structureArray = new ArrayStructureBB ( members , new int [ ] { recordRange . length ( ) } ) ; // note dependency on raf; should probably defer to subclass // loop over records byte [ ] result = structureArray . getByteBuffer ( ) . array ( ) ; int count = 0 ; for ( int recnum : recordRange ) { if ( debugRecord ) System . out . println ( \" read record \" + recnum ) ; raf . seek ( header . recStart + recnum * header . recsize ) ; // where the record starts if ( recnum != header . numrecs - 1 ) raf . readFully ( result , ( int ) ( count * header . recsize ) , ( int ) header . recsize ) ; else raf . read ( result , ( int ) ( count * header . recsize ) , ( int ) header . recsize ) ; // \"wart\" allows file to be one byte short. since its always padding, we allow count ++ ; } return structureArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from record structure that has been subsetted . Read one record at at time put requested variable into ArrayStructureMA . [CODESPLIT] private ucar . ma2 . Array readRecordDataSubset ( ucar . nc2 . Structure s , Section section ) throws java . io . IOException { Range recordRange = section . getRange ( 0 ) ; int nrecords = recordRange . length ( ) ; // create the ArrayStructureMA StructureMembers members = s . makeStructureMembers ( ) ; for ( StructureMembers . Member m : members . getMembers ( ) ) { Variable v2 = s . findVariable ( m . getName ( ) ) ; N3header . Vinfo vinfo = ( N3header . Vinfo ) v2 . getSPobject ( ) ; m . setDataParam ( ( int ) ( vinfo . begin - header . recStart ) ) ; // offset from start of record // construct the full shape int rank = m . getShape ( ) . length ; int [ ] fullShape = new int [ rank + 1 ] ; fullShape [ 0 ] = nrecords ; // the first dimension System . arraycopy ( m . getShape ( ) , 0 , fullShape , 1 , rank ) ; // the remaining dimensions Array data = Array . factory ( m . getDataType ( ) , fullShape ) ; m . setDataArray ( data ) ; m . setDataObject ( data . getIndexIterator ( ) ) ; } //LOOK this is all wrong - why using recsize ??? return null ; /* members.setStructureSize(recsize);\n    ArrayStructureMA structureArray = new ArrayStructureMA(members, new int[]{nrecords});\n\n    // note dependency on raf; should probably defer to subclass\n    // loop over records\n    byte[] record = new byte[ recsize];\n    ByteBuffer bb = ByteBuffer.wrap(record);\n    for (int recnum = recordRange.first(); recnum <= recordRange.last(); recnum += recordRange.stride()) {\n      if (debugRecord) System.out.println(\" readRecordDataSubset recno= \" + recnum);\n\n      // read one record\n      raf.seek(recStart + recnum * recsize); // where the record starts\n      if (recnum != numrecs - 1)\n        raf.readFully(record, 0, recsize);\n      else\n        raf.read(record, 0, recsize); // \"wart\" allows file to be one byte short. since its always padding, we allow\n\n      // transfer desired variable(s) to result array(s)\n      for (StructureMembers.Member m : members.getMembers()) {\n        IndexIterator dataIter = (IndexIterator) m.getDataObject();\n        IospHelper.copyFromByteBuffer(bb, m, dataIter);\n      }\n    }\n\n    return structureArray;  */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "protected HashMap dimHash = new HashMap ( 50 ) ; [CODESPLIT] @ Override public void create ( String filename , ucar . nc2 . NetcdfFile ncfile , int extra , long preallocateSize , boolean largeFile ) throws IOException { this . ncfile = ncfile ; this . readonly = false ; // finish any structures ncfile . finish ( ) ; raf = new ucar . unidata . io . RandomAccessFile ( filename , \"rw\" ) ; raf . order ( RandomAccessFile . BIG_ENDIAN ) ; if ( preallocateSize > 0 ) { java . io . RandomAccessFile myRaf = raf . getRandomAccessFile ( ) ; myRaf . setLength ( preallocateSize ) ; } header = new N3header ( ) ; header . create ( raf , ncfile , extra , largeFile , null ) ; //recsize = header.recsize;   // record size //recStart = header.recStart; // record variables start here //fileUsed = headerParser.getMinLength(); // track what is actually used _create ( raf ) ; if ( fill ) fillNonRecordVariables ( ) ; //else //  raf.setMinLength(recStart); // make sure file length is long enough, even if not written to. }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write [CODESPLIT] @ Override public void writeData ( Variable v2 , Section section , Array values ) throws java . io . IOException , InvalidRangeException { N3header . Vinfo vinfo = ( N3header . Vinfo ) v2 . getSPobject ( ) ; DataType dataType = v2 . getDataType ( ) ; if ( v2 . isUnlimited ( ) ) { Range firstRange = section . getRange ( 0 ) ; setNumrecs ( firstRange . last ( ) + 1 ) ; } if ( v2 instanceof Structure ) { if ( ! ( values instanceof ArrayStructure ) ) throw new IllegalArgumentException ( \"writeData for Structure: data must be ArrayStructure\" ) ; if ( v2 . getRank ( ) == 0 ) throw new IllegalArgumentException ( \"writeData for Structure: must have rank > 0\" ) ; Dimension d = v2 . getDimension ( 0 ) ; if ( ! d . isUnlimited ( ) ) throw new IllegalArgumentException ( \"writeData for Structure: must have unlimited dimension\" ) ; writeRecordData ( ( Structure ) v2 , section , ( ArrayStructure ) values ) ; } else { Layout layout = ( ! v2 . isUnlimited ( ) ) ? new LayoutRegular ( vinfo . begin , v2 . getElementSize ( ) , v2 . getShape ( ) , section ) : new LayoutRegularSegmented ( vinfo . begin , v2 . getElementSize ( ) , header . recsize , v2 . getShape ( ) , section ) ; writeData ( values , layout , dataType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the value of an existing attribute . Attribute is found by name which must match exactly . You cannot make an attribute longer or change the number of values . For strings : truncate if longer zero fill if shorter . Strings are padded to 4 byte boundaries ok to use padding if it exists . For numerics : must have same number of values . [CODESPLIT] @ Override public void updateAttribute ( ucar . nc2 . Variable v2 , Attribute att ) throws IOException { header . updateAttribute ( v2 , att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fill buffer with fill value [CODESPLIT] protected void fillNonRecordVariables ( ) throws IOException { // run through each variable for ( Variable v : ncfile . getVariables ( ) ) { if ( v . isUnlimited ( ) ) continue ; try { writeData ( v , v . getShapeAsSection ( ) , makeConstantArray ( v ) ) ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; // shouldnt happen } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public boolean syncExtend ( ) throws IOException { boolean result = header . synchNumrecs ( ) ; if ( result && log . isDebugEnabled ( ) ) log . debug ( \" N3iosp syncExtend \" + raf . getLocation ( ) + \" numrecs =\" + header . numrecs ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * @Override public boolean sync () throws IOException { if ( syncExtendOnly ) return syncExtend () ; [CODESPLIT] @ Override public void flush ( ) throws java . io . IOException { if ( raf != null ) { raf . flush ( ) ; header . writeNumrecs ( ) ; raf . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data values ( parameters are ignored ) . Use the start stop and stride values typically set by the constraint evaluator . [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws IOException { long tstart = System . currentTimeMillis ( ) ; Array a ; try { if ( log . isDebugEnabled ( ) ) log . debug ( getRequestedRange ( ) ) ; // set up the netcdf read int n = numDimensions ( ) ; List < Range > ranges = new ArrayList <> ( n ) ; for ( int i = 0 ; i < n ; i ++ ) ranges . ( new Range ( getStart ( i ) , getStop ( i ) , getStride ( i ) ) ) ; try { = ncVar . read ( ranges ) ; } catch ( java . lang . ArrayIndexOutOfBoundsException t ) { log . error ( getRequestedRange ( ) , t ) ; throw new RuntimeException ( \"NcSDArray java.lang.ArrayIndexOutOfBoundsException=\" + t . getMessage ( ) + \" for request= \" + getRequestedRange ( ) + \" dataset= \" + datasetName , t ) ; } if ( debug ) System . out . println ( \"  NcSDArray Read \" + getEncodedName ( ) + \" \" + a . getSize ( ) + \" elems of type = \" + a . getElementType ( ) ) ; if ( debugRead ) System . out . println ( \"  Read = \" + a . getSize ( ) + \" elems of type = \" + a . getElementType ( ) ) ; if ( log . isDebugEnabled ( ) ) { long tookTime = System . currentTimeMillis ( ) - tstart ; log . debug ( \"NcSDArray read array: \" + tookTime * .001 + \" seconds\" ) ; } } catch ( InvalidDimensionException e ) { log . error ( getRequestedRange ( ) , e ) ; throw new IllegalStateException ( \"NcSDArray InvalidDimensionException=\" + e . getMessage ( ) ) ; } catch ( InvalidRangeException e ) { log . error ( getRequestedRange ( ) , e ) ; throw new IllegalStateException ( \"NcSDArray InvalidRangeException=\" + e . getMessage ( ) ) ; } setData ( a ) ; if ( debugRead ) System . out . println ( \" PrimitiveVector len = \" + getPrimitiveVector ( ) . getLength ( ) + \" type = \" + getPrimitiveVector ( ) . getTemplate ( ) ) ; return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the level values from the specifications [CODESPLIT] protected double [ ] makeLevelValues ( ) { List < String > levels = getLevels ( ) ; if ( levels == null ) { return null ; } if ( levels . size ( ) != getSize ( ) ) { // do someting } // Time is always LINEAR int inc = 0 ; double [ ] vals = new double [ getSize ( ) ] ; String tstart = levels . get ( 0 ) . trim ( ) . toLowerCase ( ) ; String pattern = null ; if ( tstart . indexOf ( \":\" ) >= 0 ) { // HH:mmZddMMMyyyy pattern = dateFormats [ 0 ] ; } else if ( tstart . indexOf ( \"z\" ) >= 0 ) { // mmZddMMMyyyy pattern = dateFormats [ 1 ] ; } else if ( Character . isLetter ( tstart . charAt ( 0 ) ) ) { // MMMyyyy pattern = dateFormats [ 3 ] ; } else { pattern = dateFormats [ 2 ] ; // ddMMMyyyy } SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ; //sdf.setLenient(true); sdf . setTimeZone ( TimeZone . getTimeZone ( \"GMT\" ) ) ; ParsePosition p = new ParsePosition ( 0 ) ; Date d = sdf . parse ( tstart , p ) ; if ( d == null ) { System . out . println ( \"couldn't parse at \" + p . getErrorIndex ( ) ) ; d = new Date ( 0 ) ; } //System.out.println(\"start = \" + d); // set the unit sdf . applyPattern ( \"yyyy-MM-dd HH:mm:ss Z\" ) ; setUnit ( \"hours since \" + sdf . format ( d , new StringBuffer ( ) , new FieldPosition ( 0 ) ) ) ; // parse the increment // vvkk where // vv     =       an integer number, 1 or 2 digits // kk     =       mn (minute) //                hr (hour) //                dy (day) //                mo (month) //                yr (year)  String tinc = levels . get ( 1 ) . toLowerCase ( ) ; int incIndex = 0 ; for ( int i = 0 ; i < incStr . length ; i ++ ) { int index = tinc . indexOf ( incStr [ i ] ) ; if ( index < 0 ) { continue ; } int numOf = Integer . parseInt ( tinc . substring ( 0 , index ) ) ; inc = numOf ; incIndex = i ; break ; } Calendar calendar = Calendar . getInstance ( TimeZone . getTimeZone ( \"GMT\" ) ) ; calendar . setTime ( d ) ; vals [ 0 ] = 0 ; initialTime = makeTimeStruct ( calendar ) ; //System.out.println(\"initial time = \" + initialTime); int calInc = calIncs [ incIndex ] ; double hours = ( double ) 1000 * 60 * 60 ; for ( int i = 1 ; i < getSize ( ) ; i ++ ) { calendar . add ( calInc , inc ) ; // subtract from origin, convert to hours double offset = ( calendar . getTime ( ) . getTime ( ) - d . getTime ( ) ) / hours ; //millis in an hour vals [ i ] = offset ; } return vals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a time struct from the index . [CODESPLIT] public GradsTimeStruct makeTimeStruct ( int timeIndex ) { double tVal = getValues ( ) [ timeIndex ] ; Date d = DateUnit . getStandardDate ( tVal + \" \" + getUnit ( ) ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeZone ( java . util . TimeZone . getTimeZone ( \"GMT\" ) ) ; calendar . setTime ( d ) ; return makeTimeStruct ( calendar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a GradsTimeStruct from the calendar state [CODESPLIT] private GradsTimeStruct makeTimeStruct ( Calendar calendar ) { GradsTimeStruct ts = new GradsTimeStruct ( ) ; ts . year = calendar . get ( Calendar . YEAR ) ; ts . month = calendar . get ( Calendar . MONTH ) + 1 ; // MONTH is zero based ts . day = calendar . get ( Calendar . DAY_OF_MONTH ) ; ts . hour = calendar . get ( Calendar . HOUR_OF_DAY ) ; ts . minute = calendar . get ( Calendar . MINUTE ) ; ts . jday = calendar . get ( Calendar . DAY_OF_YEAR ) ; return ts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the time template parameters in a filename [CODESPLIT] public String replaceFileTemplate ( String filespec , int timeIndex ) { GradsTimeStruct ts = makeTimeStruct ( timeIndex ) ; //System.out.println(ts); String retString = filespec ; String format ; while ( hasTimeTemplate ( retString ) ) { // initial time if ( retString . indexOf ( \"%ix1\" ) >= 0 ) { retString = retString . replaceAll ( \"%ix1\" , String . format ( \"%d\" , initialTime . year / 10 ) ) ; } if ( retString . indexOf ( \"%ix3\" ) >= 0 ) { retString = retString . replaceAll ( \"%ix3\" , String . format ( \"%03d\" , initialTime . year / 10 ) ) ; } if ( retString . indexOf ( \"%iy2\" ) >= 0 ) { int cent = initialTime . year / 100 ; int val = initialTime . year - cent * 100 ; retString = retString . replaceAll ( \"%iy2\" , String . format ( \"%02d\" , val ) ) ; } if ( retString . indexOf ( \"%iy4\" ) >= 0 ) { retString = retString . replaceAll ( \"%iy4\" , String . format ( \"%d\" , initialTime . year ) ) ; } if ( retString . indexOf ( \"%im1\" ) >= 0 ) { retString = retString . replaceAll ( \"%im1\" , String . format ( \"%d\" , initialTime . month ) ) ; } if ( retString . indexOf ( \"%im2\" ) >= 0 ) { retString = retString . replaceAll ( \"%im2\" , String . format ( \"%02d\" , initialTime . month ) ) ; } if ( retString . indexOf ( \"%imc\" ) >= 0 ) { retString = retString . replaceAll ( \"%imc\" , GradsTimeStruct . months [ initialTime . month - 1 ] ) ; } if ( retString . indexOf ( \"%id1\" ) >= 0 ) { retString = retString . replaceAll ( \"%id1\" , String . format ( \"%d\" , initialTime . day ) ) ; } if ( retString . indexOf ( \"%id2\" ) >= 0 ) { retString = retString . replaceAll ( \"%id2\" , String . format ( \"%02d\" , initialTime . day ) ) ; } if ( retString . indexOf ( \"%ih1\" ) >= 0 ) { retString = retString . replaceAll ( \"%ih1\" , String . format ( \"%d\" , initialTime . hour ) ) ; } if ( retString . indexOf ( \"%ih2\" ) >= 0 ) { retString = retString . replaceAll ( \"%ih2\" , String . format ( \"%02d\" , initialTime . hour ) ) ; } if ( retString . indexOf ( \"%ih3\" ) >= 0 ) { retString = retString . replaceAll ( \"%ih3\" , String . format ( \"%03d\" , initialTime . hour ) ) ; } if ( retString . indexOf ( \"%in2\" ) >= 0 ) { retString = retString . replaceAll ( \"%in2\" , String . format ( \"%02d\" , initialTime . minute ) ) ; } // any time // decade if ( retString . indexOf ( \"%x1\" ) >= 0 ) { retString = retString . replaceAll ( \"%x1\" , String . format ( \"%d\" , ts . year / 10 ) ) ; } if ( retString . indexOf ( \"%x3\" ) >= 0 ) { retString = retString . replaceAll ( \"%x3\" , String . format ( \"%03d\" , ts . year / 10 ) ) ; } // year if ( retString . indexOf ( \"%y2\" ) >= 0 ) { int cent = ts . year / 100 ; int val = ts . year - cent * 100 ; retString = retString . replaceAll ( \"%y2\" , String . format ( \"%02d\" , val ) ) ; } if ( retString . indexOf ( \"%y4\" ) >= 0 ) { retString = retString . replaceAll ( \"%y4\" , String . format ( \"%d\" , ts . year ) ) ; } // month if ( retString . indexOf ( \"%m1\" ) >= 0 ) { retString = retString . replaceAll ( \"%m1\" , String . format ( \"%d\" , ts . month ) ) ; } if ( retString . indexOf ( \"%m2\" ) >= 0 ) { retString = retString . replaceAll ( \"%m2\" , String . format ( \"%02d\" , ts . month ) ) ; } if ( retString . indexOf ( \"%mc\" ) >= 0 ) { retString = retString . replaceAll ( \"%mc\" , GradsTimeStruct . months [ ts . month - 1 ] ) ; } // day if ( retString . indexOf ( \"%d1\" ) >= 0 ) { retString = retString . replaceAll ( \"%d1\" , String . format ( \"%d\" , ts . day ) ) ; } if ( retString . indexOf ( \"%d2\" ) >= 0 ) { retString = retString . replaceAll ( \"%d2\" , String . format ( \"%02d\" , ts . day ) ) ; } // hour if ( retString . indexOf ( \"%h1\" ) >= 0 ) { retString = retString . replaceAll ( \"%h1\" , String . format ( \"%d\" , ts . hour ) ) ; } if ( retString . indexOf ( \"%h2\" ) >= 0 ) { retString = retString . replaceAll ( \"%h2\" , String . format ( \"%02d\" , ts . hour ) ) ; } if ( retString . indexOf ( \"%h3\" ) >= 0 ) { retString = retString . replaceAll ( \"%h3\" , String . format ( \"%03d\" , ts . hour ) ) ; } // minute if ( retString . indexOf ( \"%n2\" ) >= 0 ) { retString = retString . replaceAll ( \"%n2\" , String . format ( \"%02d\" , ts . minute ) ) ; } // julian day if ( retString . indexOf ( \"%j3\" ) >= 0 ) { retString = retString . replaceAll ( \"%j3\" , String . format ( \"%03d\" , ts . jday ) ) ; } // time index (1 based) if ( retString . indexOf ( \"%t1\" ) >= 0 ) { retString = retString . replaceAll ( \"%t1\" , String . format ( \"%d\" , timeIndex + 1 ) ) ; } if ( retString . indexOf ( \"%t2\" ) >= 0 ) { retString = retString . replaceAll ( \"%t2\" , String . format ( \"%02d\" , timeIndex + 1 ) ) ; } if ( retString . indexOf ( \"%t3\" ) >= 0 ) { retString = retString . replaceAll ( \"%t3\" , String . format ( \"%03d\" , timeIndex + 1 ) ) ; } if ( retString . indexOf ( \"%t4\" ) >= 0 ) { retString = retString . replaceAll ( \"%t4\" , String . format ( \"%04d\" , timeIndex + 1 ) ) ; } if ( retString . indexOf ( \"%t5\" ) >= 0 ) { retString = retString . replaceAll ( \"%t5\" , String . format ( \"%05d\" , timeIndex + 1 ) ) ; } if ( retString . indexOf ( \"%t6\" ) >= 0 ) { retString = retString . replaceAll ( \"%t6\" , String . format ( \"%06d\" , timeIndex + 1 ) ) ; } // time index (0 based) if ( retString . indexOf ( \"%tm1\" ) >= 0 ) { retString = retString . replaceAll ( \"%tm1\" , String . format ( \"%d\" , timeIndex ) ) ; } if ( retString . indexOf ( \"%tm2\" ) >= 0 ) { retString = retString . replaceAll ( \"%tm2\" , String . format ( \"%02d\" , timeIndex ) ) ; } if ( retString . indexOf ( \"%tm3\" ) >= 0 ) { retString = retString . replaceAll ( \"%tm3\" , String . format ( \"%03d\" , timeIndex ) ) ; } if ( retString . indexOf ( \"%tm4\" ) >= 0 ) { retString = retString . replaceAll ( \"%tm4\" , String . format ( \"%04d\" , timeIndex ) ) ; } if ( retString . indexOf ( \"%tm5\" ) >= 0 ) { retString = retString . replaceAll ( \"%tm5\" , String . format ( \"%05d\" , timeIndex ) ) ; } if ( retString . indexOf ( \"%tm6\" ) >= 0 ) { retString = retString . replaceAll ( \"%tm6\" , String . format ( \"%06d\" , timeIndex ) ) ; } // forecast hours if ( retString . indexOf ( \"%f\" ) >= 0 ) { int mins = ( int ) getValues ( ) [ timeIndex ] * 60 ; int tdif ; if ( retString . indexOf ( \"%f2\" ) >= 0 ) { format = \"%02d\" ; tdif = mins / 60 ; if ( tdif > 99 ) { format = \"%d\" ; } retString = retString . replaceAll ( \"%f2\" , String . format ( format , tdif ) ) ; } if ( retString . indexOf ( \"%f3\" ) >= 0 ) { format = \"%03d\" ; tdif = mins / 60 ; if ( tdif > 999 ) { format = \"%d\" ; } retString = retString . replaceAll ( \"%f3\" , String . format ( format , tdif ) ) ; } if ( retString . indexOf ( \"%fn2\" ) >= 0 ) { format = \"%02d\" ; if ( mins > 99 ) { format = \"%d\" ; } retString = retString . replaceAll ( \"%fn2\" , String . format ( format , mins ) ) ; } if ( retString . indexOf ( \"%fhn2\" ) >= 0 ) { tdif = mins ; int hrs = tdif / 60 ; int mns = tdif - ( hrs * 60 ) ; format = \"%02d%02d\" ; if ( hrs > 99 ) { format = \"%d%02d\" ; } retString = retString . replaceAll ( \"%fhn2\" , String . format ( format , hrs , mns ) ) ; } if ( retString . indexOf ( \"%fdhn2\" ) >= 0 ) { tdif = mins ; int dys = tdif / 1440 ; int hrs = ( tdif - ( dys * 1440 ) ) / 60 ; int mns = tdif - ( dys * 1440 ) - ( hrs * 60 ) ; format = \"%02d%02d%02d\" ; if ( dys > 99 ) { format = \"%d%02d%02d\" ; } retString = retString . replaceAll ( \"%fdhn2\" , String . format ( format , dys , hrs , mns ) ) ; } } } return retString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this file definition have a time template in it? [CODESPLIT] public static boolean hasTimeTemplate ( String template ) { for ( int i = 0 ; i < timeTemplates . length ; i ++ ) { if ( template . indexOf ( timeTemplates [ i ] ) >= 0 ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the line between these two points cross the projection seam . [CODESPLIT] public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { // either point is infinite\r if ( ProjectionPointImpl . isInfinite ( pt1 ) || ProjectionPointImpl . isInfinite ( pt2 ) ) { return true ; } double y1 = pt1 . getY ( ) - falseNorthing ; double y2 = pt2 . getY ( ) - falseNorthing ; // opposite signed long lines\r return ( y1 * y2 < 0 ) && ( Math . abs ( y1 - y2 ) > 2 * earthRadius ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; double lon = Math . toRadians ( fromLon ) ; double lat = Math . toRadians ( fromLat ) ; double dlon = lon - lon0 ; double b = Math . cos ( lat ) * Math . sin ( dlon ) ; if ( ( Math . abs ( Math . abs ( b ) - 1.0 ) ) < TOLERANCE ) { // infinite projection\r toX = Double . POSITIVE_INFINITY ; toY = Double . POSITIVE_INFINITY ; } else { toX = scale * SpecialMathFunction . atanh ( b ) ; toY = scale * ( Math . atan2 ( Math . tan ( lat ) , Math . cos ( dlon ) ) - lat0 ) ; } result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) ; double fromY = world . getY ( ) ; double x = ( fromX - falseEasting ) / scale ; double d = ( fromY - falseNorthing ) / scale + lat0 ; toLon = Math . toDegrees ( lon0 + Math . atan2 ( Math . sinh ( x ) , Math . cos ( d ) ) ) ; toLat = Math . toDegrees ( Math . asin ( Math . sin ( d ) / Math . cosh ( x ) ) ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; double lon = Math . toRadians ( fromLon ) ; double lat = Math . toRadians ( fromLat ) ; double dlon = lon - lon0 ; double b = Math . cos ( lat ) * Math . sin ( dlon ) ; // infinite projection\r if ( ( Math . abs ( Math . abs ( b ) - 1.0 ) ) < TOLERANCE ) { toX = 0.0 ; toY = 0.0 ; } else { toX = scale * SpecialMathFunction . atanh ( b ) + falseEasting ; toY = scale * ( Math . atan2 ( Math . tan ( lat ) , Math . cos ( dlon ) ) - lat0 ) + falseNorthing ; } resultXA [ i ] = ( float ) toX ; resultYA [ i ] = ( float ) toY ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public double [ ] [ ] projToLatLon ( double [ ] [ ] from , double [ ] [ ] to ) { int cnt = from [ 0 ] . length ; double [ ] fromXA = from [ INDEX_X ] ; double [ ] fromYA = from [ INDEX_Y ] ; double [ ] toLatA = to [ INDEX_LAT ] ; double [ ] toLonA = to [ INDEX_LON ] ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] ; double fromY = fromYA [ i ] ; double x = ( fromX - falseEasting ) / scale ; double d = ( fromY - falseNorthing ) / scale + lat0 ; toLon = Math . toDegrees ( lon0 + Math . atan2 ( Math . sinh ( x ) , Math . cos ( d ) ) ) ; toLat = Math . toDegrees ( Math . asin ( Math . sin ( d ) / Math . cosh ( x ) ) ) ; toLatA [ i ] = ( double ) toLat ; toLonA [ i ] = ( double ) toLon ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a function to the library . The function will be inspected to determine whether it is a boolean or BaseType function . [CODESPLIT] public void add ( ServerSideFunction function ) { if ( function instanceof BoolFunction ) { boolFunctions . put ( function . getName ( ) , function ) ; } if ( function instanceof BTFunction ) { btFunctions . put ( function . getName ( ) , function ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a boolean function from the library . If the function is not found the library will attempt to load it using the mechanism described in the class documentation . [CODESPLIT] public BoolFunction getBoolFunction ( String name ) throws NoSuchFunctionException { if ( ! boolFunctions . containsKey ( name ) ) { loadNewFunction ( name ) ; } return ( BoolFunction ) boolFunctions . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a BaseType function from the library . If the function is not found the library will attempt to load it using the mechanism described in the class documentation . [CODESPLIT] public BTFunction getBTFunction ( String name ) throws NoSuchFunctionException { if ( ! btFunctions . containsKey ( name ) ) { loadNewFunction ( name ) ; } return ( BTFunction ) btFunctions . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to load a function with the given name . [CODESPLIT] protected void loadNewFunction ( String name ) { try { String fullName = prefix + name ; Class value = Class . forName ( fullName ) ; if ( ( ServerSideFunction . class ) . isAssignableFrom ( value ) ) { add ( ( ServerSideFunction ) value . newInstance ( ) ) ; return ; } } catch ( ClassNotFoundException e ) { } catch ( IllegalAccessException e ) { } catch ( InstantiationException e ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for aliases . [CODESPLIT] private String findCoordinateName ( NetcdfDataset ds , AxisType axisType ) { List < Variable > vlist = ds . getVariables ( ) ; for ( Variable aVlist : vlist ) { VariableEnhanced ve = ( VariableEnhanced ) aVlist ; if ( axisType == getAxisType ( ds , ve ) ) { return ve . getFullName ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "genProcess [CODESPLIT] @ Override @ Nullable public String getGeneratingProcessName ( int genProcess ) { if ( genProcessMap == null ) genProcessMap = readGenProcess ( fnmocTableA ) ; if ( genProcessMap == null ) return null ; return genProcessMap . get ( genProcess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ levels [CODESPLIT] protected VertCoordType getLevelType ( int code ) { if ( levelTypesMap == null ) levelTypesMap = readFnmocTable3 ( fnmocTable3 ) ; if ( levelTypesMap == null ) return super . getLevelType ( code ) ; VertCoordType levelType = levelTypesMap . get ( code ) ; if ( levelType != null ) return levelType ; return super . getLevelType ( code ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <entry > <grib1Id > 222< / grib1Id > <fnmocId > mid_cld< / fnmocId > <name > mid_cld< / name > <description > middle cloud layer< / description > <status > deprecated< / status > < / entry > [CODESPLIT] @ Nullable private HashMap < Integer , VertCoordType > readFnmocTable3 ( String path ) { try ( InputStream is = GribResourceReader . getInputStream ( path ) ) { SAXBuilder builder = new SAXBuilder ( ) ; org . jdom2 . Document doc = builder . build ( is ) ; Element root = doc . getRootElement ( ) ; HashMap < Integer , VertCoordType > result = new HashMap <> ( 200 ) ; Element fnmocTable = root . getChild ( \"fnmocTable\" ) ; List < Element > params = fnmocTable . getChildren ( \"entry\" ) ; for ( Element elem1 : params ) { int code = Integer . parseInt ( elem1 . getChildText ( \"grib1Id\" ) ) ; if ( code < 129 ) continue ; String desc = elem1 . getChildText ( \"description\" ) ; String abbrev = elem1 . getChildText ( \"name\" ) ; String units = elem1 . getChildText ( \"units\" ) ; if ( units == null ) units = ( code == 219 ) ? \"Pa\" : \"\" ; String datum = elem1 . getChildText ( \"datum\" ) ; boolean isLayer = elem1 . getChild ( \"isLayer\" ) != null ; boolean isPositiveUp = elem1 . getChild ( \"isPositiveUp\" ) != null ; VertCoordType lt = new VertCoordType ( code , desc , abbrev , units , datum , isPositiveUp , isLayer ) ; result . put ( code , lt ) ; } return result ; // all at once - thread safe\r } catch ( IOException | JDOMException e ) { logger . error ( \"Cant read FnmocTable3 = \" + path , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build an unnamed InvCatalog for this DatasetSource and return the top - level InvDataset . The ResultService for this DatasetSource is used to create the InvService for the new InvCatalog . Each InvDataset in the catalog is named with the location of the object they represent on the dataset source . [CODESPLIT] protected InvCatalog createSkeletonCatalog ( String prefixUrlPath ) throws IOException { this . checkAccessPoint ( ) ; // Create catalog. InvCatalogImpl catalog = new InvCatalogImpl ( null , null , null ) ; //this.getName(), null, null); // Create service. InvService service = new InvService ( this . getResultService ( ) . getName ( ) , this . getResultService ( ) . getServiceType ( ) . toString ( ) , this . getResultService ( ) . getBase ( ) , this . getResultService ( ) . getSuffix ( ) , this . getResultService ( ) . getDescription ( ) ) ; for ( Iterator it = this . getResultService ( ) . getProperties ( ) . iterator ( ) ; it . hasNext ( ) ; ) { service . addProperty ( ( InvProperty ) it . next ( ) ) ; } for ( Iterator it = this . getResultService ( ) . getServices ( ) . iterator ( ) ; it . hasNext ( ) ; ) { service . addService ( ( InvService ) it . next ( ) ) ; } // Add service to catalog. catalog . addService ( service ) ; // Create top-level dataset. File apFile = new File ( this . getAccessPoint ( ) ) ; InvDatasetImpl topDs = new LocalInvDataset ( null , apFile , prefixUrlPath ) ; // Set the serviceName (inherited by all datasets) in top-level dataset. ThreddsMetadata tm = new ThreddsMetadata ( false ) ; tm . setServiceName ( service . getName ( ) ) ; InvMetadata md = new InvMetadata ( topDs , null , XMLEntityResolver . CATALOG_NAMESPACE_10 , \"\" , true , true , null , tm ) ; ThreddsMetadata tm2 = new ThreddsMetadata ( false ) ; tm2 . addMetadata ( md ) ; topDs . setLocalMetadata ( tm2 ) ; // Add top-level dataset to catalog. catalog . addDataset ( topDs ) ; // Tie up any loose ends in catalog with finish(). ( ( InvCatalogImpl ) catalog ) . finish ( ) ; return ( catalog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a list of the InvDatasets contained in the given collection dataset on this DatasetSource . [CODESPLIT] protected List expandThisLevel ( InvDataset dataset , String prefixUrlPath ) { if ( dataset == null ) throw new NullPointerException ( \"Given dataset cannot be null.\" ) ; if ( ! isCollection ( dataset ) ) throw new IllegalArgumentException ( \"Dataset \\\"\" + dataset . getName ( ) + \"\\\" is not a collection dataset.\" ) ; // Deal with all files in this directory. File theDir = new File ( ( ( LocalInvDataset ) dataset ) . getLocalPath ( ) ) ; File [ ] allFiles = theDir . listFiles ( ) ; InvDataset curDs = null ; ArrayList list = new ArrayList ( ) ; for ( int i = 0 ; i < allFiles . length ; i ++ ) { try { curDs = new LocalInvDataset ( dataset , allFiles [ i ] , prefixUrlPath ) ; } catch ( IOException e ) { // Given file doesn't exist or is not under the accessPointHeader directory, skip. continue ; } list . add ( curDs ) ; } return ( list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets parameter table then grib1 parameter based on number . [CODESPLIT] public final GridParameter getParameter ( GridRecord gr ) { McIDASGridRecord mgr = ( McIDASGridRecord ) gr ; String name = mgr . getParameterName ( ) ; String desc = mgr . getGridDescription ( ) ; if ( desc . trim ( ) . equals ( \"\" ) ) { desc = name ; } String unit = visad . jmet . MetUnits . makeSymbol ( mgr . getParamUnitName ( ) ) ; return new GridParameter ( 0 , name , desc , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the LevelName . [CODESPLIT] public final String getLevelName ( GridRecord gr ) { if ( cust != null ) { String result = cust . getLevelNameShort ( gr . getLevelType1 ( ) ) ; if ( result != null ) return result ; } String levelUnit = getLevelUnit ( gr ) ; if ( levelUnit != null ) { int level1 = ( int ) gr . getLevel1 ( ) ; int level2 = ( int ) gr . getLevel2 ( ) ; if ( levelUnit . equalsIgnoreCase ( \"hPa\" ) ) { return \"pressure\" ; } else if ( level1 == 1013 ) { return \"mean sea level\" ; } else if ( level1 == 0 ) { return \"tropopause\" ; } else if ( level1 == 1001 ) { return \"surface\" ; } else if ( level2 != 0 ) { return \"layer\" ; } } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the LevelDescription . [CODESPLIT] public final String getLevelDescription ( GridRecord gr ) { if ( cust != null ) { String result = cust . getLevelDescription ( gr . getLevelType1 ( ) ) ; if ( result != null ) return result ; } // TODO:  flesh this out return getLevelName ( gr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the LevelUnit . [CODESPLIT] public final String getLevelUnit ( GridRecord gr ) { if ( cust != null ) { String result = cust . getLevelUnits ( gr . getLevelType1 ( ) ) ; if ( result != null ) return result ; } return visad . jmet . MetUnits . makeSymbol ( ( ( McIDASGridRecord ) gr ) . getLevelUnitName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the ProjectionType . [CODESPLIT] public final int getProjectionType ( GridDefRecord gds ) { String name = getProjectionName ( gds ) . trim ( ) ; switch ( name ) { case \"MERC\" : return Mercator ; case \"CONF\" : return LambertConformal ; case \"PS\" : return PolarStereographic ; default : return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is this a VerticalCoordinate . [CODESPLIT] public final boolean isVerticalCoordinate ( GridRecord gr ) { if ( cust != null ) { return cust . isVerticalCoordinate ( gr . getLevelType1 ( ) ) ; } int type = gr . getLevelType1 ( ) ; if ( ( ( McIDASGridRecord ) gr ) . hasGribInfo ( ) ) { if ( type == 20 ) { return true ; } if ( type == 100 ) { return true ; } if ( type == 101 ) { return true ; } if ( ( type >= 103 ) && ( type <= 128 ) ) { return true ; } if ( type == 141 ) { return true ; } if ( type == 160 ) { return true ; } } else if ( getLevelUnit ( gr ) . equals ( \"hPa\" ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a layer? [CODESPLIT] public boolean isLayer ( GridRecord gr ) { if ( cust != null ) { return cust . isLayer ( gr . getLevelType1 ( ) ) ; } if ( gr . getLevel2 ( ) == 0 ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message CoverageDataset { required string name = 1 ; repeated Attribute atts = 2 ; required Rectangle latlonRect = 3 ; optional Rectangle projRect = 4 ; required CalendarDateRange timeRange = 5 ; [CODESPLIT] CdmrFeatureProto . CoverageDataset . Builder encodeHeader ( CoverageCollection gridDataset , String location ) { CdmrFeatureProto . CoverageDataset . Builder builder = CdmrFeatureProto . CoverageDataset . newBuilder ( ) ; builder . setName ( location ) ; builder . setCoverageType ( convertCoverageType ( gridDataset . getCoverageType ( ) ) ) ; builder . setDateRange ( encodeDateRange ( gridDataset . getCalendarDateRange ( ) ) ) ; if ( gridDataset . getLatlonBoundingBox ( ) != null ) builder . setLatlonRect ( encodeRectangle ( gridDataset . getLatlonBoundingBox ( ) ) ) ; if ( gridDataset . getProjBoundingBox ( ) != null ) builder . setProjRect ( encodeRectangle ( gridDataset . getProjBoundingBox ( ) ) ) ; for ( Attribute att : gridDataset . getGlobalAttributes ( ) ) builder . addAtts ( NcStream . encodeAtt ( att ) ) ; for ( CoverageCoordSys gcs : gridDataset . getCoordSys ( ) ) builder . addCoordSys ( encodeCoordSys ( gcs ) ) ; for ( CoverageTransform gct : gridDataset . getCoordTransforms ( ) ) builder . addCoordTransforms ( encodeCoordTransform ( gct ) ) ; for ( CoverageCoordAxis axis : gridDataset . getCoordAxes ( ) ) builder . addCoordAxes ( encodeCoordAxis ( axis ) ) ; for ( Coverage grid : gridDataset . getCoverages ( ) ) builder . addGrids ( encodeGrid ( grid ) ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Rectangle { required double startx = 1 ; required double starty = 2 ; required double incx = 3 ; required double incy = 4 ; } [CODESPLIT] CdmrFeatureProto . Rectangle . Builder encodeRectangle ( LatLonRect rect ) { CdmrFeatureProto . Rectangle . Builder builder = CdmrFeatureProto . Rectangle . newBuilder ( ) ; //     this(r.getLowerLeftPoint(), r.getUpperRightPoint().getLatitude() - r.getLowerLeftPoint().getLatitude(), r.getWidth()); LatLonPoint ll = rect . getLowerLeftPoint ( ) ; LatLonPoint ur = rect . getUpperRightPoint ( ) ; builder . setStartx ( ll . getLongitude ( ) ) ; builder . setStarty ( ll . getLatitude ( ) ) ; builder . setIncx ( rect . getWidth ( ) ) ; builder . setIncy ( ur . getLatitude ( ) - ll . getLatitude ( ) ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message CalendarDateRange { required int64 start = 1 ; required int64 end = 2 ; required int32 calendar = 3 ; // calendar ordinal } [CODESPLIT] CdmrFeatureProto . CalendarDateRange . Builder encodeDateRange ( CalendarDateRange dateRange ) { CdmrFeatureProto . CalendarDateRange . Builder builder = CdmrFeatureProto . CalendarDateRange . newBuilder ( ) ; builder . setStart ( dateRange . getStart ( ) . getMillis ( ) ) ; builder . setEnd ( dateRange . getEnd ( ) . getMillis ( ) ) ; Calendar cal = dateRange . getStart ( ) . getCalendar ( ) ; builder . setCalendar ( convertCalendar ( cal ) ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Coverage { required string name = 1 ; // short name required DataType dataType = 2 ; optional bool unsigned = 3 [ default = false ] ; repeated Attribute atts = 4 ; required string coordSys = 5 ; } [CODESPLIT] CdmrFeatureProto . Coverage . Builder encodeGrid ( Coverage grid ) { CdmrFeatureProto . Coverage . Builder builder = CdmrFeatureProto . Coverage . newBuilder ( ) ; builder . setName ( grid . getName ( ) ) ; builder . setDataType ( NcStream . convertDataType ( grid . getDataType ( ) ) ) ; for ( Attribute att : grid . getAttributes ( ) ) builder . addAtts ( NcStream . encodeAtt ( att ) ) ; builder . setUnits ( grid . getUnitsString ( ) ) ; builder . setDescription ( grid . getDescription ( ) ) ; builder . setCoordSys ( grid . getCoordSysName ( ) ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message CoordSys { required string name = 1 ; // must be unique in dataset s CoordSys repeated string axisNames = 2 ; repeated string transformNames = 3 ; optional CoverageType coverageType = 5 ; } } [CODESPLIT] CdmrFeatureProto . CoordSys . Builder encodeCoordSys ( CoverageCoordSys gcs ) { CdmrFeatureProto . CoordSys . Builder builder = CdmrFeatureProto . CoordSys . newBuilder ( ) ; builder . setName ( gcs . getName ( ) ) ; builder . setCoverageType ( convertCoverageType ( gcs . getCoverageType ( ) ) ) ; for ( String axis : gcs . getAxisNames ( ) ) builder . addAxisNames ( axis ) ; for ( String gct : gcs . getTransformNames ( ) ) builder . addTransformNames ( gct ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message CoordTransform { required bool isHoriz = 1 ; required string name = 2 ; repeated Attribute params = 3 ; } [CODESPLIT] CdmrFeatureProto . CoordTransform . Builder encodeCoordTransform ( CoverageTransform gct ) { CdmrFeatureProto . CoordTransform . Builder builder = CdmrFeatureProto . CoordTransform . newBuilder ( ) ; builder . setIsHoriz ( gct . isHoriz ( ) ) ; builder . setName ( gct . getName ( ) ) ; for ( Attribute att : gct . getAttributes ( ) ) builder . addParams ( NcStream . encodeAtt ( att ) ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message CoordAxis { required string name = 1 ; required DataType dataType = 2 ; required int32 axisType = 3 ; // ucar . nc2 . constants . AxisType ordinal required int64 nvalues = 4 ; required string units = 5 ; optional bool isRegular = 6 ; required double min = 7 ; // required ?? required double max = 8 ; optional double resolution = 9 ; } [CODESPLIT] CdmrFeatureProto . CoordAxis . Builder encodeCoordAxis ( CoverageCoordAxis axis ) { CdmrFeatureProto . CoordAxis . Builder builder = CdmrFeatureProto . CoordAxis . newBuilder ( ) ; builder . setName ( axis . getName ( ) ) ; builder . setDataType ( NcStream . convertDataType ( axis . getDataType ( ) ) ) ; builder . setAxisType ( convertAxisType ( axis . getAxisType ( ) ) ) ; builder . setNvalues ( axis . getNcoords ( ) ) ; if ( axis . getUnits ( ) != null ) builder . setUnits ( axis . getUnits ( ) ) ; if ( axis . getDescription ( ) != null ) builder . setDescription ( axis . getDescription ( ) ) ; builder . setDepend ( convertDependenceType ( axis . getDependenceType ( ) ) ) ; for ( String s : axis . getDependsOnList ( ) ) builder . addDependsOn ( s ) ; if ( axis instanceof LatLonAxis2D ) { LatLonAxis2D latlon2D = ( LatLonAxis2D ) axis ; for ( int shape : latlon2D . getShape ( ) ) builder . addShape ( shape ) ; } for ( Attribute att : axis . getAttributes ( ) ) builder . addAtts ( NcStream . encodeAtt ( att ) ) ; builder . setSpacing ( convertSpacing ( axis . getSpacing ( ) ) ) ; builder . setStartValue ( axis . getStartValue ( ) ) ; builder . setEndValue ( axis . getEndValue ( ) ) ; builder . setResolution ( axis . getResolution ( ) ) ; if ( ! axis . isRegular ( ) && axis . getNcoords ( ) < MAX_INLINE_NVALUES ) { double [ ] values = axis . getValues ( ) ; ByteBuffer bb = ByteBuffer . allocate ( 8 * values . length ) ; DoubleBuffer db = bb . asDoubleBuffer ( ) ; db . put ( values ) ; builder . setValues ( ByteString . copyFrom ( bb . array ( ) ) ) ; } return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public enum Type { Coverage Curvilinear Grid Swath Fmrc } [CODESPLIT] static public CdmrFeatureProto . CoverageType convertCoverageType ( FeatureType type ) { switch ( type ) { case COVERAGE : return CdmrFeatureProto . CoverageType . General ; case CURVILINEAR : return CdmrFeatureProto . CoverageType . Curvilinear ; case GRID : return CdmrFeatureProto . CoverageType . Grid ; case SWATH : return CdmrFeatureProto . CoverageType . Swath ; case FMRC : return CdmrFeatureProto . CoverageType . Fmrc ; } throw new IllegalStateException ( \"illegal CoverageType \" + type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message GeoReferencedArray { required string gridName = 1 ; // full escaped name . required DataType dataType = 2 ; optional bool bigend = 3 [ default = true ] ; optional uint32 version = 4 [ default = 0 ] ; optional Compress compress = 5 [ default = NONE ] ; optional uint32 uncompressedSize = 6 ; [CODESPLIT] public CdmrFeatureProto . CoverageDataResponse encodeDataResponse ( Iterable < CoverageCoordAxis > axes , Iterable < CoverageCoordSys > coordSys , Iterable < CoverageTransform > transforms , List < GeoReferencedArray > arrays , boolean deflate ) { CdmrFeatureProto . CoverageDataResponse . Builder builder = CdmrFeatureProto . CoverageDataResponse . newBuilder ( ) ; for ( CoverageCoordAxis axis : axes ) builder . addCoordAxes ( encodeCoordAxis ( axis ) ) ; for ( CoverageCoordSys cs : coordSys ) builder . addCoordSys ( encodeCoordSys ( cs ) ) ; for ( CoverageTransform t : transforms ) builder . addCoordTransforms ( encodeCoordTransform ( t ) ) ; for ( GeoReferencedArray array : arrays ) builder . addGeoArray ( encodeGeoReferencedArray ( array , deflate ) ) ; return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "from http : // blog . eyallupu . com / 2011 / 11 / java - 7 - working - with - directories . html [CODESPLIT] public static DirectoryStream newDirectoryStream ( Path dir , String glob ) throws IOException { FileSystem fs = dir . getFileSystem ( ) ; final PathMatcher matcher = fs . getPathMatcher ( \"glob:\" + glob ) ; DirectoryStream . Filter < Path > filter = new DirectoryStream . Filter < Path > ( ) { public boolean accept ( Path entry ) { return matcher . matches ( entry . getFileName ( ) ) ; } } ; return fs . provider ( ) . newDirectoryStream ( dir , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a Coordinate Transform . [CODESPLIT] static public void registerTransform ( String transformName , Class c ) { if ( ! ( VertTransformBuilderIF . class . isAssignableFrom ( c ) ) && ! ( HorizTransformBuilderIF . class . isAssignableFrom ( c ) ) ) throw new IllegalArgumentException ( \"Class \" + c . getName ( ) + \" must implement VertTransformBuilderIF or HorizTransformBuilderIF\" ) ; // fail fast - check newInstance works\r try { c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( \"CoordTransBuilderIF Class \" + c . getName ( ) + \" cannot instantiate, probably need default Constructor\" ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"CoordTransBuilderIF Class \" + c . getName ( ) + \" is not accessible\" ) ; } // user stuff gets put at top\r if ( userMode ) transformList . add ( 0 , new Transform ( transformName , c ) ) ; else transformList . add ( new Transform ( transformName , c ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a Coordinate Transform . [CODESPLIT] static public void registerTransform ( String transformName , String className ) throws ClassNotFoundException { Class c = Class . forName ( className ) ; registerTransform ( transformName , c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a Coordinate Transform . [CODESPLIT] static public void registerTransformMaybe ( String transformName , String className ) { Class c ; try { c = Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { if ( loadWarnings ) log . warn ( \"Coordinate Transform Class \" + className + \" not found.\" ) ; return ; } registerTransform ( transformName , c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a CoordinateTransform object from the parameters in a Coordinate Transform Variable using an intrinsic or registered CoordTransBuilder . [CODESPLIT] static public CoordinateTransform makeCoordinateTransform ( NetcdfDataset ds , AttributeContainer ctv , Formatter parseInfo , Formatter errInfo ) { // standard name\r String transform_name = ctv . findAttValueIgnoreCase ( \"transform_name\" , null ) ; if ( null == transform_name ) transform_name = ctv . findAttValueIgnoreCase ( \"Projection_Name\" , null ) ; // these names are from CF - dont want to have to duplicate\r if ( null == transform_name ) transform_name = ctv . findAttValueIgnoreCase ( CF . GRID_MAPPING_NAME , null ) ; if ( null == transform_name ) transform_name = ctv . findAttValueIgnoreCase ( CF . STANDARD_NAME , null ) ; if ( null == transform_name ) { parseInfo . format ( \"**Failed to find Coordinate Transform name from Variable= %s%n\" , ctv ) ; return null ; } transform_name = transform_name . trim ( ) ; // do we have a transform registered for this ?\r Class builderClass = null ; for ( Transform transform : transformList ) { if ( transform . transName . equals ( transform_name ) ) { builderClass = transform . transClass ; break ; } } if ( null == builderClass ) { parseInfo . format ( \"**Failed to find CoordTransBuilder name= %s from Variable= %s%n\" , transform_name , ctv ) ; return null ; } // get an instance of that class\r Object builderObject ; try { builderObject = builderClass . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { log . error ( \"Cant create new instance \" + builderClass . getName ( ) , e ) ; return null ; } if ( null == builderObject ) { // cant happen - because this was tested in registerTransform()\r parseInfo . format ( \"**Failed to build CoordTransBuilder object from class= %s for Variable= %s%n\" , builderClass . getName ( ) , ctv ) ; return null ; } CoordinateTransform ct ; if ( builderObject instanceof VertTransformBuilderIF ) { VertTransformBuilderIF vertBuilder = ( VertTransformBuilderIF ) builderObject ; vertBuilder . setErrorBuffer ( errInfo ) ; ct = vertBuilder . makeCoordinateTransform ( ds , ctv ) ; } else if ( builderObject instanceof HorizTransformBuilderIF ) { HorizTransformBuilderIF horizBuilder = ( HorizTransformBuilderIF ) builderObject ; horizBuilder . setErrorBuffer ( errInfo ) ; String units = AbstractTransformBuilder . getGeoCoordinateUnits ( ds , ctv ) ; // barfola\r ct = horizBuilder . makeCoordinateTransform ( ctv , units ) ; } else { log . error ( \"Illegals class \" + builderClass . getName ( ) ) ; return null ; } if ( ct != null ) { parseInfo . format ( \" Made Coordinate transform %s from variable %s: %s%n\" , transform_name , ctv . getName ( ) , builderObject . getClass ( ) . getName ( ) ) ; } return ct ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a dummy Coordinate Transform Variable based on the given CoordinateTransform . This creates a scalar Variable with dummy data and adds the Parameters of the CoordinateTransform as attributes . [CODESPLIT] static public VariableDS makeDummyTransformVariable ( NetcdfDataset ds , CoordinateTransform ct ) { VariableDS v = new VariableDS ( ds , null , null , ct . getName ( ) , DataType . CHAR , \"\" , null , null ) ; List < Parameter > params = ct . getParameters ( ) ; for ( Parameter p : params ) { if ( p . isString ( ) ) v . addAttribute ( new Attribute ( p . getName ( ) , p . getStringValue ( ) ) ) ; else { double [ ] data = p . getNumericValues ( ) ; Array dataA = Array . factory ( DataType . DOUBLE , new int [ ] { data . length } , data ) ; v . addAttribute ( new Attribute ( p . getName ( ) , dataA ) ) ; } } v . addAttribute ( new Attribute ( _Coordinate . TransformType , ct . getTransformType ( ) . toString ( ) ) ) ; // fake data\r Array data = Array . factory ( DataType . CHAR , new int [ ] { } , new char [ ] { ' ' } ) ; v . setCachedData ( data , true ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a CoordinateTransform object from the parameters in a GridCoordTransform using an intrinsic or registered CoordTransBuilder . [CODESPLIT] static public ProjectionImpl makeProjection ( CoverageTransform gct , Formatter errInfo ) { // standard name\r String transform_name = gct . findAttValueIgnoreCase ( CF . GRID_MAPPING_NAME , null ) ; if ( null == transform_name ) { errInfo . format ( \"**Failed to find Coordinate Transform name from GridCoordTransform= %s%n\" , gct ) ; return null ; } transform_name = transform_name . trim ( ) ; // do we have a transform registered for this ?\r Class builderClass = null ; for ( Transform transform : transformList ) { if ( transform . transName . equals ( transform_name ) ) { builderClass = transform . transClass ; break ; } } if ( null == builderClass ) { errInfo . format ( \"**Failed to find CoordTransBuilder name= %s from GridCoordTransform= %s%n\" , transform_name , gct ) ; return null ; } // get an instance of that class\r HorizTransformBuilderIF builder ; try { builder = ( HorizTransformBuilderIF ) builderClass . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { log . error ( \"Cant create new instance \" + builderClass . getName ( ) , e ) ; return null ; } if ( null == builder ) { // cant happen - because this was tested in registerTransform()\r errInfo . format ( \"**Failed to build CoordTransBuilder object from class= %s for GridCoordTransform= %s%n\" , builderClass . getName ( ) , gct ) ; return null ; } String units = gct . findAttValueIgnoreCase ( CDM . UNITS , null ) ; builder . setErrorBuffer ( errInfo ) ; ProjectionCT ct = builder . makeCoordinateTransform ( gct , units ) ; assert ct != null ; return ct . getProjection ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires a PropertyChangeEvent : <ul > <li > propertyName = Dataset or File getNewValue () = InvDataset chosen . <li > propertyName = Datasets getNewValue () = InvDataset [] chosen . This can only happen if you have set doResolve = true and the resolved dataset is a list of datasets . <li > propertyName = InvAccess getNewValue () = InvAccess chosen . < / ul > [CODESPLIT] private void firePropertyChangeEvent ( PropertyChangeEvent event ) { // System.out.println(\"firePropertyChangeEvent \"+((InvDatasetImpl)ds).dump()); if ( pipeOut ) pipeEvent ( event ) ; if ( messageOut ) messageEvent ( event ) ; firePropertyChange ( event . getPropertyName ( ) , event . getOldValue ( ) , event . getNewValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap this in a JDialog component . [CODESPLIT] public JDialog makeDialog ( JFrame parent , String title , boolean modal ) { return new Dialog ( frame , title , modal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Standalone application . [CODESPLIT] public static void main ( String args [ ] ) { boolean usePopup = false ; for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . equals ( \"-usePopup\" ) ) usePopup = true ; } try { store = XMLStore . createFromFile ( \"ThreddsDatasetChooser\" , null ) ; p = store . getPreferences ( ) ; } catch ( IOException e ) { System . out . println ( \"XMLStore Creation failed \" + e ) ; } // put it together in a JFrame final JFrame frame = new JFrame ( \"Thredds Dataset Chooser\" ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { chooser . save ( ) ; Rectangle bounds = frame . getBounds ( ) ; p . putBeanObject ( FRAME_SIZE , bounds ) ; try { store . save ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } System . exit ( 0 ) ; } } ) ; chooser = new ThreddsDatasetChooser ( p , null , frame , true , usePopup , false ) ; chooser . setDoResolve ( true ) ; // frame . getContentPane ( ) . add ( chooser ) ; Rectangle bounds = ( Rectangle ) p . getBean ( FRAME_SIZE , new Rectangle ( 50 , 50 , 800 , 450 ) ) ; frame . setBounds ( bounds ) ; frame . pack ( ) ; frame . setBounds ( bounds ) ; frame . setVisible ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { ArrayDouble . D3 ddata = getCoordinateArray ( timeIndex ) ; int [ ] origin = new int [ ] { 0 , yIndex , xIndex } ; int [ ] shape = new int [ ] { ddata . getShape ( ) [ 0 ] , 1 , 1 } ; return ( ArrayDouble . D1 ) ddata . section ( origin , shape ) . reduce ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////// [CODESPLIT] public String getFileLocationFromRequestPath ( String reqPath ) { if ( datasetScan != null ) { // LOOK should check to see if its been filtered out by scan return getFileLocationFromRequestPath ( reqPath , datasetScan . getPath ( ) , datasetScan . getScanLocation ( ) , false ) ; } else if ( catScan != null ) { // LOOK should check to see if its allowed in fc return getFileLocationFromRequestPath ( reqPath , catScan . getPath ( ) , catScan . getLocation ( ) , false ) ; } else if ( featCollection != null ) { // LOOK should check to see if its allowed in fc return getFileLocationFromRequestPath ( reqPath , featCollection . getPath ( ) , featCollection . getTopDirectoryLocation ( ) , true ) ; } else { // must be a datasetRoot // LOOK should check to see if it exists ?? return getFileLocationFromRequestPath ( reqPath , getPath ( ) , getDirLocation ( ) , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private MetadataManager mm ; [CODESPLIT] public void save ( ) { collectionNameTable . saveState ( false ) ; dataTable . saveState ( false ) ; prefs . putBeanObject ( \"InfoWindowBounds\" , infoWindow . getBounds ( ) ) ; prefs . putInt ( \"splitPos\" , split . getDividerLocation ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "iterate through the observations [CODESPLIT] private void writeSequence ( StructureDS s , StructureDataIterator sdataIter ) throws IOException , XMLStreamException { int count = 0 ; try { while ( sdataIter . hasNext ( ) ) { //out.format(\"%sSequence %s count=%d%n\", indent, s.getShortName(), count++);\r StructureData sdata = sdataIter . next ( ) ; staxWriter . writeCharacters ( \"\\n\" ) ; staxWriter . writeCharacters ( indent . toString ( ) ) ; staxWriter . writeStartElement ( \"struct\" ) ; staxWriter . writeAttribute ( \"name\" , escaper . escape ( s . getShortName ( ) ) ) ; staxWriter . writeAttribute ( \"count\" , Integer . toString ( count ++ ) ) ; for ( StructureMembers . Member m : sdata . getMembers ( ) ) { Variable v = s . findVariable ( m . getName ( ) ) ; indent . incr ( ) ; if ( m . getDataType ( ) . isString ( ) || m . getDataType ( ) . isNumeric ( ) ) { writeVariable ( ( VariableDS ) v , sdata . getArray ( m ) ) ; } else if ( m . getDataType ( ) == DataType . STRUCTURE ) { StructureDS sds = ( StructureDS ) v ; ArrayStructure data = ( ArrayStructure ) sdata . getArray ( m ) ; writeSequence ( sds , data . getStructureDataIterator ( ) ) ; } else if ( m . getDataType ( ) == DataType . SEQUENCE ) { SequenceDS sds = ( SequenceDS ) v ; ArraySequence data = ( ArraySequence ) sdata . getArray ( m ) ; writeSequence ( sds , data . getStructureDataIterator ( ) ) ; } indent . decr ( ) ; } staxWriter . writeCharacters ( \"\\n\" ) ; staxWriter . writeCharacters ( indent . toString ( ) ) ; staxWriter . writeEndElement ( ) ; } } finally { sdataIter . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for OPeNDAP . html requests . Returns an html form and javascript code that allows the user to use their browser to select variables and build constraints for a data request . The DDS and DAS for the data set are used to build the form . The types in opendap . servlet . www are integral to the form generation . [CODESPLIT] public void sendDataRequestForm ( HttpServletRequest request , HttpServletResponse response , String dataSet , ServerDDS sdds , DAS myDAS ) // changed jc\r throws DAP2Exception , ParseException { if ( _Debug ) System . out . println ( \"Sending DODS Data Request Form For: \" + dataSet + \"    CE: '\" + request . getQueryString ( ) + \"'\" ) ; String requestURL ; /*\r\n        // Turn this on later if we discover we're supposed to accept\r\n        // constraint expressions as input to the Data Request Web Form\r\n    String ce;\r\n    if(request.getQueryString() == null){\r\n        ce = \"\";\r\n        }\r\n    else {\r\n        ce = \"?\" + request.getQueryString();\r\n        }\r\n*/ int suffixIndex = request . getRequestURL ( ) . toString ( ) . lastIndexOf ( \".\" ) ; requestURL = request . getRequestURL ( ) . substring ( 0 , suffixIndex ) ; String dapCssUrl = \"/\" + requestURL . split ( \"/\" , 5 ) [ 3 ] + \"/\" + \"tdsDap.css\" ; try { //PrintWriter pw = new PrintWriter(response.getOutputStream());\r PrintWriter pw ; if ( false ) { pw = new PrintWriter ( new FileOutputStream ( new File ( \"debug.html\" ) ) ) ; } else pw = response . getWriter ( ) ; wwwOutPut wOut = new wwwOutPut ( pw ) ; // Get the DDS and the DAS (if one exists) for the dataSet.\r DDS myDDS = getWebFormDDS ( dataSet , sdds ) ; //DAS myDAS = dServ.getDAS(dataSet); // change jc\r jscriptCore jsc = new jscriptCore ( ) ; pw . println ( \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0 Transitional//EN\\\"\\n\" + \"\\\"http://www.w3.org/TR/REC-html40/loose.dtd\\\">\\n\" + \"<html><head><title>OPeNDAP Dataset Query Form</title>\\n\" + \"<link type=\\\"text/css\\\" rel=\\\"stylesheet\\\" media=\\\"screen\\\" href=\\\"\" + dapCssUrl + \"\\\"/>\\n\" + \"<base href=\\\"\" + helpLocation + \"\\\">\\n\" + \"<script type=\\\"text/javascript\\\">\\n\" + \"<!--\\n\" ) ; pw . flush ( ) ; pw . println ( jsc . jScriptCode ) ; pw . flush ( ) ; pw . println ( \"DODS_URL = new dods_url(\\\"\" + requestURL + \"\\\");\\n\" + \"// -->\\n\" + \"</script>\\n\" + \"</head>\\n\" + \"<body>\\n\" + \"<p><h2 align='center'>OPeNDAP Dataset Access Form</h2>\\n\" + \"<hr>\\n\" + \"<form action=\\\"\\\">\\n\" + \"<table>\\n\" ) ; pw . flush ( ) ; wOut . writeDisposition ( requestURL ) ; pw . println ( \"<tr><td><td><hr>\\n\" ) ; wOut . writeGlobalAttributes ( myDAS , myDDS ) ; pw . println ( \"<tr><td><td><hr>\\n\" ) ; wOut . writeVariableEntries ( myDAS , myDDS ) ; pw . println ( \"</table></form>\\n\" ) ; pw . println ( \"<hr>\\n\" ) ; pw . println ( \"<address>\" ) ; pw . println ( \"<p>For questions or comments about this dataset, contact the administrator of this server [\" + serverContactName + \"] at: <a href='mailto:\" + serverContactEmail + \"'>\" + serverContactEmail + \"</a></p>\" ) ; pw . println ( \"<p>For questions or comments about OPeNDAP, email OPeNDAP support at:\" + \" <a href='mailto:\" + odapSupportEmail + \"'>\" + odapSupportEmail + \"</a></p>\" ) ; pw . println ( \"</address></body></html>\" ) ; pw . println ( \"<hr>\" ) ; pw . println ( \"<h2>DDS:</h2>\" ) ; pw . println ( \"<pre>\" ) ; myDDS . print ( pw ) ; pw . println ( \"</pre>\" ) ; pw . println ( \"<hr>\" ) ; pw . flush ( ) ; } catch ( IOException ioe ) { System . out . println ( \"OUCH! IOException: \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( System . out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Gets a DDS for the specified data set and builds it using the class factory in the package <b > opendap . servlet . www< / b > . <p / > Currently this method uses a deprecated API to perform a translation of DDS types . This is a known problem and as soon as an alternate way of achieving this result is identified we will implement it . ( Your comments appreciated! ) [CODESPLIT] public DDS getWebFormDDS ( String dataSet , ServerDDS sDDS ) // changed jc\r throws DAP2Exception , ParseException { // Get the DDS we need, using the getDDS method\r // for this particular server\r // ServerDDS sDDS = dServ.getDDS(dataSet);\r // Make a new DDS using the web form (www interface) class factory\r wwwFactory wfactory = new wwwFactory ( ) ; DDS wwwDDS = new DDS ( dataSet , wfactory ) ; wwwDDS . setURL ( dataSet ) ; // Make a special print writer to catch the ServerDDS's\r // persistent representation in a String.\r StringWriter ddsSW = new StringWriter ( ) ; sDDS . print ( new PrintWriter ( ddsSW ) ) ; // Now use that string to make an input stream to\r // pass to our new DDS for parsing.\r // Since parser expects/requires InputStream,\r // we must adapt utf16 string to at least utf-8\r ByteArrayInputStream bai = null ; try { bai = new ByteArrayInputStream ( ddsSW . toString ( ) . getBytes ( \"UTF-8\" ) ) ; } catch ( UnsupportedEncodingException uee ) { throw new DAP2Exception ( \"UTF-8 encoding not supported\" ) ; } wwwDDS . parse ( bai ) ; return ( wwwDDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * take from degrib repository : http : // slosh . nws . noaa . gov / pubview / degrib / src / degrib / metaname . c?root = degrib&view = markup Apparently for center 8 subcenter 0 and subcenter 255 ( ! ) [CODESPLIT] private void init ( ) { add ( 0 , 0 , 193 , \"ApparentT\" , \"Apparent Temperature\" , \"K\" ) ; add ( 0 , 1 , 192 , \"Wx\" , \"Weather string\" , \"\" ) ; /* LOOK ignored : grandfather'ed in a NDFD choice for POP. */ add ( 0 , 10 , 8 , \"PoP12\" , \"Prob of 0.01 In. of Precip\" , \"%\" ) ; add ( 0 , 13 , 194 , \"smokes\" , \"Surface level smoke from fires\" , \"log10(g/m^3)\" ) ; add ( 0 , 13 , 195 , \"smokec\" , \"Average vertical column smoke from fires\" , \"log10(g/m^3)\" ) ; add ( 0 , 14 , 192 , \"O3MR\" , \"Ozone Mixing Ratio\" , \"kg/kg\" ) ; add ( 0 , 14 , 193 , \"OZCON\" , \"Ozone Concentration\" , \"PPB\" ) ; /* Arthur adopted NCEP ozone values from NCEP local table to NDFD local tables. (11/14/2009) */ add ( 0 , 14 , 200 , \"OZMAX1\" , \"Ozone Daily Max from 1-hour Average\" , \"ppbV\" ) ; add ( 0 , 14 , 201 , \"OZMAX8\" , \"Ozone Daily Max from 8-hour Average\" , \"ppbV\" ) ; /* Added 1/23/2007 in preparation for SPC NDFD Grids */ add ( 0 , 19 , 194 , \"ConvOutlook\" , \"Convective Hazard Outlook\" , \"0=none; 2=tstm; 4=slight; 6=moderate; 8=high\" ) ; add ( 0 , 19 , 197 , \"TornadoProb\" , \"Tornado Probability\" , \"%\" ) ; add ( 0 , 19 , 198 , \"HailProb\" , \"Hail Probability\" , \"%\" ) ; add ( 0 , 19 , 199 , \"WindProb\" , \"Damaging Thunderstorm Wind Probability\" , \"%\" ) ; add ( 0 , 19 , 200 , \"XtrmTornProb\" , \"Extreme Tornado Probability\" , \"%\" ) ; add ( 0 , 19 , 201 , \"XtrmHailProb\" , \"Extreme Hail Probability\" , \"%\" ) ; add ( 0 , 19 , 202 , \"XtrmWindProb\" , \"Extreme Thunderstorm Wind Probability\" , \"%\" ) ; add ( 0 , 19 , 215 , \"TotalSvrProb\" , \"Total Probability of Severe Thunderstorms\" , \"%\" ) ; add ( 0 , 19 , 216 , \"TotalXtrmProb\" , \"Total Probability of Extreme Severe Thunderstorms\" , \"%\" ) ; add ( 0 , 19 , 217 , \"WWA\" , \"Watch Warning Advisory\" , \"\" ) ; /* Leaving next two lines in for grandfathering sake. 9/19/2007... Probably can remove in future. */ add ( 0 , 19 , 203 , \"TotalSvrProb\" , \"Total Probability of Severe Thunderstorms\" , \"%\" ) ; add ( 0 , 19 , 204 , \"TotalXtrmProb\" , \"Total Probability of Extreme Severe Thunderstorms\" , \"%\" ) ; add ( 0 , 192 , 192 , \"FireWx\" , \"Critical Fire Weather\" , \"%\" ) ; add ( 0 , 192 , 194 , \"DryLightning\" , \"Dry Lightning\" , \"%\" ) ; /* Arthur Added this to both NDFD and NCEP local tables. (5/1/2006) */ add ( 10 , 3 , 192 , \"Surge\" , \"Hurricane Storm Surge\" , \"m\" ) ; add ( 10 , 3 , 193 , \"ETSurge\" , \"Extra Tropical Storm Surge\" , \"m\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws UnsupportedOperationException unless the time zone is UTC [CODESPLIT] @ Override public final Chronology withZone ( DateTimeZone zone ) { if ( zone . equals ( DateTimeZone . UTC ) ) return this . withUTC ( ) ; throw new UnsupportedOperationException ( \"Not supported yet.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode an array of primitive values . [CODESPLIT] static public ByteBuffer encodeArray ( DapType vtype , Object values , ByteOrder order ) throws IOException { TypeSort atomtype = vtype . getAtomicType ( ) ; assert values != null && values . getClass ( ) . isArray ( ) ; int count = Array . getLength ( values ) ; int total = ( int ) TypeSort . getSize ( atomtype ) * count ; ByteBuffer buf = ByteBuffer . allocate ( total ) . order ( order ) ; switch ( atomtype ) { case Char : char [ ] datac = ( char [ ] ) values ; for ( int i = 0 ; i < datac . length ; i ++ ) { byte b = ( byte ) ( 0xFF L & ( long ) ( datac [ i ] ) ) ; buf . put ( b ) ; } break ; case UInt8 : case Int8 : byte [ ] data8 = ( byte [ ] ) values ; buf . put ( data8 ) ; break ; case Int16 : case UInt16 : short [ ] data16 = ( short [ ] ) values ; buf . asShortBuffer ( ) . put ( data16 ) ; buf . position ( total ) ; // because we are using asXXXBuffer break ; case Int32 : case UInt32 : int [ ] data32 = ( int [ ] ) values ; buf . asIntBuffer ( ) . put ( data32 ) ; buf . position ( total ) ; // because we are using asXXXBuffer break ; case Int64 : case UInt64 : long [ ] data64 = ( long [ ] ) values ; buf . asLongBuffer ( ) . put ( data64 ) ; buf . position ( total ) ; // because we are using asXXXBuffer break ; case Float32 : float [ ] dataf = ( float [ ] ) values ; buf . asFloatBuffer ( ) . put ( dataf ) ; buf . position ( total ) ; // because we are using asXXXBuffer break ; case Float64 : double [ ] datad = ( double [ ] ) values ; buf . asDoubleBuffer ( ) . put ( datad ) ; buf . position ( total ) ; // because we are using asXXXBuffer break ; case URL : case String : // Convert the string to a counted UTF-8 bytestring String [ ] datas = ( String [ ] ) values ; // Pass 1: get total size total = 0 ; for ( int i = 0 ; i < datas . length ; i ++ ) { String content = datas [ i ] ; byte [ ] bytes = content . getBytes ( DapUtil . UTF8 ) ; total += ( bytes . length + COUNTSIZE ) ; } buf = ByteBuffer . allocate ( total ) . order ( order ) ; // Pass 2: write the strings for ( int i = 0 ; i < datas . length ; i ++ ) { String content = datas [ i ] ; byte [ ] bytes = content . getBytes ( DapUtil . UTF8 ) ; buf . putLong ( bytes . length ) ; buf . put ( bytes ) ; } break ; case Opaque : // Unfortunately, Array.get1d does not produce // a ByteBuffer[]. Object [ ] datao = ( Object [ ] ) values ; // Pass 1: get total size total = 0 ; int size = 0 ; for ( int i = 0 ; i < datao . length ; i ++ ) { ByteBuffer opaquedata = ( ByteBuffer ) datao [ i ] ; // the data may be at an offset in the buffer size = opaquedata . remaining ( ) ; // should be limit - pos total += ( size + COUNTSIZE ) ; } buf = ByteBuffer . allocate ( total ) . order ( order ) ; // Pass 2: write the opaque elements for ( int i = 0 ; i < datao . length ; i ++ ) { ByteBuffer opaquedata = ( ByteBuffer ) datao [ i ] ; size = opaquedata . remaining ( ) ; // should be limit - pos buf . putLong ( size ) ; int savepos = opaquedata . position ( ) ; buf . put ( opaquedata ) ; opaquedata . position ( savepos ) ; } break ; case Enum : // handled by getPrimitiveType() above assert false : \"Unexpected ENUM type\" ; default : throw new DapException ( \"Unknown type: \" + vtype . getTypeName ( ) ) ; } return buf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out a prefix count [CODESPLIT] public void writeCount ( long count ) throws IOException { countbuffer . clear ( ) ; countbuffer . putLong ( count ) ; byte [ ] countbuf = countbuffer . array ( ) ; int len = countbuffer . position ( ) ; writeBytes ( countbuf , len ) ; if ( DEBUG ) { System . err . printf ( \"count: %d%n\" , count ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out an array of atomic values [CODESPLIT] public void writeAtomicArray ( DapType daptype , Object values ) throws IOException { assert values != null && values . getClass ( ) . isArray ( ) ; ByteBuffer buf = SerialWriter . encodeArray ( daptype , values , this . order ) ; byte [ ] bytes = buf . array ( ) ; int len = buf . position ( ) ; writeBytes ( bytes , len ) ; if ( DEBUG ) { System . err . printf ( \"%s: \" , daptype . getShortName ( ) ) ; for ( int i = 0 ; i < len ; i ++ ) { int x = ( int ) ( order == ByteOrder . BIG_ENDIAN ? bytes [ i ] : bytes [ ( len - 1 ) - i ] ) ; System . err . printf ( \"%02x\" , ( int ) ( x & 0xff ) ) ; } System . err . println ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out a set of bytes [CODESPLIT] public void writeBytes ( byte [ ] bytes , int len ) throws IOException { outputBytes ( bytes , 0 , len ) ; if ( this . checksummode . enabled ( ChecksumMode . DAP ) ) { this . checksum . update ( bytes , 0 , len ) ; if ( DUMPCSUM ) { System . err . print ( \"SSS \" ) ; for ( int i = 0 ; i < len ; i ++ ) { System . err . printf ( \"%02x\" , bytes [ i ] ) ; } System . err . println ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deliberate choke point for debugging [CODESPLIT] public void outputBytes ( byte [ ] bytes , int start , int count ) throws IOException { if ( DUMPDATA ) { System . err . printf ( \"output %d/%d:\" , start , count ) ; for ( int i = 0 ; i < count ; i ++ ) { System . err . printf ( \" %02x\" , bytes [ i ] ) ; } System . err . println ( \"\" ) ; System . err . flush ( ) ; } output . write ( bytes , start , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if this is a POINT datatype . If so a TableAnalyser is used to analyze its structure . The TableAnalyser is reused when the dataset is opened . <ol > <li > Can handle ANY_POINT FeatureType . <li > Must have time lat lon axis ( from CoordSysBuilder ) <li > Call TableAnalyzer . factory () to create a TableAnalyzer <li > TableAnalyzer must agree it can handle the requested FeatureType < / ol > [CODESPLIT] @ Override public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ds , Formatter errlog ) throws IOException { if ( wantFeatureType == null ) wantFeatureType = FeatureType . ANY_POINT ; if ( wantFeatureType != FeatureType . ANY_POINT ) { if ( ! wantFeatureType . isPointFeatureType ( ) ) return null ; } TableConfigurer tc = TableAnalyzer . getTableConfigurer ( wantFeatureType , ds ) ; // if no explicit tc, then check whatever we can before expensive analysis) if ( tc == null ) { boolean hasTime = false ; boolean hasLat = false ; boolean hasLon = false ; for ( CoordinateAxis axis : ds . getCoordinateAxes ( ) ) { if ( axis . getAxisType ( ) == AxisType . Time ) //&& (axis.getRank() == 1)) hasTime = true ; if ( axis . getAxisType ( ) == AxisType . Lat ) //&& (axis.getRank() == 1)) hasLat = true ; if ( axis . getAxisType ( ) == AxisType . Lon ) //&& (axis.getRank() == 1)) hasLon = true ; } // minimum we need if ( ! ( hasTime && hasLon && hasLat ) ) { errlog . format ( \"PointDataset must have lat,lon,time\" ) ; return null ; } } else if ( showTables ) { System . out . printf ( \"TableConfigurer = %s%n\" , tc . getClass ( ) . getName ( ) ) ; } try { // gotta do some work TableAnalyzer analyser = TableAnalyzer . factory ( tc , wantFeatureType , ds ) ; if ( analyser == null ) return null ; if ( ! analyser . featureTypeOk ( wantFeatureType , errlog ) ) { return null ; } return analyser ; } catch ( Throwable t ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************* This method is used to convert special characters into their actual byte values . <p / > For example in a URL the space character is represented as %20 this method will replace that with a space charater . ( a single value of 0x20 ) [CODESPLIT] private String prepCE ( String ce ) { int index ; //System.out.println(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"); //System.out.println(\"Prepping: \\\"\"+ce+\"\\\"\"); if ( ce == null ) { ce = \"\" ; //System.out.println(\"null Constraint expression.\"); } else if ( ! ce . equals ( \"\" ) ) { //System.out.println(\"Searching for:  %\"); index = ce . indexOf ( \"%\" ) ; //System.out.println(\"index of %: \"+index); if ( index == - 1 ) return ( ce ) ; if ( index > ( ce . length ( ) - 3 ) ) return ( null ) ; while ( index >= 0 ) { //System.out.println(\"Found % at character \" + index); String specChar = ce . substring ( index + 1 , index + 3 ) ; //System.out.println(\"specChar: \\\"\" + specChar + \"\\\"\"); // Convert that bad boy! char val = ( char ) Byte . parseByte ( specChar , 16 ) ; //System.out.println(\"                val: '\" + val + \"'\"); //System.out.println(\"String.valueOf(val): \\\"\" + String.valueOf(val) + \"\\\"\"); ce = ce . substring ( 0 , index ) + String . valueOf ( val ) + ce . substring ( index + 3 , ce . length ( ) ) ; //System.out.println(\"ce: \\\"\" + ce + \"\\\"\"); index = ce . indexOf ( \"%\" ) ; if ( index > ( ce . length ( ) - 3 ) ) return ( null ) ; } } //      char ca[] = ce.toCharArray(); //\tfor(int i=0; i<ca.length ;i++) //\t    System.out.print(\"'\"+(byte)ca[i]+\"' \"); //\tSystem.out.println(\"\"); //\tSystem.out.println(ce); //\tSystem.out.println(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"); //        System.out.println(\"Returning CE: \\\"\"+ce+\"\\\"\"); return ( ce ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************* Processes an incoming <code > HttpServletRequest< / code > . Uses the content of the <code > HttpServletRequest< / code > to create a <code > ReqState< / code > object in that caches the values for : <ul > <li > <b > dataSet< / b > The data set name . ( Accessible using <code > setDataSet () < / code > and <code > getDataSet () < / code > ) < / li > <li > <b > CE< / b > The constraint expression . ( Accessible using <code > setCE () < / code > and <code > getCE () < / code > ) < / li > <li > <b > requestSuffix< / b > The request suffix used by OPeNDAP DAP2 to indicate the type of response desired by the client . ( Accessible using <code > setRequestSuffix () < / code > and <code > getRequestSuffix () < / code > ) < / li > <li > <b > isClientCompressed< / b > Does the requesting client accept a compressed response?< / li > <li > <b > ServletConfig< / b > The <code > ServletConfig< / code > object for this servlet . < / li > <li > <b > ServerName< / b > The class name of this server . < / li > <li > <b > RequestURL< / b > THe URL that that was used to call thye servlet . < / li > < / ul > [CODESPLIT] protected void processDodsURL ( ) { String cxtpath = HTTPUtil . canonicalpath ( myHttpRequest . getContextPath ( ) ) ; if ( cxtpath != null && cxtpath . length ( ) == 0 ) cxtpath = null ; if ( cxtpath == null ) cxtpath = \"/\" ; // we are running as webapps/ROOT String servletpath = HTTPUtil . canonicalpath ( myHttpRequest . getServletPath ( ) ) ; if ( servletpath != null && servletpath . length ( ) == 0 ) servletpath = null ; this . dataSetName = HTTPUtil . canonicalpath ( myHttpRequest . getPathInfo ( ) ) ; if ( this . dataSetName != null && this . dataSetName . length ( ) == 0 ) this . dataSetName = null ; if ( this . dataSetName == null ) { if ( servletpath != null ) { // use servlet path if ( cxtpath != null && servletpath . startsWith ( cxtpath ) ) { this . dataSetName = servletpath . substring ( cxtpath . length ( ) ) ; } else { this . dataSetName = servletpath ; } } } else { if ( dataSetName . startsWith ( \"/dodsC\" ) ) dataSetName = dataSetName . substring ( 6 ) ; } this . requestSuffix = null ; if ( this . dataSetName != null ) { String name = this . dataSetName ; if ( name . startsWith ( \"/\" ) ) name = name . substring ( 1 ) ; // remove any leading '/' String [ ] pieces = name . split ( \"/\" ) ; if ( pieces . length == 0 || pieces [ 0 ] . length ( ) == 0 ) { requestSuffix = \"\" ; this . dataSetName = name ; } else { String endOPath = pieces [ pieces . length - 1 ] ; // Check the last element in the path for the character \".\" int index = endOPath . lastIndexOf ( ' ' ) ; // If a dot is found take the stuff after it as the DAP2 request suffix if ( index > 0 ) { // pluck the DAP2 request suffix off of the end requestSuffix = endOPath . substring ( index + 1 ) ; // Set the data set name to the entire path minus the // suffix which we know exists in the last element // of the path. this . dataSetName = this . dataSetName . substring ( 1 , this . dataSetName . lastIndexOf ( ' ' ) ) ; } else { // strip the leading slash (/) from the dataset name and set the suffix to an empty string requestSuffix = \"\" ; this . dataSetName = name ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************* Evaluates the ( private ) request object to determine if the client that sent the request accepts compressed return documents . [CODESPLIT] public boolean getAcceptsCompressed ( ) { boolean isTiny ; isTiny = false ; String encoding = this . myHttpRequest . getHeader ( \"Accept-Encoding\" ) ; if ( encoding != null ) isTiny = encoding . contains ( \"deflate\" ) ; else isTiny = false ; return ( isTiny ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * # Code table 4 . 2 - Parameter number by product discipline and parameter category 0 0 Estimated precipitation ( kg m - 2 ) 1 1 Instantaneous rain rate ( kg m - 2 s - 1 ) 2 2 Cloud top height ( m ) 3 3 Cloud top height quality indicator ( Code table 4 . 219 ) 4 4 Estimated u - component of wind ( m / s ) 5 5 Estimated v - component of wind ( m / s ) 6 6 Number of pixel used ( Numeric ) 7 7 Solar zenith angle ( deg ) 8 8 Relative azimuth angle ( deg ) 9 9 Reflectance in 0 . 6 micron channel ( % ) 10 10 Reflectance in 0 . 8 micron channel ( % ) 11 11 Reflectance in 1 . 6 micron channel ( % ) 12 12 Reflectance in 3 . 9 micron channel ( % ) 13 13 Atmospheric divergence ( / s ) 14 14 Cloudy brightness temperature ( K ) 15 15 Clear - sky brightness temperature ( K ) 16 16 Cloudy radiance ( with respect to wave number ) ( W m - 1 sr - 1 ) 17 17 Clear - sky radiance ( with respect to wave number ) ( W m - 1 sr - 1 ) 18 18 Reserved 19 19 Wind speed ( m / s ) 20 20 Aerosol optical thickness at 0 . 635 um 21 21 Aerosol optical thickness at 0 . 810 um 22 22 Aerosol optical thickness at 1 . 640 um 23 23 Angstrom coefficient # 24 - 26 Reserved 27 27 Bidirectional reflectance factor ( numeric ) 28 28 Brightness temperature ( K ) 29 29 Scaled radiance ( numeric ) # 30 - 191 Reserved # 192 - 254 Reserved for local use 255 255 Missing [CODESPLIT] private ImmutableMap < Integer , Grib2Parameter > readTable ( String path ) throws IOException { ImmutableMap . Builder < Integer , Grib2Parameter > builder = ImmutableMap . builder ( ) ; if ( debugOpen ) { System . out . printf ( \"readEcmwfTable path= %s%n\" , path ) ; } ClassLoader cl = Grib2TableConfig . class . getClassLoader ( ) ; try ( InputStream is = cl . getResourceAsStream ( path ) ) { if ( is == null ) { throw new IllegalStateException ( \"Cant find \" + path ) ; } try ( BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( is , Charset . forName ( \"UTF8\" ) ) ) ) { int count = 0 ; while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) { break ; } if ( line . startsWith ( \"#\" ) || line . trim ( ) . length ( ) == 0 ) { continue ; } count ++ ; int posBlank1 = line . indexOf ( ' ' ) ; int posBlank2 = line . indexOf ( ' ' , posBlank1 + 1 ) ; int lastParen = line . lastIndexOf ( ' ' ) ; String num1 = line . substring ( 0 , posBlank1 ) . trim ( ) ; String num2 = line . substring ( posBlank1 + 1 , posBlank2 ) ; String desc = ( lastParen > 0 ) ? line . substring ( posBlank2 + 1 , lastParen ) . trim ( ) : line . substring ( posBlank2 + 1 ) . trim ( ) ; String units = ( lastParen > 0 ) ? line . substring ( lastParen ) . trim ( ) : \"\" ; if ( units . startsWith ( \"(\" ) & units . endsWith ( \")\" ) ) units = units . substring ( 1 , units . length ( ) - 1 ) ; if ( ! num1 . equals ( num2 ) ) { if ( debug ) { System . out . printf ( \"*****num1 != num2 for %s%n\" , line ) ; } continue ; } int number = Integer . parseInt ( num1 ) ; //   public Grib2Parameter(int discipline, int category, int number, String name, String unit, String abbrev) { Grib2Parameter parameter = new Grib2Parameter ( discipline , category , number , desc , units , null , desc ) ; builder . put ( parameter . getNumber ( ) , parameter ) ; if ( debug ) { System . out . printf ( \" %s%n\" , parameter ) ; } } } } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stuff to do after UI is complete [CODESPLIT] void finishInit ( ) { // some widgets from the GridUI\r np = ui . panz ; vertPanel = ui . vertPanel ; dataValueLabel = ui . dataValueLabel ; posLabel = ui . positionLabel ; // get last saved Projection\r project = ( ProjectionImpl ) store . getBean ( LastProjectionName , null ) ; if ( project != null ) setProjection ( project ) ; // get last saved MapArea\r ProjectionRect ma = ( ProjectionRect ) store . getBean ( LastMapAreaName , null ) ; if ( ma != null ) np . setMapArea ( ma ) ; makeEventManagement ( ) ; // last thing\r /* get last dataset filename and reopen it\r\n    String filename = (String) store.get(LastDatasetName);\r\n    if (filename != null)\r\n      setDataset(filename); */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assume that its done in the event thread [CODESPLIT] boolean showDataset ( ) { // temp kludge for initialization\r java . util . List grids = gridDataset . getGrids ( ) ; if ( ( grids == null ) || grids . size ( ) == 0 ) { javax . swing . JOptionPane . showMessageDialog ( null , \"No gridded fields in file \" + gridDataset . getTitle ( ) ) ; return false ; } currentField = ( GridDatatype ) grids . get ( 0 ) ; currentSlice = 0 ; currentLevel = 0 ; currentTime = 0 ; currentEnsemble = 0 ; currentRunTime = 0 ; eventsOK = false ; // dont let this trigger redraw\r renderGrid . setGeoGrid ( currentField ) ; ui . setFields ( gridDataset . getGrids ( ) ) ; setField ( currentField ) ; // if possible, change the projection and the map area to one that fits this\r // dataset\r ProjectionImpl dataProjection = currentField . getProjection ( ) ; if ( dataProjection != null ) setProjection ( dataProjection ) ; // ready to draw\r //draw(true);\r // events now ok\r eventsOK = true ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public GridDatatype getField () { return currentField ; } [CODESPLIT] private boolean setField ( Object fld ) { GridDatatype gg = null ; if ( fld instanceof GridDatatype ) gg = ( GridDatatype ) fld ; else if ( fld instanceof String ) gg = gridDataset . findGridDatatype ( ( String ) fld ) ; if ( null == gg ) return false ; renderGrid . setGeoGrid ( gg ) ; currentField = gg ; GridCoordSystem gcs = gg . getCoordinateSystem ( ) ; gcs . setProjectionBoundingBox ( ) ; // set levels\r CoordinateAxis1D vaxis = gcs . getVerticalAxis ( ) ; levelNames = ( vaxis == null ) ? new ArrayList ( ) : vaxis . getNames ( ) ; if ( ( levelNames == null ) || ( currentLevel >= levelNames . size ( ) ) ) currentLevel = 0 ; vertPanel . setCoordSys ( currentField . getCoordinateSystem ( ) , currentLevel ) ; // set times\r if ( gcs . hasTimeAxis ( ) ) { CoordinateAxis1DTime taxis = gcs . hasTimeAxis1D ( ) ? gcs . getTimeAxis1D ( ) : gcs . getTimeAxisForRun ( 0 ) ; timeNames = ( taxis == null ) ? new ArrayList ( ) : taxis . getNames ( ) ; if ( ( timeNames == null ) || ( currentTime >= timeNames . size ( ) ) ) currentTime = 0 ; hasDependentTimeAxis = ! gcs . hasTimeAxis1D ( ) ; } else hasDependentTimeAxis = false ; // set ensembles\r CoordinateAxis1D eaxis = gcs . getEnsembleAxis ( ) ; ensembleNames = ( eaxis == null ) ? new ArrayList ( ) : eaxis . getNames ( ) ; currentEnsemble = ensembleNames . size ( ) > 0 ? 0 : - 1 ; // set runtimes\r CoordinateAxis1DTime rtaxis = gcs . getRunTimeAxis ( ) ; runtimeNames = ( rtaxis == null ) ? new ArrayList ( ) : rtaxis . getNames ( ) ; currentRunTime = runtimeNames . size ( ) > 0 ? 0 : - 1 ; ui . setField ( gg ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * TABLE C - SUB - CENTERS FOR CENTER 9 US NWS FIELD STATIONS from bdgparm . f John Halquist <John . Halquist [CODESPLIT] @ Override @ Nullable public String getSubCenterName ( int subcenter ) { if ( nwsoSubCenter == null ) nwsoSubCenter = readNwsoSubCenter ( \"resources/grib1/noaa_rfc/tableC.txt\" ) ; if ( nwsoSubCenter == null ) return null ; return nwsoSubCenter . get ( subcenter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "order : num name desc unit [CODESPLIT] @ Nullable private static Map < Integer , String > readNwsoSubCenter ( String path ) { Map < Integer , String > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , CDM . utf8Charset ) ) ) { while ( true ) { String line = br . readLine ( ) ; if ( line == null ) { break ; } if ( ( line . length ( ) == 0 ) || line . startsWith ( \"#\" ) ) { continue ; } StringBuilder lineb = new StringBuilder ( line ) ; StringUtil2 . remove ( lineb , \"'+,/\" ) ; String [ ] flds = lineb . toString ( ) . split ( \"[:]\" ) ; int val = Integer . parseInt ( flds [ 0 ] . trim ( ) ) ; // must have a number\r String name = flds [ 1 ] . trim ( ) + \": \" + flds [ 2 ] . trim ( ) ; result . put ( val , name ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe\r } catch ( IOException ioError ) { logger . warn ( \"An error occurred in Grib1Tables while trying to open the table \" + path + \" : \" + ioError ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does not handle non - standard calendars [CODESPLIT] static public CalendarDateRange of ( DateRange dr ) { if ( dr == null ) return null ; return CalendarDateRange . of ( dr . getStart ( ) . getDate ( ) , dr . getEnd ( ) . getDate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reletive error in position - GRIB numbers sometimes miscoded [CODESPLIT] public static Grib2Gds factory ( int template , byte [ ] data ) { Grib2Gds result ; switch ( template ) { case 0 : result = new LatLon ( data ) ; break ; case 1 : result = new RotatedLatLon ( data ) ; break ; case 10 : result = new Mercator ( data ) ; break ; case 20 : result = new PolarStereographic ( data ) ; break ; case 30 : result = new LambertConformal ( data , 30 ) ; break ; case 31 : result = new AlbersEqualArea ( data ) ; break ; case 40 : result = new GaussLatLon ( data ) ; break ; case 50 : // Spherical Harmonic Coefficients BOGUS\r result = new GdsSpherical ( data , template ) ; break ; case 90 : result = new SpaceViewPerspective ( data ) ; break ; // LOOK NCEP specific\r case 204 : result = new CurvilinearOrthogonal ( data ) ; break ; case 32769 : result = new RotatedLatLon32769 ( data ) ; break ; default : throw new UnsupportedOperationException ( \"Unsupported GDS type = \" + template ) ; } result . finish ( ) ; // stuff that cant be done in the constructor\r return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Code Table Code table 3 . 2 - Shape of the Earth ( 3 . 2 ) 0 : Earth assumed spherical with radius = 6 367 470 . 0 m 1 : Earth assumed spherical with radius specified ( in m ) by data producer 2 : Earth assumed oblate spheroid with size as determined by IAU in 1965 ( major axis = 6 378 160 . 0 m minor axis = 6 356 775 . 0 m f = 1 / 297 . 0 ) 3 : Earth assumed oblate spheroid with major and minor axes specified ( in km ) by data producer 4 : Earth assumed oblate spheroid as defined in IAG - GRS80 model ( major axis = 6 378 137 . 0 m minor axis = 6 356 752 . 314 m f = 1 / 298 . 257 222 101 ) 5 : Earth assumed represented by WGS84 ( as used by ICAO since 1998 ) 6 : Earth assumed spherical with radius of 6 371 229 . 0 m 7 : Earth assumed oblate spheroid with major or minor axes specified ( in m ) by data producer 8 : Earth model assumed spherical with radius of 6 371 200 m but the horizontal datum of the resulting latitude / longitude field is the WGS84 reference frame [CODESPLIT] protected Earth getEarth ( ) { switch ( earthShape ) { case 0 : return new Earth ( 6367470.0 ) ; case 1 : if ( earthRadius < 6000000 ) earthRadius *= 1000.0 ; // bad units\r return new Earth ( earthRadius ) ; case 2 : return EarthEllipsoid . IAU ; case 3 : // oblate in km, so bad values will be large and not scaled\r if ( majorAxis < 6000000 ) majorAxis *= 1000.0 ; if ( minorAxis < 6000000 ) minorAxis *= 1000.0 ; return new EarthEllipsoid ( \"Grib2 Type 3\" , - 1 , majorAxis , minorAxis , 0 ) ; case 4 : return EarthEllipsoid . IAG_GRS80 ; case 5 : return EarthEllipsoid . WGS84 ; case 6 : return new Earth ( 6371229.0 ) ; case 7 : // Oblate in meters\r if ( majorAxis < 6000000 ) majorAxis *= 1000.0 ; // bad units\r if ( minorAxis < 6000000 ) minorAxis *= 1000.0 ; // bad units\r return new EarthEllipsoid ( \"Grib2 Type 7\" , - 1 , majorAxis , minorAxis , 0 ) ; case 8 : return new Earth ( 6371200.0 ) ; case 9 : return EarthEllipsoid . Airy1830 ; default : return new Earth ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "also see Snyder p 101 [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double fromLat = Math . toRadians ( latLon . getLatitude ( ) ) ; double theta = computeTheta ( latLon . getLongitude ( ) ) ; double term = earth . isSpherical ( ) ? n2 * Math . sin ( fromLat ) : n * MapMath . qsfn ( Math . sin ( fromLat ) , e , one_es ) ; double rho = c - term ; if ( rho < 0.0 ) throw new RuntimeException ( \"F\" ) ; rho = dd * Math . sqrt ( rho ) ; double toX = rho * Math . sin ( theta ) ; double toY = rho0 - rho * Math . cos ( theta ) ; result . setLocation ( totalScale * toX + falseEasting , totalScale * toY + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = ( world . getX ( ) - falseEasting ) / totalScale ; // assumes cartesion coords in km\r double fromY = ( world . getY ( ) - falseNorthing ) / totalScale ; fromY = rho0 - fromY ; double rho = MapMath . distance ( fromX , fromY ) ; if ( rho == 0.0 ) { toLon = 0.0 ; toLat = n > 0.0 ? MapMath . HALFPI : - MapMath . HALFPI ; } else { if ( n < 0.0 ) { rho = - rho ; fromX = - fromX ; fromY = - fromY ; } double lpphi = rho / dd ; if ( ! earth . isSpherical ( ) ) { lpphi = ( c - lpphi * lpphi ) / n ; if ( Math . abs ( ec - Math . abs ( lpphi ) ) > TOL7 ) { if ( Math . abs ( lpphi ) > 2.0 ) throw new IllegalArgumentException ( \"AlbersEqualAreaEllipse x,y=\" + world ) ; lpphi = phi1_ ( lpphi , e , one_es ) ; if ( lpphi == Double . MAX_VALUE ) throw new RuntimeException ( \"I\" ) ; } else { lpphi = ( lpphi < 0. ) ? - MapMath . HALFPI : MapMath . HALFPI ; } } else { // spherical case\r lpphi = ( c - lpphi * lpphi ) / n2 ; if ( Math . abs ( lpphi ) <= 1.0 ) { lpphi = Math . asin ( lpphi ) ; } else { lpphi = ( lpphi < 0. ) ? - MapMath . HALFPI : MapMath . HALFPI ; } } toLon = Math . atan2 ( fromX , fromY ) / n ; //coverity[swapped_arguments]\r toLat = lpphi ; } result . setLatitude ( Math . toDegrees ( toLat ) ) ; result . setLongitude ( Math . toDegrees ( toLon ) + lon0deg ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parse invocation interface [CODESPLIT] public int dapparse ( String text , DDS dds , DAS das , DAP2Exception err ) throws ParseException { //setDebugLevel(1); ddsobject = dds ; dasobject = das ; errobject = ( err == null ? new DAP2Exception ( ) : err ) ; dapdebug = getDebugLevel ( ) ; Boolean accept = parse ( text ) ; if ( ! accept ) throw new ParseException ( \"Dap2 Parser returned false\" ) ; return parseClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this to parse a DDS [CODESPLIT] public int ddsparse ( String text , DDS dds ) throws ParseException { return dapparse ( text , dds , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this to parse a DAS [CODESPLIT] public int dasparse ( String text , DAS das ) throws ParseException { return dapparse ( text , null , das , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this to parse an error {} body [CODESPLIT] public int errparse ( String text , DAP2Exception err ) throws ParseException { return dapparse ( text , null , null , err ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Use the initial keyword to indicate what we are parsing [CODESPLIT] void tagparse ( Dap2Parse parsestate , int kind ) throws ParseException { /* Create the storage object corresponding to what we are parsing */ String expected = parseactual ( ) ; switch ( kind ) { case SCAN_DATASET : parseClass = DapDDS ; if ( ddsobject == null ) throw new ParseException ( \"DapParse: found DDS, expected \" + expected ) ; break ; case SCAN_ATTR : parseClass = DapDAS ; if ( dasobject == null ) throw new ParseException ( \"DapParse: found DAS, expected \" + parseactual ( ) ) ; lexstate . dassetup ( ) ; break ; case SCAN_ERROR : parseClass = DapERR ; if ( errobject == null ) throw new ParseException ( \"DapParse: found error{}, expected \" + parseactual ( ) ) ; break ; default : throw new ParseException ( \"Unknown tag argument: \" + kind ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Since there is no common parent class for BaseType Attribute and AttributeTable provide a type specific name getter . [CODESPLIT] String extractname ( Object o ) throws ParseException { if ( o instanceof BaseType ) return ( ( BaseType ) o ) . getClearName ( ) ; if ( o instanceof Attribute ) return ( ( Attribute ) o ) . getClearName ( ) ; if ( o instanceof AttributeTable ) return ( ( AttributeTable ) o ) . getClearName ( ) ; throw new ParseException ( \"extractname: illegal object class: \" + o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public final boolean init ( RandomAccessFile raf , boolean fullCheck ) throws IOException { rf = raf ; raf . order ( RandomAccessFile . BIG_ENDIAN ) ; return init ( fullCheck ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { if ( rf == null ) { logError ( \"File is null\" ) ; return false ; } gridIndex = new GridIndex ( rf . getLocation ( ) ) ; rf . order ( RandomAccessFile . BIG_ENDIAN ) ; if ( rf . length ( ) < 44 ) return false ; int numEntries = Math . abs ( readInt ( 10 ) ) ; if ( numEntries > 1000000 ) { needToSwap = true ; numEntries = Math . abs ( McIDASUtil . swbyt4 ( numEntries ) ) ; } if ( numEntries > MAX_GRIDS ) { return false ; } //System.out.println(\"need to Swap = \" + needToSwap); //System.out.println(\"number entries=\"+numEntries); // go back to the beginning rf . seek ( 0 ) ; // read the fileheader String label = rf . readString ( 32 ) ; // GEMPAK too closely like McIDAS if ( label . contains ( \"GEMPAK DATA MANAGEMENT FILE\" ) ) { logError ( \"label indicates this is a GEMPAK grid\" ) ; return false ; } else { // check that they are all printable ASCII chars for ( int i = 0 ; i < label . length ( ) ; i ++ ) { String s0 = label . substring ( i , i + 1 ) ; if ( ! ( 0 <= s0 . compareTo ( \" \" ) && s0 . compareTo ( \"~\" ) <= 0 ) ) { logError ( \"bad label, not a McIDAS grid\" ) ; return false ; } } } //System.out.println(\"label = \" + label); // int project = readInt(8); //System.out.println(\"Project = \" + project); int date = readInt ( 9 ) ; // dates are supposed to be yyyddd, but account for ccyyddd up to year 4000 if ( ( date < 10000 ) || ( date > 400000 ) ) { logError ( \"date wrong, not a McIDAS grid\" ) ; return false ; } //System.out.println(\"date = \" + date); if ( rf . length ( ) < 4 * ( numEntries + 12 ) ) return false ; int [ ] entries = new int [ numEntries ] ; for ( int i = 0 ; i < numEntries ; i ++ ) { entries [ i ] = readInt ( i + 11 ) ; // sanity check that this is indeed a McIDAS Grid file if ( entries [ i ] < - 1 ) { logError ( \"bad grid offset \" + i + \": \" + entries [ i ] ) ; return false ; } } if ( ! fullCheck ) { return true ; } // Don't swap: rf . order ( RandomAccessFile . BIG_ENDIAN ) ; for ( int i = 0 ; i < numEntries ; i ++ ) { if ( entries [ i ] == - 1 ) { continue ; } int [ ] header = new int [ 64 ] ; rf . seek ( entries [ i ] * 4 ) ; rf . readInt ( header , 0 , 64 ) ; if ( needToSwap ) { swapGridHeader ( header ) ; } try { McIDASGridRecord gr = new McIDASGridRecord ( entries [ i ] , header ) ; //if (gr.getGridDefRecordId().equals(\"CONF X:93 Y:65\")) { //if (gr.getGridDefRecordId().equals(\"CONF X:54 Y:47\")) { // figure out how to handle Mercator projections // if ( !(gr.getGridDefRecordId().startsWith(\"MERC\"))) { gridIndex . addGridRecord ( gr ) ; if ( gdsMap . get ( gr . getGridDefRecordId ( ) ) == null ) { McGridDefRecord mcdef = gr . getGridDefRecord ( ) ; //System.out.println(\"new nav \" + mcdef.toString()); gdsMap . put ( mcdef . toString ( ) , mcdef ) ; gridIndex . addHorizCoordSys ( mcdef ) ; } //} } catch ( McIDASException me ) { logError ( \"problem creating grid dir\" ) ; return false ; } } // check to see if there are any grids that we can handle if ( gridIndex . getGridRecords ( ) . isEmpty ( ) ) { logError ( \"no grids found\" ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swap the grid header avoiding strings [CODESPLIT] private void swapGridHeader ( int [ ] gh ) { McIDASUtil . flip ( gh , 0 , 5 ) ; McIDASUtil . flip ( gh , 7 , 7 ) ; McIDASUtil . flip ( gh , 9 , 10 ) ; McIDASUtil . flip ( gh , 12 , 14 ) ; McIDASUtil . flip ( gh , 32 , 51 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the grid [CODESPLIT] public float [ ] readGrid ( McIDASGridRecord gr ) throws IOException { float [ ] data ; //try { int te = ( gr . getOffsetToHeader ( ) + 64 ) * 4 ; int rows = gr . getRows ( ) ; int cols = gr . getColumns ( ) ; rf . seek ( te ) ; float scale = ( float ) gr . getParamScale ( ) ; data = new float [ rows * cols ] ; rf . order ( needToSwap ? RandomAccessFile . LITTLE_ENDIAN : RandomAccessFile . BIG_ENDIAN ) ; // int n = 0; // store such that 0,0 is in lower left corner... for ( int nc = 0 ; nc < cols ; nc ++ ) { for ( int nr = 0 ; nr < rows ; nr ++ ) { int temp = rf . readInt ( ) ; // check for missing value data [ ( rows - nr - 1 ) * cols + nc ] = ( temp == McIDASUtil . MCMISSING ) ? Float . NaN : ( ( float ) temp ) / scale ; } } rf . order ( RandomAccessFile . BIG_ENDIAN ) ; //} catch (Exception esc) { //  System.out.println(esc); //} return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an integer [CODESPLIT] public int readInt ( int word ) throws IOException { if ( rf == null ) { throw new IOException ( \"no file to read from\" ) ; } rf . seek ( word * 4 ) ; // set the order if ( needToSwap ) { rf . order ( RandomAccessFile . LITTLE_ENDIAN ) ; // swap } else { rf . order ( RandomAccessFile . BIG_ENDIAN ) ; } int idata = rf . readInt ( ) ; rf . order ( RandomAccessFile . BIG_ENDIAN ) ; return idata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for testing purposes [CODESPLIT] public static void main ( String [ ] args ) throws IOException { String file = \"GRID2001\" ; if ( args . length > 0 ) { file = args [ 0 ] ; } McIDASGridReader mg = new McIDASGridReader ( file ) ; GridIndex gridIndex = mg . getGridIndex ( ) ; List grids = gridIndex . getGridRecords ( ) ; System . out . println ( \"found \" + grids . size ( ) + \" grids\" ) ; int num = Math . min ( grids . size ( ) , 10 ) ; for ( int i = 0 ; i < num ; i ++ ) { System . out . println ( grids . get ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a constraint OWS element out . [CODESPLIT] private void writeAConstraint ( String name , boolean isImplemented ) { String defValue ; if ( isImplemented ) defValue = \"TRUE\" ; else defValue = \"FALSE\" ; fileOutput += \"<ows:Constraint name=\\\"\" + name + \"\\\"> \" + \"<ows:NoValues/> \" + \"<ows:DefaultValue>\" + defValue + \"</ows:DefaultValue> \" + \"</ows:Constraint>\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes headers and service sections [CODESPLIT] private void writeHeadersAndSS ( ) { fileOutput += \"<wfs:WFS_Capabilities xsi:schemaLocation=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd \" ) + \" xmlns:xsi=\" + WFSXMLHelper . encQuotes ( \"http://www.w3.org/2001/XMLSchema-instance\" ) + \" xmlns:xlink=\" + WFSXMLHelper . encQuotes ( \"http://www.w3.org/1999/xlink\" ) + \" xmlns:gml=\" + WFSXMLHelper . encQuotes ( \"http://opengis.net/gml\" ) + \" xmlns:fes=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/fes/2.0\" ) + \" xmlns:ogc=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/ogc\" ) + \" xmlns:ows=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/ows/1.1\\\" xmlns:wfs=\\\"http://opengis.net/wfs/2.0\" ) + \" xmlns=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/wfs/2.0\" ) + \" version=\\\"2.0.0\\\">\" ; writeServiceInfo ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes all added operations and writes an operations metadata section . [CODESPLIT] public void writeOperations ( ) { fileOutput += \"<ows:OperationsMetadata> \" ; for ( WFSRequestType rt : operationList ) { writeAOperation ( rt ) ; } // Write parameters\r fileOutput += \"<ows:Parameter name=\\\"AcceptVersions\\\"> \" + \"<ows:AllowedValues> \" + \"<ows:Value>2.0.0</ows:Value>\" + \"</ows:AllowedValues>\" + \"</ows:Parameter>\" ; fileOutput += \"<ows:Parameter name=\\\"AcceptFormats\\\">\" + \"<ows:AllowedValues> \" + \"<ows:Value>text/xml</ows:Value>\" + \"</ows:AllowedValues>\" + \"</ows:Parameter>\" ; fileOutput += \"<ows:Parameter name=\\\"Sections\\\"> \" + \"<ows:AllowedValues> \" + \"<ows:Value>ServiceIdentification</ows:Value> \" + \"<ows:Value>ServiceProvider</ows:Value> \" + \"<ows:Value>OperationsMetadata</ows:Value> \" + \"<ows:Value>FeatureTypeList</ows:Value> \" + \"</ows:AllowedValues>\" + \"</ows:Parameter>\" ; fileOutput += \"<ows:Parameter name=\\\"version\\\"> \" + \"<ows:AllowedValues> \" + \"<ows:Value>2.0.0</ows:Value>\" + \"</ows:AllowedValues>\" + \"</ows:Parameter>\" ; // Write constraints\r writeAConstraint ( \"ImplementsBasicWFS\" , true ) ; writeAConstraint ( \"ImplementsTransactionalWFS\" , false ) ; writeAConstraint ( \"ImplementsLockingWFS\" , false ) ; writeAConstraint ( \"KVPEncoding\" , false ) ; writeAConstraint ( \"XMLEncoding\" , true ) ; writeAConstraint ( \"SOAPEncoding\" , false ) ; writeAConstraint ( \"ImplementsInheritance\" , false ) ; writeAConstraint ( \"ImplementsRemoteResolve\" , false ) ; writeAConstraint ( \"ImplementsResultPaging\" , false ) ; writeAConstraint ( \"ImplementsStandardJoins\" , false ) ; writeAConstraint ( \"ImplementsSpatialJoins\" , false ) ; writeAConstraint ( \"ImplementsTemporalJoins\" , false ) ; writeAConstraint ( \"ImplementsFeatureVersioning\" , false ) ; writeAConstraint ( \"ManageStoredQueries\" , false ) ; writeAConstraint ( \"PagingIsTransactionSafe\" , false ) ; writeAConstraint ( \"QueryExpressions\" , false ) ; fileOutput += \"</ows:OperationsMetadata>\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK - needs to be a directory or maybe an MFILE collection [CODESPLIT] public void execute ( String filename ) throws IOException { try ( RandomAccessFile mraf = new RandomAccessFile ( filename , \"r\" ) ) { MessageScanner scanner = new MessageScanner ( mraf ) ; while ( scanner . hasNext ( ) ) { Message m = scanner . next ( ) ; if ( m == null ) continue ; total_msgs ++ ; if ( m . getNumberDatasets ( ) == 0 ) continue ; // LOOK check on tables complete etc ?? m . setRawBytes ( scanner . getMessageBytes ( m ) ) ; // decide what to do with the message dispatcher . dispatch ( m ) ; } dispatcher . resetBufrTableMessages ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all the files in a directory and process them . Files are sorted by filename . [CODESPLIT] public void readAll ( File dir , FileFilter ff , Closure closure , LogFilter logf , Stats stat ) throws IOException { File [ ] files = dir . listFiles ( ) ; if ( files == null ) { System . out . printf ( \"Dir has no files= %s%n\" , dir ) ; return ; } List < File > list = Arrays . asList ( files ) ; Collections . sort ( list ) ; for ( File f : list ) { if ( ( ff != null ) && ! ff . accept ( f ) ) continue ; if ( f . isDirectory ( ) ) readAll ( f , ff , closure , logf , stat ) ; else scanLogFile ( f , closure , logf , stat ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a log file . [CODESPLIT] public void scanLogFile ( File file , Closure closure , LogFilter logf , Stats stat ) throws IOException { try ( InputStream ios = new FileInputStream ( file ) ) { System . out . printf ( \"-----Reading %s %n\" , file . getPath ( ) ) ; BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( ios , CDM . utf8Charset ) , 40 * 1000 ) ; int total = 0 ; int count = 0 ; while ( ( maxLines < 0 ) || ( count < maxLines ) ) { Log log = parser . nextLog ( dataIS ) ; if ( log == null ) break ; total ++ ; if ( ( logf != null ) && ! logf . pass ( log ) ) continue ; closure . process ( log ) ; count ++ ; } if ( stat != null ) { stat . total += total ; stat . passed += count ; } System . out . printf ( \"----- %s total requests=%d passed=%d %n\" , file . getPath ( ) , total , count ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public static GempakGridReader getInstance ( RandomAccessFile raf , boolean fullCheck ) throws IOException { GempakGridReader ggr = new GempakGridReader ( raf . getLocation ( ) ) ; ggr . init ( raf , fullCheck ) ; return ggr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { boolean ok = super . init ( fullCheck ) ; if ( ! ok ) return false ; // Modeled after GD_OFIL if ( dmLabel . kftype != MFGD ) { logError ( \"not a grid file\" ) ; return false ; } // find the part for GRID DMPart part = getPart ( \"GRID\" ) ; if ( part == null ) { logError ( \"No part named GRID found\" ) ; return false ; } int lenhdr = part . klnhdr ; if ( lenhdr > LLGDHD ) { logError ( \"Grid part header too long\" ) ; return false ; } // int khdrln = lenhdr - 2; // check that the column names are correct for ( int i = 0 ; i < keys . kkcol . size ( ) ; i ++ ) { Key colkey = keys . kkcol . get ( i ) ; if ( ! colkey . name . equals ( kcolnm [ i ] ) ) { logError ( \"Column name \" + colkey + \" doesn't match \" + kcolnm [ i ] ) ; return false ; } } if ( ! fullCheck ) { return true ; } gridIndex = new GridIndex ( filename ) ; // Make the NAV and ANAL blocks float [ ] headerArray = getFileHeader ( NAVB ) ; if ( headerArray == null ) { return false ; } navBlock = new NavigationBlock ( headerArray ) ; //System.out.println(\"nav = \" + navBlock); gridIndex . addHorizCoordSys ( navBlock ) ; headerArray = getFileHeader ( ANLB ) ; if ( headerArray == null ) { return false ; } analBlock = new AnalysisBlock ( headerArray ) ; // Make the grid headers // TODO: move this up into GempakFileReader using DM_RHDA // and account for the flipping there. List < GempakGridRecord > tmpList = new ArrayList <> ( ) ; int [ ] header = new int [ dmLabel . kckeys ] ; if ( ( headers == null ) || ( headers . colHeaders == null ) ) { return false ; } int gridNum = 0 ; for ( int [ ] fullHeader : headers . colHeaders ) { gridNum ++ ; // grid numbers are 1 based if ( ( fullHeader == null ) || ( fullHeader [ 0 ] == IMISSD ) ) { continue ; } // TODO: have GempakGridRecord skip the first word System . arraycopy ( fullHeader , 1 , header , 0 , header . length ) ; GempakGridRecord gh = new GempakGridRecord ( gridNum , header ) ; gh . navBlock = navBlock ; String name = gh . getParameterName ( ) ; //if (name.equals(\"TMPK\") || //    name.equals(\"UREL\") || //    name.equals(\"VREL\") || //    name.equals(\"PMSL\")) { tmpList . add ( gh ) ; //} } // reset the file size since we've gone through all the grids. fileSize = rf . length ( ) ; // find the packing types for these grids // TODO: go back to using gridList //List gridList = gridIndex.getGridRecords(); //if ( !gridList.isEmpty()) { if ( ! tmpList . isEmpty ( ) ) { for ( GempakGridRecord gh : tmpList ) { gh . packingType = getGridPackingType ( gh . gridNumber ) ; if ( ( gh . packingType == MDGGRB ) || ( gh . packingType == MDGRB2 ) || ( gh . packingType == MDGNON ) ) { gridIndex . addGridRecord ( gh ) ; } } } else { return false ; } // check to see if there are any grids that we can handle if ( gridIndex . getGridRecords ( ) . isEmpty ( ) ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the program [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length == 0 ) { System . out . println ( \"need to supply a GEMPAK grid file name\" ) ; System . exit ( 1 ) ; } try { GempakGridParameterTable . addParameters ( \"resources/nj22/tables/gempak/wmogrib3.tbl\" ) ; GempakGridParameterTable . addParameters ( \"resources/nj22/tables/gempak/ncepgrib2.tbl\" ) ; } catch ( Exception e ) { System . out . println ( \"unable to init param tables\" ) ; } GempakGridReader ggr = getInstance ( getFile ( args [ 0 ] ) , true ) ; String var = \"PMSL\" ; if ( ( args . length > 1 ) && ! args [ 1 ] . equalsIgnoreCase ( \"X\" ) ) { var = args [ 1 ] ; } ggr . showGridInfo ( args . length != 3 ) ; GempakGridRecord gh = ggr . findGrid ( var ) ; if ( gh != null ) { System . out . println ( \"\\n\" + var + \":\" ) ; System . out . println ( gh ) ; for ( int j = 0 ; j < 2 ; j ++ ) { System . out . println ( \"Using DP: \" + ggr . useDP ) ; float [ ] data = ggr . readGrid ( gh ) ; if ( data != null ) { System . out . println ( \"# of points = \" + data . length ) ; int cnt = 0 ; int it = 10 ; float min = Float . POSITIVE_INFINITY ; float max = Float . NEGATIVE_INFINITY ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( cnt == it ) { cnt = 0 ; } cnt ++ ; if ( ( data [ i ] != RMISSD ) && ( data [ i ] < min ) ) { min = data [ i ] ; } if ( ( data [ i ] != RMISSD ) && ( data [ i ] > max ) ) { max = data [ i ] ; } } System . out . println ( \"max/min = \" + max + \"/\" + min ) ; } else { System . out . println ( \"unable to decode grid data\" ) ; } ggr . useDP = ! ggr . useDP ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the grid packing type [CODESPLIT] public int getGridPackingType ( int gridNumber ) throws IOException { // See DM_RDTR int irow = 1 ; // Always 1 for grids if ( ( gridNumber < 1 ) || ( gridNumber > dmLabel . kcol ) ) { logWarning ( \"bad grid number \" + gridNumber ) ; return - 9 ; } int iprt = getPartNumber ( \"GRID\" ) ; if ( iprt == 0 ) { logWarning ( \"couldn't find part: GRID\" ) ; return - 10 ; } // gotta subtract 1 because parts are 1 but List is 0 based DMPart part = parts . get ( iprt - 1 ) ; // check for valid data type if ( part . ktyprt != MDGRID ) { logWarning ( \"Not a valid type: \" + GempakUtil . getDataType ( part . ktyprt ) ) ; return - 21 ; } int ilenhd = part . klnhdr ; int ipoint = dmLabel . kpdata + ( irow - 1 ) * dmLabel . kcol * dmLabel . kprt + ( gridNumber - 1 ) * dmLabel . kprt + ( iprt - 1 ) ; // From DM_RPKG int istart = DM_RINT ( ipoint ) ; if ( istart == 0 ) { return - 15 ; } int length = DM_RINT ( istart ) ; int isword = istart + 1 ; if ( length <= ilenhd ) { logWarning ( \"length (\" + length + \") is less than header length (\" + ilenhd + \")\" ) ; return - 15 ; } else if ( Math . abs ( length ) > 10000000 ) { logWarning ( \"length is huge: \" + length ) ; return - 34 ; } int [ ] header = new int [ ilenhd ] ; DM_RINT ( isword , header ) ; // int nword = length - ilenhd; isword += ilenhd ; // read the data packing type return DM_RINT ( isword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the first grid with this name [CODESPLIT] public GempakGridRecord findGrid ( String parm ) { List < GridRecord > gridList = gridIndex . getGridRecords ( ) ; if ( gridList == null ) { return null ; } for ( GridRecord grid : gridList ) { GempakGridRecord gh = ( GempakGridRecord ) grid ; if ( gh . param . trim ( ) . equals ( parm ) ) { return gh ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data [CODESPLIT] public float [ ] readGrid ( GridRecord gr ) throws IOException { int gridNumber = ( ( GempakGridRecord ) gr ) . getGridNumber ( ) ; //int irow = 1;  // Always 1 for grids //int icol = gridNumber; RData data = DM_RDTR ( 1 , gridNumber , \"GRID\" , gr . getDecimalScale ( ) ) ; float [ ] vals = null ; if ( data != null ) { vals = data . data ; } return vals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack a packed grid [CODESPLIT] public float [ ] DM_RPKG ( int isword , int nword , int decimalScale ) throws IOException { // from DM_RPKG // read the data packing type float [ ] data ; int ipktyp = DM_RINT ( isword ) ; int iiword = isword + 1 ; int lendat = nword - 1 ; if ( ipktyp == MDGNON ) { // no packing data = new float [ lendat ] ; DM_RFLT ( iiword , data ) ; return data ; } int iiw ; int irw ; if ( ipktyp == MDGDIF ) { iiw = 4 ; irw = 3 ; } else if ( ipktyp == MDGRB2 ) { iiw = 4 ; irw = 1 ; } else { iiw = 3 ; irw = 2 ; } int [ ] iarray = new int [ iiw ] ; float [ ] rarray = new float [ irw ] ; DM_RINT ( iiword , iarray ) ; iiword = iiword + iiw ; lendat = lendat - iiw ; DM_RFLT ( iiword , rarray ) ; iiword = iiword + irw ; lendat = lendat - irw ; if ( ipktyp == MDGRB2 ) { data = unpackGrib2Data ( iiword , lendat , iarray , rarray ) ; return data ; } int nbits = iarray [ 0 ] ; int misflg = iarray [ 1 ] ; boolean miss = misflg != 0 ; int kxky = iarray [ 2 ] ; // int mword = kxky; int kx = 0 ; if ( iiw == 4 ) { kx = iarray [ 3 ] ; } float ref = rarray [ 0 ] ; float scale = rarray [ 1 ] ; float difmin = 0 ; if ( irw == 3 ) { difmin = rarray [ 2 ] ; } data = unpackData ( iiword , lendat , ipktyp , kxky , nbits , ref , scale , miss , difmin , kx , decimalScale ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read packed data [CODESPLIT] private synchronized float [ ] unpackData ( int iiword , int nword , int ipktyp , int kxky , int nbits , float ref , float scale , boolean miss , float difmin , int kx , int decimalScale ) throws IOException { if ( ipktyp == MDGGRB ) { if ( ! useDP ) { return unpackGrib1Data ( iiword , nword , kxky , nbits , ref , scale , miss , decimalScale ) ; } else { if ( nword * 32 < kxky * nbits ) { // to account for badly written files nword ++ ; } int [ ] ksgrid = new int [ nword ] ; DM_RINT ( iiword , ksgrid ) ; return DP_UGRB ( ksgrid , kxky , nbits , ref , scale , miss , decimalScale ) ; } } else if ( ipktyp == MDGNMC ) { return null ; } else if ( ipktyp == MDGDIF ) { return null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack grib data packed into ints [CODESPLIT] private synchronized float [ ] DP_UGRB ( int [ ] idata , int kxky , int nbits , float qmin , float scale , boolean misflg , int decimalScale ) throws IOException { float scaleFactor = ( decimalScale == 0 ) ? 1.f : ( float ) Math . pow ( 10.0 , - decimalScale ) ; // //Check for valid input. // float [ ] grid = new float [ kxky ] ; if ( ( nbits <= 1 ) || ( nbits > 31 ) ) { return grid ; } if ( scale == 0. ) { return grid ; } // //Compute missing data value. // int imax = ( int ) ( Math . pow ( 2 , nbits ) - 1 ) ; // //Retrieve data points from buffer. // int iword = 0 ; int ibit = 1 ; // 1 based bit position for ( int i = 0 ; i < kxky ; i ++ ) { // //    Get the integer from the buffer. // int jshft = nbits + ibit - 33 ; int idat = 0 ; idat = ( jshft < 0 ) ? idata [ iword ] >>> Math . abs ( jshft ) : idata [ iword ] << jshft ; idat = idat & imax ; // //    Check to see if packed integer overflows into next word. LOOK fishy bit operations // if ( jshft > 0 ) { jshft -= 32 ; int idat2 = 0 ; idat2 = idata [ iword + 1 ] >>> Math . abs ( jshft ) ; idat = idat | idat2 ; } // //    Compute value of word. // if ( ( idat == imax ) && misflg ) { grid [ i ] = RMISSD ; } else { grid [ i ] = ( qmin + idat * scale ) * scaleFactor ; } // //    Set location for next word. // ibit += nbits ; if ( ibit > 32 ) { ibit -= 32 ; iword ++ ; } /*\n            if (i < 25) {\n                System.out.println(\"grid[\"+i+\"]: \" + grid[i]);\n            }\n            */ } return grid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read packed Grib1 data using ucar . grib code [CODESPLIT] private float [ ] unpackGrib1Data ( int iiword , int nword , int kxky , int nbits , float ref , float scale , boolean miss , int decimalScale ) throws IOException { //System.out.println(\"decimal scale = \" + decimalScale); float [ ] values = new float [ kxky ] ; bitPos = 0 ; bitBuf = 0 ; next = 0 ; ch1 = 0 ; ch2 = 0 ; ch3 = 0 ; ch4 = 0 ; rf . seek ( getOffset ( iiword ) ) ; int idat ; // save a pow call if we can float scaleFactor = ( decimalScale == 0 ) ? 1.f : ( float ) Math . pow ( 10.0 , - decimalScale ) ; //float scaleFactor = (float) Math.pow(10.0, -decimalScale); for ( int i = 0 ; i < values . length ; i ++ ) { idat = bits2UInt ( nbits ) ; if ( miss && ( idat == IMISSD ) ) { values [ i ] = IMISSD ; } else { values [ i ] = ( ref + scale * idat ) * scaleFactor ; } /*\n            if (i < 25) {\n                System.out.println(\"values[\" + i + \"] = \" + values[i]);\n            }\n            */ } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read packed Grib2 data [CODESPLIT] private float [ ] unpackGrib2Data ( int iiword , int lendat , int [ ] iarray , float [ ] rarray ) throws IOException { long start = getOffset ( iiword ) ; rf . seek ( start ) ; Grib2Record gr = makeGribRecord ( rf , start ) ; float [ ] data = gr . readData ( rf ) ; if ( ( ( iarray [ 3 ] >> 6 ) & 1 ) == 0 ) { // -y scanning - flip data = gb2_ornt ( iarray [ 1 ] , iarray [ 2 ] , iarray [ 3 ] , data ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for GempakGridReader [CODESPLIT] private Grib2Record makeGribRecord ( RandomAccessFile raf , long start ) throws IOException { Grib2SectionIndicator is = new Grib2SectionIndicator ( start , 0 , 0 ) ; // apparently not in GEMPAK file (!) Grib2SectionIdentification ids = null ; Grib2SectionLocalUse lus = null ; Grib2SectionGridDefinition gds = null ; Grib2SectionProductDefinition pds = null ; Grib2SectionDataRepresentation drs = null ; Grib2SectionBitMap bms = null ; Grib2SectionData dataSection = null ; raf . seek ( start ) ; raf . order ( RandomAccessFile . BIG_ENDIAN ) ; int secLength = raf . readInt ( ) ; if ( secLength > 0 ) { ids = new Grib2SectionIdentification ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { lus = new Grib2SectionLocalUse ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { gds = new Grib2SectionGridDefinition ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { pds = new Grib2SectionProductDefinition ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { drs = new Grib2SectionDataRepresentation ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { bms = new Grib2SectionBitMap ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { dataSection = new Grib2SectionData ( raf ) ; if ( dataSection . getMsgLength ( ) > secLength ) // presumably corrupt throw new IllegalStateException ( \"Illegal Grib2SectionData Message Length\" ) ; } // LOOK - not dealing with repeated records return new Grib2Record ( null , is , ids , lus , gds , pds , drs , bms , dataSection , false , Grib2Index . ScanModeMissing ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out the navigation block so it looks something like this : <pre > GRID NAVIGATION : PROJECTION : LCC ANGLES : 25 . 0 - 95 . 0 25 . 0 GRID SIZE : 93 65 LL CORNER : 12 . 19 - 133 . 46 UR CORNER : 57 . 29 - 49 . 38 < / pre > [CODESPLIT] public void printNavBlock ( ) { StringBuilder buf = new StringBuilder ( \"GRID NAVIGATION:\" ) ; if ( navBlock != null ) { buf . append ( navBlock . toString ( ) ) ; } else { buf . append ( \"\\n\\tUNKNOWN GRID NAVIGATION\" ) ; } System . out . println ( buf . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out the analysis block so it looks something like this : [CODESPLIT] public void printAnalBlock ( ) { StringBuilder buf = new StringBuilder ( \"GRID ANALYSIS BLOCK:\" ) ; if ( analBlock != null ) { buf . append ( analBlock . toString ( ) ) ; } else { buf . append ( \"\\n\\tUNKNOWN ANALYSIS TYPE\" ) ; } System . out . println ( buf . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out the grids . [CODESPLIT] public void printGrids ( ) { List < GridRecord > gridList = gridIndex . getGridRecords ( ) ; if ( gridList == null ) return ; System . out . println ( \"  NUM       TIME1              TIME2           LEVL1 LEVL2  VCORD PARM\" ) ; for ( GridRecord aGridList : gridList ) { System . out . println ( aGridList ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List out the grid information ( aka GDINFO ) [CODESPLIT] public void showGridInfo ( boolean printGrids ) { List gridList = gridIndex . getGridRecords ( ) ; System . out . println ( \"\\nGRID FILE: \" + getFilename ( ) + \"\\n\" ) ; printNavBlock ( ) ; System . out . println ( \"\" ) ; printAnalBlock ( ) ; System . out . println ( \"\\nNumber of grids in file:  \" + gridList . size ( ) ) ; System . out . println ( \"\\nMaximum number of grids in file:  \" + dmLabel . kcol ) ; System . out . println ( \"\" ) ; if ( printGrids ) { printGrids ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gb2_ornt <p / > This function checks the fields scanning mode flags and re - orders the grid point values so that they traverse left to right for each row starting at the bottom row . <p / > gb2_ornt ( kx ky scan_mode ingrid fgrid iret ) <p / > Input parameters : kx int Number of columns ky int Number of rows scan_mode int GRIB2 scanning mode flag * ingrid float unpacked GRIB2 grid data <p / > Output parameters : * fgrid float Unpacked grid data * iret int Return code - 40 = scan mode not implemented <p / > Log : S . Gilbert 1 / 04 [CODESPLIT] private float [ ] gb2_ornt ( int kx , int ky , int scan_mode , float [ ] ingrid ) { float [ ] fgrid = new float [ ingrid . length ] ; int ibeg , jbeg , iinc , jinc , itmp ; int icnt , jcnt , kcnt , idxarr ; int idrct , jdrct , consec , boustr ; idrct = ( scan_mode >> 7 ) & 1 ; jdrct = ( scan_mode >> 6 ) & 1 ; consec = ( scan_mode >> 5 ) & 1 ; boustr = ( scan_mode >> 4 ) & 1 ; if ( idrct == 0 ) { ibeg = 0 ; iinc = 1 ; } else { ibeg = kx - 1 ; iinc = - 1 ; } if ( jdrct == 1 ) { jbeg = 0 ; jinc = 1 ; } else { jbeg = ky - 1 ; jinc = - 1 ; } kcnt = 0 ; if ( ( consec == 1 ) && ( boustr == 0 ) ) { /*  adjacent points in same column;  each column same direction  */ for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = ky * icnt + jcnt ; fgrid [ kcnt ] = ingrid [ idxarr ] ; kcnt ++ ; } } } else if ( ( consec == 0 ) && ( boustr == 0 ) ) { /*  adjacent points in same row;  each row same direction  */ for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = kx * jcnt + icnt ; fgrid [ kcnt ] = ingrid [ idxarr ] ; kcnt ++ ; } } } else if ( ( consec == 1 ) && ( boustr == 1 ) ) { /*  adjacent points in same column; each column alternates direction */ for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { itmp = jcnt ; if ( ( idrct == 1 ) && ( kx % 2 == 0 ) ) { itmp = ky - jcnt - 1 ; } for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = ky * icnt + itmp ; fgrid [ kcnt ] = ingrid [ idxarr ] ; itmp = ( itmp != jcnt ) ? jcnt : ky - jcnt - 1 ; /* toggle */ kcnt ++ ; } } } else if ( ( consec == 0 ) && ( boustr == 1 ) ) { /*  adjacent points in same row;  each row alternates direction  */ if ( jdrct == 0 ) { if ( ( idrct == 0 ) && ( ky % 2 == 0 ) ) { ibeg = kx - 1 ; iinc = - 1 ; } if ( ( idrct == 1 ) && ( ky % 2 == 0 ) ) { ibeg = 0 ; iinc = 1 ; } } for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = kx * jcnt + icnt ; fgrid [ kcnt ] = ingrid [ idxarr ] ; kcnt ++ ; } ibeg = ( ibeg != 0 ) ? 0 : kx - 1 ; /* toggle */ iinc = ( iinc != 1 ) ? 1 : - 1 ; /* toggle */ } } //else {          logically dead code //fgrid = ingrid; //} return fgrid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert bits ( nb ) to Unsigned Int . [CODESPLIT] private int bits2UInt ( int nb ) throws IOException { int bitsLeft = nb ; int result = 0 ; if ( bitPos == 0 ) { //bitBuf = raf.read(); getNextByte ( ) ; bitPos = 8 ; } while ( true ) { int shift = bitsLeft - bitPos ; if ( shift > 0 ) { // Consume the entire buffer result |= bitBuf << shift ; bitsLeft -= bitPos ; // Get the next byte from the RandomAccessFile //bitBuf = raf.read(); getNextByte ( ) ; bitPos = 8 ; } else { // Consume a portion of the buffer result |= bitBuf >> - shift ; bitPos -= bitsLeft ; bitBuf &= 0xff >> ( 8 - bitPos ) ; // mask off consumed bits return result ; } } // end while }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the next byte [CODESPLIT] private void getNextByte ( ) throws IOException { if ( ! needToSwap ) { // Get the next byte from the RandomAccessFile bitBuf = rf . read ( ) ; } else { if ( next == 3 ) { bitBuf = ch3 ; } else if ( next == 2 ) { bitBuf = ch2 ; } else if ( next == 1 ) { bitBuf = ch1 ; } else { ch1 = rf . read ( ) ; ch2 = rf . read ( ) ; ch3 = rf . read ( ) ; ch4 = rf . read ( ) ; bitBuf = ch4 ; next = 4 ; } next -- ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a variable to the container . [CODESPLIT] public void addVariable ( BaseType v ) { vals = v . newPrimitiveVector ( ) ; setClearName ( v . getClearName ( ) ) ; v . setParent ( this ) ; setContainerVar ( v ) ; // save v for cloning\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coverity [ CALL_SUPER ] [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType\r // and all of the different signatures of printDecl() in BaseType\r // lead to one signature, we must be careful to override that\r // SAME signature here. That way all calls to printDecl() for\r // this object lead to this implementation.\r //os.println(\"DVector.printDecl()\");\r os . print ( space + getTypeName ( ) ) ; vals . printDecl ( os , \" \" , print_semi , constrained ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( print_decl_p ) { printDecl ( os , space , false ) ; os . print ( \" = \" ) ; } os . print ( \"{ \" ) ; vals . printVal ( os , \"\" ) ; if ( print_decl_p ) os . println ( \"};\" ) ; else os . print ( \"}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { // Because arrays of primitive types (ie int32, float32, byte, etc) are\r // handled in the C++ core using the XDR package we must read the\r // length twice for those types. For BaseType vectors, we should read\r // it only once. This is in effect a work around for a bug in the C++\r // core as the C++ core does not consume 2 length values for the\r // BaseType vectors. Bummer...\r int length ; length = source . readInt ( ) ; if ( ! ( vals instanceof BaseTypePrimitiveVector ) ) { // because both XDR and OPeNDAP write the length, we must read it twice\r int length2 = source . readInt ( ) ; //LogStream.out.println(\"array1 length read: \"+getName()+\" \"+length+ \" -- \"+length2);\r //LogStream.out.println(\"  array type = : \"+vals.getClass().getName());\r // QC the second length\r if ( length != length2 ) { throw new DataReadException ( \"Inconsistent array length read: \" + length + \" != \" + length2 ) ; } } /* else {\r\n          LogStream.dbg.println(\"array2 length read: \"+getName()+\" \"+length);\r\n          LogStream.dbg.println(\"  array type = : \"+vals.getClass().getName());\r\n        } */ if ( length < 0 ) throw new DataReadException ( \"Negative array length read.\" ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 8 ) ; vals . setLength ( length ) ; vals . deserialize ( source , sv , statusUI ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { // Because arrays of primitive types (ie int32, float32, byte, etc) are\r // handled in the C++ core using the XDR package we must write the\r // length twice for those types. For BaseType vectors, we should write\r // it only once. This is in effect a work around for a bug in the C++\r // core as the C++ core does not consume 2 length values for thge\r // BaseType vectors. Bummer...\r int length = vals . getLength ( ) ; sink . writeInt ( length ) ; if ( ! ( vals instanceof BaseTypePrimitiveVector ) ) { // because both XDR and OPeNDAP write the length, we must write it twice\r sink . writeInt ( length ) ; } vals . externalize ( sink ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Vector< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DVector v = ( DVector ) super . cloneDAG ( map ) ; v . vals = ( PrimitiveVector ) cloneDAG ( map , vals ) ; // clone the container variable\r v . containedvar = ( BaseType ) cloneDAG ( map , containedvar ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Calendar date from fields . Uses UTZ time zone [CODESPLIT] public static CalendarDate of ( Calendar cal , int year , int monthOfYear , int dayOfMonth , int hourOfDay , int minuteOfHour , int secondOfMinute ) { Chronology base = Calendar . getChronology ( cal ) ; /* if (base == null)\r\n      base = ISOChronology.getInstanceUTC(); // already in UTC\r\n    else\r\n      base = ZonedChronology.getInstance( base, DateTimeZone.UTC); // otherwise wrap it to be in UTC  */ DateTime dt = new DateTime ( year , monthOfYear , dayOfMonth , hourOfDay , minuteOfHour , secondOfMinute , base ) ; if ( ! Calendar . isDefaultChronology ( cal ) ) dt = dt . withChronology ( Calendar . getChronology ( cal ) ) ; dt = dt . withZone ( DateTimeZone . UTC ) ; return new CalendarDate ( cal , dt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create CalendarDate from a java . util . Date . Uses standard Calendar . [CODESPLIT] public static CalendarDate of ( java . util . Date date ) { DateTime dt = new DateTime ( date , DateTimeZone . UTC ) ; return new CalendarDate ( null , dt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create CalendarDate from msecs since epoch Uses standard Calendar . [CODESPLIT] public static CalendarDate of ( long msecs ) { // Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z using ISOChronology in the specified time zone.\r DateTime dt = new DateTime ( msecs , DateTimeZone . UTC ) ; return new CalendarDate ( null , dt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create CalendarDate from msecs since epoch Uses the given Calendar . [CODESPLIT] public static CalendarDate of ( Calendar cal , long msecs ) { Chronology base = Calendar . getChronology ( cal ) ; DateTime dt = new DateTime ( msecs , base ) ; return new CalendarDate ( cal , dt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get CalendarDate from ISO date string [CODESPLIT] @ Nullable public static CalendarDate parseUdunitsOrIso ( String calendarName , String isoOrUdunits ) { CalendarDate result ; try { result = parseISOformat ( calendarName , isoOrUdunits ) ; } catch ( Exception e ) { try { result = parseUdunits ( calendarName , isoOrUdunits ) ; } catch ( Exception e2 ) { return null ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get CalendarDate from ISO date string [CODESPLIT] public static CalendarDate parseISOformat ( String calendarName , String isoDateString ) { Calendar cal = Calendar . get ( calendarName ) ; if ( cal == null ) cal = Calendar . getDefault ( ) ; return CalendarDateFormatter . isoStringToCalendarDate ( cal , isoDateString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get CalendarDate from udunit date string [CODESPLIT] public static CalendarDate parseUdunits ( String calendarName , String udunits ) { int pos = udunits . indexOf ( ' ' ) ; if ( pos < 0 ) return null ; String valString = udunits . substring ( 0 , pos ) . trim ( ) ; String unitString = udunits . substring ( pos + 1 ) . trim ( ) ; CalendarDateUnit cdu = CalendarDateUnit . of ( calendarName , unitString ) ; double val = Double . parseDouble ( valString ) ; return cdu . makeCalendarDate ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Millisec ( PeriodType . millis () ) Second ( PeriodType . seconds () ) Minute ( PeriodType . minutes () ) Hour ( PeriodType . hours () ) Day ( PeriodType . days () ) Month ( PeriodType . months () ) Year ( PeriodType . years () ) [CODESPLIT] public int getFieldValue ( CalendarPeriod . Field fld ) { switch ( fld ) { case Day : return dateTime . get ( DateTimeFieldType . dayOfMonth ( ) ) ; case Hour : return dateTime . get ( DateTimeFieldType . hourOfDay ( ) ) ; case Millisec : return dateTime . get ( DateTimeFieldType . millisOfSecond ( ) ) ; case Minute : return dateTime . get ( DateTimeFieldType . minuteOfHour ( ) ) ; case Month : return dateTime . get ( DateTimeFieldType . monthOfYear ( ) ) ; case Second : return dateTime . get ( DateTimeFieldType . secondOfMinute ( ) ) ; case Year : return dateTime . get ( DateTimeFieldType . year ( ) ) ; } throw new IllegalArgumentException ( \"unimplemented \" + fld ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "calendar date field [CODESPLIT] public CalendarDate add ( CalendarPeriod period ) { switch ( period . getField ( ) ) { case Millisec : return new CalendarDate ( cal , dateTime . plusMillis ( period . getValue ( ) ) ) ; case Second : return new CalendarDate ( cal , dateTime . plusSeconds ( period . getValue ( ) ) ) ; case Minute : return new CalendarDate ( cal , dateTime . plusMinutes ( period . getValue ( ) ) ) ; case Hour : return new CalendarDate ( cal , dateTime . plusHours ( period . getValue ( ) ) ) ; case Day : return new CalendarDate ( cal , dateTime . plusDays ( period . getValue ( ) ) ) ; case Month : return new CalendarDate ( cal , dateTime . plusMonths ( period . getValue ( ) ) ) ; case Year : return new CalendarDate ( cal , dateTime . plusYears ( period . getValue ( ) ) ) ; } throw new UnsupportedOperationException ( \"period units = \" + period ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "calendar date field [CODESPLIT] public CalendarDate subtract ( CalendarPeriod period ) { switch ( period . getField ( ) ) { case Millisec : return new CalendarDate ( cal , dateTime . minusMillis ( period . getValue ( ) ) ) ; case Second : return new CalendarDate ( cal , dateTime . minusSeconds ( period . getValue ( ) ) ) ; case Minute : return new CalendarDate ( cal , dateTime . minusMinutes ( period . getValue ( ) ) ) ; case Hour : return new CalendarDate ( cal , dateTime . minusHours ( period . getValue ( ) ) ) ; case Day : return new CalendarDate ( cal , dateTime . minusDays ( period . getValue ( ) ) ) ; case Month : return new CalendarDate ( cal , dateTime . minusMonths ( period . getValue ( ) ) ) ; case Year : return new CalendarDate ( cal , dateTime . minusYears ( period . getValue ( ) ) ) ; } throw new UnsupportedOperationException ( \"period units = \" + period ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "truncate the CalendarDate by zeroing all the fields that are less than the field . So 2013 - 03 - 01T19 : 30 becomes 2013 - 03 - 01T00 : 00 if the field is day [CODESPLIT] public CalendarDate truncate ( CalendarPeriod . Field fld ) { switch ( fld ) { case Minute : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , dateTime . getDayOfMonth ( ) , dateTime . getHourOfDay ( ) , dateTime . getMinuteOfHour ( ) , 0 ) ; case Hour : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , dateTime . getDayOfMonth ( ) , dateTime . getHourOfDay ( ) , 0 , 0 ) ; case Day : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , dateTime . getDayOfMonth ( ) , 0 , 0 , 0 ) ; case Month : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , 1 , 0 , 0 , 0 ) ; case Year : return CalendarDate . of ( cal , dateTime . getYear ( ) , 1 , 1 , 0 , 0 , 0 ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get difference between two calendar dates in given Field units [CODESPLIT] public long getDifference ( CalendarDate o , CalendarPeriod . Field fld ) { switch ( fld ) { case Millisec : return getDifferenceInMsecs ( o ) ; case Second : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_SECOND ) ; case Minute : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_MINUTE ) ; case Hour : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_HOUR ) ; case Day : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_DAY ) ; case Month : int tmonth = getFieldValue ( CalendarPeriod . Field . Month ) ; int omonth = o . getFieldValue ( CalendarPeriod . Field . Month ) ; int years = ( int ) this . getDifference ( o , CalendarPeriod . Field . Year ) ; return tmonth - omonth + 12 * years ; case Year : int tyear = getFieldValue ( CalendarPeriod . Field . Year ) ; int oyear = o . getFieldValue ( CalendarPeriod . Field . Year ) ; return tyear - oyear ; } return dateTime . getMillis ( ) - o . dateTime . getMillis ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package access [CODESPLIT] Map < Variable , Array > create ( ) throws DapException { // iterate over the variables represented in the DSP List < DapVariable > topvars = this . dmr . getTopVariables ( ) ; Map < Variable , Array > map = null ; for ( DapVariable var : topvars ) { DataCursor cursor = this . dsp . getVariableData ( var ) ; Array array = createVar ( cursor ) ; Variable cdmvar = ( Variable ) nodemap . get ( var ) ; arraymap . put ( cdmvar , array ) ; } return this . arraymap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an Atomic Valued variable . [CODESPLIT] protected CDMArrayAtomic createAtomicVar ( DataCursor data ) throws DapException { CDMArrayAtomic array = new CDMArrayAtomic ( data ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an array of structures . WARNING : the underlying CDM code ( esp . NetcdfDataset ) apparently does not support nested structure arrays ; so this code may throw an exception . [CODESPLIT] protected CDMArrayStructure createStructure ( DataCursor data ) throws DapException { CDMArrayStructure arraystruct = new CDMArrayStructure ( this . cdmroot , data ) ; DapVariable var = ( DapVariable ) data . getTemplate ( ) ; DapStructure struct = ( DapStructure ) var . getBaseType ( ) ; int nmembers = struct . getFields ( ) . size ( ) ; List < DapDimension > dimset = var . getDimensions ( ) ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; long offset = index . index ( ) ; DataCursor [ ] cursors = ( DataCursor [ ] ) data . read ( index ) ; DataCursor ithelement = cursors [ 0 ] ; for ( int f = 0 ; f < nmembers ; f ++ ) { DataCursor dc = ( DataCursor ) ithelement . readField ( f ) ; Array afield = createVar ( dc ) ; arraystruct . add ( offset , f , afield ) ; } } return arraystruct ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a sequence . WARNING : the underlying CDM code ( esp . NetcdfDataset ) apparently does not support nested sequence arrays . [CODESPLIT] protected CDMArraySequence createSequence ( DataCursor data ) throws DapException { CDMArraySequence arrayseq = new CDMArraySequence ( this . cdmroot , data ) ; DapVariable var = ( DapVariable ) data . getTemplate ( ) ; DapSequence template = ( DapSequence ) var . getBaseType ( ) ; List < DapDimension > dimset = var . getDimensions ( ) ; long dimsize = DapUtil . dimProduct ( dimset ) ; int nfields = template . getFields ( ) . size ( ) ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) ) ; while ( odom . hasNext ( ) ) { odom . next ( ) ; DataCursor seq = ( ( DataCursor [ ] ) data . read ( odom . indices ( ) ) ) [ 0 ] ; long nrecords = seq . getRecordCount ( ) ; for ( int r = 0 ; r < nrecords ; r ++ ) { DataCursor rec = seq . readRecord ( r ) ; for ( int f = 0 ; f < nfields ; f ++ ) { DataCursor dc = rec . readField ( f ) ; Array afield = createVar ( dc ) ; arrayseq . add ( r , f , afield ) ; } } } return arrayseq ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked once on first request so that everything is available especially Spring stuff . [CODESPLIT] public void doonce ( HttpServletRequest req ) throws SendError { if ( once ) return ; super . initOnce ( req ) ; if ( this . downloaddir == null ) throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , \"Download disabled\" ) ; this . downloaddirname = new File ( this . downloaddir ) . getName ( ) ; // Get the download form File downform = null ; downform = tdsContext . getDownloadForm ( ) ; if ( downform == null ) { // Look in WEB-INF directory File root = tdsContext . getServletRootDirectory ( ) ; downform = new File ( root , DEFAULTDOWNLOADFORM ) ; } try { this . downloadform = loadForm ( downform ) ; } catch ( IOException ioe ) { throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup for each request [CODESPLIT] public void setup ( HttpServletRequest req , HttpServletResponse resp ) throws SendError { this . req = req ; this . res = resp ; if ( ! once ) doonce ( req ) ; // Parse any query parameters try { this . params = new DownloadParameters ( req ) ; } catch ( IOException ioe ) { throw new SendError ( res . SC_BAD_REQUEST , ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Controller entry point ( s ) [CODESPLIT] @ RequestMapping ( value = \"**\" , method = RequestMethod . GET ) public void doGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException { try { setup ( req , res ) ; String sresult = null ; switch ( this . params . command ) { case DOWNLOAD : try { String fulltargetpath = download ( ) ; if ( this . params . fromform ) { sendForm ( \"Download succeeded: result file: \" + fulltargetpath ) ; } else { Map < String , String > result = new HashMap <> ( ) ; result . put ( \"download\" , fulltargetpath ) ; sresult = mapToString ( result , true , \"download\" ) ; sendOK ( sresult ) ; } } catch ( SendError se ) { if ( this . params . fromform ) { // Send back the download form with error msg sendForm ( \"Download failed: \" + se . getMessage ( ) ) ; } else throw se ; } break ; case INQUIRE : sresult = inquire ( ) ; // Send back the inquiry answers sendOK ( sresult ) ; break ; case NONE : // Use form-based download // Send back the download form sendForm ( \"No files downloaded\" ) ; break ; } } catch ( SendError se ) { sendError ( se ) ; } catch ( Exception e ) { String msg = getStackTrace ( e ) ; sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , msg , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reifiers [CODESPLIT] protected void makeNetcdf4 ( NetcdfFile ncfile , String target ) throws IOException { try { CancelTaskImpl cancel = new CancelTaskImpl ( ) ; FileWriter2 writer = new FileWriter2 ( ncfile , target , NetcdfFileWriter . Version . netcdf4 , chunking ) ; writer . getNetcdfFileWriter ( ) . setLargeFile ( true ) ; NetcdfFile ncfileOut = writer . write ( cancel ) ; if ( ncfileOut != null ) ncfileOut . close ( ) ; cancel . setDone ( true ) ; } catch ( IOException ioe ) { throw ioe ; // temporary } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a typical string insert backslashes before and \\\\ characters and control characters . [CODESPLIT] static protected String escapeString ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; switch ( c ) { case ' ' : buf . append ( \"\\\\\\\"\" ) ; break ; case ' ' : buf . append ( \"\\\\\\\\\" ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; default : if ( c < ' ' ) buf . append ( String . format ( \"\\\\x%02x\" , ( c & 0xff ) ) ) ; else buf . append ( ( char ) c ) ; break ; } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// [CODESPLIT] @ Override protected String buildForm ( String msg ) { StringBuilder svc = new StringBuilder ( ) ; svc . append ( this . server ) ; svc . append ( \"/\" ) ; svc . append ( this . threddsname ) ; String form = String . format ( this . downloadform , svc . toString ( ) , msg ) ; return form ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a list of ucar . ma2 . Range to a list of Slice More or less the inverst of create CDMRanges [CODESPLIT] static public List < Slice > createSlices ( List < Range > rangelist ) throws dap4 . core . util . DapException { List < Slice > slices = new ArrayList < Slice > ( rangelist . size ( ) ) ; for ( int i = 0 ; i < rangelist . size ( ) ; i ++ ) { Range r = rangelist . get ( i ) ; // r does not store last int stride = r . stride ( ) ; int first = r . first ( ) ; int n = r . length ( ) ; int stop = first + ( n * stride ) ; Slice cer = new Slice ( first , stop - 1 , stride ) ; slices . add ( cer ) ; } return slices ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test a List<Range > against a List<DapDimension > to see if the range list represents the whole set of dimensions within the specified indices . [CODESPLIT] static public boolean isWhole ( List < Range > rangelist , List < DapDimension > dimset , int start , int stop ) throws dap4 . core . util . DapException { int rsize = ( rangelist == null ? 0 : rangelist . size ( ) ) ; if ( rsize != dimset . size ( ) ) throw new dap4 . core . util . DapException ( \"range/dimset rank mismatch\" ) ; if ( rsize == 0 ) return true ; if ( start < 0 || stop < start || stop > rsize ) throw new dap4 . core . util . DapException ( \"Invalid start/stop indices\" ) ; for ( int i = start ; i < stop ; i ++ ) { Range r = rangelist . get ( i ) ; DapDimension d = dimset . get ( i ) ; if ( r . stride ( ) != 1 || r . first ( ) != 0 || r . length ( ) != d . getSize ( ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test a List<Range > against a List<Slice > to see if the range list is whole wrt the slices [CODESPLIT] static public boolean isWhole ( List < Range > rangelist , List < Slice > slices ) throws dap4 . core . util . DapException { if ( rangelist . size ( ) != slices . size ( ) ) return false ; for ( int i = 0 ; i < rangelist . size ( ) ; i ++ ) { Range r = rangelist . get ( i ) ; Slice slice = slices . get ( i ) ; if ( r . stride ( ) != 1 || r . first ( ) != 0 || r . length ( ) != slice . getCount ( ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test a List<Range > against the CDM variable s dimensions to see if the range list is whole wrt the dimensions [CODESPLIT] static public boolean isWhole ( List < Range > rangelist , Variable var ) throws dap4 . core . util . DapException { List < Dimension > dimset = var . getDimensions ( ) ; if ( rangelist . size ( ) != dimset . size ( ) ) return false ; for ( int i = 0 ; i < rangelist . size ( ) ; i ++ ) { Range r = rangelist . get ( i ) ; Dimension dim = dimset . get ( i ) ; if ( r . stride ( ) != 1 || r . first ( ) != 0 || r . length ( ) != dim . getLength ( ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NetcdfDataset can wrap a NetcdfFile . Goal of this procedure is to get down to the lowest level NetcdfFile instance . [CODESPLIT] static public NetcdfFile unwrapfile ( NetcdfFile file ) { for ( ; ; ) { if ( file instanceof NetcdfDataset ) { NetcdfDataset ds = ( NetcdfDataset ) file ; file = ds . getReferencedFile ( ) ; if ( file == null ) break ; } else break ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if any dimension is variable length [CODESPLIT] static public boolean containsVLEN ( List < Dimension > dimset ) { if ( dimset == null ) return false ; for ( Dimension dim : dimset ) { if ( dim . isVariableLength ( ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the shape inferred from a set of slices . Effective means that any trailing vlen will be ignored . [CODESPLIT] static public int [ ] computeEffectiveShape ( List < DapDimension > dimset ) { if ( dimset == null || dimset . size ( ) == 0 ) return new int [ 0 ] ; int effectiverank = dimset . size ( ) ; int [ ] shape = new int [ effectiverank ] ; for ( int i = 0 ; i < effectiverank ; i ++ ) { shape [ i ] = ( int ) dimset . get ( i ) . getSize ( ) ; } return shape ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract as a long value from a ( presumably ) atomic typed array of values ; dataset position is presumed correct . [CODESPLIT] static public long extractLongValue ( TypeSort atomtype , DataCursor dataset , Index index ) throws DapException { Object result ; result = dataset . read ( index ) ; long lvalue = CDMTypeFcns . extract ( atomtype , result ) ; return lvalue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract as a double value from a ( presumably ) atomic typed array of values ; dataset position is presumed correct . [CODESPLIT] static public double extractDoubleValue ( TypeSort atomtype , DataCursor dataset , Index index ) throws DapException { Object result ; result = dataset . read ( index ) ; double dvalue = 0.0 ; if ( atomtype . isIntegerType ( ) || atomtype . isEnumType ( ) ) { long lvalue = extractLongValue ( atomtype , dataset , index ) ; dvalue = ( double ) lvalue ; } else if ( atomtype == TypeSort . Float32 ) { dvalue = ( double ) ( ( Float ) result ) . floatValue ( ) ; } else if ( atomtype == TypeSort . Float64 ) { dvalue = ( ( Double ) result ) . doubleValue ( ) ; } else throw new ForbiddenConversionException ( ) ; return dvalue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an array of one type of values to another type [CODESPLIT] static public Object convertVector ( DapType dsttype , DapType srctype , Object src ) { int i ; TypeSort srcatomtype = srctype . getAtomicType ( ) ; TypeSort dstatomtype = dsttype . getAtomicType ( ) ; if ( srcatomtype == dstatomtype ) { return src ; } if ( srcatomtype . isIntegerType ( ) && TypeSort . getSignedVersion ( srcatomtype ) == TypeSort . getSignedVersion ( dstatomtype ) ) return src ; Object result = CDMTypeFcns . convert ( dstatomtype , srcatomtype , src ) ; if ( result == null ) throw new ForbiddenConversionException ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * static public ucar . ma2 . Array arraySlice ( ucar . ma2 . Array array Section section ) throws DapException { Case it out . if ( !dapvar . getBaseType () . isStructType () ) { // = > Atomic type if ( dapvar . isTopLevel () ) { Simplest case : use createview but watch out for final VLEN List<Range > ranges = section . getRanges () ; try { if ( CDMUtil . hasVLEN ( ranges )) return array . section ( ranges . subList ( 0 ranges . size () - 2 )) ; else return array . section ( ranges ) ; } catch ( InvalidRangeException ire ) { throw new DapException ( ire ) ; } } else throw new UnsupportedOperationException () ; // same as other cdm } else { // struct type assert ( array instanceof CDMArrayStructure ) ; CDMArrayStructure struct = ( CDMArrayStructure ) array ; if ( dapvar . isTopLevel () ) { Build a new ArrayStructure containing the relevant instances . int [] shape = section . getShape () ; StructureMembers sm = new StructureMembers ( struct . getStructureMembers () ) ; ArrayStructureMA slice = new ArrayStructureMA ( sm shape ) ; CDMOdometer odom = new CDMOdometer ( dapvar . getDimensions () section . getRanges () ) ; Compute the number of structuredata instances we need long totalsize = section . computeSize () ; List<StructureMembers . Member > mlist = sm . getMembers () ; StructureData [] newdata = new StructureData [ ( int ) totalsize ] ; for ( int i = 0 ; odom . hasNext () ; odom . next () i ++ ) { long recno = odom . index () ; StructureDataW clone = new StructureDataW ( sm ) ; newdata [ i ] = clone ; StructureData record = struct . getStructureData (( int ) recno ) ; for ( int j = 0 ; j < mlist . size () ; j ++ ) { StructureMembers . Member m = mlist . get ( j ) ; clone . setMemberData ( m record . getArray ( m )) ; } } return slice ; } else throw new UnsupportedOperationException () ; // same as other cdm } } [CODESPLIT] static public String getChecksumString ( byte [ ] checksum ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < checksum . length ; i ++ ) { byte b = checksum [ i ] ; buf . append ( hexchars . charAt ( b >> 4 ) ) ; buf . append ( hexchars . charAt ( b & 0xF ) ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a Section + variable to a constraint <p > <p > static public View sectionToView ( CDMDSP dsp Variable v Section section ) throws DapException { if ( section == null || section . getRank () == 0 ) return null ; // Get the corresponding DapNode DapVariable dv = ( DapVariable ) dsp . getNode () . get ( v ) ; if ( dv == null ) throw new DapException ( Variable has no corresponding dap node : + v . getFullName () ) ; // Get the structure path wrt DapDataset for dv // and use path plus the Section to construct a constraint List<DapVariable > structpath = DapUtil . getStructurePath ( dv ) ; List<Range > ranges = section . getRanges () ; View view = new View ( dmr ) ; int next = 0 ; for ( int i = 0 ; i < structpath . size () ; i ++ ) { dv = structpath . get ( i ) ; int rank = dv . getRank () ; ViewVariable vv = new ViewVariable ( dv ) ; List<Slice > slices = new ArrayList<Slice > ( rank ) ; for ( int j = 0 ; j < rank ; j ++ next ++ ) { if ( next > = ranges . size () ) throw new DapException ( Range :: Rank mismatch ) ; Range range = ranges . get ( next ) ; Slice slice = new Slice ( range . first () range . last () range . stride () ) . validate () ; slices . add ( slice ) ; } vv . setSlices ( slices ) ; view . put ( dv vv ) ; } view . validate ( View . EXPAND ) ; return view ; } [CODESPLIT] static public List < Range > dimsetToRanges ( List < DapDimension > dimset ) throws dap4 . core . util . DapException { if ( dimset == null ) return null ; List < Range > ranges = new ArrayList <> ( ) ; for ( int i = 0 ; i < dimset . size ( ) ; i ++ ) { DapDimension dim = dimset . get ( i ) ; try { Range r = new Range ( dim . getShortName ( ) , 0 , ( int ) dim . getSize ( ) - 1 , 1 ) ; ranges . add ( r ) ; } catch ( InvalidRangeException ire ) { throw new dap4 . core . util . DapException ( ire ) ; } } return ranges ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert given value of this unit to the new unit . <em > NOTE : the current value of this unit ignored the given value is used instead . This is different than ucar . units or SimpleUnit . < / em > [CODESPLIT] public double convertTo ( double value , TimeUnit outputUnit ) throws ConversionException { return uu . convertTo ( value , outputUnit . uu ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the time amount to the given Date return a new Date . [CODESPLIT] public Date add ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . SECOND , ( int ) getValueInSeconds ( ) ) ; return cal . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiplies this unit by another unit . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { return that instanceof ScaledUnit ? new ScaledUnit ( getScale ( ) * ( ( ScaledUnit ) that ) . getScale ( ) , getUnit ( ) . multiplyBy ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( getScale ( ) , getUnit ( ) . multiplyBy ( that ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divides this unit by another unit . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit ( getScale ( ) / ( ( ScaledUnit ) that ) . getScale ( ) , getUnit ( ) . divideBy ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( getScale ( ) , getUnit ( ) . divideBy ( that ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divides this unit into another unit . [CODESPLIT] @ Override protected Unit myDivideInto ( final Unit that ) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit ( ( ( ScaledUnit ) that ) . getScale ( ) / getScale ( ) , getUnit ( ) . divideInto ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( 1 / getScale ( ) , getUnit ( ) . divideInto ( that ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Raises this unit to a power . [CODESPLIT] @ Override protected Unit myRaiseTo ( final int power ) throws RaiseException { return new ScaledUnit ( Math . pow ( getScale ( ) , power ) , getUnit ( ) . raiseTo ( power ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a numeric value from this unit to the underlying derived unit . [CODESPLIT] public double toDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) _unit ) . toDerivedUnit ( amount * getScale ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts numeric values from this unit to the underlying derived unit . [CODESPLIT] public float [ ] toDerivedUnit ( final float [ ] input , final float [ ] output ) throws ConversionException { final float scale = ( float ) getScale ( ) ; for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] = input [ i ] * scale ; } if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . toDerivedUnit ( output , output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a numeric value from the underlying derived unit to this unit . [CODESPLIT] public double fromDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( getDerivedUnit ( ) , this ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . fromDerivedUnit ( amount ) / getScale ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the canonical string representation of the unit . [CODESPLIT] public String getCanonicalString ( ) { return DerivedUnitImpl . DIMENSIONLESS . equals ( _unit ) ? Double . toString ( getScale ( ) ) : Double . toString ( getScale ( ) ) + \" \" + _unit . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final BaseUnit meter = BaseUnit . getOrCreate ( UnitName . newUnitName ( \"meter\" , null , \"m\" ) , BaseQuantity . LENGTH ) ; final ScaledUnit nauticalMile = new ScaledUnit ( 1852f , meter ) ; System . out . println ( \"nauticalMile.getUnit().equals(meter)=\" + nauticalMile . getUnit ( ) . equals ( meter ) ) ; final ScaledUnit nauticalMileMeter = ( ScaledUnit ) nauticalMile . multiplyBy ( meter ) ; System . out . println ( \"nauticalMileMeter.divideBy(nauticalMile)=\" + nauticalMileMeter . divideBy ( nauticalMile ) ) ; System . out . println ( \"meter.divideBy(nauticalMile)=\" + meter . divideBy ( nauticalMile ) ) ; System . out . println ( \"nauticalMile.raiseTo(2)=\" + nauticalMile . raiseTo ( 2 ) ) ; System . out . println ( \"nauticalMile.toDerivedUnit(1.)=\" + nauticalMile . toDerivedUnit ( 1. ) ) ; System . out . println ( \"nauticalMile.toDerivedUnit(new float[]{1,2,3}, new float[3])[1]=\" + nauticalMile . toDerivedUnit ( new float [ ] { 1 , 2 , 3 } , new float [ 3 ] ) [ 1 ] ) ; System . out . println ( \"nauticalMile.fromDerivedUnit(1852.)=\" + nauticalMile . fromDerivedUnit ( 1852. ) ) ; System . out . println ( \"nauticalMile.fromDerivedUnit(new float[]{1852},new float[1])[0]=\" + nauticalMile . fromDerivedUnit ( new float [ ] { 1852 } , new float [ 1 ] ) [ 0 ] ) ; System . out . println ( \"nauticalMile.equals(nauticalMile)=\" + nauticalMile . equals ( nauticalMile ) ) ; final ScaledUnit nautical2Mile = new ScaledUnit ( 2 , nauticalMile ) ; System . out . println ( \"nauticalMile.equals(nautical2Mile)=\" + nauticalMile . equals ( nautical2Mile ) ) ; System . out . println ( \"nauticalMile.isDimensionless()=\" + nauticalMile . isDimensionless ( ) ) ; final BaseUnit radian = BaseUnit . getOrCreate ( UnitName . newUnitName ( \"radian\" , null , \"rad\" ) , BaseQuantity . PLANE_ANGLE ) ; final ScaledUnit degree = new ScaledUnit ( 3.14159 / 180 , radian ) ; System . out . println ( \"degree.isDimensionless()=\" + degree . isDimensionless ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the section of data described by want [CODESPLIT] public Array readData ( SectionIterable want ) throws IOException , InvalidRangeException { if ( vindex instanceof PartitionCollectionImmutable . VariableIndexPartitioned ) return readDataFromPartition ( ( PartitionCollectionImmutable . VariableIndexPartitioned ) vindex , want ) ; else return readDataFromCollection ( vindex , want ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * SectionIterable iterates over the source indexes corresponding to vindex s SparseArray . IOSP : works because variable coordinate corresponds 1 - 1 to Grib Coordinate . GribCoverage : must translate coordinates to Grib Coordinate index . want . getShape () indicates the result Array shape . SectionIterable . next ( int [] index ) is not used here . [CODESPLIT] private Array readDataFromCollection ( GribCollectionImmutable . VariableIndex vindex , SectionIterable want ) throws IOException { // first time, read records and keep in memory vindex . readRecords ( ) ; int rank = want . getRank ( ) ; int sectionLen = rank - 2 ; // all but x, y SectionIterable sectionWanted = want . subSection ( 0 , sectionLen ) ; // assert sectionLen == vindex.getRank(); LOOK true or false ?? // collect all the records that need to be read int resultIndex = 0 ; for ( int sourceIndex : sectionWanted ) { // addRecord(sourceIndex, count++); GribCollectionImmutable . Record record = vindex . getRecordAt ( sourceIndex ) ; if ( Grib . debugRead ) logger . debug ( \"GribIosp debugRead sourceIndex=%d resultIndex=%d record is null=%s%n\" , sourceIndex , resultIndex , record == null ) ; if ( record != null ) records . add ( new DataRecord ( resultIndex , record , vindex . group . getGdsHorizCoordSys ( ) ) ) ; resultIndex ++ ; } // sort by file and position, then read DataReceiverIF dataReceiver = new DataReceiver ( want . getShape ( ) , want . getRange ( rank - 2 ) , want . getRange ( rank - 1 ) ) ; read ( dataReceiver ) ; return dataReceiver . getArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Iterates using SectionIterable . next ( int [] index ) . The work of translating that down into partition heirarchy and finally to a GC is all in VariableIndexPartitioned . getDataRecord ( int [] index ) want . getShape () indicates the result Array shape . [CODESPLIT] private Array readDataFromPartition ( PartitionCollectionImmutable . VariableIndexPartitioned vindexP , SectionIterable section ) throws IOException { int rank = section . getRank ( ) ; SectionIterable sectionWanted = section . subSection ( 0 , rank - 2 ) ; // all but x, y SectionIterable . SectionIterator iterWanted = sectionWanted . getIterator ( ) ; // iterator over wanted indices in vindexP int [ ] indexWanted = new int [ rank - 2 ] ; // place to put the iterator result int [ ] useIndex = indexWanted ; // collect all the records that need to be read int resultPos = 0 ; while ( iterWanted . hasNext ( ) ) { iterWanted . next ( indexWanted ) ; // returns the vindexP index in indexWanted array // for MRUTP, must munge the index here (not in vindexP.getDataRecord, because its recursive if ( vindexP . getType ( ) == GribCollectionImmutable . Type . MRUTP ) { // find the partition from getRuntimeIdxFromMrutpTimeIndex CoordinateTime2D time2D = ( CoordinateTime2D ) vindexP . getCoordinateTime ( ) ; assert time2D != null ; int [ ] timeIndices = time2D . getTimeIndicesFromMrutp ( indexWanted [ 0 ] ) ; int [ ] indexReallyWanted = new int [ indexWanted . length + 1 ] ; indexReallyWanted [ 0 ] = timeIndices [ 0 ] ; indexReallyWanted [ 1 ] = timeIndices [ 1 ] ; System . arraycopy ( indexWanted , 1 , indexReallyWanted , 2 , indexWanted . length - 1 ) ; useIndex = indexReallyWanted ; } PartitionCollectionImmutable . DataRecord record = vindexP . getDataRecord ( useIndex ) ; if ( record == null ) { if ( Grib . debugRead ) logger . debug ( \"readDataFromPartition missing data%n\" ) ; resultPos ++ ; // can just skip, since result is prefilled with NaNs continue ; } record . resultIndex = resultPos ; records . add ( record ) ; resultPos ++ ; } // sort by file and position, then read DataReceiverIF dataReceiver = new DataReceiver ( section . getShape ( ) , section . getRange ( rank - 2 ) , section . getRange ( rank - 1 ) ) ; readPartitioned ( dataReceiver ) ; return dataReceiver . getArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coordinate based subsetting for Coverage [CODESPLIT] public Array readData2 ( CoordsSet want , RangeIterator yRange , RangeIterator xRange ) throws IOException { if ( vindex instanceof PartitionCollectionImmutable . VariableIndexPartitioned ) return readDataFromPartition2 ( ( PartitionCollectionImmutable . VariableIndexPartitioned ) vindex , want , yRange , xRange ) ; else return readDataFromCollection2 ( vindex , want , yRange , xRange ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all of the data records that have been added . The full ( x y ) record is read the reciever will subset the ( x y ) as needed . [CODESPLIT] private void read ( DataReceiverIF dataReceiver ) throws IOException { Collections . sort ( records ) ; int currFile = - 1 ; RandomAccessFile rafData = null ; try { for ( DataRecord dr : records ) { if ( Grib . debugIndexOnly || Grib . debugGbxIndexOnly ) { GribIosp . debugIndexOnlyCount ++ ; currentDataRecord = dr . record ; currentDataRafFilename = gribCollection . getDataRafFilename ( dr . record . fileno ) ; if ( Grib . debugIndexOnlyShow ) dr . show ( gribCollection ) ; dataReceiver . setDataToZero ( ) ; continue ; } if ( dr . record . fileno != currFile ) { if ( rafData != null ) rafData . close ( ) ; rafData = gribCollection . getDataRaf ( dr . record . fileno ) ; currFile = dr . record . fileno ; } if ( dr . record . pos == GribCollectionMutable . MISSING_RECORD ) continue ; if ( GribDataReader . validator != null && dr . validation != null && rafData != null ) { GribDataReader . validator . validate ( gribCollection . cust , rafData , dr . record . pos + dr . record . drsOffset , dr . validation ) ; } else if ( show && rafData != null ) { // for validation show ( dr . validation ) ; show ( rafData , dr . record . pos + dr . record . drsOffset ) ; } float [ ] data = readData ( rafData , dr ) ; GdsHorizCoordSys hcs = vindex . group . getGdsHorizCoordSys ( ) ; dataReceiver . addData ( data , dr . resultIndex , hcs . nx ) ; } } finally { if ( rafData != null ) rafData . close ( ) ; // make sure its closed even on exception } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Double - check idiom for lazy initialization of instance fields . See Effective Java 2nd Ed p . 283 . [CODESPLIT] protected StationHelper getStationHelper ( ) { if ( stationHelper == null ) { synchronized ( this ) { if ( stationHelper == null ) { try { stationHelper = createStationHelper ( ) ; } catch ( IOException e ) { // The methods that will call getStationHelper() aren't declared to throw IOException, so we must // wrap it in an unchecked exception. throw new RuntimeException ( e ) ; } } } } assert stationHelper != null : \"stationHelper is null for StationTimeSeriesCollectionImpl\" + getName ( ) ; return stationHelper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "subset [CODESPLIT] @ Override public StationTimeSeriesFeatureCollection subset ( ucar . unidata . geoloc . LatLonRect boundingBox ) throws IOException { return subset ( getStationFeatures ( boundingBox ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "might need to override for efficiency [CODESPLIT] @ Override public PointFeatureCollection flatten ( List < String > stationNames , CalendarDateRange dateRange , List < VariableSimpleIF > varList ) throws IOException { if ( ( stationNames == null ) || ( stationNames . size ( ) == 0 ) ) return new StationTimeSeriesCollectionFlattened ( this , dateRange ) ; List < StationFeature > subsetStations = getStationHelper ( ) . getStationFeaturesFromNames ( stationNames ) ; return new StationTimeSeriesCollectionFlattened ( new StationSubset ( this , subsetStations ) , dateRange ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the named service declared in the top level of this catalog . [CODESPLIT] public InvService findService ( String name ) { if ( name == null ) return null ; for ( InvService s : services ) { if ( name . equals ( s . getName ( ) ) ) return s ; // look for nested servers if ( s . getServiceType ( ) == ServiceType . COMPOUND ) { InvService result = s . findNestedService ( name ) ; if ( result != null ) return result ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve reletive URIs using the catalog s base URI . If the uriString is not reletive then no resolution is done . This also allows baseURI to be a file : scheme . [CODESPLIT] public URI resolveUri ( String uriString ) throws URISyntaxException { URI want = new URI ( uriString ) ; if ( ( baseURI == null ) || want . isAbsolute ( ) ) return want ; // gotta deal with file ourself String scheme = baseURI . getScheme ( ) ; if ( ( scheme != null ) && scheme . equals ( \"file\" ) ) { // LOOK at ucar.nc2.util.NetworkUtils.resolve String baseString = baseURI . toString ( ) ; if ( ( uriString . length ( ) > 0 ) && ( uriString . charAt ( 0 ) == ' ' ) ) return new URI ( baseString + uriString ) ; int pos = baseString . lastIndexOf ( ' ' ) ; if ( pos > 0 ) { String r = baseString . substring ( 0 , pos + 1 ) + uriString ; return new URI ( r ) ; } } //otherwise let the URI class resolve it return baseURI . resolve ( want ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve String value ; only call if isString () is true . [CODESPLIT] public String getStringValue ( ) { if ( valueS == null ) { StringBuilder sbuff = new StringBuilder ( ) ; for ( double v : valueD ) { sbuff . append ( v ) . append ( \" \" ) ; } valueS = sbuff . toString ( ) ; } return valueS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the gate size in meters [CODESPLIT] public int getGateSize ( int datatype ) { switch ( datatype ) { case REFLECTIVITY : return ( ( int ) reflect_gate_size ) ; case VELOCITY_HI : case VELOCITY_LOW : case SPECTRUM_WIDTH : return ( ( int ) doppler_gate_size ) ; //high resolution case REFLECTIVITY_HIGH : return ( ( int ) reflectHR_gate_size ) ; case VELOCITY_HIGH : return ( ( int ) velocityHR_gate_size ) ; case SPECTRUM_WIDTH_HIGH : return ( ( int ) spectrumHR_gate_size ) ; case DIFF_REFLECTIVITY_HIGH : return ( ( int ) zdrHR_gate_size ) ; case DIFF_PHASE : return ( ( int ) phiHR_gate_size ) ; case CORRELATION_COEFFICIENT : return ( ( int ) rhoHR_gate_size ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the starting gate in meters [CODESPLIT] public int getGateStart ( int datatype ) { switch ( datatype ) { case REFLECTIVITY : return ( ( int ) reflect_first_gate ) ; case VELOCITY_HI : case VELOCITY_LOW : case SPECTRUM_WIDTH : return ( ( int ) doppler_first_gate ) ; //high resolution case REFLECTIVITY_HIGH : return ( ( int ) reflectHR_first_gate ) ; case VELOCITY_HIGH : return ( ( int ) velocityHR_first_gate ) ; case SPECTRUM_WIDTH_HIGH : return ( ( int ) spectrumHR_first_gate ) ; case DIFF_REFLECTIVITY_HIGH : return ( ( int ) zdrHR_first_gate ) ; case DIFF_PHASE : return ( ( int ) phiHR_first_gate ) ; case CORRELATION_COEFFICIENT : return ( ( int ) rhoHR_first_gate ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the number of gates [CODESPLIT] public int getGateCount ( int datatype ) { switch ( datatype ) { case REFLECTIVITY : return ( ( int ) reflect_gate_count ) ; case VELOCITY_HI : case VELOCITY_LOW : case SPECTRUM_WIDTH : return ( ( int ) doppler_gate_count ) ; // hight resolution case REFLECTIVITY_HIGH : return ( ( int ) reflectHR_gate_count ) ; case VELOCITY_HIGH : return ( ( int ) velocityHR_gate_count ) ; case SPECTRUM_WIDTH_HIGH : return ( ( int ) spectrumHR_gate_count ) ; case DIFF_REFLECTIVITY_HIGH : return ( ( int ) zdrHR_gate_count ) ; case DIFF_PHASE : return ( ( int ) phiHR_gate_count ) ; case CORRELATION_COEFFICIENT : return ( ( int ) rhoHR_gate_count ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from this record . [CODESPLIT] public void readData ( RandomAccessFile raf , int datatype , Range gateRange , IndexIterator ii ) throws IOException { long offset = message_offset ; offset += MESSAGE_HEADER_SIZE ; // offset is from \"start of digital radar data message header\" offset += getDataOffset ( datatype ) ; raf . seek ( offset ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"  read recno \" + recno + \" at offset \" + offset + \" count= \" + getGateCount ( datatype ) ) ; logger . debug ( \"   offset: reflect= \" + reflect_offset + \" velocity= \" + velocity_offset + \" spWidth= \" + spectWidth_offset ) ; } int dataCount = getGateCount ( datatype ) ; if ( datatype == DIFF_PHASE ) { short [ ] data = new short [ dataCount ] ; raf . readShort ( data , 0 , dataCount ) ; for ( int gateIdx : gateRange ) { if ( gateIdx >= dataCount ) ii . setShortNext ( MISSING_DATA ) ; else ii . setShortNext ( data [ gateIdx ] ) ; } } else { byte [ ] data = new byte [ dataCount ] ; raf . readFully ( data ) ; //short [] ds = convertunsignedByte2Short(data); for ( int gateIdx : gateRange ) { if ( gateIdx >= dataCount ) ii . setByteNext ( MISSING_DATA ) ; else ii . setByteNext ( data [ gateIdx ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instances which have same content are equal . <p / > public boolean equals ( Object oo ) { if ( this == oo ) return true ; if ( ! ( oo instanceof Level2Record )) return false ; return hashCode () == oo . hashCode () ; } <p / > / ** Override Object . hashCode () to implement equals . * public int hashCode () { if ( hashCode == 0 ) { int result = 17 ; result = 37 * result + elevation_num ; // result = 37 * result + cut ; // result = 37 * result + datatype ; hashCode = result ; } return hashCode ; } private volatile int hashCode = 0 ; [CODESPLIT] public short [ ] convertunsignedByte2Short ( byte [ ] inb ) { int len = inb . length ; short [ ] outs = new short [ len ] ; int i = 0 ; for ( byte b : inb ) { outs [ i ++ ] = convertunsignedByte2Short ( b ) ; } return outs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a NetcdfDataset as an NcML - G document to the specified stream . [CODESPLIT] public void writeXML ( NetcdfDataset ncd , OutputStream os , boolean showCoords , String uri ) throws IOException { // Output the document, use standard formatter\r //XMLOutputter fmt = new XMLOutputter(\"  \", true);\r //fmt.setLineSeparator(\"\\n\");\r XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; fmt . output ( makeDocument ( ncd , showCoords , uri ) , os ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private Element makeReferenceSys ( ReferenceSystem referenceSystem ) { Element elem = new Element ( referenceCoordinateSystem thredds . client . catalog . Catalog . ncmlNS ) ; elem . setAttribute ( name referenceSystem . getName () ) ; elem . setAttribute ( authority referenceSystem . getAuthority () ) ; if ( referenceSystem . getReferenceType () ! = null ) elem . setAttribute ( type referenceSystem . getReferenceType () . toString () ) ; [CODESPLIT] private Element makeVariable ( VariableDS var ) { Element varElem = new Element ( \"variable\" , thredds . client . catalog . Catalog . ncmlNS ) ; varElem . setAttribute ( \"name\" , var . getFullName ( ) ) ; StringBuffer buff = new StringBuffer ( ) ; List dims = var . getDimensions ( ) ; for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { Dimension dim = ( Dimension ) dims . get ( i ) ; if ( i > 0 ) buff . append ( \" \" ) ; buff . append ( dim . getShortName ( ) ) ; } if ( buff . length ( ) > 0 ) varElem . setAttribute ( \"shape\" , buff . toString ( ) ) ; DataType dt = var . getDataType ( ) ; if ( dt != null ) varElem . setAttribute ( \"type\" , dt . toString ( ) ) ; // attributes\r for ( Attribute att : var . getAttributes ( ) ) { varElem . addContent ( makeAttribute ( att , \"attribute\" ) ) ; } if ( var . isMetadata ( ) ) varElem . addContent ( makeValues ( var ) ) ; // coordinate systems\r List csys = var . getCoordinateSystems ( ) ; if ( csys . size ( ) > 0 ) { buff . setLength ( 0 ) ; for ( int i = 0 ; i < csys . size ( ) ; i ++ ) { CoordinateSystem cs = ( CoordinateSystem ) csys . get ( i ) ; if ( i > 0 ) buff . append ( \" \" ) ; buff . append ( cs . getName ( ) ) ; } varElem . setAttribute ( \"coordinateSystems\" , buff . toString ( ) ) ; } return varElem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////// [CODESPLIT] public SubsetParams makeSubset ( ) { SubsetParams subset = new SubsetParams ( ) ; // vars subset . set ( SubsetParams . variables , var ) ; // horiz if ( stns != null ) subset . set ( SubsetParams . stations , stns ) ; else if ( hasLatLonBB ( ) ) subset . set ( SubsetParams . latlonBB , getLatLonBoundingBox ( ) ) ; else if ( hasLatLonPoint ( ) ) subset . set ( SubsetParams . latlonPoint , new LatLonPointImpl ( getLatitude ( ) , getLongitude ( ) ) ) ; // time CalendarDate date = getRequestedDate ( Calendar . getDefault ( ) ) ; CalendarDateRange dateRange = getCalendarDateRange ( Calendar . getDefault ( ) ) ; if ( isAllTimes ( ) ) { subset . set ( SubsetParams . timeAll , true ) ; } else if ( date != null ) { subset . set ( SubsetParams . time , date ) ; } else if ( dateRange != null ) { subset . set ( SubsetParams . timeRange , dateRange ) ; } else { subset . set ( SubsetParams . timePresent , true ) ; } if ( timeWindow != null ) { CalendarPeriod period = CalendarPeriod . of ( timeWindow ) ; subset . set ( SubsetParams . timeWindow , period ) ; } return subset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deal with having components on more than one line [CODESPLIT] public Dimension preferredLayoutSize ( Container target ) { synchronized ( target . getTreeLock ( ) ) { Dimension dim = new Dimension ( 0 , 0 ) ; for ( int i = 0 ; i < target . getComponentCount ( ) ; i ++ ) { Component m = target . getComponent ( i ) ; if ( m . isVisible ( ) ) { Dimension d = m . getPreferredSize ( ) ; // original // dim.height = Math.max(dim.height, d.height); //if (i > 0) { dim.width += hgap; } // dim.width += d.width; // new  way Point p = m . getLocation ( ) ; dim . width = Math . max ( dim . width , p . x + d . width ) ; dim . height = Math . max ( dim . height , p . y + d . height ) ; } } Insets insets = target . getInsets ( ) ; dim . width += insets . left + insets . right + getHgap ( ) * 2 ; dim . height += insets . top + insets . bottom + getVgap ( ) * 2 ; return dim ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the requested dataset if it is the ancestor dataset or an allowed descendant of the ancestor dataset otherwise return null . The given filter determines whether a dataset is allowed or not . [CODESPLIT] static CrawlableDataset verifyDescendantDataset ( CrawlableDataset ancestorCrDs , String path , CrawlableDatasetFilter filter ) { // Make sure requested path is descendant of ancestor dataset. if ( ! ancestorCrDs . isCollection ( ) ) throw new IllegalArgumentException ( \"Ancestor dataset <\" + ancestorCrDs . getPath ( ) + \"> not a collection.\" ) ; if ( ! path . startsWith ( ancestorCrDs . getPath ( ) ) ) throw new IllegalArgumentException ( \"Dataset path <\" + path + \"> not descendant of given dataset <\" + ancestorCrDs . getPath ( ) + \">.\" ) ; // If path and ancestor are the same, return ancestor. if ( path . length ( ) == ancestorCrDs . getPath ( ) . length ( ) ) return ancestorCrDs ; // Crawl into the dataset collection through each level of the given path // checking that each level is accepted by the given CrawlableDatasetFilter. String remainingPath = path . substring ( ancestorCrDs . getPath ( ) . length ( ) ) ; if ( remainingPath . startsWith ( \"/\" ) ) remainingPath = remainingPath . substring ( 1 ) ; String [ ] pathSegments = remainingPath . split ( \"/\" ) ; CrawlableDataset curCrDs = ancestorCrDs ; for ( int i = 0 ; i < pathSegments . length ; i ++ ) { curCrDs = curCrDs . getDescendant ( pathSegments [ i ] ) ; if ( filter != null ) if ( ! filter . accept ( curCrDs ) ) return null ; } // Only check complete path for existence since speed of check depends on implementation. if ( ! curCrDs . exists ( ) ) return null ; return curCrDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array psArray = readArray ( psVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; //p0 = (p0Var == null) ? 1.0 : p0Var.readScalarDouble();\r p0 = computeP0 ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; // it's possible to have rank 3 because pressure can have a level, usually 1\r // Check if rank 3 and try to reduce\r if ( psArray . getRank ( ) == 3 ) psArray = psArray . reduce ( 0 ) ; int [ ] shape2D = psArray . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index psIndex = psArray . getIndex ( ) ; ArrayDouble . D3 press = new ArrayDouble . D3 ( nz , ny , nx ) ; double ps ; for ( int z = 0 ; z < nz ; z ++ ) { double term1 = aArray . getDouble ( aIndex . set ( z ) ) * p0 ; //AP might need unit conversion\r if ( ! apUnits . equals ( units ) ) { term1 = convertPressureToPSUnits ( apUnits , term1 ) ; } double bz = bArray . getDouble ( bIndex . set ( z ) ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { ps = psArray . getDouble ( psIndex . set ( y , x ) ) ; press . set ( z , y , x , term1 + bz * ps ) ; } } } return press ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array psArray = readArray ( psVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; //p0 = (p0Var == null) ? 1.0 : p0Var.readScalarDouble();\r p0 = computeP0 ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; // it's possible to have rank 3 because pressure can have a level, usually 1\r // Check if rank 3 and try to reduce\r if ( psArray . getRank ( ) == 3 ) psArray = psArray . reduce ( 0 ) ; Index psIndex = psArray . getIndex ( ) ; ArrayDouble . D1 press = new ArrayDouble . D1 ( nz ) ; double ps ; for ( int z = 0 ; z < nz ; z ++ ) { double term1 = aArray . getDouble ( aIndex . set ( z ) ) * p0 ; //AP might need unit conversion\r if ( ! apUnits . equals ( units ) ) { term1 = convertPressureToPSUnits ( apUnits , term1 ) ; } double bz = bArray . getDouble ( bIndex . set ( z ) ) ; ps = psArray . getDouble ( psIndex . set ( yIndex , xIndex ) ) ; press . set ( z , term1 + bz * ps ) ; } return press ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ProjectionRect from the given LatLonRect . Handles lat / lon points that do not intersect the projection panel . [CODESPLIT] @ Override public ProjectionRect latLonToProjBB ( LatLonRect rect ) { BoundingBoxHelper bbhelper = new BoundingBoxHelper ( this , maxR ) ; return bbhelper . latLonToProjBB ( rect ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] static void tryit ( double want , double x ) { System . out . printf ( \"x = %f %f %f %n\" , x , x / want , want / x ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts UDUnits to UCUM . <br > UDUnits : http : // www . unidata . ucar . edu / software / udunits / udunits - 1 / etc / udunits . dat http : // www . unidata . ucar . edu / software / udunits / udunits - 2 / udunits2 . html I worked with v 2 . 1 . 9 <br > UCUM : http : // unitsofmeasure . org / ucum . html I worked with Version : 1 . 8 $Revision : 28894 $ <p / > <p > UDUnits supports lots of aliases ( short and long ) and plurals ( usually by adding s ) . These all get reduced to UCUM s short and canonical - only units . <p / > <p > Notes : <ul > <li > This method is a strictly case sensitive . The only UDUnits that should be capitalized ( other than acronyms ) are Btu Gregorian ... Julian ... PI . <br > The only UDUnits that may be capitalized are Celsius Fahrenheit Kelvin Rankine . <li > For 10 to the UCUM allows 10 * or 10^ . This method uses 10^ . <li > NTU becomes { ntu } . <li > PSU or psu becomes { psu } . < / ul > <p / > return the UDUnits converted to UCUM . null returns null . returns . throws Exception if trouble . [CODESPLIT] public static String udunitsToUcum ( String udunits ) { if ( udunits == null ) { return null ; } //is it a point in time? e.g., seconds since 1970-01-01T00:00:00T int sincePo = udunits . indexOf ( \" since \" ) ; if ( sincePo > 0 ) { try { //test if really appropriate double baf [ ] = ErddapCalendar2 . getTimeBaseAndFactor ( udunits ) ; //throws exception if trouble //use 'factor', since it is more forgiving than udunitsToUcum converter String u ; if ( Misc . nearlyEquals ( baf [ 1 ] , 0.001 , 1e-6 ) ) { // Can't simply do \"baf[1] == 0.001\". u = \"ms\" ; } else if ( baf [ 1 ] == 1 ) { u = \"s\" ; } else if ( baf [ 1 ] == ErddapCalendar2 . SECONDS_PER_MINUTE ) { u = \"min\" ; } else if ( baf [ 1 ] == ErddapCalendar2 . SECONDS_PER_HOUR ) { u = \"h\" ; } else if ( baf [ 1 ] == ErddapCalendar2 . SECONDS_PER_DAY ) { u = \"d\" ; } else if ( baf [ 1 ] == 30 * ErddapCalendar2 . SECONDS_PER_DAY ) { // mo_j ? u = \"mo\" ; } else if ( baf [ 1 ] == 360 * ErddapCalendar2 . SECONDS_PER_DAY ) { // a_j ? u = \"a\" ; } else { u = udunitsToUcum ( udunits . substring ( 0 , sincePo ) ) ; //shouldn't happen, but weeks? microsec? } //make \"s{since 1970-01-01T00:00:00T} return u + \"{\" + udunits . substring ( sincePo + 1 ) + \"}\" ; } catch ( Exception e ) { } } //parse udunits and build ucum, till done StringBuilder ucum = new StringBuilder ( ) ; int udLength = udunits . length ( ) ; int po = 0 ; //po is next position to be read while ( po < udLength ) { char ch = udunits . charAt ( po ) ; //letter   if ( isUdunitsLetter ( ch ) ) { //includes 'µ' and '°' //find contiguous letters|_|digit (no '-')  int po2 = po + 1 ; while ( po2 < udLength && ( isUdunitsLetter ( udunits . charAt ( po2 ) ) || udunits . charAt ( po2 ) == ' ' || ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) ) { po2 ++ ; } String tUdunits = udunits . substring ( po , po2 ) ; po = po2 ; //some udunits have internal digits, but none end in digits  //if it ends in digits, treat as exponent //find contiguous digits at end int firstDigit = tUdunits . length ( ) ; while ( firstDigit >= 1 && ErddapString2 . isDigit ( tUdunits . charAt ( firstDigit - 1 ) ) ) { firstDigit -- ; } String exponent = tUdunits . substring ( firstDigit ) ; tUdunits = tUdunits . substring ( 0 , firstDigit ) ; String tUcum = oneUdunitsToUcum ( tUdunits ) ; //deal with PER -> /  if ( tUcum . equals ( \"/\" ) ) { char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //2 '/' cancel out } else if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //  '/' replaces '.' } else { ucum . append ( ' ' ) ; } } else { ucum . append ( tUcum ) ; } //add the exponent ucum . append ( exponent ) ; //catch -exponent as a number below continue ; } //number if ( ch == ' ' || ErddapString2 . isDigit ( ch ) ) { //find contiguous digits int po2 = po + 1 ; while ( po2 < udLength && ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) { po2 ++ ; } //decimal place + digit (not just .=multiplication) boolean hasDot = false ; if ( po2 < udLength - 1 && udunits . charAt ( po2 ) == ' ' && ErddapString2 . isDigit ( udunits . charAt ( po2 + 1 ) ) ) { hasDot = true ; po2 += 2 ; while ( po2 < udLength && ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) { po2 ++ ; } } //exponent?     e-  or e{digit} boolean hasE = false ; if ( po2 < udLength - 1 && Character . toLowerCase ( udunits . charAt ( po2 ) ) == ' ' && ( udunits . charAt ( po2 + 1 ) == ' ' || ErddapString2 . isDigit ( udunits . charAt ( po2 + 1 ) ) ) ) { hasE = true ; po2 += 2 ; while ( po2 < udLength && ErddapString2 . isDigit ( udunits . charAt ( po2 ) ) ) { po2 ++ ; } } String num = udunits . substring ( po , po2 ) ; po = po2 ; //convert floating point to rational number if ( hasDot || hasE ) { int rational [ ] = ErddapString2 . toRational ( ErddapString2 . parseDouble ( num ) ) ; if ( rational [ 1 ] == Integer . MAX_VALUE ) { ucum . append ( num ) ; //ignore the trouble !!! ??? } else if ( rational [ 1 ] == 0 ) //includes {0, 0} { ucum . append ( rational [ 0 ] ) ; } else { ucum . append ( rational [ 0 ] ) . append ( \".10^\" ) . append ( rational [ 1 ] ) ; } } else { //just copy num ucum . append ( num ) ; } continue ; } //space or . or · (183) (multiplication) if ( ch == ' ' || ch == ' ' || ch == 183 ) { char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' || lastUcum == ' ' ) { //if last token was / or .,  do nothing } else { ucum . append ( ' ' ) ; } po ++ ; continue ; } // *  (multiplication * or exponent **) if ( ch == ' ' ) { po ++ ; if ( po < udLength && udunits . charAt ( po ) == ' ' ) { ucum . append ( ' ' ) ; // exponent: ** -> ^ po ++ ; } else { char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' || lastUcum == ' ' ) { //if last token was / or .,  do nothing } else { ucum . append ( ' ' ) ; } } continue ; } // / if ( ch == ' ' ) { po ++ ; char lastUcum = ucum . length ( ) == 0 ? ' ' : ucum . charAt ( ucum . length ( ) - 1 ) ; if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //  2 '/' cancel out } else if ( lastUcum == ' ' ) { ucum . setCharAt ( ucum . length ( ) - 1 , ' ' ) ; //  '/' replaces '.' } else { ucum . append ( ' ' ) ; } continue ; } // \" if ( ch == ' ' ) { po ++ ; ucum . append ( \"''\" ) ; continue ; } //otherwise, punctuation.   copy it ucum . append ( ch ) ; po ++ ; } return ucum . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts one udunits term ( perhaps with metric prefix ( es )) to the corresponding ucum string . If udunits is just metric prefix ( es ) this returns the prefix acronym ( s ) with { count } as suffix ( e . g . dkilo returns dk { count } ) . If this can t completely convert udunits it returns the original udunits ( e . g . kiloBobs remains kiloBobs ( to avoid exact becoming ect ) . [CODESPLIT] private static String oneUdunitsToUcum ( String udunits ) { //repeatedly pull off start of udunits and build ucum, till done String oldUdunits = udunits ; StringBuilder ucum = new StringBuilder ( ) ; MAIN : while ( true ) { //try to find udunits in hashMap String tUcum = udHashMap . get ( udunits ) ; if ( tUcum != null ) { //success! done! ucum . append ( tUcum ) ; return ucum . toString ( ) ; } //try to separate out a metricName prefix (e.g., \"kilo\") for ( int p = 0 ; p < nMetric ; p ++ ) { if ( udunits . startsWith ( metricName [ p ] ) ) { udunits = udunits . substring ( metricName [ p ] . length ( ) ) ; ucum . append ( metricAcronym [ p ] ) ; if ( udunits . length ( ) == 0 ) { ucum . append ( \"{count}\" ) ; return ucum . toString ( ) ; } continue MAIN ; } } //try to separate out a metricAcronym prefix (e.g., \"k\") for ( int p = 0 ; p < nMetric ; p ++ ) { if ( udunits . startsWith ( metricAcronym [ p ] ) ) { udunits = udunits . substring ( metricAcronym [ p ] . length ( ) ) ; ucum . append ( metricAcronym [ p ] ) ; if ( udunits . length ( ) == 0 ) { ucum . append ( \"{count}\" ) ; return ucum . toString ( ) ; } continue MAIN ; } } return oldUdunits ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts UCUM to UDUnits . <br > UDUnits : http : // www . unidata . ucar . edu / software / udunits / udunits - 1 / etc / udunits . dat http : // www . unidata . ucar . edu / software / udunits / udunits - 2 / udunits2 . html <br > UCUM : http : // unitsofmeasure . org / ucum . html <p / > <p > UCUM tends to be short canonical - only and strict . Many UCUM units are the same in UDUnits . <p / > <p > UDUnits supports lots of aliases ( short and long ) and plurals ( usually by adding s ) . This tries to convert UCUM to a short common UDUNIT units . <p / > <p > Problems : <ul > <li > UCUM has only deg no concept of degree_east|north|true|true . < / ul > <p / > <p > Notes : <ul > <li > This method is a strictly case sensitive . <li > For 10 to the UCUM allows 10 * or 10^ . This method uses 10^ . <li > { ntu } becomes NTU . <li > { psu } becomes PSU . < / ul > <p / > return the UCUM converted to UDUNITS . null returns null . returns . [CODESPLIT] public static String ucumToUdunits ( String ucum ) { if ( ucum == null ) { return null ; } StringBuilder udunits = new StringBuilder ( ) ; int ucLength = ucum . length ( ) ; if ( ucLength == 0 ) { return \"\" ; } //is it a time point?  e.g., s{since 1970-01-01T00:00:00T} if ( ucum . charAt ( ucLength - 1 ) == ' ' && //quick reject ucum . indexOf ( ' ' ) == ucLength - 1 ) { //reasonably quick reject int sincePo = ucum . indexOf ( \"{since \" ) ; if ( sincePo > 0 ) { //is first part an atomic ucum unit? String tUdunits = ucHashMap . get ( ucum . substring ( 0 , sincePo ) ) ; if ( tUdunits != null ) { return tUdunits + \" \" + ucum . substring ( sincePo + 1 , ucLength - 1 ) ; } } } //parse ucum and build udunits, till done         int po = 0 ; //po is next position to be read while ( po < ucLength ) { char ch = ucum . charAt ( po ) ; //letter   if ( isUcumLetter ( ch ) ) { //includes [, ], {, }, 'µ' and \"'\" //find contiguous letters|_|digit (no '-')  int po2 = po + 1 ; while ( po2 < ucLength && ( isUcumLetter ( ucum . charAt ( po2 ) ) || ucum . charAt ( po2 ) == ' ' || ErddapString2 . isDigit ( ucum . charAt ( po2 ) ) ) ) { po2 ++ ; } String tUcum = ucum . substring ( po , po2 ) ; po = po2 ; //some ucum have internal digits, but none end in digits  //if it ends in digits, treat as exponent //find contiguous digits at end int firstDigit = tUcum . length ( ) ; while ( firstDigit >= 1 && ErddapString2 . isDigit ( tUcum . charAt ( firstDigit - 1 ) ) ) { firstDigit -- ; } String exponent = tUcum . substring ( firstDigit ) ; tUcum = tUcum . substring ( 0 , firstDigit ) ; String tUdunits = oneUcumToUdunits ( tUcum ) ; //deal with PER -> /  if ( tUdunits . equals ( \"/\" ) ) { char lastUdunits = udunits . length ( ) == 0 ? ' ' : udunits . charAt ( udunits . length ( ) - 1 ) ; if ( lastUdunits == ' ' ) { udunits . setCharAt ( udunits . length ( ) - 1 , ' ' ) ; //2 '/' cancel out } else if ( lastUdunits == ' ' ) { udunits . setCharAt ( udunits . length ( ) - 1 , ' ' ) ; //  '/' replaces '.' } else { udunits . append ( ' ' ) ; } } else { udunits . append ( tUdunits ) ; } //add the exponent udunits . append ( exponent ) ; //catch -exponent as a number below continue ; } //number if ( ch == ' ' || ErddapString2 . isDigit ( ch ) ) { //find contiguous digits int po2 = po + 1 ; while ( po2 < ucLength && ErddapString2 . isDigit ( ucum . charAt ( po2 ) ) ) { po2 ++ ; } // ^-  or ^{digit} if ( po2 < ucLength - 1 && Character . toLowerCase ( ucum . charAt ( po2 ) ) == ' ' && ( ucum . charAt ( po2 + 1 ) == ' ' || ErddapString2 . isDigit ( ucum . charAt ( po2 + 1 ) ) ) ) { po2 += 2 ; while ( po2 < ucLength && ErddapString2 . isDigit ( ucum . charAt ( po2 ) ) ) { po2 ++ ; } } String num = ucum . substring ( po , po2 ) ; po = po2 ; udunits . append ( num ) ; continue ; } // . if ( ch == ' ' ) { po ++ ; udunits . append ( ' ' ) ; // ' ' is more common than '.' in udunits continue ; } // * if ( ch == ' ' ) { po ++ ; udunits . append ( ' ' ) ; continue ; } // '  '' if ( ch == ' ' ) { po ++ ; if ( po < ucLength && ucum . charAt ( po ) == ' ' ) { udunits . append ( \"arc_second\" ) ; po ++ ; } else { udunits . append ( \"arc_minute\" ) ; } continue ; } //otherwise, punctuation.   copy it //  / (division), \" doesn't occur, udunits . append ( ch ) ; po ++ ; } return udunits . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts one ucum term ( perhaps with metric prefix ( es )) ( to the corresponding udunits string . If ucum is just metric prefix ( es ) this returns the metric prefix acronym ( s ) with { count } as suffix ( e . g . dkilo returns dk { count } ) . If this can t completely convert ucum it returns the original ucum ( e . g . kiloBobs remains kiloBobs ( to avoid exact becoming ect ) . [CODESPLIT] private static String oneUcumToUdunits ( String ucum ) { //repeatedly pull off start of ucum and build udunits, till done String oldUcum = ucum ; StringBuilder udunits = new StringBuilder ( ) ; MAIN : while ( true ) { //try to find ucum in hashMap String tUdunits = ucHashMap . get ( ucum ) ; if ( tUdunits != null ) { //success! done! udunits . append ( tUdunits ) ; return udunits . toString ( ) ; } //try to separate out a metricAcronym prefix (e.g., \"k\") for ( int p = 0 ; p < nMetric ; p ++ ) { if ( ucum . startsWith ( metricAcronym [ p ] ) ) { ucum = ucum . substring ( metricAcronym [ p ] . length ( ) ) ; udunits . append ( metricAcronym [ p ] ) ; if ( ucum . length ( ) == 0 ) { udunits . append ( \"{count}\" ) ; return udunits . toString ( ) ; } continue MAIN ; } } //try to separate out a twoAcronym prefix (e.g., \"Ki\") for ( int p = 0 ; p < nTwo ; p ++ ) { if ( ucum . startsWith ( twoAcronym [ p ] ) ) { ucum = ucum . substring ( twoAcronym [ p ] . length ( ) ) ; char udch = udunits . length ( ) > 0 ? udunits . charAt ( udunits . length ( ) - 1 ) : ' ' ; if ( udch != ' ' && udch != ' ' && udch != ' ' ) { udunits . append ( ' ' ) ; } if ( ucum . length ( ) == 0 ) { udunits . append ( \"{count}\" ) ; return udunits . toString ( ) ; } udunits . append ( twoValue [ p ] ) . append ( \".\" ) ; continue MAIN ; } } //ends in comment?  try to just convert the beginning int po1 = oldUcum . lastIndexOf ( ' ' ) ; if ( po1 > 0 && oldUcum . endsWith ( \"}\" ) ) { return oneUcumToUdunits ( oldUcum . substring ( 0 , po1 ) ) + oldUcum . substring ( po1 ) ; } return oldUcum ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the contents of { @code inputStream } into a HashMap . Each key - value pair in the input will result in an entry in the map . <p / > The specified stream remains open after this method returns . [CODESPLIT] public static HashMap < String , String > getHashMapStringString ( InputStream inputStream , String charset ) throws IOException { HashMap < String , String > ht = new HashMap <> ( ) ; ErddapStringArray sa = ErddapStringArray . fromInputStream ( inputStream , charset ) ; int n = sa . size ( ) ; int i = 0 ; while ( i < n ) { String s = sa . get ( i ++ ) ; if ( s . startsWith ( \"#\" ) ) { continue ; } while ( i < n && s . endsWith ( \"\\\\\" ) ) { s = s . substring ( 0 , s . length ( ) - 1 ) + sa . get ( i ++ ) ; } int po = s . indexOf ( ' ' ) ; if ( po < 0 ) { continue ; } //new String: so not linked to big source file's text ht . put ( s . substring ( 0 , po ) . trim ( ) , s . substring ( po + 1 ) . trim ( ) ) ; } return ht ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Center name from table C - 1 or C - 11 [CODESPLIT] public static String getCenterName ( int center_id , int edition ) { String result = ( edition == 1 ) ? getTableValue ( 1 , center_id ) : getTableValue ( 11 , center_id ) ; if ( result != null ) return result ; if ( center_id == 0 ) return \"WMO standard table\" ; return \"Unknown center=\" + center_id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Center name from table C - 1 or C - 11 [CODESPLIT] public static String getCenterNameBufr ( int center_id , int edition ) { String result = ( edition < 4 ) ? getTableValue ( 1 , center_id ) : getTableValue ( 11 , center_id ) ; if ( result != null ) return result ; if ( center_id == 0 ) return \"WMO standard table\" ; return \"Unknown center=\" + center_id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Not supported by SimpleCatalogBuilder . [CODESPLIT] public InvCatalogImpl generateProxyDsResolverCatalog ( CrawlableDataset catalogCrDs , ProxyDatasetHandler pdh ) throws IOException { throw new java . lang . UnsupportedOperationException ( \"This method not supported by SimpleCatalogBuilder.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the lat / lon / alt bounding boxes from the dataset . [CODESPLIT] static public ThreddsMetadata . GeospatialCoverage extractGeospatial ( InvDatasetImpl threddsDataset ) throws IOException { ThreddsDataFactory . Result result = null ; try { result = new ThreddsDataFactory ( ) . openFeatureDataset ( threddsDataset , null ) ; if ( result . fatalError ) { System . out . println ( \" openDatatype errs=\" + result . errLog ) ; return null ; } if ( result . featureType == FeatureType . GRID ) { System . out . println ( \" GRID=\" + result . location ) ; GridDataset gridDataset = ( GridDataset ) result . featureDataset ; return extractGeospatial ( gridDataset ) ; } else if ( result . featureType == FeatureType . POINT ) { PointObsDataset pobsDataset = ( PointObsDataset ) result . featureDataset ; LatLonRect llbb = pobsDataset . getBoundingBox ( ) ; if ( null != llbb ) { ThreddsMetadata . GeospatialCoverage gc = new ThreddsMetadata . GeospatialCoverage ( ) ; gc . setBoundingBox ( llbb ) ; return gc ; } } else if ( result . featureType == FeatureType . STATION ) { StationObsDataset sobsDataset = ( StationObsDataset ) result . featureDataset ; LatLonRect llbb = sobsDataset . getBoundingBox ( ) ; if ( null != llbb ) { ThreddsMetadata . GeospatialCoverage gc = new ThreddsMetadata . GeospatialCoverage ( ) ; gc . setBoundingBox ( llbb ) ; return gc ; } } } finally { try { if ( ( result != null ) && ( result . featureDataset != null ) ) result . featureDataset . close ( ) ; } catch ( IOException ioe ) { logger . error ( \"Closing dataset \" + result . featureDataset , ioe ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract a list of data variables ( and their canonical names if possible ) from the dataset . [CODESPLIT] static public ThreddsMetadata . Variables extractVariables ( InvDatasetImpl threddsDataset ) throws IOException { ThreddsDataFactory . Result result = null ; try { result = new ThreddsDataFactory ( ) . openFeatureDataset ( threddsDataset , null ) ; if ( result . fatalError ) { System . out . println ( \" openDatatype errs=\" + result . errLog ) ; return null ; } if ( result . featureType == FeatureType . GRID ) { // System.out.println(\" extractVariables GRID=\" + result.location); GridDataset gridDataset = ( GridDataset ) result . featureDataset ; return extractVariables ( threddsDataset , gridDataset ) ; } else if ( ( result . featureType == FeatureType . STATION ) || ( result . featureType == FeatureType . POINT ) ) { PointObsDataset pobsDataset = ( PointObsDataset ) result . featureDataset ; ThreddsMetadata . Variables vars = new ThreddsMetadata . Variables ( \"CF-1.0\" ) ; for ( VariableSimpleIF vs : pobsDataset . getDataVariables ( ) ) { ThreddsMetadata . Variable v = new ThreddsMetadata . Variable ( ) ; vars . addVariable ( v ) ; v . setName ( vs . getShortName ( ) ) ; v . setDescription ( vs . getDescription ( ) ) ; v . setUnits ( vs . getUnitsString ( ) ) ; ucar . nc2 . Attribute att = vs . findAttributeIgnoreCase ( \"standard_name\" ) ; if ( att != null ) v . setVocabularyName ( att . getStringValue ( ) ) ; } vars . sort ( ) ; return vars ; } } finally { try { if ( ( result != null ) && ( result . featureDataset != null ) ) result . featureDataset . close ( ) ; } catch ( IOException ioe ) { logger . error ( \"Closing dataset \" + result . featureDataset , ioe ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////// [CODESPLIT] static public ThreddsMetadata . Variables extractVariables ( FeatureDatasetPoint fd ) { ThreddsMetadata . Variables vars = new ThreddsMetadata . Variables ( \"CF-1.5\" ) ; List < VariableSimpleIF > dataVars = fd . getDataVariables ( ) ; if ( dataVars == null ) return vars ; for ( VariableSimpleIF v : dataVars ) { ThreddsMetadata . Variable tv = new ThreddsMetadata . Variable ( ) ; vars . addVariable ( tv ) ; tv . setName ( v . getShortName ( ) ) ; tv . setDescription ( v . getDescription ( ) ) ; tv . setUnits ( v . getUnitsString ( ) ) ; ucar . nc2 . Attribute att = v . findAttributeIgnoreCase ( \"standard_name\" ) ; if ( att != null ) tv . setVocabularyName ( att . getStringValue ( ) ) ; } vars . sort ( ) ; return vars ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a CalendarDateUnit from a calendar name and a udunit string = unit since calendarDate [CODESPLIT] static public CalendarDateUnit of ( String calendarName , String udunitString ) { Calendar calt = Calendar . get ( calendarName ) ; if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , udunitString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a CalendarDateUnit from a calendar and a udunit string = unit since calendarDate [CODESPLIT] static public CalendarDateUnit withCalendar ( Calendar calt , String udunitString ) { if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , udunitString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a CalendarDateUnit from a calendar a CalendarPeriod . Field and a base date [CODESPLIT] static public CalendarDateUnit of ( Calendar calt , CalendarPeriod . Field periodField , CalendarDate baseDate ) { if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , periodField , baseDate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inverse of makeCalendarDate [CODESPLIT] public double makeOffsetFromRefDate ( CalendarDate date ) { if ( isCalendarField ) { if ( date . equals ( baseDate ) ) return 0.0 ; return date . getDifference ( baseDate , periodField ) ; } else { long msecs = date . getDifferenceInMsecs ( baseDate ) ; return msecs / period . getValueInMillisecs ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inverse of makeOffsetFromRefDate [CODESPLIT] public CalendarDate makeCalendarDate ( double value ) { if ( isCalendarField ) return baseDate . add ( CalendarPeriod . of ( ( int ) value , periodField ) ) ; // LOOK int vs double\r else return baseDate . add ( value , periodField ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public static void main ( String [ ] args ) { CalendarDateUnit cdu ; String s = \"calendar Month since 2012-01-19T18:00:00.000Z\" ; cdu = CalendarDateUnit . of ( null , s ) ; System . out . printf ( \"%s == %s%n\" , s , cdu ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public java . io . File chooseFile () { if ( !readOk ) return null ; w . show () ; [CODESPLIT] public String chooseFilenameToSave ( String defaultFilename ) { chooser . setDialogType ( JFileChooser . SAVE_DIALOG ) ; String result = ( defaultFilename == null ) ? chooseFilename ( ) : chooseFilename ( defaultFilename ) ; chooser . setDialogType ( JFileChooser . OPEN_DIALOG ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow user to select file then return the filename in canonical form always using / never \\ [CODESPLIT] public String chooseFilename ( ) { if ( ! readOk ) return null ; selectedFile = false ; //selectedURL = false;\r w . setVisible ( true ) ; // modal, so blocks; listener calls hide(), which unblocks.\r if ( selectedFile ) { File file = chooser . getSelectedFile ( ) ; if ( file == null ) return null ; try { return file . getCanonicalPath ( ) . replace ( ' ' , ' ' ) ; } catch ( IOException ioe ) { } // return null\r } /* if (selectedURL) {\r\n      return (String) urlComboBox.getSelectedItem();\r\n    }  */ return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the corresponding quantity dimension . [CODESPLIT] public QuantityDimension getQuantityDimension ( ) { Factor [ ] factors = getFactors ( ) ; for ( int i = factors . length ; -- i >= 0 ; ) { Factor factor = factors [ i ] ; factors [ i ] = new Factor ( ( ( BaseUnit ) factor . getBase ( ) ) . getBaseQuantity ( ) , factor . getExponent ( ) ) ; } return new QuantityDimension ( factors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { System . out . println ( \"new UnitDimension() = \\\"\" + new UnitDimension ( ) + ' ' ) ; UnitDimension timeDimension = new UnitDimension ( BaseUnit . getOrCreate ( UnitName . newUnitName ( \"second\" , null , \"s\" ) , BaseQuantity . TIME ) ) ; System . out . println ( \"timeDimension = \\\"\" + timeDimension + ' ' ) ; UnitDimension lengthDimension = new UnitDimension ( BaseUnit . getOrCreate ( UnitName . newUnitName ( \"meter\" , null , \"m\" ) , BaseQuantity . LENGTH ) ) ; System . out . println ( \"lengthDimension = \\\"\" + lengthDimension + ' ' ) ; System . out . println ( \"lengthDimension.isReciprocalOf(timeDimension) = \\\"\" + lengthDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; UnitDimension hertzDimension = timeDimension . raiseTo ( - 1 ) ; System . out . println ( \"hertzDimension = \\\"\" + hertzDimension + ' ' ) ; System . out . println ( \"hertzDimension.isReciprocalOf(timeDimension) = \\\"\" + hertzDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; System . out . println ( \"lengthDimension.divideBy(timeDimension) = \\\"\" + lengthDimension . divideBy ( timeDimension ) + ' ' ) ; System . out . println ( \"lengthDimension.divideBy(timeDimension).raiseTo(2) = \\\"\" + lengthDimension . divideBy ( timeDimension ) . raiseTo ( 2 ) + ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if this is a valid SIGMET - IRIS file for this IOServiceProvider . [CODESPLIT] public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) { try { raf . order ( RandomAccessFile . LITTLE_ENDIAN ) ; // The first struct in the file is the product_hdr, which will have the\r // standard structure_header, followed by other embedded structures.\r // Each of these structures also have a structure header. To validate\r // the file we check for a product_hdr (by looking for type 27 in the\r // structure_header), then a product_configuration structure (by looking\r // for type 26 in its structure_header), then checking that that\r // the product_configuration does indicate a type of RAW data (type 15)\r raf . seek ( 0 ) ; short [ ] data = new short [ 13 ] ; raf . readShort ( data , 0 , 13 ) ; return ( data [ 0 ] == ( short ) 27 && data [ 6 ] == ( short ) 26 && data [ 12 ] == ( short ) 15 ) ; } catch ( IOException ioe ) { System . out . println ( \"In isValidFile(): \" + ioe . toString ( ) ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open existing file and populate ncfile with it . [CODESPLIT] public void open ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws java . io . IOException { super . open ( raf , ncfile , cancelTask ) ; //java.util.Map<String, Number> recHdr=new java.util.HashMap<String, Number>();\r java . util . Map < String , String > hdrNames = new java . util . HashMap < String , String > ( ) ; volScan = new SigmetVolumeScan ( raf , ncfile , varList ) ; this . varList = init ( raf , ncfile , hdrNames ) ; // doData(raf, ncfile, varList);\r // raf.close();\r // this.ncfile.close();\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read some global data from SIGMET file . The SIGMET file consists of records with fixed length = 6144 bytes . [CODESPLIT] static public java . util . Map < String , Number > readRecordsHdr ( ucar . unidata . io . RandomAccessFile raf ) { java . util . Map < String , Number > recHdr1 = new java . util . HashMap < String , Number > ( ) ; try { int nparams = 0 ; //      -- Read from <product_end> of the 1st record -- 12+320+120\r //      -- Calculate Nyquist velocity --------------------\r raf . seek ( 452 ) ; int prf = raf . readInt ( ) ; raf . seek ( 480 ) ; int wave = raf . readInt ( ) ; float vNyq = calcNyquist ( prf , wave ) ; recHdr1 . put ( \"vNyq\" , vNyq ) ; //      -- Read from the 2nd record----------- 6144+12(strucr_hdr)+168(from ingest_config)\r raf . seek ( 6324 ) ; int radar_lat = raf . readInt ( ) ; int radar_lon = raf . readInt ( ) ; //6328\r short ground_height = raf . readShort ( ) ; //6332\r short radar_height = raf . readShort ( ) ; //6334\r raf . skipBytes ( 4 ) ; short num_rays = raf . readShort ( ) ; // 6340\r raf . skipBytes ( 2 ) ; int radar_alt = raf . readInt ( ) ; //6344\r raf . seek ( 6648 ) ; int time_beg = raf . readInt ( ) ; raf . seek ( 6652 ) ; int time_end = raf . readInt ( ) ; raf . seek ( 6772 ) ; int data_mask = raf . readInt ( ) ; for ( int j = 0 ; j < 32 ; j ++ ) { nparams += ( ( data_mask >> j ) & ( 0x1 ) ) ; } raf . seek ( 6912 ) ; short multiprf = raf . readShort ( ) ; raf . seek ( 7408 ) ; int range_first = raf . readInt ( ) ; //  cm    7408\r int range_last = raf . readInt ( ) ; //  cm  7412\r raf . skipBytes ( 2 ) ; short bins = raf . readShort ( ) ; //7418\r if ( bins % 2 != 0 ) bins = ( short ) ( bins + 1 ) ; raf . skipBytes ( 4 ) ; int step = raf . readInt ( ) ; //  cm    7424\r raf . seek ( 7574 ) ; short number_sweeps = raf . readShort ( ) ; // 7574\r raf . seek ( 12312 ) ; int base_time = raf . readInt ( ) ; //<ingest_data_header> 3d rec\r raf . skipBytes ( 2 ) ; short year = raf . readShort ( ) ; short month = raf . readShort ( ) ; short day = raf . readShort ( ) ; recHdr1 . put ( \"radar_lat\" , calcAngle ( radar_lat ) ) ; recHdr1 . put ( \"radar_lon\" , calcAngle ( radar_lon ) ) ; recHdr1 . put ( \"range_first\" , range_first ) ; recHdr1 . put ( \"range_last\" , range_last ) ; recHdr1 . put ( \"ground_height\" , ground_height ) ; recHdr1 . put ( \"radar_height\" , radar_height ) ; recHdr1 . put ( \"radar_alt\" , radar_alt ) ; recHdr1 . put ( \"step\" , step ) ; recHdr1 . put ( \"bins\" , bins ) ; //System.out.println(\"  bins=\"+bins);\r recHdr1 . put ( \"num_rays\" , num_rays ) ; //System.out.println(\"  rays=\"+num_rays);\r recHdr1 . put ( \"nparams\" , nparams ) ; //System.out.println(\"  nparams=\"+nparams);\r recHdr1 . put ( \"multiprf\" , multiprf ) ; recHdr1 . put ( \"number_sweeps\" , number_sweeps ) ; //System.out.println(\"IN HDR:  number_sweeps=\"+number_sweeps);\r recHdr1 . put ( \"year\" , year ) ; recHdr1 . put ( \"month\" , month ) ; recHdr1 . put ( \"day\" , day ) ; recHdr1 . put ( \"base_time\" , base_time ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; e . printStackTrace ( ) ; } return recHdr1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read StationName strings [CODESPLIT] public java . util . Map < String , String > readStnNames ( ucar . unidata . io . RandomAccessFile raf ) { java . util . Map < String , String > hdrNames = new java . util . HashMap < String , String > ( ) ; try { raf . seek ( 6288 ) ; String stnName = raf . readString ( 16 ) ; //System.out.println(\" stnName=\"+stnName.trim());\r raf . seek ( 6306 ) ; String stnName_util = raf . readString ( 16 ) ; hdrNames . put ( \"StationName\" , stnName . trim ( ) ) ; hdrNames . put ( \"StationName_SetupUtility\" , stnName_util . trim ( ) ) ; } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; e . printStackTrace ( ) ; } return hdrNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define Dimensions Variables Attributes in ncfile [CODESPLIT] public ArrayList < Variable > init ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , java . util . Map < String , String > hdrNames ) throws java . io . IOException { // prepare attribute values\r String [ ] data_name = { \" \" , \"TotalPower\" , \"Reflectivity\" , \"Velocity\" , \"Width\" , \"Differential_Reflectivity\" } ; String [ ] unit = { \" \" , \"dbZ\" , \"dbZ\" , \"m/sec\" , \"m/sec\" , \"dB\" } ; int [ ] type = { 1 , 2 , 3 , 4 , 5 } ; String def_datafile = \"SIGMET-IRIS\" ; String tim = \"\" ; int ngates = 0 ; recHdr = readRecordsHdr ( raf ) ; hdrNames = readStnNames ( raf ) ; String stnName = hdrNames . get ( \"StationName\" ) ; String stnName_util = hdrNames . get ( \"StationName_SetupUtility\" ) ; float radar_lat = recHdr . get ( \"radar_lat\" ) . floatValue ( ) ; //System.out.println(\"rad_lat=\"+radar_lat);\r float radar_lon = recHdr . get ( \"radar_lon\" ) . floatValue ( ) ; //System.out.println(\"rad_lon=\"+radar_lon);\r short ground_height = recHdr . get ( \"ground_height\" ) . shortValue ( ) ; //System.out.println(\"ground_H=\"+ground_height);\r short radar_height = recHdr . get ( \"radar_height\" ) . shortValue ( ) ; //System.out.println(\"radar_H=\"+radar_height);\r int radar_alt = ( recHdr . get ( \"radar_alt\" ) . intValue ( ) ) / 100 ; //System.out.println(\"rad_alt=\"+radar_alt);\r short num_rays = recHdr . get ( \"num_rays\" ) . shortValue ( ) ; //System.out.println(\"num_rays=\"+num_rays);\r short bins = recHdr . get ( \"bins\" ) . shortValue ( ) ; //System.out.println(\"bins=\"+bins);\r float range_first = ( recHdr . get ( \"range_first\" ) . intValue ( ) ) * 0.01f ; //System.out.println(\"range_1st=\"+range_first);\r float range_last = ( recHdr . get ( \"range_last\" ) . intValue ( ) ) * 0.01f ; //System.out.println(\"step=\"+step);\r short number_sweeps = recHdr . get ( \"number_sweeps\" ) . shortValue ( ) ; //System.out.println(\"number_sweeps=\"+number_sweeps);\r int nparams = ( recHdr . get ( \"nparams\" ) . intValue ( ) ) ; //System.out.println(\"nparams=\"+nparams);\r short year = recHdr . get ( \"year\" ) . shortValue ( ) ; //System.out.println(\"year=\"+year);\r short month = recHdr . get ( \"month\" ) . shortValue ( ) ; short day = recHdr . get ( \"day\" ) . shortValue ( ) ; int base_time = ( recHdr . get ( \"base_time\" ) . intValue ( ) ) ; // define number of gates for every sweep\r sweep_bins = new int [ nparams * number_sweeps ] ; if ( number_sweeps > 1 ) { sweep_bins = volScan . getNumberGates ( ) ; } else { for ( int kk = 0 ; kk < nparams ; kk ++ ) { sweep_bins [ kk ] = bins ; } } // add Dimensions\r Dimension scanR = new Dimension ( \"scanR\" , number_sweeps , true ) ; Dimension radial = new Dimension ( \"radial\" , num_rays , true ) ; Dimension [ ] gateR = new Dimension [ number_sweeps ] ; String dim_name = \"gateR\" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { if ( number_sweeps > 1 ) { dim_name = \"gateR_sweep_\" + ( j + 1 ) ; } gateR [ j ] = new Dimension ( dim_name , sweep_bins [ j ] , true ) ; } ncfile . addDimension ( null , scanR ) ; ncfile . addDimension ( null , radial ) ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { ncfile . addDimension ( null , gateR [ j ] ) ; } ArrayList < Dimension > dims0 = new ArrayList < Dimension > ( ) ; ArrayList < Dimension > dims1 = new ArrayList < Dimension > ( ) ; ArrayList < Dimension > dims2 = new ArrayList < Dimension > ( ) ; ArrayList < Dimension > dims3 = new ArrayList < Dimension > ( ) ; ArrayList < Variable > varList = new ArrayList < Variable > ( ) ; Variable [ ] [ ] v = new Variable [ nparams ] [ number_sweeps ] ; String var_name = \"\" ; for ( int j = 0 ; j < nparams ; j ++ ) { int tp = type [ j ] ; var_name = data_name [ tp ] ; for ( int jj = 0 ; jj < number_sweeps ; jj ++ ) { if ( number_sweeps > 1 ) { var_name = data_name [ tp ] + \"_sweep_\" + ( jj + 1 ) ; } v [ j ] [ jj ] = new Variable ( ncfile , null , null , var_name ) ; v [ j ] [ jj ] . setDataType ( DataType . FLOAT ) ; dims2 . add ( radial ) ; dims2 . add ( gateR [ jj ] ) ; v [ j ] [ jj ] . setDimensions ( dims2 ) ; v [ j ] [ jj ] . addAttribute ( new Attribute ( CDM . LONG_NAME , var_name ) ) ; v [ j ] [ jj ] . addAttribute ( new Attribute ( CDM . UNITS , unit [ tp ] ) ) ; String coordinates = \"time elevationR azimuthR distanceR\" ; v [ j ] [ jj ] . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; v [ j ] [ jj ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 999.99f ) ) ; ncfile . addVariable ( null , v [ j ] [ jj ] ) ; varList . add ( v [ j ] [ jj ] ) ; dims2 . clear ( ) ; } } tsu_sec = new int [ number_sweeps ] ; String [ ] tsu = new String [ number_sweeps ] ; String [ ] time_units = new String [ number_sweeps ] ; tsu_sec = volScan . getStartSweep ( ) ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { String st1 = Short . toString ( month ) ; if ( st1 . length ( ) < 2 ) st1 = \"0\" + st1 ; String st2 = Short . toString ( day ) ; if ( st2 . length ( ) < 2 ) st2 = \"0\" + st2 ; date0 = String . valueOf ( year ) + \"-\" + st1 + \"-\" + st2 ; tsu [ i ] = date0 + \"T\" + calcTime ( tsu_sec [ i ] , 0 ) + \"Z\" ; } for ( int j = 0 ; j < number_sweeps ; j ++ ) { time_units [ j ] = \"secs since \" + tsu [ j ] ; } dims0 . add ( radial ) ; // add \"time\" variable\r Variable [ ] time = new Variable [ number_sweeps ] ; String tm = \"time\" ; String tm_name = \"\" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { tm_name = tm ; if ( number_sweeps > 1 ) { tm_name = tm + \"_sweep_\" + ( j + 1 ) ; } time [ j ] = new Variable ( ncfile , null , null , tm_name ) ; time [ j ] . setDataType ( DataType . INT ) ; time [ j ] . setDimensions ( dims0 ) ; time [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , \"time from start of sweep\" ) ) ; time [ j ] . addAttribute ( new Attribute ( CDM . UNITS , time_units [ j ] ) ) ; time [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ) ; time [ j ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 99 ) ) ; ncfile . addVariable ( null , time [ j ] ) ; varList . add ( time [ j ] ) ; } // add \"elevationR\" variable\r Variable [ ] elevationR = new Variable [ number_sweeps ] ; String ele = \"elevationR\" ; String ele_name = \"\" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { ele_name = ele ; if ( number_sweeps > 1 ) { ele_name = ele + \"_sweep_\" + ( j + 1 ) ; } elevationR [ j ] = new Variable ( ncfile , null , null , ele_name ) ; elevationR [ j ] . setDataType ( DataType . FLOAT ) ; elevationR [ j ] . setDimensions ( dims0 ) ; elevationR [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , \"elevation angle\" ) ) ; elevationR [ j ] . addAttribute ( new Attribute ( CDM . UNITS , \"degrees\" ) ) ; elevationR [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . RadialElevation . toString ( ) ) ) ; elevationR [ j ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 999.99f ) ) ; ncfile . addVariable ( null , elevationR [ j ] ) ; varList . add ( elevationR [ j ] ) ; } // add \"azimuthR\" variable\r Variable [ ] azimuthR = new Variable [ number_sweeps ] ; String azim = \"azimuthR\" ; String azim_name = \"\" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { azim_name = azim ; if ( number_sweeps > 1 ) { azim_name = azim + \"_sweep_\" + ( j + 1 ) ; } azimuthR [ j ] = new Variable ( ncfile , null , null , azim_name ) ; azimuthR [ j ] . setDataType ( DataType . FLOAT ) ; azimuthR [ j ] . setDimensions ( dims0 ) ; azimuthR [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , \"azimuth angle\" ) ) ; azimuthR [ j ] . addAttribute ( new Attribute ( CDM . UNITS , \"degrees\" ) ) ; azimuthR [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . RadialAzimuth . toString ( ) ) ) ; azimuthR [ j ] . addAttribute ( new Attribute ( CDM . MISSING_VALUE , - 999.99f ) ) ; ncfile . addVariable ( null , azimuthR [ j ] ) ; varList . add ( azimuthR [ j ] ) ; } // add \"distanceR\" variable\r Variable [ ] distanceR = new Variable [ number_sweeps ] ; String dName = \"distanceR\" ; String dist_name = \"\" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { dist_name = dName ; if ( number_sweeps > 1 ) { dist_name = dName + \"_sweep_\" + ( j + 1 ) ; } distanceR [ j ] = new Variable ( ncfile , null , null , dist_name ) ; distanceR [ j ] . setDataType ( DataType . FLOAT ) ; dims1 . add ( gateR [ j ] ) ; distanceR [ j ] . setDimensions ( dims1 ) ; distanceR [ j ] . addAttribute ( new Attribute ( CDM . LONG_NAME , \"radial distance\" ) ) ; distanceR [ j ] . addAttribute ( new Attribute ( CDM . UNITS , \"m\" ) ) ; distanceR [ j ] . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . RadialDistance . toString ( ) ) ) ; ncfile . addVariable ( null , distanceR [ j ] ) ; varList . add ( distanceR [ j ] ) ; dims1 . clear ( ) ; } // add \"numGates\" variable\r dims3 . add ( scanR ) ; Variable numGates = new Variable ( ncfile , null , null , \"numGates\" ) ; numGates . setDataType ( DataType . INT ) ; numGates . setDimensions ( dims3 ) ; numGates . addAttribute ( new Attribute ( CDM . LONG_NAME , \"number of gates in the sweep\" ) ) ; ncfile . addVariable ( null , numGates ) ; varList . add ( numGates ) ; // add global attributes\r ncfile . addAttribute ( null , new Attribute ( \"definition\" , \"SIGMET-IRIS RAW\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"description\" , \"SIGMET-IRIS data are reading by Netcdf IOSP\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"StationName\" , stnName ) ) ; ncfile . addAttribute ( null , new Attribute ( \"StationName_SetupUtility\" , stnName_util ) ) ; ncfile . addAttribute ( null , new Attribute ( \"radar_lat\" , radar_lat ) ) ; ncfile . addAttribute ( null , new Attribute ( \"radar_lon\" , radar_lon ) ) ; ncfile . addAttribute ( null , new Attribute ( \"ground_height\" , ground_height ) ) ; ncfile . addAttribute ( null , new Attribute ( \"radar_height\" , radar_height ) ) ; ncfile . addAttribute ( null , new Attribute ( \"radar_alt\" , radar_alt ) ) ; ncfile . addAttribute ( null , new Attribute ( \"num_data_types\" , nparams ) ) ; ncfile . addAttribute ( null , new Attribute ( \"number_sweeps\" , number_sweeps ) ) ; String sn = \"start_sweep\" ; String snn = \"\" ; for ( int j = 0 ; j < number_sweeps ; j ++ ) { snn = sn ; if ( number_sweeps > 1 ) { snn = sn + \"_\" + ( j + 1 ) ; } ncfile . addAttribute ( null , new Attribute ( snn , tsu [ j ] ) ) ; } ncfile . addAttribute ( null , new Attribute ( \"num_rays\" , num_rays ) ) ; ncfile . addAttribute ( null , new Attribute ( \"max_number_gates\" , bins ) ) ; ncfile . addAttribute ( null , new Attribute ( \"range_first\" , range_first ) ) ; ncfile . addAttribute ( null , new Attribute ( \"range_last\" , range_last ) ) ; ncfile . addAttribute ( null , new Attribute ( \"DataType\" , \"Radial\" ) ) ; ncfile . addAttribute ( null , new Attribute ( CDM . CONVENTIONS , _Coordinate . Convention ) ) ; // --------- fill all of values in the ncfile ------\r doNetcdfFileCoordinate ( ncfile , volScan . base_time , volScan . year , volScan . month , volScan . day , varList , recHdr ) ; ncfile . finish ( ) ; return varList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill all of the variables / attributes in the ncfile [CODESPLIT] public void doNetcdfFileCoordinate ( ucar . nc2 . NetcdfFile ncfile , int [ ] bst , short [ ] yr , short [ ] m , short [ ] dda , ArrayList < Variable > varList , java . util . Map < String , Number > recHdr ) { // prepare attribute values\r String [ ] unit = { \" \" , \"dbZ\" , \"dbZ\" , \"m/sec\" , \"m/sec\" , \"dB\" } ; String def_datafile = \"SIGMET-IRIS\" ; Short header_length = 80 ; Short ray_header_length = 6 ; int ngates = 0 ; float radar_lat = recHdr . get ( \"radar_lat\" ) . floatValue ( ) ; //System.out.println(\"rad_lat=\"+radar_lat);\r float radar_lon = recHdr . get ( \"radar_lon\" ) . floatValue ( ) ; //System.out.println(\"rad_lon=\"+radar_lon);\r short ground_height = recHdr . get ( \"ground_height\" ) . shortValue ( ) ; //System.out.println(\"ground_H=\"+ground_height);\r short radar_height = recHdr . get ( \"radar_height\" ) . shortValue ( ) ; //System.out.println(\"radar_H=\"+radar_height);\r int radar_alt = ( recHdr . get ( \"radar_alt\" ) . intValue ( ) ) / 100 ; //System.out.println(\"rad_alt=\"+radar_alt);\r short num_rays = recHdr . get ( \"num_rays\" ) . shortValue ( ) ; //System.out.println(\"HERE!! num_rays=\"+num_rays);\r float range_first = ( recHdr . get ( \"range_first\" ) . intValue ( ) ) * 0.01f ; //System.out.println(\"range_1st=\"+range_first);\r float range_last = ( recHdr . get ( \"range_last\" ) . intValue ( ) ) * 0.01f ; //System.out.println(\"step=\"+step);\r short number_sweeps = recHdr . get ( \"number_sweeps\" ) . shortValue ( ) ; int nparams = ( recHdr . get ( \"nparams\" ) . intValue ( ) ) ; //System.out.println(\"nparams=\"+nparams);\r // define date/time\r //int last_t=(int)(ray[nparams*number_sweeps-1][num_rays-1].getTime());\r int last_t = volScan . lastRay . getTime ( ) ; String sss1 = Short . toString ( m [ 0 ] ) ; if ( sss1 . length ( ) < 2 ) sss1 = \"0\" + sss1 ; String sss2 = Short . toString ( dda [ 0 ] ) ; if ( sss2 . length ( ) < 2 ) sss2 = \"0\" + sss2 ; String base_date0 = String . valueOf ( yr [ 0 ] ) + \"-\" + sss1 + \"-\" + sss2 ; String sss11 = Short . toString ( m [ number_sweeps - 1 ] ) ; if ( sss11 . length ( ) < 2 ) sss11 = \"0\" + sss11 ; String sss22 = Short . toString ( dda [ number_sweeps - 1 ] ) ; if ( sss22 . length ( ) < 2 ) sss22 = \"0\" + sss22 ; String base_date1 = String . valueOf ( yr [ number_sweeps - 1 ] ) + \"-\" + sss11 + \"-\" + sss22 ; String start_time = base_date0 + \"T\" + calcTime ( bst [ 0 ] , 0 ) + \"Z\" ; String end_time = base_date1 + \"T\" + calcTime ( bst [ number_sweeps - 1 ] , last_t ) + \"Z\" ; ncfile . addAttribute ( null , new Attribute ( \"time_coverage_start\" , start_time ) ) ; ncfile . addAttribute ( null , new Attribute ( \"time_coverage_end\" , end_time ) ) ; // set all of Variables\r try { int sz = varList . size ( ) ; ArrayFloat . D2 [ ] dataArr = new ArrayFloat . D2 [ nparams * number_sweeps ] ; Index [ ] dataIndex = new Index [ nparams * number_sweeps ] ; Ray [ ] rtemp = new Ray [ ( int ) num_rays ] ; // NCdump.printArray(dataArr[0], \"Total_Power\", System.out, null);\r Variable [ ] distanceR = new Variable [ number_sweeps ] ; ArrayFloat . D1 [ ] distArr = new ArrayFloat . D1 [ number_sweeps ] ; Index [ ] distIndex = new Index [ number_sweeps ] ; String distName = \"distanceR\" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { distName = \"distanceR_sweep_\" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( distName . trim ( ) ) ) { distanceR [ i ] = aVarList ; break ; } } distArr [ i ] = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , distanceR [ i ] . getShape ( ) ) ; distIndex [ i ] = distArr [ i ] . getIndex ( ) ; // for (int jj=0; jj<num_rays; jj++) { rtemp[jj]=ray[i][jj]; }\r ngates = sweep_bins [ i ] ; float stp = calcStep ( range_first , range_last , ( short ) ngates ) ; for ( int ii = 0 ; ii < ngates ; ii ++ ) { distArr [ i ] . setFloat ( distIndex [ i ] . set ( ii ) , ( range_first + ii * stp ) ) ; } } // NCdump.printArray(distArr[0], \"distanceR\", System.out, null);\r List rgp = volScan . getTotalPowerGroups ( ) ; if ( rgp . size ( ) == 0 ) rgp = volScan . getReflectivityGroups ( ) ; List [ ] sgp = new ArrayList [ number_sweeps ] ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { sgp [ i ] = ( List ) rgp . get ( ( short ) i ) ; } Variable [ ] time = new Variable [ number_sweeps ] ; ArrayInt . D1 [ ] timeArr = new ArrayInt . D1 [ number_sweeps ] ; Index [ ] timeIndex = new Index [ number_sweeps ] ; String t_n = \"time\" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { t_n = \"time_sweep_\" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( t_n . trim ( ) ) ) { time [ i ] = aVarList ; break ; } } //                if (time[i].getShape().length == 0) {\r //                    continue;\r //                }\r timeArr [ i ] = ( ArrayInt . D1 ) Array . factory ( DataType . INT , time [ i ] . getShape ( ) ) ; timeIndex [ i ] = timeArr [ i ] . getIndex ( ) ; List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }\r for ( int jj = 0 ; jj < num_rays ; jj ++ ) { timeArr [ i ] . setInt ( timeIndex [ i ] . set ( jj ) , rtemp [ jj ] . getTime ( ) ) ; } } // NCdump.printArray(timeArr[0], \"time\", System.out, null);\r Variable [ ] azimuthR = new Variable [ number_sweeps ] ; ArrayFloat . D1 [ ] azimArr = new ArrayFloat . D1 [ number_sweeps ] ; Index [ ] azimIndex = new Index [ number_sweeps ] ; String azimName = \"azimuthR\" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { azimName = \"azimuthR_sweep_\" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( azimName . trim ( ) ) ) { azimuthR [ i ] = aVarList ; break ; } } azimArr [ i ] = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , azimuthR [ i ] . getShape ( ) ) ; azimIndex [ i ] = azimArr [ i ] . getIndex ( ) ; List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }\r for ( int jj = 0 ; jj < num_rays ; jj ++ ) { azimArr [ i ] . setFloat ( azimIndex [ i ] . set ( jj ) , rtemp [ jj ] . getAz ( ) ) ; } } //NCdump.printArray(azimArr[0], \"azimuthR\", System.out, null);\r Variable [ ] elevationR = new Variable [ number_sweeps ] ; ArrayFloat . D1 [ ] elevArr = new ArrayFloat . D1 [ number_sweeps ] ; Index [ ] elevIndex = new Index [ number_sweeps ] ; String elevName = \"elevationR\" ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { if ( number_sweeps > 1 ) { elevName = \"elevationR_sweep_\" + ( i + 1 ) ; } for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( elevName . trim ( ) ) ) { elevationR [ i ] = aVarList ; break ; } } elevArr [ i ] = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , elevationR [ i ] . getShape ( ) ) ; elevIndex [ i ] = elevArr [ i ] . getIndex ( ) ; List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }\r for ( int jj = 0 ; jj < num_rays ; jj ++ ) { elevArr [ i ] . setFloat ( elevIndex [ i ] . set ( jj ) , rtemp [ jj ] . getElev ( ) ) ; } } // NCdump.printArray(elevArr[0], \"elevationR\", System.out, null);\r Variable numGates = null ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { for ( Variable aVarList : varList ) { if ( ( aVarList . getShortName ( ) ) . equals ( \"numGates\" ) ) { numGates = aVarList ; break ; } } } ArrayInt . D1 gatesArr = ( ArrayInt . D1 ) Array . factory ( DataType . INT , numGates . getShape ( ) ) ; Index gatesIndex = gatesArr . getIndex ( ) ; for ( int i = 0 ; i < number_sweeps ; i ++ ) { List rlist = sgp [ i ] ; for ( int jj = 0 ; jj < num_rays ; jj ++ ) { rtemp [ jj ] = ( Ray ) rlist . get ( jj ) ; } //ray[i][jj]; }\r ngates = rtemp [ 0 ] . getBins ( ) ; gatesArr . setInt ( gatesIndex . set ( i ) , ngates ) ; } for ( int i = 0 ; i < number_sweeps ; i ++ ) { distanceR [ i ] . setCachedData ( distArr [ i ] , false ) ; time [ i ] . setCachedData ( timeArr [ i ] , false ) ; azimuthR [ i ] . setCachedData ( azimArr [ i ] , false ) ; elevationR [ i ] . setCachedData ( elevArr [ i ] , false ) ; } numGates . setCachedData ( gatesArr , false ) ; // startSweep.setCachedData(sweepArr, false);\r //          -------------------------------------------------\r // int b=(int)ray[0][0].getBins();\r // -- Test of readData() and readToByteChannel() -----------------\r /*\r\nRange r1=new Range(356, 359);\r\nRange r2=new Range(0, 15);\r\njava.util.List arlist=new ArrayList();\r\narlist.add(r1);\r\narlist.add(r2);\r\nArray testArr=readData(v[0], new Section(arlist));\r\nNCdump.printArray(testArr, \"Total_Power_sweep_1\", System.out, null);\r\nWritableByteChannel channel=new FileOutputStream(new File(\"C:\\\\netcdf\\\\tt.dat\")).getChannel();\r\nlong ikk=readToByteChannel(v[0], new Section(arlist), channel);\r\nSystem.out.println(\"IKK=\"+ikk);\r\nchannel.close();\r\n      */ //---------------------------------------------------\r } catch ( Exception e ) { System . out . println ( e . toString ( ) ) ; e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from a top level Variable and return a memory resident Array . [CODESPLIT] public Array readData1 ( ucar . nc2 . Variable v2 , Section section ) throws IOException , InvalidRangeException { //doData(raf, ncfile, varList);\r int [ ] sh = section . getShape ( ) ; Array temp = Array . factory ( v2 . getDataType ( ) , sh ) ; long pos0 = 0 ; // Suppose that the data has LayoutRegular\r LayoutRegular index = new LayoutRegular ( pos0 , v2 . getElementSize ( ) , v2 . getShape ( ) , section ) ; if ( v2 . getShortName ( ) . startsWith ( \"time\" ) | v2 . getShortName ( ) . startsWith ( \"numGates\" ) ) { temp = readIntData ( index , v2 ) ; } else { temp = readFloatData ( index , v2 ) ; } return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from a top level Variable of INTEGER data type and return a memory resident Array . [CODESPLIT] public Array readIntData ( LayoutRegular index , Variable v2 ) throws IOException { int [ ] var = ( int [ ] ) ( v2 . read ( ) . get1DJavaArray ( v2 . getDataType ( ) ) ) ; int [ ] data = new int [ ( int ) index . getTotalNelems ( ) ] ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; System . arraycopy ( var , ( int ) chunk . getSrcPos ( ) / 4 , data , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return Array . factory ( v2 . getDataType ( ) , new int [ ] { ( int ) index . getTotalNelems ( ) } , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from a top level Variable and send data to a WritableByteChannel . [CODESPLIT] public long readToByteChannel11 ( ucar . nc2 . Variable v2 , Section section , WritableByteChannel channel ) throws java . io . IOException , ucar . ma2 . InvalidRangeException { Array data = readData ( v2 , section ) ; float [ ] ftdata = new float [ ( int ) data . getSize ( ) ] ; byte [ ] bytedata = new byte [ ( int ) data . getSize ( ) * 4 ] ; IndexIterator iter = data . getIndexIterator ( ) ; int i = 0 ; ByteBuffer buffer = ByteBuffer . allocateDirect ( bytedata . length ) ; while ( iter . hasNext ( ) ) { ftdata [ i ] = iter . getFloatNext ( ) ; bytedata [ i ] = new Float ( ftdata [ i ] ) . byteValue ( ) ; buffer . put ( bytedata [ i ] ) ; i ++ ; } buffer = ByteBuffer . wrap ( bytedata ) ; // write the bytes to the channel\r int count = channel . write ( buffer ) ; System . out . println ( \"COUNT=\" + count ) ; // check if all bytes where written\r if ( buffer . hasRemaining ( ) ) { // if not all bytes were written, move the unwritten bytes to the beginning and\r // set position just after the last unwritten byte\r buffer . compact ( ) ; } else { buffer . clear ( ) ; } return ( long ) count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate radial elevation of each ray [CODESPLIT] static float calcElev ( short angle ) { final double maxval = 65536.0 ; double ang = ( double ) angle ; if ( angle < 0 ) ang = ( ~ angle ) + 1 ; double temp = ( ang / maxval ) * 360.0 ; BigDecimal bd = new BigDecimal ( temp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate distance between sequential bins in a ray [CODESPLIT] static float calcStep ( float range_first , float range_last , short num_bins ) { float step = ( range_last - range_first ) / ( num_bins - 1 ) ; BigDecimal bd = new BigDecimal ( step ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate azimuth of a ray [CODESPLIT] static float calcAz ( short az0 , short az1 ) { // output in deg\r float azim0 = calcAngle ( az0 ) ; float azim1 = calcAngle ( az1 ) ; float d = 0.0f ; d = Math . abs ( azim0 - azim1 ) ; if ( ( az0 < 0 ) & ( az1 > 0 ) ) { d = Math . abs ( 360.0f - azim0 ) + Math . abs ( azim1 ) ; } double temp = azim0 + d * 0.5 ; if ( temp > 360.0 ) { temp -= 360.0 ; } BigDecimal bd = new BigDecimal ( temp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate data values from raw ingest data [CODESPLIT] static float calcData ( Map < String , Number > recHdr , short dty , byte data ) { short [ ] coef = { 1 , 2 , 3 , 4 } ; // MultiPRF modes\r short multiprf = recHdr . get ( \"multiprf\" ) . shortValue ( ) ; float vNyq = recHdr . get ( \"vNyq\" ) . floatValue ( ) ; double temp = - 999.99 ; switch ( dty ) { default : // dty=1,2 -total_power, reflectivity (dBZ)\r if ( data != 0 ) { temp = ( ( ( int ) data & 0xFF ) - 64 ) * 0.5 ; } break ; case 3 : // dty=3 - mean velocity (m/sec)\r if ( data != 0 ) { temp = ( ( ( ( int ) data & 0xFF ) - 128 ) / 127.0 ) * vNyq * coef [ multiprf ] ; } break ; case 4 : // dty=4 - spectrum width (m/sec)\r if ( data != 0 ) { double v = ( ( ( ( int ) data & 0xFF ) - 128 ) / 127.0 ) * vNyq * coef [ multiprf ] ; temp = ( ( ( int ) data & 0xFF ) / 256.0 ) * v ; } break ; case 5 : // dty=5 - differential reflectivity (dB)\r if ( data != 0 ) { temp = ( ( ( ( int ) data & 0xFF ) - 128 ) / 16.0 ) ; } break ; } BigDecimal bd = new BigDecimal ( temp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate time as hh : mm : ss [CODESPLIT] static String calcTime ( int t , int t0 ) { StringBuilder tim = new StringBuilder ( ) ; int [ ] tt = new int [ 3 ] ; int mmh = ( t + t0 ) / 60 ; tt [ 2 ] = ( t + t0 ) % 60 ; // Define SEC\r tt [ 0 ] = mmh / 60 ; // Define HOUR\r tt [ 1 ] = mmh % 60 ; // Define MIN\r for ( int i = 0 ; i < 3 ; i ++ ) { String s = Integer . toString ( tt [ i ] ) ; int len = s . length ( ) ; if ( len < 2 ) { s = \"0\" + tt [ i ] ; } if ( i != 2 ) s += \":\" ; tim . append ( s ) ; } return tim . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate of Nyquist velocity [CODESPLIT] static float calcNyquist ( int prf , int wave ) { double tmp = ( prf * wave * 0.01 ) * 0.25 ; tmp = tmp * 0.01 ; //Make it m/sec\r BigDecimal bd = new BigDecimal ( tmp ) ; BigDecimal result = bd . setScale ( 2 , RoundingMode . HALF_DOWN ) ; return result . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the builder to make the Vertical Transform function [CODESPLIT] public VerticalTransform makeVerticalTransform ( NetcdfDataset ds , Dimension timeDim ) { return builder . makeMathTransform ( ds , timeDim , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "partitions can be removed ( ! ) [CODESPLIT] public void removePartition ( MCollection partition ) { for ( MFile mfile : partIndexFiles ) { if ( mfile . getName ( ) . equalsIgnoreCase ( partition . getCollectionName ( ) ) ) { List < MFile > part = new ArrayList <> ( partIndexFiles ) ; part . remove ( mfile ) ; partIndexFiles = part ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write equivilent uncompressed version of the file . [CODESPLIT] private RandomAccessFile uncompress ( RandomAccessFile raf2 , String ufilename , boolean debug ) throws IOException { raf2 . seek ( 0 ) ; byte [ ] header = new byte [ Cinrad2Record . FILE_HEADER_SIZE ] ; int bytesRead = raf2 . read ( header ) ; if ( bytesRead != header . length ) { throw new IOException ( \"Error reading CINRAD header -- got \" + bytesRead + \" rather than\" + header . length ) ; } RandomAccessFile dout2 = new RandomAccessFile ( ufilename , \"rw\" ) ; boolean eof = false ; int numCompBytes ; byte [ ] ubuff = new byte [ 40000 ] ; byte [ ] obuff = new byte [ 40000 ] ; try { dout2 . write ( header ) ; CBZip2InputStream cbzip2 = new CBZip2InputStream ( ) ; while ( ! eof ) { try { numCompBytes = raf2 . readInt ( ) ; if ( numCompBytes == - 1 ) { if ( debug ) log . debug ( \"  done: numCompBytes=-1 \" ) ; break ; } } catch ( EOFException ee ) { if ( debug ) log . debug ( \"  got EOFException \" ) ; break ; // assume this is ok } if ( debug ) { log . debug ( \"reading compressed bytes \" + numCompBytes + \" input starts at \" + raf2 . getFilePointer ( ) + \"; output starts at \" + dout2 . getFilePointer ( ) ) ; } /*\n        * For some stupid reason, the last block seems to\n        * have the number of bytes negated.  So, we just\n        * assume that any negative number (other than -1)\n        * is the last block and go on our merry little way.\n        */ if ( numCompBytes < 0 ) { if ( debug ) log . debug ( \"last block?\" + numCompBytes ) ; numCompBytes = - numCompBytes ; eof = true ; } byte [ ] buf = new byte [ numCompBytes ] ; raf2 . readFully ( buf ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( buf , 2 , numCompBytes - 2 ) ; //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis); cbzip2 . setStream ( bis ) ; int total = 0 ; int nread ; /*\n        while ((nread = cbzip2.read(ubuff)) != -1) {\n          dout2.write(ubuff, 0, nread);\n          total += nread;\n        }\n        */ try { while ( ( nread = cbzip2 . read ( ubuff ) ) != - 1 ) { if ( total + nread > obuff . length ) { byte [ ] temp = obuff ; obuff = new byte [ temp . length * 2 ] ; System . arraycopy ( temp , 0 , obuff , 0 , temp . length ) ; } System . arraycopy ( ubuff , 0 , obuff , total , nread ) ; total += nread ; } if ( obuff . length >= 0 ) dout2 . write ( obuff , 0 , total ) ; } catch ( BZip2ReadException ioe ) { log . debug ( \"Cinrad2IOSP.uncompress \" , ioe ) ; } float nrecords = ( float ) ( total / 2432.0 ) ; if ( debug ) log . debug ( \"  unpacked \" + total + \" num bytes \" + nrecords + \" records; ouput ends at \" + dout2 . getFilePointer ( ) ) ; } dout2 . flush ( ) ; } catch ( EOFException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { dout2 . close ( ) ; throw e ; } return dout2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the debug flags [CODESPLIT] static public void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugOpen = debugFlag . isSet ( \"Grid/open\" ) ; debugMissing = debugFlag . isSet ( \"Grid/missing\" ) ; debugMissingDetails = debugFlag . isSet ( \"Grid/missingDetails\" ) ; debugProj = debugFlag . isSet ( \"Grid/projection\" ) ; debugVert = debugFlag . isSet ( \"Grid/vertical\" ) ; debugTiming = debugFlag . isSet ( \"Grid/timing\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set how indexes are used for both open and sync [CODESPLIT] static public void setExtendIndex ( boolean b ) { indexFileModeOnOpen = b ? IndexExtendMode . extendwrite : IndexExtendMode . readonly ; indexFileModeOnSync = b ? IndexExtendMode . extendwrite : IndexExtendMode . readonly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the service provider for reading . [CODESPLIT] @ Override public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data for the variable [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { long start = System . currentTimeMillis ( ) ; Array dataArray = Array . factory ( DataType . FLOAT , section . getShape ( ) ) ; GridVariable pv = ( GridVariable ) v2 . getSPobject ( ) ; // Canonical ordering is ens, time, level, lat, lon int rangeIdx = 0 ; Range ensRange = pv . hasEnsemble ( ) ? section . getRange ( rangeIdx ++ ) : new Range ( 0 , 0 ) ; Range timeRange = ( section . getRank ( ) > 2 ) ? section . getRange ( rangeIdx ++ ) : new Range ( 0 , 0 ) ; Range levRange = pv . hasVert ( ) ? section . getRange ( rangeIdx ++ ) : new Range ( 0 , 0 ) ; Range yRange = section . getRange ( rangeIdx ++ ) ; Range xRange = section . getRange ( rangeIdx ) ; IndexIterator ii = dataArray . getIndexIterator ( ) ; for ( int ensIdx : ensRange ) { for ( int timeIdx : timeRange ) { for ( int levelIdx : levRange ) { readXY ( v2 , ensIdx , timeIdx , levelIdx , yRange , xRange , ii ) ; } } } if ( debugTiming ) { long took = System . currentTimeMillis ( ) - start ; System . out . println ( \"  read data took=\" + took + \" msec \" ) ; } return dataArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read one YX array [CODESPLIT] private void readXY ( Variable v2 , int ensIdx , int timeIdx , int levIdx , Range yRange , Range xRange , IndexIterator ii ) throws IOException , InvalidRangeException { GridVariable pv = ( GridVariable ) v2 . getSPobject ( ) ; GridHorizCoordSys hsys = pv . getHorizCoordSys ( ) ; int nx = hsys . getNx ( ) ; GridRecord record = pv . findRecord ( ensIdx , timeIdx , levIdx ) ; if ( record == null ) { Attribute att = v2 . findAttribute ( \"missing_value\" ) ; float missing_value = ( att == null ) ? - 9999.0f : att . getNumericValue ( ) . floatValue ( ) ; int xyCount = yRange . length ( ) * xRange . length ( ) ; for ( int j = 0 ; j < xyCount ; j ++ ) { ii . setFloatNext ( missing_value ) ; } return ; } // otherwise read it float [ ] data = _readData ( record ) ; if ( data == null ) { _readData ( record ) ; // debug return ; } // LOOK can improve with System.copy ?? for ( int y : yRange ) { for ( int x : xRange ) { int index = y * nx + x ; ii . setFloatNext ( data [ index ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this XY level missing? [CODESPLIT] public boolean isMissingXY ( Variable v2 , int timeIdx , int ensIdx , int levIdx ) throws InvalidRangeException { GridVariable pv = ( GridVariable ) v2 . getSPobject ( ) ; if ( ( timeIdx < 0 ) || ( timeIdx >= pv . getNTimes ( ) ) ) { throw new InvalidRangeException ( \"timeIdx=\" + timeIdx ) ; } if ( ( levIdx < 0 ) || ( levIdx >= pv . getVertNlevels ( ) ) ) { throw new InvalidRangeException ( \"levIdx=\" + levIdx ) ; } if ( ( ensIdx < 0 ) || ( ensIdx >= pv . getNEnsembles ( ) ) ) { throw new InvalidRangeException ( \"ensIdx=\" + ensIdx ) ; } return ( null == pv . findRecord ( ensIdx , timeIdx , levIdx ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The goal of parse () is to extract info from the underlying HttpRequest and cache it in this object . <p > In particular the incoming URL needs to be decomposed into multiple pieces . Certain assumptions are made : 1 . every incoming url is of the form ( a ) http ( s ) : // host : port / d4ts / or ( b ) http ( s ) : // host : port / d4ts / <datasetpath > ?query Case a indicates that the front page is to be returned . Case b indicates a request for a dataset ( or dsr ) and its value is determined by its extensions . The query may be absent . We want to extract the following pieces . 1 . ( In URI parlance ) The scheme plus the authority : http : // host : port 3 . The return type : depending on the last extension ( e . g . . txt ) . 4 . The requested value : depending on the next to last extension ( e . g . . dap ) . 5 . The suffix path specifying the actual dataset : datasetpath with return and request type extensions removed . 6 . The url path = servletpath + datasetpath . 7 . The query part . [CODESPLIT] protected void parse ( ) throws IOException { this . url = request . getRequestURL ( ) . toString ( ) ; // does not include query // The mock servlet code does not construct a query string, // so if we are doing testing, construct from parametermap. if ( DapController . TESTING ) { this . querystring = makeQueryString ( this . request ) ; } else { this . querystring = request . getQueryString ( ) ; // raw (undecoded) } XURI xuri ; try { xuri = new XURI ( this . url ) . parseQuery ( this . querystring ) ; } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } // Now, construct various items StringBuilder buf = new StringBuilder ( ) ; buf . append ( request . getScheme ( ) ) ; buf . append ( \"://\" ) ; buf . append ( request . getServerName ( ) ) ; int port = request . getServerPort ( ) ; if ( port > 0 ) { buf . append ( \":\" ) ; buf . append ( port ) ; } this . server = buf . toString ( ) ; // There appears to be some inconsistency in how the url path is divided up // depending on if this is a spring controller vs a raw servlet. // Try to canonicalize so that context path always ends with id // and servletpath does not start with it. String id = controller . getServletID ( ) ; String sp = DapUtil . canonicalpath ( request . getServletPath ( ) ) ; String cp = DapUtil . canonicalpath ( request . getContextPath ( ) ) ; if ( ! cp . endsWith ( id ) ) // probably spring ; contextpath does not ends with id cp = cp + \"/\" + id ; buf . append ( cp ) ; this . controllerpath = buf . toString ( ) ; sp = HTTPUtil . relpath ( sp ) ; if ( sp . startsWith ( id ) ) // probably spring also sp = sp . substring ( id . length ( ) ) ; this . datasetpath = HTTPUtil . relpath ( sp ) ; this . datasetpath = DapUtil . nullify ( this . datasetpath ) ; this . mode = null ; if ( this . datasetpath == null ) { // Presume mode is a capabilities request this . mode = RequestMode . CAPABILITIES ; this . format = ResponseFormat . HTML ; } else { // Decompose path by '.' String [ ] pieces = this . datasetpath . split ( \"[.]\" ) ; // Search backward looking for the mode (dmr or dap) // meanwhile capturing the format extension int modepos = 0 ; for ( int i = pieces . length - 1 ; i >= 1 ; i -- ) { //ignore first piece String ext = pieces [ i ] ; // We assume that the set of response formats does not interset the set of request modes RequestMode mode = RequestMode . modeFor ( ext ) ; ResponseFormat format = ResponseFormat . formatFor ( ext ) ; if ( mode != null ) { // Stop here this . mode = mode ; modepos = i ; break ; } else if ( format != null ) { if ( this . format != null ) throw new DapException ( \"Multiple response formats specified: \" + ext ) . setCode ( HttpServletResponse . SC_BAD_REQUEST ) ; this . format = format ; } } // Set the datasetpath to the entire path before the mode defining extension. if ( modepos > 0 ) this . datasetpath = DapUtil . join ( pieces , \".\" , 0 , modepos ) ; } if ( this . mode == null ) this . mode = RequestMode . DSR ; if ( this . format == null ) this . format = ResponseFormat . NONE ; // Parse the query string into a Map if ( querystring != null && querystring . length ( ) > 0 ) this . queries = xuri . getQueryFields ( ) ; // For testing purposes, get the desired endianness to use with replies String p = queryLookup ( Dap4Util . DAP4ENDIANTAG ) ; if ( p != null ) { Integer oz = DapUtil . stringToInteger ( p ) ; if ( oz == null ) this . order = ByteOrder . LITTLE_ENDIAN ; else this . order = ( oz != 0 ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; } // Ditto for no checksum p = queryLookup ( Dap4Util . DAP4CSUMTAG ) ; if ( p != null ) { this . checksummode = ChecksumMode . modeFor ( p ) ; } if ( this . checksummode == null ) this . checksummode = DEFAULTCSUM ; if ( DEBUG ) { DapLog . debug ( \"DapRequest: controllerpath =\" + this . controllerpath ) ; DapLog . debug ( \"DapRequest: extension=\" + ( this . mode == null ? \"null\" : this . mode . extension ( ) ) ) ; DapLog . debug ( \"DapRequest: datasetpath=\" + this . datasetpath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the x y bounding box in projection coordinates . [CODESPLIT] public ProjectionRect getBoundingBox ( ) { if ( mapArea == null ) { CoordinateAxis horizXaxis = getXHorizAxis ( ) ; CoordinateAxis horizYaxis = getYHorizAxis ( ) ; if ( ( horizXaxis == null ) || ! horizXaxis . isNumeric ( ) || ( horizYaxis == null ) || ! horizYaxis . isNumeric ( ) ) return null ; // impossible // x,y may be 2D if ( ( horizXaxis instanceof CoordinateAxis2D ) && ( horizYaxis instanceof CoordinateAxis2D ) ) { // could try to optimize this - just get corners or something CoordinateAxis2D xaxis2 = ( CoordinateAxis2D ) horizXaxis ; CoordinateAxis2D yaxis2 = ( CoordinateAxis2D ) horizYaxis ; mapArea = null ; // getBBfromCorners(xaxis2, yaxis2);  LOOK LOOK // mapArea = new ProjectionRect(horizXaxis.getMinValue(), horizYaxis.getMinValue(), //         horizXaxis.getMaxValue(), horizYaxis.getMaxValue()); } else { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) horizXaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) horizYaxis ; /* add one percent on each side if its a projection. WHY?\n        double dx = 0.0, dy = 0.0;\n        if (!isLatLon()) {\n          dx = .01 * (xaxis1.getCoordEdge((int) xaxis1.getSize()) - xaxis1.getCoordEdge(0));\n          dy = .01 * (yaxis1.getCoordEdge((int) yaxis1.getSize()) - yaxis1.getCoordEdge(0));\n        }\n\n        mapArea = new ProjectionRect(xaxis1.getCoordEdge(0) - dx, yaxis1.getCoordEdge(0) - dy,\n            xaxis1.getCoordEdge((int) xaxis1.getSize()) + dx,\n            yaxis1.getCoordEdge((int) yaxis1.getSize()) + dy); */ mapArea = new ProjectionRect ( xaxis1 . getCoordEdge ( 0 ) , yaxis1 . getCoordEdge ( 0 ) , xaxis1 . getCoordEdge ( ( int ) xaxis1 . getSize ( ) ) , yaxis1 . getCoordEdge ( ( int ) yaxis1 . getSize ( ) ) ) ; } } return mapArea ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Lat / Lon coordinates of the midpoint of a grid cell using the x y indices [CODESPLIT] public LatLonPoint getLatLon ( int xindex , int yindex ) { double x , y ; CoordinateAxis horizXaxis = getXHorizAxis ( ) ; CoordinateAxis horizYaxis = getYHorizAxis ( ) ; if ( horizXaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizXaxis ; x = horiz1D . getCoordValue ( xindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizXaxis ; x = horiz2D . getCoordValue ( yindex , xindex ) ; } if ( horizYaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizYaxis ; y = horiz1D . getCoordValue ( yindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizYaxis ; y = horiz2D . getCoordValue ( yindex , xindex ) ; } return isLatLon ( ) ? new LatLonPointImpl ( y , x ) : getLatLon ( x , y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get horizontal bounding box in lat lon coordinates . [CODESPLIT] public LatLonRect getLatLonBoundingBox ( ) { if ( llbb == null ) { if ( ( getXHorizAxis ( ) instanceof CoordinateAxis2D ) && ( getYHorizAxis ( ) instanceof CoordinateAxis2D ) ) { return null ; } CoordinateAxis horizXaxis = getXHorizAxis ( ) ; CoordinateAxis horizYaxis = getYHorizAxis ( ) ; if ( isLatLon ( ) ) { double startLat = horizYaxis . getMinValue ( ) ; double startLon = horizXaxis . getMinValue ( ) ; double deltaLat = horizYaxis . getMaxValue ( ) - startLat ; double deltaLon = horizXaxis . getMaxValue ( ) - startLon ; LatLonPoint llpt = new LatLonPointImpl ( startLat , startLon ) ; llbb = new LatLonRect ( llpt , deltaLat , deltaLon ) ; } else { ProjectionImpl dataProjection = getProjection ( ) ; ProjectionRect bb = getBoundingBox ( ) ; if ( bb != null ) llbb = dataProjection . projToLatLonBB ( bb ) ; } } return llbb ; /*  // look at all 4 corners of the bounding box\n        LatLonPointImpl llpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getLowerLeftPoint(), new LatLonPointImpl());\n        LatLonPointImpl lrpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getLowerRightPoint(), new LatLonPointImpl());\n        LatLonPointImpl urpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getUpperRightPoint(), new LatLonPointImpl());\n        LatLonPointImpl ulpt = (LatLonPointImpl) dataProjection.projToLatLon(bb.getUpperLeftPoint(), new LatLonPointImpl());\n\n        // Check if grid contains poles.\n        boolean includesNorthPole = false;\n        int[] resultNP;\n        resultNP = findXYindexFromLatLon(90.0, 0, null);\n        if (resultNP[0] != -1 && resultNP[1] != -1)\n          includesNorthPole = true;\n        boolean includesSouthPole = false;\n        int[] resultSP;\n        resultSP = findXYindexFromLatLon(-90.0, 0, null);\n        if (resultSP[0] != -1 && resultSP[1] != -1)\n          includesSouthPole = true;\n\n        if (includesNorthPole && !includesSouthPole) {\n          llbb = new LatLonRect(llpt, new LatLonPointImpl(90.0, 0.0)); // ??? lon=???\n          llbb.extend(lrpt);\n          llbb.extend(urpt);\n          llbb.extend(ulpt);\n          // OR\n          //llbb.extend( new LatLonRect( llpt, lrpt ));\n          //llbb.extend( new LatLonRect( lrpt, urpt ) );\n          //llbb.extend( new LatLonRect( urpt, ulpt ) );\n          //llbb.extend( new LatLonRect( ulpt, llpt ) );\n        } else if (includesSouthPole && !includesNorthPole) {\n          llbb = new LatLonRect(llpt, new LatLonPointImpl(-90.0, -180.0)); // ??? lon=???\n          llbb.extend(lrpt);\n          llbb.extend(urpt);\n          llbb.extend(ulpt);\n        } else {\n          double latMin = Math.min(llpt.getLatitude(), lrpt.getLatitude());\n          double latMax = Math.max(ulpt.getLatitude(), urpt.getLatitude());\n\n          // longitude is a bit tricky as usual\n          double lonMin = getMinOrMaxLon(llpt.getLongitude(), ulpt.getLongitude(), true);\n          double lonMax = getMinOrMaxLon(lrpt.getLongitude(), urpt.getLongitude(), false);\n\n          llpt.set(latMin, lonMin);\n          urpt.set(latMax, lonMax);\n\n          llbb = new LatLonRect(llpt, urpt);\n        }\n      }\n    }  */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This reports how well different compression schemes would work on the specific data . Should be renamed [CODESPLIT] public static void calcScaleOffset ( GribData . Bean bean1 , Formatter f ) { float [ ] data ; try { data = bean1 . readData ( ) ; } catch ( IOException e ) { f . format ( \"IOException %s\" , e . getMessage ( ) ) ; return ; } int npoints = data . length ; // we always use unsigned packed // \"If the packed values are intended to be interpreted as signed/unsigned integers\" // http://www.unidata.ucar.edu/software/netcdf/docs/BestPractices.html int nbits = bean1 . getNBits ( ) ; int width = ( 2 << nbits - 1 ) - 2 ; // unsigned int missing_value = ( 2 << nbits - 1 ) - 1 ; // all ones - reserved for missing value // int width2 = (2 << (nbits-1)) - 1;  // signed f . format ( \" nbits = %d%n\" , nbits ) ; f . format ( \" npoints = %d%n\" , npoints ) ; f . format ( \" width = %d (0x%s) %n\" , width , Long . toHexString ( width ) ) ; f . format ( \" scale = %g %n\" , bean1 . getScale ( ) ) ; f . format ( \" resolution = %g %n\" , bean1 . getScale ( ) / 2 ) ; f . format ( \" range = %f %n%n\" , bean1 . getMaximum ( ) - bean1 . getMinimum ( ) ) ; float dataMin = Float . MAX_VALUE ; float dataMax = - Float . MAX_VALUE ; for ( float fd : data ) { if ( Float . isNaN ( fd ) ) continue ; dataMin = Math . min ( dataMin , fd ) ; dataMax = Math . max ( dataMax , fd ) ; } f . format ( \"           actual    computed%n\" ) ; f . format ( \" dataMin = %8f %8f%n\" , dataMin , bean1 . getMinimum ( ) ) ; f . format ( \" dataMax = %8f %8f%n\" , dataMax , bean1 . getMaximum ( ) ) ; f . format ( \" actual range = %f%n\" , ( dataMax - dataMin ) ) ; // scale_factor =(dataMax - dataMin) / (2^n - 1) // add_offset = dataMin + 2^(n-1) * scale_factor double scale_factor = ( dataMax - dataMin ) / width ; // float add_offset = dataMin + width2 * scale_factor / 2; // signed double add_offset = dataMin ; // unsigned f . format ( \" scale_factor = %g%n\" , scale_factor ) ; f . format ( \" add_offset = %g%n\" , add_offset ) ; // unpacked_data_value = packed_data_value * scale_factor + add_offset // packed_data_value = nint((unpacked_data_value - add_offset) / scale_factor) ByteBuffer bb = ByteBuffer . allocate ( 4 * npoints ) ; IntBuffer intBuffer = bb . asIntBuffer ( ) ; double diffMax = - Double . MAX_VALUE ; double diffTotal = 0 ; double diffTotal2 = 0 ; for ( float fd : data ) { if ( Float . isNaN ( fd ) ) { intBuffer . put ( missing_value ) ; continue ; } // otherwise pack it int packed_data = ( int ) Math . round ( ( fd - add_offset ) / scale_factor ) ; // nint((unpacked_data_value - add_offset) / scale_factor) double unpacked_data = packed_data * scale_factor + add_offset ; double diff = Math . abs ( fd - unpacked_data ) ; if ( diff > scale_factor / 2 ) f . format ( \"***   org=%g, packed_data=%d unpacked=%g diff = %g%n\" , fd , packed_data , unpacked_data , diff ) ; diffMax = Math . max ( diffMax , diff ) ; diffTotal += diff ; diffTotal2 += diff * diff ; intBuffer . put ( packed_data ) ; } f . format ( \"%n max_diff = %g%n\" , diffMax ) ; f . format ( \" avg_diff = %g%n\" , diffTotal / data . length ) ; // Math.sqrt( sumsq/n - avg * avg) double mean = diffTotal / npoints ; double var = ( diffTotal2 / npoints - mean * mean ) ; f . format ( \" std_diff = %g%n\" , Math . sqrt ( var ) ) ; f . format ( \"%nCompression%n\" ) ; f . format ( \" number of values = %d%n\" , npoints ) ; f . format ( \" uncompressed as floats = %d%n\" , npoints * 4 ) ; int packedBitsLen = npoints * nbits / 8 ; f . format ( \" uncompressed packed bits = %d%n\" , packedBitsLen ) ; f . format ( \" grib data length = %d%n\" , bean1 . getDataLength ( ) ) ; f . format ( \" grib msg length = %d%n\" , bean1 . getMsgLength ( ) ) ; byte [ ] bdata = convertToBytes ( data ) ; byte [ ] scaledData = bb . array ( ) ; //////////////////////////////////////////// f . format ( \"%ndeflate (float)%n\" ) ; Deflater deflater = new Deflater ( ) ; deflater . setInput ( bdata ) ; deflater . finish ( ) ; int compressedSize = deflater . deflate ( new byte [ 10 * npoints ] ) ; deflater . end ( ) ; f . format ( \" compressedSize = %d%n\" , compressedSize ) ; f . format ( \" ratio floats / size = %f%n\" , ( float ) ( npoints * 4 ) / compressedSize ) ; f . format ( \" ratio packed bits / size = %f%n\" , ( float ) packedBitsLen / compressedSize ) ; f . format ( \" ratio size / grib = %f%n\" , ( float ) compressedSize / bean1 . getMsgLength ( ) ) ; ///////////////////////////////////////////////////////// f . format ( \"%ndeflate (scaled ints)%n\" ) ; deflater = new Deflater ( ) ; deflater . setInput ( scaledData ) ; deflater . finish ( ) ; compressedSize = deflater . deflate ( new byte [ 10 * npoints ] ) ; deflater . end ( ) ; f . format ( \" compressedSize = %d%n\" , compressedSize ) ; f . format ( \" ratio floats / size = %f%n\" , ( float ) ( npoints * 4 ) / compressedSize ) ; f . format ( \" ratio packed bits / size = %f%n\" , ( float ) packedBitsLen / compressedSize ) ; f . format ( \" ratio size / grib = %f%n\" , ( float ) compressedSize / bean1 . getMsgLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this when you have set all the sequence lengths . [CODESPLIT] public void finish ( ) { sequenceOffset = new int [ nelems ] ; total = 0 ; for ( int i = 0 ; i < nelems ; i ++ ) { sequenceOffset [ i ] = total ; total += sequenceLen [ i ] ; } sdata = new StructureData [ nelems ] ; for ( int i = 0 ; i < nelems ; i ++ ) sdata [ i ] = new StructureDataA ( this , sequenceOffset [ i ] ) ; // make the member arrays for ( StructureMembers . Member m : members . getMembers ( ) ) { int [ ] mShape = m . getShape ( ) ; int [ ] shape = new int [ mShape . length + 1 ] ; shape [ 0 ] = total ; System . arraycopy ( mShape , 0 , shape , 1 , mShape . length ) ; // LOOK not doing nested structures Array data = Array . factory ( m . getDataType ( ) , shape ) ; m . setDataArray ( data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flatten the Structures into a 1D array of Structures of length getTotalNumberOfStructures () . [CODESPLIT] public ArrayStructure flatten ( ) { ArrayStructureW aw = new ArrayStructureW ( getStructureMembers ( ) , new int [ ] { total } ) ; for ( int i = 0 ; i < total ; i ++ ) { StructureData sdata = new StructureDataA ( this , i ) ; aw . setStructureData ( sdata , i ) ; } return aw ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Blank fill sbuff with blanks until position tabStop . [CODESPLIT] public static void tab ( StringBuffer sbuff , int tabStop , boolean alwaysOne ) { int len = sbuff . length ( ) ; if ( tabStop > len ) { sbuff . setLength ( tabStop ) ; for ( int i = len ; i < tabStop ; i ++ ) { sbuff . setCharAt ( i , ' ' ) ; } } else if ( alwaysOne ) { sbuff . setLength ( len + 1 ) ; sbuff . setCharAt ( len , ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new string by padding the existing one with blanks to specified width . Do nothing if length is already greater or equal to width . [CODESPLIT] public static String pad ( String s , int width , boolean rightJustify ) { if ( s . length ( ) >= width ) { return s ; } StringBuilder sbuff = new StringBuilder ( width ) ; int need = width - s . length ( ) ; sbuff . setLength ( need ) ; for ( int i = 0 ; i < need ; i ++ ) { sbuff . setCharAt ( i , ' ' ) ; } if ( rightJustify ) { sbuff . append ( s ) ; } else { sbuff . insert ( 0 , s ) ; } return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format an integer value . [CODESPLIT] public static String i ( int v , int width ) { return pad ( Integer . toString ( v ) , width , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format a long value . [CODESPLIT] public static String l ( long v , int width ) { return pad ( Long . toString ( v ) , width , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Double value formatting with minimum number of significant figures in a specified width . This will try to do a reasonable job of getting a representation that has min_sigfig significant figures in the specified width . Right now all it does is call d ( double d int min_sigfig ) and left pad out to width chars . [CODESPLIT] public static String d ( double d , int min_sigfig , int width ) { String s = Format . d ( d , min_sigfig ) ; return pad ( s , width , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Nicely formatted representation of bytes eg turn 5 . 636E7 into [CODESPLIT] public static String formatByteSize ( double size ) { String unit = null ; if ( size > 1.0e15 ) { unit = \"Pbytes\" ; size *= 1.0e-15 ; } else if ( size > 1.0e12 ) { unit = \"Tbytes\" ; size *= 1.0e-12 ; } else if ( size > 1.0e9 ) { unit = \"Gbytes\" ; size *= 1.0e-9 ; } else if ( size > 1.0e6 ) { unit = \"Mbytes\" ; size *= 1.0e-6 ; } else if ( size > 1.0e3 ) { unit = \"Kbytes\" ; size *= 1.0e-3 ; } else { unit = \"bytes\" ; } return Format . d ( size , 4 ) + \" \" + unit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show the value of a double to the significant figures [CODESPLIT] private static void show ( double d , int sigfig ) { System . out . println ( \"Format.d(\" + d + \",\" + sigfig + \") == \" + Format . d ( d , sigfig ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show the value of a double with specified number of decimal places [CODESPLIT] private static void show2 ( double d , int dec_places ) { System . out . println ( \"Format.dfrac(\" + d + \",\" + dec_places + \") == \" + Format . dfrac ( d , dec_places ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the information as an XML document [CODESPLIT] public String writeXML ( Document doc ) { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the information as an XML document [CODESPLIT] public void writeXML ( Document doc , OutputStream os ) throws IOException { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; fmt . output ( doc , os ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the Dataset Description XML document from this GridDataset [CODESPLIT] public Document makeDatasetDescription ( ) { Element rootElem = new Element ( \"gridDataset\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"location\" , gds . getLocation ( ) ) ; if ( null != path ) rootElem . setAttribute ( \"path\" , path ) ; /* dimensions\r\n    List dims = getDimensions(gds);\r\n    for (int j = 0; j < dims.size(); j++) {\r\n      Dimension dim = (Dimension) dims.get(j);\r\n      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeDimension(dim, null));\r\n    } */ // coordinate axes\r for ( CoordinateAxis axis : getCoordAxes ( gds ) ) { rootElem . addContent ( writeAxis ( axis ) ) ; } /* grids\r\n    List grids = gds.getGrids();\r\n    Collections.sort(grids, new GridComparator());\r\n    for (int i = 0; i < grids.size(); i++) {\r\n      GeoGrid grid = (GeoGrid) grids.get(i);\r\n      rootElem.addContent(writeGrid(grid));\r\n    } */ /* coordinate systems\r\n    List gridSets = gds.getGridsets();\r\n    for (int i = 0; i < gridSets.size(); i++) {\r\n      GridDataset.Gridset gridset = (GridDataset.Gridset) gridSets.get(i);\r\n      rootElem.addContent(writeCoordSys(gridset.getGeoCoordSystem()));\r\n    } */ // gridSets\r List < GridDataset . Gridset > gridSets = gds . getGridsets ( ) ; Collections . sort ( gridSets , new GridSetComparator ( ) ) ; for ( GridDataset . Gridset gridset : gridSets ) { rootElem . addContent ( writeGridSet ( gridset ) ) ; } // coordinate transforms\r for ( CoordinateTransform ct : getCoordTransforms ( gds ) ) { rootElem . addContent ( writeCoordTransform ( ct ) ) ; } /* global attributes\r\n    Iterator atts = gds.getGlobalAttributes().iterator();\r\n    while (atts.hasNext()) {\r\n      ucar.nc2.Attribute att = (ucar.nc2.Attribute) atts.next();\r\n      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeAttribute(att, \"attribute\", null));\r\n    } */ // add lat/lon bounding box\r LatLonRect bb = gds . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range\r CalendarDate start = gds . getCalendarDateStart ( ) ; CalendarDate end = gds . getCalendarDateEnd ( ) ; if ( ( start != null ) && ( end != null ) ) { Element dateRange = new Element ( \"TimeSpan\" ) ; dateRange . addContent ( new Element ( \"begin\" ) . addContent ( start . toString ( ) ) ) ; dateRange . addContent ( new Element ( \"end\" ) . addContent ( end . toString ( ) ) ) ; rootElem . addContent ( dateRange ) ; } // add accept list\r addAcceptList ( rootElem ) ; //    elem.addContent(new Element(\"accept\").addContent(\"xml\"));\r //    elem.addContent(new Element(\"accept\").addContent(\"csv\"));\r //    elem.addContent(new Element(\"accept\").addContent(\"netcdf\"));    \r return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the Grid Form XML document from this GridDataset . Used to create the Grid HTML form cause I dont know XSLT [CODESPLIT] public Document makeGridForm ( ) { Element rootElem = new Element ( \"gridForm\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"location\" , gds . getLocation ( ) ) ; if ( null != path ) rootElem . setAttribute ( \"path\" , path ) ; // its all about grids\r List < GridDatatype > grids = gds . getGrids ( ) ; Collections . sort ( grids , new GridComparator ( ) ) ; // sort by time axis, vert axis, grid name\r CoordinateAxis currentTime = null ; CoordinateAxis currentVert = null ; Element timeElem = null ; Element vertElem = null ; boolean newTime ; for ( int i = 0 ; i < grids . size ( ) ; i ++ ) { GeoGrid grid = ( GeoGrid ) grids . get ( i ) ; GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; CoordinateAxis time = gcs . getTimeAxis ( ) ; CoordinateAxis vert = gcs . getVerticalAxis ( ) ; /* System.out.println(\" grid \"+grid.getName()\r\n              +\" time=\"+(time == null ? \" null\" : time.hashCode())\r\n              +\" vert=\"+(vert == null ? \" null\" : vert.hashCode())); */ //Assuming all variables in dataset has ensemble dim if one has\r if ( i == 0 ) { CoordinateAxis1D ens = gcs . getEnsembleAxis ( ) ; if ( ens != null ) { Element ensAxisEl = writeAxis2 ( ens , \"ensemble\" ) ; rootElem . addContent ( ensAxisEl ) ; } } if ( ( i == 0 ) || ! compareAxis ( time , currentTime ) ) { timeElem = new Element ( \"timeSet\" ) ; rootElem . addContent ( timeElem ) ; Element timeAxisElement = writeAxis2 ( time , \"time\" ) ; if ( timeAxisElement != null ) timeElem . addContent ( timeAxisElement ) ; currentTime = time ; newTime = true ; } else { newTime = false ; } if ( newTime || ! compareAxis ( vert , currentVert ) ) { vertElem = new Element ( \"vertSet\" ) ; timeElem . addContent ( vertElem ) ; Element vertAxisElement = writeAxis2 ( vert , \"vert\" ) ; if ( vertAxisElement != null ) vertElem . addContent ( vertAxisElement ) ; currentVert = vert ; } vertElem . addContent ( writeGrid ( grid ) ) ; } // add lat/lon bounding box\r LatLonRect bb = gds . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add projected bounding box\r //--> Asuming all gridSets have the same coordinates and bbox\r ProjectionRect rect = grids . get ( 0 ) . getCoordinateSystem ( ) . getBoundingBox ( ) ; Element projBBOX = new Element ( \"projectionBox\" ) ; Element minx = new Element ( \"minx\" ) ; minx . addContent ( Double . valueOf ( rect . getMinX ( ) ) . toString ( ) ) ; projBBOX . addContent ( minx ) ; Element maxx = new Element ( \"maxx\" ) ; maxx . addContent ( Double . valueOf ( rect . getMaxX ( ) ) . toString ( ) ) ; projBBOX . addContent ( maxx ) ; Element miny = new Element ( \"miny\" ) ; miny . addContent ( Double . valueOf ( rect . getMinY ( ) ) . toString ( ) ) ; projBBOX . addContent ( miny ) ; Element maxy = new Element ( \"maxy\" ) ; maxy . addContent ( Double . valueOf ( rect . getMaxY ( ) ) . toString ( ) ) ; projBBOX . addContent ( maxy ) ; rootElem . addContent ( projBBOX ) ; // add date range\r CalendarDate start = gds . getCalendarDateStart ( ) ; CalendarDate end = gds . getCalendarDateEnd ( ) ; if ( ( start != null ) && ( end != null ) ) { Element dateRange = new Element ( \"TimeSpan\" ) ; dateRange . addContent ( new Element ( \"begin\" ) . addContent ( start . toString ( ) ) ) ; dateRange . addContent ( new Element ( \"end\" ) . addContent ( end . toString ( ) ) ) ; rootElem . addContent ( dateRange ) ; } // add accept list\r addAcceptList ( rootElem ) ; //    Element elem = new Element(\"AcceptList\");\r //    elem.addContent(new Element(\"accept\").addContent(\"xml\"));\r //    elem.addContent(new Element(\"accept\").addContent(\"csv\"));\r //    elem.addContent(new Element(\"accept\").addContent(\"netcdf\"));\r //    rootElem.addContent(elem);\r return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private List getDimensions ( ucar . nc2 . dt . GridDataset gds ) { HashSet dimHash = new HashSet () ; List grids = gds . getGrids () ; for ( int i = 0 ; i < grids . size () ; i ++ ) { GeoGrid grid = ( GeoGrid ) grids . get ( i ) ; List dims = grid . getDimensions () ; for ( int j = 0 ; j < dims . size () ; j ++ ) { Dimension dim = ( Dimension ) dims . get ( j ) ; dimHash . add ( dim ) ; } } List list = Arrays . asList ( dimHash . toArray () ) ; Collections . sort ( list ) ; return list ; } [CODESPLIT] private Element writeAxis ( CoordinateAxis axis ) { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; Element varElem = new Element ( \"axis\" ) ; varElem . setAttribute ( \"name\" , axis . getFullName ( ) ) ; varElem . setAttribute ( \"shape\" , getShapeString ( axis . getShape ( ) ) ) ; // axis.getDimensionsString());\r DataType dt = axis . getDataType ( ) ; varElem . setAttribute ( \"type\" , dt . toString ( ) ) ; AxisType axisType = axis . getAxisType ( ) ; if ( null != axisType ) varElem . setAttribute ( \"axisType\" , axisType . toString ( ) ) ; // attributes\r for ( Attribute att : axis . getAttributes ( ) ) { varElem . addContent ( ncmlWriter . makeAttributeElement ( att ) ) ; } if ( axis . getRank ( ) == 1 ) { try { Element values = ncmlWriter . makeValuesElement ( axis , true ) ; varElem . addContent ( values ) ; } catch ( IOException e ) { String message = String . format ( \"Couldn't read values for %s. Omitting <values> element.\" , axis . getFullName ( ) ) ; logger . warn ( message , e ) ; } } return varElem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "display name plus the dimensions [CODESPLIT] private String getShapeString ( int [ ] shape ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < shape . length ; i ++ ) { if ( i != 0 ) buf . append ( \" \" ) ; buf . append ( shape [ i ] ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private Element writeCoordSys ( GridCoordSystem cs ) { Element csElem = new Element ( coordSys ) ; csElem . setAttribute ( name cs . getName () ) ; List axes = cs . getCoordinateAxes () ; for ( int i = 0 ; i < axes . size () ; i ++ ) { CoordinateAxis axis = ( CoordinateAxis ) axes . get ( i ) ; Element axisElem = new Element ( axisRef ) ; axisElem . setAttribute ( name axis . getName () ) ; csElem . addContent ( axisElem ) ; } List cts = cs . getCoordinateTransforms () ; for ( int j = 0 ; j < cts . size () ; j ++ ) { CoordinateTransform ct = ( CoordinateTransform ) cts . get ( j ) ; Element elem = new Element ( coordTransRef ) ; elem . setAttribute ( name ct . getName () ) ; csElem . addContent ( elem ) ; } return csElem ; } [CODESPLIT] private Element writeCoordTransform ( CoordinateTransform ct ) { Element ctElem = new Element ( \"coordTransform\" ) ; ctElem . setAttribute ( \"name\" , ct . getName ( ) ) ; ctElem . setAttribute ( \"transformType\" , ct . getTransformType ( ) . toString ( ) ) ; for ( Parameter param : ct . getParameters ( ) ) { Element pElem = new Element ( \"parameter\" ) ; pElem . setAttribute ( \"name\" , param . getName ( ) ) ; pElem . setAttribute ( \"value\" , param . getStringValue ( ) ) ; ctElem . addContent ( pElem ) ; } return ctElem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] public static void main ( String args [ ] ) throws IOException { String url = \"cdmremote:http://localhost:8080/thredds/cdmremote/grib/NCDC/CFSR/NCDC-CFSR/PGB-LatLon0p5\" ; GridDataset ncd = ucar . nc2 . dt . grid . GridDataset . open ( url ) ; GridDatasetInfo info = new GridDatasetInfo ( ncd , null ) ; FileOutputStream fos2 = new FileOutputStream ( \"C:/tmp2/gridInfo.xml\" ) ; info . writeXML ( info . makeGridForm ( ) , fos2 ) ; fos2 . close ( ) ; String infoString = info . writeXML ( info . makeGridForm ( ) ) ; System . out . println ( infoString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform sanity checks on a slice and repair where possible . [CODESPLIT] public Slice finish ( ) throws DapException { // Attempt to repair undefined values if ( this . first == UNDEFINED ) this . first = 0 ; // default if ( this . stride == UNDEFINED ) this . stride = 1 ; // default if ( this . stop == UNDEFINED && this . maxsize != UNDEFINED ) this . stop = this . maxsize ; if ( this . stop == UNDEFINED && this . maxsize == UNDEFINED ) this . stop = this . first + 1 ; if ( this . maxsize == UNDEFINED && this . stop != UNDEFINED ) this . maxsize = this . stop ; // else (this.stop != UNDEFINED && this.maxsize != UNDEFINED) assert ( this . first != UNDEFINED ) ; assert ( this . stride != UNDEFINED ) ; assert ( this . stop != UNDEFINED ) ; // sanity checks if ( this . first > this . maxsize ) throw new DapException ( \"Slice: first index > max size\" ) ; if ( this . stop > ( this . maxsize + 1 ) ) throw new DapException ( \"Slice: stop > max size\" ) ; if ( this . first < 0 ) throw new DapException ( \"Slice: first index < 0\" ) ; if ( this . stop < 0 ) throw new DapException ( \"Slice: stop index < 0\" ) ; if ( this . stride <= 0 ) throw new DapException ( \"Slice: stride index <= 0\" ) ; if ( this . first > this . stop ) throw new DapException ( \"Slice: first index > last\" ) ; return this ; // fluent interface }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the number of elements in the slice . Note that this is different from getStop () because stride is taken into account . [CODESPLIT] public long getCount ( ) { assert this . first != UNDEFINED && this . stride != UNDEFINED && this . stop != UNDEFINED ; long count = ( this . stop ) - this . first ; count = ( count + this . stride - 1 ) ; count /= this . stride ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert this slice to a string suitable for use in a constraint [CODESPLIT] public String toConstraintString ( ) throws DapException { assert this . first != UNDEFINED && this . stride != UNDEFINED && this . stop != UNDEFINED ; if ( ( this . stop - this . first ) == 0 ) { return String . format ( \"[0]\" ) ; } else if ( this . stride == 1 ) { if ( ( this . stop - this . first ) == 1 ) return String . format ( \"[%d]\" , this . first ) ; else return String . format ( \"[%d:%d]\" , this . first , this . stop - 1 ) ; } else return String . format ( \"[%d:%d:%d]\" , this . first , this . stride , this . stop - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take two slices and compose src wrt target Assume neither argument is null . This code should match ucar . ma2 . Section in thredds and dceconstraint . c in the netcdf - c library . [CODESPLIT] static public Slice compose ( Slice target , Slice src ) throws DapException { long sr_stride = target . getStride ( ) * src . getStride ( ) ; long sr_first = MAP ( target , src . getFirst ( ) ) ; long lastx = MAP ( target , src . getLast ( ) ) ; long sr_last = ( target . getLast ( ) < lastx ? target . getLast ( ) : lastx ) ; //min(last(),lastx) return new Slice ( sr_first , sr_last + 1 , sr_stride , sr_last + 1 ) . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map ith element of one range wrt a target range [CODESPLIT] static long MAP ( Slice target , long i ) throws DapException { if ( i < 0 ) throw new DapException ( \"Slice.compose: i must be >= 0\" ) ; if ( i > target . getStop ( ) ) throw new DapException ( \"i must be < stop\" ) ; return target . getFirst ( ) + i * target . getStride ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provide a simple dump of binary data [CODESPLIT] static public void dumpbytes ( ByteBuffer buf0 , boolean skipdmr ) { int savepos = buf0 . position ( ) ; int limit0 = buf0 . limit ( ) ; int skipcount = 0 ; if ( limit0 > MAXLIMIT ) limit0 = MAXLIMIT ; if ( limit0 >= buf0 . limit ( ) ) limit0 = buf0 . limit ( ) ; if ( skipdmr ) { ByteOrder saveorder = buf0 . order ( ) ; buf0 . order ( ByteOrder . BIG_ENDIAN ) ; // must read in network order skipcount = buf0 . getInt ( ) ; //dmr count buf0 . order ( saveorder ) ; skipcount &= 0xFFFFFF ; // mask off the flags to get true count skipcount += 4 ; // skip the count also } byte [ ] bytes = new byte [ ( limit0 + 8 ) - skipcount ] ; Arrays . fill ( bytes , ( byte ) 0 ) ; buf0 . position ( savepos + skipcount ) ; buf0 . get ( bytes , 0 , limit0 - skipcount ) ; buf0 . position ( savepos ) ; System . err . println ( \"order=\" + buf0 . order ( ) ) ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) . order ( buf0 . order ( ) ) ; dumpbytes ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump the contents of a buffer from 0 to position [CODESPLIT] static public void dumpbytes ( ByteBuffer buf0 ) { int stop = buf0 . limit ( ) ; int size = stop + 8 ; int savepos = buf0 . position ( ) ; assert savepos == 0 ; byte [ ] bytes = new byte [ size ] ; Arrays . fill ( bytes , ( byte ) 0 ) ; buf0 . get ( bytes , 0 , stop ) ; buf0 . position ( savepos ) ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) . order ( buf0 . order ( ) ) ; buf . position ( 0 ) ; buf . limit ( size ) ; int i = 0 ; try { for ( i = 0 ; buf . position ( ) < stop ; i ++ ) { savepos = buf . position ( ) ; int iv = buf . getInt ( ) ; buf . position ( savepos ) ; long lv = buf . getLong ( ) ; buf . position ( savepos ) ; short sv = buf . getShort ( ) ; buf . position ( savepos ) ; byte b = buf . get ( ) ; int ub = ( ( int ) b ) & 0x000000FF ; long uiv = ( ( long ) iv ) & 0xFFFFFFFF  L ; int usv = ( ( int ) sv ) & 0xFFFF ; int ib = ( int ) b ; char c = ( char ) ub ; String s = Character . toString ( c ) ; if ( c == ' ' ) s = \"\\\\r\" ; else if ( c == ' ' ) s = \"\\\\n\" ; else if ( c < ' ' || c >= 0x7f ) s = \"?\" ; System . err . printf ( \"[%03d] %02x %03d %4d '%s'\" , i , ub , ub , ib , s ) ; System . err . printf ( \"\\t%12d 0x%08x\" , iv , uiv ) ; System . err . printf ( \"\\t%5d\\t0x%04x\" , sv , usv ) ; System . err . println ( ) ; System . err . flush ( ) ; } } catch ( Exception e ) { System . err . println ( \"failure:\" + e ) ; } finally { System . err . flush ( ) ; //new Exception().printStackTrace(System.err); System . err . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the EarthEllipsoid that matches this name . [CODESPLIT] public static EarthEllipsoid getType ( String name ) { if ( name == null ) return null ; return hash . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the EarthEllipsoid that matches this EPSG Id . [CODESPLIT] public static EarthEllipsoid getType ( int epsgId ) { Collection < EarthEllipsoid > all = getAll ( ) ; for ( EarthEllipsoid ellipsoid : all ) { if ( ellipsoid . epsgId == epsgId ) { return ellipsoid ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message DataCol { string name = 1 ; // fullname for top shortname for member DataType dataType = 2 ; Section section = 3 ; bool bigend = 4 ; uint32 version = 5 ; bool isVlen = 7 ; uint32 nelems = 9 ; [CODESPLIT] public NcStreamProto . DataCol encodeData2 ( String name , boolean isVlen , Section section , Array data ) { NcStreamProto . DataCol . Builder builder = NcStreamProto . DataCol . newBuilder ( ) ; DataType dataType = data . getDataType ( ) ; builder . setName ( name ) ; builder . setDataType ( NcStream . convertDataType ( data . getDataType ( ) ) ) ; builder . setBigend ( ByteOrder . nativeOrder ( ) == ByteOrder . BIG_ENDIAN ) ; builder . setVersion ( NcStream . ncstream_data_version ) ; if ( ! isVlen ) { builder . setNelems ( ( int ) data . getSize ( ) ) ; builder . setSection ( NcStream . encodeSection ( section ) ) ; } if ( isVlen ) { builder . setIsVlen ( true ) ; encodeVlenData ( builder , section , data ) ; } else if ( dataType == DataType . STRING ) { if ( data instanceof ArrayChar ) { // is this possible ? ArrayChar cdata = ( ArrayChar ) data ; for ( String s : cdata ) builder . addStringdata ( s ) ; Section ssection = section . removeLast ( ) ; builder . setSection ( NcStream . encodeSection ( ssection ) ) ; } else if ( data instanceof ArrayObject ) { IndexIterator iter = data . getIndexIterator ( ) ; while ( iter . hasNext ( ) ) builder . addStringdata ( ( String ) iter . next ( ) ) ; } else { throw new IllegalStateException ( \"Unknown class for STRING =\" + data . getClass ( ) . getName ( ) ) ; } } else if ( dataType == DataType . OPAQUE ) { if ( data instanceof ArrayObject ) { IndexIterator iter = data . getIndexIterator ( ) ; while ( iter . hasNext ( ) ) { ByteBuffer bb = ( ByteBuffer ) iter . next ( ) ; // Need to use duplicate so that internal state of bb isn't affected builder . addOpaquedata ( ByteString . copyFrom ( bb . duplicate ( ) ) ) ; } } else { throw new IllegalStateException ( \"Unknown class for OPAQUE =\" + data . getClass ( ) . getName ( ) ) ; } } else if ( dataType == DataType . STRUCTURE ) { builder . setStructdata ( encodeStructureData ( data ) ) ; } else if ( dataType == DataType . SEQUENCE ) { throw new UnsupportedOperationException ( \"Not implemented yet SEQUENCE =\" + data . getClass ( ) . getName ( ) ) ; } else { // normal case builder . setPrimdata ( copyArrayToByteString ( data ) ) ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public Array decode ( NcStreamProto . DataCol dproto , Section parentSection ) throws IOException { ByteOrder bo = dproto . getBigend ( ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; DataType dataType = NcStream . convertDataType ( dproto . getDataType ( ) ) ; Section section = ( dataType == DataType . SEQUENCE ) ? new Section ( ) : NcStream . decodeSection ( dproto . getSection ( ) ) ; if ( ! dproto . getIsVlen ( ) ) { assert dproto . getNelems ( ) == section . computeSize ( ) ; } // special cases if ( dproto . getIsVlen ( ) ) { if ( parentSection == null ) return decodeVlenData ( dproto ) ; else return decodeVlenData ( dproto , parentSection ) ; } else if ( dataType == DataType . STRING ) { Array data = Array . factory ( dataType , section . getShape ( ) ) ; IndexIterator ii = data . getIndexIterator ( ) ; for ( String s : dproto . getStringdataList ( ) ) { ii . setObjectNext ( s ) ; } return data ; } else if ( dataType == DataType . STRUCTURE ) { return decodeStructureData ( dproto , parentSection ) ; } else if ( dataType == DataType . OPAQUE ) { Array data = Array . factory ( dataType , section . getShape ( ) ) ; IndexIterator ii = data . getIndexIterator ( ) ; for ( ByteString s : dproto . getOpaquedataList ( ) ) { ii . setObjectNext ( s . asReadOnlyByteBuffer ( ) ) ; } return data ; } else { // common case ByteBuffer bb = dproto . getPrimdata ( ) . asReadOnlyByteBuffer ( ) ; bb . order ( bo ) ; return Array . factory ( dataType , section . getShape ( ) , bb ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "top level vlen [CODESPLIT] public Array decodeVlenData ( NcStreamProto . DataCol dproto ) throws IOException { DataType dataType = NcStream . convertDataType ( dproto . getDataType ( ) ) ; ByteBuffer bb = dproto . getPrimdata ( ) . asReadOnlyByteBuffer ( ) ; ByteOrder bo = dproto . getBigend ( ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; bb . order ( bo ) ; Array alldata = Array . factory ( dataType , new int [ ] { dproto . getNelems ( ) } , bb ) ; // flat array IndexIterator all = alldata . getIndexIterator ( ) ; Section section = NcStream . decodeSection ( dproto . getSection ( ) ) ; Array [ ] data = new Array [ ( int ) section . computeSize ( ) ] ; // divide the primitive data into variable length arrays int count = 0 ; for ( int len : dproto . getVlensList ( ) ) { Array primdata = Array . factory ( dataType , new int [ ] { len } ) ; IndexIterator prim = primdata . getIndexIterator ( ) ; for ( int i = 0 ; i < len ; i ++ ) { prim . setObjectNext ( all . getObjectNext ( ) ) ; // generic } data [ count ++ ] = primdata ; } // return Array.makeObjectArray(dataType, data[0].getClass(), section.getShape(), data); return Array . makeVlenArray ( section . getShape ( ) , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "vlen inside a Structure [CODESPLIT] private Array decodeVlenData ( NcStreamProto . DataCol dproto , Section parentSection ) throws IOException { DataType dataType = NcStream . convertDataType ( dproto . getDataType ( ) ) ; ByteBuffer bb = dproto . getPrimdata ( ) . asReadOnlyByteBuffer ( ) ; ByteOrder bo = dproto . getBigend ( ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; bb . order ( bo ) ; Array alldata = Array . factory ( dataType , new int [ ] { dproto . getNelems ( ) } , bb ) ; // 1D array IndexIterator all = alldata . getIndexIterator ( ) ; int psize = ( int ) parentSection . computeSize ( ) ; Section section = NcStream . decodeSection ( dproto . getSection ( ) ) ; Section vsection = section . removeFirst ( parentSection ) ; int vsectionSize = ( int ) vsection . computeSize ( ) ; // the # of varlen Arrays at the inner structure // LOOK check for scalar // divide the primitive data into variable length arrays int countInner = 0 ; Array [ ] pdata = new Array [ psize ] ; for ( int pCount = 0 ; pCount < psize ; pCount ++ ) { Array [ ] vdata = new Array [ vsectionSize ] ; for ( int vCount = 0 ; vCount < vsectionSize ; vCount ++ ) { int vlen = dproto . getVlens ( countInner ++ ) ; Array primdata = Array . factory ( dataType , new int [ ] { vlen } ) ; IndexIterator prim = primdata . getIndexIterator ( ) ; for ( int i = 0 ; i < vlen ; i ++ ) { prim . setObjectNext ( all . getObjectNext ( ) ) ; // generic } vdata [ vCount ] = primdata ; } pdata [ pCount ] = Array . makeVlenArray ( vsection . getShape ( ) , vdata ) ; } // ArrayObject(parentShape) return Array . makeVlenArray ( parentSection . getShape ( ) , pdata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract all A - HREF contained URLS from the given URL and return in List [CODESPLIT] public ArrayList extract ( String url ) throws IOException { if ( debug ) System . out . println ( \" URLextract=\" + url ) ; baseURL = new URL ( url ) ; InputStream in = baseURL . openStream ( ) ; InputStreamReader r = new InputStreamReader ( filterTag ( in ) , CDM . UTF8 ) ; HTMLEditorKit . ParserCallback callback = new CallerBacker ( ) ; urlList = new ArrayList ( ) ; wantURLS = true ; wantText = false ; parser . parse ( r , callback , false ) ; return urlList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract text content from the given URL and return in String [CODESPLIT] public String getTextContent ( String url ) throws IOException { if ( debug ) System . out . println ( \" URL.getTextContent=\" + url ) ; baseURL = new URL ( url ) ; InputStream in = baseURL . openStream ( ) ; InputStreamReader r = new InputStreamReader ( filterTag ( in ) , CDM . UTF8 ) ; HTMLEditorKit . ParserCallback callback = new CallerBacker ( ) ; textBuffer = new StringBuffer ( 3000 ) ; wantURLS = false ; wantText = true ; parser . parse ( r , callback , false ) ; return textBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "workaround for HTMLEditorKit . Parser cant deal with content - encoding [CODESPLIT] private InputStream filterTag ( InputStream in ) throws IOException { BufferedReader buffIn = new BufferedReader ( new InputStreamReader ( in , CDM . UTF8 ) ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( 10000 ) ; String line = buffIn . readLine ( ) ; while ( line != null ) { String lline = line . toLowerCase ( ) ; if ( lline . contains ( \"<meta \" ) ) // skip meta tags continue ; //System.out.println(\"--\"+line); bos . write ( line . getBytes ( CDM . utf8Charset ) ) ; line = buffIn . readLine ( ) ; } buffIn . close ( ) ; return new ByteArrayInputStream ( bos . toByteArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK DataOutputStream uses big - endian [CODESPLIT] @ Override public long readToByteChannel ( ucar . nc2 . Variable v2 , Section section , WritableByteChannel channel ) throws java . io . IOException , ucar . ma2 . InvalidRangeException { Array data = readData ( v2 , section ) ; return IospHelper . copyToByteChannel ( data , channel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the Dataset Description XML document from this GridDataset [CODESPLIT] public Document makeDatasetDescription ( ) throws IOException { Element rootElem = new Element ( \"gridDataset\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"location\" , gcd . getName ( ) ) ; if ( null != path ) rootElem . setAttribute ( \"path\" , path ) ; // coordinate axes for ( CoverageCoordAxis axis : gcd . getCoordAxes ( ) ) { rootElem . addContent ( writeAxis ( axis ) ) ; } // gridSets for ( CoordSysSet gridset : gcd . getCoverageSets ( ) ) { rootElem . addContent ( writeCoverageSet ( gridset . getCoordSys ( ) , gridset . getCoverages ( ) , gcd . getProjBoundingBox ( ) ) ) ; } // coordinate transforms for ( CoverageTransform ct : gcd . getCoordTransforms ( ) ) { rootElem . addContent ( writeCoordTransform ( ct ) ) ; } /* global attributes\n     Iterator atts = gds.getGlobalAttributes().iterator();\n     while (atts.hasNext()) {\n       ucar.nc2.Attribute att = (ucar.nc2.Attribute) atts.next();\n       rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeAttribute(att, \"attribute\", null));\n     } */ // add lat/lon bounding box LatLonRect bb = gcd . getLatlonBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range CalendarDateRange calDateRange = gcd . getCalendarDateRange ( ) ; if ( calDateRange != null ) { Element dateRange = new Element ( \"TimeSpan\" ) ; dateRange . addContent ( new Element ( \"begin\" ) . addContent ( calDateRange . getStart ( ) . toString ( ) ) ) ; dateRange . addContent ( new Element ( \"end\" ) . addContent ( calDateRange . getEnd ( ) . toString ( ) ) ) ; rootElem . addContent ( dateRange ) ; } return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private Element writeCoordSys ( GridCoordSystem cs ) { Element csElem = new Element ( coordSys ) ; csElem . setAttribute ( name cs . getName () ) ; List axes = cs . getCoordinateAxes () ; for ( int i = 0 ; i < axes . size () ; i ++ ) { CoordinateAxis axis = ( CoordinateAxis ) axes . get ( i ) ; Element axisElem = new Element ( axisRef ) ; axisElem . setAttribute ( name axis . getName () ) ; csElem . addContent ( axisElem ) ; } List cts = cs . getCoordinateTransforms () ; for ( int j = 0 ; j < cts . size () ; j ++ ) { CoordinateTransform ct = ( CoordinateTransform ) cts . get ( j ) ; Element elem = new Element ( coordTransRef ) ; elem . setAttribute ( name ct . getName () ) ; csElem . addContent ( elem ) ; } return csElem ; } [CODESPLIT] private Element writeCoordTransform ( CoverageTransform ct ) { Element ctElem = new Element ( \"coordTransform\" ) ; ctElem . setAttribute ( \"name\" , ct . getName ( ) ) ; ctElem . setAttribute ( \"transformType\" , ct . isHoriz ( ) ? \"Projection\" : \"Vertical\" ) ; for ( Attribute param : ct . getAttributes ( ) ) { Element pElem = ncmlWriter . makeAttributeElement ( param ) ; pElem . setName ( \"parameter\" ) ; ctElem . addContent ( pElem ) ; } return ctElem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all ; replace old if has same name [CODESPLIT] @ Override public void addAll ( Iterable < Attribute > atts ) { for ( Attribute att : atts ) addAttribute ( att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an Attribute by name . [CODESPLIT] @ Override public boolean removeAttribute ( String attName ) { Attribute att = findAttribute ( attName ) ; return att != null && atts . remove ( att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an Attribute by name ignoring case [CODESPLIT] @ Override public boolean removeAttributeIgnoreCase ( String attName ) { Attribute att = findAttributeIgnoreCase ( attName ) ; return att != null && atts . remove ( att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get offsets from firstDate in units of timeUnit [CODESPLIT] public List < Double > getOffsetsInTimeUnits ( ) { double start = firstDate . getMillis ( ) ; List < Double > result = new ArrayList <> ( runtimes . length ) ; for ( int idx = 0 ; idx < runtimes . length ; idx ++ ) { double runtime = ( double ) getRuntime ( idx ) ; double msecs = ( runtime - start ) ; result . add ( msecs / timeUnit . getValueInMillisecs ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add an ActionSource listener [CODESPLIT] public void addActionSourceListener ( ActionSourceListener l ) { if ( ! eventType . equals ( l . getEventTypeName ( ) ) ) throw new IllegalArgumentException ( \"ActionCoordinator: tried to add ActionSourceListener for wrong kind of Action \" + eventType + \" != \" + l . getEventTypeName ( ) ) ; lm . addListener ( l ) ; l . addActionValueListener ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add an ActionValue listener public void addActionValueListener ( ActionValueListener l ) { lm . addListener ( l ) ; } remove an ActionValue listener public void removeActionValueListener ( ActionValueListener l ) { lm . removeListener ( l ) ; } [CODESPLIT] static public void main ( String [ ] argv ) { ActionCoordinator ac = new ActionCoordinator ( \"test\" ) ; /*    System.out.println(\"failure test------------\");\n    try {\n      ac.addActionSourceListener(new ActionSourceListener(\"that\") {\n        public void actionPerformed( java.awt.event.ActionEvent e) {\n          System.out.println(\" event ok \");\n        }\n      });\n      System.out.println(\"good dog!\");\n    } catch (IllegalArgumentException e) {\n      System.out.println(\"bad dog! = \"+e);\n    }\n\n    System.out.println(\"next test------------\");  */ ActionSourceListener as1 = new ActionSourceListener ( \"test\" ) { public void actionPerformed ( ActionValueEvent e ) { System . out . println ( \" first listener got event \" + e . getValue ( ) ) ; } } ; ac . addActionSourceListener ( as1 ) ; ActionSourceListener as2 = new ActionSourceListener ( \"test\" ) { public void actionPerformed ( ActionValueEvent e ) { System . out . println ( \" second listener got event \" + e . getValue ( ) ) ; } } ; ac . addActionSourceListener ( as2 ) ; ActionSourceListener as3 = new ActionSourceListener ( \"test\" ) { public void actionPerformed ( ActionValueEvent e ) { System . out . println ( \" third listener got event \" + e . getValue ( ) ) ; } } ; ac . addActionSourceListener ( as3 ) ; as1 . fireActionValueEvent ( \"testing\" , \"newValue 1\" ) ; as2 . fireActionValueEvent ( \"testing\" , \"newValue 2\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HttpSessionAttributeListener [CODESPLIT] public void attributeRemoved ( HttpSessionBindingEvent e ) { if ( e . getValue ( ) instanceof GuardedDataset ) { GuardedDataset gdataset = ( GuardedDataset ) e . getValue ( ) ; gdataset . close ( ) ; //System.out.printf(\" close gdataset %s in session %s %n\", gdataset, e.getSession().getId()); //if (log.isDebugEnabled()) log.debug(\" close gdataset \" + gdataset + \" in session \" + e.getSession().getId()); } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use factory to obtain a EsriShapefileRenderer . This caches the EsriShapefile for reuse . <p / > Implementation note : should switch to weak references . [CODESPLIT] static public EsriShapefileRenderer factory ( String filename ) { if ( sfileHash == null ) sfileHash = new HashMap < String , EsriShapefileRenderer > ( ) ; if ( sfileHash . containsKey ( filename ) ) return sfileHash . get ( filename ) ; try { EsriShapefileRenderer sfile = new EsriShapefileRenderer ( filename ) ; sfileHash . put ( filename , sfile ) ; return sfile ; } catch ( Exception ex ) { //System.err.println(\"EsriShapefileRenderer failed on \" + filename + \"\\n\" + ex);\r //ex.printStackTrace();\r return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the value ( parameters are ignored ) . [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws IOException { setData ( ncVar . read ( ) ) ; return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( print_decl_p ) { printDecl ( os , space , false ) ; os . println ( \" = \\\"\" + Util . escattr ( val ) + \"\\\";\" ) ; } else os . print ( \"\\\"\" + Util . escattr ( val ) + \"\\\"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { int dap_len = source . readInt ( ) ; //LogStream.out.println(\"DString deserialize string dap_length: \"+ dap_len);\r if ( dap_len < 0 ) throw new DataReadException ( \"Negative string length (dap_length: \" + dap_len + \") read.\" ) ; if ( dap_len > Short . MAX_VALUE ) throw new DataReadException ( \"DString deserialize string length (dap_length: \" + dap_len + \") too large.\" ) ; int modFour = dap_len % 4 ; // number of bytes to pad\r int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; byte byteArray [ ] = new byte [ dap_len ] ; // With blackdown JDK1.1.8v3 (comes with matlab 6) read() didn't always\r // finish reading a string.  readFully() insures that it gets all <dap_len>\r // characters it requested.  rph 08/20/01.\r //source.read(byteArray, 0, dap_len);\r source . readFully ( byteArray , 0 , dap_len ) ; // pad out to a multiple of four bytes\r byte unused ; for ( int i = 0 ; i < pad ; i ++ ) unused = source . readByte ( ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 4 + dap_len + pad ) ; // convert bytes to a new String using ISO8859_1 (Latin 1) encoding.\r // This was chosen because it converts each byte to its Unicode value\r // with no translation (the first 256 glyphs in Unicode are ISO8859_1)\r try { val = new String ( byteArray , 0 , dap_len , \"ISO8859_1\" ) ; hasValue = true ; } catch ( UnsupportedEncodingException e ) { // this should never happen\r throw new UnsupportedEncodingException ( \"ISO8859_1 encoding not supported by this VM!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { // convert String to a byte array using ISO8859_1 (Latin 1) encoding.\r // This was chosen because it converts each byte to its Unicode value\r // with no translation (the first 256 glyphs in Unicode are ISO8859_1)\r try { byte byteArray [ ] = val . getBytes ( \"ISO8859_1\" ) ; sink . writeInt ( byteArray . length ) ; int modFour = byteArray . length % 4 ; // number of bytes to pad\r int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; sink . write ( byteArray , 0 , byteArray . length ) ; for ( int i = 0 ; i < pad ; i ++ ) { sink . writeByte ( 0 ) ; } } catch ( UnsupportedEncodingException e ) { // this should never happen\r throw new UnsupportedEncodingException ( \"ISO8859_1 encoding not supported by this VM!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if either coordinate is + / - infinite . This happens sometimes in projective geometry . [CODESPLIT] public boolean isInfinite ( ) { return ( x == java . lang . Double . POSITIVE_INFINITY ) || ( x == java . lang . Double . NEGATIVE_INFINITY ) || ( y == java . lang . Double . POSITIVE_INFINITY ) || ( y == java . lang . Double . NEGATIVE_INFINITY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if either coordinate in <code > pt< / code > is + / - infinite . This happens sometimes in projective geometry . [CODESPLIT] static public boolean isInfinite ( ProjectionPoint pt ) { return ( pt . getX ( ) == java . lang . Double . POSITIVE_INFINITY ) || ( pt . getX ( ) == java . lang . Double . NEGATIVE_INFINITY ) || ( pt . getY ( ) == java . lang . Double . POSITIVE_INFINITY ) || ( pt . getY ( ) == java . lang . Double . NEGATIVE_INFINITY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the shape of the largest possible <b > contiguous< / b > chunk starting at { @link #getCurrentCounter () } and with { @code numElems < = maxChunkElems } . [CODESPLIT] public int [ ] computeChunkShape ( long maxChunkElems ) { int [ ] chunkShape = new int [ rank ] ; for ( int iDim = 0 ; iDim < rank ; ++ iDim ) { int size = ( int ) ( maxChunkElems / stride [ iDim ] ) ; size = ( size == 0 ) ? 1 : size ; size = Math . min ( size , shape [ iDim ] - current [ iDim ] ) ; chunkShape [ iDim ] = size ; } return chunkShape ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public void setValue ( NativeLong value ) { getPointer () . setNativeLong ( 0 value ) ; } [CODESPLIT] public void setValue ( SizeT value ) { Pointer p = getPointer ( ) ; if ( Native . SIZE_T_SIZE == 8 ) { p . setLong ( 0 , value . longValue ( ) ) ; } else { p . setInt ( 0 , value . intValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a java . util . Date from this udunits String . [CODESPLIT] static public Date getStandardDate ( String text ) { double value ; String udunitString ; text = text . trim ( ) ; StringTokenizer stoker = new StringTokenizer ( text ) ; String firstToke = stoker . nextToken ( ) ; try { value = Double . parseDouble ( firstToke ) ; udunitString = text . substring ( firstToke . length ( ) ) ; } catch ( NumberFormatException e ) { // stupid way to test if it starts with a number\r value = 0.0 ; udunitString = text ; } DateUnit du ; try { du = new DateUnit ( udunitString ) ; } catch ( Exception e ) { return null ; } return du . makeDate ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a java . util . Date from a udunit or ISO String . [CODESPLIT] static public Date getStandardOrISO ( String text ) { Date result = getStandardDate ( text ) ; if ( result == null ) { DateFormatter formatter = new DateFormatter ( ) ; result = formatter . getISODate ( text ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the origin Date . [CODESPLIT] public Date getDateOrigin ( ) { if ( ! ( uu instanceof TimeScaleUnit ) ) return null ; TimeScaleUnit tu = ( TimeScaleUnit ) uu ; return tu . getOrigin ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the equivalent java . util . Date . [CODESPLIT] public Date getDate ( ) { double secs = timeUnit . getValueInSeconds ( value ) ; return new Date ( getDateOrigin ( ) . getTime ( ) + ( long ) ( 1000 * secs ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Date from this base unit and the given value . [CODESPLIT] public Date makeDate ( double val ) { if ( Double . isNaN ( val ) ) return null ; double secs = timeUnit . getValueInSeconds ( val ) ; //\r return new Date ( getDateOrigin ( ) . getTime ( ) + ( long ) ( 1000 * secs ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the equivalent value from this base unit and the given Date . Inverse of makeDate . [CODESPLIT] public double makeValue ( Date date ) { double secs = date . getTime ( ) / 1000.0 ; double origin_secs = getDateOrigin ( ) . getTime ( ) / 1000.0 ; double diff = secs - origin_secs ; try { timeUnit . setValueInSeconds ( diff ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) ) ; } return timeUnit . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a standard GMT string representation from this unit and given value . [CODESPLIT] public String makeStandardDateString ( double value ) { Date date = makeDate ( value ) ; if ( date == null ) return null ; DateFormatter formatter = new DateFormatter ( ) ; return formatter . toDateTimeStringISO ( date ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the grid spacing in kilometers [CODESPLIT] private double getGridSpacingInKm ( String type ) { double value = gds . getDouble ( type ) ; if ( Double . isNaN ( value ) ) return value ; String gridUnit = gds . getParam ( GridDefRecord . GRID_UNITS ) ; SimpleUnit unit ; if ( gridUnit == null || gridUnit . length ( ) == 0 ) { unit = SimpleUnit . meterUnit ; } else { unit = SimpleUnit . factory ( gridUnit ) ; } if ( unit != null && SimpleUnit . isCompatible ( unit . getUnitString ( ) , \"km\" ) ) { value = unit . convertTo ( value , SimpleUnit . kmUnit ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the dimensions associated with this coord sys to the netCDF file [CODESPLIT] void addDimensionsToNetcdfFile ( NetcdfFile ncfile ) { if ( isLatLon ) { ncfile . addDimension ( g , new Dimension ( \"lat\" , gds . getInt ( GridDefRecord . NY ) , true ) ) ; ncfile . addDimension ( g , new Dimension ( \"lon\" , gds . getInt ( GridDefRecord . NX ) , true ) ) ; } else { ncfile . addDimension ( g , new Dimension ( \"y\" , gds . getInt ( GridDefRecord . NY ) , true ) ) ; ncfile . addDimension ( g , new Dimension ( \"x\" , gds . getInt ( GridDefRecord . NX ) , true ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the variables to the netCDF file [CODESPLIT] void addToNetcdfFile ( NetcdfFile ncfile ) { if ( isLatLon ) { double dy ; if ( gds . getDouble ( GridDefRecord . DY ) == GridDefRecord . UNDEFINED ) { dy = setLatLonDxDy ( ) ; } else { dy = ( gds . getDouble ( GridDefRecord . LA2 ) < gds . getDouble ( GridDefRecord . LA1 ) ) ? - gds . getDouble ( GridDefRecord . DY ) : gds . getDouble ( GridDefRecord . DY ) ; } // lat if ( isGaussian ) { addGaussianLatAxis ( ncfile , \"lat\" , \"degrees_north\" , \"latitude coordinate\" , \"latitude\" , AxisType . Lat ) ; } else { addCoordAxis ( ncfile , \"lat\" , gds . getInt ( GridDefRecord . NY ) , gds . getDouble ( GridDefRecord . LA1 ) , dy , \"degrees_north\" , \"latitude coordinate\" , \"latitude\" , AxisType . Lat ) ; } // lon addCoordAxis ( ncfile , \"lon\" , gds . getInt ( GridDefRecord . NX ) , gds . getDouble ( GridDefRecord . LO1 ) , gds . getDouble ( GridDefRecord . DX ) , \"degrees_east\" , \"longitude coordinate\" , \"longitude\" , AxisType . Lon ) ; // add dummy variable for lat/lon coord system addCoordSystemVariable ( ncfile , \"latLonCoordSys\" , \"time lat lon\" ) ; } else { int projType = lookup . getProjectionType ( gds ) ; if ( makeProjection ( ncfile , projType ) ) { double [ ] yData , xData ; if ( projType == GridTableLookup . RotatedLatLon ) { double dy = ( gds . getDouble ( \"La2\" ) < gds . getDouble ( GridDefRecord . LA1 ) ? - gds . getDouble ( GridDefRecord . DY ) : gds . getDouble ( GridDefRecord . DY ) ) ; yData = addCoordAxis ( ncfile , \"y\" , gds . getInt ( GridDefRecord . NY ) , gds . getDouble ( GridDefRecord . LA1 ) , dy , \"degrees\" , \"y coordinate of projection\" , \"projection_y_coordinate\" , AxisType . GeoY ) ; xData = addCoordAxis ( ncfile , \"x\" , gds . getInt ( GridDefRecord . NX ) , gds . getDouble ( GridDefRecord . LO1 ) , gds . getDouble ( GridDefRecord . DX ) , \"degrees\" , \"x coordinate of projection\" , \"projection_x_coordinate\" , AxisType . GeoX ) ; } else if ( projType == GridTableLookup . Orthographic ) { yData = addCoordAxis ( ncfile , \"y\" , gds . getInt ( GridDefRecord . NY ) , starty , incry , \"km\" , // fake km - really pixel \"y coordinate of projection\" , \"projection_y_coordinate\" , AxisType . GeoY ) ; // dunno what the 3 is xData = addCoordAxis ( ncfile , \"x\" , gds . getInt ( GridDefRecord . NX ) , startx , incrx , \"km\" , \"x coordinate of projection\" , \"projection_x_coordinate\" , AxisType . GeoX ) ; } else if ( projType == GridTableLookup . Curvilinear ) { yData = null ; xData = null ; } else { yData = addCoordAxis ( ncfile , \"y\" , gds . getInt ( GridDefRecord . NY ) , starty , getDyInKm ( ) , \"km\" , \"y coordinate of projection\" , \"projection_y_coordinate\" , AxisType . GeoY ) ; xData = addCoordAxis ( ncfile , \"x\" , gds . getInt ( GridDefRecord . NX ) , startx , getDxInKm ( ) , \"km\" , \"x coordinate of projection\" , \"projection_x_coordinate\" , AxisType . GeoX ) ; } // optional 2D lat/lon if ( GridServiceProvider . addLatLon && ( projType != GridTableLookup . Curvilinear ) ) addLatLon2D ( ncfile , xData , yData ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a coordinate axis [CODESPLIT] private double [ ] addCoordAxis ( NetcdfFile ncfile , String name , int n , double start , double incr , String units , String desc , String standard_name , AxisType axis ) { // ncfile.addDimension(g, new Dimension(name, n, true)); Variable v = new Variable ( ncfile , g , null , name ) ; v . setDataType ( DataType . DOUBLE ) ; v . setDimensions ( name ) ; // create the data double [ ] data = new double [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { data [ i ] = start + incr * i ; } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { n } , data ) ; v . setCachedData ( dataArray , false ) ; v . addAttribute ( new Attribute ( \"units\" , units ) ) ; v . addAttribute ( new Attribute ( \"long_name\" , desc ) ) ; v . addAttribute ( new Attribute ( \"standard_name\" , standard_name ) ) ; v . addAttribute ( new Attribute ( \"grid_spacing\" , incr + \" \" + units ) ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axis . toString ( ) ) ) ; ncfile . addVariable ( g , v ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a gaussian lat axis [CODESPLIT] private double [ ] addGaussianLatAxis ( NetcdfFile ncfile , String name , String units , String desc , String standard_name , AxisType axis ) { double np = gds . getDouble ( GridDefRecord . NUMBERPARALLELS ) ; if ( Double . isNaN ( np ) ) np = gds . getDouble ( \"Np\" ) ; if ( Double . isNaN ( np ) ) throw new IllegalArgumentException ( \"Gaussian Lat/Lon grid must have 'NumberParallels' or 'Np' (number of parallels) parameter\" ) ; double startLat = gds . getDouble ( GridDefRecord . LA1 ) ; double endLat = gds . getDouble ( GridDefRecord . LA2 ) ; int nlats = ( int ) ( 2 * np ) ; GaussianLatitudes gaussLats = GaussianLatitudes . factory ( nlats ) ; int bestStartIndex = 0 , bestEndIndex = 0 ; double bestStartDiff = Double . MAX_VALUE ; double bestEndDiff = Double . MAX_VALUE ; for ( int i = 0 ; i < nlats ; i ++ ) { double diff = Math . abs ( gaussLats . latd [ i ] - startLat ) ; if ( diff < bestStartDiff ) { bestStartDiff = diff ; bestStartIndex = i ; } diff = Math . abs ( gaussLats . latd [ i ] - endLat ) ; if ( diff < bestEndDiff ) { bestEndDiff = diff ; bestEndIndex = i ; } } int ny = gds . getInt ( GridDefRecord . NY ) ; if ( Math . abs ( bestEndIndex - bestStartIndex + 1 ) != ny ) { log . warn ( \"GRIB gaussian lats: NP != NY, use NY\" ) ; // see email from Toussaint@dkrz.de datafil: nlats = ny ; gaussLats = GaussianLatitudes . factory ( nlats ) ; bestStartIndex = 0 ; bestEndIndex = ny - 1 ; } boolean goesUp = bestEndIndex > bestStartIndex ; Variable v = new Variable ( ncfile , g , null , name ) ; v . setDataType ( DataType . DOUBLE ) ; v . setDimensions ( name ) ; // create the data int useIndex = bestStartIndex ; double [ ] data = new double [ ny ] ; double [ ] gaussw = new double [ ny ] ; for ( int i = 0 ; i < ny ; i ++ ) { data [ i ] = gaussLats . latd [ useIndex ] ; gaussw [ i ] = gaussLats . gaussw [ useIndex ] ; if ( goesUp ) { useIndex ++ ; } else { useIndex -- ; } } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { ny } , data ) ; v . setCachedData ( dataArray , false ) ; v . addAttribute ( new Attribute ( \"units\" , units ) ) ; v . addAttribute ( new Attribute ( \"long_name\" , desc ) ) ; v . addAttribute ( new Attribute ( \"standard_name\" , standard_name ) ) ; v . addAttribute ( new Attribute ( \"weights\" , \"gaussw\" ) ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axis . toString ( ) ) ) ; ncfile . addVariable ( g , v ) ; v = new Variable ( ncfile , g , null , \"gaussw\" ) ; v . setDataType ( DataType . DOUBLE ) ; v . setDimensions ( name ) ; v . addAttribute ( new Attribute ( \"long_name\" , \"gaussian weights (unnormalized)\" ) ) ; dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { ny } , gaussw ) ; v . setCachedData ( dataArray , false ) ; ncfile . addVariable ( g , v ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a projection and add it to the netCDF file [CODESPLIT] private boolean makeProjection ( NetcdfFile ncfile , int projType ) { switch ( projType ) { case GridTableLookup . RotatedLatLon : makeRotatedLatLon ( ncfile ) ; break ; case GridTableLookup . PolarStereographic : makePS ( ) ; break ; case GridTableLookup . LambertConformal : makeLC ( ) ; break ; case GridTableLookup . Mercator : makeMercator ( ) ; break ; case GridTableLookup . Orthographic : //makeSpaceViewOrOthographic(); makeMSGgeostationary ( ) ; break ; case GridTableLookup . Curvilinear : makeCurvilinearAxis ( ncfile ) ; break ; default : throw new UnsupportedOperationException ( \"unknown projection = \" + gds . getInt ( GridDefRecord . GRID_TYPE ) ) ; } // dummy coordsys variable Variable v = new Variable ( ncfile , g , null , grid_name ) ; v . setDataType ( DataType . CHAR ) ; v . setDimensions ( \"\" ) ; // scalar char [ ] data = new char [ ] { ' ' } ; Array dataArray = Array . factory ( DataType . CHAR , new int [ 0 ] , data ) ; v . setCachedData ( dataArray , false ) ; for ( Attribute att : attributes ) v . addAttribute ( att ) ; // add CF Conventions attributes v . addAttribute ( new Attribute ( GridCF . EARTH_SHAPE , shape_name ) ) ; // LOOK - spherical earth ?? double radius_spherical_earth = gds . getDouble ( GridDefRecord . RADIUS_SPHERICAL_EARTH ) ; // have to check both because Grib1 and Grib2 used different names if ( Double . isNaN ( radius_spherical_earth ) ) radius_spherical_earth = gds . getDouble ( \"radius_spherical_earth\" ) ; if ( ! Double . isNaN ( radius_spherical_earth ) ) { //inconsistent - sometimes in km, sometimes in m. if ( radius_spherical_earth < 10000.00 ) // then its in km radius_spherical_earth *= 1000.0 ; // convert to meters v . addAttribute ( new Attribute ( GridCF . EARTH_RADIUS , radius_spherical_earth ) ) ; //this attribute needs to be meters } else { // oblate earth double major_axis = gds . getDouble ( GridDefRecord . MAJOR_AXIS_EARTH ) ; if ( Double . isNaN ( major_axis ) ) major_axis = gds . getDouble ( \"major_axis_earth\" ) ; double minor_axis = gds . getDouble ( GridDefRecord . MINOR_AXIS_EARTH ) ; if ( Double . isNaN ( minor_axis ) ) minor_axis = gds . getDouble ( \"minor_axis_earth\" ) ; if ( ! Double . isNaN ( major_axis ) && ! Double . isNaN ( minor_axis ) ) { v . addAttribute ( new Attribute ( GridCF . SEMI_MAJOR_AXIS , major_axis ) ) ; v . addAttribute ( new Attribute ( GridCF . SEMI_MINOR_AXIS , minor_axis ) ) ; } } addGDSparams ( v ) ; ncfile . addVariable ( g , v ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the GDS params to the variable as attributes [CODESPLIT] private void addGDSparams ( Variable v ) { // add all the gds parameters List < String > keyList = new ArrayList <> ( gds . getKeys ( ) ) ; Collections . sort ( keyList ) ; String pre = getGDSprefix ( ) ; for ( String key : keyList ) { String name = pre + \"_param_\" + key ; String vals = gds . getParam ( key ) ; try { int vali = Integer . parseInt ( vals ) ; if ( key . equals ( GridDefRecord . VECTOR_COMPONENT_FLAG ) ) { String cf = GridCF . VectorComponentFlag . of ( vali ) ; v . addAttribute ( new Attribute ( name , cf ) ) ; } else { v . addAttribute ( new Attribute ( name , vali ) ) ; } } catch ( Exception e ) { try { double vald = Double . parseDouble ( vals ) ; v . addAttribute ( new Attribute ( name , vald ) ) ; } catch ( Exception e2 ) { v . addAttribute ( new Attribute ( name , vals ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add coordinate system variable [CODESPLIT] private void addCoordSystemVariable ( NetcdfFile ncfile , String name , String dims ) { Variable v = new Variable ( ncfile , g , null , name ) ; v . setDataType ( DataType . CHAR ) ; v . setDimensions ( \"\" ) ; // scalar Array dataArray = Array . factory ( DataType . CHAR , new int [ 0 ] , new char [ ] { ' ' } ) ; v . setCachedData ( dataArray , false ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , dims ) ) ; if ( isLatLon ( ) ) v . addAttribute ( new Attribute ( _Coordinate . Transforms , \"\" ) ) ; // to make sure its identified as a Coordinate System Variable else v . addAttribute ( new Attribute ( _Coordinate . Transforms , getGridName ( ) ) ) ; addGDSparams ( v ) ; ncfile . addVariable ( g , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a LambertConformalConic projection [CODESPLIT] private void makeLC ( ) { // we have to project in order to find the origin proj = new LambertConformal ( gds . getDouble ( GridDefRecord . LATIN1 ) , gds . getDouble ( GridDefRecord . LOV ) , gds . getDouble ( GridDefRecord . LATIN1 ) , gds . getDouble ( GridDefRecord . LATIN2 ) ) ; LatLonPointImpl startLL = new LatLonPointImpl ( gds . getDouble ( GridDefRecord . LA1 ) , gds . getDouble ( GridDefRecord . LO1 ) ) ; ProjectionPointImpl start = ( ProjectionPointImpl ) proj . latLonToProj ( startLL ) ; startx = start . getX ( ) ; starty = start . getY ( ) ; if ( Double . isNaN ( getDxInKm ( ) ) ) { setDxDy ( startx , starty , proj ) ; } if ( GridServiceProvider . debugProj ) { System . out . println ( \"GridHorizCoordSys.makeLC start at latlon \" + startLL ) ; double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( \"GridHorizCoordSys.makeLC end at latlon \" + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( \"   end at proj coord \" + endPP ) ; double endx = startx + getNx ( ) * getDxInKm ( ) ; double endy = starty + getNy ( ) * getDyInKm ( ) ; System . out . println ( \"   should be x=\" + endx + \" y=\" + endy ) ; } attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , \"lambert_conformal_conic\" ) ) ; if ( gds . getDouble ( GridDefRecord . LATIN1 ) == gds . getDouble ( GridDefRecord . LATIN2 ) ) { attributes . add ( new Attribute ( GridCF . STANDARD_PARALLEL , gds . getDouble ( GridDefRecord . LATIN1 ) ) ) ; } else { double [ ] data = new double [ ] { gds . getDouble ( GridDefRecord . LATIN1 ) , gds . getDouble ( GridDefRecord . LATIN2 ) } ; attributes . add ( new Attribute ( GridCF . STANDARD_PARALLEL , Array . factory ( DataType . DOUBLE , new int [ ] { 2 } , data ) ) ) ; } //attributes.add(new Attribute(\"longitude_of_central_meridian\", attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_CENTRAL_MERIDIAN , gds . getDouble ( GridDefRecord . LOV ) ) ) ; //attributes.add(new Attribute(\"latitude_of_projection_origin\", attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , gds . getDouble ( GridDefRecord . LATIN1 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a PolarStereographic projection [CODESPLIT] private void makePS ( ) { String nproj = gds . getParam ( GridDefRecord . NPPROJ ) ; double latOrigin = ( nproj == null || nproj . equalsIgnoreCase ( \"true\" ) ) ? 90.0 : - 90.0 ; // Why the scale factor?. according to GRIB docs: // \"Grid lengths are in units of meters, at the 60 degree latitude circle nearest to the pole\" // since the scale factor at 60 degrees = k = 2*k0/(1+sin(60))  [Snyder,Working Manual p157] // then to make scale = 1 at 60 degrees, k0 = (1+sin(60))/2 = .933 double scale ; double lad = gds . getDouble ( GridDefRecord . LAD ) ; if ( Double . isNaN ( lad ) ) { scale = .933 ; } else { scale = ( 1.0 + Math . sin ( Math . toRadians ( Math . abs ( lad ) ) ) ) / 2 ; } proj = new Stereographic ( latOrigin , gds . getDouble ( GridDefRecord . LOV ) , scale ) ; // we have to project in order to find the origin ProjectionPointImpl start = ( ProjectionPointImpl ) proj . latLonToProj ( new LatLonPointImpl ( gds . getDouble ( GridDefRecord . LA1 ) , gds . getDouble ( GridDefRecord . LO1 ) ) ) ; startx = start . getX ( ) ; starty = start . getY ( ) ; if ( Double . isNaN ( getDxInKm ( ) ) ) setDxDy ( startx , starty , proj ) ; if ( GridServiceProvider . debugProj ) { System . out . printf ( \"starting proj coord %s lat/lon %s%n\" , start , proj . projToLatLon ( start ) ) ; System . out . println ( \"   should be LA1=\" + gds . getDouble ( GridDefRecord . LA1 ) + \" l)1=\" + gds . getDouble ( GridDefRecord . LO1 ) ) ; } attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , \"polar_stereographic\" ) ) ; //attributes.add(new Attribute(\"longitude_of_projection_origin\", attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , gds . getDouble ( GridDefRecord . LOV ) ) ) ; //attributes.add(new Attribute(\"straight_vertical_longitude_from_pole\", attributes . add ( new Attribute ( GridCF . STRAIGHT_VERTICAL_LONGITUDE_FROM_POLE , gds . getDouble ( GridDefRecord . LOV ) ) ) ; //attributes.add(new Attribute(\"scale_factor_at_projection_origin\", attributes . add ( new Attribute ( GridCF . SCALE_FACTOR_AT_PROJECTION_ORIGIN , scale ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , latOrigin ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a Mercator projection [CODESPLIT] private void makeMercator ( ) { /**\n     * Construct a Mercator Projection.\n     * @param lon0 longitude of origin (degrees)\n     * @param par standard parallel (degrees). cylinder cuts earth at this latitude.\n     */ double Latin = gds . getDouble ( GridDefRecord . LAD ) ; // name depends on Grib version 1 or 2 if ( Double . isNaN ( Latin ) ) Latin = gds . getDouble ( GridDefRecord . LATIN ) ; double Lo1 = gds . getDouble ( GridDefRecord . LO1 ) ; //gds.Lo1; double La1 = gds . getDouble ( GridDefRecord . LA1 ) ; //gds.La1; // put longitude origin at first point - doesnt actually matter proj = new Mercator ( Lo1 , Latin ) ; // find out where ProjectionPoint startP = proj . latLonToProj ( new LatLonPointImpl ( La1 , Lo1 ) ) ; startx = startP . getX ( ) ; starty = startP . getY ( ) ; if ( Double . isNaN ( getDxInKm ( ) ) ) { setDxDy ( startx , starty , proj ) ; } attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , \"mercator\" ) ) ; attributes . add ( new Attribute ( GridCF . STANDARD_PARALLEL , Latin ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lo1 ) ) ; if ( GridServiceProvider . debugProj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; if ( Lo2 < Lo1 ) Lo2 += 360 ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( \"GridHorizCoordSys.makeMercator: end at latlon= \" + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( \"   start at proj coord \" + new ProjectionPointImpl ( startx , starty ) ) ; System . out . println ( \"   end at proj coord \" + endPP ) ; double endx = startx + ( getNx ( ) - 1 ) * getDxInKm ( ) ; double endy = starty + ( getNy ( ) - 1 ) * getDyInKm ( ) ; System . out . println ( \"   should be x=\" + endx + \" y=\" + endy ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RotatedLatLon [CODESPLIT] private void makeRotatedLatLon ( NetcdfFile ncfile ) { double splat = gds . getDouble ( GridDefRecord . SPLAT ) ; double splon = gds . getDouble ( GridDefRecord . SPLON ) ; double spangle = gds . getDouble ( GridDefRecord . ROTATIONANGLE ) ; // Given projection coordinates, need LatLon coordinates proj = new RotatedLatLon ( splat , splon , spangle ) ; LatLonPoint startLL = proj . projToLatLon ( new ProjectionPointImpl ( gds . getDouble ( GridDefRecord . LO1 ) , gds . getDouble ( GridDefRecord . LA1 ) ) ) ; startx = startLL . getLongitude ( ) ; starty = startLL . getLatitude ( ) ; addCoordSystemVariable ( ncfile , \"latLonCoordSys\" , \"time y x\" ) ; // splat, splon, spangle attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , \"rotated_latlon_grib\" ) ) ; attributes . add ( new Attribute ( \"grid_south_pole_latitude\" , splat ) ) ; attributes . add ( new Attribute ( \"grid_south_pole_longitude\" , splon ) ) ; attributes . add ( new Attribute ( \"grid_south_pole_angle\" , spangle ) ) ; if ( GridServiceProvider . debugProj ) { System . out . println ( \"Location of pole of rotated grid:\" ) ; System . out . println ( \"Lon=\" + splon + \", Lat=\" + splat ) ; System . out . println ( \"Axial rotation about pole of rotated grid:\" + spangle ) ; System . out . println ( \"Location of LL in rotated grid:\" ) ; System . out . println ( \"Lon=\" + gds . getDouble ( GridDefRecord . LO1 ) + \", \" + \"Lat=\" + gds . getDouble ( GridDefRecord . LA1 ) ) ; System . out . println ( \"Location of LL in non-rotated grid:\" ) ; System . out . println ( \"Lon=\" + startx + \", Lat=\" + starty ) ; double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; System . out . println ( \"Location of UR in rotated grid:\" ) ; System . out . println ( \"Lon=\" + Lo2 + \", Lat=\" + La2 ) ; System . out . println ( \"Location of UR in non-rotated grid:\" ) ; LatLonPoint endUR = proj . projToLatLon ( new ProjectionPointImpl ( Lo2 , La2 ) ) ; System . out . println ( \"Lon=\" + endUR . getLongitude ( ) + \", Lat=\" + endUR . getLatitude ( ) ) ; double dy = ( La2 < gds . getDouble ( GridDefRecord . LA1 ) ) ? - gds . getDouble ( GridDefRecord . DY ) : gds . getDouble ( GridDefRecord . DY ) ; double endx = gds . getDouble ( GridDefRecord . LO1 ) + ( getNx ( ) - 1 ) * gds . getDouble ( GridDefRecord . DX ) ; double endy = gds . getDouble ( GridDefRecord . LA1 ) + ( getNy ( ) - 1 ) * dy ; System . out . println ( \"End point rotated grid should be x=\" + endx + \" y=\" + endy ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a Space View Orthographic projection [CODESPLIT] private void makeSpaceViewOrOthographic ( ) { double Lat0 = gds . getDouble ( GridDefRecord . LAP ) ; // sub-satellite point lat double Lon0 = gds . getDouble ( GridDefRecord . LOP ) ; // sub-satellite point lon double xp = gds . getDouble ( GridDefRecord . XP ) ; // sub-satellite point in grid lengths double yp = gds . getDouble ( GridDefRecord . YP ) ; double dx = gds . getDouble ( GridDefRecord . DX ) ; // apparent diameter in units of grid lengths double dy = gds . getDouble ( GridDefRecord . DY ) ; // have to check both names because Grib1 and Grib2 used different names double major_axis = gds . getDouble ( GridDefRecord . MAJOR_AXIS_EARTH ) ; // km if ( Double . isNaN ( major_axis ) ) major_axis = gds . getDouble ( \"major_axis_earth\" ) ; double minor_axis = gds . getDouble ( GridDefRecord . MINOR_AXIS_EARTH ) ; // km if ( Double . isNaN ( minor_axis ) ) minor_axis = gds . getDouble ( \"minor_axis_earth\" ) ; // Nr = altitude of camera from center, in units of radius double nr = gds . getDouble ( GridDefRecord . NR ) * 1e-6 ; double apparentDiameter = 2 * Math . sqrt ( ( nr - 1 ) / ( nr + 1 ) ) ; // apparent diameter, units of radius (see Snyder p 173) // app diameter kmeters / app diameter grid lengths = m per grid length double gridLengthX = major_axis * apparentDiameter / dx ; double gridLengthY = minor_axis * apparentDiameter / dy ; // have to add to both for consistency gds . addParam ( GridDefRecord . DX , String . valueOf ( 1000 * gridLengthX ) ) ; // meters gds . addParam ( GridDefRecord . DX , new Double ( 1000 * gridLengthX ) ) ; gds . addParam ( GridDefRecord . DY , String . valueOf ( 1000 * gridLengthY ) ) ; // meters gds . addParam ( GridDefRecord . DY , new Double ( 1000 * gridLengthY ) ) ; startx = - gridLengthX * xp ; // km starty = - gridLengthY * yp ; double radius = Earth . getRadius ( ) / 1000.0 ; // km if ( nr == 1111111111.0 ) { // LOOK: not sure how all ones will appear as a double, need example proj = new Orthographic ( Lat0 , Lon0 , radius ) ; attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , \"orthographic\" ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lon0 ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , Lat0 ) ) ; } else { // \"space view perspective\" double height = ( nr - 1.0 ) * radius ; // height = the height of the observing camera in km proj = new VerticalPerspectiveView ( Lat0 , Lon0 , radius , height ) ; attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , \"vertical_perspective\" ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lon0 ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , Lat0 ) ) ; attributes . add ( new Attribute ( \"height_above_earth\" , height ) ) ; } if ( GridServiceProvider . debugProj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) + 360.0 ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( \"GridHorizCoordSys.makeOrthographic end at latlon \" + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( \"   end at proj coord \" + endPP ) ; double endx = startx + getNx ( ) * getDxInKm ( ) ; double endy = starty + getNy ( ) * getDyInKm ( ) ; System . out . println ( \"   should be x=\" + endx + \" y=\" + endy ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a Eumetsat MSG Normalized Geostationary Projection projection . Fake coordinates for now then see if this can be generalized . [CODESPLIT] private void makeMSGgeostationary ( ) { double Lat0 = gds . getDouble ( GridDefRecord . LAP ) ; // sub-satellite point lat double Lon0 = gds . getDouble ( GridDefRecord . LOP ) ; // sub-satellite point lon //int nx = gds.getInt(GridDefRecord.NX); int ny = gds . getInt ( GridDefRecord . NY ) ; int x_off = gds . getInt ( GridDefRecord . XP ) ; // sub-satellite point in grid lengths int y_off = gds . getInt ( GridDefRecord . YP ) ; double dx ; // = gds.getDouble(GridDefRecord.DX);  // apparent diameter of earth in units of grid lengths double dy = gds . getDouble ( GridDefRecord . DY ) ; // per Simon Eliot 1/18/2010, there is a bug in Eumetsat grib files, // we need to \"correct for ellipsoidal earth\" // (Note we should check who the originating center is // \"Originating_center\" = \"EUMETSAT Operation Centre\" in the GRIB id (section 1)) // although AFAIK, eumetsat is only one using this projection. if ( dy < 2100 ) { dx = 1207 ; dy = 1203 ; } else { dx = 3622 ; dy = 3610 ; } // have to check both names because Grib1 and Grib2 used different names double major_axis = gds . getDouble ( GridDefRecord . MAJOR_AXIS_EARTH ) ; // m if ( Double . isNaN ( major_axis ) ) major_axis = gds . getDouble ( \"major_axis_earth\" ) ; double minor_axis = gds . getDouble ( GridDefRecord . MINOR_AXIS_EARTH ) ; // m if ( Double . isNaN ( minor_axis ) ) minor_axis = gds . getDouble ( \"minor_axis_earth\" ) ; // Nr = altitude of camera from center, in units of radius double nr = gds . getDouble ( GridDefRecord . NR ) * 1e-6 ; // altitude of the camera from the Earths centre, measured in units of the Earth (equatorial) radius // CFAC = 2^16 / {[2 * arcsine (10^6 / Nr)] / dx } double as = 2 * Math . asin ( 1.0 / nr ) ; double cfac = dx / as ; double lfac = dy / as ; // use km, so scale by the earth radius double scale_factor = ( nr - 1 ) * major_axis / 1000 ; // this sets the units of the projection x,y coords in km double scale_x = scale_factor ; // LOOK fake neg need scan value double scale_y = - scale_factor ; // LOOK fake neg need scan value startx = scale_factor * ( 1 - x_off ) / cfac ; starty = scale_factor * ( y_off - ny ) / lfac ; incrx = scale_factor / cfac ; incry = scale_factor / lfac ; attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , \"MSGnavigation\" ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lon0 ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , Lat0 ) ) ; //attributes.add(new Attribute(\"semi_major_axis\", new Double(major_axis))); //attributes.add(new Attribute(\"semi_minor_axis\", new Double(minor_axis))); attributes . add ( new Attribute ( \"height_from_earth_center\" , nr * major_axis ) ) ; attributes . add ( new Attribute ( \"scale_x\" , scale_x ) ) ; attributes . add ( new Attribute ( \"scale_y\" , scale_y ) ) ; proj = new MSGnavigation ( Lat0 , Lon0 , major_axis , minor_axis , nr * major_axis , scale_x , scale_y ) ; if ( GridServiceProvider . debugProj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) + 360.0 ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( \"GridHorizCoordSys.makeMSGgeostationary end at latlon \" + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( \"   end at proj coord \" + endPP ) ; double endx = 1 + getNx ( ) ; double endy = 1 + getNy ( ) ; System . out . println ( \"   should be x=\" + endx + \" y=\" + endy ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CurvilinearAxis [CODESPLIT] private void makeCurvilinearAxis ( NetcdfFile ncfile ) { List < Variable > vars = ncfile . getRootGroup ( ) . getVariables ( ) ; String latpp = null , lonpp = null , latU = null , lonU = null , latV = null , lonV = null ; // has to be done twice because there's no guarantee that the // coordinate variables will be accessed first List < String > timeDimLL = new ArrayList <> ( ) ; List < String > timeDimV = new ArrayList <> ( ) ; for ( Variable var : vars ) { if ( var . getShortName ( ) . startsWith ( \"Latitude\" ) ) { // remove time dependency int [ ] shape = var . getShape ( ) ; if ( var . getRank ( ) == 3 && shape [ 0 ] == 1 ) { // remove time dependencies - MAJOR KLUDGE List < Dimension > dims = var . getDimensions ( ) ; if ( ! timeDimLL . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimLL . add ( dims . get ( 0 ) . getShortName ( ) ) ; dims . remove ( 0 ) ; var . setDimensions ( dims ) ; } // add lat attributes var . addAttribute ( new Attribute ( \"units\" , \"degrees_north\" ) ) ; var . addAttribute ( new Attribute ( \"long_name\" , \"latitude coordinate\" ) ) ; var . addAttribute ( new Attribute ( \"standard_name\" , \"latitude\" ) ) ; var . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; if ( var . getShortName ( ) . contains ( \"U_Wind_Component\" ) ) { latU = var . getFullName ( ) ; } else if ( var . getShortName ( ) . contains ( \"V_Wind_Component\" ) ) { latV = var . getFullName ( ) ; } else { latpp = var . getFullName ( ) ; } } else if ( var . getShortName ( ) . startsWith ( \"Longitude\" ) ) { // remove time dependency int [ ] shape = var . getShape ( ) ; if ( var . getRank ( ) == 3 && shape [ 0 ] == 1 ) { // remove time dependencies - MAJOR KLUDGE List < Dimension > dims = var . getDimensions ( ) ; if ( ! timeDimLL . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimLL . add ( dims . get ( 0 ) . getShortName ( ) ) ; dims . remove ( 0 ) ; var . setDimensions ( dims ) ; } // add lon attributes var . addAttribute ( new Attribute ( \"units\" , \"degrees_east\" ) ) ; var . addAttribute ( new Attribute ( \"long_name\" , \"longitude coordinate\" ) ) ; var . addAttribute ( new Attribute ( \"standard_name\" , \"longitude\" ) ) ; var . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; if ( var . getShortName ( ) . contains ( \"U_Wind_Component\" ) ) { lonU = var . getFullName ( ) ; } else if ( var . getShortName ( ) . contains ( \"V_Wind_Component\" ) ) { lonV = var . getFullName ( ) ; } else { lonpp = var . getFullName ( ) ; } } } // add coordinates attribute to variables for ( Variable var : vars ) { List < Dimension > dims = var . getDimensions ( ) ; if ( var . getShortName ( ) . startsWith ( \"U-component\" ) ) { var . addAttribute ( new Attribute ( \"coordinates\" , latU + \" \" + lonU ) ) ; if ( ! timeDimV . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimV . add ( dims . get ( 0 ) . getShortName ( ) ) ; } else if ( var . getShortName ( ) . startsWith ( \"V-component\" ) ) { var . addAttribute ( new Attribute ( \"coordinates\" , latV + \" \" + lonV ) ) ; if ( ! timeDimV . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimV . add ( dims . get ( 0 ) . getShortName ( ) ) ; // rest of variables default to Pressure_Point } else { var . addAttribute ( new Attribute ( \"coordinates\" , latpp + \" \" + lonpp ) ) ; if ( ! timeDimV . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimV . add ( dims . get ( 0 ) . getShortName ( ) ) ; } } /* remove Latitude/Longitude time dimension and variable if possible\n    for( String tdLL : timeDimLL) {\n      if( timeDimV.contains( tdLL ))\n        continue;\n      // else only used with Lat/Lon\n      ncfile.getRootGroup().removeDimension( tdLL );\n      ncfile.getRootGroup().removeVariable( tdLL );\n    } */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the dx and dy from startx starty and projection . [CODESPLIT] private void setDxDy ( double startx , double starty , ProjectionImpl proj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; if ( Double . isNaN ( Lo2 ) || Double . isNaN ( La2 ) ) { return ; } LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; ProjectionPointImpl end = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; double dx = Math . abs ( end . getX ( ) - startx ) / ( gds . getInt ( GridDefRecord . NX ) - 1 ) ; double dy = Math . abs ( end . getY ( ) - starty ) / ( gds . getInt ( GridDefRecord . NY ) - 1 ) ; gds . addParam ( GridDefRecord . DX , String . valueOf ( dx ) ) ; gds . addParam ( GridDefRecord . DY , String . valueOf ( dy ) ) ; gds . addParam ( GridDefRecord . GRID_UNITS , \"km\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate Dx Dy Lat Lon Grid Note : this assumes lo1 < lo2 and dx is positive going east [CODESPLIT] private double setLatLonDxDy ( ) { double lo1 = gds . getDouble ( GridDefRecord . LO1 ) ; double la1 = gds . getDouble ( GridDefRecord . LA1 ) ; double lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double la2 = gds . getDouble ( GridDefRecord . LA2 ) ; if ( Double . isNaN ( lo2 ) || Double . isNaN ( la2 ) ) { return Double . NaN ; } if ( lo2 < lo1 ) lo2 += 360 ; double dx = Math . abs ( lo2 - lo1 ) / ( gds . getInt ( GridDefRecord . NX ) - 1 ) ; double dy = Math . abs ( la2 - la1 ) / ( gds . getInt ( GridDefRecord . NY ) - 1 ) ; gds . addParam ( GridDefRecord . DX , String . valueOf ( dx ) ) ; gds . addParam ( GridDefRecord . DY , String . valueOf ( dy ) ) ; // in case someone checked on these before, we need to override gds . addParam ( GridDefRecord . DX , new Double ( dx ) ) ; gds . addParam ( GridDefRecord . DY , new Double ( dy ) ) ; gds . addParam ( GridDefRecord . GRID_UNITS , \"degree\" ) ; return dy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected InvAccessImpl readAccess ( InvDatasetImpl dataset , Element accessElem ) { String urlPath = accessElem . getAttributeValue ( \"urlPath\" ) ; String serviceName = accessElem . getAttributeValue ( \"serviceName\" ) ; String dataFormat = accessElem . getAttributeValue ( \"dataFormat\" ) ; return new InvAccessImpl ( dataset , urlPath , serviceName , null , dataFormat , readDataSize ( accessElem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read a dataset element [CODESPLIT] protected InvDatasetImpl readDataset ( InvCatalogImpl catalog , InvDatasetImpl parent , Element dsElem , URI base ) { // deal with aliases String name = dsElem . getAttributeValue ( \"name\" ) ; String alias = dsElem . getAttributeValue ( \"alias\" ) ; if ( alias != null ) { InvDatasetImpl ds = ( InvDatasetImpl ) catalog . findDatasetByID ( alias ) ; if ( ds == null ) { factory . appendErr ( \" ** Parse error: dataset named \" + name + \" has illegal alias = \" + alias + \"\\n\" ) ; return null ; } return new InvDatasetImplProxy ( name , ds ) ; } InvDatasetImpl dataset = new InvDatasetImpl ( parent , name ) ; readDatasetInfo ( catalog , dataset , dsElem , base ) ; if ( InvCatalogFactory . debugXML ) System . out . println ( \" Dataset added: \" + dataset . dump ( ) ) ; return dataset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read a dataset scan element [CODESPLIT] protected InvDatasetScan readDatasetScan ( InvCatalogImpl catalog , InvDatasetImpl parent , Element dsElem , URI base ) { InvDatasetScan datasetScan ; if ( dsElem . getAttributeValue ( \"dirLocation\" ) == null ) { if ( dsElem . getAttributeValue ( \"location\" ) == null ) { logger . error ( \"readDatasetScan(): datasetScan has neither a \\\"location\\\" nor a \\\"dirLocation\\\" attribute.\" ) ; datasetScan = null ; } else { return readDatasetScanNew ( catalog , parent , dsElem , base ) ; } } else { String name = dsElem . getAttributeValue ( \"name\" ) ; factory . appendWarning ( \"**Warning: Dataset \" + name + \" using old form of DatasetScan (dirLocation instead of location)\\n\" ) ; String path = dsElem . getAttributeValue ( \"path\" ) ; String scanDir = expandAliasForPath ( dsElem . getAttributeValue ( \"dirLocation\" ) ) ; String filter = dsElem . getAttributeValue ( \"filter\" ) ; String addDatasetSizeString = dsElem . getAttributeValue ( \"addDatasetSize\" ) ; String addLatest = dsElem . getAttributeValue ( \"addLatest\" ) ; String sortOrderIncreasingString = dsElem . getAttributeValue ( \"sortOrderIncreasing\" ) ; boolean sortOrderIncreasing = false ; if ( sortOrderIncreasingString != null ) if ( sortOrderIncreasingString . equalsIgnoreCase ( \"true\" ) ) sortOrderIncreasing = true ; boolean addDatasetSize = true ; if ( addDatasetSizeString != null ) if ( addDatasetSizeString . equalsIgnoreCase ( \"false\" ) ) addDatasetSize = false ; if ( path != null ) { if ( path . charAt ( 0 ) == ' ' ) path = path . substring ( 1 ) ; int last = path . length ( ) - 1 ; if ( path . charAt ( last ) == ' ' ) path = path . substring ( 0 , last ) ; } if ( scanDir != null ) { int last = scanDir . length ( ) - 1 ; if ( scanDir . charAt ( last ) != ' ' ) scanDir = scanDir + ' ' ; } Element atcElem = dsElem . getChild ( \"addTimeCoverage\" , defNS ) ; String dsNameMatchPattern = null ; String startTimeSubstitutionPattern = null ; String duration = null ; if ( atcElem != null ) { dsNameMatchPattern = atcElem . getAttributeValue ( \"datasetNameMatchPattern\" ) ; startTimeSubstitutionPattern = atcElem . getAttributeValue ( \"startTimeSubstitutionPattern\" ) ; duration = atcElem . getAttributeValue ( \"duration\" ) ; } try { datasetScan = new InvDatasetScan ( catalog , parent , name , path , scanDir , filter , addDatasetSize , addLatest , sortOrderIncreasing , dsNameMatchPattern , startTimeSubstitutionPattern , duration ) ; readDatasetInfo ( catalog , datasetScan , dsElem , base ) ; if ( InvCatalogFactory . debugXML ) System . out . println ( \" Dataset added: \" + datasetScan . dump ( ) ) ; } catch ( Exception e ) { logger . error ( \"Reading DatasetScan\" , e ) ; datasetScan = null ; } } return datasetScan ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] protected DatasetEnhancer readDatasetScanAddTimeCoverage ( Element addTimeCovElem ) { DatasetEnhancer timeCovEnhancer = null ; String matchName = addTimeCovElem . getAttributeValue ( \"datasetNameMatchPattern\" ) ; String matchPath = addTimeCovElem . getAttributeValue ( \"datasetPathMatchPattern\" ) ; String subst = addTimeCovElem . getAttributeValue ( \"startTimeSubstitutionPattern\" ) ; String duration = addTimeCovElem . getAttributeValue ( \"duration\" ) ; if ( matchName != null && subst != null && duration != null ) { timeCovEnhancer = RegExpAndDurationTimeCoverageEnhancer . getInstanceToMatchOnDatasetName ( matchName , subst , duration ) ; } else if ( matchPath != null && subst != null && duration != null ) { timeCovEnhancer = RegExpAndDurationTimeCoverageEnhancer . getInstanceToMatchOnDatasetPath ( matchPath , subst , duration ) ; } return timeCovEnhancer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * MetadataConverterIF [CODESPLIT] public Object readMetadataContent ( InvDataset dataset , org . jdom2 . Element mdataElement ) { InvMetadata m = readMetadata ( dataset . getParentCatalog ( ) , ( InvDatasetImpl ) dataset , mdataElement ) ; return m . getThreddsMetadata ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is only called for ThredddsMetadata [CODESPLIT] public Object readMetadataContentFromURL ( InvDataset dataset , java . net . URI uri ) throws java . io . IOException { Element elem = readContentFromURL ( uri ) ; Object contentObject = readMetadataContent ( dataset , elem ) ; if ( debugMetadataRead ) System . out . println ( \" convert to \" + contentObject . getClass ( ) . getName ( ) ) ; return contentObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( InvCatalogImpl catalog , OutputStream os , boolean raw ) throws IOException { this . raw = raw ; writeXML ( catalog , os ) ; this . raw = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * protected void writeCat6InheritedMetadata ( Element elem ThreddsMetadata tmi ) { if (( tmi . getDataType () == null ) && ( tmi . getServiceName () == null ) && ( tmi . getAuthority () == null ) && ( tmi . getProperties () . size () == 0 )) return ; [CODESPLIT] protected void writeInheritedMetadata ( Element elem , ThreddsMetadata tmi ) { Element mdataElem = new Element ( \"metadata\" , defNS ) ; mdataElem . setAttribute ( \"inherited\" , \"true\" ) ; writeThreddsMetadata ( mdataElem , tmi ) ; if ( mdataElem . getChildren ( ) . size ( ) > 0 ) elem . addContent ( mdataElem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the type for the first level of this GridRecord [CODESPLIT] public int getLevelType1 ( ) { // TODO:  flush this out int gribLevel = getDirBlock ( ) [ 51 ] ; int levelType = 0 ; if ( ! ( ( gribLevel == McIDASUtil . MCMISSING ) || ( gribLevel == 0 ) ) ) { levelType = gribLevel ; } else { levelType = 1 ; } return levelType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if this is a valid file for this IOServiceProvider . You must make this method thread safe ie dont keep any state . [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { raf . seek ( 0 ) ; String test = raf . readString ( MAGIC . length ( ) ) ; return test . equals ( MAGIC ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open existing file and populate ncfile with it . This method is only called by the NetcdfFile constructor on itself . The provided NetcdfFile object will be empty except for the location String and the IOServiceProvider associated with this NetcdfFile object . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; Structure seq = new Sequence ( ncfile , null , null , RECORD ) ; ncfile . addVariable ( null , seq ) ; /*\r\n    makeLightningVariable(NetcdfFile ncfile, Group group,\r\n                          Structure seq, String name,\r\n                          DataType dataType, String dims,\r\n                          String longName, String cfName,\r\n                          String units, AxisType type) {\r\n    */ Variable v = makeLightningVariable ( ncfile , null , seq , TSEC , DataType . INT , \"\" , \"time of stroke\" , null , secondsSince1970 , AxisType . Time ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , \"nsec\" , DataType . INT , \"\" , \"nanoseconds since tsec\" , null , \"1.0e-9 s\" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , LAT , DataType . INT , \"\" , \"latitude\" , \"latitude\" , CDM . LAT_UNITS , AxisType . Lat ) ; v . addAttribute ( new Attribute ( CDM . SCALE_FACTOR , new Float ( 1.0e-3 ) ) ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , LON , DataType . INT , \"\" , \"longitude\" , \"longitude\" , CDM . LON_UNITS , AxisType . Lon ) ; v . addAttribute ( new Attribute ( CDM . SCALE_FACTOR , new Float ( 1.0e-3 ) ) ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , SIGNAL , DataType . SHORT , \"\" , \"signal strength/polarity [150 NLDN measures ~= 30 kAmps]\" , null , \"\" , null ) ; v . addAttribute ( new Attribute ( CDM . SCALE_FACTOR , new Float ( 1.0e-1 ) ) ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , MULTIPLICITY , DataType . BYTE , \"\" , \"multiplicity [#strokes per flash]\" , null , \"\" , null ) ; seq . addMemberVariable ( v ) ; v = new Variable ( ncfile , null , seq , FILL ) ; v . setDataType ( DataType . BYTE ) ; v . setDimensions ( \"\" ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , MAJOR_AXIS , DataType . BYTE , \"\" , \"error ellipse semi-major axis\" , null , \"\" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , ECCENTRICITY , DataType . BYTE , \"\" , \"error ellipse eccentricity \" , null , \"\" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , ELLIPSE_ANGLE , DataType . BYTE , \"\" , \"error ellipse axis angle of orientation \" , null , \"degrees\" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , CHISQR , DataType . BYTE , \"\" , \"chi-squared\" , null , \"\" , null ) ; seq . addMemberVariable ( v ) ; addLightningGlobalAttributes ( ncfile ) ; ncfile . finish ( ) ; sm = seq . makeStructureMembers ( ) ; sm . findMember ( TSEC ) . setDataParam ( 0 ) ; sm . findMember ( NSEC ) . setDataParam ( 4 ) ; sm . findMember ( LAT ) . setDataParam ( 8 ) ; sm . findMember ( LON ) . setDataParam ( 12 ) ; sm . findMember ( SIGNAL ) . setDataParam ( 18 ) ; sm . findMember ( MULTIPLICITY ) . setDataParam ( 22 ) ; sm . findMember ( FILL ) . setDataParam ( 23 ) ; sm . findMember ( MAJOR_AXIS ) . setDataParam ( 24 ) ; sm . findMember ( ECCENTRICITY ) . setDataParam ( 25 ) ; sm . findMember ( ELLIPSE_ANGLE ) . setDataParam ( 26 ) ; sm . findMember ( CHISQR ) . setDataParam ( 27 ) ; sm . setStructureSize ( recSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the global attributes . [CODESPLIT] protected void addLightningGlobalAttributes ( NetcdfFile ncfile ) { super . addLightningGlobalAttributes ( ncfile ) ; ncfile . addAttribute ( null , new Attribute ( \"title\" , \"NLDN Lightning Data\" ) ) ; ncfile . addAttribute ( null , new Attribute ( CDM . CONVENTIONS , \"NLDN-CDM\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from a top level Variable and return a memory resident Array . This Array has the same element type as the Variable and the requested shape . [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { return new ArraySequence ( sm , new SeqIter ( ) , nelems ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an array of bytes to the compressed output stream . This method will block until all the bytes are written . [CODESPLIT] public void write ( byte [ ] b , int off , int len ) throws IOException { count += len ; super . write ( b , off , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . <p / > <h2 > Important Note< / h2 > This method overrides the BaseType method of the same name and type signature and it significantly changes the behavior for all versions of <code > printVal () < / code > for this type : <b > <i > All the various versions of printVal () will only print a value or a value with declaration if the variable is in the projection . < / i > < / b > <br > <br > In other words if a call to <code > isProject () < / code > for a particular variable returns <code > true< / code > then <code > printVal () < / code > will print a value ( or a declaration and a value ) . <br > <br > If <code > isProject () < / code > for a particular variable returns <code > false< / code > then <code > printVal () < / code > is basically a No - Op . <br > <br > [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; super . printVal ( os , space , print_decl_p ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The RelOps interface defines how each type responds to relational operators . Most ( all? ) types will not have sensible responses to all of the relational operators ( e . g . DInt won t know how to match a regular expression but DString will ) . For those operators that are nonsensical a class should throw InvalidOperatorException . [CODESPLIT] public boolean equal ( BaseType bt ) throws InvalidOperatorException , RegExpException , SBHException { return ( Operator . op ( EQUAL , this , bt ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Server - side serialization for OPeNDAP variables ( sub - classes of <code > BaseType< / code > ) . This does not send the entire class as the Java <code > Serializable< / code > interface does rather it sends only the binary data values . Other software is responsible for sending variable type information ( see <code > DDS< / code > ) . <p / > Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { if ( ! isRead ( ) ) read ( dataset , specialO ) ; if ( ce . evalClauses ( specialO ) ) externalize ( sink ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the unencoded name of the class instance . [CODESPLIT] @ Override public void setClearName ( String clearname ) { super . setClearName ( clearname ) ; if ( _attr != null ) _attr . setClearName ( clearname ) ; if ( _attrTbl != null ) _attrTbl . setClearName ( clearname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { //LogStream.out.println(\"BaseType.printDecl()...\");\r os . print ( space + getTypeName ( ) + \" \" + getEncodedName ( ) ) ; if ( print_semi ) os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the variable s declaration . Same as <code > printDecl ( os space true ) < / code > . [CODESPLIT] public final void printDecl ( PrintWriter os , String space ) { printDecl ( os , space , true , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the variable s declaration using <code > OutputStream< / code > . [CODESPLIT] public final void printDecl ( OutputStream os , String space , boolean print_semi , boolean constrained ) { PrintWriter pw = new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( os , Util . UTF8 ) ) ) ; printDecl ( pw , space , print_semi , constrained ) ; pw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the variable s declaration using <code > OutputStream< / code > . [CODESPLIT] public final void printDecl ( OutputStream os , String space , boolean print_semi ) { printDecl ( os , space , print_semi , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > BaseType< / code > . See DAPNode . cloneDAG . [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { BaseType bt = ( BaseType ) super . cloneDAG ( map ) ; if ( this . _attrTbl != null ) bt . _attrTbl = ( AttributeTable ) cloneDAG ( map , this . _attrTbl ) ; if ( this . _attr != null ) bt . _attr = new Attribute ( getClearName ( ) , bt . _attrTbl ) ; return bt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : resultTime / gml : TimeInstant [CODESPLIT] public static TimeInstantType initTimeInstant ( TimeInstantType timeInstant ) { // @gml:id String id = MarshallingUtil . createIdForType ( TimeInstantType . class ) ; timeInstant . setId ( id ) ; // gml:timePosition NcTimePositionType . initTimePosition ( timeInstant . addNewTimePosition ( ) ) ; return timeInstant ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to find the coordinate variable of the specified type . [CODESPLIT] static public String getCoordinateName ( NetcdfDataset ds , AxisType a ) { List < Variable > varList = ds . getVariables ( ) ; for ( Variable v : varList ) { if ( v instanceof Structure ) { List < Variable > vars = ( ( Structure ) v ) . getVariables ( ) ; for ( Variable vs : vars ) { String axisType = ds . findAttValueIgnoreCase ( vs , _Coordinate . AxisType , null ) ; if ( ( axisType != null ) && axisType . equals ( a . toString ( ) ) ) return vs . getShortName ( ) ; } } else { String axisType = ds . findAttValueIgnoreCase ( v , _Coordinate . AxisType , null ) ; if ( ( axisType != null ) && axisType . equals ( a . toString ( ) ) ) return v . getShortName ( ) ; } } if ( a == AxisType . Lat ) return findVariableName ( ds , \"latitude\" ) ; if ( a == AxisType . Lon ) return findVariableName ( ds , \"longitude\" ) ; if ( a == AxisType . Time ) return findVariableName ( ds , \"time\" ) ; if ( a == AxisType . Height ) { Variable v = findVariable ( ds , \"altitude\" ) ; if ( null == v ) v = findVariable ( ds , \"depth\" ) ; if ( v != null ) return v . getShortName ( ) ; } // I think the CF part is done by the CoordSysBuilder adding the _CoordinateAxisType attrinutes.\r return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to find the coordinate variable of the specified type which has the specified dimension as its firsst dimension [CODESPLIT] static public String getCoordinateName ( NetcdfDataset ds , AxisType a , Dimension dim ) { String name = getCoordinateName ( ds , a ) ; if ( name == null ) return null ; Variable v = ds . findVariable ( name ) ; if ( v == null ) return null ; if ( v . isScalar ( ) ) return null ; if ( ! v . getDimension ( 0 ) . equals ( dim ) ) return null ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an ErrorResponse to the equivalent XML [CODESPLIT] public String buildXML ( ) { StringBuilder response = new StringBuilder ( ) ; response . append ( \"<Error\" ) ; if ( code > 0 ) response . append ( String . format ( \" httpcode=\\\"%d\\\"\" , code ) ) ; response . append ( \">\\n\" ) ; if ( message != null ) response . append ( \"<Message>\" + getMessage ( ) + \"</Message>\\n\" ) ; if ( context != null ) response . append ( \"<Context>\" + getContext ( ) + \"</Context>\\n\" ) ; if ( otherinfo != null ) response . append ( \"<OtherInformation>\" + getOtherInfo ( ) + \"</OtherInformation>\\n\" ) ; return response . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an ErrorResponse to the equivalent DapException . [CODESPLIT] public DapException buildException ( ) { String XML = buildXML ( ) ; DapException dapex = new DapException ( XML ) . setCode ( code ) ; return dapex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the list of Dimensions that were created [CODESPLIT] private List < Dimension > breakupLevels ( NetcdfDataset ds , Variable levelVar ) throws IOException { if ( debugBreakup ) parseInfo . format ( \"breakupLevels = %s%n\" , levelVar . getShortName ( ) ) ; List < Dimension > dimList = new ArrayList <> ( ) ; ArrayChar levelVarData ; try { levelVarData = ( ArrayChar ) levelVar . read ( ) ; } catch ( IOException ioe ) { return dimList ; } List < String > values = null ; String currentUnits = null ; ArrayChar . StringIterator iter = levelVarData . getStringIterator ( ) ; while ( iter . hasNext ( ) ) { String s = iter . next ( ) ; if ( debugBreakup ) parseInfo . format ( \"   %s%n\" , s ) ; StringTokenizer stoke = new StringTokenizer ( s ) ; /* problem with blank string:\r\n   char pvvLevels(levels_35=35, charsPerLevel=10);\r\n\"MB 1000   \", \"MB 975    \", \"MB 950    \", \"MB 925    \", \"MB 900    \", \"MB 875    \", \"MB 850    \", \"MB 825    \", \"MB 800    \", \"MB 775    \", \"MB 750    \",\r\n\"MB 725    \", \"MB 700    \", \"MB 675    \", \"MB 650    \", \"MB 625    \", \"MB 600    \", \"MB 575    \", \"MB 550    \", \"MB 525    \", \"MB 500    \", \"MB 450    \",\r\n\"MB 400    \", \"MB 350    \", \"MB 300    \", \"MB 250    \", \"MB 200    \", \"MB 150    \", \"MB 100    \", \"BL 0 30   \", \"BL 60 90  \", \"BL 90 120 \", \"BL 120 150\",\r\n\"BL 150 180\", \"\"\r\n*/ if ( ! stoke . hasMoreTokens ( ) ) continue ; // skip it\r // first token is the unit\r String units = stoke . nextToken ( ) . trim ( ) ; if ( ! units . equals ( currentUnits ) ) { if ( values != null ) dimList . add ( makeZCoordAxis ( ds , values , currentUnits ) ) ; values = new ArrayList <> ( ) ; currentUnits = units ; } // next token is the value\r if ( stoke . hasMoreTokens ( ) ) values . add ( stoke . nextToken ( ) ) ; else values . add ( \"0\" ) ; } if ( values != null ) dimList . add ( makeZCoordAxis ( ds , values , currentUnits ) ) ; if ( debugBreakup ) parseInfo . format ( \"  done breakup%n\" ) ; return dimList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make a new variable out of the list in values [CODESPLIT] private Dimension makeZCoordAxis ( NetcdfDataset ds , List < String > values , String units ) throws IOException { int len = values . size ( ) ; String name = makeZCoordName ( units ) ; if ( len > 1 ) name = name + Integer . toString ( len ) ; else name = name + values . get ( 0 ) ; StringUtil2 . replace ( name , ' ' , \"-\" ) ; Dimension dim ; if ( null != ( dim = ds . getRootGroup ( ) . findDimension ( name ) ) ) { if ( dim . getLength ( ) == len ) { // check against actual values\r Variable coord = ds . getRootGroup ( ) . findVariable ( name ) ; Array coordData = coord . read ( ) ; Array newData = Array . makeArray ( coord . getDataType ( ) , values ) ; if ( MAMath . nearlyEquals ( coordData , newData ) ) { if ( debugBreakup ) parseInfo . format ( \"  use existing coord %s%n\" , dim ) ; return dim ; } } } String orgName = name ; int count = 1 ; while ( ds . getRootGroup ( ) . findDimension ( name ) != null ) { name = orgName + \"-\" + count ; count ++ ; } // create new one\r dim = new Dimension ( name , len ) ; ds . addDimension ( null , dim ) ; if ( debugBreakup ) parseInfo . format ( \"  make Dimension = %s length = %d%n\" , name , len ) ; // if (len < 2) return dim; // skip 1D\r if ( debugBreakup ) { parseInfo . format ( \"  make ZCoordAxis = = %s length = %d%n\" , name , len ) ; } CoordinateAxis v = new CoordinateAxis1D ( ds , null , name , DataType . DOUBLE , name , makeUnitsName ( units ) , makeLongName ( name ) ) ; String positive = getZisPositive ( ds , v ) ; if ( null != positive ) v . addAttribute ( new Attribute ( _Coordinate . ZisPositive , positive ) ) ; v . setValues ( values ) ; ds . addCoordinateAxis ( v ) ; parseInfo . format ( \"Created Z Coordinate Axis = \" ) ; v . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( \"%n\" ) ; return dim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create new variables as sections of ncVar [CODESPLIT] private void createNewVariables ( NetcdfDataset ds , Variable ncVar , List < Dimension > newDims , Dimension levelDim ) throws InvalidRangeException { List < Dimension > dims = ncVar . getDimensions ( ) ; int newDimIndex = dims . indexOf ( levelDim ) ; //String shapeS = ncVar.getShapeS();\r int [ ] origin = new int [ ncVar . getRank ( ) ] ; int [ ] shape = ncVar . getShape ( ) ; int count = 0 ; for ( Dimension dim : newDims ) { String name = ncVar . getShortName ( ) + \"-\" + dim . getShortName ( ) ; origin [ newDimIndex ] = count ; shape [ newDimIndex ] = dim . getLength ( ) ; Variable varNew = ncVar . section ( new Section ( origin , shape ) ) ; varNew . setName ( name ) ; varNew . setDimension ( newDimIndex , dim ) ; // synthesize long name\r String long_name = ds . findAttValueIgnoreCase ( ncVar , CDM . LONG_NAME , ncVar . getShortName ( ) ) ; long_name = long_name + \"-\" + dim . getShortName ( ) ; ds . addVariableAttribute ( varNew , new Attribute ( CDM . LONG_NAME , long_name ) ) ; ds . addVariable ( null , varNew ) ; parseInfo . format ( \"Created New Variable as section = \" ) ; varNew . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( \"%n\" ) ; count += dim . getLength ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct time coordinate from reftime variable [CODESPLIT] private CoordinateAxis makeTimeCoordAxisFromReference ( NetcdfDataset ds , Variable timeVar , Array vals ) { Variable refVar = ds . findVariable ( \"reftime\" ) ; if ( refVar == null ) return null ; double refValue ; try { Array refArray = refVar . read ( ) ; refValue = refArray . getDouble ( refArray . getIndex ( ) ) ; // get the first value\r } catch ( IOException ioe ) { return null ; } if ( refValue == N3iosp . NC_FILL_DOUBLE ) return null ; // construct the values array - make it a double to be safe\r Array dvals = Array . factory ( DataType . DOUBLE , vals . getShape ( ) ) ; IndexIterator diter = dvals . getIndexIterator ( ) ; IndexIterator iiter = vals . getIndexIterator ( ) ; while ( iiter . hasNext ( ) ) diter . setDoubleNext ( iiter . getDoubleNext ( ) + refValue ) ; // add reftime to each of the values\r String units = ds . findAttValueIgnoreCase ( refVar , CDM . UNITS , \"seconds since 1970-1-1 00:00:00\" ) ; units = normalize ( units ) ; String desc = \"synthesized time coordinate from reftime, valtimeMINUSreftime\" ; CoordinateAxis1D timeCoord = new CoordinateAxis1D ( ds , null , \"timeCoord\" , DataType . DOUBLE , \"record\" , units , desc ) ; timeCoord . setCachedData ( dvals , true ) ; parseInfo . format ( \"Created Time Coordinate Axis From Reference = \" ) ; timeCoord . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( \"%n\" ) ; return timeCoord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shave n bits off the float [CODESPLIT] public static float bitShave ( float value , int bitMask ) { if ( Float . isNaN ( value ) ) return value ; // ?? int bits = Float . floatToRawIntBits ( value ) ; int shave = bits & bitMask ; return Float . intBitsToFloat ( shave ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write Grib file to a netcdf4 file . Experimental . [CODESPLIT] public static void main ( String [ ] args ) { String fileIn = ( args . length > 0 ) ? args [ 0 ] : \"Q:/cdmUnitTest/formats/grib2/LMPEF_CLM_050518_1200.grb\" ; String fileOut = ( args . length > 1 ) ? args [ 1 ] : \"C:/tmp/ds.mint.bi\" ; try ( GribToNetcdfWriter writer = new GribToNetcdfWriter ( fileIn , fileOut ) ) { writer . write ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the set of Enhancements that is associated with the given string . <p / > <table border = 1 > <tr > <th > String< / th > <th > Enhancements< / th > < / tr > <tr > <td > All< / td > <td > ConvertEnums ConvertUnsigned ApplyScaleOffset ConvertMissing CoordSystems< / td > < / tr > <tr > <td > None< / td > <td > &lt ; empty&gt ; < / td > < / tr > <tr > <td > ConvertEnums< / td > <td > ConvertEnums< / td > < / tr > <tr > <td > ConvertUnsigned< / td > <td > ConvertUnsigned< / td > < / tr > <tr > <td > ApplyScaleOffset< / td > <td > ApplyScaleOffset< / td > < / tr > <tr > <td > ConvertMissing< / td > <td > ConvertMissing< / td > < / tr > <tr > <td > CoordSystems< / td > <td > CoordSystems< / td > < / tr > <tr > <td > IncompleteCoordSystems< / td > <td > CoordSystems< / td > < / tr > <tr > <td > true< / td > <td > Alias for All < / td > < / tr > <tr > <td > ScaleMissingDefer< / td > <td > Alias for None < / td > < / tr > <tr > <td > AllDefer< / td > <td > ConvertEnums CoordSystems< / td > < / tr > <tr > <td > ScaleMissing< / td > <td > ConvertUnsigned ApplyScaleOffset ConvertMissing< / td > < / tr > < / table > [CODESPLIT] static public Set < Enhance > parseEnhanceMode ( String enhanceMode ) { if ( enhanceMode == null ) return null ; switch ( enhanceMode . toLowerCase ( ) ) { case \"all\" : return getEnhanceAll ( ) ; case \"none\" : return getEnhanceNone ( ) ; case \"convertenums\" : return EnumSet . of ( Enhance . ConvertEnums ) ; case \"convertunsigned\" : return EnumSet . of ( Enhance . ConvertUnsigned ) ; case \"applyscaleoffset\" : return EnumSet . of ( Enhance . ApplyScaleOffset ) ; case \"convertmissing\" : return EnumSet . of ( Enhance . ConvertMissing ) ; case \"coordsystems\" : return EnumSet . of ( Enhance . CoordSystems ) ; case \"incompletecoordsystems\" : return EnumSet . of ( Enhance . CoordSystems , Enhance . IncompleteCoordSystems ) ; // Legacy strings, retained for backwards compatibility: case \"true\" : return getEnhanceAll ( ) ; case \"scalemissingdefer\" : return getEnhanceNone ( ) ; case \"alldefer\" : return EnumSet . of ( Enhance . ConvertEnums , Enhance . CoordSystems ) ; case \"scalemissing\" : return EnumSet . of ( Enhance . ConvertUnsigned , Enhance . ApplyScaleOffset , Enhance . ConvertMissing ) ; // Return null by default, since some valid strings actually return an empty set. default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable file caching . call this before calling acquireFile () . When application terminates call NetcdfDataset . shutdown () . [CODESPLIT] static public synchronized void initNetcdfFileCache ( int minElementsInMemory , int maxElementsInMemory , int hardLimit , int period ) { netcdfFileCache = new ucar . nc2 . util . cache . FileCache ( \"NetcdfFileCache \" , minElementsInMemory , maxElementsInMemory , hardLimit , period ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make NetcdfFile into NetcdfDataset with given enhance mode [CODESPLIT] static public NetcdfDataset wrap ( NetcdfFile ncfile , Set < Enhance > mode ) throws IOException { if ( ncfile instanceof NetcdfDataset ) { NetcdfDataset ncd = ( NetcdfDataset ) ncfile ; if ( ! ncd . enhanceNeeded ( mode ) ) return ( NetcdfDataset ) ncfile ; } // enhancement requires wrappping, to not modify underlying dataset, eg if cached // perhaps need a method variant that allows the ncfile to be modified return new NetcdfDataset ( ncfile , mode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for opening a dataset through the netCDF API and identifying its coordinate variables . [CODESPLIT] static public NetcdfDataset openDataset ( String location , boolean enhance , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return openDataset ( location , enhance , - 1 , cancelTask , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for opening a dataset through the netCDF API and identifying its coordinate variables . [CODESPLIT] static public NetcdfDataset openDataset ( String location , boolean enhance , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; return openDataset ( durl , enhance ? defaultEnhanceMode : null , buffer_size , cancelTask , spiObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for opening a dataset through the netCDF API and identifying its coordinate variables . [CODESPLIT] static public NetcdfDataset openDataset ( DatasetUrl location , Set < Enhance > enhanceMode , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { // do not acquire NetcdfFile ncfile = openOrAcquireFile ( null , null , null , location , buffer_size , cancelTask , spiObject ) ; NetcdfDataset ds ; if ( ncfile instanceof NetcdfDataset ) { ds = ( NetcdfDataset ) ncfile ; enhance ( ds , enhanceMode , cancelTask ) ; // enhance \"in place\", ie modify the NetcdfDataset } else { ds = new NetcdfDataset ( ncfile , enhanceMode ) ; // enhance when wrapping } return ds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Enhancement use cases 1 . open NetcdfDataset ( enhance ) . 2 . NcML - must create the NetcdfDataset and enhance when its done . [CODESPLIT] static private CoordSysBuilderIF enhance ( NetcdfDataset ds , Set < Enhance > mode , CancelTask cancelTask ) throws IOException { if ( mode == null ) { mode = EnumSet . noneOf ( Enhance . class ) ; } // CoordSysBuilder may enhance dataset: add new variables, attributes, etc CoordSysBuilderIF builder = null ; if ( mode . contains ( Enhance . CoordSystems ) && ! ds . enhanceMode . contains ( Enhance . CoordSystems ) ) { builder = ucar . nc2 . dataset . CoordSysBuilder . factory ( ds , cancelTask ) ; builder . augmentDataset ( ds , cancelTask ) ; ds . convUsed = builder . getConventionUsed ( ) ; } // now enhance enum/scale/offset/unsigned, using augmented dataset if ( ( mode . contains ( Enhance . ConvertEnums ) && ! ds . enhanceMode . contains ( Enhance . ConvertEnums ) ) || ( mode . contains ( Enhance . ConvertUnsigned ) && ! ds . enhanceMode . contains ( Enhance . ConvertUnsigned ) ) || ( mode . contains ( Enhance . ApplyScaleOffset ) && ! ds . enhanceMode . contains ( Enhance . ApplyScaleOffset ) ) || ( mode . contains ( Enhance . ConvertMissing ) && ! ds . enhanceMode . contains ( Enhance . ConvertMissing ) ) ) { for ( Variable v : ds . getVariables ( ) ) { VariableEnhanced ve = ( VariableEnhanced ) v ; ve . enhance ( mode ) ; if ( ( cancelTask != null ) && cancelTask . isCancel ( ) ) return null ; } } // now find coord systems which may change some Variables to axes, etc if ( builder != null ) { // temporarily set enhanceMode if incomplete coordinate systems are allowed if ( mode . contains ( Enhance . IncompleteCoordSystems ) ) { ds . enhanceMode . add ( Enhance . IncompleteCoordSystems ) ; builder . buildCoordinateSystems ( ds ) ; ds . enhanceMode . remove ( Enhance . IncompleteCoordSystems ) ; } else { builder . buildCoordinateSystems ( ds ) ; } } /* timeTaxis must be CoordinateAxis1DTime\n    for (CoordinateSystem cs : ds.getCoordinateSystems()) {\n      cs.makeTimeAxis();\n    } */ ds . finish ( ) ; // recalc the global lists ds . enhanceMode . addAll ( mode ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as openDataset but file is acquired through the File Cache with defaultEnhanceMode without the need of setting the enhanceMode via the signature . You still close with NetcdfDataset . close () the release is handled automatically . You must first call initNetcdfFileCache () for caching to actually take place . [CODESPLIT] static public NetcdfDataset acquireDataset ( DatasetUrl location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return acquireDataset ( null , location , defaultEnhanceMode , - 1 , cancelTask , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * static public NetcdfDataset acquireDataset ( FileFactory fac String location Set<Enhance > enhanceMode int buffer_size ucar . nc2 . util . CancelTask cancelTask Object iospMessage ) throws IOException { [CODESPLIT] static public NetcdfDataset acquireDataset ( FileFactory fac , DatasetUrl durl , Set < Enhance > enhanceMode , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object iospMessage ) throws IOException { // caching not turned on if ( netcdfFileCache == null ) { if ( fac == null ) return openDataset ( durl , enhanceMode , buffer_size , cancelTask , iospMessage ) ; else // must use the factory if there is one return ( NetcdfDataset ) fac . open ( durl , buffer_size , cancelTask , iospMessage ) ; } if ( fac != null ) return ( NetcdfDataset ) openOrAcquireFile ( netcdfFileCache , fac , null , durl , buffer_size , cancelTask , iospMessage ) ; fac = new MyNetcdfDatasetFactory ( durl , enhanceMode ) ; return ( NetcdfDataset ) openOrAcquireFile ( netcdfFileCache , fac , fac . hashCode ( ) , durl , buffer_size , cancelTask , iospMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for opening a NetcdfFile through the netCDF API . [CODESPLIT] public static NetcdfFile openFile ( String location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; return openOrAcquireFile ( null , null , null , durl , - 1 , cancelTask , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for opening a NetcdfFile through the netCDF API . May be any kind of file that can be read through the netCDF API including OpenDAP and NcML . <p > <p > This does not necessarily return a NetcdfDataset or enhance the dataset ; use NetcdfDataset . openDataset () method for that . [CODESPLIT] public static NetcdfFile openFile ( DatasetUrl location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { return openOrAcquireFile ( null , null , null , location , buffer_size , cancelTask , spiObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as openFile but file is acquired through the File Cache . You still close with NetcdfFile . close () the release is handled automatically . You must first call initNetcdfFileCache () for caching to actually take place . [CODESPLIT] static public NetcdfFile acquireFile ( DatasetUrl location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return acquireFile ( null , null , location , - 1 , cancelTask , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as openFile but file is acquired through the File Cache . You still close with NetcdfFile . close () the release is handled automatically . You must first call initNetcdfFileCache () for caching to actually take place . [CODESPLIT] static public NetcdfFile acquireFile ( ucar . nc2 . util . cache . FileFactory factory , Object hashKey , DatasetUrl location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { // must use the factory if there is one but no fileCache if ( ( netcdfFileCache == null ) && ( factory != null ) ) { return ( NetcdfFile ) factory . open ( location , buffer_size , cancelTask , spiObject ) ; } return openOrAcquireFile ( netcdfFileCache , factory , hashKey , location , buffer_size , cancelTask , spiObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Open or acquire a NetcdfFile . [CODESPLIT] static private NetcdfFile openOrAcquireFile ( FileCache cache , FileFactory factory , Object hashKey , DatasetUrl durl , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { if ( durl . serviceType != null ) { switch ( durl . serviceType ) { case OPENDAP : return acquireDODS ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case CdmRemote : return acquireCdmRemote ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case DAP4 : return acquireDap4 ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case NCML : return acquireNcml ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case THREDDS : Formatter log = new Formatter ( ) ; DataFactory tdf = new DataFactory ( ) ; NetcdfFile ncfile = tdf . openDataset ( durl . trueurl , false , cancelTask , log ) ; // LOOK acquire ?? if ( ncfile == null ) throw new IOException ( log . toString ( ) ) ; return ncfile ; case File : case HTTPServer : break ; // fall through default : throw new IOException ( \"Unknown service type: \" + durl . serviceType . toString ( ) ) ; } } // Next to last resort: find in the cache if ( cache != null ) { if ( factory == null ) factory = defaultNetcdfFileFactory ; return ( NetcdfFile ) cache . acquire ( factory , hashKey , durl , buffer_size , cancelTask , spiObject ) ; } // Last resort: try to open as a file or remote file return NetcdfFile . open ( durl . trueurl , buffer_size , cancelTask , spiObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] static private NetcdfFile acquireNcml ( FileCache cache , FileFactory factory , Object hashKey , String location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { if ( cache == null ) return NcMLReader . readNcML ( location , cancelTask ) ; if ( factory == null ) factory = new NcMLFactory ( ) ; // LOOK maybe always should use NcMLFactory ? return ( NetcdfFile ) cache . acquire ( factory , hashKey , DatasetUrl . findDatasetUrl ( location ) , buffer_size , cancelTask , spiObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear Coordinate System metadata to allow them to be redone [CODESPLIT] public void clearCoordinateSystems ( ) { coordSys = new ArrayList <> ( ) ; coordAxes = new ArrayList <> ( ) ; coordTransforms = new ArrayList <> ( ) ; for ( Variable v : getVariables ( ) ) { VariableEnhanced ve = ( VariableEnhanced ) v ; ve . clearCoordinateSystems ( ) ; // ?? } enhanceMode . remove ( Enhance . CoordSystems ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the CoordinateAxis with the specified Axis Type . [CODESPLIT] public CoordinateAxis findCoordinateAxis ( AxisType type ) { if ( type == null ) return null ; for ( CoordinateAxis v : coordAxes ) { if ( type == v . getAxisType ( ) ) return v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the CoordinateAxis with the specified type . [CODESPLIT] public CoordinateAxis findCoordinateAxis ( String fullName ) { if ( fullName == null ) return null ; for ( CoordinateAxis v : coordAxes ) { if ( fullName . equals ( v . getFullName ( ) ) ) return v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the CoordinateSystem with the specified name . [CODESPLIT] public CoordinateSystem findCoordinateSystem ( String name ) { if ( name == null ) return null ; for ( CoordinateSystem v : coordSys ) { if ( name . equals ( v . getName ( ) ) ) return v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the CoordinateTransform with the specified name . [CODESPLIT] public CoordinateTransform findCoordinateTransform ( String name ) { if ( name == null ) return null ; for ( CoordinateTransform v : coordTransforms ) { if ( name . equals ( v . getName ( ) ) ) return v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close all resources ( files sockets etc ) associated with this dataset . If the underlying file was acquired it will be released otherwise closed . [CODESPLIT] @ Override public synchronized void close ( ) throws java . io . IOException { if ( agg != null ) { agg . persistWrite ( ) ; // LOOK  maybe only on real close ?? agg . close ( ) ; } if ( cache != null ) { //unlocked = true; if ( cache . release ( this ) ) return ; } if ( orgFile != null ) orgFile . close ( ) ; orgFile = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////// [CODESPLIT] @ Override protected Boolean makeRecordStructure ( ) { if ( this . orgFile == null ) return false ; Boolean hasRecord = ( Boolean ) this . orgFile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ( hasRecord == null ) || ! hasRecord ) return false ; Variable orgV = this . orgFile . getRootGroup ( ) . findVariable ( \"record\" ) ; if ( ( orgV == null ) || ! ( orgV instanceof Structure ) ) return false ; Structure orgStructure = ( Structure ) orgV ; Dimension udim = getUnlimitedDimension ( ) ; if ( udim == null ) return false ; Group root = getRootGroup ( ) ; StructureDS newStructure = new StructureDS ( this , root , null , \"record\" , udim . getShortName ( ) , null , null ) ; newStructure . setOriginalVariable ( orgStructure ) ; for ( Variable v : getVariables ( ) ) { if ( ! v . isUnlimited ( ) ) continue ; VariableDS memberV ; try { memberV = ( VariableDS ) v . slice ( 0 , 0 ) ; // set unlimited dimension to 0 } catch ( InvalidRangeException e ) { log . error ( \"Cant slice variable \" + v ) ; return false ; } memberV . setParentStructure ( newStructure ) ; // reparent /* memberV.createNewCache(); // decouple caching\n      //orgV = orgStructure.findVariable(v.getShortName());\n      //if (orgV != null)\n      //  memberV.setOriginalVariable(orgV);\n\n      // remove record dimension\n      List<Dimension> dims = new ArrayList<Dimension>(v.getDimensions());\n      dims.remove(0);\n      memberV.setDimensions(dims); */ newStructure . addMemberVariable ( memberV ) ; } root . addVariable ( newStructure ) ; finish ( ) ; //if (isEnhancedScaleOffset()) //  newStructure.enhance(); return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a CoordinateAxis to the dataset by turning the VariableDS into a CoordinateAxis ( if needed ) . Also adds it to the list of variables . Replaces any existing Variable and CoordinateAxis with the same name . [CODESPLIT] public CoordinateAxis addCoordinateAxis ( VariableDS v ) { if ( v == null ) return null ; CoordinateAxis oldVar = findCoordinateAxis ( v . getFullName ( ) ) ; if ( oldVar != null ) coordAxes . remove ( oldVar ) ; CoordinateAxis ca = ( v instanceof CoordinateAxis ) ? ( CoordinateAxis ) v : CoordinateAxis . factory ( this , v ) ; coordAxes . add ( ca ) ; if ( v . isMemberOfStructure ( ) ) { Structure parentOrg = v . getParentStructure ( ) ; // gotta be careful to get the wrapping parent Structure parent = ( Structure ) findVariable ( parentOrg . getFullNameEscaped ( ) ) ; parent . replaceMemberVariable ( ca ) ; } else { removeVariable ( v . getParentGroup ( ) , v . getShortName ( ) ) ; // remove by short name if it exists addVariable ( ca . getParentGroup ( ) , ca ) ; } return ca ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is this enhancement already done ? [CODESPLIT] public boolean enhanceNeeded ( Set < Enhance > want ) throws IOException { if ( want == null ) return false ; for ( Enhance mode : want ) { if ( ! this . enhanceMode . contains ( mode ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the list of values from a starting value and an increment . Will reshape to variable if needed . [CODESPLIT] public void setValues ( Variable v , int npts , double start , double incr ) { if ( npts != v . getSize ( ) ) throw new IllegalArgumentException ( \"bad npts = \" + npts + \" should be \" + v . getSize ( ) ) ; Array data = Array . makeArray ( v . getDataType ( ) , npts , start , incr ) ; if ( v . getRank ( ) != 1 ) data = data . reshape ( v . getShape ( ) ) ; v . setCachedData ( data , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data values from a list of Strings . [CODESPLIT] public void setValues ( Variable v , List < String > values ) throws IllegalArgumentException { Array data = Array . makeArray ( v . getDataType ( ) , values ) ; if ( data . getSize ( ) != v . getSize ( ) ) throw new IllegalArgumentException ( \"Incorrect number of values specified for the Variable \" + v . getFullName ( ) + \" needed= \" + v . getSize ( ) + \" given=\" + data . getSize ( ) ) ; if ( v . getRank ( ) != 1 ) // dont have to reshape for rank 1 data = data . reshape ( v . getShape ( ) ) ; v . setCachedData ( data , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a 1D array from a list of strings . [CODESPLIT] static public Array makeArray ( DataType dtype , List < String > stringValues ) throws NumberFormatException { return Array . makeArray ( dtype , stringValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show debug / underlying implementation details [CODESPLIT] @ Override public void getDetailInfo ( Formatter f ) { f . format ( \"NetcdfDataset location= %s%n\" , getLocation ( ) ) ; f . format ( \"  title= %s%n\" , getTitle ( ) ) ; f . format ( \"  id= %s%n\" , getId ( ) ) ; f . format ( \"  fileType= %s%n\" , getFileTypeId ( ) ) ; f . format ( \"  fileDesc= %s%n\" , getFileTypeDescription ( ) ) ; f . format ( \"  class= %s%n\" , getClass ( ) . getName ( ) ) ; if ( agg == null ) { f . format ( \"  has no Aggregation element%n\" ) ; } else { f . format ( \"%nAggregation:%n\" ) ; agg . getDetailInfo ( f ) ; } if ( orgFile == null ) { f . format ( \"  has no referenced NetcdfFile%n\" ) ; showCached ( f ) ; showProxies ( f ) ; } else { f . format ( \"%nReferenced File:%n\" ) ; f . format ( \"%s\" , orgFile . getDetailInfo ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Debugging : get the information from parsing [CODESPLIT] void dumpClasses ( Group g , PrintWriter out ) { out . println ( \"Dimensions:\" ) ; for ( Dimension ds : g . getDimensions ( ) ) { out . println ( \"  \" + ds . getShortName ( ) + \" \" + ds . getClass ( ) . getName ( ) ) ; } out . println ( \"Atributes:\" ) ; for ( Attribute a : g . getAttributes ( ) ) { out . println ( \"  \" + a . getShortName ( ) + \" \" + a . getClass ( ) . getName ( ) ) ; } out . println ( \"Variables:\" ) ; dumpVariables ( g . getVariables ( ) , out ) ; out . println ( \"Groups:\" ) ; for ( Group nested : g . getGroups ( ) ) { out . println ( \"  \" + nested . getFullName ( ) + \" \" + nested . getClass ( ) . getName ( ) ) ; dumpClasses ( nested , out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debugging [CODESPLIT] public static void debugDump ( PrintWriter out , NetcdfDataset ncd ) { String referencedLocation = ncd . orgFile == null ? \"(null)\" : ncd . orgFile . getLocation ( ) ; out . println ( \"\\nNetcdfDataset dump = \" + ncd . getLocation ( ) + \" url= \" + referencedLocation + \"\\n\" ) ; ncd . dumpClasses ( ncd . getRootGroup ( ) , out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK : Can we use CFPointWriter . CommandLine for CLI parsing instead? Would that break existing scripts? [CODESPLIT] public static void main ( String arg [ ] ) throws IOException { String usage = \"usage: ucar.nc2.dataset.NetcdfDataset -in <fileIn> -out <fileOut> [-isLargeFile] [-netcdf4]\" ; if ( arg . length < 4 ) { System . out . println ( usage ) ; System . exit ( 0 ) ; } boolean isLargeFile = false ; boolean netcdf4 = false ; String datasetIn = null , datasetOut = null ; for ( int i = 0 ; i < arg . length ; i ++ ) { String s = arg [ i ] ; if ( s . equalsIgnoreCase ( \"-in\" ) ) datasetIn = arg [ i + 1 ] ; if ( s . equalsIgnoreCase ( \"-out\" ) ) datasetOut = arg [ i + 1 ] ; if ( s . equalsIgnoreCase ( \"-isLargeFile\" ) ) isLargeFile = true ; if ( s . equalsIgnoreCase ( \"-netcdf4\" ) ) netcdf4 = true ; } if ( ( datasetIn == null ) || ( datasetOut == null ) ) { System . out . println ( usage ) ; System . exit ( 0 ) ; } CancelTaskImpl cancel = new CancelTaskImpl ( ) ; NetcdfFile ncfileIn = ucar . nc2 . dataset . NetcdfDataset . openFile ( datasetIn , cancel ) ; System . out . printf ( \"NetcdfDatataset read from %s write to %s \" , datasetIn , datasetOut ) ; NetcdfFileWriter . Version version = netcdf4 ? NetcdfFileWriter . Version . netcdf4 : NetcdfFileWriter . Version . netcdf3 ; FileWriter2 writer = new ucar . nc2 . FileWriter2 ( ncfileIn , datasetOut , version , null ) ; writer . getNetcdfFileWriter ( ) . setLargeFile ( isLargeFile ) ; NetcdfFile ncfileOut = writer . write ( cancel ) ; if ( ncfileOut != null ) ncfileOut . close ( ) ; ncfileIn . close ( ) ; cancel . setDone ( true ) ; System . out . printf ( \"%s%n\" , cancel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static FeatureDatasetPoint getPointDataset ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsPointDataset ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static GridDataset getGridDataset ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsGridDataset ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static CoverageCollection getCoverageCollection ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsCoverageDataset ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static NetcdfFile getNetcdfFile ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsNetcdfFile ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public FeatureDatasetPoint openAsPointDataset ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return datasetManager . openPointDataset ( request , response , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public CoverageCollection openAsCoverageDataset ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return datasetManager . openCoverageDataset ( request , response , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public GridDataset openAsGridDataset ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return isRemote ? ucar . nc2 . dt . grid . GridDataset . open ( path ) : datasetManager . openGridDataset ( request , response , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public NetcdfFile openAsNetcdfFile ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return isRemote ? NetcdfDataset . openDataset ( path ) : datasetManager . openNetcdfFile ( request , response , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when we dont know how many in the iteration [CODESPLIT] private Array extractMemberArrayFromIteration ( StructureMembers . Member proxym , int [ ] rshape ) throws IOException { DataType dataType = proxym . getDataType ( ) ; Object dataArray = null ; int count = 0 ; int initial = 1000 ; try ( StructureDataIterator sdataIter = getStructureDataIterator ( ) ) { switch ( dataType ) { case DOUBLE : { ArrayList < Double > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; double [ ] data = sdata . getJavaArrayDouble ( realm ) ; for ( double aData : data ) result . ( aData ) ; count ++ ; } double [ ] da = new double [ result . size ( ) ] ; int i = 0 ; for ( Double d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case FLOAT : { ArrayList < Float > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; float [ ] data = sdata . getJavaArrayFloat ( realm ) ; for ( float aData : data ) result . ( aData ) ; count ++ ; } float [ ] da = new float [ result . size ( ) ] ; int i = 0 ; for ( Float d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case UBYTE : case BYTE : case ENUM1 : { ArrayList < Byte > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; byte [ ] data = sdata . getJavaArrayByte ( realm ) ; for ( byte aData : data ) result . ( aData ) ; count ++ ; } byte [ ] da = new byte [ result . size ( ) ] ; int i = 0 ; for ( Byte d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case USHORT : case SHORT : case ENUM2 : { ArrayList < Short > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; short [ ] data = sdata . getJavaArrayShort ( realm ) ; for ( short aData : data ) result . ( aData ) ; count ++ ; } short [ ] da = new short [ result . size ( ) ] ; int i = 0 ; for ( Short d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case UINT : case INT : case ENUM4 : { ArrayList < Integer > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; int [ ] data = sdata . getJavaArrayInt ( realm ) ; for ( int aData : data ) result . ( aData ) ; count ++ ; } int [ ] da = new int [ result . size ( ) ] ; int i = 0 ; for ( Integer d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case ULONG : case LONG : { ArrayList < Long > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; long [ ] data = sdata . getJavaArrayLong ( realm ) ; for ( long aData : data ) result . ( aData ) ; count ++ ; } long [ ] da = new long [ result . size ( ) ] ; int i = 0 ; for ( Long d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case CHAR : { ArrayList < Character > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; char [ ] data = sdata . getJavaArrayChar ( realm ) ; for ( char aData : data ) result . ( aData ) ; count ++ ; } char [ ] da = new char [ result . size ( ) ] ; int i = 0 ; for ( Character d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case STRING : { ArrayList < String > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; String [ ] data = sdata . getJavaArrayString ( realm ) ; result . addAll ( Arrays . asList ( data ) ) ; count ++ ; } String [ ] da = new String [ result . size ( ) ] ; int i = 0 ; for ( String d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case STRUCTURE : { ArrayList < StructureData > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; ArrayStructure as = sdata . getArrayStructure ( realm ) ; StructureDataIterator innerIter = as . getStructureDataIterator ( ) ; while ( innerIter . hasNext ( ) ) result . add ( innerIter . next ( ) ) ; count ++ ; } rshape [ 0 ] = count ; StructureMembers membersw = new StructureMembers ( proxym . getStructureMembers ( ) ) ; // no data arrays get propagated\r return new ArrayStructureW ( membersw , rshape , result . toArray ( new StructureData [ 0 ] ) ) ; } } } // create an array to hold the result\r rshape [ 0 ] = count ; return Array . factory ( dataType , rshape , dataArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the linear index from the current odometer indices . [CODESPLIT] public long index ( ) { long offset = 0 ; for ( int i = 0 ; i < this . indices . length ; i ++ ) { offset *= this . dimsizes [ i ] ; offset += this . indices [ i ] ; } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make MFileOS7 if file exists otherwise return null [CODESPLIT] static public MFileOS7 getExistingFile ( String filename ) throws IOException { if ( filename == null ) return null ; Path path = Paths . get ( filename ) ; if ( Files . exists ( path ) ) return new MFileOS7 ( path ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the known ServiceType that matches the given name ( ignoring case ) or null if the name is unknown . [CODESPLIT] public static ServiceType findType ( String name ) { if ( name == null ) return null ; for ( ServiceType serviceType : members ) { if ( serviceType . name . equalsIgnoreCase ( name ) ) return serviceType ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a ServiceType that matches the given name by either matching a known type ( ignoring case ) or creating an unknown type . [CODESPLIT] public static ServiceType getType ( String name ) { if ( name == null ) return null ; ServiceType type = findType ( name ) ; return type != null ? type : new ServiceType ( name , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public void setCollection ( String filename ) throws IOException { if ( filename . endsWith ( GribCollection . IDX_EXT )) { openIndex ( filename ) ; } else { openCollection ( filename ) ; } } [CODESPLIT] public void setCollection ( String spec ) throws IOException { this . spec = spec ; this . cust = null ; Formatter f = new Formatter ( ) ; this . dcm = scanCollection ( spec , f ) ; if ( dcm == null ) { javax . swing . JOptionPane . showMessageDialog ( this , \"Collection is null\\n\" + f . toString ( ) ) ; return ; } Map < Grib2Variable , Grib2ParameterBean > pdsSet = new HashMap <> ( ) ; Map < Integer , Grib2SectionGridDefinition > gdsSet = new HashMap <> ( ) ; java . util . List < Grib2ParameterBean > params = new ArrayList <> ( ) ; int fileno = 0 ; for ( MFile mfile : fileList ) { f . format ( \"%n %s%n\" , mfile . getPath ( ) ) ; try ( ucar . unidata . io . RandomAccessFile raf = new ucar . unidata . io . RandomAccessFile ( mfile . getPath ( ) , \"r\" ) ) { raf . order ( ByteOrder . BIG_ENDIAN ) ; processGribFile ( mfile , fileno ++ , raf , pdsSet , gdsSet , params , f ) ; } } param2BeanTable . setBeans ( params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public boolean writeIndex ( Formatter f ) throws IOException { MCollection dcm = scanCollection ( spec f ) ; [CODESPLIT] public void showInfo ( Formatter f ) { if ( dcm == null ) { if ( spec == null ) return ; dcm = scanCollection ( spec , f ) ; if ( dcm == null ) return ; } // just a list of the files f . format ( \"dcm = %s%n\" , dcm ) ; try { for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \"  %s%n\" , mfile . getPath ( ) ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; //To change body of catch statement use File | Settings | File Templates. } // show nrecords, data size int nrecords = 0 ; long dataSize = 0 ; long msgSize = 0 ; for ( Object o : param2BeanTable . getBeans ( ) ) { Grib2ParameterBean p = ( Grib2ParameterBean ) o ; for ( Grib2RecordBean r : p . getRecordBeans ( ) ) { nrecords ++ ; dataSize += r . getDataLength ( ) ; msgSize += r . getMsgLength ( ) ; } } f . format ( \"nrecords = %d, total grib data size = %d, total grib msg sizes = %d\" , nrecords , dataSize , msgSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void checkRuntimes ( Formatter f ) { Map<Date DateCount > runs = new HashMap<Date DateCount > () ; List<Grib2ParameterBean > params = param2BeanTable . getBeans () ; for ( Grib2ParameterBean pb : params ) { List<Grib2RecordBean > records = pb . getRecordBeans () ; for ( Grib2RecordBean record : records ) { Date d = record . getBaseTime () ; DateCount dc = runs . get ( d ) ; if ( dc == null ) { dc = new DateCount ( d ) ; runs . put ( d dc ) ; } dc . count ++ ; } } [CODESPLIT] private void checkDuplicates ( Formatter f ) { // how unique are the pds ? Set < Long > pdsMap = new HashSet <> ( ) ; int dups = 0 ; int count = 0 ; // do all records have the same runtime ? Map < CalendarDate , DateCount > dateMap = new HashMap <> ( ) ; List < Grib2ParameterBean > params = param2BeanTable . getBeans ( ) ; for ( Grib2ParameterBean param : params ) { for ( Grib2RecordBean record : param . getRecordBeans ( ) ) { CalendarDate d = record . gr . getReferenceDate ( ) ; DateCount dc = dateMap . get ( d ) ; if ( dc == null ) { dc = new DateCount ( d ) ; dateMap . put ( d , dc ) ; } dc . count ++ ; Grib2SectionProductDefinition pdss = record . gr . getPDSsection ( ) ; long crc = pdss . calcCRC ( ) ; if ( pdsMap . contains ( crc ) ) dups ++ ; else pdsMap . add ( crc ) ; count ++ ; } } f . format ( \"PDS duplicates = %d / %d%n%n\" , dups , count ) ; List < DateCount > dcList = new ArrayList <> ( dateMap . values ( ) ) ; Collections . sort ( dcList ) ; f . format ( \"Run Dates%n\" ) ; int total = 0 ; for ( DateCount dc : dcList ) { f . format ( \" %s == %d%n\" , dc . d , dc . count ) ; total += dc . count ; } f . format ( \"total records = %d%n\" , total ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////// [CODESPLIT] private void writeToFile ( List beans ) { if ( fileChooser == null ) fileChooser = new FileManager ( null , null , null , ( PreferencesExt ) prefs . node ( \"FileManager\" ) ) ; FileOutputStream fos = null ; RandomAccessFile raf = null ; try { String filename = null ; boolean append = false ; int n = 0 ; MFile curr = null ; for ( Object o : beans ) { Grib2RecordBean bean = ( Grib2RecordBean ) o ; MFile mfile = fileList . get ( bean . gr . getFile ( ) ) ; if ( curr == null || curr != mfile ) { if ( raf != null ) raf . close ( ) ; raf = new RandomAccessFile ( mfile . getPath ( ) , \"r\" ) ; curr = mfile ; } if ( fos == null ) { String defloc = mfile . getPath ( ) ; filename = fileChooser . chooseFilenameToSave ( defloc + \".grib2\" ) ; if ( filename == null ) return ; File f = new File ( filename ) ; append = f . exists ( ) ; fos = new FileOutputStream ( filename , append ) ; } Grib2SectionIndicator is = bean . gr . getIs ( ) ; int size = ( int ) ( is . getMessageLength ( ) ) ; long startPos = is . getStartPos ( ) ; if ( startPos < 0 ) { JOptionPane . showMessageDialog ( Grib2DataPanel . this , \"Old index does not have message start - record not written\" ) ; } byte [ ] rb = new byte [ size ] ; raf . seek ( startPos ) ; raf . readFully ( rb ) ; fos . write ( rb ) ; n ++ ; } JOptionPane . showMessageDialog ( Grib2DataPanel . this , filename + \": \" + n + \" records successfully written, append=\" + append ) ; } catch ( Exception ex ) { JOptionPane . showMessageDialog ( Grib2DataPanel . this , \"ERROR: \" + ex . getMessage ( ) ) ; ex . printStackTrace ( ) ; } finally { try { if ( fos != null ) fos . close ( ) ; if ( raf != null ) raf . close ( ) ; } catch ( IOException ioe ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a List of all the features in the shapefile that intersect the specified bounding box . This requires testing every feature in the List created at construction so it s faster to just give a bounding box o the constructor if you will only do this once . [CODESPLIT] public List < EsriFeature > getFeatures ( Rectangle2D bBox ) { if ( bBox == null ) return features ; List < EsriFeature > list = new ArrayList <> ( ) ; for ( EsriFeature gf : features ) { if ( gf . getBounds2D ( ) . intersects ( bBox ) ) list . add ( gf ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discretize elements of array to a lower resolution . For example if resolution = 100 . the value 3 . 14159265358979 will be changed to 3 . 14 . [CODESPLIT] private void discretize ( double [ ] d , int n ) { if ( coarseness == 0.0 ) return ; for ( int i = 0 ; i < n ; i ++ ) { d [ i ] = ( Math . rint ( resolution * d [ i ] ) / resolution ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ncDataset , VariableEnhanced v ) { String name = v . getShortName ( ) ; if ( name . equals ( \"time\" ) ) { return AxisType . Time ; } if ( name . equals ( \"lat\" ) ) { return AxisType . Lat ; } if ( name . equals ( \"lon\" ) ) { return AxisType . Lon ; } // if (name.equals(\"xLeo\") ) return AxisType.GeoX;\r // if (name.equals(\"yLeo\") ) return AxisType.GeoY;\r if ( name . equals ( \"alt\" ) ) { return AxisType . Height ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a NetcdfDataset out of this NetcdfFile adding coordinates etc . [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { // latitude\r if ( ! hasAxisType ( ds , AxisType . Lat ) ) { // already has _CoordinateAxisType\r if ( ! addAxisType ( ds , \"latitude\" , AxisType . Lat ) ) { // directly named\r String vname = ds . findAttValueIgnoreCase ( null , \"latitude_coordinate\" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Lat ) ) { // attribute named\r Variable v = hasUnits ( ds , \"degrees_north,degrees_N,degreesN,degree_north,degree_N,degreeN\" ) ; if ( v != null ) addAxisType ( v , AxisType . Lat ) ; // CF-1\r } } } // longitude\r if ( ! hasAxisType ( ds , AxisType . Lon ) ) { // already has _CoordinateAxisType\r if ( ! addAxisType ( ds , \"longitude\" , AxisType . Lon ) ) { // directly named\r String vname = ds . findAttValueIgnoreCase ( null , \"longitude_coordinate\" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Lon ) ) { // attribute named\r Variable v = hasUnits ( ds , \"degrees_east,degrees_E,degreesE,degree_east,degree_E,degreeE\" ) ; if ( v != null ) addAxisType ( v , AxisType . Lon ) ; // CF-1\r } } } // altitude\r if ( ! hasAxisType ( ds , AxisType . Height ) ) { // already has _CoordinateAxisType\r if ( ! addAxisType ( ds , \"altitude\" , AxisType . Height ) ) { // directly named\r if ( ! addAxisType ( ds , \"depth\" , AxisType . Height ) ) { // directly named\r String vname = ds . findAttValueIgnoreCase ( null , \"altitude_coordinate\" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Height ) ) { // attribute named\r for ( int i = 0 ; i < ds . getVariables ( ) . size ( ) ; i ++ ) { VariableEnhanced ve = ( VariableEnhanced ) ds . getVariables ( ) . get ( i ) ; String positive = ds . findAttValueIgnoreCase ( ( Variable ) ve , CF . POSITIVE , null ) ; if ( positive != null ) { addAxisType ( ( Variable ) ve , AxisType . Height ) ; // CF-1\r break ; } } } } } } // time\r if ( ! hasAxisType ( ds , AxisType . Time ) ) { // already has _CoordinateAxisType\r if ( ! addAxisType ( ds , \"time\" , AxisType . Time ) ) { // directly named\r String vname = ds . findAttValueIgnoreCase ( null , \"time_coordinate\" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Time ) ) { // attribute named\r for ( int i = 0 ; i < ds . getVariables ( ) . size ( ) ; i ++ ) { VariableEnhanced ve = ( VariableEnhanced ) ds . getVariables ( ) . get ( i ) ; String unit = ve . getUnitsString ( ) ; if ( unit == null ) continue ; if ( SimpleUnit . isDateUnit ( unit ) ) { addAxisType ( ( Variable ) ve , AxisType . Time ) ; // CF-1\r break ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all the content from another ThreddsMetadata [CODESPLIT] public void add ( ThreddsMetadata tmd , boolean includeInherited ) { creators . addAll ( tmd . getCreators ( ) ) ; contributors . addAll ( tmd . getContributors ( ) ) ; dates . addAll ( tmd . getDates ( ) ) ; docs . addAll ( tmd . getDocumentation ( ) ) ; keywords . addAll ( tmd . getKeywords ( ) ) ; projects . addAll ( tmd . getProjects ( ) ) ; properties . addAll ( tmd . getProperties ( ) ) ; publishers . addAll ( tmd . getPublishers ( ) ) ; variables . addAll ( tmd . getVariables ( ) ) ; if ( includeInherited ) metadata . addAll ( tmd . getMetadata ( ) ) ; else { for ( InvMetadata mdata : tmd . getMetadata ( ) ) { if ( ! mdata . isInherited ( ) ) metadata . add ( mdata ) ; } } // LOOK! should be copies ??!! if ( gc == null ) gc = tmd . getGeospatialCoverage ( ) ; if ( timeCoverage == null ) timeCoverage = tmd . getTimeCoverage ( ) ; if ( serviceName == null ) serviceName = tmd . getServiceName ( ) ; if ( dataType == null ) dataType = tmd . getDataType ( ) ; if ( dataSize == 0.0 ) dataSize = tmd . getDataSize ( ) ; if ( dataFormat == null ) dataFormat = tmd . getDataFormatType ( ) ; if ( authorityName == null ) authorityName = tmd . getAuthority ( ) ; if ( variableMapLink == null ) variableMapLink = tmd . getVariableMap ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set specified type of documentation [CODESPLIT] public void addDocumentation ( String type , String content ) { if ( content == null ) { removeDocumentation ( type ) ; return ; } content = content . trim ( ) ; for ( InvDocumentation doc : getDocumentation ( ) ) { String dtype = doc . getType ( ) ; if ( ( dtype != null ) && dtype . equalsIgnoreCase ( type ) ) { doc . setInlineContent ( content ) ; return ; } } if ( content . length ( ) > 0 ) addDocumentation ( new InvDocumentation ( null , null , null , type , content ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove all instances of specified type of documentation [CODESPLIT] public void removeDocumentation ( String type ) { Iterator iter = docs . iterator ( ) ; while ( iter . hasNext ( ) ) { InvDocumentation doc = ( InvDocumentation ) iter . next ( ) ; String dtype = doc . getType ( ) ; if ( ( dtype != null ) && dtype . equalsIgnoreCase ( type ) ) iter . remove ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////// [CODESPLIT] private long getFilePos ( long elem ) { int segno = 0 ; while ( elem >= segMax [ segno ] ) segno ++ ; return segPos [ segno ] + elem - segMin [ segno ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "how many more bytes are in this segment ? [CODESPLIT] private int getMaxBytes ( long start ) { int segno = 0 ; while ( start >= segMax [ segno ] ) segno ++ ; return ( int ) ( segMax [ segno ] - start ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a time unit to a CalendarPeriod GRIB1 and GRIB2 are the same ( ! ) [CODESPLIT] public static CalendarPeriod getCalendarPeriod ( int timeUnit ) { // LOOK - some way to intern these ? put in hash table  ?\r switch ( timeUnit ) { // code table 4.4\r case 0 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Minute ) ; case 1 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Hour ) ; case 2 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Day ) ; case 3 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Month ) ; case 4 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Year ) ; case 5 : return CalendarPeriod . of ( 10 , CalendarPeriod . Field . Year ) ; case 6 : return CalendarPeriod . of ( 30 , CalendarPeriod . Field . Year ) ; case 7 : return CalendarPeriod . of ( 100 , CalendarPeriod . Field . Year ) ; case 10 : return CalendarPeriod . of ( 3 , CalendarPeriod . Field . Hour ) ; case 11 : return CalendarPeriod . of ( 6 , CalendarPeriod . Field . Hour ) ; case 12 : return CalendarPeriod . of ( 12 , CalendarPeriod . Field . Hour ) ; case 13 : return CalendarPeriod . of ( 15 , CalendarPeriod . Field . Minute ) ; case 14 : return CalendarPeriod . of ( 30 , CalendarPeriod . Field . Minute ) ; default : throw new UnsupportedOperationException ( \"Unknown time unit = \" + timeUnit ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of all variables in this vector . This method is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space ) { int len = getLength ( ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) { // to print properly, cast to long and convert to unsigned\r os . print ( ( ( long ) getValue ( i ) ) & 0xFFFF L ) ; os . print ( \", \" ) ; } // print last value, if any, without trailing comma\r if ( len > 0 ) os . print ( ( ( long ) getValue ( len - 1 ) ) & 0xFFFF L ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { int modFour = vals . length % 4 ; // number of bytes to pad\r int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; for ( int i = 0 ; i < vals . length ; i ++ ) { vals [ i ] = source . readByte ( ) ; if ( statusUI != null ) { statusUI . incrementByteCount ( 1 ) ; if ( statusUI . userCancelled ( ) ) throw new DataReadException ( \"User cancelled\" ) ; } } // pad out to a multiple of four bytes\r byte unused ; for ( int i = 0 ; i < pad ; i ++ ) unused = source . readByte ( ) ; if ( statusUI != null ) statusUI . incrementByteCount ( pad ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { int modFour = vals . length % 4 ; // number of bytes to pad\r int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; for ( int i = 0 ; i < vals . length ; i ++ ) { sink . writeByte ( vals [ i ] ) ; } // pad out to a multiple of four bytes\r for ( int i = 0 ; i < pad ; i ++ ) sink . writeByte ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a subset of the data to a <code > DataOutputStream< / code > . [CODESPLIT] public void externalize ( DataOutputStream sink , int start , int stop , int stride ) throws IOException { int count = 0 ; for ( int i = start ; i <= stop ; i += stride ) { sink . writeByte ( vals [ i ] ) ; count ++ ; } // pad out to a multiple of four bytes\r int modFour = count % 4 ; int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; for ( int i = 0 ; i < pad ; i ++ ) sink . writeByte ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the input stream to the given resource [CODESPLIT] public static InputStream getInputStream ( String resourceName ) throws FileNotFoundException { // Try class loader to get resource\r ClassLoader cl = GribResourceReader . class . getClassLoader ( ) ; InputStream s = cl . getResourceAsStream ( resourceName ) ; if ( s != null ) { return s ; } // Try the file system\r File f = new File ( resourceName ) ; if ( f . exists ( ) ) return new FileInputStream ( f ) ; // give up\r throw new FileNotFoundException ( \"Cant find resource \" + resourceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this my file? [CODESPLIT] public static boolean isMine ( NetcdfFile ncfile ) { String cs = ncfile . findAttValueIgnoreCase ( null , CDM . CONVENTIONS , null ) ; if ( cs != null ) return false ; String s = ncfile . findAttValueIgnoreCase ( null , \"DataType\" , null ) ; if ( ( s == null ) || ! ( s . equalsIgnoreCase ( \"LatLonGrid\" ) || s . equalsIgnoreCase ( \"LatLonHeightGrid\" ) ) ) return false ; if ( ( null == ncfile . findGlobalAttribute ( \"Latitude\" ) ) || ( null == ncfile . findGlobalAttribute ( \"Longitude\" ) ) || ( null == ncfile . findGlobalAttribute ( \"LatGridSpacing\" ) ) || ( null == ncfile . findGlobalAttribute ( \"LonGridSpacing\" ) ) || ( null == ncfile . findGlobalAttribute ( \"Time\" ) ) ) return false ; return ! ( null == ncfile . findDimension ( \"Lat\" ) || null == ncfile . findDimension ( \"Lon\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * static public StructureData make ( String name String value ) { StructureMembers members = new StructureMembers ( ) ; StructureMembers . Member m = members . addMember ( name null null DataType . STRING new int [] { 1 } ) ; StructureDataW sw = new StructureDataW ( members ) ; Array dataArray = Array . factory ( DataType . STRING new int [] { 1 } ) ; dataArray . setObject ( dataArray . getIndex () value ) ; sw . setMemberData ( m dataArray ) ; return sw ; } [CODESPLIT] static public StructureData make ( String name , Object value ) { StructureMembers members = new StructureMembers ( \"\" ) ; DataType dtype = DataType . getType ( value . getClass ( ) , false ) ; // LOOK unsigned StructureMembers . Member m = members . addMember ( name , null , null , dtype , new int [ ] { 1 } ) ; StructureDataW sw = new StructureDataW ( members ) ; Array dataArray = Array . factory ( dtype , new int [ ] { 1 } ) ; dataArray . setObject ( dataArray . getIndex ( ) , value ) ; sw . setMemberData ( m , dataArray ) ; return sw ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CatalogCrawler . Listener [CODESPLIT] @ Override public void getDataset ( Dataset ds , Object context ) { if ( ds . hasAccess ( ) ) { DataFactory tdataFactory = new DataFactory ( ) ; Access access = tdataFactory . chooseDatasetAccess ( ds . getAccess ( ) ) ; if ( access == null ) throw new IllegalStateException ( ) ; MFileRemote mfile = new MFileRemote ( access ) ; if ( mfile . getPath ( ) . endsWith ( \".xml\" ) ) return ; // eliminate latest.xml  LOOK kludge-o-rama mfiles . add ( mfile ) ; if ( debug ) System . out . format ( \"add %s %n\" , mfile . getPath ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a Convention . [CODESPLIT] static public void registerConvention ( String conventionName , Class c , ConventionNameOk match ) { if ( ! ( CoordSysBuilderIF . class . isAssignableFrom ( c ) ) ) throw new IllegalArgumentException ( \"CoordSysBuilderIF Class \" + c . getName ( ) + \" must implement CoordSysBuilderIF\" ) ; // fail fast - check newInstance works\r try { c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( \"CoordSysBuilderIF Class \" + c . getName ( ) + \" cannot instantiate, probably need default Constructor\" ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"CoordSysBuilderIF Class \" + c . getName ( ) + \" is not accessible\" ) ; } // user stuff gets put at top\r if ( userMode ) conventionList . add ( 0 , new Convention ( conventionName , c , match ) ) ; else conventionList . add ( new Convention ( conventionName , c , match ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a Convention . [CODESPLIT] static public void registerConvention ( String conventionName , String className ) throws ClassNotFoundException { Class c = Class . forName ( className ) ; registerConvention ( conventionName , c , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Breakup list of Convention names in the Convention attribute in CF compliant way . [CODESPLIT] static public List < String > breakupConventionNames ( String convAttValue ) { List < String > names = new ArrayList <> ( ) ; if ( ( convAttValue . indexOf ( ' ' ) > 0 ) || ( convAttValue . indexOf ( ' ' ) > 0 ) ) { StringTokenizer stoke = new StringTokenizer ( convAttValue , \",;\" ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } else if ( ( convAttValue . indexOf ( ' ' ) > 0 ) ) { StringTokenizer stoke = new StringTokenizer ( convAttValue , \"/\" ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } else { StringTokenizer stoke = new StringTokenizer ( convAttValue , \" \" ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } return names ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a list of Conventions [CODESPLIT] static public String buildConventionAttribute ( String mainConv , String ... convAtts ) { List < String > result = new ArrayList <> ( ) ; result . add ( mainConv ) ; for ( String convs : convAtts ) { if ( convs == null ) continue ; List < String > ss = breakupConventionNames ( convs ) ; // may be a list\r for ( String s : ss ) { if ( matchConvention ( s ) == null ) // only add extra ones, not ones that compete with mainConv\r result . add ( s ) ; } } // now form comma separated result\r boolean start = true ; Formatter f = new Formatter ( ) ; for ( String s : result ) { if ( start ) f . format ( \"%s\" , s ) ; else f . format ( \", %s\" , s ) ; start = false ; } return f . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a CoordSysBuilder whose job it is to add Coordinate information to a NetcdfDataset . [CODESPLIT] static public @ Nonnull CoordSysBuilderIF factory ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { // look for the Conventions attribute\r String convName = ds . findAttValueIgnoreCase ( null , CDM . CONVENTIONS , null ) ; if ( convName == null ) convName = ds . findAttValueIgnoreCase ( null , \"Convention\" , null ) ; // common mistake Convention instead of Conventions\r if ( convName != null ) convName = convName . trim ( ) ; // look for ncml first\r if ( convName != null ) { String convNcML = ncmlHash . get ( convName ) ; if ( convNcML != null ) { CoordSysBuilder csb = new CoordSysBuilder ( ) ; NcMLReader . wrapNcML ( ds , convNcML , cancelTask ) ; return csb ; } } // look for registered conventions using convention name\r Class convClass = null ; if ( convName != null ) { convClass = matchConvention ( convName ) ; // now look for comma or semicolon or / delimited list\r if ( convClass == null ) { List < String > names = breakupConventionNames ( convName ) ; if ( names . size ( ) > 0 ) { // search the registered conventions, in order\r for ( Convention conv : conventionList ) { for ( String name : names ) { if ( name . equalsIgnoreCase ( conv . convName ) ) { convClass = conv . convClass ; convName = name ; } } if ( convClass != null ) break ; } } } } // look for ones that dont use Convention attribute, in order added.\r // call static isMine() using reflection.\r if ( convClass == null ) { for ( Convention conv : conventionList ) { Class c = conv . convClass ; Method m ; try { m = c . getMethod ( \"isMine\" , NetcdfFile . class ) ; // LOOK cant we test if method exists ?\r } catch ( NoSuchMethodException ex ) { continue ; } try { Boolean result = ( Boolean ) m . invoke ( null , ds ) ; if ( result ) { convClass = c ; break ; } } catch ( Exception ex ) { log . error ( \"ERROR: Class \" + c . getName ( ) + \" Exception invoking isMine method\\n\" + ex ) ; } } } // use service loader mechanism\r // call static isMine() using reflection.\r CoordSysBuilderIF builder = null ; if ( convClass == null ) { for ( CoordSysBuilderIF csb : ServiceLoader . load ( CoordSysBuilderIF . class ) ) { Class c = csb . getClass ( ) ; Method m ; try { m = c . getMethod ( \"isMine\" , NetcdfFile . class ) ; } catch ( NoSuchMethodException ex ) { continue ; } try { Boolean result = ( Boolean ) m . invoke ( null , ds ) ; if ( result ) { builder = csb ; convClass = c ; break ; } } catch ( Exception ex ) { log . error ( \"ERROR: Class \" + c . getName ( ) + \" Exception invoking isMine method%n\" + ex ) ; } } } // if no convention class found, use the default\r if ( convClass == null ) convClass = DefaultConvention . class ; if ( builder == null ) { // get an instance of the class\r try { builder = ( CoordSysBuilderIF ) convClass . newInstance ( ) ; } catch ( Exception e ) { log . error ( \"failed on CoordSysBuilderIF for \" + convClass . getName ( ) , e ) ; throw new RuntimeException ( e ) ; } } if ( convName == null ) builder . addUserAdvice ( \"No 'Conventions' global attribute.\" ) ; else if ( convClass == DefaultConvention . class ) builder . addUserAdvice ( \"No CoordSysBuilder is defined for Conventions= '\" + convName + \"'\\n\" ) ; else builder . setConventionUsed ( convClass . getName ( ) ) ; ds . addAttribute ( null , new Attribute ( _Coordinate . _CoordSysBuilder , convClass . getName ( ) ) ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Heres where the work is to identify coordinate axes and coordinate systems . [CODESPLIT] @ Override public void buildCoordinateSystems ( NetcdfDataset ncDataset ) { // put status info into parseInfo that can be shown to someone trying to debug this process\r parseInfo . format ( \"Parsing with Convention = %s%n\" , conventionName ) ; // Bookkeeping info for each variable is kept in the VarProcess inner class\r addVariables ( ncDataset , ncDataset . getVariables ( ) , varList ) ; // identify which variables are coordinate axes\r findCoordinateAxes ( ncDataset ) ; // identify which variables are used to describe coordinate system\r findCoordinateSystems ( ncDataset ) ; // identify which variables are used to describe coordinate transforms\r findCoordinateTransforms ( ncDataset ) ; // turn Variables into CoordinateAxis objects\r makeCoordinateAxes ( ncDataset ) ; // make Coordinate Systems for all Coordinate Systems Variables\r makeCoordinateSystems ( ncDataset ) ; // assign explicit CoordinateSystem objects to variables\r assignCoordinateSystemsExplicit ( ncDataset ) ; // assign implicit CoordinateSystem objects to variables\r makeCoordinateSystemsImplicit ( ncDataset ) ; // optionally assign implicit CoordinateSystem objects to variables that dont have one yet\r if ( useMaximalCoordSys ) makeCoordinateSystemsMaximal ( ncDataset ) ; // make Coordinate Transforms\r makeCoordinateTransforms ( ncDataset ) ; // assign Coordinate Transforms\r assignCoordinateTransforms ( ncDataset ) ; if ( debug ) System . out . println ( \"parseInfo = \\n\" + parseInfo . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify coordinate axes set VarProcess . isCoordinateAxis = true . Default is to look for those referenced by _CoordinateAxes attribute . Note coordinate variables are already identified . [CODESPLIT] protected void findCoordinateAxes ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . coordAxes != null ) findCoordinateAxes ( vp , vp . coordAxes ) ; if ( vp . coordinates != null ) findCoordinateAxes ( vp , vp . coordinates ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify coordinate systems set VarProcess . isCoordinateSystem = true . Default is to look for those referenced by _CoordinateSystems attribute . [CODESPLIT] protected void findCoordinateSystems ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . coordSys != null ) { StringTokenizer stoker = new StringTokenizer ( vp . coordSys ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap != null ) { if ( ! ap . isCoordinateSystem ) parseInfo . format ( \" CoordinateSystem = %s added; referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; ap . isCoordinateSystem = true ; } else { parseInfo . format ( \"***Cant find coordSystem %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( \"***Cant find coordSystem %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify coordinate transforms set VarProcess . isCoordinateTransform = true . Default is to look for those referenced by _CoordinateTransforms attribute ( or has a _CoordinateTransformType attribute done in VarProcess constructor ) [CODESPLIT] protected void findCoordinateTransforms ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . coordTransforms != null ) { StringTokenizer stoker = new StringTokenizer ( vp . coordTransforms ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap != null ) { if ( ! ap . isCoordinateTransform ) parseInfo . format ( \" CoordinateTransform = %s added; referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; ap . isCoordinateTransform = true ; } else { parseInfo . format ( \"***Cant find CoordinateTransform %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( \"***Cant find CoordinateTransform %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take previously identified Coordinate Axis and Coordinate Variables and make them into a CoordinateAxis . Uses the getAxisType () method to figure out the type if not already set . [CODESPLIT] protected void makeCoordinateAxes ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . isCoordinateAxis || vp . isCoordinateVariable ) { if ( vp . axisType == null ) vp . axisType = getAxisType ( ncDataset , ( VariableEnhanced ) vp . v ) ; if ( vp . axisType == null ) { userAdvice . format ( \"Coordinate Axis %s does not have an assigned AxisType%n\" , vp . v . getFullName ( ) ) ; } vp . makeIntoCoordinateAxis ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take all previously identified Coordinate Systems and create a CoordinateSystem object . [CODESPLIT] protected void makeCoordinateSystems ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . isCoordinateSystem ) { vp . makeCoordinateSystem ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign explicit CoordinateSystem objects to variables . [CODESPLIT] protected void assignCoordinateSystemsExplicit ( NetcdfDataset ncDataset ) { // look for explicit references to coord sys variables\r for ( VarProcess vp : varList ) { if ( vp . coordSys != null && ! vp . isCoordinateTransform ) { StringTokenizer stoker = new StringTokenizer ( vp . coordSys ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap == null ) { parseInfo . format ( \"***Cant find Coordinate System variable %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( \"***Cant find Coordinate System variable %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; continue ; } if ( ap . cs == null ) { parseInfo . format ( \"***Not a Coordinate System variable %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( \"***Not a Coordinate System variable %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; continue ; } VariableEnhanced ve = ( VariableEnhanced ) vp . v ; ve . addCoordinateSystem ( ap . cs ) ; } } } // look for explicit references from coord sys variables to data variables\r for ( VarProcess csVar : varList ) { if ( ! csVar . isCoordinateSystem || ( csVar . coordSysFor == null ) ) continue ; // get list of dimensions from '_CoordinateSystemFor' attribute\r List < Dimension > dimList = new ArrayList <> ( 6 ) ; StringTokenizer stoker = new StringTokenizer ( csVar . coordSysFor ) ; while ( stoker . hasMoreTokens ( ) ) { String dname = stoker . nextToken ( ) ; Dimension dim = ncDataset . getRootGroup ( ) . findDimension ( dname ) ; if ( dim == null ) { parseInfo . format ( \"***Cant find Dimension %s referenced from CoordSys var= %s%n\" , dname , csVar . v . getFullName ( ) ) ; userAdvice . format ( \"***Cant find Dimension %s referenced from CoordSys var= %s%n\" , dname , csVar . v . getFullName ( ) ) ; } else dimList . add ( dim ) ; } // look for vars with those dimensions\r for ( VarProcess vp : varList ) { if ( ! vp . hasCoordinateSystem ( ) && vp . isData ( ) && ( csVar . cs != null ) ) { VariableEnhanced ve = ( VariableEnhanced ) vp . v ; if ( CoordinateSystem . isSubset ( dimList , vp . v . getDimensionsAll ( ) ) && CoordinateSystem . isSubset ( vp . v . getDimensionsAll ( ) , dimList ) ) ve . addCoordinateSystem ( csVar . cs ) ; } } } // look for explicit listings of coordinate axes\r for ( VarProcess vp : varList ) { VariableEnhanced ve = ( VariableEnhanced ) vp . v ; if ( ! vp . hasCoordinateSystem ( ) && ( vp . coordAxes != null ) && vp . isData ( ) ) { List < CoordinateAxis > dataAxesList = getAxes ( vp , vp . coordAxes , vp . v . getFullName ( ) ) ; if ( dataAxesList . size ( ) > 1 ) { String coordSysName = CoordinateSystem . makeName ( dataAxesList ) ; CoordinateSystem cs = ncDataset . findCoordinateSystem ( coordSysName ) ; if ( cs != null ) { ve . addCoordinateSystem ( cs ) ; parseInfo . format ( \" assigned explicit CoordSystem '%s' for var= %s%n\" , cs . getName ( ) , vp . v . getFullName ( ) ) ; } else { CoordinateSystem csnew = new CoordinateSystem ( ncDataset , dataAxesList , null ) ; ve . addCoordinateSystem ( csnew ) ; ncDataset . addCoordinateSystem ( csnew ) ; parseInfo . format ( \" created explicit CoordSystem '%s' for var= %s%n\" , csnew . getName ( ) , vp . v . getFullName ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make implicit CoordinateSystem objects for variables that dont already have one by using the variables list of coordinate axes and any coordinateVariables for it . Must be at least 2 axes . All of a variable s _Coordinate Variables_ plus any variables listed in a * __CoordinateAxes_ * or * _coordinates_ * attribute will be made into an * _implicit_ * Coordinate System . If there are at least two axes and the coordinate system uses all of the variable s dimensions it will be asssigned to the data variable . [CODESPLIT] protected void makeCoordinateSystemsImplicit ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( ! vp . hasCoordinateSystem ( ) && vp . maybeData ( ) ) { List < CoordinateAxis > dataAxesList = vp . findCoordinateAxes ( true ) ; if ( dataAxesList . size ( ) < 2 ) continue ; VariableEnhanced ve = ( VariableEnhanced ) vp . v ; String csName = CoordinateSystem . makeName ( dataAxesList ) ; CoordinateSystem cs = ncDataset . findCoordinateSystem ( csName ) ; if ( ( cs != null ) && cs . isComplete ( vp . v ) ) { // must be complete\r ve . addCoordinateSystem ( cs ) ; parseInfo . format ( \" assigned implicit CoordSystem '%s' for var= %s%n\" , cs . getName ( ) , vp . v . getFullName ( ) ) ; } else { CoordinateSystem csnew = new CoordinateSystem ( ncDataset , dataAxesList , null ) ; csnew . setImplicit ( true ) ; if ( csnew . isComplete ( vp . v ) ) { ve . addCoordinateSystem ( csnew ) ; ncDataset . addCoordinateSystem ( csnew ) ; parseInfo . format ( \" created implicit CoordSystem '%s' for var= %s%n\" , csnew . getName ( ) , vp . v . getFullName ( ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a variable still doesnt have a coordinate system use hueristics to try to find one that was probably forgotten . Examine existing CS . create a subset of axes that fits the variable . Choose the one with highest rank . It must have X Y or lat lon . If so add it . [CODESPLIT] protected void makeCoordinateSystemsMaximal ( NetcdfDataset ncDataset ) { boolean requireCompleteCoordSys = ! ncDataset . getEnhanceMode ( ) . contains ( NetcdfDataset . Enhance . IncompleteCoordSystems ) ; for ( VarProcess vp : varList ) { VariableEnhanced ve = ( VariableEnhanced ) vp . v ; if ( vp . hasCoordinateSystem ( ) || ! vp . isData ( ) ) continue ; // look through all axes that fit\r List < CoordinateAxis > axisList = new ArrayList <> ( ) ; List < CoordinateAxis > axes = ncDataset . getCoordinateAxes ( ) ; for ( CoordinateAxis axis : axes ) { if ( isCoordinateAxisForVariable ( axis , ve ) ) axisList . add ( axis ) ; } if ( axisList . size ( ) < 2 ) continue ; String csName = CoordinateSystem . makeName ( axisList ) ; CoordinateSystem cs = ncDataset . findCoordinateSystem ( csName ) ; boolean okToBuild = false ; // do coordinate systems need to be complete?\r // default enhance mode is yes, they must be complete\r if ( requireCompleteCoordSys ) { if ( cs != null ) { // only build if coordinate system is complete\r okToBuild = cs . isComplete ( ve ) ; } } else { // coordinate system can be incomplete, so we're ok to build if we find something\r okToBuild = true ; } if ( cs != null && okToBuild ) { ve . addCoordinateSystem ( cs ) ; parseInfo . format ( \" assigned maximal CoordSystem '%s' for var= %s%n\" , cs . getName ( ) , ve . getFullName ( ) ) ; } else { CoordinateSystem csnew = new CoordinateSystem ( ncDataset , axisList , null ) ; // again, do coordinate systems need to be complete?\r // default enhance mode is yes, they must be complete\r if ( requireCompleteCoordSys ) { // only build if new coordinate system is complete\r okToBuild = csnew . isComplete ( ve ) ; } if ( okToBuild ) { csnew . setImplicit ( true ) ; ve . addCoordinateSystem ( csnew ) ; ncDataset . addCoordinateSystem ( csnew ) ; parseInfo . format ( \" created maximal CoordSystem '%s' for var= %s%n\" , csnew . getName ( ) , ve . getFullName ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this axis fit this variable . True if all of the dimensions in the axis also appear in the variable . If char variable last dimension is left out . [CODESPLIT] protected boolean isCoordinateAxisForVariable ( Variable axis , VariableEnhanced v ) { List < Dimension > varDims = v . getDimensionsAll ( ) ; List < Dimension > axisDims = axis . getDimensionsAll ( ) ; // a CHAR variable must really be a STRING, so leave out the last (string length) dimension\r int checkDims = axisDims . size ( ) ; if ( axis . getDataType ( ) == DataType . CHAR ) checkDims -- ; for ( int i = 0 ; i < checkDims ; i ++ ) { Dimension axisDim = axisDims . get ( i ) ; if ( ! varDims . contains ( axisDim ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take all previously identified Coordinate Transforms and create a CoordinateTransform object by calling CoordTransBuilder . makeCoordinateTransform () . [CODESPLIT] protected void makeCoordinateTransforms ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && vp . ct == null ) { vp . ct = CoordTransBuilder . makeCoordinateTransform ( vp . ds , vp . v , parseInfo , userAdvice ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign CoordinateTransform objects to Coordinate Systems . [CODESPLIT] protected void assignCoordinateTransforms ( NetcdfDataset ncDataset ) { // look for explicit transform assignments on the coordinate systems\r for ( VarProcess vp : varList ) { if ( vp . isCoordinateSystem && vp . coordTransforms != null ) { StringTokenizer stoker = new StringTokenizer ( vp . coordTransforms ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap != null ) { if ( ap . ct != null ) { vp . addCoordinateTransform ( ap . ct ) ; parseInfo . format ( \" assign explicit coordTransform %s to CoordSys= %s%n\" , ap . ct , vp . cs ) ; } else { parseInfo . format ( \"***Cant find coordTransform in %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( \"***Cant find coordTransform in %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; } } else { parseInfo . format ( \"***Cant find coordTransform variable= %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( \"***Cant find coordTransform variable= %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; } } } } // look for explicit coordSys assignments on the coordinate transforms\r for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && ( vp . ct != null ) && ( vp . coordSys != null ) ) { StringTokenizer stoker = new StringTokenizer ( vp . coordSys ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess vcs = findVarProcess ( vname , vp ) ; if ( vcs == null ) { parseInfo . format ( \"***Cant find coordSystem variable= %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( \"***Cant find coordSystem variable= %s referenced from var= %s%n\" , vname , vp . v . getFullName ( ) ) ; } else { vcs . addCoordinateTransform ( vp . ct ) ; parseInfo . format ( \"***assign explicit coordTransform %s to CoordSys=  %s%n\" , vp . ct , vp . cs ) ; } } } } // look for coordAxes assignments on the coordinate transforms\r for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && ( vp . ct != null ) && ( vp . coordAxes != null ) ) { List < CoordinateAxis > dataAxesList = vp . findCoordinateAxes ( false ) ; if ( dataAxesList . size ( ) > 0 ) { for ( CoordinateSystem cs : ncDataset . getCoordinateSystems ( ) ) { if ( cs . containsAxes ( dataAxesList ) ) { cs . addCoordinateTransform ( vp . ct ) ; parseInfo . format ( \"***assign (implicit coordAxes) coordTransform %s to CoordSys=  %s%n\" , vp . ct , cs ) ; } } } } } // look for coordAxisType assignments on the coordinate transforms\r for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && ( vp . ct != null ) && ( vp . coordAxisTypes != null ) ) { List < AxisType > axisTypesList = new ArrayList <> ( ) ; StringTokenizer stoker = new StringTokenizer ( vp . coordAxisTypes ) ; while ( stoker . hasMoreTokens ( ) ) { String name = stoker . nextToken ( ) ; AxisType atype ; if ( null != ( atype = AxisType . getType ( name ) ) ) axisTypesList . add ( atype ) ; } if ( axisTypesList . size ( ) > 0 ) { for ( CoordinateSystem cs : ncDataset . getCoordinateSystems ( ) ) { if ( cs . containsAxisTypes ( axisTypesList ) ) { cs . addCoordinateTransform ( vp . ct ) ; parseInfo . format ( \"***assign (implicit coordAxisType) coordTransform %s to CoordSys=  %s%n\" , vp . ct , cs ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "track coordinate variables [CODESPLIT] protected void addCoordinateVariable ( Dimension dim , VarProcess vp ) { List < VarProcess > list = coordVarMap . get ( dim ) ; if ( list == null ) { list = new ArrayList <> ( ) ; coordVarMap . put ( dim , list ) ; } if ( ! list . contains ( vp ) ) list . add ( vp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Munge this catalog so the given dataset is the top catalog . [CODESPLIT] public void subset ( InvDataset ds ) { InvDatasetImpl dataset = ( InvDatasetImpl ) ds ; // Make all inherited metadata local. dataset . transferMetadata ( dataset , true ) ; topDataset = dataset ; datasets . clear ( ) ; // throw away the rest datasets . add ( topDataset ) ; // parent lookups need to be local //InvService service = dataset.getServiceDefault(); //if (service != null) LOOK //  dataset.serviceName = service.getName(); dataset . dataType = dataset . getDataType ( ) ; // all properties need to be local // LOOK dataset.setPropertiesLocal( new ArrayList(dataset.getProperties())); // next part requires this before it dataset . setCatalog ( this ) ; dataset . parent = null ; // any referenced services need to be local List < InvService > services = new ArrayList < InvService > ( dataset . getServicesLocal ( ) ) ; findServices ( services , dataset ) ; dataset . setServicesLocal ( services ) ; finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] void findServices ( List < InvService > result , InvDataset ds ) { if ( ds instanceof InvCatalogRef ) return ; // look for access elements with unresolved services for ( InvAccess a : ds . getAccess ( ) ) { InvService s = a . getService ( ) ; InvDataset d = a . getDataset ( ) ; if ( null == d . findService ( s . getName ( ) ) && ! ( result . contains ( s ) ) ) result . add ( s ) ; } // recurse into nested datasets for ( InvDataset nested : ds . getDatasets ( ) ) { findServices ( result , nested ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Munge this catalog to remove any dataset that doesnt pass through the filter . [CODESPLIT] public void filter ( DatasetFilter filter ) { mark ( filter , topDataset ) ; delete ( topDataset ) ; this . filter = filter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unread CatalogRefs are always kept . [CODESPLIT] private boolean mark ( DatasetFilter filter , InvDatasetImpl ds ) { if ( ds instanceof InvCatalogRef ) { InvCatalogRef catRef = ( InvCatalogRef ) ds ; if ( ! catRef . isRead ( ) ) return false ; } // recurse into nested datasets first boolean allMarked = true ; for ( InvDataset nested : ds . getDatasets ( ) ) { allMarked &= mark ( filter , ( InvDatasetImpl ) nested ) ; } if ( ! allMarked ) return false ; if ( filter . accept ( ds ) >= 0 ) return false ; // mark for deletion ds . setMark ( true ) ; if ( debugFilter ) System . out . println ( \" mark \" + ds . getName ( ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove marked datasets [CODESPLIT] private void delete ( InvDatasetImpl ds ) { if ( ds instanceof InvCatalogRef ) { InvCatalogRef catRef = ( InvCatalogRef ) ds ; if ( ! catRef . isRead ( ) ) return ; } Iterator iter = ds . getDatasets ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { InvDatasetImpl nested = ( InvDatasetImpl ) iter . next ( ) ; if ( nested . getMark ( ) ) { iter . remove ( ) ; if ( debugFilter ) System . out . println ( \" remove \" + nested . getName ( ) ) ; } else delete ( nested ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finish constructing after all elements have been added or modified . This routine will do any needed internal consistency work . Its ok to call multiple times . [CODESPLIT] public boolean finish ( ) { // make topDataset if needed //if (topDataset == null) { if ( datasets . size ( ) == 1 ) { // already only one; make it top topDataset = ( InvDatasetImpl ) datasets . get ( 0 ) ; } else { // create one topDataset = new InvDatasetImpl ( null , name == null ? \"Top Dataset\" : name ) ; for ( InvDataset dataset : datasets ) topDataset . addDataset ( ( InvDatasetImpl ) dataset ) ; topDataset . setServicesLocal ( services ) ; } //} topDataset . setCatalog ( this ) ; // build dataset hash table dsHash = new HashMap < String , InvDataset > ( ) ; addDatasetIds ( topDataset ) ; // recurse through the datasets and finish them return topDataset . finish ( ) ; } private void addDatasetIds ( InvDatasetImpl ds ) { addDatasetByID ( ds ) ; if ( ds instanceof InvCatalogRef ) return ; //if (ds instanceof InvDatasetFmrc) return; // recurse into nested for ( InvDataset invDataset : ds . getDatasets ( ) ) { InvDatasetImpl nested = ( InvDatasetImpl ) invDataset ; addDatasetIds ( nested ) ; } } /**\n   * Add Dataset to internal hash.\n   *\n   * @param ds : add this dataset if ds.getID() != null\n   * @see InvCatalog#findDatasetByID\n   */ public void addDatasetByID  ( InvDatasetImpl ds ) { //if (ds.getID() != null && ds.getID().startsWith(\"null\")) //  System.out.printf(\"HEY addDatasetByID %s%n\", ds.getID()); if ( ds . getID ( ) != null ) dsHash . put ( ds . getID ( ) , ds ) ; } /**\n   * Find the dataset in this catalog by its ID. If found, remove it.\n   *\n   * @param ds Remove this dataset from the hash\n   */ public void removeDatasetByID  ( InvDatasetImpl ds ) { if ( ds . getID ( ) != null ) dsHash . remove ( ds . getID ( ) ) ; } /**\n   * Add Dataset (1.0)\n   *\n   * @param ds add this dataset\n   */ public void addDataset  ( InvDatasetImpl ds ) { if ( ds != null ) datasets . add ( ds ) ; } /**\n   * Remove the given dataset from this catalog if it is a direct child of this catalog.\n   *\n   * @param ds remove this dataset\n   * @return true if found and removed\n   */ public boolean removeDataset  ( InvDatasetImpl ds ) { if ( this . datasets . remove ( ds ) ) { ds . setParent ( null ) ; removeDatasetByID ( ds ) ; return true ; } return false ; } /**\n   * Replace the given dataset if it is a nested dataset.\n   *\n   * @param remove - the dataset element to be removed\n   * @param add    - the dataset element to be added\n   * @return true on success\n   */ public boolean replaceDataset  ( InvDatasetImpl remove , InvDatasetImpl add ) { if ( topDataset . equals ( remove ) ) { topDataset = add ; topDataset . setCatalog ( this ) ; } for ( int i = 0 ; i < datasets . size ( ) ; i ++ ) { InvDataset dataset = datasets . get ( i ) ; if ( dataset . equals ( remove ) ) { datasets . set ( i , add ) ; removeDatasetByID ( remove ) ; addDatasetByID ( add ) ; return true ; } } return false ; } /**\n   * Add Property (1.0)\n   *\n   * @param p add this property\n   */ public void addProperty  ( InvProperty p ) { properties . add ( p ) ; } /**\n   * Add Service (1.0)\n   *\n   * @param s add this service\n   */ public void addService  ( InvService s ) { if ( s == null ) throw new IllegalArgumentException ( \"Service to add was null.\" ) ; // While adding a service, there are three possible results: if ( s . getName ( ) != null ) { Object obj = serviceHash . get ( s . getName ( ) ) ; if ( obj == null ) { // 1) No service with matching name entry was found, add given service; serviceHash . put ( s . getName ( ) , s ) ; services . add ( s ) ; return ; } else { // A service with matching name was found. if ( s . equals ( obj ) ) { // 2) matching name entry, objects are equal so OK; return ; } else { // 3) matching name entry, objects are not equal so ??? // @todo throw an exception??? // Currently just dropping given service log . append ( \"Multiple Services with the same name\\n\" ) ; return ; } } } } /**\n   * Add top-level InvDataset to this catalog.\n   *\n   * @deprecated Use addDataset() instead; datamodel now allows multiple top level datasets.\n   */ public void setDataset  ( InvDatasetImpl ds ) { topDataset = ds ; addDataset ( ds ) ; } /**\n   * String describing how the catalog was created, for debugging.\n   *\n   * @return how the catalog was created, for debugging\n   */ public String getCreateFrom  ( ) { return createFrom ; } /**\n   * Set how the catalog was created, for debugging.\n   * @param createFrom how the catalog was created, for debugging\n   */ public void setCreateFrom  ( String createFrom ) { this . createFrom = createFrom ; } /**\n   * Set the catalog base URI.\n   * Its used to resolve reletive URLS.\n   * @param baseURI set to this\n   */ public void setBaseURI  ( URI baseURI ) { this . baseURI = baseURI ; } /**\n   * @return the catalog base URI.\n   */ public URI getBaseURI  ( ) { return baseURI ; } /*\n   * @return DTD string\n   *\n  public String getDTDid() {\n    return dtdID;\n  }\n\n  /*\n   * set DTD\n   *\n  public void setDTDid(String dtdID) {\n    this.dtdID = dtdID;\n  } */ /**\n   * Set the expires date after which the catalog is no longer valid.\n   *\n   * @param expiresDate a {@link DateType} representing the date after which the catlog is no longer valid.\n   */ public void setExpires  ( DateType expiresDate ) { this . expires = expiresDate ; } /**\n   * Check if there is a fatal error and catalog should not be used.\n   *\n   * @return true if catalog not useable.\n   */ public boolean hasFatalError  ( ) { return hasError ; } /**\n   * Append an error message to the message log. Call check() to get the log when\n   * everything is done.\n   *\n   * @param message   append this message to log\n   * @param isInvalid true if this is a fatal error.\n   */ public void appendErrorMessage  ( String message , boolean isInvalid ) { log . append ( message ) ; hasError = hasError | isInvalid ; } /**\n   * Check internal data structures.\n   *\n   * @param out  : print errors here\n   * @param show : print messages for each object (debug)\n   * @return true if no fatal consistency errors.\n   */ public boolean check  ( StringBuilder out , boolean show ) { boolean isValid = ! hasError ; out . append ( \"----Catalog Validation\\n\" ) ; if ( log . length ( ) > 0 ) out . append ( log ) ; if ( show ) System . out . println ( \" catalog valid = \" + isValid ) ; //if (topDataset != null) //  isValid &= topDataset.check( out, show); for ( InvDataset ds : datasets ) { InvDatasetImpl dsi = ( InvDatasetImpl ) ds ; dsi . check ( out , show ) ; // cant make it invalid !! } return isValid ; } public String getLog  ( ) { return log . toString ( ) ; } /**\n   * Debugging: dump entire data structure.\n   *\n   * @return String representation.\n   */ public String dump  ( ) { StringBuilder buff = new StringBuilder ( 1000 ) ; buff . setLength ( 0 ) ; buff . append ( \"Catalog <\" ) . append ( getName ( ) ) . append ( \"> <\" ) . append ( getVersion ( ) ) . append ( \"> <\" ) . append ( getCreateFrom ( ) ) . append ( \">\\n\" ) ; buff . append ( topDataset . dump ( 2 ) ) ; return buff . toString ( ) ; } /*\n   * Add a PropertyChangeEvent Listener. THIS IS EXPERIMENTAL DO NOT RELY ON.\n   * Throws a PropertyChangeEvent:\n   * <ul><li>propertyName = \"InvCatalogRefInit\", getNewValue() = InvCatalogRef that was just initialized\n   * </ul>\n   * @param l the listener\n   *\n  public void addPropertyChangeListener(PropertyChangeListener l) {\n    if (listenerList == null) listenerList = new EventListenerList();\n    listenerList.add(PropertyChangeListener.class, l);\n  }\n\n  /**\n   * Remove a PropertyChangeEvent Listener.\n   * @param l the listener\n   *\n  public void removePropertyChangeListener(PropertyChangeListener l) {\n    listenerList.remove(PropertyChangeListener.class, l);\n  }\n\n  private EventListenerList listenerList = null;\n\n  // PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue)\n  void firePropertyChangeEvent(PropertyChangeEvent event) {\n    // System.out.println(\"firePropertyChangeEvent \"+event);\n    if (listenerList == null) return;\n\n    // Process the listeners last to first\n    Object[] listeners = listenerList.getListenerList();\n    for (int i = listeners.length - 2; i >= 0; i -= 2) {\n      if (listeners[i] == PropertyChangeListener.class) {\n        ((PropertyChangeListener) listeners[i + 1]).propertyChange(event);\n      }\n    }\n  } */ /**\n   * This finds the topmost catalog, even when its a InvCatalogRef.\n   * Used to throw a PropertyChange event on the top catalog.\n   *\n   * @return top catalog\n   */ InvCatalogImpl getTopCatalog  ( ) { return ( top == null ) ? this : top ; } void setTopCatalog  ( InvCatalogImpl top ) { this . top = top ; } private InvCatalogImpl top = null ; //////////////////////////////////////////// /* private InvCatalogFactory factory = null;\n  // private InvCatalogConvertIF converter = null;\n\n  // this is how catalogRefs read their catalogs\n  InvCatalogFactory getCatalogFactory() {\n    return factory;\n  }\n\n  void setCatalogFactory(InvCatalogFactory factory) {\n    this.factory = factory;\n  }\n\n  // track converter\n  InvCatalogConvertIF getCatalogConverter() {\n    return converter;\n  }\n\n  void setCatalogConverter(InvCatalogConvertIF converter) {\n    this.converter = converter;\n  } */ /*\n   * Set the connverter to 1.0, typically to write a 0.6 out to a 1.0\n   *\n  public void setCatalogConverterToVersion1() {\n    setCatalogConverter(factory.getCatalogConverter(XMLEntityResolver.CATALOG_NAMESPACE_10));\n  } */ /**\n   * Write the catalog as an XML document to the specified stream.\n   *\n   * @param os write to this OutputStream\n   * @throws java.io.IOException on an error.\n   */ public void writeXML  ( java . io . OutputStream os ) throws java . io . IOException { InvCatalogConvertIF converter = InvCatalogFactory . getDefaultConverter ( ) ; converter . writeXML ( this , os ) ; } /**\n   * Write the catalog as an XML document to the specified stream.\n   *\n   * @param os  write to this OutputStream\n   * @param raw if true, write original (server) version, else write client version\n   * @throws java.io.IOException on an error.\n   */ public void writeXML  ( java . io . OutputStream os , boolean raw ) throws java . io . IOException { InvCatalogConvertIF converter = InvCatalogFactory . getDefaultConverter ( ) ; converter . writeXML ( this , os , raw ) ; } ////////////////////////////////////////////////////////////////////////// /**\n   * Get dataset roots.\n   *\n   * @return List of InvProperty. May be empty, may not be null.\n   */ public java . util . List < DataRootConfig > getDatasetRoots  ( ) { return roots ; } /**\n   * Add Dataset Root, key = path,  value = location.\n   * @param root add a dataset root\n   */ public void addDatasetRoot  ( DataRootConfig root ) { roots . add ( root ) ; } /**\n   * InvCatalogImpl elements with same values are equal.\n   */ public boolean equals  ( Object o ) { if ( this == o ) return true ; if ( ! ( o instanceof InvCatalogImpl ) ) return false ; return o . hashCode ( ) == this . hashCode ( ) ; } /**\n   * Override Object.hashCode() to implement equals.\n   */ public int hashCode  ( ) { if ( hashCode == 0 ) { int result = 17 ; if ( null != getName ( ) ) result = 37 * result + getName ( ) . hashCode ( ) ; result = 37 * result + getServices ( ) . hashCode ( ) ; result = 37 * result + getDatasets ( ) . hashCode ( ) ; hashCode = result ; } return hashCode ; } private volatile int hashCode = 0 ; // Bloch, item 8 public boolean isStatic  ( ) { return isStatic ; } public void setStatic  ( boolean aStatic ) { isStatic = aStatic ; } } ", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts a string [ units ] since [ isoDate ] ( e . g . minutes since 1985 - 01 - 01 ) into a baseSeconds ( seconds since 1970 - 01 - 01 ) and a factor ( minutes returns 60 ) . <br > So simplistically epochSeconds = storedTime * factor + baseSeconds . <br > Or simplistically storedTime = ( epochSeconds - baseSeconds ) / factor . [CODESPLIT] public static double [ ] getTimeBaseAndFactor ( String tsUnits ) throws Exception { String errorInMethod = ErddapString2 . ERROR + \" in Calendar2.getTimeBaseAndFactor(\" + tsUnits + \"):\\n\" ; if ( tsUnits == null ) { throw new NullPointerException ( errorInMethod + \"tsUnits must be non-null.\" ) ; } int sincePo = tsUnits . toLowerCase ( ) . indexOf ( \" since \" ) ; if ( sincePo <= 0 ) throw new IllegalArgumentException ( errorInMethod + \"units string doesn't contain \\\" since \\\".\" ) ; double factorToGetSeconds = factorToGetSeconds ( tsUnits . substring ( 0 , sincePo ) ) ; GregorianCalendar baseGC = parseISODateTimeZulu ( tsUnits . substring ( sincePo + 7 ) ) ; double baseSeconds = baseGC . getTimeInMillis ( ) / 1000.0 ; return new double [ ] { baseSeconds , factorToGetSeconds } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This returns the factor to multiply by units data to get seconds data ( e . g . minutes returns 60 ) . This is used for part of dealing with udunits - style minutes since 1970 - 01 - 01 - style strings . [CODESPLIT] public static double factorToGetSeconds ( String units ) throws Exception { units = units . trim ( ) . toLowerCase ( ) ; if ( units . equals ( \"ms\" ) || units . equals ( \"msec\" ) || units . equals ( \"msecs\" ) || units . equals ( \"millis\" ) || units . equals ( \"millisec\" ) || units . equals ( \"millisecs\" ) || units . equals ( \"millisecond\" ) || units . equals ( \"milliseconds\" ) ) return 0.001 ; if ( units . equals ( \"s\" ) || units . equals ( \"sec\" ) || units . equals ( \"secs\" ) || units . equals ( \"second\" ) || units . equals ( \"seconds\" ) ) return 1 ; if ( units . equals ( \"m\" ) || units . equals ( \"min\" ) || units . equals ( \"mins\" ) || units . equals ( \"minute\" ) || units . equals ( \"minutes\" ) ) return SECONDS_PER_MINUTE ; if ( units . equals ( \"h\" ) || units . equals ( \"hr\" ) || units . equals ( \"hrs\" ) || units . equals ( \"hour\" ) || units . equals ( \"hours\" ) ) return SECONDS_PER_HOUR ; if ( units . equals ( \"d\" ) || units . equals ( \"day\" ) || units . equals ( \"days\" ) ) return SECONDS_PER_DAY ; if ( units . equals ( \"week\" ) || units . equals ( \"weeks\" ) ) return 7 * SECONDS_PER_DAY ; if ( units . equals ( \"mon\" ) || units . equals ( \"mons\" ) || units . equals ( \"month\" ) || units . equals ( \"months\" ) ) return 30 * SECONDS_PER_DAY ; if ( units . equals ( \"yr\" ) || units . equals ( \"yrs\" ) || units . equals ( \"year\" ) || units . equals ( \"years\" ) ) return 360 * SECONDS_PER_DAY ; throw new RuntimeException ( ErddapString2 . ERROR + \" in Calendar2.factorToGetSeconds: units=\\\"\" + units + \"\\\" is invalid.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This parses n int values from s and stores results in resultsN ( or leaves items in resultsN untouched if no value available ) . [CODESPLIT] private static void parseN ( String s , char separatorN [ ] , int resultsN [ ] ) { //ensure s starts with a digit if ( s == null ) s = \"\" ; s = s . trim ( ) ; int sLength = s . length ( ) ; if ( sLength < 1 || ! ( s . charAt ( 0 ) == ' ' || ErddapString2 . isDigit ( s . charAt ( 0 ) ) ) ) { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } int po1 , po2 = - 1 ; //String2.log(\"parseN \" + s); //search for digits, non-digit.   \"1970-01-01T00:00:00.000-01:00\" boolean mMode = s . charAt ( 0 ) == ' ' ; //initial '-' is required and included when evaluating number int nParts = separatorN . length ; for ( int part = 0 ; part < nParts ; part ++ ) { if ( po2 + 1 < sLength ) { //accumulate digits po1 = po2 + 1 ; po2 = po1 ; if ( mMode ) { if ( po2 < sLength && s . charAt ( po2 ) == ' ' ) po2 ++ ; else { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } } while ( po2 < sLength && ErddapString2 . isDigit ( s . charAt ( po2 ) ) ) po2 ++ ; //digit //if no number, return; we're done if ( po2 == po1 ) return ; if ( part > 0 && separatorN [ part - 1 ] == ' ' ) { resultsN [ part ] = ErddapMath2 . roundToInt ( 1000 * ErddapString2 . parseDouble ( \"0.\" + s . substring ( po1 , po2 ) ) ) ; //String2.log(\"  millis=\" + resultsN[part]); } else { resultsN [ part ] = ErddapString2 . parseInt ( s . substring ( po1 , po2 ) ) ; } //if invalid number, return trouble if ( resultsN [ part ] == Integer . MAX_VALUE ) { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } //if no more source characters, we're done if ( po2 >= sLength ) { //String2.log(\"  \" + String2.toCSSVString(resultsN)); return ; } //if invalid separator, stop trying to read more; return trouble mMode = false ; char ch = s . charAt ( po2 ) ; if ( ch == ' ' ) ch = ' ' ; if ( separatorN [ part ] == ' ' ) { } else if ( separatorN [ part ] == ' )    if ( ch == ' ' ) { //do nothing } else if ( ch == ' ' ) { po2 -- ; //number starts with - mMode = true ; } else { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } } else if ( ch != separatorN [ part ] ) { //if not exact match ... //if current part is ':' or '.' and not matched, try to skip forward to '±' if ( ( separatorN [ part ] == ' ' || separatorN [ part ] == ' ' ) && part < nParts - 1 ) { int pmPart = ErddapString2 . indexOf ( separatorN , ' ,   art    ) ;  if ( pmPart >= 0 ) { //String2.log(\"  jump to +/-\"); part = pmPart ; if ( ch == ' ' ) { //do nothing } else if ( ch == ' ' ) { po2 -- ; //number starts with - mMode = true ; } else { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } continue ; } //if < 0, fall through to failure } resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts an ISO date time string ( [ - ] YYYY - MM - DDTHH : MM : SS . SSS±ZZ : ZZ ) into a GregorianCalendar object . <br > It is lenient ; so Jan 32 is converted to Feb 1 ; <br > The T may be any non - digit . <br > The time zone can be omitted . <br > The parts at the end of the time can be omitted . <br > If there is no time the end parts of the date can be omitted . Year is required . <br > This tries hard to be tolerant of non - valid formats ( e . g . 1971 - 1 - 2 1971 - 01 ) <br > As of 11 / 9 / 2006 NO LONGER TRUE : If year is 0 .. 49 it is assumed to be 2000 .. 2049 . <br > As of 11 / 9 / 2006 NO LONGER TRUE : If year is 50 .. 99 it is assumed to be 1950 .. 1999 . <br > If the string is too short the end of 1970 - 01 - 01T00 : 00 : 00 . 000Z will be added ( effectively ) . <br > If the string is too long the excess will be ignored . <br > If a required separator is incorrect it is an error . <br > If the date is improperly formatted it returns null . <br > Timezone Z or is treated as - 00 : 00 ( UTC / Zulu time ) <br > Timezones : e . g . 2007 - 01 - 02T03 : 04 : 05 - 01 : 00 is same as 2007 - 01 - 02T04 : 04 : 05 [CODESPLIT] public static GregorianCalendar parseISODateTime ( GregorianCalendar gc , String s ) { if ( s == null ) s = \"\" ; boolean negative = s . startsWith ( \"-\" ) ; if ( negative ) s = s . substring ( 1 ) ; if ( s . length ( ) < 1 || ! ErddapString2 . isDigit ( s . charAt ( 0 ) ) ) throw new RuntimeException ( ErddapString2 . ERROR + \" in parseISODateTime: for first character of dateTime='\" + s + \"' isn't a digit!\" ) ; if ( gc == null ) throw new RuntimeException ( ErddapString2 . ERROR + \" in parseISODateTime: gc is null!\" ) ; //default ymdhmsmom     year is the only required value int ymdhmsmom [ ] = { Integer . MAX_VALUE , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 } ; //remove trailing Z or \"UTC\" s = s . trim ( ) ; if ( Character . toLowerCase ( s . charAt ( s . length ( ) - 1 ) ) == ' ' ) s = s . substring ( 0 , s . length ( ) - 1 ) . trim ( ) ; if ( s . length ( ) >= 3 ) { String last3 = s . substring ( s . length ( ) - 3 ) . toLowerCase ( ) ; if ( last3 . equals ( \"utc\" ) || last3 . equals ( \"gmt\" ) ) s = s . substring ( 0 , s . length ( ) - 3 ) . trim ( ) ; } //if e.g., 1970-01-01 00:00:00 0:00, change ' ' to '+' (first ' '->'+' is irrelevant) s = ErddapString2 . replaceAll ( s , ' ' , ' ' ) ; //separators (\\u0000=any non-digit) char separator [ ] = { ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ,   : ,   \\ } ;  parseN ( s , separator , ymdhmsmom ) ; if ( ymdhmsmom [ 0 ] == Integer . MAX_VALUE ) throw new RuntimeException ( ErddapString2 . ERROR + \" in parseISODateTime: dateTime='\" + s + \"' has an invalid format!\" ) ; //do time zone adjustment //String2.log(\"#7=\" + ymdhmsmom[7] + \" #8=\" + ymdhmsmom[8]); if ( ymdhmsmom [ 7 ] != 0 ) ymdhmsmom [ 3 ] -= ymdhmsmom [ 7 ] ; if ( ymdhmsmom [ 8 ] != 0 ) ymdhmsmom [ 4 ] -= ymdhmsmom [ 7 ] < 0 ? - ymdhmsmom [ 8 ] : ymdhmsmom [ 8 ] ; //set gc      month -1 since gc month is 0.. gc . set ( ( negative ? - 1 : 1 ) * ymdhmsmom [ 0 ] , ymdhmsmom [ 1 ] - 1 , ymdhmsmom [ 2 ] , ymdhmsmom [ 3 ] , ymdhmsmom [ 4 ] , ymdhmsmom [ 5 ] ) ; gc . set ( MILLISECOND , ymdhmsmom [ 6 ] ) ; gc . get ( YEAR ) ; //force recalculations return gc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main . [CODESPLIT] public static void main ( String args [ ] ) throws Exception { //String fileIn = \"C:/data/dt2/point/bufr/IUA_CWAO_20060202_12.bufr\";\r //String fileIn = \"C:/data/bufr/edition3/idd/profiler/PROFILER_3.bufr\";\r //String fileIn = \"C:/data/bufr/edition3/ecmwf/synop.bufr\";\r //String fileIn = \"R:/testdata2/bufr/edition3/idd/profiler/PROFILER_1.bufr\";\r String fileIn = \"D:/mlode/bufr/cat.out\" ; NetcdfDataset ncf = NetcdfDataset . openDataset ( fileIn ) ; System . out . println ( ncf . toString ( ) ) ; /* Structure s = (Structure) ncf.findVariable(obsRecord);\r\n    StructureData sdata = s.readStructure(2);\r\n    PrintWriter pw = new PrintWriter(System.out);\r\n    NCdumpW.printStructureData(pw, sdata);  */ new WriteT41_ncFlat ( ncf , \"D:/mlode/bufr/cat2.nc\" , true ) ; //Variable v = ncf.findVariable(\"recordIndex\");\r //NCdumpW.printArray(v.read(), \"recordIndex\", pw, null);\r /* ucar.nc2.Variable v;\r\n\r\n    v = ncf.findVariable(\"trajectory_id\");\r\n    if (v != null) {\r\n      Array data = v.read();\r\n      NCdump.printArray(data, v.getName(), System.out, null);\r\n    }\r\n    v = ncf.findVariable(\"station_id\");\r\n    if (v != null) {\r\n      Array data = v.read();\r\n      NCdump.printArray(data, v.getName(), System.out, null);\r\n    }\r\n    v = ncf.findVariable(\"firstChild\");\r\n    if (v != null) {\r\n      Array data = v.read();\r\n      NCdump.printArray(data, v.getName(), System.out, null);\r\n    }\r\n    v = ncf.findVariable(\"numChildren\");\r\n    if (v != null) {\r\n      Array data = v.read();\r\n      NCdump.printArray(data, v.getName(), System.out, null);\r\n    }\r\n    System.out.println();\r\n\r\n    v = ncf.findVariable(\"record\");\r\n    //ucar.nc2.Variable v = ncf.findVariable(\"Latitude\");\r\n    //ucar.nc2.Variable v = ncf.findVariable(\"time\");\r\n    //System.out.println();\r\n    //System.out.println( v.toString());\r\n\r\n    if (v instanceof Structure) {\r\n      Structure s = (Structure) v;\r\n      StructureDataIterator iter = s.getStructureIterator();\r\n      int count = 0;\r\n      PrintWriter pw = new PrintWriter( System.out);\r\n      while (iter.hasNext()) {\r\n        System.out.println(\"record \"+count);\r\n        NCdumpW.printStructureData(pw, iter.next());\r\n        count++;\r\n      }\r\n      Array data = v.read();\r\n      NCdump.printArray(data, \"record\", System.out, null);\r\n    } else {\r\n      Array data = v.read();\r\n      int[] length = data.getShape();\r\n      System.out.println();\r\n      System.out.println(\"v2 length =\" + length[0]);\r\n\r\n      IndexIterator ii = data.getIndexIterator();\r\n      for (; ii.hasNext();) {\r\n        System.out.println(ii.getFloatNext());\r\n      }\r\n    }\r\n    ncf.close();  */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static Methods [CODESPLIT] static File findSystemTempDir ( String [ ] candidates ) { for ( String candidate : candidates ) { File f = new File ( candidate ) ; if ( f . exists ( ) && f . canRead ( ) && f . canWrite ( ) ) return f ; if ( f . mkdirs ( ) ) // Try to create the path return f ; } // As a last resort use the java temp file mechanism try { File tempfile = File . createTempFile ( \"tmp\" , \"tmp\" ) ; File tempdir = tempfile . getParentFile ( ) ; if ( ! tempdir . canWrite ( ) || ! tempdir . canRead ( ) ) return null ; return tempdir ; } catch ( IOException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Servlet API ( Selected ) [CODESPLIT] public void init ( ) throws ServletException { try { if ( initialized ) return ; initialized = true ; logServerStartup . info ( getClass ( ) . getName ( ) + \" initialization\" ) ; System . setProperty ( \"file.encoding\" , \"UTF-8\" ) ; Field charset = Charset . class . getDeclaredField ( \"defaultCharset\" ) ; charset . setAccessible ( true ) ; charset . set ( null , null ) ; } catch ( Exception e ) { throw new ServletException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked on first get so that everything is available especially Spring stuff . [CODESPLIT] public void initOnce ( HttpServletRequest req ) throws SendError { if ( once ) return ; once = true ; log . info ( getClass ( ) . getName ( ) + \" GET initialization\" ) ; if ( this . tdsContext == null ) throw new SendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , \"Cannot find TDS Context\" ) ; // Get server host + port name StringBuilder buf = new StringBuilder ( ) ; buf . append ( req . getServerName ( ) ) ; int port = req . getServerPort ( ) ; if ( port > 0 ) { buf . append ( \":\" ) ; buf . append ( port ) ; } this . server = buf . toString ( ) ; // Obtain servlet path info String tmp = HTTPUtil . canonicalpath ( req . getContextPath ( ) ) ; this . threddsname = HTTPUtil . nullify ( HTTPUtil . relpath ( tmp ) ) ; tmp = HTTPUtil . canonicalpath ( req . getServletPath ( ) ) ; this . requestname = HTTPUtil . nullify ( HTTPUtil . relpath ( tmp ) ) ; if ( this . threddsname == null ) this . threddsname = DEFAULTSERVLETNAME ; // Get the upload dir File updir = tdsContext . getUploadDir ( ) ; if ( updir == null ) { log . warn ( \"No tds.upload.dir specified\" ) ; this . uploaddir = null ; } else this . uploaddir = HTTPUtil . canonicalpath ( updir . getAbsolutePath ( ) ) ; // Get the download dir File downdir = tdsContext . getDownloadDir ( ) ; if ( downdir == null ) { log . warn ( \"No tds.download.dir specified\" ) ; this . downloaddir = null ; } else this . downloaddir = HTTPUtil . canonicalpath ( downdir . getAbsolutePath ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// [CODESPLIT] protected String inquire ( ) { Map < String , String > result = new HashMap <> ( ) ; // Return all known server key values if ( this . downloaddir != null ) result . put ( \"downloaddir\" , this . downloaddir ) ; if ( this . uploaddir != null ) result . put ( \"uploaddir\" , this . uploaddir ) ; String sresult = mapToString ( result , true , \"download\" ) ; return sresult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for BufrMessageViewer [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , Message single ) throws IOException { this . raf = raf ; protoMessage = single ; protoMessage . getRootDataDescriptor ( ) ; // construct the data descriptors, check for complete tables if ( ! protoMessage . isTablesComplete ( ) ) throw new IllegalStateException ( \"BUFR file has incomplete tables\" ) ; BufrConfig config = BufrConfig . openFromMessage ( raf , protoMessage , null ) ; // this fills the netcdf object Construct2 construct = new Construct2 ( protoMessage , config , ncfile ) ; obsStructure = construct . getObsStructure ( ) ; isSingle = true ; ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public String getDetailInfo ( ) { Formatter ff = new Formatter ( ) ; ff . format ( \"%s\" , super . getDetailInfo ( ) ) ; protoMessage . dump ( ff ) ; ff . format ( \"%n\" ) ; config . show ( ff ) ; return ff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add value to the named counter . Add counter if it doesnt already exist . [CODESPLIT] public boolean count ( String name , Comparable value ) { Counter counter = map . get ( name ) ; if ( counter == null ) { counter = add ( name ) ; } return counter . count ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an instance of this database . [CODESPLIT] public static synchronized StandardPrefixDB instance ( ) throws PrefixDBException { if ( instance == null ) { try { instance = new StandardPrefixDB ( ) ; } catch ( final Exception e ) { throw new PrefixDBException ( \"Couldn't create standard prefix-database\" , e ) ; } } return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a prefix to the database . [CODESPLIT] private void add ( final String name , final String symbol , final double definition ) throws PrefixExistsException { addName ( name , definition ) ; addSymbol ( symbol , definition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final PrefixDB db = StandardPrefixDB . instance ( ) ; System . out . println ( \"db.getPrefixBySymbol(\\\"cm\\\") = \\\"\" + db . getPrefixBySymbol ( \"cm\" ) + ' ' ) ; System . out . println ( \"db.getPrefixBySymbol(\\\"dm\\\") = \\\"\" + db . getPrefixBySymbol ( \"dm\" ) + ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for other behavior override this ; use compareXXX routines . [CODESPLIT] public int compare ( TableRow other , int col ) { String s1 = getValueAt ( col ) . toString ( ) ; String s2 = other . getValueAt ( col ) . toString ( ) ; int ret = s1 . compareToIgnoreCase ( s2 ) ; // break ties if ( ret == 0 ) return compareTie ( other , col ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for use by the subclass [CODESPLIT] protected int compareBoolean ( TableRow other , int col , boolean b1 , boolean b2 ) { // break ties if ( b1 == b2 ) return compareTie ( other , col ) ; return b1 ? 1 : - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser specific methods [CODESPLIT] DapGroup getGroupScope ( ) throws DapException { DapGroup gscope = ( DapGroup ) searchScope ( DapSort . GROUP , DapSort . DATASET ) ; if ( gscope == null ) throw new DapException ( \"Undefined Group Scope\" ) ; return gscope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attribute map utilities [CODESPLIT] SaxEvent pull ( XMLAttributeMap map , String name ) { SaxEvent event = map . remove ( name . toLowerCase ( ) ) ; return event ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add any reserved xml attributes to a node unchanged [CODESPLIT] void passReserved ( XMLAttributeMap map , DapNode node ) throws ParseException { try { DapAttribute attr = null ; for ( Map . Entry < String , SaxEvent > entry : map . entrySet ( ) ) { SaxEvent event = entry . getValue ( ) ; String key = entry . getKey ( ) ; String value = event . value ; if ( isReserved ( key ) ) node . addXMLAttribute ( key , value ) ; } } catch ( DapException de ) { throw new ParseException ( de ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attribute map utilities [CODESPLIT] SaxEvent peek ( XMLAttributeMap map , String name ) { SaxEvent event = map . get ( name . toLowerCase ( ) ) ; return event ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attribute construction [CODESPLIT] DapAttribute makeAttribute ( DapSort sort , String name , DapType basetype , List < String > nslist , DapNode parent ) throws DapException { DapAttribute attr = new DapAttribute ( name , basetype ) ; if ( sort == DapSort . ATTRIBUTE ) { attr . setBaseType ( basetype ) ; } parent . addAttribute ( attr ) ; attr . setNamespaceList ( nslist ) ; return attr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Abstract action definitions [CODESPLIT] @ Override void enterdataset ( XMLAttributeMap attrs ) throws ParseException { this . debug = getDebugLevel ( ) > 0 ; // make sure we have the latest value if ( debug ) report ( \"enterdataset\" ) ; SaxEvent name = pull ( attrs , \"name\" ) ; SaxEvent dapversion = pull ( attrs , \"dapversion\" ) ; SaxEvent dmrversion = pull ( attrs , \"dmrversion\" ) ; if ( isempty ( name ) ) throw new ParseException ( \"Empty dataset name attribute\" ) ; // convert and test version numbers float ndapversion = DAPVERSION ; if ( dapversion != null ) try { ndapversion = Float . parseFloat ( dapversion . value ) ; } catch ( NumberFormatException nfe ) { ndapversion = DAPVERSION ; } if ( ndapversion != DAPVERSION ) throw new ParseException ( \"Dataset dapVersion mismatch: \" + dapversion . value ) ; float ndmrversion = DMRVERSION ; if ( dmrversion != null ) try { ndmrversion = Float . parseFloat ( dmrversion . value ) ; } catch ( NumberFormatException nfe ) { ndmrversion = DMRVERSION ; } if ( ndmrversion != DMRVERSION ) throw new ParseException ( \"Dataset dmrVersion mismatch: \" + dmrversion . value ) ; this . root = new DapDataset ( name . value ) ; this . root . setDapVersion ( Float . toString ( ndapversion ) ) ; this . root . setDMRVersion ( Float . toString ( ndmrversion ) ) ; this . root . setDataset ( this . root ) ; passReserved ( attrs , this . root ) ; scopestack . push ( this . root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is called for <Value > ... < / Value > [CODESPLIT] @ Override void value ( String value ) throws ParseException { if ( debug ) report ( \"value\" ) ; try { DapAttribute parent = ( DapAttribute ) getScope ( DapSort . ATTRIBUTE ) ; createvalue ( value , parent ) ; } catch ( DapException de ) { throw new ParseException ( de ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public boolean isValid ( NcssPointParamsBean params , ConstraintValidatorContext constraintValidatorContext ) { constraintValidatorContext . disableDefaultConstraintViolation ( ) ; boolean isValid = true ; boolean isStnRequest = params . hasLatLonPoint ( ) && params . hasStations ( ) ; boolean isPointRequest = params . hasLatLonPoint ( ) && ! params . hasStations ( ) ; // if no stn param is provided ignore all the others, it must be a point request // if stn == all --> all stations\t\t if ( ! isStnRequest && ! isPointRequest ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.lat_or_lon_missing}\" ) . addConstraintViolation ( ) ; } /* if( params.getSubset() != null && !params.getSubset().equals(\"stns\") && !params.getSubset().equals(\"all\") && !params.getSubset().equals(\"bb\")  ){\n\t\t\tisValid = false;\n\t\t\tconstraintValidatorContext\n\t\t\t.buildConstraintViolationWithTemplate(\"{thredds.server.ncSubset.validation.subsettypeerror}\")\n\t\t\t.addConstraintViolation();\t\t\t\n\t\t}\t\t\n\t\t\n\t\tif( params.getSubset() != null && params.getSubset().equals(\"stns\") && params.getStns() == null ){\n\t\t\tisValid = false;\n\t\t\tconstraintValidatorContext\n\t\t\t.buildConstraintViolationWithTemplate(\"{thredds.server.ncSubset.validation.subsettypeerror.no_stns_param}\")\n\t\t\t.addConstraintViolation();\t\t\t\n\t\t}\n\t\t\n\t\tif( params.getSubset() != null && params.getSubset().equals(\"bb\") && (params.getNorth()  == null || params.getSouth() == null || params.getEast() == null || params.getWest() == null  )){\n\t\t\tisValid = false;\n\t\t\tconstraintValidatorContext\n\t\t\t.buildConstraintViolationWithTemplate(\"{thredds.server.ncSubset.validation.subsettypeerror.no_bounding_box}\")\n\t\t\t.addConstraintViolation();\t\t\t\n\t\t}\t\t*/ return isValid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a valid date range was specified [CODESPLIT] private boolean hasValidDateRange ( String time_start , String time_end , String time_duration ) { // no range if ( ( null == time_start ) && ( null == time_end ) && ( null == time_duration ) ) return false ; if ( ( null != time_start ) && ( null != time_end ) ) return true ; if ( ( null != time_start ) && ( null != time_duration ) ) return true ; if ( ( null != time_end ) && ( null != time_duration ) ) return true ; // misformed range // errs.append(\"Must have 2 of 3 parameters: time_start, time_end, time_duration\\n\"); return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterator interface extended [CODESPLIT] @ Override public boolean hasNext ( ) { switch ( state ) { case INITIAL : return ( slice . getFirst ( ) < slice . getStop ( ) ) ; case STARTED : return ( this . index < slice . getLast ( ) ) ; case DONE : } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > Attribute< / code > which matches name . [CODESPLIT] public final Attribute getAttribute ( String clearname ) { //throws NoSuchAttributeException {\r Attribute a = ( Attribute ) _attr . get ( clearname ) ; return ( a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > Attribute< / code > which matches name . [CODESPLIT] public final boolean hasAttribute ( String clearname ) { Attribute a = ( Attribute ) _attr . get ( clearname ) ; if ( a == null ) { return ( false ) ; } return ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an attribute to the table . If the given name already refers to an attribute and the attribute has a vector value the given value is appended to the attribute vector . Calling this function repeatedly is the way to create an attribute vector . <p / > The function throws an exception if the attribute is a container or if the type of the input value does not match the existing attribute s type and the <code > check< / code > parameter is true . Use the <code > appendContainer< / code > method to add container attributes . [CODESPLIT] public final void appendAttribute ( String clearname , int type , String value , boolean check ) throws DASException { Attribute a = ( Attribute ) _attr . get ( clearname ) ; if ( a != null && ( type != a . getType ( ) ) ) { // type mismatch error\r throw new AttributeExistsException ( \"The Attribute `\" + clearname + \"' was previously defined with a different type.\" ) ; } else if ( a != null ) { a . appendValue ( value , check ) ; } else { a = new Attribute ( type , clearname , value , check ) ; _attr . put ( clearname , a ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an attribute to the table . If the given name already refers to an attribute and the attribute has a vector value the given value is appended to the attribute vector . Calling this function repeatedly is the way to create an attribute vector . <p / > The function throws an exception if the attribute is a container or if the type of the input value does not match the existing attribute s type . Use the <code > appendContainer< / code > method to add container attributes . [CODESPLIT] public final void appendAttribute ( String clearname , int type , String value ) throws DASException { appendAttribute ( clearname , type , value , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and append an attribute container to the table . A container is another <code > AttributeTable< / code > object . [CODESPLIT] public final AttributeTable appendContainer ( String clearname ) { // return null if clearname already exists\r // FIXME! THIS SHOULD RETURN AN EXCEPTION!\r if ( _attr . get ( clearname ) != null ) return null ; AttributeTable at = new AttributeTable ( clearname ) ; Attribute a = new Attribute ( clearname , at ) ; _attr . put ( clearname , a ) ; return at ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and append an attribute container to the table . A container is another <code > AttributeTable< / code > object . [CODESPLIT] public final void addContainer ( String clearname , AttributeTable at ) throws AttributeExistsException { // return null if name already exists\r if ( _attr . get ( clearname ) != null ) { throw new AttributeExistsException ( \"The Attribute '\" + clearname + \"' already exists in the container '\" + getEncodedName ( ) + \"'\" ) ; } Attribute a = new Attribute ( clearname , at ) ; _attr . put ( clearname , a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an alias to the current table . This method is used by the DAS parser to build Aliases for the DAS . And the DDSXMLParser to add them to the DDX <p / > The new ( 9 / 26 / 02 ) DDS requires the use of <code > addAlias ( String String String ) < / code > and is the preffered way of representing the DAS information . [CODESPLIT] public final void addAlias ( String alias , String attributeName ) throws NoSuchAttributeException , AttributeExistsException { // complain if alias name already exists in this AttributeTable.\r if ( _attr . get ( alias ) != null ) { throw new AttributeExistsException ( \"Could not alias `\" + alias + \"' to `\" + attributeName + \"'. \" + \"It is a duplicat name in this AttributeTable\" ) ; } if ( Debug . isSet ( \"AttributTable\" ) ) { log . debug ( \"Adding alias '\" + alias + \"' to AttributeTable '\" + getClearName ( ) + \"'\" ) ; } Alias newAlias = new Alias ( alias , attributeName ) ; _attr . put ( alias , newAlias ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the attribute named <code > name< / code > . If the attribute has a vector value delete the <code > i< / code > th element of the vector . [CODESPLIT] public final void delAttribute ( String clearname , int i ) throws DASException { if ( i == - 1 ) { // delete the whole attribute\r _attr . remove ( clearname ) ; } else { Attribute a = ( Attribute ) _attr . get ( clearname ) ; if ( a != null ) { if ( a . isContainer ( ) ) { _attr . remove ( clearname ) ; // delete the entire container\r } else { a . deleteValueAt ( i ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the attribute table on the given <code > PrintWriter< / code > . [CODESPLIT] public void print ( PrintWriter os , String pad ) { if ( Debug . isSet ( \"AttributTable\" ) ) os . println ( \"Entered AttributeTable.print()\" ) ; os . println ( pad + getEncodedName ( ) + \" {\" ) ; for ( Enumeration e = getNames ( ) ; e . hasMoreElements ( ) ; ) { String name = ( String ) e . nextElement ( ) ; Attribute a = getAttribute ( name ) ; if ( a != null ) a . print ( os , pad + \"    \" ) ; } os . println ( pad + \"}\" ) ; if ( Debug . isSet ( \"AttributTable\" ) ) os . println ( \"Leaving AttributeTable.print()\" ) ; os . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the attribute table on the given <code > OutputStream< / code > . [CODESPLIT] public final void print ( OutputStream os , String pad ) { print ( new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( os , Util . UTF8 ) ) ) , pad ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > AttributeTable< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { AttributeTable at = ( AttributeTable ) super . cloneDAG ( map ) ; at . _attr = new SortedTable ( ) ; for ( int i = 0 ; i < _attr . size ( ) ; i ++ ) { String key = ( String ) _attr . getKey ( i ) ; Attribute element = ( Attribute ) _attr . elementAt ( i ) ; // clone element (don't clone key because it's a read-only String)\r at . _attr . put ( key , ( Attribute ) cloneDAG ( map , element ) ) ; } return at ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "subcenters [CODESPLIT] @ Override public String getSubCenterName ( int subcenter ) { if ( subcenterMap == null ) subcenterMap = makeSubcenterMap ( ) ; return subcenterMap . get ( subcenter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gen process [CODESPLIT] @ Override @ Nullable public String getGeneratingProcessName ( int genProcess ) { if ( genProcessMap == null ) makeGenProcessMap ( ) ; return genProcessMap . get ( genProcess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ levels [CODESPLIT] @ Override public Grib1ParamLevel getParamLevel ( Grib1SectionProductDefinition pds ) { int levelType = pds . getLevelType ( ) ; int pds11 = pds . getLevelValue1 ( ) ; int pds12 = pds . getLevelValue2 ( ) ; int pds1112 = pds11 << 8 | pds12 ; switch ( levelType ) { case 210 : return new Grib1ParamLevel ( this , levelType , ( float ) pds1112 , GribNumbers . MISSING ) ; case 218 : return new Grib1ParamLevel ( this , levelType , ( float ) pds11 + 200 , ( float ) pds12 + 200 ) ; case 246 : return new Grib1ParamLevel ( this , levelType , ( float ) pds1112 , GribNumbers . MISSING ) ; default : return new Grib1ParamLevel ( this , pds ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if this point is nearly equal to { @code that } . The near equality of points is determined using { @link Misc#nearlyEquals ( double double double ) } with the specified maxRelDiff . [CODESPLIT] public boolean nearlyEquals ( LatLonPointNoNormalize that , double maxRelDiff ) { return Misc . nearlyEquals ( this . getLatitude ( ) , that . getLatitude ( ) , maxRelDiff ) && Misc . nearlyEquals ( this . getLongitude ( ) , that . getLongitude ( ) , maxRelDiff ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a relative path as an array of path segments ( see { @link #getPathSegments ( String ) } return the path relative to the first path segment . [CODESPLIT] public static String stepDownRelativePath ( String [ ] pathSegments ) { if ( ! CrawlableDatasetUtils . isValidRelativePath ( pathSegments ) ) throw new IllegalArgumentException ( \"Path segments not a valid relative path.\" ) ; if ( pathSegments . length < 2 ) throw new IllegalArgumentException ( \"Number of path segments must be > 1.\" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 1 ; i < pathSegments . length - 1 ; i ++ ) { sb . append ( pathSegments [ i ] ) . append ( \"/\" ) ; } sb . append ( pathSegments [ pathSegments . length - 1 ] ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a DSP using its class string name . [CODESPLIT] synchronized public void register ( String className , boolean last ) throws DapException { try { Class < ? extends DSP > klass = ( Class < ? extends DSP > ) loader . loadClass ( className ) ; register ( klass , last ) ; } catch ( ClassNotFoundException e ) { throw new DapException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a DSP class . [CODESPLIT] synchronized public void register ( Class < ? extends DSP > klass , boolean last ) { // is this already defined? if ( registered ( klass ) ) return ; if ( last ) registry . add ( new Registration ( klass ) ) ; else registry . add ( 0 , new Registration ( klass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if a specific DSP is registered [CODESPLIT] synchronized public boolean registered ( Class < ? extends DSP > klass ) { for ( Registration r : registry ) { if ( r . dspclass == klass ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregister dsp . [CODESPLIT] synchronized public void unregister ( Class < ? extends DSP > klass ) { for ( int i = 0 ; i < registry . size ( ) ; i ++ ) { if ( registry . get ( i ) . dspclass == klass ) { registry . remove ( i ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lazy instantiation . [CODESPLIT] public static Grib2Tables factory ( int center , int subCenter , int masterVersion , int localVersion , int genProcessId ) { Grib2TablesId id = new Grib2TablesId ( center , subCenter , masterVersion , localVersion , genProcessId ) ; Grib2Tables cust = tables . get ( id ) ; if ( cust != null ) return cust ; // note that we match on id, so same Grib2Customizer may be mapped to multiple id's (eg match on -1)\r Grib2TableConfig config = Grib2TableConfig . matchTable ( id ) ; cust = build ( config ) ; tables . put ( id , cust ) ; return cust ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the time interval in units of gr . getPDS () . getTimeUnit () [CODESPLIT] @ Nullable public TimeCoordIntvDateValue getForecastTimeInterval ( Grib2Record gr ) { // note  from Arthur Taylor (degrib):\r /* If there was a range I used:\r\n\r\n    End of interval (EI) = (bytes 36-42 show an \"end of overall time interval\")\r\n    C1) End of Interval = EI;\r\n    Begin of Interval = EI - range\r\n\r\n    and if there was no interval then I used:\r\n    C2) End of Interval = Begin of Interval = Ref + ForeT.\r\n    */ if ( ! gr . getPDS ( ) . isTimeInterval ( ) ) return null ; Grib2Pds . PdsInterval pdsIntv = ( Grib2Pds . PdsInterval ) gr . getPDS ( ) ; int timeUnitOrg = gr . getPDS ( ) . getTimeUnit ( ) ; // calculate total \"range\"\r int range = 0 ; for ( Grib2Pds . TimeInterval ti : pdsIntv . getTimeIntervals ( ) ) { if ( ti . timeRangeUnit == 255 ) continue ; if ( ( ti . timeRangeUnit != timeUnitOrg ) || ( ti . timeIncrementUnit != timeUnitOrg && ti . timeIncrementUnit != 255 && ti . timeIncrement != 0 ) ) { if ( ! timeUnitWarnWasSent ) { logger . warn ( \"TimeInterval has different units timeUnit org=\" + timeUnitOrg + \" TimeInterval=\" + ti . timeIncrementUnit ) ; timeUnitWarnWasSent = true ; // throw new RuntimeException(\"TimeInterval(2) has different units\");\r } } range += ti . timeRangeLength ; if ( ti . timeIncrementUnit != 255 ) range += ti . timeIncrement ; } CalendarPeriod unitPeriod = Grib2Utils . getCalendarPeriod ( convertTimeUnit ( timeUnitOrg ) ) ; if ( unitPeriod == null ) return null ; CalendarPeriod period = unitPeriod . multiply ( range ) ; // End of Interval as date\r CalendarDate EI = pdsIntv . getIntervalTimeEnd ( ) ; if ( EI == CalendarDate . UNKNOWN ) { // all values were set to zero   LOOK guessing!\r return new TimeCoordIntvDateValue ( gr . getReferenceDate ( ) , period ) ; } else { return new TimeCoordIntvDateValue ( period , EI ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get interval size in units of hours . Only use in GribVariable to decide on variable identity when intvMerge = false . [CODESPLIT] public double getForecastTimeIntervalSizeInHours ( Grib2Pds pds ) { Grib2Pds . PdsInterval pdsIntv = ( Grib2Pds . PdsInterval ) pds ; int timeUnitOrg = pds . getTimeUnit ( ) ; // calculate total \"range\" in units of timeUnit\r int range = 0 ; for ( Grib2Pds . TimeInterval ti : pdsIntv . getTimeIntervals ( ) ) { if ( ti . timeRangeUnit == 255 ) continue ; if ( ( ti . timeRangeUnit != timeUnitOrg ) || ( ti . timeIncrementUnit != timeUnitOrg && ti . timeIncrementUnit != 255 && ti . timeIncrement != 0 ) ) { logger . warn ( \"TimeInterval(2) has different units timeUnit org=\" + timeUnitOrg + \" TimeInterval=\" + ti . timeIncrementUnit ) ; throw new RuntimeException ( \"TimeInterval(2) has different units\" ) ; } range += ti . timeRangeLength ; if ( ti . timeIncrementUnit != 255 ) range += ti . timeIncrement ; } // now convert that range to units of the requested period.\r CalendarPeriod timeUnitPeriod = Grib2Utils . getCalendarPeriod ( convertTimeUnit ( timeUnitOrg ) ) ; if ( timeUnitPeriod == null ) return GribNumbers . UNDEFINEDD ; if ( timeUnitPeriod . equals ( CalendarPeriod . Hour ) ) return range ; double fac ; if ( timeUnitPeriod . getField ( ) == CalendarPeriod . Field . Month ) { fac = 30.0 * 24.0 ; // nominal hours in a month\r } else if ( timeUnitPeriod . getField ( ) == CalendarPeriod . Field . Year ) { fac = 365.0 * 24.0 ; // nominal hours in a year\r } else { fac = CalendarPeriod . Hour . getConvertFactor ( timeUnitPeriod ) ; } return fac * range ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this has a time interval coordinate get time interval [CODESPLIT] @ Nullable public int [ ] getForecastTimeIntervalOffset ( Grib2Record gr ) { TimeCoordIntvDateValue tinvd = getForecastTimeInterval ( gr ) ; if ( tinvd == null ) return null ; Grib2Pds pds = gr . getPDS ( ) ; int unit = convertTimeUnit ( pds . getTimeUnit ( ) ) ; TimeCoordIntvValue tinv = tinvd . convertReferenceDate ( gr . getReferenceDate ( ) , Grib2Utils . getCalendarPeriod ( unit ) ) ; if ( tinv == null ) return null ; int [ ] result = new int [ 2 ] ; result [ 0 ] = tinv . getBounds1 ( ) ; result [ 1 ] = tinv . getBounds2 ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unit of vertical coordinate . from Grib2 code table 4 . 5 . Only levels with units get a dimension added [CODESPLIT] @ Override public VertCoordType getVertUnit ( int code ) { //     VertCoordType(int code, String desc, String abbrev, String units, String datum, boolean isPositiveUp, boolean isLayer)\r switch ( code ) { case 11 : case 12 : return new VertCoordType ( code , \"m\" , null , true ) ; case 20 : return new VertCoordType ( code , \"K\" , null , false ) ; case 100 : return new VertCoordType ( code , \"Pa\" , null , false ) ; case 102 : return new VertCoordType ( code , \"m\" , \"mean sea level\" , true ) ; case 103 : return new VertCoordType ( code , \"m\" , \"ground\" , true ) ; case 104 : case 105 : return new VertCoordType ( code , \"sigma\" , null , false ) ; // positive?\r case 106 : return new VertCoordType ( code , \"m\" , \"land surface\" , false ) ; case 107 : return new VertCoordType ( code , \"K\" , null , true ) ; // positive?\r case 108 : return new VertCoordType ( code , \"Pa\" , \"ground\" , true ) ; case 109 : return new VertCoordType ( code , \"K m2 kg-1 s-1\" , null , true ) ; // positive?\r case 114 : return new VertCoordType ( code , \"numeric\" , null , false ) ; case 117 : return new VertCoordType ( code , \"m\" , null , true ) ; case 119 : return new VertCoordType ( code , \"Pa\" , null , false ) ; // ??\r case 160 : return new VertCoordType ( code , \"m\" , \"sea level\" , false ) ; case 161 : return new VertCoordType ( code , \"m\" , \"water surface\" , false ) ; // LOOK NCEP specific\r case 235 : return new VertCoordType ( code , \"0.1 C\" , null , true ) ; case 237 : return new VertCoordType ( code , \"m\" , null , true ) ; case 238 : return new VertCoordType ( code , \"m\" , null , true ) ; default : return new VertCoordType ( code , null , null , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute inferred information [CODESPLIT] public void finish ( ) { if ( this . finished ) return ; if ( this . ce == null ) this . visiblenodes = nodelist ; else { this . visiblenodes = new ArrayList < DapNode > ( nodelist . size ( ) ) ; for ( int i = 0 ; i < nodelist . size ( ) ; i ++ ) { DapNode node = nodelist . get ( i ) ; if ( ce . references ( node ) ) visiblenodes . add ( node ) ; } } this . topvariables = new ArrayList < DapVariable > ( ) ; this . allvariables = new ArrayList < DapVariable > ( ) ; this . allgroups = new ArrayList < DapGroup > ( ) ; this . allenums = new ArrayList < DapEnumeration > ( ) ; this . allcompounds = new ArrayList < DapStructure > ( ) ; this . alldimensions = new ArrayList < DapDimension > ( ) ; finishR ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive helper [CODESPLIT] protected void finishR ( DapNode node ) { if ( ce != null && ! ce . references ( node ) ) return ; switch ( node . getSort ( ) ) { case DIMENSION : this . alldimensions . add ( ( DapDimension ) node ) ; break ; case ENUMERATION : this . allenums . add ( ( DapEnumeration ) node ) ; break ; case SEQUENCE : case STRUCTURE : this . allcompounds . add ( ( DapStructure ) node ) ; break ; case VARIABLE : if ( node . isTopLevel ( ) ) this . topvariables . add ( ( DapVariable ) node ) ; this . allvariables . add ( ( DapVariable ) node ) ; break ; case GROUP : case DATASET : DapGroup g = ( DapGroup ) node ; this . allgroups . add ( g ) ; for ( DapNode subnode : g . getDecls ( ) ) { finishR ( subnode ) ; } break ; default : /*ignore*/ break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an FQN and use it to trace to a specific object in a dataset . Note that this is quite tricky in the face of backslash escapes . Because of backslash escapes we cannot use the String . split function because it does appear to be possible to write a regexp that handles preceding backslashes correctly . Instead we must parse character by character left to right . Traversal into structs : In theory a map variable could point to a field of a structure . However in practice this will not work because we would need a specific instance of that field which means including dimension indices must be included starting from some top - level variable . We choose for now to make that illegal until such time as there is a well - defined meaning for this . Note : this assumes the fqn is absolute ( i . e . starts with / ) . [CODESPLIT] public DapNode lookup ( String fqn , DapSort ... sortset ) throws DapException { fqn = fqn . trim ( ) ; if ( fqn == null ) return null ; if ( \"\" . equals ( fqn ) || \"/\" . equals ( fqn ) ) { return this ; } if ( fqn . charAt ( 0 ) == ' ' ) fqn = fqn . substring ( 1 ) ; // remove leading / //Check first for an atomic type TypeSort ts = TypeSort . getTypeSort ( fqn ) ; if ( ts != null && ts . isAtomic ( ) ) { // see if we are looking for an atomic type for ( DapSort ds : sortset ) { if ( ds == DapSort . ATOMICTYPE ) return DapType . lookup ( ts ) ; } } // Do not use split to be able to look for escaped '/' // Warning: elements of path are unescaped List < String > path = DapUtil . backslashSplit ( fqn , ' ' ) ; DapGroup current = dataset ; // Walk all but the last element to walk group path for ( int i = 0 ; i < path . size ( ) - 1 ; i ++ ) { String groupname = Escape . backslashUnescape ( path . get ( i ) ) ; DapGroup g = ( DapGroup ) current . findInGroup ( groupname , DapSort . GROUP ) ; if ( g == null ) return null ; assert ( g . getSort ( ) == DapSort . GROUP ) ; current = ( DapGroup ) g ; } if ( ! ALLOWFIELDMAPS ) { String targetname = Escape . backslashUnescape ( path . get ( path . size ( ) - 1 ) ) ; return current . findInGroup ( targetname , sortset ) ; } else { // ALLOWFIELDMAPS) // We need to handle the last segment of the group path // to deal with struct walking using '.'. We need to obtain the last segment // with escapes intact so we can spot '.' separators. // Locate the last element in the last group // Start by looking for any containing structure String varpart = path . get ( path . size ( ) - 1 ) ; // Note that this still has escapes // So that '.' parsing will be correct. List < String > structpath = DapUtil . backslashSplit ( varpart , ' ' ) ; String outer = Escape . backslashUnescape ( structpath . get ( 0 ) ) ; if ( structpath . size ( ) == 1 ) { return current . findInGroup ( outer , sortset ) ; } else { // It is apparently a structure field // locate the outermost structure to start with DapStructure currentstruct = ( DapStructure ) current . findInGroup ( outer , DapSort . STRUCTURE , DapSort . SEQUENCE ) ; if ( currentstruct == null ) return null ; // does not exist // search for the innermost structure String fieldname ; for ( int i = 1 ; i < structpath . size ( ) - 1 ; i ++ ) { fieldname = Escape . backslashUnescape ( structpath . get ( i ) ) ; DapVariable field = ( DapVariable ) currentstruct . findByName ( fieldname ) ; if ( field == null ) throw new DapException ( \"No such field: \" + fieldname ) ; if ( ! field . isCompound ( ) ) break ; currentstruct = ( DapStructure ) field . getBaseType ( ) ; } fieldname = Escape . backslashUnescape ( structpath . get ( structpath . size ( ) - 1 ) ) ; DapVariable field = currentstruct . findByName ( fieldname ) ; if ( field == null ) throw new DapException ( \"No such field: \" + fieldname ) ; if ( field . getSort ( ) . oneof ( sortset ) ) return ( field ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort the nodelist into prefix left to right order [CODESPLIT] public void sort ( ) { List < DapNode > sorted = new ArrayList < DapNode > ( ) ; sortR ( this , sorted ) ; // Assign indices for ( int i = 0 ; i < sorted . size ( ) ; i ++ ) { sorted . get ( i ) . setIndex ( i ) ; } this . nodelist = sorted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort helper [CODESPLIT] public void sortR ( DapNode node , List < DapNode > sortlist ) { DapVariable var = null ; Map < String , DapAttribute > attrs = null ; sortlist . add ( node ) ; switch ( node . getSort ( ) ) { case DATASET : case GROUP : // Walk the decls in this group in order // attributes, dimensions, enums, variables, groups DapGroup group = ( DapGroup ) node ; attrs = group . getAttributes ( ) ; for ( Map . Entry < String , DapAttribute > entry : attrs . entrySet ( ) ) { sortR ( entry . getValue ( ) , sortlist ) ; } List < DapDimension > dims = group . getDimensions ( ) ; if ( dims != null ) for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { sortR ( dims . get ( i ) , sortlist ) ; } List < DapEnumeration > enums = group . getEnums ( ) ; if ( enums != null ) for ( int i = 0 ; i < enums . size ( ) ; i ++ ) { sortR ( enums . get ( i ) , sortlist ) ; } List < DapVariable > vars = group . getVariables ( ) ; if ( vars != null ) for ( int i = 0 ; i < vars . size ( ) ; i ++ ) { sortR ( vars . get ( i ) , sortlist ) ; } List < DapGroup > groups = group . getGroups ( ) ; if ( groups != null ) for ( int i = 0 ; i < groups . size ( ) ; i ++ ) { sortR ( groups . get ( i ) , sortlist ) ; } break ; case VARIABLE : var = ( DapVariable ) node ; attrs = var . getAttributes ( ) ; if ( attrs != null ) for ( Map . Entry < String , DapAttribute > entry : attrs . entrySet ( ) ) { sortR ( entry . getValue ( ) , sortlist ) ; } List < DapMap > maps = var . getMaps ( ) ; if ( maps != null ) for ( int i = 0 ; i < maps . size ( ) ; i ++ ) { sortR ( maps . get ( i ) , sortlist ) ; } dims = var . getDimensions ( ) ; if ( dims != null ) for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { sortR ( dims . get ( i ) , sortlist ) ; } break ; case ATTRIBUTE : attrs = node . getAttributes ( ) ; if ( attrs != null ) for ( String name : attrs . keySet ( ) ) { sortR ( attrs . get ( name ) , sortlist ) ; } break ; default : break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare 2 tables print report . [CODESPLIT] public static void compareTables ( Grib2ParamTableInterface t1 , Grib2ParamTableInterface t2 , Formatter f ) { int extra = 0 ; int udunits = 0 ; int conflict = 0 ; f . format ( \"%s%n\" , t2 . getName ( ) ) ; for ( GribTables . Parameter p1 : t1 . getParameters ( ) ) { if ( t1 . getParameter ( p1 . getNumber ( ) ) == null ) { f . format ( \" ERROR %s missing own parameter %d%n\" , t1 . getShortName ( ) , p1 . getNumber ( ) ) ; } GribTables . Parameter p2 = t2 . getParameter ( p1 . getNumber ( ) ) ; if ( p2 == null ) { extra ++ ; if ( verbose ) { f . format ( \"  %s missing %s%n\" , t2 . getShortName ( ) , p1 ) ; } } else { if ( ! Util . equivilantName ( p1 . getName ( ) , p2 . getName ( ) ) ) { f . format ( \"  p1=%10s %s%n\" , p1 . getId ( ) , p1 . getName ( ) ) ; f . format ( \"  p2=%10s %s%n\" , p2 . getId ( ) , p2 . getName ( ) ) ; conflict ++ ; } if ( ! p1 . getUnit ( ) . equalsIgnoreCase ( p2 . getUnit ( ) ) ) { String cu1 = Util . cleanUnit ( p1 . getUnit ( ) ) ; String cu2 = Util . cleanUnit ( p2 . getUnit ( ) ) ; // eliminate common non-udunits boolean isUnitless1 = Util . isUnitless ( cu1 ) ; boolean isUnitless2 = Util . isUnitless ( cu2 ) ; if ( isUnitless1 != isUnitless2 ) { f . format ( \"  unitless for %10s %s != %s%n\" , p1 . getId ( ) , cu1 , cu2 ) ; udunits ++ ; } else if ( ! isUnitless1 ) { try { SimpleUnit su1 = SimpleUnit . factoryWithExceptions ( cu1 ) ; if ( ! su1 . isCompatible ( cu2 ) ) { f . format ( \"  incompatible for %10s %s (%s) != %s (org %s)%n\" , p1 . getId ( ) , cu1 , su1 , cu2 , p2 . getUnit ( ) ) ; udunits ++ ; } } catch ( Exception e ) { f . format ( \"  udunits cant parse=%10s %15s %15s%n\" , p1 . getId ( ) , cu1 , cu2 ) ; } } } } } int missing = 0 ; for ( GribTables . Parameter p2 : t2 . getParameters ( ) ) { if ( t2 . getParameter ( p2 . getNumber ( ) ) == null ) { f . format ( \" ERROR %s missing own parameter %d%n\" , t2 . getShortName ( ) , p2 . getNumber ( ) ) ; } GribTables . Parameter p1 = t1 . getParameter ( p2 . getNumber ( ) ) ; if ( p1 == null ) { missing ++ ; f . format ( \"  %s missing %s%n\" , t1 . getShortName ( ) , p2 ) ; } } if ( conflict > 0 || udunits > 0 || missing > 0 ) { f . format ( \" ***Conflicts=%d extra=%d udunits=%d missing=%s%n\" , conflict , extra , udunits , missing ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stuff for Iosp [CODESPLIT] RandomAccessFile getRaf ( int partno , int fileno ) throws IOException { Partition part = getPartition ( partno ) ; try ( GribCollectionImmutable gc = part . getGribCollection ( ) ) { return gc . getDataRaf ( fileno ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging [CODESPLIT] public String getFilename ( int partno , int fileno ) throws IOException { Partition part = getPartition ( partno ) ; try ( GribCollectionImmutable gc = part . getGribCollection ( ) ) { return gc . getFilename ( fileno ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if this is a valid file for this IOServiceProvider . [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { try { raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . seek ( 0 ) ; raf . skipBytes ( 4 ) ; String test = raf . readString ( 40 ) ; return test . equals ( EMISSIONS ) || test . equals ( AVERAGE ) || test . equals ( AIRQUALITY ) || test . equals ( INSTANT ) ; } catch ( IOException ioe ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open existing file and populate ncfile with it . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { /*\r\n     * <b>open</b> initializes the file meta data and creates all variables.\r\n     * The meta-data and variable information is gathered from the UAM-IV\r\n     * header.  The header format is detailed in the CAMx User's \r\n     * guide and copied here.\r\n     * \r\n     * Header:\r\n     * name,note,ione,nspec,ibdate,btime,iedate,etime\r\n     * rdum,rdum,iutm,xorg,yorg,delx,dely,nx,ny,nz,idum,idum,rdum,rdum,rdum\r\n     * ione,ione,nx,ny\r\n     * (mspec(l),l=1,nspec)\r\n     *\r\n     * name - Text string (character*4(10) array)\r\n     * note - Text string containing file description (character*4(60) array)\r\n     * ione - Dummy variable = 1\r\n     * nspec - Number of species on file\r\n     * ibdate - Beginning date (YYJJJ)\r\n     * btime - Beginning hour (HHMM)\r\n     * iedate - Ending date (YYJJJ)\r\n     * etime - Ending hour (HHMM)\r\n     * rdum - Dummy real variable\r\n     * iutm - UTM zone (ignored for other projections)\r\n     * xorg - Grid x-origin at southwest corner of domain (m or degrees longitude)\r\n     * yorg - Grid y-origin at southwest corner of domain (m or degrees latitude)\r\n     * delx - Cell size in x-direction (m or degrees longitude)\r\n     * dely - Cell size in y-direction (m or degrees longitude)\r\n     * nx - Number of grid columns\r\n     * ny - Number of grid rows\r\n     * nz - Number of layers\r\n     * idum - Dummy integer variable\r\n     * mspec - Species names for nspec species (character*4(10,nspec) array)\r\n     *\r\n     *\r\n     *   time step is HHMMSS\r\n     *\r\n     *  the projection is:\r\n     *   LCC // >  :GDTYP = 2; // int\r\n     *   First True Latitude (Alpha):  \t30N // >  :P_ALP = 30.0; // double\r\n     *   Second True Latitude (Beta): \t60N // >  :P_BET = 60.0; // double\r\n     *   Central Longitude (Gamma): \t100W //>  :XCENT = -100.0; // double\r\n     *   Projection Origin: \t(100W, 40N) //>  :YCENT = 40.0; // double\r\n     *\r\n     */ // Internalize raf and ncfile\r super . open ( raf , ncfile , cancelTask ) ; // set raf to big endian and start at the beginning\r raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . seek ( 0 ) ; // Read first line of UAM-IV header\r raf . skipBytes ( 4 ) ; // Skip record pad\r String name = raf . readString ( 40 ) ; // read 40 name\r String note = raf . readString ( 240 ) ; int itzone = raf . readInt ( ) ; // Read the time zone\r int nspec = raf . readInt ( ) ; // Read number of species\r int bdate = raf . readInt ( ) ; // get file start date\r float btime = raf . readFloat ( ) ; // get file start time\r int edate = raf . readInt ( ) ; // get file end date\r float etime = raf . readFloat ( ) ; // get file end time\r int btimei = ( int ) btime ; // convert btime to an integer\r // CAMx times are sometimes provided as HH or HHMM.\r // IOAPI times are always provided as HHMMSS.\r // CAMx times less than 100 are HH and should be\r // multipled by 100 to get HHMM.  CAMx times less\r // 10000 are HHMM and should be multipled by 100\r // to get HHMMSS.\r if ( btimei < 100 ) btimei = btimei * 100 ; if ( btimei < 10000 ) btimei = btimei * 100 ; /*\r\n    * Dates are YYJJJ and are heuristically converted\r\n    * to YYYYJJJ based on the following assumption:\r\n    * YY < 70 are 2000\r\n    * YY >= 70 are 1900\r\n    *\r\n    */ if ( bdate < 70000 ) { edate = edate + 2000000 ; bdate = bdate + 2000000 ; } else { edate = edate + 1900000 ; bdate = bdate + 1900000 ; } raf . skipBytes ( 4 ) ; //Skip record pad\r // Read second line of UAM-IV header\r raf . skipBytes ( 4 ) ; //Skip record pad\r float plon = raf . readFloat ( ) ; // get polar longitude\r float plat = raf . readFloat ( ) ; // get polar latitude\r int iutm = raf . readInt ( ) ; // get utm\r float xorg = raf . readFloat ( ) ; // get x origin in meters\r float yorg = raf . readFloat ( ) ; // get y origin in meters\r float delx = raf . readFloat ( ) ; // get x cell size in meters\r float dely = raf . readFloat ( ) ; // get y cell size in meters\r int nx = raf . readInt ( ) ; // get number of columns\r int ny = raf . readInt ( ) ; // get number of rows\r int nz = raf . readInt ( ) ; // get number of layers\r // get projection number\r //    (0: lat-lon;\r //     1: Universal Transverse Mercator;\r //     2: Lambert Conic Conformal;\r //     3: Polar stereographic)\r // These translate to IOAPI GDTYP3D values 1, 5, 2, and 6 respectively\r int iproj = raf . readInt ( ) ; int istag = raf . readInt ( ) ; // Read stagger indicator\r float tlat1 = raf . readFloat ( ) ; // Read true latitude 1\r float tlat2 = raf . readFloat ( ) ; // Read true latitude 2\r raf . skipBytes ( 4 ) ; //Skip 1 dummies\r raf . skipBytes ( 4 ) ; //Skip record pad\r // Read third line of UAM-IV header\r raf . skipBytes ( 4 ) ; //Skip record pad\r raf . skipBytes ( 8 ) ; //Skip 2 dummies\r int nx2 = raf . readInt ( ) ; // duplicate number of columns\r int ny2 = raf . readInt ( ) ; // duplicate number of rows\r raf . skipBytes ( 8 ) ; //Skip 2 dummies    \r nz = Math . max ( nz , 1 ) ; // number of layers; Emissions files occasionally report 0 layers\r /*\r\n     * 1) Read each species name\r\n     * 2) remove white space from the name\r\n     * 3) store the names\r\n     * 4) internalize them\r\n     */ int count = 0 ; String [ ] spc_names = new String [ nspec ] ; while ( count < nspec ) { String spc = raf . readString ( 40 ) ; // 1) read species name\r spc_names [ count ++ ] = spc . replace ( \" \" , \"\" ) ; // 2&3) store name without whitespace\r } this . species_names = spc_names ; // 4) internalize names\r raf . skipBytes ( 4 ) ; // Skip record pad\r // Note this position; it is the start of the data block\r this . data_start = raf . getFilePointer ( ) ; // Note the number of float equivalents (4 byte chunks) in data block\r int data_length_float_equivalents = ( ( int ) raf . length ( ) - ( int ) data_start ) / 4 ; // Store 2D value size\r this . n2dvals = nx * ny ; // Store 3D value size\r this . n3dvals = nx * ny * nz ; // Store 2D binary data block size: include values (nx*ny), \r // species name (10), a dummy (1) and 2 record pads\r int spc_2D_block = nx * ny + 10 + 2 + 1 ; // Store 3D binary data block size\r this . spc_3D_block = spc_2D_block * nz ; // Store whole data block size; includes date (6)\r this . data_block = this . spc_3D_block * nspec + 6 ; // Store the number of times\r int ntimes = data_length_float_equivalents / this . data_block ; // Add dimensions based on header values\r ncfile . addDimension ( null , new Dimension ( \"TSTEP\" , ntimes , true ) ) ; ncfile . addDimension ( null , new Dimension ( \"LAY\" , nz , true ) ) ; ncfile . addDimension ( null , new Dimension ( \"ROW\" , ny , true ) ) ; ncfile . addDimension ( null , new Dimension ( \"COL\" , nx , true ) ) ; // Force sync of dimensions\r ncfile . finish ( ) ; count = 0 ; /*\r\n    * For each species, create a variable with long_name,\r\n    * and var_desc, and units.  long_name and var_desc are\r\n    * simply the species name.  units is heuristically\r\n    * determined from the name\r\n    */ HashSet < String > AeroSpcs = new HashSet <> ( Arrays . asList ( \"PSO4\" , \"PNO3\" , \"PNH4\" , \"PH2O\" , \"SOPA\" , \"SOPB\" , \"NA\" , \"PCL\" , \"POA\" , \"PEC\" , \"FPRM\" , \"FCRS\" , \"CPRM\" , \"CCRS\" ) ) ; HashSet < String > LULC = new HashSet <> ( Arrays . asList ( \"WATER\" , \"ICE\" , \"LAKE\" , \"ENEEDL\" , \"EBROAD\" , \"DNEEDL\" , \"DBROAD\" , \"TBROAD\" , \"DDECID\" , \"ESHRUB\" , \"DSHRUB\" , \"TSHRUB\" , \"SGRASS\" , \"LGRASS\" , \"CROPS\" , \"RICE\" , \"SUGAR\" , \"MAIZE\" , \"COTTON\" , \"ICROPS\" , \"URBAN\" , \"TUNDRA\" , \"SWAMP\" , \"DESERT\" , \"MWOOD\" , \"TFOREST\" ) ) ; while ( count < nspec ) { String spc = spc_names [ count ++ ] ; Variable temp = ncfile . addVariable ( null , spc , DataType . FLOAT , \"TSTEP LAY ROW COL\" ) ; if ( spc . equals ( WINDX ) || spc . equals ( WINDY ) || spc . equals ( SPEED ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"m/s\" ) ) ; } else if ( spc . equals ( VERTDIFF ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"m**2/s\" ) ) ; } else if ( spc . equals ( TEMP ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"K\" ) ) ; } else if ( spc . equals ( PRESS ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"hPa\" ) ) ; } else if ( spc . equals ( HEIGHT ) || spc . equals ( PBL ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"m\" ) ) ; } else if ( spc . equals ( CLDWATER ) || spc . equals ( PRECIP ) || spc . equals ( RAIN ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"g/m**3\" ) ) ; } else if ( spc . equals ( CLDOD ) || spc . equals ( \"CLOUDOD\" ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"none\" ) ) ; } else if ( spc . equals ( \"SNOWCOVER\" ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"yes/no\" ) ) ; } else if ( spc . startsWith ( \"SOA\" ) || AeroSpcs . contains ( spc ) ) { if ( name . equals ( EMISSIONS ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"g/time\" ) ) ; } else { temp . addAttribute ( new Attribute ( CDM . UNITS , \"ug/m**3\" ) ) ; } } else if ( LULC . contains ( spc ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"fraction\" ) ) ; } else if ( spc . lastIndexOf ( \"_\" ) > - 1 ) { String tmpunit = spc . substring ( spc . lastIndexOf ( \"_\" ) + 1 ) ; tmpunit = tmpunit . trim ( ) ; switch ( tmpunit ) { case \"M2pS\" : tmpunit = \"m**2/s\" ; break ; case \"MpS\" : tmpunit = \"m/s\" ; break ; case \"PPM\" : tmpunit = \"ppm\" ; break ; case \"MB\" : tmpunit = \"millibar\" ; break ; case \"GpM3\" : tmpunit = \"g/m**3\" ; break ; case \"M\" : tmpunit = \"m\" ; break ; } temp . addAttribute ( new Attribute ( CDM . UNITS , tmpunit ) ) ; } else { if ( name . equals ( EMISSIONS ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , \"mol/time\" ) ) ; } else { temp . addAttribute ( new Attribute ( CDM . UNITS , \"ppm\" ) ) ; } } temp . addAttribute ( new Attribute ( CDM . LONG_NAME , spc ) ) ; temp . addAttribute ( new Attribute ( \"var_desc\" , spc ) ) ; } /*\r\n    * Create 1...n array of \"sigma\" values\r\n    */ double [ ] sigma = new double [ nz + 1 ] ; count = 0 ; while ( count < nz + 1 ) { sigma [ count ++ ] = count ; } int [ ] size = new int [ 1 ] ; size [ 0 ] = nz + 1 ; Array sigma_arr = Array . factory ( DataType . DOUBLE , size , sigma ) ; /*\r\n    * Add meta-data according to the IOAPI conventions\r\n    * http://www.baronams.com/products/ioapi\r\n    */ ncfile . addAttribute ( null , new Attribute ( \"VGLVLS\" , sigma_arr ) ) ; ncfile . addAttribute ( null , new Attribute ( \"SDATE\" , bdate ) ) ; ncfile . addAttribute ( null , new Attribute ( \"STIME\" , btimei ) ) ; ncfile . addAttribute ( null , new Attribute ( \"TSTEP\" , 10000 ) ) ; ncfile . addAttribute ( null , new Attribute ( \"NSTEPS\" , ntimes ) ) ; ncfile . addAttribute ( null , new Attribute ( \"NLAYS\" , nz ) ) ; ncfile . addAttribute ( null , new Attribute ( \"NROWS\" , ny ) ) ; ncfile . addAttribute ( null , new Attribute ( \"NCOLS\" , nx ) ) ; ncfile . addAttribute ( null , new Attribute ( \"XORIG\" , ( double ) xorg ) ) ; ncfile . addAttribute ( null , new Attribute ( \"YORIG\" , ( double ) yorg ) ) ; ncfile . addAttribute ( null , new Attribute ( \"XCELL\" , ( double ) delx ) ) ; ncfile . addAttribute ( null , new Attribute ( \"YCELL\" , ( double ) dely ) ) ; /*\r\n     * IOAPI Projection parameters are provided by a colocated camxproj.txt file;\r\n     *\r\n     * to do:\r\n     * 1) needs earth radius\r\n     * 2) needs better error checking\r\n    */ Integer gdtyp = 2 ; Double p_alp = 20. ; Double p_bet = 60. ; Double p_gam = 0. ; Double xcent = - 95. ; Double ycent = 25. ; if ( ! ( ( iproj == 0 ) && ( tlat1 == 0 ) && ( tlat2 == 0 ) && ( plon == 0 ) && ( plat == 0 ) ) ) { xcent = ( double ) plon ; ycent = ( double ) plat ; if ( iproj == 0 ) { // Lat-Lon (iproj=0) has no additional information\r gdtyp = 1 ; } else if ( iproj == 1 ) { // UTM uses only iutm \r gdtyp = 5 ; p_alp = ( double ) iutm ; } else if ( iproj == 2 ) { gdtyp = 2 ; p_alp = ( double ) tlat1 ; p_bet = ( double ) tlat2 ; p_gam = ( double ) plon ; } else if ( iproj == 3 ) { gdtyp = 6 ; if ( plat == 90 ) { p_alp = 1. ; } else if ( plat == - 90 ) { p_alp = - 1. ; } p_bet = ( double ) tlat1 ; p_gam = ( double ) plon ; } else { gdtyp = 2 ; p_alp = 20. ; p_bet = 60. ; p_gam = 0. ; xcent = - 95. ; ycent = 25. ; } } String thisLine ; String projpath = raf . getLocation ( ) ; Boolean lgdtyp = false ; Boolean lp_alp = false ; Boolean lp_bet = false ; Boolean lp_gam = false ; Boolean lxcent = false ; Boolean lycent = false ; int lastIndex = projpath . lastIndexOf ( File . separator ) ; if ( lastIndex <= 0 ) lastIndex = projpath . lastIndexOf ( ' ' ) ; if ( lastIndex > 0 ) projpath = projpath . substring ( 0 , lastIndex ) ; projpath = projpath + File . separator + \"camxproj.txt\" ; File paramFile = new File ( projpath ) ; if ( paramFile . exists ( ) ) { try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( new FileInputStream ( paramFile ) , CDM . UTF8 ) ) ) { while ( ( thisLine = br . readLine ( ) ) != null ) { if ( thisLine . length ( ) == 0 ) continue ; if ( thisLine . charAt ( 0 ) == ' ' ) continue ; String [ ] key_value = thisLine . split ( \"=\" ) ; switch ( key_value [ 0 ] ) { case \"GDTYP\" : gdtyp = Integer . parseInt ( key_value [ 1 ] ) ; lgdtyp = true ; break ; case \"P_ALP\" : p_alp = Double . parseDouble ( key_value [ 1 ] ) ; lp_alp = true ; break ; case \"P_BET\" : p_bet = Double . parseDouble ( key_value [ 1 ] ) ; lp_bet = true ; break ; case \"P_GAM\" : p_gam = Double . parseDouble ( key_value [ 1 ] ) ; lp_gam = true ; break ; case \"YCENT\" : ycent = Double . parseDouble ( key_value [ 1 ] ) ; lycent = true ; break ; case \"XCENT\" : xcent = Double . parseDouble ( key_value [ 1 ] ) ; lxcent = true ; break ; } } } if ( ! lgdtyp ) log . warn ( \"GDTYP not found; using \" + gdtyp . toString ( ) ) ; if ( ! lp_alp ) log . warn ( \"P_ALP not found; using \" + p_alp . toString ( ) ) ; if ( ! lp_bet ) log . warn ( \"P_BET not found; using \" + p_bet . toString ( ) ) ; if ( ! lp_gam ) log . warn ( \"P_GAM not found; using \" + p_gam . toString ( ) ) ; if ( ! lxcent ) log . warn ( \"XCENT not found; using \" + xcent . toString ( ) ) ; if ( ! lycent ) log . warn ( \"YCENT not found; using \" + ycent . toString ( ) ) ; } else { if ( log . isDebugEnabled ( ) ) log . debug ( \"UAMIVServiceProvider: adding projection file\" ) ; try ( FileOutputStream out = new FileOutputStream ( paramFile ) ) { OutputStreamWriter fout = new OutputStreamWriter ( out , CDM . utf8Charset ) ; BufferedWriter bw = new BufferedWriter ( fout ) ; bw . write ( \"# Projection parameters are based on IOAPI.  For details, see www.baronams.com/products/ioapi/GRIDS.html\" ) ; bw . newLine ( ) ; bw . write ( \"GDTYP=\" ) ; bw . write ( gdtyp . toString ( ) ) ; bw . newLine ( ) ; bw . write ( \"P_ALP=\" ) ; bw . write ( p_alp . toString ( ) ) ; bw . newLine ( ) ; bw . write ( \"P_BET=\" ) ; bw . write ( p_bet . toString ( ) ) ; bw . newLine ( ) ; bw . write ( \"P_GAM=\" ) ; bw . write ( p_gam . toString ( ) ) ; bw . newLine ( ) ; bw . write ( \"XCENT=\" ) ; bw . write ( xcent . toString ( ) ) ; bw . newLine ( ) ; bw . write ( \"YCENT=\" ) ; bw . write ( ycent . toString ( ) ) ; bw . newLine ( ) ; bw . flush ( ) ; bw . close ( ) ; } } ncfile . addAttribute ( null , new Attribute ( \"GDTYP\" , gdtyp ) ) ; ncfile . addAttribute ( null , new Attribute ( \"P_ALP\" , p_alp ) ) ; ncfile . addAttribute ( null , new Attribute ( \"P_BET\" , p_bet ) ) ; ncfile . addAttribute ( null , new Attribute ( \"P_GAM\" , p_gam ) ) ; ncfile . addAttribute ( null , new Attribute ( \"XCENT\" , xcent ) ) ; ncfile . addAttribute ( null , new Attribute ( \"YCENT\" , ycent ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from a top level Variable and return a memory resident Array . This Array has the same element type as the Variable and the requested shape . [CODESPLIT] public ucar . ma2 . Array readData ( Variable v2 , Section wantSection ) throws IOException , InvalidRangeException { /*\r\n     * <b>readData</b> seeks and reads the data for each variable.  The variable\r\n     * data format is detailed in the CAMx User's guide and summarized here.\r\n     * \r\n     * For each time:\r\n     *   ibdate,btime,iedate,etime\r\n     *   Loop from 1 to nspec species:\r\n     *     ione,mspec(l),((val(i,j,l),i=1,nx),j=1,ny)\r\n     *\r\n     *\r\n     * ione - Dummy variable = 1\r\n     * nspec - Number of species on file\r\n     * ibdate - Beginning date (YYJJJ)\r\n     * btime - Beginning hour (HHMM)\r\n     * iedate - Ending date (YYJJJ)\r\n     * etime - Ending hour (HHMM)\r\n     * mspec - Species names for nspec species (character*4(10,nspec) array)\r\n     * val - Species l, layer k initial concentrations (ppm for gases, ug/m3 for aerosols)\r\n     *       for nx grid columns and ny grid rows\r\n     *\r\n     */ // CAMx UAM-IV Files are all big endian\r raf . order ( RandomAccessFile . BIG_ENDIAN ) ; // Prepare an array for binary data\r int size = ( int ) v2 . getSize ( ) ; float [ ] arr = new float [ size ] ; // Move to data block of file\r raf . seek ( this . data_start ) ; /*\r\n     * First record is stime,sdate,etime,edate\r\n     * We are skipping the data, but checking\r\n     * the consistency of the Fortran \"unformatted\"\r\n     * data record\r\n    */ int pad1 = raf . readInt ( ) ; raf . skipBytes ( 16 ) ; int pad2 = raf . readInt ( ) ; if ( pad1 != pad2 ) { throw new IOException ( \"Asymmetric fortran buffer values: 1\" ) ; } // Find species name/id associated with this variable\r int spcid = - 1 ; String spc = \"\" ; while ( ! spc . equals ( v2 . getShortName ( ) ) ) { spc = this . species_names [ ++ spcid ] ; } /*\r\n    * Skip data associated with species that are prior\r\n    * in the data block\r\n    */ raf . skipBytes ( this . spc_3D_block * spcid * 4 ) ; // Initialize count for indexing arr\r int count = 0 ; while ( count < size ) { /*\r\n      * Read species name and store the initial record pad.\r\n      * Note: it might be good to compare\r\n      *       spc string to variable.getShortName\r\n      */ if ( count == 0 ) { pad1 = raf . readInt ( ) ; int ione = raf . readInt ( ) ; spc = raf . readString ( 40 ) ; } /*\r\n      * If we have read a 2D slice, read the final record pad\r\n      * and compare to initial record pad.  If everything is okay, proceed.\r\n      * (1) skip to next 2D slice\r\n      * (2) store initial pad\r\n      * (3) read spc name\r\n      * Note: it might be good to compare\r\n      *       spc string to variable.getShortName\r\n      */ if ( ( count != 0 ) && ( ( count % this . n2dvals ) == 0 ) ) { pad2 = raf . readInt ( ) ; if ( pad1 != pad2 ) { //System.out.println(pad1);\r //System.out.println(pad2);\r throw new IOException ( \"Asymmetric fortran buffer values: 2\" ) ; } if ( ( count % this . n3dvals ) == 0 ) { raf . skipBytes ( ( this . data_block - this . spc_3D_block ) * 4 ) ; } pad1 = raf . readInt ( ) ; int ione = raf . readInt ( ) ; spc = raf . readString ( 40 ) ; } /*\r\n      * Attempt to read a Float from the file\r\n      */ try { arr [ count ++ ] = raf . readFloat ( ) ; } catch ( java . lang . ArrayIndexOutOfBoundsException io ) { throw new IOException ( io . getMessage ( ) ) ; } } // Convert java float[] to ma2.Array\r Array data = Array . factory ( DataType . FLOAT , v2 . getShape ( ) , arr ) ; // Subset the data based on the wantSection and return a 4D variable\r return data . sectionNoReduce ( wantSection . getRanges ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find first variable with given attribute name [CODESPLIT] static public VarAtt findVariableWithAttribute ( NetcdfDataset ds , String attName ) { for ( Variable v : ds . getVariables ( ) ) { Attribute att = v . findAttributeIgnoreCase ( attName ) ; if ( att != null ) return new VarAtt ( v , att ) ; } // descend into structures\r for ( Variable v : ds . getVariables ( ) ) { if ( v instanceof Structure ) { Structure s = ( Structure ) v ; for ( Variable vs : s . getVariables ( ) ) { Attribute att = vs . findAttributeIgnoreCase ( attName ) ; if ( att != null ) return new VarAtt ( vs , att ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find first variable with given attribute name and value . If not found search one level into structures . [CODESPLIT] static public Variable findVariableWithAttributeValue ( NetcdfDataset ds , String attName , String attValue ) { for ( Variable v : ds . getVariables ( ) ) { String haveValue = ds . findAttValueIgnoreCase ( v , attName , null ) ; if ( ( haveValue != null ) && haveValue . equals ( attValue ) ) return v ; } // descend into structures\r for ( Variable v : ds . getVariables ( ) ) { if ( v instanceof Structure ) { Variable vn = findVariableWithAttributeValue ( ( Structure ) v , attName , attValue ) ; if ( null != vn ) return vn ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find first variable with given attribute name and value [CODESPLIT] static public String findNameOfVariableWithAttributeValue ( NetcdfDataset ds , String attName , String attValue ) { Variable v = findVariableWithAttributeValue ( ds , attName , attValue ) ; return ( v == null ) ? null : v . getShortName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find first member variable in this struct with given attribute name and value [CODESPLIT] static public Variable findVariableWithAttributeValue ( Structure struct , String attName , String attValue ) { for ( Variable v : struct . getVariables ( ) ) { Attribute att = v . findAttributeIgnoreCase ( attName ) ; if ( ( att != null ) && att . getStringValue ( ) . equals ( attValue ) ) return v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find structure variable of rank 2 with the 2 given dimensions ( or ) Find structure variable of rank 1 with the 1 given dimension [CODESPLIT] static public Structure findStructureWithDimensions ( NetcdfDataset ds , Dimension dim0 , Dimension dim1 ) { for ( Variable v : ds . getVariables ( ) ) { if ( ! ( v instanceof Structure ) ) continue ; if ( dim1 != null && v . getRank ( ) == 2 && v . getDimension ( 0 ) . equals ( dim0 ) && v . getDimension ( 1 ) . equals ( dim1 ) ) return ( Structure ) v ; if ( dim1 == null && v . getRank ( ) == 1 && v . getDimension ( 0 ) . equals ( dim0 ) ) return ( Structure ) v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find first nested structure [CODESPLIT] static public Structure findNestedStructure ( Structure s ) { for ( Variable v : s . getVariables ( ) ) { if ( ( v instanceof Structure ) ) return ( Structure ) v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this dataset have a record structure? netcdf - 3 specific [CODESPLIT] static public boolean hasNetcdf3RecordStructure ( NetcdfDataset ds ) { Variable v = ds . findVariable ( \"record\" ) ; return ( v != null ) && ( v . getDataType ( ) == DataType . STRUCTURE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translate key to value [CODESPLIT] static public String getLiteral ( NetcdfDataset ds , String key , Formatter errlog ) { if ( key . startsWith ( \":\" ) ) { String val = ds . findAttValueIgnoreCase ( null , key . substring ( 1 ) , null ) ; if ( ( val == null ) && ( errlog != null ) ) errlog . format ( \" Cant find global attribute %s%n\" , key ) ; return val ; } return key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turn the key into a String and return the corresponding featureType if any . [CODESPLIT] static public FeatureType getFeatureType ( NetcdfDataset ds , String key , Formatter errlog ) { FeatureType ft = null ; String fts = getLiteral ( ds , key , errlog ) ; if ( fts != null ) { ft = FeatureType . valueOf ( fts . toUpperCase ( ) ) ; if ( ( ft == null ) && ( errlog != null ) ) errlog . format ( \" Cant find Feature type %s from %s%n\" , fts , key ) ; } return ft ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the variable pointed to by key [CODESPLIT] static public String getVariableName ( NetcdfDataset ds , String key , Formatter errlog ) { Variable v = null ; String vs = getLiteral ( ds , key , errlog ) ; if ( vs != null ) { v = ds . findVariable ( vs ) ; if ( ( v == null ) && ( errlog != null ) ) errlog . format ( \" Cant find Variable %s from %s%n\" , vs , key ) ; } return v == null ? null : v . getShortName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the dimension pointed to by key [CODESPLIT] static public Dimension getDimension ( NetcdfDataset ds , String key , Formatter errlog ) { Dimension d = null ; String s = getLiteral ( ds , key , errlog ) ; if ( s != null ) { d = ds . findDimension ( s ) ; // LOOK use group\r if ( ( d == null ) && ( errlog != null ) ) errlog . format ( \" Cant find Variable %s from %s%n\" , s , key ) ; } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the dimension pointed to by key [CODESPLIT] static public String getDimensionName ( NetcdfDataset ds , String key , Formatter errlog ) { Dimension d = getDimension ( ds , key , errlog ) ; return ( d == null ) ? null : d . getShortName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coordinate value at the i j index . [CODESPLIT] public double getCoordValue ( int j , int i ) { if ( coords == null ) doRead ( ) ; return coords . get ( j , i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "larger than you would ever expect [CODESPLIT] static private double connectLon ( double connect , double val ) { if ( Double . isNaN ( connect ) ) return val ; if ( Double . isNaN ( val ) ) return val ; double diff = val - connect ; if ( Math . abs ( diff ) < MAX_JUMP ) return val ; // common case fast\r // we have to add or subtract 360\r double result = diff > 0 ? val - 360 : val + 360 ; double diff2 = connect - result ; if ( ( Math . abs ( diff2 ) ) < Math . abs ( diff ) ) val = result ; return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coordinate values as a 1D double array in canonical order . [CODESPLIT] public double [ ] getCoordValues ( ) { if ( coords == null ) doRead ( ) ; if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis2D.getCoordValues() on non-numeric\" ) ; return ( double [ ] ) coords . get1DJavaArray ( DataType . DOUBLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new CoordinateAxis2D as a section of this CoordinateAxis2D . [CODESPLIT] public CoordinateAxis2D section ( Range r1 , Range r2 ) throws InvalidRangeException { List < Range > section = new ArrayList <> ( ) ; section . add ( r1 ) ; section . add ( r2 ) ; return ( CoordinateAxis2D ) section ( section ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normal case : do something reasonable in deciding on the edges when we have the midpoints of a 2D coordinate . [CODESPLIT] static public ArrayDouble . D2 makeEdges ( ArrayDouble . D2 midpoints ) { int [ ] shape = midpoints . getShape ( ) ; int ny = shape [ 0 ] ; int nx = shape [ 1 ] ; ArrayDouble . D2 edge = new ArrayDouble . D2 ( ny + 1 , nx + 1 ) ; for ( int y = 0 ; y < ny - 1 ; y ++ ) { for ( int x = 0 ; x < nx - 1 ; x ++ ) { // the interior edges are the average of the 4 surrounding midpoints\r double xval = ( midpoints . get ( y , x ) + midpoints . get ( y , x + 1 ) + midpoints . get ( y + 1 , x ) + midpoints . get ( y + 1 , x + 1 ) ) / 4 ; edge . set ( y + 1 , x + 1 , xval ) ; } // extrapolate to exterior points\r edge . set ( y + 1 , 0 , edge . get ( y + 1 , 1 ) - ( edge . get ( y + 1 , 2 ) - edge . get ( y + 1 , 1 ) ) ) ; edge . set ( y + 1 , nx , edge . get ( y + 1 , nx - 1 ) + ( edge . get ( y + 1 , nx - 1 ) - edge . get ( y + 1 , nx - 2 ) ) ) ; } // extrapolate to the first and last row\r for ( int x = 0 ; x < nx + 1 ; x ++ ) { edge . set ( 0 , x , edge . get ( 1 , x ) - ( edge . get ( 2 , x ) - edge . get ( 1 , x ) ) ) ; edge . set ( ny , x , edge . get ( ny - 1 , x ) + ( edge . get ( ny - 1 , x ) - edge . get ( ny - 2 , x ) ) ) ; } return edge ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Experimental : for WRF rotated ( NMM E ) Grids [CODESPLIT] static public ArrayDouble . D2 makeXEdgesRotated ( ArrayDouble . D2 midx ) { int [ ] shape = midx . getShape ( ) ; int ny = shape [ 0 ] ; int nx = shape [ 1 ] ; ArrayDouble . D2 edgex = new ArrayDouble . D2 ( ny + 2 , nx + 1 ) ; // compute the interior rows\r for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 1 ; x < nx ; x ++ ) { double xval = ( midx . get ( y , x - 1 ) + midx . get ( y , x ) ) / 2 ; edgex . set ( y + 1 , x , xval ) ; } edgex . set ( y + 1 , 0 , midx . get ( y , 0 ) - ( edgex . get ( y + 1 , 1 ) - midx . get ( y , 0 ) ) ) ; edgex . set ( y + 1 , nx , midx . get ( y , nx - 1 ) - ( edgex . get ( y + 1 , nx - 1 ) - midx . get ( y , nx - 1 ) ) ) ; } // compute the first row\r for ( int x = 0 ; x < nx ; x ++ ) { edgex . set ( 0 , x , midx . get ( 0 , x ) ) ; } // compute the last row\r for ( int x = 0 ; x < nx - 1 ; x ++ ) { edgex . set ( ny + 1 , x , midx . get ( ny - 1 , x ) ) ; } return edgex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Experimental : for WRF rotated ( NMM E ) Grids [CODESPLIT] static public ArrayDouble . D2 makeYEdgesRotated ( ArrayDouble . D2 midy ) { int [ ] shape = midy . getShape ( ) ; int ny = shape [ 0 ] ; int nx = shape [ 1 ] ; ArrayDouble . D2 edgey = new ArrayDouble . D2 ( ny + 2 , nx + 1 ) ; // compute the interior rows\r for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 1 ; x < nx ; x ++ ) { double yval = ( midy . get ( y , x - 1 ) + midy . get ( y , x ) ) / 2 ; edgey . set ( y + 1 , x , yval ) ; } edgey . set ( y + 1 , 0 , midy . get ( y , 0 ) - ( edgey . get ( y + 1 , 1 ) - midy . get ( y , 0 ) ) ) ; edgey . set ( y + 1 , nx , midy . get ( y , nx - 1 ) - ( edgey . get ( y + 1 , nx - 1 ) - midy . get ( y , nx - 1 ) ) ) ; } // compute the first row\r for ( int x = 0 ; x < nx ; x ++ ) { double pt0 = midy . get ( 0 , x ) ; double pt = edgey . get ( 2 , x ) ; double diff = pt0 - pt ; edgey . set ( 0 , x , pt0 + diff ) ; } // compute the last row\r for ( int x = 0 ; x < nx - 1 ; x ++ ) { double pt0 = midy . get ( ny - 1 , x ) ; double pt = edgey . get ( ny - 1 , x ) ; double diff = pt0 - pt ; edgey . set ( ny + 1 , x , pt0 + diff ) ; } return edgey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bounds calculations [CODESPLIT] private ArrayDouble . D3 makeBoundsFromAux ( ) { if ( ! computeIsInterval ( ) ) return null ; Attribute boundsAtt = findAttributeIgnoreCase ( CF . BOUNDS ) ; if ( boundsAtt == null ) return null ; String boundsVarName = boundsAtt . getStringValue ( ) ; VariableDS boundsVar = ( VariableDS ) ncd . findVariable ( getParentGroup ( ) , boundsVarName ) ; Array data ; try { //boundsVar.setUseNaNs(false); // missing values not allowed\r data = boundsVar . read ( ) ; } catch ( IOException e ) { log . warn ( \"CoordinateAxis2D.makeBoundsFromAux read failed \" , e ) ; return null ; } ArrayDouble . D3 bounds ; assert ( data . getRank ( ) == 3 ) && ( data . getShape ( ) [ 2 ] == 2 ) : \"incorrect shape data for variable \" + boundsVar ; if ( data instanceof ArrayDouble . D3 ) { bounds = ( ArrayDouble . D3 ) data ; } else { bounds = ( ArrayDouble . D3 ) Array . factory ( DataType . DOUBLE , data . getShape ( ) ) ; MAMath . copy ( data , bounds ) ; } return bounds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return index if only one match if no matches return - 1 if > 1 match return - nhits [CODESPLIT] private int findSingleHit ( ArrayDouble . D2 boundsForRun , double target ) { int hits = 0 ; int idxFound = - 1 ; int n = boundsForRun . getShape ( ) [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( contains ( target , boundsForRun . get ( i , 0 ) , boundsForRun . get ( i , 1 ) ) ) { hits ++ ; idxFound = i ; } } if ( hits == 1 ) return idxFound ; if ( hits == 0 ) return - 1 ; return - hits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return index of closest value to target [CODESPLIT] private int findClosest ( ArrayDouble . D2 boundsForRun , double target ) { double minDiff = Double . MAX_VALUE ; int idxFound = - 1 ; int n = boundsForRun . getShape ( ) [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { double midpoint = ( boundsForRun . get ( i , 0 ) + boundsForRun . get ( i , 1 ) ) / 2.0 ; double diff = Math . abs ( midpoint - target ) ; if ( diff < minDiff ) { minDiff = diff ; idxFound = i ; } } return idxFound ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private static void doit2 ( String spec String timePart Formatter errlog ) { CollectionSpecParser specp = new CollectionSpecParser ( spec timePart errlog ) ; System . out . printf ( spec = %s timePart = %s%n%s%n spec timePart specp ) ; String err = errlog . toString () ; if ( err . length () > 0 ) System . out . printf ( %s%n err ) ; System . out . printf ( ----------------------------------- %n ) ; } [CODESPLIT] private static void doit ( String spec , Formatter errlog ) { CollectionSpecParser specp = new CollectionSpecParser ( spec , errlog ) ; System . out . printf ( \"spec= %s%n%s%n\" , spec , specp ) ; String err = errlog . toString ( ) ; if ( err . length ( ) > 0 ) System . out . printf ( \"%s%n\" , err ) ; System . out . printf ( \"-----------------------------------%n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the system of units . This must be called before any call to <code > instance () < / code > . [CODESPLIT] public static synchronized void setInstance ( final UnitSystem instance ) throws UnitSystemException { if ( instance != null ) { throw new UnitSystemException ( \"Unit system already used\" ) ; } UnitSystemManager . instance = instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getName is deprecated because as the code below shows it has no consistent meaning . Sometimes it returns the short name sometimes it returns the full name . [CODESPLIT] @ Deprecated public String getName ( ) { switch ( sort ) { case ATTRIBUTE : case DIMENSION : case ENUMERATION : // for these cases, getName is getShortName return getShortName ( ) ; case VARIABLE : // Atomic case SEQUENCE : case STRUCTURE : case GROUP : // for these cases, getName is getFullName return getFullName ( ) ; default : break ; } return getShortName ( ) ; // default }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NetcdfDataset can end up wrapping a variable in multiple wrapping classes ( e . g . VariableDS ) . Goal of this procedure is to get down to the lowest level Variable instance [CODESPLIT] static public CDMNode unwrap ( CDMNode node ) { if ( ! ( node instanceof Variable ) ) return node ; Variable inner = ( Variable ) node ; for ( ; ; ) { if ( inner instanceof VariableDS ) { VariableDS vds = ( VariableDS ) inner ; inner = vds . getOriginalVariable ( ) ; if ( inner == null ) { inner = vds ; break ; } } else if ( inner instanceof StructureDS ) { StructureDS sds = ( StructureDS ) inner ; inner = sds . getOriginalVariable ( ) ; if ( inner == null ) { inner = sds ; break ; } } else break ; // base case we have straight Variable or Stucture } return inner ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an action to the popup menu . Note that the menuName is made the NAME value of the action . [CODESPLIT] public void addAction ( String menuName , Action act ) { act . putValue ( Action . NAME , menuName ) ; super . add ( act ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an action to the popup menu with an icon . Note that the menuName is made the NAME value of the action . [CODESPLIT] public void addAction ( String menuName , String iconName , Action act ) { addAction ( menuName , BAMutil . getIcon ( iconName , true ) , act ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an action to the popup menu with an icon . Note that the menuName is made the NAME value of the action . [CODESPLIT] public void addAction ( String menuName , ImageIcon icon , Action act ) { act . putValue ( Action . NAME , menuName ) ; act . putValue ( Action . SMALL_ICON , icon ) ; JMenuItem mi = add ( act ) ; mi . setHorizontalTextPosition ( SwingConstants . LEFT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an action to the popup menu using a JCheckBoxMenuItem . Fetch the toggle state using : <pre > Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; < / pre > [CODESPLIT] public void addActionCheckBox ( String menuName , AbstractAction act , boolean state ) { JMenuItem mi = new JCheckBoxMenuItem ( menuName , state ) ; mi . addActionListener ( new BAMutil . ActionToggle ( act , mi ) ) ; act . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; add ( mi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the longest match . [CODESPLIT] public Match match ( String path ) { SortedMap < String , Match > tail = treeMap . tailMap ( path ) ; if ( tail . isEmpty ( ) ) return null ; String after = tail . firstKey ( ) ; //System.out.println(\"  \"+path+\"; after=\"+afterPath);\r if ( path . startsWith ( after ) ) // common case\r return treeMap . get ( after ) ; // have to check more, until no common starting chars\r for ( String key : tail . keySet ( ) ) { if ( path . startsWith ( key ) ) return treeMap . get ( key ) ; // terminate when there's no match at all.\r if ( StringUtil2 . match ( path , key ) == 0 ) break ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the known MetadataType that matches the given name ( ignoring case ) or null if the name is unknown . [CODESPLIT] public static MetadataType findType ( String name ) { if ( name == null ) return null ; for ( MetadataType m : members ) { if ( m . name . equalsIgnoreCase ( name ) ) return m ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a MetadataType that matches the given name by either matching a known type ( ignoring case ) or creating an unknown type . [CODESPLIT] public static MetadataType getType ( String name ) { if ( name == null ) return null ; MetadataType type = findType ( name ) ; return type != null ? type : new MetadataType ( name , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reading [CODESPLIT] public void open ( RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; headerParser = new H5header ( this . raf , ncfile , this ) ; headerParser . read ( null ) ; // check if its an HDF5-EOS file Group eosInfo = ncfile . getRootGroup ( ) . findGroup ( HdfEos . HDF5_GROUP ) ; if ( eosInfo != null && useHdfEos ) { isEos = HdfEos . amendFromODL ( ncfile , eosInfo ) ; } ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all the work is here so can be called recursively [CODESPLIT] private Array readData ( ucar . nc2 . Variable v2 , long dataPos , Section wantSection ) throws IOException , InvalidRangeException { H5header . Vinfo vinfo = ( H5header . Vinfo ) v2 . getSPobject ( ) ; DataType dataType = v2 . getDataType ( ) ; Object data ; Layout layout ; if ( vinfo . useFillValue ) { // fill value only Object pa = IospHelper . makePrimitiveArray ( ( int ) wantSection . computeSize ( ) , dataType , vinfo . getFillValue ( ) ) ; if ( dataType == DataType . CHAR ) pa = IospHelper . convertByteToChar ( ( byte [ ] ) pa ) ; return Array . factory ( dataType , wantSection . getShape ( ) , pa ) ; } if ( vinfo . mfp != null ) { // filtered if ( debugFilter ) System . out . println ( \"read variable filtered \" + v2 . getFullName ( ) + \" vinfo = \" + vinfo ) ; assert vinfo . isChunked ; ByteOrder bo = ( vinfo . typeInfo . endian == 0 ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; layout = new H5tiledLayoutBB ( v2 , wantSection , raf , vinfo . mfp . getFilters ( ) , bo ) ; if ( vinfo . typeInfo . isVString ) { data = readFilteredStringData ( ( LayoutBB ) layout ) ; } else { data = IospHelper . readDataFill ( ( LayoutBB ) layout , v2 . getDataType ( ) , vinfo . getFillValue ( ) ) ; } } else { // normal case if ( debug ) System . out . println ( \"read variable \" + v2 . getFullName ( ) + \" vinfo = \" + vinfo ) ; DataType readDtype = v2 . getDataType ( ) ; int elemSize = v2 . getElementSize ( ) ; Object fillValue = vinfo . getFillValue ( ) ; int endian = vinfo . typeInfo . endian ; // fill in the wantSection wantSection = Section . fill ( wantSection , v2 . getShape ( ) ) ; if ( vinfo . typeInfo . hdfType == 2 ) { // time readDtype = vinfo . mdt . timeType ; elemSize = readDtype . getSize ( ) ; fillValue = N3iosp . getFillValueDefault ( readDtype ) ; } else if ( vinfo . typeInfo . hdfType == 8 ) { // enum H5header . TypeInfo baseInfo = vinfo . typeInfo . base ; readDtype = baseInfo . dataType ; elemSize = readDtype . getSize ( ) ; fillValue = N3iosp . getFillValueDefault ( readDtype ) ; endian = baseInfo . endian ; } else if ( vinfo . typeInfo . hdfType == 9 ) { // vlen elemSize = vinfo . typeInfo . byteSize ; endian = vinfo . typeInfo . endian ; //wantSection = wantSection.removeVlen(); // remove vlen dimension } if ( vinfo . isChunked ) { layout = new H5tiledLayout ( ( H5header . Vinfo ) v2 . getSPobject ( ) , readDtype , wantSection ) ; } else { layout = new LayoutRegular ( dataPos , elemSize , v2 . getShape ( ) , wantSection ) ; } data = readData ( vinfo , v2 , layout , readDtype , wantSection . getShape ( ) , fillValue , endian ) ; } if ( data instanceof Array ) return ( Array ) data ; else if ( dataType == DataType . STRUCTURE ) return convertStructure ( ( Structure ) v2 , layout , wantSection . getShape ( ) , ( byte [ ] ) data ) ; // LOOK else return Array . factory ( dataType , wantSection . getShape ( ) , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Read data subset from file for a variable return Array or java primitive array . [CODESPLIT] private Object readData ( H5header . Vinfo vinfo , Variable v , Layout layout , DataType dataType , int [ ] shape , Object fillValue , int endian ) throws java . io . IOException , InvalidRangeException { H5header . TypeInfo typeInfo = vinfo . typeInfo ; // special processing if ( typeInfo . hdfType == 2 ) { // time Object data = IospHelper . readDataFill ( raf , layout , dataType , fillValue , endian , true ) ; Array timeArray = Array . factory ( dataType , shape , data ) ; // now transform into an ISO Date String String [ ] stringData = new String [ ( int ) timeArray . getSize ( ) ] ; int count = 0 ; while ( timeArray . hasNext ( ) ) { long time = timeArray . nextLong ( ) ; stringData [ count ++ ] = CalendarDate . of ( time ) . toString ( ) ; } return Array . factory ( DataType . STRING , shape , stringData ) ; } if ( typeInfo . hdfType == 8 ) { // enum Object data = IospHelper . readDataFill ( raf , layout , dataType , fillValue , endian ) ; return Array . factory ( dataType , shape , data ) ; } if ( typeInfo . isVlen ) { // vlen (not string) DataType readType = dataType ; if ( typeInfo . base . hdfType == 7 ) // reference readType = DataType . LONG ; // general case is to read an array of vlen objects // each vlen generates an Array - so return ArrayObject of Array // boolean scalar = false; // layout.getTotalNelems() == 1; // if scalar, return just the len Array // remove 12/25/10 jcaron Array [ ] data = new Array [ ( int ) layout . getTotalNelems ( ) ] ; int count = 0 ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) { long address = chunk . getSrcPos ( ) + layout . getElemSize ( ) * i ; Array vlenArray = headerParser . getHeapDataArray ( address , readType , endian ) ; data [ count ++ ] = ( typeInfo . base . hdfType == 7 ) ? convertReference ( vlenArray ) : vlenArray ; } } int prefixrank = 0 ; for ( int i = 0 ; i < shape . length ; i ++ ) { // find leftmost vlen if ( shape [ i ] < 0 ) { prefixrank = i ; break ; } } Array result ; if ( prefixrank == 0 ) // if scalar, return just the singleton vlen array result = data [ 0 ] ; else { int [ ] newshape = new int [ prefixrank ] ; System . arraycopy ( shape , 0 , newshape , 0 , prefixrank ) ; // result = Array.makeObjectArray(readType, data[0].getClass(), newshape, data); result = Array . makeVlenArray ( newshape , data ) ; } /*\n      else if (prefixrank == 1) // LOOK cant these two cases be combines - just differ in shape ??\n        result = Array.makeObjectArray(readType, data[0].getClass(), new int[]{count}, data);\n     else {  // LOOK cant these two cases be combines - just differ in shape ??\n          // Otherwise create and fill in an n-dimensional Array Of Arrays\n          int[] newshape = new int[prefixrank];\n          System.arraycopy(shape, 0, newshape, 0, prefixrank);\n          Array ndimarray = Array.makeObjectArray(readType, Array.class, newshape, null);\n          // Transfer the elements of data into the n-dim arrays\n          IndexIterator iter = ndimarray.getIndexIterator();\n          for(int i = 0;iter.hasNext();i++) {\n              iter.setObjectNext(data[i]);\n          }\n          result = ndimarray;\n      } */ //return (scalar) ? data[0] : new ArrayObject(data[0].getClass(), shape, data); //return new ArrayObject(data[0].getClass(), shape, data); return result ; } if ( dataType == DataType . STRUCTURE ) { // LOOK what about subset ? int recsize = layout . getElemSize ( ) ; long size = recsize * layout . getTotalNelems ( ) ; byte [ ] byteArray = new byte [ ( int ) size ] ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; if ( debugStructure ) System . out . println ( \" readStructure \" + v . getFullName ( ) + \" chunk= \" + chunk + \" index.getElemSize= \" + layout . getElemSize ( ) ) ; // copy bytes directly into the underlying byte[] LOOK : assumes contiguous layout ?? raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFully ( byteArray , ( int ) chunk . getDestElem ( ) * recsize , chunk . getNelems ( ) * recsize ) ; } // place data into an ArrayStructureBB return convertStructure ( ( Structure ) v , layout , shape , byteArray ) ; // LOOK } // normal case return readDataPrimitive ( layout , dataType , shape , fillValue , endian , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recursive [CODESPLIT] private boolean convertStructure ( Structure s , StructureMembers sm ) { boolean hasHeap = false ; for ( StructureMembers . Member m : sm . getMembers ( ) ) { Variable v2 = s . findVariable ( m . getName ( ) ) ; assert v2 != null ; H5header . Vinfo vm = ( H5header . Vinfo ) v2 . getSPobject ( ) ; // apparently each member may have seperate byte order (!!!??) if ( vm . typeInfo . endian >= 0 ) m . setDataObject ( vm . typeInfo . endian == RandomAccessFile . LITTLE_ENDIAN ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; // vm.dataPos : offset since start of Structure m . setDataParam ( ( int ) vm . dataPos ) ; // track if there is a heap if ( v2 . getDataType ( ) == DataType . STRING || v2 . isVariableLength ( ) ) hasHeap = true ; // recurse if ( v2 instanceof Structure ) { Structure nested = ( Structure ) v2 ; StructureMembers nestSm = nested . makeStructureMembers ( ) ; m . setStructureMembers ( nestSm ) ; hasHeap |= convertStructure ( nested , nestSm ) ; } } return hasHeap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public static int setOffsets ( StructureMembers members ) { int offset = 0 ; for ( StructureMembers . Member m : members . getMembers () ) { m . setDataParam ( offset ) ; offset + = m . getSizeBytes () ; [CODESPLIT] void convertHeap ( ArrayStructureBB asbb , int pos , StructureMembers sm ) throws java . io . IOException , InvalidRangeException { ByteBuffer bb = asbb . getByteBuffer ( ) ; for ( StructureMembers . Member m : sm . getMembers ( ) ) { if ( m . getDataType ( ) == DataType . STRING ) { m . setDataObject ( ByteOrder . nativeOrder ( ) ) ; // the index is always written in \"native order\" int size = m . getSize ( ) ; int destPos = pos + m . getDataParam ( ) ; String [ ] result = new String [ size ] ; for ( int i = 0 ; i < size ; i ++ ) result [ i ] = headerParser . readHeapString ( , destPos + i * 16 ) ; // 16 byte \"heap ids\" are in the ByteBuffer int index = asbb . addObjectToHeap ( result ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; // the string index is always written in \"native order\" bb . putInt ( destPos , index ) ; // overwrite with the index into the StringHeap } else if ( m . isVariableLength ( ) ) { int startPos = pos + m . getDataParam ( ) ; bb . order ( ByteOrder . LITTLE_ENDIAN ) ; ByteOrder bo = ( ByteOrder ) m . getDataObject ( ) ; int endian = bo . equals ( ByteOrder . LITTLE_ENDIAN ) ? RandomAccessFile . LITTLE_ENDIAN : RandomAccessFile . BIG_ENDIAN ; // Compute rank and size upto the first (and ideally last) VLEN int [ ] fieldshape = m . getShape ( ) ; int prefixrank = 0 ; int size = 1 ; for ( ; prefixrank < fieldshape . length ; prefixrank ++ ) { if ( fieldshape [ prefixrank ] < 0 ) break ; size *= fieldshape [ prefixrank ] ; } assert size == m . getSize ( ) : \"Internal error: field size mismatch\" ; Array [ ] fieldarray = new Array [ size ] ; // hold all the vlen instance data // destPos will point to each vlen instance in turn // assuming we have 'size' such instances in a row. int destPos = startPos ; for ( int i = 0 ; i < size ; i ++ ) { // vlenarray extracts the i'th vlen contents (struct not supported). Array vlenArray = headerParser . readHeapVlen ( bb , destPos , m . getDataType ( ) , endian ) ; fieldarray [ i ] = vlenArray ; destPos += VLEN_T_SIZE ; // Apparentlly no way to compute VLEN_T_SIZE on the fly } Array result ; if ( prefixrank == 0 ) // if scalar, return just the singleton vlen array result = fieldarray [ 0 ] ; else { int [ ] newshape = new int [ prefixrank ] ; System . arraycopy ( fieldshape , 0 , newshape , 0 , prefixrank ) ; // result = Array.makeObjectArray(m.getDataType(), fieldarray[0].getClass(), newshape, fieldarray); result = Array . makeVlenArray ( newshape , fieldarray ) ; } /* if (prefixrank == 1)\n          result = Array.makeObjectArray(m.getDataType(), fieldarray[0].getClass(), new int[]{size}, fieldarray);\n        else {\n          // Otherwise create and fill in an n-dimensional Array Of Arrays\n          int[] newshape = new int[prefixrank];\n          System.arraycopy(fieldshape, 0, newshape, 0, prefixrank);\n          Array ndimarray = Array.makeObjectArray(m.getDataType(), Array.class, newshape, null);\n          // Transfer the elements of data into the n-dim arrays\n          IndexIterator iter = ndimarray.getIndexIterator();\n          for(int i = 0;iter.hasNext();i++) {\n              iter.setObjectNext(fieldarray[i]);\n          }\n          result = ndimarray;\n        } */ //Array vlenArray = headerParser.readHeapVlen(bb, destPos, m.getDataType(), endian); int index = asbb . addObjectToHeap ( result ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; bb . putInt ( startPos , index ) ; // overwrite with the index into the Heap } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Read data subset from file for a variable create primitive array . [CODESPLIT] Object readDataPrimitive ( Layout layout , DataType dataType , int [ ] shape , Object fillValue , int endian , boolean convertChar ) throws java . io . IOException , InvalidRangeException { if ( dataType == DataType . STRING ) { int size = ( int ) layout . getTotalNelems ( ) ; String [ ] sa = new String [ size ] ; int count = 0 ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) { // 16 byte \"heap ids\" sa [ count ++ ] = headerParser . readHeapString ( chunk . getSrcPos ( ) + layout . getElemSize ( ) * i ) ; } } return sa ; } if ( dataType == DataType . OPAQUE ) { Array opArray = Array . factory ( DataType . OPAQUE , shape ) ; assert ( new Section ( shape ) . computeSize ( ) == layout . getTotalNelems ( ) ) ; int count = 0 ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; int recsize = layout . getElemSize ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) { byte [ ] pa = new byte [ recsize ] ; raf . seek ( chunk . getSrcPos ( ) + i * recsize ) ; raf . readFully ( pa , 0 , recsize ) ; opArray . setObject ( count ++ , ByteBuffer . wrap ( pa ) ) ; } } return opArray ; } // normal case return IospHelper . readDataFill ( raf , layout , dataType , fillValue , endian , convertChar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "old way [CODESPLIT] private StructureData readStructure ( Structure s , ArrayStructureW asw , long dataPos ) throws IOException , InvalidRangeException { StructureDataW sdata = new StructureDataW ( asw . getStructureMembers ( ) ) ; if ( debug ) System . out . println ( \" readStructure \" + s . getFullName ( ) + \" dataPos = \" + dataPos ) ; for ( Variable v2 : s . getVariables ( ) ) { H5header . Vinfo vinfo = ( H5header . Vinfo ) v2 . getSPobject ( ) ; if ( debug ) System . out . println ( \" readStructureMember \" + v2 . getFullName ( ) + \" vinfo = \" + vinfo ) ; Array dataArray = readData ( v2 , dataPos + vinfo . dataPos , v2 . getShapeAsSection ( ) ) ; sdata . setMemberData ( v2 . getShortName ( ) , dataArray ) ; } return sdata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a NetcdfDataset out of this NetcdfFile adding coordinates etc . [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { if ( null != ds . findVariable ( \"x\" ) ) return ; // check if its already been done - aggregating enhanced datasets.\r // old way\r Attribute att = ds . findGlobalAttribute ( \"MAPPROJ\" ) ; int projType = att . getNumericValue ( ) . intValue ( ) ; double lat1 = findAttributeDouble ( ds , \"TRUELAT1\" , Double . NaN ) ; double lat2 = findAttributeDouble ( ds , \"TRUELAT2\" , Double . NaN ) ; double lat_origin = lat1 ; double lon_origin = findAttributeDouble ( ds , \"TRUELON\" , Double . NaN ) ; double false_easting = 0.0 ; double false_northing = 0.0 ; // new way\r String projName = ds . findAttValueIgnoreCase ( null , CF . GRID_MAPPING_NAME , null ) ; if ( projName != null ) { projName = projName . trim ( ) ; lat_origin = findAttributeDouble ( ds , \"latitude_of_projection_origin\" , Double . NaN ) ; lon_origin = findAttributeDouble ( ds , \"longitude_of_central_meridian\" , Double . NaN ) ; false_easting = findAttributeDouble ( ds , \"false_easting\" , 0.0 ) ; false_northing = findAttributeDouble ( ds , \"false_northing\" , 0.0 ) ; Attribute att2 = ds . findGlobalAttributeIgnoreCase ( \"standard_parallel\" ) ; if ( att2 != null ) { lat1 = att2 . getNumericValue ( ) . doubleValue ( ) ; lat2 = ( att2 . getLength ( ) > 1 ) ? att2 . getNumericValue ( 1 ) . doubleValue ( ) : lat1 ; } } else { if ( projType == 2 ) projName = \"lambert_conformal_conic\" ; } Variable coord_var = ds . findVariable ( \"x_stag\" ) ; if ( ! Double . isNaN ( false_easting ) || ! Double . isNaN ( false_northing ) ) { String units = ds . findAttValueIgnoreCase ( coord_var , CDM . UNITS , null ) ; double scalef = 1.0 ; try { scalef = SimpleUnit . getConversionFactor ( units , \"km\" ) ; } catch ( IllegalArgumentException e ) { log . error ( units + \" not convertible to km\" ) ; } false_easting *= scalef ; false_northing *= scalef ; } ProjectionImpl proj ; if ( ( projName != null ) && projName . equalsIgnoreCase ( \"lambert_conformal_conic\" ) ) { proj = new LambertConformal ( lat_origin , lon_origin , lat1 , lat2 , false_easting , false_northing ) ; projCT = new ProjectionCT ( \"Projection\" , \"FGDC\" , proj ) ; if ( false_easting == 0.0 ) calcCenterPoints ( ds , proj ) ; // old way\r } else { parseInfo . format ( \"ERROR: unknown projection type = %s%n\" , projName ) ; } if ( debugProj && ( proj != null ) ) { System . out . println ( \" using LC \" + proj . paramsToString ( ) ) ; double lat_check = findAttributeDouble ( ds , \"CTRLAT\" , Double . NaN ) ; double lon_check = findAttributeDouble ( ds , \"CTRLON\" , Double . NaN ) ; LatLonPointImpl lpt0 = new LatLonPointImpl ( lat_check , lon_check ) ; ProjectionPoint ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( \"CTR lpt0= \" + lpt0 + \" ppt0=\" + ppt0 ) ; Variable xstag = ds . findVariable ( \"x_stag\" ) ; ArrayFloat . D1 xstagData = ( ArrayFloat . D1 ) xstag . read ( ) ; float center_x = xstagData . get ( ( int ) xstag . getSize ( ) - 1 ) ; Variable ystag = ds . findVariable ( \"y_stag\" ) ; ArrayFloat . D1 ystagData = ( ArrayFloat . D1 ) ystag . read ( ) ; float center_y = ystagData . get ( ( int ) ystag . getSize ( ) - 1 ) ; System . out . println ( \"CTR should be x,y= \" + center_x / 2000 + \", \" + center_y / 2000 ) ; lpt0 = new LatLonPointImpl ( lat_origin , lon_origin ) ; ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( \"ORIGIN lpt0= \" + lpt0 + \" ppt0=\" + ppt0 ) ; lpt0 = new LatLonPointImpl ( lat_origin , lon_origin ) ; ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( \"TRUE ORIGIN lpt0= \" + lpt0 + \" ppt0=\" + ppt0 ) ; } if ( projCT != null ) { VariableDS v = makeCoordinateTransformVariable ( ds , projCT ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisTypes , \"GeoX GeoY\" ) ) ; ds . addVariable ( null , v ) ; } if ( ds . findVariable ( \"x_stag\" ) != null ) ds . addCoordinateAxis ( makeCoordAxis ( ds , \"x\" ) ) ; if ( ds . findVariable ( \"y_stag\" ) != null ) ds . addCoordinateAxis ( makeCoordAxis ( ds , \"y\" ) ) ; if ( ds . findVariable ( \"z_stag\" ) != null ) ds . addCoordinateAxis ( makeCoordAxis ( ds , \"z\" ) ) ; Variable zsoil = ds . findVariable ( \"ZPSOIL\" ) ; if ( zsoil != null ) zsoil . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . GeoZ . toString ( ) ) ) ; ds . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "old [CODESPLIT] private void calcCenterPoints ( NetcdfDataset ds , Projection proj ) throws IOException { double lat_check = findAttributeDouble ( ds , \"CTRLAT\" , Double . NaN ) ; double lon_check = findAttributeDouble ( ds , \"CTRLON\" , Double . NaN ) ; LatLonPointImpl lpt0 = new LatLonPointImpl ( lat_check , lon_check ) ; ProjectionPoint ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( \"CTR lpt0= \" + lpt0 + \" ppt0=\" + ppt0 ) ; Variable xstag = ds . findVariable ( \"x_stag\" ) ; int nxpts = ( int ) xstag . getSize ( ) ; ArrayFloat . D1 xstagData = ( ArrayFloat . D1 ) xstag . read ( ) ; float center_x = xstagData . get ( nxpts - 1 ) ; double false_easting = center_x / 2000 - ppt0 . getX ( ) * 1000.0 ; System . out . println ( \"false_easting= \" + false_easting ) ; Variable ystag = ds . findVariable ( \"y_stag\" ) ; int nypts = ( int ) ystag . getSize ( ) ; ArrayFloat . D1 ystagData = ( ArrayFloat . D1 ) ystag . read ( ) ; float center_y = ystagData . get ( nypts - 1 ) ; double false_northing = center_y / 2000 - ppt0 . getY ( ) * 1000.0 ; System . out . println ( \"false_northing= \" + false_northing ) ; double dx = findAttributeDouble ( ds , \"DX\" , Double . NaN ) ; double dy = findAttributeDouble ( ds , \"DY\" , Double . NaN ) ; double w = dx * ( nxpts - 1 ) ; double h = dy * ( nypts - 1 ) ; double startx = ppt0 . getX ( ) * 1000.0 - w / 2 ; double starty = ppt0 . getY ( ) * 1000.0 - h / 2 ; xstag . setValues ( nxpts , startx , dx ) ; ystag . setValues ( nypts , starty , dy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private CoordinateAxis makeCoordAxis ( NetcdfDataset ds , String axisName ) throws IOException { Variable stagV = ds . findVariable ( axisName + \"_stag\" ) ; Array data_stag = stagV . read ( ) ; int n = ( int ) data_stag . getSize ( ) - 1 ; DataType dt = DataType . getType ( data_stag ) ; Array data = Array . factory ( dt , new int [ ] { n } ) ; Index stagIndex = data_stag . getIndex ( ) ; Index dataIndex = data . getIndex ( ) ; for ( int i = 0 ; i < n ; i ++ ) { double val = data_stag . getDouble ( stagIndex . set ( i ) ) + data_stag . getDouble ( stagIndex . set ( i + 1 ) ) ; data . setDouble ( dataIndex . set ( i ) , 0.5 * val ) ; } DataType dtype = DataType . getType ( data ) ; String units = ds . findAttValueIgnoreCase ( stagV , CDM . UNITS , \"m\" ) ; CoordinateAxis v = new CoordinateAxis1D ( ds , null , axisName , dtype , axisName , units , \"synthesized non-staggered \" + axisName + \" coordinate\" ) ; v . setCachedData ( data , true ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort specific [CODESPLIT] public void addSegment ( CEAST segment ) { assert sort == Sort . SEGMENT ; if ( subnodes == null ) subnodes = new NodeList ( ) ; subnodes . add ( segment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "testing 1 - 2 - 3 [CODESPLIT] public static void main ( String [ ] args ) { ProjectionManager d = new ProjectionManager ( null , null ) ; d . setVisible ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first occurrence of match in data . [CODESPLIT] public int indexOf ( byte [ ] data , int start , int max ) { int j = 0 ; if ( data . length == 0 ) return - 1 ; if ( start + max > data . length ) System . out . println ( \"HEY KMPMatch\" ) ; for ( int i = start ; i < start + max ; i ++ ) { while ( j > 0 && match [ j ] != data [ i ] ) j = failure [ j - 1 ] ; if ( match [ j ] == data [ i ] ) j ++ ; if ( j == match . length ) return i - match . length + 1 ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Finds the first occurrence of match in data . @param data search in this byte block @param start start at data [ start ] @param max end at data [ start + max ] @return index into block of first match else - 1 if not found . [CODESPLIT] private int [ ] computeFailure ( byte [ ] match ) { int [ ] result = new int [ match . length ] ; int j = 0 ; for ( int i = 1 ; i < match . length ; i ++ ) { while ( j > 0 && match [ j ] != match [ i ] ) j = result [ j - 1 ] ; if ( match [ j ] == match [ i ] ) j ++ ; result [ i ] = j ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////// [CODESPLIT] public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { String convention = ncd . findAttValueIgnoreCase ( null , \"Conventions\" , null ) ; if ( ( null != convention ) && convention . equals ( _Coordinate . Convention ) ) { String format = ncd . findAttValueIgnoreCase ( null , \"Format\" , null ) ; if ( format != null && format . equals ( \"Level3/NIDS\" ) ) return this ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method removes the least popular picture ( s ) in the cache . It first removes those pictures which have been suggested for removal . And then it picks any it can find As many pictures are removed as nescessary untill there are less pictures in the cache than the Settings . maxCache specifies . ( If maxCache is 0 then the Enumeration finds no elements and we don t get an endless loop . [CODESPLIT] public static synchronized void removeLeastPopular ( ) { Tools . log ( \"PictureCache.removeLeastPopular:\" ) ; //reportCache(); Enumeration e = removalQueue . elements ( ) ; while ( ( e . hasMoreElements ( ) ) && ( pictureCache . size ( ) >= maxCache ) ) { String removeElement = ( String ) e . nextElement ( ) ; Tools . log ( \"PictureCache.remove: \" + removeElement ) ; pictureCache . remove ( removeElement ) ; removalQueue . remove ( removeElement ) ; } e = pictureCache . keys ( ) ; while ( ( pictureCache . size ( ) >= maxCache ) && ( e . hasMoreElements ( ) ) ) { String removeElement = ( String ) e . nextElement ( ) ; Tools . log ( \"PictureCache.remove: \" + removeElement ) ; pictureCache . remove ( removeElement ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "store an image in the cache [CODESPLIT] public static synchronized void add ( URL url , SourcePicture sp ) { Tools . log ( \"PictureCache.add: \" + url . toString ( ) ) ; if ( sp . getSourceBufferedImage ( ) == null ) { Tools . log ( \"PictureCache.add: invoked with a null picture! Not cached!\" ) ; return ; } if ( ( maxCache < 1 ) ) { Tools . log ( \"PictureCache.add: cache is diabled. Not adding picture.\" ) ; return ; } if ( isInCache ( url ) ) { Tools . log ( \"Picture \" + url . toString ( ) + \" is already in the cache. Not adding again.\" ) ; return ; } if ( pictureCache . size ( ) >= maxCache ) removeLeastPopular ( ) ; if ( pictureCache . size ( ) < maxCache ) pictureCache . put ( url . toString ( ) , sp ) ; //reportCache();\t }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to inspect the cache [CODESPLIT] public static synchronized void reportCache ( ) { Tools . log ( \"   PictureCache.reportCache: cache contains: \" + Integer . toString ( pictureCache . size ( ) ) + \" max: \" + Integer . toString ( maxCache ) ) ; //Tools.freeMem(); Enumeration e = pictureCache . keys ( ) ; while ( e . hasMoreElements ( ) ) { Tools . log ( \"   Cache contains: \" + ( ( String ) e . nextElement ( ) ) ) ; } Tools . log ( \"  End of cache contents\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to stop all background loading [CODESPLIT] public static void stopBackgroundLoading ( ) { Enumeration e = cacheLoadsInProgress . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( SourcePicture ) e . nextElement ( ) ) . stopLoading ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to stop all background loading except the indicated file . Returns whether the image is already being loaded . True = loading in progress False = not in progress . [CODESPLIT] public static boolean stopBackgroundLoadingExcept ( URL exemptionURL ) { SourcePicture sp ; String exemptionURLString = exemptionURL . toString ( ) ; Enumeration e = cacheLoadsInProgress . elements ( ) ; boolean inProgress = false ; while ( e . hasMoreElements ( ) ) { sp = ( ( SourcePicture ) e . nextElement ( ) ) ; if ( ! sp . getUrlString ( ) . equals ( exemptionURLString ) ) sp . stopLoading ( ) ; else { Tools . log ( \"PictureCache.stopBackgroundLoading: picture was already loading\" ) ; inProgress = true ; } } return inProgress ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "listeners will receive columnAdded () / columnRemoved () event [CODESPLIT] public void setColumnVisible ( TableColumn column , boolean visible ) { if ( isColumnVisible ( column ) == visible ) { return ; // Visibility status did not change. } if ( ! visible ) { super . removeColumn ( column ) ; } else { // find the visible index of the column: // iterate through both collections of visible and all columns, counting // visible columns up to the one that's about to be shown again int noVisibleColumns = tableColumns . size ( ) ; int noInvisibleColumns = allTableColumns . size ( ) ; int visibleIndex = 0 ; for ( int invisibleIndex = 0 ; invisibleIndex < noInvisibleColumns ; ++ invisibleIndex ) { TableColumn visibleColumn = ( visibleIndex < noVisibleColumns ? tableColumns . get ( visibleIndex ) : null ) ; TableColumn testColumn = allTableColumns . get ( invisibleIndex ) ; if ( testColumn == column ) { if ( visibleColumn != column ) { super . addColumn ( column ) ; super . moveColumn ( tableColumns . size ( ) - 1 , visibleIndex ) ; } return ; // #################### } if ( testColumn == visibleColumn ) { ++ visibleIndex ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes <code > column< / code > from this column model . Posts <code > columnRemoved< / code > event . Will do nothing if the column is not in this model . [CODESPLIT] @ Override public void removeColumn ( TableColumn column ) { int allColumnsIndex = allTableColumns . indexOf ( column ) ; if ( allColumnsIndex != - 1 ) { allTableColumns . removeElementAt ( allColumnsIndex ) ; } super . removeColumn ( column ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves the column from <code > oldIndex< / code > to <code > newIndex< / code > . Posts <code > columnMoved< / code > event . Will not move any columns if <code > oldIndex< / code > equals <code > newIndex< / code > . [CODESPLIT] @ Override public void moveColumn ( int oldIndex , int newIndex ) { if ( ( oldIndex < 0 ) || ( oldIndex >= getColumnCount ( ) ) || ( newIndex < 0 ) || ( newIndex >= getColumnCount ( ) ) ) throw new IllegalArgumentException ( \"moveColumn() - Index out of range\" ) ; TableColumn fromColumn = tableColumns . get ( oldIndex ) ; TableColumn toColumn = tableColumns . get ( newIndex ) ; int allColumnsOldIndex = allTableColumns . indexOf ( fromColumn ) ; int allColumnsNewIndex = allTableColumns . indexOf ( toColumn ) ; if ( oldIndex != newIndex ) { allTableColumns . removeElementAt ( allColumnsOldIndex ) ; allTableColumns . insertElementAt ( fromColumn , allColumnsNewIndex ) ; } super . moveColumn ( oldIndex , newIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > of all the columns in the model . [CODESPLIT] public Enumeration < TableColumn > getColumns ( boolean onlyVisible ) { Vector columns = ( onlyVisible ? tableColumns : allTableColumns ) ; return columns . elements ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > TableColumn< / code > object for the column at <code > columnIndex< / code > . [CODESPLIT] public TableColumn getColumn ( int columnIndex , boolean onlyVisible ) { if ( onlyVisible ) { return tableColumns . elementAt ( columnIndex ) ; } else { return allTableColumns . elementAt ( columnIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapted from JTable . createDefaultColumnsFromModel () . [CODESPLIT] public void createColumnsFromModel ( TableModel newModel ) { if ( newModel != model ) { if ( model != null ) { model . removeTableModelListener ( this ) ; // Stop listening to old model. } newModel . addTableModelListener ( this ) ; // Start listening to new one. model = newModel ; } // Removes all current columns including the hidden ones. // For visible columns that are removed, TableColumnModelEvents get fired. while ( ! allTableColumns . isEmpty ( ) ) { removeColumn ( allTableColumns . elementAt ( 0 ) ) ; } // Create new columns from the data model info for ( int modelColumnIndex = 0 ; modelColumnIndex < newModel . getColumnCount ( ) ; modelColumnIndex ++ ) { TableColumn newColumn = new TableColumn ( modelColumnIndex ) ; String columnName = newModel . getColumnName ( modelColumnIndex ) ; newColumn . setHeaderValue ( columnName ) ; addColumn ( newColumn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static factory methods for creating HTTPMethod instances [CODESPLIT] static public HTTPMethod Get ( HTTPSession session , String legalurl ) throws HTTPException { return makemethod ( HTTPSession . Methods . Get , session , legalurl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Common method creation code so we can isolate mocking [CODESPLIT] static protected HTTPMethod makemethod ( HTTPSession . Methods m , HTTPSession session , String url ) throws HTTPException { HTTPMethod meth = null ; if ( MOCKMETHODCLASS == null ) { // do the normal case meth = new HTTPMethod ( m , session , url ) ; } else { //(MOCKMETHODCLASS != null) java . lang . Class methodcl = MOCKMETHODCLASS ; Constructor < HTTPMethod > cons = null ; try { cons = methodcl . getConstructor ( HTTPSession . Methods . class , HTTPSession . class , String . class ) ; } catch ( Exception e ) { throw new HTTPException ( \"HTTPFactory: no proper HTTPMethod constructor available\" , e ) ; } try { meth = cons . newInstance ( m , session , url ) ; } catch ( Exception e ) { throw new HTTPException ( \"HTTPFactory: HTTPMethod constructor failed\" , e ) ; } } return meth ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public void deflate ( Formatter f , Variable v ) throws IOException { H5header . Vinfo vinfo = ( H5header . Vinfo ) v . getSPobject ( ) ; DataBTree btree = vinfo . btree ; if ( btree == null || vinfo . useFillValue ) { f . format ( \"%s not chunked%n\" , v . getShortName ( ) ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * extend Variable { repeated PartitionVariable partition = 100 ; repeated Parameter vparams = 101 ; // not used yet } [CODESPLIT] @ Override protected GribCollectionMutable . VariableIndex readVariableExtensions ( GribCollectionMutable . GroupGC group , GribCollectionProto . Variable proto , GribCollectionMutable . VariableIndex vi ) { List < GribCollectionProto . PartitionVariable > pvList = proto . getPartVariableList ( ) ; PartitionCollectionMutable . VariableIndexPartitioned vip = pc . makeVariableIndexPartitioned ( group , vi , pvList . size ( ) ) ; vip . setPartitions ( pvList ) ; // cant put this in the constructor vip . ndups = vi . ndups ; vip . nrecords = vi . nrecords ; vip . nmissing = vi . nmissing ; return vip ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Partition { required string name = 1 ; // name is used in TDS - eg the subdirectory when generated by TimePartitionCollections required string filename = 2 ; // the gribCollection . ncx2 file required string directory = 3 ; // top directory optional uint64 lastModified = 4 ; } [CODESPLIT] private PartitionCollectionMutable . Partition makePartition ( GribCollectionProto . Partition proto ) { long partitionDateMillisecs = proto . getPartitionDate ( ) ; CalendarDate partitionDate = partitionDateMillisecs > 0 ? CalendarDate . of ( partitionDateMillisecs ) : null ; return pc . addPartition ( proto . getName ( ) , proto . getFilename ( ) , proto . getLastModified ( ) , proto . getLength ( ) , null , partitionDate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return an integer type value ( including long but not floats ) [CODESPLIT] public Object nextInteger ( DapType basetype ) throws DapException { TypeSort atomtype = basetype . getTypeSort ( ) ; if ( ! atomtype . isIntegerType ( ) ) throw new DapException ( \"Unexpected type: \" + basetype ) ; boolean unsigned = atomtype . isUnsigned ( ) ; switch ( atomtype ) { case Int8 : return new byte [ ] { ( byte ) ( random . nextInt ( 1 << 8 ) - ( 1 << 7 ) ) } ; case UInt8 : return new byte [ ] { ( byte ) ( random . nextInt ( 1 << 8 ) & 0xFF ) } ; case Int16 : return new short [ ] { ( short ) ( random . nextInt ( 1 << 16 ) - ( 1 << 15 ) ) } ; case UInt16 : return new short [ ] { ( short ) ( random . nextInt ( 1 << 16 ) ) } ; case Int32 : return new int [ ] { random . nextInt ( ) } ; case UInt32 : long l = random . nextLong ( ) ; l = l & 0xFFFFFFFF ; return new int [ ] { ( int ) l } ; case Int64 : return new long [ ] { random . nextLong ( ) } ; case UInt64 : return new long [ ] { new BigInteger ( 64 , random ) . longValue ( ) } ; } throw new DapException ( \"Unexpected type: \" + basetype ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return a float type value [CODESPLIT] public Object nextFloat ( DapType basetype ) throws DapException { TypeSort atomtype = basetype . getTypeSort ( ) ; switch ( atomtype ) { case Float32 : return new float [ ] { random . nextFloat ( ) } ; case Float64 : return new double [ ] { random . nextDouble ( ) } ; default : break ; } throw new DapException ( \"Unexpected type: \" + basetype ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an integer in range 1 .. max inclusive . [CODESPLIT] public int nextCount ( int max ) throws DapException { int min = 1 ; if ( max < min || min < 1 ) throw new DapException ( \"bad range\" ) ; int range = ( max + 1 ) - min ; // min..max+1 -> 0..(max+1)-min int n = random . nextInt ( range ) ; //  0..(max+1)-min n = n + min ; // min..(max+1) if ( DEBUG ) System . err . println ( \"RandomValue.nextCount: \" + n ) ; return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close all resources ( files sockets etc ) associated with this file . [CODESPLIT] @ Override public synchronized void close ( ) throws java . io . IOException { if ( closed ) return ; closed = true ; // avoid circular calls dsp = null ; // nodemap = null;  unused? }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do a bulk read on a list of Variables and return a corresponding list of Array that contains the results of a full read on each Variable . TODO : optimize to make only a single server call and cache the results . [CODESPLIT] @ Override public List < Array > readArrays ( List < Variable > variables ) throws IOException { List < Array > result = new ArrayList < Array > ( ) ; for ( Variable variable : variables ) { result . add ( variable . read ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Primary read entry point . This is the primary implementor of Variable . read . [CODESPLIT] @ Override protected Array readData ( Variable cdmvar , Section section ) throws IOException , InvalidRangeException { // The section is applied wrt to the DataDMR, so it // takes into account any constraint used in forming the dataDMR. // We use the Section to produce a view of the underlying variable array. assert this . dsp != null ; Array result = arraymap . get ( cdmvar ) ; if ( result == null ) throw new IOException ( \"No data for variable: \" + cdmvar . getFullName ( ) ) ; if ( section != null ) { if ( cdmvar . getRank ( ) != section . getRank ( ) ) throw new InvalidRangeException ( String . format ( \"Section rank != %s rank\" , cdmvar . getFullName ( ) ) ) ; List < Range > ranges = section . getRanges ( ) ; // Case out the possibilities if ( CDMUtil . hasVLEN ( ranges ) ) { ranges = ranges . subList ( 0 , ranges . size ( ) - 1 ) ; // may produce empty list } if ( ranges . size ( ) > 0 && ! CDMUtil . isWhole ( ranges , cdmvar ) ) result = result . sectionNoReduce ( ranges ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException { val = source . readInt ( ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "filesystem can t be re - created either . [CODESPLIT] private static FileSystemProvider getProvider ( URI uri ) throws IOException { if ( fsproviders . containsKey ( uri . getScheme ( ) ) ) { return fsproviders . get ( uri . getScheme ( ) ) ; } else { FileSystem fs ; try { fs = FileSystems . newFileSystem ( uri , new HashMap < String , Object > ( ) , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } catch ( FileSystemAlreadyExistsException e ) { fs = FileSystems . getFileSystem ( uri ) ; } fsproviders . put ( uri . getScheme ( ) , fs . provider ( ) ) ; return fs . provider ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is the old Gempak table not as precise [CODESPLIT] private static void readStationTable ( ) throws IOException { stationTableHash = new HashMap < String , Station > ( ) ; ClassLoader cl = Level2VolumeScan . class . getClassLoader ( ) ; InputStream is = cl . getResourceAsStream ( \"resources/nj22/tables/nexrad.tbl\" ) ; List < TableParser . Record > recs = TableParser . readTable ( is , \"3,15,46, 54,60d,67d,73d\" , 50000 ) ; for ( TableParser . Record record : recs ) { Station s = new Station ( ) ; s . id = \"K\" + record . get ( 0 ) ; s . name = record . get ( 2 ) + \" \" + record . get ( 3 ) ; s . lat = ( Double ) record . get ( 4 ) * .01 ; s . lon = ( Double ) record . get ( 5 ) * .01 ; s . elev = ( Double ) record . get ( 6 ) ; stationTableHash . put ( s . id , s ) ; if ( showStations ) System . out . println ( \" station= \" + s ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////// [CODESPLIT] static private int parseLine ( String line ) throws IOException { int balony = 0 ; Matcher matcher = dataPattern . matcher ( line ) ; if ( matcher . matches ( ) ) { for ( int i = 1 ; i <= matcher . groupCount ( ) ; i ++ ) { String r = matcher . group ( i ) ; if ( r == null ) continue ; int value = ( int ) Long . parseLong ( r . trim ( ) ) ; balony += value ; } } else { System . out . printf ( \"Fail on %s%n\" , line ) ; } return balony ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] static private NetcdfFile open ( String filename ) throws IOException { Ghcnm iosp = new Ghcnm ( ) ; RandomAccessFile raf = new RandomAccessFile ( filename , \"r\" ) ; NetcdfFile ncfile = new NetcdfFileSubclass ( iosp , filename ) ; iosp . open ( raf , ncfile , null ) ; return ncfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { ArrayDouble . D3 data = original . getCoordinateArray ( timeIndex ) ; int [ ] origin = new int [ 3 ] ; int [ ] shape = new int [ 3 ] ; shape [ 0 ] = subsetList . get ( 0 ) . length ( ) ; shape [ 1 ] = 1 ; shape [ 2 ] = 1 ; origin [ 0 ] = timeIndex ; if ( isTimeDependent ( ) && ( t_range != null ) ) { origin [ 0 ] = t_range . element ( timeIndex ) ; } origin [ 1 ] = yIndex ; origin [ 2 ] = xIndex ; Array section = data . section ( origin , shape ) ; return ( ArrayDouble . D1 ) section . reduce ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by CoordinateND . makeSparseArray ; not used by CoordinateTime2D [CODESPLIT] @ Override public int getIndex ( T gr ) { Integer result = valMap . get ( extract ( gr ) ) ; return ( result == null ) ? 0 : result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////// [CODESPLIT] public static void main ( String args [ ] ) throws HTTPException { // prefs storage\r try { String prefStore = ucar . util . prefs . XMLStore . makeStandardFilename ( \".unidata\" , \"TdsMonitor.xml\" ) ; store = ucar . util . prefs . XMLStore . createFromFile ( prefStore , null ) ; prefs = store . getPreferences ( ) ; Debug . setStore ( prefs . node ( \"Debug\" ) ) ; } catch ( IOException e ) { System . out . println ( \"XMLStore Creation failed \" + e ) ; } // initializations\r BAMutil . setResourcePath ( \"/resources/nj22/ui/icons/\" ) ; // put UI in a JFrame\r frame = new JFrame ( \"TDS Monitor\" ) ; ui = new TdsMonitor ( prefs , frame ) ; frame . setIconImage ( BAMutil . getImage ( \"netcdfUI\" ) ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { if ( ! done ) ui . exit ( ) ; } } ) ; frame . getContentPane ( ) . add ( ui ) ; Rectangle bounds = ( Rectangle ) prefs . getBean ( FRAME_SIZE , new Rectangle ( 50 , 50 , 800 , 450 ) ) ; frame . setBounds ( bounds ) ; frame . pack ( ) ; frame . setBounds ( bounds ) ; frame . setVisible ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reminder for subclasses to set this [CODESPLIT] protected void removeDataVariable ( String varName ) { Iterator iter = dataVariables . iterator ( ) ; while ( iter . hasNext ( ) ) { VariableSimpleIF v = ( VariableSimpleIF ) iter . next ( ) ; if ( v . getShortName ( ) . equals ( varName ) ) iter . remove ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert cloud height to meters [CODESPLIT] private String cloud_hgt2_meters ( String height ) { if ( height . equals ( \"999\" ) ) { return \"30000\" ; } else { //\t\t$meters = 30 * $height ; return Integer . toString ( 30 * Integer . parseInt ( height ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Class FXY enElementName BUFR_Unit BUFR_Scale BUFR_ReferenceValue BUFR_DataWidth_Bits CREX_Unit CREX_Scale CREX_DataWidth 20 20009 General weather indicator ( TAF / METAR ) Code table 0 0 4 Code table 0 2 [CODESPLIT] private void writeDiff ( TableB wmo , TableB t , Formatter out ) { out . format ( \"#%n# BUFR diff written from %s against %s %n#%n\" , t . getName ( ) , wmo . getName ( ) ) ; out . format ( \"Class,FXY,enElementName,BUFR_Unit,BUFR_Scale,BUFR_ReferenceValue,BUFR_DataWidth_Bits%n\" ) ; List < TableB . Descriptor > listDesc = new ArrayList <> ( t . getDescriptors ( ) ) ; Collections . sort ( listDesc ) ; for ( TableB . Descriptor d1 : listDesc ) { TableB . Descriptor d2 = wmo . getDescriptor ( d1 . getId ( ) ) ; if ( ( d2 == null ) || ( d1 . getScale ( ) != d2 . getScale ( ) ) || ( d1 . getRefVal ( ) != d2 . getRefVal ( ) ) || ( d1 . getDataWidth ( ) != d2 . getDataWidth ( ) ) ) { short fxy = d1 . getId ( ) ; //        int f = (fxy & 0xC000) >> 14;\r int x = ( fxy & 0x3F00 ) >> 8 ; int y = fxy & 0xFF ; out . format ( \"%d,%2d%03d,\\\"%s\\\",%s,%d,%d,%d%n\" , x , x , y , d1 . getName ( ) , d1 . getUnits ( ) , d1 . getScale ( ) , d1 . getRefVal ( ) , d1 . getDataWidth ( ) ) ; } } out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "here is where agg variables get read [CODESPLIT] @ Override public Array reallyRead ( Variable mainv , Section section , CancelTask cancelTask ) throws IOException , InvalidRangeException { FmrcInvLite . Gridset . Grid gridLite = ( FmrcInvLite . Gridset . Grid ) mainv . getSPobject ( ) ; // read the original type - if its been promoted to a new type, the conversion happens after this read\r DataType dtype = ( mainv instanceof VariableDS ) ? ( ( VariableDS ) mainv ) . getOriginalDataType ( ) : mainv . getDataType ( ) ; Array allData = Array . factory ( dtype , section . getShape ( ) ) ; int destPos = 0 ; // assumes the first two dimensions are runtime and time: LOOK: ensemble ??\r List < Range > ranges = section . getRanges ( ) ; Range runRange = ranges . get ( 0 ) ; Range timeRange = ranges . get ( 1 ) ; List < Range > innerSection = ranges . subList ( 2 , ranges . size ( ) ) ; // keep track of open file - must be local variable for thread safety\r HashMap < String , NetcdfDataset > openFilesRead = new HashMap <> ( ) ; try { // iterate over the desired runs\r for ( int runIdx : runRange ) { //Date runDate = vstate.runTimes.get(runIdx);\r // iterate over the desired forecast times\r for ( int timeIdx : timeRange ) { Array result = null ; // find the inventory for this grid, runtime, and hour\r TimeInventory . Instance timeInv = gridLite . getInstance ( runIdx , timeIdx ) ; if ( timeInv != null ) { if ( debugRead ) System . out . printf ( \"HIT %d %d \" , runIdx , timeIdx ) ; result = read ( timeInv , gridLite . name , innerSection , openFilesRead ) ; // may return null\r result = MAMath . convert ( result , dtype ) ; // just in case it need to be converted\r } // missing data\r if ( result == null ) { int [ ] shape = new Section ( innerSection ) . getShape ( ) ; result = ( ( VariableDS ) mainv ) . getMissingDataArray ( shape ) ; // fill with missing values\r if ( debugRead ) System . out . printf ( \"MISS %d %d \" , runIdx , timeIdx ) ; } if ( debugRead ) System . out . printf ( \"%d %d reallyRead %s %d bytes start at %d total size is %d%n\" , runIdx , timeIdx , mainv . getFullName ( ) , result . getSize ( ) , destPos , allData . getSize ( ) ) ; Array . arraycopy ( result , 0 , allData , destPos , ( int ) result . getSize ( ) ) ; destPos += result . getSize ( ) ; } } return allData ; } finally { // close any files used during this operation\r closeAll ( openFilesRead ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rest of stuff for construction / deserialization [CODESPLIT] private void constructTransient ( ) { useColors = colors ; edge = new double [ ncolors ] ; hist = new int [ ncolors + 1 ] ; lm = new ListenerManager ( \"java.beans.PropertyChangeListener\" , \"java.beans.PropertyChangeEvent\" , \"propertyChange\" ) ; missingDataColor = Color . white ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the number of colors in the colorscale . [CODESPLIT] public void setNumColors ( int n ) { if ( n != ncolors ) { colors = new Color [ n ] ; int prevn = Math . min ( ncolors , n ) ; System . arraycopy ( useColors , 0 , colors , 0 , prevn ) ; for ( int i = ncolors ; i < n ; i ++ ) colors [ i ] = Color . white ; useColors = colors ; ncolors = n ; edge = new double [ ncolors ] ; hist = new int [ ncolors + 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get the color at the given index or the missing data color . [CODESPLIT] public Color getColor ( int i ) { if ( i >= 0 && i < ncolors ) return useColors [ i ] ; else if ( i == ncolors && hasMissingData ) return missingDataColor ; else throw new IllegalArgumentException ( \"Color Scale getColor \" + i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data min / max interval . The color intervals are set based on this . A PropertyChangeEvent is sent when this is called . Currently the intervals are calculated in the following way ( where incr = ( max - min ) / ( n - 2 )) : <pre > <p / > edge data interval 0 min value < = min 1 min + incr min < = value < min + incr 2 min + 2 * incr min + incr < = value < min + 2 * incr ith min + i * incr min + ( i - 1 ) * incr < = value < min + i * incr n - 2 max min + ( n - 3 ) * incr < = value < max n - 1 max max < value n value = missingDataValue < / pre > [CODESPLIT] public void setMinMax ( double min , double max ) { this . min = min ; this . max = max ; interval = ( max - min ) / ( ncolors - 2 ) ; // set edges\r for ( int i = 0 ; i < ncolors ; i ++ ) edge [ i ] = min + i * interval ; lm . sendEvent ( new PropertyChangeEvent ( this , \"ColorScaleLimits\" , null , this ) ) ; } /**\r\n   * This is an optimization for counting the number of colors in each interval.\r\n   * the histpogram is populated by calls to getIndexFromValue().\r\n   *\r\n   * @return the index with the maximum histogram count.\r\n   */ public int getHistMax ( ) { int max = 0 , maxi = 0 ; for ( int i = 0 ; i <= ncolors ; i ++ ) if ( hist [ i ] > max ) { max = hist [ i ] ; maxi = i ; } return maxi ; } /**\r\n   * reset the histogram.\r\n   */ public void resetHist  ( ) { for ( int i = 0 ; i <= ncolors ; i ++ ) hist [ i ] = 0 ; } public String toString  ( ) { return name ; } public Object clone  ( ) { ColorScale cl = new ColorScale ( name , colors ) ; /*try {\r\n      cl = (ColorScale) super.clone();\r\n    } catch(CloneNotSupportedException e) {\r\n      return null;\r\n    } // ignore\r\n\r\n    // non primitive fields must be cloned separately\r\n    cl.name = new String(name);\r\n    cl.set(this);\r\n    cl.construct();  */ return ( Object ) cl ; } /////////// private ////////////////////\r // this is for editing a colorscale\r private void editModeBegin  ( ) { Color [ ] editColors = new Color [ ncolors ] ; System . arraycopy ( colors , 0 , editColors , 0 , ncolors ) ; useColors = editColors ; } private void editModeEnd  ( boolean accept ) { if ( accept ) { System . arraycopy ( useColors , 0 , colors , 0 , ncolors ) ; } useColors = colors ; } private void setColor  ( int i , Color c ) { if ( i >= 0 && i < ncolors ) useColors [ i ] = c ; } /* private void set( ColorScale cs) {\r\n   set(cs.getColors());\r\n } */ private void setColors  ( Color [ ] c ) { ncolors = c . length ; colors = new Color [ ncolors ] ; System . arraycopy ( c , 0 , colors , 0 , ncolors ) ; edge = new double [ ncolors ] ; hist = new int [ ncolors + 1 ] ; useColors = colors ; // ??\r } // serialization\r private void readObject  ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . readInt ( ) ; this . name = s . readUTF ( ) ; this . colors = ( Color [ ] ) s . readObject ( ) ; this . ncolors = colors . length ; constructTransient ( ) ; } private void writeObject  ( ObjectOutputStream s ) throws IOException { s . writeInt ( objectVersion ) ; s . writeUTF ( this . name ) ; s . writeObject ( this . colors ) ; } // heres the swing component part of a ColorScale: static so its not part of serialization\r // originally designed to allow popup editor to change colors; this has been disabled; all\r // changes made by COlorManager. design could be cleaned up, but maybe I want that back later?\r public static class Panel extends JPanel { private int type ; private int size = 50 ; private ColorScale cs ; private JLabel unitLabel = new JLabel ( \"unit\" , SwingConstants . CENTER ) ; private JPanel lpanel ; private boolean editable = false ; private int selected = - 1 ; private int nColorInterval ; private String [ ] label ; private boolean useLabel = true ; private FontUtil . StandardFont sf = FontUtil . getStandardFont ( 10 ) ; public Panel ( Component parent ) { this ( parent , ColorScale . VERTICAL , null ) ; } public Panel ( Component parent , ColorScale cscale ) { this ( parent , ColorScale . VERTICAL , cscale ) ; } public Panel ( Component parent , int type , ColorScale cscale ) { this . cs = ( cscale == null ) ? new ColorScale ( \"default\" ) : cscale ; this . type = type ; if ( type == ColorScale . VERTICAL ) { setPreferredSize ( new Dimension ( size , 400 ) ) ; setLayout ( new BoxLayout ( this , BoxLayout . Y_AXIS ) ) ; } else { setPreferredSize ( new Dimension ( 400 , size ) ) ; setLayout ( new BoxLayout ( this , BoxLayout . X_AXIS ) ) ; } setListener ( ) ; nColorInterval = cs . getNumColors ( ) ; for ( int i = 0 ; i < nColorInterval ; i ++ ) { ColorInterval intv = new ColorInterval ( nColorInterval - i - 1 ) ; add ( intv ) ; } lpanel = new JPanel ( ) ; lpanel . add ( unitLabel ) ; //unitLabel.setBorder( new javax.swing.border.EtchedBorder());\r if ( type == ColorScale . VERTICAL ) lpanel . setPreferredSize ( new Dimension ( size , 0 ) ) ; else lpanel . setPreferredSize ( new Dimension ( 0 , size ) ) ; add ( lpanel ) ; label = new String [ nColorInterval ] ; calcLabels ( ) ; /* creates a popup men, attaches it to this Panel\r\n     PopupMenu popupMenu = new PopupMenu(this, \"options\");\r\n     popupMenu.add(\"Edit\", new AbstractAction() {\r\n       public void actionPerformed(ActionEvent e) {\r\n         System.out.println(\"popup edit action\");\r\n         dialog.show();\r\n       }\r\n     }); */ } private void calcLabels ( ) { label [ 0 ] = \"<\" + Format . d ( cs . getEdge ( 0 ) , sigfig ) ; for ( int i = 1 ; i < nColorInterval - 1 ; i ++ ) { label [ i ] = Format . d ( cs . getEdge ( i ) , sigfig ) ; } label [ nColorInterval - 1 ] = \">\" + Format . d ( cs . getEdge ( nColorInterval - 2 ) , sigfig ) ; } private void setListener ( ) { // listen for changes so we can redraw\r cs . addPropertyChangeListener ( new java . beans . PropertyChangeListener ( ) { public void propertyChange ( java . beans . PropertyChangeEvent e ) { if ( e . getPropertyName ( ) . equals ( \"ColorScaleLimits\" ) ) calcLabels ( ) ; repaint ( ) ; } } ) ; } public ColorScale getColorScale ( ) { return cs ; } // change the current cscale\r public void setColorScale ( ColorScale cscale ) { if ( nColorInterval != cscale . getNumColors ( ) ) { removeAll ( ) ; nColorInterval = cscale . getNumColors ( ) ; label = new String [ nColorInterval ] ; for ( int i = 0 ; i < nColorInterval ; i ++ ) { ColorInterval intv = new ColorInterval ( nColorInterval - i - 1 ) ; add ( intv ) ; label [ i ] = \"none\" ; } add ( lpanel ) ; revalidate ( ) ; } this . cs = cscale ; setListener ( ) ; calcLabels ( ) ; repaint ( ) ; } // set existing colorscale to have new colors\r public void setColors ( Color [ ] c ) { if ( nColorInterval != c . length ) { removeAll ( ) ; nColorInterval = c . length ; label = new String [ nColorInterval ] ; for ( int i = 0 ; i < nColorInterval ; i ++ ) { ColorInterval intv = new ColorInterval ( nColorInterval - i - 1 ) ; add ( intv ) ; label [ i ] = \"none\" ; } add ( lpanel ) ; revalidate ( ) ; } cs . setColors ( c ) ; cs . editModeBegin ( ) ; // again\r if ( debugColors ) { for ( int i = 0 ; i < cs . getNumColors ( ) ; i ++ ) System . out . println ( cs . getColor ( i ) ) ; } calcLabels ( ) ; repaint ( ) ; } public void setColor ( Color c ) { cs . setColor ( selected , c ) ; } //public void setEditable( boolean b) { editable = b; }\r public void setEditMode ( boolean on , boolean accept ) { if ( on ) { editable = true ; cs . editModeBegin ( ) ; } else { cs . editModeEnd ( accept ) ; if ( accept ) setColorScale ( cs ) ; selected = - 1 ; editable = false ; } repaint ( ) ; } public void setSelected ( int i ) { selected = i ; } public void setShowText ( boolean b ) { useLabel = b ; } /*private void edit(int which) {\r\n      if (!editable)\r\n        return;\r\n      selected = which;\r\n      repaint();\r\n      cs.setEditMode(true);\r\n      //dialog.show();\r\n    }*/ public void setUnitString ( String s ) { unitLabel . setText ( s ) ; //System.out.println(\"new text = \"+s);\r //unitLabel.repaint(s);\r } public void print ( Graphics2D g , double x , double y , double width , double height ) { int n = cs . getNumColors ( ) ; double size = ( type == ColorScale . VERTICAL ) ? height / n : width / n ; int count = 0 ; for ( int i = 0 ; i < getComponentCount ( ) ; i ++ ) { Component c = getComponent ( i ) ; if ( c instanceof ColorInterval ) { ColorInterval intv = ( ColorInterval ) c ; if ( type == ColorScale . VERTICAL ) intv . printV ( g , ( int ) x , ( int ) ( y + count * size ) , ( int ) width , ( int ) size ) ; else { double xpos = x + width - ( count + 1 ) * size ; intv . printH ( g , ( int ) xpos , ( int ) y , ( int ) size , ( int ) height ) ; } count ++ ; } } } /* private class OkListener implements ActionListener {\r\n      public void actionPerformed(ActionEvent e) {\r\n        selected = -1;\r\n        cs.accept();\r\n        repaint();\r\n      }\r\n    }  // end inner class OkListener\r\n\r\n    private class CancelListener implements ActionListener {\r\n      public void actionPerformed(ActionEvent e) {\r\n        selected = -1;\r\n        cs.cancel();\r\n        repaint();\r\n      }\r\n    } // end inner class CancelListener  */ private class ColorInterval extends JComponent { private int rank ; ColorInterval ( int r ) { this . rank = r ; //setPreferredSize( new Dimension(40,40));\r addMouseListener ( new MouseAdapter ( ) { public void mousePressed ( MouseEvent e ) { if ( editable ) { selected = rank ; Panel . this . repaint ( ) ; } } } ) ; } public void printV ( Graphics2D g , int x , int y , int width , int height ) { int textSize = 15 ; // LOOK : neeed to calculate this\r g . setColor ( cs . getColor ( rank ) ) ; g . fillRect ( x , y + textSize , width , height - textSize ) ; //g.setColor( Color.black);\r //g.drawRect( x, y+textSize, width, height-textSize);\r if ( useLabel ) { g . setColor ( Color . black ) ; g . setFont ( sf . getFont ( ) ) ; g . drawString ( label [ rank ] , x + 3 , y + 10 ) ; } } public void printH ( Graphics2D g , int x , int y , int width , int height ) { int textSize = 15 ; // LOOK : neeed to calculate this\r g . setColor ( cs . getColor ( rank ) ) ; g . fillRect ( x , y + textSize , width , height - 2 * textSize ) ; g . setColor ( Color . white ) ; g . drawRect ( x , y + textSize , width , height - 2 * textSize ) ; if ( useLabel ) { g . setColor ( Color . black ) ; g . setFont ( sf . getFont ( ) ) ; if ( rank % 2 == 0 ) // even\r g . drawString ( label [ rank ] , x , y + textSize ) ; else g . drawString ( label [ rank ] , x , y + height ) ; } } public void paintComponent ( Graphics g ) { Rectangle b = getBounds ( ) ; g . setColor ( cs . getColor ( rank ) ) ; g . fillRect ( 0 , 0 , b . width - 1 , b . height - 1 ) ; g . setColor ( ( selected == rank ) ? Color . magenta : Color . black ) ; g . drawRect ( 0 , 0 , b . width - 1 , b . height - 1 ) ; if ( selected == rank ) { g . drawLine ( 0 , 0 , b . width , b . height ) ; g . drawLine ( 0 , b . height , b . width , 0 ) ; } if ( useLabel ) { g . setColor ( Color . black ) ; g . setFont ( sf . getFont ( ) ) ; g . drawString ( label [ rank ] , 3 , 10 ) ; } } } // end inner class ColorInterval\r } // end inner class ColorScale.Panel\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of all variables in this vector . This method is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space ) { int len = vals . length ; for ( int i = 0 ; i < len - 1 ; i ++ ) { os . print ( vals [ i ] ) ; os . print ( \", \" ) ; } // print last value, if any, without trailing comma\r if ( len > 0 ) os . print ( vals [ len - 1 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { for ( int i = 0 ; i < vals . length ; i ++ ) { sink . writeDouble ( vals [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * set the bounds of the world coordinates . The point ( world . getX () world . getY () ) is mapped to the lower left point of the screen . The point ( world . getX () + world . Width () world . getY () + world . Height () ) is mapped to the upper right corner . Therefore if coords decrease as you go up world . Height () should be negetive . [CODESPLIT] public void setWorldBounds ( ScaledPanel . Bounds world ) { worldBounds . set ( world ) ; transform = null ; if ( debugBounds ) System . out . println ( \"  setWorldBounds = \" + worldBounds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "User must get this Graphics2D and draw into it when panel needs redrawing [CODESPLIT] public Graphics2D getBufferedImageGraphics ( ) { if ( bImage == null ) return null ; Graphics2D g2 = bImage . createGraphics ( ) ; // set graphics attributes if ( transform == null ) transform = calcTransform ( screenBounds , worldBounds ) ; g2 . setTransform ( transform ) ; g2 . setStroke ( new BasicStroke ( 0.0f ) ) ; // default stroke size is one pixel g2 . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_SPEED ) ; g2 . setBackground ( backColor ) ; g2 . setClip ( worldBounds . getRect ( ) ) ; return g2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "System - triggered redraw . [CODESPLIT] public void paintComponent ( Graphics g ) { if ( bImage != null ) g . drawImage ( bImage , 0 , 0 , backColor , imageObs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "map world coords to screen coords . [CODESPLIT] private AffineTransform calcTransform ( Rectangle2D screen , Bounds world ) { // scale to limiting dimension double xs = screen . getWidth ( ) / ( world . getRight ( ) - world . getLeft ( ) ) ; double ys = screen . getHeight ( ) / ( world . getLower ( ) - world . getUpper ( ) ) ; AffineTransform cat = new AffineTransform ( ) ; cat . setToScale ( xs , ys ) ; cat . translate ( - world . getLeft ( ) , - world . getUpper ( ) ) ; if ( debugTransform ) { System . out . println ( \"TPanel calcTransform = \" ) ; System . out . println ( \"  screen = \" + screen ) ; System . out . println ( \"  world = \" + world ) ; System . out . println ( \"  transform = \" + cat . getScaleX ( ) + \" \" + cat . getShearX ( ) + \" \" + cat . getTranslateX ( ) ) ; System . out . println ( \"              \" + cat . getShearY ( ) + \" \" + cat . getScaleY ( ) + \" \" + cat . getTranslateY ( ) ) ; Point2D src = new Point2D . Double ( world . getLeft ( ) , world . getUpper ( ) ) ; Point2D dst = new Point2D . Double ( 0.0 , 0.0 ) ; System . out . println ( \"  upper left pt = \" + src ) ; System . out . println ( \"  transform = \" + cat . transform ( src , dst ) ) ; src = new Point2D . Double ( world . getRight ( ) , world . getLower ( ) ) ; System . out . println ( \"  lower right pt = \" + src ) ; System . out . println ( \"  transform = \" + cat . transform ( src , dst ) ) ; } return cat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a session url AuthScope and a Method url AuthScope Indicate it the are compatible as defined as follows . The method AuthScope is <i > compatible< / i > with the session AuthScope if its host + port is the same as the session s host + port and its scheme is compatible where e . g . http is compatible with https . The scope realm is ignored . [CODESPLIT] static boolean authscopeCompatible ( AuthScope ss , AuthScope ms ) { assert ( ss . getScheme ( ) != null && ms . getScheme ( ) != null ) ; if ( ! ss . getHost ( ) . equalsIgnoreCase ( ms . getHost ( ) ) ) return false ; if ( ss . getPort ( ) != ms . getPort ( ) ) return false ; String sss = ss . getScheme ( ) . toLowerCase ( ) ; String mss = ms . getScheme ( ) . toLowerCase ( ) ; if ( ! sss . equals ( mss ) ) { // Do some special casing if ( sss . endsWith ( \"s\" ) ) sss = sss . substring ( 0 , sss . length ( ) - 1 ) ; if ( mss . endsWith ( \"s\" ) ) mss = mss . substring ( 0 , mss . length ( ) - 1 ) ; if ( ! sss . equals ( mss ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a session url AuthScope and a Method url AuthScope return a new AuthScope that is the upgrade / merge of the other two . Here upgrade changes the scheme ( only ) to move http - > https . Assumes authscopeCompatible () is true . [CODESPLIT] static AuthScope authscopeUpgrade ( AuthScope ss , AuthScope ms ) { assert ( HTTPAuthUtil . authscopeCompatible ( ss , ms ) ) ; String sss = ss . getScheme ( ) . toLowerCase ( ) ; String mss = ms . getScheme ( ) . toLowerCase ( ) ; String upgrade = sss ; if ( sss . startsWith ( \"http\" ) && mss . startsWith ( \"http\" ) ) { if ( sss . equals ( \"https\" ) || mss . equals ( \"https\" ) ) upgrade = \"https\" ; } AuthScope host = new AuthScope ( ss . getHost ( ) , ss . getPort ( ) , AuthScope . ANY_REALM , upgrade ) ; return host ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an AuthScope from a URI ; remove any principal [CODESPLIT] static AuthScope uriToAuthScope ( URI uri ) { assert ( uri != null ) ; return new AuthScope ( uri . getHost ( ) , uri . getPort ( ) , AuthScope . ANY_REALM , uri . getScheme ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compares GDS for duplicates [CODESPLIT] public void finish ( ) { if ( gcs . size ( ) == 1 ) return ; if ( gcs . size ( ) == 2 ) { List hcs = getHorizCoordSys ( ) ; GridDefRecord . compare ( ( GridDefRecord ) hcs . get ( 0 ) , ( GridDefRecord ) hcs . get ( 1 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if this Factor is the reciprocal of another Factor . [CODESPLIT] public boolean isReciprocalOf ( final Factor that ) { return getBase ( ) . equals ( that . getBase ( ) ) && getExponent ( ) == - that . getExponent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : defaultPointMetadata / wml2 : DefaultTVPMeasurementMetadata [CODESPLIT] public static TVPMeasurementMetadataType initDefaultTVPMeasurementMetadata ( TVPMeasurementMetadataType defaultTVPMeasurementMetadata , VariableSimpleIF dataVar ) { // wml2:uom UnitReference uom = NcUnitReference . initUom ( defaultTVPMeasurementMetadata . addNewUom ( ) , dataVar ) ; if ( uom == null ) { defaultTVPMeasurementMetadata . unsetUom ( ) ; } // wml2:interpolationType NcReferenceType . initInterpolationType ( defaultTVPMeasurementMetadata . addNewInterpolationType ( ) ) ; return defaultTVPMeasurementMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if the service Base is reletive [CODESPLIT] public boolean isRelativeBase ( ) { if ( getType ( ) == ServiceType . Compound ) return true ; try { URI uri = new java . net . URI ( base ) ; return ! uri . isAbsolute ( ) ; } catch ( java . net . URISyntaxException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gather context information for the given HTTP request and return a log message appropriate for logging at the start of the request . <p / > <p > The following context information is gathered : <ul > <li > ID - an identifier for the current thread ; < / li > <li > host - the remote host ( IP address or host name ) ; < / li > <li > userid - the id of the remote user ; < / li > <li > startTime - the system time in millis when this request is started ( i . e . when this method is called ) ; and< / li > <li > request - The HTTP request e . g . GET / index . html HTTP / 1 . 1 . < / li > < / ul > <p / > <p > Call this method at the start of each HttpServlet doXXX () method ( e . g . doGet () doPut () ) or Spring MVC Controller handle () method . [CODESPLIT] public static String setupRequestContext ( HttpServletRequest req ) { // Setup context.\r //HttpSession session = req.getSession(false);\r /* MDC.put(\"host\", req.getRemoteHost());\r\n    MDC.put(\"ident\", (session == null) ? \"-\" : session.getId());\r\n    MDC.put(\"userid\", req.getRemoteUser() != null ? req.getRemoteUser() : \"-\"); */ MDC . put ( \"ID\" , Long . toString ( logServerAccessId . incrementAndGet ( ) ) ) ; MDC . put ( \"startTime\" , Long . toString ( System . currentTimeMillis ( ) ) ) ; String query = req . getQueryString ( ) ; query = ( query != null ) ? \"?\" + query : \"\" ; Formatter request = new Formatter ( ) ; request . format ( \"\\\"%s %s%s %s\\\"\" , req . getMethod ( ) , req . getRequestURI ( ) , query , req . getProtocol ( ) ) ; MDC . put ( \"request\" , request . toString ( ) ) ; return \"Remote host: \" + req . getRemoteHost ( ) + \" - Request: \" + request . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gather context information for the current non - request thread and return a log message appropriate for logging . <p / > <p > The following context information is gathered : <ul > <li > ID - an identifier for the current thread ; and< / li > <li > startTime - the system time in millis when this method is called . < / li > < / ul > <p / > <p > Call this method only for non - request servlet activities e . g . during init () or destroy () . [CODESPLIT] public static String setupNonRequestContext ( ) { // Setup context.\r MDC . put ( \"ID\" , Long . toString ( logServerAccessId . incrementAndGet ( ) ) ) ; MDC . put ( \"startTime\" , Long . toString ( System . currentTimeMillis ( ) ) ) ; return \"Non-request thread opening.\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "API [CODESPLIT] public String generate ( String dataseturl ) throws IOException { StringWriter sw = new StringWriter ( ) ; IndentWriter printer = new IndentWriter ( sw ) ; printer . marginPrintln ( \"<DatasetServices\" ) ; printer . indent ( 2 ) ; printer . marginPrintln ( \"xmlns=\\\"http://xml.opendap.org/ns/DAP/4.0/dataset-services#\\\">\" ) ; printer . outdent ( ) ; printer . marginPrint ( \"<DapVersion>\" ) ; printer . print ( DapProtocol . X_DAP_VERSION ) ; printer . println ( \"</DapVersion>\" ) ; printer . marginPrint ( \"<ServerSoftwareVersion>\" ) ; printer . print ( DapProtocol . X_DAP_SERVER ) ; printer . println ( \"</ServerSoftwareVersion>\" ) ; printer . marginPrintln ( \"<Service title=\\\"DAP4 Dataset Services\\\"\" ) ; printer . indent ( 3 ) ; printer . marginPrintln ( \"role=\\\"http://services.opendap.org/dap4/dataset-services\\\">\" ) ; printer . outdent ( 3 ) ; printer . indent ( ) ; printer . marginPrint ( \"<link type=\\\"\" ) ; printer . print ( DapProtocol . contenttypes . get ( RequestMode . DSR ) . contenttype ) ; printer . println ( \"\\\"\" ) ; printer . indent ( 2 ) ; printer . marginPrint ( \"href=\\\"\" ) ; printer . print ( dataseturl ) ; printer . println ( \"\\\">\" ) ; printer . outdent ( 2 ) ; printer . indent ( ) ; printer . marginPrintln ( \"<alt type=\\\"text/xml\\\"/>\" ) ; printer . outdent ( ) ; printer . marginPrintln ( \"</link>\" ) ; printer . marginPrintln ( \"<link type=\\\"text/xml\\\"\" ) ; printer . indent ( 2 ) ; printer . marginPrint ( \"href=\\\"\" ) ; printer . print ( dataseturl ) ; printer . println ( \".xml\\\"/>\" ) ; printer . outdent ( 2 ) ; printer . outdent ( ) ; printer . marginPrintln ( \"</Service>\" ) ; printer . marginPrintln ( \"<Service title=\\\"DAP4 Dataset Metadata\\\"\" ) ; printer . indent ( 3 ) ; printer . marginPrintln ( \"role=\\\"http://services.opendap.org/dap4/dataset-metadata\\\">\" ) ; printer . outdent ( 3 ) ; printer . indent ( ) ; printer . marginPrint ( \"<link type=\\\"\" ) ; printer . print ( DapProtocol . contenttypes . get ( RequestMode . DMR ) . contenttype ) ; printer . println ( \"\\\"\" ) ; printer . indent ( 2 ) ; printer . marginPrint ( \"href=\\\"\" ) ; printer . print ( dataseturl ) ; printer . println ( \".dmr\\\">\" ) ; printer . outdent ( 2 ) ; printer . indent ( ) ; printer . marginPrintln ( \"<alt type=\\\"text/xml\\\"/>\" ) ; printer . outdent ( ) ; printer . marginPrintln ( \"</link>\" ) ; printer . marginPrintln ( \"<link type=\\\"text/xml\\\"\" ) ; printer . indent ( 2 ) ; printer . marginPrint ( \"href=\\\"\" ) ; printer . print ( dataseturl ) ; printer . println ( \".dmr.xml\\\"/>\" ) ; printer . outdent ( 2 ) ; printer . outdent ( ) ; printer . marginPrintln ( \"</Service>\" ) ; printer . marginPrintln ( \"<Service title=\\\"DAP4 Dataset Data\\\"\" ) ; printer . indent ( 2 ) ; printer . marginPrintln ( \"role=\\\"http://services.opendap.org/dap4/data\\\">\" ) ; printer . outdent ( 2 ) ; printer . indent ( ) ; printer . marginPrint ( \"<link type=\\\"\" ) ; printer . print ( DapProtocol . contenttypes . get ( RequestMode . DAP ) . contenttype ) ; printer . println ( \"\\\"\" ) ; printer . indent ( 2 ) ; printer . marginPrint ( \"href=\\\"\" ) ; printer . print ( dataseturl ) ; printer . println ( \".dap\\\"/>\" ) ; printer . outdent ( 2 ) ; printer . outdent ( ) ; printer . marginPrintln ( \"</Service>\" ) ; printer . outdent ( ) ; printer . marginPrintln ( \"</DatasetServices>\" ) ; printer . flush ( ) ; printer . close ( ) ; sw . close ( ) ; return sw . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a catalog for the given directory . [CODESPLIT] public InvCatalog getDirCatalog ( File directory , String filterPattern , boolean sortInIncreasingOrder , boolean addDatasetSize ) { return ( this . getDirCatalog ( directory , filterPattern , sortInIncreasingOrder , null , addDatasetSize , null , null , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find which index holds the value want [CODESPLIT] public int findIdx ( int want ) { if ( isConstant ) return ( want == start ) ? 0 : - 1 ; if ( isSequential ) return want - start ; if ( isSorted ) { return Arrays . binarySearch ( raw , want ) ; } // linear search for ( int i = 0 ; i < raw . length ; i ++ ) if ( raw [ i ] == want ) return i ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvMetadata content object from an XML document at a named URL . The content object is an ArrayList of CatalogGenConfig instances . [CODESPLIT] private Object readMetadataContentFromURL ( InvDataset dataset , String urlString ) throws java . net . MalformedURLException , java . io . IOException { // @todo This isn't used anywhere. Remove? Document doc ; try { SAXBuilder builder = new SAXBuilder ( true ) ; doc = builder . build ( urlString ) ; } catch ( JDOMException e ) { log . error ( \"CatGenConfigMetadataFactory parsing error= \\n\" + e . getMessage ( ) ) ; throw new java . io . IOException ( \"CatGenConfigMetadataFactory parsing error= \" + e . getMessage ( ) ) ; } if ( showParsedXML ) { XMLOutputter xmlOut = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; System . out . println ( \"*** catalog/showParsedXML = \\n\" + xmlOut . outputString ( doc ) + \"\\n*******\" ) ; } return ( readMetadataContentJdom ( dataset , doc . getRootElement ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvMetadata content object from an org . w3c . dom . Element . The content object is an ArrayList of CatalogGenConfig instances . [CODESPLIT] public Object readMetadataContent ( InvDataset dataset , org . jdom2 . Element mdataElement ) { log . debug ( \"readMetadataContent(): .\" ) ; // convert to JDOM element //Element mdataElement = builder.build( mdataDomElement ); return readMetadataContentJdom ( dataset , mdataElement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the InvMetadata content object to a org . w3c . dom . Element [CODESPLIT] public void addMetadataContent ( org . jdom2 . Element mdataJdomElement , Object contentObject ) { // convert to JDOM element //Element mdataJdomElement = builder.build( mdataElement ); ArrayList catGenConfigList = ( ArrayList ) contentObject ; Iterator iter = catGenConfigList . iterator ( ) ; while ( iter . hasNext ( ) ) { CatalogGenConfig cgc = ( CatalogGenConfig ) iter . next ( ) ; mdataJdomElement . addContent ( createCatGenConfigElement ( cgc ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the content object . [CODESPLIT] public boolean validateMetadataContent ( Object contentObject , StringBuilder out ) { boolean ok = true ; ArrayList catGenConfigList = ( ArrayList ) contentObject ; Iterator iter = catGenConfigList . iterator ( ) ; while ( iter . hasNext ( ) ) { CatalogGenConfig catGenConf = ( CatalogGenConfig ) iter . next ( ) ; ok &= catGenConf . validate ( out ) ; } return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a metadata JDOM element return metadata content object ( ArrayList of CatalogGenConfig ) . <p / > From the given metadata JDOM element build ( and return ) an ArrayList of CatalogGenConfig instances . [CODESPLIT] private Object readMetadataContentJdom ( InvDataset dataset , Element mdataElement ) { Namespace catGenConfigNamespace = null ; ArrayList catGenConfigList = new ArrayList ( ) ; // Get the \"catalogGenConfig\" children elements with // CatalogGenConfig namespace first and then with THREDDS namespace. Iterator iter = mdataElement . getChildren ( \"catalogGenConfig\" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) . iterator ( ) ; if ( ! iter . hasNext ( ) ) iter = mdataElement . getChildren ( \"catalogGenConfig\" , mdataElement . getNamespace ( ) ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Element catGenConfigElement = ( Element ) iter . next ( ) ; if ( debug ) { log . debug ( \"readMetadataContent=\" + catGenConfigElement ) ; } catGenConfigList . add ( readCatGenConfigElement ( dataset , catGenConfigElement ) ) ; } return ( catGenConfigList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a CatalogGenConfig when given a catalogGenConfig JDOM element . [CODESPLIT] private CatalogGenConfig readCatGenConfigElement ( InvDataset parentDataset , Element catGenConfElement ) { String type = catGenConfElement . getAttributeValue ( \"type\" ) ; CatalogGenConfig catGenConf = new CatalogGenConfig ( parentDataset , type ) ; // get any datasetSource elements java . util . List list = catGenConfElement . getChildren ( \"datasetSource\" , catGenConfElement . getNamespace ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Element dsSourceElement = ( Element ) list . get ( i ) ; catGenConf . setDatasetSource ( readDatasetSourceElement ( parentDataset , dsSourceElement ) ) ; } // @todo Start only allowing datasetSource elements in catalogGenConfig elements. //    // get any datasetNamer elements //    list = catGenConfElement.getChildren( \"datasetNamer\", catGenConfElement.getNamespace() ); //    for (int i=0; i< list.size(); i++) //    { //      Element dsNamerElement = (Element) list.get(i); // //      catGenConf.addDatasetNamer( readDatasetNamerElement( parentDataset, //                                                           dsNamerElement)); //    } return ( catGenConf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a DatasetSource when given a datasetSource JDOM element . [CODESPLIT] private DatasetSource readDatasetSourceElement ( InvDataset parentDataset , Element dsSourceElement ) { String name = dsSourceElement . getAttributeValue ( \"name\" ) ; String type = dsSourceElement . getAttributeValue ( \"type\" ) ; String structure = dsSourceElement . getAttributeValue ( \"structure\" ) ; String accessPoint = dsSourceElement . getAttributeValue ( \"accessPoint\" ) ; String createCatalogRefs = dsSourceElement . getAttributeValue ( \"createCatalogRefs\" ) ; // get the resultService element Element resultServiceElement = dsSourceElement . getChild ( \"resultService\" , dsSourceElement . getNamespace ( ) ) ; ResultService resultService = readResultServiceElement ( parentDataset , resultServiceElement ) ; DatasetSource dsSource = DatasetSource . newDatasetSource ( name , DatasetSourceType . getType ( type ) , DatasetSourceStructure . getStructure ( structure ) , accessPoint , resultService ) ; if ( createCatalogRefs != null ) { dsSource . setCreateCatalogRefs ( Boolean . valueOf ( createCatalogRefs ) . booleanValue ( ) ) ; } // get any datasetNamer elements java . util . List list = dsSourceElement . getChildren ( \"datasetNamer\" , dsSourceElement . getNamespace ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Element dsNamerElement = ( Element ) list . get ( i ) ; dsSource . addDatasetNamer ( readDatasetNamerElement ( parentDataset , dsNamerElement ) ) ; } // get any datasetFilter elements list = dsSourceElement . getChildren ( \"datasetFilter\" , dsSourceElement . getNamespace ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Element dsFilterElement = ( Element ) list . get ( i ) ; dsSource . addDatasetFilter ( readDatasetFilterElement ( dsSource , dsFilterElement ) ) ; } return ( dsSource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a DatasetNamer when given a datasetNamer JDOM element . [CODESPLIT] private DatasetNamer readDatasetNamerElement ( InvDataset parentDataset , Element dsNamerElement ) { String name = dsNamerElement . getAttributeValue ( \"name\" ) ; String addLevel = dsNamerElement . getAttributeValue ( \"addLevel\" ) ; String type = dsNamerElement . getAttributeValue ( \"type\" ) ; String matchPattern = dsNamerElement . getAttributeValue ( \"matchPattern\" ) ; String substitutePattern = dsNamerElement . getAttributeValue ( \"substitutePattern\" ) ; String attribContainer = dsNamerElement . getAttributeValue ( \"attribContainer\" ) ; String attribName = dsNamerElement . getAttributeValue ( \"attribName\" ) ; DatasetNamer dsNamer = new DatasetNamer ( parentDataset , name , addLevel , type , matchPattern , substitutePattern , attribContainer , attribName ) ; return ( dsNamer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a DatasetFilter when given a datasetFilter JDOM element . [CODESPLIT] private DatasetFilter readDatasetFilterElement ( DatasetSource parentDatasetSource , Element dsFilterElement ) { String name = dsFilterElement . getAttributeValue ( \"name\" ) ; String type = dsFilterElement . getAttributeValue ( \"type\" ) ; String matchPattern = dsFilterElement . getAttributeValue ( \"matchPattern\" ) ; DatasetFilter dsFilter = new DatasetFilter ( parentDatasetSource , name , DatasetFilter . Type . getType ( type ) , matchPattern ) ; String matchPatternTarget = dsFilterElement . getAttributeValue ( \"matchPatternTarget\" ) ; dsFilter . setMatchPatternTarget ( matchPatternTarget ) ; if ( dsFilterElement . getAttributeValue ( \"applyToCollectionDatasets\" ) != null ) { boolean applyToCollectionDatasets = Boolean . valueOf ( dsFilterElement . getAttributeValue ( \"applyToCollectionDatasets\" ) ) . booleanValue ( ) ; dsFilter . setApplyToCollectionDatasets ( applyToCollectionDatasets ) ; } if ( dsFilterElement . getAttributeValue ( \"applyToAtomicDatasets\" ) != null ) { boolean applyToAtomicDatasets = Boolean . valueOf ( dsFilterElement . getAttributeValue ( \"applyToAtomicDatasets\" ) ) . booleanValue ( ) ; dsFilter . setApplyToAtomicDatasets ( applyToAtomicDatasets ) ; } if ( dsFilterElement . getAttributeValue ( \"rejectMatchingDatasets\" ) != null ) { boolean rejectMatchingDatasets = Boolean . valueOf ( dsFilterElement . getAttributeValue ( \"rejectMatchingDatasets\" ) ) . booleanValue ( ) ; dsFilter . setRejectMatchingDatasets ( rejectMatchingDatasets ) ; } return ( dsFilter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a ResultService when given a resultService JDOM element . [CODESPLIT] private ResultService readResultServiceElement ( InvDataset parentDataset , Element resultServiceElement ) { String name = resultServiceElement . getAttributeValue ( \"name\" ) ; String serviceType = resultServiceElement . getAttributeValue ( \"serviceType\" ) ; String base = resultServiceElement . getAttributeValue ( \"base\" ) ; String suffix = resultServiceElement . getAttributeValue ( \"suffix\" ) ; String accessPointHeader = resultServiceElement . getAttributeValue ( \"accessPointHeader\" ) ; return ( new ResultService ( name , ServiceType . getType ( serviceType ) , base , suffix , accessPointHeader ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a catalogGenConfig JDOM element [CODESPLIT] private org . jdom2 . Element createCatGenConfigElement ( CatalogGenConfig cgc ) { // @todo Need to deal with the 0.6 and 1.0 namespaces. Element cgcElem = new Element ( \"catalogGenConfig\" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( cgc != null ) { if ( cgc . getType ( ) != null ) { cgcElem . setAttribute ( \"type\" , cgc . getType ( ) . toString ( ) ) ; } // Add 'datasetSource' element DatasetSource dsSource = cgc . getDatasetSource ( ) ; cgcElem . addContent ( createDatasetSourceElement ( dsSource ) ) ; } return ( cgcElem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a DatasetSource JDOM element [CODESPLIT] private org . jdom2 . Element createDatasetSourceElement ( DatasetSource dsSource ) { Element dssElem = new Element ( \"datasetSource\" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( dsSource != null ) { // Add 'name' attribute. if ( dsSource . getName ( ) != null ) { dssElem . setAttribute ( \"name\" , dsSource . getName ( ) ) ; } // Add 'type' attribute. if ( dsSource . getType ( ) != null ) { dssElem . setAttribute ( \"type\" , dsSource . getType ( ) . toString ( ) ) ; } // Add 'structure' attribute. if ( dsSource . getStructure ( ) != null ) { dssElem . setAttribute ( \"structure\" , dsSource . getStructure ( ) . toString ( ) ) ; } // Add 'accessPoint' attribute. if ( dsSource . getAccessPoint ( ) != null ) { dssElem . setAttribute ( \"accessPoint\" , dsSource . getAccessPoint ( ) ) ; } // Add 'createCatalogRefs' attribute. dssElem . setAttribute ( \"createCatalogRefs\" , Boolean . toString ( dsSource . isCreateCatalogRefs ( ) ) ) ; // Add 'resultService' element ResultService rs = dsSource . getResultService ( ) ; dssElem . addContent ( createResultServiceElement ( rs ) ) ; // Add 'datasetNamer' elements java . util . List list = dsSource . getDatasetNamerList ( ) ; for ( int j = 0 ; j < list . size ( ) ; j ++ ) { DatasetNamer dsNamer = ( DatasetNamer ) list . get ( j ) ; dssElem . addContent ( createDatasetNamerElement ( dsNamer ) ) ; } // Add 'datasetFilter' elements list = dsSource . getDatasetFilterList ( ) ; for ( int j = 0 ; j < list . size ( ) ; j ++ ) { DatasetFilter dsFilter = ( DatasetFilter ) list . get ( j ) ; dssElem . addContent ( createDatasetFilterElement ( dsFilter ) ) ; } } return ( dssElem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a DatasetNamer JDOM element [CODESPLIT] private org . jdom2 . Element createDatasetNamerElement ( DatasetNamer dsNamer ) { Element dsnElem = new Element ( \"datasetNamer\" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( dsNamer != null ) { // Add 'name' attribute. if ( dsNamer . getName ( ) != null ) { dsnElem . setAttribute ( \"name\" , dsNamer . getName ( ) ) ; } // Add 'addLevel' attribute. dsnElem . setAttribute ( \"addLevel\" , Boolean . toString ( dsNamer . getAddLevel ( ) ) ) ; // Add 'type' attribute. if ( dsNamer . getType ( ) != null ) { dsnElem . setAttribute ( \"type\" , dsNamer . getType ( ) . toString ( ) ) ; } // Add 'matchPattern' attribute. if ( dsNamer . getMatchPattern ( ) != null ) { dsnElem . setAttribute ( \"matchPattern\" , dsNamer . getMatchPattern ( ) ) ; } // Add 'subsitutePattern' attribute. if ( dsNamer . getSubstitutePattern ( ) != null ) { dsnElem . setAttribute ( \"substitutePattern\" , dsNamer . getSubstitutePattern ( ) ) ; } // Add 'attribContainer' attribute. if ( dsNamer . getAttribContainer ( ) != null ) { dsnElem . setAttribute ( \"attribContainer\" , dsNamer . getAttribContainer ( ) ) ; } // Add 'attribName' attribute. if ( dsNamer . getAttribName ( ) != null ) { dsnElem . setAttribute ( \"attribName\" , dsNamer . getAttribName ( ) ) ; } } return ( dsnElem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a DatasetFilter JDOM element [CODESPLIT] private org . jdom2 . Element createDatasetFilterElement ( DatasetFilter dsFilter ) { Element dsfElem = new Element ( \"datasetFilter\" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( dsFilter != null ) { // Add 'name' attribute. if ( dsFilter . getName ( ) != null ) { dsfElem . setAttribute ( \"name\" , dsFilter . getName ( ) ) ; } // Add 'type' attribute. if ( dsFilter . getType ( ) != null ) { dsfElem . setAttribute ( \"type\" , dsFilter . getType ( ) . toString ( ) ) ; } // Add 'matchPattern' attribute. if ( dsFilter . getMatchPattern ( ) != null ) { dsfElem . setAttribute ( \"matchPattern\" , dsFilter . getMatchPattern ( ) ) ; } // Add 'matchPatternTarget' attribute. if ( dsFilter . getMatchPatternTarget ( ) != null ) { dsfElem . setAttribute ( \"matchPatternTarget\" , dsFilter . getMatchPatternTarget ( ) ) ; } // Add 'applyToCollectionDatasets' attribute. dsfElem . setAttribute ( \"applyToCollectionDatasets\" , String . valueOf ( dsFilter . isApplyToCollectionDatasets ( ) ) ) ; // Add 'applyToAtomicDatasets' attribute. dsfElem . setAttribute ( \"applyToAtomicDatasets\" , String . valueOf ( dsFilter . isApplyToAtomicDatasets ( ) ) ) ; // Add 'rejectMatchingDatasets' attribute. dsfElem . setAttribute ( \"rejectMatchingDatasets\" , String . valueOf ( dsFilter . isRejectMatchingDatasets ( ) ) ) ; } return ( dsfElem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ResultService JDOM element [CODESPLIT] private org . jdom2 . Element createResultServiceElement ( ResultService resultService ) { Element rsElem = new Element ( \"resultService\" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( resultService != null ) { // Add 'name' attribute. if ( resultService . getName ( ) != null ) { rsElem . setAttribute ( \"name\" , resultService . getName ( ) ) ; } // Add 'serviceType' attribute. if ( resultService . getServiceType ( ) != null ) { rsElem . setAttribute ( \"serviceType\" , resultService . getServiceType ( ) . toString ( ) ) ; } // Add 'base' attribute. if ( resultService . getBase ( ) != null ) { rsElem . setAttribute ( \"base\" , resultService . getBase ( ) ) ; } // Add 'suffix' attribute. if ( resultService . getSuffix ( ) != null ) { rsElem . setAttribute ( \"suffix\" , resultService . getSuffix ( ) ) ; } // Add 'accessPointHeader' attribute. if ( resultService . getAccessPointHeader ( ) != null ) { rsElem . setAttribute ( \"accessPointHeader\" , resultService . getAccessPointHeader ( ) ) ; } } return ( rsElem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value of the named flag . If it doesnt exist it will be added to the store and the menu with a value of false . [CODESPLIT] static public boolean isSet ( String flagName ) { if ( store == null ) return false ; NamePart np = partit ( flagName ) ; if ( debug ) { try { if ( ( np . storeName . length ( ) > 0 ) && ! store . nodeExists ( np . storeName ) ) System . out . println ( \"Debug.isSet create node = \" + flagName + \" \" + np ) ; else if ( null == store . node ( np . storeName ) . get ( np . keyName , null ) ) System . out . println ( \"Debug.isSet create flag = \" + flagName + \" \" + np ) ; } catch ( BackingStoreException e ) { } } // add it if it doesnt already exist boolean value = store . node ( np . storeName ) . getBoolean ( np . keyName , false ) ; store . node ( np . storeName ) . putBoolean ( np . keyName , value ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct cascading pull - aside menus using the values of the debug flags in the Preferences object . [CODESPLIT] static public void constructMenu ( JMenu topMenu ) { if ( debug ) System . out . println ( \"Debug.constructMenu \" ) ; if ( topMenu . getItemCount ( ) > 0 ) topMenu . removeAll ( ) ; try { addToMenu ( topMenu , store ) ; // recursive } catch ( BackingStoreException e ) { } topMenu . revalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recursive menu adding [CODESPLIT] static private void addToMenu ( JMenu menu , Preferences prefs ) throws BackingStoreException { if ( debug ) System . out . println ( \" addMenu \" + prefs . name ( ) ) ; String [ ] keys = prefs . keys ( ) ; for ( String key : keys ) { boolean bval = prefs . getBoolean ( key , false ) ; String fullname = prefs . absolutePath ( ) + \"/\" + key ; menu . add ( new DebugMenuItem ( fullname , key , bval ) ) ; // menu leaf if ( debug ) System . out . println ( \"   leaf= <\" + key + \"><\" + fullname + \">\" ) ; } String [ ] kidName = prefs . childrenNames ( ) ; for ( String aKidName : kidName ) { Preferences pkid = prefs . node ( aKidName ) ; JMenu subMenu = new JMenu ( pkid . name ( ) ) ; menu . add ( subMenu ) ; addToMenu ( subMenu , pkid ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add parameters from the table [CODESPLIT] public void addParameters ( String tbl ) throws IOException { try ( InputStream is = getInputStream ( tbl ) ) { if ( is == null ) { throw new IOException ( \"Unable to open \" + tbl ) ; } String content = readContents ( is ) ; // LOOK this is silly - should just read one line at a time\r // List           lines   = StringUtil.split(content, \"\\n\", false);\r String [ ] lines = content . split ( \"\\n\" ) ; List < String [ ] > result = new ArrayList <> ( ) ; for ( String line : lines ) { //String line  = (String) lines.get(i);\r String tline = line . trim ( ) ; if ( tline . length ( ) == 0 ) { continue ; } if ( tline . startsWith ( \"!\" ) ) { continue ; } String [ ] words = new String [ indices . length ] ; for ( int idx = 0 ; idx < indices . length ; idx ++ ) { if ( indices [ idx ] >= tline . length ( ) ) { continue ; } if ( indices [ idx ] + lengths [ idx ] > tline . length ( ) ) { words [ idx ] = line . substring ( indices [ idx ] ) ; } else { words [ idx ] = line . substring ( indices [ idx ] , indices [ idx ] + lengths [ idx ] ) ; } //if (trimWords) {\r words [ idx ] = words [ idx ] . trim ( ) ; //}\r } result . add ( words ) ; } for ( String [ ] aResult : result ) { GempakParameter p = makeParameter ( aResult ) ; if ( p != null ) { if ( p . getName ( ) . contains ( \"(\" ) ) { templateParamMap . put ( p . getName ( ) , p ) ; } else { paramMap . put ( p . getName ( ) , p ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a parameter from the tokens [CODESPLIT] private GempakParameter makeParameter ( String [ ] words ) { int num = 0 ; String description ; if ( words [ 0 ] != null ) { num = ( int ) Double . parseDouble ( words [ 0 ] ) ; } if ( ( words [ 3 ] == null ) || words [ 3 ] . equals ( \"\" ) ) { // no param name\r return null ; } String name = words [ 3 ] ; if ( name . contains ( \"-\" ) ) { int first = name . indexOf ( \"-\" ) ; int last = name . lastIndexOf ( \"-\" ) ; StringBuilder buf = new StringBuilder ( name . substring ( 0 , first ) ) ; buf . append ( \"(\" ) ; for ( int i = first ; i <= last ; i ++ ) { buf . append ( \"\\\\d\" ) ; } buf . append ( \")\" ) ; buf . append ( name . substring ( last + 1 ) ) ; name = buf . toString ( ) ; } if ( ( words [ 1 ] == null ) || words [ 1 ] . equals ( \"\" ) ) { description = words [ 3 ] ; } else { description = words [ 1 ] ; } String unit = words [ 2 ] ; if ( unit != null ) { unit = unit . replaceAll ( \"\\\\*\\\\*\" , \"\" ) ; if ( unit . equals ( \"-\" ) ) { unit = \"\" ; } } int decimalScale ; try { decimalScale = Integer . parseInt ( words [ 4 ] . trim ( ) ) ; } catch ( NumberFormatException ne ) { decimalScale = 0 ; } return new GempakParameter ( num , name , description , unit , decimalScale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the parameter for the given name [CODESPLIT] public GempakParameter getParameter ( String name ) { GempakParameter param = paramMap . get ( name ) ; if ( param == null ) { // try the regex list\r Set < String > keys = templateParamMap . keySet ( ) ; if ( ! keys . isEmpty ( ) ) { for ( String key : keys ) { Pattern p = Pattern . compile ( key ) ; Matcher m = p . matcher ( name ) ; if ( m . matches ( ) ) { //System.out.println(\"found match \" + key + \" for \" + name);\r String value = m . group ( 1 ) ; GempakParameter match = templateParamMap . get ( key ) ; param = new GempakParameter ( match . getNumber ( ) , name , match . getDescription ( ) + \" (\" + value + \" hour)\" , match . getUnit ( ) , match . getDecimalScale ( ) ) ; paramMap . put ( name , param ) ; break ; } } } } return param ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test [CODESPLIT] public static void main ( String [ ] args ) throws IOException { GempakParameterTable pt = new GempakParameterTable ( ) ; //pt.addParameters(\"resources/nj22/tables/gempak/wmogrib3.tbl\");\r pt . addParameters ( \"resources/nj22/tables/gempak/params.tbl\" ) ; if ( args . length > 0 ) { String param = args [ 0 ] ; GempakParameter parm = pt . getParameter ( param ) ; if ( parm != null ) { System . out . println ( \"Found \" + param + \": \" + parm ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in the bytes from the given InputStream and construct and return a String . Closes the InputStream argument . [CODESPLIT] private String readContents ( InputStream is ) throws IOException { return new String ( readBytes ( is ) , CDM . utf8Charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the bytes in the given input stream . [CODESPLIT] private byte [ ] readBytes ( InputStream is ) throws IOException { int totalRead = 0 ; byte [ ] content = new byte [ 1000000 ] ; while ( true ) { int howMany = is . read ( content , totalRead , content . length - totalRead ) ; if ( howMany < 0 ) { break ; } if ( howMany == 0 ) { continue ; } totalRead += howMany ; if ( totalRead >= content . length ) { byte [ ] tmp = content ; int newLength = ( ( content . length < 25000000 ) ? content . length * 2 : content . length + 5000000 ) ; content = new byte [ newLength ] ; System . arraycopy ( tmp , 0 , content , 0 , totalRead ) ; } } is . close ( ) ; byte [ ] results = new byte [ totalRead ] ; System . arraycopy ( content , 0 , results , 0 , totalRead ) ; return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the input stream to the given resource [CODESPLIT] private InputStream getInputStream ( String resourceName ) throws IOException { // Try class loader to get resource\r ClassLoader cl = GempakParameterTable . class . getClassLoader ( ) ; InputStream s = cl . getResourceAsStream ( resourceName ) ; if ( s != null ) { return s ; } //Try the file system\r File f = new File ( resourceName ) ; if ( f . exists ( ) ) { s = new FileInputStream ( f ) ; } if ( s != null ) { return s ; } //Try it as a url\r Matcher m = Pattern . compile ( \" \" ) . matcher ( resourceName ) ; String encodedUrl = m . replaceAll ( \"%20\" ) ; URL dataUrl = new URL ( encodedUrl ) ; URLConnection connection = dataUrl . openConnection ( ) ; return connection . getInputStream ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : defaultPointMetadata / wml2 : DefaultTVPMeasurementMetadata / wml2 : uom [CODESPLIT] public static UnitReference initUom ( UnitReference uom , VariableSimpleIF dataVar ) { // @code String udunits = dataVar . getUnitsString ( ) ; if ( udunits == null ) { // Variable may not have a \"units\" attribute. return null ; } String ucum = ErddapEDUnits . udunitsToUcum ( udunits ) ; uom . setCode ( ucum ) ; return uom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] protected static double getMetersConversionFactor ( String unitsString ) throws Exception { SimpleUnit unit = SimpleUnit . factoryWithExceptions ( unitsString ) ; return unit . convertTo ( 1.0 , SimpleUnit . meterUnit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] public String getDetailInfo ( ) { StringBuffer sbuff = new StringBuffer ( ) ; sbuff . append ( \"TrajectoryObsDataset\\n\" ) ; sbuff . append ( \"  adapter   = \" + getClass ( ) . getName ( ) + \"\\n\" ) ; sbuff . append ( \"  trajectories:\" + \"\\n\" ) ; for ( Iterator it = this . getTrajectoryIds ( ) . iterator ( ) ; it . hasNext ( ) ; ) { sbuff . append ( \"      \" + ( String ) it . next ( ) + \"\\n\" ) ; } sbuff . append ( super . getDetailInfo ( ) ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] public boolean syncExtend ( ) { if ( ! this . netcdfDataset . hasUnlimitedDimension ( ) ) { return false ; } try { if ( ! this . netcdfDataset . syncExtend ( ) ) { return false ; } } catch ( IOException e ) { return false ; } // Update number of points in this TrajectoryObsDataset and in the child TrajectoryObsDatatype. int newNumPoints = this . trajectoryDim . getLength ( ) ; if ( this . trajectoryNumPoint >= newNumPoints ) { return false ; } this . trajectoryNumPoint = newNumPoints ; ( ( Trajectory ) this . trajectory ) . setNumPoints ( this . trajectoryNumPoint ) ; // Update end date in this TrajectoryObsDataset and in the child TrajectoryObsDatatype. try { endDate = trajectory . getTime ( trajectoryNumPoint - 1 ) ; } catch ( IOException e ) { return false ; } ( ( Trajectory ) trajectory ) . setEndDate ( endDate ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "but we can define a stronger contract . [CODESPLIT] @ Override public PointFeature next ( ) throws NoSuchElementException { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( \"The iteration has no more elements.\" ) ; } PointFeature pointFeat = pointIter . next ( ) ; assert pointFeat != null : \"hasNext() should have been false. WTF?\" ; calcBounds ( pointFeat ) ; return pointFeat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the level values from the specifications [CODESPLIT] protected double [ ] makeLevelValues ( ) { double [ ] vals = new double [ getSize ( ) ] ; for ( int i = 0 ; i < getSize ( ) ; i ++ ) { vals [ i ] = i ; } return vals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the ensemble template parameter in a filename [CODESPLIT] public String replaceFileTemplate ( String filespec , int ensIndex ) { return filespec . replaceAll ( ENS_TEMPLATE_ID , getEnsembleNames ( ) . get ( ensIndex ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set extra information used by station obs datasets . [CODESPLIT] public void setStationInfo ( String stnIdVName , String stnDescVName ) { this . stnIdVName = stnIdVName ; this . stnDescVName = stnDescVName ; Variable stationVar = ncfile . findVariable ( stnIdVName ) ; stationIdType = stationVar . getDataType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This reads through all the records in the dataset and constructs a list of RecordPointObs or RecordStationObs . It does not cache the data . <p > If stnIdVName is not null its a StationDataset then construct a Station HashMap of StationImpl objects . Add the RecordStationObs into the list of obs for that station . [CODESPLIT] public ArrayList readAllCreateObs ( CancelTask cancel ) throws IOException { // see if its a station or point dataset boolean hasStations = stnIdVName != null ; if ( hasStations ) stnHash = new HashMap < Object , ucar . unidata . geoloc . Station > ( ) ; // get min and max date and lat,lon double minDate = Double . MAX_VALUE ; double maxDate = - Double . MAX_VALUE ; double minLat = Double . MAX_VALUE ; double maxLat = - Double . MAX_VALUE ; double minLon = Double . MAX_VALUE ; double maxLon = - Double . MAX_VALUE ; // read all the data, create a RecordObs ArrayList records = new ArrayList ( ) ; int recno = 0 ; try ( StructureDataIterator ii = recordVar . getStructureIterator ( ) ) { while ( ii . hasNext ( ) ) { StructureData sdata = ii . next ( ) ; StructureMembers members = sdata . getStructureMembers ( ) ; Object stationId = null ; if ( hasStations ) { if ( stationIdType == DataType . INT ) { int stationNum = sdata . getScalarInt ( stnIdVName ) ; stationId = new Integer ( stationNum ) ; } else stationId = sdata . getScalarString ( stnIdVName ) . trim ( ) ; } String desc = ( stnDescVName == null ) ? null : sdata . getScalarString ( stnDescVName ) ; double lat = sdata . convertScalarDouble ( latVName ) ; double lon = sdata . convertScalarDouble ( lonVName ) ; double alt = ( altVName == null ) ? Double . NaN : altScaleFactor * sdata . convertScalarDouble ( altVName ) ; double obsTime = sdata . convertScalarDouble ( members . findMember ( obsTimeVName ) ) ; double nomTime = ( nomTimeVName == null ) ? obsTime : sdata . convertScalarDouble ( members . findMember ( nomTimeVName ) ) ; //double obsTime = sdata.convertScalarDouble( members.findMember( obsTimeVName) ); //double nomTime = (nomTimeVName == null) ? obsTime : sdata.convertScalarDouble( members.findMember( nomTimeVName)); if ( hasStations ) { StationImpl stn = ( StationImpl ) stnHash . get ( stationId ) ; if ( stn == null ) { stn = new StationImpl ( stationId . toString ( ) , desc , lat , lon , alt ) ; stnHash . put ( stationId , stn ) ; } RecordStationObs stnObs = new RecordStationObs ( stn , obsTime , nomTime , recno ) ; records . add ( stnObs ) ; stn . addObs ( stnObs ) ; } else { records . add ( new RecordPointObs ( new ucar . unidata . geoloc . EarthLocationImpl ( lat , lon , alt ) , obsTime , nomTime , recno ) ) ; } // track date range and bounding box minDate = Math . min ( minDate , obsTime ) ; maxDate = Math . max ( maxDate , obsTime ) ; minLat = Math . min ( minLat , lat ) ; maxLat = Math . max ( maxLat , lat ) ; minLon = Math . min ( minLon , lon ) ; maxLon = Math . max ( maxLon , lon ) ; recno ++ ; if ( ( cancel != null ) && cancel . isCancel ( ) ) return null ; } } boundingBox = new LatLonRect ( new LatLonPointImpl ( minLat , minLon ) , new LatLonPointImpl ( maxLat , maxLon ) ) ; return records ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register for PropertyChange events when the value of the Field changes . When accept () is called you will get a new PropertyChangeEvent ( this fldName oldValue newValue ) where the oldValue newValue will be String Integer Boolean etc . [CODESPLIT] public void addPropertyChangeListener ( PropertyChangeListener pcl ) { if ( listenerList == null ) listenerList = new javax . swing . event . EventListenerList ( ) ; listenerList . add ( PropertyChangeListener . class , pcl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if edit value is valid put error message in buff . [CODESPLIT] protected boolean validate ( StringBuffer buff ) { if ( ! _validate ( buff ) ) return false ; Object editValue = getEditValue ( ) ; if ( editValue == null ) return false ; for ( FieldValidator v : validators ) { if ( ! v . validate ( this , editValue , buff ) ) return false ; } if ( acceptIfDifferent ( editValue ) ) { setEditValue ( validValue ) ; sendEvent ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get current value from editComponent save to store . If different from old value fire PropertyChangeEvent . Return false if invalid format add error message to buff if not null . [CODESPLIT] protected boolean accept ( StringBuffer buff ) { if ( ! validate ( buff ) ) { validate ( buff ) ; return false ; } if ( acceptIfDifferent ( getEditValue ( ) ) ) { setStoreValue ( validValue ) ; sendEvent ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if this value is different from current accepted value ( using equals () ) ; If so set old value to accepted value then accepted value to this value . [CODESPLIT] protected boolean acceptIfDifferent ( Object newValue ) { // System.out.println(\"isDifferent \"+newValue+\" \"+value);\r if ( ( newValue == null ) && ( validValue == null ) ) return false ; if ( ( validValue != null ) && validValue . equals ( newValue ) ) return false ; previousValue = getValue ( ) ; validValue = newValue ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get value from store put value into editComponent [CODESPLIT] protected void restoreValue ( Object defValue ) { if ( storeData != null ) { validValue = getStoreValue ( defValue ) ; setEditValue ( validValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The value in the store has changed : update the edit component send event if its different from previous [CODESPLIT] protected void setNewValueFromStore ( ) { Object newValue = getStoreValue ( validValue ) ; if ( acceptIfDifferent ( newValue ) ) { setEditValue ( newValue ) ; sendEvent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "send PropertyChangeEvent [CODESPLIT] protected void sendEvent ( ) { if ( listenerList != null ) { PropertyChangeEvent event = new PropertyChangeEvent ( this , name , previousValue , getValue ( ) ) ; Object [ ] listeners = listenerList . getListenerList ( ) ; for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 )  ( ( PropertyChangeListener ) listeners [ i + 1 ] ) . propertyChange ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "An integer input field with an associated CDM . UNITS label . [CODESPLIT] static private void showFormatInfo ( JFormattedTextField tf ) { JFormattedTextField . AbstractFormatter ff = tf . getFormatter ( ) ; System . out . println ( \"AbstractFormatter  \" + ff . getClass ( ) . getName ( ) ) ; if ( ff instanceof NumberFormatter ) { NumberFormatter nf = ( NumberFormatter ) ff ; Format f = nf . getFormat ( ) ; System . out . println ( \" Format  = \" + f . getClass ( ) . getName ( ) ) ; if ( f instanceof NumberFormat ) { NumberFormat nfat = ( NumberFormat ) f ; System . out . println ( \" getMinimumIntegerDigits=\" + nfat . getMinimumIntegerDigits ( ) ) ; System . out . println ( \" getMaximumIntegerDigits=\" + nfat . getMaximumIntegerDigits ( ) ) ; System . out . println ( \" getMinimumFractionDigits=\" + nfat . getMinimumFractionDigits ( ) ) ; System . out . println ( \" getMaximumFractionDigits=\" + nfat . getMaximumFractionDigits ( ) ) ; } if ( f instanceof DecimalFormat ) { DecimalFormat df = ( DecimalFormat ) f ; System . out . println ( \" Pattern  = \" + df . toPattern ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This dorks with Double . toString () : [CODESPLIT] private static String formatDouble ( double d , int min_sigFigs , int fixed_decimals ) { String s = java . lang . Double . toString ( d ) ; if ( java . lang . Double . isNaN ( d ) ) return s ; // extract the sign\r String sign ; String unsigned ; if ( s . startsWith ( \"-\" ) || s . startsWith ( \"+\" ) ) { sign = s . substring ( 0 , 1 ) ; unsigned = s . substring ( 1 ) ; } else { sign = \"\" ; unsigned = s ; } // deal with exponential notation\r String mantissa ; String exponent ; int eInd = unsigned . indexOf ( ' ' ) ; if ( eInd == - 1 ) eInd = unsigned . indexOf ( ' ' ) ; if ( eInd == - 1 ) { mantissa = unsigned ; exponent = \"\" ; } else { mantissa = unsigned . substring ( 0 , eInd ) ; exponent = unsigned . substring ( eInd ) ; } // deal with decimal point\r StringBuffer number , fraction ; int dotInd = mantissa . indexOf ( ' ' ) ; if ( dotInd == - 1 ) { number = new StringBuffer ( mantissa ) ; fraction = new StringBuffer ( \"\" ) ; } else { number = new StringBuffer ( mantissa . substring ( 0 , dotInd ) ) ; fraction = new StringBuffer ( mantissa . substring ( dotInd + 1 ) ) ; } // number of significant figures\r int numFigs = number . length ( ) ; int fracFigs = fraction . length ( ) ; // can do either fixed_decimals or min_sigFigs\r if ( fixed_decimals != - 1 ) { if ( fixed_decimals == 0 ) { fraction . setLength ( 0 ) ; } else if ( fixed_decimals > fracFigs ) { int want = fixed_decimals - fracFigs ; for ( int i = 0 ; i < want ; i ++ ) fraction . append ( \"0\" ) ; } else if ( fixed_decimals < fracFigs ) { int chop = fracFigs - fixed_decimals ; // LOOK should round !!\r fraction . setLength ( fraction . length ( ) - chop ) ; } fracFigs = fixed_decimals ; } else { // Don't count leading zeros in the fraction, if no number\r if ( ( numFigs == 0 || number . toString ( ) . equals ( \"0\" ) ) && fracFigs > 0 ) { numFigs = 0 ; number = new StringBuffer ( \"\" ) ; for ( int i = 0 ; i < fraction . length ( ) ; ++ i ) { if ( fraction . charAt ( i ) != ' ' ) break ; -- fracFigs ; } } // Don't count trailing zeroes in the number if no fraction\r if ( ( fracFigs == 0 ) && numFigs > 0 ) { for ( int i = number . length ( ) - 1 ; i > 0 ; i -- ) { if ( number . charAt ( i ) != ' ' ) break ; -- numFigs ; } } // deal with min sig figures\r int sigFigs = numFigs + fracFigs ; if ( sigFigs > min_sigFigs ) { // Want fewer figures in the fraction; chop (should round? )\r int chop = Math . min ( sigFigs - min_sigFigs , fracFigs ) ; fraction . setLength ( fraction . length ( ) - chop ) ; fracFigs -= chop ; } } /*int sigFigs = numFigs + fracFigs;\r\n    if (sigFigs > max_sigFigs) {\r\n\r\n      if (numFigs >= max_sigFigs) {  // enough sig figs in just the number part\r\n        fraction.setLength( 0 );\r\n        for ( int i=max_sigFigs; i<numFigs; ++i )\r\n          number.setCharAt( i, '0' );  // should round?\r\n      } else {\r\n\r\n        // Want fewer figures in the fraction; chop (should round? )\r\n        int chop = sigFigs - max_sigFigs;\r\n        fraction.setLength( fraction.length() - chop );\r\n      }\r\n    }\r\n\r\n\r\n    /* may want a fixed decimal place\r\n    if (dec_places != -1) {\r\n\r\n      if (dec_places == 0) {\r\n        fraction.setLength( 0 );\r\n        fracFigs = 0;\r\n      } else if (dec_places > fracFigs) {\r\n        int want = dec_places - fracFigs;\r\n        for (int i=0; i<want; i++)\r\n          fraction.append(\"0\");\r\n      } else if (dec_places < fracFigs) {\r\n        int chop = fracFigs - dec_places;\r\n        fraction.setLength( fraction.length() - chop );\r\n        fracFigs = dec_places;\r\n      }\r\n\r\n    } */ if ( fraction . length ( ) == 0 ) return sign + number + exponent ; else return sign + number + \".\" + fraction + exponent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the bit map array . [CODESPLIT] @ Nullable public byte [ ] getBitmap ( RandomAccessFile raf ) throws IOException { // no bitMap\r if ( bitMapIndicator == 255 ) return null ; // LOOK: bitMapIndicator=254 == previously defined bitmap\r if ( bitMapIndicator == 254 ) logger . debug ( \"HEY bitMapIndicator=254 previously defined bitmap\" ) ; if ( bitMapIndicator != 0 ) { throw new UnsupportedOperationException ( \"Grib2 Bit map section pre-defined (provided by center) = \" + bitMapIndicator ) ; } raf . seek ( startingPosition ) ; int length = GribNumbers . int4 ( raf ) ; raf . skipBytes ( 2 ) ; byte [ ] data = new byte [ length - 6 ] ; raf . readFully ( data ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Catalog { uint64 catId = 1 ; // sequence no string catLocation = 2 ; bool isRoot = 3 ; uint64 lastRead = 4 ; } [CODESPLIT] public void writeExternal ( DataOutputStream out ) throws IOException { ConfigCatalogExtProto . Catalog . Builder builder = ConfigCatalogExtProto . Catalog . newBuilder ( ) ; builder . setCatId ( catId ) ; builder . setCatLocation ( catRelLocation ) ; builder . setIsRoot ( isRoot ) ; builder . setLastRead ( lastRead ) ; ConfigCatalogExtProto . Catalog index = builder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; out . writeInt ( b . length ) ; out . write ( b ) ; total_count ++ ; total_nbytes += b . length + 4 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the known DataFormatType that matches the given name ( ignoring case ) or null if the name is unknown . [CODESPLIT] public static DataFormatType findType ( String name ) { if ( name == null ) return null ; for ( DataFormatType m : members ) { if ( m . name . equalsIgnoreCase ( name ) ) return m ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a DataFormatType for the given name by either matching a known type ( ignoring case ) or creating an unknown type . [CODESPLIT] public static DataFormatType getType ( String name ) { if ( name == null ) return null ; DataFormatType t = findType ( name ) ; return t != null ? t : new DataFormatType ( name , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gml : Point [CODESPLIT] public static PointType initPoint ( PointType point , StationTimeSeriesFeature stationFeat ) { // @gml:id String id = MarshallingUtil . createIdForType ( PointType . class ) ; point . setId ( id ) ; // gml:pos NcDirectPositionType . initPos ( point . addNewPos ( ) , stationFeat ) ; return point ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "allow calling from outside [CODESPLIT] public void setNetcdfFile ( NetcdfFile ncf ) { this . ncfile = ncf ; this . filename = ncf . getLocation ( ) ; final GetDataRunnable runner = new GetDataRunnable ( ) { public void run ( Object o ) throws IOException { final StringWriter sw = new StringWriter ( 50000 ) ; NCdumpW . print ( ncfile , command , sw , task ) ; result = sw . toString ( ) ; } } ; task = new GetDataTask ( runner , filename , null ) ; stopButton . startProgressMonitorTask ( task ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 1 ) single runtime 1a timeOffset 1b time or timeRange 1c none = constant runtime dataset 2 ) multiple runtimes 2a timeOffset = constant offset dataset 2b time ( not range ) = constant forecast dataset [CODESPLIT] public Optional < List < CoverageCoordAxis > > subset ( SubsetParams params , AtomicBoolean isConstantForcast , boolean makeCFcompliant ) { List < CoverageCoordAxis > result = new ArrayList <> ( ) ; Optional < CoverageCoordAxis > axiso = runAxis . subset ( params ) ; if ( ! axiso . isPresent ( ) ) return Optional . empty ( axiso . getErrorMessage ( ) ) ; CoverageCoordAxis1D runAxisSubset = ( CoverageCoordAxis1D ) axiso . get ( ) ; result . add ( runAxisSubset ) ; // subset on timeOffset (1a, 1c, 2a) if ( params . hasTimeOffsetParam ( ) || ! params . hasTimeParam ( ) ) { axiso = timeOffset . subset ( params ) ; if ( ! axiso . isPresent ( ) ) return Optional . empty ( axiso . getErrorMessage ( ) ) ; CoverageCoordAxis timeOffsetSubset = axiso . get ( ) ; result . add ( timeOffsetSubset ) ; if ( makeCFcompliant ) // add a time cordinate result . add ( makeCFTimeCoord ( runAxisSubset , ( CoverageCoordAxis1D ) timeOffsetSubset ) ) ; // possible the twoD time case, if nruns > 1 return Optional . of ( result ) ; } // subset on time, # runtimes = 1 (1b) if ( runAxisSubset . getNcoords ( ) == 1 ) { double val = runAxisSubset . getCoordMidpoint ( 0 ) ; // not sure runAxis is needed. maybe use runtimeSubset CalendarDate runDate = runAxisSubset . makeDate ( val ) ; Optional < TimeOffsetAxis > too = timeOffset . subsetFromTime ( params , runDate ) ; if ( ! too . isPresent ( ) ) return Optional . empty ( too . getErrorMessage ( ) ) ; TimeOffsetAxis timeOffsetSubset = too . get ( ) ; result . add ( timeOffsetSubset ) ; if ( makeCFcompliant ) result . add ( makeCFTimeCoord ( runAxisSubset , timeOffsetSubset ) ) ; return Optional . of ( result ) ; } // tricky case 2b time (point only not range) = constant forecast dataset // data reader has to skip around the 2D times // 1) the runtimes may be subset by whats available // 2) timeOffset could become an aux coordinate // 3) time coordinate becomes a scalar, isConstantForcast . set ( true ) ; CalendarDate dateWanted ; if ( params . isTrue ( SubsetParams . timePresent ) ) dateWanted = CalendarDate . present ( ) ; else dateWanted = ( CalendarDate ) params . get ( SubsetParams . time ) ; if ( dateWanted == null ) throw new IllegalStateException ( \"Must have time parameter\" ) ; double wantOffset = runAxisSubset . convert ( dateWanted ) ; // forecastDate offset from refdate double start = timeOffset . getStartValue ( ) ; double end = timeOffset . getEndValue ( ) ; CoordAxisHelper helper = new CoordAxisHelper ( timeOffset ) ; // brute force search LOOK specialize for regular ? List < Integer > runtimeIdx = new ArrayList <> ( ) ; // list of runtime indexes that have this forecast // List<Integer> offsetIdx = new ArrayList<>();  // list of offset indexes that have this forecast List < Double > offset = new ArrayList <> ( ) ; // corresponding offset from start of run for ( int i = 0 ; i < runAxisSubset . getNcoords ( ) ; i ++ ) { // public double getOffsetInTimeUnits(CalendarDate convertFrom, CalendarDate convertTo); double runOffset = runAxisSubset . getCoordMidpoint ( i ) ; if ( end + runOffset < wantOffset ) continue ; if ( wantOffset < start + runOffset ) break ; int idx = helper . search ( wantOffset - runOffset ) ; if ( idx >= 0 ) { runtimeIdx . add ( i ) ; // the ith runtime // offsetIdx.add(idx);   // the idx time offset offset . add ( wantOffset - runOffset ) ; // the offset from the runtime } } // here are the runtimes int ncoords = runtimeIdx . size ( ) ; double [ ] runValues = new double [ ncoords ] ; double [ ] offsetValues = new double [ ncoords ] ; int count = 0 ; for ( int k = 0 ; k < ncoords ; k ++ ) { offsetValues [ count ] = offset . get ( k ) ; runValues [ count ++ ] = runAxisSubset . getCoordMidpoint ( runtimeIdx . get ( k ) ) ; } CoverageCoordAxisBuilder runbuilder = new CoverageCoordAxisBuilder ( runAxisSubset ) . subset ( null , CoverageCoordAxis . Spacing . irregularPoint , ncoords , runValues ) ; // LOOK check for regular (in CovCoordAxis ?) CoverageCoordAxis1D runAxisSubset2 = new CoverageCoordAxis1D ( runbuilder ) ; CoverageCoordAxisBuilder timebuilder = new CoverageCoordAxisBuilder ( timeOffset ) . subset ( runAxisSubset2 . getName ( ) , CoverageCoordAxis . Spacing . irregularPoint , ncoords , offsetValues ) ; // aux coord (LOOK interval) ?? CoverageCoordAxis1D timeOffsetSubset = new TimeOffsetAxis ( timebuilder ) ; CoverageCoordAxis scalarTimeCoord = makeScalarTimeCoord ( wantOffset , runAxisSubset ) ; // nothing needed for CF, the run coordinate acts as the CF time independent coord. timeOffset is aux, forecastTime is scalar return Optional . of ( Lists . newArrayList ( runAxisSubset2 , timeOffsetSubset , scalarTimeCoord ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( addName ) pw . print ( \", \" ) ; pw . print ( ( new Float ( getValue ( ) ) ) . toString ( ) ) ; if ( newLine ) pw . print ( \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debugging flags . This is a way to decouple setting flags from particular implementations . [CODESPLIT] static public void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugCE = debugFlag . isSet ( \"DODS/constraintExpression\" ) ; debugServerCall = debugFlag . isSet ( \"DODS/serverCall\" ) ; debugOpenResult = debugFlag . isSet ( \"DODS/debugOpenResult\" ) ; debugDataResult = debugFlag . isSet ( \"DODS/debugDataResult\" ) ; debugCharArray = debugFlag . isSet ( \"DODS/charArray\" ) ; debugConstruct = debugFlag . isSet ( \"DODS/constructNetcdf\" ) ; debugPreload = debugFlag . isSet ( \"DODS/preload\" ) ; debugTime = debugFlag . isSet ( \"DODS/timeCalls\" ) ; showNCfile = debugFlag . isSet ( \"DODS/showNCfile\" ) ; debugAttributes = debugFlag . isSet ( \"DODS/attributes\" ) ; debugCached = debugFlag . isSet ( \"DODS/cache\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the canonical form of the URL . If the urlName starts with http : or https : change it to start with dods : otherwise leave it alone . [CODESPLIT] public static String canonicalURL ( String urlName ) { if ( urlName . startsWith ( \"http:\" ) ) return \"dods:\" + urlName . substring ( 5 ) ; if ( urlName . startsWith ( \"https:\" ) ) return \"dods:\" + urlName . substring ( 6 ) ; return urlName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * parse the DDS creating a tree of DodsV objects private ArrayList parseDDS ( DDS dds ) throws IOException { ArrayList dodsVlist = new ArrayList () ; [CODESPLIT] private void parseGlobalAttributes ( DAS das , DodsV root , DODSNetcdfFile dodsfile ) { List < DODSAttribute > atts = root . attributes ; for ( ucar . nc2 . Attribute ncatt : atts ) { rootGroup . addAttribute ( ncatt ) ; } // loop over attribute tables, collect global attributes Enumeration tableNames = das . getNames ( ) ; while ( tableNames . hasMoreElements ( ) ) { String tableName = ( String ) tableNames . nextElement ( ) ; AttributeTable attTable = das . getAttributeTableN ( tableName ) ; if ( attTable == null ) continue ; // should probably never happen /* if (tableName.equals(\"NC_GLOBAL\") || tableName.equals(\"HDF_GLOBAL\")) {\n        java.util.Enumeration attNames = attTable.getNames();\n        while (attNames.hasMoreElements()) {\n          String attName = (String) attNames.nextElement();\n          dods.dap.Attribute att = attTable.getAttribute(attName);\n\n          DODSAttribute ncatt = new DODSAttribute( attName, att);\n          addAttribute( null, ncatt);\n        }\n\n          } else */ if ( tableName . equals ( \"DODS_EXTRA\" ) ) { Enumeration attNames = attTable . getNames ( ) ; while ( attNames . hasMoreElements ( ) ) { String attName = ( String ) attNames . nextElement ( ) ; if ( attName . equals ( \"Unlimited_Dimension\" ) ) { opendap . dap . Attribute att = attTable . getAttribute ( attName ) ; DODSAttribute ncatt = new DODSAttribute ( attName , att ) ; setUnlimited ( ncatt . getStringValue ( ) ) ; } else logger . warn ( \" Unknown DODS_EXTRA attribute = \" + attName + \" \" + location ) ; } } else if ( tableName . equals ( \"EXTRA_DIMENSION\" ) ) { Enumeration attNames = attTable . getNames ( ) ; while ( attNames . hasMoreElements ( ) ) { String attName = ( String ) attNames . nextElement ( ) ; opendap . dap . Attribute att = attTable . getAttribute ( attName ) ; DODSAttribute ncatt = new DODSAttribute ( attName , att ) ; int length = ncatt . getNumericValue ( ) . intValue ( ) ; Dimension extraDim = new Dimension ( attName , length ) ; addDimension ( null , extraDim ) ; } } /* else if (null == root.findDodsV( tableName, false)) {\n  addAttributes(attTable.getName(), attTable);\n      } */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Go thru the variables / structure - variables and their attributes and move to the proper groups . [CODESPLIT] protected void reGroup ( ) throws DAP2Exception { assert ( RC . getUseGroups ( ) ) ; Group rootgroup = this . getRootGroup ( ) ; // Start by moving global attributes // An issue to be addressed is that some attributes that should be attached // to variables, instead get made global with name var.att. Object [ ] gattlist = rootgroup . getAttributes ( ) . toArray ( ) ; for ( Object att : gattlist ) { Attribute ncatt = ( Attribute ) att ; String dodsname = ncatt . getDODSName ( ) ; NamePieces pieces = parseName ( dodsname ) ; if ( pieces . var != null ) { // Figure out which variable to which this attribute should be moved. // In the event that there is no matching // variable, then keep the attribute as is. String searchname = pieces . var ; if ( pieces . prefix != null ) searchname = pieces . prefix + ' ' + searchname ; Variable v = findVariable ( searchname ) ; if ( v != null ) { // move attribute rootgroup . remove ( ncatt ) ; v . addAttribute ( ncatt ) ; // change attribute name to remove var. String newname = pieces . name ; ncatt . setName ( newname ) ; } } else if ( pieces . prefix != null ) { // We have a true group global name to move to proper group // convert prefix to an actual group Group g = rootgroup . makeRelativeGroup ( this , dodsname , true ) ; rootgroup . remove ( ncatt ) ; g . addAttribute ( ncatt ) ; if ( OLDGROUPCODE ) { ncatt . setName ( pieces . name ) ; } } } Object [ ] varlist = rootgroup . getVariables ( ) . toArray ( ) ; if ( false ) { // This should have been done by computegroup() // Now move variables for ( Object var : varlist ) { if ( var instanceof DODSVariable ) { DODSVariable v = ( DODSVariable ) var ; reGroupVariable ( rootgroup , v ) ; } else throw new DAP2Exception ( \"regroup: unexpected variable type: \" + var . getClass ( ) . getCanonicalName ( ) ) ; } } // In theory, we should be able to fix variable attributes // by just removing the group prefix. However, there is the issue // that attribute names sometimes have as a suffix varname.attname. // So, we should use that to adjust the attribute to attach to that // variable. for ( Object var : varlist ) { reGroupVariableAttributes ( rootgroup , ( Variable ) var ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility to decompose a name [CODESPLIT] NamePieces parseName ( String name ) { NamePieces pieces = new NamePieces ( ) ; int dotpos = name . lastIndexOf ( ' ' ) ; int slashpos = name . lastIndexOf ( ' ' ) ; if ( slashpos < 0 && dotpos < 0 ) { pieces . name = name ; } else if ( slashpos >= 0 && dotpos < 0 ) { pieces . prefix = name . substring ( 0 , slashpos ) ; pieces . name = name . substring ( slashpos + 1 , name . length ( ) ) ; } else if ( slashpos < 0 && dotpos >= 0 ) { pieces . var = name . substring ( 0 , dotpos ) ; pieces . name = name . substring ( dotpos + 1 , name . length ( ) ) ; } else { //slashpos >= 0 && dotpos >= 0) if ( slashpos > dotpos ) { pieces . prefix = name . substring ( 0 , slashpos ) ; pieces . name = name . substring ( slashpos + 1 , name . length ( ) ) ; } else { //slashpos < dotpos) pieces . prefix = name . substring ( 0 , slashpos ) ; pieces . var = name . substring ( slashpos + 1 , dotpos ) ; pieces . name = name . substring ( dotpos + 1 , name . length ( ) ) ; } } // fixup if ( pieces . prefix != null && pieces . prefix . length ( ) == 0 ) pieces . prefix = null ; if ( pieces . var != null && pieces . var . length ( ) == 0 ) pieces . var = null ; if ( pieces . name . length ( ) == 0 ) pieces . name = null ; return pieces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void constructTopVariables ( DodsV rootDodsV , CancelTask cancelTask ) throws IOException { List < DodsV > topVariables = rootDodsV . children ; for ( DodsV dodsV : topVariables ) { if ( dodsV . bt instanceof DConstructor ) continue ; addVariable ( rootGroup , null , dodsV ) ; if ( cancelTask != null && cancelTask . isCancel ( ) ) return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recursively make new variables : all new variables come through here [CODESPLIT] Variable addVariable ( Group parentGroup , Structure parentStructure , DodsV dodsV ) throws IOException { Variable v = makeVariable ( parentGroup , parentStructure , dodsV ) ; if ( v != null ) { addAttributes ( v , dodsV ) ; if ( parentStructure != null ) parentStructure . addMemberVariable ( v ) ; else { parentGroup = computeGroup ( v . getDODSName ( ) , v , parentGroup ) ; parentGroup . addVariable ( v ) ; } dodsV . isDone = true ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make a structure into a group if its scalar and all parents are groups [CODESPLIT] private boolean isGroup ( DStructure dstruct ) { BaseType parent = ( BaseType ) dstruct . getParent ( ) ; if ( parent == null ) return true ; if ( parent instanceof DStructure ) return isGroup ( ( DStructure ) parent ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void addAttributes ( String tableName AttributeTable attTable ) { [CODESPLIT] private void addAttributes ( Variable v , DodsV dodsV ) { List < DODSAttribute > atts = dodsV . attributes ; for ( Attribute ncatt : atts ) { v . addAttribute ( ncatt ) ; } // this is the case where its (probably) a Grid, and so _Coordinate.Axes has been assigned, but if // theres also a coordinates attribute, need to add that info Attribute axes = v . findAttribute ( CF . COORDINATES ) ; Attribute _axes = v . findAttribute ( _Coordinate . Axes ) ; if ( ( null != axes ) && ( null != _axes ) ) { v . addAttribute ( combineAxesAttrs ( axes , _axes ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if this is netcdf char array . [CODESPLIT] Dimension getNetcdfStrlenDim ( DODSVariable v ) { AttributeTable table = das . getAttributeTableN ( v . getFullName ( ) ) ; // LOOK this probably doesnt work for nested variables if ( table == null ) return null ; opendap . dap . Attribute dodsAtt = table . getAttribute ( \"DODS\" ) ; if ( dodsAtt == null ) return null ; AttributeTable dodsTable = dodsAtt . getContainerN ( ) ; if ( dodsTable == null ) return null ; opendap . dap . Attribute att = dodsTable . getAttribute ( \"strlen\" ) ; if ( att == null ) return null ; String strlen = att . getValueAtN ( 0 ) ; opendap . dap . Attribute att2 = dodsTable . getAttribute ( \"dimName\" ) ; String dimName = ( att2 == null ) ? null : att2 . getValueAtN ( 0 ) ; if ( debugCharArray ) System . out . println ( v . getFullName ( ) + \" has strlen= \" + strlen + \" dimName= \" + dimName ) ; int dimLength ; try { dimLength = Integer . parseInt ( strlen ) ; } catch ( NumberFormatException e ) { logger . warn ( \"DODSNetcdfFile \" + location + \" var = \" + v . getFullName ( ) + \" error on strlen attribute = \" + strlen ) ; return null ; } if ( dimLength <= 0 ) return null ; // LOOK what about unlimited ?? return new Dimension ( dimName , dimLength , dimName != null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If an equivilent shared dimension already exists use it else add d to shared dimensions . Equivilent is same name and length . [CODESPLIT] Dimension getSharedDimension ( Group group , Dimension d ) { if ( d . getShortName ( ) == null ) return d ; if ( group == null ) group = rootGroup ; for ( Dimension sd : group . getDimensions ( ) ) { if ( sd . getShortName ( ) . equals ( d . getShortName ( ) ) && sd . getLength ( ) == d . getLength ( ) ) return sd ; } d . setShared ( true ) ; group . addDimension ( d ) ; return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct list of dimensions to use [CODESPLIT] List < Dimension > constructDimensions ( Group group , opendap . dap . DArray dodsArray ) { if ( group == null ) group = rootGroup ; List < Dimension > dims = new ArrayList < Dimension > ( ) ; Enumeration enumerate = dodsArray . getDimensions ( ) ; while ( enumerate . hasMoreElements ( ) ) { opendap . dap . DArrayDimension dad = ( opendap . dap . DArrayDimension ) enumerate . nextElement ( ) ; String name = dad . getEncodedName ( ) ; if ( name != null ) name = StringUtil2 . unescape ( name ) ; Dimension myd ; if ( name == null ) { // if no name, make an anonymous dimension myd = new Dimension ( null , dad . getSize ( ) , false ) ; } else { // see if shared if ( RC . getUseGroups ( ) ) { if ( name . indexOf ( ' ' ) >= 0 ) { // place dimension in proper group group = group . makeRelativeGroup ( this , name , true ) ; // change our name name = name . substring ( name . lastIndexOf ( ' ' ) + 1 ) ; } } myd = group . findDimension ( name ) ; if ( myd == null ) { // add as shared myd = new Dimension ( name , dad . getSize ( ) ) ; group . addDimension ( myd ) ; } else if ( myd . getLength ( ) != dad . getSize ( ) ) { // make a non-shared dimension myd = new Dimension ( name , dad . getSize ( ) , false ) ; } // else use existing, shared dimension } dims . add ( myd ) ; // add it to the list } return dims ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "full name [CODESPLIT] private String makeDODSname ( DodsV dodsV ) { DodsV parent = dodsV . parent ; if ( parent . bt != null ) return ( makeDODSname ( parent ) + \".\" + dodsV . bt . getEncodedName ( ) ) ; return dodsV . bt . getEncodedName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the DODS data class corresponding to the Netcdf data type . This is the inverse of convertToNCType () . [CODESPLIT] static public int convertToDODSType ( DataType dataType ) { if ( dataType == DataType . STRING ) return opendap . dap . Attribute . STRING ; if ( dataType == DataType . BYTE ) return opendap . dap . Attribute . BYTE ; if ( dataType == DataType . FLOAT ) return opendap . dap . Attribute . FLOAT32 ; if ( dataType == DataType . DOUBLE ) return opendap . dap . Attribute . FLOAT64 ; if ( dataType == DataType . SHORT ) return opendap . dap . Attribute . INT16 ; if ( dataType == DataType . USHORT ) return opendap . dap . Attribute . UINT16 ; if ( dataType == DataType . INT ) return opendap . dap . Attribute . INT32 ; if ( dataType == DataType . UINT ) return opendap . dap . Attribute . UINT32 ; if ( dataType == DataType . BOOLEAN ) return opendap . dap . Attribute . BYTE ; if ( dataType == DataType . LONG ) return opendap . dap . Attribute . INT32 ; // LOOK no LONG type! // shouldnt happen return opendap . dap . Attribute . STRING ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Netcdf data type corresponding to the DODS data type . This is the inverse of convertToDODSType () . [CODESPLIT] static public DataType convertToNCType ( int dodsDataType , boolean isUnsigned ) { switch ( dodsDataType ) { case opendap . dap . Attribute . BYTE : return isUnsigned ? DataType . UBYTE : DataType . BYTE ; case opendap . dap . Attribute . FLOAT32 : return DataType . FLOAT ; case opendap . dap . Attribute . FLOAT64 : return DataType . DOUBLE ; case opendap . dap . Attribute . INT16 : return DataType . SHORT ; case opendap . dap . Attribute . UINT16 : return DataType . USHORT ; case opendap . dap . Attribute . INT32 : return DataType . INT ; case opendap . dap . Attribute . UINT32 : return DataType . UINT ; default : return DataType . STRING ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Netcdf data type corresponding to the DODS BaseType class . This is the inverse of convertToDODSType () . [CODESPLIT] static public DataType convertToNCType ( opendap . dap . BaseType dtype , boolean isUnsigned ) { if ( dtype instanceof DString ) return DataType . STRING ; else if ( ( dtype instanceof DStructure ) || ( dtype instanceof DSequence ) || ( dtype instanceof DGrid ) ) return DataType . STRUCTURE ; else if ( dtype instanceof DFloat32 ) return DataType . FLOAT ; else if ( dtype instanceof DFloat64 ) return DataType . DOUBLE ; else if ( dtype instanceof DUInt32 ) return DataType . UINT ; else if ( dtype instanceof DUInt16 ) return DataType . USHORT ; else if ( dtype instanceof DInt32 ) return DataType . INT ; else if ( dtype instanceof DInt16 ) return DataType . SHORT ; else if ( dtype instanceof DByte ) return isUnsigned ? DataType . UBYTE : DataType . BYTE ; else throw new IllegalArgumentException ( \"DODSVariable illegal type = \" + dtype . getTypeName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get whether this is an unsigned type . [CODESPLIT] static public boolean isUnsigned ( opendap . dap . BaseType dtype ) { return ( dtype instanceof DByte ) || ( dtype instanceof DUInt16 ) || ( dtype instanceof DUInt32 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This does the actual connection to the opendap server and reading of the data . All data calls go through here so we can add debugging . [CODESPLIT] DataDDS readDataDDSfromServer ( String CE ) throws IOException , opendap . dap . DAP2Exception { if ( debugServerCall ) System . out . println ( \"DODSNetcdfFile.readDataDDSfromServer = <\" + CE + \">\" ) ; long start = 0 ; if ( debugTime ) start = System . currentTimeMillis ( ) ; if ( ! CE . startsWith ( \"?\" ) ) CE = \"?\" + CE ; DataDDS data ; synchronized ( this ) { data = dodsConnection . getData ( CE , null ) ; } if ( debugTime ) System . out . println ( \"DODSNetcdfFile.readDataDDSfromServer took = \" + ( System . currentTimeMillis ( ) - start ) / 1000.0 ) ; if ( debugDataResult ) { System . out . println ( \" dataDDS return:\" ) ; data . print ( System . out ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a single call to the DODS Server to read all the named variable s data in one client / server roundtrip . [CODESPLIT] @ Override public List < Array > readArrays ( List < Variable > preloadVariables ) throws IOException { //For performance tests: //if (true) return super.readArrays (variables); if ( preloadVariables . size ( ) == 0 ) return new ArrayList < Array > ( ) ; // construct the list of variables, skipping ones with cached data List < DodsV > reqDodsVlist = new ArrayList < DodsV > ( ) ; DodsV root ; for ( Variable var : preloadVariables ) { if ( var . hasCachedData ( ) ) continue ; reqDodsVlist . add ( ( DodsV ) var . getSPobject ( ) ) ; } Collections . sort ( reqDodsVlist ) ; // \"depth first\" order // read the data DataDDS dataDDS ; Map < DodsV , DodsV > map = new HashMap < DodsV , DodsV > ( 2 * reqDodsVlist . size ( ) + 1 ) ; if ( reqDodsVlist . size ( ) > 0 ) { // Create the request StringBuilder requestString = new StringBuilder ( ) ; for ( int i = 0 ; i < reqDodsVlist . size ( ) ; i ++ ) { DodsV dodsV = reqDodsVlist . get ( i ) ; requestString . append ( i == 0 ? \"?\" : \",\" ) ; // requestString.append(makeDODSname(dodsV)); requestString . append ( dodsV . getEncodedName ( ) ) ; } String s = requestString . toString ( ) ; try { dataDDS = readDataDDSfromServer ( requestString . toString ( ) ) ; root = DodsV . parseDataDDS ( dataDDS ) ; } catch ( Exception exc ) { logger . error ( \"ERROR readDataDDSfromServer on \" + requestString , exc ) ; throw new IOException ( exc . getMessage ( ) ) ; } // gotta find the corresponding data in \"depth first\" order for ( DodsV ddsV : reqDodsVlist ) { DodsV dataV = root . findDataV ( ddsV ) ; if ( dataV != null ) { if ( debugConvertData ) System . out . println ( \"readArray found dataV= \" + makeDODSname ( ddsV ) ) ; dataV . isDone = true ; map . put ( ddsV , dataV ) ; // thread safe! } else { logger . error ( \"ERROR findDataV cant find \" + makeDODSname ( ddsV ) + \" on \" + location ) ; } } } // For each variable either extract the data or use cached data. List < Array > result = new ArrayList < Array > ( ) ; for ( Variable var : preloadVariables ) { if ( var . hasCachedData ( ) ) { result . add ( var . read ( ) ) ; } else { Array data = null ; DodsV ddsV = ( DodsV ) var . getSPobject ( ) ; DodsV dataV = map . get ( ddsV ) ; if ( dataV == null ) { logger . error ( \"DODSNetcdfFile.readArrays cant find \" + makeDODSname ( ddsV ) + \" in dataDDS; \" + location ) ; //dataDDS.print( System.out); } else { if ( debugConvertData ) System . out . println ( \"readArray converting \" + makeDODSname ( ddsV ) ) ; dataV . isDone = true ; try { if ( var . isMemberOfStructure ( ) ) { // we want the top structure this variable is contained in. while ( ( dataV . parent != null ) && ( dataV . parent . bt != null ) ) { dataV = dataV . parent ; } data = convertD2N . convertNestedVariable ( var , null , dataV , true ) ; } else data = convertD2N . convertTopVariable ( var , null , dataV ) ; } catch ( DAP2Exception de ) { logger . error ( \"ERROR convertVariable on \" + var . getFullName ( ) , de ) ; throw new IOException ( de . getMessage ( ) ) ; } if ( var . isCaching ( ) ) { var . setCachedData ( data ) ; if ( debugCached ) System . out . println ( \" cache for <\" + var . getFullName ( ) + \"> length =\" + data . getSize ( ) ) ; } } result . add ( data ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * this is for reading variables that are members of structures protected Array readMemberData ( ucar . nc2 . Variable v Section section boolean flatten ) throws IOException InvalidRangeException { StringBuffer buff = new StringBuffer ( 100 ) ; buff . setLength ( 0 ) ; [CODESPLIT] public Array readWithCE ( ucar . nc2 . Variable v , String CE ) throws IOException { Array dataArray ; try { DataDDS dataDDS = readDataDDSfromServer ( CE ) ; DodsV root = DodsV . parseDataDDS ( dataDDS ) ; DodsV want = root . children . get ( 0 ) ; // can only be one if ( v . isMemberOfStructure ( ) ) dataArray = convertD2N . convertNestedVariable ( v , null , want , true ) ; else dataArray = convertD2N . convertTopVariable ( v , null , want ) ; } catch ( DAP2Exception ex ) { ex . printStackTrace ( ) ; throw new IOException ( ex . getMessage ( ) ) ; } catch ( ParseException ex ) { ex . printStackTrace ( ) ; throw new IOException ( ex . getMessage ( ) ) ; } return dataArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging [CODESPLIT] public void getDetailInfo ( Formatter f ) { super . getDetailInfo ( f ) ; f . format ( \"DDS = %n\" ) ; ByteArrayOutputStream buffOS = new ByteArrayOutputStream ( 8000 ) ; dds . print ( buffOS ) ; f . format ( \"%s%n\" , new String ( buffOS . toByteArray ( ) , Util . UTF8 ) ) ; f . format ( \"%nDAS = %n\" ) ; buffOS = new ByteArrayOutputStream ( 8000 ) ; das . print ( buffOS ) ; f . format ( \"%s%n\" , new String ( buffOS . toByteArray ( ) , Util . UTF8 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a gif file make it into an ImageIcon . [CODESPLIT] public static ImageIcon getIcon ( String fullIconName , boolean errMsg ) { ImageIcon icon = null ; java . net . URL iconR = cl . getResource ( fullIconName ) ; if ( debugIcon ) { System . out . println ( \"classLoader \" + cl . getClassLoader ( ) ) ; System . out . println ( \"  Resource.getIcon on \" + fullIconName + \" = \" + iconR ) ; } if ( iconR != null ) icon = new ImageIcon ( iconR ) ; if ( ( icon == null ) && errMsg ) System . out . println ( \"  ERROR: Resource.getIcon failed on \" + fullIconName ) ; else if ( debugIcon ) System . out . println ( \"  Resource.getIcon ok on \" + fullIconName ) ; return icon ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a gif file make it into an Image . [CODESPLIT] public static Image getImage ( String fullImageName ) { Image image = null ; java . net . URL url = cl . getResource ( fullImageName ) ; if ( url != null ) image = Toolkit . getDefaultToolkit ( ) . createImage ( url ) ; if ( image == null ) System . out . println ( \"  ERROR: Resource.getImageResource failed on \" + fullImageName ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a gif file make it into a Cursor . [CODESPLIT] public static Cursor makeCursor ( String name ) { Image image = getImage ( name ) ; if ( null == image ) return null ; Cursor cursor ; try { Toolkit tk = Toolkit . getDefaultToolkit ( ) ; if ( debug ) { ImageObserver obs = new ImageObserver ( ) { public boolean imageUpdate ( Image image , int flags , int x , int y , int width , int height ) { return true ; } } ; System . out . println ( \" bestCursorSize = \" + tk . getBestCursorSize ( image . getWidth ( obs ) , image . getHeight ( obs ) ) ) ; System . out . println ( \" getMaximumCursorColors = \" + tk . getMaximumCursorColors ( ) ) ; } cursor = tk . createCustomCursor ( image , new Point ( 17 , 17 ) , name ) ; } catch ( IndexOutOfBoundsException e ) { System . out . println ( \"NavigatedPanel createCustomCursor failed \" + e ) ; return null ; } return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a resource as a Stream . First try ClassLoader . getResourceAsStream () . If that fails try a plain old FileInputStream () . [CODESPLIT] public static InputStream getFileResource ( String resourcePath ) { InputStream is = cl . getResourceAsStream ( resourcePath ) ; if ( is != null ) { if ( debug ) System . out . println ( \"Resource.getResourceAsStream ok on \" + resourcePath ) ; return is ; } else if ( debug ) System . out . println ( \"Resource.getResourceAsStream failed on (\" + resourcePath + \")\" ) ; try { is = new FileInputStream ( resourcePath ) ; if ( debug ) System . out . println ( \"Resource.FileInputStream ok on \" + resourcePath ) ; } catch ( FileNotFoundException e ) { if ( debug ) System . out . println ( \"  FileNotFoundException: Resource.getFile failed on \" + resourcePath ) ; } catch ( java . security . AccessControlException e ) { if ( debug ) System . out . println ( \"  AccessControlException: Resource.getFile failed on \" + resourcePath ) ; } return is ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "test [CODESPLIT] public static void main ( String [ ] args ) throws IOException { System . out . println ( \"java.class.path = \" + System . getProperty ( \"java.class.path\" ) ) ; System . out . println ( \"Class = \" + cl ) ; System . out . println ( \"Class Loader = \" + cl . getClassLoader ( ) ) ; try ( InputStream is = getFileResource ( \"/ucar.unidata.util/Resource.java\" ) ) { } try ( InputStream is = getFileResource ( \"Resource.java\" ) ) { } try ( InputStream is = getFileResource ( \"test/test/Resource.java\" ) ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from RandomAccessFile create primitive array of size Layout . getTotalNelems . Reading is controlled by the Layout object . [CODESPLIT] static public Object readDataFill ( RandomAccessFile raf , Layout index , DataType dataType , Object fillValue , int byteOrder ) throws java . io . IOException { Object arr = ( fillValue == null ) ? makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType ) : makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType , fillValue ) ; return readData ( raf , index , dataType , arr , byteOrder , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from RandomAccessFile place in given primitive array . Reading is controlled by the Layout object . [CODESPLIT] static public Object readData ( RandomAccessFile raf , Layout layout , DataType dataType , Object arr , int byteOrder , boolean convertChar ) throws java . io . IOException { if ( showLayoutTypes ) System . out . println ( \"***RAF LayoutType=\" + layout . getClass ( ) . getName ( ) ) ; if ( dataType . getPrimitiveClassType ( ) == byte . class || dataType == DataType . CHAR ) { byte [ ] pa = ( byte [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFully ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } if ( convertChar && dataType == DataType . CHAR ) return convertByteToChar ( pa ) ; else return pa ; // javac ternary compile error\r } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = ( short [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readShort ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = ( int [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readInt ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = ( float [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFloat ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = ( double [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readDouble ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = ( long [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readLong ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . STRUCTURE ) { byte [ ] pa = ( byte [ ] ) arr ; int recsize = layout . getElemSize ( ) ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFully ( pa , ( int ) chunk . getDestElem ( ) * recsize , chunk . getNelems ( ) * recsize ) ; } return pa ; } throw new IllegalStateException ( \"unknown type= \" + dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from PositioningDataInputStream create primitive array of size Layout . getTotalNelems . Reading is controlled by the Layout object . [CODESPLIT] static public Object readDataFill ( PositioningDataInputStream is , Layout index , DataType dataType , Object fillValue ) throws java . io . IOException { Object arr = ( fillValue == null ) ? makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType ) : makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType , fillValue ) ; return readData ( is , index , dataType , arr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from PositioningDataInputStream place in given primitive array . Reading is controlled by the Layout object . [CODESPLIT] static public Object readData ( PositioningDataInputStream raf , Layout index , DataType dataType , Object arr ) throws java . io . IOException { if ( showLayoutTypes ) System . out . println ( \"***PositioningDataInputStream LayoutType=\" + index . getClass ( ) . getName ( ) ) ; if ( dataType . getPrimitiveClassType ( ) == byte . class || dataType == DataType . CHAR ) { byte [ ] pa = ( byte [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . read ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } //return (dataType == DataType.CHAR) ? convertByteToChar(pa) : pa;\r if ( dataType == DataType . CHAR ) return convertByteToChar ( pa ) ; else return pa ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = ( short [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readShort ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = ( int [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readInt ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = ( float [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readFloat ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = ( double [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readDouble ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = ( long [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readLong ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . STRUCTURE ) { int recsize = index . getElemSize ( ) ; byte [ ] pa = ( byte [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . read ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) * recsize , chunk . getNelems ( ) * recsize ) ; } return pa ; } throw new IllegalStateException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from ByteBuffer create primitive array of size Layout . getTotalNelems . Reading is controlled by the Layout object . [CODESPLIT] static public Object readDataFill ( LayoutBB layout , DataType dataType , Object fillValue ) throws java . io . IOException { long size = layout . getTotalNelems ( ) ; if ( dataType == DataType . STRUCTURE ) size *= layout . getElemSize ( ) ; Object arr = ( fillValue == null ) ? makePrimitiveArray ( ( int ) size , dataType ) : makePrimitiveArray ( ( int ) size , dataType , fillValue ) ; return readData ( layout , dataType , arr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from ByteBuffer place in given primitive array . Reading is controlled by the LayoutBB object . [CODESPLIT] static public Object readData ( LayoutBB layout , DataType dataType , Object arr ) throws java . io . IOException { if ( showLayoutTypes ) System . out . println ( \"***BB LayoutType=\" + layout . getClass ( ) . getName ( ) ) ; if ( dataType . getPrimitiveClassType ( ) == byte . class || ( dataType == DataType . CHAR ) ) { byte [ ] pa = ( byte [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; ByteBuffer bb = chunk . getByteBuffer ( ) ; bb . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = . get ( ) ; } //return (dataType == DataType.CHAR) ? convertByteToChar(pa) : pa;\r if ( dataType == DataType . CHAR ) return convertByteToChar ( pa ) ; else return pa ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = ( short [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; ShortBuffer buff = chunk . getShortBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = ( int [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; IntBuffer buff = chunk . getIntBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = ( float [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; FloatBuffer buff = chunk . getFloatBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = ( double [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; DoubleBuffer buff = chunk . getDoubleBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = ( long [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; LongBuffer buff = chunk . getLongBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType == DataType . STRUCTURE ) { byte [ ] pa = ( byte [ ] ) arr ; int recsize = layout . getElemSize ( ) ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; ByteBuffer bb = chunk . getByteBuffer ( ) ; bb . position ( chunk . getSrcElem ( ) * recsize ) ; int pos = ( int ) chunk . getDestElem ( ) * recsize ; for ( int i = 0 ; i < chunk . getNelems ( ) * recsize ; i ++ ) pa [ pos ++ ] = . get ( ) ; } return pa ; } throw new IllegalStateException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy data to a channel . Used by ncstream . Not doing Structures correctly yet . [CODESPLIT] public static long copyToByteChannel ( Array data , WritableByteChannel channel ) throws java . io . IOException { Class classType = data . getElementType ( ) ; /* if (data instanceof ArrayStructure) { // use NcStream encoding\r\n      DataOutputStream os = new DataOutputStream(Channels.newOutputStream(channel));\r\n      return NcStream.encodeArrayStructure((ArrayStructure) data, null, os);\r\n    } */ DataOutputStream outStream = new DataOutputStream ( Channels . newOutputStream ( channel ) ) ; IndexIterator iterA = data . getIndexIterator ( ) ; if ( classType == double . class ) { while ( iterA . hasNext ( ) ) outStream . writeDouble ( iterA . getDoubleNext ( ) ) ; } else if ( classType == float . class ) { while ( iterA . hasNext ( ) ) outStream . writeFloat ( iterA . getFloatNext ( ) ) ; } else if ( classType == long . class ) { while ( iterA . hasNext ( ) ) outStream . writeLong ( iterA . getLongNext ( ) ) ; } else if ( classType == int . class ) { while ( iterA . hasNext ( ) ) outStream . writeInt ( iterA . getIntNext ( ) ) ; } else if ( classType == short . class ) { while ( iterA . hasNext ( ) ) outStream . writeShort ( iterA . getShortNext ( ) ) ; } else if ( classType == char . class ) { // LOOK why are we using chars anyway ?\r byte [ ] pa = convertCharToByte ( ( char [ ] ) data . get1DJavaArray ( DataType . CHAR ) ) ; outStream . write ( pa , 0 , pa . length ) ; } else if ( classType == byte . class ) { while ( iterA . hasNext ( ) ) outStream . writeByte ( iterA . getByteNext ( ) ) ; } else if ( classType == boolean . class ) { while ( iterA . hasNext ( ) ) outStream . writeBoolean ( iterA . getBooleanNext ( ) ) ; } else if ( classType == String . class ) { long size = 0 ; while ( iterA . hasNext ( ) ) { String s = ( String ) iterA . getObjectNext ( ) ; size += NcStream . writeVInt ( outStream , s . length ( ) ) ; byte [ ] b = s . getBytes ( CDM . utf8Charset ) ; outStream . write ( b ) ; size += b . length ; } return size ; } else if ( classType == ByteBuffer . class ) { // OPAQUE\r long size = 0 ; while ( iterA . hasNext ( ) ) { ByteBuffer bb = ( ByteBuffer ) iterA . getObjectNext ( ) ; size += NcStream . writeVInt ( outStream , bb . limit ( ) ) ; bb . rewind ( ) ; channel . write ( bb ) ; size += bb . limit ( ) ; } return size ; } else if ( data instanceof ArrayObject ) { // vlen\r long size = 0 ; //size += NcStream.writeVInt(outStream, (int) data.getSize()); // nelems already written\r while ( iterA . hasNext ( ) ) { Array row = ( Array ) iterA . getObjectNext ( ) ; ByteBuffer bb = row . getDataAsByteBuffer ( ) ; byte [ ] result = bb . array ( ) ; size += NcStream . writeVInt ( outStream , result . length ) ; // size in bytes\r outStream . write ( result ) ; // array\r size += result . length ; } return size ; } else throw new UnsupportedOperationException ( \"Class type = \" + classType . getName ( ) ) ; return data . getSizeBytes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create 1D primitive array of the given size and type [CODESPLIT] static public Object makePrimitiveArray ( int size , DataType dataType ) { Object arr = null ; if ( ( dataType . getPrimitiveClassType ( ) == byte . class ) || ( dataType == DataType . CHAR ) || ( dataType == DataType . OPAQUE ) || ( dataType == DataType . STRUCTURE ) ) { arr = new byte [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { arr = new short [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { arr = new int [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { arr = new long [ size ] ; } else if ( dataType == DataType . FLOAT ) { arr = new float [ size ] ; } else if ( dataType == DataType . DOUBLE ) { arr = new double [ size ] ; } else if ( dataType == DataType . STRING ) { arr = new String [ size ] ; } return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create 1D primitive array of the given size and type fill it with the given value [CODESPLIT] static public Object makePrimitiveArray ( int size , DataType dataType , Object fillValue ) { if ( dataType . getPrimitiveClassType ( ) == byte . class || ( dataType == DataType . CHAR ) ) { byte [ ] pa = new byte [ size ] ; byte val = ( ( Number ) fillValue ) . byteValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; // if (dataType == DataType.CHAR) return convertByteToChar(pa);\r return pa ; } else if ( dataType == DataType . OPAQUE ) { return new byte [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = new short [ size ] ; short val = ( ( Number ) fillValue ) . shortValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = new int [ size ] ; int val = ( ( Number ) fillValue ) . intValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = new long [ size ] ; long val = ( ( Number ) fillValue ) . longValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = new float [ size ] ; float val = ( ( Number ) fillValue ) . floatValue ( ) ; if ( val != 0.0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = new double [ size ] ; double val = ( ( Number ) fillValue ) . doubleValue ( ) ; if ( val != 0.0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType == DataType . STRING ) { String [ ] pa = new String [ size ] ; for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = ( String ) fillValue ; return pa ; } else if ( dataType == DataType . STRUCTURE ) { byte [ ] pa = new byte [ size ] ; if ( fillValue != null ) { byte [ ] val = ( byte [ ] ) fillValue ; int count = 0 ; while ( count < size ) for ( byte aVal : val ) pa [ count ++ ] = aVal ; } return pa ; } throw new IllegalStateException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert byte array to char array assuming UTF - 8 encoding [CODESPLIT] static public char [ ] convertByteToCharUTF ( byte [ ] byteArray ) { Charset c = CDM . utf8Charset ; CharBuffer output = c . decode ( ByteBuffer . wrap ( byteArray ) ) ; return output . array ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert char array to byte array assuming UTF - 8 encoding [CODESPLIT] static public byte [ ] convertCharToByteUTF ( char [ ] from ) { Charset c = CDM . utf8Charset ; ByteBuffer output = c . encode ( CharBuffer . wrap ( from ) ) ; return output . array ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert byte array to char array [CODESPLIT] static public char [ ] convertByteToChar ( byte [ ] byteArray ) { int size = byteArray . length ; char [ ] cbuff = new char [ size ] ; for ( int i = 0 ; i < size ; i ++ ) cbuff [ i ] = ( char ) DataType . unsignedByteToShort ( byteArray [ i ] ) ; // NOTE: not Unicode !\r return cbuff ; } // convert char array to byte array\r static public byte [ ] convertCharToByte ( char [ ] from ) { byte [ ] to = null ; if ( from != null ) { int size = from . length ; to = new byte [ size ] ; for ( int i = 0 ; i < size ; i ++ ) to [ i ] = ( byte ) from [ i ] ; // LOOK wrong, convert back to unsigned byte ???\r } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "section reading for member data [CODESPLIT] static public ucar . ma2 . Array readSection ( ParsedSectionSpec cer ) throws IOException , InvalidRangeException { Variable inner = null ; List < Range > totalRanges = new ArrayList <> ( ) ; ParsedSectionSpec current = cer ; while ( current != null ) { totalRanges . addAll ( current . section . getRanges ( ) ) ; inner = current . v ; current = current . child ; } assert inner != null ; Section total = new Section ( totalRanges ) ; Array result = Array . factory ( inner . getDataType ( ) , total . getShape ( ) ) ; // must be a Structure\r Structure outer = ( Structure ) cer . v ; Structure outerSubset = outer . select ( cer . child . v . getShortName ( ) ) ; // allows IOSPs to optimize for  this case\r ArrayStructure outerData = ( ArrayStructure ) outerSubset . read ( cer . section ) ; extractSection ( cer . child , outerData , result . getIndexIterator ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK could be used in createView ?? [CODESPLIT] static private ArrayStructure sectionArrayStructure ( ParsedSectionSpec child , ArrayStructure innerData , StructureMembers . Member m ) throws IOException , InvalidRangeException { StructureMembers membersw = new StructureMembers ( m . getStructureMembers ( ) ) ; // no data arrays get propagated\r ArrayStructureW result = new ArrayStructureW ( membersw , child . section . getShape ( ) ) ; int count = 0 ; Section . Iterator iter = child . section . getIterator ( child . v . getShape ( ) ) ; while ( iter . hasNext ( ) ) { int recno = iter . next ( null ) ; StructureData sd = innerData . getStructureData ( recno ) ; result . setStructureData ( sd , count ++ ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] void add ( long recno , int fieldno , Array field ) { FieldArrays fs = records [ ( int ) recno ] ; if ( fs == null ) records [ ( int ) recno ] = ( fs = new FieldArrays ( this . nmembers ) ) ; fs . fields [ fieldno ] = field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the index th StructureData ( StructureDataA ) object We need instances of StructureData to give to the user . We use StructureDataA so we can centralize everything in this class . The total number of StructureData objects is dimsize . [CODESPLIT] @ Override public StructureData getStructureData ( int index ) { assert ( super . sdata != null ) ; if ( index < 0 || index >= this . dimsize ) throw new IllegalArgumentException ( index + \" >= \" + super . sdata . length ) ; assert ( super . sdata [ index ] != null ) ; return super . sdata [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member databuffer of type String or char . [CODESPLIT] public String getScalarString ( int recnum , StructureMembers . Member m ) { Array data = m . getDataArray ( ) ; return ( String ) data . getObject ( recnum ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Non - atomic cases [CODESPLIT] public StructureData getScalarStructure ( int index , StructureMembers . Member m ) { if ( m . getDataType ( ) != DataType . STRUCTURE ) throw new ForbiddenConversionException ( \"Atomic field cannot be converted to Structure\" ) ; Array ca = memberArray ( index , memberIndex ( m ) ) ; if ( ca . getDataType ( ) != DataType . STRUCTURE && ca . getDataType ( ) != DataType . SEQUENCE ) throw new ForbiddenConversionException ( \"Attempt to access non-structure member\" ) ; CDMArrayStructure as = ( CDMArrayStructure ) ca ; return as . getStructureData ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Key interface method coming in from StructureDataA . [CODESPLIT] @ Override public ucar . ma2 . Array getArray ( int recno , StructureMembers . Member m ) { return ( ucar . ma2 . Array ) memberArray ( recno , memberIndex ( m ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] @ Override protected StructureData makeStructureData ( ArrayStructure as , int index ) { if ( super . sdata [ index ] == null ) super . sdata [ index ] = new StructureDataA ( as , index ) ; return super . sdata [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the StructureMembers object from a DapStructure . May need to recurse if a field is itself a Structure [CODESPLIT] static StructureMembers computemembers ( DapVariable var ) { DapStructure ds = ( DapStructure ) var . getBaseType ( ) ; StructureMembers sm = new StructureMembers ( ds . getShortName ( ) ) ; List < DapVariable > fields = ds . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; DapType dt = field . getBaseType ( ) ; DataType cdmtype = CDMTypeFcns . daptype2cdmtype ( dt ) ; StructureMembers . Member m = sm . addMember ( field . getShortName ( ) , \"\" , null , cdmtype , CDMUtil . computeEffectiveShape ( field . getDimensions ( ) ) ) ; m . setDataParam ( i ) ; // So we can index into various lists // recurse if this field is itself a structure if ( dt . getTypeSort ( ) . isStructType ( ) ) { StructureMembers subsm = computemembers ( field ) ; m . setStructureMembers ( subsm ) ; } } return sm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { // to print properly, cast to long and convert unsigned to signed\r long tempVal = ( ( long ) getValue ( ) ) & 0xFFFFFFFF L ; if ( print_decl_p ) { printDecl ( os , space , false ) ; os . println ( \" = \" + tempVal + \";\" ) ; } else os . print ( tempVal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add this as a dimension to a netCDF file [CODESPLIT] public void addDimensionsToNetcdfFile ( NetcdfFile ncfile , Group g ) { ncfile . addDimension ( g , new Dimension ( getName ( ) , getNEnsembles ( ) , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "test [CODESPLIT] public static void main ( String args [ ] ) { JFrame frame = new JFrame ( \"Test prefs Field\" ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ) ; PrefPanel . Dialog d = new PrefPanel . Dialog ( frame , false , \"title\" , null , null ) ; PrefPanel pp = d . getPrefPanel ( ) ; final Field . Text tf = pp . addTextField ( \"text\" , \"text\" , \"defValue\" ) ; pp . setCursor ( 1 , 0 ) ; pp . addTextField ( \"text2\" , \"text2\" , \"text2\" ) ; //final Field.Int intf = pp.addIntField(\"int\", \"int\", 66); tf . setText ( \"better value\" ) ; d . finish ( ) ; d . show ( ) ; JPanel main = new JPanel ( new FlowLayout ( ) ) ; frame . getContentPane ( ) . add ( main ) ; main . setPreferredSize ( new Dimension ( 200 , 200 ) ) ; frame . pack ( ) ; frame . setLocation ( 300 , 300 ) ; frame . setVisible ( true ) ; pp . addActionListener ( e -> { String text = tf . getText ( ) ; tf . setText ( text + \"1\" ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a CrawlableDataset for the given path using the CrawlableDataset implementation indicated by the given class name . [CODESPLIT] public static CrawlableDataset createCrawlableDataset ( String path , String className , Object configObj ) throws IOException , ClassNotFoundException , NoSuchMethodException , IllegalAccessException , InvocationTargetException , InstantiationException , IllegalArgumentException , NullPointerException // throws CrDsException, IllegalArgumentException { if ( path == null ) throw new NullPointerException ( \"Given path must not be null.\" ) ; String tmpClassName = ( className == null ? defaultClassName : className ) ; // @todo Remove alias until sure how to handle things like \".scour*\" being a regular file. //    if ( CrawlableDatasetAlias.isAlias( tmpPath) ) //        return new CrawlableDatasetAlias( tmpPath, tmpClassName, configObj ); // Get the Class instance for desired CrawlableDataset implementation. Class crDsClass = Class . forName ( tmpClassName ) ; // Check that the Class is a CrawlableDataset. if ( ! CrawlableDataset . class . isAssignableFrom ( crDsClass ) ) { throw new IllegalArgumentException ( \"Requested class <\" + className + \"> not an implementation of thredds.crawlabledataset.CrawlableDataset.\" ) ; } // Instantiate the desired CrawlableDataset. Class [ ] argTypes = { String . class , Object . class } ; Object [ ] args = { path , configObj } ; Constructor constructor = crDsClass . getDeclaredConstructor ( argTypes ) ; try { return ( CrawlableDataset ) constructor . newInstance ( args ) ; } catch ( InvocationTargetException e ) { if ( IOException . class . isAssignableFrom ( e . getCause ( ) . getClass ( ) ) ) throw ( IOException ) e . getCause ( ) ; else throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize the given path so that it can be used in the creation of a CrawlableDataset . This method can be used on absolute or relative paths . [CODESPLIT] public static String normalizePath ( String path ) { // Replace any occurance of a backslash (\"\\\") with a slash (\"/\"). // NOTE: Both String and Pattern escape backslash, so need four backslashes to find one. // NOTE: No longer replace multiple backslashes with one slash, which allows for UNC pathnames (Windows LAN addresses). //       Was path.replaceAll( \"\\\\\\\\+\", \"/\"); String newPath = path . replaceAll ( \"\\\\\\\\\" , \"/\" ) ; // Remove trailing slashes. while ( newPath . endsWith ( \"/\" ) && ! newPath . equals ( \"/\" ) ) newPath = newPath . substring ( 0 , newPath . length ( ) - 1 ) ; return newPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "implement GisFeature methods : [CODESPLIT] public java . awt . geom . Rectangle2D getBounds2D ( ) { // Get the bounding box for this feature. from java.awt.geom.Rectangle2D double x0 = ( ( ( ContourLine ) ( lines . get ( 0 ) ) ) . getX ( ) ) [ 0 ] ; double y0 = ( ( ( ContourLine ) ( lines . get ( 0 ) ) ) . getY ( ) ) [ 0 ] ; double xMaxInd = x0 , xmin = x0 , yMaxInd = y0 , ymin = y0 ; for ( int i = 0 ; i < lines . size ( ) ; i ++ ) { GisPart cline = ( ContourLine ) ( lines . get ( i ) ) ; double [ ] xpts = cline . getX ( ) ; double [ ] ypts = cline . getY ( ) ; for ( int j = 0 ; j < cline . getNumPoints ( ) ; j ++ ) { if ( xpts [ j ] < xmin ) xmin = xpts [ j ] ; else if ( xpts [ j ] > xMaxInd ) xMaxInd = xpts [ j ] ; if ( ypts [ j ] < ymin ) ymin = ypts [ j ] ; else if ( ypts [ j ] > yMaxInd ) yMaxInd = ypts [ j ] ; } } // Rectangle2D.Double(double x, double y, double width, double height) Rectangle2D . Double rect = new Rectangle2D . Double ( xmin , ymin , xMaxInd - xmin , yMaxInd - ymin ) ; return rect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is where persist () reads / writes files [CODESPLIT] static public void setPersistenceCache ( DiskCache2 dc ) { diskCache2 = dc ; if ( diskCache2 != null ) diskCache2 . setAlwaysUseCache ( true ) ; // the persistence cache file has same name as the ncml - must put it into the cache else clobber ncml  7/31/2014\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a nested dataset specified by an explicit netcdf element . enhance is handled by the reader so its always false here . [CODESPLIT] public void addExplicitDataset ( String cacheName , String location , String id , String ncoordS , String coordValueS , String sectionSpec , ucar . nc2 . util . cache . FileFactory reader ) { Dataset nested = makeDataset ( cacheName , location , id , ncoordS , coordValueS , sectionSpec , null , reader ) ; explicitDatasets . add ( nested ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a dataset scan [CODESPLIT] public void addDatasetScan ( Element crawlableDatasetElement , String dirName , String suffix , String regexpPatternString , String dateFormatMark , Set < NetcdfDataset . Enhance > enhanceMode , String subdirs , String olderThan ) { datasetManager . addDirectoryScan ( dirName , suffix , regexpPatternString , subdirs , olderThan , enhanceMode ) ; this . dateFormatMark = dateFormatMark ; if ( dateFormatMark != null ) { isDate = true ; if ( type == Type . joinExisting ) type = Type . joinExistingOne ; // tricky\r DateExtractor dateExtractor = new DateExtractorFromName ( dateFormatMark , true ) ; datasetManager . setDateExtractor ( dateExtractor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "experimental [CODESPLIT] public void addCollection ( String spec , String olderThan ) throws IOException { datasetManager = MFileCollectionManager . open ( spec , spec , olderThan , new Formatter ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all elements are processed finish construction [CODESPLIT] public void finish ( CancelTask cancelTask ) throws IOException { datasetManager . scan ( true ) ; // Make the list of Datasets, by scanning if needed.\r cacheDirty = true ; makeDatasets ( cancelTask ) ; //ucar.unidata.io.RandomAccessFile.setDebugAccess( true);\r buildNetcdfDataset ( cancelTask ) ; //ucar.unidata.io.RandomAccessFile.setDebugAccess( false);\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the list of Datasets from explicit and scans . [CODESPLIT] protected void makeDatasets ( CancelTask cancelTask ) throws IOException { // heres where the results will go\r datasets = new ArrayList <> ( ) ; for ( MFile cd : datasetManager . getFilesSorted ( ) ) { datasets . add ( makeDataset ( cd ) ) ; } // sort using Aggregation.Dataset as Comparator.\r // Sort by date if it exists, else filename.\r Collections . sort ( datasets ) ; /* optionally extract the date\r\n      String dateCoordS = null;\r\n      if (null != dateFormatMark) {\r\n        String filename = myf.getName(); // LOOK operates on name, not path\r\n        Date dateCoord = DateFromString.getDateUsingDemarkatedCount(filename, dateFormatMark, '#');\r\n        dateCoordS = formatter.toDateTimeStringISO(dateCoord);\r\n        if (debugDateParse) System.out.println(\"  adding \" + myf.getPath() + \" date= \" + dateCoordS);\r\n      } else {\r\n        if (debugDateParse) System.out.println(\"  adding \" + myf.getPath());\r\n      }\r\n\r\n      String location = myf.getPath();\r\n      Aggregation.Dataset ds = makeDataset(location, location, null, null, dateCoordS, null, enhance, null);\r\n      datasets.add(ds);\r\n    }\r\n\r\n    // Sort by date if it exists, else filename.\r\n    Collections.sort(datasets, new Comparator<Aggregation.Dataset>() {\r\n      public int compare(Aggregation.Dataset ds1, Aggregation.Dataset ds2) {\r\n        if(ds1.cd == null)\r\n           return ds1.getLocation().compareTo(ds2.getLocation()) ;\r\n        if (ds1.cd.dateCoord != null) // LOOK can we generalize\r\n          return ds1.cd.dateCoord.compareTo(ds2.cd.dateCoord);\r\n        else\r\n          return ds1.cd.file.getName().compareTo(ds2.cd.file.getName());\r\n      }\r\n    });  */ // add the explicit datasets - these need to be kept in order\r // LOOK - should they be before or after scanned? Does it make sense to mix scan and explicit?\r // AggFmrcSingle sets explicit datasets - the scan is empty\r for ( Aggregation . Dataset dataset : explicitDatasets ) { datasets . add ( dataset ) ; } // Remove unreadable files (i.e. due to permissions) from the aggregation.\r // LOOK: Is this logic we should install \"upstream\", perhaps in MFileCollectionManager?\r // It would affect other collections than just NcML aggregation in that case.\r for ( Iterator < Dataset > datasetsIter = datasets . iterator ( ) ; datasetsIter . hasNext ( ) ; ) { Dataset dataset = datasetsIter . next ( ) ; Path datasetPath ; if ( dataset . getMFile ( ) instanceof MFileOS ) { datasetPath = ( ( MFileOS ) dataset . getMFile ( ) ) . getFile ( ) . toPath ( ) ; } else if ( dataset . getMFile ( ) instanceof MFileOS7 ) { datasetPath = ( ( MFileOS7 ) dataset . getMFile ( ) ) . getNioPath ( ) ; } else { continue ; } if ( ! Files . isReadable ( datasetPath ) ) { // File.canRead() is broken on Windows, but the JDK7 methods work.\r logger . warn ( \"Aggregation member isn't readable (permissions issue?). Skipping: \" + datasetPath ) ; datasetsIter . remove ( ) ; } } // check for duplicate location\r Set < String > dset = new HashSet <> ( 2 * datasets . size ( ) ) ; for ( Aggregation . Dataset dataset : datasets ) { if ( dset . contains ( dataset . cacheLocation ) ) logger . warn ( \"Duplicate dataset in aggregation = \" + dataset . cacheLocation ) ; dset . add ( dataset . cacheLocation ) ; } if ( datasets . size ( ) == 0 ) { throw new IllegalStateException ( \"There are no datasets in the aggregation \" + datasetManager ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open one of the nested datasets as a template for the aggregation dataset . [CODESPLIT] protected Dataset getTypicalDataset ( ) throws IOException { List < Dataset > nestedDatasets = getDatasets ( ) ; int n = nestedDatasets . size ( ) ; if ( n == 0 ) throw new FileNotFoundException ( \"No datasets in this aggregation\" ) ; int select ; if ( typicalDatasetMode == TypicalDataset . LATEST ) select = n - 1 ; else if ( typicalDatasetMode == TypicalDataset . PENULTIMATE ) select = ( n < 2 ) ? 0 : n - 2 ; else if ( typicalDatasetMode == TypicalDataset . FIRST ) select = 0 ; else { // random is default\r if ( r == null ) r = new Random ( ) ; select = ( n < 2 ) ? 0 : r . nextInt ( n ) ; } return nestedDatasets . get ( select ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dataset factory so subclasses can override [CODESPLIT] protected Dataset makeDataset ( String cacheName , String location , String id , String ncoordS , String coordValueS , String sectionSpec , EnumSet < NetcdfDataset . Enhance > enhance , ucar . nc2 . util . cache . FileFactory reader ) { return new Dataset ( cacheName , location , id , enhance , reader ) ; // overridden in OuterDim, tiled\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "All non - agg variables use a proxy to acquire the file before reading . If the variable is caching read data into cache now . If not caching VariableEnhanced . setProxyReader () is called . [CODESPLIT] protected void setDatasetAcquireProxy ( Dataset typicalDataset , NetcdfDataset newds ) throws IOException { DatasetProxyReader proxy = new DatasetProxyReader ( typicalDataset ) ; setDatasetAcquireProxy ( proxy , newds . getRootGroup ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This tracks Dataset elements that have resource control attributes [CODESPLIT] void putResourceControl ( Dataset ds ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( \"putResourceControl \" + ds . getRestrictAccess ( ) + \" for \" + ds . getName ( ) ) ; resourceControlHash . put ( ds . getUrlPath ( ) , ds . getRestrictAccess ( ) ) ; // resourceControl is inherited, but no guarentee that children paths are related, unless its a //   DatasetScan or InvDatasetFmrc. So we keep track of all datasets that have a ResourceControl, including children // DatasetScan and InvDatasetFmrc must use a PathMatcher, others can use exact match (hash) /* if (ds instanceof DatasetScan) {\n      DatasetScan scan = (DatasetScan) ds;\n      if (debugResourceControl)\n        System.out.println(\"putResourceControl \" + ds.getRestrictAccess() + \" for datasetScan \" + scan.getPath());\n      resourceControlMatcher.put(scan.getPath(), ds.getRestrictAccess());\n\n    } else { // dataset\n      if (debugResourceControl)\n        System.out.println(\"putResourceControl \" + ds.getRestrictAccess() + \" for dataset \" + ds.getUrlPath());\n\n      // LOOK: seems like you only need to add if InvAccess.InvService.isReletive\n      // LOOK: seems like we should use resourceControlMatcher to make sure we match .dods, etc\n      for (Access access : ds.getAccess()) {\n        if (access.getService().isRelativeBase())\n          resourceControlHash.put(access.getUrlPath(), ds.getRestrictAccess());\n      }\n    }  */ hasResourceControl = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a point to the end of the line . [CODESPLIT] public void addPoint ( double x , double y ) { Point ptPrev = null ; if ( points . size ( ) > 0 ) { ptPrev = points . get ( points . size ( ) - 1 ) ; } this . points . add ( new CFPoint ( x , y , ptPrev , null , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the previous line which makes up the multiline which this line is a part of . If prev is a CFLine automatically connect the other line to this line as well . [CODESPLIT] public void setNext ( Line next ) { if ( next instanceof CFLine ) { setNext ( ( CFLine ) next ) ; } else this . next = next ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the previous line which makes up the multiline which this line is a part of . If prev is a CFLine automatically connect the other line to this line as well . [CODESPLIT] public void setPrev ( Line prev ) { if ( prev instanceof CFLine ) { setPrev ( ( CFLine ) prev ) ; } else this . prev = prev ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a dataset variable and index automatically populates this Line and returns it . If not found returns null . [CODESPLIT] public Line setupLine ( NetcdfDataset dataset , Variable var , int index ) { this . points . clear ( ) ; Array xPts = null ; Array yPts = null ; Variable nodeCounts = null ; Variable partNodeCounts = null ; List < CoordinateAxis > axes = dataset . getCoordinateAxes ( ) ; CoordinateAxis x = null ; CoordinateAxis y = null ; String [ ] nodeCoords = var . findAttributeIgnoreCase ( CF . NODE_COORDINATES ) . getStringValue ( ) . split ( \" \" ) ; // Look for x and y\r for ( CoordinateAxis ax : axes ) { if ( ax . getFullName ( ) . equals ( nodeCoords [ 0 ] ) ) x = ax ; if ( ax . getFullName ( ) . equals ( nodeCoords [ 1 ] ) ) y = ax ; } // Affirm node counts\r String node_c_str = var . findAttValueIgnoreCase ( CF . NODE_COUNT , \"\" ) ; if ( ! node_c_str . equals ( \"\" ) ) { nodeCounts = dataset . findVariable ( node_c_str ) ; } else return null ; // Affirm part node counts\r String pNodeCoStr = var . findAttValueIgnoreCase ( CF . PART_NODE_COUNT , \"\" ) ; if ( ! pNodeCoStr . equals ( \"\" ) ) { partNodeCounts = dataset . findVariable ( pNodeCoStr ) ; } SimpleGeometryIndexFinder indexFinder = new SimpleGeometryIndexFinder ( nodeCounts ) ; //Get beginning and ending indicies for this polygon\r int lower = indexFinder . getBeginning ( index ) ; int upper = indexFinder . getEnd ( index ) ; try { xPts = x . read ( lower + \":\" + upper ) . reduce ( ) ; yPts = y . read ( lower + \":\" + upper ) . reduce ( ) ; IndexIterator itrX = xPts . getIndexIterator ( ) ; IndexIterator itrY = yPts . getIndexIterator ( ) ; // No multipolygons just read in the whole thing\r if ( partNodeCounts == null ) { this . next = null ; this . prev = null ; // x and y should have the same shape, will add some handling on this\r while ( itrX . hasNext ( ) ) { this . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; } switch ( var . getRank ( ) ) { case 2 : this . setData ( var . read ( CFSimpleGeometryHelper . getSubsetString ( var , index ) ) . reduce ( ) ) ; break ; case 1 : this . setData ( var . read ( \"\" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations\r } } // If there are multipolygons then take the upper and lower of it and divy it up\r else { Line tail = this ; Array pnc = partNodeCounts . read ( ) ; IndexIterator pncItr = pnc . getIndexIterator ( ) ; // In part node count search for the right index to begin looking for \"part node counts\"\r int pncInd = 0 ; int pncEnd = 0 ; while ( pncEnd < lower ) { pncEnd += pncItr . getIntNext ( ) ; pncInd ++ ; } // Now the index is found, use part node count and the index to find each part node count of each individual part\r while ( lower < upper ) { int smaller = pnc . getInt ( pncInd ) ; while ( smaller > 0 ) { tail . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; smaller -- ; } // Set data of each\t\r switch ( var . getRank ( ) ) { case 2 : tail . setData ( var . read ( CFSimpleGeometryHelper . getSubsetString ( var , index ) ) . reduce ( ) ) ; break ; case 1 : tail . setData ( var . read ( \"\" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations\r } lower += tail . getPoints ( ) . size ( ) ; pncInd ++ ; tail . setNext ( new CFLine ( ) ) ; tail = tail . getNext ( ) ; } //Clean up\r tail = tail . getPrev ( ) ; if ( tail != null ) tail . setNext ( null ) ; } } catch ( IOException | InvalidRangeException | InvalidDataseriesException e ) { cfl . error ( e . getMessage ( ) ) ; ; return null ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the upper bounding box coordinate on the line . [CODESPLIT] public double [ ] getBBUpper ( ) { double [ ] bbUpper = new double [ 2 ] ; List < Point > ptList = this . getPoints ( ) ; if ( ptList . isEmpty ( ) ) return null ; bbUpper [ 0 ] = ptList . get ( 0 ) . getY ( ) ; bbUpper [ 1 ] = ptList . get ( 0 ) . getY ( ) ; for ( Point pt : this . getPoints ( ) ) { if ( bbUpper [ 0 ] < pt . getX ( ) ) { bbUpper [ 0 ] = pt . getX ( ) ; } if ( bbUpper [ 1 ] < pt . getY ( ) ) { bbUpper [ 1 ] = pt . getY ( ) ; } } // Got maximum points, add some padding.\r bbUpper [ 0 ] += 10 ; bbUpper [ 1 ] += 10 ; return bbUpper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the lower bounding box coordinate on the line . [CODESPLIT] public double [ ] getBBLower ( ) { double [ ] bbLower = new double [ 2 ] ; List < Point > ptList = this . getPoints ( ) ; if ( ptList . isEmpty ( ) ) return null ; bbLower [ 0 ] = ptList . get ( 0 ) . getY ( ) ; bbLower [ 1 ] = ptList . get ( 0 ) . getY ( ) ; for ( Point pt : this . getPoints ( ) ) { if ( bbLower [ 0 ] > pt . getX ( ) ) { bbLower [ 0 ] = pt . getX ( ) ; } if ( bbLower [ 1 ] > pt . getY ( ) ) { bbLower [ 1 ] = pt . getY ( ) ; } } // Got minimum points, add some padding.\r bbLower [ 0 ] -= 10 ; bbLower [ 1 ] -= 10 ; return bbLower ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate this DatasetFilter object . Return true if valid false if invalid . [CODESPLIT] boolean validate ( StringBuilder out ) { this . isValid = true ; // If log from construction has content, append to validation output msg. if ( this . log . length ( ) > 0 ) { out . append ( this . log ) ; } // Validity check: 'name' cannot be null. (Though, 'name' // can be an empty string.) if ( this . getName ( ) == null ) { isValid = false ; out . append ( \" ** DatasetFilter (4): null value for name is not valid.\" ) ; } // Check that type is not null. if ( this . getType ( ) == null ) { isValid = false ; out . append ( \" ** DatasetFilter (5): null value for type is not valid (set with bad string?).\" ) ; } // Validity check: 'matchPattern' must be null if 'type' value // is not 'RegExp'. if ( this . type == DatasetFilter . Type . REGULAR_EXPRESSION && this . matchPattern == null ) { isValid = false ; out . append ( \" ** DatasetFilter (6): null value for matchPattern not valid when type is 'RegExp'.\" ) ; } if ( this . type != DatasetFilter . Type . REGULAR_EXPRESSION && this . type != null && this . matchPattern != null ) { isValid = false ; out . append ( \" ** DatasetFilter (7): matchPattern value (\" + this . matchPattern + \") must be null if type is not 'RegExp'.\" ) ; } return ( this . isValid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test whether the given dataset matches the filter criteria . [CODESPLIT] private boolean match ( InvDataset dataset ) { // Check whether this filter applies to the given dataset. if ( this . getParentDatasetSource ( ) . isCollection ( dataset ) && ! this . applyToCollectionDatasets ) return ( false ) ; if ( ( ! this . getParentDatasetSource ( ) . isCollection ( dataset ) ) && ! this . applyToAtomicDatasets ) return ( false ) ; // Set the default matchPatternTarget so old versions still work. if ( this . matchPatternTarget == null ) { if ( this . getParentDatasetSource ( ) . isCollection ( dataset ) ) { this . setMatchPatternTarget ( \"name\" ) ; } else { this . setMatchPatternTarget ( \"urlPath\" ) ; } } if ( this . type == DatasetFilter . Type . REGULAR_EXPRESSION ) { boolean isMatch ; if ( this . getMatchPatternTarget ( ) . equals ( \"name\" ) ) { java . util . regex . Matcher matcher = this . regExpPattern . matcher ( dataset . getName ( ) ) ; isMatch = matcher . find ( ) ; } else if ( this . getMatchPatternTarget ( ) . equals ( \"urlPath\" ) ) { java . util . regex . Matcher matcher = this . regExpPattern . matcher ( ( ( InvDatasetImpl ) dataset ) . getUrlPath ( ) ) ; isMatch = matcher . find ( ) ; } else { // ToDo deal with any matchPatternTarget (XPath-ish) isMatch = false ; } //      // Invert the meaning of a match (accept things that don't match). //      if ( this.isRejectMatchingDatasets()) //      { //        // If match, return false. //        return( regExpMatch == null ? true : false ); //      } //      // Don't invert (a match is a match). //      else //      { // If match, return true. return ( isMatch ) ; //      } } else { System . err . println ( \"WARNING -- DatasetFilter.accept(): unsupported type\" + \" <\" + this . type . toString ( ) + \">.\" ) ; return ( false ) ; // @todo think about exceptions. //throw new java.lang.Exception( \"DatasetFilter.accept():\" + //  \" unsupported type <\" + this.type.toString() + \">.\"); } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a dataset and a group of filters return true if the group of filters indicates that the dataset should be accepted false if it should be rejected . <p / > To make filtering out a set of datasets as easy as allowing a set of datasets DatasetFilter provides a dataset reject mode as well as a dataset accept mode . Rejection of a dataset by any filter overrides acceptance by any number of filters . Therefore to be accepted by the group a dataset needs to be accepted by at least one filter however rejection by a single filter will cause rejection by the group . <p / > If the filter group is empty the dataset will be accepted . [CODESPLIT] public static boolean acceptDatasetByFilterGroup ( List filters , InvDataset dataset , boolean isCollectionDataset ) { if ( filters == null ) throw new NullPointerException ( \"Given null list of filters.\" ) ; if ( dataset == null ) throw new NullPointerException ( \"Given null dataset.\" ) ; // If not filters, accept all datasets. if ( filters . isEmpty ( ) ) return ( true ) ; // Loop through DatasetFilter list to check if current dataset should be accepted. // @todo If none of the filters apply to directories, accept all directories. boolean accept = false ; boolean anyApplyToAtomic = false ; boolean anyApplyToCollection = false ; for ( Iterator it = filters . iterator ( ) ; it . hasNext ( ) ; ) { DatasetFilter curFilter = ( DatasetFilter ) it . next ( ) ; anyApplyToAtomic |= curFilter . isApplyToAtomicDatasets ( ) ; anyApplyToCollection |= curFilter . isApplyToCollectionDatasets ( ) ; if ( curFilter . isAcceptMatchingDatasets ( ) ) { if ( curFilter . accept ( dataset ) ) { accept = true ; // Dataset accepted by current DatasetFilter. } } else // if ( ! curFilter.isAcceptMatchingDatasets()) { if ( curFilter . reject ( dataset ) ) { return ( false ) ; // Rejection takes precedence over accpetance } } } // At least one filter accepted (and none rejected), so accept. if ( accept ) return ( true ) ; // Check if any filters apply to dataset. If none apply, accept the dataset. if ( isCollectionDataset ) { if ( ! anyApplyToCollection ) return ( true ) ; // Collection ds, no collection filters. } else { if ( ! anyApplyToAtomic ) return ( true ) ; // Atomic ds, no atomic filters. } // Dataset not accepted or rejected by any DatasetFilter (so reject). return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fdPoint remains open . [CODESPLIT] public void addAll ( FeatureDatasetPoint fdPoint ) throws IOException { try ( PointFeatureIterator pointFeatIter = new FlattenedDatasetPointCollection ( fdPoint ) . getPointFeatureIterator ( ) ) { while ( pointFeatIter . hasNext ( ) ) { StationPointFeature pointFeat = ( StationPointFeature ) pointFeatIter . next ( ) ; add ( pointFeat ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Double - check idiom for lazy initialization of instance fields . See Effective Java 2nd Ed p . 283 . [CODESPLIT] private StationFeatureCopyFactory getStationFeatureCopyFactory ( StationPointFeature proto ) throws IOException { if ( stationFeatCopyFactory == null ) { synchronized ( this ) { if ( stationFeatCopyFactory == null ) { stationFeatCopyFactory = createStationFeatureCopyFactory ( proto ) ; } } } assert stationFeatCopyFactory != null : \"We screwed this up.\" ; return stationFeatCopyFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a constraint expression . Variables in the projection are marked as such in the CEEvaluator s ServerDDS instance . The selection subexpression is then parsed and a list of Clause objects is built . <p / > The parser is located in opendap . servers . parsers . CeParser . [CODESPLIT] public void parseConstraint ( String constraint , String urlencoded ) throws ParseException , opendap . dap . DAP2Exception , NoSuchVariableException , NoSuchFunctionException , InvalidOperatorException , InvalidParameterException , SBHException , WrongTypeException { if ( clauseFactory == null ) { clauseFactory = new ClauseFactory ( ) ; } // Parses constraint expression (duh...) and sets the // projection flag for each member of the CE's ServerDDS // instance. This also builds the list of clauses. try { CeParser . constraint_expression ( this , _dds . getFactory ( ) , clauseFactory , constraint , urlencoded ) ; } catch ( ConstraintException ce ) { // convert to a DAP2Exception ce . printStackTrace ( ) ; throw new DAP2Exception ( ce ) ; } if ( _Debug ) { int it = 0 ; Enumeration ec = getClauses ( ) ; System . out . println ( \"Results of clause parsing:\" ) ; if ( ! ec . hasMoreElements ( ) ) System . out . println ( \"    No Clauses Found.\" ) ; while ( ec . hasMoreElements ( ) ) { it ++ ; System . out . println ( \"    Clause \" + it + \": \" + ec . nextElement ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience wrapper for parseConstraint . [CODESPLIT] public void parseConstraint ( ReqState rs ) throws ParseException , opendap . dap . DAP2Exception , NoSuchVariableException , NoSuchFunctionException , InvalidOperatorException , InvalidParameterException , SBHException , WrongTypeException { parseConstraint ( rs . getConstraintExpression ( ) , rs . getRequestURL ( ) . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function sends the variables described in the constrained DDS to the output described by <code > sink< / code > . This function calls <code > parse_constraint () < / code > <code > BaseType :: read () < / code > and <code > ServerIO :: serialize () < / code > . [CODESPLIT] public void send ( String dataset , OutputStream sink , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { Enumeration e = _dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { ServerMethods s = ( ServerMethods ) e . nextElement ( ) ; if ( _Debug ) System . out . println ( \"Sending variable: \" + ( ( BaseType ) s ) . getEncodedName ( ) ) ; if ( s . isProject ( ) ) { if ( _Debug ) System . out . println ( \"Calling \" + ( ( BaseType ) s ) . getTypeName ( ) + \".serialize() (Name: \" + ( ( BaseType ) s ) . getEncodedName ( ) + \")\" ) ; //System.out.printf(\"serialize %s (%s) start=%d%n \", ((BaseType) s).getName(), ((BaseType) s).getTypeName(), //    ((DataOutputStream) sink).size()); s . serialize ( dataset , ( DataOutputStream ) sink , this , specialO ) ; } } //System.out.printf(\"serialize total size=%d%n \", ((DataOutputStream) sink).size()); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate all of the Clauses in the Clause vector . [CODESPLIT] public boolean evalClauses ( Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { boolean result = true ; Enumeration ec = getClauses ( ) ; while ( ec . hasMoreElements ( ) && result == true ) { Object o = ec . nextElement ( ) ; if ( _Debug ) { System . out . println ( \"Evaluating clause: \" + ec . nextElement ( ) ) ; } result = ( ( TopLevelClause ) o ) . evaluate ( ) ; } // Hack: pop the projections of all DArrayDimensions that // have been pushed. return ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mark all the variables in the DDS either as part of the current projection ( when <code > state< / code > is true ) or not ( <code > state< / code > is false ) . This is a convenience function that provides a way to clear or set an entire dataset described by a DDS with respect to its projection . [CODESPLIT] public void markAll ( boolean state ) throws DAP2Exception , NoSuchVariableException , SBHException { // For all the Variables in the DDS Enumeration e = _dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { // Get the thing Object o = e . nextElement ( ) ; //- Clip this to stop marking all dimensions of Grids and Arrays // If we are marking all for true, then we need to make sure // we get all the parts of each array and grid // This code should probably be moved into SDArray and SDGrid. // There we should add a resetProjections() method that changes // the current projection to be the entire array. 11/18/99 jhrg if ( state ) { if ( o instanceof SDArray ) { // Is this thing a SDArray? SDArray SDA = ( SDArray ) o ; // Get it's DArrayDimensions Enumeration eSDA = SDA . getDimensions ( ) ; while ( eSDA . hasMoreElements ( ) ) { DArrayDimension dad = ( DArrayDimension ) eSDA . nextElement ( ) ; // Tweak it's projection state dad . setProjection ( 0 , 1 , dad . getSize ( ) - 1 ) ; } } else if ( o instanceof SDGrid ) { // Is this thing a SDGrid? SDGrid SDG = ( SDGrid ) o ; SDArray sdgA = ( SDArray ) SDG . getVar ( 0 ) ; // Get it's internal SDArray. // Get it's DArrayDimensions Enumeration eSDA = sdgA . getDimensions ( ) ; while ( eSDA . hasMoreElements ( ) ) { DArrayDimension dad = ( DArrayDimension ) eSDA . nextElement ( ) ; // Tweak it's projection state dad . setProjection ( 0 , 1 , dad . getSize ( ) - 1 ) ; } } } //-------------------------- End Clip --------------------------- ServerMethods s = ( ServerMethods ) o ; s . setProject ( state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print all of the Clauses in the Clause vector . [CODESPLIT] public void printConstraint ( PrintWriter pw ) { Enumeration ec = getClauses ( ) ; boolean first = true ; while ( ec . hasMoreElements ( ) ) { Clause cl = ( Clause ) ec . nextElement ( ) ; if ( ! first ) pw . print ( \" & \" ) ; cl . printConstraint ( pw ) ; first = false ; } pw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Amend the given NetcdfFile with metadata from HDF - EOS structMetadata . All Variables named StructMetadata . n where n = 1 2 3 ... are read in and their contents concatenated to make the structMetadata String . [CODESPLIT] static public boolean amendFromODL ( NetcdfFile ncfile , Group eosGroup ) throws IOException { String smeta = getStructMetadata ( eosGroup ) ; if ( smeta == null ) { return false ; } HdfEos fixer = new HdfEos ( ) ; fixer . fixAttributes ( ncfile . getRootGroup ( ) ) ; fixer . amendFromODL ( ncfile , smeta ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Amend the given NetcdfFile with metadata from HDF - EOS structMetadata [CODESPLIT] private void amendFromODL ( NetcdfFile ncfile , String structMetadata ) throws IOException { Group rootg = ncfile . getRootGroup ( ) ; ODLparser parser = new ODLparser ( ) ; Element root = parser . parseFromString ( structMetadata ) ; // now we have the ODL in JDOM elements\r FeatureType featureType = null ; // SWATH\r Element swathStructure = root . getChild ( \"SwathStructure\" ) ; if ( swathStructure != null ) { List < Element > swaths = swathStructure . getChildren ( ) ; for ( Element elemSwath : swaths ) { Element swathNameElem = elemSwath . getChild ( \"SwathName\" ) ; if ( swathNameElem == null ) { log . warn ( \"No SwathName element in {} {} \" , elemSwath . getName ( ) , ncfile . getLocation ( ) ) ; continue ; } String swathName = NetcdfFile . makeValidCdmObjectName ( swathNameElem . getText ( ) . trim ( ) ) ; Group swathGroup = findGroupNested ( rootg , swathName ) ; //if (swathGroup == null)\r //  swathGroup = findGroupNested(rootg, H4header.createValidObjectName(swathName));\r if ( swathGroup != null ) { featureType = amendSwath ( ncfile , elemSwath , swathGroup ) ; } else { log . warn ( \"Cant find swath group {} {}\" , swathName , ncfile . getLocation ( ) ) ; } } } // GRID\r Element gridStructure = root . getChild ( \"GridStructure\" ) ; if ( gridStructure != null ) { List < Element > grids = gridStructure . getChildren ( ) ; for ( Element elemGrid : grids ) { Element gridNameElem = elemGrid . getChild ( \"GridName\" ) ; if ( gridNameElem == null ) { log . warn ( \"No GridName element in {} {} \" , elemGrid . getName ( ) , ncfile . getLocation ( ) ) ; continue ; } String gridName = NetcdfFile . makeValidCdmObjectName ( gridNameElem . getText ( ) . trim ( ) ) ; Group gridGroup = findGroupNested ( rootg , gridName ) ; //if (gridGroup == null)\r //  gridGroup = findGroupNested(rootg, H4header.createValidObjectName(gridName));\r if ( gridGroup != null ) { featureType = amendGrid ( elemGrid , ncfile , gridGroup , ncfile . getLocation ( ) ) ; } else { log . warn ( \"Cant find Grid group {} {}\" , gridName , ncfile . getLocation ( ) ) ; } } } // POINT - NOT DONE YET\r Element pointStructure = root . getChild ( \"PointStructure\" ) ; if ( pointStructure != null ) { List < Element > pts = pointStructure . getChildren ( ) ; for ( Element elem : pts ) { Element nameElem = elem . getChild ( \"PointName\" ) ; if ( nameElem == null ) { log . warn ( \"No PointName element in {} {}\" , elem . getName ( ) , ncfile . getLocation ( ) ) ; continue ; } String name = nameElem . getText ( ) . trim ( ) ; Group ptGroup = findGroupNested ( rootg , name ) ; //if (ptGroup == null)\r //  ptGroup = findGroupNested(rootg, H4header.createValidObjectName(name));\r if ( ptGroup != null ) { featureType = FeatureType . POINT ; } else { log . warn ( \"Cant find Point group {} {}\" , name , ncfile . getLocation ( ) ) ; } } } if ( featureType != null ) { if ( showWork ) { log . debug ( \"***EOS featureType= {}\" , featureType . toString ( ) ) ; } rootg . addAttribute ( new Attribute ( CF . FEATURE_TYPE , featureType . toString ( ) ) ) ; // rootg.addAttribute(new Attribute(CDM.CONVENTIONS, \"HDFEOS\"));\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert to shared dimensions [CODESPLIT] private void setSharedDimensions ( Variable v , List < Element > values , List < Dimension > unknownDims , String location ) { if ( values . size ( ) == 0 ) { return ; } // remove the \"scalar\" dumbension\r Iterator < Element > iter = values . iterator ( ) ; while ( iter . hasNext ( ) ) { Element value = iter . next ( ) ; String dimName = value . getText ( ) . trim ( ) ; if ( dimName . equalsIgnoreCase ( \"scalar\" ) ) { iter . remove ( ) ; } } // gotta have same number of dimensions\r List < Dimension > oldDims = v . getDimensions ( ) ; if ( oldDims . size ( ) != values . size ( ) ) { log . error ( \"Different number of dimensions for {} {}\" , v , location ) ; return ; } List < Dimension > newDims = new ArrayList <> ( ) ; Group group = v . getParentGroup ( ) ; for ( int i = 0 ; i < values . size ( ) ; i ++ ) { Element value = values . get ( i ) ; String dimName = value . getText ( ) . trim ( ) ; dimName = NetcdfFile . makeValidCdmObjectName ( dimName ) ; Dimension dim = group . findDimension ( dimName ) ; Dimension oldDim = oldDims . get ( i ) ; if ( dim == null ) { dim = checkUnknownDims ( dimName , unknownDims , oldDim , location ) ; } if ( dim == null ) { log . error ( \"Unknown Dimension= {} for variable = {} {} \" , dimName , v . getFullName ( ) , location ) ; return ; } if ( dim . getLength ( ) != oldDim . getLength ( ) ) { log . error ( \"Shared dimension ({}) has different length than data dimension ({}) shared={} org={} for {} {}\" , dim . getShortName ( ) , oldDim . getShortName ( ) , dim . getLength ( ) , oldDim . getLength ( ) , v , location ) ; return ; } newDims . add ( dim ) ; } v . setDimensions ( newDims ) ; if ( showWork ) { log . debug ( \" set shared dimensions for {}\" , v . getNameAndDimensions ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look if the wanted dimension is in the unknownDims list . [CODESPLIT] private Dimension checkUnknownDims ( String wantDim , List < Dimension > unknownDims , Dimension oldDim , String location ) { for ( Dimension dim : unknownDims ) { if ( dim . getShortName ( ) . equals ( wantDim ) ) { int len = oldDim . getLength ( ) ; if ( len == 0 ) { dim . setUnlimited ( true ) ; // allow zero length dimension !!\r } dim . setLength ( len ) ; // use existing (anon) dimension\r Group parent = dim . getGroup ( ) ; parent . addDimensionIfNotExists ( dim ) ; // add to the parent\r unknownDims . remove ( dim ) ; // remove from list LOOK is this ok?\r log . warn ( \"unknownDim {} length set to {}{}\" , wantDim , oldDim . getLength ( ) , location ) ; return dim ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for a group with the given name . recurse into subgroups if needed . breadth first [CODESPLIT] private Group findGroupNested ( Group parent , String name ) { for ( Group g : parent . getGroups ( ) ) { if ( g . getShortName ( ) . equals ( name ) ) { return g ; } } for ( Group g : parent . getGroups ( ) ) { Group result = findGroupNested ( g , name ) ; if ( result != null ) { return result ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get inline content as a string else null if there is none [CODESPLIT] public String readXlinkContent ( ) throws java . io . IOException { if ( uri == null ) return \"\" ; URL url = uri . toURL ( ) ; InputStream is = url . openStream ( ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( is . available ( ) ) ; // copy to string byte [ ] buffer = new byte [ 1024 ] ; while ( true ) { int bytesRead = is . read ( buffer ) ; if ( bytesRead == - 1 ) break ; os . write ( buffer , 0 , bytesRead ) ; } is . close ( ) ; return new String ( os . toByteArray ( ) , CDM . utf8Charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the standard URL with resolution if the URL is reletive . catalog . resolveURI ( getUnresolvedUrlName () ) [CODESPLIT] public String getStandardUrlName ( ) { URI uri = getStandardUri ( ) ; if ( uri == null ) return null ; return uri . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct the standard THREDDS access URI for this dataset access method resolve if the URI is relative . [CODESPLIT] public URI getStandardUri ( ) { try { InvCatalog cat = dataset . getParentCatalog ( ) ; if ( cat == null ) return new URI ( getUnresolvedUrlName ( ) ) ; return cat . resolveUri ( getUnresolvedUrlName ( ) ) ; } catch ( java . net . URISyntaxException e ) { logger . warn ( \"Error parsing URL= \" + getUnresolvedUrlName ( ) ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "********************************************************************** Parse the . ini file indicated by the <code > private String iniFile< / code > . [CODESPLIT] private void parseFile ( ) { try { try ( BufferedReader fp = new BufferedReader ( new InputStreamReader ( new FileInputStream ( iniFile ) , Charset . forName ( \"UTF-8\" ) ) ) ; ) { boolean done = false ; while ( ! done ) { String thisLine = fp . readLine ( ) ; if ( thisLine != null && thisLine . trim ( ) . length ( ) == 0 ) thisLine = null ; if ( thisLine != null ) { if ( Debug ) System . out . println ( \"Read: \\\"\" + thisLine + \"\\\"\" ) ; if ( thisLine . startsWith ( \";\" ) || thisLine . equalsIgnoreCase ( \"\" ) ) { // Do nothing, it's a comment if ( Debug ) System . out . println ( \"Ignoring comment or blank line...\" ) ; } else { int cindx = thisLine . indexOf ( \";\" ) ; if ( cindx > 0 ) thisLine = thisLine . substring ( 0 , cindx ) . trim ( ) ; if ( Debug ) System . out . println ( \"Comments removed: \\\"\" + thisLine + \"\\\"\" ) ; if ( thisLine . startsWith ( \"[\" ) && thisLine . endsWith ( \"]\" ) ) { String sname = thisLine . substring ( 1 , thisLine . length ( ) - 1 ) . trim ( ) ; if ( Debug ) System . out . println ( \"Found Section Name: \" + sname ) ; if ( sectionNames == null ) sectionNames = new Vector ( ) ; sectionNames . add ( sname ) ; if ( sectionProperties == null ) sectionProperties = new Vector ( ) ; sectionProperties . add ( new Vector ( ) ) ; } else if ( sectionNames != null && sectionProperties != null ) { int eqidx = thisLine . indexOf ( \"=\" ) ; if ( eqidx != - 1 ) { String pair [ ] = new String [ 2 ] ; pair [ 0 ] = thisLine . substring ( 0 , eqidx ) . trim ( ) ; pair [ 1 ] = thisLine . substring ( eqidx + 1 , thisLine . length ( ) ) . trim ( ) ; if ( Debug ) System . out . println ( \"pair[0]: \\\"\" + pair [ 0 ] + \"\\\"   pair[1]: \\\"\" + pair [ 1 ] + \"\\\"\" ) ; // Add the pair to the current property list, which is the // last element in the sectionProperties vector. ( ( Vector ) sectionProperties . lastElement ( ) ) . add ( pair ) ; } } } } else { done = true ; } } } } catch ( FileNotFoundException e ) { System . err . println ( \"Could Not Find ini File: \\\"\" + iniFile + \"\\\"\" ) ; } catch ( IOException e ) { System . err . println ( \"Could Not Read ini File: \\\"\" + iniFile + \"\\\"\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "********************************************************************** Get the list of properties for the section <code > sectionName< / code > . [CODESPLIT] public Enumeration getPropList ( String sectionName ) { if ( sectionNames == null ) { System . err . println ( errMsg ) ; return ( null ) ; } int sectionIndex = 0 ; Enumeration e = sectionNames . elements ( ) ; boolean done = false ; while ( ! done && e . hasMoreElements ( ) ) { String thisName = ( String ) e . nextElement ( ) ; if ( sectionName . equalsIgnoreCase ( thisName ) ) done = true ; else sectionIndex ++ ; } if ( ! done ) return ( null ) ; return ( ( ( Vector ) sectionProperties . elementAt ( sectionIndex ) ) . elements ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "********************************************************************** Get the named property from the current section . [CODESPLIT] public String getProperty ( String propertyName ) { if ( currentSection < 0 ) { String msg = \"You must use the setSection() method before you can use getProperty().\" ; System . err . println ( msg ) ; return ( msg ) ; } String pair [ ] = null ; Enumeration e = ( ( Vector ) sectionProperties . elementAt ( currentSection ) ) . elements ( ) ; boolean done = false ; while ( ! done && e . hasMoreElements ( ) ) { pair = ( String [ ] ) e . nextElement ( ) ; if ( pair [ 0 ] . equalsIgnoreCase ( propertyName ) ) done = true ; } if ( done ) return ( pair [ 1 ] ) ; return ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "********************************************************************** Prints the iniFile . [CODESPLIT] public void printProps ( PrintStream ps ) { Enumeration se = getSectionList ( ) ; if ( se == null ) { ps . println ( errMsg ) ; } else { while ( se . hasMoreElements ( ) ) { String sname = ( String ) se . nextElement ( ) ; setSection ( sname ) ; ps . println ( \"[\" + sname + \"]\" ) ; Enumeration pe = getPropList ( sname ) ; while ( pe != null && pe . hasMoreElements ( ) ) { String pair [ ] = ( String [ ] ) pe . nextElement ( ) ; String prop = pair [ 0 ] ; String valu = getProperty ( prop ) ; ps . println ( \"    \\\"\" + prop + \"\\\" = \\\"\" + valu + \"\\\"\" ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "********************************************************************** Set the section of the iniFile that you wish to work with . This is persistent for the life of the object or until it s set again . [CODESPLIT] public boolean setSection ( String sectionName ) { if ( sectionNames == null ) { System . err . println ( errMsg ) ; return ( false ) ; } int sectionIndex = 0 ; Enumeration e = sectionNames . elements ( ) ; boolean done = false ; while ( ! done && e . hasMoreElements ( ) ) { String thisName = ( String ) e . nextElement ( ) ; if ( sectionName . equalsIgnoreCase ( thisName ) ) done = true ; else sectionIndex ++ ; } if ( ! done ) return ( false ) ; currentSection = sectionIndex ; return ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct input fields based on Projection Class [CODESPLIT] public void setProjection ( ProjectionManager . ProjectionClass pc ) { // clear out any fields\r removeAll ( ) ; for ( ProjectionManager . ProjectionParam pp : pc . paramList ) { // construct the label\r JPanel thisPanel = new JPanel ( ) ; thisPanel . add ( new JLabel ( pp . name + \": \" ) ) ; // text input field\r JTextField tf = new JTextField ( ) ; pp . setTextField ( tf ) ; tf . setColumns ( 12 ) ; thisPanel . add ( tf ) ; add ( thisPanel ) ; } revalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changed 4 / 28 / 10 dmh : legal dods names are not same as legal javascript names so translate . [CODESPLIT] public static String nameForJsCode ( String dodsName ) { StringBuilder buf = new StringBuilder ( dodsName ) ; for ( int i = 0 ; i < buf . length ( ) ; i ++ ) { char c = buf . charAt ( i ) ; if ( c == ' ' ) buf . replace ( i , i + 1 , \"_\" ) ; else if ( legal_javascript_id_chars . indexOf ( c ) < 0 ) { String s = \"_\" + String . valueOf ( ( int ) c ) + \"_\" ; buf . replace ( i , i + 1 , s ) ; } } return \"dods_\" + buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * void WWWOutput :: write_variable_entries ( DAS &das DDS &dds ) { This writes the text Variables : and then sets up the table so that the first variable s section is written into column two . _os << \\ <tr > <td align = \\ right \\ valign = \\ top \\ > <h3 > <a href = \\ dods_form_help . html#dataset_variables \\ > Variables : < / a > < / h3 > <td > ; [CODESPLIT] public void writeVariableEntries ( DAS das , DDS dds ) { // This writes the text `Variables:' and then sets up the table\r // so that the first variable's section is written into column two.\r pWrt . print ( \"<tr>\\n\" + \"<td align=\\\"right\\\" valign=\\\"top\\\">\\n\" + \"<h3><a href=\\\"opendap_form_help.html#dataset_variables\\\">Variables:</a></h3>\\n\" + \"<br><td>\\n\" ) ; Enumeration e = dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; ( ( BrowserForm ) bt ) . printBrowserForm ( pWrt , das ) ; writeVariableAttributes ( bt , das ) ; pWrt . print ( \"\\n<p><p>\\n\\n\" ) ; // End the current var's section\r pWrt . print ( \"<tr><td><td>\\n\\n\" ) ; // Start the next var in column two\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * void WWWOutput :: write_variable_attributes ( BaseType * btp DAS &das ) { AttrTable * attr = das . get_table ( btp - > name () ) ; Don t write anything if there are no attributes . if ( !attr ) return ; [CODESPLIT] public void writeVariableAttributes ( BaseType bt , DAS das ) { try { AttributeTable attr = das . getAttributeTable ( bt . getEncodedName ( ) ) ; if ( attr != null ) { pWrt . print ( \"<textarea name=\\\"\" + bt . getLongName ( ) . replace ( ' ' , ' ' ) + \"_attr\" + \"\\\" rows=\" + _attrRows + \" cols=\" + _attrCols + \">\\n\" ) ; writeAttributes ( attr ) ; pWrt . print ( \"</textarea>\\n\\n\" ) ; } } catch ( NoSuchAttributeException nsae ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : featureOfInterest / wml2 : MonitoringPoint / sams : shape [CODESPLIT] public static ShapeType initShape ( ShapeType shape , StationTimeSeriesFeature stationFeat ) { // gml:Point PointDocument pointDoc = PointDocument . Factory . newInstance ( ) ; NcPointType . initPoint ( pointDoc . addNewPoint ( ) , stationFeat ) ; shape . set ( pointDoc ) ; return shape ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified component to the layout using the specified constraint object . [CODESPLIT] public void addLayoutComponent ( Component comp , Object constraint ) { if ( debug ) System . out . println ( name + \" addLayoutComponent= \" + comp . getClass ( ) . getName ( ) + \" \" + comp . hashCode ( ) + \" \" + constraint ) ; if ( ! ( constraint instanceof Constraint ) ) throw new IllegalArgumentException ( \"MySpringLayout must be Constraint\" ) ; constraintMap . put ( comp , constraint ) ; globalBounds = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invalidates the layout indicating that if the layout manager has cached information it should be discarded . [CODESPLIT] public void invalidateLayout ( Container target ) { if ( debug ) System . out . println ( name + \" invalidateLayout \" ) ; globalBounds = null ; // this probably need to be scheduled later ?? // layoutContainer( target); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified component from the layout . [CODESPLIT] public void removeLayoutComponent ( Component comp ) { if ( debug ) System . out . println ( \"removeLayoutComponent\" ) ; constraintMap . remove ( comp ) ; globalBounds = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the preferred size dimensions for the specified container given the components it contains . @param parent the container to be laid out [CODESPLIT] public Dimension preferredLayoutSize ( Container parent ) { if ( globalBounds == null ) layoutContainer ( parent ) ; if ( debug ) System . out . println ( name + \" preferredLayoutSize \" + globalBounds . getSize ( ) + \" \" + parent . getInsets ( ) ) ; return globalBounds . getSize ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the minimum size dimensions for the specified container given the components it contains . [CODESPLIT] public Dimension minimumLayoutSize ( Container parent ) { if ( debug ) System . out . println ( \"minimumLayoutSize\" ) ; if ( globalBounds == null ) layoutContainer ( parent ) ; return globalBounds . getSize ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lays out the specified container . [CODESPLIT] public void layoutContainer ( Container target ) { synchronized ( target . getTreeLock ( ) ) { if ( debug ) System . out . println ( name + \" layoutContainer \" ) ; // first layout any nested LayoutM components // it seems that generally Swing laysout from outer to inner ??? int n = target . getComponentCount ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Component comp = target . getComponent ( i ) ; if ( comp instanceof Container ) { Container c = ( Container ) comp ; LayoutManager m = c . getLayout ( ) ; if ( m instanceof LayoutM ) m . layoutContainer ( c ) ; } } // now layout this container reset ( target ) ; globalBounds = new Rectangle ( 0 , 0 , 0 , 0 ) ; while ( ! layoutPass ( target ) ) target . setPreferredSize ( globalBounds . getSize ( ) ) ; // ?? } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this CoordinateSystem can be made into a RadialCoordSys . [CODESPLIT] public static boolean isRadialCoordSys ( Formatter parseInfo , CoordinateSystem cs ) { return ( cs . getAzimuthAxis ( ) != null ) && ( cs . getRadialAxis ( ) != null ) && ( cs . getElevationAxis ( ) != null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the CoordinateSystem cs can be made into a GridCoordSys for the Variable v . [CODESPLIT] public static RadialCoordSys makeRadialCoordSys ( Formatter parseInfo , CoordinateSystem cs , VariableEnhanced v ) { if ( parseInfo != null ) { parseInfo . format ( \" \" ) ; v . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( \" check CS \" + cs . getName ( ) ) ; } if ( isRadialCoordSys ( parseInfo , cs ) ) { RadialCoordSys rcs = new RadialCoordSys ( cs ) ; if ( cs . isComplete ( v ) ) { if ( parseInfo != null ) parseInfo . format ( \" OK%n\" ) ; return rcs ; } else { if ( parseInfo != null ) parseInfo . format ( \" NOT complete%n\" ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the maximum radial distance in km . [CODESPLIT] public double getMaximumRadial ( ) { if ( maxRadial == 0.0 ) { try { Array radialData = getRadialAxisDataCached ( ) ; maxRadial = MAMath . getMaximum ( radialData ) ; String units = getRadialAxis ( ) . getUnitsString ( ) ; SimpleUnit radialUnit = SimpleUnit . factory ( units ) ; maxRadial = radialUnit . convertTo ( maxRadial , SimpleUnit . kmUnit ) ; // convert to km } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } } return maxRadial ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the units of Calendar time . To get a Date from a time value call DateUnit . getStandardDate ( double value ) . To get units as a String call DateUnit . getUnitsString () . [CODESPLIT] public ucar . nc2 . units . DateUnit getTimeUnits ( ) throws Exception { if ( null == dateUnit ) { dateUnit = new DateUnit ( timeAxis . getUnitsString ( ) ) ; } return dateUnit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] static public void main ( String [ ] args ) { System . out . println ( \"1 Deg=\" + Math . toDegrees ( 1000 * 111.0 / Earth . getRadius ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data for the given point ( earthlocation ) and if bounded is true returns data for the closest point within the grid for points outside of the grid [CODESPLIT] public Point readData ( GridDatatype grid , CalendarDate date , EarthLocation location , boolean bounded ) throws java . io . IOException { if ( ! bounded ) { if ( Double . isNaN ( location . getAltitude ( ) ) ) { return readData ( grid , date , location . getLatitude ( ) , location . getLongitude ( ) ) ; } else { return readData ( grid , date , location . getAltitude ( ) , location . getLatitude ( ) , location . getLongitude ( ) ) ; } } //Bounded --> Read closest data \r GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; int tidx = findTimeIndexForCalendarDate ( gcs , date ) ; int [ ] xy = gcs . findXYindexFromLatLonBounded ( location . getLatitude ( ) , location . getLongitude ( ) , null ) ; LatLonPoint latlon = gcs . getLatLon ( xy [ 0 ] , xy [ 1 ] ) ; Point p = new Point ( ) ; p . lat = latlon . getLatitude ( ) ; p . lon = latlon . getLongitude ( ) ; int zidx = - 1 ; if ( ! Double . isNaN ( location . getAltitude ( ) ) ) { CoordinateAxis1D zAxis = gcs . getVerticalAxis ( ) ; zidx = zAxis . findCoordElement ( location . getAltitude ( ) ) ; p . z = zAxis . getCoordValue ( zidx ) ; } Array data = grid . readDataSlice ( tidx , zidx , xy [ 1 ] , xy [ 0 ] ) ; p . dataValue = data . getDouble ( data . getIndex ( ) ) ; return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ///////////////////////////////////////////////////// Uses apache HttpComponents [CODESPLIT] private HTTPMethod processMethod ( HTTPSession httpclient , String url , Command cmd ) throws HTTPException , UnsupportedEncodingException { HTTPMethod m = null ; if ( cmd == Command . GET ) m = HTTPFactory . Get ( httpclient , url ) ; else if ( cmd == Command . HEAD ) m = HTTPFactory . Head ( httpclient , url ) ; else if ( cmd == Command . OPTIONS ) m = HTTPFactory . Options ( httpclient , url ) ; else if ( cmd == Command . PUT ) { m = HTTPFactory . Put ( httpclient , url ) ; m . setRequestContent ( new StringEntity ( ta . getText ( ) ) ) ; // was  setRequestContentAsString(ta.getText());\r } return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses apache commons HttpClient [CODESPLIT] @ Urlencoded private void openURL2 ( String urlString , Command cmd ) { HTTPMethod m ; try ( HTTPSession httpclient = HTTPFactory . newSession ( urlString ) ) { /* you might think this works, but it doesnt:\r\n      URI raw = new URI(urlString.trim());\r\n      appendLine(\"raw scheme= \" + raw.getScheme() + \"\\n auth= \" + raw.getRawAuthority() + \"\\n path= \" + raw.getRawPath() +\r\n           \"\\n query= \" + raw.getRawQuery() + \"\\n fragment= \" + raw.getRawFragment()+\"\\n\");\r\n\r\n      URI url = new URI(raw.getScheme(), raw.getRawAuthority(),\r\n              URIUtil.encodePath(raw.getRawPath()),\r\n              URIUtil.encodeQuery(raw.getRawQuery()),\r\n              raw.getRawFragment());\r\n      appendLine(\"encoded scheme= \" + url.getScheme() + \"\\n auth= \" + url.getAuthority() + \"\\n path= \" + url.getPath() +\r\n           \"\\n query= \" + url.getQuery() + \"\\n fragment= \" + url.getFragment()+\"\\n\");\r\n      urlString = url.toString();\r\n              */ //urlString = URLnaming.escapeQuery(urlString);\r if ( cmd == Command . GET ) m = HTTPFactory . Get ( httpclient , urlString ) ; else if ( cmd == Command . HEAD ) m = HTTPFactory . Head ( httpclient , urlString ) ; else if ( cmd == Command . OPTIONS ) m = HTTPFactory . Options ( httpclient , urlString ) ; else if ( cmd == Command . PUT ) { m = HTTPFactory . Put ( httpclient , urlString ) ; m . setRequestContent ( new StringEntity ( ta . getText ( ) ) ) ; // was  setRequestContentAsString(ta.getText());\r } else { throw new IOException ( \"Unsupported command: \" + cmd ) ; } m . setCompression ( \"gzip,deflate\" ) ; /* FIX\r\n      appendLine(\"HttpClient \" + m.getName() + \" \" + urlString);\r\n\r\n      appendLine(\"   do Authentication= \" + m.getDoAuthentication());\r\n      appendLine(\"   follow Redirects= \" + m.getFollowRedirects());\r\n\r\n\r\n      appendLine(\"   cookie policy= \" + p.getCookiePolicy());\r\n      appendLine(\"   http version= \" + p.getVersion().toString());\r\n      appendLine(\"   timeout (msecs)= \" + p.getSoTimeout());\r\n      appendLine(\"   virtual host= \" + p.getVirtualHost());\r\n      */ printHeaders ( \"Request Headers = \" , m . getRequestHeaders ( ) ) ; appendLine ( \" \" ) ; m . execute ( ) ; printHeaders ( \"Request Headers2 = \" , m . getRequestHeaders ( ) ) ; appendLine ( \" \" ) ; appendLine ( \"Status = \" + m . getStatusCode ( ) + \" \" + m . getStatusText ( ) ) ; appendLine ( \"Status Line = \" + m . getStatusLine ( ) ) ; printHeaders ( \"Response Headers = \" , m . getResponseHeaders ( ) ) ; if ( cmd == Command . GET ) { appendLine ( \"\\nResponseBody---------------\" ) ; String charset = m . getResponseCharSet ( ) ; if ( charset == null ) charset = CDM . UTF8 ; String contents = null ; // check for deflate and gzip compression\r Header h = m . getResponseHeader ( \"content-encoding\" ) ; String encoding = ( h == null ) ? null : h . getValue ( ) ; if ( encoding != null && encoding . equals ( \"deflate\" ) ) { byte [ ] body = m . getResponseAsBytes ( ) ; if ( body != null ) { InputStream is = new BufferedInputStream ( new InflaterInputStream ( new ByteArrayInputStream ( body ) ) , 10000 ) ; contents = IO . readContents ( is , charset ) ; double ratio = ( double ) contents . length ( ) / body . length ; appendLine ( \"  deflate encoded=\" + body . length + \" decoded=\" + contents . length ( ) + \" ratio= \" + ratio ) ; } } else if ( encoding != null && encoding . equals ( \"gzip\" ) ) { byte [ ] body = m . getResponseAsBytes ( ) ; if ( body != null ) { InputStream is = new BufferedInputStream ( new GZIPInputStream ( new ByteArrayInputStream ( body ) ) , 10000 ) ; contents = IO . readContents ( is , charset ) ; double ratio = ( double ) contents . length ( ) / body . length ; appendLine ( \"  gzip encoded=\" + body . length + \" decoded=\" + contents . length ( ) + \" ratio= \" + ratio ) ; } } else { byte [ ] body = m . getResponseAsBytes ( 50 * 1000 ) ; // max 50 Kbytes\r contents = ( body == null ) ? \"\" : new String ( body , charset ) ; } if ( contents != null ) { if ( contents . length ( ) > 50 * 1000 ) // limit contents\r contents = contents . substring ( 0 , 50 * 1000 ) ; appendLine ( contents ) ; } } else if ( cmd == Command . OPTIONS ) printSet ( \"AllowedMethods = \" , HTTPFactory . getAllowedMethods ( ) ) ; } catch ( IOException e ) { StringWriter sw = new StringWriter ( 5000 ) ; e . printStackTrace ( new PrintWriter ( sw ) ) ; appendLine ( sw . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses java . net [CODESPLIT] private void openURL ( String urlString , Command command ) { try { //Open the URLConnection for reading\r URL u = new URL ( urlString ) ; currentConnection = ( HttpURLConnection ) u . openConnection ( ) ; currentConnection . setRequestMethod ( command . toString ( ) ) ; // GET or HEAD\r currentConnection . setAllowUserInteraction ( true ) ; clear ( ) ; appendLine ( command + \" request for \" + urlString ) ; // request headers\r Map < String , List < String > > reqs = currentConnection . getRequestProperties ( ) ; for ( Map . Entry < String , List < String > > ent : reqs . entrySet ( ) ) { append ( \" \" + ent . getKey ( ) + \": \" ) ; for ( String v : ent . getValue ( ) ) append ( v + \" \" ) ; appendLine ( \"\" ) ; } appendLine ( \"\" ) ; appendLine ( \"getFollowRedirects=\" + HttpURLConnection . getFollowRedirects ( ) ) ; appendLine ( \"getInstanceFollowRedirects=\" + currentConnection . getInstanceFollowRedirects ( ) ) ; appendLine ( \"AllowUserInteraction=\" + currentConnection . getAllowUserInteraction ( ) ) ; appendLine ( \"\" ) ; int code = currentConnection . getResponseCode ( ) ; String response = currentConnection . getResponseMessage ( ) ; // response headers\r appendLine ( \" HTTP/1.x \" + code + \" \" + response ) ; appendLine ( \" content-length: \" + currentConnection . getContentLength ( ) ) ; appendLine ( \" content-encoding: \" + currentConnection . getContentEncoding ( ) ) ; appendLine ( \" content-type: \" + currentConnection . getContentType ( ) ) ; appendLine ( \"\\nHeaders: \" ) ; for ( int j = 1 ; true ; j ++ ) { String header = currentConnection . getHeaderField ( j ) ; String key = currentConnection . getHeaderFieldKey ( j ) ; if ( header == null || key == null ) break ; appendLine ( \" \" + key + \": \" + header ) ; } appendLine ( \"\" ) ; appendLine ( \"contents:\" ) ; // read it\r java . io . InputStream is = currentConnection . getInputStream ( ) ; ByteArrayOutputStream bout = new ByteArrayOutputStream ( 200000 ) ; IO . copy ( is , bout ) ; is . close ( ) ; append ( new String ( bout . toByteArray ( ) , CDM . utf8Charset ) ) ; appendLine ( \"end contents\" ) ; } catch ( MalformedURLException e ) { append ( urlString + \" is not a parseable URL\" ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform geographic Earth coordinates to satellite view angle coordinate system also known as the intermediate coordinate system in CGMS Normalized Geostationary Projection . [CODESPLIT] public double [ ] earthToSat ( double geographic_lon , double geographic_lat ) { geographic_lat = geographic_lat * DEG_TO_RAD ; geographic_lon = geographic_lon * DEG_TO_RAD ; double geocentric_lat = Math . atan ( ( ( r_pol * r_pol ) / ( r_eq * r_eq ) ) * Math . tan ( geographic_lat ) ) ; double r_earth = r_pol / Math . sqrt ( 1.0 - ( ( r_eq * r_eq - r_pol * r_pol ) / ( r_eq * r_eq ) ) * Math . cos ( geocentric_lat ) * Math . cos ( geocentric_lat ) ) ; double r_1 = h - r_earth * Math . cos ( geocentric_lat ) * Math . cos ( geographic_lon - sub_lon ) ; double r_2 = - r_earth * Math . cos ( geocentric_lat ) * Math . sin ( geographic_lon - sub_lon ) ; double r_3 = r_earth * Math . sin ( geocentric_lat ) ; if ( r_1 > h ) { // often two geoid intersect points, use the closer one. return new double [ ] { Double . NaN , Double . NaN } ; } double lamda_sat = Double . NaN ; double theta_sat = Double . NaN ; if ( scan_geom . equals ( GEOS ) ) { // GEOS (eg. SEVIRI, MSG)  CGMS 03, 4.4.3.2, Normalized Geostationary Projection lamda_sat = Math . atan ( - r_2 / r_1 ) ; theta_sat = Math . asin ( r_3 / Math . sqrt ( r_1 * r_1 + r_2 * r_2 + r_3 * r_3 ) ) ; } else if ( scan_geom . equals ( GOES ) ) { // GOES (eg. GOES-R ABI) lamda_sat = Math . asin ( - r_2 / Math . sqrt ( r_1 * r_1 + r_2 * r_2 + r_3 * r_3 ) ) ; theta_sat = Math . atan ( r_3 / r_1 ) ; } return new double [ ] { lamda_sat , theta_sat } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform satellite view angle coordinates known as the intermeidate coordinates in the CGMS Normalized Geostationary Projection to geographic Earth coordinates . [CODESPLIT] public double [ ] satToEarth ( double x , double y ) { if ( scan_geom . equals ( GOES ) ) { // convert from GOES to GEOS for transfrom below double [ ] lambda_theta_geos = GOES_to_GEOS ( x , y ) ; x = lambda_theta_geos [ 0 ] ; y = lambda_theta_geos [ 1 ] ; } double c1 = ( h * Math . cos ( x ) * Math . cos ( y ) ) * ( h * Math . cos ( x ) * Math . cos ( y ) ) ; double c2 = ( Math . cos ( y ) * Math . cos ( y ) + fp * Math . sin ( y ) * Math . sin ( y ) ) * d ; if ( c1 < c2 ) { return new double [ ] { Double . NaN , Double . NaN } ; } double s_d = Math . sqrt ( c1 - c2 ) ; double s_n = ( h * Math . cos ( x ) * Math . cos ( y ) - s_d ) / ( Math . cos ( y ) * Math . cos ( y ) + fp * Math . sin ( y ) * Math . sin ( y ) ) ; double s_1 = h - s_n * Math . cos ( x ) * Math . cos ( y ) ; double s_2 = s_n * Math . sin ( x ) * Math . cos ( y ) ; double s_3 = - s_n * Math . sin ( y ) ; double s_xy = Math . sqrt ( s_1 * s_1 + s_2 * s_2 ) ; double geographic_lon = Math . atan ( s_2 / s_1 ) + sub_lon ; double geographic_lat = Math . atan ( - fp * ( s_3 / s_xy ) ) ; double lonDegrees = RAD_TO_DEG * geographic_lon ; double latDegrees = RAD_TO_DEG * geographic_lat ; // force output longitude to -180 to 180 range if ( lonDegrees < - 180.0 ) lonDegrees += 360.0 ; if ( lonDegrees > 180.0 ) lonDegrees -= 360.0 ; return new double [ ] { lonDegrees , latDegrees } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform view angle coordinates in the GOES scan geometry frame to view angle coordinates in the GEOS scan geometry frame . [CODESPLIT] public double [ ] GOES_to_GEOS ( double lamda_goes , double theta_goes ) { double theta_geos = Math . asin ( Math . sin ( theta_goes ) * Math . cos ( lamda_goes ) ) ; double lamda_geos = Math . atan ( Math . tan ( lamda_goes ) / Math . cos ( theta_goes ) ) ; return new double [ ] { lamda_geos , theta_geos } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform fractional FGF coordinates to ( longitude latitude ) . [CODESPLIT] public double [ ] FGFtoEarth ( double fgf_x , double fgf_y , double scale_x , double offset_x , double scale_y , double offset_y ) { double [ ] xy = FGFtoSat ( fgf_x , fgf_y , scale_x , offset_x , scale_y , offset_y ) ; return satToEarth ( xy [ 0 ] , xy [ 1 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform fractional FGF coordinates to ( lamda theta ) radians . [CODESPLIT] public double [ ] FGFtoSat ( double fgf_x , double fgf_y , double scale_x , double offset_x , double scale_y , double offset_y ) { double x = fgf_x * scale_x + offset_x ; double y = fgf_y * scale_y + offset_y ; return new double [ ] { x , y } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform integer FGF coordinates to ( longitude latitude ) of pixel center The ( i j ) pixel zero - based refers to the pixel center . [CODESPLIT] public double [ ] elemLineToEarth ( int elem , int line , double scale_x , double offset_x , double scale_y , double offset_y ) { return FGFtoEarth ( ( double ) elem , ( double ) line , scale_x , offset_x , scale_y , offset_y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform Earth coordinates ( lon lat ) to fractional FGF coordinates . [CODESPLIT] public double [ ] earthToFGF ( double geographic_lon , double geographic_lat , double scale_x , double offset_x , double scale_y , double offset_y ) { double [ ] xy = earthToSat ( geographic_lon , geographic_lat ) ; return SatToFGF ( xy [ 0 ] , xy [ 1 ] , scale_x , offset_x , scale_y , offset_y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform pixel center Earth coordinates ( lon lat ) to integer FGF coordinates . [CODESPLIT] public int [ ] earthToElemLine ( double geographic_lon , double geographic_lat , double scale_x , double offset_x , double scale_y , double offset_y ) { double [ ] fgf = earthToFGF ( geographic_lon , geographic_lat , scale_x , offset_x , scale_y , offset_y ) ; int elem = ( int ) Math . floor ( fgf [ 0 ] + 0.5 ) ; int line = ( int ) Math . floor ( fgf [ 1 ] + 0.5 ) ; return new int [ ] { elem , line } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform ( lamda theta ) in radians to fractional FGF coordinates . [CODESPLIT] public double [ ] SatToFGF ( double lamda , double theta , double scale_x , double offset_x , double scale_y , double offset_y ) { double fgf_x = ( lamda - offset_x ) / scale_x ; double fgf_y = ( theta - offset_y ) / scale_y ; return new double [ ] { fgf_x , fgf_y } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find sweep_angle_axis associated with a scan geometry [CODESPLIT] public static String scanGeomToSweepAngleAxis ( String scanGeometry ) { String sweepAngleAxis = \"y\" ; if ( scanGeometry . equals ( GOES ) ) { sweepAngleAxis = \"x\" ; } return sweepAngleAxis ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find scan geometry associated with sweep_angle_axis [CODESPLIT] public static String sweepAngleAxisToScanGeom ( String sweepAngleAxis ) { String scanGeom = GOES ; if ( sweepAngleAxis . equals ( \"y\" ) ) { scanGeom = GEOS ; } return scanGeom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the list of runtime coordinates ; add any that are not already present and make an empty CoordinateTimeAbstract for it [CODESPLIT] void setRuntimeCoords ( CoordinateRuntime runtimes ) { for ( int idx = 0 ; idx < runtimes . getSize ( ) ; idx ++ ) { CalendarDate cd = runtimes . getRuntimeDate ( idx ) ; long runtime = runtimes . getRuntime ( idx ) ; CoordinateTimeAbstract time = timeMap . get ( runtime ) ; if ( time == null ) { time = isTimeInterval ? new CoordinateTimeIntv ( this . code , this . timeUnit , cd , new ArrayList <> ( 0 ) , null ) : new CoordinateTime ( this . code , this . timeUnit , cd , new ArrayList <> ( 0 ) , null ) ; timeMap . put ( runtime , time ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a ucar . nc2 . dt . PointObsDataset write out in CF point format . [CODESPLIT] public static boolean rewritePointObsDataset ( String fileIn , String fileOut , boolean inMemory ) throws IOException { System . out . println ( \"Rewrite2 .nc files from \" + fileIn + \" to \" + fileOut + \" inMemory= \" + inMemory ) ; long start = System . currentTimeMillis ( ) ; // do it in memory for speed NetcdfFile ncfile = inMemory ? NetcdfFile . openInMemory ( fileIn ) : NetcdfFile . open ( fileIn ) ; NetcdfDataset ncd = new NetcdfDataset ( ncfile ) ; StringBuilder errlog = new StringBuilder ( ) ; PointObsDataset pobsDataset = ( PointObsDataset ) TypedDatasetFactory . open ( FeatureType . POINT , ncd , null , errlog ) ; if ( pobsDataset == null ) return false ; writePointObsDataset ( pobsDataset , fileOut ) ; pobsDataset . close ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . println ( \" that took \" + ( took - start ) + \" msecs\" ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write data from a ucar . nc2 . dt . PointObsDataset into CF point format . [CODESPLIT] public static void writePointObsDataset ( PointObsDataset pobsDataset , String fileOut ) throws IOException { // see if we have an altitude String altUnits = null ; DataIterator iterOne = pobsDataset . getDataIterator ( - 1 ) ; while ( iterOne . hasNext ( ) ) { PointObsDatatype pobsData = ( PointObsDatatype ) iterOne . nextData ( ) ; ucar . unidata . geoloc . EarthLocation loc = pobsData . getLocation ( ) ; altUnits = Double . isNaN ( loc . getAltitude ( ) ) ? null : \"meters\" ; break ; } List < VariableSimpleIF > vars = pobsDataset . getDataVariables ( ) ; List < PointObVar > nvars = new ArrayList < PointObVar > ( vars . size ( ) ) ; // put vars in order for ( VariableSimpleIF v : vars ) { if ( v . getDataType ( ) . isNumeric ( ) ) nvars . add ( new PointObVar ( v ) ) ; } int ndoubles = vars . size ( ) ; double [ ] dvals = new double [ ndoubles ] ; for ( VariableSimpleIF v : vars ) { if ( v . getDataType ( ) . isString ( ) ) nvars . add ( new PointObVar ( v ) ) ; } String [ ] svals = new String [ vars . size ( ) - ndoubles ] ; FileOutputStream fos = new FileOutputStream ( fileOut ) ; DataOutputStream out = new DataOutputStream ( fos ) ; CFPointObWriter writer = new CFPointObWriter ( out , pobsDataset . getGlobalAttributes ( ) , altUnits , nvars , - 1 ) ; DataIterator iter = pobsDataset . getDataIterator ( 1000 * 1000 ) ; while ( iter . hasNext ( ) ) { PointObsDatatype pobsData = ( PointObsDatatype ) iter . nextData ( ) ; StructureData sdata = pobsData . getData ( ) ; int dcount = 0 ; int scount = 0 ; for ( PointObVar v : nvars ) { if ( v . getDataType ( ) . isNumeric ( ) ) { Array data = sdata . getArray ( v . getName ( ) ) ; data . resetLocalIterator ( ) ; if ( data . hasNext ( ) ) dvals [ dcount ++ ] = data . nextDouble ( ) ; } else if ( v . getDataType ( ) . isString ( ) ) { ArrayChar data = ( ArrayChar ) sdata . getArray ( v . getName ( ) ) ; svals [ scount ++ ] = data . getString ( ) ; } } ucar . unidata . geoloc . EarthLocation loc = pobsData . getLocation ( ) ; writer . addPoint ( loc . getLatitude ( ) , loc . getLongitude ( ) , loc . getAltitude ( ) , pobsData . getObservationTimeAsDate ( ) , dvals , svals ) ; } writer . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a ucar . nc2 . ft . PointFeatureCollection write out in CF point format . [CODESPLIT] public static boolean rewritePointFeatureDataset ( String fileIn , String fileOut , boolean inMemory ) throws IOException { System . out . println ( \"Rewrite2 .nc files from \" + fileIn + \" to \" + fileOut + \" inMemory= \" + inMemory ) ; long start = System . currentTimeMillis ( ) ; // do it in memory for speed NetcdfFile ncfile = inMemory ? NetcdfFile . openInMemory ( fileIn ) : NetcdfFile . open ( fileIn ) ; NetcdfDataset ncd = new NetcdfDataset ( ncfile ) ; Formatter errlog = new Formatter ( ) ; FeatureDataset fd = FeatureDatasetFactoryManager . wrap ( FeatureType . ANY_POINT , ncd , null , errlog ) ; if ( fd == null ) return false ; if ( fd instanceof FeatureDatasetPoint ) { writePointFeatureCollection ( ( FeatureDatasetPoint ) fd , fileOut ) ; fd . close ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . println ( \" that took \" + ( took - start ) + \" msecs\" ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a ucar . nc2 . ft . PointFeatureCollection in CF point format . [CODESPLIT] public static int writePointFeatureCollection ( FeatureDatasetPoint pfDataset , String fileOut ) throws IOException { // extract the PointFeatureCollection PointFeatureCollection pointFeatureCollection = null ; List < DsgFeatureCollection > featureCollectionList = pfDataset . getPointFeatureCollectionList ( ) ; for ( DsgFeatureCollection featureCollection : featureCollectionList ) { if ( featureCollection instanceof PointFeatureCollection ) pointFeatureCollection = ( PointFeatureCollection ) featureCollection ; } if ( null == pointFeatureCollection ) throw new IOException ( \"There is no PointFeatureCollection in  \" + pfDataset . getLocation ( ) ) ; long start = System . currentTimeMillis ( ) ; FileOutputStream fos = new FileOutputStream ( fileOut ) ; DataOutputStream out = new DataOutputStream ( new BufferedOutputStream ( fos , 10000 ) ) ; WriterCFPointDataset writer = null ; /* LOOK BAD\n    List<VariableSimpleIF> dataVars = new ArrayList<VariableSimpleIF>();\n    ucar.nc2.NetcdfFile ncfile = pfDataset.getNetcdfFile();\n    if ((ncfile == null) || !(ncfile instanceof NetcdfDataset))  {\n      dataVars.addAll(pfDataset.getDataVariables());\n    } else {\n      NetcdfDataset ncd = (NetcdfDataset) ncfile;\n      for (VariableSimpleIF vs : pfDataset.getDataVariables()) {\n        if (ncd.findCoordinateAxis(vs.getName()) == null)\n          dataVars.add(vs);\n      }\n    } */ int count = 0 ; for ( PointFeature pointFeature : pointFeatureCollection ) { StructureData data = pointFeature . getDataAll ( ) ; if ( count == 0 ) { EarthLocation loc = pointFeature . getLocation ( ) ; // LOOK we dont know this until we see the obs String altUnits = Double . isNaN ( loc . getAltitude ( ) ) ? null : \"meters\" ; // LOOK units may be wrong writer = new WriterCFPointDataset ( out , pfDataset . getGlobalAttributes ( ) , altUnits ) ; writer . writeHeader ( pfDataset . getDataVariables ( ) , - 1 ) ; } writer . writeRecord ( pointFeature , data ) ; count ++ ; } writer . finish ( ) ; out . flush ( ) ; out . close ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . printf ( \"Write %d records from %s to %s took %d msecs %n\" , count , pfDataset . getLocation ( ) , fileOut , took ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data array of any type as an Array . For more efficiency use getScalarXXX ( Member ) or getJavaArrayXXX ( Member ) is possible . [CODESPLIT] public Array getArray ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( \"illegal member name =\" + memberName ) ; return getArray ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data array of any type as an Object eg Float Double String etc . [CODESPLIT] public Object getScalarObject ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( \"illegal member name =\" + memberName ) ; return getScalarObject ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data array of any type as an Object eg Float Double String etc . [CODESPLIT] public Object getScalarObject ( StructureMembers . Member m ) { DataType dataType = m . getDataType ( ) ; //boolean isScalar = m.isScalar(); if ( dataType == DataType . DOUBLE ) { return getScalarDouble ( m ) ; } else if ( dataType == DataType . FLOAT ) { return getScalarFloat ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == byte . class ) { return getScalarByte ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { return getScalarShort ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { return getScalarInt ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { return getScalarLong ( m ) ; } else if ( dataType == DataType . CHAR ) { return getScalarString ( m ) ; } else if ( dataType == DataType . STRING ) { return getScalarString ( m ) ; } else if ( dataType == DataType . STRUCTURE ) { return getScalarStructure ( m ) ; } else if ( dataType == DataType . SEQUENCE ) { return getArraySequence ( m ) ; } throw new RuntimeException ( \"Dont have implemenation for \" + dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar value as a float with conversion as needed . Underlying type must be convertible to float . [CODESPLIT] public float convertScalarFloat ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( \"illegal member name =\" + memberName ) ; return convertScalarFloat ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get String value from rank 0 String or rank 1 char member array . [CODESPLIT] public String getScalarString ( String memberName ) { StructureMembers . Member m = findMember ( memberName ) ; if ( null == m ) throw new IllegalArgumentException ( \"Member not found= \" + memberName ) ; return getScalarString ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type Structure . [CODESPLIT] public StructureData getScalarStructure ( String memberName ) { StructureMembers . Member m = findMember ( memberName ) ; if ( null == m ) throw new IllegalArgumentException ( \"Member not found= \" + memberName ) ; return getScalarStructure ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type Structure . [CODESPLIT] public ArrayStructure getArrayStructure ( String memberName ) { StructureMembers . Member m = findMember ( memberName ) ; if ( null == m ) throw new IllegalArgumentException ( \"Member not found= \" + memberName ) ; return getArrayStructure ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get ArraySequence for a member of type Sequence . [CODESPLIT] public ArraySequence getArraySequence ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( \"illegal member name =\" + memberName ) ; return getArraySequence ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging [CODESPLIT] public void showInternal ( Formatter f , Indent indent ) { f . format ( \"%sStructureData %s class=%s hash=0x%x%n\" , indent , members . getName ( ) , this . getClass ( ) . getName ( ) , hashCode ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the full heirarchical name of the dataset which has all parent collection names . [CODESPLIT] public String getFullName ( ) { return ( parent == null ) ? name : ( parent . getFullName ( ) == null || parent . getFullName ( ) . length ( ) == 0 ) ? name : parent . getFullName ( ) + \"/\" + name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this dataset has an authority and an ID then the concatenation of them is the globally unique ID . [CODESPLIT] public String getUniqueID ( ) { String authority = getAuthority ( ) ; if ( ( authority != null ) && ( getID ( ) != null ) ) return authority + \":\" + getID ( ) ; else if ( getID ( ) != null ) return getID ( ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get access element of the specified service type for this dataset . If more than one get the first one . [CODESPLIT] public InvAccess getAccess ( thredds . catalog . ServiceType type ) { for ( InvAccess a : getAccess ( ) ) { InvService s = a . getService ( ) ; if ( s . getServiceType ( ) == type ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get access element that matches the given access standard URL . Match on a . getStandardUrlName () . [CODESPLIT] public InvAccess findAccess ( String accessURL ) { for ( InvAccess a : getAccess ( ) ) { if ( accessURL . equals ( a . getStandardUrlName ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an immediate child dataset by its name . [CODESPLIT] public InvDatasetImpl findDatasetByName ( String name ) { for ( InvDataset ds : getDatasets ( ) ) { if ( ds . getName ( ) . equals ( name ) ) return ( InvDatasetImpl ) ds ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get containing catalog . [CODESPLIT] public InvCatalog getParentCatalog ( ) { if ( catalog != null ) return catalog ; return ( parent != null ) ? parent . getParentCatalog ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the metadata elements of the specified type . [CODESPLIT] public java . util . List < InvMetadata > getMetadata ( thredds . catalog . MetadataType want ) { List < InvMetadata > result = new ArrayList < InvMetadata > ( ) ; for ( InvMetadata m : getMetadata ( ) ) { MetadataType mtype = MetadataType . getType ( m . getMetadataType ( ) ) ; if ( mtype == want ) result . add ( m ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the named service declared in this dataset or one of its parents . [CODESPLIT] public InvService findService ( String name ) { if ( name == null ) return null ; // search local (but expanded) services for ( InvService p : services ) { if ( p . getName ( ) . equals ( name ) ) return p ; } // not found, look in parent if ( parent != null ) return parent . findService ( name ) ; return ( catalog == null ) ? null : catalog . findService ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the resource control value which indicates that only users with proper permission can access this resource . <p / > ??? Not sure if the value indicates anything or just set or not set . [CODESPLIT] public String getRestrictAccess ( ) { if ( restrictAccess != null ) return restrictAccess ; // not found, look in parent if ( parent != null ) return parent . getRestrictAccess ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get Variables from the specified vocabulary [CODESPLIT] public ThreddsMetadata . Variables getVariables ( String vocab ) { ThreddsMetadata . Variables result = new ThreddsMetadata . Variables ( vocab , null , null , null , null ) ; if ( variables == null ) return result ; for ( ThreddsMetadata . Variables vs : variables ) { if ( vs . getVocabulary ( ) . equals ( vocab ) ) result . getVariableList ( ) . addAll ( vs . getVariableList ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private LatLonPointImpl origin ; // why are we keeping this? [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new FlatEarth ( getOriginLat ( ) , getOriginLon ( ) , getRotationAngle ( ) ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; double dx , dy ; fromLat = Math . toRadians ( fromLat ) ; dy = radius * ( fromLat - lat0 ) ; dx = radius * Math . cos ( fromLat ) * ( Math . toRadians ( fromLon ) - lon0 ) ; toX = cosRot * dx - sinRot * dy ; toY = sinRot * dx + cosRot * dy ; result . setLocation ( toX , toY ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double x = world . getX ( ) ; double y = world . getY ( ) ; double cosl ; int TOLERENCE = 1 ; double xp , yp ; xp = cosRot * x + sinRot * y ; yp = - sinRot * x + cosRot * y ; toLat = Math . toDegrees ( lat0 ) + Math . toDegrees ( yp / radius ) ; //double lat2; //lat2 = lat0 + Math.toDegrees(yp/radius); cosl = Math . cos ( Math . toRadians ( toLat ) ) ; if ( Math . abs ( cosl ) < TOLERANCE ) { toLon = Math . toDegrees ( lon0 ) ; } else { toLon = Math . toDegrees ( lon0 ) + Math . toDegrees ( xp / cosl / radius ) ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double dy = radius * ( fromLat - lat0 ) ; double dx = radius * Math . cos ( fromLat ) * ( Math . toRadians ( fromLon ) - lon0 ) ; toX = cosRot * dx - sinRot * dy ; toY = sinRot * dx + cosRot * dy ; resultXA [ i ] = ( float ) toX ; resultYA [ i ] = ( float ) toY ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public double [ ] [ ] projToLatLon ( double [ ] [ ] from , double [ ] [ ] to ) { int cnt = from [ 0 ] . length ; double [ ] fromXA = from [ INDEX_X ] ; double [ ] fromYA = from [ INDEX_Y ] ; double [ ] toLatA = to [ INDEX_LAT ] ; double [ ] toLonA = to [ INDEX_LON ] ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] ; double fromY = fromYA [ i ] ; double xp = cosRot * fromX + sinRot * fromY ; double yp = - sinRot * fromX + cosRot * fromY ; //toLat =  lat0 + Math.toDegrees(yp); toLat = Math . toDegrees ( lat0 ) + Math . toDegrees ( yp / radius ) ; double cosl = Math . cos ( Math . toRadians ( toLat ) ) ; if ( Math . abs ( cosl ) < TOLERANCE ) { toLon = Math . toDegrees ( lon0 ) ; } else { toLon = Math . toDegrees ( lon0 ) + Math . toDegrees ( xp / cosl / radius ) ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; toLatA [ i ] = toLat ; toLonA [ i ] = toLon ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test [CODESPLIT] public static void main ( String [ ] args ) { FlatEarth a = new FlatEarth ( 90 , - 100 , 0.0 ) ; ProjectionPoint p = a . latLonToProj ( 89 , - 101 ) ; System . out . println ( \"proj point = \" + p ) ; LatLonPoint ll = a . projToLatLon ( p ) ; System . out . println ( \"ll = \" + ll ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all catalogRef elements in the dataset tree formed by the given dataset list . [CODESPLIT] public static List < InvCatalogRef > findAllCatRefsInDatasetTree ( List < InvDataset > datasets , StringBuilder log , boolean onlyRelativeUrls ) { List < InvCatalogRef > catRefList = new ArrayList < InvCatalogRef > ( ) ; for ( InvDataset invds : datasets ) { InvDatasetImpl curDs = ( InvDatasetImpl ) invds ; if ( curDs instanceof InvDatasetScan ) continue ; if ( curDs instanceof InvCatalogRef ) { InvCatalogRef catRef = ( InvCatalogRef ) curDs ; String name = catRef . getName ( ) ; String href = catRef . getXlinkHref ( ) ; URI uri ; try { uri = new URI ( href ) ; } catch ( URISyntaxException e ) { log . append ( log . length ( ) > 0 ? \"\\n\" : \"\" ) . append ( \"***WARN - CatalogRef [\" ) . append ( name ) . append ( \"] with bad HREF [\" ) . append ( href ) . append ( \"] \" ) ; continue ; } if ( onlyRelativeUrls && uri . isAbsolute ( ) ) continue ; catRefList . add ( catRef ) ; continue ; } if ( curDs . hasNestedDatasets ( ) ) catRefList . addAll ( findAllCatRefsInDatasetTree ( curDs . getDatasets ( ) , log , onlyRelativeUrls ) ) ; } return catRefList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape the characters necessary for a path to be valid for a URL [CODESPLIT] static public String escapePathForURL ( String path ) { try { return new URI ( null , null , path , null ) . toString ( ) ; } catch ( URISyntaxException e ) { return path ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException { ArrayDouble . D3 array ; Array pertArray = getTimeSlice ( pertVar , timeIndex ) ; Array baseArray = getTimeSlice ( baseVar , timeIndex ) ; //ADD: use MAMath?\r //ADD: use IndexIterator from getIndexIteratorFast?\r int [ ] shape = pertArray . getShape ( ) ; //ADD: assert that rank = 3\r //ADD: assert that both arrays are same shape\r int ni = shape [ 0 ] ; int nj = shape [ 1 ] ; int nk = shape [ 2 ] ; array = new ArrayDouble . D3 ( ni , nj , nk ) ; Index index = array . getIndex ( ) ; for ( int i = 0 ; i < ni ; i ++ ) { for ( int j = 0 ; j < nj ; j ++ ) { for ( int k = 0 ; k < nk ; k ++ ) { index . set ( i , j , k ) ; double d = pertArray . getDouble ( index ) + baseArray . getDouble ( index ) ; if ( isZStag ) { d = d / 9.81 ; //convert geopotential to height\r } array . setDouble ( index , d ) ; } } } if ( isXStag ) { array = addStagger ( array , 2 ) ; //assuming x dim index is 2\r } if ( isYStag ) { array = addStagger ( array , 1 ) ; //assuming y dim index is 1\r } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { ArrayDouble . D3 data = getCoordinateArray ( timeIndex ) ; int [ ] origin = new int [ 3 ] ; int [ ] shape = new int [ 3 ] ; origin [ 0 ] = 0 ; origin [ 1 ] = yIndex ; origin [ 2 ] = xIndex ; shape [ 0 ] = data . getShape ( ) [ 0 ] ; shape [ 1 ] = 1 ; shape [ 2 ] = 1 ; Array tmp = data . section ( origin , shape ) ; return ( ArrayDouble . D1 ) tmp . reduce ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add 1 to the size of the array for the given dimension . Use linear average and interpolation to fill in the values . [CODESPLIT] private ArrayDouble . D3 addStagger ( ArrayDouble . D3 array , int dimIndex ) { //ADD: assert 0<=dimIndex<=2\r int [ ] shape = array . getShape ( ) ; int [ ] newShape = new int [ 3 ] ; System . arraycopy ( shape , 0 , newShape , 0 , 3 ) ; newShape [ dimIndex ] ++ ; int ni = newShape [ 0 ] ; int nj = newShape [ 1 ] ; int nk = newShape [ 2 ] ; ArrayDouble . D3 newArray = new ArrayDouble . D3 ( ni , nj , nk ) ; //Index newIndex = newArray.getIndex();\r //extract 1d array to be extended\r int n = shape [ dimIndex ] ; //length of extracted array\r double [ ] d = new double [ n ] ; //tmp array to hold extracted values\r int [ ] eshape = new int [ 3 ] ; //shape of extracted array\r int [ ] neweshape = new int [ 3 ] ; //shape of new array slice to write into\r for ( int i = 0 ; i < 3 ; i ++ ) { eshape [ i ] = ( i == dimIndex ) ? n : 1 ; neweshape [ i ] = ( i == dimIndex ) ? n + 1 : 1 ; } int [ ] origin = new int [ 3 ] ; try { //loop through the other 2 dimensions and \"extrapinterpolate\" the other\r for ( int i = 0 ; i < ( ( dimIndex == 0 ) ? 1 : ni ) ; i ++ ) { for ( int j = 0 ; j < ( ( dimIndex == 1 ) ? 1 : nj ) ; j ++ ) { for ( int k = 0 ; k < ( ( dimIndex == 2 ) ? 1 : nk ) ; k ++ ) { origin [ 0 ] = i ; origin [ 1 ] = j ; origin [ 2 ] = k ; IndexIterator it = array . section ( origin , eshape ) . getIndexIterator ( ) ; for ( int l = 0 ; l < n ; l ++ ) { d [ l ] = it . getDoubleNext ( ) ; //get the original values\r } double [ ] d2 = extrapinterpolate ( d ) ; //compute new values\r //define slice of new array to write into\r IndexIterator newit = newArray . section ( origin , neweshape ) . getIndexIterator ( ) ; for ( int l = 0 ; l < n + 1 ; l ++ ) { newit . setDoubleNext ( d2 [ l ] ) ; } } } } } catch ( InvalidRangeException e ) { //ADD: report error?\r return null ; } return newArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add one element to the array by linear interpolation and extrapolation at the ends . [CODESPLIT] private double [ ] extrapinterpolate ( double [ ] array ) { int n = array . length ; double [ ] d = new double [ n + 1 ] ; //end points from linear extrapolation\r //equations confirmed by Christopher Lindholm\r d [ 0 ] = 1.5 * array [ 0 ] - 0.5 * array [ 1 ] ; d [ n ] = 1.5 * array [ n - 1 ] - 0.5 * array [ n - 2 ] ; //inner points from simple average\r for ( int i = 1 ; i < n ; i ++ ) { d [ i ] = 0.5 * ( array [ i - 1 ] + array [ i ] ) ; } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy constructor - avoid clone !! [CODESPLIT] public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new AlbersEqualArea ( getOriginLat ( ) , getOriginLon ( ) , getParallelOne ( ) , getParallelTwo ( ) , getFalseEasting ( ) , getFalseNorthing ( ) , getEarthRadius ( ) ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Precalculate some stuff [CODESPLIT] private void precalculate ( ) { double par1r = Math . toRadians ( this . par1 ) ; double par2r = Math . toRadians ( this . par2 ) ; if ( Math . abs ( par2 - par1 ) < TOLERANCE ) { // single parallel\r n = Math . sin ( par1r ) ; } else { n = ( Math . sin ( par1r ) + Math . sin ( par2r ) ) / 2.0 ; } double c2 = Math . pow ( Math . cos ( par1r ) , 2 ) ; C = c2 + 2 * n * Math . sin ( par1r ) ; rho0 = computeRho ( lat0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the RHO parameter [CODESPLIT] private double computeRho ( double lat ) { return earth_radius * Math . sqrt ( C - 2 * n * Math . sin ( lat ) ) / n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute theta [CODESPLIT] private double computeTheta ( double lon ) { double dlon = LatLonPointImpl . lonNormal ( Math . toDegrees ( lon ) - lon0Degrees ) ; return n * Math . toRadians ( dlon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the scale at the given lat . [CODESPLIT] public double getScale ( double lat ) { lat = Math . toRadians ( lat ) ; double n = Math . cos ( lat ) ; double d = Math . sqrt ( C - 2 * n * Math . sin ( lat ) ) ; return n / d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; fromLon = Math . toRadians ( fromLon ) ; double rho = computeRho ( fromLat ) ; double theta = computeTheta ( fromLon ) ; toX = rho * Math . sin ( theta ) + falseEasting ; toY = rho0 - rho * Math . cos ( theta ) + falseNorthing ; result . setLocation ( toX , toY ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double rrho0 = rho0 ; if ( n < 0 ) { rrho0 *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = rrho0 - fromY ; double rho = Math . sqrt ( fromX * fromX + yd * yd ) ; double theta = Math . atan2 ( fromX , yd ) ; if ( n < 0 ) { rho *= - 1.0 ; } toLat = Math . toDegrees ( Math . asin ( ( C - Math . pow ( ( rho * n / earth_radius ) , 2 ) ) / ( 2 * n ) ) ) ; toLon = Math . toDegrees ( theta / n + lon0 ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { int cnt = from [ 0 ] . length ; float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] toLatA = to [ INDEX_LAT ] ; float [ ] toLonA = to [ INDEX_LON ] ; double rrho0 = rho0 ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] - falseEasting ; double fromY = fromYA [ i ] - falseNorthing ; if ( n < 0 ) { rrho0 *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = rrho0 - fromY ; double rho = Math . sqrt ( fromX * fromX + yd * yd ) ; double theta = Math . atan2 ( fromX , yd ) ; if ( n < 0 ) { rho *= - 1.0 ; } toLat = Math . toDegrees ( Math . asin ( ( C - Math . pow ( ( rho * n / earth_radius ) , 2 ) ) / ( 2 * n ) ) ) ; toLon = Math . toDegrees ( theta / n + lon0 ) ; toLatA [ i ] = ( float ) toLat ; toLonA [ i ] = ( float ) toLon ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public double [ ] [ ] latLonToProj ( double [ ] [ ] from , double [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; double [ ] fromLatA = from [ latIndex ] ; double [ ] fromLonA = from [ lonIndex ] ; double [ ] resultXA = to [ INDEX_X ] ; double [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; fromLon = Math . toRadians ( fromLon ) ; double rho = computeRho ( fromLat ) ; double theta = computeTheta ( fromLon ) ; toX = rho * Math . sin ( theta ) ; toY = rho0 - rho * Math . cos ( theta ) ; resultXA [ i ] = toX + falseEasting ; resultYA [ i ] = toY + falseNorthing ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test [CODESPLIT] public static void main ( String [ ] args ) { AlbersEqualArea a = new AlbersEqualArea ( 23 , - 96 , 29.5 , 45.5 ) ; System . out . printf ( \"name=%s%n\" , a . getName ( ) ) ; System . out . println ( \"ll = 35N 75W\" ) ; ProjectionPoint p = a . latLonToProj ( 35 , - 75 ) ; System . out . println ( \"proj point = \" + p ) ; LatLonPoint ll = a . projToLatLon ( p ) ; System . out . println ( \"ll = \" + ll ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( addName ) pw . print ( \", \" ) ; String s = getValue ( ) ; // Get rid of null terminations on strings\r if ( ( s . length ( ) > 0 ) && s . charAt ( s . length ( ) - 1 ) == ( ( char ) 0 ) ) { // jc mod\r if ( _Debug ) System . out . println ( \"Removing null termination from string \\\"\" + getEncodedName ( ) + \"\\\".\" ) ; char cArray [ ] = s . toCharArray ( ) ; s = new String ( cArray , 0 , cArray . length - 1 ) ; } pw . print ( \"\\\"\" + s + \"\\\"\" ) ; if ( newLine ) pw . print ( \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xs : element ref = dc : title / > <xs : element ref = dc : creator / > <xs : element ref = dc : subject / > <xs : element ref = dc : description / > <xs : element ref = dc : publisher / > <xs : element ref = dc : contributor / > <xs : element ref = dc : date / > <xs : element ref = dc : type / > <xs : element ref = dc : format / > <xs : element ref = dc : identifier / > <xs : element ref = dc : source / > <xs : element ref = dc : language / > <xs : element ref = dc : relation / > <xs : element ref = dc : coverage / > <xs : element ref = dc : rights / > <! -- controlled vocabulary from dcmitype -- > <xs : element ref = dcmitype : dcmitype / > [CODESPLIT] public void writeDataset ( InvDataset ds , Element rootElem ) { rootElem . addContent ( new Element ( \"title\" , defNS ) . addContent ( ds . getName ( ) ) ) ; rootElem . addContent ( new Element ( \"Entry_ID\" , defNS ) . addContent ( ds . getUniqueID ( ) ) ) ; // keywords List < ThreddsMetadata . Vocab > list = ds . getKeywords ( ) ; if ( list . size ( ) > 0 ) { for ( ThreddsMetadata . Vocab k : list ) { rootElem . addContent ( new Element ( \"Keyword\" , defNS ) . addContent ( k . getText ( ) ) ) ; } } //temporal CalendarDateRange tm = ds . getCalendarDateCoverage ( ) ; Element tmElem = new Element ( \"Temporal_Coverage\" , defNS ) ; rootElem . addContent ( tmElem ) ; tmElem . addContent ( new Element ( \"Start_Date\" , defNS ) . addContent ( tm . getStart ( ) . toString ( ) ) ) ; tmElem . addContent ( new Element ( \"End_Date\" , defNS ) . addContent ( tm . getEnd ( ) . toString ( ) ) ) ; //geospatial ThreddsMetadata . GeospatialCoverage geo = ds . getGeospatialCoverage ( ) ; Element geoElem = new Element ( \"Spatial_Coverage\" , defNS ) ; rootElem . addContent ( geoElem ) ; geoElem . addContent ( new Element ( \"Southernmost_Latitude\" , defNS ) . addContent ( Double . toString ( geo . getLatSouth ( ) ) ) ) ; geoElem . addContent ( new Element ( \"Northernmost_Latitude\" , defNS ) . addContent ( Double . toString ( geo . getLatNorth ( ) ) ) ) ; geoElem . addContent ( new Element ( \"Westernmost_Latitude\" , defNS ) . addContent ( Double . toString ( geo . getLonWest ( ) ) ) ) ; geoElem . addContent ( new Element ( \"Easternmost_Latitude\" , defNS ) . addContent ( Double . toString ( geo . getLonEast ( ) ) ) ) ; rootElem . addContent ( new Element ( \"Use_Constraints\" , defNS ) . addContent ( ds . getDocumentation ( \"rights\" ) ) ) ; // data center List < ThreddsMetadata . Source > slist = ds . getPublishers ( ) ; if ( list . size ( ) > 0 ) { for ( ThreddsMetadata . Source p : slist ) { Element dataCenter = new Element ( \"Data_Center\" , defNS ) ; rootElem . addContent ( dataCenter ) ; writePublisher ( p , dataCenter ) ; } } rootElem . addContent ( new Element ( \"Summary\" , defNS ) . addContent ( ds . getDocumentation ( \"summary\" ) ) ) ; Element primaryURLelem = new Element ( \"Related_URL\" , defNS ) ; rootElem . addContent ( primaryURLelem ) ; String primaryURL = threddsServerURL + \"?catalog=\" + ( ( InvCatalogImpl ) ds . getParentCatalog ( ) ) . getBaseURI ( ) . toString ( ) + \"&dataset=\" + ds . getID ( ) ; primaryURLelem . addContent ( new Element ( \"URL_Content_Type\" , defNS ) . addContent ( \"THREDDS access page\" ) ) ; primaryURLelem . addContent ( new Element ( \"URL\" , defNS ) . addContent ( primaryURL ) ) ; DateType today = new DateType ( false , new Date ( ) ) ; rootElem . addContent ( new Element ( \"DIF_Creation_Date\" , defNS ) . addContent ( today . toDateTimeStringISO ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "testing [CODESPLIT] public static void main ( String [ ] args ) throws Exception { InvCatalogFactory catFactory = InvCatalogFactory . getDefaultFactory ( true ) ; doOne ( catFactory , \"file:///C:/dev/thredds/catalog/test/data/TestHarvest.xml\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a valid file? [CODESPLIT] @ Override public boolean isValidFile ( RandomAccessFile raf ) throws IOException { try { gemreader = makeStationReader ( ) ; return gemreader . init ( raf , false ) ; } catch ( Exception ioe ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the service provider for reading . [CODESPLIT] @ Override public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { //System.out.printf(\"GempakSurfaceIOSP open %s (%s) %n\", raf.getLocation(), Calendar.getInstance().getTime());\r super . open ( raf , ncfile , cancelTask ) ; if ( gemreader == null ) { gemreader = makeStationReader ( ) ; } initTables ( ) ; gemreader . init ( raf , true ) ; buildNCFile ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the detail information [CODESPLIT] public String getDetailInfo ( ) { Formatter ff = new Formatter ( ) ; ff . format ( \"%s\" , super . getDetailInfo ( ) ) ; ff . format ( \"%s\" , parseInfo ) ; return ff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a structure for the part [CODESPLIT] protected Structure makeStructure ( String partName , List < Dimension > dimensions , boolean includeMissing ) { List < GempakParameter > params = gemreader . getParameters ( partName ) ; if ( params == null ) { return null ; } Structure sVar = new Structure ( ncfile , null , null , partName ) ; sVar . setDimensions ( dimensions ) ; for ( GempakParameter param : params ) { sVar . addMemberVariable ( makeParamVariable ( param , null ) ) ; } if ( includeMissing ) { sVar . addMemberVariable ( makeMissingVariable ( ) ) ; } return sVar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the missing variable [CODESPLIT] protected Variable makeMissingVariable ( ) { Variable var = new Variable ( ncfile , null , null , MISSING_VAR ) ; var . setDataType ( DataType . BYTE ) ; var . setDimensions ( ( List < Dimension > ) null ) ; var . addAttribute ( new Attribute ( \"description\" , \"missing flag - 1 means all params are missing\" ) ) ; var . addAttribute ( new Attribute ( CDM . MISSING_VALUE , ( byte ) 1 ) ) ; return var ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a variable from a GempakParmaeter [CODESPLIT] protected Variable makeParamVariable ( GempakParameter param , List < Dimension > dims ) { Variable var = new Variable ( ncfile , null , null , param . getName ( ) ) ; var . setDataType ( DataType . FLOAT ) ; var . setDimensions ( dims ) ; var . addAttribute ( new Attribute ( CDM . LONG_NAME , param . getDescription ( ) ) ) ; String units = param . getUnit ( ) ; if ( ( units != null ) && ! units . equals ( \"\" ) ) { var . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; } var . addAttribute ( new Attribute ( CDM . MISSING_VALUE , RMISS ) ) ; return var ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add on global attributes for all types [CODESPLIT] protected void addGlobalAttributes ( ) { // global stuff\r ncfile . addAttribute ( null , new Attribute ( CDM . CONVENTIONS , getConventions ( ) ) ) ; String fileType = \"GEMPAK \" + gemreader . getFileType ( ) ; ncfile . addAttribute ( null , new Attribute ( \"file_format\" , fileType ) ) ; ncfile . addAttribute ( null , new Attribute ( \"history\" , \"Direct read of \" + fileType + \" into NetCDF-Java API\" ) ) ; ncfile . addAttribute ( null , new Attribute ( CF . FEATURE_TYPE , getCFFeatureType ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the size of a particular station variable [CODESPLIT] protected int getStnVarSize ( String name ) { int size = - 1 ; for ( int i = 0 ; i < stnVarNames . length ; i ++ ) { if ( name . equals ( stnVarNames [ i ] ) ) { size = stnVarSizes [ i ] ; break ; } } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the station variables from a representative station [CODESPLIT] protected List < Variable > makeStationVars ( List < GempakStation > stations , Dimension dim ) { int numStations = stations . size ( ) ; List < Variable > vars = new ArrayList <> ( ) ; List < String > stnKeyNames = gemreader . getStationKeyNames ( ) ; for ( String varName : stnKeyNames ) { Variable v = makeStationVariable ( varName , dim ) ; Attribute stIDAttr = new Attribute ( CF . STANDARD_NAME , \"station_id\" ) ; if ( varName . equals ( GempakStation . STID ) ) { // Use STID as the station_id for the dataset.\r v . addAttribute ( stIDAttr ) ; } vars . add ( v ) ; } // see if we fill these in completely now\r if ( ( dim != null ) && ( numStations > 0 ) ) { for ( Variable v : vars ) { Array varArray ; if ( v . getDataType ( ) . equals ( DataType . CHAR ) ) { int [ ] shape = v . getShape ( ) ; varArray = new ArrayChar . D2 ( shape [ 0 ] , shape [ 1 ] ) ; } else { varArray = get1DArray ( v . getDataType ( ) , numStations ) ; } assert varArray != null ; int index = 0 ; String varname = v . getFullName ( ) ; for ( GempakStation stn : stations ) { String test = \"\" ; switch ( varname ) { case GempakStation . STID : test = stn . getName ( ) ; break ; case GempakStation . STNM : ( ( ArrayInt . D1 ) varArray ) . set ( index , stn . getSTNM ( ) ) ; break ; case GempakStation . SLAT : ( ( ArrayFloat . D1 ) varArray ) . set ( index , ( float ) stn . getLatitude ( ) ) ; break ; case GempakStation . SLON : ( ( ArrayFloat . D1 ) varArray ) . set ( index , ( float ) stn . getLongitude ( ) ) ; break ; case GempakStation . SELV : ( ( ArrayFloat . D1 ) varArray ) . set ( index , ( float ) stn . getAltitude ( ) ) ; break ; case GempakStation . STAT : test = stn . getSTAT ( ) ; break ; case GempakStation . COUN : test = stn . getCOUN ( ) ; break ; case GempakStation . STD2 : test = stn . getSTD2 ( ) ; break ; case GempakStation . SPRI : ( ( ArrayInt . D1 ) varArray ) . set ( index , stn . getSPRI ( ) ) ; break ; case GempakStation . SWFO : test = stn . getSWFO ( ) ; break ; case GempakStation . WFO2 : test = stn . getWFO2 ( ) ; break ; } if ( ! test . equals ( \"\" ) ) { ( ( ArrayChar . D2 ) varArray ) . setString ( index , test ) ; } index ++ ; } v . setCachedData ( varArray , false ) ; } } return vars ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a 1DArray for the type and length [CODESPLIT] private Array get1DArray ( DataType type , int len ) { Array varArray = null ; if ( type . equals ( DataType . FLOAT ) ) { varArray = new ArrayFloat . D1 ( len ) ; } else if ( type . equals ( DataType . DOUBLE ) ) { varArray = new ArrayDouble . D1 ( len ) ; } else if ( type . equals ( DataType . INT ) ) { varArray = new ArrayInt . D1 ( len , false ) ; } return varArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a station variable [CODESPLIT] protected Variable makeStationVariable ( String varname , Dimension firstDim ) { String longName = varname ; String unit = null ; DataType type = DataType . CHAR ; List < Dimension > dims = new ArrayList <> ( ) ; List < Attribute > attrs = new ArrayList <> ( ) ; if ( firstDim != null ) { dims . add ( firstDim ) ; } switch ( varname ) { case GempakStation . STID : longName = \"Station identifier\" ; dims . add ( DIM_LEN8 ) ; break ; case GempakStation . STNM : longName = \"WMO station id\" ; type = DataType . INT ; break ; case GempakStation . SLAT : longName = \"latitude\" ; unit = CDM . LAT_UNITS ; type = DataType . FLOAT ; attrs . add ( new Attribute ( CF . STANDARD_NAME , \"latitude\" ) ) ; break ; case GempakStation . SLON : longName = \"longitude\" ; unit = CDM . LON_UNITS ; type = DataType . FLOAT ; attrs . add ( new Attribute ( CF . STANDARD_NAME , \"longitude\" ) ) ; break ; case GempakStation . SELV : longName = \"altitude\" ; unit = \"meter\" ; type = DataType . FLOAT ; attrs . add ( new Attribute ( CF . POSITIVE , CF . POSITIVE_UP ) ) ; attrs . add ( new Attribute ( CF . STANDARD_NAME , CF . STATION_ALTITUDE ) ) ; break ; case GempakStation . STAT : longName = \"state or province\" ; dims . add ( DIM_LEN2 ) ; break ; case GempakStation . COUN : longName = \"country code\" ; dims . add ( DIM_LEN2 ) ; break ; case GempakStation . STD2 : longName = \"Extended station id\" ; dims . add ( DIM_LEN4 ) ; break ; case GempakStation . SPRI : longName = \"Station priority\" ; type = DataType . INT ; break ; case GempakStation . SWFO : longName = \"WFO code\" ; dims . add ( DIM_LEN4 ) ; break ; case GempakStation . WFO2 : longName = \"Second WFO code\" ; dims . add ( DIM_LEN4 ) ; break ; } Variable v = new Variable ( ncfile , null , null , varname ) ; v . setDataType ( type ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; if ( unit != null ) { v . addAttribute ( new Attribute ( CDM . UNITS , unit ) ) ; } if ( type . equals ( DataType . FLOAT ) ) { v . addAttribute ( new Attribute ( CDM . MISSING_VALUE , RMISS ) ) ; } else if ( type . equals ( DataType . INT ) ) { v . addAttribute ( new Attribute ( CDM . MISSING_VALUE , IMISS ) ) ; } if ( ! attrs . isEmpty ( ) ) { for ( Attribute attr : attrs ) { v . addAttribute ( attr ) ; } } if ( ! dims . isEmpty ( ) ) { v . setDimensions ( dims ) ; } else { v . setDimensions ( ( String ) null ) ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute post - reduction state . [CODESPLIT] private int yy_lr_goto_state_ ( int yystate , int yysym ) { int yyr = yypgoto_ [ yysym - yyntokens_ ] + yystate ; if ( 0 <= yyr && yyr <= yylast_ && yycheck_ [ yyr ] == yystate ) return yytable_ [ yyr ] ; else return yydefgoto_ [ yysym - yyntokens_ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Return YYSTR after stripping away unnecessary quotes and backslashes so that it s suitable for yyerror . The heuristic is that double - quoting is unnecessary unless the string contains an apostrophe a comma or backslash ( other than backslash - backslash ) . YYSTR is taken from yytname . [CODESPLIT] private final String yytnamerr_ ( String yystr ) { if ( yystr . charAt ( 0 ) == ' ' ) { StringBuffer yyr = new StringBuffer ( ) ; strip_quotes : for ( int i = 1 ; i < yystr . length ( ) ; i ++ ) switch ( yystr . charAt ( i ) ) { case ' ' : case ' ' : break strip_quotes ; case ' ' : if ( yystr . charAt ( ++ i ) != ' ' ) break strip_quotes ; /* Fall through.  */ default : yyr . append ( yystr . charAt ( i ) ) ; break ; case ' ' : return yyr . toString ( ) ; } } else if ( yystr . equals ( \"$end\" ) ) return \"end of input\" ; return yystr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * -------------------------------- . | Print this symbol on YYOUTPUT . | -------------------------------- [CODESPLIT] private void yy_symbol_print ( String s , int yytype , Object yyvaluep ) { if ( yydebug > 0 ) yycdebug ( s + ( yytype < yyntokens_ ? \" token \" : \" nterm \" ) + yytname_ [ yytype ] + \" (\" + ( yyvaluep == null ? \"(null)\" : yyvaluep . toString ( ) ) + \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse input from the scanner that was specified at object construction time . Return whether the end of the input was reached successfully . [CODESPLIT] public boolean parse ( ) throws ParseException , ParseException { /* Lookahead and lookahead in internal form.  */ int yychar = yyempty_ ; int yytoken = 0 ; /* State.  */ int yyn = 0 ; int yylen = 0 ; int yystate = 0 ; YYStack yystack = new YYStack ( ) ; int label = YYNEWSTATE ; /* Error handling.  */ int yynerrs_ = 0 ; /* Semantic value of the lookahead.  */ Object yylval = null ; yycdebug ( \"Starting parse\\n\" ) ; yyerrstatus_ = 0 ; /* Initialize the stack.  */ yystack . push ( yystate , yylval ) ; for ( ; ; ) switch ( label ) { /* New state.  Unlike in the C/C++ skeletons, the state is already\n           pushed when we come here.  */ case YYNEWSTATE : yycdebug ( \"Entering state \" + yystate + \"\\n\" ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; /* Accept?  */ if ( yystate == yyfinal_ ) return true ; /* Take a decision.  First try without lookahead.  */ yyn = yypact_ [ yystate ] ; if ( yy_pact_value_is_default_ ( yyn ) ) { label = YYDEFAULT ; break ; } /* Read a lookahead token.  */ if ( yychar == yyempty_ ) { yycdebug ( \"Reading a token: \" ) ; yychar = yylexer . yylex ( ) ; yylval = yylexer . getLVal ( ) ; } /* Convert token to internal form.  */ if ( yychar <= Lexer . EOF ) { yychar = yytoken = Lexer . EOF ; yycdebug ( \"Now at end of input.\\n\" ) ; } else { yytoken = yytranslate_ ( yychar ) ; yy_symbol_print ( \"Next token is\" , yytoken , yylval ) ; } /* If the proper action on seeing token YYTOKEN is to reduce or to\n           detect an error, take that action.  */ yyn += yytoken ; if ( yyn < 0 || yylast_ < yyn || yycheck_ [ yyn ] != yytoken ) label = YYDEFAULT ; /* <= 0 means reduce or error.  */ else if ( ( yyn = yytable_ [ yyn ] ) <= 0 ) { if ( yy_table_value_is_error_ ( yyn ) ) label = YYERRLAB ; else { yyn = - yyn ; label = YYREDUCE ; } } else { /* Shift the lookahead token.  */ yy_symbol_print ( \"Shifting\" , yytoken , yylval ) ; /* Discard the token being shifted.  */ yychar = yyempty_ ; /* Count tokens shifted since error; after three, turn off error\n               status.  */ if ( yyerrstatus_ > 0 ) -- yyerrstatus_ ; yystate = yyn ; yystack . push ( yystate , yylval ) ; label = YYNEWSTATE ; } break ; /*-----------------------------------------------------------.\n      | yydefault -- do the default action for the current state.  |\n      `-----------------------------------------------------------*/ case YYDEFAULT : yyn = yydefact_ [ yystate ] ; if ( yyn == 0 ) label = YYERRLAB ; else label = YYREDUCE ; break ; /*-----------------------------.\n      | yyreduce -- Do a reduction.  |\n      `-----------------------------*/ case YYREDUCE : yylen = yyr2_ [ yyn ] ; label = yyaction ( yyn , yystack , yylen ) ; yystate = yystack . stateAt ( 0 ) ; break ; /*------------------------------------.\n      | yyerrlab -- here on detecting error |\n      `------------------------------------*/ case YYERRLAB : /* If not already recovering from an error, report this error.  */ if ( yyerrstatus_ == 0 ) { ++ yynerrs_ ; if ( yychar == yyempty_ ) yytoken = yyempty_ ; yyerror ( yysyntax_error ( yystate , yytoken ) ) ; } if ( yyerrstatus_ == 3 ) { /* If just tried and failed to reuse lookahead token after an\n         error, discard it.  */ if ( yychar <= Lexer . EOF ) { /* Return failure if at end of input.  */ if ( yychar == Lexer . EOF ) return false ; } else yychar = yyempty_ ; } /* Else will try to reuse lookahead token after shifting the error\n           token.  */ label = YYERRLAB1 ; break ; /*-------------------------------------------------.\n      | errorlab -- error raised explicitly by YYERROR.  |\n      `-------------------------------------------------*/ case YYERROR : /* Do not reclaim the symbols of the rule which action triggered\n           this YYERROR.  */ yystack . pop ( yylen ) ; yylen = 0 ; yystate = yystack . stateAt ( 0 ) ; label = YYERRLAB1 ; break ; /*-------------------------------------------------------------.\n      | yyerrlab1 -- common code for both syntax error and YYERROR.  |\n      `-------------------------------------------------------------*/ case YYERRLAB1 : yyerrstatus_ = 3 ; /* Each real token shifted decrements this.  */ for ( ; ; ) { yyn = yypact_ [ yystate ] ; if ( ! yy_pact_value_is_default_ ( yyn ) ) { yyn += yyterror_ ; if ( 0 <= yyn && yyn <= yylast_ && yycheck_ [ yyn ] == yyterror_ ) { yyn = yytable_ [ yyn ] ; if ( 0 < yyn ) break ; } } /* Pop the current state because it cannot handle the\n             * error token.  */ if ( yystack . height == 0 ) return false ; yystack . pop ( ) ; yystate = yystack . stateAt ( 0 ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; } if ( label == YYABORT ) /* Leave the switch.  */ break ; /* Shift the error token.  */ yy_symbol_print ( \"Shifting\" , yystos_ [ yyn ] , yylval ) ; yystate = yyn ; yystack . push ( yyn , yylval ) ; label = YYNEWSTATE ; break ; /* Accept.  */ case YYACCEPT : return true ; /* Abort.  */ case YYABORT : return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate an error message . [CODESPLIT] private String yysyntax_error ( int yystate , int tok ) { if ( yyErrorVerbose ) { /* There are many possibilities here to consider:\n           - If this state is a consistent state with a default action,\n             then the only way this function was invoked is if the\n             default action is an error action.  In that case, don't\n             check for expected tokens because there are none.\n           - The only way there can be no lookahead present (in tok) is\n             if this state is a consistent state with a default action.\n             Thus, detecting the absence of a lookahead is sufficient to\n             determine that there is no unexpected or expected token to\n             report.  In that case, just report a simple \"syntax error\".\n           - Don't assume there isn't a lookahead just because this\n             state is a consistent state with a default action.  There\n             might have been a previous inconsistent state, consistent\n             state with a non-default action, or user semantic action\n             that manipulated yychar.  (However, yychar is currently out\n             of scope during semantic actions.)\n           - Of course, the expected token list depends on states to\n             have correct lookahead information, and it depends on the\n             parser not to perform extra reductions after fetching a\n             lookahead from the scanner and before detecting a syntax\n             error.  Thus, state merging (from LALR or IELR) and default\n             reductions corrupt the expected token list.  However, the\n             list is correct for canonical LR with one exception: it\n             will still contain any token that will not be accepted due\n             to an error action in a later state.\n        */ if ( tok != yyempty_ ) { /* FIXME: This method of building the message is not compatible\n               with internationalization.  */ StringBuffer res = new StringBuffer ( \"syntax error, unexpected \" ) ; res . append ( yytnamerr_ ( yytname_ [ tok ] ) ) ; int yyn = yypact_ [ yystate ] ; if ( ! yy_pact_value_is_default_ ( yyn ) ) { /* Start YYX at -YYN if negative to avoid negative\n                   indexes in YYCHECK.  In other words, skip the first\n                   -YYN actions for this state because they are default\n                   actions.  */ int yyxbegin = yyn < 0 ? - yyn : 0 ; /* Stay within bounds of both yycheck and yytname.  */ int yychecklim = yylast_ - yyn + 1 ; int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_ ; int count = 0 ; for ( int x = yyxbegin ; x < yyxend ; ++ x ) if ( yycheck_ [ x + yyn ] == x && x != yyterror_ && ! yy_table_value_is_error_ ( yytable_ [ x + yyn ] ) ) ++ count ; if ( count < 5 ) { count = 0 ; for ( int x = yyxbegin ; x < yyxend ; ++ x ) if ( yycheck_ [ x + yyn ] == x && x != yyterror_ && ! yy_table_value_is_error_ ( yytable_ [ x + yyn ] ) ) { res . append ( count ++ == 0 ? \", expecting \" : \" or \" ) ; res . append ( yytnamerr_ ( yytname_ [ x ] ) ) ; } } } return res . toString ( ) ; } } return \"syntax error\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Report on the debug stream that the rule yyrule is going to be reduced . [CODESPLIT] private void yy_reduce_print ( int yyrule , YYStack yystack ) { if ( yydebug == 0 ) return ; int yylno = yyrline_ [ yyrule ] ; int yynrhs = yyr2_ [ yyrule ] ; /* Print the symbols being reduced, and their result.  */ yycdebug ( \"Reducing stack by rule \" + ( yyrule - 1 ) + \" (line \" + yylno + \"), \" ) ; /* The symbols being reduced.  */ for ( int yyi = 0 ; yyi < yynrhs ; yyi ++ ) yy_symbol_print ( \"   $\" + ( yyi + 1 ) + \" =\"  , yystos_ [ yystack . stateAt ( yynrhs - ( yyi + 1 ) ) ] , ( ( yystack . valueAt ( yynrhs - ( yyi + 1 ) ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * the parse function allows the specification of a new stream in case one is reusing the parser [CODESPLIT] boolean parse ( String constraint ) throws ParseException { ( ( Celex ) yylexer ) . reset ( parsestate , constraint ) ; return parse ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This parses then fills in the evaluator from the AST [CODESPLIT] static public boolean constraint_expression ( CEEvaluator ceEval , BaseTypeFactory factory , ClauseFactory clauseFactory , String constraint , String url // for error reporting ) throws DAP2Exception , ParseException { CeParser parser = new CeParser ( factory ) ; parser . setURL ( url ) ; parser . setConstraint ( constraint ) ; ServerDDS sdds = ceEval . getDDS ( ) ; if ( ! parser . parse ( constraint ) ) return false ; ASTconstraint root = ( ASTconstraint ) parser . getAST ( ) ; root . init ( ceEval , factory , clauseFactory , sdds , parser . getASTnodeset ( ) ) ; root . walkConstraint ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this prefix against another PrefixSymbol . The sort keys are decreasing length ( major ) and increasing lexicality ( minor ) . [CODESPLIT] public final int compareTo ( Object obj ) { String thatID = ( ( PrefixSymbol ) obj ) . getID ( ) ; int comp = thatID . length ( ) - getID ( ) . length ( ) ; if ( comp == 0 ) comp = getID ( ) . compareTo ( thatID ) ; return comp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this prefix against a String . The sort keys are decreasing length ( major ) and increasing lexicality ( minor ) . [CODESPLIT] public final int compareTo ( String string ) { int comp = string . length ( ) - getID ( ) . length ( ) ; return comp < 0 ? comp : comp == 0 ? ( getID ( ) . compareTo ( string ) == 0 ? 0 : - 1 ) : ( getID ( ) . compareTo ( string . substring ( 0 , getID ( ) . length ( ) ) ) == 0 ? 0 : - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the DMR trimmed . [CODESPLIT] public String readDMR ( ) throws DapException { try { if ( state != State . INITIAL ) throw new DapException ( \"Attempt to read DMR twice\" ) ; byte [ ] dmr8 = null ; if ( requestmode == RequestMode . DMR ) { // The whole buffer is the dmr; // but we do not know the length ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; int c ; while ( ( c = input . read ( ) ) >= 0 ) { baos . write ( c ) ; } baos . close ( ) ; dmr8 = baos . toByteArray ( ) ; } else if ( requestmode == RequestMode . DAP ) { // Pull in the DMR chunk header if ( ! readHeader ( input ) ) throw new DapException ( \"Malformed chunk count\" ) ; // Read the DMR databuffer dmr8 = new byte [ this . chunksize ] ; int red = read ( dmr8 , 0 , this . chunksize ) ; if ( red < this . chunksize ) throw new DapException ( \"Short chunk\" ) ; } else assert false : \"Internal error\" ; // Convert DMR to a string String dmr = new String ( dmr8 , DapUtil . UTF8 ) ; // Clean it up dmr = dmr . trim ( ) ; // Make sure it has trailing \\r\\n\" if ( dmr . endsWith ( \"\\r\\n\" ) ) { // do nothing } else if ( dmr . endsWith ( \"\\n\" ) ) dmr = dmr . substring ( 0 , dmr . length ( ) - 2 ) + \"\\r\\n\" ; else dmr = dmr + \"\\r\\n\" ; // Figure out the endian-ness of the response this . remoteorder = ( flags & DapUtil . CHUNK_LITTLE_ENDIAN ) == 0 ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; this . nochecksum = ( flags & DapUtil . CHUNK_NOCHECKSUM ) != 0 ; // Set the state if ( ( flags & DapUtil . CHUNK_ERROR ) != 0 ) state = State . ERROR ; else if ( ( flags & DapUtil . CHUNK_END ) != 0 ) state = State . END ; else state = State . DATA ; return dmr ; //return the DMR } catch ( IOException ioe ) { throw new DapException ( ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an error chunk [CODESPLIT] public String readError ( ) throws IOException { state = State . ERROR ; // Read the error body databuffer byte [ ] bytes = new byte [ this . chunksize ] ; try { if ( read ( bytes , 0 , this . chunksize ) < this . chunksize ) throw new ErrorException ( \"Short chunk\" ) ; } catch ( IOException ioe ) { throw new ErrorException ( ioe ) ; } String document = new String ( bytes , DapUtil . UTF8 ) ; return document ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the next byte of databuffer from the input stream . The value byte is returned as an <code > int< / code > in the range <code > 0< / code > to <code > 255< / code > . If no byte is available because the end of the stream has been reached the value <code > - 1< / code > is returned . This method blocks until input databuffer is available the end of the stream is detected or an exception is thrown . <p > Operates by loading chunk by chunk . If an error chunk is detected then return ErrorException ( which is a subclass of IOException ) . [CODESPLIT] public int read ( ) throws IOException { if ( requestmode == RequestMode . DMR ) throw new UnsupportedOperationException ( \"Attempt to read databuffer when DMR only\" ) ; // Runtime if ( avail <= 0 ) { if ( ( flags & DapUtil . CHUNK_END ) != 0 ) return - 1 ; // Treat as EOF if ( ! readHeader ( input ) ) return - 1 ; // EOF // See if we have an error chunk, // and if so, turn it into an exception if ( ( flags & DapUtil . CHUNK_ERROR ) != 0 ) { String document = readError ( ) ; throwError ( document ) ; } } avail -- ; return input . read ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads up to len databuffer of databuffer from the input stream into an array of databuffer . An attempt is made to read as many as len databuffer but a smaller number may be read . The number of databuffer actually read is returned as an integer . [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { // Sanity check if ( off < 0 || len < 0 ) throw new IndexOutOfBoundsException ( ) ; // Runtime if ( off >= buf . length || buf . length < ( off + len ) ) throw new IndexOutOfBoundsException ( ) ; //Runtime if ( requestmode == RequestMode . DMR ) throw new UnsupportedOperationException ( \"Attempt to read databuffer when DMR only\" ) ; // Runtime // Attempt to read len bytes out of a sequence of chunks int count = len ; int pos = off ; while ( count > 0 ) { if ( avail <= 0 ) { if ( ( flags & DapUtil . CHUNK_END ) != 0 || ! readHeader ( input ) ) return ( len - count ) ; // return # databuffer read // See if we have an error chunk, // and if so, turn it into an exception if ( ( flags & DapUtil . CHUNK_ERROR ) != 0 ) { String document = readError ( ) ; throwError ( document ) ; } } else { int actual = ( this . avail < count ? this . avail : count ) ; int red = input . read ( buf , pos , actual ) ; if ( red < 0 ) throw new IOException ( \"Unexpected EOF\" ) ; pos += red ; count -= red ; this . avail -= red ; } } return len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the size + flags header from the input stream and use it to initialize the chunk state [CODESPLIT] boolean readHeader ( InputStream input ) throws IOException { byte [ ] bytehdr = new byte [ 4 ] ; int red = input . read ( bytehdr ) ; if ( red == - 1 ) return false ; if ( red < 4 ) throw new IOException ( \"Short binary chunk count\" ) ; this . flags = ( ( int ) bytehdr [ 0 ] ) & 0xFF ; // Keep unsigned bytehdr [ 0 ] = 0 ; ByteBuffer buf = ByteBuffer . wrap ( bytehdr ) . order ( ByteOrder . BIG_ENDIAN ) ; this . chunksize = buf . getInt ( ) ; this . avail = this . chunksize ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <Exp_CodeFlagTables_E > <No > 837< / No > <FXY > 002119< / FXY > <ElementName_E > Instrument operations< / ElementName_E > <CodeFigure > 0< / CodeFigure > <EntryName_E > Intermediate frequency calibration mode ( IF CAL ) < / EntryName_E > <Status > Operational< / Status > < / Exp_CodeFlagTables_E > [CODESPLIT] static private void init ( Map < Short , CodeFlagTables > table ) { String filename = BufrTables . RESOURCE_PATH + CodeFlagFilename ; try ( InputStream is = CodeFlagTables . class . getResourceAsStream ( filename ) ) { SAXBuilder builder = new SAXBuilder ( ) ; org . jdom2 . Document tdoc = builder . build ( is ) ; org . jdom2 . Element root = tdoc . getRootElement ( ) ; List < Element > elems = root . getChildren ( ) ; for ( Element elem : elems ) { String fxyS = elem . getChildText ( \"FXY\" ) ; String desc = elem . getChildText ( \"ElementName_en\" ) ; short fxy = Descriptor . getFxy2 ( fxyS ) ; CodeFlagTables ct = table . get ( fxy ) ; if ( ct == null ) { ct = new CodeFlagTables ( fxy , desc ) ; table . put ( fxy , ct ) ; // System.out.printf(\" added %s == %s %n\", ct.id, desc);\r } String line = elem . getChildText ( \"No\" ) ; String codeS = elem . getChildText ( \"CodeFigure\" ) ; String value = elem . getChildText ( \"EntryName_en\" ) ; if ( ( codeS == null ) || ( value == null ) ) continue ; if ( value . toLowerCase ( ) . startsWith ( \"reserved\" ) ) continue ; if ( value . toLowerCase ( ) . startsWith ( \"not used\" ) ) continue ; int code ; if ( codeS . toLowerCase ( ) . contains ( \"all\" ) ) { code = - 1 ; } else try { code = Integer . parseInt ( codeS ) ; } catch ( NumberFormatException e ) { log . debug ( \"NumberFormatException on line \" + line + \" in \" + codeS ) ; continue ; } ct . addValue ( ( short ) code , value ) ; } } catch ( IOException | JDOMException e ) { log . error ( \"Can't read BUFR code table \" + filename , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "udunits [CODESPLIT] static public String toDateTimeStringISO ( CalendarDate cd ) { if ( cd . getDateTime ( ) . getMillisOfSecond ( ) == 0 ) return isof . print ( cd . getDateTime ( ) ) ; else return isof_with_millis_of_second . print ( cd . getDateTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Old version using DateFormatter @param iso ISO 8601 date String @return equivilent Date [CODESPLIT] @ Deprecated static public Date parseISODate ( String iso ) { DateFormatter df = new DateFormatter ( ) ; return df . getISODate ( iso ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an ISO formatted String to a CalendarDate . @param calt calendar may be null for default calendar ( Calendar . getDefault () ) @param iso ISO 8601 date String <pre > possible forms for W3C profile of ISO 8601 Year : YYYY ( eg 1997 ) Year and month : YYYY - MM ( eg 1997 - 07 ) Complete date : YYYY - MM - DD ( eg 1997 - 07 - 16 ) Complete date plus hours and minutes : YYYY - MM - DDThh : mmTZD ( eg 1997 - 07 - 16T19 : 20 + 01 : 00 ) Complete date plus hours minutes and seconds : YYYY - MM - DDThh : mm : ssTZD ( eg 1997 - 07 - 16T19 : 20 : 30 + 01 : 00 ) Complete date plus hours minutes seconds and a decimal fraction of a second YYYY - MM - DDThh : mm : ss . sTZD ( eg 1997 - 07 - 16T19 : 20 : 30 . 45 + 01 : 00 ) [CODESPLIT] static public CalendarDate isoStringToCalendarDate ( Calendar calt , String iso ) throws IllegalArgumentException { DateTime dt = parseIsoTimeString ( calt , iso ) ; Calendar useCal = Calendar . of ( dt . getChronology ( ) ) ; return new CalendarDate ( useCal , dt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does not handle non - standard Calendars [CODESPLIT] static public Date isoStringToDate ( String iso ) throws IllegalArgumentException { CalendarDate dt = isoStringToCalendarDate ( null , iso ) ; return dt . toDate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : MeasurementTVP [CODESPLIT] public static MeasureTVPType initMeasurementTVP ( MeasureTVPType measurementTVP , PointFeature pointFeat , VariableSimpleIF dataVar ) throws IOException { // wml2:time NcTimePositionType . initTime ( measurementTVP . addNewTime ( ) , pointFeat ) ; // wml2:value NcMeasureType . initValue ( measurementTVP . addNewValue ( ) , pointFeat , dataVar ) ; return measurementTVP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a URL or file in as a table . [CODESPLIT] static public List < Record > readTable ( String urlString , String format , int maxLines ) throws IOException , NumberFormatException { InputStream ios ; if ( urlString . startsWith ( \"http:\" ) ) { URL url = new URL ( urlString ) ; ios = url . openStream ( ) ; } else { ios = new FileInputStream ( urlString ) ; } return readTable ( ios , format , maxLines ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads an input stream containing lines of ascii in fixed width format . Breaks each line into a set of Fields ( space or comma delimited ) which may be String integer or double . [CODESPLIT] static public List < Record > readTable ( InputStream ios , String format , int maxLines ) throws IOException , NumberFormatException { List < Record > result ; try { TableParser parser = new TableParser ( format ) ; result = parser . readAllRecords ( ios , maxLines ) ; } finally { ios . close ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy contents of src to target . skip ones that already exist ( by name ) . Dimensions and Variables are replaced with equivalent elements but unlimited dimensions are turned into regular dimensions . Attribute doesnt have to be replaced because its immutable so its copied by reference . [CODESPLIT] static public void transferDataset ( NetcdfFile src , NetcdfDataset target , ReplaceVariableCheck replaceCheck ) { transferGroup ( src , target , src . getRootGroup ( ) , target . getRootGroup ( ) , replaceCheck ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transfer the objects in src group to the target group [CODESPLIT] static private void transferGroup ( NetcdfFile ds , NetcdfDataset targetDs , Group src , Group targetGroup , ReplaceVariableCheck replaceCheck ) { boolean unlimitedOK = true ; // LOOK why not allowed? // group attributes transferGroupAttributes ( src , targetGroup ) ; // dimensions for ( Dimension d : src . getDimensions ( ) ) { if ( null == targetGroup . findDimensionLocal ( d . getShortName ( ) ) ) { Dimension newd = new Dimension ( d . getShortName ( ) , d . getLength ( ) , d . isShared ( ) , unlimitedOK && d . isUnlimited ( ) , d . isVariableLength ( ) ) ; targetGroup . addDimension ( newd ) ; } } // variables for ( Variable v : src . getVariables ( ) ) { Variable targetV = targetGroup . findVariable ( v . getShortName ( ) ) ; VariableEnhanced targetVe = ( VariableEnhanced ) targetV ; boolean replace = ( replaceCheck != null ) && replaceCheck . replace ( v ) ; // replaceCheck not currently used if ( replace || ( null == targetV ) ) { // replace it if ( ( v instanceof Structure ) && ! ( v instanceof StructureDS ) ) { v = new StructureDS ( targetGroup , ( Structure ) v ) ; // else if (!(v instanceof VariableDS) && !(v instanceof StructureDS)) Doug Lindolm } else if ( ! ( v instanceof VariableDS ) ) { v = new VariableDS ( targetGroup , v , false ) ; // enhancement done by original variable, this is just to reparent to target dataset. } if ( null != targetV ) targetGroup . remove ( targetV ) ; targetGroup . addVariable ( v ) ; // reparent group v . resetDimensions ( ) ; // dimensions will be different } else if ( ! targetV . hasCachedData ( ) && ( targetVe . getOriginalVariable ( ) == null ) ) { // this is the case where we defined the variable, but didnt set its data. we now set it with the first nested // dataset that has a variable with the same name targetVe . setOriginalVariable ( v ) ; } } // nested groups - check if target already has it for ( Group srcNested : src . getGroups ( ) ) { Group nested = targetGroup . findGroup ( srcNested . getShortName ( ) ) ; if ( null == nested ) { nested = new Group ( ds , targetGroup , srcNested . getShortName ( ) ) ; targetGroup . addGroup ( nested ) ; } transferGroup ( ds , targetDs , srcNested , nested , replaceCheck ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy attributes from src to target skip ones that already exist ( by name ) [CODESPLIT] static public void transferVariableAttributes ( Variable src , Variable target ) { for ( Attribute a : src . getAttributes ( ) ) { if ( null == target . findAttribute ( a . getShortName ( ) ) ) target . addAttribute ( a ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy attributes from src to target skip ones that already exist ( by name ) [CODESPLIT] static public void transferGroupAttributes ( Group src , Group target ) { for ( Attribute a : src . getAttributes ( ) ) { if ( null == target . findAttribute ( a . getShortName ( ) ) ) target . addAttribute ( a ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the Group in newFile that corresponds ( by name ) with oldGroup [CODESPLIT] static public Group findGroup ( NetcdfFile newFile , Group oldGroup ) { List < Group > chain = new ArrayList <> ( 5 ) ; Group g = oldGroup ; while ( g . getParentGroup ( ) != null ) { // skip the root chain . add ( 0 , g ) ; // put in front g = g . getParentGroup ( ) ; } Group newg = newFile . getRootGroup ( ) ; for ( Group oldg : chain ) { newg = newg . findGroup ( oldg . getShortName ( ) ) ; if ( newg == null ) return null ; } return newg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stn file must be in the same directory or one up [CODESPLIT] private File getStnFile ( String location ) { File file = new File ( location ) ; File stnFile = new File ( file . getParentFile ( ) , STN_FILE ) ; if ( ! stnFile . exists ( ) ) { if ( file . getParentFile ( ) == null ) return null ; stnFile = new File ( file . getParentFile ( ) . getParentFile ( ) , STN_FILE ) ; if ( ! stnFile . exists ( ) ) return null ; } return stnFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if a DAT file [CODESPLIT] @ Override public void open ( RandomAccessFile raff , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raff , ncfile , cancelTask ) ; int pos = location . lastIndexOf ( \".\" ) ; String ext = location . substring ( pos ) ; File file = new File ( location ) ; File stnFile = getStnFile ( location ) ; if ( stnFile == null ) throw new FileNotFoundException ( \"Station File does not exist=\" + location ) ; if ( ext . equals ( IDX_EXT ) ) { stnRaf = RandomAccessFile . acquire ( stnFile . getPath ( ) ) ; } else if ( ext . equals ( DAT_EXT ) ) { stnRaf = RandomAccessFile . acquire ( stnFile . getPath ( ) ) ; dataRaf = raff ; //extract the station id\r String name = file . getName ( ) ; stationId = name . substring ( 0 , name . length ( ) - DAT_EXT . length ( ) ) ; } else { // pointed to the station file\r stnRaf = raff ; dataDir = new File ( file . getParentFile ( ) , DAT_DIR ) ; } NcmlConstructor ncmlc = new NcmlConstructor ( ) ; if ( ! ncmlc . populateFromResource ( \"resources/nj22/iosp/igra-por.ncml\" , ncfile ) ) { throw new IllegalStateException ( ncmlc . getErrlog ( ) . toString ( ) ) ; } ncfile . finish ( ) ; //dataVinfo = setVinfo(dataRaf, ncfile, dataPattern, \"all_data\");\r stnVinfo = setVinfo ( stnRaf , ncfile , stnPattern , \"station\" ) ; seriesVinfo = setVinfo ( stnRaf , ncfile , dataHeaderPattern , \"station.time_series\" ) ; profileVinfo = setVinfo ( stnRaf , ncfile , dataPattern , \"station.time_series.levels\" ) ; StructureMembers . Member m = stnVinfo . sm . findMember ( STNID ) ; StructureDataRegexp . VinfoField f = ( StructureDataRegexp . VinfoField ) m . getDataObject ( ) ; stn_fldno = f . fldno ; /* make index file if needed\r\n    File idxFile = new File(base + IDX_EXT);\r\n    if (!idxFile.exists())\r\n      makeIndex(stnVinfo, dataVinfo, idxFile);\r\n    else\r\n      readIndex(idxFile.getPath());  */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { StructureDataRegexp . Vinfo vinfo = ( StructureDataRegexp . Vinfo ) v2 . getSPobject ( ) ; if ( stationId != null ) return new ArraySequence ( vinfo . sm , new SingleStationSeqIter ( vinfo ) , vinfo . nelems ) ; else return new ArraySequence ( vinfo . sm , new StationSeqIter ( vinfo ) , vinfo . nelems ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////// [CODESPLIT] public SubsetParams makeSubset ( CoverageCollection gcd ) { Calendar cal = gcd . getCalendar ( ) ; boolean isFmrc = gcd . getCoverageType ( ) == FeatureType . FMRC ; SubsetParams subset = new SubsetParams ( ) ; // vars subset . set ( SubsetParams . variables , var ) ; // other coords if ( vertCoord != null ) subset . set ( SubsetParams . vertCoord , vertCoord ) ; if ( ensCoord != null ) subset . set ( SubsetParams . ensCoord , ensCoord ) ; // horiz subset if ( hasProjectionBB ( ) ) subset . set ( SubsetParams . projBB , getProjectionBB ( ) ) ; else if ( hasLatLonBB ( ) ) subset . set ( SubsetParams . latlonBB , getLatLonBoundingBox ( ) ) ; if ( horizStride != null && horizStride != 1 ) subset . set ( SubsetParams . horizStride , horizStride ) ; if ( hasLatLonPoint ( ) ) subset . set ( SubsetParams . latlonPoint , new LatLonPointImpl ( getLatitude ( ) , getLongitude ( ) ) ) ; if ( isFmrc ) { // 2D Time subsetting // runtime CalendarDate rundate = getRuntimeDate ( cal ) ; if ( rundate != null ) subset . set ( SubsetParams . runtime , rundate ) ; else if ( allRuntime ) subset . set ( SubsetParams . runtimeAll , true ) ; else subset . set ( SubsetParams . runtimeLatest , true ) ; // default // timeOffset if ( timeOffsetVal != null ) subset . set ( SubsetParams . timeOffset , timeOffsetVal ) ; else if ( firstTimeOffset ) subset . set ( SubsetParams . timeOffsetFirst , true ) ; else { // if no timeOffset, will allow some time values CalendarDate date = getRequestedDate ( cal ) ; CalendarDateRange dateRange = getCalendarDateRange ( cal ) ; if ( isPresentTime ( ) ) subset . setTimePresent ( ) ; else if ( isAllTimes ( ) && ! allRuntime ) { subset . set ( SubsetParams . timeAll , true ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } else if ( date != null ) { // for allRuntimes, only a date is allowed subset . set ( SubsetParams . time , date ) ; } else if ( dateRange != null && ! allRuntime ) { subset . set ( SubsetParams . timeRange , dateRange ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } } } else { // not an FMRC // time CalendarDate date = getRequestedDate ( cal ) ; CalendarDateRange dateRange = getCalendarDateRange ( cal ) ; if ( isPresentTime ( ) ) subset . setTimePresent ( ) ; else if ( isAllTimes ( ) ) { subset . set ( SubsetParams . timeAll , true ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } else if ( date != null ) { subset . set ( SubsetParams . time , date ) ; } else if ( dateRange != null ) { subset . set ( SubsetParams . timeRange , dateRange ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } else { subset . set ( SubsetParams . timePresent , true ) ; } } return subset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the first instance of c at or after fromIndex ( 0 .. ) in cArray . [CODESPLIT] public static int indexOf ( char [ ] cArray , char c , int fromIndex ) { int cArrayLength = cArray . length ; for ( int index = Math . max ( fromIndex , 0 ) ; index < cArrayLength ; index ++ ) { if ( cArray [ index ] == c ) return index ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This includes hiASCII / ISO Latin 1 / ISO 8859 - 1 but not extensive unicode characters . Letters are A .. Z a .. z and #192 .. #255 ( except #215 and #247 ) . For unicode characters see Java Lang Spec pg 14 . [CODESPLIT] public static boolean isLetter ( int c ) { //return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) //|| ((c >= '\\u00c0') && (c <= '\\u00FF') && (c != '\\u00d7') //&& (c != '\\u00f7'))); if ( c < ' ' ) return false ; if ( c <= ' ' ) return true ; if ( c < ' ' ) return false ; if ( c <= ' ' ) return true ; if ( c < ' ' ) return false ; if ( c == ' ' ) return false ; if ( c <= ' ' ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string where all occurences of <TT > oldCh< / TT > have been replaced with <TT > newCh< / TT > . This doesn t throw exceptions if bad values . [CODESPLIT] public static String replaceAll ( String s , char oldCh , char newCh ) { int po = s . indexOf ( oldCh ) ; if ( po < 0 ) return s ; StringBuilder buffer = new StringBuilder ( s ) ; while ( po >= 0 ) { buffer . setCharAt ( po , newCh ) ; po = s . indexOf ( oldCh , po + 1 ) ; } return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string to an int . Leading or trailing spaces are automatically removed . This accepts hexadecimal integers starting with 0x . Leading 0 s ( e . g . 0012 ) are ignored ; number is treated as decimal ( not octal as Java would ) . Floating point numbers are rounded . This won t throw an exception if the number isn t formatted right . To make a string from an int use + i Integer . toHexString or Integer . toString ( i radix ) . [CODESPLIT] public static int parseInt ( String s ) { //*** XML.decodeEntities relies on leading 0's being ignored  //    and number treated as decimal (not octal) //quickly reject most non-numbers //This is a huge speed improvement when parsing ASCII data files //  because Java is very slow at filling in the stack trace when an exception is thrown. if ( s == null ) return Integer . MAX_VALUE ; s = s . trim ( ) ; if ( s . length ( ) == 0 ) return Integer . MAX_VALUE ; char ch = s . charAt ( 0 ) ; if ( ( ch < ' ' || ch > ' ' ) && ch != ' ' && ch != ' ' && ch != ' ' ) return Integer . MAX_VALUE ; //try to parse hex or regular int         try { if ( s . startsWith ( \"0x\" ) ) return Integer . parseInt ( s . substring ( 2 ) , 16 ) ; return Integer . parseInt ( s ) ; } catch ( Exception e ) { //falls through } //round from double? try { //2011-02-09 Bob Simons added to avoid Java hang bug. //But now, latest version of Java is fixed. //if (isDoubleTrouble(s)) return 0;   return ErddapMath2 . roundToInt ( Double . parseDouble ( s ) ) ; } catch ( Exception e ) { return Integer . MAX_VALUE ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string to a double . Leading or trailing spaces are automatically removed . This accepts hexadecimal integers starting with 0x . Whole number starting with 0 ( e . g . 012 ) is treated as decimal ( not octal as Java would ) . This won t throw an exception if the number isn t formatted right . [CODESPLIT] public static double parseDouble ( String s ) { //quickly reject most non-numbers //This is a huge speed improvement when parsing ASCII data files //  because Java is very slow at filling in the stack trace when an exception is thrown. if ( s == null ) return Double . NaN ; s = s . trim ( ) ; if ( s . length ( ) == 0 ) return Double . NaN ; char ch = s . charAt ( 0 ) ; if ( ( ch < ' ' || ch > ' ' ) && ch != ' ' && ch != ' ' && ch != ' ' ) return Double . NaN ; try { if ( s . startsWith ( \"0x\" ) ) return Integer . parseInt ( s . substring ( 2 ) , 16 ) ; //2011-02-09 Bob Simons added to avoid Java hang bug. //But now, latest version of Java is fixed. //if (isDoubleTrouble(s)) return 0;   return Double . parseDouble ( s ) ; } catch ( Exception e ) { return Double . NaN ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts String representation of a long . Leading or trailing spaces are automatically removed . This * doesn t * round . So floating point values lead to Long . MAX_VALUE . [CODESPLIT] public static long parseLong ( String s ) { //quickly reject most non-numbers //This is a huge speed improvement when parsing ASCII data files //  because Java is very slow at filling in the stack trace when an exception is thrown. if ( s == null ) return Long . MAX_VALUE ; s = s . trim ( ) ; if ( s . length ( ) == 0 ) return Long . MAX_VALUE ; char ch = s . charAt ( 0 ) ; if ( ( ch < ' ' || ch > ' ' ) && ch != ' ' && ch != ' ' ) return Long . MAX_VALUE ; try { if ( s . startsWith ( \"0x\" ) ) return Long . parseLong ( s . substring ( 2 ) , 16 ) ; return Long . parseLong ( s ) ; } catch ( Exception e ) { return Long . MAX_VALUE ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts a double to a rational number ( m * 10^t ) . This is similar to Math2 . mantissa and Math2 . intExponent but works via string manipulation to avoid roundoff problems ( e . g . with 6 . 6260755e - 24 ) . [CODESPLIT] public static int [ ] toRational ( double d ) { if ( d == 0 ) return new int [ ] { 0 , 0 } ; if ( ! ErddapMath2 . isFinite ( d ) ) return new int [ ] { 1 , Integer . MAX_VALUE } ; String s = \"\" + d ; //-12.0 or 6.6260755E-24 //String2.log(\"\\nd=\" + d + \"\\ns=\" + s); int ten = 0 ; //remove the e int epo = s . indexOf ( ' ' ) ; if ( epo > 0 ) { ten = parseInt ( s . substring ( epo + 1 ) ) ; s = s . substring ( 0 , epo ) ; //String2.log(\"remove E s=\" + s + \" ten=\" + ten); } //remove .0; remove decimal point if ( s . endsWith ( \".0\" ) ) s = s . substring ( 0 , s . length ( ) - 2 ) ; int dpo = s . indexOf ( ' ' ) ; if ( dpo > 0 ) { ten -= s . length ( ) - dpo - 1 ; s = s . substring ( 0 , dpo ) + s . substring ( dpo + 1 ) ; //String2.log(\"remove . s=\" + s + \" ten=\" + ten); } //convert s to long //need to lose some precision? long tl = parseLong ( s ) ; //String2.log(\"tl=\" + tl + \" s=\" + s); while ( Math . abs ( tl ) > 1000000000 ) { tl = Math . round ( tl / 10.0 ) ; ten ++ ; //String2.log(\"tl=\" + tl + \" ten=\" + ten); } //remove trailing 0's while ( tl != 0 && tl / 10 == tl / 10.0 ) { tl /= 10 ; ten ++ ; //String2.log(\"remove 0 tl=\" + tl + \" ten=\" + ten); } //add up to 3 0's? if ( tl < 100000 && ten >= 1 && ten <= 3 ) { while ( ten > 0 ) { tl *= 10 ; ten -- ; } } return new int [ ] { ( int ) tl , ten } ; //safe since large values handled above }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the beginning index of a geometry s points given the index of the geometry within the array . [CODESPLIT] public int getBeginning ( int index ) { //Test if the last end is the new beginning\r if ( index == ( pastIndex + 1 ) ) { return previousEnd + 1 ; } // Otherwise, find it!\r int newBeginning = 0 ; for ( int i = 0 ; i < index ; i ++ ) { newBeginning += getNodeCount ( i ) ; } pastIndex = index ; previousBegin = newBeginning ; return newBeginning ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the ending index of a geometry s points given the index of the geometry within the array . [CODESPLIT] public int getEnd ( int index ) { // Test if the last beginning is the new end\r if ( index == ( pastIndex - 1 ) ) { return previousBegin - 1 ; } // Otherwise find it!\r int new_end = 0 ; for ( int i = 0 ; i < index + 1 ; i ++ ) { new_end += getNodeCount ( i ) ; } pastIndex = index ; previousEnd = new_end ; return new_end - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for OPeNDAP ascii requests . Returns OPeNDAP DAP2 data in comma delimited ascii columns for ingestion into some not so OPeNDAP enabled application such as MS - Excel . Accepts constraint expressions in exactly the same way as the regular OPeNDAP dataserver . [CODESPLIT] public void sendASCII ( ReqState rs , String dataSet ) throws DAP2Exception , ParseException { if ( Debug . isSet ( \"showResponse\" ) ) System . out . println ( \"Sending OPeNDAP ASCII Data For: \" + dataSet + \"    CE: '\" + rs . getConstraintExpression ( ) + \"'\" ) ; String requestURL , ce ; DataDDS dds ; if ( rs . getConstraintExpression ( ) == null ) { ce = \"\" ; } else { ce = \"?\" + rs . getConstraintExpression ( ) ; } int suffixIndex = rs . getRequestURL ( ) . toString ( ) . lastIndexOf ( \".\" ) ; requestURL = rs . getRequestURL ( ) . substring ( 0 , suffixIndex ) ; if ( Debug . isSet ( \"showResponse\" ) ) { System . out . println ( \"New Request URL Resource: '\" + requestURL + \"'\" ) ; System . out . println ( \"New Request Constraint Expression: '\" + ce + \"'\" ) ; } if ( _Debug ) System . out . println ( \"Making connection to .dods service...\" ) ; try ( DConnect2 url = new DConnect2 ( requestURL , true ) ) { if ( _Debug ) System . out . println ( \"Requesting data...\" ) ; dds = url . getData ( ce , null , new asciiFactory ( ) ) ; if ( _Debug ) System . out . println ( \" ASC DDS: \" ) ; if ( _Debug ) dds . print ( System . out ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; PrintWriter pwDebug = new PrintWriter ( new OutputStreamWriter ( System . out , Util . UTF8 ) ) ; if ( dds != null ) { dds . print ( pw ) ; pw . println ( \"---------------------------------------------\" ) ; String s = \"\" ; Enumeration e = dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; if ( _Debug ) ( ( toASCII ) bt ) . toASCII ( pwDebug , true , null , true ) ; //bt.toASCII(pw,addName,getNAme(),true);\r ( ( toASCII ) bt ) . toASCII ( pw , true , null , true ) ; } } else { String betterURL = rs . getRequestURL ( ) . substring ( 0 , rs . getRequestURL ( ) . lastIndexOf ( \".\" ) ) + \".dods?\" + rs . getConstraintExpression ( ) ; pw . println ( \"-- ASCII RESPONSE HANDLER PROBLEM --\" ) ; pw . println ( \"\" ) ; pw . println ( \"The ASCII response handler was unable to obtain requested data set.\" ) ; pw . println ( \"\" ) ; pw . println ( \"Because this handler calls it's own OPeNDAP server to get the requested\" ) ; pw . println ( \"data the source error is obscured.\" ) ; pw . println ( \"\" ) ; pw . println ( \"To get a better idea of what is going wrong, try requesting the URL:\" ) ; pw . println ( \"\" ) ; pw . println ( \"    \" + betterURL ) ; pw . println ( \"\" ) ; pw . println ( \"And then look carefully at the returned document. Note that if you\" ) ; pw . println ( \"are using a browser to access the URL the returned document will\" ) ; pw . println ( \"more than likely be treated as a download and written to your\" ) ; pw . println ( \"local disk. It should be a file with the extension \\\".dods\\\"\" ) ; pw . println ( \"\" ) ; pw . println ( \"Locate it, open it with a text editor, and find your\" ) ; pw . println ( \"way to happiness and inner peace.\" ) ; pw . println ( \"\" ) ; } //pw.println(\"</pre>\");\r pw . flush ( ) ; if ( _Debug ) pwDebug . flush ( ) ; } catch ( FileNotFoundException fnfe ) { System . out . println ( \"OUCH! FileNotFoundException: \" + fnfe . getMessage ( ) ) ; fnfe . printStackTrace ( System . out ) ; } catch ( MalformedURLException mue ) { System . out . println ( \"OUCH! MalformedURLException: \" + mue . getMessage ( ) ) ; mue . printStackTrace ( System . out ) ; } catch ( IOException ioe ) { System . out . println ( \"OUCH! IOException: \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( System . out ) ; } catch ( Throwable t ) { System . out . println ( \"OUCH! Throwable: \" + t . getMessage ( ) ) ; t . printStackTrace ( System . out ) ; } if ( _Debug ) System . out . println ( \" GetAsciiHandler done\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throw exception if failure [CODESPLIT] boolean createIndex ( FeatureCollectionConfig . PartitionType ptype , Formatter errlog ) throws IOException { if ( ptype == FeatureCollectionConfig . PartitionType . all ) return createAllRuntimeCollections ( errlog ) ; else return createMultipleRuntimeCollections ( errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throw exception if failure [CODESPLIT] private boolean createMultipleRuntimeCollections ( Formatter errlog ) throws IOException { long start = System . currentTimeMillis ( ) ; List < MFile > files = new ArrayList <> ( ) ; List < ? extends Group > groups = makeGroups ( files , false , errlog ) ; List < MFile > allFiles = Collections . unmodifiableList ( files ) ; if ( allFiles . size ( ) == 0 ) { throw new IllegalStateException ( \"No files in this collection =\" + name + \" topdir=\" + dcm . getRoot ( ) ) ; } if ( groups . size ( ) == 0 ) { throw new IllegalStateException ( \"No records in this collection =\" + name + \" topdir=\" + dcm . getRoot ( ) ) ; } // Create the master runtimes, classify the result CalendarDateRange calendarDateRangeAll = null ; //boolean allTimesAreOne = true; boolean allTimesAreUnique = true ; Set < Long > allRuntimes = new HashSet <> ( ) ; for ( Group g : groups ) { allRuntimes . addAll ( g . getCoordinateRuntimes ( ) ) ; for ( Coordinate coord : g . getCoordinates ( ) ) { if ( coord instanceof CoordinateTime2D ) { CoordinateTime2D coord2D = ( CoordinateTime2D ) coord ; if ( allTimesAreUnique ) { allTimesAreUnique = coord2D . hasUniqueTimes ( ) ; } } if ( coord instanceof CoordinateTimeAbstract ) { CalendarDateRange calendarDateRange = ( ( CoordinateTimeAbstract ) coord ) . makeCalendarDateRange ( null ) ; if ( calendarDateRangeAll == null ) calendarDateRangeAll = calendarDateRange ; else calendarDateRangeAll = calendarDateRangeAll . extend ( calendarDateRange ) ; } } } List < Long > sortedList = new ArrayList <> ( allRuntimes ) ; Collections . sort ( sortedList ) ; if ( sortedList . size ( ) == 0 ) throw new IllegalArgumentException ( \"No runtimes in this collection =\" + name ) ; else if ( sortedList . size ( ) == 1 ) this . type = GribCollectionImmutable . Type . SRC ; else if ( allTimesAreUnique ) this . type = GribCollectionImmutable . Type . MRUTC ; else this . type = GribCollectionImmutable . Type . MRC ; CoordinateRuntime masterRuntimes = new CoordinateRuntime ( sortedList , null ) ; MFile indexFileForRuntime = GribCollectionMutable . makeIndexMFile ( this . name , directory ) ; boolean ok = writeIndex ( this . name , indexFileForRuntime . getPath ( ) , masterRuntimes , groups , allFiles , calendarDateRangeAll ) ; /* if (this.type ==  GribCollectionImmutable.Type.MRC) {\n      GribBestDatasetBuilder.makeDatasetBest();\n    } */ long took = System . currentTimeMillis ( ) - start ; logger . debug ( \"That took {} msecs\" , took ) ; return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates seperate collection and index for each runtime . [CODESPLIT] private boolean createAllRuntimeCollections ( Formatter errlog ) throws IOException { long start = System . currentTimeMillis ( ) ; this . type = GribCollectionImmutable . Type . SRC ; boolean ok = true ; List < MFile > files = new ArrayList <> ( ) ; List < ? extends Group > groups = makeGroups ( files , true , errlog ) ; List < MFile > allFiles = Collections . unmodifiableList ( files ) ; // gather into collections with a single runtime Map < Long , List < Group > > runGroups = new HashMap <> ( ) ; for ( Group g : groups ) { List < Group > runGroup = runGroups . computeIfAbsent ( g . getRuntime ( ) . getMillis ( ) , k -> new ArrayList <> ( ) ) ; runGroup . add ( g ) ; } // write each rungroup separately boolean multipleRuntimes = runGroups . values ( ) . size ( ) > 1 ; List < MFile > partitions = new ArrayList <> ( ) ; for ( List < Group > runGroupList : runGroups . values ( ) ) { Group g = runGroupList . get ( 0 ) ; // if multiple Runtimes, we will write a partition. otherwise, we need to use the standard name (without runtime) so we know the filename from the collection String gcname = multipleRuntimes ? GribCollectionMutable . makeName ( this . name , g . getRuntime ( ) ) : this . name ; MFile indexFileForRuntime = GribCollectionMutable . makeIndexMFile ( gcname , directory ) ; // not using disk cache LOOK why ? partitions . add ( indexFileForRuntime ) ; // create the master runtimes, consisting of the single runtime List < Long > runtimes = new ArrayList <> ( 1 ) ; runtimes . add ( g . getRuntime ( ) . getMillis ( ) ) ; CoordinateRuntime masterRuntimes = new CoordinateRuntime ( runtimes , null ) ; CalendarDateRange calendarDateRangeAll = null ; for ( Coordinate coord : g . getCoordinates ( ) ) { if ( coord instanceof CoordinateTimeAbstract ) { CalendarDateRange calendarDateRange = ( ( CoordinateTimeAbstract ) coord ) . makeCalendarDateRange ( null ) ; if ( calendarDateRangeAll == null ) calendarDateRangeAll = calendarDateRange ; else calendarDateRangeAll = calendarDateRangeAll . extend ( calendarDateRange ) ; } } assert calendarDateRangeAll != null ; // for each Group write an index file ok &= writeIndex ( gcname , indexFileForRuntime . getPath ( ) , masterRuntimes , runGroupList , allFiles , calendarDateRangeAll ) ; logger . info ( \"GribCollectionBuilder write {} ok={}\" , indexFileForRuntime . getPath ( ) , ok ) ; } // if theres more than one runtime, create a partition collection to collect all the runtimes together if ( multipleRuntimes ) { Collections . sort ( partitions ) ; // ?? PartitionManager part = new PartitionManagerFromIndexList ( dcm , partitions , logger ) ; part . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , dcm . getAuxInfo ( FeatureCollectionConfig . AUX_CONFIG ) ) ; ok &= GribCdmIndex . updateGribCollectionFromPCollection ( isGrib1 , part , CollectionUpdateType . always , errlog , logger ) ; } long took = System . currentTimeMillis ( ) - start ; logger . debug ( \"That took {} msecs\" , took ) ; return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if edit value is valid put error message in buff . [CODESPLIT] protected boolean _validate ( StringBuffer buff ) { String editValue = tf . getText ( ) . trim ( ) ; if ( editValue . length ( ) == 0 ) return true ; // empty ok try { new TimeDuration ( tf . getText ( ) ) ; return true ; } catch ( java . text . ParseException e ) { buff . append ( label ) . append ( \": \" ) . append ( e . getMessage ( ) ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get current value from editComponent [CODESPLIT] protected Object getEditValue ( ) { String editValue = tf . getText ( ) . trim ( ) ; if ( editValue . length ( ) == 0 ) return null ; // empty ok try { return new TimeDuration ( editValue ) ; } catch ( java . text . ParseException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set current value of editComponent [CODESPLIT] protected void setEditValue ( Object value ) { if ( value == null ) tf . setText ( \"\" ) ; else tf . setText ( value . toString ( ) ) ; // tf.repaint(); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the string of entity ID for the Dorade image file [CODESPLIT] DataType getDataType ( int format ) { DataType p ; switch ( format ) { case 1 : // 8-bit signed integer format.\r p = DataType . SHORT ; break ; case 2 : // 16-bit signed integer format.\r p = DataType . FLOAT ; break ; case 3 : // 32-bit signed integer format.\r p = DataType . LONG ; break ; case 4 : // 32-bit IEEE float format.\r p = DataType . FLOAT ; break ; case 5 : //  16-bit IEEE float format.\r p = DataType . DOUBLE ; break ; default : p = null ; break ; } //end of switch\r return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { Attribute leoAtt = ds . findGlobalAttribute ( \"leoId\" ) ; if ( leoAtt == null ) { if ( ds . findVariable ( \"time\" ) == null ) { // create a time variable - assume its linear along the vertical dimension\r double start = ds . readAttributeDouble ( null , \"start_time\" , Double . NaN ) ; double stop = ds . readAttributeDouble ( null , \"stop_time\" , Double . NaN ) ; if ( Double . isNaN ( start ) && Double . isNaN ( stop ) ) { double top = ds . readAttributeDouble ( null , \"toptime\" , Double . NaN ) ; double bot = ds . readAttributeDouble ( null , \"bottime\" , Double . NaN ) ; this . conventionName = \"Cosmic2\" ; if ( top > bot ) { stop = top ; start = bot ; } else { stop = bot ; start = top ; } } Dimension dim = ds . findDimension ( \"MSL_alt\" ) ; Variable dimV = ds . findVariable ( \"MSL_alt\" ) ; Array dimU = dimV . read ( ) ; int inscr = ( dimU . getFloat ( 1 ) - dimU . getFloat ( 0 ) ) > 0 ? 1 : 0 ; int n = dim . getLength ( ) ; double incr = ( stop - start ) / n ; String timeUnits = \"seconds since 1980-01-06 00:00:00\" ; Variable timeVar = new VariableDS ( ds , null , null , \"time\" , DataType . DOUBLE , dim . getShortName ( ) , timeUnits , null ) ; ds . addVariable ( null , timeVar ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , timeUnits ) ) ; timeVar . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ) ; int dir = ds . readAttributeInteger ( null , \"irs\" , 1 ) ; ArrayDouble . D1 data = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , new int [ ] { n } ) ; if ( inscr == 0 ) { if ( dir == 1 ) { for ( int i = 0 ; i < n ; i ++ ) { data . set ( i , start + i * incr ) ; } } else { for ( int i = 0 ; i < n ; i ++ ) { data . set ( i , stop - i * incr ) ; } } } else { for ( int i = 0 ; i < n ; i ++ ) { data . set ( i , stop - i * incr ) ; } } timeVar . setCachedData ( data , false ) ; } Variable v = ds . findVariable ( \"Lat\" ) ; if ( v == null ) { v = ds . findVariable ( \"GEO_lat\" ) ; } v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; Variable v1 = ds . findVariable ( \"Lon\" ) ; if ( v1 == null ) { v1 = ds . findVariable ( \"GEO_lon\" ) ; } v1 . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; } else { Dimension dim = ds . findDimension ( \"time\" ) ; int n = dim . getLength ( ) ; Variable latVar = new VariableDS ( ds , null , null , \"Lat\" , DataType . FLOAT , dim . getShortName ( ) , \"degree\" , null ) ; latVar . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; ds . addVariable ( null , latVar ) ; Variable lonVar = new VariableDS ( ds , null , null , \"Lon\" , DataType . FLOAT , dim . getShortName ( ) , \"degree\" , null ) ; lonVar . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; ds . addVariable ( null , lonVar ) ; Variable altVar = new VariableDS ( ds , null , null , \"MSL_alt\" , DataType . FLOAT , dim . getShortName ( ) , \"meter\" , null ) ; altVar . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Height . toString ( ) ) ) ; ds . addVariable ( null , altVar ) ; // cal data array\r ArrayFloat . D1 latData = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , new int [ ] { n } ) ; ArrayFloat . D1 lonData = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , new int [ ] { n } ) ; ArrayFloat . D1 altData = ( ArrayFloat . D1 ) Array . factory ( DataType . FLOAT , new int [ ] { n } ) ; ArrayDouble . D1 timeData = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , new int [ ] { n } ) ; this . conventionName = \"Cosmic3\" ; int iyr = ds . readAttributeInteger ( null , \"year\" , 2009 ) ; int mon = ds . readAttributeInteger ( null , \"month\" , 0 ) ; int iday = ds . readAttributeInteger ( null , \"day\" , 0 ) ; int ihr = ds . readAttributeInteger ( null , \"hour\" , 0 ) ; int min = ds . readAttributeInteger ( null , \"minute\" , 0 ) ; int sec = ds . readAttributeInteger ( null , \"second\" , 0 ) ; double start = ds . readAttributeDouble ( null , \"startTime\" , Double . NaN ) ; double stop = ds . readAttributeDouble ( null , \"stopTime\" , Double . NaN ) ; double incr = ( stop - start ) / n ; int t = 0 ; // double julian = juday(mon, iday, iyr);\r // cal the dtheta based pm attributes\r double dtheta = gast ( iyr , mon , iday , ihr , min , sec , t ) ; Variable tVar = ds . findVariable ( \"time\" ) ; String timeUnits = \"seconds since 1980-01-06 00:00:00\" ; //dtime.getUnit().toString();\r tVar . removeAttributeIgnoreCase ( CDM . VALID_RANGE ) ; tVar . removeAttributeIgnoreCase ( CDM . UNITS ) ; tVar . addAttribute ( new Attribute ( CDM . UNITS , timeUnits ) ) ; tVar . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ) ; Variable v = ds . findVariable ( \"xLeo\" ) ; Array xLeo = v . read ( ) ; v = ds . findVariable ( \"yLeo\" ) ; Array yLeo = v . read ( ) ; v = ds . findVariable ( \"zLeo\" ) ; Array zLeo = v . read ( ) ; double a = 6378.1370 ; double b = 6356.7523142 ; IndexIterator iiter0 = xLeo . getIndexIterator ( ) ; IndexIterator iiter1 = yLeo . getIndexIterator ( ) ; IndexIterator iiter2 = zLeo . getIndexIterator ( ) ; int i = 0 ; while ( iiter0 . hasNext ( ) ) { double [ ] v_inertial = new double [ 3 ] ; v_inertial [ 0 ] = iiter0 . getDoubleNext ( ) ; //.getDouble(i); //.nextDouble();\r v_inertial [ 1 ] = iiter1 . getDoubleNext ( ) ; //.getDouble(i); //.nextDouble();\r v_inertial [ 2 ] = iiter2 . getDoubleNext ( ) ; //.getDouble(i); //.nextDouble();\r double [ ] uvz = new double [ 3 ] ; uvz [ 0 ] = 0.0 ; uvz [ 1 ] = 0.0 ; uvz [ 2 ] = 1.0 ; // v_ecef should be in the (approximate) ECEF frame\r // double[] v_ecf = execute(v_inertial, julian);\r double [ ] v_ecf = spin ( v_inertial , uvz , - 1 * dtheta ) ; // cal lat/lon here\r // double [] llh = ECFtoLLA(v_ecf[0]*1000, v_ecf[1]*1000, v_ecf[2]*1000, a,  b);\r double [ ] llh = xyzell ( a , b , v_ecf ) ; latData . set ( i , ( float ) llh [ 0 ] ) ; lonData . set ( i , ( float ) llh [ 1 ] ) ; altData . set ( i , ( float ) llh [ 2 ] ) ; timeData . set ( i , start + i * incr ) ; i ++ ; } latVar . setCachedData ( latData , false ) ; lonVar . setCachedData ( lonData , false ) ; altVar . setCachedData ( altData , false ) ; tVar . setCachedData ( timeData , false ) ; } ds . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NAME : XYZELL <p / > CALL XYZELL ( A B XSTAT XSTELL ) <p / > PURPOSE : COMPUTATION OF ELLIPSOIDAL COORDINATES XSTELL GIVEN THE CARTESIAN COORDINATES XSTAT <p / > PARAMETERS : IN : A : SEMI - MAJOR AXIS OF THE REFERENCE R * 8 ELLIPSOID IN METERS B : SEMI - MINOR AXIS OF THE REFERENCE R * 8 ELLIPSOID IN METERS DXELL ( 3 ) : TRANSLATION COMPONENTS FROM THE R * 8 ORIGIN OF THE CART . COORD . SYSTEM ( X Y Z ) TO THE CENTER OF THE REF . ELLIPSOID ( IN METRES ) SCELL : SCALE FACTOR BETWEEN REF . ELLIPSOID R * 8 AND WGS - 84 XSTAT ( 3 ) : CARTESIAN COORDINATES ( M ) R * 8 OUT : XSTELL ( 3 ) : ELLIPSOIDAL COORDINATES R * 8 XSTELL ( 1 ) : ELL . LATITUDE ( RADIAN ) XSTELL ( 2 ) : ELL . LONGITUDE ( RADIAN ) XSTELL ( 3 ) : ELL . HEIGHT ( M ) <p / > SR CALLED : DMLMTV <p / > REMARKS : --- <p / > AUTHOR : M . ROTHACHER <p / > VERSION : 3 . 4 ( JAN 93 ) <p / > CREATED : 87 / 11 / 03 12 : 32 LAST MODIFIED : 88 / 11 / 21 17 : 36 <p / > COPYRIGHT : ASTRONOMICAL INSTITUTE 1987 UNIVERSITY OF BERNE SWITZERLAND [CODESPLIT] public double [ ] xyzell ( double a , double b , double [ ] xstat ) { double [ ] xstell = new double [ 3 ] ; double e2 , s , rlam , zps , h , phi , n , hp , phip ; int i , niter ; e2 = ( a * a - b * b ) / ( a * a ) ; s = Math . sqrt ( xstat [ 0 ] * xstat [ 0 ] + xstat [ 1 ] * xstat [ 1 ] ) ; rlam = Math . atan2 ( xstat [ 1 ] , xstat [ 0 ] ) ; zps = xstat [ 2 ] / s ; h = Math . sqrt ( xstat [ 0 ] * xstat [ 0 ] + xstat [ 1 ] * xstat [ 1 ] + xstat [ 2 ] * xstat [ 2 ] ) - a ; phi = Math . atan ( zps / ( 1.0 - e2 * a / ( a + h ) ) ) ; niter = 0 ; for ( i = 1 ; i <= 10000000 ; i ++ ) { n = a / Math . sqrt ( 1.0 - e2 * Math . sin ( phi ) * Math . sin ( phi ) ) ; hp = h ; phip = phi ; h = s / Math . cos ( phi ) - n ; phi = Math . atan ( zps / ( 1.0 - e2 * n / ( n + h ) ) ) ; niter = niter + 1 ; if ( ( Math . abs ( phip - phi ) <= 1.e-11 ) && ( Math . abs ( hp - h ) <= 1.e-5 ) ) { break ; } if ( niter >= 10 ) { phi = - 999.0 ; rlam = - 999.0 ; h = - 999.0 ; break ; } } xstell [ 0 ] = phi * 180 / 3.1415926 ; xstell [ 1 ] = rlam * 180 / 3.1415926 ; xstell [ 2 ] = h ; return xstell ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------- gast . f <p / > This subroutine computes the Greenwich Apparent Siderial Time angle given a UTC date and time . <p / > parameter Input parameters : Inputs : [CODESPLIT] public double gast ( int iyr , int imon , int iday , int ihr , int imin , double sec , double dsec ) { //\r //    implicit double precision (a-h,o-z)\r //    character(len=*), parameter :: header = '$URL: svn://ursa.cosmic.ucar.edu/trunk/src/roam/gast.f $ $Id: gast.f 10129 2008-07-30 17:10:52Z dhunt $'\r //\r // Coordinate transform from the celestial inertial reference frame to the geo-\r // centered Greenwich reference frame.\r // Call a subroutine to calculate the Julian day \"djd\":\r double djd = juday ( imon , iday , iyr ) ; //djd=julean day.\r double tu = ( djd - 2451545.0 ) / 36525.0 ; double gmst = 24110.548410 + 8640184.8128660 * tu + 0.093104 * tu * tu - 6.2E-6 * Math . pow ( tu , 3 ) ; //       !gmst=Greenwich mean...\r double utco = ( ihr * 3600 ) + ( imin * 60 ) + sec ; return togreenw ( dsec , utco , gmst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JDAY calculates the Julian Day number ( JD ) from the Gregorian month day and year ( M D Y ) . ( NOT VALID BEFORE 10 / 15 / 1582 ) [CODESPLIT] public double juday ( int M , int D , int Y ) { double JD ; double IY = Y - ( 12 - M ) / 10 ; double IM = M + 1 + 12 * ( ( 12 - M ) / 10 ) ; double I = IY / 100 ; double J = 2 - I + I / 4 + Math . round ( 365.25 * IY ) + Math . round ( 30.6001 * IM ) ; JD = ( J + D + 1720994.50 ) ; return JD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine is to transform the locations and velocities of the GPS and LEO satellites from the celestial inertial reference frame to the Earth centered Greenwich reference frame . The dummy arguments iyear month and iday are the calender year month and day of the occultation event . The dummy arguments ihour minute and sec are the UTC time . Reference : Astronomical Alamanus 1993 <p / > Modified subroutine from Dasheng s code . [CODESPLIT] public double togreenw ( double rectt , double utco , double gmst ) { double pi = Math . acos ( - 1.00 ) ; //\r // For each occultation ID, its TU and GMST are the same.  However, every\r // occultation event takes place at gmst+uts, uts is progressively increasing\r // with every occultation event.\r double utc = ( utco + rectt ) * 1.0027379093 ; gmst = gmst + utc ; //in seconds, without eoe correction.\r //  gmst may be a positive number or may be a negative number.\r while ( gmst < 0.0 ) { gmst = gmst + 86400.00 ; } while ( gmst > 86400.00 ) { gmst = gmst - 86400.00 ; } // gmst = the Greenwich mean sidereal time.\r // This gmst is without the corrections from the equation of equinoxes.  For\r // GPS/MET applications, the corrections from equation of equinoxes is not\r // necessary because of the accurary needed.\r return gmst * 2.0 * pi / 86400.0 ; //!*** This is the THETA in radian.\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------- file spin . f <p / > This subroutine rotates vector V1 around vector VS at angle A . V2 is the vector after the rotation . <p / > <p / > parameter Input parameters : v1 - Vector to be rotated vs - Vector around which to rotate v1 a - angle of rotation Output parameters : v2 - output vector <p / > S . V . Sokolovskiy URL : svn : // ursa . cosmic . ucar . edu / trunk / src / roam / spin . f $ $Id : spin . f 10129 2008 - 07 - 30 17 : 10 : 52Z dhunt $ ----------------------------------------------------------------------- [CODESPLIT] public double [ ] spin ( double [ ] v1 , double [ ] vs , double a ) { //     implicit real*8(a-h,o-z)\r //     dimension v1(3),vs(3),vsn(3),v2(3),v3(3),s(3,3)\r //     Calculation of the unit vector around which\r //     the rotation should be done.\r double [ ] v2 = new double [ 3 ] ; double [ ] vsn = new double [ 3 ] ; double [ ] v3 = new double [ 3 ] ; double vsabs = Math . sqrt ( vs [ 0 ] * vs [ 0 ] + vs [ 1 ] * vs [ 1 ] + vs [ 2 ] * vs [ 2 ] ) ; for ( int i = 0 ; i < 3 ; i ++ ) { vsn [ i ] = vs [ i ] / vsabs ; } // Calculation of the rotation matrix.\r double a1 = Math . cos ( a ) ; double a2 = 1.0 - a1 ; double a3 = Math . sin ( a ) ; double [ ] [ ] s = new double [ 3 ] [ 3 ] ; s [ 0 ] [ 0 ] = a2 * vsn [ 0 ] * vsn [ 0 ] + a1 ; s [ 0 ] [ 1 ] = a2 * vsn [ 0 ] * vsn [ 1 ] - a3 * vsn [ 2 ] ; s [ 0 ] [ 2 ] = a2 * vsn [ 0 ] * vsn [ 2 ] + a3 * vsn [ 1 ] ; s [ 1 ] [ 0 ] = a2 * vsn [ 1 ] * vsn [ 0 ] + a3 * vsn [ 2 ] ; s [ 1 ] [ 1 ] = a2 * vsn [ 1 ] * vsn [ 1 ] + a1 ; s [ 1 ] [ 2 ] = a2 * vsn [ 1 ] * vsn [ 2 ] - a3 * vsn [ 0 ] ; s [ 2 ] [ 0 ] = a2 * vsn [ 2 ] * vsn [ 0 ] - a3 * vsn [ 1 ] ; s [ 2 ] [ 1 ] = a2 * vsn [ 2 ] * vsn [ 1 ] + a3 * vsn [ 0 ] ; s [ 2 ] [ 2 ] = a2 * vsn [ 2 ] * vsn [ 2 ] + a1 ; // Calculation of the rotated vector.\r for ( int i = 0 ; i < 3 ; i ++ ) { v3 [ i ] = s [ i ] [ 0 ] * v1 [ 0 ] + s [ i ] [ 1 ] * v1 [ 1 ] + s [ i ] [ 2 ] * v1 [ 2 ] ; } System . arraycopy ( v3 , 0 , v2 , 0 , 3 ) ; return v2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] public double [ ] execute ( double [ ] eci , double julian ) { double Xi = eci [ 0 ] ; double Yi = eci [ 1 ] ; double Zi = eci [ 2 ] ; double c , s ; double GHA ; double [ ] ecef = new double [ 3 ] ; //Compute GHAD\r /* System generated locals */ double d__1 , d__2 , d__3 ; /* Local variables */ double tsec , tday , gmst , t , omega , tfrac , tu , dat ; /*     INPUT IS TIME \"secondsSince1970\" IN SECONDS AND \"TDAY\" */ /*     WHICH IS WHOLE DAYS FROM 1970 JAN 1 0H */ /*     THE OUTPUT IS GREENWICH HOUR ANGLE IN DEGREES */ /*     XOMEGA IS ROTATION RATE IN DEGREES/SEC */ /*     FOR COMPATABILITY */ tday = ( double ) ( ( int ) ( julian / 86400. ) ) ; tsec = julian - tday * 86400 ; /*     THE NUMBER OF DAYS FROM THE J2000 EPOCH */ /*     TO 1970 JAN 1 0H UT1 IS -10957.5 */ t = tday - ( float ) 10957.5 ; tfrac = tsec / 86400. ; dat = t ; tu = dat / 36525. ; /* Computing 2nd power */ d__1 = tu ; /* Computing 3rd power */ d__2 = tu ; d__3 = d__2 ; gmst = tu * 8640184.812866 + 24110.54841 + d__1 * d__1 * .093104 - d__3 * ( d__2 * d__2 ) * 6.2e-6 ; /*     COMPUTE THE EARTH'S ROTATION RATE */ /* Computing 2nd power */ d__1 = tu ; omega = tu * 5.098097e-6 + 86636.55536790872 - d__1 * d__1 * 5.09e-10 ; /*     COMPUTE THE GMST AND GHA */ //  da is earth nutation - currently unused\r double da = 0.0 ; gmst = gmst + omega * tfrac + da * RTD * 86400. / 360. ; gmst = gmst % 86400 ; if ( gmst < 0. ) { gmst += 86400. ; } gmst = gmst / 86400. * 360. ; //ghan = gmst;\r //  returns gha in radians\r gmst = gmst * DTR ; GHA = gmst ; //RotateZ\r c = Math . cos ( GHA ) ; s = Math . sin ( GHA ) ; double X = c * Xi + s * Yi ; double Y = - s * Xi + c * Yi ; //Set outputs\r ecef [ 0 ] = X ; ecef [ 1 ] = Y ; ecef [ 2 ] = Zi ; return ecef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "comparing api to others [CODESPLIT] public static double [ ] ECFtoLLA ( double x , double y , double z , double a , double b ) { double longitude = Math . atan2 ( y , x ) ; double ePrimeSquared = ( a * a - b * b ) / ( b * b ) ; double p = Math . sqrt ( x * x + y * y ) ; double theta = Math . atan ( ( z * a ) / ( p * b ) ) ; double sineTheta = Math . sin ( theta ) ; double cosTheta = Math . cos ( theta ) ; double f = 1 / 298.257223563 ; double e2 = 2 * f - f * f ; double top = z + ePrimeSquared * b * sineTheta * sineTheta * sineTheta ; double bottom = p - e2 * a * cosTheta * cosTheta * cosTheta ; double geodeticLat = Math . atan ( top / bottom ) ; double sineLat = Math . sin ( geodeticLat ) ; double N = a / Math . sqrt ( 1 - e2 * sineLat * sineLat ) ; double altitude = ( p / Math . cos ( geodeticLat ) ) - N ; // maintain longitude btw -PI and PI\r if ( longitude > Math . PI ) { longitude -= 2 * Math . PI ; } else if ( longitude < - Math . PI ) { longitude += 2 * Math . PI ; } return new double [ ] { geodeticLat , longitude , altitude } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read in lat / lon points one time for this class [CODESPLIT] private static boolean readWorldMap ( ) { java . io . DataInputStream dis ; String filename = \"/resources/nj22/ui/maps/cil_100km.mapr\" ; java . io . InputStream is = null ; long secs = System . currentTimeMillis ( ) ; is = Resource . getFileResource ( filename ) ; if ( is == null ) { System . err . println ( \"WorldMap read failed on resource \" + filename ) ; return false ; } else { dis = new java . io . DataInputStream ( is ) ; } // need an AbstractGisFeature for visad worldMapFeature = new WorldMapFeature ( ) ; // need an ArrayList of AbstractGisFeature's for GisFeatureRenderer gisList = new ArrayList ( ) ; gisList . add ( worldMapFeature ) ; partList = new ArrayList ( ) ; while ( true ) { try { int npts = dis . readInt ( ) ; dis . readInt ( ) ; // minx -- not used. dis . readInt ( ) ; // maxx -- not used. dis . readInt ( ) ; // miny -- not used. dis . readInt ( ) ; // maxy -- not used. MapRun run = new MapRun ( npts ) ; for ( int i = 0 ; i < npts ; i ++ ) { run . wx [ i ] = ( ( double ) dis . readInt ( ) ) / SECS_PER_DEG ; run . wy [ i ] = ( ( double ) dis . readInt ( ) ) / SECS_PER_DEG ; } partList . add ( run ) ; total_pts += npts ; } catch ( EOFException ex ) { break ; } catch ( Exception ex ) { System . err . println ( \"WorldMap exception \" + ex ) ; break ; } } try { is . close ( ) ; } catch ( Exception ex ) { } if ( debugTime ) { secs = System . currentTimeMillis ( ) - secs ; System . out . println ( \"WorldMap read file: \" + secs * .001 + \" seconds\" ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean up strings to be used for unit string [CODESPLIT] public static String cleanUnit ( String unit ) { if ( unit == null ) return null ; // These specific words become dimensionless\r if ( unit . equalsIgnoreCase ( \"Proportion\" ) || unit . equalsIgnoreCase ( \"Numeric\" ) ) unit = \"\" ; // So does '-'\r else if ( unit . equalsIgnoreCase ( \"-\" ) ) { unit = \"\" ; // Make sure degree(s) true gets concatenated with '_'\r } else if ( unit . startsWith ( \"degree\" ) && unit . endsWith ( \"true\" ) ) { unit = unit . replace ( ' ' , ' ' ) ; // And only do the rest of the conversion if it's not a \"* table *\" entry\r } else if ( ! unit . contains ( \" table \" ) ) { if ( unit . startsWith ( \"/\" ) ) unit = \"1\" + unit ; unit = unit . trim ( ) ; unit = StringUtil2 . remove ( unit , \"**\" ) ; StringBuilder sb = new StringBuilder ( unit ) ; StringUtil2 . remove ( sb , \"^[]\" ) ; StringUtil2 . replace ( sb , ' ' , \".\" ) ; StringUtil2 . replace ( sb , ' ' , \".\" ) ; unit = sb . toString ( ) ; } return unit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean up strings to be used in Netcdf Object names [CODESPLIT] public static String cleanName ( String name ) { if ( name == null ) return null ; int pos = name . indexOf ( \"(see\" ) ; if ( pos < 0 ) pos = name . indexOf ( \"(See\" ) ; if ( pos > 0 ) name = name . substring ( 0 , pos ) ; name = StringUtil2 . replace ( name , ' ' , \"-\" ) ; StringBuilder sb = new StringBuilder ( name ) ; StringUtil2 . replace ( sb , ' ' , \"plus\" ) ; StringUtil2 . remove ( sb , \".;,=[]()/*\\\"\" ) ; return StringUtil2 . collapseWhitespace ( sb . toString ( ) . trim ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare two names from tables trying to ignore superfulous characters . [CODESPLIT] public static boolean equivilantName ( String name1 , String name2 ) { if ( name1 == null || name2 == null ) return ( name1 == name2 ) ; String name1clean = cleanName ( name1 ) . toLowerCase ( ) ; String name2clean = cleanName ( name2 ) . toLowerCase ( ) ; if ( name1 . equals ( name2 ) ) return true ; StringBuilder sb1 = new StringBuilder ( name1clean ) ; StringUtil2 . remove ( sb1 , \" -’'\"); \r  StringBuilder sb2 = new StringBuilder ( name2clean ) ; StringUtil2 . remove ( sb2 , \" -’'\"); \r  return sb1 . toString ( ) . equals ( sb2 . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given unit is unitless . [CODESPLIT] public static boolean isUnitless ( String unit ) { if ( unit == null ) return true ; String munge = unit . toLowerCase ( ) . trim ( ) ; munge = StringUtil2 . remove ( munge , ' ' ) ; return munge . length ( ) == 0 || munge . startsWith ( \"numeric\" ) || munge . startsWith ( \"non-dim\" ) || munge . startsWith ( \"see\" ) || munge . startsWith ( \"proportion\" ) || munge . startsWith ( \"code\" ) || munge . startsWith ( \"0=\" ) || munge . equals ( \"1\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a URL ready to use in a generated HTML page from a URL that is either absolute or relative to the webapp context path . That is if relative it is relative to http : // server : port / thredds / . <p / > <p > For simplicity all relative URLs are converted to URLs that are absolute paths . For instance catalog . xml becomes / thredds / catalog . xml . [CODESPLIT] public String prepareUrlStringForHtml ( String url ) { if ( url == null ) return null ; URI uri ; try { uri = new URI ( url ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( \"Given a bad URL [\" + url + \"].\" , e ) ; } if ( uri . isAbsolute ( ) ) return uri . toString ( ) ; if ( url . startsWith ( \"/\" ) ) return url ; return this . getWebappContextPath ( ) + \"/\" + url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "input is xml file with just the <featureCollection > [CODESPLIT] static public FeatureCollectionConfig getConfigFromSnippet ( String filename ) { org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( filename ) ; } catch ( Exception e ) { System . out . printf ( \"Error parsing featureCollection %s err = %s\" , filename , e . getMessage ( ) ) ; return null ; } return FeatureCollectionReader . readFeatureCollection ( doc . getRootElement ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert this GisFeature to a java . awt . Shape using the default coordinate system mapping gisFeature ( x y ) - > screen ( x y ) . LOOK STILL HAVE TO crossSeam () [CODESPLIT] public Shape getShape ( ) { int npts = getNumPoints ( ) ; GeneralPath path = new GeneralPath ( GeneralPath . WIND_EVEN_ODD , npts ) ; java . util . Iterator pi = getGisParts ( ) ; while ( pi . hasNext ( ) ) { GisPart gp = ( GisPart ) pi . next ( ) ; double [ ] xx = gp . getX ( ) ; double [ ] yy = gp . getY ( ) ; int np = gp . getNumPoints ( ) ; if ( np > 0 ) path . moveTo ( ( float ) xx [ 0 ] , ( float ) yy [ 0 ] ) ; for ( int i = 1 ; i < np ; i ++ ) { path . lineTo ( ( float ) xx [ i ] , ( float ) yy [ i ] ) ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert this GisFeature to a java . awt . Shape . The data coordinate system is assumed to be ( lat lon ) use the projection to transform points so project . latLonToProj ( gisFeature ( x y )) - > screen ( x y ) . [CODESPLIT] public Shape getProjectedShape ( ProjectionImpl displayProject ) { LatLonPointImpl workL = new LatLonPointImpl ( ) ; ProjectionPointImpl lastW = new ProjectionPointImpl ( ) ; GeneralPath path = new GeneralPath ( GeneralPath . WIND_EVEN_ODD , getNumPoints ( ) ) ; boolean showPts = ucar . util . prefs . ui . Debug . isSet ( \"projection/showPoints\" ) ; java . util . Iterator pi = getGisParts ( ) ; while ( pi . hasNext ( ) ) { GisPart gp = ( GisPart ) pi . next ( ) ; double [ ] xx = gp . getX ( ) ; double [ ] yy = gp . getY ( ) ; boolean skipPrev = false ; int count = 0 ; for ( int i = 0 ; i < gp . getNumPoints ( ) ; i ++ ) { workL . set ( yy [ i ] , xx [ i ] ) ; ProjectionPoint pt = displayProject . latLonToProj ( workL ) ; if ( showPts ) { System . out . println ( \"AbstractGisFeature getProjectedShape 1 \" + xx [ i ] + \" \" + yy [ i ] + \" === \" + pt . getX ( ) + \" \" + pt . getY ( ) ) ; if ( displayProject . crossSeam ( pt , lastW ) ) System . out . println ( \"***cross seam\" ) ; } // deal with possible NaNs if ( Double . isNaN ( pt . getX ( ) ) || Double . isNaN ( pt . getY ( ) ) ) { skipPrev = true ; continue ; } if ( ( count == 0 ) || skipPrev || displayProject . crossSeam ( pt , lastW ) ) path . moveTo ( ( float ) pt . getX ( ) , ( float ) pt . getY ( ) ) ; else path . lineTo ( ( float ) pt . getX ( ) , ( float ) pt . getY ( ) ) ; count ++ ; skipPrev = false ; lastW . setLocation ( pt ) ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert this GisFeature to a java . awt . Shape . The data coordinate system is in the coordinates of dataProject and the screen is in the coordinates of displayProject . So : displayProject . latLonToProj ( dataProject . projToLatLon ( gisFeature ( x y ))) - > screen ( x y ) . [CODESPLIT] public Shape getProjectedShape ( ProjectionImpl dataProject , ProjectionImpl displayProject ) { ProjectionPointImpl pt1 = new ProjectionPointImpl ( ) ; ProjectionPointImpl lastW = new ProjectionPointImpl ( ) ; GeneralPath path = new GeneralPath ( GeneralPath . WIND_EVEN_ODD , getNumPoints ( ) ) ; boolean showPts = ucar . util . prefs . ui . Debug . isSet ( \"projection/showPoints\" ) ; java . util . Iterator pi = getGisParts ( ) ; while ( pi . hasNext ( ) ) { GisPart gp = ( GisPart ) pi . next ( ) ; double [ ] xx = gp . getX ( ) ; double [ ] yy = gp . getY ( ) ; boolean skipPrev = false ; int count = 0 ; for ( int i = 0 ; i < gp . getNumPoints ( ) ; i ++ ) { pt1 . setLocation ( xx [ i ] , yy [ i ] ) ; LatLonPoint llpt = dataProject . projToLatLon ( pt1 ) ; ProjectionPoint pt2 = displayProject . latLonToProj ( llpt ) ; if ( showPts ) { System . out . println ( \"AbstractGisFeature getProjectedShape 2 \" + xx [ i ] + \" \" + yy [ i ] + \" === \" + pt2 . getX ( ) + \" \" + pt2 . getY ( ) ) ; if ( displayProject . crossSeam ( pt2 , lastW ) ) System . out . println ( \"***cross seam\" ) ; } // deal with possible NaNs if ( Double . isNaN ( pt2 . getX ( ) ) || Double . isNaN ( pt2 . getY ( ) ) ) { skipPrev = true ; continue ; } if ( ( count == 0 ) || skipPrev || displayProject . crossSeam ( pt2 , lastW ) ) path . moveTo ( ( float ) pt2 . getX ( ) , ( float ) pt2 . getY ( ) ) ; else path . lineTo ( ( float ) pt2 . getX ( ) , ( float ) pt2 . getY ( ) ) ; count ++ ; skipPrev = false ; lastW . setLocation ( pt2 ) ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * taken from http : // www . nssl . noaa . gov / projects / mrms / operational / tables . php [CODESPLIT] private void init ( ) { add ( 209 , 2 , 0 , \"LightningDensityNLDN1min\" , \"CG Lightning Density 1-min - NLDN\" , \"flashes/km^2/min\" , - 3 , - 1 ) ; add ( 209 , 2 , 1 , \"LightningDensityNLDN5min\" , \"CG Lightning Density 5-min - NLDN\" , \"flashes/km^2/min\" , - 3 , - 1 ) ; add ( 209 , 2 , 2 , \"LightningDensityNLDN15min\" , \"CG Lightning Density 15-min - NLDN\" , \"flashes/km^2/min\" , - 3 , - 1 ) ; add ( 209 , 2 , 3 , \"LightningDensityNLDN30min\" , \"CG Lightning Density 30-min - NLDN\" , \"flashes/km^2/min\" , - 3 , - 1 ) ; add ( 209 , 2 , 4 , \"LightningProbabilityNext30min\" , \"Lightning Probability 0-30 minutes - NLDN\" , \"%\" , 0 , 0 ) ; add ( 209 , 3 , 0 , \"MergedAzShear0to2kmAGL\" , \"Azimuth Shear 0-2km AGL\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 1 , \"MergedAzShear3to6kmAGL\" , \"Azimuth Shear 3-6km AGL\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 2 , \"RotationTrack30min\" , \"Rotation Track 0-2km AGL 30-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 3 , \"RotationTrack60min\" , \"Rotation Track 0-2km AGL 60-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 4 , \"RotationTrack120min\" , \"Rotation Track 0-2km AGL 120-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 5 , \"RotationTrack240min\" , \"Rotation Track 0-2km AGL 240-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 6 , \"RotationTrack360min\" , \"Rotation Track 0-2km AGL 360-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 7 , \"RotationTrack1440min\" , \"Rotation Track 0-2km AGL 1440-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 14 , \"RotationTrackML30min\" , \"Rotation Track 0-3km AGL 30-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 15 , \"RotationTrackML60min\" , \"Rotation Track 0-3km AGL 60-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 16 , \"RotationTrackML120min\" , \"Rotation Track 0-3km AGL 120-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 17 , \"RotationTrackML240min\" , \"Rotation Track 0-3km AGL 240-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 18 , \"RotationTrackML360min\" , \"Rotation Track 0-3km AGL 360-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 19 , \"RotationTrackML1440min\" , \"Rotation Track 0-3km AGL 1440-min\" , \"0.001/s\" , 0 , 0 ) ; add ( 209 , 3 , 26 , \"SHI\" , \"Severe Hail Index\" , \"index\" , - 3 , - 1 ) ; add ( 209 , 3 , 27 , \"POSH\" , \"Prob of Severe Hail\" , \"%\" , - 3 , - 1 ) ; add ( 209 , 3 , 28 , \"MESH\" , \"Maximum Estimated Size of Hail (MESH)\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 3 , 29 , \"MESHMax30min\" , \"MESH Hail Swath 30-min\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 3 , 30 , \"MESHMax60min\" , \"MESH Hail Swath 60-min\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 3 , 31 , \"MESHMax120min\" , \"MESH Hail Swath 120-min\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 3 , 32 , \"MESHMax240min\" , \"MESH Hail Swath 240-min\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 3 , 33 , \"MESHMax360min\" , \"MESH Hail Swath 360-min\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 3 , 34 , \"MESHMax1440min\" , \"MESH Hail Swath 1440-min\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 3 , 41 , \"VIL\" , \"Vertically Integrated Liquid\" , \"kg/m^2\" , - 3 , - 1 ) ; add ( 209 , 3 , 42 , \"VILDensity\" , \"Vertically Integrated Liquid Density\" , \"g/m^3\" , - 3 , - 1 ) ; add ( 209 , 3 , 43 , \"VII\" , \"Vertically Integrated Ice\" , \"kg/m^2\" , - 3 , - 1 ) ; add ( 209 , 3 , 44 , \"EchoTop18\" , \"Echo Top - 18 dBZ MSL\" , \"km\" , - 3 , - 1 ) ; add ( 209 , 3 , 45 , \"EchoTop30\" , \"Echo Top - 30 dBZ MSL\" , \"km\" , - 3 , - 1 ) ; add ( 209 , 3 , 46 , \"EchoTop50\" , \"Echo Top - 50 dBZ MSL\" , \"km\" , - 3 , - 1 ) ; add ( 209 , 3 , 47 , \"EchoTop60\" , \"Echo Top - 60 dBZ MSL\" , \"km\" , - 3 , - 1 ) ; add ( 209 , 3 , 48 , \"H50AboveM20C\" , \"Thickness [50 dBZ top - (-20C)]\" , \"km\" , - 999 , - 99 ) ; add ( 209 , 3 , 49 , \"H50Above0C\" , \"Thickness [50 dBZ top - 0C]\" , \"km\" , - 999 , - 99 ) ; add ( 209 , 3 , 50 , \"H60AboveM20C\" , \"Thickness [60 dBZ top - (-20C)]\" , \"km\" , - 999 , - 99 ) ; add ( 209 , 3 , 51 , \"H60Above0C\" , \"Thickness [60 dBZ top - 0C]\" , \"km\" , - 999 , - 99 ) ; add ( 209 , 3 , 52 , \"Reflectivity0C\" , \"Isothermal Reflectivity at 0C\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 3 , 53 , \"ReflectivityM5C\" , \"Isothermal Reflectivity at -5C\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 3 , 54 , \"ReflectivityM10C\" , \"Isothermal Reflectivity at -10C\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 3 , 55 , \"ReflectivityM15C\" , \"Isothermal Reflectivity at -15C\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 3 , 56 , \"ReflectivityM20C\" , \"Isothermal Reflectivity at -20C\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 3 , 57 , \"ReflectivityAtLowestAltitude\" , \"ReflectivityAtLowestAltitude\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 3 , 58 , \"MergedReflectivityAtLowestAltitude\" , \"Non Quality Controlled Reflectivity At Lowest Altitude\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 4 , 0 , \"IRband4\" , \"Infrared (E/W blend)\" , \"K\" , - 999 , - 99 ) ; add ( 209 , 4 , 1 , \"Visible\" , \"Visible (E/W blend)\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 4 , 2 , \"WaterVapor\" , \"Water Vapor (E/W blend)\" , \"K\" , - 999 , - 99 ) ; add ( 209 , 4 , 3 , \"CloudCover\" , \"Cloud Cover\" , \"K\" , - 999 , - 99 ) ; add ( 209 , 6 , 0 , \"PrecipFlag\" , \"Surface Precipitation Type (Convective, Stratiform, Tropical, Hail, Snow)\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 6 , 1 , \"PrecipRate\" , \"Radar Precipitation Rate\" , \"mm/hr\" , - 3 , - 1 ) ; add ( 209 , 6 , 2 , \"RadarOnlyQPE01H\" , \"Radar precipitation accumulation 1-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 3 , \"RadarOnlyQPE03H\" , \"Radar precipitation accumulation 3-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 4 , \"RadarOnlyQPE06H\" , \"Radar precipitation accumulation 6-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 5 , \"RadarOnlyQPE12H\" , \"Radar precipitation accumulation 12-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 6 , \"RadarOnlyQPE24H\" , \"Radar precipitation accumulation 24-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 7 , \"RadarOnlyQPE48H\" , \"Radar precipitation accumulation 48-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 8 , \"RadarOnlyQPE72H\" , \"Radar precipitation accumulation 72-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 9 , \"GaugeCorrQPE01H\" , \"Local gauge bias corrected radar precipitation accumulation 1-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 10 , \"GaugeCorrQPE03H\" , \"Local gauge bias corrected radar precipitation accumulation 3-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 11 , \"GaugeCorrQPE06H\" , \"Local gauge bias corrected radar precipitation accumulation 6-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 12 , \"GaugeCorrQPE12H\" , \"Local gauge bias corrected radar precipitation accumulation 12-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 13 , \"GaugeCorrQPE24H\" , \"Local gauge bias corrected radar precipitation accumulation 24-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 14 , \"GaugeCorrQPE48H\" , \"Local gauge bias corrected radar precipitation accumulation 48-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 15 , \"GaugeCorrQPE72H\" , \"Local gauge bias corrected radar precipitation accumulation 72-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 16 , \"GaugeOnlyQPE01H\" , \"Gauge only precipitation accumulation 1-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 17 , \"GaugeOnlyQPE03H\" , \"Gauge only precipitation accumulation 3-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 18 , \"GaugeOnlyQPE06H\" , \"Gauge only precipitation accumulation 6-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 19 , \"GaugeOnlyQPE12H\" , \"Gauge only precipitation accumulation 12-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 20 , \"GaugeOnlyQPE24H\" , \"Gauge only precipitation accumulation 24-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 21 , \"GaugeOnlyQPE48H\" , \"Gauge only precipitation accumulation 48-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 22 , \"GaugeOnlyQPE72H\" , \"Gauge only precipitation accumulation 72-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 23 , \"MountainMapperQPE01H\" , \"Mountain Mapper precipitation accumulation 1-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 24 , \"MountainMapperQPE03H\" , \"Mountain Mapper precipitation accumulation 3-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 25 , \"MountainMapperQPE06H\" , \"Mountain Mapper precipitation accumulation 6-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 26 , \"MountainMapperQPE12H\" , \"Mountain Mapper precipitation accumulation 12-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 27 , \"MountainMapperQPE24H\" , \"Mountain Mapper precipitation accumulation 24-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 28 , \"MountainMapperQPE48H\" , \"Mountain Mapper precipitation accumulation 48-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 6 , 29 , \"MountainMapperQPE72H\" , \"Mountain Mapper precipitation accumulation 72-hour\" , \"mm\" , - 3 , - 1 ) ; add ( 209 , 7 , 0 , \"ModelSurfaceTemp\" , \"Model Surface temperature [RAP 13km]\" , \"C\" , - 999 , - 99 ) ; add ( 209 , 7 , 1 , \"ModelWetBulbTemp\" , \"Model Surface wet bulb temperature [RAP 13km]\" , \"C\" , - 999 , - 99 ) ; add ( 209 , 7 , 2 , \"WarmRainProbability\" , \"Probability of warm rain [RAP 13km derived]\" , \"%\" , - 3 , - 1 ) ; add ( 209 , 7 , 3 , \"ModelHeight0C\" , \"Model Freezing Level Height [RAP 13km] MSL\" , \"m\" , - 3 , - 1 ) ; add ( 209 , 7 , 4 , \"BrightBandTopHeight\" , \"Brightband Top Radar [RAP 13km derived] AGL\" , \"m\" , - 3 , - 1 ) ; add ( 209 , 7 , 5 , \"BrightBandBottomHeight\" , \"Brightband Bottom Radar [RAP 13km derived] AGL\" , \"m\" , - 3 , - 1 ) ; add ( 209 , 8 , 0 , \"RadarQualityIndex\" , \"Radar Quality Index\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 1 , \"GaugeInflIndex01H\" , \"Gauge Influence Index for 1-hour QPE\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 2 , \"GaugeInflIndex03H\" , \"Gauge Influence Index for 3-hour QPE\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 3 , \"GaugeInflIndex06H\" , \"Gauge Influence Index for 6-hour QPE\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 4 , \"GaugeInflIndex12H\" , \"Gauge Influence Index for 12-hour QPE\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 5 , \"GaugeInflIndex24H\" , \"Gauge Influence Index for 24-hour QPE\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 6 , \"GaugeInflIndex48H\" , \"Gauge Influence Index for 48-hour QPE\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 7 , \"GaugeInflIndex72H\" , \"Gauge Influence Index for 72-hour QPE\" , \"dimensionless\" , - 3 , - 1 ) ; add ( 209 , 8 , 8 , \"SeamlessHSR\" , \"Seamless Hybrid Scan Reflectivity with VPR correction\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 8 , 9 , \"SeamlessHSRHeight\" , \"Height of Seamless Hybrid Scan Reflectivity AGL\" , \"km\" , - 3 , - 1 ) ; add ( 209 , 9 , 0 , \"ConusMergedReflectivityQC\" , \"WSR-88D 3D Reflectivity Mosaic - 33 CAPPIS (500-19000m)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 9 , 1 , \"ConusPlusMergedReflectivityQC\" , \"All Radar 3D Reflectivity Mosaic - 33 CAPPIS (500-19000m)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 10 , 0 , \"MergedReflectivityQCComposite\" , \"Composite Reflectivity Mosaic (optimal method)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 10 , 1 , \"HeightCompositeReflectivity\" , \"Height of Composite Reflectivity Mosaic (optimal method) MSL\" , \"m\" , - 3 , - 1 ) ; add ( 209 , 10 , 2 , \"LowLevelCompositeReflectivity\" , \"Low-Level Composite Reflectivity Mosaic (0-4km)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 10 , 3 , \"HeightLowLevelCompositeReflectivity\" , \"Height of Low-Level Composite Reflectivity Mosaic (0-4km) MSL\" , \"m\" , - 3 , - 1 ) ; add ( 209 , 10 , 4 , \"LayerCompositeReflectivity_Low\" , \"Layer Composite Reflectivity Mosaic 0-24kft (low altitude)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 10 , 5 , \"LayerCompositeReflectivity_High\" , \"Layer Composite Reflectivity Mosaic 24-60 kft (highest altitude)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 10 , 6 , \"LayerCompositeReflectivity_Super\" , \"Layer Composite Reflectivity Mosaic 33-60 kft (super high altitude)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 10 , 7 , \"ReflectivityCompositeHourlyMax\" , \"Composite Reflectivity Hourly Maximum\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 10 , 8 , \"ReflectivityMaxAboveM10C\" , \"Maximum Reflectivity at -10 deg C height and above\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 11 , 0 , \"MergedBaseReflectivityQC\" , \"Mosaic Base Reflectivity (optimal method)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 11 , 1 , \"MergedReflectivityComposite\" , \"UnQc'd Composite Reflectivity Mosaic (max ref)\" , \"dBZ\" , - 999 , - 99 ) ; add ( 209 , 11 , 2 , \"MergedReflectivityQComposite\" , \"Composite Reflectivity Mosaic (max ref)\" , \"dBZ\" , - 999 , - 99 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use a factory so we can debug constructor calls [CODESPLIT] static Notes factory ( NoteSort ns , int g , int id , Nc4DSP dsp ) { Notes note = null ; switch ( ns ) { case TYPE : note = new TypeNotes ( g , id , dsp ) ; break ; case VAR : note = new VarNotes ( g , id , dsp ) ; break ; case DIM : note = new DimNotes ( g , id , dsp ) ; break ; case GROUP : note = new GroupNotes ( g , id , dsp ) ; break ; } return note ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manage the compound id for variables [CODESPLIT] static public long getVarId ( VarNotes note ) { return getVarId ( note . gid , note . id , note . getFieldIndex ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the DDS creating a tree of DodsV objects . The root node is only a container ie it has no BaseType . The Darray object ( which has the dimension info ) becomes a field of the DodsV rather than being in the tree . [CODESPLIT] static DodsV parseDDS ( DDS dds ) { DodsV root = new DodsV ( null , null ) ; // recursively get the Variables from the DDS\r Enumeration variables = dds . getVariables ( ) ; parseVariables ( root , variables ) ; // assign depth first sequence number\r root . assignSequence ( root ) ; return root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively build the dodsV tree . 1 ) put all Variables into a DodsV 2 ) unravel DConstructors ( DSequence DStructure DGrid ) 3 ) for Darray we put Variable = elemType and store the darray seperately not in the heirarchy . [CODESPLIT] static private void parseVariables ( DodsV parent , Enumeration children ) { while ( children . hasMoreElements ( ) ) { opendap . dap . BaseType bt = ( opendap . dap . BaseType ) children . nextElement ( ) ; if ( bt instanceof DList ) { String mess = \"Variables of type \" + bt . getClass ( ) . getName ( ) + \" are not supported.\" ; logger . warn ( mess ) ; continue ; } DodsV dodsV = new DodsV ( parent , bt ) ; if ( bt instanceof DConstructor ) { DConstructor dcon = ( DConstructor ) bt ; java . util . Enumeration enumerate2 = dcon . getVariables ( ) ; parseVariables ( dodsV , enumerate2 ) ; } else if ( bt instanceof DArray ) { DArray da = ( DArray ) bt ; // Check to see if the array has any zero-length dimension; if so then ignore\r for ( Enumeration e = da . getDimensions ( ) ; e . hasMoreElements ( ) ; ) { DArrayDimension dim = ( DArrayDimension ) e . nextElement ( ) ; if ( dim . getSize ( ) <= 0 ) return ; } BaseType elemType = da . getPrimitiveVector ( ) . getTemplate ( ) ; dodsV . bt = elemType ; dodsV . darray = da ; if ( ( elemType instanceof DGrid ) || ( elemType instanceof DSequence ) || ( elemType instanceof DList ) ) { String mess = \"Arrays of type \" + elemType . getClass ( ) . getName ( ) + \" are not supported.\" ; logger . warn ( mess ) ; continue ; } if ( elemType instanceof DStructure ) { // note that for DataDDS, cant traverse this further to find the data.\r DConstructor dcon = ( DConstructor ) elemType ; java . util . Enumeration nestedVariables = dcon . getVariables ( ) ; parseVariables ( dodsV , nestedVariables ) ; } } parent . children . add ( dodsV ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the DDS creating a tree of DodsV objects . The root node is only a container ie it has no BaseType . The Darray object ( which has the dimension info ) becomes a field of the DodsV rather than being in the tree . [CODESPLIT] static DodsV parseDataDDS ( DataDDS dds ) throws NoSuchVariableException { DodsV root = new DodsV ( null , null ) ; // recursively get the Variables from the DDS\r Enumeration variables = dds . getVariables ( ) ; parseDataVariables ( root , variables ) ; // assign depth first sequence number\r root . assignSequence ( root ) ; return root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively build the dodsV tree . 1 ) put all Variables into a DodsV 2 ) unravel DConstructors ( DSequence DStructure DGrid ) 3 ) for Darray we put Variable = elemType and store the darray seperately not in the heirarchy . [CODESPLIT] static private void parseDataVariables ( DodsV parent , Enumeration children ) throws NoSuchVariableException { while ( children . hasMoreElements ( ) ) { opendap . dap . BaseType bt = ( opendap . dap . BaseType ) children . nextElement ( ) ; DodsV dodsV = new DodsV ( parent , bt ) ; parent . children . add ( dodsV ) ; if ( bt instanceof DGrid ) { DGrid dgrid = ( DGrid ) bt ; if ( dodsV . parent . bt == null ) { // is top level\r // top level grids are replaced by their \"data array\"\r dodsV . darray = ( DArray ) dgrid . getVar ( 0 ) ; processDArray ( dodsV ) ; } else { // nested grids are made into Structures\r dodsV . makeAllDimensions ( ) ; } java . util . Enumeration enumerate2 = dgrid . getVariables ( ) ; parseDataVariables ( dodsV , enumerate2 ) ; } else if ( bt instanceof DSequence ) { DSequence dseq = ( DSequence ) bt ; int seqlen = dseq . getRowCount ( ) ; if ( seqlen > 0 ) { DArrayDimension ddim = new DArrayDimension ( seqlen , null ) ; dodsV . dimensions . add ( ddim ) ; } dodsV . makeAllDimensions ( ) ; java . util . Enumeration enumerate2 = dseq . getVariables ( ) ; parseDataVariables ( dodsV , enumerate2 ) ; } else if ( bt instanceof DConstructor ) { DStructure dcon = ( DStructure ) bt ; // LOOK DConstructor != DStructure?\r dodsV . makeAllDimensions ( ) ; java . util . Enumeration enumerate2 = dcon . getVariables ( ) ; parseDataVariables ( dodsV , enumerate2 ) ; } else if ( bt instanceof DArray ) { dodsV . darray = ( DArray ) bt ; processDArray ( dodsV ) ; dodsV . bt = dodsV . elemType ; if ( dodsV . elemType instanceof DStructure ) { DStructure dcon = ( DStructure ) dodsV . elemType ; java . util . Enumeration nestedVariables = dcon . getVariables ( ) ; parseDataVariables ( dodsV , nestedVariables ) ; } } else { dodsV . makeAllDimensions ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the DAS assign attribute tables to the DodsV objects . Nested attribute tables are supposed to follow the tree we construct with dodsV so its easy to assign to correct dodsV . [CODESPLIT] void parseDAS ( DAS das ) throws IOException { Enumeration tableNames = das . getNames ( ) ; while ( tableNames . hasMoreElements ( ) ) { String tableName = ( String ) tableNames . nextElement ( ) ; AttributeTable attTable = das . getAttributeTableN ( tableName ) ; if ( tableName . equals ( \"NC_GLOBAL\" ) || tableName . equals ( \"HDF_GLOBAL\" ) ) { addAttributeTable ( this , attTable , tableName , true ) ; } else if ( tableName . equals ( \"DODS_EXTRA\" ) || tableName . equals ( \"EXTRA_DIMENSION\" ) ) { // handled seperately in DODSNetcdfFile\r continue ; } else { DodsV dodsV = findDodsV ( tableName , false ) ; // short name matches the table name\r if ( dodsV != null ) { addAttributeTable ( dodsV , attTable , tableName , true ) ; } else { dodsV = findTableDotDelimited ( tableName ) ; if ( dodsV != null ) { addAttributeTable ( dodsV , attTable , tableName , true ) ; } else { if ( debugAttributes ) System . out . println ( \"DODSNetcdf getAttributes CANT find <\" + tableName + \"> add to globals\" ) ; addAttributeTable ( this , attTable , tableName , false ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the immediate children for a BaseType with given name . [CODESPLIT] DodsV findDodsV ( String name , boolean useDone ) { for ( DodsV dodsV : children ) { if ( useDone && dodsV . isDone ) continue ; // LOOK useDone ??\r if ( ( name == null ) || ( dodsV == null ) || ( dodsV . bt == null ) ) { logger . warn ( \"Corrupted structure\" ) ; continue ; } if ( name . equals ( dodsV . bt . getEncodedName ( ) ) ) return dodsV ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the DodsV object in the dataVlist corresponding to the ddsV [CODESPLIT] DodsV findDataV ( DodsV ddsV ) { if ( ddsV . parent . bt != null ) { DodsV parentV = findDataV ( ddsV . parent ) ; if ( parentV == null ) // dataDDS may not have the structure wrapper\r return findDodsV ( ddsV . bt . getEncodedName ( ) , true ) ; return parentV . findDodsV ( ddsV . bt . getEncodedName ( ) , true ) ; } DodsV dataV = findDodsV ( ddsV . bt . getEncodedName ( ) , true ) ; /* if ((dataV == null) && (ddsV.bt instanceof DGrid)) { // when asking for the Grid array\r\n      DodsV gridArray = (DodsV) ddsV.children.get(0);\r\n      return findDodsV( gridArray.bt.getName(), dataVlist, true);\r\n    } */ return dataV ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a child by index [CODESPLIT] DodsV findByIndex ( int index ) { if ( children . size ( ) <= index ) return null ; return children . get ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private static void doit ( String urlName ) throws IOException , DAP2Exception { System . out . println ( \"DODSV read =\" + urlName ) ; try ( DConnect2 dodsConnection = new DConnect2 ( urlName , true ) ) { // get the DDS\r DDS dds = dodsConnection . getDDS ( ) ; dds . print ( System . out ) ; DodsV root = DodsV . parseDDS ( dds ) ; // get the DAS\r DAS das = dodsConnection . getDAS ( ) ; das . print ( System . out ) ; root . parseDAS ( das ) ; // show the dodsV tree\r root . show ( System . out , \"\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the shape : length of Variable in each dimension . A scalar ( rank 0 ) will have an int [ 0 ] shape . [CODESPLIT] public int [ ] getShape ( ) { int [ ] result = new int [ shape . length ] ; // optimization over clone() System . arraycopy ( shape , 0 , result , 0 , shape . length ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the parent group . [CODESPLIT] public Group getParentGroup ( ) { Group g = super . getParentGroup ( ) ; if ( g == null ) { g = ncfile . getRootGroup ( ) ; super . setParentGroup ( g ) ; } assert g != null ; return g ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the ith dimension . [CODESPLIT] public Dimension getDimension ( int i ) { if ( ( i < 0 ) || ( i >= getRank ( ) ) ) return null ; return dimensions . get ( i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the index of the named Dimension in this Variable . [CODESPLIT] public int findDimensionIndex ( String name ) { for ( int i = 0 ; i < dimensions . size ( ) ; i ++ ) { Dimension d = dimensions . get ( i ) ; if ( name . equals ( d . getShortName ( ) ) ) return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Unit String for the Variable . Looks for the CDM . UNITS attribute value [CODESPLIT] public String getUnitsString ( ) { String units = null ; Attribute att = findAttribute ( CDM . UNITS ) ; if ( att == null ) att = findAttributeIgnoreCase ( CDM . UNITS ) ; if ( ( att != null ) && att . isString ( ) ) { units = att . getStringValue ( ) ; if ( units != null ) units = units . trim ( ) ; } return units ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get shape as a Section object . [CODESPLIT] public Section getShapeAsSection ( ) { if ( shapeAsSection == null ) { try { List < Range > list = new ArrayList <> ( ) ; for ( Dimension d : dimensions ) { int len = d . getLength ( ) ; if ( len > 0 ) list . add ( new Range ( d . getShortName ( ) , 0 , len - 1 ) ) ; else if ( len == 0 ) list . add ( Range . EMPTY ) ; // LOOK empty not named else { assert d . isVariableLength ( ) ; list . add ( Range . VLEN ) ; // LOOK vlen not named } } shapeAsSection = new Section ( list ) . makeImmutable ( ) ; } catch ( InvalidRangeException e ) { log . error ( \"Bad shape in variable \" + getFullName ( ) , e ) ; throw new IllegalStateException ( e . getMessage ( ) ) ; } } return shapeAsSection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Variable that is a logical subsection of this Variable . No data is read until a read method is called on it . [CODESPLIT] public Variable section ( List < Range > ranges ) throws InvalidRangeException { return section ( new Section ( ranges , shape ) . makeImmutable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Variable that is a logical subsection of this Variable . No data is read until a read method is called on it . [CODESPLIT] public Variable section ( Section subsection ) throws InvalidRangeException { subsection = Section . fill ( subsection , shape ) ; // create a copy of this variable with a proxy reader Variable sectionV = copy ( ) ; // subclasses must override sectionV . setProxyReader ( new SectionReader ( this , subsection ) ) ; sectionV . shape = subsection . getShape ( ) ; sectionV . createNewCache ( ) ; // dont share the cache sectionV . setCaching ( false ) ; // dont cache // replace dimensions if needed !! LOOK not shared sectionV . dimensions = new ArrayList <> ( ) ; for ( int i = 0 ; i < getRank ( ) ; i ++ ) { Dimension oldD = getDimension ( i ) ; Dimension newD = ( oldD . getLength ( ) == sectionV . shape [ i ] ) ? oldD : new Dimension ( oldD . getShortName ( ) , sectionV . shape [ i ] , false ) ; newD . setUnlimited ( oldD . isUnlimited ( ) ) ; sectionV . dimensions . add ( newD ) ; } sectionV . resetShape ( ) ; return sectionV ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Variable that is a logical slice of this Variable by fixing the specified dimension at the specified index value . This reduces rank by 1 . No data is read until a read method is called on it . [CODESPLIT] public Variable slice ( int dim , int value ) throws InvalidRangeException { if ( ( dim < 0 ) || ( dim >= shape . length ) ) throw new InvalidRangeException ( \"Slice dim invalid= \" + dim ) ; // ok to make slice of record dimension with length 0 boolean recordSliceOk = false ; if ( ( dim == 0 ) && ( value == 0 ) ) { Dimension d = getDimension ( 0 ) ; recordSliceOk = d . isUnlimited ( ) ; } // otherwise check slice in range if ( ! recordSliceOk ) { if ( ( value < 0 ) || ( value >= shape [ dim ] ) ) throw new InvalidRangeException ( \"Slice value invalid= \" + value + \" for dimension \" + dim ) ; } // create a copy of this variable with a proxy reader Variable sliceV = copy ( ) ; // subclasses must override Section slice = new Section ( getShapeAsSection ( ) ) ; slice . replaceRange ( dim , new Range ( value , value ) ) . makeImmutable ( ) ; sliceV . setProxyReader ( new SliceReader ( this , dim , slice ) ) ; sliceV . createNewCache ( ) ; // dont share the cache sliceV . setCaching ( false ) ; // dont cache // remove that dimension - reduce rank sliceV . dimensions . remove ( dim ) ; sliceV . resetShape ( ) ; return sliceV ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Variable that is a logical view of this Variable by eliminating the specified dimension ( s ) of length 1 . No data is read until a read method is called on it . [CODESPLIT] public Variable reduce ( List < Dimension > dims ) throws InvalidRangeException { List < Integer > dimIdx = new ArrayList <> ( dims . size ( ) ) ; for ( Dimension d : dims ) { assert dimensions . contains ( d ) ; assert d . getLength ( ) == 1 ; dimIdx . add ( dimensions . indexOf ( d ) ) ; } // create a copy of this variable with a proxy reader Variable sliceV = copy ( ) ; // subclasses must override sliceV . setProxyReader ( new ReduceReader ( this , dimIdx ) ) ; sliceV . createNewCache ( ) ; // dont share the cache sliceV . setCaching ( false ) ; // dont cache // remove dimension(s) - reduce rank for ( Dimension d : dims ) sliceV . dimensions . remove ( ) ; sliceV . resetShape ( ) ; return sliceV ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public by accident . [CODESPLIT] public void setEnumTypedef ( EnumTypedef enumTypedef ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( ! dataType . isEnum ( ) ) throw new UnsupportedOperationException ( \"Can only call Variable.setEnumTypedef() on enum types\" ) ; this . enumTypedef = enumTypedef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a section of the data for this Variable and return a memory resident Array . The Array has the same element type as the Variable and the requested shape . Note that this does not do rank reduction so the returned Array has the same rank as the Variable . Use Array . reduce () for rank reduction . <p / > <code > assert ( origin [ ii ] + shape [ ii ] * stride [ ii ] < = Variable . shape [ ii ] ) ; < / code > <p / > [CODESPLIT] public Array read ( int [ ] origin , int [ ] shape ) throws IOException , InvalidRangeException { if ( ( origin == null ) && ( shape == null ) ) return read ( ) ; if ( origin == null ) return read ( new Section ( shape ) ) ; if ( shape == null ) return read ( new Section ( origin , this . shape ) ) ; return read ( new Section ( origin , shape ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a section of the data for this Variable from the netcdf file and return a memory resident Array . [CODESPLIT] public Array read ( List < Range > ranges ) throws IOException , InvalidRangeException { if ( null == ranges ) return _read ( ) ; return read ( new Section ( ranges ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a section of the data for this Variable from the netcdf file and return a memory resident Array . The Array has the same element type as the Variable and the requested shape . Note that this does not do rank reduction so the returned Array has the same rank as the Variable . Use Array . reduce () for rank reduction . <p / > If the Variable is a member of an array of Structures this returns only the variable s data in the first Structure so that the Array shape is the same as the Variable . To read the data in all structures use ncfile . readSectionSpec () . <p / > Note this only allows you to specify a subset of this variable . If the variable is nested in a array of structures and you want to subset that use NetcdfFile . read ( String sectionSpec boolean flatten ) ; [CODESPLIT] public Array read ( ucar . ma2 . Section section ) throws java . io . IOException , ucar . ma2 . InvalidRangeException { return ( section == null ) ? _read ( ) : _read ( Section . fill ( section , shape ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value as a String for a scalar Variable . May also be one - dimensional of length 1 . May also be one - dimensional of type CHAR which wil be turned into a scalar String . [CODESPLIT] public String readScalarString ( ) throws IOException { Array data = getScalarData ( ) ; if ( dataType == DataType . STRING ) return ( String ) data . getObject ( Index . scalarIndexImmutable ) ; else if ( dataType == DataType . CHAR ) { ArrayChar dataC = ( ArrayChar ) data ; return dataC . getString ( ) ; } else throw new IllegalArgumentException ( \"readScalarString not STRING or CHAR \" + getFullName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "non - structure - member Variables . [CODESPLIT] protected Array _read ( ) throws IOException { // caching overrides the proxyReader // check if already cached if ( cache . data != null ) { if ( debugCaching ) System . out . println ( \"got data from cache \" + getFullName ( ) ) ; return cache . data . copy ( ) ; } Array data = proxyReader . reallyRead ( this , null ) ; // optionally cache it if ( isCaching ( ) ) { setCachedData ( data ) ; if ( debugCaching ) System . out . println ( \"cache \" + getFullName ( ) ) ; return cache . data . copy ( ) ; // dont let users get their nasty hands on cached data } else { return data ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public by accident do not call directly . [CODESPLIT] @ Override public Array reallyRead ( Variable client , CancelTask cancelTask ) throws IOException { if ( isMemberOfStructure ( ) ) { // LOOK should be UnsupportedOperationException ?? List < String > memList = new ArrayList <> ( ) ; memList . add ( this . getShortName ( ) ) ; Structure s = getParentStructure ( ) . select ( memList ) ; ArrayStructure as = ( ArrayStructure ) s . read ( ) ; return as . extractMemberArray ( as . findMember ( getShortName ( ) ) ) ; } try { return ncfile . readData ( this , getShapeAsSection ( ) ) ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; throw new IOException ( e . getMessage ( ) ) ; // cant happen haha } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assume filled validated Section [CODESPLIT] protected Array _read ( Section section ) throws IOException , InvalidRangeException { // check if its really a full read if ( ( null == section ) || section . computeSize ( ) == getSize ( ) ) return _read ( ) ; // full read was cached if ( isCaching ( ) ) { if ( cache . data == null ) { setCachedData ( _read ( ) ) ; // read and cache entire array if ( debugCaching ) System . out . println ( \"cache \" + getFullName ( ) ) ; } if ( debugCaching ) System . out . println ( \"got data from cache \" + getFullName ( ) ) ; return cache . data . sectionNoReduce ( section . getRanges ( ) ) . copy ( ) ; // subset it, return copy } return proxyReader . reallyRead ( this , section , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public by accident do not call directly . [CODESPLIT] @ Override public Array reallyRead ( Variable client , Section section , CancelTask cancelTask ) throws IOException , InvalidRangeException { if ( isMemberOfStructure ( ) ) { throw new UnsupportedOperationException ( \"Cannot directly read section of Member Variable=\" + getFullName ( ) ) ; } // read just this section return ncfile . readData ( this , section ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * structure - member Variable ; section has a Range for each array in the parent stuctures ( s ) and for the Variable . private Array _readMemberData ( List<Range > section boolean flatten ) throws IOException InvalidRangeException { / * Variable useVar = ( ioVar ! = null ) ? ioVar : this ; NetcdfFile useFile = ( ncfileIO ! = null ) ? ncfileIO : ncfile ; return useFile . readMemberData ( useVar section flatten ) ; } [CODESPLIT] public long readToByteChannel ( Section section , WritableByteChannel wbc ) throws IOException , InvalidRangeException { if ( ( ncfile == null ) || hasCachedData ( ) ) return IospHelper . copyToByteChannel ( read ( section ) , wbc ) ; return ncfile . readToByteChannel ( this , section , wbc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the display name plus the dimensions eg float name ( dim1 dim2 ) [CODESPLIT] public String getNameAndDimensions ( ) { Formatter buf = new Formatter ( ) ; getNameAndDimensions ( buf , true , false ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the display name plus the dimensions eg float name ( dim1 dim2 ) [CODESPLIT] public String getNameAndDimensions ( boolean strict ) { Formatter buf = new Formatter ( ) ; getNameAndDimensions ( buf , false , strict ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the display name plus the dimensions eg name ( dim1 dim2 ) [CODESPLIT] public void getNameAndDimensions ( StringBuffer buf ) { Formatter proxy = new Formatter ( ) ; getNameAndDimensions ( proxy , true , false ) ; buf . append ( proxy . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add display name plus the dimensions to the StringBuffer [CODESPLIT] public void getNameAndDimensions ( StringBuilder buf , boolean useFullName , boolean strict ) { Formatter proxy = new Formatter ( ) ; getNameAndDimensions ( proxy , useFullName , strict ) ; buf . append ( proxy . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add display name plus the dimensions to the StringBuffer [CODESPLIT] public void getNameAndDimensions ( Formatter buf , boolean useFullName , boolean strict ) { useFullName = useFullName && ! strict ; String name = useFullName ? getFullName ( ) : getShortName ( ) ; if ( strict ) name = NetcdfFile . makeValidCDLName ( getShortName ( ) ) ; buf . format ( \"%s\" , name ) ; if ( shape != null ) { if ( getRank ( ) > 0 ) buf . format ( \"(\" ) ; for ( int i = 0 ; i < dimensions . size ( ) ; i ++ ) { Dimension myd = dimensions . get ( i ) ; String dimName = myd . getShortName ( ) ; if ( ( dimName != null ) && strict ) dimName = NetcdfFile . makeValidCDLName ( dimName ) ; if ( i != 0 ) buf . format ( \", \" ) ; if ( myd . isVariableLength ( ) ) { buf . format ( \"*\" ) ; } else if ( myd . isShared ( ) ) { if ( ! strict ) buf . format ( \"%s=%d\" , dimName , myd . getLength ( ) ) ; else buf . format ( \"%s\" , dimName ) ; } else { if ( dimName != null ) { buf . format ( \"%s=\" , dimName ) ; } buf . format ( \"%d\" , myd . getLength ( ) ) ; } } if ( getRank ( ) > 0 ) buf . format ( \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CDL representation of a Variable . [CODESPLIT] public String writeCDL ( boolean useFullName , boolean strict ) { Formatter buf = new Formatter ( ) ; writeCDL ( buf , new Indent ( 2 ) , useFullName , strict ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String representation of Variable and its attributes . [CODESPLIT] public String toStringDebug ( ) { Formatter f = new Formatter ( ) ; f . format ( \"Variable %s\" , getFullName ( ) ) ; if ( ncfile != null ) { f . format ( \" in file %s\" , getDatasetLocation ( ) ) ; String extra = ncfile . toStringDebug ( this ) ; if ( extra != null ) f . format ( \" %s\" , extra ) ; } return f . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data type [CODESPLIT] public void setDataType ( DataType dataType ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; this . dataType = dataType ; this . elementSize = getDataType ( ) . getSize ( ) ; /* why is this needed ??\n    EnumTypedef etd = getEnumTypedef();\n    if (etd != null) {\n      DataType etdtype = etd.getBaseType();\n      if (dataType != etdtype)\n        log.error(\"Variable.setDataType: enum basetype mismatch: {} != {}\", etdtype, dataType);\n\n      /* DataType basetype = null;\n      if (dataType == DataType.ENUM1) basetype = DataType.BYTE;\n      else if (dataType == DataType.ENUM2) basetype = DataType.SHORT;\n      else if (dataType == DataType.ENUM4) basetype = DataType.INT;\n      else basetype = etdtype;\n\n      if (etdtype != null && dataType != etdtype)\n      else\n        etd.setBaseType(basetype);\n    }  */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the shape with a list of Dimensions . The Dimensions may be shared or not . Dimensions are in order slowest varying first . Send a null for a scalar . Technically you can use Dimensions from any group ; pragmatically you should only use Dimensions contained in the Variable s parent groups . [CODESPLIT] public void setDimensions ( List < Dimension > dims ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; this . dimensions = ( dims == null ) ? new ArrayList <> ( ) : new ArrayList <> ( dims ) ; resetShape ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use when dimensions have changed to recalculate the shape . [CODESPLIT] public void resetShape ( ) { // if (immutable) throw new IllegalStateException(\"Cant modify\");  LOOK allow this for unlimited dimension updating this . shape = new int [ dimensions . size ( ) ] ; for ( int i = 0 ; i < dimensions . size ( ) ; i ++ ) { Dimension dim = dimensions . get ( i ) ; shape [ i ] = dim . getLength ( ) ; //shape[i] = Math.max(dim.getLength(), 0); // LOOK // if (dim.isUnlimited() && (i != 0)) // LOOK only true for Netcdf-3 //   throw new IllegalArgumentException(\"Unlimited dimension must be outermost\"); if ( dim . isVariableLength ( ) ) { //if (dimensions.size() != 1) //  throw new IllegalArgumentException(\"Unknown dimension can only be used in 1 dim array\"); //else isVariableLength = true ; } } this . shapeAsSection = null ; // recalc next time its asked for }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the dimensions using the dimensions names . The dimension is searched for recursively in the parent groups . [CODESPLIT] public void setDimensions ( String dimString ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; try { setDimensions ( Dimension . makeDimensionsList ( getParentGroup ( ) , dimString ) ) ; //this.dimensions = Dimension.makeDimensionsList(getParentGroup(), dimString); resetShape ( ) ; } catch ( IllegalStateException e ) { throw new IllegalArgumentException ( \"Variable \" + getFullName ( ) + \" setDimensions = '\" + dimString + \"' FAILED: \" + e . getMessage ( ) + \" file = \" + getDatasetLocation ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the dimension array . Anonymous dimensions are left alone . Shared dimensions are searched for recursively in the parent groups . [CODESPLIT] public void resetDimensions ( ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; ArrayList < Dimension > newDimensions = new ArrayList <> ( ) ; for ( Dimension dim : dimensions ) { if ( dim . isShared ( ) ) { Dimension newD = getParentGroup ( ) . findDimension ( dim . getShortName ( ) ) ; if ( newD == null ) throw new IllegalArgumentException ( \"Variable \" + getFullName ( ) + \" resetDimensions  FAILED, dim doesnt exist in parent group=\" + dim ) ; newDimensions . add ( newD ) ; } else { newDimensions . add ( dim ) ; } } this . dimensions = newDimensions ; resetShape ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the dimensions using all anonymous ( unshared ) dimensions [CODESPLIT] public void setDimensionsAnonymous ( int [ ] shape ) throws InvalidRangeException { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; this . dimensions = new ArrayList <> ( ) ; for ( int i = 0 ; i < shape . length ; i ++ ) { if ( ( shape [ i ] < 1 ) && ( shape [ i ] != - 1 ) ) throw new InvalidRangeException ( \"shape[\" + i + \"]=\" + shape [ i ] + \" must be > 0\" ) ; Dimension anon ; if ( shape [ i ] == - 1 ) { anon = Dimension . VLEN ; isVariableLength = true ; } else { anon = new Dimension ( null , shape [ i ] , false , false , false ) ; } dimensions . add ( anon ) ; } resetShape ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace a dimension with an equivalent one . [CODESPLIT] public void setDimension ( int idx , Dimension dim ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; dimensions . set ( idx , dim ) ; resetShape ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will this Variable be cached when read . Set externally or calculated based on total size < sizeToCache . <p > This will always return { @code false } if { @link #permitCaching caching isn t permitted } . [CODESPLIT] public boolean isCaching ( ) { if ( ! permitCaching ) { return false ; } if ( ! this . cache . cachingSet ) { cache . isCaching = ! isVariableLength && ( getSize ( ) * getElementSize ( ) < getSizeToCache ( ) ) ; if ( debugCaching ) System . out . printf ( \"  cache %s %s %d < %d%n\" , getFullName ( ) , cache . isCaching , getSize ( ) * getElementSize ( ) , getSizeToCache ( ) ) ; this . cache . cachingSet = true ; } return cache . isCaching ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data cache [CODESPLIT] public void setCachedData ( Array cacheData , boolean isMetadata ) { if ( ( cacheData != null ) && ( cacheData . getElementType ( ) != getDataType ( ) . getPrimitiveClassType ( ) ) ) throw new IllegalArgumentException ( \"setCachedData type=\" + cacheData . getElementType ( ) + \" incompatible with variable type=\" + getDataType ( ) ) ; this . cache . data = cacheData ; this . isMetadata = isMetadata ; this . cache . cachingSet = true ; this . cache . isCaching = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get list of Dimensions including parents if any . [CODESPLIT] public List < Dimension > getDimensionsAll ( ) { List < Dimension > dimsAll = new ArrayList <> ( ) ; addDimensionsAll ( dimsAll , this ) ; return dimsAll ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate if this is a classic coordinate variable : has same name as its first dimension . If type char must be 2D else must be 1D . [CODESPLIT] public boolean isCoordinateVariable ( ) { if ( ( dataType == DataType . STRUCTURE ) || isMemberOfStructure ( ) ) // Structures and StructureMembers cant be coordinate variables return false ; int n = getRank ( ) ; if ( n == 1 && dimensions . size ( ) == 1 ) { Dimension firstd = dimensions . get ( 0 ) ; if ( getShortName ( ) . equals ( firstd . getShortName ( ) ) ) { //  : short names match return true ; } } if ( n == 2 && dimensions . size ( ) == 2 ) { // two dimensional Dimension firstd = dimensions . get ( 0 ) ; if ( shortName . equals ( firstd . getShortName ( ) ) && // short names match ( getDataType ( ) == DataType . CHAR ) ) { // must be char valued (really a String) return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "you must set EarthLocation before you call this . [CODESPLIT] protected void setBoundingBox ( ) { LatLonRect largestBB = null ; // look through all the coord systems for ( Object o : csHash . values ( ) ) { RadialCoordSys sys = ( RadialCoordSys ) o ; sys . setOrigin ( origin ) ; LatLonRect bb = sys . getBoundingBox ( ) ; if ( largestBB == null ) largestBB = bb ; else if ( bb != null ) largestBB . extend ( bb ) ; } boundingBox = largestBB ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call after adding all runs [CODESPLIT] void finish ( ) { gridList = new ArrayList <> ( uvHash . values ( ) ) ; Collections . sort ( gridList ) ; // find the common coordinates\r for ( GridVariable grid : gridList ) { grid . finish ( ) ; } // assign sequence number for time\r int seqno = 0 ; for ( TimeCoord tc : timeCoords ) tc . setId ( seqno ++ ) ; // assign sequence number for vertical coords with same name\r HashMap < String , List < VertCoord > > map = new HashMap <> ( ) ; for ( VertCoord vc : vertCoords ) { List < VertCoord > list = map . get ( vc . getName ( ) ) ; if ( list == null ) { list = new ArrayList <> ( ) ; map . put ( vc . getName ( ) , list ) ; } list . add ( vc ) ; } for ( List < VertCoord > list : map . values ( ) ) { if ( list . size ( ) > 0 ) { int count = 0 ; for ( VertCoord vc : list ) { if ( count > 0 ) vc . setName ( vc . getName ( ) + count ) ; count ++ ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////// [CODESPLIT] private void parseTemporalExtentForm ( ) { // from the form if ( temporal == null ) { errs . format ( \"form must have temporal=(all|range|point)%n\" ) ; fatal = true ; return ; } if ( temporal . equalsIgnoreCase ( \"all\" ) ) temporalSelection = TemporalSelection . all ; else if ( temporal . equalsIgnoreCase ( \"range\" ) ) temporalSelection = TemporalSelection . range ; else if ( temporal . equalsIgnoreCase ( \"point\" ) ) temporalSelection = TemporalSelection . point ; if ( temporal . equalsIgnoreCase ( \"range\" ) ) { try { parseTimeExtent ( ) ; } catch ( Throwable t ) { errs . format ( \"badly specified time range\" ) ; fatal = true ; } } else if ( temporal . equalsIgnoreCase ( \"point\" ) ) { timePoint = parseDate ( \"time\" , time ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get all datasets contained directly in this catalog [CODESPLIT] public Iterable < Dataset > getAllDatasets ( ) { List < Dataset > all = new ArrayList <> ( ) ; addAll ( this , all ) ; return all ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A path is a Synthetic path if it ends in . dmr or . syn [CODESPLIT] public boolean dspMatch ( String path , DapContext context ) { for ( String ext : SYNEXTENSIONS ) { if ( path . endsWith ( ext ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provide an extra API for use in testing [CODESPLIT] public CDMDSP open ( NetcdfDataset ncd ) throws DapException { assert this . context != null ; this . dmrfactory = new DMRFactory ( ) ; this . ncdfile = ncd ; setLocation ( this . ncdfile . getLocation ( ) ) ; buildDMR ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track generic CDMNode < - > DapNode [CODESPLIT] protected void recordNode ( CDMNode cdm , DapNode dap ) { assert this . nodemap . get ( cdm ) == null && this . nodemap . get ( dap ) == null ; this . nodemap . put ( cdm , dap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track Variable < - > DapVariable [CODESPLIT] protected void recordVar ( Variable cdm , DapVariable dap ) { cdm = CDMUtil . unwrap ( cdm ) ; assert varmap . get ( cdm ) == null && varmap . get ( dap ) == null ; varmap . put ( cdm , dap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track Variable < - > DapStructure [CODESPLIT] protected void recordStruct ( Variable cdm , DapStructure dap ) { cdm = CDMUtil . unwrap ( cdm ) ; assert this . nodemap . get ( cdm ) == null && this . nodemap . get ( dap ) == null ; compoundmap . put ( cdm , dap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track Variable < - > DapSequence [CODESPLIT] protected void recordSeq ( Variable cdm , DapSequence dap ) { cdm = CDMUtil . unwrap ( cdm ) ; assert this . vlenmap . get ( cdm ) == null && this . vlenmap . get ( dap ) == null ; vlenmap . put ( cdm , dap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the metadata from the NetcdfDataset and build the DMR . [CODESPLIT] public void buildDMR ( ) throws DapException { if ( getDMR ( ) != null ) return ; try { if ( DUMPCDL ) { System . out . println ( \"writecdl:\" ) ; this . ncdfile . writeCDL ( System . out , false ) ; System . out . flush ( ) ; } // Use the file path to define the dataset name String name = this . ncdfile . getLocation ( ) ; // Normalize the name name = DapUtil . canonicalpath ( name ) ; // Remove any path prefix int index = name . lastIndexOf ( ' ' ) ; if ( index >= 0 ) name = name . substring ( index + 1 , name . length ( ) ) ; // Initialize the root dataset node setDMR ( ( DapDataset ) dmrfactory . newDataset ( name ) . annotate ( NetcdfDataset . class , this . ncdfile ) ) ; // Map the CDM root group to this group recordNode ( this . ncdfile . getRootGroup ( ) , getDMR ( ) ) ; getDMR ( ) . setBase ( DapUtil . canonicalpath ( this . ncdfile . getLocation ( ) ) ) ; // Now recursively build the tree. Start by // Filling the dataset with the contents of the ncfile // root group. fillgroup ( getDMR ( ) , this . ncdfile . getRootGroup ( ) ) ; // Add an order index to the tree getDMR ( ) . sort ( ) ; // Now locate the coordinate variables for maps /* Walk looking for VariableDS instances */ processmappedvariables ( this . ncdfile . getRootGroup ( ) ) ; // Now set the view getDMR ( ) . finish ( ) ; } catch ( DapException e ) { setDMR ( null ) ; throw new DapException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actions [CODESPLIT] protected void fillgroup ( DapGroup dapgroup , Group cdmgroup ) throws DapException { // Create decls in dap group for Dimensions for ( Dimension cdmdim : cdmgroup . getDimensions ( ) ) { DapDimension dapdim = builddim ( cdmdim ) ; } // Create decls in dap group for Enumerations for ( EnumTypedef cdmenum : cdmgroup . getEnumTypedefs ( ) ) { String name = cdmenum . getShortName ( ) ; DapEnumeration dapenum = buildenum ( cdmenum ) ; dapenum . setShortName ( name ) ; dapgroup . addDecl ( dapenum ) ; } // Create decls in dap group for vlen induced Sequences // Do this before building compound types for ( Variable cdmvar0 : cdmgroup . getVariables ( ) ) { Variable cdmvar = CDMUtil . unwrap ( cdmvar0 ) ; buildseqtypes ( cdmvar ) ; } // Create decls in dap group for Compound Types for ( Variable cdmvar0 : cdmgroup . getVariables ( ) ) { Variable cdmvar = CDMUtil . unwrap ( cdmvar0 ) ; if ( cdmvar . getDataType ( ) != DataType . STRUCTURE && cdmvar . getDataType ( ) != DataType . SEQUENCE ) continue ; DapStructure struct = buildcompoundtype ( cdmvar , dapgroup ) ; } // Create decls in dap group for Variables for ( Variable cdmvar0 : cdmgroup . getVariables ( ) ) { Variable cdmvar = CDMUtil . unwrap ( cdmvar0 ) ; DapNode newvar = buildvariable ( cdmvar , dapgroup , cdmvar . getDimensions ( ) ) ; } // Create decls in dap group for subgroups for ( Group subgroup : cdmgroup . getGroups ( ) ) { DapGroup newgroup = buildgroup ( subgroup ) ; dapgroup . addDecl ( newgroup ) ; } // Create decls in dap group for group-level attributes buildattributes ( dapgroup , cdmgroup . getAttributes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declaration Builders [CODESPLIT] protected DapDimension builddim ( Dimension cdmdim ) throws DapException { if ( cdmdim . isVariableLength ( ) ) throw new DapException ( \"* dimensions not supported\" ) ; DapDimension dapdim = null ; long cdmsize = dapsize ( cdmdim ) ; String name = cdmdim . getShortName ( ) ; if ( name != null && name . length ( ) == 0 ) name = null ; boolean shared = cdmdim . isShared ( ) ; if ( ! shared ) { // Unlike the parser, since we are working // from a NetcdfDataset instance, there might // be multiple anonymous dimension objects // the same size. So, just go ahead and create // multiple instances. dapdim = ( DapDimension ) dmrfactory . newDimension ( null , cdmsize ) ; getDMR ( ) . addDecl ( dapdim ) ; } else { // Non anonymous; create in current group dapdim = ( DapDimension ) dmrfactory . newDimension ( name , cdmsize ) ; dapdim . setShared ( true ) ; if ( cdmdim . isUnlimited ( ) ) { dapdim . setUnlimited ( true ) ; } Group cdmparent = cdmdim . getGroup ( ) ; DapGroup dapparent = ( DapGroup ) this . nodemap . get ( cdmparent ) ; assert dapparent != null ; assert ( dapparent != null ) ; dapparent . addDecl ( dapdim ) ; } recordNode ( cdmdim , dapdim ) ; return dapdim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create a sequence from a variable with a variable length last dimension . Suppose we have cdm equivalent to this : T var [ d1 ] ... [ dn ]] [ * ] We convert to the following <Sequence name = var > <T name = var / > <Dim name = d1 / > ... <Dim name = dn / > < / Sequence > [CODESPLIT] protected DapSequence buildseqtype ( Variable cdmvar ) throws DapException { cdmvar = CDMUtil . unwrap ( cdmvar ) ; assert ( CDMUtil . hasVLEN ( cdmvar ) ) ; DataType dt = cdmvar . getDataType ( ) ; DapType daptype = CDMTypeFcns . cdmtype2daptype ( dt ) ; DapSequence seq = ( DapSequence ) dmrfactory . newSequence ( cdmvar . getShortName ( ) ) ; // fill DapSequence with a single field; note that the dimensions // are elided because they will attach to the sequence variable, // not the field DapVariable field = dmrfactory . newVariable ( cdmvar . getShortName ( ) , daptype ) ; seq . addField ( field ) ; field . setParent ( seq ) ; recordSeq ( cdmvar , seq ) ; return seq ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walk this variable including fields to construct sequence types for any contained vlen dimensions [CODESPLIT] protected void buildseqtypes ( Variable cdmvar ) throws DapException { if ( CDMUtil . hasVLEN ( cdmvar ) ) { buildseqtype ( cdmvar ) ; } if ( cdmvar . getDataType ( ) == DataType . STRUCTURE || cdmvar . getDataType ( ) == DataType . SEQUENCE ) { Structure struct = ( Structure ) cdmvar ; List < Variable > fields = struct . getVariables ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { Variable field = fields . get ( i ) ; buildseqtypes ( field ) ; // recurse for inner vlen dims } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign dimensions to a variable [CODESPLIT] protected void builddimrefs ( DapVariable dapvar , List < Dimension > cdmdims ) throws DapException { if ( cdmdims == null || cdmdims . size ( ) == 0 ) return ; // It is unfortunately the case that the dimensions // associated with the variable are not // necessarily the same object as those dimensions // as declared, so we need to use a non-trivial // matching algorithm. for ( Dimension cdmdim : cdmdims ) { DapDimension dapdim = null ; if ( cdmdim . isShared ( ) ) { Dimension declareddim = finddimdecl ( cdmdim ) ; if ( declareddim == null ) throw new DapException ( \"Unprocessed cdm dimension: \" + cdmdim ) ; dapdim = ( DapDimension ) this . nodemap . get ( declareddim ) ; assert dapdim != null ; } else if ( cdmdim . isVariableLength ( ) ) { // ignore continue ; } else { //anonymous dapdim = builddim ( cdmdim ) ; } assert ( dapdim != null ) : \"Internal error\" ; dapvar . addDimension ( dapdim ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unfortunately the CDM Iosp does not actually use the declared enums . Rather for every enum type d variable a new enum decl is defined . So we need to find the original enum decl that matches the variable s enum . [CODESPLIT] protected EnumTypedef findMatchingEnum ( EnumTypedef varenum ) throws DapException { List < EnumTypedef > candidates = new ArrayList <> ( ) ; for ( Map . Entry < DapNode , CDMNode > entry : this . nodemap . getCDMMap ( ) . entrySet ( ) ) { CDMNode cdmnode = entry . getValue ( ) ; if ( cdmnode . getSort ( ) != CDMSort . ENUMERATION ) continue ; // Compare the enumeration (note names will differ) EnumTypedef target = ( EnumTypedef ) cdmnode ; /* Ideally, we should test the types of the enums,\n               but, unfortunately, the var enum is always enum4.\n            if(target.getBaseType() != varenum.getBaseType())\n                continue;\n            */ Map < Integer , String > targetmap = target . getMap ( ) ; Map < Integer , String > varmap = varenum . getMap ( ) ; if ( targetmap . size ( ) != varmap . size ( ) ) continue ; boolean match = true ; // until otherwise shown for ( Map . Entry < Integer , String > tpair : targetmap . entrySet ( ) ) { String tname = tpair . getValue ( ) ; int value = ( int ) tpair . getKey ( ) ; boolean found = false ; for ( Map . Entry < Integer , String > vpair : varmap . entrySet ( ) ) { if ( tname . equals ( vpair . getValue ( ) ) && value == ( int ) vpair . getKey ( ) ) { found = true ; break ; } } if ( ! found ) { match = false ; break ; } } if ( ! match ) continue ; // Save it unless it is shadowed by a closer enum boolean shadowed = false ; for ( EnumTypedef etd : candidates ) { if ( shadows ( etd . getGroup ( ) , target . getGroup ( ) ) ) { shadowed = true ; break ; } } if ( ! shadowed ) candidates . add ( target ) ; } switch ( candidates . size ( ) ) { case 0 : throw new DapException ( \"CDMDSP: No matching enum type decl: \" + varenum . getShortName ( ) ) ; case 1 : break ; default : throw new DapException ( \"CDMDSP: Multiple matching enum type decls: \" + varenum . getShortName ( ) ) ; } return candidates . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// [CODESPLIT] protected NetcdfFile createNetcdfFile ( String location , CancelTask canceltask ) throws DapException { try { NetcdfFile ncfile = NetcdfFile . open ( location , - 1 , canceltask , getContext ( ) ) ; return ncfile ; } catch ( DapException de ) { if ( DEBUG ) de . printStackTrace ( ) ; throw de ; } catch ( Exception e ) { if ( DEBUG ) e . printStackTrace ( ) ; throw new DapException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strip vlen dimensions from a set of dimensions [CODESPLIT] static List < Dimension > getCoreDimset ( List < Dimension > dimset ) throws DapException { if ( dimset == null ) return null ; List < Dimension > core = new ArrayList <> ( ) ; int pos = - 1 ; int count = 0 ; for ( int i = 0 ; i < dimset . size ( ) ; i ++ ) { if ( dimset . get ( i ) . isVariableLength ( ) ) { pos = i ; count ++ ; } else core . add ( dimset . get ( i ) ) ; } if ( ( pos != dimset . size ( ) - 1 ) || count > 1 ) throw new DapException ( \"Unsupported use of (*) Dimension\" ) ; return core ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some attributes that are added by the NetcdfDataset need to be kept out of the DMR . This function defines that set . [CODESPLIT] protected boolean suppress ( String attrname ) { if ( attrname . startsWith ( \"_Coord\" ) ) return true ; if ( attrname . equals ( CDM . UNSIGNED ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////// [CODESPLIT] public java . util . List < FileBean > scan ( String top , Formatter errlog ) { List < FileBean > result = new ArrayList <> ( ) ; File topFile = new File ( top ) ; if ( ! topFile . exists ( ) ) { errlog . format ( \"File %s does not exist\" , top ) ; return result ; } if ( topFile . isDirectory ( ) ) scanDirectory ( topFile , false , result , errlog ) ; else { FileBean fdb = null ; try { fdb = new FileBean ( topFile ) ; } catch ( IOException e ) { System . out . printf ( \"FAIL, skip %s%n\" , topFile . getPath ( ) ) ; } result . add ( fdb ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the original string representation of this clause . For use in debugging . [CODESPLIT] public void printConstraint ( PrintWriter os ) { if ( constant ) { value . printVal ( os , \"\" , false ) ; } else { value . printConstraint ( os ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gml : description [CODESPLIT] public static StringOrRefType initDescription ( StringOrRefType description , StationTimeSeriesFeature stationFeat ) { // TEXT description . setStringValue ( stationFeat . getDescription ( ) ) ; return description ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "open the file and extract BUFR messages [CODESPLIT] public int scanBufrFile ( String filename , Counter total ) throws Exception { int count = 0 ; try ( RandomAccessFile raf = new RandomAccessFile ( filename , \"r\" ) ) { MessageScanner scan = new MessageScanner ( raf ) ; while ( scan . hasNext ( ) ) { Message m = scan . next ( ) ; if ( m == null ) continue ; try { if ( showMess ) out . format ( \"%sMessage %d header=%s%n\" , indent , count , m . getHeader ( ) ) ; count ++ ; Counter counter = new Counter ( ) ; processBufrMessageAsDataset ( scan , m , counter ) ; if ( showMess ) out . format ( \"%scount=%d miss=%d%n\" , indent , counter . nvals , counter . nmiss ) ; total . add ( counter ) ; } catch ( Exception e ) { System . out . printf ( \"  BARF:%s on %s%n\" , e . getMessage ( ) , m . getHeader ( ) ) ; indent . setIndentLevel ( 0 ) ; } } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert one message ino a NetcdfDataset and print data [CODESPLIT] private void processBufrMessageAsDataset ( MessageScanner scan , Message m , Counter counter ) throws Exception { byte [ ] mbytes = scan . getMessageBytes ( m ) ; NetcdfFile ncfile = NetcdfFile . openInMemory ( \"test\" , mbytes , \"ucar.nc2.iosp.bufr.BufrIosp\" ) ; Sequence obs = ( Sequence ) ncfile . findVariable ( BufrIosp2 . obsRecord ) ; StructureDataIterator sdataIter = obs . getStructureIterator ( - 1 ) ; processSequence ( obs , sdataIter , counter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "iterate through the observations [CODESPLIT] private void processSequence ( Structure s , StructureDataIterator sdataIter , Counter counter ) throws IOException { indent . incr ( ) ; int count = 0 ; try { while ( sdataIter . hasNext ( ) ) { if ( showData ) out . format ( \"%sSequence %s count=%d%n\" , indent , s . getShortName ( ) , count ++ ) ; StructureData sdata = sdataIter . next ( ) ; indent . incr ( ) ; for ( StructureMembers . Member m : sdata . getMembers ( ) ) { Variable v = s . findVariable ( m . getName ( ) ) ; if ( m . getDataType ( ) . isString ( ) || m . getDataType ( ) . isNumeric ( ) ) { processVariable ( v , sdata . getArray ( m ) , counter ) ; } else if ( m . getDataType ( ) == DataType . STRUCTURE ) { Structure sds = ( Structure ) v ; ArrayStructure data = ( ArrayStructure ) sdata . getArray ( m ) ; processSequence ( sds , data . getStructureDataIterator ( ) , counter ) ; } else if ( m . getDataType ( ) == DataType . SEQUENCE ) { Sequence sds = ( Sequence ) v ; ArraySequence data = ( ArraySequence ) sdata . getArray ( m ) ; processSequence ( sds , data . getStructureDataIterator ( ) , counter ) ; } } indent . decr ( ) ; } } finally { sdataIter . close ( ) ; } indent . decr ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private ArrayInt . D1 parentArray = new ArrayInt . D1 ( 1 ) ; [CODESPLIT] private void createRecordVariables ( List < ? extends VariableSimpleIF > dataVars ) { ncfileOut . addDimension ( null , new Dimension ( recordDimName , 0 , true , true , false ) ) ; // time variable Variable timeVar = ncfileOut . addVariable ( null , timeName , DataType . DOUBLE , recordDimName ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , \"secs since 1970-01-01 00:00:00\" ) ) ; timeVar . addAttribute ( new Attribute ( CDM . LONG_NAME , \"date/time of observation\" ) ) ; recordVars . add ( timeVar ) ; // latitude variable Variable latVar = ncfileOut . addVariable ( null , latName , DataType . DOUBLE , recordDimName ) ; latVar . addAttribute ( new Attribute ( CDM . UNITS , \"degrees_north\" ) ) ; latVar . addAttribute ( new Attribute ( CDM . LONG_NAME , \"latitude of observation\" ) ) ; latVar . addAttribute ( new Attribute ( \"standard_name\" , \"latitude\" ) ) ; recordVars . add ( latVar ) ; // longitude variable Variable lonVar = ncfileOut . addVariable ( null , lonName , DataType . DOUBLE , recordDimName ) ; lonVar . addAttribute ( new Attribute ( CDM . UNITS , \"degrees_east\" ) ) ; lonVar . addAttribute ( new Attribute ( CDM . LONG_NAME , \"longitude of observation\" ) ) ; lonVar . addAttribute ( new Attribute ( \"standard_name\" , \"longitude\" ) ) ; recordVars . add ( lonVar ) ; if ( useAlt ) { // altitude variable Variable altVar = ncfileOut . addVariable ( null , altName , DataType . DOUBLE , recordDimName ) ; altVar . addAttribute ( new Attribute ( CDM . UNITS , altUnits ) ) ; altVar . addAttribute ( new Attribute ( CDM . LONG_NAME , \"altitude of observation\" ) ) ; altVar . addAttribute ( new Attribute ( \"standard_name\" , \"longitude\" ) ) ; altVar . addAttribute ( new Attribute ( CF . POSITIVE , CF1Convention . getZisPositive ( altName , altUnits ) ) ) ; recordVars . add ( altVar ) ; } String coordinates = timeName + \" \" + latName + \" \" + lonName ; if ( useAlt ) coordinates = coordinates + \" \" + altName ; Attribute coordAtt = new Attribute ( CF . COORDINATES , coordinates ) ; // find all dimensions needed by the data variables for ( VariableSimpleIF var : dataVars ) { List < Dimension > dims = var . getDimensions ( ) ; dimSet . addAll ( dims ) ; } // add them for ( Dimension d : dimSet ) { if ( isExtraDimension ( d ) ) ncfileOut . addDimension ( null , new Dimension ( d . getShortName ( ) , d . getLength ( ) , true , false , d . isVariableLength ( ) ) ) ; } // add the data variables all using the record dimension for ( VariableSimpleIF oldVar : dataVars ) { if ( ncfileOut . findVariable ( oldVar . getShortName ( ) ) != null ) continue ; List < Dimension > dims = oldVar . getDimensions ( ) ; StringBuilder dimNames = new StringBuilder ( recordDimName ) ; for ( Dimension d : dims ) { if ( isExtraDimension ( d ) ) dimNames . append ( \" \" ) . append ( d . getShortName ( ) ) ; } Variable newVar = ncfileOut . addVariable ( null , oldVar . getShortName ( ) , oldVar . getDataType ( ) , dimNames . toString ( ) ) ; recordVars . add ( newVar ) ; List < Attribute > atts = oldVar . getAttributes ( ) ; for ( Attribute att : atts ) newVar . addAttribute ( att ) ; newVar . addAttribute ( coordAtt ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a ucar . nc2 . ft . PointFeatureCollection in CF point format . [CODESPLIT] public static int writePointFeatureCollection ( FeatureDatasetPoint pfDataset , String fileOut ) throws IOException { // extract the PointFeatureCollection PointFeatureCollection pointFeatureCollection = null ; List < DsgFeatureCollection > featureCollectionList = pfDataset . getPointFeatureCollectionList ( ) ; for ( DsgFeatureCollection featureCollection : featureCollectionList ) { if ( featureCollection instanceof PointFeatureCollection ) pointFeatureCollection = ( PointFeatureCollection ) featureCollection ; } if ( null == pointFeatureCollection ) throw new IOException ( \"There is no PointFeatureCollection in  \" + pfDataset . getLocation ( ) ) ; long start = System . currentTimeMillis ( ) ; FileOutputStream fos = new FileOutputStream ( fileOut ) ; DataOutputStream out = new DataOutputStream ( new BufferedOutputStream ( fos , 10000 ) ) ; WriterCFPointDataset writer = null ; // LOOK BAD List < VariableSimpleIF > dataVars = new ArrayList < VariableSimpleIF > ( ) ; ucar . nc2 . NetcdfFile ncfile = pfDataset . getNetcdfFile ( ) ; if ( ( ncfile == null ) || ! ( ncfile instanceof NetcdfDataset ) ) { dataVars . addAll ( pfDataset . getDataVariables ( ) ) ; } else { NetcdfDataset ncd = ( NetcdfDataset ) ncfile ; for ( VariableSimpleIF vs : pfDataset . getDataVariables ( ) ) { if ( ncd . findCoordinateAxis ( vs . getShortName ( ) ) == null ) dataVars . add ( vs ) ; } } int count = 0 ; for ( PointFeature pointFeature : pointFeatureCollection ) { StructureData data = pointFeature . getDataAll ( ) ; if ( count == 0 ) { EarthLocation loc = pointFeature . getLocation ( ) ; // LOOK we dont know this until we see the obs String altUnits = Double . isNaN ( loc . getAltitude ( ) ) ? null : \"meters\" ; // LOOK units may be wrong writer = new WriterCFPointDataset ( out , pfDataset . getGlobalAttributes ( ) , altUnits ) ; writer . writeHeader ( dataVars , - 1 ) ; } writer . writeRecord ( pointFeature , data ) ; count ++ ; } writer . finish ( ) ; out . flush ( ) ; out . close ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . printf ( \"Write %d records from %s to %s took %d msecs %n\" , count , pfDataset . getLocation ( ) , fileOut , took ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a ucar . nc2 . dt . PointObsDataset write out in CF point format . [CODESPLIT] public static void rewritePointObsDataset ( String fileIn , String fileOut , boolean inMemory ) throws IOException { System . out . println ( \"Rewrite .nc files from \" + fileIn + \" to \" + fileOut + \"inMem= \" + inMemory ) ; long start = System . currentTimeMillis ( ) ; // do it in memory for speed NetcdfFile ncfile = inMemory ? NetcdfFile . openInMemory ( fileIn ) : NetcdfFile . open ( fileIn ) ; NetcdfDataset ncd = new NetcdfDataset ( ncfile ) ; StringBuilder errlog = new StringBuilder ( ) ; PointObsDataset pobsDataset = ( PointObsDataset ) TypedDatasetFactory . open ( FeatureType . POINT , ncd , null , errlog ) ; FileOutputStream fos = new FileOutputStream ( fileOut ) ; DataOutputStream out = new DataOutputStream ( fos ) ; WriterCFPointDataset writer = null ; DataIterator iter = pobsDataset . getDataIterator ( 1000 * 1000 ) ; while ( iter . hasNext ( ) ) { PointObsDatatype pobsData = ( PointObsDatatype ) iter . nextData ( ) ; StructureData sdata = pobsData . getData ( ) ; if ( writer == null ) { ucar . unidata . geoloc . EarthLocation loc = pobsData . getLocation ( ) ; String altUnits = Double . isNaN ( loc . getAltitude ( ) ) ? null : \"meters\" ; writer = new WriterCFPointDataset ( out , ncfile . getGlobalAttributes ( ) , altUnits ) ; writer . writeHeader ( pobsDataset . getDataVariables ( ) , - 1 ) ; } writer . writeRecord ( pobsData , sdata ) ; } writer . finish ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . println ( \"Rewrite \" + fileIn + \" to \" + fileOut + \" took = \" + took ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GET handles the case where its a remote URL ( dods or http ) [CODESPLIT] public void doGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { log . info ( \"doGet(): \" + UsageLog . setupRequestContext ( req ) ) ; String urlString = req . getParameter ( \"URL\" ) ; if ( urlString == null ) { log . info ( \"doGet(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_BAD_REQUEST , 0 ) ) ; res . sendError ( HttpServletResponse . SC_BAD_REQUEST , \"Must have a URL parameter\" ) ; return ; } // validate the url String try { URI uri = new URI ( urlString ) ; urlString = uri . toASCIIString ( ) ; // LOOK do we want just toString() ? Is this useful \"input validation\" ? } catch ( URISyntaxException e ) { log . info ( \"doGet(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_BAD_REQUEST , 0 ) ) ; res . sendError ( HttpServletResponse . SC_BAD_REQUEST , \"URISyntaxException on URU parameter\" ) ; return ; } String xml = req . getParameter ( \"xml\" ) ; boolean wantXml = ( xml != null ) && xml . equals ( \"true\" ) ; try { int len = showValidatorResults ( res , urlString , wantXml ) ; log . info ( \"doGet(): URL = \" + urlString ) ; log . info ( \"doGet(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_OK , len ) ) ; } catch ( Exception e ) { log . info ( \"doGet(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_BAD_REQUEST , 0 ) ) ; res . sendError ( HttpServletResponse . SC_BAD_REQUEST , \"Invalid input\" ) ; } catch ( Throwable e ) { log . error ( \"doGet(): Validator internal error\" , e ) ; log . info ( \"doGet(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , 0 ) ) ; res . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , \"Validator internal error\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "POST handles uploaded files [CODESPLIT] public void doPost ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { log . info ( \"doPost(): \" + UsageLog . setupRequestContext ( req ) ) ; // Check that we have a file upload request boolean isMultipart = ServletFileUpload . isMultipartContent ( req ) ; if ( ! isMultipart ) { log . info ( \"doPost(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_BAD_REQUEST , 0 ) ) ; res . sendError ( HttpServletResponse . SC_BAD_REQUEST ) ; return ; } //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload ( this . cdmValidatorContext . getFileuploadFileItemFactory ( ) ) ; upload . setSizeMax ( this . cdmValidatorContext . getMaxFileUploadSize ( ) ) ; // maximum bytes before a FileUploadException will be thrown List < FileItem > fileItems ; try { fileItems = ( List < FileItem > ) upload . parseRequest ( req ) ; } catch ( FileUploadException e ) { log . info ( \"doPost(): Validator FileUploadException\" , e ) ; log . info ( \"doPost(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_BAD_REQUEST , 0 ) ) ; if ( ! res . isCommitted ( ) ) res . sendError ( HttpServletResponse . SC_BAD_REQUEST ) ; return ; } //Process the uploaded items String username = null ; boolean wantXml = false ; for ( FileItem item : fileItems ) { if ( item . isFormField ( ) ) { if ( \"username\" . equals ( item . getFieldName ( ) ) ) username = item . getString ( ) ; if ( \"xml\" . equals ( item . getFieldName ( ) ) ) wantXml = item . getString ( ) . equals ( \"true\" ) ; } } for ( FileItem item : fileItems ) { if ( ! item . isFormField ( ) ) { try { processUploadedFile ( req , res , ( DiskFileItem ) item , username , wantXml ) ; return ; } catch ( Exception e ) { log . info ( \"doPost(): Validator processUploadedFile\" , e ) ; log . info ( \"doPost(): \" + UsageLog . closingMessageForRequestContext ( HttpServletResponse . SC_BAD_REQUEST , 0 ) ) ; res . sendError ( HttpServletResponse . SC_BAD_REQUEST , e . getMessage ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Iterator < TrajectoryFeature > iterator ( ) { try { PointFeatureCollectionIterator pfIterator = getPointFeatureCollectionIterator ( ) ; return new CollectionIteratorAdapter <> ( pfIterator ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the affine transform based on screen size and world bounding box [CODESPLIT] public AffineTransform getTransform ( ) { at . setTransform ( pix_per_world , 0.0 , 0.0 , - pix_per_world , pix_x0 , pix_y0 ) ; if ( debug ) { System . out . println ( \"Navigation getTransform = \" + pix_per_world + \" \" + pix_x0 + \" \" + pix_y0 ) ; System . out . println ( \"  transform = \" + at ) ; } return at ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "calculate if we want to rotate based on aspect ratio [CODESPLIT] public boolean wantRotate ( double displayWidth , double displayHeight ) { getMapArea ( bb ) ; // current world bounding box boolean aspectDisplay = displayHeight < displayWidth ; boolean aspectWorldBB = bb . getHeight ( ) < bb . getWidth ( ) ; return ( aspectDisplay ^ aspectWorldBB ) ; // aspects are different }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate an affine transform based on the display size parameters - used for printing . @param rotate should the page be rotated? @param displayX upper right corner of display area @param displayY upper right corner of display area @param displayWidth display area @param displayHeight display area [CODESPLIT] public AffineTransform calcTransform ( boolean rotate , double displayX , double displayY , double displayWidth , double displayHeight ) { getMapArea ( bb ) ; // current world bounding box // scale to limiting dimension double pxpsx , pypsy ; if ( rotate ) { pxpsx = displayHeight / bb . getWidth ( ) ; pypsy = displayWidth / bb . getHeight ( ) ; } else { pxpsx = displayWidth / bb . getWidth ( ) ; pypsy = displayHeight / bb . getHeight ( ) ; } double pps = Math . min ( pxpsx , pypsy ) ; // calc offset: based on center point staying in center double wx0 = bb . getX ( ) + bb . getWidth ( ) / 2 ; // world midpoint double wy0 = bb . getY ( ) + bb . getHeight ( ) / 2 ; double x0 = displayX + displayWidth / 2 - pps * wx0 ; double y0 = displayY + displayHeight / 2 + pps * wy0 ; AffineTransform cat = new AffineTransform ( pps , 0.0 , 0.0 , - pps , x0 , y0 ) ; // rotate if we need to if ( rotate ) cat . rotate ( Math . PI / 2 , wx0 , wy0 ) ; if ( debug ) { System . out . println ( \"Navigation calcTransform = \" + displayX + \" \" + displayY + \" \" + displayWidth + \" \" + displayHeight ) ; System . out . println ( \"  world = \" + bb ) ; System . out . println ( \"  scale/origin = \" + pps + \" \" + x0 + \" \" + y0 ) ; System . out . println ( \"  transform = \" + cat ) ; } return cat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get current MapArea . [CODESPLIT] public ProjectionRect getMapArea ( ProjectionRect rect ) { if ( rect == null ) rect = new ProjectionRect ( ) ; double width = pwidth / pix_per_world ; double height = pheight / pix_per_world ; // center point double wx0 = ( pwidth / 2 - pix_x0 ) / pix_per_world ; double wy0 = ( pix_y0 - pheight / 2 ) / pix_per_world ; rect . setRect ( wx0 - width / 2 , wy0 - height / 2 , // minx, miny width , height ) ; // width, height return rect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert a world coordinate to a display point [CODESPLIT] public Point2D worldToScreen ( ProjectionPointImpl w , Point2D p ) { p . setLocation ( pix_per_world * w . getX ( ) + pix_x0 , - pix_per_world * w . getY ( ) + pix_y0 ) ; return p ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert screen Rectangle to a projection ( world ) rectangle [CODESPLIT] public ProjectionRect screenToWorld ( Point2D start , Point2D end ) { ProjectionPointImpl p1 = new ProjectionPointImpl ( ) ; ProjectionPointImpl p2 = new ProjectionPointImpl ( ) ; screenToWorld ( start , p1 ) ; screenToWorld ( end , p2 ) ; return new ProjectionRect ( p1 . getX ( ) , p1 . getY ( ) , p2 . getX ( ) , p2 . getY ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert a projection ( world ) rectangle to a screen Rectangle [CODESPLIT] public java . awt . Rectangle worldToScreen ( ProjectionRect projRect ) { Point2D p1 = new Point2D . Double ( ) ; Point2D p2 = new Point2D . Double ( ) ; worldToScreen ( ( ProjectionPointImpl ) projRect . getMaxPoint ( ) , p1 ) ; worldToScreen ( ( ProjectionPointImpl ) projRect . getMinPoint ( ) , p2 ) ; return new java . awt . Rectangle ( ( int ) p1 . getX ( ) , ( int ) p1 . getY ( ) , ( int ) p2 . getX ( ) , ( int ) p2 . getY ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call this to change the center of the screen s world coordinates . deltax deltay in display coordinates [CODESPLIT] public void pan ( double deltax , double deltay ) { zoom . push ( ) ; pix_x0 -= deltax ; pix_y0 -= deltay ; fireMapAreaEvent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call this to zoom into a subset of the screen . startx starty are the upper left corner of the box in display coords width height the size of the box in display coords [CODESPLIT] public void zoom ( double startx , double starty , double width , double height ) { if ( debugZoom ) System . out . println ( \"zoom \" + startx + \" \" + starty + \" \" + width + \" \" + height + \" \" ) ; if ( ( width < 5 ) || ( height < 5 ) ) return ; zoom . push ( ) ; pix_x0 -= startx + width / 2 - pwidth / 2 ; pix_y0 -= starty + height / 2 - pheight / 2 ; zoom ( pwidth / width ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adjust bounding box to fit inside the screen size [CODESPLIT] private void recalcFromBoundingBox ( ) { if ( debugRecalc ) { System . out . println ( \"Navigation recalcFromBoundingBox= \" + bb ) ; System . out . println ( \"  \" + pwidth + \" \" + pheight ) ; } // decide which dimension is limiting double pixx_per_wx = ( bb . getWidth ( ) == 0.0 ) ? 1 : pwidth / bb . getWidth ( ) ; double pixy_per_wy = ( bb . getHeight ( ) == 0.0 ) ? 1 : pheight / bb . getHeight ( ) ; pix_per_world = Math . min ( pixx_per_wx , pixy_per_wy ) ; // calc the center point double wx0 = bb . getX ( ) + bb . getWidth ( ) / 2 ; double wy0 = bb . getY ( ) + bb . getHeight ( ) / 2 ; // calc offset based on center point pix_x0 = pwidth / 2 - pix_per_world * wx0 ; pix_y0 = pheight / 2 + pix_per_world * wy0 ; if ( debugRecalc ) { System . out . println ( \"Navigation recalcFromBoundingBox done= \" + pix_per_world + \" \" + pix_x0 + \" \" + pix_y0 ) ; System . out . println ( \"  \" + pwidth + \" \" + pheight + \" \" + bb ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a listener . [CODESPLIT] public synchronized void addListener ( Object l ) { if ( ! listeners . contains ( l ) ) { listeners . add ( l ) ; hasListeners = true ; } else logger . warn ( \"ListenerManager.addListener already has Listener \" + l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a listener . [CODESPLIT] public synchronized void removeListener ( Object l ) { if ( listeners . contains ( l ) ) { listeners . remove ( l ) ; hasListeners = ( listeners . size ( ) > 0 ) ; } else logger . warn ( \"ListenerManager.removeListener couldnt find Listener \" + l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send an event to all registered listeners . If an exception is thrown remove the Listener from the list [CODESPLIT] public synchronized void sendEvent ( java . util . EventObject event ) { if ( ! hasListeners || ! enabled ) return ; Object [ ] args = new Object [ 1 ] ; args [ 0 ] = event ; // send event to all listeners ListIterator iter = listeners . listIterator ( ) ; while ( iter . hasNext ( ) ) { Object client = iter . next ( ) ; try { method . invoke ( client , args ) ; } catch ( IllegalAccessException e ) { logger . error ( \"ListenerManager IllegalAccessException\" , e ) ; iter . remove ( ) ; } catch ( IllegalArgumentException e ) { logger . error ( \"ListenerManager IllegalArgumentException\" , e ) ; iter . remove ( ) ; } catch ( InvocationTargetException e ) { // logger.error(\"ListenerManager InvocationTargetException on \" + method+ \" threw exception \" + e.getTargetException(), e); throw new RuntimeException ( e . getCause ( ) ) ; // pass exception to the caller of sendEvent() } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send an event to all registered listeners except the named one . [CODESPLIT] public synchronized void sendEventExcludeSource ( java . util . EventObject event ) { if ( ! hasListeners || ! enabled ) return ; Object source = event . getSource ( ) ; Object [ ] args = new Object [ 1 ] ; args [ 0 ] = event ; // send event to all listeners except the source ListIterator iter = listeners . listIterator ( ) ; while ( iter . hasNext ( ) ) { Object client = iter . next ( ) ; if ( client == source ) continue ; try { method . invoke ( client , args ) ; } catch ( IllegalAccessException | InvocationTargetException | IllegalArgumentException e ) { e . printStackTrace ( ) ; if ( e . getCause ( ) != null ) e . getCause ( ) . printStackTrace ( ) ; // iter.remove(); logger . error ( \"ListenerManager calling \" + method + \" threw exception \" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ncdump that parses a command string . [CODESPLIT] public static boolean print ( String command , Writer out , ucar . nc2 . util . CancelTask ct ) throws IOException { // pull out the filename from the command String filename ; StringTokenizer stoke = new StringTokenizer ( command ) ; if ( stoke . hasMoreTokens ( ) ) filename = stoke . nextToken ( ) ; else { out . write ( usage ) ; return false ; } try ( NetcdfFile nc = NetcdfDataset . openFile ( filename , ct ) ) { // the rest of the command int pos = command . indexOf ( filename ) ; command = command . substring ( pos + filename . length ( ) ) ; return print ( nc , command , out , ct ) ; } catch ( java . io . FileNotFoundException e ) { out . write ( \"file not found= \" ) ; out . write ( filename ) ; return false ; } finally { out . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ncdump parsing command string file already open . [CODESPLIT] public static boolean print ( NetcdfFile nc , String command , Writer out , ucar . nc2 . util . CancelTask ct ) throws IOException { WantValues showValues = WantValues . none ; boolean ncml = false ; boolean strict = false ; String varNames = null ; String trueDataset = null ; String fakeDataset = null ; if ( command != null ) { StringTokenizer stoke = new StringTokenizer ( command ) ; while ( stoke . hasMoreTokens ( ) ) { String toke = stoke . nextToken ( ) ; if ( toke . equalsIgnoreCase ( \"-help\" ) ) { out . write ( usage ) ; out . write ( ' ' ) ; return true ; } if ( toke . equalsIgnoreCase ( \"-vall\" ) ) showValues = WantValues . all ; if ( toke . equalsIgnoreCase ( \"-c\" ) && ( showValues == WantValues . none ) ) showValues = WantValues . coordsOnly ; if ( toke . equalsIgnoreCase ( \"-ncml\" ) ) ncml = true ; if ( toke . equalsIgnoreCase ( \"-cdl\" ) || toke . equalsIgnoreCase ( \"-strict\" ) ) strict = true ; if ( toke . equalsIgnoreCase ( \"-v\" ) && stoke . hasMoreTokens ( ) ) varNames = stoke . nextToken ( ) ; if ( toke . equalsIgnoreCase ( \"-datasetname\" ) && stoke . hasMoreTokens ( ) ) { fakeDataset = stoke . nextToken ( ) ; if ( fakeDataset . length ( ) == 0 ) fakeDataset = null ; if ( fakeDataset != null ) { trueDataset = nc . getLocation ( ) ; nc . setLocation ( fakeDataset ) ; } } } } boolean ok = print ( nc , out , showValues , ncml , strict , varNames , ct ) ; if ( trueDataset != null && fakeDataset != null ) nc . setLocation ( trueDataset ) ; return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ncdump - like print of netcdf file . [CODESPLIT] public static boolean print ( String filename , Writer out , boolean showAll , boolean showCoords , boolean ncml , boolean strict , String varNames , ucar . nc2 . util . CancelTask ct ) throws IOException { try ( NetcdfFile nc = NetcdfDataset . openFile ( filename , ct ) ) { return print ( nc , out , showAll , showCoords , ncml , strict , varNames , ct ) ; } catch ( java . io . FileNotFoundException e ) { out . write ( \"file not found= \" ) ; out . write ( filename ) ; out . flush ( ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ncdump - like print of netcdf file . [CODESPLIT] public static boolean print ( NetcdfFile nc , Writer out , boolean showAll , boolean showCoords , boolean ncml , boolean strict , String varNames , ucar . nc2 . util . CancelTask ct ) throws IOException { WantValues showValues = WantValues . none ; if ( showAll ) showValues = WantValues . all ; else if ( showCoords ) showValues = WantValues . coordsOnly ; return print ( nc , out , showValues , ncml , strict , varNames , ct ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ncdump - like print of netcdf file . [CODESPLIT] public static boolean print ( NetcdfFile nc , Writer out , WantValues showValues , boolean ncml , boolean strict , String varNames , ucar . nc2 . util . CancelTask ct ) throws IOException { boolean headerOnly = ( showValues == WantValues . none ) && ( varNames == null ) ; try { if ( ncml ) writeNcML ( nc , out , showValues , null ) ; // output schema in NcML else if ( headerOnly ) nc . writeCDL ( new PrintWriter ( out ) , strict ) ; // output schema in CDL form (like ncdump) else { PrintWriter ps = new PrintWriter ( out ) ; nc . toStringStart ( ps , strict ) ; Indent indent = new Indent ( 2 ) ; indent . incr ( ) ; ps . printf ( \"%n%sdata:%n\" , indent ) ; indent . incr ( ) ; if ( showValues == WantValues . all ) { // dump all data for ( Variable v : nc . getVariables ( ) ) { printArray ( v . read ( ) , v . getFullName ( ) , ps , indent , ct ) ; if ( ct != null && ct . isCancel ( ) ) return false ; } } else if ( showValues == WantValues . coordsOnly ) { // dump coordVars for ( Variable v : nc . getVariables ( ) ) { if ( v . isCoordinateVariable ( ) ) printArray ( v . read ( ) , v . getFullName ( ) , ps , indent , ct ) ; if ( ct != null && ct . isCancel ( ) ) return false ; } } if ( ( showValues != WantValues . all ) && ( varNames != null ) ) { // dump the list of variables StringTokenizer stoke = new StringTokenizer ( varNames , \";\" ) ; while ( stoke . hasMoreTokens ( ) ) { String varSubset = stoke . nextToken ( ) ; // variable name and optionally a subset if ( varSubset . indexOf ( ' ' ) >= 0 ) { // has a selector Array data = nc . readSection ( varSubset ) ; printArray ( data , varSubset , ps , indent , ct ) ; } else { // do entire variable Variable v = nc . findVariable ( varSubset ) ; if ( v == null ) { ps . print ( \" cant find variable: \" + varSubset + \"\\n   \" + usage ) ; continue ; } // dont print coord vars if they are already printed if ( ( showValues != WantValues . coordsOnly ) || v . isCoordinateVariable ( ) ) printArray ( v . read ( ) , v . getFullName ( ) , ps , indent , ct ) ; } if ( ct != null && ct . isCancel ( ) ) return false ; } } indent . decr ( ) ; indent . decr ( ) ; nc . toStringEnd ( ps ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; out . write ( e . getMessage ( ) ) ; out . flush ( ) ; return false ; } out . flush ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print all the data of the given Variable . [CODESPLIT] static public String printVariableData ( VariableIF v , ucar . nc2 . util . CancelTask ct ) throws IOException { Array data = v . read ( ) ; /* try {\n      data = v.isMemberOfStructure() ? v.readAllStructures(null, true) : v.read();\n    }\n    catch (InvalidRangeException ex) {\n      return ex.getMessage();\n    } */ StringWriter writer = new StringWriter ( 10000 ) ; printArray ( data , v . getFullName ( ) , new PrintWriter ( writer ) , new Indent ( 2 ) , ct ) ; return writer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a section of the data of the given Variable . [CODESPLIT] static public String printVariableDataSection ( Variable v , String sectionSpec , ucar . nc2 . util . CancelTask ct ) throws IOException , InvalidRangeException { Array data = v . read ( sectionSpec ) ; StringWriter writer = new StringWriter ( 20000 ) ; printArray ( data , v . getFullName ( ) , new PrintWriter ( writer ) , new Indent ( 2 ) , ct ) ; return writer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print contents of a StructureData . [CODESPLIT] static public void printStructureData ( PrintWriter out , StructureData sdata ) throws IOException { printStructureData ( out , sdata , new Indent ( 2 ) , null ) ; out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print array as undifferentiated sequence of values . [CODESPLIT] static public void printArrayPlain ( Array ma , PrintWriter out ) { ma . resetLocalIterator ( ) ; while ( ma . hasNext ( ) ) { out . print ( ma . next ( ) ) ; out . print ( ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print array to PrintWriter [CODESPLIT] static public void printArray ( Array array , PrintWriter pw ) { printArray ( array , null , null , pw , new Indent ( 2 ) , null , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the NcML representation for a file . Note that ucar . nc2 . dataset . NcMLWriter has a JDOM implementation for complete NcML . This method implements only the core NcML for plain ole netcdf files . [CODESPLIT] static public void writeNcML ( NetcdfFile ncfile , Writer writer , WantValues showValues , String url ) throws IOException { Preconditions . checkNotNull ( ncfile ) ; Preconditions . checkNotNull ( writer ) ; Preconditions . checkNotNull ( showValues ) ; Predicate < Variable > writeVarsPred ; switch ( showValues ) { case none : writeVarsPred = NcMLWriter . writeNoVariablesPredicate ; break ; case coordsOnly : writeVarsPred = NcMLWriter . writeCoordinateVariablesPredicate ; break ; case all : writeVarsPred = NcMLWriter . writeAllVariablesPredicate ; break ; default : String message = String . format ( \"CAN'T HAPPEN: showValues (%s) != null and checked all possible enum values.\" , showValues ) ; throw new AssertionError ( message ) ; } NcMLWriter ncmlWriter = new NcMLWriter ( ) ; ncmlWriter . setWriteVariablesPredicate ( writeVarsPred ) ; Element netcdfElement = ncmlWriter . makeNetcdfElement ( ncfile , url ) ; ncmlWriter . writeToWriter ( netcdfElement , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main program . <p > <strong > ucar . nc2 . NCdumpW filename [ - cdl | - ncml ] [ - c | - vall ] [ - v varName1 ; varName2 ; .. ] [ - v varName ( 0 : 1 : 12 ) ] < / strong > <p > where : <ul > <li > filename : path of any CDM readable file <li > cdl or ncml : output format is CDL or NcML <li > - vall : dump all variable data <li > - c : dump coordinate variable data <li > - v varName1 ; varName2 ; : dump specified variable ( s ) <li > - v varName ( 0 : 1 : 12 ) : dump specified variable section < / ul > Default is to dump the header info only . [CODESPLIT] public static void main ( String [ ] args ) { if ( args . length == 0 ) { System . out . println ( usage ) ; return ; } StringBuilder sbuff = new StringBuilder ( ) ; for ( String arg : args ) { sbuff . append ( arg ) ; sbuff . append ( \" \" ) ; } try { Writer writer = new BufferedWriter ( new OutputStreamWriter ( System . out , CDM . utf8Charset ) ) ; NCdumpW . print ( sbuff . toString ( ) , writer , null ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * from CF : false_easting ( false_northing ) : The value added to all abscissa ( ordinate ) values in the rectangular coordinates for a map projection . This value frequently is assigned to eliminate negative numbers . Expressed in the unit of the coordinate variable identified by the standard name projection_x_coordinate ( projection_y_coordinate ) . [CODESPLIT] static public double getFalseEastingScaleFactor ( NetcdfDataset ds , AttributeContainer ctv ) { String units = getGeoCoordinateUnits ( ds , ctv ) ; return getFalseEastingScaleFactor ( units ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a variable attribute as a double . [CODESPLIT] protected double readAttributeDouble ( AttributeContainer v , String attname , double defValue ) { Attribute att = v . findAttributeIgnoreCase ( attname ) ; if ( att == null ) return defValue ; if ( att . isString ( ) ) return Double . parseDouble ( att . getStringValue ( ) ) ; else return att . getNumericValue ( ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an attribute as double [ 2 ] . If only one value make second same as first . [CODESPLIT] protected double [ ] readAttributeDouble2 ( Attribute att ) { if ( att == null ) return null ; double [ ] val = new double [ 2 ] ; if ( att . isString ( ) ) { StringTokenizer stoke = new StringTokenizer ( att . getStringValue ( ) ) ; val [ 0 ] = Double . parseDouble ( stoke . nextToken ( ) ) ; val [ 1 ] = stoke . hasMoreTokens ( ) ? Double . parseDouble ( stoke . nextToken ( ) ) : val [ 0 ] ; } else { val [ 0 ] = att . getNumericValue ( ) . doubleValue ( ) ; val [ 1 ] = ( att . getLength ( ) > 1 ) ? att . getNumericValue ( 1 ) . doubleValue ( ) : val [ 0 ] ; } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Parameter to a CoordinateTransform . Make sure that the variable exists . If readData is true read the data and use it as the value of the parameter otherwise use the variable name as the value of the parameter . [CODESPLIT] protected boolean addParameter ( CoordinateTransform rs , String paramName , NetcdfFile ds , String varNameEscaped ) { if ( null == ( ds . findVariable ( varNameEscaped ) ) ) { if ( null != errBuffer ) errBuffer . format ( \"CoordTransBuilder %s: no Variable named %s%n\" , getTransformName ( ) , varNameEscaped ) ; return false ; } rs . addParameter ( new Parameter ( paramName , varNameEscaped ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the earth radius in km from the attribute earth_radius . Normally this is in meters convert to km if its > 10 000 . Use Earth . getRadius () as default . [CODESPLIT] protected double getEarthRadiusInKm ( AttributeContainer ctv ) { double earth_radius = readAttributeDouble ( ctv , CF . EARTH_RADIUS , Earth . getRadius ( ) ) ; if ( earth_radius > 10000.0 ) earth_radius *= .001 ; return earth_radius ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "try problem logs [CODESPLIT] public static void main ( String [ ] args ) throws IOException { AccessLogParser p = new AccessLogParser ( ) ; String line = \"24.18.236.132 - - [04/Feb/2011:17:49:03 -0700] \\\"GET /thredds/fileServer//nexrad/level3/N0R/YUX/20110205/Level3_YUX_N0R_20110205_0011.nids \\\" 200 10409 \\\"-\\\" \\\"-\\\" 17\" ; Matcher m = regPattern . matcher ( line ) ; System . out . printf ( \"%s %s%n\" , m . matches ( ) , m ) ; for ( int i = 0 ; i < m . groupCount ( ) ; i ++ ) { System . out . println ( \" \" + i + \" \" + m . group ( i ) ) ; } LogReader . Log log = p . parseLog ( line ) ; System . out . printf ( \"%s%n\" , log ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Finish constructing after all elements have been added . [CODESPLIT] public boolean finish ( ) { if ( serviceName != null ) { this . service = dataset . findService ( serviceName ) ; if ( this . service == null ) log . append ( \"**InvAccess in (\" ) . append ( dataset . getFullName ( ) ) . append ( \"): has unknown service named (\" ) . append ( serviceName ) . append ( \")\\n\" ) ; } // check urlPath is ok try { new java . net . URI ( urlPath ) ; } catch ( java . net . URISyntaxException e ) { log . append ( \"**InvAccess in (\" ) . append ( dataset . getFullName ( ) ) . append ( \"):\\n\" + \"   urlPath= \" ) . append ( urlPath ) . append ( \")\\n  URISyntaxException=\" ) . append ( e . getMessage ( ) ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////// [CODESPLIT] boolean check ( StringBuilder out , boolean show ) { boolean isValid = true ; if ( log . length ( ) > 0 ) { isValid = false ; out . append ( log ) ; } if ( getService ( ) == null ) { out . append ( \"**InvAccess in (\" ) . append ( dataset . getFullName ( ) ) . append ( \"): with urlPath= (\" ) . append ( urlPath ) . append ( \") has no valid service\\n\" ) ; isValid = false ; } else if ( getStandardUrlName ( ) == null ) { out . append ( \"**InvAccess in (\" ) . append ( dataset . getFullName ( ) ) . append ( \"): with urlPath= (\" ) . append ( urlPath ) . append ( \") has invalid URL\\n\" ) ; isValid = false ; } if ( show ) System . out . println ( \"   access \" + urlPath + \" valid = \" + isValid ) ; return isValid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DataCursor API ( Except as Implemented in AbstractCursor ) [CODESPLIT] @ Override public Object read ( Index index ) throws DapException { return read ( DapUtil . indexToSlices ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support methods [CODESPLIT] protected Object readAtomic ( List < Slice > slices ) throws DapException { if ( slices == null ) throw new DapException ( \"DataCursor.read: null set of slices\" ) ; assert this . scheme == Scheme . ATOMIC ; DapVariable atomvar = ( DapVariable ) getTemplate ( ) ; int rank = atomvar . getRank ( ) ; assert slices != null && ( ( rank == 0 && slices . size ( ) == 1 ) || ( slices . size ( ) == rank ) ) ; DapType basetype = atomvar . getBaseType ( ) ; return readAs ( atomvar , basetype , slices ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow specification of basetype to use ; used for enumerations [CODESPLIT] protected Object readAs ( DapVariable atomvar , DapType basetype , List < Slice > slices ) throws DapException { if ( basetype . getTypeSort ( ) == TypeSort . Enum ) { // short circuit this case basetype = ( ( DapEnumeration ) basetype ) . getBaseType ( ) ; return readAs ( atomvar , basetype , slices ) ; } long count = DapUtil . sliceProduct ( slices ) ; Object result = LibTypeFcns . newVector ( basetype , count ) ; Odometer odom = Odometer . factory ( slices ) ; if ( DapUtil . isContiguous ( slices ) && basetype . isFixedSize ( ) ) readContig ( slices , basetype , count , odom , result ) ; else readOdom ( slices , basetype , odom , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "D4Cursor Extensions [CODESPLIT] public D4Cursor setElements ( D4Cursor [ ] instances ) { if ( ! ( getScheme ( ) == Scheme . SEQARRAY || getScheme ( ) == Scheme . STRUCTARRAY ) ) throw new IllegalStateException ( \"Adding element to !(structure|sequence array) object\" ) ; DapVariable var = ( DapVariable ) getTemplate ( ) ; this . elements = instances ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "actions that control the dataset [CODESPLIT] private void makeActionsDataset ( ) { /*  choose local dataset\n    AbstractAction chooseLocalDatasetAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        String filename = fileChooser.chooseFilename();\n        if (filename == null) return;\n\n        Dataset invDs;\n        try {     // DatasetNode parent, String name, Map<String, Object> flds, List< AccessBuilder > accessBuilders, List< DatasetBuilder > datasetBuilders\n          Map<String, Object> flds = new HashMap<>();\n          flds.put(Dataset.FeatureType, FeatureType.GRID.toString());\n          flds.put(Dataset.ServiceName, ServiceType.File.toString());  // bogus\n          invDs = new Dataset(null, filename, flds, null, null);\n          setDataset(invDs);\n\n        } catch (Exception ue) {\n          JOptionPane.showMessageDialog(CoverageDisplay.this, \"Invalid filename = <\" + filename + \">\\n\" + ue.getMessage());\n          ue.printStackTrace();\n        }\n      }\n    };\n    BAMutil.setActionProperties(chooseLocalDatasetAction, \"FileChooser\", \"open Local dataset...\", false, 'L', -1);\n\n    /* saveDatasetAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        String fname = controller.getDatasetName();\n        if (fname != null) {\n          savedDatasetList.add( fname);\n          BAMutil.addActionToMenu( savedDatasetMenu, new DatasetAction( fname), 0);\n        }\n      }\n    };\n    BAMutil.setActionProperties( saveDatasetAction, null, \"save dataset\", false, 'S', 0);\n    */ // Configure chooseProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) . setVisible ( ) ; } } ; BAMutil . setActionProperties ( chooseProjectionAction , null , \"Projection Manager...\" , false , ' ' , 0 ) ; saveCurrentProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) ; // set the bounding box ProjectionImpl proj = navPanel . getProjectionImpl ( ) . constructCopy ( ) ; proj . setDefaultMapArea ( navPanel . getMapArea ( ) ) ; //if (debug) System.out.println(\" GV save projection \"+ proj); // projManage.setMap(renderAll.get(\"Map\"));   LOOK! //projManager.saveProjection( proj); } } ; BAMutil . setActionProperties ( saveCurrentProjectionAction , null , \"save Current Projection\" , false , ' ' , 0 ) ; /* chooseColorScaleAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        if (null == csManager) // lazy instantiation\n          makeColorScaleManager();\n        csManager.show();\n      }\n    };\n    BAMutil.setActionProperties( chooseColorScaleAction, null, \"ColorScale Manager...\", false, 'C', 0);\n\n    */ // redraw redrawAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { repaint ( ) ; start ( true ) ; draw ( true ) ; } } ; BAMutil . setActionProperties ( redrawAction , \"alien\" , \"RedRaw\" , false , ' ' , 0 ) ; showDatasetInfoAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( infoWindow == null ) { datasetInfoTA = new TextHistoryPane ( ) ; infoWindow = new IndependentWindow ( \"Dataset Information\" , BAMutil . getImage ( \"GDVs\" ) , datasetInfoTA ) ; infoWindow . setSize ( 700 , 700 ) ; infoWindow . setLocation ( 100 , 100 ) ; } datasetInfoTA . clear ( ) ; if ( coverageDataset != null ) { Formatter f = new Formatter ( ) ; coverageDataset . toString ( f ) ; datasetInfoTA . appendLine ( f . toString ( ) ) ; } else { datasetInfoTA . appendLine ( \"No coverageDataset loaded\" ) ; } datasetInfoTA . gotoTop ( ) ; infoWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showDatasetInfoAction , \"Information\" , \"Show info...\" , false , ' ' , - 1 ) ; /*showNcMLAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        if (ncmlWindow == null) {\n          ncmlTA = new TextHistoryPane();\n          ncmlWindow = new IndependentWindow(\"Dataset NcML\", BAMutil.getImage( \"GDVs\"), ncmlTA);\n          ncmlWindow.setSize(700,700);\n          ncmlWindow.setLocation(200, 70);\n        }\n\n        ncmlTA.clear();\n        //datasetInfoTA.appendLine( \"GeoGrid XML for \"+ controller.getDatasetName()+\"\\n\");\n        ncmlTA.appendLine( controller.getNcML());\n        ncmlTA.gotoTop();\n        ncmlWindow.show();\n      }\n    };\n    BAMutil.setActionProperties( showNcMLAction, null, \"Show NcML...\", false, 'X', -1);  */ /* showGridDatasetInfoAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        if (ncmlWindow == null) {\n          ncmlTA = new TextHistoryPane();\n          ncmlWindow = new IndependentWindow(\"Dataset NcML\", BAMutil.getImage( \"GDVs\"), ncmlTA);\n          ncmlWindow.setSize(700,700);\n          ncmlWindow.setLocation(200, 70);\n        }\n\n        ncmlTA.clear();\n        //datasetInfoTA.appendLine( \"GeoGrid XML for \"+ controller.getDatasetName()+\"\\n\");\n        ncmlTA.appendLine( controller.getDatasetXML());\n        ncmlTA.gotoTop();\n        ncmlWindow.show();\n      }\n    };\n    BAMutil.setActionProperties( showGridDatasetInfoAction, null, \"Show GridDataset Info XML...\", false, 'X', -1);\n\n      // show netcdf dataset Table\n    /* showNetcdfDatasetAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        NetcdfDataset netcdfDataset = controller.getNetcdfDataset();\n        if (null != netcdfDataset) {\n          try {\n            dsTable.setDataset(netcdfDataset, null);\n          } catch (IOException e1) {\n            e1.printStackTrace();\n            return;\n          }\n          dsDialog.show();\n        }\n      }\n    };\n    BAMutil.setActionProperties( showNetcdfDatasetAction, \"netcdf\", \"NetcdfDataset Table Info...\", false, 'D', -1);  */ minmaxHorizAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . horiz ) ; setDataMinMaxType ( ColorScale . MinMaxType . horiz ) ; } } ; BAMutil . setActionProperties ( minmaxHorizAction , null , \"Horizontal plane\" , false , ' ' , 0 ) ; minmaxLogAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . log ) ; setDataMinMaxType ( ColorScale . MinMaxType . log ) ; } } ; BAMutil . setActionProperties ( minmaxLogAction , null , \"log horiz plane\" , false , ' ' , 0 ) ; /* minmaxVolAction =  new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        csDataMinMax.setSelectedIndex(GridRenderer.VOL_MinMaxType);\n        controller.setDataMinMaxType(GridRenderer.MinMaxType.vert;\n      }\n    };\n    BAMutil.setActionProperties( minmaxVolAction, null, \"Grid volume\", false, 'G', 0); */ minmaxHoldAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . hold ) ; setDataMinMaxType ( ColorScale . MinMaxType . hold ) ; } } ; BAMutil . setActionProperties ( minmaxHoldAction , null , \"Hold scale constant\" , false , ' ' , 0 ) ; fieldLoopAction = new LoopControlAction ( fieldChooser ) ; levelLoopAction = new LoopControlAction ( levelChooser ) ; timeLoopAction = new LoopControlAction ( timeChooser ) ; runtimeLoopAction = new LoopControlAction ( runtimeChooser ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the actions can then be attached to buttcons menus etc [CODESPLIT] private void makeActions ( ) { boolean state ; dataProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; if ( state ) { ProjectionImpl dataProjection = coverageRenderer . getDataProjection ( ) ; if ( null != dataProjection ) setProjection ( dataProjection ) ; } else { setProjection ( new LatLonProjection ( ) ) ; } } } ; BAMutil . setActionProperties ( dataProjectionAction , \"DataProjection\" , \"use Data Projection\" , true , ' ' , 0 ) ; dataProjectionAction . putValue ( BAMutil . STATE , true ) ; // contouring drawBBAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawBB ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( drawBBAction , \"Contours\" , \"draw bounding box\" , true , ' ' , 0 ) ; drawBBAction . putValue ( BAMutil . STATE , false ) ; // draw horiz drawHorizAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; drawHorizOn = state . booleanValue ( ) ; setDrawHorizAndVert ( drawHorizOn , drawVertOn ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( drawHorizAction , \"DrawHoriz\" , \"draw horizontal\" , true , ' ' , 0 ) ; state = store . getBoolean ( \"drawHorizAction\" , true ) ; drawHorizAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; drawHorizOn = state ; // draw Vert drawVertAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; drawVertOn = state . booleanValue ( ) ; setDrawHorizAndVert ( drawHorizOn , drawVertOn ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( drawVertAction , \"DrawVert\" , \"draw vertical\" , true , ' ' , 0 ) ; state = store . getBoolean ( \"drawVertAction\" , false ) ; drawVertAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; drawVertOn = state ; // show grid showGridAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawGridLines ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( showGridAction , \"Grid\" , \"show grid lines\" , true , ' ' , 0 ) ; state = store . getBoolean ( \"showGridAction\" , false ) ; showGridAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; coverageRenderer . setDrawGridLines ( state ) ; // contouring showContoursAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawContours ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( showContoursAction , \"Contours\" , \"show contours\" , true , ' ' , 0 ) ; state = store . getBoolean ( \"showContoursAction\" , false ) ; showContoursAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; coverageRenderer . setDrawContours ( state ) ; // contouring labels showContourLabelsAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawContourLabels ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( showContourLabelsAction , \"ContourLabels\" , \"show contour labels\" , true , ' ' , 0 ) ; state = store . getBoolean ( \"showContourLabelsAction\" , false ) ; showContourLabelsAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; coverageRenderer . setDrawContourLabels ( state ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save all data in the PersistentStore [CODESPLIT] public void save ( ) { //store.putInt( \"vertSplit\", splitDraw.getDividerLocation()); store . putBoolean ( \"navToolbarAction\" , ( ( Boolean ) navToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( \"moveToolbarAction\" , ( ( Boolean ) moveToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; if ( projManager != null ) projManager . storePersistentData ( ) ; /* if (csManager != null)\n      csManager.storePersistentData();\n    if (sysConfigDialog != null)\n      sysConfigDialog.storePersistentData(); */ //dsTable.save(); //dsTable.getPrefs().putBeanObject(\"DialogBounds\", dsDialog.getBounds()); store . put ( GEOTIFF_FILECHOOSER_DEFAULTDIR , geotiffFileChooser . getCurrentDirectory ( ) ) ; store . putBeanObject ( LastMapAreaName , navPanel . getMapArea ( ) ) ; store . putBeanObject ( LastProjectionName , navPanel . getProjectionImpl ( ) ) ; //if (gridDataset != null) //  store.put(LastDatasetName, gridDataset.getTitle()); store . putBeanObject ( ColorScaleName , colorScale ) ; store . putBoolean ( \"showGridAction\" , ( ( Boolean ) showGridAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( \"showContoursAction\" , ( ( Boolean ) showContoursAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( \"showContourLabelsAction\" , ( ( Boolean ) showContourLabelsAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private boolean chooseDataset ( String url ) { InvDataset invDs = new InvDatasetImpl ( fname ServerType . NETCDF ) ; return chooseDataset ( invDs ) ; } [CODESPLIT] private void setSelected ( boolean b ) { selected = b ; //showGridTableAction.setEnabled(b); //showNcMLAction.setEnabled(b); //showNcMLAction.setEnabled(b); //showNetcdfDatasetAction.setEnabled(b); //showGridDatasetInfoAction.setEnabled(b); //showNetcdfXMLAction.setEnabled( b); navToolbarAction . setEnabled ( b ) ; moveToolbarAction . setEnabled ( b ) ; //controller.showGridAction.setEnabled( b); //controller.showContoursAction.setEnabled( b); //controller.showContourLabelsAction.setEnabled( b); redrawAction . setEnabled ( b ) ; minmaxHorizAction . setEnabled ( b ) ; minmaxLogAction . setEnabled ( b ) ; minmaxHoldAction . setEnabled ( b ) ; fieldLoopAction . setEnabled ( b ) ; levelLoopAction . setEnabled ( b ) ; timeLoopAction . setEnabled ( b ) ; runtimeLoopAction . setEnabled ( b ) ; navPanel . setEnabledActions ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assume that its done in the event thread [CODESPLIT] boolean showDataset ( ) { // temp kludge for initialization Iterable < Coverage > grids = coverageDataset . getCoverages ( ) ; currentField = grids . iterator ( ) . next ( ) ; // first currentSlice = 0 ; currentLevel = 0 ; currentTime = 0 ; currentEnsemble = 0 ; currentRunTime = 0 ; eventsOK = false ; // dont let this trigger redraw this . dataState = coverageRenderer . setCoverage ( coverageDataset , currentField ) ; coverageRenderer . setDataProjection ( currentField . getCoordSys ( ) . getProjection ( ) ) ; // setFields(grids); setField ( currentField ) ; // LOOK if possible, change the projection and the map area to one that fits this dataset ProjectionImpl dataProjection = currentField . getCoordSys ( ) . getProjection ( ) ; if ( dataProjection != null ) setProjection ( dataProjection ) ; // ready to draw //draw(true); // events now ok eventsOK = true ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void drawV ( boolean immediate ) { if ( !startOK ) return ; ScaledPanel drawArea = vertPanel . getDrawArea () ; Graphics2D gV = drawArea . getBufferedImageGraphics () ; if ( gV == null ) return ; [CODESPLIT] private synchronized void redrawLater ( ) { //redrawComplete |= complete; boolean already = redrawTimer . isRunning ( ) ; if ( debugThread ) System . out . println ( \"redrawLater isRunning= \" + already ) ; if ( already ) redrawTimer . restart ( ) ; else redrawTimer . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets parameter table then grib1 parameter based on number . [CODESPLIT] public final GridParameter getParameter ( GridRecord gr ) { String name = gr . getParameterName ( ) ; GridParameter gp = GempakGridParameterTable . getParameter ( name ) ; if ( gp != null ) { return gp ; } return new GridParameter ( 0 , name , name , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is this a PositiveUp VerticalCoordinate . [CODESPLIT] public final boolean isPositiveUp ( GridRecord gr ) { int type = gr . getLevelType1 ( ) ; if ( ( type == 1 ) || ( type == 5 ) ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : observedProperty [CODESPLIT] public static ReferenceType initObservedProperty ( ReferenceType observedProperty , VariableSimpleIF dataVar ) { // @xlink:title observedProperty . setTitle ( dataVar . getShortName ( ) ) ; return observedProperty ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct the Action that is called when this bean s menu item / buttcon is selected . Typically this routine is only called once when the bean is added . The Action itself is called whenever the menu / buttcon is selected . [CODESPLIT] public javax . swing . Action getAction ( ) { AbstractAction useMap = new AbstractAction ( getActionName ( ) , getIcon ( ) ) { public void actionPerformed ( java . awt . event . ActionEvent e ) { firePropertyChangeEvent ( this , \"Renderer\" , null , getRenderer ( ) ) ; } } ; useMap . putValue ( Action . SHORT_DESCRIPTION , getActionDesc ( ) ) ; return useMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience routine to make a button with a popup menu attached . to use : <pre > thredds . ui . PopupMenu mapBeanMenu = MapBean . makeMapSelectButton () ; AbstractButton butt = ( AbstractButton ) mapBeanMenu . getParentComponent () ; addToMenu ( butt ) ; [CODESPLIT] static public PopupMenu makeMapSelectButton ( ) { AbstractAction mapSelectAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { //System.out.println(\"mapSelectAction\");\r //mapPopup.show();\r } } ; BAMutil . setActionProperties ( mapSelectAction , \"WorldMap\" , \"select map\" , false , ' ' , - 1 ) ; AbstractButton mapSelectButton = BAMutil . makeButtconFromAction ( mapSelectAction ) ; PopupMenu mapPopup = new PopupMenu ( mapSelectButton , \"Select Map\" , true ) ; return mapPopup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts numeric values from this unit to another unit . [CODESPLIT] public double [ ] convertTo ( final double [ ] amounts , final Unit outputUnit ) throws ConversionException { return convertTo ( amounts , outputUnit , new double [ amounts . length ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts numeric values from this unit to another unit . [CODESPLIT] public float [ ] convertTo ( final float [ ] input , final Unit outputUnit , final float [ ] output ) throws ConversionException { return getConverterTo ( outputUnit ) . convert ( input , output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if numeric values in this unit are convertible with another unit . [CODESPLIT] public boolean isCompatible ( final Unit that ) { // jeffm: for some reason just calling getDerivedUnit().equals(...) // with jikes 1.1.7 as the compiler causes the jvm to crash. // The Unit u1=... does not crash. final Unit u1 = getDerivedUnit ( ) ; return u1 . equals ( that . getDerivedUnit ( ) ) ; // return getDerivedUnit().equals(that.getDerivedUnit()); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a label for a quantity in this unit . [CODESPLIT] public String makeLabel ( final String quantityID ) { final StringBuilder buf = new StringBuilder ( quantityID ) ; if ( quantityID . contains ( \" \" ) ) { buf . insert ( 0 , ' ' ) . append ( ' ' ) ; } buf . append ( ' ' ) ; final int start = buf . length ( ) ; buf . append ( toString ( ) ) ; if ( buf . substring ( start ) . indexOf ( ' ' ) != - 1 ) { buf . insert ( start , ' ' ) . append ( ' ' ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : featureOfInterest / wml2 : MonitoringPoint [CODESPLIT] public static MonitoringPointType initMonitoringPointType ( MonitoringPointType monitoringPoint , StationTimeSeriesFeature stationFeat ) { // @gml:id String id = MarshallingUtil . createIdForType ( MonitoringPointType . class ) ; monitoringPoint . setId ( id ) ; // gml:identifier NcCodeWithAuthorityType . initIdentifier ( monitoringPoint . addNewIdentifier ( ) , stationFeat ) ; // gml:description NcStringOrRefType . initDescription ( monitoringPoint . addNewDescription ( ) , stationFeat ) ; if ( monitoringPoint . getDescription ( ) . getStringValue ( ) == null || monitoringPoint . getDescription ( ) . getStringValue ( ) . isEmpty ( ) ) { monitoringPoint . unsetDescription ( ) ; } // sam:sampledFeature monitoringPoint . addNewSampledFeature ( ) ; monitoringPoint . setNilSampledFeatureArray ( 0 ) ; // Set the \"sam:sampledFeature\" we just added to nil. // sams:shape NcShapeType . initShape ( monitoringPoint . addNewShape ( ) , stationFeat ) ; return monitoringPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a Variable name and a beginning index and end index returns a list of polygon ( inclusive on both sides ) [CODESPLIT] public List < Polygon > getPolygons ( String name , int indexBegin , int indexEnd ) { return builder . getPolygons ( name , indexBegin , indexEnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a Variable name and a beginning index and end index returns a list of lines ( inclusive on both sides ) [CODESPLIT] public List < Line > getLines ( String name , int indexBegin , int indexEnd ) { return builder . getLines ( name , indexBegin , indexEnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a Variable name and a beginning index and end index returns a list of points ( inclusive on both sides ) [CODESPLIT] public List < Point > getPoints ( String name , int indexBegin , int indexEnd ) { return builder . getPoints ( name , indexBegin , indexEnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Position file at bitOffset from startPos [CODESPLIT] public void setBitOffset ( int bitOffset ) throws IOException { if ( bitOffset % 8 == 0 ) { raf . seek ( startPos + bitOffset / 8 ) ; bitPos = 0 ; bitBuf = 0 ; } else { raf . seek ( startPos + bitOffset / 8 ) ; bitPos = 8 - ( bitOffset % 8 ) ; bitBuf = ( byte ) raf . read ( ) ; bitBuf &= 0xff >> ( 8 - bitPos ) ; // mask off consumed bits      \r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the next nb bits and return an Unsigned Long . [CODESPLIT] public long bits2UInt ( int nb ) throws IOException { assert nb <= 64 ; assert nb >= 0 ; long result = 0 ; int bitsLeft = nb ; while ( bitsLeft > 0 ) { // we ran out of bits - fetch the next byte...\r if ( bitPos == 0 ) { bitBuf = nextByte ( ) ; bitPos = BIT_LENGTH ; } // -- retrieve bit from current byte ----------\r // how many bits to read from the current byte\r int size = Math . min ( bitsLeft , bitPos ) ; // move my part to start\r int myBits = bitBuf >> ( bitPos - size ) ; // mask-off sign-extending\r myBits &= BYTE_BITMASK ; // mask-off bits of next value\r myBits &= ~ ( BYTE_BITMASK << size ) ; // -- put bit to result ----------------------\r // where to place myBits inside of result\r int shift = bitsLeft - size ; assert shift >= 0 ; // put it there\r result |= myBits << shift ; // -- put bit to result ----------------------\r // update information on what we consumed\r bitsLeft -= size ; bitPos -= size ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the next nb bits and return an Signed Long . [CODESPLIT] public long bits2SInt ( int nb ) throws IOException { long result = bits2UInt ( nb ) ; // check if we're negative\r if ( getBit ( result , nb ) ) { // it's negative! reset leading bit\r result = setBit ( result , nb , false ) ; // build 2's-complement\r result = ~ result & LONG_BITMASK ; result = result + 1 ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a connection to the DODS server . [CODESPLIT] private void openConnection ( String urlString , Command command ) throws IOException , DAP2Exception { InputStream is = null ; try { try ( HTTPMethod method = HTTPFactory . Get ( _session , urlString ) ) { if ( acceptCompress ) method . setCompression ( \"deflate,gzip\" ) ; // enable sessions if ( allowSessions ) method . setUseSessions ( true ) ; int statusCode ; for ( ; ; ) { statusCode = method . execute ( ) ; if ( statusCode != HttpStatus . SC_SERVICE_UNAVAILABLE ) break ; Thread . sleep ( 5000 ) ; System . err . println ( \"Service Unavailable\" ) ; } // debug // if (debugHeaders) ucar.httpservices.HttpClientManager.showHttpRequestInfo(f, method); if ( statusCode == HttpStatus . SC_NOT_FOUND ) { throw new DAP2Exception ( DAP2Exception . NO_SUCH_FILE , method . getStatusText ( ) + \": \" + urlString ) ; } if ( statusCode == HttpStatus . SC_UNAUTHORIZED || statusCode == HttpStatus . SC_FORBIDDEN ) { throw new InvalidCredentialsException ( method . getStatusText ( ) ) ; } if ( statusCode != HttpStatus . SC_OK ) { throw new DAP2Exception ( \"Method failed:\" + method . getStatusText ( ) + \" on URL= \" + urlString ) ; } // Get the response body. is = method . getResponseAsStream ( ) ; // check if its an error Header header = method . getResponseHeader ( \"Content-Description\" ) ; if ( header != null && ( header . getValue ( ) . equals ( \"dods-error\" ) || header . getValue ( ) . equals ( \"dods_error\" ) ) ) { // create server exception object DAP2Exception ds = new DAP2Exception ( ) ; // parse the Error object from stream and throw it ds . parse ( is ) ; throw ds ; } ver = new ServerVersion ( method ) ; checkHeaders ( method ) ; // check for deflator Header h = method . getResponseHeader ( \"content-encoding\" ) ; String encoding = ( h == null ) ? null : h . getValue ( ) ; //if (encoding != null) LogStream.out.println(\"encoding= \" + encoding); if ( encoding != null && encoding . equals ( \"deflate\" ) ) { is = new BufferedInputStream ( new InflaterInputStream ( is ) , 1000 ) ; if ( showCompress ) System . out . printf ( \"deflate %s%n\" , urlString ) ; } else if ( encoding != null && encoding . equals ( \"gzip\" ) ) { is = new BufferedInputStream ( new GZIPInputStream ( is ) , 1000 ) ; if ( showCompress ) System . out . printf ( \"gzip %s%n\" , urlString ) ; } else { if ( showCompress ) System . out . printf ( \"none %s%n\" , urlString ) ; } command . process ( is ) ; } } catch ( IOException | DAP2Exception e ) { throw e ; } catch ( Exception e ) { Util . check ( e ) ; //e.printStackTrace(); throw new DAP2Exception ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the DAS object from the dataset referenced by this object s URL . The DAS object is referred to by appending . das to the end of a DODS URL . [CODESPLIT] public DAS getDAS ( ) throws IOException , DAP2Exception { DASCommand command = new DASCommand ( ) ; if ( filePath != null ) { // url was file: File daspath = new File ( filePath + \".das\" ) ; // See if the das file exists if ( daspath . canRead ( ) ) { try ( FileInputStream is = new FileInputStream ( daspath ) ) { command . process ( is ) ; } } } else if ( stream != null ) { command . process ( stream ) ; } else { // assume url is remote try { openConnection ( urlString + \".das\" + getCompleteCE ( projString , selString ) , command ) ; } catch ( DAP2Exception de ) { //if(de.getErrorCode() != DAP2Exception.NO_SUCH_FILE) //throw de;  // rethrow } } return command . das ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the DDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . dds to the end of a OPeNDAP URL . [CODESPLIT] public DDS getDDS ( String CE ) throws IOException , ParseException , DAP2Exception { DDSCommand command = new DDSCommand ( ) ; command . setURL ( CE == null || CE . length ( ) == 0 ? urlString : urlString + \"?\" + CE ) ; if ( filePath != null ) { try ( FileInputStream is = new FileInputStream ( filePath + \".dds\" ) ) { command . process ( is ) ; } } else if ( stream != null ) { command . process ( stream ) ; } else { // must be a remote url openConnection ( urlString + \".dds\" + ( getCompleteCE ( CE ) ) , command ) ; } return command . dds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use some sense when assembling the CE . Since this DConnect object may have constructed using a CE any new CE will have to be integrated into it for subsequent requests . Try to do this in a sensible manner! [CODESPLIT] private String getCompleteCE ( String CE ) { String localProjString = null ; String localSelString = null ; if ( CE == null ) return \"\" ; //remove any leading '?' if ( CE . startsWith ( \"?\" ) ) CE = CE . substring ( 1 ) ; int selIndex = CE . indexOf ( ' ' ) ; if ( selIndex == 0 ) { localProjString = \"\" ; localSelString = CE ; } else if ( selIndex > 0 ) { localSelString = CE . substring ( selIndex ) ; localProjString = CE . substring ( 0 , selIndex ) ; } else { // selIndex < 0 localProjString = CE ; localSelString = \"\" ; } String ce = projString ; if ( ! localProjString . equals ( \"\" ) ) { if ( ! ce . equals ( \"\" ) && localProjString . indexOf ( ' ' ) != 0 ) ce += \",\" ; ce += localProjString ; } if ( ! selString . equals ( \"\" ) ) { if ( selString . indexOf ( ' ' ) != 0 ) ce += \"&\" ; ce += selString ; } if ( ! localSelString . equals ( \"\" ) ) { if ( localSelString . indexOf ( ' ' ) != 0 ) ce += \"&\" ; ce += localSelString ; } if ( ce . length ( ) > 0 ) ce = \"?\" + ce ; if ( false ) { DAPNode . log . debug ( \"projString: '\" + projString + \"'\" ) ; DAPNode . log . debug ( \"localProjString: '\" + localProjString + \"'\" ) ; DAPNode . log . debug ( \"selString: '\" + selString + \"'\" ) ; DAPNode . log . debug ( \"localSelString: '\" + localSelString + \"'\" ) ; DAPNode . log . debug ( \"Complete CE: \" + ce ) ; } return ce ; // escaping will happen elsewhere }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ALternate interface to getCompleteCE ( String ce ) [CODESPLIT] private String getCompleteCE ( String proj , String sel ) { if ( proj != null && proj . length ( ) == 0 ) proj = \"\" ; // canonical if ( sel != null && sel . length ( ) == 0 ) sel = null ; // canonical StringBuilder buf = new StringBuilder ( ) ; if ( proj . startsWith ( \"?\" ) ) buf . append ( proj . substring ( 1 ) ) ; else buf . append ( proj ) ; if ( sel != null ) { if ( sel . startsWith ( \"&\" ) ) buf . append ( sel ) ; else { buf . append ( \"&\" ) ; buf . append ( sel ) ; } } return getCompleteCE ( buf . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the DDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . ddx to the end of a OPeNDAP URL . The server should send back a DDX ( A DDS in XML format ) which will get parsed here ( locally ) and a new DDS instantiated using the DDSXMLParser . [CODESPLIT] public DDS getDDX ( String CE ) throws IOException , ParseException , DDSException , DAP2Exception { DDXCommand command = new DDXCommand ( ) ; openConnection ( urlString + \".ddx\" + ( getCompleteCE ( CE ) ) , command ) ; return command . dds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the DataDDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . ddx to the end of a OPeNDAP URL . The server should send back a DDX ( A DDS in XML format ) which will get parsed here ( locally ) and a new DDS instantiated using the DDSXMLParser . [CODESPLIT] public DataDDS getDataDDX ( String CE ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { return getDataDDX ( CE , new DefaultFactory ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the DataDDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . ddx to the end of a OPeNDAP URL . The server should send back a DDX ( A DDS in XML format ) which will get parsed here ( locally ) and a new DDS instantiated using the DDSXMLParser . [CODESPLIT] public DataDDS getDataDDX ( String CE , BaseTypeFactory btf ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { DataDDXCommand command = new DataDDXCommand ( btf , this . ver ) ; openConnection ( urlString + \".ddx\" + ( getCompleteCE ( CE ) ) , command ) ; return command . dds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Data object from the dataset referenced by this object s URL given the constraint expression CE . Note that the Data object is really just a DDS object with data bound to the variables . The DDS will probably contain fewer variables ( and those might have different types ) than in the DDS returned by getDDS () because that method returns the entire DDS ( but without any data ) while this method returns only those variables listed in the projection part of the constraint expression . <p > Note that if CE is an empty String then the entire dataset will be returned unless a sticky CE has been specified in the constructor . [CODESPLIT] public DataDDS getData ( String CE , StatusUI statusUI , BaseTypeFactory btf ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { if ( CE != null && CE . trim ( ) . length ( ) == 0 ) CE = null ; DataDDS dds = new DataDDS ( ver , btf ) ; DataDDSCommand command = new DataDDSCommand ( dds , statusUI ) ; command . setURL ( urlString + ( CE == null ? \"\" : \"?\" + CE ) ) ; if ( filePath != null ) { // url is file: File dodspath = new File ( filePath + \".dods\" ) ; // See if the dods file exists if ( dodspath . canRead ( ) ) { /* WARNING: any constraints are ignored in reading the file */ try ( FileInputStream is = new FileInputStream ( dodspath ) ) { command . process ( is ) ; } } } else if ( stream != null ) { command . process ( stream ) ; } else { String urls = urlString + \".dods\" + ( CE == null ? \"\" : getCompleteCE ( CE ) ) ; openConnection ( urls , command ) ; } return command . dds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Data object from the dataset referenced by this object s URL given the constraint expression CE . Note that the Data object is really just a DDS object with data bound to the variables . The DDS will probably contain fewer variables ( and those might have different types ) than in the DDS returned by getDDS () because that method returns the entire DDS ( but without any data ) while this method returns only those variables listed in the projection part of the constraint expression . <p > Note that if CE is an empty String then the entire dataset will be returned unless a sticky CE has been specified in the constructor . [CODESPLIT] public DataDDS getData ( String CE , StatusUI statusUI ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { return getData ( CE , statusUI , new DefaultFactory ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the line between these two points cross the projection seam . [CODESPLIT] @ Override public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { // either point is infinite\r if ( ProjectionPointImpl . isInfinite ( pt1 ) || ProjectionPointImpl . isInfinite ( pt2 ) ) { return true ; } // opposite signed long lines\r double x1 = pt1 . getX ( ) - falseEasting ; double x2 = pt2 . getX ( ) - falseEasting ; return ( x1 * x2 < 0 ) && ( Math . abs ( x1 - x2 ) > earthRadius ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] @ Override public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double deltaLon_d = LatLonPointImpl . range180 ( latLon . getLongitude ( ) - centMeridian ) ; double fromLat_r = Math . toRadians ( latLon . getLatitude ( ) ) ; double toX = earthRadius * Math . toRadians ( deltaLon_d ) * Math . cos ( fromLat_r ) ; double toY = earthRadius * fromLat_r ; // p 247 Snyder\r result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint [CODESPLIT] @ Override public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double toLat_r = fromY / earthRadius ; double toLon_r ; if ( Misc . nearlyEquals ( Math . abs ( toLat_r ) , PI_OVER_2 , 1e-10 ) ) { toLat_r = toLat_r < 0 ? - PI_OVER_2 : + PI_OVER_2 ; toLon_r = Math . toRadians ( centMeridian ) ; // if lat == +- pi/2, set lon = centMeridian (Snyder 248)\r } else if ( Math . abs ( toLat_r ) < PI_OVER_2 ) { toLon_r = Math . toRadians ( centMeridian ) + fromX / ( earthRadius * Math . cos ( toLat_r ) ) ; } else { return INVALID ; // Projection point is off the map.\r } if ( Misc . nearlyEquals ( Math . abs ( toLon_r ) , PI , 1e-10 ) ) { toLon_r = toLon_r < 0 ? - PI : + PI ; } else if ( Math . abs ( toLon_r ) > PI ) { return INVALID ; // Projection point is off the map.\r } result . setLatitude ( Math . toDegrees ( toLat_r ) ) ; result . setLongitude ( Math . toDegrees ( toLon_r ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the points at which { @code projBB } intersects the map edge . [CODESPLIT] public List < ProjectionPoint > getMapEdgeIntercepts ( ProjectionRect projBB ) { List < ProjectionPoint > intercepts = new LinkedList <> ( ) ; for ( ProjectionPoint topIntercept : getMapEdgeInterceptsAtY ( projBB . getUpperRightPoint ( ) . getY ( ) ) ) { if ( pointIsBetween ( topIntercept , projBB . getUpperLeftPoint ( ) , projBB . getUpperRightPoint ( ) ) ) { intercepts . add ( topIntercept ) ; } } for ( ProjectionPoint rightIntercept : getMapEdgeInterceptsAtX ( projBB . getUpperRightPoint ( ) . getX ( ) ) ) { if ( pointIsBetween ( rightIntercept , projBB . getUpperRightPoint ( ) , projBB . getLowerRightPoint ( ) ) ) { intercepts . add ( rightIntercept ) ; } } for ( ProjectionPoint bottomIntercept : getMapEdgeInterceptsAtY ( projBB . getLowerLeftPoint ( ) . getY ( ) ) ) { if ( pointIsBetween ( bottomIntercept , projBB . getLowerLeftPoint ( ) , projBB . getLowerRightPoint ( ) ) ) { intercepts . add ( bottomIntercept ) ; } } for ( ProjectionPoint leftIntercept : getMapEdgeInterceptsAtX ( projBB . getLowerLeftPoint ( ) . getX ( ) ) ) { if ( pointIsBetween ( leftIntercept , projBB . getLowerLeftPoint ( ) , projBB . getUpperLeftPoint ( ) ) ) { intercepts . add ( leftIntercept ) ; } } return intercepts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the points at which the line { @code x = x0 } intersects the map edge . [CODESPLIT] public List < ProjectionPoint > getMapEdgeInterceptsAtX ( double x0 ) { List < ProjectionPoint > mapEdgeIntercepts = new LinkedList <> ( ) ; if ( projToLatLon ( x0 , falseNorthing ) == INVALID ) { // The line {@code x = x0} does not intersect the map.\r return mapEdgeIntercepts ; // Empty list.\r } double x0natural = x0 - falseEasting ; double limitLon_r = ( x0natural < 0 ) ? - PI : + PI ; double deltaLon_r = limitLon_r - Math . toRadians ( centMeridian ) ; // This formula comes from solving 30-1 for phi, and then plugging it into 30-2. See Snyder, p 247.\r double minY = - earthRadius * Math . acos ( x0natural / ( earthRadius * deltaLon_r ) ) ; double maxY = + earthRadius * Math . acos ( x0natural / ( earthRadius * deltaLon_r ) ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( x0 , minY + falseNorthing ) ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( x0 , maxY + falseNorthing ) ) ; return mapEdgeIntercepts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the points at which the line { @code y = y0 } intersects the map edge . [CODESPLIT] public List < ProjectionPoint > getMapEdgeInterceptsAtY ( double y0 ) { List < ProjectionPoint > mapEdgeIntercepts = new LinkedList <> ( ) ; if ( projToLatLon ( falseEasting , y0 ) == INVALID ) { // The line {@code y = y0} does not intersect the map.\r return mapEdgeIntercepts ; // Empty list.\r } double minX = getXAt ( y0 , - PI ) ; double maxX = getXAt ( y0 , + PI ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( minX , y0 ) ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( maxX , y0 ) ) ; return mapEdgeIntercepts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reference Date ( octet 13 - 17 ) . Reference time of data – date and time of start of averaging or accumulation period . [CODESPLIT] public final CalendarDate getReferenceDate ( ) { int century = getReferenceCentury ( ) - 1 ; if ( century == - 1 ) century = 20 ; int year = getOctet ( 13 ) ; int month = getOctet ( 14 ) ; int day = getOctet ( 15 ) ; int hour = getOctet ( 16 ) ; int minute = getOctet ( 17 ) ; return CalendarDate . of ( null , century * 100 + year , month , day , hour , minute , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * NCEP Appendix C Manual 388 http : // www . nco . ncep . noaa . gov / pmb / docs / on388 / appendixc . html states that if the PDS is > 28 bytes and octet 41 == 1 then it s an ensemble an product . [CODESPLIT] public boolean isEnsemble ( ) { switch ( getCenter ( ) ) { case 7 : return ( ( rawData . length >= 43 ) && ( getOctet ( 41 ) == 1 ) ) ; case 98 : return ( ( rawData . length >= 51 ) && ( getOctet ( 41 ) == 1 || getOctet ( 41 ) == 30 ) && ( getOctet ( 43 ) == 10 || getOctet ( 43 ) == 11 ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": ": title = WPDN data : selected by ob time : time range from 1207951200 to 1207954800 ; [CODESPLIT] public boolean isMine ( FeatureType wantFeatureType , NetcdfDataset ds ) { String title = ds . findAttValueIgnoreCase ( null , \"title\" , null ) ; if ( title == null ) { title = ds . findAttValueIgnoreCase ( null , \"DD_reference\" , null ) ; if ( title != null ) { title = ds . findVariable ( \"staLat\" ) != null ? title : null ; } } return title != null && ( title . startsWith ( \"WPDN data\" ) || title . startsWith ( \"RASS data\" ) || title . contains ( \"88-21-R2\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This code tweaks our catalog output to match . [CODESPLIT] private String idvDatasetCatalog ( String xml ) { String ret = xml . replace ( \"variables\" , \"Variables\" ) ; ret = ret . replace ( \"timeCoverage\" , \"TimeSpan\" ) ; StringBuilder sub = new StringBuilder ( ret . substring ( 0 , ret . indexOf ( \"<geospatialCoverage>\" ) ) ) ; sub . append ( \"<LatLonBox>\\n\\t<north>90.0</north>\\n\\t<south>-90.0</south>\" ) ; sub . append ( \"\\n\\t<east>180.0</east>\\n\\t<west>-180.0</west></LatLonBox>\" ) ; String endCoverage = \"</geospatialCoverage>\" ; sub . append ( ret . substring ( ret . indexOf ( endCoverage ) + endCoverage . length ( ) ) ) ; return sub . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "present and 14 days . [CODESPLIT] private DateRange idvCompatibleRange ( DateRange range ) { CalendarDate start = range . getStart ( ) . getCalendarDate ( ) ; CalendarDate end = range . getEnd ( ) . getCalendarDate ( ) ; return new DateRange ( start . toDate ( ) , end . toDate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : phenomenonTime [CODESPLIT] public static TimeObjectPropertyType initPhenomenonTime ( TimeObjectPropertyType phenomenonTime , StationTimeSeriesFeature stationFeat ) throws IOException { // gml:TimePeriod TimePeriodDocument timePeriodDoc = TimePeriodDocument . Factory . newInstance ( ) ; NcTimePeriodType . initTimePeriod ( timePeriodDoc . addNewTimePeriod ( ) , stationFeat ) ; phenomenonTime . set ( timePeriodDoc ) ; return phenomenonTime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check basic DMSP file validity of given random access file . [CODESPLIT] boolean isValidFile ( ucar . unidata . io . RandomAccessFile raFile ) { // @todo This method should not be called if read() has or will be called on this instance. this . raFile = raFile ; try { this . actualSize = raFile . length ( ) ; } catch ( IOException e ) { return ( false ) ; } try { this . readHeaderFromFile ( raFile ) ; this . handleFileInformation ( ) ; this . handleProcessingInformation ( ) ; this . handleSatelliteInformation ( ) ; this . handleSensorInformation ( ) ; } catch ( IOException e ) { return ( false ) ; } return ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the header information from the file into name / value pairs . [CODESPLIT] private void readHeaderFromFile ( ucar . unidata . io . RandomAccessFile raFile ) throws IOException { long pos = 0 ; raFile . seek ( pos ) ; // Read in first record. this . headerSizeInBytes = raFile . length ( ) > this . headerSizeInBytesGuess ? this . headerSizeInBytesGuess : ( int ) raFile . length ( ) ; byte [ ] b = new byte [ this . headerSizeInBytes ] ; if ( raFile . read ( b ) != this . headerSizeInBytes ) throw new IOException ( \"Invalid DMSP file: could not read first \" + this . headerSizeInBytes + \" bytes.\" ) ; String fullHeader = new String ( b , CDM . utf8Charset ) ; // Make sure header starts with the proper item. if ( ! fullHeader . startsWith ( HeaderInfoTitle . FILE_ID . toString ( ) ) ) { throw new IOException ( \"Invalid DMSP file: header does not start with \\\"\" + HeaderInfoTitle . FILE_ID . toString ( ) + \"\\\".\" ) ; } // Make sure header contains end-of-header marker. int endOfHeaderIndex = fullHeader . indexOf ( HeaderInfoTitle . END_HEADER . toString ( ) ) ; if ( endOfHeaderIndex == - 1 ) { throw new IOException ( \"Invalid DMSP file: header does not end with \\\"\" + HeaderInfoTitle . END_HEADER . toString ( ) + \"\\\".\" ) ; } // Drop the end-of-header marker and the line feed ('\\n') proceeding it. header = fullHeader . substring ( 0 , endOfHeaderIndex - 1 ) . split ( \"\\n\" ) ; int lineSeperatorIndex = 0 ; String curHeaderLine = null ; String curHeaderTitle = null ; String curHeaderValue = null ; for ( String aHeader : this . header ) { curHeaderLine = aHeader . trim ( ) ; lineSeperatorIndex = curHeaderLine . indexOf ( ' ' ) ; if ( lineSeperatorIndex == - 1 ) throw new IOException ( \"Invalid DMSP file: header line <\" + curHeaderLine + \"> contains no seperator <:>.\" ) ; if ( lineSeperatorIndex == 0 ) throw new IOException ( \"Invalid DMSP file: header line <\" + curHeaderLine + \"> contains no title.\" ) ; if ( lineSeperatorIndex == curHeaderLine . length ( ) - 1 ) throw new IOException ( \"Invalid DMSP file: header line <\" + curHeaderLine + \"> contains no value.\" ) ; curHeaderTitle = curHeaderLine . substring ( 0 , lineSeperatorIndex ) . trim ( ) ; curHeaderValue = curHeaderLine . substring ( lineSeperatorIndex + 1 ) . trim ( ) ; if ( curHeaderValue . equals ( \"\" ) ) throw new IOException ( \"Invalid DMSP file: header line <\" + curHeaderLine + \"> contains no value.\" ) ; headerInfo . put ( curHeaderTitle , curHeaderValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the file header information about the file ( e . g . file ID dataset ID record size number of records ) and create netCDF attributes and dimensions where appropriate . [CODESPLIT] private void handleFileInformation ( ) throws IOException { fileIdAtt = new Attribute ( this . fileIdAttName , headerInfo . get ( HeaderInfoTitle . FILE_ID . toString ( ) ) ) ; datasetIdAtt = new Attribute ( this . datasetIdAttName , headerInfo . get ( HeaderInfoTitle . DATA_SET_ID . toString ( ) ) ) ; recordSizeInBytes = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . RECORD_BYTES . toString ( ) ) ) ; numRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_RECORDS . toString ( ) ) ) ; numHeaderRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_HEADER_RECORDS . toString ( ) ) ) ; numDataRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_DATA_RECORDS . toString ( ) ) ) ; numDataRecordsDim = new Dimension ( this . numDataRecordsDimName , numDataRecords , true , true , false ) ; numArtificialDataRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_ARTIFICIAL_DATA_RECORDS . toString ( ) ) ) ; this . headerSizeInBytes = this . numHeaderRecords * this . recordSizeInBytes ; if ( numRecords * ( ( long ) this . recordSizeInBytes ) != this . actualSize ) { throw new IOException ( \"Invalid DMSP file: the number of records <\" + this . numRecords + \"> times the record size <\" + this . recordSizeInBytes + \"> does not equal the size of the file <\" + this . actualSize + \">.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the processing / history information from the header . [CODESPLIT] private void handleProcessingInformation ( ) throws IOException { suborbitHistoryAtt = new Attribute ( this . suborbitHistoryAttName , headerInfo . get ( HeaderInfoTitle . SUBORBIT_HISTORY . toString ( ) ) ) ; processingSystemAtt = new Attribute ( this . processingSystemAttName , headerInfo . get ( HeaderInfoTitle . PROCESSING_SYSTEM . toString ( ) ) ) ; String processingDateString = headerInfo . get ( HeaderInfoTitle . PROCESSING_DATE . toString ( ) ) ; try { processingDate = DateFormatHandler . ALT_DATE_TIME . getDateFromDateTimeString ( processingDateString ) ; } catch ( ParseException e ) { throw new IOException ( \"Invalid DMSP file: processing date string <\" + processingDateString + \"> not parseable: \" + e . getMessage ( ) ) ; } processingDateAtt = new Attribute ( this . processingDateAttName , DateFormatHandler . ISO_DATE_TIME . getDateTimeStringFromDate ( processingDate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the satellite information from the header . [CODESPLIT] private void handleSatelliteInformation ( ) { spacecraftIdAtt = new Attribute ( this . spacecraftIdAttName , headerInfo . get ( HeaderInfoTitle . SPACECRAFT_ID . toString ( ) ) ) ; noradIdAtt = new Attribute ( this . noradIdAttName , headerInfo . get ( HeaderInfoTitle . NORAD_ID . toString ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the sensor information from the header . [CODESPLIT] private void handleSensorInformation ( ) { numSamplesPerBand = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . SAMPLES_PER_BAND . toString ( ) ) ) ; numSamplesPerBandDim = new Dimension ( this . numSamplesPerBandDimName , numSamplesPerBand ) ; // Read nominal resolution information nominalResolutionAtt = new Attribute ( nominalResolutionAttName , headerInfo . get ( HeaderInfoTitle . NOMINAL_RESOLUTION . toString ( ) ) ) ; // Read bands per scanlin information. bandsPerScanlineAtt = new Attribute ( bandsPerScanlineAttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BANDS_PER_SCANLINE . toString ( ) ) ) ) ; // Read bytes per smaple information bytesPerSampleAtt = new Attribute ( bytesPerSampleAttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BYTES_PER_SAMPLE . toString ( ) ) ) ) ; // Read byte offset for band 1 information. byteOffsetBand1Att = new Attribute ( byteOffsetBand1AttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BYTE_OFFSET_BAND_1 . toString ( ) ) ) ) ; // Read byte offset for band 2 information. byteOffsetBand2Att = new Attribute ( byteOffsetBand2AttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BYTE_OFFSET_BAND_2 . toString ( ) ) ) ) ; // Band 1 description band1Att = new Attribute ( band1AttName , headerInfo . get ( HeaderInfoTitle . BAND_1 . toString ( ) ) ) ; // Band 2 description band2Att = new Attribute ( band2AttName , headerInfo . get ( HeaderInfoTitle . BAND_2 . toString ( ) ) ) ; // Band organization bandOrganizationAtt = new Attribute ( bandOrganizationAttName , headerInfo . get ( HeaderInfoTitle . ORGANIZATION . toString ( ) ) ) ; // thermal offset thermalOffsetAtt = new Attribute ( thermalOffsetAttName , headerInfo . get ( HeaderInfoTitle . THERMAL_OFFSET . toString ( ) ) ) ; // thermal scale thermalScaleAtt = new Attribute ( thermalScaleAttName , headerInfo . get ( HeaderInfoTitle . THERMAL_SCALE . toString ( ) ) ) ; // percent daylight percentDaylightAtt = new Attribute ( percentDaylightAttName , Double . valueOf ( headerInfo . get ( HeaderInfoTitle . PERCENT_DAYLIGHT . toString ( ) ) ) ) ; // percent full moon percentFullMoonAtt = new Attribute ( percentFullMoonAttName , Double . valueOf ( headerInfo . get ( HeaderInfoTitle . PERCENT_FULL_MOON . toString ( ) ) ) ) ; // percent terminator evident percentTerminatorEvidentAtt = new Attribute ( percentTerminatorEvidentAttName , Double . valueOf ( headerInfo . get ( HeaderInfoTitle . PERCENT_TERMINATOR_EVIDENT . toString ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a string containing the header name / value pairs . [CODESPLIT] protected String headerInfoDump ( ) { StringBuilder retVal = new StringBuilder ( ) ; for ( String curHeaderTitle : this . headerInfo . keySet ( ) ) { String curHeaderValue = this . headerInfo . get ( curHeaderTitle ) ; retVal . append ( curHeaderTitle ) ; retVal . append ( \":::::\" ) ; retVal . append ( curHeaderValue ) ; retVal . append ( \":::::\\n\" ) ; } return ( retVal . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an XML Document from a URL and return the root element . [CODESPLIT] static public Element readRootElement ( String location ) throws IOException { org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( location ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } return doc . getRootElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make sure that text is XML safe [CODESPLIT] static public String cleanCharacterData ( String text ) { if ( text == null ) return null ; boolean bad = false ; for ( int i = 0 , len = text . length ( ) ; i < len ; i ++ ) { int ch = text . charAt ( i ) ; if ( ! org . jdom2 . Verifier . isXMLCharacter ( ch ) ) { bad = true ; break ; } } if ( ! bad ) return text ; StringBuilder sbuff = new StringBuilder ( text . length ( ) ) ; for ( int i = 0 , len = text . length ( ) ; i < len ; i ++ ) { int ch = text . charAt ( i ) ; if ( org . jdom2 . Verifier . isXMLCharacter ( ch ) ) sbuff . append ( ( char ) ch ) ; } return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if this is a valid file for this IOServiceProvider . [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { raf . seek ( 0 ) ; int n = MAGIC . length ( ) ; if ( raf . length ( ) < n ) { return false ; } String got = raf . readString ( n ) ; return ( pMAGIC . matcher ( got ) . find ( ) || pMAGIC_OLD . matcher ( got ) . find ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open existing file and populate ncfile with it . This method is only called by the NetcdfFile constructor on itself . The provided NetcdfFile object will be empty except for the location String and the IOServiceProvider associated with this NetcdfFile object . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; isExtended = checkFormat ( ) ; isoDateFormat = new SimpleDateFormat ( ) ; isoDateFormat . setTimeZone ( java . util . TimeZone . getTimeZone ( \"GMT\" ) ) ; isoDateFormat . applyPattern ( isExtended ? TIME_FORMAT_EX : TIME_FORMAT ) ; Sequence seq = makeSequence ( ncfile ) ; ncfile . addVariable ( null , seq ) ; addLightningGlobalAttributes ( ncfile ) ; ncfile . finish ( ) ; sm = seq . makeStructureMembers ( ) ; ArrayStructureBB . setOffsets ( sm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the global attributes . [CODESPLIT] protected void addLightningGlobalAttributes ( NetcdfFile ncfile ) { super . addLightningGlobalAttributes ( ncfile ) ; ncfile . addAttribute ( null , new Attribute ( \"title\" , \"USPLN Lightning Data\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"file_format\" , \"USPLN1 \" + ( isExtended ? \"(extended)\" : \"(original)\" ) ) ) ; /*\r\n    ncfile.addAttribute(null,\r\n                        new Attribute(\"time_coverage_start\",\r\n                                      time_min + \" \" + secondsSince1970));\r\n    ncfile.addAttribute(null,\r\n                        new Attribute(\"time_coverage_end\",\r\n                                      time_max + \" \" + secondsSince1970));\r\n\r\n    ncfile.addAttribute(null,\r\n                        new Attribute(\"geospatial_lat_min\",\r\n                                      new Double(lat_min)));\r\n    ncfile.addAttribute(null,\r\n                        new Attribute(\"geospatial_lat_max\",\r\n                                      new Double(lat_max)));\r\n\r\n    ncfile.addAttribute(null,\r\n                        new Attribute(\"geospatial_lon_min\",\r\n                                      new Double(lon_min)));\r\n    ncfile.addAttribute(null,\r\n                        new Attribute(\"geospatial_lon_max\",\r\n                                      new Double(lon_max)));\r\n    */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all the data and return the number of strokes [CODESPLIT] private boolean checkFormat ( ) throws IOException { raf . seek ( 0 ) ; boolean extended = false ; while ( true ) { long offset = raf . getFilePointer ( ) ; String line = raf . readLine ( ) ; if ( line == null ) { break ; } if ( pMAGIC . matcher ( line ) . find ( ) || pMAGIC_OLD . matcher ( line ) . find ( ) ) { extended = pMAGIC_EX . matcher ( line ) . find ( ) ; break ; } } return extended ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all the data and return the number of strokes [CODESPLIT] int readAllData ( RandomAccessFile raf ) throws IOException , NumberFormatException , ParseException { ArrayList offsetList = new ArrayList ( ) ; java . text . SimpleDateFormat isoDateTimeFormat = new java . text . SimpleDateFormat ( TIME_FORMAT ) ; isoDateTimeFormat . setTimeZone ( java . util . TimeZone . getTimeZone ( \"GMT\" ) ) ; lat_min = 1000.0 ; lat_max = - 1000.0 ; lon_min = 1000.0 ; lon_max = - 1000.0 ; time_min = Double . POSITIVE_INFINITY ; time_max = Double . NEGATIVE_INFINITY ; raf . seek ( 0 ) ; int count = 0 ; boolean knowExtended = false ; while ( true ) { long offset = raf . getFilePointer ( ) ; String line = raf . readLine ( ) ; if ( line == null ) { break ; } if ( pMAGIC . matcher ( line ) . find ( ) || pMAGIC_OLD . matcher ( line ) . find ( ) ) { if ( ! knowExtended ) { isExtended = pMAGIC_EX . matcher ( line ) . find ( ) ; if ( isExtended ) { isoDateTimeFormat . applyPattern ( TIME_FORMAT_EX ) ; } knowExtended = true ; } continue ; } // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,1             (original)\r // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,0.25,0.5,80   (extended)\r StringTokenizer stoker = new StringTokenizer ( line , \",\\r\\n\" ) ; while ( stoker . hasMoreTokens ( ) ) { Date date = isoDateTimeFormat . parse ( stoker . nextToken ( ) ) ; double lat = Double . parseDouble ( stoker . nextToken ( ) ) ; double lon = Double . parseDouble ( stoker . nextToken ( ) ) ; double amp = Double . parseDouble ( stoker . nextToken ( ) ) ; int nstrokes = 1 ; double axisMaj = Double . NaN ; double axisMin = Double . NaN ; int orient = 0 ; if ( isExtended ) { axisMaj = Double . parseDouble ( stoker . nextToken ( ) ) ; axisMin = Double . parseDouble ( stoker . nextToken ( ) ) ; orient = Integer . parseInt ( stoker . nextToken ( ) ) ; } else { nstrokes = Integer . parseInt ( stoker . nextToken ( ) ) ; } Stroke s = isExtended ? new Stroke ( date , lat , lon , amp , axisMaj , axisMin , orient ) : new Stroke ( date , lat , lon , amp , nstrokes ) ; lat_min = Math . min ( lat_min , s . lat ) ; lat_max = Math . max ( lat_max , s . lat ) ; lon_min = Math . min ( lon_min , s . lon ) ; lon_max = Math . max ( lon_max , s . lon ) ; time_min = Math . min ( time_min , s . secs ) ; time_max = Math . max ( time_max , s . secs ) ; } offsetList . add ( new Long ( offset ) ) ; count ++ ; } offsets = new long [ count ] ; for ( int i = 0 ; i < offsetList . size ( ) ; i ++ ) { Long off = ( Long ) offsetList . get ( i ) ; offsets [ i ] = off . longValue ( ) ; } //System.out.println(\"processed \" + count + \" records\");\r return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from a top level Variable and return a memory resident Array . This Array has the same element type as the Variable and the requested shape . [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { return new ArraySequence ( sm , getStructureIterator ( null , 0 ) , nelems ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a string that contains WWW escape sequences translate those escape sequences back into ASCII characters . Return the modified string . [CODESPLIT] private static String xunescapeString ( String in , char escape , boolean spaceplus ) { try { if ( in == null ) return null ; byte [ ] utf8 = in . getBytes ( utf8Charset ) ; byte escape8 = ( byte ) escape ; byte [ ] out = new byte [ utf8 . length ] ; // Should be max we need int index8 = 0 ; for ( int i = 0 ; i < utf8 . length ; ) { byte b = utf8 [ i ++ ] ; if ( b == plus && spaceplus ) { out [ index8 ++ ] = blank ; } else if ( b == escape8 ) { // check to see if there are enough characters left if ( i + 2 <= utf8 . length ) { b = ( byte ) ( fromHex ( utf8 [ i ] ) << 4 | fromHex ( utf8 [ i + 1 ] ) ) ; i += 2 ; } } out [ index8 ++ ] = b ; } return new String ( out , 0 , index8 , utf8Charset ) ; } catch ( Exception e ) { return in ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the DEFINITIVE URL constraint expression escape function . [CODESPLIT] public static String escapeURLQuery ( String ce ) { try { ce = escapeString ( ce , _allowableInUrlQuery ) ; } catch ( Exception e ) { ce = null ; } return ce ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the DEFINITIVE URL constraint expression unescape function . [CODESPLIT] public static String unescapeURLQuery ( String ce ) { try { ce = unescapeString ( ce ) ; } catch ( Exception e ) { ce = null ; } return ce ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the DEFINITIVE URL BACKSLASH unescape function . [CODESPLIT] public static String backslashDecode ( String s ) { StringBuilder buf = new StringBuilder ( s ) ; int i = 0 ; while ( i < buf . length ( ) ) { if ( buf . charAt ( i ) == ' ' ) { buf . deleteCharAt ( i ) ; } i ++ ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the DEFINITIVE URL BACKSLASH escape function . [CODESPLIT] public static String backslashEncode ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = buf . charAt ( i ) ; if ( _MustBackslashEscape . indexOf ( c ) >= 0 ) buf . append ( _BACKSLASHEscape ) ; buf . append ( ( char ) c ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make lightning variables @param ncfile the netCDF file @param group the group ( may be null ) @param seq the sequence to add to @param name variable name @param dataType the data type @param dims dimenstion names @param longName the long_name attribute value ( a description ) @param cfName the CF standard_name attribute value ( may be null ) @param units the units attribute value ( if null not added ) @param type coordinate axis type units ( if null not added ) [CODESPLIT] protected Variable makeLightningVariable ( NetcdfFile ncfile , Group group , Structure seq , String name , DataType dataType , String dims , String longName , String cfName , String units , AxisType type ) { Variable v = new Variable ( ncfile , group , seq , name ) ; v . setDataType ( dataType ) ; v . setDimensions ( dims ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; if ( cfName != null ) { v . addAttribute ( new Attribute ( CF . STANDARD_NAME , cfName ) ) ; } if ( units != null ) { v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; } if ( type != null ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , type . toString ( ) ) ) ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the global attributes . Specific implementations should call super and then add their own . [CODESPLIT] protected void addLightningGlobalAttributes ( NetcdfFile ncfile ) { ncfile . addAttribute ( null , new Attribute ( CF . FEATURE_TYPE , CF . FeatureType . point . toString ( ) ) ) ; ncfile . addAttribute ( null , new Attribute ( CDM . HISTORY , \"Read directly by Netcdf Java IOSP\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "res . setHeader ( Content - Disposition attachment ; filename = + path + . nc ) ; [CODESPLIT] public static String setContentDispositionValue ( String filename , String suffix ) { int pos = filename . lastIndexOf ( ' ' ) ; String outname = ( pos > 0 ) ? filename . substring ( pos + 1 ) : filename ; int pos2 = outname . lastIndexOf ( ' ' ) ; outname = ( pos > 0 ) ? outname . substring ( 0 , pos2 ) : outname ; outname = outname + suffix ; return setContentDispositionValue ( outname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType // and all of the different signatures of printDecl() in BaseType // lead to one signature, we must be careful to override that // SAME signature here. That way all calls to printDecl() for // this object lead to this implementation. boolean isSingle = false ; boolean isStructure = false ; boolean isGrid = false ; boolean psemi = true ; //os.println(\"The grid contains \"+projectedComponents(true)+\" projected components\"); if ( constrained && projectedComponents ( true ) == 0 ) return ; // If we are printing the declaration of a constrained Grid then check for // the case where the projection removes all but one component; the // resulting object is a simple array. // 2013-2-26: Heimbigner : this is incorrect, even single // projected components should be in a structure. /* Wrong\n            if (constrained && projectedComponents(true) == 1) {\n            //os.println(\"It's a single Array.\");\n            isSingle = true;\n            psemi = print_semi;\n        } */ // If there are M (< N) components (Array and Maps combined) in a N // component Grid, send the M components as elements of a Structure. // This will preserve the grouping without violating the rules for a // Grid. else if ( constrained && ! projectionYieldsGrid ( true ) ) { //os.println(\"It's a Structure.\"); isStructure = true ; } else { // The number of elements in the (projected) Grid must be such that // we have a valid Grid object; send it as such. //os.println(\"It's a Grid.\"); isGrid = true ; } if ( isGrid ) os . println ( space + getTypeName ( ) + \" {\" ) ; if ( isGrid ) os . println ( space + \" ARRAY:\" ) ; if ( isStructure ) os . println ( space + \"Structure {\" ) ; ( ( SDArray ) arrayVar ) . printDecl ( os , space + \"    \" , psemi , constrained ) ; if ( isGrid ) os . println ( space + \" MAPS:\" ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { SDArray sda = ( SDArray ) e . nextElement ( ) ; sda . printDecl ( os , space + \"    \" , psemi , constrained ) ; } if ( isStructure || isGrid ) { os . print ( space + \"} \" + getEncodedName ( ) ) ; if ( print_semi ) os . println ( \";\" ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . <p / > <h2 > Important Note< / h2 > This method overrides the BaseType method of the same name and type signature and it significantly changes the behavior for all versions of <code > printVal () < / code > for this type : <b > <i > All the various versions of printVal () will only print a value or a value with declaration if the variable is in the projection . < / i > < / b > <br > <br > In other words if a call to <code > isProject () < / code > for a particular variable returns <code > true< / code > then <code > printVal () < / code > will print a value ( or a declaration and a value ) . <br > <br > If <code > isProject () < / code > for a particular variable returns <code > false< / code > then <code > printVal () < / code > is basically a No - Op . <br > <br > [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; //System.out.println(\"\\nSome Part of this object is projected...\"); if ( print_decl_p ) { printDecl ( os , space , false , true ) ; os . print ( \" = \" ) ; } boolean isStillGrid = projectionYieldsGrid ( true ) ; os . print ( \"{ \" ) ; if ( isStillGrid ) os . print ( \"ARRAY: \" ) ; if ( ( ( SDArray ) arrayVar ) . isProject ( ) ) arrayVar . printVal ( os , \"\" , false ) ; if ( isStillGrid ) os . print ( \" MAPS: \" ) ; boolean firstPass = true ; Enumeration e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { SDArray sda = ( SDArray ) e . nextElement ( ) ; if ( ( ( SDArray ) sda ) . isProject ( ) ) { if ( ! firstPass ) os . print ( \", \" ) ; sda . printVal ( os , \"\" , false ) ; firstPass = false ; } } os . print ( \" }\" ) ; if ( print_decl_p ) os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the state of this variable s projection . <code > true< / code > means that this variable is part of the current projection as defined by the current constraint expression otherwise the current projection for this variable should be <code > false< / code > . [CODESPLIT] @ Override public void setProject ( boolean state , boolean all ) { setProjected ( state ) ; if ( all ) { // System.out.println(\"SDGrid:setProject: Blindly setting Project\"); ( ( SDArray ) arrayVar ) . setProject ( state ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; sm . setProject ( state ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Server - side serialization for OPeNDAP variables ( sub - classes of <code > BaseType< / code > ) . This does not send the entire class as the Java <code > Serializable< / code > interface does rather it sends only the binary data values . Other software is responsible for sending variable type information ( see <code > DDS< / code > ) . <p / > Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { if ( ! isRead ( ) ) read ( dataset , specialO ) ; if ( ce . evalClauses ( specialO ) ) { if ( ( ( ServerMethods ) arrayVar ) . isProject ( ) ) ( ( ServerMethods ) arrayVar ) . serialize ( dataset , sink , ce , specialO ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; if ( sm . isProject ( ) ) sm . serialize ( dataset , sink , ce , specialO ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the projection information for this dimension . The internal <code > DArray< / code > is retrieved and then the <code > DArrayDimension< / code > associated with the <code > dimension< / code > specified is retrieved and the <code > start< / code > <code > stride< / code > and <code > stop< / code > parameters are passed to its <code > setProjection () < / code > method . [CODESPLIT] public void setProjection ( int dimension , int start , int stride , int stop ) throws InvalidDimensionException , SBHException { try { DArray a = ( DArray ) getVar ( 0 ) ; DArrayDimension d = a . getDimension ( dimension ) ; d . setProjection ( start , stride , stop ) ; DArray map = ( DArray ) getVar ( dimension + 1 ) ; DArrayDimension mapD = map . getDimension ( 0 ) ; mapD . setProjection ( start , stride , stop ) ; } catch ( NoSuchVariableException e ) { throw new InvalidDimensionException ( \"SDGrid.setProjection(): Bad Value for dimension!: \" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the <b > start< / b > value for the projection of the <code > dimension< / code > indicated . The parameter <code > dimension< / code > is checked against the instance of the <code > SDArray< / code > for bounds violation . [CODESPLIT] public int getStart ( int dimension ) throws InvalidDimensionException { try { DArray a = ( DArray ) getVar ( 0 ) ; DArrayDimension d = a . getDimension ( dimension ) ; return ( d . getStart ( ) ) ; } catch ( NoSuchVariableException e ) { throw new InvalidDimensionException ( \"SDGrid.getStart(): Bad Value for dimension!: \" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printXML ( PrintWriter pw , String pad , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType // and all of the different signatures of printDecl() in BaseType // lead to one signature, we must be careful to override that // SAME signature here. That way all calls to printDecl() for // this object lead to this implementation. boolean isSingle = false ; boolean isStructure = false ; boolean isGrid = false ; boolean psemi = true ; //os.println(\"The gird contains \"+projectedComponents(true)+\" projected components\"); if ( constrained && projectedComponents ( true ) == 0 ) return ; // If we are printing the declaration of a constrained Grid then check for // the case where the projection removes all but one component; the // resulting object is a simple array. if ( constrained && projectedComponents ( true ) == 1 ) { //os.println(\"It's a single Array.\"); isSingle = true ; } // If there are M (< N) componets (Array and Maps combined) in a N // component Grid, send the M components as elements of a Struture. // This will preserve the grouping without violating the rules for a // Grid. else if ( constrained && ! projectionYieldsGrid ( true ) ) { //os.println(\"It's a Structure.\"); isStructure = true ; } else { // The number of elements in the (projected) Grid must be such that // we have a valid Grid object; send it as such. //os.println(\"It's a Grid.\"); isGrid = true ; } if ( isGrid ) { pw . print ( pad + \"<Grid \" ) ; if ( getEncodedName ( ) != null ) { pw . print ( \" name=\\\"\" + DDSXMLParser . normalizeToXML ( getEncodedName ( ) ) + \"\\\"\" ) ; } pw . println ( \">\" ) ; } if ( isStructure ) { pw . print ( pad + \"<Structure\" ) ; if ( getEncodedName ( ) != null ) { pw . print ( \" name=\\\"\" + DDSXMLParser . normalizeToXML ( getEncodedName ( ) ) + \"\\\"\" ) ; } pw . println ( \">\" ) ; } Enumeration e = getAttributeNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = getAttribute ( aName ) ; if ( a != null ) a . printXML ( pw , pad + \"\\t\" , constrained ) ; } ( ( SDArray ) arrayVar ) . printXML ( pw , pad + ( isSingle ? \"\" : \"\\t\" ) , constrained ) ; if ( isGrid ) { e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { SDArray map = ( SDArray ) e . nextElement ( ) ; //Coverity[DEADCODE] map . printAsMapXML ( pw , pad + ( isSingle ? \"\" : \"\\t\" ) , constrained ) ; } } else { e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { SDArray sda = ( SDArray ) e . nextElement ( ) ; sda . printXML ( pw , pad + ( isSingle ? \"\" : \"\\t\" ) , constrained ) ; } } if ( isStructure ) { pw . println ( pad + \"</Structure>\" ) ; } else if ( isGrid ) { pw . println ( pad + \"</Grid>\" ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the short resulting from swapping 2 bytes at a specified offset in a byte array . [CODESPLIT] static public short swapShort ( byte [ ] b , int offset ) { // 2 bytes\r int low = b [ offset ] & 0xff ; int high = b [ offset + 1 ] & 0xff ; return ( short ) ( high << 8 | low ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the int resulting from reversing 4 bytes at a specified offset in a byte array . [CODESPLIT] static public int swapInt ( byte [ ] b , int offset ) { // 4 bytes\r int accum = 0 ; for ( int shiftBy = 0 , i = offset ; shiftBy < 32 ; shiftBy += 8 , i ++ ) { accum |= ( b [ i ] & 0xff ) << shiftBy ; } return accum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the double resulting from reversing 8 bytes at a specified offset in a byte array . [CODESPLIT] static public double swapDouble ( byte [ ] b , int offset ) { long accum = 0 ; long shiftedval ; for ( int shiftBy = 0 , i = offset ; shiftBy < 64 ; shiftBy += 8 , i ++ ) { shiftedval = ( ( long ) ( b [ i ] & 0xff ) ) << shiftBy ; accum |= shiftedval ; } return Double . longBitsToDouble ( accum ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the float resulting from reversing 4 bytes of a specified float . [CODESPLIT] static public float swapFloat ( float v ) { int l = swapInt ( Float . floatToIntBits ( v ) ) ; return ( Float . intBitsToFloat ( l ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the double resulting from reversing 8 bytes of a specified double . [CODESPLIT] static public double swapDouble ( double v ) { long l = swapLong ( Double . doubleToLongBits ( v ) ) ; return ( Double . longBitsToDouble ( l ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a short to an array of 2 bytes . [CODESPLIT] static public byte [ ] shortToBytes ( short v ) { byte [ ] b = new byte [ 2 ] ; int allbits = 255 ; for ( int i = 0 ; i < 2 ; i ++ ) { b [ 1 - i ] = ( byte ) ( ( v & ( allbits << i * 8 ) ) >> i * 8 ) ; } return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an int to an array of 4 bytes . [CODESPLIT] static public byte [ ] intToBytes ( int v ) { byte [ ] b = new byte [ 4 ] ; int allbits = 255 ; for ( int i = 0 ; i < 4 ; i ++ ) { b [ 3 - i ] = ( byte ) ( ( v & ( allbits << i * 8 ) ) >> i * 8 ) ; } return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a long to an array of 8 bytes . [CODESPLIT] static public byte [ ] longToBytes ( long v ) { byte [ ] b = new byte [ 8 ] ; long allbits = 255 ; for ( int i = 0 ; i < 8 ; i ++ ) { b [ 7 - i ] = ( byte ) ( ( v & ( allbits << i * 8 ) ) >> i * 8 ) ; } return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data { @link ucar . ma2 . Array } from the variable at the specified time index if applicable . If the variable does not have a time dimension the data array will have the same rank as the Variable . If the variable has a time dimension the data array will have rank - 1 . [CODESPLIT] protected Array readArray ( Variable v , int timeIndex ) throws IOException , InvalidRangeException { int [ ] shape = v . getShape ( ) ; int [ ] origin = new int [ v . getRank ( ) ] ; if ( getTimeDimension ( ) != null ) { int dimIndex = v . findDimensionIndex ( getTimeDimension ( ) . getShortName ( ) ) ; if ( dimIndex >= 0 ) { shape [ dimIndex ] = 1 ; origin [ dimIndex ] = timeIndex ; return v . read ( origin , shape ) . reduce ( dimIndex ) ; } } return v . read ( origin , shape ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a subset of this VerticalTransform . [CODESPLIT] public VerticalTransform subset ( Range t_range , Range z_range , Range y_range , Range x_range ) throws ucar . ma2 . InvalidRangeException { return new VerticalTransformSubset ( this , t_range , z_range , y_range , x_range ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "current version [CODESPLIT] public static GridDatasetInv open ( MCollection cm , MFile mfile , Element ncml ) throws IOException { // do we already have it ?\r byte [ ] xmlBytes = ( ( CollectionManagerAbstract ) cm ) . getMetadata ( mfile , \"fmrInv.xml\" ) ; // LOOK should we keep this functionality ??\r if ( xmlBytes != null ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( \" got xmlFile in cache =\" + mfile . getPath ( ) + \" size = \" + xmlBytes . length ) ; if ( xmlBytes . length < 300 ) { logger . warn ( \" xmlFile in cache only has nbytes =\" + xmlBytes . length + \"; will reread\" ) ; // drop through and regenerate\r } else { GridDatasetInv inv = readXML ( xmlBytes ) ; // check if version required regen\r if ( inv . version >= REQ_VERSION ) { // check if file has changed\r long fileModifiedSecs = mfile . getLastModified ( ) / 1000 ; // ignore msecs\r long xmlModifiedSecs = inv . getLastModified ( ) / 1000 ; // ignore msecs\r if ( xmlModifiedSecs >= fileModifiedSecs ) { // LOOK if fileDate is -1, will always succeed\r if ( logger . isDebugEnabled ( ) ) logger . debug ( \" cache ok \" + new Date ( inv . getLastModified ( ) ) + \" >= \" + new Date ( mfile . getLastModified ( ) ) + \" for \" + mfile . getName ( ) ) ; return inv ; // ok, use it\r } else { if ( logger . isInfoEnabled ( ) ) logger . info ( \" cache out of date \" + new Date ( inv . getLastModified ( ) ) + \" < \" + new Date ( mfile . getLastModified ( ) ) + \" for \" + mfile . getName ( ) ) ; } } else { if ( logger . isInfoEnabled ( ) ) logger . info ( \" version needs upgrade \" + inv . version + \" < \" + REQ_VERSION + \" for \" + mfile . getName ( ) ) ; } } } // generate it and save it\r GridDataset gds = null ; try { if ( ncml == null ) { gds = GridDataset . open ( mfile . getPath ( ) ) ; } else { NetcdfFile nc = NetcdfDataset . acquireFile ( new DatasetUrl ( null , mfile . getPath ( ) ) , null ) ; NetcdfDataset ncd = NcMLReader . mergeNcML ( nc , ncml ) ; // create new dataset\r ncd . enhance ( ) ; // now that the ncml is added, enhance \"in place\", ie modify the NetcdfDataset\r gds = new GridDataset ( ncd ) ; } // System.out.println(\"gds dataset= \"+ gds.getNetcdfDataset());\r GridDatasetInv inv = new GridDatasetInv ( gds , cm . extractDate ( mfile ) ) ; String xmlString = inv . writeXML ( new Date ( mfile . getLastModified ( ) ) ) ; ( ( CollectionManagerAbstract ) cm ) . putMetadata ( mfile , \"fmrInv.xml\" , xmlString . getBytes ( CDM . utf8Charset ) ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \" added xmlFile \" + mfile . getPath ( ) + \".fmrInv.xml to cache\" ) ; if ( debug ) System . out . printf ( \" added xmlFile %s.fmrInv.xml to cache%n\" , mfile . getPath ( ) ) ; // System.out.println(\"new xmlBytes= \"+ xmlString);\r return inv ; } finally { if ( gds != null ) gds . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////// [CODESPLIT] private TimeCoord getTimeCoordinate ( CoordinateAxis1DTime axis ) { // check for same axis\r for ( TimeCoord tc : times ) { if ( tc . getAxisName ( ) . equals ( axis . getFullName ( ) ) ) return tc ; } // check for same offsets\r TimeCoord want = new TimeCoord ( runDate , axis ) ; for ( TimeCoord tc : times ) { if ( ( tc . equalsData ( want ) ) ) return tc ; } // its a new one\r times . add ( want ) ; return want ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////// [CODESPLIT] private VertCoord getVertCoordinate ( int wantId ) { if ( wantId < 0 ) return null ; for ( VertCoord vc : vaxes ) { if ( vc . getId ( ) == wantId ) return vc ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////// [CODESPLIT] private EnsCoord getEnsCoordinate ( int ens_id ) { if ( ens_id < 0 ) return null ; for ( EnsCoord ec : eaxes ) { if ( ( ec . getId ( ) == ens_id ) ) return ec ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the XML representation to a String . [CODESPLIT] public String writeXML ( Date lastModified ) { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( writeDocument ( lastModified ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the XML representation of the GridDatasetInv [CODESPLIT] Document writeDocument ( Date lastModified ) { Element rootElem = new Element ( \"gridInventory\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"location\" , location ) ; rootElem . setAttribute ( \"runTime\" , runTimeString ) ; if ( lastModified != null ) { rootElem . setAttribute ( \"lastModified\" , CalendarDateFormatter . toDateTimeString ( lastModified ) ) ; } rootElem . setAttribute ( \"version\" , Integer . toString ( CURR_VERSION ) ) ; // list all the vertical coords\r Collections . sort ( vaxes ) ; int count = 0 ; for ( VertCoord vc : vaxes ) { vc . setId ( count ++ ) ; Element vcElem = new Element ( \"vertCoord\" ) ; rootElem . addContent ( vcElem ) ; vcElem . setAttribute ( \"id\" , Integer . toString ( vc . getId ( ) ) ) ; vcElem . setAttribute ( \"name\" , vc . getName ( ) ) ; if ( vc . getUnits ( ) != null ) vcElem . setAttribute ( CDM . UNITS , vc . getUnits ( ) ) ; StringBuilder sbuff = new StringBuilder ( ) ; double [ ] values1 = vc . getValues1 ( ) ; double [ ] values2 = vc . getValues2 ( ) ; for ( int j = 0 ; j < values1 . length ; j ++ ) { if ( j > 0 ) sbuff . append ( \" \" ) ; sbuff . append ( Double . toString ( values1 [ j ] ) ) ; if ( values2 != null ) { sbuff . append ( \",\" ) ; sbuff . append ( Double . toString ( values2 [ j ] ) ) ; } } vcElem . addContent ( sbuff . toString ( ) ) ; } // list all the time coords\r count = 0 ; for ( TimeCoord tc : times ) { tc . setId ( count ++ ) ; Element timeElement = new Element ( \"timeCoord\" ) ; rootElem . addContent ( timeElement ) ; timeElement . setAttribute ( \"id\" , Integer . toString ( tc . getId ( ) ) ) ; timeElement . setAttribute ( \"name\" , tc . getName ( ) ) ; timeElement . setAttribute ( \"isInterval\" , tc . isInterval ( ) ? \"true\" : \"false\" ) ; Formatter sbuff = new Formatter ( ) ; if ( tc . isInterval ( ) ) { double [ ] bound1 = tc . getBound1 ( ) ; double [ ] bound2 = tc . getBound2 ( ) ; for ( int j = 0 ; j < bound1 . length ; j ++ ) sbuff . format ( ( Locale ) null , \"%f %f,\" , bound1 [ j ] , bound2 [ j ] ) ; } else { for ( double offset : tc . getOffsetTimes ( ) ) sbuff . format ( ( Locale ) null , \" % , \" , offset ) ; } timeElement . addContent ( sbuff . toString ( ) ) ; List < GridDatasetInv . Grid > vars = tc . getGridInventory ( ) ; Collections . sort ( vars ) ; for ( Grid grid : vars ) { Element varElem = new Element ( \"grid\" ) ; timeElement . addContent ( varElem ) ; varElem . setAttribute ( \"name\" , grid . name ) ; if ( grid . ec != null ) varElem . setAttribute ( \"ens_id\" , Integer . toString ( grid . ec . getId ( ) ) ) ; if ( grid . vc != null ) varElem . setAttribute ( \"vert_id\" , Integer . toString ( grid . vc . getId ( ) ) ) ; } } return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a GridDatasetInv from its XML representation [CODESPLIT] private static GridDatasetInv readXML ( byte [ ] xmlString ) throws IOException { InputStream is = new BufferedInputStream ( new ByteArrayInputStream ( xmlString ) ) ; org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( is ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) + \" reading from XML \" ) ; } Element rootElem = doc . getRootElement ( ) ; GridDatasetInv fmr = new GridDatasetInv ( ) ; fmr . runTimeString = rootElem . getAttributeValue ( \"runTime\" ) ; fmr . location = rootElem . getAttributeValue ( \"location\" ) ; if ( fmr . location == null ) fmr . location = rootElem . getAttributeValue ( \"name\" ) ; // old way\r String lastModifiedS = rootElem . getAttributeValue ( \"lastModified\" ) ; if ( lastModifiedS != null ) fmr . lastModified = CalendarDateFormatter . isoStringToDate ( lastModifiedS ) ; String version = rootElem . getAttributeValue ( \"version\" ) ; fmr . version = ( version == null ) ? 0 : Integer . parseInt ( version ) ; if ( fmr . version < REQ_VERSION ) return fmr ; fmr . runDate = DateUnit . parseCalendarDate ( fmr . runTimeString ) ; java . util . List < Element > vList = rootElem . getChildren ( \"vertCoord\" ) ; for ( Element vertElem : vList ) { VertCoord vc = new VertCoord ( ) ; fmr . vaxes . add ( vc ) ; vc . setId ( Integer . parseInt ( vertElem . getAttributeValue ( \"id\" ) ) ) ; vc . setName ( vertElem . getAttributeValue ( \"name\" ) ) ; vc . setUnits ( vertElem . getAttributeValue ( CDM . UNITS ) ) ; // parse the values\r String values = vertElem . getTextNormalize ( ) ; StringTokenizer stoke = new StringTokenizer ( values ) ; int n = stoke . countTokens ( ) ; double [ ] values1 = new double [ n ] ; double [ ] values2 = null ; int count = 0 ; while ( stoke . hasMoreTokens ( ) ) { String toke = stoke . nextToken ( ) ; int pos = toke . indexOf ( ' ' ) ; if ( pos < 0 ) values1 [ count ] = Double . parseDouble ( toke ) ; else { if ( values2 == null ) values2 = new double [ n ] ; String val1 = toke . substring ( 0 , pos ) ; String val2 = toke . substring ( pos + 1 ) ; values1 [ count ] = Double . parseDouble ( val1 ) ; values2 [ count ] = Double . parseDouble ( val2 ) ; } count ++ ; } vc . setValues1 ( values1 ) ; vc . setValues2 ( values2 ) ; } java . util . List < Element > tList = rootElem . getChildren ( \"timeCoord\" ) ; for ( Element timeElem : tList ) { TimeCoord tc = new TimeCoord ( fmr . runDate ) ; fmr . times . add ( tc ) ; tc . setId ( Integer . parseInt ( timeElem . getAttributeValue ( \"id\" ) ) ) ; String s = timeElem . getAttributeValue ( \"isInterval\" ) ; boolean isInterval = ( s != null ) && ( s . equals ( \"true\" ) ) ; if ( isInterval ) { String boundsAll = timeElem . getTextNormalize ( ) ; String [ ] bounds = boundsAll . split ( \",\" ) ; int n = bounds . length ; double [ ] bound1 = new double [ n ] ; double [ ] bound2 = new double [ n ] ; int count = 0 ; for ( String b : bounds ) { String [ ] value = b . split ( \" \" ) ; bound1 [ count ] = Double . parseDouble ( value [ 0 ] ) ; bound2 [ count ] = Double . parseDouble ( value [ 1 ] ) ; count ++ ; } tc . setBounds ( bound1 , bound2 ) ; } else { String values = timeElem . getTextNormalize ( ) ; String [ ] value = values . split ( \",\" ) ; int n = value . length ; double [ ] offsets = new double [ n ] ; int count = 0 ; for ( String v : value ) offsets [ count ++ ] = Double . parseDouble ( v ) ; tc . setOffsetTimes ( offsets ) ; } //get the variable names\r List < Element > varList = timeElem . getChildren ( \"grid\" ) ; for ( Element vElem : varList ) { Grid grid = fmr . makeGrid ( vElem . getAttributeValue ( \"name\" ) ) ; if ( vElem . getAttributeValue ( \"ens_id\" ) != null ) grid . ec = fmr . getEnsCoordinate ( Integer . parseInt ( vElem . getAttributeValue ( \"ens_id\" ) ) ) ; if ( vElem . getAttributeValue ( \"vert_id\" ) != null ) grid . vc = fmr . getVertCoordinate ( Integer . parseInt ( vElem . getAttributeValue ( \"vert_id\" ) ) ) ; tc . addGridInventory ( grid ) ; grid . tc = tc ; } } return fmr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Reset the lexer [CODESPLIT] public void reset ( Dap2Parse state ) { this . parsestate = state ; this . text = new TextStream ( ) ; yytext = new StringBuilder ( ) ; lval = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entry point for the scanner . Returns the token identifier corresponding to the next token and prepares to return the semantic value of the token . [CODESPLIT] public int yylex ( ) throws ParseException { int token ; int c ; token = 0 ; yytext . setLength ( 0 ) ; text . mark ( ) ; try { token = - 1 ; while ( token < 0 && ( c = text . read ( ) ) > 0 ) { if ( c == ' ' ) { lineno ++ ; } else if ( c <= ' ' || c == ' ' ) { /* whitespace: ignore */ } else if ( c == ' ' ) { /* single line comment */ for ( ; ; ) { c = text . read ( ) ; if ( c == ' ' || c == ' ' ) break ; } } else if ( worddelims . indexOf ( c ) >= 0 ) { token = c ; } else if ( c == ' ' ) { boolean more = true ; /* We have a string token; will be reported as SCAN_WORD */ while ( more && ( c = text . read ( ) ) > 0 ) { if ( DAP2STRING ) { /* Implement DAP2 standard */ switch ( c ) { case ' ' : more = false ; break ; case ' ' : c = text . read ( ) ; if ( c < 0 ) more = false ; break ; case ' ' : default : break ; } } else { // not used : Implement a more java/c like alternative for string encoding switch ( c ) { case ' ' : more = false ; break ; case ' ' : c = text . read ( ) ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : { int d1 , d2 ; c = text . read ( ) ; d1 = tohex ( c ) ; if ( d1 < 0 ) { throw new ParseException ( \"Illegal \\\\xDD in TOKEN_STRING\" ) ; } else { c = text . read ( ) ; d2 = tohex ( c ) ; if ( d2 < 0 ) { throw new ParseException ( \"Illegal \\\\xDD in TOKEN_STRING\" ) ; } else { c = ( ( d1 ) << 4 ) | d2 ; } } } break ; default : break ; } break ; default : break ; } } if ( more ) yytext . append ( ( char ) c ) ; } token = WORD_STRING ; } else if ( wordchars1 . indexOf ( c ) >= 0 ) { yytext . append ( ( char ) c ) ; /* we have a SCAN_WORD (== identifier | number) */ while ( ( c = text . read ( ) ) > 0 ) { if ( wordcharsn . indexOf ( c ) < 0 ) { text . backup ( ) ; break ; } yytext . append ( ( char ) c ) ; } token = WORD_WORD ; /* assume */ /* check for keyword */ String tmp = yytext . toString ( ) ; for ( int i = 0 ; ; i ++ ) { if ( keywords [ i ] == null ) break ; if ( keywords [ i ] . equalsIgnoreCase ( tmp ) ) { token = keytokens [ i ] ; break ; } } } else { /* illegal */ String msg = String . format ( \"Illegal Character: '%c'\" , c ) ; yytext . append ( ( char ) c ) ; lexerror ( msg ) ; throw new ParseException ( msg ) ; } } // do eof check if ( token <= 0 ) { token = 0 ; lval = null ; } else { lval = ( yytext . length ( ) == 0 ? ( String ) null : yytext . toString ( ) ) ; } if ( parsestate . getDebugLevel ( ) > 0 ) dumptoken ( token , ( String ) lval ) ; return token ; /* Return the type of the token.  */ } catch ( IOException ioe ) { throw new ParseException ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entry point for error reporting . Emits an error in a user - defined way . [CODESPLIT] public void yyerror ( String s ) { String kind = \"?\" ; switch ( parsestate . parseClass ) { case Dap2Parse . DapDAS : kind = \"DAS\" ; break ; case Dap2Parse . DapDDS : kind = \"DDS\" ; break ; case Dap2Parse . DapERR : kind = \"Error\" ; break ; default : kind = \"?\" ; break ; } System . err . println ( \"yyerror: \" + s + \"; \" + kind + \" parse failed at line: \" + lineno + \" char: \" + charno + \"; near: \" ) ; String context = parsestate . flatten ( getInput ( ) ) ; int show = ( context . length ( ) < CONTEXTLEN ? context . length ( ) : CONTEXTLEN ) ; System . err . println ( context . substring ( context . length ( ) - show ) + \"^\" ) ; if ( parsestate . getURL ( ) != null ) System . err . println ( \"\\turl=\" + parsestate . getURL ( ) ) ; new Exception ( ) . printStackTrace ( System . err ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; if ( null == c ) { double a = aVar . readScalarDouble ( ) ; double b = bVar . readScalarDouble ( ) ; depth_c = depthCVar . readScalarDouble ( ) ; c = makeC ( sArray , a , b ) ; } return makeHeight ( etaArray , sArray , depthArray , c , depth_c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and the specified X Y index for Lat - Lon point . [CODESPLIT] public ArrayDouble . D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; if ( null == c ) { double a = aVar . readScalarDouble ( ) ; double b = bVar . readScalarDouble ( ) ; depth_c = depthCVar . readScalarDouble ( ) ; c = makeC ( sArray , a , b ) ; } return makeHeight1D ( etaArray , sArray , depthArray , c , depth_c , xIndex , yIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the C array [CODESPLIT] private Array makeC ( Array s , double a , double b ) { int nz = ( int ) s . getSize ( ) ; Index sIndex = s . getIndex ( ) ; if ( a == 0 ) return s ; // per R. Signell, USGS\r ArrayDouble . D1 c = new ArrayDouble . D1 ( nz ) ; double fac1 = 1.0 - b ; double denom1 = 1.0 / Math . sinh ( a ) ; double denom2 = 1.0 / ( 2.0 * Math . tanh ( 0.5 * a ) ) ; for ( int i = 0 ; i < nz ; i ++ ) { double sz = s . getDouble ( sIndex . set ( i ) ) ; double term1 = fac1 * Math . sinh ( a * sz ) * denom1 ; double term2 = b * ( Math . tanh ( a * ( sz + 0.5 ) ) * denom2 - 0.5 ) ; c . set ( i , term1 + term2 ) ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make height from the given data . <br > old equationn : height ( x y z ) = eta ( x y ) * ( 1 + s ( z )) + depth_c * s ( z ) + ( depth ( x y ) - depth_c ) * C ( z ) <p / > <p / > / * - sachin 03 / 23 / 09 The new corrected equation according to Hernan Arango ( Rutgers ) height ( x y z ) = S ( x y z ) + eta ( x y ) * ( 1 + S ( x y z ) / depth ( x y ) ) <p / > where S ( x y z ) = depth_c * s ( z ) + ( depth ( x y ) - depth_c ) * C ( z ) / [CODESPLIT] private ArrayDouble . D3 makeHeight ( Array eta , Array s , Array depth , Array c , double depth_c ) { int nz = ( int ) s . getSize ( ) ; Index sIndex = s . getIndex ( ) ; Index cIndex = c . getIndex ( ) ; int [ ] shape2D = eta . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index etaIndex = eta . getIndex ( ) ; Index depthIndex = depth . getIndex ( ) ; ArrayDouble . D3 height = new ArrayDouble . D3 ( nz , ny , nx ) ; for ( int z = 0 ; z < nz ; z ++ ) { double sz = s . getDouble ( sIndex . set ( z ) ) ; double cz = c . getDouble ( cIndex . set ( z ) ) ; double term1 = depth_c * sz ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { //-sachin 03/23/09  modifications according to corrected equation.\r double fac1 = depth . getDouble ( depthIndex . set ( y , x ) ) ; double term2 = ( fac1 - depth_c ) * cz ; double Sterm = term1 + term2 ; double term3 = eta . getDouble ( etaIndex . set ( y , x ) ) ; double term4 = 1 + Sterm / fac1 ; double hterm = Sterm + term3 * term4 ; height . set ( z , y , x , hterm ) ; } } } return height ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiate the response with an XML file with an XML header [CODESPLIT] public void startXML ( ) { fileOutput += \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" ; fileOutput += \"<schema \" + \"xmlns:\" + WFSController . TDSNAMESPACE + \"=\" + WFSXMLHelper . encQuotes ( namespace ) + \" \" + \"xmlns:ogc=\\\"http://www.opengis.net/ogc\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" \" + \"xmlns=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns:gml=\\\"http://www.opengis.net/gml\\\" \" + \"targetNamespace=\\\"\" + server + \"\\\" elementFormDefault=\\\"qualified\\\" \" + \"version=\\\"0.1\\\">\" ; fileOutput += \"<xsd:import namespace=\\\"http://www.opengis.net/gml\\\" \" + \"schemaLocation=\\\"http://schemas.opengis.net/gml/2.1.2/feature.xsd\\\"/>\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the features from the featureList . For each feature write its attributes [CODESPLIT] public void writeFeatures ( ) { for ( WFSFeature feat : featureList ) { fileOutput += \"<xsd:complexType name=\\\"\" + feat . getTitle ( ) + \"\\\">\" ; fileOutput += \"<xsd:complexContent>\" ; fileOutput += \"<xsd:extension base=\\\"gml:\" + feat . getType ( ) + \"\\\">\" ; fileOutput += \"<xsd:sequence>\" ; for ( WFSFeatureAttribute attribute : feat . getAttributes ( ) ) { fileOutput += \"<xsd:element name =\\\"\" + attribute . getName ( ) + \"\\\" type=\\\"\" + attribute . getType ( ) + \"\\\"/>\" ; } fileOutput += \"</xsd:sequence>\" ; fileOutput += \"</xsd:extension>\" ; fileOutput += \"</xsd:complexContent>\" ; fileOutput += \"</xsd:complexType>\" ; fileOutput += \"<xsd:element name =\\\"\" + feat . getName ( ) + \"\\\" type=\\\"tds:\" + feat . getTitle ( ) + \"\\\"/>\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add levels from the GridRecords [CODESPLIT] void addLevels ( List < GridRecord > records ) { for ( GridRecord record : records ) { Double d = new Double ( record . getLevel1 ( ) ) ; if ( ! levels . contains ( d ) ) { levels . add ( d ) ; } if ( dontUseVertical && ( levels . size ( ) > 1 ) ) { if ( GridServiceProvider . debugVert ) { System . out . println ( \"GribCoordSys: unused level coordinate has > 1 levels = \" + verticalName + \" \" + record . getLevelType1 ( ) + \" \" + levels . size ( ) ) ; } } } Collections . sort ( levels ) ; if ( positive . equals ( \"down\" ) ) { Collections . reverse ( levels ) ; // TODO: delete /* for( int i = 0; i < (levels.size()/2); i++ ){\n        Double tmp = (Double) levels.get( i );\n        levels.set( i, levels.get(levels.size() -i -1));\n        levels.set(levels.size() -i -1, tmp );\n     } */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match levels [CODESPLIT] boolean matchLevels ( List < GridRecord > records ) { // first create a new list List < Double > levelList = new ArrayList < Double > ( records . size ( ) ) ; for ( GridRecord record : records ) { Double d = new Double ( record . getLevel1 ( ) ) ; if ( ! levelList . contains ( d ) ) { levelList . add ( d ) ; } } Collections . sort ( levelList ) ; if ( positive . equals ( \"down\" ) ) { Collections . reverse ( levelList ) ; } // gotta equal existing list return levelList . equals ( levels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add dimensions to the netcdf file [CODESPLIT] void addDimensionsToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( dontUseVertical ) { return ; } int nlevs = levels . size ( ) ; ncfile . addDimension ( g , new Dimension ( verticalName , nlevs , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add this coordinate system to the netCDF file [CODESPLIT] void addToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( dontUseVertical ) { return ; } if ( g == null ) { g = ncfile . getRootGroup ( ) ; } String dims = \"time\" ; if ( ! dontUseVertical ) { dims = dims + \" \" + verticalName ; } if ( hcs . isLatLon ( ) ) { dims = dims + \" lat lon\" ; } else { dims = dims + \" y x\" ; } //Collections.sort( levels); int nlevs = levels . size ( ) ; // ncfile.addDimension(g, new Dimension(verticalName, nlevs, true)); // coordinate axis and coordinate system Variable Variable v = new Variable ( ncfile , g , null , verticalName ) ; v . setDataType ( DataType . DOUBLE ) ; v . addAttribute ( new Attribute ( \"long_name\" , lookup . getLevelDescription ( record ) ) ) ; v . addAttribute ( new Attribute ( \"units\" , lookup . getLevelUnit ( record ) ) ) ; // positive attribute needed for CF-1 Height and Pressure if ( positive != null ) { v . addAttribute ( new Attribute ( \"positive\" , positive ) ) ; } if ( units != null ) { AxisType axisType ; if ( SimpleUnit . isCompatible ( \"millibar\" , units ) ) { axisType = AxisType . Pressure ; } else if ( SimpleUnit . isCompatible ( \"m\" , units ) ) { axisType = AxisType . Height ; } else { axisType = AxisType . GeoZ ; } v . addAttribute ( new Attribute ( \"grid_level_type\" , Integer . toString ( record . getLevelType1 ( ) ) ) ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axisType . toString ( ) ) ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , dims ) ) ; if ( ! hcs . isLatLon ( ) ) { v . addAttribute ( new Attribute ( _Coordinate . Transforms , hcs . getGridName ( ) ) ) ; } } double [ ] data = new double [ nlevs ] ; for ( int i = 0 ; i < levels . size ( ) ; i ++ ) { Double d = ( Double ) levels . get ( i ) ; data [ i ] = d . doubleValue ( ) ; } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { nlevs } , data ) ; v . setDimensions ( verticalName ) ; v . setCachedData ( dataArray , false ) ; ncfile . addVariable ( g , v ) ; // look for vertical transforms if ( record . getLevelType1 ( ) == 109 ) { findCoordinateTransform ( g , \"Pressure\" , record . getLevelType1 ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the coordinate transform [CODESPLIT] void findCoordinateTransform ( Group g , String nameStartsWith , int levelType ) { // look for variable that uses this coordinate List < Variable > vars = g . getVariables ( ) ; for ( Variable v : vars ) { if ( v . getShortName ( ) . equals ( nameStartsWith ) ) { Attribute att = v . findAttribute ( \"grid_level_type\" ) ; if ( ( att == null ) || ( att . getNumericValue ( ) . intValue ( ) != levelType ) ) { continue ; } v . addAttribute ( new Attribute ( _Coordinate . TransformType , \"Vertical\" ) ) ; v . addAttribute ( new Attribute ( \"transform_name\" , \"Existing3DField\" ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the index of a particular GridRecord [CODESPLIT] int getIndex ( GridRecord record ) { Double d = new Double ( record . getLevel1 ( ) ) ; return levels . indexOf ( d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Be sure to call this when your application exits otherwise your process may not exit without being killed . [CODESPLIT] static public void exit ( ) { if ( timer != null ) { timer . cancel ( ) ; System . out . printf ( \"DiskCache2.exit()%n\" ) ; } timer = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default DiskCache2 strategy : use $user_home / . unidata / cache / no scouring alwaysUseCache = false Mimics default DiskCache static class [CODESPLIT] static public DiskCache2 getDefault ( ) { String root = System . getProperty ( \"nj22.cache\" ) ; if ( root == null ) { String home = System . getProperty ( \"user.home\" ) ; if ( home == null ) home = System . getProperty ( \"user.dir\" ) ; if ( home == null ) home = \".\" ; root = home + \"/.unidata/cache/\" ; } DiskCache2 result = new DiskCache2 ( ) ; result . setRootDirectory ( root ) ; result . alwaysUseCache = false ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the cache root directory . Create it if it doesnt exist . Normally this is set in the Constructor . [CODESPLIT] public void setRootDirectory ( String cacheDir ) { if ( ! cacheDir . endsWith ( \"/\" ) ) cacheDir = cacheDir + \"/\" ; root = StringUtil2 . replace ( cacheDir , ' ' , \"/\" ) ; // no nasty backslash File dir = new File ( root ) ; if ( ! dir . mkdirs ( ) ) { // ok } if ( ! dir . exists ( ) ) { fail = true ; cacheLog . error ( \"DiskCache2 failed to create directory \" + root ) ; } else { cacheLog . debug ( \"DiskCache2 create directory \" + root ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a File in the cache corresponding to the fileLocation . File may or may not exist . If fileLocation has / in it and cachePathPolicy == NestedDirectory the nested directories will be created . [CODESPLIT] public File getCacheFile ( String fileLocation ) { if ( neverUseCache ) return null ; if ( ! alwaysUseCache ) { File f = new File ( fileLocation ) ; if ( canWrite ( f ) ) return f ; } File f = new File ( makeCachePath ( fileLocation ) ) ; //if (f.exists()) // f.setLastModified( System.currentTimeMillis()); if ( cachePathPolicy == CachePathPolicy . NestedDirectory ) { File dir = f . getParentFile ( ) ; if ( ! dir . exists ( ) ) { boolean ret = dir . mkdirs ( ) ; if ( ! ret ) cacheLog . warn ( \"Error creating dir: \" + dir ) ; } } return f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the named File . If exists or isWritable return it . Otherwise get corresponding file in the cache directory . [CODESPLIT] public File getFile ( String fileLocation ) { if ( ! alwaysUseCache ) { File f = new File ( fileLocation ) ; if ( f . exists ( ) ) return f ; if ( canWrite ( f ) ) return f ; } if ( neverUseCache ) { throw new IllegalStateException ( \"neverUseCache=true, but file does not exist and directory is not writeable =\" + fileLocation ) ; } File f = new File ( makeCachePath ( fileLocation ) ) ; if ( cachePathPolicy == CachePathPolicy . NestedDirectory ) { File dir = f . getParentFile ( ) ; if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) cacheLog . warn ( \"Cant create directories for file \" + dir . getPath ( ) ) ; } return f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if we can write to the file . [CODESPLIT] public static boolean canWrite ( File f ) { Path path = f . toPath ( ) . toAbsolutePath ( ) ; try { if ( Files . isDirectory ( path ) ) { // Try to create a file within the directory to determine if it's writable. Files . delete ( Files . createTempFile ( path , \"check\" , null ) ) ; } else if ( Files . isRegularFile ( path ) ) { // Try to open the file for writing in append mode. Files . newOutputStream ( path , StandardOpenOption . APPEND ) . close ( ) ; } else { // File does not exist. See if it's parent directory exists and is writeable. Files . delete ( Files . createTempFile ( path . getParent ( ) , \"check\" , null ) ) ; } } catch ( IOException | SecurityException e ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looking for an existing file in cache or no [CODESPLIT] public File getExistingFileOrCache ( String fileLocation ) { File f = new File ( fileLocation ) ; if ( f . exists ( ) ) return f ; if ( neverUseCache ) return null ; File fc = new File ( makeCachePath ( fileLocation ) ) ; if ( fc . exists ( ) ) return fc ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new uniquely named file in the root directory . Mimics File . createTempFile () [CODESPLIT] public synchronized File createUniqueFile ( String prefix , String suffix ) { if ( suffix == null ) suffix = \".tmp\" ; Random random = new Random ( System . currentTimeMillis ( ) ) ; File result = new File ( getRootDirectory ( ) , prefix + Integer . toString ( random . nextInt ( ) ) + suffix ) ; while ( result . exists ( ) ) result = new File ( getRootDirectory ( ) , prefix + Integer . toString ( random . nextInt ( ) ) + suffix ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the cache filename [CODESPLIT] private String makeCachePath ( String fileLocation ) { // remove ':', '?', '=', replace '\\' with '/', leading or trailing '/' String cachePath = fileLocation ; cachePath = StringUtil2 . remove ( cachePath , ' ' ) ; cachePath = StringUtil2 . remove ( cachePath , ' ' ) ; cachePath = StringUtil2 . replace ( cachePath , ' ' , \"/\" ) ; if ( cachePath . startsWith ( \"/\" ) ) cachePath = cachePath . substring ( 1 ) ; if ( cachePath . endsWith ( \"/\" ) ) cachePath = cachePath . substring ( 0 , cachePath . length ( ) - 1 ) ; cachePath = StringUtil2 . remove ( cachePath , ' ' ) ; // remove directories if ( cachePathPolicy == CachePathPolicy . OneDirectory ) { cachePath = StringUtil2 . replace ( cachePath , ' ' , \"-\" ) ; } // eliminate leading directories else if ( cachePathPolicy == CachePathPolicy . NestedTruncate ) { int pos = cachePath . indexOf ( cachePathPolicyParam ) ; if ( pos >= 0 ) cachePath = cachePath . substring ( pos + cachePathPolicyParam . length ( ) ) ; if ( cachePath . startsWith ( \"/\" ) ) cachePath = cachePath . substring ( 1 ) ; } // make sure the parent directory exists if ( cachePathPolicy != CachePathPolicy . OneDirectory ) { File file = new File ( root + cachePath ) ; File parent = file . getParentFile ( ) ; if ( ! parent . exists ( ) ) { if ( root == null ) { // LOOK shouldnt happen, remove soon System . out . printf ( \"mkdir4 %s%n\" , parent . getPath ( ) ) ; new Throwable ( ) . printStackTrace ( ) ; } boolean ret = parent . mkdirs ( ) ; if ( ! ret ) cacheLog . warn ( \"Error creating parent: \" + parent ) ; } } return root + cachePath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show cache contents for debugging . [CODESPLIT] public void showCache ( PrintStream pw ) { pw . println ( \"Cache files\" ) ; pw . println ( \"Size   LastModified       Filename\" ) ; File dir = new File ( root ) ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) for ( File file : files ) { String org = null ; try { org = URLDecoder . decode ( file . getName ( ) , \"UTF8\" ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } pw . println ( \" \" + file . length ( ) + \" \" + new Date ( file . lastModified ( ) ) + \" \" + org ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove any files or directories whose last modified time greater than persistMinutes [CODESPLIT] public void cleanCache ( File dir , Formatter sbuff , boolean isRoot ) { long now = System . currentTimeMillis ( ) ; File [ ] files = dir . listFiles ( ) ; if ( files == null ) { throw new IllegalStateException ( \"DiskCache2: not a directory or I/O error on dir=\" + dir . getAbsolutePath ( ) ) ; } // check for empty directory if ( ! isRoot && ( files . length == 0 ) ) { long duration = now - dir . lastModified ( ) ; duration /= 1000 * 60 ; // minutes if ( duration > persistMinutes ) { boolean ok = dir . delete ( ) ; if ( ! ok ) cacheLog . error ( \"Unable to delete file \" + dir . getAbsolutePath ( ) ) ; if ( sbuff != null ) sbuff . format ( \" deleted %s %s lastModified= %s%n\" , ok , dir . getPath ( ) , CalendarDate . of ( dir . lastModified ( ) ) ) ; } return ; } // check for expired files for ( File file : files ) { if ( file . isDirectory ( ) ) { cleanCache ( file , sbuff , false ) ; } else { long duration = now - file . lastModified ( ) ; duration /= 1000 * 60 ; // minutes if ( duration > persistMinutes ) { boolean ok = file . delete ( ) ; if ( ! ok ) cacheLog . error ( \"Unable to delete file \" + file . getAbsolutePath ( ) ) ; if ( sbuff != null ) sbuff . format ( \" deleted %s %s lastModified= %s%n\" , ok , file . getPath ( ) , CalendarDate . of ( file . lastModified ( ) ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method has the standard behavior when this object has been created using the standard constructors . Otherwise it uses currentToken and expectedTokenSequences to generate a parse error message and returns it . If this object has been created due to a parse error and you do not catch it ( it gets thrown from the parser ) then this method is called during the printing of the final stack trace and hence the correct error message gets displayed . [CODESPLIT] public String getMessage ( ) { if ( ! specialConstructor ) { return super . getMessage ( ) ; } StringBuilder expected = new StringBuilder ( ) ; int maxSize = 0 ; for ( int [ ] expectedTokenSequence : expectedTokenSequences ) { if ( maxSize < expectedTokenSequence . length ) { maxSize = expectedTokenSequence . length ; } for ( int anExpectedTokenSequence : expectedTokenSequence ) { expected . append ( tokenImage [ anExpectedTokenSequence ] ) . append ( ' ' ) ; } if ( expectedTokenSequence [ expectedTokenSequence . length - 1 ] != 0 ) { expected . append ( \"...\" ) ; } expected . append ( eol ) . append ( \"    \" ) ; } StringBuilder b = new StringBuilder ( \"Encountered \\\"\" ) ; Token tok = currentToken . next ; for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i != 0 ) b . append ( \" \" ) ; if ( tok . kind == 0 ) { b . append ( tokenImage [ 0 ] ) ; break ; } b . append ( \" \" ) . append ( tokenImage [ tok . kind ] ) . append ( \" \\\"\" ) ; b . append ( add_escapes ( tok . image ) ) ; b . append ( \" \\\"\" ) ; tok = tok . next ; } b . append ( \"\\\" at line \" ) . append ( currentToken . next . beginLine ) . append ( \", column \" ) . append ( currentToken . next . beginColumn ) ; b . append ( \".\" ) . append ( eol ) ; if ( expectedTokenSequences . length == 1 ) { b . append ( \"Was expecting:\" ) . append ( eol ) . append ( \"    \" ) ; } else { b . append ( \"Was expecting one of:\" ) . append ( eol ) . append ( \"    \" ) ; } expected . append ( expected . toString ( ) ) ; return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////// TableModelListener //////////////////////////////////////////////// [CODESPLIT] @ Override public void tableChanged ( final TableModelEvent e ) { if ( e . getFirstRow ( ) == TableModelEvent . HEADER_ROW ) { return ; // Do not respond to changes in the number of columns here, only row and data changes. } // ColumnWidthsResizer requires that the internal Swing TableModelListeners that update the JTable view // run their updates BEFORE it does its thing. Unfortunately, the order in which listeners are notified is // undefined (see https://weblogs.java.net/blog/alexfromsun/archive/2011/06/15/swing-better-world-listeners). // As a work-around, we're going to place the resize operation at the end of the event queue. That way, it'll // be executed after all TableModelListeners have been notified. EventQueue . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { // Do not cache the value of doFullScan; we need to reevaluate each time because the number of rows in // the table could have changed. boolean doFullScan = table . getRowCount ( ) <= fullScanCutoff ; if ( e . getColumn ( ) == TableModelEvent . ALL_COLUMNS ) { resize ( table , doFullScan ) ; // Resize all columns. } else { resize ( table , e . getColumn ( ) , doFullScan ) ; // Resize only the affected column. } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////// TableColumnModelListener ///////////////////////////////////////////// [CODESPLIT] @ Override public void columnAdded ( TableColumnModelEvent e ) { boolean doFullScan = table . getRowCount ( ) <= fullScanCutoff ; resize ( table , e . getToIndex ( ) , doFullScan ) ; // Only resize added column. }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the bearing between the 2 points . See calculateBearing below . [CODESPLIT] public static Bearing calculateBearing ( Earth e , LatLonPoint pt1 , LatLonPoint pt2 , Bearing result ) { return calculateBearing ( e , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , pt2 . getLatitude ( ) , pt2 . getLongitude ( ) , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the bearing between the 2 points . See calculateBearing below . Uses default Earth object . [CODESPLIT] public static Bearing calculateBearing ( LatLonPoint pt1 , LatLonPoint pt2 , Bearing result ) { return calculateBearing ( defaultEarth , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , pt2 . getLatitude ( ) , pt2 . getLongitude ( ) , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes distance ( in km ) azimuth ( degrees clockwise positive from North 0 to 360 ) and back azimuth ( degrees clockwise positive from North 0 to 360 ) from latitude - longituide point pt1 to latitude - longituide pt2 . Uses default Earth object . [CODESPLIT] public static Bearing calculateBearing ( double lat1 , double lon1 , double lat2 , double lon2 , Bearing result ) { return calculateBearing ( defaultEarth , lat1 , lon1 , lat2 , lon2 , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes distance ( in km ) azimuth ( degrees clockwise positive from North 0 to 360 ) and back azimuth ( degrees clockwise positive from North 0 to 360 ) from latitude - longituide point pt1 to latitude - longituide pt2 . <p > Algorithm from U . S . National Geodetic Survey FORTRAN program inverse subroutine INVER1 by L . PFEIFER and JOHN G . GERGEN . See http : // www . ngs . noaa . gov / TOOLS / Inv_Fwd / Inv_Fwd . html <P > Original documentation : <br > SOLUTION OF THE GEODETIC INVERSE PROBLEM AFTER T . VINCENTY <br > MODIFIED RAINSFORD S METHOD WITH HELMERT S ELLIPTICAL TERMS <br > EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL <br > STANDPOINT / FOREPOINT MUST NOT BE THE GEOGRAPHIC POLE < / P > Reference ellipsoid is the WGS - 84 ellipsoid . <br > See http : // www . colorado . edu / geography / gcraft / notes / datum / elist . html <p / > Requires close to 1 . 4 E - 5 seconds wall clock time per call on a 550 MHz Pentium with Linux 7 . 2 . [CODESPLIT] public static Bearing calculateBearing ( Earth e , double lat1 , double lon1 , double lat2 , double lon2 , Bearing result ) { if ( result == null ) { result = new Bearing ( ) ; } if ( ( lat1 == lat2 ) && ( lon1 == lon2 ) ) { result . distance = 0 ; result . azimuth = 0 ; result . backazimuth = 0 ; return result ; } A = e . getMajor ( ) ; F = e . getFlattening ( ) ; R = 1.0 - F ; // Algorithm from National Geodetic Survey, FORTRAN program \"inverse,\"\r // subroutine \"INVER1,\" by L. PFEIFER and JOHN G. GERGEN.\r // http://www.ngs.noaa.gov/TOOLS/Inv_Fwd/Inv_Fwd.html\r // Conversion to JAVA from FORTRAN was made with as few changes as possible\r // to avoid errors made while recasting form, and to facilitate any future\r // comparisons between the original code and the altered version in Java.\r // Original documentation:\r // SOLUTION OF THE GEODETIC INVERSE PROBLEM AFTER T.VINCENTY\r // MODIFIED RAINSFORD'S METHOD WITH HELMERT'S ELLIPTICAL TERMS\r // EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL\r // STANDPOINT/FOREPOINT MUST NOT BE THE GEOGRAPHIC POLE\r // A IS THE SEMI-MAJOR AXIS OF THE REFERENCE ELLIPSOID\r // F IS THE FLATTENING (NOT RECIPROCAL) OF THE REFERNECE ELLIPSOID\r // LATITUDES GLAT1 AND GLAT2\r // AND LONGITUDES GLON1 AND GLON2 ARE IN RADIANS POSITIVE NORTH AND EAST\r // FORWARD AZIMUTHS AT BOTH POINTS RETURNED IN RADIANS FROM NORTH\r //\r // Reference ellipsoid is the WGS-84 ellipsoid.\r // See http://www.colorado.edu/geography/gcraft/notes/datum/elist.html\r // FAZ is forward azimuth in radians from pt1 to pt2;\r // BAZ is backward azimuth from point 2 to 1;\r // S is distance in meters.\r //\r // Conversion to JAVA from FORTRAN was made with as few changes as possible\r // to avoid errors made while recasting form, and to facilitate any future\r // comparisons between the original code and the altered version in Java.\r //\r //IMPLICIT REAL*8 (A-H,O-Z)\r //  COMMON/CONST/PI,RAD\r //  COMMON/ELIPSOID/A,F\r double GLAT1 = rad * lat1 ; double GLAT2 = rad * lat2 ; double TU1 = R * Math . sin ( GLAT1 ) / Math . cos ( GLAT1 ) ; double TU2 = R * Math . sin ( GLAT2 ) / Math . cos ( GLAT2 ) ; double CU1 = 1. / Math . sqrt ( TU1 * TU1 + 1. ) ; double SU1 = CU1 * TU1 ; double CU2 = 1. / Math . sqrt ( TU2 * TU2 + 1. ) ; double S = CU1 * CU2 ; double BAZ = S * TU2 ; double FAZ = BAZ * TU1 ; double GLON1 = rad * lon1 ; double GLON2 = rad * lon2 ; double X = GLON2 - GLON1 ; double D , SX , CX , SY , CY , Y , SA , C2A , CZ , E , C ; int loopCnt = 0 ; do { loopCnt ++ ; //Check for an infinite loop\r if ( loopCnt > 1000 ) { throw new IllegalArgumentException ( \"Too many iterations calculating bearing:\" + lat1 + \" \" + lon1 + \" \" + lat2 + \" \" + lon2 ) ; } SX = Math . sin ( X ) ; CX = Math . cos ( X ) ; TU1 = CU2 * SX ; TU2 = BAZ - SU1 * CU2 * CX ; SY = Math . sqrt ( TU1 * TU1 + TU2 * TU2 ) ; CY = S * CX + FAZ ; Y = Math . atan2 ( SY , CY ) ; SA = S * SX / SY ; C2A = - SA * SA + 1. ; CZ = FAZ + FAZ ; if ( C2A > 0. ) { CZ = - CZ / C2A + CY ; } E = CZ * CZ * 2. - 1. ; C = ( ( - 3. * C2A + 4. ) * F + 4. ) * C2A * F / 16. ; D = X ; X = ( ( E * CY * C + CZ ) * SY * C + Y ) * SA ; X = ( 1. - C ) * X * F + GLON2 - GLON1 ; //IF(DABS(D-X).GT.EPS) GO TO 100\r } while ( Math . abs ( D - X ) > EPS ) ; if ( loopCnt > maxLoopCnt ) { maxLoopCnt = loopCnt ; //        System.err.println(\"loopCnt:\" + loopCnt);\r } FAZ = Math . atan2 ( TU1 , TU2 ) ; BAZ = Math . atan2 ( CU1 * SX , BAZ * CX - SU1 * CU2 ) + Math . PI ; X = Math . sqrt ( ( 1. / R / R - 1. ) * C2A + 1. ) + 1. ; X = ( X - 2. ) / X ; C = 1. - X ; C = ( X * X / 4. + 1. ) / C ; D = ( 0.375 * X * X - 1. ) * X ; X = E * CY ; S = 1. - E - E ; S = ( ( ( ( SY * SY * 4. - 3. ) * S * CZ * D / 6. - X ) * D / 4. + CZ ) * SY * D + Y ) * C * A * R ; result . distance = S / 1000.0 ; // meters to km\r result . azimuth = FAZ * deg ; // radians to degrees\r if ( result . azimuth < 0.0 ) { result . azimuth += 360.0 ; // reset azs from -180 to 180 to 0 to 360\r } result . backazimuth = BAZ * deg ; // radians to degrees; already in 0 to 360 range\r return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test the calculations - forward and back [CODESPLIT] public static void main ( String [ ] args ) { //Bearing         workBearing = new Bearing();\r LatLonPointImpl pt1 = new LatLonPointImpl ( 40 , - 105 ) ; LatLonPointImpl pt2 = new LatLonPointImpl ( 37.4 , - 118.4 ) ; Bearing b = calculateBearing ( pt1 , pt2 , null ) ; System . out . println ( \"Bearing from \" + pt1 + \" to \" + pt2 + \" = \\n\\t\" + b ) ; LatLonPointImpl pt3 = new LatLonPointImpl ( ) ; pt3 = findPoint ( pt1 , b . getAngle ( ) , b . getDistance ( ) , pt3 ) ; System . out . println ( \"using first point, angle and distance, found second point at \" + pt3 ) ; pt3 = findPoint ( pt2 , b . getBackAzimuth ( ) , b . getDistance ( ) , pt3 ) ; System . out . println ( \"using second point, backazimuth and distance, found first point at \" + pt3 ) ; /*  uncomment for timing tests\r\n        for(int j=0;j<10;j++) {\r\n            long t1 = System.currentTimeMillis();\r\n            for(int i=0;i<30000;i++) {\r\n                workBearing = Bearing.calculateBearing(42.5,-93.0,\r\n                                                       48.9,-117.09,workBearing);\r\n            }\r\n            long t2 = System.currentTimeMillis();\r\n            System.err.println (\"time:\" + (t2-t1));\r\n        }\r\n        */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate a position given an azimuth and distance from another point . [CODESPLIT] public static LatLonPointImpl findPoint ( Earth e , LatLonPoint pt1 , double az , double dist , LatLonPointImpl result ) { return findPoint ( e , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , az , dist , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate a position given an azimuth and distance from another point . Uses default Earth . [CODESPLIT] public static LatLonPointImpl findPoint ( LatLonPoint pt1 , double az , double dist , LatLonPointImpl result ) { return findPoint ( defaultEarth , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , az , dist , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate a position given an azimuth and distance from another point . See details below . Uses default Earth . [CODESPLIT] public static LatLonPointImpl findPoint ( double lat1 , double lon1 , double az , double dist , LatLonPointImpl result ) { return findPoint ( defaultEarth , lat1 , lon1 , az , dist , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate a position given an azimuth and distance from another point . <p / > <p / > Algorithm from National Geodetic Survey FORTRAN program forward subroutine DIRCT1 by stephen j . frakes . http : // www . ngs . noaa . gov / TOOLS / Inv_Fwd / Inv_Fwd . html <p > Original documentation : <pre > SOLUTION OF THE GEODETIC DIRECT PROBLEM AFTER T . VINCENTY MODIFIED RAINSFORD S METHOD WITH HELMERT S ELLIPTICAL TERMS EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL < / pre > [CODESPLIT] public static LatLonPointImpl findPoint ( Earth e , double lat1 , double lon1 , double az , double dist , LatLonPointImpl result ) { if ( result == null ) { result = new LatLonPointImpl ( ) ; } if ( ( dist == 0 ) ) { result . setLatitude ( lat1 ) ; result . setLongitude ( lon1 ) ; return result ; } A = e . getMajor ( ) ; F = e . getFlattening ( ) ; R = 1.0 - F ; // Algorithm from National Geodetic Survey, FORTRAN program \"forward,\"\r // subroutine \"DIRCT1,\" by stephen j. frakes.\r // http://www.ngs.noaa.gov/TOOLS/Inv_Fwd/Inv_Fwd.html\r // Conversion to JAVA from FORTRAN was made with as few changes as\r // possible to avoid errors made while recasting form, and\r // to facilitate any future comparisons between the original\r // code and the altered version in Java.\r // Original documentation:\r //   SUBROUTINE DIRCT1(GLAT1,GLON1,GLAT2,GLON2,FAZ,BAZ,S)\r //\r //   SOLUTION OF THE GEODETIC DIRECT PROBLEM AFTER T.VINCENTY\r //   MODIFIED RAINSFORD'S METHOD WITH HELMERT'S ELLIPTICAL TERMS\r //   EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL\r //\r //   A IS THE SEMI-MAJOR AXIS OF THE REFERENCE ELLIPSOID\r //   F IS THE FLATTENING OF THE REFERENCE ELLIPSOID\r //   LATITUDES AND LONGITUDES IN RADIANS POSITIVE NORTH AND EAST\r //   AZIMUTHS IN RADIANS CLOCKWISE FROM NORTH\r //   GEODESIC DISTANCE S ASSUMED IN UNITS OF SEMI-MAJOR AXIS A\r //\r //   PROGRAMMED FOR CDC-6600 BY LCDR L.PFEIFER NGS ROCKVILLE MD 20FEB75\r //   MODIFIED FOR SYSTEM 360 BY JOHN G GERGEN NGS ROCKVILLE MD 750608\r //\r if ( az < 0.0 ) { az += 360.0 ; // reset azs from -180 to 180 to 0 to 360\r } double FAZ = az * rad ; double GLAT1 = lat1 * rad ; double GLON1 = lon1 * rad ; double S = dist * 1000. ; // convert to meters\r double TU = R * Math . sin ( GLAT1 ) / Math . cos ( GLAT1 ) ; double SF = Math . sin ( FAZ ) ; double CF = Math . cos ( FAZ ) ; double BAZ = 0. ; if ( CF != 0 ) { BAZ = Math . atan2 ( TU , CF ) * 2 ; } double CU = 1. / Math . sqrt ( TU * TU + 1. ) ; double SU = TU * CU ; double SA = CU * SF ; double C2A = - SA * SA + 1. ; double X = Math . sqrt ( ( 1. / R / R - 1. ) * C2A + 1. ) + 1. ; X = ( X - 2. ) / X ; double C = 1. - X ; C = ( X * X / 4. + 1 ) / C ; double D = ( 0.375 * X * X - 1. ) * X ; TU = S / R / A / C ; double Y = TU ; double SY , CY , CZ , E , GLAT2 , GLON2 ; do { SY = Math . sin ( Y ) ; CY = Math . cos ( Y ) ; CZ = Math . cos ( BAZ + Y ) ; E = CZ * CZ * 2. - 1. ; C = Y ; X = E * CY ; Y = E + E - 1. ; Y = ( ( ( SY * SY * 4. - 3. ) * Y * CZ * D / 6. + X ) * D / 4. - CZ ) * SY * D + TU ; } while ( Math . abs ( Y - C ) > EPS ) ; BAZ = CU * CY * CF - SU * SY ; C = R * Math . sqrt ( SA * SA + BAZ * BAZ ) ; D = SU * CY + CU * SY * CF ; GLAT2 = Math . atan2 ( D , C ) ; C = CU * CY - SU * SY * CF ; X = Math . atan2 ( SY * SF , C ) ; C = ( ( - 3. * C2A + 4. ) * F + 4. ) * C2A * F / 16. ; D = ( ( E * CY * C + CZ ) * SY * C + Y ) * SA ; GLON2 = GLON1 + X - ( 1. - C ) * D * F ; BAZ = ( Math . atan2 ( SA , BAZ ) + Math . PI ) * deg ; result . setLatitude ( GLAT2 * deg ) ; result . setLongitude ( GLON2 * deg ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to invoke with a filename or URL of a picture that is to be loaded a new thread . This is handy to update the screen while the loading chuggs along in the background . [CODESPLIT] public void loadPictureInThread ( URL imageUrl , int priority , double rotation ) { if ( pictureStatusCode == LOADING ) { stopLoadingExcept ( imageUrl ) ; } this . imageUrl = imageUrl ; this . rotation = rotation ; LoadThread t = new LoadThread ( this ) ; t . setPriority ( priority ) ; t . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to invoke with a filename or URL of a picture that is to be loaded in the main thread . [CODESPLIT] public void loadPicture ( URL imageUrl , double rotation ) { if ( pictureStatusCode == LOADING ) { stopLoadingExcept ( imageUrl ) ; } this . imageUrl = imageUrl ; this . rotation = rotation ; loadPicture ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "loads a picture from the URL in the imageUrl object into the sourcePictureBufferedImage object and updates the status when done or failed . [CODESPLIT] public void loadPicture ( ) { Tools . log ( \"SourcePicture.loadPicture: \" + imageUrl . toString ( ) + \" loaded into SourcePicture object: \" + Integer . toString ( this . hashCode ( ) ) ) ; //Tools.freeMem(); setStatus ( LOADING , \"Loading: \" + imageUrl . toString ( ) ) ; abortFlag = false ; try { // Java 1.4 way with a Listener ImageInputStream iis = ImageIO . createImageInputStream ( imageUrl . openStream ( ) ) ; Iterator i = ImageIO . getImageReaders ( iis ) ; if ( ! i . hasNext ( ) ) { throw new IOException ( \"No Readers Available!\" ) ; } reader = ( ImageReader ) i . next ( ) ; // grab the first one reader . addIIOReadProgressListener ( imageProgressListener ) ; reader . setInput ( iis ) ; sourcePictureBufferedImage = null ; // try { sourcePictureBufferedImage = reader . read ( 0 ) ; // just get the first image /* } catch ( OutOfMemoryError e ) {\n\t\t\t\tTools.log(\"SourcePicture caught an OutOfMemoryError while loading an image.\" );\n\n\t\t\t\tiis.close();\n\t\t\t\treader.removeIIOReadProgressListener( imageProgressListener );\n\t\t\t\treader.dispose();\n\n\t\t\t\tsetStatus(ERROR, \"Out of Memory Error while reading \" + imageUrl.toString());\n\t\t\t\tsourcePictureBufferedImage = null; \n\t\t\t\t// PictureCache.clear();\n\n\t\t\t\tJOptionPane.showMessageDialog( null,  //deliberately null or it swaps the window\n\t\t\t\t\t\"outOfMemoryError\",\n\t\t\t\t\t\"genericError\",\n\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\n\n\t\t\t\tSystem.gc();\n\t\t\t\tSystem.runFinalization();\n\n\t\t\t\tTools.log(\"JPO has now run a garbage collection and finalization.\");\n\t\t\t\treturn;\n\t\t\t} */ iis . close ( ) ; reader . removeIIOReadProgressListener ( imageProgressListener ) ; //Tools.log(\"!!dispose being called!!\"); reader . dispose ( ) ; if ( ! abortFlag ) { if ( rotation != 0 ) { setStatus ( ROTATING , \"Rotating: \" + imageUrl . toString ( ) ) ; int xRot = sourcePictureBufferedImage . getWidth ( ) / 2 ; int yRot = sourcePictureBufferedImage . getHeight ( ) / 2 ; AffineTransform rotateAf = AffineTransform . getRotateInstance ( Math . toRadians ( rotation ) , xRot , yRot ) ; AffineTransformOp op = new AffineTransformOp ( rotateAf , AffineTransformOp . TYPE_BILINEAR ) ; Rectangle2D newBounds = op . getBounds2D ( sourcePictureBufferedImage ) ; // a simple AffineTransform would give negative top left coordinates --> // do another transform to get 0,0 as top coordinates again. double minX = newBounds . getMinX ( ) ; double minY = newBounds . getMinY ( ) ; AffineTransform translateAf = AffineTransform . getTranslateInstance ( minX * ( - 1 ) , minY * ( - 1 ) ) ; rotateAf . preConcatenate ( translateAf ) ; op = new AffineTransformOp ( rotateAf , AffineTransformOp . TYPE_BILINEAR ) ; newBounds = op . getBounds2D ( sourcePictureBufferedImage ) ; // this piece of code is so essential!!! Otherwise the internal image format // is totally altered and either the AffineTransformOp decides it doesn't // want to rotate the image or web browsers can't read the resulting image. BufferedImage targetImage = new BufferedImage ( ( int ) newBounds . getWidth ( ) , ( int ) newBounds . getHeight ( ) , BufferedImage . TYPE_3BYTE_BGR ) ; sourcePictureBufferedImage = op . filter ( sourcePictureBufferedImage , targetImage ) ; } setStatus ( READY , \"Loaded: \" + imageUrl . toString ( ) ) ; PictureCache . add ( imageUrl , ( SourcePicture ) this . clone ( ) ) ; } else { setStatus ( ERROR , \"Aborted: \" + imageUrl . toString ( ) ) ; sourcePictureBufferedImage = null ; } } catch ( IOException e ) { setStatus ( ERROR , \"Error while reading \" + imageUrl . toString ( ) ) ; sourcePictureBufferedImage = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method can be invoked to stop the current reader [CODESPLIT] public void stopLoading ( ) { if ( imageUrl == null ) return ; // SourcePicture has never been used yet Tools . log ( \"SourcePicture.stopLoading: called on \" + imageUrl ) ; if ( pictureStatusCode == LOADING ) { reader . abort ( ) ; abortFlag = true ; //reader.dispose(); //setStatus( ERROR, \"Cache Loading was stopped \" + imageUrl.toString() ); //sourcePictureBufferedImage = null;  // actually the thread reading the image continues } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method can be invoked to stop the current reader except if it is reading the desired file . It returns true is the desired file is being loaded . Otherwise it returns false . [CODESPLIT] public boolean stopLoadingExcept ( URL exemptionURL ) { if ( imageUrl == null ) return false ; // has never been used yet if ( pictureStatusCode != LOADING ) { Tools . log ( \"SourcePicture.stopLoadingExcept: called but pointless since image is not LOADING: \" + imageUrl . toString ( ) ) ; return false ; } if ( ! exemptionURL . toString ( ) . equals ( imageUrl . toString ( ) ) ) { Tools . log ( \"SourcePicture.stopLoadingExcept: called with Url \" + exemptionURL . toString ( ) + \" --> stopping loading of \" + imageUrl . toString ( ) ) ; stopLoading ( ) ; return true ; } else return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the size of the image or Zero if there is none [CODESPLIT] public Dimension getSize ( ) { if ( sourcePictureBufferedImage != null ) return new Dimension ( sourcePictureBufferedImage . getWidth ( ) , sourcePictureBufferedImage . getHeight ( ) ) ; else return new Dimension ( 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to register the listening object of the status events [CODESPLIT] public void addListener ( SourcePictureListener listener ) { Tools . log ( \"SourcePicture.addListener: listener added on SourcePicture \" + Integer . toString ( this . hashCode ( ) ) + \" of class: \" + listener . getClass ( ) . toString ( ) ) ; sourcePictureListeners . add ( listener ) ; //showListeners(); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to register the listening object of the status events [CODESPLIT] public void removeListener ( SourcePictureListener listener ) { Tools . log ( \"SourcePicture.removeListener: listener removed from SourcePicture \" + Integer . toString ( this . hashCode ( ) ) + \" of class: \" + listener . getClass ( ) . toString ( ) ) ; sourcePictureListeners . remove ( listener ) ; //showListeners(); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that sets the status of the ScalablePicture object and notifies intereasted objects of a change in status ( not built yet ) . [CODESPLIT] private void setStatus ( int statusCode , String statusMessage ) { Tools . log ( \"\\nSourcePicture.setStatus: sending status: \" + statusMessage ) ; pictureStatusCode = statusCode ; pictureStatusMessage = statusMessage ; Vector nonmodifiedVector = ( Vector ) sourcePictureListeners . clone ( ) ; Enumeration e = nonmodifiedVector . elements ( ) ; while ( e . hasMoreElements ( ) ) { //((SourcePictureListener) e.nextElement()) //\t.sourceStatusChange(pictureStatusCode, pictureStatusMessage, this ); SourcePictureListener spl = ( ( SourcePictureListener ) e . nextElement ( ) ) ; spl . sourceStatusChange ( pictureStatusCode , pictureStatusMessage , this ) ; Tools . log ( \"\\nSourcePicture.setStatus: sending status: \" + statusMessage + \" to \" + spl . getClass ( ) . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the buffered image . Unusual method use with care . [CODESPLIT] public void setSourceBufferedImage ( BufferedImage img , String statusMessage ) { sourcePictureBufferedImage = img ; setStatus ( READY , statusMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct the standard THREDDS access URI for this dataset access method resolved agaisnt the parent catalog if the URI is relative . [CODESPLIT] public URI getStandardUri ( ) { try { Catalog cat = dataset . getParentCatalog ( ) ; if ( cat == null ) return new URI ( getUnresolvedUrlName ( ) ) ; return cat . resolveUri ( getUnresolvedUrlName ( ) ) ; } catch ( java . net . URISyntaxException e ) { throw new RuntimeException ( \"Error parsing URL= \" + getUnresolvedUrlName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for associated fields [CODESPLIT] DataDescriptor makeAssociatedField ( int bitWidth ) { DataDescriptor assDD = new DataDescriptor ( ) ; assDD . name = name + \"_associated_field\" ; assDD . units = \"\" ; assDD . refVal = 0 ; assDD . scale = 0 ; assDD . bitWidth = bitWidth ; assDD . type = 0 ; assDD . f = 0 ; assDD . x = 31 ; assDD . y = 22 ; assDD . fxy = ( short ) ( ( f << 14 ) + ( x << 8 ) + ( y ) ) ; return assDD ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transfer info from the proto message to another message with the exact same structure . [CODESPLIT] static public void transferInfo ( List < DataDescriptor > fromList , List < DataDescriptor > toList ) { // get info from proto message\r if ( fromList . size ( ) != toList . size ( ) ) throw new IllegalArgumentException ( \"list sizes dont match \" + fromList . size ( ) + \" != \" + toList . size ( ) ) ; for ( int i = 0 ; i < fromList . size ( ) ; i ++ ) { DataDescriptor from = fromList . get ( i ) ; DataDescriptor to = toList . get ( i ) ; to . refersTo = from . refersTo ; to . name = from . name ; if ( from . getSubKeys ( ) != null ) transferInfo ( from . getSubKeys ( ) , to . getSubKeys ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "count the bits used by the data in this dd and its children only accurate for not compressed and not variable length [CODESPLIT] int countBits ( ) { int total_nbits = 0 ; total_nbytesCDM = 0 ; for ( DataDescriptor dd : subKeys ) { if ( dd . subKeys != null ) { total_nbits += dd . countBits ( ) ; total_nbytesCDM += dd . total_nbytesCDM ; } else if ( dd . f == 0 ) { total_nbits += dd . bitWidth ; total_nbytesCDM += dd . getByteWidthCDM ( ) ; } } // replication\r if ( replication > 1 ) { total_nbits *= replication ; total_nbytesCDM *= replication ; } return total_nbits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK need different hashCode reader assumes using object id [CODESPLIT] public boolean equals2 ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) != o . getClass ( ) ) return false ; DataDescriptor that = ( DataDescriptor ) o ; if ( fxy != that . fxy ) return false ; if ( replication != that . replication ) return false ; if ( type != that . type ) return false ; if ( subKeys != null ? ! subKeys . equals ( that . subKeys ) : that . subKeys != null ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "has to use hashCode2 so cant use list . hashCode () [CODESPLIT] private int getListHash ( ) { if ( subKeys == null ) return 0 ; int result = 1 ; for ( DataDescriptor e : subKeys ) result = 31 * result + ( e == null ? 0 : e . hashCode2 ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the dbase file header . [CODESPLIT] private int loadHeader ( ) { if ( headerLoaded ) return 0 ; InputStream s = stream ; if ( s == null ) return - 1 ; try { BufferedInputStream bs = new BufferedInputStream ( s ) ; ds = new DataInputStream ( bs ) ; /* read the header as one block of bytes*/ Header = new byte [ 32 ] ; ds . readFully ( Header ) ; //System.out.println(\"dbase header is \" + Header);\r if ( Header [ 0 ] == ' ' ) { //looks like html coming back to us!\r close ( ds ) ; return - 1 ; } filetype = Header [ 0 ] ; /* 4 bytes for number of records is in little endian */ nrecords = Swap . swapInt ( Header , 4 ) ; nbytesheader = Swap . swapShort ( Header , 8 ) ; /* read in the Field Descriptors */ /* have to figure how many there are from\r\n      * the header size.  Should be nbytesheader/32 -1\r\n      */ nfields = ( nbytesheader / 32 ) - 1 ; if ( nfields < 1 ) { System . out . println ( \"nfields = \" + nfields ) ; System . out . println ( \"nbytesheader = \" + nbytesheader ) ; return - 1 ; } FieldDesc = new DbaseFieldDesc [ nfields ] ; data = new DbaseData [ nfields ] ; for ( int i = 0 ; i < nfields ; i ++ ) { FieldDesc [ i ] = new DbaseFieldDesc ( ds , filetype ) ; data [ i ] = new DbaseData ( FieldDesc [ i ] , nrecords ) ; } /* read the last byte of the header (0x0d) */ ds . readByte ( ) ; headerLoaded = true ; } catch ( java . io . IOException e ) { close ( s ) ; return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the dbase file data . [CODESPLIT] private int loadData ( ) { if ( ! headerLoaded ) return - 1 ; if ( dataLoaded ) return 0 ; InputStream s = stream ; if ( s == null ) return - 1 ; try { /* read in the data */ for ( int i = 0 ; i < nrecords ; i ++ ) { /* read the data record indicator */ byte recbyte = ds . readByte ( ) ; if ( recbyte == 0x20 ) { for ( int j = 0 ; j < nfields ; j ++ ) { data [ j ] . readRowN ( ds , i ) ; } } else { /* a deleted record */ nrecords -- ; i -- ; } } dataLoaded = true ; } catch ( java . io . IOException e ) { close ( s ) ; return - 1 ; } finally { close ( s ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the data for a given field by name . [CODESPLIT] public DbaseData getField ( String Name ) { for ( int i = 0 ; i < nfields ; i ++ ) { if ( FieldDesc [ i ] . Name . equals ( Name ) ) return data [ i ] ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the double array of data for a field by Name . [CODESPLIT] public double [ ] getDoublesByName ( String Name ) { DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) == DbaseData . TYPE_CHAR ) { String [ ] s = d . getStrings ( ) ; double [ ] dd = new double [ s . length ] ; for ( int i = 0 ; i < s . length ; i ++ ) { dd [ i ] = Double . valueOf ( s [ i ] ) ; } return dd ; } if ( d . getType ( ) == DbaseData . TYPE_BOOLEAN ) { boolean [ ] b = d . getBooleans ( ) ; double [ ] dd = new double [ b . length ] ; for ( int i = 0 ; i < b . length ; i ++ ) { if ( b [ i ] ) { dd [ i ] = 1 ; } else { dd [ i ] = 0 ; } } return dd ; } return d . getDoubles ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the string array of data for a field by Name . [CODESPLIT] public String [ ] getStringsByName ( String Name ) { DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) != DbaseData . TYPE_CHAR ) return null ; return d . getStrings ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the boolean array of data for a field by Name . [CODESPLIT] public boolean [ ] getBooleansByName ( String Name ) { DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) != DbaseData . TYPE_BOOLEAN ) return null ; return d . getBooleans ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the name of a field by column number . [CODESPLIT] public String getFieldName ( int i ) { if ( i >= nfields || i < 0 ) { return null ; } return ( FieldDesc [ i ] . Name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a list of all the field names in the dbase file [CODESPLIT] public String [ ] getFieldNames ( ) { String [ ] s = new String [ nfields ] ; for ( int i = 0 ; i < nfields ; i ++ ) { s [ i ] = getFieldName ( i ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test program dumps a Dbase file to stdout . [CODESPLIT] public static void main ( String [ ] args ) { if ( args . length < 1 ) { System . out . println ( \"filename or URL required\" ) ; System . exit ( - 1 ) ; } for ( String s : args ) { System . out . println ( \"*** Dump of Dbase \" + s + \":\" ) ; try { DbaseFile dbf = new DbaseFile ( s ) ; // load() method reads all data at once\r if ( dbf . loadHeader ( ) != 0 ) { System . out . println ( \"Error loading header\" + s ) ; System . exit ( - 1 ) ; } // output schema as [type0 field0, type1 field1, ...]\r String [ ] fieldNames = dbf . getFieldNames ( ) ; System . out . print ( \"[\" ) ; int nf = dbf . getNumFields ( ) ; DbaseData [ ] dbd = new DbaseData [ nf ] ; for ( int field = 0 ; field < nf ; field ++ ) { dbd [ field ] = dbf . getField ( field ) ; switch ( dbd [ field ] . getType ( ) ) { case DbaseData . TYPE_BOOLEAN : System . out . print ( \"boolean \" ) ; break ; case DbaseData . TYPE_CHAR : System . out . print ( \"String \" ) ; break ; case DbaseData . TYPE_NUMERIC : System . out . print ( \"double \" ) ; break ; } System . out . print ( fieldNames [ field ] ) ; if ( field < nf - 1 ) System . out . print ( \", \" ) ; } System . out . println ( \"]\" ) ; if ( dbf . loadData ( ) != 0 ) { System . out . println ( \"Error loading data\" + s ) ; System . exit ( - 1 ) ; } // output data\r for ( int rec = 0 ; rec < dbf . getNumRecords ( ) ; rec ++ ) { for ( int field = 0 ; field < nf ; field ++ ) { System . out . print ( dbd [ field ] . getData ( rec ) ) ; if ( field < nf - 1 ) System . out . print ( \", \" ) ; else System . out . println ( ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attributes are not allowed on some node types [CODESPLIT] public Map < String , DapAttribute > getAttributes ( ) { if ( attributes == null ) attributes = new HashMap < String , DapAttribute > ( ) ; return attributes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This may occur after initial construction [CODESPLIT] synchronized public DapAttribute setAttribute ( DapAttribute attr ) throws DapException { if ( attributes == null ) attributes = new HashMap < String , DapAttribute > ( ) ; DapAttribute old = attributes . get ( attr . getShortName ( ) ) ; attributes . put ( attr . getShortName ( ) , attr ) ; attr . setParent ( this ) ; return old ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by AbstractDSP to suppress certain attributes . [CODESPLIT] public synchronized void removeAttribute ( DapAttribute attr ) throws DapException { if ( this . attributes == null ) return ; String name = attr . getShortName ( ) ; if ( this . attributes . containsKey ( name ) ) this . attributes . remove ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closest containing group [CODESPLIT] public DapGroup getGroup ( ) { if ( this . sort == DapSort . DATASET ) return null ; // Walk the parent node until we find a group DapNode group = parent ; while ( group != null ) { switch ( group . getSort ( ) ) { case DATASET : case GROUP : return ( DapGroup ) group ; default : group = group . getParent ( ) ; break ; } } return ( DapGroup ) group ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closest containing group structure sequence [CODESPLIT] public DapNode getContainer ( ) { DapNode parent = this . parent ; switch ( getSort ( ) ) { default : break ; case ENUMCONST : parent = ( ( DapEnumConst ) this ) . getParent ( ) . getContainer ( ) ; break ; case ATTRIBUTE : case ATTRIBUTESET : case OTHERXML : parent = ( ( DapAttribute ) this ) . getParent ( ) ; if ( parent instanceof DapVariable ) parent = parent . getContainer ( ) ; break ; case MAP : parent = ( ( DapMap ) this ) . getVariable ( ) . getContainer ( ) ; break ; } return parent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the parent DapNode ; may sometimes be same as container but not always ( think attributes or maps ) . Invariant : parent must be either a group or a variable . We can infer the container so set that also . [CODESPLIT] public void setParent ( DapNode parent ) { assert this . parent == null ; assert ( ( this . getSort ( ) == DapSort . ENUMCONST && parent . getSort ( ) == DapSort . ENUMERATION ) || parent . getSort ( ) . isa ( DapSort . GROUP ) || parent . getSort ( ) == DapSort . VARIABLE || parent . getSort ( ) == DapSort . STRUCTURE || parent . getSort ( ) == DapSort . SEQUENCE || this . getSort ( ) == DapSort . ATTRIBUTE || this . getSort ( ) == DapSort . ATTRIBUTESET ) ; this . parent = parent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Here escaped means backslash escaped short name [CODESPLIT] public String getEscapedShortName ( ) { if ( this . escapedname == null ) this . escapedname = Escape . backslashEscape ( getShortName ( ) , null ) ; return this . escapedname ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the path upto and including some specified containing node ( null = > root ) The containing node is included as is this node . [CODESPLIT] public List < DapNode > getPath ( ) { List < DapNode > path = new ArrayList < DapNode > ( ) ; DapNode current = this ; for ( ; ; ) { path . add ( 0 , current ) ; current = current . getParent ( ) ; if ( current == null ) break ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the transitive list of containers Not including this node [CODESPLIT] public List < DapNode > getContainerPath ( ) { List < DapNode > path = new ArrayList < DapNode > ( ) ; DapNode current = this . getContainer ( ) ; for ( ; ; ) { path . add ( 0 , current ) ; if ( current . getContainer ( ) == null ) break ; current = current . getContainer ( ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the transitive list of containing groups Possibly including this node [CODESPLIT] public List < DapGroup > getGroupPath ( ) { List < DapGroup > path = new ArrayList < DapGroup > ( ) ; DapNode current = this ; for ( ; ; ) { if ( current . getSort ( ) == DapSort . GROUP || current . getSort ( ) == DapSort . DATASET ) path . add ( 0 , ( DapGroup ) current ) ; if ( current . getContainer ( ) == null ) break ; current = current . getContainer ( ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the FQN of this node [CODESPLIT] public String computefqn ( ) { List < DapNode > path = getPath ( ) ; // excludes root/wrt StringBuilder fqn = new StringBuilder ( ) ; DapNode parent = path . get ( 0 ) ; for ( int i = 1 ; i < path . size ( ) ; i ++ ) { // start at 1 to skip root DapNode current = path . get ( i ) ; // Depending on what parent is, use different delimiters switch ( parent . getSort ( ) ) { case DATASET : case GROUP : case ENUMERATION : fqn . append ( ' ' ) ; fqn . append ( Escape . backslashEscape ( current . getShortName ( ) , \"/.\" ) ) ; break ; // These use '.' case STRUCTURE : case SEQUENCE : case ENUMCONST : case VARIABLE : fqn . append ( ' ' ) ; fqn . append ( current . getEscapedShortName ( ) ) ; break ; default : // Others should never happen throw new IllegalArgumentException ( \"Illegal FQN parent\" ) ; } parent = current ; } return fqn . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Misc . Methods [CODESPLIT] public boolean isTopLevel ( ) { return parent == null || parent . getSort ( ) == DapSort . DATASET || parent . getSort ( ) == DapSort . GROUP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TypedDatasetFactoryIF [CODESPLIT] public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { String convStr = ncd . findAttValueIgnoreCase ( null , \"Conventions\" , null ) ; if ( ( null != convStr ) && convStr . startsWith ( \"CF/Radial\" ) ) return this ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] protected void addRadialVariable ( NetcdfDataset nds , Variable var ) { RadialVariable rsvar = null ; String vName = var . getShortName ( ) ; int tIdx = var . findDimensionIndex ( \"time\" ) ; int rIdx = var . findDimensionIndex ( \"range\" ) ; int ptsIdx = var . findDimensionIndex ( \"n_points\" ) ; if ( ( ( tIdx == 0 ) && ( rIdx == 1 ) ) || ( ptsIdx == 0 ) ) { VariableSimpleIF v = new MyRadialVariableAdapter ( vName , var . getAttributes ( ) ) ; rsvar = makeRadialVariable ( nds , v , var ) ; } if ( rsvar != null ) { dataVariables . add ( rsvar ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] public String getInfo ( ) { StringBuffer sbuff = new StringBuffer ( ) ; sbuff . append ( \"CFRadial2Dataset\\n\" ) ; sbuff . append ( super . getDetailInfo ( ) ) ; sbuff . append ( \"\\n\\n\" ) ; sbuff . append ( parseInfo . toString ( ) ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compilation [CODESPLIT] protected void build ( String document , byte [ ] serialdata , ByteOrder order ) throws DapException { DapDataset dmr = parseDMR ( document ) ; if ( DEBUG || DUMPDMR ) { System . err . println ( \"\\n+++++++++++++++++++++\" ) ; System . err . println ( dmr ) ; System . err . println ( \"+++++++++++++++++++++\\n\" ) ; } if ( DEBUG || DUMPDAP ) { ByteBuffer data = ByteBuffer . wrap ( serialdata ) ; System . err . println ( \"+++++++++++++++++++++\" ) ; System . err . println ( \"\\n---------------------\" ) ; DapDump . dumpbytes ( data , false ) ; System . err . println ( \"\\n---------------------\\n\" ) ; } build ( dmr , serialdata , order ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the data from the incoming serial data Note that some DSP s will not use [CODESPLIT] protected void build ( DapDataset dmr , byte [ ] serialdata , ByteOrder order ) throws DapException { setDMR ( dmr ) ; // \"Compile\" the databuffer section of the server response this . databuffer = ByteBuffer . wrap ( serialdata ) . order ( order ) ; D4DataCompiler compiler = new D4DataCompiler ( this , getChecksumMode ( ) , getOrder ( ) , this . databuffer ) ; compiler . compile ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not tested [CODESPLIT] private void write ( StationObsDataset sobsDataset ) throws IOException { createGlobalAttributes ( ) ; createStations ( sobsDataset . getStations ( ) ) ; ncfile . addGlobalAttribute ( \"time_coverage_start\" , dateFormatter . toDateTimeStringISO ( sobsDataset . getStartDate ( ) ) ) ; ncfile . addGlobalAttribute ( \"time_coverage_end\" , dateFormatter . toDateTimeStringISO ( sobsDataset . getEndDate ( ) ) ) ; createDataVariables ( sobsDataset . getDataVariables ( ) ) ; // global attributes List gatts = sobsDataset . getGlobalAttributes ( ) ; for ( int i = 0 ; i < gatts . size ( ) ; i ++ ) { Attribute att = ( Attribute ) gatts . get ( i ) ; ncfile . addGlobalAttribute ( att ) ; } // done with define mode ncfile . create ( ) ; // write out the station info writeStationData ( sobsDataset . getStations ( ) ) ; // now write the observations if ( ! ( Boolean ) ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ) throw new IllegalStateException ( \"can't add record variable\" ) ; int [ ] origin = new int [ 1 ] ; int [ ] originTime = new int [ 2 ] ; int recno = 0 ; ArrayStructureW sArray = null ; ArrayObject . D1 timeArray = new ArrayObject . D1 ( DataType . STRING , String . class , false , 1 ) ; DataIterator diter = sobsDataset . getDataIterator ( 1000 * 1000 ) ; while ( diter . hasNext ( ) ) { StationObsDatatype sobs = ( StationObsDatatype ) diter . nextData ( ) ; StructureData recordData = sobs . getData ( ) ; // needs to be wrapped as an ArrayStructure, even though we are only writing one at a time. if ( sArray == null ) sArray = new ArrayStructureW ( recordData . getStructureMembers ( ) , new int [ ] { 1 } ) ; sArray . setStructureData ( recordData , 0 ) ; // date is handled specially timeArray . set ( 0 , dateFormatter . toDateTimeStringISO ( sobs . getObservationTimeAsDate ( ) ) ) ; // write the recno record origin [ 0 ] = recno ; originTime [ 0 ] = recno ; try { ncfile . write ( \"record\" , origin , sArray ) ; ncfile . writeStringData ( timeName , originTime , timeArray ) ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; throw new IllegalStateException ( e ) ; } recno ++ ; } ncfile . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the object that has the specified key . This returns the object itself not a copy so if you change the bean and call store . save () any changes to the object will be saved even without calling putBean () . If you want to change the object without saving the changes you must make a copy of the object yourself . [CODESPLIT] public Object getBean ( String key , Object def ) { if ( key == null ) throw new NullPointerException ( \"Null key\" ) ; if ( isRemoved ( ) ) throw new IllegalStateException ( \"Node has been removed.\" ) ; synchronized ( lock ) { Object result = null ; try { result = _getObject ( key ) ; if ( result != null ) { if ( result instanceof Bean . Collection ) result = ( ( Bean . Collection ) result ) . getCollection ( ) ; else if ( result instanceof Bean ) result = ( ( Bean ) result ) . getObject ( ) ; } } catch ( Exception e ) { // Ignoring exception causes default to be returned } return ( result == null ? def : result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores an object using simple bean properties . If the exact key and value are already in the storedDefaults ( using equals () to test for equality ) then it is not stored . [CODESPLIT] public void putBean ( String key , Object newValue ) { // if matches a stored Default, dont store Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , new Bean ( newValue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores a Collection of beans . The beans are stored using simple bean properties . The collection of beans must all be of the same class . [CODESPLIT] public void putBeanCollection ( String key , Collection newValue ) { // if matches a stored Default, dont store Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , new Bean . Collection ( newValue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores an object using XMLEncoder / XMLDecoder . Use this for arbitrary objects . If the exact key and value are already in the storedDefaults ( using equals () to test for equality ) then it is not stored . [CODESPLIT] public void putBeanObject ( String key , Object newValue ) { // if matches a stored Default, dont store Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an arrayList . This returns a copy of the stored list . [CODESPLIT] public List getList ( String key , List def ) { try { Object bean = getBean ( key , def ) ; return ( List ) bean ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements <tt > AbstractPreferences< / tt > <tt > childrenNamesSpi () < / tt > method . Find all children nodes of this node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected String [ ] childrenNamesSpi ( ) { HashSet allKids = new HashSet ( children . keySet ( ) ) ; PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKids . addAll ( sd . childrenNamesSpi ( absolutePath ( ) ) ) ; ArrayList list = new ArrayList ( allKids ) ; Collections . sort ( list ) ; String result [ ] = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) result [ i ] = list . get ( i ) . toString ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Find all children nodes of named node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected Collection childrenNamesSpi ( String nodePath ) { HashSet allKids = new HashSet ( ) ; try { if ( nodeExists ( nodePath ) ) { PreferencesExt node = ( PreferencesExt ) node ( nodePath ) ; allKids . addAll ( node . children . keySet ( ) ) ; } } catch ( java . util . prefs . BackingStoreException e ) { } PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKids . addAll ( sd . childrenNamesSpi ( nodePath ) ) ; return allKids ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Find all key names of this node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected String [ ] keysSpi ( ) throws BackingStoreException { HashSet allKeys = new HashSet ( keyValues . keySet ( ) ) ; //show( \"allKeys1 \", allKeys); PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKeys . addAll ( sd . keysSpi ( absolutePath ( ) ) ) ; //show( \"allKeys2 \", allKeys); ArrayList list = new ArrayList ( allKeys ) ; Collections . sort ( list ) ; //show( \"allKeys3 \", list); String result [ ] = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) result [ i ] = list . get ( i ) . toString ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Find all keys of named node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected Collection keysSpi ( String nodePath ) { HashSet allKeys = new HashSet ( ) ; try { if ( nodeExists ( nodePath ) ) { PreferencesExt node = ( PreferencesExt ) node ( nodePath ) ; //show( \"subKeys1 \"+nodePath, node.keyValues.keySet()); allKeys . addAll ( node . keyValues . keySet ( ) ) ; } } catch ( java . util . prefs . BackingStoreException e ) { } PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) { allKeys . addAll ( sd . keysSpi ( nodePath ) ) ; //show( \"subKeys2 \", allKeys); } return allKeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the named child of this preference node creating it if it does not already exist . It is guaranteed that name is non - null non - empty does not contain the slash character ( / ) and is no longer than Preferences . MAX_NAME_LENGTH characters . Also it is guaranteed that this node has not been removed . ( The implementor needn t check for any of these things . ) [CODESPLIT] protected AbstractPreferences childSpi ( String name ) { PreferencesExt child ; if ( null != ( child = ( PreferencesExt ) children . get ( name ) ) ) return child ; child = new PreferencesExt ( this , name ) ; children . put ( name , child ) ; child . newNode = true ; return child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets the value with this keyName if not found look in storedDefaults . [CODESPLIT] protected String getSpi ( String keyName ) { Object o = _getObject ( keyName ) ; return ( o == null ) ? null : o . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Stores the value with this key if not already in storedDefaults . [CODESPLIT] protected void putSpi ( String key , String newValue ) { // if matches a stored Default, dont store String oldValue = getSpi ( key ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * removes node no effect on storedDefaults [CODESPLIT] protected void removeNodeSpi ( ) throws BackingStoreException { //System.out.println(\" removeNodeSpi :\"+name()); if ( parent != null ) { if ( null == parent . children . remove ( name ( ) ) ) System . out . println ( \"ERROR PreferencesExt.removeNodeSpi :\" + name ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assume key non - null locked node [CODESPLIT] private Object _getObject ( String keyName ) { Object result = null ; try { result = keyValues . get ( keyName ) ; if ( result == null ) { // if failed, check the stored Defaults PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) result = sd . getObjectFromNode ( absolutePath ( ) , keyName ) ; } } catch ( Exception e ) { // Ignoring exception causes default to be returned } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "isolate dependencies here - in case we have a minimal I / O mode where not all fields are available [CODESPLIT] public float [ ] readData ( RandomAccessFile raf ) throws IOException { Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drss . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drss . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drss . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( gds . isThin ( ) ) data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , GribData . getInterpolationMethod ( ) ) ; lastRecordRead = this ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging - do not use [CODESPLIT] @ Nullable public int [ ] readRawData ( RandomAccessFile raf ) throws IOException { Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drss . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drss . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drss . getDrs ( raf ) ; return reader . getRawData ( raf , bms , gdrs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data array [CODESPLIT] public float [ ] readData ( RandomAccessFile raf , long drsPos ) throws IOException { raf . seek ( drsPos ) ; Grib2SectionDataRepresentation drs = new Grib2SectionDataRepresentation ( raf ) ; Grib2SectionBitMap bms = new Grib2SectionBitMap ( raf ) ; Grib2SectionData dataSection = new Grib2SectionData ( raf ) ; Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drs . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drs . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drs . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( gds . isThin ( ) ) data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , GribData . getInterpolationMethod ( ) ) ; lastRecordRead = this ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data array : use when you want to be independent of the GribRecord [CODESPLIT] public static float [ ] readData ( RandomAccessFile raf , long drsPos , long bmsPos , int gdsNumberPoints , int scanMode , int nx , int ny , int [ ] nptsInLine ) throws IOException { raf . seek ( drsPos ) ; Grib2SectionDataRepresentation drs = new Grib2SectionDataRepresentation ( raf ) ; Grib2SectionBitMap bms = new Grib2SectionBitMap ( raf ) ; Grib2SectionData dataSection = new Grib2SectionData ( raf ) ; if ( bmsPos > 0 ) bms = Grib2SectionBitMap . factory ( raf , bmsPos ) ; Grib2DataReader reader = new Grib2DataReader ( drs . getDataTemplate ( ) , gdsNumberPoints , drs . getDataPoints ( ) , scanMode , nx , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drs . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( nptsInLine != null ) data = QuasiRegular . convertQuasiGrid ( data , nptsInLine , nx , ny , GribData . getInterpolationMethod ( ) ) ; if ( getlastRecordRead ) lastRecordRead = Grib2RecordScanner . findRecordByDrspos ( raf , drsPos ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print data from a DSP - optionally constrained [CODESPLIT] public DSPPrinter print ( ) throws DapException { DapDataset dmr = this . dsp . getDMR ( ) ; if ( this . ce == null ) this . ce = CEConstraint . getUniversal ( dmr ) ; this . printer . setIndent ( 0 ) ; List < DapVariable > topvars = dmr . getTopVariables ( ) ; for ( int i = 0 ; i < topvars . size ( ) ; i ++ ) { DapVariable top = topvars . get ( i ) ; List < Slice > slices = this . ce . getConstrainedSlices ( top ) ; if ( this . ce . references ( top ) ) { DataCursor data = dsp . getVariableData ( top ) ; printVariable ( data , slices ) ; } } printer . eol ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print an arbitrary DataVariable using a constraint . <p > Handling newlines is a bit tricky so the rule is that the last newline is elided and left for the caller to print . Exceptions : ? [CODESPLIT] protected void printVariable ( DataCursor data , List < Slice > slices ) throws DapException { DapVariable dapv = ( DapVariable ) data . getTemplate ( ) ; if ( data . isScalar ( ) ) { assert slices == Slice . SCALARSLICES ; printScalar ( data ) ; } else { // not scalar printArray ( data , slices ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a single structure or sequence or record instance [CODESPLIT] protected void printCompoundInstance ( DataCursor datav ) throws DapException { //Index index = datav.getIndex(); DapStructure dstruct = ( DapStructure ) ( ( DapVariable ) datav . getTemplate ( ) ) . getBaseType ( ) ; switch ( datav . getScheme ( ) ) { case STRUCTURE : case RECORD : List < DapVariable > dfields = dstruct . getFields ( ) ; for ( int f = 0 ; f < dfields . size ( ) ; f ++ ) { DapVariable field = dfields . get ( f ) ; List < Slice > fieldslices = this . ce . getConstrainedSlices ( field ) ; DataCursor fdata = datav . readField ( f ) ; printVariable ( fdata , fieldslices ) ; } break ; case SEQUENCE : DapSequence dseq = ( DapSequence ) dstruct ; long count = datav . getRecordCount ( ) ; for ( long r = 0 ; r < count ; r ++ ) { DataCursor dr = datav . readRecord ( r ) ; printer . marginPrint ( \"[\" ) ; printer . eol ( ) ; printer . indent ( ) ; printCompoundInstance ( dr ) ; printer . outdent ( ) ; printer . marginPrint ( \"]\" ) ; } break ; default : throw new DapException ( \"Unexpected data cursor scheme:\" + datav . getScheme ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy constructor - avoid clone !! [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { // constructor takes sweep_angle_axis, so need to translate between // scan geometry and sweep_angle_axis first // GOES: x // GEOS: y String sweepAxisAngle = GEOSTransform . scanGeomToSweepAngleAxis ( navigation . scan_geom ) ; return new Geostationary ( navigation . sub_lon_degrees , sweepAxisAngle , geoCoordinateScaleFactor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an NcML element to a string . [CODESPLIT] public String writeToString ( Element elem ) { try ( StringWriter writer = new StringWriter ( ) ) { writeToWriter ( elem , writer ) ; return writer . toString ( ) ; } catch ( IOException e ) { throw new AssertionError ( \"CAN'T HAPPEN: StringWriter.close() is a no-op.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an NcML element to an output file . [CODESPLIT] public void writeToFile ( Element elem , File outFile ) throws IOException { try ( OutputStream outStream = new BufferedOutputStream ( new FileOutputStream ( outFile , false ) ) ) { writeToStream ( elem , outStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an NcML element to an output stream . [CODESPLIT] public void writeToStream ( Element elem , OutputStream outStream ) throws IOException { try ( Writer writer = new BufferedWriter ( new OutputStreamWriter ( new BufferedOutputStream ( outStream ) , xmlFormat . getEncoding ( ) ) ) ) { writeToWriter ( elem , writer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an NcML element to a Writer . [CODESPLIT] public void writeToWriter ( Element elem , Writer writer ) throws IOException { xmlOutputter . setFormat ( xmlFormat ) ; elem . detach ( ) ; // In case this element had previously been added to a Document.\r xmlOutputter . output ( new Document ( elem ) , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////// Element creation //////////////////////////////////////// [CODESPLIT] public Element makeExplicitNetcdfElement ( NetcdfFile ncFile , String location ) { Element netcdfElem = makeNetcdfElement ( ncFile , location ) ; netcdfElem . addContent ( 0 , new Element ( \"explicit\" , namespace ) ) ; return netcdfElem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "enum Typedef [CODESPLIT] public Element makeEnumTypedefElement ( EnumTypedef etd ) { Element typeElem = new Element ( \"enumTypedef\" , namespace ) ; typeElem . setAttribute ( \"name\" , etd . getShortName ( ) ) ; typeElem . setAttribute ( \"type\" , etd . getBaseType ( ) . toString ( ) ) ; // Use a TreeMap so that the key-value pairs are emitted in a consistent order.\r TreeMap < Integer , String > map = new TreeMap <> ( etd . getMap ( ) ) ; for ( Map . Entry < Integer , String > entry : map . entrySet ( ) ) { typeElem . addContent ( new Element ( \"enum\" , namespace ) . setAttribute ( \"key\" , Integer . toString ( entry . getKey ( ) ) ) . addContent ( entry . getValue ( ) ) ) ; } return typeElem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only for shared dimensions . [CODESPLIT] public Element makeDimensionElement ( Dimension dim ) throws IllegalArgumentException { if ( ! dim . isShared ( ) ) { throw new IllegalArgumentException ( \"Cannot create private dimension: \" + \"in NcML, <dimension> elements are always shared.\" ) ; } Element dimElem = new Element ( \"dimension\" , namespace ) ; dimElem . setAttribute ( \"name\" , dim . getShortName ( ) ) ; dimElem . setAttribute ( \"length\" , Integer . toString ( dim . getLength ( ) ) ) ; if ( dim . isUnlimited ( ) ) dimElem . setAttribute ( \"isUnlimited\" , \"true\" ) ; return dimElem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @code <values > } element from the variable s data . [CODESPLIT] public Element makeValuesElement ( Variable variable , boolean allowRegular ) throws IOException { Element elem = new Element ( \"values\" , namespace ) ; StringBuilder buff = new StringBuilder ( ) ; Array a = variable . read ( ) ; if ( variable . getDataType ( ) == DataType . CHAR ) { char [ ] data = ( char [ ] ) a . getStorage ( ) ; elem . setText ( new String ( data ) ) ; } else if ( variable . getDataType ( ) == DataType . STRING ) { elem . setAttribute ( \"separator\" , \"|\" ) ; int count = 0 ; for ( IndexIterator iter = a . getIndexIterator ( ) ; iter . hasNext ( ) ; ) { if ( count ++ > 0 ) { buff . append ( \"|\" ) ; } buff . append ( iter . getObjectNext ( ) ) ; } elem . setText ( buff . toString ( ) ) ; } else { //check to see if regular\r if ( allowRegular && ( a . getRank ( ) == 1 ) && ( a . getSize ( ) > 2 ) ) { Index ima = a . getIndex ( ) ; double start = a . getDouble ( ima . set ( 0 ) ) ; double incr = a . getDouble ( ima . set ( 1 ) ) - start ; boolean isRegular = true ; for ( int i = 2 ; i < a . getSize ( ) ; i ++ ) { double v1 = a . getDouble ( ima . set ( i ) ) ; double v0 = a . getDouble ( ima . set ( i - 1 ) ) ; if ( ! ucar . nc2 . util . Misc . nearlyEquals ( v1 - v0 , incr ) ) isRegular = false ; } if ( isRegular ) { elem . setAttribute ( \"start\" , Double . toString ( start ) ) ; elem . setAttribute ( \"increment\" , Double . toString ( incr ) ) ; elem . setAttribute ( \"npts\" , Long . toString ( variable . getSize ( ) ) ) ; return elem ; } } // not regular\r boolean isRealType = ( variable . getDataType ( ) == DataType . DOUBLE ) || ( variable . getDataType ( ) == DataType . FLOAT ) ; IndexIterator iter = a . getIndexIterator ( ) ; buff . append ( isRealType ? iter . getDoubleNext ( ) : iter . getIntNext ( ) ) ; while ( iter . hasNext ( ) ) { buff . append ( \" \" ) ; buff . append ( isRealType ? iter . getDoubleNext ( ) : iter . getIntNext ( ) ) ; } elem . setText ( buff . toString ( ) ) ; } // not string\r return elem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : MeasurementTVP / wml2 : value [CODESPLIT] public static MeasureType initValue ( MeasureType value , PointFeature pointFeat , VariableSimpleIF dataVar ) throws IOException { // TEXT StructureMembers . Member firstDataMember = pointFeat . getDataAll ( ) . findMember ( dataVar . getShortName ( ) ) ; assert firstDataMember != null : String . format ( \"%s appeared in the list of data variables but not in the StructureData.\" , dataVar . getShortName ( ) ) ; Array dataArray = pointFeat . getDataAll ( ) . getArray ( firstDataMember ) ; assert dataArray . getSize ( ) == 1 : String . format ( \"Expected array to be scalar, but its shape was %s.\" , Arrays . toString ( dataArray . getShape ( ) ) ) ; double dataVal = dataArray . getDouble ( 0 ) ; value . setDoubleValue ( dataVal ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the coordinate transform [CODESPLIT] public ProjectionCT makeCoordinateTransform ( AttributeContainer ctv , String units ) { int [ ] area = getIntArray ( ctv , McIDASAreaProjection . ATTR_AREADIR ) ; int [ ] nav = getIntArray ( ctv , McIDASAreaProjection . ATTR_NAVBLOCK ) ; int [ ] aux = null ; if ( ctv . findAttributeIgnoreCase ( McIDASAreaProjection . ATTR_AUXBLOCK ) != null ) { aux = getIntArray ( ctv , McIDASAreaProjection . ATTR_AUXBLOCK ) ; } // not clear if its ok if aux is null, coverity is complaining\r McIDASAreaProjection proj = new McIDASAreaProjection ( area , nav , aux ) ; return new ProjectionCT ( ctv . getName ( ) , \"FGDC\" , proj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the int array from the variable attribute [CODESPLIT] private int [ ] getIntArray ( AttributeContainer ctv , String attName ) { Attribute att = ctv . findAttribute ( attName ) ; if ( att == null ) { throw new IllegalArgumentException ( \"McIDASArea coordTransformVariable \" + ctv . getName ( ) + \" must have \" + attName + \" attribute\" ) ; } Array arr = att . getValues ( ) ; return ( int [ ] ) arr . get1DJavaArray ( int . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Vert [CODESPLIT] @ Override public VertCoordType getVertUnit ( int code ) { switch ( code ) { case 235 : return new VertCoordType ( code , \"0.1 C\" , null , true ) ; case 237 : return new VertCoordType ( code , \"m\" , null , true ) ; case 238 : return new VertCoordType ( code , \"m\" , null , true ) ; case 241 : return new VertCoordType ( code , \"count\" , null , true ) ; // eg see NCEP World Watch datasets\r default : return super . getVertUnit ( code ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "shared by all instances [CODESPLIT] @ Override @ Nullable public String getStatisticName ( int id ) { if ( id < 192 ) return super . getStatisticName ( id ) ; if ( statName == null ) statName = initTable410 ( ) ; if ( statName == null ) return null ; return statName . get ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "shared by all instances [CODESPLIT] @ Override @ Nullable public String getGeneratingProcessName ( int genProcess ) { if ( genProcessMap == null ) genProcessMap = NcepTables . getNcepGenProcess ( ) ; if ( genProcessMap == null ) return null ; return genProcessMap . get ( genProcess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see http : // www . nco . ncep . noaa . gov / pmb / docs / grib2 / grib2_doc . shtml [CODESPLIT] private Map < String , String > initCodes ( ) { codeMap . put ( \"3.1.204\" , \"Curvilinear_Orthogonal\" ) ; codeMap . put ( \"4.3.192\" , \"Forecast Confidence Indicator\" ) ; codeMap . put ( \"4.3.193\" , \"Bias Corrected Ensemble Forecast\" ) ; codeMap . put ( \"4.5.200\" , \"Entire atmosphere layer\" ) ; codeMap . put ( \"4.5.201\" , \"Entire ocean layer\" ) ; codeMap . put ( \"4.5.204\" , \"Highest tropospheric freezing level\" ) ; codeMap . put ( \"4.5.206\" , \"Grid scale cloud bottom level\" ) ; codeMap . put ( \"4.5.207\" , \"Grid scale cloud top level\" ) ; codeMap . put ( \"4.5.209\" , \"Boundary layer cloud bottom level\" ) ; codeMap . put ( \"4.5.210\" , \"Boundary layer cloud top level\" ) ; codeMap . put ( \"4.5.211\" , \"Boundary layer cloud layer\" ) ; codeMap . put ( \"4.5.212\" , \"Low cloud bottom level\" ) ; codeMap . put ( \"4.5.213\" , \"Low cloud top level\" ) ; codeMap . put ( \"4.5.214\" , \"Low cloud layer\" ) ; codeMap . put ( \"4.5.215\" , \"Cloud ceiling\" ) ; codeMap . put ( \"4.5.220\" , \"Planetary Boundary Layer\" ) ; codeMap . put ( \"4.5.221\" , \"Layer Between Two Hybrid Levels\" ) ; codeMap . put ( \"4.5.222\" , \"Middle cloud bottom level\" ) ; codeMap . put ( \"4.5.223\" , \"Middle cloud top level\" ) ; codeMap . put ( \"4.5.224\" , \"Middle cloud layer\" ) ; codeMap . put ( \"4.5.232\" , \"High cloud bottom level\" ) ; codeMap . put ( \"4.5.233\" , \"High cloud top level\" ) ; codeMap . put ( \"4.5.234\" , \"High cloud layer\" ) ; codeMap . put ( \"4.5.235\" , \"Ocean isotherm level\" ) ; codeMap . put ( \"4.5.236\" , \"Layer between two depths below ocean surface\" ) ; codeMap . put ( \"4.5.237\" , \"Bottom of ocean mixed layer\" ) ; codeMap . put ( \"4.5.238\" , \"Bottom of ocean isothermal layer\" ) ; codeMap . put ( \"4.5.239\" , \"Layer Ocean Surface and 26C Ocean Isothermal Level\" ) ; codeMap . put ( \"4.5.240\" , \"Ocean Mixed Layer\" ) ; codeMap . put ( \"4.5.241\" , \"Ordered Sequence of Data\" ) ; codeMap . put ( \"4.5.242\" , \"Convective cloud bottom level\" ) ; codeMap . put ( \"4.5.243\" , \"Convective cloud top level\" ) ; codeMap . put ( \"4.5.244\" , \"Convective cloud layer\" ) ; codeMap . put ( \"4.5.245\" , \"Lowest level of the wet bulb zero\" ) ; codeMap . put ( \"4.5.246\" , \"Maximum equivalent potential temperature level\" ) ; codeMap . put ( \"4.5.247\" , \"Equilibrium level\" ) ; codeMap . put ( \"4.5.248\" , \"Shallow convective cloud bottom level\" ) ; codeMap . put ( \"4.5.249\" , \"Shallow convective cloud top level\" ) ; codeMap . put ( \"4.5.251\" , \"Deep convective cloud bottom level\" ) ; codeMap . put ( \"4.5.252\" , \"Deep convective cloud top level\" ) ; codeMap . put ( \"4.5.253\" , \"Lowest bottom level of supercooled liquid water layer\" ) ; codeMap . put ( \"4.5.254\" , \"Highest top level of supercooled liquid water layer\" ) ; codeMap . put ( \"4.6.192\" , \"Perturbed Ensemble Member\" ) ; codeMap . put ( \"4.7.192\" , \"Unweighted Mode of All Members\" ) ; codeMap . put ( \"4.7.193\" , \"Percentile value (10%) of All Members\" ) ; codeMap . put ( \"4.7.194\" , \"Percentile value (50%) of All Members\" ) ; codeMap . put ( \"4.7.195\" , \"Percentile value (90%) of All Members\" ) ; codeMap . put ( \"4.10.192\" , \"Climatological Mean Value\" ) ; codeMap . put ( \"4.10.193\" , \"Average of N forecasts\" ) ; codeMap . put ( \"4.10.194\" , \"Average of N uninitialized analyses\" ) ; codeMap . put ( \"4.10.195\" , \"Average of forecast accumulations\" ) ; codeMap . put ( \"4.10.196\" , \"Average of successive forecast accumulations\" ) ; codeMap . put ( \"4.10.197\" , \"Average of forecast averages\" ) ; codeMap . put ( \"4.10.198\" , \"Average of successive forecast averages\" ) ; codeMap . put ( \"4.10.199\" , \"Climatological Average of N analyses, each a year apart\" ) ; codeMap . put ( \"4.10.200\" , \"Climatological Average of N forecasts, each a year apart\" ) ; codeMap . put ( \"4.10.201\" , \"Climatological Root Mean Square difference between N forecasts and their verifying analyses, each a year apart\" ) ; codeMap . put ( \"4.10.202\" , \"Climatological Standard Deviation of N forecasts from the mean of the same N forecasts, for forecasts one year apart\" ) ; codeMap . put ( \"4.10.203\" , \"Climatological Standard Deviation of N analyses from the mean of the same N analyses, for analyses one year apart\" ) ; codeMap . put ( \"4.10.204\" , \"Average of forecast accumulations\" ) ; codeMap . put ( \"4.10.205\" , \"Average of forecast averages\" ) ; codeMap . put ( \"4.10.206\" , \"Average of forecast accumulations\" ) ; codeMap . put ( \"4.10.207\" , \"Average of forecast averages\" ) ; return codeMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Need a few test cases : 1 ) Anne s TDR case - catalog a collection of TDS served data . 2 ) Catalog a collection of local data files . 3 ) [CODESPLIT] public static void main1 ( String [ ] args ) { // Test case 2: local data files. String collectionPath = \"C:/Ethan/data/mlode\" ; String startPath = \"grid/NCEP\" ; String catWriteDirPath = \"C:/Ethan/data/tmpTest\" ; if ( args . length == 3 ) { collectionPath = args [ 0 ] ; startPath = args [ 1 ] ; catWriteDirPath = args [ 2 ] ; } File catWriteDir = new File ( catWriteDirPath ) ; File collectionFile = new File ( collectionPath ) ; CrawlableDataset collectionCrDs = new CrawlableDatasetFile ( collectionFile ) ; InvService service = new InvService ( \"myServer\" , \"File\" , collectionCrDs . getPath ( ) + \"/\" , null , null ) ; CrawlableDatasetFilter filter = null ; CrawlableDataset topCatCrDs = collectionCrDs . getDescendant ( startPath ) ; CatGenAndWrite cgaw = new CatGenAndWrite ( \"DATA\" , \"My data\" , \"\" , service , collectionCrDs , topCatCrDs , filter , null , catWriteDir ) ; try { cgaw . genCatAndSubCats ( topCatCrDs ) ; } catch ( IOException e ) { log . error ( \"I/O error generating and writing catalogs at and under \\\"\" + topCatCrDs . getPath ( ) + \"\\\": \" + e . getMessage ( ) ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for constructing a base unit . [CODESPLIT] private static BaseUnit bu ( final String name , final String symbol , final BaseQuantity quantity ) throws NameException , UnitExistsException { return BaseUnit . getOrCreate ( UnitName . newUnitName ( name , null , symbol ) , quantity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for constructing a derived unit . [CODESPLIT] private static Unit du ( final String name , final String symbol , final Unit definition ) throws NameException { return definition . clone ( UnitName . newUnitName ( name , null , symbol ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the base unit database of the SI . [CODESPLIT] private static UnitDBImpl baseUnitDB ( ) throws NameException , UnitExistsException , NoSuchUnitException { final UnitDBImpl db = new UnitDBImpl ( 9 , 9 ) ; db . addUnit ( AMPERE ) ; db . addUnit ( CANDELA ) ; db . addUnit ( KELVIN ) ; db . addUnit ( KILOGRAM ) ; db . addUnit ( METER ) ; db . addUnit ( MOLE ) ; db . addUnit ( SECOND ) ; db . addUnit ( RADIAN ) ; db . addUnit ( STERADIAN ) ; db . addAlias ( \"metre\" , \"meter\" ) ; return db ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the derived unit database of the SI . [CODESPLIT] private static UnitDBImpl derivedUnitDB ( ) throws NameException , UnitExistsException , NoSuchUnitException { final UnitDBImpl db = new UnitDBImpl ( 42 , 43 ) ; db . addUnit ( HERTZ ) ; db . addUnit ( NEWTON ) ; db . addUnit ( PASCAL ) ; db . addUnit ( JOULE ) ; db . addUnit ( WATT ) ; db . addUnit ( COULOMB ) ; db . addUnit ( VOLT ) ; db . addUnit ( FARAD ) ; db . addUnit ( OHM ) ; db . addUnit ( SIEMENS ) ; db . addUnit ( WEBER ) ; db . addUnit ( TESLA ) ; db . addUnit ( HENRY ) ; db . addUnit ( DEGREE_CELSIUS ) ; db . addUnit ( LUMEN ) ; db . addUnit ( LUX ) ; db . addUnit ( BECQUEREL ) ; db . addUnit ( GRAY ) ; db . addUnit ( SIEVERT ) ; db . addUnit ( MINUTE ) ; db . addUnit ( HOUR ) ; db . addUnit ( DAY ) ; db . addUnit ( ARC_DEGREE ) ; db . addUnit ( ARC_MINUTE ) ; db . addUnit ( ARC_SECOND ) ; db . addUnit ( LITER ) ; db . addUnit ( METRIC_TON ) ; db . addUnit ( NAUTICAL_MILE ) ; db . addUnit ( KNOT ) ; db . addUnit ( ANGSTROM ) ; db . addUnit ( ARE ) ; db . addUnit ( HECTARE ) ; db . addUnit ( BARN ) ; db . addUnit ( BAR ) ; db . addUnit ( GAL ) ; db . addUnit ( CURIE ) ; db . addUnit ( ROENTGEN ) ; db . addUnit ( RAD ) ; db . addUnit ( REM ) ; db . addAlias ( \"litre\" , \"liter\" , \"l\" ) ; db . addAlias ( \"tonne\" , \"metric ton\" ) ; db . addSymbol ( \"tne\" , \"tonne\" ) ; return db ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance of the SI system of units . [CODESPLIT] public static synchronized SI instance ( ) throws UnitSystemException { if ( si == null ) { try { si = new SI ( ) ; } catch ( final UnitException e ) { throw new UnitSystemException ( \"Couldn't initialize class SI\" , e ) ; } } return si ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] protected void update ( CollectionUpdateType force ) throws IOException { // this may be called from a background thread, or from checkState() request thread logger . debug ( \"update {} force={}\" , name , force ) ; boolean changed ; MFileCollectionManager dcm ; switch ( force ) { case always : case test : dcm = ( MFileCollectionManager ) getDatasetCollectionManager ( ) ; changed = dcm . scan ( false ) ; if ( changed ) super . update ( force ) ; break ; case never : return ; default : super . update ( force ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called by DataRootHandler . makeDynamicCatalog () when the catref is requested [CODESPLIT] @ Override public CatalogBuilder makeCatalog ( String match , String orgPath , URI catURI ) throws IOException { logger . debug ( \"FMRC make catalog for \" + match + \" \" + catURI ) ; State localState = checkState ( ) ; try { if ( ( match == null ) || ( match . length ( ) == 0 ) ) { return makeCatalogTop ( catURI , localState ) ; } else if ( match . equals ( RUNS ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Runs ) ) return makeCatalogRuns ( catURI , localState ) ; else if ( match . equals ( OFFSET ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantOffsets ) ) return makeCatalogOffsets ( catURI , localState ) ; else if ( match . equals ( FORECAST ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantForecasts ) ) return makeCatalogForecasts ( catURI , localState ) ; else if ( match . startsWith ( FILES ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Files ) ) { return makeCatalogFiles ( catURI , localState , datasetCollection . getFilenames ( ) , true ) ; } } catch ( Exception e ) { logger . error ( \"Error making catalog for \" + configPath , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override protected DatasetBuilder makeDatasetTop ( URI catURI , State localState ) { DatasetBuilder top = new DatasetBuilder ( null ) ; top . transferInheritedMetadata ( parent ) ; // make all inherited metadata local top . setName ( name ) ; top . addServiceToCatalog ( virtualService ) ; ThreddsMetadata tmi = top . getInheritableMetadata ( ) ; // LOOK allow to change ?? tmi . set ( Dataset . FeatureType , FeatureType . GRID . toString ( ) ) ; // override GRIB tmi . set ( Dataset . ServiceName , virtualService . getName ( ) ) ; if ( localState . coverage != null ) tmi . set ( Dataset . GeospatialCoverage , localState . coverage ) ; if ( localState . dateRange != null ) tmi . set ( Dataset . TimeCoverage , localState . dateRange ) ; if ( localState . vars != null ) tmi . set ( Dataset . VariableGroups , localState . vars ) ; if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . TwoD ) ) { DatasetBuilder twoD = new DatasetBuilder ( top ) ; twoD . setName ( \"Forecast Model Run Collection (2D time coordinates)\" ) ; String myname = name + \"_\" + FMRC ; myname = StringUtil2 . replace ( myname , ' ' , \"_\" ) ; twoD . put ( Dataset . UrlPath , this . configPath + \"/\" + myname ) ; twoD . put ( Dataset . Id , this . configPath + \"/\" + myname ) ; twoD . addToList ( Dataset . Documentation , new Documentation ( null , null , null , \"summary\" , \"Forecast Model Run Collection (2D time coordinates).\" ) ) ; top . addDataset ( twoD ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Best ) ) { DatasetBuilder best = new DatasetBuilder ( top ) ; best . setName ( \"Best Time Series\" ) ; String myname = name + \"_\" + BEST ; myname = StringUtil2 . replace ( myname , ' ' , \"_\" ) ; best . put ( Dataset . UrlPath , this . configPath + \"/\" + myname ) ; best . put ( Dataset . Id , this . configPath + \"/\" + myname ) ; best . addToList ( Dataset . Documentation , new Documentation ( null , null , null , \"summary\" , \"Best time series, taking the data from the most recent run available.\" ) ) ; top . addDataset ( best ) ; } if ( config . fmrcConfig . getBestDatasets ( ) != null ) { for ( FeatureCollectionConfig . BestDataset bd : config . fmrcConfig . getBestDatasets ( ) ) { DatasetBuilder ds = new DatasetBuilder ( top ) ; ds . setName ( bd . name ) ; String myname = name + \"_\" + bd . name ; myname = StringUtil2 . replace ( myname , ' ' , \"_\" ) ; ds . put ( Dataset . UrlPath , this . configPath + \"/\" + myname ) ; ds . put ( Dataset . Id , this . configPath + \"/\" + myname ) ; ds . addToList ( Dataset . Documentation , new Documentation ( null , null , null , \"summary\" , \"Best time series, excluding offset hours less than \" + bd . greaterThan ) ) ; top . addDataset ( ds ) ; } } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Runs ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( RUN_TITLE ) ; ds . setHref ( getCatalogHref ( RUNS ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantForecasts ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( FORECAST_TITLE ) ; ds . setHref ( getCatalogHref ( FORECAST ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantOffsets ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( OFFSET_TITLE ) ; ds . setHref ( getCatalogHref ( OFFSET ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Files ) && ( topDirectory != null ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( FILES ) ; ds . setHref ( getCatalogHref ( FILES ) ) ; top . addDataset ( ds ) ; } return top ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a coordinate interval find what grid element matches it . [CODESPLIT] int findCoordElement ( double [ ] target , boolean bounded ) { switch ( axis . getSpacing ( ) ) { case regularInterval : // can use midpoint return findCoordElementRegular ( ( target [ 0 ] + target [ 1 ] ) / 2 , bounded ) ; case contiguousInterval : // can use midpoint return findCoordElementContiguous ( ( target [ 0 ] + target [ 1 ] ) / 2 , bounded ) ; case discontiguousInterval : // cant use midpoint return findCoordElementDiscontiguousInterval ( target , bounded ) ; } throw new IllegalStateException ( \"unknown spacing\" + axis . getSpacing ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "same contract as findCoordElement () [CODESPLIT] private int findCoordElementRegular ( double coordValue , boolean bounded ) { int n = axis . getNcoords ( ) ; if ( n == 1 && bounded ) return 0 ; double distance = coordValue - axis . getCoordEdge1 ( 0 ) ; double exactNumSteps = distance / axis . getResolution ( ) ; //int index = (int) Math.round(exactNumSteps); // ties round to +Inf int index = ( int ) exactNumSteps ; // truncate down if ( bounded && index < 0 ) return 0 ; if ( bounded && index >= n ) return n - 1 ; // check that found point is within interval if ( index >= 0 && index < n ) { double lower = axis . getCoordEdge1 ( index ) ; double upper = axis . getCoordEdge2 ( index ) ; if ( axis . isAscending ( ) ) { assert lower <= coordValue : lower + \" should be le \" + coordValue ; assert upper >= coordValue : upper + \" should be ge \" + coordValue ; } else { assert lower >= coordValue : lower + \" should be ge \" + coordValue ; assert upper <= coordValue : upper + \" should be le \" + coordValue ; } } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a binary search to find the index of the element of the array whose value is contained in the contiguous intervals . irregularPoint // irregular spaced points ( values npts ) edges halfway between coords contiguousInterval // irregular contiguous spaced intervals ( values npts ) values are the edges and there are npts + 1 coord halfway between edges <p > same contract as findCoordElement () [CODESPLIT] private int findCoordElementContiguous ( double target , boolean bounded ) { int n = axis . getNcoords ( ) ; //double resolution = (values[n-1] - values[0]) / (n - 1); //int startGuess = (int) Math.round((target - values[0]) / resolution); int low = 0 ; int high = n - 1 ; if ( axis . isAscending ( ) ) { // Check that the point is within range if ( target < axis . getCoordEdge1 ( 0 ) ) return bounded ? 0 : - 1 ; else if ( target > axis . getCoordEdgeLast ( ) ) return bounded ? n - 1 : n ; // do a binary search to find the nearest index int mid ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; // binary search if ( contains ( target , mid , true ) ) return mid ; else if ( axis . getCoordEdge2 ( mid ) < target ) low = mid ; else high = mid ; } return contains ( target , low , true ) ? low : high ; } else { // descending // Check that the point is within range if ( target > axis . getCoordEdge1 ( 0 ) ) return bounded ? 0 : - 1 ; else if ( target < axis . getCoordEdgeLast ( ) ) return bounded ? n - 1 : n ; // do a binary search to find the nearest index int mid ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; // binary search if ( contains ( target , mid , false ) ) return mid ; else if ( axis . getCoordEdge2 ( mid ) < target ) high = mid ; else low = mid ; } return contains ( target , low , false ) ? low : high ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK not using bounded [CODESPLIT] private int findCoordElementDiscontiguousInterval ( double target , boolean bounded ) { int idx = findSingleHit ( target ) ; if ( idx >= 0 ) return idx ; if ( idx == - 1 ) return - 1 ; // no hits // multiple hits = choose closest to the midpoint return findClosest ( target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK not using bounded [CODESPLIT] private int findCoordElementDiscontiguousInterval ( double [ ] target , boolean bounded ) { for ( int i = 0 ; i < axis . getNcoords ( ) ; i ++ ) { double edge1 = axis . getCoordEdge1 ( i ) ; double edge2 = axis . getCoordEdge2 ( i ) ; if ( Misc . nearlyEquals ( edge1 , target [ 0 ] ) && Misc . nearlyEquals ( edge2 , target [ 1 ] ) ) return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return index if only one match if no matches return - 1 if > 1 match return - nhits [CODESPLIT] private int findSingleHit ( double target ) { int hits = 0 ; int idxFound = - 1 ; int n = axis . getNcoords ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( contains ( target , i ) ) { hits ++ ; idxFound = i ; } } if ( hits == 1 ) return idxFound ; if ( hits == 0 ) return - 1 ; return - hits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if its a tie use the larger one [CODESPLIT] private int findClosest ( double target ) { double minDiff = Double . MAX_VALUE ; double useValue = Double . MIN_VALUE ; int idxFound = - 1 ; for ( int i = 0 ; i < axis . getNcoords ( ) ; i ++ ) { double coord = axis . getCoordMidpoint ( i ) ; double diff = Math . abs ( coord - target ) ; if ( diff < minDiff || ( diff == minDiff && coord > useValue ) ) { minDiff = diff ; idxFound = i ; useValue = coord ; } } return idxFound ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////// [CODESPLIT] public Optional < CoverageCoordAxisBuilder > subset ( double minValue , double maxValue , int stride ) { return subsetValues ( minValue , maxValue , stride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look must handle discon interval different [CODESPLIT] private Optional < CoverageCoordAxisBuilder > subsetValues ( double minValue , double maxValue , int stride ) { if ( axis . getSpacing ( ) == CoverageCoordAxis . Spacing . discontiguousInterval ) return subsetValuesDiscontinuous ( minValue , maxValue , stride ) ; double lower = axis . isAscending ( ) ? Math . min ( minValue , maxValue ) : Math . max ( minValue , maxValue ) ; double upper = axis . isAscending ( ) ? Math . max ( minValue , maxValue ) : Math . min ( minValue , maxValue ) ; int minIndex = findCoordElement ( lower , false ) ; int maxIndex = findCoordElement ( upper , false ) ; if ( minIndex >= axis . getNcoords ( ) ) return Optional . empty ( String . format ( \"no points in subset: lower %f > end %f\" , lower , axis . getEndValue ( ) ) ) ; if ( maxIndex < 0 ) return Optional . empty ( String . format ( \"no points in subset: upper %f < start %f\" , upper , axis . getStartValue ( ) ) ) ; if ( minIndex < 0 ) minIndex = 0 ; if ( maxIndex >= axis . getNcoords ( ) ) maxIndex = axis . getNcoords ( ) - 1 ; int count = maxIndex - minIndex + 1 ; if ( count <= 0 ) throw new IllegalArgumentException ( \"no points in subset\" ) ; try { return Optional . of ( subsetByIndex ( new Range ( minIndex , maxIndex , stride ) ) ) ; } catch ( InvalidRangeException e ) { return Optional . empty ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Range must be contained in this range [CODESPLIT] @ Nonnull CoverageCoordAxisBuilder subsetByIndex ( Range range ) throws InvalidRangeException { int ncoords = range . length ( ) ; if ( range . last ( ) >= axis . getNcoords ( ) ) throw new InvalidRangeException ( \"range.last() >= axis.getNcoords()\" ) ; double resolution = 0.0 ; int count2 = 0 ; double [ ] values = axis . getValues ( ) ; // will be null for regular double [ ] subsetValues = null ; switch ( axis . getSpacing ( ) ) { case regularInterval : case regularPoint : resolution = range . stride ( ) * axis . getResolution ( ) ; break ; case irregularPoint : subsetValues = new double [ ncoords ] ; for ( int i : range ) subsetValues [ count2 ++ ] = values [ i ] ; break ; case contiguousInterval : subsetValues = new double [ ncoords + 1 ] ; // need npts+1 for ( int i : range ) subsetValues [ count2 ++ ] = values [ i ] ; subsetValues [ count2 ] = values [ range . last ( ) + 1 ] ; break ; case discontiguousInterval : subsetValues = new double [ 2 * ncoords ] ; // need 2*npts for ( int i : range ) { subsetValues [ count2 ++ ] = values [ 2 * i ] ; subsetValues [ count2 ++ ] = values [ 2 * i + 1 ] ; } break ; } // subset(int ncoords, double start, double end, double[] values) CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder ( axis ) ; builder . subset ( ncoords , axis . getCoordMidpoint ( range . first ( ) ) , axis . getCoordMidpoint ( range . last ( ) ) , resolution , subsetValues ) ; builder . setRange ( range ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * http : // stackoverflow . com / questions / 24660408 / how - can - i - get - intellij - debugger - to - allow - my - apps - shutdown - hooks - to - run?lq = 1 Unfortunately you can t use breakpoints in your shutdown hook body when you use Stop button : these breakpoints are silently ignored . [CODESPLIT] @ Override public void destroy ( ) { System . out . printf ( \"TdsInit.destroy() is called%n\" ) ; // prefs try { store . save ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; startupLog . error ( \"TdsInit: Prefs save failed\" , ioe ) ; } // background threads if ( cdmDiskCacheTimer != null ) cdmDiskCacheTimer . cancel ( ) ; FileCache . shutdown ( ) ; // this handles background threads for all instances of FileCache DiskCache2 . exit ( ) ; // this handles background threads for all instances of DiskCache2 thredds . inventory . bdb . MetadataManager . closeAll ( ) ; executor . shutdownNow ( ) ; /* try {\n      catalogWatcher.close();\n    } catch (IOException ioe) {\n      ioe.printStackTrace();\n      startupLog.error(\"catalogWatcher close failed\", ioe);\n    } */ // open file caches RandomAccessFile . shutdown ( ) ; NetcdfDataset . shutdown ( ) ; // memory caches GribCdmIndex . shutdown ( ) ; datasetManager . setDatasetTracker ( null ) ; // closes the existing tracker collectionUpdater . shutdown ( ) ; startupLog . info ( \"TdsInit shutdown\" ) ; MDC . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////// [CODESPLIT] void writeNetcdf ( NetcdfOutputChooser . Data data ) { if ( data . version == NetcdfFileWriter . Version . ncstream ) { writeNcstream ( data . outputFilename ) ; return ; } try { FileWriter2 writer = new FileWriter2 ( ds , data . outputFilename , data . version , Nc4ChunkingStrategy . factory ( data . chunkerType , data . deflate , data . shuffle ) ) ; NetcdfFile result = writer . write ( ) ; result . close ( ) ; JOptionPane . showMessageDialog ( this , \"File successfully written\" ) ; } catch ( Exception ioe ) { JOptionPane . showMessageDialog ( this , \"ERROR: \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public void showTreeViewWindow () { if ( treeWindow == null ) { datasetTree = new DatasetTreeView () ; treeWindow = new IndependentWindow ( TreeView datasetTree ) ; treeWindow . setIconImage ( thredds . ui . BAMutil . getImage ( netcdfUI )) ; treeWindow . setBounds ( ( Rectangle ) prefs . getBean ( treeWindow new Rectangle ( 150 100 400 700 ))) ; } [CODESPLIT] private void showDeclaration ( BeanTable from , boolean isNcml ) { Variable v = getCurrentVariable ( from ) ; if ( v == null ) return ; infoTA . clear ( ) ; if ( isNcml ) { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; ncmlWriter . setNamespace ( null ) ; ncmlWriter . getXmlFormat ( ) . setOmitDeclaration ( true ) ; Element varElement = ncmlWriter . makeVariableElement ( v , false ) ; infoTA . appendLine ( ncmlWriter . writeToString ( varElement ) ) ; } else { infoTA . appendLine ( v . toString ( ) ) ; } if ( Debug . isSet ( \"Xdeveloper\" ) ) { infoTA . appendLine ( \"\\n\" ) ; infoTA . appendLine ( \"FULL NAME = \" + v . getFullName ( ) ) ; infoTA . appendLine ( \"\\n\" ) ; infoTA . appendLine ( v . toStringDebug ( ) ) ; } infoTA . gotoTop ( ) ; infoWindow . setTitle ( \"Variable Info\" ) ; infoWindow . show ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void showMissingData ( BeanTable from ) { VariableBean vb = ( VariableBean ) from . getSelectedBean () ; if ( vb == null ) return ; Variable v = vb . vs ; if (( v ! = null ) && ( v . getDataType () == ucar . nc2 . DataType . STRUCTURE )) { showMissingStructureData ( ( Structure ) v ) ; } if ( !vb . vs . hasMissing () ) return ; [CODESPLIT] private void dataTable ( BeanTable from ) { VariableBean vb = ( VariableBean ) from . getSelectedBean ( ) ; if ( vb == null ) return ; Variable v = vb . vs ; if ( v instanceof Structure ) { try { dataTable . setStructure ( ( Structure ) v ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } dataWindow . setComponent ( dataTable ) ; } else { List < VariableBean > l = from . getSelectedBeans ( ) ; List < Variable > vl = new ArrayList <> ( ) ; for ( VariableBean vb1 : l ) { if ( vb1 == null ) return ; v = vb1 . vs ; if ( v != null ) { vl . add ( v ) ; } else return ; } variableTable . setDataset ( ds ) ; variableTable . setVariableList ( vl ) ; variableTable . createTable ( ) ; dataWindow . setComponent ( variableTable ) ; } Rectangle r = ( Rectangle ) prefs . getBean ( \"dataWindowBounds\" , new Rectangle ( 50 , 300 , 1000 , 1200 ) ) ; dataWindow . setBounds ( r ) ; dataWindow . show ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////// [CODESPLIT] private void doGribIndex ( Formatter f , MCollection dcm , boolean eachFile ) throws IOException { Counters counters = new Counters ( ) ; // must open collection again without gbx filtering try ( MCollection dcm2 = getCollectionUnfiltered ( spec , f ) ) { for ( MFile mfile : dcm2 . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; f . format ( \" %s%n\" , path ) ; doGribIndex ( f , mfile , counters , eachFile ) ; } } counters . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doCheckLocalParams ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"Check Grib-1 Parameter Tables for local entries%n\" ) ; int [ ] accum = new int [ 4 ] ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; f . format ( \"%n %s%n\" , path ) ; try { doCheckLocalParams ( mfile , f , accum ) ; } catch ( Throwable t ) { System . out . printf ( \"FAIL on %s%n\" , mfile . getPath ( ) ) ; t . printStackTrace ( ) ; } } f . format ( \"%nGrand total=%d local = %d missing = %d%n\" , accum [ 0 ] , accum [ 2 ] , accum [ 3 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look through the collection and find what GDS templates are used . [CODESPLIT] private void doCheckTables ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { Counters counters = new Counters ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; f . format ( \" %s%n\" , path ) ; if ( useIndex ) doCheckTablesWithIndex ( f , mfile , counters ) ; else doCheckTablesNoIndex ( f , mfile , counters ) ; } f . format ( \"Check Parameter Tables%n\" ) ; counters . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////// [CODESPLIT] private void doScanIssues ( Formatter f , MCollection dcm , boolean useIndex , boolean eachFile , boolean extraInfo ) throws IOException { Counters countersAll = new Counters ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { Counters countersOneFile = countersAll . makeSubCounters ( ) ; String path = mfile . getPath ( ) ; f . format ( \" %s%n\" , path ) ; if ( useIndex ) doScanIssuesWithIndex ( f , mfile , extraInfo , countersOneFile ) ; else doScanIssuesNoIndex ( f , mfile , extraInfo , countersOneFile ) ; if ( eachFile ) { countersOneFile . show ( f ) ; } countersAll . addTo ( countersOneFile ) ; } f . format ( \"ScanIssues - all files%n\" ) ; countersAll . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////// [CODESPLIT] private void doShowEncoding ( Formatter f , MCollection dcm ) throws IOException { Counters countersAll = new Counters ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \" %s%n\" , mfile . getPath ( ) ) ; // need dataRaf, so cant useIndex doShowEncodingNoIndex ( f , mfile , countersAll ) ; } countersAll . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look through the collection and find what GDS templates are used . [CODESPLIT] private void doUniqueGds ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"Show Unique GDS%n\" ) ; Map < Integer , GdsList > gdsSet = new HashMap <> ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \" %s%n\" , mfile . getPath ( ) ) ; doUniqueGds ( mfile , gdsSet , f ) ; } List < GdsList > sorted = new ArrayList <> ( gdsSet . values ( ) ) ; Collections . sort ( sorted ) ; for ( GdsList gdsl : sorted ) { f . format ( \"%nGDS %s template= %d %n\" , gdsl . gds . getNameShort ( ) , gdsl . gds . template ) ; for ( FileCount fc : gdsl . fileList ) { f . format ( \"  %5d %s %n\" , fc . countRecords , fc . f . getPath ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a FeatureDataset from a URL location string . Example URLS : <ul > <li > http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : file : c : / test / data / catalog / addeStationDataset . xml#AddeSurfaceData ( absolute file ) <li > thredds : resolve : resolveURL < / ul > [CODESPLIT] public DataFactory . Result openFeatureDataset ( String urlString , ucar . nc2 . util . CancelTask task ) throws IOException { DataFactory . Result result = new DataFactory . Result ( ) ; Dataset dataset = openCatalogFromLocation ( urlString , task , result ) ; if ( result . fatalError || dataset == null ) return result ; return openFeatureDataset ( null , dataset , task , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a FeatureDataset from an Dataset object deciding on which Access to use . [CODESPLIT] @ Nonnull public DataFactory . Result openFeatureDataset ( Dataset Dataset , ucar . nc2 . util . CancelTask task ) throws IOException { return openFeatureDataset ( null , Dataset , task , new Result ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a FeatureDataset from an Access object . [CODESPLIT] public DataFactory . Result openFeatureDataset ( Access access , ucar . nc2 . util . CancelTask task ) throws IOException { Dataset ds = access . getDataset ( ) ; DataFactory . Result result = new Result ( ) ; if ( ds . getFeatureType ( ) == null ) { result . errLog . format ( \"InvDatasert must specify a FeatureType%n\" ) ; result . fatalError = true ; return result ; } return openFeatureDataset ( ds . getFeatureType ( ) , access , task , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a NetcdfDataset from a URL location string . Example URLS : <ul > <li > http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : file : c : / dev / netcdf - java - 2 . 2 / test / data / catalog / addeStationDataset . xml#AddeSurfaceData ( absolute file ) <li > thredds : resolve : resolveURL < / ul > [CODESPLIT] public NetcdfDataset openDataset ( String location , boolean acquire , ucar . nc2 . util . CancelTask task , Formatter log ) throws IOException { Result result = new Result ( ) ; Dataset dataset = openCatalogFromLocation ( location , task , result ) ; if ( result . fatalError || dataset == null ) { if ( log != null ) log . format ( \"%s\" , result . errLog ) ; result . close ( ) ; return null ; } return openDataset ( dataset , acquire , task , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the best access in case theres more than one based on what the CDM knows how to open and use . [CODESPLIT] public Access chooseDatasetAccess ( List < Access > accessList ) { if ( accessList . size ( ) == 0 ) return null ; Access access = null ; if ( preferAccess != null ) { for ( ServiceType type : preferAccess ) { access = findAccessByServiceType ( accessList , type ) ; if ( access != null ) break ; } } // the order indicates preference if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . CdmRemote ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DODS ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . OPENDAP ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DAP4 ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . File ) ; // should mean that it can be opened through netcdf API if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . HTTPServer ) ; // should mean that it can be opened through netcdf API /* look for HTTP with format we can read\n    if (access == null) {\n      Access tryAccess = findAccessByServiceType(accessList, ServiceType.HTTPServer);\n\n      if (tryAccess != null) {\n        DataFormatType format = tryAccess.getDataFormatType();\n\n        // these are the file types we can read\n        if ((DataFormatType.NCML == format) || (DataFormatType.NETCDF == format)) {   // removed 4/4/2015 jc\n        //if ((DataFormatType.BUFR == format) || (DataFormatType.GINI == format) || (DataFormatType.GRIB1 == format)\n        //        || (DataFormatType.GRIB2 == format) || (DataFormatType.HDF5 == format) || (DataFormatType.NCML == format)\n       //         || (DataFormatType.NETCDF == format) || (DataFormatType.NEXRAD2 == format) || (DataFormatType.NIDS == format)) {\n          access = tryAccess;\n        }\n      }\n    } */ // ADDE if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . ADDE ) ; // RESOLVER if ( access == null ) { access = findAccessByServiceType ( accessList , ServiceType . Resolver ) ; } return access ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add information from the Dataset to the NetcdfDataset . [CODESPLIT] public static void annotate ( Dataset ds , NetcdfDataset ncDataset ) { ncDataset . setTitle ( ds . getName ( ) ) ; ncDataset . setId ( ds . getId ( ) ) ; // add properties as global attributes for ( Property p : ds . getProperties ( ) ) { String name = p . getName ( ) ; if ( null == ncDataset . findGlobalAttribute ( name ) ) { ncDataset . addAttribute ( null , new Attribute ( name , p . getValue ( ) ) ) ; } } /* ThreddsMetadata.GeospatialCoverage geoCoverage = ds.getGeospatialCoverage();\n   if (geoCoverage != null) {\n     if ( null != geoCoverage.getNorthSouthRange()) {\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lat_min\", new Double(geoCoverage.getLatSouth())));\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lat_max\", new Double(geoCoverage.getLatNorth())));\n     }\n     if ( null != geoCoverage.getEastWestRange()) {\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lon_min\", new Double(geoCoverage.getLonWest())));\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lon_max\", new Double(geoCoverage.getLonEast())));\n     }\n     if ( null != geoCoverage.getUpDownRange()) {\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_vertical_min\", new Double(geoCoverage.getHeightStart())));\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_vertical_max\", new Double(geoCoverage.getHeightStart() + geoCoverage.getHeightExtent())));\n     }\n   }\n\n   DateRange timeCoverage = ds.getTimeCoverage();\n   if (timeCoverage != null) {\n     ncDataset.addAttribute(null, new Attribute(\"time_coverage_start\", timeCoverage.getStart().toDateTimeStringISO()));\n     ncDataset.addAttribute(null, new Attribute(\"time_coverage_end\", timeCoverage.getEnd().toDateTimeStringISO()));\n   } */ ncDataset . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for an access method for an image datatype [CODESPLIT] private Access getImageAccess ( Dataset ds , ucar . nc2 . util . CancelTask task , Result result ) throws IOException { List < Access > accessList = new ArrayList <> ( ds . getAccess ( ) ) ; // a list of all the accesses while ( accessList . size ( ) > 0 ) { Access access = chooseImageAccess ( accessList ) ; if ( access == null ) { result . errLog . format ( \"No access that could be used for Image Type %s %n\" , ds ) ; return null ; } // deal with RESOLVER type String datasetLocation = access . getStandardUrlName ( ) ; Dataset rds = openResolver ( datasetLocation , task , result ) ; if ( rds == null ) return null ; // use the access list from the resolved dataset accessList = new ArrayList <> ( ds . getAccess ( ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private Access findAccessByServiceType ( List < Access > accessList , ServiceType type ) { for ( Access a : accessList ) { ServiceType stype = a . getService ( ) . getType ( ) ; if ( stype != null && stype . toString ( ) . equalsIgnoreCase ( type . toString ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private Access findAccessByDataFormatType ( List < Access > accessList , DataFormatType type ) { for ( Access a : accessList ) { DataFormatType has = a . getDataFormatType ( ) ; if ( has != null && type . toString ( ) . equalsIgnoreCase ( has . toString ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////// [CODESPLIT] public String getDetailInfo ( ) { StringBuffer sbuff = new StringBuffer ( ) ; sbuff . append ( \"PointObsDataset\\n\" ) ; sbuff . append ( \"  adapter   = \" ) . append ( getClass ( ) . getName ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \"  timeUnit  = \" ) . append ( getTimeUnits ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \"  dataClass = \" ) . append ( getDataClass ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \"  dataCount = \" ) . append ( getDataCount ( ) ) . append ( \"\\n\" ) ; sbuff . append ( super . getDetailInfo ( ) ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "UnsupportedOperation [CODESPLIT] @ Override public ArrayStructure readStructure ( int start , int count ) throws IOException , ucar . ma2 . InvalidRangeException { throw new UnsupportedOperationException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "isolate dependencies here - in case we have a minimal I / O mode where not all fields are available [CODESPLIT] public float [ ] readData ( RandomAccessFile raf , GribData . InterpolationMethod method ) throws IOException { Grib1Gds gds = getGDS ( ) ; Grib1DataReader reader = new Grib1DataReader ( pdss . getDecimalScale ( ) , gds . getScanMode ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , gds . getNpts ( ) , dataSection . getStartingPosition ( ) ) ; byte [ ] bm = ( bitmap == null ) ? null : bitmap . getBitmap ( raf ) ; float [ ] data = reader . getData ( raf , bm ) ; if ( gdss . isThin ( ) ) { data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , method ) ; } lastRecordRead = this ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data array by first reading in GribRecord . All sections are read in so scanMode is from the datafile not the index . [CODESPLIT] public static float [ ] readData ( RandomAccessFile raf , long startPos ) throws IOException { raf . seek ( startPos ) ; Grib1Record gr = new Grib1Record ( raf ) ; return gr . readData ( raf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Read data array : use when you want to be independent of the GribRecord [CODESPLIT] public GribData . Info getBinaryDataInfo ( RandomAccessFile raf ) throws IOException { GribData . Info info = dataSection . getBinaryDataInfo ( raf ) ; info . decimalScaleFactor = pdss . getDecimalScale ( ) ; info . bitmapLength = ( bitmap == null ) ? 0 : bitmap . getLength ( raf ) ; info . nPoints = getGDS ( ) . getNpts ( ) ; info . msgLength = is . getMessageLength ( ) ; if ( bitmap == null ) { info . ndataPoints = info . nPoints ; } else { byte [ ] bm = bitmap . getBitmap ( raf ) ; if ( bm == null ) { info . ndataPoints = info . nPoints ; } else { // have to count the bits to see how many data values are stored\r info . ndataPoints = GribNumbers . countBits ( bm ) ; } } return info ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging - do not use [CODESPLIT] public int [ ] readRawData ( RandomAccessFile raf ) throws IOException { Grib1Gds gds = getGDS ( ) ; Grib1DataReader reader = new Grib1DataReader ( pdss . getDecimalScale ( ) , gds . getScanMode ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , gds . getNpts ( ) , dataSection . getStartingPosition ( ) ) ; byte [ ] bm = ( bitmap == null ) ? null : bitmap . getBitmap ( raf ) ; return reader . getDataRaw ( raf , bm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "e . g . of server with problem ( 2 - Nov - 2006 ) : http : // acdisc . sci . gsfc . nasa . gov / opendap - bin / nph - dods / OPENDAP / Giovanni / [CODESPLIT] private String forceChild ( String url ) { String prefix = path ; if ( prefix . endsWith ( \"/\" ) ) prefix = path . substring ( 0 , path . length ( ) - 1 ) ; // because the url also contains a '/' that we will use\t\t\t int j = url . substring ( 0 , url . length ( ) - 1 ) . lastIndexOf ( ' ' ) ; // url.length() - 1 was intentional .. if the last char is a '/', we're interested in the previous one. if ( j >= 0 ) { String ret = prefix + url . substring ( j ) ; return ret ; } else // relative paths .. leave intact return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reassemble the url using the specified parts [CODESPLIT] public String assemble ( EnumSet < Parts > parts ) { StringBuilder uri = new StringBuilder ( ) ; // Note that format and base may be same, so case it out int useformat = ( parts . contains ( Parts . FORMAT ) ? 1 : 0 ) ; int usebase = ( parts . contains ( Parts . BASE ) ? 2 : 0 ) ; switch ( useformat + usebase ) { case 0 + 0 : // neither break ; case 1 + 0 : // FORMAT only uri . append ( this . formatprotocol + \":\" ) ; break ; case 2 + 0 : // BASE only uri . append ( this . baseprotocol + \":\" ) ; break ; case 2 + 1 : // both uri . append ( this . formatprotocol + \":\" ) ; if ( ! this . baseprotocol . equals ( this . formatprotocol ) ) uri . append ( this . formatprotocol + \":\" ) ; break ; } uri . append ( this . baseprotocol . equals ( \"file\" ) ? \"/\" : \"//\" ) ; if ( userinfo != null && parts . contains ( Parts . PWD ) ) uri . append ( this . userinfo + \":\" ) ; if ( this . host != null && parts . contains ( Parts . HOST ) ) uri . append ( this . host ) ; if ( this . path != null && parts . contains ( Parts . PATH ) ) uri . append ( this . path ) ; if ( this . query != null && parts . contains ( Parts . QUERY ) ) uri . append ( \"?\" + this . query ) ; if ( this . frag != null && parts . contains ( Parts . FRAG ) ) uri . append ( \"#\" + this . frag ) ; return uri . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Canonicalize a part of a URL [CODESPLIT] static public String canonical ( String s ) { if ( s != null ) { s = s . trim ( ) ; if ( s . length ( ) == 0 ) s = null ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static boolean isMine ( NetcdfFile ncfile ) { if ( null == ncfile . findDimension ( \"south_north\" ) ) return false ; // ARW only\r Attribute att = ncfile . findGlobalAttribute ( \"DYN_OPT\" ) ; if ( att != null ) { if ( att . getNumericValue ( ) . intValue ( ) != 2 ) return false ; } else { att = ncfile . findGlobalAttribute ( \"GRIDTYPE\" ) ; if ( att != null ) { if ( ! att . getStringValue ( ) . equalsIgnoreCase ( \"C\" ) && ! att . getStringValue ( ) . equalsIgnoreCase ( \"E\" ) ) return false ; } } att = ncfile . findGlobalAttribute ( \"MAP_PROJ\" ) ; return att != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ARW Users Guide p 3 - 19 <pre > 7 . MAP_PROJ_NAME : Character string specifying type of map projection . Valid entries are : polar - > Polar stereographic lambert - > Lambert conformal ( secant and tangent ) mercator - > Mercator [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) { if ( null != ds . findVariable ( \"x\" ) ) return ; // check if its already been done - aggregating enhanced datasets.\r Attribute att = ds . findGlobalAttribute ( \"GRIDTYPE\" ) ; gridE = att != null && att . getStringValue ( ) . equalsIgnoreCase ( \"E\" ) ; // kludge in fixing the units\r List < Variable > vlist = ds . getVariables ( ) ; for ( Variable v : vlist ) { att = v . findAttributeIgnoreCase ( CDM . UNITS ) ; if ( att != null ) { String units = att . getStringValue ( ) ; if ( units != null ) v . addAttribute ( new Attribute ( CDM . UNITS , normalize ( units ) ) ) ; // removes the old\r } } // make projection transform\r att = ds . findGlobalAttribute ( \"MAP_PROJ\" ) ; int projType = att . getNumericValue ( ) . intValue ( ) ; boolean isLatLon = false ; if ( projType == 203 ) { /* centerX = centralLon;\r\n      centerY = centralLat;\r\n      ds.addCoordinateAxis( makeLonCoordAxis( ds, \"longitude\", ds.findDimension(\"west_east\")));\r\n      ds.addCoordinateAxis( makeLatCoordAxis( ds, \"latitude\", ds.findDimension(\"south_north\")));  */ Variable glat = ds . findVariable ( \"GLAT\" ) ; if ( glat == null ) { parseInfo . format ( \"Projection type 203 - expected GLAT variable not found%n\" ) ; } else { glat . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; if ( gridE ) glat . addAttribute ( new Attribute ( _Coordinate . Stagger , CDM . ARAKAWA_E ) ) ; glat . setDimensions ( \"south_north west_east\" ) ; glat . setCachedData ( convertToDegrees ( glat ) , false ) ; glat . addAttribute ( new Attribute ( CDM . UNITS , CDM . LAT_UNITS ) ) ; } Variable glon = ds . findVariable ( \"GLON\" ) ; if ( glon == null ) { parseInfo . format ( \"Projection type 203 - expected GLON variable not found%n\" ) ; } else { glon . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; if ( gridE ) glon . addAttribute ( new Attribute ( _Coordinate . Stagger , CDM . ARAKAWA_E ) ) ; glon . setDimensions ( \"south_north west_east\" ) ; glon . setCachedData ( convertToDegrees ( glon ) , false ) ; glon . addAttribute ( new Attribute ( CDM . UNITS , CDM . LON_UNITS ) ) ; } VariableDS v = new VariableDS ( ds , null , null , \"LatLonCoordSys\" , DataType . CHAR , \"\" , null , null ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , \"GLAT GLON Time\" ) ) ; Array data = Array . factory ( DataType . CHAR , new int [ ] { } , new char [ ] { ' ' } ) ; v . setCachedData ( data , true ) ; ds . addVariable ( null , v ) ; Variable dataVar = ds . findVariable ( \"LANDMASK\" ) ; dataVar . addAttribute ( new Attribute ( _Coordinate . Systems , \"LatLonCoordSys\" ) ) ; } else { double lat1 = findAttributeDouble ( ds , \"TRUELAT1\" ) ; double lat2 = findAttributeDouble ( ds , \"TRUELAT2\" ) ; double centralLat = findAttributeDouble ( ds , \"CEN_LAT\" ) ; // center of grid\r double centralLon = findAttributeDouble ( ds , \"CEN_LON\" ) ; // center of grid\r double standardLon = findAttributeDouble ( ds , \"STAND_LON\" ) ; // true longitude\r double standardLat = findAttributeDouble ( ds , \"MOAD_CEN_LAT\" ) ; ProjectionImpl proj = null ; switch ( projType ) { case 0 : // for diagnostic runs with no georeferencing\r proj = new FlatEarth ( ) ; projCT = new ProjectionCT ( \"flat_earth\" , \"FGDC\" , proj ) ; // System.out.println(\" using LC \"+proj.paramsToString());\r break ; case 1 : proj = new LambertConformal ( standardLat , standardLon , lat1 , lat2 , 0.0 , 0.0 , 6370 ) ; projCT = new ProjectionCT ( \"Lambert\" , \"FGDC\" , proj ) ; // System.out.println(\" using LC \"+proj.paramsToString());\r break ; case 2 : // Thanks to Heiko Klein for figuring out WRF Stereographic\r double lon0 = ( Double . isNaN ( standardLon ) ) ? centralLon : standardLon ; double lat0 = ( Double . isNaN ( centralLat ) ) ? lat2 : centralLat ; // ?? 7/20/2010\r double scaleFactor = ( 1 + Math . abs ( Math . sin ( Math . toRadians ( lat1 ) ) ) ) / 2. ; // R Schmunk 9/10/07\r // proj = new Stereographic(lat2, lon0, scaleFactor);\r proj = new Stereographic ( lat0 , lon0 , scaleFactor , 0.0 , 0.0 , 6370 ) ; projCT = new ProjectionCT ( \"Stereographic\" , \"FGDC\" , proj ) ; break ; case 3 : proj = new Mercator ( standardLon , lat1 , 0.0 , 0.0 , 6370 ) ; // thanks to Robert Schmunk with edits for non-MOAD grids\r projCT = new ProjectionCT ( \"Mercator\" , \"FGDC\" , proj ) ; // proj = new TransverseMercator(standardLat, standardLon, 1.0);\r //projCT = new ProjectionCT(\"TransverseMercator\", \"FGDC\", proj);\r break ; case 6 : // version 3 \"lat-lon\", including global\r // http://www.mmm.ucar.edu/wrf/users/workshops/WS2008/presentations/1-2.pdf\r // use 2D XLAT, XLONG\r isLatLon = true ; for ( Variable v : vlist ) { if ( v . getShortName ( ) . startsWith ( \"XLAT\" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; removeConstantTimeDim ( ds , v ) ; } else if ( v . getShortName ( ) . startsWith ( \"XLONG\" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; removeConstantTimeDim ( ds , v ) ; } else if ( v . getShortName ( ) . equals ( \"T\" ) ) { // ANOTHER MAJOR KLUDGE to pick up 4D fields\r v . addAttribute ( new Attribute ( _Coordinate . Axes , \"Time XLAT XLONG z\" ) ) ; } else if ( v . getShortName ( ) . equals ( \"U\" ) ) { v . addAttribute ( new Attribute ( _Coordinate . Axes , \"Time XLAT_U XLONG_U z\" ) ) ; } else if ( v . getShortName ( ) . equals ( \"V\" ) ) { v . addAttribute ( new Attribute ( _Coordinate . Axes , \"Time XLAT_V XLONG_V z\" ) ) ; } else if ( v . getShortName ( ) . equals ( \"W\" ) ) { v . addAttribute ( new Attribute ( _Coordinate . Axes , \"Time XLAT XLONG z_stag\" ) ) ; } } break ; default : parseInfo . format ( \"ERROR: unknown projection type = %s%n\" , projType ) ; break ; } if ( proj != null ) { LatLonPointImpl lpt1 = new LatLonPointImpl ( centralLat , centralLon ) ; // center of the grid\r ProjectionPoint ppt1 = proj . latLonToProj ( lpt1 , new ProjectionPointImpl ( ) ) ; centerX = ppt1 . getX ( ) ; centerY = ppt1 . getY ( ) ; if ( debug ) { System . out . println ( \"centerX=\" + centerX ) ; System . out . println ( \"centerY=\" + centerY ) ; } } // make axes\r if ( ! isLatLon ) { ds . addCoordinateAxis ( makeXCoordAxis ( ds , \"x\" , ds . findDimension ( \"west_east\" ) ) ) ; ds . addCoordinateAxis ( makeXCoordAxis ( ds , \"x_stag\" , ds . findDimension ( \"west_east_stag\" ) ) ) ; ds . addCoordinateAxis ( makeYCoordAxis ( ds , \"y\" , ds . findDimension ( \"south_north\" ) ) ) ; ds . addCoordinateAxis ( makeYCoordAxis ( ds , \"y_stag\" , ds . findDimension ( \"south_north_stag\" ) ) ) ; } ds . addCoordinateAxis ( makeZCoordAxis ( ds , \"z\" , ds . findDimension ( \"bottom_top\" ) ) ) ; ds . addCoordinateAxis ( makeZCoordAxis ( ds , \"z_stag\" , ds . findDimension ( \"bottom_top_stag\" ) ) ) ; if ( projCT != null ) { VariableDS v = makeCoordinateTransformVariable ( ds , projCT ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisTypes , \"GeoX GeoY\" ) ) ; if ( gridE ) v . addAttribute ( new Attribute ( _Coordinate . Stagger , CDM . ARAKAWA_E ) ) ; ds . addVariable ( null , v ) ; } } // time coordinate variations\r if ( ds . findVariable ( \"Time\" ) == null ) { // Can skip this if its already there, eg from NcML\r CoordinateAxis taxis = makeTimeCoordAxis ( ds , \"Time\" , ds . findDimension ( \"Time\" ) ) ; if ( taxis == null ) taxis = makeTimeCoordAxis ( ds , \"Time\" , ds . findDimension ( \"Times\" ) ) ; if ( taxis != null ) ds . addCoordinateAxis ( taxis ) ; } ds . addCoordinateAxis ( makeSoilDepthCoordAxis ( ds , \"ZS\" ) ) ; ds . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pretty much WRF specific [CODESPLIT] private String normalize ( String units ) { switch ( units ) { case \"fraction\" : units = \"\" ; break ; case \"dimensionless\" : units = \"\" ; break ; case \"NA\" : units = \"\" ; break ; case \"-\" : units = \"\" ; break ; default : units = StringUtil2 . substitute ( units , \"**\" , \"^\" ) ; units = StringUtil2 . remove ( units , ' ' ) ; units = StringUtil2 . remove ( units , ' ' ) ; break ; } return units ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private CoordinateAxis makeLonCoordAxis ( NetcdfDataset ds , String axisName , Dimension dim ) { if ( dim == null ) return null ; double dx = 4 * findAttributeDouble ( ds , \"DX\" ) ; int nx = dim . getLength ( ) ; double startx = centerX - dx * ( nx - 1 ) / 2 ; CoordinateAxis v = new CoordinateAxis1D ( ds , null , axisName , DataType . DOUBLE , dim . getShortName ( ) , \"degrees_east\" , \"synthesized longitude coordinate\" ) ; v . setValues ( nx , startx , dx ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , \"Lon\" ) ) ; if ( ! axisName . equals ( dim . getShortName ( ) ) ) v . addAttribute ( new Attribute ( _Coordinate . AliasForDimension , dim . getShortName ( ) ) ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign CoordinateTransform objects to Coordinate Systems . [CODESPLIT] protected void assignCoordinateTransforms ( NetcdfDataset ncDataset ) { super . assignCoordinateTransforms ( ncDataset ) ; // any cs whose got a vertical coordinate with no units\r List < CoordinateSystem > csys = ncDataset . getCoordinateSystems ( ) ; for ( CoordinateSystem cs : csys ) { if ( cs . getZaxis ( ) != null ) { String units = cs . getZaxis ( ) . getUnitsString ( ) ; if ( ( units == null ) || ( units . trim ( ) . length ( ) == 0 ) ) { VerticalCT vct = makeWRFEtaVerticalCoordinateTransform ( ncDataset , cs ) ; if ( vct != null ) cs . addCoordinateTransform ( vct ) ; parseInfo . format ( \"***Added WRFEta verticalCoordinateTransform to %s%n\" , cs . getName ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A path is file if it has no base protocol or is file : [CODESPLIT] static public boolean dspMatch ( String path , DapContext context ) { for ( String s : EXTENSIONS ) { if ( path . endsWith ( s ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main entry point [CODESPLIT] public DapDataset compile ( ) throws DapException { // create and fill the root group buildrootgroup ( this . ncid ) ; if ( this . dmr != null ) dmr . finish ( ) ; return this . dmr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// [CODESPLIT] protected void buildrootgroup ( int ncid ) throws DapException { int ret ; byte [ ] namep = new byte [ NC_MAX_NAME + 1 ] ; errcheck ( ret = nc4 . nc_inq_grpname ( ncid , namep ) ) ; String [ ] pieces = DapUtil . canonicalpath ( this . path ) . split ( \"[/]\" ) ; DapDataset g = factory . newDataset ( pieces [ pieces . length - 1 ] ) ; GroupNotes gi = ( GroupNotes ) Nc4Notes . factory ( NoteSort . GROUP , ncid , ncid , this . dsp ) ; gi . set ( g ) ; this . dsp . note ( gi ) ; this . dmr = g ; fillgroup ( ncid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// [CODESPLIT] int [ ] getGroups ( int gid ) throws DapException { int ret , n ; IntByReference ip = new IntByReference ( ) ; errcheck ( ret = nc4 . nc_inq_grps ( gid , ip , null ) ) ; n = ip . getValue ( ) ; int [ ] grpids = null ; if ( n > 0 ) { grpids = new int [ n ] ; errcheck ( ret = nc4 . nc_inq_grps ( gid , ip , grpids ) ) ; } else grpids = new int [ 0 ] ; return grpids ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Object [] convert ( int count Object src TypeNotes basetype ) throws DapException { boolean isenum = isenumtype ( basetype ) ; boolean isopaque = basetype . isOpaque () ; TypeNotes truetype = basetype ; if ( isenum ) truetype = enumbasetype ( basetype ) ; [CODESPLIT] protected void errcheck ( int ret ) throws DapException { if ( ret != 0 ) { String msg = String . format ( \"TestNetcdf: errno=%d; %s\" , ret , nc4 . nc_strerror ( ret ) ) ; if ( DEBUG ) System . err . println ( msg ) ; throw new DapException ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finish getting the metadata if necessary . If this is an XLink this will trigger a read of the href the first time called . [CODESPLIT] public void finish ( ) { if ( init ) return ; init = true ; if ( xlinkHref == null ) return ; xlinkHref = xlinkHref . trim ( ) ; try { this . xlinkUri = dataset . getParentCatalog ( ) . resolveUri ( xlinkHref ) ; } catch ( java . net . URISyntaxException e ) { log . append ( \" ** Error: Bad URL in metadata href = \" ) . append ( xlinkHref ) . append ( \"\\n\" ) ; return ; } // open and read the referenced catalog XML try { if ( converter == null ) { log . append ( \"  **InvMetadata on = (\" ) . append ( this ) . append ( \"): has no converter\\n\" ) ; return ; } contentObject = converter . readMetadataContentFromURL ( dataset , xlinkUri ) ; if ( isThreddsMetadata ) tm = ( ThreddsMetadata ) contentObject ; } catch ( java . io . IOException e ) { log . append ( \"  **InvMetadata on = (\" ) . append ( xlinkUri ) . append ( \"): Exception (\" ) . append ( e . getMessage ( ) ) . append ( \")\\n\" ) ; // e.printStackTrace(); } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which the key is mapped in this table . [CODESPLIT] public synchronized Object get ( Object key ) { int index = keys . indexOf ( key ) ; if ( index != - 1 ) return elements . elementAt ( index ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the specified key to the specified value in this table . [CODESPLIT] public synchronized Object put ( Object key , Object value ) throws NullPointerException { if ( key == null || value == null ) throw new NullPointerException ( ) ; int index = keys . indexOf ( key ) ; if ( index != - 1 ) { Object prev = elements . elementAt ( index ) ; elements . setElementAt ( value , index ) ; return prev ; } else { keys . addElement ( key ) ; elements . addElement ( value ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the key ( and its corresponding value ) from this table . If the key is not in the table do nothing . [CODESPLIT] public synchronized Object remove ( Object key ) { int index = keys . indexOf ( key ) ; if ( index != - 1 ) { Object prev = elements . elementAt ( index ) ; keys . removeElementAt ( index ) ; elements . removeElementAt ( index ) ; return prev ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return this as a java Date object [CODESPLIT] public Date getDate ( ) { Calendar calendar = Calendar . getInstance ( TimeZone . getTimeZone ( \"GMT\" ) ) ; calendar . set ( Calendar . YEAR , year ) ; calendar . set ( Calendar . MONTH , month - 1 ) ; // MONTH is zero based calendar . set ( Calendar . DAY_OF_MONTH , day ) ; calendar . set ( Calendar . HOUR_OF_DAY , hour ) ; calendar . set ( Calendar . MINUTE , minute ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; return calendar . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a DapDataset : - as DMR - optionally constrained [CODESPLIT] public void print ( ) throws IOException { if ( this . ce == null ) this . ce = CEConstraint . getUniversal ( dmr ) ; assert ( this . ce != null ) ; this . printer . setIndent ( 0 ) ; printNode ( dmr ) ; // start printing at the root printer . eol ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print an arbitrary DapNode and its subnodes as if it is being sent to a client with optional constraint ; inclusions are determined by the view . <p > Handling newlines is a bit tricky because they may be embedded for e . g . groups enums etc . So the rule is that the last newline is elided and left for the caller to print . Exceptions : printMetadata printDimrefs printMaps [CODESPLIT] public void printNode ( DapNode node ) throws IOException { if ( node == null ) return ; DapSort sort = node . getSort ( ) ; String dmrname = sort . getName ( ) ; switch ( sort ) { case DATASET : // treat like group case GROUP : if ( ! this . ce . references ( node ) ) break ; DapGroup group = ( DapGroup ) node ; printer . marginPrint ( \"<\" + dmrname ) ; int flags = ( sort == DapSort . DATASET ? PERLINE : NILFLAGS ) ; printXMLAttributes ( node , ce , flags ) ; printer . println ( \">\" ) ; printer . indent ( ) ; // Make the output order conform to the spec if ( group . getDimensions ( ) . size ( ) > 0 ) { for ( DapNode subnode : group . getDimensions ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } } if ( group . getEnums ( ) . size ( ) > 0 ) { for ( DapNode subnode : group . getEnums ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } } if ( group . getVariables ( ) . size ( ) > 0 ) for ( DapNode subnode : group . getVariables ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } printMetadata ( node ) ; if ( group . getGroups ( ) . size ( ) > 0 ) for ( DapNode subnode : group . getGroups ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } printer . outdent ( ) ; printer . marginPrint ( \"</\" + dmrname + \">\" ) ; break ; case DIMENSION : if ( ! this . ce . references ( node ) ) break ; DapDimension dim = ( DapDimension ) node ; if ( ! dim . isShared ( ) ) break ; // ignore, here, anonymous dimensions printer . marginPrint ( \"<\" + dmrname ) ; printXMLAttributes ( node , ce , NILFLAGS ) ; if ( dim . isUnlimited ( ) ) printXMLAttribute ( AbstractDSP . UCARTAGUNLIMITED , \"1\" , NILFLAGS ) ; if ( hasMetadata ( node ) ) { printer . println ( \">\" ) ; printMetadata ( node ) ; printer . marginPrint ( \"</\" + dmrname + \">\" ) ; } else { printer . print ( \"/>\" ) ; } break ; case ENUMERATION : if ( ! this . ce . references ( node ) ) break ; DapEnumeration en = ( DapEnumeration ) node ; printer . marginPrint ( \"<\" + dmrname ) ; printXMLAttributes ( en , ce , NILFLAGS ) ; printer . println ( \">\" ) ; printer . indent ( ) ; List < String > econstnames = en . getNames ( ) ; for ( String econst : econstnames ) { DapEnumConst value = en . lookup ( econst ) ; assert ( value != null ) ; printer . marginPrintln ( String . format ( \"<EnumConst name=\\\"%s\\\" value=\\\"%d\\\"/>\" , Escape . entityEscape ( econst , null ) , value . getValue ( ) ) ) ; } printMetadata ( node ) ; printer . outdent ( ) ; printer . marginPrint ( \"</\" + dmrname + \">\" ) ; break ; case VARIABLE : if ( ! this . ce . references ( node ) ) break ; DapVariable var = ( DapVariable ) node ; DapType type = var . getBaseType ( ) ; printer . marginPrint ( \"<\" + type . getTypeSort ( ) . name ( ) ) ; printXMLAttributes ( node , ce , NILFLAGS ) ; if ( type . isAtomic ( ) ) { if ( ( hasMetadata ( node ) || hasDimensions ( var ) || hasMaps ( var ) ) ) { printer . println ( \">\" ) ; printer . indent ( ) ; if ( hasDimensions ( var ) ) printDimrefs ( var ) ; if ( hasMetadata ( var ) ) printMetadata ( var ) ; if ( hasMaps ( var ) ) printMaps ( var ) ; printer . outdent ( ) ; printer . marginPrint ( \"</\" + type . getTypeSort ( ) . name ( ) + \">\" ) ; } else printer . print ( \"/>\" ) ; } else if ( type . getTypeSort ( ) . isCompound ( ) ) { DapStructure struct = ( DapStructure ) type ; printer . println ( \">\" ) ; printer . indent ( ) ; for ( DapVariable field : struct . getFields ( ) ) { if ( ! this . ce . references ( field ) ) continue ; printNode ( field ) ; printer . eol ( ) ; } printDimrefs ( var ) ; printMetadata ( var ) ; printMaps ( var ) ; printer . outdent ( ) ; printer . marginPrint ( \"</\" + type . getTypeSort ( ) . name ( ) + \">\" ) ; } else assert false : \"Illegal variable base type\" ; break ; default : assert ( false ) : \"Unexpected sort: \" + sort . name ( ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print info from the node that needs to be in the form of xml attributes [CODESPLIT] void printXMLAttributes ( DapNode node , CEConstraint ce , int flags ) throws IOException { if ( ( flags & PERLINE ) != 0 ) printer . indent ( 2 ) ; // Print name first, if non-null and !NONAME // Note that the short name needs to use // entity escaping (which is done by printXMLattribute), // but backslash escaping is not required. String name = node . getShortName ( ) ; if ( name != null && ( flags & NONAME ) == 0 ) { name = node . getShortName ( ) ; printXMLAttribute ( \"name\" , name , flags ) ; } switch ( node . getSort ( ) ) { case DATASET : DapDataset dataset = ( DapDataset ) node ; printXMLAttribute ( \"dapVersion\" , dataset . getDapVersion ( ) , flags ) ; printXMLAttribute ( \"dmrVersion\" , dataset . getDMRVersion ( ) , flags ) ; // boilerplate printXMLAttribute ( \"xmlns\" , \"http://xml.opendap.org/ns/DAP/4.0#\" , flags ) ; printXMLAttribute ( \"xmlns:dap\" , \"http://xml.opendap.org/ns/DAP/4.0#\" , flags ) ; break ; case DIMENSION : DapDimension orig = ( DapDimension ) node ; if ( orig . isShared ( ) ) { //not Anonymous // name will have already been printed // Now, we need to get the size as defined by the constraint DapDimension actual = this . ce . getRedefDim ( orig ) ; if ( actual == null ) actual = orig ; long size = actual . getSize ( ) ; printXMLAttribute ( \"size\" , Long . toString ( size ) , flags ) ; } break ; case ENUMERATION : printXMLAttribute ( \"basetype\" , ( ( DapEnumeration ) node ) . getBaseType ( ) . getTypeName ( ) , flags ) ; break ; case VARIABLE : DapVariable var = ( DapVariable ) node ; DapType basetype = var . getBaseType ( ) ; if ( basetype . isEnumType ( ) ) { printXMLAttribute ( \"enum\" , basetype . getTypeName ( ) , flags ) ; } break ; case ATTRIBUTE : DapAttribute attr = ( DapAttribute ) node ; basetype = attr . getBaseType ( ) ; printXMLAttribute ( \"type\" , basetype . getTypeName ( ) , flags ) ; if ( attr . getBaseType ( ) . isEnumType ( ) ) { printXMLAttribute ( \"enum\" , basetype . getTypeName ( ) , flags ) ; } break ; default : break ; // node either has no attributes or name only } //switch if ( ! this . testing ) printReserved ( node ) ; if ( ( flags & PERLINE ) != 0 ) { printer . outdent ( 2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PrintXMLAttributes helper function [CODESPLIT] protected void printXMLAttribute ( String name , String value , int flags ) throws DapException { if ( name == null ) return ; if ( ( flags & NONNIL ) == 0 && ( value == null || value . length ( ) == 0 ) ) return ; if ( ( flags & PERLINE ) != 0 ) { printer . eol ( ) ; printer . margin ( ) ; } printer . print ( \" \" + name + \"=\" ) ; printer . print ( \"\\\"\" ) ; if ( value != null ) { // add xml entity escaping if ( ( flags & XMLESCAPED ) == 0 ) value = Escape . entityEscape ( value , \"\\\"\" ) ; printer . print ( value ) ; } printer . print ( \"\\\"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special here is not the same as reserved [CODESPLIT] static boolean isSpecial ( DapAttribute attr ) { if ( attr . getParent ( ) . getSort ( ) == DapSort . DATASET ) { for ( String s : GROUPSPECIAL ) { if ( s . equals ( attr . getShortName ( ) ) ) return true ; } } else if ( attr . getParent ( ) . getSort ( ) == DapSort . VARIABLE ) { for ( String s : VARSPECIAL ) { if ( s . equals ( attr . getShortName ( ) ) ) return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the dimrefs for a variable s dimensions . If the variable has a non - whole projection then use size else use the dimension name . [CODESPLIT] void printDimrefs ( DapVariable var ) throws DapException { if ( var . getRank ( ) == 0 ) return ; List < DapDimension > dimset = this . ce . getConstrainedDimensions ( var ) ; if ( dimset == null ) throw new DapException ( \"Unknown variable: \" + var ) ; assert var . getRank ( ) == dimset . size ( ) ; for ( int i = 0 ; i < var . getRank ( ) ; i ++ ) { DapDimension dim = dimset . get ( i ) ; printer . marginPrint ( \"<Dim\" ) ; if ( dim . isShared ( ) ) { String fqn = dim . getFQN ( ) ; assert ( fqn != null ) : \"Illegal Dimension reference\" ; fqn = fqnXMLEscape ( fqn ) ; printXMLAttribute ( \"name\" , fqn , XMLESCAPED ) ; } else { long size = dim . getSize ( ) ; // the size for printing purposes printXMLAttribute ( \"size\" , Long . toString ( size ) , NILFLAGS ) ; } printer . println ( \"/>\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "XML escape a dap fqn and converting to &quot ; Assumes backslash escapes are in effect for / and . [CODESPLIT] static public String fqnXMLEscape ( String fqn ) { // Split the fqn into pieces StringBuilder xml = new StringBuilder ( ) ; String segment = null ; List < String > segments = Escape . backslashsplit ( fqn , ' ' ) ; for ( int i = 1 ; i < segments . size ( ) - 1 ; i ++ ) { // skip leading / segment = segments . get ( i ) ; segment = Escape . backslashUnescape ( segment ) ; // get to raw name segment = Escape . entityEscape ( segment , \"\\\"\" ) ; // '\"' -> &quot; segment = Escape . backslashEscape ( segment , \"/.\" ) ; // re-escape xml . append ( \"/\" ) ; xml . append ( segment ) ; } // Last segment might be structure path, so similar processing, // but worry about '.' segment = segments . get ( segments . size ( ) - 1 ) ; segments = Escape . backslashsplit ( segment , ' ' ) ; xml . append ( \"/\" ) ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { segment = segments . get ( i ) ; segment = Escape . backslashUnescape ( segment ) ; // get to raw name segment = Escape . entityEscape ( segment , \"\\\"\" ) ; // '\"' -> &quot; segment = Escape . backslashEscape ( segment , \"/.\" ) ; // re-escape if ( i > 0 ) xml . append ( \".\" ) ; xml . append ( segment ) ; } return xml . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize ; note that the file is reopened here [CODESPLIT] public boolean init ( String location , NetcdfFile ncfile ) throws AreaFileException { af = new AreaFile ( location ) ; //read metadata\r dirBlock = af . getDir ( ) ; ad = af . getAreaDirectory ( ) ; int numElements = ad . getElements ( ) ; int numLines = ad . getLines ( ) ; int numBands = ad . getNumberOfBands ( ) ; bandMap = ad . getBands ( ) ; navBlock = af . getNav ( ) ; Date nomTime = ad . getNominalTime ( ) ; DateFormatter df = new DateFormatter ( ) ; try { nav = AREAnav . makeAreaNav ( navBlock , af . getAux ( ) ) ; } catch ( McIDASException me ) { throw new AreaFileException ( me . getMessage ( ) ) ; } int sensor = dirBlock [ AreaFile . AD_SENSORID ] ; String calName = McIDASUtil . intBitsToString ( dirBlock [ AreaFile . AD_CALTYPE ] ) ; int calType = getCalType ( calName ) ; // TODO:  Need to support calibrated data.\r if ( ( af . getCal ( ) != null ) && CalibratorFactory . hasCalibrator ( sensor ) ) { //System.out.println(\"can calibrate\");\r try { calibrator = CalibratorFactory . getCalibrator ( sensor , calType , af . getCal ( ) ) ; } catch ( CalibratorException ce ) { // System.out.println(\"can't make calibrator\");\r calibrator = null ; } //System.out.println(\"calibrator = \" + calibrator);\r } calUnit = ad . getCalibrationUnitName ( ) ; calScale = ( 1.0f / ad . getCalibrationScaleFactor ( ) ) ; // make the dimensions\r Dimension elements = new Dimension ( \"elements\" , numElements , true ) ; Dimension lines = new Dimension ( \"lines\" , numLines , true ) ; Dimension bands = new Dimension ( \"bands\" , numBands , true ) ; Dimension time = new Dimension ( \"time\" , 1 , true ) ; Dimension dirDim = new Dimension ( \"dirSize\" , AreaFile . AD_DIRSIZE , true ) ; Dimension navDim = new Dimension ( \"navSize\" , navBlock . length , true ) ; List < Dimension > image = new ArrayList <> ( ) ; image . add ( time ) ; image . add ( bands ) ; image . add ( lines ) ; image . add ( elements ) ; ncfile . addDimension ( null , elements ) ; ncfile . addDimension ( null , lines ) ; ncfile . addDimension ( null , bands ) ; ncfile . addDimension ( null , time ) ; ncfile . addDimension ( null , dirDim ) ; ncfile . addDimension ( null , navDim ) ; Array varArray ; // make the variables\r // time\r Variable timeVar = new Variable ( ncfile , null , null , \"time\" ) ; timeVar . setDataType ( DataType . INT ) ; timeVar . setDimensions ( \"time\" ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , \"seconds since \" + df . toDateTimeString ( nomTime ) ) ) ; timeVar . addAttribute ( new Attribute ( \"long_name\" , \"time\" ) ) ; varArray = new ArrayInt . D1 ( 1 , false ) ; ( ( ArrayInt . D1 ) varArray ) . set ( 0 , 0 ) ; timeVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , timeVar ) ; // lines and elements\r Variable lineVar = new Variable ( ncfile , null , null , \"lines\" ) ; lineVar . setDataType ( DataType . INT ) ; lineVar . setDimensions ( \"lines\" ) ; //lineVar.addAttribute(new Attribute(CDM.UNITS, \"km\"));\r lineVar . addAttribute ( new Attribute ( \"standard_name\" , \"projection_y_coordinate\" ) ) ; varArray = new ArrayInt . D1 ( numLines , false ) ; for ( int i = 0 ; i < numLines ; i ++ ) { int pos = nav . isFlippedLineCoordinates ( ) ? i : numLines - i - 1 ; ( ( ArrayInt . D1 ) varArray ) . set ( i , pos ) ; } lineVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , lineVar ) ; Variable elementVar = new Variable ( ncfile , null , null , \"elements\" ) ; elementVar . setDataType ( DataType . INT ) ; elementVar . setDimensions ( \"elements\" ) ; //elementVar.addAttribute(new Attribute(CDM.UNITS, \"km\"));\r elementVar . addAttribute ( new Attribute ( \"standard_name\" , \"projection_x_coordinate\" ) ) ; varArray = new ArrayInt . D1 ( numElements , false ) ; for ( int i = 0 ; i < numElements ; i ++ ) { ( ( ArrayInt . D1 ) varArray ) . set ( i , i ) ; } elementVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , elementVar ) ; // TODO: handle bands and calibrations\r Variable bandVar = new Variable ( ncfile , null , null , \"bands\" ) ; bandVar . setDataType ( DataType . INT ) ; bandVar . setDimensions ( \"bands\" ) ; bandVar . addAttribute ( new Attribute ( \"long_name\" , \"spectral band number\" ) ) ; bandVar . addAttribute ( new Attribute ( \"axis\" , \"Z\" ) ) ; Array bandArray = new ArrayInt . D1 ( numBands , false ) ; for ( int i = 0 ; i < numBands ; i ++ ) { ( ( ArrayInt . D1 ) bandArray ) . set ( i , bandMap [ i ] ) ; } bandVar . setCachedData ( bandArray , false ) ; ncfile . addVariable ( null , bandVar ) ; // the image\r Variable imageVar = new Variable ( ncfile , null , null , \"image\" ) ; imageVar . setDataType ( DataType . INT ) ; imageVar . setDimensions ( image ) ; setCalTypeAttributes ( imageVar , getCalType ( calName ) ) ; imageVar . addAttribute ( new Attribute ( getADDescription ( AreaFile . AD_CALTYPE ) , calName ) ) ; imageVar . addAttribute ( new Attribute ( \"bands\" , bandArray ) ) ; imageVar . addAttribute ( new Attribute ( \"grid_mapping\" , \"AREAnav\" ) ) ; ncfile . addVariable ( null , imageVar ) ; Variable dirVar = new Variable ( ncfile , null , null , \"areaDirectory\" ) ; dirVar . setDataType ( DataType . INT ) ; dirVar . setDimensions ( \"dirSize\" ) ; setAreaDirectoryAttributes ( dirVar ) ; ArrayInt . D1 dirArray = new ArrayInt . D1 ( AreaFile . AD_DIRSIZE , false ) ; for ( int i = 0 ; i < AreaFile . AD_DIRSIZE ; i ++ ) { dirArray . set ( i , dirBlock [ i ] ) ; } dirVar . setCachedData ( dirArray , false ) ; ncfile . addVariable ( null , dirVar ) ; Variable navVar = new Variable ( ncfile , null , null , \"navBlock\" ) ; navVar . setDataType ( DataType . INT ) ; navVar . setDimensions ( \"navSize\" ) ; setNavBlockAttributes ( navVar ) ; ArrayInt . D1 navArray = new ArrayInt . D1 ( navBlock . length , false ) ; for ( int i = 0 ; i < navBlock . length ; i ++ ) { navArray . set ( i , navBlock [ i ] ) ; } navVar . setCachedData ( navArray , false ) ; ncfile . addVariable ( null , navVar ) ; // projection variable\r ProjectionImpl projection = new McIDASAreaProjection ( af ) ; Variable proj = new Variable ( ncfile , null , null , \"AREAnav\" ) ; proj . setDataType ( DataType . CHAR ) ; proj . setDimensions ( \"\" ) ; for ( Parameter p : projection . getProjectionParameters ( ) ) { proj . addAttribute ( new Attribute ( p ) ) ; } // For now, we have to overwrite the parameter versions of thes\r proj . addAttribute ( new Attribute ( \"grid_mapping_name\" , McIDASAreaProjection . GRID_MAPPING_NAME ) ) ; /*\r\n        proj.addAttribute(new Attribute(McIDASAreaProjection.ATTR_AREADIR,\r\n                                        dirArray));\r\n        proj.addAttribute(new Attribute(McIDASAreaProjection.ATTR_NAVBLOCK,\r\n                                        navArray));\r\n        */ varArray = new ArrayChar . D0 ( ) ; ( ( ArrayChar . D0 ) varArray ) . set ( ' ' ) ; proj . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , proj ) ; // add global attributes\r ncfile . addAttribute ( null , new Attribute ( \"Conventions\" , \"CF-1.0\" ) ) ; ncfile . addAttribute ( null , new Attribute ( CF . FEATURE_TYPE , FeatureType . GRID . toString ( ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"nominal_image_time\" , df . toDateTimeString ( nomTime ) ) ) ; String encStr = \"netCDF encoded on \" + df . toDateTimeString ( new Date ( ) ) ; ncfile . addAttribute ( null , new Attribute ( \"history\" , encStr ) ) ; //Lastly, finish the file\r ncfile . finish ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check to see if this is a valid AREA file . [CODESPLIT] public static boolean isValidFile ( RandomAccessFile raf ) { String fileName = raf . getLocation ( ) ; AreaFile af = null ; try { af = new AreaFile ( fileName ) ; // LOOK opening again not ok for isValidFile\r return true ; } catch ( AreaFileException e ) { return false ; // barfola\r } finally { if ( af != null ) af . close ( ) ; // LOOK need to look at this code\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the values for a variable [CODESPLIT] public Array readVariable ( Variable v2 , Section section ) throws IOException , InvalidRangeException { // not sure why timeRange isn't used...will comment out\r // for now\r // TODO: use timeRange in readVariable\r //Range timeRange = null;\r Range bandRange = null ; Range geoXRange = null ; Range geoYRange = null ; Array dataArray ; if ( section == null ) { dataArray = Array . factory ( v2 . getDataType ( ) , v2 . getShape ( ) ) ; } else if ( section . getRank ( ) > 0 ) { if ( section . getRank ( ) > 3 ) { //timeRange = (Range) section.getRange(0);\r bandRange = section . getRange ( 1 ) ; geoYRange = section . getRange ( 2 ) ; geoXRange = section . getRange ( 3 ) ; } else if ( section . getRank ( ) > 2 ) { //timeRange = (Range) section.getRange(0);\r geoYRange = section . getRange ( 1 ) ; geoXRange = section . getRange ( 2 ) ; } else if ( section . getRank ( ) > 1 ) { geoYRange = section . getRange ( 0 ) ; geoXRange = section . getRange ( 1 ) ; } dataArray = Array . factory ( v2 . getDataType ( ) , section . getShape ( ) ) ; } else { String strRank = Integer . toString ( section . getRank ( ) ) ; String msg = \"Invalid Rank: \" + strRank + \". Must be > 0.\" ; throw new IndexOutOfBoundsException ( msg ) ; } String varname = v2 . getFullName ( ) ; Index dataIndex = dataArray . getIndex ( ) ; if ( varname . equals ( \"latitude\" ) || varname . equals ( \"longitude\" ) ) { double [ ] [ ] pixel = new double [ 2 ] [ 1 ] ; double [ ] [ ] latLon ; assert geoXRange != null ; assert geoYRange != null ; // Use Range object, which calculates requested i, j\r // values and incorporates stride\r for ( int i = 0 ; i < geoXRange . length ( ) ; i ++ ) { for ( int j = 0 ; j < geoYRange . length ( ) ; j ++ ) { pixel [ 0 ] [ 0 ] = ( double ) geoXRange . element ( i ) ; pixel [ 1 ] [ 0 ] = ( double ) geoYRange . element ( j ) ; latLon = nav . toLatLon ( pixel ) ; if ( varname . equals ( \"lat\" ) ) { dataArray . setFloat ( dataIndex . set ( j , i ) , ( float ) ( latLon [ 0 ] [ 0 ] ) ) ; } else { dataArray . setFloat ( dataIndex . set ( j , i ) , ( float ) ( latLon [ 1 ] [ 0 ] ) ) ; } } } } if ( varname . equals ( \"image\" ) ) { try { int [ ] [ ] pixelData ; if ( bandRange != null ) { for ( int k = 0 ; k < bandRange . length ( ) ; k ++ ) { int bandIndex = bandRange . element ( k ) + 1 ; // band numbers in McIDAS are 1 based\r for ( int j = 0 ; j < geoYRange . length ( ) ; j ++ ) { for ( int i = 0 ; i < geoXRange . length ( ) ; i ++ ) { pixelData = af . getData ( geoYRange . element ( j ) , geoXRange . element ( i ) , 1 , 1 , bandIndex ) ; dataArray . setInt ( dataIndex . set ( 0 , k , j , i ) , ( pixelData [ 0 ] [ 0 ] ) ) ; } } } } else { assert geoXRange != null ; assert geoYRange != null ; for ( int j = 0 ; j < geoYRange . length ( ) ; j ++ ) { for ( int i = 0 ; i < geoXRange . length ( ) ; i ++ ) { pixelData = af . getData ( geoYRange . element ( j ) , geoXRange . element ( i ) , 1 , 1 ) ; dataArray . setInt ( dataIndex . set ( 0 , j , i ) , ( pixelData [ 0 ] [ 0 ] ) ) ; } } } } catch ( AreaFileException afe ) { throw new IOException ( afe . toString ( ) ) ; } } return dataArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the area directory attributes on the variable [CODESPLIT] private void setAreaDirectoryAttributes ( Variable v ) { if ( ( dirBlock == null ) || ( ad == null ) ) { return ; } for ( int i = 1 ; i < 14 ; i ++ ) { if ( i == 7 ) { continue ; } v . addAttribute ( new Attribute ( getADDescription ( i ) , dirBlock [ i ] ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the navigation block attributes on the variable [CODESPLIT] private void setNavBlockAttributes ( Variable v ) { if ( ( navBlock == null ) || ( ad == null ) ) { return ; } v . addAttribute ( new Attribute ( \"navigation_type\" , McIDASUtil . intBitsToString ( navBlock [ 0 ] ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a description for a particular Area Directory entry [CODESPLIT] private String getADDescription ( int index ) { String desc = \"dir(\" + index + \")\" ; switch ( index ) { case AreaFile . AD_STATUS : desc = \"relative position of the image object in the ADDE dataset\" ; break ; case AreaFile . AD_VERSION : desc = \"AREA version\" ; break ; case AreaFile . AD_SENSORID : desc = \"SSEC sensor source number\" ; break ; case AreaFile . AD_IMGDATE : desc = \"nominal year and Julian day of the image (yyyddd)\" ; break ; case AreaFile . AD_IMGTIME : desc = \"nominal time of the image (hhmmss)\" ; break ; case AreaFile . AD_STLINE : desc = \"upper-left image line coordinate\" ; break ; case AreaFile . AD_STELEM : desc = \"upper-left image element coordinate\" ; break ; case AreaFile . AD_NUMLINES : desc = \"number of lines in the image\" ; break ; case AreaFile . AD_NUMELEMS : desc = \"number of data points per line\" ; break ; case AreaFile . AD_DATAWIDTH : desc = \"number of bytes per data point\" ; break ; case AreaFile . AD_LINERES : desc = \"line resolution\" ; break ; case AreaFile . AD_ELEMRES : desc = \"element resolution\" ; break ; case AreaFile . AD_NUMBANDS : desc = \"number of spectral bands\" ; break ; case AreaFile . AD_PFXSIZE : desc = \"length of the line prefix\" ; break ; case AreaFile . AD_PROJNUM : desc = \"SSEC project number used when creating the file\" ; break ; case AreaFile . AD_CRDATE : desc = \"year and Julian day the image file was created (yyyddd)\" ; break ; case AreaFile . AD_CRTIME : desc = \"image file creation time (hhmmss)\" ; break ; case AreaFile . AD_BANDMAP : desc = \"spectral band map: bands 1-32\" ; break ; case AreaFile . AD_DATAOFFSET : desc = \"byte offset to the start of the data block\" ; break ; case AreaFile . AD_NAVOFFSET : desc = \"byte offset to the start of the navigation block\" ; break ; case AreaFile . AD_VALCODE : desc = \"validity code\" ; break ; case AreaFile . AD_STARTDATE : desc = \"actual image start year and Julian day (yyyddd)\" ; break ; case AreaFile . AD_STARTTIME : desc = \"actual image start time (hhmmss) in milliseconds for POES data\" ; break ; case AreaFile . AD_STARTSCAN : desc = \"actual image start scan\" ; break ; case AreaFile . AD_DOCLENGTH : desc = \"length of the prefix documentation\" ; break ; case AreaFile . AD_CALLENGTH : desc = \"length of the prefix calibration\" ; break ; case AreaFile . AD_LEVLENGTH : desc = \"length of the prefix band list\" ; break ; case AreaFile . AD_SRCTYPE : desc = \"source type\" ; break ; case AreaFile . AD_CALTYPE : desc = \"calibration type\" ; break ; case AreaFile . AD_SRCTYPEORIG : desc = \"original source type\" ; break ; case AreaFile . AD_CALTYPEUNIT : desc = \"calibration unit\" ; break ; case AreaFile . AD_CALTYPESCALE : desc = \"calibration scaling\" ; break ; case AreaFile . AD_AUXOFFSET : desc = \"byte offset to the supplemental block\" ; break ; case AreaFile . AD_CALOFFSET : desc = \"byte offset to the calibration block\" ; break ; case AreaFile . AD_NUMCOMMENTS : desc = \"number of comment cards\" ; break ; } desc = desc . replaceAll ( \"\\\\s\" , \"_\" ) ; return desc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the calibration type from the name [CODESPLIT] private int getCalType ( String calName ) { int calTypeOut = Calibrator . CAL_NONE ; if ( calName . trim ( ) . equals ( \"ALB\" ) ) { calTypeOut = Calibrator . CAL_ALB ; } else if ( calName . trim ( ) . equals ( \"BRIT\" ) ) { calTypeOut = Calibrator . CAL_BRIT ; } else if ( calName . trim ( ) . equals ( \"RAD\" ) ) { calTypeOut = Calibrator . CAL_RAD ; } else if ( calName . trim ( ) . equals ( \"RAW\" ) ) { calTypeOut = Calibrator . CAL_RAW ; } else if ( calName . trim ( ) . equals ( \"TEMP\" ) ) { calTypeOut = Calibrator . CAL_TEMP ; } return calTypeOut ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the long name and units for the calibration type [CODESPLIT] private void setCalTypeAttributes ( Variable image , int calType ) { String longName = \"image values\" ; //String unit     = \"\";\r switch ( calType ) { case Calibrator . CAL_ALB : longName = \"albedo\" ; //unit     = \"%\";\r break ; case Calibrator . CAL_BRIT : longName = \"brightness values\" ; break ; case Calibrator . CAL_TEMP : longName = \"temperature\" ; //unit     = \"K\";\r break ; case Calibrator . CAL_RAD : longName = \"pixel radiance values\" ; //unit     = \"mW/m2/sr/cm-1\";\r break ; case Calibrator . CAL_RAW : longName = \"raw image values\" ; break ; default : break ; } image . addAttribute ( new Attribute ( \"long_name\" , longName ) ) ; if ( calUnit != null ) { image . addAttribute ( new Attribute ( CDM . UNITS , calUnit ) ) ; } if ( calScale != 1.f ) { image . addAttribute ( new Attribute ( \"scale_factor\" , calScale ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "search for Axis by Type assign to TableConfig if found . search for Lat Lon Time Height . [CODESPLIT] static public void findCoords ( TableConfig nt , NetcdfDataset ds , Predicate p ) { nt . lat = findCoordShortNameByType ( ds , AxisType . Lat , p ) ; nt . lon = findCoordShortNameByType ( ds , AxisType . Lon , p ) ; nt . time = findCoordShortNameByType ( ds , AxisType . Time , p ) ; nt . elev = findCoordShortNameByType ( ds , AxisType . Height , p ) ; if ( nt . elev == null ) nt . elev = findCoordShortNameByType ( ds , AxisType . Pressure , p ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "search for Axis by Type . [CODESPLIT] static public String findCoordNameByType ( NetcdfDataset ds , AxisType atype ) { CoordinateAxis coordAxis = findCoordByType ( ds , atype ) ; return coordAxis == null ? null : coordAxis . getFullName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for Axis by Type . [CODESPLIT] static public CoordinateAxis findCoordByType ( NetcdfDataset ds , AxisType atype ) { return findCoordByType ( ds , atype , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "search for Axis by Type and test against a predicate [CODESPLIT] static public CoordinateAxis findCoordByType ( NetcdfDataset ds , AxisType atype , Predicate p ) { // try the \"best\" coordinate system\r CoordinateSystem use = findBestCoordinateSystem ( ds ) ; if ( use == null ) return null ; CoordinateAxis result = findCoordByType ( use . getCoordinateAxes ( ) , atype , p ) ; if ( result != null ) return result ; // try all the axes\r return findCoordByType ( ds . getCoordinateAxes ( ) , atype , p ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "search for Dimension used by axis of given by Type . [CODESPLIT] static public Dimension findDimensionByType ( NetcdfDataset ds , AxisType atype ) { CoordinateAxis axis = findCoordByType ( ds , atype ) ; if ( axis == null ) return null ; if ( axis . isScalar ( ) ) return null ; return axis . getDimension ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the CoordinateSystem with the most number of CoordinateAxes [CODESPLIT] static private CoordinateSystem findBestCoordinateSystem ( NetcdfDataset ds ) { // find coordinate system with highest rank (largest number of axes)\r CoordinateSystem use = null ; for ( CoordinateSystem cs : ds . getCoordinateSystems ( ) ) { if ( use == null ) use = cs ; else if ( cs . getCoordinateAxes ( ) . size ( ) > use . getCoordinateAxes ( ) . size ( ) ) use = cs ; } return use ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the dependent axis that depend on independentAxis [CODESPLIT] private CoverageCoordAxis1D findDependent ( CoverageCoordAxis independentAxis , AxisType axisType ) { for ( CoverageCoordAxis axis : axes ) { if ( axis . getDependenceType ( ) == CoverageCoordAxis . DependenceType . dependent ) { for ( String axisName : axis . dependsOn ) { if ( axisName . equalsIgnoreCase ( independentAxis . getName ( ) ) && axis . getAxisType ( ) == axisType ) return ( CoverageCoordAxis1D ) axis ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the state of this variable s projection . <code > true< / code > means that this variable is part of the current projection as defined by the current constraint expression otherwise the current projection for this variable should be <code > false< / code > . [CODESPLIT] @ Override public void setProject ( boolean state , boolean all ) { super . setProject ( state , all ) ; if ( all ) for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; sm . setProject ( state , all ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the row vector for into which to read a row os data for this sequence . When serving sequence data to clients the prefered method is to read one row of the sequence at a time in to this vector evaluate the constraint expression clauses on the current data and then send it to the client if it satisfies the constraint . The NOT recomended way is to read the ENTIRE sequence into memory prior to sending it ( that would be most inefficient ) . [CODESPLIT] public Vector getRowVector ( ) throws NoSuchVariableException { if ( getRowCount ( ) == 0 ) { if ( _Debug ) System . out . println ( \"This sequence has \" + getRowCount ( ) + \" rows.\" ) ; Vector rv = new Vector ( ) ; for ( int i = 0 ; i < elementCount ( false ) ; i ++ ) { if ( _Debug ) System . out . println ( \"Building variable \" + i + \": \" + getVar ( i ) . getEncodedName ( ) ) ; rv . add ( getVar ( i ) ) ; } if ( _Debug ) System . out . println ( \"Adding row to sequence...\" ) ; addRow ( rv ) ; } return ( getRow ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType // and all of the different signatures of printDecl() in BaseType // lead to one signature, we must be careful to override that // SAME signature here. That way all calls to printDecl() for // this object lead to this implementation. // Also, since printDecl()is (multiple) overloaded in BaseType and // all of the different signatures of printDecl() in BaseType lead to // the signature we are overriding here, we MUST call the printDecl // with the SAME signature THROUGH the super class reference // (assuming we want the super class functionality). If we do // otherwise, we will create an infinte call loop. OOPS! // If we are constrained, make sure some part of this thing is projected if ( constrained && ! isProject ( ) ) return ; super . printDecl ( os , space , print_semi , constrained ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . <p / > <h2 > Important Note< / h2 > This method overrides the BaseType method of the same name and type signature and it significantly changes the behavior for all versions of <code > printVal () < / code > for this type : <b > <i > All the various versions of printVal () will only print a value or a value with declaration if the variable is in the projection . < / i > < / b > <br > <br > In other words if a call to <code > isProject () < / code > for a particular variable returns <code > true< / code > then <code > printVal () < / code > will print a value ( or a declaration and a value ) . <br > <br > If <code > isProject () < / code > for a particular variable returns <code > false< / code > then <code > printVal () < / code > is basically a No - Op . <br > <br > [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; if ( print_decl_p ) { printDecl ( os , space , false , true ) ; os . print ( \" = \" ) ; } os . print ( \"{ \" ) ; try { boolean firstPass = true ; Vector v = getRowVector ( ) ; for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) { // get next instance variable BaseType bt = ( BaseType ) e2 . nextElement ( ) ; if ( ( ( ServerMethods ) bt ) . isProject ( ) ) { if ( ! firstPass ) os . print ( \", \" ) ; bt . printVal ( os , \"\" , false ) ; firstPass = false ; } } } catch ( NoSuchVariableException e ) { os . println ( \"Very Bad Things Happened When I Tried To Print \" + \"A Row Of The Sequence: \" + getEncodedName ( ) ) ; } os . print ( \" }\" ) ; if ( print_decl_p ) os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the state of this variable s projection . <code > true< / code > means that this variable is part of the current projection as defined by the current constraint expression otherwise the current projection for this variable should be <code > false< / code > . [CODESPLIT] @ Override public void setProject ( boolean state , boolean all ) { setProjected ( state ) ; if ( all ) for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; sm . setProject ( state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Read property . A normal variable is read using the <code > read () < / code > method . Once read the <em > Read< / em > property is <code > true< / code > . Use this function to manually set the property value . By default this property is false . [CODESPLIT] public void setAllReadFlags ( boolean state ) { ReadMe = state ; for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; //System.out.println(\"Setting Read Flag for \"+((BaseType)sm).getName()+\" to \"+state); sm . setRead ( state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Server - side serialization for OPeNDAP variables ( sub - classes of <code > BaseType< / code > ) . This does not send the entire class as the Java <code > Serializable< / code > interface does rather it sends only the binary data values . Other software is responsible for sending variable type information ( see <code > DDS< / code > ) . <p > <p / > Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { boolean moreToRead = true ; while ( moreToRead ) { if ( ! isRead ( ) ) { // ************* Pulled out the getLevel() check in order to support the \"new\" // and \"improved\" serialization of OPeNDAP sequences. 8/31/01 ndp //                if(getLevel() != 0 )  // Read only the outermost level //                    return; moreToRead = read ( dataset , specialO ) ; } //System.out.println(\"Evaluating Clauses...\"); if ( ce . evalClauses ( specialO ) ) { //System.out.println(\"Clauses evaluated true\"); // ************* Pulled out the getLevel() check in order to support the \"new\" // and \"improved\" serialization of OPeNDAP sequences. 8/31/01 ndp //                if(getLevel() == 0){ writeMarker ( sink , START_OF_INSTANCE ) ; //                } for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; if ( sm . isProject ( ) ) { if ( _Debug ) System . out . println ( \"Sending variable: \" + ( ( BaseType ) sm ) . getEncodedName ( ) ) ; sm . serialize ( dataset , sink , ce , specialO ) ; } } } if ( moreToRead ) setAllReadFlags ( false ) ; } // ************* Pulled out the getLevel() check in order to support the \"new\" // and \"improved\" serialization of OPeNDAP sequences. 8/31/01 ndp //        if(getLevel() == 0){ writeMarker ( sink , END_OF_SEQUENCE ) ; //        } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a variable to the container . [CODESPLIT] public void addVariable ( BaseType v , int part ) { v . setParent ( this ) ; varTemplate . addElement ( v ) ; if ( v instanceof DSequence ) ( ( DSequence ) v ) . setLevel ( getLevel ( ) + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the named variable . <b > Note : < / b > In <code > DSequence< / code > this method returns the template variable which holds no data . If you need to get a variable containing data use <code > getRow< / code > or the <code > getVariable< / code > method which takes a row number parameter . [CODESPLIT] public BaseType getVariable ( String name ) throws NoSuchVariableException { int dotIndex = name . indexOf ( ' ' ) ; if ( dotIndex != - 1 ) { // name contains \".\"\r String aggregate = name . substring ( 0 , dotIndex ) ; String field = name . substring ( dotIndex + 1 ) ; BaseType aggRef = getVariable ( aggregate ) ; if ( aggRef instanceof DConstructor ) return ( ( DConstructor ) aggRef ) . getVariable ( field ) ; // recurse\r else ; // fall through to throw statement\r } else { for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType v = ( BaseType ) e . nextElement ( ) ; if ( v . getEncodedName ( ) . equals ( name ) ) return v ; } } throw new NoSuchVariableException ( \"DSequence: getVariable()\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the indexed variable . For a DSrquence this returns the <code > BaseType< / code > from the <code > index< / code > th column from the internal map <code > Vector< / code > . [CODESPLIT] public BaseType getVar ( int index ) throws NoSuchVariableException { if ( index < varTemplate . size ( ) ) return ( ( BaseType ) varTemplate . elementAt ( index ) ) ; else throw new NoSuchVariableException ( \"DSequence.getVariable(\" + index + \" - 1)\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the named variable in the given row of the sequence . [CODESPLIT] public BaseType getVariable ( int row , String name ) throws NoSuchVariableException { int dotIndex = name . indexOf ( ' ' ) ; if ( dotIndex != - 1 ) { // name contains \".\"\r String aggregate = name . substring ( 0 , dotIndex ) ; String field = name . substring ( dotIndex + 1 ) ; BaseType aggRef = getVariable ( aggregate ) ; if ( aggRef instanceof DConstructor ) return ( ( DConstructor ) aggRef ) . getVariable ( field ) ; // recurse\r else ; // fall through to throw statement\r } else { Vector selectedRow = ( Vector ) allValues . elementAt ( row ) ; for ( Enumeration e = selectedRow . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType v = ( BaseType ) e . nextElement ( ) ; if ( v . getEncodedName ( ) . equals ( name ) ) return v ; } } throw new NoSuchVariableException ( \"DSequence: getVariable()\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for internal consistency . For <code > DSequence< / code > verify that the variables have unique names . [CODESPLIT] public void checkSemantics ( boolean all ) throws BadSemanticsException { super . checkSemantics ( all ) ; Util . uniqueNames ( varTemplate , getEncodedName ( ) , getTypeName ( ) ) ; if ( all ) { for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . checkSemantics ( true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( print_decl_p ) { printDecl ( os , space , false ) ; os . print ( \" = \" ) ; } os . print ( \"{ \" ) ; for ( Enumeration e1 = allValues . elements ( ) ; e1 . hasMoreElements ( ) ; ) { // get next instance vector\r os . print ( \"{ \" ) ; Vector v = ( Vector ) e1 . nextElement ( ) ; for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) { // get next instance variable\r BaseType bt = ( BaseType ) e2 . nextElement ( ) ; bt . printVal ( os , \"\" , false ) ; if ( e2 . hasMoreElements ( ) ) os . print ( \", \" ) ; } os . print ( \" }\" ) ; if ( e1 . hasMoreElements ( ) ) os . print ( \", \" ) ; } os . print ( \" }\" ) ; if ( print_decl_p ) os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , DataReadException { //LogStream.out.println(\"ServerVersion.getMajor() \"+sv.getMajor()+\"  ServerVersion.getMinor(): \"+sv.getMinor());\r // check for old servers\r if ( sv != null && ( sv . getMajor ( ) < 2 || ( sv . getMajor ( ) == 2 && sv . getMinor ( ) < 15 ) ) ) { //LogStream.out.println(\"Using oldDeserialize() mechanism.\");\r oldDeserialize ( source , sv , statusUI ) ; } else { //LogStream.out.println(\"Using new deserialize() mechanism.\");\r // ************* Pulled out the getLevel() check in order to support the \"new\"\r // and \"improved\" serialization of OPeNDAP sequences. 8/31/01 ndp\r //            // top level of sequence handles start and end markers\r //            if (getLevel() == 0) {\r // loop until end of sequence\r for ( ; ; ) { byte marker = readMarker ( source ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 4 ) ; if ( marker == START_OF_INSTANCE ) deserializeSingle ( source , sv , statusUI ) ; else if ( marker == END_OF_SEQUENCE ) break ; else throw new DataReadException ( \"Sequence start marker not found\" ) ; } // ************* Pulled out the getLevel() check in order to support the \"new\"\r // and \"improved\" serialization of OPeNDAP sequences. 8/31/01 ndp\r //            }\r //\t    else {\r //                // lower levels only deserialize a single instance at a time\r //                deserializeSingle(source, sv, statusUI);\r //            }\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The old deserialize protocol has a number of limitations stemming from its inability to tell when the sequence is finished . It s really only good for a Dataset containing a single sequence or where the sequence is the last thing in the dataset . To handle this we just read single instances until we get an IOException then stop . [CODESPLIT] private void oldDeserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , DataReadException { try { for ( ; ; ) { deserializeSingle ( source , sv , statusUI ) ; } } catch ( EOFException e ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize a single row of the <code > DSequence< / code > . [CODESPLIT] private void deserializeSingle ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { // create a new instance from the variable template Vector\r Vector newInstance = new Vector ( ) ; for ( int i = 0 ; i < varTemplate . size ( ) ; i ++ ) { BaseType bt = ( BaseType ) varTemplate . elementAt ( i ) ; newInstance . addElement ( bt . clone ( ) ) ; } // deserialize the new instance\r for ( Enumeration e = newInstance . elements ( ) ; e . hasMoreElements ( ) ; ) { if ( statusUI != null && statusUI . userCancelled ( ) ) throw new DataReadException ( \"User cancelled\" ) ; ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . deserialize ( source , sv , statusUI ) ; } // add the new instance to the allValues vector\r allValues . addElement ( newInstance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a marker byte from the input stream . [CODESPLIT] private byte readMarker ( DataInputStream source ) throws IOException { byte marker = source . readByte ( ) ; // pad out to a multiple of four bytes\r byte unused ; for ( int i = 0 ; i < 3 ; i ++ ) unused = source . readByte ( ) ; return marker ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a marker byte to the output stream . [CODESPLIT] protected void writeMarker ( DataOutputStream sink , byte marker ) throws IOException { //for(int i=0; i<4; i++)\r sink . writeByte ( marker ) ; sink . writeByte ( ( byte ) 0 ) ; sink . writeByte ( ( byte ) 0 ) ; sink . writeByte ( ( byte ) 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { // loop until end of sequence\r for ( int i = 0 ; i < allValues . size ( ) ; i ++ ) { // ************* Pulled out the getLevel() check in order to support the \"new\"\r // and \"improved\" serialization of OPeNDAP sequences. 8/31/01 ndp\r //            if (getLevel() == 0)\r writeMarker ( sink , START_OF_INSTANCE ) ; Vector rowVec = ( Vector ) allValues . elementAt ( i ) ; for ( int j = 0 ; j < rowVec . size ( ) ; j ++ ) { ClientIO bt = ( ClientIO ) rowVec . elementAt ( j ) ; bt . externalize ( sink ) ; } } // ************* Pulled out the getLevel() check in order to support the \"new\"\r // and \"improved\" serialization of OPeNDAP sequences. 8/31/01 ndp\r //        if (getLevel() == 0)\r writeMarker ( sink , END_OF_SEQUENCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Sequence< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DSequence s = ( DSequence ) super . cloneDAG ( map ) ; s . varTemplate = new Vector ( ) ; for ( int i = 0 ; i < varTemplate . size ( ) ; i ++ ) { BaseType bt = ( BaseType ) varTemplate . elementAt ( i ) ; BaseType btclone = ( BaseType ) cloneDAG ( map , bt ) ; s . varTemplate . addElement ( btclone ) ; } s . allValues = new Vector ( ) ; for ( int i = 0 ; i < allValues . size ( ) ; i ++ ) { Vector rowVec = ( Vector ) allValues . elementAt ( i ) ; Vector newVec = new Vector ( ) ; for ( int j = 0 ; j < rowVec . size ( ) ; j ++ ) { BaseType bt = ( BaseType ) rowVec . elementAt ( j ) ; newVec . addElement ( ( BaseType ) cloneDAG ( map , bt ) ) ; } s . allValues . addElement ( newVec ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public API [CODESPLIT] public boolean parse ( String document ) throws SAXException { // Trim and strip any leading <?xml...?> StringBuilder doc = new StringBuilder ( document . trim ( ) ) ; int index = doc . indexOf ( \"<?xml\" ) ; if ( index == 0 ) { index = doc . indexOf ( \"?>\" ) ; if ( index < 0 ) throw new SAXException ( \"Document has malformed <?xml...?> prefix\" ) ; doc . delete ( 0 , index + 2 ) ; // remove any leading crlf while ( doc . length ( ) > 0 && \"\\r\\n\" . indexOf ( doc . charAt ( 0 ) ) >= 0 ) doc . deleteCharAt ( 0 ) ; document = doc . toString ( ) ; } this . document = document ; // Create the sax parser that will drive us with events try { spf = SAXParserFactory . newInstance ( ) ; spf . setValidating ( false ) ; spf . setNamespaceAware ( true ) ; spf . setFeature ( LOAD_EXTERNAL_DTD , false ) ; saxparser = spf . newSAXParser ( ) ; // Set up for the parse input = new ByteArrayInputStream ( document . getBytes ( UTF8 ) ) ; saxparser . parse ( input , this ) ; //'this' is link to subclass parser return true ; } catch ( Exception e ) { throw new SAXException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entity resolution ( Ignored ) [CODESPLIT] @ Override public InputSource resolveEntity ( String publicId , String systemId ) { if ( TRACE ) trace ( \"eventtype.RESOLVEENTITY: %s.%s%n\" , publicId , systemId ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Error handling Events [CODESPLIT] @ Override public void fatalError ( SAXParseException e ) throws SAXException { throw new SAXParseException ( String . format ( \"Sax fatal error: %s; %s%n\" , e , report ( this . locator ) ) , this . locator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Location printing [CODESPLIT] protected void locatedEvent ( SaxEvent token ) throws SAXException { try { yyevent ( token ) ; } catch ( SAXException se ) { throw new SAXException ( locatedError ( se . getMessage ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the demo chart . [CODESPLIT] private static TimeSeries createDataset ( String name , double base , RegularTimePeriod start , int count ) { TimeSeries series = new TimeSeries ( name , start . getClass ( ) ) ; RegularTimePeriod period = start ; double value = base ; for ( int i = 0 ; i < count ; i ++ ) { series . add ( period , value ) ; period = period . next ( ) ; value = value * ( 1 + ( Math . random ( ) - 0.495 ) / 10.0 ) ; } return series ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starting point for the demonstration application . [CODESPLIT] public static void main ( String [ ] args ) { TimeSeries dataset1 = createDataset ( \"Series 1\" , 100.0 , new Minute ( ) , 200 ) ; MultipleAxisChart demo = new MultipleAxisChart ( \"Multiple Axis Demo 1\" , \"Time of Day\" , \"Primary Range Axis\" , dataset1 ) ; /* AXIS 2\n    NumberAxis axis2 = new NumberAxis(\"Range Axis 2\");\n    axis2.setFixedDimension(10.0);\n    axis2.setAutoRangeIncludesZero(false);\n    plot.setRangeAxis(1, axis2);\n    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_LEFT); /\n\n    plot.setDataset(1, dataset2);\n    plot.mapDatasetToRangeAxis(1, 1);\n    XYItemRenderer renderer2 = new StandardXYItemRenderer();\n    plot.setRenderer(1, renderer2); */ TimeSeries dataset2 = createDataset ( \"Series 2\" , 1000.0 , new Minute ( ) , 170 ) ; demo . addSeries ( \"Range Axis 2\" , dataset2 ) ; /*     // AXIS 3\n    NumberAxis axis3 = new NumberAxis(\"Range Axis 3\");\n    plot.setRangeAxis(2, axis3);\n\n    XYDataset dataset3 = createDataset(\"Series 3\", 10000.0, new Minute(), 170);\n    plot.setDataset(2, dataset3);\n    plot.mapDatasetToRangeAxis(2, 2);\n    XYItemRenderer renderer3 = new StandardXYItemRenderer();\n    plot.setRenderer(2, renderer3);\n    */ TimeSeries dataset3 = createDataset ( \"Series 3\" , 10000.0 , new Minute ( ) , 170 ) ; demo . addSeries ( \"Range Axis 3\" , dataset3 ) ; /* AXIS 4\n    NumberAxis axis4 = new NumberAxis(\"Range Axis 4\");\n    plot.setRangeAxis(3, axis4);\n\n    XYDataset dataset4 = createDataset(\"Series 4\", 25.0, new Minute(), 200);\n    plot.setDataset(3, dataset4);\n    plot.mapDatasetToRangeAxis(3, 3);\n\n    XYItemRenderer renderer4 = new StandardXYItemRenderer();\n    plot.setRenderer(3, renderer4); */ TimeSeries dataset4 = createDataset ( \"Series 4\" , 25.0 , new Minute ( ) , 200 ) ; demo . addSeries ( \"Range Axis 4\" , dataset4 ) ; demo . finish ( new java . awt . Dimension ( 600 , 270 ) ) ; JFrame frame = new JFrame ( \"Demovabulous \" ) ; frame . getContentPane ( ) . add ( demo , BorderLayout . CENTER ) ; frame . setSize ( 640 , 480 ) ; frame . setVisible ( true ) ; frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK can we optimize ?? [CODESPLIT] public String [ ] getJavaArrayString ( StructureMembers . Member m ) { if ( m . getDataType ( ) == DataType . STRING ) { Array data = getArray ( m ) ; int n = m . getSize ( ) ; String [ ] result = new String [ n ] ; for ( int i = 0 ; i < result . length ; i ++ ) result [ i ] = ( String ) data . getObject ( i ) ; return result ; } else if ( m . getDataType ( ) == DataType . CHAR ) { ArrayChar data = ( ArrayChar ) getArray ( m ) ; ArrayChar . StringIterator iter = data . getStringIterator ( ) ; String [ ] result = new String [ iter . getNumElems ( ) ] ; int count = 0 ; while ( iter . hasNext ( ) ) result [ count ++ ] = iter . next ( ) ; return result ; } throw new IllegalArgumentException ( \"getJavaArrayString: not String DataType :\" + m . getDataType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array of available parameter names for this volume . [CODESPLIT] public DoradePARM [ ] getParamList ( ) { int paramCount = 0 ; for ( int i = 0 ; i < nSensors ; i ++ ) paramCount += myRADDs [ i ] . getNParams ( ) ; DoradePARM [ ] list = new DoradePARM [ paramCount ] ; int next = 0 ; for ( int i = 0 ; i < nSensors ; i ++ ) { int nParams = myRADDs [ i ] . getNParams ( ) ; System . arraycopy ( myRADDs [ i ] . getParamList ( ) , 0 , list , next , nParams ) ; next += nParams ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "override superclass [CODESPLIT] private void makeMyUI ( ) { AbstractAction incrFontAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { stnRender . incrFontSize ( ) ; redraw ( ) ; } } ; BAMutil . setActionProperties ( incrFontAction , \"FontIncr\" , \"increase font size\" , false , ' ' , - 1 ) ; AbstractAction decrFontAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { stnRender . decrFontSize ( ) ; redraw ( ) ; } } ; BAMutil . setActionProperties ( decrFontAction , \"FontDecr\" , \"decrease font size\" , false , ' ' , - 1 ) ; JCheckBox declutCB = new JCheckBox ( \"Declutter\" , true ) ; declutCB . addActionListener ( e -> { setDeclutter ( ( ( JCheckBox ) e . getSource ( ) ) . isSelected ( ) ) ; } ) ; AbstractAction bbAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { geoSelectionMode = ! geoSelectionMode ; np . setGeoSelectionMode ( geoSelectionMode ) ; redraw ( ) ; } } ; BAMutil . setActionProperties ( bbAction , \"geoselect\" , \"select geo region\" , true , ' ' , - 1 ) ; bbAction . putValue ( BAMutil . STATE , geoSelectionMode ? Boolean . TRUE : Boolean . FALSE ) ; // the fields use a PrefPanel if ( regionSelect ) { minmaxPP = new PrefPanel ( null , null ) ; minLonField = minmaxPP . addDoubleField ( \"minLon\" , \"minLon\" , geoSelection . getMinX ( ) , nfracDig , 0 , 0 , null ) ; maxLonField = minmaxPP . addDoubleField ( \"maxLon\" , \"maxLon\" , geoSelection . getMaxX ( ) , nfracDig , 2 , 0 , null ) ; minLatField = minmaxPP . addDoubleField ( \"minLat\" , \"minLat\" , geoSelection . getMinY ( ) , nfracDig , 4 , 0 , null ) ; maxLatField = minmaxPP . addDoubleField ( \"maxLat\" , \"maxLat\" , geoSelection . getMaxY ( ) , nfracDig , 6 , 0 , null ) ; minmaxPP . finish ( true , BorderLayout . EAST ) ; minmaxPP . addActionListener ( e -> { // \"Apply\" was called double minLon = minLonField . getDouble ( ) ; double minLat = minLatField . getDouble ( ) ; double maxLon = maxLonField . getDouble ( ) ; double maxLat = maxLatField . getDouble ( ) ; LatLonRect llbb = new LatLonRect ( new LatLonPointImpl ( minLat , minLon ) , new LatLonPointImpl ( maxLat , maxLon ) ) ; setGeoSelection ( llbb ) ; redraw ( ) ; } ) ; } // assemble setLayout ( new BorderLayout ( ) ) ; if ( stationSelect ) { BAMutil . addActionToContainer ( toolPanel , incrFontAction ) ; BAMutil . addActionToContainer ( toolPanel , decrFontAction ) ; toolPanel . add ( declutCB ) ; } if ( regionSelect ) BAMutil . addActionToContainer ( toolPanel , bbAction ) ; if ( dateSelect ) BAMutil . addActionToContainer ( toolPanel , dateAction ) ; JPanel upperPanel = new JPanel ( new BorderLayout ( ) ) ; if ( regionSelect ) upperPanel . add ( minmaxPP , BorderLayout . NORTH ) ; upperPanel . add ( toolPanel , BorderLayout . SOUTH ) ; JPanel statusPanel = new JPanel ( new BorderLayout ( ) ) ; statusPanel . setBorder ( new EtchedBorder ( ) ) ; JLabel positionLabel = new JLabel ( \"position\" ) ; statusPanel . add ( positionLabel , BorderLayout . CENTER ) ; np . setPositionLabel ( positionLabel ) ; add ( upperPanel , BorderLayout . NORTH ) ; add ( np , BorderLayout . CENTER ) ; add ( statusPanel , BorderLayout . SOUTH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the list of Stations . [CODESPLIT] public void setStations ( java . util . List stns ) { stnRender . setStations ( stns ) ; redraw ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks for the station with given id . If found makes it current . Redraws . [CODESPLIT] public void setSelectedStation ( String id ) { stnRender . setSelectedStation ( id ) ; selectedStation = stnRender . getSelectedStation ( ) ; assert selectedStation != null ; np . setLatLonCenterMapArea ( selectedStation . getLatitude ( ) , selectedStation . getLongitude ( ) ) ; redraw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Redraw the graphics on the screen . [CODESPLIT] protected void redraw ( ) { long tstart = System . currentTimeMillis ( ) ; java . awt . Graphics2D gNP = np . getBufferedImageGraphics ( ) ; if ( gNP == null ) // panel not drawn on screen yet return ; // clear it gNP . setBackground ( np . getBackgroundColor ( ) ) ; java . awt . Rectangle r = gNP . getClipBounds ( ) ; gNP . clearRect ( r . x , r . y , r . width , r . height ) ; if ( regionSelect && geoSelectionMode ) { if ( geoSelection != null ) drawBB ( gNP , geoSelection , Color . cyan ) ; if ( geoBounds != null ) drawBB ( gNP , geoBounds , null ) ; // System.out.println(\"GeoRegionChooser.redraw geoBounds= \"+geoBounds); if ( geoSelection != null ) { // gNP.setColor( Color.orange); Navigation navigate = np . getNavigation ( ) ; double handleSize = RubberbandRectangleHandles . handleSizePixels / navigate . getPixPerWorld ( ) ; Rectangle2D rect = new Rectangle2D . Double ( geoSelection . getX ( ) , geoSelection . getY ( ) , geoSelection . getWidth ( ) , geoSelection . getHeight ( ) ) ; RubberbandRectangleHandles . drawHandledRect ( gNP , rect , handleSize ) ; if ( debug ) System . out . println ( \"GeoRegionChooser.drawHandledRect=\" + handleSize + \" = \" + geoSelection ) ; } } for ( int i = 0 ; i < renderers . size ( ) ; i ++ ) { ucar . nc2 . ui . util . Renderer rend = ( Renderer ) renderers . get ( i ) ; rend . draw ( gNP , atI ) ; } gNP . dispose ( ) ; if ( debug ) { long tend = System . currentTimeMillis ( ) ; System . out . println ( \"StationRegionDateChooser draw time = \" + ( tend - tstart ) / 1000.0 + \" secs\" ) ; } // copy buffer to the screen np . repaint ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup needed for all SingleTrajectoryObsDatatypes . Can only be called once . [CODESPLIT] public void setTrajectoryInfo ( Config trajConfig ) throws IOException { if ( timeDim != null ) throw new IllegalStateException ( \"The setTrajectoryInfo() method can only be called once.\" ) ; this . trajectoryId = trajConfig . getTrajectoryId ( ) ; this . timeDim = trajConfig . getTimeDim ( ) ; this . timeVar = trajConfig . getTimeVar ( ) ; this . latVar = trajConfig . getLatVar ( ) ; this . lonVar = trajConfig . getLonVar ( ) ; this . elevVar = trajConfig . getElevVar ( ) ; trajectoryNumPoint = this . timeDim . getLength ( ) ; timeVarUnitsString = this . timeVar . findAttribute ( \"units\" ) . getStringValue ( ) ; // Check that time, lat, lon, elev units are acceptable. if ( DateUnit . getStandardDate ( timeVarUnitsString ) == null ) { throw new IllegalArgumentException ( \"Units of time variable <\" + timeVarUnitsString + \"> not a date unit.\" ) ; } String latVarUnitsString = this . latVar . findAttribute ( \"units\" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( latVarUnitsString , \"degrees_north\" ) ) { throw new IllegalArgumentException ( \"Units of lat var <\" + latVarUnitsString + \"> not compatible with \\\"degrees_north\\\".\" ) ; } String lonVarUnitsString = this . lonVar . findAttribute ( \"units\" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( lonVarUnitsString , \"degrees_east\" ) ) { throw new IllegalArgumentException ( \"Units of lon var <\" + lonVarUnitsString + \"> not compatible with \\\"degrees_east\\\".\" ) ; } String elevVarUnitsString = this . elevVar . findAttribute ( \"units\" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( elevVarUnitsString , \"meters\" ) ) { throw new IllegalArgumentException ( \"Units of elev var <\" + elevVarUnitsString + \"> not compatible with \\\"meters\\\".\" ) ; } try { elevVarUnitsConversionFactor = getMetersConversionFactor ( elevVarUnitsString ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Exception on getMetersConversionFactor() for the units of elev var <\" + elevVarUnitsString + \">.\" ) ; } if ( this . netcdfDataset . hasUnlimitedDimension ( ) && this . netcdfDataset . getUnlimitedDimension ( ) . equals ( timeDim ) ) { Object result = this . netcdfDataset . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ( result != null ) && ( Boolean ) result ) this . recordVar = ( Structure ) this . netcdfDataset . getRootGroup ( ) . findVariable ( \"record\" ) ; else this . recordVar = new StructurePseudo ( this . netcdfDataset , null , \"record\" , timeDim ) ; } else { this . recordVar = new StructurePseudo ( this . netcdfDataset , null , \"record\" , timeDim ) ; } // @todo HACK, HACK, HACK - remove once addRecordStructure() deals with ncd attribute changes. Variable elevVarInRecVar = this . recordVar . findVariable ( this . elevVar . getFullNameEscaped ( ) ) ; if ( ! elevVarUnitsString . equals ( elevVarInRecVar . findAttribute ( \"units\" ) . getStringValue ( ) ) ) { elevVarInRecVar . addAttribute ( new Attribute ( \"units\" , elevVarUnitsString ) ) ; } trajectoryVarsMap = new HashMap ( ) ; //for ( Iterator it = this.recordVar.getVariables().iterator(); it.hasNext(); ) for ( Iterator it = this . netcdfDataset . getRootGroup ( ) . getVariables ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Variable curVar = ( Variable ) it . next ( ) ; if ( curVar . getRank ( ) > 0 && ! curVar . equals ( this . timeVar ) && ! curVar . equals ( this . latVar ) && ! curVar . equals ( this . lonVar ) && ! curVar . equals ( this . elevVar ) && ( this . recordVar == null ? true : ! curVar . equals ( this . recordVar ) ) ) { MyTypedDataVariable typedVar = new MyTypedDataVariable ( new VariableDS ( null , curVar , true ) ) ; dataVariables . add ( typedVar ) ; trajectoryVarsMap . put ( typedVar . getShortName ( ) , typedVar ) ; } } trajectory = new SingleTrajectory ( this . trajectoryId , trajectoryNumPoint , this . timeVar , timeVarUnitsString , this . latVar , this . lonVar , this . elevVar , dataVariables , trajectoryVarsMap ) ; startDate = trajectory . getTime ( 0 ) ; endDate = trajectory . getTime ( trajectoryNumPoint - 1 ) ; ( ( SingleTrajectory ) trajectory ) . setStartDate ( startDate ) ; ( ( SingleTrajectory ) trajectory ) . setEndDate ( endDate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static methods [CODESPLIT] static public DapType lookup ( TypeSort atomic ) { if ( atomic == TypeSort . Enum ) return null ; // we need more info return typemap . get ( atomic ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] @ Override public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; double fromLat_r = Math . toRadians ( fromLat ) ; // infinite projection\r if ( ( Math . abs ( 90.0 - Math . abs ( fromLat ) ) ) < TOLERANCE ) { toX = Double . POSITIVE_INFINITY ; toY = Double . POSITIVE_INFINITY ; } else { toX = A * Math . toRadians ( LatLonPointImpl . range180 ( fromLon - this . lon0 ) ) ; toY = A * SpecialMathFunction . atanh ( Math . sin ( fromLat_r ) ) ; // p 41 Snyder\r } result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] @ Override public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double toLon = Math . toDegrees ( fromX / A ) + lon0 ; double e = Math . exp ( - fromY / A ) ; double toLat = Math . toDegrees ( Math . PI / 2 - 2 * Math . atan ( e ) ) ; // Snyder p 44\r result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( Catalog catalog , OutputStream os , boolean raw ) throws IOException { this . raw = raw ; writeXML ( catalog , os ) ; this . raw = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( Catalog catalog , OutputStream os ) throws IOException { // Output the document, use standard formatter //XMLOutputter fmt = new XMLOutputter(); //fmt.setNewlines(true); //fmt.setIndent(\"  \"); //fmt.setTrimAllWhite( true); XMLOutputter fmt = new XMLOutputter ( org . jdom2 . output . Format . getPrettyFormat ( ) ) ; // LOOK maybe compact ?? fmt . output ( writeCatalog ( catalog ) , os ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * protected void writeCat6InheritedMetadata ( Element elem ThreddsMetadata tmi ) { if (( tmi . getDataType () == null ) && ( tmi . getServiceName () == null ) && ( tmi . getAuthority () == null ) && ( tmi . getProperties () . size () == 0 )) return ; [CODESPLIT] protected void writeInheritedMetadata ( Element elem , Dataset ds ) { Element mdataElem = new Element ( \"metadata\" , Catalog . defNS ) ; mdataElem . setAttribute ( \"inherited\" , \"true\" ) ; ThreddsMetadata tmi = ( ThreddsMetadata ) ds . getLocalField ( Dataset . ThreddsMetadataInheritable ) ; if ( tmi == null ) return ; writeThreddsMetadata ( mdataElem , tmi ) ; if ( mdataElem . getChildren ( ) . size ( ) > 0 ) elem . addContent ( mdataElem ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a <code > Rectangle2D< / code > object to this <code > Rectangle2D< / code > . The resulting <code > Rectangle2D< / code > is the union of the two <code > Rectangle2D< / code > objects . [CODESPLIT] public void add ( ProjectionRect r ) { double x1 = Math . min ( getMinX ( ) , r . getMinX ( ) ) ; double x2 = Math . max ( getMaxX ( ) , r . getMaxX ( ) ) ; double y1 = Math . min ( getMinY ( ) , r . getMinY ( ) ) ; double y2 = Math . max ( getMaxY ( ) , r . getMaxY ( ) ) ; setRect ( x1 , y1 , x2 - x1 , y2 - y1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a point specified by the double precision arguments <code > newx< / code > and <code > newy< / code > to this <code > Rectangle2D< / code > . The resulting <code > Rectangle2D< / code > is the smallest <code > Rectangle2D< / code > that contains both the original <code > Rectangle2D< / code > and the specified point . <p > After adding a point a call to <code > contains< / code > with the added point as an argument does not necessarily return <code > true< / code > . The <code > contains< / code > method does not return <code > true< / code > for points on the right or bottom edges of a rectangle . Therefore if the added point falls on the left or bottom edge of the enlarged rectangle <code > contains< / code > returns <code > false< / code > for that point . [CODESPLIT] public void add ( double newx , double newy ) { double x1 = Math . min ( getMinX ( ) , newx ) ; double x2 = Math . max ( getMaxX ( ) , newx ) ; double y1 = Math . min ( getMinY ( ) , newy ) ; double y2 = Math . max ( getMaxY ( ) , newy ) ; setRect ( x1 , y1 , x2 - x1 , y2 - y1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Intersects the pair of specified source <code > Rectangle2D< / code > objects and puts the result into the specified destination <code > Rectangle2D< / code > object . One of the source rectangles can also be the destination to avoid creating a third Rectangle2D object but in this case the original points of this source rectangle will be overwritten by this method . [CODESPLIT] public static void intersect ( ProjectionRect src1 , ProjectionRect src2 , ProjectionRect dest ) { double x1 = Math . max ( src1 . getMinX ( ) , src2 . getMinX ( ) ) ; double y1 = Math . max ( src1 . getMinY ( ) , src2 . getMinY ( ) ) ; double x2 = Math . min ( src1 . getMaxX ( ) , src2 . getMaxX ( ) ) ; double y2 = Math . min ( src1 . getMaxY ( ) , src2 . getMaxY ( ) ) ; dest . setRect ( x1 , y1 , x2 - x1 , y2 - y1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if this bounding box contains { @code point } . [CODESPLIT] public boolean contains ( ProjectionPoint point ) { return DoubleMath . fuzzyCompare ( point . getX ( ) , getMinX ( ) , 1e-6 ) >= 0 && DoubleMath . fuzzyCompare ( point . getX ( ) , getMaxX ( ) , 1e-6 ) <= 0 && DoubleMath . fuzzyCompare ( point . getY ( ) , getMinY ( ) , 1e-6 ) >= 0 && DoubleMath . fuzzyCompare ( point . getY ( ) , getMaxY ( ) , 1e-6 ) <= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the object from the input stream of the serialized object [CODESPLIT] private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { double x = s . readDouble ( ) ; double y = s . readDouble ( ) ; double w = s . readDouble ( ) ; double h = s . readDouble ( ) ; setRect ( x , y , w , h ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrtie the object to the output stream [CODESPLIT] private void writeObject ( ObjectOutputStream s ) throws IOException { s . writeDouble ( getX ( ) ) ; s . writeDouble ( getY ( ) ) ; s . writeDouble ( getWidth ( ) ) ; s . writeDouble ( getHeight ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if this rectangle is nearly equal to { @code other } . The near equality of corners is determined using { @link ProjectionPoint#nearlyEquals ( ProjectionPoint double ) } with the specified maxRelDiff . [CODESPLIT] public boolean nearlyEquals ( ProjectionRect other , double maxRelDiff ) { return this . getLowerLeftPoint ( ) . nearlyEquals ( other . getLowerLeftPoint ( ) , maxRelDiff ) && this . getUpperRightPoint ( ) . nearlyEquals ( other . getUpperRightPoint ( ) , maxRelDiff ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all the entries in another UnitDBImpl to this database . [CODESPLIT] public void add ( final UnitDBImpl that ) throws UnitExistsException { unitSet . addAll ( that . unitSet ) ; nameMap . putAll ( that . nameMap ) ; symbolMap . putAll ( that . symbolMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a unit to the database . [CODESPLIT] public void addUnit ( final Unit unit ) throws UnitExistsException , NameException { if ( unit . getName ( ) == null ) { throw new NameException ( \"Unit name can't be null\" ) ; } addByName ( unit . getName ( ) , unit ) ; addByName ( unit . getPlural ( ) , unit ) ; addBySymbol ( unit . getSymbol ( ) , unit ) ; unitSet . add ( unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an alias for a unit already in the database . [CODESPLIT] public final void addAlias ( final String alias , final String name ) throws NoSuchUnitException , UnitExistsException { addAlias ( alias , name , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a symbol for a unit already in the database . [CODESPLIT] public final void addSymbol ( final String symbol , final String name ) throws NoSuchUnitException , UnitExistsException { addAlias ( null , name , symbol , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an alias for a unit already in the database . [CODESPLIT] public final void addAlias ( final String alias , final String name , final String symbol , final String plural ) throws NoSuchUnitException , UnitExistsException { addAlias ( UnitID . newUnitID ( alias , plural , symbol ) , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an alias for a unit already in the database . [CODESPLIT] public final void addAlias ( final UnitID alias , final String name ) throws NoSuchUnitException , UnitExistsException { final Unit unit = getByName ( name ) ; if ( unit == null ) { throw new NoSuchUnitException ( name ) ; } addByName ( alias . getName ( ) , unit ) ; addByName ( alias . getPlural ( ) , unit ) ; addBySymbol ( alias . getSymbol ( ) , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a unit by either name plural or symbol . Retrieving the unit by symbol is attempted before retrieving the unit by name because symbol comparisons are case sensitive and hence should be more robust . [CODESPLIT] public Unit get ( final String id ) { Unit unit = getBySymbol ( id ) ; if ( unit == null ) { unit = getByName ( id ) ; } return unit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a unit to the database by name . [CODESPLIT] private final void addByName ( final String name , final Unit newUnit ) throws UnitExistsException { if ( name != null ) { addUnique ( nameMap , canonicalize ( name ) , newUnit ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a unit to the database by symbol . [CODESPLIT] private final void addBySymbol ( final String symbol , final Unit newUnit ) throws UnitExistsException { if ( symbol != null ) { addUnique ( symbolMap , symbol , newUnit ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a unique unit to a map .. [CODESPLIT] private static final void addUnique ( final Map < String , Unit > map , final String key , final Unit newUnit ) throws UnitExistsException { final Unit oldUnit = map . put ( key , newUnit ) ; if ( oldUnit != null && ! oldUnit . equals ( newUnit ) ) { throw new UnitExistsException ( oldUnit , newUnit ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// [CODESPLIT] protected void buildFileList ( Root rootinfo ) throws DapException { File root = new File ( rootinfo . getFullPath ( ) ) ; if ( ! root . isDirectory ( ) ) throw new DapException ( \"FrontPage: specified root directory is not a directory: \" + rootinfo . getFullPath ( ) ) ; if ( ! root . canRead ( ) ) throw new DapException ( \"FrontPage: specified root directory is not readable: \" + rootinfo . getFullPath ( ) ) ; // take files from set of files immediately under root File [ ] candidates = root . listFiles ( ) ; List < FileSource > activesources = new ArrayList < FileSource > ( ) ; // Capture lists of files for each FileSource for ( FileSource src : SOURCES ) { List < File > matches = new ArrayList < File > ( ) ; for ( File candidate : candidates ) { String name = candidate . getName ( ) ; boolean excluded = false ; for ( String exclude : expatterns ) { if ( name . indexOf ( exclude ) >= 0 ) { excluded = true ; break ; } } if ( excluded ) continue ; if ( ! name . endsWith ( src . ext ) ) continue ; if ( ! candidate . canRead ( ) ) { DapLog . info ( \"FrontPage: file not readable: \" + candidate ) ; continue ; } matches . add ( candidate ) ; } if ( matches . size ( ) > 0 ) { // Sort the set of files matches . sort ( new Comparator < File > ( ) { public int compare ( File f1 , File f2 ) { return f1 . getName ( ) . compareTo ( f2 . getName ( ) ) ; } } ) ; if ( DUMPFILELIST ) { for ( File x : matches ) { System . err . printf ( \"file: %s/%s%n\" , rootinfo . prefix , x . getName ( ) ) ; } } FileSource clone = new FileSource ( src . ext , src . tag ) ; clone . files = matches ; activesources . add ( clone ) ; } } rootinfo . setFiles ( activesources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a set of MenuItems to the given JMenu one for each possible L&F . if this platform doesnt support the L&F disable the MenuItem . [CODESPLIT] public void addToMenu ( final JMenu menu ) { final UIManager . LookAndFeelInfo [ ] plafInfo = UIManager . getInstalledLookAndFeels ( ) ; for ( UIManager . LookAndFeelInfo aPlafInfo : plafInfo ) { addToMenu ( aPlafInfo . getName ( ) , aPlafInfo . getClassName ( ) , menu ) ; } final LookAndFeel current = UIManager . getLookAndFeel ( ) ; System . out . printf ( \"current L&F=%s%n\" , current . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * C ++ implementation static bool name_is_global ( string &name ) { static Regex global ( \\\\ ( . * global . * \\\\ ) \\\\ | \\\\ ( . * opendap . * \\\\ ) 1 ) ; downcase ( name ) ; return global . match ( name . c_str () name . length () ) ! = - 1 ; } [CODESPLIT] public static boolean nameIsGlobal ( String name ) { String lcName = name . toLowerCase ( ) ; boolean global = false ; if ( lcName . indexOf ( \"global\" ) >= 0 ) global = true ; if ( lcName . indexOf ( \"dods\" ) >= 0 ) global = true ; //System.out.println(\"nameIsGlobal(): \"+global);\r return ( global ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [CODESPLIT] public static String fancyTypeName ( BaseType bt ) { if ( bt instanceof DByte ) return ( \"8 bit Byte\" ) ; if ( bt instanceof DUInt16 ) return ( \"16 bit Unsigned Integer\" ) ; if ( bt instanceof DInt16 ) return ( \"16 bit Integer\" ) ; if ( bt instanceof DUInt32 ) return ( \"32 bit Unsigned Integer\" ) ; if ( bt instanceof DInt32 ) return ( \"32 bit Integer\" ) ; if ( bt instanceof DFloat32 ) return ( \"32 bit Real\" ) ; if ( bt instanceof DFloat64 ) return ( \"64 bit Real\" ) ; if ( bt instanceof DURL ) return ( \"URL\" ) ; if ( bt instanceof DString ) return ( \"String\" ) ; if ( bt instanceof DArray ) { DArray a = ( DArray ) bt ; StringBuilder type = new StringBuilder ( ) ; type . append ( \"Array of \" ) ; type . append ( fancyTypeName ( a . getPrimitiveVector ( ) . getTemplate ( ) ) ) ; type . append ( \"s \" ) ; Enumeration e = a . getDimensions ( ) ; while ( e . hasMoreElements ( ) ) { DArrayDimension dad = ( DArrayDimension ) e . nextElement ( ) ; type . append ( \"[\" ) ; type . append ( dad . getEncodedName ( ) ) ; type . append ( \" = 0..\" ) ; type . append ( dad . getSize ( ) - 1 ) ; type . append ( \"]\" ) ; } type . append ( \"\\n\" ) ; return ( type . toString ( ) ) ; } if ( bt instanceof DStructure ) return ( \"Structure\" ) ; if ( bt instanceof DSequence ) return ( \"Sequence\" ) ; if ( bt instanceof DGrid ) return ( \"Grid\" ) ; return ( \"UNKNOWN\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tricky bit of business . recapture the entire record based on drs position . for validation . [CODESPLIT] @ Nullable public static Grib2Record findRecordByDrspos ( RandomAccessFile raf , long drsPos ) throws IOException { long pos = Math . max ( 0 , drsPos - ( 20 * 1000 ) ) ; // go back 20K\r Grib2RecordScanner scan = new Grib2RecordScanner ( raf , pos ) ; while ( scan . hasNext ( ) ) { ucar . nc2 . grib . grib2 . Grib2Record gr = scan . next ( ) ; Grib2SectionDataRepresentation drs = gr . getDataRepresentationSection ( ) ; if ( drsPos == drs . getStartingPosition ( ) ) return gr ; if ( raf . getFilePointer ( ) > drsPos ) break ; // missed it.\r } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "side effect is that the new record is in repeatRecord [CODESPLIT] private boolean nextRepeating ( ) throws IOException { raf . seek ( repeatPos ) ; GribNumbers . int4 ( raf ) ; // skip octets 1-4\r int section = raf . read ( ) ; // find out what section this is\r raf . seek ( repeatPos ) ; // back to beginning of section\r if ( section == 2 ) { repeatRecord . setLus ( new Grib2SectionLocalUse ( raf ) ) ; repeatRecord . setGdss ( new Grib2SectionGridDefinition ( raf ) ) ; repeatRecord . setPdss ( new Grib2SectionProductDefinition ( raf ) ) ; repeatRecord . setDrs ( new Grib2SectionDataRepresentation ( raf ) ) ; repeatRecord . setBms ( new Grib2SectionBitMap ( raf ) , false ) ; repeatRecord . setDataSection ( new Grib2SectionData ( raf ) ) ; repeatRecord . repeat = section ; } else if ( section == 3 ) { repeatRecord . setGdss ( new Grib2SectionGridDefinition ( raf ) ) ; repeatRecord . setPdss ( new Grib2SectionProductDefinition ( raf ) ) ; repeatRecord . setDrs ( new Grib2SectionDataRepresentation ( raf ) ) ; repeatRecord . setBms ( new Grib2SectionBitMap ( raf ) , false ) ; repeatRecord . setDataSection ( new Grib2SectionData ( raf ) ) ; repeatRecord . repeat = section ; } else if ( section == 4 ) { repeatRecord . setPdss ( new Grib2SectionProductDefinition ( raf ) ) ; repeatRecord . setDrs ( new Grib2SectionDataRepresentation ( raf ) ) ; repeatRecord . setBms ( new Grib2SectionBitMap ( raf ) , false ) ; repeatRecord . setDataSection ( new Grib2SectionData ( raf ) ) ; repeatRecord . repeat = section ; } else { if ( debugRepeat ) logger . debug ( \" REPEAT Terminate %d%n\" , section ) ; lastPos = repeatPos ; // start next scan from here\r repeatPos = - 1 ; repeatRecord = null ; repeatBms = null ; return false ; } // look for repeating bms\r Grib2SectionBitMap bms = repeatRecord . getBitmapSection ( ) ; if ( bms . getBitMapIndicator ( ) == 254 ) { // replace BMS with last good one\r if ( repeatBms == null ) throw new IllegalStateException ( \"No bms in repeating section\" ) ; repeatRecord . setBms ( repeatBms , true ) ; //debug\r if ( debugRepeat ) logger . debug ( \"replaced bms %d%n\" , section ) ; repeatRecord . repeat += 1000 ; } else if ( bms . getBitMapIndicator ( ) == 0 ) { // track last good bms\r repeatBms = repeatRecord . getBitmapSection ( ) ; } // keep only unique gds\r if ( ( section == 2 ) || ( section == 3 ) ) { // look for duplicate gds\r Grib2SectionGridDefinition gds = repeatRecord . getGDSsection ( ) ; long crc = gds . calcCRC ( ) ; Grib2SectionGridDefinition gdsCached = gdsMap . get ( crc ) ; if ( gdsCached != null ) repeatRecord . setGdss ( gdsCached ) ; else gdsMap . put ( crc , gds ) ; } // check to see if we are at the end\r long pos = raf . getFilePointer ( ) ; long ending = repeatRecord . getIs ( ) . getEndPos ( ) ; if ( pos + 34 < ending ) { // give it 30 bytes of slop\r if ( debugRepeat ) logger . debug ( \" REPEAT AGAIN %d != %d%n\" , pos + 4 , ending ) ; repeatPos = pos ; return true ; } if ( debug ) logger . debug ( \" REPEAT read until %d grib ending at %d header ='%s'%n\" , raf . getFilePointer ( ) , ending , StringUtil2 . cleanup ( header ) ) ; // check that end section is correct\r raf . seek ( ending - 4 ) ; for ( int i = 0 ; i < 4 ; i ++ ) { if ( raf . read ( ) != 55 ) { String clean = StringUtil2 . cleanup ( header ) ; if ( clean . length ( ) > 40 ) clean = clean . substring ( 0 , 40 ) + \"...\" ; logger . warn ( \"  REPEAT Missing End of GRIB message at pos=\" + ending + \" header= \" + clean + \" for=\" + raf . getLocation ( ) ) ; break ; } } lastPos = raf . getFilePointer ( ) ; if ( debugRepeat ) logger . debug ( \" REPEAT DONE%n\" ) ; repeatPos = - 1 ; // no more repeats in this record\r return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called if its scalar [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws NoSuchVariableException , IOException { // read the scalar structure into memory StructureData sdata = ncVar . readStructure ( ) ; setData ( sdata ) ; return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK - should modify to use hasNetcdf . setData ( StructureData ) for efficiency [CODESPLIT] public void setData ( StructureData sdata ) { int count = 0 ; StructureMembers sm = sdata . getStructureMembers ( ) ; java . util . Enumeration vars = getVariables ( ) ; while ( vars . hasMoreElements ( ) ) { // loop through both structures HasNetcdfVariable hasNetcdf = ( HasNetcdfVariable ) vars . nextElement ( ) ; StructureMembers . Member m = sm . getMember ( count ++ ) ; // extract the data and set it into the dods object Array data = sdata . getArray ( m ) ; hasNetcdf . setData ( data ) ; } setRead ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "overrride for array of Structures [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { if ( org == null ) { super . serialize ( dataset , sink , ce , specialO ) ; return ; } // use the projection info in the original java . util . Enumeration vars = org . getVariables ( ) ; // run through each structure member StructureMembers sm = sdata . getStructureMembers ( ) ; int count = 0 ; while ( vars . hasMoreElements ( ) ) { HasNetcdfVariable sm_org = ( HasNetcdfVariable ) vars . nextElement ( ) ; boolean isProjected = ( ( ServerMethods ) sm_org ) . isProject ( ) ; if ( isProjected ) { StructureMembers . Member m = sm . getMember ( count ) ; sm_org . serialize ( sink , sdata , m ) ; } count ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the unpacked data values for a selected parameter . [CODESPLIT] public float [ ] getParamValues ( DoradeRDAT rdat , float [ ] workingArray ) throws DescriptorException { if ( ! paramName . equals ( rdat . getParamName ( ) ) ) throw new DescriptorException ( \"parameter name mismatch\" ) ; byte [ ] paramData = rdat . getRawData ( ) ; int nCells = myRADD . getNCells ( ) ; float [ ] values ; if ( workingArray != null && workingArray . length == nCells ) { values = workingArray ; } else { values = new float [ nCells ] ; } short [ ] svalues = null ; if ( myRADD . getCompressionScheme ( ) == DoradeRADD . COMPRESSION_HRD ) { if ( binaryFormat != DoradePARM . FORMAT_16BIT_INT ) { throw new DescriptorException ( \"Cannot unpack \" + \"compressed data with binary format \" + binaryFormat ) ; } svalues = uncompressHRD ( paramData , nCells ) ; } for ( int cell = 0 ; cell < nCells ; cell ++ ) { switch ( binaryFormat ) { case DoradePARM . FORMAT_8BIT_INT : byte bval = paramData [ cell ] ; values [ cell ] = ( bval == badDataFlag ) ? BAD_VALUE : ( bval - bias ) / scale ; break ; case DoradePARM . FORMAT_16BIT_INT : short sval = ( svalues != null ) ? svalues [ cell ] : grabShort ( paramData , 2 * cell ) ; values [ cell ] = ( sval == badDataFlag ) ? BAD_VALUE : ( sval - bias ) / scale ; break ; case DoradePARM . FORMAT_32BIT_INT : int ival = grabInt ( paramData , 4 * cell ) ; values [ cell ] = ( ival == badDataFlag ) ? BAD_VALUE : ( ival - bias ) / scale ; break ; case DoradePARM . FORMAT_32BIT_FLOAT : float fval = grabFloat ( paramData , 4 * cell ) ; values [ cell ] = ( fval == badDataFlag ) ? BAD_VALUE : ( fval - bias ) / scale ; break ; case DoradePARM . FORMAT_16BIT_FLOAT : throw new DescriptorException ( \"can't unpack 16-bit \" + \"float data yet\" ) ; default : throw new DescriptorException ( \"bad binary format (\" + binaryFormat + \")\" ) ; } } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack MIT / HRD - compressed data into an array of exactly nCells shorts . [CODESPLIT] private short [ ] uncompressHRD ( byte [ ] compressedData , int nCells ) throws DescriptorException { short [ ] svalues = new short [ nCells ] ; int cPos = 0 ; // position in the compressed data, in bytes int nextCell = 0 ; int runLength ; for ( ; ; nextCell += runLength ) { // // Each run begins with a 16-bin run descriptor.  The // high order bit is set if the run consists of bad flags. // The remaining 15 bits tell the length of the run. // A run length of 1 indicates the end of compressed data. // short runDescriptor = grabShort ( compressedData , cPos ) ; cPos += 2 ; boolean runHasGoodValues = ( ( runDescriptor & 0x8000 ) != 0 ) ; runLength = runDescriptor & 0x7fff ; if ( runLength == 1 ) break ; // // Sanity check on run length // if ( ( nextCell + runLength ) > nCells ) throw new DescriptorException ( \"attempt to unpack \" + \"too many cells\" ) ; // // If the run contains good values, then the next runLength // values in the compressed data stream are real values.  Otherwise // we need to fill with runLength bad value flags. // for ( int cell = nextCell ; cell < nextCell + runLength ; cell ++ ) { if ( runHasGoodValues ) { svalues [ cell ] = grabShort ( compressedData , cPos ) ; cPos += 2 ; } else { svalues [ cell ] = ( short ) badDataFlag ; } } } // // Fill the remainder of the array (if any) with bad value flags // for ( int cell = nextCell ; cell < nCells ; cell ++ ) svalues [ cell ] = ( short ) badDataFlag ; return svalues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "map limit circle of this radius from the origin p 173 [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new VerticalPerspectiveView ( getOriginLat ( ) , getOriginLon ( ) , R , getHeight ( ) , false_east , false_north ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Precalculate some stuff [CODESPLIT] private void precalculate ( ) { sinLat0 = Math . sin ( lat0 ) ; cosLat0 = Math . cos ( lat0 ) ; lon0Degrees = Math . toDegrees ( lon0 ) ; P = 1.0 + H / R ; // \"map limit\" circle of this radius from the origin, p 173\r maxR = .99 * R * Math . sqrt ( ( P - 1 ) / ( P + 1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double cosc = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double ksp = ( P - 1.0 ) / ( P - cosc ) ; if ( cosc < 1.0 / P ) { toX = Double . POSITIVE_INFINITY ; toY = Double . POSITIVE_INFINITY ; } else { toX = false_east + R * ksp * Math . cos ( fromLat ) * Math . sin ( lonDiff ) ; toY = false_north + R * ksp * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) ; } result . setLocation ( toX , toY ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) ; double fromY = world . getY ( ) ; fromX = fromX - false_east ; fromY = fromY - false_north ; double rho = Math . sqrt ( fromX * fromX + fromY * fromY ) ; double r = rho / R ; double con = P - 1.0 ; double com = P + 1.0 ; double c = Math . asin ( ( P - Math . sqrt ( 1.0 - ( r * r * com ) / con ) ) / ( con / r + r / con ) ) ; toLon = lon0 ; double temp = 0 ; if ( Math . abs ( rho ) > TOLERANCE ) { toLat = Math . asin ( Math . cos ( c ) * sinLat0 + ( fromY * Math . sin ( c ) * cosLat0 / rho ) ) ; if ( Math . abs ( lat0 - PI_OVER_4 ) > TOLERANCE ) { // not 90 or -90\r temp = rho * cosLat0 * Math . cos ( c ) - fromY * sinLat0 * Math . sin ( c ) ; toLon = lon0 + Math . atan ( fromX * Math . sin ( c ) / temp ) ; } else if ( Double . compare ( lat0 , PI_OVER_4 ) == 0 ) { toLon = lon0 + Math . atan ( fromX / - fromY ) ; temp = - fromY ; } else { toLon = lon0 + Math . atan ( fromX / fromY ) ; temp = fromY ; } } else { toLat = lat0 ; } toLat = Math . toDegrees ( toLat ) ; toLon = Math . toDegrees ( toLon ) ; if ( temp < 0 ) { toLon += 180 ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double cosc = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double ksp = ( P - 1.0 ) / ( P - cosc ) ; if ( cosc < 1.0 / P ) { toX = Double . POSITIVE_INFINITY ; toY = Double . POSITIVE_INFINITY ; } else { toX = false_east + R * ksp * Math . cos ( fromLat ) * Math . sin ( lonDiff ) ; toY = false_north + R * ksp * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) ; } resultXA [ i ] = ( float ) toX ; resultYA [ i ] = ( float ) toY ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <GRIB2_22_0_0_Template_en > <No > 1451< / No > <Title_en > Product definition template 4 . 55 - spatio - temporal changing tiles at a horizontal level or horizontal layer at a point in time< / Title_en > <OctetNo > 35< / OctetNo > <Contents_en > Type of second fixed surface< / Contents_en > <Note_en > ( see Code table 4 . 5 ) < / Note_en > <Status > Operational< / Status > < / GRIB2_22_0_0_Template_en > [CODESPLIT] private void readXml ( Version version ) throws IOException { try ( InputStream ios = WmoTemplateTables . class . getResourceAsStream ( version . getResourceName ( ) ) ) { if ( ios == null ) { throw new IOException ( \"cant open TemplateTable %s \" + version . getResourceName ( ) ) ; } org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( ios ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } Map < String , TemplateTable > map = new HashMap <> ( ) ; String [ ] elems = version . getElemNames ( ) ; assert elems != null ; assert elems . length > 3 ; Element root = doc . getRootElement ( ) ; List < Element > featList = root . getChildren ( elems [ 0 ] ) ; // 0 = main element\r for ( Element elem : featList ) { String desc = elem . getChildTextNormalize ( elems [ 1 ] ) ; // 1 = title\r String octet = elem . getChildTextNormalize ( \"OctetNo\" ) ; String content = elem . getChildTextNormalize ( elems [ 3 ] ) ; // 3 = content\r String status = elem . getChildTextNormalize ( \"Status\" ) ; String note = elem . getChildTextNormalize ( elems [ 2 ] ) ; // 2 == note\r TemplateTable template = map . computeIfAbsent ( desc , name -> new TemplateTable ( name ) ) ; template . add ( octet , content , status , note ) ; } ios . close ( ) ; List < TemplateTable > tlist = new ArrayList <> ( map . values ( ) ) ; for ( TemplateTable t : tlist ) { if ( t . m1 == 3 ) { t . add ( 1 , 4 , \"GDS length\" ) ; t . add ( 5 , 1 , \"Section\" ) ; t . add ( 6 , 1 , \"Source of Grid Definition (see code table 3.0)\" ) ; t . add ( 7 , 4 , \"Number of data points\" ) ; t . add ( 11 , 1 , \"Number of octects for optional list of numbers\" ) ; t . add ( 12 , 1 , \"Interpretation of list of numbers\" ) ; t . add ( 13 , 2 , \"Grid Definition Template Number\" ) ; } else if ( t . m1 == 4 ) { t . add ( 1 , 4 , \"PDS length\" ) ; t . add ( 5 , 1 , \"Section\" ) ; t . add ( 6 , 2 , \"Number of coordinates values after Template\" ) ; t . add ( 8 , 2 , \"Product Definition Template Number\" ) ; } Collections . sort ( t . flds ) ; } this . templateTables = map . values ( ) . stream ( ) . sorted ( ) . collect ( ImmutableList . toImmutableList ( ) ) ; ImmutableMap . Builder < String , TemplateTable > builder = ImmutableMap . builder ( ) ; map . values ( ) . forEach ( t -> builder . put ( t . getId ( ) , t ) ) ; this . templateMap = builder . build ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Find station that contains this point . If it exists make it the selected station . @param pickPt : world coordinates @return station that contains this point or null if none . [CODESPLIT] public void draw ( java . awt . Graphics2D g , java . awt . geom . AffineTransform normal2Device ) { if ( ( project == null ) || ! posWasCalc ) return ; // use world coordinates for position, but draw in screen coordinates\r // so that the symbols stay the same size\r AffineTransform world2Device = g . getTransform ( ) ; g . setTransform ( normal2Device ) ; //  identity transform for screen coords\r // transform World to Normal coords:\r //    world2Normal = pixelAT-1 * world2Device\r // cache for pick closest\r AffineTransform world2Normal ; try { world2Normal = normal2Device . createInverse ( ) ; world2Normal . concatenate ( world2Device ) ; } catch ( java . awt . geom . NoninvertibleTransformException e ) { System . out . println ( \" RendSurfObs: NoninvertibleTransformException on \" + normal2Device ) ; return ; } // we want aliasing; but save previous state to restore at end\r Object saveHint = g . getRenderingHint ( RenderingHints . KEY_ANTIALIASING ) ; //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\r //    RenderingHints.VALUE_ANTIALIAS_ON);\r g . setStroke ( new java . awt . BasicStroke ( 1.0f ) ) ; /* set up the grid\r\n    Rectangle2D bbox = (Rectangle2D) g.getClip(); // clipping area in normal coords\r\n    // clear the grid = \"no stations are drawn\"\r\n    stationGrid.clear();\r\n    // set the grid size based on typical bounding box\r\n    stationGrid.setGrid(bbox, typicalBB.getWidth(), typicalBB.getHeight());\r\n\r\n\r\n    // always draw selected\r\n    if (selected != null) {\r\n      selected.calcPos( world2Normal);\r\n      stationGrid.markIfClear( selected.getBB(), selected);\r\n      selected.draw(g);\r\n    } */ g . setFont ( textFont . getFont ( ) ) ; g . setColor ( color ) ; int count = 0 ; int npts = obsUIlist . size ( ) ; GeneralPath path = new GeneralPath ( GeneralPath . WIND_EVEN_ODD , npts ) ; for ( int i = 0 ; i < npts ; i ++ ) { ObservationUI s = ( ObservationUI ) obsUIlist . get ( i ) ; s . calcPos ( world2Normal ) ; s . draw ( g ) ; if ( Double . isNaN ( s . screenPos . getX ( ) ) ) { System . out . println ( \"screenPos=\" + s . screenPos + \" world = \" + s . worldPos ) ; continue ; } if ( count == 0 ) path . moveTo ( ( float ) s . screenPos . getX ( ) , ( float ) s . screenPos . getY ( ) ) ; else path . lineTo ( ( float ) s . screenPos . getX ( ) , ( float ) s . screenPos . getY ( ) ) ; count ++ ; } g . setColor ( color ) ; if ( drawConnectingLine ) g . draw ( path ) ; // draw selected\r if ( selected != null ) selected . draw ( g ) ; // restore\r g . setTransform ( world2Device ) ; g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , saveHint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a FeatureDataset from a URL location string . Example URLS : <ul > <li > http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : file : c : / test / data / catalog / addeStationDataset . xml#AddeSurfaceData ( absolute file ) <li > thredds : resolve : resolveURL < / ul > [CODESPLIT] public ThreddsDataFactory . Result openFeatureDataset ( String urlString , ucar . nc2 . util . CancelTask task ) throws IOException { ThreddsDataFactory . Result result = new ThreddsDataFactory . Result ( ) ; InvDataset invDataset = processLocation ( urlString , task , result ) ; if ( result . fatalError ) return result ; return openFeatureDataset ( null , invDataset , task , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a FeatureDataset from an InvDataset object deciding on which InvAccess to use . [CODESPLIT] public ThreddsDataFactory . Result openFeatureDataset ( InvDataset invDataset , ucar . nc2 . util . CancelTask task ) throws IOException { return openFeatureDataset ( null , invDataset , task , new Result ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a FeatureDataset from an InvAccess object . [CODESPLIT] public ThreddsDataFactory . Result openFeatureDataset ( InvAccess access , ucar . nc2 . util . CancelTask task ) throws IOException { InvDataset invDataset = access . getDataset ( ) ; ThreddsDataFactory . Result result = new Result ( ) ; if ( invDataset . getDataType ( ) == null ) { result . errLog . format ( \"InvDatasert must specify a FeatureType%n\" ) ; result . fatalError = true ; return result ; } return openFeatureDataset ( invDataset . getDataType ( ) , access , task , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to open as a NetcdfDataset . [CODESPLIT] public NetcdfDataset openDataset ( InvDataset invDataset , boolean acquire , ucar . nc2 . util . CancelTask task , Formatter log ) throws IOException { Result result = new Result ( ) ; NetcdfDataset ncd = openDataset ( invDataset , acquire , task , result ) ; if ( log != null ) log . format ( \"%s\" , result . errLog ) ; return ( result . fatalError ) ? null : ncd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the best access in case theres more than one based on what the CDM knows how to open and use . [CODESPLIT] public InvAccess chooseDatasetAccess ( List < InvAccess > accessList ) { if ( accessList . size ( ) == 0 ) return null ; InvAccess access = null ; if ( preferAccess != null ) { for ( ServiceType type : preferAccess ) { access = findAccessByServiceType ( accessList , type ) ; if ( access != null ) break ; } } // the order indicates preference if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . CdmRemote ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DODS ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . OPENDAP ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DAP4 ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . FILE ) ; // should mean that it can be opened through netcdf API if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . NETCDF ) ; //  ServiceType.NETCDF is deprecated, use FILE // look for HTTP with format we can read if ( access == null ) { InvAccess tryAccess = findAccessByServiceType ( accessList , ServiceType . HTTPServer ) ; if ( tryAccess == null ) tryAccess = findAccessByServiceType ( accessList , ServiceType . HTTP ) ; //  ServiceType.HTTP should be HTTPServer if ( tryAccess != null ) { DataFormatType format = tryAccess . getDataFormatType ( ) ; // these are the file types we can read if ( ( DataFormatType . BUFR == format ) || ( DataFormatType . GINI == format ) || ( DataFormatType . GRIB1 == format ) || ( DataFormatType . GRIB2 == format ) || ( DataFormatType . HDF5 == format ) || ( DataFormatType . NCML == format ) || ( DataFormatType . NETCDF == format ) || ( DataFormatType . NEXRAD2 == format ) || ( DataFormatType . NIDS == format ) ) { access = tryAccess ; } } } // ADDE if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . ADDE ) ; // RESOLVER if ( access == null ) { access = findAccessByServiceType ( accessList , ServiceType . RESOLVER ) ; } return access ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add information from the InvDataset to the NetcdfDataset . [CODESPLIT] public static void annotate ( InvDataset ds , NetcdfDataset ncDataset ) { ncDataset . setTitle ( ds . getName ( ) ) ; ncDataset . setId ( ds . getID ( ) ) ; // add properties as global attributes for ( InvProperty p : ds . getProperties ( ) ) { String name = p . getName ( ) ; if ( null == ncDataset . findGlobalAttribute ( name ) ) { ncDataset . addAttribute ( null , new Attribute ( name , p . getValue ( ) ) ) ; } } /* ThreddsMetadata.GeospatialCoverage geoCoverage = ds.getGeospatialCoverage();\n   if (geoCoverage != null) {\n     if ( null != geoCoverage.getNorthSouthRange()) {\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lat_min\", new Double(geoCoverage.getLatSouth())));\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lat_max\", new Double(geoCoverage.getLatNorth())));\n     }\n     if ( null != geoCoverage.getEastWestRange()) {\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lon_min\", new Double(geoCoverage.getLonWest())));\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_lon_max\", new Double(geoCoverage.getLonEast())));\n     }\n     if ( null != geoCoverage.getUpDownRange()) {\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_vertical_min\", new Double(geoCoverage.getHeightStart())));\n       ncDataset.addAttribute(null, new Attribute(\"geospatial_vertical_max\", new Double(geoCoverage.getHeightStart() + geoCoverage.getHeightExtent())));\n     }\n   }\n\n   DateRange timeCoverage = ds.getTimeCoverage();\n   if (timeCoverage != null) {\n     ncDataset.addAttribute(null, new Attribute(\"time_coverage_start\", timeCoverage.getStart().toDateTimeStringISO()));\n     ncDataset.addAttribute(null, new Attribute(\"time_coverage_end\", timeCoverage.getEnd().toDateTimeStringISO()));\n   } */ ncDataset . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for an access method for an image datatype [CODESPLIT] private InvAccess getImageAccess ( InvDataset invDataset , ucar . nc2 . util . CancelTask task , Result result ) { List < InvAccess > accessList = new ArrayList <> ( invDataset . getAccess ( ) ) ; // a list of all the accesses while ( accessList . size ( ) > 0 ) { InvAccess access = chooseImageAccess ( accessList ) ; if ( access != null ) return access ; // next choice is resolver type. access = invDataset . getAccess ( ServiceType . RESOLVER ) ; // no valid access if ( access == null ) { result . errLog . format ( \"No access that could be used for Image Type %s %n\" , invDataset ) ; return null ; } // deal with RESOLVER type String datasetLocation = access . getStandardUrlName ( ) ; InvDatasetImpl rds = openResolver ( datasetLocation , task , result ) ; if ( rds == null ) return null ; // use the access list from the resolved dataset accessList = new ArrayList <> ( invDataset . getAccess ( ) ) ; } // loop over accesses return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private InvAccess findAccessByServiceType ( List < InvAccess > accessList , ServiceType type ) { for ( InvAccess a : accessList ) { if ( type . toString ( ) . equalsIgnoreCase ( a . getService ( ) . getServiceType ( ) . toString ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private InvAccess findAccessByDataFormatType ( List < InvAccess > accessList , DataFormatType type ) { for ( InvAccess a : accessList ) { if ( type . toString ( ) . equalsIgnoreCase ( a . getDataFormatType ( ) . toString ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "first one override [CODESPLIT] public static List < Property > removeDups ( List < Property > org ) { List < Property > result = new ArrayList <> ( org . size ( ) ) ; for ( Property p : org ) if ( ! result . contains ( p ) ) // O(n**2) result . add ( p ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only used by PartitionBuilder not PartitionBuilderFromIndex [CODESPLIT] void addPartition ( int partno , int groupno , int varno , int ndups , int nrecords , int nmissing , GribCollectionMutable . VariableIndex vi ) { if ( partList == null ) partList = new ArrayList <> ( nparts ) ; partList . add ( new PartitionForVariable2D ( partno , groupno , varno ) ) ; this . ndups += ndups ; this . nrecords += nrecords ; this . nmissing += nmissing ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "acquire or construct GribCollection - caller must call gc . close () when done [CODESPLIT] public GribCollectionImmutable getGribCollection ( ) throws IOException { String path = getIndexFilenameInCache ( ) ; if ( path == null ) { if ( Grib . debugIndexOnly ) { // we are running in debug mode where we only have the indices, not the data files // tricky: substitute the current root File orgParentDir = new File ( directory ) ; File currentFile = new File ( PartitionCollectionMutable . this . indexFilename ) ; File currentParent = currentFile . getParentFile ( ) ; File currentParentWithDir = new File ( currentParent , orgParentDir . getName ( ) ) ; File nestedIndex = isPartitionOfPartitions ? new File ( currentParentWithDir , filename ) : new File ( currentParent , filename ) ; // JMJ path = nestedIndex . getPath ( ) ; } else { throw new FileNotFoundException ( \"No index filename for partition= \" + this . toString ( ) ) ; } } // LOOK not cached return ( GribCollectionImmutable ) PartitionCollectionImmutable . partitionCollectionFactory . open ( new DatasetUrl ( null , path ) , - 1 , null , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the children must already exist [CODESPLIT] @ Nullable public GribCollectionMutable makeGribCollection ( ) { GribCollectionMutable result = GribCdmIndex . openMutableGCFromIndex ( dcm . getIndexFilename ( GribCdmIndex . NCX_SUFFIX ) , config , false , true , logger ) ; if ( result == null ) { logger . error ( \"Failed on openMutableGCFromIndex {}\" , dcm . getIndexFilename ( GribCdmIndex . NCX_SUFFIX ) ) ; return null ; } lastModified = result . lastModified ; fileSize = result . fileSize ; if ( result . masterRuntime != null ) partitionDate = result . masterRuntime . getFirstDate ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method that returns a RegExpAndDurationTimeCoverageEnhancer instance that will apply the match pattern to the dataset name . [CODESPLIT] public static RegExpAndDurationTimeCoverageEnhancer getInstanceToMatchOnDatasetName ( String matchPattern , String substitutionPattern , String duration ) { return new RegExpAndDurationTimeCoverageEnhancer ( matchPattern , substitutionPattern , duration , MatchTarget . DATASET_NAME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method that returns a RegExpAndDurationTimeCoverageEnhancer instance that will apply the match pattern to the dataset path . [CODESPLIT] public static RegExpAndDurationTimeCoverageEnhancer getInstanceToMatchOnDatasetPath ( String matchPattern , String substitutionPattern , String duration ) { return new RegExpAndDurationTimeCoverageEnhancer ( matchPattern , substitutionPattern , duration , MatchTarget . DATASET_PATH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an QueryCapability from an XML document at a named URL . check dqc . isValid dqc . getErrorMessages () to see if ok . If Disk caching is set cache the dqc and check IfModifiedSince . [CODESPLIT] public QueryCapability readXML ( String uriString ) throws IOException { // get URI URI uri ; try { uri = new URI ( uriString ) ; } catch ( URISyntaxException e ) { throw new MalformedURLException ( e . getMessage ( ) ) ; } // check if its cached if ( diskCache != null ) { File file = diskCache . getCacheFile ( uriString ) ; if ( file != null ) { HttpURLConnection conn = null ; try { URL url = uri . toURL ( ) ; conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( \"GET\" ) ; conn . setIfModifiedSince ( file . lastModified ( ) ) ; int code = conn . getResponseCode ( ) ; if ( code == HttpURLConnection . HTTP_OK ) { java . io . InputStream is = conn . getInputStream ( ) ; if ( is != null ) { try ( FileOutputStream fout = new FileOutputStream ( file ) ) { IO . copyB ( is , fout , buffer_size ) ; // cache it } try ( InputStream fin = new BufferedInputStream ( new FileInputStream ( file ) , 50000 ) ) { return readXML ( fin , uri ) ; } } } else { // use file try ( FileInputStream fin = new FileInputStream ( file ) ) { return readXML ( fin , uri ) ; } } } finally { if ( conn != null ) conn . disconnect ( ) ; } } // has file // no file - read and cache IO . readURLtoFileWithExceptions ( uriString , file , buffer_size ) ; try ( InputStream fin = new BufferedInputStream ( new FileInputStream ( file ) , 50000 ) ) { return readXML ( fin , uri ) ; } } // has diskCache // otherwise just open the URL warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; Document doc = null ; try { doc = builder . build ( uriString ) ; } catch ( JDOMException e ) { fatalMessages . append ( e . getMessage ( ) ) ; // makes it invalid } return readXML ( doc , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an QueryCapability from an InputStream . check dqc . isValid dqc . getErrorMessages () to see if ok . [CODESPLIT] public QueryCapability readXML ( InputStream docIs , URI uri ) throws IOException { // get ready for XML parsing warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; Document doc = null ; try { doc = builder . build ( docIs ) ; } catch ( JDOMException e ) { fatalMessages . append ( e . getMessage ( ) ) ; // makes it invalid } return readXML ( doc , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvCatalog from an a JDOM document . check dqc . isValid dqc . getErrorMessages () to see if ok . [CODESPLIT] private QueryCapability readXML ( org . jdom2 . Document doc , URI uri ) throws IOException { if ( doc == null ) { // parse failed QueryCapability dqc = new QueryCapability ( ) ; if ( fatalMessages . length ( ) > 0 ) dqc . appendErrorMessage ( fatalMessages . toString ( ) , true ) ; // makes it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( errMessages . toString ( ) , false ) ; // doesnt make it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( warnMessages . toString ( ) , false ) ; // doesnt make it invalid return dqc ; } // decide on converter based on namespace Element root = doc . getRootElement ( ) ; String namespace = root . getNamespaceURI ( ) ; DqcConvertIF fac = namespaceToDqcConverterHash . get ( namespace ) ; if ( fac == null ) { fac = defaultConverter ; // LOOK if ( debugVersion ) System . out . println ( \"use default converter \" + fac . getClass ( ) . getName ( ) + \"; no namespace \" + namespace ) ; } else if ( debugVersion ) System . out . println ( \"use converter \" + fac . getClass ( ) . getName ( ) + \" based on namespace \" + namespace ) ; // convert to object model QueryCapability dqc = fac . parseXML ( this , doc , uri ) ; if ( fatalMessages . length ( ) > 0 ) dqc . appendErrorMessage ( fatalMessages . toString ( ) , true ) ; // makes it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( errMessages . toString ( ) , false ) ; // doesnt make it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( warnMessages . toString ( ) , false ) ; // doesnt make it invalid return dqc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the catalog as an XML document to a String . [CODESPLIT] public String writeXML ( QueryCapability dqc ) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream ( 10000 ) ; writeXML ( dqc , os ) ; return os . toString ( CDM . utf8Charset . name ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( QueryCapability dqc , OutputStream os ) throws IOException { String ns = versionToNamespaceHash . get ( dqc . getVersion ( ) ) ; DqcConvertIF fac = namespaceToDqcConverterHash . get ( ns ) ; if ( fac == null ) fac = defaultConverter ; fac . writeXML ( dqc , os ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the catalog as an XML document to the specified filename . [CODESPLIT] public boolean writeXML ( QueryCapability dqc , String filename ) { try { BufferedOutputStream os = new BufferedOutputStream ( new FileOutputStream ( filename ) ) ; writeXML ( dqc , os ) ; os . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "testing [CODESPLIT] private static void doOne ( DqcFactory fac , String url ) { System . out . println ( \"***read \" + url ) ; try { QueryCapability dqc = fac . readXML ( url ) ; System . out . println ( \" dqc hasFatalError= \" + dqc . hasFatalError ( ) ) ; System . out . println ( \" dqc messages= \\n\" + dqc . getErrorMessages ( ) ) ; fac . writeXML ( dqc , System . out ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the projection information for this dimension . The parameters <code > start< / code > <code > stride< / code > and <code > stop< / code > are checked to verify that they make sense relative to each other and to the size of this dimension . If not an Invalid ParameterException is thrown . The general rule is : 0&lt ; = start&lt ; size 0&lt ; stride 0&lt ; = stop&lt ; size start&lt ; = stop . [CODESPLIT] public void setProjection ( int start , int stride , int stop ) throws InvalidDimensionException { if ( projection != null ) { // See if we are changing start/stride/stop\r if ( getSize ( ) != start || getStride ( ) != stride || getStop ( ) != stop ) { Formatter f = new Formatter ( ) ; f . format ( \" [%d:%d:%d (%d)] != [%d:%d:%d (%d)]\" , start , stride , stop , projection . size , projection . start , projection . stride , projection . stop , projection . size ) ; throw new ConstraintException ( \"Implementation limitation: muliple references to same variable in single constraint: \" + container . getLongName ( ) + f . toString ( ) ) ; } } String msg = \"DArrayDimension.setProjection: Bad Projection Request: \" ; // validate the arguments\r if ( start < 0 ) throw new InvalidDimensionException ( msg + \"start < 0\" ) ; if ( stride <= 0 ) throw new InvalidDimensionException ( msg + \"stride <= 0\" ) ; if ( stop < 0 ) throw new InvalidDimensionException ( msg + \"stop < 0\" ) ; if ( start < decl . start ) throw new InvalidDimensionException ( msg + \"start (\" + start + \") < size (\" + decl . size + \") for \" + _nameClear ) ; if ( stop >= decl . size ) throw new InvalidDimensionException ( msg + \"stop >= size: \" + stop + \":\" + decl . size ) ; if ( stop < start ) throw new InvalidDimensionException ( msg + \"stop < start\" ) ; projection = new Slice ( start , stride , stop ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Array< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DArrayDimension d = ( DArrayDimension ) super . cloneDAG ( map ) ; if ( container != null ) d . container = ( DArray ) cloneDAG ( map , container ) ; return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Structures must be fixed sized [CODESPLIT] private ucar . ma2 . ArrayStructure readStructureData ( ucar . nc2 . Structure s , Section section ) throws java . io . IOException , InvalidRangeException { H4header . Vinfo vinfo = ( H4header . Vinfo ) s . getSPobject ( ) ; vinfo . setLayoutInfo ( ) ; // make sure needed info is present\r int recsize = vinfo . elemSize ; // create the ArrayStructure\r StructureMembers members = s . makeStructureMembers ( ) ; for ( StructureMembers . Member m : members . getMembers ( ) ) { Variable v2 = s . findVariable ( m . getName ( ) ) ; H4header . Minfo minfo = ( H4header . Minfo ) v2 . getSPobject ( ) ; m . setDataParam ( minfo . offset ) ; } members . setStructureSize ( recsize ) ; ArrayStructureBB structureArray = new ArrayStructureBB ( members , section . getShape ( ) ) ; // LOOK subset\r // loop over records\r byte [ ] result = structureArray . getByteBuffer ( ) . array ( ) ; /*if (vinfo.isChunked) {\r\n      InputStream is = getChunkedInputStream(vinfo);\r\n      PositioningDataInputStream dataSource = new PositioningDataInputStream(is);\r\n      Layout layout = new LayoutRegular(vinfo.start, recsize, s.getShape(), section);\r\n      IospHelper.readData(dataSource, layout, DataType.STRUCTURE, result);  */ if ( ! vinfo . isLinked && ! vinfo . isCompressed ) { Layout layout = new LayoutRegular ( vinfo . start , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( raf , layout , DataType . STRUCTURE , result , - 1 , true ) ; /* option 1\r\n    } else if (vinfo.isLinked && !vinfo.isCompressed) {\r\n      Layout layout = new LayoutSegmented(vinfo.segPos, vinfo.segSize, recsize, s.getShape(), section);\r\n      IospHelper.readData(raf, layout, DataType.STRUCTURE, result, -1);  */ // option 2\r } else if ( vinfo . isLinked && ! vinfo . isCompressed ) { InputStream is = new LinkedInputStream ( vinfo ) ; PositioningDataInputStream dataSource = new PositioningDataInputStream ( is ) ; Layout layout = new LayoutRegular ( 0 , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( dataSource , layout , DataType . STRUCTURE , result ) ; } else if ( ! vinfo . isLinked && vinfo . isCompressed ) { InputStream is = getCompressedInputStream ( vinfo ) ; PositioningDataInputStream dataSource = new PositioningDataInputStream ( is ) ; Layout layout = new LayoutRegular ( 0 , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( dataSource , layout , DataType . STRUCTURE , result ) ; } else if ( vinfo . isLinked && vinfo . isCompressed ) { InputStream is = getLinkedCompressedInputStream ( vinfo ) ; PositioningDataInputStream dataSource = new PositioningDataInputStream ( is ) ; Layout layout = new LayoutRegular ( 0 , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( dataSource , layout , DataType . STRUCTURE , result ) ; } else { throw new IllegalStateException ( ) ; } return structureArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "brings up the indicated picture on the display . [CODESPLIT] public void setPicture ( URL filenameURL , String legendParam , double rotation ) { legend = legendParam ; centerWhenScaled = true ; sclPic . setScaleSize ( getSize ( ) ) ; sclPic . stopLoadingExcept ( filenameURL ) ; sclPic . loadAndScalePictureInThread ( filenameURL , Thread . MAX_PRIORITY , rotation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the buffered image directly . [CODESPLIT] public void setBufferedImage ( BufferedImage img , String statusMessage ) { legend = statusMessage ; centerWhenScaled = true ; Dimension dim = getSize ( ) ; sclPic . setScaleSize ( dim ) ; SourcePicture source = new SourcePicture ( ) ; source . setSourceBufferedImage ( img , statusMessage ) ; sclPic . setSourcePicture ( source ) ; if ( ! scaleToFit ) sclPic . setScaleFactor ( 1.0 ) ; sclPic . scalePicture ( ) ; repaint ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multifilies the scale factor so that paint () method scales the image larger . This method calls { [CODESPLIT] public void zoomIn ( ) { double OldScaleFactor = sclPic . getScaleFactor ( ) ; double NewScaleFactor = OldScaleFactor * 1.5 ; // If scaling goes from scale down to scale up, set ScaleFactor to exactly 1 if ( ( OldScaleFactor < 1 ) && ( NewScaleFactor > 1 ) ) NewScaleFactor = 1 ; // Check if the picture would get to large and cause the system to \"hang\"\t\t if ( ( sclPic . getOriginalWidth ( ) * sclPic . getScaleFactor ( ) < maximumPictureSize ) && ( sclPic . getOriginalHeight ( ) * sclPic . getScaleFactor ( ) < maximumPictureSize ) ) { sclPic . setScaleFactor ( NewScaleFactor ) ; sclPic . createScaledPictureInThread ( Thread . MAX_PRIORITY ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method sets the desired scaled size of the ScalablePicture to the size of the JPanel and fires off a createScaledPictureInThread request if the ScalablePicture has been loaded or is ready . [CODESPLIT] public void zoomToFit ( ) { //Tools.log(\"zoomToFit invoked\"); sclPic . setScaleSize ( getSize ( ) ) ; // prevent useless rescale events when the picture is not ready if ( sclPic . getStatusCode ( ) == sclPic . LOADED || sclPic . getStatusCode ( ) == sclPic . READY ) { sclPic . createScaledPictureInThread ( Thread . MAX_PRIORITY ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set image to center of panel by putting the coordinates of the middle of the original image into the Center to X and Center to Y varaibles by invoking the setCenterLoaction method . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . [CODESPLIT] public void centerImage ( ) { if ( sclPic . getOriginalImage ( ) != null ) { setCenterLocation ( ( int ) sclPic . getOriginalWidth ( ) / 2 , ( int ) sclPic . getOriginalHeight ( ) / 2 ) ; repaint ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that moves the image up by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . <p > <img src = .. / scrollUp . png border = 0 > <p > @see #scrollUp () @see #scrollDown () @see #scrollLeft () @see #scrollRight () [CODESPLIT] public void scrollUp ( ) { // if the bottom edge of the picture is visible, do not scroll if ( ( ( sclPic . getOriginalHeight ( ) - focusPoint . y ) * sclPic . getScaleFactor ( ) ) + getSize ( ) . height / 2 > getSize ( ) . height ) { focusPoint . y = focusPoint . y + ( int ) ( getSize ( ) . height * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( \"Scrollup rejected because bottom of picture is already showing.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that moves the image down by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . <p > <img src = .. / scrollDown . png border = 0 > <p > [CODESPLIT] public void scrollDown ( ) { if ( getSize ( ) . height / 2 - focusPoint . y * sclPic . getScaleFactor ( ) < 0 ) { focusPoint . y = focusPoint . y - ( int ) ( getSize ( ) . height * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( \"Scroll down rejected because top edge is aready visible\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that moves the image left by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . works just liks { [CODESPLIT] public void scrollLeft ( ) { // if the bottom edge of the picture is visible, do not scroll if ( ( ( sclPic . getOriginalWidth ( ) - focusPoint . x ) * sclPic . getScaleFactor ( ) ) + getSize ( ) . width / 2 > getSize ( ) . width ) { focusPoint . x = focusPoint . x + ( int ) ( getSize ( ) . width * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( \"Scrollup rejected because right edge of picture is already showing.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that moves the image right by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . works just liks { [CODESPLIT] public void scrollRight ( ) { if ( getSize ( ) . width / 2 - focusPoint . x * sclPic . getScaleFactor ( ) < 0 ) { focusPoint . x = focusPoint . x - ( int ) ( getSize ( ) . width * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( \"Scroll left rejected because left edge is aready visible\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to set the center of the image to the true coordinates in the picture but doesn t call <code > repaint () < / code > [CODESPLIT] public void setCenterLocation ( int Xparameter , int Yparameter ) { Tools . log ( \"setCenterLocation invoked with \" + Xparameter + \" x \" + Yparameter ) ; focusPoint . setLocation ( Xparameter , Yparameter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we are overriding the default paintComponent method grabbing the Graphics handle and doing our own drawing here . Esentially this method draws a large black rectangle . A drawRenderedImage is then painted doing an affine transformation on the scaled image to position it so the the desired point is in the middle of the Graphics object . The picture is not scaled here because this is a slow operation and only needs to be done once while moving the image is something the user is likely to do more often . [CODESPLIT] public void paintComponent ( Graphics g ) { int WindowWidth = getSize ( ) . width ; int WindowHeight = getSize ( ) . height ; Tools . log ( \"paintComponent called\" ) ; if ( Dragging == false ) { //otherwise it's already a move Cursor setCursor ( new Cursor ( Cursor . WAIT_CURSOR ) ) ; } if ( sclPic . getScaledPicture ( ) != null ) { Graphics2D g2d = ( Graphics2D ) g ; int X_Offset = ( int ) ( ( double ) ( WindowWidth / 2 ) - ( focusPoint . x * sclPic . getScaleFactor ( ) ) ) ; int Y_Offset = ( int ) ( ( double ) ( WindowHeight / 2 ) - ( focusPoint . y * sclPic . getScaleFactor ( ) ) ) ; // clear damaged component area Rectangle clipBounds = g2d . getClipBounds ( ) ; g2d . setColor ( Color . black ) ; // getBackground()); g2d . fillRect ( clipBounds . x , clipBounds . y , clipBounds . width , clipBounds . height ) ; g2d . drawRenderedImage ( sclPic . getScaledPicture ( ) , AffineTransform . getTranslateInstance ( X_Offset , Y_Offset ) ) ; //g2d.drawImage(sclPic.getScaledPicture(), null, 0, 0); if ( showInfo ) { g2d . setColor ( Color . white ) ; g2d . drawString ( legend , infoPoint . x , infoPoint . y ) ; g2d . drawString ( \"Size: \" + Integer . toString ( sclPic . getOriginalWidth ( ) ) + \" x \" + Integer . toString ( sclPic . getOriginalHeight ( ) ) + \" Offset: \" + X_Offset + \" x \" + Y_Offset + \" Mid: \" + Integer . toString ( focusPoint . x ) + \" x \" + Integer . toString ( focusPoint . y ) + \" Scale: \" + twoDecimalFormatter . format ( sclPic . getScaleFactor ( ) ) , infoPoint . x , infoPoint . y + lineSpacing ) ; /* g2d.drawString(\"File: \" + sclPic.getFilename()\n\t\t\t\t\t\t, infoPoint.x\n\t\t\t\t\t\t, infoPoint.y + (2 * lineSpacing) );\n\t\t\t\tg2d.drawString(\"Loaded in: \" \n\t\t\t\t\t\t+ twoDecimalFormatter.format( sclPic.getSourcePicture().loadTime / 1000F )\n\t\t\t\t\t\t+ \" Seconds\"\n\t\t\t\t\t\t, infoPoint.x\n\t\t\t\t\t\t, infoPoint.y + (3 * lineSpacing) );\n\t\t\t\tg2d.drawString(\"Free memory: \" \n\t\t\t\t\t\t+ Long.toString( Runtime.getRuntime().freeMemory( )/1024/1024, 0 ) \n\t\t\t\t\t\t+ \" MB\"\n\t\t\t\t\t\t, infoPoint.x\n\t\t\t\t\t\t, infoPoint.y + (4 * lineSpacing) ); */ } } else { // paint a black square g . setClip ( 0 , 0 , WindowWidth , WindowHeight ) ; g . setColor ( Color . black ) ; g . fillRect ( 0 , 0 , WindowWidth , WindowHeight ) ; } if ( Dragging == false ) { //otherwise a move Cursor and should remain setCursor ( new Cursor ( Cursor . DEFAULT_CURSOR ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that gets invoked from the ScalablePicture object to notify of status changes . The ScalablePicture goes through several statusses : UNINITIALISED GARBAGE_COLLECTION LOADING SCALING READY ERROR . <p > Each status is passed to the listener upon receipt . <p > When the ScalablePicture signals that it is READY the legend of the picture is sent to the listener . The method { [CODESPLIT] public void scalableStatusChange ( int pictureStatusCode , String pictureStatusMessage ) { Tools . log ( \"PicturePane.scalableStatusChange: got a status change: \" + pictureStatusMessage ) ; if ( pictureStatusCode == ScalablePicture . READY ) { Tools . log ( \"PicturePane.scalableStatusChange: a READY status\" ) ; pictureStatusMessage = legend ; if ( centerWhenScaled ) { Tools . log ( \"PicturePane.scalableStatusChange: centering image\" ) ; centerImage ( ) ; } Tools . log ( \"PicturePane.scalableStatusChange: forcing Panel repaint\" ) ; repaint ( ) ; } Enumeration e = picturePaneListeners . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( ScalablePictureListener ) e . nextElement ( ) ) . scalableStatusChange ( pictureStatusCode , pictureStatusMessage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine converts the two integers stored in a grid file into three integers containing the date time and forecast time . [CODESPLIT] public static int [ ] TG_FTOI ( int [ ] iftime , int start ) { int [ ] intdtf = new int [ 3 ] ; // If there is no forecast information, the string is stored as\r // date and time.\r if ( iftime [ start ] < 100000000 ) { intdtf [ 0 ] = iftime [ start ] ; intdtf [ 1 ] = iftime [ start + 1 ] ; intdtf [ 2 ] = 0 ; //  Otherwise, decode date/time and forecast info from the\r //  two integers. \r } else { //  The first word contains MMDDYYHHMM.  This must be turned\r //  into YYMMDD and HHMM.\r intdtf [ 0 ] = iftime [ start ] / 10000 ; intdtf [ 1 ] = iftime [ start ] - intdtf [ 0 ] * 10000 ; int mmdd = intdtf [ 0 ] / 100 ; int iyyy = intdtf [ 0 ] - mmdd * 100 ; intdtf [ 0 ] = iyyy * 10000 + mmdd ; //  The forecast time remains the same.\r intdtf [ 2 ] = iftime [ start + 1 ] ; } return intdtf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine converts an integer time array containing the date time and forecast time into a GEMPAK grid time . [CODESPLIT] public static String TG_ITOC ( int [ ] intdtf ) { String gdattim = \"\" ; //Check for the blank time which may be found.\r if ( ( intdtf [ 0 ] == 0 ) && ( intdtf [ 1 ] == 0 ) && ( intdtf [ 2 ] == 0 ) ) { return gdattim ; } //  Put the date and time into the character time.\r gdattim = TI_CDTM ( intdtf [ 0 ] , intdtf [ 1 ] ) ; //  Decode the forecast information if there is any.\r if ( intdtf [ 2 ] != 0 ) { String [ ] timeType = TG_CFTM ( intdtf [ 2 ] ) ; String ftype = timeType [ 0 ] ; String ftime = timeType [ 1 ] ; //      Combine two parts into string.\r gdattim = gdattim . substring ( 0 , 11 ) + ftype + ftime ; } return gdattim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine converts an integer grid forecast time into the character forecast type and time . The forecast type is A ( analysis ) F ( forecast ) G ( guess ) or I ( initialize ) . If the forecast time is less than 100 and the minutes are 00 only hh is returned . [CODESPLIT] public static String [ ] TG_CFTM ( int ifcast ) { String ftype = \"\" ; String ftime = \"\" ; //Check for negative times.\r if ( ifcast < 0 ) { return new String [ ] { ftype , ftime } ; } // Get the number representing forecast type and convert to a\r // character.\r int iftype = ifcast / 100000 ; if ( iftype == 0 ) { ftype = \"A\" ; } else if ( iftype == 1 ) { ftype = \"F\" ; } else if ( iftype == 2 ) { ftype = \"G\" ; } else if ( iftype == 3 ) { ftype = \"I\" ; } // Convert the time to a character.  Add 100000 so that leading\r // zeros will be encoded.\r int iftime = ifcast - iftype * 100000 ; int ietime = iftime + 100000 ; String fff = ST_INCH ( ietime ) ; // If the forecast time has minutes, set the character output\r // to all five digits. Otherwise, use only the first three digits,\r // which represent hours.\r if ( ietime % 100 == 0 ) { ftime = fff . substring ( 1 , 4 ) ; } else { ftime = fff . substring ( 1 ) ; } return new String [ ] { ftype , ftime } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine converts an integer date ( YYMMDD ) and time ( HHMM ) [CODESPLIT] public static String TI_CDTM ( int idate , int itime ) { String dattim ; int [ ] idtarr = new int [ 5 ] ; idtarr [ 0 ] = idate / 10000 ; idtarr [ 1 ] = ( idate - idtarr [ 0 ] * 10000 ) / 100 ; idtarr [ 2 ] = idate % 100 ; idtarr [ 3 ] = itime / 100 ; idtarr [ 4 ] = itime % 100 ; dattim = TI_ITOC ( idtarr ) ; return dattim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine converts an integer time array into a standard GEMPAK time . The integers are checked for validity . [CODESPLIT] public static String TI_ITOC ( int [ ] idtarr ) { String dattim ; String date , time ; //   Put array values into variables.\r int iyear = idtarr [ 0 ] ; int imonth = idtarr [ 1 ] ; int iday = idtarr [ 2 ] ; int ihour = idtarr [ 3 ] ; int iminut = idtarr [ 4 ] ; //  Check for leap year.\r //int ndays = TI_DAYM(iyear, imonth);\r iyear = iyear % 100 ; //  Check that each of these values is valid.\r /*  TODO: Check these\r\n            IF  ( iyear .lt. 0 )  iret = -7\r\n            IF  ( ( imonth .lt. 1 ) .or. ( imonth .gt. 12 ) ) iret = -8\r\n            IF  ( ( iday   .lt. 1 ) .or. ( iday   .gt. ndays ) )\r\n         +                                                    iret = -9\r\n            IF  ( ( ihour  .lt. 0 ) .or. ( ihour  .gt. 24 ) ) iret = -10\r\n            IF  ( ( iminut .lt. 0 ) .or. ( iminut .gt. 60 ) ) iret = -11\r\n            IF  ( iret .ne. 0 )  RETURN\r\n        */ //  Get the date and time.\r int idate = iyear * 10000 + imonth * 100 + iday ; int itime = ihour * 100 + iminut ; //  Convert date and time to character strings.\r //  Fill in blanks with zeroes.\r date = StringUtil2 . padZero ( idate , 6 ) ; time = StringUtil2 . padZero ( itime , 4 ) ; dattim = date + \"/\" + time ; return dattim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine returns the number of days in the given month . The year must be a full four - digit year . [CODESPLIT] public static int TI_DAYM ( int iyear , int imon ) { int iday = 0 ; if ( ( imon > 0 ) && ( imon < 13 ) ) { //  Pick the number of days for the given month.\r iday = month [ imon - 1 ] ; if ( ( imon == 2 ) && LEAP ( iyear ) ) { iday = iday + 1 ; } } return iday ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the int bits to a string [CODESPLIT] public static String ST_ITOC ( int value ) { byte [ ] bval = new byte [ 4 ] ; bval [ 0 ] = ( byte ) ( ( value & 0xff000000 ) >>> 24 ) ; bval [ 1 ] = ( byte ) ( ( value & 0x00ff0000 ) >>> 16 ) ; bval [ 2 ] = ( byte ) ( ( value & 0x0000ff00 ) >>> 8 ) ; bval [ 3 ] = ( byte ) ( ( value & 0x000000ff ) ) ; return new String ( bval , CDM . utf8Charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the int bits to a string [CODESPLIT] public static String ST_ITOC ( int [ ] values ) { StringBuilder sb = new StringBuilder ( ) ; for ( int value : values ) { sb . append ( ST_ITOC ( value ) ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine translates a numeric value for IVCORD into its character value in VCOORD . [CODESPLIT] public static String LV_CCRD ( int ivcord ) { //Translate known vertical coordinates or look for parameter name.\r String vcoord = \"\" ; //Check for numeric vertical coordinates.\r if ( ( ivcord >= 0 ) && ( ivcord < vertCoords . length ) ) { vcoord = vertCoords [ ivcord ] ; } else if ( ivcord > 100 ) { //     Check for character name as vertical coordinate.  Check that\r //     each character is an alphanumeric character.\r vcoord = ST_ITOC ( ivcord ) ; /*\r\n              Check for bad values\r\n\r\n                DO  i = 1, 4\r\n                    v = vcoord (i:i)\r\n                    IF  ( ( ( v .lt. 'A' ) .or. ( v .gt. 'Z' ) ) .and.\r\n     +                    ( ( v .lt. '0' ) .or. ( v .gt. '9' ) ) )  THEN\r\n                        ier = -1\r\n                    END IF\r\n                END DO\r\n            END IF\r\n            */ } return vcoord ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swap the order of the integers in place . [CODESPLIT] public static int [ ] swp4 ( int [ ] values , int startIndex , int number ) { for ( int i = startIndex ; i < startIndex + number ; i ++ ) { values [ i ] = Integer . reverseBytes ( values [ i ] ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a name for the grid packing type [CODESPLIT] public static String getGridPackingName ( int pktyp ) { String packingType = \"UNKNOWN\" ; switch ( pktyp ) { case GempakConstants . MDGNON : packingType = \"MDGNON\" ; break ; case GempakConstants . MDGGRB : packingType = \"MDGGRB\" ; break ; case GempakConstants . MDGNMC : packingType = \"MDGNMC\" ; break ; case GempakConstants . MDGDIF : packingType = \"MDGDIF\" ; break ; case GempakConstants . MDGDEC : packingType = \"MDGDEC\" ; break ; case GempakConstants . MDGRB2 : packingType = \"MDGRB2\" ; break ; default : break ; } return packingType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a name for the data packing type [CODESPLIT] public static String getDataType ( int typrt ) { String dataType = \"\" + typrt ; switch ( typrt ) { case GempakConstants . MDREAL : dataType = \"MDREAL\" ; break ; case GempakConstants . MDINTG : dataType = \"MDINTG\" ; break ; case GempakConstants . MDCHAR : dataType = \"MDCHAR\" ; break ; case GempakConstants . MDRPCK : dataType = \"MDRPCK\" ; break ; case GempakConstants . MDGRID : dataType = \"MDGRID\" ; break ; default : break ; } return dataType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data stream from the given InputStream . In the C ++ version this code was in Connect . [CODESPLIT] public void readData ( InputStream is , StatusUI statusUI ) throws IOException , EOFException , DAP2Exception { /* ByteArrayOutputStream bout = new ByteArrayOutputStream(50 * 1000);\r\n      copy(is, bout);\r\n      LogStream.dbg.printf(\" readData size=%d %n\",bout.size());\r\n      LogStream.dbg.logflush();\r\n      ByteArrayInputStream bufferedIS = new ByteArrayInputStream( bout.toByteArray());  */ //statusUI = new Counter();\r // Buffer the input stream for better performance\r BufferedInputStream bufferedIS = new BufferedInputStream ( is ) ; // Use a DataInputStream for deserialize\r DataInputStream dataIS = new DataInputStream ( bufferedIS ) ; for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { if ( statusUI != null && statusUI . userCancelled ( ) ) throw new DataReadException ( \"User cancelled\" ) ; ClientIO bt = ( ClientIO ) e . nextElement ( ) ; /* if (true) {\r\n            BaseType btt = (BaseType) bt;\r\n            System.out.printf(\"Deserializing: %s (%s) %n\", btt.getEncodedName(), ((BaseType) bt).getTypeName());\r\n          } */ bt . deserialize ( dataIS , ver , statusUI ) ; } //LogStream.out.printf(\"Deserializing: total size = %s %n\", counter);\r // notify GUI of finished download\r if ( statusUI != null ) statusUI . finished ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] private long copy ( InputStream in , OutputStream out ) throws IOException { long totalBytesRead = 0 ; byte [ ] buffer = new byte [ 8000 ] ; while ( true ) { int bytesRead = in . read ( buffer ) ; if ( bytesRead == - 1 ) break ; out . write ( buffer , 0 , bytesRead ) ; totalBytesRead += bytesRead ; } return totalBytesRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the dataset just read . In the C ++ version this code was in <code > geturl< / code > . [CODESPLIT] public void printVal ( PrintWriter pw ) { for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . printVal ( pw , \"\" , true ) ; pw . flush ( ) ; } pw . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump the dataset using externalize methods . This should create a multipart Mime document with the binary representation of the DDS that is currently in memory . [CODESPLIT] public final void externalize ( OutputStream os , boolean compress , boolean headers ) throws IOException { // First, print headers\r if ( headers ) { PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( os , Util . UTF8 ) ) ; pw . println ( \"HTTP/1.0 200 OK\" ) ; pw . println ( \"XDAP: \" + ServerVersion . DAP2_PROTOCOL_VERSION ) ; pw . println ( \"XDODS-Server: DODS/\" + ServerVersion . DAP2_PROTOCOL_VERSION ) ; pw . println ( \"Content-type: application/octet-stream\" ) ; pw . println ( \"Content-Description: dods-data\" ) ; if ( compress ) { pw . println ( \"Content-Encoding: deflate\" ) ; } pw . println ( ) ; pw . flush ( ) ; } // Buffer the output stream for better performance\r OutputStream bufferedOS ; if ( compress ) { // need a BufferedOutputStream - 3X performance - LOOK: why ??\r bufferedOS = new BufferedOutputStream ( new DeflaterOutputStream ( os ) ) ; } else { bufferedOS = new BufferedOutputStream ( os ) ; } // Redefine PrintWriter here, so the DDS is also compressed if necessary\r PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( bufferedOS , Util . UTF8 ) ) ; print ( pw ) ; // pw.println(\"Data:\");  // JCARON CHANGED\r pw . flush ( ) ; bufferedOS . write ( \"\\nData:\\n\" . getBytes ( CDM . utf8Charset ) ) ; // JCARON CHANGED\r bufferedOS . flush ( ) ; // Use a DataOutputStream for serialize\r DataOutputStream dataOS = new DataOutputStream ( bufferedOS ) ; for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . externalize ( dataOS ) ; } // Note: for DeflaterOutputStream, flush() is not sufficient to flush\r // all buffered data\r dataOS . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the Tag that matches the code . [CODESPLIT] public static TagEnum getTag ( short code ) { TagEnum te = hash . get ( code ) ; if ( te == null ) te = new TagEnum ( \"UNKNOWN\" , \"UNKNOWN\" , code ) ; return te ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method for class testing . <p / > Invocation : <PRE > java Getopts option set arg0 arg1 ... argn < / PRE > [CODESPLIT] public static void main ( String args [ ] ) { int i ; String args1 [ ] = new String [ args . length - 1 ] ; System . arraycopy ( args , 1 , args1 , 0 , args . length - 1 ) ; for ( i = 0 ; i < args . length ; i ++ ) { System . out . println ( \"args[\" + i + \"] : \" + args [ i ] ) ; } try { Getopts opts = new Getopts ( args [ 0 ] , args1 ) ; Enumeration names = opts . swList ( ) ; i = 0 ; while ( names . hasMoreElements ( ) ) { OptSwitch cs = opts . getSwitch ( ( Character ) names . nextElement ( ) ) ; System . out . println ( \"args[\" + i + \"] : \" + ( char ) cs . sw + \" \" + cs . type + \" \" + cs . set + \" \" + cs . val ) ; i ++ ; } String argp [ ] = opts . argList ( ) ; for ( i = 0 ; i < argp . length ; i ++ ) { System . out . println ( \"argv[\" + i + \"] : \" + argp [ i ] ) ; } } catch ( InvalidSwitch e ) { System . out . print ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open from a URL : adde : use AddeImage . factory () http : use javax . imageio . ImageIO . read () file : javax . imageio . ImageIO . read () [CODESPLIT] public BufferedImage open ( String location ) throws java . io . IOException { log = new StringBuffer ( ) ; if ( location . startsWith ( \"http:\" ) ) { try { URL url = new URL ( location ) ; currentFile = null ; return javax . imageio . ImageIO . read ( url ) ; } catch ( MalformedURLException e ) { log . append ( e . getMessage ( ) ) ; //e.printStackTrace(); return null ; } catch ( IOException e ) { log . append ( e . getMessage ( ) ) ; //e.printStackTrace(); return null ; } } else { if ( location . startsWith ( \"file:)\" ) ) location = location . substring ( 5 ) ; try { File f = new File ( location ) ; if ( ! f . exists ( ) ) { return null ; } currentFile = f ; currentDir = null ; return javax . imageio . ImageIO . read ( f ) ; } catch ( MalformedURLException e ) { log . append ( e . getMessage ( ) ) ; //e.printStackTrace(); return null ; } catch ( IOException e ) { log . append ( e . getMessage ( ) ) ; //e.printStackTrace(); return null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This assumes you have opened a file . looks in the parent directory . [CODESPLIT] public BufferedImage getNextImage ( boolean forward ) { if ( grid != null ) { if ( forward ) { this . time ++ ; if ( this . time >= this . ntimes ) this . time = 0 ; } else { this . time -- ; if ( this . time < 0 ) this . time = this . ntimes - 1 ; } Array data ; try { data = grid . readDataSlice ( this . time , 0 , - 1 , - 1 ) ; return ImageArrayAdapter . makeGrayscaleImage ( data , grid ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } } if ( currentFile == null ) return null ; if ( currentDir == null ) { currentDirFileNo = 0 ; currentDir = currentFile . getParentFile ( ) ; currentDirFileList = new ArrayList <> ( ) ; addToList ( currentDir , currentDirFileList ) ; //Arrays.asList(currentDir.listFiles()); //Collections.sort(currentDirFileList); for ( int i = 0 ; i < currentDirFileList . size ( ) ; i ++ ) { File file = currentDirFileList . get ( i ) ; if ( file . equals ( currentFile ) ) currentDirFileNo = i ; } } if ( forward ) { currentDirFileNo ++ ; if ( currentDirFileNo >= currentDirFileList . size ( ) ) currentDirFileNo = 0 ; } else { currentDirFileNo -- ; if ( currentDirFileNo < 0 ) currentDirFileNo = currentDirFileList . size ( ) - 1 ; } File nextFile = currentDirFileList . get ( currentDirFileNo ) ; try { System . out . println ( \"Open image \" + nextFile ) ; return javax . imageio . ImageIO . read ( nextFile ) ; } catch ( IOException e ) { System . out . println ( \"Failed to open image \" + nextFile ) ; return getNextImage ( forward ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conmpute the size in databuffer of the daptype wrt to a serialization ; 0 if undefined . [CODESPLIT] static public int size ( DapType type ) { switch ( type . getTypeSort ( ) ) { case Char : // remember serial size is 1, not 2. case UInt8 : case Int8 : return 1 ; case Int16 : case UInt16 : return 2 ; case Int32 : case UInt32 : case Float32 : return 4 ; case Int64 : case UInt64 : case Float64 : return 8 ; case Enum : return size ( ( ( DapEnumeration ) type ) . getBaseType ( ) ) ; default : break ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an array of one type of values to another type [CODESPLIT] static public Object convertVector ( DapType dsttype , DapType srctype , Object src ) throws DapException { int i ; TypeSort srcatomtype = srctype . getAtomicType ( ) ; TypeSort dstatomtype = dsttype . getAtomicType ( ) ; if ( srcatomtype == dstatomtype ) return src ; if ( srcatomtype . isIntegerType ( ) && TypeSort . getSignedVersion ( srcatomtype ) == TypeSort . getSignedVersion ( dstatomtype ) ) return src ; Object result = null ; boolean ok = true ; int len = 0 ; char [ ] csrc ; byte [ ] bsrc ; short [ ] shsrc ; int [ ] isrc ; long [ ] lsrc ; float [ ] fsrc ; double [ ] dsrc ; char [ ] cresult ; byte [ ] bresult ; short [ ] shresult ; int [ ] iresult ; long [ ] lresult ; float [ ] fresult ; double [ ] dresult ; BigInteger bi ; boolean srcunsigned = srcatomtype . isUnsigned ( ) ; boolean dstunsigned = dstatomtype . isUnsigned ( ) ; // Do a double switch src X dst (ugh!) switch ( srcatomtype ) { case Char : //Char-> csrc = ( char [ ] ) src ; len = csrc . length ; switch ( dstatomtype ) { case Int8 : //char->int8 case UInt8 : //char->uint8 return src ; case Int16 : //char->Int16 case UInt16 : //char->UInt16; result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Int32 : //char->Int32 case UInt32 : //char->UInt32; result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Int64 : //char->Int64 case UInt64 : //char->UInt64; result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Float32 : result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; default : ok = false ; break ; } break ; case Int8 : //Int8-> bsrc = ( byte [ ] ) src ; len = bsrc . length ; switch ( dstatomtype ) { case Char : //int8->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) bsrc [ i ] ) & 0xFF ) ; } break ; case Int16 : //int8->Int16 case UInt16 : //int8->UInt16; result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) bsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] &= ( short ) 0xFF ; } } break ; case Int32 : //int8->Int32 case UInt32 : //int8->UInt32; result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) bsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] &= 0xFF ; } } break ; case Int64 : //int8->Int64 case UInt64 : //int8->UInt64; result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) bsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFF L ; } } break ; case Float32 : //int8->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) bsrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) bsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt8 : //UInt8-> bsrc = ( byte [ ] ) src ; len = bsrc . length ; switch ( dstatomtype ) { case Char : //Byte->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) bsrc [ i ] ) & 0xFF ) ; } break ; case Int16 : //Byte->Int16 case UInt16 : //Byte->UInt16; result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) ( ( ( int ) bsrc [ i ] ) & 0xFF ) ; } break ; case Int32 : //Byte->Int32 case UInt32 : //Byte->UInt32; result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( ( int ) bsrc [ i ] ) & 0xFF ; } break ; case Int64 : //Byte->Int64 case UInt64 : //Byte->UInt64; result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( ( long ) bsrc [ i ] ) & 0xFF L ; } break ; case Float32 : //Byte->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( int ) bsrc [ i ] & 0xFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( int ) bsrc [ i ] & 0xFF ) ; } break ; default : ok = false ; break ; } break ; case Int16 : //Int16-> shsrc = ( short [ ] ) src ; len = shsrc . length ; switch ( dstatomtype ) { case Char : //int16->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) shsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : //int16->Int8 case UInt8 : //int16->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) shsrc [ i ] ; } break ; case Int32 : //int16->Int32 case UInt32 : //int16->UInt32; result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) shsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] &= 0xFFFF ; } } break ; case Int64 : //int16->Int64 case UInt64 : //int16->UInt64; result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) shsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFFFF L ; } } break ; case Float32 : //int16->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) shsrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) shsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt16 : //UInt16-> shsrc = ( short [ ] ) src ; len = shsrc . length ; switch ( dstatomtype ) { case Char : //UInt16->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) shsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : //UInt16->Int8 case UInt8 : //UInt16->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) shsrc [ i ] ; } break ; case Int32 : //UInt16->Int32 case UInt32 : //UInt16->UInt32; result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( ( int ) shsrc [ i ] ) & 0xFFFF ; } break ; case Int64 : //UInt16->Int64 case UInt64 : //UInt16->UInt64; result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( ( long ) shsrc [ i ] ) & 0xFFFF L ; } break ; case Float32 : //UInt16->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( int ) shsrc [ i ] & 0xFFFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( int ) shsrc [ i ] & 0xFFFF ) ; } break ; default : ok = false ; break ; } break ; case Int32 : //Int32-> isrc = ( int [ ] ) src ; len = isrc . length ; switch ( dstatomtype ) { case Char : //int32->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( isrc [ i ] & 0xFF ) ; } break ; case Int8 : //Int32->Int8 case UInt8 : //Int32->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) isrc [ i ] ; } break ; case Int16 : //Int32->Int16 case UInt16 : //Int32->UInt16; result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) isrc [ i ] ; } break ; case Int64 : //Int32->Int64 case UInt64 : //Int32->UInt64 result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) isrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFFFF L ; } } break ; case Float32 : //int32->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) isrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) isrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt32 : //UInt32-> isrc = ( int [ ] ) src ; len = isrc . length ; switch ( dstatomtype ) { case Char : //UInt32->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) isrc [ i ] ) & 0xFF ) ; } break ; case Int8 : //Int32->Int8 case UInt8 : //UInt32->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) isrc [ i ] ; } break ; case Int16 : //Int32->Int16 case UInt16 : //UInt32->UInt16 result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) isrc [ i ] ; } break ; case Int64 : //Int32->Int64 case UInt64 : //UInt32->UInt64; result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) isrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFFFFFFFF  L ; } } break ; case Float32 : //UInt32->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( int ) isrc [ i ] & 0xFFFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( int ) isrc [ i ] & 0xFFFF ) ; } break ; default : ok = false ; break ; } break ; case Int64 : //Int64-> lsrc = ( long [ ] ) src ; len = lsrc . length ; switch ( dstatomtype ) { case Char : //Int64->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( lsrc [ i ] & 0xFF ) ; } break ; case Int8 : //Int64->Int8 case UInt8 : //Int64->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) lsrc [ i ] ; } break ; case Int16 : //Int64->Int16 case UInt16 : //Int64->UInt16; result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) lsrc [ i ] ; } break ; case Int32 : //Int64->Int32 case UInt32 : //Int64->UInt32; result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) lsrc [ i ] ; } break ; case Float32 : //Int64->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) lsrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) lsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt64 : //UInt64-> lsrc = ( long [ ] ) src ; len = lsrc . length ; switch ( dstatomtype ) { case Char : //UInt64->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( lsrc [ i ] & 0xFF L ) ; } break ; case Int8 : //Int64->Int8 case UInt8 : //UInt64->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) lsrc [ i ] ; } break ; case Int16 : //Int64->Int16 case UInt16 : //UInt64->UInt16 result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) lsrc [ i ] ; } break ; case Int32 : //Int64->Int32 case UInt32 : //UInt64->UInt32 result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) lsrc [ i ] ; } break ; case Float32 : //UInt64->float result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bi = BigInteger . valueOf ( lsrc [ i ] ) ; bi = bi . and ( DapUtil . BIG_UMASK64 ) ; fresult [ i ] = bi . floatValue ( ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bi = BigInteger . valueOf ( lsrc [ i ] ) ; bi = bi . and ( DapUtil . BIG_UMASK64 ) ; dresult [ i ] = bi . doubleValue ( ) ; } break ; default : ok = false ; break ; } break ; case Float32 : //Float32-> fsrc = ( float [ ] ) src ; len = fsrc . length ; switch ( dstatomtype ) { case Char : //Float32->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) fsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : //Float32->Int8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) fsrc [ i ] ; } break ; case UInt8 : //Float32->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } bresult [ i ] = ( byte ) fsrc [ i ] ; } break ; case Int16 : //Float32->Int16 result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) fsrc [ i ] ; } break ; case UInt16 : //Float32->UInt16 result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } shresult [ i ] = ( short ) fsrc [ i ] ; } break ; case Int32 : //Float32->Int32 case UInt32 : //Float32->UInt32 result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } iresult [ i ] = ( int ) fsrc [ i ] ; } break ; case Int64 : //Float32->Int64 result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { BigDecimal bd = new BigDecimal ( fsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case UInt64 : //Float32->UInt64 result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } // not convertible BigDecimal bd = new BigDecimal ( fsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case Float64 : //Float32->Float64 result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) fsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case Float64 : //Float64-> dsrc = ( double [ ] ) src ; len = dsrc . length ; switch ( dstatomtype ) { case Char : //Float64->char result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) dsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : //Float64->Int8 case UInt8 : //Float64->UInt8 result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) dsrc [ i ] ; } break ; case Int16 : //Float64->Int16 case UInt16 : //Float64->UInt16 result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) dsrc [ i ] ; } break ; case Int32 : //Float64->Int32 case UInt32 : //Float64->UInt32 result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) dsrc [ i ] ; } break ; case Int64 : //Float64->Int64 result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { BigDecimal bd = new BigDecimal ( dsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case UInt64 : //Float64->UInt64 result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( dsrc [ i ] < 0 ) { ok = false ; break ; } // not convertible BigDecimal bd = new BigDecimal ( dsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case Float32 : //Float32->Float64 result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) dsrc [ i ] ; } break ; default : ok = false ; break ; } break ; default : throw new DapException ( String . format ( \"Illegal Conversion: %s->%s\" , srctype , dsttype ) ) ; } if ( ! ok ) throw new DapException ( String . format ( \"Illegal Conversion: %s->%s\" , srctype , dsttype ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the sum of the values in the given array . [CODESPLIT] private static int sumArray ( int [ ] arr ) { if ( arr == null ) throw new NullPointerException ( \"null array\" ) ; if ( arr . length == 0 ) throw new IllegalArgumentException ( \"Zero-length array\" ) ; int sum = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] <= 0 ) { throw new IllegalArgumentException ( \"All array values must be > 0\" ) ; } sum += arr [ i ] ; } return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the grid scale . [CODESPLIT] public void setGrid ( Rectangle2D bbox , double width , double height ) { offsetX = bbox . getX ( ) ; offsetY = bbox . getY ( ) ; // number of grid cells countX = Math . min ( nx , ( int ) ( bbox . getWidth ( ) / ( scaleOverlap * width ) ) ) ; countY = Math . min ( ny , ( int ) ( bbox . getHeight ( ) / ( scaleOverlap * height ) ) ) ; gridWidth = bbox . getWidth ( ) / countX ; gridHeight = bbox . getHeight ( ) / countY ; if ( debug ) System . out . println ( \"SpatialGrid size \" + gridWidth + \" \" + gridHeight + \" = \" + countX + \" by \" + countY + \" scaleOverlap= \" + scaleOverlap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set how much the data may overlap . [CODESPLIT] public void setOverlap ( int overlap ) { // overlap limited to [0, 50%] double dover = Math . max ( 0.0 , Math . min ( .01 * overlap , .50 ) ) ; scaleOverlap = 1.0 - dover ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clear all the grid cells [CODESPLIT] public void clear ( ) { for ( int y = 0 ; y < countY ; y ++ ) for ( int x = 0 ; x < countX ; x ++ ) gridArray [ y ] [ x ] . used = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given rect intersects an already drawn one . If not set the corresponding cell as marked store object return true meaning ok to draw . [CODESPLIT] public boolean markIfClear ( Rectangle2D rect , Object o ) { double centerX = rect . getX ( ) + rect . getWidth ( ) / 2 ; double centerY = rect . getY ( ) + rect . getHeight ( ) / 2 ; int indexX = ( int ) ( ( centerX - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( centerY - offsetY ) / gridHeight ) ; if ( debugMark ) System . out . println ( \"markIfClear \" + rect + \" \" + indexX + \" \" + indexY ) ; if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) // outside box return false ; GridCell gwant = gridArray [ indexY ] [ indexX ] ; if ( gwant . used ) // already taken return false ; if ( null != findIntersection ( rect ) ) return false ; // its ok to use gwant . used = true ; gwant . objectBB = rect ; gwant . o = o ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given rect intersects an already drawn object [CODESPLIT] public Object findIntersection ( Rectangle2D rect ) { double centerX = rect . getX ( ) + rect . getWidth ( ) / 2 ; double centerY = rect . getY ( ) + rect . getHeight ( ) / 2 ; int indexX = ( int ) ( ( centerX - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( centerY - offsetY ) / gridHeight ) ; // outside box if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) return null ; // check the surrounding points for ( int y = Math . max ( 0 , indexY - 1 ) ; y <= Math . min ( countY - 1 , indexY + 1 ) ; y ++ ) { for ( int x = Math . max ( 0 , indexX - 1 ) ; x <= Math . min ( countX - 1 , indexX + 1 ) ; x ++ ) { GridCell gtest = gridArray [ y ] [ x ] ; if ( ! gtest . used ) continue ; if ( intersectsOverlap ( rect , gtest . objectBB ) ) // hits an adjacent rectangle return gtest . o ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given point is contained in already drawn object [CODESPLIT] public Object findIntersection ( Point2D p ) { int indexX = ( int ) ( ( p . getX ( ) - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( p . getY ( ) - offsetY ) / gridHeight ) ; // outside box if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) return null ; // check the surrounding points for ( int y = Math . max ( 0 , indexY - 1 ) ; y <= Math . min ( countY - 1 , indexY + 1 ) ; y ++ ) { for ( int x = Math . max ( 0 , indexX - 1 ) ; x <= Math . min ( countX - 1 , indexX + 1 ) ; x ++ ) { GridCell gtest = gridArray [ y ] [ x ] ; if ( ! gtest . used ) continue ; if ( gtest . objectBB . contains ( p . getX ( ) , p . getY ( ) ) ) return gtest . o ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the closest marked cell to the given point [CODESPLIT] public Object findClosest ( Point2D pt ) { Object o = null ; int indexX = ( int ) ( ( pt . getX ( ) - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( pt . getY ( ) - offsetY ) / gridHeight ) ; if ( debugClosest ) System . out . println ( \"findClosest \" + pt + \" \" + indexX + \" \" + indexY ) ; if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) // outside box return null ; GridCell gwant = gridArray [ indexY ] [ indexX ] ; if ( gwant . used ) // that was easy return gwant . o ; // check the surrounding points along perimeter of increasing diameter for ( int p = 1 ; p < Math . max ( countX - 1 , countY - 1 ) ; p ++ ) if ( null != ( o = findClosestAlongPerimeter ( pt , indexX , indexY , p ) ) ) return o ; return null ; // nothing found }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "with center cell [ x y ] and side of length 2 * perimeter + 1 [CODESPLIT] private Object findClosestAlongPerimeter ( Point2D pt , int centerX , int centerY , int perimeter ) { Object closestO = null ; double closestD = MAX_DOUBLE ; // top and bottom row for ( int y = centerY - perimeter ; y <= centerY + perimeter ; y += 2 * perimeter ) for ( int x = centerX - perimeter ; x <= centerX + perimeter ; x ++ ) { double distance = distanceSq ( pt , x , y ) ; if ( distance < closestD ) { closestO = gridArray [ y ] [ x ] . o ; closestD = distance ; if ( debugClosest ) System . out . println ( \"   closest \" + gridArray [ y ] [ x ] ) ; } } // middle rows for ( int y = centerY - perimeter + 1 ; y <= centerY + perimeter - 1 ; y ++ ) for ( int x = centerX - perimeter ; x <= centerX + perimeter ; x += 2 * perimeter ) { double distance = distanceSq ( pt , x , y ) ; if ( distance < closestD ) { closestO = gridArray [ y ] [ x ] . o ; closestD = distance ; if ( debugClosest ) System . out . println ( \"   closest \" + gridArray [ y ] [ x ] ) ; } } return closestO ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if out of bbox or cell not marked return MAX_DOUBLE [CODESPLIT] private double distanceSq ( Point2D pt , int indexX , int indexY ) { if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) // outside bounding box return MAX_DOUBLE ; GridCell gtest = gridArray [ indexY ] [ indexX ] ; if ( ! gtest . used ) // nothing in this cell return MAX_DOUBLE ; // get distance from center of cell Rectangle2D rect = gtest . objectBB ; double dx = rect . getX ( ) + rect . getWidth ( ) / 2 - pt . getX ( ) ; double dy = rect . getY ( ) + rect . getHeight ( ) / 2 - pt . getY ( ) ; return ( dx * dx + dy * dy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup needed for all MultiTrajectoryObsDatatypes . [CODESPLIT] public void setTrajectoryInfo ( Dimension trajDim , Variable trajVar , Dimension timeDim , Variable timeVar , Variable latVar , Variable lonVar , Variable elevVar ) throws IOException { this . trajDim = trajDim ; this . trajVar = trajVar ; this . timeDim = timeDim ; this . timeVar = timeVar ; this . latVar = latVar ; this . lonVar = lonVar ; this . elevVar = elevVar ; trajectoryNumPoint = this . timeDim . getLength ( ) ; timeVarUnitsString = this . timeVar . findAttribute ( \"units\" ) . getStringValue ( ) ; // Check that time, lat, lon, elev units are acceptable. if ( DateUnit . getStandardDate ( timeVarUnitsString ) == null ) throw new IllegalArgumentException ( \"Units of time variable <\" + timeVarUnitsString + \"> not a date unit.\" ) ; String latVarUnitsString = this . latVar . findAttribute ( \"units\" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( latVarUnitsString , \"degrees_north\" ) ) throw new IllegalArgumentException ( \"Units of lat var <\" + latVarUnitsString + \"> not compatible with \\\"degrees_north\\\".\" ) ; String lonVarUnitsString = this . lonVar . findAttribute ( \"units\" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( lonVarUnitsString , \"degrees_east\" ) ) throw new IllegalArgumentException ( \"Units of lon var <\" + lonVarUnitsString + \"> not compatible with \\\"degrees_east\\\".\" ) ; String elevVarUnitsString = this . elevVar . findAttribute ( \"units\" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( elevVarUnitsString , \"meters\" ) ) throw new IllegalArgumentException ( \"Units of elev var <\" + elevVarUnitsString + \"> not compatible with \\\"meters\\\".\" ) ; try { elevVarUnitsConversionFactor = getMetersConversionFactor ( elevVarUnitsString ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Exception on getMetersConversionFactor() for the units of elev var <\" + elevVarUnitsString + \">.\" ) ; } if ( this . netcdfDataset . hasUnlimitedDimension ( ) && this . netcdfDataset . getUnlimitedDimension ( ) . equals ( timeDim ) ) { this . netcdfDataset . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; this . recordVar = ( Structure ) this . netcdfDataset . getRootGroup ( ) . findVariable ( \"record\" ) ; } else { this . recordVar = new StructurePseudo ( this . netcdfDataset , null , \"record\" , timeDim ) ; } // @todo HACK, HACK, HACK - remove once addRecordStructure() deals with ncd attribute changes. Variable latVarInRecVar = this . recordVar . findVariable ( this . latVar . getFullNameEscaped ( ) ) ; Attribute latVarUnitsAtt = latVarInRecVar . findAttribute ( \"units\" ) ; if ( latVarUnitsAtt != null && ! latVarUnitsString . equals ( latVarUnitsAtt . getStringValue ( ) ) ) latVarInRecVar . addAttribute ( new Attribute ( \"units\" , latVarUnitsString ) ) ; Variable lonVarInRecVar = this . recordVar . findVariable ( this . lonVar . getFullNameEscaped ( ) ) ; Attribute lonVarUnitsAtt = lonVarInRecVar . findAttribute ( \"units\" ) ; if ( lonVarUnitsAtt != null && ! lonVarUnitsString . equals ( lonVarUnitsAtt . getStringValue ( ) ) ) lonVarInRecVar . addAttribute ( new Attribute ( \"units\" , lonVarUnitsString ) ) ; Variable elevVarInRecVar = this . recordVar . findVariable ( this . elevVar . getFullNameEscaped ( ) ) ; Attribute elevVarUnitsAtt = elevVarInRecVar . findAttribute ( \"units\" ) ; if ( elevVarUnitsAtt != null && ! elevVarUnitsString . equals ( elevVarUnitsAtt . getStringValue ( ) ) ) elevVarInRecVar . addAttribute ( new Attribute ( \"units\" , elevVarUnitsString ) ) ; trajectoryVarsMap = new HashMap ( ) ; for ( Iterator it = this . netcdfDataset . getRootGroup ( ) . getVariables ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Variable curVar = ( Variable ) it . next ( ) ; if ( curVar . getRank ( ) >= 2 && //  !curVar.equals( this.trajVar) && // These two are both one dimensional arrays //  !curVar.equals( this.timeVar) && // ! curVar . equals ( this . latVar ) && ! curVar . equals ( this . lonVar ) && ! curVar . equals ( this . elevVar ) && ( this . recordVar == null ? true : ! curVar . equals ( this . recordVar ) ) ) { MyTypedDataVariable typedVar = new MyTypedDataVariable ( new VariableDS ( null , curVar , true ) ) ; dataVariables . add ( typedVar ) ; trajectoryVarsMap . put ( typedVar . getShortName ( ) , typedVar ) ; } } Range startPointRange = null ; Range endPointRange = null ; try { startPointRange = new Range ( 0 , 0 ) ; endPointRange = new Range ( trajectoryNumPoint - 1 , trajectoryNumPoint - 1 ) ; } catch ( InvalidRangeException e ) { IOException ioe = new IOException ( \"Start or end point range invalid: \" + e . getMessage ( ) ) ; ioe . initCause ( e ) ; throw ( ioe ) ; } List section0 = new ArrayList ( 1 ) ; List section1 = new ArrayList ( 1 ) ; section0 . add ( startPointRange ) ; section1 . add ( endPointRange ) ; Array startTimeArray ; Array endTimeArray ; try { startTimeArray = this . timeVar . read ( section0 ) ; endTimeArray = this . timeVar . read ( section1 ) ; } catch ( InvalidRangeException e ) { IOException ioe = new IOException ( \"Invalid range during read of start or end point: \" + e . getMessage ( ) ) ; ioe . initCause ( e ) ; throw ( ioe ) ; } String startTimeString ; String endTimeString ; if ( this . timeVar . getDataType ( ) . equals ( DataType . DOUBLE ) ) { startTimeString = startTimeArray . getDouble ( startTimeArray . getIndex ( ) ) + \" \" + timeVarUnitsString ; endTimeString = endTimeArray . getDouble ( endTimeArray . getIndex ( ) ) + \" \" + timeVarUnitsString ; } else if ( this . timeVar . getDataType ( ) . equals ( DataType . FLOAT ) ) { startTimeString = startTimeArray . getFloat ( startTimeArray . getIndex ( ) ) + \" \" + timeVarUnitsString ; endTimeString = endTimeArray . getFloat ( endTimeArray . getIndex ( ) ) + \" \" + timeVarUnitsString ; } else if ( this . timeVar . getDataType ( ) . equals ( DataType . INT ) ) { startTimeString = startTimeArray . getInt ( startTimeArray . getIndex ( ) ) + \" \" + timeVarUnitsString ; endTimeString = endTimeArray . getInt ( endTimeArray . getIndex ( ) ) + \" \" + timeVarUnitsString ; } else { String tmpMsg = \"Time var <\" + this . timeVar . getFullName ( ) + \"> is not a double, float, or integer <\" + timeVar . getDataType ( ) . toString ( ) + \">.\" ; //log.error( tmpMsg ); throw new IllegalArgumentException ( tmpMsg ) ; } startDate = DateUnit . getStandardDate ( startTimeString ) ; endDate = DateUnit . getStandardDate ( endTimeString ) ; trajectoryIds = new ArrayList ( ) ; trajectories = new ArrayList ( ) ; trajectoriesMap = new HashMap ( ) ; Array trajArray = this . trajVar . read ( ) ; Index index = trajArray . getIndex ( ) ; for ( int i = 0 ; i < trajArray . getSize ( ) ; i ++ ) { String curTrajId ; if ( this . trajVar . getDataType ( ) . equals ( DataType . STRING ) ) { curTrajId = ( String ) trajArray . getObject ( index . set ( i ) ) ; } else if ( this . trajVar . getDataType ( ) . equals ( DataType . DOUBLE ) ) { curTrajId = String . valueOf ( trajArray . getDouble ( index . set ( i ) ) ) ; } else if ( this . trajVar . getDataType ( ) . equals ( DataType . FLOAT ) ) { curTrajId = String . valueOf ( trajArray . getFloat ( index . set ( i ) ) ) ; } else if ( this . trajVar . getDataType ( ) . equals ( DataType . INT ) ) { curTrajId = String . valueOf ( trajArray . getInt ( index . set ( i ) ) ) ; } else { String tmpMsg = \"Trajectory var <\" + this . trajVar . getFullName ( ) + \"> is not a string, double, float, or integer <\" + this . trajVar . getDataType ( ) . toString ( ) + \">.\" ; //log.error( tmpMsg ); throw new IllegalStateException ( tmpMsg ) ; } MultiTrajectory curTraj = new MultiTrajectory ( curTrajId , i , trajectoryNumPoint , startDate , endDate , this . trajVar , this . timeVar , timeVarUnitsString , this . latVar , this . lonVar , this . elevVar , dataVariables , trajectoryVarsMap ) ; trajectoryIds . add ( curTrajId ) ; trajectories . add ( curTraj ) ; trajectoriesMap . put ( curTrajId , curTraj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the canonical form of the URL . If the urlName starts with http : change it to start with cdmremote : otherwise leave it alone . [CODESPLIT] public static String canonicalURL ( String urlName ) { if ( urlName . startsWith ( \"http:\" ) ) return SCHEME + urlName . substring ( 5 ) ; return urlName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "session may be null if so will be closed on method . close () [CODESPLIT] public static InputStream sendQuery ( HTTPSession session , String remoteURI , String query ) throws IOException { long start = System . currentTimeMillis ( ) ; StringBuilder sbuff = new StringBuilder ( remoteURI ) ; sbuff . append ( \"?\" ) ; sbuff . append ( query ) ; if ( showRequest ) System . out . printf ( \" CdmRemote sendQuery= %s\" , sbuff ) ; HTTPMethod method = HTTPFactory . Get ( session , sbuff . toString ( ) ) ; try { int statusCode = method . execute ( ) ; if ( statusCode == 404 ) { throw new FileNotFoundException ( method . getPath ( ) + \" \" + method . getStatusLine ( ) ) ; } else if ( statusCode >= 400 ) { throw new IOException ( method . getPath ( ) + \" \" + method . getStatusLine ( ) ) ; } InputStream stream = method . getResponseBodyAsStream ( ) ; if ( showRequest ) System . out . printf ( \" took %d msecs %n\" , System . currentTimeMillis ( ) - start ) ; // Leave the stream open. We must also leave the HTTPMethod open because the two are linked: // calling close() on one object causes the other object to be closed as well. return stream ; } catch ( IOException e ) { // Close the HTTPMethod if there was an exception; otherwise leave it open. method . close ( ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array eta = readArray ( etaVar , timeIndex ) ; Array sigma = readArray ( sVar , timeIndex ) ; Array depth = readArray ( depthVar , timeIndex ) ; int nz = ( int ) sigma . getSize ( ) ; Index sIndex = sigma . getIndex ( ) ; int [ ] shape2D = eta . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index etaIndex = eta . getIndex ( ) ; Index depthIndex = depth . getIndex ( ) ; ArrayDouble . D3 height = new ArrayDouble . D3 ( nz , ny , nx ) ; for ( int z = 0 ; z < nz ; z ++ ) { double sigmaVal = sigma . getDouble ( sIndex . set ( z ) ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { double etaVal = eta . getDouble ( etaIndex . set ( y , x ) ) ; double depthVal = depth . getDouble ( depthIndex . set ( y , x ) ) ; height . set ( z , y , x , etaVal + sigmaVal * ( depthVal + etaVal ) ) ; } } } return height ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array eta = readArray ( etaVar , timeIndex ) ; Array sigma = readArray ( sVar , timeIndex ) ; Array depth = readArray ( depthVar , timeIndex ) ; int nz = ( int ) sigma . getSize ( ) ; Index sIndex = sigma . getIndex ( ) ; Index etaIndex = eta . getIndex ( ) ; Index depthIndex = depth . getIndex ( ) ; ArrayDouble . D1 height = new ArrayDouble . D1 ( nz ) ; for ( int z = 0 ; z < nz ; z ++ ) { double sigmaVal = sigma . getDouble ( sIndex . set ( z ) ) ; double etaVal = eta . getDouble ( etaIndex . set ( yIndex , xIndex ) ) ; double depthVal = depth . getDouble ( depthIndex . set ( yIndex , xIndex ) ) ; height . set ( z , etaVal + sigmaVal * ( depthVal + etaVal ) ) ; } return height ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for creating a new BaseUnit or obtaining a previously - created one . [CODESPLIT] public static synchronized BaseUnit getOrCreate ( final UnitName id , final BaseQuantity baseQuantity ) throws NameException , UnitExistsException { BaseUnit baseUnit ; final BaseUnit nameUnit = nameMap . get ( id ) ; final BaseUnit quantityUnit = quantityMap . get ( baseQuantity ) ; if ( nameUnit != null || quantityUnit != null ) { baseUnit = nameUnit != null ? nameUnit : quantityUnit ; if ( ( nameUnit != null && ! baseQuantity . equals ( nameUnit . getBaseQuantity ( ) ) ) || ( quantityUnit != null && ! id . equals ( quantityUnit . getUnitName ( ) ) ) ) { throw new UnitExistsException ( \"Attempt to incompatibly redefine base unit \\\"\" + baseUnit + ' ' ) ; } } else { baseUnit = new BaseUnit ( id , baseQuantity ) ; quantityMap . put ( baseQuantity , baseUnit ) ; nameMap . put ( id , baseUnit ) ; } return baseUnit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final BaseUnit meter = new BaseUnit ( UnitName . newUnitName ( \"meter\" , null , \"m\" ) , BaseQuantity . LENGTH ) ; System . out . println ( \"meter.getBaseQuantity()=\" + meter . getBaseQuantity ( ) ) ; System . out . println ( \"meter.toDerivedUnit(1.)=\" + meter . toDerivedUnit ( 1. ) ) ; System . out . println ( \"meter.toDerivedUnit(new float[] {2})[0]=\" + meter . toDerivedUnit ( new float [ ] { 2 } , new float [ 1 ] ) [ 0 ] ) ; System . out . println ( \"meter.fromDerivedUnit(1.)=\" + meter . fromDerivedUnit ( 1. ) ) ; System . out . println ( \"meter.fromDerivedUnit(new float[] {3})[0]=\" + meter . fromDerivedUnit ( new float [ ] { 3 } , new float [ 1 ] ) [ 0 ] ) ; System . out . println ( \"meter.isCompatible(meter)=\" + meter . isCompatible ( meter ) ) ; final BaseUnit radian = new BaseUnit ( UnitName . newUnitName ( \"radian\" , null , \"rad\" ) , BaseQuantity . PLANE_ANGLE ) ; System . out . println ( \"meter.isCompatible(radian)=\" + meter . isCompatible ( radian ) ) ; System . out . println ( \"meter.isDimensionless()=\" + meter . isDimensionless ( ) ) ; System . out . println ( \"radian.isDimensionless()=\" + radian . isDimensionless ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called from Aggregation Fmrc FeatureDatasetFactoryManager [CODESPLIT] static public CollectionManager open ( String collectionName , String collectionSpec , String olderThan , Formatter errlog ) throws IOException { if ( collectionSpec . startsWith ( CATALOG ) ) return new CollectionManagerCatalog ( collectionName , collectionSpec , olderThan , errlog ) ; else return MFileCollectionManager . open ( collectionName , collectionSpec , olderThan , errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * clean up deleted files in metadata manager protected void deleteOld ( Map<String MFile > newMap ) { if ( store == null && enableMetadataManager ) initMM () ; if ( store ! = null ) store . delete ( newMap ) ; } [CODESPLIT] public void putMetadata ( MFile file , String key , byte [ ] value ) { if ( store == null ) initMM ( ) ; if ( store != null ) store . put ( file . getPath ( ) + \"#\" + key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the set of leading protocols for a url ; may be more than one . Watch out for Windows paths starting with a drive letter = > protocol names must all have a length > 1 . Watch out for :: Each captured protocol is saved without trailing : Assume : the protocols MUST be terminated by the occurrence of / . [CODESPLIT] static public List < String > getProtocols ( String url ) { List < String > allprotocols = new ArrayList <> ( ) ; // all leading protocols upto path or host // Note, we cannot use split because of the context sensitivity // This code is quite ugly because of all the confounding cases // (e.g. windows path, embedded colons, etc.). // Specifically, the 'file:' protocol is a problem because // it has no many non-standard forms such as file:x/y file://x/y file:///x/y. StringBuilder buf = new StringBuilder ( url ) ; // If there are any leading protocols, then they must stop at the first '/'. int slashpos = buf . indexOf ( \"/\" ) ; // Check special case of file:<path> with no slashes after file: if ( url . startsWith ( \"file:\" ) && \"/\\\\\" . indexOf ( url . charAt ( 5 ) ) < 0 ) { allprotocols . add ( \"file\" ) ; } else if ( slashpos >= 0 ) { // Remove everything after the first slash buf . delete ( slashpos + 1 , buf . length ( ) ) ; for ( ; ; ) { int index = buf . indexOf ( \":\" ) ; if ( index < 0 ) break ; // no more protocols // Validate protocol if ( ! validateprotocol ( url , 0 , index ) ) break ; String protocol = buf . substring ( 0 , index ) ; // not including trailing ':' allprotocols . add ( protocol ) ; buf . delete ( 0 , index + 1 ) ; // remove the leading protocol } } return allprotocols ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] static public DatasetUrl findDatasetUrl ( String orgLocation ) throws IOException { ServiceType svctype = null ; // Canonicalize the location String location = StringUtil2 . replace ( orgLocation . trim ( ) , ' ' , \"/\" ) ; List < String > allprotocols = DatasetUrl . getProtocols ( location ) ; String trueurl = location ; String leadprotocol ; if ( allprotocols . size ( ) == 0 ) { leadprotocol = \"file\" ; // The location has no leading protocols, assume file: } else { leadprotocol = allprotocols . get ( 0 ) ; } // Priority in deciding // the service type is as follows. // 1. \"protocol\" tag in fragment // 2. specific protocol in fragment // 3. leading protocol // 4. path extension // 5. contact the server (if defined) // temporarily remove any trailing query or fragment String fragment = null ; int pos = trueurl . lastIndexOf ( ' ' ) ; if ( pos >= 0 ) { fragment = trueurl . substring ( pos + 1 , trueurl . length ( ) ) ; trueurl = trueurl . substring ( 0 , pos ) ; } pos = location . lastIndexOf ( ' ' ) ; String query = null ; if ( pos >= 0 ) { query = trueurl . substring ( pos + 1 , trueurl . length ( ) ) ; trueurl = trueurl . substring ( 0 , pos ) ; } if ( fragment != null ) svctype = searchFragment ( fragment ) ; if ( svctype == null ) // See if leading protocol tells us how to interpret svctype = decodeLeadProtocol ( leadprotocol ) ; if ( svctype == null ) // See if path tells us how to interpret svctype = searchPath ( trueurl ) ; if ( svctype == null ) { //There are several possibilities at this point; all of which // require further info to disambiguate //  - we have file://<path> or file:<path>; we need to see if //    the extension can help, otherwise, start defaulting. //  - we have a simple url: e.g. http://... ; contact the server if ( leadprotocol . equals ( \"file\" ) ) { svctype = decodePathExtension ( trueurl ) ; // look at the path extension if ( svctype == null && checkIfNcml ( new File ( location ) ) ) { svctype = ServiceType . NCML ; } } else { svctype = disambiguateHttp ( trueurl ) ; // special cases if ( ( svctype == null || svctype == ServiceType . HTTPServer ) ) { // ncml file being served over http? if ( checkIfRemoteNcml ( trueurl ) ) { svctype = ServiceType . NCML ; } } } } if ( svctype == ServiceType . NCML ) { // ?? // If lead protocol was null and then pretend it was a file // Note that technically, this should be 'file://' trueurl = ( allprotocols . size ( ) == 0 ? \"file:\" + trueurl : location ) ; } // Add back the query and fragment (if any) if ( query != null || fragment != null ) { StringBuilder buf = new StringBuilder ( trueurl ) ; if ( query != null ) { buf . append ( ' ' ) ; buf . append ( query ) ; } if ( fragment != null ) { buf . append ( ' ' ) ; buf . append ( fragment ) ; } trueurl = buf . toString ( ) ; } return new DatasetUrl ( svctype , trueurl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a location find markers indicated which protocol to use LOOK what use case is this handling ? [CODESPLIT] static private ServiceType searchFragment ( String fragment ) { if ( fragment . length ( ) == 0 ) return null ; Map < String , String > map = parseFragment ( fragment ) ; if ( map == null ) return null ; String protocol = map . get ( \"protocol\" ) ; if ( protocol == null ) { for ( String p : FRAGPROTOCOLS ) { if ( map . get ( p ) != null ) { protocol = p ; break ; } } } if ( protocol != null ) { if ( protocol . equalsIgnoreCase ( \"dap\" ) || protocol . equalsIgnoreCase ( \"dods\" ) ) return ServiceType . OPENDAP ; if ( protocol . equalsIgnoreCase ( \"dap4\" ) ) return ServiceType . DAP4 ; if ( protocol . equalsIgnoreCase ( \"cdmremote\" ) ) return ServiceType . CdmRemote ; if ( protocol . equalsIgnoreCase ( \"thredds\" ) ) return ServiceType . THREDDS ; if ( protocol . equalsIgnoreCase ( \"ncml\" ) ) return ServiceType . NCML ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given the fragment part of a url see if it parses as name = value pairs separated by & ( same as query part ) . [CODESPLIT] static private Map < String , String > parseFragment ( String fragment ) { Map < String , String > map = new HashMap <> ( ) ; if ( fragment != null && fragment . length ( ) >= 0 ) { if ( fragment . charAt ( 0 ) == ' ' ) fragment = fragment . substring ( 1 ) ; String [ ] pairs = fragment . split ( \"[ \\t]*[&][ \\t]*\" ) ; for ( String pair : pairs ) { String [ ] pieces = pair . split ( \"[ \\t]*[=][ \\t]*\" ) ; switch ( pieces . length ) { case 1 : map . put ( EscapeStrings . unescapeURL ( pieces [ 0 ] ) . toLowerCase ( ) , \"true\" ) ; break ; case 2 : map . put ( EscapeStrings . unescapeURL ( pieces [ 0 ] ) . toLowerCase ( ) , EscapeStrings . unescapeURL ( pieces [ 1 ] ) . toLowerCase ( ) ) ; break ; default : return null ; // does not parse } } } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a url search the path to look for protocol indicators [CODESPLIT] static private ServiceType searchPath ( String url ) { if ( false ) { // Disable for now if ( url == null || url . length ( ) == 0 ) return null ; url = url . toLowerCase ( ) ; // for matching purposes for ( int i = 0 ; i < FRAGPROTOCOLS . length ; i ++ ) { String p = FRAGPROTOCOLS [ i ] ; if ( url . indexOf ( \"/thredds/\" + p . toLowerCase ( ) + \"/\" ) >= 0 ) { return FRAGPROTOSVCTYPE [ i ] ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check path extension ; assumes no query or fragment [CODESPLIT] static private ServiceType decodePathExtension ( String path ) { // Look at the path extensions if ( path . endsWith ( \".dds\" ) || path . endsWith ( \".das\" ) || path . endsWith ( \".dods\" ) ) return ServiceType . OPENDAP ; if ( path . endsWith ( \".dmr\" ) || path . endsWith ( \".dap\" ) || path . endsWith ( \".dsr\" ) ) return ServiceType . DAP4 ; if ( path . endsWith ( \".xml\" ) || path . endsWith ( \".ncml\" ) ) return ServiceType . NCML ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Attempt to map a leading url protocol url to a service type ( see thredds . catalog . ServiceType ) . Possible service types should include at least the following . <ol > <li > OPENDAP ( DAP2 protocol ) <li > DAP4 ( DAP4 protocol ) <li > CdmRemote ( remote ncstream ) < / ol > [CODESPLIT] @ Urlencoded static private ServiceType decodeLeadProtocol ( String protocol ) throws IOException { if ( protocol . equals ( \"dods\" ) ) return ServiceType . OPENDAP ; else if ( protocol . equals ( \"dap4\" ) ) return ServiceType . DAP4 ; else if ( protocol . equals ( \"httpserver\" ) || protocol . equals ( \"nodods\" ) ) return ServiceType . HTTPServer ; else if ( protocol . equals ( CdmRemote . PROTOCOL ) ) return ServiceType . CdmRemote ; else if ( protocol . equals ( DataFactory . PROTOCOL ) ) //thredds return ServiceType . THREDDS ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the URL alone is not sufficient to disambiguate the location then this method will attempt to do a specific kind of request on the server typically a HEAD call using the URL . It finds the header Content - Description and uses it value ( e . g . ncstream or dods etc ) in order to disambiguate . [CODESPLIT] @ Urlencoded static private ServiceType disambiguateHttp ( String location ) throws IOException { boolean checkDap2 = false , checkDap4 = false , checkCdmr = false ; // some TDS specific tests if ( location . contains ( \"cdmremote\" ) ) { ServiceType result = checkIfCdmr ( location ) ; if ( result != null ) return result ; checkCdmr = true ; } if ( location . contains ( \"dodsC\" ) ) { ServiceType result = checkIfDods ( location ) ; if ( result != null ) return result ; checkDap2 = true ; } if ( location . contains ( \"dap4\" ) ) { ServiceType result = checkIfDap4 ( location ) ; if ( result != null ) return result ; checkDap4 = true ; } if ( ! checkDap2 ) { ServiceType result = checkIfDods ( location ) ; if ( result != null ) return result ; } if ( ! checkDap4 ) { ServiceType result = checkIfDap4 ( location ) ; if ( result != null ) return result ; } if ( ! checkCdmr ) { ServiceType result = checkIfCdmr ( location ) ; if ( result != null ) return result ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cdmremote [CODESPLIT] static private ServiceType checkIfCdmr ( String location ) throws IOException { try ( HTTPMethod method = HTTPFactory . Head ( location + \"?req=header\" ) ) { int statusCode = method . execute ( ) ; if ( statusCode >= 300 ) { if ( statusCode == HttpStatus . SC_UNAUTHORIZED || statusCode == HttpStatus . SC_FORBIDDEN ) throw new IOException ( \"Unauthorized to open dataset \" + location ) ; else throw new IOException ( location + \" is not a valid URL, return status=\" + statusCode ) ; } Header h = method . getResponseHeader ( \"Content-Description\" ) ; if ( ( h != null ) && ( h . getValue ( ) != null ) ) { String v = h . getValue ( ) ; if ( v . equalsIgnoreCase ( \"ncstream\" ) ) return ServiceType . CdmRemote ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not sure what other opendap servers do so fall back on check for dds [CODESPLIT] static private ServiceType checkIfDods ( String location ) throws IOException { int len = location . length ( ) ; // Strip off any trailing .dds, .das, or .dods if ( location . endsWith ( \".dds\" ) ) location = location . substring ( 0 , len - \".dds\" . length ( ) ) ; if ( location . endsWith ( \".das\" ) ) location = location . substring ( 0 , len - \".das\" . length ( ) ) ; if ( location . endsWith ( \".dods\" ) ) location = location . substring ( 0 , len - \".dods\" . length ( ) ) ; // Opendap assumes that the caller has properly escaped the url try ( // For some reason, the head method is not using credentials // method = session.newMethodHead(location + \".dds\"); HTTPMethod method = HTTPFactory . Get ( location + \".dds\" ) ) { int status = method . execute ( ) ; if ( status == 200 ) { Header h = method . getResponseHeader ( \"Content-Description\" ) ; if ( ( h != null ) && ( h . getValue ( ) != null ) ) { String v = h . getValue ( ) ; if ( v . equalsIgnoreCase ( \"dods-dds\" ) || v . equalsIgnoreCase ( \"dods_dds\" ) ) return ServiceType . OPENDAP ; else throw new IOException ( \"OPeNDAP Server Error= \" + method . getResponseAsString ( ) ) ; } } if ( status == HttpStatus . SC_UNAUTHORIZED || status == HttpStatus . SC_FORBIDDEN ) throw new IOException ( \"Unauthorized to open dataset \" + location ) ; // not dods return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check for dmr [CODESPLIT] static private ServiceType checkIfDap4 ( String location ) throws IOException { // Strip off any trailing DAP4 prefix if ( location . endsWith ( \".dap\" ) ) location = location . substring ( 0 , location . length ( ) - \".dap\" . length ( ) ) ; else if ( location . endsWith ( \".dmr\" ) ) location = location . substring ( 0 , location . length ( ) - \".dmr\" . length ( ) ) ; else if ( location . endsWith ( \".dmr.xml\" ) ) location = location . substring ( 0 , location . length ( ) - \".dmr.xml\" . length ( ) ) ; else if ( location . endsWith ( \".dsr\" ) ) location = location . substring ( 0 , location . length ( ) - \".dsr\" . length ( ) ) ; try ( HTTPMethod method = HTTPFactory . Get ( location + \".dmr.xml\" ) ) { int status = method . execute ( ) ; if ( status == 200 ) { Header h = method . getResponseHeader ( \"Content-Type\" ) ; if ( ( h != null ) && ( h . getValue ( ) != null ) ) { String v = h . getValue ( ) ; if ( v . startsWith ( \"application/vnd.opendap.org\" ) ) return ServiceType . DAP4 ; } } if ( status == HttpStatus . SC_UNAUTHORIZED || status == HttpStatus . SC_FORBIDDEN ) throw new IOException ( \"Unauthorized to open dataset \" + location ) ; // not dods return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK compression not used [CODESPLIT] public long sendData2 ( Variable v , Section section , OutputStream out , NcStreamCompression compress ) throws IOException , InvalidRangeException { if ( show ) System . out . printf ( \" %s section=%s%n\" , v . getFullName ( ) , section ) ; boolean isVlen = v . isVariableLength ( ) ; //  && v.getRank() > 1;\r if ( isVlen ) v . read ( section ) ; NcStreamDataCol encoder = new NcStreamDataCol ( ) ; NcStreamProto . DataCol dataProto = encoder . encodeData2 ( v . getFullName ( ) , isVlen , section , v . read ( section ) ) ; // LOOK trap error, write error message ??\r // dataProto.writeDelimitedTo(out);\r long size = 0 ; size += writeBytes ( out , NcStream . MAGIC_DATA2 ) ; // data version 3\r byte [ ] datab = dataProto . toByteArray ( ) ; size += NcStream . writeVInt ( out , datab . length ) ; // dataProto len\r size += writeBytes ( out , datab ) ; // dataProto\r return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return last name part of an fqn ; result will be escaped . [CODESPLIT] static public String fqnSuffix ( String fqn ) { int structindex = fqn . lastIndexOf ( ' ' ) ; int groupindex = fqn . lastIndexOf ( ' ' ) ; if ( structindex >= 0 ) return fqn . substring ( structindex + 1 , fqn . length ( ) ) ; else return fqn . substring ( groupindex + 1 , fqn . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return prefix name part of an fqn ; result will be escaped . [CODESPLIT] static public String fqnPrefix ( String fqn ) { int structindex = fqn . lastIndexOf ( ' ' ) ; int groupindex = fqn . lastIndexOf ( ' ' ) ; if ( structindex >= 0 ) return fqn . substring ( 0 , structindex ) ; else return fqn . substring ( 0 , groupindex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walk the specified subtree dir tree to try to locate file|dir named filename . Use breadth first search . [CODESPLIT] static public String locateFile ( String filename , String abspath , boolean wantdir ) { Deque < String > q = new ArrayDeque < String > ( ) ; // clean up the path and filename filename = filename . trim ( ) . replace ( ' ' , ' ' ) ; abspath = abspath . trim ( ) . replace ( ' ' , ' ' ) ; if ( filename . charAt ( 0 ) == ' ' ) filename = filename . substring ( 1 ) ; if ( filename . endsWith ( \"/\" ) ) filename = filename . substring ( 0 , filename . length ( ) - 1 ) ; if ( abspath . endsWith ( \"/\" ) ) abspath = abspath . substring ( 0 , abspath . length ( ) - 1 ) ; q . addFirst ( abspath ) ; // prime the search queue for ( ; ; ) { // breadth first search String currentpath = q . poll ( ) ; if ( currentpath == null ) break ; // done searching File current = new File ( currentpath ) ; File [ ] contents = current . listFiles ( ) ; if ( contents != null ) { for ( File subfile : contents ) { if ( ! subfile . getName ( ) . equals ( filename ) ) continue ; if ( ( wantdir && subfile . isDirectory ( ) ) || ( ! wantdir && subfile . isFile ( ) ) ) { // Assume this is it return DapUtil . canonicalpath ( subfile . getAbsolutePath ( ) ) ; } } for ( File subfile : contents ) { if ( subfile . isDirectory ( ) ) q . addFirst ( currentpath + \"/\" + subfile . getName ( ) ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walk the specified dir tree to locate file specified by relative path . Use breadth first search . [CODESPLIT] static public String locateRelative ( String relpath , String abspath , boolean wantdir ) { // clean up the path and filename relpath = relpath . trim ( ) . replace ( ' ' , ' ' ) ; if ( relpath . charAt ( 0 ) == ' ' ) relpath = relpath . substring ( 1 ) ; if ( relpath . endsWith ( \"/\" ) ) relpath = relpath . substring ( 0 , relpath . length ( ) - 1 ) ; String [ ] pieces = relpath . split ( \"[/]\" ) ; String partial = abspath ; for ( int i = 0 ; i < pieces . length - 1 ; i ++ ) { String nextdir = locateFile ( pieces [ i ] , abspath , true ) ; if ( nextdir == null ) return null ; partial = nextdir ; } // See if the final file|dir exists in this dir String finalpath = locateFile ( pieces [ pieces . length - 1 ] , partial , wantdir ) ; return finalpath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert path to : 1 . use / consistently 2 . remove any trailing / 3 . trim blanks 4 . Be aware of possible windows drive letter [CODESPLIT] static public String canonicalpath ( String path ) { if ( path == null ) return null ; path = path . trim ( ) ; path = path . replace ( ' ' , ' ' ) ; if ( path . endsWith ( \"/\" ) ) path = path . substring ( 0 , path . length ( ) - 1 ) ; boolean abs = ( path . length ( ) > 0 && path . charAt ( 0 ) == ' ' ) ; if ( abs ) path = path . substring ( 1 ) ; // temporary if ( DapUtil . hasDriveLetter ( path ) ) { // As a last step, lowercase the drive letter, if any path = path . substring ( 0 , 1 ) . toLowerCase ( ) + path . substring ( 1 ) ; } else if ( abs ) path = \"/\" + path ; return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Properly extract the byte contents of a ByteBuffer [CODESPLIT] static public byte [ ] extract ( ByteBuffer buf ) { int len = buf . limit ( ) ; byte [ ] bytes = new byte [ len ] ; buf . rewind ( ) ; buf . get ( bytes ) ; return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a dap variable get the path from the top - level variable to and including the given variable such that all but the last element is a structure . [CODESPLIT] static public List < DapVariable > getStructurePath ( DapVariable var ) { List < DapNode > path = var . getPath ( ) ; List < DapVariable > structpath = new ArrayList < DapVariable > ( ) ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { DapNode node = path . get ( i ) ; switch ( node . getSort ( ) ) { case DATASET : case GROUP : break ; case VARIABLE : structpath . add ( ( DapVariable ) node ) ; break ; default : assert false : \"Internal error\" ; } } return structpath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert paths to null [CODESPLIT] static public String nullify ( String path ) { return ( path != null && path . length ( ) == 0 ? null : path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test a List<Slice > against set of DapDimensions to see if the list is whole wrt the dimensions [CODESPLIT] static public boolean isWhole ( List < Slice > slices , List < DapDimension > dimset ) { if ( slices . size ( ) != dimset . size ( ) ) return false ; for ( int i = 0 ; i < slices . size ( ) ; i ++ ) { Slice slice = slices . get ( i ) ; DapDimension dim = dimset . get ( i ) ; if ( slice . getStride ( ) != 1 || slice . getFirst ( ) != 0 || slice . getCount ( ) != dim . getSize ( ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an Array of Strings and a separator and a count concat the first count elements of an array with separator between them . A null string is treated like . [CODESPLIT] static public String join ( String [ ] array , String sep , int from , int upto ) { if ( sep == null ) sep = \"\" ; if ( from < 0 || upto > array . length ) throw new IndexOutOfBoundsException ( ) ; if ( upto <= from ) return \"\" ; StringBuilder result = new StringBuilder ( ) ; boolean first = true ; for ( int i = from ; i < upto ; i ++ , first = false ) { if ( ! first ) result . append ( sep ) ; result . append ( array [ i ] ) ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return true if this path appears to start with a windows drive letter [CODESPLIT] static public boolean hasDriveLetter ( String path ) { boolean hasdr = false ; if ( path != null && path . length ( ) >= 2 ) { hasdr = ( DRIVELETTERS . indexOf ( path . charAt ( 0 ) ) >= 0 && path . charAt ( 1 ) == ' ' ) ; } return hasdr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the set of leading protocols for a url ; may be more than one . [CODESPLIT] static public List < String > getProtocols ( String url , int [ ] breakpoint ) { // break off any leading protocols; // there may be more than one. // Watch out for Windows paths starting with a drive letter. // Each protocol has trailing ':'  removed List < String > allprotocols = new ArrayList <> ( ) ; // all leading protocols upto path or host // Note, we cannot use split because of the context sensitivity StringBuilder buf = new StringBuilder ( url ) ; int protosize = 0 ; for ( ; ; ) { int index = buf . indexOf ( \":\" ) ; if ( index < 0 ) break ; // no more protocols String protocol = buf . substring ( 0 , index ) ; // Check for windows drive letter if ( index == 1 //=>|protocol| == 1 => windows drive letter && \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\" . indexOf ( buf . charAt ( 0 ) ) >= 0 ) break ; allprotocols . add ( protocol ) ; buf . delete ( 0 , index + 1 ) ; // remove the leading protocol protosize += ( index + 1 ) ; if ( buf . indexOf ( \"/\" ) == 0 ) break ; // anything after this is not a protocol } breakpoint [ 0 ] = protosize ; return allprotocols ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provide a helper function to convert an Index object to a slice list . [CODESPLIT] static public List < Slice > indexToSlices ( Index indices , DapVariable template ) throws dap4 . core . util . DapException { List < DapDimension > dims = template . getDimensions ( ) ; List < Slice > slices = indexToSlices ( indices , dims ) ; return slices ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provide a helper function to convert an offset to a slice list . [CODESPLIT] static public List < Slice > offsetToSlices ( long offset , DapVariable template ) throws DapException { List < DapDimension > dims = template . getDimensions ( ) ; long [ ] dimsizes = DapUtil . getDimSizes ( dims ) ; return indexToSlices ( offsetToIndex ( offset , dimsizes ) , template ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an offset ( single index ) and a set of dimensions compute the set of dimension indices that correspond to the offset . [CODESPLIT] static public Index offsetToIndex ( long offset , long [ ] dimsizes ) { // offset = d3*(d2*(d1*(x1))+x2)+x3 long [ ] indices = new long [ dimsizes . length ] ; for ( int i = dimsizes . length - 1 ; i >= 0 ; i -- ) { indices [ i ] = offset % dimsizes [ i ] ; offset = ( offset - indices [ i ] ) / dimsizes [ i ] ; } return new Index ( indices , dimsizes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an offset ( single index ) and a set of dimensions compute the set of dimension indices that correspond to the offset . [CODESPLIT] static public List < Slice > indexToSlices ( Index indices ) throws DapException { // short circuit the scalar case if ( indices . getRank ( ) == 0 ) return Slice . SCALARSLICES ; // offset = d3*(d2*(d1*(x1))+x2)+x3 List < Slice > slices = new ArrayList <> ( indices . rank ) ; for ( int i = 0 ; i < indices . rank ; i ++ ) { long isize = indices . indices [ i ] ; slices . add ( new Slice ( isize , isize + 1 , 1 , indices . dimsizes [ i ] ) ) ; } return slices ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if a set of slices represent a contiguous region This is equivalent to saying all strides are one [CODESPLIT] static public boolean isContiguous ( List < Slice > slices ) { for ( Slice sl : slices ) { if ( sl . getStride ( ) != 1 ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if a set of slices represent a single position [CODESPLIT] static public boolean isSinglePoint ( List < Slice > slices ) { for ( Slice sl : slices ) { if ( sl . getCount ( ) != 1 ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a set of slices refers to a single position then return the corresponding Index . Otherwise throw Exception . [CODESPLIT] static public Index slicesToIndex ( List < Slice > slices ) throws DapException { long [ ] positions = new long [ slices . size ( ) ] ; long [ ] dimsizes = new long [ slices . size ( ) ] ; for ( int i = 0 ; i < positions . length ; i ++ ) { Slice s = slices . get ( i ) ; if ( s . getCount ( ) != 1 ) throw new DapException ( \"Attempt to convert non-singleton sliceset to index\" ) ; positions [ i ] = s . getFirst ( ) ; dimsizes [ i ] = s . getMax ( ) ; } return new Index ( positions , dimsizes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the result of a data request . Only one variable at a time . [CODESPLIT] public DataResult readData ( InputStream is , NetcdfFile ncfile , String location ) throws IOException { byte [ ] b = new byte [ 4 ] ; int bytesRead = NcStream . readFully ( is , b ) ; if ( bytesRead < b . length ) throw new EOFException ( location ) ; if ( NcStream . test ( b , NcStream . MAGIC_DATA ) ) return readData1 ( is , ncfile ) ; if ( NcStream . test ( b , NcStream . MAGIC_DATA2 ) ) return readData2 ( is ) ; throw new IOException ( \"Data transfer corrupted on \" + location ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK [CODESPLIT] public StructureDataIterator getStructureIterator ( InputStream is , NetcdfFile ncfile ) throws IOException { if ( ! NcStream . readAndTest ( is , NcStream . MAGIC_DATA ) ) throw new IOException ( \"Data transfer corrupted on \" + ncfile . getLocation ( ) ) ; int psize = NcStream . readVInt ( is ) ; if ( debug ) System . out . println ( \"  readData data message len= \" + psize ) ; byte [ ] dp = new byte [ psize ] ; NcStream . readFully ( is , dp ) ; NcStreamProto . Data dproto = NcStreamProto . Data . parseFrom ( dp ) ; // if (debug) System.out.println(\" readData proto = \" + dproto);\r Structure s = ( Structure ) ncfile . findVariable ( dproto . getVarName ( ) ) ; StructureMembers members = s . makeStructureMembers ( ) ; ArrayStructureBB . setOffsets ( members ) ; ByteOrder bo = NcStream . decodeDataByteOrder ( dproto ) ; return new StreamDataIterator ( is , members , bo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////// [CODESPLIT] private NetcdfFile proto2nc ( NcStreamProto . Header proto , NetcdfFile ncfile ) throws InvalidProtocolBufferException { if ( ncfile == null ) ncfile = new NetcdfFileSubclass ( ) ; // not used i think\r ncfile . setLocation ( proto . getLocation ( ) ) ; if ( proto . getId ( ) . length ( ) > 0 ) ncfile . setId ( proto . getId ( ) ) ; if ( proto . getTitle ( ) . length ( ) > 0 ) ncfile . setTitle ( proto . getTitle ( ) ) ; NcStreamProto . Group root = proto . getRoot ( ) ; NcStream . readGroup ( root , ncfile , ncfile . getRootGroup ( ) ) ; ncfile . finish ( ) ; return ncfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XML document from this info [CODESPLIT] public Document makeDocument ( ) { Element rootElem = new Element ( \"pointConfig\" ) ; Document doc = new Document ( rootElem ) ; if ( tableConfigurerClass != null ) rootElem . addContent ( new Element ( \"tableConfigurer\" ) . setAttribute ( \"class\" , tableConfigurerClass ) ) ; if ( tc . featureType != null ) rootElem . setAttribute ( \"featureType\" , tc . featureType . toString ( ) ) ; rootElem . addContent ( writeTable ( tc ) ) ; return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * MAGIC_START version sizeIndex BufrCdmIndexProto ( sizeIndex bytes ) [CODESPLIT] private boolean writeIndex2 ( String bufrFilename , BufrConfig config , File indexFile ) throws IOException { if ( indexFile . exists ( ) ) { if ( ! indexFile . delete ( ) ) log . warn ( \" BufrCdmIndex cant delete index file {}\" , indexFile . getPath ( ) ) ; } log . debug ( \" createIndex for {}\" , indexFile . getPath ( ) ) ; try ( RandomAccessFile raf = new RandomAccessFile ( indexFile . getPath ( ) , \"rw\" ) ) { raf . order ( RandomAccessFile . BIG_ENDIAN ) ; //// header message raf . write ( MAGIC_START . getBytes ( CDM . utf8Charset ) ) ; raf . writeInt ( version ) ; // build it BufrCdmIndexProto . BufrIndex . Builder indexBuilder = BufrCdmIndexProto . BufrIndex . newBuilder ( ) ; indexBuilder . setFilename ( bufrFilename ) ; root = buildField ( config . getRootConverter ( ) ) ; indexBuilder . setRoot ( root ) ; indexBuilder . setStart ( config . getStart ( ) ) ; indexBuilder . setEnd ( config . getEnd ( ) ) ; indexBuilder . setNobs ( config . getNobs ( ) ) ; Map < String , BufrConfig . BufrStation > smaps = config . getStationMap ( ) ; if ( smaps != null ) { List < BufrConfig . BufrStation > stations = new ArrayList < BufrConfig . BufrStation > ( smaps . values ( ) ) ; Collections . sort ( stations ) ; for ( BufrConfig . BufrStation s : stations ) { indexBuilder . addStations ( buildStation ( s ) ) ; } } // write it BufrCdmIndexProto . BufrIndex index = indexBuilder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; NcStream . writeVInt ( raf , b . length ) ; // message size raf . write ( b ) ; // message  - all in one gulp log . debug ( \"  file size =  %d bytes\" , raf . length ( ) ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create new ArrayDouble with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayDouble factory ( Index index , double [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayDouble . D0 ( index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayDouble . D1 ( index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayDouble . D2 ( index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayDouble . D3 ( index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayDouble . D4 ( index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayDouble . D5 ( index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayDouble . D6 ( index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayDouble . D7 ( index , storage ) ; } else { return new ArrayDouble ( index , storage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { double [ ] ja = ( double [ ] ) javaArray ; for ( double aJa : ja ) iter . setDoubleNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set extra information used by station obs datasets . Use stnIdVName or stnIndexVName . [CODESPLIT] public void setStationInfo ( String stnIdVName , String stnDescVName , String stnIndexVName , StationHelper stationHelper ) { this . stnIdVName = stnIdVName ; this . stnDescVName = stnDescVName ; this . stnIndexVName = stnIndexVName ; this . stationHelper = stationHelper ; if ( stnIdVName != null ) { Variable stationVar = ncfile . findVariable ( stnIdVName ) ; stationIdType = stationVar . getDataType ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "access it members [CODESPLIT] public void setShortNames ( String latVName , String lonVName , String altVName , String obsTimeVName , String nomTimeVName ) { this . latVName = latVName ; this . lonVName = lonVName ; this . zcoordVName = altVName ; this . obsTimeVName = obsTimeVName ; this . nomTimeVName = nomTimeVName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public PointFeature factory ( StationImpl s , StructureData sdata , int recno ) { if ( s == null ) return new RecordPointObs ( sdata , recno ) ; else return new RecordStationObs ( s , sdata , recno ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . <p / > <h2 > Important Note< / h2 > This method overrides the BaseType method of the same name and type signature and it significantly changes the behavior for all versions of <code > printVal () < / code > for this type : <b > <i > All the various versions of printVal () will only print a value or a value with declaration if the variable is in the projection . < / i > < / b > <br > <br > In other words if a call to <code > isProject () < / code > for a particular variable returns <code > true< / code > then <code > printVal () < / code > will print a value ( or a declaration and a value ) . <br > <br > If <code > isProject () < / code > for a particular variable returns <code > false< / code > then <code > printVal () < / code > is basically a No - Op . <br > <br > [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; PrimitiveVector pv = getPrimitiveVector ( ) ; if ( pv instanceof BaseTypePrimitiveVector ) { BaseTypePrimitiveVector vals = ( BaseTypePrimitiveVector ) pv ; if ( print_decl_p ) { printDecl ( os , space , false , true ) ; os . print ( \" = \" ) ; } os . print ( \"{ \" ) ; //vals.printVal(os, \"\"); ServerMethods sm ; int len = vals . getLength ( ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) { sm = ( ServerMethods ) vals . getValue ( i ) ; if ( sm . isProject ( ) ) { ( ( BaseType ) sm ) . printVal ( os , \"\" , false ) ; os . print ( \", \" ) ; } } // print last value, if any, without trailing comma if ( len > 0 ) { sm = ( ServerMethods ) vals . getValue ( len - 1 ) ; if ( sm . isProject ( ) ) { ( ( BaseType ) sm ) . printVal ( os , \"\" , false ) ; } } os . print ( \"}\" ) ; if ( print_decl_p ) os . println ( \";\" ) ; } else { super . printVal ( os , space , print_decl_p ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read NCEP mnemonic BUFR tables . [CODESPLIT] public static boolean read ( InputStream ios , BufrTables . Tables tables ) throws IOException { if ( ios == null ) return false ; if ( tables . b == null ) tables . b = new TableB ( \"fake\" , \"fake\" ) ; if ( tables . d == null ) tables . d = new TableD ( \"fake\" , \"fake\" ) ; HashMap < String , String > number = new HashMap <> ( ) ; // key = mnemonic value = fxy\r HashMap < String , String > desc = new HashMap <> ( ) ; // key = mnemonic value = description\r HashMap < String , String > mnseq = new HashMap <> ( ) ; try { BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( ios , CDM . utf8Charset ) ) ; // read  mnemonic table\r Matcher m ; // read header info and disregard\r while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) throw new RuntimeException ( \"Bad NCEP mnemonic BUFR table \" ) ; if ( line . contains ( \"MNEMONIC\" ) ) break ; } // read mnemonic, number, and description\r //| HEADR    | 362001 | TABLE D ENTRY - PROFILE COORDINATES                      |\r while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; if ( line . contains ( \"MNEMONIC\" ) ) break ; if ( line . contains ( \"----\" ) ) continue ; if ( line . startsWith ( \"*\" ) ) continue ; if ( line . startsWith ( \"|       \" ) ) continue ; m = fields3 . matcher ( line ) ; if ( m . find ( ) ) { String mnu = m . group ( 1 ) . trim ( ) ; String fxy = m . group ( 2 ) . trim ( ) ; if ( fxy . startsWith ( \"3\" ) ) { number . put ( mnu , fxy ) ; desc . put ( mnu , m . group ( 3 ) . replace ( \"TABLE D ENTRY - \" , \"\" ) . trim ( ) ) ; } else if ( fxy . startsWith ( \"0\" ) ) { number . put ( mnu , fxy ) ; desc . put ( mnu , m . group ( 3 ) . replace ( \"TABLE B ENTRY - \" , \"\" ) . trim ( ) ) ; } else if ( fxy . startsWith ( \"A\" ) ) { number . put ( mnu , fxy ) ; desc . put ( mnu , m . group ( 3 ) . replace ( \"TABLE A ENTRY - \" , \"\" ) . trim ( ) ) ; } } else if ( debugTable ) { System . out . println ( \"bad mnemonic, number, and description: \" + line ) ; } } // read in sequences using mnemonics\r //| ETACLS1  | HEADR {PROFILE} SURF FLUX HYDR D10M {SLYR} XTRA                   |\r while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; if ( line . contains ( \"MNEMONIC\" ) ) break ; if ( line . contains ( \"----\" ) ) continue ; if ( line . startsWith ( \"|       \" ) ) continue ; if ( line . startsWith ( \"*\" ) ) continue ; m = fields2 . matcher ( line ) ; if ( m . find ( ) ) { String mnu = m . group ( 1 ) . trim ( ) ; if ( mnseq . containsKey ( mnu ) ) { // concat lines with same mnu\r String value = mnseq . get ( mnu ) ; value = value + \" \" + m . group ( 2 ) ; mnseq . put ( mnu , value ) ; } else { mnseq . put ( mnu , m . group ( 2 ) ) ; } } else if ( debugTable ) { System . out . println ( \"bad sequence mnemonic: \" + line ) ; } } // create sequences, replacing mnemonics with numbers\r for ( Map . Entry < String , String > ent : mnseq . entrySet ( ) ) { String seq = ent . getValue ( ) ; seq = seq . replaceAll ( \"\\\\<\" , \"1-1-0 0-31-0 \" ) ; seq = seq . replaceAll ( \"\\\\>\" , \"\" ) ; seq = seq . replaceAll ( \"\\\\{\" , \"1-1-0 0-31-1 \" ) ; seq = seq . replaceAll ( \"\\\\}\" , \"\" ) ; seq = seq . replaceAll ( \"\\\\(\" , \"1-1-0 0-31-2 \" ) ; seq = seq . replaceAll ( \"\\\\)\" , \"\" ) ; StringTokenizer stoke = new StringTokenizer ( seq , \" \" ) ; List < Short > list = new ArrayList <> ( ) ; while ( stoke . hasMoreTokens ( ) ) { String mn = stoke . nextToken ( ) ; if ( mn . charAt ( 1 ) == ' ' ) { list . add ( Descriptor . getFxy ( mn ) ) ; continue ; } // element descriptor needs hyphens\r m = ints6 . matcher ( mn ) ; if ( m . find ( ) ) { String F = mn . substring ( 0 , 1 ) ; String X = removeLeading0 ( mn . substring ( 1 , 3 ) ) ; String Y = removeLeading0 ( mn . substring ( 3 ) ) ; list . add ( Descriptor . getFxy ( F + \"-\" + X + \"-\" + Y ) ) ; continue ; } if ( mn . startsWith ( \"\\\"\" ) ) { int idx = mn . lastIndexOf ( ' ' ) ; String count = mn . substring ( idx + 1 ) ; list . add ( Descriptor . getFxy ( \"1-1-\" + count ) ) ; mn = mn . substring ( 1 , idx ) ; } if ( mn . startsWith ( \".\" ) ) { String des = mn . substring ( mn . length ( ) - 4 ) ; mn = mn . replace ( des , \"....\" ) ; } String fxy = number . get ( mn ) ; String F = fxy . substring ( 0 , 1 ) ; String X = removeLeading0 ( fxy . substring ( 1 , 3 ) ) ; String Y = removeLeading0 ( fxy . substring ( 3 ) ) ; list . add ( Descriptor . getFxy ( F + \"-\" + X + \"-\" + Y ) ) ; } String fxy = number . get ( ent . getKey ( ) ) ; String X = removeLeading0 ( fxy . substring ( 1 , 3 ) ) ; String Y = removeLeading0 ( fxy . substring ( 3 ) ) ; // these are in latest tables\r if ( XlocalCutoff > Integer . parseInt ( X ) && YlocalCutoff > Integer . parseInt ( Y ) ) continue ; //key = F + \"-\" + X + \"-\" + Y;\r short seqX = Short . parseShort ( X . trim ( ) ) ; short seqY = Short . parseShort ( Y . trim ( ) ) ; tables . d . addDescriptor ( seqX , seqY , ent . getKey ( ) , list ) ; //short id = Descriptor.getFxy(key);\r //sequences.put(Short.valueOf(id), tableD);\r } // add some static repetition sequences\r // LOOK why?\r List < Short > list = new ArrayList <> ( ) ; // 16 bit delayed repetition\r list . add ( Descriptor . getFxy ( \"1-1-0\" ) ) ; list . add ( Descriptor . getFxy ( \"0-31-2\" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 1 , \"\" , list ) ; //tableD = new DescriptorTableD(\"\", \"3-60-1\", list, false);\r //tableD.put( \"3-60-1\", d);\r //short id = Descriptor.getFxy(\"3-60-1\");\r //sequences.put(Short.valueOf(id), tableD);\r list = new ArrayList <> ( ) ; // 8 bit delayed repetition\r list . add ( Descriptor . getFxy ( \"1-1-0\" ) ) ; list . add ( Descriptor . getFxy ( \"0-31-1\" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 2 , \"\" , list ) ; //tableD = new DescriptorTableD(\"\", \"3-60-2\", list, false);\r //tableD.put( \"3-60-2\", d);\r //id = Descriptor.getFxy(\"3-60-2\");\r //sequences.put(Short.valueOf(id), tableD);\r list = new ArrayList <> ( ) ; // 8 bit delayed repetition\r list . add ( Descriptor . getFxy ( \"1-1-0\" ) ) ; list . add ( Descriptor . getFxy ( \"0-31-1\" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 3 , \"\" , list ) ; //tableD = new DescriptorTableD(\"\", \"3-60-3\", list, false);\r //tableD.put( \"3-60-3\", d);\r //id = Descriptor.getFxy(\"3-60-3\");\r //sequences.put(Short.valueOf(id), tableD);\r list = new ArrayList <> ( ) ; // 1 bit delayed repetition\r list . add ( Descriptor . getFxy ( \"1-1-0\" ) ) ; list . add ( Descriptor . getFxy ( \"0-31-0\" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 4 , \"\" , list ) ; //tableD = new DescriptorTableD(\"\", \"3-60-4\", list, false);\r //tableD.put( \"3-60-4\", d);\r //id = Descriptor.getFxy(\"3-60-4\");\r //sequences.put(Short.valueOf(id), tableD);\r // add in element descriptors\r //  MNEMONIC | SCAL | REFERENCE   | BIT | UNITS\r //| FTIM     |    0 |           0 |  24 | SECONDS                  |-------------|\r //tableB = new TableB(tablename, tablename);\r while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; if ( line . contains ( \"MNEMONIC\" ) ) break ; if ( line . startsWith ( \"|       \" ) ) continue ; if ( line . startsWith ( \"*\" ) ) continue ; m = fields5 . matcher ( line ) ; if ( m . find ( ) ) { if ( m . group ( 1 ) . equals ( \"\" ) ) { continue ; } else if ( number . containsKey ( m . group ( 1 ) . trim ( ) ) ) { // add descriptor to tableB\r String fxy = number . get ( m . group ( 1 ) . trim ( ) ) ; String X = fxy . substring ( 1 , 3 ) ; String Y = fxy . substring ( 3 ) ; String mnu = m . group ( 1 ) . trim ( ) ; String descr = desc . get ( mnu ) ; short x = Short . parseShort ( X . trim ( ) ) ; short y = Short . parseShort ( Y . trim ( ) ) ; // these are in latest tables so skip  LOOK WHY\r if ( XlocalCutoff > x && YlocalCutoff > y ) continue ; int scale = Integer . parseInt ( m . group ( 2 ) . trim ( ) ) ; int refVal = Integer . parseInt ( m . group ( 3 ) . trim ( ) ) ; int width = Integer . parseInt ( m . group ( 4 ) . trim ( ) ) ; String units = m . group ( 5 ) . trim ( ) ; tables . b . addDescriptor ( x , y , scale , refVal , width , mnu , units , descr ) ; } else if ( debugTable ) { System . out . println ( \"bad element descriptors: \" + line ) ; } } } } finally { ios . close ( ) ; } // LOOK why ?\r // default for NCEP\r // 0; 63; 0; 0; 0; 16; Numeric; Byte count\r tables . b . addDescriptor ( ( short ) 63 , ( short ) 0 , 0 , 0 , 16 , \"Byte count\" , \"Numeric\" , null ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read NCEP mnemonic BUFR tables . [CODESPLIT] private static void readSubCategories ( String fileIn , PrintStream out , String token ) throws IOException { System . out . printf ( \"%s%n\" , fileIn ) ; try ( FileInputStream in = new FileInputStream ( fileIn ) ) { BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( in , CDM . utf8Charset ) ) ; while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; int posb = line . indexOf ( \"DISCONTINUED\" ) ; if ( posb > 0 ) continue ; posb = line . indexOf ( \"NO LONGER\" ) ; if ( posb > 0 ) continue ; posb = line . indexOf ( \"WAS REPLACED\" ) ; if ( posb > 0 ) continue ; int pos = line . indexOf ( token ) ; if ( pos < 0 ) continue ; System . out . printf ( \"%s%n\" , line ) ; boolean is31 = token . equals ( \"031-\" ) ; String subline = is31 ? line . substring ( pos ) : line . substring ( pos + token . length ( ) ) ; //if (is31) System.out.printf(\" '%s'%n\", subline);\r int pos2 = subline . indexOf ( ' ' ) ; String catS = subline . substring ( 0 , pos2 ) ; String desc = subline . substring ( pos2 + 1 ) ; //System.out.printf(\"   cat='%s'%n\", catS);\r //System.out.printf(\"  desc='%s'%n\", desc);\r int cat = Integer . parseInt ( catS . substring ( 0 , 3 ) ) ; int subcat = Integer . parseInt ( catS . substring ( 4 , 7 ) ) ; desc = StringUtil2 . remove ( desc , ' ' ) . trim ( ) ; //System.out.printf(\"  cat=%d subcat=%d%n\", cat,subcat);\r //System.out.printf(\"  desc='%s'%n\", desc);\r //System.out.printf(\"%d, %d, %s%n\", cat, subcat, desc);\r out . printf ( \"%d; %d; %s%n\" , cat , subcat , desc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Field construction [CODESPLIT] public HTTPFormBuilder add ( String fieldname , String text ) throws HTTPException { if ( fieldname == null || text == null || fieldname . length ( ) == 0 ) throw new IllegalArgumentException ( ) ; Field f = new Field ( Sort . TEXT , fieldname , text , null ) ; parts . put ( fieldname , f ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "input is xml file with just the <featureCollection > [CODESPLIT] public FeatureCollectionConfig readConfigFromFile ( String filename ) { org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( filename ) ; } catch ( Exception e ) { System . out . printf ( \"Error parsing featureCollection %s err = %s\" , filename , e . getMessage ( ) ) ; return null ; } return readConfig ( doc . getRootElement ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a catalog and extract a FeatureCollectionConfig from it [CODESPLIT] public FeatureCollectionConfig readConfigFromCatalog ( String catalogAndPath ) { String catFilename ; String fcName = null ; int pos = catalogAndPath . indexOf ( \"#\" ) ; if ( pos > 0 ) { catFilename = catalogAndPath . substring ( 0 , pos ) ; fcName = catalogAndPath . substring ( pos + 1 ) ; } else { catFilename = catalogAndPath ; } File cat = new File ( catFilename ) ; org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( cat ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } try { List < Element > fcElems = new ArrayList <> ( ) ; findFeatureCollection ( doc . getRootElement ( ) , fcName , fcElems ) ; if ( fcElems . size ( ) > 0 ) return readConfig ( fcElems . get ( 0 ) ) ; } catch ( IllegalStateException e ) { e . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add single declaration [CODESPLIT] public void addDecl ( DapNode newdecl ) throws DapException { DapSort newsort = newdecl . getSort ( ) ; String newname = newdecl . getShortName ( ) ; boolean suppress = false ; // Look for name conflicts (ignore anonymous dimensions) if ( newsort != DapSort . DIMENSION || newname != null ) { for ( DapNode decl : decls ) { if ( newsort == decl . getSort ( ) && newname . equals ( decl . getShortName ( ) ) ) throw new DapException ( \"DapGroup: attempt to add duplicate decl: \" + newname ) ; } } else { // Anonymous DapDimension anon = ( DapDimension ) newdecl ; assert ( newsort == DapSort . DIMENSION && newname == null ) ; // Search for matching anonymous dimension boolean found = false ; for ( DapDimension dim : dimensions ) { if ( ! dim . isShared ( ) && dim . getSize ( ) == anon . getSize ( ) ) { found = true ; break ; } } // Define the anondecl in root group if ( ! found && ! isTopLevel ( ) ) getDataset ( ) . addDecl ( anon ) ; suppress = found || ! isTopLevel ( ) ; } if ( ! suppress ) { decls . add ( newdecl ) ; newdecl . setParent ( this ) ; // Cross link } switch ( newdecl . getSort ( ) ) { case ATTRIBUTE : case ATTRIBUTESET : case OTHERXML : super . addAttribute ( ( DapAttribute ) newdecl ) ; break ; case DIMENSION : if ( ! suppress ) dimensions . add ( ( DapDimension ) newdecl ) ; break ; case ENUMERATION : enums . add ( ( DapEnumeration ) newdecl ) ; break ; case ATOMICTYPE : break ; // do nothing case STRUCTURE : case SEQUENCE : compounds . add ( ( DapStructure ) newdecl ) ; break ; case VARIABLE : variables . add ( ( DapVariable ) newdecl ) ; break ; case GROUP : case DATASET : if ( this != ( DapGroup ) newdecl ) groups . add ( ( DapGroup ) newdecl ) ; break ; default : throw new ClassCastException ( newdecl . getShortName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We will need to re - order the groups [CODESPLIT] void updateGroups ( List < DapGroup > groups ) { // Verify that the incoming groups are all and only in the list of groups. assert ( groups . size ( ) == this . groups . size ( ) ) : \"Update groups: not same size\" ; for ( DapGroup g : groups ) { if ( ! this . groups . contains ( g ) ) assert ( false ) : \"Update groups: attempt to add new group\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an FQN and use it to trace to a specific object in a dataset . Absolute FQN paths are passed to DapDataset . findByFQN () . Relative FQNs are assumed to be WRT to the FQN of this node [CODESPLIT] public DapNode findByFQN ( String fqn , DapSort ... sortset ) throws DapException { fqn = fqn . trim ( ) ; if ( fqn == null ) return null ; if ( fqn . charAt ( 0 ) != ' ' ) { String prefix = this . getFQN ( ) ; fqn = prefix + ' ' + fqn ; } return getDataset ( ) . lookup ( fqn , sortset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locate a variable in this group [CODESPLIT] public DapVariable findVariable ( String name ) { DapNode var = findInGroup ( name , DapSort . VARIABLE ) ; return ( DapVariable ) var ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private boolean compare ( List<Dimension > dims1 List<Dimension > dims2 ) { if ( dims1 . size () ! = dims2 . size () ) return false ; for ( int i = 0 ; i < dims1 . size () ; i ++ ) { Dimension dim1 = dims1 . get ( i ) ; Dimension dim2 = dims2 . get ( i ) ; if ( !dim1 . getName () . equals ( dim2 . getName () )) return false ; if ( dim1 . getLength () ! = dim2 . getLength () ) return false ; } return true ; } [CODESPLIT] private boolean compareGroups ( Group org , Group copy , ObjFilter filter ) { if ( showCompare ) f . format ( \"compare Group %s to %s %n\" , org . getShortName ( ) , copy . getShortName ( ) ) ; boolean ok = true ; if ( ! org . getShortName ( ) . equals ( copy . getShortName ( ) ) ) { f . format ( \" ** names are different %s != %s %n\" , org . getShortName ( ) , copy . getShortName ( ) ) ; ok = false ; } // dimensions\r ok &= checkDimensions ( org . getDimensions ( ) , copy . getDimensions ( ) ) ; ok &= checkDimensions ( copy . getDimensions ( ) , org . getDimensions ( ) ) ; // attributes\r ok &= checkAttributes ( null , org . getAttributes ( ) , copy . getAttributes ( ) , filter ) ; // enums\r ok &= checkEnums ( org , copy ) ; // variables\r // cant use object equality, just match on short name\r for ( Variable orgV : org . getVariables ( ) ) { Variable copyVar = copy . findVariable ( orgV . getShortName ( ) ) ; if ( copyVar == null ) { f . format ( \" ** cant find variable %s in 2nd file%n\" , orgV . getFullName ( ) ) ; ok = false ; } else { ok &= compareVariables ( orgV , copyVar , filter , compareData , true ) ; } } for ( Variable copyV : copy . getVariables ( ) ) { Variable orgV = org . findVariable ( copyV . getShortName ( ) ) ; if ( orgV == null ) { f . format ( \" ** cant find variable %s in 1st file%n\" , copyV . getFullName ( ) ) ; ok = false ; } } // nested groups\r List groups = new ArrayList ( ) ; String name = org . isRoot ( ) ? \"root\" : org . getFullName ( ) ; ok &= checkAll ( name , org . getGroups ( ) , copy . getGroups ( ) , groups ) ; for ( int i = 0 ; i < groups . size ( ) ; i += 2 ) { Group orgGroup = ( Group ) groups . get ( i ) ; Group copyGroup = ( Group ) groups . get ( i + 1 ) ; ok &= compareGroups ( orgGroup , copyGroup , filter ) ; } return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return an arrayList of paired objects . [CODESPLIT] private boolean checkAttributes ( Variable v , List < Attribute > list1 , List < Attribute > list2 , ObjFilter filter ) { boolean ok = true ; String name = v == null ? \"global\" : \"variable \" + v . getFullName ( ) ; for ( Attribute att1 : list1 ) { if ( filter == null || filter . attCheckOk ( v , att1 ) ) ok &= checkEach ( name , att1 , \"file1\" , list1 , \"file2\" , list2 , null ) ; } for ( Attribute att2 : list2 ) { if ( filter == null || filter . attCheckOk ( v , att2 ) ) ok &= checkEach ( name , att2 , \"file2\" , list2 , \"file1\" , list1 , null ) ; } return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return an arrayList of paired objects . [CODESPLIT] private boolean checkEnums ( Group org , Group copy ) { boolean ok = true ; for ( EnumTypedef enum1 : org . getEnumTypedefs ( ) ) { if ( showCompare ) f . format ( \"compare Enum %s%n\" , enum1 . getShortName ( ) ) ; EnumTypedef enum2 = copy . findEnumeration ( enum1 . getShortName ( ) ) ; if ( enum2 == null ) { f . format ( \"  ** Enum %s not in file2 %n\" , enum1 . getShortName ( ) ) ; ok = false ; continue ; } if ( ! enum1 . equals ( enum2 ) ) { f . format ( \"  ** Enum %s not equal%n  %s%n  %s%n\" , enum1 . getShortName ( ) , enum1 , enum2 ) ; ok = false ; } } for ( EnumTypedef enum2 : copy . getEnumTypedefs ( ) ) { EnumTypedef enum1 = org . findEnumeration ( enum2 . getShortName ( ) ) ; if ( enum1 == null ) { f . format ( \"  ** Enum %s not in file1 %n\" , enum2 . getShortName ( ) ) ; ok = false ; } } return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return an arrayList of paired objects . [CODESPLIT] private boolean checkAll ( String what , List list1 , List list2 , List result ) { boolean ok = true ; for ( Object aList1 : list1 ) { ok &= checkEach ( what , aList1 , \"file1\" , list1 , \"file2\" , list2 , result ) ; } for ( Object aList2 : list2 ) { ok &= checkEach ( what , aList2 , \"file2\" , list2 , \"file1\" , list1 , null ) ; } return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check that want is in both list1 and list2 using object . equals () [CODESPLIT] private boolean checkEach ( String what , Object want1 , String name1 , List list1 , String name2 , List list2 , List result ) { boolean ok = true ; try { int index2 = list2 . indexOf ( want1 ) ; if ( index2 < 0 ) { f . format ( \"  ** %s: %s 0x%x (%s) not in %s %n\" , what , want1 , want1 . hashCode ( ) , name1 , name2 ) ; ok = false ; } else { // found it in second list\r Object want2 = list2 . get ( index2 ) ; int index1 = list1 . indexOf ( want2 ) ; if ( index1 < 0 ) { // can this happen ??\r f . format ( \"  ** %s: %s 0x%x (%s) not in %s %n\" , what , want2 , want2 . hashCode ( ) , name2 , name1 ) ; ok = false ; } else { // found it in both lists\r Object want = list1 . get ( index1 ) ; if ( ! want . equals ( want1 ) ) { f . format ( \"  ** %s: %s 0x%x (%s) not equal to %s 0x%x (%s) %n\" , what , want1 , want1 . hashCode ( ) , name1 , want2 , want2 . hashCode ( ) , name2 ) ; ok = false ; } else { if ( showEach ) f . format ( \"  OK <%s> equals <%s>%n\" , want1 , want2 ) ; if ( result != null ) { result . add ( want1 ) ; result . add ( want2 ) ; } } } } } catch ( Throwable t ) { t . printStackTrace ( ) ; f . format ( \" *** Throwable= %s %n\" , t . getMessage ( ) ) ; } return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The COARDS standard offers limited support for climatological time . For compatibility with COARDS time coordinates should also be recognised as climatological if they have a units attribute of time - units relative to midnight on 1 January in year 0 i . e . since 0 - 1 - 1 in udunits syntax and provided they refer to the real - world calendar . We do not recommend this convention because ( a ) it does not provide any information about the intervals used to compute the climatology and ( b ) there is no standard for how dates since year 1 will be encoded with units having a reference time in year 0 since this year does not exist ; consequently there may be inconsistencies among software packages in the interpretation of the time coordinates . Year 0 may be a valid year in non - real - world calendars and therefore cannot be used to signal climatological time in such cases . [CODESPLIT] public static boolean isMine ( String hasName ) { if ( hasName . equalsIgnoreCase ( \"COARDS\" ) ) return true ; List < String > names = breakupConventionNames ( hasName ) ; for ( String name : names ) { if ( name . equalsIgnoreCase ( \"COARDS\" ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we assume that coordinate axes get identified by being coordinate variables [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ncDataset , VariableEnhanced v ) { String unit = v . getUnitsString ( ) ; if ( unit == null ) return null ; unit = unit . trim ( ) ; if ( unit . equalsIgnoreCase ( \"degrees_east\" ) || unit . equalsIgnoreCase ( \"degrees_E\" ) || unit . equalsIgnoreCase ( \"degreesE\" ) || unit . equalsIgnoreCase ( \"degree_east\" ) || unit . equalsIgnoreCase ( \"degree_E\" ) || unit . equalsIgnoreCase ( \"degreeE\" ) ) return AxisType . Lon ; if ( unit . equalsIgnoreCase ( \"degrees_north\" ) || unit . equalsIgnoreCase ( \"degrees_N\" ) || unit . equalsIgnoreCase ( \"degreesN\" ) || unit . equalsIgnoreCase ( \"degree_north\" ) || unit . equalsIgnoreCase ( \"degree_N\" ) || unit . equalsIgnoreCase ( \"degreeN\" ) ) return AxisType . Lat ; if ( SimpleUnit . isDateUnit ( unit ) ) { return AxisType . Time ; } // look for other z coordinate\r if ( SimpleUnit . isCompatible ( \"mbar\" , unit ) ) return AxisType . Pressure ; if ( unit . equalsIgnoreCase ( \"level\" ) || unit . equalsIgnoreCase ( \"layer\" ) || unit . equalsIgnoreCase ( \"sigma_level\" ) ) return AxisType . GeoZ ; String positive = ncDataset . findAttValueIgnoreCase ( ( Variable ) v , CF . POSITIVE , null ) ; if ( positive != null ) { if ( SimpleUnit . isCompatible ( \"m\" , unit ) ) return AxisType . Height ; else return AxisType . GeoZ ; } // a bad idea, but CDC SST relies on it :\r // :Source = \"NOAA/National Climatic Data Center\";\r // :Contact = \"Dick Reynolds, email: Richard.W.Reynolds@noaa.gov & Chunying Liu, email: Chunying.liu@noaa.gov\";\r //:netcdf_Convention = \"COARDS\";\r // if (checkForMeter && SimpleUnit.isCompatible(\"m\", unit))\r //   return AxisType.Height;\r return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The time unit statistical type derived from code table 5 ) [CODESPLIT] @ Nullable public static GribStatType getStatType ( int timeRangeIndicator ) { switch ( timeRangeIndicator ) { case 3 : case 6 : case 7 : case 51 : case 113 : case 115 : case 117 : case 120 : case 123 : return GribStatType . Average ; case 4 : case 114 : case 116 : case 124 : return GribStatType . Accumulation ; case 5 : return GribStatType . DifferenceFromEnd ; case 118 : return GribStatType . Covariance ; case 119 : case 125 : return GribStatType . StandardDeviation ; default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public Optional < HorizCoordSys > subset ( SubsetParams params ) { LatLonRect llbb = ( LatLonRect ) params . get ( SubsetParams . latlonBB ) ; ProjectionRect projbb = ( ProjectionRect ) params . get ( SubsetParams . projBB ) ; LatLonPoint latlon = ( LatLonPoint ) params . get ( SubsetParams . latlonPoint ) ; Integer horizStride = ( Integer ) params . get ( SubsetParams . horizStride ) ; if ( horizStride == null || horizStride < 1 ) horizStride = 1 ; CoverageCoordAxis1D xaxisSubset = null , yaxisSubset = null ; CoverageCoordAxis lataxisSubset = null , lonaxisSubset = null ; Optional < CoverageCoordAxis > opt ; Optional < CoverageCoordAxisBuilder > optb ; Formatter errMessages = new Formatter ( ) ; try { if ( latlon != null ) { // overrides other horiz subset params if ( isProjection ) { CoordAxisHelper xhelper = new CoordAxisHelper ( xAxis ) ; CoordAxisHelper yhelper = new CoordAxisHelper ( yAxis ) ; // we have to transform latlon to projection coordinates ProjectionImpl proj = transform . getProjection ( ) ; ProjectionPoint pp = proj . latLonToProj ( latlon ) ; optb = xhelper . subsetContaining ( pp . getX ( ) ) ; if ( optb . isPresent ( ) ) xaxisSubset = new CoverageCoordAxis1D ( optb . get ( ) ) ; else errMessages . format ( \"xaxis: %s;%n\" , optb . getErrorMessage ( ) ) ; optb = yhelper . subsetContaining ( pp . getY ( ) ) ; if ( optb . isPresent ( ) ) yaxisSubset = new CoverageCoordAxis1D ( optb . get ( ) ) ; else errMessages . format ( \"yaxis: %s;%n\" , optb . getErrorMessage ( ) ) ; } else { CoordAxisHelper xhelper = new CoordAxisHelper ( lonAxis ) ; CoordAxisHelper yhelper = new CoordAxisHelper ( latAxis ) ; double lonNormal = LatLonPointImpl . lonNormalFrom ( latlon . getLongitude ( ) , lonAxis . getStartValue ( ) ) ; optb = xhelper . subsetContaining ( lonNormal ) ; if ( optb . isPresent ( ) ) lonaxisSubset = new CoverageCoordAxis1D ( optb . get ( ) ) ; else errMessages . format ( \"lonaxis: %s;%n\" , optb . getErrorMessage ( ) ) ; optb = yhelper . subsetContaining ( latlon . getLatitude ( ) ) ; if ( optb . isPresent ( ) ) lataxisSubset = new CoverageCoordAxis1D ( optb . get ( ) ) ; else errMessages . format ( \"lataxis: %s;%n\" , optb . getErrorMessage ( ) ) ; } } else if ( projbb != null ) { if ( isProjection ) { opt = xAxis . subset ( projbb . getMinX ( ) , projbb . getMaxX ( ) , horizStride ) ; if ( opt . isPresent ( ) ) xaxisSubset = ( CoverageCoordAxis1D ) opt . get ( ) ; else errMessages . format ( \"xaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; opt = yAxis . subset ( projbb . getMinY ( ) , projbb . getMaxY ( ) , horizStride ) ; if ( opt . isPresent ( ) ) yaxisSubset = ( CoverageCoordAxis1D ) opt . get ( ) ; else errMessages . format ( \"yaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; } /* else {  // WTF projbb on non Projection ?\n          ProjectionImpl proj = transform.getProjection();\n          LatLonRect llrect = proj.projToLatLonBB(projbb);\n          opt = lonaxis.subset(llrect.getLonMin(), llrect.getLonMax(), horizStride);\n          if (opt.isPresent()) lonaxisSubset = opt.get();\n          else errMessages.format(\"lonaxis: %s;%n\", opt.getErrorMessage());\n\n          opt = lataxis.subset(llrect.getLatMin(), llrect.getLatMax(), horizStride);\n          if (opt.isPresent()) lataxisSubset = opt.get();\n          else errMessages.format(\"lataxis: %s;%n\", opt.getErrorMessage());\n        } */ } else if ( llbb != null ) { LatLonRect full = calcLatLonBoundingBox ( ) ; assert full != null ; if ( ! full . containedIn ( llbb ) ) { // if request contains entire bb, then no subsetting needed if ( isProjection ) { // we have to transform latlon to projection coordinates ProjectionImpl proj = transform . getProjection ( ) ; ProjectionRect prect = proj . latLonToProjBB ( llbb ) ; // allow projection to override opt = xAxis . subset ( prect . getMinX ( ) , prect . getMaxX ( ) , horizStride ) ; if ( opt . isPresent ( ) ) xaxisSubset = ( CoverageCoordAxis1D ) opt . get ( ) ; else errMessages . format ( \"xaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; opt = yAxis . subset ( prect . getMinY ( ) , prect . getMaxY ( ) , horizStride ) ; if ( opt . isPresent ( ) ) yaxisSubset = ( CoverageCoordAxis1D ) opt . get ( ) ; else errMessages . format ( \"yaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; } else { opt = subsetLon ( llbb , horizStride ) ; if ( opt . isPresent ( ) ) lonaxisSubset = opt . get ( ) ; else errMessages . format ( \"lonaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; opt = latAxis . subset ( llbb . getLatMin ( ) , llbb . getLatMax ( ) , horizStride ) ; if ( opt . isPresent ( ) ) lataxisSubset = opt . get ( ) ; else errMessages . format ( \"lataxis: %s;%n\" , opt . getErrorMessage ( ) ) ; } } } else if ( horizStride > 1 ) { // no bounding box, just horiz stride if ( isProjection ) { opt = xAxis . subsetByIndex ( xAxis . getRange ( ) . setStride ( horizStride ) ) ; if ( opt . isPresent ( ) ) xaxisSubset = ( CoverageCoordAxis1D ) opt . get ( ) ; else errMessages . format ( \"xaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; opt = yAxis . subsetByIndex ( yAxis . getRange ( ) . setStride ( horizStride ) ) ; if ( opt . isPresent ( ) ) yaxisSubset = ( CoverageCoordAxis1D ) opt . get ( ) ; else errMessages . format ( \"yaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; } else { opt = lonAxis . subsetByIndex ( lonAxis . getRange ( ) . setStride ( horizStride ) ) ; if ( opt . isPresent ( ) ) lonaxisSubset = opt . get ( ) ; else errMessages . format ( \"lonaxis: %s;%n\" , opt . getErrorMessage ( ) ) ; opt = latAxis . subsetByIndex ( latAxis . getRange ( ) . setStride ( horizStride ) ) ; if ( opt . isPresent ( ) ) lataxisSubset = opt . get ( ) ; else errMessages . format ( \"lataxis: %s;%n\" , opt . getErrorMessage ( ) ) ; } } } catch ( InvalidRangeException e ) { errMessages . format ( \"%s;%n\" , e . getMessage ( ) ) ; } String errs = errMessages . toString ( ) ; if ( errs . length ( ) > 0 ) return Optional . empty ( errs ) ; // makes a copy of the axis if ( xaxisSubset == null && xAxis != null ) xaxisSubset = ( CoverageCoordAxis1D ) xAxis . copy ( ) ; if ( yaxisSubset == null && yAxis != null ) yaxisSubset = ( CoverageCoordAxis1D ) yAxis . copy ( ) ; if ( lataxisSubset == null && latAxis != null ) lataxisSubset = latAxis . copy ( ) ; if ( lonaxisSubset == null && lonAxis != null ) lonaxisSubset = lonAxis . copy ( ) ; return Optional . of ( new HorizCoordSys ( xaxisSubset , yaxisSubset , lataxisSubset , lonaxisSubset , transform ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "here s where to deal with crossing seam [CODESPLIT] private Optional < CoverageCoordAxis > subsetLon ( LatLonRect llbb , int stride ) throws InvalidRangeException { double wantMin = LatLonPointImpl . lonNormalFrom ( llbb . getLonMin ( ) , lonAxis . getStartValue ( ) ) ; double wantMax = LatLonPointImpl . lonNormalFrom ( llbb . getLonMax ( ) , lonAxis . getStartValue ( ) ) ; double start = lonAxis . getStartValue ( ) ; double end = lonAxis . getEndValue ( ) ; // use MAMath.MinMax as a container for two values, min and max List < MAMath . MinMax > lonIntvs = subsetLonIntervals ( wantMin , wantMax , start , end ) ; if ( lonIntvs . size ( ) == 0 ) return Optional . empty ( String . format ( \"longitude want [%f,%f] does not intersect lon axis [%f,%f]\" , wantMin , wantMax , start , end ) ) ; if ( lonIntvs . size ( ) == 1 ) { MAMath . MinMax lonIntv = lonIntvs . get ( 0 ) ; return lonAxis . subset ( lonIntv . min , lonIntv . max , stride ) ; } // this is the seam crossing case return lonAxis . subsetByIntervals ( lonIntvs , stride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * longitude subset after normalizing to start draw a circle representing longitude values from start to start + 360 . all values are on this circle and are > start . put start at bottom of circle end > start data has values from start counterclockwise to end . wantMin wantMax can be anywhere want goes from wantMin counterclockwise to wantMax . wantMin may be less than or greater than wantMax . [CODESPLIT] private List < MAMath . MinMax > subsetLonIntervals ( double wantMin , double wantMax , double start , double end ) { if ( wantMin <= wantMax ) { if ( wantMin > end && wantMax > end ) // none A.1 return Collections . EMPTY_LIST ; if ( wantMin < end && wantMax < end ) // A.2 return Lists . newArrayList ( new MAMath . MinMax ( wantMin , wantMax ) ) ; if ( wantMin < end && wantMax > end ) // A.3 return Lists . newArrayList ( new MAMath . MinMax ( wantMin , end ) ) ; } else { if ( wantMin > end && wantMax > end ) // all B.1 return Lists . newArrayList ( new MAMath . MinMax ( start , end ) ) ; if ( wantMin < end && wantMax < end ) { // B.2 return Lists . newArrayList ( new MAMath . MinMax ( wantMin , end ) , new MAMath . MinMax ( start , wantMax ) ) ; } if ( wantMin < end && wantMax > end ) // B.3 return Lists . newArrayList ( new MAMath . MinMax ( wantMin , end ) ) ; } // otherwise shouldnt get to this logger . error ( \"longitude want [%f,%f] does not intersect axis [%f,%f]\" , wantMin , wantMax , start , end ) ; return Collections . EMPTY_LIST ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return y x range [CODESPLIT] public List < RangeIterator > getRanges ( ) { List < RangeIterator > result = new ArrayList <> ( ) ; result . add ( getYAxis ( ) . getRange ( ) ) ; RangeIterator lonRange = getXAxis ( ) . getRangeIterator ( ) ; if ( lonRange == null ) lonRange = getXAxis ( ) . getRange ( ) ; // clumsy result . add ( lonRange ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the bounding box of this coordinate reference system in projection coordinates . If this CRS { @link #isProjection isn t a projection } than { @code null } is returned . [CODESPLIT] public ProjectionRect calcProjectionBoundingBox ( ) { if ( ! isProjection ) return null ; double minX = Math . min ( xAxis . getCoordEdgeFirst ( ) , xAxis . getCoordEdgeLast ( ) ) ; double minY = Math . min ( yAxis . getCoordEdgeFirst ( ) , yAxis . getCoordEdgeLast ( ) ) ; double width = Math . abs ( xAxis . getCoordEdgeLast ( ) - xAxis . getCoordEdgeFirst ( ) ) ; double height = Math . abs ( yAxis . getCoordEdgeLast ( ) - yAxis . getCoordEdgeFirst ( ) ) ; return new ProjectionRect ( new ProjectionPointImpl ( minX , minY ) , width , height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the bounding box of this coordinate reference system in latitude / longitude . This method properly handles coverages that straddle the international date line by deriving its bounding box from the { @link #calcConnectedLatLonBoundaryPoints ( int int ) connected latitude / longitude boundary } . <p > If this CRS { @link #isProjection is a projection } its lat / lon boundary is computed by converting each point in its { @link #calcProjectionBoundaryPoints () projection boundary } to latitude / longitude using the { @link Projection projection } . [CODESPLIT] public LatLonRect calcLatLonBoundingBox ( ) { double minLat = Double . MAX_VALUE ; double minLon = Double . MAX_VALUE ; double maxLat = - Double . MAX_VALUE ; double maxLon = - Double . MAX_VALUE ; for ( LatLonPointNoNormalize boundaryPoint : calcConnectedLatLonBoundaryPoints ( ) ) { minLat = Math . min ( minLat , boundaryPoint . getLatitude ( ) ) ; minLon = Math . min ( minLon , boundaryPoint . getLongitude ( ) ) ; maxLat = Math . max ( maxLat , boundaryPoint . getLatitude ( ) ) ; maxLon = Math . max ( maxLon , boundaryPoint . getLongitude ( ) ) ; } return new LatLonRect ( new LatLonPointImpl ( minLat , minLon ) , new LatLonPointImpl ( maxLat , maxLon ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the latitude / longitude boundary of this coordinate reference system . The boundary starts at the lower left corner of the coverage -- i . e . { @code ( y [ 0 ] x [ 0 ] ) } -- and consists of the points that lie along the bottom right top and left edges in that order . <p > The { @code maxPointsInYEdge } parameter establishes a limit on the number of boundary points that ll be included from the right and left edges . { @code maxPointsInXEdge } establishes a similar limit for the bottom and top edges . The size of the returned list will be { @code ≤ 2 * maxPointsInYEdge + 2 * maxPointsInXEdge } . Note that the corners are always included regardless of the arguments . If you wish to include ALL of the points along the edges in the boundary simply choose values for the parameters that are greater than the lengths of the corresponding axes in the CRS . { @link Integer#MAX_VALUE } works great . In that case the size of the returned list will be { @code 2 * numXcoords + 2 * numYcoords } . <p > If this CRS { @link #isProjection is a projection } the lat / lon boundary is computed by converting each point in its { @link #calcProjectionBoundaryPoints () projection boundary } to latitude / longitude using the { @link Projection projection } . <p > Points in the boundary will be { @link #connectLatLonPoints connected } . This facilitates proper interpretation of the boundary if it s rendered as a georeferenced polygon particularly when the boundary crosses the international date line . [CODESPLIT] public List < LatLonPointNoNormalize > calcConnectedLatLonBoundaryPoints ( int maxPointsInYEdge , int maxPointsInXEdge ) { List < LatLonPoint > points ; if ( isProjection ) { points = calcLatLonBoundaryPointsFromProjection ( maxPointsInYEdge , maxPointsInXEdge ) ; } else if ( isLatLon1D ) { points = calcLatLon1DBoundaryPoints ( maxPointsInYEdge , maxPointsInXEdge ) ; } else if ( isLatLon2D ) { points = calcLatLon2DBoundaryPoints ( maxPointsInYEdge , maxPointsInXEdge ) ; } else { throw new AssertionError ( \"HorizCoordSys was not a projection, latLon1D, or latLon2D.\" ) ; } return connectLatLonPoints ( points ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the boundary of this coordinate reference system in projection coordinates . The boundary starts at the lower left corner of the coverage -- i . e . { @code ( y [ 0 ] x [ 0 ] ) } -- and consists of the points that lie along the bottom right top and left edges in that order . <p > The { @code maxPointsInYEdge } parameter establishes a limit on the number of boundary points that ll be included from the right and left edges . { @code maxPointsInXEdge } establishes a similar limit for the bottom and top edges . The size of the returned list will be { @code ≤ 2 * maxPointsInYEdge + 2 * maxPointsInXEdge } . Note that the corners are always included regardless of the arguments . If you wish to include ALL of the points along the edges in the boundary simply choose values for the parameters that are greater than the lengths of the corresponding axes in the CRS . { @link Integer#MAX_VALUE } works great . In that case the size of the returned list will be { @code 2 * numXcoords + 2 * numYcoords } . [CODESPLIT] public List < ProjectionPoint > calcProjectionBoundaryPoints ( int maxPointsInYEdge , int maxPointsInXEdge ) { if ( ! isProjection ) { throw new UnsupportedOperationException ( \"Coordinate system is not a projection.\" ) ; } checkMaxPointsInEdges ( maxPointsInYEdge , maxPointsInXEdge ) ; int numYtotal = yAxis . getNcoords ( ) ; int numXtotal = xAxis . getNcoords ( ) ; int strideY = calcStride ( numYtotal , maxPointsInYEdge ) ; int strideX = calcStride ( numXtotal , maxPointsInXEdge ) ; List < ProjectionPoint > points = new LinkedList <> ( ) ; // Bottom boundary points for ( int i = 0 ; i < numXtotal ; i += strideX ) { points . add ( new ProjectionPointImpl ( xAxis . getCoordEdge1 ( i ) , yAxis . getCoordEdgeFirst ( ) ) ) ; } // Right boundary points for ( int j = 0 ; j < numYtotal ; j += strideY ) { points . add ( new ProjectionPointImpl ( xAxis . getCoordEdgeLast ( ) , yAxis . getCoordEdge1 ( j ) ) ) ; } // Top boundary points for ( int i = numXtotal - 1 ; i >= 0 ; i -= strideX ) { points . add ( new ProjectionPointImpl ( xAxis . getCoordEdge2 ( i ) , yAxis . getCoordEdgeLast ( ) ) ) ; } // Left boundary points for ( int j = numYtotal - 1 ; j >= 0 ; j -= strideY ) { points . add ( new ProjectionPointImpl ( xAxis . getCoordEdgeFirst ( ) , yAxis . getCoordEdge2 ( j ) ) ) ; } assertNotExceedingMaxBoundaryPoints ( points . size ( ) , maxPointsInYEdge , maxPointsInXEdge ) ; return points ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of points that is equivalent to the input list but with longitude values adjusted to ensure that adjacent elements are connected . <p > Two points are connected if the absolute difference of their { @link LatLonPointImpl#lonNormal normalized longitudes } is { @code ≤180 } . For example the longitudes { @code 112 } and { @code 124 } are connected . So are { @code 15 } and { @code - 27 } . <p > Two points may be disconnected if they lie on opposite sides of the international date line . For example the longitudes { @code 175 } and { @code - 175 } are disconnected because their absolute difference is { @code 350 } which is { @code > 180 } . To connect the two points we adjust the second longitude to an equivalent value in the range { @code [ firstLon ± 180 ] } by adding or subtracting { @code 360 } . So { @code - 175 } would become { @code 185 } . We perform this adjustment for each pair of adjacent elements in the list . <p > Performing the above adjustment will result in longitudes that lie outside of the normalized range of ( { @code [ - 180 180 ] } ) . To be precise if adjustments are necessary all of the longitudes in the returned list will be in either { @code [ - 360 0 ] } or { @code [ 0 360 ] } . Consequently adjusted points cannot be returned as { @link LatLonPoint } s ; they are returned as { @link LatLonPointNoNormalize } objects instead . <p > Longitudes { @code lon1 } and { @code lon2 } are considered equivalent if { @code lon1 == lon2 + 360 * i } for some integer { @code i } . [CODESPLIT] public static List < LatLonPointNoNormalize > connectLatLonPoints ( List < LatLonPoint > points ) { LinkedList < LatLonPointNoNormalize > connectedPoints = new LinkedList <> ( ) ; for ( LatLonPoint point : points ) { double curLat = point . getLatitude ( ) ; double curLon = point . getLongitude ( ) ; if ( ! connectedPoints . isEmpty ( ) ) { double prevLon = connectedPoints . getLast ( ) . getLongitude ( ) ; curLon = LatLonPointImpl . lonNormal ( curLon , prevLon ) ; } connectedPoints . add ( new LatLonPointNoNormalize ( curLat , curLon ) ) ; } return connectedPoints ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link #calcConnectedLatLonBoundaryPoints ( int int ) latitude / longitude boundary } of this coordinate reference system as a polygon in WKT . It is used in the OpenLayers map in NCSS as well as the datasetBoundaries endpoint . [CODESPLIT] public String getLatLonBoundaryAsWKT ( int maxPointsInYEdge , int maxPointsInXEdge ) { List < LatLonPointNoNormalize > points = calcConnectedLatLonBoundaryPoints ( maxPointsInYEdge , maxPointsInXEdge ) ; StringBuilder sb = new StringBuilder ( \"POLYGON((\" ) ; for ( LatLonPointNoNormalize point : points ) { sb . append ( String . format ( \"%.3f %.3f, \" , point . getLongitude ( ) , point . getLatitude ( ) ) ) ; } sb . delete ( sb . length ( ) - 2 , sb . length ( ) ) ; // Nuke trailing comma and space. sb . append ( \"))\" ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provide defaults for a settings map [CODESPLIT] static synchronized protected void setDefaults ( Map < Prop , Object > props ) { if ( false ) { // turn off for now props . put ( Prop . HANDLE_AUTHENTICATION , Boolean . TRUE ) ; } props . put ( Prop . HANDLE_REDIRECTS , Boolean . TRUE ) ; props . put ( Prop . ALLOW_CIRCULAR_REDIRECTS , Boolean . TRUE ) ; props . put ( Prop . MAX_REDIRECTS , ( Integer ) DFALTREDIRECTS ) ; props . put ( Prop . SO_TIMEOUT , ( Integer ) DFALTSOTIMEOUT ) ; props . put ( Prop . CONN_TIMEOUT , ( Integer ) DFALTCONNTIMEOUT ) ; props . put ( Prop . CONN_REQ_TIMEOUT , ( Integer ) DFALTCONNREQTIMEOUT ) ; props . put ( Prop . USER_AGENT , DFALTUSERAGENT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Timeouts [CODESPLIT] static synchronized public void setGlobalConnectionTimeout ( int timeout ) { if ( timeout >= 0 ) { globalsettings . put ( Prop . CONN_TIMEOUT , ( Integer ) timeout ) ; globalsettings . put ( Prop . CONN_REQ_TIMEOUT , ( Integer ) timeout ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compression [CODESPLIT] static synchronized public void setGlobalCompression ( String compressors ) { if ( globalsettings . get ( Prop . COMPRESSION ) != null ) removeGlobalCompression ( ) ; String compresslist = checkCompressors ( compressors ) ; if ( HTTPUtil . nullify ( compresslist ) == null ) throw new IllegalArgumentException ( \"Bad compressors: \" + compressors ) ; globalsettings . put ( Prop . COMPRESSION , compresslist ) ; HttpResponseInterceptor hrsi ; if ( compresslist . contains ( \"gzip\" ) ) { hrsi = new GZIPResponseInterceptor ( ) ; rspintercepts . add ( hrsi ) ; } if ( compresslist . contains ( \"deflate\" ) ) { hrsi = new DeflateResponseInterceptor ( ) ; rspintercepts . add ( hrsi ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It is convenient to be able to directly set the Credentials ( not the provider ) when those credentials are fixed . [CODESPLIT] static public void setGlobalCredentials ( Credentials creds , AuthScope scope ) throws HTTPException { assert ( creds != null ) ; if ( scope == null ) scope = AuthScope . ANY ; CredentialsProvider provider = new BasicCredentialsProvider ( ) ; provider . setCredentials ( scope , creds ) ; setGlobalCredentialsProvider ( provider , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interceptors : Only supported at global level [CODESPLIT] static protected void setInterceptors ( HttpClientBuilder cb ) { for ( HttpRequestInterceptor hrq : reqintercepts ) { cb . addInterceptorLast ( hrq ) ; } for ( HttpResponseInterceptor hrs : rspintercepts ) { cb . addInterceptorLast ( hrs ) ; } // Add debug interceptors for ( HttpRequestInterceptor hrq : dbgreq ) { cb . addInterceptorFirst ( hrq ) ; } for ( HttpResponseInterceptor hrs : dbgrsp ) { cb . addInterceptorFirst ( hrs ) ; } // Hack: add Content-Encoding suppressor cb . addInterceptorFirst ( CEKILL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the sessionid cookie value [CODESPLIT] public String getSessionID ( ) { String sid = null ; String jsid = null ; List < Cookie > cookies = this . sessioncontext . getCookieStore ( ) . getCookies ( ) ; for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equalsIgnoreCase ( \"sessionid\" ) ) sid = cookie . getValue ( ) ; if ( cookie . getName ( ) . equalsIgnoreCase ( \"jsessionid\" ) ) jsid = cookie . getValue ( ) ; } return ( sid == null ? jsid : sid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the max number of redirects to follow [CODESPLIT] public HTTPSession setMaxRedirects ( int n ) { if ( n < 0 ) //validate throw new IllegalArgumentException ( \"setMaxRedirects\" ) ; localsettings . put ( Prop . MAX_REDIRECTS , n ) ; this . cachevalid = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable / disable redirection following Default is yes . [CODESPLIT] public HTTPSession setFollowRedirects ( boolean tf ) { localsettings . put ( Prop . HANDLE_REDIRECTS , ( Boolean ) tf ) ; this . cachevalid = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should we use sessionid s? [CODESPLIT] public HTTPSession setUseSessions ( boolean tf ) { localsettings . put ( Prop . USESESSIONS , ( Boolean ) tf ) ; this . cachevalid = false ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the session . This implies closing any open methods . [CODESPLIT] synchronized public void close ( ) { if ( this . closed ) return ; // multiple calls ok closed = true ; for ( HTTPMethod m : this . methods ) { m . close ( ) ; // forcibly close; will invoke removemethod(). } methods . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the most general case [CODESPLIT] public HTTPSession setCredentialsProvider ( CredentialsProvider provider , AuthScope scope ) throws HTTPException { if ( provider == null ) throw new NullPointerException ( this . getClass ( ) . getName ( ) ) ; if ( scope == null ) scope = AuthScope . ANY ; localcreds . put ( scope , provider ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It is convenient to be able to directly set the Credentials ( not the provider ) when those credentials are fixed . [CODESPLIT] public HTTPSession setCredentials ( Credentials creds , AuthScope scope ) throws HTTPException { assert ( creds != null ) ; if ( scope == null ) scope = AuthScope . ANY ; CredentialsProvider provider = new BasicCredentialsProvider ( ) ; provider . setCredentials ( scope , creds ) ; setCredentialsProvider ( provider , scope ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle authentication and Proxy ing [CODESPLIT] synchronized protected void setAuthenticationAndProxy ( HttpClientBuilder cb ) throws HTTPException { // First, setup the ssl factory cb . setSSLSocketFactory ( ( SSLConnectionSocketFactory ) authcontrols . get ( AuthProp . SSLFACTORY ) ) ; // Second, Construct a CredentialsProvider that is // the union of the Proxy credentials plus // either the global or local credentials; local overrides global // Unfortunately, we cannot either clone or extract the contents // of the client supplied provider, so we are forced (for now) // to modify the client supplied provider. // Look in the local credentials first for for best scope match AuthScope bestMatch = HTTPAuthUtil . bestmatch ( scope , localcreds . keySet ( ) ) ; CredentialsProvider cp = null ; if ( bestMatch != null ) { cp = localcreds . get ( bestMatch ) ; } else { bestMatch = HTTPAuthUtil . bestmatch ( scope , globalcredfactories . keySet ( ) ) ; if ( bestMatch != null ) { HTTPProviderFactory factory = globalcredfactories . get ( bestMatch ) ; cp = factory . getProvider ( bestMatch ) ; } } // Build the proxy credentials and AuthScope Credentials proxycreds = null ; AuthScope proxyscope = null ; String user = ( String ) authcontrols . get ( AuthProp . PROXYUSER ) ; String pwd = ( String ) authcontrols . get ( AuthProp . PROXYPWD ) ; HttpHost httpproxy = ( HttpHost ) authcontrols . get ( AuthProp . HTTPPROXY ) ; HttpHost httpsproxy = ( HttpHost ) authcontrols . get ( AuthProp . HTTPSPROXY ) ; if ( user != null && ( httpproxy != null || httpsproxy != null ) ) { if ( httpproxy != null ) proxyscope = HTTPAuthUtil . hostToAuthScope ( httpproxy ) ; else //httpsproxy != null proxyscope = HTTPAuthUtil . hostToAuthScope ( httpsproxy ) ; proxycreds = new UsernamePasswordCredentials ( user , pwd ) ; } if ( cp == null && proxycreds != null && proxyscope != null ) { // If client provider is null and proxycreds are not, // then use proxycreds alone cp = new BasicCredentialsProvider ( ) ; cp . setCredentials ( proxyscope , proxycreds ) ; } else if ( cp != null && proxycreds != null && proxyscope != null ) { // If client provider is not null and proxycreds are not, // then add proxycreds to the client provider cp . setCredentials ( proxyscope , proxycreds ) ; } if ( cp != null ) this . sessioncontext . setCredentialsProvider ( cp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package scope [CODESPLIT] public Map < Prop , Object > mergedSettings ( ) { Map < Prop , Object > merged ; synchronized ( this ) { // keep coverity happy //Merge Settings; merged = HTTPUtil . merge ( globalsettings , localsettings ) ; } return Collections . unmodifiableMap ( merged ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] static String getCanonicalURL ( String legalurl ) { if ( legalurl == null ) return null ; int index = legalurl . indexOf ( ' ' ) ; if ( index >= 0 ) legalurl = legalurl . substring ( 0 , index ) ; // remove any trailing extension //index = legalurl.lastIndexOf('.'); //if(index >= 0) legalurl = legalurl.substring(0,index); return HTTPUtil . canonicalpath ( legalurl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If we are testing then track the sessions for kill [CODESPLIT] static protected synchronized void track ( HTTPSession session ) { if ( ! TESTING ) throw new UnsupportedOperationException ( ) ; if ( sessionList == null ) sessionList = new ConcurrentSkipListSet < HTTPSession > ( ) ; sessionList . add ( session ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Only allow if debugging [CODESPLIT] static public void clearkeystore ( ) { if ( ! TESTING ) throw new UnsupportedOperationException ( ) ; authcontrols . setReadOnly ( false ) ; authcontrols . remove ( AuthProp . KEYSTORE ) ; authcontrols . remove ( AuthProp . KEYPASSWORD ) ; authcontrols . remove ( AuthProp . TRUSTSTORE ) ; authcontrols . remove ( AuthProp . TRUSTPASSWORD ) ; authcontrols . setReadOnly ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Only allow if debugging [CODESPLIT] static public void rebuildkeystore ( String path , String pwd ) { if ( ! TESTING ) throw new UnsupportedOperationException ( ) ; KeyStore newks = buildkeystore ( path , pwd ) ; authcontrols . setReadOnly ( false ) ; authcontrols . put ( AuthProp . KEYSTORE , newks ) ; authcontrols . setReadOnly ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deprecated but here for back compatibility [CODESPLIT] @ Deprecated static public void setGlobalCredentialsProvider ( AuthScope scope , CredentialsProvider provider ) throws HTTPException { setGlobalCredentialsProvider ( provider , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obsolete [CODESPLIT] static protected synchronized void kill ( ) { if ( sessionList != null ) { for ( HTTPSession session : sessionList ) { session . close ( ) ; } sessionList . clear ( ) ; connmgr . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the most general case [CODESPLIT] @ Deprecated static public void setGlobalCredentialsProvider ( CredentialsProvider provider , AuthScope scope ) throws HTTPException { HTTPProviderFactory factory = new SingleProviderFactory ( provider ) ; setCredentialsProviderFactory ( factory , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private DqcFactory dqcFactory = null ; [CODESPLIT] void validate ( String urlString ) { if ( urlString == null ) return ; URI uri ; try { uri = new URI ( urlString ) ; } catch ( URISyntaxException e ) { javax . swing . JOptionPane . showMessageDialog ( null , \"URISyntaxException on URL (\" + urlString + \") \" + e . getMessage ( ) + \"\\n\" ) ; return ; } String contents = getText ( ) ; //boolean isCatalog = contents.indexOf(\"queryCapability\") < 0; ByteArrayInputStream is = new ByteArrayInputStream ( contents . getBytes ( CDM . utf8Charset ) ) ; try { CatalogBuilder catFactory = new CatalogBuilder ( ) ; Catalog cat = catFactory . buildFromLocation ( urlString , null ) ; boolean isValid = ! catFactory . hasFatalError ( ) ; javax . swing . JOptionPane . showMessageDialog ( this , \"Catalog Validation = \" + isValid + \"\\n\" + catFactory . getErrorMessage ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a subclass of Index optimized for this array s rank [CODESPLIT] static public Index factory ( int [ ] shape ) { int rank = shape . length ; switch ( rank ) { case 0 : return new Index0D ( ) ; case 1 : return new Index1D ( shape ) ; case 2 : return new Index2D ( shape ) ; case 3 : return new Index3D ( shape ) ; case 4 : return new Index4D ( shape ) ; case 5 : return new Index5D ( shape ) ; case 6 : return new Index6D ( shape ) ; case 7 : return new Index7D ( shape ) ; default : return new Index ( shape ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute standard strides based on array s shape . Ignore vlen [CODESPLIT] static private long computeStrides ( int [ ] shape , int [ ] stride ) { long product = 1 ; for ( int ii = shape . length - 1 ; ii >= 0 ; ii -- ) { final int thisDim = shape [ ii ] ; if ( thisDim < 0 ) continue ; // ignore vlen\r stride [ ii ] = ( int ) product ; product *= thisDim ; } return product ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Index based on current one except flip the index so that it runs from shape [ index ] - 1 to 0 . Leave rightmost vlen alone . [CODESPLIT] Index flip ( int index ) { if ( ( index < 0 ) || ( index >= rank ) ) throw new IllegalArgumentException ( ) ; Index i = ( Index ) this . clone ( ) ; if ( shape [ index ] >= 0 ) { // !vlen case\r i . offset += stride [ index ] * ( shape [ index ] - 1 ) ; i . stride [ index ] = - stride [ index ] ; } i . fastIterator = false ; i . precalc ( ) ; // any subclass-specific optimizations\r return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new Index based on a subsection of this one with rank reduction if dimension length == 1 . [CODESPLIT] Index section ( List < Range > ranges ) throws InvalidRangeException { // check ranges are valid\r if ( ranges . size ( ) != rank ) throw new InvalidRangeException ( \"Bad ranges [] length\" ) ; for ( int ii = 0 ; ii < rank ; ii ++ ) { Range r = ranges . get ( ii ) ; if ( r == null ) continue ; if ( r == Range . VLEN ) continue ; if ( ( r . first ( ) < 0 ) || ( r . first ( ) >= shape [ ii ] ) ) throw new InvalidRangeException ( \"Bad range starting value at index \" + ii + \" == \" + r . first ( ) ) ; if ( ( r . last ( ) < 0 ) || ( r . last ( ) >= shape [ ii ] ) ) throw new InvalidRangeException ( \"Bad range ending value at index \" + ii + \" == \" + r . last ( ) ) ; } int reducedRank = rank ; for ( Range r : ranges ) { if ( ( r != null ) && ( r . length ( ) == 1 ) ) reducedRank -- ; } Index newindex = Index . factory ( reducedRank ) ; newindex . offset = offset ; // calc shape, size, and index transformations\r // calc strides into original (backing) store\r int newDim = 0 ; for ( int ii = 0 ; ii < rank ; ii ++ ) { Range r = ranges . get ( ii ) ; if ( r == null ) { // null range means use the whole original dimension\r newindex . shape [ newDim ] = shape [ ii ] ; newindex . stride [ newDim ] = stride [ ii ] ; //if (name != null) newindex.name[newDim] = name[ii];\r newDim ++ ; } else if ( r . length ( ) != 1 ) { newindex . shape [ newDim ] = r . length ( ) ; newindex . stride [ newDim ] = stride [ ii ] * r . stride ( ) ; newindex . offset += stride [ ii ] * r . first ( ) ; //if (name != null) newindex.name[newDim] = name[ii];\r newDim ++ ; } else { newindex . offset += stride [ ii ] * r . first ( ) ; // constant due to rank reduction\r } } newindex . size = computeSize ( newindex . shape ) ; newindex . fastIterator = fastIterator && ( newindex . size == size ) ; // if equal, then its not a real subset, so can still use fastIterator\r newindex . precalc ( ) ; // any subclass-specific optimizations\r return newindex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Index based on current one by eliminating any dimensions with length one . [CODESPLIT] Index reduce ( ) { Index c = this ; for ( int ii = 0 ; ii < rank ; ii ++ ) if ( shape [ ii ] == 1 ) { // do this on the first one you find\r Index newc = c . reduce ( ii ) ; return newc . reduce ( ) ; // any more to do?\r } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Index based on current one by eliminating the specified dimension ; [CODESPLIT] Index reduce ( int dim ) { if ( ( dim < 0 ) || ( dim >= rank ) ) throw new IllegalArgumentException ( \"illegal reduce dim \" + dim ) ; if ( shape [ dim ] != 1 ) throw new IllegalArgumentException ( \"illegal reduce dim \" + dim + \" : length != 1\" ) ; Index newindex = Index . factory ( rank - 1 ) ; newindex . offset = offset ; int count = 0 ; for ( int ii = 0 ; ii < rank ; ii ++ ) { if ( ii != dim ) { newindex . shape [ count ] = shape [ ii ] ; newindex . stride [ count ] = stride [ ii ] ; //if (name != null) newindex.name[count] = name[ii];\r count ++ ; } } newindex . size = computeSize ( newindex . shape ) ; newindex . fastIterator = fastIterator ; newindex . precalc ( ) ; // any subclass-specific optimizations\r return newindex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new Index based on current one except transpose two of the indices . [CODESPLIT] Index transpose ( int index1 , int index2 ) { if ( ( index1 < 0 ) || ( index1 >= rank ) ) throw new IllegalArgumentException ( ) ; if ( ( index2 < 0 ) || ( index2 >= rank ) ) throw new IllegalArgumentException ( ) ; Index newIndex = ( Index ) this . clone ( ) ; newIndex . stride [ index1 ] = stride [ index2 ] ; newIndex . stride [ index2 ] = stride [ index1 ] ; newIndex . shape [ index1 ] = shape [ index2 ] ; newIndex . shape [ index2 ] = shape [ index1 ] ; /* if (name != null) {\r\n      newIndex.name[index1] = name[index2];\r\n      newIndex.name[index2] = name[index1];\r\n    } */ newIndex . fastIterator = false ; newIndex . precalc ( ) ; // any subclass-specific optimizations\r return newIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create a new Index based on a permutation of the current indices ; vlen fails . [CODESPLIT] Index permute ( int [ ] dims ) { if ( dims . length != shape . length ) throw new IllegalArgumentException ( ) ; for ( int dim : dims ) if ( ( dim < 0 ) || ( dim >= rank ) ) throw new IllegalArgumentException ( ) ; boolean isPermuted = false ; Index newIndex = ( Index ) this . clone ( ) ; for ( int i = 0 ; i < dims . length ; i ++ ) { newIndex . stride [ i ] = stride [ dims [ i ] ] ; newIndex . shape [ i ] = shape [ dims [ i ] ] ; //if (name != null) newIndex.name[i] = name[dims[i]];\r if ( i != dims [ i ] ) isPermuted = true ; } newIndex . fastIterator = fastIterator && ! isPermuted ; // useful optimization\r newIndex . precalc ( ) ; // any subclass-specific optimizations\r return newIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an index iterator for traversing the array in canonical order . [CODESPLIT] IndexIterator getIndexIterator ( Array maa ) { if ( fastIterator ) return new IteratorFast ( size , maa ) ; else return new IteratorImpl ( maa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current element s index into the 1D backing array . VLEN stops processing . [CODESPLIT] public int currentElement ( ) { int value = offset ; // NB: dont have to check each index again\r for ( int ii = 0 ; ii < rank ; ii ++ ) { // general rank\r if ( shape [ ii ] < 0 ) break ; //vlen\r value += current [ ii ] * stride [ ii ] ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the current counter from the 1D current element currElement = offset + stride [ 0 ] * current [ 0 ] + ... [CODESPLIT] public void setCurrentCounter ( int currElement ) { currElement -= offset ; for ( int ii = 0 ; ii < rank ; ii ++ ) { // general rank\r if ( shape [ ii ] < 0 ) { current [ ii ] = - 1 ; break ; } current [ ii ] = currElement / stride [ ii ] ; currElement -= current [ ii ] * stride [ ii ] ; } set ( current ) ; // transfer to subclass fields\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the current element s index . General - rank case . [CODESPLIT] public Index set ( int [ ] index ) { if ( index . length != rank ) throw new ArrayIndexOutOfBoundsException ( ) ; if ( rank == 0 ) return this ; int prefixrank = ( hasvlen ? rank : rank - 1 ) ; System . arraycopy ( index , 0 , current , 0 , prefixrank ) ; if ( hasvlen ) current [ prefixrank ] = - 1 ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set current element at dimension dim to v [CODESPLIT] public void setDim ( int dim , int value ) { if ( value < 0 || value >= shape [ dim ] ) // check index here\r throw new ArrayIndexOutOfBoundsException ( ) ; if ( shape [ dim ] >= 0 ) //!vlen\r current [ dim ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set current element at dimension 0 1 2 to v0 v1 v2 [CODESPLIT] public Index set ( int v0 , int v1 , int v2 ) { setDim ( 0 , v0 ) ; setDim ( 1 , v1 ) ; setDim ( 2 , v2 ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String representation [CODESPLIT] public String toStringDebug ( ) { StringBuilder sbuff = new StringBuilder ( 100 ) ; sbuff . setLength ( 0 ) ; sbuff . append ( \" shape= \" ) ; for ( int ii = 0 ; ii < rank ; ii ++ ) { sbuff . append ( shape [ ii ] ) ; sbuff . append ( \" \" ) ; } sbuff . append ( \" stride= \" ) ; for ( int ii = 0 ; ii < rank ; ii ++ ) { sbuff . append ( stride [ ii ] ) ; sbuff . append ( \" \" ) ; } /* if (name != null) {\r\n      sbuff.append(\" names= \");\r\n      for (int ii = 0; ii < rank; ii++) {\r\n        sbuff.append(name[ii]);\r\n        sbuff.append(\" \");\r\n      }\r\n    } */ sbuff . append ( \" offset= \" ) . append ( offset ) ; sbuff . append ( \" rank= \" ) . append ( rank ) ; sbuff . append ( \" size= \" ) . append ( size ) ; sbuff . append ( \" current= \" ) ; for ( int ii = 0 ; ii < rank ; ii ++ ) { sbuff . append ( current [ ii ] ) ; sbuff . append ( \" \" ) ; } return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if we all time intervals have the same length . [CODESPLIT] public String getTimeIntervalName ( ) { // are they the same length ? int firstValue = - 1 ; for ( TimeCoordIntvValue tinv : timeIntervals ) { int value = ( tinv . getBounds2 ( ) - tinv . getBounds1 ( ) ) ; if ( firstValue < 0 ) firstValue = value ; else if ( value != firstValue ) return MIXED_INTERVALS ; } firstValue = ( firstValue * timeUnit . getValue ( ) ) ; return firstValue + \"_\" + timeUnit . getField ( ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make calendar date range using the first and last ending bounds [CODESPLIT] @ Override public CalendarDateRange makeCalendarDateRange ( ucar . nc2 . time . Calendar cal ) { CalendarDateUnit cdu = CalendarDateUnit . of ( cal , timeUnit . getField ( ) , refDate ) ; CalendarDate start = cdu . makeCalendarDate ( timeUnit . getValue ( ) * timeIntervals . get ( 0 ) . getBounds2 ( ) ) ; CalendarDate end = cdu . makeCalendarDate ( timeUnit . getValue ( ) * timeIntervals . get ( getSize ( ) - 1 ) . getBounds2 ( ) ) ; return CalendarDateRange . of ( start , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { //Trace.startTrace(); if ( ! super . init ( fullCheck ) ) { return false ; } if ( ( dmLabel . kftype != MFSN ) && ( dmLabel . kftype != MFSF ) ) { logError ( \"not a point data file \" ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in the stations and times . Subclasses should call this during init () [CODESPLIT] protected boolean readStationsAndTimes ( boolean uniqueTimes ) { for ( DMPart apart : parts ) { List < GempakParameter > params = makeParams ( apart ) ; partParamMap . put ( apart . kprtnm , params ) ; } // get the date/time keys dateTimeKeys = getDateTimeKeys ( ) ; if ( ( dateTimeKeys == null ) || dateTimeKeys . isEmpty ( ) ) { return false ; } // get the station info stationKeys = findStationKeys ( ) ; if ( ( stationKeys == null ) || stationKeys . isEmpty ( ) ) { return false ; } stations = getStationList ( ) ; makeFileSubType ( ) ; // null out the old cached list dates = null ; dateList = makeDateList ( uniqueTimes ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the date / time information [CODESPLIT] private List < Key > getDateTimeKeys ( ) { Key date = findKey ( DATE ) ; Key time = findKey ( TIME ) ; if ( ( date == null ) || ( time == null ) || ! date . type . equals ( time . type ) ) { return null ; } List < Key > dt = new ArrayList <> ( 2 ) ; dt . add ( date ) ; dt . add ( time ) ; return dt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of dates [CODESPLIT] protected List < String > makeDateList ( boolean unique ) { Key date = dateTimeKeys . get ( 0 ) ; Key time = dateTimeKeys . get ( 1 ) ; List < int [ ] > toCheck ; if ( date . type . equals ( ROW ) ) { toCheck = headers . rowHeaders ; } else { toCheck = headers . colHeaders ; } List < String > fileDates = new ArrayList <> ( ) ; for ( int [ ] header : toCheck ) { if ( header [ 0 ] != IMISSD ) { // convert to GEMPAK date/time int idate = header [ date . loc + 1 ] ; int itime = header [ time . loc + 1 ] ; // TODO: Add in the century String dateTime = GempakUtil . TI_CDTM ( idate , itime ) ; fileDates . add ( dateTime ) ; } } if ( unique && ! fileDates . isEmpty ( ) ) { SortedSet < String > uniqueTimes = Collections . synchronizedSortedSet ( new TreeSet < String > ( ) ) ; uniqueTimes . addAll ( fileDates ) ; fileDates . clear ( ) ; fileDates . addAll ( uniqueTimes ) ; } return fileDates ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make GempakParameters from the list of [CODESPLIT] private List < GempakParameter > makeParams ( DMPart part ) { List < GempakParameter > gemparms = new ArrayList <> ( part . kparms ) ; for ( DMParam param : part . params ) { String name = param . kprmnm ; GempakParameter parm = GempakParameters . getParameter ( name ) ; if ( parm == null ) { //System.out.println(\"couldn't find \" + name //                   + \" in params table\"); parm = new GempakParameter ( 1 , name , name , \"\" , 0 ) ; } gemparms . add ( parm ) ; } return gemparms ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the station list [CODESPLIT] private List < GempakStation > getStationList ( ) { Key slat = findKey ( GempakStation . SLAT ) ; if ( slat == null ) { return null ; } List < int [ ] > toCheck ; if ( slat . type . equals ( ROW ) ) { toCheck = headers . rowHeaders ; } else { toCheck = headers . colHeaders ; } List < GempakStation > fileStations = new ArrayList <> ( ) ; int i = 0 ; for ( int [ ] header : toCheck ) { if ( header [ 0 ] != IMISSD ) { GempakStation station = makeStation ( header ) ; if ( station != null ) { station . setIndex ( i + 1 ) ; fileStations . add ( station ) ; } } i ++ ; } return fileStations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a station from the header info [CODESPLIT] private GempakStation makeStation ( int [ ] header ) { if ( ( stationKeys == null ) || stationKeys . isEmpty ( ) ) { return null ; } GempakStation newStation = new GempakStation ( ) ; for ( Key key : stationKeys ) { int loc = key . loc + 1 ; switch ( key . name ) { case GempakStation . STID : newStation . setSTID ( GempakUtil . ST_ITOC ( header [ loc ] ) . trim ( ) ) ; break ; case GempakStation . STNM : newStation . setSTNM ( header [ loc ] ) ; break ; case GempakStation . SLAT : newStation . setSLAT ( header [ loc ] ) ; break ; case GempakStation . SLON : newStation . setSLON ( header [ loc ] ) ; break ; case GempakStation . SELV : newStation . setSELV ( header [ loc ] ) ; break ; case GempakStation . SPRI : newStation . setSPRI ( header [ loc ] ) ; break ; case GempakStation . STAT : newStation . setSTAT ( GempakUtil . ST_ITOC ( header [ loc ] ) . trim ( ) ) ; break ; case GempakStation . COUN : newStation . setCOUN ( GempakUtil . ST_ITOC ( header [ loc ] ) . trim ( ) ) ; break ; case GempakStation . SWFO : newStation . setSWFO ( GempakUtil . ST_ITOC ( header [ loc ] ) . trim ( ) ) ; break ; case GempakStation . WFO2 : newStation . setWFO2 ( GempakUtil . ST_ITOC ( header [ loc ] ) . trim ( ) ) ; break ; case GempakStation . STD2 : newStation . setSTD2 ( GempakUtil . ST_ITOC ( header [ loc ] ) . trim ( ) ) ; break ; } } return newStation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the station key names [CODESPLIT] public List < String > getStationKeyNames ( ) { List < String > keys = new ArrayList <> ( ) ; if ( ( stationKeys != null ) && ! stationKeys . isEmpty ( ) ) { for ( Key key : stationKeys ) { keys . add ( key . name ) ; } } return keys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the station keys [CODESPLIT] private List < Key > findStationKeys ( ) { Key stid = findKey ( GempakStation . STID ) ; Key stnm = findKey ( GempakStation . STNM ) ; Key slat = findKey ( GempakStation . SLAT ) ; Key slon = findKey ( GempakStation . SLON ) ; Key selv = findKey ( GempakStation . SELV ) ; Key stat = findKey ( GempakStation . STAT ) ; Key coun = findKey ( GempakStation . COUN ) ; Key std2 = findKey ( GempakStation . STD2 ) ; Key spri = findKey ( GempakStation . SPRI ) ; Key swfo = findKey ( GempakStation . SWFO ) ; Key wfo2 = findKey ( GempakStation . WFO2 ) ; if ( ( slat == null ) || ( slon == null ) || ! slat . type . equals ( slon . type ) ) { return null ; } String tslat = slat . type ; // check to make sure they are all in the same set of keys List < Key > stKeys = new ArrayList <> ( ) ; stKeys . add ( slat ) ; stKeys . add ( slon ) ; if ( ( stid != null ) && ! stid . type . equals ( tslat ) ) { return null ; } else if ( ( stnm != null ) && ! stnm . type . equals ( tslat ) ) { return null ; } else if ( ( selv != null ) && ! selv . type . equals ( tslat ) ) { return null ; } else if ( ( stat != null ) && ! stat . type . equals ( tslat ) ) { return null ; } else if ( ( coun != null ) && ! coun . type . equals ( tslat ) ) { return null ; } else if ( ( std2 != null ) && ! std2 . type . equals ( tslat ) ) { return null ; } else if ( ( spri != null ) && ! spri . type . equals ( tslat ) ) { return null ; } else if ( ( swfo != null ) && ! swfo . type . equals ( tslat ) ) { return null ; } else if ( ( wfo2 != null ) && ! wfo2 . type . equals ( tslat ) ) { return null ; } if ( stid != null ) { stKeys . add ( stid ) ; } if ( stnm != null ) { stKeys . add ( stnm ) ; } if ( selv != null ) { stKeys . add ( selv ) ; } if ( stat != null ) { stKeys . add ( stat ) ; } if ( coun != null ) { stKeys . add ( coun ) ; } if ( std2 != null ) { stKeys . add ( std2 ) ; } if ( spri != null ) { stKeys . add ( spri ) ; } if ( swfo != null ) { stKeys . add ( swfo ) ; } if ( wfo2 != null ) { stKeys . add ( wfo2 ) ; } return stKeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of dates in this file . [CODESPLIT] public List < Date > getDates ( ) { if ( ( dates == null || dates . isEmpty ( ) ) && ! dateList . isEmpty ( ) ) { dates = new ArrayList <> ( dateList . size ( ) ) ; dateFmt . setTimeZone ( TimeZone . getTimeZone ( \"GMT\" ) ) ; for ( String dateString : dateList ) { Date d = dateFmt . parse ( dateString , new ParsePosition ( 0 ) ) ; //DateFromString.getDateUsingSimpleDateFormat(dateString, //    DATE_FORMAT); dates . add ( d ) ; } } return dates ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the list of dates in the file [CODESPLIT] public void printDates ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( \"\\nDates:\\n\" ) ; for ( String date : dateList ) { builder . append ( \"\\t\" ) ; builder . append ( date ) ; builder . append ( \"\\n\" ) ; } System . out . println ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the list of dates in the file [CODESPLIT] public void printStations ( boolean list ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( \"\\nStations:\\n\" ) ; if ( list ) { for ( GempakStation station : getStations ( ) ) { builder . append ( station ) ; builder . append ( \"\\n\" ) ; } } else { builder . append ( \"\\t\" ) ; builder . append ( getStations ( ) . size ( ) ) ; } System . out . println ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the station index for the specified station id . [CODESPLIT] public int findStationIndex ( String id ) { for ( GempakStation station : getStations ( ) ) { if ( station . getSTID ( ) . equals ( id ) ) { return station . getIndex ( ) ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the type for this file [CODESPLIT] public String getFileType ( ) { String type = \"Unknown\" ; switch ( dmLabel . kftype ) { case MFSN : type = \"Sounding\" ; break ; case MFSF : type = \"Surface\" ; break ; default : } if ( ! subType . equals ( \"\" ) ) { type = type + \" (\" + subType + \")\" ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set depth + = n [CODESPLIT] public void indent ( int n ) { depth += n ; if ( depth < 0 ) depth = 0 ; else if ( depth > MAXDEPTH ) depth = MAXDEPTH ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set depth = n [CODESPLIT] public void setIndent ( int n ) { depth = n ; if ( depth < 0 ) depth = 0 ; else if ( depth > MAXDEPTH ) depth = MAXDEPTH ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Only call on the root node [CODESPLIT] public void init ( CEEvaluator ceEval , BaseTypeFactory factory , ClauseFactory clauseFactory , ServerDDS sdds , List < AST > nodes ) { this . ceEval = ceEval ; this . clauseFactory = clauseFactory ; this . factory = factory ; this . sdds = sdds ; this . root = this ; for ( AST node : nodes ) node . setRoot ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { StringBuilder buf = new StringBuilder () ; boolean first = true ; if ( projections ! = null ) for ( ASTprojection p : projections ) { buf . append (( first ? : ) + p . toString () ) ; first = false ; } first = true ; if ( selections ! = null ) for ( ASTclause c : selections ) { buf . append ( c . toString () ) ; first = false ; } return buf . toString () ; } [CODESPLIT] public void walkConstraint ( ) throws DAP2ServerSideException , DAP2Exception { if ( projections != null ) for ( ASTprojection proj : projections ) { proj . walk ( ceEval ) ; } else getCeEval ( ) . markAll ( true ) ; if ( selections != null ) for ( ASTclause cl : selections ) { getCeEval ( ) . appendClause ( cl . translate ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { if ( var ! = null ) return var . toString () ; else return fcn . toString () ; } [CODESPLIT] void walk ( CEEvaluator ceEval ) throws DAP2ServerSideException , DAP2Exception , NoSuchFunctionException , NoSuchVariableException { if ( fcn != null ) { SubClause subclause = fcn . translate ( ) ; getCeEval ( ) . appendClause ( subclause ) ; } else { Stack components = new Stack ( ) ; components = var . collect ( components ) ; markStackedVariables ( components ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { StringBuilder buf = new StringBuilder () ; boolean first = true ; buf . append ( fcnname ) ; buf . append ( ( ) ; if ( args ! = null ) for ( ASTvalue arg : args ) { if ( !first ) buf . append ( ) ; else { first = false ; } buf . append ( arg . toString () ) ; } buf . append ( ) ) ; return buf . toString () ; } [CODESPLIT] SubClause translate ( ) throws DAP2ServerSideException , DAP2Exception , NoSuchFunctionException , NoSuchVariableException { SubClause subclause = null ; Vector < SubClause > cvtargs = new Vector < SubClause > ( ) ; if ( args != null ) for ( ASTvalue arg : args ) cvtargs . addElement ( arg . translate ( ) ) ; subclause = getClauseFactory ( ) . newBTFunctionClause ( fcnname , cvtargs ) ; return subclause ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { StringBuilder buf = new StringBuilder () ; boolean first = true ; for ( ASTsegment seg : segments ) { buf . append (( first ? : . ) + seg . toString () ) ; first = false ; } return buf . toString () ; } [CODESPLIT] Stack collect ( Stack components ) throws DAP2ServerSideException , DAP2Exception , NoSuchFunctionException , NoSuchVariableException { for ( ASTsegment segment : segments ) { components = segment . collect ( components ) ; } return components ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { StringBuilder buf = new StringBuilder () ; buf . append ( name ) ; if ( slices ! = null ) for ( ASTslice slice : slices ) { buf . append ( slice . toString () ) ; } return buf . toString () ; } [CODESPLIT] Stack collect ( Stack components ) throws DAP2ServerSideException , DAP2Exception , NoSuchFunctionException , NoSuchVariableException { BaseType bt = null ; ServerArrayMethods sam = null ; components = getSdds ( ) . search ( name , components ) ; if ( slices != null && slices . size ( ) > 0 ) { try { bt = ( BaseType ) components . peek ( ) ; } catch ( ClassCastException cce ) { String msg = \"Attempt to treat the variable `\" + name + \"' as if it is an array.\" ; throw new DAP2Exception ( DAP2Exception . MALFORMED_EXPR , msg ) ; } if ( bt instanceof DGrid ) { // project the grid and the coordinate variable DGrid grid = ( ( DGrid ) bt ) ; bt = grid . getArray ( ) ; sam = ( ServerArrayMethods ) bt ; for ( int i = 0 ; i < slices . size ( ) ; i ++ ) { ASTslice slice = slices . get ( i ) ; slice . walk ( sam , i ) ; } // walk the coordinate variables also for ( int i = 0 ; i < slices . size ( ) ; i ++ ) { ASTslice slice = slices . get ( i ) ; bt = grid . getVar ( i + 1 ) ; sam = ( ServerArrayMethods ) bt ; slice . walk ( sam , 0 ) ; } } else if ( bt instanceof ServerArrayMethods ) { sam = ( ServerArrayMethods ) bt ; for ( int i = 0 ; i < slices . size ( ) ; i ++ ) { ASTslice slice = slices . get ( i ) ; slice . walk ( sam , i ) ; } } } return components ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { if ( stride == 1 ) { if ( first == last ) return String . format ( [ %d ] first ) ; else return String . format ( [ %d : %d ] first last ) ; } else return String . format ( [ %d : %d : %d ] first stride last ) ; } [CODESPLIT] void walk ( ServerArrayMethods sam , int index ) throws InvalidDimensionException , SBHException { sam . setProjection ( index , ( int ) start , ( int ) stride , ( int ) stop ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { StringBuilder buf = new StringBuilder () ; if ( constant ! = null ) buf . append ( constant . toString () ) ; else if ( var ! = null ) buf . append ( var . toString () ) ; else if ( fcn ! = null ) buf . append ( fcn . toString () ) ; else assert ( false ) ; return buf . toString () ; } [CODESPLIT] SubClause translate ( ) throws DAP2ServerSideException , DAP2Exception , NoSuchFunctionException , NoSuchVariableException { SubClause subclause = null ; if ( constant != null ) { subclause = constant . translate ( ) ; } else if ( var != null ) { Stack components = new Stack ( ) ; components = var . collect ( components ) ; subclause = getClauseFactory ( ) . newValueClause ( ( BaseType ) components . pop ( ) , false ) ; } else if ( fcn != null ) { subclause = fcn . translate ( ) ; } else assert ( false ) ; return subclause ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { StringBuilder buf = new StringBuilder () ; switch ( tag ) { case STRINGCONST : buf . append ( String . format ( \\ %s \\ text )) ; break ; case INTCONST : buf . append ( String . format ( %d intvalue )) ; break ; case FLOATCONST : buf . append ( String . format ( % . 1f floatvalue )) ; break ; default : assert ( false ) ; } return buf . toString () ; } [CODESPLIT] SubClause translate ( ) throws DAP2ServerSideException , DAP2Exception , NoSuchFunctionException , NoSuchVariableException { SubClause subclause = null ; switch ( tag ) { case ExprParserConstants . INTCONST : { String s = String . format ( \"%d\" , intvalue ) ; DInt32 i = getFactory ( ) . newDInt32 ( s ) ; i . setValue ( ( int ) intvalue ) ; ( ( ServerMethods ) i ) . setRead ( true ) ; ( ( ServerMethods ) i ) . setProject ( true ) ; subclause = getClauseFactory ( ) . newValueClause ( i , false ) ; } break ; case ExprParserConstants . FLOATCONST : { String s = String . format ( \"%.1f\" , floatvalue ) ; DFloat64 f = getFactory ( ) . newDFloat64 ( s ) ; f . setValue ( floatvalue ) ; subclause = getClauseFactory ( ) . newValueClause ( f , false ) ; } break ; case ExprParserConstants . STRINGCONST : { DString s = getFactory ( ) . newDString ( text ) ; s . setValue ( text ) ; ( ( ServerMethods ) s ) . setRead ( true ) ; ( ( ServerMethods ) s ) . setProject ( true ) ; subclause = getClauseFactory ( ) . newValueClause ( s , false ) ; } break ; default : assert ( false ) ; } return subclause ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String toString () { if ( boolfcn ! = null ) { return & + boolfcn . toString () ; } else { StringBuilder buf = new StringBuilder ( & ) ; buf . append ( lhs . toString () ) ; buf . append ( operatorString ( operator )) ; boolean first = true ; if ( rhs . size () > 1 ) buf . append ( { ) ; if ( rhs ! = null ) for ( ASTvalue value : rhs ) { buf . append (( first ? : ) + value . toString () ) ; first = false ; } if ( rhs . size () > 1 ) buf . append ( } ) ; return buf . toString () ; } } [CODESPLIT] public Clause translate ( ) throws DAP2ServerSideException , DAP2Exception , NoSuchFunctionException , NoSuchVariableException { Clause clause = null ; if ( boolfcn != null ) clause = boolfcn . translate ( ) ; else { Vector < SubClause > cvtrhs = new Vector < SubClause > ( ) ; for ( ASTvalue v : rhs ) cvtrhs . addElement ( v . translate ( ) ) ; SubClause lhsclause = lhs . translate ( ) ; clause = getClauseFactory ( ) . newRelOpClause ( operator , lhsclause , cvtrhs ) ; } return clause ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assume first dimension is TIME series [CODESPLIT] public void setVariable ( Variable v ) throws IOException { log . info ( \"variable \" + v . getShortName ( ) ) ; AbstractIntervalXYDataset dataset = null ; Dimension dim = v . getDimension ( 0 ) ; String dimName = dim . getShortName ( ) ; Attribute title = file . findGlobalAttribute ( \"title\" ) ; if ( title != null ) chart . setTitle ( title . getStringValue ( ) ) ; Variable varXdim = file . findVariable ( null , dimName ) ; boolean hasXdim = false ; if ( varXdim != null ) hasXdim = true ; boolean xIsTime = false ; XYPlot p = chart . getXYPlot ( ) ; if ( hasXdim ) { Attribute xUnit = varXdim . findAttribute ( \"units\" ) ; Attribute xAxis = varXdim . findAttribute ( \"axis\" ) ; if ( xUnit != null ) if ( xUnit . getStringValue ( ) . contains ( \"since\" ) ) xIsTime = true ; if ( xAxis != null ) if ( xAxis . getStringValue ( ) . equals ( \"T\" ) ) xIsTime = true ; if ( xUnit != null ) p . getDomainAxis ( ) . setLabel ( xUnit . getStringValue ( ) ) ; else p . getDomainAxis ( ) . setLabel ( dimName ) ; if ( xAxis != null ) log . info ( \"X axis type \" + xUnit . getDataType ( ) + \" value \" + xUnit . toString ( ) + \" is Time \" + xIsTime ) ; } int ax = 0 ; log . info ( \"dataset count \" + p . getDatasetCount ( ) ) ; if ( p . getDatasetCount ( ) >= 1 ) { if ( p . getDataset ( p . getDatasetCount ( ) - 1 ) != null ) { log . info ( \"number in dataset \" + p . getDataset ( 0 ) ) ; ax = p . getDatasetCount ( ) ; if ( ax > 0 ) { p . setRangeAxis ( ax , new NumberAxis ( ) ) ; } } } log . info ( \"axis number \" + ax ) ; final XYItemRenderer renderer = p . getRenderer ( ) ; if ( xIsTime ) { final StandardXYToolTipGenerator g = new StandardXYToolTipGenerator ( StandardXYToolTipGenerator . DEFAULT_TOOL_TIP_FORMAT , new SimpleDateFormat ( \"d-MMM-yyyy\" ) , new DecimalFormat ( \"0.00\" ) ) ; renderer . setBaseToolTipGenerator ( g ) ; dataset = new TimeSeriesCollection ( ) ; } else { final StandardXYToolTipGenerator g = new StandardXYToolTipGenerator ( StandardXYToolTipGenerator . DEFAULT_TOOL_TIP_FORMAT , new DecimalFormat ( \"0.00\" ) , new DecimalFormat ( \"0.00\" ) ) ; renderer . setBaseToolTipGenerator ( g ) ; dataset = new XYSeriesCollection ( ) ; p . setDomainAxis ( new NumberAxis ( ) ) ; // change to NumberAxis from DateAxis which is what is created } p . getRangeAxis ( ax ) . setAutoRange ( true ) ; Attribute vUnit = v . findAttribute ( \"units\" ) ; Attribute vfill = v . findAttribute ( \"_FillValue\" ) ; double dfill = Double . NaN ; if ( vfill != null ) dfill = vfill . getNumericValue ( ) . doubleValue ( ) ; if ( vUnit != null ) p . getRangeAxis ( ax ) . setLabel ( vUnit . getStringValue ( ) ) ; NetcdfDataset fds = new NetcdfDataset ( file ) ; CoordinateAxis1DTime tm = null ; List < CalendarDate > dates = null ; Array varXarray = null ; if ( hasXdim ) { varXarray = varXdim . read ( ) ; if ( xIsTime ) { tm = CoordinateAxis1DTime . factory ( fds , new VariableDS ( null , varXdim , true ) , null ) ; dates = tm . getCalendarDates ( ) ; } } Array a = v . read ( ) ; Index idx = a . getIndex ( ) ; idx . setCurrentCounter ( 0 ) ; int d2 = 1 ; int rank = idx . getRank ( ) ; for ( int k = 1 ; k < rank ; k ++ ) { d2 *= idx . getShape ( k ) ; } log . info ( \"variable : \" + v . getShortName ( ) + \" : dims \" + v . getDimensionsString ( ) + \" rank \" + rank + \" d2 \" + d2 ) ; double max = - 1000 ; double min = 1000 ; for ( int j = 0 ; j < d2 ; j ++ ) { if ( rank > 1 ) idx . set1 ( j ) ; // this wont work for 3rd dimension > 1 String name = v . getShortName ( ) ; if ( d2 > 1 ) name += \"-\" + j ; Series s1 ; if ( xIsTime ) s1 = new TimeSeries ( name ) ; else s1 = new XYSeries ( name ) ; for ( int i = 0 ; i < idx . getShape ( 0 ) ; i ++ ) { idx . set0 ( i ) ; float f = a . getFloat ( idx ) ; if ( f != dfill ) { if ( ! Float . isNaN ( f ) ) { max = Math . max ( max , f ) ; min = Math . min ( min , f ) ; } if ( xIsTime ) { Date ts = new Date ( dates . get ( i ) . getMillis ( ) ) ; ( ( TimeSeries ) s1 ) . addOrUpdate ( new Second ( ts ) , f ) ; } else if ( hasXdim ) { ( ( XYSeries ) s1 ) . addOrUpdate ( varXarray . getDouble ( i ) , f ) ; } else { ( ( XYSeries ) s1 ) . addOrUpdate ( i , f ) ; } } } if ( dataset instanceof TimeSeriesCollection ) ( ( TimeSeriesCollection ) dataset ) . addSeries ( ( TimeSeries ) s1 ) ; if ( dataset instanceof XYSeriesCollection ) ( ( XYSeriesCollection ) dataset ) . addSeries ( ( XYSeries ) s1 ) ; } final XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer ( true , false ) ; p . setRenderer ( ax , renderer1 ) ; log . info ( \"dataset \" + ax + \" max \" + max + \" min \" + min + \" : \" + dataset ) ; p . setDataset ( ax , dataset ) ; p . mapDatasetToRangeAxis ( ax , ax ) ; p . getRangeAxis ( ax ) . setLowerBound ( min ) ; p . getRangeAxis ( ax ) . setUpperBound ( max ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public void setBounds ( Rectangle r ) { // keep window on the screen Rectangle screenSize = ScreenUtils . getScreenVirtualSize ( ) ; Rectangle result = r . intersection ( screenSize ) ; if ( ! result . isEmpty ( ) ) super . setBounds ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a gbx9 index from a single grib1 or grib2 file . Use the existing index if it already exists . [CODESPLIT] public static GribIndex readOrCreateIndexFromSingleFile ( boolean isGrib1 , MFile mfile , CollectionUpdateType force , org . slf4j . Logger logger ) throws IOException { GribIndex index = isGrib1 ? new Grib1Index ( ) : new Grib2Index ( ) ; if ( ! index . readIndex ( mfile . getPath ( ) , mfile . getLastModified ( ) , force ) ) { // heres where the index date is checked against the data file\r index . makeIndex ( mfile . getPath ( ) , null ) ; logger . debug ( \"  Index written: {} == {} records\" , mfile . getName ( ) + GBX9_IDX , index . getNRecords ( ) ) ; } else if ( debug ) { logger . debug ( \"  Index read: {} == {} records\" , mfile . getName ( ) + GBX9_IDX , index . getNRecords ( ) ) ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called from Aggregation Fmrc FeatureDatasetFactoryManager [CODESPLIT] static public MFileCollectionManager open ( String collectionName , String collectionSpec , String olderThan , Formatter errlog ) throws IOException { return new MFileCollectionManager ( collectionName , collectionSpec , olderThan , errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a directory scan to the collection [CODESPLIT] public void addDirectoryScan ( String dirName , String suffix , String regexpPatternString , String subdirsS , String olderS , Object auxInfo ) { CompositeMFileFilter filters = new CompositeMFileFilter ( ) ; if ( null != regexpPatternString ) filters . addIncludeFilter ( new RegExpMatchOnName ( regexpPatternString ) ) ; else if ( suffix != null ) filters . addIncludeFilter ( new WildcardMatchOnPath ( \"*\" + suffix + \"$\" ) ) ; if ( olderS != null ) { try { TimeDuration tu = new TimeDuration ( olderS ) ; filters . addAndFilter ( new LastModifiedLimit ( ( long ) ( 1000 * tu . getValueInSeconds ( ) ) ) ) ; } catch ( Exception e ) { logger . error ( collectionName + \": Invalid time unit for olderThan = {}\" , olderS ) ; } } boolean wantSubdirs = true ; if ( ( subdirsS != null ) && subdirsS . equalsIgnoreCase ( \"false\" ) ) wantSubdirs = false ; CollectionConfig mc = new CollectionConfig ( dirName , dirName , wantSubdirs , filters , auxInfo ) ; // create name\r StringBuilder sb = new StringBuilder ( dirName ) ; if ( wantSubdirs ) sb . append ( \"**/\" ) ; if ( null != regexpPatternString ) sb . append ( regexpPatternString ) ; else if ( suffix != null ) sb . append ( suffix ) ; else sb . append ( \"noFilter\" ) ; collectionName = sb . toString ( ) ; scanList . add ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute if synchronous scan is needed . True if recheck is true and enough time has elapsed . [CODESPLIT] @ Override public boolean isScanNeeded ( ) { // see if we need to recheck\r if ( recheck == null ) { logger . debug ( \"{}: scan not needed, recheck null\" , collectionName ) ; return false ; } if ( ! hasScans ( ) ) { logger . debug ( \"{}: scan not needed, no scanners\" , collectionName ) ; return false ; } synchronized ( this ) { if ( map == null && ! isStatic ( ) ) { logger . debug ( \"{}: scan needed, never scanned\" , collectionName ) ; return true ; } } Date now = new Date ( ) ; Date lastCheckedDate = new Date ( getLastScanned ( ) ) ; Date need = recheck . add ( lastCheckedDate ) ; if ( now . before ( need ) ) { logger . debug ( \"{}: scan not needed, last scanned={}, now={}\" , collectionName , lastCheckedDate , now ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only called from synch methods [CODESPLIT] private boolean scanFirstTime ( ) throws IOException { Map < String , MFile > newMap = new HashMap <> ( ) ; if ( ! hasScans ( ) ) { map = newMap ; return false ; } reallyScan ( newMap ) ; // deleteOld(newMap); // ?? hmmmmm LOOK this seems wrong; maintainence in background ?? generally collection doesnt exist\r // implement olderThan\r if ( olderThanInMsecs > 0 ) { long olderThan = System . currentTimeMillis ( ) - olderThanInMsecs ; // new files must be older than this.\r Iterator < MFile > iter = newMap . values ( ) . iterator ( ) ; // need iterator so we can remove()\r while ( iter . hasNext ( ) ) { MFile newFile = iter . next ( ) ; String path = newFile . getPath ( ) ; if ( newFile . getLastModified ( ) > olderThan ) { // the file is too new\r iter . remove ( ) ; logger . debug ( \"{}: scan found new Dataset but its too recently modified = {}\" , collectionName , path ) ; } } } map = newMap ; this . lastScanned = System . currentTimeMillis ( ) ; this . lastChanged . set ( this . lastScanned ) ; logger . debug ( \"{} : initial scan found n datasets = {} \" , collectionName , map . keySet ( ) . size ( ) ) ; return map . keySet ( ) . size ( ) > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set debugging flags [CODESPLIT] public static void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlags ) { debug = debugFlags . isSet ( \"ncfileWriter2/debug\" ) ; debugWrite = debugFlags . isSet ( \"ncfileWriter2/debugWrite\" ) ; debugChunk = debugFlags . isSet ( \"ncfileWriter2/debugChunk\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify which variable will get written [CODESPLIT] public Variable addVariable ( Variable oldVar ) { List < Dimension > newDims = getNewDimensions ( oldVar ) ; Variable newVar ; if ( ( oldVar . getDataType ( ) . equals ( DataType . STRING ) ) && ( ! version . isExtendedModel ( ) ) ) { newVar = writer . addStringVariable ( null , oldVar , newDims ) ; } else { newVar = writer . addVariable ( null , oldVar . getShortName ( ) , oldVar . getDataType ( ) , newDims ) ; } varMap . put ( oldVar , newVar ) ; varList . add ( oldVar ) ; for ( Attribute orgAtt : oldVar . getAttributes ( ) ) writer . addVariableAttribute ( newVar , convertAttribute ( orgAtt ) ) ; return newVar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the input file to the output file . [CODESPLIT] public NetcdfFile write ( CancelTask cancel ) throws IOException { try { if ( version . isExtendedModel ( ) ) addGroupExtended ( null , fileIn . getRootGroup ( ) ) ; else addGroupClassic ( ) ; if ( cancel != null && cancel . isCancel ( ) ) return null ; // create the file\r writer . create ( ) ; if ( cancel != null && cancel . isCancel ( ) ) return null ; double total = copyVarData ( varList , null , cancel ) ; if ( cancel != null && cancel . isCancel ( ) ) return null ; writer . flush ( ) ; if ( debug ) System . out . println ( \"FileWriter done total bytes = \" + total ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; writer . abort ( ) ; // clean up\r throw ioe ; } return writer . getNetcdfFile ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] void add ( long recno , int fieldno , Array field ) { //Make sure all the space is allocated if ( records . length <= recno ) { FieldSet [ ] newrecs = new FieldSet [ ( int ) recno + 1 ] ; System . arraycopy ( records , 0 , newrecs , 0 , records . length ) ; records = newrecs ; } FieldSet fs = records [ ( int ) recno ] ; if ( fs == null ) { records [ ( int ) recno ] = ( fs = new FieldSet ( this . nmembers ) ) ; } fs . fields [ fieldno ] = field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////// [CODESPLIT] protected CDMArrayAtomic getAtomicArray ( int index , StructureMembers . Member m ) { Array dd = memberArray ( index , CDMArrayStructure . memberIndex ( m ) ) ; if ( dd . getDataType ( ) != DataType . STRUCTURE && dd . getDataType ( ) != DataType . SEQUENCE ) return ( CDMArrayAtomic ) dd ; throw new ForbiddenConversionException ( \"Cannot convert structure to AtomicArray\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the information as an XML document [CODESPLIT] public String writeXML ( ) { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( makeDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XML document from this info [CODESPLIT] public Document makeDocument ( ) { Element rootElem = new Element ( \"netcdfDatasetInfo\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"location\" , ds . getLocation ( ) ) ; rootElem . addContent ( new Element ( \"convention\" ) . setAttribute ( \"name\" , getConventionUsed ( ) ) ) ; int nDataVariables = 0 ; int nOtherVariables = 0 ; List < CoordinateAxis > axes = ds . getCoordinateAxes ( ) ; int nCoordAxes = axes . size ( ) ; for ( CoordinateAxis axis : axes ) { Element axisElem = new Element ( \"axis\" ) ; rootElem . addContent ( axisElem ) ; axisElem . setAttribute ( \"name\" , axis . getFullName ( ) ) ; axisElem . setAttribute ( \"decl\" , getDecl ( axis ) ) ; if ( axis . getAxisType ( ) != null ) axisElem . setAttribute ( \"type\" , axis . getAxisType ( ) . toString ( ) ) ; if ( axis . getUnitsString ( ) != null ) { axisElem . setAttribute ( CDM . UNITS , axis . getUnitsString ( ) ) ; axisElem . setAttribute ( \"udunits\" , isUdunits ( axis . getUnitsString ( ) ) ) ; } if ( axis instanceof CoordinateAxis1D ) { CoordinateAxis1D axis1D = ( CoordinateAxis1D ) axis ; if ( axis1D . isRegular ( ) ) axisElem . setAttribute ( \"regular\" , ucar . unidata . util . Format . d ( axis1D . getIncrement ( ) , 5 ) ) ; } } List < CoordinateSystem > csList = ds . getCoordinateSystems ( ) ; for ( CoordinateSystem cs : csList ) { Element csElem ; if ( GridCoordSys . isGridCoordSys ( null , cs , null ) ) { GridCoordSys gcs = new GridCoordSys ( cs , null ) ; csElem = new Element ( \"gridCoordSystem\" ) ; csElem . setAttribute ( \"name\" , cs . getName ( ) ) ; csElem . setAttribute ( \"horizX\" , gcs . getXHorizAxis ( ) . getFullName ( ) ) ; csElem . setAttribute ( \"horizY\" , gcs . getYHorizAxis ( ) . getFullName ( ) ) ; if ( gcs . hasVerticalAxis ( ) ) csElem . setAttribute ( \"vertical\" , gcs . getVerticalAxis ( ) . getFullName ( ) ) ; if ( gcs . hasTimeAxis ( ) ) csElem . setAttribute ( \"time\" , cs . getTaxis ( ) . getFullName ( ) ) ; } else { csElem = new Element ( \"coordSystem\" ) ; csElem . setAttribute ( \"name\" , cs . getName ( ) ) ; } List < CoordinateTransform > coordTransforms = cs . getCoordinateTransforms ( ) ; for ( CoordinateTransform ct : coordTransforms ) { Element ctElem = new Element ( \"coordTransform\" ) ; csElem . addContent ( ctElem ) ; ctElem . setAttribute ( \"name\" , ct . getName ( ) ) ; ctElem . setAttribute ( \"type\" , ct . getTransformType ( ) . toString ( ) ) ; } rootElem . addContent ( csElem ) ; } List < CoordinateTransform > coordTransforms = ds . getCoordinateTransforms ( ) ; for ( CoordinateTransform ct : coordTransforms ) { Element ctElem = new Element ( \"coordTransform\" ) ; rootElem . addContent ( ctElem ) ; ctElem . setAttribute ( \"name\" , ct . getName ( ) ) ; ctElem . setAttribute ( \"type\" , ct . getTransformType ( ) . toString ( ) ) ; List < Parameter > params = ct . getParameters ( ) ; for ( Parameter pp : params ) { Element ppElem = new Element ( \"param\" ) ; ctElem . addContent ( ppElem ) ; ppElem . setAttribute ( \"name\" , pp . getName ( ) ) ; ppElem . setAttribute ( \"value\" , pp . getStringValue ( ) ) ; } } for ( Variable var : ds . getVariables ( ) ) { VariableEnhanced ve = ( VariableEnhanced ) var ; if ( ve instanceof CoordinateAxis ) continue ; GridCoordSys gcs = getGridCoordSys ( ve ) ; if ( null != gcs ) { nDataVariables ++ ; Element gridElem = new Element ( \"grid\" ) ; rootElem . addContent ( gridElem ) ; gridElem . setAttribute ( \"name\" , ve . getFullName ( ) ) ; gridElem . setAttribute ( \"decl\" , getDecl ( ve ) ) ; if ( ve . getUnitsString ( ) != null ) { gridElem . setAttribute ( CDM . UNITS , ve . getUnitsString ( ) ) ; gridElem . setAttribute ( \"udunits\" , isUdunits ( ve . getUnitsString ( ) ) ) ; } gridElem . setAttribute ( \"coordSys\" , gcs . getName ( ) ) ; } } for ( Variable var : ds . getVariables ( ) ) { VariableEnhanced ve = ( VariableEnhanced ) var ; if ( ve instanceof CoordinateAxis ) continue ; GridCoordSys gcs = getGridCoordSys ( ve ) ; if ( null == gcs ) { nOtherVariables ++ ; Element elem = new Element ( \"variable\" ) ; rootElem . addContent ( elem ) ; elem . setAttribute ( \"name\" , ve . getFullName ( ) ) ; elem . setAttribute ( \"decl\" , getDecl ( ve ) ) ; if ( ve . getUnitsString ( ) != null ) { elem . setAttribute ( CDM . UNITS , ve . getUnitsString ( ) ) ; elem . setAttribute ( \"udunits\" , isUdunits ( ve . getUnitsString ( ) ) ) ; } elem . setAttribute ( \"coordSys\" , getCoordSys ( ve ) ) ; } } if ( nDataVariables > 0 ) { rootElem . addContent ( new Element ( \"userAdvice\" ) . addContent ( \"Dataset contains useable gridded data.\" ) ) ; if ( nOtherVariables > 0 ) rootElem . addContent ( new Element ( \"userAdvice\" ) . addContent ( \"Some variables are not gridded fields; check that is what you expect.\" ) ) ; } else { if ( nCoordAxes == 0 ) rootElem . addContent ( new Element ( \"userAdvice\" ) . addContent ( \"No Coordinate Axes were found.\" ) ) ; else rootElem . addContent ( new Element ( \"userAdvice\" ) . addContent ( \"No gridded data variables were found.\" ) ) ; } String userAdvice = getUserAdvice ( ) ; if ( userAdvice . length ( ) > 0 ) { StringTokenizer toker = new StringTokenizer ( userAdvice , \"\\n\" ) ; while ( toker . hasMoreTokens ( ) ) rootElem . addContent ( new Element ( \"userAdvice\" ) . addContent ( toker . nextToken ( ) ) ) ; } return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] public static void main ( String args [ ] ) throws IOException { String url = \"C:/data/badmodels/RUC_CONUS_80km_20051211_1900.nc\" ; try ( NetcdfDatasetInfo info = new NetcdfDatasetInfo ( url ) ) { String infoString = info . writeXML ( ) ; System . out . println ( infoString ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// Marshalling /////////////////////////////////////////////// [CODESPLIT] public static void marshalPointDataset ( FeatureDatasetPoint fdPoint , OutputStream outputStream ) throws IOException , XmlException { marshalPointDataset ( fdPoint , fdPoint . getDataVariables ( ) , outputStream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates an xml doc . If the validation fails the exception contains a detailed list of errors . [CODESPLIT] public static void validate ( XmlObject doc , boolean strict ) throws XmlException { // Create an XmlOptions instance and set the error listener. Set < XmlError > validationErrors = new HashSet <> ( ) ; XmlOptions validationOptions = new XmlOptions ( ) ; validationOptions . setErrorListener ( validationErrors ) ; // Validate the XML document final boolean isValid = doc . validate ( validationOptions ) ; // Create Exception with error message if the xml document is invalid if ( ! isValid && ! strict ) { // check if we have special validation cases which could let the message pass anyhow validationErrors = filterToOnlySerious ( validationErrors ) ; } if ( ! validationErrors . isEmpty ( ) ) { throw new XmlException ( createErrorMessage ( validationErrors ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert this multislice to a string suitable for use in a constraint [CODESPLIT] @ Override public String toConstraintString ( ) throws DapException { assert this . first != UNDEFINED && this . stride != UNDEFINED && this . stop != UNDEFINED ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( \"[\" ) ; boolean first = true ; for ( Slice sub : this . subslices ) { if ( ! first ) buf . append ( \",\" ) ; first = false ; if ( ( sub . stop - sub . first ) == 0 ) { buf . append ( \"0\" ) ; } else if ( sub . stride == 1 ) { if ( ( sub . stop - sub . first ) == 1 ) buf . append ( sub . first ) ; else buf . append ( String . format ( \"%d:%d\" , sub . first , sub . stop - 1 ) ) ; } else buf . append ( String . format ( \"%d:%d:%d\" , sub . first , sub . stride , sub . stop - 1 ) ) ; } buf . append ( \"]\" ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy () doesnt work because convert gets called twice [CODESPLIT] @ Override public Structure select ( List < String > memberNames ) { StructureDS result = new StructureDS ( getParentGroup ( ) , orgVar ) ; List < Variable > members = new ArrayList <> ( ) ; for ( String name : memberNames ) { Variable m = findVariable ( name ) ; if ( null != m ) members . add ( m ) ; } result . setMemberVariables ( members ) ; result . isSubset = true ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Structure to wrap . [CODESPLIT] public void setOriginalVariable ( ucar . nc2 . Variable orgVar ) { if ( ! ( orgVar instanceof Structure ) ) throw new IllegalArgumentException ( \"StructureDS must wrap a Structure; name=\" + orgVar . getFullName ( ) ) ; this . orgVar = ( Structure ) orgVar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "regular Variables . [CODESPLIT] @ Override public Array reallyRead ( Variable client , CancelTask cancelTask ) throws IOException { Array result ; if ( hasCachedData ( ) ) result = super . reallyRead ( client , cancelTask ) ; else if ( orgVar != null ) result = orgVar . read ( ) ; else { throw new IllegalStateException ( \"StructureDS has no way to get data\" ) ; //Object data = smProxy.getFillValue(getDataType());\r //return Array.factoryConstant(dataType.getPrimitiveClassType(), getShape(), data);\r } return convert ( result , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "section of regular Variable [CODESPLIT] @ Override public Array reallyRead ( Variable client , Section section , CancelTask cancelTask ) throws IOException , InvalidRangeException { if ( section . computeSize ( ) == getSize ( ) ) return _read ( ) ; Array result ; if ( hasCachedData ( ) ) result = super . reallyRead ( client , section , cancelTask ) ; else if ( orgVar != null ) result = orgVar . read ( section ) ; else { throw new IllegalStateException ( \"StructureDS has no way to get data\" ) ; //Object data = smProxy.getFillValue(getDataType());\r //return Array.factoryConstant(dataType.getPrimitiveClassType(), section.getShape(), data);\r } // do any needed conversions (enum/scale/offset/missing/unsigned, etc)\r return convert ( result , section ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is conversion needed? [CODESPLIT] private boolean convertNeeded ( StructureMembers smData ) { for ( Variable v : getVariables ( ) ) { if ( v instanceof VariableDS ) { VariableDS vds = ( VariableDS ) v ; if ( vds . needConvert ( ) ) return true ; } else if ( v instanceof StructureDS ) { StructureDS nested = ( StructureDS ) v ; if ( nested . convertNeeded ( null ) ) return true ; } // a variable with no data in the underlying smData\r if ( ( smData != null ) && ! varHasData ( v , smData ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "3 ) variable with cached data added to StructureDS through NcML [CODESPLIT] protected ArrayStructure convert ( Array data , Section section ) throws IOException { ArrayStructure orgAS = ( ArrayStructure ) data ; if ( ! convertNeeded ( orgAS . getStructureMembers ( ) ) ) { // name, info change only\r convertMemberInfo ( orgAS . getStructureMembers ( ) ) ; return orgAS ; } // LOOK! converting to ArrayStructureMA\r // do any enum/scale/offset/missing/unsigned conversions\r ArrayStructure newAS = ArrayStructureMA . factoryMA ( orgAS ) ; for ( StructureMembers . Member m : newAS . getMembers ( ) ) { VariableEnhanced v2 = ( VariableEnhanced ) findVariable ( m . getName ( ) ) ; if ( ( v2 == null ) && ( orgVar != null ) ) // these are from orgVar - may have been renamed\r v2 = findVariableFromOrgName ( m . getName ( ) ) ; if ( v2 == null ) continue ; if ( v2 instanceof VariableDS ) { VariableDS vds = ( VariableDS ) v2 ; if ( vds . needConvert ( ) ) { Array mdata = newAS . extractMemberArray ( m ) ; // mdata has not yet been enhanced, but vds would *think* that it has been if we used the 1-arg version of\r // VariableDS.convert(). So, we use the 2-arg version to explicitly request enhancement.\r mdata = vds . convert ( mdata , vds . getEnhanceMode ( ) ) ; newAS . setMemberArray ( m , mdata ) ; } } else if ( v2 instanceof StructureDS ) { StructureDS innerStruct = ( StructureDS ) v2 ; if ( innerStruct . convertNeeded ( null ) ) { if ( innerStruct . getDataType ( ) == DataType . SEQUENCE ) { ArrayObject . D1 seqArray = ( ArrayObject . D1 ) newAS . extractMemberArray ( m ) ; ArrayObject . D1 newSeq = ( ArrayObject . D1 ) Array . factory ( DataType . SEQUENCE , new int [ ] { ( int ) seqArray . getSize ( ) } ) ; m . setDataArray ( newSeq ) ; // put back into member array\r // wrap each Sequence\r for ( int i = 0 ; i < seqArray . getSize ( ) ; i ++ ) { ArraySequence innerSeq = ( ArraySequence ) seqArray . get ( i ) ; // get old ArraySequence\r newSeq . set ( i , new SequenceConverter ( innerStruct , innerSeq ) ) ; // wrap in converter\r } // non-Sequence Structures\r } else { Array mdata = newAS . extractMemberArray ( m ) ; mdata = innerStruct . convert ( mdata , null ) ; newAS . setMemberArray ( m , mdata ) ; } } // always convert the inner StructureMembers\r innerStruct . convertMemberInfo ( m . getStructureMembers ( ) ) ; } } StructureMembers sm = newAS . getStructureMembers ( ) ; convertMemberInfo ( sm ) ; // check for variables that have been added by NcML\r for ( Variable v : getVariables ( ) ) { if ( ! varHasData ( v , sm ) ) { try { Variable completeVar = getParentGroup ( ) . findVariable ( v . getShortName ( ) ) ; // LOOK BAD\r Array mdata = completeVar . read ( section ) ; StructureMembers . Member m = sm . addMember ( v . getShortName ( ) , v . getDescription ( ) , v . getUnitsString ( ) , v . getDataType ( ) , v . getShape ( ) ) ; newAS . setMemberArray ( m , mdata ) ; } catch ( InvalidRangeException e ) { throw new IOException ( e . getMessage ( ) ) ; } } } return newAS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * convert original structureData to one that conforms to this Structure [CODESPLIT] protected StructureData convert ( StructureData orgData , int recno ) throws IOException { if ( ! convertNeeded ( orgData . getStructureMembers ( ) ) ) { // name, info change only\r convertMemberInfo ( orgData . getStructureMembers ( ) ) ; return orgData ; } // otherwise we create a new StructureData and convert to it. expensive\r StructureMembers smResult = new StructureMembers ( orgData . getStructureMembers ( ) ) ; StructureDataW result = new StructureDataW ( smResult ) ; for ( StructureMembers . Member m : orgData . getMembers ( ) ) { VariableEnhanced v2 = ( VariableEnhanced ) findVariable ( m . getName ( ) ) ; if ( ( v2 == null ) && ( orgVar != null ) ) // why ?\r v2 = findVariableFromOrgName ( m . getName ( ) ) ; if ( v2 == null ) { findVariableFromOrgName ( m . getName ( ) ) ; // debug\r // log.warn(\"StructureDataDS.convert Cant find member \" + m.getName());\r continue ; } StructureMembers . Member mResult = smResult . findMember ( m . getName ( ) ) ; if ( v2 instanceof VariableDS ) { VariableDS vds = ( VariableDS ) v2 ; Array mdata = orgData . getArray ( m ) ; if ( vds . needConvert ( ) ) // mdata has not yet been enhanced, but vds would *think* that it has been if we used the 1-arg version of\r // VariableDS.convert(). So, we use the 2-arg version to explicitly request enhancement.\r mdata = vds . convert ( mdata , vds . getEnhanceMode ( ) ) ; result . setMemberData ( mResult , mdata ) ; } // recurse into sub-structures\r if ( v2 instanceof StructureDS ) { StructureDS innerStruct = ( StructureDS ) v2 ; // if (innerStruct.convertNeeded(null)) {\r if ( innerStruct . getDataType ( ) == DataType . SEQUENCE ) { Array a = orgData . getArray ( m ) ; if ( a instanceof ArrayObject . D1 ) { // LOOK when does this happen vs ArraySequence?\r ArrayObject . D1 seqArray = ( ArrayObject . D1 ) a ; ArrayObject . D1 newSeq = ( ArrayObject . D1 ) Array . factory ( DataType . SEQUENCE , new int [ ] { ( int ) seqArray . getSize ( ) } ) ; mResult . setDataArray ( newSeq ) ; // put into result member array\r for ( int i = 0 ; i < seqArray . getSize ( ) ; i ++ ) { ArraySequence innerSeq = ( ArraySequence ) seqArray . get ( i ) ; // get old ArraySequence\r newSeq . set ( i , new SequenceConverter ( innerStruct , innerSeq ) ) ; // wrap in converter\r } } else { ArraySequence seqArray = ( ArraySequence ) a ; result . setMemberData ( mResult , new SequenceConverter ( innerStruct , seqArray ) ) ; // wrap in converter\r } // non-Sequence Structures\r } else { Array mdata = orgData . getArray ( m ) ; mdata = innerStruct . convert ( mdata , null ) ; result . setMemberData ( mResult , mdata ) ; } //}\r // always convert the inner StructureMembers\r innerStruct . convertMemberInfo ( mResult . getStructureMembers ( ) ) ; } } StructureMembers sm = result . getStructureMembers ( ) ; convertMemberInfo ( sm ) ; // check for variables that have been added by NcML\r for ( Variable v : getVariables ( ) ) { if ( ! varHasData ( v , sm ) ) { try { Variable completeVar = getParentGroup ( ) . findVariable ( v . getShortName ( ) ) ; // LOOK BAD\r Array mdata = completeVar . read ( new Section ( ) . appendRange ( recno , recno ) ) ; StructureMembers . Member m = sm . addMember ( v . getShortName ( ) , v . getDescription ( ) , v . getUnitsString ( ) , v . getDataType ( ) , v . getShape ( ) ) ; result . setMemberData ( m , mdata ) ; } catch ( InvalidRangeException e ) { throw new IOException ( e . getMessage ( ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the wrapper StructureMembers must be converted to correspond to the wrapper Structure [CODESPLIT] private void convertMemberInfo ( StructureMembers wrapperSm ) { for ( StructureMembers . Member m : wrapperSm . getMembers ( ) ) { Variable v = findVariable ( m . getName ( ) ) ; if ( ( v == null ) && ( orgVar != null ) ) // may have been renamed\r v = ( Variable ) findVariableFromOrgName ( m . getName ( ) ) ; if ( v != null ) { // a section will have missing variables LOOK wrapperSm probably wrong in that case\r //  log.error(\"Cant find \" + m.getName());\r //else\r m . setVariableInfo ( v . getShortName ( ) , v . getDescription ( ) , v . getUnitsString ( ) , v . getDataType ( ) ) ; } // nested structures\r if ( v instanceof StructureDS ) { StructureDS innerStruct = ( StructureDS ) v ; innerStruct . convertMemberInfo ( m . getStructureMembers ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for the top variable that has an orgVar with the wanted orgName [CODESPLIT] private VariableEnhanced findVariableFromOrgName ( String orgName ) { for ( Variable vTop : getVariables ( ) ) { Variable v = vTop ; while ( v instanceof VariableEnhanced ) { VariableEnhanced ve = ( VariableEnhanced ) v ; if ( ( ve . getOriginalName ( ) != null ) && ( ve . getOriginalName ( ) . equals ( orgName ) ) ) return ( VariableEnhanced ) vTop ; v = ve . getOriginalVariable ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verify that the variable has data in the data array [CODESPLIT] private boolean varHasData ( Variable v , StructureMembers sm ) { if ( sm . findMember ( v . getShortName ( ) ) != null ) return true ; while ( v instanceof VariableEnhanced ) { VariableEnhanced ve = ( VariableEnhanced ) v ; if ( sm . findMember ( ve . getOriginalName ( ) ) != null ) return true ; v = ve . getOriginalVariable ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DO NOT USE DIRECTLY . public by accident . recalc any enhancement info [CODESPLIT] public void enhance ( Set < NetcdfDataset . Enhance > mode ) { for ( Variable v : getVariables ( ) ) { VariableEnhanced ve = ( VariableEnhanced ) v ; ve . enhance ( mode ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public NetcdfFile openNetcdfFile ( HttpServletRequest req , HttpServletResponse res , String reqPath ) throws IOException { if ( log . isDebugEnabled ( ) ) log . debug ( \"DatasetHandler wants \" + reqPath ) ; if ( reqPath == null ) return null ; if ( reqPath . startsWith ( \"/\" ) ) reqPath = reqPath . substring ( 1 ) ; // see if its under resource control if ( ! resourceControlOk ( req , res , reqPath ) ) return null ; // HEY LOOK datascan below has its own Ncml // look for a dataset (non scan, non fmrc) that has an ncml element String ncml = datasetTracker . findNcml ( reqPath ) ; if ( ncml != null ) { NetcdfFile ncfile = NetcdfDataset . acquireFile ( new NcmlFileFactory ( ncml ) , null , DatasetUrl . findDatasetUrl ( reqPath ) , - 1 , null , null ) ; if ( ncfile == null ) throw new FileNotFoundException ( reqPath ) ; return ncfile ; } // look for a match DataRootManager . DataRootMatch match = dataRootManager . findDataRootMatch ( reqPath ) ; // look for an feature collection dataset if ( ( match != null ) && ( match . dataRoot . getFeatureCollection ( ) != null ) ) { FeatureCollectionRef featCollection = match . dataRoot . getFeatureCollection ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( \"  -- DatasetHandler found FeatureCollection= \" + featCollection ) ; InvDatasetFeatureCollection fc = featureCollectionCache . get ( featCollection ) ; NetcdfFile ncfile = fc . getNetcdfDataset ( match . remaining ) ; if ( ncfile == null ) throw new FileNotFoundException ( reqPath ) ; return ncfile ; } // might be a pluggable DatasetSource: NetcdfFile ncfile = null ; for ( DatasetSource datasetSource : datasetSources ) { // LOOK linear if ( datasetSource . isMine ( req ) ) { ncfile = datasetSource . getNetcdfFile ( req , res ) ; if ( ncfile != null ) return ncfile ; } } // common case - its a file if ( match != null ) { org . jdom2 . Element netcdfElem = null ; // find ncml if it exists if ( match . dataRoot != null ) { DatasetScan dscan = match . dataRoot . getDatasetScan ( ) ; // if (dscan == null) dscan = match.dataRoot.getDatasetRootProxy();  // no ncml possible in getDatasetRootProxy if ( dscan != null ) netcdfElem = dscan . getNcmlElement ( ) ; } String location = dataRootManager . getLocationFromRequestPath ( reqPath ) ; if ( location == null ) throw new FileNotFoundException ( reqPath ) ; // if theres an ncml element, open it directly through NcMLReader, therefore not being cached. // this is safer given all the trouble we have with ncml and caching. if ( netcdfElem != null ) { String ncmlLocation = \"DatasetScan#\" + location ; // LOOK some descriptive name NetcdfDataset ncd = NcMLReader . readNcML ( ncmlLocation , netcdfElem , \"file:\" + location , null ) ; //new NcMLReader().readNetcdf(reqPath, ncd, ncd, netcdfElem, null); //if (log.isDebugEnabled()) log.debug(\"  -- DatasetHandler found DataRoot NcML = \" + ds); return ncd ; } DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; ncfile = NetcdfDataset . acquireFile ( durl , null ) ; } if ( ncfile == null ) throw new FileNotFoundException ( reqPath ) ; return ncfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public GridDataset openGridDataset ( HttpServletRequest req , HttpServletResponse res , String reqPath ) throws IOException { // first look for a feature collection DataRootManager . DataRootMatch match = dataRootManager . findDataRootMatch ( reqPath ) ; if ( ( match != null ) && ( match . dataRoot . getFeatureCollection ( ) != null ) ) { // see if its under resource control if ( ! resourceAuthorized ( req , res , match . dataRoot . getRestrict ( ) ) ) return null ; FeatureCollectionRef featCollection = match . dataRoot . getFeatureCollection ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( \"  -- DatasetHandler found FeatureCollection= \" + featCollection ) ; InvDatasetFeatureCollection fc = featureCollectionCache . get ( featCollection ) ; GridDataset gds = fc . getGridDataset ( match . remaining ) ; if ( gds == null ) throw new FileNotFoundException ( reqPath ) ; return gds ; } // fetch it as a NetcdfFile; this deals with possible NcML NetcdfFile ncfile = openNetcdfFile ( req , res , reqPath ) ; if ( ncfile == null ) return null ; NetcdfDataset ncd = null ; try { // Convert to NetcdfDataset ncd = NetcdfDataset . wrap ( ncfile , NetcdfDataset . getDefaultEnhanceMode ( ) ) ; return new ucar . nc2 . dt . grid . GridDataset ( ncd ) ; } catch ( Throwable t ) { if ( ncd == null ) ncfile . close ( ) ; else ncd . close ( ) ; if ( t instanceof IOException ) throw ( IOException ) t ; String msg = ncd == null ? \"Problem wrapping NetcdfFile in NetcdfDataset\" : \"Problem creating GridDataset from NetcdfDataset\" ; log . error ( \"openGridDataset(): \" + msg , t ) ; throw new IOException ( msg + t . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public CoverageCollection openCoverageDataset ( HttpServletRequest req , HttpServletResponse res , String reqPath ) throws IOException { if ( reqPath == null ) return null ; if ( reqPath . startsWith ( \"/\" ) ) reqPath = reqPath . substring ( 1 ) ; // see if its under resource control if ( ! resourceControlOk ( req , res , reqPath ) ) return null ; DataRootManager . DataRootMatch match = dataRootManager . findDataRootMatch ( reqPath ) ; // first look for a feature collection if ( ( match != null ) && ( match . dataRoot . getFeatureCollection ( ) != null ) ) { FeatureCollectionRef featCollection = match . dataRoot . getFeatureCollection ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( \"  -- DatasetHandler found FeatureCollection= \" + featCollection ) ; InvDatasetFeatureCollection fc = featureCollectionCache . get ( featCollection ) ; CoverageCollection gds = fc . getGridCoverage ( match . remaining ) ; if ( gds == null ) throw new FileNotFoundException ( reqPath ) ; return gds ; } // otherwise assume its a local file // try to open as a FeatureDatasetCoverage. This allows GRIB to be handle specially String location = getLocationFromRequestPath ( reqPath ) ; if ( location != null ) { Optional < FeatureDatasetCoverage > opt = CoverageDatasetFactory . openCoverageDataset ( location ) ; if ( ! opt . isPresent ( ) ) throw new FileNotFoundException ( \"Not a Grid Dataset \" + reqPath + \" err=\" + opt . getErrorMessage ( ) ) ; if ( log . isDebugEnabled ( ) ) log . debug ( \"  -- DatasetHandler found FeatureCollection from file= \" + location ) ; return opt . get ( ) . getSingleCoverageCollection ( ) ; // LOOK doesnt have to be single, then what is the URL? } // if ncml, must handle special, otherwise we're out of options for opening // a coverage collection. String ncml = datasetTracker . findNcml ( reqPath ) ; if ( ncml != null ) { Optional < FeatureDatasetCoverage > opt = CoverageDatasetFactory . openNcmlString ( ncml ) ; if ( ! opt . isPresent ( ) ) throw new FileNotFoundException ( \"NcML is not a Grid Dataset \" + reqPath + \" err=\" + opt . getErrorMessage ( ) ) ; if ( log . isDebugEnabled ( ) ) log . debug ( \"  -- DatasetHandler found FeatureCollection from NcML\" ) ; return opt . get ( ) . getSingleCoverageCollection ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if this is making a request for a restricted dataset and if so if its allowed . [CODESPLIT] public boolean resourceControlOk ( HttpServletRequest req , HttpServletResponse res , String reqPath ) { if ( null == reqPath ) reqPath = TdsPathUtils . extractPath ( req , null ) ; // see if its under resource control String rc = null ; DataRootManager . DataRootMatch match = dataRootManager . findDataRootMatch ( reqPath ) ; if ( match != null ) { rc = match . dataRoot . getRestrict ( ) ; // datasetScan, featCollection are restricted at the dataRoot } if ( rc == null ) { rc = datasetTracker . findResourceControl ( reqPath ) ; // regular datasets tracked here } return resourceAuthorized ( req , res , rc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DatasetSource [CODESPLIT] public void registerDatasetSource ( String className ) { Class vClass ; try { vClass = DatasetManager . class . getClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { log . error ( \"Attempt to load DatasetSource class \" + className + \" not found\" ) ; return ; } if ( ! ( DatasetSource . class . isAssignableFrom ( vClass ) ) ) { log . error ( \"Attempt to load class \" + className + \" does not implement \" + DatasetSource . class . getName ( ) ) ; return ; } // create instance of the class Object instance ; try { instance = vClass . newInstance ( ) ; } catch ( InstantiationException e ) { log . error ( \"Attempt to load Viewer class \" + className + \" cannot instantiate, probably need default Constructor.\" ) ; return ; } catch ( IllegalAccessException e ) { log . error ( \"Attempt to load Viewer class \" + className + \" is not accessible.\" ) ; return ; } registerDatasetSource ( ( DatasetSource ) instance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the original string representation of this clause . For use in debugging . [CODESPLIT] public void printConstraint ( PrintWriter os ) { os . print ( function . getName ( ) + \"(\" ) ; Iterator it = children . iterator ( ) ; boolean first = true ; while ( it . hasNext ( ) ) { ValueClause vc = ( ValueClause ) it . next ( ) ; if ( ! first ) os . print ( \",\" ) ; vc . printConstraint ( os ) ; first = false ; } os . print ( \")\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a valid file? [CODESPLIT] @ Override public boolean isValidFile ( RandomAccessFile raf ) throws IOException { if ( ! super . isValidFile ( raf ) ) { return false ; } // TODO:  handle other types of surface files\r return gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . MERGED ) || gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . UNMERGED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data for the variable [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { if ( gemreader == null ) { throw new IllegalStateException ( \"reader not initialized\" ) ; } return readSoundingData ( v2 , section , gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . MERGED ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in the data for the variable . In this case it should be a Structure . The section should be rank 2 ( station time ) . [CODESPLIT] private Array readSoundingData ( Variable v2 , Section section , boolean isMerged ) throws IOException { Array array = null ; if ( v2 instanceof Structure ) { Range stationRange = section . getRange ( 0 ) ; Range timeRange = section . getRange ( 1 ) ; int size = stationRange . length ( ) * timeRange . length ( ) ; Structure pdata = ( Structure ) v2 ; StructureMembers members = pdata . makeStructureMembers ( ) ; ArrayStructureBB . setOffsets ( members ) ; ArrayStructureBB abb = new ArrayStructureBB ( members , new int [ ] { size } ) ; ByteBuffer buf = abb . getByteBuffer ( ) ; for ( int stnIdx : stationRange ) { for ( int timeIdx : timeRange ) { List < String > parts = ( isMerged ) ? ( ( GempakSoundingFileReader ) gemreader ) . getMergedParts ( ) : ( ( GempakSoundingFileReader ) gemreader ) . getUnmergedParts ( ) ; boolean allMissing = true ; for ( String part : parts ) { List < GempakParameter > params = gemreader . getParameters ( part ) ; GempakFileReader . RData vals = gemreader . DM_RDTR ( timeIdx + 1 , stnIdx + 1 , part ) ; ArraySequence aseq ; Sequence seq = ( Sequence ) pdata . findVariable ( part ) ; if ( vals == null ) { aseq = makeEmptySequence ( seq ) ; } else { allMissing = false ; aseq = makeArraySequence ( seq , params , vals . data ) ; } int index = abb . addObjectToHeap ( aseq ) ; buf . putInt ( index ) ; } buf . put ( ( byte ) ( allMissing ? 1 : 0 ) ) ; } } array = abb ; } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an empty ArraySequence for missing data [CODESPLIT] private ArraySequence makeEmptySequence ( Sequence seq ) { StructureMembers members = seq . makeStructureMembers ( ) ; return new ArraySequence ( members , new EmptyStructureDataIterator ( ) , - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ArraySequence to hold the data [CODESPLIT] private ArraySequence makeArraySequence ( Sequence seq , List < GempakParameter > params , float [ ] values ) { if ( values == null ) { return makeEmptySequence ( seq ) ; } int numLevels = values . length / params . size ( ) ; StructureMembers members = seq . makeStructureMembers ( ) ; int offset = ArrayStructureBB . setOffsets ( members ) ; int size = offset * numLevels ; byte [ ] bytes = new byte [ size ] ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) ; ArrayStructureBB abb = new ArrayStructureBB ( members , new int [ ] { numLevels } , buf , 0 ) ; int var = 0 ; for ( int i = 0 ; i < numLevels ; i ++ ) { for ( GempakParameter param : params ) { if ( members . findMember ( param . getName ( ) ) != null ) { buf . putFloat ( values [ var ] ) ; } var ++ ; } } return new ArraySequence ( members , new SequenceIterator ( numLevels , abb ) , numLevels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the netCDF file [CODESPLIT] protected void fillNCFile ( ) throws IOException { String fileType = gemreader . getFileSubType ( ) ; buildFile ( fileType . equals ( GempakSoundingFileReader . MERGED ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a standard station structure [CODESPLIT] private void buildFile ( boolean isMerged ) { // Build station list\r List < GempakStation > stations = gemreader . getStations ( ) ; Dimension station = new Dimension ( \"station\" , stations . size ( ) , true ) ; ncfile . addDimension ( null , station ) ; ncfile . addDimension ( null , DIM_LEN8 ) ; ncfile . addDimension ( null , DIM_LEN4 ) ; ncfile . addDimension ( null , DIM_LEN2 ) ; List < Variable > stationVars = makeStationVars ( stations , station ) ; // loop through and add to ncfile\r for ( Variable stnVar : stationVars ) { ncfile . addVariable ( null , stnVar ) ; } // Build variable list (var(station,time))\r // time\r List < Date > timeList = gemreader . getDates ( ) ; int numTimes = timeList . size ( ) ; Dimension times = new Dimension ( TIME_VAR , numTimes , true ) ; ncfile . addDimension ( null , times ) ; Array varArray ; Variable timeVar = new Variable ( ncfile , null , null , TIME_VAR , DataType . DOUBLE , TIME_VAR ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , \"seconds since 1970-01-01 00:00:00\" ) ) ; timeVar . addAttribute ( new Attribute ( \"long_name\" , TIME_VAR ) ) ; varArray = new ArrayDouble . D1 ( numTimes ) ; int i = 0 ; for ( Date date : timeList ) { ( ( ArrayDouble . D1 ) varArray ) . set ( i , date . getTime ( ) / 1000.d ) ; i ++ ; } timeVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , timeVar ) ; // build the data structure\r List < Dimension > stationTime = new ArrayList <> ( ) ; stationTime . add ( station ) ; stationTime . add ( times ) ; String structName = ( isMerged ) ? GempakSoundingFileReader . MERGED : GempakSoundingFileReader . UNMERGED ; structName = structName + \"Sounding\" ; Structure sVar = new Structure ( ncfile , null , null , structName ) ; sVar . setDimensions ( stationTime ) ; sVar . addAttribute ( new Attribute ( CF . COORDINATES , \"time SLAT SLON SELV\" ) ) ; List < String > sequenceNames ; if ( isMerged ) { sequenceNames = new ArrayList <> ( ) ; sequenceNames . add ( GempakSoundingFileReader . SNDT ) ; } else { sequenceNames = ( ( GempakSoundingFileReader ) gemreader ) . getUnmergedParts ( ) ; } for ( String seqName : sequenceNames ) { Sequence paramData = makeSequence ( sVar , seqName , false ) ; if ( paramData == null ) { continue ; } sVar . addMemberVariable ( paramData ) ; } sVar . addMemberVariable ( makeMissingVariable ( ) ) ; ncfile . addAttribute ( null , new Attribute ( \"CF:featureType\" , CF . FeatureType . timeSeriesProfile . toString ( ) ) ) ; ncfile . addVariable ( null , sVar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a Sequence for the part [CODESPLIT] protected Sequence makeSequence ( Structure parent , String partName , boolean includeMissing ) { List < GempakParameter > params = gemreader . getParameters ( partName ) ; if ( params == null ) { return null ; } Sequence sVar = new Sequence ( ncfile , null , parent , partName ) ; sVar . setDimensions ( \"\" ) ; for ( GempakParameter param : params ) { Variable v = makeParamVariable ( param , null ) ; addVerticalCoordAttribute ( v ) ; sVar . addMemberVariable ( v ) ; } if ( includeMissing ) { sVar . addMemberVariable ( makeMissingVariable ( ) ) ; } return sVar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the vertical coordinate variables if necessary [CODESPLIT] private void addVerticalCoordAttribute ( Variable v ) { GempakSoundingFileReader gsfr = ( GempakSoundingFileReader ) gemreader ; int vertType = gsfr . getVerticalCoordinate ( ) ; String pName = v . getFullName ( ) ; if ( gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . MERGED ) ) { if ( ( vertType == GempakSoundingFileReader . PRES_COORD ) && pName . equals ( \"PRES\" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Pressure . name ( ) ) ) ; } else if ( ( vertType == GempakSoundingFileReader . HGHT_COORD ) && ( pName . equals ( \"HGHT\" ) || pName . equals ( \"MHGT\" ) || pName . equals ( \"DHGT\" ) ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Height . name ( ) ) ) ; } } else if ( pName . equals ( \"PRES\" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Pressure . name ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This allows the possibility of reading a catalog in another thread . The default implementation does not do that but a subclass may override and implement . If the catalog is read successfully it is passed on to the callback . [CODESPLIT] public void readXMLasynch ( String uriString , CatalogSetCallback callback ) { InvCatalogImpl cat = readXML ( uriString ) ; callback . setCatalog ( cat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvCatalog from an XML document at a named URI . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( String uriString ) { URI uri ; try { uri = new URI ( uriString ) ; } catch ( URISyntaxException e ) { InvCatalogImpl cat = new InvCatalogImpl ( uriString , null , null ) ; cat . appendErrorMessage ( \"**Fatal:  InvCatalogFactory.readXML URISyntaxException on URL (\" + uriString + \") \" + e . getMessage ( ) + \"\\n\" , true ) ; return cat ; } /* if (uriString.startsWith(\"file:\")) {\n      String filename = uriString.substring(5);\n      File f = new File(filename);\n      if (f.exists()) {\n        try {\n          return readXML(new FileInputStream(f), uri);\n\n        } catch (Exception e) {\n          InvCatalogImpl cat = new InvCatalogImpl(uriString, null, null);\n          cat.appendErrorMessage(\"**Fatal:  InvCatalogFactory.readXML error (\" +\n              uriString + \") \" + e.getMessage() + \"\\n\", true);\n        }\n      }\n    }  */ return readXML ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an InvCatalog from an a URI . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( URI uri ) { // get ready for XML parsing warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; org . jdom2 . Document jdomDoc ; InputStream is = null ; try { jdomDoc = saxBuilder . build ( uri . toURL ( ) ) ; //      HttpUriResolver httpUriResolver = HttpUriResolver.newDefaultUriResolver(); //      String s = httpUriResolver.getString( url ); //      //StringReader //      is = new BufferedInputStream( httpUriResolver.getInputStream( url ), 1000000 ); //      jdomDoc = saxBuilder.build( is ); } catch ( Exception e ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , null ) ; cat . appendErrorMessage ( \"**Fatal:  InvCatalogFactory.readXML failed\" + \"\\n Exception= \" + e . getClass ( ) . getName ( ) + \" \" + e . getMessage ( ) + \"\\n fatalMessages= \" + fatalMessages . toString ( ) + \"\\n errMessages= \" + errMessages . toString ( ) + \"\\n warnMessages= \" + warnMessages . toString ( ) + \"\\n\" , true ) ; return cat ; } finally { if ( is != null ) try { is . close ( ) ; } catch ( IOException e ) { log . warn ( \"Failed to close input stream [\" + uri . toString ( ) + \"].\" ) ; } } if ( fatalMessages . length ( ) > 0 ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , null ) ; cat . appendErrorMessage ( \"**Fatal:  InvCatalogFactory.readXML XML Fatal error(s) =\\n\" + fatalMessages . toString ( ) + \"\\n\" , true ) ; return cat ; } return readXML ( jdomDoc , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvCatalog by reading catalog XML from a String . [CODESPLIT] public InvCatalogImpl readXML ( String catAsString , URI baseUri ) { return readXML ( new StringReader ( catAsString ) , baseUri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvCatalog by reading catalog XML from a StringReader . [CODESPLIT] public InvCatalogImpl readXML ( StringReader catAsStringReader , URI baseUri ) { XMLEntityResolver resolver = new XMLEntityResolver ( false ) ; SAXBuilder builder = resolver . getSAXBuilder ( ) ; Document inDoc ; try { inDoc = builder . build ( catAsStringReader ) ; } catch ( Exception e ) { InvCatalogImpl cat = new InvCatalogImpl ( baseUri . toString ( ) , null , null ) ; cat . appendErrorMessage ( \"**Fatal:  InvCatalogFactory.readXML(String catAsString, URI url) failed:\" + \"\\n  Exception= \" + e . getClass ( ) . getName ( ) + \" \" + e . getMessage ( ) + \"\\n  fatalMessages= \" + fatalMessages . toString ( ) + \"\\n  errMessages= \" + errMessages . toString ( ) + \"\\n  warnMessages= \" + warnMessages . toString ( ) + \"\\n\" , true ) ; return cat ; } return readXML ( inDoc , baseUri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvCatalog from an InputStream . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( InputStream docIs , URI uri ) { // get ready for XML parsing warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; org . jdom2 . Document jdomDoc ; try { jdomDoc = saxBuilder . build ( docIs ) ; } catch ( Exception e ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , uri ) ; cat . appendErrorMessage ( \"**Fatal:  InvCatalogFactory.readXML failed\" + \"\\n Exception= \" + e . getClass ( ) . getName ( ) + \" \" + e . getMessage ( ) + \"\\n fatalMessages= \" + fatalMessages . toString ( ) + \"\\n errMessages= \" + errMessages . toString ( ) + \"\\n warnMessages= \" + warnMessages . toString ( ) + \"\\n\" , true ) ; return cat ; } if ( fatalMessages . length ( ) > 0 ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , uri ) ; cat . appendErrorMessage ( \"**Fatal:  InvCatalogFactory.readXML XML Fatal error(s) =\\n\" + fatalMessages . toString ( ) + \"\\n\" , true ) ; return cat ; } return readXML ( jdomDoc , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an InvCatalog from a JDOM document . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( org . jdom2 . Document jdomDoc , URI uri ) { // decide on converter based on namespace Element root = jdomDoc . getRootElement ( ) ; if ( ! root . getName ( ) . equalsIgnoreCase ( \"catalog\" ) ) { throw new IllegalArgumentException ( \"not a catalog\" ) ; } String namespace = root . getNamespaceURI ( ) ; InvCatalogConvertIF fac = converters . get ( namespace ) ; if ( fac == null ) { fac = defaultConverter ; // LOOK if ( debugVersion ) System . out . println ( \"use default converter \" + fac . getClass ( ) . getName ( ) + \"; no namespace \" + namespace ) ; } else if ( debugVersion ) System . out . println ( \"use converter \" + fac . getClass ( ) . getName ( ) + \" based on namespace \" + namespace ) ; InvCatalogImpl cat = fac . parseXML ( this , jdomDoc , uri ) ; cat . setCreateFrom ( uri . toString ( ) ) ; // cat.setCatalogFactory(this); //cat.setCatalogConverter(fac); cat . finish ( ) ; /* if (showCatalogXML) {\n      System.out.println(\"*** catalog/showCatalogXML\");\n      try {\n        writeXML(cat, System.out);\n      }\n      catch (IOException ex) {\n        log.warn(\"Error writing catalog for debugging\", ex);\n      }\n    }  */ if ( fatalMessages . length ( ) > 0 ) cat . appendErrorMessage ( fatalMessages . toString ( ) , true ) ; // makes it invalid if ( errMessages . length ( ) > 0 ) cat . appendErrorMessage ( errMessages . toString ( ) , false ) ; // doesnt make it invalid if ( warnMessages . length ( ) > 0 ) cat . appendErrorMessage ( warnMessages . toString ( ) , false ) ; // doesnt make it invalid return cat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the InvCatalogImpl to the OutputStream as a InvCatalog 1 . 0 document . [CODESPLIT] public void writeXML ( InvCatalogImpl catalog , OutputStream os , boolean raw ) throws IOException { InvCatalogConvertIF converter = this . getCatalogConverter ( XMLEntityResolver . CATALOG_NAMESPACE_10 ) ; converter . writeXML ( catalog , os , raw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Write the catalog as an XML document to the specified filename . [CODESPLIT] public void writeXML ( InvCatalogImpl catalog , String filename ) throws IOException { BufferedOutputStream os = new BufferedOutputStream ( new FileOutputStream ( filename ) ) ; writeXML ( catalog , os , false ) ; os . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the catalog as an XML document to a String . [CODESPLIT] public String writeXML ( InvCatalogImpl catalog ) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream ( 10000 ) ; writeXML ( catalog , os , false ) ; return new String ( os . toByteArray ( ) , CDM . utf8Charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the MetadataConverterIF registered for this key [CODESPLIT] public MetadataConverterIF getMetadataConverter ( String key ) { if ( key == null ) return null ; return metadataConverters . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "testing [CODESPLIT] private static InvCatalogImpl doOne ( InvCatalogFactory fac , String urlString , boolean show ) { System . out . println ( \"***read \" + urlString ) ; if ( show ) System . out . println ( \" original catalog=\\n\" + IO . readURLcontents ( urlString ) ) ; try { InvCatalogImpl cat = fac . readXML ( new URI ( urlString ) ) ; StringBuilder buff = new StringBuilder ( ) ; boolean isValid = cat . check ( buff , false ) ; System . out . println ( \"catalog <\" + cat . getName ( ) + \"> \" + ( isValid ? \"is\" : \"is not\" ) + \" valid\" ) ; System . out . println ( \" validation output=\\n\" + buff ) ; // if (show) System.out.println(\" parsed catalog=\\n\" + fac.writeXML(cat)); //System.out.println(\" -----\\n\"+cat.dump()); return cat ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the identifiers associated with the dimensionless derived unit . [CODESPLIT] private static UnitName dimensionlessID ( ) { UnitName id ; try { id = UnitName . newUnitName ( \"1\" , \"1\" , \"1\" ) ; } catch ( final NameException e ) { id = null ; } return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiplies this derived unit by another . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { Unit result ; if ( dimension . getRank ( ) == 0 ) { result = that ; } else { if ( ! ( that instanceof DerivedUnit ) ) { result = that . multiplyBy ( this ) ; } else { final UnitDimension thatDimension = ( ( DerivedUnit ) that ) . getDimension ( ) ; result = thatDimension . getRank ( ) == 0 ? this : new DerivedUnitImpl ( dimension . multiplyBy ( thatDimension ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divides this derived unit by another . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws OperationException { Unit result ; if ( dimension . getRank ( ) == 0 ) { result = that . raiseTo ( - 1 ) ; } else { if ( ! ( that instanceof DerivedUnit ) ) { result = that . divideInto ( this ) ; } else { final UnitDimension thatDimension = ( ( DerivedUnit ) that ) . getDimension ( ) ; result = thatDimension . getRank ( ) == 0 ? this : new DerivedUnitImpl ( dimension . divideBy ( thatDimension ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts numerical values from this unit to the derived unit . Obviously the numerical values are unchanged . [CODESPLIT] public final float [ ] toDerivedUnit ( final float [ ] input , final float [ ] output ) { if ( input != output ) { System . arraycopy ( input , 0 , output , 0 , input . length ) ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if values in this unit are convertible with another unit . [CODESPLIT] @ Override public final boolean isCompatible ( final Unit that ) { final DerivedUnit unit = that . getDerivedUnit ( ) ; return equals ( unit ) || isReciprocalOf ( unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final BaseUnit second = BaseUnit . getOrCreate ( UnitName . newUnitName ( \"second\" , null , \"s\" ) , BaseQuantity . TIME ) ; System . out . println ( \"second = \\\"\" + second + ' ' ) ; final BaseUnit meter = BaseUnit . getOrCreate ( UnitName . newUnitName ( \"meter\" , null , \"m\" ) , BaseQuantity . LENGTH ) ; System . out . println ( \"meter = \\\"\" + meter + ' ' ) ; final DerivedUnitImpl meterSecond = ( DerivedUnitImpl ) meter . myMultiplyBy ( second ) ; System . out . println ( \"meterSecond = \\\"\" + meterSecond + ' ' ) ; final DerivedUnitImpl meterPerSecond = ( DerivedUnitImpl ) meter . myDivideBy ( second ) ; System . out . println ( \"meterPerSecond = \\\"\" + meterPerSecond + ' ' ) ; final DerivedUnitImpl secondPerMeter = ( DerivedUnitImpl ) second . myDivideBy ( meter ) ; System . out . println ( \"secondPerMeter = \\\"\" + secondPerMeter + ' ' ) ; System . out . println ( \"meterPerSecond.isReciprocalOf(secondPerMeter)=\" + meterPerSecond . isReciprocalOf ( secondPerMeter ) ) ; System . out . println ( \"meter.toDerivedUnit(1.0)=\" + meter . toDerivedUnit ( 1.0 ) ) ; System . out . println ( \"meter.toDerivedUnit(new double[] {1,2,3}, new double[3])[1]=\" + meter . toDerivedUnit ( new double [ ] { 1 , 2 , 3 } , new double [ 3 ] ) [ 1 ] ) ; System . out . println ( \"meter.fromDerivedUnit(1.0)=\" + meter . fromDerivedUnit ( 1.0 ) ) ; System . out . println ( \"meter.fromDerivedUnit(new double[] {1,2,3}, new double[3])[2]=\" + meter . fromDerivedUnit ( new double [ ] { 1 , 2 , 3 } , new double [ 3 ] ) [ 2 ] ) ; System . out . println ( \"meter.isCompatible(meter)=\" + meter . isCompatible ( meter ) ) ; System . out . println ( \"meter.isCompatible(second)=\" + meter . isCompatible ( second ) ) ; System . out . println ( \"meter.equals(meter)=\" + meter . equals ( meter ) ) ; System . out . println ( \"meter.equals(second)=\" + meter . equals ( second ) ) ; System . out . println ( \"meter.isDimensionless()=\" + meter . isDimensionless ( ) ) ; final Unit sPerS = second . myDivideBy ( second ) ; System . out . println ( \"sPerS = \\\"\" + sPerS + ' ' ) ; System . out . println ( \"sPerS.isDimensionless()=\" + sPerS . isDimensionless ( ) ) ; meterPerSecond . raiseTo ( 2 ) ; meter . myDivideBy ( meterPerSecond ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the type of the Simple Geom and calls the appropriate method to build the xml [CODESPLIT] public String writeFeature ( SimpleGeometry geom ) { if ( geom instanceof Point ) return writePoint ( ( Point ) geom ) ; else if ( geom instanceof Line ) return writeLine ( ( Line ) geom ) ; else if ( geom instanceof Polygon ) return writePolygon ( ( Polygon ) geom ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes in a point and writes its xml [CODESPLIT] private String writePoint ( Point point ) { String xml = \"\" ; xml += \"<gml:Point srsName=\\\"http://www.opengis.net/gml/srs/epsg.xml@900913\\\" srsDimension=\\\"2\\\">\" + \"<gml:pos>\" + point . getX ( ) + \" \" + point . getY ( ) + \"</gml:pos>\" + \"</gml:Point>\" ; return xml ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes in a line and iterates through all its points writing the posList to xml [CODESPLIT] private String writeLine ( Line line ) { String xml = \"\" ; xml += \"<gml:LineString><gml:posList>\" ; for ( Point point : line . getPoints ( ) ) { xml += point . getX ( ) + \" \" + point . getY ( ) + \" \" ; } xml += \"</gml:posList></gml:LineString>\" ; return xml ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes in a polygon checks whether it is an interior or exterior ring and writes the corresponding xml . Iterates through all linked polygons [CODESPLIT] private String writePolygon ( Polygon poly ) { String xml = \"\" ; xml += \"<gml:Polygon>\" ; Polygon polygon = poly ; //    while (polygon != null) {\r if ( ! polygon . getInteriorRing ( ) ) { xml += \"<gml:exterior><gml:LinearRing><gml:posList>\" ; for ( Point point : polygon . getPoints ( ) ) { xml += point . getX ( ) + \" \" + point . getY ( ) + \" \" ; } xml += \"</gml:posList></gml:LinearRing></gml:exterior>\" ; } else { xml += \"<gml:interior><gml:LinearRing><gml:posList>\" ; for ( Point point : polygon . getPoints ( ) ) { xml += point . getX ( ) + \" \" + point . getY ( ) + \" \" ; } xml += \"</gml:posList></gml:LinearRing></gml:interior>\" ; } //      polygon = polygon.getNext();\r // }\r xml += \"</gml:Polygon>\" ; return xml ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser API [CODESPLIT] public boolean parse ( String input ) throws SAXException { try { DocumentBuilderFactory domfactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder dombuilder = domfactory . newDocumentBuilder ( ) ; StringReader rdr = new StringReader ( input ) ; InputSource src = new InputSource ( rdr ) ; Document doc = dombuilder . parse ( src ) ; doc . getDocumentElement ( ) . normalize ( ) ; rdr . close ( ) ; parseresponse ( doc . getDocumentElement ( ) ) ; return true ; } catch ( ParserConfigurationException | IOException e ) { throw new SAXException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "XML Attribute utilities [CODESPLIT] protected String pull ( Node n , String name ) { NamedNodeMap map = n . getAttributes ( ) ; Node attr = map . getNamedItem ( name ) ; if ( attr == null ) return null ; return attr . getNodeValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attribute construction [CODESPLIT] DapAttribute makeAttribute ( DapSort sort , String name , DapType basetype , List < String > nslist ) throws ParseException { DapAttribute attr = factory . newAttribute ( name , basetype ) ; if ( sort == DapSort . ATTRIBUTE ) { attr . setBaseType ( basetype ) ; } attr . setNamespaceList ( nslist ) ; return attr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the subnodes of a node with non - element nodes suppressed [CODESPLIT] List < Node > getSubnodes ( Node parent ) { List < Node > subs = new ArrayList <> ( ) ; NodeList nodes = parent . getChildNodes ( ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node n = nodes . item ( i ) ; if ( n . getNodeType ( ) == Node . ELEMENT_NODE ) subs . add ( n ) ; } return subs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive descent parser [CODESPLIT] protected void parseresponse ( Node root ) throws ParseException { String elemname = root . getNodeName ( ) ; if ( elemname . equalsIgnoreCase ( \"Error\" ) ) { parseerror ( root ) ; } else if ( elemname . equalsIgnoreCase ( \"Dataset\" ) ) { parsedataset ( root ) ; } else throw new ParseException ( \"Unexpected response root: \" + elemname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pass reserved xml attributes unchanged [CODESPLIT] protected void passReserved ( Node node , DapNode dap ) throws ParseException { try { NamedNodeMap attrs = node . getAttributes ( ) ; for ( int i = 0 ; i < attrs . getLength ( ) ; i ++ ) { Node n = attrs . item ( i ) ; String key = n . getNodeName ( ) ; String value = n . getNodeValue ( ) ; if ( isReserved ( key ) ) dap . addXMLAttribute ( key , value ) ; } } catch ( DapException de ) { throw new ParseException ( de ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the subset string to be used in NetCDFFile . read given a variable and some indicies . useful for subsetting timeseries [CODESPLIT] public static String getSubsetString ( Variable var , int beginInd , int endInd , int id ) { if ( var == null ) return null ; String subStr = \"\" ; List < Dimension > dimList = var . getDimensions ( ) ; // Enforce two dimension arrays\r if ( dimList . size ( ) > 2 || dimList . size ( ) < 1 ) { return null ; } for ( int i = 0 ; i < dimList . size ( ) ; i ++ ) { Dimension dim = dimList . get ( i ) ; if ( dim == null ) continue ; // If not CF Time then select only that ID\r if ( ! CF . TIME . equalsIgnoreCase ( dim . getShortName ( ) ) && ! CF . TIME . equalsIgnoreCase ( dim . getFullNameEscaped ( ) ) ) { subStr += id ; } // Otherwise subset based on time\r else { if ( beginInd < 0 || endInd < 0 ) subStr += \":\" ; else subStr += ( beginInd + \":\" + endInd ) ; } if ( i < dimList . size ( ) - 1 ) { subStr += \",\" ; } } return subStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turn any ArrayStructure into a ArrayStructureMA [CODESPLIT] static public ArrayStructureMA factoryMA ( ArrayStructure from ) throws IOException { if ( from instanceof ArrayStructureMA ) return ( ArrayStructureMA ) from ; // To create an ArrayStructureMA that we can iterate over later, we need to know the shape of \"from\".\r if ( from . getSize ( ) > 0 ) { ArrayStructureMA to = new ArrayStructureMA ( new StructureMembers ( from . getStructureMembers ( ) ) , from . getShape ( ) ) ; for ( StructureMembers . Member m : from . getMembers ( ) ) { to . setMemberArray ( m . getName ( ) , from . extractMemberArray ( m ) ) ; } return to ; } // from.getSize() <= 0. This usually means that \"from\" is an ArraySequence, and that we won't know its size until\r // we iterate over it. extractMemberArray() will do that iteration for us, and then we can use the size of the\r // array it returns to determine the shape of \"from\".\r int numRecords = - 1 ; Map < String , Array > memberArrayMap = new LinkedHashMap <> ( ) ; for ( StructureMembers . Member m : from . getMembers ( ) ) { Array array = from . extractMemberArray ( m ) ; assert array . getSize ( ) > 0 : \"array's size should have been computed in extractMemberArray().\" ; int firstDimLen = array . getShape ( ) [ 0 ] ; if ( numRecords == - 1 ) { numRecords = firstDimLen ; } else { assert numRecords == firstDimLen : String . format ( \"Expected all structure members to have the same first\" + \"dimension length, but %d != %d.\" , numRecords , firstDimLen ) ; } memberArrayMap . put ( m . getName ( ) , array ) ; } int [ ] shape ; if ( numRecords == - 1 ) { shape = new int [ ] { 0 } ; // \"from\" really was empty.\r } else { shape = new int [ ] { numRecords } ; } ArrayStructureMA to = new ArrayStructureMA ( new StructureMembers ( from . getStructureMembers ( ) ) , shape ) ; for ( Map . Entry < String , Array > entry : memberArrayMap . entrySet ( ) ) { to . setMemberArray ( entry . getKey ( ) , entry . getValue ( ) ) ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data array for this member . [CODESPLIT] public void setMemberArray ( String memberName , Array data ) { StructureMembers . Member m = members . findMember ( memberName ) ; m . setDataArray ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ArrayStructure for a Structure . Allow nested Structures . Create the data arrays and an iterator . [CODESPLIT] static public ArrayStructureMA factoryMA ( Structure from , int [ ] shape ) throws IOException { StructureMembers sm = from . makeStructureMembers ( ) ; for ( Variable v : from . getVariables ( ) ) { Array data ; if ( v instanceof Sequence ) { data = Array . factory ( DataType . SEQUENCE , shape ) ; // an array sequence - one for each parent element\r //Structure s = (Structure) v;\r //StructureMembers smn = s.makeStructureMembers();\r // data = new ArraySequenceNested(smn, (int) Index.computeSize(v.getShapeAll())); // ??\r } else if ( v instanceof Structure ) data = ArrayStructureMA . factoryMA ( ( Structure ) v , combine ( shape , v . getShape ( ) ) ) ; else data = Array . factory ( v . getDataType ( ) , combine ( shape , v . getShape ( ) ) ) ; StructureMembers . Member m = sm . findMember ( v . getShortName ( ) ) ; m . setDataArray ( data ) ; } return new ArrayStructureMA ( sm , shape ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Polygon given a variable name and the geometric index . If the Polygon is not found it will return null . If the Polygon is a part of the Multi - Polygon it will return the head ( the first Polygon in the series which constitutes the Multi - Polygon ) . [CODESPLIT] public Polygon readPolygon ( String name , int index ) { Variable polyvar = ds . findVariable ( name ) ; if ( polyvar == null ) return null ; Polygon poly = null ; // CFConvention\r if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) poly = new CFPolygon ( ) ; if ( poly == null ) return null ; else return poly . setupPolygon ( ds , polyvar , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Line given a variable name and the geometric index . If the Line is not found it will return null . If the Line is a part of the Multi - Line it will return the head ( the first Line in the series which constitutes the Multi - Line ) . [CODESPLIT] public Line readLine ( String name , int index ) { Variable linevar = ds . findVariable ( name ) ; if ( linevar == null ) return null ; Line line = null ; // CFConvention\r if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) line = new CFLine ( ) ; if ( line == null ) return null ; else return line . setupLine ( ds , linevar , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Point given a variable name and the geometric index . If the Point is not found it will return null . If the Point is a part of the Multi - Point it will return the head ( the first Point in the series which constitutes the Multi - Point ) . [CODESPLIT] public Point readPoint ( String name , int index ) { Variable pointvar = ds . findVariable ( name ) ; if ( pointvar == null ) return null ; Point pt = null ; // CFConvention\r if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) pt = new CFPoint ( ) ; if ( pt == null ) return pt ; else return pt . setupPoint ( ds , pointvar , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a variable name returns the geometry type which that variable is associated with . If the variable has no simple geometry information null will be returned . [CODESPLIT] public GeometryType getGeometryType ( String name ) { Variable geometryVar = ds . findVariable ( name ) ; if ( geometryVar == null ) return null ; // CFConvention\r if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) { Attribute geometryTypeAttr = null ; String geometry_type = null ; geometryTypeAttr = geometryVar . findAttribute ( CF . GEOMETRY_TYPE ) ; if ( geometryTypeAttr == null ) return null ; geometry_type = geometryTypeAttr . getStringValue ( ) ; switch ( geometry_type ) { case CF . POLYGON : return GeometryType . POLYGON ; case CF . LINE : return GeometryType . LINE ; case CF . POINT : return GeometryType . POINT ; default : return null ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a Station from the station data structure . [CODESPLIT] public StationTimeSeriesFeature makeStation ( StructureData stationData , int recnum ) { StationFeature s = ft . makeStation ( stationData ) ; if ( s == null ) return null ; return new StandardStationFeatureImpl ( s , timeUnit , stationData , recnum ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive AST walker ; compilation of filters is done elsewhere . [CODESPLIT] protected void compileAST ( CEAST ast ) throws DapException { switch ( ast . sort ) { case CONSTRAINT : for ( CEAST clause : ast . clauses ) { compileAST ( clause ) ; } // invoke semantic checks this . ce . expand ( ) ; this . ce . finish ( ) ; break ; case PROJECTION : scopestack . clear ( ) ; compileAST ( ast . tree ) ; break ; case SEGMENT : compilesegment ( ast ) ; break ; case SELECTION : scopestack . clear ( ) ; compileselection ( ast ) ; break ; case DEFINE : dimredef ( ast ) ; break ; default : assert false : \"uknown CEAST node type\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert field references in a filter [CODESPLIT] public void compilefilter ( DapVariable var , DapSequence seq , CEAST expr ) throws DapException { if ( expr == null ) return ; if ( expr . sort == CEAST . Sort . SEGMENT ) { // This must be a simple segment and it must appear in seq if ( expr . subnodes != null ) throw new DapException ( \"compilefilter: Non-simple segment:\" + expr . name ) ; // Look for the name in the top-level field of seq DapVariable field = seq . findByName ( expr . name ) ; if ( field == null ) throw new DapException ( \"compilefilter: Unknown filter variable:\" + expr . name ) ; expr . field = field ; } else if ( expr . sort == CEAST . Sort . EXPR ) { if ( expr . lhs != null ) compilefilter ( var , seq , expr . lhs ) ; if ( expr . rhs != null ) compilefilter ( var , seq , expr . rhs ) ; // If both lhs and rhs are non-null, // canonicalize any comparison so that it is var op const if ( expr . lhs != null && expr . rhs != null ) { boolean leftvar = ( expr . lhs . sort == CEAST . Sort . SEGMENT ) ; boolean rightvar = ( expr . rhs . sort == CEAST . Sort . SEGMENT ) ; if ( rightvar && ! leftvar ) { // swap operands CEAST tmp = expr . lhs ; expr . lhs = expr . rhs ; expr . rhs = tmp ; // fix operator switch ( expr . op ) { case LT : //x<y -> y>x expr . op = CEAST . Operator . GT ; break ; case LE : //x<=y -> y>=x expr . op = CEAST . Operator . GE ; break ; case GT : //x>y -> y<x expr . op = CEAST . Operator . LT ; break ; case GE : //x>=y -> y<=x expr . op = CEAST . Operator . LE ; break ; default : break ; // leave as is } } } } else if ( expr . sort == CEAST . Sort . CONSTANT ) { return ; } else throw new DapException ( \"compilefilter: Unexpected node type:\" + expr . sort ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a dim redefinition [CODESPLIT] protected void dimredef ( CEAST node ) throws DapException { DapDimension dim = ( DapDimension ) dataset . findByFQN ( node . name , DapSort . DIMENSION ) ; if ( dim == null ) throw new DapException ( \"Constraint dim redef: no dimension name: \" + node . name ) ; Slice slice = node . slice ; slice . finish ( ) ; ce . addRedef ( dim , slice ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private . use Array . factory () [CODESPLIT] static ArrayObject factory ( DataType dtype , Class elemType , boolean isVlen , Index index ) { return ArrayObject . factory ( dtype , elemType , isVlen , index , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create new ArrayObject with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayObject factory ( DataType dtype , Class elemType , boolean isVlen , Index index , Object [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayObject . D0 ( dtype , elemType , isVlen , index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayObject . D1 ( dtype , elemType , isVlen , index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayObject . D2 ( dtype , elemType , isVlen , index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayObject . D3 ( dtype , elemType , isVlen , index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayObject . D4 ( dtype , elemType , isVlen , index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayObject . D5 ( dtype , elemType , isVlen , index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayObject . D6 ( dtype , elemType , isVlen , index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayObject . D7 ( dtype , elemType , isVlen , index , storage ) ; } else { return new ArrayObject ( dtype , elemType , isVlen , index , storage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create new Array with given indexImpl and the same backing store [CODESPLIT] protected Array createView ( Index index ) { return ArrayObject . factory ( dataType , elementType , isVlen , index , storage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { Object [ ] ja = ( Object [ ] ) javaArray ; for ( Object aJa : ja ) iter . setObjectNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if this rectangle is nearly equal to { @code other } . The near equality of corners is determined using { @link LatLonPoint#nearlyEquals ( LatLonPoint double ) } with the specified maxRelDiff . [CODESPLIT] public boolean nearlyEquals ( LatLonRect other , double maxRelDiff ) { return this . getLowerLeftPoint ( ) . nearlyEquals ( other . getLowerLeftPoint ( ) , maxRelDiff ) && this . getUpperRightPoint ( ) . nearlyEquals ( other . getUpperRightPoint ( ) , maxRelDiff ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given lat / lon point is contined inside this rectangle . [CODESPLIT] public boolean contains ( double lat , double lon ) { // check lat first\r double eps = 1.0e-9 ; if ( ( lat + eps < lowerLeft . getLatitude ( ) ) || ( lat - eps > upperRight . getLatitude ( ) ) ) { return false ; } if ( allLongitude ) return true ; if ( crossDateline ) { // bounding box crosses the +/- 180 seam\r return ( ( lon >= lowerLeft . getLongitude ( ) ) || ( lon <= upperRight . getLongitude ( ) ) ) ; } else { // check \"normal\" lon case\r return ( ( lon >= lowerLeft . getLongitude ( ) ) && ( lon <= upperRight . getLongitude ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this bounding box is contained in another LatLonRect . [CODESPLIT] public boolean containedIn ( LatLonRect b ) { return ( b . getWidth ( ) >= width ) && b . contains ( upperRight ) && b . contains ( lowerLeft ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend the bounding box to contain this point [CODESPLIT] public void extend ( LatLonPoint p ) { if ( contains ( p ) ) return ; double lat = p . getLatitude ( ) ; double lon = p . getLongitude ( ) ; // lat is easy to deal with\r if ( lat > upperRight . getLatitude ( ) ) { upperRight . setLatitude ( lat ) ; } if ( lat < lowerLeft . getLatitude ( ) ) { lowerLeft . setLatitude ( lat ) ; } // lon is uglier\r if ( allLongitude ) { // do nothing\r } else if ( crossDateline ) { // bounding box crosses the +/- 180 seam\r double d1 = lon - upperRight . getLongitude ( ) ; double d2 = lowerLeft . getLongitude ( ) - lon ; if ( ( d1 > 0.0 ) && ( d2 > 0.0 ) ) { // needed ?\r if ( d1 > d2 ) { lowerLeft . setLongitude ( lon ) ; } else { upperRight . setLongitude ( lon ) ; } } } else { // normal case\r if ( lon > upperRight . getLongitude ( ) ) { if ( lon - upperRight . getLongitude ( ) > lowerLeft . getLongitude ( ) - lon + 360 ) { crossDateline = true ; lowerLeft . setLongitude ( lon ) ; } else { upperRight . setLongitude ( lon ) ; } } else if ( lon < lowerLeft . getLongitude ( ) ) { if ( lowerLeft . getLongitude ( ) - lon > lon + 360.0 - upperRight . getLongitude ( ) ) { crossDateline = true ; upperRight . setLongitude ( lon ) ; } else { lowerLeft . setLongitude ( lon ) ; } } } // recalc delta, center\r width = upperRight . getLongitude ( ) - lowerLeft . getLongitude ( ) ; lon0 = ( upperRight . getLongitude ( ) + lowerLeft . getLongitude ( ) ) / 2 ; if ( crossDateline ) { width += 360 ; lon0 -= 180 ; } this . allLongitude = this . allLongitude || ( this . width >= 360.0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend the bounding box to contain the given rectangle [CODESPLIT] public void extend ( LatLonRect r ) { Preconditions . checkNotNull ( r ) ; // lat is easy\r double latMin = r . getLatMin ( ) ; double latMax = r . getLatMax ( ) ; if ( latMax > upperRight . getLatitude ( ) ) { upperRight . setLatitude ( latMax ) ; } if ( latMin < lowerLeft . getLatitude ( ) ) { lowerLeft . setLatitude ( latMin ) ; } // lon is uglier\r if ( allLongitude ) return ; // everything is reletive to current LonMin\r double lonMin = getLonMin ( ) ; double lonMax = getLonMax ( ) ; double nlonMin = LatLonPointImpl . lonNormal ( r . getLonMin ( ) , lonMin ) ; double nlonMax = nlonMin + r . getWidth ( ) ; lonMin = Math . min ( lonMin , nlonMin ) ; lonMax = Math . max ( lonMax , nlonMax ) ; width = lonMax - lonMin ; allLongitude = width >= 360.0 ; if ( allLongitude ) { width = 360.0 ; lonMin = - 180.0 ; } else { lonMin = LatLonPointImpl . lonNormal ( lonMin ) ; } lowerLeft . setLongitude ( lonMin ) ; upperRight . setLongitude ( lonMin + width ) ; lon0 = lonMin + width / 2 ; crossDateline = lowerLeft . getLongitude ( ) > upperRight . getLongitude ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the instersection of this LatLon with the given one [CODESPLIT] public LatLonRect intersect ( LatLonRect clip ) { double latMin = Math . max ( getLatMin ( ) , clip . getLatMin ( ) ) ; double latMax = Math . min ( getLatMax ( ) , clip . getLatMax ( ) ) ; double deltaLat = latMax - latMin ; if ( deltaLat < 0 ) return null ; // lon as always is a pain : if not intersection, try +/- 360\r double lon1min = getLonMin ( ) ; double lon1max = getLonMax ( ) ; double lon2min = clip . getLonMin ( ) ; double lon2max = clip . getLonMax ( ) ; if ( ! intersect ( lon1min , lon1max , lon2min , lon2max ) ) { lon2min = clip . getLonMin ( ) + 360 ; lon2max = clip . getLonMax ( ) + 360 ; if ( ! intersect ( lon1min , lon1max , lon2min , lon2max ) ) { lon2min = clip . getLonMin ( ) - 360 ; lon2max = clip . getLonMax ( ) - 360 ; } } // we did our best to find an intersection\r double lonMin = Math . max ( lon1min , lon2min ) ; double lonMax = Math . min ( lon1max , lon2max ) ; double deltaLon = lonMax - lonMin ; if ( deltaLon < 0 ) return null ; return new LatLonRect ( new LatLonPointImpl ( latMin , lonMin ) , deltaLat , deltaLon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a String representation of this object . <pre > lat = [ - 90 . 00 90 . 00 ] lon = [ 0 . 00 360 . 00< / pre > [CODESPLIT] public String toString2 ( ) { return \" lat= [\" + Format . dfrac ( getLatMin ( ) , 2 ) + \",\" + Format . dfrac ( getLatMax ( ) , 2 ) + \"] lon= [\" + Format . dfrac ( getLonMin ( ) , 2 ) + \",\" + Format . dfrac ( getLonMax ( ) , 2 ) + \"]\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add elements of two arrays together allocating the result array . The result type and the operation type are taken from the type of a . [CODESPLIT] public static Array add ( Array a , Array b ) throws IllegalArgumentException { Array result = Array . factory ( a . getDataType ( ) , a . getShape ( ) ) ; if ( a . getElementType ( ) == double . class ) { addDouble ( result , a , b ) ; } else throw new UnsupportedOperationException ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add elements of two arrays together as doubles place sum in the result array . The values from the arrays a and b are converted to double ( if needed ) and the sum is converted to the type of result ( if needed ) . [CODESPLIT] public static void addDouble ( Array result , Array a , Array b ) throws IllegalArgumentException { if ( ! conformable ( result , a ) || ! conformable ( a , b ) ) throw new IllegalArgumentException ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterB = b . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setDoubleNext ( iterA . getDoubleNext ( ) + iterB . getDoubleNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that two arrays are conformable . [CODESPLIT] public static boolean conformable ( Array a , Array b ) { return conformable ( a . getShape ( ) , b . getShape ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that two array shapes are conformable . The shapes must match exactly except that dimensions of length 1 are ignored . [CODESPLIT] public static boolean conformable ( int [ ] shapeA , int [ ] shapeB ) { if ( reducedRank ( shapeA ) != reducedRank ( shapeB ) ) return false ; int rankB = shapeB . length ; int dimB = 0 ; for ( int aShapeA : shapeA ) { //System.out.println(dimA + \" \"+ dimB);\r //skip length 1 dimensions\r if ( aShapeA == 1 ) continue ; while ( dimB < rankB ) if ( shapeB [ dimB ] == 1 ) dimB ++ ; else break ; // test same shape (NB dimB cant be > rankB due to first test)\r if ( aShapeA != shapeB [ dimB ] ) return false ; dimB ++ ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert original array to desired type [CODESPLIT] public static Array convert ( Array org , DataType wantType ) { if ( org == null ) return null ; Class wantClass = wantType . getPrimitiveClassType ( ) ; if ( org . getElementType ( ) . equals ( wantClass ) ) return org ; Array result = Array . factory ( wantType , org . getShape ( ) ) ; copy ( wantType , org . getIndexIterator ( ) , result . getIndexIterator ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy using iterators . Will copy until !from . hasNext () . [CODESPLIT] public static void copy ( DataType dataType , IndexIterator from , IndexIterator to ) throws IllegalArgumentException { if ( dataType == DataType . DOUBLE ) { while ( from . hasNext ( ) ) to . setDoubleNext ( from . getDoubleNext ( ) ) ; } else if ( dataType == DataType . FLOAT ) { while ( from . hasNext ( ) ) to . setFloatNext ( from . getFloatNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { while ( from . hasNext ( ) ) to . setLongNext ( from . getLongNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { while ( from . hasNext ( ) ) to . setIntNext ( from . getIntNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { while ( from . hasNext ( ) ) to . setShortNext ( from . getShortNext ( ) ) ; } else if ( dataType == DataType . CHAR ) { while ( from . hasNext ( ) ) to . setCharNext ( from . getCharNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == byte . class ) { while ( from . hasNext ( ) ) to . setByteNext ( from . getByteNext ( ) ) ; } else if ( dataType == DataType . BOOLEAN ) { while ( from . hasNext ( ) ) to . setBooleanNext ( from . getBooleanNext ( ) ) ; } else { while ( from . hasNext ( ) ) to . setObjectNext ( from . getObjectNext ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy array a to array result the result array will be in canonical order The operation type is taken from the type of a . [CODESPLIT] public static void copy ( Array result , Array a ) throws IllegalArgumentException { Class classType = a . getElementType ( ) ; if ( classType == double . class ) { copyDouble ( result , a ) ; } else if ( classType == float . class ) { copyFloat ( result , a ) ; } else if ( classType == long . class ) { copyLong ( result , a ) ; } else if ( classType == int . class ) { copyInt ( result , a ) ; } else if ( classType == short . class ) { copyShort ( result , a ) ; } else if ( classType == char . class ) { copyChar ( result , a ) ; } else if ( classType == byte . class ) { copyByte ( result , a ) ; } else if ( classType == boolean . class ) { copyBoolean ( result , a ) ; } else copyObject ( result , a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as doubles The values from the arrays a are converted to double ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyDouble ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setDoubleNext ( iterA . getDoubleNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as floats The values from the arrays a are converted to float ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyFloat ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setFloatNext ( iterA . getFloatNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as longs The values from the array a are converted to long ( if needed ) and then converted to the type of result ( if needed ) . @param result copy to here @param a copy from here [CODESPLIT] public static void copyLong ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setLongNext ( iterA . getLongNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as integers The values from the arrays a are converted to integer ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyInt ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setIntNext ( iterA . getIntNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as shorts The values from the array a are converted to short ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyShort ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setShortNext ( iterA . getShortNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as char The values from the array a are converted to char ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyChar ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setCharNext ( iterA . getCharNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as bytes The values from the array a are converted to byte ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyByte ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setByteNext ( iterA . getByteNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as bytes The array a and result must be type boolean [CODESPLIT] public static void copyBoolean ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setBooleanNext ( iterA . getBooleanNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy array a to array result as an Object The array a and result must be type object [CODESPLIT] public static void copyObject ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( \"copy arrays are not conformable\" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) { iterR . setObjectNext ( iterA . getObjectNext ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find min and max value in this array getting values as doubles . Skip Double . NaN . [CODESPLIT] public static MAMath . MinMax getMinMax ( Array a ) { IndexIterator iter = a . getIndexIterator ( ) ; double max = - Double . MAX_VALUE ; double min = Double . MAX_VALUE ; while ( iter . hasNext ( ) ) { double val = iter . getDoubleNext ( ) ; if ( Double . isNaN ( val ) ) continue ; if ( val > max ) max = val ; if ( val < min ) min = val ; } return new MinMax ( min , max ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set all the elements of this array to the given double value . The value is converted to the element type of the array if needed . [CODESPLIT] public static void setDouble ( Array result , double val ) { IndexIterator iter = result . getIndexIterator ( ) ; while ( iter . hasNext ( ) ) { iter . setDoubleNext ( val ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sum all of the elements of array a as doubles . The values from the array a are converted to double ( if needed ) . [CODESPLIT] public static double sumDouble ( Array a ) { double sum = 0 ; IndexIterator iterA = a . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) { sum += iterA . getDoubleNext ( ) ; } return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sum all of the elements of array a as doubles . The values from the array a are converted to double ( if needed ) . [CODESPLIT] public static double sumDoubleSkipMissingData ( Array a , double missingValue ) { double sum = 0 ; IndexIterator iterA = a . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) { double val = iterA . getDoubleNext ( ) ; if ( ( val == missingValue ) || Double . isNaN ( val ) ) continue ; sum += val ; } return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the scale / offset for an array of numbers . <pre > If signed : then max value unpacked = 2^ ( n - 1 ) - 1 packed min value unpacked = - ( 2^ ( n - 1 ) - 1 ) packed note that - 2^ ( n - 1 ) is unused and a good place to map missing values by solving 2 eq in 2 unknowns we get : scale = ( max - min ) / ( 2^n - 2 ) offset = ( max + min ) / 2 If unsigned then max value unpacked = 2^n - 1 packed min value unpacked = 0 packed and : scale = ( max - min ) / ( 2^n - 1 ) offset = min One could modify this to allow a holder for missing values . < / pre > [CODESPLIT] public static MAMath . ScaleOffset calcScaleOffsetSkipMissingData ( Array a , double missingValue , int nbits ) { MAMath . MinMax minmax = getMinMaxSkipMissingData ( a , missingValue ) ; if ( a . isUnsigned ( ) ) { long size = ( 1L << nbits ) - 1 ; double offset = minmax . min ; double scale = ( minmax . max - minmax . min ) / size ; return new ScaleOffset ( scale , offset ) ; } else { long size = ( 1L << nbits ) - 2 ; double offset = ( minmax . max + minmax . min ) / 2 ; double scale = ( minmax . max - minmax . min ) / size ; return new ScaleOffset ( scale , offset ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the specified arrays have the same size signedness and <b > approximately< / b > equal corresponding elements . { @code float } elements must be within { @link Misc#defaultMaxRelativeDiffFloat } of each other as determined by { @link Misc#nearlyEquals ( double double double ) } . Similarly { @code double } elements must be within { @link Misc#defaultMaxRelativeDiffDouble } of each other . <p > { @link #equals ( Array Array ) } is an alternative to this method that requires that corresponding elements be <b > exactly< / b > equal . It is suitable for use in { @link Object#equals } implementations whereas this method isn t . [CODESPLIT] public static boolean nearlyEquals ( Array data1 , Array data2 ) { if ( data1 == data2 ) { // Covers case when both are null.\r return true ; } else if ( data1 == null || data2 == null ) { return false ; } if ( data1 . getSize ( ) != data2 . getSize ( ) ) return false ; if ( data1 . isUnsigned ( ) != data2 . isUnsigned ( ) ) return false ; DataType dt = DataType . getType ( data1 ) ; IndexIterator iter1 = data1 . getIndexIterator ( ) ; IndexIterator iter2 = data2 . getIndexIterator ( ) ; if ( dt == DataType . DOUBLE ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { double v1 = iter1 . getDoubleNext ( ) ; double v2 = iter2 . getDoubleNext ( ) ; if ( ! Misc . nearlyEquals ( v1 , v2 , Misc . defaultMaxRelativeDiffDouble ) ) return false ; } } else if ( dt == DataType . FLOAT ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { float v1 = iter1 . getFloatNext ( ) ; float v2 = iter2 . getFloatNext ( ) ; if ( ! Misc . nearlyEquals ( v1 , v2 , Misc . defaultMaxRelativeDiffFloat ) ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == int . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { int v1 = iter1 . getIntNext ( ) ; int v2 = iter2 . getIntNext ( ) ; if ( v1 != v2 ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == byte . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { short v1 = iter1 . getShortNext ( ) ; short v2 = iter2 . getShortNext ( ) ; if ( v1 != v2 ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == short . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { byte v1 = iter1 . getByteNext ( ) ; byte v2 = iter2 . getByteNext ( ) ; if ( v1 != v2 ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == long . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { long v1 = iter1 . getLongNext ( ) ; long v2 = iter2 . getLongNext ( ) ; if ( v1 != v2 ) return false ; } } else { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { if ( ! Objects . equals ( iter1 . next ( ) , iter2 . next ( ) ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * @Override public List<CalendarDate > getCalendarDates () { if ( getTimeAxis () ! = null ) return getTimeAxis () . getCalendarDates () ; [CODESPLIT] @ Override public CalendarDateRange getCalendarDateRange ( ) { if ( getTimeAxis ( ) != null ) return getTimeAxis ( ) . getCalendarDateRange ( ) ; else if ( getRunTimeAxis ( ) != null ) return getRunTimeAxis ( ) . getCalendarDateRange ( ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "turn ConfigCatalog into a mutable CatalogBuilder so we can mutate [CODESPLIT] public CatalogBuilder makeCatalogBuilder ( ) { CatalogBuilder builder = new CatalogBuilder ( this ) ; for ( Dataset ds : getDatasetsLocal ( ) ) { builder . addDataset ( makeDatasetBuilder ( null , ds ) ) ; } return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > AttributeTable< / code > with the given name . [CODESPLIT] public final AttributeTable getAttributeTable ( String name ) throws NoSuchAttributeException { AttributeTable at = null ; Attribute a = getAttribute ( name ) ; if ( a != null ) { if ( a . isContainer ( ) ) { at = a . getContainer ( ) ; } } return ( at ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > AttributeTable< / code > with the given name . [CODESPLIT] public final AttributeTable getAttributeTableN ( String name ) { AttributeTable at = null ; Attribute a = getAttribute ( name ) ; if ( a != null ) { if ( a . isContainer ( ) ) { at = a . getContainerN ( ) ; } } return ( at ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method searchs through the <code > DAS< / code > for Alias members . When an Alias is found the method attempts to resolve it to a specific Attribute . <p / > This method is invoked by <code > parse ( InputStream is ) < / code > and is used to search for Aliases in AttributeTables found in the DAS . <p / > If you are building a DAS from it s API it is important to call this method prior to returning said DAS to an application . If this call is not made Aliases will not work correctly . [CODESPLIT] public void resolveAliases ( ) throws MalformedAliasException , UnresolvedAliasException , NoSuchAttributeException { resolveAliases ( this ) ; // Enforce the rule that Aliases at the highest level of the DAS\r // must point to a container (AttributeTable)\r Enumeration e = getNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"DAS.resolveAliases() - aName: \" + aName ) ; } Attribute at = getAttribute ( aName ) ; if ( at == null || ! at . isContainer ( ) ) { throw new MalformedAliasException ( \"Aliases at the top-level of a DAS MUST reference a container (AttributeTable), not a simple Attribute\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method recursively searchs through the passed <code > AttributeTable< / code > parameter at for Alias members . When an Alias is found the method attempts to resolve it to a specific Attribute . <p / > This method gets called is invoked by <code > reolveAliases ( BaseType bt ) < / code > and is used to search for Aliases in AttributeTables found in a BaseTypes Attributes . <p / > This method manipulates the global variable <code > currentBT< / code > . [CODESPLIT] private void resolveAliases ( AttributeTable at ) throws MalformedAliasException , UnresolvedAliasException , NoSuchAttributeException { // Cache the current (parent) Attribute table. This value is\r // null if this method is called from parse();\r AttributeTable cacheAT = currentAT ; try { // Set the current AttributeTable to the one that we are searching.\r currentAT = at ; if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"DAS.resolveAliases(at=\" + at + \")\" ) ; } //getall of the Attributes from the table.\r Enumeration aNames = at . getNames ( ) ; while ( aNames . hasMoreElements ( ) ) { String aName = ( String ) aNames . nextElement ( ) ; if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"DAS.resolveAliases(at=\" + at + \") - aName: \" + aName ) ; } opendap . dap . Attribute thisA = currentAT . getAttribute ( aName ) ; if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"thisA.getClass().getName(): \" + thisA . getClass ( ) . getName ( ) ) ; } if ( thisA . isAlias ( ) ) { //Is Alias? Resolve it!\r resolveAlias ( ( Alias ) thisA ) ; if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"Resolved Alias: '\" + thisA . getEncodedName ( ) + \"'\\n\" ) ; } } else if ( thisA . isContainer ( ) ) { //Is AttributeTable (container)? Search it!\r resolveAliases ( thisA . getContainer ( ) ) ; } } } finally { // Restore the previous currentAT state.\r currentAT = cacheAT ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method attempts to resolve the past Alias to a specific Attribute in the DDS . It does this by : <ul > <li > 1 ) Tokenizing the Alias s variable and attribute fields ( see <code > Alias< / code > ) < / li > <li > 2 ) Evaluating the tokenized fields to determine if the Alias is defined in terms of a relative or absolute path < / li > <li > 3 ) Searching the DAS or the currentAT ( depending on results of 2 ) for the target Attribute < / li > <li > 4 ) Setting the Aliases intrnal reference to it s Attribute < / ul > <p / > If an Attribute matching the definition of the Alias cannot be located an Exception is thrown [CODESPLIT] private void resolveAlias ( Alias alias ) throws MalformedAliasException , UnresolvedAliasException { //Get the crucial stuff out of the Alias\r String name = alias . getClearName ( ) ; String attribute = alias . getAliasedToAttributeFieldAsClearString ( ) ; // Get ready!\r Enumeration e = null ; currentAlias = alias ; if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"\\n\\nFound: Alias \" + name + \"  \" + attribute ) ; } // Let's go\r // see if we can find an Attribute within that DAS that matches the attribute field\r // in the Alias declartion.\r // The Attribute field MAY NOT be empty.\r if ( attribute . equals ( \"\" ) ) { throw new MalformedAliasException ( \"The attribute 'attribute' in the Alias \" + \"element must have a value other than an empty string.\" ) ; } if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"Attribute: `\" + attribute + \"'\" ) ; } // Tokenize the attribute field.\r Vector aNames = opendap . dap . DDS . tokenizeAliasField ( attribute ) ; if ( Debug . isSet ( \"DAS\" ) ) { DAPNode . log . debug ( \"Attribute name tokenized to \" + aNames . size ( ) + \" elements\" ) ; e = aNames . elements ( ) ; while ( e . hasMoreElements ( ) ) { String aname = ( String ) e . nextElement ( ) ; DAPNode . log . debug ( \"name: \" + aname ) ; } } opendap . dap . Attribute targetAT = null ; // Absolute paths for attributes names must start with the dot character.\r boolean isAbsolutePath = aNames . get ( 0 ) . equals ( \".\" ) ; if ( isAbsolutePath ) { //Is it an absolute path?\r if ( aNames . size ( ) == 1 ) { throw new MalformedAliasException ( \"Aliases must reference an Attribute. \" + \"An attribute field of dot (.) references the entire \" + \"DAS, which is not allowed.\" ) ; } else { // Dump the dot from the vector of tokens and go try to find\r // the Attribute in the DAS.\r aNames . remove ( 0 ) ; targetAT = getAliasAttribute ( this , aNames ) ; } } else { throw new MalformedAliasException ( \"In the Alias '\" + name + \"'\" + \" the attribute 'attribute' does not begin with the character dot (.). \" + \"The 'attribute' field must always be an absoulute path name from the \" + \"top level of the dataset, and thus must always begin with the dot (.) character.\" ) ; } alias . setMyAttribute ( targetAT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes a ( recursive ) search of the <code > AttributeTable< / code > parameter <b > at< / b > for an <code > Attribute< / code > whose name resolves to the vector of names contained in the <code > Vector< / code > parameter <b > aNames< / b > . An Attribute is considered a match if each of it s node names in the hierarchy of AttributeTables contained in the one passed as parameter <b > at< / b > matches ( equals ) the corresponding name in the Vector <b > aNames< / b > . [CODESPLIT] private opendap . dap . Attribute getAliasAttribute ( AttributeTable att , Vector aNames ) throws MalformedAliasException , UnresolvedAliasException { // Get the first node name form the vector.\r String aName = ( String ) aNames . get ( 0 ) ; // Get the list of child nodes from the AttributeTable\r Enumeration e = att . getNames ( ) ; while ( e . hasMoreElements ( ) ) { // Get an Attribute\r String atName = ( String ) e . nextElement ( ) ; opendap . dap . Attribute a = att . getAttribute ( atName ) ; // Get the Attributes name and Normalize it.\r String normName = opendap . dap . DDS . normalize ( a . getEncodedName ( ) ) ; // Are they the same?\r if ( normName . equals ( aName ) ) { // Make sure this reference doesn't pass through an Alias.\r if ( a . isAlias ( ) ) { throw new MalformedAliasException ( \"Aliases may NOT point to other aliases\" ) ; } //dump the name from the list of names.\r aNames . remove ( 0 ) ; // Are there more?\r if ( aNames . size ( ) == 0 ) { //No! We found it!\r return ( a ) ; } else if ( a . isContainer ( ) ) { // Is this Attribute a container (it better be)\r try { // Recursively search for the rest of the name vector in the container.\r return ( getAliasAttribute ( a . getContainer ( ) , aNames ) ) ; } catch ( NoSuchAttributeException nsae ) { throw new MalformedAliasException ( \"Attribute \" + a . getEncodedName ( ) + \" is not an attribute container. (AttributeTable) \" + \" It may not contain the attribute: \" + aName ) ; } } else { // Dead-end, through an exception!\r throw new MalformedAliasException ( \"Attribute \" + a . getEncodedName ( ) + \" is not an attribute container. (AttributeTable) \" + \" It may not contain the attribute: \" + aName ) ; } } } // Nothing Matched, so this search failed.\r throw new UnresolvedAliasException ( \"The alias `\" + currentAlias . getEncodedName ( ) + \"` references the attribute: `\" + aName + \"` which cannot be found.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Attribute< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DAS das = ( DAS ) super . cloneDAG ( map ) ; return das ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Code table 6 – Data representation type Code figure Meaning 0 Latitude / longitude grid – equidistant cylindrical or Plate Carrée projection 1 Mercator projection 2 Gnomonic projection 3 Lambert conformal secant or tangent conic or bi - polar projection 4 Gaussian latitude / longitude grid 5 Polar stereographic projection 6 Universal Transverse Mercator ( UTM ) projection 7 Simple polyconic projection 8 Albers equal - area secant or tangent conic or bi - polar projection 9 Miller’s cylindrical projection 10 Rotated latitude / longitude grid 11–12 Reserved 13 Oblique Lambert conformal secant or tangent conic or bi - polar projection 14 Rotated Gaussian latitude / longitude grid 15–19 Reserved 20 Stretched latitude / longitude grid 21–23 Reserved 24 Stretched Gaussian latitude / longitude grid 25–29 Reserved 30 Stretched and rotated latitude / longitude grids 31–33 Reserved 34 Stretched and rotated Gaussian latitude / longitude grids 35–49 Reserved ^ 50 Spherical harmonic coefficients 51–59 Reserved 60 Rotated spherical harmonic coefficients 61–69 Reserved 70 Stretched spherical harmonics 71–79 Reserved 80 Stretched and rotated spherical harmonic coefficients 81–89 Reserved 90 Space view perspective or orthographic 91–191 Reserved 192–254 Reserved for local use [CODESPLIT] public static Grib1Gds factory ( int template , byte [ ] data ) { switch ( template ) { case 0 : return new LatLon ( data , 0 ) ; case 1 : return new Mercator ( data , 1 ) ; case 3 : return new LambertConformal ( data , 3 ) ; case 4 : return new GaussianLatLon ( data , 4 ) ; case 5 : return new PolarStereographic ( data , 5 ) ; case 10 : return new RotatedLatLon ( data , 10 ) ; case 50 : return new SphericalHarmonicCoefficients ( data , 50 ) ; default : return new UnknownGds ( data , template ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "signed [CODESPLIT] protected int getOctet3 ( int start ) { return GribNumbers . int3 ( getOctet ( start ) , getOctet ( start + 1 ) , getOctet ( start + 2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for OPeNDAP directory requests . Returns an html document with a list of all datasets on this server with links to their DDS DAS Information and HTML responses . [CODESPLIT] public void sendDIR ( ReqState rs ) throws opendap . dap . DAP2Exception , ParseException { if ( _Debug ) System . out . println ( \"sendDIR request = \" + rs . getRequest ( ) ) ; try { PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; // ignore String ddxCacheDir = rs.getDDXCache(rs.getRootPath()); String ddsCacheDir = rs . getDDSCache ( rs . getRootPath ( ) ) ; String thisServer = rs . getRequest ( ) . getRequestURL ( ) . toString ( ) ; pw . println ( \"<html>\" ) ; pw . println ( \"<head>\" ) ; pw . println ( \"<title>OPeNDAP Directory</title>\" ) ; pw . println ( \"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html\\\">\" ) ; pw . println ( \"</head>\" ) ; pw . println ( \"<body bgcolor=\\\"#FFFFFF\\\">\" ) ; pw . println ( \"<h1>OPeNDAP Directory for:</h1>\" ) ; pw . println ( \"<h2>\" + thisServer + \"</h2>\" ) ; // ignore printDIR(pw, ddxCacheDir, \"DDX\", thisServer); printDIR ( pw , ddsCacheDir , \"DDS\" , thisServer ) ; pw . println ( \"<hr>\" ) ; pw . println ( \"</html>\" ) ; pw . flush ( ) ; } catch ( FileNotFoundException fnfe ) { System . out . println ( \"OUCH! FileNotFoundException: \" + fnfe . getMessage ( ) ) ; fnfe . printStackTrace ( System . out ) ; } catch ( IOException ioe ) { System . out . println ( \"OUCH! IOException: \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( System . out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ProjectionImpl from the projection [CODESPLIT] static public ProjectionImpl factory ( Projection proj ) { if ( proj instanceof ProjectionImpl ) { return ( ProjectionImpl ) proj ; } return new ProjectionAdapter ( proj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl result ) { return proj . latLonToProj ( latlon , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { return proj . projToLatLon ( world , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Iterator < StationProfileFeature > iterator ( ) { try { PointFeatureCCIterator pfIterator = getNestedPointFeatureCollectionIterator ( ) ; return new NestedCollectionIteratorAdapter <> ( pfIterator ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the DEFINITIVE opendap identifier unescape function . [CODESPLIT] public static String unescapeDAPIdentifier ( String id ) { String s ; try { s = unescapeString ( id ) ; } catch ( Exception e ) { s = null ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the DEFINITIVE URL unescape function . [CODESPLIT] public static String urlDecode ( String s ) { try { //s = unescapeString(s, _URIEscape, \"\", false); s = URLDecoder . decode ( s , \"UTF-8\" ) ; } catch ( Exception e ) { s = null ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode all of the parts of the url including query and fragment [CODESPLIT] public static String unescapeURL ( String url ) { String newurl ; newurl = urlDecode ( url ) ; return newurl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "backslash escape a string [CODESPLIT] static public String backslashEscape ( String x , String reservedChars ) { if ( x == null ) { return null ; } else if ( reservedChars == null ) { return x ; } boolean ok = true ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( reservedChars . indexOf ( c ) >= 0 ) { ok = false ; break ; } } if ( ok ) return x ; // gotta do it StringBuilder sb = new StringBuilder ( x ) ; for ( int pos = 0 ; pos < sb . length ( ) ; pos ++ ) { char c = sb . charAt ( pos ) ; if ( reservedChars . indexOf ( c ) < 0 ) { continue ; } sb . setCharAt ( pos , ' ' ) ; pos ++ ; sb . insert ( pos , c ) ; pos ++ ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "backslash unescape a string [CODESPLIT] static public String backslashUnescape ( String x ) { if ( ! x . contains ( \"\\\\\" ) ) return x ; // gotta do it StringBuilder sb = new StringBuilder ( x . length ( ) ) ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( c == ' ' ) { c = x . charAt ( ++ pos ) ; // skip backslash, get next cha } sb . append ( c ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tokenize an escaped name using . as delimiter skipping \\ . [CODESPLIT] public static List < String > tokenizeEscapedName ( String escapedName ) { List < String > result = new ArrayList <> ( ) ; int pos = 0 ; int start = 0 ; while ( true ) { pos = escapedName . indexOf ( sep , pos + 1 ) ; if ( pos <= 0 ) break ; if ( ( pos > 0 ) && escapedName . charAt ( pos - 1 ) != ' ' ) { result . add ( escapedName . substring ( start , pos ) ) ; start = pos + 1 ; } } result . add ( escapedName . substring ( start , escapedName . length ( ) ) ) ; // remaining return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find first occurence of char c in escapedName excluding escaped c . [CODESPLIT] public static int indexOf ( String escapedName , char c ) { int pos = 0 ; while ( true ) { pos = escapedName . indexOf ( c , pos + 1 ) ; if ( pos <= 0 ) return pos ; if ( ( pos > 0 ) && escapedName . charAt ( pos - 1 ) != ' ' ) return pos ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a backslash escaped name convert to a DAP escaped name [CODESPLIT] public static String backslashToDAP ( String bs ) { StringBuilder buf = new StringBuilder ( ) ; int len = bs . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = bs . charAt ( i ) ; if ( i < ( len - 1 ) && c == ' ' ) { c = bs . charAt ( ++ i ) ; } if ( _allowableInDAP . indexOf ( c ) < 0 ) { buf . append ( _URIEscape ) ; // convert the char to hex String ashex = Integer . toHexString ( ( int ) c ) ; if ( ashex . length ( ) < 2 ) buf . append ( ' ' ) ; buf . append ( ashex ) ; } else buf . append ( c ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a DAP ( attribute ) string insert backslashes before and / characters . This code also escapes control characters although the spec does not call for it ; make that code conditional . [CODESPLIT] static public String backslashEscapeDapString ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; if ( true ) { if ( c < ' ' ) { switch ( c ) { case ' ' : case ' ' : case ' ' : case ' ' : buf . append ( ( char ) c ) ; break ; default : buf . append ( String . format ( \"\\\\x%02x\" , ( c & 0xff ) ) ) ; break ; } continue ; } } if ( c == ' ' ) { buf . append ( \"\\\\\\\"\" ) ; } else if ( c == ' ' ) { buf . append ( \"\\\\\\\\\" ) ; } else buf . append ( ( char ) c ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a CDM string insert backslashes before <toescape > characters . [CODESPLIT] static public String backslashEscapeCDMString ( String s , String toescape ) { if ( toescape == null || toescape . length ( ) == 0 ) return s ; if ( s == null || s . length ( ) == 0 ) return s ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; if ( toescape . indexOf ( c ) >= 0 ) { buf . append ( ' ' ) ; } buf . append ( ( char ) c ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support Methods [CODESPLIT] protected Object readAtomic ( List < Slice > slices ) throws DapException { if ( slices == null ) throw new DapException ( \"DataCursor.read: null set of slices\" ) ; assert ( this . scheme == scheme . ATOMIC ) ; DapVariable atomvar = ( DapVariable ) getTemplate ( ) ; int rank = atomvar . getRank ( ) ; assert slices != null && ( ( rank == 0 && slices . size ( ) == 1 ) || ( slices . size ( ) == rank ) ) ; // Get VarNotes and TypeNotes Notes n = ( ( Nc4DSP ) this . dsp ) . find ( this . template ) ; Object result = null ; long count = DapUtil . sliceProduct ( slices ) ; VarNotes vn = ( VarNotes ) n ; TypeNotes ti = vn . getBaseType ( ) ; if ( getContainer ( ) == null ) { if ( rank == 0 ) { //scalar result = readAtomicScalar ( vn , ti ) ; } else { result = readAtomicVector ( vn , ti , count , slices ) ; } } else { // field of a structure instance or record long elemsize = ( ( DapType ) ti . get ( ) ) . getSize ( ) ; assert ( this . container != null ) ; long trueoffset = computeTrueOffset ( this ) ; Nc4Pointer varmem = getMemory ( ) ; Nc4Pointer mem = varmem . share ( trueoffset , count * elemsize ) ; result = getatomicdata ( ti . getType ( ) , count , elemsize , mem ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a top - level scalar atomic variable [CODESPLIT] protected Object readAtomicScalar ( VarNotes vi , TypeNotes ti ) throws DapException { DapVariable atomvar = ( DapVariable ) getTemplate ( ) ; // Get into memory Nc4prototypes nc4 = ( ( Nc4DSP ) this . dsp ) . getJNI ( ) ; int ret ; DapType basetype = ti . getType ( ) ; Object result = null ; if ( basetype . isFixedSize ( ) ) { long memsize = ( ( DapType ) ti . get ( ) ) . getSize ( ) ; Nc4Pointer mem = Nc4Pointer . allocate ( memsize ) ; readcheck ( nc4 , ret = nc4 . nc_get_var ( vi . gid , vi . id , mem . p ) ) ; setMemory ( mem ) ; result = getatomicdata ( ti . getType ( ) , 1 , mem . size , mem ) ; } else if ( basetype . isStringType ( ) ) { String [ ] s = new String [ 1 ] ; readcheck ( nc4 , ret = nc4 . nc_get_var_string ( vi . gid , vi . id , s ) ) ; result = s ; } else if ( basetype . isOpaqueType ( ) ) { Nc4Pointer mem = Nc4Pointer . allocate ( ti . getSize ( ) ) ; readcheck ( nc4 , ret = nc4 . nc_get_var ( vi . gid , vi . id , mem . p ) ) ; setMemory ( mem ) ; ByteBuffer [ ] buf = new ByteBuffer [ 1 ] ; buf [ 0 ] = mem . p . getByteBuffer ( 0 , ti . getSize ( ) ) ; result = buf ; } else throw new DapException ( \"Unexpected atomic type: \" + basetype ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Nc4Cursor Extensions [CODESPLIT] public long getOffset ( ) { DapVariable dv = ( DapVariable ) getTemplate ( ) ; Notes n = ( ( Nc4DSP ) this . dsp ) . find ( dv ) ; return n . getOffset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] protected long getElementSize ( TypeNotes ti ) { DapType type = ti . getType ( ) ; switch ( type . getTypeSort ( ) ) { case Structure : case Sequence : return ti . getSize ( ) ; case String : case URL : return Pointer . SIZE ; case Enum : return getElementSize ( ( TypeNotes ) ( ( Nc4DSP ) getDSP ( ) ) . find ( ti . enumbase , NoteSort . TYPE ) ) ; case Opaque : return ti . getSize ( ) ; default : return type . getSize ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a field ref compute the true offset with respect to it top - level containing structure / record [CODESPLIT] long computeTrueOffset ( Nc4Cursor f ) throws DapException { List < Nc4Cursor > path = getCursorPath ( f ) ; long totaloffset = 0 ; Nc4Cursor current ; // First element is presumed to be a structure ore record variable, // and that its memory covers only it's instance. // Walk intermediate nodes for ( int i = 1 ; i < ( path . size ( ) - 1 ) ; i ++ ) { current = path . get ( i ) ; DapVariable template = ( DapVariable ) current . getTemplate ( ) ; VarNotes vi = ( VarNotes ) ( ( Nc4DSP ) getDSP ( ) ) . find ( template ) ; long size = vi . getSize ( ) ; long offset = current . getOffset ( ) ; long pos = 0 ; switch ( current . getScheme ( ) ) { case SEQUENCE : case STRUCTURE : pos = current . getIndex ( ) . index ( ) ; break ; case RECORD : // readrecord will have set our memory to the start of the record pos = 0 ; break ; default : throw new DapException ( \"Illegal cursor type: \" + current . getScheme ( ) ) ; } long delta = size * pos + offset ; totaloffset += delta ; } assert path . get ( path . size ( ) - 1 ) == f ; totaloffset += f . getOffset ( ) ; return totaloffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a cursor get a list of containing cursors with the following constraints . 1 . the first element in the path is a top - level variable . 2 . the remaining elements are the enclosing compound variables 3 . the last element is the incoming cursor . [CODESPLIT] static List < Nc4Cursor > getCursorPath ( Nc4Cursor cursor ) { List < Nc4Cursor > path = new ArrayList <> ( ) ; for ( ; ; ) { if ( ! cursor . getScheme ( ) . isCompoundArray ( ) ) // suppress path . add ( 0 , cursor ) ; if ( cursor . getScheme ( ) == Scheme . SEQUENCE ) { // Stop here because the sequence has the vlen mem as its mem break ; } Nc4Cursor next = ( Nc4Cursor ) cursor . getContainer ( ) ; if ( next == null ) { assert cursor . getTemplate ( ) . isTopLevel ( ) ; break ; } assert next . getTemplate ( ) . getSort ( ) == DapSort . VARIABLE ; cursor = next ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the basetype is sequence ( = > isVlen () ) then return the type of the first field of this sequence . Otherwise return null . [CODESPLIT] public TypeNotes getVlenType ( DapVariable v ) { DapType t = v . getBaseType ( ) ; if ( t . getSort ( ) != DapSort . SEQUENCE || ( ( DapSequence ) t ) . getFields ( ) . size ( ) != 1 ) throw new IllegalArgumentException ( t . getFQN ( ) ) ; DapSequence ds = ( DapSequence ) t ; DapVariable f0 = ds . getField ( 0 ) ; DapType f0type = f0 . getBaseType ( ) ; return ( TypeNotes ) ( ( Nc4DSP ) this . dsp ) . find ( f0type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public File saveObjectToFile ( S3URI s3uri , File file ) throws IOException { Optional < File > cachedFile = objectFileCache . getIfPresent ( s3uri ) ; if ( cachedFile == null ) { logger . debug ( \"Object cache MISS: '%s'\" , s3uri ) ; // Do download below. } else { logger . debug ( \"Object cache hit: '%s'\" , s3uri ) ; if ( ! cachedFile . isPresent ( ) ) { return null ; } else if ( ! cachedFile . get ( ) . exists ( ) ) { logger . info ( String . format ( \"Found cache entry {'%s'-->'%s'}, but local file doesn't exist. \" + \"Was it deleted? Re-downloading.\" , s3uri , cachedFile . get ( ) ) ) ; objectFileCache . invalidate ( s3uri ) ; // Evict old entry. Re-download below. } else if ( ! cachedFile . get ( ) . equals ( file ) ) { // Copy content of cachedFile to file. Evict cachedFile from the cache. Files . copy ( cachedFile . get ( ) , file ) ; objectFileCache . put ( s3uri , Optional . of ( file ) ) ; return file ; } else { return file ; // File already contains the content of the object at s3uri. } } cachedFile = Optional . fromNullable ( threddsS3Client . saveObjectToFile ( s3uri , file ) ) ; objectFileCache . put ( s3uri , cachedFile ) ; return cachedFile . orNull ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for searching below <code > container< / code > in the component hierarchy and return nested components that are instances of class <code > clazz< / code > it finds . Returns an empty list if no such components exist in the container . <P > Invoking this method with a class parameter of JComponent . class will return all nested components . <P > This method invokes getDescendantsOfType ( clazz container true ) [CODESPLIT] public static < T extends JComponent > List < T > getDescendantsOfType ( Class < T > clazz , Container container ) { return getDescendantsOfType ( clazz , container , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for searching below <code > container< / code > in the component hierarchy and return nested components that are instances of class <code > clazz< / code > it finds . Returns an empty list if no such components exist in the container . <P > Invoking this method with a class parameter of JComponent . class will return all nested components . [CODESPLIT] public static < T extends JComponent > List < T > getDescendantsOfType ( Class < T > clazz , Container container , boolean nested ) { List < T > tList = new ArrayList < T > ( ) ; for ( Component component : container . getComponents ( ) ) { if ( clazz . isAssignableFrom ( component . getClass ( ) ) ) { tList . add ( clazz . cast ( component ) ) ; } if ( nested || ! clazz . isAssignableFrom ( component . getClass ( ) ) ) { tList . addAll ( SwingUtils . < T > getDescendantsOfType ( clazz , ( Container ) component , nested ) ) ; } } return tList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method that searches below <code > container< / code > in the component hierarchy and returns the first found component that is an instance of class <code > clazz< / code > and has the bound property value . Returns { @code null } if such component cannot be found . [CODESPLIT] public static < T extends JComponent > T getDescendantOfType ( Class < T > clazz , Container container , String property , Object value , boolean nested ) throws IllegalArgumentException { List < T > list = getDescendantsOfType ( clazz , container , nested ) ; return getComponentFromList ( clazz , list , property , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method that searches below <code > container< / code > in the component hierarchy in a depth first manner and returns the first found component of class <code > clazz< / code > having the bound property value . <P > Returns { @code null } if such component cannot be found . <P > This method invokes getDescendantOfClass ( clazz container property value true ) [CODESPLIT] public static < T extends JComponent > T getDescendantOfClass ( Class < T > clazz , Container container , String property , Object value ) throws IllegalArgumentException { return getDescendantOfClass ( clazz , container , property , value , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method that searches below <code > container< / code > in the component hierarchy in a depth first manner and returns the first found component of class <code > clazz< / code > having the bound property value . <P > Returns { @code null } if such component cannot be found . [CODESPLIT] public static < T extends JComponent > T getDescendantOfClass ( Class < T > clazz , Container container , String property , Object value , boolean nested ) throws IllegalArgumentException { List < T > list = getDescendantsOfClass ( clazz , container , nested ) ; return getComponentFromList ( clazz , list , property , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for mapping a container in the hierarchy to its contained components . The keys are the containers and the values are lists of contained components . <P > Implementation note : The returned value is a HashMap and the values are of type ArrayList . This is subject to change so callers should code against the interfaces Map and List . [CODESPLIT] public static Map < JComponent , List < JComponent > > getComponentMap ( JComponent container , boolean nested ) { HashMap < JComponent , List < JComponent > > retVal = new HashMap < JComponent , List < JComponent > > ( ) ; for ( JComponent component : getDescendantsOfType ( JComponent . class , container , false ) ) { if ( ! retVal . containsKey ( container ) ) { retVal . put ( container , new ArrayList < JComponent > ( ) ) ; } retVal . get ( container ) . add ( component ) ; if ( nested ) { retVal . putAll ( getComponentMap ( component , nested ) ) ; } } return retVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for retrieving a subset of the UIDefaults pertaining to a particular class . [CODESPLIT] public static UIDefaults getUIDefaultsOfClass ( Class clazz ) { String name = clazz . getName ( ) ; name = name . substring ( name . lastIndexOf ( \".\" ) + 2 ) ; return getUIDefaultsOfClass ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for retrieving a subset of the UIDefaults pertaining to a particular class . [CODESPLIT] public static UIDefaults getUIDefaultsOfClass ( String className ) { UIDefaults retVal = new UIDefaults ( ) ; UIDefaults defaults = UIManager . getLookAndFeelDefaults ( ) ; List < ? > listKeys = Collections . list ( defaults . keys ( ) ) ; for ( Object key : listKeys ) { if ( key instanceof String && ( ( String ) key ) . startsWith ( className ) ) { String stringKey = ( String ) key ; String property = stringKey ; if ( stringKey . contains ( \".\" ) ) { property = stringKey . substring ( stringKey . indexOf ( \".\" ) + 1 ) ; } retVal . put ( property , defaults . get ( key ) ) ; } } return retVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for retrieving the UIDefault for a single property of a particular class . [CODESPLIT] public static Object getUIDefaultOfClass ( Class clazz , String property ) { Object retVal = null ; UIDefaults defaults = getUIDefaultsOfClass ( clazz ) ; List < Object > listKeys = Collections . list ( defaults . keys ( ) ) ; for ( Object key : listKeys ) { if ( key . equals ( property ) ) { return defaults . get ( key ) ; } if ( key . toString ( ) . equalsIgnoreCase ( property ) ) { retVal = defaults . get ( key ) ; } } return retVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for obtaining most non - null human readable properties of a JComponent . Array properties are not included . <P > Implementation note : The returned value is a HashMap . This is subject to change so callers should code against the interface Map . [CODESPLIT] public static Map < Object , Object > getProperties ( JComponent component ) { Map < Object , Object > retVal = new HashMap < Object , Object > ( ) ; Class < ? > clazz = component . getClass ( ) ; Method [ ] methods = clazz . getMethods ( ) ; Object value = null ; for ( Method method : methods ) { if ( method . getName ( ) . matches ( \"^(is|get).*\" ) && method . getParameterTypes ( ) . length == 0 ) { try { Class returnType = method . getReturnType ( ) ; if ( returnType != void . class && ! returnType . getName ( ) . startsWith ( \"[\" ) && ! setExclude . contains ( method . getName ( ) ) ) { String key = method . getName ( ) ; value = method . invoke ( component ) ; if ( value != null && ! ( value instanceof Component ) ) { retVal . put ( key , value ) ; } } // ignore exceptions that arise if the property could not be accessed } catch ( IllegalAccessException ex ) { } catch ( IllegalArgumentException ex ) { } catch ( InvocationTargetException ex ) { } } } return retVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method to obtain the Swing class from which this component was directly or indirectly derived . [CODESPLIT] public static < T extends JComponent > Class getJClass ( T component ) { Class < ? > clazz = component . getClass ( ) ; while ( ! clazz . getName ( ) . matches ( \"javax.swing.J[^.]*$\" ) ) { clazz = clazz . getSuperclass ( ) ; } return clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The goal here is to process the serialized databuffer and locate top - level variable positions in the serialized databuffer . Access to non - top - level variables is accomplished on the fly . [CODESPLIT] public void compile ( ) throws DapException { assert ( this . dataset != null && this . databuffer != null ) ; // iterate over the variables represented in the databuffer for ( DapVariable vv : this . dataset . getTopVariables ( ) ) { D4Cursor data = compileVar ( vv , null ) ; this . dsp . addVariableData ( vv , data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile a structure array . [CODESPLIT] protected D4Cursor compileStructureArray ( DapVariable var , D4Cursor container ) throws DapException { DapStructure dapstruct = ( DapStructure ) var . getBaseType ( ) ; D4Cursor structarray = new D4Cursor ( Scheme . STRUCTARRAY , this . dsp , var , container ) . setOffset ( getPos ( this . databuffer ) ) ; List < DapDimension > dimset = var . getDimensions ( ) ; long dimproduct = DapUtil . dimProduct ( dimset ) ; D4Cursor [ ] instances = new D4Cursor [ ( int ) dimproduct ] ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) , dimset ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; D4Cursor instance = compileStructure ( var , dapstruct , structarray ) ; instance . setIndex ( index ) ; instances [ ( int ) index . index ( ) ] = instance ; } structarray . setElements ( instances ) ; return structarray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile a structure instance . [CODESPLIT] protected D4Cursor compileStructure ( DapVariable var , DapStructure dapstruct , D4Cursor container ) throws DapException { int pos = getPos ( this . databuffer ) ; D4Cursor d4ds = new D4Cursor ( Scheme . STRUCTURE , ( D4DSP ) this . dsp , var , container ) . setOffset ( pos ) ; List < DapVariable > dfields = dapstruct . getFields ( ) ; for ( int m = 0 ; m < dfields . size ( ) ; m ++ ) { DapVariable dfield = dfields . get ( m ) ; D4Cursor dvfield = compileVar ( dfield , d4ds ) ; d4ds . addField ( m , dvfield ) ; assert dfield . getParent ( ) != null ; } return d4ds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile a sequence array . [CODESPLIT] protected D4Cursor compileSequenceArray ( DapVariable var , D4Cursor container ) throws DapException { DapSequence dapseq = ( DapSequence ) var . getBaseType ( ) ; D4Cursor seqarray = new D4Cursor ( Scheme . SEQARRAY , this . dsp , var , container ) . setOffset ( getPos ( this . databuffer ) ) ; List < DapDimension > dimset = var . getDimensions ( ) ; long dimproduct = DapUtil . dimProduct ( dimset ) ; D4Cursor [ ] instances = new D4Cursor [ ( int ) dimproduct ] ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) , dimset ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; D4Cursor instance = compileSequence ( var , dapseq , seqarray ) ; instance . setIndex ( index ) ; instances [ ( int ) index . index ( ) ] = instance ; } seqarray . setElements ( instances ) ; return seqarray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile a sequence as a set of records . [CODESPLIT] public D4Cursor compileSequence ( DapVariable var , DapSequence dapseq , D4Cursor container ) throws DapException { int pos = getPos ( this . databuffer ) ; D4Cursor seq = new D4Cursor ( Scheme . SEQUENCE , this . dsp , var , container ) . setOffset ( pos ) ; List < DapVariable > dfields = dapseq . getFields ( ) ; // Get the count of the number of records long nrecs = getCount ( this . databuffer ) ; for ( int r = 0 ; r < nrecs ; r ++ ) { pos = getPos ( this . databuffer ) ; D4Cursor rec = ( D4Cursor ) new D4Cursor ( D4Cursor . Scheme . RECORD , this . dsp , var , container ) . setOffset ( pos ) . setRecordIndex ( r ) ; for ( int m = 0 ; m < dfields . size ( ) ; m ++ ) { DapVariable dfield = dfields . get ( m ) ; D4Cursor dvfield = compileVar ( dfield , rec ) ; rec . addField ( m , dvfield ) ; assert dfield . getParent ( ) != null ; } seq . addRecord ( rec ) ; } return seq ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] protected int extractChecksum ( ByteBuffer data ) throws DapException { assert ChecksumMode . DAP . enabled ( this . checksummode ) ; if ( data . remaining ( ) < DapUtil . CHECKSUMSIZE ) throw new DapException ( \"Short serialization: missing checksum\" ) ; return data . getInt ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads <code > n< / code > little - endian doubles from a random access file . <p / > <p > This method is provided for speed when accessing a number of consecutive values of the same type . [CODESPLIT] public final void readLEDoubles ( double [ ] d , int n ) throws IOException { int nLeft = n ; int dCount = 0 ; int nToRead = kLongs ; while ( nLeft > 0 ) { if ( nToRead > nLeft ) nToRead = nLeft ; readLELongs ( longWorkSpace , nToRead ) ; for ( int i = 0 ; i < nToRead ; i ++ ) { d [ dCount ++ ] = Double . longBitsToDouble ( longWorkSpace [ i ] ) ; } nLeft -= nToRead ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read a long in little endian format [CODESPLIT] public long readLELong ( ) throws IOException { readFully ( w , 0 , 8 ) ; return ( long ) ( w [ 7 ] & 0xff ) << 56 | ( long ) ( w [ 6 ] & 0xff ) << 48 | ( long ) ( w [ 5 ] & 0xff ) << 40 | ( long ) ( w [ 4 ] & 0xff ) << 32 | ( long ) ( w [ 3 ] & 0xff ) << 24 | ( long ) ( w [ 2 ] & 0xff ) << 16 | ( long ) ( w [ 1 ] & 0xff ) << 8 | ( long ) ( w [ 0 ] & 0xff ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads <code > n< / code > little - endian longs from a random access file . <p / > <p > This method is provided for speed when accessing a number of consecutive values of the same type . [CODESPLIT] public final void readLELongs ( long lbuf [ ] , int n ) throws IOException { int nLeft = n ; int lCount = 0 ; int nToRead = kLongs ; while ( nLeft > 0 ) { if ( nToRead > nLeft ) nToRead = nLeft ; readFully ( byteWorkSpace , 0 , 8 * nToRead ) ; int j = 0 ; for ( int i = 0 ; i < nToRead ; i ++ ) { lbuf [ lCount ++ ] = ( long ) ( byteWorkSpace [ j ] & 0xff ) | ( long ) ( byteWorkSpace [ j + 1 ] & 0xff ) << 8 | ( long ) ( byteWorkSpace [ j + 2 ] & 0xff ) << 16 | ( long ) ( byteWorkSpace [ j + 3 ] & 0xff ) << 24 | ( long ) ( byteWorkSpace [ j + 4 ] & 0xff ) << 32 | ( long ) ( byteWorkSpace [ j + 5 ] & 0xff ) << 40 | ( long ) ( byteWorkSpace [ j + 6 ] & 0xff ) << 48 | ( long ) ( byteWorkSpace [ j + 7 ] & 0xff ) << 56 ; j += 8 ; } nLeft -= nToRead ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * protected Variable findVariableWithStandardNameAndNotDimension ( NetcdfDataset ds String standard_name Dimension outer Formatter errlog ) { for ( Variable v : ds . getVariables () ) { String stdName = ds . findAttValueIgnoreCase ( v CF . STANDARD_NAME null ) ; if (( stdName ! = null ) && stdName . equals ( standard_name ) && v . getRank () > 0 && !v . getDimension ( 0 ) . equals ( outer )) return v ; } return null ; } [CODESPLIT] protected String matchAxisTypeAndDimension ( NetcdfDataset ds , AxisType type , final Dimension outer , final Dimension inner ) { Variable var = CoordSysEvaluator . findCoordByType ( ds , type , new CoordSysEvaluator . Predicate ( ) { @ Override public boolean match ( CoordinateAxis axis ) { return ( ( axis . getRank ( ) == 2 ) && outer . equals ( axis . getDimension ( 0 ) ) && inner . equals ( axis . getDimension ( 1 ) ) ) ; } } ) ; if ( var == null ) return null ; return var . getShortName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read in the index index raf already open ; return null on failure [CODESPLIT] @ Nullable static Grib1Collection readFromIndex ( String name , RandomAccessFile raf , FeatureCollectionConfig config , org . slf4j . Logger logger ) { Grib1CollectionBuilderFromIndex builder = new Grib1CollectionBuilderFromIndex ( name , config , logger ) ; if ( ! builder . readIndex ( raf ) ) return null ; if ( builder . gc . getFiles ( ) . size ( ) == 0 ) { logger . warn ( \"Grib1CollectionBuilderFromIndex {}: has no files, force recreate \" , builder . gc . getName ( ) ) ; return null ; } return new Grib1Collection ( builder . gc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add listener : action event sent if apply button is pressed [CODESPLIT] public void addActionListener ( ActionListener l ) { listenerList . add ( java . awt . event . ActionListener . class , l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove listener [CODESPLIT] public void removeActionListener ( ActionListener l ) { listenerList . remove ( java . awt . event . ActionListener . class , l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call Field . accept () on all Fields . This puts any edits into the Store and fires PropertyChangeEvents if any values change and sends an ActionEvent to any listeners . [CODESPLIT] public boolean accept ( ) { StringBuffer buff = new StringBuffer ( \"Invalid field value \" ) ; boolean ok = true ; for ( Object o : flds . values ( ) ) ok &= ( ( Field ) o ) . accept ( buff ) ; if ( ! ok ) { try { JOptionPane . showMessageDialog ( PrefPanel . findActiveFrame ( ) , buff . toString ( ) ) ; } catch ( HeadlessException e ) { } return false ; } /* store the text widths if they exist\n    if (storeData != null) {\n      Preferences substore = prefs.node(\"sizes\");\n      iter = flds.values().iterator();\n      while (iter.hasNext()) {\n        Field fld = (Field) iter.next();\n        JComponent comp = fld.getEditComponent();\n        substore.putInt(fld.getName(), (int) comp.getPreferredSize().getWidth());\n      }\n    } */ fireEvent ( new ActionEvent ( this , 0 , \"Accept\" ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the field with the specified name . [CODESPLIT] public Field getField ( String name ) { Field fld = flds . get ( name ) ; if ( fld == null ) return null ; return ( fld instanceof FieldResizable ) ? ( ( FieldResizable ) fld ) . getDelegate ( ) : fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get current value of the named field [CODESPLIT] public Object getFieldValue ( String name ) { Field fld = getField ( name ) ; if ( fld == null ) throw new IllegalArgumentException ( \"no field named \" + name ) ; return fld . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the current value of the named field [CODESPLIT] public void setFieldValue ( String name , Object value ) { Field fld = getField ( name ) ; if ( fld == null ) throw new IllegalArgumentException ( \"no field named \" + name ) ; fld . setValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a field created by the user . [CODESPLIT] public Field addField ( Field fld ) { addField ( fld , cursorCol , cursorRow , null ) ; cursorRow ++ ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a boolean field as a checkbox . [CODESPLIT] public Field . CheckBox addCheckBoxField ( String fldName , String label , boolean defValue ) { Field . CheckBox fld = new Field . CheckBox ( fldName , label , defValue , storeData ) ; addField ( fld ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a field that edits a date [CODESPLIT] public Field . Date addDateField ( String fldName , String label , Date defValue ) { Field . Date fld = new Field . Date ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a field that edits a double [CODESPLIT] public Field . Double addDoubleField ( String fldName , String label , double defValue ) { Field . Double fld = new Field . Double ( fldName , label , defValue , - 1 , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a field that edits an integer [CODESPLIT] public Field . Int addIntField ( String fldName , String label , int defValue ) { Field . Int fld = new Field . Int ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a password text field . [CODESPLIT] public Field . Password addPasswordField ( String fldName , String label , String defValue ) { Field . Password fld = new Field . Password ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a text field . [CODESPLIT] public Field . Text addTextField ( String fldName , String label , String defValue ) { Field . Text fld = new Field . Text ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a text combobox field . [CODESPLIT] public Field . TextCombo addTextComboField ( String fldName , String label , java . util . Collection defValues , int nKeep , boolean editable ) { Field . TextCombo fld = new Field . TextCombo ( fldName , label , defValues , nKeep , storeData ) ; addField ( fld ) ; fld . setEditable ( editable ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a TextArea field . [CODESPLIT] public Field . TextArea addTextAreaField ( String fldName , String label , String def , int nrows ) { Field . TextArea fld = new Field . TextArea ( fldName , label , def , nrows , storeData ) ; addField ( fld ) ; return fld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a heading at the specified row . this spans all columns [CODESPLIT] public void addHeading ( String heading , int row ) { layoutComponents . add ( new LayoutComponent ( heading , 0 , row , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Component . [CODESPLIT] public void addComponent ( Component comp , int col , int row , String constraint ) { layoutComponents . add ( new LayoutComponent ( comp , col , row , constraint ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a seperator after the last field added . [CODESPLIT] public void addEmptyRow ( int row , int size ) { layoutComponents . add ( new LayoutComponent ( null , size , row , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call when finished adding components to the PrefPanel . [CODESPLIT] public void finish ( boolean addButtons , String where ) { if ( finished ) throw new IllegalStateException ( \"PrefPanel \" + name + \": already called finish()\" ) ; StringBuilder sbuff = new StringBuilder ( ) ; // column layout, first sort by col Collections . sort ( layoutComponents , new Comparator < LayoutComponent > ( ) { public int compare ( LayoutComponent o1 , LayoutComponent o2 ) { return o1 . col - o2 . col ; } public boolean equals ( Object o1 ) { return o1 == this ; } } ) ; // now create column layout spec and x cell constraint sbuff . setLength ( 0 ) ; int currCol = - 1 ; Iterator iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; if ( lc . col > currCol ) { if ( currCol >= 0 ) sbuff . append ( \", 5dlu, \" ) ; else sbuff . append ( \"3dlu, \" ) ; sbuff . append ( \"right:default, 3dlu, default:grow\" ) ; currCol += 2 ; } lc . ccLabel . gridX = 2 * lc . col + 2 ; lc . cc . gridX = 2 * lc . col + 4 ; } String colSpec = sbuff . toString ( ) ; if ( debugLayout ) System . out . println ( \" column layout = \" + colSpec ) ; int ncols = 2 * currCol ; // row layout, first sort by row Collections . sort ( layoutComponents , new Comparator < LayoutComponent > ( ) { public int compare ( LayoutComponent o1 , LayoutComponent o2 ) { return o1 . row - o2 . row ; } public boolean equals ( Object o1 ) { return o1 == this ; } } ) ; // now adjust for any headings, put into y cell constraint int incr = 0 ; iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; if ( ( lc . comp instanceof String ) && ( lc . row > 0 ) ) // its a header, not in first position incr ++ ; // leave space by adding a row lc . cc . gridY = lc . row + incr + 1 ; // adjust downward lc . ccLabel . gridY = lc . cc . gridY ; if ( debugLayout ) System . out . println ( lc + \" constraint = \" + lc . cc ) ; } // now create row layout spec sbuff . setLength ( 0 ) ; int currRow = - 1 ; iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; while ( lc . row > currRow ) { if ( ( lc . comp instanceof String ) && ( lc . row > 0 ) ) { sbuff . append ( \", 5dlu, default\" ) ; } else if ( ( lc . comp == null ) ) { sbuff . append ( \", \" ) . append ( lc . col ) . append ( \"dlu\" ) ; } else { if ( currRow >= 0 ) sbuff . append ( \", \" ) ; sbuff . append ( \"default\" ) ; } currRow ++ ; } } String rowSpec = sbuff . toString ( ) ; if ( debugLayout ) System . out . println ( \" row layout = \" + rowSpec ) ; // the jgoodies form layout FormLayout layout = new FormLayout ( colSpec , rowSpec ) ; PanelBuilder builder = new PanelBuilder ( layout ) ; builder . setDefaultDialogBorder ( ) ; CellConstraints cc = new CellConstraints ( ) ; // now add each component with correct constraint iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; if ( lc . comp instanceof Field ) { Field fld = ( Field ) lc . comp ; builder . addLabel ( fld . getLabel ( ) + \":\" , lc . ccLabel ) ; Component comp = fld . getEditComponent ( ) ; if ( lc . comp instanceof Field . TextArea ) comp = new JScrollPane ( comp ) ; builder . add ( comp , lc . cc ) ; } else if ( lc . comp instanceof String ) { String header = ( String ) lc . comp ; builder . addSeparator ( header , cc . xyw ( 1 , lc . cc . gridY , ncols ) ) ; } else if ( lc . comp instanceof Component ) { builder . add ( ( Component ) lc . comp , lc . cc ) ; } } mainPanel = builder . getPanel ( ) ; // button panel JPanel buttPanel = new JPanel ( ) ; JButton acceptButton = new JButton ( \"Apply\" ) ; buttPanel . add ( acceptButton , null ) ; for ( JComponent auxButton : auxButtons ) buttPanel . ( auxButton , null ) ; // button listeners acceptButton . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { accept ( ) ; } } ) ; setLayout ( new BorderLayout ( ) ) ; add ( mainPanel , BorderLayout . CENTER ) ; if ( addButtons ) { if ( where . equals ( BorderLayout . SOUTH ) ) { JPanel south = new JPanel ( ) ; south . setLayout ( new BoxLayout ( south , BoxLayout . Y_AXIS ) ) ; south . add ( new JSeparator ( SwingConstants . HORIZONTAL ) ) ; south . add ( buttPanel ) ; add ( south , BorderLayout . SOUTH ) ; } else add ( buttPanel , where ) ; } finished = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "thanks to Heinz M . Kabutz [CODESPLIT] static public Frame findActiveFrame ( ) { Frame [ ] frames = JFrame . getFrames ( ) ; for ( Frame frame : frames ) { if ( frame . isVisible ( ) ) return frame ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the value ( parameters are ignored ) . [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws IOException { if ( localVal == null ) // read first time setData ( ncVar . read ( ) ) ; setValue ( localVal ) ; setRead ( true ) ; return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cell spacing . An exception is thrown if the cell spacing is not constant . [CODESPLIT] public float getCellSpacing ( ) throws DescriptorException { float [ ] cellRanges = myCELV . getCellRanges ( ) ; // // use the first cell spacing as our expected value // float cellSpacing = cellRanges [ 1 ] - cellRanges [ 0 ] ; // // Check the rest of the cells against the expected value, allowing // 1% fudge // for ( int i = 2 ; i < cellRanges . length ; i ++ ) { float space = cellRanges [ i ] - cellRanges [ i - 1 ] ; if ( ! Misc . nearlyEquals ( space , cellSpacing ) && ( Math . abs ( space / cellSpacing - 1.0 ) > 0.01 ) ) { throw new DescriptorException ( \"variable cell spacing\" ) ; } } return cellSpacing ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the array of Factor - s constituting this dimension . [CODESPLIT] public final Factor [ ] getFactors ( ) { final Factor [ ] factors = new Factor [ _factors . length ] ; System . arraycopy ( _factors , 0 , factors , 0 , factors . length ) ; return factors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiplies this dimension by another dimension . [CODESPLIT] protected Factor [ ] mult ( final Dimension that ) { // relys on _factors always sorted final Factor [ ] factors1 = _factors ; final Factor [ ] factors2 = that . _factors ; int i1 = 0 ; int i2 = 0 ; int k = 0 ; Factor [ ] newFactors = new Factor [ factors1 . length + factors2 . length ] ; for ( ; ; ) { if ( i1 == factors1 . length ) { final int n = factors2 . length - i2 ; System . arraycopy ( factors2 , i2 , newFactors , k , n ) ; k += n ; break ; } if ( i2 == factors2 . length ) { final int n = factors1 . length - i1 ; System . arraycopy ( factors1 , i1 , newFactors , k , n ) ; k += n ; break ; } final Factor f1 = factors1 [ i1 ] ; final Factor f2 = factors2 [ i2 ] ; final int comp = f1 . getID ( ) . compareTo ( f2 . getID ( ) ) ; if ( comp < 0 ) { newFactors [ k ++ ] = f1 ; i1 ++ ; } else if ( comp == 0 ) { final int exponent = f1 . getExponent ( ) + f2 . getExponent ( ) ; if ( exponent != 0 ) { newFactors [ k ++ ] = new Factor ( f1 , exponent ) ; } i1 ++ ; i2 ++ ; } else { newFactors [ k ++ ] = f2 ; i2 ++ ; } } if ( k < newFactors . length ) { final Factor [ ] tmp = new Factor [ k ] ; System . arraycopy ( newFactors , 0 , tmp , 0 , k ) ; newFactors = tmp ; } return newFactors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Raises this dimension to a power . [CODESPLIT] protected Factor [ ] pow ( final int power ) { Factor [ ] factors ; if ( power == 0 ) { factors = new Factor [ 0 ] ; } else { factors = getFactors ( ) ; if ( power != 1 ) { for ( int i = factors . length ; -- i >= 0 ; ) { factors [ i ] = factors [ i ] . pow ( power ) ; } } } return factors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if this Dimension is the reciprocal of another dimension . [CODESPLIT] public final boolean isReciprocalOf ( final Dimension that ) { final Factor [ ] theseFactors = _factors ; final Factor [ ] thoseFactors = that . _factors ; boolean isReciprocalOf ; if ( theseFactors . length != thoseFactors . length ) { isReciprocalOf = false ; } else { int i ; for ( i = theseFactors . length ; -- i >= 0 ; ) { if ( ! theseFactors [ i ] . isReciprocalOf ( thoseFactors [ i ] ) ) { break ; } } isReciprocalOf = i < 0 ; } return isReciprocalOf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if this dimension is dimensionless . A dimension is dimensionless if it has no Factor - s or if all Factor - s are themselves dimensionless . [CODESPLIT] public final boolean isDimensionless ( ) { for ( int i = _factors . length ; -- i >= 0 ; ) { if ( ! _factors [ i ] . isDimensionless ( ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember [CODESPLIT] public static OMObservationPropertyType initObservationMember ( OMObservationPropertyType observationMember , StationTimeSeriesFeature stationFeat , VariableSimpleIF dataVar ) throws IOException { // om:OM_Observation NcOMObservationType . initOmObservation ( observationMember . addNewOMObservation ( ) , stationFeat , dataVar ) ; return observationMember ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Notify all listeners that have registered interest for notification on this event type . The event instance is lazily created using the parameters passed into the fire method . [CODESPLIT] protected void fireTreeNodesChanged ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { // Guaranteed to return a non-null array\r Object [ ] listeners = listenerList . getListenerList ( ) ; TreeModelEvent e = null ; // Process the listeners last to first, notifying\r // those that are interested in this event\r for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 ) { if ( listeners [ i ] == TreeModelListener . class ) { // Lazily create the event:\r if ( e == null ) e = new TreeModelEvent ( source , path , childIndices , children ) ; ( ( TreeModelListener ) listeners [ i + 1 ] ) . treeNodesChanged ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Notify all listeners that have registered interest for notification on this event type . The event instance is lazily created using the parameters passed into the fire method . [CODESPLIT] protected void fireTreeNodesInserted ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { // Guaranteed to return a non-null array\r Object [ ] listeners = listenerList . getListenerList ( ) ; TreeModelEvent e = null ; // Process the listeners last to first, notifying\r // those that are interested in this event\r for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 ) { if ( listeners [ i ] == TreeModelListener . class ) { // Lazily create the event:\r if ( e == null ) e = new TreeModelEvent ( source , path , childIndices , children ) ; ( ( TreeModelListener ) listeners [ i + 1 ] ) . treeNodesInserted ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Notify all listeners that have registered interest for notification on this event type . The event instance is lazily created using the parameters passed into the fire method . [CODESPLIT] protected void fireTreeNodesRemoved ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { // Guaranteed to return a non-null array\r Object [ ] listeners = listenerList . getListenerList ( ) ; TreeModelEvent e = null ; // Process the listeners last to first, notifying\r // those that are interested in this event\r for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 ) { if ( listeners [ i ] == TreeModelListener . class ) { // Lazily create the event:\r if ( e == null ) e = new TreeModelEvent ( source , path , childIndices , children ) ; ( ( TreeModelListener ) listeners [ i + 1 ] ) . treeNodesRemoved ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persist info ( ncoords coordValues ) from joinExisting since that can be expensive to recreate . [CODESPLIT] public void persistWrite ( ) throws IOException { if ( diskCache2 == null ) return ; String cacheName = getCacheName ( ) ; if ( cacheName == null ) return ; if ( cacheName . startsWith ( \"file:\" ) ) // LOOK\r cacheName = cacheName . substring ( 5 ) ; File cacheFile = diskCache2 . getCacheFile ( cacheName ) ; if ( cacheFile == null ) throw new IllegalStateException ( ) ; // only write out if something changed after the cache file was last written, or if the file has been deleted\r if ( ! cacheDirty && cacheFile . exists ( ) ) return ; FileChannel channel = null ; try { File dir = cacheFile . getParentFile ( ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) logger . error ( \"Cant make cache directory= \" + cacheFile ) ; } // Get a file channel for the file\r FileOutputStream fos = new FileOutputStream ( cacheFile ) ; channel = fos . getChannel ( ) ; // Try acquiring the lock without blocking. This method returns\r // null or throws an exception if the file is already locked.\r FileLock lock ; try { lock = channel . tryLock ( ) ; } catch ( OverlappingFileLockException e ) { // File is already locked in this thread or virtual machine\r return ; // give up\r } if ( lock == null ) return ; PrintWriter out = new PrintWriter ( new OutputStreamWriter ( fos , CDM . utf8Charset ) ) ; out . print ( \"<?xml version='1.0' encoding='UTF-8'?>\\n\" ) ; out . print ( \"<aggregation xmlns='http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2' version='3' \" ) ; out . print ( \"type='\" + type + \"' \" ) ; if ( dimName != null ) out . print ( \"dimName='\" + dimName + \"' \" ) ; if ( datasetManager . getRecheck ( ) != null ) out . print ( \"recheckEvery='\" + datasetManager . getRecheck ( ) + \"' \" ) ; out . print ( \">\\n\" ) ; List < Dataset > nestedDatasets = getDatasets ( ) ; for ( Dataset dataset : nestedDatasets ) { DatasetOuterDimension dod = ( DatasetOuterDimension ) dataset ; if ( dod . getId ( ) == null ) logger . warn ( \"id is null\" ) ; out . print ( \"  <netcdf id='\" + dod . getId ( ) + \"' \" ) ; out . print ( \"ncoords='\" + dod . getNcoords ( null ) + \"' >\\n\" ) ; for ( CacheVar pv : cacheList ) { Array data = pv . getData ( dod . getId ( ) ) ; if ( data != null ) { out . print ( \"    <cache varName='\" + pv . varName + \"' >\" ) ; while ( data . hasNext ( ) ) out . printf ( \"%s \" , data . next ( ) ) ; out . print ( \"</cache>\\n\" ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \" wrote array = \" + pv . varName + \" nelems= \" + data . getSize ( ) + \" for \" + dataset . getLocation ( ) ) ; } } out . print ( \"  </netcdf>\\n\" ) ; } out . print ( \"</aggregation>\\n\" ) ; out . close ( ) ; // this also closes the  channel and releases the lock\r long time = datasetManager . getLastScanned ( ) ; if ( time == 0 ) time = System . currentTimeMillis ( ) ; // no scans (eg all static) will have a 0\r if ( ! cacheFile . setLastModified ( time ) ) logger . warn ( \"FAIL to set lastModified on {}\" , cacheFile . getPath ( ) ) ; cacheDirty = false ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \"Aggregation persisted = \" + cacheFile . getPath ( ) + \" lastModified= \" + new Date ( datasetManager . getLastScanned ( ) ) ) ; } finally { if ( channel != null ) channel . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read info from the persistent XML file if it exists [CODESPLIT] protected void persistRead ( ) { if ( diskCache2 == null ) return ; String cacheName = getCacheName ( ) ; if ( cacheName == null ) return ; if ( cacheName . startsWith ( \"file:\" ) ) // LOOK\r cacheName = cacheName . substring ( 5 ) ; File cacheFile = diskCache2 . getCacheFile ( cacheName ) ; if ( cacheFile == null ) throw new IllegalStateException ( ) ; if ( ! cacheFile . exists ( ) ) return ; long lastWritten = cacheFile . lastModified ( ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \" Try to Read cache {} \" + cacheFile . getPath ( ) ) ; Element aggElem ; try { aggElem = ucar . nc2 . util . xml . Parse . readRootElement ( \"file:\" + cacheFile . getPath ( ) ) ; } catch ( IOException e ) { if ( debugCache ) System . out . println ( \" No cache for \" + cacheName + \" - \" + e . getMessage ( ) ) ; return ; } String version = aggElem . getAttributeValue ( \"version\" ) ; if ( ( version == null ) || ! version . equals ( \"3\" ) ) return ; // dont read old cache files, recreate\r // use a map to find datasets to avoid O(n**2) searching\r Map < String , Dataset > map = new HashMap < String , Dataset > ( ) ; for ( Dataset ds : getDatasets ( ) ) { map . put ( ds . getId ( ) , ds ) ; } List < Element > ncList = aggElem . getChildren ( \"netcdf\" , Catalog . ncmlNS ) ; for ( Element netcdfElemNested : ncList ) { String id = netcdfElemNested . getAttributeValue ( \"id\" ) ; DatasetOuterDimension dod = ( DatasetOuterDimension ) map . get ( id ) ; if ( null == dod ) { // this should mean that the dataset has been deleted. so not a problem\r if ( logger . isDebugEnabled ( ) ) logger . debug ( \" have cache but no dataset= {}\" , id ) ; continue ; } if ( logger . isDebugEnabled ( ) ) logger . debug ( \" use cache for dataset= {}\" , id ) ; MFile mfile = dod . getMFile ( ) ; if ( mfile != null && mfile . getLastModified ( ) > lastWritten ) { // skip datasets that have changed\r if ( logger . isDebugEnabled ( ) ) logger . debug ( \" dataset was changed= {}\" , mfile ) ; continue ; } if ( dod . ncoord == 0 ) { String ncoordsS = netcdfElemNested . getAttributeValue ( \"ncoords\" ) ; try { dod . ncoord = Integer . parseInt ( ncoordsS ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \" Read the cache; ncoords = {}\" , dod . ncoord ) ; } catch ( NumberFormatException e ) { logger . error ( \"bad ncoord attribute on dataset=\" + id ) ; } } // if (dod.coordValue != null) continue; // allow ncml to override\r List < Element > cacheElemList = netcdfElemNested . getChildren ( \"cache\" , Catalog . ncmlNS ) ; for ( Element cacheElemNested : cacheElemList ) { String varName = cacheElemNested . getAttributeValue ( \"varName\" ) ; CacheVar pv = findCacheVariable ( varName ) ; if ( pv != null ) { String sdata = cacheElemNested . getText ( ) ; if ( sdata . length ( ) == 0 ) continue ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \" read data for var = \" + varName + \" size= \" + sdata . length ( ) ) ; //long start = System.nanoTime();\r String [ ] vals = sdata . split ( \" \" ) ; //double took = .001 * .001 * .001 * (System.nanoTime() - start);\r //if (debugPersist) System.out.println(\"  split took = \" + took + \" sec; \");\r try { //start = System.nanoTime();\r Array data = Array . makeArray ( pv . dtype , vals ) ; //took = .001 * .001 * .001 * (System.nanoTime() - start);\r //if (debugPersist) System.out.println(\"  makeArray took = \" + took + \" sec nelems= \"+data.getSize());\r pv . putData ( id , data ) ; countCacheUse ++ ; } catch ( Exception e ) { logger . warn ( \"Error reading cached data \" , e ) ; } } else { logger . warn ( \"not a cache var=\" + varName ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "has the name getCacheName () [CODESPLIT] private String getCacheName ( ) { String cacheName = ncDataset . getLocation ( ) ; if ( cacheName == null ) cacheName = ncDataset . getCacheName ( ) ; return cacheName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a key from ( center subcenter version ) that provides correct sort order . [CODESPLIT] static int makeKey ( int center , int subcenter , int version ) { if ( center < 0 ) center = 255 ; if ( subcenter < 0 ) subcenter = 255 ; if ( version < 0 ) version = 255 ; return center * 1000 * 1000 + subcenter * 1000 + version ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Grib1ParamTables object optionally specifying a parameter table or lookup table specific to this dataset . [CODESPLIT] public static Grib1ParamTables factory ( String paramTablePath , String lookupTablePath ) throws IOException { if ( paramTablePath == null && lookupTablePath == null ) return new Grib1ParamTables ( ) ; Lookup lookup = null ; Grib1ParamTableReader override = null ; Grib1ParamTableReader table ; if ( paramTablePath != null ) { table = localTableHash . get ( paramTablePath ) ; if ( table == null ) { table = new Grib1ParamTableReader ( paramTablePath ) ; localTableHash . put ( paramTablePath , table ) ; override = table ; } } if ( lookupTablePath != null ) { lookup = new Lookup ( ) ; if ( ! lookup . readLookupTable ( lookupTablePath ) ) throw new FileNotFoundException ( \"cant read lookup table=\" + lookupTablePath ) ; } return new Grib1ParamTables ( lookup , override ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Grib1Tables object optionally specifiying a parameter table in XML specific to this dataset . [CODESPLIT] public static Grib1ParamTables factory ( org . jdom2 . Element paramTableElem ) { if ( paramTableElem == null ) return new Grib1ParamTables ( ) ; return new Grib1ParamTables ( null , new Grib1ParamTableReader ( paramTableElem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debugging only [CODESPLIT] public Grib1ParamTableReader getParameterTable ( int center , int subcenter , int tableVersion ) { Grib1ParamTableReader result = null ; if ( lookup != null ) result = lookup . getParameterTable ( center , subcenter , tableVersion ) ; if ( result == null ) result = standardLookup . getParameterTable ( center , subcenter , tableVersion ) ; // standard tables\r return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all tables in list to standard tables [CODESPLIT] public static boolean addParameterTableLookup ( String lookupFilename ) throws IOException { Lookup lookup = new Lookup ( ) ; if ( ! lookup . readLookupTable ( lookupFilename ) ) return false ; synchronized ( lock ) { standardLookup . tables . addAll ( standardTablesStart , lookup . tables ) ; standardTablesStart += lookup . tables . size ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add table to standard tables for a specific center subcenter and version . [CODESPLIT] public static void addParameterTable ( int center , int subcenter , int tableVersion , String tableFilename ) { Grib1ParamTableReader table = new Grib1ParamTableReader ( center , subcenter , tableVersion , tableFilename ) ; synchronized ( lock ) { standardLookup . tables . add ( standardTablesStart , table ) ; standardTablesStart ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply this unit by another unit . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { if ( ! that . isDimensionless ( ) ) { throw new MultiplyException ( that ) ; } return that instanceof ScaledUnit ? new ScaledUnit ( ( ( ScaledUnit ) that ) . getScale ( ) , this ) : this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide this unit by another unit . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws DivideException { if ( ! that . isDimensionless ( ) ) { throw new DivideException ( that ) ; } return that instanceof ScaledUnit ? new ScaledUnit ( 1.0 / ( ( ScaledUnit ) that ) . getScale ( ) , this ) : this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Raise this unit to a power . [CODESPLIT] @ Override protected Unit myRaiseTo ( final int power ) throws RaiseException { if ( power == 0 ) { return DerivedUnitImpl . DIMENSIONLESS ; } if ( power == 1 ) { return this ; } throw new RaiseException ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts values in this unit to the equivalent values in the convertible derived unit . [CODESPLIT] public float [ ] toDerivedUnit ( final float [ ] input , final float [ ] output ) throws ConversionException { for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] = ( float ) ( Math . exp ( input [ i ] * lnBase ) ) ; } return reference . toDerivedUnit ( output , output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts values in the convertible derived unit to the equivalent values in this unit . [CODESPLIT] public float [ ] fromDerivedUnit ( final float [ ] input , final float [ ] output ) throws ConversionException { reference . fromDerivedUnit ( input , output ) ; for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] = ( float ) ( Math . log ( output [ i ] ) / lnBase ) ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a valid file? [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { // quick test raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . seek ( 0 ) ; String got = raf . readString ( V5D . length ( ) ) ; if ( got . equals ( V5D ) ) { return true ; } else { // more rigorous test V5DStruct vv ; try { vv = V5DStruct . v5dOpenFile ( raf ) ; } catch ( BadFormException bfe ) { vv = null ; } return vv != null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the service provider for reading . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; if ( unitTable == null ) { initUnitTable ( ) ; } if ( v5dstruct == null ) { makeFile ( raf , ncfile , cancelTask ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the netcdf file [CODESPLIT] private void makeFile ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { ncfile . empty ( ) ; int [ ] sizes = new int [ 5 ] ; int [ ] map_proj = new int [ 1 ] ; String [ ] varnames = new String [ MAXVARS ] ; String [ ] varunits = new String [ MAXVARS ] ; int [ ] n_levels = new int [ MAXVARS ] ; int [ ] vert_sys = new int [ 1 ] ; float [ ] vertargs = new float [ MAXVERTARGS ] ; double [ ] times = new double [ MAXTIMES ] ; float [ ] projargs = new float [ MAXPROJARGS ] ; try { v5dstruct = V5DStruct . v5d_open ( raf , sizes , n_levels , varnames , varunits , map_proj , projargs , vert_sys , vertargs , times ) ; } catch ( BadFormException bfe ) { throw new IOException ( \"Vis5DIosp.makeFile: bad file \" + bfe . getMessage ( ) ) ; } if ( sizes [ 0 ] < 1 ) { throw new IOException ( \"Vis5DIosp.makeFile: bad file\" ) ; } int nr = sizes [ 0 ] ; int nc = sizes [ 1 ] ; int nl = sizes [ 2 ] ; int ntimes = sizes [ 3 ] ; int nvars = sizes [ 4 ] ; // System.out.println(\"nr: \"+nr); // System.out.println(\"nc: \"+nc); // System.out.println(\"nl: \"+nl); // System.out.println(\"ntimes: \"+ntimes); // System.out.println(\"nvars: \"+nvars); Dimension time = new Dimension ( TIME , ntimes , true ) ; Dimension row = new Dimension ( ROW , nr , true ) ; Dimension col = new Dimension ( COLUMN , nc , true ) ; ncfile . addDimension ( null , time ) ; ncfile . addDimension ( null , row ) ; ncfile . addDimension ( null , col ) ; // time Variable timeVar = new Variable ( ncfile , null , null , TIME ) ; timeVar . setDataType ( DataType . DOUBLE ) ; timeVar . setDimensions ( TIME ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , \"seconds since 1900-01-01 00:00:00\" ) ) ; timeVar . addAttribute ( new Attribute ( \"long_name\" , TIME ) ) ; timeVar . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ) ; Array varArray = new ArrayDouble . D1 ( ntimes ) ; for ( int i = 0 ; i < ntimes ; i ++ ) { ( ( ArrayDouble . D1 ) varArray ) . set ( i , times [ i ] ) ; } timeVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , timeVar ) ; // rows and columns Variable rowVar = new Variable ( ncfile , null , null , ROW ) ; rowVar . setDataType ( DataType . INT ) ; rowVar . setDimensions ( ROW ) ; varArray = new ArrayInt . D1 ( nr , false ) ; for ( int i = 0 ; i < nr ; i ++ ) { ( ( ArrayInt . D1 ) varArray ) . set ( i , i ) ; } rowVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , rowVar ) ; Variable colVar = new Variable ( ncfile , null , null , COLUMN ) ; colVar . setDataType ( DataType . INT ) ; colVar . setDimensions ( COLUMN ) ; varArray = new ArrayInt . D1 ( nc , false ) ; for ( int i = 0 ; i < nc ; i ++ ) { ( ( ArrayInt . D1 ) varArray ) . set ( i , i ) ; } colVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , colVar ) ; // sanity check on levels Hashtable < Integer , Object > var_table = new Hashtable <> ( ) ; boolean have3D = false ; for ( int i = 0 ; i < nvars ; i ++ ) { int nlevs = n_levels [ i ] ; if ( ! have3D && ( nlevs > 1 ) ) { have3D = true ; } var_table . put ( nlevs , new Object ( ) ) ; } int n_var_groups = var_table . size ( ) ; if ( n_var_groups > 2 ) { throw new IOException ( \"Vis5DIosp.makeFile: more than two variable groups by n_levels\" ) ; } else if ( n_var_groups == 0 ) { throw new IOException ( \"Vis5DIosp.makeFile: number of variable groups == 0\" ) ; } Variable vert = null ; if ( have3D ) { Dimension lev = new Dimension ( LEVEL , nl , true ) ; ncfile . addDimension ( null , lev ) ; vert = makeVerticalVariable ( vert_sys [ 0 ] , nl , vertargs ) ; if ( vert != null ) { ncfile . addVariable ( null , vert ) ; } } varTable = new Hashtable <> ( ) ; String dim3D = TIME + \" \" + LEVEL + \" \" + COLUMN + \" \" + ROW ; String dim2D = TIME + \" \" + COLUMN + \" \" + ROW ; //String coords3D = TIME + \" \" + vert.getName() + \" \" + LAT + \" \" + LON; String coords3D = \"unknown\" ; if ( vert != null ) { coords3D = TIME + \" Height \" + LAT + \" \" + LON ; } String coords2D = TIME + \" \" + LAT + \" \" + LON ; for ( int i = 0 ; i < nvars ; i ++ ) { Variable v = new Variable ( ncfile , null , null , varnames [ i ] ) ; if ( n_levels [ i ] > 1 ) { v . setDimensions ( dim3D ) ; v . addAttribute ( new Attribute ( CF . COORDINATES , coords3D ) ) ; } else { v . setDimensions ( dim2D ) ; v . addAttribute ( new Attribute ( CF . COORDINATES , coords2D ) ) ; } v . setDataType ( DataType . FLOAT ) ; String units = varunits [ i ] . trim ( ) ; if ( units . equals ( \"\" ) ) { // see if its in the unitTable String key = varnames [ i ] . trim ( ) . toLowerCase ( ) ; units = unitTable . get ( key ) ; } if ( units != null ) { v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; } // TODO: do two vars with the same name have different values? // check agaist duplicat variable names if ( varTable . get ( v ) == null ) { varTable . put ( v , i ) ; ncfile . addVariable ( null , v ) ; } } double [ ] [ ] proj_args = Set . floatToDouble ( new float [ ] [ ] { projargs } ) ; addLatLonVariables ( map_proj [ 0 ] , proj_args [ 0 ] , nr , nc ) ; // Vis5DGridDefRecord gridDef = new Vis5DGridDefRecord(map_proj[0], proj_args[0], nr, nc); ncfile . addAttribute ( null , new Attribute ( \"Conventions\" , \"CF-1.0\" ) ) ; ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data for the variable [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { // long startTime = System.currentTimeMillis(); Integer varIdx = varTable . get ( v2 ) ; if ( varIdx == null ) { throw new IOException ( \"unable to find variable index\" ) ; } int count = 0 ; int [ ] shape = v2 . getShape ( ) ; boolean haveZ = shape . length == 4 ; int nt = shape [ count ++ ] ; int nz = haveZ ? shape [ count ++ ] : 1 ; int ny = shape [ count ++ ] ; int nx = shape [ count ] ; count = 0 ; Range timeRange = section . getRange ( count ++ ) ; Range zRange = haveZ ? section . getRange ( count ++ ) : null ; Range yRange = section . getRange ( count ++ ) ; Range xRange = section . getRange ( count ) ; int grid_size = nx * ny * nz ; Array dataArray = Array . factory ( DataType . FLOAT , section . getShape ( ) ) ; IndexIterator ii = dataArray . getIndexIterator ( ) ; // loop over time for ( int timeIdx : timeRange ) { float [ ] data = new float [ grid_size ] ; float [ ] ranges = new float [ 2 ] ; try { v5dstruct . v5d_read ( timeIdx , varIdx , ranges , data ) ; } catch ( BadFormException bfe ) { throw new IOException ( \"Vis5DIosp.readData: \" + bfe . getMessage ( ) ) ; } if ( ( ranges [ 0 ] >= 0.99E30 ) && ( ranges [ 1 ] <= - 0.99E30 ) ) { //range_sets[j] = new Linear1DSet(0.0, 1.0, 255); } else if ( ranges [ 0 ] > ranges [ 1 ] ) { throw new IOException ( \"Vis5DIosp.readData: bad read \" + v2 . getFullName ( ) ) ; } // invert the rows float [ ] tmp_data = new float [ grid_size ] ; if ( zRange == null ) { int cnt = 0 ; for ( int mm = 0 ; mm < ny ; mm ++ ) { int start = ( mm + 1 ) * nx - 1 ; for ( int nn = 0 ; nn < nx ; nn ++ ) { tmp_data [ cnt ++ ] = data [ start -- ] ; } } } else { int cnt = 0 ; for ( int ll = 0 ; ll < nz ; ll ++ ) { for ( int mm = 0 ; mm < ny ; mm ++ ) { int start = ( ( mm + 1 ) * nx - 1 ) + nx * ny * ll ; for ( int nn = 0 ; nn < nx ; nn ++ ) { tmp_data [ cnt ++ ] = data [ start -- ] ; } } } } data = tmp_data ; // copy the data into the array for ( float aData : data ) { ii . setFloatNext ( aData ) ; } } // long end = System.currentTimeMillis() - startTime; return dataArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the unit table . This is used if there are no units in the file . [CODESPLIT] private static void initUnitTable ( ) { unitTable = new Hashtable <> ( ) ; // temperatures unitTable . put ( \"t\" , \"K\" ) ; unitTable . put ( \"td\" , \"K\" ) ; unitTable . put ( \"thte\" , \"K\" ) ; // winds unitTable . put ( \"u\" , \"m/s\" ) ; unitTable . put ( \"v\" , \"m/s\" ) ; unitTable . put ( \"w\" , \"m/s\" ) ; // pressure unitTable . put ( \"p\" , \"hPa\" ) ; unitTable . put ( \"mmsl\" , \"hPa\" ) ; // moisture unitTable . put ( \"rh\" , \"%\" ) ; // misc unitTable . put ( \"rhfz\" , \"%\" ) ; unitTable . put ( \"zagl\" , \"m\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a vertical dimension variable based on the info . Based on visad . data . vis5d . Vis5DVerticalSystem . [CODESPLIT] private Variable makeVerticalVariable ( int vert_sys , int n_levels , float [ ] vert_args ) throws IOException { String vert_unit = null ; String vert_type ; ArrayFloat . D1 data = new ArrayFloat . D1 ( n_levels ) ; AxisType axisType = null ; switch ( vert_sys ) { case ( 0 ) : vert_unit = null ; vert_type = \"height\" ; break ; case ( 1 ) : case ( 2 ) : vert_unit = \"km\" ; vert_type = \"altitude\" ; axisType = AxisType . Height ; break ; case ( 3 ) : vert_unit = \"mbar\" ; vert_type = \"pressure\" ; axisType = AxisType . Pressure ; break ; default : throw new IOException ( \"vert_sys unknown\" ) ; } Variable vertVar = new Variable ( ncfile , null , null , vert_type ) ; vertVar . setDimensions ( LEVEL ) ; vertVar . setDataType ( DataType . FLOAT ) ; if ( vert_unit != null ) { vertVar . addAttribute ( new Attribute ( CDM . UNITS , vert_unit ) ) ; } if ( axisType != null ) { vertVar . addAttribute ( new Attribute ( _Coordinate . AxisType , axisType . toString ( ) ) ) ; } switch ( vert_sys ) { case ( 0 ) : case ( 1 ) : for ( int i = 0 ; i < n_levels ; i ++ ) { data . set ( i , vert_args [ 0 ] + vert_args [ 1 ] * i ) ; } break ; case ( 2 ) : // Altitude in km - non-linear for ( int i = 0 ; i < n_levels ; i ++ ) { data . set ( i , vert_args [ i ] ) ; } break ; case ( 3 ) : // heights of pressure surfaces in km - non-linear try { Vis5DVerticalSystem . Vis5DVerticalCoordinateSystem vert_cs = new Vis5DVerticalSystem . Vis5DVerticalCoordinateSystem ( ) ; float [ ] [ ] pressures = new float [ 1 ] [ n_levels ] ; System . arraycopy ( vert_args , 0 , pressures [ 0 ] , 0 , n_levels ) ; for ( int i = 0 ; i < n_levels ; i ++ ) { pressures [ 0 ] [ i ] *= 1000 ; // km->m } pressures = vert_cs . fromReference ( pressures ) ; // convert to pressures for ( int i = 0 ; i < n_levels ; i ++ ) { data . set ( i , pressures [ 0 ] [ i ] ) ; } } catch ( VisADException ve ) { throw new IOException ( \"unable to make vertical system\" ) ; } break ; } vertVar . setCachedData ( data , false ) ; return vertVar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add lat / lon variables to the file [CODESPLIT] private void addLatLonVariables ( int map_proj , double [ ] proj_args , int nr , int nc ) throws IOException { //Vis5DGridDefRecord.printProjArgs(map_proj, proj_args); Vis5DGridDefRecord vgd = new Vis5DGridDefRecord ( map_proj , proj_args , nr , nc ) ; GridHorizCoordSys ghc = new GridHorizCoordSys ( vgd , new Vis5DLookup ( ) , null ) ; Vis5DCoordinateSystem coord_sys ; try { coord_sys = new Vis5DCoordinateSystem ( map_proj , proj_args , nr , nc ) ; Variable lat = new Variable ( ncfile , null , null , LAT ) ; lat . setDimensions ( COLUMN + \" \" + ROW ) ; lat . setDataType ( DataType . DOUBLE ) ; lat . addAttribute ( new Attribute ( \"long_name\" , \"latitude\" ) ) ; lat . addAttribute ( new Attribute ( CDM . UNITS , CDM . LAT_UNITS ) ) ; lat . addAttribute ( new Attribute ( CF . STANDARD_NAME , \"latitude\" ) ) ; lat . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; ncfile . addVariable ( null , lat ) ; Variable lon = new Variable ( ncfile , null , null , LON ) ; lon . setDimensions ( COLUMN + \" \" + ROW ) ; lon . setDataType ( DataType . DOUBLE ) ; lon . addAttribute ( new Attribute ( CDM . UNITS , CDM . LON_UNITS ) ) ; lon . addAttribute ( new Attribute ( \"long_name\" , \"longitude\" ) ) ; lon . addAttribute ( new Attribute ( CF . STANDARD_NAME , \"longitude\" ) ) ; lon . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; ncfile . addVariable ( null , lon ) ; int [ ] shape = new int [ ] { nc , nr } ; Array latArray = Array . factory ( DataType . DOUBLE , shape ) ; Array lonArray = Array . factory ( DataType . DOUBLE , shape ) ; double [ ] [ ] rowcol = new double [ 2 ] [ nr * nc ] ; for ( int x = 0 ; x < nc ; x ++ ) { for ( int y = 0 ; y < nr ; y ++ ) { int index = x * nr + y ; rowcol [ 0 ] [ index ] = y ; rowcol [ 1 ] [ index ] = x ; } } double [ ] [ ] latlon = coord_sys . toReference ( rowcol ) ; Index latIndex = latArray . getIndex ( ) ; Index lonIndex = lonArray . getIndex ( ) ; /*\n            for (int y = 0; y < nr; y++) {\n                for (int x = 0; x < nc; x++) {\n                    int index = y * nc + x;\n            */ for ( int x = 0 ; x < nc ; x ++ ) { for ( int y = 0 ; y < nr ; y ++ ) { int index = x * nr + y ; /*\n                    latArray.setDouble(latIndex.set(x, y), latlon[0][index]);\n                    lonArray.setDouble(lonIndex.set(x, y), latlon[1][index]);\n                    */ latArray . setDouble ( index , latlon [ 0 ] [ index ] ) ; lonArray . setDouble ( index , latlon [ 1 ] [ index ] ) ; } } lat . setCachedData ( latArray , false ) ; lon . setCachedData ( lonArray , false ) ; } catch ( VisADException ve ) { throw new IOException ( \"Vis5DIosp.addLatLon: \" + ve . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read and set the descriptor name size and endianness and return the entire contents of the descriptor ( including the name and size ) as a byte array . The file position will be left at the beginning of the next descriptor ( or at the end of file ) . [CODESPLIT] protected byte [ ] readDescriptor ( RandomAccessFile file , boolean littleEndianData , String expectedName ) throws DescriptorException { this . file = file ; this . littleEndianData = littleEndianData ; this . expectedName = expectedName ; verbose = getDefaultVerboseState ( expectedName ) ; byte [ ] data ; try { // // find the next descriptor with our expected name // findNext ( file ) ; // // keep track of the start of this descriptor // long startpos = file . getFilePointer ( ) ; // // get the name and descriptor size // byte [ ] header = new byte [ 8 ] ; file . readFully ( header ) ; descName = new String ( header , 0 , 4 , CDM . utf8Charset ) ; int size = grabInt ( header , 4 ) ; // // now back up to the start of the descriptor and read the entire // thing into a byte array // file . seek ( startpos ) ; data = new byte [ size ] ; file . readFully ( data ) ; } catch ( java . io . IOException ex ) { throw new DescriptorException ( ex ) ; } // // now check the name we got against the expected name // if ( ! descName . equals ( expectedName ) ) throw new DescriptorException ( \"Got descriptor name '\" + descName + \"' when expecting name '\" + expectedName + \"'\" ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skip the current DORADE descriptor in the file leaving the file position at the beginning of the next descriptor ( or at the end of file ) . [CODESPLIT] protected static void skipDescriptor ( RandomAccessFile file , boolean littleEndianData ) throws DescriptorException , java . io . IOException { try { file . readFully ( new byte [ 4 ] ) ; // skip name byte [ ] lenBytes = new byte [ 4 ] ; file . readFully ( lenBytes ) ; int descLen = grabInt ( lenBytes , 0 , littleEndianData ) ; file . readFully ( new byte [ descLen - 8 ] ) ; } catch ( java . io . EOFException eofex ) { return ; // just leave the file at EOF } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the name of the DORADE descriptor at the current location in the file . The current location will not be changed . [CODESPLIT] protected static String peekName ( RandomAccessFile file ) throws DescriptorException { try { long filepos = file . getFilePointer ( ) ; byte [ ] nameBytes = new byte [ 4 ] ; if ( file . read ( nameBytes ) == - 1 ) return null ; // EOF file . seek ( filepos ) ; return new String ( nameBytes , CDM . utf8Charset ) ; } catch ( IOException ex ) { throw new DescriptorException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given DORADE sweepfile contains little - endian data ( in violation of the DORADE definition ... ) . [CODESPLIT] public static boolean sweepfileIsLittleEndian ( RandomAccessFile file ) throws DescriptorException { int descLen ; try { file . seek ( 0 ) ; // // skip the 4-byte descriptor name // byte [ ] bytes = new byte [ 4 ] ; file . readFully ( bytes ) ; // // get the descriptor length // descLen = file . readInt ( ) ; file . seek ( 0 ) ; } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } return ( descLen < 0 || descLen > 0xffffff ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack a two - byte integer from the given byte array . [CODESPLIT] protected short grabShort ( byte [ ] bytes , int offset ) { int ndx0 = offset + ( littleEndianData ? 1 : 0 ) ; int ndx1 = offset + ( littleEndianData ? 0 : 1 ) ; // careful that we only allow sign extension on the highest order byte return ( short ) ( bytes [ ndx0 ] << 8 | ( bytes [ ndx1 ] & 0xff ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack a four - byte integer from the given byte array . [CODESPLIT] protected static int grabInt ( byte [ ] bytes , int offset , boolean littleEndianData ) { int ndx0 = offset + ( littleEndianData ? 3 : 0 ) ; int ndx1 = offset + ( littleEndianData ? 2 : 1 ) ; int ndx2 = offset + ( littleEndianData ? 1 : 2 ) ; int ndx3 = offset + ( littleEndianData ? 0 : 3 ) ; // careful that we only allow sign extension on the highest order byte return ( bytes [ ndx0 ] << 24 | ( bytes [ ndx1 ] & 0xff ) << 16 | ( bytes [ ndx2 ] & 0xff ) << 8 | ( bytes [ ndx3 ] & 0xff ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack a four - byte IEEE float from the given byte array . [CODESPLIT] protected float grabFloat ( byte [ ] bytes , int offset ) throws DescriptorException { try { byte [ ] src ; if ( littleEndianData ) { src = new byte [ 4 ] ; src [ 0 ] = bytes [ offset + 3 ] ; src [ 1 ] = bytes [ offset + 2 ] ; src [ 2 ] = bytes [ offset + 1 ] ; src [ 3 ] = bytes [ offset ] ; offset = 0 ; } else { src = bytes ; } DataInputStream stream = new DataInputStream ( new ByteArrayInputStream ( src , offset , 4 ) ) ; return stream . readFloat ( ) ; } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack an eight - byte IEEE float from the given byte array . [CODESPLIT] protected double grabDouble ( byte [ ] bytes , int offset ) throws DescriptorException { try { byte [ ] src ; if ( littleEndianData ) { src = new byte [ 8 ] ; src [ 0 ] = bytes [ offset + 7 ] ; src [ 1 ] = bytes [ offset + 6 ] ; src [ 2 ] = bytes [ offset + 5 ] ; src [ 3 ] = bytes [ offset + 4 ] ; src [ 4 ] = bytes [ offset + 3 ] ; src [ 5 ] = bytes [ offset + 2 ] ; src [ 6 ] = bytes [ offset + 1 ] ; src [ 7 ] = bytes [ offset ] ; offset = 0 ; } else { src = bytes ; } DataInputStream stream = new DataInputStream ( new ByteArrayInputStream ( src , offset , 8 ) ) ; return stream . readDouble ( ) ; } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default verbose state for new <code > DoradeDescriptor< / code > - s of the given name . [CODESPLIT] public static boolean getDefaultVerboseState ( String descriptorName ) { Boolean classVerboseState = classVerboseStates . get ( descriptorName . toUpperCase ( ) ) ; if ( classVerboseState != null ) return classVerboseState ; else return defaultVerboseState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an instance of this database . [CODESPLIT] public static synchronized StandardUnitDB instance ( ) throws UnitDBException { if ( instance == null ) { try { instance = new StandardUnitDB ( ) ; } catch ( Exception e ) { throw new UnitDBException ( \"Couldn't create standard unit-database\" , e ) ; } } return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a derived unit to the database . [CODESPLIT] private void au ( final String name , final String definition ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { au ( name , definition , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a derived unit to the database . [CODESPLIT] private void au ( final String name , final String definition , final String symbol , final String plural ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { final Unit unit = format . parse ( definition , this ) ; if ( unit == null ) { throw new NoSuchUnitException ( definition ) ; } addUnit ( unit . clone ( UnitName . newUnitName ( name , plural , symbol ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an alias for a unit to the database . [CODESPLIT] private void aa ( final String alias , final String name ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { aa ( alias , name , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a symbol for a unit to the database . [CODESPLIT] private void as ( final String symbol , final String name ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { addSymbol ( symbol , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final UnitDB db = StandardUnitDB . instance ( ) ; System . out . println ( \"db.get(\\\"meter\\\")=\" + db . get ( \"meter\" ) ) ; System . out . println ( \"db.get(\\\"meters\\\")=\" + db . get ( \"meters\" ) ) ; System . out . println ( \"db.get(\\\"metre\\\")=\" + db . get ( \"metre\" ) ) ; System . out . println ( \"db.get(\\\"metres\\\")=\" + db . get ( \"metres\" ) ) ; System . out . println ( \"db.get(\\\"m\\\")=\" + db . get ( \"m\" ) ) ; System . out . println ( \"db.get(\\\"newton\\\")=\" + db . get ( \"newton\" ) ) ; System . out . println ( \"db.get(\\\"Cel\\\")=\" + db . get ( \"Cel\" ) ) ; System . out . println ( \"db.get(\\\"Roentgen\\\")=\" + db . get ( \"Roentgen\" ) ) ; System . out . println ( \"db.get(\\\"rad\\\")=\" + db . get ( \"rad\" ) ) ; System . out . println ( \"db.get(\\\"rd\\\")=\" + db . get ( \"rd\" ) ) ; System . out . println ( \"db.get(\\\"perches\\\")=\" + db . get ( \"perches\" ) ) ; System . out . println ( \"db.get(\\\"jiffies\\\")=\" + db . get ( \"jiffies\" ) ) ; System . out . println ( \"db.get(\\\"foo\\\")=\" + db . get ( \"foo\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ try to figure out if we need to add file : to the location when writing [CODESPLIT] static public String canonicalizeWrite ( String location ) { try { URI refURI = URI . create ( location ) ; if ( refURI . isAbsolute ( ) ) return location ; } catch ( Exception e ) { //return \"file:\" + location;\r } return \"file:\" + location ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This augments URI . resolve () by also dealing with file : URIs . If baseURi is not a file : scheme then URI . resolve is called . Otherwise the last / is found in the base and the ref is appended to it . <p > For file : baseURLS : only reletive URLS not starting with / are supported . This is apparently different from the behavior of URI . resolve () so may be trouble but it allows NcML absolute location to be specified without the file : prefix . <p / > Example : <pre > base : file : // my / guide / collections / designfaq . ncml ref : sub / my . nc resolved : file : // my / guide / collections / sub / my . nc < / pre > [CODESPLIT] public static String resolve ( String baseUri , String relativeUri ) { if ( ( baseUri == null ) || ( relativeUri == null ) ) return relativeUri ; if ( relativeUri . startsWith ( \"file:\" ) ) return relativeUri ; // deal with a base file URL\r if ( baseUri . startsWith ( \"file:\" ) ) { // the case where the reletiveURL is absolute.\r // unfortunately, we may get an Exception\r try { URI uriRelative = URI . create ( relativeUri ) ; if ( uriRelative . isAbsolute ( ) ) return relativeUri ; } catch ( Exception e ) { // empty\r } if ( ( relativeUri . length ( ) > 0 ) && ( relativeUri . charAt ( 0 ) == ' ' ) ) return baseUri + relativeUri ; if ( ( relativeUri . length ( ) > 0 ) && ( relativeUri . charAt ( 0 ) == ' ' ) ) return relativeUri ; baseUri = StringUtil2 . substitute ( baseUri , \"\\\\\" , \"/\" ) ; // assumes forward slash\r int pos = baseUri . lastIndexOf ( ' ' ) ; if ( pos > 0 ) { String baseDir = baseUri . substring ( 0 , pos + 1 ) ; if ( relativeUri . equals ( \".\" ) ) { return baseDir ; } else { return baseDir + relativeUri ; } } } // non-file URLs\r //relativeUri = canonicalizeRead(relativeUri);\r try { URI relativeURI = URI . create ( relativeUri ) ; if ( relativeURI . isAbsolute ( ) ) return relativeUri ; //otherwise let the URI class resolve it\r URI baseURI = URI . create ( baseUri ) ; URI resolvedURI = baseURI . resolve ( relativeURI ) ; return resolvedURI . toASCIIString ( ) ; } catch ( IllegalArgumentException e ) { return relativeUri ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for creating a unit converter . [CODESPLIT] public static Converter create ( Unit fromUnit , Unit toUnit ) throws ConversionException { return fromUnit . getConverterTo ( toUnit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writing data [CODESPLIT] public void writeRecord ( PointFeature sobs , StructureData sdata ) throws IOException { writeRecord ( sobs . getObservationTime ( ) , sobs . getObservationTimeAsCalendarDate ( ) , sobs . getLocation ( ) , sdata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add listener : ListSelectionEvent sent when a new row is selected [CODESPLIT] public void addListSelectionListener ( ListSelectionListener l ) { listeners . add ( javax . swing . event . ListSelectionListener . class , l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove listener [CODESPLIT] public void removeListSelectionListener ( ListSelectionListener l ) { listeners . remove ( javax . swing . event . ListSelectionListener . class , l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data as a collection of StructureData . [CODESPLIT] public void setStructureData ( List < StructureData > structureData ) throws IOException { dataModel = new StructureDataModel ( structureData ) ; initTable ( dataModel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data as a collection of PointFeature . [CODESPLIT] public void setPointFeatureData ( List < PointFeature > obsData ) throws IOException { dataModel = new PointFeatureDataModel ( obsData ) ; initTable ( dataModel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws all the features that are within the graphics clip rectangle using the previously set displayProjection . [CODESPLIT] public void draw ( java . awt . Graphics2D g , AffineTransform pixelAT ) { g . setColor ( color ) ; g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; g . setStroke ( new java . awt . BasicStroke ( 0.0f ) ) ; Rectangle2D clipRect = ( Rectangle2D ) g . getClip ( ) ; Iterator siter = getShapes ( g , pixelAT ) ; while ( siter . hasNext ( ) ) { Shape s = ( Shape ) siter . next ( ) ; Rectangle2D shapeBounds = s . getBounds2D ( ) ; if ( shapeBounds . intersects ( clipRect ) ) g . draw ( s ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the set of shapes to draw convert projections if need be [CODESPLIT] protected Iterator getShapes ( java . awt . Graphics2D g , AffineTransform normal2device ) { if ( shapeList != null ) return shapeList . iterator ( ) ; if ( Debug . isSet ( \"projection/LatLonShift\" ) ) System . out . println ( \"projection/LatLonShift GisFeatureRenderer.getShapes called\" ) ; ProjectionImpl dataProject = getDataProjection ( ) ; // a list of GisFeatureAdapter-s List featList = getFeatures ( ) ; shapeList = new ArrayList ( featList . size ( ) ) ; Iterator iter = featList . iterator ( ) ; while ( iter . hasNext ( ) ) { AbstractGisFeature feature = ( AbstractGisFeature ) iter . next ( ) ; Shape shape ; if ( dataProject == null ) shape = feature . getShape ( ) ; else if ( dataProject . isLatLon ( ) ) { // always got to run it through if its lat/lon shape = feature . getProjectedShape ( displayProject ) ; //System.out.println(\"getShapes dataProject.isLatLon() \"+displayProject); } else if ( dataProject == displayProject ) { shape = feature . getShape ( ) ; //System.out.println(\"getShapes dataProject == displayProject\"); } else { shape = feature . getProjectedShape ( dataProject , displayProject ) ; //System.out.println(\"getShapes dataProject != displayProject\"); } shapeList . add ( shape ) ; } return shapeList . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : metadata / wml2 : DocumentMetadata [CODESPLIT] public static DocumentMetadataType initDocumentMetadata ( DocumentMetadataType documentMetadata ) { // @gml:id String id = MarshallingUtil . createIdForType ( DocumentMetadataType . class ) ; documentMetadata . setId ( id ) ; // wml2:generationDate DateTime generationDate = MarshallingUtil . fixedGenerationDate ; if ( generationDate == null ) { generationDate = new DateTime ( ) ; // Initialized to \"now\". } documentMetadata . setGenerationDate ( generationDate . toGregorianCalendar ( ) ) ; return documentMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "time ( nruns ntimes ) - > time ( ntimes ) with dependent reftime ( ntime ) coordinate [CODESPLIT] private void makeUniqueTimeCoordinate2D ( NetcdfFile ncfile , Group g , CoordinateTime2D time2D ) { CoordinateRuntime runtime = time2D . getRuntimeCoordinate ( ) ; int countU = 0 ; for ( int run = 0 ; run < time2D . getNruns ( ) ; run ++ ) { CoordinateTimeAbstract timeCoord = time2D . getTimeCoordinate ( run ) ; countU += timeCoord . getSize ( ) ; } int ntimes = countU ; String tcName = time2D . getName ( ) ; ncfile . addDimension ( g , new Dimension ( tcName , ntimes ) ) ; Variable v = ncfile . addVariable ( g , new Variable ( ncfile , g , null , tcName , DataType . DOUBLE , tcName ) ) ; String units = runtime . getUnit ( ) ; // + \" since \" + runtime.getFirstDate(); v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; v . addAttribute ( new Attribute ( CF . STANDARD_NAME , CF . TIME ) ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , Grib . GRIB_VALID_TIME ) ) ; v . addAttribute ( new Attribute ( CF . CALENDAR , Calendar . proleptic_gregorian . toString ( ) ) ) ; // the data is not generated until asked for to save space if ( ! time2D . isTimeInterval ( ) ) { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . offU , time2D , null ) ) ; } else { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . intvU , time2D , null ) ) ; // bounds for intervals String bounds_name = tcName + \"_bounds\" ; Variable bounds = ncfile . addVariable ( g , new Variable ( ncfile , g , null , bounds_name , DataType . DOUBLE , tcName + \" 2\" ) ) ; v . addAttribute ( new Attribute ( CF . BOUNDS , bounds_name ) ) ; bounds . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; bounds . addAttribute ( new Attribute ( CDM . LONG_NAME , \"bounds for \" + tcName ) ) ; bounds . setSPobject ( new Time2Dinfo ( Time2DinfoType . boundsU , time2D , null ) ) ; } if ( runtime . getNCoords ( ) != 1 ) { // for this case we have to generate a separate reftime, because have to use the same dimension String refName = \"ref\" + tcName ; if ( g . findVariable ( refName ) == null ) { Variable vref = ncfile . addVariable ( g , new Variable ( ncfile , g , null , refName , DataType . DOUBLE , tcName ) ) ; vref . addAttribute ( new Attribute ( CF . STANDARD_NAME , CF . TIME_REFERENCE ) ) ; vref . addAttribute ( new Attribute ( CDM . LONG_NAME , Grib . GRIB_RUNTIME ) ) ; vref . addAttribute ( new Attribute ( CF . CALENDAR , Calendar . proleptic_gregorian . toString ( ) ) ) ; vref . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; vref . setSPobject ( new Time2Dinfo ( Time2DinfoType . isUniqueRuntime , time2D , null ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * non unique time case 3 ) time ( nruns ntimes ) with reftime ( nruns ) [CODESPLIT] private void makeTimeCoordinate2D ( NetcdfFile ncfile , Group g , CoordinateTime2D time2D , GribCollectionImmutable . Type gctype ) { CoordinateRuntime runtime = time2D . getRuntimeCoordinate ( ) ; int ntimes = time2D . getNtimes ( ) ; String tcName = time2D . getName ( ) ; String dims = runtime . getName ( ) + \" \" + tcName ; int dimLength = ntimes ; ncfile . addDimension ( g , new Dimension ( tcName , dimLength ) ) ; Variable v = ncfile . addVariable ( g , new Variable ( ncfile , g , null , tcName , DataType . DOUBLE , dims ) ) ; String units = runtime . getUnit ( ) ; // + \" since \" + runtime.getFirstDate(); v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; v . addAttribute ( new Attribute ( CF . STANDARD_NAME , CF . TIME ) ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , Grib . GRIB_VALID_TIME ) ) ; v . addAttribute ( new Attribute ( CF . CALENDAR , Calendar . proleptic_gregorian . toString ( ) ) ) ; // the data is not generated until asked for to save space if ( ! time2D . isTimeInterval ( ) ) { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . off , time2D , null ) ) ; } else { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . intv , time2D , null ) ) ; // bounds for intervals String bounds_name = tcName + \"_bounds\" ; Variable bounds = ncfile . addVariable ( g , new Variable ( ncfile , g , null , bounds_name , DataType . DOUBLE , dims + \" 2\" ) ) ; v . addAttribute ( new Attribute ( CF . BOUNDS , bounds_name ) ) ; bounds . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; bounds . addAttribute ( new Attribute ( CDM . LONG_NAME , \"bounds for \" + tcName ) ) ; bounds . setSPobject ( new Time2Dinfo ( Time2DinfoType . bounds , time2D , null ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only for the 2d times [CODESPLIT] private Array makeLazyTime1Darray ( Variable v2 , Time2Dinfo info ) { int length = info . time1D . getSize ( ) ; double [ ] data = new double [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { data [ i ] = Double . NaN ; } // coordinate values switch ( info . which ) { case reftime : CoordinateRuntime rtc = ( CoordinateRuntime ) info . time1D ; int count = 0 ; for ( double val : rtc . getOffsetsInTimeUnits ( ) ) { data [ count ++ ] = val ; } return Array . factory ( DataType . DOUBLE , v2 . getShape ( ) , data ) ; case timeAuxRef : CoordinateTimeAbstract time = ( CoordinateTimeAbstract ) info . time1D ; count = 0 ; List < Double > masterOffsets = gribCollection . getMasterRuntime ( ) . getOffsetsInTimeUnits ( ) ; for ( int masterIdx : time . getTime2runtime ( ) ) { data [ count ++ ] = masterOffsets . get ( masterIdx - 1 ) ; } return Array . factory ( DataType . DOUBLE , v2 . getShape ( ) , data ) ; default : throw new IllegalStateException ( \"makeLazyTime1Darray must be reftime or timeAuxRef\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only for the 2d times [CODESPLIT] private Array makeLazyTime2Darray ( Variable coord , Time2Dinfo info ) { CoordinateTime2D time2D = info . time2D ; CalendarPeriod timeUnit = time2D . getTimeUnit ( ) ; int nruns = time2D . getNruns ( ) ; int ntimes = time2D . getNtimes ( ) ; int length = ( int ) coord . getSize ( ) ; if ( info . which == Time2DinfoType . bounds ) { length *= 2 ; } double [ ] data = new double [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { data [ i ] = Double . NaN ; } int count ; // coordinate values switch ( info . which ) { case off : for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTime coordTime = ( CoordinateTime ) time2D . getTimeCoordinate ( runIdx ) ; int timeIdx = 0 ; for ( int val : coordTime . getOffsetSorted ( ) ) { data [ runIdx * ntimes + timeIdx ] = timeUnit . getValue ( ) * val + time2D . getOffset ( runIdx ) ; timeIdx ++ ; } } break ; case offU : count = 0 ; for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTime coordTime = ( CoordinateTime ) time2D . getTimeCoordinate ( runIdx ) ; for ( int val : coordTime . getOffsetSorted ( ) ) { data [ count ++ ] = timeUnit . getValue ( ) * val + time2D . getOffset ( runIdx ) ; } } break ; case intv : for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; int timeIdx = 0 ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ runIdx * ntimes + timeIdx ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; // use upper bounds for coord value timeIdx ++ ; } } break ; case intvU : count = 0 ; for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ count ++ ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; // use upper bounds for coord value } } break ; case is1Dtime : CoordinateRuntime runtime = time2D . getRuntimeCoordinate ( ) ; count = 0 ; for ( double val : runtime . getOffsetsInTimeUnits ( ) ) { // convert to udunits data [ count ++ ] = val ; } break ; case isUniqueRuntime : // the aux runtime coordinate CoordinateRuntime runtimeU = time2D . getRuntimeCoordinate ( ) ; List < Double > runOffsets = runtimeU . getOffsetsInTimeUnits ( ) ; count = 0 ; for ( int run = 0 ; run < time2D . getNruns ( ) ; run ++ ) { CoordinateTimeAbstract timeCoord = time2D . getTimeCoordinate ( run ) ; for ( int time = 0 ; time < timeCoord . getNCoords ( ) ; time ++ ) { data [ count ++ ] = runOffsets . get ( run ) ; } } break ; case bounds : for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; int timeIdx = 0 ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ runIdx * ntimes * 2 + timeIdx ] = timeUnit . getValue ( ) * tinv . getBounds1 ( ) + time2D . getOffset ( runIdx ) ; data [ runIdx * ntimes * 2 + timeIdx + 1 ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; timeIdx += 2 ; } } break ; case boundsU : count = 0 ; for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ count ++ ] = timeUnit . getValue ( ) * tinv . getBounds1 ( ) + time2D . getOffset ( runIdx ) ; data [ count ++ ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; } } break ; default : throw new IllegalStateException ( ) ; } return Array . factory ( DataType . DOUBLE , coord . getShape ( ) , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { long start = System . currentTimeMillis ( ) ; // see if its time2D - then generate data on the fly if ( v2 . getSPobject ( ) instanceof Time2Dinfo ) { Time2Dinfo info = ( Time2Dinfo ) v2 . getSPobject ( ) ; Array data = makeLazyCoordinateData ( v2 , info ) ; Section sectionFilled = Section . fill ( section , v2 . getShape ( ) ) ; return data . sectionNoReduce ( sectionFilled . getRanges ( ) ) ; } try { Array result ; GribCollectionImmutable . VariableIndex vindex = ( GribCollectionImmutable . VariableIndex ) v2 . getSPobject ( ) ; GribDataReader dataReader = GribDataReader . factory ( gribCollection , vindex ) ; SectionIterable sectionIter = new SectionIterable ( section , v2 . getShape ( ) ) ; result = dataReader . readData ( sectionIter ) ; long took = System . currentTimeMillis ( ) - start ; return result ; } catch ( IOException ioe ) { logger . error ( \"Failed to readData \" , ioe ) ; throw ioe ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK - needs to be a directory or maybe an MFILE collection [CODESPLIT] public void execute ( String filename ) throws IOException { File input = new File ( filename ) ; out . format ( \"BufrSplitter on %s length=%d%n\" , input . getPath ( ) , input . length ( ) ) ; try ( InputStream is = new FileInputStream ( input ) ) { processStream ( is ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process all the bytes in the stream [CODESPLIT] public void processStream ( InputStream is ) throws IOException { int pos = - 1 ; Buffer b = null ; while ( true ) { b = ( pos < 0 ) ? readBuffer ( is ) : readBuffer ( is , b , pos ) ; pos = processBuffer ( b , is ) ; if ( b . done ) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read into dest byte array until buffer is full or end of stream [CODESPLIT] private boolean readBuffer ( InputStream is , byte [ ] dest , int start , int want ) throws IOException { int done = 0 ; while ( done < want ) { int got = is . read ( dest , start + done , want - done ) ; if ( got < 0 ) return false ; done += got ; } if ( showRead ) System . out . println ( \"Read buffer at \" + bytesRead + \" len=\" + done ) ; bytesRead += done ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read into new Buffer until buffer is full or end of stream [CODESPLIT] private Buffer readBuffer ( InputStream is ) throws IOException { Buffer b = new Buffer ( ) ; int want = BUFFSIZE ; while ( b . have < want ) { int got = is . read ( b . buff , b . have , want - b . have ) ; if ( got < 0 ) { b . done = true ; break ; } b . have += got ; } if ( showRead ) System . out . println ( \"Read buffer at \" + bytesRead + \" len=\" + b . have ) ; bytesRead += b . have ; return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read into new Buffer until buffer is full or end of stream [CODESPLIT] private Buffer readBuffer ( InputStream is , Buffer prev , int pos ) throws IOException { Buffer b = new Buffer ( ) ; // copy remains of last buffer here int remain = prev . have - pos ; //if (remain > BUFFSIZE /2) //  out.format(\" remain = \"+remain+\" bytesRead=\"+bytesRead); System . arraycopy ( prev . buff , pos , b . buff , 0 , remain ) ; b . have = remain ; int want = BUFFSIZE ; while ( b . have < want ) { int got = is . read ( b . buff , b . have , want - b . have ) ; if ( got < 0 ) { b . done = true ; break ; } b . have += got ; } if ( showRead ) System . out . println ( \"Read buffer at \" + bytesRead + \" len=\" + b . have ) ; bytesRead += b . have ; return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get more bytes into buffer . Stop when endSequence is found . [CODESPLIT] private void getMoreBytes ( ) throws IOException { currentOffset = 0 ; // reset current array offset to 0\r int bytesRead = 0 ; // bytes read so far\r int lookingFor = 0 ; // character in endSequence to look for\r for ( ; bytesRead < lineBuf . length ; bytesRead ++ ) { int c = in . read ( ) ; if ( c == - 1 ) break ; // break on EOL and return what we have so far\r lineBuf [ bytesRead ] = ( byte ) c ; if ( lineBuf [ bytesRead ] == endSequence [ lookingFor ] ) { lookingFor ++ ; if ( lookingFor == endSequence . length ) { endFound = true ; break ; } } else if ( lineBuf [ bytesRead ] == endSequence [ 0 ] ) { // CHANGED JC\r lookingFor = 1 ; } else { lookingFor = 0 ; } } bytesRemaining = bytesRead ; // number of bytes we've read\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads up to len bytes of data from this input stream into an array of bytes . This method blocks until some input is available . [CODESPLIT] public int read ( byte b [ ] , int off , int len ) throws IOException { if ( len <= 0 ) { return 0 ; } int c = read ( ) ; if ( c == - 1 ) return - 1 ; b [ off ] = ( byte ) c ; // We've read one byte successfully, let's try for more\r int i = 1 ; try { for ( ; i < len ; i ++ ) { c = read ( ) ; if ( c == - 1 ) { break ; } b [ off + i ] = ( byte ) c ; } } catch ( IOException e ) { } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips over and discards n bytes of data from the input stream . [CODESPLIT] public long skip ( long n ) { if ( bytesRemaining >= n ) { bytesRemaining -= n ; return n ; } else { int oldBytesRemaining = bytesRemaining ; bytesRemaining = 0 ; return oldBytesRemaining ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reading [CODESPLIT] public void open ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; mySweep = new DoradeSweep ( raf . getRandomAccessFile ( ) ) ; headerParser = new Doradeheader ( ) ; headerParser . read ( mySweep , ncfile , null ) ; ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { System . out . println ( \"new QuantityDimension() = \\\"\" + new QuantityDimension ( ) + ' ' ) ; QuantityDimension timeDimension = new QuantityDimension ( BaseQuantity . TIME ) ; System . out . println ( \"timeDimension = \\\"\" + timeDimension + ' ' ) ; QuantityDimension lengthDimension = new QuantityDimension ( BaseQuantity . LENGTH ) ; System . out . println ( \"lengthDimension = \\\"\" + lengthDimension + ' ' ) ; System . out . println ( \"lengthDimension.isReciprocalOf(timeDimension) = \\\"\" + lengthDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; QuantityDimension hertzDimension = timeDimension . raiseTo ( - 1 ) ; System . out . println ( \"hertzDimension = \\\"\" + hertzDimension + ' ' ) ; System . out . println ( \"hertzDimension.isReciprocalOf(timeDimension) = \\\"\" + hertzDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; System . out . println ( \"lengthDimension.divideBy(timeDimension) = \\\"\" + lengthDimension . divideBy ( timeDimension ) + ' ' ) ; System . out . println ( \"lengthDimension.divideBy(timeDimension).raiseTo(2) = \\\"\" + lengthDimension . divideBy ( timeDimension ) . raiseTo ( 2 ) + ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array orogArray = readArray ( orogVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; int [ ] shape2D = orogArray . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index orogIndex = orogArray . getIndex ( ) ; ArrayDouble . D3 height = new ArrayDouble . D3 ( nz , ny , nx ) ; for ( int z = 0 ; z < nz ; z ++ ) { double az = aArray . getDouble ( aIndex . set ( z ) ) ; double bz = bArray . getDouble ( bIndex . set ( z ) ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { double orog = orogArray . getDouble ( orogIndex . set ( y , x ) ) ; height . set ( z , y , x , az + bz * orog ) ; } } } return height ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array orogArray = readArray ( orogVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; Index orogIndex = orogArray . getIndex ( ) ; ArrayDouble . D1 height = new ArrayDouble . D1 ( nz ) ; for ( int z = 0 ; z < nz ; z ++ ) { double az = aArray . getDouble ( aIndex . set ( z ) ) ; double bz = bArray . getDouble ( bIndex . set ( z ) ) ; double orog = orogArray . getDouble ( orogIndex . set ( yIndex , xIndex ) ) ; height . set ( z , az + bz * orog ) ; } return height ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match levels [CODESPLIT] boolean matchLevels ( List < GridRecord > records ) { // first create a new list List < LevelCoord > levelList = new ArrayList < LevelCoord > ( records . size ( ) ) ; for ( GridRecord record : records ) { LevelCoord lc = new LevelCoord ( record . getLevel1 ( ) , record . getLevel2 ( ) ) ; if ( ! levelList . contains ( lc ) ) { levelList . add ( lc ) ; } } Collections . sort ( levelList ) ; if ( positive . equals ( \"down\" ) ) { Collections . reverse ( levelList ) ; } // gotta equal existing list return levelList . equals ( levels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add this coord as a dimension to the netCDF file [CODESPLIT] void addDimensionsToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( ! isVertDimensionUsed ( ) ) return ; int nlevs = levels . size ( ) ; if ( coordValues != null ) nlevs = coordValues . length ; ncfile . addDimension ( g , new Dimension ( getVariableName ( ) , nlevs , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add this coord as a variable in the netCDF file [CODESPLIT] void addToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( ! isVertDimensionUsed ( ) ) { typicalRecord = null ; // allow gc return ; } if ( g == null ) { g = ncfile . getRootGroup ( ) ; } // coordinate axis Variable v = new Variable ( ncfile , g , null , getVariableName ( ) ) ; v . setDataType ( DataType . DOUBLE ) ; String desc = getLevelDesc ( ) ; v . addAttribute ( new Attribute ( \"long_name\" , desc ) ) ; v . addAttribute ( new Attribute ( \"units\" , lookup . getLevelUnit ( typicalRecord ) ) ) ; // positive attribute needed for CF-1 Height and Pressure if ( positive != null ) { v . addAttribute ( new Attribute ( \"positive\" , positive ) ) ; } if ( units != null ) { AxisType axisType ; if ( SimpleUnit . isCompatible ( \"millibar\" , units ) ) { axisType = AxisType . Pressure ; } else if ( SimpleUnit . isCompatible ( \"m\" , units ) ) { axisType = AxisType . Height ; } else { axisType = AxisType . GeoZ ; } addExtraAttributes ( v ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axisType . toString ( ) ) ) ; } if ( coordValues == null ) { coordValues = new double [ levels . size ( ) ] ; for ( int i = 0 ; i < levels . size ( ) ; i ++ ) { LevelCoord lc = ( LevelCoord ) levels . get ( i ) ; coordValues [ i ] = lc . mid ; } } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { coordValues . length } , coordValues ) ; v . setDimensions ( getVariableName ( ) ) ; v . setCachedData ( dataArray , true ) ; ncfile . addVariable ( g , v ) ; if ( usesBounds ) { Dimension bd = ucar . nc2 . dataset . DatasetConstructor . getBoundsDimension ( ncfile ) ; String bname = getVariableName ( ) + \"_bounds\" ; v . addAttribute ( new Attribute ( \"bounds\" , bname ) ) ; v . addAttribute ( new Attribute ( _Coordinate . ZisLayer , \"true\" ) ) ; Variable b = new Variable ( ncfile , g , null , bname ) ; b . setDataType ( DataType . DOUBLE ) ; b . setDimensions ( getVariableName ( ) + \" \" + bd . getShortName ( ) ) ; b . addAttribute ( new Attribute ( \"long_name\" , \"bounds for \" + v . getFullName ( ) ) ) ; b . addAttribute ( new Attribute ( \"units\" , lookup . getLevelUnit ( typicalRecord ) ) ) ; Array boundsArray = Array . factory ( DataType . DOUBLE , new int [ ] { coordValues . length , 2 } ) ; ucar . ma2 . Index ima = boundsArray . getIndex ( ) ; for ( int i = 0 ; i < coordValues . length ; i ++ ) { LevelCoord lc = ( LevelCoord ) levels . get ( i ) ; boundsArray . setDouble ( ima . set ( i , 0 ) , lc . value1 ) ; boundsArray . setDouble ( ima . set ( i , 1 ) , lc . value2 ) ; } b . setCachedData ( boundsArray , true ) ; ncfile . addVariable ( g , b ) ; } if ( factors != null ) { // check if already created if ( g == null ) { g = ncfile . getRootGroup ( ) ; } if ( g . findVariable ( \"hybrida\" ) != null ) return ; v . addAttribute ( new Attribute ( \"standard_name\" , \"atmosphere_hybrid_sigma_pressure_coordinate\" ) ) ; v . addAttribute ( new Attribute ( \"formula_terms\" , \"ap: hybrida b: hybridb ps: Pressure\" ) ) ; // create  hybrid factor variables // add hybrida variable Variable ha = new Variable ( ncfile , g , null , \"hybrida\" ) ; ha . setDataType ( DataType . DOUBLE ) ; ha . addAttribute ( new Attribute ( \"long_name\" , \"level_a_factor\" ) ) ; ha . addAttribute ( new Attribute ( \"units\" , \"\" ) ) ; ha . setDimensions ( getVariableName ( ) ) ; // add data int middle = factors . length / 2 ; double [ ] adata ; double [ ] bdata ; if ( levels . size ( ) < middle ) { // only partial data wanted adata = new double [ levels . size ( ) ] ; bdata = new double [ levels . size ( ) ] ; } else { adata = new double [ middle ] ; bdata = new double [ middle ] ; } for ( int i = 0 ; i < middle && i < levels . size ( ) ; i ++ ) adata [ i ] = factors [ i ] ; Array haArray = Array . factory ( DataType . DOUBLE , new int [ ] { adata . length } , adata ) ; ha . setCachedData ( haArray , true ) ; ncfile . addVariable ( g , ha ) ; // add hybridb variable Variable hb = new Variable ( ncfile , g , null , \"hybridb\" ) ; hb . setDataType ( DataType . DOUBLE ) ; hb . addAttribute ( new Attribute ( \"long_name\" , \"level_b_factor\" ) ) ; hb . addAttribute ( new Attribute ( \"units\" , \"\" ) ) ; hb . setDimensions ( getVariableName ( ) ) ; // add data for ( int i = 0 ; i < middle && i < levels . size ( ) ; i ++ ) bdata [ i ] = factors [ i + middle ] ; Array hbArray = Array . factory ( DataType . DOUBLE , new int [ ] { bdata . length } , bdata ) ; hb . setCachedData ( hbArray , true ) ; ncfile . addVariable ( g , hb ) ; /*  // TODO: delete next time modifying code\n      double[] adata = new double[ middle ];\n      for( int i = 0; i < middle; i++ )\n        adata[ i ] = factors[ i ];\n      Array haArray = Array.factory(DataType.DOUBLE, new int[]{adata.length}, adata);\n      ha.setCachedData(haArray, true);\n      ncfile.addVariable(g, ha);\n\n      // add hybridb variable\n      Variable hb = new Variable(ncfile, g, null, \"hybridb\");\n      hb.setDataType(DataType.DOUBLE);\n      hb.addAttribute(new Attribute(\"long_name\",  \"level_b_factor\" ));\n      //hb.addAttribute(new Attribute(\"standard_name\", \"atmosphere_hybrid_sigma_pressure_coordinate\" ));\n      hb.addAttribute(new Attribute(\"units\", \"\"));\n      hb.setDimensions(getVariableName());\n      // add data\n      double[] bdata = new double[ middle ];\n      for( int i = 0; i < middle; i++ )\n        bdata[ i ] = factors[ i + middle ];\n      Array hbArray = Array.factory(DataType.DOUBLE, new int[]{bdata.length}, bdata);\n      hb.setCachedData(hbArray, true);\n      ncfile.addVariable(g, hb);\n      */ } // allow gc // typicalRecord = null; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coordinate index for the record [CODESPLIT] private int coordIndex ( GridRecord record ) { double val = record . getLevel1 ( ) ; double val2 = record . getLevel2 ( ) ; if ( usesBounds && ( val > val2 ) ) { val = record . getLevel2 ( ) ; val2 = record . getLevel1 ( ) ; } for ( int i = 0 ; i < levels . size ( ) ; i ++ ) { LevelCoord lc = ( LevelCoord ) levels . get ( i ) ; if ( usesBounds ) { if ( ucar . nc2 . util . Misc . nearlyEquals ( lc . value1 , val ) && ucar . nc2 . util . Misc . nearlyEquals ( lc . value2 , val2 ) ) { return i ; } } else { if ( ucar . nc2 . util . Misc . nearlyEquals ( lc . value1 , val ) ) { return i ; } } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checking the file [CODESPLIT] public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) { NOWRadheader localHeader = new NOWRadheader ( ) ; return ( localHeader . isValidFile ( raf ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the file and read the header part [CODESPLIT] public void open ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile file , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; headerParser = new NOWRadheader ( ) ; try { headerParser . read ( this . raf , ncfile ) ; } catch ( Exception e ) { } // myInfo = headerParser.getVarInfo();\r pcode = 0 ; ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data for each variable passed in [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { // subset\r Object data ; Array outputData ; byte [ ] vdata = null ; NOWRadheader . Vinfo vinfo ; ByteBuffer bos ; List < Range > ranges = section . getRanges ( ) ; vinfo = ( NOWRadheader . Vinfo ) v2 . getSPobject ( ) ; vdata = headerParser . getData ( ( int ) vinfo . hoff ) ; bos = ByteBuffer . wrap ( vdata ) ; data = readOneScanData ( bos , vinfo , v2 . getShortName ( ) ) ; outputData = Array . factory ( v2 . getDataType ( ) , v2 . getShape ( ) , data ) ; outputData = outputData . flip ( 1 ) ; // outputData = outputData.flip(2);\r return ( outputData . sectionNoReduce ( ranges ) . copy ( ) ) ; // return outputData;\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all the work is here so can be called recursively [CODESPLIT] public Object readOneScanData ( ByteBuffer bos , NOWRadheader . Vinfo vinfo , String vName ) throws IOException , InvalidRangeException { int doff = ( int ) vinfo . hoff ; int npixel = vinfo . yt * vinfo . xt ; byte [ ] rdata = null ; byte [ ] ldata = new byte [ vinfo . xt ] ; byte [ ] pdata = new byte [ npixel ] ; byte [ ] b2 = new byte [ 2 ] ; bos . position ( doff ) ; // begining of image data\r if ( ( DataType . unsignedByteToShort ( bos . get ( ) ) != 0xF0 ) || ( bos . get ( ) != 0x0C ) ) { return null ; } int ecode ; int color ; int datapos ; int offset = 0 ; int roffset = 0 ; boolean newline = true ; int linenum = 0 ; while ( true ) { // line number\r if ( newline ) { bos . get ( b2 ) ; linenum = ( DataType . unsignedByteToShort ( b2 [ 1 ] ) << 8 ) + DataType . unsignedByteToShort ( b2 [ 0 ] ) ; // System.out.println(\"Line Number = \" + linenum);\r } // int linenum = bytesToInt(b2[0], b2[1], true);\r // System.out.println(\"Line Number = \" + linenum);\r // if(linenum == 1225)\r //   System.out.println(\" HHHHH\");\r short b = DataType . unsignedByteToShort ( bos . get ( ) ) ; color = b & 0xF ; ecode = b >> 4 ; datapos = bos . position ( ) ; int datarun ; if ( ecode == 0xF ) { byte bb1 = bos . get ( datapos - 2 ) ; byte bb2 = bos . get ( datapos ) ; if ( ( color == 0x0 ) && ( bb1 == 0x00 ) && ( bb2 == 0x00 ) ) { datapos += 1 ; } bos . position ( datapos ) ; datarun = 0 ; } else if ( ecode == 0xE ) { byte b0 = bos . get ( datapos ) ; datarun = DataType . unsignedByteToShort ( b0 ) + 1 ; datapos += 1 ; bos . position ( datapos ) ; } else if ( ecode == 0xD ) { b2 [ 0 ] = bos . get ( datapos ) ; b2 [ 1 ] = bos . get ( datapos + 1 ) ; datarun = ( DataType . unsignedByteToShort ( b2 [ 1 ] ) << 8 ) + DataType . unsignedByteToShort ( b2 [ 0 ] ) + 1 ; datapos += 2 ; bos . position ( datapos ) ; } else { datarun = ecode + 1 ; } // move the unpacked data in the data line\r rdata = new byte [ datarun ] ; for ( int i = 0 ; i < datarun ; i ++ ) { rdata [ i ] = ( byte ) color ; } System . arraycopy ( rdata , 0 , ldata , roffset , datarun ) ; roffset = roffset + datarun ; // System.out.println(\"run ecode = \" + ecode + \" and data run \" + datarun + \" and totalrun \" + roffset);\r // check to see if the beginning of the next line or at the end of the file\r short c0 = DataType . unsignedByteToShort ( bos . get ( ) ) ; if ( c0 == 0x00 ) { short c1 = DataType . unsignedByteToShort ( bos . get ( ) ) ; short c2 = DataType . unsignedByteToShort ( bos . get ( ) ) ; // System.out.println(\"c1 and c2 \" + c1 + \" \" + c2);\r if ( ( c0 == 0x00 ) && ( c1 == 0xF0 ) && ( c2 == 0x0C ) ) { // beginning of next line\r //  System.out.println(\"linenum   \" + linenum + \"   and this line total \" + roffset);\r //  if (roffset != 3661) {\r //      System.out.println(\"ERROR missing data, this line total only \" + roffset);\r //  }\r System . arraycopy ( ldata , 0 , pdata , offset , roffset ) ; offset = offset + vinfo . xt ; roffset = 0 ; newline = true ; ldata = new byte [ vinfo . xt ] ; } else if ( ( c1 == 0xF0 ) && ( c2 == 0x02 ) ) { // end of the file\r break ; } else { datapos = bos . position ( ) - 3 ; bos . position ( datapos ) ; newline = false ; } } else { newline = false ; datapos = bos . position ( ) ; bos . position ( datapos - 1 ) ; } } return pdata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from encoded values and run len into regular data array [CODESPLIT] public byte [ ] readOneRowData ( byte [ ] ddata , int rLen , int xt ) throws IOException , InvalidRangeException { int run ; byte [ ] bdata = new byte [ xt ] ; int nbin = 0 ; int total = 0 ; for ( run = 0 ; run < rLen ; run ++ ) { int drun = DataType . unsignedByteToShort ( ddata [ run ] ) >> 4 ; byte dcode1 = ( byte ) ( DataType . unsignedByteToShort ( ddata [ run ] ) & 0Xf ) ; for ( int i = 0 ; i < drun ; i ++ ) { bdata [ nbin ++ ] = dcode1 ; total ++ ; } } if ( total < xt ) { for ( run = total ; run < xt ; run ++ ) { bdata [ run ] = 0 ; } } return bdata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "take advantage of the work already done by NetcdfDataset [CODESPLIT] private void createFromDataset ( NetcdfDataset ncd ) { // get coordinate variables, disjunct from variables for ( CoordinateAxis axis : ncd . getCoordinateAxes ( ) ) { coordvars . put ( axis . getShortName ( ) , axis ) ; } // dup the variable set ddsvars = new ArrayList <> ( 50 ) ; // collect grid array variables and set of coordinate variables used in grids for ( Variable v : ncd . getVariables ( ) ) { if ( coordvars . containsKey ( v . getShortName ( ) ) ) continue ; // skip coordinate variables ddsvars . add ( v ) ; boolean isgridarray = ( v . getRank ( ) > 1 ) && ( v . getDataType ( ) != DataType . STRUCTURE ) && ( v . getParentStructure ( ) == null ) ; if ( ! isgridarray ) continue ; List < Dimension > dimset = v . getDimensions ( ) ; int rank = dimset . size ( ) ; for ( int i = 0 ; isgridarray && i < rank ; i ++ ) { Dimension dim = dimset . get ( i ) ; if ( dim . getShortName ( ) == null ) isgridarray = false ; else { Variable gv = coordvars . get ( dim . getShortName ( ) ) ; if ( gv == null ) isgridarray = false ; } } if ( isgridarray ) { gridarrays . put ( v . getFullName ( ) , v ) ; for ( Dimension dim : dimset ) { Variable gv = coordvars . get ( dim . getShortName ( ) ) ; if ( gv != null ) used . put ( gv . getFullName ( ) , gv ) ; } } } // Create the set of coordinates for ( Variable cv : ncd . getCoordinateAxes ( ) ) { BaseType bt = createVariable ( ncd , cv ) ; addVariable ( bt ) ; } // Create the set of variables for ( Variable cv : ddsvars ) { BaseType bt = createVariable ( ncd , cv ) ; addVariable ( bt ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "turn Variable into opendap variable [CODESPLIT] private BaseType createVariable ( NetcdfFile ncfile , Variable v ) { BaseType bt ; if ( v . getRank ( ) == 0 ) // scalar bt = createScalarVariable ( ncfile , v ) ; else if ( v . getDataType ( ) == DataType . CHAR ) { if ( v . getRank ( ) > 1 ) bt = new NcSDCharArray ( v ) ; else bt = new NcSDString ( v ) ; } else if ( v . getDataType ( ) == DataType . STRING ) { if ( v . getRank ( ) == 0 ) bt = new NcSDString ( v ) ; else bt = new NcSDArray ( v , new NcSDString ( v ) ) ; } else // non-char multidim array bt = createArray ( ncfile , v ) ; return bt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > ?< / code > . See BaseType . cloneDAG () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { NcDDS d = ( NcDDS ) super . cloneDAG ( map ) ; d . coordvars = coordvars ; return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called by Navigation [CODESPLIT] void fireMapAreaEvent ( ) { if ( debugZoom ) System . out . println ( \"NP.fireMapAreaEvent \" ) ; // decide if we need a new Projection: for LatLonProjection only if ( project . isLatLon ( ) ) { LatLonProjection llproj = ( LatLonProjection ) project ; ProjectionRect box = getMapArea ( ) ; double center = llproj . getCenterLon ( ) ; double lonBeg = LatLonPointImpl . lonNormal ( box . getMinX ( ) , center ) ; double lonEnd = lonBeg + box . getMaxX ( ) - box . getMinX ( ) ; boolean showShift = Debug . isSet ( \"projection/LatLonShift\" ) || debugNewProjection ; if ( showShift ) System . out . println ( \"projection/LatLonShift: min,max = \" + box . getMinX ( ) + \" \" + box . getMaxX ( ) + \" beg,end= \" + lonBeg + \" \" + lonEnd + \" center = \" + center ) ; if ( ( lonBeg < center - 180 ) || ( lonEnd > center + 180 ) ) { // got to do it double wx0 = box . getX ( ) + box . getWidth ( ) / 2 ; llproj . setCenterLon ( wx0 ) ; // shift cylinder seam double newWx0 = llproj . getCenterLon ( ) ; // normalize wx0 to [-180,180] setWorldCenterX ( newWx0 ) ; // tell navigation panel to shift if ( showShift ) System . out . println ( \"projection/LatLonShift: shift center to \" + wx0 + \"->\" + newWx0 ) ; // send projection event instead of map area event lmProject . sendEvent ( new NewProjectionEvent ( this , llproj ) ) ; return ; } } // send new map area event lmMapArea . sendEvent ( new NewMapAreaEvent ( this , getMapArea ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Map Area . [CODESPLIT] public void setMapArea ( ProjectionRect ma ) { if ( debugBB ) System . out . println ( \"NP.setMapArea \" + ma ) ; navigate . setMapArea ( ma ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Map Area by converting LatLonRect to a ProjectionRect . [CODESPLIT] public void setMapArea ( LatLonRect llbb ) { if ( debugBB ) System . out . println ( \"NP.setMapArea (ll) \" + llbb ) ; navigate . setMapArea ( project . latLonToProjBB ( llbb ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the center point of the MapArea [CODESPLIT] public void setLatLonCenterMapArea ( double lat , double lon ) { ProjectionPoint center = project . latLonToProj ( lat , lon ) ; ProjectionRect ma = getMapArea ( ) ; ma . setX ( center . getX ( ) - ma . getWidth ( ) / 2 ) ; ma . setY ( center . getY ( ) - ma . getHeight ( ) / 2 ) ; setMapArea ( ma ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Projection change the Map Area to the projection s default . [CODESPLIT] public void setProjectionImpl ( ProjectionImpl p ) { // transfer selection region to new coord system if ( geoSelection != null ) { LatLonRect geoLL = project . projToLatLonBB ( geoSelection ) ; setGeoSelection ( p . latLonToProjBB ( geoLL ) ) ; } // switch projections project = p ; navigate . setMapArea ( project . getDefaultMapArea ( ) ) ; if ( Debug . isSet ( \"projection/set\" ) || debugNewProjection ) System . out . println ( \"projection/set NP=\" + project ) ; // transfer reference point to new coord system if ( hasReference ) { refWorld . setLocation ( project . latLonToProj ( refLatLon ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all of the toolbar s actions to a menu . [CODESPLIT] public void addActionsToMenu ( JMenu menu ) { BAMutil . addActionToMenu ( menu , zoomIn ) ; BAMutil . addActionToMenu ( menu , zoomOut ) ; BAMutil . addActionToMenu ( menu , zoomBack ) ; BAMutil . addActionToMenu ( menu , zoomDefault ) ; menu . addSeparator ( ) ; BAMutil . addActionToMenu ( menu , moveUp ) ; BAMutil . addActionToMenu ( menu , moveDown ) ; BAMutil . addActionToMenu ( menu , moveRight ) ; BAMutil . addActionToMenu ( menu , moveLeft ) ; menu . addSeparator ( ) ; BAMutil . addActionToMenu ( menu , setReferenceAction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "from panning so wait delay msecs before doing the redraw . [CODESPLIT] private void redrawLater ( int delay ) { boolean already = ( redrawTimer != null ) && ( redrawTimer . isRunning ( ) ) ; if ( debugThread ) System . out . println ( \"redrawLater isRunning= \" + already ) ; if ( already ) return ; // initialize Timer the first time if ( redrawTimer == null ) { redrawTimer = new javax . swing . Timer ( 0 , new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { drawG ( ) ; redrawTimer . stop ( ) ; // one-shot timer } } ) ; } // start the timer running redrawTimer . setDelay ( delay ) ; redrawTimer . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets whether the user can zoom / pan on this NavigatedPanel . Default = true . [CODESPLIT] public void setChangeable ( boolean mode ) { if ( mode == changeable ) return ; changeable = mode ; if ( toolbar != null ) toolbar . setEnabled ( mode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "note : I believe that the RepaintManager is not used on JPanel subclasses ??? [CODESPLIT] public void repaint ( long tm , int x , int y , int width , int height ) { if ( debugDraw ) System . out . println ( \"REPAINT \" + repaintCount + \" x \" + x + \" y \" + y + \" width \" + width + \" heit \" + height ) ; if ( debugThread ) System . out . println ( \" thread = \" + Thread . currentThread ( ) ) ; repaintCount ++ ; super . repaint ( tm , x , y , width , height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "System - triggered redraw . [CODESPLIT] public void paintComponent ( Graphics g ) { if ( debugDraw ) System . out . println ( \"System called paintComponent clip= \" + g . getClipBounds ( ) ) ; draw ( ( Graphics2D ) g ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "User must get this Graphics2D and draw into it when panel needs redrawing [CODESPLIT] public Graphics2D getBufferedImageGraphics ( ) { if ( bImage == null ) return null ; Graphics2D g2 = bImage . createGraphics ( ) ; // set clipping rectangle into boundingBox navigate . getMapArea ( boundingBox ) ; if ( debugBB ) System . out . println ( \" getBufferedImageGraphics BB = \" + boundingBox ) ; // set graphics attributes g2 . setTransform ( navigate . getTransform ( ) ) ; g2 . setStroke ( new BasicStroke ( 0.0f ) ) ; // default stroke size is one pixel g2 . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_SPEED ) ; Rectangle2D hr = new Rectangle2D . Double ( ) ; hr . setRect ( boundingBox . getX ( ) , boundingBox . getY ( ) , boundingBox . getWidth ( ) , boundingBox . getHeight ( ) ) ; g2 . setClip ( hr ) ; // normalized coord system, because transform is applied g2 . setBackground ( backColor ) ; return g2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This calculates the Affine Transform that maps the current map area ( in Projection Coordinates ) to a display area ( in arbitrary units ) . @param rotate should the page be rotated? @param displayX upper right corner of display area @param displayY upper right corner of display area @param displayWidth display area @param displayHeight display area [CODESPLIT] public AffineTransform calcTransform ( boolean rotate , double displayX , double displayY , double displayWidth , double displayHeight ) { return navigate . calcTransform ( rotate , displayX , displayY , displayWidth , displayHeight ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when component resizes we need a new buffer [CODESPLIT] private void newScreenSize ( Rectangle b ) { boolean sameSize = ( b . width == myBounds . width ) && ( b . height == myBounds . height ) ; if ( debugBounds ) System . out . println ( \"NavigatedPanel newScreenSize old= \" + myBounds ) ; if ( sameSize && ( b . x == myBounds . x ) && ( b . y == myBounds . y ) ) return ; myBounds . setBounds ( b ) ; if ( sameSize ) return ; if ( debugBounds ) System . out . println ( \"  newBounds = \" + b ) ; // create new buffer the size of the window //if (bImage != null) //  bImage.dispose(); if ( ( b . width > 0 ) && ( b . height > 0 ) ) { bImage = new BufferedImage ( b . width , b . height , BufferedImage . TYPE_INT_RGB ) ; // why RGB ? } else { // why not device dependent? bImage = null ; } navigate . setScreenSize ( b . width , b . height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "draw and drawG are like paintImmediately () [CODESPLIT] public void drawG ( ) { Graphics g = getGraphics ( ) ; // bypasses double buffering ? if ( null != g ) { draw ( ( Graphics2D ) g ) ; g . dispose ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the currently selected Variable . [CODESPLIT] public void setSelected ( VariableIF v ) { if ( v == null ) { return ; } // construct chain of variables\r final List < VariableIF > vchain = new ArrayList <> ( ) ; vchain . add ( v ) ; VariableIF vp = v ; while ( vp . isMemberOfStructure ( ) ) { vp = vp . getParentStructure ( ) ; vchain . add ( 0 , vp ) ; // reverse\r } // construct chain of groups\r final List < Group > gchain = new ArrayList <> ( ) ; Group gp = vp . getParentGroup ( ) ; gchain . add ( gp ) ; while ( gp . getParentGroup ( ) != null ) { gp = gp . getParentGroup ( ) ; gchain . add ( 0 , gp ) ; // reverse\r } final List < Object > pathList = new ArrayList <> ( ) ; // start at root, work down through the nested groups, if any\r GroupNode gnode = ( GroupNode ) model . getRoot ( ) ; pathList . add ( gnode ) ; Group parentGroup = gchain . get ( 0 ) ; // always the root group\r for ( int i = 1 ; i < gchain . size ( ) ; i ++ ) { parentGroup = gchain . get ( i ) ; gnode = gnode . findNestedGroup ( parentGroup ) ; assert gnode != null ; pathList . add ( gnode ) ; } vp = vchain . get ( 0 ) ; VariableNode vnode = gnode . findNestedVariable ( vp ) ; if ( vnode == null ) { return ; } // not found\r pathList . add ( vnode ) ; // now work down through the structure members, if any\r for ( int i = 1 ; i < vchain . size ( ) ; i ++ ) { vp = vchain . get ( i ) ; vnode = vnode . findNestedVariable ( vp ) ; if ( vnode == null ) { return ; } // not found\r pathList . add ( vnode ) ; } // convert to TreePath, and select it\r final Object [ ] paths = pathList . toArray ( ) ; final TreePath treePath = new TreePath ( paths ) ; tree . setSelectionPath ( treePath ) ; tree . scrollPathToVisible ( treePath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : add index range checks [CODESPLIT] public Class getElementType ( ) { DataType dt = CDMTypeFcns . daptype2cdmtype ( this . basetype ) ; if ( dt == null ) throw new IllegalArgumentException ( \"Unknown datatype: \" + this . basetype ) ; return CDMTypeFcns . cdmElementClass ( dt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert int base to Index based [CODESPLIT] public double getDouble ( int offset ) { DapVariable d4var = ( DapVariable ) getTemplate ( ) ; long [ ] dimsizes = DapUtil . getDimSizes ( d4var . getDimensions ( ) ) ; return getDouble ( DapUtil . offsetToIndex ( offset , dimsizes ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array element at a specific dap4 index as a double [CODESPLIT] protected double getDouble ( dap4 . core . util . Index idx ) { assert data . getScheme ( ) == Scheme . ATOMIC ; try { Object value = data . read ( idx ) ; value = Convert . convert ( DapType . FLOAT64 , this . basetype , value ) ; return ( Double ) java . lang . reflect . Array . get ( value , 0 ) ; } catch ( IOException ioe ) { throw new IndexOutOfBoundsException ( ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array element at a specific dap4 index as an Object [CODESPLIT] protected Object getObject ( dap4 . core . util . Index idx ) { assert data . getScheme ( ) == Scheme . ATOMIC ; try { Object value = data . read ( idx ) ; value = java . lang . reflect . Array . get ( value , 0 ) ; return value ; } catch ( IOException ioe ) { throw new IndexOutOfBoundsException ( ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the string of Sector for the GINI image file [CODESPLIT] String gini_GetSectorID ( int ent_id ) { String name ; switch ( ent_id ) { case 0 : name = \"Northern Hemisphere Composite\" ; break ; case 1 : name = \"East CONUS\" ; break ; case 2 : name = \"West CONUS\" ; break ; case 3 : name = \"Alaska Regional\" ; break ; case 4 : name = \"Alaska National\" ; break ; case 5 : name = \"Hawaii Regional\" ; break ; case 6 : name = \"Hawaii National\" ; break ; case 7 : name = \"Puerto Rico Regional\" ; break ; case 8 : name = \"Puerto Rico National\" ; break ; case 9 : name = \"Supernational\" ; break ; case 10 : name = \"NH Composite - Meteosat/GOES E/ GOES W/GMS\" ; break ; case 11 : name = \"Central CONUS\" ; break ; case 12 : name = \"East Floater\" ; break ; case 13 : name = \"West Floater\" ; break ; case 14 : name = \"Central Floater\" ; break ; case 15 : name = \"Polar Floater\" ; break ; default : name = \"Unknown-ID\" ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the channel ID for the GINI image file [CODESPLIT] String gini_GetEntityID ( int ent_id ) { String name ; switch ( ent_id ) { case 2 : name = \"Miscellaneous\" ; break ; case 3 : name = \"JERS\" ; break ; case 4 : name = \"ERS/QuikSCAT/Scatterometer\" ; break ; case 5 : name = \"POES/NPOESS\" ; break ; case 6 : name = \"Composite\" ; break ; case 7 : name = \"DMSP satellite Image\" ; break ; case 8 : name = \"GMS satellite Image\" ; break ; case 9 : name = \"METEOSAT satellite Image\" ; break ; case 10 : name = \"GOES-7 satellite Image\" ; break ; case 11 : name = \"GOES-8 satellite Image\" ; break ; case 12 : name = \"GOES-9 satellite Image\" ; break ; case 13 : name = \"GOES-10 satellite Image\" ; break ; case 14 : name = \"GOES-11 satellite Image\" ; break ; case 15 : name = \"GOES-12 satellite Image\" ; break ; case 16 : name = \"GOES-13 satellite Image\" ; break ; case 17 : name = \"GOES-14 satellite Image\" ; break ; case 18 : name = \"GOES-15 satellite Image\" ; break ; case 19 : // GOES-R name = \"GOES-16 satellite Image\" ; break ; case 99 : // special snowflake GEMPAK Composite Images generated by Unidata name = \"RADAR-MOSIAC Composite Image\" ; break ; default : name = \"Unknown\" ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the channel ID for the GINI image file [CODESPLIT] String gini_GetPhysElemID ( int phys_elem , int ent_id ) { String name ; switch ( phys_elem ) { case 1 : name = \"VIS\" ; break ; case 3 : name = \"IR_WV\" ; break ; case 2 : case 4 : case 5 : case 6 : case 7 : name = \"IR\" ; break ; case 13 : name = \"LI\" ; break ; case 14 : name = \"PW\" ; break ; case 15 : name = \"SFC_T\" ; break ; case 16 : name = \"LI\" ; break ; case 17 : name = \"PW\" ; break ; case 18 : name = \"SFC_T\" ; break ; case 19 : name = \"CAPE\" ; break ; case 20 : name = \"T\" ; break ; case 21 : name = \"WINDEX\" ; break ; case 22 : name = \"DMPI\" ; break ; case 23 : name = \"MDPI\" ; break ; case 25 : if ( ent_id == 99 ) name = \"HHC\" ; else name = \"Volcano_imagery\" ; break ; case 26 : name = \"EchoTops\" ; break ; case 27 : if ( ent_id == 99 ) name = \"Reflectivity\" ; else name = \"CTP\" ; break ; case 28 : if ( ent_id == 99 ) name = \"Reflectivity\" ; else name = \"Cloud_Amount\" ; break ; case 29 : name = \"VIL\" ; break ; case 30 : case 31 : name = \"Precipitation\" ; break ; case 40 : case 41 : case 42 : case 43 : case 44 : case 45 : case 46 : case 47 : case 48 : case 49 : case 50 : case 51 : case 52 : case 53 : case 54 : case 55 : case 56 : case 57 : case 58 : name = \"sounder_imagery\" ; break ; case 59 : name = \"VIS_sounder\" ; break ; default : name = \"Unknown\" ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the channel ID for the GINI image file [CODESPLIT] String getPhysElemLongName ( int phys_elem , int ent_id ) { switch ( phys_elem ) { case 1 : return \"Imager Visible\" ; case 2 : return \"Imager 3.9 micron IR\" ; case 3 : return \"Imager 6.7/6.5 micron IR (WV)\" ; case 4 : return \"Imager 11 micron IR\" ; case 5 : return \"Imager 12 micron IR\" ; case 6 : return \"Imager 13 micron IR\" ; case 7 : return \"Imager 1.3 micron IR\" ; case 13 : return \"Lifted Index LI\" ; case 14 : return \"Precipitable Water PW\" ; case 15 : return \"Surface Skin Temperature\" ; case 16 : return \"Lifted Index LI\" ; case 17 : return \"Precipitable Water PW\" ; case 18 : return \"Surface Skin Temperature\" ; case 19 : return \"Convective Available Potential Energy\" ; case 20 : return \"land-sea Temperature\" ; case 21 : return \"Wind Index\" ; case 22 : return \"Dry Microburst Potential Index\" ; case 23 : return \"Microburst Potential Index\" ; case 24 : return \"Derived Convective Inhibition\" ; case 25 : if ( ent_id == 99 ) return \"1km National Hybrid Hydrometeor Classification Composite (Unidata)\" ; else return \"Volcano_imagery\" ; case 26 : if ( ent_id == 99 ) return \"1 km National Echo Tops Composite (Unidata)\" ; else return \"4 km National Echo Tops\" ; case 27 : if ( ent_id == 99 ) return \"1 km National Base Reflectivity Composite (Unidata)\" ; else return \"Cloud Top Pressure or Height\" ; case 28 : if ( ent_id == 99 ) return \"1 km National Reflectivity Composite (Unidata)\" ; else return \"Cloud Amount\" ; case 29 : if ( ent_id == 99 ) return \"1 km National Vertically Integrated Liquid Water (Unidata)\" ; else return \"4 km National Vertically Integrated Liquid Water\" ; case 30 : if ( ent_id == 99 ) return \"1 km National 1-hour Precipitation (Unidata)\" ; else return \"Surface wind speeds over oceans and Great Lakes\" ; case 31 : if ( ent_id == 99 ) return \"4 km National Storm Total Precipitation (Unidata)\" ; else return \"Surface Wetness\" ; case 32 : return \"Ice concentrations\" ; case 33 : return \"Ice type\" ; case 34 : return \"Ice edge\" ; case 35 : return \"Cloud water content\" ; case 36 : return \"Surface type\" ; case 37 : return \"Snow indicator\" ; case 38 : return \"Snow/water content\" ; case 39 : return \"Derived volcano imagery\" ; case 41 : return \"Sounder 14.71 micron imagery\" ; case 42 : return \"Sounder 14.37 micron imagery\" ; case 43 : return \"Sounder 14.06 micron imagery\" ; case 44 : return \"Sounder 13.64 micron imagery\" ; case 45 : return \"Sounder 13.37 micron imagery\" ; case 46 : return \"Sounder 12.66 micron imagery\" ; case 47 : return \"Sounder 12.02 micron imagery\" ; case 48 : return \"11.03 micron sounder image\" ; case 49 : return \"Sounder 11.03 micron imagery\" ; case 50 : return \"7.43 micron sounder image\" ; case 51 : return \"7.02 micron sounder image\" ; case 52 : return \"6.51 micron sounder image\" ; case 53 : return \"Sounder 4.57 micron imagery\" ; case 54 : return \"Sounder 4.52 micron imagery\" ; case 55 : return \"4.45 micron sounder image\" ; case 56 : return \"Sounder 4.13 micron imagery\" ; case 57 : return \"3.98 micron sounder image\" ; case 58 : return \"Sounder 3.74 micron imagery\" ; case 59 : return \"VIS sounder image \" ; default : return \"unknown physical element \" + phys_elem ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a scaled 3 - byte integer from file and convert to double [CODESPLIT] private double readScaledInt ( ByteBuffer buf ) { // Get the first two bytes short s1 = buf . getShort ( ) ; // And the last one as unsigned short s2 = DataType . unsignedByteToShort ( buf . get ( ) ) ; // Get the sign bit, converting from 0 or 2 to +/- 1. int posneg = 1 - ( ( s1 & 0x8000 ) >> 14 ) ; // Combine the first two bytes (without sign bit) with the last byte. // Multiply by proper factor for +/- int nn = ( ( ( s1 & 0x7FFF ) << 8 ) | s2 ) * posneg ; return ( double ) nn / 10000.0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience function ; look up Parameter by name ignoring case . [CODESPLIT] public Parameter findParameterIgnoreCase ( String name ) { for ( Parameter a : params ) { if ( name . equalsIgnoreCase ( a . getName ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterator API Overrides [CODESPLIT] @ Override public boolean hasNext ( ) { if ( this . current >= odomset . size ( ) ) return false ; Odometer ocurrent = odomset . get ( this . current ) ; if ( ocurrent . hasNext ( ) ) return true ; // Try to move to next odometer this . current ++ ; return hasNext ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the total number of elements . [CODESPLIT] @ Override public long totalSize ( ) { long size = 1 ; for ( int i = 0 ; i < this . rank ; i ++ ) { size *= slice ( i ) . getCount ( ) ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the ctl file [CODESPLIT] private void parseDDF ( int maxLines ) throws IOException { //long start2 = System.currentTimeMillis();\r variableList = new ArrayList <> ( ) ; dimList = new ArrayList <> ( ) ; attrList = new ArrayList <> ( ) ; // LOOK not using raf - opened file again\r int count = 0 ; try ( BufferedReader r = new BufferedReader ( new InputStreamReader ( new FileInputStream ( ddFile ) , CDM . utf8Charset ) ) ) { boolean inVarSection = false ; boolean inEnsSection = false ; String line ; String original ; GradsDimension curDim = null ; while ( ( original = r . readLine ( ) ) != null ) { count ++ ; if ( count > maxLines ) { error = true ; return ; } original = original . trim ( ) ; if ( original . isEmpty ( ) ) { continue ; } line = original . toLowerCase ( ) ; if ( line . startsWith ( \"@ \" ) ) { attrList . add ( GradsAttribute . parseAttribute ( original ) ) ; continue ; } // ignore attribute metadata and comments\r if ( line . startsWith ( \"*\" ) ) { continue ; } if ( inEnsSection ) { if ( line . startsWith ( ENDEDEF . toLowerCase ( ) ) ) { inEnsSection = false ; continue ; // done skipping ensemble definitions\r } // parse the ensemble info\r } if ( inVarSection ) { if ( line . startsWith ( ENDVARS . toLowerCase ( ) ) ) { inVarSection = false ; continue ; // done parsing variables\r } GradsVariable var = new GradsVariable ( original ) ; int numLevels = var . getNumLevels ( ) ; if ( numLevels == 0 ) { numLevels = 1 ; } gridsPerTimeStep += numLevels ; // parse a variable\r variableList . add ( var ) ; } else { // not in var section or edef section, look for general metadata\r StringTokenizer st = new StringTokenizer ( original ) ; String label = st . nextToken ( ) ; // TODO: Handle other options\r if ( label . equalsIgnoreCase ( OPTIONS ) ) { curDim = null ; while ( st . hasMoreTokens ( ) ) { String token = st . nextToken ( ) ; if ( token . equalsIgnoreCase ( BIG_ENDIAN ) ) { bigEndian = true ; } else if ( token . equalsIgnoreCase ( LITTLE_ENDIAN ) ) { bigEndian = false ; } else if ( token . equalsIgnoreCase ( BYTESWAPPED ) ) { swapByteOrder ( ) ; } else if ( token . equalsIgnoreCase ( YREV ) ) { yReversed = true ; } else if ( token . equalsIgnoreCase ( TEMPLATE ) ) { isTemplate = true ; } else if ( token . equalsIgnoreCase ( SEQUENTIAL ) ) { isSequential = true ; } } } else if ( label . equalsIgnoreCase ( CHSUB ) ) { int start = Integer . parseInt ( st . nextToken ( ) ) ; int end = Integer . parseInt ( st . nextToken ( ) ) ; String sub = st . nextToken ( ) ; addChsub ( new Chsub ( start , end , sub ) ) ; } else if ( label . equalsIgnoreCase ( DSET ) ) { curDim = null ; dataFile = st . nextToken ( ) ; } else if ( label . equalsIgnoreCase ( UNDEF ) ) { curDim = null ; missingData = Double . parseDouble ( st . nextToken ( ) ) ; } else if ( label . equalsIgnoreCase ( XYHEADER ) ) { curDim = null ; xyHeaderBytes = Integer . parseInt ( st . nextToken ( ) ) ; } else if ( label . equalsIgnoreCase ( FILEHEADER ) ) { curDim = null ; fileHeaderBytes = Integer . parseInt ( st . nextToken ( ) ) ; } else if ( label . equalsIgnoreCase ( XDEF ) ) { int xSize = Integer . valueOf ( st . nextToken ( ) ) ; String xMapping = st . nextToken ( ) ; xDim = new GradsDimension ( label , xSize , xMapping ) ; curDim = xDim ; dimList . add ( xDim ) ; } else if ( label . equalsIgnoreCase ( YDEF ) ) { int ySize = Integer . valueOf ( st . nextToken ( ) ) ; String yMapping = st . nextToken ( ) ; yDim = new GradsDimension ( label , ySize , yMapping ) ; curDim = yDim ; dimList . add ( yDim ) ; } else if ( label . equalsIgnoreCase ( ZDEF ) ) { int zSize = Integer . valueOf ( st . nextToken ( ) ) ; String zMapping = st . nextToken ( ) ; zDim = new GradsDimension ( label , zSize , zMapping ) ; curDim = zDim ; dimList . add ( zDim ) ; } else if ( label . equalsIgnoreCase ( TDEF ) ) { int tSize = Integer . valueOf ( st . nextToken ( ) ) ; // we can read the following directly\r // since tdef never uses \"levels\"\r String tMapping = st . nextToken ( ) ; tDim = new GradsTimeDimension ( label , tSize , tMapping ) ; curDim = tDim ; dimList . add ( tDim ) ; } else if ( label . equalsIgnoreCase ( EDEF ) ) { int eSize = Integer . valueOf ( st . nextToken ( ) ) ; // Check if EDEF entry is the short or extended version\r if ( st . nextToken ( ) . equalsIgnoreCase ( GradsEnsembleDimension . NAMES ) ) { inEnsSection = false ; String eMapping = GradsEnsembleDimension . NAMES ; eDim = new GradsEnsembleDimension ( label , eSize , eMapping ) ; curDim = eDim ; dimList . add ( curDim ) ; } else { // TODO: handle list of ensembles\r curDim = null ; inEnsSection = true ; } } else if ( label . equalsIgnoreCase ( PDEF ) ) { curDim = null ; hasProjection = true ; } else if ( label . equalsIgnoreCase ( VARS ) ) { curDim = null ; inVarSection = true ; } else if ( label . equalsIgnoreCase ( DTYPE ) ) { curDim = null ; dataType = st . nextToken ( ) ; } else if ( label . equalsIgnoreCase ( TITLE ) ) { curDim = null ; title = original . substring ( original . indexOf ( \" \" ) ) . trim ( ) ; } else if ( curDim != null ) { curDim . addLevel ( label ) ; } // get the rest of the tokens\r if ( curDim != null ) { while ( st . hasMoreTokens ( ) ) { curDim . addLevel ( st . nextToken ( ) ) ; } } } } // end parsing loop\r //System.out.println(\"Time to parse file = \"\r //                   + (System.currentTimeMillis() - start2));\r // update the units for the zDimension if they are specified as\r // an attribute\r if ( zDim != null ) { for ( GradsAttribute attr : attrList ) { if ( attr . getVariable ( ) . equalsIgnoreCase ( ZDEF ) && attr . getType ( ) . equalsIgnoreCase ( GradsAttribute . STRING ) && attr . getName ( ) . equalsIgnoreCase ( \"units\" ) ) { zDim . setUnit ( attr . getValue ( ) ) ; break ; } } } } catch ( IOException ioe ) { log . error ( \"Error parsing metadata for \" + ddFile ) ; throw new IOException ( \"error parsing metadata for \" + ddFile ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swap the byte order from the system default [CODESPLIT] private void swapByteOrder ( ) { // NB: we are setting bigEndian to be opposite the system arch\r String arch = System . getProperty ( \"os.arch\" ) ; if ( arch . equals ( \"x86\" ) || // Windows, Linux\r arch . equals ( \"arm\" ) || // Window CE\r arch . equals ( \"x86_64\" ) || // Windows64, Mac OS-X\r arch . equals ( \"amd64\" ) || // Linux64?\r arch . equals ( \"alpha\" ) ) { // Utrix, VAX, DECOS\r bigEndian = true ; } else { bigEndian = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the number of timesteps per file and the starting offset [CODESPLIT] public int [ ] getTimeStepsPerFile ( String filename ) { if ( chsubs != null ) { for ( Chsub ch : chsubs ) { if ( filename . contains ( ch . subString ) ) { return new int [ ] { ch . numTimes , ch . startTimeIndex } ; } } } return new int [ ] { timeStepsPerFile , 0 } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the file name for the particular time and ensemble index [CODESPLIT] public String getFileName ( int eIndex , int tIndex ) { String dataFilePath = dataFile ; if ( ( getTemplateType ( ) == ENS_TEMPLATE ) || ( getTemplateType ( ) == ENS_TIME_TEMPLATE ) ) { dataFilePath = getEnsembleDimension ( ) . replaceFileTemplate ( dataFilePath , eIndex ) ; } dataFilePath = getTimeDimension ( ) . replaceFileTemplate ( dataFilePath , tIndex ) ; if ( ( chsubs != null ) && ( dataFilePath . contains ( CHSUB_TEMPLATE_ID ) ) ) { for ( Chsub ch : chsubs ) { if ( ( tIndex >= ch . startTimeIndex ) && ( tIndex <= ch . endTimeIndex ) ) { dataFilePath = dataFilePath . replace ( CHSUB_TEMPLATE_ID , ch . subString ) ; break ; } } } return getFullPath ( dataFilePath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of filenames [CODESPLIT] private List < String > getFileNames ( ) throws IOException { if ( fileNames == null ) { fileNames = new ArrayList <> ( ) ; timeStepsPerFile = tDim . getSize ( ) ; if ( ! isTemplate ( ) ) { // single file\r fileNames . add ( getFullPath ( getDataFile ( ) ) ) ; } else { // figure out template type\r long start = System . currentTimeMillis ( ) ; List < String > fileSet = new ArrayList <> ( ) ; String template = getDataFile ( ) ; if ( GradsTimeDimension . hasTimeTemplate ( template ) ) { if ( template . contains ( GradsEnsembleDimension . ENS_TEMPLATE_ID ) ) { templateType = ENS_TIME_TEMPLATE ; } else { templateType = TIME_TEMPLATE ; } } else { // not time - either ens or chsub\r if ( template . contains ( GradsEnsembleDimension . ENS_TEMPLATE_ID ) ) { templateType = ENS_TEMPLATE ; } else { templateType = TIME_TEMPLATE ; } } if ( templateType == ENS_TEMPLATE ) { for ( int e = 0 ; e < eDim . getSize ( ) ; e ++ ) { fileSet . add ( getFullPath ( eDim . replaceFileTemplate ( template , e ) ) ) ; } } else if ( ( templateType == TIME_TEMPLATE ) || ( templateType == ENS_TIME_TEMPLATE ) ) { int numens = ( templateType == TIME_TEMPLATE ) ? 1 : eDim . getSize ( ) ; for ( int t = 0 ; t < tDim . getSize ( ) ; t ++ ) { for ( int e = 0 ; e < numens ; e ++ ) { String file = getFileName ( e , t ) ; if ( ! fileSet . contains ( file ) ) { fileSet . add ( file ) ; } } } // this'll be a bogus number if chsub was used\r timeStepsPerFile = tDim . getSize ( ) / ( fileSet . size ( ) / numens ) ; } //System.out.println(\"Time to generate file list = \"\r //                   + (System.currentTimeMillis() - start));\r fileNames . addAll ( fileSet ) ; } //long start2 = System.currentTimeMillis();\r // now make sure they exist\r for ( String file : fileNames ) { File f = new File ( file ) ; if ( ! f . exists ( ) ) { log . error ( \"File: \" + f + \" does not exist\" ) ; throw new IOException ( \"File: \" + f + \" does not exist\" ) ; } } //System.out.println(\"Time to check file list = \"\r //                   + (System.currentTimeMillis() - start2));\r } return fileNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the path to the Data Descriptor File [CODESPLIT] private String getDDFPath ( ) { if ( pathToDDF == null ) { int lastSlash = ddFile . lastIndexOf ( \"/\" ) ; if ( lastSlash < 0 ) { lastSlash = ddFile . lastIndexOf ( File . separator ) ; } pathToDDF = ( lastSlash < 0 ) ? \"\" : ddFile . substring ( 0 , lastSlash + 1 ) ; } return pathToDDF ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the full path for a given filename [CODESPLIT] private String getFullPath ( String filename ) { String file ; String ddfPath = getDDFPath ( ) ; if ( filename . startsWith ( \"^\" ) ) { file = filename . replace ( \"^\" , \"\" ) ; file = ddfPath + file ; } else { File f = new File ( filename ) ; if ( ! f . isAbsolute ( ) ) { file = ddfPath + filename ; } else { file = filename ; } } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Chsub [CODESPLIT] private void addChsub ( Chsub sub ) { if ( chsubs == null ) { chsubs = new ArrayList <> ( ) ; } chsubs . add ( sub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public void writeDataAll ( DataOutputStream stream ) throws IOException { for ( Vinfo vinfo : vinfoList ) { if ( ! vinfo . isRecord ) { Variable v = vinfo . v ; assert filePos == vinfo . offset ; if ( debugPos ) System . out . println ( \" writing at \" + filePos + \" should be \" + vinfo . offset + \" \" + v . getFullName ( ) ) ; int nbytes = writeDataFast ( v , stream , v . read ( ) ) ; filePos += nbytes ; filePos += pad ( stream , nbytes , ( byte ) 0 ) ; } } // see if it has a record dimension we can use // see if it has a record dimension we can use boolean useRecordDimension = ncfile . hasUnlimitedDimension ( ) ; if ( useRecordDimension ) { ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; } // write record data if ( useRecordDimension ) { boolean first = true ; int nrec = 0 ; Structure recordVar = ( Structure ) ncfile . findVariable ( \"record\" ) ; try ( StructureDataIterator ii = recordVar . getStructureIterator ( ) ) { while ( ii . hasNext ( ) ) { StructureData sdata = ii . next ( ) ; int count = 0 ; for ( Vinfo vinfo : vinfoList ) { if ( vinfo . isRecord ) { Variable v = vinfo . v ; int nbytes = writeDataFast ( v , stream , sdata . getArray ( v . getShortName ( ) ) ) ; count += nbytes ; count += pad ( stream , nbytes , ( byte ) 0 ) ; if ( first && debugWriteData ) System . out . println ( v . getShortName ( ) + \" wrote \" + count + \" bytes\" ) ; } } if ( first && debugWriteData ) { System . out . println ( \"wrote \" + count + \" bytes\" ) ; first = false ; } nrec ++ ; } } if ( debugWriteData ) System . out . println ( \"wrote \" + nrec + \" records\" ) ; stream . flush ( ) ; // remove the record structure this is rather fishy, perhaps better to leave it ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_REMOVE_RECORD_STRUCTURE ) ; ncfile . finish ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////// [CODESPLIT] private long writeData ( Variable v , DataOutputStream stream , Array values ) throws java . io . IOException { DataType dataType = v . getDataType ( ) ; IndexIterator ii = values . getIndexIterator ( ) ; if ( dataType == DataType . BYTE ) { while ( ii . hasNext ( ) ) stream . write ( ii . getByteNext ( ) ) ; return values . getSize ( ) ; } else if ( dataType == DataType . CHAR ) { while ( ii . hasNext ( ) ) stream . write ( ii . getByteNext ( ) ) ; return values . getSize ( ) ; } else if ( dataType == DataType . SHORT ) { while ( ii . hasNext ( ) ) stream . writeShort ( ii . getShortNext ( ) ) ; return 2 * values . getSize ( ) ; } else if ( dataType == DataType . INT ) { while ( ii . hasNext ( ) ) stream . writeInt ( ii . getIntNext ( ) ) ; return 4 * values . getSize ( ) ; } else if ( dataType == DataType . FLOAT ) { while ( ii . hasNext ( ) ) stream . writeFloat ( ii . getFloatNext ( ) ) ; return 4 * values . getSize ( ) ; } else if ( dataType == DataType . DOUBLE ) { while ( ii . hasNext ( ) ) stream . writeDouble ( ii . getDoubleNext ( ) ) ; return 8 * values . getSize ( ) ; } throw new IllegalStateException ( \"dataType= \" + dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the offset in units of timeUnit from the given reference date? [CODESPLIT] public TimeCoordIntvValue convertReferenceDate ( CalendarDate refDate , CalendarPeriod timeUnit ) { if ( timeUnit == null ) { throw new IllegalArgumentException ( \"null time unit\" ) ; } int startOffset = timeUnit . getOffset ( refDate , start ) ; // LOOK wrong - not dealing with value ?? int endOffset = timeUnit . getOffset ( refDate , end ) ; return new TimeCoordIntvValue ( startOffset , endOffset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * create new ArrayBoolean with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayBoolean factory ( Index index , boolean [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayBoolean . D0 ( index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayBoolean . D1 ( index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayBoolean . D2 ( index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayBoolean . D3 ( index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayBoolean . D4 ( index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayBoolean . D5 ( index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayBoolean . D6 ( index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayBoolean . D7 ( index , storage ) ; } else { return new ArrayBoolean ( index , storage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { boolean [ ] ja = ( boolean [ ] ) javaArray ; for ( boolean aJa : ja ) iter . setBooleanNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check if this file is a nids / tdwr file [CODESPLIT] public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) { try { long t = raf . length ( ) ; if ( t == 0 ) { throw new IOException ( \"zero length file \" ) ; } } catch ( IOException e ) { return ( false ) ; } try { int p = this . readWMO ( raf ) ; if ( p == 0 ) return false ; // not unidata radar mosiac gini file\r } catch ( IOException e ) { return ( false ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read the header of input file and parsing the WMO part [CODESPLIT] int readWMO ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { int pos = 0 ; //long     actualSize = 0;\r raf . seek ( pos ) ; int readLen = 35 ; // Read in the contents of the NEXRAD Level III product head\r byte [ ] b = new byte [ readLen ] ; int rc = raf . read ( b ) ; if ( rc != readLen ) { // out.println(\" error reading nids product header\");\r return 0 ; } // new check\r int iarr2_1 = bytesToInt ( b [ 0 ] , b [ 1 ] , false ) ; int iarr2_16 = bytesToInt ( b [ 30 ] , b [ 31 ] , false ) ; int iarr2_10 = bytesToInt ( b [ 18 ] , b [ 19 ] , false ) ; int iarr2_7 = bytesToInt ( b [ 12 ] , b [ 13 ] , false ) ; if ( ( iarr2_1 == iarr2_16 ) && ( ( iarr2_1 >= 16 ) && ( iarr2_1 <= 299 ) ) && ( iarr2_10 == - 1 ) && ( iarr2_7 < 10000 ) ) { noHeader = true ; return 1 ; } //Get product message header into a string for processing\r String pib = new String ( b , CDM . utf8Charset ) ; if ( pib . indexOf ( \"SDUS\" ) != - 1 ) { noHeader = false ; return 1 ; } else if ( raf . getLocation ( ) . indexOf ( \".nids\" ) != - 1 ) { noHeader = true ; return 1 ; // } else if(checkMsgHeader(raf) == 1) {\r //    noHeader = true;\r //     return 1;\r } else return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read the compressed data [CODESPLIT] public byte [ ] getUncompData ( int offset , int len ) { if ( len == 0 ) len = uncompdata . length - offset ; byte [ ] data = new byte [ len ] ; System . arraycopy ( uncompdata , offset , data , 0 , len ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read and parse the header of the nids / tdwr file [CODESPLIT] void read ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile ) throws IOException { int hedsiz ; /* NEXRAD header size            */ int rc ; /* function return status        */ int hoff = 0 ; int type ; int zlibed ; boolean isZ = false ; int encrypt ; long actualSize ; int readLen ; readWMO ( raf ) ; this . ncfile = ncfile ; actualSize = raf . length ( ) ; int pos = 0 ; raf . seek ( pos ) ; // Read in the whole contents of the NEXRAD Level III product since\r // some product require to go through the whole file to build the  struct of file.\r readLen = ( int ) actualSize ; byte [ ] b = new byte [ readLen ] ; rc = raf . read ( b ) ; if ( rc != readLen ) { log . warn ( \" error reading nids product header \" + raf . getLocation ( ) ) ; } if ( ! noHeader ) { //Get product message header into a string for processing\r String pib = new String ( b , 0 , 100 , CDM . utf8Charset ) ; type = 0 ; pos = pib . indexOf ( \"\\r\\r\\n\" ) ; while ( pos != - 1 ) { hoff = pos + 3 ; type ++ ; pos = pib . indexOf ( \"\\r\\r\\n\" , pos + 1 ) ; } raf . seek ( hoff ) ; // Test the next two bytes to see if the image portion looks like\r // it is zlib-compressed.\r byte [ ] b2 = new byte [ 2 ] ; // byte[] b4 = new byte[4];\r System . arraycopy ( b , hoff , b2 , 0 , 2 ) ; zlibed = isZlibHed ( b2 ) ; if ( zlibed == 0 ) { encrypt = IsEncrypt ( b2 ) ; if ( encrypt == 1 ) { log . error ( \"error reading encryted product \" + raf . getLocation ( ) ) ; throw new IOException ( \"unable to handle the product with encrypt code \" + encrypt ) ; } } // process product description for station ID\r byte [ ] b3 = new byte [ 3 ] ; switch ( type ) { case 0 : log . warn ( \"ReadNexrInfo:: Unable to seek to ID \" + raf . getLocation ( ) ) ; break ; case 1 : case 2 : case 3 : case 4 : System . arraycopy ( b , hoff - 6 , b3 , 0 , 3 ) ; stationId = new String ( b3 , CDM . utf8Charset ) ; try { NexradStationDB . init ( ) ; // make sure database is initialized\r NexradStationDB . Station station = NexradStationDB . get ( \"K\" + stationId ) ; if ( station != null ) { stationName = station . name ; } } catch ( IOException ioe ) { log . error ( \"NexradStationDB.init \" + raf . getLocation ( ) , ioe ) ; } break ; default : break ; } if ( zlibed == 1 ) { isZ = true ; uncompdata = GetZlibedNexr ( b , readLen , hoff ) ; //uncompdata = Nidsiosp.readCompData(hoff, 160) ;\r if ( uncompdata == null ) { log . warn ( \"ReadNexrInfo: error uncompressing image \" + raf . getLocation ( ) ) ; uncompdata = new byte [ b . length - hoff ] ; System . arraycopy ( b , hoff , uncompdata , 0 , b . length - hoff ) ; } } else { uncompdata = new byte [ b . length - hoff ] ; System . arraycopy ( b , hoff , uncompdata , 0 , b . length - hoff ) ; } } else { uncompdata = new byte [ b . length ] ; System . arraycopy ( b , 0 , uncompdata , 0 , b . length ) ; // stationId  = \"YYY\";\r } byte [ ] b2 = new byte [ 2 ] ; ByteBuffer bos = ByteBuffer . wrap ( uncompdata ) ; rc = read_msghead ( bos , 0 ) ; hedsiz = 18 ; Pinfo pinfo = read_proddesc ( bos , hedsiz ) ; hedsiz += 102 ; // Set product-dependent information\r int prod_type = code_typelookup ( pinfo . pcode ) ; setProductInfo ( prod_type , pinfo ) ; //int windb = 0;\r int pcode1Number = 0 ; int pcode2Number = 0 ; int pcode8Number = 0 ; int pcode4Number = 0 ; int pcode5Number = 0 ; int pcode10Number = 0 ; int pcode6Number = 0 ; int pcode25Number = 0 ; int pcode12Number = 0 ; int pcode13Number = 0 ; int pcode14Number = 0 ; int pcode15Number = 0 ; int pcode16Number = 0 ; int pcode19Number = 0 ; int pcode20Number = 0 ; int pkcode1Doff [ ] = null ; int pkcode2Doff [ ] = null ; int pkcode8Doff [ ] = null ; int pkcode1Size [ ] = null ; int pkcode2Size [ ] = null ; int pkcode8Size [ ] = null ; int pkcode4Doff [ ] = null ; int pkcode5Doff [ ] = null ; int pkcode10Doff [ ] = null ; int pkcode10Dlen [ ] = null ; int pkcode6Doff [ ] = null ; int pkcode6Dlen [ ] = null ; int pkcode25Doff [ ] = null ; int pkcode12Doff [ ] = null ; int pkcode13Doff [ ] = null ; int pkcode14Doff [ ] = null ; int pkcode12Dlen [ ] = null ; int pkcode13Dlen [ ] = null ; int pkcode14Dlen [ ] = null ; int pkcode15Dlen [ ] = null ; int pkcode15Doff [ ] = null ; int pkcode16Dlen [ ] = null ; int pkcode16Doff [ ] = null ; int pkcode19Dlen [ ] = null ; int pkcode19Doff [ ] = null ; int pkcode20Dlen [ ] = null ; int pkcode20Doff [ ] = null ; // Get product symbology header (needed to get image shape)\r ifloop : if ( pinfo . offsetToSymbologyBlock != 0 ) { // Symbology header\r if ( pinfo . p8 == 1 ) { // TDWR data and the symbology is compressed\r int size = shortsToInt ( pinfo . p9 , pinfo . p10 , false ) ; uncompdata = uncompressed ( bos , hedsiz , size ) ; bos = ByteBuffer . wrap ( uncompdata ) ; } Sinfo sinfo = read_dividlen ( bos , hedsiz ) ; if ( rc == 0 || pinfo . divider != - 1 ) { log . warn ( \"error in product symbology header \" + raf . getLocation ( ) ) ; } if ( sinfo . id != 1 ) { if ( pinfo . pcode == 82 ) { read_SATab ( bos , hedsiz ) ; } break ifloop ; } hedsiz += 10 ; // Symbology layer\r int klayer = pinfo . offsetToSymbologyBlock * 2 + 10 ; for ( int i = 0 ; i < sinfo . nlayers ; i ++ ) { hedsiz = klayer ; bos . position ( hedsiz ) ; short Divlen_divider = bos . getShort ( ) ; hedsiz += 2 ; int Divlen_length = bos . getInt ( ) ; hedsiz += 4 ; if ( Divlen_divider != - 1 ) { log . warn ( \"error reading length divider \" + raf . getLocation ( ) ) ; } int icount = 0 ; int plen ; while ( icount < Divlen_length ) { int boff = klayer + icount + 6 ; bos . position ( boff ) ; bos . get ( b2 ) ; int pkcode = getUInt ( b2 , 2 ) ; hedsiz += 2 ; boff += 2 ; switch ( pkcode ) { case 18 : //  DPA\r case 17 : //   (pkcode == 0x11)   Digital Precipitation Array\r hedsiz += 8 ; plen = pcode_DPA ( bos , boff , hoff , hedsiz , isZ , i , pkcode ) ; break ; case 10 : //     (pkcode == 0xA)\r if ( pkcode10Doff == null ) { pkcode10Doff = new int [ 250 ] ; pkcode10Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; // for unlinked Vector Packet the length of data block\r pkcode10Doff [ pcode10Number ] = boff + 2 ; pkcode10Dlen [ pcode10Number ] = ( plen - 2 ) / 8 ; pcode10Number ++ ; //pcode_10n7( bos, boff, hoff, isZ, pkcode );\r break ; case 1 : if ( pkcode1Doff == null ) { pkcode1Doff = new int [ 250 ] ; pkcode1Size = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode1Doff [ pcode1Number ] = boff + 2 ; pkcode1Size [ pcode1Number ] = plen - 4 ; pcode1Number ++ ; break ; case 2 : if ( pkcode2Doff == null ) { pkcode2Doff = new int [ 250 ] ; pkcode2Size = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode2Doff [ pcode2Number ] = boff + 2 ; pkcode2Size [ pcode2Number ] = plen - 4 ; pcode2Number ++ ; break ; case 8 : //text string\r if ( pkcode8Doff == null ) { pkcode8Doff = new int [ 550 ] ; pkcode8Size = new int [ 550 ] ; } plen = bos . getShort ( ) ; pkcode8Doff [ pcode8Number ] = boff + 2 ; pkcode8Size [ pcode8Number ] = plen - 6 ; pcode8Number ++ ; break ; case 3 : case 11 : case 25 : if ( pkcode25Doff == null ) { pkcode25Doff = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode25Doff [ pcode25Number ] = boff + 2 ; pcode25Number ++ ; break ; case 12 : if ( pkcode12Doff == null ) { pkcode12Doff = new int [ 250 ] ; pkcode12Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode12Doff [ pcode12Number ] = boff + 2 ; pkcode12Dlen [ pcode12Number ] = plen / 4 ; pcode12Number ++ ; break ; case 13 : if ( pkcode13Doff == null ) { pkcode13Doff = new int [ 250 ] ; pkcode13Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode13Doff [ pcode13Number ] = boff + 2 ; pkcode13Dlen [ pcode13Number ] = plen / 4 ; pcode13Number ++ ; break ; case 14 : if ( pkcode14Doff == null ) { pkcode14Doff = new int [ 250 ] ; pkcode14Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode14Doff [ pcode14Number ] = boff + 2 ; pkcode14Dlen [ pcode14Number ] = plen / 4 ; pcode14Number ++ ; break ; case 15 : if ( pkcode15Doff == null ) { pkcode15Doff = new int [ 250 ] ; pkcode15Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode15Doff [ pcode15Number ] = boff + 2 ; pkcode15Dlen [ pcode15Number ] = plen / 6 ; pcode15Number ++ ; break ; case 166 : if ( pkcode16Doff == null ) { pkcode16Doff = new int [ 250 ] ; pkcode16Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode16Doff [ pcode16Number ] = boff + 2 ; pkcode16Dlen [ pcode16Number ] = plen / 4 ; pcode16Number ++ ; break ; case 19 : if ( pkcode19Doff == null ) { pkcode19Doff = new int [ 250 ] ; pkcode19Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode19Doff [ pcode19Number ] = boff + 2 ; pkcode19Dlen [ pcode19Number ] = plen / 10 ; pcode19Number ++ ; break ; case 20 : if ( pkcode20Doff == null ) { pkcode20Doff = new int [ 250 ] ; pkcode20Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; pkcode20Doff [ pcode20Number ] = boff + 2 ; pkcode20Dlen [ pcode20Number ] = plen / 8 ; pcode20Number ++ ; break ; case 4 : // wind barb\r if ( pkcode4Doff == null ) { pkcode4Doff = new int [ 1000 ] ; } plen = bos . getShort ( ) ; pkcode4Doff [ pcode4Number ] = boff + 2 ; pcode4Number ++ ; break ; case 5 : //   Vector Arrow Data\r if ( pkcode5Doff == null ) { pkcode5Doff = new int [ 1000 ] ; } plen = bos . getShort ( ) ; pkcode5Doff [ pcode5Number ] = boff + 2 ; pcode5Number ++ ; break ; case 43 : plen = bos . getShort ( ) ; break ; case 23 : case 24 : plen = bos . getShort ( ) ; int poff = 2 ; while ( poff < plen ) { int pcode = bos . getShort ( ) ; int len = bos . getShort ( ) ; switch ( pcode ) { case 2 : if ( pkcode2Doff == null ) { pkcode2Doff = new int [ 250 ] ; pkcode2Size = new int [ 250 ] ; } pkcode2Doff [ pcode2Number ] = boff + poff + 4 ; pkcode2Size [ pcode2Number ] = len - 4 ; pcode2Number ++ ; break ; case 6 : if ( pkcode6Doff == null ) { pkcode6Doff = new int [ 250 ] ; pkcode6Dlen = new int [ 250 ] ; } pkcode6Doff [ pcode6Number ] = boff + poff + 4 ; pkcode6Dlen [ pcode6Number ] = ( len - 6 ) / 4 ; pcode6Number ++ ; break ; case 25 : if ( pkcode25Doff == null ) { pkcode25Doff = new int [ 250 ] ; } pkcode25Doff [ pcode25Number ] = boff + poff + 4 ; pcode25Number ++ ; break ; default : log . error ( \"error reading pcode= \" + pcode + \" \" + raf . getLocation ( ) ) ; throw new IOException ( \"error reading pcode, \" + \"unable to handle the packet with code \" + pcode ) ; } poff = poff + len + 4 ; // Need to advance the file's position\r bos . position ( bos . position ( ) + len ) ; } break ; case 0x0802 : log . warn ( \"Encountered unhandled packet code 0x0802 (contour color) -- reading past.\" ) ; Divlen_divider = bos . getShort ( ) ; // Color marker\r if ( Divlen_divider != 0x0002 ) { log . warn ( \"Missing color marker!\" ) ; } plen = 2 ; break ; case 0x0E03 : log . warn ( \"Encountered unhandled packet code 0x0E03 (linked contours) -- reading past.\" ) ; Divlen_divider = bos . getShort ( ) ; // Start marker\r if ( Divlen_divider != 0x8000 ) { log . warn ( \"Missing start marker!\" ) ; } // Read past start x, y for now\r bos . getShort ( ) ; bos . getShort ( ) ; plen = 6 + bos . getShort ( ) ; break ; default : if ( pkcode == 0xAF1F || pkcode == 16 ) { /* radial image                  */ hedsiz += pcode_radial ( bos , hoff , hedsiz , isZ , uncompdata , pinfo . threshold ) ; //myInfo = new Vinfo (cname, numX, numX0, numY, numY0, hoff, hedsiz, isR, isZ);\r plen = Divlen_length ; break ; } else if ( pkcode == 28 ) { /* radial image                  */ hedsiz += pcode_generic ( bos , hoff , hedsiz , isZ , uncompdata , pinfo . threshold ) ; //myInfo = new Vinfo (cname, numX, numX0, numY, numY0, hoff, hedsiz, isR, isZ);\r plen = Divlen_length ; break ; } else if ( pkcode == 0xBA0F || pkcode == 0xBA07 ) { /* raster image                  */ hedsiz += pcode_raster ( bos , ( short ) pkcode , hoff , hedsiz , isZ , uncompdata ) ; //myInfo = new Vinfo (cname, numX, numX0, numY, numY0, hoff, hedsiz, isR, isZ);\r plen = Divlen_length ; break ; } else { log . error ( \"error reading pkcode equals \" + pkcode + \" \" + raf . getLocation ( ) ) ; throw new IOException ( \"error reading pkcode, unable to handle the product with code \" + pkcode ) ; } // size and beginning data position in file\r } //end of switch\r icount = icount + plen + 4 ; } klayer = klayer + Divlen_length + 6 ; } //int curDoff = hedsiz;\r if ( pkcode8Doff != null ) { pcode_128 ( pkcode8Doff , pkcode8Size , 8 , hoff , pcode8Number , \"textStruct_code8\" , \"\" , isZ ) ; } if ( pkcode1Doff != null ) { pcode_128 ( pkcode1Doff , pkcode1Size , 1 , hoff , pcode1Number , \"textStruct_code1\" , \"\" , isZ ) ; } if ( pkcode2Doff != null ) { pcode_128 ( pkcode2Doff , pkcode2Size , 2 , hoff , pcode2Number , \"textStruct_code2\" , \"\" , isZ ) ; } if ( pkcode10Doff != null ) { pcode_10n9 ( pkcode10Doff , pkcode10Dlen , hoff , pcode10Number , isZ ) ; } if ( pkcode4Doff != null ) { pcode_4 ( pkcode4Doff , hoff , pcode4Number , isZ ) ; } if ( pkcode5Doff != null ) { pcode_5 ( pkcode5Doff , hoff , pcode5Number , isZ ) ; } if ( pkcode6Doff != null ) { pcode_6n7 ( pkcode6Doff , pkcode6Dlen , hoff , pcode6Number , isZ , \"linkedVector\" , 6 ) ; } if ( pkcode25Doff != null ) { pcode_25 ( pkcode25Doff , hoff , pcode25Number , isZ ) ; } if ( pkcode12Doff != null ) { pcode_12n13n14 ( pkcode12Doff , pkcode12Dlen , hoff , pcode12Number , isZ , \"TVS\" , 12 ) ; } if ( pkcode13Doff != null ) { pcode_12n13n14 ( pkcode13Doff , pkcode13Dlen , hoff , pcode13Number , isZ , \"hailPositive\" , 13 ) ; } if ( pkcode14Doff != null ) { pcode_12n13n14 ( pkcode14Doff , pkcode14Dlen , hoff , pcode14Number , isZ , \"hailProbable\" , 14 ) ; } if ( pkcode19Doff != null ) { pcode_12n13n14 ( pkcode19Doff , pkcode19Dlen , hoff , pcode19Number , isZ , \"hailIndex\" , 19 ) ; } if ( pkcode20Doff != null ) { pcode_12n13n14 ( pkcode20Doff , pkcode20Dlen , hoff , pcode20Number , isZ , \"mesocyclone\" , 20 ) ; } } else { log . debug ( \"GetNexrDirs:: no product symbology block found (no image data) \" + raf . getLocation ( ) ) ; } if ( pinfo . offsetToTabularBlock != 0 ) { int tlayer = pinfo . offsetToTabularBlock * 2 ; bos . position ( tlayer ) ; if ( bos . hasRemaining ( ) ) { short tab_divider = bos . getShort ( ) ; if ( tab_divider != - 1 ) { log . error ( \"Block divider not found \" + raf . getLocation ( ) ) ; throw new IOException ( \"error reading graphic alphanumeric block\" ) ; } short tab_bid = bos . getShort ( ) ; int tblen = bos . getInt ( ) ; bos . position ( tlayer + 116 ) ; int inc = bos . getInt ( ) ; bos . position ( tlayer + 128 ) ; // skip the second header and prod description\r tab_divider = bos . getShort ( ) ; if ( tab_divider != - 1 ) { log . error ( \"tab divider not found \" + raf . getLocation ( ) ) ; throw new IOException ( \"error reading graphic alphanumeric block\" ) ; } int npage = bos . getShort ( ) ; int ppos = bos . position ( ) ; ArrayList dims = new ArrayList ( ) ; Dimension tbDim = new Dimension ( \"pageNumber\" , npage ) ; ncfile . addDimension ( null , tbDim ) ; dims . add ( tbDim ) ; Variable ppage = new Variable ( ncfile , null , null , \"TabMessagePage\" ) ; ppage . setDimensions ( dims ) ; ppage . setDataType ( DataType . STRING ) ; ppage . addAttribute ( new Attribute ( CDM . LONG_NAME , \"Graphic Product Message\" ) ) ; ncfile . addVariable ( null , ppage ) ; ppage . setSPobject ( new Vinfo ( npage , 0 , tblen , 0 , hoff , ppos , isR , isZ , null , null , tab_bid , 0 ) ) ; } } if ( pinfo . offsetToGraphicBlock != 0 ) { int gpkcode1Doff [ ] = null ; int gpkcode2Doff [ ] = null ; int gpkcode10Doff [ ] = null ; int gpkcode10Dlen [ ] = null ; int gpkcode8Doff [ ] = null ; int gpkcode1Size [ ] = null ; int gpkcode2Size [ ] = null ; int gpkcode8Size [ ] = null ; int gpcode1Number = 0 ; int gpcode10Number = 0 ; int gpcode8Number = 0 ; int gpcode2Number = 0 ; int tlayer = pinfo . offsetToGraphicBlock * 2 ; bos . position ( tlayer ) ; short graphic_divider = bos . getShort ( ) ; short graphic_bid = bos . getShort ( ) ; if ( graphic_divider != - 1 || graphic_bid != 2 ) { log . error ( \"error reading graphic alphanumeric block \" + raf . getLocation ( ) ) ; throw new IOException ( \"error reading graphic alphanumeric block\" ) ; } int blen = bos . getInt ( ) ; int clen = 0 ; int npage = bos . getShort ( ) ; int lpage ; int ipage = 0 ; int plen ; while ( ( clen < blen ) && ( ipage < npage ) ) { //  bos.position(ppos);\r int ppos = bos . position ( ) ; ipage = bos . getShort ( ) ; lpage = bos . getShort ( ) ; int icnt = 0 ; ppos = ppos + 4 ; while ( icnt < lpage ) { bos . position ( ppos + icnt ) ; int pkcode = bos . getShort ( ) ; if ( pkcode == 8 ) { if ( gpkcode8Doff == null ) { gpkcode8Doff = new int [ 550 ] ; gpkcode8Size = new int [ 550 ] ; } plen = bos . getShort ( ) ; gpkcode8Doff [ gpcode8Number ] = ppos + 4 + icnt ; gpkcode8Size [ gpcode8Number ] = plen - 6 ; icnt += plen + 4 ; gpcode8Number ++ ; } else if ( pkcode == 1 ) { if ( gpkcode1Doff == null ) { gpkcode1Doff = new int [ 550 ] ; gpkcode1Size = new int [ 550 ] ; } plen = bos . getShort ( ) ; gpkcode1Doff [ gpcode1Number ] = ppos + 4 + icnt ; gpkcode1Size [ gpcode1Number ] = plen - 4 ; icnt += plen + 4 ; gpcode1Number ++ ; } else if ( pkcode == 10 ) { if ( gpkcode10Doff == null ) { gpkcode10Doff = new int [ 250 ] ; gpkcode10Dlen = new int [ 250 ] ; } plen = bos . getShort ( ) ; // for unlinked Vector Packet the length of data block\r gpkcode10Doff [ gpcode10Number ] = ppos + 4 + icnt ; gpkcode10Dlen [ gpcode10Number ] = ( plen - 2 ) / 8 ; icnt += plen + 4 ; gpcode10Number ++ ; } else { plen = bos . getShort ( ) ; icnt += plen + 4 ; } //  else {\r //      out.println( \"error reading pkcode equals \" + pkcode);\r //      throw new IOException(\"error reading pkcode in graphic alpha num block \" + pkcode);\r //  }\r } ppos = ppos + lpage + 4 ; clen = clen + lpage + 4 ; } if ( gpkcode8Doff != null ) { pcode_128 ( gpkcode8Doff , gpkcode8Size , 8 , hoff , gpcode8Number , \"textStruct_code8g\" , \"g\" , isZ ) ; } if ( gpkcode2Doff != null ) { pcode_128 ( gpkcode2Doff , gpkcode2Size , 2 , hoff , gpcode8Number , \"textStruct_code2g\" , \"g\" , isZ ) ; } if ( gpkcode1Doff != null ) { pcode_128 ( gpkcode1Doff , gpkcode1Size , 1 , hoff , gpcode1Number , \"textStruct_code1g\" , \"g\" , isZ ) ; } if ( gpkcode10Doff != null ) { pcode_10n9 ( gpkcode10Doff , gpkcode10Dlen , hoff , gpcode10Number , isZ ) ; } /*\r\n         int ppos = bos.position();\r\n         ArrayList dims =  new ArrayList();\r\n         Dimension tbDim = new Dimension(\"pageNumber\", npage, true);\r\n         ncfile.addDimension( null, tbDim);\r\n         dims.add( tbDim);\r\n         Variable ppage = new Variable(ncfile, null, null, \"GraphicMessagePage\");\r\n         ppage.setDimensions(dims);\r\n         ppage.setDataType(DataType.STRING);\r\n         ppage.addAttribute( new Attribute(CDM.LONG_NAME, \"Graphic Product Message\"));\r\n         ncfile.addVariable(null, ppage);\r\n         ppage.setSPobject( new Vinfo (npage, 0, tblen, 0, hoff, ppos, isR, isZ, null, null, graphic_bid));\r\n           */ } // finish\r ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a dataset for special graphic symbol packet with code 12 13 and 14 [CODESPLIT] int pcode_12n13n14 ( int [ ] pos , int [ ] dlen , int hoff , int len , boolean isZ , String structName , int code ) { //int vlen = len;\r int vlen = 0 ; for ( int i = 0 ; i < len ; i ++ ) { vlen = vlen + dlen [ i ] ; } ArrayList dims = new ArrayList ( ) ; Dimension sDim = new Dimension ( \"graphicSymbolSize\" , vlen ) ; ncfile . addDimension ( null , sDim ) ; dims . add ( sDim ) ; Structure dist = new Structure ( ncfile , null , null , structName ) ; dist . setDimensions ( dims ) ; ncfile . addVariable ( null , dist ) ; dist . addAttribute ( new Attribute ( CDM . LONG_NAME , \"special graphic symbol for code \" + code ) ) ; Variable i0 = new Variable ( ncfile , null , dist , \"x_start\" ) ; i0 . setDimensions ( ( String ) null ) ; i0 . setDataType ( DataType . FLOAT ) ; i0 . addAttribute ( new Attribute ( CDM . UNITS , \"KM\" ) ) ; dist . addMemberVariable ( i0 ) ; Variable j0 = new Variable ( ncfile , null , dist , \"y_start\" ) ; j0 . setDimensions ( ( String ) null ) ; j0 . setDataType ( DataType . FLOAT ) ; j0 . addAttribute ( new Attribute ( CDM . UNITS , \"KM\" ) ) ; dist . addMemberVariable ( j0 ) ; int [ ] pos1 = new int [ len ] ; int [ ] dlen1 = new int [ len ] ; System . arraycopy ( dlen , 0 , dlen1 , 0 , len ) ; System . arraycopy ( pos , 0 , pos1 , 0 , len ) ; dist . setSPobject ( new Vinfo ( 0 , 0 , 0 , 0 , hoff , 0 , isR , isZ , pos1 , dlen1 , code , 0 ) ) ; return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a dataset for special symbol packet with code 25 [CODESPLIT] int pcode_25 ( int [ ] pos , int hoff , int len , boolean isZ ) { ArrayList dims = new ArrayList ( ) ; Dimension sDim = new Dimension ( \"circleSize\" , len ) ; ncfile . addDimension ( null , sDim ) ; dims . add ( sDim ) ; Structure dist = new Structure ( ncfile , null , null , \"circleStruct\" ) ; dist . setDimensions ( dims ) ; ncfile . addVariable ( null , dist ) ; dist . addAttribute ( new Attribute ( CDM . LONG_NAME , \"Circle Packet\" ) ) ; Variable ii0 = new Variable ( ncfile , null , dist , \"x_center\" ) ; ii0 . setDimensions ( ( String ) null ) ; ii0 . setDataType ( DataType . SHORT ) ; dist . addMemberVariable ( ii0 ) ; Variable ii1 = new Variable ( ncfile , null , dist , \"y_center\" ) ; ii1 . setDimensions ( ( String ) null ) ; ii1 . setDataType ( DataType . SHORT ) ; dist . addMemberVariable ( ii1 ) ; Variable jj0 = new Variable ( ncfile , null , dist , \"radius\" ) ; jj0 . setDimensions ( ( String ) null ) ; jj0 . setDataType ( DataType . SHORT ) ; dist . addMemberVariable ( jj0 ) ; int [ ] pos1 = new int [ len ] ; System . arraycopy ( pos , 0 , pos1 , 0 , len ) ; dist . setSPobject ( new Vinfo ( 0 , 0 , 0 , 0 , hoff , 0 , isR , isZ , pos1 , null , 25 , 0 ) ) ; return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check level III file header [CODESPLIT] int checkMsgHeader ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { int rc ; long actualSize ; int readLen ; actualSize = raf . length ( ) ; int pos = 0 ; raf . seek ( pos ) ; // Read in the whole contents of the NEXRAD Level III product since\r // some product require to go through the whole file to build the  struct of file.\r readLen = ( int ) actualSize ; byte [ ] b = new byte [ readLen ] ; rc = raf . read ( b ) ; if ( rc != readLen ) { log . warn ( \" error reading nids product header \" + raf . getLocation ( ) ) ; } ByteBuffer bos = ByteBuffer . wrap ( b ) ; return read_msghead ( bos , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a dataset for vector arrow data packet with code 5 [CODESPLIT] int pcode_5 ( int [ ] pos , int hoff , int len , boolean isZ ) { ArrayList dims = new ArrayList ( ) ; //int vlen =len;\r Dimension sDim = new Dimension ( \"windBarbSize\" , len ) ; ncfile . addDimension ( null , sDim ) ; dims . add ( sDim ) ; Structure dist = new Structure ( ncfile , null , null , \"vectorArrow\" ) ; dist . setDimensions ( dims ) ; ncfile . addVariable ( null , dist ) ; dist . addAttribute ( new Attribute ( CDM . LONG_NAME , \"Vector Arrow Data\" ) ) ; Variable i0 = new Variable ( ncfile , null , dist , \"x_start\" ) ; i0 . setDimensions ( ( String ) null ) ; i0 . setDataType ( DataType . SHORT ) ; i0 . addAttribute ( new Attribute ( CDM . UNITS , \"KM\" ) ) ; dist . addMemberVariable ( i0 ) ; Variable j0 = new Variable ( ncfile , null , dist , \"y_start\" ) ; j0 . setDimensions ( ( String ) null ) ; j0 . setDataType ( DataType . SHORT ) ; j0 . addAttribute ( new Attribute ( CDM . UNITS , \"KM\" ) ) ; dist . addMemberVariable ( j0 ) ; Variable direct = new Variable ( ncfile , null , dist , \"direction\" ) ; direct . setDimensions ( ( String ) null ) ; direct . setDataType ( DataType . SHORT ) ; direct . addAttribute ( new Attribute ( CDM . UNITS , \"degree\" ) ) ; dist . addMemberVariable ( direct ) ; Variable speed = new Variable ( ncfile , null , dist , \"arrowLength\" ) ; speed . setDimensions ( ( String ) null ) ; speed . setDataType ( DataType . SHORT ) ; speed . addAttribute ( new Attribute ( CDM . UNITS , \"pixels\" ) ) ; dist . addMemberVariable ( speed ) ; Variable speed1 = new Variable ( ncfile , null , dist , \"arrowHeadLength\" ) ; speed1 . setDimensions ( ( String ) null ) ; speed1 . setDataType ( DataType . SHORT ) ; speed1 . addAttribute ( new Attribute ( CDM . UNITS , \"pixels\" ) ) ; dist . addMemberVariable ( speed1 ) ; int [ ] pos1 = new int [ len ] ; System . arraycopy ( pos , 0 , pos1 , 0 , len ) ; dist . setSPobject ( new Vinfo ( 0 , 0 , 0 , 0 , hoff , 0 , isR , isZ , pos1 , null , 4 , 0 ) ) ; return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a dataset for text and special symbol packets with code 1 2 and 8 [CODESPLIT] int pcode_128 ( int [ ] pos , int [ ] size , int code , int hoff , int len , String structName , String abbre , boolean isZ ) { //int vlen = len;\r ArrayList dims = new ArrayList ( ) ; Dimension sDim = new Dimension ( \"textStringSize\" + abbre + code , len ) ; ncfile . addDimension ( null , sDim ) ; dims . add ( sDim ) ; Structure dist = new Structure ( ncfile , null , null , structName + abbre ) ; dist . setDimensions ( dims ) ; ncfile . addVariable ( null , dist ) ; dist . addAttribute ( new Attribute ( CDM . LONG_NAME , \"text and special symbol for code \" + code ) ) ; if ( code == 8 ) { Variable strVal = new Variable ( ncfile , null , dist , \"strValue\" ) ; strVal . setDimensions ( ( String ) null ) ; strVal . setDataType ( DataType . SHORT ) ; strVal . addAttribute ( new Attribute ( CDM . UNITS , \"\" ) ) ; dist . addMemberVariable ( strVal ) ; } Variable i0 = new Variable ( ncfile , null , dist , \"x_start\" ) ; i0 . setDimensions ( ( String ) null ) ; i0 . setDataType ( DataType . SHORT ) ; i0 . addAttribute ( new Attribute ( CDM . UNITS , \"KM\" ) ) ; dist . addMemberVariable ( i0 ) ; Variable j0 = new Variable ( ncfile , null , dist , \"y_start\" ) ; j0 . setDimensions ( ( String ) null ) ; j0 . setDataType ( DataType . SHORT ) ; j0 . addAttribute ( new Attribute ( CDM . UNITS , \"KM\" ) ) ; dist . addMemberVariable ( j0 ) ; Variable tstr = new Variable ( ncfile , null , dist , \"textString\" ) ; tstr . setDimensions ( ( String ) null ) ; tstr . setDataType ( DataType . STRING ) ; tstr . addAttribute ( new Attribute ( CDM . UNITS , \"\" ) ) ; dist . addMemberVariable ( tstr ) ; int [ ] pos1 = new int [ len ] ; System . arraycopy ( pos , 0 , pos1 , 0 , len ) ; dist . setSPobject ( new Vinfo ( 0 , 0 , 0 , 0 , hoff , 0 , isR , isZ , pos1 , size , code , 0 ) ) ; return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a dataset for linked vector packet and unlinked vector packet [CODESPLIT] int pcode_10n9 ( int [ ] pos , int [ ] dlen , int hoff , int len , boolean isZ ) { ArrayList dims = new ArrayList ( ) ; Variable v ; int vlen = 0 ; for ( int i = 0 ; i < len ; i ++ ) { vlen = vlen + dlen [ i ] ; } Dimension sDim = new Dimension ( \"unlinkedVectorSize\" , vlen ) ; ncfile . addDimension ( null , sDim ) ; dims . add ( sDim ) ; Structure dist = new Structure ( ncfile , null , null , \"unlinkedVectorStruct\" ) ; dist . setDimensions ( dims ) ; ncfile . addVariable ( null , dist ) ; dist . addAttribute ( new Attribute ( CDM . LONG_NAME , \"Unlinked Vector Packet\" ) ) ; v = new Variable ( ncfile , null , null , \"iValue\" ) ; v . setDataType ( DataType . SHORT ) ; v . setDimensions ( ( String ) null ) ; dist . addMemberVariable ( v ) ; Variable ii0 = new Variable ( ncfile , null , dist , \"x_start\" ) ; ii0 . setDimensions ( ( String ) null ) ; ii0 . setDataType ( DataType . SHORT ) ; dist . addMemberVariable ( ii0 ) ; Variable ii1 = new Variable ( ncfile , null , dist , \"y_start\" ) ; ii1 . setDimensions ( ( String ) null ) ; ii1 . setDataType ( DataType . SHORT ) ; dist . addMemberVariable ( ii1 ) ; Variable jj0 = new Variable ( ncfile , null , dist , \"x_end\" ) ; jj0 . setDimensions ( ( String ) null ) ; jj0 . setDataType ( DataType . SHORT ) ; dist . addMemberVariable ( jj0 ) ; Variable jj1 = new Variable ( ncfile , null , dist , \"y_end\" ) ; jj1 . setDimensions ( ( String ) null ) ; jj1 . setDataType ( DataType . SHORT ) ; dist . addMemberVariable ( jj1 ) ; int [ ] pos1 = new int [ len ] ; int [ ] dlen1 = new int [ len ] ; System . arraycopy ( pos , 0 , pos1 , 0 , len ) ; System . arraycopy ( dlen , 0 , dlen1 , 0 , len ) ; dist . setSPobject ( new Vinfo ( 0 , 0 , 0 , 0 , hoff , 0 , isR , isZ , pos1 , dlen1 , 10 , 0 ) ) ; return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a dataset for NIDS digital precipitation array [CODESPLIT] int pcode_DPA ( ByteBuffer bos , int pos , int hoff , int hedsiz , boolean isZ , int slayer , int code ) { byte [ ] b2 = new byte [ 2 ] ; int soff ; ArrayList dims = new ArrayList ( ) ; bos . position ( pos ) ; bos . get ( b2 , 0 , 2 ) ; // reserved\r bos . get ( b2 , 0 , 2 ) ; // reserved\r bos . get ( b2 , 0 , 2 ) ; short numBox = ( short ) getInt ( b2 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; short numRow = ( short ) getInt ( b2 , 2 ) ; soff = 8 ; numY0 = 0 ; numX0 = 0 ; numX = numBox ; numY = numRow ; if ( slayer == 0 ) { Dimension jDim = new Dimension ( \"y\" , numY ) ; Dimension iDim = new Dimension ( \"x\" , numX ) ; ncfile . addDimension ( null , iDim ) ; ncfile . addDimension ( null , jDim ) ; dims . add ( jDim ) ; dims . add ( iDim ) ; Variable v = new Variable ( ncfile , null , null , cname + \"_\" + slayer ) ; v . setDataType ( DataType . SHORT ) ; v . setDimensions ( dims ) ; ncfile . addVariable ( null , v ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , ctitle + \" at Symbology Layer \" + slayer ) ) ; v . setSPobject ( new Vinfo ( numX , numX0 , numY , numY0 , hoff , hedsiz , isR , isZ , null , null , code , 0 ) ) ; v . addAttribute ( new Attribute ( CDM . UNITS , cunit ) ) ; v . addAttribute ( new Attribute ( CDM . MISSING_VALUE , 255 ) ) ; } //else  if(slayer == 1) {\r //  ncfile.addDimension( null, iDim);\r //  ncfile.addDimension( null, jDim);\r //}\r for ( int row = 0 ; row < numRow ; row ++ ) { int runLen = bos . getShort ( ) ; byte [ ] rdata = new byte [ runLen ] ; bos . get ( rdata , 0 , runLen ) ; if ( runLen < 2 ) { return soff ; } else { soff += runLen + 2 ; } } //end of for loop\r if ( slayer == 0 ) { double ddx = code_reslookup ( pcode ) ; ncfile . addAttribute ( null , new Attribute ( \"cdm_data_type\" , FeatureType . GRID . toString ( ) ) ) ; // create coordinate variables\r Variable xaxis = new Variable ( ncfile , null , null , \"x\" ) ; xaxis . setDataType ( DataType . DOUBLE ) ; xaxis . setDimensions ( \"x\" ) ; xaxis . addAttribute ( new Attribute ( CDM . LONG_NAME , \"projection x coordinate\" ) ) ; xaxis . addAttribute ( new Attribute ( CDM . UNITS , \"km\" ) ) ; xaxis . addAttribute ( new Attribute ( _Coordinate . AxisType , \"GeoX\" ) ) ; double [ ] data1 = new double [ numX ] ; for ( int i = 0 ; i < numX ; i ++ ) data1 [ i ] = numX0 + i * ddx ; Array dataA = Array . factory ( DataType . DOUBLE , new int [ ] { numX } , data1 ) ; xaxis . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , xaxis ) ; Variable yaxis = new Variable ( ncfile , null , null , \"y\" ) ; yaxis . setDataType ( DataType . DOUBLE ) ; yaxis . setDimensions ( \"y\" ) ; yaxis . addAttribute ( new Attribute ( CDM . LONG_NAME , \"projection y coordinate\" ) ) ; yaxis . addAttribute ( new Attribute ( CDM . UNITS , \"km\" ) ) ; yaxis . addAttribute ( new Attribute ( _Coordinate . AxisType , \"GeoY\" ) ) ; data1 = new double [ numY ] ; for ( int i = 0 ; i < numY ; i ++ ) data1 [ i ] = numY0 + i * ddx ; dataA = Array . factory ( DataType . DOUBLE , new int [ ] { numY } , data1 ) ; yaxis . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , yaxis ) ; ProjectionImpl projection = new FlatEarth ( lat_min , lon_max ) ; //ProjectionImpl projection = new LambertConformal(latitude, longitude, latitude, latitude);\r // coordinate transform variable\r Variable ct = new Variable ( ncfile , null , null , projection . getClassName ( ) ) ; ct . setDataType ( DataType . CHAR ) ; ct . setDimensions ( \"\" ) ; List params = projection . getProjectionParameters ( ) ; for ( int i = 0 ; i < params . size ( ) ; i ++ ) { Parameter p = ( Parameter ) params . get ( i ) ; ct . addAttribute ( new Attribute ( p ) ) ; } ct . addAttribute ( new Attribute ( _Coordinate . TransformType , \"Projection\" ) ) ; ct . addAttribute ( new Attribute ( _Coordinate . Axes , \"x y\" ) ) ; // fake data\r dataA = Array . factory ( DataType . CHAR , new int [ ] { } ) ; dataA . setChar ( dataA . getIndex ( ) , ' ' ) ; ct . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , ct ) ; } return soff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a raster dataset for NIDS raster products ; [CODESPLIT] int pcode_raster ( ByteBuffer bos , short pkcode , int hoff , int hedsiz , boolean isZ , byte [ ] data ) { byte [ ] b2 = new byte [ 2 ] ; int soff ; ArrayList dims = new ArrayList ( ) ; int iscale = 1 ; /* data scale                    */ int ival ; ival = convertShort2unsignedInt ( threshold [ 0 ] ) ; if ( ( ival & ( 1 << 13 ) ) != 0 ) iscale = 20 ; if ( ( ival & ( 1 << 12 ) ) != 0 ) iscale = 10 ; short [ ] rasp_code = new short [ 3 ] ; rasp_code [ 0 ] = pkcode ; bos . get ( b2 , 0 , 2 ) ; rasp_code [ 1 ] = ( short ) getInt ( b2 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; rasp_code [ 2 ] = ( short ) getInt ( b2 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; //        short rasp_i = (short)getInt(b2, 2);\r bos . get ( b2 , 0 , 2 ) ; //        short rasp_j = (short)getInt(b2, 2);\r bos . get ( b2 , 0 , 2 ) ; short rasp_xscale = ( short ) getInt ( b2 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; //        short rasp_xscalefract = (short)getInt(b2, 2);\r bos . get ( b2 , 0 , 2 ) ; //        short rasp_yscale = (short)getInt(b2, 2);\r bos . get ( b2 , 0 , 2 ) ; //        short rasp_yscalefract = (short)getInt(b2, 2);\r bos . get ( b2 , 0 , 2 ) ; short num_rows = ( short ) getInt ( b2 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; //        short packing = (short)getInt(b2, 2);\r soff = 20 ; hedsiz = hedsiz + soff ; int nlevel = code_levelslookup ( pcode ) ; double ddx = code_reslookup ( pcode ) ; int [ ] levels = getLevels ( nlevel , threshold ) ; //prod_info_size = (int) (num_rows * scale);\r //out.println( \"resp scale \" + (int)rasp_xscale + \" and \" + (int)rasp_xscalefract+ \" and \" + (int)rasp_yscale+ \" and \" + (int)rasp_yscalefract );\r numY0 = 0 ; //rasp_j;\r numX0 = 0 ; //rasp_i;\r numX = num_rows ; numY = num_rows ; Dimension jDim = new Dimension ( \"y\" , numY , true , false , false ) ; Dimension iDim = new Dimension ( \"x\" , numX , true , false , false ) ; dims . add ( jDim ) ; dims . add ( iDim ) ; ncfile . addDimension ( null , iDim ) ; ncfile . addDimension ( null , jDim ) ; //ncfile.addAttribute(null, new Attribute(\"cdm_data_type\", thredds.catalog.DataType.GRID.toString()));\r if ( cname . startsWith ( \"Precip\" ) ) { ncfile . addAttribute ( null , new Attribute ( \"isRadial\" , new Integer ( 3 ) ) ) ; ddx = ddx * rasp_xscale ; } ncfile . addAttribute ( null , new Attribute ( \"cdm_data_type\" , FeatureType . GRID . toString ( ) ) ) ; //Variable dist = new Variable(ncfile, null, null, \"distance\");\r //dist.setDataType(DataType.INT);\r //dist.setDimensions(dims);\r //ncfile.addVariable(null, dist);\r //dist.setSPobject( new Vinfo ( numX, numX0, numY, numY0, hoff, hedsiz, isR, isZ, null, null, pkcode, 0));\r String coordinates = \"x y time latitude longitude altitude\" ; Variable v = new Variable ( ncfile , null , null , cname + \"_RAW\" ) ; v . setDataType ( DataType . BYTE ) ; v . setDimensions ( dims ) ; ncfile . addVariable ( null , v ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , ctitle ) ) ; v . addAttribute ( new Attribute ( CDM . UNITS , cunit ) ) ; v . setSPobject ( new Vinfo ( numX , numX0 , numY , numY0 , hoff , hedsiz , isR , isZ , null , null , pkcode , 0 ) ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; if ( cname . startsWith ( \"VertLiquid\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } else if ( cname . startsWith ( \"EchoTop\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } else if ( cname . startsWith ( \"BaseReflectivityComp\" ) || cname . startsWith ( \"LayerCompReflect\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } else if ( cname . startsWith ( \"Precip\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } // create coordinate variables\r Variable xaxis = new Variable ( ncfile , null , null , \"x\" ) ; xaxis . setDataType ( DataType . DOUBLE ) ; xaxis . setDimensions ( \"x\" ) ; xaxis . addAttribute ( new Attribute ( CDM . LONG_NAME , \"projection x coordinate\" ) ) ; xaxis . addAttribute ( new Attribute ( CDM . UNITS , \"km\" ) ) ; xaxis . addAttribute ( new Attribute ( _Coordinate . AxisType , \"GeoX\" ) ) ; double [ ] data1 = new double [ numX ] ; for ( int i = 0 ; i < numX ; i ++ ) data1 [ i ] = numX0 + i * ddx ; Array dataA = Array . factory ( DataType . DOUBLE , new int [ ] { numX } , data1 ) ; xaxis . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , xaxis ) ; Variable yaxis = new Variable ( ncfile , null , null , \"y\" ) ; yaxis . setDataType ( DataType . DOUBLE ) ; yaxis . setDimensions ( \"y\" ) ; yaxis . addAttribute ( new Attribute ( CDM . LONG_NAME , \"projection y coordinate\" ) ) ; yaxis . addAttribute ( new Attribute ( CDM . UNITS , \"km\" ) ) ; yaxis . addAttribute ( new Attribute ( _Coordinate . AxisType , \"GeoY\" ) ) ; data1 = new double [ numY ] ; for ( int i = 0 ; i < numY ; i ++ ) data1 [ i ] = numY0 + i * ddx ; dataA = Array . factory ( DataType . DOUBLE , new int [ ] { numY } , data1 ) ; yaxis . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , yaxis ) ; ProjectionImpl projection = new FlatEarth ( lat_min , lon_max ) ; //ProjectionImpl projection = new LambertConformal(latitude, longitude, latitude, latitude);\r // coordinate transform variable\r Variable ct = new Variable ( ncfile , null , null , projection . getClassName ( ) ) ; ct . setDataType ( DataType . CHAR ) ; ct . setDimensions ( \"\" ) ; List params = projection . getProjectionParameters ( ) ; for ( int i = 0 ; i < params . size ( ) ; i ++ ) { Parameter p = ( Parameter ) params . get ( i ) ; ct . addAttribute ( new Attribute ( p ) ) ; } ct . addAttribute ( new Attribute ( _Coordinate . TransformType , \"Projection\" ) ) ; ct . addAttribute ( new Attribute ( _Coordinate . Axes , \"x y\" ) ) ; // fake data\r dataA = Array . factory ( DataType . CHAR , new int [ ] { } ) ; dataA . setChar ( dataA . getIndex ( ) , ' ' ) ; ct . setCachedData ( dataA , false ) ; ncfile . addVariable ( null , ct ) ; return soff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a radial dataset for NIDS radial products ; [CODESPLIT] int pcode_radial ( ByteBuffer bos , int hoff , int hedsiz , boolean isZ , byte [ ] data , short [ ] threshold ) throws IOException { byte [ ] b2 = new byte [ 2 ] ; int soff ; ArrayList dims = new ArrayList ( ) ; int iscale = 1 ; /* data scale                    */ int ival ; ival = convertShort2unsignedInt ( threshold [ 0 ] ) ; if ( ( ival & ( 1 << 13 ) ) != 0 ) iscale = 20 ; if ( ( ival & ( 1 << 12 ) ) != 0 ) iscale = 10 ; bos . get ( b2 , 0 , 2 ) ; short first_bin = ( short ) getInt ( b2 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; short num_bin = ( short ) ( getUInt ( b2 , 2 ) ) ; if ( this . pcode == 94 || this . pcode == 99 ) num_bin = addBinSize ( num_bin ) ; bos . get ( b2 , 0 , 2 ) ; //        short radp_i = (short)getInt(b2, 2);\r bos . get ( b2 , 0 , 2 ) ; //        short radp_j = (short)getInt(b2, 2);\r bos . get ( b2 , 0 , 2 ) ; short radp_scale = ( short ) getInt ( b2 , 2 ) ; if ( this . pcode == 134 || this . pcode == 135 ) radp_scale = ( short ) ( radp_scale * 1000 ) ; bos . get ( b2 , 0 , 2 ) ; short num_radials = ( short ) getInt ( b2 , 2 ) ; soff = 12 ; hedsiz = hedsiz + soff ; numY0 = 0 ; numY = num_radials ; numX0 = first_bin ; numX = num_bin ; int nlevel = code_levelslookup ( pcode ) ; int [ ] levels ; //prod_info_size = 2 * (int) (num_bin * scale + 0.5);\r //dimensions: radial, bin\r ncfile . addAttribute ( null , new Attribute ( \"cdm_data_type\" , FeatureType . RADIAL . toString ( ) ) ) ; Dimension radialDim = new Dimension ( \"azimuth\" , num_radials ) ; ncfile . addDimension ( null , radialDim ) ; Dimension binDim = new Dimension ( \"gate\" , num_bin ) ; ncfile . addDimension ( null , binDim ) ; dims . add ( radialDim ) ; dims . add ( binDim ) ; ArrayList dims1 = new ArrayList ( ) ; ArrayList dims2 = new ArrayList ( ) ; dims1 . add ( radialDim ) ; dims2 . add ( binDim ) ; // Variable aziVar = new Variable(ncfile, null, null, \"azimuth\");\r // aziVar.setDataType(DataType.FLOAT);\r // aziVar.setDimensions(dims1);\r // ncfile.addVariable(null, aziVar);\r // aziVar.addAttribute( new Attribute(CDM.LONG_NAME, \"azimuth angle in degrees: 0 = true north, 90 = east\"));\r // aziVar.addAttribute( new Attribute(CDM.UNITS, \"degrees\"));\r // aziVar.setSPobject( new Vinfo (numX, numX0, numY, numY0, hoff, hedsiz, isR, isZ, null, null, 0));\r // dims1 =  new ArrayList();\r // dims1.add(binDim);\r //Variable gateV = new Variable(ncfile, null, null, \"gate1\");\r //gateV.setDataType(DataType.FLOAT);\r //gateV.setDimensions(dims2);\r //ncfile.addVariable(null, gateV);\r //gateV.addAttribute( new Attribute(CDM.LONG_NAME, \"radial distance to start of gate\"));\r //gateV.addAttribute( new Attribute(CDM.UNITS, \"m\"));\r //gateV.setSPobject( new Vinfo (numX, numX0, numY, radp_scale, hoff, hedsiz, isR, isZ, null, null, 0, 0));\r isR = true ; // add elevation coordinate variable\r String vName = \"elevation\" ; String lName = \"elevation angle in degres: 0 = parallel to pedestal base, 90 = perpendicular\" ; Attribute att = new Attribute ( _Coordinate . AxisType , AxisType . RadialElevation . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , p3 ) ; // add azimuth coordinate variable\r vName = \"azimuth\" ; lName = \"azimuth angle in degrees: 0 = true north, 90 = east\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . RadialAzimuth . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , 0 ) ; // add gate coordinate variable\r vName = \"gate\" ; lName = \"Radial distance to the start of gate\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . RadialDistance . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims2 , att , DataType . FLOAT , \"meters\" , hoff , hedsiz , isZ , radp_scale ) ; // add radial coordinate variable\r vName = \"latitude\" ; lName = \"Latitude of the instrument\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , 0 ) ; vName = \"longitude\" ; lName = \"Longitude of the instrument\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , 0 ) ; vName = \"altitude\" ; lName = \"Altitude in meters (asl) of the instrument\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Height . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"meters\" , hoff , hedsiz , isZ , 0 ) ; vName = \"rays_time\" ; lName = \"rays time\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . DOUBLE , \"milliseconds since 1970-01-01 00:00 UTC\" , hoff , hedsiz , isZ , 0 ) ; //add RAW, BRIT variables for all radial variable\r if ( pcode == 182 || pcode == 99 ) { levels = getTDWRLevels ( nlevel , threshold ) ; iscale = 10 ; } else if ( pcode == 186 || pcode == 94 ) { threshold [ 0 ] = - 320 ; threshold [ 1 ] = 5 ; threshold [ 2 ] = 254 ; levels = getTDWRLevels ( nlevel , threshold ) ; iscale = 10 ; } else if ( pcode == 32 ) { levels = getTDWRLevels1 ( nlevel , threshold ) ; iscale = 10 ; } else if ( pcode == 138 ) { levels = getTDWRLevels1 ( nlevel , threshold ) ; iscale = 100 ; } else if ( pcode == 134 || pcode == 135 ) { levels = getTDWRLevels2 ( nlevel , threshold ) ; iscale = 1 ; } else if ( pcode == 159 || pcode == 161 || pcode == 163 || pcode == 170 || pcode == 172 || pcode == 173 || pcode == 174 || pcode == 175 || pcode == 165 || pcode == 177 ) { levels = getDualpolLevels ( threshold ) ; iscale = 100 ; } else { levels = getLevels ( nlevel , threshold ) ; } Variable v = new Variable ( ncfile , null , null , cname + \"_RAW\" ) ; v . setDataType ( DataType . UBYTE ) ; v . setDimensions ( dims ) ; ncfile . addVariable ( null , v ) ; v . addAttribute ( new Attribute ( CDM . UNITS , cunit ) ) ; String coordinates = \"elevation azimuth gate rays_time latitude longitude altitude\" ; v . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; // v.addAttribute( new Attribute(CDM.UNSIGNED, \"true\"));\r v . setSPobject ( new Vinfo ( numX , numX0 , numY , numY0 , hoff , hedsiz , isR , isZ , null , levels , 0 , nlevel ) ) ; // addVariable(cname + \"_Brightness\", ctitle + \" Brightness\", ncfile, dims, coordinates, DataType.FLOAT,\r //                 cunit, hoff, hedsiz, isZ, nlevel, levels, iscale);\r if ( cname . startsWith ( \"CorrelationCoefficient\" ) || cname . startsWith ( \"HydrometeorClassification\" ) || cname . startsWith ( \"DifferentialReflectivity\" ) || cname . startsWith ( \"DifferentialPhase\" ) || cname . startsWith ( \"HypridHydrometeorClassification\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } else if ( cname . startsWith ( \"OneHourAccumulation\" ) || cname . startsWith ( \"DigitalAccumulationArray\" ) || cname . startsWith ( \"StormTotalAccumulation\" ) || cname . startsWith ( \"DigitalStormTotalAccumulation\" ) || cname . startsWith ( \"Accumulation3Hour\" ) || cname . startsWith ( \"Accumulation24Hour\" ) || cname . startsWith ( \"Digital1HourDifferenceAccumulation\" ) || cname . startsWith ( \"DigitalInstantaneousPrecipitationRate\" ) || cname . startsWith ( \"DigitalInstantaneousPrecipitationRate\" ) || cname . startsWith ( \"DigitalTotalDifferenceAccumulation\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } else if ( cname . startsWith ( \"BaseReflectivity\" ) || cname . endsWith ( \"Reflectivity\" ) || cname . startsWith ( \"SpectrumWidth\" ) ) { //addVariable(cname + \"_VIP\", ctitle + \" VIP Level\", ncfile, dims, coordinates, DataType.FLOAT,\r //             cunit, hoff, hedsiz, isZ, nlevel, levels, iscale);\r addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } else if ( cname . startsWith ( \"RadialVelocity\" ) || cname . startsWith ( \"StormMeanVelocity\" ) || cname . startsWith ( \"BaseVelocity\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } else if ( cname . startsWith ( \"Precip\" ) || cname . endsWith ( \"Precip\" ) || cname . startsWith ( \"EnhancedEchoTop\" ) || cname . startsWith ( \"DigitalIntegLiquid\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } return soff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for level3 176 product [CODESPLIT] public List parseComponents ( ByteBuffer datainput ) throws IOException { ArrayList arraylist = null ; int i = datainput . getInt ( ) ; if ( i != 0 ) i = datainput . getInt ( ) ; for ( int j = 0 ; j < i ; j ++ ) { datainput . getInt ( ) ; int type = datainput . getInt ( ) ; arraylist = parseData ( datainput ) ; } return arraylist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for level3 176 product [CODESPLIT] public ArrayList parseData ( ByteBuffer datainput ) throws IOException { ArrayList arraylist = new ArrayList ( ) ; int numRadials ; int numBins ; int dataOffset ; readInString ( datainput ) ; // desc\r datainput . getFloat ( ) ; // numBins\r float rangeToFirstBin = datainput . getFloat ( ) ; datainput . getInt ( ) ; // numOfParms\r datainput . getInt ( ) ; numRadials = datainput . getInt ( ) ; dataOffset = datainput . position ( ) ; //getting numbin  by checking the first radial, but the data offset should be before this read\r datainput . getFloat ( ) ; datainput . getFloat ( ) ; datainput . getFloat ( ) ; numBins = datainput . getInt ( ) ; arraylist . add ( numBins ) ; arraylist . add ( numRadials ) ; arraylist . add ( rangeToFirstBin ) ; arraylist . add ( dataOffset ) ; //data = null;\r /*    for(int k = 0; k < numRadials; k++)\r\n        {\r\n            angleData[k] = datainput.getFloat();\r\n            datainput.getFloat();\r\n            datainput.getFloat();\r\n            numBins = datainput.getInt();\r\n            readInString(datainput);\r\n            if(data == null)\r\n                data = new short[numRadials * numBins];\r\n            numBins = datainputstream.readInt();\r\n            for(int l = 0; l < numBins; l++)\r\n                data[k * numBins + l] = (short)datainputstream.getInt();\r\n\r\n        }  */ return arraylist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for level3 176 product [CODESPLIT] public List parseParameters ( ByteBuffer datainput ) throws IOException { ArrayList arraylist = new ArrayList ( ) ; int i = datainput . getInt ( ) ; if ( i > 0 ) i = datainput . getInt ( ) ; for ( int j = 0 ; j < i ; j ++ ) { arraylist . add ( readInString ( datainput ) ) ; HashMap hm = addAttributePairs ( readInString ( datainput ) ) ; arraylist . add ( hm ) ; } return arraylist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for level3 176 product [CODESPLIT] public HashMap addAttributePairs ( String s ) { java . util . regex . Pattern PARAM_PATTERN = java . util . regex . Pattern . compile ( \"([\\\\w*\\\\s*?]*)\\\\=([(\\\\<|\\\\{|\\\\[|\\\\()?\\\\w*\\\\s*?\\\\.?\\\\,?\\\\-?\\\\/?\\\\%?(\\\\>|\\\\}|\\\\]|\\\\))?]*)\" ) ; HashMap attributes = new HashMap ( ) ; for ( java . util . regex . Matcher matcher = PARAM_PATTERN . matcher ( s ) ; matcher . find ( ) ; attributes . put ( matcher . group ( 1 ) . trim ( ) , matcher . group ( 2 ) . trim ( ) ) ) ; return attributes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for level3 176 product [CODESPLIT] public static String readInString ( ByteBuffer datainput ) throws IOException { StringBuffer stringbuffer = new StringBuffer ( ) ; int i = datainput . getInt ( ) ; for ( int j = 0 ; j < i ; j ++ ) { char c = ( char ) ( datainput . get ( ) & 0xff ) ; stringbuffer . append ( c ) ; } int k = i % 4 ; if ( k != 0 ) k = 4 - k ; for ( int l = 0 ; l < k ; l ++ ) datainput . get ( ) ; return stringbuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct a generic radial dataset for dualpol radial products ; [CODESPLIT] int pcode_generic ( ByteBuffer bos , int hoff , int hedsiz , boolean isZ , byte [ ] data , short [ ] threshold ) throws IOException { byte [ ] b2 = new byte [ 2 ] ; int soff = 0 ; ArrayList dims = new ArrayList ( ) ; int iscale = 1 ; /* data scale                    */ bos . get ( b2 , 0 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; bos . get ( b2 , 0 , 2 ) ; readInString ( bos ) ; // vname\r readInString ( bos ) ; // vdesp\r bos . getInt ( ) ; // code\r bos . getInt ( ) ; // type\r bos . getInt ( ) ; // time\r readInString ( bos ) ; // rnameStr\r bos . getFloat ( ) ; // lat\r bos . getFloat ( ) ; // lon\r bos . getFloat ( ) ; // height\r bos . getInt ( ) ; // vscanStartTime\r bos . getInt ( ) ; // eleScanStartTime\r float eleAngle = bos . getFloat ( ) ; p3 = ( short ) eleAngle ; bos . getInt ( ) ; // volScanNum\r bos . getInt ( ) ; // opMode\r bos . getInt ( ) ; // volPattern\r bos . getInt ( ) ; // eleNum\r bos . getDouble ( ) ; // skip 8 bytes\r parseParameters ( bos ) ; // aa - do nothing\r List cc = parseComponents ( bos ) ; // assuming only radial component\r if ( cc == null ) { throw new IOException ( \"Error reading components for radial data\" ) ; } int num_radials = ( Integer ) cc . get ( 1 ) ; int num_bin = ( Integer ) cc . get ( 0 ) ; float rangeToFirstBin = ( Float ) cc . get ( 2 ) ; int dataOffset = ( Integer ) cc . get ( 3 ) ; numY0 = 0 ; numY = num_radials ; numX0 = ( int ) rangeToFirstBin ; //first_bin;\r numX = num_bin ; int nlevel = code_levelslookup ( pcode ) ; int [ ] levels ; short radp_scale = 1000 ; hedsiz = dataOffset ; //prod_info_size = 2 * (int) (num_bin * scale + 0.5);\r //dimensions: radial, bin\r ncfile . addAttribute ( null , new Attribute ( \"cdm_data_type\" , FeatureType . RADIAL . toString ( ) ) ) ; Dimension radialDim = new Dimension ( \"azimuth\" , num_radials ) ; ncfile . addDimension ( null , radialDim ) ; Dimension binDim = new Dimension ( \"gate\" , num_bin ) ; ncfile . addDimension ( null , binDim ) ; dims . add ( radialDim ) ; dims . add ( binDim ) ; ArrayList dims1 = new ArrayList ( ) ; ArrayList dims2 = new ArrayList ( ) ; dims1 . add ( radialDim ) ; dims2 . add ( binDim ) ; isR = true ; // add elevation coordinate variable\r String vName = \"elevation\" ; String lName = \"elevation angle in degres: 0 = parallel to pedestal base, 90 = perpendicular\" ; Attribute att = new Attribute ( _Coordinate . AxisType , AxisType . RadialElevation . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , p3 ) ; // add azimuth coordinate variable\r vName = \"azimuth\" ; lName = \"azimuth angle in degrees: 0 = true north, 90 = east\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . RadialAzimuth . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , 0 ) ; // add gate coordinate variable\r vName = \"gate\" ; lName = \"Radial distance to the start of gate\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . RadialDistance . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims2 , att , DataType . FLOAT , \"meters\" , hoff , hedsiz , isZ , radp_scale ) ; // add radial coordinate variable\r vName = \"latitude\" ; lName = \"Latitude of the instrument\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , 0 ) ; vName = \"longitude\" ; lName = \"Longitude of the instrument\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"degrees\" , hoff , hedsiz , isZ , 0 ) ; vName = \"altitude\" ; lName = \"Altitude in meters (asl) of the instrument\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Height . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . FLOAT , \"meters\" , hoff , hedsiz , isZ , 0 ) ; vName = \"rays_time\" ; lName = \"rays time\" ; att = new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ; addParameter ( vName , lName , ncfile , dims1 , att , DataType . DOUBLE , \"milliseconds since 1970-01-01 00:00 UTC\" , hoff , hedsiz , isZ , 0 ) ; if ( pcode == 176 ) { levels = getDualpolLevels ( threshold ) ; iscale = 1 ; } else { levels = getLevels ( nlevel , threshold ) ; } Variable v = new Variable ( ncfile , null , null , cname + \"_RAW\" ) ; v . setDataType ( DataType . USHORT ) ; v . setDimensions ( dims ) ; ncfile . addVariable ( null , v ) ; v . addAttribute ( new Attribute ( CDM . UNITS , cunit ) ) ; String coordinates = \"elevation azimuth gate rays_time latitude longitude altitude\" ; v . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; // v.addAttribute( new Attribute(CDM.UNSIGNED, \"true\"));\r v . setSPobject ( new Vinfo ( numX , numX0 , numY , numY0 , hoff , hedsiz , isR , isZ , null , levels , 0 , nlevel ) ) ; if ( cname . startsWith ( \"DigitalInstantaneousPrecipitationRate\" ) ) { addVariable ( cname , ctitle , ncfile , dims , coordinates , DataType . FLOAT , cunit , hoff , hedsiz , isZ , nlevel , levels , iscale ) ; } return soff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the table to calibrate data value [CODESPLIT] public int [ ] getLevels ( int nlevel , short [ ] th ) { int [ ] levels = new int [ nlevel ] ; int ival ; int isign ; for ( int i = 0 ; i < nlevel ; i ++ ) { /* calibrated data values        */ ival = convertShort2unsignedInt ( th [ i ] ) ; if ( ( ival & 0x00008000 ) == 0 ) { isign = - 1 ; if ( ( ival & 0x00000100 ) == 0 ) isign = 1 ; levels [ i ] = isign * ( ival & 0x000000FF ) ; } else { levels [ i ] = - 9999 + ( ival & 0x000000FF ) ; } } return levels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the calibrate data values for TDWR data [CODESPLIT] public int [ ] getTDWRLevels ( int nlevel , short [ ] th ) { int [ ] levels = new int [ nlevel ] ; //th[2]+2 ];\r int inc = th [ 1 ] ; levels [ 0 ] = - 9866 ; levels [ 1 ] = - 9866 ; for ( int i = 2 ; i < nlevel ; i ++ ) { /* calibrated data values        */ levels [ i ] = th [ 0 ] + ( i - 2 ) * inc ; } return levels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the calibrate data values for TDWR data [CODESPLIT] public int [ ] getTDWRLevels1 ( int nlevel , short [ ] th ) { int [ ] levels = new int [ nlevel ] ; //th[2] ];\r int inc = th [ 1 ] ; for ( int i = 0 ; i < nlevel ; i ++ ) { /* calibrated data values        */ levels [ i ] = th [ 0 ] + ( i ) * inc ; } return levels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the calibrate data values for dualpol data [CODESPLIT] public int [ ] getDualpolLevels ( short [ ] th ) { int inc = th . length ; int [ ] levels = new int [ inc ] ; //th[2] ];\r for ( int i = 0 ; i < inc ; i ++ ) { /* calibrated data values        */ levels [ i ] = th [ i ] ; } return levels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the calibrate data values for TDWR data [CODESPLIT] public int [ ] getTDWRLevels2 ( int nlevel , short [ ] th ) { int inc = th . length ; int [ ] levels = new int [ inc ] ; //th[2] ];\r for ( int i = 0 ; i < inc ; i ++ ) { /* calibrated data values        */ levels [ i ] = th [ i ] ; } return levels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adding new variable to the netcdf file [CODESPLIT] void addVariable ( String pName , String longName , NetcdfFile nc , ArrayList dims , String coordinates , DataType dtype , String ut , long hoff , long hedsiz , boolean isZ , int nlevel , int [ ] levels , int iscale ) { Variable v = new Variable ( nc , null , null , pName ) ; v . setDataType ( dtype ) ; v . setDimensions ( dims ) ; ncfile . addVariable ( null , v ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; v . addAttribute ( new Attribute ( CDM . UNITS , ut ) ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; v . setSPobject ( new Vinfo ( numX , numX0 , numY , numY0 , hoff , hedsiz , isR , isZ , null , levels , iscale , nlevel ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adding new parameter to the netcdf file [CODESPLIT] void addParameter ( String pName , String longName , NetcdfFile nc , ArrayList dims , Attribute att , DataType dtype , String ut , long hoff , long doff , boolean isZ , int y0 ) { String vName = pName ; Variable vVar = new Variable ( nc , null , null , vName ) ; vVar . setDataType ( dtype ) ; if ( dims != null ) vVar . setDimensions ( dims ) ; else vVar . setDimensions ( \"\" ) ; if ( att != null ) vVar . addAttribute ( att ) ; vVar . addAttribute ( new Attribute ( CDM . UNITS , ut ) ) ; vVar . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; nc . addVariable ( null , vVar ) ; vVar . setSPobject ( new Vinfo ( numX , numX0 , numY , y0 , hoff , doff , isR , isZ , null , null , 0 , 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Misc [CODESPLIT] private int getProductLevel ( int prod_elevation ) { int level = 0 ; if ( prod_elevation == 5 ) level = 0 ; else if ( prod_elevation == 9 ) level = 1 ; else if ( prod_elevation == 13 || prod_elevation == 15 ) level = 2 ; else if ( prod_elevation == 18 ) level = 3 ; else if ( prod_elevation == 24 ) level = 4 ; else if ( prod_elevation == 31 ) level = 6 ; return level ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parsing the product information into netcdf dataset [CODESPLIT] void setProductInfo ( int prod_type , Pinfo pinfo ) { /* memo field                */ String [ ] cmode = new String [ ] { \"Maintenance\" , \"Clear Air\" , \"Precip Mode\" } ; short prod_max = pinfo . p4 ; short prod_min = 0 ; int prod_elevation = 0 ; //int prod_info;\r int prod_top ; int radial = 0 ; String summary = null ; java . util . Date endDate ; java . util . Date startDate ; String dstring ; double t1 = 124.0 * 1.853 / 111.26 ; double t2 = 230 / ( 111.26 * Math . cos ( Math . toRadians ( latitude ) ) ) ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; //* Math.cos(Math.toRadians(lat_min));\r lon_max = longitude - t2 ; //* Math.cos(Math.toRadians(lat_min));\r startDate = getDate ( volumeScanDate , volumeScanTime * 1000 ) ; endDate = getDate ( volumeScanDate , volumeScanTime * 1000 ) ; if ( prod_type == SPECTRUM ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Base Specturm Width \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( pcode , prod_elevation / 10 ) ; ctitle = \"BREF: Base Spectrum Width\" ; cunit = \"Knots\" ; cname = \"SpectrumWidth\" ; summary = ctilt + \" is a radial image of base reflectivity at tilt \" + ( prod_elevation / 10 + 1 ) + \" and range 124 nm\" ; if ( pcode == 28 ) { t1 = t1 * 0.25 ; t2 = t2 * 0.25 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; //* Math.cos(Math.toRadians(lat_min));\r lon_max = longitude - t2 ; //* Math.cos(Math.toRadians(lat_min));\r summary = ctilt + \" is a radial image of base reflectivity at tilt \" + ( prod_elevation / 10 + 1 ) + \" and range 32 nm\" ; } } else if ( prod_type == DigitalDifferentialReflectivity ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Differential Reflectivity \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 15 , pLevel ) ; ctitle = \"Dualpol: Digital Differential Reflectivity\" ; cunit = \"dBz\" ; cname = \"DifferentialReflectivity\" ; summary = ctilt + \" is a radial image of dual pol differential reflectivity field and its range 162 nm\" ; } else if ( prod_type == DigitalCorrelationCoefficient ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Correlation Coefficient \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 16 , pLevel ) ; ctitle = \"Dualpol: Digital Correlation Coefficient\" ; cunit = \" \" ; cname = \"CorrelationCoefficient\" ; summary = ctilt + \" is a radial image of dual pol Correlation Coefficient field and its range 162 nm\" ; } else if ( prod_type == DigitalDifferentialPhase ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Differential Phase \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 17 , pLevel ) ; ctitle = \"Dualpol: Digital Differential Phase\" ; cunit = \"Degree/km\" ; cname = \"DifferentialPhase\" ; summary = ctilt + \" is a radial image of dual pol Differential Phase field and its range 162 nm\" ; } else if ( prod_type == HydrometeorClassification ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Hydrometeor Classification \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 18 , pLevel ) ; ctitle = \"Dualpol: Hydrometeor Classification\" ; cunit = \" \" ; cname = \"HydrometeorClassification\" ; summary = ctilt + \" is a radial image of dual pol Hydrometeor Classification field and its range 162 nm\" ; } else if ( prod_type == HypridHydrometeorClassification ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Hyprid Hydrometeor Classification \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 18 , pLevel ) ; ctitle = \"Dualpol: Hyprid Hydrometeor Classification\" ; cunit = \" \" ; cname = \"HypridHydrometeorClassification\" ; summary = ctilt + \" is a radial image of dual pol Hyprid Hydrometeor Classification field and its range 162 nm\" ; } else if ( prod_type == OneHourAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"One Hour Accumulation \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; ctilt = \"OHA\" ; ctitle = \"Dualpol: One Hour Accumulation\" ; cunit = \"IN\" ; cname = \"OneHourAccumulation\" ; summary = ctilt + \" is a radial image of dual pol One Hour Accumulation field and its range 124 nm\" ; } else if ( prod_type == DigitalAccumulationArray ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Digital Accumulation Array \" + cmode [ pinfo . opmode ] ; ctilt = \"DAA\" ; ctitle = \"Dualpol: Digital Accumulation Array\" ; cunit = \"IN\" ; cname = \"DigitalAccumulationArray\" ; summary = ctilt + \" is a radial image of dual pol Digital Accumulation Array field and its range 124 nm\" ; } else if ( prod_type == StormTotalAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Storm Total Accumulation \" + cmode [ pinfo . opmode ] ; ctilt = \"PTA\" ; ctitle = \"Dualpol: Storm Total Accumulation\" ; cunit = \"IN\" ; cname = \"StormTotalAccumulation\" ; summary = ctilt + \" is a radial image of dual pol Storm Total Accumulation field and its range 124 nm\" ; } else if ( prod_type == DigitalStormTotalAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Digital Storm Total Accumulation  \" + cmode [ pinfo . opmode ] ; ctilt = \"DTA\" ; ctitle = \"Dualpol: Digital Storm Total Accumulation\" ; cunit = \"IN\" ; cname = \"DigitalStormTotalAccumulation\" ; summary = ctilt + \" is a radial image of dual pol Digital StormTotal Accumulation field and its range 124 nm\" ; } else if ( prod_type == Accumulation3Hour ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Hyprid Hydrometeor Classification \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 18 , pLevel ) ; ctitle = \"Dualpol: 3-hour Accumulation\" ; cunit = \"IN\" ; cname = \"Accumulation3Hour\" ; summary = ctilt + \" is a radial image of dual pol 3-hour Accumulation field and its range 124 nm\" ; } else if ( prod_type == Digital1HourDifferenceAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Digital One Hour Difference Accumulation \" + cmode [ pinfo . opmode ] ; ctilt = \"DOD\" ; ctitle = \"Dualpol: Digital One Hour Difference Accumulation\" ; cunit = \"IN\" ; cname = \"Digital1HourDifferenceAccumulation\" ; summary = ctilt + \" is a radial image of dual pol Digital One Hour Difference Accumulation field and its range 124 nm\" ; } else if ( prod_type == DigitalTotalDifferenceAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Digital Total Difference Accumulation \" + cmode [ pinfo . opmode ] ; ctilt = \"DSD\" ; ctitle = \"Dualpol: Digital Total Difference Accumulation\" ; cunit = \"IN\" ; cname = \"DigitalTotalDifferenceAccumulation\" ; summary = ctilt + \" is a radial image of dual pol Digital Total Difference Accumulation field and its range 124 nm\" ; } else if ( prod_type == DigitalInstantaneousPrecipitationRate ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Digital Instantaneous Precipitation Rate \" + cmode [ pinfo . opmode ] ; ctilt = \"DPR\" ; ctitle = \"Dualpol: Digital Instantaneous Precipitation Rate\" ; cunit = \"IN/Hour\" ; cname = \"DigitalInstantaneousPrecipitationRate\" ; summary = ctilt + \" is a radial image of dual pol Digital Instantaneous Precipitation Rate field and its range 124 nm\" ; } else if ( prod_type == BaseReflectivityDR ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Base Reflectivity DR \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 94 , pLevel ) ; ctitle = \"HighResolution: Base Reflectivity\" ; cunit = \"dBz\" ; cname = \"BaseReflectivityDR\" ; summary = ctilt + \" is a radial image of base reflectivity field and its range 248 nm\" ; } else if ( prod_type == BaseVelocityDV ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Base Velocity DR \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 99 , pLevel ) ; ctitle = \"HighResolution: Base Velocity\" ; cunit = \"m/s\" ; cname = \"BaseVelocityDV\" ; summary = ctilt + \" is a radial image of base velocity field and its range 124 nm\" ; } else if ( prod_type == DigitalVert_Liquid ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Digital Hybrid Reflect \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 134 , prod_elevation / 10 ) ; ctitle = \"Digital: Vertical Integ Liquid\" ; cunit = \"kg/m^2\" ; cname = \"DigitalIntegLiquid\" ; summary = ctilt + \" is a radial image high resolution vertical integral liquid and range 248 nm\" ; } else if ( prod_type == DigitalHybridReflect ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Digital Hybrid Reflect \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 19 , prod_elevation / 10 ) ; ctitle = \"DigitalHybrid: Reflectivity\" ; cunit = \"dBz\" ; cname = \"DigitalHybridReflectivity\" ; summary = ctilt + \" is a radial image of base reflectivity at tilt \" + ( prod_elevation / 10 + 1 ) + \" and range 124 nm\" ; } else if ( prod_type == Base_Reflect || prod_type == Reflect1 ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Base Reflct \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; if ( prod_type == Reflect1 ) { ctilt = \"R\" + prod_elevation / 10 ; summary = ctilt + \" is a radial image of base reflectivity at tilt \" + ( prod_elevation / 10 + 1 ) ; } else { ctilt = pname_lookup ( 19 , prod_elevation / 10 ) ; summary = ctilt + \" is a radial image of base reflectivity at tilt \" + ( prod_elevation / 10 + 1 ) + \" and range 124 nm\" ; } ctitle = \"BREF: Base Reflectivity\" ; cunit = \"dBz\" ; cname = \"BaseReflectivity\" ; } else if ( prod_type == BaseReflect248 ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = \"Base Reflct 248 \" + prod_elevation / 10 + \" DEG \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 20 , prod_elevation / 10 ) ; ctitle = \"BREF: 248 nm Base Reflectivity\" ; cunit = \"dBz\" ; cname = \"BaseReflectivity248\" ; summary = ctilt + \" is a radial image of base reflectivity at tilt \" + ( prod_elevation / 10 + 1 ) + \" and range 248 nm\" ; t1 = 248.0 * 1.853 / 111.26 ; t2 = 460 / ( 111.26 * Math . cos ( Math . toRadians ( latitude ) ) ) ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Comp_Reflect ) { radial = 3 ; prod_elevation = - 1 ; ctilt = pname_lookup ( pinfo . pcode , elevationNumber ) ; if ( pinfo . pcode == 36 || pinfo . pcode == 38 ) { t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } summary = ctilt + \"is a raster image of composite reflectivity\" ; cmemo = \"Composite Reflectivity at \" + cmode [ pinfo . opmode ] ; ctitle = \"CREF Composite Reflectivity\" + ctilt ; cunit = \"dBz\" ; cname = \"BaseReflectivityComp\" ; } else if ( prod_type == Layer_Reflect_Avg || prod_type == Layer_Reflect_Max ) { radial = 3 ; prod_elevation = pinfo . p5 ; prod_top = pinfo . p6 ; ctilt = pname_lookup ( pcode , 0 ) ; summary = ctilt + \" is a raster image of composite reflectivity at range 124 nm\" ; cmemo = \"Layer Reflct \" + prod_elevation + \" - \" + prod_top + cmode [ pinfo . opmode ] ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; ctitle = \"LREF: Layer Composite Reflectivity\" ; cunit = \"dBz\" ; cname = \"LayerCompReflect\" ; } else if ( prod_type == EnhancedEcho_Tops ) { radial = 1 ; prod_elevation = - 1 ; summary = \"EET is a radial image of echo tops at range 186 nm\" ; cmemo = \"Enhanced Echo Tops [K FT] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 135 , elevationNumber ) ; ctitle = \"TOPS: Enhanced Echo Tops\" ; cunit = \"K FT\" ; cname = \"EnhancedEchoTop\" ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Echo_Tops ) { radial = 3 ; prod_elevation = - 1 ; summary = \"NET is a raster image of echo tops at range 124 nm\" ; cmemo = \"Echo Tops [K FT] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 41 , elevationNumber ) ; ctitle = \"TOPS: Echo Tops\" ; cunit = \"K FT\" ; cname = \"EchoTop\" ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_1 ) { radial = 1 ; prod_elevation = - 1 ; prod_max /= 10 ; endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = \"N1P is a raster image of 1 hour surface rainfall accumulation at range 124 nm\" ; cmemo = \"1-hr Rainfall [IN] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 78 , elevationNumber ) ; ctitle = \"PRE1: Surface 1-hour Rainfall Total\" ; cunit = \"IN\" ; cname = \"Precip1hr\" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_3 ) { radial = 1 ; prod_elevation = - 1 ; prod_max /= 10 ; endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = \"N3P is a raster image of 3 hour surface rainfall accumulation at range 124 nm\" ; cmemo = \"3-hr Rainfall [IN] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 79 , elevationNumber ) ; ctitle = \"PRE3: Surface 3-hour Rainfall Total\" ; cunit = \"IN\" ; cname = \"Precip3hr\" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == DigitalStormTotalPrecip ) { radial = 1 ; prod_elevation = - 1 ; //startDate = getDate( pinfo.p5, pinfo.p6 * 60 * 1000);\r endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = \"DSP is a radial image of digital storm total rainfall\" ; cmemo = \"Digital Strm Total Precip [IN] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 80 , elevationNumber ) ; ctitle = \"DPRE: Digital Storm Total Rainfall\" ; cunit = \"IN\" ; cname = \"DigitalPrecip\" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_Accum ) { radial = 1 ; prod_elevation = - 1 ; //startDate = getDate( pinfo.p5, pinfo.p6 * 60 * 1000);\r endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = \"NTP is a raster image of storm total rainfall accumulation at range 124 nm\" ; cmemo = \"Strm Tot Rain [IN] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 80 , elevationNumber ) ; ctitle = \"PRET: Surface Storm Total Rainfall\" ; cunit = \"IN\" ; cname = \"PrecipAccum\" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_Array ) { radial = 3 ; prod_elevation = - 1 ; summary = \"DPA is a raster image of hourly digital precipitation array at range 124 nm\" ; endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; cmemo = \"Precip Array [IN] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 81 , elevationNumber ) ; ctitle = \"PRET: Hourly Digital Precipitation Array\" ; cunit = \"dBA\" ; cname = \"PrecipArray\" ; } else if ( prod_type == Vert_Liquid ) { radial = 3 ; prod_elevation = - 1 ; summary = \"NVL is a raster image of verticalintegrated liguid at range 124 nm\" ; cmemo = \"Vert Int Lq H2O [mm] \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 57 , elevationNumber ) ; ctitle = \"VIL: Vertically-integrated Liquid Water\" ; cunit = \"kg/m^2\" ; cname = \"VertLiquid\" ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Velocity || prod_type == Velocity1 ) { radial = 1 ; prod_elevation = pinfo . p3 ; prod_min = pinfo . p4 ; prod_max = pinfo . p5 ; if ( prod_type == Velocity ) { ctilt = pname_lookup ( pinfo . pcode , prod_elevation / 10 ) ; } else { ctilt = \"V\" + prod_elevation / 10 ; } if ( pinfo . pcode == 25 ) { t1 = 32.0 * 1.853 / 111.26 ; t2 = 64 / ( 111.26 * Math . cos ( Math . toRadians ( latitude ) ) ) ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; summary = ctilt + \" is a radial image of base velocity\" + ( prod_elevation / 10 + 1 ) + \" and  range 32 nm\" ; cunit = \"m/s\" ; } else { summary = ctilt + \" is a radial image of base velocity at tilt \" + ( prod_elevation / 10 + 1 ) ; cunit = \"m/s\" ; } cmemo = \"Rad Vel \" + prod_elevation / 10. + \" DEG \" + cmode [ pinfo . opmode ] ; ctitle = \"VEL: Radial Velocity\" ; cname = \"RadialVelocity\" ; } else if ( prod_type == StrmRelMeanVel ) { radial = 1 ; prod_elevation = pinfo . p3 ; prod_min = pinfo . p4 ; prod_max = pinfo . p5 ; ctilt = pname_lookup ( 56 , prod_elevation / 10 ) ; summary = ctilt + \" is a radial image of storm relative mean radial velocity at tilt \" + ( prod_elevation / 10 + 1 ) + \" and  range 124 nm\" ; cmemo = \"StrmRelMnVl \" + prod_elevation / 10. + \" DEG \" + cmode [ pinfo . opmode ] ; ctitle = \"SRMV: Storm Relative Mean Velocity\" ; cunit = \"KT\" ; cname = \"StormMeanVelocity\" ; } else if ( prod_type == VAD ) { radial = 0 ; prod_elevation = pinfo . p3 ; prod_min = pinfo . p4 ; prod_max = pinfo . p5 ; summary = \"NVW is VAD wind profile which contains wind barbs and alpha numeric data\" ; cmemo = \"StrmRelMnVl \" + prod_elevation / 10. + \" DEG \" + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 48 , elevationNumber ) ; ctitle = \"SRMV: Velocity Azimuth Display\" ; cunit = \"KT\" ; cname = \"VADWindSpeed\" ; lat_min = latitude ; lat_max = latitude ; lon_min = longitude ; lon_max = longitude ; } else { ctilt = \"error\" ; ctitle = \"error\" ; cunit = \"error\" ; cname = \"error\" ; } /* add geo global att  */ ncfile . addAttribute ( null , new Attribute ( \"summary\" , \"Nexrad level 3 data are WSR-88D radar products.\" + summary ) ) ; ncfile . addAttribute ( null , new Attribute ( \"keywords_vocabulary\" , ctilt ) ) ; ncfile . addAttribute ( null , new Attribute ( \"conventions\" , _Coordinate . Convention ) ) ; ncfile . addAttribute ( null , new Attribute ( \"format\" , \"Level3/NIDS\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"geospatial_lat_min\" , new Float ( lat_min ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"geospatial_lat_max\" , new Float ( lat_max ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"geospatial_lon_min\" , new Float ( lon_min ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"geospatial_lon_max\" , new Float ( lon_max ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"geospatial_vertical_min\" , new Float ( height ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"geospatial_vertical_max\" , new Float ( height ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"RadarElevationNumber\" , new Integer ( prod_elevation ) ) ) ; dstring = formatter . toDateTimeStringISO ( startDate ) ; ncfile . addAttribute ( null , new Attribute ( \"time_coverage_start\" , dstring ) ) ; dstring = formatter . toDateTimeStringISO ( endDate ) ; ncfile . addAttribute ( null , new Attribute ( \"time_coverage_end\" , dstring ) ) ; ncfile . addAttribute ( null , new Attribute ( \"data_min\" , new Float ( prod_min ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"data_max\" , new Float ( prod_max ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"isRadial\" , new Integer ( radial ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uncompress the TDWR products [CODESPLIT] byte [ ] uncompressed ( ByteBuffer buf , int offset , int uncomplen ) throws IOException { byte [ ] header = new byte [ offset ] ; buf . position ( 0 ) ; buf . get ( header ) ; byte [ ] out = new byte [ offset + uncomplen ] ; System . arraycopy ( header , 0 , out , 0 , offset ) ; CBZip2InputStream cbzip2 = new CBZip2InputStream ( ) ; int numCompBytes = buf . remaining ( ) ; byte [ ] bufc = new byte [ numCompBytes ] ; buf . get ( bufc , 0 , numCompBytes ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( bufc , 2 , numCompBytes - 2 ) ; //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis);\r cbzip2 . setStream ( bis ) ; int total = 0 ; int nread ; byte [ ] ubuff = new byte [ 40000 ] ; byte [ ] obuff = new byte [ 40000 ] ; try { while ( ( nread = cbzip2 . read ( ubuff ) ) != - 1 ) { if ( total + nread > obuff . length ) { byte [ ] temp = obuff ; obuff = new byte [ temp . length * 2 ] ; System . arraycopy ( temp , 0 , obuff , 0 , temp . length ) ; } System . arraycopy ( ubuff , 0 , obuff , total , nread ) ; total += nread ; } if ( obuff . length >= 0 ) System . arraycopy ( obuff , 0 , out , offset , total ) ; } catch ( BZip2ReadException ioe ) { log . warn ( \"Nexrad2IOSP.uncompress \" + raf . getLocation ( ) , ioe ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * * Name : read_dividlen * * Purpose : Read divider ID header from NEXRAD Level III product * [CODESPLIT] Sinfo read_dividlen ( ByteBuffer buf , int offset ) { byte [ ] b2 = new byte [ 2 ] ; byte [ ] b4 = new byte [ 4 ] ; short D_divider ; short D_id ; Short tShort ; buf . position ( offset ) ; buf . get ( b2 , 0 , 2 ) ; tShort = ( Short ) convert ( b2 , DataType . SHORT , - 1 ) ; D_divider = tShort . shortValue ( ) ; buf . get ( b2 , 0 , 2 ) ; D_id = ( short ) getInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; block_length = getInt ( b4 , 4 ) ; buf . get ( b2 , 0 , 2 ) ; number_layers = ( short ) getInt ( b2 , 2 ) ; return new Sinfo ( D_divider , D_id , block_length , number_layers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * * Name : read_msghead * * Purpose : Read message header from NEXRAD Level III product * * [CODESPLIT] int read_msghead ( ByteBuffer buf , int offset ) { byte [ ] b2 = new byte [ 2 ] ; byte [ ] b4 = new byte [ 4 ] ; buf . position ( 0 ) ; buf . get ( b2 , 0 , 2 ) ; mcode = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; mdate = ( short ) getInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; mtime = getInt ( b4 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; //out.println( \"product date is \" + dstring);\r mlength = getInt ( b4 , 4 ) ; buf . get ( b2 , 0 , 2 ) ; msource = ( short ) getInt ( b2 , 2 ) ; if ( stationId == null || stationName == null ) { try { NexradStationDB . init ( ) ; // make sure database is initialized\r NexradStationDB . Station station = NexradStationDB . getByIdNumber ( \"000\" + Short . toString ( msource ) ) ; if ( station != null ) { stationId = station . id ; stationName = station . name ; } } catch ( IOException ioe ) { log . error ( \"NexradStationDB.init \" + raf . getLocation ( ) , ioe ) ; } } buf . get ( b2 , 0 , 2 ) ; mdestId = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; mNumOfBlock = ( short ) getInt ( b2 , 2 ) ; return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get unsigned integer from byte array [CODESPLIT] int getUInt ( byte [ ] b , int num ) { int base = 1 ; int i ; int word = 0 ; int bv [ ] = new int [ num ] ; for ( i = 0 ; i < num ; i ++ ) { bv [ i ] = convertunsignedByte2Short ( b [ i ] ) ; } /*\r\n        ** Calculate the integer value of the byte sequence\r\n        */ for ( i = num - 1 ; i >= 0 ; i -- ) { word += base * bv [ i ] ; base *= 256 ; } return word ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get signed integer from bytes [CODESPLIT] int getInt ( byte [ ] b , int num ) { int base = 1 ; int i ; int word = 0 ; int bv [ ] = new int [ num ] ; for ( i = 0 ; i < num ; i ++ ) { bv [ i ] = convertunsignedByte2Short ( b [ i ] ) ; } if ( bv [ 0 ] > 127 ) { bv [ 0 ] -= 128 ; base = - 1 ; } /*\r\n        ** Calculate the integer value of the byte sequence\r\n        */ for ( i = num - 1 ; i >= 0 ; i -- ) { word += base * bv [ i ] ; base *= 256 ; } return word ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * * Name : read_proddesc * * Purpose : Read product description header from NEXRAD Level III product * * [CODESPLIT] Pinfo read_proddesc ( ByteBuffer buf , int offset ) { byte [ ] b2 = new byte [ 2 ] ; byte [ ] b4 = new byte [ 4 ] ; int off = offset ; Short tShort ; Integer tInt ; //Double tDouble = null;\r /* thredds global att */ ncfile . addAttribute ( null , new Attribute ( \"title\" , \"Nexrad Level 3 Data\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"keywords\" , \"WSR-88D; NIDS\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"creator_name\" , \"NOAA/NWS\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"creator_url\" , \"http://www.ncdc.noaa.gov/oa/radar/radarproducts.html\" ) ) ; ncfile . addAttribute ( null , new Attribute ( \"naming_authority\" , \"NOAA/NCDC\" ) ) ; //      ncfile.addAttribute(null, new Attribute(\"keywords_vocabulary\", cname));\r //out.println( \"offset of buffer is \" + off);\r buf . position ( offset ) ; buf . get ( b2 , 0 , 2 ) ; tShort = ( Short ) convert ( b2 , DataType . SHORT , - 1 ) ; divider = tShort . shortValue ( ) ; ncfile . addAttribute ( null , new Attribute ( \"Divider\" , tShort ) ) ; buf . get ( b4 , 0 , 4 ) ; tInt = ( Integer ) convert ( b4 , DataType . INT , - 1 ) ; latitude = tInt . intValue ( ) / 1000.0 ; buf . get ( b4 , 0 , 4 ) ; tInt = ( Integer ) convert ( b4 , DataType . INT , - 1 ) ; longitude = tInt . intValue ( ) / 1000.0 ; buf . get ( b2 , 0 , 2 ) ; height = getInt ( b2 , 2 ) * 0.3048 ; // LOOK now in units of meters\r if ( useStationDB ) { // override by station table for more accuracy\r try { NexradStationDB . init ( ) ; // make sure database is initialized\r NexradStationDB . Station station = NexradStationDB . get ( \"K\" + stationId ) ; if ( station != null ) { latitude = station . lat ; longitude = station . lon ; height = station . elev ; stationName = station . name ; } } catch ( IOException ioe ) { log . error ( \"NexradStationDB.init \" + raf . getLocation ( ) , ioe ) ; } } ncfile . addAttribute ( null , new Attribute ( \"RadarLatitude\" , new Double ( latitude ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"RadarLongitude\" , new Double ( longitude ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"RadarAltitude\" , new Double ( height ) ) ) ; buf . get ( b2 , 0 , 2 ) ; pcode = ( short ) getInt ( b2 , 2 ) ; if ( stationId != null ) ncfile . addAttribute ( null , new Attribute ( \"ProductStation\" , stationId ) ) ; if ( stationName != null ) ncfile . addAttribute ( null , new Attribute ( \"ProductStationName\" , stationName ) ) ; buf . get ( b2 , 0 , 2 ) ; opmode = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( \"OperationalMode\" , new Short ( opmode ) ) ) ; buf . get ( b2 , 0 , 2 ) ; volumnScanPattern = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( \"VolumeCoveragePatternName\" , new Short ( volumnScanPattern ) ) ) ; buf . get ( b2 , 0 , 2 ) ; sequenceNumber = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( \"SequenceNumber\" , new Short ( sequenceNumber ) ) ) ; buf . get ( b2 , 0 , 2 ) ; volumeScanNumber = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( \"VolumeScanNumber\" , new Short ( volumeScanNumber ) ) ) ; buf . get ( b2 , 0 , 2 ) ; volumeScanDate = ( short ) getUInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; volumeScanTime = getUInt ( b4 , 4 ) ; buf . get ( b2 , 0 , 2 ) ; productDate = ( short ) getUInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; productTime = getUInt ( b4 , 4 ) ; java . util . Date pDate = getDate ( productDate , productTime * 1000 ) ; String dstring = formatter . toDateTimeStringISO ( pDate ) ; ncfile . addAttribute ( null , new Attribute ( \"DateCreated\" , dstring ) ) ; buf . get ( b2 , 0 , 2 ) ; p1 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p2 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; elevationNumber = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( \"ElevationNumber\" , new Short ( elevationNumber ) ) ) ; buf . get ( b2 , 0 , 2 ) ; p3 = ( short ) getInt ( b2 , 2 ) ; off += 40 ; if ( pcode == 182 || pcode == 186 || pcode == 32 || pcode == 94 || pcode == 99 ) { for ( int i = 0 ; i < 16 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) bytesToInt ( b2 [ 0 ] , b2 [ 1 ] , false ) ; } } else if ( pcode == 159 || pcode == 161 || pcode == 163 || pcode == 170 || pcode == 172 || pcode == 173 || pcode == 174 || pcode == 175 ) { // Scale hw 31 32\r buf . get ( b4 , 0 , 4 ) ; byte [ ] b44 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 0 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b44 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) * 100 ) ; // offset  hw 33 34\r buf . get ( b4 , 0 , 4 ) ; byte [ ] b45 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 1 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b45 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) * 100 ) ; //  hw 35 reserve\r buf . get ( b2 , 0 , 2 ) ; threshold [ 2 ] = 0 ; // hw 36, 37, 38\r for ( int i = 3 ; i < 6 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) bytesToInt ( b2 [ 0 ] , b2 [ 1 ] , false ) ; } buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; } else if ( pcode == 176 ) { // Scale hw 31 32\r buf . get ( b4 , 0 , 4 ) ; byte [ ] b44 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 0 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b44 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) ) ; // offset  hw 33 34\r buf . get ( b4 , 0 , 4 ) ; byte [ ] b45 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 1 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b45 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) ) ; //  hw 35 reserve\r buf . get ( b2 , 0 , 2 ) ; threshold [ 2 ] = 0 ; // hw 36, 37, 38\r for ( int i = 3 ; i < 6 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) bytesToInt ( b2 [ 0 ] , b2 [ 1 ] , false ) ; } buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; } else { for ( int i = 0 ; i < 16 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) getInt ( b2 , 2 ) ; } } off += 32 ; buf . get ( b2 , 0 , 2 ) ; p4 = ( short ) getInt ( b2 , 2 ) ; //int t1 = getUInt(b2, 2);\r buf . get ( b2 , 0 , 2 ) ; p5 = ( short ) getInt ( b2 , 2 ) ; //t1 = getUInt(b2, 2);\r buf . get ( b2 , 0 , 2 ) ; p6 = ( short ) getInt ( b2 , 2 ) ; //t1 = getUInt(b2, 2);\r buf . get ( b2 , 0 , 2 ) ; p7 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p8 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p9 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p10 = ( short ) getUInt ( b2 , 2 ) ; //bytesToInt(b2[0], b2[1], true); //       getInt(b2, 2); //\r off += 14 ; buf . get ( b2 , 0 , 2 ) ; numberOfMaps = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( \"NumberOfMaps\" , new Short ( numberOfMaps ) ) ) ; off += 2 ; buf . get ( b4 , 0 , 4 ) ; //tInt = (Integer)convert(b4, DataType.INT, -1);\r offsetToSymbologyBlock = getInt ( b4 , 4 ) ; //ncfile.addAttribute(null, new Attribute(\"offset_symbology_block\",new Integer(offsetToSymbologyBlock)));\r off += 4 ; buf . get ( b4 , 0 , 4 ) ; //tInt = (Integer)convert(b4, DataType.INT, -1);\r offsetToGraphicBlock = getInt ( b4 , 4 ) ; //ncfile.addAttribute(null, new Attribute(\"offset_graphic_block\",new Integer(offsetToGraphicBlock)));\r off += 4 ; buf . get ( b4 , 0 , 4 ) ; //tInt = (Integer)convert(b4, DataType.INT, -1);\r offsetToTabularBlock = getInt ( b4 , 4 ) ; //ncfile.addAttribute(null, new Attribute(\"offset_tabular_block\",new Integer(offsetToTabularBlock)));\r off += 4 ; return new Pinfo ( divider , latitude , longitude , height , pcode , opmode , threshold , sequenceNumber , volumeScanNumber , volumeScanDate , volumeScanTime , productDate , productTime , p1 , p2 , p3 , p4 , p5 , p6 , p7 , p8 , p9 , p10 , elevationNumber , numberOfMaps , offsetToSymbologyBlock , offsetToGraphicBlock , offsetToTabularBlock ) ; //return pinfo;\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this converts a byte array to another primitive array [CODESPLIT] protected Object convert ( byte [ ] barray , DataType dataType , int nelems , int byteOrder ) { if ( dataType == DataType . BYTE ) { return barray ; } if ( dataType == DataType . CHAR ) { return IospHelper . convertByteToChar ( barray ) ; } ByteBuffer bbuff = ByteBuffer . wrap ( barray ) ; if ( byteOrder >= 0 ) bbuff . order ( byteOrder == ucar . unidata . io . RandomAccessFile . LITTLE_ENDIAN ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; if ( dataType == DataType . SHORT ) { ShortBuffer tbuff = bbuff . asShortBuffer ( ) ; short [ ] pa = new short [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . INT ) { IntBuffer tbuff = bbuff . asIntBuffer ( ) ; int [ ] pa = new int [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . FLOAT ) { FloatBuffer tbuff = bbuff . asFloatBuffer ( ) ; float [ ] pa = new float [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . DOUBLE ) { DoubleBuffer tbuff = bbuff . asDoubleBuffer ( ) ; double [ ] pa = new double [ nelems ] ; tbuff . get ( pa ) ; return pa ; } throw new IllegalStateException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this converts a byte array to a wrapped primitive ( Byte Short Integer Double Float Long ) [CODESPLIT] protected Object convert ( byte [ ] barray , DataType dataType , int byteOrder ) { if ( dataType == DataType . BYTE ) { return new Byte ( barray [ 0 ] ) ; } if ( dataType == DataType . CHAR ) { return new Character ( ( char ) barray [ 0 ] ) ; } ByteBuffer bbuff = ByteBuffer . wrap ( barray ) ; if ( byteOrder >= 0 ) bbuff . order ( byteOrder == ucar . unidata . io . RandomAccessFile . LITTLE_ENDIAN ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; if ( dataType == DataType . SHORT ) { ShortBuffer tbuff = bbuff . asShortBuffer ( ) ; return new Short ( tbuff . get ( ) ) ; } else if ( dataType == DataType . INT ) { IntBuffer tbuff = bbuff . asIntBuffer ( ) ; return new Integer ( tbuff . get ( ) ) ; } else if ( dataType == DataType . LONG ) { LongBuffer tbuff = bbuff . asLongBuffer ( ) ; return new Long ( tbuff . get ( ) ) ; } else if ( dataType == DataType . FLOAT ) { FloatBuffer tbuff = bbuff . asFloatBuffer ( ) ; return new Float ( tbuff . get ( ) ) ; } else if ( dataType == DataType . DOUBLE ) { DoubleBuffer tbuff = bbuff . asDoubleBuffer ( ) ; return new Double ( tbuff . get ( ) ) ; } throw new IllegalStateException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Name : IsZlibed [CODESPLIT] int isZlibHed ( byte [ ] buf ) { short b0 = convertunsignedByte2Short ( buf [ 0 ] ) ; short b1 = convertunsignedByte2Short ( buf [ 1 ] ) ; if ( ( b0 & 0xf ) == Z_DEFLATED ) { if ( ( b0 >> 4 ) + 8 <= DEF_WBITS ) { if ( ( ( ( b0 << 8 ) + b1 ) % 31 ) == 0 ) { return 1 ; } } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * * Name : IsEncrypt * * Purpose : Check a two - byte sequence to see if it indicates the start of * an encrypted image . * [CODESPLIT] int IsEncrypt ( byte [ ] buf ) { /*\r\n        ** These tests were deduced from inspection from encrypted NOAAPORT files.\r\n        */ String b = new String ( buf , CDM . utf8Charset ) ; if ( b . startsWith ( \"R3\" ) ) { return 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * * Name : GetZlibedNexr * * Purpose : Read bytes from a NEXRAD Level III product into a buffer * This routine reads compressed image data for Level III formatted file . * We referenced McIDAS GetNexrLine function [CODESPLIT] byte [ ] GetZlibedNexr ( byte [ ] buf , int buflen , int hoff ) throws IOException { //byte[]  uncompr = new byte[ZLIB_BUF_LEN ]; /* decompression buffer          */\r //long    uncomprLen = ZLIB_BUF_LEN;        /* length of decompress space    */\r int doff ; /* # bytes offset to image       */ int numin ; /* # input bytes processed       */ numin = buflen - hoff ; if ( numin <= 0 ) { log . warn ( \" No compressed data to inflate \" + raf . getLocation ( ) ) ; return null ; } //byte[]  compr = new byte[numin-4];  /* compressed portion */\r /*\r\n      ** Uncompress first portion of the image.  This should include:\r\n      **\r\n      **     SHO\\r\\r\\n             <--+\r\n      **     SEQ#\\r\\r\\n               |  hoff bytes long\r\n      **     WMO header\\r\\r\\n         |\r\n      **     PIL\\r\\r\\n             <--+\r\n      **\r\n      **  -> CCB\r\n      **     WMO header\r\n      **     PIL\r\n      **     portion of the image\r\n      **\r\n      */ /* a new copy of buff with only compressed bytes */ System . arraycopy ( buf , hoff , buf , hoff , numin - 4 ) ; // decompress the bytes\r int resultLength ; int result = 0 ; // byte[] inflateData = null;\r byte [ ] tmp ; int uncompLen = 24500 ; /* length of decompress space    */ byte [ ] uncomp = new byte [ uncompLen ] ; Inflater inflater = new Inflater ( false ) ; inflater . setInput ( buf , hoff , numin - 4 ) ; int offset = 0 ; int limit = 20000 ; while ( inflater . getRemaining ( ) > 0 ) { try { resultLength = inflater . inflate ( uncomp , offset , 4000 ) ; } catch ( DataFormatException ex ) { //System.out.println(\"ERROR on inflation \"+ex.getMessage());\r //ex.printStackTrace();\r log . error ( \"nids Inflater\" , ex ) ; throw new IOException ( ex . getMessage ( ) , ex ) ; } offset = offset + resultLength ; result = result + resultLength ; if ( result > limit ) { // when uncomp data larger then limit, the uncomp need to increase size\r tmp = new byte [ result ] ; System . arraycopy ( uncomp , 0 , tmp , 0 , result ) ; uncompLen = uncompLen + 10000 ; uncomp = new byte [ uncompLen ] ; System . arraycopy ( tmp , 0 , uncomp , 0 , result ) ; } if ( resultLength == 0 ) { int tt = inflater . getRemaining ( ) ; byte [ ] b2 = new byte [ 2 ] ; System . arraycopy ( buf , hoff + numin - 4 - tt , b2 , 0 , 2 ) ; if ( result + tt > uncompLen ) { tmp = new byte [ result ] ; System . arraycopy ( uncomp , 0 , tmp , 0 , result ) ; uncompLen = uncompLen + 10000 ; uncomp = new byte [ uncompLen ] ; System . arraycopy ( tmp , 0 , uncomp , 0 , result ) ; } if ( isZlibHed ( b2 ) == 0 ) { System . arraycopy ( buf , hoff + numin - 4 - tt , uncomp , result , tt ) ; result = result + tt ; break ; } inflater . reset ( ) ; inflater . setInput ( buf , hoff + numin - 4 - tt , tt ) ; } } inflater . end ( ) ; /*\r\n      ** Find out how long CCB is.  This is done by using the lower order\r\n      ** 6 bits from the first uncompressed byte and all 8 bits of the\r\n      ** second uncompressed byte.\r\n      */ doff = 2 * ( ( ( uncomp [ 0 ] & 0x3f ) << 8 ) | ( uncomp [ 1 ] & 0xFF ) ) ; for ( int i = 0 ; i < 2 ; i ++ ) { /* eat WMO and PIL */ while ( ( doff < result ) && ( uncomp [ doff ] != ' ' ) ) doff ++ ; doff ++ ; } byte [ ] data = new byte [ result - doff ] ; System . arraycopy ( uncomp , doff , data , 0 , result - doff ) ; //\r /*\r\n      ** Copy header bytes to decompression buffer.  The objective is to\r\n      ** create an output buffer that looks like an uncompressed NOAAPORT\r\n      ** NEXRAD product:\r\n      **\r\n      **   Section               Product               Example             End\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      1     |        start of product        | CTRL-A              \\r\\r\\n\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      2     |        sequence number         | 237                 \\r\\r\\n\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      3     |          WMO header            | SDUS53 KARX 062213  \\r\\r\\n\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      4     |             PIL                | N0RARX              \\r\\r\\n\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      5     |                                | AAO130006R2 CH-1\r\n      **            |                                | Interface Control\r\n      **            |             CCB                | Document (ICD)\r\n      **            |                                | for the NWS NWSTG\r\n      **            |                                | Figure 7-1 p 38\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      6     |          WMO header            | SDUS53 KARX 062213  \\r\\r\\n\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      7     |             PIL                | N0RARX              \\r\\r\\n\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **            |                                |\r\n      **            |                                |\r\n      **            |                                |\r\n      **      8     |            image               |\r\n      **            |                                |\r\n      **            |                                |\r\n      **            |                                |\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **      9     |            trailer             | \\r\\r\\nETX\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **            |                                |\r\n      **     10     |     Unidata floater trailer    | \\0\\0\r\n      **            |                                |\r\n      **            +--------------------------------+\r\n      **\r\n      ** Sections 5-8 are zlib compressed.  They must be uncompressed and\r\n      ** read to find out where the image begins.  When this is done, sections\r\n      ** 5-7 are thrown away and 8 is returned immediately following 4.\r\n      ** Section 9 and, if it is there, section 10 are also thrown away.\r\n      **\r\n      */ return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * * Name : code_lookup * * Purpose : Derive some derivable metadata * [CODESPLIT] static int code_typelookup ( int code ) { int type ; final int [ ] types = { Other , Other , Other , Other , Other , /*   0-  9 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /*  10- 19 */ Other , Base_Reflect , Base_Reflect , Base_Reflect , Base_Reflect , BaseReflect248 , Base_Reflect , Velocity , /*  20- 29 */ Velocity , Velocity , Velocity , Velocity , Velocity , SPECTRUM , SPECTRUM , SPECTRUM , Other , DigitalHybridReflect , Other , Other , /*  30- 39 */ Comp_Reflect , Comp_Reflect , Comp_Reflect , Comp_Reflect , Other , Other , Echo_Tops , Other , Other , Other , /*  40- 49 */ Other , Other , Other , VAD , Other , Other , Other , Other , Other , Other , /*  50- 59 */ StrmRelMeanVel , StrmRelMeanVel , Vert_Liquid , Other , Other , Other , Other , Other , Layer_Reflect_Avg , /*  60- 69 */ Layer_Reflect_Avg , Layer_Reflect_Max , Layer_Reflect_Max , Other , Other , Other , Other , Other , Other , Other , Other , /*  70- 79 */ Other , Other , Other , Precip_1 , Precip_3 , Precip_Accum , Precip_Array , Other , /*  80- 89 */ Other , Other , Other , Other , Other , Other , Layer_Reflect_Avg , Layer_Reflect_Max , Other , Other , Other , /*  90- 99 */ BaseReflectivityDR , Other , Other , Other , Other , BaseVelocityDV , Other , Other , Other , Other , Other , /* 100-109 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /* 110-119 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /* 120-129 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , DigitalVert_Liquid , /* 130-139 */ EnhancedEcho_Tops , Other , Other , DigitalStormTotalPrecip , Other , Other , Other , Other , Other , Other , /* 140-149 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /* 150-159 */ Other , Other , Other , Other , DigitalDifferentialReflectivity , Other , DigitalCorrelationCoefficient , Other , DigitalDifferentialPhase , Other , /* 160-169 */ HydrometeorClassification , Other , Other , Other , OneHourAccumulation , DigitalAccumulationArray , StormTotalAccumulation , DigitalStormTotalAccumulation , Accumulation3Hour , Digital1HourDifferenceAccumulation , /* 170-179 */ DigitalTotalDifferenceAccumulation , DigitalInstantaneousPrecipitationRate , HypridHydrometeorClassification , Other , Other , Reflect1 , Reflect1 , Velocity1 , Velocity1 , Other , /* 180-189 */ SPECTRUM1 , Reflect1 , Reflect1 , Other , Other , } ; if ( code < 0 || code > 189 ) type = Other ; else type = types [ code ] ; return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * product id table [CODESPLIT] static String pname_lookup ( int code , int elevation ) { String pname = null ; switch ( code ) { case 15 : if ( elevation == 1 ) pname = \"NAX\" ; else if ( elevation == 3 ) pname = \"NBX\" ; else pname = \"N\" + elevation / 2 + \"X\" ; break ; case 16 : if ( elevation == 1 ) pname = \"NAC\" ; else if ( elevation == 3 ) pname = \"NBC\" ; else pname = \"N\" + elevation / 2 + \"C\" ; break ; case 17 : if ( elevation == 1 ) pname = \"NAK\" ; else if ( elevation == 3 ) pname = \"NBK\" ; else pname = \"N\" + elevation / 2 + \"K\" ; break ; case 18 : if ( elevation == 1 ) pname = \"NAH\" ; else if ( elevation == 3 ) pname = \"NBH\" ; else pname = \"N\" + elevation / 2 + \"H\" ; break ; case 19 : pname = \"N\" + elevation + \"R\" ; break ; case 20 : pname = \"N0Z\" ; break ; case 25 : pname = \"N0W\" ; break ; case 27 : pname = \"N\" + elevation + \"V\" ; break ; case 28 : pname = \"NSP\" ; break ; case 30 : pname = \"NSW\" ; break ; case 36 : pname = \"NCO\" ; break ; case 37 : pname = \"NCR\" ; break ; case 38 : pname = \"NCZ\" ; break ; case 41 : pname = \"NET\" ; break ; case 48 : pname = \"NVW\" ; break ; case 56 : pname = \"N\" + elevation + \"S\" ; break ; case 57 : pname = \"NVL\" ; break ; case 65 : pname = \"NLL\" ; break ; case 66 : pname = \"NML\" ; break ; case 78 : pname = \"N1P\" ; break ; case 79 : pname = \"N3P\" ; break ; case 80 : pname = \"NTP\" ; break ; case 81 : pname = \"DPA\" ; break ; case 90 : pname = \"NHL\" ; break ; case 94 : if ( elevation == 1 ) pname = \"NAQ\" ; else if ( elevation == 3 ) pname = \"NBQ\" ; else pname = \"N\" + elevation / 2 + \"Q\" ; break ; case 99 : if ( elevation == 1 ) pname = \"NAU\" ; else if ( elevation == 3 ) pname = \"NBU\" ; else pname = \"N\" + elevation / 2 + \"U\" ; break ; case 134 : pname = \"DVL\" ; break ; case 135 : pname = \"EET\" ; break ; case 182 : pname = \"DV\" ; break ; case 187 : case 181 : pname = \"R\" ; break ; case 186 : case 180 : pname = \"DR\" ; break ; case 183 : pname = \"V\" ; break ; case 185 : pname = \"SW\" ; break ; default : break ; } return pname ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * product resolution [CODESPLIT] static double code_reslookup ( int code ) { double data_res ; final double [ ] res = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*   0-  9 */ 0 , 0 , 0 , 0 , 0 , 0 , 1 , 2 , 4 , 1 , /*  10- 19 */ 2 , 4 , 0.25 , 0.5 , 1 , 0.25 , 0.5 , 1 , 0.25 , 0 , /*  20- 29 */ 1 , 0 , 1 , 0 , 0 , 1 , 4 , 1 , 4 , 0 , /*  30- 39 */ 0 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*  40- 49 */ 0 , 0 , 0 , 0 , 0 , 0.5 , 1 , 4 , 0 , 0 , /*  50- 59 */ 0 , 0 , 0 , 4 , 4 , 4 , 4 , 0 , 0 , 0 , /*  60- 69 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , /*  70- 79 */ 1 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 4 , /*  80- 89 */ 4 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0.25 , /*  90- 99 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 100-109 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 110-119 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 120-129 */ 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , /* 130-139 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 140-149 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0.25 , /* 150-159 */ 0 , 0.25 , 0 , 0.25 , 0 , 0.25 , 0 , 0 , 0 , 2 , /* 160-169 */ 0.25 , 2 , 0.25 , 0.25 , 0.25 , 0.25 , 0.25 , 0.25 , 0 , 0 , /* 170-179 */ 0 , 150.0 , 150.0 , 0 , 0 , 0 , 300.0 , 0 , 0 , 0 , /* 180-189 */ } ; if ( code < 0 || code > 189 ) data_res = 0 ; else data_res = res [ code ] ; return data_res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * product level tabel [CODESPLIT] static int code_levelslookup ( int code ) { int level ; final int [ ] levels = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*   0-  9 */ 0 , 0 , 0 , 0 , 0 , 0 , 8 , 8 , 8 , 16 , /*  10- 19 */ 16 , 16 , 8 , 8 , 8 , 16 , 16 , 16 , 8 , 0 , /*  20- 29 */ 8 , 0 , 256 , 0 , 0 , 8 , 8 , 16 , 16 , 0 , /*  30- 39 */ 0 , 16 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*  40- 49 */ 0 , 0 , 0 , 0 , 0 , 16 , 16 , 16 , 0 , 0 , /*  50- 59 */ 0 , 0 , 0 , 8 , 8 , 8 , 8 , 0 , 0 , 0 , /*  60- 69 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 16 , 16 , /*  70- 79 */ 16 , 256 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 8 , /*  80- 89 */ 8 , 0 , 0 , 0 , 256 , 0 , 0 , 0 , 0 , 256 , /*  90- 99 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 100-109 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 110-119 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 120-129 */ 0 , 0 , 0 , 0 , 256 , 199 , 0 , 0 , 256 , 0 , /* 130-139 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 140-149 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 256 , /* 150-159 */ 0 , 256 , 0 , 256 , 0 , 256 , 0 , 0 , 0 , 16 , /* 160-169 */ 256 , 16 , 256 , 256 , 0 , 0 , 0 , 16 , 0 , 0 , /* 170-179 */ 0 , 16 , 256 , 0 , 0 , 0 , 256 , 0 , 0 , 0 , /* 180-189 */ } ; if ( code < 0 || code > 189 ) level = 0 ; else level = levels [ code ] ; return level ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////// [CODESPLIT] public void init ( ) throws ServletException { org . slf4j . Logger logServerStartup = org . slf4j . LoggerFactory . getLogger ( \"serverStartup\" ) ; logServerStartup . info ( getClass ( ) . getName ( ) + \" initialization start\" ) ; try { System . setProperty ( \"file.encoding\" , \"UTF-8\" ) ; Field charset = Charset . class . getDeclaredField ( \"defaultCharset\" ) ; charset . setAccessible ( true ) ; charset . set ( null , null ) ; initialize ( ) ; } catch ( Exception e ) { throw new ServletException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Primary Controller Entry Point [CODESPLIT] public void handleRequest ( HttpServletRequest req , HttpServletResponse res ) throws IOException { DapLog . debug ( \"doGet(): User-Agent = \" + req . getHeader ( \"User-Agent\" ) ) ; if ( ! this . initialized ) initialize ( ) ; DapRequest daprequest = getRequestState ( req , res ) ; String url = daprequest . getOriginalURL ( ) ; StringBuilder info = new StringBuilder ( \"doGet():\" ) ; info . append ( \" dataset = \" ) ; info . append ( \" url = \" ) ; info . append ( url ) ; if ( DEBUG ) { System . err . println ( \"DAP4 Servlet: processing url: \" + daprequest . getOriginalURL ( ) ) ; } DapContext dapcxt = new DapContext ( ) ; // Add entries to the context dapcxt . put ( HttpServletRequest . class , req ) ; dapcxt . put ( HttpServletResponse . class , res ) ; dapcxt . put ( DapRequest . class , daprequest ) ; ByteOrder order = daprequest . getOrder ( ) ; ChecksumMode checksummode = daprequest . getChecksumMode ( ) ; dapcxt . put ( Dap4Util . DAP4ENDIANTAG , order ) ; dapcxt . put ( Dap4Util . DAP4CSUMTAG , checksummode ) ; // Transfer all other queries Map < String , String > queries = daprequest . getQueries ( ) ; for ( Map . Entry < String , String > entry : queries . entrySet ( ) ) { if ( dapcxt . get ( entry . getKey ( ) ) == null ) { dapcxt . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } if ( url . endsWith ( FAVICON ) ) { doFavicon ( FAVICON , dapcxt ) ; return ; } String datasetpath = DapUtil . nullify ( DapUtil . canonicalpath ( daprequest . getDataset ( ) ) ) ; try { if ( datasetpath == null ) { // This is the case where a request was made without a dataset; // According to the spec, I think we should return the // services/capabilities document doCapabilities ( daprequest , dapcxt ) ; } else { RequestMode mode = daprequest . getMode ( ) ; if ( mode == null ) throw new DapException ( \"Unrecognized request extension\" ) . setCode ( HttpServletResponse . SC_BAD_REQUEST ) ; switch ( mode ) { case DMR : doDMR ( daprequest , dapcxt ) ; break ; case DAP : doData ( daprequest , dapcxt ) ; break ; case DSR : doDSR ( daprequest , dapcxt ) ; break ; default : throw new DapException ( \"Unrecognized request extension\" ) . setCode ( HttpServletResponse . SC_BAD_REQUEST ) ; } } } catch ( Throwable t ) { t . printStackTrace ( ) ; int code = HttpServletResponse . SC_BAD_REQUEST ; if ( t instanceof DapException ) { DapException e = ( DapException ) t ; code = e . getCode ( ) ; if ( code <= 0 ) code = DapCodes . SC_BAD_REQUEST ; e . setCode ( code ) ; } else if ( t instanceof FileNotFoundException ) code = DapCodes . SC_NOT_FOUND ; else if ( t instanceof UnsupportedOperationException ) code = DapCodes . SC_FORBIDDEN ; else if ( t instanceof MalformedURLException ) code = DapCodes . SC_NOT_FOUND ; else if ( t instanceof IOException ) code = DapCodes . SC_BAD_REQUEST ; else code = DapCodes . SC_INTERNAL_SERVER_ERROR ; senderror ( daprequest , code , t ) ; } //catch }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a DSR request . * [CODESPLIT] protected void doDSR ( DapRequest drq , DapContext cxt ) throws IOException { try { DapDSR dsrbuilder = new DapDSR ( ) ; String dsr = dsrbuilder . generate ( drq . getURL ( ) ) ; OutputStream out = drq . getOutputStream ( ) ; addCommonHeaders ( drq ) ; // Add relevant headers // Wrap the outputstream with a Chunk writer ByteOrder order = ( ByteOrder ) cxt . get ( Dap4Util . DAP4ENDIANTAG ) ; ChunkWriter cw = new ChunkWriter ( out , RequestMode . DSR , order ) ; cw . writeDSR ( dsr ) ; cw . close ( ) ; } catch ( IOException ioe ) { throw new DapException ( \"DSR generation error\" , ioe ) . setCode ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a DMR request . [CODESPLIT] protected void doDMR ( DapRequest drq , DapContext cxt ) throws IOException { // Convert the url to an absolute path String realpath = getResourcePath ( drq , drq . getDatasetPath ( ) ) ; DSP dsp = DapCache . open ( realpath , cxt ) ; DapDataset dmr = dsp . getDMR ( ) ; /* Annotate with our endianness */ ByteOrder order = ( ByteOrder ) cxt . get ( Dap4Util . DAP4ENDIANTAG ) ; setEndianness ( dmr , order ) ; // Process any constraint view CEConstraint ce = null ; String sce = drq . queryLookup ( DapProtocol . CONSTRAINTTAG ) ; ce = CEConstraint . compile ( sce , dmr ) ; setConstraint ( dmr , ce ) ; // Provide a PrintWriter for capturing the DMR. StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; // Get the DMR as a string DMRPrinter dapprinter = new DMRPrinter ( dmr , ce , pw , drq . getFormat ( ) ) ; if ( cxt . get ( Dap4Util . DAP4TESTTAG ) != null ) dapprinter . testprint ( ) ; else dapprinter . print ( ) ; pw . close ( ) ; sw . close ( ) ; String sdmr = sw . toString ( ) ; if ( DEBUG ) System . err . println ( \"Sending: DMR:\\n\" + sdmr ) ; addCommonHeaders ( drq ) ; // Add relevant headers // Wrap the outputstream with a Chunk writer OutputStream out = drq . getOutputStream ( ) ; ChunkWriter cw = new ChunkWriter ( out , RequestMode . DMR , order ) ; cw . cacheDMR ( sdmr ) ; cw . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a DataDMR request . Note that if this throws an exception then it has not yet started to output a response . It a response had been initiated then the exception would produce an error chunk . <p > * [CODESPLIT] protected void doData ( DapRequest drq , DapContext cxt ) throws IOException { // Convert the url to an absolute path String realpath = getResourcePath ( drq , drq . getDatasetPath ( ) ) ; DSP dsp = DapCache . open ( realpath , cxt ) ; if ( dsp == null ) throw new DapException ( \"No such file: \" + drq . getResourceRoot ( ) ) ; DapDataset dmr = dsp . getDMR ( ) ; if ( DUMPDMR ) { printDMR ( dmr ) ; System . err . println ( printDMR ( dmr ) ) ; System . err . flush ( ) ; } /* Annotate with our endianness */ ByteOrder order = ( ByteOrder ) cxt . get ( Dap4Util . DAP4ENDIANTAG ) ; setEndianness ( dmr , order ) ; // Process any constraint CEConstraint ce = null ; String sce = drq . queryLookup ( DapProtocol . CONSTRAINTTAG ) ; ce = CEConstraint . compile ( sce , dmr ) ; setConstraint ( dmr , ce ) ; StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; // Get the DMR as a string DMRPrinter dapprinter = new DMRPrinter ( dmr , ce , pw , drq . getFormat ( ) ) ; dapprinter . print ( ) ; pw . close ( ) ; sw . close ( ) ; String sdmr = sw . toString ( ) ; if ( DEBUG || DUMPDMR ) System . err . println ( \"Sending: Data DMR:\\n\" + sdmr ) ; // Wrap the outputstream with a Chunk writer OutputStream out = drq . getOutputStream ( ) ; ChunkWriter cw = new ChunkWriter ( out , RequestMode . DAP , order ) ; cw . setWriteLimit ( getBinaryWriteLimit ( ) ) ; cw . cacheDMR ( sdmr ) ; cw . flush ( ) ; addCommonHeaders ( drq ) ; // Dump the databuffer part switch ( drq . getFormat ( ) ) { case TEXT : case XML : case HTML : throw new IOException ( \"Unsupported return format: \" + drq . getFormat ( ) ) ; /*\n            sw = new StringWriter();\n            DAPPrint dp = new DAPPrint(sw);\n            dp.print(dsp.getDataset(), ce);\n            break;\n                */ case NONE : default : DapSerializer writer = new DapSerializer ( dsp , ce , cw , order , drq . getChecksumMode ( ) ) ; writer . write ( dsp . getDMR ( ) ) ; cw . flush ( ) ; cw . close ( ) ; break ; } // Should we dump data? if ( DUMPDATA ) { byte [ ] data = cw . getDump ( ) ; if ( data != null ) DapDump . dumpbytestream ( data , cw . getWriteOrder ( ) , \"ChunkWriter.write\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility Methods [CODESPLIT] protected void addCommonHeaders ( DapRequest drq ) throws IOException { // Add relevant headers ResponseFormat format = drq . getFormat ( ) ; if ( format == null ) format = ResponseFormat . NONE ; DapProtocol . ContentType contentheaders = DapProtocol . contenttypes . get ( drq . getMode ( ) ) ; String header = contentheaders . getFormat ( format ) ; if ( header != null ) { header = header + \"; charset=utf-8\" ; drq . setResponseHeader ( \"Content-Type\" , header ) ; } else DapLog . error ( \"Cannot determine response Content-Type\" ) ; // Not sure what this should be yet //setHeader(\"Content-Description\",\"?\"); // Again, not sure what value to use //setHeader(\"Content-Disposition\",\"?\"); //not legal drq.setResponseHeader(\"Content-Encoding\", IS_BIG_ENDIAN ? BIG_ENDIAN : LITTLE_ENDIAN); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge the servlet inputs into a single object for easier transport as well as adding value . [CODESPLIT] protected DapRequest getRequestState ( HttpServletRequest rq , HttpServletResponse rsp ) throws IOException { return new DapRequest ( this , rq , rsp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate an error based on the parameters [CODESPLIT] protected void senderror ( DapRequest drq , int httpcode , Throwable t ) throws IOException { if ( httpcode == 0 ) httpcode = HttpServletResponse . SC_BAD_REQUEST ; ErrorResponse err = new ErrorResponse ( ) ; err . setCode ( httpcode ) ; if ( t == null ) { err . setMessage ( \"Servlet error: \" + drq . getURL ( ) ) ; } else { StringWriter sw = new StringWriter ( ) ; PrintWriter p = new PrintWriter ( sw ) ; t . printStackTrace ( p ) ; p . close ( ) ; sw . close ( ) ; err . setMessage ( sw . toString ( ) ) ; } err . setContext ( drq . getURL ( ) ) ; String errormsg = err . buildXML ( ) ; drq . getResponse ( ) . sendError ( httpcode , errormsg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set special attribute : endianness : overwrite exiting value [CODESPLIT] void setEndianness ( DapDataset dmr , ByteOrder order ) throws DapException { DapAttribute a = dmr . findAttribute ( DapUtil . LITTLEENDIANATTRNAME ) ; if ( a == null ) { a = new DapAttribute ( DapUtil . LITTLEENDIANATTRNAME , DapType . UINT8 ) ; dmr . addAttribute ( a ) ; } //ByteOrder order = (ByteOrder) cxt.get(Dap4Util.DAP4ENDIANTAG); String oz = ( order == ByteOrder . BIG_ENDIAN ? \"0\" : \"1\" ) ; a . setValues ( new String [ ] { oz } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set special attribute : constraint : overwrite exiting value [CODESPLIT] void setConstraint ( DapDataset dmr , CEConstraint ce ) throws DapException { if ( ce == null ) return ; if ( ce . isUniversal ( ) ) return ; DapAttribute a = dmr . findAttribute ( DapUtil . CEATTRNAME ) ; if ( a == null ) { a = new DapAttribute ( DapUtil . CEATTRNAME , DapType . STRING ) ; dmr . addAttribute ( a ) ; } String sce = ce . toConstraintString ( ) ; a . setValues ( new String [ ] { sce } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the anchor point . [CODESPLIT] public boolean anchor ( Point p ) { firstStretch = true ; anchorPt . x = p . x ; anchorPt . y = p . y ; stretchedPt . x = lastPt . x = anchorPt . x ; stretchedPt . y = lastPt . y = anchorPt . y ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Erase the last rectangle and draw a new one from the anchor point to this point . [CODESPLIT] public void stretch ( Point p ) { lastPt . x = stretchedPt . x ; lastPt . y = stretchedPt . y ; stretchedPt . x = p . x ; stretchedPt . y = p . y ; Graphics2D g = ( Graphics2D ) component . getGraphics ( ) ; if ( g != null ) { try { g . setXORMode ( component . getBackground ( ) ) ; if ( firstStretch == true ) firstStretch = false ; else drawLast ( g ) ; drawNext ( g ) ; } finally { g . dispose ( ) ; } // try } // if }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Last point done with drawing . [CODESPLIT] public void end ( Point p ) { lastPt . x = endPt . x = p . x ; lastPt . y = endPt . y = p . y ; Graphics2D g = ( Graphics2D ) component . getGraphics ( ) ; if ( g != null ) { try { g . setXORMode ( component . getBackground ( ) ) ; drawLast ( g ) ; } finally { g . dispose ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Last point done with drawing . [CODESPLIT] public void done ( ) { Graphics2D g = ( Graphics2D ) component . getGraphics ( ) ; if ( g != null ) { try { g . setXORMode ( component . getBackground ( ) ) ; drawLast ( g ) ; } finally { g . dispose ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get current Bounds [CODESPLIT] public Rectangle getBounds ( ) { return new Rectangle ( stretchedPt . x < anchorPt . x ? stretchedPt . x : anchorPt . x , stretchedPt . y < anchorPt . y ? stretchedPt . y : anchorPt . y , Math . abs ( stretchedPt . x - anchorPt . x ) , Math . abs ( stretchedPt . y - anchorPt . y ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get previous Bounds [CODESPLIT] public Rectangle lastBounds ( ) { return new Rectangle ( lastPt . x < anchorPt . x ? lastPt . x : anchorPt . x , lastPt . y < anchorPt . y ? lastPt . y : anchorPt . y , Math . abs ( lastPt . x - anchorPt . x ) , Math . abs ( lastPt . y - anchorPt . y ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the text in W3C profile of ISO 8601 format . @param text parse this text @return equivalent Date or null if failure @see <a href = http : // www . w3 . org / TR / NOTE - datetime > W3C profile of ISO 8601< / a > [CODESPLIT] @ Deprecated public Date getISODate ( String text ) { Date result ; // try \"yyyy-MM-dd HH:mm:ss\"\r try { result = stdDateTimeFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try  \"yyyy-MM-dd'T'HH:mm:ss\"\r try { result = isoDateTimeFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try \"yyyy-MM-dd'T'HH:mm\"\r try { result = isoDateNoSecsFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try \"yyyy-MM-dd HH:mm\"\r try { result = stdDateNoSecsFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try \"yyyy-MM-dd\"\r try { result = dateOnlyFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse text in the format yyyy - MM - dd HH : mm : ss [CODESPLIT] private Date stdDateTimeFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? \"\" : text . trim ( ) ; stdDateTimeFormat ( ) ; return stdDateTimeFormat . parse ( text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse text in the format yyyy - MM - dd HH : mm [CODESPLIT] private Date stdDateNoSecsFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? \"\" : text . trim ( ) ; stdDateNoSecsFormat ( ) ; return stdDateNoSecsFormat . parse ( text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse text in the format yyyy - MM - dd T HH : mm : ss [CODESPLIT] private Date isoDateTimeFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? \"\" : text . trim ( ) ; isoDateTimeFormat ( ) ; return isoDateTimeFormat . parse ( text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse text in the format yyyy - MM - dd T HH : mm [CODESPLIT] private Date isoDateNoSecsFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? \"\" : text . trim ( ) ; isoDateNoSecsFormat ( ) ; return isoDateNoSecsFormat . parse ( text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse text in the format yyyy - MM - dd [CODESPLIT] private Date dateOnlyFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? \"\" : text . trim ( ) ; dateOnlyFormat ( ) ; return dateOnlyFormat . parse ( text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "standard date format = yyyy - MM - dd HH : mm : ssZ [CODESPLIT] public String toDateTimeString ( Date date ) { if ( date == null ) return \"Unknown\" ; stdDateTimeFormat ( ) ; return stdDateTimeFormat . format ( date ) + \"Z\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "change shape of the data variables [CODESPLIT] protected void replaceDataVars ( StructureMembers sm ) { for ( StructureMembers . Member m : sm . getMembers ( ) ) { VariableSimpleIF org = this . cols . get ( m . getName ( ) ) ; int rank = org . getRank ( ) ; List < Dimension > orgDims = org . getDimensions ( ) ; // only keep the last n\r int n = m . getShape ( ) . length ; List < Dimension > dims = orgDims . subList ( rank - n , rank ) ; VariableSimpleImpl result = new VariableSimpleImpl ( org . getShortName ( ) , org . getDescription ( ) , org . getUnitsString ( ) , org . getDataType ( ) , dims ) ; for ( Attribute att : org . getAttributes ( ) ) result . ( att ) ; this . cols . put ( m . getName ( ) , result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Even if JavaBits is 64 the limit on an array size is Integer . MAX_VALUE . [CODESPLIT] public static void ensureArraySizeOkay ( long tSize , String attributeTo ) { if ( tSize >= Integer . MAX_VALUE ) throw new RuntimeException ( memoryTooMuchData + \"  \" + MessageFormat . format ( memoryArraySize , \"\" + tSize , \"\" + Integer . MAX_VALUE ) + ( attributeTo == null || attributeTo . length ( ) == 0 ? \"\" : \" (\" + attributeTo + \")\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safely rounds a double to an int . ( Math . round but rounds to a long and not safely . ) [CODESPLIT] public static int roundToInt ( double d ) { return d > Integer . MAX_VALUE || d <= Integer . MIN_VALUE - 0.5 || ! isFinite ( d ) ? Integer . MAX_VALUE : ( int ) Math . round ( d ) ; //safe since checked for larger values above }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "see http : // www . nco . ncep . noaa . gov / pmb / docs / grib2 / grib2_doc . shtml [CODESPLIT] private void initLocalTable ( ) { String tablePath = config . getPath ( ) ; ClassLoader cl = KmaLocalTables . class . getClassLoader ( ) ; try ( InputStream is = cl . getResourceAsStream ( tablePath ) ) { if ( is == null ) throw new IllegalStateException ( \"Cant find \" + tablePath ) ; List < TableParser . Record > recs = TableParser . readTable ( is , \"41,112,124i,136i,148i,160\" , 1000 ) ; for ( TableParser . Record record : recs ) { String name = ( String ) record . get ( 0 ) ; int disc = ( Integer ) record . get ( 2 ) ; int cat = ( Integer ) record . get ( 3 ) ; int param = ( Integer ) record . get ( 4 ) ; String unit = ( String ) record . get ( 5 ) ; Grib2Parameter s = new Grib2Parameter ( disc , cat , param , name , unit , null , null ) ; local . put ( makeParamId ( disc , cat , param ) , s ) ; } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 2 bytes into a signed integer . [CODESPLIT] public static int int2 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; return int2 ( a , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert unsigned bytes into an integer . [CODESPLIT] public static int uint ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; return ( int ) DataType . unsignedByteToShort ( ( byte ) a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 3 bytes into a signed integer . [CODESPLIT] public static int int3 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; return int3 ( a , b , c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 2 bytes into an unsigned integer . [CODESPLIT] public static int uint2 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; return uint2 ( a , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 3 bytes into an unsigned integer . [CODESPLIT] public static int uint3 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; return uint3 ( a , b , c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 4 bytes into a float value . [CODESPLIT] public static float float4 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; int d = raf . read ( ) ; return float4 ( a , b , c , d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 4 bytes to a float . [CODESPLIT] public static float float4 ( int a , int b , int c , int d ) { int sgn , mant , exp ; mant = b << 16 | c << 8 | d ; if ( mant == 0 ) { return 0.0f ; } sgn = - ( ( ( a & 128 ) >> 6 ) - 1 ) ; exp = ( a & 127 ) - 64 ; return ( float ) ( sgn * Math . pow ( 16.0 , exp - 6 ) * mant ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 8 bytes into a signed long . [CODESPLIT] public static long int8 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; int d = raf . read ( ) ; int e = raf . read ( ) ; int f = raf . read ( ) ; int g = raf . read ( ) ; int h = raf . read ( ) ; return ( 1 - ( ( a & 128 ) >> 6 ) ) * ( ( long ) ( a & 127 ) << 56 | ( long ) b << 48 | ( long ) c << 40 | ( long ) d << 32 | e << 24 | f << 16 | g << 8 | h ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "count number of bits on in bitmap [CODESPLIT] public static int countBits ( byte [ ] bitmap ) { int bits = 0 ; for ( byte b : bitmap ) { short s = DataType . unsignedByteToShort ( b ) ; bits += Long . bitCount ( s ) ; } return bits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lon naught ?? [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new LambertConformal ( getOriginLat ( ) , getOriginLon ( ) , getParallelOne ( ) , getParallelTwo ( ) , getFalseEasting ( ) , getFalseNorthing ( ) , earth_radius ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Precalculate some stuff [CODESPLIT] private void precalculate ( ) { if ( Math . abs ( lat0 ) > PI_OVER_2 ) { throw new IllegalArgumentException ( \"LambertConformal lat0 outside range (-90,90)\" ) ; } if ( Math . abs ( par1 ) >= 90.0 ) { throw new IllegalArgumentException ( \"LambertConformal abs(par1) >= 90\" ) ; } if ( Math . abs ( par2 ) >= 90.0 ) { throw new IllegalArgumentException ( \"LambertConformal abs(par2) >= 90\" ) ; } if ( Math . abs ( par1 - 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( \"LambertConformal par1 = 90\" ) ; } if ( Math . abs ( par1 + 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( \"LambertConformal par1 = -90\" ) ; } if ( Math . abs ( par2 - 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( \"LambertConformal par2 = 90\" ) ; } if ( Math . abs ( par2 + 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( \"LambertConformal par2 = -90\" ) ; } double par1r = Math . toRadians ( this . par1 ) ; double par2r = Math . toRadians ( this . par2 ) ; double t1 = Math . tan ( Math . PI / 4 + par1r / 2 ) ; double t2 = Math . tan ( Math . PI / 4 + par2r / 2 ) ; if ( Math . abs ( par2 - par1 ) < TOLERANCE ) { // single parallel\r n = Math . sin ( par1r ) ; } else { n = Math . log ( Math . cos ( par1r ) / Math . cos ( par2r ) ) / Math . log ( t2 / t1 ) ; } double t1n = Math . pow ( t1 , n ) ; F = Math . cos ( par1r ) * t1n / n ; earthRadiusTimesF = earth_radius * F ; double t0n = Math . pow ( Math . tan ( Math . PI / 4 + lat0 / 2 ) , n ) ; rho = earthRadiusTimesF / t0n ; lon0Degrees = Math . toDegrees ( lon0 ) ; // need to know the pole value for crossSeam\r //Point2D pt = latLonToProj( 90.0, 0.0);\r //maxY = pt.getY();\r //System.out.println(\"LC = \" +pt);\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a WKS string [CODESPLIT] public String toWKS ( ) { StringBuilder sbuff = new StringBuilder ( ) ; sbuff . append ( \"PROJCS[\\\"\" ) . append ( getName ( ) ) . append ( \"\\\",\" ) ; if ( true ) { sbuff . append ( \"GEOGCS[\\\"Normal Sphere (r=6371007)\\\",\" ) ; sbuff . append ( \"DATUM[\\\"unknown\\\",\" ) ; sbuff . append ( \"SPHEROID[\\\"sphere\\\",6371007,0]],\" ) ; } else { sbuff . append ( \"GEOGCS[\\\"WGS 84\\\",\" ) ; sbuff . append ( \"DATUM[\\\"WGS_1984\\\",\" ) ; sbuff . append ( \"SPHEROID[\\\"WGS 84\\\",6378137,298.257223563],\" ) ; sbuff . append ( \"TOWGS84[0,0,0,0,0,0,0]],\" ) ; } sbuff . append ( \"PRIMEM[\\\"Greenwich\\\",0],\" ) ; sbuff . append ( \"UNIT[\\\"degree\\\",0.0174532925199433]],\" ) ; sbuff . append ( \"PROJECTION[\\\"Lambert_Conformal_Conic_1SP\\\"],\" ) ; sbuff . append ( \"PARAMETER[\\\"latitude_of_origin\\\",\" ) . append ( getOriginLat ( ) ) . append ( \"],\" ) ; // LOOK assumes getOriginLat = getParellel\r sbuff . append ( \"PARAMETER[\\\"central_meridian\\\",\" ) . append ( getOriginLon ( ) ) . append ( \"],\" ) ; sbuff . append ( \"PARAMETER[\\\"scale_factor\\\",1],\" ) ; sbuff . append ( \"PARAMETER[\\\"false_easting\\\",\" ) . append ( falseEasting ) . append ( \"],\" ) ; sbuff . append ( \"PARAMETER[\\\"false_northing\\\",\" ) . append ( falseNorthing ) . append ( \"],\" ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the scale at the given lat . [CODESPLIT] public double getScale ( double lat ) { lat = Math . toRadians ( lat ) ; double t = Math . tan ( Math . PI / 4 + lat / 2 ) ; double tn = Math . pow ( t , n ) ; double r1 = n * F ; double r2 = Math . cos ( lat ) * tn ; return r1 / r2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; double dlon = LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ; double theta = n * Math . toRadians ( dlon ) ; double tn = Math . pow ( Math . tan ( PI_OVER_4 + fromLat / 2 ) , n ) ; double r = earthRadiusTimesF / tn ; toX = r * Math . sin ( theta ) ; toY = rho - r * Math . cos ( theta ) ; result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double rhop = rho ; if ( n < 0 ) { rhop *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = ( rhop - fromY ) ; double theta = Math . atan2 ( fromX , yd ) ; double r = Math . sqrt ( fromX * fromX + yd * yd ) ; if ( n < 0.0 ) { r *= - 1.0 ; } toLon = ( Math . toDegrees ( theta / n + lon0 ) ) ; if ( Math . abs ( r ) < TOLERANCE ) { toLat = ( ( n < 0.0 ) ? - 90.0 : 90.0 ) ; } else { double rn = Math . pow ( earth_radius * F / r , 1 / n ) ; toLat = Math . toDegrees ( 2.0 * Math . atan ( rn ) - Math . PI / 2 ) ; } result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double dlon = LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ; double theta = n * Math . toRadians ( dlon ) ; double tn = Math . pow ( Math . tan ( PI_OVER_4 + fromLat / 2 ) , n ) ; double r = earthRadiusTimesF / tn ; toX = r * Math . sin ( theta ) ; toY = rho - r * Math . cos ( theta ) ; resultXA [ i ] = ( float ) ( toX + falseEasting ) ; resultYA [ i ] = ( float ) ( toY + falseNorthing ) ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { int cnt = from [ 0 ] . length ; float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] toLatA = to [ INDEX_LAT ] ; float [ ] toLonA = to [ INDEX_LON ] ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] - falseEasting ; double fromY = fromYA [ i ] - falseNorthing ; double rhop = rho ; if ( n < 0 ) { rhop *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = ( rhop - fromY ) ; double theta = Math . atan2 ( fromX , yd ) ; double r = Math . sqrt ( fromX * fromX + yd * yd ) ; if ( n < 0.0 ) { r *= - 1.0 ; } toLon = ( Math . toDegrees ( theta / n + lon0 ) ) ; if ( Math . abs ( r ) < TOLERANCE ) { toLat = ( ( n < 0.0 ) ? - 90.0 : 90.0 ) ; } else { double rn = Math . pow ( earth_radius * F / r , 1 / n ) ; toLat = Math . toDegrees ( 2.0 * Math . atan ( rn ) - Math . PI / 2 ) ; } toLatA [ i ] = ( float ) toLat ; toLonA [ i ] = ( float ) toLon ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape selected characters in a string using XML entities [CODESPLIT] static public String entityEscape ( String s , String wrt ) { if ( wrt == null ) wrt = ENTITYESCAPES ; StringBuilder escaped = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; int index = wrt . indexOf ( c ) ; if ( index < 0 ) escaped . append ( c ) ; else switch ( c ) { case ' ' : escaped . append ( ' ' + ENTITY_AMP + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_LT + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_GT + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_QUOT + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_APOS + ' ' ) ; break ; case ' ' : case ' ' : case ' ' : escaped . append ( c ) ; // These are the only legal control chars break ; case ' ' : // What to do about nul? currrently we suppress it break ; default : if ( c >= ' ' ) escaped . append ( c ) ; break ; } } return escaped . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape control chars plus selected other characters in a string using backslash The definitive list is in netcdf - c / ncgen / ncgen . l . [CODESPLIT] static public String backslashEscape ( String s , String wrt ) { if ( wrt == null ) wrt = BACKSLASHESCAPE ; StringBuilder escaped = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c < ' ' || c == 127 ) { escaped . append ( ' ' ) ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; default : escaped . append ( ' ' ) ; escaped . append ( Escape . toHex ( ( int ) c ) ) ; continue ; /* since this is a string */ } } else if ( c == ' ' || wrt . indexOf ( c ) >= 0 ) escaped . append ( ' ' ) ; escaped . append ( c ) ; } return escaped . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove backslashed characters in a string [CODESPLIT] static public String backslashUnescape ( String s ) { StringBuilder clear = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; ) { char c = s . charAt ( i ++ ) ; if ( c == ' ' ) { c = s . charAt ( i ++ ) ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; default : break ; } clear . append ( c ) ; } else clear . append ( c ) ; } return clear . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string with respect to a separator character and taking backslashes into consideration . [CODESPLIT] static public List < String > backslashsplit ( String s , char sep ) { List < String > path = new ArrayList < String > ( ) ; int len = s . length ( ) ; StringBuilder piece = new StringBuilder ( ) ; int i = 0 ; for ( ; i <= len - 1 ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' && i < ( len - 1 ) ) { piece . append ( c ) ; // keep escapes in place piece . append ( s . charAt ( ++ i ) ) ; } else if ( c == sep ) { path . add ( piece . toString ( ) ) ; piece . setLength ( 0 ) ; } else piece . append ( c ) ; } path . add ( piece . toString ( ) ) ; return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean up a string : currently means : 1 . strip off everything after the first nul character [CODESPLIT] static public String cleanString ( String s ) { int index = s . indexOf ( ( char ) 0 ) ; if ( index >= 0 ) s = s . substring ( 0 , index ) ; return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////// [CODESPLIT] @ RequestMapping ( value = \"/**\" , method = RequestMethod . GET , params = \"req=featureType\" ) public ResponseEntity < String > handleFeatureTypeRequest ( HttpServletRequest request , HttpServletResponse response ) throws IOException { if ( ! allowedServices . isAllowed ( StandardService . cdmrFeatureGrid ) ) throw new ServiceNotAllowed ( StandardService . cdmrFeatureGrid . toString ( ) ) ; String datasetPath = TdsPathUtils . extractPath ( request , StandardService . cdmrFeatureGrid . getBase ( ) ) ; try ( CoverageCollection cc = TdsRequestedDataset . getCoverageCollection ( request , response , datasetPath ) ) { if ( cc == null ) return null ; // return new ResponseEntity<>(\"\", HttpStatus.NOT_FOUND); HttpHeaders responseHeaders = new HttpHeaders ( ) ; responseHeaders . set ( ContentType . HEADER , ContentType . text . getContentHeader ( ) ) ; return new ResponseEntity <> ( cc . getCoverageType ( ) . toString ( ) , responseHeaders , HttpStatus . OK ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method [CODESPLIT] public static Fmrc open ( String collection , Formatter errlog ) throws IOException { if ( collection . startsWith ( MFileCollectionManager . CATALOG ) ) { CollectionManagerCatalog manager = new CollectionManagerCatalog ( collection , collection , null , errlog ) ; return new Fmrc ( manager , new FeatureCollectionConfig ( ) ) ; } else if ( collection . endsWith ( \".ncml\" ) ) { NcmlCollectionReader ncmlCollection = NcmlCollectionReader . open ( collection , errlog ) ; if ( ncmlCollection == null ) return null ; Fmrc fmrc = new Fmrc ( ncmlCollection . getCollectionManager ( ) , new FeatureCollectionConfig ( ) ) ; fmrc . setNcml ( ncmlCollection . getNcmlOuter ( ) , ncmlCollection . getNcmlInner ( ) ) ; return fmrc ; } return new Fmrc ( collection , errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "scan has been done create FmrcInv [CODESPLIT] private FmrcInv makeFmrcInv ( Formatter debug ) throws IOException { try { Map < CalendarDate , FmrInv > fmrMap = new HashMap <> ( ) ; // all files are grouped by run date in an FmrInv\r List < FmrInv > fmrList = new ArrayList <> ( ) ; // an fmrc is a collection of fmr\r // get the inventory, sorted by path\r for ( MFile f : manager . getFilesSorted ( ) ) { Map < String , String > filesRunDateMap = ( ( MFileCollectionManager ) manager ) . getFilesRunDateMap ( ) ; CalendarDate runDate ; if ( ! filesRunDateMap . isEmpty ( ) ) { // run time has been defined in NcML FMRC agg by the coord attribute,\r // so explicitly set it in the dataset using the _Coordinate.ModelBaseDate\r // global attribute, otherwise the run time offsets might be incorrectly\r // computed if the incorrect run date is found in GridDatasetInv.java (line\r // 177 with comment // Look: not really right )\r runDate = CalendarDate . parseISOformat ( null , filesRunDateMap . get ( f . getPath ( ) ) ) ; Element element = new Element ( \"netcdf\" , ncNSHttps ) ; Element runDateAttr = ncmlWriter . makeAttributeElement ( new Attribute ( _Coordinate . ModelRunDate , runDate . toString ( ) ) ) ; config . innerNcml = element . addContent ( runDateAttr ) ; } GridDatasetInv inv ; try { inv = GridDatasetInv . open ( manager , f , config . innerNcml ) ; // inventory is discovered for each GDS\r } catch ( IOException ioe ) { logger . warn ( \"Error opening \" + f . getPath ( ) + \"(skipped)\" , ioe ) ; continue ; // skip\r } runDate = inv . getRunDate ( ) ; if ( debug != null ) debug . format ( \"  opened %s rundate = %s%n\" , f . getPath ( ) , inv . getRunDateString ( ) ) ; // add to fmr for that rundate\r FmrInv fmr = fmrMap . get ( runDate ) ; if ( fmr == null ) { fmr = new FmrInv ( runDate ) ; fmrMap . put ( runDate , fmr ) ; fmrList . add ( fmr ) ; } fmr . addDataset ( inv , debug ) ; } if ( debug != null ) debug . format ( \"%n\" ) ; // finish the FmrInv\r Collections . sort ( fmrList ) ; for ( FmrInv fmr : fmrList ) { fmr . finish ( ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \"Fmrc:\" + config . name + \": made fmr with rundate=\" + fmr . getRunDate ( ) + \" nfiles= \" + fmr . getFiles ( ) . size ( ) ) ; } return new FmrcInv ( \"fmrc:\" + manager . getCollectionName ( ) , fmrList , config . fmrcConfig . regularize ) ; } catch ( Throwable t ) { logger . error ( \"makeFmrcInv\" , t ) ; throw new RuntimeException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the ones that dont start with thredds [CODESPLIT] static public String getServiceSpecial ( String path ) { String ss = null ; if ( path . startsWith ( \"/dqcServlet\" ) ) ss = \"dqcServlet\" ; else if ( path . startsWith ( \"/cdmvalidator\" ) ) ss = \"cdmvalidator\" ; return ss ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation requires the path to be relative to the root directory and a descendant of the root directory . It also requires the relative path at each path segment to be a descendant of the root directory i . e . it cannot start with .. / or contain .. / path segments such that once normalized it would start with .. / ( e . g . dir1 / .. / .. / dir2 once normalized would be .. / dir2 ) . [CODESPLIT] public File getFile ( String path ) { if ( path == null ) return null ; String workPath = StringUtils . cleanPath ( path ) ; if ( workPath . startsWith ( \"../\" ) ) return null ; if ( new File ( workPath ) . isAbsolute ( ) ) return null ; File file = new File ( this . rootDirectory , workPath ) ; if ( file . exists ( ) ) return file ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of variables contained in this object . For simple and vector type variables it always returns 1 . To count the number of simple - type variable in the variable tree rooted at this variable set <code > leaves< / code > to <code > true< / code > . [CODESPLIT] public int elementCount ( boolean leaves ) { if ( ! leaves ) return mapVars . size ( ) + 1 ; // Number of Maps plus 1 Array component\r else { int count = 0 ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; count += bt . elementCount ( leaves ) ; } count += arrayVar . elementCount ( leaves ) ; return count ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a variable to the container . [CODESPLIT] public void addVariable ( BaseType v , int part ) { if ( ! ( v instanceof DArray ) ) throw new IllegalArgumentException ( \"Grid `\" + getEncodedName ( ) + \"'s' member `\" + arrayVar . getEncodedName ( ) + \"' must be an array\" ) ; v . setParent ( this ) ; switch ( part ) { case ARRAY : arrayVar = ( DArray ) v ; return ; case MAPS : mapVars . addElement ( v ) ; return ; default : throw new IllegalArgumentException ( \"addVariable(): Unknown Grid part\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the indexed variable . For a DGrid the index 0 returns the <code > DArray< / code > and indexes 1 and higher return the associated map <code > Vector< / code > s . [CODESPLIT] public BaseType getVar ( int index ) throws NoSuchVariableException { if ( index == 0 ) { return ( arrayVar ) ; } else { int i = index - 1 ; if ( i < mapVars . size ( ) ) return ( ( BaseType ) mapVars . elementAt ( i ) ) ; else throw new NoSuchVariableException ( \"DGrid.getVariable() No Such variable: \" + index + \" - 1\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for internal consistency . For <code > DGrid< / code > verify that the map variables have unique names and match the number of dimensions of the array variable . [CODESPLIT] public void checkSemantics ( boolean all ) throws BadSemanticsException { super . checkSemantics ( all ) ; Util . uniqueNames ( mapVars , getEncodedName ( ) , getTypeName ( ) ) ; if ( arrayVar == null ) throw new BadSemanticsException ( \"DGrid.checkSemantics(): Null grid base array in `\" + getEncodedName ( ) + \"'\" ) ; // check semantics of array variable\r arrayVar . checkSemantics ( all ) ; // enough maps?\r if ( mapVars . size ( ) != arrayVar . numDimensions ( ) ) throw new BadSemanticsException ( \"DGrid.checkSemantics(): The number of map variables for grid `\" + getEncodedName ( ) + \"' does not match the number of dimensions of `\" + arrayVar . getEncodedName ( ) + \"'\" ) ; //----- I added this next test 12/3/99. As soon as I did I questioned whether or not\r //----- it adds any value. ie: Can it ever happen that this test fails? I don't think\r //----- so now that I have written it...  ndp 12/3/99\r // Is the size of the maps equal to the size of the cooresponding dimensions?\r Enumeration emap = mapVars . elements ( ) ; Enumeration edims = arrayVar . getDimensions ( ) ; int dim = 0 ; while ( emap . hasMoreElements ( ) && edims . hasMoreElements ( ) ) { DArray thisMapArray = ( DArray ) emap . nextElement ( ) ; Enumeration ema = thisMapArray . getDimensions ( ) ; DArrayDimension thisMapDim = ( DArrayDimension ) ema . nextElement ( ) ; DArrayDimension thisArrayDim = ( DArrayDimension ) edims . nextElement ( ) ; if ( thisMapDim . getSize ( ) != thisArrayDim . getSize ( ) ) { throw new BadSemanticsException ( \"In grid '\" + getEncodedName ( ) + \" The size of dimension \" + dim + \" in the array component '\" + arrayVar . getEncodedName ( ) + \"is not equal to the size of the coresponding map vector '\" + thisMapArray . getEncodedName ( ) + \".\" ) ; } dim ++ ; } //----- end  ndp 12/3/99\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coverity [ CALL_SUPER ] [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { os . println ( space + getTypeName ( ) + \" {\" ) ; os . println ( space + \" ARRAY:\" ) ; arrayVar . printDecl ( os , space + \"    \" , true ) ; os . println ( space + \" MAPS:\" ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . printDecl ( os , space + \"    \" , true ) ; } os . print ( space + \"} \" + getEncodedName ( ) ) ; if ( print_semi ) os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { arrayVar . externalize ( sink ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . externalize ( sink ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "How many prohected components of this Grid object? [CODESPLIT] public int projectedComponents ( boolean constrained ) { int comp ; if ( constrained ) { comp = ( ( DArray ) arrayVar ) . isProject ( ) ? 1 : 0 ; Enumeration e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { if ( ( ( DArray ) e . nextElement ( ) ) . isProject ( ) ) comp ++ ; } } else { comp = 1 + mapVars . size ( ) ; } return comp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When projected ( using whatever the current constraint provides in the way of a projection ) am I still a Grid? [CODESPLIT] public boolean projectionYieldsGrid ( boolean constrained ) { if ( ! constrained ) return true ; // For each dimension in the Array part, check the corresponding Map\r // vector to make sure it is present in the projected Grid. If for each\r // projected dimension in the Array component, there is a matching Map\r // vector, then the Grid is valid.\r boolean valid = true ; // Don't bother checking if the Array component is not included.\r if ( ! ( ( SDArray ) arrayVar ) . isProject ( ) ) return false ; int nadims = arrayVar . numDimensions ( ) ; int nmaps = getVarCount ( ) - 1 ; //Enumeration aDims = arrayVar.getDimensions();\r //Enumeration e = mapVars.elements();\r //while (valid && e.hasMoreElements() && aDims.hasMoreElements()) {\r if ( nadims != nmaps ) valid = false ; else for ( int d = 0 ; d < nadims ; d ++ ) { try { DArrayDimension thisDim = arrayVar . getDimension ( d ) ; //(DArrayDimension) aDims.nextElement();\r SDArray mapArray = ( SDArray ) getVar ( d + 1 ) ; //e.nextElement();\r DArrayDimension mapDim = mapArray . getFirstDimension ( ) ; if ( thisDim . getSize ( ) > 0 ) { // LogStream.out.println(\"Dimension Contains Data.\");\r if ( mapArray . isProject ( ) ) { // This map vector better be projected!\r // LogStream.out.println(\"Map Vector Projected, checking projection image...\");\r // Check the matching Map vector; the Map projection must equal\r // the Array dimension projection\r // wrong: valid at this point might have been false: valid = true;\r valid = valid && mapDim . getStart ( ) == thisDim . getStart ( ) ; valid = valid && mapDim . getStop ( ) == thisDim . getStop ( ) ; valid = valid && mapDim . getStride ( ) == thisDim . getStride ( ) ; } else { // LogStream.out.println(\"Map Vector not Projected.\");\r valid = false ; } } else { // LogStream.out.println(\"Dimension empty. Verifying corresponding Map vector not projected...\");\r // Corresponding Map vector must be excluded from the\r // projection or it's not a grid.\r valid = ! mapArray . isProject ( ) ; } } catch ( Exception e ) { Util . check ( e ) ; valid = false ; break ; } } //if (e.hasMoreElements() != aDims.hasMoreElements()) valid = false;\r return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > DGrid< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DGrid g = ( DGrid ) super . cloneDAG ( map ) ; g . arrayVar = ( DArray ) cloneDAG ( map , arrayVar ) ; g . mapVars = new Vector ( ) ; for ( int i = 0 ; i < mapVars . size ( ) ; i ++ ) { BaseType bt = ( BaseType ) mapVars . elementAt ( i ) ; BaseType btclone = ( BaseType ) cloneDAG ( map , bt ) ; g . mapVars . addElement ( btclone ) ; } return g ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the level values from the specifications [CODESPLIT] protected double [ ] makeLevelValues ( ) { if ( levels == null ) { return null ; } if ( levels . size ( ) != size ) { // do someting\r } double [ ] vals = new double [ size ] ; if ( mapping . equalsIgnoreCase ( LEVELS ) ) { for ( int i = 0 ; i < vals . length ; i ++ ) { vals [ i ] = Double . parseDouble ( levels . get ( i ) ) ; } } else if ( mapping . equalsIgnoreCase ( LINEAR ) ) { double start = 0 ; double inc = 0 ; start = Double . parseDouble ( levels . get ( 0 ) ) ; inc = Double . parseDouble ( levels . get ( 1 ) ) ; for ( int i = 0 ; i < size ; i ++ ) { vals [ i ] = start + i * inc ; } // TODO: figure out a better way to do this in case they don't start with gaus (e.g. MOM32)\r } else if ( mapping . toLowerCase ( ) . startsWith ( \"gaus\" ) ) { vals = GradsUtil . getGaussianLatitudes ( mapping , ( int ) Double . parseDouble ( levels . get ( 0 ) ) , size ) ; } // sanity check on z units\r if ( name . equals ( GradsDataDescriptorFile . ZDEF ) ) { for ( int i = 0 ; i < vals . length ; i ++ ) { double val = vals [ i ] ; if ( val > 1050 ) { unitName = \"Pa\" ; break ; } else if ( val < 10 ) { // sometimes it's just a level number\r // probably should be something else, but dimensionless\r unitName = \"\" ; break ; } } } return vals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser primary actions [CODESPLIT] @ Override CEAST constraint ( CEAST . NodeList clauses ) throws ParseException { CEAST node = new CEAST ( CEAST . Sort . CONSTRAINT ) ; node . clauses = clauses ; node . dimdefs = dimdefs ; // save for constructing the DMR this . constraint = node ; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selection actions [CODESPLIT] @ Override CEAST selection ( CEAST projection , CEAST filter ) throws ParseException { CEAST node = new CEAST ( CEAST . Sort . SELECTION ) ; node . projection = projection ; node . filter = filter ; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser list support [CODESPLIT] @ Override CEAST . NodeList nodelist ( CEAST . NodeList list , CEAST ast ) { if ( list == null ) list = new CEAST . NodeList ( ) ; if ( ast != null ) list . add ( ast ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return record header time as a CalendarDate [CODESPLIT] public final CalendarDate getReferenceTime ( ) { int sec = ( second < 0 || second > 59 ) ? 0 : second ; return CalendarDate . of ( null , year , month , day , hour , minute , sec ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a section of an ArrayStructureBB [CODESPLIT] static public ArrayStructureBB factory ( ArrayStructureBB org , Section section ) { if ( section == null || section . computeSize ( ) == org . getSize ( ) ) return org ; return new ArrayStructureBBsection ( org . getStructureMembers ( ) , org . getShape ( ) , org . getByteBuffer ( ) , section ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a document for a File . <p / > The document has three fields : <ul > <li > <code > path< / code > -- containing the pathname of the file as a stored untokenized field ; <li > <code > modified< / code > -- containing the last modified date of the file as a field as created by <a href = lucene . document . DateTools . html > DateTools< / a > ; and <li > <code > contents< / code > -- containing the full contents of the file as a Reader field ; [CODESPLIT] public Document makeDocument ( File f ) throws java . io . FileNotFoundException { // make a new, empty document Document doc = new Document ( ) ; // Add the path of the file as a field named \"path\".  Use a field that is // indexed (i.e. searchable), but don't tokenize the field into words. doc . add ( new Field ( \"path\" , f . getPath ( ) , Field . Store . YES , Field . Index . UN_TOKENIZED ) ) ; // Add the last modified date of the file a field named \"modified\".  Use // a field that is indexed (i.e. searchable), but don't tokenize the field // into words. doc . add ( new Field ( \"modified\" , DateTools . timeToString ( f . lastModified ( ) , DateTools . Resolution . MINUTE ) , Field . Store . YES , Field . Index . UN_TOKENIZED ) ) ; // Add the contents of the file to a field named \"contents\".  Specify a Reader, // so that the text of the file is tokenized and indexed, but not stored. // Note that FileReader expects the file to be in the system's default encoding. // If that's not the case searching for special characters will fail. // doc.add(new Field(\"contents\", new FileReader(f))); // return the document return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index all text files under a directory . [CODESPLIT] public static void main1 ( String [ ] args ) { if ( INDEX_DIR . exists ( ) ) { System . out . println ( \"Cannot save index to '\" + INDEX_DIR + \"' directory, please delete it first\" ) ; System . exit ( 1 ) ; } LuceneIndexer indexer = new LuceneIndexer ( ) ; Date start = new Date ( ) ; try { IndexWriter writer = new IndexWriter ( INDEX_DIR , new StandardAnalyzer ( ) , true ) ; System . out . println ( \"Indexing to directory '\" + INDEX_DIR + \"'...\" ) ; indexer . indexDocs ( writer , DOC_DIR ) ; System . out . println ( \"Optimizing...\" ) ; writer . optimize ( ) ; writer . close ( ) ; Date end = new Date ( ) ; System . out . println ( end . getTime ( ) - start . getTime ( ) + \" total milliseconds\" ) ; } catch ( IOException e ) { System . out . println ( \" caught a \" + e . getClass ( ) + \"\\n with message: \" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deserialize the Grib1Record object [CODESPLIT] private Grib1Record readRecord ( Grib1IndexProto . Grib1Record p ) { Grib1SectionIndicator is = new Grib1SectionIndicator ( p . getGribMessageStart ( ) , p . getGribMessageLength ( ) ) ; Grib1SectionProductDefinition pds = new Grib1SectionProductDefinition ( p . getPds ( ) . toByteArray ( ) ) ; Grib1SectionGridDefinition gds = pds . gdsExists ( ) ? gdsList . get ( p . getGdsIdx ( ) ) : new Grib1SectionGridDefinition ( pds ) ; Grib1SectionBitMap bms = pds . bmsExists ( ) ? new Grib1SectionBitMap ( p . getBmsPos ( ) ) : null ; Grib1SectionBinaryData dataSection = new Grib1SectionBinaryData ( p . getDataPos ( ) , p . getDataLen ( ) ) ; return new Grib1Record ( p . getHeader ( ) . toByteArray ( ) , is , gds , pds , bms , dataSection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK what about extending an index ?? [CODESPLIT] public boolean makeIndex ( String filename , RandomAccessFile dataRaf ) throws IOException { String idxPath = filename ; if ( ! idxPath . endsWith ( GBX9_IDX ) ) idxPath += GBX9_IDX ; File idxFile = GribIndexCache . getFileOrCache ( idxPath ) ; File idxFileTmp = GribIndexCache . getFileOrCache ( idxPath + \".tmp\" ) ; RandomAccessFile raf = null ; try ( FileOutputStream fout = new FileOutputStream ( idxFileTmp ) ) { //// header message\r fout . write ( MAGIC_START . getBytes ( CDM . utf8Charset ) ) ; NcStream . writeVInt ( fout , version ) ; Map < Long , Integer > gdsMap = new HashMap <> ( ) ; gdsList = new ArrayList <> ( ) ; records = new ArrayList <> ( 200 ) ; Grib1IndexProto . Grib1Index . Builder rootBuilder = Grib1IndexProto . Grib1Index . newBuilder ( ) ; rootBuilder . setFilename ( filename ) ; if ( dataRaf == null ) { // open if dataRaf not already open\r raf = RandomAccessFile . acquire ( filename ) ; dataRaf = raf ; } Grib1RecordScanner scan = new Grib1RecordScanner ( dataRaf ) ; while ( scan . hasNext ( ) ) { Grib1Record r = scan . next ( ) ; if ( r == null ) break ; // done\r records . add ( r ) ; Grib1SectionGridDefinition gdss = r . getGDSsection ( ) ; Integer index = gdsMap . get ( gdss . calcCRC ( ) ) ; if ( gdss . getPredefinedGridDefinition ( ) >= 0 ) // skip predefined gds - they dont have raw bytes\r index = 0 ; else if ( index == null ) { gdsList . add ( gdss ) ; index = gdsList . size ( ) - 1 ; gdsMap . put ( gdss . calcCRC ( ) , index ) ; rootBuilder . addGdsList ( makeGdsProto ( gdss ) ) ; } rootBuilder . addRecords ( makeRecordProto ( r , index ) ) ; } if ( records . isEmpty ( ) ) throw new RuntimeException ( \"No GRIB1 records found in \" + dataRaf . getLocation ( ) ) ; ucar . nc2 . grib . grib1 . Grib1IndexProto . Grib1Index index = rootBuilder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; NcStream . writeVInt ( fout , b . length ) ; // message size\r fout . write ( b ) ; // message  - all in one gulp\r logger . debug ( \"  made gbx9 index for {} size={}\" , filename , b . length ) ; return true ; } finally { if ( raf != null ) raf . close ( ) ; // only close if it was opened here\r // now switch\r RandomAccessFile . eject ( idxFile . getPath ( ) ) ; boolean deleteOk = ! idxFile . exists ( ) || idxFile . delete ( ) ; boolean renameOk = idxFileTmp . renameTo ( idxFile ) ; if ( ! deleteOk ) logger . error ( \"  could not delete Grib1Index= {}\" , idxFile . getPath ( ) ) ; if ( ! renameOk ) logger . error ( \"  could not rename Grib1Index= {}\" , idxFile . getPath ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation requires a relative path . The relative path may not start with .. / or once normalized start with .. / . Here normalized means that . / and path / .. segments are removed e . g . dir1 / .. / .. / dir2 once normalized would be .. / dir2 . [CODESPLIT] public File getFile ( String path ) { File file ; for ( DescendantFileSource curLocator : chain ) { file = curLocator . getFile ( path ) ; if ( file != null ) return file ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do we think this is a M3IO file . [CODESPLIT] public static boolean isMine ( NetcdfFile ncfile ) { return ( null != ncfile . findGlobalAttribute ( \"XORIG\" ) ) && ( null != ncfile . findGlobalAttribute ( \"YORIG\" ) ) && ( null != ncfile . findGlobalAttribute ( \"XCELL\" ) ) && ( null != ncfile . findGlobalAttribute ( \"YCELL\" ) ) && ( null != ncfile . findGlobalAttribute ( \"NCOLS\" ) ) && ( null != ncfile . findGlobalAttribute ( \"NROWS\" ) ) ; // M3IOVGGridConvention - is this true for this class ?? // return ncFile.findGlobalAttribute( \"VGLVLS\" ) != null && isValidM3IOFile_( ncFile ); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Intend to use EPSG system parameters [CODESPLIT] private CoordinateTransform makeUTMProjection ( NetcdfDataset ds ) { int zone = ( int ) findAttributeDouble ( ds , \"P_ALP\" ) ; double ycent = findAttributeDouble ( ds , \"YCENT\" ) ; //double lon0 = findAttributeDouble( \"X_CENT\"); //double lat0 = findAttributeDouble( \"Y_CENT\"); /**\n     * Construct a UTM Projection.\n     * @param zone - UTM zone\n     * @param if ycent < 0, then isNorth = False\n     */ boolean isNorth = true ; if ( ycent < 0 ) isNorth = false ; UtmProjection utm = new UtmProjection ( zone , isNorth ) ; return new ProjectionCT ( \"UTM\" , \"EPSG\" , utm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////// [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ds , VariableEnhanced ve ) { Variable v = ( Variable ) ve ; String vname = v . getShortName ( ) ; if ( vname . equalsIgnoreCase ( \"x\" ) ) return AxisType . GeoX ; if ( vname . equalsIgnoreCase ( \"y\" ) ) return AxisType . GeoY ; if ( vname . equalsIgnoreCase ( \"lat\" ) ) return AxisType . Lat ; if ( vname . equalsIgnoreCase ( \"lon\" ) ) return AxisType . Lon ; if ( vname . equalsIgnoreCase ( \"time\" ) ) return AxisType . Time ; if ( vname . equalsIgnoreCase ( \"level\" ) ) return AxisType . GeoZ ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the service provider for reading . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; if ( areaReader == null ) areaReader = new AreaReader ( ) ; try { areaReader . init ( raf . getLocation ( ) , ncfile ) ; } catch ( Throwable e ) { close ( ) ; // try not to leak files throw new IOException ( e ) ; } finally { raf . close ( ) ; // avoid leaks } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data for the variable [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { return areaReader . readVariable ( v2 , section ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reacquire any resources like file handles [CODESPLIT] public void reacquire ( ) throws IOException { try { areaReader . af = new AreaFile ( location ) ; } catch ( Throwable e ) { throw new IOException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this date before the given date . if isPresent always false . [CODESPLIT] public boolean before ( Date d ) { if ( isPresent ( ) ) return false ; return date . isBefore ( CalendarDate . of ( d ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this date before the given date . if d . isPresent always true else if this . isPresent false . [CODESPLIT] public boolean before ( DateType d ) { if ( d . isPresent ( ) ) return true ; if ( isPresent ( ) ) return false ; return date . isBefore ( d . getCalendarDate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this date after the given date . if isPresent always true . [CODESPLIT] public boolean after ( Date d ) { if ( isPresent ( ) ) return true ; return date . isAfter ( CalendarDate . of ( d ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "test [CODESPLIT] private static void doOne ( String s ) { try { System . out . println ( \"\\nString = (\" + s + \")\" ) ; DateType d = new DateType ( s , null , null ) ; System . out . println ( \"DateType = (\" + d . toString ( ) + \")\" ) ; System . out . println ( \"Date = (\" + d . getDate ( ) + \")\" ) ; } catch ( java . text . ParseException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when we have a real catalog ( filename ! = CATSCAN ) [CODESPLIT] public ConfigCatalog getCatalog ( File baseDir , String matchRemaining , String filename , CatalogReader reader ) throws IOException { String relLocation = ( matchRemaining . length ( ) >= 1 ) ? location + \"/\" + matchRemaining : location ; File absLocation = new File ( baseDir , relLocation ) ; ConfigCatalog cc = reader . getFromAbsolutePath ( absLocation + \"/\" + filename ) ; if ( cc == null ) logger . warn ( \"Cant find catalog from scan: \" + absLocation + \"/\" + filename ) ; return cc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when we have a catalog built from a directory ( filename == CATSCAN ) [CODESPLIT] public CatalogBuilder makeCatalogFromDirectory ( File baseDir , String matchRemaining , URI baseURI ) throws IOException { String relLocation = ( matchRemaining . length ( ) >= 1 ) ? location + \"/\" + matchRemaining : location ; String name = ( matchRemaining . length ( ) >= 1 ) ? getName ( ) + \"/\" + matchRemaining : getName ( ) ; File absLocation = new File ( baseDir , relLocation ) ; // it must be a directory Path wantDir = absLocation . toPath ( ) ; if ( ! Files . exists ( wantDir ) ) throw new FileNotFoundException ( \"Requested catalog does not exist =\" + absLocation ) ; if ( ! Files . isDirectory ( wantDir ) ) throw new FileNotFoundException ( \"Not a directory =\" + absLocation ) ; // Setup and create catalog builder. CatalogBuilder catBuilder = new CatalogBuilder ( ) ; catBuilder . setBaseURI ( baseURI ) ; assert this . getParentCatalog ( ) != null ; DatasetBuilder top = new DatasetBuilder ( null ) ; top . transferMetadata ( this , true ) ; top . setName ( name ) ; top . put ( Dataset . Id , null ) ; // no id for top catBuilder . addDataset ( top ) ; // first look for catalogs try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( wantDir , \"*.xml\" ) ) { for ( Path p : ds ) { if ( ! Files . isDirectory ( p ) ) { String pfilename = p . getFileName ( ) . toString ( ) ; String urlPath = pfilename ; //String path = dataDirComplete.length() == 0 ? filename : dataDirComplete + \"/\" + filename;  // reletive starting from current directory CatalogRefBuilder catref = new CatalogRefBuilder ( top ) ; catref . setTitle ( urlPath ) ; catref . setHref ( urlPath ) ; top . addDataset ( catref ) ; } } } // now look for directories try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( wantDir ) ) { for ( Path dir : ds ) { if ( Files . isDirectory ( dir ) ) { String dfilename = dir . getFileName ( ) . toString ( ) ; String urlPath = ( matchRemaining . length ( ) >= 1 ) ? dfilename + \"/\" + matchRemaining : dfilename ; CatalogRefBuilder catref = new CatalogRefBuilder ( top ) ; catref . setTitle ( urlPath ) ; catref . setHref ( urlPath + \"/\" + CATSCAN ) ; catref . addToList ( Dataset . Properties , new Property ( \"CatalogScan\" , \"true\" ) ) ; top . addDataset ( catref ) ; } } } return catBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the known CollectionType that matches the given name ( ignoring case ) or null if the name is unknown . [CODESPLIT] public static CollectionType findType ( String name ) { if ( name == null ) return null ; for ( CollectionType m : members ) { if ( m . name . equalsIgnoreCase ( name ) ) return m ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a CollectionType that matches the given name by either matching a known type ( ignoring case ) or creating an unknown type . [CODESPLIT] public static CollectionType getType ( String name ) { if ( name == null ) return null ; CollectionType type = findType ( name ) ; return type != null ? type : new CollectionType ( name , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the i th value of the array . [CODESPLIT] public final void setValue ( int i , BaseType newVal ) { vals [ i ] = newVal ; BaseType parent = ( BaseType ) getTemplate ( ) . getParent ( ) ; vals [ i ] . setParent ( parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { for ( int i = 0 ; i < vals . length ; i ++ ) { // create new variable from template\r vals [ i ] = ( BaseType ) getTemplate ( ) . clone ( ) ; ( ( ClientIO ) vals [ i ] ) . deserialize ( source , sv , statusUI ) ; if ( statusUI != null && statusUI . userCancelled ( ) ) throw new DataReadException ( \"User cancelled\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { for ( int i = 0 ; i < vals . length ; i ++ ) { // LogStream.out.println(\"\\t\\t\\tI AM THE WALRUS!\");\r ( ( ClientIO ) vals [ i ] ) . externalize ( sink ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a CoordinateSystem to the dataset . [CODESPLIT] public void addCoordinateSystem ( CoordinateSystem cs ) { if ( cs == null ) throw new RuntimeException ( \"Attempted to add null CoordinateSystem to var \" + forVar . getFullName ( ) ) ; if ( coordSys == null ) coordSys = new ArrayList <> ( 5 ) ; coordSys . add ( cs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the description of the Variable . Default is to look for attributes in this order : CDM . LONG_NAME description title standard_name . [CODESPLIT] public String getDescription ( ) { if ( ( desc == null ) && ( forVar != null ) ) { Attribute att = forVar . findAttributeIgnoreCase ( CDM . LONG_NAME ) ; if ( ( att != null ) && att . isString ( ) ) desc = att . getStringValue ( ) ; if ( desc == null ) { att = forVar . findAttributeIgnoreCase ( \"description\" ) ; if ( ( att != null ) && att . isString ( ) ) desc = att . getStringValue ( ) ; } if ( desc == null ) { att = forVar . findAttributeIgnoreCase ( CDM . TITLE ) ; if ( ( att != null ) && att . isString ( ) ) desc = att . getStringValue ( ) ; } if ( desc == null ) { att = forVar . findAttributeIgnoreCase ( CF . STANDARD_NAME ) ; if ( ( att != null ) && att . isString ( ) ) desc = att . getStringValue ( ) ; } } return ( desc == null ) ? null : desc . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Unit String for this Variable . Default is to use the CDM . UNITS attribute . [CODESPLIT] public void setUnitsString ( String units ) { this . units = units ; forVar . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Unit String for the Variable . May be set explicitly else look for attribute CDM . UNITS . [CODESPLIT] public String getUnitsString ( ) { String result = units ; if ( ( result == null ) && ( forVar != null ) ) { Attribute att = forVar . findAttribute ( CDM . UNITS ) ; if ( att == null ) att = forVar . findAttributeIgnoreCase ( CDM . UNITS ) ; if ( ( att != null ) && att . isString ( ) ) result = att . getStringValue ( ) ; } return ( result == null ) ? null : result . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called from TdsInit on spring - managed auto - wired bean [CODESPLIT] public synchronized void init ( ReadMode readMode , PreferencesExt prefs ) { if ( readMode == null ) readMode = defaultReadMode ; this . prefs = prefs ; trackerNumber = prefs . getLong ( \"trackerNumber\" , 1 ) ; numberCatalogs = prefs . getInt ( \"numberCatalogs\" , 10 ) ; nextCatId = prefs . getLong ( \"nextCatId\" , 1 ) ; makeDebugActions ( ) ; this . contentRootPath = this . tdsContext . getThreddsDirectory ( ) ; this . contextPath = tdsContext . getContextPath ( ) ; reread ( readMode , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called from init () and from trigger controller [CODESPLIT] public synchronized boolean reread ( ReadMode readMode , boolean isStartup ) { readNow = System . currentTimeMillis ( ) ; logCatalogInit . info ( \"=========================================================================================\\n\" + \"ConfigCatalogInitialization readMode={} isStartup={}\" , readMode , isStartup ) ; catPathMap = new HashSet <> ( ) ; fcNameMap = new HashMap <> ( ) ; if ( ccc != null ) ccc . invalidateAll ( ) ; // remove anything in cache if ( fcCache != null ) fcCache . invalidateAll ( ) ; // remove anything in cache if ( ! isStartup && readMode == ReadMode . always ) trackerNumber ++ ; // must write a new database if TDS is already running and rereading all if ( ! isDebugMode || this . datasetTracker == null ) this . datasetTracker = new DatasetTrackerChronicle ( trackerDir , maxDatasets , trackerNumber ) ; boolean databaseAlreadyExists = datasetTracker . exists ( ) ; // detect if tracker database exists if ( ! databaseAlreadyExists ) { readMode = ReadMode . always ; logCatalogInit . info ( \"ConfigCatalogInitializion datasetTracker database does not exist, set readMode to=\" + readMode ) ; } if ( this . callback == null ) this . callback = new StatCallback ( readMode ) ; // going to reread global services allowedServices . clearGlobalServices ( ) ; switch ( readMode ) { case always : // if the database already exists, we need to close it // before we reinit if ( databaseAlreadyExists ) { logCatalogInit . info ( \"ConfigCatalogInitializion datasetTracker database already exists - closing it before reinitialization.\" ) ; try { this . datasetTracker . close ( ) ; } catch ( IOException e ) { logCatalogInit . error ( \"There was an error closing the datasetTracker database.\" , e ) ; } this . datasetTracker . reinit ( ) ; } this . catalogTracker = new CatalogTracker ( trackerDir , true , numberCatalogs , nextCatId ) ; this . dataRootTracker = new DataRootTracker ( trackerDir , true , callback ) ; this . dataRootPathMatcher = new DataRootPathMatcher ( ccc , dataRootTracker ) ; // starting over readRootCatalogs ( readMode ) ; break ; case check : this . catalogTracker = new CatalogTracker ( trackerDir , false , numberCatalogs , nextCatId ) ; // use existing catalog list this . dataRootTracker = new DataRootTracker ( trackerDir , false , callback ) ; // use existing data roots this . dataRootPathMatcher = new DataRootPathMatcher ( ccc , dataRootTracker ) ; readRootCatalogs ( readMode ) ; // read just roots to get global services checkExistingCatalogs ( readMode ) ; break ; case triggerOnly : this . catalogTracker = new CatalogTracker ( trackerDir , false , numberCatalogs , nextCatId ) ; // use existing catalog list this . dataRootTracker = new DataRootTracker ( trackerDir , false , callback ) ; // use existing data roots this . dataRootPathMatcher = new DataRootPathMatcher ( ccc , dataRootTracker ) ; readRootCatalogs ( readMode ) ; // read just roots to get global services break ; } numberCatalogs = catalogTracker . size ( ) ; nextCatId = catalogTracker . getNextCatId ( ) ; if ( prefs != null ) { prefs . putLong ( \"trackerNumber\" , trackerNumber ) ; prefs . putLong ( \"nextCatId\" , nextCatId ) ; prefs . putInt ( \"numberCatalogs\" , numberCatalogs ) ; } callback . finish ( ) ; logCatalogInit . info ( \"\\nConfigCatalogInitializion stats\\n\" + callback ) ; try { datasetTracker . save ( ) ; catalogTracker . save ( ) ; dataRootTracker . save ( ) ; } catch ( IOException e ) { // e.printStackTrace(); logCatalogInit . error ( \"datasetTracker.save() failed\" , e ) ; } // heres where we may be doing a switcheroo in a running TDS if ( dataRootManager != null ) dataRootManager . setDataRootPathMatcher ( dataRootPathMatcher ) ; if ( datasetManager != null ) datasetManager . setDatasetTracker ( datasetTracker ) ; // cleanup old version of the database if ( ! isStartup && readMode == ReadMode . always ) { DatasetTrackerChronicle . cleanupBefore ( trackerDir , trackerNumber ) ; } long took = System . currentTimeMillis ( ) - readNow ; logCatalogInit . info ( \"ConfigCatalogInitializion finished took={} msecs\" , took ) ; // cleanup catPathMap = null ; fcNameMap = null ; catalogTracker = null ; return true ; // ok }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "catalogRelpath must be relative to rootDir [CODESPLIT] private void checkCatalogToRead ( ReadMode readMode , String catalogRelPath , boolean isRoot , long lastRead ) throws IOException { if ( exceedLimit ) return ; catalogRelPath = StringUtils . cleanPath ( catalogRelPath ) ; File catalogFile = new File ( this . contentRootPath , catalogRelPath ) ; if ( ! catalogFile . exists ( ) ) { catalogTracker . removeCatalog ( catalogRelPath ) ; logCatalogInit . error ( ERROR + \"initCatalog(): Catalog [\" + catalogRelPath + \"] does not exist.\" ) ; return ; } long lastModified = catalogFile . lastModified ( ) ; if ( ! isRoot && readMode != ReadMode . always && lastModified < lastRead ) return ; // skip catalogs that havent changed if ( ! isRoot && readMode == ReadMode . triggerOnly ) return ; // skip non-root catalogs for trigger only if ( show ) System . out . printf ( \"initCatalog %s%n\" , catalogRelPath ) ; // make sure we havent already read it if ( catPathMap . contains ( catalogRelPath ) ) { logCatalogInit . error ( ERROR + \"initCatalog(): Catalog [\" + catalogRelPath + \"] already seen, possible loop (skip).\" ) ; return ; } catPathMap . add ( catalogRelPath ) ; Set < String > idSet = new HashSet <> ( ) ; // look for unique ids // if (logCatalogInit.isDebugEnabled()) logCatalogInit.debug(\"initCatalog {} -> {}\", path, f.getAbsolutePath()); // read it ConfigCatalog cat = readCatalog ( catalogRelPath , catalogFile . getPath ( ) ) ; if ( cat == null ) { logCatalogInit . error ( ERROR + \"initCatalog(): failed to read catalog <\" + catalogFile . getPath ( ) + \">.\" ) ; return ; } long catId = catalogTracker . put ( new CatalogExt ( 0 , catalogRelPath , isRoot , readNow ) ) ; if ( isRoot ) { if ( ccc != null ) ccc . put ( catalogRelPath , cat ) ; allowedServices . addGlobalServices ( cat . getServices ( ) ) ; if ( readMode == ReadMode . triggerOnly ) return ; // thats all we need } if ( callback != null ) callback . hasCatalogRef ( cat ) ; // look for datasetRoots for ( DatasetRootConfig p : cat . getDatasetRoots ( ) ) dataRootPathMatcher . addRoot ( p , catalogRelPath , readMode == ReadMode . always ) ; // check for duplicates on complete reread if ( callback == null ) { // LOOK WTF? List < String > disallowedServices = allowedServices . getDisallowedServices ( cat . getServices ( ) ) ; if ( ! disallowedServices . isEmpty ( ) ) { allowedServices . getDisallowedServices ( cat . getServices ( ) ) ; logCatalogInit . error ( ERROR + \"initCatalog(): declared services: \" + Arrays . toString ( disallowedServices . toArray ( ) ) + \" in catalog: \" + catalogFile . getPath ( ) + \" are disallowed in threddsConfig file\" ) ; } } // look for dataRoots in datasetScans and featureCollections dataRootPathMatcher . extractDataRoots ( catalogRelPath , cat . getDatasetsLocal ( ) , readMode == ReadMode . always , fcNameMap ) ; // get the directory path, reletive to the rootDir int pos = catalogRelPath . lastIndexOf ( \"/\" ) ; String dirPath = ( pos > 0 ) ? catalogRelPath . substring ( 0 , pos + 1 ) : \"\" ; processDatasets ( catId , readMode , dirPath , cat . getDatasetsLocal ( ) , idSet ) ; // recurse // look for catalogScans for ( CatalogScan catScan : cat . getCatalogScans ( ) ) { if ( exceedLimit ) return ; Path relLocation = Paths . get ( dirPath , catScan . getLocation ( ) ) ; Path absLocation = Paths . get ( catalogFile . getParent ( ) , catScan . getLocation ( ) ) ; // if (catalogWatcher != null) catalogWatcher.registerAll(absLocation); readCatsInDirectory ( readMode , relLocation . toString ( ) , absLocation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the actual work of reading a catalog . [CODESPLIT] private ConfigCatalog readCatalog ( String catalogRelPath , String catalogFullPath ) { URI uri ; try { // uri = new URI(\"file:\" + StringUtil2.escape(catalogFullPath, \"/:-_.\")); // needed ? uri = new URI ( this . contextPath + \"/catalog/\" + catalogRelPath ) ; } catch ( URISyntaxException e ) { logCatalogInit . error ( ERROR + \"readCatalog(): URISyntaxException=\" + e . getMessage ( ) ) ; return null ; } ConfigCatalogBuilder builder = new ConfigCatalogBuilder ( ) ; try { // read the catalog logCatalogInit . info ( \"-------readCatalog(): path=\" + catalogRelPath ) ; ConfigCatalog cat = ( ConfigCatalog ) builder . buildFromLocation ( catalogFullPath , uri ) ; if ( builder . hasFatalError ( ) ) { logCatalogInit . error ( ERROR + \"   invalid catalog -- \" + builder . getErrorMessage ( ) ) ; return null ; } if ( builder . getErrorMessage ( ) . length ( ) > 0 ) logCatalogInit . debug ( builder . getErrorMessage ( ) ) ; return cat ; } catch ( Throwable t ) { logCatalogInit . error ( ERROR + \"  Exception on catalog=\" + catalogFullPath + \" \" + t . getMessage ( ) + \"\\n log=\" + builder . getErrorMessage ( ) , t ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dirPath = the directory path reletive to the rootDir [CODESPLIT] private void processDatasets ( long catId , ReadMode readMode , String dirPath , List < Dataset > datasets , Set < String > idMap ) throws IOException { if ( exceedLimit ) return ; for ( Dataset ds : datasets ) { if ( datasetTracker . trackDataset ( catId , ds , callback ) ) countDatasets ++ ; if ( maxDatasetsProcess > 0 && countDatasets > maxDatasetsProcess ) exceedLimit = true ; // look for duplicate ids String id = ds . getID ( ) ; if ( id != null ) { if ( idMap . contains ( id ) ) { logCatalogInit . error ( ERROR + \"Duplicate id on  '\" + ds . getName ( ) + \"' id= '\" + id + \"'\" ) ; } else { idMap . add ( id ) ; } } if ( ( ds instanceof DatasetScan ) || ( ds instanceof FeatureCollectionRef ) ) continue ; if ( ds instanceof CatalogScan ) continue ; if ( ds instanceof CatalogRef ) { // follow catalog refs CatalogRef catref = ( CatalogRef ) ds ; String href = catref . getXlinkHref ( ) ; // if (logCatalogInit.isDebugEnabled()) logCatalogInit.debug(\"  catref.getXlinkHref=\" + href); // Check that catRef is relative if ( ! href . startsWith ( \"http:\" ) ) { // Clean up relative URLs that start with \"./\" if ( href . startsWith ( \"./\" ) ) { href = href . substring ( 2 ) ; } String path ; String contextPathPlus = this . contextPath + \"/\" ; if ( href . startsWith ( contextPathPlus ) ) { path = href . substring ( contextPathPlus . length ( ) ) ; // absolute starting from content root } else if ( href . startsWith ( \"/\" ) ) { // Drop the catRef because it points to a non-TDS served catalog. logCatalogInit . error ( ERROR + \"Skipping catalogRef <xlink:href=\" + href + \">. Reference is relative to the server outside the context path [\" + contextPathPlus + \"]. \" + \"Parent catalog info: Name=\\\"\" + catref . getParentCatalog ( ) . getName ( ) + \"\\\"; Base URI=\\\"\" + catref . getParentCatalog ( ) . getUriString ( ) + \"\\\"; dirPath=\\\"\" + dirPath + \"\\\".\" ) ; continue ; } else { path = dirPath + href ; // reletive starting from current directory } CatalogExt ext = catalogTracker . get ( path ) ; long lastRead = ( ext == null ) ? 0 : ext . getLastRead ( ) ; checkCatalogToRead ( readMode , path , false , lastRead ) ; } } else { // recurse through nested datasets processDatasets ( catId , readMode , dirPath , ds . getDatasetsLocal ( ) , idMap ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dirPath is the directory relative to rootDir directory is absolute [CODESPLIT] private void readCatsInDirectory ( ReadMode readMode , String dirPath , Path directory ) throws IOException { if ( exceedLimit ) return ; // do any catalogs first try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( directory , \"*.xml\" ) ) { for ( Path p : ds ) { if ( ! Files . isDirectory ( p ) ) { // path must be relative to rootDir String filename = p . getFileName ( ) . toString ( ) ; String path = dirPath . length ( ) == 0 ? filename : dirPath + \"/\" + filename ; // reletive starting from current directory CatalogExt ext = catalogTracker . get ( path ) ; long lastRead = ( ext == null ) ? 0 : ext . getLastRead ( ) ; checkCatalogToRead ( readMode , path , false , lastRead ) ; } } } // now recurse into the directory try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( directory ) ) { for ( Path dir : ds ) { if ( Files . isDirectory ( dir ) ) { String dirPathChild = dirPath + \"/\" + dir . getFileName ( ) . toString ( ) ; // reletive starting from current directory readCatsInDirectory ( readMode , dirPathChild , dir ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public void makeDebugActions ( ) { DebugCommands . Category debugHandler = debugCommands . findCategory ( \"Catalogs\" ) ; DebugCommands . Action act ; act = new DebugCommands . Action ( \"showCatalogExt\" , \"Show known catalogs\" ) { public void doAction ( DebugCommands . Event e ) { e . pw . printf ( \"numberCatalogs=%d nextCatId=%d%n\" , numberCatalogs , nextCatId ) ; e . pw . printf ( \"%nid  root  lastRead     path%n\" ) ; CatalogTracker catalogTracker = new CatalogTracker ( trackerDir , false , numberCatalogs , 0 ) ; for ( CatalogExt cat : catalogTracker . getCatalogs ( ) ) { e . pw . printf ( \"%3d: %5s %s %s%n\" , cat . getCatId ( ) , cat . isRoot ( ) , CalendarDate . of ( cat . getLastRead ( ) ) , cat . getCatRelLocation ( ) ) ; } } } ; debugHandler . addAction ( act ) ; act = new DebugCommands . Action ( \"showRoots\" , \"Show root catalogs\" ) { public void doAction ( DebugCommands . Event e ) { StringBuilder sbuff = new StringBuilder ( ) ; synchronized ( ConfigCatalogInitialization . this ) { for ( String catPath : rootCatalogKeys ) { sbuff . append ( \" catalog= \" ) . append ( catPath ) . append ( \"\\n\" ) ; //String filename = StringUtil2.unescape(cat.getUriString()); //sbuff.append(\" from= \").append(filename).append(\"\\n\"); } } e . pw . println ( ) ; e . pw . println ( Escape . html ( sbuff . toString ( ) ) ) ; } } ; debugHandler . addAction ( act ) ; act = new DebugCommands . Action ( \"showStats\" , \"Show catalog initialization stats\" ) { public void doAction ( DebugCommands . Event e ) { if ( callback != null ) e . pw . printf ( \"%n%s%n\" , Escape . html ( callback . toString ( ) ) ) ; else e . pw . printf ( \"N/A%n\" ) ; } } ; debugHandler . addAction ( act ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if point lies between two longitudes deal with wrapping . [CODESPLIT] static public boolean betweenLon ( double lon , double lonBeg , double lonEnd ) { lonBeg = lonNormal ( lonBeg , lon ) ; lonEnd = lonNormal ( lonEnd , lon ) ; return ( lon >= lonBeg ) && ( lon <= lonEnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "put longitude into the range [ start start + 360 ] deg [CODESPLIT] static public double lonNormalFrom ( double lon , double start ) { while ( lon < start ) lon += 360 ; while ( lon > start + 360 ) lon -= 360 ; return lon ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a nicely formatted representation of a latitude eg 40 . 34N or 12 . 9S . [CODESPLIT] static public String latToString ( double lat , int ndec ) { boolean is_north = ( lat >= 0.0 ) ; if ( ! is_north ) lat = - lat ; String f = \"%.\" + ndec + \"f\" ; Formatter latBuff = new Formatter ( ) ; latBuff . format ( f , lat ) ; latBuff . format ( \"%s\" , is_north ? \"N\" : \"S\" ) ; return latBuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a nicely formatted representation of a longitude eg 120 . 3W or 99 . 99E . [CODESPLIT] static public String lonToString ( double lon , int ndec ) { double wlon = lonNormal ( lon ) ; boolean is_east = ( wlon >= 0.0 ) ; if ( ! is_east ) wlon = - wlon ; String f = \"%.\" + ndec + \"f\" ; Formatter latBuff = new Formatter ( ) ; latBuff . format ( f , wlon ) ; latBuff . format ( \"%s\" , is_east ? \"E\" : \"W\" ) ; return latBuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this base quantity to another base quantity . [CODESPLIT] public int compareTo ( final BaseQuantity that ) { int comp ; if ( this == that ) { comp = 0 ; } else { comp = getName ( ) . compareToIgnoreCase ( that . getName ( ) ) ; if ( comp == 0 && getSymbol ( ) != null ) { comp = getSymbol ( ) . compareTo ( that . getSymbol ( ) ) ; } } return comp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) { System . out . println ( \"AMOUNT_OF_SUBSTANCE.getName() = \" + AMOUNT_OF_SUBSTANCE . getName ( ) ) ; System . out . println ( \"LUMINOUS_INTENSITY.getSymbol() = \" + LUMINOUS_INTENSITY . getSymbol ( ) ) ; System . out . println ( \"PLANE_ANGLE.getSymbol() = \" + PLANE_ANGLE . getSymbol ( ) ) ; System . out . println ( \"LENGTH.equals(LENGTH) = \" + LENGTH . equals ( LENGTH ) ) ; System . out . println ( \"LENGTH.equals(MASS) = \" + LENGTH . equals ( MASS ) ) ; System . out . println ( \"LENGTH.equals(PLANE_ANGLE) = \" + LENGTH . equals ( PLANE_ANGLE ) ) ; System . out . println ( \"PLANE_ANGLE.equals(PLANE_ANGLE) = \" + PLANE_ANGLE . equals ( PLANE_ANGLE ) ) ; System . out . println ( \"PLANE_ANGLE.equals(SOLID_ANGLE) = \" + PLANE_ANGLE . equals ( SOLID_ANGLE ) ) ; System . out . println ( \"LENGTH.compareTo(LENGTH) = \" + LENGTH . compareTo ( LENGTH ) ) ; System . out . println ( \"LENGTH.compareTo(MASS) = \" + LENGTH . compareTo ( MASS ) ) ; System . out . println ( \"LENGTH.compareTo(PLANE_ANGLE) = \" + LENGTH . compareTo ( PLANE_ANGLE ) ) ; System . out . println ( \"PLANE_ANGLE.compareTo(PLANE_ANGLE) = \" + PLANE_ANGLE . compareTo ( PLANE_ANGLE ) ) ; System . out . println ( \"PLANE_ANGLE.compareTo(SOLID_ANGLE) = \" + PLANE_ANGLE . compareTo ( SOLID_ANGLE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the currently selected InvDataset . [CODESPLIT] public DatasetNode getSelectedDataset ( ) { InvCatalogTreeNode tnode = getSelectedNode ( ) ; return tnode == null ? null : tnode . ds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the currently selected InvDataset . [CODESPLIT] public void setSelectedDataset ( Dataset ds ) { if ( ds == null ) return ; TreePath path = makePath ( ds ) ; if ( path == null ) return ; tree . setSelectionPath ( path ) ; tree . scrollPathToVisible ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the TreePath corresponding to the given TreeNode . [CODESPLIT] TreePath makeTreePath ( TreeNode node ) { ArrayList < TreeNode > path = new ArrayList <> ( ) ; path . add ( node ) ; TreeNode parent = node . getParent ( ) ; while ( parent != null ) { path . add ( 0 , parent ) ; parent = parent . getParent ( ) ; } Object [ ] paths = path . toArray ( ) ; return new TreePath ( paths ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open all nodes of the tree . [CODESPLIT] public void openAll ( boolean includeCatref ) { if ( catalog == null ) return ; open ( ( InvCatalogTreeNode ) model . getRoot ( ) , includeCatref ) ; tree . repaint ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the InvCatalog to display . The catalog is read asynchronously and displayed if successfully read . You must use a PropertyChangeEventListener to be notified if successful . [CODESPLIT] public void setCatalog ( String location ) { CatalogBuilder builder = new CatalogBuilder ( ) ; try { Catalog cat = builder . buildFromLocation ( location , null ) ; setCatalog ( cat ) ; } catch ( Exception ioe ) { JOptionPane . showMessageDialog ( this , \"Error opening catalog location \" + location + \" err=\" + builder . getErrorMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the catalog to be displayed . If ok then a Catalog PropertyChangeEvent is sent . [CODESPLIT] public void setCatalog ( Catalog catalog ) { if ( catalog == null ) return ; String catalogName = catalog . getBaseURI ( ) . toString ( ) ; this . catalog = catalog ; // send catalog event setCatalogURL ( catalogName ) ; // display tree // this sends TreeNode events model = new InvCatalogTreeModel ( catalog ) ; tree . setModel ( model ) ; // debug if ( debugTree ) { System . out . println ( \"*** catalog/showJTree =\" ) ; showNode ( tree . getModel ( ) , tree . getModel ( ) . getRoot ( ) ) ; System . out . println ( \"*** \" ) ; } // look for a specific dataset int pos = catalogName . indexOf ( ' ' ) ; if ( pos >= 0 ) { String id = catalogName . substring ( pos + 1 ) ; Dataset dataset = catalog . findDatasetByID ( id ) ; if ( dataset != null ) { setSelectedDataset ( dataset ) ; firePropertyChangeEvent ( new PropertyChangeEvent ( this , \"Selection\" , null , dataset ) ) ; } } // send catalog event firePropertyChangeEvent ( new PropertyChangeEvent ( this , \"Catalog\" , null , catalogName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] private void showNode ( TreeModel tree , Object node ) { if ( node == null ) return ; InvCatalogTreeNode tnode = ( InvCatalogTreeNode ) node ; DatasetNode cp = tnode . ds ; System . out . println ( \" node= \" + cp . getName ( ) + \" leaf= \" + tree . isLeaf ( node ) ) ; for ( int i = 0 ; i < tree . getChildCount ( node ) ; i ++ ) showNode ( tree , tree . getChild ( node , i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging only [CODESPLIT] public void showInfo ( Formatter f , Grib1Customizer cust1 ) { //f.format(\"%nVariables%n\"); //f.format(\"%n  %3s %3s %3s%n\", \"time\", \"vert\", \"ens\"); GribRecordStats all = new GribRecordStats ( ) ; for ( VariableBag vb : gribvars ) { f . format ( \"Variable %s (%d)%n\" , Grib1Iosp . makeVariableName ( cust , gribConfig , vb . first . getPDSsection ( ) ) , vb . hashCode ( ) ) ; vb . coordND . showInfo ( f , all ) ; //f.format(\"  %3d %3d %3d %s records = %d density = %f hash=%d\", vb.timeCoordIndex, vb.vertCoordIndex, vb.ensCoordIndex, //        vname, vb.atomList.size(), vb.recordMap.density(), vb.cdmHash); f . format ( \"%n\" ) ; } f . format ( \"%n all= %s\" , all . show ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for aliases . [CODESPLIT] @ Override protected void findCoordinateAxes ( NetcdfDataset ds ) { for ( VarProcess vp : varList ) { if ( vp . isCoordinateVariable ) continue ; Variable ncvar = vp . v ; if ( ! ( ncvar instanceof VariableDS ) ) continue ; // cant be a structure String dimName = findAlias ( ds , ncvar ) ; if ( dimName . length ( ) == 0 ) // none continue ; Dimension dim = ds . findDimension ( dimName ) ; if ( null != dim ) { vp . isCoordinateAxis = true ; parseInfo . format ( \" Coordinate Axis added (GDV alias) = %s for dimension %s%n\" , vp . v . getFullName ( ) , dimName ) ; } } super . findCoordinateAxes ( ds ) ; // desperado findCoordinateAxesForce ( ds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for an coord_axis or coord_alias attribute [CODESPLIT] private String findAlias ( NetcdfDataset ds , Variable v ) { String alias = ds . findAttValueIgnoreCase ( v , \"coord_axis\" , null ) ; if ( alias == null ) alias = ds . findAttValueIgnoreCase ( v , \"coord_alias\" , \"\" ) ; return alias ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bigendian [CODESPLIT] public final void writeInt ( int v ) throws IOException { write ( int3 ( v ) ) ; write ( int2 ( v ) ) ; write ( int1 ( v ) ) ; write ( int0 ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an int in a variable - length format . Writes between one and five bytes . Smaller values take fewer bytes . Negative numbers are not supported . [CODESPLIT] public int writeVInt ( int i ) throws IOException { int count = 0 ; while ( ( i & ~ 0x7F ) != 0 ) { writeByte ( ( byte ) ( ( i & 0x7f ) | 0x80 ) ) ; i >>>= 7 ; count ++ ; } writeByte ( ( byte ) i ) ; return count + 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an long in a variable - length format . Writes between one and nine ( ? ) bytes . Smaller values take fewer bytes . Negative numbers are not supported . [CODESPLIT] public int writeVLong ( long i ) throws IOException { int count = 0 ; while ( ( i & ~ 0x7F ) != 0 ) { writeByte ( ( byte ) ( ( i & 0x7f ) | 0x80 ) ) ; i >>>= 7 ; count ++ ; } writeByte ( ( byte ) i ) ; return count + 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a string . ( vlen ) [ char ] [CODESPLIT] public int writeString ( String s ) throws IOException { int length = s . length ( ) ; int count = writeVInt ( length ) ; count += writeChars ( s , 0 , length ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a sequence of UTF - 8 encoded characters from a string . [CODESPLIT] public int writeChars ( String s , int start , int length ) throws IOException { final int end = start + length ; int count = 0 ; for ( int i = start ; i < end ; i ++ ) { final int code = ( int ) s . charAt ( i ) ; if ( code >= 0x01 && code <= 0x7F ) { writeByte ( ( byte ) code ) ; count ++ ; } else if ( ( ( code >= 0x80 ) && ( code <= 0x7FF ) ) || code == 0 ) { writeByte ( ( byte ) ( 0xC0 | ( code >> 6 ) ) ) ; writeByte ( ( byte ) ( 0x80 | ( code & 0x3F ) ) ) ; count += 2 ; } else { writeByte ( ( byte ) ( 0xE0 | ( code >>> 12 ) ) ) ; writeByte ( ( byte ) ( 0x80 | ( ( code >> 6 ) & 0x3F ) ) ) ; writeByte ( ( byte ) ( 0x80 | ( code & 0x3F ) ) ) ; count += 3 ; } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private char [] chars ; [CODESPLIT] public String readString ( ) throws IOException { int length = readVInt ( ) ; // if (chars == null || length > chars.length) char [ ] chars = new char [ length ] ; readChars ( chars , 0 , length ) ; return new String ( chars , 0 , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads UTF - 8 encoded characters into an array . [CODESPLIT] public void readChars ( char [ ] buffer , int start , int length ) throws IOException { final int end = start + length ; for ( int i = start ; i < end ; i ++ ) { byte b = readByte ( ) ; if ( ( b & 0x80 ) == 0 ) buffer [ i ] = ( char ) ( b & 0x7F ) ; else if ( ( b & 0xE0 ) != 0xE0 ) { buffer [ i ] = ( char ) ( ( ( b & 0x1F ) << 6 ) | ( readByte ( ) & 0x3F ) ) ; } else buffer [ i ] = ( char ) ( ( ( b & 0x0F ) << 12 ) | ( ( readByte ( ) & 0x3F ) << 6 ) | ( readByte ( ) & 0x3F ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from this record . [CODESPLIT] public void readData ( RandomAccessFile raf , Range gateRange , IndexIterator ii ) throws IOException { final int REC_SIZE = 6144 ; raf . seek ( offset ) ; byte [ ] data = new byte [ bins ] ; float [ ] dd = new float [ bins ] ; byte d ; int nb = 0 ; short a00 ; // raf.readFully(data);\r if ( dataRead > 0 ) { raf . seek ( offset ) ; for ( int i = 0 ; i < dataRead ; i ++ ) { d = raf . readByte ( ) ; dd [ i ] = SigmetIOServiceProvider . calcData ( SigmetIOServiceProvider . recHdr , getDataType ( ) , d ) ; nb ++ ; } } // System.out.println(\"this is az \" + getAz());\r raf . seek ( offset1 ) ; int cur_len = offset1 ; while ( nb < ( int ) bins ) { // --- Check if the code=1 (\"1\" means an end of a ray)\r a00 = raf . readShort ( ) ; cur_len = cur_len + 2 ; if ( a00 == ( short ) 1 ) { for ( int uk = 0 ; uk < ( int ) bins ; uk ++ ) { dd [ uk ] = - 999.99f ; } break ; } if ( a00 < 0 ) { // -- This is data\r int nwords = a00 & 0x7fff ; int dataRead1 = nwords * 2 ; int pos = 0 ; if ( cur_len % REC_SIZE == 0 ) { pos = 0 ; break ; } raf . seek ( cur_len ) ; for ( int i = 0 ; i < dataRead1 ; i ++ ) { d = raf . readByte ( ) ; dd [ nb ] = SigmetIOServiceProvider . calcData ( SigmetIOServiceProvider . recHdr , getDataType ( ) , d ) ; nb = nb + 1 ; cur_len = cur_len + 1 ; if ( nb % REC_SIZE == 0 ) { pos = i + 1 ; break ; } } if ( pos > 0 ) { break ; } } else if ( a00 > 0 & a00 != 1 ) { int num_zero = a00 * 2 ; int dataRead1 = num_zero ; for ( int k = 0 ; k < dataRead1 ; k ++ ) { dd [ nb + k ] = SigmetIOServiceProvider . calcData ( SigmetIOServiceProvider . recHdr , getDataType ( ) , ( byte ) 0 ) ; } nb = nb + dataRead1 ; if ( cur_len % REC_SIZE == 0 ) { break ; } } } // ------ end of while for num_bins---------------------------------\r for ( int gateIdx : gateRange ) { if ( gateIdx >= bins ) ii . setFloatNext ( Float . NaN ) ; else ii . setFloatNext ( dd [ gateIdx ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we are running with only ncx index files no data [CODESPLIT] public static void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugRead = debugFlag . isSet ( \"Grib/showRead\" ) ; debugIndexOnly = debugFlag . isSet ( \"Grib/indexOnly\" ) ; debugIndexOnlyShow = debugFlag . isSet ( \"Grib/indexOnlyShow\" ) ; debugGbxIndexOnly = debugFlag . isSet ( \"Grib/debugGbxIndexOnly\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <! -- C : / data / dt2 / station / ndbc . nc -- > <stationFeature > <stationId > : station < / stationId > <stationDesc > : description < / stationDesc > <coordAxis type = lat > lat< / coordAxis > <coordAxis type = lon > lon< / coordAxis > <coordAxis type = height > 0< / coordAxis > <table dim = time > <coordAxis type = time > time< / coordAxis > < / table > < / stationFeature > [CODESPLIT] public TableConfig getConfig ( FeatureType wantFeatureType , NetcdfDataset ds , Formatter errlog ) { Dimension obsDim = ds . getUnlimitedDimension ( ) ; if ( obsDim == null ) { CoordinateAxis axis = CoordSysEvaluator . findCoordByType ( ds , AxisType . Time ) ; if ( ( axis != null ) && axis . isScalar ( ) ) obsDim = axis . getDimension ( 0 ) ; } if ( obsDim == null ) { errlog . format ( \"Must have an Observation dimension: unlimited dimension, or from Time Coordinate\" ) ; return null ; } boolean hasStruct = Evaluator . hasNetcdf3RecordStructure ( ds ) ; // wants a Point\r if ( ( wantFeatureType == FeatureType . POINT ) ) { TableConfig nt = new TableConfig ( Table . Type . Structure , hasStruct ? \"record\" : obsDim . getShortName ( ) ) ; nt . structName = \"record\" ; nt . structureType = hasStruct ? TableConfig . StructureType . Structure : TableConfig . StructureType . PsuedoStructure ; nt . featureType = FeatureType . POINT ; CoordSysEvaluator . findCoords ( nt , ds , null ) ; return nt ; } // otherwise, make it a Station\r TableConfig nt = new TableConfig ( Table . Type . Top , \"station\" ) ; nt . featureType = FeatureType . STATION ; nt . lat = CoordSysEvaluator . findCoordNameByType ( ds , AxisType . Lat ) ; nt . lon = CoordSysEvaluator . findCoordNameByType ( ds , AxisType . Lon ) ; nt . stnId = ds . findAttValueIgnoreCase ( null , \"station\" , null ) ; nt . stnDesc = ds . findAttValueIgnoreCase ( null , \"description\" , null ) ; if ( nt . stnDesc == null ) nt . stnDesc = ds . findAttValueIgnoreCase ( null , \"comment\" , null ) ; TableConfig obs = new TableConfig ( Table . Type . Structure , hasStruct ? \"record\" : obsDim . getShortName ( ) ) ; obs . structName = \"record\" ; obs . structureType = hasStruct ? TableConfig . StructureType . Structure : TableConfig . StructureType . PsuedoStructure ; obs . dimName = obsDim . getShortName ( ) ; obs . time = CoordSysEvaluator . findCoordNameByType ( ds , AxisType . Time ) ; nt . addChild ( obs ) ; return nt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array ps = readArray ( psVar , timeIndex ) ; Index psIndex = ps . getIndex ( ) ; int nz = sigma . length ; int [ ] shape2D = ps . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; ArrayDouble . D3 result = new ArrayDouble . D3 ( nz , ny , nx ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { double psVal = ps . getDouble ( psIndex . set ( y , x ) ) ; for ( int z = 0 ; z < nz ; z ++ ) { result . set ( z , y , x , ptop + sigma [ z ] * ( psVal - ptop ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array ps = readArray ( psVar , timeIndex ) ; Index psIndex = ps . getIndex ( ) ; int nz = sigma . length ; ArrayDouble . D1 result = new ArrayDouble . D1 ( nz ) ; double psVal = ps . getDouble ( psIndex . set ( yIndex , xIndex ) ) ; for ( int z = 0 ; z < nz ; z ++ ) { result . set ( z , ptop + sigma [ z ] * ( psVal - ptop ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a member . [CODESPLIT] public void addMember ( Member m ) { members . add ( m ) ; if ( memberHash != null ) memberHash . put ( m . getName ( ) , m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given member [CODESPLIT] public int hideMember ( Member m ) { if ( m == null ) return - 1 ; int index = members . indexOf ( m ) ; members . remove ( m ) ; if ( memberHash != null ) memberHash . remove ( m . getName ( ) ) ; return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the names of the members . [CODESPLIT] public java . util . List < String > getMemberNames ( ) { List < String > memberNames = new ArrayList <> ( ) ; for ( Member m : members ) { memberNames . add ( m . getName ( ) ) ; } return memberNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the member by its name . [CODESPLIT] public Member findMember ( String memberName ) { if ( memberName == null ) return null ; if ( memberHash == null ) { // delay making the hash table until needed int initial_capacity = ( int ) ( members . size ( ) / .75 ) + 1 ; memberHash = new HashMap <> ( initial_capacity ) ; for ( Member m : members ) memberHash . put ( m . getName ( ) , m ) ; } return memberHash . get ( memberName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the bitmap array when needed return null if none . [CODESPLIT] @ Nullable public byte [ ] getBitmap ( RandomAccessFile raf ) throws IOException { if ( startingPosition <= 0 ) { throw new IllegalStateException ( \"Grib1 Bit map has bad starting position\" ) ; } raf . seek ( startingPosition ) ; // octet 1-3 (length of section)\r int length = GribNumbers . uint3 ( raf ) ; // octet 4 unused bits\r raf . read ( ) ; // unused\r // octets 5-6\r int bm = raf . readShort ( ) ; if ( bm != 0 ) { logger . warn ( \"Grib1 Bit map section pre-defined (provided by center) bitmap number = {}\" , bm ) ; return null ; } // not sure if length is set correctly when pre-define bitmap is used, so  wait until that to test\r // seeing a -1, bail out\r if ( length <= 6 || length > 10e6 ) { // look max  ??\r return null ; } // read the bits as integers\r int n = length - 6 ; byte [ ] data = new byte [ n ] ; raf . readFully ( data ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the state from the last saved in the PreferencesExt . [CODESPLIT] public void restoreState ( PreferencesExt store ) { if ( store == null ) return ; int ncols = table . getColumnCount ( ) ; // stored column order int [ ] modelIndex = ( int [ ] ) store . getBean ( \"ColumnOrder\" , null ) ; if ( ( modelIndex != null ) && ( modelIndex . length == ncols ) ) { // what about invisible ?? // make invisible any not stored boolean [ ] visible = new boolean [ ncols ] ; for ( int aModelIndex : modelIndex ) if ( aModelIndex < ncols ) visible [ aModelIndex ] = true ; // modify popup menu for ( int i = 0 ; i < ncols ; i ++ ) if ( ! visible [ i ] ) { //System.out.println( colName[i]+\" hide \"+i); acts [ i ] . hideColumn ( ) ; acts [ i ] . putValue ( BAMutil . STATE , new Boolean ( false ) ) ; } // now set the header order TableColumnModel tcm = table . getColumnModel ( ) ; int n = Math . min ( modelIndex . length , table . getColumnCount ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { TableColumn tc = tcm . getColumn ( i ) ; tc . setModelIndex ( modelIndex [ i ] ) ; String name = model . getColumnName ( modelIndex [ i ] ) ; tc . setHeaderValue ( name ) ; tc . setIdentifier ( name ) ; if ( useThreads && ( modelIndex [ i ] == threadCol ) ) { threadHeaderRenderer = new ThreadHeaderRenderer ( threadCol ) ; tc . setHeaderRenderer ( threadHeaderRenderer ) ; } else tc . setHeaderRenderer ( new SortedHeaderRenderer ( name , modelIndex [ i ] ) ) ; } } // set the column widths Object colWidths = store . getBean ( \"ColumnWidths\" , null ) ; if ( colWidths == null ) return ; int [ ] size = ( int [ ] ) colWidths ; setColumnWidths ( size ) ; if ( debug ) { System . out . println ( \" read widths = \" ) ; for ( int aSize : size ) System . out . print ( \" \" + aSize ) ; System . out . println ( ) ; } boolean isThreadsOn = store . getBoolean ( \"isThreadsOn\" , false ) ; if ( useThreads ) { model . setThreadsOn ( isThreadsOn ) ; threadHeaderRenderer . setOn ( isThreadsOn ) ; } int colNo = store . getInt ( \"SortOnCol\" , 0 ) ; boolean reverse = store . getBoolean ( \"SortReverse\" , false ) ; model . setSortCol ( colNo ) ; model . setReverse ( reverse ) ; setSortCol ( colNo , reverse ) ; model . sort ( ) ; table . fireDataChanged ( ) ; } private void setColumnWidths  ( int [ ] sizes ) { TableColumnModel tcm = table . getColumnModel ( ) ; for ( int i = 0 ; i < table . getColumnCount ( ) ; i ++ ) { TableColumn tc = tcm . getColumn ( i ) ; int maxw = ( ( sizes == null ) || ( i >= sizes . length ) ) ? 10 : sizes [ i ] ; //     model.getPreferredWidthForColumn(tc) : sizes[i]; tc . setPreferredWidth ( maxw ) ; } //table.sizeColumnsToFit(0);     //  must be called due to a JTable bug } public void setColOn  ( int colno , boolean state , int pos ) { // System.out.println(\"setColOn \"+colno+\" \"+state+\" \"+pos); acts [ colno ] . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; if ( state ) acts [ colno ] . addAtPos ( pos ) ; else acts [ colno ] . hideColumn ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save state to the PreferencesExt . [CODESPLIT] public void saveState ( PreferencesExt store ) { if ( store == null ) return ; int ncols = table . getColumnCount ( ) ; int [ ] size = new int [ ncols ] ; int [ ] modelIndex = new int [ ncols ] ; TableColumnModel tcm = table . getColumnModel ( ) ; for ( int i = 0 ; i < ncols ; i ++ ) { TableColumn tc = tcm . getColumn ( i ) ; size [ i ] = tc . getWidth ( ) ; modelIndex [ i ] = tc . getModelIndex ( ) ; } store . putBeanObject ( \"ColumnWidths\" , size ) ; store . putBeanObject ( \"ColumnOrder\" , modelIndex ) ; store . putInt ( \"SortOnCol\" , model . getSortCol ( ) ) ; store . putBoolean ( \"SortReverse\" , model . getReverse ( ) ) ; store . putBoolean ( \"isThreadsOn\" , model . isThreadsOn ( ) ) ; if ( debug ) { System . out . println ( \" store widths = \" ) ; for ( int aSize : size ) System . out . print ( \" \" + aSize ) ; System . out . println ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the currently selected rows . [CODESPLIT] public Iterator getSelectedRows ( ) { TreePath [ ] paths = table . getSelectionPaths ( ) ; if ( ( paths == null ) || ( paths . length < 1 ) ) return null ; HashSet set = new HashSet ( 2 * paths . length ) ; for ( TreePath path : paths ) { model . addRowsToSetFromPath ( table . getTree ( ) , path , set ) ; } return set . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the current selection to this row . [CODESPLIT] public void setSelectedRow ( int rowno ) { if ( ( rowno < 0 ) || ( rowno >= model . getRowCount ( ) ) ) return ; if ( debugSetPath ) System . out . println ( \"TreeTableSorted setSelected \" + rowno ) ; selectedRow = model . getRow ( rowno ) ; TreePath path = model . getPath ( selectedRow ) ; if ( path != null ) table . setSelectionPath ( path ) ; // for mysterious reasons, gotta do it again later invokeSetPath ( ) ; ensureRowIsVisible ( rowno ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this array translates the column index to the model index [CODESPLIT] public int [ ] getModelIndex ( ) { int [ ] modelIndex = new int [ model . getColumnCount ( ) ] ; try { TableColumnModel tcm = table . getColumnModel ( ) ; for ( int i = 0 ; i < model . getColumnCount ( ) ; i ++ ) { TableColumn tc = tcm . getColumn ( i ) ; modelIndex [ i ] = tc . getModelIndex ( ) ; } } catch ( java . lang . ArrayIndexOutOfBoundsException e ) { //can happen when model size increases } return modelIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void ensureRowIsVisible ( int nRow ) { Rectangle visibleRect = table . getCellRect ( nRow , 0 , true ) ; if ( debugSetPath ) System . out . println ( \"----ensureRowIsVisible = \" + visibleRect ) ; if ( visibleRect != null ) { visibleRect . x = scrollPane . getViewport ( ) . getViewPosition ( ) . x ; table . scrollRectToVisible ( visibleRect ) ; table . repaint ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Copy constructor . This makes a local copy of all the data in the from StrucureData . @param from copy from here [CODESPLIT] public void setMemberData ( StructureMembers . Member m , Array data ) { if ( data == null ) throw new IllegalArgumentException ( \"data cant be null\" ) ; memberData . put ( m , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data array of any type as an Array . [CODESPLIT] public Array getArray ( StructureMembers . Member m ) { if ( m == null ) throw new IllegalArgumentException ( \"member is null\" ) ; return memberData . get ( m ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type double . [CODESPLIT] public double getScalarDouble ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getDouble ( Index . scalarIndexImmutable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get java double array for a member of type double . [CODESPLIT] public double [ ] getJavaArrayDouble ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( double [ ] ) data . getStorage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type float . [CODESPLIT] public float getScalarFloat ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getFloat ( Index . scalarIndexImmutable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get java float array for a member of type float . [CODESPLIT] public float [ ] getJavaArrayFloat ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( float [ ] ) data . getStorage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type byte . [CODESPLIT] public byte getScalarByte ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getByte ( Index . scalarIndexImmutable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get java byte array for a member of type byte . [CODESPLIT] public byte [ ] getJavaArrayByte ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( byte [ ] ) data . getStorage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type int . [CODESPLIT] public int getScalarInt ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getInt ( Index . scalarIndexImmutable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get java int array for a member of type int . [CODESPLIT] public int [ ] getJavaArrayInt ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( int [ ] ) data . getStorage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type short . [CODESPLIT] public short getScalarShort ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getShort ( Index . scalarIndexImmutable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get java short array for a member of type short . [CODESPLIT] public short [ ] getJavaArrayShort ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( short [ ] ) data . getStorage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type long . [CODESPLIT] public long getScalarLong ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getLong ( Index . scalarIndexImmutable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get java long array for a member of type long . [CODESPLIT] public long [ ] getJavaArrayLong ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( long [ ] ) data . getStorage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type char . [CODESPLIT] public char getScalarChar ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getChar ( Index . scalarIndexImmutable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get java char array for a member of type char . [CODESPLIT] public char [ ] getJavaArrayChar ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( char [ ] ) data . getStorage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get String value from rank 0 String or rank 1 char member array . [CODESPLIT] public String getScalarString ( StructureMembers . Member m ) { if ( m . getDataType ( ) == DataType . STRING ) { Array data = getArray ( m ) ; if ( data == null ) data = getArray ( m ) ; return ( String ) data . getObject ( 0 ) ; } else { char [ ] ba = getJavaArrayChar ( m ) ; int count = 0 ; while ( count < ba . length ) { if ( 0 == ba [ count ] ) break ; count ++ ; } return new String ( ba , 0 , count ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type Structure . [CODESPLIT] public StructureData getScalarStructure ( StructureMembers . Member m ) { ArrayStructure data = ( ArrayStructure ) getArray ( m ) ; return data . getStructureData ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write all harvestable datasets to DIF records that have at least the minimum metadata . Call isDatasetUseable () to find out . [CODESPLIT] public void writeDatasetEntries ( InvCatalogImpl cat , String fileDir , StringBuilder mess ) { this . fileDir = fileDir ; this . messBuffer = mess ; File dir = new File ( fileDir ) ; if ( ! dir . exists ( ) ) { boolean ret = dir . mkdirs ( ) ; assert ret ; } CatalogCrawler . Listener listener = new CatalogCrawler . Listener ( ) { public void getDataset ( InvDataset ds , Object context ) { doOneDataset ( ds ) ; } public boolean getCatalogRef ( InvCatalogRef dd , Object context ) { return true ; } } ; ByteArrayOutputStream bis = new ByteArrayOutputStream ( ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( bis , CDM . utf8Charset ) ) ; CatalogCrawler crawler = new CatalogCrawler ( CatalogCrawler . USE_ALL , true , listener ) ; crawler . crawl ( cat , null , pw , null ) ; mess . append ( \"\\n*********************\\n\" ) ; mess . append ( new String ( bis . toByteArray ( ) , CDM . utf8Charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a DIF record for a specific dataset [CODESPLIT] public void doOneDataset ( InvDataset ds ) { if ( debug ) System . out . println ( \"doDataset \" + ds . getName ( ) ) ; if ( isDatasetUseable ( ds , messBuffer ) ) { String id = StringUtil2 . replace ( ds . getID ( ) , \"/\" , \"-\" ) ; String fileOutName = fileDir + \"/\" + id + \".dif.xml\" ; try { OutputStream out = new BufferedOutputStream ( new FileOutputStream ( fileOutName ) ) ; // writeOneEntry(ds, System.out, mess); writeOneEntry ( ds , out , messBuffer ) ; out . close ( ) ; messBuffer . append ( \" OK on Write\\n\" ) ; } catch ( IOException ioe ) { messBuffer . append ( \"DIFWriter failed on write \" + ioe . getMessage ( ) + \"\\n\" ) ; log . error ( \"DIFWriter failed on write \" + ioe . getMessage ( ) , ioe ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if a dataset is harvestable to a DIF record . [CODESPLIT] public boolean isDatasetUseable ( InvDataset ds , StringBuilder sbuff ) { boolean ok = true ; sbuff . append ( \"Dataset \" + ds . getName ( ) + \" id = \" + ds . getID ( ) + \": \" ) ; if ( ! ds . isHarvest ( ) ) { ok = false ; sbuff . append ( \"Dataset \" + ds . getName ( ) + \" id = \" + ds . getID ( ) + \" has harvest = false\\n\" ) ; } if ( ds . getName ( ) == null ) { ok = false ; sbuff . append ( \" missing Name field\\n\" ) ; } if ( ds . getUniqueID ( ) == null ) { ok = false ; sbuff . append ( \" missing ID field\\n\" ) ; } ThreddsMetadata . Variables vs = ds . getVariables ( \"DIF\" ) ; if ( ( vs == null ) || ( vs . getVariableList ( ) . size ( ) == 0 ) ) vs = ds . getVariables ( \"GRIB-1\" ) ; if ( ( vs == null ) || ( vs . getVariableList ( ) . size ( ) == 0 ) ) vs = ds . getVariables ( \"GRIB-2\" ) ; if ( ( vs == null ) || ( vs . getVariableList ( ) . size ( ) == 0 ) ) { ok = false ; sbuff . append ( \" missing Variables with DIF or GRIB compatible vocabulary\\n\" ) ; } List list = ds . getPublishers ( ) ; if ( ( list == null ) || ( list . size ( ) == 0 ) ) { ok = false ; sbuff . append ( \" must have publisher element that defines the data center\\n\" ) ; } String summary = ds . getDocumentation ( \"summary\" ) ; if ( summary == null ) { ok = false ; sbuff . append ( \" must have documentation element of type summary\\n\" ) ; } sbuff . append ( \" useable= \" + ok + \"\\n\" ) ; return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility routine to keep list of objects small . add fldValue to the fldName list in flds . fldValue may be a list or an object . if no list just keep the object without creating a list ( common case ) . otherwise add it to the existing list . [CODESPLIT] public static void addToList ( Map < String , Object > flds , String fldName , Object fldValue ) { if ( fldValue == null ) return ; Object prevVal = flds . get ( fldName ) ; if ( prevVal == null ) { flds . put ( fldName , fldValue ) ; return ; } List prevList ; if ( prevVal instanceof List ) { prevList = ( List ) prevVal ; } else { prevList = new ArrayList ( 5 ) ; prevList . add ( prevVal ) ; flds . put ( fldName , prevList ) ; } if ( fldValue instanceof List ) { prevList . addAll ( ( List ) fldValue ) ; } else { prevList . add ( fldValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make an immutable copy without changin DatasetBuilder [CODESPLIT] public Dataset copyDataset ( DatasetNode parent ) { return new Dataset ( parent , name , flds , accessBuilders , datasetBuilders ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transfer all metadata optionally also inheritable metadata from parents [CODESPLIT] public void transferMetadata ( DatasetNode from , boolean parentsAlso ) { if ( parentsAlso ) { ThreddsMetadata inherit = getInheritableMetadata ( ) ; // make sure exists inheritMetadata ( from , inherit . getFlds ( ) ) ; } // local metadata for ( Map . Entry < String , Object > entry : from . getFldIterator ( ) ) { if ( parentsAlso && entry . getKey ( ) . equals ( Dataset . ThreddsMetadataInheritable ) ) continue ; // already did this if ( Dataset . listFlds . contains ( entry . getKey ( ) ) ) addToNewList ( flds , entry . getKey ( ) , entry . getValue ( ) ) ; else flds . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } // tmi must be mutable, transfer if not ThreddsMetadata tmiOld = ( ThreddsMetadata ) get ( Dataset . ThreddsMetadataInheritable ) ; if ( tmiOld != null && tmiOld . isImmutable ( ) ) { ThreddsMetadata tmiNew = new ThreddsMetadata ( tmiOld ) ; flds . put ( Dataset . ThreddsMetadataInheritable , tmiNew ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "place directly into flds ( not in this . tmi ) LOOK why not into tmi ?? LOOK put into tmi see what breaks! [CODESPLIT] public void transferInheritedMetadata ( DatasetNode from ) { ThreddsMetadata tmi = getInheritableMetadata ( ) ; inheritMetadata ( from , tmi . getFlds ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the inheritable ThreddsMetadata object . If doesnt exist create new empty one [CODESPLIT] public ThreddsMetadata getInheritableMetadata ( ) { ThreddsMetadata tmi = ( ThreddsMetadata ) get ( Dataset . ThreddsMetadataInheritable ) ; if ( tmi == null ) { tmi = new ThreddsMetadata ( ) ; put ( Dataset . ThreddsMetadataInheritable , tmi ) ; } return tmi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add in a new product [CODESPLIT] void addProduct ( GridRecord record ) { records . add ( record ) ; if ( firstRecord == null ) { firstRecord = record ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * is this a time interval variable [CODESPLIT] protected void addExtraAttributes ( GridParameter param , Variable v ) { int icf = hcs . getGds ( ) . getInt ( GridDefRecord . VECTOR_COMPONENT_FLAG ) ; String flag = GridCF . VectorComponentFlag . of ( icf ) ; v . addAttribute ( new Attribute ( GridDefRecord . VECTOR_COMPONENT_FLAG , flag ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the netcdf variable . If vname is not already set use useName as name [CODESPLIT] Variable makeVariable ( NetcdfFile ncfile , Group g , String useName , RandomAccessFile raf ) { assert records . size ( ) > 0 : \"no records for this variable\" ; this . nlevels = getVertNlevels ( ) ; this . ntimes = tcs . getNTimes ( ) ; if ( vname == null ) { useName = StringUtil2 . replace ( useName , ' ' , \"_\" ) ; this . vname = useName ; } Variable v = new Variable ( ncfile , g , null , vname ) ; v . setDataType ( DataType . FLOAT ) ; Formatter dims = new Formatter ( ) ; if ( hasEnsemble ( ) ) { dims . format ( \"ens \" ) ; } dims . format ( \"%s \" , tcs . getName ( ) ) ; if ( getVertIsUsed ( ) ) { dims . format ( \"%s \" , getVertName ( ) ) ; hasVert = true ; } if ( hcs . isLatLon ( ) ) { dims . format ( \"lat lon\" ) ; } else { dims . format ( \"y x\" ) ; } v . setDimensions ( dims . toString ( ) ) ; // add attributes GridParameter param = lookup . getParameter ( firstRecord ) ; if ( param == null ) return null ; String unit = param . getUnit ( ) ; if ( unit == null ) unit = \"\" ; v . addAttribute ( new Attribute ( \"units\" , unit ) ) ; v . addAttribute ( new Attribute ( \"long_name\" , makeLongName ( ) ) ) ; v . addAttribute ( new Attribute ( \"missing_value\" , lookup . getFirstMissingValue ( ) ) ) ; if ( ! hcs . isLatLon ( ) ) { if ( GridServiceProvider . addLatLon ) v . addAttribute ( new Attribute ( \"coordinates\" , \"lat lon\" ) ) ; v . addAttribute ( new Attribute ( \"grid_mapping\" , hcs . getGridName ( ) ) ) ; } addExtraAttributes ( param , v ) ; v . setSPobject ( this ) ; int nrecs = ntimes * nlevels ; if ( hasEnsemble ( ) ) nrecs *= ecs . getNEnsembles ( ) ; recordTracker = new GridRecord [ nrecs ] ; if ( log . isDebugEnabled ( ) ) log . debug ( \"Record Assignment for Variable \" + getName ( ) ) ; boolean oneSent = false ; for ( GridRecord p : records ) { int level = getVertIndex ( p ) ; if ( ! getVertIsUsed ( ) && ( level > 0 ) ) { log . warn ( \"inconsistent level encoding=\" + level ) ; level = 0 ; // inconsistent level encoding ?? } int time = tcs . findIndex ( p ) ; // System.out.println(\"time=\"+time+\" level=\"+level); if ( level < 0 ) { log . warn ( \"LEVEL NOT FOUND record; level=\" + level + \" time= \" + time + \" for \" + getName ( ) + \" file=\" + ncfile . getLocation ( ) + \"\\n\" + \"   \" + getVertLevelName ( ) + \" (type=\" + p . getLevelType1 ( ) + \",\" + p . getLevelType2 ( ) + \")  value=\" + p . getLevel1 ( ) + \",\" + p . getLevel2 ( ) + \"\\n\" ) ; getVertIndex ( p ) ; // allow breakpoint continue ; } if ( time < 0 ) { log . warn ( \"TIME NOT FOUND record; level=\" + level + \" time= \" + time + \" for \" + getName ( ) + \" file=\" + ncfile . getLocation ( ) + \"\\n\" + \" validTime= \" + p . getValidTime ( ) + \"\\n\" ) ; tcs . findIndex ( p ) ; // allow breakpoint continue ; } oneSent = trackRecords ( time , level , p , raf , oneSent ) ; } // let all references to Index go, to reduce retained size LOOK records . clear ( ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging [CODESPLIT] public void showRecord ( int recnum , Formatter f ) { if ( ( recnum < 0 ) || ( recnum > recordTracker . length - 1 ) ) { f . format ( \"%d out of range [0,%d]%n\" , recnum , recordTracker . length - 1 ) ; return ; } GridRecord gr = recordTracker [ recnum ] ; if ( hasEnsemble ( ) ) { // recnum = ens * (ntimes * nlevels) + (time * nlevels) + level int ens = recnum / ( nlevels * ntimes ) ; int tmp = recnum - ens * ( nlevels * ntimes ) ; int time = tmp / nlevels ; int level = tmp % nlevels ; f . format ( \"recnum=%d (record hash=%d) ens=%d time=%s(%d) level=%f(%d)%n\" , recnum , gr . hashCode ( ) , ens , tcs . getCoord ( time ) , time , vc . getCoord ( level ) , level ) ; } else { int time = recnum / nlevels ; int level = recnum % nlevels ; f . format ( \"recnum=%d (record hash=%d) time=%s(%d) level=%f(%d)%n\" , recnum , gr . hashCode ( ) , tcs . getCoord ( time ) , time , vc . getCoord ( level ) , level ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump out the missing data [CODESPLIT] public void showMissing ( Formatter f ) { //System.out.println(\"  \" +name+\" ntimes (across)= \"+ ntimes+\" nlevs (down)= \"+ nlevels+\":\"); int count = 0 , total = 0 ; f . format ( \"  %s%n\" , name ) ; for ( int j = 0 ; j < nlevels ; j ++ ) { f . format ( \"   \" ) ; for ( int i = 0 ; i < ntimes ; i ++ ) { boolean missing = recordTracker [ i * nlevels + j ] == null ; f . format ( \"%s\" , missing ? \"-\" : \"X\" ) ; if ( missing ) count ++ ; total ++ ; } f . format ( \"%n\" ) ; } f . format ( \"  MISSING= %d / %d for %s%n\" , count , total , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump out the missing data as a summary [CODESPLIT] public int showMissingSummary ( Formatter f ) { int count = 0 ; int total = recordTracker . length ; for ( int i = 0 ; i < total ; i ++ ) { if ( recordTracker [ i ] == null ) count ++ ; } f . format ( \"  MISSING= %d / %d for %s%n\" , count , total , name ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the grid record for the time and level indices Canonical ordering is ens time level [CODESPLIT] public GridRecord findRecord ( int ens , int time , int level ) { if ( hasEnsemble ( ) ) { return recordTracker [ ens * ( ntimes * nlevels ) + ( time * nlevels ) + level ] ; } else { return recordTracker [ time * nlevels + level ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump this variable [CODESPLIT] public String dump ( ) { DateFormatter formatter = new DateFormatter ( ) ; Formatter sbuff = new Formatter ( ) ; sbuff . format ( \"%s %d %n\" , name , records . size ( ) ) ; for ( GridRecord record : records ) { sbuff . format ( \" level = %d %f\" , record . getLevelType1 ( ) , record . getLevel1 ( ) ) ; if ( null != record . getValidTime ( ) ) sbuff . format ( \" time = %s\" , formatter . toDateTimeString ( record . getValidTime ( ) ) ) ; sbuff . format ( \"%n\" ) ; } return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a long name for the variable [CODESPLIT] protected String makeLongName ( ) { Formatter f = new Formatter ( ) ; GridParameter param = lookup . getParameter ( firstRecord ) ; if ( param == null ) return null ; f . format ( \"%s\" , param . getDescription ( ) ) ; String levelName = makeLevelName ( firstRecord , lookup ) ; if ( levelName . length ( ) != 0 ) f . format ( \" @ %s\" , levelName ) ; return f . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a TypedDatasetFactoryIF . [CODESPLIT] static public void registerFactory ( FeatureType datatype , String className ) throws ClassNotFoundException { Class c = Class . forName ( className ) ; registerFactory ( datatype , c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a class that implements a TypedDatasetFactoryIF . [CODESPLIT] static public void registerFactory ( FeatureType datatype , Class c ) { if ( ! ( TypedDatasetFactoryIF . class . isAssignableFrom ( c ) ) ) throw new IllegalArgumentException ( \"Class \" + c . getName ( ) + \" must implement TypedDatasetFactoryIF\" ) ; // fail fast - check newInstance works Object instance ; try { instance = c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( \"CoordTransBuilderIF Class \" + c . getName ( ) + \" cannot instantiate, probably need default Constructor\" ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( \"CoordTransBuilderIF Class \" + c . getName ( ) + \" is not accessible\" ) ; } // user stuff gets put at top if ( userMode ) transformList . add ( 0 , new Factory ( datatype , c , ( TypedDatasetFactoryIF ) instance ) ) ; else transformList . add ( new Factory ( datatype , c , ( TypedDatasetFactoryIF ) instance ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a dataset as a TypedDataset . [CODESPLIT] static public TypedDataset open ( FeatureType datatype , String location , ucar . nc2 . util . CancelTask task , StringBuilder errlog ) throws IOException { DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; NetcdfDataset ncd = NetcdfDataset . acquireDataset ( durl , true , task ) ; return open ( datatype , ncd , task , errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a dataset as a TypedDataset . [CODESPLIT] static public TypedDataset open ( FeatureType datatype , NetcdfDataset ncd , ucar . nc2 . util . CancelTask task , StringBuilder errlog ) throws IOException { // look for a Factory that claims this dataset Class useClass = null ; for ( Factory fac : transformList ) { if ( ( datatype != null ) && ( datatype != fac . datatype ) ) continue ; if ( fac . instance . isMine ( ncd ) ) { useClass = fac . c ; break ; } } // Factory not found if ( null == useClass ) { // POINT is also a STATION if ( datatype == FeatureType . POINT ) { return open ( FeatureType . STATION , ncd , task , errlog ) ; } // if explicitly requested, give em a GridDataset even if no Grids if ( datatype == FeatureType . GRID ) { return null ; // new ucar.nc2.dt.grid.GridDataset( ncd);   LOOK have to copy old  GridDataset to archive } if ( null == datatype ) { // if no datatype was requested, give em a GridDataset only if some Grids are found. ucar . nc2 . dt . grid . GridDataset gds = new ucar . nc2 . dt . grid . GridDataset ( ncd ) ; if ( gds . getGrids ( ) . size ( ) > 0 ) return null ; // gds;    LOOK have to copy old  GridDataset to archive } errlog . append ( \"**Failed to find Datatype Factory for= \" ) . append ( ncd . getLocation ( ) ) . append ( \" datatype= \" ) . append ( datatype ) . append ( \"\\n\" ) ; return null ; } // get a new instance of the Factory class, for thread safety TypedDatasetFactoryIF builder = null ; try { builder = ( TypedDatasetFactoryIF ) useClass . newInstance ( ) ; } catch ( InstantiationException e ) { errlog . append ( e . getMessage ( ) ) . append ( \"\\n\" ) ; } catch ( IllegalAccessException e ) { errlog . append ( e . getMessage ( ) ) . append ( \"\\n\" ) ; } if ( null == builder ) { errlog . append ( \"**Error on TypedDatasetFactory object from class= \" ) . append ( useClass . getName ( ) ) . append ( \"\\n\" ) ; return null ; } return builder . open ( ncd , task , errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : defaultPointMetadata [CODESPLIT] public static TVPDefaultMetadataPropertyType initDefaultPointMetadata ( TVPDefaultMetadataPropertyType defaultPointMetadata , VariableSimpleIF dataVar ) { // wml2:DefaultTVPMeasurementMetadata DefaultTVPMeasurementMetadataDocument defaultTVPMeasurementMetadataDoc = DefaultTVPMeasurementMetadataDocument . Factory . newInstance ( ) ; NcTVPMeasurementMetadataType . initDefaultTVPMeasurementMetadata ( defaultTVPMeasurementMetadataDoc . addNewDefaultTVPMeasurementMetadata ( ) , dataVar ) ; defaultPointMetadata . set ( defaultTVPMeasurementMetadataDoc ) ; return defaultPointMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException { // throw away first three bytes (padding)\r byte unused ; for ( int i = 0 ; i < 3 ; i ++ ) { unused = source . readByte ( ) ; } // read fourth byte\r val = source . readByte ( ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { // print three null bytes (padding)\r for ( int i = 0 ; i < 3 ; i ++ ) { sink . writeByte ( 0 ) ; } sink . writeByte ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Spacing [CODESPLIT] public boolean isAscending ( ) { loadValuesIfNeeded ( ) ; switch ( spacing ) { case regularInterval : case regularPoint : return getResolution ( ) > 0 ; case irregularPoint : return values [ 0 ] <= values [ ncoords - 1 ] ; case contiguousInterval : return values [ 0 ] <= values [ ncoords ] ; case discontiguousInterval : return values [ 0 ] <= values [ 2 * ncoords - 1 ] ; } throw new IllegalStateException ( \"unknown spacing\" + spacing ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CalendarDate double [ 2 ] or Double [CODESPLIT] public Object getCoordObject ( int index ) { if ( axisType == AxisType . RunTime ) return makeDate ( getCoordMidpoint ( index ) ) ; if ( isInterval ( ) ) return new double [ ] { getCoordEdge1 ( index ) , getCoordEdge2 ( index ) } ; return getCoordMidpoint ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only for longitude only for regular ( do we need a subclass for longitude 1D coords ?? [CODESPLIT] public Optional < CoverageCoordAxis > subsetByIntervals ( List < MAMath . MinMax > lonIntvs , int stride ) { if ( axisType != AxisType . Lon ) return Optional . empty ( \"subsetByIntervals only for longitude\" ) ; if ( ! isRegular ( ) ) return Optional . empty ( \"subsetByIntervals only for regular longitude\" ) ; CoordAxisHelper helper = new CoordAxisHelper ( this ) ; double start = Double . NaN ; boolean first = true ; List < RangeIterator > ranges = new ArrayList <> ( ) ; for ( MAMath . MinMax lonIntv : lonIntvs ) { if ( first ) start = lonIntv . min ; first = false ; Optional < RangeIterator > opt = helper . makeRange ( lonIntv . min , lonIntv . max , stride ) ; if ( ! opt . isPresent ( ) ) return Optional . empty ( opt . getErrorMessage ( ) ) ; ranges . add ( opt . get ( ) ) ; } try { RangeComposite compositeRange = new RangeComposite ( AxisType . Lon . toString ( ) , ranges ) ; int npts = compositeRange . length ( ) ; double end = start + npts * resolution ; CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder ( this ) ; // copy builder . subset ( npts , start , end , resolution , null ) ; builder . setRange ( null ) ; builder . setCompositeRange ( compositeRange ) ; return Optional . of ( new CoverageCoordAxis1D ( builder ) ) ; } catch ( InvalidRangeException e ) { return Optional . empty ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK incomplete handling of subsetting params [CODESPLIT] protected Optional < CoverageCoordAxisBuilder > subsetBuilder ( SubsetParams params ) { if ( params == null ) return Optional . of ( new CoverageCoordAxisBuilder ( this ) ) ; CoordAxisHelper helper = new CoordAxisHelper ( this ) ; switch ( getAxisType ( ) ) { case GeoZ : case Pressure : case Height : Double dval = params . getVertCoord ( ) ; if ( dval != null ) return Optional . of ( helper . subsetClosest ( dval ) ) ; // use midpoint of interval LOOK may not always be unique double [ ] intv = params . getVertCoordIntv ( ) ; if ( intv != null ) return Optional . of ( helper . subsetClosest ( ( intv [ 0 ] + intv [ 1 ] ) / 2 ) ) ; double [ ] vertRange = params . getVertRange ( ) ; // used by WCS if ( vertRange != null ) return helper . subset ( vertRange [ 0 ] , vertRange [ 1 ] , 1 ) ; // default is all break ; case Ensemble : Double eval = params . getDouble ( SubsetParams . ensCoord ) ; if ( eval != null ) { return Optional . of ( helper . subsetClosest ( eval ) ) ; } // default is all break ; // x,y get seperately subsetted case GeoX : case GeoY : case Lat : case Lon : throw new IllegalArgumentException ( ) ; // return null; // LOOK heres a case where null is \"correct\" case Time : if ( params . isTrue ( SubsetParams . timePresent ) ) return Optional . of ( helper . subsetLatest ( ) ) ; CalendarDate date = ( CalendarDate ) params . get ( SubsetParams . time ) ; if ( date != null ) return Optional . of ( helper . subsetClosest ( date ) ) ; Integer stride = ( Integer ) params . get ( SubsetParams . timeStride ) ; if ( stride == null || stride < 0 ) stride = 1 ; CalendarDateRange dateRange = ( CalendarDateRange ) params . get ( SubsetParams . timeRange ) ; if ( dateRange != null ) return helper . subset ( dateRange , stride ) ; // If no time range or time point, a timeOffset can be used to specify the time point. /* CalendarDate timeOffsetDate = params.getTimeOffsetDate();\n        if (timeOffsetDate != null) {\n          return Optional.of(helper.subsetClosest(timeOffsetDate));\n        } */ // A time offset or time offset interval starts from the rundate of the offset Double timeOffset = params . getTimeOffset ( ) ; CalendarDate runtime = params . getRunTime ( ) ; if ( timeOffset != null ) { if ( runtime != null ) { date = makeDateInTimeUnits ( runtime , timeOffset ) ; return Optional . of ( helper . subsetClosest ( date ) ) ; } else { return Optional . of ( helper . subsetClosest ( timeOffset ) ) ; } } // If a time interval is sent, search for match. double [ ] timeOffsetIntv = params . getTimeOffsetIntv ( ) ; if ( timeOffsetIntv != null && runtime != null ) { // double midOffset = (timeOffsetIntv[0] + timeOffsetIntv[1]) / 2; CalendarDate [ ] dateIntv = new CalendarDate [ 2 ] ; dateIntv [ 0 ] = makeDateInTimeUnits ( runtime , timeOffsetIntv [ 0 ] ) ; dateIntv [ 1 ] = makeDateInTimeUnits ( runtime , timeOffsetIntv [ 1 ] ) ; return Optional . of ( helper . subsetClosest ( dateIntv ) ) ; } if ( stride != 1 ) try { return Optional . of ( helper . subsetByIndex ( getRange ( ) . setStride ( stride ) ) ) ; } catch ( InvalidRangeException e ) { return Optional . empty ( e . getMessage ( ) ) ; } // default is all break ; case RunTime : CalendarDate rundate = ( CalendarDate ) params . get ( SubsetParams . runtime ) ; if ( rundate != null ) return Optional . of ( helper . subsetClosest ( rundate ) ) ; /*        CalendarDateRange rundateRange = (CalendarDateRange) params.get(SubsetParams.runtimeRange);\n        if (rundateRange != null)\n          return helper.subset(rundateRange, 1); */ if ( params . isTrue ( SubsetParams . runtimeAll ) ) break ; // default is latest return Optional . of ( helper . subsetLatest ( ) ) ; case TimeOffset : Double oval = params . getDouble ( SubsetParams . timeOffset ) ; if ( oval != null ) { return Optional . of ( helper . subsetClosest ( oval ) ) ; } // If a time interval is sent, search for match. timeOffsetIntv = params . getTimeOffsetIntv ( ) ; if ( timeOffsetIntv != null ) { return Optional . of ( helper . subsetClosest ( ( timeOffsetIntv [ 0 ] + timeOffsetIntv [ 1 ] ) / 2 ) ) ; } if ( params . isTrue ( SubsetParams . timeOffsetFirst ) ) { try { return Optional . of ( helper . subsetByIndex ( new Range ( 1 ) ) ) ; } catch ( InvalidRangeException e ) { return Optional . empty ( e . getMessage ( ) ) ; } } // default is all break ; } // otherwise return copy the original axis return Optional . of ( new CoverageCoordAxisBuilder ( this ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { for ( int i = 0 ; i < vals . length ; i ++ ) { vals [ i ] = source . readInt ( ) ; if ( statusUI != null ) { statusUI . incrementByteCount ( 4 ) ; if ( statusUI . userCancelled ( ) ) throw new DataReadException ( \"User cancelled\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { for ( int i = 0 ; i < vals . length ; i ++ ) { sink . writeInt ( vals [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Figure out what kind of netcdf - related file we have . Constraint : leave raf read pointer to point just after the magic number . [CODESPLIT] static public int checkFileType ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { int format = 0 ; byte [ ] magic = new byte [ MAGIC_NUMBER_LEN ] ; // If this is not an HDF5 file, then the magic number is at // position 0; If it is an HDF5 file, then we need to search // forward for it. // Look for the relevant leading tag raf . seek ( 0 ) ; if ( raf . readBytes ( magic , 0 , MAGIC_NUMBER_LEN ) < MAGIC_NUMBER_LEN ) return 0 ; // unknown // Some version of CDF int hdrlen = 0 ; hdrlen = CDF1HEAD . length ; // all CDF headers are assumed to be same length format = 0 ; if ( memequal ( CDF1HEAD , magic , CDF1HEAD . length ) ) format = NC_FORMAT_CLASSIC ; else if ( memequal ( CDF2HEAD , magic , CDF2HEAD . length ) ) format = NC_FORMAT_64BIT_OFFSET ; else if ( memequal ( CDF5HEAD , magic , CDF5HEAD . length ) ) format = NC_FORMAT_CDF5 ; else if ( memequal ( H4HEAD , magic , H4HEAD . length ) ) format = NC_FORMAT_HDF4 ; if ( format != 0 ) { raf . seek ( hdrlen ) ; return format ; } // For HDF5, we need to search forward format = 0 ; long filePos = 0 ; long size = raf . length ( ) ; while ( ( filePos < size - 8 ) && ( filePos < MAXHEADERPOS ) ) { boolean match ; raf . seek ( filePos ) ; if ( raf . readBytes ( magic , 0 , MAGIC_NUMBER_LEN ) < MAGIC_NUMBER_LEN ) return 0 ; // unknown // Test for HDF5 if ( memequal ( H5HEAD , magic , H5HEAD . length ) ) { format = NC_FORMAT_HDF5 ; break ; } filePos = ( filePos == 0 ) ? 512 : 2 * filePos ; } if ( format != 0 ) raf . seek ( filePos + H5HEAD . length ) ; return format ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Not quite memcmp [CODESPLIT] static boolean memequal ( byte [ ] b1 , byte [ ] b2 , int len ) { if ( b1 == b2 ) return true ; if ( b1 == null || b2 == null ) return false ; if ( b1 . length < len || b2 . length < len ) return false ; for ( int i = 0 ; i < len ; i ++ ) { if ( b1 [ i ] != b2 [ i ] ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( _Debug ) { System . out . println ( \"asciiArray.toASCII(\" + addName + \",'\" + rootName + \"')  getName(): \" + getEncodedName ( ) ) ; System . out . println ( \"  PrimitiveVector size = \" + getPrimitiveVector ( ) . getLength ( ) ) ; } if ( addName ) pw . print ( \"\\n\" ) ; int dims = numDimensions ( ) ; int shape [ ] = new int [ dims ] ; int i = 0 ; for ( Enumeration e = getDimensions ( ) ; e . hasMoreElements ( ) ; ) { DArrayDimension d = ( DArrayDimension ) e . nextElement ( ) ; shape [ i ++ ] = d . getSize ( ) ; } if ( newLine ) pw . print ( \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print an array . This is a private member function . [CODESPLIT] private int asciiArray ( PrintWriter os , boolean addName , String label , int index , int dims , int shape [ ] , int offset ) { //os.println(\"\\n\\n\");\r //os.println(\"\\tdims:   \" + dims);\r //os.println(\"\\toffset: \" + offset);\r //os.println(\"\\tshape[\"+offset+\"]: \" + shape[offset]);\r //os.println(\"\\tindex: \" + index);\r //os.println(\"\\n\");\r if ( dims == 1 ) { if ( addName ) os . print ( label ) ; for ( int i = 0 ; i < shape [ offset ] ; i ++ ) { PrimitiveVector pv = getPrimitiveVector ( ) ; if ( pv instanceof BaseTypePrimitiveVector ) { BaseType bt = ( ( BaseTypePrimitiveVector ) pv ) . getValue ( index ++ ) ; if ( i > 0 ) { if ( bt instanceof DString ) os . print ( \", \" ) ; else os . println ( \"\" ) ; } ( ( toASCII ) bt ) . toASCII ( os , false , null , false ) ; } else { if ( i > 0 ) os . print ( \", \" ) ; pv . printSingleVal ( os , index ++ ) ; } } if ( addName ) os . print ( \"\\n\" ) ; return index ; } else { for ( int i = 0 ; i < shape [ offset ] ; i ++ ) { StringBuilder s = new StringBuilder ( ) ; s . append ( label ) ; s . append ( \"[\" ) ; s . append ( i ) ; s . append ( \"]\" ) ; if ( ( dims - 1 ) == 1 ) s . append ( \", \" ) ; index = asciiArray ( os , addName , s . toString ( ) , index , dims - 1 , shape , offset + 1 ) ; } return index ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DSP Extensions [CODESPLIT] @ Override public void setContext ( DapContext context ) { this . context = context ; // Extract some things from the context Object o = this . context . get ( Dap4Util . DAP4ENDIANTAG ) ; if ( o != null ) setOrder ( ( ByteOrder ) o ) ; o = this . context . get ( Dap4Util . DAP4CSUMTAG ) ; if ( o != null ) setChecksumMode ( ChecksumMode . modeFor ( o . toString ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It is common to want to parse a DMR text to a DapDataset so provide this utility . [CODESPLIT] protected DapDataset parseDMR ( String document ) throws DapException { // Parse the dmr Dap4Parser parser ; //if(USEDOM) parser = new DOM4Parser ( null ) ; //else //    parser = new DOM4Parser(new DefaultDMRFactory()); if ( PARSEDEBUG ) parser . setDebugLevel ( 1 ) ; try { if ( ! parser . parse ( document ) ) throw new DapException ( \"DMR Parse failed\" ) ; } catch ( SAXException se ) { throw new DapException ( se ) ; } if ( parser . getErrorResponse ( ) != null ) throw new DapException ( \"Error Response Document not supported\" ) ; DapDataset result = parser . getDMR ( ) ; processAttributes ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walk the dataset tree and remove selected attributes such as _Unsigned [CODESPLIT] protected void processAttributes ( DapDataset dataset ) throws DapException { List < DapNode > nodes = dataset . getNodeList ( ) ; for ( DapNode node : nodes ) { switch ( node . getSort ( ) ) { case GROUP : case DATASET : case VARIABLE : Map < String , DapAttribute > attrs = node . getAttributes ( ) ; if ( attrs . size ( ) > 0 ) { List < DapAttribute > suppressed = new ArrayList <> ( ) ; for ( DapAttribute dattr : attrs . values ( ) ) { if ( suppress ( dattr . getShortName ( ) ) ) suppressed . add ( dattr ) ; } for ( DapAttribute dattr : suppressed ) { node . removeAttribute ( dattr ) ; } } break ; default : break ; /*ignore*/ } } // Try to extract the byte order getEndianAttribute ( dataset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some attributes that are added by the NetcdfDataset need to be kept out of the DMR . This function defines that set . [CODESPLIT] protected boolean suppress ( String attrname ) { if ( attrname . startsWith ( \"_Coord\" ) ) return true ; if ( attrname . equals ( \"_Unsigned\" ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given date string ( starting at the first numeric character ) using the given date format string ( as described in java . text . SimpleDateFormat ) and return a Date . [CODESPLIT] public static Date getDateUsingSimpleDateFormat ( String dateString , String dateFormatString ) { // Determine first numeric character in dateString and drop proceeding characters. int smallestIndex = dateString . length ( ) ; if ( smallestIndex == 0 ) return null ; for ( int i = 0 ; i < 10 ; i ++ ) { int curIndex = dateString . indexOf ( String . valueOf ( i ) ) ; if ( curIndex != - 1 && smallestIndex > curIndex ) smallestIndex = curIndex ; } return getDateUsingCompleteDateFormatWithOffset ( dateString , dateFormatString , smallestIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given date string starting at a position given by the offset of the demark character in the dateFormatString . The rest of the dateFormatString is the date format string ( as described in java . text . SimpleDateFormat ) . <pre > Example : dateString = wrfout_d01_2006 - 07 - 06_080000 . nc dateFormatString = wrfout_d01_#yyyy - MM - dd_HHmm < / pre > This simply counts over wrfout_d01_ number of chars in dateString then applies the remaining dateFormatString . [CODESPLIT] public static Date getDateUsingDemarkatedCount ( String dateString , String dateFormatString , char demark ) { // the position of the demark char is where to start parsing the dateString int pos1 = dateFormatString . indexOf ( demark ) ; // the rest of the dateFormatString is the SimpleDateFormat dateFormatString = dateFormatString . substring ( pos1 + 1 ) ; return getDateUsingCompleteDateFormatWithOffset ( dateString , dateFormatString , pos1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given date string ( between the demarcation characters ) using the given date format string ( as described in java . text . SimpleDateFormat ) and return a Date . <pre > Example : dateString = / data / anything / 2006070611 / wrfout_d01_2006 - 07 - 06_080000 . nc dateFormatString = #wrfout_d01_#yyyy - MM - dd_HHmm would extract the date 2006 - 07 - 06T08 : 00 [CODESPLIT] public static Date getDateUsingDemarkatedMatch ( String dateString , String dateFormatString , char demark ) { // extract the match string int pos1 = dateFormatString . indexOf ( demark ) ; int pos2 = dateFormatString . indexOf ( demark , pos1 + 1 ) ; if ( ( pos1 < 0 ) || ( pos2 < 0 ) ) { logger . error ( \"Must delineate Date between 2 '#' chars, dateFormatString = '\" + dateFormatString + \"'\" , new Throwable ( ) ) ; return null ; } String match = dateFormatString . substring ( pos1 + 1 , pos2 ) ; int pos3 = dateString . indexOf ( match ) ; if ( pos3 < 0 ) return null ; if ( pos1 > 0 ) { // pos1 > 0, date is before the match: \"yyyyMMddHH#/wrfout_d01_#\" dateFormatString = dateFormatString . substring ( 0 , pos1 ) ; dateString = dateString . substring ( pos3 - dateFormatString . length ( ) , pos3 ) ; } else { // pos1 == 0, date is after the match: \"#wrfout_d01_#yyyy-MM-dd_HHmm\" dateFormatString = dateFormatString . substring ( pos2 + 1 ) ; dateString = dateString . substring ( pos3 + match . length ( ) ) ; } // any leading or trailing \".\" in the dateFormatString means trim int posDot1 = 0 ; while ( dateFormatString . charAt ( posDot1 ) == ' ' ) posDot1 ++ ; int posDot2 = dateFormatString . length ( ) ; while ( dateFormatString . charAt ( posDot2 - 1 ) == ' ' ) posDot2 -- ; if ( posDot1 != 0 || posDot2 != dateFormatString . length ( ) ) { dateFormatString = dateFormatString . substring ( posDot1 , posDot2 ) ; dateString = dateString . substring ( posDot1 , posDot2 ) ; } return getDateUsingCompleteDateFormatWithOffset ( dateString , dateFormatString , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given date string ( starting at the given startIndex ) using the given date format string ( as described in java . text . SimpleDateFormat ) and return a Date . Assumes TimeZone is GMT . [CODESPLIT] public static Date getDateUsingCompleteDateFormatWithOffset ( String dateString , String dateFormatString , int startIndex ) { try { SimpleDateFormat dateFormat = new SimpleDateFormat ( dateFormatString , Locale . US ) ; dateFormat . setTimeZone ( TimeZone . getTimeZone ( \"GMT\" ) ) ; // We have to cut off the dateString, so that it doesnt grab extra characters. // eg  new SimpleDateFormat(\"yyyyMMdd_HH\").parse(\"20061129_06\") -> 2006-12-24T00:00:00Z (WRONG!) String s ; if ( startIndex + dateFormatString . length ( ) <= dateString . length ( ) ) s = dateString . substring ( startIndex , startIndex + dateFormatString . length ( ) ) ; else s = dateString ; Date result = dateFormat . parse ( s ) ; if ( result == null ) throw new RuntimeException ( \"SimpleDateFormat bad =\" + dateFormatString + \" working on =\" + s ) ; return result ; } catch ( ParseException e ) { throw new RuntimeException ( \"SimpleDateFormat = \" + dateFormatString + \" fails on \" + dateString + \" ParseException:\" + e . getMessage ( ) ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( \"SimpleDateFormat = \" + dateFormatString + \" fails on \" + dateString + \" IllegalArgumentException:\" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use regular expression capture group replacement to construct a date string and return the Date that is obtained by parseing the constructed date string using the date format string yyyy - MM - dd T HH : mm . [CODESPLIT] public static Date getDateUsingRegExp ( String dateString , String matchPattern , String substitutionPattern ) { String dateFormatString = \"yyyy-MM-dd'T'HH:mm\" ; return getDateUsingRegExpAndDateFormat ( dateString , matchPattern , substitutionPattern , dateFormatString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The same as getDateUsingRegExp () except the date format string to be used must be specified . [CODESPLIT] public static Date getDateUsingRegExpAndDateFormat ( String dateString , String matchPattern , String substitutionPattern , String dateFormatString ) { // Match the given date string against the regular expression. java . util . regex . Pattern pattern = java . util . regex . Pattern . compile ( matchPattern ) ; java . util . regex . Matcher matcher = pattern . matcher ( dateString ) ; if ( ! matcher . matches ( ) ) { return null ; } // Build date string to use with date format string by // substituting the capture groups into the substitution pattern. StringBuffer dateStringFormatted = new StringBuffer ( ) ; matcher . appendReplacement ( dateStringFormatted , substitutionPattern ) ; if ( dateStringFormatted . length ( ) == 0 ) { return null ; } return getDateUsingCompleteDateFormat ( dateStringFormatted . toString ( ) , dateFormatString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] @ Override public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl result ) { double fromLat = Math . toRadians ( latlon . getLatitude ( ) ) ; double theta = Math . toRadians ( latlon . getLongitude ( ) ) ; if ( projectionLongitude != 0 && ! Double . isNaN ( theta ) ) { theta = MapMath . normalizeLongitude ( theta - projectionLongitude ) ; } ProjectionPointImpl out = new ProjectionPointImpl ( ) ; project ( theta , fromLat , out ) ; result . setLocation ( totalScale * out . getX ( ) + falseEasting , totalScale * out . getY ( ) + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] @ Override public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double fromX = ( world . getX ( ) - falseEasting ) / totalScale ; // assumes cartesian coords in km\r double fromY = ( world . getY ( ) - falseNorthing ) / totalScale ; ProjectionPointImpl pp = new ProjectionPointImpl ( ) ; projectInverse ( fromX , fromY , pp ) ; if ( pp . getX ( ) < - Math . PI ) { pp . setX ( - Math . PI ) ; } else if ( pp . getX ( ) > Math . PI ) { pp . setX ( Math . PI ) ; } if ( projectionLongitude != 0 && ! Double . isNaN ( pp . getX ( ) ) ) { pp . setX ( MapMath . normalizeLongitude ( pp . getX ( ) + projectionLongitude ) ) ; } result . setLatitude ( Math . toDegrees ( pp . getY ( ) ) ) ; result . setLongitude ( Math . toDegrees ( pp . getX ( ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only one message per CoordinatePartitionUnionizer instance [CODESPLIT] public void addCoords ( List < Coordinate > coords , PartitionCollectionMutable . Partition part ) { Coordinate runtime = null ; for ( Coordinate coord : coords ) { switch ( coord . getType ( ) ) { case runtime : CoordinateRuntime rtime = ( CoordinateRuntime ) coord ; if ( runtimeBuilder == null ) runtimeBuilder = new CoordinateRuntime . Builder2 ( rtime . getTimeUnits ( ) ) ; runtimeBuilder . addAll ( coord ) ; runtime = coord ; if ( debugPartitionErrors && ! duplicateRuntimeMessage && part != null ) testDuplicateRuntime ( rtime , part ) ; break ; case time : CoordinateTime time = ( CoordinateTime ) coord ; if ( timeBuilder == null ) timeBuilder = new CoordinateTime . Builder2 ( coord . getCode ( ) , time . getTimeUnit ( ) , time . getRefDate ( ) ) ; timeBuilder . addAll ( coord ) ; break ; case timeIntv : CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) coord ; if ( timeIntvBuilder == null ) timeIntvBuilder = new CoordinateTimeIntv . Builder2 ( null , coord . getCode ( ) , timeIntv . getTimeUnit ( ) , timeIntv . getRefDate ( ) ) ; timeIntvBuilder . addAll ( intervalFilter ( ( CoordinateTimeIntv ) coord ) ) ; break ; case time2D : CoordinateTime2D time2D = ( CoordinateTime2D ) coord ; if ( time2DBuilder == null ) time2DBuilder = new CoordinateTime2DUnionizer ( time2D . isTimeInterval ( ) , time2D . getTimeUnit ( ) , coord . getCode ( ) , false , logger ) ; time2DBuilder . addAll ( time2D ) ; // debug CoordinateRuntime runtimeFrom2D = time2D . getRuntimeCoordinate ( ) ; if ( ! runtimeFrom2D . equals ( runtime ) ) logger . warn ( \"HEY CoordinateUnionizer runtimes not equal\" ) ; break ; case ens : if ( ensBuilder == null ) ensBuilder = new CoordinateEns . Builder2 ( coord . getCode ( ) ) ; ensBuilder . addAll ( coord ) ; break ; case vert : CoordinateVert vertCoord = ( CoordinateVert ) coord ; if ( vertBuilder == null ) vertBuilder = new CoordinateVert . Builder2 ( coord . getCode ( ) , vertCoord . getVertUnit ( ) ) ; vertBuilder . addAll ( coord ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a <Value > ... < / Value > into its component strings . Generally type checking is not performed . String quotes are obeyed and backslash escapes are removed . [CODESPLIT] static public List < String > collectValues ( String text ) throws ParseException { List < String > values = new ArrayList < String > ( ) ; StringBuffer buf = new StringBuffer ( ) ; text = text . trim ( ) + ' ' ; int i = 0 ; for ( ; ; ) { char c = text . charAt ( i ++ ) ; if ( c == ' ' ) break ; // eos if ( c <= ' ' || c == 127 ) // whitespace continue ; if ( c == ' ' ) { // collect char constant c = text . charAt ( i ++ ) ; if ( c == ' ' ) throw new ParseException ( \"Malformed char constant: no final '''\" ) ; else if ( i >= 128 ) throw new ParseException ( \"Illegal char constant: \" + ( int ) c ) ; buf . append ( c ) ; values . add ( buf . toString ( ) ) ; buf . setLength ( 0 ) ; } else if ( c == ' ' ) { // collect quoted string for ( ; ; ) { c = text . charAt ( i ++ ) ; if ( c == ' ' ) { i -- ; break ; } if ( c == ' ' ) { c = text . charAt ( i ++ ) ; } else if ( c == ' ' ) break ; buf . append ( c ) ; } if ( c == ' ' ) throw new ParseException ( \"Malformed string: no final '\\\"'\" ) ; values . add ( buf . toString ( ) ) ; buf . setLength ( 0 ) ; } else { // collect upto next whitespace or eos do { if ( c == ' ' ) { c = text . charAt ( i ++ ) ; } buf . append ( c ) ; c = text . charAt ( i ++ ) ; } while ( c > ' ' && c != 127 ) ; values . add ( buf . toString ( ) ) ; buf . setLength ( 0 ) ; if ( c == 0 ) i -- ; // So we never move past the trailing eol } } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reading [CODESPLIT] public void open ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; headerParser = new FysatHeader ( ) ; headerParser . read ( raf , ncfile ) ; ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all the work is here so can be called recursively [CODESPLIT] private Array readData ( ucar . nc2 . Variable v2 , long dataPos , int [ ] origin , int [ ] shape , int [ ] stride ) throws IOException , InvalidRangeException { // long length = myRaf.length(); raf . seek ( dataPos ) ; Vinfo vi = ( Vinfo ) v2 . getSPobject ( ) ; int data_size = vi . vsize ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; Array array ; if ( vi . classType == DataType . BYTE . getPrimitiveClassType ( ) ) { array = Array . factory ( DataType . BYTE , v2 . getShape ( ) , data ) ; } else if ( vi . classType == DataType . SHORT . getPrimitiveClassType ( ) ) { EndianByteBuffer byteBuff = new EndianByteBuffer ( data , vi . byteOrder ) ; short [ ] sdata = byteBuff . getShortArray ( ) ; //for(int i=0; i<sdata.length; i++){ //\tSystem.out.println(sdata[i]); //} array = Array . factory ( DataType . SHORT , v2 . getShape ( ) , sdata ) ; } else if ( vi . classType == DataType . INT . getPrimitiveClassType ( ) ) { EndianByteBuffer byteBuff = new EndianByteBuffer ( data , vi . byteOrder ) ; short [ ] idata = byteBuff . getShortArray ( ) ; array = Array . factory ( DataType . INT , v2 . getShape ( ) , idata ) ; } else { throw new UnsupportedEncodingException ( ) ; } return array . sectionNoReduce ( origin , shape , stride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for the compressed data read all out into a array and then parse into requested [CODESPLIT] public Array readCompressedData ( ucar . nc2 . Variable v2 , long dataPos , int [ ] origin , int [ ] shape , int [ ] stride ) throws IOException , InvalidRangeException { long length = raf . length ( ) ; raf . seek ( dataPos ) ; int data_size = ( int ) ( length - dataPos ) ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; ByteArrayInputStream ios = new ByteArrayInputStream ( data ) ; BufferedImage image = javax . imageio . ImageIO . read ( ios ) ; Raster raster = image . getData ( ) ; DataBuffer db = raster . getDataBuffer ( ) ; if ( db instanceof DataBufferByte ) { DataBufferByte dbb = ( DataBufferByte ) db ; byte [ ] udata = dbb . getData ( ) ; Array array = Array . factory ( DataType . BYTE , v2 . getShape ( ) , udata ) ; v2 . setCachedData ( array , false ) ; return array . sectionNoReduce ( origin , shape , stride ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * * Name : GetGiniLine * * Purpose : Extract a line of data from a GINI image * * Parameters : * buf - buffer containing image data * * Returns : * SUCCESS == 1 * FAILURE == 0 * * [CODESPLIT] private byte [ ] getGiniLine ( int nx , int ny , long doff , int lineNumber , int len , int stride ) throws IOException { byte [ ] data = new byte [ len ] ; /*\n    ** checking image file and set location of first line in file\n    */ raf . seek ( doff ) ; if ( lineNumber >= ny ) throw new IOException ( \"Try to access the file at line number= \" + lineNumber + \" larger then last line number = \" + ny ) ; /*\n    ** Read in the requested line\n    */ int offset = lineNumber * nx + ( int ) doff ; //myRaf.seek ( offset ); for ( int i = 0 ; i < len ; i ++ ) { raf . seek ( offset ) ; data [ i ] = raf . readByte ( ) ; offset = offset + stride ; //myRaf.seek(offset); } //myRaf.read( data, 0, len); return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "some weird adjustment for la1 and la2 . [CODESPLIT] public void setGaussianLats ( int nparallels , float la1 , float la2 ) { log . debug ( \"la1 {}, la2 {}\" , la1 , la2 ) ; if ( this . gaussLats != null ) throw new RuntimeException ( \"Cant modify GdsHorizCoordSys\" ) ; int nlats = ( 2 * nparallels ) ; GaussianLatitudes gaussLats = GaussianLatitudes . factory ( nlats ) ; int bestStartIndex = 0 , bestEndIndex = 0 ; double bestStartDiff = Double . MAX_VALUE ; double bestEndDiff = Double . MAX_VALUE ; for ( int i = 0 ; i < nlats ; i ++ ) { double diff = Math . abs ( gaussLats . latd [ i ] - la1 ) ; if ( diff < bestStartDiff ) { bestStartDiff = diff ; bestStartIndex = i ; } diff = Math . abs ( gaussLats . latd [ i ] - la2 ) ; if ( diff < bestEndDiff ) { bestEndDiff = diff ; bestEndIndex = i ; } } log . debug ( \"first pass: bestStartIndex {}, bestEndIndex {}\" , bestStartIndex , bestEndIndex ) ; if ( Math . abs ( bestEndIndex - bestStartIndex ) + 1 != nyRaw ) { log . warn ( \"GRIB gaussian lats: NP != NY, use NY\" ) ; // see email from Toussaint@dkrz.de datafil:\r nlats = nyRaw ; gaussLats = GaussianLatitudes . factory ( nlats ) ; bestStartIndex = 0 ; bestEndIndex = nyRaw - 1 ; } boolean goesUp = bestEndIndex > bestStartIndex ; log . debug ( \"bestStartIndex {}, bestEndIndex {}, goesUp {}\" , bestStartIndex , bestEndIndex , goesUp ) ; // create the data\r int useIndex = bestStartIndex ; float [ ] data = new float [ nyRaw ] ; float [ ] gaussw = new float [ nyRaw ] ; for ( int i = 0 ; i < nyRaw ; i ++ ) { data [ i ] = ( float ) gaussLats . latd [ useIndex ] ; gaussw [ i ] = ( float ) gaussLats . gaussw [ useIndex ] ; log . trace ( \"i {}, useIndex {}, data {}, gaussw {}\" , i , useIndex , data [ i ] , gaussw [ i ] ) ; if ( goesUp ) { useIndex ++ ; } else { useIndex -- ; } } this . gaussLats = Array . factory ( DataType . FLOAT , new int [ ] { nyRaw } , data ) ; this . gaussw = Array . factory ( DataType . FLOAT , new int [ ] { nyRaw } , gaussw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] protected void init ( double a , double f , int zone , boolean isNorth ) { A = a ; F = 1.0 / f ; // F is flattening\r this . axlon0_deg = ( zone * 6 - 183 ) ; this . axlon0 = axlon0_deg * RADIANS_PER_DEGREE ; double polx2b , polx3b , polx4b , polx5b ; //  Create the ERM constants.\r Eps2 = ( F ) * ( 2.0 - F ) ; Eps25 = .25 * ( Eps2 ) ; Epps2 = ( Eps2 ) / ( 1.0 - Eps2 ) ; polx2b = Eps2 + 1.0 / 4.0 * Math . pow ( Eps2 , 2 ) + 15.0 / 128.0 * Math . pow ( Eps2 , 3 ) - 455.0 / 4096.0 * Math . pow ( Eps2 , 4 ) ; polx2b = 3.0 / 8.0 * polx2b ; polx3b = Math . pow ( Eps2 , 2 ) + 3.0 / 4.0 * Math . pow ( Eps2 , 3 ) - 77.0 / 128.0 * Math . pow ( Eps2 , 4 ) ; polx3b = 15.0 / 256.0 * polx3b ; polx4b = Math . pow ( Eps2 , 3 ) - 41.0 / 32.0 * Math . pow ( Eps2 , 4 ) ; polx4b = polx4b * 35.0 / 3072.0 ; polx5b = - 315.0 / 131072.0 * Math . pow ( Eps2 , 4 ) ; poly1b = 1.0 - ( 1.0 / 4.0 * Eps2 ) - ( 3.0 / 64.0 * Math . pow ( Eps2 , 2 ) ) - ( 5.0 / 256.0 * Math . pow ( Eps2 , 3 ) ) - ( 175.0 / 16384.0 * Math . pow ( Eps2 , 4 ) ) ; poly2b = polx2b * - 2.0 + polx3b * 4.0 - polx4b * 6.0 + polx5b * 8.0 ; poly3b = polx3b * - 8.0 + polx4b * 32.0 - polx5b * 80.0 ; poly4b = polx4b * - 32.0 + polx5b * 192.0 ; poly5b = polx5b * - 128.0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a section specification String . These have the form : <pre > section specification : = selector | selector . selector selector : = varName [ ( dims ) ] varName : = ESCAPED_STRING <p / > dims : = dim | dim dims dim : = : | slice | start : end | start : end : stride slice : = INTEGER start : = INTEGER stride : = INTEGER end : = INTEGER ESCAPED_STRING : must escape characters = . ( < / pre > <p / > Nonterminals are in lower case terminals are in upper case literals are in single quotes . Optional components are enclosed between square braces [ and ] . [CODESPLIT] public static ParsedSectionSpec parseVariableSection ( NetcdfFile ncfile , String variableSection ) throws InvalidRangeException { List < String > tokes = EscapeStrings . tokenizeEscapedName ( variableSection ) ; if ( tokes . size ( ) == 0 ) throw new IllegalArgumentException ( \"empty sectionSpec = \" + variableSection ) ; String selector = tokes . get ( 0 ) ; ParsedSectionSpec outerV = parseVariableSelector ( ncfile , selector ) ; // parse each selector, find the inner variable ParsedSectionSpec current = outerV ; for ( int i = 1 ; i < tokes . size ( ) ; i ++ ) { selector = tokes . get ( i ) ; current . child = parseVariableSelector ( current . v , selector ) ; current = current . child ; } return outerV ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse variable name and index selector out of the selector String . variable name must be escaped [CODESPLIT] private static ParsedSectionSpec parseVariableSelector ( Object parent , String selector ) throws InvalidRangeException { String varNameEsc , indexSelect = null ; int pos1 = EscapeStrings . indexOf ( selector , ' ' ) ; if ( pos1 < 0 ) { // no index varNameEsc = selector ; } else { varNameEsc = selector . substring ( 0 , pos1 ) ; int pos2 = selector . indexOf ( ' ' , pos1 + 1 ) ; indexSelect = selector . substring ( pos1 , pos2 ) ; } if ( debugSelector ) System . out . println ( \" parseVariableSection <\" + selector + \"> = <\" + varNameEsc + \">, <\" + indexSelect + \">\" ) ; Variable v = null ; if ( parent instanceof NetcdfFile ) { // then varNameEsc = varFullNameEsc (i.e. includes groups) NetcdfFile ncfile = ( NetcdfFile ) parent ; v = ncfile . findVariable ( varNameEsc ) ; } else if ( parent instanceof Structure ) { // then varNameEsc = memberNameEsc (i.e. includes groups) Structure s = ( Structure ) parent ; v = s . findVariable ( NetcdfFile . makeNameUnescaped ( varNameEsc ) ) ; // s.findVariable wants unescaped version } if ( v == null ) throw new IllegalArgumentException ( \" cant find variable: \" + varNameEsc + \" in selector=\" + selector ) ; if ( v . getDataType ( ) == DataType . SEQUENCE ) indexSelect = null ; // ignore whatever was sent // get the selected Ranges, or all, and add to the list Section section ; if ( indexSelect != null ) { section = new Section ( indexSelect ) ; section = Section . fill ( section , v . getShape ( ) ) ; // Check section has no nulls, set from shape array. } else { section = v . getShapeAsSection ( ) ; // all } return new ParsedSectionSpec ( v , section ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make section specification String from a range list for a Variable . [CODESPLIT] public static String makeSectionSpecString ( Variable v , List < Range > ranges ) throws InvalidRangeException { StringBuilder sb = new StringBuilder ( ) ; makeSpec ( sb , v , ranges ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is the point ( lat lon ) contained in the ( row col ) rectangle ? [CODESPLIT] private boolean containsOld ( double wantLat , double wantLon , int [ ] rectIndex ) { rectIndex [ 0 ] = Math . max ( Math . min ( rectIndex [ 0 ] , nrows - 1 ) , 0 ) ; rectIndex [ 1 ] = Math . max ( Math . min ( rectIndex [ 1 ] , ncols - 1 ) , 0 ) ; int row = rectIndex [ 0 ] ; int col = rectIndex [ 1 ] ; if ( debug ) System . out . printf ( \" (%d,%d) contains (%f,%f) in (lat=%f %f) (lon=%f %f) ?%n\" , rectIndex [ 0 ] , rectIndex [ 1 ] , wantLat , wantLon , latEdge . get ( row , col ) , latEdge . get ( row + 1 , col ) , lonEdge . get ( row , col ) , lonEdge . get ( row , col + 1 ) ) ; if ( wantLat < latEdge . get ( row , col ) ) return false ; if ( wantLat > latEdge . get ( row + 1 , col ) ) return false ; if ( wantLon < lonEdge . get ( row , col ) ) return false ; if ( wantLon > lonEdge . get ( row , col + 1 ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * http : // mathforum . org / library / drmath / view / 54386 . html [CODESPLIT] private boolean contains ( double wantLat , double wantLon , int [ ] rectIndex ) { rectIndex [ 0 ] = Math . max ( Math . min ( rectIndex [ 0 ] , nrows - 1 ) , 0 ) ; rectIndex [ 1 ] = Math . max ( Math . min ( rectIndex [ 1 ] , ncols - 1 ) , 0 ) ; int row = rectIndex [ 0 ] ; int col = rectIndex [ 1 ] ; double x1 = lonEdge . get ( row , col ) ; double y1 = latEdge . get ( row , col ) ; double x2 = lonEdge . get ( row , col + 1 ) ; double y2 = latEdge . get ( row , col + 1 ) ; double x3 = lonEdge . get ( row + 1 , col + 1 ) ; double y3 = latEdge . get ( row + 1 , col + 1 ) ; double x4 = lonEdge . get ( row + 1 , col ) ; double y4 = latEdge . get ( row + 1 , col ) ; // must all have same determinate sign boolean sign = detIsPositive ( x1 , y1 , x2 , y2 , wantLon , wantLat ) ; if ( sign != detIsPositive ( x2 , y2 , x3 , y3 , wantLon , wantLat ) ) return false ; if ( sign != detIsPositive ( x3 , y3 , x4 , y4 , wantLon , wantLat ) ) return false ; if ( sign != detIsPositive ( x4 , y4 , x1 , y1 , wantLon , wantLat ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * choose x y such that ( matrix multiply ) : [CODESPLIT] private boolean jump2 ( double wantLat , double wantLon , int [ ] rectIndex ) { int row = Math . max ( Math . min ( rectIndex [ 0 ] , nrows - 1 ) , 0 ) ; int col = Math . max ( Math . min ( rectIndex [ 1 ] , ncols - 1 ) , 0 ) ; double lat = latEdge . get ( row , col ) ; double lon = lonEdge . get ( row , col ) ; double diffLat = wantLat - lat ; double diffLon = wantLon - lon ; double dlatdy = latEdge . get ( row + 1 , col ) - lat ; double dlatdx = latEdge . get ( row , col + 1 ) - lat ; double dlondx = lonEdge . get ( row , col + 1 ) - lon ; double dlondy = lonEdge . get ( row + 1 , col ) - lon ; // solve for dlon double dx = ( diffLon - dlondy * diffLat / dlatdy ) / ( dlondx - dlatdx * dlondy / dlatdy ) ; // double dy =  (diffLat - dlatdx * diffLon / dlondx) / (dlatdy - dlatdx * dlondy / dlondx); double dy = ( diffLat - dlatdx * dx ) / dlatdy ; if ( debug ) System . out . printf ( \"   jump from %d %d (dlondx=%f dlondy=%f dlatdx=%f dlatdy=%f) (diffLat,Lon=%f %f) (deltalat,Lon=%f %f)\" , row , col , dlondx , dlondy , dlatdx , dlatdy , diffLat , diffLon , dy , dx ) ; int drow = ( int ) Math . round ( dy ) ; int dcol = ( int ) Math . round ( dx ) ; if ( ( drow == 0 ) && ( dcol == 0 ) ) { if ( debug ) System . out . printf ( \"%n   incr:\" ) ; return incr ( wantLat , wantLon , rectIndex ) ; } else { rectIndex [ 0 ] = Math . max ( Math . min ( row + drow , nrows - 1 ) , 0 ) ; rectIndex [ 1 ] = Math . max ( Math . min ( col + dcol , ncols - 1 ) , 0 ) ; if ( debug ) System . out . printf ( \" to (%d %d)%n\" , rectIndex [ 0 ] , rectIndex [ 1 ] ) ; if ( ( row == rectIndex [ 0 ] ) && ( col == rectIndex [ 1 ] ) ) return false ; // nothing has changed } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we think its got to be in one of the 9 boxes around rectIndex [CODESPLIT] private boolean box9 ( double wantLat , double wantLon , int [ ] rectIndex ) { int row = rectIndex [ 0 ] ; int minrow = Math . max ( row - 1 , 0 ) ; int maxrow = Math . min ( row + 1 , nrows ) ; int col = rectIndex [ 1 ] ; int mincol = Math . max ( col - 1 , 0 ) ; int maxcol = Math . min ( col + 1 , ncols ) ; if ( debug ) System . out . printf ( \"%n   box9:\" ) ; for ( int i = minrow ; i <= maxrow ; i ++ ) for ( int j = mincol ; j <= maxcol ; j ++ ) { rectIndex [ 0 ] = i ; rectIndex [ 1 ] = j ; if ( contains ( wantLat , wantLon , rectIndex ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the <code > CoordinateTransform< / code > from the dataset [CODESPLIT] public VerticalCT makeCoordinateTransform ( NetcdfDataset ds , AttributeContainer ctv ) { String formula_terms = getFormula ( ctv ) ; if ( null == formula_terms ) return null ; // parse the formula string String [ ] values = parseFormula ( formula_terms , \"a b orog\" ) ; if ( values == null ) return null ; a = values [ 0 ] ; b = values [ 1 ] ; orog = values [ 2 ] ; VerticalCT rs = new VerticalCT ( \"AtmHybridHeight_Transform_\" + ctv . getName ( ) , getTransformName ( ) , VerticalCT . Type . HybridHeight , this ) ; rs . addParameter ( new Parameter ( \"standard_name\" , getTransformName ( ) ) ) ; rs . addParameter ( new Parameter ( \"formula_terms\" , formula_terms ) ) ; rs . addParameter ( new Parameter ( \"formula\" , \"height(x,y,z) = a(z) + b(z)*orog(x,y)\" ) ) ; if ( ! addParameter ( rs , HybridHeight . A , ds , a ) ) { return null ; } if ( ! addParameter ( rs , HybridHeight . B , ds , b ) ) { return null ; } if ( ! addParameter ( rs , HybridHeight . OROG , ds , orog ) ) { return null ; } return rs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calling close will force the method to close and will force any open stream to terminate . If the session is local Then that too will be closed . [CODESPLIT] public synchronized void close ( ) { if ( closed ) return ; // recursive calls ok closed = true ; // mark as closed to prevent recursive calls if ( methodstream != null ) { try { this . methodstream . close ( ) ; // May recursr } catch ( IOException ioe ) { /*failure is ok*/ } this . methodstream = null ; } // Force release underlying connection back to the connection manager if ( this . lastresponse != null ) { if ( false ) { try { try { // Attempt to keep connection alive by consuming its remaining content EntityUtils . consume ( this . lastresponse . getEntity ( ) ) ; } finally { HttpClientUtils . closeQuietly ( this . lastresponse ) ; // Paranoia } } catch ( IOException ignore ) { /*ignore*/ } } else HttpClientUtils . closeQuietly ( this . lastresponse ) ; this . lastresponse = null ; } if ( session != null ) { session . removeMethod ( this ) ; if ( localsession ) { session . close ( ) ; session = null ; } } this . lastrequest = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a request add headers and content then send to HTTPSession to do the bulk of the work . [CODESPLIT] public int execute ( ) throws HTTPException { HttpResponse res = executeRaw ( ) ; if ( res != null ) return res . getStatusLine ( ) . getStatusCode ( ) ; else throw new HTTPException ( \"HTTPMethod.execute: null response\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug only [CODESPLIT] public HttpResponse executeRaw ( ) throws HTTPException { if ( this . closed ) throw new IllegalStateException ( \"HTTPMethod: attempt to execute closed method\" ) ; if ( this . executed ) throw new IllegalStateException ( \"HTTPMethod: attempt to re-execute method\" ) ; this . executed = true ; if ( this . methodurl == null ) throw new HTTPException ( \"HTTPMethod: no url specified\" ) ; if ( ! localsession && ! sessionCompatible ( this . methodurl ) ) throw new HTTPException ( \"HTTPMethod: session incompatible url: \" + this . methodurl ) ; // Capture the current state of the parent HTTPSession; never to be modified in this class this . settings = session . mergedSettings ( ) ; try { // add range header if ( this . range != null ) { this . headers . put ( \"Range\" , \"bytes=\" + range [ 0 ] + \"-\" + range [ 1 ] ) ; range = null ; } RequestBuilder rb = getRequestBuilder ( ) ; setcontent ( rb ) ; setheaders ( rb , this . headers ) ; this . lastrequest = buildRequest ( rb , this . settings ) ; AuthScope methodscope = HTTPAuthUtil . uriToAuthScope ( this . methodurl ) ; AuthScope target = HTTPAuthUtil . authscopeUpgrade ( session . getSessionScope ( ) , methodscope ) ; // AFAIK, targethost, httpclient, rb, and session // contain non-overlapping info => we cannot derive one // from any of the others. HttpHost targethost = HTTPAuthUtil . authscopeToHost ( target ) ; HttpClientBuilder cb = HttpClients . custom ( ) ; configClient ( cb , this . settings ) ; session . setAuthenticationAndProxy ( cb ) ; HttpClient httpclient = cb . build ( ) ; if ( MOCKEXECUTOR != null ) { URI uri = this . lastrequest . getURI ( ) ; this . lastresponse = MOCKEXECUTOR . execute ( this . lastrequest ) ; } else { this . lastresponse = httpclient . execute ( targethost , this . lastrequest , session . getContext ( ) ) ; } if ( this . lastresponse == null ) throw new HTTPException ( \"HTTPMethod.execute: Response was null\" ) ; return this . lastresponse ; } catch ( IOException ioe ) { throw new HTTPException ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected TableConfig getPointConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( info . time . getRank ( ) != 1 ) { errlog . format ( \"CFpointObs type=point: coord time must have rank 1, coord var= %s %n\" , info . time . getNameAndDimensions ( ) ) ; return null ; } Dimension obsDim = info . time . getDimension ( 0 ) ; TableConfig obsTable = makeSingle ( ds , obsDim , errlog ) ; obsTable . featureType = FeatureType . POINT ; return obsTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected TableConfig getStationConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingStation ( ds , info , CF . FeatureType . timeSeries , errlog ) ) return null ; // make station table\r TableConfig stnTable = makeStationTable ( ds , FeatureType . STATION , info , errlog ) ; if ( stnTable == null ) return null ; Dimension obsDim = info . childDim ; TableConfig obsTable = null ; switch ( info . encoding ) { case single : obsTable = makeSingle ( ds , obsDim , errlog ) ; break ; case multidim : obsTable = makeMultidimInner ( ds , stnTable , info . childDim , info , errlog ) ; if ( info . time . getRank ( ) == 1 ) { // join time(time)\r obsTable . addJoin ( new JoinArray ( info . time , JoinArray . Type . raw , 0 ) ) ; obsTable . time = info . time . getFullName ( ) ; } break ; case raggedContiguous : stnTable . numRecords = info . ragged_rowSize . getFullName ( ) ; obsTable = makeRaggedContiguousChildTable ( ds , info . parentDim , info . childDim , info . childStruct , errlog ) ; break ; case raggedIndex : obsTable = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; break ; case flat : info . set ( Encoding . flat , obsDim ) ; obsTable = makeStructTable ( ds , FeatureType . STATION , info , errlog ) ; obsTable . parentIndex = ( info . instanceId == null ) ? null : info . instanceId . getFullName ( ) ; Variable stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . CF_ROLE , CF . STATION_ID , obsDim , errlog ) ; if ( stnIdVar == null ) stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . STANDARD_NAME , CF . STATION_ID , obsDim , errlog ) ; obsTable . stnId = ( stnIdVar == null ) ? null : stnIdVar . getFullName ( ) ; obsTable . stnDesc = Evaluator . findNameOfVariableWithAttributeValue ( ds , CF . STANDARD_NAME , CF . PLATFORM_NAME ) ; if ( obsTable . stnDesc == null ) obsTable . stnDesc = Evaluator . findNameOfVariableWithAttributeValue ( ds , CF . STANDARD_NAME , CF . STATION_DESC ) ; obsTable . stnWmoId = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_WMOID , obsDim , errlog ) ; obsTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . SURFACE_ALTITUDE , obsDim , errlog ) ; if ( obsTable . stnAlt == null ) obsTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_ALTITUDE , obsDim , errlog ) ; break ; } if ( obsTable == null ) return null ; stnTable . addChild ( obsTable ) ; return stnTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// [CODESPLIT] protected TableConfig getProfileConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingProfile ( ds , info , errlog ) ) return null ; TableConfig profileTable = makeStructTable ( ds , FeatureType . PROFILE , info , errlog ) ; if ( profileTable == null ) return null ; profileTable . feature_id = identifyIdVariableName ( ds , CF . FeatureType . profile ) ; if ( profileTable . feature_id == null ) { errlog . format ( \"CFpointObs getProfileConfig cant find a profile id %n\" ) ; } // obs table\r VariableDS z = CoordSysEvaluator . findCoordByType ( ds , AxisType . Height ) ; if ( z == null ) z = CoordSysEvaluator . findCoordByType ( ds , AxisType . Pressure ) ; if ( z == null ) z = CoordSysEvaluator . findCoordByType ( ds , AxisType . GeoZ ) ; if ( z == null ) { errlog . format ( \"CFpointObs getProfileConfig cant find a Height coordinate %n\" ) ; return null ; } if ( info . childStruct == null ) info . childStruct = z . getParentStructure ( ) ; TableConfig obsTable = null ; switch ( info . encoding ) { case single : obsTable = makeSingle ( ds , info . childDim , errlog ) ; break ; case multidim : obsTable = makeMultidimInner ( ds , profileTable , info . childDim , info , errlog ) ; if ( z . getRank ( ) == 1 ) { // z(z)\r obsTable . addJoin ( new JoinArray ( z , JoinArray . Type . raw , 0 ) ) ; obsTable . elev = z . getFullName ( ) ; } break ; case raggedContiguous : profileTable . numRecords = info . ragged_rowSize . getFullName ( ) ; obsTable = makeRaggedContiguousChildTable ( ds , info . parentDim , info . childDim , info . childStruct , errlog ) ; break ; case raggedIndex : obsTable = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; break ; case flat : throw new UnsupportedOperationException ( \"CFpointObs: profile flat encoding\" ) ; } if ( obsTable == null ) return null ; profileTable . addChild ( obsTable ) ; return profileTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// [CODESPLIT] protected TableConfig getTrajectoryConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingTraj ( ds , info , errlog ) ) return null ; TableConfig trajTable = makeStructTable ( ds , FeatureType . TRAJECTORY , info , errlog ) ; if ( trajTable == null ) return null ; trajTable . feature_id = identifyIdVariableName ( ds , CF . FeatureType . trajectory ) ; if ( trajTable . feature_id == null ) { errlog . format ( \"CFpointObs getTrajectoryConfig cant find a trajectoy id %n\" ) ; } // obs table\r //Dimension obsDim = time.getDimension(time.getRank() - 1); // may be time(time) or time(traj, obs)\r TableConfig obsConfig = null ; switch ( info . encoding ) { case single : obsConfig = makeSingle ( ds , info . childDim , errlog ) ; break ; case multidim : obsConfig = makeMultidimInner ( ds , trajTable , info . childDim , info , errlog ) ; if ( info . time . getRank ( ) == 1 ) { // join time(obs) or time(time)\r obsConfig . addJoin ( new JoinArray ( info . time , JoinArray . Type . raw , 0 ) ) ; obsConfig . time = info . time . getFullName ( ) ; } break ; case raggedContiguous : trajTable . numRecords = info . ragged_rowSize . getFullName ( ) ; obsConfig = makeRaggedContiguousChildTable ( ds , info . parentDim , info . childDim , info . childStruct , errlog ) ; break ; case raggedIndex : obsConfig = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; break ; case flat : throw new UnsupportedOperationException ( \"CFpointObs: trajectory flat encoding\" ) ; } if ( obsConfig == null ) return null ; trajTable . addChild ( obsConfig ) ; return trajTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// [CODESPLIT] protected TableConfig getTimeSeriesProfileConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingTimeSeriesProfile ( ds , info , CF . FeatureType . timeSeriesProfile , errlog ) ) return null ; VariableDS time = CoordSysEvaluator . findCoordByType ( ds , AxisType . Time ) ; if ( time == null ) return null ; if ( time . getRank ( ) == 0 && time . getParentStructure ( ) == null ) { errlog . format ( \"CFpointObs timeSeriesProfile cannot have a scalar time coordinate%n\" ) ; // why ?\r return null ; } /* distinguish multidim from flat\r\n    if ((info.encoding == Encoding.multidim) && (time.getRank() < 3) && (z.getRank() < 3)) {\r\n      Variable parentId = identifyParent(ds, CF.FeatureType.timeSeriesProfile);\r\n      if ((parentId != null) && (parentId.getRank() == 1) && (parentId.getDimension(0).equals(time.getDimension(0)))) {\r\n        if (time.getRank() == 1) // multidim time must be 2 or 3 dim\r\n          info = new EncodingInfo(Encoding.flat, parentId);\r\n        else if (time.getRank() == 2) {\r\n          Dimension zDim = z.getDimension(z.getRank() - 1); // may be z(z) or z(profile, z)\r\n          if (zDim.equals(time.getDimension(1))) // flat 2D time will have time as inner dim \r\n            info = new EncodingInfo(Encoding.flat, parentId);\r\n        }\r\n      }\r\n    } */ TableConfig stationTable = makeStationTable ( ds , FeatureType . STATION_PROFILE , info , errlog ) ; if ( stationTable == null ) return null ; //Dimension stationDim = ds.findDimension(stationTable.dimName);\r //Dimension profileDim = null;\r //Dimension zDim = null;\r VariableDS z = info . alt ; switch ( info . encoding ) { case single : { assert ( ( time . getRank ( ) >= 1 ) && ( time . getRank ( ) <= 2 ) ) : \"time must be rank 1 or 2\" ; assert ( ( z . getRank ( ) >= 1 ) && ( z . getRank ( ) <= 2 ) ) : \"z must be rank 1 or 2\" ; if ( time . getRank ( ) == 2 ) { if ( z . getRank ( ) == 2 ) // 2d time, 2d z\r assert time . getDimensions ( ) . equals ( z . getDimensions ( ) ) : \"rank-2 time and z dimensions must be the same\" ; else // 2d time, 1d z\r assert time . getDimension ( 1 ) . equals ( z . getDimension ( 0 ) ) : \"rank-2 time must have z inner dimension\" ; //profileDim = time.getDimension(0);\r //zDim = time.getDimension(1);\r } else { // 1d time\r if ( z . getRank ( ) == 2 ) { // 1d time, 2d z\r assert z . getDimension ( 0 ) . equals ( time . getDimension ( 0 ) ) : \"rank-2 z must have time outer dimension\" ; //profileDim = z.getDimension(0);\r //zDim = z.getDimension(1);\r } else { // 1d time, 1d z\r assert ! time . getDimension ( 0 ) . equals ( z . getDimension ( 0 ) ) : \"time and z dimensions must be different\" ; //profileDim = time.getDimension(0);\r //zDim = z.getDimension(0);\r } } // make profile table\r TableConfig profileTable = makeStructTable ( ds , FeatureType . PROFILE , new EncodingInfo ( ) . set ( Encoding . multidim , info . childDim ) , errlog ) ; if ( profileTable == null ) return null ; if ( time . getRank ( ) == 1 ) { // join time(time)\r //profileTable.addJoin(new JoinArray(time, JoinArray.Type.raw, 0));\r profileTable . addJoin ( new JoinArray ( time , JoinArray . Type . level , 1 ) ) ; profileTable . time = time . getFullName ( ) ; } stationTable . addChild ( profileTable ) ; // make the inner (z) table\r TableConfig zTable = makeMultidimInner ( ds , profileTable , info . grandChildDim , info , errlog ) ; if ( z . getRank ( ) == 1 ) { // join z(z)\r zTable . addJoin ( new JoinArray ( z , JoinArray . Type . raw , 0 ) ) ; zTable . elev = z . getFullName ( ) ; } profileTable . addChild ( zTable ) ; break ; } case multidim : { assert ( ( time . getRank ( ) >= 1 ) && ( time . getRank ( ) <= 3 ) ) : \"time must be rank 2 or 3\" ; assert ( ( z . getRank ( ) == 1 ) || ( z . getRank ( ) == 3 ) ) : \"z must be rank 1 or 3\" ; if ( time . getRank ( ) == 3 ) { if ( z . getRank ( ) == 3 ) // 3d time, 3d z\r assert time . getDimensions ( ) . equals ( z . getDimensions ( ) ) : \"rank-3 time and z dimensions must be the same\" ; else // 3d time, 1d z\r assert time . getDimension ( 2 ) . equals ( z . getDimension ( 0 ) ) : \"rank-3 time must have z inner dimension\" ; //profileDim = time.getDimension(1);\r //zDim = time.getDimension(2);\r } else if ( time . getRank ( ) == 2 ) { // 2d time\r if ( z . getRank ( ) == 3 ) { // 2d time, 3d z\r assert z . getDimension ( 1 ) . equals ( time . getDimension ( 1 ) ) : \"rank-2 time must have time inner dimension\" ; //profileDim = z.getDimension(1);\r //zDim = z.getDimension(2);\r } else { // 2d time, 1d z\r assert ! time . getDimension ( 0 ) . equals ( z . getDimension ( 0 ) ) : \"time and z dimensions must be different\" ; assert ! time . getDimension ( 1 ) . equals ( z . getDimension ( 0 ) ) : \"time and z dimensions must be different\" ; //profileDim = time.getDimension(1);\r //zDim = z.getDimension(0);\r } } else { // 1d time\r if ( z . getRank ( ) == 1 ) { assert ! time . getDimension ( 0 ) . equals ( z . getDimension ( 0 ) ) : \"time and z dimensions must be different\" ; } } TableConfig profileTable = makeMultidimInner ( ds , stationTable , info . childDim , info , errlog ) ; if ( profileTable == null ) return null ; if ( time . getRank ( ) == 1 ) { // join time(time)\r profileTable . addJoin ( new JoinArray ( time , JoinArray . Type . level , 1 ) ) ; profileTable . time = time . getFullName ( ) ; } stationTable . addChild ( profileTable ) ; // make the inner (z) table\r TableConfig zTable = makeMultidimInner3D ( ds , stationTable , profileTable , info . grandChildDim , errlog ) ; if ( z . getRank ( ) == 1 ) { // join z(z)\r zTable . addJoin ( new JoinArray ( z , JoinArray . Type . raw , 0 ) ) ; zTable . elev = z . getFullName ( ) ; } profileTable . addChild ( zTable ) ; break ; } case raggedIndex : { TableConfig profileTable = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; stationTable . addChild ( profileTable ) ; profileTable . numRecords = info . ragged_rowSize . getFullName ( ) ; TableConfig obsTable = makeRaggedContiguousChildTable ( ds , info . childDim , info . grandChildDim , info . grandChildStruct , errlog ) ; profileTable . addChild ( obsTable ) ; break ; } case raggedContiguous : // NOT USED\r throw new UnsupportedOperationException ( \"CFpointObs: timeSeriesProfile raggedContiguous encoding not allowed\" ) ; /*\r\n      case flat:\r\n        //profileDim = time.getDimension(0); // may be time(profile) or time(profile, z)\r\n        Variable parentId = identifyParent(ds, CF.FeatureType.timeSeriesProfile);\r\n\r\n        TableConfig profileTable = makeStructTable(ds, FeatureType.PROFILE, info, errlog);\r\n        profileTable.parentIndex = parentId.getName();\r\n        profileTable.stnId = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_ID, info.childDim, errlog);\r\n        profileTable.stnDesc = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_DESC, info.childDim, errlog);\r\n        profileTable.stnWmoId = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_WMOID, info.childDim, errlog);\r\n        profileTable.stnAlt = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_ALTITUDE, info.childDim, errlog);\r\n        stationTable.addChild(profileTable);\r\n\r\n        //zDim = z.getDimension(z.getRank() - 1); // may be z(z) or z(profile, z)\r\n        TableConfig zTable = makeMultidimInner(ds, profileTable, info.grandChildDim, errlog);\r\n        if (z.getRank() == 1) // z(z)\r\n          zTable.addJoin(new JoinArray(z, JoinArray.Type.raw, 0));\r\n        profileTable.addChild(zTable);\r\n\r\n        break; */ } return stationTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for stations figure out the encoding [CODESPLIT] protected boolean identifyEncodingStation ( NetcdfDataset ds , EncodingInfo info , CF . FeatureType ftype , Formatter errlog ) { // find the obs dimension\r Dimension obsDim = null ; if ( info . time . getRank ( ) > 0 ) obsDim = info . time . getDimension ( info . time . getRank ( ) - 1 ) ; // may be time(time) or time(stn, obs)\r else if ( info . time . getParentStructure ( ) != null ) { Structure parent = info . time . getParentStructure ( ) ; // if time axis is a structure member, try pulling dimension out of parent structure\r obsDim = parent . getDimension ( parent . getRank ( ) - 1 ) ; } if ( obsDim == null ) { errlog . format ( \"CFpointObs: must have a non-scalar Time coordinate%n\" ) ; return false ; } // find the station dimension\r if ( info . lat . getRank ( ) == 0 ) { // scalar means single\r info . set ( Encoding . single , null , obsDim ) ; return true ; } Dimension stnDim = info . lat . getDimension ( 0 ) ; if ( obsDim == stnDim ) { info . set ( Encoding . flat , null , obsDim ) ; // not used ?\r return true ; } // the raggeds\r if ( identifyRaggeds ( ds , info , stnDim , obsDim , errlog ) ) return true ; // heres whats left\r if ( info . lat . getRank ( ) == 1 ) { //Encoding e = (info.time.getParentStructure() != null) ? Encoding.multiStructure : Encoding.multidim;\r info . set ( Encoding . multidim , stnDim , obsDim ) ; return true ; } errlog . format ( \"CFpointObs: %s Must have Lat/Lon coordinates of rank 0 or 1%n\" , ftype ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify ragged array representations for single nests ( station profile trajectory ) [CODESPLIT] protected boolean identifyRaggeds ( NetcdfDataset ds , EncodingInfo info , Dimension instanceDim , Dimension sampleDim , Formatter errlog ) { // check for contiguous\r Evaluator . VarAtt varatt = Evaluator . findVariableWithAttribute ( ds , CF . SAMPLE_DIMENSION ) ; // CF 1.6\r if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_ROWSIZE ) ; // backwards compatibility\r if ( varatt != null ) { Variable ragged_rowSize = varatt . var ; String sampleDimName = varatt . att . getStringValue ( ) ; if ( sampleDim != null && ! sampleDimName . equals ( sampleDim . getShortName ( ) ) ) { errlog . format ( \"CFpointObs: Contiguous ragged array representation: row_size variable has sample dimension %s must be %s%n\" , sampleDimName , sampleDim . getShortName ( ) ) ; return false ; } if ( sampleDim == null ) { sampleDim = ds . findDimension ( sampleDimName ) ; if ( sampleDim == null ) { errlog . format ( \"CFpointObs: Contiguous ragged array representation: row_size variable has invalid sample dimension %s%n\" , sampleDimName ) ; return false ; } } Dimension rrDim ; if ( ragged_rowSize . getRank ( ) > 0 ) rrDim = ragged_rowSize . getDimension ( 0 ) ; // nobs(station)\r else if ( ragged_rowSize . getParentStructure ( ) != null ) { Structure parent = ragged_rowSize . getParentStructure ( ) ; // if ragged_rowSize is a structure member, use dimension of parent structure\r rrDim = parent . getDimension ( 0 ) ; } else { errlog . format ( \"CFpointObs: Contiguous ragged array representation: row_size variable (%s) must have rank 1%n\" , ragged_rowSize ) ; return false ; } if ( instanceDim != null && instanceDim != rrDim ) { errlog . format ( \"CFpointObs: Contiguous ragged array representation: row_size variable has invalid instance dimension %s must be %s%n\" , rrDim , instanceDim ) ; return false ; } instanceDim = rrDim ; if ( ragged_rowSize . getDataType ( ) != DataType . INT ) { errlog . format ( \"CFpointObs: Contiguous ragged array representation: row_size variable must be of type integer%n\" ) ; return false ; } info . set ( Encoding . raggedContiguous , instanceDim , sampleDim ) ; info . ragged_rowSize = ragged_rowSize ; info . parentStruct = ragged_rowSize . getParentStructure ( ) ; return true ; } // rowsize was found\r varatt = Evaluator . findVariableWithAttribute ( ds , CF . INSTANCE_DIMENSION ) ; // CF 1.6\r if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_PARENTINDEX ) ; // backwards compatibility\r if ( varatt != null ) { Variable ragged_parentIndex = varatt . var ; String instanceDimName = varatt . att . getStringValue ( ) ; if ( instanceDim != null && ! instanceDimName . equals ( instanceDim . getShortName ( ) ) ) { errlog . format ( \"CFpointObs: Indexed ragged array representation: parent_index variable has instance dimension %s must be %s%n\" , instanceDimName , instanceDim . getShortName ( ) ) ; return false ; } if ( instanceDim == null ) { instanceDim = ds . findDimension ( instanceDimName ) ; if ( instanceDim == null ) { errlog . format ( \"CFpointObs: Indexed ragged array representation: parent_index variable has invalid instance dimension %s%n\" , instanceDimName ) ; return false ; } } if ( ragged_parentIndex . getDataType ( ) != DataType . INT ) { errlog . format ( \"CFpointObs: Indexed ragged array representation: parent_index variable must be of type integer%n\" ) ; return false ; } // allow netcdf-4 structures, eg kunicki\r if ( ragged_parentIndex . isMemberOfStructure ( ) ) { Structure s = ragged_parentIndex . getParentStructure ( ) ; if ( s . getRank ( ) == 0 || ! s . getDimension ( 0 ) . equals ( sampleDim ) ) { errlog . format ( \"CFpointObs: Indexed ragged array representation (structure): parent_index variable must be of form Struct { %s }(%s) %n\" , ragged_parentIndex . getFullName ( ) , sampleDim . getShortName ( ) ) ; return false ; } } else { if ( ragged_parentIndex . getRank ( ) != 1 || ! ragged_parentIndex . getDimension ( 0 ) . equals ( sampleDim ) ) { errlog . format ( \"CFpointObs: Indexed ragged array representation: parent_index variable must be of form %s(%s) %n\" , ragged_parentIndex . getFullName ( ) , sampleDim . getShortName ( ) ) ; return false ; } } info . set ( Encoding . raggedIndex , instanceDim , sampleDim ) ; info . ragged_parentIndex = ragged_parentIndex ; info . childStruct = ragged_parentIndex . getParentStructure ( ) ; return true ; } // parent index was found\r /* kunicki 10/21/2011\r\n    Variable ragged_parentIndex = Evaluator.getVariableWithAttributeValue(ds, CF.RAGGED_PARENTINDEX, parentDim.getShortName());\r\n    if ((ragged_parentIndex == null) ||\r\n            (!ragged_parentIndex.isMemberOfStructure() && (ragged_parentIndex.getRank() == 0 || ragged_parentIndex.getDimension(0).getShortName() != childDim.getShortName()) ||\r\n                    (ragged_parentIndex.isMemberOfStructure() && (ragged_parentIndex.getParentStructure().getRank() == 0 || ragged_parentIndex.getParentStructure().getDimension(0).getShortName() != childDim.getShortName())))\r\n            ) {\r\n      // if ((null == ragged_parentIndex) || (ragged_parentIndex.getRank() == 0) || (ragged_parentIndex.getDimension(0).getShortName() != childDim.getShortName())) {\r\n      errlog.format(\"there must be a ragged_parent_index variable with outer dimension that matches obs dimension %s%n\", childDim.getShortName());\r\n      return null;\r\n    }  */ return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify ragged array representations for double nests ( timeSeries profile timeSeries trajectory ) <p / > This uses the contiguous ragged array representation for each profile ( 9 . 5 . 43 . 3 ) and the indexed ragged array representation to organise the profiles into time series ( 9 . 3 . 54 ) . The canonical use case is when writing real - time data streams that contain profiles from many stations arriving randomly with the data for each entire profile written all at once . [CODESPLIT] protected boolean identifyDoubleRaggeds ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) { // the timeseries are stored as ragged index\r Evaluator . VarAtt varatt = Evaluator . findVariableWithAttribute ( ds , CF . INSTANCE_DIMENSION ) ; if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_PARENTINDEX ) ; if ( varatt == null ) return false ; Variable ragged_parentIndex = varatt . var ; String instanceDimName = varatt . att . getStringValue ( ) ; Dimension stationDim = ds . findDimension ( instanceDimName ) ; if ( stationDim == null ) { errlog . format ( \"CFpointObs: Indexed ragged array representation: parent_index variable has illegal value for %s = %s%n\" , CF . INSTANCE_DIMENSION , instanceDimName ) ; return false ; } if ( ragged_parentIndex . getDataType ( ) != DataType . INT ) { errlog . format ( \"CFpointObs: Indexed ragged array representation: parent_index variable must be of type integer%n\" ) ; return false ; } if ( ragged_parentIndex . getRank ( ) != 1 && info . childStruct == null ) { errlog . format ( \"CFpointObs: Indexed ragged array representation: parent_index variable %s must be 1D %n\" , ragged_parentIndex ) ; return false ; } Dimension profileDim = ( info . childDim != null ) ? info . childDim : ragged_parentIndex . getDimension ( 0 ) ; // onto the profiles, stored contiguously\r varatt = Evaluator . findVariableWithAttribute ( ds , CF . SAMPLE_DIMENSION ) ; if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_ROWSIZE ) ; if ( varatt == null ) return false ; Variable ragged_rowSize = varatt . var ; String obsDimName = varatt . att . getStringValue ( ) ; Dimension obsDim = ds . findDimension ( obsDimName ) ; if ( obsDimName == null ) { errlog . format ( \"CFpointObs: Contiguous ragged array representation: parent_index variable has illegal value for %s = %s%n\" , CF . SAMPLE_DIMENSION , obsDimName ) ; return false ; } if ( ! obsDimName . equals ( info . grandChildDim . getShortName ( ) ) ) { errlog . format ( \"CFpointObs: Contiguous ragged array representation: row_size variable has obs dimension %s must be %s%n\" , obsDimName , info . childDim ) ; return false ; } if ( ragged_rowSize . getDataType ( ) != DataType . INT ) { errlog . format ( \"CFpointObs: Contiguous ragged array representation: row_size variable must be of type integer%n\" ) ; return false ; } if ( info . childDim == null ) { // nc4 ext\r Dimension profileDim2 = ragged_rowSize . getDimension ( 0 ) ; if ( profileDim2 != profileDim ) { errlog . format ( \"CFpointObs: Double ragged array representation dimensions do not agree: %s != %s%n\" , profileDim2 . getShortName ( ) , profileDim . getShortName ( ) ) ; return false ; } } info . set ( Encoding . raggedIndex , stationDim , profileDim , obsDim ) ; info . ragged_parentIndex = ragged_parentIndex ; info . ragged_rowSize = ragged_rowSize ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for station and stationProfile not flat [CODESPLIT] private TableConfig makeStationTable ( NetcdfDataset ds , FeatureType ftype , EncodingInfo info , Formatter errlog ) throws IOException { Variable lat = CoordSysEvaluator . findCoordByType ( ds , AxisType . Lat ) ; Variable lon = CoordSysEvaluator . findCoordByType ( ds , AxisType . Lon ) ; if ( lat == null || lon == null ) { errlog . format ( \"CFpointObs: must have lat and lon coordinates%n\" ) ; return null ; } //Dimension stationDim = (info.encoding == Encoding.single) ? null : lat.getDimension(0); // assumes outer dim of lat is parent dimension, single = scalar\r Table . Type stationTableType = Table . Type . Structure ; if ( info . encoding == Encoding . single ) stationTableType = Table . Type . Top ; if ( info . encoding == Encoding . flat ) stationTableType = Table . Type . Construct ; Dimension stationDim = ( info . encoding == Encoding . flat ) ? info . childDim : info . parentDim ; String name = ( stationDim == null ) ? \" single\" : stationDim . getShortName ( ) ; TableConfig stnTable = new TableConfig ( stationTableType , name ) ; stnTable . featureType = ftype ; // stnId\r Variable stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . CF_ROLE , CF . TIMESERIES_ID , stationDim , errlog ) ; if ( stnIdVar == null ) stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . STANDARD_NAME , CF . STATION_ID , stationDim , errlog ) ; if ( stnIdVar == null ) { errlog . format ( \"CFpointObs: must have a Station id variable with %s = %s%n\" , CF . CF_ROLE , CF . TIMESERIES_ID ) ; return null ; } stnTable . stnId = stnIdVar . getFullName ( ) ; info . instanceId = stnIdVar ; stnTable . stnDesc = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . PLATFORM_NAME , stationDim , errlog ) ; if ( stnTable . stnDesc == null ) stnTable . stnDesc = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_DESC , stationDim , errlog ) ; stnTable . stnWmoId = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . PLATFORM_ID , stationDim , errlog ) ; if ( stnTable . stnWmoId == null ) stnTable . stnWmoId = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_WMOID , stationDim , errlog ) ; stnTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . SURFACE_ALTITUDE , stationDim , errlog ) ; if ( stnTable . stnAlt == null ) stnTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_ALTITUDE , stationDim , errlog ) ; stnTable . lat = lat . getFullName ( ) ; stnTable . lon = lon . getFullName ( ) ; if ( info . encoding != Encoding . single && stationDim != null ) { stnTable . dimName = stationDim . getShortName ( ) ; makeStructureInfo ( stnTable , ds , stnIdVar . getParentStructure ( ) , stationDim ) ; } // LOOK probably need a standard name here\r // optional alt coord - detect if its a station height or actually associated with the obs, eg for a profile\r if ( stnTable . stnAlt == null ) { Variable alt = CoordSysEvaluator . findCoordByType ( ds , AxisType . Height ) ; if ( alt != null ) { if ( ( info . encoding == Encoding . single ) && alt . getRank ( ) == 0 ) stnTable . stnAlt = alt . getFullName ( ) ; if ( ( info . encoding != Encoding . single ) && ( lat . getRank ( ) == alt . getRank ( ) ) && alt . getRank ( ) > 0 && alt . getDimension ( 0 ) . equals ( stationDim ) ) stnTable . stnAlt = alt . getFullName ( ) ; } } return stnTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private TableConfig makeRaggedContiguousChildTable ( NetcdfDataset ds , Dimension parentDim , Dimension childDim , Structure childStruct , Formatter errlog ) throws IOException { TableConfig childTable = new TableConfig ( Table . Type . Contiguous , childDim . getShortName ( ) ) ; childTable . dimName = childDim . getShortName ( ) ; childTable . lat = matchAxisTypeAndDimension ( ds , AxisType . Lat , childDim ) ; childTable . lon = matchAxisTypeAndDimension ( ds , AxisType . Lon , childDim ) ; childTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Height , childDim ) ; if ( childTable . elev == null ) childTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Pressure , childDim ) ; if ( childTable . elev == null ) childTable . elev = matchAxisTypeAndDimension ( ds , AxisType . GeoZ , childDim ) ; childTable . time = matchAxisTypeAndDimension ( ds , AxisType . Time , childDim ) ; makeStructureInfo ( childTable , ds , childStruct , childDim ) ; return childTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the inner table of Structure ( outer inner ) and middle table of Structure ( outer middle inner ) [CODESPLIT] private TableConfig makeMultidimInner ( NetcdfDataset ds , TableConfig parentTable , Dimension obsDim , EncodingInfo info , Formatter errlog ) throws IOException { Dimension parentDim = ds . findDimension ( parentTable . dimName ) ; Table . Type obsTableType = ( parentTable . structureType == TableConfig . StructureType . PsuedoStructure ) ? Table . Type . MultidimInnerPsuedo : Table . Type . MultidimInner ; // if (info.time.isMemberOfStructure()) obsTableType = Table.Type.Structure;\r TableConfig obsTable = new TableConfig ( obsTableType , obsDim . getShortName ( ) ) ; obsTable . lat = matchAxisTypeAndDimension ( ds , AxisType . Lat , parentDim , obsDim ) ; obsTable . lon = matchAxisTypeAndDimension ( ds , AxisType . Lon , parentDim , obsDim ) ; obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Height , parentDim , obsDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Pressure , parentDim , obsDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . GeoZ , parentDim , obsDim ) ; obsTable . time = matchAxisTypeAndDimension ( ds , AxisType . Time , parentDim , obsDim ) ; // divide up the variables between the parent and the obs\r List < String > obsVars ; List < Variable > vars = ds . getVariables ( ) ; List < String > parentVars = new ArrayList <> ( vars . size ( ) ) ; obsVars = new ArrayList <> ( vars . size ( ) ) ; for ( Variable orgV : vars ) { if ( orgV instanceof Structure ) continue ; Dimension dim0 = orgV . getDimension ( 0 ) ; if ( ( dim0 != null ) && dim0 . equals ( parentDim ) ) { if ( ( orgV . getRank ( ) == 1 ) || ( ( orgV . getRank ( ) == 2 ) && orgV . getDataType ( ) == DataType . CHAR ) ) { parentVars . add ( orgV . getShortName ( ) ) ; } else { Dimension dim1 = orgV . getDimension ( 1 ) ; if ( ( dim1 != null ) && dim1 . equals ( obsDim ) ) obsVars . add ( orgV . getShortName ( ) ) ; } } } parentTable . vars = parentVars ; // parentTable.vars = parentTable.isPsuedoStructure ? parentVars : null; // restrict to these if psuedoStruct\r obsTable . structureType = parentTable . structureType ; obsTable . outerName = parentDim . getShortName ( ) ; obsTable . innerName = obsDim . getShortName ( ) ; obsTable . dimName = ( parentTable . structureType == TableConfig . StructureType . PsuedoStructure ) ? obsTable . outerName : obsTable . innerName ; obsTable . structName = obsDim . getShortName ( ) ; obsTable . vars = obsVars ; return obsTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the inner table of Structure ( outer middle inner ) [CODESPLIT] private TableConfig makeMultidimInner3D ( NetcdfDataset ds , TableConfig outerTable , TableConfig middleTable , Dimension innerDim , Formatter errlog ) throws IOException { Dimension outerDim = ds . findDimension ( outerTable . dimName ) ; Dimension middleDim = ds . findDimension ( middleTable . innerName ) ; Table . Type obsTableType = ( outerTable . structureType == TableConfig . StructureType . PsuedoStructure ) ? Table . Type . MultidimInnerPsuedo3D : Table . Type . MultidimInner3D ; TableConfig obsTable = new TableConfig ( obsTableType , innerDim . getShortName ( ) ) ; obsTable . structureType = TableConfig . StructureType . PsuedoStructure2D ; obsTable . dimName = outerTable . dimName ; obsTable . outerName = middleTable . innerName ; obsTable . innerName = innerDim . getShortName ( ) ; obsTable . structName = innerDim . getShortName ( ) ; obsTable . lat = matchAxisTypeAndDimension ( ds , AxisType . Lat , outerDim , middleDim , innerDim ) ; obsTable . lon = matchAxisTypeAndDimension ( ds , AxisType . Lon , outerDim , middleDim , innerDim ) ; obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Height , outerDim , middleDim , innerDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Pressure , middleDim , innerDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . GeoZ , middleDim , innerDim ) ; obsTable . time = matchAxisTypeAndDimension ( ds , AxisType . Time , outerDim , middleDim , innerDim ) ; // divide up the variables between the 3 tables\r List < Variable > vars = ds . getVariables ( ) ; List < String > outerVars = new ArrayList <> ( vars . size ( ) ) ; List < String > middleVars = new ArrayList <> ( vars . size ( ) ) ; List < String > innerVars = new ArrayList <> ( vars . size ( ) ) ; for ( Variable orgV : vars ) { if ( orgV instanceof Structure ) continue ; if ( ( orgV . getRank ( ) == 1 ) || ( ( orgV . getRank ( ) == 2 ) && orgV . getDataType ( ) == DataType . CHAR ) ) { if ( outerDim . equals ( orgV . getDimension ( 0 ) ) ) outerVars . add ( orgV . getShortName ( ) ) ; } else if ( orgV . getRank ( ) == 2 ) { if ( outerDim . equals ( orgV . getDimension ( 0 ) ) && middleDim . equals ( orgV . getDimension ( 1 ) ) ) middleVars . add ( orgV . getShortName ( ) ) ; } else if ( orgV . getRank ( ) == 3 ) { if ( outerDim . equals ( orgV . getDimension ( 0 ) ) && middleDim . equals ( orgV . getDimension ( 1 ) ) && innerDim . equals ( orgV . getDimension ( 2 ) ) ) innerVars . add ( orgV . getShortName ( ) ) ; } } outerTable . vars = outerVars ; middleTable . vars = middleVars ; obsTable . vars = innerVars ; return obsTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "class I don t understand enough of the code base to anticipate implementation artifacts . [CODESPLIT] protected String matchAxisTypeAndDimension ( NetcdfDataset ds , AxisType type , final Dimension outer ) { Variable var = CoordSysEvaluator . findCoordByType ( ds , type , new CoordSysEvaluator . Predicate ( ) { public boolean match ( CoordinateAxis axis ) { if ( ( outer == null ) && ( axis . getRank ( ) == 0 ) ) return true ; if ( ( outer != null ) && ( axis . getRank ( ) == 1 ) && ( outer . equals ( axis . getDimension ( 0 ) ) ) ) return true ; // if axis is structure member, try pulling dimension out of parent structure\r if ( axis . getParentStructure ( ) != null ) { Structure parent = axis . getParentStructure ( ) ; if ( ( outer != null ) && ( parent . getRank ( ) == 1 ) && ( outer . equals ( parent . getDimension ( 0 ) ) ) ) return true ; } return false ; } } ) ; if ( var == null ) return null ; return var . getFullName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Added 5 - 30 - 2006 to allow for resetting of the input used by this object . This saves in memory allocation costs [CODESPLIT] public void setStream ( InputStream zStream ) { last = 0 ; origPtr = 0 ; blockSize100k = 0 ; blockRandomised = false ; bsBuff = 0 ; bsLive = 0 ; mCrc = new CRC ( ) ; nInUse = 0 ; bsStream = null ; streamEnd = false ; currentChar = - 1 ; currentState = START_BLOCK_STATE ; storedBlockCRC = storedCombinedCRC = 0 ; computedBlockCRC = computedCombinedCRC = 0 ; i2 = count = chPrev = ch2 = 0 ; i = tPos = 0 ; rNToGo = 0 ; rTPos = 0 ; j2 = 0 ; z = 0 ; bsSetStream ( zStream ) ; initialize ( ) ; if ( ! streamEnd ) { // Handle if initialize does not detect valid bz2 stream initBlock ( ) ; setupBlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the stream . [CODESPLIT] public int read ( ) { if ( streamEnd ) { return - 1 ; } else { int retChar = currentChar ; switch ( currentState ) { case START_BLOCK_STATE : break ; case RAND_PART_A_STATE : break ; case RAND_PART_B_STATE : setupRandPartB ( ) ; break ; case RAND_PART_C_STATE : setupRandPartC ( ) ; break ; case NO_RAND_PART_A_STATE : break ; case NO_RAND_PART_B_STATE : setupNoRandPartB ( ) ; break ; case NO_RAND_PART_C_STATE : setupNoRandPartC ( ) ; break ; default : break ; } return retChar ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this from awt event thread . The task is run in a background thread . [CODESPLIT] public void start ( java . awt . Component top , String taskName , int progressMaxCount ) { // create ProgressMonitor pm = new javax . swing . ProgressMonitor ( top , taskName , \"\" , 0 , progressMaxCount ) ; pm . setMillisToDecideToPopup ( millisToDecideToPopup ) ; pm . setMillisToPopup ( millisToPopup ) ; // do task in a seperate, non-event, thread taskThread = new Thread ( task ) ; taskThread . start ( ) ; // create timer, whose events happen on the awt event Thread ActionListener watcher = new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { secs ++ ; if ( pm . isCanceled ( ) ) { task . cancel ( ) ; } else { // indicate progress String note = task . getNote ( ) ; pm . setNote ( note == null ? secs + \" secs\" : note ) ; int progress = task . getProgress ( ) ; pm . setProgress ( progress <= 0 ? secs : progress ) ; } // need to make sure task acknowledges the cancel; so dont shut down // until the task is done if ( task . isDone ( ) ) { timer . stop ( ) ; pm . close ( ) ; // Toolkit.getDefaultToolkit().beep(); if ( task . isError ( ) ) { javax . swing . JOptionPane . showMessageDialog ( null , task . getErrorMessage ( ) ) ; } if ( task . isSuccess ( ) ) fireEvent ( new ActionEvent ( this , 0 , \"success\" ) ) ; else if ( task . isError ( ) ) fireEvent ( new ActionEvent ( this , 0 , \"error\" ) ) ; else if ( task . isCancel ( ) ) fireEvent ( new ActionEvent ( this , 0 , \"cancel\" ) ) ; else fireEvent ( new ActionEvent ( this , 0 , \"done\" ) ) ; } } } ; timer = new javax . swing . Timer ( 1000 , watcher ) ; // every second timer . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Misc . [CODESPLIT] static public byte [ ] readbinaryfile ( File f ) throws IOException { try ( FileInputStream fis = new FileInputStream ( f ) ) { return readbinaryfile ( fis ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a uri string to an instance of java . net . URI . The critical thing is that this procedure can handle backslash escaped uris as well as %xx escaped uris . [CODESPLIT] static public URI parseToURI ( final String u ) throws URISyntaxException { StringBuilder buf = new StringBuilder ( ) ; int i = 0 ; while ( i < u . length ( ) ) { char c = u . charAt ( i ) ; if ( c == ' ' ) { if ( i + 1 == u . length ( ) ) throw new URISyntaxException ( u , \"Trailing '\\' at end of url\" ) ; buf . append ( \"%5c\" ) ; i ++ ; c = u . charAt ( i ) ; buf . append ( String . format ( \"%%%02x\" , ( int ) c ) ) ; } else buf . append ( c ) ; i ++ ; } return new URI ( buf . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove selected fields from a URI producing a new URI [CODESPLIT] static URI uriExclude ( final URI uri , URIPart ... excludes ) { URIBuilder urib = new URIBuilder ( ) ; EnumSet < URIPart > set = EnumSet . of ( excludes [ 0 ] , excludes ) ; for ( URIPart part : URIPart . values ( ) ) { if ( set . contains ( part ) ) continue ; switch ( part ) { case SCHEME : urib . setScheme ( uri . getScheme ( ) ) ; break ; case USERINFO : urib . setUserInfo ( uri . getUserInfo ( ) ) ; break ; case HOST : urib . setHost ( uri . getHost ( ) ) ; break ; case PORT : urib . setPort ( uri . getPort ( ) ) ; break ; case PATH : urib . setPath ( uri . getPath ( ) ) ; break ; case QUERY : urib . setCustomQuery ( uri . getQuery ( ) ) ; break ; case FRAGMENT : urib . setFragment ( uri . getFragment ( ) ) ; break ; } } try { return urib . build ( ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a zero - length string to null [CODESPLIT] static public String nullify ( String s ) { if ( s != null && s . length ( ) == 0 ) s = null ; return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join two string together to form proper path WITHOUT trailing slash [CODESPLIT] static public String canonjoin ( String prefix , String suffix ) { if ( prefix == null ) prefix = \"\" ; if ( suffix == null ) suffix = \"\" ; prefix = HTTPUtil . canonicalpath ( prefix ) ; suffix = HTTPUtil . canonicalpath ( suffix ) ; StringBuilder result = new StringBuilder ( ) ; result . append ( prefix ) ; int prelen = prefix . length ( ) ; if ( prelen > 0 && result . charAt ( prelen - 1 ) != ' ' ) { result . append ( ' ' ) ; prelen ++ ; } if ( suffix . length ( ) > 0 && suffix . charAt ( 0 ) == ' ' ) result . append ( suffix . substring ( 1 ) ) ; else result . append ( suffix ) ; int len = result . length ( ) ; if ( len > 0 && result . charAt ( len - 1 ) == ' ' ) { result . deleteCharAt ( len - 1 ) ; len -- ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert path to use / consistently and to remove any trailing / [CODESPLIT] static public String canonicalpath ( String path ) { if ( path == null ) return null ; StringBuilder b = new StringBuilder ( path ) ; canonicalpath ( b ) ; return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert path to remove any leading / or drive letter assumes canonical . [CODESPLIT] static public String relpath ( String path ) { if ( path == null ) return null ; StringBuilder b = new StringBuilder ( path ) ; canonicalpath ( b ) ; if ( b . length ( ) > 0 ) { if ( b . charAt ( 0 ) == ' ' ) b . deleteCharAt ( 0 ) ; if ( hasDriveLetter ( b ) ) b . delete ( 0 , 2 ) ; } return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support function [CODESPLIT] static protected boolean hasDriveLetter ( StringBuilder path ) { return ( path . length ( ) >= 2 && path . charAt ( 1 ) == ' ' && DRIVELETTERS . indexOf ( path . charAt ( 0 ) ) >= 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert path to add a leading / ; assumes canonical . [CODESPLIT] static public String abspath ( String path ) { if ( path == null ) return \"/\" ; StringBuilder b = new StringBuilder ( path ) ; canonicalpath ( b ) ; if ( b . charAt ( 0 ) == ' ' ) b . deleteCharAt ( 0 ) ; if ( b . charAt ( 0 ) != ' ' || ! hasDriveLetter ( b ) ) b . insert ( 0 , ' ' ) ; return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accept datasets whose last modified date is at least the last modified limit of milliseconds in the past . [CODESPLIT] public boolean accept ( CrawlableDataset dataset ) { Date lastModDate = dataset . lastModified ( ) ; if ( lastModDate != null ) { long now = System . currentTimeMillis ( ) ; if ( now - lastModDate . getTime ( ) > lastModifiedLimitInMillis ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////// [CODESPLIT] static MFile makeIndexMFile ( String collectionName , File directory ) { String nameNoBlanks = StringUtil2 . replace ( collectionName , ' ' , \"_\" ) ; return new GcMFile ( directory , nameNoBlanks + GribCdmIndex . NCX_SUFFIX , - 1 , - 1 , - 1 ) ; // LOOK dont know lastMod, size. can it be added later? }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for making partition collection [CODESPLIT] void copyInfo ( GribCollectionMutable from ) { this . center = from . center ; this . subcenter = from . subcenter ; this . master = from . master ; this . local = from . local ; this . genProcessType = from . genProcessType ; this . genProcessId = from . genProcessId ; this . backProcessId = from . backProcessId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The files that comprise the collection . Actual paths including the grib cache if used . [CODESPLIT] public List < String > getFilenames ( ) { List < String > result = new ArrayList <> ( ) ; for ( MFile file : fileMap . values ( ) ) result . ( file . getPath ( ) ) ; Collections . sort ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public by accident do not use [CODESPLIT] void setIndexRaf ( RandomAccessFile indexRaf ) { this . indexRaf = indexRaf ; if ( indexRaf != null ) { this . indexFilename = indexRaf . getLocation ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get index filename [CODESPLIT] private String getIndexFilepathInCache ( ) { File indexFile = GribCdmIndex . makeIndexFile ( name , directory ) ; return GribIndexCache . getFileOrCache ( indexFile . getPath ( ) ) . getPath ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set from GribCollectionBuilderFromIndex . readFromIndex () [CODESPLIT] File setOrgDirectory ( String orgDirectory ) { this . orgDirectory = orgDirectory ; directory = new File ( orgDirectory ) ; if ( ! directory . exists ( ) ) { File indexFile = new File ( indexFilename ) ; File parent = indexFile . getParentFile ( ) ; if ( parent . exists ( ) ) directory = parent ; } return directory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stuff for FileCacheable [CODESPLIT] public void close ( ) throws java . io . IOException { if ( indexRaf != null ) { indexRaf . close ( ) ; indexRaf = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coverity [ CALL_SUPER ] [CODESPLIT] public void printXML ( PrintWriter pw , String pad , boolean constrained ) { Enumeration e = getAttributeNames ( ) ; Enumeration ve = getVariables ( ) ; boolean hasAttributes = e . hasMoreElements ( ) ; boolean hasVariables = ve . hasMoreElements ( ) ; pw . print ( pad + \"<\" + getTypeName ( ) ) ; if ( getEncodedName ( ) != null ) { pw . print ( \" name=\\\"\" + DDSXMLParser . normalizeToXML ( getClearName ( ) ) + \"\\\"\" ) ; } if ( hasAttributes || hasVariables ) { pw . println ( \">\" ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = getAttribute ( aName ) ; if ( a != null ) a . printXML ( pw , pad + \"\\t\" , constrained ) ; } while ( ve . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) ve . nextElement ( ) ; bt . printXML ( pw , pad + \"\\t\" , constrained ) ; } pw . println ( pad + \"</\" + getTypeName ( ) + \">\" ) ; } else { pw . println ( \"/>\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Number of nested fields [CODESPLIT] public int ncounters ( ) { if ( nested == null ) return 1 ; else { int ncounters = 0 ; for ( BitCounterCompressed [ ] counters : nested ) { if ( counters == null ) continue ; for ( BitCounterCompressed counter : counters ) if ( counter != null ) ncounters += counter . ncounters ( ) ; } return ncounters ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open an existing Netcdf file for writing data . Cannot add new objects you can only read / write data to existing Variables . Setting fill = false is more efficient use when you know you will write all data . [CODESPLIT] static public NetcdfFileWriteable openExisting ( String location , boolean fill ) throws IOException { return new NetcdfFileWriteable ( location , fill , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Netcdf file put it into define mode . Make calls to addXXX () then when all objects are added call create () . You cannot read or write data until create () is called . Setting fill = false is more efficient use when you know you will write all data . [CODESPLIT] static public NetcdfFileWriteable createNew ( String location , boolean fill ) throws IOException { return new NetcdfFileWriteable ( location , fill , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( String dimName , int length ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( length <= 0 ) throw new IllegalArgumentException ( \"dimension length must be > 0 :\" + length ) ; if ( ! N3iosp . isValidNetcdfObjectName ( dimName ) ) throw new IllegalArgumentException ( \"illegal netCDF-3 dimension name: \" + dimName ) ; Dimension dim = new Dimension ( dimName , length , true , false , false ) ; super . addDimension ( null , dim ) ; return dim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( String dimName , int length , boolean isShared , boolean isUnlimited , boolean isVariableLength ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( dimName ) ) throw new IllegalArgumentException ( \"illegal netCDF-3 dimension name \" + dimName ) ; Dimension dim = new Dimension ( dimName , length , isShared , isUnlimited , isVariableLength ) ; super . addDimension ( null , dim ) ; return dim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a Dimension . Must be in define mode . [CODESPLIT] public Dimension renameDimension ( String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; Dimension dim = findDimension ( oldName ) ; if ( null != dim ) dim . setName ( newName ) ; return dim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Global attribute to the file . Must be in define mode . [CODESPLIT] public Attribute addGlobalAttribute ( Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( att . getShortName ( ) ) ) { String attName = N3iosp . makeValidNetcdfObjectName ( att . getShortName ( ) ) ; log . warn ( \"illegal netCDF-3 attribute name= \" + att . getShortName ( ) + \" change to \" + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } return super . addAttribute ( null , att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Global attribute of type String to the file . Must be in define mode . [CODESPLIT] public Attribute addGlobalAttribute ( String name , String value ) { return addGlobalAttribute ( new Attribute ( name , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Global attribute of type Array to the file . Must be in define mode . [CODESPLIT] public Attribute addGlobalAttribute ( String name , Array values ) { return addGlobalAttribute ( new Attribute ( name , values ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a global Attribute . Must be in define mode . [CODESPLIT] public Attribute deleteGlobalAttribute ( String attName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; Attribute att = findGlobalAttribute ( attName ) ; if ( null == att ) return null ; rootGroup . remove ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a global Attribute . Must be in define mode . [CODESPLIT] public Attribute renameGlobalAttribute ( String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; Attribute att = findGlobalAttribute ( oldName ) ; if ( null == att ) return null ; rootGroup . remove ( att ) ; att = new Attribute ( newName , att . getValues ( ) ) ; rootGroup . addAttribute ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String varName , DataType dataType , Dimension [ ] dims ) { ArrayList < Dimension > list = new ArrayList < Dimension > ( ) ; list . addAll ( Arrays . asList ( dims ) ) ; return addVariable ( varName , dataType , list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String varName , DataType dataType , String dims ) { // parse the list ArrayList < Dimension > list = new ArrayList < Dimension > ( ) ; StringTokenizer stoker = new StringTokenizer ( dims ) ; while ( stoker . hasMoreTokens ( ) ) { String tok = stoker . nextToken ( ) ; Dimension d = rootGroup . findDimension ( tok ) ; if ( null == d ) throw new IllegalArgumentException ( \"Cant find dimension \" + tok ) ; list . add ( d ) ; } return addVariable ( varName , dataType , list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String shortName , DataType dataType , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( shortName ) ) throw new IllegalArgumentException ( \"illegal netCDF-3 variable name: \" + shortName ) ; if ( ! valid . contains ( dataType ) ) throw new IllegalArgumentException ( \"illegal dataType for netcdf-3 format: \" + dataType ) ; // check unlimited int count = 0 ; for ( Dimension d : dims ) { if ( d . isUnlimited ( ) ) if ( count != 0 ) throw new IllegalArgumentException ( \"Unlimited dimension \" + d + \" must be first instead its  =\" + count ) ; count ++ ; } Variable v = new Variable ( this , rootGroup , null , shortName ) ; v . setDataType ( dataType ) ; v . setDimensions ( dims ) ; long size = v . getSize ( ) * v . getElementSize ( ) ; if ( size > N3iosp . MAX_VARSIZE ) throw new IllegalArgumentException ( \"Variable size in bytes \" + size + \" may not exceed \" + N3iosp . MAX_VARSIZE ) ; super . addVariable ( null , v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable with DataType = String to the file . Must be in define mode . The variable will be stored in the file as a CHAR variable . A new dimension with name varName_strlen is automatically added with length max_strlen . [CODESPLIT] public Variable addStringVariable ( String varName , List < Dimension > dims , int max_strlen ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( varName ) ) throw new IllegalArgumentException ( \"illegal netCDF-3 variable name: \" + varName ) ; Variable v = new Variable ( this , rootGroup , null , varName ) ; v . setDataType ( DataType . CHAR ) ; Dimension d = addDimension ( varName + \"_strlen\" , max_strlen ) ; ArrayList < Dimension > sdims = new ArrayList < Dimension > ( dims ) ; sdims . add ( d ) ; v . setDimensions ( sdims ) ; super . addVariable ( null , v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a Variable . Must be in define mode . [CODESPLIT] public Variable renameVariable ( String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; Variable v = findVariable ( oldName ) ; if ( null != v ) v . setName ( newName ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an attribute to the named Variable . Must be in define mode . [CODESPLIT] public void addVariableAttribute ( String varName , Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( att . getShortName ( ) ) ) { String attName = N3iosp . makeValidNetcdfObjectName ( att . getShortName ( ) ) ; log . warn ( \"illegal netCDF-3 attribute name= \" + att . getShortName ( ) + \" change to \" + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } Variable v = rootGroup . findVariable ( varName ) ; if ( null == v ) throw new IllegalArgumentException ( \"addVariableAttribute variable name not found = <\" + varName + \">\" ) ; v . addAttribute ( att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an attribute of type String to the named Variable . Must be in define mode . [CODESPLIT] public void addVariableAttribute ( String varName , String attName , String value ) { addVariableAttribute ( varName , new Attribute ( attName , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an attribute of type Array to the named Variable . Must be in define mode . [CODESPLIT] public void addVariableAttribute ( String varName , String attName , Array value ) { Attribute att = new Attribute ( attName , value ) ; addVariableAttribute ( varName , att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a variable Attribute . Must be in define mode . [CODESPLIT] public Attribute deleteVariableAttribute ( String varName , String attName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; Variable v = findVariable ( varName ) ; if ( v == null ) return null ; Attribute att = v . findAttribute ( attName ) ; if ( null == att ) return null ; v . remove ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a variable Attribute . Must be in define mode . [CODESPLIT] public Attribute renameVariableAttribute ( String varName , String attName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; Variable v = findVariable ( varName ) ; if ( v == null ) return null ; Attribute att = v . findAttribute ( attName ) ; if ( null == att ) return null ; v . remove ( att ) ; att = new Attribute ( newName , att . getValues ( ) ) ; v . addAttribute ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the value of an existing attribute . Attribute is found by name which must match exactly . You cannot make an attribute longer or change the number of values . For strings : truncate if longer zero fill if shorter . Strings are padded to 4 byte boundaries ok to use padding if it exists . For numerics : must have same number of values . [CODESPLIT] public void updateAttribute ( ucar . nc2 . Variable v2 , Attribute att ) throws IOException { if ( defineMode ) throw new UnsupportedOperationException ( \"in define mode\" ) ; spiw . updateAttribute ( v2 , att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After you have added all of the Dimensions Variables and Attributes call create () to actually create the file . You must be in define mode . After this call you are no longer in define mode . [CODESPLIT] public void create ( ) throws java . io . IOException { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( cached_spiw == null ) { spi = SPFactory . getServiceProvider ( ) ; spiw = ( IOServiceProviderWriter ) spi ; } else { spiw = cached_spiw ; spi = spiw ; } spiw . setFill ( fill ) ; spiw . create ( location , this , extraHeader , preallocateSize , isLargeFile ) ; defineMode = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rewrite entire file [CODESPLIT] private void rewrite ( ) throws IOException { // close existing file, rename and open as read-only spiw . flush ( ) ; spiw . close ( ) ; File prevFile = new File ( location ) ; File tmpFile = new File ( location + \".tmp\" ) ; if ( tmpFile . exists ( ) ) tmpFile . delete ( ) ; if ( ! prevFile . renameTo ( tmpFile ) ) { System . out . printf ( \"%50s prevFile.exists=%s canRead=%s canWrite=%s%n\" , prevFile . getPath ( ) , prevFile . exists ( ) , prevFile . canRead ( ) , prevFile . canWrite ( ) ) ; System . out . printf ( \"%50s  tmpFile.exists=%s canRead=%s canWrite=%s%n\" , tmpFile . getPath ( ) , tmpFile . exists ( ) , tmpFile . canRead ( ) , tmpFile . canWrite ( ) ) ; throw new RuntimeException ( \"Cant rename \" + prevFile . getAbsolutePath ( ) + \" to \" + tmpFile . getAbsolutePath ( ) ) ; } NetcdfFile oldFile = NetcdfFile . open ( tmpFile . getPath ( ) ) ; // use record dimension if it has one Structure recordVar = null ; if ( oldFile . hasUnlimitedDimension ( ) ) { oldFile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; recordVar = ( Structure ) oldFile . findVariable ( \"record\" ) ; /* if (recordVar != null) {\n        Boolean result = (Boolean) spiw.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);\n        if (!result)\n          recordVar = null;\n      } */ } // create new file with current set of objects spiw . create ( location , this , extraHeader , preallocateSize , isLargeFile ) ; spiw . setFill ( fill ) ; //isClosed = false; // wait till header is written before adding the record variable to the file if ( recordVar != null ) { Boolean result = ( Boolean ) spiw . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ! result ) recordVar = null ; } // copy old file to new List < Variable > oldList = new ArrayList < Variable > ( getVariables ( ) . size ( ) ) ; for ( Variable v : getVariables ( ) ) { Variable oldVar = oldFile . findVariable ( v . getFullNameEscaped ( ) ) ; if ( oldVar != null ) oldList . add ( oldVar ) ; } FileWriter . copyVarData ( this , oldList , recordVar , null ) ; flush ( ) ; // delete old oldFile . close ( ) ; if ( ! tmpFile . delete ( ) ) throw new RuntimeException ( \"Cant delete \" + location ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write data to the named variable origin assumed to be 0 . Must not be in define mode . [CODESPLIT] public void write ( String fullNameEsc , Array values ) throws java . io . IOException , InvalidRangeException { write ( fullNameEsc , new int [ values . getRank ( ) ] , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write data to the named variable . Must not be in define mode . [CODESPLIT] public void write ( String fullNameEsc , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { if ( defineMode ) throw new UnsupportedOperationException ( \"in define mode\" ) ; ucar . nc2 . Variable v2 = findVariable ( fullNameEsc ) ; if ( v2 == null ) throw new IllegalArgumentException ( \"NetcdfFileWriteable.write illegal variable name = \" + fullNameEsc ) ; spiw . writeData ( v2 , new Section ( origin , values . getShape ( ) ) , values ) ; v2 . invalidateCache ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write String data to a CHAR variable origin assumed to be 0 . Must not be in define mode . [CODESPLIT] public void writeStringData ( String varName , Array values ) throws java . io . IOException , InvalidRangeException { writeStringData ( varName , new int [ values . getRank ( ) ] , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write String data to a CHAR variable . Must not be in define mode . [CODESPLIT] public void writeStringData ( String fullNameEsc , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { if ( values . getElementType ( ) != String . class ) throw new IllegalArgumentException ( \"Must be ArrayObject of String \" ) ; ucar . nc2 . Variable v2 = findVariable ( fullNameEsc ) ; if ( v2 == null ) throw new IllegalArgumentException ( \"illegal variable name = \" + fullNameEsc ) ; if ( v2 . getDataType ( ) != DataType . CHAR ) throw new IllegalArgumentException ( \"variable \" + fullNameEsc + \" is not type CHAR\" ) ; int rank = v2 . getRank ( ) ; int strlen = v2 . getShape ( rank - 1 ) ; // turn it into an ArrayChar ArrayChar cvalues = ArrayChar . makeFromStringArray ( ( ArrayObject ) values , strlen ) ; int [ ] corigin = new int [ rank ] ; System . arraycopy ( origin , 0 , corigin , 0 , rank - 1 ) ; write ( fullNameEsc , corigin , cvalues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "close the file . [CODESPLIT] @ Override public synchronized void close ( ) throws java . io . IOException { if ( spiw != null ) { flush ( ) ; spiw . close ( ) ; spiw = null ; } spi = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String varName , Class componentType , Dimension [ ] dims ) { List < Dimension > list = new ArrayList < Dimension > ( ) ; list . addAll ( Arrays . asList ( dims ) ) ; return addVariable ( varName , DataType . getType ( componentType , false ) , list ) ; // LOOK unsigned }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public static GempakSurfaceFileReader getInstance ( RandomAccessFile raf , boolean fullCheck ) throws IOException { GempakSurfaceFileReader gsfr = new GempakSurfaceFileReader ( ) ; gsfr . init ( raf , fullCheck ) ; return gsfr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { if ( ! super . init ( fullCheck ) ) { return false ; } // Modeled after SF_OFIL\r if ( dmLabel . kftype != MFSF ) { logError ( \"not a surface data file \" ) ; return false ; } int numParams = 0 ; String partType = ( ( dmLabel . kfsrce == 100 ) && ( dmLabel . kprt == 1 ) ) ? SFTX : SFDT ; DMPart part = getPart ( partType ) ; if ( part == null ) { logError ( \"No part named \" + partType + \" found\" ) ; return false ; } else { numParams = part . kparms ; } if ( ! readStationsAndTimes ( true ) ) { logError ( \"Unable to read stations and times\" ) ; return false ; } // since the reads are ob by ob, set buffer size small\r if ( subType . equals ( STANDARD ) ) rf . setBufferSize ( 256 ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the file subType . [CODESPLIT] protected void makeFileSubType ( ) { // determine file type\r Key key = findKey ( GempakStation . SLAT ) ; if ( key == null ) throw new IllegalStateException ( \"File does not have key=\" + GempakStation . SLAT ) ; String latType = key . type ; Key dateKey = findKey ( DATE ) ; if ( dateKey != null && ! dateKey . type . equals ( latType ) ) { if ( latType . equals ( ROW ) ) { subType = CLIMATE ; } else { subType = STANDARD ; } } else { subType = SHIP ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the list of dates in the file [CODESPLIT] public void printOb ( int row , int col ) { int stnIndex = ( getFileSubType ( ) . equals ( CLIMATE ) ) ? row : col ; List < GempakStation > stations = getStations ( ) ; if ( stations . isEmpty ( ) || stnIndex > stations . size ( ) ) { System . out . println ( \"\\nNo data available\" ) ; return ; } GempakStation station = getStations ( ) . get ( stnIndex - 1 ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( \"\\nStation:\\n\" ) ; builder . append ( station . toString ( ) ) ; builder . append ( \"\\nObs\\n\\t\" ) ; List < GempakParameter > params = getParameters ( SFDT ) ; for ( GempakParameter parm : params ) { builder . append ( StringUtil2 . padLeft ( parm . getName ( ) , 7 ) ) ; builder . append ( \"\\t\" ) ; } builder . append ( \"\\n\" ) ; RData rd ; try { rd = DM_RDTR ( row , col , SFDT ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; rd = null ; } if ( rd == null ) { builder . append ( \"No Data Available\" ) ; } else { builder . append ( \"\\t\" ) ; float [ ] data = rd . data ; for ( int i = 0 ; i < data . length ; i ++ ) { builder . append ( StringUtil2 . padLeft ( Format . formatDouble ( data [ i ] , 7 , 1 ) , 7 ) ) ; builder . append ( \"\\t\" ) ; } int [ ] header = rd . header ; if ( header . length > 0 ) { builder . append ( \"\\nOb Time = \" ) ; builder . append ( header [ 0 ] ) ; } } System . out . println ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the program [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length == 0 ) { System . out . println ( \"need to supply a GEMPAK surface file name\" ) ; System . exit ( 1 ) ; } try { GempakParameters . addParameters ( \"resources/nj22/tables/gempak/params.tbl\" ) ; } catch ( Exception e ) { System . out . println ( \"unable to init param tables\" ) ; } GempakSurfaceFileReader gsfr = getInstance ( getFile ( args [ 0 ] ) , true ) ; System . out . println ( \"Type = \" + gsfr . getSurfaceFileType ( ) ) ; gsfr . printFileLabel ( ) ; gsfr . printKeys ( ) ; gsfr . printHeaders ( ) ; gsfr . printParts ( ) ; //gsfr.printDates();\r //gsfr.printStations(false);\r int row = 1 ; int col = 1 ; if ( args . length > 1 ) { row = Integer . parseInt ( args [ 1 ] ) ; } if ( args . length > 2 ) { col = Integer . parseInt ( args [ 2 ] ) ; } gsfr . printOb ( row , col ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes headers and bounding box [CODESPLIT] private void writeHeadersAndBB ( ) { fileOutput += \"<wfs:FeatureCollection xsi:schemaLocation=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd \" + namespace + \" \" + server + \"?request=DescribeFeatureType\" + WFSXMLHelper . AMPERSAND + \"service=wfs\" + WFSXMLHelper . AMPERSAND + \"version=2.0.0\" + WFSXMLHelper . AMPERSAND + \"typename=\" + WFSController . TDSNAMESPACE + \"%3A\" + ftName ) + \" xmlns:xsi=\" + WFSXMLHelper . encQuotes ( \"http://www.w3.org/2001/XMLSchema-instance\" ) + \" xmlns:xlink=\" + WFSXMLHelper . encQuotes ( \"http://www.w3.org/1999/xlink\" ) + \" xmlns:gml=\" + WFSXMLHelper . encQuotes ( \"http://opengis.net/gml/3.2\" ) + \" xmlns:fes=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/fes/2.0\" ) + \" xmlns:ogc=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/ogc\" ) + \" xmlns:wfs=\" + WFSXMLHelper . encQuotes ( \"http://opengis.net/wfs/2.0\" ) + \" xmlns:\" + WFSController . TDSNAMESPACE + \"=\" + WFSXMLHelper . encQuotes ( namespace ) + \" xmlns=\" + WFSXMLHelper . encQuotes ( \"http://www.opengis.net/wfs/2.0\" ) + \" version=\\\"2.0.0\\\" numberMatched=\" + WFSXMLHelper . encQuotes ( String . valueOf ( geometries . size ( ) ) ) + \" numberReturned=\" + WFSXMLHelper . encQuotes ( String . valueOf ( geometries . size ( ) ) ) + \">\" ; double [ ] boundLower ; double [ ] boundUpper ; if ( geometries . isEmpty ( ) ) { boundLower = new double [ 2 ] ; boundUpper = new double [ 2 ] ; boundLower [ 0 ] = - 180 ; boundLower [ 1 ] = - 90 ; boundUpper [ 0 ] = 180 ; boundUpper [ 1 ] = 90 ; } else { boundLower = geometries . get ( 0 ) . getBBLower ( ) ; boundUpper = geometries . get ( 0 ) . getBBUpper ( ) ; } // WFS Bounding Box\r for ( SimpleGeometry item : geometries ) { // Find the overall BB\r // Test Lower\r double [ ] low = item . getBBLower ( ) ; if ( boundLower [ 0 ] > low [ 0 ] ) boundLower [ 0 ] = low [ 0 ] ; if ( boundLower [ 1 ] > low [ 1 ] ) boundLower [ 1 ] = low [ 1 ] ; // Test Upper\r double [ ] upper = item . getBBUpper ( ) ; if ( boundUpper [ 0 ] < upper [ 0 ] ) boundUpper [ 0 ] = upper [ 0 ] ; if ( boundUpper [ 1 ] < upper [ 1 ] ) boundUpper [ 1 ] = upper [ 1 ] ; // Add some padding\r boundLower [ 0 ] -= 10 ; boundLower [ 1 ] -= 10 ; boundUpper [ 0 ] += 10 ; boundUpper [ 1 ] += 10 ; } fileOutput += \"<wfs:boundedBy>\" + \"<wfs:Envelope srsName=\" + \"\\\"urn:ogc:def:crs:EPSG::4326\\\"\" + \">\" + \"<wfs:lowerCorner>\" + boundLower [ 0 ] + \" \" + boundLower [ 1 ] + \"</wfs:lowerCorner>\" + \"<wfs:upperCorner>\" + boundUpper [ 0 ] + \" \" + boundUpper [ 1 ] + \"</wfs:upperCorner>\" + \"</wfs:Envelope>\" + \"</wfs:boundedBy>\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In the WFS specification for GetFeature each feature type is its own member and so writeMembers add each member to the fileOutput [CODESPLIT] public void writeMembers ( ) { int index = 1 ; GMLFeatureWriter writer = new GMLFeatureWriter ( ) ; for ( SimpleGeometry geometryItem : geometries ) { // Find bounding box information\r double [ ] lowerCorner = geometryItem . getBBLower ( ) ; double [ ] upperCorner = geometryItem . getBBUpper ( ) ; fileOutput += \"<wfs:member>\" // Write Geometry Information\r + \"<\" + WFSController . TDSNAMESPACE + \":\" + ftName + \" gml:id=\\\"\" + ftName + \".\" + index + \"\\\">\" // GML Bounding Box\r + \"<gml:boundedBy>\" + \"<gml:Envelope srsName=\" + \"\\\"urn:ogc:def:crs:EPSG::4326\\\"\" + \">\" + \"<gml:lowerCorner>\" + lowerCorner [ 0 ] + \" \" + lowerCorner [ 1 ] + \"</gml:lowerCorner>\" + \"<gml:upperCorner>\" + upperCorner [ 0 ] + \" \" + upperCorner [ 1 ] + \"</gml:upperCorner>\" + \"</gml:Envelope>\" + \"</gml:boundedBy>\" + \"<\" + WFSController . TDSNAMESPACE + \":geometryInformation>\" ; //write GML features\r fileOutput += writer . writeFeature ( geometryItem ) ; // Cap off headers\r fileOutput += \"</\" + WFSController . TDSNAMESPACE + \":geometryInformation>\" + \"</\" + WFSController . TDSNAMESPACE + \":\" + ftName + \">\" + \"</wfs:member>\" ; index ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write stationObsDataset XML document [CODESPLIT] public String writeStationObsDatasetXML ( ) { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( makeStationObsDatasetDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write stationCollection XML document [CODESPLIT] public String writeStationCollectionXML ( ) throws IOException { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( makeStationCollectionDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XML document from this info [CODESPLIT] public Document makeStationCollectionDocument ( ) throws IOException { Element rootElem = new Element ( \"stationCollection\" ) ; Document doc = new Document ( rootElem ) ; List stns = sobs . getStations ( ) ; System . out . println ( \"nstns = \" + stns . size ( ) ) ; for ( int i = 0 ; i < stns . size ( ) ; i ++ ) { ucar . unidata . geoloc . Station s = ( ucar . unidata . geoloc . Station ) stns . get ( i ) ; Element sElem = new Element ( \"station\" ) ; sElem . setAttribute ( \"name\" , s . getName ( ) ) ; if ( s . getWmoId ( ) != null ) sElem . setAttribute ( \"wmo_id\" , s . getWmoId ( ) ) ; if ( s . getDescription ( ) != null ) sElem . addContent ( new Element ( \"description\" ) . addContent ( s . getDescription ( ) ) ) ; sElem . addContent ( new Element ( \"longitude\" ) . addContent ( ucar . unidata . util . Format . d ( s . getLongitude ( ) , 6 ) ) ) ; sElem . addContent ( new Element ( \"latitide\" ) . addContent ( ucar . unidata . util . Format . d ( s . getLatitude ( ) , 6 ) ) ) ; if ( ! Double . isNaN ( s . getAltitude ( ) ) ) sElem . addContent ( new Element ( \"altitude\" ) . addContent ( ucar . unidata . util . Format . d ( s . getAltitude ( ) , 6 ) ) ) ; rootElem . addContent ( sElem ) ; } return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XML document from this info [CODESPLIT] public Document makeStationObsDatasetDocument ( ) { Element rootElem = new Element ( \"stationObsDataset\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"location\" , sobs . getLocationURI ( ) ) ; if ( null != path ) rootElem . setAttribute ( \"path\" , path ) ; /* dimensions\n    List dims = getDimensions(sobs);\n    for (int j = 0; j < dims.size(); j++) {\n      Dimension dim = (Dimension) dims.get(j);\n      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeDimension(dim, null));\n    } */ /* coordinate axes\n    List coordAxes = getCoordAxes(sobs);\n    for (int i = 0; i < coordAxes.size(); i++) {\n      CoordinateAxis axis = (CoordinateAxis) coordAxes.get(i);\n      rootElem.addContent(writeAxis(axis));\n    } */ // grids List vars = sobs . getDataVariables ( ) ; Collections . sort ( vars ) ; for ( int i = 0 ; i < vars . size ( ) ; i ++ ) { VariableSimpleIF v = ( VariableSimpleIF ) vars . get ( i ) ; rootElem . addContent ( writeVariable ( v ) ) ; } /* global attributes\n    Iterator atts = sobs.getGlobalAttributes().iterator();\n    while (atts.hasNext()) {\n      ucar.nc2.Attribute att = (ucar.nc2.Attribute) atts.next();\n      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeAttribute(att, \"attribute\", null));\n    } */ // add lat/lon bounding box LatLonRect bb = sobs . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range Date start = sobs . getStartDate ( ) ; Date end = sobs . getEndDate ( ) ; if ( ( start != null ) && ( end != null ) ) { DateFormatter format = new DateFormatter ( ) ; Element dateRange = new Element ( \"TimeSpan\" ) ; dateRange . addContent ( new Element ( \"begin\" ) . addContent ( format . toDateTimeStringISO ( start ) ) ) ; dateRange . addContent ( new Element ( \"end\" ) . addContent ( format . toDateTimeStringISO ( end ) ) ) ; rootElem . addContent ( dateRange ) ; } // add accept list Element elem = new Element ( \"AcceptList\" ) ; elem . addContent ( new Element ( \"accept\" ) . addContent ( \"raw\" ) ) ; elem . addContent ( new Element ( \"accept\" ) . addContent ( \"xml\" ) ) ; elem . addContent ( new Element ( \"accept\" ) . addContent ( \"csv\" ) ) ; elem . addContent ( new Element ( \"accept\" ) . addContent ( \"netcdf\" ) ) ; elem . addContent ( new Element ( \"accept\" ) . addContent ( \"netcdfStream\" ) ) ; rootElem . addContent ( elem ) ; return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] public static void main ( String args [ ] ) throws IOException { String url = \"C:/data/metars/Surface_METAR_20060326_0000.nc\" ; StationObsDataset ncd = ( StationObsDataset ) TypedDatasetFactory . open ( FeatureType . STATION , url , null , new StringBuilder ( ) ) ; StationObsDatasetInfo info = new StationObsDatasetInfo ( ncd , null ) ; FileOutputStream fos2 = new FileOutputStream ( \"C:/TEMP/stationCollection.xml\" ) ; GZIPOutputStream zout = new GZIPOutputStream ( fos2 ) ; info . writeStationObsDatasetXML ( System . out ) ; info . writeStationCollectionXML ( zout ) ; zout . close ( ) ; File f = new File ( \"C:/TEMP/stationCollection.xml\" ) ; System . out . println ( \" size=\" + f . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the DSR ; do not bother to cache . [CODESPLIT] public void writeDSR ( String dsr ) throws IOException { if ( state != State . INITIAL ) throw new DapException ( \"Attempt to write DSR twice\" ) ; if ( dsr == null ) throw new DapException ( \"Attempt to write empty DSR\" ) ; // Strip off any trailing sequence of CR or LF. int len = dsr . length ( ) ; while ( len > 0 ) { char c = dsr . charAt ( len - 1 ) ; if ( c != ' ' && c != ' ' ) break ; len -- ; } if ( dsr . length ( ) == 0 ) throw new DapException ( \"Attempt to write empty DSR\" ) ; dsr = dsr . substring ( 0 , len ) + DapUtil . CRLF ; // Add <?xml...?> prefix dsr = XMLDOCUMENTHEADER + \"\\n\" + dsr ; // Convert the dsr to UTF-8 and then to byte[] byte [ ] dsr8 = DapUtil . extract ( DapUtil . UTF8 . encode ( dsr ) ) ; sendDXR ( dsr8 ) ; state = State . END ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cache the DMR . What it really does is cache the DMR and write it at the point where it is needed ; either in close () if writing the DMR only or in writeChunk () if writing data as well . [CODESPLIT] public void cacheDMR ( String dmr ) throws IOException { if ( state != State . INITIAL ) throw new DapException ( \"Attempt to write DMR twice\" ) ; if ( dmr == null ) throw new DapException ( \"Attempt to write empty DMR\" ) ; // Strip off any trailing sequence of CR or LF. int len = dmr . length ( ) ; while ( len > 0 ) { char c = dmr . charAt ( len - 1 ) ; if ( c != ' ' && c != ' ' ) break ; len -- ; } if ( dmr . length ( ) == 0 ) throw new DapException ( \"Attempt to write empty DMR\" ) ; dmr = dmr . substring ( 0 , len ) + DapUtil . CRLF ; // Prepend the <?xml...?> prefix dmr = XMLDOCUMENTHEADER + \"\\n\" + dmr ; // Convert the dmr to UTF-8 and then to byte[] this . dmr8 = DapUtil . extract ( DapUtil . UTF8 . encode ( dmr ) ) ; state = State . DMR ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Output the specifiedd DMR or DSR or ... but xml only . [CODESPLIT] void sendDXR ( byte [ ] dxr8 ) throws IOException { if ( dxr8 == null || dxr8 . length == 0 ) return ; // do nothing if ( mode == RequestMode . DMR || mode == RequestMode . DSR ) { state = State . END ; } else { //mode == DATA // Prefix with chunk header int flags = DapUtil . CHUNK_DATA ; if ( this . writeorder == ByteOrder . LITTLE_ENDIAN ) flags |= DapUtil . CHUNK_LITTLE_ENDIAN ; chunkheader ( dxr8 . length , flags , this . header ) ; // write the header output . write ( DapUtil . extract ( this . header ) ) ; state = State . DATA ; } // write the DXR output . write ( dxr8 ) ; output . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an error chunk . If mode == DMR then replaces the dmr else reset the current chunk thus losing any partial write . [CODESPLIT] public void writeError ( int httpcode , String msg , String cxt , String other ) throws IOException { dmr8 = null ; ErrorResponse response = new ErrorResponse ( httpcode , msg , cxt , other ) ; String errorbody = response . buildXML ( ) ; // Convert the error body into utf8 then to byte[] byte [ ] errbody8 = DapUtil . extract ( DapUtil . UTF8 . encode ( errorbody ) ) ; if ( mode == RequestMode . DMR ) { sendDXR ( errbody8 ) ; } else { //mode == DATA // clear any partial chunk chunk . clear ( ) ; // create an error header int flags = DapUtil . CHUNK_ERROR | DapUtil . CHUNK_END ; chunkheader ( errbody8 . length , flags , header ) ; output . write ( DapUtil . extract ( header ) ) ; output . write ( errbody8 ) ; output . flush ( ) ; } state = State . ERROR ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out the current chunk ( with given set of flags ) . [CODESPLIT] void writeChunk ( int flags ) throws IOException { // If flags indicate CHUNK_END // and amount to write is zero, // go ahead and write the zero size chunk. if ( chunk == null ) chunk = ByteBuffer . allocate ( maxbuffersize ) ; int buffersize = chunk . position ( ) ; chunkheader ( buffersize , flags , header ) ; // output the header followed by the data (if any) // Zero size chunk is ok. output . write ( DapUtil . extract ( header ) ) ; if ( buffersize > 0 ) output . write ( chunk . array ( ) , 0 , buffersize ) ; chunk . clear ( ) ; // reset }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes this output stream and releases any system resources associated with this stream . Except the underlying stream is not actually closed ; that is left to the servlet level [CODESPLIT] public void close ( ) throws IOException { if ( closed ) return ; closed = true ; if ( dmr8 != null ) { sendDXR ( dmr8 ) ; dmr8 = null ; } if ( mode == RequestMode . DMR ) return ; // only DMR should be sent // If there is no partial chunk to write then // we are done; else verify we can write and write the last // chunk; => multiple closes are ok. if ( chunk == null || chunk . position ( ) == 0 ) return ; // There is data left to write. verifystate ( ) ; // are we in a state supporting data write? // Force out the current chunk (might be empty) // but do not close the underlying output stream state = State . DATA ; // pretend int flags = DapUtil . CHUNK_END ; writeChunk ( flags ) ; state = State . END ; this . output . flush ( ) ; // Do not close if ( this . saveoutput != null ) { // write to true output target this . saveoutput . write ( ( ( ByteArrayOutputStream ) this . output ) . toByteArray ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overload flush to also write out the DMR [CODESPLIT] @ Override public void flush ( ) throws IOException { if ( mode == RequestMode . DMR ) return ; // leave to close() to do this if ( dmr8 != null ) { sendDXR ( dmr8 ) ; dmr8 = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes len bytes from the specified byte array starting at offset off to this output stream . <p > If this write fills up the chunk buffer then write out the buffer and put the remaining bytes into the reset buffer . [CODESPLIT] @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { verifystate ( ) ; if ( writecount + len >= writelimit ) throw new DapException ( \"Attempt to write too much data: limit=\" + writecount + len ) . setCode ( DapCodes . SC_REQUESTED_RANGE_NOT_SATISFIABLE ) ; if ( chunk == null ) chunk = ByteBuffer . allocate ( maxbuffersize ) . order ( getWriteOrder ( ) ) ; if ( state == State . DMR ) { chunk . clear ( ) ; // reset state = State . DATA ; } assert ( state == State . DATA ) ; if ( b . length < off + len ) throw new BufferUnderflowException ( ) ; int left = len ; int offset = off ; while ( left > 0 ) { int avail = chunk . remaining ( ) ; do { if ( avail == 0 ) { writeChunk ( DapUtil . CHUNK_DATA ) ; avail = chunk . remaining ( ) ; } int towrite = ( left < avail ? left : avail ) ; chunk . put ( b , off , towrite ) ; left -= towrite ; avail -= towrite ; } while ( left > 0 ) ; } writecount += len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "needed for constructCopy [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = ( saveParams == null ) ? new UtmProjection ( getZone ( ) , isNorth ( ) ) : new UtmProjection ( saveParams . a , saveParams . f , getZone ( ) , isNorth ( ) ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; return convert2xy . latLonToProj ( fromLat , fromLon , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { return convert2latlon . projToLatLon ( world . getX ( ) , world . getY ( ) , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * roszelld@usgs . gov m transforming coordinates ( which are in UTM Zone 17N projection ) to lat / lon . [CODESPLIT] public static void main ( String arg [ ] ) { UtmProjection utm = new UtmProjection ( 17 , true ) ; LatLonPoint ll = utm . projToLatLon ( 577.8000000000001 , 2951.8 ) ; System . out . printf ( \"%15.12f %15.12f%n\" , ll . getLatitude ( ) , ll . getLongitude ( ) ) ; assert Misc . nearlyEquals ( ll . getLongitude ( ) , - 80.21802662821469 , 1.0e-8 ) ; assert Misc . nearlyEquals ( ll . getLatitude ( ) , 26.685132668190793 , 1.0e-8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "got to use this or subclass readObservations () [CODESPLIT] public void addObs ( StationObsDatatype sobs ) { if ( null == obsList ) obsList = new ArrayList < StationObsDatatype > ( ) ; obsList . add ( sobs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look at config and decide if tasks need to be started [CODESPLIT] public void scheduleTasks ( FeatureCollectionConfig config , Logger logger ) { if ( disabled || failed ) return ; if ( logger == null ) logger = fcLogger ; FeatureCollectionConfig . UpdateConfig updateConfig = ( isTdm ) ? config . tdmConfig : config . updateConfig ; if ( updateConfig == null || updateConfig . updateType == CollectionUpdateType . never ) return ; String collectionName = config . getCollectionName ( ) ; // prob dont need to set a job if theres no chron job ? // Job to update the collection org . quartz . JobDataMap map = new org . quartz . JobDataMap ( ) ; map . put ( EVENT_BUS , eventBus ) ; map . put ( COLLECTION_NAME , collectionName ) ; map . put ( LOGGER , logger ) ; JobDetail updateJob = JobBuilder . newJob ( UpdateCollectionJob . class ) . withIdentity ( collectionName , \"UpdateCollection\" ) . storeDurably ( ) . usingJobData ( map ) . build ( ) ; try { if ( ! scheduler . checkExists ( updateJob . getKey ( ) ) ) { scheduler . addJob ( updateJob , false ) ; } else { logger . warn ( \"scheduler failed to add updateJob for \" + updateJob . getKey ( ) + \". Another Job exists with that identification.\" ) ; } } catch ( Throwable e ) { logger . error ( \"scheduler failed to add updateJob for \" + config , e ) ; return ; } // task to run the job on startup if ( updateConfig . startupType != CollectionUpdateType . never ) { map = new org . quartz . JobDataMap ( ) ; map . put ( UpdateType , updateConfig . startupType ) ; map . put ( Source , \"startup\" ) ; Date runTime = new Date ( new Date ( ) . getTime ( ) + startupWait ) ; // wait startupWait before trigger SimpleTrigger startupTrigger = ( SimpleTrigger ) TriggerBuilder . newTrigger ( ) . withIdentity ( collectionName , \"startup\" ) . startAt ( runTime ) . forJob ( updateJob ) . usingJobData ( map ) . build ( ) ; try { scheduler . scheduleJob ( startupTrigger ) ; logger . info ( \"scheduleJob startup scan force={} for '{}' at {}\" , updateConfig . startupType . toString ( ) , config . collectionName , runTime ) ; } catch ( Throwable e ) { logger . error ( \"scheduleJob failed to schedule startup Job for \" + config , e ) ; return ; } } // task to run the job periodically, with rescan if ( updateConfig . rescan != null ) { map = new org . quartz . JobDataMap ( ) ; map . put ( UpdateType , updateConfig . updateType ) ; map . put ( Source , \"rescan\" ) ; CronTrigger rescanTrigger = TriggerBuilder . newTrigger ( ) . withIdentity ( collectionName , \"rescan\" ) . withSchedule ( CronScheduleBuilder . cronSchedule ( updateConfig . rescan ) ) . forJob ( updateJob ) . usingJobData ( map ) . build ( ) ; try { scheduler . scheduleJob ( rescanTrigger ) ; logger . info ( \"scheduleJob recurring scan for '{}' cronExpr={}\" , config . collectionName , updateConfig . rescan ) ; } catch ( Throwable e ) { logger . error ( \"scheduleJob failed to schedule cron Job\" , e ) ; // e.printStackTrace(); } } /* updating the proto dataset\n    FeatureCollectionConfig.ProtoConfig pconfig = config.protoConfig;\n    if (pconfig.change != null) {\n      org.quartz.JobDataMap pmap = new org.quartz.JobDataMap();\n      pmap.put(DCM_NAME, manager);\n      map.put(LOGGER, logger);\n      JobDetail protoJob = JobBuilder.newJob(ChangeProtoJob.class)\n              .withIdentity(jobName, \"UpdateProto\")\n              .usingJobData(pmap)\n              .storeDurably()\n              .build();\n\n      try {\n        CronTrigger protoTrigger = TriggerBuilder.newTrigger()\n                .withIdentity(jobName, \"rereadProto\")\n                .withSchedule(CronScheduleBuilder.cronSchedule(pconfig.change))\n                .build();\n        scheduler.scheduleJob(protoJob, protoTrigger);\n        if (logger != null)logger.info(\"Schedule proto update for '{}' cronExpr={}\", config.collectionName, pconfig.change);\n\n      } catch (Throwable e) {\n        if (logger != null)logger.error(\"cronExecutor failed to schedule RereadProtoJob\", e);\n        // e.printStackTrace();\n      }\n    } */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is want contained in this Range? [CODESPLIT] public boolean contains ( int want ) { if ( want < first ( ) ) return false ; if ( want > last ( ) ) return false ; if ( stride == 1 ) return true ; return ( want - first ) % stride == 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Range by composing a Range that is reletive to this Range . Revised 2013 / 04 / 19 by Dennis Heimbigner to handle edge cases . See the commentary associated with the netcdf - c file dceconstraints . h function dceslicecompose () . [CODESPLIT] public Range compose ( Range r ) throws InvalidRangeException { if ( ( length ( ) == 0 ) || ( r . length ( ) == 0 ) ) return EMPTY ; if ( this == VLEN || r == VLEN ) return VLEN ; /* if(false) {// Original version\n    // Note that this version assumes that range r is\n    // correct with respect to this.\n    int first = element(r.first());\n    int stride = stride() * r.stride();\n    int last = element(r.last());\n    return new Range(name, first, last, stride);\n} else {//new version: handles versions all values of r. */ int sr_stride = this . stride * r . stride ; int sr_first = element ( r . first ( ) ) ; // MAP(this,i) == element(i) int lastx = element ( r . last ( ) ) ; int sr_last = ( last ( ) < lastx ? last ( ) : lastx ) ; //min(last(),lastx) //unused int sr_length = (sr_last + 1) - sr_first; return new Range ( name , sr_first , sr_last , sr_stride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Range by compacting this Range by removing the stride . first = first / stride last = last / stride stride = 1 . [CODESPLIT] public Range compact ( ) throws InvalidRangeException { if ( stride == 1 ) return this ; int first = first ( ) / stride ; // LOOK WTF ? int last = first + length ( ) - 1 ; return new Range ( name , first , last , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get ith element [CODESPLIT] public int element ( int i ) throws InvalidRangeException { if ( i < 0 ) throw new InvalidRangeException ( \"i must be >= 0\" ) ; if ( i >= length ) throw new InvalidRangeException ( \"i must be < length\" ) ; return first + i * stride ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the index for this element : inverse of element [CODESPLIT] public int index ( int want ) throws InvalidRangeException { if ( want < first ) throw new InvalidRangeException ( \"elem must be >= first\" ) ; int result = ( want - first ) / stride ; if ( result > length ) throw new InvalidRangeException ( \"elem must be <= first = n * stride\" ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Range by intersecting with a Range using same interval as this Range . NOTE : we dont yet support intersection when both Ranges have strides [CODESPLIT] public Range intersect ( Range r ) throws InvalidRangeException { if ( ( length ( ) == 0 ) || ( r . length ( ) == 0 ) ) return EMPTY ; if ( this == VLEN || r == VLEN ) return VLEN ; int last = Math . min ( this . last ( ) , r . last ( ) ) ; int resultStride = stride * r . stride ( ) ; int useFirst ; if ( resultStride == 1 ) { // both strides are 1 useFirst = Math . max ( this . first ( ) , r . first ( ) ) ; } else if ( stride == 1 ) { // then r has a stride if ( r . first ( ) >= first ( ) ) useFirst = r . first ( ) ; else { int incr = ( first ( ) - r . first ( ) ) / resultStride ; useFirst = r . first ( ) + incr * resultStride ; if ( useFirst < first ( ) ) useFirst += resultStride ; } } else if ( r . stride == 1 ) { // then this has a stride if ( first ( ) >= r . first ( ) ) useFirst = first ( ) ; else { int incr = ( r . first ( ) - first ( ) ) / resultStride ; useFirst = first ( ) + incr * resultStride ; if ( useFirst < r . first ( ) ) useFirst += resultStride ; } } else { throw new UnsupportedOperationException ( \"Intersection when both ranges have a stride\" ) ; } if ( useFirst > last ) return EMPTY ; return new Range ( name , useFirst , last , resultStride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a given Range intersects this one . NOTE : we dont yet support intersection when both Ranges have strides [CODESPLIT] public boolean intersects ( Range r ) { if ( ( length ( ) == 0 ) || ( r . length ( ) == 0 ) ) return false ; if ( this == VLEN || r == VLEN ) return true ; int last = Math . min ( this . last ( ) , r . last ( ) ) ; int resultStride = stride * r . stride ( ) ; int useFirst ; if ( resultStride == 1 ) { // both strides are 1 useFirst = Math . max ( this . first ( ) , r . first ( ) ) ; } else if ( stride == 1 ) { // then r has a stride if ( r . first ( ) >= first ( ) ) useFirst = r . first ( ) ; else { int incr = ( first ( ) - r . first ( ) ) / resultStride ; useFirst = r . first ( ) + incr * resultStride ; if ( useFirst < first ( ) ) useFirst += resultStride ; } } else if ( r . stride ( ) == 1 ) { // then this has a stride if ( first ( ) >= r . first ( ) ) useFirst = first ( ) ; else { int incr = ( r . first ( ) - first ( ) ) / resultStride ; useFirst = first ( ) + incr * resultStride ; if ( useFirst < r . first ( ) ) useFirst += resultStride ; } } else { throw new UnsupportedOperationException ( \"Intersection when both ranges have a stride\" ) ; } return ( useFirst <= last ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Range shifting this range by a constant factor . [CODESPLIT] public Range shiftOrigin ( int origin ) throws InvalidRangeException { if ( this == VLEN ) return VLEN ; int first = first ( ) - origin ; int last = last ( ) - origin ; return new Range ( name , first , last , stride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Range by making the union with a Range using same interval as this Range . NOTE : no strides [CODESPLIT] public Range union ( Range r ) throws InvalidRangeException { if ( length ( ) == 0 ) return r ; if ( this == VLEN || r == VLEN ) return VLEN ; if ( r . length ( ) == 0 ) return this ; int first = Math . min ( this . first ( ) , r . first ( ) ) ; int last = Math . max ( this . last ( ) , r . last ( ) ) ; return new Range ( name , first , last ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the first element in a strided array after some index start . Return the smallest element k in the Range such that <ul > <li > k > = first <li > k > = start <li > k < = last <li > k = element of this Range < / ul > [CODESPLIT] public int getFirstInInterval ( int start ) { if ( start > last ( ) ) return - 1 ; if ( start <= first ) return first ; if ( stride == 1 ) return start ; int offset = start - first ; int i = offset / stride ; i = ( offset % stride == 0 ) ? i : i + 1 ; // round up return first + i * stride ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private . use Array . factory () [CODESPLIT] static ArrayLong factory ( Index index , boolean isUnsigned ) { return ArrayLong . factory ( index , isUnsigned , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { long [ ] ja = ( long [ ] ) javaArray ; for ( long aJa : ja ) iter . setLongNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from file for a variable create primitive array . [CODESPLIT] protected Object readData ( Layout index , DataType dataType ) throws java . io . IOException { return IospHelper . readDataFill ( raf , index , dataType , null , - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data subset from file for a variable to WritableByteChannel . Will send as bigendian since thats what the underlying file has . [CODESPLIT] protected long readData ( Layout index , DataType dataType , WritableByteChannel out ) throws java . io . IOException { long count = 0 ; if ( dataType . getPrimitiveClassType ( ) == byte . class || dataType == DataType . CHAR ) { while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; count += raf . readToByteChannel ( out , chunk . getSrcPos ( ) , chunk . getNelems ( ) ) ; } } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; count += raf . readToByteChannel ( out , chunk . getSrcPos ( ) , 2 * chunk . getNelems ( ) ) ; } } else if ( dataType . getPrimitiveClassType ( ) == int . class || ( dataType == DataType . FLOAT ) ) { while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; count += raf . readToByteChannel ( out , chunk . getSrcPos ( ) , 4 * chunk . getNelems ( ) ) ; } } else if ( ( dataType == DataType . DOUBLE ) || dataType . getPrimitiveClassType ( ) == long . class ) { while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; count += raf . readToByteChannel ( out , chunk . getSrcPos ( ) , 8 * chunk . getNelems ( ) ) ; } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write data to a file for a variable . [CODESPLIT] protected void writeData ( Array values , Layout index , DataType dataType ) throws java . io . IOException { if ( ( dataType == DataType . BYTE ) || ( dataType == DataType . CHAR ) ) { IndexIterator ii = values . getIndexIterator ( ) ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . seek ( chunk . getSrcPos ( ) ) ; for ( int k = 0 ; k < chunk . getNelems ( ) ; k ++ ) raf . write ( ii . getByteNext ( ) ) ; } return ; } else if ( dataType == DataType . STRING ) { // LOOK not legal IndexIterator ii = values . getIndexIterator ( ) ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . seek ( chunk . getSrcPos ( ) ) ; for ( int k = 0 ; k < chunk . getNelems ( ) ; k ++ ) { String val = ( String ) ii . getObjectNext ( ) ; if ( val != null ) raf . write ( val . getBytes ( CDM . utf8Charset ) ) ; // LOOK ?? } } return ; } else if ( dataType == DataType . SHORT ) { IndexIterator ii = values . getIndexIterator ( ) ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . seek ( chunk . getSrcPos ( ) ) ; for ( int k = 0 ; k < chunk . getNelems ( ) ; k ++ ) raf . writeShort ( ii . getShortNext ( ) ) ; } return ; } else if ( dataType == DataType . INT ) { IndexIterator ii = values . getIndexIterator ( ) ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . seek ( chunk . getSrcPos ( ) ) ; for ( int k = 0 ; k < chunk . getNelems ( ) ; k ++ ) raf . writeInt ( ii . getIntNext ( ) ) ; } return ; } else if ( dataType == DataType . FLOAT ) { IndexIterator ii = values . getIndexIterator ( ) ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . seek ( chunk . getSrcPos ( ) ) ; for ( int k = 0 ; k < chunk . getNelems ( ) ; k ++ ) raf . writeFloat ( ii . getFloatNext ( ) ) ; } return ; } else if ( dataType == DataType . DOUBLE ) { IndexIterator ii = values . getIndexIterator ( ) ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . seek ( chunk . getSrcPos ( ) ) ; for ( int k = 0 ; k < chunk . getNelems ( ) ; k ++ ) raf . writeDouble ( ii . getDoubleNext ( ) ) ; } return ; } throw new IllegalStateException ( \"dataType= \" + dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <! -- C : / data / dt2 / station / madis2 . sao -- > <stationCollection > <table dim = maxStaticIds limit = nStaticIds > <lastLink > lastRecord< / lastLink > [CODESPLIT] public TableConfig getConfig ( FeatureType wantFeatureType , NetcdfDataset ds , Formatter errlog ) { Dimension obsDim = Evaluator . getDimension ( ds , \"recNum\" , errlog ) ; if ( obsDim == null ) { errlog . format ( \"MADIS: must have an Observation dimension: named recNum\" ) ; return null ; } VNames vn = getVariableNames ( ds , errlog ) ; String levVarName = null ; String levDimName = null ; boolean hasStruct = Evaluator . hasNetcdf3RecordStructure ( ds ) ; FeatureType ft = Evaluator . getFeatureType ( ds , \":thredds_data_type\" , errlog ) ; if ( null == ft ) { if ( ( ds . findDimension ( \"manLevel\" ) != null ) && ( ds . findVariable ( \"prMan\" ) != null ) ) { ft = FeatureType . STATION_PROFILE ; levVarName = \"prMan\" ; levDimName = \"manLevel\" ; } else if ( ( ds . findDimension ( \"level\" ) != null ) && ( ds . findVariable ( \"levels\" ) != null ) ) { ft = FeatureType . STATION_PROFILE ; levVarName = \"levels\" ; levDimName = \"level\" ; } } if ( null == ft ) ft = FeatureType . POINT ; // points if ( ( wantFeatureType == FeatureType . POINT ) || ( ft == FeatureType . POINT ) ) { TableConfig ptTable = new TableConfig ( Table . Type . Structure , hasStruct ? \"record\" : obsDim . getShortName ( ) ) ; ptTable . structName = \"record\" ; ptTable . featureType = FeatureType . POINT ; ptTable . structureType = hasStruct ? TableConfig . StructureType . Structure : TableConfig . StructureType . PsuedoStructure ; ptTable . dimName = obsDim . getShortName ( ) ; ptTable . time = vn . obsTime ; ptTable . timeNominal = vn . nominalTime ; ptTable . lat = vn . lat ; ptTable . lon = vn . lon ; ptTable . elev = vn . elev ; return ptTable ; } if ( ft == FeatureType . STATION ) { TableConfig stnTable = new TableConfig ( Table . Type . Construct , \"station\" ) ; stnTable . featureType = FeatureType . STATION ; TableConfig obs = new TableConfig ( Table . Type . ParentId , \"record\" ) ; obs . parentIndex = vn . stnId ; obs . dimName = Evaluator . getDimensionName ( ds , \"recNum\" , errlog ) ; obs . time = vn . obsTime ; obs . timeNominal = vn . nominalTime ; obs . stnId = vn . stnId ; obs . stnDesc = vn . stnDesc ; obs . lat = vn . lat ; obs . lon = vn . lon ; obs . elev = vn . elev ; stnTable . addChild ( obs ) ; return stnTable ; } else if ( ft == FeatureType . STATION_PROFILE ) { TableConfig stnTable = new TableConfig ( Table . Type . Construct , \"station\" ) ; stnTable . featureType = FeatureType . STATION_PROFILE ; TableConfig obs = new TableConfig ( Table . Type . ParentId , \"record\" ) ; obs . parentIndex = vn . stnId ; obs . dimName = Evaluator . getDimensionName ( ds , \"recNum\" , errlog ) ; obs . time = vn . obsTime ; obs . timeNominal = vn . nominalTime ; obs . stnId = vn . stnId ; obs . stnDesc = vn . stnDesc ; obs . lat = vn . lat ; obs . lon = vn . lon ; obs . stnAlt = vn . elev ; stnTable . addChild ( obs ) ; TableConfig lev = new TableConfig ( Table . Type . MultidimInner , \"mandatory\" ) ; lev . elev = levVarName ; lev . outerName = obs . dimName ; lev . innerName = levDimName ; obs . addChild ( lev ) ; return stnTable ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data values ( parameters are ignored ) . Use the start stop and stride values that were set by the constraint evaluator . [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws IOException { boolean hasStride = false ; Array a ; try { if ( debugRead ) { System . out . println ( \"NcSDCharArray read \" + ncVar . getFullName ( ) ) ; for ( int i = 0 ; i < numDimensions ( ) ; i ++ ) { DArrayDimension d = getDimension ( i ) ; System . out . println ( \" \" + d . getEncodedName ( ) + \" \" + getStart ( i ) + \" \" + getStop ( i ) + \" \" + getStride ( i ) ) ; } } // set up the netcdf read int n = numDimensions ( ) ; int [ ] origin = new int [ n + 1 ] ; int [ ] shape = new int [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { origin [ i ] = getStart ( i ) ; shape [ i ] = getStop ( i ) - getStart ( i ) + 1 ; hasStride = hasStride || ( getStride ( i ) > 1 ) ; } origin [ n ] = 0 ; shape [ n ] = strLen ; a = ncVar . read ( origin , shape ) ; if ( debugRead ) System . out . println ( \"  Read = \" + a . getSize ( ) + \" elems of type = \" + a . getElementType ( ) ) ; // deal with strides using a section if ( hasStride ) { List < Range > ranges = new ArrayList <> ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int s = getStride ( i ) ; if ( s > 1 ) { // otherwise null, means \"take all elements\" ranges . add ( new Range ( 0 , shape [ i ] , s ) ) ; if ( debugRead ) System . out . println ( \" Section dim \" + i + \" stride = \" + s ) ; } } ranges . add ( null ) ; //  get all a = a . section ( ranges ) ; if ( debugRead ) System . out . println ( \"   section size \" + a . getSize ( ) ) ; } } catch ( InvalidDimensionException e ) { log . error ( \"read char array\" , e ) ; throw new IllegalStateException ( \"NcSDCharArray InvalidDimensionException\" ) ; } catch ( InvalidRangeException e ) { log . error ( \"read char array\" , e ) ; throw new IllegalStateException ( \"NcSDCharArray InvalidRangeException\" ) ; } setData ( a ) ; return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then resave it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { for ( int i = 0 ; i < vals . length ; i ++ ) { sink . writeBoolean ( vals [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a subset of the data to a <code > DataOutputStream< / code > . [CODESPLIT] public void externalize ( DataOutputStream sink , int start , int stop , int stride ) throws IOException { for ( int i = start ; i <= stop ; i += stride ) sink . writeBoolean ( vals [ i ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new primitive vector using a subset of the data . [CODESPLIT] public PrimitiveVector subset ( int start , int stop , int stride ) { BooleanPrimitiveVector n = new BooleanPrimitiveVector ( getTemplate ( ) ) ; stride = Math . max ( stride , 1 ) ; stop = Math . max ( start , stop ) ; int length = 1 + ( stop - start ) / stride ; n . setLength ( length ) ; int count = 0 ; for ( int i = start ; i <= stop ; i += stride ) { n . setValue ( count , vals [ i ] ) ; count ++ ; } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > BooleanPrimitiveVector< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { BooleanPrimitiveVector v = ( BooleanPrimitiveVector ) super . cloneDAG ( map ) ; if ( vals != null ) { v . vals = new boolean [ vals . length ] ; System . arraycopy ( vals , 0 , v . vals , 0 , vals . length ) ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * type info codes from hntdefs . h #define DFNT_UCHAR8 3 #define DFNT_CHAR8 4 #define DFNT_FLOAT32 5 #define DFNT_FLOAT64 6 [CODESPLIT] static DataType setDataType ( short type , Variable v ) { DataType dt ; switch ( type ) { case 3 : dt = DataType . UBYTE ; break ; case 4 : dt = DataType . CHAR ; break ; case 5 : dt = DataType . FLOAT ; break ; case 6 : dt = DataType . DOUBLE ; break ; case 20 : dt = DataType . BYTE ; break ; case 21 : dt = DataType . UBYTE ; break ; case 22 : dt = DataType . SHORT ; break ; case 23 : dt = DataType . USHORT ; break ; case 24 : dt = DataType . INT ; break ; case 25 : dt = DataType . UINT ; break ; case 26 : dt = DataType . LONG ; break ; case 27 : dt = DataType . ULONG ; break ; default : throw new IllegalStateException ( \"unknown type= \" + type ) ; } if ( v != null ) { v . setDataType ( dt ) ; } return dt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return sorted catalogs [CODESPLIT] public Iterable < ? extends CatalogExt > getCatalogs ( ) { if ( catalogs == null ) readCatalogs ( ) ; List < CatalogExt > result = new ArrayList <> ( ) ; for ( CatalogExt ext : catalogs . values ( ) ) result . ( ext ) ; Collections . sort ( result , ( o1 , o2 ) -> o1 . getCatRelLocation ( ) . compareTo ( o2 . getCatRelLocation ( ) ) ) ; // java 8 lambda, baby return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accessors [CODESPLIT] @ Override public void addEntry ( String urlpath , String fileprefix ) throws DapException { // Canonicalize the urlpath String urlprefix = DapUtil . canonicalpath ( urlpath ) ; // Canonicalize the file path fileprefix = DapUtil . canonicalpath ( fileprefix ) ; url2path . put ( urlprefix , fileprefix ) ; // overwrite path2url . put ( fileprefix , urlprefix ) ; // overwrite }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "File loader [CODESPLIT] public void load ( String filepath ) throws IOException { String [ ] lines ; try ( InputStream is = new FileInputStream ( filepath ) ; ) { String content = DapUtil . readtextfile ( is ) ; lines = content . split ( \"[\\n]\" ) ; } for ( String line : lines ) { String [ ] pieces = line . split ( \"[=]\" ) ; if ( pieces . length != 2 ) throw new IOException ( \"File: \" + filepath + \"; malformed line: \" + line ) ; addEntry ( pieces [ 0 ] , pieces [ 1 ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "URLMap API [CODESPLIT] @ Override public Result mapURL ( String urlpath ) throws DapException { // Canonicalize the urlpath urlpath = DapUtil . canonicalpath ( urlpath ) ; Result result = longestmatch ( url2path , urlpath ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "delete old databases [CODESPLIT] public static void cleanupBefore ( String pathname , long trackerNumber ) { for ( long tnum = trackerNumber - 1 ; tnum > 0 ; tnum -- ) { File oldDatabaseFile = new File ( pathname + datasetName + \".\" + tnum ) ; if ( ! oldDatabaseFile . exists ( ) ) break ; if ( oldDatabaseFile . delete ( ) ) { catalogInitLog . info ( \"DatasetTrackerChronicle deleted {} \" , oldDatabaseFile . getAbsolutePath ( ) ) ; } else { catalogInitLog . error ( \"DatasetTrackerChronicle not able to delete {} \" , oldDatabaseFile . getAbsolutePath ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the grid nav block values [CODESPLIT] public void setValues ( float [ ] values ) { vals = values ; proj = GempakUtil . ST_ITOC ( Float . floatToIntBits ( vals [ 1 ] ) ) . trim ( ) ; addParam ( PROJ , proj ) ; addParam ( GDS_KEY , this . toString ( ) ) ; setParams ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the parameters for the GDS . TODO Add the following : The following simple map projections may be specified : [CODESPLIT] private void setParams ( ) { String angle1 = String . valueOf ( vals [ 10 ] ) ; String angle2 = String . valueOf ( vals [ 11 ] ) ; String angle3 = String . valueOf ( vals [ 12 ] ) ; String lllat = String . valueOf ( vals [ 6 ] ) ; String lllon = String . valueOf ( vals [ 7 ] ) ; String urlat = String . valueOf ( vals [ 8 ] ) ; String urlon = String . valueOf ( vals [ 9 ] ) ; addParam ( NX , String . valueOf ( vals [ 4 ] ) ) ; addParam ( NY , String . valueOf ( vals [ 5 ] ) ) ; addParam ( LA1 , lllat ) ; addParam ( LO1 , lllon ) ; addParam ( LA2 , urlat ) ; addParam ( LO2 , urlon ) ; switch ( proj ) { case \"STR\" : case \"NPS\" : case \"SPS\" : addParam ( LOV , angle2 ) ; // TODO:  better to just set pole? if ( proj . equals ( \"SPS\" ) ) { addParam ( \"NpProj\" , \"false\" ) ; } break ; case \"LCC\" : case \"SCC\" : addParam ( LATIN1 , angle1 ) ; addParam ( LOV , angle2 ) ; addParam ( LATIN2 , angle3 ) ; // TODO: test this break ; case \"MER\" : case \"MCD\" : String standardLat ; if ( vals [ 10 ] == 0 ) { // use average latitude float lat = ( vals [ 8 ] + vals [ 6 ] ) / 2 ; standardLat = String . valueOf ( lat ) ; } else { standardLat = angle1 ; } addParam ( \"Latin\" , standardLat ) ; addParam ( LOV , angle2 ) ; break ; case \"CED\" : double lllatv = vals [ 6 ] ; double lllonv = vals [ 7 ] ; double urlatv = vals [ 8 ] ; double urlonv = vals [ 9 ] ; if ( urlonv <= lllonv ) { urlonv += 360. ; } double dx = Math . abs ( ( urlonv - lllonv ) / ( vals [ 4 ] - 1 ) ) ; double dy = Math . abs ( ( urlatv - lllatv ) / ( vals [ 5 ] - 1 ) ) ; addParam ( DX , String . valueOf ( dx ) ) ; addParam ( DY , String . valueOf ( dy ) ) ; addParam ( LO2 , String . valueOf ( urlonv ) ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "seems to handle swath as well ?? [CODESPLIT] public void writeGrid ( String gridDataset_filename , String gridName , int time , int level , boolean greyScale , LatLonRect pt ) throws IOException { try ( GridDataset dataset = ucar . nc2 . dt . grid . GridDataset . open ( gridDataset_filename ) ) { GridDatatype grid = dataset . findGridDatatype ( gridName ) ; if ( grid == null ) { throw new IllegalArgumentException ( \"No grid named \" + gridName + \" in fileName\" ) ; } GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; ProjectionImpl proj = grid . getProjection ( ) ; if ( ! gcs . isRegularSpatial ( ) ) { Attribute att = dataset . findGlobalAttributeIgnoreCase ( \"datasetId\" ) ; if ( att != null && att . getStringValue ( ) . contains ( \"DMSP\" ) ) { // LOOK!! writeSwathGrid ( gridDataset_filename , gridName , time , level , greyScale , pt ) ; return ; } else { throw new IllegalArgumentException ( \"Must have 1D x and y axes for \" + grid . getFullName ( ) ) ; } } CoordinateAxis1D xaxis = ( CoordinateAxis1D ) gcs . getXHorizAxis ( ) ; CoordinateAxis1D yaxis = ( CoordinateAxis1D ) gcs . getYHorizAxis ( ) ; if ( ! xaxis . isRegular ( ) || ! yaxis . isRegular ( ) ) { throw new IllegalArgumentException ( \"Must be evenly spaced grid = \" + grid . getFullName ( ) ) ; } // read in data Array data = grid . readDataSlice ( time , level , - 1 , - 1 ) ; Array lon = xaxis . read ( ) ; Array lat = yaxis . read ( ) ; // units may need to be scaled to meters double scaler = ( xaxis . getUnitsString ( ) . equalsIgnoreCase ( \"km\" ) ) ? 1000.0 : 1.0 ; if ( yaxis . getCoordValue ( 0 ) < yaxis . getCoordValue ( 1 ) ) { data = data . flip ( 0 ) ; lat = lat . flip ( 0 ) ; } if ( gcs . isLatLon ( ) ) { data = geoShiftDataAtLon ( data , lon ) ; lon = geoShiftLon ( lon ) ; } // now it is time to subset the data out of latlonrect // it is assumed that latlonrect pt is in +-180 LatLonPointImpl llp0 = pt . getLowerLeftPoint ( ) ; LatLonPointImpl llpn = pt . getUpperRightPoint ( ) ; double minLon = llp0 . getLongitude ( ) ; double minLat = llp0 . getLatitude ( ) ; double maxLon = llpn . getLongitude ( ) ; double maxLat = llpn . getLatitude ( ) ; // (x1, y1) is upper left point and (x2, y2) is lower right point int x1 ; int x2 ; int y1 ; int y2 ; double xStart ; double yStart ; if ( ! gcs . isLatLon ( ) ) { ProjectionPoint pjp0 = proj . latLonToProj ( maxLat , minLon ) ; x1 = getXIndex ( lon , pjp0 . getX ( ) , 0 ) ; y1 = getYIndex ( lat , pjp0 . getY ( ) , 0 ) ; yStart = pjp0 . getY ( ) * 1000.0 ; //latArray[y1]; xStart = pjp0 . getX ( ) * 1000.0 ; //lonArray[x1]; ProjectionPoint pjpn = proj . latLonToProj ( minLat , maxLon ) ; x2 = getXIndex ( lon , pjpn . getX ( ) , 1 ) ; y2 = getYIndex ( lat , pjpn . getY ( ) , 1 ) ; } else { xStart = minLon ; yStart = maxLat ; x1 = getLonIndex ( lon , minLon , 0 ) ; y1 = getLatIndex ( lat , maxLat , 0 ) ; x2 = getLonIndex ( lon , maxLon , 1 ) ; y2 = getLatIndex ( lat , minLat , 1 ) ; } // data must go from top to bottom double xInc = xaxis . getIncrement ( ) * scaler ; double yInc = Math . abs ( yaxis . getIncrement ( ) ) * scaler ; // subsetting data inside the box Array data1 = getYXDataInBox ( data , x1 , x2 , y1 , y2 ) ; if ( pageNumber > 1 ) { geotiff . initTags ( ) ; } // write it out writeGrid ( grid , data1 , greyScale , xStart , yStart , xInc , yInc , pageNumber ) ; pageNumber ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write Swath Grid data to the geotiff file . [CODESPLIT] private void writeSwathGrid ( String fileName , String gridName , int time , int level , boolean greyScale , LatLonRect llr ) throws IOException { GridDataset dataset = ucar . nc2 . dt . grid . GridDataset . open ( fileName ) ; GridDatatype grid = dataset . findGridDatatype ( gridName ) ; GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; ProjectionImpl proj = grid . getProjection ( ) ; CoordinateAxis2D xaxis = ( CoordinateAxis2D ) gcs . getXHorizAxis ( ) ; CoordinateAxis2D yaxis = ( CoordinateAxis2D ) gcs . getYHorizAxis ( ) ; // read in data Array data = grid . readDataSlice ( time , level , - 1 , - 1 ) ; Array lon = xaxis . read ( ) ; Array lat = yaxis . read ( ) ; double [ ] swathInfo = getSwathLatLonInformation ( lat , lon ) ; // units may need to be scaled to meters double scaler = ( xaxis . getUnitsString ( ) . equalsIgnoreCase ( \"km\" ) ) ? 1000.0 : 1.0 ; //if (yaxis.getCoordValue(0, 0) < yaxis.getCoordValue(0, 1)) {//??? data = data . flip ( 0 ) ; //lat = lat.flip(0); //} if ( gcs . isLatLon ( ) ) { data = geoShiftDataAtLon ( data , lon ) ; lon = geoShiftLon ( lon ) ; } double minLon ; double minLat ; double maxLon ; double maxLat ; double xStart ; double yStart ; //upper right point double xInc = swathInfo [ 0 ] * scaler ; double yInc = swathInfo [ 1 ] * scaler ; // (x1, y1) is upper left point and (x2, y2) is lower right point int x1 ; int x2 ; int y1 ; int y2 ; if ( llr == null ) { //get the whole area minLon = swathInfo [ 4 ] ; minLat = swathInfo [ 2 ] ; maxLon = swathInfo [ 5 ] ; maxLat = swathInfo [ 3 ] ; xStart = minLon ; yStart = maxLat ; x1 = 0 ; y1 = 0 ; x2 = ( int ) ( ( maxLon - minLon ) / xInc + 0.5 ) ; y2 = ( int ) ( ( maxLat - minLat ) / yInc + 0.5 ) ; } else { //assign the special area  surrounded by the llr LatLonPointImpl llp0 = llr . getLowerLeftPoint ( ) ; LatLonPointImpl llpn = llr . getUpperRightPoint ( ) ; minLon = ( llp0 . getLongitude ( ) < swathInfo [ 4 ] ) ? swathInfo [ 4 ] : llp0 . getLongitude ( ) ; minLat = ( llp0 . getLatitude ( ) < swathInfo [ 2 ] ) ? swathInfo [ 2 ] : llp0 . getLatitude ( ) ; maxLon = ( llpn . getLongitude ( ) > swathInfo [ 5 ] ) ? swathInfo [ 5 ] : llpn . getLongitude ( ) ; maxLat = ( llpn . getLatitude ( ) > swathInfo [ 3 ] ) ? swathInfo [ 3 ] : llpn . getLatitude ( ) ; //construct the swath  LatLonRect LatLonPointImpl pUpLeft = new LatLonPointImpl ( swathInfo [ 3 ] , swathInfo [ 4 ] ) ; LatLonPointImpl pDownRight = new LatLonPointImpl ( swathInfo [ 2 ] , swathInfo [ 5 ] ) ; LatLonRect swathLLR = new LatLonRect ( pUpLeft , pDownRight ) ; LatLonRect bIntersect = swathLLR . intersect ( llr ) ; if ( bIntersect == null ) { throw new IllegalArgumentException ( \"The assigned extent of latitude and longitude is unvalid. No intersection with the swath extent\" ) ; } xStart = minLon ; yStart = maxLat ; x1 = ( int ) ( ( minLon - swathInfo [ 4 ] ) / xInc + 0.5 ) ; y1 = ( int ) Math . abs ( ( maxLat - swathInfo [ 3 ] ) / yInc + 0.5 ) ; x2 = ( int ) ( ( maxLon - swathInfo [ 4 ] ) / xInc + 0.5 ) ; y2 = ( int ) Math . abs ( ( minLat - swathInfo [ 3 ] ) / yInc + 0.5 ) ; } if ( ! gcs . isLatLon ( ) ) { ProjectionPoint pjp0 = proj . latLonToProj ( maxLat , minLon ) ; x1 = getXIndex ( lon , pjp0 . getX ( ) , 0 ) ; y1 = getYIndex ( lat , pjp0 . getY ( ) , 0 ) ; yStart = pjp0 . getY ( ) * scaler ; //latArray[y1]; xStart = pjp0 . getX ( ) * scaler ; //lonArray[x1]; ProjectionPoint pjpn = proj . latLonToProj ( minLat , maxLon ) ; x2 = getXIndex ( lon , pjpn . getX ( ) , 1 ) ; y2 = getYIndex ( lat , pjpn . getY ( ) , 1 ) ; } else { //calculate the x1, x2, y1, y2, xstart, ystart. } Array targetImage = getTargetImagerFromSwath ( lat , lon , data , swathInfo ) ; Array interpolatedImage = interpolation ( targetImage ) ; Array clippedImage = getClippedImageFromInterpolation ( interpolatedImage , x1 , x2 , y1 , y2 ) ; //Array clippedImage = getYXDataInBox(interpolatedImage, x1, x2, y1, y2); if ( pageNumber > 1 ) { geotiff . initTags ( ) ; } writeGrid ( grid , clippedImage , greyScale , xStart , yStart , xInc , yInc , pageNumber ) ; pageNumber ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "interpolate the swath data to regular grid [CODESPLIT] private Array interpolation ( Array arr ) { int [ ] orishape = arr . getShape ( ) ; int width = orishape [ 1 ] ; int height = orishape [ 0 ] ; int pixelNum = width * height ; Array interpolatedArray = Array . factory ( DataType . FLOAT , orishape ) ; for ( int i = 0 ; i < height ; i ++ ) { for ( int j = 0 ; j < width ; j ++ ) { int curIndex = i * width + j ; float curValue = arr . getFloat ( curIndex ) ; if ( curValue == 0 ) //Black hole. Need to fill. { float tempPixelSum = 0 ; int numNeighborHasValue = 0 ; //Get the values of eight neighborhood if ( ( curIndex - 1 >= 0 ) && ( curIndex - 1 < pixelNum ) ) { float left = arr . getFloat ( curIndex - 1 ) ; if ( left > 0 ) { tempPixelSum += left ; numNeighborHasValue ++ ; } } if ( ( curIndex + 1 >= 0 ) && ( curIndex + 1 < pixelNum ) ) { float right = arr . getFloat ( curIndex + 1 ) ; if ( right > 0 ) { tempPixelSum += right ; numNeighborHasValue ++ ; } } if ( ( curIndex - width >= 0 ) && ( curIndex - width < pixelNum ) ) { float up = arr . getFloat ( curIndex - width ) ; if ( up > 0 ) { tempPixelSum += up ; numNeighborHasValue ++ ; } } if ( ( curIndex + width >= 0 ) && ( curIndex + width < pixelNum ) ) { float down = arr . getFloat ( curIndex + width ) ; if ( down > 0 ) { tempPixelSum += down ; numNeighborHasValue ++ ; } } if ( ( curIndex - width - 1 >= 0 ) && ( curIndex - width - 1 < pixelNum ) ) { float upleft = arr . getFloat ( curIndex - width - 1 ) ; if ( upleft > 0 ) { tempPixelSum += upleft ; numNeighborHasValue ++ ; } } if ( ( curIndex - width + 1 >= 0 ) && ( curIndex - width + 1 < pixelNum ) ) { float upright = arr . getFloat ( curIndex - width + 1 ) ; if ( upright > 0 ) { tempPixelSum += upright ; numNeighborHasValue ++ ; } } if ( ( curIndex + width - 1 >= 0 ) && ( curIndex + width - 1 < pixelNum ) ) { float downleft = arr . getFloat ( curIndex + width - 1 ) ; if ( downleft > 0 ) { tempPixelSum += downleft ; numNeighborHasValue ++ ; } } if ( ( curIndex + width + 1 >= 0 ) && ( curIndex + width + 1 < pixelNum ) ) { float downright = arr . getFloat ( curIndex + width + 1 ) ; if ( downright > 0 ) { tempPixelSum += downright ; numNeighborHasValue ++ ; } } if ( tempPixelSum > 0 ) { float val = numNeighborHasValue == 0 ? 0 : tempPixelSum / numNeighborHasValue ; interpolatedArray . setFloat ( curIndex , val ) ; } } else { interpolatedArray . setFloat ( curIndex , curValue ) ; } } } return interpolatedArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get lat lon information from the swath [CODESPLIT] private double [ ] getSwathLatLonInformation ( Array lat , Array lon ) { // Calculate the increment of latitude and longitude of original swath data // Calculate the size of the boundingBox // element0: Longitude increment // element1: Latitude increment // element2: minLat // element3: maxLat // element4: minLon // element5: maxLon // element6: width of the boundingBox // element7: height of the boundingBox double increment [ ] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; IndexIterator latIter = lat . getIndexIterator ( ) ; IndexIterator lonIter = lon . getIndexIterator ( ) ; int numScan = ( lat . getShape ( ) ) [ 0 ] ; int numSample = ( lat . getShape ( ) ) [ 1 ] ; double maxLat = - 91 , minLat = 91 , maxLon = - 181 , minLon = 181 ; float firstLineStartLat = 0 ; float firstLineStartLon = 0 ; float firstLineEndLat = 0 ; float firstLineEndLon = 0 ; float lastLineStartLat = 0 ; float lastLineStartLon = 0 ; float lastLineEndLat = 0 ; float lastLineEndLon = 0 ; for ( int i = 0 ; i < numScan ; i ++ ) { for ( int j = 0 ; j < numSample ; j ++ ) { if ( latIter . hasNext ( ) && lonIter . hasNext ( ) ) { float curLat = latIter . getFloatNext ( ) ; float curLon = lonIter . getFloatNext ( ) ; if ( ( i == 0 ) && ( j == 0 ) ) { firstLineStartLat = curLat ; firstLineStartLon = curLon ; } else if ( ( i == 0 ) && ( j == numSample - 1 ) ) { firstLineEndLat = curLat ; firstLineEndLon = curLon ; } else if ( ( i == numScan - 1 ) && ( j == 0 ) ) { lastLineStartLat = curLat ; lastLineStartLon = curLon ; } else if ( ( i == numScan - 1 ) && ( j == numSample - 1 ) ) { lastLineEndLat = curLat ; lastLineEndLon = curLon ; } } } } double [ ] edgeLat = { firstLineStartLat , firstLineEndLat , lastLineStartLat , lastLineEndLat } ; double [ ] edgeLon = { firstLineStartLon , firstLineEndLon , lastLineStartLon , lastLineEndLon } ; for ( int i = 0 ; i < edgeLat . length ; i ++ ) { maxLat = ( ( maxLat > edgeLat [ i ] ) ? maxLat : edgeLat [ i ] ) ; minLat = ( ( minLat < edgeLat [ i ] ) ? minLat : edgeLat [ i ] ) ; maxLon = ( ( maxLon > edgeLon [ i ] ) ? maxLon : edgeLon [ i ] ) ; minLon = ( ( minLon < edgeLon [ i ] ) ? minLon : edgeLon [ i ] ) ; } double xInc1 = Math . abs ( ( firstLineEndLon - firstLineStartLon ) / numSample ) ; //double xInc2 = Math.abs((lastLineEndLon - lastLineStartLon)/numSample); double yInc1 = Math . abs ( ( lastLineStartLat - firstLineStartLat ) / numScan ) ; //double yInc2 = Math.abs((lastLineEndLat - firstLineEndLat)/numScan); increment [ 0 ] = xInc1 ; // > xInc2 ? xInc1 : xInc2; increment [ 1 ] = yInc1 ; // > yInc2 ? yInc1 : yInc2; increment [ 2 ] = minLat ; increment [ 3 ] = maxLat ; increment [ 4 ] = minLon ; increment [ 5 ] = maxLon ; increment [ 6 ] = ( maxLon - minLon ) / xInc1 ; increment [ 7 ] = ( maxLat - minLat ) / yInc1 ; return increment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used by H5tiledLayout [CODESPLIT] LayoutTiled . DataChunkIterator getDataChunkIteratorNoFilter ( Section want , int nChunkDim ) throws IOException { /*\r\n    if (if (debugChunkOrder) ) {\r\n    DataChunkIteratorNoFilter iter = new DataChunkIteratorNoFilter(null, nChunkDim);\r\n    int count = 0;\r\n    int last = -1;\r\n    while (iter.hasNext()) {\r\n      LayoutTiled.DataChunk chunk = iter.next();\r\n      System.out.printf(\"%d : %d%n\", count++, tiling.order(chunk.offset));\r\n      if (tiling.order(chunk.offset) <= last)\r\n        System.out.println(\"HEY\");\r\n      last = tiling.order(chunk.offset);\r\n    }\r\n    }*/ return new DataChunkIteratorNoFilter ( want , nChunkDim ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; double [ ] [ ] xy = anav . toLinEle ( new double [ ] [ ] { { fromLat } , { fromLon } } ) ; if ( xy == null ) return null ; toX = xy [ 0 ] [ 0 ] ; toY = xy [ 1 ] [ 0 ] ; result . setLocation ( toX , toY ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) ; double fromY = world . getY ( ) ; double [ ] [ ] latlon = anav . toLatLon ( new double [ ] [ ] { { fromX } , { fromY } } ) ; toLat = latlon [ 0 ] [ 0 ] ; toLon = latlon [ 1 ] [ 0 ] ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] [ ] xy = anav . toLinEle ( new float [ ] [ ] { fromLatA , fromLonA } ) ; if ( xy == null ) return null ; to [ INDEX_X ] = xy [ 0 ] ; to [ INDEX_Y ] = xy [ 1 ] ; return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] [ ] latlon = anav . toLatLon ( new float [ ] [ ] { fromXA , fromYA } ) ; to [ INDEX_LAT ] = latlon [ 0 ] ; to [ INDEX_LON ] = latlon [ 1 ] ; return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This returns true when the line between pt1 and pt2 crosses the seam . When the cone is flattened the seam is lon0 + - 180 . [CODESPLIT] public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { // either point is infinite\r if ( ProjectionPointImpl . isInfinite ( pt1 ) || ProjectionPointImpl . isInfinite ( pt2 ) ) { return true ; } if ( Double . isNaN ( pt1 . getX ( ) ) || Double . isNaN ( pt1 . getY ( ) ) || Double . isNaN ( pt2 . getX ( ) ) || Double . isNaN ( pt2 . getY ( ) ) ) { return true ; } // opposite signed X values, larger then 5000 km\r return ( pt1 . getX ( ) * pt2 . getX ( ) < 0 ) && ( Math . abs ( pt1 . getX ( ) - pt2 . getX ( ) ) > 5000.0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make a double array out of an int array [CODESPLIT] private double [ ] makeDoubleArray ( int [ ] ints ) { double [ ] newArray = new double [ ints . length ] ; for ( int i = 0 ; i < ints . length ; i ++ ) { newArray [ i ] = ints [ i ] ; } return newArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////// [CODESPLIT] @ RequestMapping ( value = { \"**/dataset.xml\" , \"**/pointDataset.xml\" } ) // Same response for both Grid and GridAsPoint. public ModelAndView getDatasetDescriptionXml ( HttpServletRequest req , HttpServletResponse res ) throws IOException { String datasetPath = getDatasetPath ( req ) ; try ( CoverageCollection gcd = TdsRequestedDataset . getCoverageCollection ( req , res , datasetPath ) ) { if ( gcd == null ) return null ; // restricted dataset String datasetUrlPath = buildDatasetUrl ( datasetPath ) ; CoverageDatasetCapabilities writer = new CoverageDatasetCapabilities ( gcd , \"path\" ) ; Document doc = writer . makeDatasetDescription ( ) ; Element root = doc . getRootElement ( ) ; root . setAttribute ( \"location\" , datasetUrlPath ) ; root . addContent ( makeAcceptXML ( SupportedOperation . GRID_REQUEST ) ) ; return new ModelAndView ( \"threddsXmlView\" , \"Document\" , doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supported for backwards compatibility . We prefer that datasetBoundaries . wkt or datasetBoundaries . json are used . [CODESPLIT] @ RequestMapping ( \"**/datasetBoundaries.xml\" ) public void getDatasetBoundaries ( NcssParamsBean params , HttpServletRequest req , HttpServletResponse res ) throws IOException , UnsupportedResponseFormatException { SupportedFormat format = SupportedOperation . DATASET_BOUNDARIES_REQUEST . getSupportedFormat ( params . getAccept ( ) ) ; switch ( format ) { case WKT : getDatasetBoundariesWKT ( req , res ) ; break ; case JSON : getDatasetBoundariesGeoJSON ( req , res ) ; break ; default : throw new IllegalArgumentException ( String . format ( \"Expected %s or %s, but got %s\" , SupportedFormat . WKT , SupportedFormat . JSON , format ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that all the requested vars exist . If all fills out the param . vars with all grid names Throws exception if some of the variables in the request are not contained in the dataset [CODESPLIT] private void checkRequestedVars ( CoverageCollection gcd , NcssGridParamsBean params ) throws VariableNotContainedInDatasetException { // if var == all --> all variables requested if ( params . getVar ( ) . get ( 0 ) . equalsIgnoreCase ( \"all\" ) ) { params . setVar ( getAllGridNames ( gcd ) ) ; return ; } // Check vars are contained in the grid for ( String gridName : params . getVar ( ) ) { Coverage grid = gcd . findCoverage ( gridName ) ; if ( grid == null ) throw new VariableNotContainedInDatasetException ( \"Variable: \" + gridName + \" is not contained in the requested dataset\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if all the variables have the same vertical axis ( if they have an axis ) . Could be broadened to allow all with same coordinate unites? coordinate value?? [CODESPLIT] protected boolean checkVarsHaveSameVertAxis ( CoverageCollection gcd , NcssGridParamsBean params ) { String zaxisName = null ; for ( String gridName : params . getVar ( ) ) { Coverage grid = gcd . findCoverage ( gridName ) ; CoverageCoordAxis zaxis = grid . getCoordSys ( ) . getZAxis ( ) ; if ( zaxis != null ) { if ( zaxisName == null ) zaxisName = zaxis . getName ( ) ; else if ( ! zaxisName . equals ( zaxis . getName ( ) ) ) return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Stereographic Projection using latitude of true scale and calculating scale factor . <p > Since the scale factor at lat = k = 2 * k0 / ( 1 + sin ( lat )) [ Snyder Working Manual p157 ] then to make scale = 1 at lat set k0 = ( 1 + sin ( lat )) / 2 [CODESPLIT] static public Stereographic factory ( double latt , double lont , double latTrue ) { double scale = ( 1.0 + Math . sin ( Math . toRadians ( latTrue ) ) ) / 2.0 ; return new Stereographic ( latt , lont , scale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate polar stereographic scale factor based on the natural latitude and longitude of the original Ref : OGP Surveying and Positioning Guidance Note number 7 part 2 April 2009 http : // www . epsg . org added by Qun He <qunhe@unc . edu > [CODESPLIT] private double getScaleFactor ( double lat_ts , boolean north ) { double e = 0.081819191 ; double tf = 1.0 , mf = 1.0 , k0 = 1.0 ; double root = ( 1 + e * Math . sin ( lat_ts ) ) / ( 1 - e * Math . sin ( lat_ts ) ) ; double power = e / 2 ; if ( north ) tf = Math . tan ( Math . PI / 4 - lat_ts / 2 ) * ( Math . pow ( root , power ) ) ; else tf = Math . tan ( Math . PI / 4 + lat_ts / 2 ) / ( Math . pow ( root , power ) ) ; mf = Math . cos ( lat_ts ) / Math . sqrt ( 1 - e * e * Math . pow ( Math . sin ( lat_ts ) , 2 ) ) ; k0 = mf * Math . sqrt ( Math . pow ( 1 + e , 1 + e ) * Math . pow ( 1 - e , 1 - e ) ) / ( 2 * tf ) ; return Double . isNaN ( k0 ) ? 1.0 : k0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; double lat = Math . toRadians ( fromLat ) ; double lon = Math . toRadians ( fromLon ) ; // keep away from the singular point\r if ( ( Math . abs ( lat + latt ) <= TOLERANCE ) ) { lat = - latt * ( 1.0 - TOLERANCE ) ; } double sdlon = Math . sin ( lon - lont ) ; double cdlon = Math . cos ( lon - lont ) ; double sinlat = Math . sin ( lat ) ; double coslat = Math . cos ( lat ) ; double k = 2.0 * scale / ( 1.0 + sinlatt * sinlat + coslatt * coslat * cdlon ) ; toX = k * coslat * sdlon ; toY = k * ( coslatt * sinlat - sinlatt * coslat * cdlon ) ; result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double phi , lam ; double rho = Math . sqrt ( fromX * fromX + fromY * fromY ) ; double c = 2.0 * Math . atan2 ( rho , 2.0 * scale ) ; double sinc = Math . sin ( c ) ; double cosc = Math . cos ( c ) ; if ( Math . abs ( rho ) < TOLERANCE ) { phi = latt ; } else { phi = Math . asin ( cosc * sinlatt + fromY * sinc * coslatt / rho ) ; } toLat = Math . toDegrees ( phi ) ; if ( ( Math . abs ( fromX ) < TOLERANCE ) && ( Math . abs ( fromY ) < TOLERANCE ) ) { lam = lont ; } else if ( Math . abs ( coslatt ) < TOLERANCE ) { lam = lont + Math . atan2 ( fromX , ( ( latt > 0 ) ? - fromY : fromY ) ) ; } else { lam = lont + Math . atan2 ( fromX * sinc , rho * coslatt * cosc - fromY * sinc * sinlatt ) ; } toLon = Math . toDegrees ( lam ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { int cnt = from [ 0 ] . length ; float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] toLatA = to [ INDEX_LAT ] ; float [ ] toLonA = to [ INDEX_LON ] ; double phi , lam ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] - falseEasting ; double fromY = fromYA [ i ] - falseNorthing ; double rho = Math . sqrt ( fromX * fromX + fromY * fromY ) ; double c = 2.0 * Math . atan2 ( rho , 2.0 * scale ) ; double sinc = Math . sin ( c ) ; double cosc = Math . cos ( c ) ; if ( Math . abs ( rho ) < TOLERANCE ) { phi = latt ; } else { phi = Math . asin ( cosc * sinlatt + fromY * sinc * coslatt / rho ) ; } toLat = Math . toDegrees ( phi ) ; if ( ( Math . abs ( fromX ) < TOLERANCE ) && ( Math . abs ( fromY ) < TOLERANCE ) ) { lam = lont ; } else if ( Math . abs ( coslatt ) < TOLERANCE ) { lam = lont + Math . atan2 ( fromX , ( ( latt > 0 ) ? - fromY : fromY ) ) ; } else { lam = lont + Math . atan2 ( fromX * sinc , rho * coslatt * cosc - fromY * sinc * sinlatt ) ; } toLon = Math . toDegrees ( lam ) ; toLatA [ i ] = ( float ) toLat ; toLonA [ i ] = ( float ) toLon ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public double [ ] [ ] latLonToProj ( double [ ] [ ] from , double [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; double [ ] fromLatA = from [ latIndex ] ; double [ ] fromLonA = from [ lonIndex ] ; double [ ] resultXA = to [ INDEX_X ] ; double [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; double lat = Math . toRadians ( fromLat ) ; double lon = Math . toRadians ( fromLon ) ; // keep away from the singular point\r if ( ( Math . abs ( lat + latt ) <= TOLERANCE ) ) { lat = - latt * ( 1.0 - TOLERANCE ) ; } double sdlon = Math . sin ( lon - lont ) ; double cdlon = Math . cos ( lon - lont ) ; double sinlat = Math . sin ( lat ) ; double coslat = Math . cos ( lat ) ; double k = 2.0 * scale / ( 1.0 + sinlatt * sinlat + coslatt * coslat * cdlon ) ; toX = k * coslat * sdlon ; toY = k * ( coslatt * sinlat - sinlatt * coslat * cdlon ) ; resultXA [ i ] = toX + falseEasting ; resultYA [ i ] = toY + falseNorthing ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the DatasetSourceStructure that matches this name . [CODESPLIT] public static DatasetSourceStructure getStructure ( String name ) { if ( name == null ) return null ; return ( DatasetSourceStructure ) hash . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to work under Intellij . [CODESPLIT] @ Override public String getResourcePath ( DapRequest drq , String location ) throws DapException { String realpath ; if ( TdsRequestedDataset . getDatasetManager ( ) != null ) { realpath = TdsRequestedDataset . getLocationFromRequestPath ( location ) ; } else { assert TdsRequestedDataset . getDatasetManager ( ) == null ; String prefix = drq . getResourceRoot ( ) ; assert ( prefix != null ) ; realpath = DapUtil . canonjoin ( prefix , location ) ; } if ( ! TESTING ) { if ( ! TdsRequestedDataset . resourceControlOk ( drq . getRequest ( ) , drq . getResponse ( ) , realpath ) ) throw new DapException ( \"Not authorized: \" + location ) . setCode ( DapCodes . SC_FORBIDDEN ) ; } File f = new File ( realpath ) ; if ( ! f . exists ( ) || ! f . canRead ( ) ) throw new DapException ( \"Not found: \" + location ) . setCode ( DapCodes . SC_NOT_FOUND ) ; //ncfile = TdsRequestedDataset.getNetcdfFile(this.request, this.response, path); return realpath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill in the netCDF file [CODESPLIT] public void open ( GridIndex index , GridTableLookup lookup , int version , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { // create the HorizCoord Systems : one for each gds List < GridDefRecord > hcsList = index . getHorizCoordSys ( ) ; boolean needGroups = ( hcsList . size ( ) > 1 ) ; for ( GridDefRecord gds : hcsList ) { Group g = null ; if ( needGroups ) { g = new Group ( ncfile , null , gds . getGroupName ( ) ) ; ncfile . addGroup ( null , g ) ; } // (GridDefRecord gdsIndex, String grid_name, String shape_name, Group g) GridHorizCoordSys hcs = makeGridHorizCoordSys ( gds , lookup , g ) ; hcsHash . put ( gds . getParam ( GridDefRecord . GDS_KEY ) , hcs ) ; } // run through each record GridRecord firstRecord = null ; List < GridRecord > records = index . getGridRecords ( ) ; for ( GridRecord gridRecord : records ) { if ( firstRecord == null ) { firstRecord = gridRecord ; } GridHorizCoordSys hcs = hcsHash . get ( gridRecord . getGridDefRecordId ( ) ) ; int cdmHash = gridRecord . cdmVariableHash ( ) ; GridVariable pv = hcs . varHash . get ( cdmHash ) ; if ( null == pv ) { String name = gridRecord . cdmVariableName ( lookup , true , true ) ; pv = makeGridVariable ( indexFilename , name , hcs , lookup ) ; hcs . varHash . put ( cdmHash , pv ) ; // keep track of all products with same parameter name == \"simple name\" String simpleName = gridRecord . getParameterDescription ( ) ; List < GridVariable > plist = hcs . productHash . get ( simpleName ) ; if ( null == plist ) { plist = new ArrayList <> ( ) ; hcs . productHash . put ( simpleName , plist ) ; } plist . add ( pv ) ; } /* else if ( lookup instanceof Grib2GridTableLookup ) {\n        Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;\n        // check for non interval pv and interval record which needs a interval pv\n        if( ! pv.isInterval() && g2lookup.isInterval(gridRecord) ) {\n          // make an interval variable\n          String interval = name +\"_interval\";\n          pv = (GridVariable) hcs.varHash.get(interval);\n          if (null == pv) {\n            pv = new GridVariable(interval, hcs, lookup);\n            hcs.varHash.put(cdmHash, pv);\n            String simpleName = makeVariableName(gridRecord, lookup, false, true); // LOOK may not be a good idea\n            List<GridVariable> plist = hcs.productHash.get(simpleName);\n            if (null == plist) {\n              plist = new ArrayList<GridVariable>();\n              hcs.productHash.put(simpleName, plist);\n            }\n            plist.add(pv);\n          }\n\n        } else if ( pv.isInterval() && !g2lookup.isInterval(gridRecord)  ) {\n          // make a non-interval variable\n          // logger.info( \"Non-Interval records for %s%n\", pv.getName());  LOOK\n            continue;\n        }\n      } // grid2 */ pv . addProduct ( gridRecord ) ; } // global CF Conventions // Conventions attribute change must be in sync with CDM code ncfile . addAttribute ( null , new Attribute ( \"Conventions\" , \"CF-1.4\" ) ) ; addExtraAttributes ( firstRecord , lookup , ncfile ) ; // CF Global attributes ncfile . addAttribute ( null , new Attribute ( \"title\" , lookup . getTitle ( ) ) ) ; if ( lookup . getInstitution ( ) != null ) ncfile . addAttribute ( null , new Attribute ( \"institution\" , lookup . getInstitution ( ) ) ) ; String source = lookup . getSource ( ) ; if ( source != null && ! source . startsWith ( \"Unknown\" ) ) ncfile . addAttribute ( null , new Attribute ( \"source\" , source ) ) ; // String now = formatter.toDateTimeStringISO( Calendar.getInstance().getTime()); ncfile . addAttribute ( null , new Attribute ( \"history\" , \"Direct read of \" + lookup . getGridType ( ) + \" into NetCDF-Java 4 API\" ) ) ; if ( lookup . getComment ( ) != null ) ncfile . addAttribute ( null , new Attribute ( \"comment\" , lookup . getComment ( ) ) ) ; // dataset discovery //if ( center != null) //  ncfile.addAttribute(null, new Attribute(\"center_name\", center)); // CDM attributes ncfile . addAttribute ( null , new Attribute ( CF . FEATURE_TYPE , FeatureType . GRID . toString ( ) ) ) ; ncfile . addAttribute ( null , new Attribute ( \"file_format\" , lookup . getGridType ( ) ) ) ; // ncfile.addAttribute(null, new Attribute(\"location\", ncfile.getLocation())); ncfile . addAttribute ( null , new Attribute ( _Coordinate . ModelRunDate , formatter . toDateTimeStringISO ( lookup . getFirstBaseTime ( ) ) ) ) ; /* if (fmrcCoordSys != null) {\n      makeDefinedCoordSys(ncfile, lookup, fmrcCoordSys);\n    } else {\n      makeDenseCoordSys(ncfile, lookup, cancelTask);\n    } */ makeDenseCoordSys ( ncfile , lookup , cancelTask ) ; if ( GridServiceProvider . debugMissing ) { try ( Formatter f = new Formatter ( System . out ) ) { int count = 0 ; Collection < GridHorizCoordSys > hcset = hcsHash . values ( ) ; for ( GridHorizCoordSys hcs : hcset ) { List < GridVariable > gribvars = new ArrayList <> ( hcs . varHash . values ( ) ) ; for ( GridVariable gv : gribvars ) { count += gv . showMissingSummary ( f ) ; } } System . out . println ( \" total missing= \" + count ) ; } } if ( GridServiceProvider . debugMissingDetails ) { Formatter f = new Formatter ( ) ; Collection < GridHorizCoordSys > hcset = hcsHash . values ( ) ; for ( GridHorizCoordSys hcs : hcset ) { f . format ( \"******** Horiz Coordinate= %s%n\" , hcs . getGridName ( ) ) ; String lastVertDesc = null ; List < GridVariable > gribvars = new ArrayList <> ( hcs . varHash . values ( ) ) ; Collections . sort ( gribvars , new CompareGridVariableByVertName ( ) ) ; for ( GridVariable gv : gribvars ) { String vertDesc = gv . getVertName ( ) ; if ( ! vertDesc . equals ( lastVertDesc ) ) { f . format ( \"---Vertical Coordinate= %s%n\" , vertDesc ) ; lastVertDesc = vertDesc ; } gv . showMissing ( f ) ; } } } // clean out stuff we dont need anymore //for (GridHorizCoordSys ghcs : hcsHash.values()) { //  ghcs.empty(); //} }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make coordinate system without missing data - means that we have to make a coordinate axis for each unique set of time or vertical levels . [CODESPLIT] private void makeDenseCoordSys ( NetcdfFile ncfile , GridTableLookup lookup , CancelTask cancelTask ) throws IOException { List < GridTimeCoord > timeCoords = new ArrayList <> ( ) ; List < GridVertCoord > vertCoords = new ArrayList <> ( ) ; List < GridEnsembleCoord > ensembleCoords = new ArrayList <> ( ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeZone ( java . util . TimeZone . getTimeZone ( \"GMT\" ) ) ; // loop over HorizCoordSys Collection < GridHorizCoordSys > hcset = hcsHash . values ( ) ; for ( GridHorizCoordSys hcs : hcset ) { if ( ( cancelTask != null ) && cancelTask . isCancel ( ) ) break ; // loop over GridVariables in the HorizCoordSys // create the time and vertical coordinates List < GridVariable > gribvars = new ArrayList <> ( hcs . varHash . values ( ) ) ; for ( GridVariable gv : gribvars ) { if ( ( cancelTask != null ) && cancelTask . isCancel ( ) ) break ; List < GridRecord > recordList = gv . getRecords ( ) ; GridRecord record = recordList . get ( 0 ) ; String vname = gv . makeLevelName ( record , lookup ) ; // look to see if vertical already exists GridVertCoord useVertCoord = null ; for ( GridVertCoord gvcs : vertCoords ) { if ( vname . equals ( gvcs . getLevelName ( ) ) ) { if ( gvcs . matchLevels ( recordList ) ) { // must have the same levels useVertCoord = gvcs ; } } } if ( useVertCoord == null ) { // nope, got to create it useVertCoord = makeGridVertCoord ( recordList , vname , lookup , hcs ) ; vertCoords . add ( useVertCoord ) ; } gv . setVertCoord ( useVertCoord ) ; // look to see if time coord already exists GridTimeCoord useTimeCoord = null ; for ( GridTimeCoord gtc : timeCoords ) { if ( gtc . matchTimes ( recordList ) ) { // must have the same time coords useTimeCoord = gtc ; break ; } } if ( useTimeCoord == null ) { // nope, got to create it useTimeCoord = makeGridTimeCoord ( recordList , ncfile . getLocation ( ) ) ; timeCoords . add ( useTimeCoord ) ; } gv . setTimeCoord ( useTimeCoord ) ; if ( gv . isEnsemble ( ) ) { GridEnsembleCoord useEnsembleCoord = addEnsembles ( ensembleCoords , recordList ) ; if ( useEnsembleCoord != null ) gv . setEnsembleCoord ( useEnsembleCoord ) ; } } // assign time coordinate names, add dimensions to file // reverse sort by length - give time dimensions unique names Collections . sort ( timeCoords ) ; int count = 0 ; for ( GridTimeCoord tcs : timeCoords ) { tcs . setSequence ( count ++ ) ; tcs . addDimensionsToNetcdfFile ( ncfile , hcs . getGroup ( ) ) ; } // add Ensemble dimensions, give Ensemble dimensions unique names int seqno = 0 ; for ( GridEnsembleCoord gec : ensembleCoords ) { gec . setSequence ( seqno ++ ) ; gec . addDimensionsToNetcdfFile ( ncfile , hcs . getGroup ( ) ) ; } // add x, y dimensions hcs . addDimensionsToNetcdfFile ( ncfile ) ; // add vertical dimensions, give them unique names Collections . sort ( vertCoords ) ; int vcIndex = 0 ; String listName = null ; int start = 0 ; for ( vcIndex = 0 ; vcIndex < vertCoords . size ( ) ; vcIndex ++ ) { GridVertCoord gvcs = vertCoords . get ( vcIndex ) ; String vname = gvcs . getLevelName ( ) ; if ( listName == null ) { listName = vname ; // initial } if ( ! vname . equals ( listName ) ) { makeVerticalDimensions ( vertCoords . subList ( start , vcIndex ) , ncfile , hcs . getGroup ( ) ) ; listName = vname ; start = vcIndex ; } } makeVerticalDimensions ( vertCoords . subList ( start , vcIndex ) , ncfile , hcs . getGroup ( ) ) ; // create a variable for each entry, but check for other products with same simple name to disambiguate List < List < GridVariable > > products = new ArrayList <> ( hcs . productHash . values ( ) ) ; for ( List < GridVariable > plist : products ) { if ( ( cancelTask != null ) && cancelTask . isCancel ( ) ) break ; if ( plist . size ( ) == 1 ) { GridVariable pv = plist . get ( 0 ) ; String name = pv . getFirstRecord ( ) . cdmVariableName ( lookup , false , false ) ; // plain ole name Variable v = pv . makeVariable ( ncfile , hcs . getGroup ( ) , name , raf ) ; ncfile . addVariable ( hcs . getGroup ( ) , v ) ; } else { // collect them grouped by vertical coord Map < GridVertCoord , VertCollection > vcMap = new HashMap <> ( ) ; for ( GridVariable gv : plist ) { VertCollection vc = vcMap . get ( gv . getVertCoord ( ) ) ; if ( vc == null ) { vc = new VertCollection ( gv ) ; vcMap . put ( gv . getVertCoord ( ) , vc ) ; } vc . list . add ( gv ) ; } // sort by larger # vert levels List < VertCollection > vclist = new ArrayList <> ( vcMap . values ( ) ) ; Collections . sort ( vclist ) ; boolean firstVertCoord = true ; for ( VertCollection vc : vclist ) { boolean hasMultipleLevels = vc . vc . getNLevels ( ) > 1 ; boolean noLevelOk = firstVertCoord ; //  && hasMultipleLevels;  LOOK turned off for now 9/15/10 List < GridVariable > list = vc . list ; if ( list . size ( ) == 1 ) { GridVariable gv = list . get ( 0 ) ; String name = gv . getFirstRecord ( ) . cdmVariableName ( lookup , ! noLevelOk , false ) ; ncfile . addVariable ( hcs . getGroup ( ) , gv . makeVariable ( ncfile , hcs . getGroup ( ) , name , raf ) ) ; } else { for ( GridVariable gv : list ) { // more than one - disambiguate by stat name String name = gv . getFirstRecord ( ) . cdmVariableName ( lookup , ! noLevelOk , true ) ; ncfile . addVariable ( hcs . getGroup ( ) , gv . makeVariable ( ncfile , hcs . getGroup ( ) , name , raf ) ) ; } } firstVertCoord = false ; } } // multiple vertical levels } // create variable // add coordinate variables at the end for ( GridTimeCoord tcs : timeCoords ) { tcs . addToNetcdfFile ( ncfile , hcs . getGroup ( ) ) ; } for ( GridEnsembleCoord ens : ensembleCoords ) { ens . addToNetcdfFile ( ncfile , hcs . getGroup ( ) ) ; } hcs . addToNetcdfFile ( ncfile ) ; for ( GridVertCoord gvcs : vertCoords ) { gvcs . addToNetcdfFile ( ncfile , hcs . getGroup ( ) ) ; } } // loop over hcs // TODO: check this,  in ToolsUI it caused problems //for (GridVertCoord gvcs : vertCoords) { //  gvcs.empty(); //} }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a vertical dimensions [CODESPLIT] private void makeVerticalDimensions ( List < GridVertCoord > vertCoordList , NetcdfFile ncfile , Group group ) { // find biggest vert coord GridVertCoord gvcs0 = null ; int maxLevels = 0 ; for ( GridVertCoord gvcs : vertCoordList ) { if ( gvcs . getNLevels ( ) > maxLevels ) { gvcs0 = gvcs ; maxLevels = gvcs . getNLevels ( ) ; } } int seqno = 1 ; for ( GridVertCoord gvcs : vertCoordList ) { if ( gvcs != gvcs0 ) { gvcs . setSequence ( seqno ++ ) ; } gvcs . addDimensionsToNetcdfFile ( ncfile , group ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the header and populate the ncfile [CODESPLIT] boolean readPIB ( RandomAccessFile raf ) throws IOException { this . firstHeader = new AwxFileFirstHeader ( ) ; int pos = 0 ; raf . seek ( pos ) ; // gini header process byte [ ] buf = new byte [ FY_AWX_PIB_LEN ] ; int count = raf . read ( buf ) ; EndianByteBuffer byteBuffer ; if ( count == FY_AWX_PIB_LEN ) { byteBuffer = new EndianByteBuffer ( buf , this . firstHeader . byteOrder ) ; this . firstHeader . fillHeader ( byteBuffer ) ; } else { return false ; } if ( ! ( ( this . firstHeader . fileName . endsWith ( \".AWX\" ) || this . firstHeader . fileName . endsWith ( \".awx\" ) ) && this . firstHeader . firstHeaderLength == FY_AWX_PIB_LEN ) ) { return false ; } // skip the fills of the first record //  raf.seek(FY_AWX_PIB_LEN + this.firstHeader.fillSectionLength); buf = new byte [ this . firstHeader . secondHeaderLength ] ; raf . readFully ( buf ) ; byteBuffer = new EndianByteBuffer ( buf , this . firstHeader . byteOrder ) ; switch ( this . firstHeader . typeOfProduct ) { case AwxFileFirstHeader . AWX_PRODUCT_TYPE_UNDEFINED : throw new UnsupportedDatasetException ( ) ; case AwxFileFirstHeader . AWX_PRODUCT_TYPE_GEOSAT_IMAGE : secondHeader = new AwxFileGeoSatelliteSecondHeader ( ) ; secondHeader . fillHeader ( byteBuffer ) ; break ; case AwxFileFirstHeader . AWX_PRODUCT_TYPE_POLARSAT_IMAGE : throw new UnsupportedDatasetException ( ) ; case AwxFileFirstHeader . AWX_PRODUCT_TYPE_GRID : secondHeader = new AwxFileGridProductSecondHeader ( ) ; secondHeader . fillHeader ( byteBuffer ) ; break ; case AwxFileFirstHeader . AWX_PRODUCT_TYPE_DISCREET : throw new UnsupportedDatasetException ( ) ; case AwxFileFirstHeader . AWX_PRODUCT_TYPE_GRAPH_ANALIYSIS : throw new UnsupportedDatasetException ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finish constructing after all elements have been added . This does the inheritence thing This can be called again if new elements are added . [CODESPLIT] public boolean finish ( ) { boolean ok = true ; java . util . Iterator iter ; logger . debug ( \"Now finish \" + getName ( ) + \" id= \" + getID ( ) ) ; authorityName = null ; dataType = null ; dataFormatType = null ; defaultService = null ; gc = null ; tc = null ; docs = new ArrayList <> ( ) ; metadata = new ArrayList <> ( ) ; properties = new ArrayList <> ( ) ; creators = new ArrayList <> ( ) ; contributors = new ArrayList <> ( ) ; dates = new ArrayList <> ( ) ; keywords = new ArrayList <> ( ) ; projects = new ArrayList <> ( ) ; publishers = new ArrayList <> ( ) ; variables = new ArrayList <> ( ) ; canonicalize ( ) ; // canonicalize thredds metadata transfer2PublicMetadata ( tm , true ) ; // add local metadata transfer2PublicMetadata ( tmi , true ) ; // add local inherited metadata transferInheritable2PublicMetadata ( ( InvDatasetImpl ) getParent ( ) ) ; // add inheritable metadata from parents // build the expanded access list access = new ArrayList <> ( ) ; // add access element if urlPath is specified if ( ( urlPath != null ) && ( getServiceDefault ( ) != null ) ) { InvAccessImpl a = new InvAccessImpl ( this , urlPath , getServiceDefault ( ) ) ; a . setSize ( size ) ; a . finish ( ) ; addExpandedAccess ( a ) ; } // add local access elements iter = accessLocal . iterator ( ) ; while ( iter . hasNext ( ) ) { InvAccessImpl a = ( InvAccessImpl ) iter . next ( ) ; a . finish ( ) ; addExpandedAccess ( a ) ; } // recurse into child datasets. if ( ! ( this instanceof InvCatalogRef ) ) { for ( InvDataset invDataset : this . getDatasets ( ) ) { InvDatasetImpl curDs = ( InvDatasetImpl ) invDataset ; ok &= curDs . finish ( ) ; } } return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look for InvMetadata elements in the parent that need to be added to the public metadata of this dataset . Recurse up through all ancestors . [CODESPLIT] private void transferInheritable2PublicMetadata ( InvDatasetImpl parent ) { if ( parent == null ) return ; logger . debug ( \" inheritFromParent= \" + parent . getID ( ) ) ; transfer2PublicMetadata ( parent . getLocalMetadataInheritable ( ) , true ) ; //transfer2PublicMetadata(parent.getCat6Metadata(), true); /* look through local metadata, find inherited InvMetadata elements\n    ThreddsMetadata tmd = parent.getLocalMetadata();\n    Iterator iter = tmd.getMetadata().iterator();\n    while (iter.hasNext()) {\n      InvMetadata meta = (InvMetadata) iter.next();\n      if (meta.isInherited()) {\n        if (!meta.isThreddsMetadata()) {\n          metadata.add(meta);\n        } else {\n          if (debugInherit) System.out.println(\"  inheritMetadata Element \" + tmd.isInherited() + \" \" + meta.isInherited());\n          meta.finish(); // make sure XLink is read in.\n          transfer2PublicMetadata(meta.getThreddsMetadata(), false);\n        }\n      }\n    } */ // recurse transferInheritable2PublicMetadata ( ( InvDatasetImpl ) parent . getParent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "take all elements from tmd and add to the public metadata of this dataset . for InvMetadata elements only add if inheritAll || InvMetadata . isInherited () . [CODESPLIT] private void transfer2PublicMetadata ( ThreddsMetadata tmd , boolean inheritAll ) { if ( tmd == null ) return ; logger . debug ( \"  transferMetadata \" + tmd ) ; if ( authorityName == null ) authorityName = tmd . getAuthority ( ) ; if ( dataType == null || ( dataType == FeatureType . ANY ) ) dataType = tmd . getDataType ( ) ; if ( dataFormatType == null || dataFormatType == DataFormatType . NONE ) dataFormatType = tmd . getDataFormatType ( ) ; if ( defaultService == null ) defaultService = findService ( tmd . getServiceName ( ) ) ; if ( gc == null ) { ThreddsMetadata . GeospatialCoverage tgc = tmd . getGeospatialCoverage ( ) ; if ( ( tgc != null ) && ! tgc . isEmpty ( ) ) gc = tgc ; } if ( tc == null ) { DateRange ttc = tmd . getTimeCoverage ( ) ; if ( ttc != null ) { tc = ttc ; } } if ( tc == null ) tc = tmd . getTimeCoverage ( ) ; for ( InvProperty item : tmd . getProperties ( ) ) { logger . debug ( \"  add Property \" + item + \" to \" + getID ( ) ) ; properties . add ( item ) ; } creators . addAll ( tmd . getCreators ( ) ) ; contributors . addAll ( tmd . getContributors ( ) ) ; dates . addAll ( tmd . getDates ( ) ) ; docs . addAll ( tmd . getDocumentation ( ) ) ; keywords . addAll ( tmd . getKeywords ( ) ) ; projects . addAll ( tmd . getProjects ( ) ) ; publishers . addAll ( tmd . getPublishers ( ) ) ; variables . addAll ( tmd . getVariables ( ) ) ; if ( variableMapLink == null ) variableMapLink = tmd . variableMapLink ; for ( InvMetadata meta : tmd . getMetadata ( ) ) { if ( meta . isInherited ( ) || inheritAll ) { if ( ! meta . isThreddsMetadata ( ) ) { metadata . add ( meta ) ; } else { logger . debug ( \"  add metadata Element \" + tmd . isInherited ( ) + \" \" + meta ) ; meta . finish ( ) ; // make sure XLink is read in. transfer2PublicMetadata ( meta . getThreddsMetadata ( ) , inheritAll ) ; metadata . add ( meta ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transfer all inheritable metadata from fromDs to the local metadata of this dataset . Called by InvDatasetScan to transfer inheritable metaddata to the nested catalogRef [CODESPLIT] public void transferMetadata ( InvDatasetImpl fromDs , boolean copyInheritedMetadataFromParents ) { if ( fromDs == null ) return ; logger . debug ( \" transferMetadata= \" + fromDs . getName ( ) ) ; if ( this != fromDs ) getLocalMetadata ( ) . add ( fromDs . getLocalMetadata ( ) , false ) ; transferInheritableMetadata ( fromDs , getLocalMetadataInheritable ( ) , copyInheritedMetadataFromParents ) ; setResourceControl ( fromDs . getRestrictAccess ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transfer inherited metadata consolidating it into target [CODESPLIT] private void transferInheritableMetadata ( InvDatasetImpl fromDs , ThreddsMetadata target , boolean copyInheritedMetadataFromParents ) { if ( fromDs == null ) return ; logger . debug ( \" transferInheritedMetadata= \" + fromDs . getName ( ) ) ; target . add ( fromDs . getLocalMetadataInheritable ( ) , true ) ; /* look through local metadata, find inherited InvMetadata elements\n    ThreddsMetadata tmd = fromDs.getLocalMetadata();\n    Iterator iter = tmd.getMetadata().iterator();\n    while (iter.hasNext()) {\n      InvMetadata meta = (InvMetadata) iter.next();\n      if (meta.isInherited()) {\n        if (!meta.isThreddsMetadata()) {\n          tmc.addMetadata( meta);\n        } else {\n          logger.debug(\"  transferInheritedMetadata \"+meta.hashCode()+\" = \"+meta);\n          meta.finish(); // LOOK ?? make sure XLink is read in.\n          tmc.add( meta.getThreddsMetadata(), true);\n        }\n      }\n    }   */ // now do the same for the parents if ( copyInheritedMetadataFromParents ) transferInheritableMetadata ( ( InvDatasetImpl ) fromDs . getParent ( ) , target , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put metadata into canonical form . All non - inherited thredds metadata put into single metadata element pointed to by getLocalMetadata () . All inherited thredds metadata put into single metadata element pointed to by getLocalMetadataInherited () . This is needed to do reliable editing . [CODESPLIT] protected void canonicalize ( ) { List < InvMetadata > whatsLeft = new ArrayList <> ( ) ; List < InvMetadata > original = new ArrayList <> ( tm . metadata ) ; // get copy of metadata tm . metadata = new ArrayList <> ( ) ; // transfer all non-inherited thredds metadata to tm // transfer all inherited thredds metadata to tmi for ( InvMetadata m : original ) { if ( m . isThreddsMetadata ( ) && ! m . isInherited ( ) && ! m . hasXlink ( ) ) { ThreddsMetadata nested = m . getThreddsMetadata ( ) ; tm . add ( nested , false ) ; } else if ( m . isThreddsMetadata ( ) && m . isInherited ( ) && ! m . hasXlink ( ) ) { ThreddsMetadata nested = m . getThreddsMetadata ( ) ; tmi . add ( nested , true ) ; } else { whatsLeft . add ( m ) ; } } // non ThreddsMetadata goes into tm tm . metadata . addAll ( whatsLeft ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK these are wrong [CODESPLIT] public void setContributors ( List < ThreddsMetadata . Contributor > a ) { List < ThreddsMetadata . Contributor > dest = tm . getContributors ( ) ; for ( ThreddsMetadata . Contributor item : a ) { if ( ! dest . contains ( item ) ) dest . add ( item ) ; } hashCode = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a nested dataset at the location indicated by index . [CODESPLIT] public void addDataset ( int index , InvDatasetImpl ds ) { if ( ds == null ) return ; ds . setParent ( this ) ; datasets . add ( index , ds ) ; hashCode = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given dataset element from this dataset if it is in the dataset . [CODESPLIT] public boolean removeDataset ( InvDatasetImpl ds ) { if ( this . datasets . remove ( ds ) ) { ds . setParent ( null ) ; InvCatalogImpl cat = ( InvCatalogImpl ) getParentCatalog ( ) ; if ( cat != null ) cat . removeDatasetByID ( ds ) ; return ( true ) ; } return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the given dataset if it is a nesetd dataset . [CODESPLIT] public boolean replaceDataset ( InvDatasetImpl remove , InvDatasetImpl add ) { for ( int i = 0 ; i < datasets . size ( ) ; i ++ ) { InvDataset dataset = datasets . get ( i ) ; if ( dataset . equals ( remove ) ) { datasets . set ( i , add ) ; InvCatalogImpl cat = ( InvCatalogImpl ) getParentCatalog ( ) ; if ( cat != null ) { cat . removeDatasetByID ( remove ) ; cat . addDatasetByID ( add ) ; } return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a service to this dataset . [CODESPLIT] public void addService ( InvService service ) { // System.out.println(\"--add dataset service= \"+service.getName()); servicesLocal . add ( service ) ; services . add ( service ) ; // add nested servers for ( InvService nested : service . getServices ( ) ) { services . add ( nested ) ; // System.out.println(\"--add expanded service= \"+nested.getName()); } hashCode = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a service from this dataset . [CODESPLIT] public void removeService ( InvService service ) { servicesLocal . remove ( service ) ; services . remove ( service ) ; // remove nested servers for ( InvService nested : service . getServices ( ) ) { services . remove ( nested ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the list of services attached specifically to this dataset . Discard any previous servies . [CODESPLIT] public void setServicesLocal ( java . util . List < InvService > s ) { this . services = new ArrayList <> ( ) ; this . servicesLocal = new ArrayList <> ( ) ; for ( InvService elem : s ) { addService ( elem ) ; } hashCode = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given InvMetadata from the set of metadata local to this dataset . [CODESPLIT] public boolean removeLocalMetadata ( InvMetadata metadata ) { InvDatasetImpl parentDataset = ( ( InvDatasetImpl ) metadata . getParentDataset ( ) ) ; List localMdata = parentDataset . getLocalMetadata ( ) . getMetadata ( ) ; if ( localMdata . contains ( metadata ) ) { if ( localMdata . remove ( metadata ) ) { hashCode = 0 ; // Need to recalculate the hash code. return ( true ) ; } } return ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look up the User property having the given key [CODESPLIT] public Object getUserProperty ( Object key ) { if ( userMap == null ) return null ; return userMap . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an Html representation of the given dataset . <p > With datasetEvents catrefEvents = true this is used to construct an HTML page on the client ( eg using HtmlPage ) ; the client then detects URL clicks and processes . <p > With datasetEvents catrefEvents = false this is used to construct an HTML page on the server . ( eg using HtmlPage ) ; the client then detects URL clicks and processes . [CODESPLIT] static public void writeHtmlDescription ( StringBuilder buff , InvDatasetImpl ds , boolean complete , boolean isServer , boolean datasetEvents , boolean catrefEvents , boolean resolveRelativeUrls ) { if ( ds == null ) return ; if ( complete ) { buff . append ( \"<!DOCTYPE html PUBLIC \\\"-//W3C//DTD HTML 4.01 Transitional//EN\\\"\\n\" ) . append ( \"        \\\"http://www.w3.org/TR/html4/loose.dtd\\\">\\n\" ) . append ( \"<html>\\n\" ) ; buff . append ( \"<head>\" ) ; buff . append ( \"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=iso-8859-1\\\">\" ) ; buff . append ( \"</head>\" ) ; buff . append ( \"<body>\\n\" ) ; } buff . append ( \"<h2>Dataset: \" ) . append ( ds . getFullName ( ) ) . append ( \"</h2>\\n<ul>\\n\" ) ; if ( ( ds . getDataFormatType ( ) != null ) && ( ds . getDataFormatType ( ) != DataFormatType . NONE ) ) buff . append ( \" <li><em>Data format: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( ds . getDataFormatType ( ) . toString ( ) ) ) . append ( \"</li>\\n\" ) ; if ( ( ds . getDataSize ( ) != 0.0 ) && ! Double . isNaN ( ds . getDataSize ( ) ) ) buff . append ( \" <li><em>Data size: </em>\" ) . append ( Format . formatByteSize ( ds . getDataSize ( ) ) ) . append ( \"</li>\\n\" ) ; if ( ( ds . getDataType ( ) != null ) && ( ds . getDataType ( ) != FeatureType . ANY ) ) buff . append ( \" <li><em>Data type: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( ds . getDataType ( ) . toString ( ) ) ) . append ( \"</li>\\n\" ) ; if ( ( ds . getCollectionType ( ) != null ) && ( ds . getCollectionType ( ) != CollectionType . NONE ) ) buff . append ( \" <li><em>Collection type: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( ds . getCollectionType ( ) . toString ( ) ) ) . append ( \"</li>\\n\" ) ; if ( ds . isHarvest ( ) ) buff . append ( \" <li><em>Harvest: </em>\" ) . append ( ds . isHarvest ( ) ) . append ( \"</li>\\n\" ) ; if ( ds . getAuthority ( ) != null ) buff . append ( \" <li><em>Naming Authority: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( ds . getAuthority ( ) ) ) . append ( \"</li>\\n\" ) ; if ( ds . getID ( ) != null ) buff . append ( \" <li><em>ID: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( ds . getID ( ) ) ) . append ( \"</li>\\n\" ) ; if ( ds . getRestrictAccess ( ) != null ) buff . append ( \" <li><em>RestrictAccess: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( ds . getRestrictAccess ( ) ) ) . append ( \"</li>\\n\" ) ; if ( ds instanceof InvCatalogRef ) { InvCatalogRef catref = ( InvCatalogRef ) ds ; String href = resolveRelativeUrls || catrefEvents ? resolve ( ds , catref . getXlinkHref ( ) ) : catref . getXlinkHref ( ) ; if ( catrefEvents ) href = \"catref:\" + href ; buff . append ( \" <li><em>CatalogRef: </em>\" ) . append ( makeHref ( href , null ) ) . append ( \"</li>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; java . util . List < InvDocumentation > docs = ds . getDocumentation ( ) ; if ( docs . size ( ) > 0 ) { buff . append ( \"<h3>Documentation:</h3>\\n<ul>\\n\" ) ; for ( InvDocumentation doc : docs ) { String type = ( doc . getType ( ) == null ) ? \"\" : \"<strong>\" + StringUtil2 . quoteHtmlContent ( doc . getType ( ) ) + \":</strong> \" ; String inline = doc . getInlineContent ( ) ; if ( ( inline != null ) && ( inline . length ( ) > 0 ) ) buff . append ( \" <li>\" ) . append ( type ) . append ( StringUtil2 . quoteHtmlContent ( inline ) ) . append ( \"</li>\\n\" ) ; if ( doc . hasXlink ( ) ) { // buff.append(\" <li>\" + type + makeHrefResolve(ds, url.toString(), doc.getXlinkTitle()) + \"</a>\\n\"); buff . append ( \" <li>\" ) . append ( type ) . append ( makeHref ( doc . getXlinkHref ( ) , doc . getXlinkTitle ( ) ) ) . append ( \"</li>\\n\" ) ; } } buff . append ( \"</ul>\\n\" ) ; } java . util . List < InvAccess > access = ds . getAccess ( ) ; if ( access . size ( ) > 0 ) { buff . append ( \"<h3>Access:</h3>\\n<ol>\\n\" ) ; for ( InvAccess a : access ) { InvService s = a . getService ( ) ; String urlString = resolveRelativeUrls || datasetEvents ? a . getStandardUrlName ( ) : a . getUnresolvedUrlName ( ) ; String fullUrlString = urlString ; if ( datasetEvents ) fullUrlString = \"dataset:\" + fullUrlString ; if ( isServer ) { ServiceType stype = s . getServiceType ( ) ; if ( ( stype == ServiceType . OPENDAP ) || ( stype == ServiceType . DODS ) ) fullUrlString = fullUrlString + \".html\" ; else if ( stype == ServiceType . DAP4 ) fullUrlString = fullUrlString + \".dmr.xml\" ; else if ( stype == ServiceType . WCS ) fullUrlString = fullUrlString + \"?service=WCS&version=1.0.0&request=GetCapabilities\" ; else if ( stype == ServiceType . WMS ) fullUrlString = fullUrlString + \"?service=WMS&version=1.3.0&request=GetCapabilities\" ; //NGDC update 8/18/2011 else if ( stype == ServiceType . NCML || stype == ServiceType . UDDC || stype == ServiceType . ISO ) { String catalogUrl = ds . getCatalogUrl ( ) ; String datasetId = ds . id ; if ( catalogUrl . indexOf ( ' ' ) > 0 ) catalogUrl = catalogUrl . substring ( 0 , catalogUrl . lastIndexOf ( ' ' ) ) ; try { catalogUrl = URLEncoder . encode ( catalogUrl , \"UTF-8\" ) ; datasetId = URLEncoder . encode ( datasetId , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } fullUrlString = fullUrlString + \"?catalog=\" + catalogUrl + \"&dataset=\" + datasetId ; } else if ( stype == ServiceType . NetcdfSubset ) fullUrlString = fullUrlString + \"/dataset.html\" ; else if ( ( stype == ServiceType . CdmRemote ) || ( stype == ServiceType . CdmrFeature ) ) fullUrlString = fullUrlString + \"?req=form\" ; } buff . append ( \" <li> <b>\" ) . append ( StringUtil2 . quoteHtmlContent ( s . getServiceType ( ) . toString ( ) ) ) ; buff . append ( \":</b> \" ) . append ( makeHref ( fullUrlString , urlString ) ) . append ( \"</li>\\n\" ) ; } buff . append ( \"</ol>\\n\" ) ; } java . util . List < ThreddsMetadata . Contributor > contributors = ds . getContributors ( ) ; if ( contributors . size ( ) > 0 ) { buff . append ( \"<h3>Contributors:</h3>\\n<ul>\\n\" ) ; for ( ThreddsMetadata . Contributor t : contributors ) { String role = ( t . getRole ( ) == null ) ? \"\" : \"<strong> (\" + StringUtil2 . quoteHtmlContent ( t . getRole ( ) ) + \")</strong> \" ; buff . append ( \" <li>\" ) . append ( StringUtil2 . quoteHtmlContent ( t . getName ( ) ) ) . append ( role ) . append ( \"</li>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; } java . util . List < ThreddsMetadata . Vocab > keywords = ds . getKeywords ( ) ; if ( keywords . size ( ) > 0 ) { buff . append ( \"<h3>Keywords:</h3>\\n<ul>\\n\" ) ; for ( ThreddsMetadata . Vocab t : keywords ) { String vocab = ( t . getVocabulary ( ) == null ) ? \"\" : \" <strong>(\" + StringUtil2 . quoteHtmlContent ( t . getVocabulary ( ) ) + \")</strong> \" ; buff . append ( \" <li>\" ) . append ( StringUtil2 . quoteHtmlContent ( t . getText ( ) ) ) . append ( vocab ) . append ( \"</li>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; } java . util . List < DateType > dates = ds . getDates ( ) ; if ( dates . size ( ) > 0 ) { buff . append ( \"<h3>Dates:</h3>\\n<ul>\\n\" ) ; for ( DateType d : dates ) { String type = ( d . getType ( ) == null ) ? \"\" : \" <strong>(\" + StringUtil2 . quoteHtmlContent ( d . getType ( ) ) + \")</strong> \" ; buff . append ( \" <li>\" ) . append ( StringUtil2 . quoteHtmlContent ( d . getText ( ) ) ) . append ( type ) . append ( \"</li>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; } java . util . List < ThreddsMetadata . Vocab > projects = ds . getProjects ( ) ; if ( projects . size ( ) > 0 ) { buff . append ( \"<h3>Projects:</h3>\\n<ul>\\n\" ) ; for ( ThreddsMetadata . Vocab t : projects ) { String vocab = ( t . getVocabulary ( ) == null ) ? \"\" : \" <strong>(\" + StringUtil2 . quoteHtmlContent ( t . getVocabulary ( ) ) + \")</strong> \" ; buff . append ( \" <li>\" ) . append ( StringUtil2 . quoteHtmlContent ( t . getText ( ) ) ) . append ( vocab ) . append ( \"</li>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; } java . util . List < ThreddsMetadata . Source > creators = ds . getCreators ( ) ; if ( creators . size ( ) > 0 ) { buff . append ( \"<h3>Creators:</h3>\\n<ul>\\n\" ) ; for ( ThreddsMetadata . Source t : creators ) { buff . append ( \" <li><strong>\" ) . append ( StringUtil2 . quoteHtmlContent ( t . getName ( ) ) ) . append ( \"</strong><ul>\\n\" ) ; buff . append ( \" <li><em>email: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( t . getEmail ( ) ) ) . append ( \"</li>\\n\" ) ; if ( t . getUrl ( ) != null ) { String newUrl = resolveRelativeUrls ? makeHrefResolve ( ds , t . getUrl ( ) , null ) : makeHref ( t . getUrl ( ) , null ) ; buff . append ( \" <li> <em>\" ) . append ( newUrl ) . append ( \"</em></li>\\n\" ) ; } buff . append ( \" </ul></li>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; } java . util . List < ThreddsMetadata . Source > publishers = ds . getPublishers ( ) ; if ( publishers . size ( ) > 0 ) { buff . append ( \"<h3>Publishers:</h3>\\n<ul>\\n\" ) ; for ( ThreddsMetadata . Source t : publishers ) { buff . append ( \" <li><strong>\" ) . append ( StringUtil2 . quoteHtmlContent ( t . getName ( ) ) ) . append ( \"</strong><ul>\\n\" ) ; buff . append ( \" <li><em>email: </em>\" ) . append ( StringUtil2 . quoteHtmlContent ( t . getEmail ( ) ) ) . append ( \"\\n\" ) ; if ( t . getUrl ( ) != null ) { String urlLink = resolveRelativeUrls ? makeHrefResolve ( ds , t . getUrl ( ) , null ) : makeHref ( t . getUrl ( ) , null ) ; buff . append ( \" <li> <em>\" ) . append ( urlLink ) . append ( \"</em>\\n\" ) ; } buff . append ( \" </ul>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; } /*\n    4.2:\n    <h3>Variables:</h3>\n    <ul>\n    <li><em>Vocabulary</em> [DIF]:\n    <ul>\n     <li><strong>Reflectivity</strong> =  <i></i> = EARTH SCIENCE &gt; Spectral/Engineering &gt; Radar &gt; Radar Reflectivity (db)\n     <li><strong>Velocity</strong> =  <i></i> = EARTH SCIENCE &gt; Spectral/Engineering &gt; Radar &gt; Doppler Velocity (m/s)\n     <li><strong>SpectrumWidth</strong> =  <i></i> = EARTH SCIENCE &gt; Spectral/Engineering &gt; Radar &gt; Doppler Spectrum Width (m/s)\n     </ul>\n     </ul>\n    </ul>\n\n    4.3:\n    <h3>Variables:</h3>\n    <ul>\n    <li><em>Vocabulary</em> [CF-1.0]:\n    <ul>\n     <li><strong>d3d (meters) </strong> =  <i>3D Depth at Nodes\n    <p>        </i> = depth_at_nodes\n     <li><strong>depth (meters) </strong> =  <i>Bathymetry</i> = depth\n     <li><strong>eta (m) </strong> =  <i></i> =\n     <li><strong>temp (Celsius) </strong> =  <i>Temperature\n    <p>        </i> = sea_water_temperature\n     <li><strong>u (m/s) </strong> =  <i>Eastward Water\n    <p>          Velocity\n    <p>        </i> = eastward_sea_water_velocity\n     <li><strong>v (m/s) </strong> =  <i>Northward Water\n    <p>          Velocity\n    <p>        </i> = northward_sea_water_velocity\n    </ul>\n    </ul>\n     */ java . util . List < ThreddsMetadata . Variables > vars = ds . getVariables ( ) ; if ( vars . size ( ) > 0 ) { buff . append ( \"<h3>Variables:</h3>\\n<ul>\\n\" ) ; for ( ThreddsMetadata . Variables t : vars ) { buff . append ( \"<li><em>Vocabulary</em> [\" ) ; if ( t . getVocabUri ( ) != null ) { URI uri = t . getVocabUri ( ) ; String vocabLink = resolveRelativeUrls ? makeHrefResolve ( ds , uri . toString ( ) , t . getVocabulary ( ) ) : makeHref ( uri . toString ( ) , t . getVocabulary ( ) ) ; buff . append ( vocabLink ) ; } else { buff . append ( StringUtil2 . quoteHtmlContent ( t . getVocabulary ( ) ) ) ; } buff . append ( \"]:\\n<ul>\\n\" ) ; java . util . List < ThreddsMetadata . Variable > vlist = t . getVariableList ( ) ; if ( vlist . size ( ) > 0 ) { for ( ThreddsMetadata . Variable v : vlist ) { String units = ( v . getUnits ( ) == null || v . getUnits ( ) . length ( ) == 0 ) ? \"\" : \" (\" + v . getUnits ( ) + \") \" ; buff . append ( \" <li><strong>\" ) . append ( StringUtil2 . quoteHtmlContent ( v . getName ( ) + units ) ) . append ( \"</strong> = \" ) ; String desc = ( v . getDescription ( ) == null ) ? \"\" : \" <i>\" + StringUtil2 . quoteHtmlContent ( v . getDescription ( ) ) + \"</i> = \" ; buff . append ( desc ) ; if ( v . getVocabularyName ( ) != null ) buff . append ( StringUtil2 . quoteHtmlContent ( v . getVocabularyName ( ) ) ) ; buff . append ( \"\\n\" ) ; } } buff . append ( \"</ul>\\n\" ) ; } buff . append ( \"</ul>\\n\" ) ; } if ( ds . getVariableMapLink ( ) != null ) { buff . append ( \"<h3>Variables:</h3>\\n\" ) ; buff . append ( \"<ul><li>\" + makeHref ( ds . getVariableMapLink ( ) , \"VariableMap\" ) + \"</li></ul>\\n\" ) ; } ThreddsMetadata . GeospatialCoverage gc = ds . getGeospatialCoverage ( ) ; if ( ( gc != null ) && ! gc . isEmpty ( ) ) { buff . append ( \"<h3>GeospatialCoverage:</h3>\\n<ul>\\n\" ) ; if ( gc . isGlobal ( ) ) buff . append ( \" <li><em> Global </em>\\n\" ) ; buff . append ( \" <li><em> Longitude: </em> \" ) . append ( rangeString ( gc . getEastWestRange ( ) ) ) . append ( \"</li>\\n\" ) ; buff . append ( \" <li><em> Latitude: </em> \" ) . append ( rangeString ( gc . getNorthSouthRange ( ) ) ) . append ( \"</li>\\n\" ) ; if ( gc . getUpDownRange ( ) != null ) { buff . append ( \" <li><em> Altitude: </em> \" ) . append ( rangeString ( gc . getUpDownRange ( ) ) ) . append ( \" (positive is <strong>\" ) . append ( StringUtil2 . quoteHtmlContent ( gc . getZPositive ( ) ) ) . append ( \")</strong></li>\\n\" ) ; } java . util . List < ThreddsMetadata . Vocab > nlist = gc . getNames ( ) ; if ( ( nlist != null ) && ( nlist . size ( ) > 0 ) ) { buff . append ( \" <li><em>  Names: </em> <ul>\\n\" ) ; for ( ThreddsMetadata . Vocab elem : nlist ) { buff . append ( \" <li>\" ) . append ( StringUtil2 . quoteHtmlContent ( elem . getText ( ) ) ) . append ( \"\\n\" ) ; } buff . append ( \" </ul>\\n\" ) ; } buff . append ( \" </ul>\\n\" ) ; } CalendarDateRange tc = ds . getCalendarDateCoverage ( ) ; if ( tc != null ) { buff . append ( \"<h3>TimeCoverage:</h3>\\n<ul>\\n\" ) ; CalendarDate start = tc . getStart ( ) ; if ( start != null ) buff . append ( \" <li><em>  Start: </em> \" ) . append ( start . toString ( ) ) . append ( \"\\n\" ) ; CalendarDate end = tc . getEnd ( ) ; if ( end != null ) { buff . append ( \" <li><em>  End: </em> \" ) . append ( end . toString ( ) ) . append ( \"\\n\" ) ; } CalendarDuration duration = tc . getDuration ( ) ; if ( duration != null ) buff . append ( \" <li><em>  Duration: </em> \" ) . append ( StringUtil2 . quoteHtmlContent ( duration . toString ( ) ) ) . append ( \"\\n\" ) ; CalendarDuration resolution = tc . getResolution ( ) ; if ( resolution != null ) { buff . append ( \" <li><em>  Resolution: </em> \" ) . append ( StringUtil2 . quoteHtmlContent ( resolution . toString ( ) ) ) . append ( \"\\n\" ) ; } buff . append ( \" </ul>\\n\" ) ; } java . util . List < InvMetadata > metadata = ds . getMetadata ( ) ; boolean gotSomeMetadata = false ; for ( InvMetadata m : metadata ) { if ( m . hasXlink ( ) ) gotSomeMetadata = true ; } if ( gotSomeMetadata ) { buff . append ( \"<h3>Metadata:</h3>\\n<ul>\\n\" ) ; for ( InvMetadata m : metadata ) { String type = ( m . getMetadataType ( ) == null ) ? \"\" : m . getMetadataType ( ) ; if ( m . hasXlink ( ) ) { String title = ( m . getXlinkTitle ( ) == null ) ? \"Type \" + type : m . getXlinkTitle ( ) ; String mdLink = resolveRelativeUrls ? makeHrefResolve ( ds , m . getXlinkHref ( ) , title ) : makeHref ( m . getXlinkHref ( ) , title ) ; buff . append ( \" <li> \" ) . append ( mdLink ) . append ( \"\\n\" ) ; } //else { //buff.append(\" <li> <pre>\"+m.getMetadataType()+\" \"+m.getContentObject()+\"</pre>\\n\"); //} } buff . append ( \"</ul>\\n\" ) ; } java . util . List < InvProperty > propsOrg = ds . getProperties ( ) ; java . util . List < InvProperty > props = new ArrayList <> ( ds . getProperties ( ) . size ( ) ) ; for ( InvProperty p : propsOrg ) { if ( ! p . getName ( ) . startsWith ( \"viewer\" ) ) // eliminate the viewer properties from the html view props . add ( p ) ; } if ( props . size ( ) > 0 ) { buff . append ( \"<h3>Properties:</h3>\\n<ul>\\n\" ) ; for ( InvProperty p : props ) { if ( p . getName ( ) . equals ( \"attachments\" ) ) // LOOK whats this ? { String attachLink = resolveRelativeUrls ? makeHrefResolve ( ds , p . getValue ( ) , p . getName ( ) ) : makeHref ( p . getValue ( ) , p . getName ( ) ) ; buff . append ( \" <li>\" ) . append ( attachLink ) . append ( \"\\n\" ) ; } else { buff . append ( \" <li>\" ) . append ( StringUtil2 . quoteHtmlContent ( p . getName ( ) + \" = \\\"\" + p . getValue ( ) ) ) . append ( \"\\\"\\n\" ) ; } } buff . append ( \"</ul>\\n\" ) ; } if ( complete ) buff . append ( \"</body></html>\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolve reletive URLS against the catalog URL . [CODESPLIT] static public String resolve ( InvDataset ds , String href ) { InvCatalog cat = ds . getParentCatalog ( ) ; if ( cat != null ) { try { java . net . URI uri = cat . resolveUri ( href ) ; href = uri . toString ( ) ; } catch ( java . net . URISyntaxException e ) { logger . warn ( \"InvDatasetImpl.writeHtml: error parsing URL= \" + href ) ; } } return href ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate this DatasetNamer object . Return true if valid false if invalid . [CODESPLIT] boolean validate ( StringBuilder out ) { this . isValid = true ; // If log from construction has content, append to validation output msg. if ( this . msgLog . length ( ) > 0 ) { out . append ( this . msgLog ) ; } // Check that name is not null (it can be an empty string). if ( this . getName ( ) == null ) { this . isValid = false ; out . append ( \" ** DatasetNamer (1): null value for name is not valid.\" ) ; } // Check that addLevel is not null. // boolean can't be null //if ( this.getAddLevel() == null) //{ //  this.isValid = false; //  out.append(\" ** DatasetNamer (2): null value for addLevel is not valid.\"); //} // Check that type is not null. if ( this . getType ( ) == null ) { this . isValid = false ; out . append ( \" ** DatasetNamer (3): null value for type is not valid (set with bad string?).\" ) ; } if ( this . getType ( ) == DatasetNamerType . REGULAR_EXPRESSION && ( this . getMatchPattern ( ) == null || this . getSubstitutePattern ( ) == null ) ) { this . isValid = false ; out . append ( \" ** DatasetNamer (4): invalid datasetNamer <\" + this . getName ( ) + \">;\" + \" type is \" + this . getType ( ) . toString ( ) + \": matchPattern(\" + this . getMatchPattern ( ) + \") and substitutionPattern(\" + this . getSubstitutePattern ( ) + \") \" + \"must not be null.\" ) ; } if ( this . getType ( ) == DatasetNamerType . DODS_ATTRIBUTE && ( this . getAttribContainer ( ) == null || this . getAttribName ( ) == null ) ) { this . isValid = false ; out . append ( \" ** DatasetNamer (5): invalid datasetNamer <\" + this . getName ( ) + \">;\" + \" type is \" + this . getType ( ) . toString ( ) + \": attriuteContainer(\" + this . getAttribContainer ( ) + \") and attributeName(\" + this . getAttribName ( ) + \") must not be null.\" ) ; } return ( this . isValid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to name the given dataset . [CODESPLIT] public boolean nameDataset ( InvDatasetImpl dataset ) { if ( this . type == DatasetNamerType . REGULAR_EXPRESSION ) { return ( this . nameDatasetRegExp ( dataset ) ) ; } /* else if (this.type == DatasetNamerType.DODS_ATTRIBUTE) {\n      return (this.nameDatasetDodsAttrib(dataset));\n    } */ else { String tmpMsg = \"This DatasetNamer <\" + this . getName ( ) + \"> has unsupported type <\" + this . type . toString ( ) + \">.\" ; logger . error ( \"nameDataset(): \" + tmpMsg ) ; throw new IllegalStateException ( tmpMsg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to name the given dataset . [CODESPLIT] public boolean nameDatasetList ( java . util . List datasetList ) throws java . lang . Exception { boolean returnValue = false ; InvDatasetImpl curDataset = null ; for ( int i = 0 ; i < datasetList . size ( ) ; i ++ ) { curDataset = ( InvDatasetImpl ) datasetList . get ( i ) ; returnValue &= this . nameDataset ( curDataset ) ; } return ( returnValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get list of data descriptors as Strings [CODESPLIT] public final List < String > getDescriptors ( ) { List < String > desc = new ArrayList < String > ( ) ; for ( short fxy : descriptors ) desc . ( Descriptor . makeString ( fxy ) ) ; return desc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize [CODESPLIT] private void init ( double a , double f , int zone , boolean hemisphere_north ) { A = a ; F = 1.0 / f ; // F is flattening\r this . zone = zone ; this . hemisphere_north = hemisphere_north ; //  Create the ERM constants.\r Eps2 = ( F ) * ( 2.0 - F ) ; Eps25 = .25 * ( Eps2 ) ; EF = F / ( 2.0 - F ) ; Con2 = 2 / ( 1.0 - Eps2 ) ; Con6 = .166666666666667 ; Con24 = 4 * .0416666666666667 / ( 1 - Eps2 ) ; Con120 = .00833333333333333 ; Con720 = 4 * .00138888888888888 / ( 1 - Eps2 ) ; double polx1a = 1.0 - Eps2 / 4.0 - 3.0 / 64.0 * Math . pow ( Eps2 , 2 ) - 5.0 / 256.0 * Math . pow ( Eps2 , 3 ) - 175.0 / 16384.0 * Math . pow ( Eps2 , 4 ) ; conap = A * polx1a ; double polx2a = 3.0 / 2.0 * EF - 27.0 / 32.0 * Math . pow ( EF , 3 ) ; double polx4a = 21.0 / 16.0 * Math . pow ( EF , 2 ) - 55.0 / 32.0 * Math . pow ( EF , 4 ) ; double polx6a = 151.0 / 96.0 * Math . pow ( EF , 3 ) ; double polx8a = 1097.0 / 512.0 * Math . pow ( EF , 4 ) ; polx2b = polx2a * 2.0 + polx4a * 4.0 + polx6a * 6.0 + polx8a * 8.0 ; polx3b = polx4a * - 8.0 - polx6a * 32.0 - 80.0 * polx8a ; polx4b = polx6a * 32.0 + 192.0 * polx8a ; polx5b = - 128.0 * polx8a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Difficult thing is to return the extra line assocated with the previous good log We do this by not returning until we get a match on the next log . We have to rewind . [CODESPLIT] public LogReader . Log nextLog ( BufferedReader dataIS ) throws IOException { ServletLog log = new ServletLog ( ) ; boolean haveLog = false ; while ( true ) { dataIS . mark ( 20 * 1000 ) ; // track where we are\r String line = dataIS . readLine ( ) ; if ( line == null ) { return haveLog ? log : null ; } // if (count++ < limit) System.out.println(\"\\n\" + line);                      nTest reqe\r try { Matcher m = commonPattern . matcher ( line ) ; if ( m . matches ( ) ) { if ( haveLog ) { // have a log, next one matches, proceed\r try { dataIS . reset ( ) ; return log ; } catch ( Throwable t ) { System . out . println ( \"Cant reset \" + line ) ; } } haveLog = true ; // next match will return the current log\r log . date = convertDate ( m . group ( 1 ) ) ; log . reqTime = parseLong ( m . group ( 2 ) ) ; log . reqSeq = parseLong ( m . group ( 3 ) ) ; log . level = m . group ( 4 ) . intern ( ) ; log . where = m . group ( 5 ) ; String rest = m . group ( 6 ) ; if ( rest . contains ( \"Request Completed\" ) ) { int pos = rest . indexOf ( \"Request Completed\" ) ; Matcher m2 = donePattern . matcher ( rest . substring ( pos ) ) ; if ( m2 . matches ( ) ) { log . returnCode = parse ( m2 . group ( 1 ) ) ; log . sizeBytes = parseLong ( m2 . group ( 2 ) ) ; log . msecs = parseLong ( m2 . group ( 3 ) ) ; log . isDone = true ; } else { System . out . println ( \"Cant parse donePattern= \" + rest ) ; System . out . println ( \" line= \" + line ) ; log . addExtra ( rest ) ; } } else if ( rest . contains ( \"Remote host\" ) ) { int pos = rest . indexOf ( \"Remote host\" ) ; Matcher m2 = startPattern . matcher ( rest . substring ( pos ) ) ; if ( m2 . matches ( ) ) { log . ip = m2 . group ( 1 ) ; log . verb = m2 . group ( 2 ) . intern ( ) ; log . path = EscapeStrings . urlDecode ( m2 . group ( 3 ) ) ; //old  URLDecoder.decode(m2.group(3));\r if ( m2 . groupCount ( ) > 4 ) log . http = m2 . group ( 4 ) . intern ( ) ; log . isStart = true ; } else { System . out . println ( \"Cant parse startPattern= \" + rest ) ; System . out . println ( \" line= \" + line ) ; log . addExtra ( rest ) ; } } else { // a non-start, non-done log\r log . addExtra ( rest ) ; } } else { // the true extra line\r //System.out.println(\"No match on \" + line);\r log . addExtra ( line ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; System . out . println ( \"Cant parse \" + line ) ; log . addExtra ( line ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs the full server URI from a request [CODESPLIT] public static String constructServerPath ( HttpServletRequest hsreq ) { return hsreq . getScheme ( ) + \"://\" + hsreq . getServerName ( ) + \":\" + hsreq . getServerPort ( ) + \"/thredds/wfs/\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes GetCapabilities requests . [CODESPLIT] private void getCapabilities ( PrintWriter out , HttpServletRequest hsreq , SimpleGeometryCSBuilder sgcs ) { WFSGetCapabilitiesWriter gcdw = new WFSGetCapabilitiesWriter ( out , WFSController . constructServerPath ( hsreq ) ) ; gcdw . startXML ( ) ; gcdw . addOperation ( WFSRequestType . GetCapabilities ) ; gcdw . addOperation ( WFSRequestType . DescribeFeatureType ) ; gcdw . addOperation ( WFSRequestType . GetFeature ) ; gcdw . writeOperations ( ) ; List < String > seriesNames = sgcs . getGeometrySeriesNames ( ) ; for ( String name : seriesNames ) { gcdw . addFeature ( new WFSFeature ( TDSNAMESPACE + \":\" + name , name ) ) ; } gcdw . writeFeatureTypes ( ) ; gcdw . finishXML ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes GetFeature requests . [CODESPLIT] private WFSExceptionWriter getFeature ( PrintWriter out , HttpServletRequest hsreq , SimpleGeometryCSBuilder sgcs , String ftName , String fullFtName ) { List < SimpleGeometry > geometryList = new ArrayList < SimpleGeometry > ( ) ; GeometryType geoT = sgcs . getGeometryType ( ftName ) ; if ( geoT == null ) { return new WFSExceptionWriter ( \"Feature Type of \" + fullFtName + \" not found.\" , \"GetFeature\" , \"OperationProcessingFailed\" ) ; } try { switch ( geoT ) { case POINT : Point pt = sgcs . getPoint ( ftName , 0 ) ; int j = 0 ; while ( pt != null ) { geometryList . add ( pt ) ; j ++ ; pt = sgcs . getPoint ( ftName , j ) ; } break ; case LINE : Line line = sgcs . getLine ( ftName , 0 ) ; int k = 0 ; while ( line != null ) { geometryList . add ( line ) ; k ++ ; line = sgcs . getLine ( ftName , k ) ; } break ; case POLYGON : Polygon poly = sgcs . getPolygon ( ftName , 0 ) ; int i = 0 ; while ( poly != null ) { geometryList . add ( poly ) ; i ++ ; poly = sgcs . getPolygon ( ftName , i ) ; } break ; } } // Perhaps will change this to be implemented in the CFPolygon class\r catch ( ArrayIndexOutOfBoundsException aout ) { } WFSGetFeatureWriter gfdw = new WFSGetFeatureWriter ( out , WFSController . constructServerPath ( hsreq ) , WFSController . getXMLNamespaceXMLNSValue ( hsreq ) , geometryList , ftName ) ; gfdw . startXML ( ) ; gfdw . writeMembers ( ) ; gfdw . finishXML ( ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks request parameters for errors . Will send back an XML Exception if any errors are encountered . [CODESPLIT] private WFSExceptionWriter checkParametersForError ( String request , String version , String service , String typeName ) { // The SERVICE parameter is required. If not specified, is an error (throw exception through XML).\r if ( service != null ) { // For the WFS servlet it must be WFS if not, write out an InvalidParameterValue exception.\r if ( ! service . equalsIgnoreCase ( \"WFS\" ) ) { return new WFSExceptionWriter ( \"WFS Server error. SERVICE parameter must be of value WFS.\" , \"service\" , \"InvalidParameterValue\" ) ; } } else { return new WFSExceptionWriter ( \"WFS server error. SERVICE parameter is required.\" , \"request\" , \"MissingParameterValue\" ) ; } // The REQUEST Parameter is required. If not specified, is an error (throw exception through XML).\r if ( request != null ) { // Only go through version checks if NOT a Get Capabilities request, the VERSION parameter is required for all operations EXCEPT GetCapabilities section 7.6.25 of WFS 2.0 Interface Standard\r if ( ! request . equalsIgnoreCase ( WFSRequestType . GetCapabilities . toString ( ) ) ) { if ( version != null ) { // If the version is not failed report exception VersionNegotiationFailed, from OGC Web Services Common Standard section 7.4.1\r // Get each part\r String [ ] versionParts = version . split ( \"\\\\.\" ) ; for ( int ind = 0 ; ind < versionParts . length ; ind ++ ) { // Check if number will throw NumberFormatException if not.\r try { Integer . valueOf ( versionParts [ ind ] ) ; } /* Version parameters are only allowed to consist of numbers and periods. If this is not the case then\r\n\t\t\t\t\t\t * It qualifies for InvalidParameterException\r\n\t\t\t\t\t\t */ catch ( NumberFormatException excep ) { return new WFSExceptionWriter ( \"WFS server error. VERSION parameter consists of invalid characters.\" , \"version\" , \"InvalidParameterValue\" ) ; } } /* Now the version parts are all constructed from the parameter\r\n\t\t\t\t\t * Analyze for correctness. \r\n\t\t\t\t\t */ boolean validVersion = false ; // If just number 2 is specified, assume 2.0.0, pass the check\r if ( versionParts . length == 1 ) if ( versionParts [ 0 ] . equals ( \"2\" ) ) validVersion = true ; // Two or more version parts specified, make sure it's 2.0.#.#...\r if ( versionParts . length >= 2 ) if ( versionParts [ 0 ] . equals ( \"2\" ) && versionParts [ 1 ] . equals ( \"0\" ) ) validVersion = true ; /* Another exception VersionNegotiationFailed is specified by OGC Web Services Common\r\n\t\t\t\t\t * for version mismatches. If the version check failed print this exception\r\n\t\t\t\t\t */ if ( ! validVersion ) { return new WFSExceptionWriter ( \"WFS Server error. Version requested is not supported.\" , null , \"VersionNegotiationFailed\" ) ; } } else { return new WFSExceptionWriter ( \"WFS server error. VERSION parameter is required.\" , \"request\" , \"MissingParameterValue\" ) ; } // Last check to see if typenames is specified, must be for GetFeature, DescribeFeatureType\r if ( typeName == null ) { return new WFSExceptionWriter ( \"WFS server error. For the specifed request, parameter typename or typenames must be specified.\" , request , \"MissingParameterValue\" ) ; } } WFSRequestType reqToProc = WFSRequestType . getWFSRequestType ( request ) ; if ( reqToProc == null ) return new WFSExceptionWriter ( \"WFS server error. REQUEST parameter is not valid. Possible values: GetCapabilities, \" + \"DescribeFeatureType, GetFeature\" , \"request\" , \"InvalidParameterValue\" ) ; } else { return new WFSExceptionWriter ( \"WFS server error. REQUEST parameter is required.\" , \"request\" , \"MissingParameterValue\" ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A handler for WFS based HTTP requests that sends to other request handlers to handle the request . [CODESPLIT] @ RequestMapping ( \"**\" ) public void httpHandler ( HttpServletRequest hsreq , HttpServletResponse hsres ) { try { PrintWriter wr = hsres . getWriter ( ) ; List < String > paramNames = new LinkedList < String > ( ) ; Enumeration < String > paramNamesE = hsreq . getParameterNames ( ) ; while ( paramNamesE . hasMoreElements ( ) ) paramNames . add ( paramNamesE . nextElement ( ) ) ; // Prepare parameters\r String request = null ; String version = null ; String service = null ; String typeNames = null ; String datasetReqPath = null ; String actualPath = null ; String actualFTName = null ; NetcdfDataset dataset = null ; if ( hsreq . getServletPath ( ) . length ( ) > 4 ) { datasetReqPath = hsreq . getServletPath ( ) . substring ( 4 , hsreq . getServletPath ( ) . length ( ) ) ; } actualPath = TdsRequestedDataset . getLocationFromRequestPath ( datasetReqPath ) ; if ( actualPath != null ) dataset = NetcdfDataset . openDataset ( actualPath ) ; else return ; List < CoordinateSystem > csList = dataset . getCoordinateSystems ( ) ; SimpleGeometryCSBuilder cs = new SimpleGeometryCSBuilder ( dataset , csList . get ( 0 ) , null ) ; /* Look for parameter names to assign values\r\n\t\t\t * in order to avoid casing issues with parameter names (such as a mismatch between reQUEST and request and REQUEST).\r\n\t\t\t */ for ( String paramName : paramNames ) { if ( paramName . equalsIgnoreCase ( \"REQUEST\" ) ) { request = hsreq . getParameter ( paramName ) ; } if ( paramName . equalsIgnoreCase ( \"VERSION\" ) ) { version = hsreq . getParameter ( paramName ) ; } if ( paramName . equalsIgnoreCase ( \"SERVICE\" ) ) { service = hsreq . getParameter ( paramName ) ; } if ( paramName . equalsIgnoreCase ( \"TYPENAMES\" ) || paramName . equalsIgnoreCase ( \"TYPENAME\" ) ) { typeNames = hsreq . getParameter ( paramName ) ; // Remove namespace header for getFeature\r if ( typeNames != null ) if ( typeNames . length ( ) > TDSNAMESPACE . length ( ) ) { actualFTName = typeNames . substring ( TDSNAMESPACE . length ( ) + 1 , typeNames . length ( ) ) ; } } } WFSExceptionWriter paramError = checkParametersForError ( request , version , service , typeNames ) ; WFSExceptionWriter requestProcessingError = null ; // If parameter checks all pass launch the request\r if ( paramError == null ) { WFSRequestType reqToProc = WFSRequestType . getWFSRequestType ( request ) ; switch ( reqToProc ) { case GetCapabilities : getCapabilities ( wr , hsreq , cs ) ; break ; case DescribeFeatureType : describeFeatureType ( wr , hsreq , actualFTName ) ; break ; case GetFeature : requestProcessingError = getFeature ( wr , hsreq , cs , actualFTName , typeNames ) ; break ; } } // Parameter checks did not all pass, print the error and return\r else { paramError . write ( hsres ) ; return ; } /* Specifically writes out exceptions that were incurred\r\n\t\t\t * while processing requests.\r\n\t\t\t */ if ( requestProcessingError != null ) { requestProcessingError . write ( hsres ) ; return ; } } catch ( IOException io ) { throw new RuntimeException ( \"The writer may not have been able to been have retrieved\" + \" or the requested dataset was not found\" , io ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A path is a DAP4 path if at least one of the following is true . 1 . it has dap4 : as its leading protocol 2 . it has #protocol = dap4 in its fragment [CODESPLIT] public boolean dspMatch ( String url , DapContext context ) { try { XURI xuri = new XURI ( url ) ; if ( true ) { boolean found = false ; for ( String scheme : DAP4SCHEMES ) { if ( scheme . equalsIgnoreCase ( xuri . getBaseProtocol ( ) ) || scheme . equalsIgnoreCase ( xuri . getFormatProtocol ( ) ) ) { found = true ; break ; } } if ( ! found ) return false ; // Might still be a non-dap4 url String formatproto = xuri . getFormatProtocol ( ) ; if ( DAP4PROTO . equalsIgnoreCase ( formatproto ) ) return true ; for ( String [ ] pair : DAP4QUERYMARKERS ) { String tag = xuri . getQueryFields ( ) . get ( pair [ 0 ] ) ; if ( tag != null && ( pair [ 1 ] == null || pair [ 1 ] . equalsIgnoreCase ( tag ) ) ) return true ; } for ( String [ ] pair : DAP4FRAGMARKERS ) { String tag = xuri . getFragFields ( ) . get ( pair [ 0 ] ) ; if ( tag != null && ( pair [ 1 ] == null || pair [ 1 ] . equalsIgnoreCase ( tag ) ) ) return true ; } } else return true ; } catch ( URISyntaxException use ) { return false ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a connection and make a request for the ( possibly constrained ) DMR . [CODESPLIT] protected void build ( ) throws DapException { String methodurl = buildURL ( this . xuri . assemble ( XURI . URLONLY ) , DATASUFFIX , this . dmr , this . basece ) ; InputStream stream ; // Make the request and return an input stream for accessing the databuffer // Should fill in bigendian and stream fields stream = callServer ( methodurl ) ; try { ChunkInputStream reader ; if ( DEBUG ) { byte [ ] raw = DapUtil . readbinaryfile ( stream ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( raw ) ; DapDump . dumpbytestream ( raw , getOrder ( ) , \"httpdsp.build\" ) ; reader = new ChunkInputStream ( bis , RequestMode . DAP , getOrder ( ) ) ; } else { // Wrap the input stream as a ChunkInputStream reader = new ChunkInputStream ( stream , RequestMode . DAP , getOrder ( ) ) ; } // Extract and \"compile\" the server response String document = reader . readDMR ( ) ; // Extract all the remaining bytes byte [ ] bytes = DapUtil . readbinaryfile ( reader ) ; // use super.build to compile super . build ( document , bytes , getOrder ( ) ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; throw new DapException ( t ) ; } finally { try { stream . close ( ) ; } catch ( IOException ioe ) { /*ignore*/ } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provide a method for getting the capabilities document . [CODESPLIT] public String getCapabilities ( String url ) throws IOException { // Save the original url String saveurl = this . xuri . getOriginal ( ) ; parseURL ( url ) ; String fdsurl = buildURL ( this . xuri . assemble ( XURI . URLALL ) , DSRSUFFIX , null , null ) ; try { // Make the request and return an input stream for accessing the databuffer // Should fill in context bigendian and stream fields InputStream stream = callServer ( fdsurl ) ; // read the result, convert to string and return. byte [ ] bytes = DapUtil . readbinaryfile ( stream ) ; String document = new String ( bytes , DapUtil . UTF8 ) ; return document ; } finally { parseURL ( saveurl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] static protected String buildURL ( String baseurl , String suffix , DapDataset template , String ce ) { StringBuilder methodurl = new StringBuilder ( ) ; methodurl . append ( baseurl ) ; if ( suffix != null ) { methodurl . append ( ' ' ) ; methodurl . append ( suffix ) ; } if ( ce != null && ce . length ( ) > 0 ) { methodurl . append ( QUERYSTART ) ; methodurl . append ( CONSTRAINTTAG ) ; methodurl . append ( ' ' ) ; methodurl . append ( ce ) ; } return methodurl . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////// CrawlableDatasetFile //////////////////////////////////////// [CODESPLIT] @ Override public File getFile ( ) { try { return threddsS3Client . saveObjectToFile ( s3uri , s3uri . getTempFile ( ) ) ; } catch ( IOException e ) { logger . error ( String . format ( \"Could not save S3 object '%s' to file.\" , s3uri ) , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the size of the dataset in bytes . Will be zero if this dataset is a collection or non - existent . [CODESPLIT] @ Override public long length ( ) { // If the summary is already in the cache, return it. // It'll have been added by a listDatasets() call on the parent directory. S3ObjectSummary objectSummary = objectSummaryCache . getIfPresent ( s3uri ) ; if ( objectSummary != null ) { return objectSummary . getSize ( ) ; } /* Get the metadata directly from S3. This will be expensive.\n         * We get punished hard if length() and/or lastModified() is called on a bunch of datasets without\n         * listDatasets() first being called on their parent directory.\n         *\n         * So, is the right thing to do here \"getParentDataset().listDatasets()\" and then query the cache again?\n         * Perhaps, but listDatasets() throws an IOException, and length() and lastModified() do not.\n         * We would have to change their signatures and the upstream client code to make it work.\n         */ ObjectMetadata metadata = threddsS3Client . getObjectMetadata ( s3uri ) ; if ( metadata != null ) { return metadata . getContentLength ( ) ; } else { // \"this\" may be a collection or non-existent. In both cases, we return 0. return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the date that the dataset was last modified . Will be null if the dataset is a collection or non - existent . [CODESPLIT] @ Override public Date lastModified ( ) { S3ObjectSummary objectSummary = objectSummaryCache . getIfPresent ( s3uri ) ; if ( objectSummary != null ) { return objectSummary . getLastModified ( ) ; } ObjectMetadata metadata = threddsS3Client . getObjectMetadata ( s3uri ) ; if ( metadata != null ) { return metadata . getLastModified ( ) ; } else { // \"this\" may be a collection or non-existent. In both cases, we return null. return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Exception handlers [CODESPLIT] @ ExceptionHandler ( NcssException . class ) public ResponseEntity < String > handle ( NcssException e ) { HttpHeaders responseHeaders = new HttpHeaders ( ) ; responseHeaders . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity <> ( e . getMessage ( ) , responseHeaders , HttpStatus . BAD_REQUEST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unit testing [CODESPLIT] public static String getDatasetPath ( String path ) { if ( path . startsWith ( StandardService . netcdfSubsetGrid . getBase ( ) ) ) { // strip off /ncss/grid/ path = path . substring ( StandardService . netcdfSubsetGrid . getBase ( ) . length ( ) ) ; } else if ( path . startsWith ( StandardService . netcdfSubsetPoint . getBase ( ) ) ) { // strip off /ncss/point/ path = path . substring ( StandardService . netcdfSubsetPoint . getBase ( ) . length ( ) ) ; } // strip off endings for ( String ending : endings ) { if ( path . endsWith ( ending ) ) { int len = path . length ( ) - ending . length ( ) ; path = path . substring ( 0 , len ) ; break ; } } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generator [CODESPLIT] public void generate ( CEConstraint ce , ChunkWriter cw , boolean withdmr , ChecksumMode mode ) throws DapException { begin ( ce , cw , withdmr , mode ) ; if ( this . withdmr ) generateDMR ( this . dmr ) ; dataset ( this . dmr ) ; end ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Node specific generators [CODESPLIT] public void dataset ( DapDataset dmr ) throws DapException { // Iterate over the variables in order for ( DapVariable var : this . dmr . getTopVariables ( ) ) { if ( ! this . ce . references ( var ) ) continue ; variable ( var ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a dataset variable and index automatically populates this Point and returns it . If not found returns null . [CODESPLIT] public Point setupPoint ( NetcdfDataset set , Variable vari , int index ) { // Points are much simpler, node_count is used multigeometries so it's a bit different\r // No need for the index finder here, unless there is a multipoint\r Array xPts = null ; Array yPts = null ; Integer ind = ( int ) index ; Variable nodeCounts = null ; boolean multi = false ; SimpleGeometryIndexFinder indexFinder = null ; List < CoordinateAxis > axes = set . getCoordinateAxes ( ) ; CoordinateAxis x = null ; CoordinateAxis y = null ; String [ ] nodeCoords = vari . findAttributeIgnoreCase ( CF . NODE_COORDINATES ) . getStringValue ( ) . split ( \" \" ) ; // Look for x and y\r for ( CoordinateAxis ax : axes ) { if ( ax . getFullName ( ) . equals ( nodeCoords [ 0 ] ) ) x = ax ; if ( ax . getFullName ( ) . equals ( nodeCoords [ 1 ] ) ) y = ax ; } // Node count is used very differently in points\r // Similar use to part_node_count in other geometries\r String node_c_str = vari . findAttValueIgnoreCase ( CF . NODE_COUNT , \"\" ) ; if ( ! node_c_str . equals ( \"\" ) ) { nodeCounts = set . findVariable ( node_c_str ) ; indexFinder = new SimpleGeometryIndexFinder ( nodeCounts ) ; multi = true ; } try { //\r if ( multi ) { xPts = x . read ( indexFinder . getBeginning ( index ) + \":\" + indexFinder . getEnd ( index ) ) . reduce ( ) ; yPts = y . read ( indexFinder . getBeginning ( index ) + \":\" + indexFinder . getEnd ( index ) ) . reduce ( ) ; } else { xPts = x . read ( ind . toString ( ) ) . reduce ( ) ; yPts = y . read ( ind . toString ( ) ) . reduce ( ) ; this . x = xPts . getDouble ( 0 ) ; this . y = yPts . getDouble ( 0 ) ; } // Set points\r if ( ! multi ) { this . x = xPts . getDouble ( 0 ) ; this . y = yPts . getDouble ( 0 ) ; // Set data of each\r switch ( vari . getRank ( ) ) { case 2 : this . setData ( vari . read ( CFSimpleGeometryHelper . getSubsetString ( vari , index ) ) . reduce ( ) ) ; break ; case 1 : this . setData ( vari . read ( \"\" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations\r } } else { IndexIterator itrX = xPts . getIndexIterator ( ) ; IndexIterator itrY = yPts . getIndexIterator ( ) ; this . next = null ; this . prev = null ; Point point = this ; // x and y should have the same shape (size), will add some handling on this\r while ( itrX . hasNext ( ) ) { point . setX ( itrX . getDoubleNext ( ) ) ; point . setY ( itrY . getDoubleNext ( ) ) ; // Set data of each\r switch ( vari . getRank ( ) ) { case 2 : point . setData ( vari . read ( CFSimpleGeometryHelper . getSubsetString ( vari , index ) ) . reduce ( ) ) ; break ; case 1 : point . setData ( vari . read ( \"\" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations\r } point . setNext ( new CFPoint ( ) ) ; // -1 is a default value, it gets assigned eventually\r point = point . getNext ( ) ; } // Clean up the last point since it will be invalid\r point = point . getPrev ( ) ; point . setNext ( null ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; return null ; } catch ( InvalidDataseriesException e ) { e . printStackTrace ( ) ; return null ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the file path dealing with leading and trailing path seperators ( which must be a slash ( / )) for the given directory and file paths . <p / > Note : Dealing with path strings is fragile . ToDo : Switch from using path strings to java . io . Files . [CODESPLIT] public static String formFilename ( String dirPath , String filePath ) { if ( ( dirPath == null ) || ( filePath == null ) ) return null ; if ( filePath . startsWith ( \"/\" ) ) filePath = filePath . substring ( 1 ) ; return dirPath . endsWith ( \"/\" ) ? dirPath + filePath : dirPath + \"/\" + filePath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a file to the response stream . [CODESPLIT] public static void returnFile ( HttpServlet servlet , String contentPath , String path , HttpServletRequest req , HttpServletResponse res , String contentType ) throws IOException { String filename = ServletUtil . formFilename ( contentPath , path ) ; log . debug ( \"returnFile(): returning file <\" + filename + \">.\" ) ; // No file, nothing to view\r if ( filename == null ) { res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } // dontallow ..\r if ( filename . contains ( \"..\" ) ) { res . sendError ( HttpServletResponse . SC_FORBIDDEN ) ; return ; } // dont allow access to WEB-INF or META-INF\r String upper = filename . toUpperCase ( ) ; if ( upper . contains ( \"WEB-INF\" ) || upper . contains ( \"META-INF\" ) ) { res . sendError ( HttpServletResponse . SC_FORBIDDEN ) ; return ; } returnFile ( servlet , req , res , new File ( filename ) , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a file to the response stream . Handles Range requests . [CODESPLIT] public static void returnFile ( HttpServlet servlet , HttpServletRequest req , HttpServletResponse res , File file , String contentType ) throws IOException { // No file, nothing to view\r if ( file == null ) { res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } // check that it exists\r if ( ! file . exists ( ) ) { res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return ; } // not a directory\r if ( ! file . isFile ( ) ) { res . sendError ( HttpServletResponse . SC_BAD_REQUEST ) ; return ; } // Set the type of the file\r String filename = file . getPath ( ) ; if ( null == contentType ) { if ( filename . endsWith ( \".html\" ) ) contentType = ContentType . html . getContentHeader ( ) ; else if ( filename . endsWith ( \".xml\" ) ) contentType = ContentType . xml . getContentHeader ( ) ; else if ( filename . endsWith ( \".txt\" ) || ( filename . endsWith ( \".log\" ) ) ) contentType = ContentType . text . getContentHeader ( ) ; else if ( filename . indexOf ( \".log.\" ) > 0 ) contentType = ContentType . text . getContentHeader ( ) ; else if ( filename . endsWith ( \".nc\" ) ) contentType = ContentType . netcdf . getContentHeader ( ) ; else if ( filename . endsWith ( \".nc4\" ) ) contentType = ContentType . netcdf . getContentHeader ( ) ; else if ( servlet != null ) contentType = servlet . getServletContext ( ) . getMimeType ( filename ) ; if ( contentType == null ) contentType = ContentType . binary . getContentHeader ( ) ; } returnFile ( req , res , file , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a file to the response stream . Handles Range requests . [CODESPLIT] public static void returnFile ( HttpServletRequest req , HttpServletResponse res , File file , String contentType ) throws IOException { res . setContentType ( contentType ) ; res . addDateHeader ( \"Last-Modified\" , file . lastModified ( ) ) ; // res.setHeader(\"Content-Disposition\", \"attachment; filename=\\\"\" + file.getName() + \"\\\"\");\r // see if its a Range Request\r boolean isRangeRequest = false ; long startPos = 0 , endPos = Long . MAX_VALUE ; String rangeRequest = req . getHeader ( \"Range\" ) ; if ( rangeRequest != null ) { // bytes=12-34 or bytes=12-\r int pos = rangeRequest . indexOf ( \"=\" ) ; if ( pos > 0 ) { int pos2 = rangeRequest . indexOf ( \"-\" ) ; if ( pos2 > 0 ) { String startString = rangeRequest . substring ( pos + 1 , pos2 ) ; String endString = rangeRequest . substring ( pos2 + 1 ) ; startPos = Long . parseLong ( startString ) ; if ( endString . length ( ) > 0 ) endPos = Long . parseLong ( endString ) + 1 ; isRangeRequest = true ; } } } // set content length\r long fileSize = file . length ( ) ; long contentLength = fileSize ; if ( isRangeRequest ) { endPos = Math . min ( endPos , fileSize ) ; contentLength = endPos - startPos ; } // when compression is turned on, ContentLength has to be overridden\r // this is also true for HEAD, since this must be the same as GET without the body\r if ( contentLength > Integer . MAX_VALUE ) res . addHeader ( \"Content-Length\" , Long . toString ( contentLength ) ) ; // allow content length > MAX_INT\r else res . setContentLength ( ( int ) contentLength ) ; String filename = file . getPath ( ) ; // indicate we allow Range Requests\r res . addHeader ( \"Accept-Ranges\" , \"bytes\" ) ; if ( req . getMethod ( ) . equals ( \"HEAD\" ) ) { return ; } try { if ( isRangeRequest ) { // set before content is sent\r res . addHeader ( \"Content-Range\" , \"bytes \" + startPos + \"-\" + ( endPos - 1 ) + \"/\" + fileSize ) ; res . setStatus ( HttpServletResponse . SC_PARTIAL_CONTENT ) ; try ( RandomAccessFile craf = RandomAccessFile . acquire ( filename ) ) { IO . copyRafB ( craf , startPos , contentLength , res . getOutputStream ( ) , new byte [ 60000 ] ) ; return ; } } // Return the file\r ServletOutputStream out = res . getOutputStream ( ) ; IO . copyFileB ( file , out , 60 * 1000 ) ; /* try (WritableByteChannel cOut = Channels.newChannel(out)) {\r\n        IO.copyFileWithChannels(file, cOut);\r\n        res.flushBuffer();\r\n      } */ } // @todo Split up this exception handling: those from file access vs those from dealing with response\r //       File access: catch and res.sendError()\r //       response: don't catch (let bubble up out of doGet() etc)\r catch ( FileNotFoundException e ) { log . error ( \"returnFile(): FileNotFoundException= \" + filename ) ; if ( ! res . isCommitted ( ) ) res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; } catch ( java . net . SocketException e ) { log . info ( \"returnFile(): SocketException sending file: \" + filename + \" \" + e . getMessage ( ) ) ; } catch ( IOException e ) { String eName = e . getClass ( ) . getName ( ) ; // dont want compile time dependency on ClientAbortException\r if ( eName . equals ( \"org.apache.catalina.connector.ClientAbortException\" ) ) { log . debug ( \"returnFile(): ClientAbortException while sending file: \" + filename + \" \" + e . getMessage ( ) ) ; return ; } if ( e . getMessage ( ) . startsWith ( \"File transfer not complete\" ) ) { // coming from FileTransfer.transferTo()\r log . debug ( \"returnFile() \" + e . getMessage ( ) ) ; return ; } log . error ( \"returnFile(): IOException (\" + e . getClass ( ) . getName ( ) + \") sending file \" , e ) ; if ( ! res . isCommitted ( ) ) res . sendError ( HttpServletResponse . SC_NOT_FOUND , \"Problem sending file: \" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send given content string as the HTTP response . [CODESPLIT] public static void returnString ( String contents , HttpServletResponse res ) throws IOException { try { ServletOutputStream out = res . getOutputStream ( ) ; IO . copy ( new ByteArrayInputStream ( contents . getBytes ( CDM . utf8Charset ) ) , out ) ; } catch ( IOException e ) { log . error ( \" IOException sending string: \" , e ) ; res . sendError ( HttpServletResponse . SC_NOT_FOUND , \"Problem sending string: \" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the proper content length for the string [CODESPLIT] public static int setResponseContentLength ( HttpServletResponse response , String s ) throws UnsupportedEncodingException { int length = s . getBytes ( response . getCharacterEncoding ( ) ) . length ; response . setContentLength ( length ) ; return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the request URL relative to the server ( i . e . starting with the context path ) . [CODESPLIT] public static String getReletiveURL ( HttpServletRequest req ) { return req . getContextPath ( ) + req . getServletPath ( ) + req . getPathInfo ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forward this request to the CatalogServices servlet ( / catalog . html ) . [CODESPLIT] public static void forwardToCatalogServices ( HttpServletRequest req , HttpServletResponse res ) throws IOException , ServletException { String reqs = \"catalog=\" + getReletiveURL ( req ) ; String query = req . getQueryString ( ) ; if ( query != null ) reqs = reqs + \"&\" + query ; log . info ( \"forwardToCatalogServices(): request string = \\\"/catalog.html?\" + reqs + \"\\\"\" ) ; // dispatch to CatalogHtml servlet\r RequestForwardUtils . forwardRequestRelativeToCurrentContext ( \"/catalog.html?\" + reqs , req , res ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the server part eg http : // motherlode : 8080 [CODESPLIT] public static String getRequestServer ( HttpServletRequest req ) { return req . getScheme ( ) + \"://\" + req . getServerName ( ) + \":\" + req . getServerPort ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The request base as a URI [CODESPLIT] public static URI getRequestURI ( HttpServletRequest req ) { try { return new URI ( getRequestBase ( req ) ) ; } catch ( URISyntaxException e ) { e . printStackTrace ( ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "servletPath + pathInfo [CODESPLIT] public static String getRequestPath ( HttpServletRequest req ) { StringBuilder buff = new StringBuilder ( ) ; if ( req . getServletPath ( ) != null ) buff . append ( req . getServletPath ( ) ) ; if ( req . getPathInfo ( ) != null ) buff . append ( req . getPathInfo ( ) ) ; return buff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The entire request including query string [CODESPLIT] public static String getRequest ( HttpServletRequest req ) { String query = req . getQueryString ( ) ; return getRequestBase ( req ) + ( query == null ? \"\" : \"?\" + query ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value of the given parameter for the given request . Should only be used if the parameter is known to only have one value . If used on a multi - valued parameter the first value is returned . [CODESPLIT] public static String getParameterIgnoreCase ( HttpServletRequest req , String paramName ) { Enumeration e = req . getParameterNames ( ) ; while ( e . hasMoreElements ( ) ) { String s = ( String ) e . nextElement ( ) ; if ( s . equalsIgnoreCase ( paramName ) ) return req . getParameter ( s ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show details about the request [CODESPLIT] static public String showRequestDetail ( HttpServletRequest req ) { StringBuilder sbuff = new StringBuilder ( ) ; sbuff . append ( \"Request Info\\n\" ) ; sbuff . append ( \" req.getServerName(): \" ) . append ( req . getServerName ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getServerPort(): \" ) . append ( req . getServerPort ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getContextPath:\" ) . append ( req . getContextPath ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getServletPath:\" ) . append ( req . getServletPath ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getPathInfo:\" ) . append ( req . getPathInfo ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getQueryString:\" ) . append ( req . getQueryString ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" getQueryStringDecoded:\" ) . append ( EscapeStrings . urlDecode ( req . getQueryString ( ) ) ) . append ( \"\\n\" ) ; /*try {\r\n      sbuff.append(\" getQueryStringDecoded:\").append(URLDecoder.decode(req.getQueryString(), \"UTF-8\")).append(\"\\n\");\r\n    } catch (UnsupportedEncodingException e1) {\r\n      e1.printStackTrace();\r\n    }*/ sbuff . append ( \" req.getRequestURI:\" ) . append ( req . getRequestURI ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" getRequestBase:\" ) . append ( getRequestBase ( req ) ) . append ( \"\\n\" ) ; sbuff . append ( \" getRequestServer:\" ) . append ( getRequestServer ( req ) ) . append ( \"\\n\" ) ; sbuff . append ( \" getRequest:\" ) . append ( getRequest ( req ) ) . append ( \"\\n\" ) ; sbuff . append ( \"\\n\" ) ; sbuff . append ( \" req.getPathTranslated:\" ) . append ( req . getPathTranslated ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \"\\n\" ) ; sbuff . append ( \" req.getScheme:\" ) . append ( req . getScheme ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getProtocol:\" ) . append ( req . getProtocol ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getMethod:\" ) . append ( req . getMethod ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \"\\n\" ) ; sbuff . append ( \" req.getContentType:\" ) . append ( req . getContentType ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getContentLength:\" ) . append ( req . getContentLength ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getRemoteAddr():\" ) . append ( req . getRemoteAddr ( ) ) ; try { sbuff . append ( \" getRemoteHost():\" ) . append ( java . net . InetAddress . getByName ( req . getRemoteHost ( ) ) . getHostName ( ) ) . append ( \"\\n\" ) ; } catch ( java . net . UnknownHostException e ) { sbuff . append ( \" getRemoteHost():\" ) . append ( e . getMessage ( ) ) . append ( \"\\n\" ) ; } sbuff . append ( \" getRemoteUser():\" ) . append ( req . getRemoteUser ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \"\\n\" ) ; sbuff . append ( \"Request Parameters:\\n\" ) ; Enumeration params = req . getParameterNames ( ) ; while ( params . hasMoreElements ( ) ) { String name = ( String ) params . nextElement ( ) ; String values [ ] = req . getParameterValues ( name ) ; if ( values != null ) { for ( int i = 0 ; i < values . length ; i ++ ) { sbuff . append ( \"  \" ) . append ( name ) . append ( \"  (\" ) . append ( i ) . append ( \"): \" ) . append ( values [ i ] ) . append ( \"\\n\" ) ; } } } sbuff . append ( \"\\n\" ) ; sbuff . append ( \"Request Headers:\\n\" ) ; Enumeration names = req . getHeaderNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Enumeration values = req . getHeaders ( name ) ; // support multiple values\r if ( values != null ) { while ( values . hasMoreElements ( ) ) { String value = ( String ) values . nextElement ( ) ; sbuff . append ( \"  \" ) . append ( name ) . append ( \": \" ) . append ( value ) . append ( \"\\n\" ) ; } } } sbuff . append ( \" ------------------\\n\" ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * static public void showSession ( HttpServletRequest req PrintStream out ) { [CODESPLIT] static public String showSecurity ( HttpServletRequest req , String role ) { StringBuilder sbuff = new StringBuilder ( ) ; sbuff . append ( \"Security Info\\n\" ) ; sbuff . append ( \" req.getRemoteUser(): \" ) . append ( req . getRemoteUser ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.getUserPrincipal(): \" ) . append ( req . getUserPrincipal ( ) ) . append ( \"\\n\" ) ; sbuff . append ( \" req.isUserInRole(\" ) . append ( role ) . append ( \"):\" ) . append ( req . isUserInRole ( role ) ) . append ( \"\\n\" ) ; sbuff . append ( \" ------------------\\n\" ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * static private String getServerInfoName ( String serverInfo ) { int slash = serverInfo . indexOf ( / ) ; if ( slash == - 1 ) return serverInfo ; else return serverInfo . substring ( 0 slash ) ; } [CODESPLIT] static public void showThreads ( PrintStream pw ) { Thread current = Thread . currentThread ( ) ; ThreadGroup group = current . getThreadGroup ( ) ; while ( true ) { if ( group . getParent ( ) == null ) break ; group = group . getParent ( ) ; } showThreads ( pw , group , current ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////// [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ds , VariableEnhanced ve ) { Variable v = ( Variable ) ve ; String vname = v . getShortName ( ) ; String units = v . getUnitsString ( ) ; if ( units . equalsIgnoreCase ( CDM . LON_UNITS ) ) return AxisType . Lon ; if ( units . equalsIgnoreCase ( CDM . LAT_UNITS ) ) return AxisType . Lat ; if ( vname . equalsIgnoreCase ( \"x\" ) ) return AxisType . GeoX ; if ( vname . equalsIgnoreCase ( \"lon\" ) ) return AxisType . Lon ; if ( vname . equalsIgnoreCase ( \"y\" ) ) return AxisType . GeoY ; if ( vname . equalsIgnoreCase ( \"lat\" ) ) return AxisType . Lat ; if ( vname . equalsIgnoreCase ( \"record\" ) ) return AxisType . Time ; Dimension dim = v . getDimension ( 0 ) ; if ( ( dim != null ) && dim . getShortName ( ) . equalsIgnoreCase ( \"record\" ) ) return AxisType . Time ; String unit = ve . getUnitsString ( ) ; if ( unit != null ) { if ( SimpleUnit . isCompatible ( \"millibar\" , unit ) ) return AxisType . Pressure ; if ( SimpleUnit . isCompatible ( \"m\" , unit ) ) return AxisType . Height ; } return AxisType . GeoZ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save persistent state . [CODESPLIT] public void save ( ) { if ( catListBox != null ) catListBox . save ( ) ; if ( prefs != null ) { if ( fileChooser != null ) fileChooser . save ( ) ; if ( catgenFileChooser != null ) catgenFileChooser . save ( ) ; prefs . putInt ( HDIVIDER , split . getDividerLocation ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap this in a JDialog component . [CODESPLIT] public JDialog makeDialog ( RootPaneContainer parent , String title , boolean modal ) { this . parent = parent ; return new Dialog ( parent , title , modal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a file directory . [CODESPLIT] public int writeDirectory ( HttpServletResponse res , File dir , String path ) throws IOException { // error checking if ( dir == null ) { res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return 0 ; } if ( ! dir . exists ( ) || ! dir . isDirectory ( ) ) { res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return 0 ; } // Get directory as HTML String dirHtmlString = getDirectory ( path , dir ) ; thredds . servlet . ServletUtil . setResponseContentLength ( res , dirHtmlString ) ; res . setContentType ( ContentType . html . getContentHeader ( ) ) ; PrintWriter writer = res . getWriter ( ) ; writer . write ( dirHtmlString ) ; writer . flush ( ) ; return dirHtmlString . length ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * create new ArrayFloat with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayFloat factory ( Index index , float [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayFloat . D0 ( index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayFloat . D1 ( index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayFloat . D2 ( index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayFloat . D3 ( index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayFloat . D4 ( index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayFloat . D5 ( index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayFloat . D6 ( index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayFloat . D7 ( index , storage ) ; } else { return new ArrayFloat ( index , storage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { float [ ] ja = ( float [ ] ) javaArray ; for ( float aJa : ja ) iter . setFloatNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : MeasurementTVP / wml2 : time [CODESPLIT] public static TimePositionType initTime ( TimePositionType time , PointFeature pointFeat ) { // TEXT time . setStringValue ( pointFeat . getNominalTimeAsCalendarDate ( ) . toString ( ) ) ; return time ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : phenomenonTime / gml : TimePeriod / gml : beginPosition [CODESPLIT] public static TimePositionType initBeginPosition ( TimePositionType beginPosition , CalendarDate date ) throws IOException { // TEXT beginPosition . setStringValue ( date . toString ( ) ) ; return beginPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : phenomenonTime / gml : TimePeriod / gml : endPosition [CODESPLIT] public static TimePositionType initEndPosition ( TimePositionType endPosition , CalendarDate date ) throws IOException { // TEXT endPosition . setStringValue ( date . toString ( ) ) ; return endPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : resultTime / gml : TimeInstant / gml : timePosition [CODESPLIT] public static TimePositionType initTimePosition ( TimePositionType timePosition ) { DateTime resultTime = MarshallingUtil . fixedResultTime ; if ( resultTime == null ) { resultTime = new DateTime ( ) ; // Initialized to \"now\". } // TEXT timePosition . setStringValue ( resultTime . toString ( ) ) ; return timePosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////// [CODESPLIT] public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { String format = ncd . findAttValueIgnoreCase ( null , \"format\" , null ) ; if ( format != null ) { if ( format . startsWith ( \"nssl/netcdf\" ) ) return this ; } Dimension az = ncd . findDimension ( \"Azimuth\" ) ; Dimension gt = ncd . findDimension ( \"Gate\" ) ; if ( ( null != az ) && ( null != gt ) ) { return this ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not used yet [CODESPLIT] public void setBitOffset ( DataDescriptor dkey ) { if ( bitPosition == null ) bitPosition = new HashMap < DataDescriptor , Integer > ( 2 * parent . getSubKeys ( ) . size ( ) ) ; bitPosition . put ( dkey , bitOffset ) ; bitOffset += dkey . getBitWidth ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Track nested Tables . [CODESPLIT] public BitCounterUncompressed makeNested ( DataDescriptor subKey , int n , int row , int replicationCountSize ) { if ( subCounters == null ) subCounters = new HashMap < DataDescriptor , BitCounterUncompressed [ ] > ( 5 ) ; // assumes DataDescriptor.equals is ==\r BitCounterUncompressed [ ] subCounter = subCounters . get ( subKey ) ; if ( subCounter == null ) { subCounter = new BitCounterUncompressed [ nrows ] ; // one for each row in this table\r subCounters . put ( subKey , subCounter ) ; } BitCounterUncompressed rc = new BitCounterUncompressed ( subKey , n , replicationCountSize ) ; subCounter [ row ] = rc ; return rc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "total bits of this table and all subtables [CODESPLIT] int countBits ( int startBit ) { countBits = replicationCountSize ; this . startBit = new int [ nrows ] ; for ( int i = 0 ; i < nrows ; i ++ ) { this . startBit [ i ] = startBit + countBits ; if ( debug ) System . out . println ( \" BitCounterUncompressed row \" + i + \" startBit=\" + this . startBit [ i ] ) ; for ( DataDescriptor nd : parent . subKeys ) { BitCounterUncompressed [ ] bitCounter = ( subCounters == null ) ? null : subCounters . get ( nd ) ; if ( bitCounter == null ) // a regular field\r countBits += nd . getBitWidth ( ) ; else { if ( debug ) System . out . println ( \" ---------> nested \" + nd . getFxyName ( ) + \" starts at =\" + ( startBit + countBits ) ) ; countBits += bitCounter [ i ] . countBits ( startBit + countBits ) ; if ( debug ) System . out . println ( \" <--------- nested \" + nd . getFxyName ( ) + \" ends at =\" + ( startBit + countBits ) ) ; } } } return countBits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ! GRIB2 parameter table ! !D# = Discipline number !CT# = Category number ( Octet 10 Code Table 4 . 2 ) !ID# = Parameter number ( Octet 11 ) !PD# = Product Definition Template number ( Octet 8 - 9 Code Table 4 . 0 ) ! ! temperature !D# CT# ID# PD# NAME UNITS GNAM SCALE MISSING HZREMAP DIRECTION !23|123|123|123|12345678901234567890123456789012|12345678901234567890|123456789012|12345|123456 . 89|12345678|1234567890 1 2 3 4 5 6 7 8 9 10 11 12 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 000 000 000 000 Temperature K TMPK 0 - 9999 . 00 0 0 000 000 000 019 Temperature Below Normal % PTBN 0 - 9999 . 00 0 0 000 000 000 029 Temperature Near Normal % PTNN 0 - 9999 . 00 0 0 000 000 000 039 Temperature Above Normal % PTAN 0 - 9999 . 00 0 0 000 000 001 000 Virtual Temperature K TVRK 0 - 9999 . 00 0 0 000 000 002 000 Potential Temperature K THTA 0 - 9999 . 00 0 0 000 000 003 000 Equivalent Potential Temp K THTE 0 - 9999 . 00 0 0 000 000 004 008 Maximum Temperature K TMXK 0 - 9999 . 00 0 0 000 000 005 008 Minimum Temperature K TMNK 0 - 9999 . 00 0 0 000 000 006 000 Dew Point Temperature K DWPK 0 - 9999 . 00 0 0 000 000 007 000 Dew Point Depression K DPDK 0 - 9999 . 00 0 0 000 000 008 000 Lapse Rate K m ** - 1 LAPS 0 - 9999 . 00 0 0 000 000 009 000 Temperature Anomaly K TMPKA 0 - 9999 . 00 0 0 000 000 010 000 Latent Heat Net Flux W m ** - 2 FXLH 0 - 9999 . 00 0 0 000 000 011 000 Sensible Heat Net Flux W m ** - 2 FXSH 0 - 9999 . 00 0 0 000 000 012 000 Heat Index K HEAT 0 - 9999 . 00 0 0 000 000 013 000 Wind Chill Factor K CHILL 0 - 9999 . 00 0 0 !000 000 014 000 Minimum Dew Point Depression K ???? 0 - 9999 . 00 0 0 !000 000 015 000 Virtual Potential Temperature K ???? 0 - 9999 . 00 0 0 ! ! moisture !D# CT# ID# PD# NAME UNITS GNAM SCALE MISSING HZREMAP DIRECTION !23|123|123|123|12345678901234567890123456789012|12345678901234567890|123456789012|12345|123456 . 89|12345678|1234567890 000 001 000 000 Specific Humidity kg kg ** - 1 SPFH 0 - 9999 . 00 0 0 [CODESPLIT] private Map < Integer , Grib2Parameter > initLocalTable ( String resourcePath , @ Nullable Formatter f ) { Map < Integer , Grib2Parameter > result = new HashMap <> ( 100 ) ; try ( InputStream is = GribResourceReader . getInputStream ( resourcePath ) ) { if ( f != null ) f . format ( \"%s, %-20s, %-20s, %-20s%n\" , \"id\" , \"name\" , \"units\" , \"gname\" ) ; TableParser parser = new TableParser ( \"3i,7i,11i,15i,49,69,74,\" ) ; parser . setComment ( \"!\" ) ; List < TableParser . Record > recs = parser . readAllRecords ( is , 50000 ) ; for ( TableParser . Record record : recs ) { int disc = ( Integer ) record . get ( 0 ) ; int cat = ( Integer ) record . get ( 1 ) ; int id = ( Integer ) record . get ( 2 ) ; int template = ( Integer ) record . get ( 3 ) ; // LOOK - 19, 29, 39 ??? String name = ( ( String ) record . get ( 4 ) ) . trim ( ) ; String units = ( ( String ) record . get ( 5 ) ) . trim ( ) ; String gname = ( ( String ) record . get ( 6 ) ) . trim ( ) ; String ids = disc + \"-\" + cat + \"-\" + id ; if ( f != null ) f . format ( \"%s == %-20s, %-20s, %-20s%n\" , ids , name , units , gname ) ; Grib2Parameter gp = new Grib2Parameter ( disc , cat , id , gname , units , null , name ) ; result . put ( Grib2Tables . makeParamId ( disc , cat , id ) , gp ) ; } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append this line to the bottom of the JTextArea . A newline is added and JTextArea is scrolled to bottom ; remove lines at top if needed . [CODESPLIT] public void appendLine ( String line ) { if ( count >= nlines ) { try { int remove = Math . max ( removeIncr , count - nlines ) ; // nlines may have changed int offset = ta . getLineEndOffset ( remove ) ; ta . replaceRange ( \"\" , 0 , offset ) ; } catch ( Exception e ) { log . error ( \"Problem in TextHistoryPane\" , e ) ; } count = nlines - removeIncr ; } ta . append ( line ) ; ta . append ( \"\\n\" ) ; count ++ ; // scroll to end ta . setCaretPosition ( ta . getText ( ) . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * This is part of the Lexer interface [CODESPLIT] public int yylex ( ) throws ParseException { int token ; int c ; token = 0 ; yytext . setLength ( 0 ) ; /* invariant: p always points to current char */ try { token = - 1 ; while ( token < 0 ) { if ( ( c = read ( ) ) <= 0 ) break ; if ( c == ' ' ) { } else if ( c <= ' ' || c == ' ' ) { /* whitespace: ignore */ } else if ( worddelims . indexOf ( c ) >= 0 ) { /* don't put in yytext to avoid memory leak */ token = c ; } else if ( c == ' ' ) { boolean more = true ; /* We have a string token; will be reported as SCAN_STRINGCONST */ while ( more && ( c = read ( ) ) > 0 ) { if ( c == ' ' ) more = false ; else if ( c == ' ' ) { c = read ( ) ; if ( c < 0 ) more = false ; } if ( more ) yytext . append ( ( char ) c ) ; } token = SCAN_STRINGCONST ; } else if ( false && numchars1 . indexOf ( c ) >= 0 ) { // we might have a SCAN_NUMBERCONST boolean isnumber = false ; yytext . append ( ( char ) c ) ; while ( ( c = read ( ) ) > 0 ) { if ( numcharsn . indexOf ( c ) < 0 ) { pushback ( c ) ; break ; } yytext . append ( ( char ) c ) ; } removetrailingblanks ( ) ; //See if this is a number try { Double number = new Double ( yytext . toString ( ) ) ; isnumber = true ; } catch ( NumberFormatException nfe ) { isnumber = false ; } //A number followed by an id char is assumed to just be a funny id if ( isnumber ) { c = read ( ) ; if ( wordcharsn . indexOf ( c ) >= 0 ) { // this is apparently just a funny id token = SCAN_WORD ; } else { // its really a number token = SCAN_NUMBERCONST ; if ( c != ' ' ) pushback ( c ) ; } } else { // !isNumber /* Now, if the funny word has a \".\" in it,\n                           we have to back up to that dot */ int dotpoint = yytext . toString ( ) . indexOf ( ' ' ) ; if ( dotpoint >= 0 ) { for ( int i = 0 ; i < dotpoint ; i ++ ) { pushback ( yytext . charAt ( i ) ) ; } yytext . setLength ( dotpoint ) ; } token = SCAN_WORD ; } } else if ( wordornumberchars1 . indexOf ( c ) >= 0 ) { boolean isnumber = false ; /* we have a WORD or a number*/ yytext . append ( ( char ) c ) ; while ( ( c = read ( ) ) > 0 ) { if ( wordornumbercharsn . indexOf ( c ) < 0 ) { pushback ( c ) ; break ; } yytext . append ( ( char ) c ) ; } removetrailingblanks ( ) ; /* If this looks like a number, then treat it as such.*/ try { new Double ( yytext . toString ( ) ) ; isnumber = true ; } catch ( NumberFormatException nfe ) { isnumber = false ; } if ( isnumber ) token = SCAN_NUMBERCONST ; else { token = SCAN_WORD ; /* If this is a mistaken number, then we need to\n                           backup to the last occurrence of a dot '.'\n                           because all other number characters are legitmate\n                           identifier characters. Special case occurs when\n                           we are left with a single dot.\n                         */ int dotpoint = yytext . toString ( ) . indexOf ( ' ' ) ; if ( dotpoint >= 0 ) { // pushback the whole of yytext (in reverse order) for ( int i = yytext . length ( ) - 1 ; i >= 0 ; i -- ) pushback ( yytext . charAt ( i ) ) ; yytext . setLength ( 0 ) ; if ( dotpoint == 0 ) { // single character delimiter token = ' ' ; yytext . append ( ( char ) ( c = read ( ) ) ) ; } else  { // Recollect up to but not including the first dot. for ( int i = 0 ; i < dotpoint ; i ++ ) yytext . append ( ( char ) ( c = read ( ) ) ) ; } } } } else { /* we have a single char token */ token = c ; } } if ( token < 0 ) { token = 0 ; lval = null ; } else { // We have to apply DAP2 %xx escaping if this is a SCAN_WORD String text = yytext . toString ( ) ; if ( token == SCAN_WORD ) text = EscapeStrings . unescapeDAPIdentifier ( text ) ; lval = ( text . length ( ) == 0 ? ( String ) null : text ) ; } if ( parsestate . getDebugLevel ( ) > 0 ) dumptoken ( token , ( String ) lval ) ; return token ; /* Return the type of the token.  */ } catch ( IOException ioe ) { throw new ParseException ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entry point for error reporting . Emits an error in a user - defined way . [CODESPLIT] public void yyerror ( String s ) { Ceparse . log . error ( \"yyerror: constraint parse error:\" + s + \"; char \" + charno ) ; if ( yytext . length ( ) > 0 ) Ceparse . log . error ( \" near |\" + yytext + \"|\" ) ; // Add extra info if ( parsestate . getURL ( ) != null ) Ceparse . log . error ( \"\\turl=\" + parsestate . getURL ( ) ) ; Ceparse . log . error ( \"\\tconstraint=\" + ( constraint == null ? \"none\" : constraint ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "System . out . println ( drag : + deltax + + deltay ) ; } [CODESPLIT] public static void main ( String args [ ] ) { JFrame frame = new JFrame ( \"Test MyMouseAdapter\" ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ) ; JLabel comp = new JLabel ( \"test  sdfk sdf ks;dflk ;sdlkf ldsk lk\" ) ; comp . setOpaque ( true ) ; comp . setBackground ( Color . white ) ; comp . setForeground ( Color . black ) ; comp . addMouseListener ( new MyMouseAdapter ( ) ) ; JPanel main = new JPanel ( new FlowLayout ( ) ) ; frame . getContentPane ( ) . add ( main ) ; main . setPreferredSize ( new Dimension ( 200 , 200 ) ) ; main . add ( comp ) ; frame . pack ( ) ; frame . setLocation ( 300 , 300 ) ; frame . setVisible ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accessors [CODESPLIT] public DapVariable findByName ( String shortname ) { for ( DapVariable field : fields ) { if ( shortname . equals ( field . getShortName ( ) ) ) return field ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XML document for the stations in this dataset possible subsetted by bb . Must be a station dataset . [CODESPLIT] public Document makeStationCollectionDocument ( LatLonRect bb , String [ ] names ) throws IOException { List < DsgFeatureCollection > list = fdp . getPointFeatureCollectionList ( ) ; DsgFeatureCollection fc = list . get ( 0 ) ; // LOOK maybe should pass in the dsg?\r if ( ! ( fc instanceof StationTimeSeriesFeatureCollection ) ) { throw new UnsupportedOperationException ( fc . getClass ( ) . getName ( ) + \" not a StationTimeSeriesFeatureCollection\" ) ; } StationTimeSeriesFeatureCollection sobs = ( StationTimeSeriesFeatureCollection ) fc ; Element rootElem = new Element ( \"stationCollection\" ) ; Document doc = new Document ( rootElem ) ; List < StationFeature > stations ; if ( bb != null ) stations = sobs . getStationFeatures ( bb ) ; else if ( names != null ) stations = sobs . getStationFeatures ( Arrays . asList ( names ) ) ; else stations = sobs . getStationFeatures ( ) ; for ( Station s : stations ) { Element sElem = new Element ( \"station\" ) ; sElem . setAttribute ( \"name\" , s . getName ( ) ) ; if ( s . getWmoId ( ) != null ) sElem . setAttribute ( \"wmo_id\" , s . getWmoId ( ) ) ; if ( ( s . getDescription ( ) != null ) && ( s . getDescription ( ) . length ( ) > 0 ) ) sElem . addContent ( new Element ( \"description\" ) . addContent ( s . getDescription ( ) ) ) ; sElem . addContent ( new Element ( \"longitude\" ) . addContent ( Double . toString ( s . getLongitude ( ) ) ) ) ; sElem . addContent ( new Element ( \"latitide\" ) . addContent ( Double . toString ( s . getLatitude ( ) ) ) ) ; if ( ! Double . isNaN ( s . getAltitude ( ) ) ) sElem . addContent ( new Element ( \"altitude\" ) . addContent ( Double . toString ( s . getAltitude ( ) ) ) ) ; rootElem . addContent ( sElem ) ; } return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the capabilities XML document for this dataset [CODESPLIT] public Document getCapabilitiesDocument ( ) { Element rootElem = new Element ( \"capabilities\" ) ; Document doc = new Document ( rootElem ) ; if ( null != path ) { rootElem . setAttribute ( \"location\" , path ) ; Element elem = new Element ( \"featureDataset\" ) ; FeatureType ft = fdp . getFeatureType ( ) ; elem . setAttribute ( \"type\" , ft . toString ( ) . toLowerCase ( ) ) ; String url = path . replace ( \"dataset.xml\" , ft . toString ( ) . toLowerCase ( ) + \".xml\" ) ; elem . setAttribute ( \"url\" , url ) ; rootElem . addContent ( elem ) ; } List < DsgFeatureCollection > list = fdp . getPointFeatureCollectionList ( ) ; DsgFeatureCollection fc = list . get ( 0 ) ; // LOOK maybe should pass in the dsg?\r rootElem . addContent ( writeTimeUnit ( fc . getTimeUnit ( ) ) ) ; rootElem . addContent ( new Element ( \"AltitudeUnits\" ) . addContent ( fc . getAltUnits ( ) ) ) ; // data variables\r List < ? extends VariableSimpleIF > vars = fdp . getDataVariables ( ) ; Collections . sort ( vars ) ; for ( VariableSimpleIF v : vars ) { rootElem . addContent ( writeVariable ( v ) ) ; } /* CollectionInfo info;\r\n    try {\r\n      info = new DsgCollectionHelper(fc).calcBounds();\r\n    } catch (IOException e) {\r\n      throw new RuntimeException(e);\r\n    } */ LatLonRect bb = fc . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range\r CalendarDateRange dateRange = fc . getCalendarDateRange ( ) ; if ( dateRange != null ) { Element drElem = new Element ( \"TimeSpan\" ) ; // from KML\r drElem . addContent ( new Element ( \"begin\" ) . addContent ( dateRange . getStart ( ) . toString ( ) ) ) ; drElem . addContent ( new Element ( \"end\" ) . addContent ( dateRange . getEnd ( ) . toString ( ) ) ) ; if ( dateRange . getResolution ( ) != null ) drElem . addContent ( new Element ( \"resolution\" ) . addContent ( dateRange . getResolution ( ) . toString ( ) ) ) ; rootElem . addContent ( drElem ) ; } /* add accept list\r\n    Element elem = new Element(\"AcceptList\");\r\n    //elem.addContent(new Element(\"accept\").addContent(\"raw\"));\r\n    elem.addContent(new Element(\"accept\").addContent(\"csv\").setAttribute(\"displayName\", \"csv\"));\r\n    elem.addContent(new Element(\"accept\").addContent(\"text/csv\").setAttribute(\"displayName\", \"csv (file)\"));\r\n    elem.addContent(new Element(\"accept\").addContent(\"xml\").setAttribute(\"displayName\", \"xml\"));\r\n    elem.addContent(new Element(\"accept\").addContent(\"text/xml\").setAttribute(\"displayName\", \"xml (file)\"));\r\n    elem.addContent(new Element(\"accept\").addContent(\"waterml2\").setAttribute(\"displayName\", \"WaterML 2.0\"));\r\n    elem.addContent(new Element(\"accept\").addContent(\"netcdf\").setAttribute(\"displayName\", \"CF/NetCDF-3\"));\r\n    //elem.addContent(new Element(\"accept\").addContent(\"ncstream\"));\r\n    rootElem.addContent(elem); */ return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private . use Array . factory () [CODESPLIT] static ArrayByte factory ( Index index , boolean isUnsigned ) { return ArrayByte . factory ( index , isUnsigned , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { byte [ ] ja = ( byte [ ] ) javaArray ; for ( byte aJa : ja ) iter . setByteNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private : mostly for iterators [CODESPLIT] public double getDouble ( int index ) { byte val = storage [ index ] ; return ( double ) ( isUnsigned ( ) ? DataType . unsignedByteToShort ( val ) : val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "coord based record finding . note only one record at a time [CODESPLIT] @ Nullable synchronized Record getRecordAt ( SubsetParams coords ) { int [ ] want = new int [ getRank ( ) ] ; int count = 0 ; int runIdx = - 1 ; for ( Coordinate coord : getCoordinates ( ) ) { int idx = - 1 ; switch ( coord . getType ( ) ) { case runtime : CalendarDate runtimeCooord = coords . getRunTime ( ) ; idx = coord . getIndex ( runtimeCooord ) ; runIdx = idx ; break ; case timeIntv : double [ ] timeIntv = coords . getTimeOffsetIntv ( ) ; idx = coord . getIndex ( new TimeCoordIntvValue ( ( int ) timeIntv [ 0 ] , ( int ) timeIntv [ 1 ] ) ) ; break ; case time : Double timeOffset = coords . getTimeOffset ( ) ; // Double int coordInt = timeOffset . intValue ( ) ; idx = coord . getIndex ( coordInt ) ; break ; case time2D : timeIntv = coords . getTimeOffsetIntv ( ) ; if ( timeIntv != null ) { TimeCoordIntvValue coordTinv = new TimeCoordIntvValue ( ( int ) timeIntv [ 0 ] , ( int ) timeIntv [ 1 ] ) ; idx = ( ( CoordinateTime2D ) coord ) . findTimeIndexFromVal ( runIdx , coordTinv ) ; // LOOK can only use if orthogonal break ; } Double timeCoord = coords . getTimeOffset ( ) ; if ( timeCoord != null ) { coordInt = timeCoord . intValue ( ) ; idx = ( ( CoordinateTime2D ) coord ) . findTimeIndexFromVal ( runIdx , coordInt ) ; break ; } // the OneTime case CoordinateTime2D coord2D = ( CoordinateTime2D ) coord ; if ( coord2D . getNtimes ( ) == 1 ) { idx = 0 ; break ; } throw new IllegalStateException ( \"time2D must have timeOffset ot timeOffsetIntv coordinare\" ) ; case vert : double [ ] vertIntv = coords . getVertCoordIntv ( ) ; if ( vertIntv != null ) { VertCoordValue coordVert = new VertCoordValue ( vertIntv [ 0 ] , vertIntv [ 1 ] ) ; idx = coord . getIndex ( coordVert ) ; break ; } Double vertCoord = coords . getVertCoord ( ) ; if ( vertCoord != null ) { VertCoordValue coordVert = new VertCoordValue ( vertCoord ) ; idx = coord . getIndex ( coordVert ) ; } break ; case ens : Double ensVal = coords . getEnsCoord ( ) ; idx = ( ( CoordinateEns ) coord ) . getIndexByMember ( ensVal ) ; break ; default : logger . warn ( \"GribCollectionImmutable: missing CoordVal for {}%n\" , coord . getName ( ) ) ; } if ( idx < 0 ) { logger . debug ( \"Cant find index for value in axis {} in variable {}\" , coord . getName ( ) , name ) ; return null ; } want [ count ++ ] = idx ; } return sa . getContent ( want ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the ith coordinate [CODESPLIT] public Coordinate getCoordinate ( int index ) { int grpIndex = coordIndex . get ( index ) ; return group . coords . get ( grpIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DMRFactory API [CODESPLIT] public DapAttribute newAttribute ( String name , DapType basetype ) { DapAttribute node = new DapAttribute ( name , basetype ) ; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the item to the top of the list . If it already exists move it to the top . [CODESPLIT] public void addItem ( Object item ) { if ( item == null ) return ; for ( int i = 0 ; i < getItemCount ( ) ; i ++ ) { if ( item . equals ( getItemAt ( i ) ) ) { if ( i == 0 ) { setSelectedIndex ( 0 ) ; return ; // already there\r } removeItemAt ( i ) ; } } // add as first in the list\r insertItemAt ( item , 0 ) ; setSelectedIndex ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this to obtain the list of items . [CODESPLIT] public List < Object > getItemList ( ) { ArrayList < Object > list = new ArrayList < Object > ( ) ; for ( int i = 0 ; i < getItemCount ( ) && i < nkeep ; i ++ ) list . ( getItemAt ( i ) ) ; return list ; } /**\r\n   * Use this to set the list of items.\r\n   * @param list of items, may be any Object type.\r\n   */ public void setItemList ( Collection < Object > list ) { if ( list == null ) return ; setModel ( new DefaultComboBoxModel ( list . toArray ( ) ) ) ; if ( list . size ( ) > 0 ) setSelectedIndex ( 0 ) ; } /** Set the number of items to keep */ public void setNkeep  ( int nkeep ) { this . nkeep = nkeep ; } /** Get the number of items to keep */ public int getNkeep  ( ) { return nkeep ; } /** Get value from Store, will be an ArrayList or null */ protected Object getStoreValue  ( Object defValue ) { if ( prefs == null ) return defValue ; return ( ( PreferencesExt ) prefs ) . getBean ( LIST , defValue ) ; } /** Put new value into Store, must be a List of Strings */ protected void setStoreValue  ( List newValue ) { if ( prefs != null ) prefs . putList ( LIST , newValue ) ; } // debug\r private static long lastEvent ; public static void main  ( String args [ ] ) throws IOException { JFrame frame = new JFrame ( \"Test\" ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ) ; final ComboBox cb = new ComboBox ( null ) ; cb . addActionListener ( e -> { System . out . println ( \"**** cb event=\" + e ) ; if ( e . getActionCommand ( ) . equals ( \"comboBoxChanged\" ) ) { //System.out.println(\"cb.getSelectedItem=\"+cb.getSelectedItem());\r cb . addItem ( cb . getSelectedItem ( ) ) ; } } ) ; cb . getEditor ( ) . getEditorComponent ( ) . setForeground ( Color . red ) ; /* JButton butt = new JButton(\"accept\");\r\n   butt.addActionListener( new AbstractAction() {\r\n      public void actionPerformed(ActionEvent e) {\r\n        System.out.println(\"butt accept\");\r\n        cb.accept();\r\n     }\r\n   }); */ JPanel main = new JPanel ( ) ; main . add ( cb ) ; // main.add(butt);\r frame . getContentPane ( ) . add ( main ) ; // cb.setPreferredSize(new java.awt.Dimension(500, 200));\r frame . pack ( ) ; frame . setLocation ( 300 , 300 ) ; frame . setVisible ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { int nz = ( int ) pressure . getSize ( ) ; int [ ] shape2D = pressure . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; ArrayDouble . D3 result = new ArrayDouble . D3 ( nz , ny , nx ) ; IndexIterator ii = pressure . getIndexIterator ( ) ; for ( int z = 0 ; z < nz ; z ++ ) { double p = ii . getDoubleNext ( ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { result . set ( z , y , x , p ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK this could be a problem [CODESPLIT] @ ExceptionHandler ( Throwable . class ) public ResponseEntity < String > handle ( Throwable ex ) throws Throwable { // If the exception is annotated with @ResponseStatus rethrow it and let // the framework handle it - like the OrderNotFoundException example // at the start of this post. // AnnotationUtils is a Spring Framework utility class. // see https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc if ( AnnotationUtils . findAnnotation ( ex . getClass ( ) , ResponseStatus . class ) != null ) throw ex ; logger . error ( \"uncaught exception\" , ex ) ; // ex.printStackTrace(); // temporary - remove in production HttpHeaders responseHeaders = new HttpHeaders ( ) ; responseHeaders . setContentType ( MediaType . TEXT_PLAIN ) ; String msg = ex . getMessage ( ) ; StringWriter sw = new StringWriter ( ) ; PrintWriter p = new PrintWriter ( sw ) ; ex . printStackTrace ( p ) ; p . close ( ) ; sw . close ( ) ; msg = sw . toString ( ) ; return new ResponseEntity <> ( \"Throwable exception handled : \" + htmlEscape ( msg ) , responseHeaders , HttpStatus . INTERNAL_SERVER_ERROR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return ith slice [CODESPLIT] public Slice slice ( int i ) { if ( i < 0 || i >= this . rank ) throw new IllegalArgumentException ( ) ; return this . slices . get ( i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the total number of elements . [CODESPLIT] public long totalSize ( ) { long size = 1 ; for ( int i = 0 ; i < this . rank ; i ++ ) { size *= this . slices . get ( i ) . getCount ( ) ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterator API [CODESPLIT] @ Override public boolean hasNext ( ) { int stop = this . rank ; switch ( this . state ) { case INITIAL : return true ; case STARTED : int i ; for ( i = stop - 1 ; i >= 0 ; i -- ) { // walk backwards if ( this . index . indices [ i ] <= this . endpoint [ i ] ) return true ; } this . state = STATE . DONE ; break ; case DONE : } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return - 1 if we have completed . [CODESPLIT] public int step ( int firstpos , int lastpos ) { for ( int i = lastpos - 1 ; i >= firstpos ; i -- ) { // walk backwards if ( this . index . indices [ i ] > this . endpoint [ i ] ) this . index . indices [ i ] = this . slices . get ( i ) . getFirst ( ) ; // reset this position else { this . index . indices [ i ] += this . slices . get ( i ) . getStride ( ) ; // move to next indices return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http : // www . nco . ncep . noaa . gov / pmb / docs / on388 / table5 . html [CODESPLIT] @ Override public GribStatType getStatType ( int timeRangeIndicator ) { switch ( timeRangeIndicator ) { case 128 : case 129 : case 130 : case 131 : case 132 : case 133 : case 137 : case 138 : case 139 : case 140 : return GribStatType . Average ; case 134 : return GribStatType . RootMeanSquare ; case 135 : case 136 : return GribStatType . StandardDeviation ; default : return super . getStatType ( timeRangeIndicator ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public so can be called from Grib2 [CODESPLIT] @ Nullable public static Map < Integer , String > getNcepGenProcess ( ) { if ( genProcessMap != null ) return genProcessMap ; String path = \"resources/grib1/ncep/ncepTableA.xml\" ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ) { SAXBuilder builder = new SAXBuilder ( ) ; org . jdom2 . Document doc = builder . build ( is ) ; Element root = doc . getRootElement ( ) ; HashMap < Integer , String > result = new HashMap <> ( 200 ) ; List < Element > params = root . getChildren ( \"parameter\" ) ; for ( Element elem1 : params ) { int code = Integer . parseInt ( elem1 . getAttributeValue ( \"code\" ) ) ; String desc = elem1 . getChildText ( \"description\" ) ; result . put ( code , desc ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe\r } catch ( IOException | JDOMException ioe ) { logger . error ( \"Cant read NCEP Table 1 = \" + path , ioe ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////// levels [CODESPLIT] protected VertCoordType getLevelType ( int code ) { if ( code < 129 ) return super . getLevelType ( code ) ; // LOOK dont let NCEP override standard tables (??) looks like a conflict with level code 210 (!)\r if ( levelTypesMap == null ) levelTypesMap = readTable3 ( \"resources/grib1/ncep/ncepTable3.xml\" ) ; if ( levelTypesMap == null ) return super . getLevelType ( code ) ; VertCoordType levelType = levelTypesMap . get ( code ) ; if ( levelType != null ) return levelType ; return super . getLevelType ( code ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * MAGIC_START version sizeRecords SparseArray s ( sizeRecords bytes ) sizeIndex GribCollectionIndex ( sizeIndex bytes ) [CODESPLIT] boolean writeIndex ( String name , File idxFile , CoordinateRuntime masterRuntime , List < Group > groups , List < MFile > files , GribCollectionImmutable . Type type , CalendarDateRange dateRange ) throws IOException { Grib2Record first = null ; // take global metadata from here boolean deleteOnClose = false ; if ( idxFile . exists ( ) ) { RandomAccessFile . eject ( idxFile . getPath ( ) ) ; if ( ! idxFile . delete ( ) ) { logger . error ( \"gc2 cant delete index file {}\" , idxFile . getPath ( ) ) ; } } logger . debug ( \" createIndex for {}\" , idxFile . getPath ( ) ) ; try ( RandomAccessFile raf = new RandomAccessFile ( idxFile . getPath ( ) , \"rw\" ) ) { //// header message raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . write ( MAGIC_START . getBytes ( CDM . utf8Charset ) ) ; raf . writeInt ( version ) ; long lenPos = raf . getFilePointer ( ) ; raf . writeLong ( 0 ) ; // save space to write the length of the record section long countBytes = 0 ; int countRecords = 0 ; Set < Integer > allFileSet = new HashSet <> ( ) ; for ( Group g : groups ) { g . fileSet = new HashSet <> ( ) ; for ( Grib2CollectionBuilder . VariableBag vb : g . gribVars ) { if ( first == null ) first = vb . first ; GribCollectionProto . SparseArray vr = writeSparseArray ( vb , g . fileSet ) ; byte [ ] b = vr . toByteArray ( ) ; vb . pos = raf . getFilePointer ( ) ; vb . length = b . length ; raf . write ( b ) ; countBytes += b . length ; countRecords += vb . coordND . getSparseArray ( ) . countNotMissing ( ) ; } allFileSet . addAll ( g . fileSet ) ; } if ( logger . isDebugEnabled ( ) ) { long bytesPerRecord = countBytes / ( ( countRecords == 0 ) ? 1 : countRecords ) ; logger . debug ( \"  write RecordMaps: bytes = {} record = {} bytesPerRecord={}\" , countBytes , countRecords , bytesPerRecord ) ; } if ( first == null ) { deleteOnClose = true ; throw new IOException ( \"GribCollection \" + name + \" has no records\" ) ; } long pos = raf . getFilePointer ( ) ; raf . seek ( lenPos ) ; raf . writeLong ( countBytes ) ; raf . seek ( pos ) ; // back to the output. /*\n      message GribCollection {\n        string name = 1;         // must be unique - index filename is name.ncx\n        string topDir = 2;       // MFile, Partition filenames are reletive to this\n        repeated MFile mfiles = 3;        // list of grib MFiles\n        repeated Dataset dataset = 4;\n        repeated Gds gds = 5;             // unique Gds, shared amongst datasets\n        Coord masterRuntime = 6;  // list of runtimes in this GC\n\n        int32 center = 7;      // these 4 fields are to get a GribCustomizer\n        int32 subcenter = 8;\n        int32 master = 9;\n        int32 local = 10;       // grib1 table Version\n\n        int32 genProcessType = 11;\n        int32 genProcessId = 12;\n        int32 backProcessId = 13;\n        int32 version = 14;     // >= 3 for proto3 (5.0+)\n\n        // repeated Parameter params = 20;      // not used\n        FcConfig config = 21;\n\n        // extensions\n        repeated Partition partitions = 100;\n        bool isPartitionOfPartitions = 101;\n        repeated uint32 run2part = 102 [packed=true];  // masterRuntime index to partition index\n      }\n       */ GribCollectionProto . GribCollection . Builder indexBuilder = GribCollectionProto . GribCollection . newBuilder ( ) ; indexBuilder . setName ( name ) ; indexBuilder . setTopDir ( dcm . getRoot ( ) ) ; indexBuilder . setVersion ( currentVersion ) ; // directory and mfile list File directory = new File ( dcm . getRoot ( ) ) ; List < GcMFile > gcmfiles = GcMFile . makeFiles ( directory , files , allFileSet ) ; for ( GcMFile gcmfile : gcmfiles ) { GribCollectionProto . MFile . Builder b = GribCollectionProto . MFile . newBuilder ( ) ; b . setFilename ( gcmfile . getName ( ) ) ; b . setLastModified ( gcmfile . getLastModified ( ) ) ; b . setLength ( gcmfile . getLength ( ) ) ; b . setIndex ( gcmfile . index ) ; indexBuilder . addMfiles ( b . build ( ) ) ; } indexBuilder . setMasterRuntime ( writeCoordProto ( masterRuntime ) ) ; //gds for ( Object go : groups ) { Group g = ( Group ) go ; indexBuilder . addGds ( writeGdsProto ( g . gdss . getRawBytes ( ) , - 1 ) ) ; } // the GC dataset indexBuilder . addDataset ( writeDatasetProto ( type , groups ) ) ; // what about just storing first ?? Grib2SectionIdentification ids = first . getId ( ) ; indexBuilder . setCenter ( ids . getCenter_id ( ) ) ; indexBuilder . setSubcenter ( ids . getSubcenter_id ( ) ) ; indexBuilder . setMaster ( ids . getMaster_table_version ( ) ) ; indexBuilder . setLocal ( ids . getLocal_table_version ( ) ) ; Grib2Pds pds = first . getPDS ( ) ; indexBuilder . setGenProcessType ( pds . getGenProcessType ( ) ) ; indexBuilder . setGenProcessId ( pds . getGenProcessId ( ) ) ; indexBuilder . setBackProcessId ( pds . getBackProcessId ( ) ) ; indexBuilder . setStartTime ( dateRange . getStart ( ) . getMillis ( ) ) ; indexBuilder . setEndTime ( dateRange . getEnd ( ) . getMillis ( ) ) ; GribCollectionProto . GribCollection index = indexBuilder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; NcStream . writeVInt ( raf , b . length ) ; // message size raf . write ( b ) ; // message  - all in one gulp logger . debug ( \"  write GribCollectionIndex= {} bytes\" , b . length ) ; } finally { // remove it on failure if ( deleteOnClose && ! idxFile . delete ( ) ) logger . error ( \" gc2 cant deleteOnClose index file {}\" , idxFile . getPath ( ) ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Record { uint32 fileno = 1 ; // which GRIB file ? key into GC . fileMap uint64 pos = 2 ; // offset in GRIB file of the start of entire message uint64 bmsPos = 3 ; // use alternate bms if non - zero uint32 drsOffset = 4 ; // offset of drs from pos ( grib2 only ) } [CODESPLIT] private GribCollectionProto . SparseArray writeSparseArray ( Grib2CollectionBuilder . VariableBag vb , Set < Integer > fileSet ) { GribCollectionProto . SparseArray . Builder b = GribCollectionProto . SparseArray . newBuilder ( ) ; SparseArray < Grib2Record > sa = vb . coordND . getSparseArray ( ) ; for ( int size : sa . getShape ( ) ) b . addSize ( size ) ; for ( int track : sa . getTrack ( ) ) b . addTrack ( track ) ; for ( Grib2Record gr : sa . getContent ( ) ) { GribCollectionProto . Record . Builder br = GribCollectionProto . Record . newBuilder ( ) ; br . setFileno ( gr . getFile ( ) ) ; fileSet . add ( gr . getFile ( ) ) ; long startPos = gr . getIs ( ) . getStartPos ( ) ; br . setStartPos ( startPos ) ; if ( gr . isBmsReplaced ( ) ) { Grib2SectionBitMap bms = gr . getBitmapSection ( ) ; br . setBmsOffset ( ( int ) ( bms . getStartingPosition ( ) - startPos ) ) ; } Grib2SectionDataRepresentation drs = gr . getDataRepresentationSection ( ) ; br . setDrsOffset ( ( int ) ( drs . getStartingPosition ( ) - startPos ) ) ; b . addRecords ( br ) ; } b . setNdups ( sa . getNdups ( ) ) ; return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = datasetScan substitutionGroup = dataset > <xsd : complexType > <xsd : complexContent > <xsd : extension base = DatasetType > <xsd : sequence > <xsd : element ref = filter minOccurs = 0 maxOccurs = 1 / > <xsd : element ref = namer minOccurs = 0 maxOccurs = 1 / > <xsd : element ref = sort minOccurs = 0 maxOccurs = 1 / > <xsd : element ref = addLatest minOccurs = 0 maxOccurs = 1 / > <xsd : element ref = addProxies minOccurs = 0 maxOccurs = 1 / > <xsd : element name = addDatasetSize minOccurs = 0 maxOccurs = 1 / > <xsd : element ref = addTimeCoverage minOccurs = 0 maxOccurs = 1 / > < / xsd : sequence > [CODESPLIT] public DatasetScanConfig readDatasetScanConfig ( Element dsElem ) { DatasetScanConfig result = new DatasetScanConfig ( ) ; result . name = dsElem . getAttributeValue ( \"name\" ) ; result . path = StringUtil2 . trim ( dsElem . getAttributeValue ( \"path\" ) , ' ' ) ; if ( result . path == null ) { errlog . format ( \"ERROR: must specify path attribute.%n\" ) ; fatalError = true ; } String scanDir = dsElem . getAttributeValue ( \"location\" ) ; if ( scanDir == null ) { errlog . format ( \"ERROR: must specify directory root in location attribute.%n\" ) ; fatalError = true ; } else { result . scanDir = AliasTranslator . translateAlias ( scanDir ) ; File scanFile = new File ( result . scanDir ) ; if ( ! scanFile . exists ( ) ) { errlog . format ( \"ERROR: directory %s does not exist%n\" , result . scanDir ) ; fatalError = true ; } } result . restrictAccess = dsElem . getAttributeValue ( \"restrictAccess\" ) ; // look for ncml Element ncmlElem = dsElem . getChild ( \"netcdf\" , Catalog . defNS ) ; if ( ncmlElem != null ) { ncmlElem . detach ( ) ; result . ncmlElement = ncmlElem ; } // Read filter element Element filterElem = dsElem . getChild ( \"filter\" , Catalog . defNS ) ; result . filters = readDatasetScanFilter ( filterElem ) ; // Read namer element Element namerElem = dsElem . getChild ( \"namer\" , Catalog . defNS ) ; result . namers = readDatasetScanNamer ( namerElem ) ; // Read filesSort or sort element Element filesSortElem = dsElem . getChild ( \"filesSort\" , Catalog . defNS ) ; if ( filesSortElem != null ) result . isSortIncreasing = readFilesSort ( filesSortElem ) ; Element sorterElem = dsElem . getChild ( \"sort\" , Catalog . defNS ) ; if ( ! result . isSortIncreasing . isPresent ( ) && sorterElem != null ) result . isSortIncreasing = readSort ( sorterElem ) ; // Deal with latest String addLatestAttribute = dsElem . getAttributeValue ( \"addLatest\" ) ; Element addLatestElem = dsElem . getChild ( \"addLatest\" , Catalog . defNS ) ; // not in docs Element addProxiesElem = dsElem . getChild ( \"addProxies\" , Catalog . defNS ) ; result . addLatest = readDatasetScanAddProxies ( addProxiesElem , addLatestElem , addLatestAttribute ) ; /* Read addDatasetSize element.\n    Element addDsSizeElem = dsElem.getChild(\"addDatasetSize\", Catalog.defNS);\n    if (addDsSizeElem != null) {                                               // docs: default true\n      if (addDsSizeElem.getTextNormalize().equalsIgnoreCase(\"false\"))\n        result.addDatasetSize = false;\n    } */ // Read addTimeCoverage element. Element addTimeCovElem = dsElem . getChild ( \"addTimeCoverage\" , Catalog . defNS ) ; if ( addTimeCovElem != null ) { result . addTimeCoverage = readDatasetScanAddTimeCoverage ( addTimeCovElem ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = filter > <xsd : complexType > <xsd : choice > <xsd : sequence minOccurs = 0 maxOccurs = unbounded > <xsd : element name = include type = FilterSelectorType minOccurs = 0 / > <xsd : element name = exclude type = FilterSelectorType minOccurs = 0 / > < / xsd : sequence > < / xsd : choice > < / xsd : complexType > < / xsd : element > [CODESPLIT] private List < DatasetScanConfig . Filter > readDatasetScanFilter ( Element filterElem ) { List < DatasetScanConfig . Filter > filters = new ArrayList <> ( ) ; if ( filterElem == null ) return null ; for ( Element curElem : filterElem . getChildren ( ) ) { String regExpAttVal = curElem . getAttributeValue ( \"regExp\" ) ; String wildcardAttVal = curElem . getAttributeValue ( \"wildcard\" ) ; String lastModLimitAttValS = curElem . getAttributeValue ( \"lastModLimitInMillis\" ) ; if ( regExpAttVal == null && wildcardAttVal == null && lastModLimitAttValS == null ) { // If no regExp or wildcard attributes, skip this selector. errlog . format ( \"WARN: readDatasetScanFilter(): no regExp, wildcard, or lastModLimitInMillis attribute in filter child <%s>%n\" , curElem . getName ( ) ) ; } else { // Determine if applies to atomic datasets, default true. String atomicAttVal = curElem . getAttributeValue ( \"atomic\" ) ; boolean atomic = ( atomicAttVal == null || ! atomicAttVal . equalsIgnoreCase ( \"false\" ) ) ; // Determine if applies to collection datasets, default false. String collectionAttVal = curElem . getAttributeValue ( \"collection\" ) ; boolean notCollection = collectionAttVal == null || ! collectionAttVal . equalsIgnoreCase ( \"true\" ) ; // Determine if include or exclude selectors. boolean includer = true ; if ( curElem . getName ( ) . equals ( \"exclude\" ) ) { includer = false ; } else if ( ! curElem . getName ( ) . equals ( \"include\" ) ) { errlog . format ( \"WARN: readDatasetScanFilter(): unhandled filter child <%s>.%n\" , curElem . getName ( ) ) ; continue ; } // check for errors long lastModLimitAttVal = - 1 ; if ( lastModLimitAttValS != null ) { try { lastModLimitAttVal = Long . parseLong ( lastModLimitAttValS ) ; } catch ( NumberFormatException e ) { errlog . format ( \"WARN: readDatasetScanFilter(): lastModLimitInMillis not valid <%s>.%n\" , curElem ) ; } } filters . add ( new DatasetScanConfig . Filter ( regExpAttVal , wildcardAttVal , lastModLimitAttVal , atomic , ! notCollection , includer ) ) ; } } return filters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = namer > <xsd : complexType > <xsd : choice maxOccurs = unbounded > <xsd : element name = regExpOnName type = NamerSelectorType / > <xsd : element name = regExpOnPath type = NamerSelectorType / > < / xsd : choice > < / xsd : complexType > < / xsd : element > [CODESPLIT] protected List < DatasetScanConfig . Namer > readDatasetScanNamer ( Element namerElem ) { List < DatasetScanConfig . Namer > result = new ArrayList <> ( ) ; if ( namerElem == null ) return result ; for ( Element curElem : namerElem . getChildren ( ) ) { String regExp = curElem . getAttributeValue ( \"regExp\" ) ; String replaceString = curElem . getAttributeValue ( \"replaceString\" ) ; boolean onName = curElem . getName ( ) . equals ( \"regExpOnName\" ) ; boolean onPath = curElem . getName ( ) . equals ( \"regExpOnPath\" ) ; if ( ! onName && ! onPath ) { errlog . format ( \"WARN: readDatasetScanNamer(): namer child '%s'%n\" , curElem . getName ( ) ) ; continue ; } result . add ( new DatasetScanConfig . Namer ( onName , regExp , replaceString ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = sort > <xsd : complexType > <xsd : choice > <xsd : element name = lexigraphicByName > <xsd : complexType > <xsd : attribute name = increasing type = xsd : boolean / > < / xsd : complexType > < / xsd : element > <xsd : element name = crawlableDatasetSorterImpl minOccurs = 0 type = UserImplType / > < / xsd : choice > < / xsd : complexType > < / xsd : element > [CODESPLIT] protected Optional < Boolean > readFilesSort ( Element sorterElem ) { String increasingString = sorterElem . getAttributeValue ( \"increasing\" ) ; if ( increasingString != null ) { if ( increasingString . equalsIgnoreCase ( \"true\" ) ) return Optional . of ( true ) ; else if ( increasingString . equalsIgnoreCase ( \"false\" ) ) return Optional . of ( false ) ; } return Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = addTimeCoverage > <xsd : complexType > <xsd : attribute name = datasetNameMatchPattern type = xsd : string / > <xsd : attribute name = datasetPathMatchPattern type = xsd : string / > <xsd : attribute name = startTimeSubstitutionPattern type = xsd : string / > <xsd : attribute name = duration type = xsd : string / > < / xsd : complexType > < / xsd : element > [CODESPLIT] protected DatasetScanConfig . AddTimeCoverage readDatasetScanAddTimeCoverage ( Element addTimeCovElem ) { String matchName = addTimeCovElem . getAttributeValue ( \"datasetNameMatchPattern\" ) ; String matchPath = addTimeCovElem . getAttributeValue ( \"datasetPathMatchPattern\" ) ; String subst = addTimeCovElem . getAttributeValue ( \"startTimeSubstitutionPattern\" ) ; String duration = addTimeCovElem . getAttributeValue ( \"duration\" ) ; boolean err = false ; if ( subst == null ) { errlog . format ( \"WARN: readDatasetScanAddTimeCoverage(): must have startTimeSubstitutionPattern elem=<%s>%n\" , addTimeCovElem ) ; err = true ; } else if ( duration == null ) { errlog . format ( \"WARN: readDatasetScanAddTimeCoverage(): must have duration elem=<%s>%n\" , addTimeCovElem ) ; err = true ; } else if ( matchName == null && matchPath == null ) { errlog . format ( \"WARN: readDatasetScanAddTimeCoverage(): must have either datasetNameMatchPattern or datasetPathMatchPattern elem=<%s>%n\" , addTimeCovElem ) ; err = true ; } return err ? null : new DatasetScanConfig . AddTimeCoverage ( matchName , matchPath , subst , duration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all CdmrFeatureDatasets must return their featureType - use as a fail - fast test of the endpoint [CODESPLIT] public static FeatureType isCdmrfEndpoint ( String endpoint ) throws IOException { HTTPSession httpClient = HTTPFactory . newSession ( endpoint ) ; String url = endpoint + \"?req=featureType\" ; // get the header try ( HTTPMethod method = HTTPFactory . Get ( httpClient , url ) ) { method . setFollowRedirects ( true ) ; int statusCode = method . execute ( ) ; if ( statusCode != 200 ) return null ; String content = method . getResponseAsString ( ) ; return FeatureType . getType ( content ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value type of the option switch to the type passed [CODESPLIT] public void SetHasValue ( int type ) { this . type = type ; if ( debug ) { System . out . println ( \"sw = \" + ( char ) sw + \"; type = \" + type + \"; set = \" + set + \"; val = \" + val ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : phenomenonTime / gml : TimePeriod [CODESPLIT] public static TimePeriodType initTimePeriod ( TimePeriodType timePeriod , StationTimeSeriesFeature stationFeat ) throws IOException { // @gml:id String id = MarshallingUtil . createIdForType ( TimePeriodType . class ) ; timePeriod . setId ( id ) ; CollectionInfo info ; try { info = new DsgCollectionHelper ( stationFeat ) . calcBounds ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } CalendarDateRange cdr = info . getCalendarDateRange ( stationFeat . getTimeUnit ( ) ) ; if ( cdr != null ) { // gml:beginPosition NcTimePositionType . initBeginPosition ( timePeriod . addNewBeginPosition ( ) , cdr . getStart ( ) ) ; // gml:endPosition NcTimePositionType . initEndPosition ( timePeriod . addNewEndPosition ( ) , cdr . getEnd ( ) ) ; } return timePeriod ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a Grib1Gds object from a pds and predefined tables . [CODESPLIT] public static Grib1Gds factory ( int center , int gridNumber ) { if ( center == 7 ) { return factoryNCEP ( gridNumber ) ; } else throw new IllegalArgumentException ( \"Dont have predefined GDS \" + gridNumber + \" from \" + center ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "21 - 26 61 - 64 : International Exchange and Family of Services ( FOS ) grids . So may be more general than NCEP [CODESPLIT] private static Grib1Gds factoryNCEP ( int gridNumber ) { switch ( gridNumber ) { case 21 : return new NcepLatLon ( gridNumber , 37 , 36 , 0.0F , 0.0F , 90.0F , 180.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 22 : return new NcepLatLon ( gridNumber , 37 , 36 , 0.0F , - 180.0F , 90.0F , 0.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 23 : return new NcepLatLon ( gridNumber , 37 , 36 , - 90.0F , 0.0F , 180.0F , 0.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 24 : return new NcepLatLon ( gridNumber , 37 , 36 , - 90.0F , - 180.0F , 0.0F , 0.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 25 : return new NcepLatLon ( gridNumber , 72 , 18 , 0.0F , 0.0F , 90.0F , 355.0F , 5.0F , 5.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 26 : return new NcepLatLon ( gridNumber , 72 , 18 , - 90.0F , 0.0F , 0.0F , 355.0F , 5.0F , 5.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 61 : return new NcepLatLon ( gridNumber , 91 , 45 , 0.0F , 0.0F , 90.0F , 180.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 62 : return new NcepLatLon ( gridNumber , 91 , 45 , - 90.0F , 0.0F , 0.0F , 180.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 63 : return new NcepLatLon ( gridNumber , 91 , 45 , - 90.0F , 0.0F , 0.0F , 180.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 64 : return new NcepLatLon ( gridNumber , 91 , 45 , - 90.0F , - 180.0F , 0.0F , 0.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 87 : return new NcepPS ( gridNumber , 81 , 62 , 22.8756F , 239.5089F , 255.0F , 68153.0F , 68153.0F , ( byte ) 0x08 , ( byte ) 64 ) ; } throw new IllegalArgumentException ( \"Dont have predefined GDS \" + gridNumber + \" from NCEP (center 7)\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy all bytes from in and throw them away . [CODESPLIT] static public long copy2null ( InputStream in , int buffersize ) throws IOException { long totalBytesRead = 0 ; if ( buffersize <= 0 ) buffersize = default_file_buffersize ; byte [ ] buffer = new byte [ buffersize ] ; while ( true ) { int n = in . read ( buffer ) ; if ( n == - 1 ) break ; totalBytesRead += n ; } // if (fout != null) fout.format(\"done=%d %n\",totalBytesRead);\r return totalBytesRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy all bytes from in and throw them away . [CODESPLIT] static public long copy2null ( FileChannel in , int buffersize ) throws IOException { long totalBytesRead = 0 ; if ( buffersize <= 0 ) buffersize = default_file_buffersize ; ByteBuffer buffer = ByteBuffer . allocate ( buffersize ) ; while ( true ) { int n = in . read ( buffer ) ; if ( n == - 1 ) break ; totalBytesRead += n ; buffer . flip ( ) ; } return totalBytesRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy all bytes from in to out specify buffer size [CODESPLIT] static public long copyB ( InputStream in , OutputStream out , int bufferSize ) throws IOException { long totalBytesRead = 0 ; int done = 0 , next = 1 ; byte [ ] buffer = new byte [ bufferSize ] ; while ( true ) { int n = in . read ( buffer ) ; if ( n == - 1 ) break ; out . write ( buffer , 0 , n ) ; totalBytesRead += n ; if ( showCopy ) { done += n ; if ( done > 1000 * 1000 * next ) { System . out . println ( next + \" Mb\" ) ; next ++ ; } } } out . flush ( ) ; return totalBytesRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the contents from the inputStream and place into a String with any error messages put in the return String . [CODESPLIT] static public String readContents ( InputStream is , String charset ) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream ( 10 * default_file_buffersize ) ; IO . copy ( is , bout ) ; return bout . toString ( charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the contents from the inputStream and place into a byte array with any error messages put in the return String . [CODESPLIT] static public byte [ ] readContentsToByteArray ( InputStream is ) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream ( 10 * default_file_buffersize ) ; IO . copy ( is , bout ) ; return bout . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wite the contents from the String to a Stream [CODESPLIT] static public void writeContents ( String contents , OutputStream os ) throws IOException { ByteArrayInputStream bin = new ByteArrayInputStream ( contents . getBytes ( CDM . utf8Charset ) ) ; IO . copy ( bin , os ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy one file to another . [CODESPLIT] static public void copyFile ( String fileInName , String fileOutName ) throws IOException { try ( FileInputStream fin = new FileInputStream ( fileInName ) ; FileOutputStream fout = new FileOutputStream ( fileOutName ) ) { InputStream in = new BufferedInputStream ( fin ) ; OutputStream out = new BufferedOutputStream ( fout ) ; IO . copy ( in , out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy one file to another . [CODESPLIT] static public void copyFile ( File fileIn , File fileOut ) throws IOException { try ( FileInputStream fin = new FileInputStream ( fileIn ) ; FileOutputStream fout = new FileOutputStream ( fileOut ) ) { InputStream in = new BufferedInputStream ( fin ) ; OutputStream out = new BufferedOutputStream ( fout ) ; IO . copy ( in , out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy file to output stream [CODESPLIT] static public void copy2File ( byte [ ] src , String fileOut ) throws IOException { try ( FileOutputStream fout = new FileOutputStream ( fileOut ) ) { InputStream in = new BufferedInputStream ( new ByteArrayInputStream ( src ) ) ; OutputStream out = new BufferedOutputStream ( fout ) ; IO . copy ( in , out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy file to output stream [CODESPLIT] static public void copyFile ( String fileInName , OutputStream out ) throws IOException { copyFileB ( new File ( fileInName ) , out , default_file_buffersize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy file to output stream specify internal buffer size [CODESPLIT] static public void copyFileB ( File fileIn , OutputStream out , int bufferSize ) throws IOException { try ( FileInputStream fin = new FileInputStream ( fileIn ) ) { InputStream in = new BufferedInputStream ( fin ) ; IO . copyB ( in , out , bufferSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy part of a RandomAccessFile to output stream specify internal buffer size [CODESPLIT] static public long copyRafB ( ucar . unidata . io . RandomAccessFile raf , long offset , long length , OutputStream out , byte [ ] buffer ) throws IOException { int bufferSize = buffer . length ; long want = length ; raf . seek ( offset ) ; while ( want > 0 ) { int len = ( int ) Math . min ( want , bufferSize ) ; int bytesRead = raf . read ( buffer , 0 , len ) ; if ( bytesRead <= 0 ) break ; out . write ( buffer , 0 , bytesRead ) ; want -= bytesRead ; } out . flush ( ) ; return length - want ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy an entire directory tree . [CODESPLIT] static public void copyDirTree ( String fromDirName , String toDirName ) throws IOException { File fromDir = new File ( fromDirName ) ; File toDir = new File ( toDirName ) ; if ( ! fromDir . exists ( ) ) return ; if ( ! toDir . exists ( ) ) { if ( ! toDir . mkdirs ( ) ) { throw new IOException ( \"Could not create directory: \" + toDir ) ; } } File [ ] files = fromDir . listFiles ( ) ; if ( files != null ) for ( File f : files ) { if ( f . isDirectory ( ) ) copyDirTree ( f . getAbsolutePath ( ) , toDir . getAbsolutePath ( ) + \"/\" + f . getName ( ) ) ; else copyFile ( f . getAbsolutePath ( ) , toDir . getAbsolutePath ( ) + \"/\" + f . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the file and place contents into a byte array with any error messages put in the return String . [CODESPLIT] static public byte [ ] readFileToByteArray ( String filename ) throws IOException { try ( FileInputStream fin = new FileInputStream ( filename ) ) { InputStream in = new BufferedInputStream ( fin ) ; return readContentsToByteArray ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the contents from the named file and place into a String assuming UTF - 8 encoding . [CODESPLIT] static public String readFile ( String filename ) throws IOException { try ( FileInputStream fin = new FileInputStream ( filename ) ) { InputStreamReader reader = new InputStreamReader ( fin , CDM . utf8Charset ) ; StringWriter swriter = new StringWriter ( 50000 ) ; UnsynchronizedBufferedWriter writer = new UnsynchronizedBufferedWriter ( swriter ) ; writer . write ( reader ) ; return swriter . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write String contents to a file using UTF - 8 encoding . [CODESPLIT] static public void writeToFile ( String contents , File file ) throws IOException { try ( FileOutputStream fout = new FileOutputStream ( file ) ) { OutputStreamWriter fw = new OutputStreamWriter ( fout , CDM . utf8Charset ) ; UnsynchronizedBufferedWriter writer = new UnsynchronizedBufferedWriter ( fw ) ; writer . write ( contents ) ; writer . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write byte [] contents to a file . [CODESPLIT] static public void writeToFile ( byte [ ] contents , File file ) throws IOException { try ( FileOutputStream fw = new FileOutputStream ( file ) ) { fw . write ( contents ) ; fw . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write contents to a file using UTF - 8 encoding . [CODESPLIT] static public void writeToFile ( String contents , String fileOutName ) throws IOException { writeToFile ( contents , new File ( fileOutName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy input stream to file . close input stream when done . [CODESPLIT] static public long writeToFile ( InputStream in , String fileOutName ) throws IOException { try ( FileOutputStream fout = new FileOutputStream ( fileOutName ) ) { OutputStream out = new BufferedOutputStream ( fout ) ; return IO . copy ( in , out ) ; } finally { if ( null != in ) in . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy contents of URL to output stream specify internal buffer size . request gzip encoding [CODESPLIT] static public long copyUrlB ( String urlString , OutputStream out , int bufferSize ) throws IOException { long count ; URL url ; try { url = new URL ( urlString ) ; } catch ( MalformedURLException e ) { throw new IOException ( \"** MalformedURLException on URL <\" + urlString + \">\\n\" + e . getMessage ( ) + \"\\n\" ) ; } try { java . net . URLConnection connection = url . openConnection ( ) ; java . net . HttpURLConnection httpConnection = null ; if ( connection instanceof java . net . HttpURLConnection ) { httpConnection = ( java . net . HttpURLConnection ) connection ; httpConnection . addRequestProperty ( \"Accept-Encoding\" , \"gzip\" ) ; } if ( showHeaders ) { showRequestHeaders ( urlString , connection ) ; } // get response\r if ( httpConnection != null ) { int responseCode = httpConnection . getResponseCode ( ) ; if ( responseCode / 100 != 2 ) throw new IOException ( \"** Cant open URL <\" + urlString + \">\\n Response code = \" + responseCode + \"\\n\" + httpConnection . getResponseMessage ( ) + \"\\n\" ) ; } if ( showHeaders && ( httpConnection != null ) ) { int code = httpConnection . getResponseCode ( ) ; String response = httpConnection . getResponseMessage ( ) ; // response headers\r System . out . println ( \"\\nRESPONSE for \" + urlString + \": \" ) ; System . out . println ( \" HTTP/1.x \" + code + \" \" + response ) ; System . out . println ( \"Headers: \" ) ; for ( int j = 1 ; ; j ++ ) { String header = connection . getHeaderField ( j ) ; String key = connection . getHeaderFieldKey ( j ) ; if ( header == null || key == null ) break ; System . out . println ( \" \" + key + \": \" + header ) ; } } // read it\r try ( InputStream is = connection . getInputStream ( ) ) { BufferedInputStream bis ; // check if its gzipped\r if ( \"gzip\" . equalsIgnoreCase ( connection . getContentEncoding ( ) ) ) { bis = new BufferedInputStream ( new GZIPInputStream ( is ) , 8000 ) ; } else { bis = new BufferedInputStream ( is , 8000 ) ; } if ( out == null ) count = IO . copy2null ( bis , bufferSize ) ; else count = IO . copyB ( bis , out , bufferSize ) ; } } catch ( java . net . ConnectException e ) { if ( showStackTrace ) e . printStackTrace ( ) ; throw new IOException ( \"** ConnectException on URL: <\" + urlString + \">\\n\" + e . getMessage ( ) + \"\\nServer probably not running\" ) ; } catch ( java . net . UnknownHostException e ) { if ( showStackTrace ) e . printStackTrace ( ) ; throw new IOException ( \"** UnknownHostException on URL: <\" + urlString + \">\\n\" ) ; } catch ( Exception e ) { if ( showStackTrace ) e . printStackTrace ( ) ; throw new IOException ( \"** Exception on URL: <\" + urlString + \">\\n\" + e ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns a ParseException into a OPeNDAP DAP2 error and sends it to the client . [CODESPLIT] public void parseExceptionHandler ( ParseException pe , HttpServletResponse response ) { //log.error(\"DODSServlet.parseExceptionHandler\", pe); if ( Debug . isSet ( \"showException\" ) ) { log . error ( pe . toString ( ) ) ; printThrowable ( pe ) ; } try { BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; response . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // This should probably be set to \"plain\" but this works, the // C++ slients don't barf as they would if I sent \"plain\" AND // the C++ don't expect compressed data if I do this... response . setHeader ( \"Content-Encoding\" , \"\" ) ; // response.setContentType(\"text/plain\"); // Strip any double quotes out of the parser error message. // These get stuck in auto-magically by the javacc generated parser // code and they break our error parser (bummer!) String msg = pe . getMessage ( ) . replace ( ' ' , ' ' ) ; DAP2Exception de2 = new DAP2Exception ( opendap . dap . DAP2Exception . CANNOT_READ_FILE , msg ) ; de2 . print ( eOut ) ; } catch ( IOException ioe ) { log . error ( \"Cannot respond to client! IO Error: \" + ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a OPeNDAP DAP2 error to the client . [CODESPLIT] public void dap2ExceptionHandler ( DAP2Exception de , HttpServletResponse response ) { //log.info(\"DODSServlet.dodsExceptionHandler (\" + de.getErrorCode() + \") \" + de.getErrorMessage()); if ( Debug . isSet ( \"showException\" ) ) { log . error ( de . toString ( ) ) ; de . printStackTrace ( ) ; printDODSException ( de ) ; } // Convert Dap2Excaption code to an HttpCode switch ( de . getErrorCode ( ) ) { case DAP2Exception . NO_SUCH_FILE : case DAP2Exception . CANNOT_READ_FILE : response . setStatus ( HttpStatus . SC_NOT_FOUND ) ; break ; case DAP2Exception . NO_AUTHORIZATION : response . setStatus ( HttpStatus . SC_UNAUTHORIZED ) ; break ; case DAP2Exception . NO_SUCH_VARIABLE : case DAP2Exception . MALFORMED_EXPR : case DAP2Exception . UNKNOWN_ERROR : // fall thru default : response . setStatus ( HttpStatus . SC_BAD_REQUEST ) ; break ; } try { BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; response . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // This should probably be set to \"plain\" but this works, the // C++ slients don't barf as they would if I sent \"plain\" AND // the C++ don't expect compressed data if I do this... response . setHeader ( \"Content-Encoding\" , \"\" ) ; de . print ( eOut ) ; } catch ( IOException ioe ) { log . error ( \"Cannot respond to client! IO Error: \" + ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends an error to the client . fix : The problem is that if the message is already committed when the IOException occurs the headers dont get set . [CODESPLIT] public void IOExceptionHandler ( IOException e , ReqState rs ) { HttpServletResponse response = rs . getResponse ( ) ; try { BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; response . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // This should probably be set to \"plain\" but this works, the // C++ slients don't barf as they would if I sent \"plain\" AND // the C++ don't expect compressed data if I do this... response . setHeader ( \"Content-Encoding\" , \"\" ) ; // Strip any double quotes out of the parser error message. // These get stuck in auto-magically by the javacc generated parser // code and they break our error parser (bummer!) String msg = e . getMessage ( ) ; if ( msg != null ) msg = msg . replace ( ' ' , ' ' ) ; DAP2Exception de2 = new DAP2Exception ( opendap . dap . DAP2Exception . CANNOT_READ_FILE , msg ) ; de2 . print ( eOut ) ; if ( Debug . isSet ( \"showException\" ) ) { // Error message log . error ( \"DODServlet ERROR (IOExceptionHandler): \" + e ) ; log . error ( rs . toString ( ) ) ; if ( track ) { RequestDebug reqD = ( RequestDebug ) rs . getUserObject ( ) ; log . error ( \"  request number: \" + reqD . reqno + \" thread: \" + reqD . threadDesc ) ; } printThrowable ( e ) ; } } catch ( IOException ioe ) { log . error ( \"Cannot respond to client! IO Error: \" + ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a OPeNDAP DAP2 error ( type UNKNOWN ERROR ) to the client and displays a message on the server console . [CODESPLIT] public void sendDODSError ( ReqState rs , String clientMsg , String serverMsg ) throws Exception { rs . getResponse ( ) . setContentType ( \"text/plain\" ) ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // Commented because of a bug in the OPeNDAP C++ stuff... //response.setHeader(\"Content-Encoding\", \"none\"); ServletOutputStream Out = rs . getResponse ( ) . getOutputStream ( ) ; DAP2Exception de = new DAP2Exception ( opendap . dap . DAP2Exception . UNKNOWN_ERROR , clientMsg ) ; de . print ( Out ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; log . error ( serverMsg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for the client s DDX request . Requires the getDDX () method implemented by each server localization effort . <p > <p > Once the DDX has been parsed and constrained it is sent to the requesting client . [CODESPLIT] public void doGetDDX ( ReqState rs ) throws Exception { if ( Debug . isSet ( \"showResponse\" ) ) { log . debug ( \"doGetDDX for dataset: \" + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( null == ds ) return ; rs . getResponse ( ) . setContentType ( \"text/plain\" ) ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-ddx\" ) ; // Commented because of a bug in the OPeNDAP C++ stuff... // rs.getResponse().setHeader(\"Content-Encoding\", \"plain\"); OutputStream Out = new BufferedOutputStream ( rs . getResponse ( ) . getOutputStream ( ) ) ; // Utilize the getDDS() method to get a parsed and populated DDS // for this server. ServerDDS myDDS = ds . getDDS ( ) ; if ( rs . getConstraintExpression ( ) . equals ( \"\" ) ) { // No Constraint Expression? // Send the whole DDS myDDS . printXML ( Out ) ; Out . flush ( ) ; } else { // Otherwise, send the constrained DDS // Instantiate the CEEvaluator and parse the constraint expression CEEvaluator ce = new CEEvaluator ( myDDS ) ; ce . parseConstraint ( rs ) ; // Send the constrained DDS back to the client PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( Out , Util . UTF8 ) ) ; myDDS . printConstrainedXML ( pw ) ; pw . flush ( ) ; } rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; if ( Debug . isSet ( \"showResponse\" ) ) { if ( rs . getConstraintExpression ( ) . equals ( \"\" ) ) { // No Constraint Expression? //          log.debug(\"Unconstrained DDX=\\n\"); //          myDDS.printXML(System.out); } else { //          log.debug(\"Constrained DDX=\\n\"); //          myDDS.printConstrainedXML(System.out); } } } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException pe ) { IOExceptionHandler ( pe , rs ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed if ( ds != null ) ds . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for the client s data request . Requires the getDDS () method implemented by each server localization effort . <p > <p > Once the DDS has been parsed the data is read ( using the class in the localized server factory etc . ) compared to the constraint expression and then sent to the client . [CODESPLIT] public void doGetBLOB ( ReqState rs ) throws Exception { if ( Debug . isSet ( \"showResponse\" ) ) { log . debug ( \"doGetBLOB For: \" + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; rs . getResponse ( ) . setContentType ( \"application/octet-stream\" ) ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-blob\" ) ; ServletOutputStream sOut = rs . getResponse ( ) . getOutputStream ( ) ; OutputStream bOut ; DeflaterOutputStream dOut = null ; if ( rs . getAcceptsCompressed ( ) && allowDeflate ) { rs . getResponse ( ) . setHeader ( \"Content-Encoding\" , \"deflate\" ) ; dOut = new DeflaterOutputStream ( sOut ) ; bOut = new BufferedOutputStream ( dOut ) ; } else { // Commented out because of a bug in the OPeNDAP C++ stuff... //rs.getResponse().setHeader(\"Content-Encoding\", \"plain\"); bOut = new BufferedOutputStream ( sOut ) ; } // Utilize the getDDS() method to get // a parsed and populated DDS // for this server. ServerDDS myDDS = ds . getDDS ( ) ; cacheArrayShapes ( myDDS ) ; // Instantiate the CEEvaluator and parse the constraint expression CEEvaluator ce = new CEEvaluator ( myDDS , new ClauseFactory ( functionLibrary ) ) ; ce . parseConstraint ( rs . getConstraintExpression ( ) , rs . getRequestURL ( ) . toString ( ) ) ; // Send the binary data back to the client DataOutputStream sink = new DataOutputStream ( bOut ) ; int seqLength = 5 ; String sls = rs . getInitParameter ( \"SequenceLength\" ) ; if ( sls != null ) { seqLength = ( Integer . valueOf ( sls ) ) . intValue ( ) ; } testEngine te = new testEngine ( seqLength ) ; ce . send ( myDDS . getEncodedName ( ) , sink , te ) ; sink . flush ( ) ; // Finish up sending the compressed stuff, but don't // close the stream (who knows what the Servlet may expect!) if ( rs . getAcceptsCompressed ( ) ) { if ( bOut != null ) bOut . flush ( ) ; if ( dOut != null ) ( ( DeflaterOutputStream ) dOut ) . finish ( ) ; } //? if(null != dOut) dOut.finish(); //? bOut.flush(); rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException ioe ) { IOExceptionHandler ( ioe , rs ) ; } finally { // release lock if needed if ( ds != null ) ds . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for the client s directory request . <p > Returns an html document to the client showing ( a possibly pseudo ) listing of the datasets available on the server in a directory listing format . <p > The bulk of this code resides in the class opendap . servlet . GetDirHandler and documentation may be found there . [CODESPLIT] public void doGetDIR ( ReqState rs ) throws Exception { rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/html\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-directory\" ) ; try { GetDirHandler di = new GetDirHandler ( ) ; di . sendDIR ( rs ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends an html document to the client explaining that they have used a poorly formed URL and then the help page ... [CODESPLIT] public void badURL ( HttpServletRequest request , HttpServletResponse response ) throws Exception { if ( Debug . isSet ( \"showResponse\" ) ) { log . debug ( \"Sending Bad URL Page.\" ) ; } //log.info(\"DODSServlet.badURL \" + rs.getRequest().getRequestURI()); response . setContentType ( \"text/html\" ) ; response . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; response . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // Commented because of a bug in the OPeNDAP C++ stuff... //rs.getResponse().setHeader(\"Content-Encoding\", \"plain\"); PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( response . getOutputStream ( ) , Util . UTF8 ) ) ; printBadURLPage ( pw ) ; printHelpPage ( pw ) ; pw . flush ( ) ; response . setStatus ( HttpServletResponse . SC_OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for OPeNDAP info requests . Returns an HTML document describing the contents of the servers datasets . <p > The bulk of this code resides in the class opendap . servlet . GetInfoHandler and documentation may be found there . [CODESPLIT] public void doGetINFO ( ReqState rs ) throws Exception { if ( Debug . isSet ( \"showResponse\" ) ) { log . debug ( \"doGetINFO For: \" + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/html\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-description\" ) ; GetInfoHandler di = new GetInfoHandler ( ) ; di . sendINFO ( pw , ds , rs ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException pe ) { IOExceptionHandler ( pe , rs ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed if ( ds != null ) ds . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for OPeNDAP . html requests . Returns the OPeNDAP Web Interface ( aka The Interface From Hell ) to the client . <p > The bulk of this code resides in the class opendap . servlet . GetHTMLInterfaceHandler and documentation may be found there . [CODESPLIT] public void doGetHTML ( ReqState rs ) throws Exception { GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/html\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-form\" ) ; // Utilize the getDDS() method to get\ta parsed and populated DDS // for this server. ServerDDS myDDS = ds . getDDS ( ) ; DAS das = ds . getDAS ( ) ; GetHTMLInterfaceHandler di = new GetHTMLInterfaceHandler ( ) ; di . sendDataRequestForm ( rs , rs . getDataSet ( ) , myDDS , das ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException pe ) { IOExceptionHandler ( pe , rs ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed if ( ds != null ) ds . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for OPeNDAP catalog . xml requests . [CODESPLIT] public void doGetCatalog ( ReqState rs ) throws Exception { rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/xml\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-catalog\" ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; printCatalog ( rs , pw ) ; pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to be overridden by servers that implement catalogs [CODESPLIT] protected void printCatalog ( ReqState rs , PrintWriter os ) throws IOException { os . println ( \"Catalog not available for this server\" ) ; os . println ( \"Server version = \" + getServerVersion ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for OPeNDAP status requests ; not publically available used only for debugging [CODESPLIT] public void doGetSystemProps ( ReqState rs ) throws Exception { rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/html\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-status\" ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; pw . println ( \"<html>\" ) ; pw . println ( \"<title>System Properties</title>\" ) ; pw . println ( \"<hr>\" ) ; pw . println ( \"<body><h2>System Properties</h2>\" ) ; pw . println ( \"<h3>Date: \" + new Date ( ) + \"</h3>\" ) ; Properties sysp = System . getProperties ( ) ; Enumeration e = sysp . propertyNames ( ) ; pw . println ( \"<ul>\" ) ; while ( e . hasMoreElements ( ) ) { String name = ( String ) e . nextElement ( ) ; String value = System . getProperty ( name ) ; pw . println ( \"<li>\" + name + \": \" + value + \"</li>\" ) ; } pw . println ( \"</ul>\" ) ; pw . println ( \"<h3>Runtime Info:</h3>\" ) ; Runtime rt = Runtime . getRuntime ( ) ; pw . println ( \"JVM Max Memory:   \" + ( rt . maxMemory ( ) / 1024 ) / 1000. + \" MB (JVM Maximum Allowable Heap)<br>\" ) ; pw . println ( \"JVM Total Memory: \" + ( rt . totalMemory ( ) / 1024 ) / 1000. + \" MB (JVM Heap size)<br>\" ) ; pw . println ( \"JVM Free Memory:  \" + ( rt . freeMemory ( ) / 1024 ) / 1000. + \" MB (Unused part of heap)<br>\" ) ; pw . println ( \"JVM Used Memory:  \" + ( ( rt . totalMemory ( ) - rt . freeMemory ( ) ) / 1024 ) / 1000. + \" MB (Currently active memory)<br>\" ) ; pw . println ( \"<hr>\" ) ; pw . println ( \"</body>\" ) ; pw . println ( \"</html>\" ) ; pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for OPeNDAP status requests ; not publically available used only for debugging [CODESPLIT] public void doGetStatus ( ReqState rs ) throws Exception { rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/html\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-status\" ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; pw . println ( \"<title>Server Status</title>\" ) ; pw . println ( \"<body><ul>\" ) ; printStatus ( pw ) ; pw . println ( \"</ul></body>\" ) ; pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to be overridden by servers that implement status report [CODESPLIT] protected void printStatus ( PrintWriter os ) { os . println ( \"<h2>Server version = \" + getServerVersion ( ) + \"</h2>\" ) ; os . println ( \"<h2>Number of Requests Received = \" + HitCounter + \"</h2>\" ) ; if ( track ) { int n = prArr . size ( ) ; int pending = 0 ; StringBuilder preqs = new StringBuilder ( ) ; for ( int i = 0 ; i < n ; i ++ ) { ReqState rs = ( ReqState ) prArr . get ( i ) ; RequestDebug reqD = ( RequestDebug ) rs . getUserObject ( ) ; if ( ! reqD . done ) { preqs . append ( \"<pre>-----------------------\\n\" ) ; preqs . append ( \"Request[\" ) ; preqs . append ( reqD . reqno ) ; preqs . append ( \"](\" ) ; preqs . append ( reqD . threadDesc ) ; preqs . append ( \") is pending.\\n\" ) ; preqs . append ( rs . toString ( ) ) ; preqs . append ( \"</pre>\" ) ; pending ++ ; } } os . println ( \"<h2>\" + pending + \" Pending Request(s)</h2>\" ) ; os . println ( preqs . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a bit of instrumentation that I kept around to let me look at the state of the incoming <code > HttpServletRequest< / code > from the client . This method calls the <code > get * < / code > methods of the request and prints the results to standard out . [CODESPLIT] public void probeRequest ( PrintStream ps , ReqState rs ) { Enumeration e ; int i ; HttpServletRequest request = rs . getRequest ( ) ; ps . println ( \"####################### PROBE ##################################\" ) ; ps . println ( \"The HttpServletRequest object is actually a: \" + request . getClass ( ) . getName ( ) ) ; ps . println ( \"\" ) ; ps . println ( \"HttpServletRequest Interface:\" ) ; ps . println ( \"    getAuthType:           \" + request . getAuthType ( ) ) ; ps . println ( \"    getMethod:             \" + request . getMethod ( ) ) ; ps . println ( \"    getPathInfo:           \" + request . getPathInfo ( ) ) ; ps . println ( \"    getPathTranslated:     \" + request . getPathTranslated ( ) ) ; ps . println ( \"    getRequestURL:         \" + request . getRequestURL ( ) ) ; ps . println ( \"    getQueryString:        \" + request . getQueryString ( ) ) ; ps . println ( \"    getRemoteUser:         \" + request . getRemoteUser ( ) ) ; ps . println ( \"    getRequestedSessionId: \" + request . getRequestedSessionId ( ) ) ; ps . println ( \"    getRequestURI:         \" + request . getRequestURI ( ) ) ; ps . println ( \"    getServletPath:        \" + request . getServletPath ( ) ) ; ps . println ( \"    isRequestedSessionIdFromCookie: \" + request . isRequestedSessionIdFromCookie ( ) ) ; ps . println ( \"    isRequestedSessionIdValid:      \" + request . isRequestedSessionIdValid ( ) ) ; ps . println ( \"    isRequestedSessionIdFromURL:    \" + request . isRequestedSessionIdFromURL ( ) ) ; ps . println ( \"\" ) ; i = 0 ; e = request . getHeaderNames ( ) ; ps . println ( \"    Header Names:\" ) ; while ( e . hasMoreElements ( ) ) { i ++ ; String s = ( String ) e . nextElement ( ) ; ps . print ( \"        Header[\" + i + \"]: \" + s ) ; ps . println ( \": \" + request . getHeader ( s ) ) ; } ps . println ( \"\" ) ; ps . println ( \"ServletRequest Interface:\" ) ; ps . println ( \"    getCharacterEncoding:  \" + request . getCharacterEncoding ( ) ) ; ps . println ( \"    getContentType:        \" + request . getContentType ( ) ) ; ps . println ( \"    getContentLength:      \" + request . getContentLength ( ) ) ; ps . println ( \"    getProtocol:           \" + request . getProtocol ( ) ) ; ps . println ( \"    getScheme:             \" + request . getScheme ( ) ) ; ps . println ( \"    getServerName:         \" + request . getServerName ( ) ) ; ps . println ( \"    getServerPort:         \" + request . getServerPort ( ) ) ; ps . println ( \"    getRemoteAddr:         \" + request . getRemoteAddr ( ) ) ; ps . println ( \"    getRemoteHost:         \" + request . getRemoteHost ( ) ) ; //ps.println(\"    getRealPath:           \"+request.getRealPath()); ps . println ( \".............................\" ) ; ps . println ( \"\" ) ; i = 0 ; e = request . getAttributeNames ( ) ; ps . println ( \"    Attribute Names:\" ) ; while ( e . hasMoreElements ( ) ) { i ++ ; String s = ( String ) e . nextElement ( ) ; ps . print ( \"        Attribute[\" + i + \"]: \" + s ) ; ps . println ( \" Type: \" + request . getAttribute ( s ) ) ; } ps . println ( \".............................\" ) ; ps . println ( \"\" ) ; i = 0 ; e = request . getParameterNames ( ) ; ps . println ( \"    Parameter Names:\" ) ; while ( e . hasMoreElements ( ) ) { i ++ ; String s = ( String ) e . nextElement ( ) ; ps . print ( \"        Parameter[\" + i + \"]: \" + s ) ; ps . println ( \" Value: \" + request . getParameter ( s ) ) ; } ps . println ( \"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\" ) ; ps . println ( \" . . . . . . . . . Servlet Infomation API  . . . . . . . . . . . . . .\" ) ; ps . println ( \"\" ) ; ps . println ( \"Servlet Context:\" ) ; ps . println ( \"\" ) ; i = 0 ; e = servletContext . getAttributeNames ( ) ; ps . println ( \"    Attribute Names:\" ) ; while ( e . hasMoreElements ( ) ) { i ++ ; String s = ( String ) e . nextElement ( ) ; ps . print ( \"        Attribute[\" + i + \"]: \" + s ) ; ps . println ( \" Type: \" + servletContext . getAttribute ( s ) ) ; } ps . println ( \"    ServletContext.getRealPath(\\\".\\\"): \" + servletContext . getRealPath ( \".\" ) ) ; ps . println ( \"    ServletContext.getMajorVersion(): \" + servletContext . getMajorVersion ( ) ) ; //        ps.println(\"ServletContext.getMimeType():     \" + sc.getMimeType()); ps . println ( \"    ServletContext.getMinorVersion(): \" + servletContext . getMinorVersion ( ) ) ; //        ps.println(\"ServletContext.getRealPath(): \" + sc.getRealPath()); ps . println ( \".............................\" ) ; ps . println ( \"Servlet Config:\" ) ; ps . println ( \"\" ) ; ServletConfig scnfg = getServletConfig ( ) ; i = 0 ; e = scnfg . getInitParameterNames ( ) ; ps . println ( \"    InitParameters:\" ) ; while ( e . hasMoreElements ( ) ) { String p = ( String ) e . nextElement ( ) ; ps . print ( \"        InitParameter[\" + i + \"]: \" + p ) ; ps . println ( \" Value: \" + scnfg . getInitParameter ( p ) ) ; i ++ ; } ps . println ( \"\" ) ; ps . println ( \"######################## END PROBE ###############################\" ) ; ps . println ( \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles incoming requests from clients . Parses the request and determines what kind of OPeNDAP response the client is requesting . If the request is understood then the appropriate handler method is called otherwise an error is returned to the client . <p > This method is the entry point for <code > DTSServlet< / code > . [CODESPLIT] public void doGet ( HttpServletRequest request , HttpServletResponse response ) { log . debug ( \"DTS doGet()\" ) ; long tid = Thread . currentThread ( ) . getId ( ) ; log . debug ( \"thread=\" + tid ) ; // setHeader(\"Last-Modified\", (new Date()).toString() ); boolean isDebug = false ; ReqState rs = null ; RequestDebug reqD = null ; try { //      if(Debug.isSet(\"probeRequest\")) //        probeRequest(System.out, rs); rs = getRequestState ( request , response ) ; assert ( rs != null ) ; if ( rs != null ) { String ds = rs . getDataSet ( ) ; String suff = rs . getRequestSuffix ( ) ; isDebug = ( ( ds != null ) && ds . equals ( \"debug\" ) && ( suff != null ) && suff . equals ( \"\" ) ) ; } synchronized ( syncLock ) { if ( ! isDebug ) { long reqno = HitCounter ++ ; if ( track ) { reqD = new RequestDebug ( reqno , Thread . currentThread ( ) . toString ( ) ) ; rs . setUserObject ( reqD ) ; if ( prArr == null ) prArr = new ArrayList ( 10000 ) ; prArr . add ( ( int ) reqno , rs ) ; } if ( Debug . isSet ( \"showRequest\" ) ) { log . debug ( \"-------------------------------------------\" ) ; log . debug ( \"Server: \" + getServerName ( ) + \"   Request #\" + reqno ) ; log . debug ( \"Client: \" + request . getRemoteHost ( ) ) ; log . debug ( rs . toString ( ) ) ; log . debug ( \"Request dataset: '\" + rs . getDataSet ( ) + \"' suffix: '\" + rs . getRequestSuffix ( ) + \"' CE: '\" + rs . getConstraintExpression ( ) + \"'\" ) ; } } } // synch if ( rs != null ) { String dataSet = rs . getDataSet ( ) ; String requestSuffix = rs . getRequestSuffix ( ) ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; // Make sure always set if ( dataSet == null || dataSet . equals ( \"/\" ) || dataSet . equals ( \"\" ) ) { doGetDIR ( rs ) ; } else if ( dataSet . equalsIgnoreCase ( \"/version\" ) || dataSet . equalsIgnoreCase ( \"/version/\" ) ) { doGetVER ( rs ) ; } else if ( dataSet . equalsIgnoreCase ( \"/help\" ) || dataSet . equalsIgnoreCase ( \"/help/\" ) ) { doGetHELP ( rs ) ; } else if ( dataSet . equalsIgnoreCase ( \"/\" + requestSuffix ) ) { doGetHELP ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"dds\" ) ) { doGetDDS ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"das\" ) ) { doGetDAS ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"ddx\" ) ) { doGetDDX ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"blob\" ) ) { doGetBLOB ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"dods\" ) ) { doGetDAP2Data ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"asc\" ) || requestSuffix . equalsIgnoreCase ( \"ascii\" ) ) { doGetASC ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"info\" ) ) { doGetINFO ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"html\" ) || requestSuffix . equalsIgnoreCase ( \"htm\" ) ) { doGetHTML ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"ver\" ) || requestSuffix . equalsIgnoreCase ( \"version\" ) ) { doGetVER ( rs ) ; } else if ( requestSuffix . equalsIgnoreCase ( \"help\" ) ) { doGetHELP ( rs ) ; /* JC added\n        } else if(dataSet.equalsIgnoreCase(\"catalog\") && requestSuffix.equalsIgnoreCase(\"xml\")) {\n          doGetCatalog(rs);\n        } else if(dataSet.equalsIgnoreCase(\"status\")) {\n          doGetStatus(rs);\n        } else if(dataSet.equalsIgnoreCase(\"systemproperties\")) {\n          doGetSystemProps(rs);\n        } else if(isDebug) {\n          doDebug(rs);  */ } else if ( requestSuffix . equals ( \"\" ) ) { badURL ( request , response ) ; } else { badURL ( request , response ) ; } } else { // rs == null badURL ( request , response ) ; } if ( reqD != null ) reqD . done = true ; } catch ( Throwable e ) { anyExceptionHandler ( e , rs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************** [CODESPLIT] void showMemUsed ( String from ) { long totalMemory = Runtime . getRuntime ( ) . totalMemory ( ) ; long freeMemory = Runtime . getRuntime ( ) . freeMemory ( ) ; //long maxMemory = Runtime.getRuntime ().maxMemory (); long usedMemory = ( totalMemory - freeMemory ) ; log . debug ( \"****showMemUsed \" + from ) ; log . debug ( \" totalMemory \" + totalMemory ) ; log . debug ( \" freeMemory \" + freeMemory ) ; //log.debug(\" maxMemory \"+maxMemory); log . debug ( \" usedMemory \" + usedMemory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the Bad URL Page page to the passed PrintWriter [CODESPLIT] private void printBadURLPage ( PrintWriter pw ) { pw . println ( \"<h3>Error in URL</h3>\" ) ; pw . println ( \"The URL extension did not match any that are known by this\" ) ; pw . println ( \"server. Below is a list of the five extensions that are be recognized by\" ) ; pw . println ( \"all OPeNDAP servers. If you think that the server is broken (that the URL you\" ) ; pw . println ( \"submitted should have worked), then please contact the\" ) ; pw . println ( \"OPeNDAP user support coordinator at: \" ) ; pw . println ( \"<a href=\\\"mailto:support@unidata.ucar.edu\\\">support@unidata.ucar.edu</a><p>\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reference reference or base time as Dare . [CODESPLIT] public CalendarDate getReferenceDate ( ) { return CalendarDate . of ( null , year , month , day , hour , minute , second ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an entity for resolution . Specify a local resource and / or a URL . Look for the local Resource first . [CODESPLIT] static public void initEntity ( String entityName , String resourceName , String urlName ) { String entity = null ; try ( InputStream is = ucar . nc2 . util . IO . getFileResource ( resourceName ) ) { // try to read from local file resource, eg from catalog.jar\r ByteArrayOutputStream sbuff = new ByteArrayOutputStream ( 3000 ) ; if ( is != null ) { IO . copy ( is , sbuff ) ; entity = new String ( sbuff . toByteArray ( ) , CDM . utf8Charset ) ; logger . debug ( \" *** entity \" + entityName + \" mapped to local resource at \" + resourceName ) ; } else if ( urlName != null ) { // otherwise, get from network\r entity = IO . readURLcontentsWithException ( urlName ) ; logger . debug ( \" *** entity \" + entityName + \" mapped to remote URL at \" + urlName ) ; } } catch ( IOException e ) { System . out . println ( \" *** FAILED to map entity \" + entityName + \" locally at \" + resourceName + \" or remotely at \" + urlName ) ; // e.printStackTrace();\r } entityHash . put ( entityName , entity ) ; entityHash . put ( urlName , entity ) ; // also map it to the remote URL\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we read the DTD / schema locally if we can . [CODESPLIT] public org . xml . sax . InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { logger . debug ( \"  publicId=\" + publicId + \" systemId=\" + systemId ) ; String entity = entityHash . get ( systemId ) ; if ( entity != null ) { logger . debug ( \" *** resolved  with local copy\" ) ; return new MyInputSource ( entity ) ; } if ( systemId . contains ( \"InvCatalog.0.6.dtd\" ) ) { entity = entityHash . get ( \"http://www.unidata.ucar.edu/schemas/thredds/InvCatalog.0.6.dtd\" ) ; if ( entity != null ) { logger . debug ( \" *** resolved2 with local copy\" ) ; return new MyInputSource ( entity ) ; } } logger . debug ( \" *** not resolved\" ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lOOK probably desnt work [CODESPLIT] private Array readVlenData ( Variable v , Section section , DataStorage dataStorage ) throws IOException , InvalidRangeException { raf . seek ( dataStorage . filePos ) ; int nelems = readVInt ( raf ) ; Array [ ] result = new Array [ nelems ] ; for ( int elem = 0 ; elem < nelems ; elem ++ ) { int dsize = readVInt ( raf ) ; byte [ ] data = new byte [ dsize ] ; raf . readFully ( data ) ; Array dataArray = Array . factory ( v . getDataType ( ) , ( int [ ] ) null , ByteBuffer . wrap ( data ) ) ; result [ elem ] = dataArray ; } // return Array.makeObjectArray(v.getDataType(), result[0].getClass(), new int[]{nelems}, result);\r return Array . makeVlenArray ( new int [ ] { nelems } , result ) ; //return dataArray.section(section.getRanges());\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "optionally read in all messages return as List<NcMess > [CODESPLIT] public void openDebug ( RandomAccessFile raf , NetcdfFile ncfile , List < NcsMess > ncm ) throws IOException { raf . seek ( 0 ) ; long pos = raf . getFilePointer ( ) ; if ( ! readAndTest ( raf , NcStream . MAGIC_START ) ) { if ( ncm != null ) { ncm . add ( new NcsMess ( pos , 0 , \"MAGIC_START missing - abort\" ) ) ; return ; } throw new IOException ( \"Data corrupted on \" + raf . getLocation ( ) ) ; } if ( ncm != null ) ncm . add ( new NcsMess ( pos , 4 , \"MAGIC_START\" ) ) ; pos = raf . getFilePointer ( ) ; if ( ! readAndTest ( raf , NcStream . MAGIC_HEADER ) ) { if ( ncm != null ) { ncm . add ( new NcsMess ( pos , 0 , \"MAGIC_HEADER missing - abort\" ) ) ; return ; } throw new IOException ( \"Data corrupted on \" + ncfile . getLocation ( ) ) ; } if ( ncm != null ) ncm . add ( new NcsMess ( pos , 4 , \"MAGIC_HEADER\" ) ) ; // assume for the moment it always starts with one header message\r pos = raf . getFilePointer ( ) ; int msize = readVInt ( raf ) ; byte [ ] m = new byte [ msize ] ; raf . readFully ( m ) ; NcStreamProto . Header proto = NcStreamProto . Header . parseFrom ( m ) ; if ( ncm != null ) ncm . add ( new NcsMess ( pos , msize , proto ) ) ; version = proto . getVersion ( ) ; NcStreamProto . Group root = proto . getRoot ( ) ; NcStream . readGroup ( root , ncfile , ncfile . getRootGroup ( ) ) ; ncfile . finish ( ) ; // then we have a stream of data messages with a final END or ERR\r while ( ! raf . isAtEndOfFile ( ) ) { pos = raf . getFilePointer ( ) ; byte [ ] b = new byte [ 4 ] ; raf . readFully ( b ) ; if ( test ( b , NcStream . MAGIC_END ) ) { if ( ncm != null ) ncm . add ( new NcsMess ( pos , 4 , \"MAGIC_END\" ) ) ; break ; } if ( test ( b , NcStream . MAGIC_ERR ) ) { int esize = readVInt ( raf ) ; byte [ ] dp = new byte [ esize ] ; raf . readFully ( dp ) ; NcStreamProto . Error error = NcStreamProto . Error . parseFrom ( dp ) ; if ( ncm != null ) ncm . add ( new NcsMess ( pos , esize , error . getMessage ( ) ) ) ; break ; // assume broken now ?\r } if ( ! test ( b , NcStream . MAGIC_DATA ) ) { if ( ncm != null ) ncm . add ( new NcsMess ( pos , 4 , \"MAGIC_DATA missing - abort\" ) ) ; break ; } if ( ncm != null ) ncm . add ( new NcsMess ( pos , 4 , \"MAGIC_DATA\" ) ) ; // data messages\r pos = raf . getFilePointer ( ) ; int psize = readVInt ( raf ) ; byte [ ] dp = new byte [ psize ] ; raf . readFully ( dp ) ; NcStreamProto . Data dproto = NcStreamProto . Data . parseFrom ( dp ) ; ByteOrder bo = NcStream . decodeDataByteOrder ( dproto ) ; // LOOK not using bo !!\r Variable v = ncfile . findVariable ( dproto . getVarName ( ) ) ; if ( v == null ) { System . out . printf ( \" ERR cant find var %s%n%s%n\" , dproto . getVarName ( ) , dproto ) ; } if ( debug ) System . out . printf ( \" dproto = %s for %s%n\" , dproto , v . getShortName ( ) ) ; if ( ncm != null ) ncm . add ( new NcsMess ( pos , psize , dproto ) ) ; List < DataStorage > storage ; if ( v != null ) { storage = ( List < DataStorage > ) v . getSPobject ( ) ; // LOOK could be an in memory Rtree using section\r if ( storage == null ) { storage = new ArrayList <> ( ) ; v . setSPobject ( storage ) ; } } else storage = new ArrayList <> ( ) ; // barf\r // version < 3\r if ( dproto . getDataType ( ) == NcStreamProto . DataType . STRUCTURE ) { pos = raf . getFilePointer ( ) ; msize = readVInt ( raf ) ; m = new byte [ msize ] ; raf . readFully ( m ) ; NcStreamProto . StructureData sdata = NcStreamProto . StructureData . parseFrom ( m ) ; DataStorage dataStorage = new DataStorage ( msize , pos , dproto ) ; dataStorage . sdata = sdata ; if ( ncm != null ) ncm . add ( new NcsMess ( dataStorage . filePos , msize , sdata ) ) ; storage . add ( dataStorage ) ; } else if ( dproto . getVdata ( ) ) { DataStorage dataStorage = new DataStorage ( 0 , raf . getFilePointer ( ) , dproto ) ; int nelems = readVInt ( raf ) ; int totalSize = 0 ; for ( int i = 0 ; i < nelems ; i ++ ) { int dsize = readVInt ( raf ) ; totalSize += dsize ; raf . skipBytes ( dsize ) ; } dataStorage . nelems = nelems ; dataStorage . size = totalSize ; if ( ncm != null ) ncm . add ( new NcsMess ( dataStorage . filePos , totalSize , dataStorage ) ) ; storage . add ( dataStorage ) ; } else { // regular data\r int dsize = readVInt ( raf ) ; DataStorage dataStorage = new DataStorage ( dsize , raf . getFilePointer ( ) , dproto ) ; if ( ncm != null ) ncm . add ( new NcsMess ( dataStorage . filePos , dsize , dataStorage ) ) ; storage . add ( dataStorage ) ; raf . skipBytes ( dsize ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an NcML file from a String and construct a NcmlCollectionReader from its scan or scanFmrc element . [CODESPLIT] static public NcmlCollectionReader readNcML ( String ncmlString , Formatter errlog ) throws IOException { StringReader reader = new StringReader ( ncmlString ) ; org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; if ( debugURL ) System . out . println ( \" NetcdfDataset NcML String = <\" + ncmlString + \">\" ) ; doc = builder . build ( new StringReader ( ncmlString ) ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } if ( debugXML ) System . out . println ( \" SAXBuilder done\" ) ; return readXML ( doc , errlog , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an NcML file from a URL location and construct a NcmlCollectionReader from its scan or scanFmrc element . [CODESPLIT] static public NcmlCollectionReader open ( String ncmlLocation , Formatter errlog ) throws IOException { if ( ! ncmlLocation . startsWith ( \"http:\" ) && ! ncmlLocation . startsWith ( \"file:\" ) ) ncmlLocation = \"file:\" + ncmlLocation ; URL url = new URL ( ncmlLocation ) ; org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; if ( debugURL ) System . out . println ( \" NetcdfDataset URL = <\" + url + \">\" ) ; doc = builder . build ( url ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } if ( debugXML ) System . out . println ( \" SAXBuilder done\" ) ; return readXML ( doc , errlog , ncmlLocation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace any char not alphanumeric or in allowChars by replaceChar . [CODESPLIT] static public String allow ( String x , String allowChars , char replaceChar ) { boolean ok = true ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( ! ( Character . isLetterOrDigit ( c ) || ( 0 <= allowChars . indexOf ( c ) ) ) ) { ok = false ; break ; } } if ( ok ) return x ; // gotta do it\r StringBuilder sb = new StringBuilder ( x ) ; for ( int pos = 0 ; pos < sb . length ( ) ; pos ++ ) { char c = sb . charAt ( pos ) ; if ( Character . isLetterOrDigit ( c ) || ( 0 <= allowChars . indexOf ( c ) ) ) { continue ; } sb . setCharAt ( pos , replaceChar ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Break the given text into lines respecting word boundaries ( blank space ) . [CODESPLIT] public static String breakTextAtWords ( String text , String insert , int lineSize ) { StringBuilder buff = new StringBuilder ( ) ; StringTokenizer stoker = new StringTokenizer ( text ) ; int lineCount = 0 ; while ( stoker . hasMoreTokens ( ) ) { String tok = stoker . nextToken ( ) ; if ( tok . length ( ) + lineCount >= lineSize ) { buff . append ( insert ) ; lineCount = 0 ; } buff . append ( tok ) ; buff . append ( \" \" ) ; lineCount += tok . length ( ) + 1 ; } return buff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete any non - printable characters [CODESPLIT] public static String cleanup ( byte [ ] h ) { byte [ ] bb = new byte [ h . length ] ; int count = 0 ; for ( byte b : h ) { if ( b >= 32 && b < 127 ) bb [ count ++ ] = b ; } return new String ( bb , 0 , count , CDM . utf8Charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove any char not alphanumeric or in okChars . [CODESPLIT] static public String filter ( String x , String okChars ) { boolean ok = true ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( ! ( Character . isLetterOrDigit ( c ) || ( 0 <= okChars . indexOf ( c ) ) ) ) { ok = false ; break ; } } if ( ok ) { return x ; } // gotta do it\r StringBuilder sb = new StringBuilder ( x . length ( ) ) ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( Character . isLetterOrDigit ( c ) || ( 0 <= okChars . indexOf ( c ) ) ) { sb . append ( c ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all but printable ascii [CODESPLIT] static public String filter7bits ( String s ) { if ( s == null ) return null ; char [ ] bo = new char [ s . length ( ) ] ; int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( ( c < 128 ) && ( c > 31 ) || ( ( c == ' ' ) || ( c == ' ' ) ) ) { bo [ count ++ ] = c ; } } return new String ( bo , 0 , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "transform embedded space to _ [CODESPLIT] static public String makeValidCdmObjectName ( String name ) { name = name . trim ( ) ; // common case no change\r boolean ok = true ; for ( int i = 0 ; i < name . length ( ) ; i ++ ) { int c = name . charAt ( i ) ; if ( c < 0x20 ) ok = false ; if ( c == ' ' ) ok = false ; if ( c == ' ' ) ok = false ; if ( ! ok ) break ; } if ( ok ) return name ; StringBuilder sbuff = new StringBuilder ( name . length ( ) ) ; for ( int i = 0 , len = name . length ( ) ; i < len ; i ++ ) { int c = name . charAt ( i ) ; if ( ( c == ' ' ) || ( c == ' ' ) ) sbuff . append ( ' ' ) ; else if ( c >= 0x20 ) sbuff . append ( ( char ) c ) ; } return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count number of chars that match in two strings starting from front . [CODESPLIT] static public int match ( String s1 , String s2 ) { int i = 0 ; while ( ( i < s1 . length ( ) ) && ( i < s2 . length ( ) ) ) { if ( s1 . charAt ( i ) != s2 . charAt ( i ) ) { break ; } i ++ ; } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pad the given string with padString on the left up to the given length . [CODESPLIT] public static String padLeft ( String s , int desiredLength , String padString ) { while ( s . length ( ) < desiredLength ) { s = padString + s ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pad the given string with padString on the right up to the given length . [CODESPLIT] public static String padRight ( String s , int desiredLength , String padString ) { StringBuilder ret = new StringBuilder ( s ) ; while ( ret . length ( ) < desiredLength ) { ret . append ( padString ) ; } return ret . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all occurrences of the substring sub in the string s . [CODESPLIT] static public String remove ( String s , String sub ) { int len = sub . length ( ) ; int pos ; while ( 0 <= ( pos = s . indexOf ( sub ) ) ) { s = s . substring ( 0 , pos ) + s . substring ( pos + len ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all occurrences of the character c in the string s . [CODESPLIT] static public String remove ( String s , int c ) { if ( 0 > s . indexOf ( c ) ) { // none\r return s ; } StringBuilder buff = new StringBuilder ( s ) ; int i = 0 ; while ( i < buff . length ( ) ) { if ( buff . charAt ( i ) == c ) { buff . deleteCharAt ( i ) ; } else { i ++ ; } } return buff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all occurrences of the character c at the end of s . [CODESPLIT] static public String removeFromEnd ( String s , int c ) { if ( 0 > s . indexOf ( c ) ) // none\r return s ; int len = s . length ( ) ; while ( ( s . charAt ( len - 1 ) == c ) && ( len > 0 ) ) len -- ; if ( len == s . length ( ) ) return s ; return s . substring ( 0 , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove any whitespace ( ie . Character . isWhitespace ) from the input string . [CODESPLIT] public static String removeWhitespace ( String inputString ) { StringBuilder sb = new StringBuilder ( ) ; char [ ] chars = inputString . toCharArray ( ) ; for ( char c : chars ) { if ( Character . isWhitespace ( c ) ) { continue ; } sb . append ( c ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collapse continuous whitespace into one single . [CODESPLIT] static public String collapseWhitespace ( String s ) { int len = s . length ( ) ; StringBuilder b = new StringBuilder ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = s . charAt ( i ) ; if ( ! Character . isWhitespace ( c ) ) { b . append ( c ) ; } else { b . append ( ' ' ) ; while ( ( i + 1 < len ) && Character . isWhitespace ( s . charAt ( i + 1 ) ) ) { i ++ ; /// skip further whitespace\r } } } return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace any char out in s with in . [CODESPLIT] static public String replace ( String s , char out , String in ) { if ( s . indexOf ( out ) < 0 ) { return s ; } // gotta do it\r StringBuilder sb = new StringBuilder ( s ) ; replace ( sb , out , in ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all occurrences of any char in replaceChar with corresponding String in replaceWith [CODESPLIT] static public String replace ( String x , char [ ] replaceChar , String [ ] replaceWith ) { // common case no replacement\r boolean ok = true ; for ( char aReplaceChar : replaceChar ) { int pos = x . indexOf ( aReplaceChar ) ; ok = ( pos < 0 ) ; if ( ! ok ) break ; } if ( ok ) return x ; // gotta do it\r StringBuilder sb = new StringBuilder ( x ) ; for ( int i = 0 ; i < replaceChar . length ; i ++ ) { int pos = x . indexOf ( replaceChar [ i ] ) ; if ( pos >= 0 ) { replace ( sb , replaceChar [ i ] , replaceWith [ i ] ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces all occurrences of pattern in string with value [CODESPLIT] public static String replace ( String string , String pattern , String value ) { if ( pattern . length ( ) == 0 ) return string ; if ( ! string . contains ( pattern ) ) return string ; // ok gotta do it\r StringBuilder returnValue = new StringBuilder ( ) ; int patternLength = pattern . length ( ) ; while ( true ) { int idx = string . indexOf ( pattern ) ; if ( idx < 0 ) break ; returnValue . append ( string . substring ( 0 , idx ) ) ; if ( value != null ) returnValue . append ( value ) ; string = string . substring ( idx + patternLength ) ; } returnValue . append ( string ) ; return returnValue . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all occurrences of orgReplace with orgChar ; inverse of replace () . [CODESPLIT] static public String unreplace ( String x , String [ ] orgReplace , char [ ] orgChar ) { // common case no replacement\r boolean ok = true ; for ( String anOrgReplace : orgReplace ) { int pos = x . indexOf ( anOrgReplace ) ; ok = ( pos < 0 ) ; if ( ! ok ) break ; } if ( ok ) return x ; // gotta do it\r StringBuilder result = new StringBuilder ( x ) ; for ( int i = 0 ; i < orgReplace . length ; i ++ ) { int pos = result . indexOf ( orgReplace [ i ] ) ; if ( pos >= 0 ) { unreplace ( result , orgReplace [ i ] , orgChar [ i ] ) ; } } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all occurrences of the match in original and substitute the subst string . [CODESPLIT] static public String substitute ( String original , String match , String subst ) { String s = original ; int pos ; while ( 0 <= ( pos = s . indexOf ( match ) ) ) { StringBuilder sb = new StringBuilder ( s ) ; s = sb . replace ( pos , pos + match . length ( ) , subst ) . toString ( ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape any char not alphanumeric or in okChars . Escape by replacing char with %xx ( hex ) . [CODESPLIT] static public String escape ( String x , String okChars ) { StringBuilder newname = new StringBuilder ( ) ; for ( char c : x . toCharArray ( ) ) { if ( c == ' ' ) { newname . append ( \"%%\" ) ; } else if ( ! Character . isLetterOrDigit ( c ) && okChars . indexOf ( c ) < 0 ) { newname . append ( ' ' ) ; newname . append ( Integer . toHexString ( ( 0xFF & ( int ) c ) ) ) ; } else newname . append ( c ) ; } return newname . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This finds any %xx and converts to the equivalent char . Inverse of escape () . [CODESPLIT] static public String unescape ( String x ) { if ( x . indexOf ( ' ' ) < 0 ) { return x ; } // gotta do it\r char [ ] b = new char [ 2 ] ; StringBuilder sb = new StringBuilder ( x ) ; for ( int pos = 0 ; pos < sb . length ( ) ; pos ++ ) { char c = sb . charAt ( pos ) ; if ( c != ' ' ) { continue ; } if ( pos >= sb . length ( ) - 2 ) { // malformed - should be %xx\r return x ; } b [ 0 ] = sb . charAt ( pos + 1 ) ; b [ 1 ] = sb . charAt ( pos + 2 ) ; int value ; try { value = Integer . parseInt ( new String ( b ) , 16 ) ; } catch ( NumberFormatException e ) { continue ; // not a hex number\r } c = ( char ) value ; sb . setCharAt ( pos , c ) ; sb . delete ( pos + 1 , pos + 3 ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all occurences of match strings in original and substitute the corresponding subst string . [CODESPLIT] static public String substitute ( String original , String [ ] match , String [ ] subst ) { boolean ok = true ; for ( String aMatch : match ) { if ( original . contains ( aMatch ) ) { ok = false ; break ; } } if ( ok ) { return original ; } // gotta do it;\r StringBuilder sb = new StringBuilder ( original ) ; for ( int i = 0 ; i < match . length ; i ++ ) { substitute ( sb , match [ i ] , subst [ i ] ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove any of the characters in out from sb [CODESPLIT] static public void remove ( StringBuilder sb , String out ) { int i = 0 ; while ( i < sb . length ( ) ) { int c = sb . charAt ( i ) ; boolean ok = true ; for ( int j = 0 ; j < out . length ( ) ; j ++ ) { if ( out . charAt ( j ) == c ) { sb . delete ( i , i + 1 ) ; ok = false ; break ; } } if ( ok ) i ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace any String out in sb with char in . [CODESPLIT] static public void unreplace ( StringBuilder sb , String out , char in ) { int pos ; while ( 0 <= ( pos = sb . indexOf ( out ) ) ) { sb . setCharAt ( pos , in ) ; sb . delete ( pos + 1 , pos + out . length ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace any of the characters from out with corresponding character from in [CODESPLIT] static public void replace ( StringBuilder sb , String out , String in ) { for ( int i = 0 ; i < sb . length ( ) ; i ++ ) { int c = sb . charAt ( i ) ; for ( int j = 0 ; j < out . length ( ) ; j ++ ) { if ( out . charAt ( j ) == c ) sb . setCharAt ( i , in . charAt ( j ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all occurences of the match in original and substitute the subst string directly into the original . [CODESPLIT] static public void substitute ( StringBuilder sbuff , String match , String subst ) { int pos , fromIndex = 0 ; int substLen = subst . length ( ) ; int matchLen = match . length ( ) ; while ( 0 <= ( pos = sbuff . indexOf ( match , fromIndex ) ) ) { sbuff . replace ( pos , pos + matchLen , subst ) ; fromIndex = pos + substLen ; // make sure dont get into an infinite loop\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove bad char from beginning or end of string [CODESPLIT] static public String trim ( String s , int bad ) { int len = s . length ( ) ; int st = 0 ; while ( ( st < len ) && ( s . charAt ( st ) == bad ) ) { st ++ ; } while ( ( st < len ) && ( s . charAt ( len - 1 ) == bad ) ) { len -- ; } return ( ( st > 0 ) || ( len < s . length ( ) ) ) ? s . substring ( st , len ) : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "old school : used by FMRC and Point [CODESPLIT] protected void makeCollection ( ) { Formatter errlog = new Formatter ( ) ; datasetCollection = new MFileCollectionManager ( config , errlog , logger ) ; topDirectory = datasetCollection . getRoot ( ) ; String errs = errlog . toString ( ) ; if ( errs . length ( ) > 0 ) logger . warn ( \"MFileCollectionManager parse error = {} \" , errs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "called by eventBus this is where the trigger comes in [CODESPLIT] @ Subscribe public void processEvent ( CollectionUpdateEvent event ) { if ( ! config . collectionName . equals ( event . getCollectionName ( ) ) ) return ; // not for me try { update ( event . getType ( ) ) ; } catch ( IOException e ) { logger . error ( \"Error processing event\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////// [CODESPLIT] public void showStatus ( Formatter f ) { try { checkState ( ) ; _showStatus ( f , false , null ) ; } catch ( Throwable t ) { StringWriter sw = new StringWriter ( 5000 ) ; t . printStackTrace ( new PrintWriter ( sw ) ) ; f . format ( sw . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A request has come in check that the state has been initialized . this is called from the request thread . [CODESPLIT] protected State checkState ( ) throws IOException { State localState ; synchronized ( lock ) { if ( first ) { firstInit ( ) ; updateCollection ( state , config . updateConfig . updateType ) ; // makeDatasetTop(state); first = false ; } localState = state . copy ( ) ; } return localState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collection was changed update internal objects . called by CollectionUpdater trigger via handleCollectionEvent so in a quartz scheduler thread [CODESPLIT] protected void update ( CollectionUpdateType force ) throws IOException { // this may be called from a background thread, or from checkState() request thread State localState ; synchronized ( lock ) { if ( first ) { state = checkState ( ) ; state . lastInvChange = System . currentTimeMillis ( ) ; return ; } // do the update in a local object localState = state . copy ( ) ; } updateCollection ( localState , force ) ; // makeDatasetTop(localState); localState . lastInvChange = System . currentTimeMillis ( ) ; // switch to live synchronized ( lock ) { state = localState ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected String makeFullName ( DatasetNode ds ) { if ( ds . getParent ( ) == null ) return ds . getName ( ) ; String parentName = makeFullName ( ds . getParent ( ) ) ; if ( parentName == null || parentName . length ( ) == 0 ) return ds . getName ( ) ; return parentName + \"/\" + ds . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the containing catalog of this feature collection http : // server : port / thredds / catalog / path / catalog . xml [CODESPLIT] protected CatalogBuilder makeCatalogTop ( URI catURI , State localState ) throws IOException , URISyntaxException { Catalog parentCatalog = parent . getParentCatalog ( ) ; CatalogBuilder topCatalog = new CatalogBuilder ( ) ; topCatalog . setName ( makeFullName ( parent ) ) ; topCatalog . setVersion ( parentCatalog . getVersion ( ) ) ; topCatalog . setBaseURI ( catURI ) ; DatasetBuilder top = makeDatasetTop ( catURI , localState ) ; topCatalog . addDataset ( top ) ; // topCatalog.addService(StandardServices.latest.getService());  // in case its needed topCatalog . addService ( virtualService ) ; return topCatalog ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this catalog lists the individual files comprising the collection . [CODESPLIT] protected CatalogBuilder makeCatalogFiles ( URI catURI , State localState , List < String > filenames , boolean addLatest ) throws IOException { Catalog parentCatalog = parent . getParentCatalog ( ) ; CatalogBuilder result = new CatalogBuilder ( ) ; result . setName ( makeFullName ( parent ) ) ; result . setVersion ( parentCatalog . getVersion ( ) ) ; result . setBaseURI ( catURI ) ; result . addService ( orgService ) ; DatasetBuilder top = new DatasetBuilder ( null ) ; top . transferInheritedMetadata ( parent ) ; // make all inherited metadata local top . setName ( FILES ) ; // add Variables, GeospatialCoverage, TimeCoverage ThreddsMetadata tmi = top . getInheritableMetadata ( ) ; tmi . set ( Dataset . TimeCoverage , null ) ; // LOOK if ( localState . coverage != null ) { tmi . set ( Dataset . GeospatialCoverage , localState . coverage ) ; } tmi . set ( Dataset . ServiceName , orgService . getName ( ) ) ; result . addDataset ( top ) ; if ( addLatest ) { DatasetBuilder latest = new DatasetBuilder ( top ) ; latest . setName ( getLatestFileName ( ) ) ; latest . put ( Dataset . UrlPath , LATEST_DATASET_CATALOG ) ; latest . put ( Dataset . Id , LATEST_DATASET_CATALOG ) ; latest . put ( Dataset . ServiceName , latestService . getName ( ) ) ; latest . addServiceToCatalog ( latestService ) ; top . addDataset ( latest ) ; } // sort copy of files List < String > sortedFilenames = new ArrayList <> ( filenames ) ; Collections . sort ( sortedFilenames , String . CASE_INSENSITIVE_ORDER ) ; // if not increasing (i.e. we WANT newest file listed first), reverse sort if ( ! this . config . getSortFilesAscending ( ) ) { Collections . reverse ( sortedFilenames ) ; } for ( String f : sortedFilenames ) { if ( ! f . startsWith ( topDirectory ) ) logger . warn ( \"File {} doesnt start with topDir {}\" , f , topDirectory ) ; DatasetBuilder ds = new DatasetBuilder ( top ) ; String fname = f . substring ( topDirectory . length ( ) + 1 ) ; ds . setName ( fname ) ; String lpath = this . configPath + \"/\" + FILES + \"/\" + fname ; // String lpath = getPath() + \"/\" + FILES + \"/\" + fname; ds . put ( Dataset . UrlPath , lpath ) ; ds . put ( Dataset . Id , lpath ) ; ds . put ( Dataset . VariableMapLinkURI , new ThreddsMetadata . UriResolved ( makeMetadataLink ( lpath , VARIABLES ) , catURI ) ) ; File file = new File ( f ) ; ds . put ( Dataset . DataSize , file . length ( ) ) ; top . addDataset ( ds ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the associated Grid Dataset if any . called by DatasetHandler . openGridDataset () [CODESPLIT] public ucar . nc2 . dt . grid . GridDataset getGridDataset ( String matchPath ) throws IOException { return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the dataset named by the path . called by DatasetHandler . getNetcdfFile () [CODESPLIT] public NetcdfDataset getNetcdfDataset ( String matchPath ) throws IOException { int pos = matchPath . indexOf ( ' ' ) ; String type = ( pos > - 1 ) ? matchPath . substring ( 0 , pos ) : matchPath ; String name = ( pos > - 1 ) ? matchPath . substring ( pos + 1 ) : \"\" ; // this assumes that these are files. also might be remote datasets from a catalog if ( type . equalsIgnoreCase ( FILES ) ) { if ( topDirectory == null ) return null ; String filename = new StringBuilder ( topDirectory ) . append ( topDirectory . endsWith ( \"/\" ) ? \"\" : \"/\" ) . append ( name ) . toString ( ) ; DatasetUrl durl = new DatasetUrl ( null , filename ) ; return NetcdfDataset . acquireDataset ( null , durl , null , - 1 , null , null ) ; // no enhancement } GridDataset gds = getGridDataset ( matchPath ) ; // LOOK cant be right return ( gds == null ) ? null : ( NetcdfDataset ) gds . getNetcdfFile ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this says that a File URL has to be topDirectory + [ FILES / + ] + match . remaining [CODESPLIT] public File getFile ( String remaining ) { if ( null == topDirectory ) return null ; int pos = remaining . indexOf ( FILES ) ; StringBuilder fname = new StringBuilder ( topDirectory ) ; if ( ! topDirectory . endsWith ( \"/\" ) ) fname . append ( \"/\" ) ; fname . append ( ( pos > - 1 ) ? remaining . substring ( pos + FILES . length ( ) + 1 ) : remaining ) ; return new File ( fname . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * http : // www . unidata . ucar . edu / software / netcdf / docs / BestPractices . html Packed Data Values [CODESPLIT] private void doCopyCompress ( Formatter f , ucar . nc2 . grib . grib2 . Grib2Record gr , RandomAccessFile raf , OutputStream out , Counters counters ) throws IOException { float [ ] data = gr . readData ( raf ) ; Grib2SectionDataRepresentation drss = gr . getDataRepresentationSection ( ) ; drss . getDrs ( raf ) ; // calc scale/offset GribData . Info info = gr . getBinaryDataInfo ( raf ) ; int nbits = info . numberOfBits ; counters . count ( \"Nbits\" , nbits ) ; int width = ( 2 << ( nbits - 1 ) ) - 1 ; //f.format(\" nbits = %d%n\", nbits); //f.format(\" width = %d (0x%s) %n\", width2, Long.toHexString(width2)); float dataMin = Float . MAX_VALUE ; float dataMax = - Float . MAX_VALUE ; for ( float fd : data ) { dataMin = Math . min ( dataMin , fd ) ; dataMax = Math . max ( dataMax , fd ) ; } //f.format(\" dataMin = %f%n\", dataMin); //f.format(\" dataMax = %f%n\", dataMax); // f.format(\" range = %f%n\", (dataMax - dataMin)); // scale_factor =(dataMax - dataMin) / (2^n - 1) // add_offset = dataMin + 2^(n-1) * scale_factor //float scale_factor = (dataMax - dataMin) / width2; //float add_offset = dataMin + width2 * scale_factor / 2; float scale_factor = ( dataMax - dataMin ) / ( width - 2 ) ; float add_offset = dataMin - scale_factor ; //f.format(\" scale_factor = %f%n\", scale_factor); //f.format(\" add_offset = %f%n\", add_offset); // unpacked_data_value = packed_data_value * scale_factor + add_offset // packed_data_value = nint((unpacked_data_value - add_offset) / scale_factor) /* compressedSize = out.size();\n      f.format(\" compressedSize = %d%n\", compressedSize);\n      f.format(\" compressedRatio = %f%n\", (float) compressedSize / (n*nbits/8));\n      f.format(\" ratio with grib = %f%n\", (float) compressedSize / bean1.getDataLength());  */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doCheckTables ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"Check Grib-2 Parameter Tables%n\" ) ; int [ ] accum = new int [ 4 ] ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \"%n %s%n\" , mfile . getPath ( ) ) ; doCheckTables ( mfile , f , accum ) ; } f . format ( \"%nGrand total=%d not operational = %d local = %d missing = %d%n\" , accum [ 0 ] , accum [ 1 ] , accum [ 2 ] , accum [ 3 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doLocalUseSection ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"Show Local Use Section%n\" ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \" %s%n\" , mfile . getPath ( ) ) ; doLocalUseSection ( mfile , f , useIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look through the collection and find what GDS and PDS templates are used . [CODESPLIT] private void doUniqueTemplates ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"Show Unique GDS and PDS templates%n\" ) ; Map < Integer , FileList > gdsSet = new HashMap <> ( ) ; Map < Integer , FileList > pdsSet = new HashMap <> ( ) ; Map < Integer , FileList > drsSet = new HashMap <> ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \" %s%n\" , mfile . getPath ( ) ) ; doUniqueTemplates ( mfile , gdsSet , pdsSet , drsSet , f ) ; } List < FileList > sorted = new ArrayList <> ( gdsSet . values ( ) ) ; Collections . sort ( sorted ) ; for ( FileList gdsl : sorted ) { f . format ( \"%nGDS %s template= %d %n\" , gdsl . name , gdsl . template ) ; for ( FileCount fc : gdsl . fileList ) { f . format ( \"  %5d %s %n\" , fc . countRecords , fc . f . getPath ( ) ) ; } } List < FileList > sortedPds = new ArrayList <> ( pdsSet . values ( ) ) ; Collections . sort ( sortedPds ) ; for ( FileList pdsl : sortedPds ) { f . format ( \"%n===================================================%n\" ) ; f . format ( \"%nPDS %s template= %d %n\" , pdsl . name , pdsl . template ) ; for ( FileCount fc : pdsl . fileList ) { f . format ( \"  %5d %s %n\" , fc . countRecords , fc . f . getPath ( ) ) ; } } List < FileList > sortedDrs = new ArrayList <> ( drsSet . values ( ) ) ; Collections . sort ( sortedDrs ) ; for ( FileList pdsl : sortedDrs ) { f . format ( \"%n===================================================%n\" ) ; f . format ( \"%nDRS %s template= %d %n\" , pdsl . name , pdsl . template ) ; for ( FileCount fc : pdsl . fileList ) { f . format ( \"  %5d %s %n\" , fc . countRecords , fc . f . getPath ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////// [CODESPLIT] private void doPdsSummary ( Formatter f , MCollection dcm , boolean eachFile ) throws IOException { Counters countersAll = new Counters ( ) ; countersAll . add ( \"template\" ) ; countersAll . add ( \"timeUnit\" ) ; countersAll . add ( \"timeOffset\" ) ; countersAll . add ( \"timeIntervalSize\" ) ; countersAll . add ( \"levelType\" ) ; countersAll . add ( \"genProcessType\" ) ; countersAll . add ( \"genProcessId\" ) ; countersAll . add ( \"levelScale\" ) ; countersAll . add ( \"nExtraCoords\" ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \"---%s%n\" , mfile . getPath ( ) ) ; doPdsSummary ( f , mfile , countersAll ) ; if ( eachFile ) { countersAll . show ( f ) ; countersAll . reset ( ) ; } } f . format ( \"PdsSummary - all files%n\" ) ; if ( ! eachFile ) countersAll . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doIdProblems ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"Look for ID Problems%n\" ) ; Counters countersAll = new Counters ( ) ; countersAll . add ( \"discipline\" ) ; countersAll . add ( \"masterTable\" ) ; countersAll . add ( \"localTable\" ) ; countersAll . add ( \"centerId\" ) ; countersAll . add ( \"subcenterId\" ) ; countersAll . add ( \"genProcess\" ) ; countersAll . add ( \"backProcess\" ) ; countersAll . add ( \"significanceOfReference\" ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \" %s%n\" , mfile . getPath ( ) ) ; doIdProblems ( f , mfile , useIndex , countersAll ) ; } countersAll . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doDrsSummary ( Formatter f , MCollection dcm , boolean useIndex , boolean eachFile , boolean extra ) throws IOException { f . format ( \"Show Unique DRS Templates%n\" ) ; Counters countersAll = new Counters ( ) ; countersAll . add ( \"DRS_template\" ) ; countersAll . add ( \"BMS indicator\" ) ; countersAll . add ( \"DRS template 40 signed problem\" ) ; countersAll . add ( \"Number_of_Bits\" ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \"------- %s%n\" , mfile . getPath ( ) ) ; if ( useIndex ) doDrsSummaryIndex ( f , mfile , extra , countersAll ) ; else doDrsSummaryScan ( f , mfile , extra , countersAll ) ; if ( eachFile ) { countersAll . show ( f ) ; f . format ( \"%n\" ) ; countersAll . reset ( ) ; } } if ( ! eachFile ) countersAll . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////// [CODESPLIT] private void doGdsSummary ( Formatter f , MCollection dcm , boolean extra ) throws IOException { f . format ( \"Show Unique GDS Templates%n\" ) ; Counters counters = new Counters ( ) ; counters . add ( \"template\" ) ; counters . add ( \"scanMode\" ) ; counters . add ( \"scanModeDifference\" ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \" %s%n\" , mfile . getPath ( ) ) ; doGdsSummary ( f , mfile , counters , extra ) ; } counters . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////// [CODESPLIT] private void doTimeCoord ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { Counters counters = new Counters ( ) ; counters . add ( \"template\" ) ; counters . add ( \"timeUnit\" ) ; counters . add ( \"statType\" ) ; counters . add ( \"NumberTimeIntervals\" ) ; counters . add ( \"TimeIntervalsDiffer\" ) ; counters . add ( \"TimeIntervalsLength\" ) ; int count = 0 ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \" %s%n\" , mfile . getPath ( ) ) ; count += doTimeCoord ( f , mfile , counters ) ; } f . format ( \"total records = %d%n\" , count ) ; counters . show ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void doRename ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( \"CHECK Grib-2 Names: Old vs New for collection %s%n\" , dcm . getCollectionName ( ) ) ; List < VarName > varNames = new ArrayList <> ( 3000 ) ; Map < String , List < String > > gridsAll = new HashMap <> ( 1000 ) ; // old -> list<new> int countExactMatch = 0 ; int countExactMatchIg = 0 ; int countOldVars = 0 ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( \"%n%s%n\" , mfile . getPath ( ) ) ; Map < Integer , GridMatch > gridsNew = getGridsNew ( mfile , f ) ; Map < Integer , GridMatch > gridsOld = getGridsOld ( mfile , f ) ; // look for exact match on name Set < String > namesNew = new HashSet <> ( gridsNew . size ( ) ) ; for ( GridMatch gm : gridsNew . values ( ) ) namesNew . ( gm . grid . getFullName ( ) ) ; for ( GridMatch gm : gridsOld . values ( ) ) { if ( namesNew . contains ( gm . grid . getFullName ( ) ) ) countExactMatch ++ ; countOldVars ++ ; } // look for exact match on hashcode for ( GridMatch gm : gridsNew . values ( ) ) { GridMatch match = gridsOld . get ( gm . hashCode ( ) ) ; if ( match != null ) { gm . match = match ; match . match = gm ; } } // look for alternative match for ( GridMatch gm : gridsNew . values ( ) ) { if ( gm . match == null ) { GridMatch match = altMatch ( gm , gridsOld . values ( ) ) ; if ( match != null ) { gm . match = match ; match . match = gm ; } } } // print out match f . format ( \"%n\" ) ; List < GridMatch > listNew = new ArrayList <> ( gridsNew . values ( ) ) ; Collections . sort ( listNew ) ; for ( GridMatch gm : listNew ) { f . format ( \" %s%n\" , gm . grid . findAttributeIgnoreCase ( Grib . VARIABLE_ID_ATTNAME ) ) ; f . format ( \" %s (%d)%n\" , gm . grid . getFullName ( ) , gm . hashCode ( ) ) ; if ( gm . match != null ) { boolean exact = gm . match . grid . getFullName ( ) . equals ( gm . grid . getFullName ( ) ) ; boolean exactIg = ! exact && gm . match . grid . getFullName ( ) . equalsIgnoreCase ( gm . grid . getFullName ( ) ) ; if ( exactIg ) countExactMatchIg ++ ; String status = exact ? \" \" : exactIg ? \"**\" : \" *\" ; f . format ( \"%s%s (%d)%n\" , status , gm . match . grid . getFullName ( ) , gm . match . hashCode ( ) ) ; } f . format ( \"%n\" ) ; } // print out missing f . format ( \"%nMISSING MATCHES IN NEW%n\" ) ; List < GridMatch > list = new ArrayList <> ( gridsNew . values ( ) ) ; Collections . sort ( list ) ; for ( GridMatch gm : list ) { if ( gm . match == null ) f . format ( \" %s (%s) == %s%n\" , gm . grid . getFullName ( ) , gm . show ( ) , gm . grid . getDescription ( ) ) ; } f . format ( \"%nMISSING MATCHES IN OLD%n\" ) ; List < GridMatch > listOld = new ArrayList <> ( gridsOld . values ( ) ) ; Collections . sort ( listOld ) ; for ( GridMatch gm : listOld ) { if ( gm . match == null ) f . format ( \" %s (%s)%n\" , gm . grid . getFullName ( ) , gm . show ( ) ) ; } // add to gridsAll to track old -> new mapping for ( GridMatch gmOld : listOld ) { String key = gmOld . grid . getShortName ( ) ; List < String > newGrids = gridsAll . get ( key ) ; if ( newGrids == null ) { newGrids = new ArrayList <> ( ) ; gridsAll . put ( key , newGrids ) ; } if ( gmOld . match != null ) { String keyNew = gmOld . match . grid . getShortName ( ) ; if ( ! newGrids . contains ( keyNew ) ) newGrids . add ( keyNew ) ; } } // add matches to VarNames for ( GridMatch gmOld : listOld ) { if ( gmOld . match == null ) { f . format ( \"MISSING %s (%s)%n\" , gmOld . grid . getFullName ( ) , gmOld . show ( ) ) ; continue ; } Attribute att = gmOld . match . grid . findAttributeIgnoreCase ( Grib . VARIABLE_ID_ATTNAME ) ; String varId = att == null ? \"\" : att . getStringValue ( ) ; varNames . add ( new VarName ( mfile . getName ( ) , gmOld . grid . getShortName ( ) , gmOld . match . grid . getShortName ( ) , varId ) ) ; } } // show old -> new mapping f . format ( \"%nOLD -> NEW MAPPINGS%n\" ) ; List < String > keys = new ArrayList <> ( gridsAll . keySet ( ) ) ; int total = keys . size ( ) ; int dups = 0 ; Collections . sort ( keys ) ; for ( String key : keys ) { f . format ( \" OLD %s%n\" , key ) ; List < String > newGrids = gridsAll . get ( key ) ; Collections . sort ( newGrids ) ; if ( newGrids . size ( ) > 1 ) dups ++ ; for ( String newKey : newGrids ) f . format ( \" NEW %s%n\" , newKey ) ; . format ( \"%n\" ) ; } . format ( \"Exact matches=%d  Exact ignore case=%d  totalOldVars=%d%n\" , countExactMatch , countExactMatchIg , countOldVars ) ; . format ( \"Number with more than one map=%d total=%d%n\" , dups , total ) ; // old -> new mapping xml table if ( ! useIndex ) { Element rootElem = new Element ( \"gribVarMap\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"collection\" , dcm . getCollectionName ( ) ) ; String currentDs = null ; Element dsElem = null ; for ( VarName vn : varNames ) { if ( ! vn . dataset . equals ( currentDs ) ) { dsElem = new Element ( \"dataset\" ) ; rootElem . addContent ( dsElem ) ; dsElem . setAttribute ( \"name\" , vn . dataset ) ; currentDs = vn . dataset ; } Element param = new Element ( \"param\" ) ; dsElem . addContent ( param ) ; param . setAttribute ( \"oldName\" , vn . oldVar ) ; param . setAttribute ( \"newName\" , vn . newVar ) ; param . setAttribute ( \"varId\" , vn . varId ) ; } FileOutputStream fout = new FileOutputStream ( \"C:/tmp/grib2VarMap.xml\" ) ; XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; fmt . output ( doc , fout ) ; fout . close ( ) ; } /*  old -> new mapping xml table\n   if (!useIndex) {\n     Element rootElem = new Element(\"gribVarMap\");\n     Document doc = new Document(rootElem);\n     rootElem.setAttribute(\"collection\", dcm.getCollectionName());\n\n     for (String key : keys) {\n       Element param = new Element(\"param\");\n       rootElem.addContent(param);\n       param.setAttribute(\"oldName\", key);\n       List<String> newGrids = gridsAll.get(key);\n       Collections.sort(newGrids);\n       for (String newKey : newGrids)\n         param.addContent(new Element(\"newName\").addContent(newKey));\n     }\n\n     FileOutputStream fout = new FileOutputStream(\"C:/tmp/gribVarMap.xml\");\n     XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());\n     fmt.output(doc, fout);\n     fout.close();\n   } */ } private GridMatch altMatch  ( GridMatch want , Collection < GridMatch > test ) { // look for scale factor errors in prob for ( GridMatch gm : test ) { if ( gm . match != null ) continue ; // already matched if ( gm . altMatch ( want ) ) { //gm.altMatch(want); //debug return gm ; } } // give up matching the prob for ( GridMatch gm : test ) { if ( gm . match != null ) continue ; // already matched if ( gm . altMatchNoProb ( want ) ) { //gm.altMatchNoProb(want); // debug return gm ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a list of all the nested datasets . [CODESPLIT] @ Override public java . util . List < InvDataset > getDatasets ( ) { read ( ) ; return useProxy ? proxy . getDatasets ( ) : super . getDatasets ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Release resources - undo the read of the catalog . This is needed when crawling large catalogs . For modest catalogs that you will repeatedly examine do not use this method . [CODESPLIT] public void release ( ) { datasets = new java . util . ArrayList <> ( ) ; proxy = null ; useProxy = false ; init = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the referenced catalog asynchronously if the catalog factory supports it . If it doesnt this method will work equivilently to read () which is called the first time getDatasets () is called . If the catalog is already read in the callback will be called immediately before this method exits . [CODESPLIT] public synchronized void readAsynch ( InvCatalogFactory factory , CatalogSetCallback caller ) { if ( init ) { caller . setCatalog ( ( InvCatalogImpl ) getParentCatalog ( ) ) ; return ; } // may be reletive String hrefResolved ; try { java . net . URI uri = getParentCatalog ( ) . resolveUri ( href ) ; hrefResolved = uri . toString ( ) ; } catch ( java . net . URISyntaxException e ) { // this is to display an error message proxy = new InvDatasetImpl ( null , \"HREF ERROR\" ) ; if ( debug ) System . out . println ( \"HREF ERROR =\\n  \" + href + \" err= \" + e . getMessage ( ) ) ; proxy . addProperty ( new InvProperty ( \"HREF ERROR\" , href ) ) ; datasets . add ( proxy ) ; return ; } // open and read the referenced catalog XML asynchronously // setCatalog will be called when ready try { if ( debug ) System . out . println ( \" InvCatalogRef readXMLasynch \" + getFullName ( ) + \"  hrefResolved = \" + hrefResolved ) ; factory . readXMLasynch ( hrefResolved , new Callback ( caller ) ) ; } catch ( Exception e ) { // this is to display an error message proxy = new InvDatasetImpl ( null , \"HREF ERROR\" ) ; if ( debug ) System . out . println ( \"HREF ERROR =\\n  \" + href + \" err= \" + e . getMessage ( ) ) ; proxy . addProperty ( new InvProperty ( \"HREF ERROR\" , href ) ) ; datasets . add ( proxy ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// proxy [CODESPLIT] @ Override public thredds . catalog . InvDatasetImpl findDatasetByName ( java . lang . String p0 ) { return ! useProxy ? super . findDatasetByName ( p0 ) : proxy . findDatasetByName ( p0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * LOOK public thredds . catalog . InvCatalog getParentCatalog () { return !useProxy ? super . getParentCatalog () : proxy . getParentCatalog () ; } [CODESPLIT] @ Override public java . util . List < ThreddsMetadata . Vocab > getProjects ( ) { return ! useProxy ? super . getProjects ( ) : proxy . getProjects ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public void setLevels ( ucar . nc2 . dataset . grid . GridCoordSys gcs int current ) { this . zAxis = gcs . getVerticalAxis () ; if ( zAxis == null ) { slider . setEnabled ( false ) ; return ; } set up the slider and conversion slider . setEnabled ( true ) ; slider . setInverted ( !gcs . isZPositive () ) ; slider . setToolTipText ( zAxis . getUnitString () ) ; setSelectedIndex ( current ) ; [CODESPLIT] private int calcFracDigits ( String d ) { int pos = d . indexOf ( \".\" ) ; if ( pos < 0 ) return 0 ; return d . length ( ) - pos - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for OPeNDAP info requests . Returns an html document describing the contents of the servers datasets . <p / > The INFOcache &lt ; init - param&gt ; element in the web . xml file specifies the designated location for : <ul > <li > . info response override files . < / li > <li > Server specific HTML * files . < / li > <li > Dataset specific HTML * files . < / li > < / ul > <p / > The server specific HTML * files must be named #servlet# . html where #servlet# is the name of the servlet that is running as the OPeNDAP server in question . This name is determined at run time by using the class called Class ( this . getClass () . getName () ) . <p / > <p > In the C ++ code the analogy is the per - cgi file names . < / p > <p / > <p / > The dataset specific HTML * files are located by catenating . html to #name# where #name# is the name of the dataset . If the filename part of #name# is of the form [ A - Za - z ] + [ 0 - 9 ] * . * then this function also looks for a file whose name is [ A - Za - z ] . html For example if #name# is ... / data / fnoc1 . nc this function first looks for ... / data / fnoc1 . nc . html . However if that does not exist it will look for ... / data / fnoc . html . This allows one per - dataset file to be used for a collection of files with the same root name . < / p > <p / > NB : An HTML * file contains HTML without the <html > <head > or <body > tags ( my own notation ) . <p / > <h3 > Look for the user supplied Server - and dataset - specific HTML * documents . < / h3 > [CODESPLIT] public void sendINFO ( PrintWriter pw , GuardedDataset gds , ReqState rs ) throws DAP2Exception , ParseException { if ( _Debug ) System . out . println ( \"opendap.servlet.GetInfoHandler.sendINFO() reached.\" ) ; String responseDoc = null ; ServerDDS myDDS = null ; DAS myDAS = null ; myDDS = gds . getDDS ( ) ; myDAS = gds . getDAS ( ) ; infoDir = rs . getINFOCache ( rs . getRootPath ( ) ) ; responseDoc = loadOverrideDoc ( infoDir , rs . getDataSet ( ) ) ; if ( responseDoc != null ) { if ( _Debug ) System . out . println ( \"override document: \" + responseDoc ) ; pw . print ( responseDoc ) ; } else { String user_html = get_user_supplied_docs ( rs . getServerClassName ( ) , rs . getDataSet ( ) ) ; String global_attrs = buildGlobalAttributes ( myDAS , myDDS ) ; String variable_sum = buildVariableSummaries ( myDAS , myDDS ) ; // Send the document back to the client. pw . println ( \"<html><head><title>Dataset Information</title>\" ) ; pw . println ( \"<style type=\\\"text/css\\\">\" ) ; pw . println ( \"<!-- ul {list-style-type: none;} -->\" ) ; pw . println ( \"</style>\" ) ; pw . println ( \"</head>\" ) ; pw . println ( \"<body>\" ) ; if ( global_attrs . length ( ) > 0 ) { pw . println ( global_attrs ) ; pw . println ( \"<hr>\" ) ; } pw . println ( variable_sum ) ; pw . println ( \"<hr>\" ) ; pw . println ( user_html ) ; pw . println ( \"</body></html>\" ) ; // Flush the output buffer. pw . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Checks the info directory for user supplied override documents for the passed dataset name . If there are overridedocuments present then the contents are read and returned to the caller as a string . [CODESPLIT] public String loadOverrideDoc ( String infoDir , String dataSet ) throws DAP2Exception { StringBuilder userDoc = new StringBuilder ( ) ; String overrideFile = dataSet + \".ovr\" ; //Try to open and read the override file for this dataset. try { File fin = new File ( infoDir + overrideFile ) ; try ( BufferedReader svIn = new BufferedReader ( new InputStreamReader ( new FileInputStream ( fin ) , Util . UTF8 ) ) ; ) { boolean done = false ; while ( ! done ) { String line = svIn . readLine ( ) ; if ( line == null ) { done = true ; } else { userDoc . append ( line ) ; userDoc . append ( \"\\n\" ) ; } } } } catch ( FileNotFoundException fnfe ) { userDoc . append ( \"<h2>No Could Not Open Override Document.</h2><hr>\" ) ; return ( null ) ; } catch ( IOException ioe ) { throw ( new DAP2Exception ( opendap . dap . DAP2Exception . UNKNOWN_ERROR , ioe . getMessage ( ) ) ) ; } return ( userDoc . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [CODESPLIT] private String buildGlobalAttributes ( DAS das , ServerDDS dds ) { boolean found = false ; StringBuilder ga = new StringBuilder ( ) ; ga . append ( \"<h3>Dataset Information</h3>\\n<table>\\n\" ) ; Enumeration edas = das . getNames ( ) ; while ( edas . hasMoreElements ( ) ) { String name = ( String ) edas . nextElement ( ) ; if ( ! dasTools . nameInKillFile ( name ) && ( dasTools . nameIsGlobal ( name ) || ! dasTools . nameInDDS ( name , dds ) ) ) { try { AttributeTable attr = das . getAttributeTable ( name ) ; if ( attr != null ) { Enumeration e = attr . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = attr . getAttribute ( aName ) ; found = true ; ga . append ( \"\\n<tr><td align=right valign=top><b>\" ) ; ga . append ( aName + \"</b>:</td>\\n\" ) ; ga . append ( \"<td align=left>\" ) ; Enumeration es = a . getValues ( ) ; while ( es . hasMoreElements ( ) ) { String val = ( String ) es . nextElement ( ) ; ga . append ( val ) ; ga . append ( \"<br>\" ) ; } ga . append ( \"</td></tr>\\n\" ) ; } } } catch ( NoSuchAttributeException nsae ) { } } } ga . append ( \"</table>\\n<p>\\n\" ) ; if ( ! found ) ga . setLength ( 0 ) ; return ( ga . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [CODESPLIT] private String buildVariableSummaries ( DAS das , ServerDDS dds ) { StringBuilder vs = new StringBuilder ( ) ; vs . append ( \"<h3>Variables in this Dataset</h3>\\n<table>\\n\" ) ; Enumeration e = dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; vs . append ( \"<tr>\" ) ; vs . append ( summarizeVariable ( bt , das ) ) ; vs . append ( \"</tr>\" ) ; } vs . append ( \"</table>\\n<p>\\n\" ) ; return ( vs . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make deep copy from sdata to another StructureData object whose data is self contained [CODESPLIT] static public StructureDataDeep copy ( StructureData sdata , StructureMembers members ) { ArrayStructureBB abb = copyToArrayBB ( sdata , members , ByteOrder . BIG_ENDIAN ) ; return new StructureDataDeep ( abb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make deep copy from an ArrayStructure to a ArrayStructureBB whose data is contained in a ByteBuffer [CODESPLIT] static public ArrayStructureBB copyToArrayBB ( ArrayStructure as , ByteOrder bo , boolean canonical ) throws IOException { if ( ! canonical && as . getClass ( ) . equals ( ArrayStructureBB . class ) ) { // no subclasses, LOOK detect already canonical later ArrayStructureBB abb = ( ArrayStructureBB ) as ; ByteBuffer bb = abb . getByteBuffer ( ) ; if ( bo == null || bo . equals ( bb . order ( ) ) ) return abb ; } StructureMembers smo = as . getStructureMembers ( ) ; StructureMembers sm = new StructureMembers ( smo ) ; ArrayStructureBB abb = new ArrayStructureBB ( sm , as . getShape ( ) ) ; ArrayStructureBB . setOffsets ( sm ) ; // this makes the packing canonical if ( bo != null ) { ByteBuffer bb = abb . getByteBuffer ( ) ; bb . order ( bo ) ; } try ( StructureDataIterator iter = as . getStructureDataIterator ( ) ) { while ( iter . hasNext ( ) ) copyToArrayBB ( iter . next ( ) , abb ) ; } return abb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make deep copy to an ArrayStructureBB whose data is contained in a ByteBuffer . Use the order of the members in the given Structure ; skip copying any not in the Structure [CODESPLIT] static public ArrayStructureBB copyToArrayBB ( Structure s , ArrayStructure as , ByteOrder bo ) throws IOException { StructureMembers sm = s . makeStructureMembers ( ) ; ArrayStructureBB abb = new ArrayStructureBB ( sm , as . getShape ( ) ) ; ArrayStructureBB . setOffsets ( sm ) ; if ( bo != null ) { ByteBuffer bb = abb . getByteBuffer ( ) ; bb . order ( bo ) ; } try ( StructureDataIterator iter = as . getStructureDataIterator ( ) ) { while ( iter . hasNext ( ) ) copyToArrayBB ( iter . next ( ) , abb ) ; } return abb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make deep copy from a StructureData to a ArrayStructureBB whose data is contained in a ByteBuffer . [CODESPLIT] static public ArrayStructureBB copyToArrayBB ( StructureData sdata ) { return copyToArrayBB ( sdata , new StructureMembers ( sdata . getStructureMembers ( ) ) , ByteOrder . BIG_ENDIAN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make deep copy from a StructureData to a ArrayStructureBB whose data is contained in a ByteBuffer [CODESPLIT] static public ArrayStructureBB copyToArrayBB ( StructureData sdata , StructureMembers sm , ByteOrder bo ) { int size = sm . getStructureSize ( ) ; ByteBuffer bb = ByteBuffer . allocate ( size ) ; // default is big endian bb . order ( bo ) ; ArrayStructureBB abb = new ArrayStructureBB ( sm , new int [ ] { 1 } , bb , 0 ) ; ArrayStructureBB . setOffsets ( sm ) ; copyToArrayBB ( sdata , abb ) ; return abb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make deep copy from a StructureData into the given ArrayStructureBB [CODESPLIT] static public int copyToArrayBB ( StructureData sdata , ArrayStructureBB abb ) { //StructureMembers sm = sdata.getStructureMembers(); ByteBuffer bb = abb . getByteBuffer ( ) ; int start = bb . limit ( ) ; for ( StructureMembers . Member wantMember : abb . getMembers ( ) ) { StructureMembers . Member m = sdata . findMember ( wantMember . getName ( ) ) ; assert m != null ; assert m . getDataType ( ) == wantMember . getDataType ( ) ; DataType dtype = m . getDataType ( ) ; //System.out.printf(\"do %s (%s) = %d%n\", m.getName(), m.getDataType(), bb.position()); if ( m . isScalar ( ) ) { switch ( dtype ) { case STRING : bb . putInt ( abb . addObjectToHeap ( sdata . getScalarString ( m ) ) ) ; break ; case FLOAT : bb . putFloat ( sdata . getScalarFloat ( m ) ) ; break ; case DOUBLE : bb . putDouble ( sdata . getScalarDouble ( m ) ) ; break ; case INT : case UINT : case ENUM4 : bb . putInt ( sdata . getScalarInt ( m ) ) ; break ; case SHORT : case USHORT : case ENUM2 : bb . putShort ( sdata . getScalarShort ( m ) ) ; break ; case BYTE : case UBYTE : case ENUM1 : bb . put ( sdata . getScalarByte ( m ) ) ; break ; case CHAR : bb . put ( ( byte ) sdata . getScalarChar ( m ) ) ; break ; case LONG : case ULONG : bb . putLong ( sdata . getScalarLong ( m ) ) ; break ; case STRUCTURE : StructureData sd = sdata . getScalarStructure ( m ) ; ArrayStructureBB out_abb = new ArrayStructureBB ( sd . getStructureMembers ( ) , new int [ ] { 1 } , bb , 0 ) ; copyToArrayBB ( sd , out_abb ) ; break ; default : throw new IllegalStateException ( \"scalar \" + dtype . toString ( ) ) ; /* case BOOLEAN:\n           break;\n         case SEQUENCE:\n           break;\n         case OPAQUE:\n           break; */ } } else { int n = m . getSize ( ) ; switch ( dtype ) { case STRING : String [ ] ss = sdata . getJavaArrayString ( m ) ; bb . putInt ( abb . addObjectToHeap ( ss ) ) ; // stored as String[] on the heap break ; case FLOAT : float [ ] fdata = sdata . getJavaArrayFloat ( m ) ; for ( int i = 0 ; i < n ; i ++ ) bb . putFloat ( fdata [ i ] ) ; break ; case DOUBLE : double [ ] ddata = sdata . getJavaArrayDouble ( m ) ; for ( int i = 0 ; i < n ; i ++ ) bb . putDouble ( ddata [ i ] ) ; break ; case INT : case ENUM4 : int [ ] idata = sdata . getJavaArrayInt ( m ) ; for ( int i = 0 ; i < n ; i ++ ) bb . putInt ( idata [ i ] ) ; break ; case SHORT : case ENUM2 : short [ ] shdata = sdata . getJavaArrayShort ( m ) ; for ( int i = 0 ; i < n ; i ++ ) bb . putShort ( shdata [ i ] ) ; break ; case BYTE : case ENUM1 : byte [ ] bdata = sdata . getJavaArrayByte ( m ) ; for ( int i = 0 ; i < n ; i ++ ) bb . put ( bdata [ i ] ) ; break ; case CHAR : char [ ] cdata = sdata . getJavaArrayChar ( m ) ; bb . put ( IospHelper . convertCharToByte ( cdata ) ) ; break ; case LONG : long [ ] ldata = sdata . getJavaArrayLong ( m ) ; for ( int i = 0 ; i < n ; i ++ ) bb . putLong ( ldata [ i ] ) ; break ; default : throw new IllegalStateException ( \"array \" + dtype . toString ( ) ) ; /* case BOOLEAN:\n          break;\n         case OPAQUE:\n          break;\n        case STRUCTURE:\n          break; // */ case SEQUENCE : break ; // skip } } } return bb . limit ( ) - start ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only use in GribVariable to decide on variable identity when intvMerge = false . By returning a constant we dont intvMerge = false . Problem is we cant reconstruct interval length without reference time which is not in the pds . [CODESPLIT] @ Override public double getForecastTimeIntervalSizeInHours ( Grib2Pds pds ) { Grib2Pds . PdsInterval pdsIntv = ( Grib2Pds . PdsInterval ) pds ; // override here only if timeRangeUnit = 255 boolean needOverride = false ; for ( Grib2Pds . TimeInterval ti : pdsIntv . getTimeIntervals ( ) ) { needOverride = ( ti . timeRangeUnit == 255 ) ; } if ( ! needOverride ) return super . getForecastTimeIntervalSizeInHours ( pds ) ; return 12.0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new CoordinateAxis1D as a section of this CoordinateAxis1D . [CODESPLIT] public CoordinateAxis1D section ( Range r ) throws InvalidRangeException { Section section = new Section ( ) . appendRange ( r ) ; CoordinateAxis1D result = ( CoordinateAxis1D ) section ( section ) ; int len = r . length ( ) ; // deal with the midpoints, bounds if ( isNumeric ( ) ) { double [ ] new_mids = new double [ len ] ; for ( int idx = 0 ; idx < len ; idx ++ ) { int old_idx = r . element ( idx ) ; new_mids [ idx ] = coords [ old_idx ] ; } result . coords = new_mids ; if ( isInterval ) { double [ ] new_bound1 = new double [ len ] ; double [ ] new_bound2 = new double [ len ] ; double [ ] new_edge = new double [ len + 1 ] ; for ( int idx = 0 ; idx < len ; idx ++ ) { int old_idx = r . element ( idx ) ; new_bound1 [ idx ] = bound1 [ old_idx ] ; new_bound2 [ idx ] = bound2 [ old_idx ] ; new_edge [ idx ] = bound1 [ old_idx ] ; new_edge [ idx + 1 ] = bound2 [ old_idx ] ; // all but last are overwritten } result . bound1 = new_bound1 ; result . bound2 = new_bound2 ; result . edge = new_edge ; } else { double [ ] new_edge = new double [ len + 1 ] ; for ( int idx = 0 ; idx < len ; idx ++ ) { int old_idx = r . element ( idx ) ; new_edge [ idx ] = edge [ old_idx ] ; new_edge [ idx + 1 ] = edge [ old_idx + 1 ] ; // all but last are overwritten } result . edge = new_edge ; } } if ( names != null ) { String [ ] new_names = new String [ len ] ; for ( int idx = 0 ; idx < len ; idx ++ ) { int old_idx = r . element ( idx ) ; new_names [ idx ] = names [ old_idx ] ; } result . names = new_names ; } result . wasCalcRegular = false ; result . calcIsRegular ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of names to be used for user selection . The ith one refers to the ith coordinate . [CODESPLIT] public List < NamedObject > getNames ( ) { int n = getDimension ( 0 ) . getLength ( ) ; List < NamedObject > names = new ArrayList <> ( n ) ; for ( int i = 0 ; i < n ; i ++ ) names . ( new ucar . nc2 . util . NamedAnything ( getCoordName ( i ) , getShortName ( ) + \" \" + getUnitsString ( ) ) ) ; return names ; } /**\n   * The \"name\" of the ith coordinate. If nominal, this is all there is to a coordinate.\n   * If numeric, this will return a String representation of the coordinate.\n   *\n   * @param index which one ?\n   * @return the ith coordinate value as a String\n   */ public String getCoordName ( int index ) { if ( ! wasRead ) doRead ( ) ; if ( isNumeric ( ) ) return Format . d ( getCoordValue ( index ) , 5 , 8 ) ; else return names [ index ] ; } /**\n   * Get the ith coordinate value. This is the value of the coordinate axis at which\n   * the data value is associated. These must be strictly monotonic.\n   *\n   * @param index which coordinate. Between 0 and getNumElements()-1 inclusive.\n   * @return coordinate value.\n   * @throws UnsupportedOperationException if !isNumeric()\n   */ public double getCoordValue  ( int index ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordValue() on non-numeric\" ) ; if ( ! wasRead ) doRead ( ) ; return coords [ index ] ; } @ Override public double getMinValue  ( ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordValue() on non-numeric\" ) ; if ( ! wasRead ) doRead ( ) ; return Math . min ( coords [ 0 ] , coords [ coords . length - 1 ] ) ; } @ Override public double getMaxValue  ( ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordValue() on non-numeric\" ) ; if ( ! wasRead ) doRead ( ) ; return Math . max ( coords [ 0 ] , coords [ coords . length - 1 ] ) ; } public double getMinEdgeValue  ( ) { if ( edge == null ) return getMinValue ( ) ; if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordValue() on non-numeric\" ) ; if ( ! wasRead ) doRead ( ) ; return Math . min ( edge [ 0 ] , edge [ edge . length - 1 ] ) ; } public double getMaxEdgeValue  ( ) { if ( edge == null ) return getMaxValue ( ) ; if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordValue() on non-numeric\" ) ; if ( ! wasRead ) doRead ( ) ; return Math . max ( edge [ 0 ] , edge [ edge . length - 1 ] ) ; } /**\n   * Get the ith coordinate edge. Exact only if isContiguous() is true, otherwise use getBound1() and getBound2().\n   * This is the value where the underlying grid element switches\n   * from \"belonging to\" coordinate value i-1 to \"belonging to\" coordinate value i.\n   * In some grids, this may not be well defined, and so should be considered an\n   * approximation or a visualization hint.\n   * <p><pre>\n   *  Coordinate edges must be strictly monotonic:\n   *    coordEdge(0) < coordValue(0) < coordEdge(1) < coordValue(1) ...\n   *    ... coordEdge(i) < coordValue(i) < coordEdge(i+1) < coordValue(i+1) ...\n   *    ... coordEdge(n-1) < coordValue(n-1) < coordEdge(n)\n   *  </pre>\n   *\n   * @param index which coordinate. Between 0 and getNumElements() inclusive.\n   * @return coordinate edge.\n   * @throws UnsupportedOperationException if !isNumeric()\n   */ public double getCoordEdge  ( int index ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordEdge() on non-numeric\" ) ; if ( ! wasBoundsDone ) makeBounds ( ) ; return edge [ index ] ; } /**\n   * Get the coordinate values as a double array.\n   *\n   * @return coordinate value.\n   * @throws UnsupportedOperationException if !isNumeric()\n   */ public double [ ] getCoordValues  ( ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordValues() on non-numeric\" ) ; if ( ! wasRead ) doRead ( ) ; return coords . clone ( ) ; } /**\n   * Get the coordinate edges as a double array.\n   * Exact only if isContiguous() is true, otherwise use getBound1() and getBound2().\n   *\n   * @return coordinate edges.\n   * @throws UnsupportedOperationException if !isNumeric()\n   */ public double [ ] getCoordEdges  ( ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getCoordEdges() on non-numeric\" ) ; if ( ! wasBoundsDone ) makeBounds ( ) ; return edge . clone ( ) ; } @ Override public boolean isContiguous  ( ) { if ( ! wasBoundsDone ) makeBounds ( ) ; // this sets isContiguous return isContiguous ; } /////////////////////////////////////////////// /**\n   * If this coordinate has interval values.\n   * If so, then one should use getBound1, getBound2, and not getCoordEdges()\n   *\n   * @return true if coordinate has interval values\n   */ public boolean isInterval  ( ) { if ( ! wasBoundsDone ) makeBounds ( ) ; // this sets isInterval return isInterval ; } /**\n   * Get the coordinate bound1 as a double array.\n   * bound1[i] # coordValue[i] # bound2[i], where # is < if increasing (bound1[i] < bound1[i+1])\n   * else < if decreasing.\n   *\n   * @return coordinate bound1.\n   * @throws UnsupportedOperationException if !isNumeric()\n   */ public double [ ] getBound1  ( ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getBound1() on non-numeric\" ) ; if ( ! wasBoundsDone ) makeBounds ( ) ; if ( bound1 == null ) makeBoundsFromEdges ( ) ; assert bound1 != null ; return bound1 . clone ( ) ; } /**\n   * Get the coordinate bound1 as a double array.\n   * bound1[i] # coordValue[i] # bound2[i],  where # is < if increasing (bound1[i] < bound1[i+1])\n   * else < if decreasing.\n   *\n   * @return coordinate bound2.\n   * @throws UnsupportedOperationException if !isNumeric()\n   */ public double [ ] getBound2  ( ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis1D.getBound2() on non-numeric\" ) ; if ( ! wasBoundsDone ) makeBounds ( ) ; if ( bound2 == null ) makeBoundsFromEdges ( ) ; assert bound2 != null ; return bound2 . clone ( ) ; } /**\n   * Get the coordinate bounds for the ith coordinate.\n   * Can use this for isContiguous() true or false.\n   *\n   * @param i coordinate index\n   * @return double[2] edges for ith coordinate\n   */ public double [ ] getCoordBounds  ( int i ) { if ( ! wasBoundsDone ) makeBounds ( ) ; double [ ] e = new double [ 2 ] ; if ( isContiguous ( ) ) { e [ 0 ] = getCoordEdge ( i ) ; e [ 1 ] = getCoordEdge ( i + 1 ) ; } else { e [ 0 ] = bound1 [ i ] ; e [ 1 ] = bound2 [ i ] ; } return e ; } public double getCoordBoundsMidpoint  ( int i ) { double [ ] bounds = getCoordBounds ( i ) ; return ( bounds [ 0 ] + bounds [ 1 ] ) / 2 ; } /**\n   * Given a coordinate value, find what grid element contains it.\n   * This means that\n   * <pre>\n   * edge[i] <= value < edge[i+1] (if values are ascending)\n   * edge[i] > value >= edge[i+1] (if values are descending)\n   * </pre>\n   *\n   * @param coordVal position in this coordinate system\n   * @return index of grid point containing it, or -1 if outside grid area\n   */ public int findCoordElement  ( double coordVal ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis.findCoordElement() on non-numeric\" ) ; if ( isRegular ( ) ) return findCoordElementRegular ( coordVal , false ) ; if ( isContiguous ( ) ) return findCoordElementIrregular ( coordVal , false ) ; else return findCoordElementNonContiguous ( coordVal , false ) ; } /**\n   * Given a coordinate position, find what grid element contains it, or is closest to it.\n   *\n   * @param coordVal position in this coordinate system\n   * @return index of grid point containing it, or best estimate of closest grid interval.\n   */ public int findCoordElementBounded  ( double coordVal ) { if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( \"CoordinateAxis.findCoordElementBounded() on non-numeric\" ) ; // the scalar or len-1 case: if ( this . getSize ( ) == 1 ) return 0 ; if ( isRegular ( ) ) return findCoordElementRegular ( coordVal , true ) ; if ( isContiguous ( ) ) return findCoordElementIrregular ( coordVal , true ) ; else return findCoordElementNonContiguous ( coordVal , true ) ; } /**\n   * @deprecated use findCoordElement(coordVal)\n   */ public int findCoordElement  ( double coordVal , int lastIndex ) { return findCoordElement ( coordVal ) ; } ////////////////////////////////////////////////////////////////// // following is from Jon Blower's ncWMS // faster routines for coordValue -> index search // significantly modified /**\n   * Optimize the regular case\n   * Gets the index of the given point. Uses index = (value - start) / stride,\n   * hence this is faster than an exhaustive search.\n   * from jon blower's ncWMS.\n   *\n   * @param coordValue The value along this coordinate axis\n   * @param bounded    if false and not in range, return -1, else nearest index\n   * @return the index that is nearest to this point, or -1 if the point is\n   * out of range for the axis\n   */ private int findCoordElementRegular  ( double coordValue , boolean bounded ) { int n = ( int ) this . getSize ( ) ; // the scalar or len-1 case: if ( this . getSize ( ) == 1 ) { return 0 ; } /*  if (axisType == AxisType.Lon) {\n      double maxValue = this.start + this.increment * n;\n      if (betweenLon(coordValue, this.start, maxValue)) {\n        double distance = LatLonPointImpl.getClockwiseDistanceTo(this.start, coordValue);\n        double exactNumSteps = distance / this.increment;\n        // This axis might wrap, so we make sure that the returned index is within range\n        return ((int) Math.round(exactNumSteps)) % (int) this.getSize();\n\n      } else if (coordValue < this.start) {\n        return bounded ? 0 : -1;\n      } else {\n        return bounded ? n - 1 : -1;\n      }\n    } */ double distance = coordValue - this . start ; double exactNumSteps = distance / this . increment ; int index = ( int ) Math . round ( exactNumSteps ) ; if ( index < 0 ) return bounded ? 0 : - 1 ; else if ( index >= n ) return bounded ? n - 1 : - 1 ; return index ; } private boolean betweenLon  ( double lon , double lonBeg , double lonEnd ) { while ( lon < lonBeg ) lon += 360 ; return ( lon >= lonBeg ) && ( lon <= lonEnd ) ; } /**\n   * Performs a binary search to find the index of the element of the array\n   * whose value is contained in the interval, so must be contiguous.\n   *\n   * @param target  The value to search for\n   * @param bounded if false, and not in range, return -1, else nearest index\n   * @return the index of the element in values whose value is closest to target,\n   * or -1 if the target is out of range\n   */ private int findCoordElementIrregular  ( double target , boolean bounded ) { int n = ( int ) this . getSize ( ) ; int low = 0 ; int high = n ; if ( isAscending ) { // Check that the point is within range if ( target < this . edge [ low ] ) return bounded ? 0 : - 1 ; else if ( target > this . edge [ high ] ) return bounded ? n - 1 : - 1 ; // do a binary search to find the nearest index int mid = low ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; double midVal = this . edge [ mid ] ; if ( midVal == target ) return mid ; else if ( midVal < target ) low = mid ; else high = mid ; } return low ; } else { // Check that the point is within range if ( target > this . edge [ low ] ) return bounded ? 0 : - 1 ; else if ( target < this . edge [ high ] ) return bounded ? n - 1 : - 1 ; // do a binary search to find the nearest index int mid = low ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; double midVal = this . edge [ mid ] ; if ( midVal == target ) return mid ; else if ( midVal < target ) high = mid ; else low = mid ; } return high - 1 ; } } /**\n   * Given a coordinate position, find what grid element contains it.\n   * Only use if isContiguous() == false\n   * This algorithm does a linear search in the bound1[] amd bound2[] array.\n   * <p>\n   * This means that\n   * <pre>\n   * edge[i] <= pos < edge[i+1] (if values are ascending)\n   * edge[i] > pos >= edge[i+1] (if values are descending)\n   * </pre>\n   *\n   * @param target  The value to search for\n   * @param bounded if false, and not in range, return -1, else nearest index\n   * @return the index of the element in values whose value is closest to target,\n   * or -1 if the target is out of range\n   */ private int findCoordElementNonContiguous  ( double target , boolean bounded ) { double [ ] bounds1 = getBound1 ( ) ; double [ ] bounds2 = getBound2 ( ) ; int n = bounds1 . length ; if ( isAscending ) { // Check that the point is within range if ( target < bounds1 [ 0 ] ) return bounded ? 0 : - 1 ; else if ( target > bounds2 [ n - 1 ] ) return bounded ? n - 1 : - 1 ; int [ ] idx = findSingleHit ( bounds1 , bounds2 , target ) ; if ( idx [ 0 ] == 0 && ! bounded ) return - 1 ; // no hits if ( idx [ 0 ] == 1 ) return idx [ 1 ] ; // one hit // multiple hits = choose closest to the midpoint i guess return findClosest ( coords , target ) ; } else { // Check that the point is within range if ( target > bounds1 [ 0 ] ) return bounded ? 0 : - 1 ; else if ( target < bounds2 [ n - 1 ] ) return bounded ? n - 1 : - 1 ; int [ ] idx = findSingleHit ( bounds2 , bounds1 , target ) ; if ( idx [ 0 ] == 0 && ! bounded ) return - 1 ; // no hits if ( idx [ 0 ] == 1 ) return idx [ 1 ] ; // multiple hits = choose closest to the midpoint i guess return findClosest ( getCoordValues ( ) , target ) ; } } // return index if only one match, else -1 private int [ ] findSingleHit  ( double [ ] low , double [ ] high , double target ) { int hits = 0 ; int idxFound = - 1 ; int n = low . length ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( low [ i ] <= target ) && ( target <= high [ i ] ) ) { hits ++ ; idxFound = i ; } } return new int [ ] { hits , idxFound } ; } // return index of closest value to target private int findClosest  ( double [ ] values , double target ) { double minDiff = Double . MAX_VALUE ; int idxFound = - 1 ; int n = values . length ; for ( int i = 0 ; i < n ; i ++ ) { double diff = Math . abs ( values [ i ] - target ) ; if ( diff < minDiff ) { minDiff = diff ; idxFound = i ; } } return idxFound ; } /////////////////////////////////////////////////////////////////////////////// // check if Regular /**\n   * Get starting value if isRegular()\n   *\n   * @return starting value if isRegular()\n   */ public double getStart  ( ) { calcIsRegular ( ) ; return start ; } /**\n   * Get increment value if isRegular()\n   *\n   * @return increment value if isRegular()\n   */ public double getIncrement  ( ) { calcIsRegular ( ) ; return increment ; } /**\n   * If true, then value(i) = <i>getStart()</i> + i * <i>getIncrement()</i>.\n   *\n   * @return if evenly spaced.\n   */ public boolean isRegular  ( ) { calcIsRegular ( ) ; return isRegular ; } private void calcIsRegular  ( ) { if ( wasCalcRegular ) return ; if ( ! wasRead ) doRead ( ) ; if ( ! isNumeric ( ) ) isRegular = false ; else if ( getSize ( ) < 2 ) isRegular = true ; else { start = getCoordValue ( 0 ) ; int n = ( int ) getSize ( ) ; increment = ( getCoordValue ( n - 1 ) - getCoordValue ( 0 ) ) / ( n - 1 ) ; isRegular = true ; for ( int i = 1 ; i < getSize ( ) ; i ++ ) if ( ! ucar . nc2 . util . Misc . nearlyEquals ( getCoordValue ( i ) - getCoordValue ( i - 1 ) , increment , 5.0e-3 ) ) { isRegular = false ; break ; } } wasCalcRegular = true ; } /////////////////////////////////////////////////////////////////////////////// private void doRead  ( ) { if ( isNumeric ( ) ) { readValues ( ) ; wasRead = true ; if ( getSize ( ) < 2 ) isAscending = true ; else isAscending = getCoordValue ( 0 ) < getCoordValue ( 1 ) ; //  calcIsRegular(); */ } else if ( getDataType ( ) == DataType . STRING ) { readStringValues ( ) ; wasRead = true ; } else { readCharValues ( ) ; wasRead = true ; } } // turns longitude coordinate into monotonic, dealing with possible wrap. public void correctLongitudeWrap  ( ) { // correct non-monotonic longitude coords if ( axisType != AxisType . Lon ) { return ; } if ( ! wasRead ) doRead ( ) ; if ( ! wasBoundsDone ) makeBounds ( ) ; boolean monotonic = true ; for ( int i = 0 ; i < coords . length - 1 ; i ++ ) monotonic &= isAscending ? coords [ i ] < coords [ i + 1 ] : coords [ i ] > coords [ i + 1 ] ; if ( ! monotonic ) { boolean cross = false ; if ( isAscending ) { for ( int i = 0 ; i < coords . length ; i ++ ) { if ( cross ) coords [ i ] += 360 ; if ( ! cross && ( i < coords . length - 1 ) && ( coords [ i ] > coords [ i + 1 ] ) ) cross = true ; } } else { for ( int i = 0 ; i < coords . length ; i ++ ) { if ( cross ) coords [ i ] -= 360 ; if ( ! cross && ( i < coords . length - 1 ) && ( coords [ i ] < coords [ i + 1 ] ) ) cross = true ; } } // LOOK - need to make sure we get stuff from the cache Array cachedData = Array . factory ( DataType . DOUBLE , getShape ( ) , coords ) ; if ( getDataType ( ) != DataType . DOUBLE ) cachedData = MAMath . convert ( cachedData , getDataType ( ) ) ; setCachedData ( cachedData ) ; if ( ! isInterval ) { makeEdges ( ) ; } } } // only used if String private void readStringValues  ( ) { int count = 0 ; Array data ; try { data = read ( ) ; } catch ( IOException ioe ) { log . error ( \"Error reading string coordinate values \" , ioe ) ; throw new IllegalStateException ( ioe ) ; } names = new String [ ( int ) data . getSize ( ) ] ; IndexIterator ii = data . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) names [ count ++ ] = ( String ) ii . getObjectNext ( ) ; } private void readCharValues  ( ) { int count = 0 ; ArrayChar data ; try { data = ( ArrayChar ) read ( ) ; } catch ( IOException ioe ) { log . error ( \"Error reading char coordinate values \" , ioe ) ; throw new IllegalStateException ( ioe ) ; } ArrayChar . StringIterator iter = data . getStringIterator ( ) ; names = new String [ iter . getNumElems ( ) ] ; while ( iter . hasNext ( ) ) names [ count ++ ] = iter . next ( ) ; } private void readValues  ( ) { Array data ; try { // setUseNaNs(false); // missing values not allowed LOOK not true for point data !! data = read ( ) ; // if (!hasCachedData()) setCachedData(data, false); //cache data for subsequent reading } catch ( IOException ioe ) { log . error ( \"Error reading coordinate values \" , ioe ) ; throw new IllegalStateException ( ioe ) ; } coords = ( double [ ] ) data . get1DJavaArray ( DataType . DOUBLE ) ; //IndexIterator iter = data.getIndexIterator(); //while (iter.hasNext()) //  coords[count++] = iter.getDoubleNext(); } /**\n   * Calculate bounds, set isInterval, isContiguous\n   */ private void makeBounds  ( ) { if ( ! wasRead ) doRead ( ) ; if ( isNumeric ( ) ) { if ( ! makeBoundsFromAux ( ) ) { makeEdges ( ) ; } } wasBoundsDone = true ; } private boolean makeBoundsFromAux  ( ) { Attribute boundsAtt = findAttributeIgnoreCase ( CF . BOUNDS ) ; if ( ( null == boundsAtt ) || ! boundsAtt . isString ( ) ) return false ; String boundsVarName = boundsAtt . getStringValue ( ) ; VariableDS boundsVar = ( VariableDS ) ncd . findVariable ( getParentGroup ( ) , boundsVarName ) ; if ( null == boundsVar ) return false ; if ( 2 != boundsVar . getRank ( ) ) return false ; if ( getDimension ( 0 ) != boundsVar . getDimension ( 0 ) ) return false ; if ( 2 != boundsVar . getDimension ( 1 ) . getLength ( ) ) return false ; Array data ; try { boundsVar . removeEnhancement ( NetcdfDataset . Enhance . ConvertMissing ) ; // Don't convert missing values to NaN. data = boundsVar . read ( ) ; } catch ( IOException e ) { log . warn ( \"CoordinateAxis1D.hasBounds read failed \" , e ) ; return false ; } assert ( data . getRank ( ) == 2 ) && ( data . getShape ( ) [ 1 ] == 2 ) : \"incorrect shape data for variable \" + boundsVar ; // extract the bounds int n = shape [ 0 ] ; double [ ] value1 = new double [ n ] ; double [ ] value2 = new double [ n ] ; Index ima = data . getIndex ( ) ; for ( int i = 0 ; i < n ; i ++ ) { ima . set0 ( i ) ; value1 [ i ] = data . getDouble ( ima . set1 ( 0 ) ) ; value2 [ i ] = data . getDouble ( ima . set1 ( 1 ) ) ; } /* flip if needed\n    boolean firstLower = true; // in the first interval, is lower < upper ?\n    for (int i = 0; i < value1.length; i++) {\n      if (Misc.nearlyEquals(value1[i], value2[i])) continue; // skip when lower == upper\n      firstLower = value1[i] < value2[i];\n      break;\n    }\n    // check first against last : lower, unless all lower equal then upper\n    boolean goesUp = (n < 2) || value1[n - 1] > value1[0] || (Misc.nearlyEquals(value1[n - 1], value2[0]) && value2[n - 1] > value2[0]);\n    if (goesUp != firstLower) {\n      double[] temp = value1;\n      value1 = value2;\n      value2 = temp;\n    } */ // decide if they are contiguous boolean contig = true ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( ! ucar . nc2 . util . Misc . nearlyEquals ( value1 [ i + 1 ] , value2 [ i ] ) ) contig = false ; } if ( contig ) { edge = new double [ n + 1 ] ; edge [ 0 ] = value1 [ 0 ] ; for ( int i = 1 ; i < n + 1 ; i ++ ) edge [ i ] = value2 [ i - 1 ] ; } else { // what does edge mean when not contiguous ?? edge = new double [ n + 1 ] ; edge [ 0 ] = value1 [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) edge [ i ] = ( value1 [ i ] + value2 [ i - 1 ] ) / 2 ; edge [ n ] = value2 [ n - 1 ] ; isContiguous = false ; } bound1 = value1 ; bound2 = value2 ; isInterval = true ; return true ; } private void makeEdges  ( ) { int size = ( int ) getSize ( ) ; edge = new double [ size + 1 ] ; if ( size < 1 ) return ; for ( int i = 1 ; i < size ; i ++ ) edge [ i ] = ( coords [ i - 1 ] + coords [ i ] ) / 2 ; edge [ 0 ] = coords [ 0 ] - ( edge [ 1 ] - coords [ 0 ] ) ; edge [ size ] = coords [ size - 1 ] + ( coords [ size - 1 ] - edge [ size - 1 ] ) ; isContiguous = true ; } private void makeBoundsFromEdges  ( ) { int size = ( int ) getSize ( ) ; if ( size == 0 ) return ; bound1 = new double [ size ] ; bound2 = new double [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { bound1 [ i ] = edge [ i ] ; bound2 [ i ] = edge [ i + 1 ] ; } // flip if needed if ( bound1 [ 0 ] > bound2 [ 0 ] ) { double [ ] temp = bound1 ; bound1 = bound2 ; bound2 = temp ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////// JFileChooser /////////////////////////////////////////////////// [CODESPLIT] @ Override public int showDialog ( Component parent , String approveButtonText ) throws HeadlessException { int returnValue = super . showDialog ( parent , approveButtonText ) ; this . dialog = null ; // dialog was disposed in super-method. Null out so we don't try to use it. return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a TableConfigurer for this dataset if there is one . [CODESPLIT] static public TableConfigurer getTableConfigurer ( FeatureType wantFeatureType , NetcdfDataset ds ) throws IOException { String convUsed = null ; // search for the Conventions attribute\r String convName = ds . findAttValueIgnoreCase ( null , CDM . CONVENTIONS , null ) ; if ( convName == null ) convName = ds . findAttValueIgnoreCase ( null , \"Convention\" , null ) ; // now search for TableConfigurer using that Convention\r Configurator anal = null ; if ( convName != null ) { convName = convName . trim ( ) ; // search for Convention parsing class\r anal = matchConfigurator ( convName ) ; if ( anal != null ) { convUsed = convName ; if ( debug ) System . out . println ( \"  TableConfigurer found using convName \" + convName ) ; } // now search for comma or semicolon or / delimited list\r if ( anal == null ) { List < String > names = new ArrayList <> ( ) ; if ( ( convName . indexOf ( ' ' ) > 0 ) || ( convName . indexOf ( ' ' ) > 0 ) ) { StringTokenizer stoke = new StringTokenizer ( convName , \",;\" ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } else if ( ( convName . indexOf ( ' ' ) > 0 ) ) { StringTokenizer stoke = new StringTokenizer ( convName , \"/\" ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } if ( names . size ( ) > 0 ) { // search the registered conventions, in order\r for ( Configurator conv : conventionList ) { for ( String name : names ) { if ( name . equalsIgnoreCase ( conv . convName ) ) { anal = conv ; convUsed = name ; if ( debug ) System . out . println ( \"  TableConfigurer found using convName \" + convName ) ; } } if ( anal != null ) break ; } } } } // search for ones that dont use Convention attribute, in order added.\r // call method isMine() using reflection.\r if ( anal == null ) { for ( Configurator conv : conventionList ) { Class c = conv . confClass ; Method isMineMethod ; try { isMineMethod = c . getMethod ( \"isMine\" , new Class [ ] { FeatureType . class , NetcdfDataset . class } ) ; } catch ( NoSuchMethodException ex ) { continue ; } try { Boolean result = ( Boolean ) isMineMethod . invoke ( conv . confInstance , wantFeatureType , ds ) ; if ( debug ) System . out . println ( \"  TableConfigurer.isMine \" + c . getName ( ) + \" result = \" + result ) ; if ( result ) { anal = conv ; convUsed = conv . convName ; break ; } } catch ( Exception ex ) { System . out . println ( \"ERROR: Class \" + c . getName ( ) + \" Exception invoking isMine method%n\" + ex ) ; } } } // Instantiate a new TableConfigurer object\r TableConfigurer tc = null ; if ( anal != null ) { try { tc = ( TableConfigurer ) anal . confClass . newInstance ( ) ; tc . setConvName ( convName ) ; tc . setConvUsed ( convUsed ) ; } catch ( InstantiationException | IllegalAccessException e ) { log . error ( \"TableConfigurer create failed\" , e ) ; } } return tc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a TableAnalyser for this dataset with the given TableConfigurer [CODESPLIT] static public TableAnalyzer factory ( TableConfigurer tc , FeatureType wantFeatureType , NetcdfDataset ds ) throws IOException { // Create a TableAnalyzer with this TableConfigurer (may be null)\r TableAnalyzer analyzer = new TableAnalyzer ( ds , tc ) ; if ( tc != null ) { if ( tc . getConvName ( ) == null ) analyzer . userAdvice . format ( \" No 'Conventions' global attribute.%n\" ) ; else analyzer . userAdvice . format ( \" Conventions global attribute = %s %n\" , tc . getConvName ( ) ) ; // add the convention name used\r if ( tc . getConvUsed ( ) != null ) { analyzer . setConventionUsed ( tc . getConvUsed ( ) ) ; if ( ! tc . getConvUsed ( ) . equals ( tc . getConvName ( ) ) ) analyzer . userAdvice . format ( \" TableConfigurer used = \" + tc . getConvUsed ( ) + \".%n\" ) ; } } else { analyzer . userAdvice . format ( \" No TableConfigurer found, using default analysis.%n\" ) ; } // construct the nested table object\r analyzer . analyze ( wantFeatureType ) ; return analyzer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for debugging messages [CODESPLIT] public FeatureType getFirstFeatureType ( ) { for ( NestedTable nt : leaves ) { if ( nt . hasCoords ( ) ) return nt . getFeatureType ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a NestedTable object for the dataset . [CODESPLIT] private void analyze ( FeatureType wantFeatureType ) throws IOException { // for netcdf-3 files, convert record dimension to structure\r // LOOK may be problems when served via opendap\r boolean structAdded = ( Boolean ) ds . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( tc == null ) { makeTablesDefault ( structAdded ) ; makeNestedTables ( ) ; } else { configResult = tc . getConfig ( wantFeatureType , ds , errlog ) ; if ( configResult != null ) addTableRecurse ( configResult ) ; // kinda stupid\r else { // use default\r makeTablesDefault ( structAdded ) ; makeNestedTables ( ) ; } } // find the leaves\r for ( TableConfig config : tableSet ) { if ( config . children == null ) { // its a leaf\r NestedTable flatTable = new NestedTable ( ds , config , errlog ) ; leaves . add ( flatTable ) ; } } if ( PointDatasetStandardFactory . showTables ) getDetailInfo ( new Formatter ( System . out ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "no TableConfig was passed in - gotta wing it [CODESPLIT] private void makeTablesDefault ( boolean structAdded ) throws IOException { // make Structures into a table\r List < Variable > vars = new ArrayList <> ( ds . getVariables ( ) ) ; Iterator < Variable > iter = vars . iterator ( ) ; while ( iter . hasNext ( ) ) { Variable v = iter . next ( ) ; if ( v instanceof Structure ) { // handles Sequences too\r TableConfig st = new TableConfig ( Table . Type . Structure , v . getFullName ( ) ) ; CoordSysEvaluator . findCoords ( st , ds , null ) ; st . structName = v . getFullName ( ) ; st . nestedTableName = v . getShortName ( ) ; addTable ( st ) ; checkIfTrajectory ( st ) ; iter . remove ( ) ; findNestedStructures ( ( Structure ) v , st ) ; // look for nested structures\r } else if ( structAdded && v . isUnlimited ( ) ) { iter . remove ( ) ; } } if ( tableSet . size ( ) > 0 ) return ; // search at dimensions that lat, lon, time coordinates use\r Set < Dimension > dimSet = new HashSet <> ( 10 ) ; for ( CoordinateAxis axis : ds . getCoordinateAxes ( ) ) { if ( ( axis . getAxisType ( ) == AxisType . Lat ) || ( axis . getAxisType ( ) == AxisType . Lon ) || ( axis . getAxisType ( ) == AxisType . Time ) ) for ( Dimension dim : axis . getDimensions ( ) ) dimSet . ( dim ) ; } // lat, lon, time all use same dimension - use it\r if ( dimSet . size ( ) == 1 ) { final Dimension obsDim = ( Dimension ) dimSet . toArray ( ) [ 0 ] ; TableConfig st = new TableConfig ( Table . Type . Structure , obsDim . getShortName ( ) ) ; st . structureType = obsDim . isUnlimited ( ) ? TableConfig . StructureType . Structure : TableConfig . StructureType . PsuedoStructure ; st . structName = obsDim . isUnlimited ( ) ? \"record\" : obsDim . getShortName ( ) ; st . dimName = obsDim . getShortName ( ) ; CoordSysEvaluator . findCoords ( st , ds , new CoordSysEvaluator . Predicate ( ) { public boolean match ( CoordinateAxis axis ) { return obsDim . equals ( axis . getDimension ( 0 ) ) ; } } ) ; CoordinateAxis time = CoordSysEvaluator . findCoordByType ( ds , AxisType . Time ) ; if ( ( time != null ) && ( time . getRank ( ) == 0 ) ) { st . addJoin ( new JoinArray ( time , JoinArray . Type . scalar , 0 ) ) ; st . time = time . getShortName ( ) ; } addTable ( st ) ; checkIfTrajectory ( st ) ; } if ( tableSet . size ( ) > 0 ) return ; // try the time dimension\r CoordinateAxis time = null ; for ( CoordinateAxis axis : ds . getCoordinateAxes ( ) ) { if ( ( axis . getAxisType ( ) == AxisType . Time ) && axis . isIndependentCoordinate ( ) ) { time = axis ; break ; } } if ( time != null ) { Dimension obsDim = time . getDimension ( 0 ) ; TableConfig st = new TableConfig ( Table . Type . Structure , obsDim . getShortName ( ) ) ; st . structureType = TableConfig . StructureType . PsuedoStructure ; st . dimName = obsDim . getShortName ( ) ; CoordSysEvaluator . findCoords ( st , ds , null ) ; addTable ( st ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public void showTables ( java . util . Formatter sf ) { sf . format ( %nTables%n ) ; for ( NestedTable . Table t : tableSet ) sf . format ( %s%n t ) ; [CODESPLIT] public void showNestedTables ( java . util . Formatter sf ) { for ( NestedTable nt : leaves ) { nt . show ( sf ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XML document from this info [CODESPLIT] private Document makeDocument ( ) { Element rootElem = new Element ( \"featureDataset\" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( \"location\" , ds . getLocation ( ) ) ; rootElem . addContent ( new Element ( \"analyser\" ) . setAttribute ( \"class\" , getName ( ) ) ) ; if ( ft != null ) rootElem . setAttribute ( \"featureType\" , ft . toString ( ) ) ; for ( NestedTable nt : leaves ) { writeTable ( rootElem , nt . getLeaf ( ) ) ; } return doc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////// [CODESPLIT] static void doit ( String filename ) throws IOException { System . out . println ( filename ) ; NetcdfDataset ncd = ucar . nc2 . dataset . NetcdfDataset . openDataset ( filename ) ; TableAnalyzer csa = TableAnalyzer . factory ( null , null , ncd ) ; csa . getDetailInfo ( new Formatter ( System . out ) ) ; System . out . println ( \"%n-----------------\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a valid file? [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { mcGridReader = new McIDASGridReader ( ) ; return mcGridReader . init ( raf , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the service provider for reading . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { //debugProj = true; super . open ( raf , ncfile , cancelTask ) ; long start = System . currentTimeMillis ( ) ; if ( mcGridReader == null ) { mcGridReader = new McIDASGridReader ( ) ; } mcGridReader . init ( raf ) ; GridIndex index = mcGridReader . getGridIndex ( ) ; open ( index , cancelTask ) ; if ( debugOpen ) { System . out . println ( \" GridServiceProvider.open \" + ncfile . getLocation ( ) + \" took \" + ( System . currentTimeMillis ( ) - start ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the index and create the netCDF file from that [CODESPLIT] protected void open ( GridIndex index , CancelTask cancelTask ) throws IOException { McIDASLookup lookup = new McIDASLookup ( ( McIDASGridRecord ) index . getGridRecords ( ) . get ( 0 ) ) ; GridIndexToNC delegate = new GridIndexToNC ( index . filename ) ; //delegate.setUseDescriptionForVariableName(false); delegate . open ( index , lookup , 4 , ncfile , cancelTask ) ; ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sync and extend [CODESPLIT] public boolean sync ( ) { try { if ( ! mcGridReader . init ( ) ) { return false ; } GridIndex index = mcGridReader . getGridIndex ( ) ; // reconstruct the ncfile objects ncfile . empty ( ) ; open ( index , null ) ; return true ; } catch ( IOException ioe ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private . use Array . factory () [CODESPLIT] static ArrayShort factory ( Index index , boolean isUnsigned ) { return ArrayShort . factory ( index , isUnsigned , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { short [ ] ja = ( short [ ] ) javaArray ; for ( short aJa : ja ) iter . setShortNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy to javaArray from storage using the iterator : used by copyToNDJavaArray ; [CODESPLIT] protected void copyTo1DJavaArray ( IndexIterator iter , Object javaArray ) { short [ ] ja = ( short [ ] ) javaArray ; for ( int i = 0 ; i < ja . length ; i ++ ) ja [ i ] = iter . getShortNext ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private : mostly for iterators [CODESPLIT] public double getDouble ( int index ) { short val = storage [ index ] ; return ( double ) ( isUnsigned ( ) ? DataType . unsignedShortToInt ( val ) : val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Sends a OPeNDAP DAP2 error to the client . [CODESPLIT] public void dap2ExceptionHandler ( DAP2Exception de , HttpServletResponse response ) { log . info ( \"DODSServlet.dodsExceptionHandler (\" + de . getErrorCode ( ) + \") \" + de . getErrorMessage ( ) ) ; if ( Debug . isSet ( \"showException\" ) ) { de . print ( System . err ) ; de . printStackTrace ( System . err ) ; printDODSException ( de ) ; } try { BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; response . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // This should probably be set to \"plain\" but this works, the // C++ slients don't barf as they would if I sent \"plain\" AND // the C++ don't expect compressed data if I do this... response . setHeader ( \"Content-Encoding\" , \"\" ) ; de . print ( eOut ) ; } catch ( IOException ioe ) { log . error ( \"Cannot respond to client! IO Error: \" + ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Sends an error to the client . [CODESPLIT] public void anyExceptionHandler ( Throwable e , ReqState rs ) { log . error ( \"DODServlet ERROR (anyExceptionHandler): \" + e ) ; printThrowable ( e ) ; try { if ( rs == null ) throw new DAP2Exception ( \"anyExceptionHandler: no request state provided\" ) ; log . error ( rs . toString ( ) ) ; HttpServletResponse response = rs . getResponse ( ) ; log . error ( rs . toString ( ) ) ; if ( track ) { RequestDebug reqD = ( RequestDebug ) rs . getUserObject ( ) ; log . error ( \"  request number: \" + reqD . reqno + \" thread: \" + reqD . threadDesc ) ; } response . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // This should probably be set to \"plain\" but this works, the // C++ slients don't barf as they would if I sent \"plain\" AND // the C++ don't expect compressed data if I do this... response . setHeader ( \"Content-Encoding\" , \"\" ) ; // Strip any double quotes out of the parser error message. // These get stuck in auto-magically by the javacc generated parser // code and they break our error parser (bummer!) String msg = e . getMessage ( ) ; if ( msg != null ) msg = msg . replace ( ' ' , ' ' ) ; DAP2Exception de2 = new DAP2Exception ( opendap . dap . DAP2Exception . UNDEFINED_ERROR , msg ) ; BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; de2 . print ( eOut ) ; } catch ( Exception ioe ) { log . error ( \"Cannot respond to client! IO Error: \" + ioe . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Sends a OPeNDAP DAP2 error ( type UNKNOWN ERROR ) to the client and displays a message on the server console . [CODESPLIT] public void sendDODSError ( HttpServletRequest request , HttpServletResponse response , String clientMsg , String serverMsg ) throws IOException , ServletException { response . setContentType ( \"text/plain\" ) ; response . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; response . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // Commented because of a bug in the OPeNDAP C++ stuff... //response.setHeader(\"Content-Encoding\", \"none\"); ServletOutputStream Out = response . getOutputStream ( ) ; DAP2Exception de = new DAP2Exception ( opendap . dap . DAP2Exception . UNKNOWN_ERROR , clientMsg ) ; de . print ( Out ) ; response . setStatus ( HttpServletResponse . SC_OK ) ; log . error ( serverMsg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for the client s DAS request . Operates on the assumption that the DAS information is cached on a disk local to the server . If you don t like that then you better override it in your server : ) <p / > <p > Once the DAS has been parsed it is sent to the requesting client . [CODESPLIT] public void doGetDAS ( ReqState rs ) throws Exception { if ( Debug . isSet ( \"showResponse\" ) ) { log . debug ( \"doGetDAS for dataset: \" + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; rs . getResponse ( ) . setContentType ( \"text/plain\" ) ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-das\" ) ; // Commented because of a bug in the OPeNDAP C++ stuff... //rs.getResponse().setHeader(\"Content-Encoding\", \"plain\"); OutputStream Out = new BufferedOutputStream ( rs . getResponse ( ) . getOutputStream ( ) ) ; DAS myDAS = ds . getDAS ( ) ; myDAS . print ( Out ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; if ( Debug . isSet ( \"showResponse\" ) ) { //log.debug(\"DAS=\\n\"); //myDAS.print(LogStream.out); } } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed if ( ds != null ) ds . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Sends an html document to the client explaining that they have used a poorly formed URL and then the help page ... [CODESPLIT] public void badURL ( ReqState rs ) throws Exception { if ( Debug . isSet ( \"showResponse\" ) ) { log . debug ( \"Sending Bad URL Page.\" ) ; } //log.info(\"DODSServlet.badURL \" + rs.getRequest().getRequestURI()); rs . getResponse ( ) . setContentType ( \"text/html\" ) ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-error\" ) ; // Commented because of a bug in the OPeNDAP C++ stuff... //rs.getResponse().setHeader(\"Content-Encoding\", \"plain\"); PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; printBadURLPage ( pw ) ; printHelpPage ( pw ) ; pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for OPeNDAP ascii data requests . Returns the request data as a comma delimited ascii file . Note that this means that the more complex OPeNDAP structures such as Grids get flattened ... <p / > <p / > Modified 2 / 8 / 07 jcaron to not make a DConnect2 call to itself [CODESPLIT] public void doGetASC ( ReqState rs ) throws Exception { if ( Debug . isSet ( \"showResponse\" ) ) { log . debug ( \"doGetASC For: \" + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/plain\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods-ascii\" ) ; if ( debug ) log . debug ( \"Sending OPeNDAP ASCII Data For: \" + rs + \"  CE: '\" + rs . getConstraintExpression ( ) + \"'\" ) ; ServerDDS dds = ds . getDDS ( ) ; //dds = url.getData(ce, null, new asciiFactory());  previous way // Instantiate the CEEvaluator and parse the constraint expression CEEvaluator ce = new CEEvaluator ( dds ) ; // i think this makes the dds constrained ce . parseConstraint ( rs ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; dds . printConstrained ( pw ) ; pw . println ( \"---------------------------------------------\" ) ; AsciiWriter writer = new AsciiWriter ( ) ; // could be static writer . toASCII ( pw , dds , ds ) ; // the way that getDAP2Data works // DataOutputStream sink = new DataOutputStream(bOut); // ce.send(myDDS.getName(), sink, ds); pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed if ( ds != null ) ds . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for debug requests ; [CODESPLIT] public void doDebug ( ReqState rs ) throws IOException { rs . getResponse ( ) . setHeader ( \"XDODS-Server\" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( \"text/html\" ) ; rs . getResponse ( ) . setHeader ( \"Content-Description\" , \"dods_debug\" ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; pw . println ( \"<title>Debugging</title>\" ) ; pw . println ( \"<body><pre>\" ) ; StringTokenizer tz = new StringTokenizer ( rs . getConstraintExpression ( ) , \"=;\" ) ; while ( tz . hasMoreTokens ( ) ) { String cmd = tz . nextToken ( ) ; pw . println ( \"Cmd= \" + cmd ) ; if ( cmd . equals ( \"help\" ) ) { pw . println ( \" help;log;logEnd;logShow\" ) ; pw . println ( \" showFlags;showInitParameters;showRequest\" ) ; pw . println ( \" on|off=(flagName)\" ) ; doDebugCmd ( cmd , tz , pw ) ; // for subclasses } else if ( cmd . equals ( \"on\" ) ) Debug . set ( tz . nextToken ( ) , true ) ; else if ( cmd . equals ( \"off\" ) ) Debug . set ( tz . nextToken ( ) , false ) ; else if ( cmd . equals ( \"showFlags\" ) ) { Iterator iter = Debug . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String key = ( String ) iter . next ( ) ; pw . println ( \"  \" + key + \" \" + Debug . isSet ( key ) ) ; } } else if ( cmd . equals ( \"showInitParameters\" ) ) pw . println ( rs . toString ( ) ) ; else if ( cmd . equals ( \"showRequest\" ) ) probeRequest ( pw , rs ) ; else if ( ! doDebugCmd ( cmd , tz , pw ) ) { // for subclasses pw . println ( \"  unrecognized command\" ) ; } } pw . println ( \"--------------------------------------\" ) ; pw . println ( \"Logging is on\" ) ; Iterator iter = Debug . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String key = ( String ) iter . next ( ) ; boolean val = Debug . isSet ( key ) ; if ( val ) pw . println ( \"  \" + key + \" \" + Debug . isSet ( key ) ) ; } pw . println ( \"</pre></body>\" ) ; pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ This is a bit of instrumentation that I kept around to let me look at the state of the incoming <code > HttpServletRequest< / code > from the client . This method calls the <code > get * < / code > methods of the request and prints the results to standard out . [CODESPLIT] public void probeRequest ( PrintWriter ps , ReqState rs ) { Enumeration e ; int i ; ps . println ( \"####################### PROBE ##################################\" ) ; ps . println ( \"The HttpServletRequest object is actually a: \" + rs . getRequest ( ) . getClass ( ) . getName ( ) ) ; ps . println ( \"\" ) ; ps . println ( \"HttpServletRequest Interface:\" ) ; ps . println ( \"    getAuthType:           \" + rs . getRequest ( ) . getAuthType ( ) ) ; ps . println ( \"    getMethod:             \" + rs . getRequest ( ) . getMethod ( ) ) ; ps . println ( \"    getPathInfo:           \" + rs . getRequest ( ) . getPathInfo ( ) ) ; ps . println ( \"    getPathTranslated:     \" + rs . getRequest ( ) . getPathTranslated ( ) ) ; ps . println ( \"    getRequestURL:         \" + rs . getRequest ( ) . getRequestURL ( ) ) ; ps . println ( \"    getQueryString:        \" + rs . getRequest ( ) . getQueryString ( ) ) ; ps . println ( \"    getRemoteUser:         \" + rs . getRequest ( ) . getRemoteUser ( ) ) ; ps . println ( \"    getRequestedSessionId: \" + rs . getRequest ( ) . getRequestedSessionId ( ) ) ; ps . println ( \"    getRequestURI:         \" + rs . getRequest ( ) . getRequestURI ( ) ) ; ps . println ( \"    getServletPath:        \" + rs . getRequest ( ) . getServletPath ( ) ) ; ps . println ( \"    isRequestedSessionIdFromCookie: \" + rs . getRequest ( ) . isRequestedSessionIdFromCookie ( ) ) ; ps . println ( \"    isRequestedSessionIdValid:      \" + rs . getRequest ( ) . isRequestedSessionIdValid ( ) ) ; ps . println ( \"    isRequestedSessionIdFromURL:    \" + rs . getRequest ( ) . isRequestedSessionIdFromURL ( ) ) ; ps . println ( \"\" ) ; i = 0 ; e = rs . getRequest ( ) . getHeaderNames ( ) ; ps . println ( \"    Header Names:\" ) ; while ( e . hasMoreElements ( ) ) { i ++ ; String s = ( String ) e . nextElement ( ) ; ps . print ( \"        Header[\" + i + \"]: \" + s ) ; ps . println ( \": \" + rs . getRequest ( ) . getHeader ( s ) ) ; } ps . println ( \"\" ) ; ps . println ( \"ServletRequest Interface:\" ) ; ps . println ( \"    getCharacterEncoding:  \" + rs . getRequest ( ) . getCharacterEncoding ( ) ) ; ps . println ( \"    getContentType:        \" + rs . getRequest ( ) . getContentType ( ) ) ; ps . println ( \"    getContentLength:      \" + rs . getRequest ( ) . getContentLength ( ) ) ; ps . println ( \"    getProtocol:           \" + rs . getRequest ( ) . getProtocol ( ) ) ; ps . println ( \"    getScheme:             \" + rs . getRequest ( ) . getScheme ( ) ) ; ps . println ( \"    getServerName:         \" + rs . getRequest ( ) . getServerName ( ) ) ; ps . println ( \"    getServerPort:         \" + rs . getRequest ( ) . getServerPort ( ) ) ; ps . println ( \"    getRemoteAddr:         \" + rs . getRequest ( ) . getRemoteAddr ( ) ) ; ps . println ( \"    getRemoteHost:         \" + rs . getRequest ( ) . getRemoteHost ( ) ) ; //ps.println(\"    getRealPath:           \"+rs.getRequest().getRealPath()); ps . println ( \".............................\" ) ; ps . println ( \"\" ) ; i = 0 ; e = rs . getRequest ( ) . getAttributeNames ( ) ; ps . println ( \"    Attribute Names:\" ) ; while ( e . hasMoreElements ( ) ) { i ++ ; String s = ( String ) e . nextElement ( ) ; ps . print ( \"        Attribute[\" + i + \"]: \" + s ) ; ps . println ( \" Type: \" + rs . getRequest ( ) . getAttribute ( s ) ) ; } ps . println ( \".............................\" ) ; ps . println ( \"\" ) ; i = 0 ; e = rs . getRequest ( ) . getParameterNames ( ) ; ps . println ( \"    Parameter Names:\" ) ; while ( e . hasMoreElements ( ) ) { i ++ ; String s = ( String ) e . nextElement ( ) ; ps . print ( \"        Parameter[\" + i + \"]: \" + s ) ; ps . println ( \" Value: \" + rs . getRequest ( ) . getParameter ( s ) ) ; } ps . println ( \"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\" ) ; ps . println ( \" . . . . . . . . . Servlet Infomation API  . . . . . . . . . . . . . .\" ) ; ps . println ( \"\" ) ; ps . println ( \"Servlet Context:\" ) ; ps . println ( \"\" ) ; /* i = 0;\n    e = servletContext.getAttributeNames();\n    ps.println(\"    Attribute Names:\");\n    while (e.hasMoreElements()) {\n      i++;\n      String s = (String) e.nextElement();\n      ps.print(\"        Attribute[\" + i + \"]: \" + s);\n      ps.println(\" Type: \" + servletContext.getAttribute(s));\n    }\n\n    ps.println(\"    ServletContext.getRealPath(\\\".\\\"): \" + servletContext.getRealPath(\".\"));\n    ps.println(\"    ServletContext.getMajorVersion(): \" + servletContext.getMajorVersion());\n//        ps.println(\"ServletContext.getMimeType():     \" + sc.getMimeType());\n    ps.println(\"    ServletContext.getMinorVersion(): \" + servletContext.getMinorVersion());\n//        ps.println(\"ServletContext.getRealPath(): \" + sc.getRealPath()); */ ps . println ( \".............................\" ) ; ps . println ( \"Servlet Config:\" ) ; ps . println ( \"\" ) ; ServletConfig scnfg = getServletConfig ( ) ; i = 0 ; e = scnfg . getInitParameterNames ( ) ; ps . println ( \"    InitParameters:\" ) ; while ( e . hasMoreElements ( ) ) { String p = ( String ) e . nextElement ( ) ; ps . print ( \"        InitParameter[\" + i + \"]: \" + p ) ; ps . println ( \" Value: \" + scnfg . getInitParameter ( p ) ) ; i ++ ; } ps . println ( \"\" ) ; ps . println ( \"######################## END PROBE ###############################\" ) ; ps . println ( \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Prints the OPeNDAP Server help page to the passed PrintWriter [CODESPLIT] private void printHelpPage ( PrintWriter pw ) { pw . println ( \"<h3>OPeNDAP Server Help</h3>\" ) ; pw . println ( \"To access most of the features of this OPeNDAP server, append\" ) ; pw . println ( \"one of the following a eight suffixes to a URL: .das, .dds, .dods, .ddx, .blob, .info,\" ) ; pw . println ( \".ver or .help. Using these suffixes, you can ask this server for:\" ) ; pw . println ( \"<dl>\" ) ; pw . println ( \"<dt> das  </dt> <dd> Dataset Attribute Structure (DAS)</dd>\" ) ; pw . println ( \"<dt> dds  </dt> <dd> Dataset Descriptor Structure (DDS)</dd>\" ) ; pw . println ( \"<dt> dods </dt> <dd> DataDDS object (A constrained DDS populated with data)</dd>\" ) ; pw . println ( \"<dt> ddx  </dt> <dd> XML version of the DDS/DAS</dd>\" ) ; pw . println ( \"<dt> blob </dt> <dd> Serialized binary data content for requested data set, \" + \"with the constraint expression applied.</dd>\" ) ; pw . println ( \"<dt> info </dt> <dd> info object (attributes, types and other information)</dd>\" ) ; pw . println ( \"<dt> html </dt> <dd> html form for this dataset</dd>\" ) ; pw . println ( \"<dt> ver  </dt> <dd> return the version number of the server</dd>\" ) ; pw . println ( \"<dt> help </dt> <dd> help information (this text)</dd>\" ) ; pw . println ( \"</dl>\" ) ; pw . println ( \"For example, to request the DAS object from the FNOC1 dataset at URI/GSO (a\" ) ; pw . println ( \"test dataset) you would appand `.das' to the URL:\" ) ; pw . println ( \"http://opendap.gso.url.edu/cgi-bin/nph-nc/data/fnoc1.nc.das.\" ) ; pw . println ( \"<p><b>Note</b>: Many OPeNDAP clients supply these extensions for you so you don't\" ) ; pw . println ( \"need to append them (for example when using interfaces supplied by us or\" ) ; pw . println ( \"software re-linked with a OPeNDAP client-library). Generally, you only need to\" ) ; pw . println ( \"add these if you are typing a URL directly into a WWW browser.\" ) ; pw . println ( \"<p><b>Note</b>: If you would like version information for this server but\" ) ; pw . println ( \"don't know a specific data file or data set name, use `/version' for the\" ) ; pw . println ( \"filename. For example: http://opendap.gso.url.edu/cgi-bin/nph-nc/version will\" ) ; pw . println ( \"return the version number for the netCDF server used in the first example. \" ) ; pw . println ( \"<p><b>Suggestion</b>: If you're typing this URL into a WWW browser and\" ) ; pw . println ( \"would like information about the dataset, use the `.info' extension.\" ) ; pw . println ( \"<p>If you'd like to see a data values, use the `.html' extension and submit a\" ) ; pw . println ( \"query using the customized form.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the variable s declaration in XML . This function is used to create the XML representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printXML ( PrintWriter pw , String pad , boolean constrained ) { // BEWARE! Since printXML()is (multiple) overloaded in BaseType // and all of the different signatures of printXML() in BaseType // lead to one signature, we must be careful to override that // SAME signature here. That way all calls to printDecl() for // this object lead to this implementation. // Also, since printXML()is (multiple) overloaded in BaseType // and all of the different signatures of printXML() in BaseType // lead to the signature we are overriding here, we MUST call // the printXML with the SAME signature THROUGH the super class // reference (assuming we want the super class functionality). If // we do otherwise, we will create an infinte call loop. OOPS! // System.out.println(\"SDString.printXML(pw,pad,\"+constrained+\")  Project: \"+Project); if ( constrained && ! isProject ( ) ) return ; super . printXML ( pw , pad , constrained ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the latitude values for the given type . [CODESPLIT] public static double [ ] getGaussianLatitudes ( String type , int start , int num ) throws IllegalArgumentException { double [ ] baseArray = null ; start -- ; // it's one based if ( type . equalsIgnoreCase ( GAUST62 ) ) { baseArray = gltst62 ; } else if ( type . equalsIgnoreCase ( GAUSR15 ) ) { baseArray = glts15 ; } else if ( type . equalsIgnoreCase ( GAUSR20 ) ) { baseArray = glts20 ; } else if ( type . equalsIgnoreCase ( GAUSR30 ) ) { baseArray = glts30 ; } else if ( type . equalsIgnoreCase ( GAUSR40 ) ) { baseArray = glats ; } else { throw new IllegalArgumentException ( \"Unsupported type: \" + type ) ; } if ( start + num > baseArray . length ) { throw new IllegalArgumentException ( \"Maximum \" + baseArray . length + \" latitudes exceeded\" ) ; } double [ ] retVals = new double [ num ] ; for ( int i = 0 ; i < num ; i ++ ) { retVals [ i ] = baseArray [ start + i ] ; } return retVals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the long resulting from reversing 8 bytes at a specified offset in a byte array . [CODESPLIT] static public long swapLong ( byte [ ] b , int offset ) { // 8 bytes long accum = 0 ; long shiftedval ; for ( int shiftBy = 0 , i = offset ; shiftBy < 64 ; shiftBy += 8 , i ++ ) { shiftedval = ( ( long ) ( b [ i ] & 0xff ) ) << shiftBy ; accum |= shiftedval ; } return accum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the float resulting from reversing 4 bytes at a specified offset in a byte array . [CODESPLIT] static public float swapFloat ( byte [ ] b , int offset ) { int accum = 0 ; for ( int shiftBy = 0 , i = offset ; shiftBy < 32 ; shiftBy += 8 , i ++ ) accum |= ( [ i ] & 0xff ) << shiftBy ; return Float . intBitsToFloat ( accum ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the char resulting from swapping 2 bytes at a specified offset in a byte array . [CODESPLIT] static public char swapChar ( byte [ ] b , int offset ) { // 2 bytes int low = b [ offset ] & 0xff ; int high = b [ offset + 1 ] & 0xff ; return ( char ) ( high << 8 | low ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The attribute coordinates is an alias for _CoordinateAxes . [CODESPLIT] protected void findCoordinateAxes ( NetcdfDataset ds ) { // coordinates is an alias for _CoordinateAxes\r for ( VarProcess vp : varList ) { if ( vp . coordAxes == null ) { // dont override if already set\r String coordsString = ds . findAttValueIgnoreCase ( vp . v , CF . COORDINATES , null ) ; if ( coordsString != null ) { vp . coordinates = coordsString ; } } } super . findCoordinateAxes ( ds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Parameter to a CoordinateTransform . The variable attribute points to a another variable that has the data in it . Make sure that atrribute and variable exist . Id readData is true read the data and use it as the value of the parameter otherwise use the name as the value of the parameter . [CODESPLIT] protected boolean addParameter2 ( CoordinateTransform rs , String paramName , NetcdfFile ds , AttributeContainer v , String attName , boolean readData ) { String varName ; if ( null == ( varName = v . findAttValueIgnoreCase ( attName , null ) ) ) { parseInfo . format ( \"CSMConvention No Attribute named %s%n\" , attName ) ; return false ; } varName = varName . trim ( ) ; Variable dataVar ; if ( null == ( dataVar = ds . findVariable ( varName ) ) ) { parseInfo . format ( \"CSMConvention No Variable named %s%n\" , varName ) ; return false ; } if ( readData ) { Array data ; try { data = dataVar . read ( ) ; } catch ( IOException e ) { parseInfo . format ( \"CSMConvention failed on read of %s err= %s%n\" , varName , e . getMessage ( ) ) ; return false ; } double [ ] vals = ( double [ ] ) data . get1DJavaArray ( DataType . DOUBLE ) ; rs . addParameter ( new Parameter ( paramName , vals ) ) ; } else rs . addParameter ( new Parameter ( paramName , varName ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the Variable with the specified ( short ) name in this group . [CODESPLIT] public Variable findVariable ( String varShortName ) { if ( varShortName == null ) return null ; for ( Variable v : variables ) { if ( varShortName . equals ( v . getShortName ( ) ) ) return v ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the Variable with the specified ( short ) name in this group or a parent group . [CODESPLIT] public Variable findVariableOrInParent ( String varShortName ) { if ( varShortName == null ) return null ; Variable v = findVariable ( varShortName ) ; Group parent = getParentGroup ( ) ; if ( ( v == null ) && ( parent != null ) ) v = parent . findVariableOrInParent ( varShortName ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the Group with the specified ( short ) name . [CODESPLIT] public Group findGroup ( String groupShortName ) { if ( groupShortName == null ) return null ; // groupShortName = NetcdfFile.makeNameUnescaped(groupShortName); for ( Group group : groups ) { if ( groupShortName . equals ( group . getShortName ( ) ) ) return group ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve a Dimension using its ( short ) name . If it doesnt exist in this group recursively look in parent groups . [CODESPLIT] public Dimension findDimension ( String name ) { if ( name == null ) return null ; // name = NetcdfFile.makeNameUnescaped(name); Dimension d = findDimensionLocal ( name ) ; if ( d != null ) return d ; Group parent = getParentGroup ( ) ; if ( parent != null ) return parent . findDimension ( name ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve a Dimension using its ( short ) name in this group only [CODESPLIT] public Dimension findDimensionLocal ( String name ) { if ( name == null ) return null ; // name =  NetcdfFile.makeNameUnescaped(name); for ( Dimension d : dimensions ) { if ( name . equals ( d . getShortName ( ) ) ) return d ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "AttributeHelper [CODESPLIT] public java . util . List < Attribute > getAttributes ( ) { return attributes . filter ( attributes , Attribute . SPECIALS ) . getAttributes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an Enumeration Typedef using its ( short ) name . If it doesnt exist in this group recursively look in parent groups . [CODESPLIT] public EnumTypedef findEnumeration ( String name ) { if ( name == null ) return null ; // name =  NetcdfFile.makeNameUnescaped(name); for ( EnumTypedef d : enumTypedefs ) { if ( name . equals ( d . getShortName ( ) ) ) return d ; } Group parent = getParentGroup ( ) ; if ( parent != null ) return parent . findEnumeration ( name ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the common parent of this and the other group . Cant fail since the root group is always a parent of any 2 groups . [CODESPLIT] public Group commonParent ( Group other ) { if ( isParent ( other ) ) return this ; if ( other . isParent ( this ) ) return other ; while ( ! other . isParent ( this ) ) other = other . getParentGroup ( ) ; return other ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a parent of the other Group? [CODESPLIT] public boolean isParent ( Group other ) { while ( ( other != this ) && ( other . getParentGroup ( ) != null ) ) other = other . getParentGroup ( ) ; return ( other == this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get String with name and attributes . Used in short descriptions like tooltips . [CODESPLIT] public String getNameAndAttributes ( ) { StringBuilder sbuff = new StringBuilder ( ) ; sbuff . append ( \"Group \" ) ; sbuff . append ( getShortName ( ) ) ; sbuff . append ( \"\\n\" ) ; for ( Attribute att : attributes . getAttributes ( ) ) { sbuff . append ( \"  \" ) . append ( getShortName ( ) ) . append ( \":\" ) ; sbuff . append ( att . toString ( ) ) ; sbuff . append ( \";\" ) ; sbuff . append ( \"\\n\" ) ; } return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Group s parent Group [CODESPLIT] public void setParentGroup ( Group parent ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; super . setParentGroup ( parent == null ? ncfile . getRootGroup ( ) : parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified shared dimension to this group . [CODESPLIT] public void addDimension ( Dimension dim ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( ! dim . isShared ( ) ) { throw new IllegalArgumentException ( \"Dimensions added to a group must be shared.\" ) ; } if ( findDimensionLocal ( dim . getShortName ( ) ) != null ) throw new IllegalArgumentException ( \"Dimension name (\" + dim . getShortName ( ) + \") must be unique within Group \" + getShortName ( ) ) ; dimensions . add ( dim ) ; dim . setGroup ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified shared dimension to this group but only if another dimension with the same name doesn t already exist . [CODESPLIT] public boolean addDimensionIfNotExists ( Dimension dim ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( ! dim . isShared ( ) ) { throw new IllegalArgumentException ( \"Dimensions added to a group must be shared.\" ) ; } if ( findDimensionLocal ( dim . getShortName ( ) ) != null ) return false ; dimensions . add ( dim ) ; dim . setGroup ( this ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a nested Group [CODESPLIT] public void addGroup ( Group g ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( findGroup ( g . getShortName ( ) ) != null ) throw new IllegalArgumentException ( \"Group name (\" + g . getShortName ( ) + \") must be unique within Group \" + getShortName ( ) ) ; groups . add ( g ) ; g . setParentGroup ( this ) ; // groups are a tree - only one parent }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an Enumeration [CODESPLIT] public void addEnumeration ( EnumTypedef e ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( e == null ) return ; e . setParentGroup ( this ) ; enumTypedefs . add ( e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Variable [CODESPLIT] public void addVariable ( Variable v ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( v == null ) return ; if ( findVariable ( v . getShortName ( ) ) != null ) { //Variable other = findVariable(v.getShortName()); // debug throw new IllegalArgumentException ( \"Variable name (\" + v . getShortName ( ) + \") must be unique within Group \" + getShortName ( ) ) ; } variables . add ( v ) ; v . setParentGroup ( this ) ; // variable can only be in one group }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an Dimension : uses the dimension hashCode to find it . [CODESPLIT] public boolean remove ( Dimension d ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; return d != null && dimensions . remove ( d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an Attribute : uses the Group hashCode to find it . [CODESPLIT] public boolean remove ( Group g ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; return g != null && groups . remove ( g ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a Variable : uses the variable hashCode to find it . [CODESPLIT] public boolean remove ( Variable v ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; return v != null && variables . remove ( v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove a Dimension using its name in this group only [CODESPLIT] public boolean removeDimension ( String dimName ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; for ( int i = 0 ; i < dimensions . size ( ) ; i ++ ) { Dimension d = dimensions . get ( i ) ; if ( dimName . equals ( d . getShortName ( ) ) ) { dimensions . remove ( d ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove a Variable using its ( short ) name in this group only [CODESPLIT] public boolean removeVariable ( String shortName ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; for ( int i = 0 ; i < variables . size ( ) ; i ++ ) { Variable v = variables . get ( i ) ; if ( shortName . equals ( v . getShortName ( ) ) ) { variables . remove ( v ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make this immutable . [CODESPLIT] public Group setImmutable ( ) { super . setImmutable ( ) ; variables = Collections . unmodifiableList ( variables ) ; dimensions = Collections . unmodifiableList ( dimensions ) ; groups = Collections . unmodifiableList ( groups ) ; attributes . setImmutable ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create groups to ensure path is defined [CODESPLIT] public Group makeRelativeGroup ( NetcdfFile ncf , String path , boolean ignorelast ) { path = path . trim ( ) ; path = path . replace ( \"//\" , \"/\" ) ; boolean isabsolute = ( path . charAt ( 0 ) == ' ' ) ; if ( isabsolute ) path = path . substring ( 1 ) ; // iteratively create path String pieces [ ] = path . split ( \"/\" ) ; if ( ignorelast ) pieces [ pieces . length - 1 ] = null ; Group current = ( isabsolute ? ncfile . getRootGroup ( ) : this ) ; for ( String name : pieces ) { if ( name == null ) continue ; String clearname = NetcdfFile . makeNameUnescaped ( name ) ; //?? Group next = current . findGroup ( clearname ) ; if ( next == null ) { next = new Group ( ncf , current , clearname ) ; current . addGroup ( next ) ; } current = next ; } return current ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a DAS object from the collection of <code > BaseType< / code > variables and their associated <code > Attributes< / code > . This DAS is correctly formed ( vis - a - vis the DAP specification ) for this DDS . [CODESPLIT] public DAS getDAS ( ) throws DASException { DAS myDAS = new DAS ( ) ; try { // Since the DDS can contain Attributes, in addtion to Attribute containers (AttributeTables) // at the top (dataset) level and the DAS cannot, it is required that these Attributes be // bundled into a container at the top level of the DAS. // In the code that follows this container is called \"looseEnds\" // Make the container. AttributeTable looseEnds = new AttributeTable ( getLooseEndsTableName ( ) ) ; // Carfully populate it from the one at our top-level. Since we are using the // API and also copying containers here in order to build a new version, // we must use a clone of this (the DDS's) AttributeTable. AttributeTable atTbl = ( AttributeTable ) getAttributeTable ( ) . clone ( ) ; int countLooseAttributes = 0 ; // Work on each Attribute in the container. Enumeration e = atTbl . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = atTbl . getAttribute ( aName ) ; String clearname = a . getClearName ( ) ; if ( a . isAlias ( ) ) { // copy an alias. String attribute = ( ( Alias ) a ) . getAliasedToAttributeFieldAsClearString ( ) ; looseEnds . addAlias ( clearname , convertDDSAliasFieldsToDASAliasFields ( attribute ) ) ; countLooseAttributes ++ ; } else if ( a . isContainer ( ) ) { // A reference copy. This is why we are working with a clone. myDAS . addAttributeTable ( clearname , a . getContainer ( ) ) ; } else { // copy an Attribute and it's values... int type = a . getType ( ) ; Enumeration vals = a . getValues ( ) ; while ( vals . hasMoreElements ( ) ) { String value = ( String ) vals . nextElement ( ) ; looseEnds . appendAttribute ( clearname , type , value , true ) ; } countLooseAttributes ++ ; } } if ( _Debug ) { DAPNode . log . debug ( \"Found \" + countLooseAttributes + \" top level Attributes.\" ) ; } //if (_Debug) myDAS.print(LogStream.dbg); // Only add this AttributeTable if actually contains Attributes! if ( countLooseAttributes > 0 ) { if ( _Debug ) DAPNode . log . debug ( \"Creating looseEnds table: \" + looseEnds . getEncodedName ( ) ) ; myDAS . addAttributeTable ( looseEnds . getEncodedName ( ) , looseEnds ) ; } // Walk through the variables at the top level. e = getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; // Build the correct AttributeTable for it at the Toplevel of the DAS buildDASAttributeTable ( bt , myDAS ) ; } //if (_Debug) myDAS.print(LogStream.dbg); // Make sure that the Aliases resolve correctly. Since we are moving from a // DDS/DDX space to a DFAS space the Aliases may not be resolvable. In that // case an exception will get thrown... myDAS . resolveAliases ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new DASException ( opendap . dap . DAP2Exception . UNKNOWN_ERROR , \"Could not create a DAS from this DDX object.\\n\" + \"Because of the structural differences between the DDX and the DAS it is \" + \"possible for the DDX to contain sets of Attributes that cannot be represented \" + \"in a DAS object.\\n\" + \"The specific problem was an execption of type \" + e . getClass ( ) . getName ( ) + \" with an \" + \"error message of: \\n\" + e . getMessage ( ) ) ; } return ( myDAS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method just makes sure that the attribute field in each Aliases resolves correctly if there ends up being a looseEnds Attribute Table at the top level . [CODESPLIT] private String convertDDSAliasFieldsToDASAliasFields ( String attribute ) throws MalformedAliasException { String prefix = \"\" ; Vector aNames = tokenizeAliasField ( attribute ) ; // We know that the first token should be a dot, we look at the // second token to see if it references a variable in the DDS. String topName = ( String ) aNames . get ( 1 ) ; boolean foundIt = false ; Enumeration e = getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; String normName = normalize ( bt . getEncodedName ( ) ) ; if ( topName . equals ( normName ) ) foundIt = true ; } if ( ! foundIt ) { // The Attribute referenced is at the top level of the DDS itself. // The Attributes at the top level of the DDS get repackaged into // a special AttributeTable, this makes the Aliases that point to // any of these Attribute resolve correctly. prefix = \".\" + getLooseEndsTableName ( ) ; } return ( prefix + attribute ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make A helper function for <code > getLooseEndsTableName< / code > insures that there are no naming conflicts when creating a looseEnds <code > AttributeTable< / code > [CODESPLIT] private String checkLooseEndsTableNameConflict ( String clearname , int attempt ) { Enumeration e = getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; String btName = bt . getEncodedName ( ) ; //LogStream.out.println(\"bt: '\"+btName+\"'  dataset: '\"+name+\"'\"); if ( btName . equals ( clearname ) ) { clearname = repairLooseEndsTableConflict ( clearname , attempt ++ ) ; clearname = checkLooseEndsTableNameConflict ( clearname , attempt ) ; } } AttributeTable at = getAttributeTable ( ) ; e = at . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; if ( aName . equals ( clearname ) ) { clearname = repairLooseEndsTableConflict ( clearname , attempt ++ ) ; clearname = checkLooseEndsTableNameConflict ( clearname , attempt ) ; } } return ( clearname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A helper function for <code > checkLooseEndsTableNameConflict< / code > insures that there are no naming conflicts when creating a looseEnds <code > AttributeTable< / code > [CODESPLIT] private String repairLooseEndsTableConflict ( String badName , int attempt ) { DAPNode . log . debug ( \"Repairing toplevel attribute table name conflict. Attempt: \" + attempt ) ; String name = \"\" ; switch ( attempt ) { case 0 : name = badName + \"_DatasetAttributes_0\" ; break ; default : int last_ = badName . lastIndexOf ( \"_\" ) ; name = badName . substring ( 0 , last_ ) + \"_\" + attempt ; break ; } return ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds AttributeTables ( from BaseType variables ) for us in a DAS created by getDAS () [CODESPLIT] private void buildDASAttributeTable ( BaseType bt , AttributeTable atbl ) throws DASException { // Get this BaseType's AttributeTable. Since we are using the AttributeTable // interface to build the DAS (which will have a different structure than the // table we are getting anyway), we don't need a copy, only the reference. AttributeTable tBTAT = bt . getAttributeTable ( ) ; // if the table is empty, then do nothing if ( tBTAT == null || tBTAT . size ( ) == 0 ) return ; // Start a new (child) AttributeTable (using the name of the one we are // copying) in the (parent) AttributeTable we are working on. AttributeTable newAT = atbl . appendContainer ( tBTAT . getEncodedName ( ) ) ; if ( _Debug ) { DAPNode . log . debug ( \"newAT.getName(): \" + newAT . getEncodedName ( ) ) ; } // Get each Attribute in the AttributeTable that we are copying, // and then put it's values into our new AttributeTable; Enumeration e = tBTAT . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String attrName = ( String ) e . nextElement ( ) ; Attribute attr = tBTAT . getAttribute ( attrName ) ; populateAttributeTable ( newAT , attr ) ; } // If this BaseType is a \"container\" type (aka complex type, aka DConstructor) // Then we have to search it's children for Attributes and then  them // and put them in our new Attribute Table. if ( bt instanceof DConstructor ) { Enumeration v = ( ( DConstructor ) bt ) . getVariables ( ) ; while ( v . hasMoreElements ( ) ) { BaseType thisBT = ( BaseType ) v . nextElement ( ) ; buildDASAttributeTable ( thisBT , newAT ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds AttributeTables ( from BaseType variables ) for us in a DAS created by getDAS () [CODESPLIT] private void populateAttributeTable ( AttributeTable atTable , Attribute attr ) throws DASException { // Always check for Aliases first! They return the values for their targets // when asked if they are containers! if ( attr . isAlias ( ) ) { String alias = attr . getEncodedName ( ) ; String attribute = ( ( Alias ) attr ) . getAliasedToAttributeFieldAsClearString ( ) ; if ( _Debug ) DAPNode . log . debug ( \"Adding Alias name: \" + alias ) ; atTable . addAlias ( alias , convertDDSAliasFieldsToDASAliasFields ( attribute ) ) ; } else if ( attr . isContainer ( ) ) { // If this Attribute is a container of other Attributes (an AttributeTable) // then we need to recurse to get it's children. // Get this Attribute's container (AttributeTable). // Since we are using the AttributeTable // interface to build the DAS (which will have a different structure than the // table we are getting anyway), we don't need a copy, only the reference. AttributeTable thisTable = attr . getContainer ( ) ; // Start a new (child) AttributeTable (using the name of the one we are // copying) in the (parent) AttributeTable we are working on. if ( _Debug ) DAPNode . log . debug ( \"Appending AttributeTable name: \" + thisTable . getEncodedName ( ) ) ; AttributeTable newTable = atTable . appendContainer ( thisTable . getEncodedName ( ) ) ; // Get each Attribute in the AttributeTable that we are copying, // and then put it's values into our new AttributeTable; Enumeration e = thisTable . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String attrName = ( String ) e . nextElement ( ) ; Attribute thisAttr = thisTable . getAttribute ( attrName ) ; populateAttributeTable ( newTable , thisAttr ) ; } } else { // Since the Attribute is a \"leaf\" and not a container we need to // push it's contents into the AttributeTable that we are building. int type = attr . getType ( ) ; String name = attr . getEncodedName ( ) ; Enumeration v = attr . getValues ( ) ; while ( v . hasMoreElements ( ) ) { String value = ( String ) v . nextElement ( ) ; if ( _Debug ) DAPNode . log . debug ( \"AtributeTable: \" + atTable . getEncodedName ( ) + \" Appending Attribute name: \" + name + \"  type: \" + type + \" value: \" + value ) ; atTable . appendAttribute ( name , type , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a DAS constructed from this DDS and it s BaseType variables . [CODESPLIT] public void printDAS ( PrintWriter pw ) { DAS myDAS = null ; try { myDAS = this . getDAS ( ) ; myDAS . print ( pw ) ; } catch ( DASException dasE ) { pw . println ( \"\\n\\nCould not get a DAS object to print!\\n\" + \"DDS.getDAS() threw an Exception. Message: \\n\" + dasE . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a variable from the <code > DDS< / code > . Does nothing if the variable can t be found . If there are multiple variables with the same name only the first will be removed . To detect this call the <code > checkSemantics< / code > method to verify that each variable has a unique name . [CODESPLIT] public void delVariable ( String name ) { try { BaseType bt = getVariable ( name ) ; vars . removeElement ( bt ) ; } catch ( NoSuchVariableException e ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is the variable <code > var< / code > a vector of DConstructors? Return true if it is false otherwise . This mess will recurse into a DVector s template BaseType ( which is a BaseTypePrimivitiveVector ) and look to see if that is either a DConstructor or <em > contains< / em > a DConstructor . So the <code > List Strucutre { ... } g [ 10 ] ; < / code > should be handled correctly . <p > <p / > Note that the List type modifier may only appear once . [CODESPLIT] private DConstructor isVectorOfDConstructor ( BaseType var ) { if ( ! ( var instanceof DVector ) ) return null ; if ( ! ( ( ( DVector ) var ) . getPrimitiveVector ( ) instanceof BaseTypePrimitiveVector ) ) return null ; // OK. We have a DVector whose template is a BaseTypePrimitiveVector. BaseTypePrimitiveVector btpv = ( BaseTypePrimitiveVector ) ( ( DVector ) var ) . getPrimitiveVector ( ) ; // After that nasty cast, is the template a DConstructor? if ( btpv . getTemplate ( ) instanceof DConstructor ) return ( DConstructor ) btpv . getTemplate ( ) ; else return isVectorOfDConstructor ( btpv . getTemplate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a reference to the named variable . [CODESPLIT] public BaseType getVariable ( String name ) throws NoSuchVariableException { Stack s = new Stack ( ) ; s = search ( name , s ) ; return ( BaseType ) s . pop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look for <code > name< / code > in the DDS . Start the search using the ctor variable ( or array / list of ctors ) found on the top of the Stack <code > compStack< / code > ( for component stack ) . When the named variable is found return the stack compStack modified so that it now contains each ctor - type variable that on the path to the named variable . If the variable is not found after exhausting all possibilities throw NoSuchVariable . <p > <p / > Note : This method takes the stack as a parameter so that it can be used by a parser that is working through a list of identifiers that represents the path to a variable <em > as well as< / em > a shorthand notation for the identifier that is the equivalent to the leaf node name alone . In the form case the caller helps build the stack by repeatedly calling <code > search< / code > in the latter case this method must build the stack itself . This method is over kill for the first case . [CODESPLIT] public Stack search ( String name , Stack compStack ) throws NoSuchVariableException { DDSSearch ddsSearch = new DDSSearch ( compStack ) ; if ( ddsSearch . deepSearch ( name ) ) return ddsSearch . components ; else throw new NoSuchVariableException ( \"The variable `\" + name + \"' was not found in the dataset.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a <b > DDX< / b > from the named <code > InputStream< / code > . This method calls a generated parser to interpret an XML representation of a <code > DDS< / code > ( aka a <b > DDX< / b > ) and instantiate that <code > DDS< / code > in memory . This method does the following : <ul > <li > Gets a new <code > DDSXMLParser< / code > using the <code > BaseTypeFactory< / code > held in this ( the <code > DDS< / code > ) class . < / li > <li > Uses the <code > DDSXMLParser< / code > to parse the DDX waiting in the <code > InputStream< / code > <i > is< / i > . < / li > <li > Calls <code > DDS . checkForAttributeNameConflict () < / code > < / li > <li > Calls <code > DDS . resolveAliases () < / code > < / li > < / ul > <p / > The last two items should be called EVERY time a <code > DDS< / code > is populated with variables ( by a parser or through the <code > DDS< / code > API ) and prior to releasing it for use to any calling program . [CODESPLIT] public void parseXML ( InputStream is , boolean validation ) throws DAP2Exception { DDSXMLParser dp = new DDSXMLParser ( opendapNameSpace ) ; dp . parse ( is , this , factory , validation ) ; // Check for name conflicts. IN the XML representation // of the DDS it is syntactically possible for a // variable container (Dconstructor) to possess an // Attribute that has the same name as one of the container // variable's member variables. That's a NO-NO!. // Check for it here and throw a nice fat exception if we find it. checkForAttributeNameConflict ( ) ; // Resolve the aliases. Aliases are basically analagous // to softlinks in a UNIX filesystem. Since an alias // can point any Attribute in the dataset, the vailidity // of the alias cannot be checked until all of the // members of the Dataset (both variables and their // Attributes) have been built. Once that is done // we can check to make sure that every alias points // at a vaild Attribute (and not another alias, non-existent // Attribute, etc) resolveAliases ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a <b > DDX< / b > from the named <code > Document< / code > . This method calls a generated parser to interpret an XML representation of a <code > DDS< / code > ( aka a <b > DDX< / b > ) and instantiate that <code > DDS< / code > in memory . This method does the following : <ul > <li > Gets a new <code > DDSXMLParser< / code > using the <code > BaseTypeFactory< / code > held in this ( the <code > DDS< / code > ) class . < / li > <li > Uses the <code > DDSXMLParser< / code > to parse the DDX waiting in the <code > InputStream< / code > <i > is< / i > . < / li > <li > Calls <code > DDS . checkForAttributeNameConflict () < / code > < / li > <li > Calls <code > DDS . resolveAliases () < / code > < / li > < / ul > <p / > <p / > The last two items should be called EVERY time a <code > DDS< / code > is populated with variables ( by a parser or through the <code > DDS< / code > API ) and prior to releasing it for use to any calling program . [CODESPLIT] public void parseXML ( Document ddxDoc , boolean validation ) throws DAP2Exception { DDSXMLParser dp = new DDSXMLParser ( opendapNameSpace ) ; dp . parse ( ddxDoc , this , factory , validation ) ; // Check for name conflicts. IN the XML representation // of the DDS it is syntactically possible for a // variable container (Dconstructor) to possess an // Attribute that has the same name as one of the container // variable's member variables. That's a NO-NO!. // Check for it here and throw a nice fat exception if we find it. checkForAttributeNameConflict ( ) ; // Resolve the aliases. Aliases are basically analagous // to softlinks in a UNIX filesystem. Since an alias // can point any Attribute in the dataset, the vailidity // of the alias cannot be checked until all of the // members of the Dataset (both variables and their // Attributes) have been built. Once that is done // we can check to make sure that every alias points // at a vaild Attribute (and not another alias, non-existent // Attribute, etc) resolveAliases ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the semantics of the <code > DDS< / code > . If <code > all< / code > is true check not only the semantics of the <code > DDS< / code > itself but also recursively check all variables in the dataset . [CODESPLIT] public void checkSemantics ( boolean all ) throws BadSemanticsException { if ( getEncodedName ( ) == null ) { DAPNode . log . error ( \"A dataset must have a name\" ) ; throw new BadSemanticsException ( \"DDS.checkSemantics(): A dataset must have a name\" ) ; } Util . uniqueNames ( vars , getEncodedName ( ) , \"Dataset\" ) ; if ( all ) { for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . checkSemantics ( true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the <code > DDS< / code > on the given <code > PrintWriter< / code > . [CODESPLIT] public void print ( PrintWriter os ) { os . println ( \"Dataset {\" ) ; for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . printDecl ( os ) ; } os . print ( \"} \" ) ; if ( getEncodedName ( ) != null ) os . print ( getEncodedName ( ) ) ; os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Before the DDS can be used all of the Aliases in the various AttributeTables must be resolved . This means that it is necessary to verify that each Alias references an Attribute that exists and is not another Alias . This is accomplished by searching the DDS s variable s attribute holdings for Aliases Everytime an Alias is located a new search begins to find the Attribute that the Alias is attempting to reference . <p / > This method recursively searchs through the passed <code > BaseType< / code > parameter bt for Alias members of AttributeTables and when they are found attempts to resolve them to a specific Attribute . <p / > This method gets called at the top level at the parser ONLY after the entire DDS has been parsed and built . It s intial invocation get passed the DDS ( which is in fact a <code > BaseType< / code > ) <p / > <p / > This method manipulates the global variable <code > currentBT< / code > . [CODESPLIT] private void resolveAliases ( BaseType bt ) throws MalformedAliasException , UnresolvedAliasException , NoSuchAttributeException { // cache the current/parent BaseType (a container) BaseType cacheBT = currentBT ; try { // Make the one we are about to search the current one. currentBT = bt ; // Make the current AttributeTable null to indicate that we are at the top // AttributeTable of a new current BaseType. currentAT = null ; if ( Debug . isSet ( \"DDS.resolveAliases\" ) ) DAPNode . log . debug ( \"Searching for Aliases in the Attributes of Variable: \" + bt . getEncodedName ( ) ) ; // Process the Attributes of this BaseType. resolveAliases ( bt . getAttributeTable ( ) ) ; // Now if this current BaseType is a container type, then we better // search and resolve Aliases in it's children. if ( bt instanceof DConstructor ) { if ( Debug . isSet ( \"DDS.resolveAliases\" ) ) DAPNode . log . debug ( \"Searching for Aliases in the children of Variable: \" + bt . getEncodedName ( ) ) ; Enumeration bte = ( ( DConstructor ) bt ) . getVariables ( ) ; while ( bte . hasMoreElements ( ) ) { BaseType thisBT = ( BaseType ) bte . nextElement ( ) ; // Recursive call... resolveAliases ( thisBT ) ; } } } finally { // Restore the previous current BaseType state. currentBT = cacheBT ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method recursively searchs through the passed <code > AttributeTable< / code > parameter at for Alias members . When an Alias is found the method attempts to resolve it to a specific Attribute . <p / > This method is invoked by <code > resolveAliases ( BaseType bt ) < / code > and is used to search for Aliases in AttributeTables found in a BaseTypes Attributes . <p / > This method manipulates the global variable <code > currentBT< / code > . [CODESPLIT] private void resolveAliases ( AttributeTable at ) throws MalformedAliasException , UnresolvedAliasException , NoSuchAttributeException { // Cache the current (parent) Attribute table. This value is // null if this method is call from resolveAliases(BasetType bt) AttributeTable cacheAT = currentAT ; try { // Set the current AttributeTable to the one that we are searching. currentAT = at ; //getall of the Attributes from the table. Enumeration aNames = currentAT . getNames ( ) ; while ( aNames . hasMoreElements ( ) ) { String aName = ( String ) aNames . nextElement ( ) ; opendap . dap . Attribute thisA = currentAT . getAttribute ( aName ) ; if ( thisA . isAlias ( ) ) { //Is Alias? Resolve it! resolveAlias ( ( Alias ) thisA ) ; if ( Debug . isSet ( \"DDS.resolveAliases\" ) ) { DAPNode . log . debug ( \"Resolved Alias: '\" + thisA . getEncodedName ( ) + \"'\\n\" ) ; } } else if ( thisA . isContainer ( ) ) { //Is AttributeTable (container)? Search it! resolveAliases ( thisA . getContainer ( ) ) ; } } } finally { // Restore the previous currentAT state. currentAT = cacheAT ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method attempts to resolve the past Alias to a specific Attribute in the DDS . It does this by : <ul > <li > 1 ) Tokenizing the Alias s attribute field ( see <code > Alias< / code > ) < / li > <li > 2 ) Evaluating the tokenized field to locate the longest possible variable name represented as a consecutive set of tokens < / li > <li > 2 ) Evaluating the the remaining tokenized field to locate the Attribute that this Alias is attempting to reference< / li > <li > 4 ) Setting the Aliases internal references for it s Variable and it s Attribute . < / ul > <p / > If an Attribute matching the definition of the Alias cannot be located an Exception is thrown [CODESPLIT] private void resolveAlias ( Alias alias ) throws MalformedAliasException , UnresolvedAliasException { //Get the crucial stuff out of the Alias String name = alias . getEncodedName ( ) ; String attribute = alias . getAliasedToAttributeFieldAsClearString ( ) ; if ( Debug . isSet ( \"DDS.resolveAliases\" ) ) { DAPNode . log . debug ( \"\\n\\nFound: Alias \" + name + \"  \" + attribute ) ; } // The Attribute field MAY NOT be empty. if ( attribute . equals ( \"\" ) ) { throw new MalformedAliasException ( \"The attribute 'attribute' in the Alias \" + \"element (name: '\" + name + \"') must have a value other than an empty string.\" ) ; } if ( Debug . isSet ( \"DDS.resolveAliases\" ) ) { DAPNode . log . debug ( \"Attribute: `\" + attribute + \"'\" ) ; } // Tokenize the attribute field. Vector aNames = tokenizeAliasField ( attribute ) ; if ( Debug . isSet ( \"DDS.resolveAliases\" ) ) { DAPNode . log . debug ( \"Attribute name tokenized to \" + aNames . size ( ) + \" elements\" ) ; Enumeration e = aNames . elements ( ) ; while ( e . hasMoreElements ( ) ) { String aname = ( String ) e . nextElement ( ) ; DAPNode . log . debug ( \"name: \" + aname ) ; } } // The variable reference is the first part of the attribute field. // Let's go find it... BaseType targetBT = null ; // Absolute paths for attributes names must start with the dot character. boolean isAbsolutePath = aNames . get ( 0 ) . equals ( \".\" ) ; if ( ! isAbsolutePath ) { //Is it not an absolute path? throw new MalformedAliasException ( \"In the Alias '\" + name + \"'\" + \" the value of the attribute 'attribute' does not begin with the character dot (.). \" + \"The value of the 'attribute' field must always be an absolute path name from the \" + \"top level of the variable reference, and thus must always begin with the dot (.) character.\" ) ; } if ( aNames . size ( ) == 1 ) { // Is it only a dot? throw new MalformedAliasException ( \"In the Alias '\" + name + \"'\" + \" the value of the attribute 'attribute' contains only the character dot (.). \" + \"The value of the 'attribute' field must always reference an Attribute using an absolute path name from the \" + \"top level of the DAS, and must reference an attribute within the DAS. A simple dot is not allowed.\" ) ; } aNames . remove ( 0 ) ; // Remove the first token, which by now we know is a single dot. targetBT = getDeepestMatchingVariable ( this , aNames ) ; if ( targetBT == null ) { // No matching BaseType? // Then assume the attribute field references a // top (Dataset) level Attribute. targetBT = this ; } //LogStream.out.println(\"Alias references variable:\t.\"+targetBT.getLongName()); // Now that we have found a target BaseType variable that matches the reference in // the variable field of the Alias (b.t.w. that's a good thing) let's go // see if we can find an Attribute within that targetBT that matches the attribute field // in the Alias decleration. Attribute targetAT = null ; if ( aNames . size ( ) == 0 ) { // If there are no remaining tokens in the attribute field then // we are referencing the attribute container of the targetBT. targetAT = targetBT . getAttribute ( ) ; } else { // Go try to find the Attribute in the targetBT. targetAT = getAttribute ( targetBT . getAttributeTable ( ) , aNames ) ; } alias . setMyVariable ( targetBT ) ; alias . setMyAttribute ( targetAT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method executes a ( recursive ) search of the <code > DConstructor< / code > parameter <b > dcBT< / b > for a <code > BaseType< / code > variable whose name resolves to the vector of names contained in the <code > Vector< / code > parameter <b > vNames< / b > . A variable is considered a match if each of it s node names in the hierarchy of containers in the one passed as parameter <b > dcBT< / b > matches ( equals ) the corresponding name in the Vector <b > vNames< / b > . [CODESPLIT] private BaseType getDeepestMatchingVariable ( DConstructor dcBT , Vector vNames ) { // Get the first name from the Vector String vName = ( String ) vNames . get ( 0 ) ; // Get all of the child variables from the Dconstructor Enumeration bte = dcBT . getVariables ( ) ; while ( bte . hasMoreElements ( ) ) { // Get this variable BaseType bt = ( BaseType ) bte . nextElement ( ) ; // Get and normalize it's name. String normName = normalize ( bt . getClearName ( ) ) ; // Compare the names if ( normName . equals ( vName ) ) { // They match! // Remove the name from the vector. vNames . remove ( 0 ) ; if ( vNames . size ( ) == 0 ) { // are there more names? // Nope! We Found it! return bt ; } if ( bt instanceof DConstructor ) { // If there are more names then this thing better be a container // recursively search it for the remaining names... BaseType nextBT = getDeepestMatchingVariable ( ( DConstructor ) bt , vNames ) ; if ( nextBT != null ) return ( nextBT ) ; return ( bt ) ; } return ( bt ) ; } } return ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The <code > normalize< / code > method is used to normalize variable and attribute name strings prior to their comparison with the normalized tokens extracted from the variable and name fields in an Alias declaration . <p / > The rule for this normalization is as follows : <p / > <ul > <li > The &quot ; ( double quote ) and the \\ ( backslash aka escape ) characters MUST be escaped ( using the \\ character ) in the <b > variable< / b > and <b > attribute< / b > fields . < / li > < / ul > [CODESPLIT] public static String normalize ( String field ) { boolean Debug = false ; StringBuffer sb = new StringBuffer ( field ) ; for ( int offset = 0 ; offset < sb . length ( ) ; offset ++ ) { char c = sb . charAt ( offset ) ; // for every quote and slach in the string, add a slash in front of it. if ( c == slash || c == quote ) { sb . insert ( offset , slash ) ; offset ++ ; } } //Coverity[DEADCODE] if ( Debug ) { DAPNode . log . debug ( \"String: `\" + field + \"` normalized to: `\" + sb + \"`\" ) ; } return ( sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The <code > tokenizeAliasFiled () < / code > method is used to tokenize the <b > variable< / b > and the <b > attribute< / b > fields in the alias declaration . It is required that these fields be <b > normalized< / b > in the XML instance document . The rules for this normalization are as follows : <ul > <p / > <li > The &quot ; ( double quote ) and the \\ ( backslash aka escape ) characters MUST be escaped ( using the \\ character ) in the <b > variable< / b > and <b > attribute< / b > fields . < / li > <p / > <li > The <b > variable< / b > and <b > attribute< / b > fields must be enclosed in double quotes if their values contain the dot ( . ) character . < / li > <p / > <li > Fully qualified <b > variable< / b > and <b > attribute< / b > names always begin with the dot ( . ) character . < / li > < / ul > [CODESPLIT] public static Vector tokenizeAliasField ( String field ) throws MalformedAliasException { boolean Debug = false ; // find the index of the last element in the field. int lastIndex = field . length ( ) - 1 ; // make a place to put the tokens. Vector tokens = new Vector ( ) ; //Coverity[DEADCODE] if ( Debug ) { DAPNode . log . debug ( \"lastIndexOf(dot): \" + field . lastIndexOf ( dot ) + \"   lastIndex: \" + lastIndex ) ; } // Does this thing start with a quote? if ( field . charAt ( 0 ) == quote ) { // find the closing quote. // Because this token starts with a quote, it must be normalized // (see method description). The closing quote must exist, // and it cannont be escaped. // The first character in the token is the one following the // leadin quote. int start = 1 ; // prepare to search for a closing quote. int end = - 1 ; boolean done = false ; boolean escaped = false ; // search for the quote for ( int i = 1 ; i <= lastIndex || ! done ; i ++ ) { char c = field . charAt ( i ) ; //LogStream.out.println(\"Checking for clear quote on char: \"+c+\" escaped=\"+escaped+\"  done=\"+done); // Was this character escaped (with a slash)? if ( escaped ) { // then ignore it and unset the escaped flag // since the escape has been consumed. escaped = false ; } else { // otherwise, is it an escape (slash) character if ( c == slash ) { // the set the escaoed flag to true. escaped = true ; } else if ( c == quote ) { // if it's not an escape (slash) then is it a quote? //LogStream.out.println(\"Found quote!\"); end = i ; done = true ; } } } //LogStream.out.println(\"start=\"+start+\"  end=\"+end+\"  lastIndex=\"+lastIndex); // if the end is less than 0 then it didn't get set // during the search for the quote, and thus the closing quote wasn't // found. Throw an exception! if ( end < 0 ) throw new MalformedAliasException ( \"Alias fields that begin with the quote (\\\") sign \" + \"must have a closing quote.\" ) ; // If there is more stuff, and that stuff is not seperated from the // closing quote by a dot character, then it's bad syntax. if ( lastIndex > end && field . charAt ( end + 1 ) != dot ) throw new MalformedAliasException ( \"Alias fields must be seperated by the dot (.) character.\" ) ; // The last caharcter in the field may not be an (unquoted) dot. if ( field . charAt ( lastIndex ) == dot ) throw new MalformedAliasException ( \"Alias fields may not end with the dot (.) character.\" ) ; // Looks like we found a complete token. // Get it. String firstToken = field . substring ( start , end ) ; // Add it to the tokens Vector. tokens . add ( firstToken ) ; // if there is more stuff, then tokenize it. if ( end < lastIndex ) { // get the rest of the stuff String theRest = field . substring ( end + 2 ) ; // tokenize it and add each of the returned tokens to // this tokens Vector. // Recursive call. Enumeration tkns = tokenizeAliasField ( theRest ) . elements ( ) ; while ( tkns . hasMoreElements ( ) ) tokens . add ( tkns . nextElement ( ) ) ; } return ( tokens ) ; } // Find the first dot. This simplistic search is appropriate because // if this field contained a dot as part of it's name it should have // been encased in quotes and handled by the previous logic. int firstDot = field . indexOf ( dot ) ; if ( firstDot == 0 ) { // Does this thing start with dot? // Then it must be an absolute path. // NOTE: This should be true ONLY for the first token // in the list. By that I mean that a leading dot in // the field string should only occur when the // variable or alias field begins a dot. A secondary // token may only start with a dot if the dot is // actually part of the field, and thus it should be // encased in quotes. String thisToken = \".\" ; tokens . add ( thisToken ) ; // Check to see if there are more characters in the field to be tokenized. // If there are, tokenize them. if ( lastIndex > 0 ) { String theRest = field . substring ( 1 ) ; // Recursive call Enumeration tkns = tokenizeAliasField ( theRest ) . elements ( ) ; // Take the tokens from the rest of the fields and // add them to this token vector. while ( tkns . hasMoreElements ( ) ) tokens . add ( tkns . nextElement ( ) ) ; } return ( tokens ) ; } if ( firstDot > 0 ) { // A secondary token may only contain a dot if the dot is // actually part of the field, and thus the field should have been // encased in quotes. Since we already check for a leading quote, // the first dor MUST be the end of the token. String firstToken = field . substring ( 0 , firstDot ) ; tokens . add ( firstToken ) ; // A quick syntax check. if ( lastIndex == firstDot ) throw new MalformedAliasException ( \"Alias fields may not end with the dot (.) character.\" ) ; // Get the rest of the field string String theRest = field . substring ( firstDot + 1 ) ; // tokenize it, and add it's tokens to this token Vector. Enumeration tkns = tokenizeAliasField ( theRest ) . elements ( ) ; while ( tkns . hasMoreElements ( ) ) tokens . add ( tkns . nextElement ( ) ) ; return ( tokens ) ; } // This field string might be the final token, if we // get here it must be so add it to the tokens vector tokens . add ( field ) ; return ( tokens ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the peristent representation of the <code > DDS< / code > as an XML document . This XML document is know as a <b > DDX< / b > . The DDX can be parsed using the <code > DDSXMLParser< / code > [CODESPLIT] public void printXML ( PrintWriter pw , String pad , boolean constrained ) { pw . println ( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" ) ; pw . print ( \"<Dataset\" ) ; if ( getEncodedName ( ) != null ) pw . print ( \" name=\\\"\" + DDSXMLParser . normalizeToXML ( getEncodedName ( ) ) + \"\\\"\" ) ; pw . println ( ) ; pw . println ( \"xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"\" ) ; pw . println ( \"xmlns=\\\"\" + opendapNameSpace + \"\\\"\" ) ; pw . print ( \"xsi:schemaLocation=\\\"\" ) ; pw . print ( opendapNameSpace + \"  \" ) ; pw . print ( schemaLocation ) ; pw . println ( \"\\\" >\" ) ; pw . println ( \"\" ) ; Enumeration e = getAttributeNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = getAttribute ( aName ) ; if ( a != null ) a . printXML ( pw , pad + \"\\t\" , constrained ) ; } pw . println ( \"\" ) ; Enumeration ve = getVariables ( ) ; while ( ve . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) ve . nextElement ( ) ; bt . printXML ( pw , pad + \"\\t\" , constrained ) ; } pw . println ( \"\" ) ; if ( _dataBlobID != null ) { pw . println ( pad + \"\\t\" + \"<dataBLOB href=\\\"\" + DDSXMLParser . normalizeToXML ( _dataBlobID ) + \"\\\"/>\" ) ; } pw . println ( pad + \"</Dataset>\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes the passed parameter <code > das< / code > and attempts to incorporate it s contents into the Attributes of the DDS variables . If an <code > Attribute< / code > in the <code > DAS< / code > can t be associated with a variable in a logical manner then it is placed at the top level of the DDS . ( Basically it becomes a toplevel attribute in the dataset ) [CODESPLIT] public void ingestDAS ( DAS das ) { try { ingestAttributeTable ( das , this ) ; resolveAliases ( ) ; } catch ( DASException de ) { DAPNode . log . error ( \"DDS.ingestDAS(): \" + de . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A helper methods for ingestDAS () . [CODESPLIT] private void ingestAttribute ( Attribute a , BaseType bt ) throws DASException { if ( a . isAlias ( ) ) { // copy an alias. String name = a . getEncodedName ( ) ; String attribute = ( ( Alias ) a ) . getAliasedToAttributeFieldAsClearString ( ) ; bt . addAttributeAlias ( name , attribute ) ; } else if ( a . isContainer ( ) ) { AttributeTable at = a . getContainer ( ) ; ingestAttributeTable ( at , bt ) ; } else { // copy an Attribute and it's values... String name = a . getEncodedName ( ) ; int type = a . getType ( ) ; Enumeration vals = a . getValues ( ) ; while ( vals . hasMoreElements ( ) ) { String value = ( String ) vals . nextElement ( ) ; bt . appendAttribute ( name , type , value , true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A helper methods for ingestDAS () . [CODESPLIT] private void ingestAttributeTable ( AttributeTable at , DConstructor dc ) throws DASException { Enumeration ate = at . getNames ( ) ; while ( ate . hasMoreElements ( ) ) { String aName = ( String ) ate . nextElement ( ) ; Attribute a = at . getAttribute ( aName ) ; boolean foundIt = false ; Enumeration bte = dc . getVariables ( ) ; while ( bte . hasMoreElements ( ) ) { BaseType thisBT = ( BaseType ) bte . nextElement ( ) ; String bName = thisBT . getEncodedName ( ) ; if ( bName . equals ( aName ) ) { if ( a . isContainer ( ) && thisBT instanceof DConstructor ) { ingestAttributeTable ( a . getContainer ( ) , ( DConstructor ) thisBT ) ; } else { ingestAttribute ( a , thisBT ) ; } foundIt = true ; } } if ( ! foundIt ) { ingestAttribute ( a , dc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A helper methods for ingestDAS () . [CODESPLIT] private void ingestAttributeTable ( AttributeTable at , BaseType bt ) throws DASException { try { String atName = at . getEncodedName ( ) ; String bName = bt . getEncodedName ( ) ; //LogStream.out.println(\"ingestATTbl: atName:\"+atName+\" bName: \"+bName); if ( bName . equals ( atName ) ) { //LogStream.out.println(\"adding each attribute!\"); Enumeration e = at . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = at . getAttribute ( aName ) ; ingestAttribute ( a , bt ) ; } } else { //LogStream.out.println(\"addingcontainer!\"); bt . addAttributeContainer ( at ) ; } } catch ( AttributeExistsException ase ) { Enumeration e = at . getNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = at . getAttribute ( aName ) ; ingestAttribute ( a , bt ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for name conflicts . In the XML representation of the DDS it is syntactically possible for a variable container ( Dconstructor ) to possess an Attribute that has the same name as one of the container variable s member variables . That s a NO - NO! . Check for it here and throw a nice fat exception if we find it . [CODESPLIT] private void checkForAttributeNameConflict ( DConstructor dc ) throws BadSemanticsException { if ( _Debug ) { DAPNode . log . debug ( \"Checking \" + dc . getTypeName ( ) + \" \" + dc . getClearName ( ) + \" for name conflicts.\" ) ; } Enumeration bte = dc . getVariables ( ) ; while ( bte . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) bte . nextElement ( ) ; //LogStream.out.println(\"     member: \"+bt.getTypeName()+\" \"+bt.getName()); Enumeration ate = dc . getAttributeNames ( ) ; while ( ate . hasMoreElements ( ) ) { String aName = ( String ) ate . nextElement ( ) ; //LogStream.out.println(\"         attribute: \"+aName); if ( aName . equals ( bt . getEncodedName ( ) ) ) { throw new BadSemanticsException ( \"The variable '\" + dc . getLongName ( ) + \"' has an Attribute with the same name ('\" + aName + \"') as one of it's \" + \"member variables (\" + bt . getTypeName ( ) + \" \" + bt . getEncodedName ( ) + \")\\n\" + \"This is NOT allowed.\" ) ; } } if ( bt instanceof DConstructor ) { // LogStream.out.println(\"     member '\"+bt.getName()+\"' is a container. Better Check it!\"); // Recursive call!! checkForAttributeNameConflict ( ( DConstructor ) bt ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This a wrapper method for <code > DDS . print () < / code > . [CODESPLIT] public String getDDSText ( ) { StringWriter sw = new StringWriter ( ) ; this . print ( new PrintWriter ( sw ) ) ; return sw . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This a wrapper method for <code > DDS . printXML () < / code > . [CODESPLIT] public String getDDXText ( ) { StringWriter sw = new StringWriter ( ) ; this . printXML ( new PrintWriter ( sw ) ) ; return sw . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > DDS< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DDS d = ( DDS ) super . cloneDAG ( map ) ; d . vars = new Vector ( ) ; for ( int i = 0 ; i < vars . size ( ) ; i ++ ) { BaseType element = ( BaseType ) vars . elementAt ( i ) ; d . vars . addElement ( cloneDAG ( map , element ) ) ; } d . setEncodedName ( this . getEncodedName ( ) ) ; // Question: // What about copying the BaseTypeFactory? // Do we want a reference to the same one? Or another             // Is there a difference? Should we be building the clone // using \"new DDS(getFactory())\"?? // Answer: // Yes. Use the same type factory! d . factory = this . factory ; return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK what about extending an index ?? [CODESPLIT] public boolean makeIndex ( String filename , RandomAccessFile dataRaf ) throws IOException { String idxPath = filename ; if ( ! idxPath . endsWith ( GBX9_IDX ) ) idxPath += GBX9_IDX ; File idxFile = GribIndexCache . getFileOrCache ( idxPath ) ; File idxFileTmp = GribIndexCache . getFileOrCache ( idxPath + \".tmp\" ) ; boolean ok = false ; RandomAccessFile raf = null ; try ( FileOutputStream fout = new FileOutputStream ( idxFileTmp ) ) { //// header message\r fout . write ( MAGIC_START . getBytes ( CDM . utf8Charset ) ) ; NcStream . writeVInt ( fout , version ) ; Map < Long , Integer > gdsMap = new HashMap <> ( ) ; gdsList = new ArrayList <> ( ) ; records = new ArrayList <> ( 200 ) ; Grib2IndexProto . Grib2Index . Builder rootBuilder = Grib2IndexProto . Grib2Index . newBuilder ( ) ; rootBuilder . setFilename ( filename ) ; if ( dataRaf == null ) { raf = RandomAccessFile . acquire ( filename ) ; dataRaf = raf ; } Grib2RecordScanner scan = new Grib2RecordScanner ( dataRaf ) ; while ( scan . hasNext ( ) ) { Grib2Record r = scan . next ( ) ; if ( r == null ) break ; // done\r records . add ( r ) ; Grib2SectionGridDefinition gdss = r . getGDSsection ( ) ; Integer index = gdsMap . get ( gdss . calcCRC ( ) ) ; if ( index == null ) { gdsList . add ( gdss ) ; index = gdsList . size ( ) - 1 ; gdsMap . put ( gdss . calcCRC ( ) , index ) ; rootBuilder . addGdsList ( makeGdsProto ( gdss ) ) ; } rootBuilder . addRecords ( makeRecordProto ( r , index , r . getGDS ( ) . scanMode ) ) ; } if ( records . isEmpty ( ) ) throw new RuntimeException ( \"No GRIB2 records found in \" + dataRaf . getLocation ( ) ) ; Grib2IndexProto . Grib2Index index = rootBuilder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; NcStream . writeVInt ( fout , b . length ) ; // message size\r fout . write ( b ) ; // message  - all in one gulp\r logger . debug ( \"  made gbx9 index for {} size={}\" , filename , b . length ) ; ok = true ; return true ; } finally { if ( raf != null ) raf . close ( ) ; // only close if we opened it\r // now switch; fout has been closed\r if ( ok ) { RandomAccessFile . eject ( idxFile . getPath ( ) ) ; boolean deleteOk = ! idxFile . exists ( ) || idxFile . delete ( ) ; boolean renameOk = idxFileTmp . renameTo ( idxFile ) ; if ( ! deleteOk ) logger . error ( \"  could not delete Grib2Index= {}\" , idxFile . getPath ( ) ) ; if ( ! renameOk ) logger . error ( \"  could not rename Grib2Index= {}\" , idxFile . getPath ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message GribIdSection { required uint32 center_id = 1 ; required uint32 subcenter_id = 2 ; required uint32 master_table_version = 3 ; required uint32 local_table_version = 4 ; required uint32 significanceOfRT = 5 ; repeated uint32 refDate = 6 [ packed = true ] ; // year month day hour minute second ; required uint32 productionStatus = 7 ; required uint32 processedDataType = 8 ; } [CODESPLIT] private Grib2IndexProto . GribIdSection makeIdProto ( Grib2SectionIdentification id ) { Grib2IndexProto . GribIdSection . Builder b = Grib2IndexProto . GribIdSection . newBuilder ( ) ; b . setCenterId ( id . getCenter_id ( ) ) ; b . setSubcenterId ( id . getSubcenter_id ( ) ) ; b . setMasterTableVersion ( id . getMaster_table_version ( ) ) ; b . setLocalTableVersion ( id . getLocal_table_version ( ) ) ; b . setSignificanceOfRT ( id . getSignificanceOfRT ( ) ) ; b . addRefDate ( id . getYear ( ) ) ; b . addRefDate ( id . getMonth ( ) ) ; b . addRefDate ( id . getDay ( ) ) ; b . addRefDate ( id . getHour ( ) ) ; b . addRefDate ( id . getMinute ( ) ) ; b . addRefDate ( id . getSecond ( ) ) ; b . setProductionStatus ( id . getProductionStatus ( ) ) ; b . setProcessedDataType ( id . getTypeOfProcessedData ( ) ) ; return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write GridDatatype data to the geotiff file . [CODESPLIT] public void writeGrid ( GridDataset dataset , GridDatatype grid , Array data , boolean greyScale ) throws IOException { GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; if ( ! gcs . isRegularSpatial ( ) ) { throw new IllegalArgumentException ( \"Must have 1D x and y axes for \" + grid . getFullName ( ) ) ; } CoordinateAxis1D xaxis = ( CoordinateAxis1D ) gcs . getXHorizAxis ( ) ; CoordinateAxis1D yaxis = ( CoordinateAxis1D ) gcs . getYHorizAxis ( ) ; // units may need to be scaled to meters double scaler = ( xaxis . getUnitsString ( ) . equalsIgnoreCase ( \"km\" ) ) ? 1000.0 : 1.0 ; // data must go from top to bottom double xStart = xaxis . getCoordEdge ( 0 ) * scaler ; double yStart = yaxis . getCoordEdge ( 0 ) * scaler ; double xInc = xaxis . getIncrement ( ) * scaler ; double yInc = Math . abs ( yaxis . getIncrement ( ) ) * scaler ; if ( yaxis . getCoordValue ( 0 ) < yaxis . getCoordValue ( 1 ) ) { data = data . flip ( 0 ) ; yStart = yaxis . getCoordEdge ( ( int ) yaxis . getSize ( ) ) * scaler ; } if ( ! xaxis . isRegular ( ) || ! yaxis . isRegular ( ) ) { throw new IllegalArgumentException ( \"Must be evenly spaced grid = \" + grid . getFullName ( ) ) ; } if ( pageNumber > 1 ) { geotiff . initTags ( ) ; } // write it out writeGrid ( grid , data , greyScale , xStart , yStart , xInc , yInc , pageNumber ) ; pageNumber ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write Grid data to the geotiff file . Grid currently must : <ol > <li > have a 1D X and Y coordinate axes . <li > be lat / lon or Lambert Conformal Projection <li > be equally spaced < / ol > [CODESPLIT] protected void writeGrid ( GridDatatype grid , Array data , boolean greyScale , double xStart , double yStart , double xInc , double yInc , int imageNumber ) throws IOException { int nextStart = 0 ; GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; // get rid of this when all projections are implemented if ( ! gcs . isLatLon ( ) && ! ( gcs . getProjection ( ) instanceof LambertConformal ) && ! ( gcs . getProjection ( ) instanceof Stereographic ) && ! ( gcs . getProjection ( ) instanceof Mercator ) //  && !(gcs.getProjection() instanceof TransverseMercator)   LOOK broken ?? && ! ( gcs . getProjection ( ) instanceof AlbersEqualAreaEllipse ) && ! ( gcs . getProjection ( ) instanceof AlbersEqualArea ) ) { throw new IllegalArgumentException ( \"Unsupported projection = \" + gcs . getProjection ( ) . getClass ( ) . getName ( ) ) ; } // write the data first MAMath . MinMax dataMinMax = grid . getMinMaxSkipMissingData ( data ) ; if ( greyScale ) { ArrayByte result = replaceMissingValuesAndScale ( grid , data , dataMinMax ) ; nextStart = geotiff . writeData ( ( byte [ ] ) result . getStorage ( ) , imageNumber ) ; } else { ArrayFloat result = replaceMissingValues ( grid , data , dataMinMax ) ; nextStart = geotiff . writeData ( ( float [ ] ) result . getStorage ( ) , imageNumber ) ; } // set the width and the height int height = data . getShape ( ) [ 0 ] ; // Y int width = data . getShape ( ) [ 1 ] ; // X writeMetadata ( greyScale , xStart , yStart , xInc , yInc , height , width , imageNumber , nextStart , dataMinMax , gcs . getProjection ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace missing values with dataMinMax . min - 1 . 0 ; return a floating point data array . [CODESPLIT] private ArrayFloat replaceMissingValues ( IsMissingEvaluator grid , Array data , MAMath . MinMax dataMinMax ) { float minValue = ( float ) ( dataMinMax . min - 1.0 ) ; ArrayFloat floatArray = ( ArrayFloat ) Array . factory ( DataType . FLOAT , data . getShape ( ) ) ; IndexIterator dataIter = data . getIndexIterator ( ) ; IndexIterator floatIter = floatArray . getIndexIterator ( ) ; while ( dataIter . hasNext ( ) ) { float v = dataIter . getFloatNext ( ) ; if ( grid . isMissing ( ( double ) v ) ) { v = minValue ; } floatIter . setFloatNext ( v ) ; } return floatArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace missing values with 0 ; scale other values between 1 and 255 return a byte data array . [CODESPLIT] private ArrayByte replaceMissingValuesAndScale ( IsMissingEvaluator grid , Array data , MAMath . MinMax dataMinMax ) { double scale = 254.0 / ( dataMinMax . max - dataMinMax . min ) ; ArrayByte byteArray = ( ArrayByte ) Array . factory ( DataType . BYTE , data . getShape ( ) ) ; IndexIterator dataIter = data . getIndexIterator ( ) ; IndexIterator resultIter = byteArray . getIndexIterator ( ) ; byte bv ; while ( dataIter . hasNext ( ) ) { double v = dataIter . getDoubleNext ( ) ; if ( grid . isMissing ( v ) ) { bv = 0 ; } else { int iv = ( int ) ( ( v - dataMinMax . min ) * scale + 1 ) ; bv = ( byte ) ( iv & 0xff ) ; } resultIter . setByteNext ( bv ) ; } return byteArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK WTF ?? is this the seam crossing ?? [CODESPLIT] private double geoShiftGetXstart ( Array lon , double inc ) { Index ilon = lon . getIndex ( ) ; int [ ] lonShape = lon . getShape ( ) ; IndexIterator lonIter = lon . getIndexIterator ( ) ; double xlon = 0.0 ; LatLonPoint p0 = new LatLonPointImpl ( 0 , lon . getFloat ( ilon . set ( 0 ) ) ) ; LatLonPoint pN = new LatLonPointImpl ( 0 , lon . getFloat ( ilon . set ( lonShape [ 0 ] - 1 ) ) ) ; xlon = p0 . getLongitude ( ) ; while ( lonIter . hasNext ( ) ) { float l = lonIter . getFloatNext ( ) ; LatLonPoint pn = new LatLonPointImpl ( 0 , l ) ; if ( pn . getLongitude ( ) < xlon ) { xlon = pn . getLongitude ( ) ; } } if ( p0 . getLongitude ( ) == pN . getLongitude ( ) ) { xlon = xlon - inc ; } return xlon ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write GridCoverage data to the geotiff file . [CODESPLIT] public void writeGrid ( GeoReferencedArray array , boolean greyScale ) throws IOException { CoverageCoordSys gcs = array . getCoordSysForData ( ) ; if ( ! gcs . isRegularSpatial ( ) ) throw new IllegalArgumentException ( \"Must have 1D x and y axes for \" + array . getCoverageName ( ) ) ; Projection proj = gcs . getProjection ( ) ; CoverageCoordAxis1D xaxis = ( CoverageCoordAxis1D ) gcs . getXAxis ( ) ; CoverageCoordAxis1D yaxis = ( CoverageCoordAxis1D ) gcs . getYAxis ( ) ; // latlon coord does not need to be scaled double scaler = ( xaxis . getUnits ( ) . equalsIgnoreCase ( \"km\" ) ) ? 1000.0 : 1.0 ; // data must go from top to bottom double xStart = xaxis . getCoordEdge1 ( 0 ) * scaler ; double yStart = yaxis . getCoordEdge1 ( 0 ) * scaler ; double xInc = xaxis . getResolution ( ) * scaler ; double yInc = Math . abs ( yaxis . getResolution ( ) ) * scaler ; Array data = array . getData ( ) . reduce ( ) ; if ( yaxis . getCoordMidpoint ( 0 ) < yaxis . getCoordMidpoint ( 1 ) ) { data = data . flip ( 0 ) ; yStart = yaxis . getCoordEdgeLast ( ) ; } /*  remove - i think unneeded, monotonic lon handled in CoordinateAxis1D. JC 3/18/2013\n     if (gcs.isLatLon()) {\n      Array lon = xaxis.read();\n      data = geoShiftDataAtLon(data, lon);\n      xStart = geoShiftGetXstart(lon, xInc);\n      //xStart = -180.0;\n    }  */ if ( pageNumber > 1 ) { geotiff . initTags ( ) ; } // write the data first int nextStart = 0 ; MAMath . MinMax dataMinMax = MAMath . getMinMaxSkipMissingData ( data , array ) ; if ( greyScale ) { ArrayByte result = replaceMissingValuesAndScale ( array , data , dataMinMax ) ; nextStart = geotiff . writeData ( ( byte [ ] ) result . getStorage ( ) , pageNumber ) ; } else { ArrayFloat result = replaceMissingValues ( array , data , dataMinMax ) ; nextStart = geotiff . writeData ( ( float [ ] ) result . getStorage ( ) , pageNumber ) ; } // set the width and the height int height = data . getShape ( ) [ 0 ] ; // Y int width = data . getShape ( ) [ 1 ] ; // X writeMetadata ( greyScale , xStart , yStart , xInc , yInc , height , width , pageNumber , nextStart , dataMinMax , proj ) ; pageNumber ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for an aliased coord that may have multiple variables : dimName = alias1 alias2 ; Variable alias1 ( dim ) ; Variable alias2 ( dim ) ; [CODESPLIT] private List < Variable > searchAliasedDimension ( NetcdfDataset ds , Dimension dim ) { String dimName = dim . getShortName ( ) ; String alias = ds . findAttValueIgnoreCase ( null , dimName , null ) ; if ( alias == null ) return null ; List < Variable > vars = new ArrayList <> ( ) ; StringTokenizer parser = new StringTokenizer ( alias , \" ,\" ) ; while ( parser . hasMoreTokens ( ) ) { String token = parser . nextToken ( ) ; Variable ncvar = ds . findVariable ( token ) ; if ( ncvar == null ) continue ; if ( ncvar . getRank ( ) != 1 ) continue ; Iterator dimIter = ncvar . getDimensions ( ) . iterator ( ) ; Dimension dim2 = ( Dimension ) dimIter . next ( ) ; if ( dimName . equals ( dim2 . getShortName ( ) ) ) { vars . add ( ncvar ) ; if ( debug ) System . out . print ( \" \" + token ) ; } } if ( debug ) System . out . println ( ) ; return vars ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given the information on construction writes the necessary exception information . [CODESPLIT] public void write ( HttpServletResponse hsr ) throws IOException { PrintWriter xmlResponse = hsr . getWriter ( ) ; xmlResponse . append ( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" ) ; xmlResponse . append ( \"<ows:ExceptionReport xml:lang=\\\"en-US\\\" xsi:schemaLocation=\\\"http://www.opengis.net/ows/1.1\" + \" http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd\\\" version=\\\"2.0.0\\\" xmlns:ows=\\\"http://www.opengis.net/ows/1.1\\\"\" + \" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\" ) ; xmlResponse . append ( \"<ows:Exception \" ) ; if ( locator != null ) xmlResponse . append ( \"locator=\\\"\" + locator + \"\\\" \" ) ; xmlResponse . append ( \"exceptionCode=\\\"\" + ExceptionCode + \"\\\">\" ) ; xmlResponse . append ( \"<ows:ExceptionText>\" + text + \"</ows:ExceptionText>\" ) ; xmlResponse . append ( \"</ows:Exception>\" ) ; xmlResponse . append ( \"</ows:ExceptionReport>\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private . use Array . factory () [CODESPLIT] static ArrayInt factory ( Index index , boolean isUnsigned ) { return ArrayInt . factory ( index , isUnsigned , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * create new ArrayInt with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayInt factory ( Index index , boolean isUnsigned , int [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayInt . D0 ( index , isUnsigned , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayInt . D1 ( index , isUnsigned , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayInt . D2 ( index , isUnsigned , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayInt . D3 ( index , isUnsigned , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayInt . D4 ( index , isUnsigned , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayInt . D5 ( index , isUnsigned , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayInt . D6 ( index , isUnsigned , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayInt . D7 ( index , isUnsigned , storage ) ; } else { return new ArrayInt ( index , isUnsigned , storage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { int [ ] ja = ( int [ ] ) javaArray ; for ( int aJa : ja ) iter . setIntNext ( aJa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package private : mostly for iterators [CODESPLIT] public double getDouble ( int index ) { int val = storage [ index ] ; return ( double ) ( isUnsigned ( ) ? DataType . unsignedIntToLong ( val ) : val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Begin API Override [CODESPLIT] @ Override public synchronized String nc_inq_libvers ( ) { String ret ; try { ce ( ) ; ret = nc4 . nc_inq_libvers ( ) ; if ( TRACE ) trace ( ret , \"nc_inq_libvers\" , \"-\" ) ; } finally { cx ( ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "open GribCollectionImmutable from an existing index file . return null on failure [CODESPLIT] static GribCollectionImmutable acquireGribCollection ( FileFactory factory , Object hashKey , String location , int buffer_size , CancelTask cancelTask , Object spiObject ) throws IOException { FileCacheable result ; DatasetUrl durl = new DatasetUrl ( null , location ) ; if ( gribCollectionCache != null ) { // FileFactory factory, Object hashKey, String location, int buffer_size, CancelTask cancelTask, Object spiObject result = GribCdmIndex . gribCollectionCache . acquire ( factory , hashKey , durl , buffer_size , cancelTask , spiObject ) ; } else { // String location, int buffer_size, ucar.nc2.util.CancelTask cancelTask, Object iospMessage result = factory . open ( durl , buffer_size , cancelTask , spiObject ) ; } return ( GribCollectionImmutable ) result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public static File getTopIndexFileFromConfig ( FeatureCollectionConfig config ) { File indexFile = makeTopIndexFileFromConfig ( config ) ; return GribIndexCache . getExistingFileOrCache ( indexFile . getPath ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is only used for the top level GribCollection . [CODESPLIT] private static File makeTopIndexFileFromConfig ( FeatureCollectionConfig config ) { Formatter errlog = new Formatter ( ) ; CollectionSpecParser specp = config . getCollectionSpecParser ( errlog ) ; String name = StringUtil2 . replace ( config . collectionName , ' ' , \"/\" ) ; // String cname = DirectoryCollection.makeCollectionName(name, Paths.get(specp.getRootDir())); return makeIndexFile ( name , new File ( specp . getRootDir ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find out what kind of index this is [CODESPLIT] public static GribCollectionType getType ( RandomAccessFile raf ) throws IOException { String magic ; raf . seek ( 0 ) ; magic = raf . readString ( Grib2CollectionWriter . MAGIC_START . getBytes ( CDM . utf8Charset ) . length ) ; switch ( magic ) { case Grib2CollectionWriter . MAGIC_START : return GribCollectionType . GRIB2 ; case Grib1CollectionWriter . MAGIC_START : return GribCollectionType . GRIB1 ; case Grib2PartitionBuilder . MAGIC_START : return GribCollectionType . Partition2 ; case Grib1PartitionBuilder . MAGIC_START : return GribCollectionType . Partition1 ; } return GribCollectionType . none ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "open GribCollectionImmutable from an existing index file . return null on failure [CODESPLIT] @ Nullable public static GribCollectionImmutable openCdmIndex ( String indexFilename , FeatureCollectionConfig config , boolean useCache , Logger logger ) throws IOException { File indexFileInCache = useCache ? GribIndexCache . getExistingFileOrCache ( indexFilename ) : new File ( indexFilename ) ; if ( indexFileInCache == null ) return null ; String indexFilenameInCache = indexFileInCache . getPath ( ) ; String name = makeNameFromIndexFilename ( indexFilename ) ; GribCollectionImmutable result = null ; try ( RandomAccessFile raf = RandomAccessFile . acquire ( indexFilenameInCache ) ) { GribCollectionType type = getType ( raf ) ; switch ( type ) { case GRIB2 : result = Grib2CollectionBuilderFromIndex . readFromIndex ( name , raf , config , logger ) ; break ; case Partition2 : result = Grib2PartitionBuilderFromIndex . createTimePartitionFromIndex ( name , raf , config , logger ) ; break ; case GRIB1 : result = Grib1CollectionBuilderFromIndex . readFromIndex ( name , raf , config , logger ) ; break ; case Partition1 : result = Grib1PartitionBuilderFromIndex . createTimePartitionFromIndex ( name , raf , config , logger ) ; break ; default : logger . warn ( \"GribCdmIndex.openCdmIndex failed on {} type={}\" , indexFilenameInCache , type ) ; } } catch ( FileNotFoundException ioe ) { throw ioe ; } catch ( Throwable t ) { logger . warn ( \"GribCdmIndex.openCdmIndex failed on \" + indexFilenameInCache , t ) ; RandomAccessFile . eject ( indexFilenameInCache ) ; if ( ! indexFileInCache . delete ( ) ) logger . warn ( \"failed to delete {}\" , indexFileInCache . getPath ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "open GribCollectionImmutable from an existing index file . return null on failure [CODESPLIT] @ Nullable public static GribCollectionMutable openMutableGCFromIndex ( String indexFilename , FeatureCollectionConfig config , boolean dataOnly , boolean useCache , Logger logger ) { File indexFileInCache = useCache ? GribIndexCache . getExistingFileOrCache ( indexFilename ) : new File ( indexFilename ) ; if ( indexFileInCache == null ) { return null ; } String indexFilenameInCache = indexFileInCache . getPath ( ) ; String name = makeNameFromIndexFilename ( indexFilename ) ; GribCollectionMutable result = null ; try ( RandomAccessFile raf = RandomAccessFile . acquire ( indexFilenameInCache ) ) { GribCollectionType type = getType ( raf ) ; switch ( type ) { case GRIB2 : result = Grib2CollectionBuilderFromIndex . openMutableGCFromIndex ( name , raf , config , logger ) ; break ; case Partition2 : result = Grib2PartitionBuilderFromIndex . openMutablePCFromIndex ( name , raf , config , logger ) ; break ; case GRIB1 : result = Grib1CollectionBuilderFromIndex . openMutableGCFromIndex ( name , raf , config , logger ) ; break ; case Partition1 : result = Grib1PartitionBuilderFromIndex . openMutablePCFromIndex ( name , raf , config , logger ) ; break ; default : logger . warn ( \"GribCdmIndex.openMutableGCFromIndex failed on {} type={}\" , indexFilenameInCache , type ) ; } if ( result != null ) { result . lastModified = raf . getLastModified ( ) ; result . fileSize = raf . length ( ) ; } } catch ( Throwable t ) { logger . warn ( \"GribCdmIndex.openMutableGCFromIndex failed on \" + indexFilenameInCache , t ) ; } if ( result == null ) { RandomAccessFile . eject ( indexFilenameInCache ) ; if ( ! indexFileInCache . delete ( ) ) logger . warn ( \"failed to delete {}\" , indexFileInCache . getPath ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used ( only ) by GribCollectionBuilder [CODESPLIT] public static boolean updateGribCollectionFromPCollection ( boolean isGrib1 , PartitionManager dcm , CollectionUpdateType updateType , Formatter errlog , org . slf4j . Logger logger ) throws IOException { if ( updateType == CollectionUpdateType . never || dcm instanceof CollectionSingleIndexFile ) { // LOOK would isIndexFile() be better ? // then just open the existing index file return false ; } boolean changed = updatePartition ( isGrib1 , dcm , updateType , logger , errlog ) ; if ( errlog != null ) errlog . format ( \"PartitionCollection %s was recreated %s%n\" , dcm . getCollectionName ( ) , changed ) ; return changed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update Grib Collection if needed [CODESPLIT] public static boolean updateGribCollection ( FeatureCollectionConfig config , CollectionUpdateType updateType , Logger logger ) throws IOException { if ( logger == null ) logger = classLogger ; long start = System . currentTimeMillis ( ) ; Formatter errlog = new Formatter ( ) ; CollectionSpecParser specp = config . getCollectionSpecParser ( errlog ) ; Path rootPath = Paths . get ( specp . getRootDir ( ) ) ; boolean isGrib1 = config . type == FeatureCollectionType . GRIB1 ; boolean changed ; if ( config . ptype == FeatureCollectionConfig . PartitionType . none || config . ptype == FeatureCollectionConfig . PartitionType . all ) { try ( CollectionAbstract dcm = new CollectionPathMatcher ( config , specp , logger ) ) { changed = updateGribCollection ( isGrib1 , dcm , updateType , FeatureCollectionConfig . PartitionType . none , logger , errlog ) ; } } else if ( config . ptype == FeatureCollectionConfig . PartitionType . timePeriod ) { try ( TimePartition tp = new TimePartition ( config , specp , logger ) ) { changed = updateTimePartition ( isGrib1 , tp , updateType , logger ) ; } } else { // LOOK assume wantSubdirs makes it into a Partition. Isnt there something better ?? if ( specp . wantSubdirs ( ) ) { // its a partition try ( DirectoryPartition dpart = new DirectoryPartition ( config , rootPath , true , new GribCdmIndex ( logger ) , NCX_SUFFIX , logger ) ) { dpart . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , config ) ; changed = updateDirectoryCollectionRecurse ( isGrib1 , dpart , config , updateType , logger ) ; } } else { // otherwise its a leaf directory changed = updateLeafCollection ( isGrib1 , config , updateType , true , logger , rootPath ) ; } } long took = System . currentTimeMillis ( ) - start ; logger . info ( \"updateGribCollection {} changed {} took {} msecs\" , config . collectionName , changed , took ) ; return changed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return true if changed exception on failure [CODESPLIT] public static boolean updateGribCollection ( boolean isGrib1 , MCollection dcm , CollectionUpdateType updateType , FeatureCollectionConfig . PartitionType ptype , Logger logger , Formatter errlog ) throws IOException { logger . debug ( \"GribCdmIndex.updateGribCollection %s %s%n\" , dcm . getCollectionName ( ) , updateType ) ; if ( ! isUpdateNeeded ( dcm . getIndexFilename ( NCX_SUFFIX ) , updateType , ( isGrib1 ? GribCollectionType . GRIB1 : GribCollectionType . GRIB2 ) , logger ) ) return false ; boolean changed ; if ( isGrib1 ) { // existing case handles correctly - make seperate index for each runtime (OR) partition == runtime Grib1CollectionBuilder builder = new Grib1CollectionBuilder ( dcm . getCollectionName ( ) , dcm , logger ) ; changed = builder . updateNeeded ( updateType ) && builder . createIndex ( ptype , errlog ) ; } else { Grib2CollectionBuilder builder = new Grib2CollectionBuilder ( dcm . getCollectionName ( ) , dcm , logger ) ; changed = builder . updateNeeded ( updateType ) && builder . createIndex ( ptype , errlog ) ; } return changed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return true if changed exception on failure [CODESPLIT] private static boolean updatePartition ( boolean isGrib1 , PartitionManager dcm , CollectionUpdateType updateType , Logger logger , Formatter errlog ) throws IOException { boolean changed ; if ( isGrib1 ) { Grib1PartitionBuilder builder = new Grib1PartitionBuilder ( dcm . getCollectionName ( ) , new File ( dcm . getRoot ( ) ) , dcm , logger ) ; changed = builder . updateNeeded ( updateType ) && builder . createPartitionedIndex ( updateType , errlog ) ; } else { Grib2PartitionBuilder builder = new Grib2PartitionBuilder ( dcm . getCollectionName ( ) , new File ( dcm . getRoot ( ) ) , dcm , logger ) ; changed = builder . updateNeeded ( updateType ) && builder . createPartitionedIndex ( updateType , errlog ) ; } return changed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update all the gbx indices in one directory and the ncx index for that directory [CODESPLIT] private static boolean updateLeafCollection ( boolean isGrib1 , FeatureCollectionConfig config , CollectionUpdateType updateType , boolean isTop , Logger logger , Path dirPath ) throws IOException { if ( config . ptype == FeatureCollectionConfig . PartitionType . file ) { return updateFilePartition ( isGrib1 , config , updateType , isTop , logger , dirPath ) ; } else { Formatter errlog = new Formatter ( ) ; CollectionSpecParser specp = config . getCollectionSpecParser ( errlog ) ; try ( DirectoryCollection dcm = new DirectoryCollection ( config . collectionName , dirPath , isTop , config . olderThan , logger ) ) { dcm . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , config ) ; if ( specp . getFilter ( ) != null ) dcm . setStreamFilter ( new StreamFilter ( specp . getFilter ( ) , specp . getFilterOnName ( ) ) ) ; boolean changed = updateGribCollection ( isGrib1 , dcm , updateType , FeatureCollectionConfig . PartitionType . directory , logger , errlog ) ; logger . debug ( \"  GribCdmIndex.updateDirectoryPartition was updated=%s on %s%n\" , changed , dirPath ) ; return changed ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "File Partition : each File is a collection of Grib records and the collection of all files in the directory is a PartitionCollection . Rewrite the PartitionCollection and optionally its children [CODESPLIT] private static boolean updateFilePartition ( final boolean isGrib1 , final FeatureCollectionConfig config , final CollectionUpdateType updateType , boolean isTop , final Logger logger , Path dirPath ) throws IOException { long start = System . currentTimeMillis ( ) ; final Formatter errlog = new Formatter ( ) ; CollectionSpecParser specp = config . getCollectionSpecParser ( errlog ) ; try ( FilePartition partition = new FilePartition ( config . collectionName , dirPath , isTop , config . olderThan , logger ) ) { partition . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , config ) ; if ( specp . getFilter ( ) != null ) partition . setStreamFilter ( new StreamFilter ( specp . getFilter ( ) , specp . getFilterOnName ( ) ) ) ; logger . debug ( \"GribCdmIndex.updateFilePartition %s %s%n\" , partition . getCollectionName ( ) , updateType ) ; if ( ! isUpdateNeeded ( partition . getIndexFilename ( NCX_SUFFIX ) , updateType , ( isGrib1 ? GribCollectionType . Partition1 : GribCollectionType . Partition2 ) , logger ) ) return false ; final AtomicBoolean anyChange = new AtomicBoolean ( false ) ; // just need a mutable boolean we can declare final // redo the children here if ( updateType != CollectionUpdateType . testIndexOnly ) { // skip children on testIndexOnly partition . iterateOverMFileCollection ( mfile -> { MCollection part = new CollectionSingleFile ( mfile , logger ) ; part . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , config ) ; try { boolean changed = updateGribCollection ( isGrib1 , part , updateType , FeatureCollectionConfig . PartitionType . file , logger , errlog ) ; if ( changed ) anyChange . set ( true ) ; } catch ( IllegalStateException t ) { logger . warn ( \"Error making partition {} '{}'\" , part . getRoot ( ) , t . getMessage ( ) ) ; partition . removePartition ( part ) ; // keep on truckin; can happen if directory is empty } catch ( Throwable t ) { logger . error ( \"Error making partition \" + part . getRoot ( ) , t ) ; partition . removePartition ( part ) ; } } ) ; } // LOOK what if theres only one file? try { // redo partition index if needed, will detect if children have changed boolean recreated = updatePartition ( isGrib1 , partition , updateType , logger , errlog ) ; long took = System . currentTimeMillis ( ) - start ; if ( recreated ) logger . info ( \"RewriteFilePartition {} took {} msecs\" , partition . getCollectionName ( ) , took ) ; return recreated ; } catch ( IllegalStateException t ) { logger . warn ( \"Error making partition {} '{}'\" , partition . getRoot ( ) , t . getMessage ( ) ) ; return false ; } catch ( Throwable t ) { logger . error ( \"Error making partition \" + partition . getRoot ( ) , t ) ; return false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open GribCollection from config . CollectionUpdater calls InvDatasetFc . update () calls InvDatasetFcGrib . updateCollection () [CODESPLIT] public static GribCollectionImmutable openGribCollection ( FeatureCollectionConfig config , CollectionUpdateType updateType , Logger logger ) throws IOException { // update if needed boolean changed = updateGribCollection ( config , updateType , logger ) ; File idxFile = makeTopIndexFileFromConfig ( config ) ; // If call to updateGribCollection shows a change happened, then collection changed. // If updateType is never (tds is in charge of updating, not TDM or some other external application), // then this is being called after receiving an outside trigger. Assume collection changed. // // At this point, there isn't a good way of invalidating the gribColectionCache entries associated with the // particular collection being updated, so we have to clear the whole cache. Will revisit this in // 5.0 if performance is an issue if ( ( updateType == CollectionUpdateType . never ) || changed ) { gribCollectionCache . clearCache ( true ) ; } return openCdmIndex ( idxFile . getPath ( ) , config , true , logger ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by IOSPs [CODESPLIT] public static GribCollectionImmutable openGribCollectionFromRaf ( RandomAccessFile raf , FeatureCollectionConfig config , CollectionUpdateType updateType , org . slf4j . Logger logger ) throws IOException { GribCollectionImmutable result ; // check if its a plain ole GRIB1/2 data file boolean isGrib1 = false ; boolean isGrib2 = Grib2RecordScanner . isValidFile ( raf ) ; if ( ! isGrib2 ) isGrib1 = Grib1RecordScanner . isValidFile ( raf ) ; if ( isGrib1 || isGrib2 ) { result = openGribCollectionFromDataFile ( isGrib1 , raf , config , updateType , null , logger ) ; // close the data file, the ncx raf file is managed by gribCollection raf . close ( ) ; } else { // check its an ncx file result = openGribCollectionFromIndexFile ( raf , config , logger ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a grib collection from a single grib1 or grib2 file . Create the gbx9 and ncx2 files if needed . [CODESPLIT] private static GribCollectionImmutable openGribCollectionFromDataFile ( boolean isGrib1 , RandomAccessFile dataRaf , FeatureCollectionConfig config , CollectionUpdateType updateType , Formatter errlog , org . slf4j . Logger logger ) throws IOException { String filename = dataRaf . getLocation ( ) ; File dataFile = new File ( filename ) ; MFile mfile = new MFileOS ( dataFile ) ; return openGribCollectionFromDataFile ( isGrib1 , mfile , updateType , config , errlog , logger ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "from a single file read in the index create if it doesnt exist ; return null on failure [CODESPLIT] @ Nullable public static GribCollectionImmutable openGribCollectionFromDataFile ( boolean isGrib1 , MFile mfile , CollectionUpdateType updateType , FeatureCollectionConfig config , Formatter errlog , org . slf4j . Logger logger ) throws IOException { MCollection dcm = new CollectionSingleFile ( mfile , logger ) ; dcm . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , config ) ; if ( isGrib1 ) { Grib1CollectionBuilder builder = new Grib1CollectionBuilder ( dcm . getCollectionName ( ) , dcm , logger ) ; // LOOK ignoring partition type boolean changed = ( builder . updateNeeded ( updateType ) && builder . createIndex ( FeatureCollectionConfig . PartitionType . file , errlog ) ) ; } else { Grib2CollectionBuilder builder = new Grib2CollectionBuilder ( dcm . getCollectionName ( ) , dcm , logger ) ; boolean changed = ( builder . updateNeeded ( updateType ) && builder . createIndex ( FeatureCollectionConfig . PartitionType . file , errlog ) ) ; } // the index file should now exist, open it GribCollectionImmutable result = openCdmIndex ( dcm . getIndexFilename ( NCX_SUFFIX ) , config , true , logger ) ; if ( result != null ) return result ; // if open fails, force recreate the index if ( updateType == CollectionUpdateType . never ) return null ; // not allowed to write if ( updateType == CollectionUpdateType . always ) return null ; // already tried to force write, give up return openGribCollectionFromDataFile ( isGrib1 , mfile , CollectionUpdateType . always , config , errlog , logger ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a grib collection / partition collection from an existing ncx2 file . PartionCollection . partition . getGribCollection () . [CODESPLIT] @ Nullable public static GribCollectionImmutable openGribCollectionFromIndexFile ( RandomAccessFile indexRaf , FeatureCollectionConfig config , org . slf4j . Logger logger ) throws IOException { GribCollectionType type = getType ( indexRaf ) ; String location = indexRaf . getLocation ( ) ; File f = new File ( location ) ; int pos = f . getName ( ) . lastIndexOf ( \".\" ) ; String name = ( pos > 0 ) ? f . getName ( ) . substring ( 0 , pos ) : f . getName ( ) ; // remove \".ncx2\" switch ( type ) { case Partition1 : return Grib1PartitionBuilderFromIndex . createTimePartitionFromIndex ( name , indexRaf , config , logger ) ; case GRIB1 : return Grib1CollectionBuilderFromIndex . readFromIndex ( name , indexRaf , config , logger ) ; case Partition2 : return Grib2PartitionBuilderFromIndex . createTimePartitionFromIndex ( name , indexRaf , config , logger ) ; case GRIB2 : return Grib2CollectionBuilderFromIndex . readFromIndex ( name , indexRaf , config , logger ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ IndexReader interface [CODESPLIT] @ Override public boolean readChildren ( Path indexFile , AddChildCallback callback ) throws IOException { logger . debug ( \"GribCdmIndex.readChildren %s%n\" , indexFile ) ; try ( RandomAccessFile raf = RandomAccessFile . acquire ( indexFile . toString ( ) ) ) { GribCollectionType type = getType ( raf ) ; if ( type == GribCollectionType . Partition1 || type == GribCollectionType . Partition2 ) { if ( openIndex ( raf , logger ) ) { String topDir = gribCollectionIndex . getTopDir ( ) ; int n = gribCollectionIndex . getMfilesCount ( ) ; // partition index files stored in MFiles for ( int i = 0 ; i < n ; i ++ ) { GribCollectionProto . MFile mfilep = gribCollectionIndex . getMfiles ( i ) ; callback . addChild ( topDir , mfilep . getFilename ( ) , mfilep . getLastModified ( ) ) ; } return true ; } } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match has different semantics than urlCompare [CODESPLIT] static boolean urlMatch ( URL pattern , URL url ) { int relation ; if ( pattern == null ) return ( url == null ) ; if ( ! ( url . getHost ( ) . endsWith ( pattern . getHost ( ) ) ) ) return false ; // e.g. pattern=x.y.org url=y.org if ( ! ( url . getPath ( ) . startsWith ( pattern . getPath ( ) ) ) ) return false ; // e.g. pattern=y.org/a/b url=y.org/a if ( pattern . getPort ( ) > 0 && pattern . getPort ( ) != url . getPort ( ) ) return false ; // note: all other fields are ignored return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow users to add to the default rc [CODESPLIT] static synchronized public void add ( String key , String value , String url ) { if ( key == null ) return ; if ( ! initialized ) RC . initialize ( ) ; Triple t = new Triple ( key , value , url ) ; dfaltRC . insert ( t ) ; // recompute well-knowns setWellKnown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow users to search the default rc [CODESPLIT] static synchronized public String find ( String key , String url ) { if ( key == null ) return null ; if ( ! initialized ) RC . initialize ( ) ; Triple t = dfaltRC . lookup ( key , url ) ; return ( t == null ? null : t . value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Record some well known parameters [CODESPLIT] static void setWellKnown ( ) { if ( dfaltRC . triplestore . size ( ) == 0 ) return ; // Walk the set of triples looking for those that have no url for ( String key : dfaltRC . keySet ( ) ) { Triple triple = dfaltRC . lookup ( key ) ; if ( triple . url == null ) { RC . set ( key , triple . value ) ; // let set sort it out } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "overwrite existing entries [CODESPLIT] public boolean load ( String abspath ) { abspath = abspath . replace ( ' ' , ' ' ) ; File rcFile = new File ( abspath ) ; if ( ! rcFile . exists ( ) || ! rcFile . canRead ( ) ) { return false ; } if ( showlog ) log . debug ( \"Loading rc file: \" + abspath ) ; try ( BufferedReader rdr = new BufferedReader ( new InputStreamReader ( new FileInputStream ( rcFile ) , CDM . UTF8 ) ) ) { for ( int lineno = 1 ; ; lineno ++ ) { URL url = null ; String line = rdr . readLine ( ) ; if ( line == null ) break ; // trim leading blanks line = line . trim ( ) ; if ( line . length ( ) == 0 ) continue ; // empty line if ( line . charAt ( 0 ) == ' ' ) continue ; // check for comment // parse the line if ( line . charAt ( 0 ) == LTAG ) { int rindex = line . indexOf ( RTAG ) ; if ( rindex < 0 ) return false ; if ( showlog ) log . error ( \"Malformed [url] at \" + abspath + \".\" + lineno ) ; String surl = line . substring ( 1 , rindex ) ; try { url = new URL ( surl ) ; } catch ( MalformedURLException mue ) { if ( showlog ) log . error ( \"Malformed [url] at \" + abspath + \".\" + lineno ) ; } line = line . substring ( rindex + 1 ) ; // trim again line = line . trim ( ) ; } // Get the key,value part String [ ] pieces = line . split ( \"\\\\s*=\\\\s*\" ) ; assert ( pieces . length == 1 || pieces . length == 2 ) ; // Create the triple String value = \"1\" ; if ( pieces . length == 2 ) value = pieces [ 1 ] . trim ( ) ; Triple triple = new Triple ( pieces [ 0 ] . trim ( ) , value , url ) ; List < Triple > list = triplestore . get ( triple . key ) ; if ( list == null ) list = new ArrayList < Triple > ( ) ; Triple prev = addtriple ( list , triple ) ; triplestore . put ( triple . key , list ) ; } } catch ( FileNotFoundException fe ) { if ( showlog ) log . debug ( \"Loading rc file: \" + abspath ) ; return false ; } catch ( IOException ioe ) { if ( showlog ) log . error ( \"File \" + abspath + \": IO exception: \" + ioe . getMessage ( ) ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow for external loading [CODESPLIT] public Triple insert ( Triple t ) { if ( t . key == null ) return null ; List < Triple > list = triplestore . get ( t . key ) ; if ( list == null ) list = new ArrayList < Triple > ( ) ; Triple prev = addtriple ( list , t ) ; triplestore . put ( t . key , list ) ; return prev ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the original string representation of this clause . For use in debugging . [CODESPLIT] public void printConstraint ( PrintWriter os ) { lhs . printConstraint ( os ) ; String op = ExprParserConstants . tokenImage [ operator ] ; op = op . substring ( 1 , op . length ( ) - 1 ) ; os . print ( op ) ; //os.print(ExprParserConstants.tokenImage[operator].substring(2, 3)); if ( rhs . size ( ) == 1 ) { ( ( ValueClause ) rhs . get ( 0 ) ) . printConstraint ( os ) ; } else { os . print ( \"{\" ) ; Iterator it = rhs . iterator ( ) ; boolean first = true ; while ( it . hasNext ( ) ) { if ( ! first ) os . print ( \",\" ) ; ( ( ValueClause ) it . next ( ) ) . printConstraint ( os ) ; first = false ; } os . print ( \"}\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get top level datasets contained directly in this catalog . Do not dereference catRefs . [CODESPLIT] public List < Dataset > getDatasetsLocal ( ) { List < Dataset > datasets = ( List < Dataset > ) flds . get ( Dataset . Datasets ) ; return datasets == null ? new ArrayList <> ( 0 ) : datasets ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look though all datasets here or under here . do not go into catrefs [CODESPLIT] public Dataset findDatasetByName ( String name ) { for ( Dataset ds : getDatasets ( ) ) { if ( ds . getName ( ) . equals ( name ) ) return ds ; Dataset result = ds . findDatasetByName ( name ) ; if ( result != null ) return result ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets new projection for subsequent drawing . [CODESPLIT] public void setProjection ( ProjectionImpl project ) { displayProject = project ; if ( featSetList == null ) return ; Iterator iter = featSetList . iterator ( ) ; while ( iter . hasNext ( ) ) { FeatureSet fs = ( FeatureSet ) iter . next ( ) ; fs . newProjection = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we have to deal with both projections and resolution - dependence [CODESPLIT] protected Iterator getShapes ( java . awt . Graphics2D g , AffineTransform normal2device ) { long startTime = System . currentTimeMillis ( ) ; if ( featSetList == null ) { initFeatSetList ( ) ; assert ! featSetList . isEmpty ( ) ; } // which featureSet should we ue? FeatureSet fs = ( FeatureSet ) featSetList . get ( 0 ) ; if ( featSetList . size ( ) > 1 ) { // compute scale double scale = 1.0 ; try { AffineTransform world2device = g . getTransform ( ) ; AffineTransform world2normal = normal2device . createInverse ( ) ; world2normal . concatenate ( world2device ) ; scale = Math . max ( Math . abs ( world2normal . getScaleX ( ) ) , Math . abs ( world2normal . getShearX ( ) ) ) ; // drawing or printing if ( Debug . isSet ( \"GisFeature/showTransform\" ) ) { System . out . println ( \"GisFeature/showTransform: \" + world2normal + \"\\n scale = \" + scale ) ; } } catch ( java . awt . geom . NoninvertibleTransformException e ) { System . out . println ( \" GisRenderFeature: NoninvertibleTransformException on \" + normal2device ) ; } if ( ! displayProject . isLatLon ( ) ) scale *= 111.0 ; // km/deg double minD = Double . MAX_VALUE ; for ( Object aFeatSetList : featSetList ) { FeatureSet tryfs = ( FeatureSet ) aFeatSetList ; double d = Math . abs ( scale * tryfs . minDist - pixelMatch ) ; // we want min features ~ 2 pixels if ( d < minD ) { minD = d ; fs = tryfs ; } } if ( Debug . isSet ( \"GisFeature/MapResolution\" ) ) { System . out . println ( \"GisFeature/MapResolution: scale = \" + scale + \" minDist = \" + fs . minDist ) ; } } // we may have deferred the actual creation of the points if ( fs . featureList == null ) fs . createFeatures ( ) ; // ok, now see if we need to project if ( ! displayProject . equals ( fs . project ) ) { fs . setProjection ( displayProject ) ; } else { // deal with LatLon if ( fs . newProjection && displayProject . isLatLon ( ) ) { fs . setProjection ( displayProject ) ; } } fs . newProjection = false ; if ( Debug . isSet ( \"GisFeature/timing/getShapes\" ) ) { long tookTime = System . currentTimeMillis ( ) - startTime ; System . out . println ( \"timing.getShapes: \" + tookTime * .001 + \" seconds\" ) ; } // so return it, already return fs . getShapes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "make an ArrayList of Shapes from the given featureList and current display Projection [CODESPLIT] private ArrayList makeShapes ( Iterator featList ) { Shape shape ; ArrayList shapeList = new ArrayList ( ) ; ProjectionImpl dataProject = getDataProjection ( ) ; if ( Debug . isSet ( \"GisFeature/MapDraw\" ) ) { System . out . println ( \"GisFeature/MapDraw: makeShapes with \" + displayProject ) ; } /*    if (Debug.isSet(\"bug.drawShapes\")) {\n      int count =0;\n      // make each GisPart a seperate shape for debugging\nfeats:while (featList.hasNext()) {\n        AbstractGisFeature feature = (AbstractGisFeature) featList.next();\n        java.util.Iterator pi = feature.getGisParts();\n        while (pi.hasNext()) {\n          GisPart gp = (GisPart) pi.next();\n          int np = gp.getNumPoints();\n          GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, np);\n          double[] xx = gp.getX();\n          double[] yy = gp.getY();\n          path.moveTo((float) xx[0], (float) yy[0]);\n          if (count == 63)\n                System.out.println(\"moveTo x =\"+xx[0]+\" y= \"+yy[0]);\n          for(int i = 1; i < np; i++) {\n            path.lineTo((float) xx[i], (float) yy[i]);\n            if (count == 63)\n                System.out.println(\"lineTo x =\"+xx[i]+\" y= \"+yy[i]);\n          }\n          shapeList.add(path);\n          if (count == 63)\n            break feats;\n          count++;\n        }\n      }\n      System.out.println(\"bug.drawShapes: #shapes =\" +shapeList.size());\n      return shapeList;\n    }  */ while ( featList . hasNext ( ) ) { AbstractGisFeature feature = ( AbstractGisFeature ) featList . next ( ) ; if ( dataProject . isLatLon ( ) ) // always got to run it through if its lat/lon shape = feature . getProjectedShape ( displayProject ) ; else if ( dataProject == displayProject ) shape = feature . getShape ( ) ; else shape = feature . getProjectedShape ( dataProject , displayProject ) ; shapeList . add ( shape ) ; } return shapeList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this PrefixName with a string . [CODESPLIT] public final int compareTo ( String string ) { return getID ( ) . length ( ) >= string . length ( ) ? getID ( ) . compareToIgnoreCase ( string ) : getID ( ) . compareToIgnoreCase ( string . substring ( 0 , getID ( ) . length ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The given task is run in a background thread . Progress is indicated once a second . You cannot call this method again till the task is completed . [CODESPLIT] public boolean startProgressMonitorTask ( ProgressMonitorTask pmt ) { if ( busy ) return false ; busy = true ; this . task = pmt ; isCancelled = false ; count = 0 ; setIcon ( icon [ 0 ] ) ; // create timer, whose events happen on the awt event Thread ActionListener watcher = new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { //System.out.println(\"timer event\"+evt); if ( isCancelled && ! task . isCancel ( ) ) { task . cancel ( ) ; if ( debug ) System . out . println ( \" task.cancel\" ) ; return ; // give it a chance to finish up } else { // indicate progress count ++ ; setIcon ( icon [ count % 2 ] ) ; if ( debug ) System . out . println ( \" stop count=\" + count ) ; } // need to make sure task acknowledges the cancel; so dont shut down // until the task is done if ( task . isDone ( ) ) { if ( myTimer != null ) myTimer . stop ( ) ; myTimer = null ; if ( task . isError ( ) ) javax . swing . JOptionPane . showMessageDialog ( null , task . getErrorMessage ( ) ) ; if ( task . isSuccess ( ) ) fireEvent ( new ActionEvent ( this , 0 , \"success\" ) ) ; else if ( task . isError ( ) ) fireEvent ( new ActionEvent ( this , 0 , \"error\" ) ) ; else if ( task . isCancel ( ) ) fireEvent ( new ActionEvent ( this , 0 , \"cancel\" ) ) ; else fireEvent ( new ActionEvent ( this , 0 , \"done\" ) ) ; busy = false ; } } } ; myTimer = new javax . swing . Timer ( 1000 , watcher ) ; // every second myTimer . start ( ) ; // do task in a seperate, non-event, thread Thread taskThread = new Thread ( task ) ; taskThread . start ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update all the grib indices in one directory and the collection index for that directory [CODESPLIT] private Accum scanLeafDirectoryCollection ( boolean isGrib1 , FeatureCollectionConfig config , Counters parentCounters , Logger logger , Path dirPath , boolean isTop , Indent indent , Formatter fm ) throws IOException { if ( config . ptype == FeatureCollectionConfig . PartitionType . file ) { reportOneFileHeader ( indent , fm ) ; fm . format ( \"%sDirectory %s%n\" , indent , dirPath ) ; } Accum accum = new Accum ( ) ; int nfiles = 0 ; Counters countersThisDir = parentCounters . makeSubCounters ( ) ; Formatter errlog = new Formatter ( ) ; CollectionSpecParser specp = config . getCollectionSpecParser ( errlog ) ; DirectoryCollection dcm = new DirectoryCollection ( config . collectionName , dirPath , isTop , config . olderThan , logger ) ; // dcm.setUseGribFilter(false); dcm . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , config ) ; if ( specp . getFilter ( ) != null ) dcm . setStreamFilter ( new StreamFilter ( specp . getFilter ( ) , specp . getFilterOnName ( ) ) ) ; try ( CloseableIterator < MFile > iter = dcm . getFileIterator ( ) ) { while ( iter . hasNext ( ) ) { MFile mfile = iter . next ( ) ; Counters countersOneFile = countersThisDir . makeSubCounters ( ) ; int nrecords = 0 ; if ( isGrib1 ) { Grib1Index grib1Index = readGrib1Index ( mfile , false ) ; if ( grib1Index == null ) { System . out . printf ( \"%s%s: read or create failed%n\" , indent , mfile . getPath ( ) ) ; continue ; } for ( ucar . nc2 . grib . grib1 . Grib1Record gr : grib1Index . getRecords ( ) ) { accumGrib1Record ( gr , countersOneFile ) ; nrecords ++ ; } } else { Grib2Index grib2Index = readGrib2Index ( mfile , false ) ; if ( grib2Index == null ) { System . out . printf ( \"%s%s: read or create failed%n\" , indent , mfile . getPath ( ) ) ; continue ; } for ( ucar . nc2 . grib . grib2 . Grib2Record gr : grib2Index . getRecords ( ) ) { accumGrib2Record ( gr , countersOneFile ) ; nrecords ++ ; } } accum . nrecords += nrecords ; countersThisDir . addTo ( countersOneFile ) ; if ( config . ptype == FeatureCollectionConfig . PartitionType . file ) reportOneFile ( mfile , nrecords , countersOneFile , indent , fm ) ; nfiles ++ ; // get file sizes String path = mfile . getPath ( ) ; if ( path . endsWith ( GribIndex . GBX9_IDX ) ) { accum . indexSize += ( ( float ) mfile . getLength ( ) / ( 1000 * 1000 ) ) ; // mb } else { accum . fileSize += ( ( float ) mfile . getLength ( ) / ( 1000 * 1000 ) ) ; // mb File idxFile = GribIndexCache . getExistingFileOrCache ( path + GribIndex . GBX9_IDX ) ; if ( idxFile . exists ( ) ) accum . indexSize += ( ( float ) idxFile . length ( ) / ( 1000 * 1000 ) ) ; // mb } } } parentCounters . addTo ( countersThisDir ) ; accum . nfiles += nfiles ; accum . last = reportOneDir ( dirPath . toString ( ) , accum , countersThisDir , indent , accum . last ) ; return accum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK need an option to only scan latest last partition or something [CODESPLIT] private boolean needsUpdate ( CollectionUpdateType ff , File collectionIndexFile ) throws IOException { long collectionLastModified = collectionIndexFile . lastModified ( ) ; Set < String > newFileSet = new HashSet <> ( ) ; for ( MCollection dcm : partitionManager . makePartitions ( CollectionUpdateType . test ) ) { String partitionIndexFilename = StringUtil2 . replace ( dcm . getIndexFilename ( GribCdmIndex . NCX_SUFFIX ) , ' ' , \"/\" ) ; File partitionIndexFile = GribIndexCache . getExistingFileOrCache ( partitionIndexFilename ) ; if ( partitionIndexFile == null ) // make sure each partition has an index return true ; if ( collectionLastModified < partitionIndexFile . lastModified ( ) ) // and the partition index is earlier than the collection index return true ; newFileSet . add ( partitionIndexFilename ) ; } if ( ff == CollectionUpdateType . testIndexOnly ) return false ; // now see if any files were deleted GribCdmIndex reader = new GribCdmIndex ( logger ) ; List < MFile > oldFiles = new ArrayList <> ( ) ; reader . readMFiles ( collectionIndexFile . toPath ( ) , oldFiles ) ; Set < String > oldFileSet = new HashSet <> ( ) ; for ( MFile oldFile : oldFiles ) { if ( ! newFileSet . contains ( oldFile . getPath ( ) ) ) return true ; // got deleted - must recreate the index oldFileSet . add ( oldFile . getPath ( ) ) ; } // now see if any files were added for ( String newFilename : newFileSet ) { if ( ! oldFileSet . contains ( newFilename ) ) return true ; // got added - must recreate the index } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return true if changed exception on failure [CODESPLIT] boolean createPartitionedIndex ( CollectionUpdateType forcePartition , Formatter errlog ) throws IOException { if ( errlog == null ) errlog = new Formatter ( ) ; // info will be discarded // create partitions from the partitionManager for ( MCollection dcmp : partitionManager . makePartitions ( forcePartition ) ) { dcmp . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , partitionManager . getAuxInfo ( FeatureCollectionConfig . AUX_CONFIG ) ) ; result . addPartition ( dcmp ) ; } result . sortPartitions ( ) ; // after this the partition list is immutable // choose the \"canonical\" partition, aka prototype // only used in copyInfo int n = result . getPartitionSize ( ) ; if ( n == 0 ) { errlog . format ( \"ERR Nothing in this partition = %s%n\" , result . showLocation ( ) ) ; throw new IllegalStateException ( \"Nothing in this partition =\" + result . showLocation ( ) ) ; } int idx = partitionManager . getProtoIndex ( n ) ; PartitionCollectionMutable . Partition canon = result . getPartition ( idx ) ; logger . debug ( \"     Using canonical partition {}\" , canon . getDcm ( ) . getCollectionName ( ) ) ; try ( GribCollectionMutable gc = canon . makeGribCollection ( ) ) { // LOOK open/close canonical partition if ( gc == null ) throw new IllegalStateException ( \"canon.makeGribCollection failed on =\" + result . showLocation ( ) + \" \" + canon . getName ( ) + \"; errs=\" + errlog ) ; // copy info from canon gribCollection to result partitionCollection result . copyInfo ( gc ) ; result . isPartitionOfPartitions = ( gc instanceof PartitionCollectionMutable ) ; result . dateRange = gc . dateRange ; } // check consistency across vert and ens coords // create partitioned variables // partition index is used - do not resort partitions GribCollectionMutable . Dataset ds2D = makeDataset2D ( errlog ) ; if ( ds2D == null ) { errlog . format ( \" ERR makeDataset2D failed, index not written on %s%n\" , result . showLocation ( ) ) ; throw new IllegalStateException ( \"makeDataset2D failed, index not written on =\" + result . showLocation ( ) + \"; errs=\" + errlog ) ; } // Make Best for a TwoD if ( ds2D . gctype == GribCollectionImmutable . Type . TwoD ) makeDatasetBest ( ds2D , false ) ; //else if (ds2D.gctype == GribCollectionImmutable.Type.MRUTC) //  makeTime2runtime(ds2D, false); // ready to write the index file return writeIndex ( result , errlog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * LOOK heres a place where one could post process and combine instead of at coverage level . this would benefit iosp ie the netcdf API private void makeTime2runtime ( GribCollectionMutable . Dataset ds2D boolean isComplete ) throws IOException { [CODESPLIT] private void makeDatasetBest ( GribCollectionMutable . Dataset ds2D , boolean isComplete ) { GribCollectionMutable . Dataset dsBest = result . makeDataset ( isComplete ? GribCollectionImmutable . Type . BestComplete : GribCollectionImmutable . Type . Best ) ; int npart = result . getPartitionSize ( ) ; // for each 2D group for ( GribCollectionMutable . GroupGC group2D : ds2D . groups ) { GribCollectionMutable . GroupGC groupB = dsBest . addGroupCopy ( group2D ) ; // make copy of group, add to Best dataset groupB . isTwoD = false ; // for each time2D, create the best time coordinates HashMap < Coordinate , CoordinateTimeAbstract > map2DtoBest = new HashMap <> ( ) ; // associate 2D coord with best CoordinateSharerBest sharer = new CoordinateSharerBest ( ) ; for ( Coordinate coord : group2D . coords ) { if ( coord instanceof CoordinateRuntime ) continue ; // skip it if ( coord instanceof CoordinateTime2D ) { CoordinateTimeAbstract best = ( ( CoordinateTime2D ) coord ) . makeBestTimeCoordinate ( result . masterRuntime ) ; if ( ! isComplete ) best = best . makeBestFromComplete ( ) ; sharer . addCoordinate ( best ) ; map2DtoBest . put ( coord , best ) ; } else { sharer . addCoordinate ( coord ) ; } } groupB . coords = sharer . finish ( ) ; // these are the unique coords for group Best // transfer variables to Best group, set shared Coordinates for ( GribCollectionMutable . VariableIndex vi2d : group2D . variList ) { // copy vi2d and add to groupB PartitionCollectionMutable . VariableIndexPartitioned vip = result . makeVariableIndexPartitioned ( groupB , vi2d , npart ) ; vip . finish ( ) ; // set shared coordinates List < Coordinate > newCoords = new ArrayList <> ( ) ; for ( Integer groupIndex : vi2d . coordIndex ) { Coordinate coord2D = group2D . coords . get ( groupIndex ) ; if ( coord2D instanceof CoordinateRuntime ) continue ; // skip runtime; if ( coord2D instanceof CoordinateTime2D ) { newCoords . add ( map2DtoBest . get ( coord2D ) ) ; // add the best coordinate for that CoordinateTime2D } else { newCoords . add ( coord2D ) ; } } vip . coordIndex = sharer . reindex ( newCoords ) ; } } // loop over groups }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * MAGIC_START version sizeRecords VariableRecords ( sizeRecords bytes ) sizeIndex GribCollectionIndex ( sizeIndex bytes ) [CODESPLIT] protected boolean writeIndex ( PartitionCollectionMutable pc , Formatter f ) throws IOException { File idxFile = GribIndexCache . getFileOrCache ( partitionManager . getIndexFilename ( GribCdmIndex . NCX_SUFFIX ) ) ; if ( idxFile . exists ( ) ) { RandomAccessFile . eject ( idxFile . getPath ( ) ) ; if ( ! idxFile . delete ( ) ) logger . error ( \"gc2tp cant delete \" + idxFile . getPath ( ) ) ; } writer = new GribCollectionWriter ( null , null ) ; try ( RandomAccessFile raf = new RandomAccessFile ( idxFile . getPath ( ) , \"rw\" ) ) { raf . order ( RandomAccessFile . BIG_ENDIAN ) ; //// header message raf . write ( getMagicStart ( ) . getBytes ( CDM . utf8Charset ) ) ; raf . writeInt ( getVersion ( ) ) ; raf . writeLong ( 0 ) ; // no record section /*\n      message GribCollection {\n        required string name = 1;         // must be unique - index filename is name.ncx\n        required string topDir = 2;       // filenames are reletive to this\n        repeated MFile mfiles = 3;        // list of grib MFiles\n        repeated Dataset dataset = 4;\n        repeated Gds gds = 5;             // unique Gds, shared amongst datasets\n\n        required int32 center = 6;      // these 4 fields are to get a GribTable object\n        required int32 subcenter = 7;\n        required int32 master = 8;\n        required int32 local = 9;       // grib1 table Version\n\n        optional int32 genProcessType = 10;\n        optional int32 genProcessId = 11;\n        optional int32 backProcessId = 12;\n\n        // repeated Parameter params = 20;      // not used\n        FcConfig config = 21;\n        uint64 startTime = 22; // calendar date, first valid time\n        uint64 endTime = 23;   // calendar date, last valid time\n\n        extensions 100 to 199;\n      }\n\n      extend GribCollection {\n        repeated Partition partitions = 100;\n      }\n       */ GribCollectionProto . GribCollection . Builder indexBuilder = GribCollectionProto . GribCollection . newBuilder ( ) ; indexBuilder . setName ( pc . getName ( ) ) ; Path topDir = pc . directory . toPath ( ) ; String pathS = StringUtil2 . replace ( topDir . toString ( ) , ' ' , \"/\" ) ; indexBuilder . setTopDir ( pathS ) ; // mfiles are the partition indexes int count = 0 ; for ( PartitionCollectionMutable . Partition part : pc . partitions ) { GribCollectionProto . MFile . Builder b = GribCollectionProto . MFile . newBuilder ( ) ; String pathRS = makeReletiveFilename ( pc , part ) ; // reletive to pc.directory b . setFilename ( pathRS ) ; b . setLastModified ( part . getLastModified ( ) ) ; b . setLength ( part . fileSize ) ; b . setIndex ( count ++ ) ; indexBuilder . addMfiles ( b . build ( ) ) ; } indexBuilder . setCenter ( pc . center ) ; indexBuilder . setSubcenter ( pc . subcenter ) ; indexBuilder . setMaster ( pc . master ) ; indexBuilder . setLocal ( pc . local ) ; indexBuilder . setGenProcessId ( pc . genProcessId ) ; indexBuilder . setGenProcessType ( pc . genProcessType ) ; indexBuilder . setBackProcessId ( pc . backProcessId ) ; indexBuilder . setStartTime ( pc . dateRange . getStart ( ) . getMillis ( ) ) ; indexBuilder . setEndTime ( pc . dateRange . getEnd ( ) . getMillis ( ) ) ; indexBuilder . setMasterRuntime ( writer . writeCoordProto ( pc . masterRuntime ) ) ; // dataset for ( GribCollectionMutable . Dataset ds : pc . datasets ) indexBuilder . addDataset ( writeDatasetProto ( pc , ds ) ) ; // extensions if ( pc . run2part != null ) { for ( int part : pc . run2part ) indexBuilder . addRun2Part ( part ) ; } for ( PartitionCollectionMutable . Partition part : pc . partitions ) indexBuilder . addPartitions ( writePartitionProto ( pc , part ) ) ; indexBuilder . setIsPartitionOfPartitions ( pc . isPartitionOfPartitions ) ; // write it out GribCollectionProto . GribCollection index = indexBuilder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; NcStream . writeVInt ( raf , b . length ) ; // message size raf . write ( b ) ; // message  - all in one gulp f . format ( \"Grib2PartitionIndex= %d bytes file size =  %d bytes%n%n\" , b . length , raf . length ( ) ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Dataset { required Type type = 1 ; repeated Group groups = 2 ; } [CODESPLIT] private GribCollectionProto . Dataset writeDatasetProto ( PartitionCollectionMutable pc , GribCollectionMutable . Dataset ds ) throws IOException { GribCollectionProto . Dataset . Builder b = GribCollectionProto . Dataset . newBuilder ( ) ; GribCollectionProto . Dataset . Type type = GribCollectionProto . Dataset . Type . valueOf ( ds . gctype . toString ( ) ) ; b . setType ( type ) ; for ( GribCollectionMutable . GroupGC group : ds . groups ) b . addGroups ( writeGroupProto ( pc , group ) ) ; return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Group { Gds gds = 1 ; // use this to build the HorizCoordSys repeated Variable variables = 2 ; // list of variables repeated Coord coords = 3 ; // list of coordinates repeated uint32 fileno = 4 [ packed = true ] ; // the component files that are in this group key into gc . mfiles } [CODESPLIT] private GribCollectionProto . Group writeGroupProto ( PartitionCollectionMutable pc , GribCollectionMutable . GroupGC g ) throws IOException { GribCollectionProto . Group . Builder b = GribCollectionProto . Group . newBuilder ( ) ; b . setGds ( GribCollectionWriter . writeGdsProto ( g . horizCoordSys . getRawGds ( ) , g . horizCoordSys . getPredefinedGridDefinition ( ) ) ) ; for ( GribCollectionMutable . VariableIndex vb : g . variList ) { b . addVariables ( writeVariableProto ( ( PartitionCollectionMutable . VariableIndexPartitioned ) vb ) ) ; } for ( Coordinate coord : g . coords ) { switch ( coord . getType ( ) ) { case runtime : b . addCoords ( writer . writeCoordProto ( ( CoordinateRuntime ) coord ) ) ; break ; case time : b . addCoords ( writer . writeCoordProto ( ( CoordinateTime ) coord ) ) ; break ; case timeIntv : b . addCoords ( writer . writeCoordProto ( ( CoordinateTimeIntv ) coord ) ) ; break ; case time2D : b . addCoords ( writer . writeCoordProto ( ( CoordinateTime2D ) coord ) ) ; break ; case vert : b . addCoords ( writer . writeCoordProto ( ( CoordinateVert ) coord ) ) ; break ; case ens : b . addCoords ( writer . writeCoordProto ( ( CoordinateEns ) coord ) ) ; break ; } } if ( g . filenose != null ) for ( Integer fileno : g . filenose ) b . addFileno ( fileno ) ; return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Variable { uint32 discipline = 1 ; bytes pds = 2 ; // raw pds repeated uint32 ids = 3 [ packed = true ] ; // extra info not in pds ; grib2 id section [CODESPLIT] private GribCollectionProto . Variable writeVariableProto ( PartitionCollectionMutable . VariableIndexPartitioned vp ) { GribCollectionProto . Variable . Builder b = GribCollectionProto . Variable . newBuilder ( ) ; b . setDiscipline ( vp . discipline ) ; b . setPds ( ByteString . copyFrom ( vp . rawPds ) ) ; // extra id info b . addIds ( vp . center ) ; b . addIds ( vp . subcenter ) ; b . setRecordsPos ( vp . recordsPos ) ; b . setRecordsLen ( vp . recordsLen ) ; for ( int idx : vp . coordIndex ) b . addCoordIdx ( idx ) ; b . setNdups ( vp . ndups ) ; b . setNrecords ( vp . nrecords ) ; b . setMissing ( vp . nmissing ) ; /* if (vp.twot != null) { // only for 2D\n      for (int invCount : vp.twot.getCount())\n        b.addInvCount(invCount);\n    }\n\n    if (vp.time2runtime != null) { // only for 1D\n      for (int idx=0; idx < vp.time2runtime.getN(); idx++)\n        b.addTime2Runtime(vp.time2runtime.get(idx));\n    } */ // extensions if ( vp . nparts > 0 && vp . partnoSA != null ) { for ( int i = 0 ; i < vp . nparts ; i ++ ) // PartitionCollection.PartitionForVariable2D pvar : vp.getPartitionForVariable2D()) b . addPartVariable ( writePartitionVariableProto ( vp . partnoSA . get ( i ) , vp . groupnoSA . get ( i ) , vp . varnoSA . get ( i ) , vp . nrecords , vp . ndups , vp . nmissing ) ) ; // LOOK was it finished ?? } return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message PartitionVariable { uint32 groupno = 1 ; uint32 varno = 2 ; uint32 flag = 3 ; uint32 partno = 4 ; [CODESPLIT] private GribCollectionProto . PartitionVariable writePartitionVariableProto ( int partno , int groupno , int varno , int nrecords , int ndups , int nmissing ) { GribCollectionProto . PartitionVariable . Builder pb = GribCollectionProto . PartitionVariable . newBuilder ( ) ; pb . setPartno ( partno ) ; pb . setGroupno ( groupno ) ; pb . setVarno ( varno ) ; pb . setNdups ( ndups ) ; pb . setNrecords ( nrecords ) ; pb . setMissing ( nmissing ) ; return pb . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Partition { string name = 1 ; // name is used in TDS - eg the subdirectory when generated by TimePartitionCollections string filename = 2 ; // the gribCollection . ncx file reletive to gc . string directory = 3 ; // top directory NOT USED uint64 lastModified = 4 ; int64 length = 5 ; int64 partitionDate = 6 ; // partition date added 11 / 25 / 14 } [CODESPLIT] private GribCollectionProto . Partition writePartitionProto ( PartitionCollectionMutable pc , PartitionCollectionMutable . Partition p ) { GribCollectionProto . Partition . Builder b = GribCollectionProto . Partition . newBuilder ( ) ; String pathRS = makeReletiveFilename ( pc , p ) ; // reletive to pc.directory b . setFilename ( pathRS ) ; b . setName ( p . name ) ; // b.setDirectory(p.directory); b . setLastModified ( p . lastModified ) ; b . setLength ( p . fileSize ) ; if ( p . partitionDate != null ) b . setPartitionDate ( p . partitionDate . getMillis ( ) ) ; // LOOK what about calendar ?? return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK [CODESPLIT] public boolean equalsData ( ucar . nc2 . ft . fmrc . EnsCoord other ) { if ( ensembles != other . ensembles ) return false ; if ( pdn != other . pdn ) return false ; for ( int i = 0 ; i < ensTypes . length ; i ++ ) { if ( ensTypes [ i ] != other . ensTypes [ i ] ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////// [CODESPLIT] static public EnsCoord findEnsCoord ( List < EnsCoord > ensCoords , EnsCoord want ) { if ( want == null ) return null ; for ( EnsCoord ec : ensCoords ) { if ( want . equalsData ( ec ) ) return ec ; } // make a new one\r EnsCoord result = new EnsCoord ( want ) ; ensCoords . add ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extend result with all the values in the list of EnsCoord [CODESPLIT] static public void normalize ( EnsCoord result , List < EnsCoord > ecList ) { List < EnsCoord > extra = new ArrayList <> ( ) ; for ( EnsCoord ec : ecList ) { if ( ! result . equalsData ( ec ) ) { // differences can only be greater\r extra . add ( ec ) ; } } if ( extra . size ( ) == 0 ) return ; for ( EnsCoord ec : extra ) { if ( ec . getNEnsembles ( ) < result . getNEnsembles ( ) ) continue ; result = ec ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Record { uint32 fileno = 1 ; // which GRIB file ? key into GC . fileMap uint64 pos = 2 ; // offset in GRIB file of the start of entire message uint64 bmsPos = 3 ; // use alternate bms if non - zero ( grib2 only ) uint32 drsOffset = 4 ; // offset of drs from pos ( grib2 only ) } [CODESPLIT] private GribCollectionProto . SparseArray writeSparseArray ( Grib1CollectionBuilder . VariableBag vb , Set < Integer > fileSet ) { GribCollectionProto . SparseArray . Builder b = GribCollectionProto . SparseArray . newBuilder ( ) ; SparseArray < Grib1Record > sa = vb . coordND . getSparseArray ( ) ; for ( int size : sa . getShape ( ) ) { b . addSize ( size ) ; } for ( int track : sa . getTrack ( ) ) { b . addTrack ( track ) ; } for ( Grib1Record gr : sa . getContent ( ) ) { GribCollectionProto . Record . Builder br = GribCollectionProto . Record . newBuilder ( ) ; br . setFileno ( gr . getFile ( ) ) ; fileSet . add ( gr . getFile ( ) ) ; Grib1SectionIndicator is = gr . getIs ( ) ; br . setStartPos ( is . getStartPos ( ) ) ; // start of entire message b . addRecords ( br ) ; } b . setNdups ( sa . getNdups ( ) ) ; return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Dataset { Type type = 1 ; repeated Group groups = 2 ; [CODESPLIT] private GribCollectionProto . Dataset writeDatasetProto ( GribCollectionImmutable . Type type , List < Group > groups ) { GribCollectionProto . Dataset . Builder b = GribCollectionProto . Dataset . newBuilder ( ) ; GribCollectionProto . Dataset . Type ptype = GribCollectionProto . Dataset . Type . valueOf ( type . toString ( ) ) ; b . setType ( ptype ) ; for ( Group group : groups ) { b . addGroups ( writeGroupProto ( group ) ) ; } return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Group { Gds gds = 1 ; // use this to build the HorizCoordSys repeated Variable variables = 2 ; // list of variables repeated Coord coords = 3 ; // list of coordinates repeated int32 fileno = 4 [ packed = true ] ; // the component files that are in this group key into gc . mfiles } [CODESPLIT] private GribCollectionProto . Group writeGroupProto ( Group g ) { GribCollectionProto . Group . Builder b = GribCollectionProto . Group . newBuilder ( ) ; b . setGds ( writeGdsProto ( g . gdss . getRawBytes ( ) , g . gdss . getPredefinedGridDefinition ( ) ) ) ; for ( Grib1CollectionBuilder . VariableBag vbag : g . gribVars ) { b . addVariables ( writeVariableProto ( vbag ) ) ; } for ( Coordinate coord : g . coords ) { switch ( coord . getType ( ) ) { case runtime : b . addCoords ( writeCoordProto ( ( CoordinateRuntime ) coord ) ) ; break ; case time : b . addCoords ( writeCoordProto ( ( CoordinateTime ) coord ) ) ; break ; case timeIntv : b . addCoords ( writeCoordProto ( ( CoordinateTimeIntv ) coord ) ) ; break ; case time2D : b . addCoords ( writeCoordProto ( ( CoordinateTime2D ) coord ) ) ; break ; case vert : b . addCoords ( writeCoordProto ( ( CoordinateVert ) coord ) ) ; break ; case ens : b . addCoords ( writeCoordProto ( ( CoordinateEns ) coord ) ) ; break ; } } for ( Integer aFileSet : g . fileSet ) { b . addFileno ( aFileSet ) ; } return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Variable { uint32 discipline = 1 ; bytes pds = 2 ; // raw pds repeated uint32 ids = 3 [ packed = true ] ; // extra info not in pds ; grib2 id section [CODESPLIT] private GribCollectionProto . Variable writeVariableProto ( Grib1CollectionBuilder . VariableBag vb ) { GribCollectionProto . Variable . Builder b = GribCollectionProto . Variable . newBuilder ( ) ; b . setDiscipline ( 0 ) ; b . setPds ( ByteString . copyFrom ( vb . first . getPDSsection ( ) . getRawBytes ( ) ) ) ; b . setRecordsPos ( vb . pos ) ; b . setRecordsLen ( vb . length ) ; for ( int idx : vb . coordIndex ) { b . addCoordIdx ( idx ) ; } // keep stats SparseArray sa = vb . coordND . getSparseArray ( ) ; if ( sa != null ) { b . setNdups ( sa . getNdups ( ) ) ; b . setNrecords ( sa . countNotMissing ( ) ) ; b . setMissing ( sa . countMissing ( ) ) ; } return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the index - th StructureData of this ArrayStructure . [CODESPLIT] public void setObject ( int index , Object value ) { if ( sdata == null ) sdata = new StructureData [ nelems ] ; sdata [ index ] = ( StructureData ) value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the index - th StructureData of this ArrayStructure . [CODESPLIT] public StructureData getStructureData ( int index ) { if ( sdata == null ) sdata = new StructureData [ nelems ] ; if ( index >= sdata . length ) throw new IllegalArgumentException ( index + \" > \" + sdata . length ) ; if ( sdata [ index ] == null ) sdata [ index ] = makeStructureData ( this , index ) ; return sdata [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of any type for a specific record as an Array . This may avoid the overhead of creating the StructureData object but is equivilent to getStructure ( recno ) . getArray ( Member m ) . [CODESPLIT] public Array getArray ( int recno , StructureMembers . Member m ) { DataType dataType = m . getDataType ( ) ; switch ( dataType ) { case DOUBLE : double [ ] da = getJavaArrayDouble ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , da ) ; case FLOAT : float [ ] fa = getJavaArrayFloat ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , fa ) ; case BYTE : case UBYTE : case ENUM1 : byte [ ] ba = getJavaArrayByte ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , ba ) ; case SHORT : case USHORT : case ENUM2 : short [ ] sa = getJavaArrayShort ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , sa ) ; case INT : case UINT : case ENUM4 : int [ ] ia = getJavaArrayInt ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , ia ) ; case ULONG : case LONG : long [ ] la = getJavaArrayLong ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , la ) ; case CHAR : char [ ] ca = getJavaArrayChar ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , ca ) ; case STRING : String [ ] str = getJavaArrayString ( recno , m ) ; return Array . factory ( dataType , m . getShape ( ) , str ) ; case STRUCTURE : return getArrayStructure ( recno , m ) ; case SEQUENCE : return getArraySequence ( recno , m ) ; case OPAQUE : return getArrayObject ( recno , m ) ; } throw new RuntimeException ( \"Dont have implemenation for \" + dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set data for one member over all structures . This is used by VariableDS to do scale / offset . [CODESPLIT] public void setMemberArray ( StructureMembers . Member m , Array memberArray ) { m . setDataArray ( memberArray ) ; if ( memberArray instanceof ArrayStructure ) { // LOOK\r ArrayStructure as = ( ArrayStructure ) memberArray ; m . setStructureMembers ( as . getStructureMembers ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract data for one member over all structures . [CODESPLIT] public Array extractMemberArray ( StructureMembers . Member m ) throws IOException { if ( m . getDataArray ( ) != null ) return m . getDataArray ( ) ; DataType dataType = m . getDataType ( ) ; /* special handling for sequences\r\n    if (dataType == DataType.SEQUENCE) {\r\n      List<StructureData> sdataList = new ArrayList<StructureData>();\r\n      for (int recno=0; recno<getSize(); recno++) {\r\n        ArraySequence2 seq = getArraySequence(recno, m);\r\n        StructureDataIterator iter = seq.getStructureDataIterator();\r\n        while (iter.hasNext())\r\n          sdataList.add( iter.next());\r\n      }\r\n      ArraySequence2 seq = getArraySequence(0, m);\r\n      int size = sdataList.size();\r\n      StructureData[] sdataArray = sdataList.toArray( new StructureData[size]);\r\n      return new ArrayStructureW( seq.getStructureMembers(), new int[] {size}, sdataArray);\r\n   } */ // combine the shapes\r int [ ] mshape = m . getShape ( ) ; int rrank = rank + mshape . length ; int [ ] rshape = new int [ rrank ] ; System . arraycopy ( getShape ( ) , 0 , rshape , 0 , rank ) ; System . arraycopy ( mshape , 0 , rshape , rank , mshape . length ) ; // create an empty array to hold the result\r Array result ; if ( dataType == DataType . STRUCTURE ) { StructureMembers membersw = new StructureMembers ( m . getStructureMembers ( ) ) ; // no data arrays get propagated\r result = new ArrayStructureW ( membersw , rshape ) ; } else if ( dataType == DataType . OPAQUE ) { result = Array . factory ( DataType . OPAQUE , rshape ) ; } else { result = Array . factory ( dataType , rshape ) ; } IndexIterator resultIter = result . getIndexIterator ( ) ; if ( dataType == DataType . DOUBLE ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyDoubles ( recno , m , resultIter ) ; } else if ( dataType == DataType . FLOAT ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyFloats ( recno , m , resultIter ) ; } else if ( dataType . getPrimitiveClassType ( ) == byte . class ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyBytes ( recno , m , resultIter ) ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyShorts ( recno , m , resultIter ) ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyInts ( recno , m , resultIter ) ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyLongs ( recno , m , resultIter ) ; } else if ( dataType == DataType . CHAR ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyChars ( recno , m , resultIter ) ; } else if ( ( dataType == DataType . STRING ) || ( dataType == DataType . OPAQUE ) ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyObjects ( recno , m , resultIter ) ; } else if ( dataType == DataType . STRUCTURE ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copyStructures ( recno , m , resultIter ) ; } else if ( dataType == DataType . SEQUENCE ) { for ( int recno = 0 ; recno < getSize ( ) ; recno ++ ) copySequences ( recno , m , resultIter ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "member data is itself a structure and may be an array of structures . [CODESPLIT] protected void copyStructures ( int recnum , StructureMembers . Member m , IndexIterator result ) { Array data = getArray ( recnum , m ) ; IndexIterator dataIter = data . getIndexIterator ( ) ; while ( dataIter . hasNext ( ) ) result . setObjectNext ( dataIter . getObjectNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data array of any type as an Object eg Float Double String StructureData etc . [CODESPLIT] public Object getScalarObject ( int recno , StructureMembers . Member m ) { DataType dataType = m . getDataType ( ) ; if ( dataType == DataType . DOUBLE ) { return getScalarDouble ( recno , m ) ; } else if ( dataType == DataType . FLOAT ) { return getScalarFloat ( recno , m ) ; } else if ( dataType . getPrimitiveClassType ( ) == byte . class ) { return getScalarByte ( recno , m ) ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { return getScalarShort ( recno , m ) ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { return getScalarInt ( recno , m ) ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { return getScalarLong ( recno , m ) ; } else if ( dataType == DataType . CHAR ) { return getScalarString ( recno , m ) ; } else if ( dataType == DataType . STRING ) { return getScalarString ( recno , m ) ; } else if ( dataType == DataType . STRUCTURE ) { return getScalarStructure ( recno , m ) ; } else if ( dataType == DataType . OPAQUE ) { ArrayObject data = ( ArrayObject ) m . getDataArray ( ) ; return data . getObject ( recno * m . getSize ( ) ) ; // LOOK ?? \r } throw new RuntimeException ( \"Dont have implementation for \" + dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar value as a float with conversion as needed . Underlying type must be convertible to float . [CODESPLIT] public float convertScalarFloat ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) == DataType . FLOAT ) return getScalarFloat ( recnum , m ) ; if ( m . getDataType ( ) == DataType . DOUBLE ) return ( float ) getScalarDouble ( recnum , m ) ; Object o = getScalarObject ( recnum , m ) ; if ( o instanceof Number ) return ( ( Number ) o ) . floatValue ( ) ; throw new ForbiddenConversionException ( \"Type is \" + m . getDataType ( ) + \", not convertible to float\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar value as a double with conversion as needed . Underlying type must be convertible to double . [CODESPLIT] public double convertScalarDouble ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) == DataType . DOUBLE ) return getScalarDouble ( recnum , m ) ; if ( m . getDataType ( ) == DataType . FLOAT ) return ( double ) getScalarFloat ( recnum , m ) ; Object o = getScalarObject ( recnum , m ) ; if ( o instanceof Number ) return ( ( Number ) o ) . doubleValue ( ) ; throw new ForbiddenConversionException ( \"Type is \" + m . getDataType ( ) + \", not convertible to double\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar value as an int with conversion as needed . Underlying type must be convertible to int . [CODESPLIT] public int convertScalarInt ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) == DataType . INT || m . getDataType ( ) == DataType . UINT ) return getScalarInt ( recnum , m ) ; if ( m . getDataType ( ) == DataType . SHORT ) return ( int ) getScalarShort ( recnum , m ) ; if ( m . getDataType ( ) == DataType . USHORT ) return DataType . unsignedShortToInt ( getScalarShort ( recnum , m ) ) ; if ( m . getDataType ( ) == DataType . BYTE ) return ( int ) getScalarByte ( recnum , m ) ; if ( m . getDataType ( ) == DataType . UBYTE ) return ( int ) DataType . unsignedByteToShort ( getScalarByte ( recnum , m ) ) ; if ( m . getDataType ( ) == DataType . LONG || m . getDataType ( ) == DataType . ULONG ) return ( int ) getScalarLong ( recnum , m ) ; Object o = getScalarObject ( recnum , m ) ; if ( o instanceof Number ) return ( ( Number ) o ) . intValue ( ) ; throw new ForbiddenConversionException ( \"Type is \" + m . getDataType ( ) + \", not convertible to int\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar member data of type float . [CODESPLIT] public float getScalarFloat ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) != DataType . FLOAT ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be float\" ) ; Array data = m . getDataArray ( ) ; return data . getFloat ( recnum * m . getSize ( ) ) ; // gets first one in the array\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar member data of type byte . [CODESPLIT] public byte getScalarByte ( int recnum , StructureMembers . Member m ) { if ( ! ( m . getDataType ( ) . getPrimitiveClassType ( ) == byte . class ) ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be byte\" ) ; Array data = m . getDataArray ( ) ; return data . getByte ( recnum * m . getSize ( ) ) ; // gets first one in the array\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar member data of type short . [CODESPLIT] public short getScalarShort ( int recnum , StructureMembers . Member m ) { if ( ! ( m . getDataType ( ) . getPrimitiveClassType ( ) == short . class ) ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be short\" ) ; Array data = m . getDataArray ( ) ; return data . getShort ( recnum * m . getSize ( ) ) ; // gets first one in the array\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get scalar member data of type char . [CODESPLIT] public char getScalarChar ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) != DataType . CHAR ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be char\" ) ; Array data = m . getDataArray ( ) ; return data . getChar ( recnum * m . getSize ( ) ) ; // gets first one in the array\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type String or char . [CODESPLIT] public String getScalarString ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) == DataType . CHAR ) { ArrayChar data = ( ArrayChar ) m . getDataArray ( ) ; return data . getString ( recnum ) ; } if ( m . getDataType ( ) == DataType . STRING ) { Array data = m . getDataArray ( ) ; return ( String ) data . getObject ( recnum ) ; } throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be String or char\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type Structure . [CODESPLIT] public StructureData getScalarStructure ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) != DataType . STRUCTURE ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be Structure\" ) ; ArrayStructure data = ( ArrayStructure ) m . getDataArray ( ) ; return data . getStructureData ( recnum * m . getSize ( ) ) ; // gets first in the array\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type array of Structure . [CODESPLIT] public ArrayStructure getArrayStructure ( int recnum , StructureMembers . Member m ) { if ( ( m . getDataType ( ) != DataType . STRUCTURE ) && ( m . getDataType ( ) != DataType . SEQUENCE ) ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be Structure or Sequence\" ) ; if ( m . getDataType ( ) == DataType . SEQUENCE ) return getArraySequence ( recnum , m ) ; ArrayStructure array = ( ArrayStructure ) m . getDataArray ( ) ; int count = m . getSize ( ) ; StructureData [ ] this_sdata = new StructureData [ count ] ; for ( int i = 0 ; i < count ; i ++ ) this_sdata [ i ] = array . getStructureData ( recnum * count + i ) ; // make a copy of the members, but remove the data arrays, since the structureData must be used instead\r StructureMembers membersw = new StructureMembers ( array . getStructureMembers ( ) ) ; return new ArrayStructureW ( membersw , m . getShape ( ) , this_sdata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type ArraySequence [CODESPLIT] public ArraySequence getArraySequence ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) != DataType . SEQUENCE ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be Sequence\" ) ; // should store sequences as ArrayObject of ArraySequence objects\r ArrayObject array = ( ArrayObject ) m . getDataArray ( ) ; return ( ArraySequence ) array . getObject ( recnum ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get member data of type ArrayObject [CODESPLIT] public ArrayObject getArrayObject ( int recnum , StructureMembers . Member m ) { if ( m . getDataType ( ) != DataType . OPAQUE ) throw new IllegalArgumentException ( \"Type is \" + m . getDataType ( ) + \", must be Sequence\" ) ; ArrayObject array = ( ArrayObject ) m . getDataArray ( ) ; return ( ArrayObject ) array . getObject ( recnum ) ; // LOOK ??\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "experimental [CODESPLIT] int setDirect ( int v0 , int v1 , int v2 ) { if ( v0 < 0 || v0 >= shape0 ) throw new ArrayIndexOutOfBoundsException ( ) ; if ( v1 < 0 || v1 >= shape1 ) throw new ArrayIndexOutOfBoundsException ( ) ; if ( v2 < 0 || v2 >= shape2 ) throw new ArrayIndexOutOfBoundsException ( ) ; return offset + v0 * stride0 + v1 * stride1 + v2 * stride2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Precalculate some stuff [CODESPLIT] private void precalculate ( ) { sinLat0 = Math . sin ( lat0 ) ; cosLat0 = Math . cos ( lat0 ) ; lon0Degrees = Math . toDegrees ( lon0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This returns true when the line between pt1 and pt2 crosses the seam . When the cone is flattened the seam is lon0 + - 180 . [CODESPLIT] public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { // either point is infinite\r if ( ProjectionPointImpl . isInfinite ( pt1 ) || ProjectionPointImpl . isInfinite ( pt2 ) ) return true ; // opposite signed X values, larger then 5000 km\r return ( pt1 . getX ( ) * pt2 . getX ( ) < 0 ) && ( Math . abs ( pt1 . getX ( ) - pt2 . getX ( ) ) > 5000.0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force an attribute value ( typically string ) to match a given basetype [CODESPLIT] static public Object attributeConvert ( DapType type , Object value ) { if ( value == null ) return value ; if ( type . isEnumType ( ) ) { if ( value instanceof String ) { // See if the constant is an int vs enum const name try { int ival = Integer . parseInt ( value . toString ( ) ) ; return ival ; } catch ( NumberFormatException nfe ) { // Assume it is an econst name; try to locate it DapEnumConst dec = ( ( DapEnumeration ) type ) . lookup ( value . toString ( ) ) ; if ( dec == null ) return value ; return dec . getValue ( ) ; } } else if ( value instanceof Long ) { return ( Long ) value ; } } else if ( value instanceof Long ) { return ( Long ) value ; } else if ( value instanceof Float ) { return ( Float ) value ; } else if ( value instanceof Double ) { return ( Double ) value ; } else if ( value instanceof Character ) { return ( ( Character ) value ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get the size of an equivalent java object ; zero if not defined [CODESPLIT] static public int getJavaSize ( TypeSort atomtype ) { switch ( atomtype ) { case Char : case Int8 : case UInt8 : return 1 ; case Int16 : case UInt16 : return 2 ; case Int32 : case UInt32 : return 4 ; case Int64 : case UInt64 : return 8 ; case Float32 : return 4 ; case Float64 : return 8 ; default : break ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force a numeric value to be in a specified range Only defined for simple integers ( ValueClass LONG ) WARNING : unsigned values are forced into the signed size but the proper bit pattern is maintained . The term force means that if the value is outside the typed min / max values it is pegged to the min or max value depending on the sign . Note that truncation is not used . [CODESPLIT] static public long forceRange ( TypeSort basetype , long value ) { assert basetype . isIntegerType ( ) : \"Internal error\" ; switch ( basetype ) { case Char : value = minmax ( value , 0 , 255 ) ; break ; case Int8 : value = minmax ( value , ( long ) Byte . MIN_VALUE , ( long ) Byte . MAX_VALUE ) ; break ; case UInt8 : value = value & 0xFF L ; break ; case Int16 : value = minmax ( value , ( long ) Short . MIN_VALUE , ( long ) Short . MAX_VALUE ) ; break ; case UInt16 : value = value & 0xFFFF L ; break ; case Int32 : value = minmax ( value , ( long ) Integer . MIN_VALUE , ( long ) Integer . MAX_VALUE ) ; break ; case UInt32 : value = value & 0xFFFFFFFF L ; break ; case Int64 : case UInt64 : break ; // value = value case Int64: default : } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peg a value to either the min or max depending on sign . [CODESPLIT] static protected long minmax ( long value , long min , long max ) { if ( value < min ) return min ; if ( value > max ) return max ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For removePrefix / path style servlet mappings . [CODESPLIT] public static String extractPath ( HttpServletRequest req , String removePrefix ) { // may be in pathInfo (Servlet) or servletPath (Controller) String dataPath = req . getPathInfo ( ) ; if ( dataPath == null ) { dataPath = req . getServletPath ( ) ; } if ( dataPath == null ) // not sure if this is possible return \"\" ; // removePrefix or \"/\"+removePrefix if ( removePrefix != null ) { if ( dataPath . startsWith ( removePrefix ) ) { dataPath = dataPath . substring ( removePrefix . length ( ) ) ; } else if ( dataPath . startsWith ( \"/\" ) ) { dataPath = dataPath . substring ( 1 ) ; if ( dataPath . startsWith ( removePrefix ) ) dataPath = dataPath . substring ( removePrefix . length ( ) ) ; } } if ( dataPath . startsWith ( \"/\" ) ) dataPath = dataPath . substring ( 1 ) ; if ( dataPath . contains ( \"..\" ) ) // LOOK what about escapes ?? throw new IllegalArgumentException ( \"path cannot contain '..'\" ) ; return dataPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////// [CODESPLIT] public static String getFileNameForResponse ( String pathInfo , NetcdfFileWriter . Version version ) { Preconditions . checkNotNull ( version , \"version == null\" ) ; return getFileNameForResponse ( pathInfo , version . getSuffix ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] public static void printProjArgs ( int Projection , double [ ] projargs ) { double NorthBound ; double SouthBound ; double WestBound ; double EastBound ; double RowInc ; double ColInc ; double Lat1 ; double Lat2 ; double PoleRow ; double PoleCol ; double CentralLat ; double CentralLon ; double CentralRow ; double CentralCol ; double Rotation ; /* radians */ double Cone ; double Hemisphere ; double ConeFactor ; double CosCentralLat ; double SinCentralLat ; double StereoScale ; double InvScale ; double CylinderScale ; switch ( Projection ) { case PROJ_GENERIC : case PROJ_LINEAR : case PROJ_CYLINDRICAL : case PROJ_SPHERICAL : NorthBound = projargs [ 0 ] ; WestBound = projargs [ 1 ] ; RowInc = projargs [ 2 ] ; ColInc = projargs [ 3 ] ; System . out . println ( \"Generic, Linear, Cylindrical, Spherical:\" ) ; System . out . println ( \"NB: \" + NorthBound + \", WB: \" + WestBound + \", rowInc: \" + RowInc + \", colInc: \" + ColInc ) ; break ; case PROJ_ROTATED : NorthBound = projargs [ 0 ] ; WestBound = projargs [ 1 ] ; RowInc = projargs [ 2 ] ; ColInc = projargs [ 3 ] ; CentralLat = projargs [ 4 ] ; CentralLon = projargs [ 5 ] ; Rotation = projargs [ 6 ] ; System . out . println ( \"Rotated:\" ) ; System . out . println ( \"NB: \" + NorthBound + \", WB: \" + WestBound + \", rowInc: \" + RowInc + \", colInc: \" + ColInc + \", clat: \" + CentralLat + \", clon: \" + CentralLon + \", rotation: \" + Rotation ) ; break ; case PROJ_LAMBERT : Lat1 = projargs [ 0 ] ; Lat2 = projargs [ 1 ] ; PoleRow = projargs [ 2 ] ; PoleCol = projargs [ 3 ] ; CentralLon = projargs [ 4 ] ; ColInc = projargs [ 5 ] ; System . out . println ( \"Lambert: \" ) ; System . out . println ( \"lat1: \" + Lat1 + \", lat2: \" + Lat2 + \", poleRow: \" + PoleRow + \", PoleCol: \" + PoleCol + \", clon: \" + CentralLon + \", colInc: \" + ColInc ) ; break ; case PROJ_STEREO : CentralLat = projargs [ 0 ] ; CentralLon = projargs [ 1 ] ; CentralRow = projargs [ 2 ] ; CentralCol = projargs [ 3 ] ; ColInc = projargs [ 4 ] ; System . out . println ( \"Stereo: \" ) ; System . out . println ( \"clat: \" + CentralLat + \", clon: \" + CentralLon + \", cRow: \" + CentralRow + \", cCol: \" + CentralCol + \", colInc: \" + ColInc ) ; break ; default : System . out . println ( \"Projection unknown\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate a filter with respect to a Sequence record . Assumes the filter has been canonicalized so that the lhs is a variable . [CODESPLIT] protected Object eval ( DapVariable var , DapSequence seq , DataCursor record , CEAST expr ) throws DapException { switch ( expr . sort ) { case CONSTANT : return expr . value ; case SEGMENT : return fieldValue ( var , seq , record , expr . name ) ; case EXPR : Object lhs = eval ( var , seq , record , expr . lhs ) ; Object rhs = ( expr . rhs == null ? null : eval ( var , seq , record , expr . rhs ) ) ; if ( rhs != null ) switch ( expr . op ) { case LT : return compare ( lhs , rhs ) < 0 ; case LE : return compare ( lhs , rhs ) <= 0 ; case GT : return compare ( lhs , rhs ) > 0 ; case GE : return compare ( lhs , rhs ) >= 0 ; case EQ : return lhs . equals ( rhs ) ; case NEQ : return ! lhs . equals ( rhs ) ; case REQ : return lhs . toString ( ) . matches ( rhs . toString ( ) ) ; case AND : return ( ( Boolean ) lhs ) && ( ( Boolean ) rhs ) ; } else switch ( expr . op ) { case NOT : return ! ( ( Boolean ) lhs ) ; } } throw new DapException ( \"Malformed Filter\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the view to a constraint string suitable for use in a URL except not URL encoded . [CODESPLIT] public String toConstraintString ( ) { StringBuilder buf = new StringBuilder ( ) ; boolean first = true ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { Segment seg = segments . get ( i ) ; if ( ! seg . var . isTopLevel ( ) ) continue ; if ( ! first ) buf . append ( \";\" ) ; first = false ; dumpvar ( seg , buf , true ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive helper for tostring / toConstraintString [CODESPLIT] protected void dumpvar ( Segment seg , StringBuilder buf , boolean forconstraint ) { if ( seg . var . isTopLevel ( ) ) buf . append ( seg . var . getFQN ( ) ) ; else buf . append ( seg . var . getShortName ( ) ) ; List < DapDimension > dimset = seg . var . getDimensions ( ) ; // Add any slices List < Slice > slices = seg . slices ; if ( slices == null ) dimset = new ArrayList < DapDimension > ( ) ; else assert ( dimset . size ( ) == 0 && DapUtil . isScalarSlices ( slices ) ) || ( dimset . size ( ) == slices . size ( ) ) ; for ( int i = 0 ; i < dimset . size ( ) ; i ++ ) { Slice slice = slices . get ( i ) ; DapDimension dim = dimset . get ( i ) ; try { buf . append ( forconstraint ? slice . toConstraintString ( ) : slice . toString ( ) ) ; } catch ( DapException de ) { } } DapType basetype = seg . var . getBaseType ( ) ; // if the var is atomic, then we are done if ( basetype . isAtomic ( ) ) return ; // If structure and all fields are in the view, then done if ( basetype . getTypeSort ( ) . isCompound ( ) ) { DapStructure struct = ( DapStructure ) basetype ; if ( ! isWholeCompound ( struct ) ) { // Need to insert {...} and recurse buf . append ( LBRACE ) ; boolean first = true ; for ( DapVariable field : struct . getFields ( ) ) { if ( ! first ) buf . append ( \";\" ) ; first = false ; Segment fseg = findSegment ( field ) ; dumpvar ( fseg , buf , forconstraint ) ; } buf . append ( RBRACE ) ; } if ( basetype . getTypeSort ( ) . isSeqType ( ) && seg . filter != null ) { buf . append ( \"|\" ) ; buf . append ( seg . filter . toString ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reference X match [CODESPLIT] public boolean references ( DapNode node ) { boolean isref = false ; switch ( node . getSort ( ) ) { case DIMENSION : DapDimension dim = this . redef . get ( ( DapDimension ) node ) ; if ( dim == null ) dim = ( DapDimension ) node ; isref = this . dimrefs . contains ( dim ) ; break ; case ENUMERATION : isref = ( this . enums . contains ( ( DapEnumeration ) node ) ) ; break ; case VARIABLE : isref = ( findVariableIndex ( ( DapVariable ) node ) >= 0 ) ; break ; case GROUP : case DATASET : isref = ( this . groups . contains ( ( DapGroup ) node ) ) ; break ; default : break ; } return isref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selection X match <p > Evaluate a filter with respect to a Sequence record . Assumes the filter has been canonicalized . [CODESPLIT] public boolean match ( DapVariable sqvar , DapSequence seq , DataCursor rec ) throws DapException { Segment sseq = findSegment ( sqvar ) ; if ( sseq == null ) return false ; CEAST filter = sseq . filter ; if ( filter == null ) return true ; return matches ( sqvar , seq , rec , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate a filter with respect to a Sequence record . [CODESPLIT] protected boolean matches ( DapVariable var , DapSequence seq , DataCursor rec , CEAST filter ) throws DapException { Object value = eval ( var , seq , rec , filter ) ; return ( ( Boolean ) value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Search the set of variables [CODESPLIT] protected int findVariableIndex ( DapVariable var ) { for ( int i = 0 ; i < variables . size ( ) ; i ++ ) { if ( variables . get ( i ) == var ) return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locate each unexpanded Structure|Sequence and : 1 . check that none of its fields is referenced = > do not expand 2 . add all of its fields as leaves Note that #2 may end up adding additional leaf structs & / or seqs [CODESPLIT] public void expand ( ) { // Create a queue of unprocessed leaf compounds Queue < DapVariable > queue = new ArrayDeque < DapVariable > ( ) ; for ( int i = 0 ; i < variables . size ( ) ; i ++ ) { DapVariable var = variables . get ( i ) ; if ( ! var . isTopLevel ( ) ) continue ; // prime the queue DapType base = var . getBaseType ( ) ; if ( base . getTypeSort ( ) . isCompound ( ) ) { DapStructure struct = ( DapStructure ) base ; // remember Sequence subclass Structure if ( expansionCount ( struct ) == 0 ) queue . add ( var ) ; } } // Process the queue in prefix order while ( queue . size ( ) > 0 ) { DapVariable vvstruct = queue . remove ( ) ; DapStructure dstruct = ( DapStructure ) vvstruct . getBaseType ( ) ; for ( DapVariable field : dstruct . getFields ( ) ) { if ( findVariableIndex ( field ) < 0 ) { // Add field as leaf this . segments . add ( new Segment ( field ) ) ; this . variables . add ( field ) ; } DapType fbase = field . getBaseType ( ) ; if ( fbase . getTypeSort ( ) . isCompound ( ) ) { if ( expansionCount ( ( DapStructure ) fbase ) == 0 ) queue . add ( field ) ; } } } this . expansion = Expand . EXPANDED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locate each Structure|Sequence and : 1 . check that all of its fields are referenced recursively and not constrained otherwise ignore 2 . contract by removing all of the fields of the Structure or Sequence . This is intended to be ( not quite ) the dual of expand () ; [CODESPLIT] public void contract ( ) { // Create a set of contracted compounds Set < DapStructure > contracted = new HashSet <> ( ) ; for ( int i = 0 ; i < variables . size ( ) ; i ++ ) { DapVariable var = variables . get ( i ) ; if ( var . isTopLevel ( ) ) { DapType base = var . getBaseType ( ) ; if ( base . getTypeSort ( ) . isCompound ( ) ) { contractR ( ( DapStructure ) base , contracted ) ; } } } this . expansion = Expand . CONTRACTED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive helper [CODESPLIT] protected boolean contractR ( DapStructure dstruct , Set < DapStructure > contracted ) { if ( contracted . contains ( dstruct ) ) return true ; int processed = 0 ; List < DapVariable > fields = dstruct . getFields ( ) ; for ( DapVariable field : fields ) { if ( findVariableIndex ( field ) < 0 ) break ; // this compound cannot be contracted DapType base = field . getBaseType ( ) ; if ( base . getTypeSort ( ) . isCompound ( ) && ! contracted . contains ( ( field ) ) ) { if ( ! contractR ( ( DapStructure ) base , contracted ) ) break ; // this compound cannot be contracted } processed ++ ; } if ( processed < fields . size ( ) ) return false ; contracted . add ( dstruct ) ; // all compound fields were successfully contracted. return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the number of fields of a structure that already in this view . [CODESPLIT] protected int expansionCount ( DapStructure struct ) { int count = 0 ; for ( DapVariable field : struct . getFields ( ) ) { if ( findVariableIndex ( field ) >= 0 ) count ++ ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if a structure is whole which means that none of its fields is missing from the constraint all of fields use default ( non - constrained ) dimension ) and all of its fields are also whole . This must be done recursively . [CODESPLIT] protected boolean isWholeCompound ( DapStructure dstruct ) { int processed = 0 ; List < DapVariable > fields = dstruct . getFields ( ) ; for ( DapVariable field : fields ) { // not contractable if this field has non-original dimensions Segment seg = findSegment ( field ) ; if ( seg == null ) break ; // this compound is not whole List < Slice > slices = seg . slices ; if ( slices != null ) { for ( Slice slice : slices ) { if ( slice . isConstrained ( ) ) break ; } } DapType base = field . getBaseType ( ) ; if ( base . getTypeSort ( ) . isCompound ( ) ) { if ( ! isWholeCompound ( ( DapStructure ) base ) ) break ; // this compound is not whole } processed ++ ; } return ( processed == fields . size ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute dimension related information using slicing and redef info . In effect this is where projection constraints are applied <p > Assume that the constraint compiler has given us the following info : <ol > <li > A list of the variables to include . <li > A pair ( DapDimension Slice ) for each redef <li > For each variable in #1 a list of slices taken from the constraint expression < / ol > <p > Two products will be produced . <ol > <li > The variables map will be modified so that the slices properly reflect any original or redef dimensions . <li > A set dimrefs of all referenced original dimensions . < / ol > <p > The processing is as follows <ol > <li > For each redef create a new redef dimension <li > For each variable : <ol > <li > if the variable is scalar do nothing . <li > if the variable has no associated slices then make its new dimensions be the original dimensions . <li > otherwise walk the slices and create new dimensions from them ; use redefs where indicated <li > < / ol > < / ol > [CODESPLIT] protected void computedimensions ( ) throws DapException { // Build the redefmap for ( DapDimension key : redefslice . keySet ( ) ) { Slice slice = redefslice . get ( key ) ; DapDimension newdim = ( DapDimension ) key . clone ( ) ; newdim . setSize ( slice . getCount ( ) ) ; redef . put ( key , newdim ) ; } // Process each variable for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { Segment seg = segments . get ( i ) ; if ( seg . var . getRank ( ) == 0 ) continue ; List < Slice > slices = seg . slices ; List < DapDimension > orig = seg . var . getDimensions ( ) ; List < DapDimension > newdims = new ArrayList <> ( ) ; // If the slice list is short then pad it with // default slices if ( slices == null ) slices = new ArrayList < Slice > ( ) ; while ( slices . size ( ) < orig . size ( ) ) // pad { slices . add ( new Slice ( ) . setConstrained ( false ) ) ; } assert ( slices != null && slices . size ( ) == orig . size ( ) ) ; for ( int j = 0 ; j < slices . size ( ) ; j ++ ) { Slice slice = slices . get ( j ) ; DapDimension dim0 = orig . get ( j ) ; DapDimension newdim = redef . get ( dim0 ) ; if ( newdim == null ) newdim = dim0 ; // fill in the undefined last value slice . setMaxSize ( newdim . getSize ( ) ) ; slice . finish ( ) ; Slice newslice = null ; if ( slice . isConstrained ( ) ) { // Construct an anonymous dimension for this slice newdim = new DapDimension ( slice . getCount ( ) ) ; } else { // replace with a new slice from the dim newslice = new Slice ( newdim ) ; if ( newslice != null ) { // track set of referenced non-anonymous dimensions if ( ! dimrefs . contains ( dim0 ) ) dimrefs . add ( dim0 ) ; slices . set ( j , newslice ) ; } } // record the dimension per variable newdims . add ( newdim ) ; } seg . setDimset ( newdims ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walk all the included variables and accumulate the referenced enums [CODESPLIT] protected void computeenums ( ) { for ( int i = 0 ; i < variables . size ( ) ; i ++ ) { DapVariable var = variables . get ( i ) ; if ( var . getSort ( ) != DapSort . VARIABLE ) continue ; DapType daptype = var . getBaseType ( ) ; if ( ! daptype . isEnumType ( ) ) continue ; if ( ! this . enums . contains ( ( DapEnumeration ) daptype ) ) this . enums . add ( ( DapEnumeration ) daptype ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walk all the included declarations and accumulate the set of referenced groups [CODESPLIT] protected void computegroups ( ) { // 1. variables for ( int i = 0 ; i < variables . size ( ) ; i ++ ) { DapVariable var = variables . get ( i ) ; List < DapGroup > path = var . getGroupPath ( ) ; for ( DapGroup group : path ) { if ( ! this . groups . contains ( group ) ) this . groups . add ( group ) ; } } // 2. Dimensions for ( DapDimension dim : this . dimrefs ) { if ( ! dim . isShared ( ) ) continue ; List < DapGroup > path = dim . getGroupPath ( ) ; for ( DapGroup group : path ) { if ( ! this . groups . contains ( group ) ) this . groups . add ( group ) ; } } // 2. enumerations for ( DapEnumeration en : this . enums ) { List < DapGroup > path = en . getGroupPath ( ) ; for ( DapGroup group : path ) { if ( ! this . groups . contains ( group ) ) this . groups . add ( group ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static Utility for compiling a constraint string [CODESPLIT] static public CEConstraint compile ( String sce , DapDataset dmr ) throws DapException { // Process any constraint if ( sce == null || sce . length ( ) == 0 ) return CEConstraint . getUniversal ( dmr ) ; CEParserImpl ceparser = new CEParserImpl ( dmr ) ; if ( PARSEDEBUG ) ceparser . setDebugLevel ( 1 ) ; if ( DEBUG ) { System . err . println ( \"Dap4Servlet: parsing constraint: |\" + sce + \"|\" ) ; } boolean ok ; try { ok = ceparser . parse ( sce ) ; } catch ( ParseException pe ) { ok = false ; } if ( ! ok ) throw new DapException ( \"Constraint parse failed: \" + sce ) ; CEAST root = ceparser . getCEAST ( ) ; CECompiler compiler = new CECompiler ( ) ; CEConstraint ce = compiler . compile ( dmr , root ) ; ce . expand ( ) ; ce . finish ( ) ; return ce ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the variable s declaration in a C - style syntax . This method is used to create textual representation of the Data Descriptor Structure ( DDS ) . [CODESPLIT] public final void printDecl ( PrintWriter os , String space , boolean print_semi ) { printDecl ( os , space , print_semi , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > PrimitiveVector< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { PrimitiveVector v = ( PrimitiveVector ) super . cloneDAG ( map ) ; v . var = ( BaseType ) cloneDAG ( map , var ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 1 ) single runtime 1a timeOffset 1b time or timeRange 1c none = constant runtime dataset 2 ) multiple runtimes 2a timeOffset = constant offset dataset 2b time ( not range ) = constant forecast dataset [CODESPLIT] public Optional < List < CoverageCoordAxis > > subset ( SubsetParams params , AtomicBoolean isConstantForcast , boolean makeCFcompliant ) { return Optional . empty ( \"not implemented by \" + getClass ( ) . getName ( ) ) ; /* List<CoverageCoordAxis> result = new ArrayList<>();\n\n    Optional<CoverageCoordAxis> axiso = runAxis.subset(params);\n    if (!axiso.isPresent())\n      return Optional.empty(axiso.getErrorMessage());\n    CoverageCoordAxis1D runAxisSubset = (CoverageCoordAxis1D) axiso.get();\n    result.add(runAxisSubset);\n\n    // subset on timeOffset (1a, 1c, 2a)\n    if (params.hasTimeOffsetParam() || !params.hasTimeParam()) {\n      axiso = timeAxis2D.subset(params);\n      if (!axiso.isPresent())\n        return Optional.empty(axiso.getErrorMessage());\n      CoverageCoordAxis timeOffsetSubset = axiso.get();\n      result.add(timeOffsetSubset);\n\n      if (makeCFcompliant)\n        result.add(makeCFTimeCoord(runAxisSubset, (CoverageCoordAxis1D) timeOffsetSubset)); // possible the twoD time case, if nruns > 1\n      return Optional.of(result);\n    }\n\n    // subset on time, # runtimes = 1 (1b)\n    if (runAxisSubset.getNcoords() == 1) {\n      double val = runAxisSubset.getCoord(0);   // not sure runAxis is needed. maybe use runtimeSubset\n      CalendarDate runDate = runAxisSubset.makeDate(val);\n      Optional<TimeOffsetAxis> too = timeAxis2D.subsetFromTime(params, runDate);\n      if (!too.isPresent())\n        return Optional.empty(too.getErrorMessage());\n      TimeOffsetAxis timeOffsetSubset =  too.get();\n      result.add(timeOffsetSubset);\n\n      if (makeCFcompliant)\n        result.add(makeCFTimeCoord(runAxisSubset, timeOffsetSubset));\n      return Optional.of(result);\n    }\n\n    // tricky case 2b time (point only not range) = constant forecast dataset\n    // data reader has to skip around the 2D times\n    // 1) the runtimes may be subset by whats available\n    // 2) timeOffset could become an aux coordinate\n    // 3) time coordinate becomes a scalar,\n    isConstantForcast.set(true);\n\n    CalendarDate dateWanted;\n    if (params.isTrue(SubsetParams.timePresent))\n      dateWanted = CalendarDate.present();\n    else\n      dateWanted = (CalendarDate) params.get(SubsetParams.time);\n    if (dateWanted == null)\n      throw new IllegalStateException(\"Must have time parameter\");\n\n    double wantOffset = runAxisSubset.convert(dateWanted); // forecastDate offset from refdate\n    double start = timeAxis.getStartValue();\n    double end = timeAxis.getEndValue();\n    CoordAxisHelper helper = new CoordAxisHelper(timeOffset);\n\n    // brute force search LOOK specialize for regular ?\n    List<Integer> runtimeIdx = new ArrayList<>();  // list of runtime indexes that have this forecast\n    // List<Integer> offsetIdx = new ArrayList<>();  // list of offset indexes that have this forecast\n    List<Double> offset = new ArrayList<>();      // corresponding offset from start of run\n    for (int i=0; i<runAxisSubset.getNcoords(); i++) {\n      // public double getOffsetInTimeUnits(CalendarDate convertFrom, CalendarDate convertTo);\n      double runOffset = runAxisSubset.getCoord(i);\n      if (end + runOffset < wantOffset) continue;\n      if (wantOffset < start + runOffset) break;\n      int idx = helper.search(wantOffset - runOffset);\n      if (idx >= 0) {\n        runtimeIdx.add(i);  // the ith runtime\n        // offsetIdx.add(idx);   // the idx time offset\n        offset.add(wantOffset - runOffset);   // the offset from the runtime\n      }\n    }\n\n    // here are the runtimes\n    int ncoords = runtimeIdx.size();\n    double[] runValues = new double[ncoords];\n    double[] offsetValues = new double[ncoords];\n    int count = 0;\n    for (int k=0; k<ncoords; k++) {\n      offsetValues[count] = offset.get(k);\n      runValues[count++] = runAxisSubset.getCoord( runtimeIdx.get(k));\n    }\n\n    CoverageCoordAxisBuilder runbuilder = new CoverageCoordAxisBuilder(runAxisSubset)\n            .subset(null, CoverageCoordAxis.Spacing.irregularPoint, ncoords, runValues); // LOOK check for regular (in CovCoordAxis ?)\n    CoverageCoordAxis1D runAxisSubset2 = new CoverageCoordAxis1D(runbuilder);\n\n    CoverageCoordAxisBuilder timebuilder = new CoverageCoordAxisBuilder(timeOffset)\n            .subset(runAxisSubset2.getName(), CoverageCoordAxis.Spacing.irregularPoint, ncoords, offsetValues); // aux coord (LOOK interval) ??\n    CoverageCoordAxis1D timeOffsetSubset = new TimeOffsetAxis(timebuilder);\n\n    CoverageCoordAxis scalarTimeCoord = makeScalarTimeCoord(wantOffset, runAxisSubset);\n\n    // nothing needed for CF, the run coordinate acts as the CF time independent coord. timeOffset is aux, forecastTime is scalar\n    return Optional.of(Lists.newArrayList(runAxisSubset2, timeOffsetSubset, scalarTimeCoord)); // */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "accept grib2 or ncx files [CODESPLIT] @ Override public boolean isValidFile ( RandomAccessFile raf ) throws IOException { if ( raf instanceof HTTPRandomAccessFile ) { // only do remote if memory resident if ( raf . length ( ) > raf . getBufferSize ( ) ) return false ; } else { // wont accept remote index GribCdmIndex . GribCollectionType type = GribCdmIndex . getType ( raf ) ; if ( type == GribCdmIndex . GribCollectionType . GRIB2 ) return true ; if ( type == GribCdmIndex . GribCollectionType . Partition2 ) return true ; } // check for GRIB2 data file return Grib2RecordScanner . isValidFile ( raf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save all data in the PersistentStore [CODESPLIT] public void storePersistentData ( ) { store . putBeanObject ( VIEWER_SIZE , getSize ( ) ) ; store . putBeanObject ( SOURCE_WINDOW_SIZE , ( Rectangle ) sourceWindow . getBounds ( ) ) ; if ( fileChooser != null ) fileChooser . save ( ) ; if ( datasetChooser != null ) datasetChooser . save ( ) ; if ( sourcePane != null ) sourcePane . save ( ) ; /* if (catEditor != null) catEditor.save();\n    if (catCrawler != null) catCrawler.save();\n    if (serverConfigure != null) serverConfigure.save();\n    if (catCopier != null) catCopier.save();   */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "actions that are system - wide [CODESPLIT] private void makeActionsSystem ( ) { /* aboutAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent evt) {\n        new AboutWindow();\n      }\n    };\n    BAMutil.setActionProperties( aboutAction, null, \"About\", false, 'A', 0); */ /* printAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        PrinterJob printJob = PrinterJob.getPrinterJob();\n        PageFormat pf = printJob.defaultPage();\n\n        // do we need to rotate ??\n        if (panz.wantRotate( pf.getImageableWidth(), pf.getImageableHeight()))\n          pf.setOrientation( PageFormat.LANDSCAPE);\n        else\n          pf.setOrientation(PageFormat.PORTRAIT);\n\n        printJob.setPrintable(controller.getPrintable(), pf);\n        if (printJob.printDialog()) {\n          try {\n            if (Debug.isSet(\"print.job\")) System.out.println(\"call printJob.print\");\n            printJob.print();\n            if (Debug.isSet(\"print.job\")) System.out.println(\" printJob done\");\n          } catch (Exception PrintException) {\n            PrintException.printStackTrace();\n          }\n        }\n      }\n    };\n    BAMutil.setActionProperties( printAction, \"Print\", \"Print...\", false, 'P', KeyEvent.VK_P);\n\n    sysConfigAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        if (sysConfigDialog == null)\n          makeSysConfigWindow();\n        sysConfigDialog.show();\n      }\n    };\n    BAMutil.setActionProperties( sysConfigAction, \"Preferences\", \"Configure...\", false, 'C', -1);\n\n    clearDebugFlagsAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) { Debug.clear(); }\n    };\n    BAMutil.setActionProperties( clearDebugFlagsAction, null, \"Clear DebugFlags\", false, 'D', -1);\n\n    clearRecentAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        recentDatasetList = new ArrayList();\n      }\n    };\n    BAMutil.setActionProperties( clearRecentAction, null, \"Clear Recent Datasets\", false, 'R', -1);\n    */ AbstractAction clearDebugFlagsAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { /* Debug.clear(); */ } } ; BAMutil . setActionProperties ( clearDebugFlagsAction , null , \"Clear Debug Flags\" , false , ' ' , - 1 ) ; /* AbstractAction setDebugFlagsAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        // LOOK set netcdf debug flags\n\n        InvCatalogFactory.debugURL = Debug.isSet(\"InvCatalogFactory/debugURL\");\n        InvCatalogFactory.debugOpen = Debug.isSet(\"InvCatalogFactory/debugOpen\");\n        InvCatalogFactory.debugVersion = Debug.isSet(\"InvCatalogFactory/debugVersion\");\n        InvCatalogFactory.showParsedXML = Debug.isSet(\"InvCatalogFactory/showParsedXML\");\n        InvCatalogFactory.showStackTrace = Debug.isSet(\"InvCatalogFactory/showStackTrace\");\n        InvCatalogFactory.debugXML = Debug.isSet(\"InvCatalogFactory/debugXML\");\n        InvCatalogFactory.debugDBurl = Debug.isSet(\"InvCatalogFactory/debugDBurl\");\n        InvCatalogFactory.debugXMLopen = Debug.isSet(\"InvCatalogFactory/debugXMLopen\");\n        InvCatalogFactory.showCatalogXML = Debug.isSet(\"InvCatalogFactory/showCatalogXML\");\n      }\n    };\n    BAMutil.setActionProperties(setDebugFlagsAction, null, \"Set Debug Flags\", false, 'S', -1);  */ /* exitAction = new AbstractAction() {\n      public void actionPerformed(ActionEvent e) {\n        topLevel.close();\n      }\n    };\n    BAMutil.setActionProperties( exitAction, \"Exit\", \"Exit\", false, 'X', -1); */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////// [CODESPLIT] boolean init ( ) { System . setProperty ( \"tds.log.dir\" , contentTdmDir . toString ( ) ) ; if ( ! Files . exists ( threddsConfig ) ) { log . error ( \"config file {} does not exist, set -Dtds.content.root.path=<dir>\" , threddsConfig ) ; System . out . printf ( \"threddsConfig does not exist=%s%n\" , threddsConfig ) ; return false ; } ThreddsConfigReader reader = new ThreddsConfigReader ( threddsConfig . toString ( ) , log ) ; for ( String location : reader . getRootList ( \"catalogRoot\" ) ) { Resource r = new FileSystemResource ( contentThreddsDir . toString ( ) + \"/\" + location ) ; catalogRoots . add ( r ) ; } // LOOK check TdsInit /* 4.3.15: grib index file placement, using DiskCache2  */ String gribIndexDir = reader . get ( \"GribIndex.dir\" , new File ( contentThreddsDir . toString ( ) , \"cache/grib/\" ) . getPath ( ) ) ; Boolean gribIndexAlwaysUse = reader . getBoolean ( \"GribIndex.alwaysUse\" , false ) ; Boolean gribIndexNeverUse = reader . getBoolean ( \"GribIndex.neverUse\" , false ) ; String gribIndexPolicy = reader . get ( \"GribIndex.policy\" , null ) ; DiskCache2 gribCache = gribIndexNeverUse ? DiskCache2 . getNoop ( ) : new DiskCache2 ( gribIndexDir , false , - 1 , - 1 ) ; gribCache . setPolicy ( gribIndexPolicy ) ; gribCache . setAlwaysUseCache ( gribIndexAlwaysUse ) ; gribCache . setNeverUseCache ( gribIndexNeverUse ) ; GribIndexCache . setDiskCache2 ( gribCache ) ; log . info ( \"TDM set \" + gribCache ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public static GempakFileReader getInstance ( RandomAccessFile raf , boolean fullCheck ) throws IOException { GempakFileReader gfr = new GempakFileReader ( ) ; gfr . init ( raf , fullCheck ) ; return gfr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public boolean init ( RandomAccessFile raf , boolean fullCheck ) throws IOException { setByteOrder ( ) ; rf = raf ; fileSize = rf . length ( ) ; raf . seek ( 0 ) ; return init ( fullCheck ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { if ( rf == null ) { throw new IOException ( \"file has not been set\" ) ; } dmLabel = new DMLabel ( ) ; boolean labelOk = dmLabel . init ( ) ; if ( ! labelOk ) { logError ( \"not a GEMPAK file\" ) ; return false ; } // Read the keys  (DM_RKEY) readKeys ( ) ; if ( keys == null ) { logError ( \"Couldn't read keys\" ) ; return false ; } // Read the headers (DM_RHDA) readHeaders ( ) ; if ( headers == null ) { logError ( \"Couldn't read headers\" ) ; return false ; } // Read the parts (DM_RPRT) readParts ( ) ; if ( parts == null ) { logError ( \"Couldn't read parts\" ) ; return false ; } // Read the file header info (DM_RFIL) readFileHeaderInfo ( ) ; if ( fileHeaderInfo == null ) { logError ( \"Couldn't read file header info\" ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the byte order for the machine type . [CODESPLIT] public int getByteOrder ( int kmachn ) { if ( ( kmachn == MTVAX ) || ( kmachn == MTULTX ) || ( kmachn == MTALPH ) || ( kmachn == MTLNUX ) || ( kmachn == MTIGPH ) ) { return RandomAccessFile . LITTLE_ENDIAN ; } return RandomAccessFile . BIG_ENDIAN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK WTF ?? Set the machine type for this system . [CODESPLIT] void setByteOrder ( ) { String arch = System . getProperty ( \"os.arch\" ) ; if ( arch . equals ( \"x86\" ) || // Windows, Linux arch . equals ( \"arm\" ) || // Window CE arch . equals ( \"x86_64\" ) || // Windows64, Mac OS-X arch . equals ( \"amd64\" ) || // Linux64? arch . equals ( \"alpha\" ) ) { // Utrix, VAX, DECOS MTMACH = RandomAccessFile . LITTLE_ENDIAN ; } else { MTMACH = RandomAccessFile . BIG_ENDIAN ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the file header info ( DM_RFIL ) [CODESPLIT] protected void readFileHeaderInfo ( ) throws IOException { if ( dmLabel == null ) { return ; } int iread = dmLabel . kpfile ; int numheaders = dmLabel . kfhdrs ; String [ ] names = new String [ numheaders ] ; int [ ] lens = new int [ numheaders ] ; int [ ] types = new int [ numheaders ] ; for ( int i = 0 ; i < numheaders ; i ++ ) { names [ i ] = DM_RSTR ( iread ++ ) ; } for ( int i = 0 ; i < numheaders ; i ++ ) { lens [ i ] = DM_RINT ( iread ++ ) ; } for ( int i = 0 ; i < numheaders ; i ++ ) { types [ i ] = DM_RINT ( iread ++ ) ; } fileHeaderInfo = new ArrayList <> ( ) ; for ( int i = 0 ; i < numheaders ; i ++ ) { DMFileHeaderInfo ghi = new DMFileHeaderInfo ( ) ; ghi . kfhnam = names [ i ] ; ghi . kfhlen = lens [ i ] ; ghi . kfhtyp = types [ i ] ; fileHeaderInfo . add ( ghi ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in the row and column keys ( DM_KEY ) [CODESPLIT] protected void readKeys ( ) throws IOException { if ( dmLabel == null ) { return ; } keys = new DMKeys ( ) ; // read the row keys int num = dmLabel . krkeys ; List < Key > rkeys = new ArrayList <> ( num ) ; for ( int i = 0 ; i < num ; i ++ ) { String key = DM_RSTR ( dmLabel . kprkey + i ) ; rkeys . add ( new Key ( key , i , ROW ) ) ; } keys . kkrow = rkeys ; num = dmLabel . kckeys ; List < Key > ckeys = new ArrayList <> ( num ) ; for ( int i = 0 ; i < num ; i ++ ) { String key = DM_RSTR ( dmLabel . kpckey + i ) ; ckeys . add ( new Key ( key , i , COL ) ) ; } keys . kkcol = ckeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the headers ( DM_RHDA ) [CODESPLIT] protected void readHeaders ( ) throws IOException { if ( dmLabel == null ) { return ; } headers = new DMHeaders ( ) ; List < int [ ] > rowHeaders = new ArrayList <> ( dmLabel . krow ) ; int istart = dmLabel . kprowh ; // first word is a valid flag so we have to add 1 to size int [ ] header ; for ( int i = 0 ; i < dmLabel . krow ; i ++ ) { header = new int [ dmLabel . krkeys + 1 ] ; DM_RINT ( istart , header ) ; if ( header [ 0 ] != IMISSD ) { headers . lstrw = i ; } rowHeaders . add ( header ) ; istart += header . length ; } headers . rowHeaders = rowHeaders ; List < int [ ] > colHeaders = new ArrayList <> ( dmLabel . kcol ) ; istart = dmLabel . kpcolh ; for ( int i = 0 ; i < dmLabel . kcol ; i ++ ) { header = new int [ dmLabel . kckeys + 1 ] ; DM_RINT ( istart , header ) ; if ( header [ 0 ] != IMISSD ) { headers . lstcl = i ; } colHeaders . add ( header ) ; istart += header . length ; } headers . colHeaders = colHeaders ; // some of the words are characters if ( needToSwap ) { int [ ] keyLoc = new int [ swapKeys . length ] ; String [ ] keyType = new String [ swapKeys . length ] ; boolean haveRow = false ; boolean haveCol = false ; for ( int i = 0 ; i < swapKeys . length ; i ++ ) { Key key = findKey ( swapKeys [ i ] ) ; keyLoc [ i ] = ( key != null ) ? key . loc + 1 : 0 ; keyType [ i ] = ( key != null ) ? key . type : \"\" ; if ( keyType [ i ] . equals ( ROW ) ) { haveRow = true ; } if ( keyType [ i ] . equals ( COL ) ) { haveCol = true ; } } if ( haveRow ) { for ( int [ ] toCheck : headers . rowHeaders ) { for ( int j = 0 ; j < swapKeys . length ; j ++ ) { if ( keyType [ j ] . equals ( ROW ) ) { if ( swapKeys [ j ] . equals ( \"GVCD\" ) && ! ( toCheck [ keyLoc [ j ] ] > GempakUtil . vertCoords . length ) ) { continue ; } GempakUtil . swp4 ( toCheck , keyLoc [ j ] , swapNum [ j ] ) ; } } } } if ( haveCol ) { for ( int [ ] toCheck : headers . colHeaders ) { for ( int j = 0 ; j < swapKeys . length ; j ++ ) { if ( keyType [ j ] . equals ( COL ) ) { if ( swapKeys [ j ] . equals ( \"GVCD\" ) && ! ( toCheck [ keyLoc [ j ] ] > GempakUtil . vertCoords . length ) ) { continue ; } GempakUtil . swp4 ( toCheck , keyLoc [ j ] , swapNum [ j ] ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the parts ( DM_RPRT ) [CODESPLIT] protected void readParts ( ) throws IOException { if ( dmLabel == null ) { return ; } int iread = dmLabel . kppart ; int numParts = dmLabel . kprt ; DMPart [ ] partArray = new DMPart [ numParts ] ; // read the part names for ( int i = 0 ; i < numParts ; i ++ ) { partArray [ i ] = new DMPart ( ) ; partArray [ i ] . kprtnm = DM_RSTR ( iread ++ ) ; } // read the part header lengths for ( int i = 0 ; i < numParts ; i ++ ) { partArray [ i ] . klnhdr = DM_RINT ( iread ++ ) ; } // read the part types for ( int i = 0 ; i < numParts ; i ++ ) { partArray [ i ] . ktyprt = DM_RINT ( iread ++ ) ; } // get number of parameters/per part. for ( int i = 0 ; i < numParts ; i ++ ) { partArray [ i ] . kparms = DM_RINT ( iread ++ ) ; } // read parameter names for ( int i = 0 ; i < numParts ; i ++ ) { int numParms = partArray [ i ] . kparms ; List < DMParam > parms = new ArrayList <> ( numParms ) ; for ( int j = 0 ; j < numParms ; j ++ ) { DMParam dmp = new DMParam ( ) ; parms . add ( dmp ) ; dmp . kprmnm = DM_RSTR ( iread ++ ) ; } partArray [ i ] . params = parms ; } // read the scale for ( int i = 0 ; i < numParts ; i ++ ) { int numParms = partArray [ i ] . kparms ; List parms = partArray [ i ] . params ; for ( int j = 0 ; j < numParms ; j ++ ) { DMParam dmp = ( DMParam ) parms . get ( j ) ; dmp . kscale = DM_RINT ( iread ++ ) ; } } // read the offset for ( int i = 0 ; i < numParts ; i ++ ) { int numParms = partArray [ i ] . kparms ; List parms = partArray [ i ] . params ; for ( int j = 0 ; j < numParms ; j ++ ) { DMParam dmp = ( DMParam ) parms . get ( j ) ; dmp . koffst = DM_RINT ( iread ++ ) ; } } // read the nbits for ( int i = 0 ; i < numParts ; i ++ ) { int numParms = partArray [ i ] . kparms ; List parms = partArray [ i ] . params ; for ( int j = 0 ; j < numParms ; j ++ ) { DMParam dmp = ( DMParam ) parms . get ( j ) ; dmp . kbits = DM_RINT ( iread ++ ) ; } } parts = new ArrayList <> ( numParts ) ; parts . addAll ( Arrays . asList ( partArray ) . subList ( 0 , numParts ) ) ; for ( DMPart part : parts ) { if ( part . ktyprt == MDRPCK ) { part . packInfo = new PackingInfo ( part ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the program [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length == 0 ) { System . out . println ( \"need to supply a GEMPAK grid file name\" ) ; System . exit ( 1 ) ; } GempakFileReader gfr = getInstance ( getFile ( args [ 0 ] ) , true ) ; gfr . printFileLabel ( ) ; gfr . printKeys ( ) ; gfr . printHeaders ( ) ; gfr . printParts ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a key with the given name [CODESPLIT] public Key findKey ( String name ) { if ( keys == null ) { return null ; } // search rows for ( Key key : keys . kkrow ) { if ( key . name . equals ( name ) ) { return key ; } } // search columns for ( Key key : keys . kkcol ) { if ( key . name . equals ( name ) ) { return key ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the file header with this name [CODESPLIT] public DMFileHeaderInfo findFileHeader ( String name ) { if ( ( fileHeaderInfo == null ) || fileHeaderInfo . isEmpty ( ) ) { return null ; } for ( DMFileHeaderInfo fhi : fileHeaderInfo ) { if ( name . equals ( fhi . kfhnam ) ) { return fhi ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in the values for the file header [CODESPLIT] public float [ ] getFileHeader ( String name ) throws IOException { DMFileHeaderInfo fh = findFileHeader ( name ) ; if ( ( fh == null ) || ( fh . kfhtyp != MDREAL ) ) { return null ; } int knt = fileHeaderInfo . indexOf ( fh ) ; // 0 based int iread = dmLabel . kpfile + 3 * dmLabel . kfhdrs ; for ( int i = 0 ; i < knt ; i ++ ) { DMFileHeaderInfo fhi = fileHeaderInfo . get ( i ) ; iread = iread + fhi . kfhlen + 1 ; } int nword = DM_RINT ( iread ) ; if ( nword <= 0 ) { logError ( \"Invalid header length for \" + name ) ; return null ; } iread ++ ; float [ ] rheader = new float [ nword ] ; if ( name . equals ( \"NAVB\" ) && needToSwap ) { DM_RFLT ( iread , 1 , rheader , 0 ) ; needToSwap = false ; iread ++ ; DM_RFLT ( iread , 1 , rheader , 1 ) ; needToSwap = true ; iread ++ ; DM_RFLT ( iread , nword - 2 , rheader , 2 ) ; } else { DM_RFLT ( iread , rheader ) ; } return rheader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the part information [CODESPLIT] public void printParts ( ) { if ( parts == null ) { return ; } for ( int i = 0 ; i < parts . size ( ) ; i ++ ) { System . out . println ( \"\\nParts[\" + i + \"]:\" ) ; System . out . println ( parts . get ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the part with the particular name . [CODESPLIT] public int getPartNumber ( String name ) { int part = 0 ; if ( ( parts != null ) && ! parts . isEmpty ( ) ) { for ( int i = 0 ; i < parts . size ( ) ; i ++ ) { String partName = parts . get ( i ) . kprtnm ; if ( partName . equals ( name ) ) { // gotta add 1 because parts are 1 based part = i + 1 ; break ; } } } return part ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the part with the particular name . [CODESPLIT] public DMPart getPart ( String name ) { if ( ( parts != null ) && ! parts . isEmpty ( ) ) { for ( DMPart part : parts ) { String partName = part . kprtnm ; if ( partName . equals ( name ) ) { return part ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pointer to the data . Taken from DM_RDTR [CODESPLIT] public int getDataPointer ( int irow , int icol , String partName ) { int ipoint = - 1 ; if ( ( irow < 1 ) || ( irow > dmLabel . krow ) || ( icol < 1 ) || ( icol > dmLabel . kcol ) ) { System . out . println ( \"bad row or column number: \" + irow + \"/\" + icol ) ; return ipoint ; } int iprt = getPartNumber ( partName ) ; if ( iprt == 0 ) { System . out . println ( \"couldn't find part\" ) ; return ipoint ; } // gotta subtract 1 because parts are 1 but List is 0 based DMPart part = parts . get ( iprt - 1 ) ; // check for valid data type if ( ( part . ktyprt != MDREAL ) && ( part . ktyprt != MDGRID ) && ( part . ktyprt != MDRPCK ) ) { System . out . println ( \"Not a valid type\" ) ; return ipoint ; } int ilenhd = part . klnhdr ; ipoint = dmLabel . kpdata + ( irow - 1 ) * dmLabel . kcol * dmLabel . kprt + ( icol - 1 ) * dmLabel . kprt + ( iprt - 1 ) ; return ipoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an integer [CODESPLIT] public int DM_RINT ( int word ) throws IOException { if ( rf == null ) { throw new IOException ( \"DM_RINT: no file to read from\" ) ; } if ( dmLabel == null ) { throw new IOException ( \"DM_RINT: reader not initialized\" ) ; } rf . seek ( getOffset ( word ) ) ; // set the order if ( needToSwap ) { //if ((dmLabel.kmachn != MTMACH) && //   ((dmLabel.kvmst && ! mvmst) || //   (mvmst && !dmLabel.kvmst))) { rf . order ( RandomAccessFile . LITTLE_ENDIAN ) ; // swap } else { rf . order ( RandomAccessFile . BIG_ENDIAN ) ; } int idata = rf . readInt ( ) ; if ( IMISSD != dmLabel . kmissd ) { if ( idata == dmLabel . kmissd ) { idata = IMISSD ; } } rf . order ( RandomAccessFile . BIG_ENDIAN ) ; return idata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read into an array of ints . [CODESPLIT] public void DM_RINT ( int word , int num , int [ ] iarray , int start ) throws IOException { for ( int i = 0 ; i < num ; i ++ ) { if ( start + i > iarray . length ) { throw new IOException ( \"DM_RINT: start+num exceeds iarray length\" ) ; } iarray [ start + i ] = DM_RINT ( word + i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a float [CODESPLIT] public float DM_RFLT ( int word ) throws IOException { if ( rf == null ) { throw new IOException ( \"DM_RFLT: no file to read from\" ) ; } if ( dmLabel == null ) { throw new IOException ( \"DM_RFLT: reader not initialized\" ) ; } rf . seek ( getOffset ( word ) ) ; if ( needToSwap ) { // set the order //if ((dmLabel.kmachn != MTMACH) && //   ((dmLabel.kvmst && ! mvmst) || //   (mvmst && !dmLabel.kvmst))) { rf . order ( RandomAccessFile . LITTLE_ENDIAN ) ; // swap } else { rf . order ( RandomAccessFile . BIG_ENDIAN ) ; } float rdata = rf . readFloat ( ) ; if ( RMISSD != dmLabel . smissd ) { if ( Math . abs ( rdata - dmLabel . smissd ) < RDIFFD ) { rdata = RMISSD ; } } // reset to read normally rf . order ( RandomAccessFile . BIG_ENDIAN ) ; return rdata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read into an array of ints . [CODESPLIT] public void DM_RFLT ( int word , int num , float [ ] rarray , int start ) throws IOException { for ( int i = 0 ; i < num ; i ++ ) { if ( start + i > rarray . length ) { throw new IOException ( \"DM_RFLT: start+num exceeds rarray length\" ) ; } rarray [ start + i ] = DM_RFLT ( word + i ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a String [CODESPLIT] public String DM_RSTR ( int isword , int nchar ) throws IOException { if ( rf == null ) { throw new IOException ( \"DM_RSTR: no file to read from\" ) ; } rf . seek ( getOffset ( isword ) ) ; return rf . readString ( nchar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data [CODESPLIT] public RData DM_RDTR ( int irow , int icol , String partName ) throws IOException { return DM_RDTR ( irow , icol , partName , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the real ( float ) data [CODESPLIT] public RData DM_RDTR ( int irow , int icol , String partName , int decimalScale ) throws IOException { int ipoint = - 1 ; if ( ( irow < 1 ) || ( irow > dmLabel . krow ) || ( icol < 1 ) || ( icol > dmLabel . kcol ) ) { System . out . println ( \"bad row/column number \" + irow + \"/\" + icol ) ; return null ; } //System.out.println(\"reading row \" + irow + \", column \" + icol); int iprt = getPartNumber ( partName ) ; if ( iprt == 0 ) { System . out . println ( \"couldn't find part: \" + partName ) ; return null ; } // gotta subtract 1 because parts are 1 but List is 0 based DMPart part = parts . get ( iprt - 1 ) ; // check for valid real data type if ( ( part . ktyprt != MDREAL ) && ( part . ktyprt != MDGRID ) && ( part . ktyprt != MDRPCK ) ) { System . out . println ( \"Not a valid type\" ) ; return null ; } int ilenhd = part . klnhdr ; ipoint = dmLabel . kpdata + ( irow - 1 ) * dmLabel . kcol * dmLabel . kprt + ( icol - 1 ) * dmLabel . kprt + ( iprt - 1 ) ; float [ ] rdata ; int [ ] header = null ; int istart = DM_RINT ( ipoint ) ; if ( istart == 0 ) { return null ; } // start catching up here because some files are incorrectly written try { int length = DM_RINT ( istart ) ; int isword = istart + 1 ; if ( length <= ilenhd ) { //System.out.println(\"length (\" + length //                   + \") is less than header length (\" + ilenhd //                   + \")\"); return null ; } else if ( Math . abs ( length ) > 10000000 ) { //System.out.println(\"length is huge\"); return null ; } header = new int [ ilenhd ] ; DM_RINT ( isword , header ) ; int nword = length - ilenhd ; isword += header . length ; if ( part . ktyprt == MDREAL ) { rdata = new float [ nword ] ; DM_RFLT ( isword , rdata ) ; } else if ( part . ktyprt == MDGRID ) { rdata = DM_RPKG ( isword , nword , decimalScale ) ; } else { //  packed ints int [ ] idata = new int [ nword ] ; DM_RINT ( isword , idata ) ; rdata = DM_UNPK ( part , idata ) ; } } catch ( EOFException eof ) { //System.err.println(\"reading off end of file\"); rdata = null ; } RData rd = null ; if ( rdata != null ) { rd = new RData ( header , rdata ) ; } return rd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unpack an array of packed integers . [CODESPLIT] public float [ ] DM_UNPK ( DMPart part , int [ ] ibitst ) { int nparms = part . kparms ; int nwordp = part . kwordp ; int npack = ( ibitst . length - 1 ) / nwordp + 1 ; if ( npack * nwordp != ibitst . length ) { //logError(\"number of packed records not correct\"); // System.out.println(\"number of packed records not correct: \" //                   + npack * nwordp + \" vs. \" + ibitst.length); return null ; } float [ ] data = new float [ nparms * npack ] ; PackingInfo pkinf = part . packInfo ; int ir = 0 ; int ii = 0 ; for ( int pack = 0 ; pack < npack ; pack ++ ) { // //  Move bitstring into internal words.  TODO: necessary? // int [ ] jdata = new int [ nwordp ] ; System . arraycopy ( ibitst , ii , jdata , 0 , nwordp ) ; // //  Extract each data value. // for ( int idata = 0 ; idata < nparms ; idata ++ ) { // //  Extract correct bits from words using shift and mask //  operations. // int jbit = pkinf . nbitsc [ idata ] ; int jsbit = pkinf . isbitc [ idata ] ; int jshift = 1 - jsbit ; int jsword = pkinf . iswrdc [ idata ] ; int jword = jdata [ jsword ] ; // use >>> to shift avoid carrying sign along int mask = mskpat >>> ( 32 - jbit ) ; int ifield = jword >>> Math . abs ( jshift ) ; ifield = ifield & mask ; if ( ( jsbit + jbit - 1 ) > 32 ) { jword = jdata [ jsword + 1 ] ; jshift = jshift + 32 ; int iword = jword << jshift ; iword = iword & mask ; ifield = ifield | iword ; } // //  The integer data is now in ifield.  Use the scaling and //  offset terms to convert to REAL data. // if ( ifield == pkinf . imissc [ idata ] ) { data [ ir + idata ] = RMISSD ; } else { data [ ir + idata ] = ( ifield + pkinf . koffst [ idata ] ) * ( float ) pkinf . scalec [ idata ] ; } } ir += nparms ; ii += nwordp ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a bit string for an integer [CODESPLIT] protected static String getBits ( int b ) { Formatter s = new Formatter ( ) ; for ( int i = 31 ; i >= 0 ; i -- ) { if ( ( b & ( 1 << i ) ) != 0 ) { s . format ( \"1\" ) ; } else { s . format ( \"0\" ) ; } if ( i % 8 == 0 ) { s . format ( \"|\" ) ; } } return s . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public void writeDataAll ( WritableByteChannel channel ) throws IOException , InvalidRangeException { for ( Vinfo vinfo : vinfoList ) { if ( ! vinfo . isRecord ) { Variable v = vinfo . v ; // assert filePos == vinfo.offset; //if (debugPos) System.out.println(\" writing at \"+filePos+\" should be \"+vinfo.offset+\" \"+v.getFullName()); int nbytes = ( int ) v . readToByteChannel ( v . getShapeAsSection ( ) , channel ) ; filePos += nbytes ; filePos += pad ( channel , nbytes ) ; if ( debugPos ) System . out . printf ( \" read=%d vinfo=%s%n\" , nbytes , vinfo ) ; } } // must use record dimension if it exists+ boolean useRecordDimension = ncfile . hasUnlimitedDimension ( ) ; if ( useRecordDimension ) { ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; Structure recordVar = ( Structure ) ncfile . findVariable ( \"record\" ) ; Section section = new Section ( ) . appendRange ( null ) ; long bytesDone = 0 ; long done = 0 ; long nrecs = ( int ) recordVar . getSize ( ) ; int structureSize = recordVar . getElementSize ( ) ; int readAtaTime = Math . max ( 10 , buffer_size / structureSize ) ; for ( int count = 0 ; count < nrecs ; count += readAtaTime ) { long last = Math . min ( nrecs , done + readAtaTime ) ; // dont go over nrecs int need = ( int ) ( last - done ) ; // how many to read this time section . setRange ( 0 , new Range ( count , count + need - 1 ) ) ; try { bytesDone += recordVar . readToByteChannel ( section , channel ) ; done += need ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; break ; } } assert done == nrecs ; bytesDone /= 1000 * 1000 ; if ( debugWrite ) System . out . println ( \"write record var; total = \" + bytesDone + \" Mbytes # recs=\" + done ) ; // remove the record structure this is rather fishy, perhaps better to leave it ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_REMOVE_RECORD_STRUCTURE ) ; ncfile . finish ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////// [CODESPLIT] public static void writeFromFile ( NetcdfFile fileIn , String fileOutName ) throws IOException , InvalidRangeException { try ( FileOutputStream stream = new FileOutputStream ( fileOutName ) ) { WritableByteChannel channel = stream . getChannel ( ) ; DataOutputStream dout = new DataOutputStream ( Channels . newOutputStream ( channel ) ) ; N3channelWriter writer = new N3channelWriter ( fileIn ) ; int numrec = fileIn . getUnlimitedDimension ( ) == null ? 0 : fileIn . getUnlimitedDimension ( ) . getLength ( ) ; writer . writeHeader ( dout , numrec ) ; dout . flush ( ) ; writer . writeDataAll ( channel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write ncfile to a WritableByteChannel . [CODESPLIT] public static void writeToChannel ( NetcdfFile ncfile , WritableByteChannel wbc ) throws IOException , InvalidRangeException { DataOutputStream stream = new DataOutputStream ( new BufferedOutputStream ( Channels . newOutputStream ( wbc ) , 8000 ) ) ; //DataOutputStream stream = new DataOutputStream(Channels.newOutputStream(wbc));  // buffering seems to improve by 5% N3channelWriter writer = new N3channelWriter ( ncfile ) ; int numrec = ncfile . getUnlimitedDimension ( ) == null ? 0 : ncfile . getUnlimitedDimension ( ) . getLength ( ) ; writer . writeHeader ( stream , numrec ) ; stream . flush ( ) ; writer . writeDataAll ( wbc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the DDX waiting in the <code > InputStream< / code > and instantiate all of the member <code > BaseType< / code > variables and their associated <code > Attributes < / code > into a <code > DDS< / code > using the passed <code > BaseTypeFactory< / code > [CODESPLIT] public void parse ( Document ddx , DDS targetDDS , BaseTypeFactory fac , boolean validation ) throws DAP2Exception { dds = targetDDS ; factory = fac ; // Build up the OPeNDAP data objects rpresented by the XML document.\r // Additional validation will take place  during this process.\r Element root = ddx . getRootElement ( ) ; lastDoc = ddx ; // This is just a little tracker to help with debugging.\r parseLevel = 0 ; // Make sure the root element is in fact a Dataset.\r // Trying to enforce this in the schema would create a\r // contrived and difficult to interpret schema design.\r String type = root . getName ( ) ; if ( ! ( type . equals ( \"Dataset\" ) ) ) { throw new NoSuchTypeException ( \"Root Element MUST be <Dataset>. Found: \" + type ) ; } String name = root . getAttribute ( \"name\" ) . getValue ( ) ; //System.out.println(\"DDS should be named: \"+name);\r dds . setClearName ( name ) ; parentDC = dds ; currentBT = dds ; // Parse any Attributes (or AttributeTables/containers) at the\r // top level in the Dataset.\r parseAttributes ( root , \"-- \" ) ; // Parse any Aliases at the\r // top level in the Dataset.\r parseAliases ( root , \"++ \" ) ; // Parse all of the child elements (which would be OPeNDAP\r // BaseType variables) in the Dataset.\r Iterator ci = root . getChildren ( ) . iterator ( ) ; while ( ci . hasNext ( ) ) { Element child = ( Element ) ci . next ( ) ; parseBase ( child , \"    \" ) ; } //\tcatch(Exception e) {\r //\t    throw new DAP2Exception(\"PARSER ERROR! \\n\"+\r //\t                            e.getClass().getName()+ \": \"+e.getMessage());\r //\t}\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the DDX waiting in the <code > InputStream< / code > and instantiate all of the member <code > BaseType< / code > variables and their associated <code > Attributes < / code > into a <code > DDS< / code > using the passed <code > BaseTypeFactory< / code > [CODESPLIT] public void parse ( InputStream is , DDS targetDDS , BaseTypeFactory fac , boolean validation ) throws DAP2Exception { try { // get a jdom parser to parse and validate the XML document.\r SAXBuilder parser = new SAXBuilder ( ) ; // optionally turn on validation\r parser . setFeature ( \"http://apache.org/xml/features/validation/schema\" , validation ) ; // parse the document into a hierarchical document\r Document doc = parser . build ( is ) ; if ( _Debug ) System . out . println ( \"Document is \" + ( validation ? \"valid and \" : \"\" ) + \"well-formed.\\nContent: \" + doc ) ; parse ( doc , targetDDS , fac , validation ) ; } catch ( JDOMException jde ) { throw new DAP2Exception ( jde ) ; } catch ( IOException ioe ) { throw new DAP2Exception ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method recursively travels through the DOM tree locating BaseType derived nodes and placing them in the DDS . The structure of the BaseType derived elements in the XML instance document is captured in the DOM object that is being parsed . This structure again reflected in the resulting DDS . [CODESPLIT] private void parseBase ( Element e , String indent ) throws DASException , NoSuchTypeException , BadSemanticsException { parseLevel ++ ; String type = e . getName ( ) ; if ( type . equals ( \"Attribute\" ) ) { // Do nothing here, the Attributes get parsed when the BaseType's\r // get built. This conditional basically serves as a \"trap\" to\r // ignore the <Attribute> tag.\r } else if ( type . equals ( \"Alias\" ) ) { // Do nothing here, the Aliases get parsed when the BaseType's\r // get built. This conditional basically serves as a \"trap\" to\r // ignore the <Alias> tag.\r } else if ( type . equals ( \"dataBLOB\" ) ) { // dataBLOB?\r // The schema says that the href attribute is\r // required for the dataBLOB element.\r org . jdom2 . Attribute hrefAttr = e . getAttribute ( \"href\" ) ; // Since it's required we know that the getAttribute()\r // method is not going to return null.\r String contentID = hrefAttr . getValue ( ) ; if ( _Debug ) System . out . println ( \"Found dataBLOB element. contentID=\\\"\" + contentID + \"\\\"\" ) ; dds . setBlobContentID ( contentID ) ; } else { // What's left must be a OPeNDAP BaseType\r if ( _Debug ) System . out . println ( \"Parsing new BaseType element. Parse level: \" + parseLevel ) ; if ( _Debug ) showXMLElement ( e , indent ) ; // Go get a new BaseType formed from this element\r BaseType bt = newBaseType ( e ) ; // Set it's parent.\r // bt.setParent(parentDC);\r // Add it to it's parent (container)\r parentDC . addVariable ( bt ) ; // Now we need to make sure this particular BaseType\r // derived element isn't some special type that needs\r // additional parsing:\r // Is it a container?\r if ( bt instanceof DConstructor ) { // Up date the parsers state, (cache my parent)\r DConstructor myParentDC = parentDC ; parentDC = ( DConstructor ) bt ; try { // Grids are special containers, handle them\r if ( bt instanceof DGrid ) { parseGrid ( e , indent ) ; } else { // Otherwise, recurse on the children\r for ( Element child : e . getChildren ( ) ) { parseBase ( child , indent + \"    \" ) ; } } } finally { // restore my parent\r parentDC = myParentDC ; } } else if ( bt instanceof DArray ) { // Array's are special, better build it if it is one\r if ( _Debug ) System . out . println ( \"Parsing Array instance.  Array name: '\" + bt . getClearName ( ) + \"'\" ) ; parseArray ( e , ( DArray ) bt , indent ) ; } } parseLevel -- ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Arrays have special parsing need as their syntax is different from that of a typical BaseType derived type or a container type . The array is based on a template variable that can have ANY structure that can be represented by the OPeNDAP data model . With the exception of ( you knew this was comming right? ) of other arrays . IE You can t have Arrays of Arrays . This caveat is enforced by the XML schema . [CODESPLIT] private void parseArray ( Element ArrayElement , DArray da , String indent ) throws DASException , NoSuchTypeException , BadSemanticsException { int countTemplateVars = 0 ; int numDims = 0 ; for ( Element e : ArrayElement . getChildren ( ) ) { if ( _Debug ) System . out . println ( indent + \"Working on Array element: \" + e . getName ( ) ) ; // Is this element an Attribute of the Array?\r if ( e . getName ( ) . equals ( \"Attribute\" ) ) { //Then ignore it!\r } // Is this element an Attribute of the Alias?\r else if ( e . getName ( ) . equals ( \"Alias\" ) ) { //Then ignore it!\r } // Is this element an array dimension?\r else if ( e . getName ( ) . equals ( \"dimension\" ) ) { // Then count it,\r numDims ++ ; // And now let's add it to the array...\r // Array dimension are not required to have names, so\r // the schema does not enforce the use of the name attribute.\r // try to get the dimension's name, and use it id it's there.\r String name = null ; Attribute nameAttr = e . getAttribute ( \"name\" ) ; if ( nameAttr != null ) name = nameAttr . getValue ( ) ; // The presence of the 'size' attribute is enforeced by the schema.\r // get it, parse it, use it.\r int size = Integer . parseInt ( e . getAttribute ( \"size\" ) . getValue ( ) ) ; // add the dimension to the array.\r da . appendDim ( size , ( name ) ) ; } else { // otherwise, it must be THE template element.\r // Just to make sure the schema validation didn't fail (because\r // I am basically paranoid about software) count the number of\r // template candidates we find and throw an Exception later\r // if there was more than one.\r countTemplateVars ++ ; // The template element is just another BaseType\r // derived element. So, let's go build it!\r BaseType template = buildArrayTemplate ( e , indent ) ; // Oddly, in the OPeNDAP implementation of Array, the Array variable\r // takes it's name from it's (internal) template variable. This\r // is probably an artifact of the original DDSParser.\r // So, set the name of the template variable to the name of the Array.\r template . setClearName ( da . getClearName ( ) ) ; // Add the template variable to the Array\r da . addVariable ( template ) ; } } if ( _Debug ) { System . out . println ( indent + \"Built Array: \" ) ; da . printDecl ( System . out , indent ) ; System . out . println ( indent + \"dimensions: \" + numDims + \"  templates: \" + countTemplateVars ) ; } if ( countTemplateVars != 1 ) { throw new NoSuchTypeException ( \"ONLY ONE (1) TEMPLATE VARIABLE ALLOWED PER ARRAY!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the template variable for an array . The logic here has a lot in common with the logic in parseBase . I considered trying to refactor the code so that the two methods could utilize the same logic but I bagged it . Cie la vie . <p / > Arrays of arrays are not allowed this rule should is enforced through the schema validation process . [CODESPLIT] private BaseType buildArrayTemplate ( Element template , String indent ) throws DASException , NoSuchTypeException , BadSemanticsException { BaseType bt = null ; if ( _Debug ) showXMLElement ( template , indent + \"...:\" ) ; // Get all of the Attribute elements (tagged <Attribute>)\r Iterator attrElements = template . getChildren ( \"Attribute\" , opendapNameSpace ) . iterator ( ) ; if ( attrElements . hasNext ( ) ) throw new BadSemanticsException ( \"Array Template Variables MAY NOT have Attributes\" ) ; // Build the appropriate BaseType from the tag.\r bt = newBaseType ( template ) ; if ( _Debug ) System . out . println ( \"Got template: \" + bt . getTypeName ( ) + \"   \" + bt . getClearName ( ) ) ; // Now we need to make sure this particular BaseType\r // derived element isn't some special type that needs\r // additional parsing:\r // Is it a container?\r if ( bt instanceof DConstructor ) { // Up date the parsers state, (cache my parent)\r DConstructor myParentDC = parentDC ; parentDC = ( DConstructor ) bt ; try { // Grids are special containers, handle them\r if ( bt instanceof DGrid ) { parseGrid ( template , indent ) ; } else { // Otherwise, recurse on the children\r for ( Element child : template . getChildren ( ) ) { parseBase ( child , indent + \"    \" ) ; } } } finally { // restore my parent\r parentDC = myParentDC ; } } return ( bt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grids are unusual examples of DConstructor and require special handling when parsing . [CODESPLIT] private void parseGrid ( Element gridElement , String indent ) throws DASException , NoSuchTypeException , BadSemanticsException { parseLevel ++ ; // Grab the parent object (which better be a Grid!)\r // just to elminate the hassle of casting everytime...\r DGrid myGrid = ( DGrid ) parentDC ; if ( _Debug ) { System . out . println ( \"Parsing Grid Element: \" + gridElement ) ; System . out . println ( \"Grid Elements: \" ) ; //showXMLElement(gridElement, indent);\r for ( Element element : gridElement . getChildren ( ) ) System . out . println ( element ) ; } // Get and parse the grid's Array element.\r String eName = \"Array\" ; if ( _Debug ) { System . out . println ( \"Parsing Array element.\" ) ; System . out . println ( \"Asking for element: '\" + eName + \"' in namespace: '\" + opendapNameSpace + \"'\" ) ; } Element arrayElement = gridElement . getChild ( eName , opendapNameSpace ) ; if ( _Debug ) System . out . println ( \"Got Array element: \" + arrayElement ) ; DArray gridArray = ( DArray ) newBaseType ( arrayElement ) ; parseArray ( arrayElement , gridArray , indent + \"    \" ) ; // Add it to the Grid\r myGrid . addVariable ( gridArray , DGrid . ARRAY ) ; // Get the Map elements\r eName = \"Map\" ; if ( _Debug ) { System . out . println ( \"Parsing Map elements.\" ) ; System . out . println ( \"Asking for element: '\" + eName + \"' in namespace: '\" + opendapNameSpace + \"'\" ) ; } List < Element > mapElements = gridElement . getChildren ( \"Map\" , opendapNameSpace ) ; // Make sure the number of Map elements matches the dimension of the Grid Array.\r if ( mapElements . size ( ) != gridArray . numDimensions ( ) ) throw new BadSemanticsException ( \"Error in Grid syntax: \" + \"The number of Map arrays must \" + \"equal the number of dimensions \" + \"of the data array.\" ) ; // Parse each Map element and poke it into the Grid.\r for ( Element mapElement : mapElements ) { DArray thisMap = ( DArray ) newBaseType ( mapElement ) ; parseArray ( mapElement , thisMap , indent + \"    \" ) ; if ( thisMap . numDimensions ( ) != 1 ) throw new BadSemanticsException ( \"Error in Grid syntax: \" + \"Maps may have only one dimension.\" ) ; myGrid . addVariable ( thisMap , DGrid . MAPS ) ; } parseLevel -- ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A convienience function used for displaying information in _Debug mode . Prints an XML element s name content ( if any ) and Attributes to System . out [CODESPLIT] private void showXMLElement ( Element e , String indent ) { System . out . print ( parseLevel + indent + \"Element: \" + e . getName ( ) + \"  \" ) ; String text = e . getTextNormalize ( ) ; if ( ! text . equals ( \"\" ) ) System . out . print ( \" = \" + text + \"   \" ) ; //System.out.println(\"\");\r for ( Attribute att : e . getAttributes ( ) ) { //System.out.print(parseLevel + indent + \"    \");\r System . out . print ( att . getName ( ) + \": \" + att . getValue ( ) + \"  \" ) ; } System . out . println ( \"\" ) ; for ( Element kid : e . getChildren ( ) ) { showXMLElement ( kid , indent + \"    \" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Builds a new BaseType derived type from the passed XML element . <p > This happens in 4 steps : <ul > <li > 1 ) Determine the OPeNDAP type and vairiable name < / li > <li > 2 ) Get an new one of the thing in ( 1 ) < / li > <li > 3 ) Parse any Attribute tags associated with this OPeNDAP type . ( They appear as children of the XML element ) < / li > <li > 4 ) Parse any Alias tags associated with this OPeNDAP type . ( They appear as children of the XML element ) < / li > < / ul > [CODESPLIT] private BaseType newBaseType ( Element e ) throws DASException , NoSuchTypeException { if ( _Debug ) System . out . println ( \"Getting new BaseType() from: \" + e ) ; // What's the Element Name? This IS the OPeNDAP typename.\r String type = e . getName ( ) ; // What is the name of this variable? Since BaseType derived types\r // are not required to have names we have to do this carefully.\r String name = null ; org . jdom2 . Attribute nameAttr = e . getAttribute ( \"name\" ) ; if ( nameAttr != null ) name = nameAttr . getValue ( ) ; if ( _Debug ) System . out . println ( \"    type: \" + type + \"   name: '\" + name + \"'\" ) ; // GO get a fresh new OPeNDAP variable (BaseType derived type)\r currentBT = newBaseTypeFactory ( type , name ) ; //Parse any Attribute tagged child elements for this variable.\r parseAttributes ( e , \"--- \" ) ; //Parse any Alias tagged child elements for this variable.\r parseAliases ( e , \"+++ \" ) ; return ( currentBT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The name of this method might be a bit misleading . This method is basically a wrapper for the BaseTypeFactory associated with the DDS that we are building . <p / > I think it should really be a method of BaseTypeFactory . <p / > Something like : <p / > BaseTypeFactory . getNewVariable ( String typeString String name ) <p / > But well BaseTypeFactory is an interface so that s a crappy idea . * sigh * [CODESPLIT] private BaseType newBaseTypeFactory ( String typeString , String name ) throws NoSuchTypeException { BaseType bt ; if ( typeString . equals ( \"Array\" ) || typeString . equals ( \"Map\" ) ) { bt = factory . newDArray ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Grid\" ) ) { bt = factory . newDGrid ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Structure\" ) ) { bt = factory . newDStructure ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Sequence\" ) ) { bt = factory . newDSequence ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Int16\" ) ) { bt = factory . newDInt16 ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"UInt16\" ) ) { bt = factory . newDUInt16 ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Int32\" ) ) { bt = factory . newDInt32 ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"UInt32\" ) ) { bt = factory . newDUInt32 ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Float32\" ) ) { bt = factory . newDFloat32 ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Float64\" ) ) { bt = factory . newDFloat64 ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Byte\" ) ) { bt = factory . newDByte ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"String\" ) ) { bt = factory . newDString ( ) ; bt . setClearName ( name ) ; } else if ( typeString . equals ( \"Url\" ) ) { bt = factory . newDURL ( ) ; bt . setClearName ( name ) ; } else throw new NoSuchTypeException ( \"Unknown Type: \" + typeString ) ; return bt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the Attribute tags for a given variable element in the XML document . Build the appropriate Attributes and AttributeTables and add them to the the current variable s ( currentBT s ) AttributeTable . [CODESPLIT] private void parseAttributes ( Element e , String indent ) throws DASException , NoSuchTypeException { parseLevel ++ ; String subIndent = indent + \"    \" ; if ( _Debug ) System . out . println ( indent + \"Parsing Attributes: \" ) ; if ( _Debug ) System . out . println ( subIndent + \"currentBT: \" + currentBT . getTypeName ( ) + \" \" + currentBT . getClearName ( ) ) ; // Get all of the Attribute elements (tagged <Attribute>)\r for ( Element attrElement : e . getChildren ( \"Attribute\" , opendapNameSpace ) ) { String name = null ; Attribute nameAttr = attrElement . getAttribute ( \"name\" ) ; // no need to check that the getAttribute call worked because the Schema enforces\r // the presence of the \"name\" attribute for the <Attribute> tag in the OPeNDAP namespace\r name = nameAttr . getValue ( ) ; String typeName = null ; Attribute typeAttr = attrElement . getAttribute ( \"type\" ) ; // no need to check that the getAttribute call worked because the Schema enforces\r // the presence of the \"type\" attribute for the <Attribute> tag in the OPeNDAP namespace\r typeName = typeAttr . getValue ( ) ; // Is this Attribute a container??\r if ( typeName . equals ( \"Container\" ) ) { // Make sure that the document is valid for Attribute Containers and Values\r Iterator valueChildren = attrElement . getChildren ( \"value\" , opendapNameSpace ) . iterator ( ) ; if ( valueChildren . hasNext ( ) ) throw new AttributeBadValueException ( \"Container Attributes may \" + \"contain only other Attributes.\\n\" + \"Container Attributes may NOT \" + \"contain values.\" ) ; // Cache the currentAT (AttributeTable), this might be a null\r // in which case the the container should be added to the currentBT.\r AttributeTable cacheAttributeTable = currentAT ; if ( _Debug ) System . out . println ( indent + \"currentBT: \" + currentBT . getTypeName ( ) + \" \" + currentBT . getClearName ( ) ) ; if ( _Debug ) System . out . println ( indent + \"Attribute '\" + name + \"' is type \" + typeName ) ; // Add the Attribute container to the appropriate object.\r // If the currentAT is null, this indicates that we are working\r // on the top level attributes for the currentBT, if it's not\r // then we are working on the Attributes for some AttributeTable\r // contained within the top level Attributes in the currentBT.\r // Set the currentAT to the newly built (and returned) AttributeTable\r if ( currentAT == null ) currentAT = currentBT . appendAttributeContainer ( name ) ; else currentAT = currentAT . appendContainer ( name ) ; // Go parse the child Attributes of this Attribute table.\r // Note that this is a recursive call.\r parseAttributes ( attrElement , indent + \"    \" ) ; // Now parse all of the Aliases that exist in this Attribute table.\r parseAliases ( attrElement , \"+++ \" ) ; // restore the currentAT from the cached one, thus regaining the\r // the state that we entered this method with.\r currentAT = cacheAttributeTable ; } else { // Make sure that the document is valid for Attribute Containers and Values\r Iterator attrChildren = attrElement . getChildren ( \"Attribute\" , opendapNameSpace ) . iterator ( ) ; if ( attrChildren . hasNext ( ) ) throw new AttributeBadValueException ( \"Attributes must be of type Container \" + \"in order to contain other Attributes.\\n\" + \"Attributes of types other than Container \" + \"must contain values.\" ) ; // Walk through the <value> elements\r for ( Element valueChild : attrElement . getChildren ( \"value\" , opendapNameSpace ) ) { // Get the content of the value.\r // There are several methods for getting this content in the\r // org.jdom2.Element object. The method getText() makes no effort\r // to \"normalize\" the white space content. IE tabs, spaces,\r // carriage return, newlines are all preserved. This might not\r // be the right thing to do, but only time will tell.\r String value = valueChild . getText ( ) ; if ( _Debug ) { System . out . println ( subIndent + \"Attribute '\" + name + \"' of \" + currentBT . getClearName ( ) + \" is type \" + typeName + \" and has value: \" + value ) ; } // get the Attribute value type code.\r int typeVal = opendap . dap . Attribute . getTypeVal ( typeName ) ; // Add the attribute and it's value to the appropriat\r // container. Note that the interface for appending\r // values to opendap.dap.Attributes is built such that\r // the Attribute must be named each time. If the Attribte\r // name already exists, then the value is added to the list\r // of values for the Attribute. If the Attribute name does not\r // already exist, a new Attribute is made to hold the value.\r if ( currentAT == null ) currentBT . appendAttribute ( name , typeVal , value , true ) ; else currentAT . appendAttribute ( name , typeVal , value , true ) ; } } } parseLevel -- ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse all of the Alias tags in this element of the XML document . Add each one to the correct Attribute Table . [CODESPLIT] private void parseAliases ( Element e , String indent ) throws DASException { parseLevel ++ ; String subIndent = indent + \"    \" ; if ( _Debug ) System . out . println ( indent + \"Parsing Aliases: \" ) ; if ( _Debug ) System . out . println ( subIndent + \"currentBT: \" + currentBT . getTypeName ( ) + \" \" + currentBT . getClearName ( ) ) ; // Get the Alias elements\r for ( Element aliasElement : e . getChildren ( \"Alias\" , opendapNameSpace ) ) { String name = null ; Attribute nameAttr = aliasElement . getAttribute ( \"name\" ) ; // no need to check that the getAttribute call worked because the Schema enforces\r // the presence of the \"name\" attribute for the <Alias> tag in the OPeNDAP namespace\r name = nameAttr . getValue ( ) ; String attributeName = null ; Attribute attributeAttr = aliasElement . getAttribute ( \"Attribute\" ) ; // no need to check that the getAttribute call worked because the Schema enforces\r // the presence of the \"Attribute\" attribute for the <Alias> tag in the OPeNDAP namespace\r attributeName = attributeAttr . getValue ( ) ; if ( _Debug ) { System . out . println ( subIndent + \"The name '\" + name + \"' is aliased to dds attribute: '\" + attributeName + \"'\" ) ; } // Add the Alias to the appropriate container.\r if ( currentAT == null ) currentBT . addAttributeAlias ( name , attributeName ) ; else currentAT . addAlias ( name , attributeName ) ; } parseLevel -- ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to normalize strings prior to their inclusion in XML documents . XML has certain parsing requirements around reserved characters . These reserved characters must be replaced with symbols recognized by the XML parser as place holder for the actual symbol . <p / > The rule for this normalization is as follows : <p / > <ul > <li > The &lt ; ( less than ) character is replaced with &amp ; lt ; <li > The &gt ; ( greater than ) character is replaced with &amp ; gt ; <li > The &amp ; ( ampersand ) character is replaced with &amp ; amp ; <li > The ( apostrophe ) character is replaced with &amp ; apos ; <li > The &quot ; ( double quote ) character is replaced with &amp ; quot ; < / ul > [CODESPLIT] public static String normalizeToXML ( String s ) { // Some handy definitons.\r String xmlGT = \"&gt;\" ; String xmlLT = \"&lt;\" ; String xmlAmp = \"&amp;\" ; String xmlApos = \"&apos;\" ; String xmlQuote = \"&quot;\" ; boolean Debug = false ; StringBuilder sb = new StringBuilder ( s ) ; for ( int offset = 0 ; offset < sb . length ( ) ; offset ++ ) { char c = sb . charAt ( offset ) ; switch ( c ) { case ' ' : // GreaterThan\r sb . replace ( offset , offset + 1 , xmlGT ) ; break ; case ' ' : // Less Than\r sb . replace ( offset , offset + 1 , xmlLT ) ; break ; case ' ' : // Ampersand\r sb . replace ( offset , offset + 1 , xmlAmp ) ; break ; case ' ' : // Single Quote\r sb . replace ( offset , offset + 1 , xmlApos ) ; break ; case ' ' : // Double Quote\r sb . replace ( offset , offset + 1 , xmlQuote ) ; break ; default : break ; } } //Coverity[DEADCODE]\r if ( Debug ) System . out . println ( \"String: `\" + s + \"` normalized to: `\" + sb + \"`\" ) ; return ( sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : featureOfInterest [CODESPLIT] public static FeaturePropertyType initFeatureOfInterest ( FeaturePropertyType featureOfInterest , StationTimeSeriesFeature stationFeat ) { // wml2:MonitoringPoint MonitoringPointDocument monitoringPointDoc = MonitoringPointDocument . Factory . newInstance ( ) ; NcMonitoringPointType . initMonitoringPointType ( monitoringPointDoc . addNewMonitoringPoint ( ) , stationFeat ) ; featureOfInterest . set ( monitoringPointDoc ) ; return featureOfInterest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert ids to DataDescriptors expand table D [CODESPLIT] private List < DataDescriptor > decode ( List < Short > keyDesc , BufrTableLookup lookup ) { if ( keyDesc == null ) return null ; List < DataDescriptor > keys = new ArrayList < DataDescriptor > ( ) ; for ( short id : keyDesc ) { DataDescriptor dd = new DataDescriptor ( id , lookup ) ; keys . add ( dd ) ; if ( dd . f == 3 ) { TableD . Descriptor tdd = lookup . getDescriptorTableD ( dd . fxy ) ; if ( tdd == null || tdd . getSequence ( ) == null ) { dd . bad = true ; } else { dd . name = tdd . getName ( ) ; dd . subKeys = decode ( tdd . getSequence ( ) , lookup ) ; } } } return keys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "look for replication move replicated items into subtree [CODESPLIT] private List < DataDescriptor > replicate ( List < DataDescriptor > keys ) { List < DataDescriptor > tree = new ArrayList < DataDescriptor > ( ) ; Iterator < DataDescriptor > dkIter = keys . iterator ( ) ; while ( dkIter . hasNext ( ) ) { DataDescriptor dk = dkIter . next ( ) ; if ( dk . f == 1 ) { dk . subKeys = new ArrayList < DataDescriptor > ( ) ; dk . replication = dk . y ; // replication count\r if ( dk . replication == 0 ) { // delayed replication\r root . isVarLength = true ; // variable sized data == deferred replication == sequence data\r // the next one is the replication count size : does not count in field count (x)\r DataDescriptor replication = dkIter . next ( ) ; if ( replication . y == 0 ) dk . replicationCountSize = 1 ; // ??\r else if ( replication . y == 1 ) dk . replicationCountSize = 8 ; else if ( replication . y == 2 ) dk . replicationCountSize = 16 ; else if ( replication . y == 11 ) dk . repetitionCountSize = 8 ; else if ( replication . y == 12 ) dk . repetitionCountSize = 16 ; else log . error ( \"Unknown replication type= \" + replication ) ; } // transfer to the subKey list\r for ( int j = 0 ; j < dk . x && dkIter . hasNext ( ) ; j ++ ) { dk . subKeys . add ( dkIter . next ( ) ) ; } // recurse\r dk . subKeys = replicate ( dk . subKeys ) ; } else if ( ( dk . f == 3 ) && ( dk . subKeys != null ) ) { dk . subKeys = replicate ( dk . subKeys ) ; // do at all levels\r } tree . add ( dk ) ; } return tree ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * try to grab names of compounds ( structs ) if f = 1 is followed by f = 3 eg : 0 - 40 - 20 : GQisFlagQualDetailed - Quality flag for the system 1 - 01 - 010 : replication 3 - 40 - 2 : ( IASI Level 1c band description ) 0 - 25 - 140 : Start channel 0 - 25 - 141 : End channel 0 - 25 - 142 : Channel scale factor 1 - 01 - 087 : replication 3 - 40 - 3 : ( IASI Level 1c 100 channels ) 1 - 04 - 100 : replication 2 - 01 - 136 : Operator = change data width 0 - 5 - 42 : Channel number 2 - 01 - 000 : Operator = change data width 0 - 14 - 46 : Scaled IASI radiance 0 - 2 - 19 : Satellite instruments 0 - 25 - 51 : AVHRR channel combination 1 - 01 - 007 : replication 3 - 40 - 4 : ( IASI Level 1c AVHRR single scene ) 0 - 5 - 60 : Y angular position from centre of gravity 0 - 5 - 61 : Z angular position from centre of gravity 0 - 25 - 85 : Fraction of clear pixels in HIRS FOV ... [CODESPLIT] private void grabCompoundNames ( List < DataDescriptor > tree ) { for ( int i = 0 ; i < tree . size ( ) ; i ++ ) { DataDescriptor key = tree . get ( i ) ; if ( key . bad ) continue ; if ( ( key . f == 3 ) && ( key . subKeys != null ) ) { grabCompoundNames ( key . subKeys ) ; } else if ( key . f == 1 && key . x == 1 && i < tree . size ( ) - 1 ) { // replicator with 1 element\r DataDescriptor nextKey = tree . get ( i + 1 ) ; if ( nextKey . f == 3 ) { // the one element is a compound\r if ( nextKey . name != null && ! nextKey . name . isEmpty ( ) ) key . name = nextKey . name ; } else if ( key . y == 0 && i < tree . size ( ) - 2 ) { // seq has an extra key before the 3\r DataDescriptor nnKey = tree . get ( i + 2 ) ; if ( nnKey . f == 3 ) if ( nnKey . name != null && ! nnKey . name . isEmpty ( ) ) key . name = nnKey . name ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "flatten the compounds ( type 3 ) ; but dont remove bad ones [CODESPLIT] private void flatten ( List < DataDescriptor > result , List < DataDescriptor > tree ) { for ( DataDescriptor key : tree ) { if ( key . bad ) { root . isBad = true ; result . add ( key ) ; // add it anyway so we can see it in debug\r continue ; } if ( ( key . f == 3 ) && ( key . subKeys != null ) ) { flatten ( result , key . subKeys ) ; } else if ( key . f == 1 ) { // flatten the subtrees\r List < DataDescriptor > subTree = new ArrayList < DataDescriptor > ( ) ; flatten ( subTree , key . subKeys ) ; key . subKeys = subTree ; result . add ( key ) ; } else { result . add ( key ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assume theres only one in effect at a time [CODESPLIT] private void operate ( List < DataDescriptor > tree ) { if ( tree == null ) return ; boolean hasAssFields = false ; // boolean hasDpiFields = false;\r DataDescriptor . AssociatedField assField = null ; // 02 04 Y\r Iterator < DataDescriptor > iter = tree . iterator ( ) ; while ( iter . hasNext ( ) ) { DataDescriptor dd = iter . next ( ) ; if ( dd . f == 2 ) { if ( dd . x == 1 ) { changeWidth = ( dd . y == 0 ) ? null : dd ; iter . remove ( ) ; } else if ( dd . x == 2 ) { changeScale = ( dd . y == 0 ) ? null : dd ; iter . remove ( ) ; // throw new UnsupportedOperationException(\"2-2-Y (change scale)\");\r } else if ( dd . x == 3 ) { changeRefval = ( dd . y == 255 ) ? null : dd ; iter . remove ( ) ; // throw new UnsupportedOperationException(\"2-3-Y (change reference values)\");  // untested - no examples\r } else if ( dd . x == 4 ) { assField = ( dd . y == 0 ) ? null : new DataDescriptor . AssociatedField ( dd . y ) ; iter . remove ( ) ; hasAssFields = true ; } else if ( dd . x == 5 ) { // char data - this allows arbitrary string to be inserted\r dd . type = 1 ; // String\r dd . bitWidth = dd . y * 8 ; dd . name = \"Note\" ; } else if ( dd . x == 6 ) { // see L3-82 (3.1.6.5)\r // \"Y bits of data are described by the immediately following descriptor\". could they speak English?\r iter . remove ( ) ; if ( ( dd . y != 0 ) && iter . hasNext ( ) ) { // fnmoc using 2-6-0 as cancel (apparently)\r DataDescriptor next = iter . next ( ) ; next . bitWidth = dd . y ; } } else if ( dd . x == 7 ) { changeWtf = ( dd . y == 0 ) ? null : dd ; iter . remove ( ) ; } else if ( dd . x == 36 ) { if ( iter . hasNext ( ) ) { DataDescriptor dpi_dd = iter . next ( ) ; // this should be a replicated data present field\r dpi = new DataPresentIndicator ( tree , dpi_dd ) ; dd . dpi = dpi ; dpi_dd . dpi = dpi ; } } else if ( ( dd . x == 37 ) && ( dd . y == 255 ) ) { // cancel dpi\r dpi = null ; } else if ( ( dd . x == 24 ) && ( dd . y == 255 ) ) { dd . dpi = dpi ; } } else if ( dd . subKeys != null ) { operate ( dd . subKeys ) ; } else if ( dd . f == 0 ) { if ( dd . type != 3 ) { // numeric or string or enum, not compound\r if ( changeWidth != null ) dd . bitWidth += changeWidth . y - 128 ; if ( changeScale != null ) dd . scale += changeScale . y - 128 ; if ( changeRefval != null ) dd . refVal += changeRefval . y - 128 ; // LOOK wrong\r if ( changeWtf != null && dd . type == 0 ) { // see I.2 – BUFR Table C — 4\r // For Table B elements, which are not CCITT IA5 (character data), code tables, or flag tables:\r //  1. Add Y to the existing scale factor\r //  2. Multiply the existing reference value by 10 Y\r //  3. Calculate ((10 x Y) + 2) ÷  3, disregard any fractional remainder and add the result to the existing bit width.\r // HAHAHAHAHAHAHAHA\r int y = changeWtf . y ; dd . scale += y ; dd . refVal *= Math . pow ( 10 , y ) ; int wtf = ( ( 10 * y ) + 2 ) / 3 ; dd . bitWidth += wtf ; } } if ( ( dd . f == 0 ) && ( assField != null ) ) { assField . nfields ++ ; dd . assField = assField ; assField . dataFldName = dd . name ; } } } if ( hasAssFields ) addAssFields ( tree ) ; // if (hasDpiFields) addDpiFields(tree);\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////// local time types [CODESPLIT] @ Override public Grib1ParamTime getParamTime ( Grib1SectionProductDefinition pds ) { int p1 = pds . getTimeValue1 ( ) ; // octet 19 int p2 = pds . getTimeValue2 ( ) ; // octet 20 int timeRangeIndicator = pds . getTimeRangeIndicator ( ) ; // octet 21 int n = pds . getNincluded ( ) ; int start ; int end ; int forecastTime = 0 ; boolean isInterval ; switch ( timeRangeIndicator ) { /*\n      Monthly-diurnal (ds628.5/fcst_phy2m125_diurnal)\n      Average over the days of the month.\n      128: Average of N forecast products with a valid time ranging between reference time + P1 and reference time + P2;\n        products have reference times at Intervals of 24 hours, beginning at the given reference time.\n       */ case 128 : isInterval = true ; start = p1 ; end = p2 ; break ; /* 129: Temporal variance of N forecasts; each product has valid time ranging between reference time + P1 and reference time + P2;\n         products have reference times at intervals of 24 hours, beginning at the given reference time;\n         unit of measurement is square of that in Code Table 2 */ // LOOK /* 131: Temporal variance of N forecasts; valid time of the first product ranges between R + P1 and R + P2,\n          where R is reference time given in octets 13 to 17, then subsequent products have valid time range at interval of P2 - P1;\n          thus all N products cover continuous time span; products have reference times at intervals of P2 - P1, beginning at the given reference time;\n          unit of measurement is square of that in Code Table 2 */ // LOOK case 129 : case 131 : isInterval = true ; start = p1 ; end = p2 ; break ; /* 130: Average of N forecast products; valid time of the first product ranges between R + P1 and R + P2, where R is reference time given in octets 13 to 17,\n        then subsequent products have valid time range at interval of P2 - P1; thus all N products cover continuous time span; products have reference times at\n        intervals of P2 - P1, beginning at the given reference time\n       */ case 130 : isInterval = true ; start = p1 ; end = ( n > 0 ) ? p1 + n * ( p2 - p1 ) : p2 ; // prob n >= 1 break ; /* Temporal variance of N uninitialized analyses (P1 = 0) or instantaneous forecasts (P1 > 0);\n          each product has valid time at the reference time + P1;\n          products have reference times at intervals of P2, beginning at the given reference time;\n          unit of measurement is square of that in Code Table 2 */ // LOOK case 132 : forecastTime = p1 ; start = p1 ; end = ( n > 0 ) ? p1 + ( n - 1 ) * p2 : p1 ; // LOOK ?? isInterval = ( n > 0 ) ; break ; default : return super . getParamTime ( pds ) ; } return new Grib1ParamTime ( this , timeRangeIndicator , isInterval , start , end , forecastTime ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the dataset filename . [CODESPLIT] public String getDatasetFilename ( ) { String s = getEncodedName ( ) ; System . out . println ( s ) ; return ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the constrained <code > DDS< / code > on the given <code > PrintWriter< / code > . [CODESPLIT] public void printConstrained ( PrintWriter os ) { os . println ( \"Dataset {\" ) ; for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; // System.err.println(\"check: \"+bt.getLongName()+\" = \"+((ServerMethods) bt).isProject()); ServerMethods sm = ( ServerMethods ) bt ; if ( sm . isProject ( ) ) { bt . printDecl ( os , \"    \" , true , true ) ; } } os . print ( \"} \" ) ; if ( getEncodedName ( ) != null ) os . print ( getEncodedName ( ) ) ; os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a valid file? [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { if ( ! super . isValidFile ( raf ) ) { return false ; } // TODO:  handle other types of surface files\r return gemreader . getFileSubType ( ) . equals ( GempakSurfaceFileReader . STANDARD ) || gemreader . getFileSubType ( ) . equals ( GempakSurfaceFileReader . SHIP ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the CF feature type [CODESPLIT] public String getCFFeatureType ( ) { if ( gemreader . getFileSubType ( ) . equals ( GempakSurfaceFileReader . SHIP ) ) { return CF . FeatureType . point . toString ( ) ; } return CF . FeatureType . timeSeries . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data for the variable [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { if ( gemreader == null ) { return null ; } //System.out.println(\"looking for \" + v2);\r //System.out.println(\"Section = \" + section);\r //Trace.call1(\"GEMPAKSIOSP: readData\");\r Array array = null ; if ( gemreader . getFileSubType ( ) . equals ( GempakSurfaceFileReader . SHIP ) ) { array = readShipData ( v2 , section ) ; } else if ( gemreader . getFileSubType ( ) . equals ( GempakSurfaceFileReader . STANDARD ) ) { array = readStandardData ( v2 , section ) ; } else { // climate data\r //array = readClimateData(v2, section);\r } //  long took = System.currentTimeMillis() - start;\r //  System.out.println(\"  read data took=\" + took + \" msec \");\r //Trace.call2(\"GEMPAKSIOSP: readData\");\r return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in the data for the variable . In this case it should be a Structure . The section should be rank 2 ( station time ) . [CODESPLIT] private Array readStandardData ( Variable v2 , Section section ) throws IOException { Array array = null ; if ( v2 instanceof Structure ) { List < GempakParameter > params = gemreader . getParameters ( GempakSurfaceFileReader . SFDT ) ; Structure pdata = ( Structure ) v2 ; StructureMembers members = pdata . makeStructureMembers ( ) ; List < StructureMembers . Member > mbers = members . getMembers ( ) ; int i = 0 ; int numBytes = 0 ; int totalNumBytes = 0 ; for ( StructureMembers . Member member : mbers ) { member . setDataParam ( 4 * i ++ ) ; numBytes = member . getDataType ( ) . getSize ( ) ; totalNumBytes += numBytes ; } // one member is a byte\r members . setStructureSize ( totalNumBytes ) ; float [ ] missing = new float [ mbers . size ( ) ] ; int missnum = 0 ; for ( Variable v : pdata . getVariables ( ) ) { Attribute att = v . findAttribute ( \"missing_value\" ) ; missing [ missnum ++ ] = ( att == null ) ? GempakConstants . RMISSD : att . getNumericValue ( ) . floatValue ( ) ; } //int num = 0;\r Range stationRange = section . getRange ( 0 ) ; Range timeRange = section . getRange ( 1 ) ; int size = stationRange . length ( ) * timeRange . length ( ) ; // Create a ByteBuffer using a byte array\r byte [ ] bytes = new byte [ totalNumBytes * size ] ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) ; array = new ArrayStructureBB ( members , new int [ ] { size } , buf , 0 ) ; for ( int stnIdx : stationRange ) { for ( int timeIdx : timeRange ) { GempakFileReader . RData vals = gemreader . DM_RDTR ( timeIdx + 1 , stnIdx + 1 , GempakSurfaceFileReader . SFDT ) ; if ( vals == null ) { int k = 0 ; for ( StructureMembers . Member member : mbers ) { if ( member . getDataType ( ) . equals ( DataType . FLOAT ) ) { buf . putFloat ( missing [ k ] ) ; } else { buf . put ( ( byte ) 1 ) ; } k ++ ; } } else { float [ ] reals = vals . data ; int var = 0 ; for ( GempakParameter param : params ) { if ( members . findMember ( param . getName ( ) ) != null ) { buf . putFloat ( reals [ var ] ) ; } var ++ ; } // always add the missing flag\r buf . put ( ( byte ) 0 ) ; } } } //Trace.call2(\"GEMPAKSIOSP: readStandardData\");\r } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in the data for the record variable . In this case it should be a Structure of record dimension . We can handle a subset of the variables in a structure . [CODESPLIT] private Array readShipData ( Variable v2 , Section section ) throws IOException { Array array = null ; if ( v2 instanceof Structure ) { List < GempakParameter > params = gemreader . getParameters ( GempakSurfaceFileReader . SFDT ) ; Structure pdata = ( Structure ) v2 ; StructureMembers members = pdata . makeStructureMembers ( ) ; List < StructureMembers . Member > mbers = members . getMembers ( ) ; int ssize = 0 ; //int stnVarNum = 0;\r List < String > stnKeyNames = gemreader . getStationKeyNames ( ) ; for ( StructureMembers . Member member : mbers ) { if ( stnKeyNames . contains ( member . getName ( ) ) ) { int varSize = getStnVarSize ( member . getName ( ) ) ; member . setDataParam ( ssize ) ; ssize += varSize ; } else if ( member . getName ( ) . equals ( TIME_VAR ) ) { member . setDataParam ( ssize ) ; ssize += 8 ; } else if ( member . getName ( ) . equals ( MISSING_VAR ) ) { member . setDataParam ( ssize ) ; ssize += 1 ; } else { member . setDataParam ( ssize ) ; ssize += 4 ; } } members . setStructureSize ( ssize ) ; // TODO:  figure out how to get the missing value for data\r //float[] missing = new float[mbers.size()];\r //int     missnum = 0;\r //for (Variable v : pdata.getVariables()) {\r //    Attribute att = v.findAttribute(\"missing_value\");\r //    missing[missnum++] = (att == null)\r //                         ? GempakConstants.RMISSD\r //                         : att.getNumericValue().floatValue();\r //}\r Range recordRange = section . getRange ( 0 ) ; int size = recordRange . length ( ) ; // Create a ByteBuffer using a byte array\r byte [ ] bytes = new byte [ ssize * size ] ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) ; array = new ArrayStructureBB ( members , new int [ ] { size } , buf , 0 ) ; List < GempakStation > stationList = gemreader . getStations ( ) ; List < Date > dateList = gemreader . getDates ( ) ; boolean needToReadData = ! pdata . isSubset ( ) ; if ( ! needToReadData ) { // subset, see if we need some param data\r for ( GempakParameter param : params ) { if ( members . findMember ( param . getName ( ) ) != null ) { needToReadData = true ; break ; } } } //boolean hasTime = (members.findMember(TIME_VAR) != null);\r // fill out the station information\r for ( int recIdx : recordRange ) { GempakStation stn = stationList . get ( recIdx ) ; for ( String varname : stnKeyNames ) { if ( members . findMember ( varname ) == null ) { continue ; } String temp = null ; switch ( varname ) { case GempakStation . STID : temp = StringUtil2 . padRight ( stn . getName ( ) , 8 ) ; break ; case GempakStation . STNM : buf . putInt ( stn . getSTNM ( ) ) ; break ; case GempakStation . SLAT : buf . putFloat ( ( float ) stn . getLatitude ( ) ) ; break ; case GempakStation . SLON : buf . putFloat ( ( float ) stn . getLongitude ( ) ) ; break ; case GempakStation . SELV : buf . putFloat ( ( float ) stn . getAltitude ( ) ) ; break ; case GempakStation . STAT : temp = StringUtil2 . padRight ( stn . getSTAT ( ) , 2 ) ; break ; case GempakStation . COUN : temp = StringUtil2 . padRight ( stn . getCOUN ( ) , 2 ) ; break ; case GempakStation . STD2 : temp = StringUtil2 . padRight ( stn . getSTD2 ( ) , 4 ) ; break ; case GempakStation . SPRI : buf . putInt ( stn . getSPRI ( ) ) ; break ; case GempakStation . SWFO : temp = StringUtil2 . padRight ( stn . getSWFO ( ) , 4 ) ; break ; case GempakStation . WFO2 : temp = StringUtil2 . padRight ( stn . getWFO2 ( ) , 4 ) ; break ; } if ( temp != null ) { buf . put ( temp . getBytes ( CDM . utf8Charset ) ) ; } } if ( members . findMember ( TIME_VAR ) != null ) { // put in the time\r Date time = dateList . get ( recIdx ) ; buf . putDouble ( time . getTime ( ) / 1000.d ) ; } if ( needToReadData ) { int column = stn . getIndex ( ) ; GempakFileReader . RData vals = gemreader . DM_RDTR ( 1 , column , GempakSurfaceFileReader . SFDT ) ; if ( vals == null ) { for ( GempakParameter param : params ) { if ( members . findMember ( param . getName ( ) ) != null ) { buf . putFloat ( GempakConstants . RMISSD ) ; } } buf . put ( ( byte ) 1 ) ; } else { float [ ] reals = vals . data ; int var = 0 ; for ( GempakParameter param : params ) { if ( members . findMember ( param . getName ( ) ) != null ) { buf . putFloat ( reals [ var ] ) ; } var ++ ; } buf . put ( ( byte ) 0 ) ; } } } //Trace.call2(\"GEMPAKSIOSP: readShipData\");\r } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the netCDF file [CODESPLIT] protected void fillNCFile ( ) throws IOException { String fileType = gemreader . getFileSubType ( ) ; switch ( fileType ) { case GempakSurfaceFileReader . STANDARD : buildStandardFile ( ) ; break ; case GempakSurfaceFileReader . SHIP : buildShipFile ( ) ; break ; default : buildClimateFile ( ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a standard station structure [CODESPLIT] private void buildStandardFile ( ) { // Build station list\r List < GempakStation > stations = gemreader . getStations ( ) ; //Trace.msg(\"GEMPAKSIOSP: now have \" + stations.size() + \" stations\");\r Dimension station = new Dimension ( \"station\" , stations . size ( ) , true ) ; ncfile . addDimension ( null , station ) ; ncfile . addDimension ( null , DIM_LEN8 ) ; ncfile . addDimension ( null , DIM_LEN4 ) ; ncfile . addDimension ( null , DIM_LEN2 ) ; List < Variable > stationVars = makeStationVars ( stations , station ) ; // loop through and add to ncfile\r for ( Variable stnVar : stationVars ) { ncfile . addVariable ( null , stnVar ) ; } // Build variable list (var(station,time))\r // time\r List < Date > timeList = gemreader . getDates ( ) ; int numTimes = timeList . size ( ) ; Dimension times = new Dimension ( TIME_VAR , numTimes , true ) ; ncfile . addDimension ( null , times ) ; Array varArray ; Variable timeVar = new Variable ( ncfile , null , null , TIME_VAR , DataType . DOUBLE , TIME_VAR ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , \"seconds since 1970-01-01 00:00:00\" ) ) ; timeVar . addAttribute ( new Attribute ( \"long_name\" , TIME_VAR ) ) ; varArray = new ArrayDouble . D1 ( numTimes ) ; int i = 0 ; for ( Date date : timeList ) { ( ( ArrayDouble . D1 ) varArray ) . set ( i , date . getTime ( ) / 1000.d ) ; i ++ ; } timeVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , timeVar ) ; List < Dimension > stationTime = new ArrayList <> ( ) ; stationTime . add ( station ) ; stationTime . add ( times ) ; // TODO: handle other parts\r Structure sfData = makeStructure ( GempakSurfaceFileReader . SFDT , stationTime , true ) ; if ( sfData == null ) { return ; } sfData . addAttribute ( new Attribute ( CF . COORDINATES , \"time SLAT SLON SELV\" ) ) ; ncfile . addVariable ( null , sfData ) ; ncfile . addAttribute ( null , new Attribute ( \"CF:featureType\" , CF . FeatureType . timeSeries . toString ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a ship station structure . Here the columns are the stations / reports and the rows ( 1 ) are the reports . [CODESPLIT] private void buildShipFile ( ) { // Build variable list (var(station,time))\r List < GempakStation > stations = gemreader . getStations ( ) ; int numObs = stations . size ( ) ; //Trace.msg(\"GEMPAKSIOSP: now have \" + numObs + \" stations\");\r Dimension record = new Dimension ( \"record\" , numObs , true , ( numObs == 0 ) , false ) ; ncfile . addDimension ( null , record ) ; List < Dimension > records = new ArrayList <> ( 1 ) ; records . add ( record ) ; // time\r Variable timeVar = new Variable ( ncfile , null , null , TIME_VAR , DataType . DOUBLE , ( String ) null ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , \"seconds since 1970-01-01 00:00:00\" ) ) ; timeVar . addAttribute ( new Attribute ( \"long_name\" , TIME_VAR ) ) ; ncfile . addDimension ( null , DIM_LEN8 ) ; ncfile . addDimension ( null , DIM_LEN4 ) ; ncfile . addDimension ( null , DIM_LEN2 ) ; List < Variable > stationVars = makeStationVars ( stations , null ) ; List < GempakParameter > params = gemreader . getParameters ( GempakSurfaceFileReader . SFDT ) ; if ( params == null ) { return ; } Structure sVar = new Structure ( ncfile , null , null , \"Obs\" ) ; sVar . setDimensions ( records ) ; // loop through and add to ncfile\r boolean hasElevation = false ; for ( Variable stnVar : stationVars ) { if ( stnVar . getShortName ( ) . equals ( \"SELV\" ) ) { hasElevation = true ; } sVar . addMemberVariable ( stnVar ) ; } sVar . addMemberVariable ( timeVar ) ; for ( GempakParameter param : params ) { Variable var = makeParamVariable ( param , null ) ; sVar . addMemberVariable ( var ) ; } sVar . addMemberVariable ( makeMissingVariable ( ) ) ; String coords = \"Obs.time Obs.SLAT Obs.SLON\" ; if ( hasElevation ) { coords = coords + \" Obs.SELV\" ; } sVar . addAttribute ( new Attribute ( CF . COORDINATES , coords ) ) ; ncfile . addVariable ( null , sVar ) ; ncfile . addAttribute ( null , new Attribute ( \"CF:featureType\" , CF . FeatureType . point . toString ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute difference between two numbers i . e . { @code |a - b| } . [CODESPLIT] public static float absoluteDifference ( float a , float b ) { if ( Float . compare ( a , b ) == 0 ) { // Shortcut: handles infinities and NaNs. return 0 ; } else { return Math . abs ( a - b ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as { [CODESPLIT] public static double absoluteDifference ( double a , double b ) { if ( Double . compare ( a , b ) == 0 ) { // Shortcut: handles infinities and NaNs. return 0 ; } else { return Math . abs ( a - b ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the relative difference between two numbers i . e . { @code |a - b| / max ( |a| |b| ) } . <p > For cases where { @code a == 0 } { @code b == 0 } or { @code a } and { @code b } are extremely close traditional relative difference calculation breaks down . So in those instances we compute the difference relative to { @link Float#MIN_NORMAL } i . e . { @code |a - b| / Float . MIN_NORMAL } . [CODESPLIT] public static float relativeDifference ( float a , float b ) { float absDiff = absoluteDifference ( a , b ) ; if ( Float . compare ( a , b ) == 0 ) { // Shortcut: handles infinities and NaNs. return 0 ; } else if ( a == 0 || b == 0 || absDiff < Float . MIN_NORMAL ) { return absDiff / Float . MIN_NORMAL ; } else { float maxAbsValue = Math . max ( Math . abs ( a ) , Math . abs ( b ) ) ; return absDiff / maxAbsValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if two numbers are nearly equal with given absolute tolerance . [CODESPLIT] public static boolean nearlyEqualsAbs ( float a , float b , float maxAbsDiff ) { return absoluteDifference ( a , b ) <= Math . abs ( maxAbsDiff ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////// [CODESPLIT] static public boolean compare ( byte [ ] raw1 , byte [ ] raw2 , Formatter f ) { if ( raw1 == null || raw2 == null ) return false ; if ( raw1 . length != raw2 . length ) { f . format ( \"length 1= %3d != length 2=%3d%n\" , raw1 . length , raw2 . length ) ; } int len = Math . min ( raw1 . length , raw2 . length ) ; int ndiff = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( raw1 [ i ] != raw2 [ i ] ) { f . format ( \" %3d : %3d != %3d%n\" , i + 1 , raw1 [ i ] , raw2 [ i ] ) ; ndiff ++ ; } } f . format ( \"tested %d bytes  diff = %d %n\" , len , ndiff ) ; return ndiff == 0 && ( raw1 . length == raw2 . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static InvDataset copyDataset ( InvDataset dataset , List < InvService > availableServices , boolean copyInheritedMetadataFromParents ) { if ( dataset == null ) throw new IllegalArgumentException ( \"Dataset may not be null.\" ) ; if ( availableServices == null ) throw new IllegalArgumentException ( \"List of available services may not be null.\" ) ; InvDatasetImpl resultDs ; // ToDo Deal with InvDatasetScan and its ilk. if ( dataset instanceof InvCatalogRef ) { InvCatalogRef catRef = ( InvCatalogRef ) dataset ; resultDs = new InvCatalogRef ( null , catRef . getName ( ) , catRef . getXlinkHref ( ) ) ; } else { resultDs = new InvDatasetImpl ( null , dataset . getName ( ) ) ; } resultDs . setID ( dataset . getID ( ) ) ; resultDs . transferMetadata ( ( InvDatasetImpl ) dataset , copyInheritedMetadataFromParents ) ; // Only copy child InvAccess if the current dataset is not an InvCatalogRef. if ( ! ( dataset instanceof InvCatalogRef ) ) { String urlPath = ( ( InvDatasetImpl ) dataset ) . getUrlPath ( ) ; if ( urlPath != null ) resultDs . setUrlPath ( urlPath ) ; else { for ( InvAccess curAccess : dataset . getAccess ( ) ) { InvAccess access = copyAccess ( curAccess , resultDs , availableServices ) ; if ( access != null ) resultDs . addAccess ( access ) ; } } } // Only recurse into child datasets if the current dataset is not an InvCatalogRef. if ( ! ( dataset instanceof InvCatalogRef ) ) { for ( InvDataset curDs : dataset . getDatasets ( ) ) { InvDatasetImpl curDsCopy = ( InvDatasetImpl ) copyDataset ( curDs , availableServices , false ) ; curDsCopy . setParent ( resultDs ) ; resultDs . addDataset ( curDsCopy ) ; } } return resultDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * 14 . 1 <BC_TableB_BUFR14_1_0_CREX_6_1_0 > <SNo > 1< / SNo > <Class > 00< / Class > <FXY > 000001< / FXY > <ElementName_E > Table A : entry< / ElementName_E > <ElementName_F > Table A : entr?e< / ElementName_F > <ElementName_R > ??????? ? : ???????< / ElementName_R > <ElementName_S > Tabla A : elemento< / ElementName_S > <BUFR_Unit > CCITT IA5< / BUFR_Unit > <BUFR_Scale > 0< / BUFR_Scale > <BUFR_ReferenceValue > 0< / BUFR_ReferenceValue > <BUFR_DataWidth_Bits > 24< / BUFR_DataWidth_Bits > <CREX_Unit > Character< / CREX_Unit > <CREX_Scale > 0< / CREX_Scale > <CREX_DataWidth > 3< / CREX_DataWidth > <Status > Operational< / Status > <NotesToTable_E > Notes : ( see ) #BUFR14_1_0_CREX6_1_0_Notes . doc#BC_Cl000< / NotesToTable_E > < / BC_TableB_BUFR14_1_0_CREX_6_1_0 > [CODESPLIT] static void readWmoXmlTableB ( InputStream ios , TableB b ) throws IOException { org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( ios ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } Element root = doc . getRootElement ( ) ; String [ ] elems = null ; for ( Version v : Version . values ( ) ) { elems = v . getElemNamesB ( ) ; List < Element > featList = root . getChildren ( elems [ 0 ] ) ; if ( featList != null && featList . size ( ) > 0 ) { break ; } } // if not found using element name, assume its BUFR_WMO\r if ( elems == null ) { elems = Version . BUFR_WMO . getElemNamesB ( ) ; } List < Element > featList = root . getChildren ( ) ; for ( Element elem : featList ) { Element ce = elem . getChild ( elems [ 1 ] ) ; if ( ce == null ) continue ; String name = Util . cleanName ( elem . getChildTextNormalize ( elems [ 1 ] ) ) ; String units = cleanUnit ( elem . getChildTextNormalize ( \"BUFR_Unit\" ) ) ; int x = 0 , y = 0 , scale = 0 , reference = 0 , width = 0 ; String fxy = null ; String s = null ; try { fxy = elem . getChildTextNormalize ( \"FXY\" ) ; int xy = Integer . parseInt ( cleanNumber ( fxy ) ) ; x = xy / 1000 ; y = xy % 1000 ; } catch ( NumberFormatException e ) { System . out . printf ( \" key %s name '%s' fails parsing %n\" , fxy , name ) ; } try { s = elem . getChildTextNormalize ( \"BUFR_Scale\" ) ; scale = Integer . parseInt ( cleanNumber ( s ) ) ; } catch ( NumberFormatException e ) { System . out . printf ( \" key %s name '%s' has bad scale='%s'%n\" , fxy , name , s ) ; } try { s = elem . getChildTextNormalize ( \"BUFR_ReferenceValue\" ) ; reference = Integer . parseInt ( cleanNumber ( s ) ) ; } catch ( NumberFormatException e ) { System . out . printf ( \" key %s name '%s' has bad reference='%s' %n\" , fxy , name , s ) ; } try { s = elem . getChildTextNormalize ( \"BUFR_DataWidth_Bits\" ) ; width = Integer . parseInt ( cleanNumber ( s ) ) ; } catch ( NumberFormatException e ) { System . out . printf ( \" key %s name '%s' has bad width='%s' %n\" , fxy , name , s ) ; } b . addDescriptor ( ( short ) x , ( short ) y , scale , reference , width , name , units , null ) ; } ios . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <B_TableD_BUFR14_1_0_CREX_6_1_0 > <SNo > 2647< / SNo > <Category > 10< / Category > <FXY1 > 310013< / FXY1 > <ElementName1_E > ( AVHRR ( GAC ) report ) < / ElementName1_E > <FXY2 > 004005< / FXY2 > <ElementName2_E > Minute< / ElementName2_E > <Remarks_E > Minute< / Remarks_E > <Status > Operational< / Status > < / B_TableD_BUFR14_1_0_CREX_6_1_0 > [CODESPLIT] static void readWmoXmlTableD ( InputStream ios , TableD tableD ) throws IOException { org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( ios ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } int currSeqno = - 1 ; TableD . Descriptor currDesc = null ; Element root = doc . getRootElement ( ) ; String [ ] elems = null ; for ( Version v : Version . values ( ) ) { elems = v . getElemNamesD ( ) ; List < Element > featList = root . getChildren ( elems [ 0 ] ) ; if ( featList != null && featList . size ( ) > 0 ) { break ; } } if ( elems == null ) { elems = Version . BUFR_WMO . getElemNamesD ( ) ; } List < Element > featList = root . getChildren ( ) ; for ( Element elem : featList ) { Element ce = elem . getChild ( elems [ 1 ] ) ; if ( ce == null ) continue ; String seqs = elem . getChildTextNormalize ( \"FXY1\" ) ; int seq = Integer . parseInt ( seqs ) ; if ( currSeqno != seq ) { int y = seq % 1000 ; int w = seq / 1000 ; int x = w % 100 ; String seqName = Util . cleanName ( elem . getChildTextNormalize ( elems [ 1 ] ) ) ; currDesc = tableD . addDescriptor ( ( short ) x , ( short ) y , seqName , new ArrayList < Short > ( ) ) ; currSeqno = seq ; } String fnos = elem . getChildTextNormalize ( \"FXY2\" ) ; int fno = Integer . parseInt ( fnos ) ; int y = fno % 1000 ; int w = fno / 1000 ; int x = w % 100 ; int f = w / 100 ; int fxy = ( f << 14 ) + ( x << 8 ) + y ; currDesc . addFeature ( ( short ) fxy ) ; } ios . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Gds { bytes gds = 1 ; // raw gds : Grib1SectionGridDefinition or Grib2SectionGridDefinition uint32 predefinedGridDefinition = 2 ; // only grib1 ; instead of gds raw bytes ; need center subcenter to interpret } [CODESPLIT] static GribCollectionProto . Gds writeGdsProto ( byte [ ] rawGds , int predefinedGridDefinition ) { GribCollectionProto . Gds . Builder b = GribCollectionProto . Gds . newBuilder ( ) ; if ( predefinedGridDefinition >= 0 ) b . setPredefinedGridDefinition ( predefinedGridDefinition ) ; else { b . setGds ( ByteString . copyFrom ( rawGds ) ) ; } return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Coord { GribAxisType axisType = 1 ; int32 code = 2 ; // time unit ; level type string unit = 3 ; repeated float values = 4 ; repeated float bound = 5 ; // only used if interval then = ( value bound ) repeated int64 msecs = 6 ; // calendar date [CODESPLIT] GribCollectionProto . Coord writeCoordProto ( CoordinateRuntime coord ) { GribCollectionProto . Coord . Builder b = GribCollectionProto . Coord . newBuilder ( ) ; b . setAxisType ( convertAxisType ( coord . getType ( ) ) ) ; b . setCode ( coord . getCode ( ) ) ; if ( coord . getUnit ( ) != null ) b . setUnit ( coord . getUnit ( ) ) ; for ( int idx = 0 ; idx < coord . getSize ( ) ; idx ++ ) { long runtime = coord . getRuntime ( idx ) ; b . addMsecs ( runtime ) ; } return b . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * not currently used [CODESPLIT] public static GribCollectionProto . GribAxisType convertAxisType ( Coordinate . Type type ) { switch ( type ) { case runtime : return GribCollectionProto . GribAxisType . runtime ; case time : return GribCollectionProto . GribAxisType . time ; case time2D : return GribCollectionProto . GribAxisType . time2D ; case timeIntv : return GribCollectionProto . GribAxisType . timeIntv ; case ens : return GribCollectionProto . GribAxisType . ens ; case vert : return GribCollectionProto . GribAxisType . vert ; } throw new IllegalStateException ( \"illegal axis type \" + type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selected consult or iterator overrides for efficiency [CODESPLIT] @ Override public boolean references ( DapNode node ) { switch ( node . getSort ( ) ) { case DIMENSION : case ENUMERATION : case VARIABLE : case GROUP : case DATASET : return true ; default : break ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a unit specification . This method is thread - safe . [CODESPLIT] public final Unit parse ( final String spec ) throws NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , UnitSystemException { synchronized ( MUTEX ) { return parse ( spec , UnitDBManager . instance ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort Ray objects in the same sweep according to the ascended azimuth ( from 0 to 360 ) and time . [CODESPLIT] void checkSort ( Ray [ ] r ) { int j = 0 , n = 0 , n1 = 0 , n2 = 0 ; short time1 = 0 , time2 = 0 ; int [ ] k1 = new int [ 300 ] ; int [ ] k2 = new int [ 300 ] ; //      define the groups of rays with the same \"time\". For ex.:\r //      group1 - ray[0]={time=1,az=344}, ray[1]={time=1,az=345}, ... ray[11]={time=1,az=359}\r //      group2 - ray[12]={time=1,az=0}, ray[13]={time=1,az=1}, ... ray[15]={time=1,az=5}\r //      k1- array of begin indx (0,12), k2- array of end indx (11,15)\r for ( int i = 0 ; i < r . length - 1 ; i ++ ) { time1 = r [ i ] . getTime ( ) ; time2 = r [ i + 1 ] . getTime ( ) ; if ( time1 != time2 ) { k2 [ j ] = i ; j = j + 1 ; k1 [ j ] = i + 1 ; } } if ( k2 [ j ] < r . length - 1 ) { k1 [ j ] = k2 [ j - 1 ] + 1 ; k2 [ j ] = r . length - 1 ; n = j + 1 ; } //      if different groups have the same value of \"time\" (may be 2 and more groups) -\r //      it1= indx of \"k1\" of 1st group, it2= indx of \"k2\" of last group\r int it1 = 0 , it2 = 0 ; for ( int ii = 0 ; ii < j + 1 ; ii ++ ) { n1 = k1 [ ii ] ; for ( int i = 0 ; i < j + 1 ; i ++ ) { if ( i != ii ) { n2 = k1 [ i ] ; if ( r [ n1 ] . getTime ( ) == r [ n2 ] . getTime ( ) ) { it1 = ii ; it2 = i ; } } } } n1 = k1 [ it1 ] ; n2 = k1 [ it2 ] ; int s1 = k2 [ it1 ] - k1 [ it1 ] + 1 ; int s2 = k2 [ it2 ] - k1 [ it2 ] + 1 ; float [ ] t0 = new float [ s1 ] ; float [ ] t00 = new float [ s2 ] ; for ( int i = 0 ; i < s1 ; i ++ ) { t0 [ i ] = r [ n1 + i ] . getAz ( ) ; } for ( int i = 0 ; i < s2 ; i ++ ) { t00 [ i ] = r [ n2 + i ] . getAz ( ) ; } float mx0 = t0 [ 0 ] ; for ( int i = 0 ; i < s1 ; i ++ ) { if ( mx0 < t0 [ i ] ) mx0 = t0 [ i ] ; } float mx00 = t00 [ 0 ] ; for ( int i = 0 ; i < s2 ; i ++ ) { if ( mx00 < t00 [ i ] ) mx00 = t00 [ i ] ; } if ( ( mx0 > 330.0f & mx00 < 50.0f ) ) { for ( int i = 0 ; i < s1 ; i ++ ) { float q = r [ n1 + i ] . getAz ( ) ; r [ n1 + i ] . setAz ( q - 360.0f ) ; } } Arrays . sort ( r , new RayComparator ( ) ) ; for ( int i = 0 ; i < r . length ; i ++ ) { float a = r [ i ] . getAz ( ) ; if ( a < 0 & a > - 361.0f ) { float qa = r [ i ] . getAz ( ) ; r [ i ] . setAz ( qa + 360.0f ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show me lots of stuff about the passed in object [CODESPLIT] public static void probeObject ( Object o ) { Class c = o . getClass ( ) ; Class interfaces [ ] = c . getInterfaces ( ) ; Class parent = c . getSuperclass ( ) ; Method m [ ] = c . getMethods ( ) ; System . out . println ( \"********* OBJECT PROBE *********\" ) ; System . out . println ( \"Class Name:  \" + c . getName ( ) ) ; System . out . println ( \"Super Class: \" + parent . getName ( ) ) ; System . out . println ( \"Interfaces: \" ) ; for ( int i = 0 ; i < interfaces . length ; i ++ ) { System . out . println ( \"    \" + interfaces [ i ] . getName ( ) ) ; } System . out . println ( \"Methods:\" ) ; for ( int i = 0 ; i < m . length ; i ++ ) { Class params [ ] = m [ i ] . getParameterTypes ( ) ; Class excepts [ ] = m [ i ] . getExceptionTypes ( ) ; Class ret = m [ i ] . getReturnType ( ) ; System . out . print ( \"    \" + ret . getName ( ) + \"  \" + m [ i ] . getName ( ) + \"(\" ) ; for ( int j = 0 ; j < params . length ; j ++ ) { if ( j > 0 ) System . out . print ( \", \" ) ; System . out . print ( params [ j ] . getName ( ) ) ; } System . out . print ( \")  throws \" ) ; for ( int j = 0 ; j < excepts . length ; j ++ ) { if ( j > 0 ) System . out . print ( \", \" ) ; System . out . print ( excepts [ j ] . getName ( ) ) ; } System . out . println ( \"\" ) ; } System . out . println ( \"******************\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a subset of the data to a <code > DataOutputStream< / code > . [CODESPLIT] public void externalize ( DataOutputStream sink , int start , int stop , int stride ) throws IOException { for ( int i = start ; i <= stop ; i += stride ) sink . writeInt ( ( int ) vals [ i ] ) ; } /**\r\n     * Returns (a reference to) the internal storage for this PrimitiveVector\r\n     * object.\r\n     * <h2>WARNING:</h2>\r\n     * Because this method breaks encapsulation rules the user must beware!\r\n     * If we (the OPeNDAP prgramming team) choose to change the internal\r\n     * representation(s) of these types your code will probably break.\r\n     * <p/>\r\n     * This method is provided as an optimization to eliminate massive\r\n     * copying of data.\r\n     *\r\n     * @return The internal array of shorts.\r\n     */ public Object getInternalStorage ( ) { return ( vals ) ; } /**\r\n     * Set the internal storage for PrimitiveVector.\r\n     * <h2><i>WARNING:</i></h2>\r\n     * Because this method breaks encapsulation rules the user must beware!\r\n     * If we (the OPeNDAP prgramming team) choose to change the internal\r\n     * representation(s) of these types your code will probably break.\r\n     * <p/>\r\n     * This method is provided as an optimization to eliminate massive\r\n     * copying of data.\r\n     */ public void setInternalStorage  ( Object o ) { vals = ( short [ ] ) o ; } /**\r\n     * Create a new primitive vector using a subset of the data.\r\n     *\r\n     * @param start  starting index (i=start)\r\n     * @param stop   ending index (i<=stop)\r\n     * @param stride index stride (i+=stride)\r\n     * @return new primitive vector, of type Int16PrimitiveVector.\r\n     */ public PrimitiveVector subset  ( int start , int stop , int stride ) { Int16PrimitiveVector n = new Int16PrimitiveVector ( getTemplate ( ) ) ; stride = Math . max ( stride , 1 ) ; stop = Math . max ( start , stop ) ; int length = 1 + ( stop - start ) / stride ; n . setLength ( length ) ; int count = 0 ; for ( int i = start ; i <= stop ; i += stride ) { n . setValue ( count , vals [ i ] ) ; count ++ ; } return n ; } /**\r\n   * Prints the value of the variable, with its declaration.  This\r\n   * function is primarily intended for debugging OPeNDAP applications and\r\n   * text-based clients such as geturl.\r\n   *\r\n   * @param os           the <code>PrintWriter</code> on which to print the value.\r\n   * @param space        this value is passed to the <code>printDecl</code> method,\r\n   *                     and controls the leading spaces of the output.\r\n   * @param print_decl_p a boolean value controlling whether the\r\n   *                     variable declaration is printed as well as the value.\r\n   */ public void printVal  ( PrintWriter os , String space , boolean print_decl_p ) { } /**\r\n     * Returns a clone of this <code>Int16PrimitiveVector</code>.\r\n     * See DAPNode.cloneDag()\r\n     *\r\n     * @param map track previously cloned nodes\r\n     * @return a clone of this <code>Int16PrimitiveVector</code>.\r\n     */ public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { Int16PrimitiveVector v = ( Int16PrimitiveVector ) super . cloneDAG ( map ) ; if ( vals != null ) { v . vals = new short [ vals . length ] ; System . arraycopy ( vals , 0 , v . vals , 0 , vals . length ) ; } return v ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a variable is tiled if any of its dimensions are tiled [CODESPLIT] private boolean isTiled ( Variable v ) { for ( Dimension d : v . getDimensions ( ) ) { for ( Range r : section . getRanges ( ) ) { if ( d . getShortName ( ) . equals ( r . getName ( ) ) ) return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements coverting a complete best to a monotonic best . The reftime is not allowed to decrease [CODESPLIT] public CoordinateTimeAbstract makeBestFromComplete ( ) { int [ ] best = new int [ time2runtime . length ] ; int last = - 1 ; int count = 0 ; for ( int i = 0 ; i < time2runtime . length ; i ++ ) { int time = time2runtime [ i ] ; if ( time >= last ) { last = time ; best [ i ] = time ; count ++ ; } else { best [ i ] = - 1 ; } } return makeBestFromComplete ( best , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl result ) { result . setLocation ( LatLonPointImpl . lonNormal ( latlon . getLongitude ( ) , centerLon ) , latlon . getLatitude ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { result . setLongitude ( world . getX ( ) ) ; result . setLatitude ( world . getY ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { float [ ] fromX = from [ INDEX_X ] ; float [ ] fromY = from [ INDEX_Y ] ; to [ INDEX_LAT ] = fromY ; to [ INDEX_LON ] = fromX ; return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public double [ ] [ ] latLonToProj ( double [ ] [ ] from , double [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; double [ ] toX = to [ INDEX_X ] ; double [ ] toY = to [ INDEX_Y ] ; double [ ] fromLat = from [ latIndex ] ; double [ ] fromLon = from [ lonIndex ] ; double lat , lon ; for ( int i = 0 ; i < cnt ; i ++ ) { lat = fromLat [ i ] ; lon = centerLon + Math . IEEEremainder ( fromLon [ i ] - centerLon , 360.0 ) ; toX [ i ] = lon ; toY [ i ] = lat ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the line between these two points cross the projection seam . [CODESPLIT] public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { return Math . abs ( pt1 . getX ( ) - pt2 . getX ( ) ) > 270.0 ; // ?? LOOK: do I believe this\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a latlon rectangle to the equivalent ProjectionRect using this LatLonProjection to split it at the seam if needed . [CODESPLIT] public ProjectionRect [ ] latLonToProjRect ( LatLonRect latlonR ) { double lat0 = latlonR . getLowerLeftPoint ( ) . getLatitude ( ) ; double height = Math . abs ( latlonR . getUpperRightPoint ( ) . getLatitude ( ) - lat0 ) ; double width = latlonR . getWidth ( ) ; double lon0 = LatLonPointImpl . lonNormal ( latlonR . getLowerLeftPoint ( ) . getLongitude ( ) , centerLon ) ; double lon1 = LatLonPointImpl . lonNormal ( latlonR . getUpperRightPoint ( ) . getLongitude ( ) , centerLon ) ; ProjectionRect [ ] rects = new ProjectionRect [ ] { new ProjectionRect ( ) , new ProjectionRect ( ) } ; if ( lon0 < lon1 ) { rects [ 0 ] . setRect ( lon0 , lat0 , width , height ) ; rects [ 1 ] = null ; } else { double y = centerLon + 180 - lon0 ; rects [ 0 ] . setRect ( lon0 , lat0 , y , height ) ; rects [ 1 ] . setRect ( lon1 - width + y , lat0 , width - y , height ) ; } return rects ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a latlon rectangle and split it into the equivalent ProjectionRect using this LatLonProjection . The latlon rect is constructed from 2 lat / lon points . The lon values are considered coords in the latlonProjection and so do not have to be + / - 180 . [CODESPLIT] public ProjectionRect [ ] latLonToProjRect ( double lat0 , double lon0 , double lat1 , double lon1 ) { double height = Math . abs ( lat1 - lat0 ) ; lat0 = Math . min ( lat1 , lat0 ) ; double width = lon1 - lon0 ; if ( width < 1.0e-8 ) { width = 360.0 ; // assume its the whole thing\r } lon0 = LatLonPointImpl . lonNormal ( lon0 , centerLon ) ; lon1 = LatLonPointImpl . lonNormal ( lon1 , centerLon ) ; ProjectionRect [ ] rects = new ProjectionRect [ ] { new ProjectionRect ( ) , new ProjectionRect ( ) } ; if ( width >= 360.0 ) { rects [ 0 ] . setRect ( centerLon - 180.0 , lat0 , 360.0 , height ) ; rects [ 1 ] = null ; } else if ( lon0 < lon1 ) { rects [ 0 ] . setRect ( lon0 , lat0 , width , height ) ; rects [ 1 ] = null ; } else { double y = centerLon + 180 - lon0 ; rects [ 0 ] . setRect ( lon0 , lat0 , y , height ) ; rects [ 1 ] . setRect ( lon1 - width + y , lat0 , width - y , height ) ; } return rects ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK change to ResponseEntity<String > [CODESPLIT] @ RequestMapping ( method = RequestMethod . GET ) protected void showDebugPage ( HttpServletRequest request , HttpServletResponse response ) throws IOException { response . setContentType ( ContentType . html . getContentHeader ( ) ) ; response . setHeader ( \"Content-Description\" , \"thredds_debug\" ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; PrintStream pw = new PrintStream ( bos , false , CDM . UTF8 ) ; pw . println ( htmlu . getHtmlDoctypeAndOpenTag ( ) ) ; pw . println ( \"<head>\" ) ; pw . println ( \"<title>THREDDS Debug</title>\" ) ; pw . println ( \"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html\\\">\" ) ; pw . println ( htmlu . getTdsPageCssLink ( ) ) ; pw . println ( htmlu . getGoogleTrackingContent ( ) ) ; pw . println ( \"</head>\" ) ; pw . println ( \"<body>\" ) ; pw . println ( htmlu . getOldStyleHeader ( ) ) ; pw . println ( \"<br><a href='dir/content/thredds/logs/'>Show TDS Logs</a>\" ) ; pw . println ( \"<br><a href='dir/content/tdm/'>Show TDM Logs</a>\" ) ; pw . println ( \"<br><a href='dir/logs/'>Show Tomcat Logs</a>\" ) ; pw . println ( \"<br><a href='dir/catalogs/'>Show Config Catalogs</a>\" ) ; pw . println ( \"<br><a href='spring/showControllers'>Show Spring Controllers</a>\" ) ; pw . println ( \"<h2>Debug Actions</h2>\" ) ; pw . println ( \"<pre>\" ) ; String cmds = request . getQueryString ( ) ; if ( ( cmds == null ) || ( cmds . length ( ) == 0 ) ) { showDebugActions ( request , pw ) ; } else { StringTokenizer tz = new StringTokenizer ( cmds , \";\" ) ; while ( tz . hasMoreTokens ( ) ) { String cmd = tz . nextToken ( ) ; String target = null ; pw . println ( \"Cmd= \" + cmd ) ; int pos = cmd . indexOf ( ' ' ) ; String dhName = \"General\" ; if ( pos > 0 ) { dhName = cmd . substring ( 0 , pos ) ; cmd = cmd . substring ( pos + 1 ) ; } pos = cmd . indexOf ( ' ' ) ; if ( pos >= 0 ) { target = cmd . substring ( pos + 1 ) ; cmd = cmd . substring ( 0 , pos ) ; } DebugCommands . Category dh = debugCommands . findCategory ( dhName ) ; if ( dh == null ) { pw . println ( \" Unknown Debug Category=\" + dhName + \"=\" ) ; } else { DebugCommands . Action action = dh . actions . get ( cmd ) ; if ( action == null ) pw . println ( \" Unknown action=\" + cmd + \"=\" ) ; else action . doAction ( new DebugCommands . Event ( request , response , pw , bos , target ) ) ; } } } pw . println ( \"</pre></body></html>\" ) ; response . setStatus ( HttpServletResponse . SC_OK ) ; // send it out PrintWriter responsePS = response . getWriter ( ) ; responsePS . write ( bos . toString ( CDM . UTF8 ) ) ; responsePS . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "everything but header data which is binary data and capabilities which is XML [CODESPLIT] @ RequestMapping ( value = \"/**\" , method = RequestMethod . GET ) public ResponseEntity < String > handleCapabilitiesRequest ( HttpServletRequest request , HttpServletResponse response , @ RequestParam String req ) throws IOException { if ( ! allowedServices . isAllowed ( StandardService . cdmRemote ) ) throw new ServiceNotAllowed ( StandardService . cdmRemote . toString ( ) ) ; String datasetPath = TdsPathUtils . extractPath ( request , \"/cdmremote\" ) ; String absPath = getAbsolutePath ( request ) ; HttpHeaders responseHeaders ; if ( showReq ) System . out . printf ( \"CdmRemoteController req=%s%n\" , absPath + \"?\" + request . getQueryString ( ) ) ; if ( debug ) System . out . printf ( \" path=%s%n query=%s%n\" , datasetPath , request . getQueryString ( ) ) ; // LOOK heres where we want the Dataset, not the netcdfFile (!)\r try ( NetcdfFile ncfile = TdsRequestedDataset . getNetcdfFile ( request , response , datasetPath ) ) { if ( ncfile == null ) return null ; // failed resource control\r responseHeaders = new HttpHeaders ( ) ; responseHeaders . setDate ( \"Last-Modified\" , TdsRequestedDataset . getLastModified ( datasetPath ) ) ; // a request without a parameter is a test to see if this is a valid cdremote endpoint.\r // just setHeader(\"Content-Description\", \"ncstream\"), no body\r // on client, see DatasetUrl.disambiguateHttp\r if ( req == null ) { response . setContentType ( ContentType . binary . getContentHeader ( ) ) ; response . setHeader ( \"Content-Description\" , \"ncstream\" ) ; return new ResponseEntity <> ( null , responseHeaders , HttpStatus . OK ) ; } switch ( req . toLowerCase ( ) ) { case \"form\" : // ol\r case \"cdl\" : ncfile . setLocation ( datasetPath ) ; // hide where the file is stored  LOOK\r String cdl = ncfile . toString ( ) ; responseHeaders . set ( ContentType . HEADER , ContentType . text . getContentHeader ( ) ) ; return new ResponseEntity <> ( cdl , responseHeaders , HttpStatus . OK ) ; case \"ncml\" : String ncml = ncfile . toNcML ( absPath ) ; responseHeaders . set ( ContentType . HEADER , ContentType . xml . getContentHeader ( ) ) ; return new ResponseEntity <> ( ncml , responseHeaders , HttpStatus . OK ) ; default : return new ResponseEntity <> ( \"Unrecognized request\" , null , HttpStatus . BAD_REQUEST ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "experimental : should be package private [CODESPLIT] int setDirect ( int v0 , int v1 , int v2 , int v3 , int v4 ) { return offset + v0 * stride0 + v1 * stride1 + v2 * stride2 + v3 * stride3 + v4 * stride4 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "construct the TImeSeries plot for the list of logs passed in [CODESPLIT] private void showTimeSeriesAll ( java . util . List < LogReader . Log > logs ) { TimeSeries bytesSentData = new TimeSeries ( \"Bytes Sent\" , Minute . class ) ; TimeSeries timeTookData = new TimeSeries ( \"Average Latency\" , Minute . class ) ; TimeSeries nreqData = new TimeSeries ( \"Number of Requests\" , Minute . class ) ; String intervalS = \"5 minute\" ; // interval.getText().trim(); // if (intervalS.length() == 0) intervalS = \"5 minute\"; long period = 1000 * 60 * 5 ; try { TimeDuration tu = new TimeDuration ( intervalS ) ; period = ( long ) ( 1000 * tu . getValueInSeconds ( ) ) ; } catch ( Exception e ) { System . out . printf ( \"Illegal Time interval=%s %n\" , intervalS ) ; } long current = 0 ; long bytes = 0 ; long timeTook = 0 ; long total_count = 0 ; long count = 0 ; for ( LogReader . Log log : logs ) { long msecs = log . date ; if ( msecs - current > period ) { if ( current > 0 ) { total_count += count ; addPoint ( bytesSentData , timeTookData , nreqData , new Date ( current ) , bytes , count , timeTook ) ; } bytes = 0 ; count = 0 ; timeTook = 0 ; current = msecs ; } bytes += log . getBytes ( ) ; timeTook += log . getMsecs ( ) ; count ++ ; } if ( count > 0 ) addPoint ( bytesSentData , timeTookData , nreqData , new Date ( current ) , bytes , count , timeTook ) ; total_count += count ; System . out . printf ( \"showTimeSeriesAll: total_count = %d logs = %d%n\" , total_count , logs . size ( ) ) ; MultipleAxisChart mc = new MultipleAxisChart ( \"Access Logs\" , intervalS + \" average\" , \"Mbytes Sent\" , bytesSentData ) ; mc . addSeries ( \"Number of Requests\" , nreqData ) ; mc . addSeries ( \"Average Latency (secs)\" , timeTookData ) ; mc . finish ( new java . awt . Dimension ( 1000 , 1000 ) ) ; //MultipleAxisChart mc = new MultipleAxisChart(\"Bytes Sent\", \"5 min average\", \"Mbytes/sec\", bytesSentData); //Chart c2 = new Chart(\"Average Latency\", \"5 min average\", \"Millisecs\", timeTookData); //Chart c3 = new Chart(\"Number of Requests/sec\", \"5 min average\", \"\", nreqData); timeSeriesPanel . removeAll ( ) ; timeSeriesPanel . add ( mc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turn a list into a map [CODESPLIT] static public Map < String , Attribute > makeMap ( List < Attribute > atts ) { int size = ( atts == null ) ? 1 : atts . size ( ) ; Map < String , Attribute > result = new HashMap <> ( size ) ; if ( atts == null ) return result ; for ( Attribute att : atts ) result . put ( att . getShortName ( ) , att ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value as an Array . [CODESPLIT] public Array getValues ( ) { if ( values == null && svalue != null ) { values = Array . factory ( DataType . STRING , new int [ ] { 1 } ) ; values . setObject ( values . getIndex ( ) , svalue ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve String value ; only call if isString () is true . [CODESPLIT] public String getStringValue ( ) { if ( dataType != DataType . STRING ) return null ; return ( svalue != null ) ? svalue : _getStringValue ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve a numeric value by index . If it s a String it will try to parse it as a double . [CODESPLIT] public Number getNumericValue ( int index ) { if ( ( index < 0 ) || ( index >= nelems ) ) return null ; // LOOK can attributes be enum valued? for now, no switch ( dataType ) { case STRING : try { return new Double ( getStringValue ( index ) ) ; } catch ( NumberFormatException e ) { return null ; } case BYTE : case UBYTE : return values . getByte ( index ) ; case SHORT : case USHORT : return values . getShort ( index ) ; case INT : case UINT : return values . getInt ( index ) ; case FLOAT : return values . getFloat ( index ) ; case DOUBLE : return values . getDouble ( index ) ; case LONG : case ULONG : return values . getLong ( index ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write CDL representation into f [CODESPLIT] protected void writeCDL ( Formatter f , boolean strict , String parentname ) { if ( strict && ( isString ( ) || this . getEnumType ( ) != null ) ) // Force type explicitly for string. f . format ( \"string \" ) ; //note lower case and trailing blank if ( strict && parentname != null ) f . format ( NetcdfFile . makeValidCDLName ( parentname ) ) ; f . format ( \":\" ) ; f . format ( \"%s\" , strict ? NetcdfFile . makeValidCDLName ( getShortName ( ) ) : getShortName ( ) ) ; if ( isString ( ) ) { f . format ( \" = \" ) ; for ( int i = 0 ; i < getLength ( ) ; i ++ ) { if ( i != 0 ) f . format ( \", \" ) ; String val = getStringValue ( i ) ; if ( val != null ) f . format ( \"\\\"%s\\\"\" , encodeString ( val ) ) ; } } else if ( getEnumType ( ) != null ) { f . format ( \" = \" ) ; for ( int i = 0 ; i < getLength ( ) ; i ++ ) { if ( i != 0 ) f . format ( \", \" ) ; EnumTypedef en = getEnumType ( ) ; String econst = getStringValue ( i ) ; Integer ecint = en . lookupEnumInt ( econst ) ; if ( ecint == null ) throw new ForbiddenConversionException ( \"Illegal enum constant: \" + econst ) ; f . format ( \"\\\"%s\\\"\" , encodeString ( econst ) ) ; } } else { f . format ( \" = \" ) ; for ( int i = 0 ; i < getLength ( ) ; i ++ ) { if ( i != 0 ) f . format ( \", \" ) ; Number number = getNumericValue ( i ) ; if ( dataType . isUnsigned ( ) ) { // 'number' is unsigned, but will be treated as signed when we print it below, because Java only has signed // types. If it is large enough ( >= 2^(BIT_WIDTH-1) ), its most-significant bit will be interpreted as the // sign bit, which will result in an invalid (negative) value being printed. To prevent that, we're going // to widen the number before printing it. number = DataType . widenNumber ( number ) ; } f . format ( \"%s\" , number ) ; if ( dataType . isUnsigned ( ) ) { f . format ( \"U\" ) ; } if ( dataType == DataType . FLOAT ) f . format ( \"f\" ) ; else if ( dataType == DataType . SHORT || dataType == DataType . USHORT ) { f . format ( \"S\" ) ; } else if ( dataType == DataType . BYTE || dataType == DataType . UBYTE ) { f . format ( \"B\" ) ; } else if ( dataType == DataType . LONG || dataType == DataType . ULONG ) { f . format ( \"L\" ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the value as a String trimming trailing zeroes [CODESPLIT] private void setStringValue ( String val ) { if ( val == null ) throw new IllegalArgumentException ( \"Attribute value cannot be null\" ) ; // get rid of trailing nul characters int len = val . length ( ) ; while ( ( len > 0 ) && ( val . charAt ( len - 1 ) == 0 ) ) len -- ; if ( len != val . length ( ) ) val = val . substring ( 0 , len ) ; this . svalue = val ; this . nelems = 1 ; this . dataType = DataType . STRING ; //values = Array.factory(String.class, new int[]{1}); //values.setObject(values.getIndex(), val); //setValues(values); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the values from a list [CODESPLIT] public void setValues ( List values ) { if ( values == null || values . size ( ) == 0 ) throw new IllegalArgumentException ( \"Cannot determine attribute's type\" ) ; int n = values . size ( ) ; Class c = values . get ( 0 ) . getClass ( ) ; Object pa ; if ( c == String . class ) { String [ ] va = new String [ n ] ; pa = va ; for ( int i = 0 ; i < n ; i ++ ) va [ i ] = ( String ) values . get ( i ) ; } else if ( c == Integer . class ) { int [ ] va = new int [ n ] ; pa = va ; for ( int i = 0 ; i < n ; i ++ ) va [ i ] = ( Integer ) values . get ( i ) ; } else if ( c == Double . class ) { double [ ] va = new double [ n ] ; pa = va ; for ( int i = 0 ; i < n ; i ++ ) va [ i ] = ( Double ) values . get ( i ) ; } else if ( c == Float . class ) { float [ ] va = new float [ n ] ; pa = va ; for ( int i = 0 ; i < n ; i ++ ) va [ i ] = ( Float ) values . get ( i ) ; } else if ( c == Short . class ) { short [ ] va = new short [ n ] ; pa = va ; for ( int i = 0 ; i < n ; i ++ ) va [ i ] = ( Short ) values . get ( i ) ; } else if ( c == Byte . class ) { byte [ ] va = new byte [ n ] ; pa = va ; for ( int i = 0 ; i < n ; i ++ ) va [ i ] = ( Byte ) values . get ( i ) ; } else if ( c == Long . class ) { long [ ] va = new long [ n ] ; pa = va ; for ( int i = 0 ; i < n ; i ++ ) va [ i ] = ( Long ) values . get ( i ) ; } else { throw new IllegalArgumentException ( \"Unknown type for Attribute = \" + c . getName ( ) ) ; } setValues ( Array . factory ( this . dataType , new int [ ] { n } , pa ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the values from an Array [CODESPLIT] public void setValues ( Array arr ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( arr == null ) { dataType = DataType . STRING ; return ; } if ( arr . getElementType ( ) == char . class ) { // turn CHAR into STRING ArrayChar carr = ( ArrayChar ) arr ; if ( carr . getRank ( ) == 1 ) { // common case svalue = carr . getString ( ) ; this . nelems = 1 ; this . dataType = DataType . STRING ; return ; } // otherwise its an array of Strings arr = carr . make1DStringArray ( ) ; } // this should be a utility somewhere if ( arr . getElementType ( ) == ByteBuffer . class ) { // turn OPAQUE into BYTE int totalLen = 0 ; arr . resetLocalIterator ( ) ; while ( arr . hasNext ( ) ) { ByteBuffer bb = ( ByteBuffer ) arr . next ( ) ; totalLen += bb . limit ( ) ; } byte [ ] ba = new byte [ totalLen ] ; int pos = 0 ; arr . resetLocalIterator ( ) ; while ( arr . hasNext ( ) ) { ByteBuffer bb = ( ByteBuffer ) arr . next ( ) ; System . arraycopy ( bb . array ( ) , 0 , ba , pos , bb . limit ( ) ) ; pos += bb . limit ( ) ; } arr = Array . factory ( DataType . BYTE , new int [ ] { totalLen } , ba ) ; } if ( DataType . getType ( arr ) == DataType . OBJECT ) throw new IllegalArgumentException ( \"Cant set Attribute with type \" + arr . getElementType ( ) ) ; if ( arr . getRank ( ) > 1 ) arr = arr . reshape ( new int [ ] { ( int ) arr . getSize ( ) } ) ; // make sure 1D this . values = arr ; this . nelems = ( int ) arr . getSize ( ) ; this . dataType = DataType . getType ( arr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan the collection and gather information on contained datasets . [CODESPLIT] public void scan ( ) throws IOException { if ( state == 1 ) throw new IllegalStateException ( \"Scan already underway.\" ) ; if ( state >= 2 ) throw new IllegalStateException ( \"Scan has already been generated.\" ) ; state = 1 ; // Make sure proxyDsHandlers Map is not null. if ( proxyDsHandlers == null ) proxyDsHandlers = Collections . EMPTY_MAP ; // Create a skeleton catalog. genCatalog = createSkeletonCatalog ( currentLevel ) ; InvDatasetImpl topInvDs = ( InvDatasetImpl ) genCatalog . getDatasets ( ) . get ( 0 ) ; // Get the datasets in this collection. List crDsList = currentLevel . listDatasets ( this . filter ) ; // Sort the datasets in this collection. // @todo Should we move sort to end of this method? As is, we can't use naming or enhancements to determine sort order. if ( sorter != null ) sorter . sort ( crDsList ) ; // Add the datasets to the catalog. for ( int i = 0 ; i < crDsList . size ( ) ; i ++ ) //for ( Iterator it = crDsList.iterator(); it.hasNext(); ) { CrawlableDataset curCrDs = ( CrawlableDataset ) crDsList . get ( i ) ; InvDatasetImpl curInvDs = ( InvDatasetImpl ) createInvDatasetFromCrawlableDataset ( curCrDs , topInvDs , null ) ; // Add dataset info to appropriate lists. InvCrawlablePair dsInfo = new InvCrawlablePair ( curCrDs , curInvDs ) ; //allDsInfo.add( dsInfo ); if ( curCrDs . isCollection ( ) ) catRefInfo . add ( dsInfo ) ; else atomicDsInfo . add ( dsInfo ) ; // Add current InvDataset to top dataset. topInvDs . addDataset ( curInvDs ) ; } // Tie up any loose ends in catalog with finish(). ( ( InvCatalogImpl ) genCatalog ) . finish ( ) ; // Add proxy datasets to list (only if some atomic datasets in this collection). if ( atomicDsInfo . size ( ) > 0 ) { boolean anyProxiesAdded = false ; for ( Iterator it = proxyDsHandlers . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { // Get current ProxyDatasetHandler curProxy = ( ProxyDatasetHandler ) it . next ( ) ; InvService proxyService = curProxy . getProxyDatasetService ( currentLevel ) ; if ( proxyService != null ) { // Create proxy CrawlableDataset and corresponding InvDataset CrawlableDataset crDsToAdd = curProxy . createProxyDataset ( currentLevel ) ; InvDatasetImpl invDsToAdd = createInvDatasetFromCrawlableDataset ( crDsToAdd , topInvDs , proxyService ) ; // Add dataset info to appropriate lists. InvCrawlablePair dsInfo = new InvCrawlablePair ( crDsToAdd , invDsToAdd ) ; proxyDsInfo . add ( dsInfo ) ; // Add dataset to catalog int index = curProxy . getProxyDatasetLocation ( currentLevel , topInvDs . getDatasets ( ) . size ( ) ) ; topInvDs . addDataset ( index , ( InvDatasetImpl ) invDsToAdd ) ; genCatalog . addService ( proxyService ) ; anyProxiesAdded = true ; } } // Tie up any proxy dataset loose ends. if ( anyProxiesAdded ) ( ( InvCatalogImpl ) genCatalog ) . finish ( ) ; } // Add any top-level metadata. this . addTopLevelMetadata ( genCatalog , true ) ; state = 2 ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the catalog for a resolver request of the given ProxyDatasetHandler . [CODESPLIT] public InvCatalogImpl generateProxyDsResolverCatalog ( ProxyDatasetHandler pdh ) { if ( state != 2 ) throw new IllegalStateException ( \"Scan has not been performed.\" ) ; if ( ! proxyDsHandlers . containsValue ( pdh ) ) throw new IllegalArgumentException ( \"Unknown ProxyDatasetHandler.\" ) ; // Create a skeleton catalog. InvCatalogImpl catalog = createSkeletonCatalog ( currentLevel ) ; InvDatasetImpl topDs = ( InvDatasetImpl ) catalog . getDatasets ( ) . get ( 0 ) ; // Find actual dataset in the list of atomic dataset InvCrawlablePairs. InvCrawlablePair actualDsInfo = pdh . getActualDataset ( atomicDsInfo ) ; if ( actualDsInfo == null ) return catalog ; // TODO Test this case in TestDataRootHandler. InvDatasetImpl actualInvDs = ( InvDatasetImpl ) actualDsInfo . getInvDataset ( ) ; actualInvDs . setName ( pdh . getActualDatasetName ( actualDsInfo , topDs . getName ( ) ) ) ; // Add current InvDataset to top dataset. catalog . removeDataset ( topDs ) ; catalog . addDataset ( actualInvDs ) ; // topDs.addDataset( actualInvDs ); // Finish catalog. catalog . finish ( ) ; // Add any top-level metadata. this . addTopLevelMetadata ( catalog , false ) ; return catalog ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- baseID + / + node . getPath () . substring ( collectionLevel . length ) [ when ID added at catalog construction using node info ] [CODESPLIT] private String getID ( CrawlableDataset dataset ) { if ( dataset == null ) return null ; if ( collectionId == null ) return null ; int i = collectionLevel . getPath ( ) . length ( ) ; String id = dataset . getPath ( ) . substring ( i ) ; if ( id . startsWith ( \"/\" ) ) id = id . substring ( 1 ) ; if ( collectionId . equals ( \"\" ) ) { if ( id . equals ( \"\" ) ) return null ; return id ; } if ( id . equals ( \"\" ) ) return collectionId ; return ( collectionId + \"/\" + id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- collectionPath + / + node . getPath () . substring ( collectionLevel . length ) [ when service is absolute ( i . e . relative to collection ) ] [CODESPLIT] private String getUrlPath ( CrawlableDataset dataset , InvService service ) { InvService serviceForThisDs = service != null ? service : this . service ; if ( serviceForThisDs . getBase ( ) . equals ( \"\" ) && ! serviceForThisDs . getServiceType ( ) . equals ( ServiceType . COMPOUND ) ) { // Service is relative to the catalog URL. String urlPath = dataset . getPath ( ) . substring ( catalogLevel . getPath ( ) . length ( ) ) ; if ( urlPath . startsWith ( \"/\" ) ) urlPath = urlPath . substring ( 1 ) ; return urlPath ; } else { if ( serviceForThisDs . isRelativeBase ( ) ) { // Service is relative to the collection root. String relPath = dataset . getPath ( ) . substring ( collectionLevel . getPath ( ) . length ( ) ) ; if ( relPath . startsWith ( \"/\" ) ) relPath = relPath . substring ( 1 ) ; return ( ( collectionPath . equals ( \"\" ) ? \"\" : collectionPath + \"/\" ) + relPath ) ; } else { // Service base URI is Absolute so don't use collectionPath. String relPath = dataset . getPath ( ) . substring ( collectionLevel . getPath ( ) . length ( ) ) ; if ( relPath . startsWith ( \"/\" ) ) relPath = relPath . substring ( 1 ) ; return relPath ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- node . getPath () . substring ( catalogLevel . length ) + / catalog . xml [CODESPLIT] private String getXlinkHref ( CrawlableDataset dataset ) { // @todo Remove alias until sure how to handle things like \".scour*\" being a regular file. //    if ( ! CrawlableDatasetAlias.isAlias( catalogLevel.getPath()) ) //    { String path = dataset . getPath ( ) . substring ( catalogLevel . getPath ( ) . length ( ) ) ; if ( path . startsWith ( \"/\" ) ) path = path . substring ( 1 ) ; if ( path . endsWith ( \"/\" ) ) path += \"catalog.xml\" ; else path += \"/catalog.xml\" ; return CatalogUtils . escapePathForURL ( path ) ; //    } //    else //    { //      // @todo Move this functionality into CrawlableDatasetAlias //      String path = dataset.getPath(); //      int curIndex = path.length(); //      int numSegments = catalogLevel.getName().split( \"/\" ).length; //      for ( int i = 0 ; i < numSegments; i++ ) //      { //        curIndex = dataset.getPath().lastIndexOf( \"/\", curIndex - 1); //      } //      return( dataset.getPath().substring( curIndex + 1 ) + \"/catalog.xml\"); //    } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Caller must iter . finish () and out . close () . [CODESPLIT] public static int write ( OutputStream out , PointFeatureIterator pointFeatIter , String name , String timeUnitString , String altUnits ) throws IOException { int numWritten = 0 ; while ( pointFeatIter . hasNext ( ) ) { try { PointFeature pointFeat = pointFeatIter . next ( ) ; if ( numWritten == 0 ) { PointStreamProto . PointFeatureCollection protoPfc = PointStream . encodePointFeatureCollection ( name , timeUnitString , altUnits , pointFeat ) ; byte [ ] data = protoPfc . toByteArray ( ) ; PointStream . writeMagic ( out , MessageType . PointFeatureCollection ) ; NcStream . writeVInt ( out , data . length ) ; out . write ( data ) ; } PointStreamProto . PointFeature protoPointFeat = PointStream . encodePointFeature ( pointFeat ) ; byte [ ] data = protoPointFeat . toByteArray ( ) ; PointStream . writeMagic ( out , MessageType . PointFeature ) ; NcStream . writeVInt ( out , data . length ) ; out . write ( data ) ; ++ numWritten ; } catch ( Throwable t ) { NcStreamProto . Error protoError = NcStream . encodeErrorMessage ( t . getMessage ( ) != null ? t . getMessage ( ) : t . getClass ( ) . getName ( ) ) ; byte [ ] data = protoError . toByteArray ( ) ; PointStream . writeMagic ( out , PointStream . MessageType . Error ) ; NcStream . writeVInt ( out , data . length ) ; out . write ( data ) ; throw new IOException ( t ) ; } } PointStream . writeMagic ( out , PointStream . MessageType . End ) ; return numWritten ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "put a message on the queue schedule writing if not already scheduled . [CODESPLIT] void scheduleWrite ( Message m ) { q . add ( m ) ; if ( ! isScheduled . getAndSet ( true ) ) { executor . submit ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( _Debug ) System . out . println ( \"asciiGrid.toASCII(\" + addName + \",'\" + rootName + \"')  getName(): \" + getEncodedName ( ) ) ; if ( rootName != null ) rootName += \".\" + getEncodedName ( ) ; else rootName = getEncodedName ( ) ; boolean firstPass = true ; Enumeration e = getVariables ( ) ; while ( e . hasMoreElements ( ) ) { toASCII ta = ( toASCII ) e . nextElement ( ) ; if ( ! newLine && ! firstPass ) pw . print ( \", \" ) ; ta . toASCII ( pw , addName , rootName , newLine ) ; firstPass = false ; } if ( newLine ) pw . print ( \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deferred creation of components to minimize startup [CODESPLIT] public void makeComponent ( JTabbedPane parent , final String title ) { if ( parent == null ) { parent = tabbedPane ; } // find the correct index\r int n = parent . getTabCount ( ) ; int idx ; for ( idx = 0 ; idx < n ; idx ++ ) { String cTitle = parent . getTitleAt ( idx ) ; if ( cTitle . equals ( title ) ) break ; } if ( idx >= n ) { log . debug ( \"Cant find {} in {}\" , title , parent ) ; return ; } Component c ; switch ( title ) { case \"Aggregation\" : aggPanel = new AggPanel ( ( PreferencesExt ) mainPrefs . node ( \"NcMLAggregation\" ) ) ; c = aggPanel ; break ; case \"BUFR\" : bufrPanel = new BufrPanel ( ( PreferencesExt ) mainPrefs . node ( \"bufr\" ) ) ; c = bufrPanel ; break ; case \"BUFRTableB\" : bufrTableBPanel = new BufrTableBPanel ( ( PreferencesExt ) mainPrefs . node ( \"bufr2\" ) ) ; c = bufrTableBPanel ; break ; case \"BUFRTableD\" : bufrTableDPanel = new BufrTableDPanel ( ( PreferencesExt ) mainPrefs . node ( \"bufrD\" ) ) ; c = bufrTableDPanel ; break ; case \"BufrReports\" : { PreferencesExt prefs = ( PreferencesExt ) mainPrefs . node ( \"bufrReports\" ) ; ReportPanel rp = new BufrReportPanel ( prefs ) ; bufrReportPanel = new ReportOpPanel ( prefs , rp ) ; c = bufrReportPanel ; break ; } case \"BUFR-CODES\" : bufrCodePanel = new BufrCodePanel ( ( PreferencesExt ) mainPrefs . node ( \"bufr-codes\" ) ) ; c = bufrCodePanel ; break ; case \"CdmrFeature\" : cdmremotePanel = new CdmrFeatureOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"CdmrFeature\" ) ) ; c = cdmremotePanel ; break ; case \"CollectionSpec\" : fcPanel = new CollectionSpecPanel ( ( PreferencesExt ) mainPrefs . node ( \"collSpec\" ) ) ; c = fcPanel ; break ; case \"DirectoryPartition\" : dirPartPanel = new DirectoryPartitionPanel ( ( PreferencesExt ) mainPrefs . node ( \"dirPartition\" ) ) ; c = dirPartPanel ; break ; case \"NcStream\" : ncStreamPanel = new NcStreamOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"NcStream\" ) ) ; c = ncStreamPanel ; break ; case \"GRIB1collection\" : grib1CollectionPanel = new Grib1CollectionOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"grib1raw\" ) ) ; c = grib1CollectionPanel ; break ; case \"GRIB1data\" : grib1DataPanel = new Grib1DataOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"grib1Data\" ) ) ; c = grib1DataPanel ; break ; case \"GRIB-FILES\" : gribFilesPanel = new GribFilesOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"gribFiles\" ) ) ; c = gribFilesPanel ; break ; case \"GRIB2collection\" : grib2CollectionPanel = new Grib2CollectionOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"gribNew\" ) ) ; c = grib2CollectionPanel ; break ; case \"GRIB2data\" : grib2DataPanel = new Grib2DataOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"grib2Data\" ) ) ; c = grib2DataPanel ; break ; case \"BufrCdmIndex\" : bufrCdmIndexPanel = new BufrCdmIndexOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"bufrCdmIdx\" ) ) ; c = bufrCdmIndexPanel ; /* } else if (title.equals(\"CdmIndex\")) {\r\n          gribCdmIndexPanel = new GribCdmIndexPanel((PreferencesExt) mainPrefs.node(\"cdmIdx\"));\r\n          c = gribCdmIndexPanel; */ break ; case \"CdmIndex4\" : cdmIndexPanel = new CdmIndexOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"cdmIdx3\" ) ) ; c = cdmIndexPanel ; break ; case \"CdmIndexReport\" : { PreferencesExt prefs = ( PreferencesExt ) mainPrefs . node ( \"CdmIndexReport\" ) ; ReportPanel rp = new CdmIndexReportPanel ( prefs ) ; cdmIndexReportPanel = new ReportOpPanel ( prefs , rp ) ; c = cdmIndexReportPanel ; break ; } case \"GribIndex\" : gribIdxPanel = new GribIndexOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"gribIdx\" ) ) ; c = gribIdxPanel ; break ; case \"GRIB1-REPORT\" : { PreferencesExt prefs = ( PreferencesExt ) mainPrefs . node ( \"grib1Report\" ) ; ReportPanel rp = new Grib1ReportPanel ( prefs ) ; grib1ReportPanel = new ReportOpPanel ( prefs , rp ) ; c = grib1ReportPanel ; break ; } case \"GRIB2-REPORT\" : { PreferencesExt prefs = ( PreferencesExt ) mainPrefs . node ( \"gribReport\" ) ; ReportPanel rp = new Grib2ReportPanel ( prefs ) ; grib2ReportPanel = new ReportOpPanel ( prefs , rp ) ; c = grib2ReportPanel ; break ; } case \"WMO-COMMON\" : wmoCommonCodePanel = new WmoCCPanel ( ( PreferencesExt ) mainPrefs . node ( \"wmo-common\" ) ) ; c = wmoCommonCodePanel ; break ; case \"WMO-CODES\" : gribCodePanel = new GribCodePanel ( ( PreferencesExt ) mainPrefs . node ( \"wmo-codes\" ) ) ; c = gribCodePanel ; break ; case \"WMO-TEMPLATES\" : gribTemplatePanel = new GribTemplatePanel ( ( PreferencesExt ) mainPrefs . node ( \"wmo-templates\" ) ) ; c = gribTemplatePanel ; break ; case \"GRIB1-TABLES\" : grib1TablePanel = new Grib1TablePanel ( ( PreferencesExt ) mainPrefs . node ( \"grib1-tables\" ) ) ; c = grib1TablePanel ; break ; case \"GRIB2-TABLES\" : grib2TablePanel = new Grib2TablePanel ( ( PreferencesExt ) mainPrefs . node ( \"grib2-tables\" ) ) ; c = grib2TablePanel ; break ; case \"GRIB-Rewrite\" : gribRewritePanel = new GribRewriteOpPanel ( ( PreferencesExt ) mainPrefs . node ( \"grib-rewrite\" ) ) ; c = gribRewritePanel ; break ; case \"CoordSys\" : coordSysPanel = new CoordSysPanel ( ( PreferencesExt ) mainPrefs . node ( \"CoordSys\" ) ) ; c = coordSysPanel ; break ; case \"FeatureScan\" : ftPanel = new FeatureScanPanel ( ( PreferencesExt ) mainPrefs . node ( \"ftPanel\" ) ) ; c = ftPanel ; break ; case \"GeoTiff\" : geotiffPanel = new GeotiffPanel ( ( PreferencesExt ) mainPrefs . node ( \"WCS\" ) ) ; c = geotiffPanel ; break ; case \"Grids\" : gridPanel = new GeoGridPanel ( ( PreferencesExt ) mainPrefs . node ( \"grid\" ) ) ; c = gridPanel ; break ; case \"SimpleGeometry\" : simpleGeomPanel = new SimpleGeomPanel ( ( PreferencesExt ) mainPrefs . node ( \"simpleGeom\" ) ) ; c = simpleGeomPanel ; break ; case \"Coverages\" : coveragePanel = new CoveragePanel ( ( PreferencesExt ) mainPrefs . node ( \"coverage2\" ) ) ; c = coveragePanel ; break ; case \"HDF5-Objects\" : hdf5ObjectPanel = new Hdf5ObjectPanel ( ( PreferencesExt ) mainPrefs . node ( \"hdf5\" ) ) ; c = hdf5ObjectPanel ; break ; case \"HDF5-Data\" : hdf5DataPanel = new Hdf5DataPanel ( ( PreferencesExt ) mainPrefs . node ( \"hdf5data\" ) ) ; c = hdf5DataPanel ; break ; case \"Netcdf4-JNI\" : nc4viewer = new DatasetViewerPanel ( ( PreferencesExt ) mainPrefs . node ( \"nc4viewer\" ) , true ) ; c = nc4viewer ; break ; case \"HDF4\" : hdf4Panel = new Hdf4Panel ( ( PreferencesExt ) mainPrefs . node ( \"hdf4\" ) ) ; c = hdf4Panel ; break ; case \"Images\" : imagePanel = new ImagePanel ( ( PreferencesExt ) mainPrefs . node ( \"images\" ) ) ; c = imagePanel ; break ; case \"Fmrc\" : fmrcPanel = new FmrcPanel ( ( PreferencesExt ) mainPrefs . node ( \"fmrc2\" ) ) ; c = fmrcPanel ; break ; case \"Collections\" : fmrcCollectionPanel = new FmrcCollectionPanel ( ( PreferencesExt ) mainPrefs . node ( \"collections\" ) ) ; c = fmrcCollectionPanel ; break ; case \"NCDump\" : ncdumpPanel = new NCdumpPanel ( ( PreferencesExt ) mainPrefs . node ( \"NCDump\" ) ) ; c = ncdumpPanel ; break ; case \"NcmlEditor\" : ncmlEditorPanel = new NcmlEditorPanel ( ( PreferencesExt ) mainPrefs . node ( \"NcmlEditor\" ) ) ; c = ncmlEditorPanel ; break ; case \"PointFeature\" : pointFeaturePanel = new PointFeaturePanel ( ( PreferencesExt ) mainPrefs . node ( \"pointFeature\" ) ) ; c = pointFeaturePanel ; break ; case \"Radial\" : radialPanel = new RadialPanel ( ( PreferencesExt ) mainPrefs . node ( \"radial\" ) ) ; c = radialPanel ; break ; case \"StationRadial\" : stationRadialPanel = new StationRadialPanel ( ( PreferencesExt ) mainPrefs . node ( \"stationRadar\" ) ) ; c = stationRadialPanel ; break ; case \"THREDDS\" : threddsUI = new ThreddsUI ( parentFrame , ( PreferencesExt ) mainPrefs . node ( \"thredds\" ) ) ; threddsUI . addPropertyChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent e ) { if ( e . getPropertyName ( ) . equals ( \"InvAccess\" ) ) { thredds . client . catalog . Access access = ( thredds . client . catalog . Access ) e . getNewValue ( ) ; jumptoThreddsDatatype ( access ) ; } if ( e . getPropertyName ( ) . equals ( \"Dataset\" ) || e . getPropertyName ( ) . equals ( \"CoordSys\" ) || e . getPropertyName ( ) . equals ( \"File\" ) ) { thredds . client . catalog . Dataset ds = ( thredds . client . catalog . Dataset ) e . getNewValue ( ) ; setThreddsDatatype ( ds , e . getPropertyName ( ) ) ; } } } ) ; c = threddsUI ; break ; case \"Units\" : unitsPanel = new UnitsPanel ( ( PreferencesExt ) mainPrefs . node ( \"units\" ) ) ; c = unitsPanel ; break ; case \"URLdump\" : urlPanel = new URLDumpPane ( ( PreferencesExt ) mainPrefs . node ( \"urlDump\" ) ) ; c = urlPanel ; break ; case \"Viewer\" : c = viewerPanel ; break ; case \"Writer\" : writerPanel = new DatasetWriterPanel ( ( PreferencesExt ) mainPrefs . node ( \"writer\" ) ) ; c = writerPanel ; break ; case \"WMS\" : wmsPanel = new WmsPanel ( ( PreferencesExt ) mainPrefs . node ( \"wms\" ) ) ; c = wmsPanel ; break ; default : log . warn ( \"tabbedPane unknown component {}\" , title ) ; return ; } parent . setComponentAt ( idx , c ) ; log . trace ( \"tabbedPane changed {} added \" , title ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Jump to the appropriate tab based on datatype of InvDataset [CODESPLIT] private void setThreddsDatatype ( thredds . client . catalog . Dataset invDataset , String wants ) { if ( invDataset == null ) return ; boolean wantsViewer = wants . equals ( \"File\" ) ; boolean wantsCoordSys = wants . equals ( \"CoordSys\" ) ; try { // just open as a NetcdfDataset\r if ( wantsViewer ) { openNetcdfFile ( threddsDataFactory . openDataset ( invDataset , true , null , null ) ) ; return ; } if ( wantsCoordSys ) { NetcdfDataset ncd = threddsDataFactory . openDataset ( invDataset , true , null , null ) ; ncd . enhance ( ) ; // make sure its enhanced\r openCoordSystems ( ncd ) ; return ; } // otherwise do the datatype thing\r DataFactory . Result threddsData = threddsDataFactory . openFeatureDataset ( invDataset , null ) ; if ( threddsData . fatalError ) { JOptionPane . showMessageDialog ( null , \"Failed to open err=\" + threddsData . errLog ) ; return ; } jumptoThreddsDatatype ( threddsData ) ; } catch ( IOException ioe ) { JOptionPane . showMessageDialog ( null , \"Error on setThreddsDatatype = \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "jump to the appropriate tab based on datatype of InvAccess [CODESPLIT] private void jumptoThreddsDatatype ( thredds . client . catalog . Access invAccess ) { if ( invAccess == null ) { return ; } thredds . client . catalog . Service s = invAccess . getService ( ) ; if ( s . getType ( ) == ServiceType . HTTPServer ) { downloadFile ( invAccess . getStandardUrlName ( ) ) ; return ; } if ( s . getType ( ) == ServiceType . WMS ) { openWMSDataset ( invAccess . getStandardUrlName ( ) ) ; return ; } if ( s . getType ( ) == ServiceType . CdmrFeature ) { openCoverageDataset ( invAccess . getWrappedUrlName ( ) ) ; return ; } thredds . client . catalog . Dataset ds = invAccess . getDataset ( ) ; if ( ds . getFeatureType ( ) == null ) { // if no feature type, just open as a NetcdfDataset\r try { openNetcdfFile ( threddsDataFactory . openDataset ( invAccess , true , null , null ) ) ; } catch ( IOException ioe ) { JOptionPane . showMessageDialog ( null , \"Error on setThreddsDatatype = \" + ioe . getMessage ( ) ) ; } return ; } DataFactory . Result threddsData = null ; try { threddsData = threddsDataFactory . openFeatureDataset ( invAccess , null ) ; if ( threddsData . fatalError ) { JOptionPane . showMessageDialog ( null , \"Failed to open err=\" + threddsData . errLog ) ; return ; } jumptoThreddsDatatype ( threddsData ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; JOptionPane . showMessageDialog ( null , \"Error on setThreddsDatatype = \" + ioe . getMessage ( ) ) ; if ( threddsData != null ) { try { threddsData . close ( ) ; } catch ( IOException ioe2 ) { // Okay to fall through?\r } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Jump to the appropriate tab based on datatype of threddsData [CODESPLIT] private void jumptoThreddsDatatype ( DataFactory . Result threddsData ) { if ( threddsData . fatalError ) { JOptionPane . showMessageDialog ( this , \"Cant open dataset=\" + threddsData . errLog ) ; try { threddsData . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return ; } if ( threddsData . featureType . isCoverageFeatureType ( ) ) { if ( threddsData . featureDataset instanceof FeatureDatasetCoverage ) { makeComponent ( ftTabPane , \"Coverages\" ) ; coveragePanel . setDataset ( threddsData . featureDataset ) ; tabbedPane . setSelectedComponent ( ftTabPane ) ; ftTabPane . setSelectedComponent ( coveragePanel ) ; } else if ( threddsData . featureDataset instanceof GridDataset ) { makeComponent ( ftTabPane , \"Grids\" ) ; gridPanel . setDataset ( ( GridDataset ) threddsData . featureDataset ) ; tabbedPane . setSelectedComponent ( ftTabPane ) ; ftTabPane . setSelectedComponent ( gridPanel ) ; } } else if ( threddsData . featureType == FeatureType . IMAGE ) { makeComponent ( ftTabPane , \"Images\" ) ; imagePanel . setImageLocation ( threddsData . imageURL ) ; tabbedPane . setSelectedComponent ( ftTabPane ) ; ftTabPane . setSelectedComponent ( imagePanel ) ; } else if ( threddsData . featureType == FeatureType . RADIAL ) { makeComponent ( ftTabPane , \"Radial\" ) ; radialPanel . setDataset ( ( RadialDatasetSweep ) threddsData . featureDataset ) ; tabbedPane . setSelectedComponent ( ftTabPane ) ; ftTabPane . setSelectedComponent ( radialPanel ) ; } else if ( threddsData . featureType . isPointFeatureType ( ) ) { makeComponent ( ftTabPane , \"PointFeature\" ) ; pointFeaturePanel . setPointFeatureDataset ( ( PointDatasetImpl ) threddsData . featureDataset ) ; tabbedPane . setSelectedComponent ( ftTabPane ) ; ftTabPane . setSelectedComponent ( pointFeaturePanel ) ; } else if ( threddsData . featureType == FeatureType . STATION_RADIAL ) { makeComponent ( ftTabPane , \"StationRadial\" ) ; stationRadialPanel . setStationRadialDataset ( threddsData . featureDataset ) ; tabbedPane . setSelectedComponent ( ftTabPane ) ; ftTabPane . setSelectedComponent ( stationRadialPanel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle messages . [CODESPLIT] private static void setDataset ( ) { // do it in the swing event thread\r SwingUtilities . invokeLater ( ( ) -> { int pos = wantDataset . indexOf ( ' ' ) ; if ( pos > 0 ) { final String catName = wantDataset . substring ( 0 , pos ) ; // {catalog}#{dataset}\r if ( catName . endsWith ( \".xml\" ) ) { ui . makeComponent ( null , \"THREDDS\" ) ; ui . threddsUI . setDataset ( wantDataset ) ; ui . tabbedPane . setSelectedComponent ( ui . threddsUI ) ; } return ; } // default\r ui . openNetcdfFile ( wantDataset ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set look - and - feel . [CODESPLIT] private static void prepareGui ( ) { final String osName = System . getProperty ( \"os.name\" ) . toLowerCase ( ) ; final boolean isMacOs = osName . startsWith ( \"mac os x\" ) ; if ( isMacOs ) { System . setProperty ( \"apple.laf.useScreenMenuBar\" , \"true\" ) ; // fixes the case on macOS where users use the system menu option to quit rather than\r // closing a window using the 'x' button.\r Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { doSavePrefsAndUI ( ) ; } } ) ; } else { // Not macOS, so try applying Nimbus L&F, if available.\r try { for ( UIManager . LookAndFeelInfo info : UIManager . getInstalledLookAndFeels ( ) ) { if ( \"Nimbus\" . equals ( info . getName ( ) ) ) { UIManager . setLookAndFeel ( info . getClassName ( ) ) ; break ; } } } catch ( Exception exc ) { log . warn ( \"Unable to apply Nimbus look-and-feel due to {}\" , exc . toString ( ) ) ; if ( log . isTraceEnabled ( ) ) { exc . printStackTrace ( ) ; } } } // misc Gui initialization(s)\r BAMutil . setResourcePath ( \"/resources/nj22/ui/icons/\" ) ; // Setting up a font metrics object triggers one of the most time-wasting steps of GUI set up.\r // We do it now before trying to create the splash or tools interface.\r SwingUtilities . invokeLater ( ( ) -> { final Toolkit tk = Toolkit . getDefaultToolkit ( ) ; final Font f = new Font ( \"SansSerif\" , Font . PLAIN , 12 ) ; @ SuppressWarnings ( \"deprecation\" ) final FontMetrics fm = tk . getFontMetrics ( f ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Must call this method on the event thread . [CODESPLIT] private static void createToolsFrame ( ) { // put UI in a JFrame\r frame = new JFrame ( \"NetCDF (\" + DIALOG_VERSION + \") Tools\" ) ; ui = new ToolsUI ( prefs , frame ) ; frame . setIconImage ( BAMutil . getImage ( \"netcdfUI\" ) ) ; frame . addWindowListener ( new WindowAdapter ( ) { @ Override public void windowActivated ( final WindowEvent e ) { ToolsSplashScreen . getSharedInstance ( ) . setVisible ( false ) ; } @ Override public void windowClosing ( final WindowEvent e ) { if ( ! done ) { exit ( ) ; } } } ) ; frame . getContentPane ( ) . add ( ui ) ; final Rectangle have = frame . getGraphicsConfiguration ( ) . getBounds ( ) ; final Rectangle def = new Rectangle ( 50 , 50 , 800 , 800 ) ; Rectangle want = ( Rectangle ) prefs . getBean ( FRAME_SIZE , def ) ; if ( want . getX ( ) > have . getWidth ( ) - 25 ) { // may be off screen when switcing between 2 monitor system\r want = def ; } frame . setBounds ( want ) ; frame . pack ( ) ; frame . setBounds ( want ) ; // in case a dataset was on the command line\r if ( wantDataset != null ) { setDataset ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build an unnamed InvCatalog for this DatasetSource and return the top - level InvDataset . The ResultService for this DatasetSource is used to create the InvService for the new InvCatalog . Each InvDataset in the catalog is named with the location of the object they represent on the dataset source . [CODESPLIT] protected InvCatalog createSkeletonCatalog ( String prefixUrlPath ) throws IOException { String aphString = this . getResultService ( ) . getAccessPointHeader ( ) ; String apString = this . getAccessPoint ( ) ; // Check that accessPoint URL starts with accessPointHeader. if ( ! apString . startsWith ( aphString ) ) throw new IOException ( \"The accessPoint <\" + apString + \"> must start with the accessPointHeader <\" + aphString + \">.\" ) ; // Check that accessPoint URL ends with a slash (\"/\"). if ( ! apString . endsWith ( \"/\" ) ) throw new IOException ( \"The accessPoint URL must end with a \\\"/\\\" <\" + apString + \">.\" ) ; // Check that accessPoint URL is an OPeNDAP server URL. String apVersionString = apString + \"version\" ; String apVersionResultContent = null ; try { apVersionResultContent = urlExtractor . getTextContent ( apVersionString ) ; } catch ( java . io . IOException e ) { String tmpMsg = \"The accessPoint URL is not an OPeNDAP server URL (no version info) <\" + apVersionString + \">\" ; log . error ( \"expandThisType(): \" + tmpMsg , e ) ; IOException myE = new IOException ( tmpMsg + e . getMessage ( ) ) ; myE . initCause ( e ) ; throw ( myE ) ; } if ( apVersionResultContent . indexOf ( \"DODS\" ) == - 1 && apVersionResultContent . indexOf ( \"OPeNDAP\" ) == - 1 && apVersionResultContent . indexOf ( \"DAP\" ) == - 1 ) { String tmpMsg = \"The accessPoint URL version info is not valid <\" + apVersionResultContent + \">\" ; log . error ( \"expandThisType(): \" + tmpMsg ) ; throw new IOException ( tmpMsg ) ; } // Some setup stuff try { accessPointHeaderUri = new URI ( aphString ) ; } catch ( URISyntaxException e ) { throw new IOException ( \"The accessPointHeader URL failed to map to a URI <\" + aphString + \">.\" ) ; } // Create catalog. InvCatalogImpl catalog = new InvCatalogImpl ( null , null , null ) ; //this.getName(), null, null); // Create service. InvService service = new InvService ( this . getResultService ( ) . getName ( ) , this . getResultService ( ) . getServiceType ( ) . toString ( ) , this . getResultService ( ) . getBase ( ) , this . getResultService ( ) . getSuffix ( ) , this . getResultService ( ) . getDescription ( ) ) ; for ( Iterator it = this . getResultService ( ) . getProperties ( ) . iterator ( ) ; it . hasNext ( ) ; ) { service . addProperty ( ( InvProperty ) it . next ( ) ) ; } for ( Iterator it = this . getResultService ( ) . getServices ( ) . iterator ( ) ; it . hasNext ( ) ; ) { service . addService ( ( InvService ) it . next ( ) ) ; } // Add service to catalog. catalog . addService ( service ) ; // Create top-level dataset. DodsDirInvDataset topDs = null ; try { topDs = new DodsDirInvDataset ( null , new URI ( apString ) ) ; } catch ( URISyntaxException e ) { throw new IOException ( \"The accessPoint URL failed to map to a URI <\" + apString + \">.\" ) ; } // Set the serviceName (inherited by all datasets) in top-level dataset. ThreddsMetadata tm = new ThreddsMetadata ( false ) ; tm . setServiceName ( service . getName ( ) ) ; InvMetadata md = new InvMetadata ( topDs , null , XMLEntityResolver . CATALOG_NAMESPACE_10 , \"\" , true , true , null , tm ) ; ThreddsMetadata tm2 = new ThreddsMetadata ( false ) ; tm2 . addMetadata ( md ) ; topDs . setLocalMetadata ( tm2 ) ; // Add top-level dataset to catalog. catalog . addDataset ( topDs ) ; // Tie up any loose ends in catalog with finish(). ( ( InvCatalogImpl ) catalog ) . finish ( ) ; return ( catalog ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a list of the InvDatasets contained in the given collection dataset on this DatasetSource . [CODESPLIT] protected List expandThisLevel ( InvDataset dataset , String prefixUrlPath ) { // @todo Switch to return type of InvDataset (???) so can return error messages about datasets removed from list. if ( dataset == null ) throw new NullPointerException ( \"Given dataset cannot be null.\" ) ; if ( ! isCollection ( dataset ) ) throw new IllegalArgumentException ( \"Dataset \\\"\" + dataset . getName ( ) + \"\\\" is not a collection dataset.\" ) ; List dsList = new ArrayList ( ) ; // Get list of possible datasets from current URL. List possibleDsList = null ; try { possibleDsList = urlExtractor . extract ( dataset . getName ( ) ) ; } catch ( java . io . IOException e ) { log . warn ( \"expandThisLevel(): IOException while extracting dataset info from given OPeNDAP directory <\" + dataset . getName ( ) + \">, return empty list: \" + e . getMessage ( ) ) ; return ( dsList ) ; } // Handle each link in the current access path. String curDsUrlString = null ; URI curDsUri = null ; InvDataset curDs = null ; for ( Iterator it = possibleDsList . iterator ( ) ; it . hasNext ( ) ; ) // @todo curDsUrlString = (String) it.next()) { curDsUrlString = ( String ) it . next ( ) ; // Skip datasets that aren't OPeNDAP datasets (\".html\") or collection datasets (\"/\"). if ( ( ! curDsUrlString . endsWith ( \".html\" ) ) && ( ! curDsUrlString . endsWith ( \"/\" ) ) ) { log . warn ( \"expandThisLevel(): Dataset isn't an OPeNDAP dataset or collection dataset, skip <\" + dataset . getName ( ) + \">.\" ) ; continue ; } // Remove \".html\" extension. if ( curDsUrlString . endsWith ( \".html\" ) ) { curDsUrlString = curDsUrlString . substring ( 0 , curDsUrlString . length ( ) - 5 ) ; } // Avoid links back down the path hierarchy (i.e., parent directory links). if ( ! curDsUrlString . startsWith ( this . accessPointHeaderUri . toString ( ) ) ) { log . debug ( \"expandThisLevel(): current path <\" + curDsUrlString + \"> not child of given\" + \" location <\" + this . accessPointHeaderUri . toString ( ) + \">, skip.\" ) ; continue ; } // Get URI from URL string. try { curDsUri = new URI ( curDsUrlString ) ; } catch ( URISyntaxException e ) { log . error ( \"expandThisLevel(): Skipping dataset  <\" + curDsUrlString + \"> due to URISyntaxException: \" + e . getMessage ( ) ) ; continue ; } log . debug ( \"expandThisLevel(): handle dataset (\" + curDsUrlString + \")\" ) ; try { curDs = new DodsDirInvDataset ( null , curDsUri ) ; } catch ( IOException e ) { log . warn ( \"expandThisLevel(): skipping dataset <\" + curDsUri . toString ( ) + \">, not under accessPointHeader: \" + e . getMessage ( ) ) ; continue ; } dsList . add ( curDs ) ; } // END - loop through files in current directory return ( dsList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create standard name from list of axes . Sort the axes first [CODESPLIT] static public String makeName ( List < CoordinateAxis > axes ) { List < CoordinateAxis > axesSorted = new ArrayList <> ( axes ) ; Collections . sort ( axesSorted , new CoordinateAxis . AxisComparator ( ) ) ; StringBuilder buff = new StringBuilder ( ) ; for ( int i = 0 ; i < axesSorted . size ( ) ; i ++ ) { CoordinateAxis axis = axesSorted . get ( i ) ; if ( i > 0 ) buff . append ( \" \" ) ; buff . append ( axis . getFullNameEscaped ( ) ) ; } return buff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prefer smaller ranks in case more than one [CODESPLIT] private CoordinateAxis lesserRank ( CoordinateAxis a1 , CoordinateAxis a2 ) { if ( a1 == null ) return a2 ; return ( a1 . getRank ( ) <= a2 . getRank ( ) ) ? a1 : a2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the CoordinateAxis that has the given AxisType . If more than one return the one with lesser rank . [CODESPLIT] public CoordinateAxis findAxis ( AxisType type ) { CoordinateAxis result = null ; for ( CoordinateAxis axis : coordAxes ) { AxisType axisType = axis . getAxisType ( ) ; if ( ( axisType != null ) && ( axisType == type ) ) result = lesserRank ( result , axis ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the first ProjectionCT from the list of CoordinateTransforms . [CODESPLIT] public ProjectionCT getProjectionCT ( ) { for ( CoordinateTransform ct : coordTrans ) { if ( ct instanceof ProjectionCT ) return ( ProjectionCT ) ct ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Projection for this coordinate system . If isLatLon () then returns a LatLonProjection . Otherwise extracts the projection from any ProjectionCT CoordinateTransform . [CODESPLIT] public ProjectionImpl getProjection ( ) { if ( projection == null ) { if ( isLatLon ( ) ) projection = new LatLonProjection ( ) ; ProjectionCT projCT = getProjectionCT ( ) ; if ( null != projCT ) projection = projCT . getProjection ( ) ; } return projection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "true if it has X and Y CoordinateAxis and a CoordTransform Projection [CODESPLIT] public boolean isGeoXY ( ) { if ( ( xAxis == null ) || ( yAxis == null ) ) return false ; return null != getProjection ( ) && ! ( projection instanceof LatLonProjection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "true if all axes are CoordinateAxis1D and are regular [CODESPLIT] public boolean isRegular ( ) { for ( CoordinateAxis axis : coordAxes ) { if ( ! ( axis instanceof CoordinateAxis1D ) ) return false ; if ( ! ( ( CoordinateAxis1D ) axis ) . isRegular ( ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if all the Dimensions in subset are in set [CODESPLIT] public static boolean isSubset ( Collection < Dimension > subset , Collection < Dimension > set ) { for ( Dimension d : subset ) { if ( ! ( set . contains ( d ) ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do we have all the axes in the list? [CODESPLIT] public boolean containsAxes ( List < CoordinateAxis > wantAxes ) { for ( CoordinateAxis ca : wantAxes ) { if ( ! containsAxis ( ca . getFullName ( ) ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do we have the named axis? [CODESPLIT] public boolean containsAxis ( String axisName ) { for ( CoordinateAxis ca : coordAxes ) { if ( ca . getFullName ( ) . equals ( axisName ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do we have all the dimensions in the list? [CODESPLIT] public boolean containsDomain ( List < Dimension > wantDimensions ) { for ( Dimension d : wantDimensions ) { if ( ! domain . contains ( d ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do we have all the axes types in the list? [CODESPLIT] public boolean containsAxisTypes ( List < AxisType > wantAxes ) { for ( AxisType wantAxisType : wantAxes ) { if ( ! containsAxisType ( wantAxisType ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do we have an axes of the given type? [CODESPLIT] public boolean containsAxisType ( AxisType wantAxisType ) { for ( CoordinateAxis ca : coordAxes ) { if ( ca . getAxisType ( ) == wantAxisType ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This version of cloneDAG () is the primary point of cloning . If the src is already cloned then that existing clone is immediately returned . Otherwise cloneDAG ( map ) is called to have the object clone itself . Note this is static because it uses no existing state . [CODESPLIT] static public DAPNode cloneDAG ( CloneMap map , DAPNode src ) throws CloneNotSupportedException { DAPNode bt = map . nodes . get ( src ) ; if ( bt == null ) bt = src . cloneDAG ( map ) ; return bt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This procedure does the actual recursive clone . [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DAPNode node = ( DAPNode ) super . clone ( ) ; // Object.clone\r map . nodes . put ( this , node ) ; DAPNode tmp = map . nodes . get ( _myParent ) ; if ( tmp != node ) _myParent = tmp ; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "************************************************************************ Default handler for OPeNDAP . html requests . Returns an html form and javascript code that allows the user to use their browser to select variables and build constraints for a data request . The DDS and DAS for the data set are used to build the form . The types in opendap . servlet . www are integral to the form generation . [CODESPLIT] public void sendDataRequestForm ( ReqState rs , String dataSet , ServerDDS sdds , DAS myDAS ) // changed jc\r throws DAP2Exception , ParseException { if ( _Debug ) System . out . println ( \"Sending DODS Data Request Form For: \" + dataSet + \"    CE: '\" + rs . getRequest ( ) . getQueryString ( ) + \"'\" ) ; String requestURL ; /*\r\n        // Turn this on later if we discover we're supposed to accept\r\n        // constraint expressions as input to the Data Request Web Form\r\n    String ce;\r\n    if(request.getQueryString() == null){\r\n        ce = \"\";\r\n        }\r\n    else {\r\n        ce = \"?\" + request.getQueryString();\r\n        }\r\n*/ int suffixIndex = rs . getRequest ( ) . getRequestURL ( ) . toString ( ) . lastIndexOf ( \".\" ) ; requestURL = rs . getRequest ( ) . getRequestURL ( ) . substring ( 0 , suffixIndex ) ; String dapCssUrl = \"/\" + requestURL . split ( \"/\" , 5 ) [ 3 ] + \"/\" + \"tdsDap.css\" ; try { //PrintWriter pw = new PrintWriter(response.getOutputStream());\r PrintWriter pw ; if ( false ) { pw = new PrintWriter ( new FileOutputStream ( new File ( \"debug.html\" ) ) ) ; } else pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; wwwOutPut wOut = new wwwOutPut ( pw ) ; // Get the DDS and the DAS (if one exists) for the dataSet.\r DDS myDDS = getWebFormDDS ( dataSet , sdds ) ; //DAS myDAS = dServ.getDAS(dataSet); // change jc\r jscriptCore jsc = new jscriptCore ( ) ; pw . println ( \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0 Transitional//EN\\\"\\n\" + \"\\\"http://www.w3.org/TR/REC-html40/loose.dtd\\\">\\n\" + \"<html><head><title>OPeNDAP Dataset Query Form</title>\\n\" + \"<link type=\\\"text/css\\\" rel=\\\"stylesheet\\\" media=\\\"screen\\\" href=\\\"\" + dapCssUrl + \"\\\"/>\\n\" + \"<base href=\\\"\" + helpLocation + \"\\\">\\n\" + \"<script type=\\\"text/javascript\\\">\\n\" + \"<!--\\n\" ) ; pw . flush ( ) ; pw . println ( jsc . jScriptCode ) ; pw . flush ( ) ; pw . println ( \"DODS_URL = new dods_url(\\\"\" + requestURL + \"\\\");\\n\" + \"// -->\\n\" + \"</script>\\n\" + \"</head>\\n\" + \"<body>\\n\" + \"<p><h2 align='center'>OPeNDAP Dataset Access Form</h2>\\n\" + \"<hr>\\n\" + \"<form action=\\\"\\\">\\n\" + \"<table>\\n\" ) ; pw . flush ( ) ; wOut . writeDisposition ( requestURL ) ; pw . println ( \"<tr><td><td><hr>\\n\" ) ; wOut . writeGlobalAttributes ( myDAS , myDDS ) ; pw . println ( \"<tr><td><td><hr>\\n\" ) ; wOut . writeVariableEntries ( myDAS , myDDS ) ; pw . println ( \"</table></form>\\n\" ) ; pw . println ( \"<hr>\\n\" ) ; pw . println ( \"<address>Send questions or comments to: \" + \"<a href=\\\"mailto:support@unidata.ucar.edu\\\">\" + \"support@unidata.ucar.edu\" + \"</a></address>\" + \"</body></html>\\n\" ) ; pw . println ( \"<hr>\" ) ; pw . println ( \"<h2>DDS:</h2>\" ) ; pw . println ( \"<pre>\" ) ; myDDS . print ( pw ) ; pw . println ( \"</pre>\" ) ; pw . println ( \"<hr>\" ) ; pw . flush ( ) ; } catch ( IOException ioe ) { System . out . println ( \"OUCH! IOException: \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( System . out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////// [CODESPLIT] private static TypeAndOrder findTao ( int center , String key ) { Map < String , BufrCdmIndexProto . FldType > local = locals . get ( center ) ; if ( local != null ) { BufrCdmIndexProto . FldType result = local . get ( key ) ; if ( result != null ) return new TypeAndOrder ( result , - 1 ) ; } return fld2type . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public static StandardFieldsFromMessage extract ( Message m ) throws IOException { StandardFieldsFromMessage result = new StandardFieldsFromMessage ( ) ; extract ( m . ids . getCenterId ( ) , m . getRootDataDescriptor ( ) , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] public String getToolTipText ( MouseEvent event ) { String text = super . getToolTipText ( event ) ; System . out . println ( \"BeanTable tooltip \" + text ) ; return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add listener : ListSelectionEvent sent when a new row is selected [CODESPLIT] public void addListSelectionListener ( ListSelectionListener l ) { listenerList . add ( javax . swing . event . ListSelectionListener . class , l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove listener [CODESPLIT] public void removeListSelectionListener ( ListSelectionListener l ) { listenerList . remove ( javax . swing . event . ListSelectionListener . class , l ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the currently selected bean or null if none selected . [CODESPLIT] public Object getSelectedBean ( ) { int viewRowIndex = jtable . getSelectedRow ( ) ; if ( viewRowIndex < 0 ) return null ; int modelRowIndex = jtable . convertRowIndexToModel ( viewRowIndex ) ; return ( modelRowIndex < 0 ) || ( modelRowIndex >= beans . size ( ) ) ? null : beans . get ( modelRowIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the currently selected beans . Use this for multiple selection [CODESPLIT] public List getSelectedBeans ( ) { ArrayList < Object > list = new ArrayList <> ( ) ; int [ ] viewRowIndices = jtable . getSelectedRows ( ) ; for ( int viewRowIndex : viewRowIndices ) { int modelRowIndex = jtable . convertRowIndexToModel ( viewRowIndex ) ; list . add ( beans . get ( modelRowIndex ) ) ; if ( debugSelected ) System . out . println ( \" bean selected= \" + modelRowIndex + \" \" + beans . get ( modelRowIndex ) ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the currently selected cells . Use this for multiple row selection when columnSelection is on [CODESPLIT] public ArrayList < Object > getSelectedCells ( ) { ArrayList < Object > list = new ArrayList <> ( ) ; int [ ] viewRowIndices = jtable . getSelectedRows ( ) ; int [ ] viewColumnIndices = jtable . getSelectedColumns ( ) ; for ( int i = 0 ; i < viewRowIndices . length ; i ++ ) for ( int j = 0 ; i < viewColumnIndices . length ; j ++ ) { int modelRowIndex = jtable . convertRowIndexToModel ( viewRowIndices [ i ] ) ; int modelColumnIndex = jtable . convertColumnIndexToModel ( viewColumnIndices [ j ] ) ; list . add ( model . getValueAt ( modelRowIndex , modelColumnIndex ) ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the currently selected cells ( 0 false or null ) . Use this for multiple row selection when columnSelection is on [CODESPLIT] public void clearSelectedCells ( ) { int [ ] viewRowIndices = jtable . getSelectedRows ( ) ; int [ ] viewColumnIndices = jtable . getSelectedColumns ( ) ; TableColumnModel tcm = jtable . getColumnModel ( ) ; for ( int viewColumnIndex : viewColumnIndices ) { TableColumn tc = tcm . getColumn ( viewColumnIndex ) ; int modelColumnIndex = tc . getModelIndex ( ) ; Class colClass = jtable . getColumnClass ( viewColumnIndex ) ; Object zeroValue = model . zeroValue ( colClass ) ; for ( int viewRowIndex : viewRowIndices ) { int modelRowIndex = jtable . convertRowIndexToModel ( viewRowIndex ) ; model . setValueAt ( zeroValue , modelRowIndex , modelColumnIndex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set which row is selected . [CODESPLIT] public void setSelectedBean ( Object bean ) { if ( bean == null ) return ; int modelRowIndex = beans . indexOf ( bean ) ; int viewRowIndex = jtable . convertRowIndexToView ( modelRowIndex ) ; if ( viewRowIndex >= 0 ) jtable . getSelectionModel ( ) . setSelectionInterval ( viewRowIndex , viewRowIndex ) ; makeRowVisible ( viewRowIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set which rows are selected . must also call setSelectionMode ( ListSelectionModel . MULTIPLE_INTERVAL_SELECTION ) ; [CODESPLIT] public void setSelectedBeans ( List want ) { jtable . getSelectionModel ( ) . clearSelection ( ) ; for ( Object bean : want ) { int modelRowIndex = beans . indexOf ( bean ) ; int viewRowIndex = jtable . convertRowIndexToView ( modelRowIndex ) ; if ( viewRowIndex >= 0 ) { jtable . getSelectionModel ( ) . addSelectionInterval ( viewRowIndex , viewRowIndex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save state to the PreferencesExt . [CODESPLIT] public void saveState ( boolean saveData ) { if ( store == null ) return ; try { // save data if ( saveData ) { store . putBeanCollection ( \"beanList\" , beans ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } List < PropertyCol > propCols = new ArrayList <> ( ) ; HidableTableColumnModel tableColumnModel = ( HidableTableColumnModel ) jtable . getColumnModel ( ) ; Enumeration < TableColumn > columns = tableColumnModel . getColumns ( false ) ; while ( columns . hasMoreElements ( ) ) { PropertyCol propCol = new PropertyCol ( ) ; TableColumn column = columns . nextElement ( ) ; propCol . setName ( column . getIdentifier ( ) . toString ( ) ) ; propCol . setWidth ( column . getWidth ( ) ) ; propCol . setVisible ( tableColumnModel . isColumnVisible ( column ) ) ; propCols . add ( propCol ) ; } store . putBeanCollection ( \"propertyCol\" , propCols ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies the TableModel that the data in the specified bean has changed . The TableModel will then fire an event of its own which its listeners will hear ( usually a JTable ) . [CODESPLIT] public void fireBeanDataChanged ( Object bean ) { int row = beans . indexOf ( bean ) ; if ( row >= 0 ) { model . fireTableRowsUpdated ( row , row ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restore state from PreferencesExt [CODESPLIT] protected void restoreState ( ) { if ( store == null ) { return ; } ArrayList propColObjs = ( ArrayList ) store . getBean ( \"propertyCol\" , new ArrayList ( ) ) ; HidableTableColumnModel tableColumnModel = ( HidableTableColumnModel ) jtable . getColumnModel ( ) ; int newViewIndex = 0 ; for ( Object propColObj : propColObjs ) { PropertyCol propCol = ( PropertyCol ) propColObj ; try { int currentViewIndex = tableColumnModel . getColumnIndex ( propCol . getName ( ) ) ; // May throw IAE. TableColumn column = tableColumnModel . getColumn ( currentViewIndex ) ; column . setPreferredWidth ( propCol . getWidth ( ) ) ; tableColumnModel . moveColumn ( currentViewIndex , newViewIndex ) ; assert tableColumnModel . getColumn ( newViewIndex ) == column : \"tableColumn wasn't successfully moved.\" ; // We must do this last, since moveColumn() only works on visible columns. tableColumnModel . setColumnVisible ( column , propCol . isVisible ( ) ) ; if ( propCol . isVisible ( ) ) { ++ newViewIndex ; // Don't increment for hidden columns. } } catch ( IllegalArgumentException e ) { logger . debug ( String . format ( \"Column named \\\"%s\\\" was present in the preferences file but not the dataset.\" , propCol . getName ( ) ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Needed to implement Array . getElement () [CODESPLIT] static public Class cdmElementClass ( DataType dt ) { switch ( dt ) { case BOOLEAN : return boolean . class ; case ENUM1 : case BYTE : return byte . class ; case CHAR : return char . class ; case ENUM2 : case SHORT : return short . class ; case ENUM4 : case INT : return int . class ; case LONG : return long . class ; case FLOAT : return float . class ; case DOUBLE : return double . class ; case STRING : return String . class ; case OPAQUE : return ByteBuffer . class ; case UBYTE : return byte . class ; case USHORT : return short . class ; case UINT : return int . class ; case ULONG : return long . class ; default : break ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert a string to a specified cdmtype Note that if en is defined then we attempt to convert the string as enum const [CODESPLIT] static public Object attributeParse ( DataType cdmtype , EnumTypedef en , Object o ) { String so = o . toString ( ) ; if ( en != null ) { switch ( cdmtype ) { case ENUM1 : case ENUM2 : case ENUM4 : if ( ! ( o instanceof Integer ) ) throw new ConversionException ( o . toString ( ) ) ; int eval = ( Integer ) o ; String econst = en . lookupEnumString ( eval ) ; if ( econst == null ) throw new ConversionException ( o . toString ( ) ) ; return econst ; default : throw new ConversionException ( o . toString ( ) ) ; } } long lval = 0 ; double dval = 0.0 ; boolean islong = true ; boolean isdouble = true ; // Do a quick conversion checks try { lval = Long . parseLong ( so ) ; } catch ( NumberFormatException nfe ) { islong = false ; } try { dval = Double . parseDouble ( so ) ; } catch ( NumberFormatException nfe ) { isdouble = false ; } o = null ; // default is not convertible switch ( cdmtype ) { case BOOLEAN : if ( so . equalsIgnoreCase ( \"false\" ) || ( islong && lval == 0 ) ) o = Boolean . FALSE ; else o = Boolean . TRUE ; break ; case BYTE : if ( islong ) o = Byte . valueOf ( ( byte ) lval ) ; break ; case SHORT : if ( islong ) o = Short . valueOf ( ( short ) lval ) ; break ; case INT : if ( islong ) o = Integer . valueOf ( ( int ) lval ) ; break ; case LONG : if ( islong ) o = Long . valueOf ( lval ) ; break ; case UBYTE : // Keep the proper bit pattern if ( islong ) o = Byte . valueOf ( ( byte ) ( lval & 0xFF L ) ) ; break ; case USHORT : if ( islong ) o = Short . valueOf ( ( short ) ( lval & 0xFFFF L ) ) ; break ; case UINT : if ( islong ) o = Integer . valueOf ( ( int ) ( lval & 0xFFFFFFFF L ) ) ; break ; case ULONG : //Need to resort to BigInteger BigInteger bi = new BigInteger ( so ) ; bi = bi . and ( LONGMASK ) ; o = ( Long ) bi . longValue ( ) ; break ; case FLOAT : if ( islong && ! isdouble ) { dval = ( double ) lval ; isdouble = true ; } if ( isdouble ) o = ( Float ) ( ( float ) dval ) ; break ; case DOUBLE : if ( islong && ! isdouble ) { dval = ( double ) lval ; isdouble = true ; } if ( isdouble ) o = ( Double ) ( dval ) ; break ; case STRING : return so ; case OPAQUE : // Big Integer then ByteBuffer if ( so . startsWith ( \"0x\" ) || so . startsWith ( \"0X\" ) ) so = so . substring ( 2 ) ; bi = new BigInteger ( so , 16 ) ; // Now extract bytes byte [ ] bb = bi . toByteArray ( ) ; o = ByteBuffer . wrap ( bb ) ; break ; default : throw new ConversionException ( o . toString ( ) ) ; } if ( o == null ) throw new ConversionException ( o . toString ( ) ) ; return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for constructing an unknown unit from a name . [CODESPLIT] public static UnknownUnit create ( String name ) throws NameException { UnknownUnit unit ; name = name . toLowerCase ( ) ; synchronized ( map ) { unit = map . get ( name ) ; if ( unit == null ) { unit = new UnknownUnit ( name ) ; map . put ( unit . getName ( ) , unit ) ; map . put ( unit . getPlural ( ) , unit ) ; } } return unit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes this input stream and releases any system resources associated with the stream ; closes the method also . [CODESPLIT] @ Override public void close ( ) throws IOException { if ( closed ) return ; /* Allow multiple close calls */ closed = true ; try { consume ( ) ; } finally { super . close ( ) ; } if ( method != null ) method . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has v already been added to the set of extra variables? [CODESPLIT] private boolean isExtra ( Variable v ) { return v != null && extras != null && extras . contains ( v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is v a coordinate axis for this feature type? [CODESPLIT] private boolean isCoordinate ( Variable v ) { if ( v == null ) return false ; String name = v . getShortName ( ) ; return ( latVE != null && latVE . axisName . equals ( name ) ) || ( lonVE != null && lonVE . axisName . equals ( name ) ) || ( altVE != null && altVE . axisName . equals ( name ) ) || ( stnAltVE != null && stnAltVE . axisName . equals ( name ) ) || ( timeVE != null && timeVE . axisName . equals ( name ) ) || ( nomTimeVE != null && nomTimeVE . axisName . equals ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find a coord axis of the given type in the table and its parents [CODESPLIT] private CoordVarExtractor findCoordinateAxis ( Table . CoordName coordName , Table t , int nestingLevel ) { if ( t == null ) return null ; String axisName = t . findCoordinateVariableName ( coordName ) ; if ( axisName != null ) { VariableDS v = t . findVariable ( axisName ) ; if ( v != null ) return new CoordVarExtractorVariable ( v , axisName , nestingLevel ) ; if ( t . extraJoins != null ) { for ( Join j : t . extraJoins ) { v = j . findVariable ( axisName ) ; if ( v != null ) return new CoordVarExtractorVariable ( v , axisName , nestingLevel ) ; } } // see if its in the StructureData if ( t instanceof Table . TableSingleton ) { Table . TableSingleton ts = ( Table . TableSingleton ) t ; return new CoordVarStructureData ( axisName , ts . sdata ) ; } // see if its at the top level if ( t instanceof Table . TableTop ) { v = ( VariableDS ) ds . findVariable ( axisName ) ; if ( v != null ) return new CoordVarTop ( v ) ; else return new CoordVarConstant ( coordName . toString ( ) , \"\" , axisName ) ; // assume its the actual value } errlog . format ( \"NestedTable: cant find variable '%s' for coordinate type %s %n\" , axisName , coordName ) ; } // check the parent return findCoordinateAxis ( coordName , t . parent , nestingLevel + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "use recursion so that parent variables come first [CODESPLIT] private void addDataVariables ( List < VariableSimpleIF > list , Table t ) { if ( t . parent != null ) addDataVariables ( list , t . parent ) ; for ( VariableSimpleIF col : t . cols . values ( ) ) { if ( t . nondataVars . contains ( col . getFullName ( ) ) ) continue ; if ( t . nondataVars . contains ( col . getShortName ( ) ) ) continue ; // fishy list . add ( col ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add table join to this cursor level [CODESPLIT] void addParentJoin ( Cursor cursor ) throws IOException { int level = cursor . currentIndex ; Table t = getTable ( level ) ; if ( t . extraJoins != null ) { List < StructureData > sdata = new ArrayList <> ( 3 ) ; sdata . add ( cursor . tableData [ level ] ) ; for ( Join j : t . extraJoins ) { sdata . add ( j . getJoinData ( cursor ) ) ; } cursor . tableData [ level ] = StructureDataFactory . make ( sdata . toArray ( new StructureData [ sdata . size ( ) ] ) ) ; // LOOK should try to consolidate } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// Station or Station_Profile [CODESPLIT] public StructureDataIterator getStationDataIterator ( ) throws IOException { Table stationTable = root ; StructureDataIterator siter = stationTable . getStructureDataIterator ( null ) ; if ( stationTable . limit != null ) { Variable limitV = ds . findVariable ( stationTable . limit ) ; int limit = limitV . readScalarInt ( ) ; return new StructureDataIteratorLimited ( siter , limit ) ; } return siter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "also called from StandardPointFeatureIterator [CODESPLIT] StationFeature makeStation ( StructureData stationData ) { if ( stnVE . isMissing ( stationData ) ) return null ; String stationName = stnVE . getCoordValueAsString ( stationData ) ; String stationDesc = ( stnDescVE == null ) ? \"\" : stnDescVE . getCoordValueAsString ( stationData ) ; String stnWmoId = ( wmoVE == null ) ? \"\" : wmoVE . getCoordValueAsString ( stationData ) ; double lat = latVE . getCoordValue ( stationData ) ; double lon = lonVE . getCoordValue ( stationData ) ; double elev = ( stnAltVE == null ) ? Double . NaN : stnAltVE . getCoordValue ( stationData ) ; // missing lat, lon means skip this station if ( Double . isNaN ( lat ) || Double . isNaN ( lon ) ) return null ; return new StationFeatureImpl ( stationName , stationDesc , stnWmoId , lat , lon , elev , - 1 , stationData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do the conversion and return a NodeMap representing the conversion . [CODESPLIT] public NodeMap < CDMNode , DapNode > create ( ) throws DapException { // Netcdf Dataset will already have a root group Group cdmroot = ncfile . getRootGroup ( ) ; this . nodemap . put ( cdmroot , this . dmr ) ; fillGroup ( cdmroot , this . dmr , ncfile ) ; return this . nodemap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a variable or field [CODESPLIT] protected void createVar ( DapVariable dapvar , NetcdfFile ncfile , Group cdmgroup , Structure cdmparentstruct ) throws DapException { Variable cdmvar = null ; DapType basetype = dapvar . getBaseType ( ) ; if ( basetype . isAtomic ( ) ) { DapVariable atomvar = ( DapVariable ) dapvar ; cdmvar = new Variable ( ncfile , cdmgroup , cdmparentstruct , atomvar . getShortName ( ) ) ; DataType cdmbasetype ; if ( basetype . isEnumType ( ) ) cdmbasetype = CDMTypeFcns . enumTypeFor ( basetype ) ; else cdmbasetype = CDMTypeFcns . daptype2cdmtype ( basetype ) ; if ( cdmbasetype == null ) throw new DapException ( \"Unknown basetype:\" + basetype ) ; cdmvar . setDataType ( cdmbasetype ) ; if ( basetype . isEnumType ( ) ) { EnumTypedef cdmenum = ( EnumTypedef ) this . nodemap . get ( basetype ) ; if ( cdmenum == null ) throw new DapException ( \"Unknown enumeration type:\" + basetype . toString ( ) ) ; cdmvar . setEnumTypedef ( cdmenum ) ; } this . nodemap . put ( cdmvar , dapvar ) ; } else if ( basetype . isStructType ( ) ) { DapStructure dapstruct = ( DapStructure ) basetype ; Structure cdmstruct = new Structure ( ncfile , cdmgroup , cdmparentstruct , dapstruct . getShortName ( ) ) ; cdmvar = cdmstruct ; this . nodemap . put ( cdmvar , dapvar ) ; // Add the fields for ( DapVariable field : dapstruct . getFields ( ) ) { createVar ( field , ncfile , cdmgroup , cdmstruct ) ; } } else if ( basetype . isSeqType ( ) ) { DapSequence dapseq = ( DapSequence ) basetype ; // In general one would convert the sequence // to a CDM sequence with vlen // so Sequence {...} s[d1]...[dn] // => Sequence {...} s[d1]...[dn] Sequence cdmseq = new Sequence ( ncfile , cdmgroup , cdmparentstruct , dapseq . getShortName ( ) ) ; cdmvar = cdmseq ; this . nodemap . put ( cdmvar , dapvar ) ; // Add the fields for ( DapVariable field : dapseq . getFields ( ) ) { createVar ( field , ncfile , cdmgroup , cdmseq ) ; } // If the rank > 0, then add warning attribute if ( dapvar . getRank ( ) > 0 ) { List value = new ArrayList ( ) ; value . add ( \"CDM does not support Sequences with rank > 0\" ) ; Attribute warning = new Attribute ( \"_WARNING:\" , value ) ; cdmvar . addAttribute ( warning ) ; } } else assert ( false ) : \"Unknown variable sort: \" + dapvar . getSort ( ) ; int rank = dapvar . getRank ( ) ; List < Dimension > cdmdims = new ArrayList < Dimension > ( rank + 1 ) ; // +1 for vlen for ( int i = 0 ; i < rank ; i ++ ) { DapDimension dim = dapvar . getDimension ( i ) ; Dimension cdmdim = createDimensionRef ( dim , cdmgroup ) ; cdmdims . add ( cdmdim ) ; } if ( basetype . isSeqType ( ) ) { // Add the final vlen cdmdims . add ( Dimension . VLEN ) ; } cdmvar . setDimensions ( cdmdims ) ; // Create variable's attributes for ( String key : dapvar . getAttributes ( ) . keySet ( ) ) { DapAttribute attr = dapvar . getAttributes ( ) . get ( key ) ; Attribute cdmattr = createAttribute ( attr ) ; cdmvar . addAttribute ( cdmattr ) ; } if ( cdmparentstruct != null ) cdmparentstruct . addMemberVariable ( cdmvar ) ; else if ( cdmgroup != null ) cdmgroup . addVariable ( cdmvar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] void note ( Notes note ) { assert ( this . allnotes != null ) ; int gid = note . gid ; int id = note . id ; NoteSort sort = note . getSort ( ) ; Map < Long , Notes > sortnotes = this . allnotes . get ( sort ) ; assert sortnotes != null ; switch ( sort ) { case TYPE : case GROUP : case DIM : assert sortnotes . get ( id ) == null ; sortnotes . put ( ( long ) id , note ) ; break ; case VAR : long gv = Nc4Notes . getVarId ( ( VarNotes ) note ) ; assert sortnotes . get ( gv ) == null ; sortnotes . put ( gv , note ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] VarNotes findVar ( int gid , int varid ) { long gv = Nc4Notes . getVarId ( gid , varid , - 1 ) ; return ( VarNotes ) find ( gv , NoteSort . VAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] VarNotes findField ( int gid , int varid , int fid ) { long gv = Nc4Notes . getVarId ( gid , varid , fid ) ; return ( VarNotes ) find ( gv , NoteSort . VAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] Notes find ( DapNode node ) { NoteSort sort = noteSortFor ( node ) ; assert ( this . allnotes != null ) ; Map < Long , Notes > sortnotes = this . allnotes . get ( sort ) ; assert sortnotes != null ; for ( Map . Entry < Long , Notes > entries : sortnotes . entrySet ( ) ) { Notes note = entries . getValue ( ) ; if ( note . get ( ) == node ) return note ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "DSP API [CODESPLIT] @ Override public Nc4DSP open ( String filepath ) throws DapException { if ( filepath . startsWith ( \"file:\" ) ) try { XURI xuri = new XURI ( filepath ) ; filepath = xuri . getPath ( ) ; } catch ( URISyntaxException use ) { throw new DapException ( \"Malformed filepath: \" + filepath ) . setCode ( DapCodes . SC_NOT_FOUND ) ; } int ret , mode ; IntByReference ncidp = new IntByReference ( ) ; this . filepath = filepath ; try { mode = NC_NOWRITE ; Nc4Cursor . errcheck ( nc4 , ret = nc4 . nc_open ( this . filepath , mode , ncidp ) ) ; this . ncid = ncidp . getValue ( ) ; // Figure out what kind of file IntByReference formatp = new IntByReference ( ) ; Nc4Cursor . errcheck ( nc4 , ret = nc4 . nc_inq_format ( ncid , formatp ) ) ; this . format = formatp . getValue ( ) ; if ( DEBUG ) System . out . printf ( \"TestNetcdf: open: %s; ncid=%d; format=%d%n\" , this . filepath , ncid , this . format ) ; // Compile the DMR Nc4DMRCompiler dmrcompiler = new Nc4DMRCompiler ( this , ncid , dmrfactory ) ; setDMR ( dmrcompiler . compile ( ) ) ; if ( DEBUG || DUMPDMR ) { System . err . println ( \"+++++++++++++++++++++\" ) ; System . err . println ( printDMR ( getDMR ( ) ) ) ; System . err . println ( \"+++++++++++++++++++++\" ) ; } return this ; } catch ( Exception t ) { t . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] static public String makeString ( byte [ ] b ) { // null terminates int count ; for ( count = 0 ; ( count < b . length && b [ count ] != 0 ) ; count ++ ) { ; } return new String ( b , 0 , count , DapUtil . UTF8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a SimpleUnit from the given name catch Exceptions . [CODESPLIT] static public SimpleUnit factory ( String name ) { try { return factoryWithExceptions ( name ) ; } catch ( Exception e ) { if ( debugParse ) System . out . println ( \"Parse \" + name + \" got Exception \" + e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a SimpleUnit from the given name allow Exceptions . [CODESPLIT] static public SimpleUnit factoryWithExceptions ( String name ) throws UnitException { UnitFormat format = UnitFormatManager . instance ( ) ; Unit uu = format . parse ( name ) ; //if (isDateUnit(uu)) return new DateUnit(name); if ( isTimeUnit ( uu ) ) return new TimeUnit ( name ) ; return new SimpleUnit ( uu ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "need subclass access [CODESPLIT] static protected Unit makeUnit ( String name ) throws UnitException { UnitFormat format = UnitFormatManager . instance ( ) ; return format . parse ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if unitString1 is compatible to unitString2 meaning one can be converted to the other . If either unit string is illegal return false . [CODESPLIT] static public boolean isCompatible ( String unitString1 , String unitString2 ) { Unit uu1 , uu2 ; try { UnitFormat format = UnitFormatManager . instance ( ) ; uu1 = format . parse ( unitString1 ) ; } catch ( Exception e ) { if ( debugParse ) System . out . println ( \"Parse \" + unitString1 + \" got Exception1 \" + e ) ; return false ; } try { UnitFormat format = UnitFormatManager . instance ( ) ; uu2 = format . parse ( unitString2 ) ; } catch ( Exception e ) { if ( debugParse ) System . out . println ( \"Parse \" + unitString2 + \" got Exception2 \" + e ) ; return false ; } //System.out.println(\"udunits isCompatible \"+ uu1+ \" \"+ uu2); return uu1 . isCompatible ( uu2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if unitString1 is convertible to unitString2 [CODESPLIT] static public boolean isCompatibleWithExceptions ( String unitString1 , String unitString2 ) throws UnitException { UnitFormat format = UnitFormatManager . instance ( ) ; Unit uu1 = format . parse ( unitString1 ) ; Unit uu2 = format . parse ( unitString2 ) ; return uu1 . isCompatible ( uu2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if this ucar . units . Unit is a Date . [CODESPLIT] static public boolean isDateUnit ( ucar . units . Unit uu ) { boolean ok = uu . isCompatible ( dateReferenceUnit ) ; if ( ! ok ) return false ; try { uu . getConverterTo ( dateReferenceUnit ) ; return true ; } catch ( ConversionException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given unit is convertible to a date Unit . allowed format is something like : <pre > [ - ] Y [ Y [ Y [ Y ]]] - MM - DD [ ( T| ) hh [ : mm [ : ss [ . sss * ]]] [ [ + | - ] hh [[ : ] mm ]]] < / pre > [CODESPLIT] static public boolean isDateUnit ( String unitString ) { SimpleUnit su = factory ( unitString ) ; return su != null && isDateUnit ( su . getUnit ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given unit is a time Unit eg seconds . [CODESPLIT] static public boolean isTimeUnit ( String unitString ) { SimpleUnit su = factory ( unitString ) ; return su != null && isTimeUnit ( su . getUnit ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the conversion factor to convert inputUnit to outputUnit . [CODESPLIT] static public double getConversionFactor ( String inputUnitString , String outputUnitString ) throws IllegalArgumentException { SimpleUnit inputUnit = SimpleUnit . factory ( inputUnitString ) ; SimpleUnit outputUnit = SimpleUnit . factory ( outputUnitString ) ; return inputUnit . convertTo ( 1.0 , outputUnit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert given value of this unit to the new unit . [CODESPLIT] public double convertTo ( double value , SimpleUnit outputUnit ) throws IllegalArgumentException { try { return uu . convertTo ( value , outputUnit . getUnit ( ) ) ; } catch ( ConversionException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if unitString1 is compatible to unitString2 meaning one can be converted to the other . If either unit string is illegal return false . [CODESPLIT] public boolean isCompatible ( String unitString ) { Unit uuWant ; try { UnitFormat format = UnitFormatManager . instance ( ) ; uuWant = format . parse ( unitString ) ; } catch ( Exception e ) { if ( debugParse ) System . out . println ( \"Parse \" + unitString + \" got Exception1 \" + e ) ; return false ; } return uu . isCompatible ( uuWant ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this an instance of an UnknownUnit? [CODESPLIT] public boolean isUnknownUnit ( ) { ucar . units . Unit uu = getUnit ( ) ; if ( uu instanceof ucar . units . UnknownUnit ) return true ; if ( uu instanceof ucar . units . DerivedUnit ) return isUnknownUnit ( ( ucar . units . DerivedUnit ) uu ) ; if ( uu instanceof ucar . units . ScaledUnit ) { ucar . units . ScaledUnit scu = ( ucar . units . ScaledUnit ) uu ; Unit u = scu . getUnit ( ) ; if ( u instanceof ucar . units . UnknownUnit ) return true ; if ( u instanceof ucar . units . DerivedUnit ) return isUnknownUnit ( ( ucar . units . DerivedUnit ) u ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the value can only be called for ScaledUnit . [CODESPLIT] public double getValue ( ) { if ( ! ( uu instanceof ScaledUnit ) ) return Double . NaN ; ScaledUnit offset = ( ScaledUnit ) uu ; return offset . getScale ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a clause which which compares subclauses using one of the relative operators supported by the Operator class . [CODESPLIT] public TopLevelClause newRelOpClause ( int operator , SubClause lhs , List rhs ) throws DAP2ServerSideException { return new RelOpClause ( operator , lhs , rhs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a clause which invokes a function that returns a boolean value . [CODESPLIT] public TopLevelClause newBoolFunctionClause ( String functionName , List children ) throws DAP2ServerSideException , NoSuchFunctionException { BoolFunction function = functionLibrary . getBoolFunction ( functionName ) ; if ( function == null ) { if ( functionLibrary . getBTFunction ( functionName ) != null ) { throw new NoSuchFunctionException ( \"The function \" + functionName + \"() does not return a \" + \"boolean value, and must be used in a comparison or \" + \"as an argument to another function.\" ) ; } else { throw new NoSuchFunctionException ( \"This server does not support a \" + functionName + \"() function\" ) ; } } return new BoolFunctionClause ( function , children ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a clause which invokes a function that returns a BaseType . [CODESPLIT] public SubClause newBTFunctionClause ( String functionName , List children ) throws DAP2ServerSideException , NoSuchFunctionException { BTFunction function = functionLibrary . getBTFunction ( functionName ) ; if ( function == null ) { if ( functionLibrary . getBoolFunction ( functionName ) != null ) { throw new NoSuchFunctionException ( \"The function \" + functionName + \"() cannot be used as a \" + \"sub-expression in a constraint clause\" ) ; } else { throw new NoSuchFunctionException ( \"This server does not support a \" + functionName + \"() function\" ) ; } } return new BTFunctionClause ( function , children ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void writeDataFinish () throws IOException { ArrayInt . D1 nextChildArray = new ArrayInt . D1 ( recno ) ; [CODESPLIT] public void writeRecord ( StationObsDatatype sobs , StructureData sdata ) throws IOException { if ( debug ) System . out . println ( \"sobs= \" + sobs + \"; station = \" + sobs . getStation ( ) ) ; for ( Variable v : recordVars ) { if ( timeName . equals ( v . getShortName ( ) ) ) { Date d = sobs . getObservationTimeAsDate ( ) ; int secs = ( int ) ( d . getTime ( ) / 1000 ) ; timeArray . set ( 0 , secs ) ; } else if ( parentName . equals ( v . getShortName ( ) ) ) { int stationIndex = stnList . indexOf ( sobs . getStation ( ) ) ; parentArray . set ( 0 , stationIndex ) ; } else { v . setCachedData ( sdata . getArray ( v . getShortName ( ) ) , false ) ; } } ncfile . writeRecordData ( recordVars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public static void rewrite ( String fileIn , String fileOut , boolean inMemory , boolean sort ) throws IOException { System . out . println ( \"Rewrite .nc files from \" + fileIn + \" to \" + fileOut + \"inMem= \" + inMemory + \" sort= \" + sort ) ; long start = System . currentTimeMillis ( ) ; // do it in memory for speed NetcdfFile ncfile = inMemory ? NetcdfFile . openInMemory ( fileIn ) : NetcdfFile . open ( fileIn ) ; NetcdfDataset ncd = new NetcdfDataset ( ncfile ) ; StringBuilder errlog = new StringBuilder ( ) ; StationObsDataset sobs = ( StationObsDataset ) TypedDatasetFactory . open ( FeatureType . STATION , ncd , null , errlog ) ; List < ucar . unidata . geoloc . Station > stns = sobs . getStations ( ) ; List < VariableSimpleIF > vars = sobs . getDataVariables ( ) ; FileOutputStream fos = new FileOutputStream ( fileOut ) ; DataOutputStream out = new DataOutputStream ( fos ) ; WriterCFStationObsDataset writer = new WriterCFStationObsDataset ( out , \"rewrite \" + fileIn ) ; writer . writeHeader ( stns , vars , - 1 ) ; if ( sort ) { for ( ucar . unidata . geoloc . Station s : stns ) { DataIterator iter = sobs . getDataIterator ( s ) ; while ( iter . hasNext ( ) ) { StationObsDatatype sobsData = ( StationObsDatatype ) iter . nextData ( ) ; StructureData data = sobsData . getData ( ) ; writer . writeRecord ( sobsData , data ) ; } } } else { DataIterator iter = sobs . getDataIterator ( 1000 * 1000 ) ; while ( iter . hasNext ( ) ) { StationObsDatatype sobsData = ( StationObsDatatype ) iter . nextData ( ) ; StructureData data = sobsData . getData ( ) ; writer . writeRecord ( sobsData , data ) ; } } writer . finish ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . println ( \"Rewrite \" + fileIn + \" to \" + fileOut + \" took = \" + took ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapt a rank 2 array into a java . awt . image . BufferedImage . If passed a rank 3 array take first 2D slice . [CODESPLIT] public static java . awt . image . BufferedImage makeGrayscaleImage ( Array ma , IsMissingEvaluator missEval ) { if ( ma . getRank ( ) < 2 ) return null ; if ( ma . getRank ( ) == 3 ) ma = ma . reduce ( ) ; if ( ma . getRank ( ) == 3 ) ma = ma . slice ( 0 , 0 ) ; // we need 2D int h = ma . getShape ( ) [ 0 ] ; int w = ma . getShape ( ) [ 1 ] ; DataBuffer dataBuffer = makeDataBuffer ( ma , missEval ) ; WritableRaster raster = WritableRaster . createInterleavedRaster ( dataBuffer , w , h , //   int w, int h, w , //   int scanlineStride, 1 , //    int pixelStride, new int [ ] { 0 } , //   int bandOffsets[], null ) ; //   Point location) ColorSpace cs = ColorSpace . getInstance ( ColorSpace . CS_GRAY ) ; ComponentColorModel colorModel = new ComponentColorModel ( cs , new int [ ] { 8 } , false , false , Transparency . OPAQUE , DataBuffer . TYPE_BYTE ) ; return new BufferedImage ( colorModel , raster , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////// [CODESPLIT] protected String translatePathToReletiveLocation ( String dsPath , String configPath ) { if ( dsPath == null ) return null ; if ( dsPath . length ( ) == 0 ) return null ; if ( dsPath . startsWith ( \"/\" ) ) dsPath = dsPath . substring ( 1 ) ; if ( ! dsPath . startsWith ( configPath ) ) return null ; // remove the matching part, the rest is the \"reletive location\" String dataDir = dsPath . substring ( configPath . length ( ) ) ; if ( dataDir . startsWith ( \"/\" ) ) dataDir = dataDir . substring ( 1 ) ; return dataDir ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a catalog and crawl ( depth first ) all the datasets in it . Close catalogs and release their resources as you . [CODESPLIT] public int crawl ( String catUrl , CancelTask task , PrintWriter out , Object context ) { InvCatalogFactory catFactory = InvCatalogFactory . getDefaultFactory ( true ) ; InvCatalogImpl cat = catFactory . readXML ( catUrl ) ; StringBuilder buff = new StringBuilder ( ) ; boolean isValid = cat . check ( buff , false ) ; if ( out != null ) { out . println ( \"catalog <\" + cat . getName ( ) + \"> \" + ( isValid ? \"is\" : \"is not\" ) + \" valid\" ) ; out . println ( \" validation output=\\n\" + buff ) ; } if ( isValid ) return crawl ( cat , task , out , context ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Crawl a catalog thats already been opened . When you get to a dataset containing leaf datasets do all only the first or a randomly chosen one . [CODESPLIT] public int crawl ( InvCatalogImpl cat , CancelTask task , PrintWriter out , Object context ) { if ( out != null ) out . println ( \"***CATALOG \" + cat . getCreateFrom ( ) ) ; countCatrefs = 0 ; for ( InvDataset ds : cat . getDatasets ( ) ) { if ( type == Type . all ) crawlDataset ( ds , task , out , context , true ) ; else crawlDirectDatasets ( ds , task , out , context , true ) ; if ( ( task != null ) && task . isCancel ( ) ) break ; } return 1 + countCatrefs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Crawl this dataset recursively return all datasets [CODESPLIT] public void crawlDataset ( InvDataset ds , CancelTask task , PrintWriter out , Object context , boolean release ) { boolean isCatRef = ( ds instanceof InvCatalogRef ) ; if ( filter != null && filter . skipAll ( ds ) ) { if ( isCatRef && release ) ( ( InvCatalogRef ) ds ) . release ( ) ; return ; } boolean isDataScan = ds . findProperty ( \"DatasetScan\" ) != null ; if ( isCatRef ) { InvCatalogRef catref = ( InvCatalogRef ) ds ; if ( out != null ) out . println ( \" **CATREF \" + catref . getURI ( ) + \" (\" + ds . getName ( ) + \") \" ) ; countCatrefs ++ ; if ( ! listen . getCatalogRef ( catref , context ) ) { if ( release ) catref . release ( ) ; return ; } } if ( ! isCatRef || isDataScan ) listen . getDataset ( ds , context ) ; // recurse - depth first List < InvDataset > dlist = ds . getDatasets ( ) ; if ( isCatRef ) { InvCatalogRef catref = ( InvCatalogRef ) ds ; if ( ! isDataScan ) { listen . getDataset ( catref . getProxyDataset ( ) , context ) ; // wait till a catref is read, so all metadata is there ! } } for ( InvDataset dds : dlist ) { crawlDataset ( dds , task , out , context , release ) ; if ( ( task != null ) && task . isCancel ( ) ) break ; } if ( isCatRef && release ) { InvCatalogRef catref = ( InvCatalogRef ) ds ; catref . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Crawl this dataset recursively . Only send back direct datasets [CODESPLIT] public void crawlDirectDatasets ( InvDataset ds , CancelTask task , PrintWriter out , Object context , boolean release ) { boolean isCatRef = ( ds instanceof InvCatalogRef ) ; if ( filter != null && filter . skipAll ( ds ) ) { if ( isCatRef && release ) ( ( InvCatalogRef ) ds ) . release ( ) ; return ; } if ( isCatRef ) { InvCatalogRef catref = ( InvCatalogRef ) ds ; if ( out != null ) out . println ( \" **CATREF \" + catref . getURI ( ) + \" (\" + ds . getName ( ) + \") \" ) ; countCatrefs ++ ; if ( ! listen . getCatalogRef ( catref , context ) ) { if ( release ) catref . release ( ) ; return ; } } // get datasets with data access (\"leaves\") List < InvDataset > dlist = ds . getDatasets ( ) ; List < InvDataset > leaves = new ArrayList < InvDataset > ( ) ; for ( InvDataset dds : dlist ) { if ( dds . hasAccess ( ) ) leaves . add ( dds ) ; } if ( leaves . size ( ) > 0 ) { if ( type == Type . first_direct ) { InvDataset dds = leaves . get ( 0 ) ; listen . getDataset ( dds , context ) ; } else if ( type == Type . random_direct ) { listen . getDataset ( chooseRandom ( leaves ) , context ) ; } else if ( type == Type . random_direct_middle ) { listen . getDataset ( chooseRandomNotFirstOrLast ( leaves ) , context ) ; } else { // do all of them for ( InvDataset dds : leaves ) { listen . getDataset ( dds , context ) ; if ( ( task != null ) && task . isCancel ( ) ) break ; } } } // recurse for ( InvDataset dds : dlist ) { if ( dds . hasNestedDatasets ( ) ) crawlDirectDatasets ( dds , task , out , context , release ) ; if ( ( task != null ) && task . isCancel ( ) ) break ; } /* if (out != null) {\n     int took = (int) (System.currentTimeMillis() - start);\n     out.println(\" ** \" + ds.getName() + \" took \" + took + \" msecs\\n\");\n   } */ if ( ds instanceof InvCatalogRef && release ) { InvCatalogRef catref = ( InvCatalogRef ) ds ; catref . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get index file may be in cache directory may not exist [CODESPLIT] public static File getFileOrCache ( String fileLocation ) { File result = getExistingFileOrCache ( fileLocation ) ; if ( result != null ) return result ; return getDiskCache2 ( ) . getFile ( fileLocation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looking for an existing file in cache or not [CODESPLIT] public static File getExistingFileOrCache ( String fileLocation ) { File result = getDiskCache2 ( ) . getExistingFileOrCache ( fileLocation ) ; if ( result == null && Grib . debugGbxIndexOnly && fileLocation . endsWith ( \".gbx9.ncx4\" ) ) { // might create only from gbx9 for debugging int length = fileLocation . length ( ) ; String maybeIndexAlreadyExists = fileLocation . substring ( 0 , length - 10 ) + \".ncx4\" ; result = getDiskCache2 ( ) . getExistingFileOrCache ( maybeIndexAlreadyExists ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gml : Point / gml : pos [CODESPLIT] public static DirectPositionType initPos ( DirectPositionType pos , StationTimeSeriesFeature stationFeat ) { // TEXT pos . setListValue ( Arrays . asList ( stationFeat . getLatitude ( ) , stationFeat . getLongitude ( ) , stationFeat . getAltitude ( ) ) ) ; return pos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "java . net calls this : [CODESPLIT] protected PasswordAuthentication getPasswordAuthentication ( ) { if ( pwa == null ) throw new IllegalStateException ( ) ; if ( debug ) { System . out . println ( \"site= \" + getRequestingSite ( ) ) ; System . out . println ( \"port= \" + getRequestingPort ( ) ) ; System . out . println ( \"protocol= \" + getRequestingProtocol ( ) ) ; System . out . println ( \"prompt= \" + getRequestingPrompt ( ) ) ; System . out . println ( \"scheme= \" + getRequestingScheme ( ) ) ; } serverF . setText ( getRequestingHost ( ) + \":\" + getRequestingPort ( ) ) ; realmF . setText ( getRequestingPrompt ( ) ) ; dialog . setVisible ( true ) ; if ( debug ) { System . out . println ( \"user= (\" + pwa . getUserName ( ) + \")\" ) ; System . out . println ( \"password= (\" + pwa . getPassword ( ) + \")\" ) ; } return new PasswordAuthentication ( pwa . getUserName ( ) , pwa . getPassword ( ) . toCharArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http client calls this : [CODESPLIT] public Credentials getCredentials ( AuthScope scope ) { serverF . setText ( scope . getHost ( ) + \":\" + scope . getPort ( ) ) ; String realmName = scope . getRealm ( ) ; if ( realmName == null ) { realmName = \"THREDDS Data Server\" ; } realmF . setText ( realmName ) ; dialog . setVisible ( true ) ; if ( pwa == null ) throw new IllegalStateException ( ) ; if ( debug ) { System . out . println ( \"user= (\" + pwa . getUserName ( ) + \")\" ) ; System . out . println ( \"password= (\" + new String ( pwa . getPassword ( ) ) + \")\" ) ; } // Is this really necessary? UsernamePasswordCredentials upc = new UsernamePasswordCredentials ( pwa . getUserName ( ) , new String ( pwa . getPassword ( ) ) ) ; return upc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debugging do not use in production . Set counters to zero set debugging on [CODESPLIT] static public void setDebugLeaks ( boolean b ) { if ( b ) { count_openFiles . set ( 0 ) ; maxOpenFiles . set ( 0 ) ; allFiles = new HashSet <> ( 1000 ) ; } debugLeaks = b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Debugging do not use . [CODESPLIT] static public List < String > getAllFiles ( ) { if ( null == allFiles ) return null ; List < String > result = new ArrayList <> ( ) ; result . addAll ( allFiles ) ; Collections . sort ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the file and release any associated system resources . [CODESPLIT] public synchronized void close ( ) throws IOException { if ( cache != null ) { if ( cacheState > 0 ) { if ( cacheState == 1 ) { cacheState = 2 ; if ( cache . release ( this ) ) // return true if in the cache, otherwise was opened regular, so must be closed regular\r return ; cacheState = 0 ; // release failed, bail out\r } else { return ; // close has been called more than once - ok\r } } } if ( debugLeaks ) { openFiles . remove ( location ) ; if ( showOpen ) System . out . println ( \"  close \" + location ) ; } if ( file == null ) return ; // If we are writing and the buffer has been modified, flush the contents of the buffer.\r flush ( ) ; // may need to extend file, in case no fill is being used\r // may need to truncate file in case overwriting a longer file\r // use only if minLength is set (by N3iosp)\r long fileSize = file . length ( ) ; if ( ! readonly && ( minLength != 0 ) && ( minLength != fileSize ) ) { file . setLength ( minLength ) ; // System.out.println(\"TRUNCATE!!! minlength=\"+minLength);\r } // Close the underlying file object.\r file . close ( ) ; file = null ; // help the gc\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the position in the file for the next read or write . [CODESPLIT] public void seek ( long pos ) throws IOException { if ( pos < 0 ) throw new java . io . IOException ( \"Negative seek offset\" ) ; // If the seek is into the buffer, just update the file pointer.\r if ( ( pos >= bufferStart ) && ( pos < dataEnd ) ) { filePosition = pos ; return ; } // need new buffer, starting at pos\r readBuffer ( pos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the length of the file . The data in the buffer ( which may not have been written the disk yet ) is taken into account . [CODESPLIT] public long length ( ) throws IOException { long fileLength = ( file == null ) ? - 1L : file . length ( ) ; // GRIB has closed the data raf\r if ( fileLength < dataEnd ) { return dataEnd ; } else { return fileLength ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the contents of the buffer to the disk . [CODESPLIT] public void flush ( ) throws IOException { if ( bufferModified ) { file . seek ( bufferStart ) ; file . write ( buffer , 0 , dataSize ) ; //System.out.println(\"--flush at \"+bufferStart+\" dataSize= \"+dataSize+ \" filePosition= \"+filePosition);\r bufferModified = false ; } /* check min length\r\n    if (!readonly && (minLength != 0) && (minLength != file.length())) {\r\n      file.setLength(minLength);\r\n    } */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a byte of data from the file blocking until data is available . [CODESPLIT] public int read ( ) throws IOException { // If the file position is within the data, return the byte...\r if ( filePosition < dataEnd ) { int pos = ( int ) ( filePosition - bufferStart ) ; filePosition ++ ; return ( buffer [ pos ] & 0xff ) ; // ...or should we indicate EOF...\r } else if ( endOfFile ) { return - 1 ; // ...or seek to fill the buffer, and try again.\r } else { seek ( filePosition ) ; return read ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read up to <code > len< / code > bytes into an array at a specified offset . This will block until at least one byte has been read . [CODESPLIT] public int readBytes ( byte b [ ] , int off , int len ) throws IOException { // Check for end of file.\r if ( endOfFile ) { return - 1 ; } // See how many bytes are available in the buffer - if none,\r // seek to the file position to update the buffer and try again.\r int bytesAvailable = ( int ) ( dataEnd - filePosition ) ; if ( bytesAvailable < 1 ) { seek ( filePosition ) ; return readBytes ( b , off , len ) ; } // Copy as much as we can.\r int copyLength = ( bytesAvailable >= len ) ? len : bytesAvailable ; System . arraycopy ( buffer , ( int ) ( filePosition - bufferStart ) , b , off , copyLength ) ; filePosition += copyLength ; // If there is more to copy...\r if ( copyLength < len ) { int extraCopy = len - copyLength ; // If the amount remaining is more than a buffer's length, read it\r // directly from the file.\r if ( extraCopy > buffer . length ) { extraCopy = read_ ( filePosition , b , off + copyLength , len - copyLength ) ; // ...or read a new buffer full, and copy as much as possible...\r } else { seek ( filePosition ) ; if ( ! endOfFile ) { extraCopy = ( extraCopy > dataSize ) ? dataSize : extraCopy ; System . arraycopy ( buffer , 0 , b , off + copyLength , extraCopy ) ; } else { extraCopy = - 1 ; } } // If we did manage to copy any more, update the file position and\r // return the amount copied.\r if ( extraCopy > 0 ) { filePosition += extraCopy ; return copyLength + extraCopy ; } } // Return the amount copied.\r return copyLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read <code > nbytes< / code > bytes at the specified file offset send to a WritableByteChannel . This will block until all bytes are read . This uses the underlying file channel directly bypassing all user buffers . [CODESPLIT] public long readToByteChannel ( WritableByteChannel dest , long offset , long nbytes ) throws IOException { if ( fileChannel == null ) fileChannel = file . getChannel ( ) ; long need = nbytes ; while ( need > 0 ) { long count = fileChannel . transferTo ( offset , need , dest ) ; //if (count == 0) break;  // LOOK not sure what the EOF condition is\r need -= count ; offset += count ; } return nbytes - need ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read directly from file without going through the buffer . All reading goes through here or readToByteChannel ; [CODESPLIT] protected int read_ ( long pos , byte [ ] b , int offset , int len ) throws IOException { file . seek ( pos ) ; int n = file . read ( b , offset , len ) ; if ( debugAccess ) { if ( showRead ) System . out . println ( \" **read_ \" + location + \" = \" + len + \" bytes at \" + pos + \"; block = \" + ( pos / buffer . length ) ) ; debug_nseeks . incrementAndGet ( ) ; debug_nbytes . addAndGet ( len ) ; } if ( extendMode && ( n < len ) ) { //System.out.println(\" read_ = \"+len+\" at \"+pos+\"; got = \"+n);\r n = len ; } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads exactly <code > len< / code > bytes from this file into the byte array . This method reads repeatedly from the file until all the bytes are read . This method blocks until all the bytes are read the end of the stream is detected or an exception is thrown . [CODESPLIT] public final void readFully ( byte b [ ] , int off , int len ) throws IOException { int n = 0 ; while ( n < len ) { int count = this . read ( b , off + n , len - n ) ; if ( count < 0 ) { throw new EOFException ( \"Reading \" + location + \" at \" + filePosition + \" file length = \" + length ( ) ) ; } n += count ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a byte to the file . If the file has not been opened for writing an IOException will be raised only when an attempt is made to write the buffer to the file . <p / > Caveat : the effects of seek ( ) ing beyond the end of the file are undefined . [CODESPLIT] public void write ( int b ) throws IOException { // If the file position is within the block of data...\r if ( filePosition < dataEnd ) { int pos = ( int ) ( filePosition - bufferStart ) ; buffer [ pos ] = ( byte ) b ; bufferModified = true ; filePosition ++ ; // ...or (assuming that seek will not allow the file pointer\r // to move beyond the end of the file) get the correct block of\r // data...\r } else { // If there is room in the buffer, expand it...\r if ( dataSize != buffer . length ) { int pos = ( int ) ( filePosition - bufferStart ) ; buffer [ pos ] = ( byte ) b ; bufferModified = true ; filePosition ++ ; dataSize ++ ; dataEnd ++ ; // ...or do another seek to get a new buffer, and start again...\r } else { seek ( filePosition ) ; write ( b ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write <code > len< / code > bytes from an array to the file . [CODESPLIT] public void writeBytes ( byte b [ ] , int off , int len ) throws IOException { // If the amount of data is small (less than a full buffer)...\r if ( len < buffer . length ) { // If any of the data fits within the buffer...\r int spaceInBuffer = 0 ; int copyLength = 0 ; if ( filePosition >= bufferStart ) { spaceInBuffer = ( int ) ( ( bufferStart + buffer . length ) - filePosition ) ; } if ( spaceInBuffer > 0 ) { // Copy as much as possible to the buffer.\r copyLength = ( spaceInBuffer > len ) ? len : spaceInBuffer ; System . arraycopy ( b , off , buffer , ( int ) ( filePosition - bufferStart ) , copyLength ) ; bufferModified = true ; long myDataEnd = filePosition + copyLength ; dataEnd = ( myDataEnd > dataEnd ) ? myDataEnd : dataEnd ; dataSize = ( int ) ( dataEnd - bufferStart ) ; filePosition += copyLength ; ///System.out.println(\"--copy to buffer \"+copyLength+\" \"+len);\r } // If there is any data remaining, move to the new position and copy to\r // the new buffer.\r if ( copyLength < len ) { //System.out.println(\"--need more \"+copyLength+\" \"+len+\" space= \"+spaceInBuffer);\r seek ( filePosition ) ; // triggers a flush\r System . arraycopy ( b , off + copyLength , buffer , ( int ) ( filePosition - bufferStart ) , len - copyLength ) ; bufferModified = true ; long myDataEnd = filePosition + ( len - copyLength ) ; dataEnd = ( myDataEnd > dataEnd ) ? myDataEnd : dataEnd ; dataSize = ( int ) ( dataEnd - bufferStart ) ; filePosition += ( len - copyLength ) ; } // ...or write a lot of data...\r } else { // Flush the current buffer, and write this data to the file.\r if ( bufferModified ) { flush ( ) ; } file . seek ( filePosition ) ; // moved per Steve Cerruti; Jan 14, 2005\r file . write ( b , off , len ) ; //System.out.println(\"--write at \"+filePosition+\" \"+len);\r filePosition += len ; bufferStart = filePosition ; // an empty buffer\r dataSize = 0 ; dataEnd = bufferStart + dataSize ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an array of shorts [CODESPLIT] public final void readShort ( short [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { pa [ start + i ] = readShort ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an integer at the given position bypassing all buffering . [CODESPLIT] public final int readIntUnbuffered ( long pos ) throws IOException { byte [ ] bb = new byte [ 4 ] ; read_ ( pos , bb , 0 , 4 ) ; int ch1 = bb [ 0 ] & 0xff ; int ch2 = bb [ 1 ] & 0xff ; int ch3 = bb [ 2 ] & 0xff ; int ch4 = bb [ 3 ] & 0xff ; if ( ( ch1 | ch2 | ch3 | ch4 ) < 0 ) { throw new EOFException ( ) ; } if ( bigEndian ) { return ( ( ch1 << 24 ) + ( ch2 << 16 ) + ( ch3 << 8 ) + ( ch4 ) ) ; } else { return ( ( ch4 << 24 ) + ( ch3 << 16 ) + ( ch2 << 8 ) + ( ch1 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an array of ints [CODESPLIT] public final void readInt ( int [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { pa [ start + i ] = readInt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an array of longs [CODESPLIT] public final void readLong ( long [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { pa [ start + i ] = readLong ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an array of floats [CODESPLIT] public final void readFloat ( float [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { pa [ start + i ] = Float . intBitsToFloat ( readInt ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an array of doubles [CODESPLIT] public final void readDouble ( double [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { pa [ start + i ] = Double . longBitsToDouble ( readLong ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a String of known length . [CODESPLIT] public String readString ( int nbytes ) throws IOException { byte [ ] data = new byte [ nbytes ] ; readFully ( data ) ; return new String ( data , CDM . utf8Charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a String of max length zero terminate . [CODESPLIT] public String readStringMax ( int nbytes ) throws IOException { byte [ ] b = new byte [ nbytes ] ; readFully ( b ) ; int count ; for ( count = 0 ; count < nbytes ; count ++ ) if ( b [ count ] == 0 ) break ; return new String ( b , 0 , count , CDM . utf8Charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of booleans [CODESPLIT] public final void writeBoolean ( boolean [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { writeBoolean ( pa [ start + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of shorts [CODESPLIT] public final void writeShort ( short [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { writeShort ( pa [ start + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of chars [CODESPLIT] public final void writeChar ( char [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { writeChar ( pa [ start + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of ints [CODESPLIT] public final void writeInt ( int [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { writeInt ( pa [ start + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of longs [CODESPLIT] public final void writeLong ( long [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { writeLong ( pa [ start + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of floats [CODESPLIT] public final void writeFloat ( float [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { writeFloat ( pa [ start + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of doubles [CODESPLIT] public final void writeDouble ( double [ ] pa , int start , int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { writeDouble ( pa [ start + i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the string to the file as a sequence of bytes . Each character in the string is written out in sequence by discarding its high eight bits . [CODESPLIT] public final void writeBytes ( String s ) throws IOException { int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { write ( ( byte ) s . charAt ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the character array to the file as a sequence of bytes . Each character in the string is written out in sequence by discarding its high eight bits . [CODESPLIT] public final void writeBytes ( char b [ ] , int off , int len ) throws IOException { for ( int i = off ; i < len ; i ++ ) { write ( ( byte ) b [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a string to the file as a sequence of characters . Each character is written to the data output stream as if by the <code > writeChar< / code > method . [CODESPLIT] public final void writeChars ( String s ) throws IOException { int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { int v = s . charAt ( i ) ; write ( ( v >>> 8 ) & 0xFF ) ; write ( ( v ) & 0xFF ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a string to the file using UTF - 8 encoding in a machine - independent manner . <p / > First two bytes are written to the file as if by the <code > writeShort< / code > method giving the number of bytes to follow . This value is the number of bytes actually written out not the length of the string . Following the length each character of the string is output in sequence using the UTF - 8 encoding for each character . [CODESPLIT] public final void writeUTF ( String str ) throws IOException { int strlen = str . length ( ) ; int utflen = 0 ; for ( int i = 0 ; i < strlen ; i ++ ) { int c = str . charAt ( i ) ; if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { utflen ++ ; } else if ( c > 0x07FF ) { utflen += 3 ; } else { utflen += 2 ; } } if ( utflen > 65535 ) { throw new UTFDataFormatException ( ) ; } write ( ( utflen >>> 8 ) & 0xFF ) ; write ( ( utflen ) & 0xFF ) ; for ( int i = 0 ; i < strlen ; i ++ ) { int c = str . charAt ( i ) ; if ( ( c >= 0x0001 ) && ( c <= 0x007F ) ) { write ( c ) ; } else if ( c > 0x07FF ) { write ( 0xE0 | ( ( c >> 12 ) & 0x0F ) ) ; write ( 0x80 | ( ( c >> 6 ) & 0x3F ) ) ; write ( 0x80 | ( ( c ) & 0x3F ) ) ; } else { write ( 0xC0 | ( ( c >> 6 ) & 0x1F ) ) ; write ( 0x80 | ( ( c ) & 0x3F ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search forward from the current pos looking for a match . [CODESPLIT] public boolean searchForward ( KMPMatch match , int maxBytes ) throws IOException { long start = getFilePointer ( ) ; long last = ( maxBytes < 0 ) ? length ( ) : Math . min ( length ( ) , start + maxBytes ) ; long needToScan = last - start ; // check what ever is now in the buffer\r int bytesAvailable = ( int ) ( dataEnd - filePosition ) ; if ( bytesAvailable < 1 ) { seek ( filePosition ) ; // read a new buffer\r bytesAvailable = ( int ) ( dataEnd - filePosition ) ; } int bufStart = ( int ) ( filePosition - bufferStart ) ; int scanBytes = ( int ) Math . min ( bytesAvailable , needToScan ) ; int pos = match . indexOf ( buffer , bufStart , scanBytes ) ; if ( pos >= 0 ) { seek ( bufferStart + pos ) ; return true ; } int matchLen = match . getMatchLength ( ) ; needToScan -= scanBytes - matchLen ; while ( needToScan > matchLen ) { readBuffer ( dataEnd - matchLen ) ; // force new buffer\r scanBytes = ( int ) Math . min ( buffer . length , needToScan ) ; pos = match . indexOf ( buffer , 0 , scanBytes ) ; if ( pos > 0 ) { seek ( bufferStart + pos ) ; return true ; } needToScan -= scanBytes - matchLen ; } // failure\r seek ( last ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the selector result string and append . [CODESPLIT] public void appendQuery ( StringBuffer sbuff , ArrayList values ) { if ( template != null ) appendQueryFromTemplate ( sbuff , values ) ; else appendQueryFromParamValue ( sbuff , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * since none of these are required can only do consistency checks [CODESPLIT] @ Override public boolean isValid ( NcssGridParamsBean params , ConstraintValidatorContext constraintValidatorContext ) { constraintValidatorContext . disableDefaultConstraintViolation ( ) ; boolean isValid = true ; // lat/lon point if ( params . getLatitude ( ) != null || params . getLongitude ( ) != null ) { if ( ! params . hasLatLonPoint ( ) ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.lat_or_lon_missing}\" ) . addConstraintViolation ( ) ; } } // lat/lon bb if ( params . getNorth ( ) != null || params . getSouth ( ) != null || params . getEast ( ) != null || params . getWest ( ) != null ) { if ( ! params . hasLatLonBB ( ) ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.wrong_bbox}\" ) . addConstraintViolation ( ) ; } if ( params . getNorth ( ) < params . getSouth ( ) ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.north_south}\" ) . addConstraintViolation ( ) ; } if ( params . getEast ( ) < params . getWest ( ) ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.east_west}\" ) . addConstraintViolation ( ) ; } } // proj bb if ( params . getMaxx ( ) != null || params . getMinx ( ) != null || params . getMaxy ( ) != null || params . getMiny ( ) != null ) { if ( ! params . hasProjectionBB ( ) ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.wrong_pbox}\" ) . addConstraintViolation ( ) ; } if ( params . getMaxx ( ) < params . getMinx ( ) ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.rangex}\" ) . addConstraintViolation ( ) ; } if ( params . getMaxy ( ) < params . getMiny ( ) ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.rangey}\" ) . addConstraintViolation ( ) ; } } // runtime: latest, all, or time if ( params . getRuntime ( ) != null ) { if ( \"latest\" . equalsIgnoreCase ( params . getRuntime ( ) ) ) { params . setLatestRuntime ( true ) ; } else if ( \"all\" . equalsIgnoreCase ( params . getRuntime ( ) ) ) { params . setAllRuntime ( true ) ; } else { CalendarDate cd = TimeParamsValidator . validateISOString ( params . getRuntime ( ) , \"{thredds.server.ncSubset.validation.param.runtime}\" , constraintValidatorContext ) ; if ( cd != null ) params . setRuntimeDate ( cd ) ; } } // timeOffset: first or double if ( params . getTimeOffset ( ) != null ) { if ( \"first\" . equalsIgnoreCase ( params . getTimeOffset ( ) ) ) { params . setFirstTimeOffset ( true ) ; } else { try { double val = Double . parseDouble ( params . getTimeOffset ( ) ) ; params . setTimeOffsetVal ( val ) ; } catch ( NumberFormatException e ) { constraintValidatorContext . buildConstraintViolationWithTemplate ( \"{thredds.server.ncSubset.validation.param.time_offset}\" ) . addConstraintViolation ( ) ; } } } return isValid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a DirectoryPartition or DirectoryCollection [CODESPLIT] static public MCollection factory ( FeatureCollectionConfig config , Path topDir , boolean isTop , IndexReader indexReader , String suffix , org . slf4j . Logger logger ) throws IOException { DirectoryBuilder builder = new DirectoryBuilder ( config . collectionName , topDir . toString ( ) , suffix ) ; DirectoryPartition dpart = new DirectoryPartition ( config , topDir , isTop , indexReader , suffix , logger ) ; if ( ! builder . isLeaf ( indexReader ) ) { // its a partition return dpart ; } // its a collection boolean hasIndex = builder . findIndex ( ) ; if ( hasIndex ) { return dpart . makeChildCollection ( builder ) ; } else { DirectoryCollection result = new DirectoryCollection ( config . collectionName , topDir , isTop , config . olderThan , logger ) ; // no index file return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the index file using its canonical name [CODESPLIT] public boolean findIndex ( ) throws IOException { Path indexPath = Paths . get ( dir . toString ( ) , partitionName + suffix ) ; if ( Files . exists ( indexPath ) ) { this . index = indexPath ; BasicFileAttributes attr = Files . readAttributes ( indexPath , BasicFileAttributes . class ) ; this . indexLastModified = attr . lastModifiedTime ( ) ; this . indexSize = attr . size ( ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans first 100 files to decide if its a leaf . If so it becomes a DirectoryCollection else a PartitionCollection . [CODESPLIT] private boolean isLeaf ( IndexReader indexReader ) throws IOException { if ( partitionStatus == PartitionStatus . unknown ) { int countDir = 0 , countFile = 0 , count = 0 ; try ( DirectoryStream < Path > dirStream = Files . newDirectoryStream ( dir ) ) { Iterator < Path > iterator = dirStream . iterator ( ) ; while ( iterator . hasNext ( ) && count ++ < 100 ) { Path p = iterator . next ( ) ; BasicFileAttributes attr = Files . readAttributes ( p , BasicFileAttributes . class ) ; if ( attr . isDirectory ( ) ) countDir ++ ; else countFile ++ ; } } partitionStatus = ( countFile > countDir ) ? PartitionStatus . isLeaf : PartitionStatus . isDirectoryPartition ; } return partitionStatus == PartitionStatus . isLeaf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find all children directories . Does not recurse . We separate this from the constructor so it can be done on demand Public for debugging . [CODESPLIT] public List < DirectoryBuilder > constructChildren ( IndexReader indexReader , CollectionUpdateType forceCollection ) throws IOException { if ( childrenConstructed ) return children ; if ( index != null && forceCollection == CollectionUpdateType . nocheck ) { // use index if it exists constructChildrenFromIndex ( indexReader , false ) ; } else { scanForChildren ( ) ; } //once we have found children, we know that this is a time partition partitionStatus = ( children . size ( ) > 0 ) ? PartitionStatus . isDirectoryPartition : PartitionStatus . isLeaf ; childrenConstructed = true ; // otherwise we are good return children ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan for subdirectories make each into a DirectoryBuilder and add as a child [CODESPLIT] private void scanForChildren ( ) { if ( debug ) System . out . printf ( \"DirectoryBuilder.scanForChildren on %s \" , dir ) ; int count = 0 ; try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( dir ) ) { for ( Path p : ds ) { BasicFileAttributes attr = Files . readAttributes ( p , BasicFileAttributes . class ) ; if ( attr . isDirectory ( ) ) { children . add ( new DirectoryBuilder ( topCollectionName , p , attr , suffix ) ) ; if ( debug && ( ++ count % 10 == 0 ) ) System . out . printf ( \"%d \" , count ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; } if ( debug ) System . out . printf ( \"done=%d%n\" , count ) ; childrenConstructed = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read the list of files from the index [CODESPLIT] public List < MFile > readFilesFromIndex ( IndexReader indexReader ) throws IOException { List < MFile > result = new ArrayList <> ( 100 ) ; if ( index == null ) return result ; indexReader . readMFiles ( index , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a netcdf dataset using NetcdfDataset . defaultEnhanceMode plus CoordSystems and turn into a GridDataset . [CODESPLIT] static public GridDataset open ( String location ) throws java . io . IOException { return open ( location , NetcdfDataset . getDefaultEnhanceMode ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open a netcdf dataset using NetcdfDataset . defaultEnhanceMode plus CoordSystems and turn into a GridDataset . [CODESPLIT] static public GridDataset open ( String location , Set < NetcdfDataset . Enhance > enhanceMode ) throws java . io . IOException { NetcdfDataset ds = ucar . nc2 . dataset . NetcdfDataset . acquireDataset ( null , DatasetUrl . findDatasetUrl ( location ) , enhanceMode , - 1 , null , null ) ; return new GridDataset ( ds , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return GridDatatype objects grouped by GridCoordSys . All GridDatatype in a Gridset have the same GridCoordSystem . [CODESPLIT] public List < ucar . nc2 . dt . GridDataset . Gridset > getGridsets ( ) { return new ArrayList < ucar . nc2 . dt . GridDataset . Gridset > ( gridsetHash . values ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show Grids and coordinate systems . [CODESPLIT] private void getInfo ( Formatter buf ) { int countGridset = 0 ; for ( Gridset gs : gridsetHash . values ( ) ) { GridCoordSystem gcs = gs . getGeoCoordSystem ( ) ; buf . format ( \"%nGridset %d  coordSys=%s\" , countGridset , gcs ) ; buf . format ( \" LLbb=%s \" , gcs . getLatLonBoundingBox ( ) ) ; if ( ( gcs . getProjection ( ) != null ) && ! gcs . getProjection ( ) . isLatLon ( ) ) buf . format ( \" bb= %s\" , gcs . getBoundingBox ( ) ) ; buf . format ( \"%n\" ) ; buf . format ( \"Name__________________________Unit__________________________hasMissing_Description%n\" ) ; for ( GridDatatype grid : gs . getGrids ( ) ) { buf . format ( \"%s%n\" , grid . getInfo ( ) ) ; } countGridset ++ ; buf . format ( \"%n\" ) ; } buf . format ( \"%nGeoReferencing Coordinate Axes%n\" ) ; buf . format ( \"Name__________________________Units_______________Type______Description%n\" ) ; for ( CoordinateAxis axis : ncd . getCoordinateAxes ( ) ) { if ( axis . getAxisType ( ) == null ) continue ; axis . getInfo ( buf ) ; buf . format ( \"%n\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FileCacheable [CODESPLIT] @ Override public synchronized void close ( ) throws java . io . IOException { if ( fileCache != null ) { if ( fileCache . release ( this ) ) return ; } try { if ( ncd != null ) ncd . close ( ) ; } finally { ncd = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "You must call shutdown () to shut down the background threads in order to get a clean process shutdown . [CODESPLIT] public static synchronized void shutdown ( ) { if ( timer != null ) { timer . cancel ( ) ; System . out . printf ( \"FileCache.shutdown called%n\" ) ; } timer = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquire a FileCacheable and lock it so no one else can use it . call FileCacheable . close when done . [CODESPLIT] public FileCacheable acquire ( FileFactory factory , DatasetUrl durl , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return acquire ( factory , durl . trueurl , durl , - 1 , cancelTask , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquire a FileCacheable from the cache and lock it so no one else can use it . If not already in cache open it the FileFactory and put in cache . <p / > App should call FileCacheable . close when done and the file is then released instead of closed . <p / > If cache size goes over maxElement then immediately ( actually in 100 msec ) schedule a cleanup in a background thread . This means that the cache should never get much larger than maxElement unless you have them all locked . [CODESPLIT] @ Override public FileCacheable acquire ( FileFactory factory , Object hashKey , DatasetUrl location , int buffer_size , CancelTask cancelTask , Object spiObject ) throws IOException { if ( null == hashKey ) hashKey = location . trueurl ; if ( null == hashKey ) throw new IllegalArgumentException ( ) ; Tracker t = null ; if ( trackAll ) { t = new Tracker ( hashKey ) ; Tracker prev = track . putIfAbsent ( hashKey , t ) ; if ( prev != null ) t = prev ; } FileCacheable ncfile = acquireCacheOnly ( hashKey ) ; if ( ncfile != null ) { hits . incrementAndGet ( ) ; if ( t != null ) t . hit ++ ; return ncfile ; } miss . incrementAndGet ( ) ; if ( t != null ) t . miss ++ ; // open the file\r ncfile = factory . open ( location , buffer_size , cancelTask , spiObject ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"FileCache \" + name + \" acquire \" + hashKey + \" \" + ncfile . getLocation ( ) ) ; if ( debugPrint ) System . out . println ( \"  FileCache \" + name + \" acquire \" + hashKey + \" \" + ncfile . getLocation ( ) ) ; // user may have canceled\r if ( ( cancelTask != null ) && ( cancelTask . isCancel ( ) ) ) { if ( ncfile != null ) ncfile . close ( ) ; // LOOK ??\r return null ; } if ( disabled . get ( ) ) return ncfile ; // see if cache element already exists\r // cant use putIfAbsent, because we cant create the CacheElement until we know if doesnt exist\r CacheElement elem ; synchronized ( cache ) { elem = cache . get ( hashKey ) ; if ( elem == null ) cache . put ( hashKey , new CacheElement ( ncfile , hashKey ) ) ; // new element\r } // already exists, add to list\r if ( elem != null ) { synchronized ( elem ) { elem . addFile ( ncfile ) ; // add to existing list\r } } // increment the number of files in the cache\r //int count = counter.incrementAndGet();\r // do we need a cleanup ??\r boolean needHard = false ; boolean needSoft = false ; synchronized ( hasScheduled ) { if ( ! hasScheduled . get ( ) ) { int count = files . size ( ) ; if ( ( count > hardLimit ) && ( hardLimit > 0 ) ) { needHard = true ; hasScheduled . getAndSet ( true ) ; // tell other threads not to schedule another cleanup\r } else if ( ( count > softLimit ) && ( softLimit > 0 ) ) { // && wantsCleanup) { //\r hasScheduled . getAndSet ( true ) ; // tell other threads not to schedule another cleanup\r needSoft = true ; } } } if ( needHard ) { if ( debugCleanup ) System . out . println ( \"CleanupTask due to hard limit time=\" + new Date ( ) . getTime ( ) ) ; // +\" Thread=\"+Thread.currentThread().hashCode()\r cleanup ( hardLimit ) ; } else if ( needSoft ) { schedule ( new CleanupTask ( ) , 100 ) ; // immediate cleanup in 100 msec\r if ( debugCleanup ) System . out . println ( \"CleanupTask scheduled due to soft limit time=\" + new Date ( ) ) ; } return ncfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to find a file in the cache . [CODESPLIT] private FileCacheable acquireCacheOnly ( Object hashKey ) { if ( disabled . get ( ) ) return null ; // see if its in the cache\r CacheElement wantCacheElem = cache . get ( hashKey ) ; if ( wantCacheElem == null ) return null ; // not found in cache\r CacheElement . CacheFile want = null ; synchronized ( wantCacheElem ) { // synch in order to traverse the list\r for ( CacheElement . CacheFile file : wantCacheElem . list ) { if ( file . isLocked . compareAndSet ( false , true ) ) { want = file ; break ; } } } if ( want == null ) return null ; // no unlocked file in cache\r // check if modified, remove if so\r if ( want . ncfile != null ) { long lastModified = want . ncfile . getLastModified ( ) ; boolean changed = lastModified != want . lastModified ; if ( cacheLog . isDebugEnabled ( ) && changed ) cacheLog . debug ( \"FileCache \" + name + \": acquire from cache \" + hashKey + \" \" + want . ncfile . getLocation ( ) + \" was changed; discard\" ) ; if ( changed ) { remove ( want ) ; } } if ( want . ncfile != null ) { try { want . ncfile . reacquire ( ) ; // rehydrate\r } catch ( IOException ioe ) { if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"FileCache \" + name + \" acquire from cache \" + hashKey + \" \" + want . ncfile . getLocation ( ) + \" failed: \" + ioe . getMessage ( ) ) ; remove ( want ) ; // failed\r } } if ( debugPrint && want . ncfile != null ) { System . out . printf ( \"  FileCache %s found in cache %s (countLocks %d)%n\" , name , hashKey , countLocked ( ) ) ; } return want . ncfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK should you remove the entire CacheElement ? [CODESPLIT] private void remove ( CacheElement . CacheFile want ) { want . remove ( ) ; files . remove ( want . ncfile ) ; try { want . ncfile . setFileCache ( null ) ; // unhook the caching\r want . ncfile . close ( ) ; } catch ( IOException e ) { log . error ( \"close failed on \" + want . ncfile . getLocation ( ) , e ) ; } want . ncfile = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all instances of object from the cache [CODESPLIT] @ Override public void eject ( Object hashKey ) { if ( disabled . get ( ) ) return ; // see if its in the cache\r CacheElement wantCacheElem = cache . get ( hashKey ) ; if ( wantCacheElem == null ) return ; synchronized ( wantCacheElem ) { // synch in order to traverse the list\r for ( CacheElement . CacheFile want : wantCacheElem . list ) { // LOOK can we use remove(want);  ??\r files . remove ( want . ncfile ) ; try { want . ncfile . setFileCache ( null ) ; // unhook the caching\r want . ncfile . close ( ) ; // really close the file\r log . debug ( \"close \" + want . ncfile . getLocation ( ) ) ; } catch ( IOException e ) { log . error ( \"close failed on \" + want . ncfile . getLocation ( ) , e ) ; } want . ncfile = null ; if ( debugPrint ) System . out . println ( \"  FileCache \" + name + \" eject \" + hashKey ) ; } wantCacheElem . list . clear ( ) ; } cache . remove ( hashKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Release the file . This unlocks it updates its lastAccessed date . Normally applications need not call this just close the file as usual . The FileCacheable has to do tricky stuff . [CODESPLIT] @ Override public boolean release ( FileCacheable ncfile ) throws IOException { if ( ncfile == null ) return false ; if ( disabled . get ( ) ) { ncfile . setFileCache ( null ) ; // prevent infinite loops\r ncfile . close ( ) ; return false ; } // find it in the file cache\r CacheElement . CacheFile file = files . get ( ncfile ) ; // using hashCode of the FileCacheable\r if ( file != null ) { if ( ! file . isLocked . get ( ) ) { cacheLog . warn ( \"FileCache \" + name + \" release \" + ncfile . getLocation ( ) + \" not locked; hash= \" + ncfile . hashCode ( ) ) ; } file . lastAccessed = System . currentTimeMillis ( ) ; file . countAccessed ++ ; file . isLocked . set ( false ) ; file . ncfile . release ( ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"FileCache \" + name + \" release \" + ncfile . getLocation ( ) + \"; hash= \" + ncfile . hashCode ( ) ) ; if ( debugPrint ) System . out . printf ( \"  FileCache %s release %s lock=%s count=%d%n\" , name , ncfile . getLocation ( ) , file . isLocked . get ( ) , countLocked ( ) ) ; return true ; } return false ; // throw new IOException(\"FileCache \" + name + \" release does not have file in cache = \" + ncfile.getLocation());\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] public String getInfo ( FileCacheable ncfile ) throws IOException { if ( ncfile == null ) return \"\" ; // find it in the file cache\r CacheElement . CacheFile file = files . get ( ncfile ) ; if ( file != null ) { return \"File is in cache= \" + file ; } return \"File not in cache\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show individual cache entries add to formatter . [CODESPLIT] @ Override public void showCache ( Formatter format ) { ArrayList < CacheElement . CacheFile > allFiles = new ArrayList <> ( files . size ( ) ) ; for ( CacheElement elem : cache . values ( ) ) { synchronized ( elem ) { allFiles . addAll ( elem . list ) ; } } Collections . sort ( allFiles ) ; // sort so oldest are on top\r format . format ( \"%nFileCache %s (min=%d softLimit=%d hardLimit=%d scour=%d secs):%n\" , name , minElements , softLimit , hardLimit , period / 1000 ) ; format . format ( \" isLocked  accesses lastAccess                   location %n\" ) ; for ( CacheElement . CacheFile file : allFiles ) { String loc = file . ncfile != null ? file . ncfile . getLocation ( ) : \"null\" ; format . format ( \"%8s %9d %s == %s %n\" , file . isLocked , file . countAccessed , CalendarDateFormatter . toDateTimeStringISO ( file . lastAccessed ) , loc ) ; } showStats ( format ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add stat report ( hits misses etc ) to formatter . [CODESPLIT] public void showStats ( Formatter format ) { format . format ( \"  hits= %d miss= %d nfiles= %d elems= %d%n\" , hits . get ( ) , miss . get ( ) , files . size ( ) , cache . values ( ) . size ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleanup the cache bringing it down to minimum number . Will close the LRU ( least recently used ) ones first . Will not close locked files . Normally this is done in a background thread you dont need to call . <p / > We have to synchronize because of clearCache () [CODESPLIT] synchronized void cleanup ( int maxElements ) { try { /* int size = counter.get();\r\n      int fsize = files.size();\r\n      if (debug && (size != fsize)) {\r\n        log.warn(\"FileCache \" + name + \" counter \" + size + \" doesnt match files().size=\" + fsize);\r\n      } */ int size = files . size ( ) ; if ( size <= minElements ) return ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"FileCache {} cleanup started at {} for maxElements={}\" , name , CalendarDate . present ( ) , maxElements ) ; if ( debugCleanup ) System . out . printf ( \" FileCache %s cleanup started at %s for maxElements=%d%n\" , name , CalendarDate . present ( ) , maxElements ) ; cleanups . incrementAndGet ( ) ; // add unlocked files to the all list\r List < CacheElement . CacheFile > allFiles = new ArrayList <> ( size + 10 ) ; for ( CacheElement . CacheFile file : files . values ( ) ) { if ( ! file . isLocked . get ( ) ) allFiles . add ( file ) ; } Collections . sort ( allFiles ) ; // sort so oldest are on top\r // take oldest ones and put on delete list\r int need2delete = size - minElements ; int minDelete = size - maxElements ; List < CacheElement . CacheFile > deleteList = new ArrayList <> ( need2delete ) ; int count = 0 ; Iterator < CacheElement . CacheFile > iter = allFiles . iterator ( ) ; while ( iter . hasNext ( ) && ( count < need2delete ) ) { CacheElement . CacheFile file = iter . next ( ) ; if ( file . isLocked . compareAndSet ( false , true ) ) { // lock it so it isnt used anywhere else\r file . remove ( ) ; // remove from the containing element\r deleteList . add ( file ) ; count ++ ; } } if ( count < minDelete ) { cacheLog . warn ( \"FileCache \" + name + \" cleanup couldnt remove enough to keep under the maximum= \" + maxElements + \" due to locked files; currently at = \" + ( size - count ) ) ; if ( debugCleanup ) System . out . println ( \"FileCache \" + name + \" cleanup couldnt remove enough to keep under the maximum= \" + maxElements + \" due to locked files; currently at = \" + ( size - count ) ) ; } // remove empty cache elements\r synchronized ( cache ) { for ( CacheElement elem : cache . values ( ) ) { synchronized ( elem ) { if ( elem . list . size ( ) == 0 ) cache . remove ( elem . hashKey ) ; } } } // now actually close the files\r long start = System . currentTimeMillis ( ) ; for ( CacheElement . CacheFile file : deleteList ) { //counter.decrementAndGet();\r if ( null == files . remove ( file . ncfile ) ) { if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \" FileCache {} cleanup failed to remove {}%n\" , name , file . ncfile . getLocation ( ) ) ; } try { file . ncfile . setFileCache ( null ) ; file . ncfile . close ( ) ; file . ncfile = null ; // help the gc\r } catch ( IOException e ) { log . error ( \"FileCache \" + name + \" close failed on \" + file . getCacheName ( ) ) ; } } long took = System . currentTimeMillis ( ) - start ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \" FileCache {} cleanup had={} removed={} took={} msecs%n\" , name , size , deleteList . size ( ) , took ) ; if ( debugCleanup ) System . out . printf ( \" FileCache %s cleanup had=%d removed=%d took=%d msecs%n\" , name , size , deleteList . size ( ) , took ) ; } finally { // allow scheduling again\r hasScheduled . set ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert 4 bytes into a signed integer . [CODESPLIT] private static int int4 ( int a , int b , int c , int d ) { // all bits set to ones\r if ( a == 0xff && b == 0xff && c == 0xff && d == 0xff ) return UNDEFINED ; return ( 1 - ( ( a & 128 ) >> 6 ) ) * ( ( a & 127 ) << 24 | b << 16 | c << 8 | d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquire a FileCacheable and lock it so no one else can use it . call FileCacheable . close () when done . [CODESPLIT] @ Override public FileCacheable acquire ( FileFactory factory , DatasetUrl location ) throws IOException { return acquire ( factory , location . trueurl , location , - 1 , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquire a FileCacheable from the cache and lock it so no one else can use it . If not already in cache open it with FileFactory and put in cache . <p / > Call FileCacheable . close () when done ( rather than FileCacheIF . release () directly ) and the file is then released instead of closed . <p / > If cache size goes over maxElement then immediately ( actually in 100 msec ) schedule a cleanup in a background thread . This means that the cache should never get much larger than maxElement unless you have them all locked . [CODESPLIT] @ Override public FileCacheable acquire ( FileFactory factory , Object hashKey , DatasetUrl location , int buffer_size , CancelTask cancelTask , Object spiObject ) throws IOException { if ( null == hashKey ) hashKey = location . trueurl ; if ( null == hashKey ) throw new IllegalArgumentException ( ) ; Tracker t = null ; if ( trackAll ) { t = new Tracker ( hashKey ) ; Tracker prev = track . putIfAbsent ( hashKey , t ) ; if ( prev != null ) t = prev ; } FileCacheable ncfile = acquireCacheOnly ( hashKey ) ; if ( ncfile != null ) { hits . incrementAndGet ( ) ; if ( t != null ) t . hit ++ ; return ncfile ; } miss . incrementAndGet ( ) ; if ( t != null ) t . miss ++ ; // open the file ncfile = factory . open ( location , buffer_size , cancelTask , spiObject ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"FileCacheARC \" + name + \" acquire \" + hashKey + \" \" + ncfile . getLocation ( ) ) ; if ( debugPrint ) System . out . println ( \"  FileCacheARC \" + name + \" acquire \" + hashKey + \" \" + ncfile . getLocation ( ) ) ; // user may have canceled if ( ( cancelTask != null ) && ( cancelTask . isCancel ( ) ) ) { if ( ncfile != null ) ncfile . close ( ) ; return null ; } if ( disabled . get ( ) ) return ncfile ; addToCache ( hashKey , ncfile ) ; return ncfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to find a file in the cache . [CODESPLIT] private FileCacheable acquireCacheOnly ( Object hashKey ) { if ( disabled . get ( ) ) return null ; // see if its in the cache CacheElement wantCacheElem = cache . get ( hashKey ) ; if ( wantCacheElem == null ) return null ; // not found in cache CacheElement . CacheFile want = null ; for ( CacheElement . CacheFile file : wantCacheElem . list ) { if ( file . isLocked . compareAndSet ( false , true ) ) { want = file ; break ; } } if ( want == null ) return null ; // no unlocked file in cache // check if modified, remove if so if ( want . ncfile != null ) { long lastModified = want . ncfile . getLastModified ( ) ; boolean changed = lastModified != wantCacheElem . lastModified . get ( ) ; if ( changed ) { // underlying file was modified if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"FileCacheARC \" + name + \": acquire from cache \" + hashKey + \" \" + want . ncfile . getLocation ( ) + \" was changed; discard\" ) ; expireFromCache ( wantCacheElem ) ; return null ; } } updateInCache ( wantCacheElem ) ; return want . ncfile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get CacheElement specified by hashKey . If found update lastUsed in shadowCache . [CODESPLIT] private CacheElement updateInCache ( CacheElement elem ) { if ( shadowCache . firstKey ( ) == elem ) return elem ; elem . updateAccessed ( ) ; CacheElement prev = shadowCache . put ( elem , elem ) ; // faster if we could just insert at the top of the list. maybe we need to use LinkedList ? if ( prev != null && ( elem != prev ) ) { CacheElementComparator cc = new CacheElementComparator ( ) ; System . out . printf ( \"elem != prev compare=%d%n\" , cc . compare ( elem , prev ) ) ; System . out . printf ( \"hash elem =%d prev=%d%n\" , elem . hashCode ( ) , prev . hashCode ( ) ) ; } return elem ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * if ( disabled . get () ) return ; [CODESPLIT] private void addToCache ( Object hashKey , FileCacheable ncfile ) { CacheElement newCacheElem = new CacheElement ( hashKey ) ; CacheElement previous = cache . putIfAbsent ( hashKey , newCacheElem ) ; // add new element if doesnt exist CacheElement elem = ( previous != null ) ? previous : newCacheElem ; // use previous if it exists elem . addFile ( ncfile ) ; // add to existing list shadowCache . put ( newCacheElem , newCacheElem ) ; int size = cacheSize . getAndIncrement ( ) ; if ( size > softLimit ) { removeFromCache ( size - softLimit ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Release the file . This unlocks it updates its lastAccessed date . FileCacheable . close () needs to call this instead of actually closing . [CODESPLIT] @ Override public boolean release ( FileCacheable ncfile ) throws IOException { if ( ncfile == null ) return false ; if ( disabled . get ( ) ) { ncfile . setFileCache ( null ) ; // prevent infinite loops ncfile . close ( ) ; return false ; } // find it in the file cache int hashcode = System . identityHashCode ( ncfile ) ; // using Object hashCode of the FileCacheable CacheElement . CacheFile file = files . get ( hashcode ) ; if ( file != null ) { if ( ! file . isLocked . get ( ) ) { Exception e = new Exception ( \"Stack trace\" ) ; cacheLog . warn ( \"FileCacheARC \" + name + \" release \" + ncfile . getLocation ( ) + \" not locked; hash= \" + ncfile . hashCode ( ) , e ) ; } //file.lastAccessed = System.currentTimeMillis(); //file.countAccessed++; file . isLocked . set ( false ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"FileCacheARC \" + name + \" release \" + ncfile . getLocation ( ) + \"; hash= \" + ncfile . hashCode ( ) ) ; if ( debugPrint ) System . out . println ( \"  FileCacheARC \" + name + \" release \" + ncfile . getLocation ( ) ) ; return true ; } return false ; // throw new IOException(\"FileCacheARC \" + name + \" release does not have file in cache = \" + ncfile.getLocation()); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] public String getInfo ( FileCacheable ncfile ) throws IOException { if ( ncfile == null ) return \"\" ; // find it in the file cache int hashcode = System . identityHashCode ( ncfile ) ; CacheElement . CacheFile file = files . get ( hashcode ) ; if ( file != null ) { return \"File is in cache= \" + file ; } return \"File not in cache\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all cache entries . [CODESPLIT] public synchronized void clearCache ( boolean force ) { List < CacheElement . CacheFile > deleteList = new ArrayList <> ( 2 * cache . size ( ) ) ; if ( force ) { cache . clear ( ) ; // deletes everything from the cache deleteList . addAll ( files . values ( ) ) ; // add everything to the delete list files . clear ( ) ; // counter.set(0); } else { // add unlocked files to the delete list, remove from files hash Iterator < CacheElement . CacheFile > iter = files . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { CacheElement . CacheFile file = iter . next ( ) ; if ( file . isLocked . compareAndSet ( false , true ) ) { file . remove ( ) ; // remove from the containing CacheElement deleteList . add ( file ) ; iter . remove ( ) ; } } // remove empty cache elements for ( CacheElement elem : cache . values ( ) ) { if ( elem . list . size ( ) == 0 ) cache . remove ( elem . hashKey ) ; } } // close all files in deleteList for ( CacheElement . CacheFile file : deleteList ) { if ( force && file . isLocked . get ( ) ) cacheLog . warn ( \"FileCacheARC \" + name + \" force close locked file= \" + file ) ; //counter.decrementAndGet(); if ( file . ncfile == null ) continue ; try { file . ncfile . setFileCache ( null ) ; file . ncfile . close ( ) ; file . ncfile = null ; // help the gc } catch ( IOException e ) { log . error ( \"FileCacheARC \" + name + \" close failed on \" + file ) ; } } if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( \"*FileCacheARC \" + name + \" clearCache force= \" + force + \" deleted= \" + deleteList . size ( ) + \" left=\" + files . size ( ) ) ; //System.out.println(\"\\n*NetcdfFileCache.clearCache force= \" + force + \" deleted= \" + deleteList.size() + \" left=\" + counter.get()); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show individual cache entries add to formatter . [CODESPLIT] @ Override public void showCache ( Formatter format ) { ArrayList < CacheElement . CacheFile > allFiles = new ArrayList <> ( files . size ( ) ) ; for ( CacheElement elem : cache . values ( ) ) { allFiles . addAll ( elem . list ) ; } Collections . sort ( allFiles ) ; // sort so oldest are on top format . format ( \"%nFileCacheARC %s (min=%d softLimit=%d hardLimit=%d scour=%d):%n\" , name , minElements , softLimit , hardLimit , period ) ; format . format ( \"isLocked  accesses lastAccess                   location %n\" ) ; for ( CacheElement . CacheFile file : allFiles ) { String loc = file . ncfile != null ? file . ncfile . getLocation ( ) : \"null\" ; CalendarDate cd = CalendarDate . of ( file . getLastAccessed ( ) ) ; format . format ( \"%8s %9d %s %s %n\" , file . isLocked , file . getCountAccessed ( ) , CalendarDateFormatter . toTimeUnits ( cd ) , loc ) ; } showStats ( format ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////// [CODESPLIT] public void showTracking ( Formatter format ) { if ( track == null ) return ; List < Tracker > all = new ArrayList <> ( track . size ( ) ) ; for ( Tracker val : track . values ( ) ) all . ( val ) ; Collections . sort ( all ) ; // LOOK what should we sort by ?? int count = 0 ; int countAll = 0 ; format . format ( \"%nTrack of all files in FileCacheARC%n\" ) ; format . format ( \"   seq  accum   hit   miss  file%n\" ) ; for ( Tracker t : all ) { count ++ ; countAll += t . hit + t . miss ; format . format ( \"%6d  %6d : %5d %5d %s%n\" , count , countAll , t . hit , t . miss , t . key ) ; } format . format ( \"%n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * the parse function allows the specification of a new stream in case one is reusing the parser [CODESPLIT] public boolean parse ( String input ) throws ParseException { ( ( Dap2Lex ) yylexer ) . reset ( parsestate ) ; ( ( Dap2Lex ) yylexer ) . setText ( input ) ; return parse ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this CoordinateSystem can be made into a GridCoordSys . Optionally for a given variable . This currently assumes that the CoordinateSystem : <ol > <li > is georeferencing ( cs . isGeoReferencing () ) <li > x y are 1 or 2 - dimensional axes . <li > z t if they exist are 1 - dimensional axes . <li > domain rank > 1 < / ol > [CODESPLIT] public static boolean isGridCoordSys ( Formatter sbuff , CoordinateSystem cs , VariableEnhanced v ) { // must be at least 2 axes\r if ( cs . getRankDomain ( ) < 2 ) { if ( sbuff != null ) { sbuff . format ( \"%s: domain rank < 2%n\" , cs . getName ( ) ) ; } return false ; } // must be lat/lon or have x,y and projecction\r if ( ! cs . isLatLon ( ) ) { // do check for GeoXY ourself\r if ( ( cs . getXaxis ( ) == null ) || ( cs . getYaxis ( ) == null ) ) { if ( sbuff != null ) { sbuff . format ( \"%s: NO Lat,Lon or X,Y axis%n\" , cs . getName ( ) ) ; } return false ; } if ( null == cs . getProjection ( ) ) { if ( sbuff != null ) { sbuff . format ( \"%s: NO projection found%n\" , cs . getName ( ) ) ; } return false ; } } // obtain the x,y or lat/lon axes. x,y normally must be convertible to km\r CoordinateAxis xaxis , yaxis ; if ( cs . isGeoXY ( ) ) { xaxis = cs . getXaxis ( ) ; yaxis = cs . getYaxis ( ) ; // change to warning\r ProjectionImpl p = cs . getProjection ( ) ; if ( ! ( p instanceof RotatedPole ) ) { if ( ! SimpleUnit . kmUnit . isCompatible ( xaxis . getUnitsString ( ) ) ) { if ( sbuff != null ) { sbuff . format ( \"%s: X axis units are not convertible to km%n\" , cs . getName ( ) ) ; } //return false;\r } if ( ! SimpleUnit . kmUnit . isCompatible ( yaxis . getUnitsString ( ) ) ) { if ( sbuff != null ) { sbuff . format ( \"%s: Y axis units are not convertible to km%n\" , cs . getName ( ) ) ; } //return false;\r } } } else { xaxis = cs . getLonAxis ( ) ; yaxis = cs . getLatAxis ( ) ; } // check x,y rank <= 2\r if ( ( xaxis . getRank ( ) > 2 ) || ( yaxis . getRank ( ) > 2 ) ) { if ( sbuff != null ) sbuff . format ( \"%s: X or Y axis rank must be <= 2%n\" , cs . getName ( ) ) ; return false ; } // check that the x,y have at least 2 dimensions between them ( this eliminates point data)\r int xyDomainSize = CoordinateSystem . countDomain ( new CoordinateAxis [ ] { xaxis , yaxis } ) ; if ( xyDomainSize < 2 ) { if ( sbuff != null ) sbuff . format ( \"%s: X and Y axis must have 2 or more dimensions%n\" , cs . getName ( ) ) ; return false ; } List < CoordinateAxis > testAxis = new ArrayList <> ( ) ; testAxis . add ( xaxis ) ; testAxis . add ( yaxis ) ; //int countRangeRank = 2;\r CoordinateAxis z = cs . getHeightAxis ( ) ; if ( ( z == null ) || ! ( z instanceof CoordinateAxis1D ) ) z = cs . getPressureAxis ( ) ; if ( ( z == null ) || ! ( z instanceof CoordinateAxis1D ) ) z = cs . getZaxis ( ) ; if ( ( z != null ) && ! ( z instanceof CoordinateAxis1D ) ) { if ( sbuff != null ) { sbuff . format ( \"%s: Z axis must be 1D%n\" , cs . getName ( ) ) ; } return false ; } if ( z != null ) testAxis . add ( z ) ; // tom margolis 3/2/2010\r // allow runtime independent of time\r CoordinateAxis t = cs . getTaxis ( ) ; CoordinateAxis rt = cs . findAxis ( AxisType . RunTime ) ; // A runtime axis must be scalar or one-dimensional\r if ( rt != null ) { if ( ! rt . isScalar ( ) && ! ( rt instanceof CoordinateAxis1D ) ) { if ( sbuff != null ) sbuff . format ( \"%s: RunTime axis must be 1D%n\" , cs . getName ( ) ) ; return false ; } } // If time axis is two-dimensional...\r if ( ( t != null ) && ! ( t instanceof CoordinateAxis1D ) && ( t . getRank ( ) != 0 ) ) { if ( rt != null ) { if ( rt . getRank ( ) != 1 ) { if ( sbuff != null ) sbuff . format ( \"%s: Runtime axis must be 1D%n\" , cs . getName ( ) ) ; return false ; } // time first dimension must agree with runtime\r if ( ! rt . getDimension ( 0 ) . equals ( t . getDimension ( 0 ) ) ) { if ( sbuff != null ) sbuff . format ( \"%s: 2D Time axis first dimension must be runtime%n\" , cs . getName ( ) ) ; return false ; } } } if ( t != null ) testAxis . add ( t ) ; if ( rt != null ) testAxis . add ( rt ) ; CoordinateAxis ens = cs . getEnsembleAxis ( ) ; if ( ens != null ) testAxis . add ( ens ) ; if ( v != null ) { // test to see that v doesnt have extra dimensions. LOOK RELAX THIS\r List < Dimension > testDomain = new ArrayList <> ( ) ; for ( CoordinateAxis axis : testAxis ) { for ( Dimension dim : axis . getDimensions ( ) ) { if ( ! testDomain . contains ( dim ) ) testDomain . add ( dim ) ; } } if ( ! CoordinateSystem . isSubset ( v . getDimensionsAll ( ) , testDomain ) ) { if ( sbuff != null ) sbuff . format ( \" NOT complete%n\" ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the CoordinateSystem cs can be made into a GridCoordSys for the Variable v . [CODESPLIT] public static GridCoordSys makeGridCoordSys ( Formatter sbuff , CoordinateSystem cs , VariableEnhanced v ) { if ( sbuff != null ) { sbuff . format ( \" \" ) ; v . getNameAndDimensions ( sbuff , false , true ) ; sbuff . format ( \" check CS %s: \" , cs . getName ( ) ) ; } if ( isGridCoordSys ( sbuff , cs , v ) ) { GridCoordSys gcs = new GridCoordSys ( cs , sbuff ) ; if ( sbuff != null ) sbuff . format ( \" OK%n\" ) ; return gcs ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we have to delay making these since we dont identify the dimensions specifically until now [CODESPLIT] void makeVerticalTransform ( GridDataset gds , Formatter parseInfo ) { if ( vt != null ) return ; // already done\r if ( vCT == null ) return ; // no vt\r vt = vCT . makeVerticalTransform ( gds . getNetcdfDataset ( ) , timeDim ) ; if ( vt == null ) { if ( parseInfo != null ) parseInfo . format ( \"  - ERR can't make VerticalTransform = %s%n\" , vCT . getVerticalTransformType ( ) ) ; } else { if ( parseInfo != null ) parseInfo . format ( \"  - VerticalTransform = %s%n\" , vCT . getVerticalTransformType ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a global coverage over longitude ? [CODESPLIT] @ Override public boolean isGlobalLon ( ) { if ( ! isLatLon ) return false ; if ( ! ( horizXaxis instanceof CoordinateAxis1D ) ) return false ; CoordinateAxis1D lon = ( CoordinateAxis1D ) horizXaxis ; double first = lon . getCoordEdge ( 0 ) ; double last = lon . getCoordEdge ( ( int ) lon . getSize ( ) ) ; double min = Math . min ( first , last ) ; double max = Math . max ( first , last ) ; return ( max - min ) >= 360 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "true if increasing z coordinate values means up in altitude [CODESPLIT] @ Override public boolean isZPositive ( ) { if ( vertZaxis == null ) return false ; if ( vertZaxis . getPositive ( ) != null ) { return vertZaxis . getPositive ( ) . equalsIgnoreCase ( ucar . nc2 . constants . CF . POSITIVE_UP ) ; } if ( vertZaxis . getAxisType ( ) == AxisType . Height ) return true ; return vertZaxis . getAxisType ( ) != AxisType . Pressure ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a point in x y coordinate space find the x y index in the coordinate system . [CODESPLIT] @ Override public int [ ] findXYindexFromCoord ( double x_coord , double y_coord , int [ ] result ) { if ( result == null ) result = new int [ 2 ] ; if ( ( horizXaxis instanceof CoordinateAxis1D ) && ( horizYaxis instanceof CoordinateAxis1D ) ) { result [ 0 ] = ( ( CoordinateAxis1D ) horizXaxis ) . findCoordElement ( x_coord ) ; result [ 1 ] = ( ( CoordinateAxis1D ) horizYaxis ) . findCoordElement ( y_coord ) ; return result ; } else if ( ( horizXaxis instanceof CoordinateAxis2D ) && ( horizYaxis instanceof CoordinateAxis2D ) ) { if ( g2d == null ) g2d = new GridCoordinate2D ( ( CoordinateAxis2D ) horizYaxis , ( CoordinateAxis2D ) horizXaxis ) ; int [ ] result2 = new int [ 2 ] ; boolean found = g2d . findCoordElement ( y_coord , x_coord , result2 ) ; if ( found ) { result [ 0 ] = result2 [ 1 ] ; result [ 1 ] = result2 [ 0 ] ; } else { result [ 0 ] = - 1 ; result [ 1 ] = - 1 ; } return result ; } // cant happen\r throw new IllegalStateException ( \"GridCoordSystem.findXYindexFromCoord\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a point in x y coordinate space find the x y index in the coordinate system . If outside the range the closest point is returned eg 0 or n - 1 depending on if the coordinate is too small or too large . [CODESPLIT] @ Override public int [ ] findXYindexFromCoordBounded ( double x_coord , double y_coord , int [ ] result ) { if ( result == null ) result = new int [ 2 ] ; if ( ( horizXaxis instanceof CoordinateAxis1D ) && ( horizYaxis instanceof CoordinateAxis1D ) ) { result [ 0 ] = ( ( CoordinateAxis1D ) horizXaxis ) . findCoordElementBounded ( x_coord ) ; result [ 1 ] = ( ( CoordinateAxis1D ) horizYaxis ) . findCoordElementBounded ( y_coord ) ; return result ; } else if ( ( horizXaxis instanceof CoordinateAxis2D ) && ( horizYaxis instanceof CoordinateAxis2D ) ) { if ( g2d == null ) g2d = new GridCoordinate2D ( ( CoordinateAxis2D ) horizYaxis , ( CoordinateAxis2D ) horizXaxis ) ; int [ ] result2 = new int [ 2 ] ; g2d . findCoordElement ( y_coord , x_coord , result2 ) ; // returns best guess\r result [ 0 ] = result2 [ 1 ] ; result [ 1 ] = result2 [ 0 ] ; return result ; } // cant happen\r throw new IllegalStateException ( \"GridCoordSystem.findXYindexFromCoord\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a lat lon point find the x y index in the coordinate system . [CODESPLIT] @ Override public int [ ] findXYindexFromLatLon ( double lat , double lon , int [ ] result ) { Projection dataProjection = getProjection ( ) ; ProjectionPoint pp = dataProjection . latLonToProj ( new LatLonPointImpl ( lat , lon ) , new ProjectionPointImpl ( ) ) ; return findXYindexFromCoord ( pp . getX ( ) , pp . getY ( ) , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a lat lon point find the x y index in the coordinate system . If outside the range the closest point is returned [CODESPLIT] @ Override public int [ ] findXYindexFromLatLonBounded ( double lat , double lon , int [ ] result ) { Projection dataProjection = getProjection ( ) ; ProjectionPoint pp = dataProjection . latLonToProj ( new LatLonPointImpl ( lat , lon ) , new ProjectionPointImpl ( ) ) ; return findXYindexFromCoordBounded ( pp . getX ( ) , pp . getY ( ) , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the x y bounding box in projection coordinates . [CODESPLIT] @ Override public ProjectionRect getBoundingBox ( ) { if ( mapArea == null ) { if ( ( horizXaxis == null ) || ! horizXaxis . isNumeric ( ) || ( horizYaxis == null ) || ! horizYaxis . isNumeric ( ) ) return null ; // impossible\r // x,y may be 2D\r if ( ! ( horizXaxis instanceof CoordinateAxis1D ) || ! ( horizYaxis instanceof CoordinateAxis1D ) ) { /*  could try to optimize this - just get cord=ners or something\r\n        CoordinateAxis2D xaxis2 = (CoordinateAxis2D) horizXaxis;\r\n        CoordinateAxis2D yaxis2 = (CoordinateAxis2D) horizYaxis;\r\n        MAMath.MinMax\r\n        */ mapArea = new ProjectionRect ( horizXaxis . getMinValue ( ) , horizYaxis . getMinValue ( ) , horizXaxis . getMaxValue ( ) , horizYaxis . getMaxValue ( ) ) ; } else { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) horizXaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) horizYaxis ; /* add one percent on each side if its a projection. WHY?\r\n        double dx = 0.0, dy = 0.0;\r\n        if (!isLatLon()) {\r\n          dx = .01 * (xaxis1.getCoordEdge((int) xaxis1.getSize()) - xaxis1.getCoordEdge(0));\r\n          dy = .01 * (yaxis1.getCoordEdge((int) yaxis1.getSize()) - yaxis1.getCoordEdge(0));\r\n        }\r\n\r\n        mapArea = new ProjectionRect(xaxis1.getCoordEdge(0) - dx, yaxis1.getCoordEdge(0) - dy,\r\n            xaxis1.getCoordEdge((int) xaxis1.getSize()) + dx,\r\n            yaxis1.getCoordEdge((int) yaxis1.getSize()) + dy); */ mapArea = new ProjectionRect ( xaxis1 . getCoordEdge ( 0 ) , yaxis1 . getCoordEdge ( 0 ) , xaxis1 . getCoordEdge ( ( int ) xaxis1 . getSize ( ) ) , yaxis1 . getCoordEdge ( ( int ) yaxis1 . getSize ( ) ) ) ; } } return mapArea ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Lat / Lon coordinates of the midpoint of a grid cell using the x y indices [CODESPLIT] @ Override public LatLonPoint getLatLon ( int xindex , int yindex ) { double x , y ; if ( horizXaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizXaxis ; x = horiz1D . getCoordValue ( xindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizXaxis ; x = horiz2D . getCoordValue ( yindex , xindex ) ; } if ( horizYaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizYaxis ; y = horiz1D . getCoordValue ( yindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizYaxis ; y = horiz2D . getCoordValue ( yindex , xindex ) ; } return isLatLon ( ) ? new LatLonPointImpl ( y , x ) : getLatLon ( x , y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Index Ranges for the given lat lon bounding box . For projection only an approximation based on latlon corners . Must have CoordinateAxis1D or 2D for x and y axis . [CODESPLIT] @ Override public List < Range > getRangesFromLatLonRect ( LatLonRect rect ) throws InvalidRangeException { double minx , maxx , miny , maxy ; ProjectionImpl proj = getProjection ( ) ; if ( proj != null && ! ( proj instanceof VerticalPerspectiveView ) && ! ( proj instanceof MSGnavigation ) && ! ( proj instanceof Geostationary ) ) { // LOOK kludge - how to do this generrally ??\r // first clip the request rectangle to the bounding box of the grid\r LatLonRect bb = getLatLonBoundingBox ( ) ; LatLonRect rect2 = bb . intersect ( rect ) ; if ( null == rect2 ) throw new InvalidRangeException ( \"Request Bounding box does not intersect Grid \" ) ; rect = rect2 ; } CoordinateAxis xaxis = getXHorizAxis ( ) ; CoordinateAxis yaxis = getYHorizAxis ( ) ; if ( isLatLon ( ) ) { LatLonPointImpl llpt = rect . getLowerLeftPoint ( ) ; LatLonPointImpl urpt = rect . getUpperRightPoint ( ) ; LatLonPointImpl lrpt = rect . getLowerRightPoint ( ) ; LatLonPointImpl ulpt = rect . getUpperLeftPoint ( ) ; minx = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; miny = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; maxx = getMinOrMaxLon ( urpt . getLongitude ( ) , lrpt . getLongitude ( ) , false ) ; maxy = Math . min ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; // normalize to [minLon,minLon+360]\r double minLon = xaxis . getMinValue ( ) ; minx = LatLonPointImpl . lonNormalFrom ( minx , minLon ) ; maxx = LatLonPointImpl . lonNormalFrom ( maxx , minLon ) ; } else { ProjectionRect prect = getProjection ( ) . latLonToProjBB ( rect ) ; // allow projection to override\r minx = prect . getMinPoint ( ) . getX ( ) ; miny = prect . getMinPoint ( ) . getY ( ) ; maxx = prect . getMaxPoint ( ) . getX ( ) ; maxy = prect . getMaxPoint ( ) . getY ( ) ; /*\r\n      see ProjectionImpl.latLonToProjBB2()\r\n      Projection dataProjection = getProjection();\r\n      ProjectionPoint ll = dataProjection.latLonToProj(llpt, new ProjectionPointImpl());\r\n      ProjectionPoint ur = dataProjection.latLonToProj(urpt, new ProjectionPointImpl());\r\n      ProjectionPoint lr = dataProjection.latLonToProj(lrpt, new ProjectionPointImpl());\r\n      ProjectionPoint ul = dataProjection.latLonToProj(ulpt, new ProjectionPointImpl());\r\n\r\n      minx = Math.min(ll.getX(), ul.getX());\r\n      miny = Math.min(ll.getY(), lr.getY());\r\n      maxx = Math.max(ur.getX(), lr.getX());\r\n      maxy = Math.max(ul.getY(), ur.getY()); */ } if ( ( xaxis instanceof CoordinateAxis1D ) && ( yaxis instanceof CoordinateAxis1D ) ) { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) xaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) yaxis ; int minxIndex = xaxis1 . findCoordElementBounded ( minx ) ; int minyIndex = yaxis1 . findCoordElementBounded ( miny ) ; int maxxIndex = xaxis1 . findCoordElementBounded ( maxx ) ; int maxyIndex = yaxis1 . findCoordElementBounded ( maxy ) ; List < Range > list = new ArrayList <> ( ) ; list . add ( new Range ( Math . min ( minyIndex , maxyIndex ) , Math . max ( minyIndex , maxyIndex ) ) ) ; list . add ( new Range ( Math . min ( minxIndex , maxxIndex ) , Math . max ( minxIndex , maxxIndex ) ) ) ; return list ; } else if ( ( xaxis instanceof CoordinateAxis2D ) && ( yaxis instanceof CoordinateAxis2D ) && isLatLon ( ) ) { CoordinateAxis2D lon_axis = ( CoordinateAxis2D ) xaxis ; CoordinateAxis2D lat_axis = ( CoordinateAxis2D ) yaxis ; int shape [ ] = lon_axis . getShape ( ) ; int nj = shape [ 0 ] ; int ni = shape [ 1 ] ; int mini = Integer . MAX_VALUE , minj = Integer . MAX_VALUE ; int maxi = - 1 , maxj = - 1 ; // margolis 2/18/2010\r //minx = LatLonPointImpl.lonNormal( minx ); // <-- THIS IS NEW\r //maxx = LatLonPointImpl.lonNormal( maxx ); // <-- THIS IS NEW\r // brute force, examine every point LOOK BAD\r for ( int j = 0 ; j < nj ; j ++ ) { for ( int i = 0 ; i < ni ; i ++ ) { double lat = lat_axis . getCoordValue ( j , i ) ; double lon = lon_axis . getCoordValue ( j , i ) ; //lon = LatLonPointImpl.lonNormal( lon ); // <-- THIS IS NEW      \r if ( ( lat >= miny ) && ( lat <= maxy ) && ( lon >= minx ) && ( lon <= maxx ) ) { if ( i > maxi ) maxi = i ; if ( i < mini ) mini = i ; if ( j > maxj ) maxj = j ; if ( j < minj ) minj = j ; //System.out.println(j+\" \"+i+\" lat=\"+lat+\" lon=\"+lon);\r } } } // this is the case where no points are included\r if ( ( mini > maxi ) || ( minj > maxj ) ) { mini = 0 ; minj = 0 ; maxi = - 1 ; maxj = - 1 ; } ArrayList < Range > list = new ArrayList <> ( ) ; list . add ( new Range ( minj , maxj ) ) ; list . add ( new Range ( mini , maxi ) ) ; return list ; } else { throw new IllegalArgumentException ( \"must be 1D or 2D/LatLon \" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public List < CalendarDate > getCalendarDates ( ) { if ( timeTaxis != null ) return timeTaxis . getCalendarDates ( ) ; else if ( getRunTimeAxis ( ) != null ) return makeCalendarDates2D ( ) ; else return new ArrayList <> ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of level names to be used for user selection . The ith one refers to the ith level coordinate . [CODESPLIT] public List < NamedObject > getLevels ( ) { if ( vertZaxis == null ) return new ArrayList <> ( 0 ) ; int n = ( int ) vertZaxis . getSize ( ) ; List < NamedObject > levels = new ArrayList <> ( n ) ; for ( int i = 0 ; i < n ; i ++ ) levels . ( new ucar . nc2 . util . NamedAnything ( vertZaxis . getCoordName ( i ) , vertZaxis . getUnitsString ( ) ) ) ; return levels ; } /**\r\n   * Get the String name for the ith level(z) coordinate.\r\n   *\r\n   * @param index which level coordinate\r\n   * @return level name\r\n   */ public String getLevelName ( int index ) { if ( ( vertZaxis == null ) || ( index < 0 ) || ( index >= vertZaxis . getSize ( ) ) ) throw new IllegalArgumentException ( \"getLevelName = \" + index ) ; return vertZaxis . getCoordName ( index ) . trim ( ) ; } /**\r\n   * Get the index corresponding to the level name.\r\n   *\r\n   * @param name level name\r\n   * @return level index, or -1 if not found\r\n   */ public int getLevelIndex  ( String name ) { if ( ( vertZaxis == null ) || ( name == null ) ) return - 1 ; for ( int i = 0 ; i < vertZaxis . getSize ( ) ; i ++ ) { if ( vertZaxis . getCoordName ( i ) . trim ( ) . equals ( name ) ) return i ; } return - 1 ; } /**\r\n   * Get the list of time names, to be used for user selection.\r\n   * The ith one refers to the ith time coordinate.\r\n   *\r\n   * @return List of ucar.nc2.util.NamedObject, or empty list.\r\n   */ public List < NamedObject > getTimes  ( ) { List < CalendarDate > cdates = getCalendarDates ( ) ; List < NamedObject > times = new ArrayList <> ( cdates . size ( ) ) ; for ( CalendarDate cd : cdates ) { times . add ( new ucar . nc2 . util . NamedAnything ( cd . toString ( ) , \"calendar date\" ) ) ; } return times ; } ///////////////////////////////////////////////////////////////////////////\r // deprecated\r /**\r\n   * Given a point in x,y coordinate space, find the x,y index in the coordinate system.\r\n   *\r\n   * @deprecated use findXYindexFromCoord\r\n   */ public int [ ] findXYCoordElement  ( double x_coord , double y_coord , int [ ] result ) { return findXYindexFromCoord ( x_coord , y_coord , result ) ; } /**\r\n   * Get the date range\r\n   * @return date range\r\n   * @deprecated  use getCalendarDateRange\r\n   */ public DateRange getDateRange  ( ) { Date [ ] dates = getTimeDates ( ) ; if ( dates . length > 0 ) return new DateRange ( dates [ 0 ] , dates [ dates . length - 1 ] ) ; return null ; } /**\r\n   * Get the list of times as Dates.\r\n   * If 2D, return list of unique dates.\r\n   *\r\n   * @return array of java.util.Date, or Date[0].\r\n   * @deprecated  use getCalendarDates\r\n   */ public java . util . Date [ ] getTimeDates  ( ) { if ( ( timeTaxis != null ) && ( timeTaxis . getSize ( ) > 0 ) ) { return timeTaxis . getTimeDates ( ) ; } else if ( ( tAxis != null ) && ( tAxis . getSize ( ) > 0 ) ) { return makeTimes2D ( ) ; } return new Date [ 0 ] ; } private Date [ ] makeTimes2D  ( ) { Set < Date > dates = new HashSet <> ( ) ; try { // common case: see if it has a valid udunits unit\r String units = tAxis . getUnitsString ( ) ; if ( units != null && SimpleUnit . isDateUnit ( units ) && tAxis . getDataType ( ) . isNumeric ( ) ) { DateUnit du = new DateUnit ( units ) ; Array data = tAxis . read ( ) ; data . resetLocalIterator ( ) ; while ( data . hasNext ( ) ) { Date d = du . makeDate ( data . nextDouble ( ) ) ; dates . add ( d ) ; } } else if ( tAxis . getDataType ( ) == DataType . STRING ) { // otherwise, see if its a String or CHAR, and if we can parse the values as an ISO date\r DateFormatter formatter = new DateFormatter ( ) ; Array data = tAxis . read ( ) ; data . resetLocalIterator ( ) ; while ( data . hasNext ( ) ) { Date d = formatter . getISODate ( ( String ) data . next ( ) ) ; dates . add ( d ) ; } } else if ( tAxis . getDataType ( ) == DataType . CHAR ) { DateFormatter formatter = new DateFormatter ( ) ; ArrayChar data = ( ArrayChar ) tAxis . read ( ) ; ArrayChar . StringIterator iter = data . getStringIterator ( ) ; while ( iter . hasNext ( ) ) { Date d = formatter . getISODate ( iter . next ( ) ) ; dates . add ( d ) ; } } else { return new Date [ 0 ] ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } // sorted list\r int n = dates . size ( ) ; Date [ ] dd = dates . toArray ( new Date [ n ] ) ; List < Date > dateList = Arrays . asList ( dd ) ; Collections . sort ( dateList ) ; Date [ ] timeDates = new Date [ n ] ; int count = 0 ; for ( Date d : dateList ) timeDates [ count ++ ] = ; return timeDates ; } /* old way\r\n  private boolean makeTimes1D() {\r\n    int n = (int) timeTaxis.getSize();\r\n    timeDates = new Date[n];\r\n\r\n    // common case: see if it has a valid udunits unit\r\n    try {\r\n      DateUnit du = null;\r\n      String units = timeTaxis.getUnitsString();\r\n      if (units != null)\r\n        du = new DateUnit(units);\r\n      for (int i = 0; i < n; i++) {\r\n        Date d = du.makeDate(timeTaxis.getCoordValue(i));\r\n        timeDates[i] = d;\r\n      }\r\n      isDate = true;\r\n      return true;\r\n    } catch (Exception e) {\r\n      // ok to fall through\r\n    }\r\n\r\n    // otherwise, see if its a String, and if we can parse the values as an ISO date\r\n    if ((timeTaxis.getDataType() == DataType.STRING) || (timeTaxis.getDataType() == DataType.CHAR)) {\r\n      DateFormatter formatter = new DateFormatter();\r\n      for (int i = 0; i < n; i++) {\r\n        String coordValue = timeTaxis.getCoordName(i);\r\n        Date d = formatter.getISODate(coordValue);\r\n        if (d == null) {\r\n          isDate = false;\r\n          return false;\r\n        } else {\r\n          timeDates[i] = d;\r\n        }\r\n      }\r\n      isDate = true;\r\n      return true;\r\n    }\r\n\r\n    return false;\r\n  }  */ /**\r\n   * Get the string name for the ith time coordinate.\r\n   *\r\n   * @param index which time coordinate\r\n   * @return time name.\r\n   * @deprecated\r\n   */ public String getTimeName  ( int index ) { List < CalendarDate > cdates = getCalendarDates ( ) ; if ( ( index < 0 ) || ( index >= cdates . size ( ) ) ) throw new IllegalArgumentException ( \"getTimeName illegal index = \" + index ) ; return cdates . get ( index ) . toString ( ) ; } /**\r\n   * Get the index corresponding to the time name.\r\n   *\r\n   * @param name time name\r\n   * @return time index, or -1 if not found\r\n   * @deprecated\r\n   */ public int getTimeIndex  ( String name ) { List < CalendarDate > cdates = getCalendarDates ( ) ; for ( int i = 0 ; i < cdates . size ( ) ; i ++ ) { if ( cdates . get ( i ) . toString ( ) . equals ( name ) ) return i ; } return - 1 ; } /**\r\n   * Only works if coordsys has 1d time axis\r\n   * @deprecated use CoordinateAxis1DTime.findTimeIndexFromDate\r\n   */ public int findTimeIndexFromDate  ( java . util . Date d ) { if ( timeTaxis == null ) return - 1 ; return timeTaxis . findTimeIndexFromDate ( d ) ; } ///////////////////////////////////////////////////////////////////////\r // experimental\r static private double getMinOrMaxLon  ( double lon1 , double lon2 , boolean wantMin ) { double midpoint = ( lon1 + lon2 ) / 2 ; lon1 = LatLonPointImpl . lonNormal ( lon1 , midpoint ) ; lon2 = LatLonPointImpl . lonNormal ( lon2 , midpoint ) ; return wantMin ? Math . min ( lon1 , lon2 ) : Math . max ( lon1 , lon2 ) ; } static public LatLonRect getLatLonBoundingBox  ( Projection proj , double startx , double starty , double endx , double endy ) { if ( proj instanceof LatLonProjection ) { double deltaLat = endy - starty ; double deltaLon = endx - startx ; LatLonPoint llpt = new LatLonPointImpl ( starty , startx ) ; return new LatLonRect ( llpt , deltaLat , deltaLon ) ; } ProjectionRect bb = new ProjectionRect ( startx , starty , endx , endy ) ; // look at all 4 corners of the bounding box\r LatLonPointImpl llpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getLowerLeftPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPointImpl lrpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getLowerRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPointImpl urpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getUpperRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPointImpl ulpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getUpperLeftPoint ( ) , new LatLonPointImpl ( ) ) ; // Check if grid contains poles. LOOK disabled\r boolean includesNorthPole = false ; /* int[] resultNP = new int[2];\r\n    resultNP = findXYindexFromLatLon(90.0, 0, null);\r\n    if (resultNP[0] != -1 && resultNP[1] != -1)\r\n      includesNorthPole = true;  */ boolean includesSouthPole = false ; /* int[] resultSP = new int[2];\r\n    resultSP = findXYindexFromLatLon(-90.0, 0, null);\r\n    if (resultSP[0] != -1 && resultSP[1] != -1)\r\n      includesSouthPole = true;  */ LatLonRect llbb ; if ( includesNorthPole && ! includesSouthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( 90.0 , 0.0 ) ) ; // ??? lon=???\r llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; } else if ( includesSouthPole && ! includesNorthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( - 90.0 , - 180.0 ) ) ; // ??? lon=???\r llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; } else { double latMin = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; double latMax = Math . max ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; // longitude is a bit tricky as usual\r double lonMin = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; double lonMax = getMinOrMaxLon ( lrpt . getLongitude ( ) , urpt . getLongitude ( ) , false ) ; llpt . set ( latMin , lonMin ) ; urpt . set ( latMax , lonMax ) ; llbb = new LatLonRect ( llpt , urpt ) ; } return llbb ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return slider indicator position for currently selected item [CODESPLIT] protected int getItemPos ( ) { if ( nitems < 1 ) return - arrow_size ; // dont show indicator\r else if ( nitems == 1 ) return b . width / 2 ; // indicator in center\r int item = table . getSelectedRowIndex ( ) ; // selected item\r int eff_width = b . width - 2 * arrow_size ; // effective width\r int pixel = ( item * eff_width ) / ( nitems - 1 ) ; // divided into n-1 intervals\r return pixel + arrow_size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return item selected by this pixel position [CODESPLIT] protected int getItem ( int pixel ) { if ( nitems < 2 ) return 0 ; int eff_width = b . width - 2 * arrow_size ; // effective width\r double fitem = ( ( double ) ( pixel - arrow_size ) * ( nitems - 1 ) ) / eff_width ; int item = ( int ) ( fitem + .5 ) ; item = Math . max ( Math . min ( item , nitems - 1 ) , 0 ) ; return item ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create standard name = topCollectionName + last directory [CODESPLIT] public static String makeCollectionName ( String topCollectionName , Path dir ) { int last = dir . getNameCount ( ) - 1 ; Path lastDir = dir . getName ( last ) ; String lastDirName = lastDir . toString ( ) ; return topCollectionName + \"-\" + lastDirName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create standard name = topCollectionName + last directory [CODESPLIT] public static Path makeCollectionIndexPath ( String topCollectionName , Path dir , String suffix ) { String collectionName = makeCollectionName ( topCollectionName , dir ) ; return Paths . get ( dir . toString ( ) , collectionName + suffix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this idiom keeps the iterator from escaping so that we can use try - with - resource and ensure DirectoryStream closes . like ++ [CODESPLIT] public void iterateOverMFileCollection ( Visitor visit ) throws IOException { if ( debug ) System . out . printf ( \" iterateOverMFileCollection %s \" , collectionDir ) ; int count = 0 ; try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( collectionDir , new MyStreamFilter ( ) ) ) { for ( Path p : ds ) { try { BasicFileAttributes attr = Files . readAttributes ( p , BasicFileAttributes . class ) ; if ( ! attr . isDirectory ( ) ) visit . consume ( new MFileOS7 ( p ) ) ; if ( debug ) System . out . printf ( \"%d \" , count ++ ) ; } catch ( IOException ioe ) { // catch error and skip file logger . error ( \"Failed to read attributes from file found in Files.newDirectoryStream \" , ioe ) ; } } } if ( debug ) System . out . printf ( \"%d%n\" , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy remote files to localDir [CODESPLIT] public void getRemoteFiles ( final CancelTask _cancel ) { this . cancel = _cancel ; String urls = config . getServerPrefix ( ) + \"/thredds/admin/log/\" + type + \"/\" ; ta . append ( String . format ( \"Download URL = %s%n\" , urls ) ) ; String contents = null ; try ( HTTPMethod method = HTTPFactory . Get ( session , urls ) ) { int statusCode = method . execute ( ) ; if ( statusCode == 200 ) contents = method . getResponseAsString ( ) ; if ( ( contents == null ) || ( contents . length ( ) == 0 ) ) { ta . append ( String . format ( \"Failed to get logs at URL = %s%n%n\" , urls ) ) ; return ; } else { ta . append ( String . format ( \"Logs at URL = %s%n%s%n\" , urls , contents ) ) ; } } catch ( Throwable t ) { ta . append ( String . format ( \"Failed to get logs at URL = %s error = %s%n%n\" , urls , t . getMessage ( ) ) ) ; t . printStackTrace ( ) ; return ; } // update text area in background  http://technobuz.com/2009/05/update-jtextarea-dynamically/\r final String list = contents ; SwingWorker worker = new SwingWorker < String , Void > ( ) { @ Override protected String doInBackground ( ) throws Exception { try { ta . append ( String . format ( \"Local log files stored in = %s%n%n\" , localDir ) ) ; String [ ] lines = list . split ( \"\\n\" ) ; for ( String line : lines ) { new RemoteLog ( line . trim ( ) ) ; if ( cancel . isCancel ( ) ) { break ; } } } catch ( Throwable t ) { t . printStackTrace ( ) ; } return null ; } public void done ( ) { if ( cancel . isCancel ( ) ) ta . append ( String . format ( \"Download was cancelled for %s%n\" , type ) ) ; else ta . append ( String . format ( \"Download complete for %s%n\" , type ) ) ; } } ; // do in background\r worker . execute ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PointFeatureIterator . hasNext () doesn t guarantee idempotency but we do . [CODESPLIT] @ Override public boolean hasNext ( ) { if ( pointFeature != null ) { return true ; // pointFeature hasn't yet been consumed. } pointFeature = nextFilteredDataPoint ( ) ; if ( pointFeature == null ) { close ( ) ; return false ; } else { return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "but we can define a stronger contract . [CODESPLIT] @ Override public PointFeature next ( ) throws NoSuchElementException { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( \"This iterator has no more elements.\" ) ; } assert pointFeature != null ; PointFeature ret = pointFeature ; calcBounds ( ret ) ; pointFeature = null ; // Feature has been consumed. return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next point that satisfies the filter or { @code null } if no such point exists . [CODESPLIT] private PointFeature nextFilteredDataPoint ( ) { while ( origIter . hasNext ( ) ) { PointFeature pointFeat = origIter . next ( ) ; if ( filter . filter ( pointFeat ) ) { return pointFeat ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK maybe combine grib1 grib2 and bufr ?? [CODESPLIT] @ Override public String getSubCenterName ( int center , int subcenter ) { switch ( subcenter ) { case 0 : return null ; case 1 : return \"FSL/FRD Regional Analysis and Prediction Branch\" ; case 2 : return \"FSL/FRD Local Analysis and Prediction Branch\" ; } return super . getSubCenterName ( center , subcenter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a period string into a CalendarPeriod . Field . [CODESPLIT] public static CalendarPeriod . Field fromUnitString ( String udunit ) { udunit = udunit . trim ( ) ; udunit = udunit . toLowerCase ( ) ; if ( udunit . equals ( \"s\" ) ) return Field . Second ; if ( udunit . equals ( \"ms\" ) ) return Field . Millisec ; // eliminate plurals\r if ( udunit . endsWith ( \"s\" ) ) udunit = udunit . substring ( 0 , udunit . length ( ) - 1 ) ; switch ( udunit ) { case \"second\" : case \"sec\" : return Field . Second ; case \"millisecond\" : case \"millisec\" : case \"msec\" : return Field . Millisec ; case \"minute\" : case \"min\" : return Field . Minute ; case \"hour\" : case \"hr\" : case \"h\" : return Field . Hour ; case \"day\" : case \"d\" : return Field . Day ; case \"month\" : case \"mon\" : return Field . Month ; case \"year\" : case \"yr\" : return Field . Year ; default : throw new IllegalArgumentException ( \"cant convert \" + udunit + \" to CalendarPeriod\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "minimize memory use by interning . wacko shit in GribPartitionBuilder TimeCoordinate whoduhthunk? [CODESPLIT] public static CalendarPeriod of ( int value , Field field ) { CalendarPeriod want = new CalendarPeriod ( value , field ) ; if ( cache == null ) return want ; CalendarPeriod got = cache . getIfPresent ( want ) ; if ( got != null ) return got ; cache . put ( want , want ) ; return want ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a udunit period string into a CalendarPeriod [CODESPLIT] public static CalendarPeriod of ( String udunit ) { int value ; String units ; String [ ] split = StringUtil2 . splitString ( udunit ) ; if ( split . length == 1 ) { value = 1 ; units = split [ 0 ] ; } else if ( split . length == 2 ) { try { value = Integer . parseInt ( split [ 0 ] ) ; } catch ( Throwable t ) { return null ; } units = split [ 1 ] ; } else return null ; CalendarPeriod . Field unit = CalendarPeriod . fromUnitString ( units ) ; return CalendarPeriod . of ( value , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtract two dates return difference in units of this period . If not even will round down and log a warning [CODESPLIT] public int subtract ( CalendarDate start , CalendarDate end ) { long diff = end . getDifferenceInMsecs ( start ) ; int thislen = millisecs ( ) ; if ( ( diff % thislen != 0 ) ) log . warn ( \"roundoff error\" ) ; return ( int ) ( diff / thislen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the conversion factor of the other CalendarPeriod to this one [CODESPLIT] public double getConvertFactor ( CalendarPeriod from ) { if ( field == CalendarPeriod . Field . Month || field == CalendarPeriod . Field . Year ) { log . warn ( \" CalendarDate.convert on Month or Year\" ) ; } return ( double ) from . millisecs ( ) / millisecs ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the duration in milliseconds - + [CODESPLIT] public double getValueInMillisecs ( ) { if ( field == CalendarPeriod . Field . Month ) return 30.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value ; else if ( field == CalendarPeriod . Field . Year ) return 365.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value ; else return millisecs ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "start + offset = end [CODESPLIT] public int getOffset ( CalendarDate start , CalendarDate end ) { if ( start . equals ( end ) ) return 0 ; long start_millis = start . getDateTime ( ) . getMillis ( ) ; long end_millis = end . getDateTime ( ) . getMillis ( ) ; // 5 second slop\r Period p ; if ( start_millis < end_millis ) p = new Period ( start_millis , end_millis + 5000 , getPeriodType ( ) ) ; else p = new Period ( start_millis + 5000 , end_millis , getPeriodType ( ) ) ; return p . get ( getDurationFieldType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this a valid file? [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { try { gemreader = new GempakGridReader ( raf . getLocation ( ) ) ; return gemreader . init ( raf , false ) ; } catch ( Exception ioe ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the service provider for reading . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; // debugProj = true; long start = System . currentTimeMillis ( ) ; if ( gemreader == null ) { gemreader = new GempakGridReader ( raf . getLocation ( ) ) ; } initTables ( ) ; gemreader . init ( raf , true ) ; GridIndex index = gemreader . getGridIndex ( ) ; open ( index , cancelTask ) ; if ( debugOpen ) { System . out . println ( \" GridServiceProvider.open \" + ncfile . getLocation ( ) + \" took \" + ( System . currentTimeMillis ( ) - start ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open the index and create the netCDF file from that [CODESPLIT] protected void open ( GridIndex index , CancelTask cancelTask ) throws IOException { GempakLookup lookup = new GempakLookup ( ( GempakGridRecord ) index . getGridRecords ( ) . get ( 0 ) ) ; GridIndexToNC delegate = new GridIndexToNC ( index . filename ) ; //delegate.setUseDescriptionForVariableName(false); delegate . open ( index , lookup , 4 , ncfile , cancelTask ) ; ncfile . finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sync the file [CODESPLIT] public boolean sync ( ) throws IOException { if ( ( gemreader . getInitFileSize ( ) < raf . length ( ) ) && extendIndex ) { gemreader . init ( true ) ; GridIndex index = gemreader . getGridIndex ( ) ; // reconstruct the ncfile objects ncfile . empty ( ) ; open ( index , null ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the parameter tables . [CODESPLIT] private void initTables ( ) { try { GempakGridParameterTable . addParameters ( \"resources/nj22/tables/gempak/wmogrib3.tbl\" ) ; GempakGridParameterTable . addParameters ( \"resources/nj22/tables/gempak/ncepgrib2.tbl\" ) ; } catch ( Exception e ) { System . out . println ( \"unable to init tables\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a dataRootExt to in - memory tree . [CODESPLIT] private boolean put ( DataRootExt dateRootExt ) { map . put ( dateRootExt . getPath ( ) , dateRootExt ) ; return treeSet . add ( dateRootExt . getPath ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the longest path match . [CODESPLIT] public String findLongestPathMatch ( String reqPath ) { SortedSet < String > tail = treeSet . tailSet ( reqPath ) ; if ( tail . isEmpty ( ) ) return null ; String after = tail . first ( ) ; if ( reqPath . startsWith ( after ) ) // common case return tail . first ( ) ; // have to check more, until no common starting chars for ( String key : tail ) { if ( reqPath . startsWith ( key ) ) return key ; // terminate when there's no match at all. if ( StringUtil2 . match ( reqPath , key ) == 0 ) break ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the longest DataRoot match . [CODESPLIT] public DataRoot findDataRoot ( String reqPath ) { String path = findLongestPathMatch ( reqPath ) ; if ( path == null ) return null ; DataRootExt dataRootExt = map . get ( path ) ; if ( dataRootExt == null ) { logger . error ( \"DataRootPathMatcher found path {} but not in map\" , path ) ; return null ; } return convert2DataRoot ( dataRootExt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert a dataRootExt to a dataRoot [CODESPLIT] public @ Nonnull DataRoot convert2DataRoot ( DataRootExt dataRootExt ) { DataRoot dataRoot = dataRootExt . getDataRoot ( ) ; if ( dataRoot != null ) return dataRoot ; // otherwise must read the catalog that its in dataRoot = readDataRootFromCatalog ( dataRootExt ) ; dataRootExt . setDataRoot ( dataRoot ) ; return dataRoot ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds datasetScan datasetFmrc Look for duplicate Ids ( give message ) . Dont follow catRefs . [CODESPLIT] public void extractDataRoots ( String catalogRelPath , List < Dataset > dsList , boolean checkDups , Map < String , String > idMap ) { for ( Dataset dataset : dsList ) { if ( dataset instanceof DatasetScan ) { DatasetScan ds = ( DatasetScan ) dataset ; addRoot ( ds , catalogRelPath , checkDups ) ; } else if ( dataset instanceof FeatureCollectionRef ) { FeatureCollectionRef fc = ( FeatureCollectionRef ) dataset ; addRoot ( fc , catalogRelPath , checkDups ) ; if ( idMap != null ) { String catWithSameFc = idMap . get ( fc . getCollectionName ( ) ) ; if ( catWithSameFc != null ) logCatalogInit . warn ( \"*** ERROR: Duplicate featureCollection name {} in catalogs '{}' and '{}'\" , fc . getCollectionName ( ) , catalogRelPath , catWithSameFc ) ; else idMap . put ( fc . getCollectionName ( ) , catalogRelPath ) ; } } else if ( dataset instanceof CatalogScan ) { CatalogScan catScan = ( CatalogScan ) dataset ; addRoot ( catScan , catalogRelPath , checkDups ) ; } if ( ! ( dataset instanceof CatalogRef ) ) { // recurse extractDataRoots ( catalogRelPath , dataset . getDatasetsLocal ( ) , checkDups , idMap ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return requested CalendarDateRange . [CODESPLIT] public CalendarDateRange getCalendarDateRange ( Calendar cal ) { if ( dateRange == null ) return null ; if ( cal . equals ( Calendar . getDefault ( ) ) ) return dateRange ; // otherwise must reparse return makeCalendarDateRange ( cal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "redo the variables against the shared coordinates [CODESPLIT] public List < Integer > reindex ( List < Coordinate > coords ) { List < Integer > result = new ArrayList <> ( ) ; for ( Coordinate coord : coords ) { Coordinate sub = swap . get ( coord ) ; Coordinate use = ( sub == null ) ? coord : sub ; Integer idx = indexMap . get ( use ) ; // index into unionCoords if ( idx == null ) { throw new IllegalStateException ( ) ; } result . add ( idx ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open an existing Netcdf file for writing data . Fill mode is true . Cannot add new objects you can only read / write data to existing Variables . [CODESPLIT] static public NetcdfFileWriter openExisting ( String location ) throws IOException { return new NetcdfFileWriter ( null , location , true , null ) ; // dont know the version yet\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Netcdf file with fill mode true . [CODESPLIT] static public NetcdfFileWriter createNew ( Version version , String location , Nc4Chunking chunker ) throws IOException { return new NetcdfFileWriter ( version , location , false , chunker ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// use these calls in define mode [CODESPLIT] public Dimension addDimension ( String dimName , int length ) { return addDimension ( null , dimName , length , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a shared Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( Group g , String dimName , int length ) { return addDimension ( g , dimName , length , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a shared Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( Group g , String dimName , int length , boolean isUnlimited , boolean isVariableLength ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! isValidObjectName ( dimName ) ) throw new IllegalArgumentException ( \"illegal dimension name \" + dimName ) ; Dimension dim = new Dimension ( dimName , length , true , isUnlimited , isVariableLength ) ; ncfile . addDimension ( g , dim ) ; return dim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a Dimension . Must be in define mode . [CODESPLIT] public Dimension renameDimension ( Group g , String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! isValidObjectName ( newName ) ) throw new IllegalArgumentException ( \"illegal dimension name \" + newName ) ; if ( g == null ) g = ncfile . getRootGroup ( ) ; Dimension dim = g . findDimension ( oldName ) ; if ( null != dim ) dim . setName ( newName ) ; return dim ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Group to the file . Must be in define mode . If pass in null as the parent then the root group is returned and the name is ignored . This is how you get the root group . Note this is different from other uses of parent group . [CODESPLIT] public Group addGroup ( Group parent , String name ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( parent == null ) return ncfile . getRootGroup ( ) ; Group result = new Group ( ncfile , parent , name ) ; parent . addGroup ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Global attribute to the file . Must be in define mode . [CODESPLIT] public Attribute addGroupAttribute ( Group g , Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! isValidObjectName ( att . getShortName ( ) ) ) { String attName = createValidObjectName ( att . getShortName ( ) ) ; log . warn ( \"illegal attribute name= \" + att . getShortName ( ) + \" change to \" + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } return ncfile . addAttribute ( g , att ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a EnumTypedef to the file . Must be in define mode . [CODESPLIT] public EnumTypedef addTypedef ( Group g , EnumTypedef td ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! version . isExtendedModel ( ) ) throw new IllegalArgumentException ( \"Enum type only supported in extended model, this version is=\" + version ) ; g . addEnumeration ( td ) ; return td ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a group Attribute . Must be in define mode . [CODESPLIT] public Attribute deleteGroupAttribute ( Group g , String attName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( g == null ) g = ncfile . getRootGroup ( ) ; Attribute att = g . findAttribute ( attName ) ; if ( null == att ) return null ; g . remove ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a group Attribute . Must be in define mode . [CODESPLIT] public Attribute renameGroupAttribute ( Group g , String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! isValidObjectName ( newName ) ) { String newnewName = createValidObjectName ( newName ) ; log . warn ( \"illegal attribute name= \" + newName + \" change to \" + newnewName ) ; newName = newnewName ; } if ( g == null ) g = ncfile . getRootGroup ( ) ; Attribute att = g . findAttribute ( oldName ) ; if ( null == att ) return null ; g . remove ( att ) ; att = new Attribute ( newName , att . getValues ( ) ) ; g . addAttribute ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( Group g , String shortName , DataType dataType , String dimString ) { Group parent = ( g == null ) ? ncfile . getRootGroup ( ) : g ; return addVariable ( g , null , shortName , dataType , Dimension . makeDimensionsList ( parent , dimString ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( Group g , String shortName , DataType dataType , List < Dimension > dims ) { if ( g == null ) g = ncfile . getRootGroup ( ) ; Variable oldVar = g . findVariable ( shortName ) ; if ( oldVar != null ) return null ; return addVariable ( g , null , shortName , dataType , dims ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( Group g , Structure parent , String shortName , DataType dataType , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; DataType writeType = version . isExtendedModel ( ) ? dataType : dataType . withSignedness ( DataType . Signedness . SIGNED ) ; // use signed type for netcdf3\r boolean usingSignForUnsign = writeType != dataType ; if ( ! isValidDataType ( writeType ) ) throw new IllegalArgumentException ( \"illegal dataType: \" + dataType + \" not supported in netcdf-3\" ) ; // check unlimited if classic model\r if ( ! version . isExtendedModel ( ) ) { for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { Dimension d = dims . get ( i ) ; if ( d . isUnlimited ( ) && ( i != 0 ) ) throw new IllegalArgumentException ( \"Unlimited dimension \" + d . getShortName ( ) + \" must be first (outermost) in netcdf-3 \" ) ; } } shortName = makeValidObjectName ( shortName ) ; Variable v ; if ( dataType == DataType . STRUCTURE ) { v = new Structure ( ncfile , g , parent , shortName ) ; } else { v = new Variable ( ncfile , g , parent , shortName ) ; } v . setDataType ( writeType ) ; v . setDimensions ( dims ) ; if ( usingSignForUnsign ) v . addAttribute ( new Attribute ( CDM . UNSIGNED , \"true\" ) ) ; long size = v . getSize ( ) * v . getElementSize ( ) ; if ( version == Version . netcdf3 && size > N3iosp . MAX_VARSIZE ) throw new IllegalArgumentException ( \"Variable size in bytes \" + size + \" may not exceed \" + N3iosp . MAX_VARSIZE ) ; //System.out.printf(\"Variable size in bytes \" + size + \" may not exceed \" + N3iosp.MAX_VARSIZE);\r ncfile . addVariable ( g , v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a copy of the specified structure to the file ( netcdf4 only ) . DO NOT USE YET [CODESPLIT] public Structure addCopyOfStructure ( Group g , @ Nonnull Structure original , String shortName , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( original == null ) throw new NullPointerException ( \"Original structure must be non-null\" ) ; shortName = makeValidObjectName ( shortName ) ; if ( ! version . isExtendedModel ( ) ) throw new IllegalArgumentException ( \"Structure type only supported in extended model, version=\" + version ) ; Structure s = new Structure ( ncfile , g , null , shortName ) ; s . setDimensions ( dims ) ; for ( Variable m : original . getVariables ( ) ) { // LOOK no nested structs\r Variable nest = new Variable ( ncfile , g , s , m . getShortName ( ) ) ; nest . setDataType ( m . getDataType ( ) ) ; nest . setDimensions ( m . getDimensions ( ) ) ; nest . addAll ( m . getAttributes ( ) ) ; s . addMemberVariable ( nest ) ; } ncfile . addVariable ( g , s ) ; return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable with DataType = String to a netCDF - 3 file . Must be in define mode . The variable will be stored in the file as a CHAR variable . A new dimension with name stringVar . getShortName () _strlen is automatically added with length max_strlen as determined from the data contained in the stringVar . [CODESPLIT] public Variable addStringVariable ( Group g , Variable stringVar , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( stringVar . getShortName ( ) ) ) throw new IllegalArgumentException ( \"illegal netCDF-3 variable name: \" + stringVar . getShortName ( ) ) ; // convert STRING to CHAR\r int max_strlen = 0 ; Array data ; try { data = stringVar . read ( ) ; IndexIterator ii = data . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) { String s = ( String ) ii . getObjectNext ( ) ; max_strlen = Math . max ( max_strlen , s . length ( ) ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; String err = \"No data found for Variable \" + stringVar . getShortName ( ) + \". Cannot determine the lentgh of the new CHAR variable.\" ; log . error ( err ) ; System . out . println ( err ) ; } return addStringVariable ( g , stringVar . getShortName ( ) , dims , max_strlen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a variable with DataType = String to the file . Must be in define mode . The variable will be stored in the file as a CHAR variable . A new dimension with name varName_strlen is automatically added with length max_strlen . [CODESPLIT] public Variable addStringVariable ( Group g , String shortName , List < Dimension > dims , int max_strlen ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; shortName = makeValidObjectName ( shortName ) ; Variable v = new Variable ( ncfile , g , null , shortName ) ; v . setDataType ( DataType . CHAR ) ; Dimension d = addDimension ( g , shortName + \"_strlen\" , max_strlen ) ; List < Dimension > sdims = new ArrayList <> ( dims ) ; sdims . add ( d ) ; v . setDimensions ( sdims ) ; ncfile . addVariable ( g , v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename a Variable . Must be in define mode . [CODESPLIT] public Variable renameVariable ( String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; Variable v = ncfile . findVariable ( oldName ) ; if ( null != v ) { String fullOldNameEscaped = v . getFullNameEscaped ( ) ; v . setName ( newName ) ; varRenameMap . put ( v . getFullNameEscaped ( ) , fullOldNameEscaped ) ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an attribute to the named Variable . Must be in define mode . [CODESPLIT] public boolean addVariableAttribute ( Variable v , Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! isValidObjectName ( att . getShortName ( ) ) ) { String attName = createValidObjectName ( att . getShortName ( ) ) ; log . warn ( \"illegal netCDF-3 attribute name= \" + att . getShortName ( ) + \" change to \" + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } v . addAttribute ( att ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After you have added all of the Dimensions Variables and Attributes call create () to actually create the file . You must be in define mode . After this call you are no longer in define mode . [CODESPLIT] public void create ( ) throws java . io . IOException { if ( ! defineMode ) throw new UnsupportedOperationException ( \"not in define mode\" ) ; if ( ! isNewFile ) throw new UnsupportedOperationException ( \"can only call create on a new file\" ) ; ncfile . finish ( ) ; // ??\r spiw . setFill ( fill ) ; // ??\r spiw . create ( location , ncfile , extraHeader , preallocateSize , isLargeFile ) ; defineMode = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the redefine mode . Designed to emulate nc_redef ( redefineMode = true ) and nc_enddef ( redefineMode = false ) [CODESPLIT] public boolean setRedefineMode ( boolean redefineMode ) throws IOException { if ( redefineMode && ! defineMode ) { defineMode = true ; } else if ( ! redefineMode && defineMode ) { defineMode = false ; ncfile . finish ( ) ; // try to rewrite header, if it fails, then we have to rewrite entire file\r boolean ok = spiw . rewriteHeader ( isLargeFile ) ; // LOOK seems like we should be using isNewFile\r if ( ! ok ) rewrite ( ) ; return ! ok ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rewrite entire file [CODESPLIT] private void rewrite ( ) throws IOException { // close existing file, rename and open as read-only\r spiw . flush ( ) ; spiw . close ( ) ; File prevFile = new File ( location ) ; if ( ! prevFile . exists ( ) ) { return ; } File tmpFile = new File ( location + \".tmp\" ) ; if ( tmpFile . exists ( ) ) { boolean ok = tmpFile . delete ( ) ; if ( ! ok ) log . warn ( \"rewrite unable to delete {}\" , tmpFile . getPath ( ) ) ; } if ( ! prevFile . renameTo ( tmpFile ) ) { System . out . println ( prevFile . getPath ( ) + \" prevFile.exists \" + prevFile . exists ( ) + \" canRead = \" + prevFile . canRead ( ) ) ; System . out . println ( tmpFile . getPath ( ) + \" tmpFile.exists \" + tmpFile . exists ( ) + \" canWrite \" + tmpFile . canWrite ( ) ) ; throw new RuntimeException ( \"Cant rename \" + prevFile . getAbsolutePath ( ) + \" to \" + tmpFile . getAbsolutePath ( ) ) ; } NetcdfFile oldFile = NetcdfFile . open ( tmpFile . getPath ( ) ) ; /* use record dimension if it has one\r\n    Structure recordVar = null;\r\n    if (oldFile.hasUnlimitedDimension()) {\r\n      oldFile.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);\r\n      recordVar = (Structure) oldFile.findVariable(\"record\");\r\n      /* if (recordVar != null) {\r\n        Boolean result = (Boolean) spiw.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);\r\n        if (!result)\r\n          recordVar = null;\r\n      }\r\n      } */ // create new file with current set of objects\r spiw . create ( location , ncfile , extraHeader , preallocateSize , isLargeFile ) ; spiw . setFill ( fill ) ; //isClosed = false;\r /* wait till header is written before adding the record variable to the file\r\n    if (recordVar != null) {\r\n      Boolean result = (Boolean) spiw.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);\r\n      if (!result)\r\n        recordVar = null;\r\n    } */ FileWriter2 fileWriter2 = new FileWriter2 ( this ) ; for ( Variable v : ncfile . getVariables ( ) ) { String oldVarName = v . getFullName ( ) ; Variable oldVar = oldFile . findVariable ( oldVarName ) ; if ( oldVar != null ) { fileWriter2 . copyAll ( oldVar , v ) ; } else if ( varRenameMap . containsKey ( oldVarName ) ) { // var name has changed in ncfile - use the varRenameMap to find\r //  the correct variable name to request from oldFile\r String realOldVarName = varRenameMap . get ( oldVarName ) ; oldVar = oldFile . findVariable ( realOldVarName ) ; if ( oldVar != null ) { fileWriter2 . copyAll ( oldVar , v ) ; } } else { String message = \"Cannot find variable \" + oldVarName + \" to copy to new file.\" ; log . warn ( message ) ; System . out . println ( message ) ; } } // delete old\r oldFile . close ( ) ; if ( ! tmpFile . delete ( ) ) throw new RuntimeException ( \"Cant delete \" + tmpFile . getAbsolutePath ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For netcdf3 only take all unlimited variables and make them into a structure . [CODESPLIT] public Structure addRecordStructure ( ) { if ( version != Version . netcdf3 ) return null ; boolean ok = ( Boolean ) ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ! ok ) throw new IllegalStateException ( \"can't add record variable\" ) ; return ( Structure ) ncfile . findVariable ( \"record\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "// use these calls to write data to the file [CODESPLIT] public void write ( String varname , Array values ) throws java . io . IOException , InvalidRangeException { write ( findVariable ( varname ) , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write data to the named variable origin assumed to be 0 . Must not be in define mode . [CODESPLIT] public void write ( Variable v , Array values ) throws java . io . IOException , InvalidRangeException { if ( ncfile != v . getNetcdfFile ( ) ) throw new IllegalArgumentException ( \"Variable is not owned by this writer.\" ) ; write ( v , new int [ values . getRank ( ) ] , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write data to the named variable . Must not be in define mode . [CODESPLIT] public void write ( Variable v , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { if ( defineMode ) throw new UnsupportedOperationException ( \"in define mode\" ) ; spiw . writeData ( v , new Section ( origin , values . getShape ( ) ) , values ) ; v . invalidateCache ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write String data to a CHAR variable origin assumed to be 0 . Must not be in define mode . [CODESPLIT] public void writeStringData ( Variable v , Array values ) throws java . io . IOException , InvalidRangeException { writeStringData ( v , new int [ values . getRank ( ) ] , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write String data to a CHAR variable . Must not be in define mode . [CODESPLIT] public void writeStringData ( Variable v , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { if ( values . getElementType ( ) != String . class ) throw new IllegalArgumentException ( \"Must be ArrayObject of String \" ) ; if ( v . getDataType ( ) != DataType . CHAR ) throw new IllegalArgumentException ( \"variable \" + v . getFullName ( ) + \" is not type CHAR\" ) ; int rank = v . getRank ( ) ; int strlen = v . getShape ( rank - 1 ) ; // turn it into an ArrayChar\r ArrayChar cvalues = ArrayChar . makeFromStringArray ( ( ArrayObject ) values , strlen ) ; int [ ] corigin = new int [ rank ] ; System . arraycopy ( origin , 0 , corigin , 0 , rank - 1 ) ; write ( v , corigin , cvalues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "close the file . [CODESPLIT] public synchronized void close ( ) throws java . io . IOException { if ( spiw != null ) { setRedefineMode ( false ) ; flush ( ) ; spiw . close ( ) ; spiw = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Abort writing to this file . The file is closed . [CODESPLIT] public void abort ( ) throws java . io . IOException { if ( spiw != null ) { spiw . close ( ) ; spiw = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write XML using the bean properties of the contained object [CODESPLIT] public void writeProperties ( PrintWriter out ) throws IOException { if ( p == null ) p = BeanParser . getParser ( o . getClass ( ) ) ; p . writeProperties ( o , out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extract info from underlying feature dataset [CODESPLIT] public ThreddsMetadata extract ( Dataset threddsDataset ) throws IOException { ThreddsMetadata metadata = new ThreddsMetadata ( ) ; Map < String , Object > flds = metadata . getFlds ( ) ; try ( DataFactory . Result result = new DataFactory ( ) . openFeatureDataset ( threddsDataset , null ) ) { if ( result . fatalError ) { logger . warn ( \" openFeatureDataset failed, errs=%s%n\" , result . errLog ) ; return null ; } if ( result . featureType . isCoverageFeatureType ( ) ) { GridDataset gridDataset = ( GridDataset ) result . featureDataset ; // LOOK wrong flds . put ( Dataset . GeospatialCoverage , extractGeospatial ( gridDataset ) ) ; CalendarDateRange tc = extractCalendarDateRange ( gridDataset ) ; if ( tc != null ) flds . put ( Dataset . TimeCoverage , tc ) ; ThreddsMetadata . VariableGroup vars = extractVariables ( threddsDataset . getDataFormatName ( ) , gridDataset ) ; if ( vars != null ) flds . put ( Dataset . VariableGroups , vars ) ; } else if ( result . featureType . isPointFeatureType ( ) ) { PointDatasetImpl pobsDataset = ( PointDatasetImpl ) result . featureDataset ; LatLonRect llbb = pobsDataset . getBoundingBox ( ) ; if ( null != llbb ) flds . put ( Dataset . GeospatialCoverage , new ThreddsMetadata . GeospatialCoverage ( llbb , null , 0.0 , 0.0 ) ) ; CalendarDateRange tc = extractCalendarDateRange ( pobsDataset ) ; if ( tc != null ) flds . put ( Dataset . TimeCoverage , tc ) ; ThreddsMetadata . VariableGroup vars = extractVariables ( pobsDataset ) ; if ( vars != null ) flds . put ( Dataset . VariableGroups , vars ) ; } } catch ( IOException ioe ) { logger . error ( \"Error opening dataset \" + threddsDataset . getName ( ) , ioe ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////// [CODESPLIT] public ThreddsMetadata . GeospatialCoverage extractGeospatial ( FeatureDatasetPoint fd ) { LatLonRect llbb = fd . getBoundingBox ( ) ; if ( llbb != null ) { return new ThreddsMetadata . GeospatialCoverage ( llbb , null , 0.0 , 0.0 ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////// [CODESPLIT] public CalendarDateRange extractCalendarDateRange ( GridDataset gridDataset ) { CalendarDateRange maxDateRange = null ; for ( GridDataset . Gridset gridset : gridDataset . getGridsets ( ) ) { GridCoordSystem gsys = gridset . getGeoCoordSystem ( ) ; CalendarDateRange dateRange ; CoordinateAxis1DTime time1D = gsys . getTimeAxis1D ( ) ; if ( time1D != null ) { dateRange = time1D . getCalendarDateRange ( ) ; } else { CoordinateAxis time = gsys . getTimeAxis ( ) ; if ( time == null ) continue ; try { CalendarDateUnit du = CalendarDateUnit . of ( null , time . getUnitsString ( ) ) ; // LOOK no calendar CalendarDate minDate = du . makeCalendarDate ( time . getMinValue ( ) ) ; CalendarDate maxDate = du . makeCalendarDate ( time . getMaxValue ( ) ) ; dateRange = CalendarDateRange . of ( minDate , maxDate ) ; } catch ( Exception e ) { logger . warn ( \"Illegal Date Unit \" + time . getUnitsString ( ) ) ; continue ; } } if ( maxDateRange == null ) maxDateRange = dateRange ; else maxDateRange = maxDateRange . extend ( dateRange ) ; } return maxDateRange ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look for possible matches of old ( 4 . 2 ) grib names in new ( 4 . 3 ) dataset . [CODESPLIT] List < String > matchNcepNames ( GridDataset gds , String oldName ) { List < String > result = new ArrayList <> ( ) ; // look for exact match\r if ( contains ( gds , oldName ) ) { result . add ( oldName ) ; return result ; } Attribute att = gds . findGlobalAttributeIgnoreCase ( CDM . FILE_FORMAT ) ; boolean isGrib1 = ( att != null ) && att . getStringValue ( ) . startsWith ( \"GRIB-1\" ) ; boolean isGrib2 = ( att != null ) && att . getStringValue ( ) . startsWith ( \"GRIB-2\" ) ; HashMap < String , Renamer > map ; if ( isGrib1 ) { if ( map1 == null ) initMap1 ( ) ; map = map1 ; } else if ( isGrib2 ) { if ( map2 == null ) initMap2 ( ) ; map = map2 ; } else { return result ; // empty list\r } // look in our renamer map\r Renamer mbean = map . get ( oldName ) ; if ( mbean != null && mbean . newName != null && contains ( gds , mbean . newName ) ) { result . add ( mbean . newName ) ; // if its unique, then we are done\r return result ; } // not unique - match against NCEP dataset\r if ( mbean != null ) { String dataset = extractDatasetFromLocation ( gds . getLocation ( ) ) ; for ( VariableRenamerBean r : mbean . newVars ) { if ( r . getDatasetType ( ) . equals ( dataset ) && contains ( gds , r . newName ) ) result . add ( r . newName ) ; } if ( result . size ( ) == 1 ) return result ; // return if unique\r } // not unique, no unique match against dataset - check existence in the dataset\r result . clear ( ) ; if ( mbean != null ) { for ( VariableRenamerBean r : mbean . newVarsMap . values ( ) ) { if ( contains ( gds , r . newName ) ) result . add ( r . newName ) ; } if ( result . size ( ) > 0 ) return result ; } // try to map oldName -> new prefix\r result . clear ( ) ; String oldMunged = munge ( oldName ) ; for ( GridDatatype grid : gds . getGrids ( ) ) { String newMunged = munge ( grid . getShortName ( ) ) ; if ( newMunged . startsWith ( oldMunged ) ) result . add ( grid . getShortName ( ) ) ; } if ( result . size ( ) > 0 ) return result ; // return empty list\r return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////// [CODESPLIT] private HashMap < String , Renamer > makeMapBeans ( List < VariableRenamerBean > vbeans ) { HashMap < String , Renamer > map = new HashMap <> ( 3000 ) ; for ( VariableRenamerBean vbean : vbeans ) { // construct the old -> new mapping\r Renamer mbean = map . get ( vbean . getOldName ( ) ) ; if ( mbean == null ) { mbean = new Renamer ( vbean . getOldName ( ) ) ; map . put ( vbean . getOldName ( ) , mbean ) ; } mbean . add ( vbean ) ; } for ( Renamer rmap : map . values ( ) ) { rmap . finish ( ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : result / wml2 : MeasurementTimeseries [CODESPLIT] public static MeasurementTimeseriesType initMeasurementTimeseries ( MeasurementTimeseriesType measurementTimeseries , StationTimeSeriesFeature stationFeat , VariableSimpleIF dataVar ) throws IOException { // @gml:id String id = MarshallingUtil . createIdForType ( MeasurementTimeseriesType . class ) ; measurementTimeseries . setId ( id ) ; // wml2:defaultPointMetadata NcTVPDefaultMetadataPropertyType . initDefaultPointMetadata ( measurementTimeseries . addNewDefaultPointMetadata ( ) , dataVar ) ; // wml2:point[0..*] for ( PointFeature pf : stationFeat ) { // wml2:point Point . initPoint ( measurementTimeseries . addNewPoint ( ) , pf , dataVar ) ; } return measurementTimeseries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply this unit by another unit . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { return that instanceof OffsetUnit ? getUnit ( ) . multiplyBy ( ( ( OffsetUnit ) that ) . getUnit ( ) ) : getUnit ( ) . multiplyBy ( that ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide this unit by another unit . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws OperationException { return that instanceof OffsetUnit ? getUnit ( ) . divideBy ( ( ( OffsetUnit ) that ) . getUnit ( ) ) : getUnit ( ) . divideBy ( that ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide this unit into another unit . [CODESPLIT] @ Override protected Unit myDivideInto ( final Unit that ) throws OperationException { return that instanceof OffsetUnit ? getUnit ( ) . divideInto ( ( ( OffsetUnit ) that ) . getUnit ( ) ) : getUnit ( ) . divideInto ( that ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a value in this unit to the equivalent value in the convertible derived unit . [CODESPLIT] public double toDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . toDerivedUnit ( amount + getOffset ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a value in the convertible derived unit to the equivalent value in this unit . [CODESPLIT] public double fromDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( getDerivedUnit ( ) , this ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . fromDerivedUnit ( amount ) - getOffset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts values in the convertible derived unit to the equivalent values in this unit . [CODESPLIT] public double [ ] fromDerivedUnit ( final double [ ] input , final double [ ] output ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( getDerivedUnit ( ) , this ) ; } ( ( DerivableUnit ) getUnit ( ) ) . fromDerivedUnit ( input , output ) ; final double origin = getOffset ( ) ; for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] -= origin ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a DataDDS into an Array for a Structure member variable . [CODESPLIT] public Array convertNestedVariable ( ucar . nc2 . Variable v , List < Range > section , DodsV dataV , boolean flatten ) throws IOException , DAP2Exception { Array data = convertTopVariable ( v , section , dataV ) ; if ( flatten ) { ArrayStructure as = ( ArrayStructure ) data ; // make list of names\r List < String > names = new ArrayList <> ( ) ; Variable nested = v ; while ( nested . isMemberOfStructure ( ) ) { names . add ( 0 , nested . getShortName ( ) ) ; nested = nested . getParentStructure ( ) ; } StructureMembers . Member m = findNested ( as , names , v . getShortName ( ) ) ; Array mdata = m . getDataArray ( ) ; if ( mdata instanceof ArraySequenceNested ) { // gotta unroll\r ArraySequenceNested arraySeq = ( ArraySequenceNested ) mdata ; return arraySeq . flatten ( ) ; } return mdata ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a DataDDS into an Array for a top level variable ie not a Structure member variable . [CODESPLIT] public Array convertTopVariable ( ucar . nc2 . Variable v , List < Range > section , DodsV dataV ) throws IOException , DAP2Exception { Array data = convert ( dataV ) ; // arrays\r if ( ( dataV . darray != null ) && ( dataV . bt instanceof DString ) ) { if ( v . getDataType ( ) == DataType . STRING ) return convertStringArray ( data , v ) ; else if ( v . getDataType ( ) == DataType . CHAR ) return convertStringArrayToChar ( dataV . darray , v , section ) ; else { String mess = \"DODSVariable convertArray String invalid dataType= \" + v . getDataType ( ) ; logger . error ( mess ) ; throw new IllegalArgumentException ( mess ) ; } } if ( ( dataV . bt instanceof DString ) && ( v . getDataType ( ) == DataType . CHAR ) ) { // special case: convert String back to CHAR\r return convertStringToChar ( data , v ) ; } return data ; /* else { // the DGrid case comes here also\r\n         // create the array, using  DODS internal array so there's no copying\r\n        dods.dap.PrimitiveVector pv = dataV.darray.getPrimitiveVector();\r\n        Object storage = pv.getInternalStorage();\r\n        //storage = widenArray( pv, storage); // LOOK data conversion if needed\r\n        int[] shape = (section == null) ? v.getShape() : Range.getShape(section);\r\n        return Array.factory( v.getDataType().getPrimitiveClassType(), shape, storage);\r\n      }   */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a DataDDS into an Array [CODESPLIT] public Array convert ( DodsV dataV ) throws IOException , DAP2Exception { // scalars\r if ( dataV . darray == null ) { if ( dataV . bt instanceof DStructure ) { ArrayStructure structArray = makeArrayStructure ( dataV ) ; iconvertDataStructure ( ( DStructure ) dataV . bt , structArray . getStructureMembers ( ) ) ; return structArray ; } else if ( dataV . bt instanceof DGrid ) { throw new IllegalStateException ( \"DGrid without a darray\" ) ; } else if ( dataV . bt instanceof DSequence ) { ArrayStructure structArray = makeArrayStructure ( dataV ) ; iconvertDataSequenceArray ( ( DSequence ) dataV . bt , structArray . getStructureMembers ( ) ) ; return structArray ; } else { // scalar\r DataType dtype = dataV . getDataType ( ) ; Array scalarData = Array . factory ( dtype , new int [ 0 ] ) ; IndexIterator scalarIndex = scalarData . getIndexIterator ( ) ; iconvertDataPrimitiveScalar ( dataV . bt , scalarIndex ) ; return scalarData ; } } // arrays\r if ( dataV . darray != null ) { if ( dataV . bt instanceof DStructure ) { ArrayStructure structArray = makeArrayStructure ( dataV ) ; iconvertDataStructureArray ( dataV . darray , structArray . getStructureMembers ( ) ) ; return structArray ; } else if ( dataV . bt instanceof DString ) { return convertStringArray ( dataV . darray ) ; } else { // the DGrid case comes here also\r // create the array, using  DODS internal array so there's no copying\r opendap . dap . PrimitiveVector pv = dataV . darray . getPrimitiveVector ( ) ; Object storage = pv . getInternalStorage ( ) ; DataType dtype = dataV . getDataType ( ) ; return Array . factory ( dtype , makeShape ( dataV . darray ) , storage ) ; } } String mess = \"Unknown baseType \" + dataV . bt . getClass ( ) . getName ( ) + \" name=\" + dataV . getEncodedName ( ) ; logger . error ( mess ) ; throw new IllegalStateException ( mess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dataV is an array of DStructure : DArray with BaseTypePrimitiveVector whose values are DStructure [CODESPLIT] private void iconvertDataStructureArray ( DVector darray , StructureMembers members ) throws DAP2Exception { List < StructureMembers . Member > mlist = members . getMembers ( ) ; for ( StructureMembers . Member member : mlist ) { // get the Array for this member\r String name = member . getName ( ) ; IndexIterator ii = ( IndexIterator ) member . getDataObject ( ) ; // loop over each row, fill up the data\r BaseTypePrimitiveVector pv = ( BaseTypePrimitiveVector ) darray . getPrimitiveVector ( ) ; for ( int row = 0 ; row < pv . getLength ( ) ; row ++ ) { DStructure ds_data = ( DStructure ) pv . getValue ( row ) ; BaseType member_data = ds_data . getVariable ( name ) ; iconvertData ( member_data , ii ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert a DODS scalar value [CODESPLIT] private void iconvertDataPrimitiveScalar ( BaseType dodsScalar , IndexIterator ii ) { if ( dodsScalar instanceof DString ) { String sval = ( ( DString ) dodsScalar ) . getValue ( ) ; ii . setObjectNext ( sval ) ; } else if ( dodsScalar instanceof DUInt32 ) { int ival = ( ( DUInt32 ) dodsScalar ) . getValue ( ) ; long lval = DataType . unsignedIntToLong ( ival ) ; // LOOK unsigned\r ii . setLongNext ( lval ) ; } else if ( dodsScalar instanceof DUInt16 ) { short sval = ( ( DUInt16 ) dodsScalar ) . getValue ( ) ; // LOOK unsigned\r int ival = DataType . unsignedShortToInt ( sval ) ; ii . setIntNext ( ival ) ; } else if ( dodsScalar instanceof DFloat32 ) ii . setFloatNext ( ( ( DFloat32 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DFloat64 ) ii . setDoubleNext ( ( ( DFloat64 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DInt32 ) ii . setIntNext ( ( ( DInt32 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DInt16 ) ii . setShortNext ( ( ( DInt16 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DByte ) ii . setByteNext ( ( ( DByte ) dodsScalar ) . getValue ( ) ) ; else throw new IllegalArgumentException ( \"DODSVariable extractScalar invalid dataType= \" + dodsScalar . getClass ( ) . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert a DODS scalar value [CODESPLIT] private void iconvertDataPrimitiveArray ( PrimitiveVector pv , IndexIterator ii ) { BaseType bt = pv . getTemplate ( ) ; // set the data value, using scalarIndex from Variable\r if ( bt instanceof DString ) { BaseTypePrimitiveVector bpv = ( BaseTypePrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) { DString ds = ( DString ) bpv . getValue ( row ) ; ii . setObjectNext ( ds . getValue ( ) ) ; // LOOK CHAR ?\r } } else if ( bt instanceof DUInt32 ) { UInt32PrimitiveVector bpv = ( UInt32PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) { int ival = bpv . getValue ( row ) ; long lval = DataType . unsignedIntToLong ( ival ) ; // LOOK unsigned\r ii . setLongNext ( lval ) ; } } else if ( bt instanceof DUInt16 ) { UInt16PrimitiveVector bpv = ( UInt16PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) { short sval = bpv . getValue ( row ) ; // LOOK unsigned\r int ival = DataType . unsignedShortToInt ( sval ) ; ii . setIntNext ( ival ) ; } } else if ( bt instanceof DFloat32 ) { Float32PrimitiveVector bpv = ( Float32PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setFloatNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DFloat64 ) { Float64PrimitiveVector bpv = ( Float64PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setDoubleNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DInt32 ) { Int32PrimitiveVector bpv = ( Int32PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setIntNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DInt16 ) { Int16PrimitiveVector bpv = ( Int16PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setShortNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DByte ) { BytePrimitiveVector bpv = ( BytePrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setByteNext ( bpv . getValue ( row ) ) ; } else throw new IllegalArgumentException ( \"DODSVariable extractScalar invalid dataType= \" + bt . getClass ( ) . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "older opendap servers send netcdf char data as Strings of length 1 ( !! ) [CODESPLIT] private Array convertStringArray ( Array data , Variable ncVar ) { String [ ] storage = ( String [ ] ) data . getStorage ( ) ; int max_len = 0 ; for ( String s : storage ) { max_len = Math . max ( max_len , s . length ( ) ) ; } if ( max_len > 1 ) return data ; // below is the length=1 barfalloney\r int count = 0 ; int n = ( int ) data . getSize ( ) ; char [ ] charStorage = new char [ n ] ; for ( String s : storage ) { if ( s . length ( ) > 0 ) charStorage [ count ++ ] = s . charAt ( 0 ) ; } // change it to a char (!!). Since its no longer a String, this code wont get called again for this variable.\r ncVar . setDataType ( DataType . CHAR ) ; // return data thats been changed to chars\r return Array . factory ( DataType . CHAR , data . getShape ( ) , charStorage ) ; /* if (section == null)\r\n      section = ncVar.getRanges();\r\n\r\n    // add the strLen dimension back to the array\r\n    int[] varShape = ncVar.getShape();\r\n    int strLen = varShape[ ncVar.getRank()-1];\r\n    int total = (int) Range.computeSize(section);\r\n    int newSize = total/strLen;\r\n    String[] newStorage = new String[newSize];\r\n\r\n    // merge last dimension\r\n    StringBuffer sbuff = new StringBuffer();\r\n    int newCount = 0;\r\n    while (newCount < newSize) {\r\n      int mergeCount = 0;\r\n      sbuff.setLength(0);\r\n      while (mergeCount < strLen) {\r\n        String s = storage[strLen * newCount + mergeCount];\r\n        if (s.length() == 0) break;\r\n        sbuff.append( s);\r\n        mergeCount++;\r\n      }\r\n      newStorage[ newCount++] = sbuff.toString();\r\n    }\r\n\r\n\r\n    /* List dims = ncVar.getDimensions();\r\n    ncVar.setDimensions( dims.subList(0, ncVar.getRank()-1)); // LOOK is this dangerous or what ???\r\n    int[] newShape = ncVar.getShape();\r\n    return Array.factory( DataType.STRING.getPrimitiveClassType(), newShape, newStorage); */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is called on TDS shutdown and reinit [CODESPLIT] static synchronized public void closeAll ( ) { List < MetadataManager > closeDatabases = new ArrayList <> ( openDatabases ) ; for ( MetadataManager mm : closeDatabases ) { if ( debug ) System . out . println ( \"  close database \" + mm . collectionName ) ; mm . close ( ) ; } openDatabases = new ArrayList <> ( ) ; // empty if ( myEnv != null ) { try { // Finally, close the store and environment. myEnv . close ( ) ; myEnv = null ; logger . info ( \"closed bdb caching\" ) ; } catch ( DatabaseException dbe ) { logger . error ( \"Error closing bdb: \" , dbe ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assumes only one open at a time ; could have MetadataManagers share open databases [CODESPLIT] private synchronized void openDatabase ( ) { if ( database != null ) return ; DatabaseConfig dbConfig = new DatabaseConfig ( ) ; dbConfig . setReadOnly ( readOnly ) ; dbConfig . setAllowCreate ( ! readOnly ) ; if ( ! readOnly ) dbConfig . setDeferredWrite ( true ) ; database = myEnv . openDatabase ( null , collectionName , dbConfig ) ; openDatabases . add ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if edit value is valid put error message in buff . [CODESPLIT] @ Override protected boolean _validate ( StringBuffer buff ) { try { new DateType ( tf . getText ( ) , null , null ) ; return true ; } catch ( java . text . ParseException e ) { if ( null != buff ) buff . append ( name ) . append ( \": \" ) . append ( e . getMessage ( ) ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get current value from editComponent [CODESPLIT] @ Override protected Object getEditValue ( ) { try { return new DateType ( tf . getText ( ) , null , null ) ; } catch ( java . text . ParseException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a time udunit string [CODESPLIT] static org . joda . time . Period convertToPeriod ( int value , String udunit ) { if ( udunit . endsWith ( \"s\" ) ) udunit = udunit . substring ( 0 , udunit . length ( ) - 1 ) ; switch ( udunit ) { case \"msec\" : return Period . millis ( value ) ; case \"sec\" : return Period . seconds ( value ) ; case \"minute\" : return Period . minutes ( value ) ; case \"hour\" : case \"hr\" : return Period . hours ( value ) ; case \"day\" : return Period . days ( value ) ; case \"week\" : return Period . weeks ( value ) ; case \"month\" : return Period . months ( value ) ; case \"year\" : return Period . years ( value ) ; } throw new IllegalArgumentException ( \"cant convert \" + udunit + \" to Joda Period\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * # Code table 4 . 2 - Parameter number by product discipline and parameter category 0 0 Estimated precipitation ( kg m - 2 ) 1 1 Instantaneous rain rate ( kg m - 2 s - 1 ) 2 2 Cloud top height ( m ) 3 3 Cloud top height quality indicator ( Code table 4 . 219 ) 4 4 Estimated u - component of wind ( m / s ) 5 5 Estimated v - component of wind ( m / s ) 6 6 Number of pixel used ( Numeric ) 7 7 Solar zenith angle ( deg ) 8 8 Relative azimuth angle ( deg ) 9 9 Reflectance in 0 . 6 micron channel ( % ) 10 10 Reflectance in 0 . 8 micron channel ( % ) 11 11 Reflectance in 1 . 6 micron channel ( % ) 12 12 Reflectance in 3 . 9 micron channel ( % ) 13 13 Atmospheric divergence ( / s ) 14 14 Cloudy brightness temperature ( K ) 15 15 Clear - sky brightness temperature ( K ) 16 16 Cloudy radiance ( with respect to wave number ) ( W m - 1 sr - 1 ) 17 17 Clear - sky radiance ( with respect to wave number ) ( W m - 1 sr - 1 ) 18 18 Reserved 19 19 Wind speed ( m / s ) 20 20 Aerosol optical thickness at 0 . 635 um 21 21 Aerosol optical thickness at 0 . 810 um 22 22 Aerosol optical thickness at 1 . 640 um 23 23 Angstrom coefficient # 24 - 26 Reserved 27 27 Bidirectional reflectance factor ( numeric ) 28 28 Brightness temperature ( K ) 29 29 Scaled radiance ( numeric ) # 30 - 191 Reserved # 192 - 254 Reserved for local use 255 255 Missing [CODESPLIT] private ImmutableMap < Integer , Entry > readTable ( String path ) throws IOException { ImmutableMap . Builder < Integer , Entry > builder = ImmutableMap . builder ( ) ; if ( debugOpen ) { System . out . printf ( \"readEcmwfTable path= %s%n\" , path ) ; } ClassLoader cl = Grib2TableConfig . class . getClassLoader ( ) ; try ( InputStream is = cl . getResourceAsStream ( path ) ) { if ( is == null ) { throw new IllegalStateException ( \"Cant find \" + path ) ; } try ( BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( is , Charset . forName ( \"UTF8\" ) ) ) ) { int count = 0 ; while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) { break ; } if ( line . startsWith ( \"#\" ) || line . trim ( ) . length ( ) == 0 ) { continue ; } count ++ ; int posBlank1 = line . indexOf ( ' ' ) ; int posBlank2 = line . indexOf ( ' ' , posBlank1 + 1 ) ; int lastParen = line . lastIndexOf ( ' ' ) ; String num1 = line . substring ( 0 , posBlank1 ) . trim ( ) ; String num2 = line . substring ( posBlank1 + 1 , posBlank2 ) ; String desc = ( lastParen > 0 ) ? line . substring ( posBlank2 + 1 , lastParen ) . trim ( ) : line . substring ( posBlank2 + 1 ) . trim ( ) ; if ( ! num1 . equals ( num2 ) ) { if ( debug ) { System . out . printf ( \"*****num1 != num2 for %s%n\" , line ) ; } continue ; } int code = Integer . parseInt ( num1 ) ; EcmwfEntry entry = new EcmwfEntry ( code , desc ) ; builder . put ( entry . getCode ( ) , entry ) ; if ( debug ) { System . out . printf ( \" %s%n\" , entry ) ; } } } } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "brute force [CODESPLIT] public boolean findCoordElementForce ( double wantLat , double wantLon , int [ ] rectIndex ) { findBounds ( ) ; if ( wantLat < latMinMax . min ) return false ; if ( wantLat > latMinMax . max ) return false ; if ( wantLon < lonMinMax . min ) return false ; if ( wantLon > lonMinMax . max ) return false ; boolean saveDebug = debug ; debug = false ; for ( int row = 0 ; row < nrows ; row ++ ) { for ( int col = 0 ; col < ncols ; col ++ ) { rectIndex [ 0 ] = row ; rectIndex [ 1 ] = col ; if ( contains ( wantLat , wantLon , rectIndex ) ) { debug = saveDebug ; return true ; } } } //debug = saveDebug;\r return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the best index for the given lat lon point . @param wantLat lat of point @param wantLon lon of point @param rectIndex return ( row col ) index or best guess here . may not be null [CODESPLIT] public boolean findCoordElementNoForce ( double wantLat , double wantLon , int [ ] rectIndex ) { findBounds ( ) ; if ( wantLat < latMinMax . min ) return false ; if ( wantLat > latMinMax . max ) return false ; if ( wantLon < lonMinMax . min ) return false ; if ( wantLon > lonMinMax . max ) return false ; double gradientLat = ( latMinMax . max - latMinMax . min ) / nrows ; double gradientLon = ( lonMinMax . max - lonMinMax . min ) / ncols ; double diffLat = wantLat - latMinMax . min ; double diffLon = wantLon - lonMinMax . min ; // initial guess\r rectIndex [ 0 ] = ( int ) Math . round ( diffLat / gradientLat ) ; // row\r rectIndex [ 1 ] = ( int ) Math . round ( diffLon / gradientLon ) ; // col\r int count = 0 ; while ( true ) { count ++ ; if ( debug ) System . out . printf ( \"%nIteration %d %n\" , count ) ; if ( contains ( wantLat , wantLon , rectIndex ) ) return true ; if ( ! jump2 ( wantLat , wantLon , rectIndex ) ) return false ; // bouncing around\r if ( count > 10 ) { // last ditch attempt\r return incr ( wantLat , wantLon , rectIndex ) ; //if (!ok)\r //  log.error(\"findCoordElement didnt converge lat,lon = \"+wantLat+\" \"+ wantLon);\r //return ok;\r } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the contents of { @code inputStream } into a StringArray . Each line of input will result in an element in the array . <p / > The specified stream remains open after this method returns . [CODESPLIT] public static ErddapStringArray fromInputStream ( InputStream inputStream , String charset ) throws IOException { if ( charset == null || charset . isEmpty ( ) ) { charset = CDM . UTF8 ; } InputStreamReader isr = new InputStreamReader ( inputStream , charset ) ; BufferedReader bufferedReader = new BufferedReader ( isr ) ; ErddapStringArray sa = new ErddapStringArray ( ) ; for ( String s ; ( s = bufferedReader . readLine ( ) ) != null ; ) { sa . add ( s ) ; } // Do not call BufferedReader.close() here; that would close the underlying InputStream, which is the // responsibility of the client. This ought to be safe, as neither InputStreamReader nor BufferedReader hold any // resources that a call to close() would make free and which the garbage collector would not make free anyway. return sa ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This adds an item to the array ( increasing size by 1 ) . [CODESPLIT] public void add ( String value ) { if ( size == array . length ) //if we're at capacity ensureCapacity ( size + 1L ) ; array [ size ++ ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This ensures that the capacity is at least minCapacity . [CODESPLIT] public void ensureCapacity ( long minCapacity ) { if ( array . length < minCapacity ) { //ensure minCapacity is < Integer.MAX_VALUE ErddapMath2 . ensureArraySizeOkay ( minCapacity , \"StringArray\" ) ; //caller may know exact number needed, so don't double above 2x current size int newCapacity = ( int ) Math . min ( Integer . MAX_VALUE - 1 , array . length + ( long ) array . length ) ; if ( newCapacity < minCapacity ) newCapacity = ( int ) minCapacity ; //safe since checked above String [ ] newArray = new String [ newCapacity ] ; System . arraycopy ( array , 0 , newArray , 0 , size ) ; array = newArray ; //do last to minimize concurrency problems } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This gets a specified element . [CODESPLIT] public String get ( int index ) { if ( index >= size ) throw new IllegalArgumentException ( ErddapString2 . ERROR + \" in StringArray.get: index (\" + index + \") >= size (\" + size + \").\" ) ; return array [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { final Attribute levelAtt = ds . findAttribute ( \"/HDFEOS/ADDITIONAL/FILE_ATTRIBUTES/@ProcessLevel\" ) ; if ( levelAtt == null ) { return ; } final int level = levelAtt . getStringValue ( ) . startsWith ( \"2\" ) ? 2 : 3 ; //Attribute time = ds.findAttribute(\"/HDFEOS/ADDITIONAL/FILE_ATTRIBUTES/@TAI93At0zOfGranule\");\r if ( level == 3 ) { augmentDataset3 ( ds ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a real longitude and latitude into the rotated longitude ( X ) and rotated latitude ( Y ) . [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl destPoint ) { double lat = latlon . getLatitude ( ) ; double lon = latlon . getLongitude ( ) ; //\tLon-lat pair to xyz coordinates on sphere with radius 1\r double [ ] p0 = new double [ ] { Math . cos ( lat * RAD_PER_DEG ) * Math . cos ( lon * RAD_PER_DEG ) , Math . cos ( lat * RAD_PER_DEG ) * Math . sin ( lon * RAD_PER_DEG ) , Math . sin ( lat * RAD_PER_DEG ) } ; //\tRotate around Z-axis\r double [ ] p1 = new double [ ] { rotZ [ 0 ] [ 0 ] * p0 [ 0 ] + rotZ [ 0 ] [ 1 ] * p0 [ 1 ] + rotZ [ 0 ] [ 2 ] * p0 [ 2 ] , rotZ [ 1 ] [ 0 ] * p0 [ 0 ] + rotZ [ 1 ] [ 1 ] * p0 [ 1 ] + rotZ [ 1 ] [ 2 ] * p0 [ 2 ] , rotZ [ 2 ] [ 0 ] * p0 [ 0 ] + rotZ [ 2 ] [ 1 ] * p0 [ 1 ] + rotZ [ 2 ] [ 2 ] * p0 [ 2 ] } ; //\tRotate around Y-axis\r double [ ] p2 = new double [ ] { rotY [ 0 ] [ 0 ] * p1 [ 0 ] + rotY [ 0 ] [ 1 ] * p1 [ 1 ] + rotY [ 0 ] [ 2 ] * p1 [ 2 ] , rotY [ 1 ] [ 0 ] * p1 [ 0 ] + rotY [ 1 ] [ 1 ] * p1 [ 1 ] + rotY [ 1 ] [ 2 ] * p1 [ 2 ] , rotY [ 2 ] [ 0 ] * p1 [ 0 ] + rotY [ 2 ] [ 1 ] * p1 [ 1 ] + rotY [ 2 ] [ 2 ] * p1 [ 2 ] } ; final double lonR = LatLonPointImpl . range180 ( Math . atan2 ( p2 [ 1 ] , p2 [ 0 ] ) * DEG_PER_RAD ) ; //final double lonR = Math.atan2(p2[1], p2[0]) * DEG_PER_RAD;\r final double latR = Math . asin ( p2 [ 2 ] ) * DEG_PER_RAD ; if ( destPoint == null ) destPoint = new ProjectionPointImpl ( lonR , latR ) ; else destPoint . setLocation ( lonR , latR ) ; if ( show ) System . out . println ( \"LatLon= \" + latlon + \" proj= \" + destPoint ) ; return destPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a rotated longitude ( X ) and rotated latitude ( Y ) into a real longitude - latitude pair . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint ppt , LatLonPointImpl destPoint ) { //\t\"x\" and \"y\" input for rotated pole coords are actually a lon-lat pair\r final double lonR = LatLonPointImpl . range180 ( ppt . getX ( ) ) ; // LOOK guessing\r final double latR = ppt . getY ( ) ; //\tLon-lat pair to xyz coordinates on sphere with radius 1\r double [ ] p0 = new double [ ] { Math . cos ( latR * RAD_PER_DEG ) * Math . cos ( lonR * RAD_PER_DEG ) , Math . cos ( latR * RAD_PER_DEG ) * Math . sin ( lonR * RAD_PER_DEG ) , Math . sin ( latR * RAD_PER_DEG ) } ; //\tInverse rotate around Y-axis (using transpose of Y matrix)\r double [ ] p1 = new double [ ] { rotY [ 0 ] [ 0 ] * p0 [ 0 ] + rotY [ 1 ] [ 0 ] * p0 [ 1 ] + rotY [ 2 ] [ 0 ] * p0 [ 2 ] , rotY [ 0 ] [ 1 ] * p0 [ 0 ] + rotY [ 1 ] [ 1 ] * p0 [ 1 ] + rotY [ 2 ] [ 1 ] * p0 [ 2 ] , rotY [ 0 ] [ 2 ] * p0 [ 0 ] + rotY [ 1 ] [ 2 ] * p0 [ 1 ] + rotY [ 2 ] [ 2 ] * p0 [ 2 ] } ; //\tInverse rotate around Z-axis (using transpose of Z matrix)\r double [ ] p2 = new double [ ] { rotZ [ 0 ] [ 0 ] * p1 [ 0 ] + rotZ [ 1 ] [ 0 ] * p1 [ 1 ] + rotZ [ 2 ] [ 0 ] * p1 [ 2 ] , rotZ [ 0 ] [ 1 ] * p1 [ 0 ] + rotZ [ 1 ] [ 1 ] * p1 [ 1 ] + rotZ [ 2 ] [ 1 ] * p1 [ 2 ] , rotZ [ 0 ] [ 2 ] * p1 [ 0 ] + rotZ [ 1 ] [ 2 ] * p1 [ 1 ] + rotZ [ 2 ] [ 2 ] * p1 [ 2 ] } ; final double lon = Math . atan2 ( p2 [ 1 ] , p2 [ 0 ] ) * DEG_PER_RAD ; final double lat = Math . asin ( p2 [ 2 ] ) * DEG_PER_RAD ; if ( destPoint == null ) destPoint = new LatLonPointImpl ( lat , lon ) ; else destPoint . set ( lat , lon ) ; if ( show ) System . out . println ( \"Proj= \" + ppt + \" latlon= \" + destPoint ) ; return destPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the location being scanned ( DO NOT USE THIS METHOD public by accident ) . [CODESPLIT] public void setScanLocation ( String scanLocation ) { // ToDo LOOK Instead hand InvDatasetScan (or InvCatFactory?) an algorithm for converting an aliased location. if ( ! scanLocation . equals ( this . scanLocation ) ) { this . isValid = true ; this . scanLocation = scanLocation ; this . scanLocationCrDs = createScanLocationCrDs ( ) ; if ( this . scanLocationCrDs == null ) { isValid = false ; invalidMessage = new StringBuilder ( \"Invalid InvDatasetScan <path=\" ) . append ( rootPath ) . append ( \"; scanLocation=\" ) . append ( scanLocation ) . append ( \">: could not create CrawlableDataset for scanLocation.\" ) ; } else if ( ! this . scanLocationCrDs . exists ( ) ) { isValid = false ; invalidMessage = new StringBuilder ( \"Invalid InvDatasetScan <path=\" ) . append ( rootPath ) . append ( \"; scanLocation=\" ) . append ( scanLocation ) . append ( \">: CrawlableDataset for scanLocation does not exist.\" ) ; } else if ( ! this . scanLocationCrDs . isCollection ( ) ) { isValid = false ; invalidMessage = new StringBuilder ( \"Invalid InvDatasetScan <path=\" ) . append ( rootPath ) . append ( \"; scanLocation=\" ) . append ( scanLocation ) . append ( \">: CrawlableDataset for scanLocation not a collection.\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the CrawlableDataset path / location that corresponds to the given dataset path . The given dataset path must start with the datasetScan path for this InvDatasetScan if not a null is returned . [CODESPLIT] public String translatePathToLocation ( String dsPath ) { if ( dsPath == null ) return null ; if ( dsPath . length ( ) > 0 ) if ( dsPath . startsWith ( \"/\" ) ) dsPath = dsPath . substring ( 1 ) ; if ( ! dsPath . startsWith ( this . getPath ( ) ) ) return null ; // remove the matching part, the rest is the \"data directory\" String dataDir = dsPath . substring ( this . getPath ( ) . length ( ) ) ; if ( dataDir . startsWith ( \"/\" ) ) dataDir = dataDir . substring ( 1 ) ; CrawlableDataset curCrDs = scanLocationCrDs . getDescendant ( dataDir ) ; if ( log . isDebugEnabled ( ) ) log . debug ( \"translatePathToLocation(): url dsPath= \" + dsPath + \" to dataset dsPath= \" + curCrDs . getPath ( ) ) ; return curCrDs . getPath ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the CrawlableDataset for the given path null if this InvDatasetScan does not allow ( filters out ) the requested CrawlableDataset . [CODESPLIT] public CrawlableDataset requestCrawlableDataset ( String path ) throws IOException { String crDsPath = translatePathToLocation ( path ) ; if ( crDsPath == null ) return null ; CatalogBuilder catBuilder = buildCatalogBuilder ( ) ; if ( catBuilder == null ) return null ; return catBuilder . requestCrawlableDataset ( crDsPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to build a catalog for the given path by scanning the location associated with this InvDatasetScan . The given path must start with the path of this InvDatasetScan . [CODESPLIT] public InvCatalogImpl makeCatalogForDirectory ( String orgPath , URI catURI ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"baseURI=\" + catURI ) ; log . debug ( \"orgPath=\" + orgPath ) ; log . debug ( \"rootPath=\" + rootPath ) ; log . debug ( \"scanLocation=\" + scanLocation ) ; } // Get the dataset path. String dsDirPath = translatePathToLocation ( orgPath ) ; if ( dsDirPath == null ) { String tmpMsg = \"makeCatalogForDirectory(): Requesting path <\" + orgPath + \"> must start with \\\"\" + rootPath + \"\\\".\" ; log . error ( tmpMsg ) ; return null ; } // Setup and create catalog builder. CatalogBuilder catBuilder = buildCatalogBuilder ( ) ; if ( catBuilder == null ) return null ; // A very round about way to remove the filename (e.g., \"catalog.xml\"). // Note: Gets around \"path separator at end of path\" issues that are CrDs implementation dependant. // Note: Does not check that CrDs is allowed by filters. String dsPath = dsDirPath . substring ( scanLocationCrDs . getPath ( ) . length ( ) ) ; if ( dsPath . startsWith ( \"/\" ) ) dsPath = dsPath . substring ( 1 ) ; CrawlableDataset reqCrDs = scanLocationCrDs . getDescendant ( dsPath ) ; CrawlableDataset parent = reqCrDs . getParentDataset ( ) ; if ( parent == null ) { log . error ( \"makeCatalogForDirectory(): I/O error getting parent crDs level <\" + dsDirPath + \">: \" ) ; return null ; } dsDirPath = parent . getPath ( ) ; // Get the CrawlableDataset for the desired catalog level (checks that allowed by filters). CrawlableDataset catalogCrDs ; try { catalogCrDs = catBuilder . requestCrawlableDataset ( dsDirPath ) ; } catch ( IOException e ) { log . error ( \"makeCatalogForDirectory(): I/O error getting catalog level <\" + dsDirPath + \">: \" + e . getMessage ( ) , e ) ; return null ; } if ( catalogCrDs == null ) { log . warn ( \"makeCatalogForDirectory(): requested catalog level <\" + dsDirPath + \"> not allowed (filtered out).\" ) ; return null ; } if ( ! catalogCrDs . isCollection ( ) ) { log . warn ( \"makeCatalogForDirectory(): requested catalog level <\" + dsDirPath + \"> is not a collection.\" ) ; return null ; } // Generate the desired catalog using the builder. InvCatalogImpl catalog ; try { catalog = catBuilder . generateCatalog ( catalogCrDs ) ; } catch ( IOException e ) { log . error ( \"makeCatalogForDirectory(): catalog generation failed <\" + catalogCrDs . getPath ( ) + \">: \" + e . getMessage ( ) ) ; return null ; } // Set the catalog base URI. if ( catalog != null ) catalog . setBaseURI ( catURI ) ; //    InvDatasetImpl top = (InvDatasetImpl) catalog.getDataset(); //    // if we name it carefully, can get catalogRef to useProxy == true (disappear top dataset) //    if ( service.isRelativeBase()) { //      pos = dataDir.lastIndexOf(\"/\"); //      String lastDir = (pos > 0) ? dataDir.substring(pos+1) : dataDir; //      String topName = lastDir.length() > 0 ? lastDir : getName(); //      top.setName( topName); //    } return catalog ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to build a catalog for the given resolver path by scanning the location associated with this InvDatasetScan . The given path must start with the path of this InvDatasetScan and refer to a resolver ProxyDatasetHandler that is part of this InvDatasetScan . [CODESPLIT] public InvCatalogImpl makeProxyDsResolverCatalog ( String path , URI baseURI ) { if ( path == null ) return null ; if ( path . endsWith ( \"/\" ) ) return null ; // Get the dataset path. String dsDirPath = translatePathToLocation ( path ) ; if ( dsDirPath == null ) { log . error ( \"makeProxyDsResolverCatalog(): Requesting path <\" + path + \"> must start with \\\"\" + rootPath + \"\\\".\" ) ; return null ; } // Split into parent path and dataset name. int pos = dsDirPath . lastIndexOf ( ' ' ) ; if ( pos == - 1 ) { log . error ( \"makeProxyDsResolverCatalog(): Requesting path <\" + path + \"> must contain a slash (\\\"/\\\").\" ) ; return null ; } String dsName = dsDirPath . substring ( pos + 1 ) ; dsDirPath = dsDirPath . substring ( 0 , pos ) ; // Find matching ProxyDatasetHandler. ProxyDatasetHandler pdh = this . getProxyDatasetHandlers ( ) . get ( dsName ) ; if ( pdh == null ) { log . error ( \"makeProxyDsResolverCatalog(): No matching proxy dataset handler found <\" + dsName + \">.\" ) ; return null ; } // Setup and create catalog builder. CatalogBuilder catBuilder = buildCatalogBuilder ( ) ; if ( catBuilder == null ) return null ; // Get the CrawlableDataset for the desired catalog level. CrawlableDataset catalogCrDs ; try { catalogCrDs = catBuilder . requestCrawlableDataset ( dsDirPath ) ; } catch ( IOException e ) { log . error ( \"makeProxyDsResolverCatalog(): failed to create CrawlableDataset for catalogLevel <\" + dsDirPath + \"> and class <\" + crDsClassName + \">: \" + e . getMessage ( ) , e ) ; return null ; } if ( catalogCrDs == null ) { log . warn ( \"makeProxyDsResolverCatalog(): requested catalog level <\" + dsDirPath + \"> not allowed (filtered out).\" ) ; return null ; } if ( ! catalogCrDs . isCollection ( ) ) { log . warn ( \"makeProxyDsResolverCatalog(): requested catalog level <\" + dsDirPath + \"> not a collection.\" ) ; return null ; } // Generate the desired catalog using the builder. InvCatalogImpl catalog ; try { catalog = ( InvCatalogImpl ) catBuilder . generateProxyDsResolverCatalog ( catalogCrDs , pdh ) ; } catch ( IOException e ) { log . error ( \"makeProxyDsResolverCatalog(): catalog generation failed <\" + catalogCrDs . getPath ( ) + \">: \" + e . getMessage ( ) ) ; return null ; } // Set the catalog base URI. if ( catalog != null ) catalog . setBaseURI ( baseURI ) ; return catalog ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "What is the data type of the aggregation coordinate ? [CODESPLIT] private DataType getCoordinateType ( ) { List < Dataset > nestedDatasets = getDatasets ( ) ; DatasetOuterDimension first = ( DatasetOuterDimension ) nestedDatasets . get ( 0 ) ; return first . isStringValued ? DataType . STRING : DataType . DOUBLE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory for Grib2Pds [CODESPLIT] @ Nullable public static Grib2Pds factory ( int template , byte [ ] input ) { switch ( template ) { case 0 : return new Grib2Pds0 ( input ) ; case 1 : return new Grib2Pds1 ( input ) ; case 2 : return new Grib2Pds2 ( input ) ; case 5 : return new Grib2Pds5 ( input ) ; case 6 : return new Grib2Pds6 ( input ) ; case 8 : return new Grib2Pds8 ( input ) ; case 9 : return new Grib2Pds9 ( input ) ; case 10 : return new Grib2Pds10 ( input ) ; case 11 : return new Grib2Pds11 ( input ) ; case 12 : return new Grib2Pds12 ( input ) ; case 15 : return new Grib2Pds15 ( input ) ; case 30 : return new Grib2Pds30 ( input ) ; case 31 : return new Grib2Pds31 ( input ) ; case 48 : return new Grib2Pds48 ( input ) ; case 61 : return new Grib2Pds61 ( input ) ; default : log . warn ( \"Missing template \" + template ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public double getProbabilityLowerLimit () { return GribNumbers . UNDEFINED ; } [CODESPLIT] public void show ( Formatter f ) { f . format ( \"Grib2Pds{ id=%d-%d template=%d, forecastTime= %d timeUnit=%s vertLevel=%f}\" , getParameterCategory ( ) , getParameterNumber ( ) , template , getForecastTime ( ) , getTimeUnit ( ) , getLevelValue1 ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "null means use refTime [CODESPLIT] protected CalendarDate calcTime ( int startIndex ) { int year = GribNumbers . int2 ( getOctet ( startIndex ++ ) , getOctet ( startIndex ++ ) ) ; int month = getOctet ( startIndex ++ ) ; int day = getOctet ( startIndex ++ ) ; int hour = getOctet ( startIndex ++ ) ; int minute = getOctet ( startIndex ++ ) ; int second = getOctet ( startIndex ++ ) ; if ( ( year == 0 ) && ( month == 0 ) && ( day == 0 ) && ( hour == 0 ) && ( minute == 0 ) && ( second == 0 ) ) return CalendarDate . UNKNOWN ; // href.t00z.prob.f36.grib2\r if ( hour > 23 ) { day += ( hour / 24 ) ; hour = hour % 24 ; } return CalendarDate . of ( null , year , month , day , hour , minute , second ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply scale factor to value return a double result . [CODESPLIT] double applyScaleFactor ( int scale , int value ) { return ( ( scale == 0 ) || ( scale == 255 ) || ( value == 0 ) ) ? value : value * Math . pow ( 10 , - scale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an Html representation of the given dataset . <p > With datasetEvents catrefEvents = true this is used to construct an HTML page on the client ( eg using HtmlPage ) ; the client then detects URL clicks and processes . <p > With datasetEvents catrefEvents = false this is used to construct an HTML page on the server . ( eg using HtmlPage ) ; the client then detects URL clicks and processes . [CODESPLIT] public void writeHtmlDescription ( Formatter out , Dataset ds , boolean complete , boolean isServer , boolean datasetEvents , boolean catrefEvents , boolean resolveRelativeUrls ) { if ( ds == null ) return ; if ( complete ) { out . format ( \"<!DOCTYPE html PUBLIC \\\"-//W3C//DTD HTML 4.01 Transitional//EN\\\"%n\" ) ; out . format ( \"        \\\"http://www.w3.org/TR/html4/loose.dtd\\\">%n\" ) ; out . format ( \"<html>%n\" ) ; out . format ( \"<head>%n\" ) ; out . format ( \"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=iso-8859-1\\\">%n\" ) ; out . format ( \"</head>%n\" ) ; out . format ( \"<body>%n\" ) ; } out . format ( \"<h2>Dataset: %s</h2>%n<ul>\" , ds . getName ( ) ) ; if ( ds . getDataFormatName ( ) != null ) out . format ( \" <li><em>Data format: </em>%s</li>%n\" , htmlEscaper . escape ( ds . getDataFormatName ( ) ) ) ; if ( ( ds . getDataSize ( ) > 0 ) ) out . format ( \" <li><em>Data size: </em>%s</li>%n\" , Format . formatByteSize ( ds . getDataSize ( ) ) ) ; if ( ds . getFeatureTypeName ( ) != null ) out . format ( \" <li><em>Feature type: </em>%s</li>%n\" , htmlEscaper . escape ( ds . getFeatureTypeName ( ) ) ) ; if ( ds . getCollectionType ( ) != null ) out . format ( \" <li><em>Collection type: </em>%s</li>%n\" , htmlEscaper . escape ( ds . getCollectionType ( ) ) ) ; if ( ds . isHarvest ( ) ) out . format ( \" <li><em>Harvest:</em> true</li>%n\" ) ; if ( ds . getAuthority ( ) != null ) out . format ( \" <li><em>Naming Authority: </em>%s</li>%n%n\" , htmlEscaper . escape ( ds . getAuthority ( ) ) ) ; if ( ds . getId ( ) != null ) out . format ( \" <li><em>ID: </em>%s</li>%n\" , htmlEscaper . escape ( ds . getId ( ) ) ) ; if ( ds . getRestrictAccess ( ) != null ) out . format ( \" <li><em>RestrictAccess: </em>%s</li>%n\" , htmlEscaper . escape ( ds . getRestrictAccess ( ) ) ) ; if ( ds instanceof CatalogRef ) { CatalogRef catref = ( CatalogRef ) ds ; String href = resolveRelativeUrls | catrefEvents ? resolve ( ds , catref . getXlinkHref ( ) ) : catref . getXlinkHref ( ) ; if ( catrefEvents ) href = \"catref:\" + href ; out . format ( \" <li><em>CatalogRef: </em>%s</li>%n\" , makeHref ( href , null , null ) ) ; } out . format ( \"</ul>%n\" ) ; java . util . List < Documentation > docs = ds . getDocumentation ( ) ; if ( docs . size ( ) > 0 ) { out . format ( \"<h3>Documentation:</h3>%n<ul>%n\" ) ; for ( Documentation doc : docs ) { String type = ( doc . getType ( ) == null ) ? \"\" : \"<strong>\" + htmlEscaper . escape ( doc . getType ( ) ) + \":</strong> \" ; String inline = doc . getInlineContent ( ) ; if ( ( inline != null ) && ( inline . length ( ) > 0 ) ) out . format ( \" <li>%s %s</li>%n\" , type , htmlEscaper . escape ( inline ) ) ; if ( doc . hasXlink ( ) ) { out . format ( \" <li>%s %s</li>%n\" , type , makeHref ( doc . getXlinkHref ( ) , null , doc . getXlinkTitle ( ) ) ) ; } } out . format ( \"</ul>%n\" ) ; } java . util . List < Access > access = ds . getAccess ( ) ; if ( access . size ( ) > 0 ) { out . format ( \"<h3>Access:</h3>%n<ol>%n\" ) ; for ( Access a : access ) { Service s = a . getService ( ) ; String urlString = resolveRelativeUrls || datasetEvents ? a . getStandardUrlName ( ) : a . getUnresolvedUrlName ( ) ; String queryString = null ; // String fullUrlString = urlString; if ( datasetEvents ) urlString = \"dataset:\" + urlString ; ServiceType stype = s . getType ( ) ; if ( isServer && stype != null ) switch ( stype ) { case OPENDAP : case DODS : urlString = urlString + \".html\" ; break ; case DAP4 : urlString = urlString + \".dmr.xml\" ; break ; case WCS : queryString = \"service=WCS&version=1.0.0&request=GetCapabilities\" ; break ; case WMS : queryString = \"service=WMS&version=1.3.0&request=GetCapabilities\" ; break ; case NCML : case UDDC : case ISO : String catalogUrl = ds . getCatalogUrl ( ) ; String datasetId = ds . getId ( ) ; if ( catalogUrl != null && datasetId != null ) { if ( catalogUrl . indexOf ( ' ' ) > 0 ) catalogUrl = catalogUrl . substring ( 0 , catalogUrl . lastIndexOf ( ' ' ) ) ; /* try {\n                  catalogUrl = URLEncoder.encode(catalogUrl, \"UTF-8\");\n                  datasetId = URLEncoder.encode(datasetId, \"UTF-8\");\n                } catch (UnsupportedEncodingException e) {\n                  e.printStackTrace();\n                } */ queryString = \"catalog=\" + urlParamEscaper . escape ( catalogUrl ) + \"&dataset=\" + urlParamEscaper . escape ( datasetId ) ; } break ; case NetcdfSubset : urlString = urlString + \"/dataset.html\" ; break ; case CdmRemote : queryString = \"req=cdl\" ; break ; case CdmrFeature : queryString = \"req=form\" ; } out . format ( \" <li> <b>%s: </b>%s</li>%n\" , s . getServiceTypeName ( ) , makeHref ( urlString , queryString , null ) ) ; } out . format ( \"</ol>%n\" ) ; } java . util . List < ThreddsMetadata . Contributor > contributors = ds . getContributors ( ) ; if ( contributors . size ( ) > 0 ) { out . format ( \"<h3>Contributors:</h3>%n<ul>%n\" ) ; for ( ThreddsMetadata . Contributor t : contributors ) { String role = ( t . getRole ( ) == null ) ? \"\" : \"<strong> (\" + htmlEscaper . escape ( t . getRole ( ) ) + \")</strong> \" ; out . format ( \" <li>%s %s</li>%n\" , htmlEscaper . escape ( t . getName ( ) ) , role ) ; } out . format ( \"</ul>%n\" ) ; } java . util . List < ThreddsMetadata . Vocab > keywords = ds . getKeywords ( ) ; if ( keywords . size ( ) > 0 ) { out . format ( \"<h3>Keywords:</h3>%n<ul>%n\" ) ; for ( ThreddsMetadata . Vocab t : keywords ) { String vocab = ( t . getVocabulary ( ) == null ) ? \"\" : \" <strong>(\" + htmlEscaper . escape ( t . getVocabulary ( ) ) + \")</strong> \" ; out . format ( \" <li>%s %s</li>%n\" , htmlEscaper . escape ( t . getText ( ) ) , vocab ) ; } out . format ( \"</ul>%n\" ) ; } java . util . List < DateType > dates = ds . getDates ( ) ; if ( dates . size ( ) > 0 ) { out . format ( \"<h3>Dates:</h3>%n<ul>%n\" ) ; for ( DateType d : dates ) { String type = ( d . getType ( ) == null ) ? \"\" : \" <strong>(\" + htmlEscaper . escape ( d . getType ( ) ) + \")</strong> \" ; out . format ( \" <li>%s %s</li>%n\" , htmlEscaper . escape ( d . getText ( ) ) , type ) ; } out . format ( \"</ul>%n\" ) ; } java . util . List < ThreddsMetadata . Vocab > projects = ds . getProjects ( ) ; if ( projects . size ( ) > 0 ) { out . format ( \"<h3>Projects:</h3>%n<ul>%n\" ) ; for ( ThreddsMetadata . Vocab t : projects ) { String vocab = ( t . getVocabulary ( ) == null ) ? \"\" : \" <strong>(\" + htmlEscaper . escape ( t . getVocabulary ( ) ) + \")</strong> \" ; out . format ( \" <li>%s %s</li>%n\" , htmlEscaper . escape ( t . getText ( ) ) , vocab ) ; } out . format ( \"</ul>%n\" ) ; } java . util . List < ThreddsMetadata . Source > creators = ds . getCreators ( ) ; if ( creators . size ( ) > 0 ) { out . format ( \"<h3>Creators:</h3>%n<ul>%n\" ) ; for ( ThreddsMetadata . Source t : creators ) { out . format ( \" <li><strong>%s</strong><ul>%n\" , htmlEscaper . escape ( t . getName ( ) ) ) ; out . format ( \" <li><em>email: </em>%s</li>%n\" , htmlEscaper . escape ( t . getEmail ( ) ) ) ; if ( t . getUrl ( ) != null ) { String newUrl = resolveRelativeUrls ? makeHrefResolve ( ds , t . getUrl ( ) , null ) : makeHref ( t . getUrl ( ) , null , null ) ; out . format ( \" <li> <em>%s</em></li>%n\" , newUrl ) ; } out . format ( \" </ul></li>%n\" ) ; } out . format ( \"</ul>%n\" ) ; } java . util . List < ThreddsMetadata . Source > publishers = ds . getPublishers ( ) ; if ( publishers . size ( ) > 0 ) { out . format ( \"<h3>Publishers:</h3>%n<ul>%n\" ) ; for ( ThreddsMetadata . Source t : publishers ) { out . format ( \" <li><strong>%s</strong><ul>%n\" , htmlEscaper . escape ( t . getName ( ) ) ) ; out . format ( \" <li><em>email: </em>%s%n\" , htmlEscaper . escape ( t . getEmail ( ) ) ) ; if ( t . getUrl ( ) != null ) { String urlLink = resolveRelativeUrls ? makeHrefResolve ( ds , t . getUrl ( ) , null ) : makeHref ( t . getUrl ( ) , null , null ) ; out . format ( \" <li> <em>%s</em></li>%n\" , urlLink ) ; } out . format ( \" </ul>%n\" ) ; } out . format ( \"</ul>%n\" ) ; } /*\n     4.2:\n     <h3>Variables:</h3>\n     <ul>\n     <li><em>Vocabulary</em> [DIF]:\n     <ul>\n      <li><strong>Reflectivity</strong> =  <i></i> = EARTH SCIENCE &gt; Spectral/Engineering &gt; Radar &gt; Radar Reflectivity (db)\n      <li><strong>Velocity</strong> =  <i></i> = EARTH SCIENCE &gt; Spectral/Engineering &gt; Radar &gt; Doppler Velocity (m/s)\n      <li><strong>SpectrumWidth</strong> =  <i></i> = EARTH SCIENCE &gt; Spectral/Engineering &gt; Radar &gt; Doppler Spectrum Width (m/s)\n      </ul>\n      </ul>\n     </ul>\n \n     4.3:\n     <h3>Variables:</h3>\n     <ul>\n     <li><em>Vocabulary</em> [CF-1.0]:\n     <ul>\n      <li><strong>d3d (meters) </strong> =  <i>3D Depth at Nodes\n     <p>        </i> = depth_at_nodes\n      <li><strong>depth (meters) </strong> =  <i>Bathymetry</i> = depth\n      <li><strong>eta (m) </strong> =  <i></i> =\n      <li><strong>temp (Celsius) </strong> =  <i>Temperature\n     <p>        </i> = sea_water_temperature\n      <li><strong>u (m/s) </strong> =  <i>Eastward Water\n     <p>          Velocity\n     <p>        </i> = eastward_sea_water_velocity\n      <li><strong>v (m/s) </strong> =  <i>Northward Water\n     <p>          Velocity\n     <p>        </i> = northward_sea_water_velocity\n     </ul>\n     </ul>\n      */ java . util . List < ThreddsMetadata . VariableGroup > vars = ds . getVariables ( ) ; if ( vars . size ( ) > 0 ) { out . format ( \"<h3>Variables:</h3>%n<ul>%n\" ) ; for ( ThreddsMetadata . VariableGroup t : vars ) { out . format ( \"<li><em>Vocabulary</em> [\" ) ; if ( t . getVocabUri ( ) != null ) { ThreddsMetadata . UriResolved uri = t . getVocabUri ( ) ; String vocabLink = resolveRelativeUrls ? makeHref ( uri . resolved . toString ( ) , null , t . getVocabulary ( ) ) : makeHref ( uri . href , null , t . getVocabulary ( ) ) ; out . format ( vocabLink ) ; } else { out . format ( htmlEscaper . escape ( t . getVocabulary ( ) ) ) ; } out . format ( \"]:%n<ul>%n\" ) ; java . util . List < ThreddsMetadata . Variable > vlist = t . getVariableList ( ) ; if ( vlist . size ( ) > 0 ) { for ( ThreddsMetadata . Variable v : vlist ) { String units = ( v . getUnits ( ) == null || v . getUnits ( ) . length ( ) == 0 ) ? \"\" : \" (\" + v . getUnits ( ) + \") \" ; out . format ( \" <li><strong>%s</strong> = \" , htmlEscaper . escape ( v . getName ( ) + units ) ) ; if ( v . getDescription ( ) != null ) out . format ( \" <i>%s</i> = \" , htmlEscaper . escape ( v . getDescription ( ) ) ) ; if ( v . getVocabularyName ( ) != null ) out . format ( \"%s\" , htmlEscaper . escape ( v . getVocabularyName ( ) ) ) ; out . format ( \"%n\" ) ; } } out . format ( \"</ul>%n\" ) ; } out . format ( \"</ul>%n\" ) ; } // LOOK what about VariableMapLink string ?? if ( ds . getVariableMapLink ( ) != null ) { out . format ( \"<h3>Variables:</h3>%n\" ) ; ThreddsMetadata . UriResolved uri = ds . getVariableMapLink ( ) ; out . format ( \"<ul><li>%s</li></ul>%n\" , makeHref ( uri . resolved . toASCIIString ( ) , null , \"VariableMap\" ) ) ; } ThreddsMetadata . GeospatialCoverage gc = ds . getGeospatialCoverage ( ) ; if ( gc != null ) { out . format ( \"<h3>GeospatialCoverage:</h3>%n<ul>%n\" ) ; // if (gc.isGlobal()) out.format(\" <li><em> Global </em>%n\"); out . format ( \" <li><em> Longitude: </em> %s</li>%n\" , rangeString ( gc . getEastWestRange ( ) ) ) ; out . format ( \" <li><em> Latitude: </em> %s</li>%n\" , rangeString ( gc . getNorthSouthRange ( ) ) ) ; if ( gc . getUpDownRange ( ) != null ) { out . format ( \" <li><em> Altitude: </em> %s (positive is <strong>%s)</strong></li>%n\" , rangeString ( gc . getUpDownRange ( ) ) , gc . getZPositive ( ) ) ; } java . util . List < ThreddsMetadata . Vocab > nlist = gc . getNames ( ) ; if ( ( nlist != null ) && ( nlist . size ( ) > 0 ) ) { out . format ( \" <li><em>  Names: </em> <ul>%n\" ) ; for ( ThreddsMetadata . Vocab elem : nlist ) { out . format ( \" <li>%s</li>%n\" , htmlEscaper . escape ( elem . getText ( ) ) ) ; } out . format ( \" </ul>%n\" ) ; } out . format ( \" </ul>%n\" ) ; } DateRange tc = ds . getTimeCoverage ( ) ; if ( tc != null ) { out . format ( \"<h3>TimeCoverage:</h3>%n<ul>%n\" ) ; DateType start = tc . getStart ( ) ; if ( start != null ) out . format ( \" <li><em>  Start: </em> %s</li>%n\" , start . toString ( ) ) ; DateType end = tc . getEnd ( ) ; if ( end != null ) { out . format ( \" <li><em>  End: </em> %s</li>%n\" , end . toString ( ) ) ; } TimeDuration duration = tc . getDuration ( ) ; if ( duration != null ) out . format ( \" <li><em>  Duration: </em> %s</li>%n\" , htmlEscaper . escape ( duration . toString ( ) ) ) ; TimeDuration resolution = tc . getResolution ( ) ; if ( resolution != null ) { out . format ( \" <li><em>  Resolution: </em> %s</li>%n\" , htmlEscaper . escape ( resolution . toString ( ) ) ) ; } out . format ( \" </ul>%n\" ) ; } java . util . List < ThreddsMetadata . MetadataOther > metadata = ds . getMetadataOther ( ) ; boolean gotSomeMetadata = false ; for ( ThreddsMetadata . MetadataOther m : metadata ) { if ( m . getXlinkHref ( ) != null ) gotSomeMetadata = true ; } if ( gotSomeMetadata ) { out . format ( \"<h3>Metadata:</h3>%n<ul>%n\" ) ; for ( ThreddsMetadata . MetadataOther m : metadata ) { String type = ( m . getType ( ) == null ) ? \"\" : m . getType ( ) ; if ( m . getXlinkHref ( ) != null ) { String title = ( m . getTitle ( ) == null ) ? \"Type \" + type : m . getTitle ( ) ; String mdLink = resolveRelativeUrls ? makeHrefResolve ( ds , m . getXlinkHref ( ) , title ) : makeHref ( m . getXlinkHref ( ) , null , title ) ; out . format ( \" <li> %s</li>%n\" , mdLink ) ; } //else { //out.format(\" <li> <pre>\"+m.getMetadataType()+\" \"+m.getContentObject()+\"</pre>%n\"); //} } out . format ( \"</ul>%n\" ) ; } java . util . List < Property > propsOrg = ds . getProperties ( ) ; java . util . List < Property > props = new ArrayList <> ( ds . getProperties ( ) . size ( ) ) ; for ( Property p : propsOrg ) { if ( ! p . getName ( ) . startsWith ( \"viewer\" ) ) // eliminate the viewer properties from the html view props . add ( p ) ; } if ( props . size ( ) > 0 ) { out . format ( \"<h3>Properties:</h3>%n<ul>%n\" ) ; for ( Property p : props ) { if ( p . getName ( ) . equals ( \"attachments\" ) ) { // LOOK whats this ? String attachLink = resolveRelativeUrls ? makeHrefResolve ( ds , p . getValue ( ) , p . getName ( ) ) : makeHref ( p . getValue ( ) , null , p . getName ( ) ) ; out . format ( \" <li>%s</li>%n\" , attachLink ) ; } else { out . format ( \" <li>%s = \\\"%s\\\"</li>%n\" , htmlEscaper . escape ( p . getName ( ) ) , htmlEscaper . escape ( p . getValue ( ) ) ) ; } } out . format ( \"</ul>%n\" ) ; } if ( complete ) out . format ( \"</body></html>\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolve reletive URLS against the catalog URL . [CODESPLIT] public String resolve ( Dataset ds , String href ) { Catalog cat = ds . getParentCatalog ( ) ; if ( cat != null ) { try { java . net . URI uri = cat . resolveUri ( href ) ; href = uri . toString ( ) ; } catch ( java . net . URISyntaxException e ) { return \"DatasetHtmlWriter: error parsing URL= \" + href ; } } return href ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the localConcept files needed to create grib1 tables for use by the CDM . [CODESPLIT] private void parseLocalConcept ( String filename , String conceptName ) throws IOException { try ( InputStream is = new FileInputStream ( filename ) ) { addLocalConcept ( is , conceptName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the information from a localConcept file to super HashMap localConcepts [CODESPLIT] private void addLocalConcept ( InputStream is , String conceptName ) throws IOException { /*\n        example entry from name.def:\n\n        #Total precipitation of at least 5 mm\n        'Total precipitation of at least 5 mm' = {\n             table2Version = 131 ;\n             indicatorOfParameter = 61 ;\n            }\n         */ try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( is , ENCODING ) ) ) { String line = br . readLine ( ) ; while ( ! line . startsWith ( \"#\" ) ) line = br . readLine ( ) ; // skip while ( true ) { HashMap < String , String > items = new HashMap <> ( ) ; line = br . readLine ( ) ; if ( line == null ) break ; // done with the file if ( ( line . length ( ) == 0 ) || line . startsWith ( \"#\" ) ) continue ; line = cleanLine ( line ) ; if ( line . contains ( \"{\" ) ) { String paramName = line . split ( \"=\" ) [ 0 ] . trim ( ) ; line = br . readLine ( ) ; if ( line == null ) break ; // done with the file line = cleanLine ( line ) ; while ( line . contains ( \"=\" ) ) { String [ ] kvp = line . split ( \"=\" ) ; items . put ( kvp [ 0 ] . trim ( ) , kvp [ 1 ] . trim ( ) ) ; line = br . readLine ( ) ; if ( line == null ) break ; // done with the file line = cleanLine ( line ) ; } String tableVersion = items . get ( TABLE_VERSION_ID ) ; String parameterNumber = items . get ( PARAM_NUM_ID ) ; storeConcept ( tableVersion , parameterNumber , conceptName , paramName ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clean the string representation of a line in the localConcept file . Basic removal of tabs semicolons single quotes etc . [CODESPLIT] private String cleanLine ( String lineIn ) { String lineOut ; lineOut = lineIn . replaceAll ( \"'\" , \"\" ) ; lineOut = lineOut . replaceAll ( \"\\t\" , \"\" ) ; lineOut = lineOut . replaceAll ( \";\" , \"\" ) ; return lineOut . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store localConcept information in super HashMap localConcepts [CODESPLIT] private void storeConcept ( String tableVersion , String parameterNumber , String key , String value ) { HashMap < String , HashMap < String , String > > tmpTable ; if ( localConcepts . containsKey ( tableVersion ) ) { tmpTable = localConcepts . get ( tableVersion ) ; if ( tmpTable . containsKey ( parameterNumber ) ) { HashMap < String , String > tmpParam = tmpTable . get ( parameterNumber ) ; if ( ! tmpParam . containsKey ( key ) ) { tmpParam . put ( key , value ) ; } else { System . out . println ( \"already has key value pair: \" + key + \":\" + value ) ; } } else { HashMap < String , String > tmpParam = new HashMap <> ( 4 ) ; tmpParam . put ( key , value ) ; tmpTable . put ( parameterNumber , tmpParam ) ; } } else { tmpTable = new HashMap <> ( ) ; HashMap < String , String > tmpParam = new HashMap <> ( 4 ) ; tmpParam . put ( key , value ) ; tmpTable . put ( parameterNumber , tmpParam ) ; } localConcepts . put ( tableVersion , tmpTable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out grib1 tables based on localConcepts files - these are the tables that the CDM will read . [CODESPLIT] private void writeGrib1Tables ( ) throws IOException { SimpleDateFormat dateFormat = new SimpleDateFormat ( \"yyyy-MM-dd'T'HH:mm:ssz\" ) ; Calendar cal = Calendar . getInstance ( ) ; String writeDate = dateFormat . format ( cal . getTime ( ) ) ; String grib1Info ; List < String > tableNums = new ArrayList <> ( ) ; HashMap < String , String > paramInfo ; Path dir = Paths . get ( ecmwfLocalConceptsLoc . replace ( \"sources/\" , \"resources/resources/grib1/\" ) ) ; for ( String tableNum : localConcepts . keySet ( ) ) { tableNums . add ( tableNum ) ; String fileName = \"2.98.\" + tableNum + \".table\" ; System . out . println ( \"Writing: \" + fileName ) ; Path newFile = dir . resolve ( fileName ) ; Files . deleteIfExists ( newFile ) ; Files . createFile ( newFile ) ; try ( BufferedWriter writer = Files . newBufferedWriter ( newFile , ENCODING ) ) { writer . write ( \"# Generated by \" + this . getClass ( ) . getCanonicalName ( ) + \" on \" + writeDate ) ; writer . newLine ( ) ; for ( String paramNum : localConcepts . get ( tableNum ) . keySet ( ) ) { paramInfo = localConcepts . get ( tableNum ) . get ( paramNum ) ; String shortName = paramInfo . get ( SHORTNAME_ID ) ; String description = paramInfo . get ( DESCRIPTION_ID ) ; String units = paramInfo . get ( UNIT_ID ) ; grib1Info = paramNum + \" \" + shortName + \" [\" + description + \"] (\" + units + \")\" ; writer . write ( grib1Info ) ; writer . newLine ( ) ; } } } writeLookupTableFile ( tableNums , dir , writeDate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the lookupTables . txt file which basically registers all of the new grib1 tables with the CDM [CODESPLIT] private void writeLookupTableFile ( List < String > tableNums , Path dir , String writeDate ) throws IOException { System . out . println ( \"Writing: lookupTables.txt\" ) ; Collections . sort ( tableNums ) ; Path lookupTableReg = dir . resolve ( \"lookupTables.txt\" ) ; Files . deleteIfExists ( lookupTableReg ) ; Files . createFile ( lookupTableReg ) ; try ( BufferedWriter writer = Files . newBufferedWriter ( lookupTableReg , ENCODING ) ) { writer . write ( \"# Generated by \" + this . getClass ( ) . getCanonicalName ( ) + \" on \" + writeDate ) ; writer . newLine ( ) ; for ( String tn : tableNums ) { String tableName = \"2.98.\" + tn + \".table\" ; String reg = \"98:\\t-1:\\t\" + tn + \":\\t\" + tableName ; writer . write ( reg ) ; writer . newLine ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Quick prinout to System . out of the different parameter metadata fields [CODESPLIT] private void showLocalConcepts ( ) { for ( String tableNum : localConcepts . keySet ( ) ) { for ( String paramNum : localConcepts . get ( tableNum ) . keySet ( ) ) { for ( String key : localConcepts . get ( tableNum ) . get ( paramNum ) . keySet ( ) ) { System . out . println ( key + \":\" + localConcepts . get ( tableNum ) . get ( paramNum ) . get ( key ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate grib1 tables for the CDM based on the localConcept files from ECMWF GRIB - API [CODESPLIT] public static void main ( String [ ] args ) { EcmwfLocalConcepts ec = new EcmwfLocalConcepts ( ) ; try { ec . writeGrib1Tables ( ) ; System . out . println ( \"Finished!\" ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////// Static ////////////////////////////////////////////////////// [CODESPLIT] public void respond ( HttpServletResponse res , FeatureDataset ft , String requestPathInfo , SubsetParams queryParams , SupportedFormat format ) throws Exception { write ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : This needs testing . [CODESPLIT] public static List < VariableSimpleIF > getWantedVariables ( FeatureDatasetPoint fdPoint , SubsetParams ncssParams ) throws VariableNotContainedInDatasetException { List < String > vars = ncssParams . getVariables ( ) ; if ( vars . size ( ) == 1 && vars . get ( 0 ) . equals ( \"all\" ) ) { return fdPoint . getDataVariables ( ) ; // Return all variables. } // restrict to these variables Map < String , VariableSimpleIF > dataVarsMap = new HashMap <> ( ) ; for ( VariableSimpleIF dataVar : fdPoint . getDataVariables ( ) ) { dataVarsMap . put ( dataVar . getShortName ( ) , dataVar ) ; } List < String > allVarNames = new ArrayList <> ( dataVarsMap . keySet ( ) ) ; List < VariableSimpleIF > wantedVars = new ArrayList <> ( ) ; for ( String varName : vars ) { if ( allVarNames . contains ( varName ) ) { VariableSimpleIF var = dataVarsMap . get ( varName ) ; wantedVars . add ( var ) ; } else { throw new VariableNotContainedInDatasetException ( \"Variable: \" + varName + \" is not contained in the requested dataset\" ) ; } } return wantedVars ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : This needs testing . [CODESPLIT] public static CalendarDateRange getWantedDateRange ( SubsetParams ncssParams ) throws NcssException { if ( ncssParams . isTrue ( SubsetParams . timePresent ) ) { // present CalendarDate time = CalendarDate . present ( ) ; CalendarPeriod timeWindow = ncssParams . getTimeWindow ( ) ; if ( timeWindow == null ) timeWindow = CalendarPeriod . Hour ; return CalendarDateRange . of ( time . subtract ( timeWindow ) , time . add ( timeWindow ) ) ; } else if ( ncssParams . getTime ( ) != null ) { // Means we want just one single time. CalendarDate time = ncssParams . getTime ( ) ; CalendarPeriod timeWindow = ncssParams . getTimeWindow ( ) ; if ( timeWindow == null ) timeWindow = CalendarPeriod . Hour ; // To prevent features from being too agressively excluded, we are accepting times that are within // an hour of the specified time. // LOOK: Do we really need the +- increment? //CalendarDate startR = CalendarDate.parseISOformat(null, time); //startR = startR.subtract(CalendarPeriod.Hour); //CalendarDate endR = CalendarDate.parseISOformat(null, time); //endR = endR.add(CalendarPeriod.Hour); return CalendarDateRange . of ( time . subtract ( timeWindow ) , time . add ( timeWindow ) ) ; } else if ( ncssParams . getTimeRange ( ) != null ) { return ncssParams . getTimeRange ( ) ; } else if ( ncssParams . isTrue ( SubsetParams . timeAll ) ) { // Client explicitly requested all times. return null ; // \"null\" means that we want ALL times, i.e. \"do not subset\". } else { // Client didn't specify a time parameter. return null ; // Do not subset. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { StructureDataRegexp . Vinfo vinfo = ( StructureDataRegexp . Vinfo ) v2 . getSPobject ( ) ; return new ArraySequence ( vinfo . sm , new SeqIter ( vinfo ) , vinfo . nelems ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////// [CODESPLIT] private void readIndex ( String indexFilename ) throws IOException { try ( FileInputStream fin = new FileInputStream ( indexFilename ) ) { if ( ! NcStream . readAndTest ( fin , MAGIC_START_IDX . getBytes ( CDM . utf8Charset ) ) ) throw new IllegalStateException ( \"bad index file\" ) ; int version = fin . read ( ) ; if ( version != 1 ) throw new IllegalStateException ( \"Bad version = \" + version ) ; int count = NcStream . readVInt ( fin ) ; for ( int i = 0 ; i < count ; i ++ ) { int size = NcStream . readVInt ( fin ) ; byte [ ] pb = new byte [ size ] ; NcStream . readFully ( fin , pb ) ; StationIndex si = decodeStationIndex ( pb ) ; map . put ( si . stnId , si ) ; } } System . out . println ( \" read index map size=\" + map . values ( ) . size ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads an Error description from the named InputStream . This method calls a generated parser to interpret an ASCII representation of an <code > Error< / code > and regenerate it as a <code > DAP2Exception< / code > . [CODESPLIT] public final boolean parse ( InputStream stream ) { Dap2Parser parser = new Dap2Parser ( new DefaultFactory ( ) ) ; String text ; try { text = DConnect2 . captureStream ( stream ) ; if ( parser . errparse ( text , this ) != Dap2Parser . DapERR ) return false ; } catch ( ParseException pe ) { this . initCause ( pe ) ; } catch ( IOException pe ) { this . initCause ( pe ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the Error message on the given <code > PrintWriter< / code > . This code can be used by servlets to throw DAP2Exception to client . [CODESPLIT] public void print ( PrintWriter os ) { os . println ( \"Error {\" ) ; os . println ( \"    code = \" + errorCode + \";\" ) ; if ( errorMessage != null ) os . println ( \"    message = \" + dumpword ( errorMessage ) + \";\" ) ; //if(programType > 0) os.println(\"    program_type = \" + programType + \";\");\r if ( programSource != null ) os . println ( \"    program = \" + dumpword ( programSource ) + \";\" ) ; os . println ( \"};\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void showFile ( TableBean bean ) { infoTA . setText ( \"Table:\" + bean . getPath ( ) + \"\\n\" ) ; try ( InputStream is = GribResourceReader . getInputStream ( bean . getPath ( ) ) ) { infoTA . appendLine ( IO . readContents ( is ) ) ; infoWindow . setVisible ( true ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the DatasetSourceType that matches this name . [CODESPLIT] public static DatasetSourceType getType ( String name ) { if ( name == null ) return null ; return ( ( DatasetSourceType ) hash . get ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : featureOfInterest / wml2 : MonitoringPoint / gml : identifier [CODESPLIT] public static CodeWithAuthorityType initIdentifier ( CodeWithAuthorityType identifier , StationTimeSeriesFeature stationFeat ) { // @codespace identifier . setCodeSpace ( \"http://unidata.ucar.edu/\" ) ; // TEXT identifier . setStringValue ( stationFeat . getName ( ) ) ; return identifier ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for this abstract class . @param name @param type @param structure @param accessPoint [CODESPLIT] public static final DatasetSource newDatasetSource ( String name , DatasetSourceType type , DatasetSourceStructure structure , String accessPoint , ResultService resultService ) { if ( type == null ) { String tmpMsg = \"DatasetSource type cannot be null\" ; logger . error ( \"newDatasetSource(): \" + tmpMsg ) ; throw new IllegalArgumentException ( tmpMsg ) ; } DatasetSource tmpDsSource = null ; if ( type == DatasetSourceType . getType ( \"Local\" ) ) { tmpDsSource = new LocalDatasetSource ( ) ; } else if ( type == DatasetSourceType . getType ( \"DodsDir\" ) ) { tmpDsSource = new DodsDirDatasetSource ( ) ; } else if ( type == DatasetSourceType . getType ( \"DodsFileServer\" ) ) { tmpDsSource = new DodsFileServerDatasetSource ( ) ; } else if ( type == DatasetSourceType . getType ( \"GrADSDataServer\" ) ) { tmpDsSource = new GrADSDataServerDatasetSource ( ) ; } else { String tmpMsg = \"Unsupported DatasetSource type <\" + type . toString ( ) + \">.\" ; logger . error ( \"newDatasetSource(): \" + tmpMsg ) ; throw new IllegalArgumentException ( tmpMsg ) ; } tmpDsSource . setName ( name ) ; tmpDsSource . setStructure ( structure ) ; tmpDsSource . setAccessPoint ( accessPoint ) ; tmpDsSource . setResultService ( resultService ) ; // Test validity and append messages to log. logger . debug ( \"DatasetSource(): constructor done.\" ) ; StringBuilder log = new StringBuilder ( ) ; if ( tmpDsSource . validate ( log ) ) { logger . debug ( \"DatasetSource(): new DatasetSource is valid: {}\" , log . toString ( ) ) ; } else { logger . debug ( \"DatasetSource(): new DatasetSource is invalid: {}\" , log . toString ( ) ) ; } return ( tmpDsSource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Crawl this DatasetSource and generate a new InvCatalog return the top - level InvDataset . [CODESPLIT] public InvDataset expand ( ) throws IOException { // Get the new catalog being generated and its top-level dataset. this . resultingCatalog = this . createSkeletonCatalog ( prefixUrlPath ) ; this . accessPointDataset = ( InvDataset ) this . resultingCatalog . getDatasets ( ) . get ( 0 ) ; // IOException thrown by createSkeletonCatalog() so this check should not be necessary. if ( ! this . isCollection ( this . accessPointDataset ) ) { String tmpMsg = \"The access point dataset <\" + this . accessPointDataset . getName ( ) + \"> must be a collection dataset.\" ; logger . warn ( \"expand(): {}\" , tmpMsg ) ; throw new IOException ( tmpMsg ) ; } // Recurse into directory structure and expand. expandRecursive ( this . accessPointDataset ) ; // Finish the catalog. ( ( InvCatalogImpl ) this . resultingCatalog ) . finish ( ) ; // Remove empty collection datasets. @todo HACK - should use filters instead. this . recursivelyRemoveEmptyCollectionDatasets ( this . accessPointDataset ) ; // Return the top-level dataset. return ( this . accessPointDataset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Crawl this DatasetSource and generate a new InvCatalog with all datasets named sorted and organized as defined by this DatasetSource return the newly generated InvCatalog . [CODESPLIT] public InvCatalog fullExpand ( ) throws IOException { logger . debug ( \"fullExpand(): expanding DatasetSource named \\\"{}\\\"\" , this . getName ( ) ) ; InvDataset topDs = this . expand ( ) ; InvCatalog generatedCat = topDs . getParentCatalog ( ) ; // Add metadata to all datasets. for ( Iterator it = this . getDatasetEnhancerList ( ) . iterator ( ) ; it . hasNext ( ) ; ) { DatasetEnhancer1 dsE = ( DatasetEnhancer1 ) it . next ( ) ; dsE . addMetadata ( topDs ) ; } // Name all datasets. logger . debug ( \"fullExpand(): naming the datasets.\" ) ; this . nameDatasets ( ( InvDatasetImpl ) topDs ) ; // Sort all datasets logger . debug ( \"fullExpand(): sorting the datasets.\" ) ; this . sortDatasets ( topDs ) ; // Return the generated catalog ( ( InvCatalogImpl ) generatedCat ) . finish ( ) ; return ( generatedCat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the list of dsNamers to name the given list of datasets . [CODESPLIT] private void nameDatasets ( InvDatasetImpl datasetContainer ) { if ( this . getDatasetNamerList ( ) . isEmpty ( ) ) return ; if ( this . isFlatten ( ) ) { logger . debug ( \"nameDatasets(): structure is FLAT calling nameDatasetList()\" ) ; this . nameDatasetList ( datasetContainer ) ; } else { logger . debug ( \"nameDatasets(): structure is DIRECTORY_TREE calling\" + \" nameDatasetTree() on each dataset in dataset container\" ) ; InvDatasetImpl curDs = null ; for ( int j = 0 ; j < datasetContainer . getDatasets ( ) . size ( ) ; j ++ ) { curDs = ( InvDatasetImpl ) datasetContainer . getDatasets ( ) . get ( j ) ; this . nameDatasetTree ( curDs ) ; } } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Name the datasets contained in the given dataset . The given dataset contains a flat list of datasets . [CODESPLIT] private void nameDatasetList ( InvDatasetImpl dataset ) { // Create temporary dataset in which to hold named datasets. InvDatasetImpl namedDs = new InvDatasetImpl ( dataset , \"nameDatastList() temp dataset\" , null , null , null ) ; // InvDatasetImpl(parentDs, name, dataType, serviceName, urlPath) dataset . addDataset ( namedDs ) ; // Loop through the DatasetNamers DatasetNamer curNamer = null ; for ( int i = 0 ; i < this . datasetNamerList . size ( ) ; i ++ ) { curNamer = ( DatasetNamer ) this . datasetNamerList . get ( i ) ; logger . debug ( \"nameDatasetList(): trying namer ({})\" , curNamer . getName ( ) ) ; // If the current DatasetNamer adds a new level, create a new dataset. InvDatasetImpl addLevelDs = null ; if ( curNamer . getAddLevel ( ) ) { addLevelDs = new InvDatasetImpl ( null , curNamer . getName ( ) , null , null , null ) ; } // Iterate over remaining unnamed datasets. InvDatasetImpl curDs = null ; java . util . Iterator dsIter = dataset . getDatasets ( ) . iterator ( ) ; while ( dsIter . hasNext ( ) ) { curDs = ( InvDatasetImpl ) dsIter . next ( ) ; logger . debug ( \"nameDatasetList(): try namer on this ds ({}-{})\" , curDs . getName ( ) , curDs . getUrlPath ( ) ) ; // Try to name the current dataset. if ( curNamer . nameDataset ( curDs ) ) { logger . debug ( \"nameDatasetList(): ds named ({})\" , curDs . getName ( ) ) ; // If adding a level, add named datasets to the added level dataset. if ( curNamer . getAddLevel ( ) ) { addLevelDs . addDataset ( curDs ) ; } // Otherwise, add the named datasets to namedDs. else { namedDs . addDataset ( curDs ) ; } // Remove the now-named dataset from list of unnamed datasets. dsIter . remove ( ) ; } } // END - InvDatasetImpl loop // If the namer added a level and a dataset was named by this namer, add the // new level to the list of named datasets. if ( curNamer . getAddLevel ( ) ) { if ( addLevelDs . hasNestedDatasets ( ) ) { namedDs . addDataset ( addLevelDs ) ; } } } // END - DatasetNamer loop namedDs . finish ( ) ; // Once all datasets are named (or unnamable with these DatasetNamers), // add all the datasets in namedDs back into the given containerDataset. if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"nameDatasetList(): number of unnamed datasets is \" + dataset . getDatasets ( ) . size ( ) + \".\" ) ; logger . debug ( \"nameDatasetList(): add named datasets back to container.\" ) ; } for ( int i = 0 ; i < namedDs . getDatasets ( ) . size ( ) ; i ++ ) { dataset . addDataset ( ( InvDatasetImpl ) namedDs . getDatasets ( ) . get ( i ) ) ; } dataset . removeDataset ( namedDs ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Name the datasets in the given dataset hierarchy using this DatasetSource s list of datasetNamers . [CODESPLIT] private void nameDatasetTree ( InvDatasetImpl dataset ) { // If dataset does not have a name, try naming it with dsNamers. // @todo Rethink naming of directories (look at how DatasetFilter deals with collection vs atomic datasets). if ( dataset . getName ( ) . equals ( \"\" ) || ! dataset . hasAccess ( ) ) { logger . debug ( \"nameDatasetTree(): naming dataset ({})...\" , dataset . getUrlPath ( ) ) ; DatasetNamer dsN = null ; for ( int i = 0 ; i < this . datasetNamerList . size ( ) ; i ++ ) { dsN = ( DatasetNamer ) this . datasetNamerList . get ( i ) ; if ( dsN . nameDataset ( dataset ) ) { logger . debug ( \"nameDatasetTree(): ... used namer ({})\" , dsN . getName ( ) ) ; break ; } } } // Try to name any child datasets. InvDatasetImpl curDs = null ; for ( int j = 0 ; j < dataset . getDatasets ( ) . size ( ) ; j ++ ) { curDs = ( InvDatasetImpl ) dataset . getDatasets ( ) . get ( j ) ; logger . debug ( \"nameDatasetTree(): recurse to name child dataset ({})\" , curDs . getUrlPath ( ) ) ; this . nameDatasetTree ( curDs ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to invoke with a filename or URL of a picture that is to be loaded and scaled in a new thread . This is handy to update the screen while the loading chuggs along in the background . Make sure you invoked setScaleFactor or setScaleSize before invoking this method . <p / > Step 1 : Am I already loading what I need somewhere? If yes - > use it . Has it finished loading? If no - > wait for it If yes - > use it Else - > load it [CODESPLIT] public void loadAndScalePictureInThread ( URL imageUrl , int priority , double rotation ) { this . imageUrl = imageUrl ; boolean alreadyLoading = false ; Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: checking if picture \" + imageUrl + \" is already being loaded.\" ) ; if ( ( sourcePicture != null ) && ( sourcePicture . getUrl ( ) . toString ( ) . equals ( imageUrl . toString ( ) ) ) ) { Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: the SourcePicture is already loading the sourcePictureimage\" ) ; alreadyLoading = true ; } else if ( PictureCache . isInCache ( imageUrl ) ) { // in case the old image has a listener connected remove it\r //  fist time round the sourcePicture is still null therefore the if.\r if ( sourcePicture != null ) sourcePicture . removeListener ( this ) ; sourcePicture = PictureCache . getSourcePicture ( imageUrl ) ; String status = sourcePicture . getStatusMessage ( ) ; if ( status == null ) status = \"\" ; Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: Picture in cache! Status: \" + status ) ; if ( sourcePicture . getRotation ( ) == rotation ) { alreadyLoading = true ; Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: Picture was even rotated to the correct angle!\" ) ; } else { alreadyLoading = false ; Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: Picture was in cache but with wrong rotation. Forcing reload.\" ) ; } } if ( alreadyLoading ) { switch ( sourcePicture . getStatusCode ( ) ) { case SourcePicture . UNINITIALISED : alreadyLoading = false ; Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: pictureStatus was: UNINITIALISED\" ) ; break ; case SourcePicture . ERROR : alreadyLoading = false ; Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: pictureStatus was: ERROR\" ) ; break ; case SourcePicture . LOADING : Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: pictureStatus was: LOADING\" ) ; sourcePicture . addListener ( this ) ; setStatus ( LOADING , \"Loading: \" + imageUrl . toString ( ) ) ; sourceLoadProgressNotification ( SourcePicture . LOADING_PROGRESS , sourcePicture . getPercentLoaded ( ) ) ; scaleAfterLoad = true ; break ; case SourcePicture . ROTATING : Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: pictureStatus was: ROTATING\" ) ; setStatus ( LOADING , \"Rotating: \" + imageUrl . toString ( ) ) ; sourceLoadProgressNotification ( SourcePicture . LOADING_PROGRESS , sourcePicture . getPercentLoaded ( ) ) ; scaleAfterLoad = true ; break ; case SourcePicture . READY : Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: pictureStatus was: READY. Sending SCALING status.\" ) ; setStatus ( SCALING , \"Scaling: \" + imageUrl . toString ( ) ) ; createScaledPictureInThread ( priority ) ; break ; default : Tools . log ( \"ScalablePicture.loadAndScalePictureInThread: Don't know what status this is:\" + Integer . toString ( sourcePicture . getStatusCode ( ) ) ) ; break ; } } // if the image is not already there then load it.\r if ( ! alreadyLoading ) { if ( sourcePicture != null ) sourcePicture . removeListener ( this ) ; sourcePicture = new SourcePicture ( ) ; sourcePicture . addListener ( this ) ; setStatus ( LOADING , \"Loading: \" + imageUrl . toString ( ) ) ; scaleAfterLoad = true ; sourcePicture . loadPictureInThread ( imageUrl , priority , rotation ) ; // when the thread is done it sends a sourceStatusChange message to us\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchroneous method to load the image . It should only be called by something which is a thread itself such as the HtmlDistillerThread . Since this intended for large batch operations this bypasses the cache . [CODESPLIT] public void loadPictureImd ( URL imageUrl , double rotation ) { Tools . log ( \"loadPictureImd invoked with URL: \" + imageUrl . toString ( ) ) ; if ( sourcePicture != null ) sourcePicture . removeListener ( this ) ; sourcePicture = new SourcePicture ( ) ; sourcePicture . addListener ( this ) ; setStatus ( LOADING , \"Loading: \" + imageUrl . toString ( ) ) ; scaleAfterLoad = true ; sourcePicture . loadPicture ( imageUrl , rotation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stops all picture loading except if the Url we desire is being loaded [CODESPLIT] public void stopLoadingExcept ( URL url ) { if ( sourcePicture != null ) { boolean isCurrentlyLoading = sourcePicture . stopLoadingExcept ( url ) ; if ( ! isCurrentlyLoading ) { // sourcePicture.removeListener( this );\r } PictureCache . stopBackgroundLoadingExcept ( url ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that is invoked by the SourcePictureListener interface . Usually this will be called by the SourcePicture telling the ScalablePicture that it has completed loading . The ScalablePicture should then change it s own status and tell the ScalableListeners what s up . [CODESPLIT] public void sourceStatusChange ( int statusCode , String statusMessage , SourcePicture sp ) { //Tools.log(\"ScalablePicture.sourceStatusChange: status received from SourceImage: \" + statusMessage);\r switch ( statusCode ) { case SourcePicture . UNINITIALISED : Tools . log ( \"ScalablePicture.sourceStatusChange: pictureStatus was: UNINITIALISED message: \" + statusMessage ) ; setStatus ( UNINITIALISED , statusMessage ) ; break ; case SourcePicture . ERROR : Tools . log ( \"ScalablePicture.sourceStatusChange: pictureStatus was: ERROR message: \" + statusMessage ) ; setStatus ( ERROR , statusMessage ) ; sourcePicture . removeListener ( this ) ; break ; case SourcePicture . LOADING : Tools . log ( \"ScalablePicture.sourceStatusChange: pictureStatus was: LOADING message: \" + statusMessage ) ; setStatus ( LOADING , statusMessage ) ; break ; case SourcePicture . ROTATING : Tools . log ( \"ScalablePicture.sourceStatusChange: pictureStatus was: ROTATING message: \" + statusMessage ) ; setStatus ( LOADING , statusMessage ) ; break ; case SourcePicture . READY : Tools . log ( \"ScalablePicture.sourceStatusChange: pictureStatus was: READY message: \" + statusMessage ) ; setStatus ( LOADED , statusMessage ) ; sourcePicture . removeListener ( this ) ; if ( scaleAfterLoad ) { createScaledPictureInThread ( Thread . MAX_PRIORITY ) ; scaleAfterLoad = false ; } break ; default : Tools . log ( \"ScalablePicture.sourceStatusChange: Don't recognize this status: \" + statusMessage ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pass on the update on the loading Progress to the listening objects [CODESPLIT] public void sourceLoadProgressNotification ( int statusCode , int percentage ) { Enumeration e = scalablePictureStatusListeners . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( ScalablePictureListener ) e . nextElement ( ) ) . sourceLoadProgressNotification ( statusCode , percentage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that creates the scaled image in the background in it s own thread . [CODESPLIT] public void createScaledPictureInThread ( int priority ) { setStatus ( SCALING , \"Scaling picture.\" ) ; ScaleThread t = new ScaleThread ( this ) ; t . setPriority ( priority ) ; t . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the size of the scaled image or Zero if there is none [CODESPLIT] public Dimension getScaledSize ( ) { if ( scaledPicture != null ) return new Dimension ( scaledPicture . getWidth ( ) , scaledPicture . getHeight ( ) ) ; else return new Dimension ( 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the size of the scaled image as a neatly formatted text or Zero if there is none [CODESPLIT] public String getScaledSizeString ( ) { if ( scaledPicture != null ) return Integer . toString ( scaledPicture . getWidth ( ) ) + \" x \" + Integer . toString ( scaledPicture . getHeight ( ) ) ; else return \"0 x 0\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This static method writes the indicated renderedImage ( BufferedImage ) to the indicated file . [CODESPLIT] public static void writeJpg ( File writeFile , RenderedImage renderedImage , float jpgQuality ) { Iterator writers = ImageIO . getImageWritersByFormatName ( \"jpg\" ) ; ImageWriter writer = ( ImageWriter ) writers . next ( ) ; JPEGImageWriteParam params = new JPEGImageWriteParam ( null ) ; params . setCompressionMode ( ImageWriteParam . MODE_EXPLICIT ) ; params . setCompressionQuality ( jpgQuality ) ; params . setProgressiveMode ( ImageWriteParam . MODE_DISABLED ) ; params . setDestinationType ( new ImageTypeSpecifier ( java . awt . image . IndexColorModel . getRGBdefault ( ) , IndexColorModel . getRGBdefault ( ) . createCompatibleSampleModel ( 16 , 16 ) ) ) ; try ( ImageOutputStream ios = ImageIO . createImageOutputStream ( new FileOutputStream ( writeFile ) ) ) { writer . setOutput ( ios ) ; writer . write ( null , new IIOImage ( renderedImage , null , null ) , params ) ; ios . close ( ) ; } catch ( IOException e ) { //Tools.log(\"ScalablePicture.writeJpg caught IOException: \" +  e.getMessage() + \"\\nwhile writing \" + writeFile.toString());\r e . printStackTrace ( ) ; } //writer = null;\r writer . dispose ( ) ; //1.4.1 documentation says to do this.\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that sets the status of the ScalablePicture object and notifies intereasted objects of a change in status ( not built yet ) . [CODESPLIT] private void setStatus ( int statusCode , String statusMessage ) { String filename = ( imageUrl == null ) ? \"\" : imageUrl . toString ( ) ; Tools . log ( \"ScalablePicture.setStatus: sending: \" + statusMessage + \" to all Listeners from Image: \" + filename ) ; pictureStatusCode = statusCode ; pictureStatusMessage = statusMessage ; Enumeration e = scalablePictureStatusListeners . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( ScalablePictureListener ) e . nextElement ( ) ) . scalableStatusChange ( pictureStatusCode , pictureStatusMessage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public static GempakSoundingFileReader getInstance ( RandomAccessFile raf , boolean fullCheck ) throws IOException { GempakSoundingFileReader gsfr = new GempakSoundingFileReader ( ) ; gsfr . init ( raf , fullCheck ) ; return gsfr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { if ( ! super . init ( fullCheck ) ) { return false ; } // Modeled after SN_OFIL\r if ( dmLabel . kftype != MFSN ) { logError ( \"not a sounding data file \" ) ; return false ; } DMPart part = getPart ( SNDT ) ; if ( part != null ) { // merged file\r subType = MERGED ; String vertName = part . params . get ( 0 ) . kprmnm ; switch ( vertName ) { case \"PRES\" : ivert = PRES_COORD ; break ; case \"THTA\" : ivert = THTA_COORD ; break ; case \"HGHT\" : case \"MHGT\" : case \"DHGT\" : ivert = HGHT_COORD ; break ; default : logError ( \"unknown vertical coordinate in merged file\" ) ; return false ; } } else { unmergedParts = SN_CKUA ( ) ; boolean haveUnMerged = ! unmergedParts . isEmpty ( ) ; if ( ! haveUnMerged ) { logError ( \"unknown sounding file type - not merged/unmerged\" ) ; return false ; } else { ivert = PRES_COORD ; subType = UNMERGED ; } } if ( ! readStationsAndTimes ( true ) ) { logError ( \"Unable to read stations and times\" ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of merged parts in this file [CODESPLIT] public List < String > getMergedParts ( ) { List < String > list = new ArrayList <> ( 1 ) ; list . add ( SNDT ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the list of dates in the file [CODESPLIT] public void printOb ( int row , int col ) { GempakStation station = getStations ( ) . get ( col - 1 ) ; String time = getDateString ( row - 1 ) ; StringBuilder builder = new StringBuilder ( \"\\n\" ) ; builder . append ( makeHeader ( station , time ) ) ; builder . append ( \"\\n\" ) ; boolean merge = getFileSubType ( ) . equals ( MERGED ) ; List < String > parts ; if ( merge ) { parts = new ArrayList <> ( ) ; parts . add ( SNDT ) ; } else { parts = unmergedParts ; } for ( String part : parts ) { RData rd ; try { rd = DM_RDTR ( row , col , part ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; rd = null ; } if ( rd == null ) { continue ; } if ( ! merge ) { builder . append ( \"    \" ) ; builder . append ( part ) ; builder . append ( \"    \" ) ; builder . append ( time . substring ( time . indexOf ( \"/\" ) + 1 ) ) ; } builder . append ( \"\\n\" ) ; if ( ! merge ) { builder . append ( \"\\t\" ) ; } List < GempakParameter > params = getParameters ( part ) ; for ( GempakParameter parm : params ) { builder . append ( StringUtil2 . padLeft ( parm . getName ( ) , 7 ) ) ; builder . append ( \"\\t\" ) ; } builder . append ( \"\\n\" ) ; if ( ! merge ) { builder . append ( \"\\t\" ) ; } float [ ] data = rd . data ; int numParams = params . size ( ) ; int numLevels = data . length / numParams ; for ( int j = 0 ; j < numLevels ; j ++ ) { for ( int i = 0 ; i < numParams ; i ++ ) { builder . append ( StringUtil2 . padLeft ( Format . formatDouble ( data [ j * numParams + i ] , 7 , 1 ) , 7 ) ) ; builder . append ( \"\\t\" ) ; } builder . append ( \"\\n\" ) ; if ( ! merge ) { builder . append ( \"\\t\" ) ; } } builder . append ( \"\\n\" ) ; } builder . append ( \"\\n\" ) ; System . out . println ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the header for the text report [CODESPLIT] private String makeHeader ( GempakStation stn , String date ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( \"STID = \" ) ; builder . append ( StringUtil2 . padRight ( ( stn . getSTID ( ) . trim ( ) + stn . getSTD2 ( ) . trim ( ) ) , 8 ) ) ; builder . append ( \"\\t\" ) ; builder . append ( \"STNM = \" ) ; builder . append ( Format . i ( stn . getSTNM ( ) , 6 ) ) ; builder . append ( \"\\t\" ) ; builder . append ( \"TIME = \" ) ; builder . append ( date ) ; builder . append ( \"\\n\" ) ; builder . append ( \"SLAT = \" ) ; builder . append ( Format . d ( stn . getLatitude ( ) , 5 ) ) ; builder . append ( \"\\t\" ) ; builder . append ( \"SLON = \" ) ; builder . append ( Format . d ( stn . getLongitude ( ) , 5 ) ) ; builder . append ( \"\\t\" ) ; builder . append ( \"SELV = \" ) ; builder . append ( Format . d ( stn . getAltitude ( ) , 5 ) ) ; builder . append ( \"\\n\" ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This subroutine checks the parts in a sounding data set for the unmerged data types . [CODESPLIT] private List < String > SN_CKUA ( ) { List < String > types = new ArrayList <> ( ) ; boolean above = false ; boolean done = false ; String partToCheck ; while ( ! done ) { // check for mandatory groups\r for ( int group = 0 ; group < belowGroups . length ; group ++ ) { if ( above ) { partToCheck = aboveGroups [ group ] ; } else { partToCheck = belowGroups [ group ] ; } if ( checkForValidGroup ( partToCheck , parmLists [ group ] ) ) { types . add ( partToCheck ) ; } } if ( ! above ) { above = true ; } else { done = true ; } } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for valid groups [CODESPLIT] private boolean checkForValidGroup ( String partToCheck , String [ ] params ) { DMPart part = getPart ( partToCheck ) ; if ( part == null ) { return false ; } int i = 0 ; for ( DMParam parm : part . params ) { if ( ! ( parm . kprmnm . equals ( params [ i ++ ] ) ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the program [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length == 0 ) { System . out . println ( \"need to supply a GEMPAK sounding file name\" ) ; System . exit ( 1 ) ; } try { GempakParameters . addParameters ( \"resources/nj22/tables/gempak/params.tbl\" ) ; } catch ( Exception e ) { System . out . println ( \"unable to init param tables\" ) ; } GempakSoundingFileReader gsfr = getInstance ( getFile ( args [ 0 ] ) , true ) ; System . out . println ( \"Type = \" + gsfr . getFileType ( ) ) ; gsfr . printFileLabel ( ) ; gsfr . printKeys ( ) ; gsfr . printHeaders ( ) ; gsfr . printParts ( ) ; gsfr . printDates ( ) ; gsfr . printStations ( false ) ; int row = 1 ; int col = 1 ; if ( args . length > 1 ) { row = Integer . parseInt ( args [ 1 ] ) ; } if ( args . length > 2 ) { try { col = Integer . parseInt ( args [ 2 ] ) ; } catch ( Exception npe ) { col = gsfr . findStationIndex ( args [ 2 ] ) ; if ( col == - 1 ) { System . out . println ( \"couldn't find station \" + args [ 2 ] ) ; System . exit ( 1 ) ; } System . out . println ( \"found station at column \" + col ) ; } } gsfr . printOb ( row , col ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the cache root directory . Create it if it doesnt exist . [CODESPLIT] static public void setRootDirectory ( String cacheDir ) { if ( ! cacheDir . endsWith ( \"/\" ) ) cacheDir = cacheDir + \"/\" ; root = StringUtil2 . replace ( cacheDir , ' ' , \"/\" ) ; // no nasty backslash\r makeRootDirectory ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make sure that the current root directory exists . [CODESPLIT] static public void makeRootDirectory ( ) { File dir = new File ( root ) ; if ( ! dir . exists ( ) ) if ( ! dir . mkdirs ( ) ) throw new IllegalStateException ( \"DiskCache.setRootDirectory(): could not create root directory <\" + root + \">.\" ) ; checkExist = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a File if it exists . If not get a File that can be written to . If alwaysInCache look only in the cache otherwise look in the normal location first then in the cache . <p > [CODESPLIT] static public File getFile ( String fileLocation , boolean alwaysInCache ) { if ( alwaysInCache ) { return getCacheFile ( fileLocation ) ; } else { File f = new File ( fileLocation ) ; if ( f . exists ( ) ) return f ; // now comes the tricky part to make sure we can open and write to it\r try { if ( ! simulateUnwritableDir && f . createNewFile ( ) ) { boolean ret = f . delete ( ) ; assert ret ; return f ; } } catch ( IOException e ) { // cant write to it - drop through\r } return getCacheFile ( fileLocation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a file in the cache . File may or may not exist . We assume its always writeable . If it does exist set its LastModifiedDate to current time . [CODESPLIT] static public File getCacheFile ( String fileLocation ) { File f = new File ( makeCachePath ( fileLocation ) ) ; if ( f . exists ( ) ) { if ( ! f . setLastModified ( System . currentTimeMillis ( ) ) ) logger . warn ( \"Failed to setLastModified on \" + f . getPath ( ) ) ; } if ( ! checkExist ) { File dir = f . getParentFile ( ) ; if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) logger . warn ( \"Failed to mkdirs on \" + dir . getPath ( ) ) ; checkExist = true ; } return f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the cache filename [CODESPLIT] static private String makeCachePath ( String fileLocation ) { Escaper urlPathEscaper = UrlEscapers . urlPathSegmentEscaper ( ) ; fileLocation = fileLocation . replace ( ' ' , ' ' ) ; // LOOK - use better normalization code  eg Spring StringUtils\r String cachePath = urlPathEscaper . escape ( fileLocation ) ; return root + cachePath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all files with date < cutoff . [CODESPLIT] static public void cleanCache ( Date cutoff , StringBuilder sbuff ) { if ( sbuff != null ) sbuff . append ( \"CleanCache files before \" ) . append ( cutoff ) . append ( \"\\n\" ) ; File dir = new File ( root ) ; File [ ] children = dir . listFiles ( ) ; if ( children == null ) return ; for ( File file : children ) { Date lastMod = new Date ( file . lastModified ( ) ) ; if ( lastMod . before ( cutoff ) ) { boolean ret = file . delete ( ) ; if ( sbuff != null ) { sbuff . append ( \" delete \" ) . append ( file ) . append ( \" (\" ) . append ( lastMod ) . append ( \")\\n\" ) ; if ( ! ret ) sbuff . append ( \"Error deleting \" ) . append ( file ) . append ( \"\\n\" ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove files if needed to make cache have less than maxBytes bytes file sizes . This will remove files in sort order defined by fileComparator . The first files in the sort order are kept until the max bytes is exceeded then they are deleted . [CODESPLIT] static public void cleanCache ( long maxBytes , Comparator < File > fileComparator , StringBuilder sbuff ) { if ( sbuff != null ) sbuff . append ( \"DiskCache clean maxBytes= \" ) . append ( maxBytes ) . append ( \"on dir \" ) . append ( root ) . append ( \"\\n\" ) ; File dir = new File ( root ) ; long total = 0 , total_delete = 0 ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) { List < File > fileList = Arrays . asList ( files ) ; Collections . sort ( fileList , fileComparator ) ; for ( File file : fileList ) { if ( file . length ( ) + total > maxBytes ) { total_delete += file . length ( ) ; if ( sbuff != null ) sbuff . append ( \" delete \" ) . append ( file ) . append ( \" (\" ) . append ( file . length ( ) ) . append ( \")\\n\" ) ; if ( ! file . delete ( ) && sbuff != null ) sbuff . append ( \"Error deleting \" ) . append ( file ) . append ( \"\\n\" ) ; } else { total += file . length ( ) ; } } } if ( sbuff != null ) { sbuff . append ( \"Total bytes deleted= \" ) . append ( total_delete ) . append ( \"\\n\" ) ; sbuff . append ( \"Total bytes left in cache= \" ) . append ( total ) . append ( \"\\n\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debug [CODESPLIT] static void make ( String filename ) throws IOException { File want = DiskCache . getCacheFile ( filename ) ; System . out . println ( \"make=\" + want . getPath ( ) + \"; exists = \" + want . exists ( ) ) ; if ( ! want . exists ( ) ) { boolean ret = want . createNewFile ( ) ; assert ret ; } System . out . println ( \" canRead= \" + want . canRead ( ) + \" canWrite = \" + want . canWrite ( ) + \" lastMod = \" + new Date ( want . lastModified ( ) ) ) ; System . out . println ( \" original=\" + filename ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the named Icon from the default resource ( jar file ) . [CODESPLIT] public static ImageIcon getIcon ( String name , boolean errMsg ) { ImageIcon ii = Resource . getIcon ( defaultResourcePath + name + \".gif\" , errMsg ) ; if ( ii == null ) Resource . getIcon ( defaultResourcePath + name + \".png\" , errMsg ) ; return ii ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the named Image from the default resource ( jar file ) . [CODESPLIT] public static Image getImage ( String name ) { Image ii ; if ( name . endsWith ( \".png\" ) || name . endsWith ( \".jpg\" ) || name . endsWith ( \".gif\" ) ) ii = Resource . getImage ( defaultResourcePath + name ) ; else ii = Resource . getImage ( defaultResourcePath + name + \".gif\" ) ; return ii ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a buttcon = button with an Icon [CODESPLIT] public static AbstractButton makeButtcon ( Icon icon , Icon selected , String tooltip , boolean is_toggle ) { AbstractButton butt ; if ( is_toggle ) butt = new JToggleButton ( ) ; else butt = new JButton ( ) ; if ( debug ) System . out . println ( \"   makeButtcon\" + icon + \" \" + selected + \" \" + tooltip + \" \" + is_toggle ) ; if ( icon != null ) butt . setIcon ( icon ) ; if ( selected != null ) { if ( is_toggle ) { butt . setSelectedIcon ( selected ) ; } else { butt . setRolloverIcon ( selected ) ; butt . setRolloverSelectedIcon ( selected ) ; butt . setPressedIcon ( selected ) ; butt . setRolloverEnabled ( true ) ; } } butt . setMaximumSize ( new Dimension ( 28 , 28 ) ) ; // kludge butt . setPreferredSize ( new Dimension ( 28 , 28 ) ) ; butt . setToolTipText ( tooltip ) ; butt . setFocusPainted ( false ) ; return butt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a buttcon = button with an Icon [CODESPLIT] public static AbstractButton makeButtcon ( String iconName , String tooltip , boolean is_toggle ) { Icon icon = getIcon ( iconName , false ) ; Icon iconSel = getIcon ( iconName + \"Sel\" , false ) ; return makeButtcon ( icon , iconSel , tooltip , is_toggle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NB : doesnt add action to MenuItem [CODESPLIT] private static JMenuItem makeMenuItemFromAction ( Action act ) { // this prevents null pointer exception if user didnt call setProperties() Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; Integer mnu = ( Integer ) act . getValue ( BAMutil . MNEMONIC ) ; int mnemonic = ( tog == null ) ? - 1 : mnu . intValue ( ) ; Integer acc = ( Integer ) act . getValue ( BAMutil . ACCEL ) ; int accel = ( acc == null ) ? 0 : acc . intValue ( ) ; return makeMenuItem ( ( Icon ) act . getValue ( Action . SMALL_ICON ) , ( Icon ) act . getValue ( BAMutil . SELECTED_ICON ) , ( String ) act . getValue ( Action . SHORT_DESCRIPTION ) , is_toggle , mnemonic , accel < 0 ? 0 : accel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a MenuItem using the given Action and adds it to the given Menu . Uses Properties that have been set on the Action ( see setActionProperties () ) . All are optional except for Action . SHORT_DESCRIPTION : <pre > Action . SHORT_DESCRIPTION String MenuItem text ( required ) Action . SMALL_ICON Icon the Icon to Use BAMutil . SELECTED_ICON Icon the Icon when selected ( optional ) BAMutil . TOGGLE Boolean true if its a toggle BAMutil . MNEMONIC Integer menu item shortcut BAMutil . ACCEL Integer menu item global keyboard accelerator < / pre > <br > The Action is triggered when the MenuItem is selected . Enabling and disabling the Action does the same for the MenuItem . For toggles state is maintained in the Action and MenuItem state changes when the Action state changes . <br > <br > The point of all this is that once you set it up you work exclusively with the action object and all changes are automatically reflected in the UI . [CODESPLIT] public static JMenuItem addActionToMenu ( JMenu menu , Action act , int menuPos ) { JMenuItem mi = makeMenuItemFromAction ( act ) ; if ( menuPos >= 0 ) menu . add ( mi , menuPos ) ; else menu . add ( mi ) ; Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; // set state for toggle buttons if ( is_toggle ) { if ( debugToggle ) System . out . println ( \"addActionToMenu: \" + act . getValue ( Action . SHORT_DESCRIPTION ) + \" \" + act . getValue ( BAMutil . STATE ) ) ; Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; if ( state == null ) state = Boolean . FALSE ; act . putValue ( BAMutil . STATE , state ) ; mi . setSelected ( state . booleanValue ( ) ) ; } // add event listeners Action myAct = is_toggle ? new ToggleAction ( act ) : act ; mi . addActionListener ( myAct ) ; act . addPropertyChangeListener ( new myActionChangedListener ( mi ) ) ; return mi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NB : doesnt add action to button [CODESPLIT] private static AbstractButton _makeButtconFromAction ( Action act ) { // this prevents null pointer exception if user didnt call setProperties() Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; return makeButtcon ( ( Icon ) act . getValue ( Action . SMALL_ICON ) , ( Icon ) act . getValue ( BAMutil . SELECTED_ICON ) , ( String ) act . getValue ( Action . SHORT_DESCRIPTION ) , is_toggle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates an AbstractButton using the given Action and adds it to the given Container at the position .. Uses Properties that have been set on the Action ( see setActionProperties () ) . All are optional except for Action . SMALL_ICON : <pre > Action . SMALL_ICON Icon the Icon to Use ( required ) BAMutil . SELECTED_ICON Icon the Icon when selected ( optional ) Action . SHORT_DESCRIPTION String tooltip BAMutil . TOGGLE Boolean true if its a toggle < / pre > <br > The Action is triggered when the Button is selected . Enabling and disabling the Action does the same for the Button . For toggles state is maintained in the Action and the Button state changes when the Action state changes . <br > <br > The point of all this is that once you set it up you work exclusively with the action object and all changes are automatically reflected in the UI . [CODESPLIT] public static AbstractButton addActionToContainerPos ( Container c , Action act , int pos ) { AbstractButton butt = _makeButtconFromAction ( act ) ; if ( pos < 0 ) c . add ( butt ) ; else c . add ( butt , pos ) ; if ( debug ) System . out . println ( \" addActionToContainerPos \" + act + \" \" + butt + \" \" + pos ) ; Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; // set state for toggle buttons if ( is_toggle ) { if ( debugToggle ) System . out . println ( \"addActionToContainerPos: \" + act . getValue ( Action . SHORT_DESCRIPTION ) + \" \" + act . getValue ( BAMutil . STATE ) ) ; Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; if ( state == null ) state = Boolean . FALSE ; act . putValue ( BAMutil . STATE , state ) ; butt . setSelected ( state . booleanValue ( ) ) ; } // add event listsners Action myAct = is_toggle ? new ToggleAction ( act ) : act ; butt . addActionListener ( myAct ) ; act . addPropertyChangeListener ( new myActionChangedListener ( butt ) ) ; return butt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Standard way to set Properties for Actions . This also looks for an Icon <icon_name > Sel and if it exists : 1 ) sets SelectedIcon if its a toggle or 2 ) sets the Icon when selected ( optional ) if its not a toggle [CODESPLIT] public static void setActionProperties ( AbstractAction act , String icon_name , String action_name , boolean is_toggle , int mnemonic , int accel ) { if ( icon_name != null ) { act . putValue ( Action . SMALL_ICON , getIcon ( icon_name , true ) ) ; act . putValue ( BAMutil . SELECTED_ICON , getIcon ( icon_name + \"Sel\" , false ) ) ; } act . putValue ( Action . SHORT_DESCRIPTION , action_name ) ; act . putValue ( Action . LONG_DESCRIPTION , action_name ) ; act . putValue ( BAMutil . TOGGLE , new Boolean ( is_toggle ) ) ; act . putValue ( BAMutil . MNEMONIC , new Integer ( mnemonic ) ) ; act . putValue ( BAMutil . ACCEL , new Integer ( accel ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Standard way to set Properties and state for Toggle Actions . * [CODESPLIT] public static void setActionPropertiesToggle ( AbstractAction act , String icon_name , String action_name , boolean toggleValue , int mnemonic , int accel ) { setActionProperties ( act , icon_name , action_name , true , mnemonic , accel ) ; act . putValue ( BAMutil . STATE , new Boolean ( toggleValue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK could do better : all and maybe HashSet<Name > [CODESPLIT] public static List < StationFeature > getStationsInSubset ( StationTimeSeriesFeatureCollection stationFeatCol , SubsetParams ncssParams ) throws IOException { List < StationFeature > wantedStations ; // verify SpatialSelection has some stations if ( ncssParams . getStations ( ) != null ) { List < String > stnNames = ncssParams . getStations ( ) ; if ( stnNames . get ( 0 ) . equals ( \"all\" ) ) { wantedStations = stationFeatCol . getStationFeatures ( ) ; } else { wantedStations = stationFeatCol . getStationFeatures ( stnNames ) ; } } else if ( ncssParams . getLatLonBoundingBox ( ) != null ) { LatLonRect llrect = ncssParams . getLatLonBoundingBox ( ) ; wantedStations = stationFeatCol . getStationFeatures ( llrect ) ; } else if ( ncssParams . getLatLonPoint ( ) != null ) { Station closestStation = findClosestStation ( stationFeatCol , ncssParams . getLatLonPoint ( ) ) ; List < String > stnList = new ArrayList <> ( ) ; stnList . add ( closestStation . getName ( ) ) ; wantedStations = stationFeatCol . getStationFeatures ( stnList ) ; } else { // Want all. wantedStations = stationFeatCol . getStationFeatures ( ) ; } return wantedStations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Find the station closest to the specified point . The metric is ( lat - lat0 ) ** 2 + ( cos ( lat0 ) * ( lon - lon0 )) ** 2 [CODESPLIT] public static Station findClosestStation ( StationTimeSeriesFeatureCollection stationFeatCol , LatLonPoint pt ) throws IOException { double lat = pt . getLatitude ( ) ; double lon = pt . getLongitude ( ) ; double cos = Math . cos ( Math . toRadians ( lat ) ) ; List < StationFeature > stations = stationFeatCol . getStationFeatures ( ) ; Station min_station = stations . get ( 0 ) ; double min_dist = Double . MAX_VALUE ; for ( Station s : stations ) { double lat1 = s . getLatitude ( ) ; double lon1 = LatLonPointImpl . lonNormal ( s . getLongitude ( ) , lon ) ; double dy = Math . toRadians ( lat - lat1 ) ; double dx = cos * Math . toRadians ( lon - lon1 ) ; double dist = dy * dy + dx * dx ; if ( dist < min_dist ) { min_dist = dist ; min_station = s ; } } return min_station ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "contains a BUFR table entry [CODESPLIT] static public boolean isBufrTable ( short fxy ) { int f = ( fxy & 0xC000 ) >> 14 ; int x = ( fxy & 0x3F00 ) >> 8 ; int y = ( fxy & 0xFF ) ; return ( f == 0 ) && ( x == 0 ) && ( y < 13 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a coordinate axis from an existing Variable . [CODESPLIT] static public CoordinateAxis factory ( NetcdfDataset ncd , VariableDS vds ) { if ( ( vds . getRank ( ) == 0 ) || ( vds . getRank ( ) == 1 ) || ( vds . getRank ( ) == 2 && vds . getDataType ( ) == DataType . CHAR ) ) { return new CoordinateAxis1D ( ncd , vds ) ; } else if ( vds . getRank ( ) == 2 ) return new CoordinateAxis2D ( ncd , vds ) ; else return new CoordinateAxis ( ncd , vds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a copy with an independent cache . [CODESPLIT] public CoordinateAxis copyNoCache ( ) { CoordinateAxis axis = new CoordinateAxis ( ncd , getParentGroup ( ) , getShortName ( ) , getDataType ( ) , getDimensionsString ( ) , getUnitsString ( ) , getDescription ( ) ) ; // other state axis . axisType = this . axisType ; axis . boundaryRef = this . boundaryRef ; axis . isContiguous = this . isContiguous ; axis . positive = this . positive ; axis . cache = new Variable . Cache ( ) ; // decouple cache return axis ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the axis have numeric values . [CODESPLIT] public boolean isNumeric ( ) { return ( getDataType ( ) != DataType . CHAR ) && ( getDataType ( ) != DataType . STRING ) && ( getDataType ( ) != DataType . STRUCTURE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a string representation [CODESPLIT] public void getInfo ( Formatter buf ) { buf . format ( \"%-30s\" , getNameAndDimensions ( ) ) ; buf . format ( \"%-20s\" , getUnitsString ( ) ) ; if ( axisType != null ) { buf . format ( \"%-10s\" , axisType . toString ( ) ) ; } buf . format ( \"%s\" , getDescription ( ) ) ; /* if (isNumeric) {\n     boolean debugCoords = ucar.util.prefs.ui.Debug.isSet(\"Dataset/showCoordValues\");\n     int ndigits = debugCoords ? 9 : 4;\n     for (int i=0; i< getNumElements(); i++) {\n       buf.append(Format.d(getCoordValue(i), ndigits));\n       buf.append(\" \");\n     }\n     if (debugCoords) {\n       buf.append(\"\\n      \");\n       for (int i=0; i<=getNumElements(); i++) {\n         buf.append(Format.d(getCoordEdge(i), ndigits));\n         buf.append(\" \");\n       }\n     }\n   } else {\n     for (int i=0; i< getNumElements(); i++) {\n       buf.append(getCoordName(i));\n       buf.append(\" \");\n     }\n   } */ //buf.append(\"\\n\"); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "needed by time coordinates [CODESPLIT] public ucar . nc2 . time . Calendar getCalendarFromAttribute ( ) { Attribute cal = findAttribute ( CF . CALENDAR ) ; String s = ( cal == null ) ? null : cal . getStringValue ( ) ; if ( s == null ) { // default for CF and COARDS Attribute convention = ( ncd == null ) ? null : ncd . getRootGroup ( ) . findAttribute ( CDM . CONVENTIONS ) ; if ( convention != null ) { String hasName = convention . getStringValue ( ) ; int version = CF1Convention . getVersion ( hasName ) ; if ( version >= 0 ) { return Calendar . gregorian ; //if (version < 7 ) return Calendar.gregorian; //if (version >= 7 ) return Calendar.proleptic_gregorian; // } if ( COARDSConvention . isMine ( hasName ) ) return Calendar . gregorian ; } } return ucar . nc2 . time . Calendar . get ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort the rowList : note rowList changed not a copy of it . [CODESPLIT] public void sort ( int colNo , boolean reverse ) { model . sort ( colNo , reverse ) ; jtable . setRowSelectionInterval ( 0 , 0 ) ; ensureRowIsVisible ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the rowList with this one . [CODESPLIT] public void setList ( ArrayList rowList ) { this . list = rowList ; if ( list . size ( ) > 0 ) jtable . setRowSelectionInterval ( 0 , 0 ) ; else jtable . clearSelection ( ) ; model . sort ( ) ; jtable . revalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove elem from rowList update the table . Searches for match using object identity ( == ) [CODESPLIT] public void removeRow ( Object elem ) { Iterator iter = list . iterator ( ) ; while ( iter . hasNext ( ) ) { Object row = iter . next ( ) ; if ( row == elem ) { iter . remove ( ) ; break ; } } jtable . revalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the currently selected row . [CODESPLIT] public TableRow getSelected ( ) { if ( list . size ( ) == 0 ) return null ; int sel = jtable . getSelectedRow ( ) ; if ( sel >= 0 ) return ( TableRow ) list . get ( sel ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the current selection to this row . [CODESPLIT] public void setSelected ( int row ) { if ( ( row < 0 ) || ( row >= list . size ( ) ) ) return ; if ( debug ) System . out . println ( \"JTableSorted setSelected \" + row ) ; jtable . setRowSelectionInterval ( row , row ) ; ensureRowIsVisible ( row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increment or decrement the current selection by one row . [CODESPLIT] public void incrSelected ( boolean increment ) { if ( list . size ( ) == 0 ) return ; int curr = jtable . getSelectedRow ( ) ; if ( increment && ( curr < list . size ( ) - 1 ) ) setSelected ( curr + 1 ) ; else if ( ! increment && ( curr > 0 ) ) setSelected ( curr - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for each column get the model index [CODESPLIT] public int [ ] getModelIndex ( ) { int [ ] modelIndex = new int [ colName . length ] ; TableColumnModel tcm = jtable . getColumnModel ( ) ; for ( int i = 0 ; i < colName . length ; i ++ ) { TableColumn tc = tcm . getColumn ( i ) ; modelIndex [ i ] = tc . getModelIndex ( ) ; } return modelIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void ensureRowIsVisible ( int nRow ) { Rectangle visibleRect = jtable . getCellRect ( nRow , 0 , true ) ; if ( visibleRect != null ) { visibleRect . x = scrollPane . getViewport ( ) . getViewPosition ( ) . x ; jtable . scrollRectToVisible ( visibleRect ) ; jtable . repaint ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this . [CODESPLIT] private CalendarPeriod findRangeAdjustment ( String fmtString ) { if ( fmtString . contains ( \"H\" ) || fmtString . contains ( \"k\" ) ) return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Hour ) ; else if ( fmtString . contains ( \"d\" ) ) return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Day ) ; else if ( fmtString . contains ( \"M\" ) ) return CalendarPeriod . of ( 31 , CalendarPeriod . Field . Day ) ; else return CalendarPeriod . of ( 366 , CalendarPeriod . Field . Day ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK fake [CODESPLIT] @ Override public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { IOServiceProvider iosp = ncd . getIosp ( ) ; return ( iosp != null && iosp instanceof BufrIosp2 ) ? true : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set current value - no event [CODESPLIT] private void setSelectedIndex ( int idx ) { if ( zAxis == null ) return ; eventOK = false ; currentIdx = idx ; slider . setValue ( world2slider ( zAxis . getCoordValue ( currentIdx ) ) ) ; eventOK = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push Parse input from external lexer [CODESPLIT] public int push_parse ( int yylextoken , Object yylexval ) throws DapException , DapException { if ( ! this . push_parse_initialized ) { push_parse_initialize ( ) ; yycdebug ( \"Starting parse\\n\" ) ; yyerrstatus_ = 0 ; } else label = YYGETTOKEN ; boolean push_token_consumed = true ; for ( ; ; ) switch ( label ) { /* New state.  Unlike in the C/C++ skeletons, the state is already\n           pushed when we come here.  */ case YYNEWSTATE : yycdebug ( \"Entering state \" + yystate + \"\\n\" ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; /* Accept?  */ if ( yystate == yyfinal_ ) { label = YYACCEPT ; break ; } /* Take a decision.  First try without lookahead.  */ yyn = yypact_ [ yystate ] ; if ( yy_pact_value_is_default_ ( yyn ) ) { label = YYDEFAULT ; break ; } /* Fall Through */ case YYGETTOKEN : /* Read a lookahead token.  */ if ( yychar == yyempty_ ) { if ( ! push_token_consumed ) return YYPUSH_MORE ; yycdebug ( \"Reading a token: \" ) ; yychar = yylextoken ; yylval = yylexval ; push_token_consumed = false ; } /* Convert token to internal form.  */ if ( yychar <= Lexer . EOF ) { yychar = yytoken = Lexer . EOF ; yycdebug ( \"Now at end of input.\\n\" ) ; } else { yytoken = yytranslate_ ( yychar ) ; yy_symbol_print ( \"Next token is\" , yytoken , yylval ) ; } /* If the proper action on seeing token YYTOKEN is to reduce or to\n           detect an error, take that action.  */ yyn += yytoken ; if ( yyn < 0 || yylast_ < yyn || yycheck_ [ yyn ] != yytoken ) label = YYDEFAULT ; /* <= 0 means reduce or error.  */ else if ( ( yyn = yytable_ [ yyn ] ) <= 0 ) { if ( yy_table_value_is_error_ ( yyn ) ) label = YYERRLAB ; else { yyn = - yyn ; label = YYREDUCE ; } } else { /* Shift the lookahead token.  */ yy_symbol_print ( \"Shifting\" , yytoken , yylval ) ; /* Discard the token being shifted.  */ yychar = yyempty_ ; /* Count tokens shifted since error; after three, turn off error\n               status.  */ if ( yyerrstatus_ > 0 ) -- yyerrstatus_ ; yystate = yyn ; yystack . push ( yystate , yylval ) ; label = YYNEWSTATE ; } break ; /*-----------------------------------------------------------.\n      | yydefault -- do the default action for the current state.  |\n      `-----------------------------------------------------------*/ case YYDEFAULT : yyn = yydefact_ [ yystate ] ; if ( yyn == 0 ) label = YYERRLAB ; else label = YYREDUCE ; break ; /*-----------------------------.\n      | yyreduce -- Do a reduction.  |\n      `-----------------------------*/ case YYREDUCE : yylen = yyr2_ [ yyn ] ; label = yyaction ( yyn , yystack , yylen ) ; yystate = yystack . stateAt ( 0 ) ; break ; /*------------------------------------.\n      | yyerrlab -- here on detecting error |\n      `------------------------------------*/ case YYERRLAB : /* If not already recovering from an error, report this error.  */ if ( yyerrstatus_ == 0 ) { ++ yynerrs_ ; if ( yychar == yyempty_ ) yytoken = yyempty_ ; yyerror ( yysyntax_error ( yystate , yytoken ) ) ; } if ( yyerrstatus_ == 3 ) { /* If just tried and failed to reuse lookahead token after an\n         error, discard it.  */ if ( yychar <= Lexer . EOF ) { /* Return failure if at end of input.  */ if ( yychar == Lexer . EOF ) { label = YYABORT ; break ; } } else yychar = yyempty_ ; } /* Else will try to reuse lookahead token after shifting the error\n           token.  */ label = YYERRLAB1 ; break ; /*-------------------------------------------------.\n      | errorlab -- error raised explicitly by YYERROR.  |\n      `-------------------------------------------------*/ case YYERROR : /* Do not reclaim the symbols of the rule which action triggered\n           this YYERROR.  */ yystack . pop ( yylen ) ; yylen = 0 ; yystate = yystack . stateAt ( 0 ) ; label = YYERRLAB1 ; break ; /*-------------------------------------------------------------.\n      | yyerrlab1 -- common code for both syntax error and YYERROR.  |\n      `-------------------------------------------------------------*/ case YYERRLAB1 : yyerrstatus_ = 3 ; /* Each real token shifted decrements this.  */ for ( ; ; ) { yyn = yypact_ [ yystate ] ; if ( ! yy_pact_value_is_default_ ( yyn ) ) { yyn += yyterror_ ; if ( 0 <= yyn && yyn <= yylast_ && yycheck_ [ yyn ] == yyterror_ ) { yyn = yytable_ [ yyn ] ; if ( 0 < yyn ) break ; } } /* Pop the current state because it cannot handle the\n             * error token.  */ if ( yystack . height == 0 ) { label = YYABORT ; break ; } yystack . pop ( ) ; yystate = yystack . stateAt ( 0 ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; } if ( label == YYABORT ) /* Leave the switch.  */ break ; /* Shift the error token.  */ yy_symbol_print ( \"Shifting\" , yystos_ [ yyn ] , yylval ) ; yystate = yyn ; yystack . push ( yyn , yylval ) ; label = YYNEWSTATE ; break ; /* Accept.  */ case YYACCEPT : this . push_parse_initialized = false ; return YYACCEPT ; /* Abort.  */ case YYABORT : this . push_parse_initialized = false ; return YYABORT ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Re - ) Initialize the state of the push parser . [CODESPLIT] public void push_parse_initialize ( ) { /* Lookahead and lookahead in internal form.  */ this . yychar = yyempty_ ; this . yytoken = 0 ; /* State.  */ this . yyn = 0 ; this . yylen = 0 ; this . yystate = 0 ; this . yystack = new YYStack ( ) ; this . label = YYNEWSTATE ; /* Error handling.  */ this . yynerrs_ = 0 ; /* Semantic value of the lookahead.  */ this . yylval = null ; yystack . push ( this . yystate , this . yylval ) ; this . push_parse_initialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares elements in a <code > Vector< / code > of <code > BaseType< / code > s and throw a <code > BadSemanticsException< / code > if there are any duplicate elements . [CODESPLIT] static void uniqueNames ( Vector v , String varName , String typeName ) throws BadSemanticsException { String [ ] names = sortedNames ( v ) ; // DEBUG: print out names //for(int i=0; i<names.length; i++) { //  LogStream.err.println(\"names[\" + i + \"] = \" + names[i]); //} // look for any instance of consecutive names that are == for ( int i = 1 ; i < names . length ; i ++ ) { if ( names [ i - 1 ] . equals ( names [ i ] ) ) { throw new BadSemanticsException ( \"The variable `\" + names [ i ] + \"' is used more than once in \" + typeName + \" `\" + varName + \"'\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a <code > Vector< / code > of <code > BaseType< / code > s retrieves their names into an array of <code > String< / code > s and performs a Quick Sort on that array . [CODESPLIT] static String [ ] sortedNames ( Vector v ) throws BadSemanticsException { String [ ] names = new String [ v . size ( ) ] ; int count = 0 ; for ( Enumeration e = v . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; String tempName = bt . getEncodedName ( ) ; if ( tempName == null ) throw new BadSemanticsException ( bt . getClass ( ) . getName ( ) + \" variable with no name\" ) ; names [ count ++ ] = tempName ; } // DEBUG: print out names //for(int i=0; i<names.length; i++) { //  LogStream.err.println(\"names[\" + i + \"] = \" + names[i]); //} // assert that size is correct if ( count != names . length ) throw new IndexOutOfBoundsException ( \"Vector size changed unexpectedly\" ) ; quickSort ( names , 0 , names . length - 1 ) ; return names ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal recursive method to perform Quick Sort on name array . [CODESPLIT] static private void quickSort ( String a [ ] , int lo0 , int hi0 ) { int lo = lo0 ; int hi = hi0 ; String mid ; if ( hi0 > lo0 ) { // Arbitrarily establishing partition element as the array midpoint */ //Coverity[FB.IM_AVERAGE_COMPUTATION_COULD_OVERFLOW] mid = a [ ( lo0 + hi0 ) / 2 ] ; // loop through the array until indices cross while ( lo <= hi ) { // find the first element that is >= the partition element // starting from the left index. while ( ( lo < hi0 ) && ( a [ lo ] . compareTo ( mid ) < 0 ) ) ++ lo ; // find an element that is <= the partition element // starting from the right index. while ( ( hi > lo0 ) && ( a [ hi ] . compareTo ( mid ) > 0 ) ) -- hi ; // if the indexes have not crossed, swap if ( lo <= hi ) { swap ( a , lo , hi ) ; ++ lo ; -- hi ; } } // If the right index has not reached the left side of array, // sort the left partition. if ( lo0 < hi ) quickSort ( a , lo0 , hi ) ; // If the left index has not reached the right side of array, // sort the right partition. if ( lo < hi0 ) quickSort ( a , lo , hi0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private method to swap two elements in the array [CODESPLIT] static private void swap ( String a [ ] , int i , int j ) { String T ; T = a [ i ] ; a [ i ] = a [ j ] ; a [ j ] = T ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function escapes non - printable characters and quotes . This is used to make <code > printVal< / code > output <code > DString< / code > data in the same way as the C ++ version . Since Java supports Unicode this will need to be altered if it s desired to print <code > DString< / code > as UTF - 8 or some other character encoding . [CODESPLIT] static String escattr ( String s ) { StringBuffer buf = new StringBuffer ( s . length ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' || ( c >= ' ' && c <= ' ' ) ) { // printable ASCII character buf . append ( c ) ; } else { // non-printable ASCII character: print as unsigned octal integer // padded with leading zeros buf . append ( ' ' ) ; String numVal = Integer . toString ( ( int ) c & 0xFF , 8 ) ; for ( int pad = 0 ; pad < ( 3 - numVal . length ( ) ) ; pad ++ ) buf . append ( ' ' ) ; buf . append ( numVal ) ; } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make MFileOS if file exists otherwise return null [CODESPLIT] static public MFileOS getExistingFile ( String filename ) { if ( filename == null ) return null ; File file = new File ( filename ) ; if ( file . exists ( ) ) return new MFileOS ( file ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a real longitude and latitude into the rotated longitude ( X ) and rotated latitude ( Y ) . [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl destPoint ) { /*\r\n    Tor's algorithm\r\n    public double[] fwd(double[] lonlat)\r\n      return transform(lonlat, lonpole, polerotate, sinDlat);\r\n    */ double [ ] lonlat = new double [ 2 ] ; lonlat [ 0 ] = latlon . getLongitude ( ) ; lonlat [ 1 ] = latlon . getLatitude ( ) ; double [ ] rlonlat = rotate ( lonlat , lonpole , polerotate , sinDlat ) ; if ( destPoint == null ) destPoint = new ProjectionPointImpl ( rlonlat [ 0 ] , rlonlat [ 1 ] ) ; else destPoint . setLocation ( rlonlat [ 0 ] , rlonlat [ 1 ] ) ; if ( show ) System . out . println ( \"LatLon= \" + latlon + \" proj= \" + destPoint ) ; return destPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform a rotated longitude ( X ) and rotated latitude ( Y ) into a real longitude - latitude pair . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint ppt , LatLonPointImpl destPoint ) { /*\r\n    Tor's algorithm\r\n    public double[] inv(double[] lonlat)\r\n      return rotate(lonlat, -polerotate, -lonpole, -sinDlat);\r\n    */ double [ ] lonlat = new double [ 2 ] ; lonlat [ 0 ] = ppt . getX ( ) ; lonlat [ 1 ] = ppt . getY ( ) ; double [ ] rlonlat = rotate ( lonlat , - polerotate , - lonpole , - sinDlat ) ; if ( destPoint == null ) destPoint = new LatLonPointImpl ( rlonlat [ 1 ] , rlonlat [ 0 ] ) ; else destPoint . set ( rlonlat [ 1 ] , rlonlat [ 0 ] ) ; if ( show ) System . out . println ( \"Proj= \" + ppt + \" latlon= \" + destPoint ) ; return destPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tor s transform algorithm renamed to rotate for clarity [CODESPLIT] private double [ ] rotate ( double [ ] lonlat , double rot1 , double rot2 , double s ) { /* original code\r\n      double e = DEG2RAD * (lonlat[0] - rot1); //east\r\n      double n = DEG2RAD * lonlat[1]; //north\r\n      double cn = Math.cos(n);\r\n      double x = cn * Math.cos(e);\r\n      double y = cn * Math.sin(e);\r\n      double z = Math.sin(n);\r\n      double x2 = cosDlat * x + s * z;\r\n      double z2 = -s * x + cosDlat * z;\r\n      double R = Math.sqrt(x2 * x2 + y * y);\r\n      double e2 = Math.atan2(y, x2);\r\n      double n2 = Math.atan2(z2, R);\r\n      double rlon = RAD2DEG * e2 - rot2;\r\n      double rlat = RAD2DEG * n2;\r\n      return new double[]{rlon, rlat};\r\n     */ double e = Math . toRadians ( lonlat [ 0 ] - rot1 ) ; //east\r double n = Math . toRadians ( lonlat [ 1 ] ) ; //north\r double cn = Math . cos ( n ) ; double x = cn * Math . cos ( e ) ; double y = cn * Math . sin ( e ) ; double z = Math . sin ( n ) ; double x2 = cosDlat * x + s * z ; double z2 = - s * x + cosDlat * z ; double R = Math . sqrt ( x2 * x2 + y * y ) ; double e2 = Math . atan2 ( y , x2 ) ; double n2 = Math . atan2 ( z2 , R ) ; double rlon = Math . toDegrees ( e2 ) - rot2 ; double rlat = Math . toDegrees ( n2 ) ; return new double [ ] { rlon , rlat } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XMLStore reading from the specified filename . [CODESPLIT] static public XMLStore createFromFile ( String fileName , XMLStore storedDefaults ) throws java . io . IOException { File prefsFile = new File ( fileName ) ; // open file if it exists InputStream primIS = null , objIS = null ; if ( prefsFile . exists ( ) && prefsFile . length ( ) > 0 ) { primIS = new BufferedInputStream ( new FileInputStream ( prefsFile ) ) ; objIS = new BufferedInputStream ( new FileInputStream ( prefsFile ) ) ; } if ( debugWhichStore ) System . out . println ( \"XMLStore read from file \" + fileName ) ; XMLStore store = new XMLStore ( primIS , objIS , storedDefaults ) ; store . prefsFile = prefsFile ; return store ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an XMLStore reading from an input stream . Because of some peculiariteis you must open the input stream wtice and pass both in . [CODESPLIT] static public XMLStore createFromInputStream ( InputStream is1 , InputStream is2 , XMLStore storedDefaults ) throws java . io . IOException { if ( debugWhichStore ) System . out . println ( \"XMLStore read from input stream \" + is1 ) ; return new XMLStore ( is1 , is2 , storedDefaults ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a read - only XMLStore reading from the specified resource opened as a Resource stream using the XMLStore ClassLoader . This allows you to find files that are in jar files on the application CLASSPATH . [CODESPLIT] static public XMLStore createFromResource ( String resourceName , XMLStore storedDefaults ) throws java . io . IOException { // open files if exist Class c = XMLStore . class ; InputStream primIS = c . getResourceAsStream ( resourceName ) ; InputStream objIS = c . getResourceAsStream ( resourceName ) ; // debug //    InputStream debugIS = c.getResourceAsStream(fileName); //  System.out.println(\"Resource stream= \"+fileName); //thredds.util.IO.copy(debugIS, System.out); if ( primIS == null ) { //System.out.println(\"classLoader=\"+new XMLStore().getClass().getClassLoader()); throw new java . io . IOException ( \"XMLStore.createFromResource cant find <\" + resourceName + \">\" ) ; } if ( debugWhichStore ) System . out . println ( \"XMLStore read from resource \" + resourceName ) ; return new XMLStore ( primIS , objIS , storedDefaults ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience routine for creating an XMLStore file in a standard place . [CODESPLIT] static public String makeStandardFilename ( String appName , String storeName ) { // the directory String userHome = null ; try { userHome = System . getProperty ( \"user.home\" ) ; } catch ( Exception e ) { System . out . println ( \"XMLStore.makeStandardFilename: error System.getProperty(user.home) \" + e ) ; } if ( null == userHome ) userHome = \".\" ; String dirFilename = userHome + \"/\" + appName ; File f = new File ( dirFilename ) ; if ( ! f . exists ( ) ) { boolean ok = f . mkdirs ( ) ; // now ready for file creation in writeXML if ( ! ok ) System . out . println ( \"Error creating directories: \" + f . getAbsolutePath ( ) ) ; } return dirFilename + \"/\" + storeName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the current state of the Preferences tree to disk using the original filename . The XMLStore must have been constructed from a writeable XML file . [CODESPLIT] public void save ( ) throws java . io . IOException { if ( prefsFile == null ) throw new UnsupportedOperationException ( \"XMLStore is read-only\" ) ; // get temporary file to write to File prefTemp ; String parentFilename = prefsFile . getParent ( ) ; if ( parentFilename == null ) { prefTemp = File . createTempFile ( \"pref\" , \".xml\" ) ; } else { File parentFile = new File ( parentFilename ) ; prefTemp = File . createTempFile ( \"pref\" , \".xml\" , parentFile ) ; } prefTemp . deleteOnExit ( ) ; // save to the temp file FileOutputStream fos = new FileOutputStream ( prefTemp , false ) ; save ( fos ) ; fos . close ( ) ; // success - rename files Path xmlBackup = Paths . get ( prefsFile . getAbsolutePath ( ) + \".bak\" ) ; Path prefsPath = prefsFile . toPath ( ) ; if ( Files . exists ( prefsPath ) ) Files . move ( prefsPath , xmlBackup , StandardCopyOption . REPLACE_EXISTING ) ; Files . move ( prefTemp . toPath ( ) , prefsFile . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the current state of the Preferences tree to the given OutputStream . [CODESPLIT] public void save ( OutputStream out ) throws java . io . IOException { outputExceptionMessage = null ; // the OutputMunger strips off the XMLEncoder header OutputMunger bos = new OutputMunger ( out ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( bos , CDM . utf8Charset ) ) ; XMLEncoder beanEncoder = new XMLEncoder ( bos ) ; beanEncoder . setExceptionListener ( new ExceptionListener ( ) { public void exceptionThrown ( Exception exception ) { System . out . println ( \"XMLStore.save() got Exception: abort saving the preferences!\" ) ; exception . printStackTrace ( ) ; outputExceptionMessage = exception . getMessage ( ) ; } } ) ; pw . printf ( \"<?xml version='1.0' encoding='UTF-8'?>%n\" ) ; pw . printf ( \"<preferences EXTERNAL_XML_VERSION='1.0'>%n\" ) ; if ( ! rootPrefs . isUserNode ( ) ) pw . printf ( \"  <root type='system'>%n\" ) ; else pw . printf ( \"  <root type='user'>%n\" ) ; Indent indent = new Indent ( 2 ) ; indent . incr ( ) ; writeXmlNode ( bos , pw , rootPrefs , beanEncoder , indent ) ; if ( outputExceptionMessage != null ) throw new IOException ( outputExceptionMessage ) ; pw . printf ( \"  </root>%n\" ) ; pw . printf ( \"</preferences>%n\" ) ; pw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out an atomic variable . [CODESPLIT] protected void writeAtomicVariable ( DataCursor data , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) data . getTemplate ( ) ; assert ( this . ce . references ( template ) ) ; DapType basetype = template . getBaseType ( ) ; // get the slices from constraint List < Slice > slices = ce . getConstrainedSlices ( template ) ; if ( slices == null ) throw new DapException ( \"Unknown variable: \" + template . getFQN ( ) ) ; Object values = data . read ( slices ) ; dst . writeAtomicArray ( basetype , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out a scalar or array structure instance [CODESPLIT] protected void writeStructure ( DataCursor data , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) data . getTemplate ( ) ; DapStructure ds = ( DapStructure ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; List < Slice > slices = ce . getConstrainedSlices ( template ) ; Odometer odom = Odometer . factory ( slices ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; DataCursor [ ] instance = ( DataCursor [ ] ) data . read ( index ) ; writeStructure1 ( instance [ 0 ] , dst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out a single structure instance [CODESPLIT] protected void writeStructure1 ( DataCursor instance , SerialWriter dst ) throws IOException { assert instance . getScheme ( ) == DataCursor . Scheme . STRUCTURE ; DapVariable template = ( DapVariable ) instance . getTemplate ( ) ; assert ( this . ce . references ( template ) ) ; DapStructure ds = ( DapStructure ) template . getBaseType ( ) ; List < DapVariable > fields = ds . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; if ( ! this . ce . references ( field ) ) continue ; // not in the view DataCursor df = ( DataCursor ) instance . readField ( i ) ; writeVariable ( df , dst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out a single or array sequence instance [CODESPLIT] protected void writeSequence ( DataCursor data , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) data . getTemplate ( ) ; DapSequence ds = ( DapSequence ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; List < Slice > slices = ce . getConstrainedSlices ( template ) ; Odometer odom = Odometer . factory ( slices ) ; if ( false ) while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; DataCursor [ ] instance = ( DataCursor [ ] ) data . read ( index ) ; writeSequence1 ( instance [ 0 ] , dst ) ; } else { DataCursor [ ] instances = ( DataCursor [ ] ) data . read ( slices ) ; for ( int i = 0 ; i < instances . length ; i ++ ) { writeSequence1 ( instances [ i ] , dst ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out a single Sequence of records ( Eventually use any filter in the DapVariable ) [CODESPLIT] protected void writeSequence1 ( DataCursor instance , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) instance . getTemplate ( ) ; DapSequence seq = ( DapSequence ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; long nrecs = instance . getRecordCount ( ) ; dst . writeCount ( nrecs ) ; for ( long i = 0 ; i < nrecs ; i ++ ) { DataCursor record = instance . readRecord ( i ) ; writeRecord ( record , dst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out a single Record instance . [CODESPLIT] protected void writeRecord ( DataCursor record , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) record . getTemplate ( ) ; DapSequence seq = ( DapSequence ) template . getBaseType ( ) ; List < DapVariable > fields = seq . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; if ( ! this . ce . references ( field ) ) continue ; // not in the view DataCursor df = ( DataCursor ) record . readField ( i ) ; writeVariable ( df , dst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( _Debug ) System . out . println ( \"asciiSeq.toASCII(\" + addName + \",'\" + rootName + \"')  getName(): \" + getEncodedName ( ) ) ; //System.out.println(\"this: \" + this + \" Has \"+allValues.size() + \" elements.\");\r if ( rootName != null ) rootName += \".\" + getEncodedName ( ) ; else rootName = getEncodedName ( ) ; pw . print ( toASCIIFlatName ( rootName ) ) ; /*\r\n        for(Enumeration e1 = allValues.elements(); e1.hasMoreElements(); ) {\r\n            // get next instance vector\r\n            Vector v = (Vector)e1.nextElement();\r\n            for(Enumeration e2 = v.elements(); e2.hasMoreElements(); ) {\r\n                // get next instance variable\r\n                BaseType bt = (BaseType)e2.nextElement();\r\n\r\n        pw.print(bt.toASCIIFlatName(rootName)+\",\");\r\n            }\r\n        break;\r\n        }\r\n*/ pw . println ( \"\" ) ; int i = 0 ; for ( Enumeration e1 = allValues . elements ( ) ; e1 . hasMoreElements ( ) ; ) { int j = 0 ; // get next instance vector\r Vector v = ( Vector ) e1 . nextElement ( ) ; for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) { // get next instance variable\r toASCII ta = ( toASCII ) e2 . nextElement ( ) ; if ( j > 0 ) pw . print ( \", \" ) ; ta . toASCII ( pw , false , rootName , false ) ; j ++ ; } pw . println ( \"\" ) ; } if ( newLine ) pw . print ( \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////// [CODESPLIT] CoverageCoordAxisBuilder subset ( String dependsOn , CoverageCoordAxis . Spacing spacing , int ncoords , double [ ] values ) { assert values != null ; if ( dependsOn != null ) { this . dependenceType = CoverageCoordAxis . DependenceType . dependent ; setDependsOn ( dependsOn ) ; } this . spacing = spacing ; this . ncoords = ncoords ; this . reader = null ; this . values = values ; this . isSubset = true ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is this a valid BUFR file . [CODESPLIT] static public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { raf . seek ( 0 ) ; if ( ! raf . searchForward ( matcher , 40 * 1000 ) ) return false ; // must find \"BUFR\" in first 40k\r raf . skipBytes ( 4 ) ; BufrIndicatorSection is = new BufrIndicatorSection ( raf ) ; if ( is . getBufrEdition ( ) > 4 ) return false ; // if(is.getBufrLength() > MAX_MESSAGE_SIZE) return false;\r return ! ( is . getBufrLength ( ) > raf . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the WMO Station ID as a string [CODESPLIT] public String getWmoId ( ) { String wmoID = \"\" ; if ( ! ( stnm == GempakConstants . IMISSD ) ) { wmoID = String . valueOf ( ( int ) ( stnm / 10 ) ) ; } return wmoID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { // BEWARE! Since printDecl()is (multiplely) overloaded in BaseType and // all of the different signatures of printDecl() in BaseType lead to // one signature, we must be careful to override that SAME signature // here. That way all calls to printDecl() for this object lead to // this implementation. //os.println(\"DArray.printDecl()\"); getPrimitiveVector ( ) . printDecl ( os , space , false , constrained ) ; for ( Enumeration e = dimVector . elements ( ) ; e . hasMoreElements ( ) ; ) { DArrayDimension d = ( DArrayDimension ) e . nextElement ( ) ; os . print ( \"[\" ) ; String name = d . getEncodedName ( ) ; if ( name != null && name . length ( ) > 0 ) os . print ( d . getEncodedName ( ) + \" = \" ) ; os . print ( d . getSize ( ) + \"]\" ) ; } if ( print_semi ) os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter pw , String space , boolean print_decl_p ) { // print the declaration if print decl is true. // for each dimension, //   for each element, //     print the array given its shape, number of dimensions. // Add the `;' if ( print_decl_p ) { printDecl ( pw , space , false ) ; pw . print ( \" = \" ) ; } int dims = numDimensions ( ) ; int shape [ ] = new int [ dims ] ; int i = 0 ; for ( Enumeration e = dimVector . elements ( ) ; e . hasMoreElements ( ) ; ) { DArrayDimension d = ( DArrayDimension ) e . nextElement ( ) ; shape [ i ++ ] = d . getSize ( ) ; } printArray ( pw , 0 , dims , shape , 0 ) ; if ( print_decl_p ) pw . println ( \";\" ) ; pw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print an array . This is a private member function . [CODESPLIT] private int printArray ( PrintWriter os , int index , int dims , int shape [ ] , int offset ) { if ( dims == 1 ) { os . print ( \"{\" ) ; for ( int i = 0 ; i < shape [ offset ] - 1 ; i ++ ) { getPrimitiveVector ( ) . printSingleVal ( os , index ++ ) ; os . print ( \", \" ) ; } getPrimitiveVector ( ) . printSingleVal ( os , index ++ ) ; os . print ( \"}\" ) ; return index ; } else { os . print ( \"{\" ) ; for ( int i = 0 ; i < shape [ offset ] - 1 ; i ++ ) { index = printArray ( os , index , dims - 1 , shape , offset + 1 ) ; os . print ( \",\" ) ; } index = printArray ( os , index , dims - 1 , shape , offset + 1 ) ; os . print ( \"}\" ) ; return index ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a size and a name this function adds a dimension to the array . For example if the <code > DArray< / code > is already 10 elements long calling <code > appendDim< / code > with a size of 5 will transform the array into a 10x5 matrix . Calling it again with a size of 2 will create a 10x5x2 array and so on . [CODESPLIT] public void appendDim ( int size , String name ) { DArrayDimension newDim = new DArrayDimension ( size , name ) ; dimVector . addElement ( newDim ) ; newDim . setContainer ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this method to squeeze out all of the array dimensions whose size is equal to 1 . <br > Many queries that contstrain Arrays return an Array that has dimensions whose size has been reduced to 1 . In effect that the dimension no longer really exists except as a notational convention for tracking the hyperslab that the array represents . Since many clients have difficulty handling n - dimensional arrays this method was added to allow the client to easily squeeze the extra dimensions out of the array . [CODESPLIT] public void squeeze ( ) { if ( dimVector . size ( ) == 1 ) return ; Vector < DArrayDimension > squeezeCandidates = new Vector < DArrayDimension > ( ) ; for ( DArrayDimension dim : dimVector ) { if ( dim . getSize ( ) == 1 ) squeezeCandidates . add ( dim ) ; } if ( squeezeCandidates . size ( ) == dimVector . size ( ) ) squeezeCandidates . remove ( squeezeCandidates . size ( ) - 1 ) ; //LogStream.out.println(\"DArray.squeeze(): Removing \"+ //        squeezeCandidates.size()+\" dimensions of size 1.\"); dimVector . removeAll ( squeezeCandidates ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > DArrayDimension< / code > object for the dimension requested . It makes sure that the dimension requested exists . [CODESPLIT] public DArrayDimension getDimension ( int dimension ) throws InvalidDimensionException { // QC the passed dimension if ( dimension < dimVector . size ( ) ) return dimVector . get ( dimension ) ; else throw new InvalidDimensionException ( \"DArray.getDimension(): Bad dimension request: dimension > # of dimensions\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Array< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DArray a = ( DArray ) super . cloneDAG ( map ) ; a . dimVector = new Vector < DArrayDimension > ( ) ; for ( int i = 0 ; i < dimVector . size ( ) ; i ++ ) { DArrayDimension d = dimVector . elementAt ( i ) ; DArrayDimension dclone = ( DArrayDimension ) cloneDAG ( map , d ) ; dclone . setContainer ( a ) ; a . dimVector . addElement ( dclone ) ; } return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare 2 tables print report . [CODESPLIT] public static void compareTables ( Grib2CodeTableInterface t1 , Grib2CodeTableInterface t2 , Formatter f ) { int extra = 0 ; int conflict = 0 ; f . format ( \"%s%n\" , t2 . getName ( ) ) ; for ( Grib2CodeTableInterface . Entry p1 : t1 . getEntries ( ) ) { if ( t1 . getEntry ( p1 . getCode ( ) ) == null ) { f . format ( \" ERROR %s missing own code %d%n\" , t1 . getShortName ( ) , p1 . getCode ( ) ) ; } Grib2CodeTableInterface . Entry p2 = t2 . getEntry ( p1 . getCode ( ) ) ; if ( p2 == null ) { extra ++ ; if ( verbose ) { f . format ( \"  %s missing %s%n\" , t2 . getShortName ( ) , p1 ) ; } } else { if ( ! Util . equivilantName ( p1 . getName ( ) , p2 . getName ( ) ) ) { f . format ( \"  p1=%10s %s%n\" , p1 . getCode ( ) , p1 . getName ( ) ) ; f . format ( \"  p2=%10s %s%n\" , p2 . getCode ( ) , p2 . getName ( ) ) ; conflict ++ ; } } } int missing = 0 ; for ( Grib2CodeTableInterface . Entry p2 : t2 . getEntries ( ) ) { if ( t2 . getEntry ( p2 . getCode ( ) ) == null ) { f . format ( \" ERROR %s missing own code %d%n\" , t2 . getShortName ( ) , p2 . getCode ( ) ) ; } Grib2CodeTableInterface . Entry p1 = t1 . getEntry ( p2 . getCode ( ) ) ; if ( p1 == null ) { missing ++ ; f . format ( \"  %s missing %s%n\" , t1 . getShortName ( ) , p2 ) ; t1 . getEntry ( p2 . getCode ( ) ) ; } } if ( conflict > 0 || missing > 0 ) { f . format ( \" ***Conflicts=%d extra=%d missing=%s%n\" , conflict , extra , missing ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the state of this variable s projection . <code > true< / code > means that this variable is part of the current projection as defined by the current constraint expression otherwise the current projection for this variable should be <code > false< / code > . [CODESPLIT] public void setProject ( boolean state , boolean all ) { setProjected ( state ) ; PrimitiveVector vals = getPrimitiveVector ( ) ; ( ( ServerMethods ) ( vals . getTemplate ( ) ) ) . setProject ( state , all ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p / > Server - side serialization for OPeNDAP variables ( sub - classes of <code > BaseType< / code > ) . This does not send the entire class as the Java <code > Serializable< / code > interface does rather it sends only the binary data values . Other software is responsible for sending variable type information ( see <code > DDS< / code > ) . < / p > <p > Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . < / p > <h2 > Caution : < / h2 > When serializing arrays of sequences ( children of DSequence ) it is crucial that it be handled with great care . Sequences have been implemented so that only one instance ( or row if you will ) is retained in memory at a given time . In order to correctly serialize an array of sequences the read () method for the array must create an instance of the sequence for each member of the array typically by repeatedly cloning the template variable in the PrimitiveVector . The important next step is to NOT attempt to read any data into the sequences from within the read () method of the parent array . The sequence s data will get read and constraint expressions applied when the serialze () method of the array calls the serialize method of the sequence . Good Luck! [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { PrimitiveVector vals = getPrimitiveVector ( ) ; if ( ! isRead ( ) ) read ( dataset , specialO ) ; if ( vals . getTemplate ( ) instanceof DSequence || ce . evalClauses ( specialO ) ) { // Because arrays of primitive types (ie int32, float32, byte, // etc) are handled in the C++ core using the XDR package we must // write the length twice for those types. For BaseType vectors, // we should write it only once. This is in effect a work around // for a bug in the C++ core as the C++ core does not consume 2 // length values for thge BaseType vectors. Bummer... int length = vals . getLength ( ) ; sink . writeInt ( length ) ; // Gotta check for this to make sure that DConstructor types // (Especially SDSequence) get handled correctly!!! if ( vals instanceof BaseTypePrimitiveVector ) { for ( int i = 0 ; i < length ; i ++ ) { ServerMethods sm = ( ServerMethods ) ( ( BaseTypePrimitiveVector ) vals ) . getValue ( i ) ; sm . serialize ( dataset , sink , ce , specialO ) ; } } else { // Because both XDR and OPeNDAP read the length, we must write // it twice. sink . writeInt ( length ) ; vals . externalize ( sink ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the projection information for this dimension . The <code > DArrayDimension< / code > associated with the <code > dimension< / code > specified is retrieved and the <code > start< / code > <code > stride< / code > and <code > stop< / code > parameters are passed to its <code > setProjection () < / code > method . [CODESPLIT] public void setProjection ( int dimension , int start , int stride , int stop ) throws InvalidDimensionException { DArrayDimension d = getDimension ( dimension ) ; d . setProjection ( start , stride , stop ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to read an entry from the data stream . The stream is assumed to be in the right spot for reading . This method should be called from something controlling the reading of the entire file . [CODESPLIT] int readRowN ( DataInputStream ds , int n ) { if ( n > nrec ) return - 1 ; /* the assumption here is that the DataInputStream (ds)\r\n    * is already pointing at the right spot!\r\n    */ try { ds . readFully ( field , 0 , desc . FieldLength ) ; } catch ( java . io . IOException e ) { return - 1 ; } switch ( desc . Type ) { case ' ' : case ' ' : character [ n ] = new String ( field , CDM . utf8Charset ) ; break ; case ' ' : numeric [ n ] = Double . valueOf ( new String ( field , CDM . utf8Charset ) ) ; break ; case ' ' : /* binary floating point */ if ( desc . FieldLength == 4 ) { numeric [ n ] = ( double ) Swap . swapFloat ( field , 0 ) ; } else { numeric [ n ] = Swap . swapDouble ( field , 0 ) ; } break ; case ' ' : switch ( field [ 0 ] ) { case ' ' : case ' ' : case ' ' : case ' ' : logical [ n ] = true ; break ; default : logical [ n ] = false ; break ; } default : return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to retrieve data for this field [CODESPLIT] public Object getData ( int i ) { switch ( type ) { case TYPE_CHAR : return character [ i ] ; case TYPE_NUMERIC : return numeric [ i ] ; case TYPE_BOOLEAN : return logical [ i ] ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Param Table : <GRIB2_22_0_0_CodeFlag_exp_en > <No > 524< / No > <Title_en > Code table 4 . 2 - Parameter number by product discipline and parameter category< / Title_en > <SubTitle_en > Product discipline 0 - Meteorological products parameter category 1 : moisture< / SubTitle_en > <CodeFlag > 101< / CodeFlag > <MeaningParameterDescription_en > Specific number concentration of snow< / MeaningParameterDescription_en > <UnitComments_en > kg - 1< / UnitComments_en > <ElementDescription_en > Number of particles per unit mass of air< / ElementDescription_en > <Status > Operational< / Status > < / GRIB2_22_0_0_CodeFlag_exp_en > [CODESPLIT] private void readGribCodes ( Version version ) throws IOException { String [ ] elems = version . getElemNames ( ) ; if ( elems == null ) { throw new IllegalStateException ( \"unknown version = \" + version ) ; } try ( InputStream ios = WmoCodeFlagTables . class . getResourceAsStream ( version . getResourceName ( ) ) ) { if ( ios == null ) { logger . error ( \"cant open WmoCodeTable=\" + version . getResourceName ( ) ) ; throw new IOException ( \"cant open WmoCodeTable=\" + version . getResourceName ( ) ) ; } org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( ios ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } Element root = doc . getRootElement ( ) ; Map < String , WmoTable > map = new HashMap <> ( ) ; List < Element > featList = root . getChildren ( elems [ 0 ] ) ; // main element for ( Element elem : featList ) { String line = elem . getChildTextNormalize ( \"No\" ) ; String tableName = elem . getChildTextNormalize ( elems [ 1 ] ) ; // Title_en Element subtableElem = elem . getChild ( elems [ 2 ] ) ; // \"SubTitle_en\" TableType type ; if ( tableName . startsWith ( \"Code table 4.1 \" ) ) { type = TableType . cat ; } else if ( tableName . startsWith ( \"Code table 4.2 \" ) ) { type = TableType . param ; } else if ( tableName . startsWith ( \"Flag\" ) ) { type = TableType . flag ; } else if ( tableName . startsWith ( \"Code\" ) ) { type = TableType . code ; } else { logger . warn ( \"Unknown wmo table entry = '%s'\" , tableName ) ; continue ; } if ( subtableElem != null ) { tableName = subtableElem . getTextNormalize ( ) ; } TableType finalType = type ; WmoTable wmoTable = map . computeIfAbsent ( tableName , name -> new WmoTable ( name , finalType ) ) ; String code = elem . getChildTextNormalize ( \"CodeFlag\" ) ; String value = elem . getChildTextNormalize ( \"Value\" ) ; // Flag table only String meaning = elem . getChildTextNormalize ( elems [ 3 ] ) ; // MeaningParameterDescription_en Element unitElem = elem . getChild ( elems [ 4 ] ) ; // \"UnitComments_en\" String unit = ( unitElem == null ) ? null : unitElem . getTextNormalize ( ) ; Element statusElem = elem . getChild ( \"Status\" ) ; String status = ( statusElem == null ) ? null : statusElem . getTextNormalize ( ) ; wmoTable . addEntry ( line , code , value , meaning , unit , status ) ; } ios . close ( ) ; this . wmoTables = map . values ( ) . stream ( ) . sorted ( ) . collect ( ImmutableList . toImmutableList ( ) ) ; ImmutableMap . Builder < String , WmoTable > builder = ImmutableMap . builder ( ) ; map . values ( ) . forEach ( t -> builder . put ( t . getId ( ) , t ) ) ; this . wmoTableMap = builder . build ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a NcML variable element and nested elements when it creates a new Variable . [CODESPLIT] private Variable readVariable ( NetcdfFile ncfile , Group g , Structure parentS , Element varElem ) { String name = varElem . getAttributeValue ( \"name\" ) ; if ( name == null ) { errlog . format ( \"NcML Variable name is required (%s)%n\" , varElem ) ; return null ; } String type = varElem . getAttributeValue ( \"type\" ) ; if ( type == null ) { errlog . format ( \"NcML variable (%s) must have type attribute\" , name ) ; return null ; } DataType dtype = DataType . getType ( type ) ; String shape = varElem . getAttributeValue ( \"shape\" ) ; if ( shape == null ) shape = \"\" ; // deprecated, prefer explicit \"\"\r Variable v ; if ( dtype == DataType . STRUCTURE ) { Structure s = new Structure ( ncfile , g , parentS , name ) ; s . setDimensions ( shape ) ; v = s ; // look for nested variables\r java . util . List < Element > varList = varElem . getChildren ( \"variable\" , Catalog . ncmlNS ) ; for ( Element vElem : varList ) { readVariable ( ncfile , g , s , vElem ) ; } } else if ( dtype == DataType . SEQUENCE ) { Sequence s = new Sequence ( ncfile , g , parentS , name ) ; v = s ; // look for nested variables\r java . util . List < Element > varList = varElem . getChildren ( \"variable\" , Catalog . ncmlNS ) ; for ( Element vElem : varList ) { readVariable ( ncfile , g , s , vElem ) ; } } else { v = new Variable ( ncfile , g , parentS , name , dtype , shape ) ; // deal with values\r Element valueElem = varElem . getChild ( \"values\" , Catalog . ncmlNS ) ; if ( valueElem != null ) readValues ( v , varElem , valueElem ) ; // otherwise has fill values.\r } // look for attributes\r java . util . List < Element > attList = varElem . getChildren ( \"attribute\" , Catalog . ncmlNS ) ; for ( Element attElem : attList ) readAtt ( v , attElem ) ; if ( parentS != null ) parentS . addMemberVariable ( v ) ; else g . addVariable ( v ) ; return v ; } private void readValues ( Variable v , Element varElem , Element valuesElem ) { // check if values are specified by start / increment\r String startS = valuesElem . getAttributeValue ( \"start\" ) ; String incrS = valuesElem . getAttributeValue ( \"increment\" ) ; String nptsS = valuesElem . getAttributeValue ( \"npts\" ) ; int npts = ( nptsS == null ) ? ( int ) v . getSize ( ) : Integer . parseInt ( nptsS ) ; // either start, increment are specified\r if ( ( startS != null ) && ( incrS != null ) ) { double start = Double . parseDouble ( startS ) ; double incr = Double . parseDouble ( incrS ) ; v . setValues ( npts , start , incr ) ; return ; } // otherwise values are listed in text\r String values = varElem . getChildText ( \"values\" , Catalog . ncmlNS ) ; String sep = valuesElem . getAttributeValue ( \"separator\" ) ; if ( sep == null ) sep = \" \" ; if ( v . getDataType ( ) == DataType . CHAR ) { int nhave = values . length ( ) ; int nwant = ( int ) v . getSize ( ) ; char [ ] data = new char [ nwant ] ; int min = Math . min ( nhave , nwant ) ; for ( int i = 0 ; i < min ; i ++ ) { data [ i ] = values . charAt ( i ) ; } Array dataArray = Array . factory ( DataType . CHAR , v . getShape ( ) , data ) ; v . setCachedData ( dataArray , true ) ; } else { // or a list of values\r List < String > valList = new ArrayList <> ( ) ; StringTokenizer tokn = new StringTokenizer ( values , sep ) ; while ( tokn . hasMoreTokens ( ) ) valList . add ( tokn . nextToken ( ) ) ; v . setValues ( valList ) ; } } private void readAtt  ( Object parent , Element attElem ) { String name = attElem . getAttributeValue ( \"name\" ) ; if ( name == null ) { errlog . format ( \"NcML Attribute name is required (%s)%n\" , attElem ) ; return ; } try { ucar . ma2 . Array values = NcMLReader . readAttributeValues ( attElem ) ; Attribute att = new ucar . nc2 . Attribute ( name , values ) ; if ( parent instanceof Group ) ( ( Group ) parent ) . addAttribute ( att ) ; else if ( parent instanceof Variable ) ( ( Variable ) parent ) . addAttribute ( att ) ; } catch ( RuntimeException e ) { errlog . format ( \"NcML new Attribute Exception: %s att=%s in=%s%n\" , e . getMessage ( ) , name , parent ) ; } } /**\r\n   * Read an NcML dimension element.\r\n   *\r\n   * @param g       put dimension into this group\r\n   * @param dimElem ncml dimension element\r\n   */ private void readDim  ( Group g , Element dimElem ) { String name = dimElem . getAttributeValue ( \"name\" ) ; if ( name == null ) { errlog . format ( \"NcML Dimension name is required (%s)%n\" , dimElem ) ; return ; } String lengthS = dimElem . getAttributeValue ( \"length\" ) ; String isUnlimitedS = dimElem . getAttributeValue ( \"isUnlimited\" ) ; String isSharedS = dimElem . getAttributeValue ( \"isShared\" ) ; String isUnknownS = dimElem . getAttributeValue ( \"isVariableLength\" ) ; boolean isUnlimited = ( isUnlimitedS != null ) && isUnlimitedS . equalsIgnoreCase ( \"true\" ) ; boolean isUnknown = ( isUnknownS != null ) && isUnknownS . equalsIgnoreCase ( \"true\" ) ; boolean isShared = true ; if ( ( isSharedS != null ) && isSharedS . equalsIgnoreCase ( \"false\" ) ) isShared = false ; int len = Integer . parseInt ( lengthS ) ; if ( ( isUnknownS != null ) && isUnknownS . equalsIgnoreCase ( \"false\" ) ) len = Dimension . VLEN . getLength ( ) ; Dimension dim = new Dimension ( name , len , isShared , isUnlimited , isUnknown ) ; if ( debugConstruct ) System . out . println ( \" add new dim = \" + dim ) ; g . addDimension ( dim ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Code Table Code table 5 . 0 - Data representation template number ( 5 . 0 ) 0 : Grid point data - simple packing 1 : Matrix value at grid point - simple packing 2 : Grid point data - complex packing 3 : Grid point data - complex packing and spatial differencing 4 : Grid point data - IEEE floating point data 40 : Grid point data - JPEG 2000 code stream format 41 : Grid point data - Portable Network Graphics ( PNG ) 50 : Spectral data - simple packing 51 : Spherical harmonics data - complex packing 61 : Grid point data - simple packing with logarithm pre - processing 200 : Run length packing with level values 65535 : Missing [CODESPLIT] public float [ ] getData ( RandomAccessFile raf , Grib2SectionBitMap bitmapSection , Grib2Drs gdrs ) throws IOException { this . bitmap = bitmapSection . getBitmap ( raf ) ; this . bitmapIndicator = bitmapSection . getBitMapIndicator ( ) ; if ( bitmap != null ) { // is bitmap ok ? if ( bitmap . length * 8 < totalNPoints ) { // gdsNumberPoints == nx * ny ?? logger . warn ( \"Bitmap section length = {} != grid length {} ({},{})\" , bitmap . length , totalNPoints , nx , totalNPoints / nx ) ; throw new IllegalStateException ( \"Bitmap section length!= grid length\" ) ; } } raf . seek ( startPos + 5 ) ; // skip past first 5 bytes in data section, now ready to read float [ ] data ; switch ( dataTemplate ) { case 0 : data = getData0 ( raf , ( Grib2Drs . Type0 ) gdrs ) ; break ; case 2 : data = getData2 ( raf , ( Grib2Drs . Type2 ) gdrs ) ; break ; case 3 : data = getData3 ( raf , ( Grib2Drs . Type3 ) gdrs ) ; break ; case 40 : data = getData40 ( raf , ( Grib2Drs . Type40 ) gdrs ) ; break ; case 41 : data = getData41 ( raf , ( Grib2Drs . Type0 ) gdrs ) ; break ; case 50002 : data = getData50002 ( raf , ( Grib2Drs . Type50002 ) gdrs ) ; break ; default : throw new UnsupportedOperationException ( \"Unsupported DRS type = \" + dataTemplate ) ; } //int scanMode = gds.getGds().getScanMode(); //int nx = gds.getGds().getNx();  // needs some smarts for different type Grids scanningModeCheck ( data , scanMode , nx ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grid point data - simple packing [CODESPLIT] private float [ ] getData0 ( RandomAccessFile raf , Grib2Drs . Type0 gdrs ) throws IOException { int nb = gdrs . numberOfBits ; int D = gdrs . decimalScaleFactor ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) D ) ; float R = gdrs . referenceValue ; int E = gdrs . binaryScaleFactor ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) E ) ; // LOOK: can # datapoints differ from bitmap and data ? // dataPoints are number of points encoded, it could be less than the // totalNPoints in the grid record if bitMap is used, otherwise equal float [ ] data = new float [ totalNPoints ] ; //  Y * 10**D = R + (X1 + X2) * 2**E //   E = binary scale factor //   D = decimal scale factor //   R = reference value //   X1 = 0 //   X2 = scaled encoded value //   data[ i ] = (R + ( X1 + X2) * EE)/DD ; BitReader reader = new BitReader ( raf , startPos + 5 ) ; if ( bitmap == null ) { for ( int i = 0 ; i < totalNPoints ; i ++ ) { //data[ i ] = (R + ( X1 + X2) * EE)/DD ; data [ i ] = ( R + reader . bits2UInt ( nb ) * EE ) / DD ; } } else { for ( int i = 0 ; i < totalNPoints ; i ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ i / 8 ] , i % 8 ) ) { data [ i ] = ( R + reader . bits2UInt ( nb ) * EE ) / DD ; } else { data [ i ] = staticMissingValue ; //data[i] = R / DD; } } } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Data template 7 . 2 – Grid point data – complex packing Note : For most templates details of the packing process are described in Regulation 92 . 9 . 4 . Octet No . Contents 6–xx NG group reference values ( X1 in the decoding formula ) each of which is encoded using the number of bits specified in octet 20 of data representation template 5 . 0 . Bits set to zero shall be appended as necessary to ensure this sequence of numbers ends on an octet boundary [ xx + 1 ] –yy NG group widths each of which is encoded using the number of bits specified in octet 37 of data representation template 5 . 2 . Bits set to zero shall be appended as necessary to ensure this sequence of numbers ends on an octet boundary [ yy + 1 ] –zz NG scaled group lengths each of which is encoded using the number of bits specified in octet 47 of data representation template 5 . 2 . Bits set to zero shall be appended as necessary to ensure this sequence of numbers ends on an octet boundary ( see Note 14 of data representation template 5 . 2 ) [ zz + 1 ] –nn Packed values ( X2 in the decoding formula ) where each value is a deviation from its respective group reference value [CODESPLIT] private float [ ] getData2 ( RandomAccessFile raf , Grib2Drs . Type2 gdrs ) throws IOException { int mvm = gdrs . missingValueManagement ; float mv = getMissingValue ( gdrs ) ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) gdrs . decimalScaleFactor ) ; float R = gdrs . referenceValue ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) gdrs . binaryScaleFactor ) ; float ref_val = R / DD ; int NG = gdrs . numberOfGroups ; if ( NG == 0 ) { return nGroups0 ( bitmapIndicator , ref_val , mv ) ; } BitReader reader = new BitReader ( raf , startPos + 5 ) ; // 6-xx  Get reference values for groups (X1's) int [ ] X1 = new int [ NG ] ; int nb = gdrs . numberOfBits ; if ( nb != 0 ) { for ( int i = 0 ; i < NG ; i ++ ) { X1 [ i ] = ( int ) reader . bits2UInt ( nb ) ; } } // [xx +1 ]-yy Get number of bits used to encode each group int [ ] NB = new int [ NG ] ; nb = gdrs . bitsGroupWidths ; if ( nb != 0 ) { reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { NB [ i ] = ( int ) reader . bits2UInt ( nb ) ; } } // [yy +1 ]-zz Get the scaled group lengths using formula //     Ln = ref + Kn * len_inc, where n = 1-NG, //          ref = referenceGroupLength, and  len_inc = lengthIncrement int [ ] L = new int [ NG ] ; int ref = gdrs . referenceGroupLength ; int len_inc = gdrs . lengthIncrement ; nb = gdrs . bitsScaledGroupLength ; reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { L [ i ] = ref + ( int ) reader . bits2UInt ( nb ) * len_inc ; } L [ NG - 1 ] = gdrs . lengthLastGroup ; // enter Length of Last Group float [ ] data = new float [ totalNPoints ] ; // [zz +1 ]-nn get X2 values and calculate the results Y using formula //              Y = R + [(X1 + X2) * (2 ** E) * (10 ** D)] //               WHERE: //                     Y = THE VALUE WE ARE UNPACKING //                     R = THE REFERENCE VALUE (FIRST ORDER MINIMA) //                    X1 = THE PACKED VALUE //                    X2 = THE SECOND ORDER MINIMA //                     E = THE BINARY SCALE FACTOR //                     D = THE DECIMAL SCALE FACTOR int count = 0 ; reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { for ( int j = 0 ; j < L [ i ] ; j ++ ) { if ( NB [ i ] == 0 ) { if ( mvm == 0 ) { // X2 = 0 data [ count ++ ] = ( R + X1 [ i ] * EE ) / DD ; } else { //if (mvm == 1) || (mvm == 2 ) data [ count ++ ] = mv ; } } else { int X2 = ( int ) reader . bits2UInt ( NB [ i ] ) ; if ( mvm == 0 ) { data [ count ++ ] = ( R + ( X1 [ i ] + X2 ) * EE ) / DD ; } else { //if (mvm == 1) || (mvm == 2 ) // X2 is also set to missing value if all bits set to 1's if ( X2 == bitsmv1 [ NB [ i ] ] ) { data [ count ++ ] = mv ; } else { data [ count ++ ] = ( R + ( X1 [ i ] + X2 ) * EE ) / DD ; } } } } // end for j } // end for i if ( bitmap != null ) { int idx = 0 ; float [ ] tmp = new float [ totalNPoints ] ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ i / 8 ] , i % 8 ) ) { tmp [ i ] = data [ idx ++ ] ; } else { tmp [ i ] = mv ; } } data = tmp ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * from wgrib unpk_complex () : [CODESPLIT] private float [ ] nGroups0 ( int bitmap_flag , float ref , float mv1 ) { float [ ] data = new float [ totalNPoints ] ; if ( bitmap_flag == 255 ) { for ( int i = 0 ; i < totalNPoints ; i ++ ) { data [ i ] = ref ; } } else if ( bitmap_flag == 0 || bitmap_flag == 254 ) { int mask = 0 ; int mask_pointer = 0 ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { if ( ( i & 7 ) == 0 ) { mask = bitmap [ mask_pointer ] ; mask_pointer ++ ; } data [ i ] = ( ( mask & 128 ) == 0 ) ? ref : mv1 ; mask <<= 1 ; } } else { throw new IllegalArgumentException ( \"unknown bitmap type =\" + bitmap_flag ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Data template 7 . 3 – Grid point data – complex packing and spatial differencing Note : For most templates details of the packing process are described in Regulation 92 . 9 . 4 . Octet No . Contents 6–ww First value ( s ) of original ( undifferenced ) scaled data values followed by the overall minimum of the differences . The number of values stored is 1 greater than the order of differentiation and the field width is described at octet 49 of data representation template 5 . 3 ( see Note 1 ) [ ww + 1 ] –xx NG group reference values ( X1 in the decoding formula ) each of which is encoded using the number of bits specified in octet 20 of data representation template 5 . 0 . Bits set to zero shall be appended where necessary to ensure this sequence of numbers ends on an octet boundary [ xx + 1 ] –nn Same as for data representation template 7 . 2 [CODESPLIT] private float [ ] getData3 ( RandomAccessFile raf , Grib2Drs . Type3 gdrs ) throws IOException { int mvm = gdrs . missingValueManagement ; float mv = getMissingValue ( gdrs ) ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) gdrs . decimalScaleFactor ) ; float R = gdrs . referenceValue ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) gdrs . binaryScaleFactor ) ; float ref_val = R / DD ; int NG = gdrs . numberOfGroups ; if ( NG == 0 ) { return nGroups0 ( bitmapIndicator , ref_val , mv ) ; } BitReader reader = new BitReader ( raf , startPos + 5 ) ; int ival1 ; int ival2 = 0 ; int minsd ; // [6-ww]   1st values of undifferenced scaled values and minimums int os = gdrs . orderSpatial ; int nbitsd = gdrs . descriptorSpatial ; int sign ; // ds is number of bytes, convert to bits -1 for sign bit nbitsd = nbitsd * 8 ; if ( nbitsd > 0 ) { // first order spatial differencing g1 and gMin sign = ( int ) reader . bits2UInt ( 1 ) ; ival1 = ( int ) reader . bits2UInt ( nbitsd - 1 ) ; if ( sign == 1 ) { ival1 = - ival1 ; } if ( os == 2 ) { //second order spatial differencing h1, h2, hMin sign = ( int ) reader . bits2UInt ( 1 ) ; ival2 = ( int ) reader . bits2UInt ( nbitsd - 1 ) ; if ( sign == 1 ) { ival2 = - ival2 ; } } sign = ( int ) reader . bits2UInt ( 1 ) ; minsd = ( int ) reader . bits2UInt ( nbitsd - 1 ) ; if ( sign == 1 ) { minsd = - minsd ; } } else { float [ ] data = new float [ totalNPoints ] ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { data [ i ] = mv ; } return data ; } // [ww +1]-xx  Get reference values for groups (X1's) // X1 == gref int [ ] X1 = new int [ NG ] ; // initialized to zero int nb = gdrs . numberOfBits ; if ( nb != 0 ) { reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { X1 [ i ] = ( int ) reader . bits2UInt ( nb ) ; } } // [xx +1 ]-yy Get number of bits used to encode each group // NB == gwidth int [ ] NB = new int [ NG ] ; // initialized to zero nb = gdrs . bitsGroupWidths ; if ( nb != 0 ) { reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { NB [ i ] = ( int ) reader . bits2UInt ( nb ) ; } } int referenceGroupWidths = gdrs . referenceGroupWidths ; for ( int i = 0 ; i < NG ; i ++ ) { NB [ i ] += referenceGroupWidths ; } // [yy +1 ]-zz Get the scaled group lengths using formula //     Ln = ref + Kn * len_inc, where n = 1-NG, //          ref = referenceGroupLength, and  len_inc = lengthIncrement int [ ] L = new int [ NG ] ; // initialized to zero int referenceGroupLength = gdrs . referenceGroupLength ; nb = gdrs . bitsScaledGroupLength ; int len_inc = gdrs . lengthIncrement ; if ( nb != 0 ) { reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { L [ i ] = ( int ) reader . bits2UInt ( nb ) ; } } int totalL = 0 ; for ( int i = 0 ; i < NG ; i ++ ) { L [ i ] = L [ i ] * len_inc + referenceGroupLength ; totalL += L [ i ] ; } totalL -= L [ NG - 1 ] ; totalL += gdrs . lengthLastGroup ; //enter Length of Last Group L [ NG - 1 ] = gdrs . lengthLastGroup ; // test if ( mvm != 0 ) { if ( totalL != totalNPoints ) { logger . warn ( \"NPoints != gds.nPts: \" + totalL + \"!=\" + totalNPoints ) ; float [ ] data = new float [ totalNPoints ] ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { data [ i ] = mv ; } return data ; } } else { if ( totalL != dataNPoints ) { logger . warn ( \"NPoints != drs.nPts: \" + totalL + \"!=\" + totalNPoints ) ; float [ ] data = new float [ totalNPoints ] ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { data [ i ] = mv ; } return data ; } } float [ ] data = new float [ totalNPoints ] ; // [zz +1 ]-nn get X2 values and calculate the results Y using formula //      formula used to create values,  Y * 10**D = R + (X1 + X2) * 2**E //               Y = (R + (X1 + X2) * (2 ** E) ) / (10 ** D)] //               WHERE: //                     Y = THE VALUE WE ARE UNPACKING //                     R = THE REFERENCE VALUE (FIRST ORDER MINIMA) //                    X1 = THE PACKED VALUE //                    X2 = THE SECOND ORDER MINIMA //                     E = THE BINARY SCALE FACTOR //                     D = THE DECIMAL SCALE FACTOR int count = 0 ; reader . incrByte ( ) ; int dataSize = 0 ; boolean [ ] dataBitMap = null ; if ( mvm == 0 ) { for ( int i = 0 ; i < NG ; i ++ ) { if ( NB [ i ] != 0 ) { for ( int j = 0 ; j < L [ i ] ; j ++ ) { data [ count ++ ] = ( int ) reader . bits2UInt ( NB [ i ] ) + X1 [ i ] ; } } else { for ( int j = 0 ; j < L [ i ] ; j ++ ) { data [ count ++ ] = X1 [ i ] ; } } } // end for i } else if ( mvm == 1 || mvm == 2 ) { // don't add missing values into data but keep track of them in dataBitMap dataBitMap = new boolean [ totalNPoints ] ; dataSize = 0 ; for ( int i = 0 ; i < NG ; i ++ ) { if ( NB [ i ] != 0 ) { int msng1 = bitsmv1 [ NB [ i ] ] ; int msng2 = msng1 - 1 ; for ( int j = 0 ; j < L [ i ] ; j ++ ) { data [ count ] = ( int ) reader . bits2UInt ( NB [ i ] ) ; if ( data [ count ] == msng1 || mvm == 2 && data [ count ] == msng2 ) { dataBitMap [ count ] = false ; } else { dataBitMap [ count ] = true ; data [ dataSize ++ ] = data [ count ] + X1 [ i ] ; } count ++ ; } } else { // (NB[i] == 0 int msng1 = bitsmv1 [ gdrs . numberOfBits ] ; int msng2 = msng1 - 1 ; if ( X1 [ i ] == msng1 ) { for ( int j = 0 ; j < L [ i ] ; j ++ ) { dataBitMap [ count ++ ] = false ; } //data[count++] = X1[i]; } else if ( mvm == 2 && X1 [ i ] == msng2 ) { for ( int j = 0 ; j < L [ i ] ; j ++ ) { dataBitMap [ count ++ ] = false ; } } else { for ( int j = 0 ; j < L [ i ] ; j ++ ) { dataBitMap [ count ] = true ; data [ dataSize ++ ] = X1 [ i ] ; count ++ ; } } } } // end for i } // first order spatial differencing if ( os == 1 ) { // g1 and gMin // encoded by G(n) = F(n) - F(n -1 ) // decoded by F(n) = G(n) + F(n -1 ) // data[] at this point contains G0, G1, G2, .... data [ 0 ] = ival1 ; int itemp ; if ( mvm == 0 ) { // no missing values itemp = totalNPoints ; } else { itemp = dataSize ; } for ( int i = 1 ; i < itemp ; i ++ ) { data [ i ] += minsd ; data [ i ] = data [ i ] + data [ i - 1 ] ; } } else if ( os == 2 ) { // 2nd order data [ 0 ] = ival1 ; data [ 1 ] = ival2 ; int itemp ; if ( mvm == 0 ) { // no missing values itemp = totalNPoints ; } else { itemp = dataSize ; } for ( int i = 2 ; i < itemp ; i ++ ) { data [ i ] += minsd ; data [ i ] = data [ i ] + ( 2 * data [ i - 1 ] ) - data [ i - 2 ] ; } } // formula used to create values,  Y * 10**D = R + (X1 + X2) * 2**E //               Y = (R + (X1 + X2) * (2 ** E) ) / (10 ** D)] //               WHERE: //                     Y = THE VALUE WE ARE UNPACKING //                     R = THE REFERENCE VALUE (FIRST ORDER MINIMA) //                    X1 = THE PACKED VALUE //                    X2 = THE SECOND ORDER MINIMA //                     E = THE BINARY SCALE FACTOR //                     D = THE DECIMAL SCALE FACTOR if ( mvm == 0 ) { // no missing values for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] = ( R + ( data [ i ] * EE ) ) / DD ; } } else if ( mvm == 1 || mvm == 2 ) { // missing value == 1  || missing value == 2 int count2 = 0 ; float [ ] tmp = new float [ totalNPoints ] ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( dataBitMap [ i ] ) { tmp [ i ] = ( R + ( data [ count2 ++ ] * EE ) ) / DD ; } else { // mvm = 1 or 2 tmp [ i ] = mv ; } } data = tmp ; } // bit map is used if ( bitmap != null ) { int idx = 0 ; float [ ] tmp = new float [ totalNPoints ] ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ i / 8 ] , i % 8 ) ) { tmp [ i ] = data [ idx ++ ] ; } else { tmp [ i ] = mv ; } } data = tmp ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grid point data - JPEG 2000 code stream format [CODESPLIT] private float [ ] getData40 ( RandomAccessFile raf , Grib2Drs . Type40 gdrs ) throws IOException { // 6-xx  jpeg2000 data block to decode // dataPoints are number of points encoded, it could be less than the // totalNPoints in the grid record if bitMap is used, otherwise equal //int dataPoints = drs.getDataPoints(); int nb = gdrs . numberOfBits ; int D = gdrs . decimalScaleFactor ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) D ) ; float R = gdrs . referenceValue ; int E = gdrs . binaryScaleFactor ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) E ) ; float ref_val = R / DD ; Grib2JpegDecoder g2j = null ; // try { if ( nb != 0 ) { // there's data to decode g2j = new Grib2JpegDecoder ( nb , false ) ; byte [ ] buf = new byte [ dataLength - 5 ] ; raf . readFully ( buf ) ; g2j . decode ( buf ) ; gdrs . hasSignedProblem = g2j . hasSignedProblem ( ) ; } float [ ] result = new float [ totalNPoints ] ; // no data to decode, set to reference value if ( nb == 0 ) { for ( int i = 0 ; i < dataNPoints ; i ++ ) { result [ i ] = ref_val ; } return result ; } int [ ] idata = g2j . getGdata ( ) ; if ( bitmap == null ) { // must be one decoded value in idata for every expected data point if ( idata . length != dataNPoints ) { logger . debug ( \"Number of points in the data record {} != {} expected from GDS\" , idata . length , dataNPoints ) ; throw new IllegalStateException ( \"Number of points in the data record {} != expected from GDS\" ) ; } for ( int i = 0 ; i < dataNPoints ; i ++ ) { // Y * 10^D = R + (X1 + X2) * 2^E ; // regulation 92.9.4 // Y = (R + ( 0 + X2) * EE)/DD ; result [ i ] = ( R + idata [ i ] * EE ) / DD ; } return result ; } else { // use bitmap to skip missing values for ( int i = 0 , j = 0 ; i < totalNPoints ; i ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ i / 8 ] , i % 8 ) ) { if ( j >= idata . length ) { logger . warn ( \"HEY jj2000 data count %d < bitmask count %d, i=%d, totalNPoints=%d%n\" , idata . length , j , i , totalNPoints ) ; break ; } int indata = idata [ j ] ; result [ i ] = ( R + indata * EE ) / DD ; j ++ ; } else { result [ i ] = staticMissingValue ; } } } return result ; /* } catch (NullPointerException npe) {\n\n      logger.error(\"Grib2DataReader2.jpeg2000Unpacking: bit rate too small nb =\" + nb + \" for file\" + raf.getLocation());\n      float[] data = new float[dataNPoints];\n      for (int i = 0; i < dataNPoints; i++) {\n        data[i] = staticMissingValue;  // LOOK ??\n      }\n      return data;\n    } */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grid point data - JPEG 2000 code stream format [CODESPLIT] @ Nullable private int [ ] getData40raw ( RandomAccessFile raf , Grib2Drs . Type40 gdrs ) throws IOException { int nb = gdrs . numberOfBits ; if ( nb == 0 ) { return null ; } int missing_value = ( 2 << nb - 1 ) - 1 ; // all ones - reserved for missing value Grib2JpegDecoder g2j ; g2j = new Grib2JpegDecoder ( nb , false ) ; byte [ ] buf = new byte [ dataLength - 5 ] ; raf . readFully ( buf ) ; g2j . decode ( buf ) ; gdrs . hasSignedProblem = g2j . hasSignedProblem ( ) ; int [ ] idata = g2j . getGdata ( ) ; if ( bitmap == null ) { // must be one decoded value in idata for every expected data point if ( idata . length != totalNPoints ) { logger . debug ( \"Number of points in the data record {} != {} expected from GDS\" , idata . length , totalNPoints ) ; return null ; } return idata ; } else { // use bitmap to skip missing values int [ ] result = new int [ totalNPoints ] ; for ( int i = 0 , j = 0 ; i < totalNPoints ; i ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ i / 8 ] , i % 8 ) ) { if ( j >= idata . length ) { logger . warn ( \"HEY jj2000 data count %d < bitmask count %d, i=%d, totalNPoints=%d%n\" , idata . length , j , i , totalNPoints ) ; break ; } result [ i ] = idata [ j ] ; j ++ ; } else { result [ i ] = missing_value ; } } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Code taken from esupport ticket ZVT - 415274 [CODESPLIT] private float [ ] getData41 ( RandomAccessFile raf , Grib2Drs . Type0 gdrs ) throws IOException { int nb = gdrs . numberOfBits ; int D = gdrs . decimalScaleFactor ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) D ) ; float R = gdrs . referenceValue ; int E = gdrs . binaryScaleFactor ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) E ) ; // LOOK: can # datapoints differ from bitmap and data ? // dataPoints are number of points encoded, it could be less than the // totalNPoints in the grid record if bitMap is used, otherwise equal float [ ] data = new float [ totalNPoints ] ; // no data to decode, set to reference value if ( nb == 0 ) { Arrays . fill ( data , R ) ; return data ; } //  Y * 10**D = R + (X1 + X2) * 2**E //   E = binary scale factor //   D = decimal scale factor //   R = reference value //   X1 = 0 //   X2 = scaled encoded value //   data[ i ] = (R + ( X1 + X2) * EE)/DD ; byte [ ] buf = new byte [ dataLength - 5 ] ; raf . readFully ( buf ) ; InputStream in = new ByteArrayInputStream ( buf ) ; BufferedImage image = ImageIO . read ( in ) ; if ( nb != image . getColorModel ( ) . getPixelSize ( ) ) { logger . debug ( \"PNG pixel size disagrees with grib number of bits: \" , image . getColorModel ( ) . getPixelSize ( ) , nb ) ; } DataBuffer db = image . getRaster ( ) . getDataBuffer ( ) ; if ( bitmap == null ) { for ( int i = 0 ; i < dataNPoints ; i ++ ) { data [ i ] = ( R + db . getElem ( i ) * EE ) / DD ; } } else { for ( int bitPt = 0 , dataPt = 0 ; bitPt < totalNPoints ; bitPt ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ bitPt / 8 ] , bitPt % 8 ) ) { data [ bitPt ] = ( R + db . getElem ( dataPt ++ ) * EE ) / DD ; } else { data [ bitPt ] = staticMissingValue ; } } } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ported from https : // github . com / erdc - cm / grib_api / blob / master / src / grib_accessor_class_data_g1second_order_general_extended_packing . c [CODESPLIT] private float [ ] getData50002 ( RandomAccessFile raf , Grib2Drs . Type50002 gdrs ) throws IOException { BitReader reader ; reader = new BitReader ( raf , startPos + 5 ) ; int [ ] groupWidth = new int [ gdrs . p1 ] ; for ( int i = 0 ; i < gdrs . p1 ; i ++ ) { groupWidth [ i ] = ( int ) reader . bits2UInt ( gdrs . widthOfWidth ) ; } reader = new BitReader ( raf , raf . getFilePointer ( ) ) ; int [ ] groupLength = new int [ gdrs . p1 ] ; for ( int i = 0 ; i < gdrs . p1 ; i ++ ) { groupLength [ i ] = ( int ) reader . bits2UInt ( gdrs . widthOfLength ) ; } reader = new BitReader ( raf , raf . getFilePointer ( ) ) ; int [ ] firstOrderValues = new int [ gdrs . p1 ] ; for ( int i = 0 ; i < gdrs . p1 ; i ++ ) { firstOrderValues [ i ] = ( int ) reader . bits2UInt ( gdrs . widthOfFirstOrderValues ) ; } int bias = 0 ; if ( gdrs . orderOfSPD > 0 ) { bias = gdrs . spd [ gdrs . orderOfSPD ] ; } reader = new BitReader ( raf , raf . getFilePointer ( ) ) ; int cnt = gdrs . orderOfSPD ; int [ ] data = new int [ totalNPoints ] ; for ( int i = 0 ; i < gdrs . p1 ; i ++ ) { if ( groupWidth [ i ] > 0 ) { for ( int j = 0 ; j < groupLength [ i ] ; j ++ ) { data [ cnt ] = ( int ) reader . bits2UInt ( groupWidth [ i ] ) ; data [ cnt ] += firstOrderValues [ i ] ; cnt ++ ; } } else { for ( int j = 0 ; j < groupLength [ i ] ; j ++ ) { data [ cnt ] = firstOrderValues [ i ] ; cnt ++ ; } } } if ( gdrs . orderOfSPD >= 0 ) { System . arraycopy ( gdrs . spd , 0 , data , 0 , gdrs . orderOfSPD ) ; } int y , z , w ; switch ( gdrs . orderOfSPD ) { case 1 : y = data [ 0 ] ; for ( int i = 1 ; i < totalNPoints ; i ++ ) { y += data [ i ] + bias ; data [ i ] = y ; } break ; case 2 : y = data [ 1 ] - data [ 0 ] ; z = data [ 1 ] ; for ( int i = 2 ; i < totalNPoints ; i ++ ) { y += data [ i ] + bias ; z += y ; data [ i ] = z ; } break ; case 3 : y = data [ 2 ] - data [ 1 ] ; z = y - ( data [ 1 ] - data [ 0 ] ) ; w = data [ 2 ] ; for ( int i = 3 ; i < totalNPoints ; i ++ ) { z += data [ i ] + bias ; y += z ; w += y ; data [ i ] = w ; } break ; } int D = gdrs . decimalScaleFactor ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) D ) ; float R = gdrs . referenceValue ; int E = gdrs . binaryScaleFactor ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) E ) ; float [ ] ret = new float [ totalNPoints ] ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { ret [ i ] = ( ( ( data [ i ] * EE ) + R ) * DD ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOOK might be wrong for a quasi regular ( thin ) grid ?? [CODESPLIT] private void scanningModeCheck ( float [ ] data , int scanMode , int Xlength ) { // Mode  0  +x, -y, adjacent x, adjacent rows same dir // Mode  64 +x, +y, adjacent x, adjacent rows same dir if ( ( scanMode == 0 ) || ( scanMode == 64 ) ) // dont flip Y - handle it in the HorizCoordSys { return ; } // change -x to +x ie east to west -> west to east if ( ! GribUtils . scanModeXisPositive ( scanMode ) ) { float tmp ; int mid = Xlength / 2 ; for ( int index = 0 ; index < data . length ; index += Xlength ) { for ( int idx = 0 ; idx < mid ; idx ++ ) { tmp = data [ index + idx ] ; data [ index + idx ] = data [ index + Xlength - idx - 1 ] ; data [ index + Xlength - idx - 1 ] = tmp ; } } return ; } if ( ! GribUtils . scanModeSameDirection ( scanMode ) ) { float tmp ; int mid = Xlength / 2 ; for ( int index = 0 ; index < data . length ; index += Xlength ) { int row = index / Xlength ; if ( row % 2 != 0 ) { // odd numbered row, calculate reverse index for ( int idx = 0 ; idx < mid ; idx ++ ) { tmp = data [ index + idx ] ; data [ index + idx ] = data [ index + Xlength - idx - 1 ] ; data [ index + Xlength - idx - 1 ] = tmp ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "AbstractCursor Abstract Methods [CODESPLIT] @ Override public Object read ( List < Slice > slices ) throws DapException { switch ( this . scheme ) { case ATOMIC : return readAtomic ( slices ) ; case STRUCTURE : if ( ( ( DapVariable ) this . getTemplate ( ) ) . getRank ( ) > 0 || DapUtil . isScalarSlices ( slices ) ) throw new DapException ( \"Cannot slice a scalar variable\" ) ; CDMCursor [ ] instances = new CDMCursor [ 1 ] ; instances [ 0 ] = this ; return instances ; case SEQUENCE : if ( ( ( DapVariable ) this . getTemplate ( ) ) . getRank ( ) > 0 || DapUtil . isScalarSlices ( slices ) ) throw new DapException ( \"Cannot slice a scalar variable\" ) ; instances = new CDMCursor [ 1 ] ; instances [ 0 ] = this ; return instances ; case STRUCTARRAY : Odometer odom = Odometer . factory ( slices ) ; instances = new CDMCursor [ ( int ) odom . totalSize ( ) ] ; for ( int i = 0 ; odom . hasNext ( ) ; i ++ ) { instances [ i ] = readStructure ( odom . next ( ) ) ; } return instances ; case SEQARRAY : instances = readSequence ( slices ) ; return instances ; default : throw new DapException ( \"Attempt to slice a scalar object\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support Methods [CODESPLIT] protected Object readAtomic ( List < Slice > slices ) throws DapException { if ( slices == null ) throw new DapException ( \"DataCursor.read: null set of slices\" ) ; assert ( this . scheme == scheme . ATOMIC ) ; DapVariable atomvar = ( DapVariable ) getTemplate ( ) ; assert slices != null && ( ( atomvar . getRank ( ) == 0 && slices . size ( ) == 1 ) || ( slices . size ( ) == atomvar . getRank ( ) ) ) ; return sliceAtomic ( slices , this . array , atomvar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a netcdf - 3 file from a subset of a grid dataset [CODESPLIT] static public void makeFile ( String location , ucar . nc2 . dt . GridDataset gds , List < String > gridList , LatLonRect llbb , CalendarDateRange range ) throws IOException , InvalidRangeException { CFGridWriter writer = new CFGridWriter ( ) ; writer . makeFile ( location , gds , gridList , llbb , range , false , 1 , 1 , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a netcdf - 3 file from a subset of a grid dataset as long as it doesnt exceed a certain file size . [CODESPLIT] public long makeGridFileSizeEstimate ( ucar . nc2 . dt . GridDataset gds , List < String > gridList , LatLonRect llbb , int horizStride , Range zRange , CalendarDateRange dateRange , int stride_time , boolean addLatLon ) throws IOException , InvalidRangeException { return makeOrTestSize ( null , gds , gridList , llbb , horizStride , zRange , dateRange , stride_time , addLatLon , true , NetcdfFileWriter . Version . netcdf3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a CF compliant Netcdf - 3 file from any gridded dataset . [CODESPLIT] public void makeFile ( String location , ucar . nc2 . dt . GridDataset gds , List < String > gridList , LatLonRect llbb , CalendarDateRange range , boolean addLatLon , int horizStride , int stride_z , int stride_time ) throws IOException , InvalidRangeException { makeFile ( location , gds , gridList , llbb , horizStride , null , range , stride_time , addLatLon , NetcdfFileWriter . Version . netcdf3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the coordinate transformations ( formula_terms ) and adds the variables needed for performing that transformation to the list of variables in the new file . Also subsets the grids variables if needed . [CODESPLIT] private long processTransformationVars ( ArrayList < Variable > varList , ArrayList < String > varNameList , NetcdfDataset ncd , ucar . nc2 . dt . GridDataset gds , GridDatatype grid , Range timeRange , Range zRangeUse , LatLonRect llbb , int z_stride , int y_stride , int x_stride , List < CoordinateAxis > axisList ) throws InvalidRangeException { List < Range > yxRanges = new ArrayList < Range > ( 2 ) ; if ( llbb == null ) { yxRanges . add ( null ) ; yxRanges . add ( null ) ; } else { yxRanges = grid . getCoordinateSystem ( ) . getRangesFromLatLonRect ( llbb ) ; } return processTransformationVars ( varList , varNameList , ncd , gds , grid , timeRange , zRangeUse , yxRanges . get ( 0 ) , yxRanges . get ( 1 ) , z_stride , y_stride , x_stride ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the list of stations . [CODESPLIT] public void setStations ( java . util . List < ucar . unidata . geoloc . Station > stns ) { stations = new ArrayList < StationUI > ( stns . size ( ) ) ; stationHash . clear ( ) ; for ( int i = 0 ; i < stns . size ( ) ; i ++ ) { ucar . unidata . geoloc . Station s = ( ucar . unidata . geoloc . Station ) stns . get ( i ) ; StationUI sui = new StationUI ( s ) ; // wrap in a StationUI stations . add ( sui ) ; // wrap in a StationUI stationHash . put ( s . getName ( ) , sui ) ; } posWasCalc = false ; calcWorldPos ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set selected station based on the sttion id . [CODESPLIT] public void setSelectedStation ( String name ) { StationUI sui = ( StationUI ) stationHash . get ( name ) ; if ( sui != null ) { setSelectedStation ( sui ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find station that contains this point . If it exists make it the selected station . [CODESPLIT] public ucar . unidata . geoloc . Station pick ( Point2D pickPt ) { if ( world2Normal == null || pickPt == null || stations . isEmpty ( ) ) return null ; world2Normal . transform ( pickPt , ptN ) ; // work in normalized coordinate space StationUI closest = ( StationUI ) stationGrid . findIntersection ( ptN ) ; setSelectedStation ( closest ) ; return getSelectedStation ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find station closest to this point . Make it the selected station . [CODESPLIT] public ucar . unidata . geoloc . Station pickClosest ( Point2D pickPt ) { if ( world2Normal == null || pickPt == null || stations . isEmpty ( ) ) return null ; world2Normal . transform ( pickPt , ptN ) ; // work in normalized coordinate space StationUI closest = ( StationUI ) stationGrid . findClosest ( ptN ) ; if ( debug ) System . out . println ( \"closest= \" + closest ) ; setSelectedStation ( closest ) ; return getSelectedStation ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the selected station . [CODESPLIT] public ucar . unidata . geoloc . Station getSelectedStation ( ) { return ( selected != null ) ? selected . ddStation : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void merge ( Element iospParam ) { assert iospParam . getName ( ) . equals ( \"iospParam\" ) ; Element bufr2nc = iospParam . getChild ( \"bufr2nc\" , Catalog . ncmlNS ) ; if ( bufr2nc == null ) return ; for ( Element child : bufr2nc . getChildren ( \"fld\" , Catalog . ncmlNS ) ) merge ( child , rootConverter ) ; } private void merge ( Element jdom , FieldConverter parent ) { if ( jdom == null || parent == null ) return ; FieldConverter fld = null ; // find the corresponding field String idxName = jdom . getAttributeValue ( \"idx\" ) ; if ( idxName != null ) { try { int idx = Integer . parseInt ( idxName ) ; fld = parent . getChild ( idx ) ; } catch ( NumberFormatException ne ) { log . info ( \"BufrConfig cant find Child member index={} for file = {}\" , idxName , filename ) ; } } if ( fld == null ) { String fxyName = jdom . getAttributeValue ( \"fxy\" ) ; if ( fxyName != null ) { fld = parent . findChildByFxyName ( fxyName ) ; if ( fld == null ) { log . info ( \"BufrConfig cant find Child member fxy={} for file = {}\" , fxyName , filename ) ; } } } if ( fld == null ) { String name = jdom . getAttributeValue ( \"name\" ) ; if ( name != null ) { fld = parent . findChild ( name ) ; if ( fld == null ) { log . info ( \"BufrConfig cant find Child member name={} for file = {}\" , name , filename ) ; } } } if ( fld == null ) { log . info ( \"BufrConfig must have idx, name or fxy attribute = {} for file = {}\" , jdom , filename ) ; return ; } String action = jdom . getAttributeValue ( \"action\" ) ; if ( action != null && ! action . isEmpty ( ) ) fld . setAction ( action ) ; if ( jdom . getChildren ( \"fld\" ) != null ) { for ( Element child : jdom . getChildren ( \"fld\" , Catalog . ncmlNS ) ) { merge ( child , fld ) ; } } } //////////////////////////////////////////////////////////////////////////// private StandardFields . StandardFieldsFromStructure extract ; private boolean hasStations = false ; private boolean hasDate = false ; private int countObs = 0 ; private void scanBufrFile  ( RandomAccessFile raf ) throws Exception { NetcdfFile ncd = null ; countObs = 0 ; try { MessageScanner scanner = new MessageScanner ( raf ) ; Message protoMessage = scanner . getFirstDataMessage ( ) ; if ( protoMessage == null ) throw new IOException ( \"No message found!\" ) ; messHash = protoMessage . hashCode ( ) ; standardFields = StandardFields . extract ( protoMessage ) ; rootConverter = new FieldConverter ( protoMessage . ids . getCenterId ( ) , protoMessage . getRootDataDescriptor ( ) ) ; if ( standardFields . hasStation ( ) ) { hasStations = true ; map = new HashMap <> ( 1000 ) ; } featureType = guessFeatureType ( standardFields ) ; hasDate = standardFields . hasTime ( ) ; //ncd = NetcdfDataset.openDataset(raf.getLocation(), BufrIosp2.enhance, -1, null, null); // LOOK opening another raf ncd = NetcdfFile . open ( raf . getLocation ( ) ) ; // LOOK opening another raf Attribute centerAtt = ncd . findGlobalAttribute ( BufrIosp2 . centerId ) ; int center = ( centerAtt == null ) ? 0 : centerAtt . getNumericValue ( ) . intValue ( ) ; Sequence seq = ( Sequence ) ncd . findVariable ( null , BufrIosp2 . obsRecord ) ; extract = new StandardFields . StandardFieldsFromStructure ( center , seq ) ; StructureDataIterator iter = seq . getStructureIterator ( ) ; processSeq ( iter , rootConverter , true ) ; setStandardActions ( rootConverter ) ; } finally { if ( ncd != null ) ncd . close ( ) ; } System . out . printf ( \"nobs = %d%n\" , countObs ) ; } private FeatureType guessFeatureType  ( StandardFields . StandardFieldsFromMessage standardFields ) { if ( standardFields . hasStation ( ) ) return FeatureType . STATION ; if ( standardFields . hasTime ( ) ) return FeatureType . POINT ; return FeatureType . ANY ; } private void setStandardActions  ( FieldConverter fld ) { fld . setAction ( fld . makeAction ( ) ) ; if ( fld . flds == null ) return ; for ( FieldConverter child : fld . flds ) setStandardActions ( child ) ; } ///////////////////////////////////////////////////////////////////////////////////// private CalendarDate today = CalendarDate . present ( ) ; private void processSeq  ( StructureDataIterator sdataIter , FieldConverter parent , boolean isTop ) throws IOException { try { while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; if ( isTop ) { countObs ++ ; if ( debug && countObs % 100 == 0 ) System . out . printf ( \"%d \" , countObs ) ; if ( hasStations ) processStations ( parent , sdata ) ; if ( hasDate ) { extract . extract ( sdata ) ; CalendarDate date = extract . makeCalendarDate ( ) ; if ( Math . abs ( date . getDifferenceInMsecs ( today ) ) > 1000L * 3600 * 24 * 100 ) { extract . makeCalendarDate ( ) ; } long msecs = date . getMillis ( ) ; if ( this . start > msecs ) { this . start = msecs ; //System.out.printf(\"new start %s%n\", date); } if ( this . end < msecs ) { this . end = msecs ; //System.out.printf(\"new end %s%n\", date); } } } int count = 0 ; for ( StructureMembers . Member m : sdata . getMembers ( ) ) { if ( m . getDataType ( ) == DataType . SEQUENCE ) { FieldConverter fld = parent . getChild ( count ) ; ArraySequence data = ( ArraySequence ) sdata . getArray ( m ) ; int n = data . getStructureDataCount ( ) ; fld . trackSeqCounts ( n ) ; processSeq ( data . getStructureDataIterator ( ) , fld , false ) ; } count ++ ; } } } finally { sdataIter . close ( ) ; } } private void processStations  ( FieldConverter parent , StructureData sdata ) { BufrStation station = new BufrStation ( ) ; station . read ( parent , sdata ) ; if ( station . getName ( ) == null ) { log . warn ( \"bad station name: \" + station ) ; return ; } BufrStation check = map . get ( station . getName ( ) ) ; if ( check == null ) map . put ( station . getName ( ) , station ) ; else { check . count ++ ; if ( ! station . equals ( check ) ) log . warn ( \"bad station doesnt equal \" + station + \" != \" + check ) ; } } public class BufrStation extends StationImpl { public int count = 1 ; void read ( FieldConverter parent , StructureData sdata ) { extract . extract ( sdata ) ; setName ( extract . getStationId ( ) ) ; setLatitude ( extract . getFieldValueD ( BufrCdmIndexProto . FldType . lat ) ) ; setLongitude ( extract . getFieldValueD ( BufrCdmIndexProto . FldType . lon ) ) ; if ( extract . hasField ( BufrCdmIndexProto . FldType . stationDesc ) ) setDescription ( extract . getFieldValueS ( BufrCdmIndexProto . FldType . stationDesc ) ) ; if ( extract . hasField ( BufrCdmIndexProto . FldType . wmoId ) ) setWmoId ( extract . getFieldValueS ( BufrCdmIndexProto . FldType . wmoId ) ) ; if ( extract . hasField ( BufrCdmIndexProto . FldType . heightOfStation ) ) setAltitude ( extract . getFieldValueD ( BufrCdmIndexProto . FldType . heightOfStation ) ) ; } /* void read(FieldConverter parent, StructureData sdata) {\n      int count = 0;\n      List<FieldConverter> flds = parent.getChildren(); // asssume these track exactly the members\n      for (StructureMembers.Member m : sdata.getMembers()) {\n        FieldConverter fld = flds.get(count++);\n        if (fld.getType() == null) continue;\n\n        switch (fld.getType()) {\n          case stationId:\n            setName( readString(sdata, m));\n            break;\n          case stationDesc:\n            setDescription(sdata.getScalarString(m));\n            break;\n          case wmoId:\n            setWmoId(readString(sdata, m));\n            break;\n          case lat:\n            setLatitude(sdata.convertScalarDouble(m));\n            break;\n          case lon:\n            setLongitude(sdata.convertScalarDouble(m));\n            break;\n          case height:\n            setAltitude(sdata.convertScalarDouble(m));\n            break;\n          case heightOfStation:\n            setAltitude(sdata.convertScalarDouble(m));\n            break;\n        }\n      }\n    }\n\n    String readString(StructureData sdata, StructureMembers.Member m) {\n      if (m.getDataType().isString())\n        return sdata.getScalarString(m);\n      else if (m.getDataType().isIntegral())\n        return Integer.toString(sdata.convertScalarInt(m));\n      else if (m.getDataType().isNumeric())\n        return Double.toString(sdata.convertScalarDouble(m));\n      else return \"type \"+ m.getDataType();\n    }  */ @ Override public boolean equals ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) != o . getClass ( ) ) return false ; BufrStation that = ( BufrStation ) o ; if ( Double . compare ( that . alt , alt ) != 0 ) return false ; if ( Double . compare ( that . lat , lat ) != 0 ) return false ; if ( Double . compare ( that . lon , lon ) != 0 ) return false ; if ( desc != null ? ! desc . equals ( that . desc ) : that . desc != null ) return false ; if ( ! name . equals ( that . name ) ) return false ; if ( wmoId != null ? ! wmoId . equals ( that . wmoId ) : that . wmoId != null ) return false ; return true ; } @ Override public int hashCode ( ) { int result ; long temp ; temp = Double . doubleToLongBits ( lat ) ; result = ( int ) ( temp ^ ( temp >>> 32 ) ) ; temp = Double . doubleToLongBits ( lon ) ; result = 31 * result + ( int ) ( temp ^ ( temp >>> 32 ) ) ; temp = Double . doubleToLongBits ( alt ) ; result = 31 * result + ( int ) ( temp ^ ( temp >>> 32 ) ) ; result = 31 * result + name . hashCode ( ) ; result = 31 * result + ( desc != null ? desc . hashCode ( ) : 0 ) ; result = 31 * result + ( wmoId != null ? wmoId . hashCode ( ) : 0 ) ; return result ; } } ///////////////////////////////////////////////////////////////////////////////////////////////////// public class FieldConverter implements BufrField { DataDescriptor dds ; List < FieldConverter > flds ; BufrCdmIndexProto . FldType type ; BufrCdmIndexProto . FldAction action ; int min = Integer . MAX_VALUE ; int max = 0 ; boolean isSeq ; private FieldConverter ( int center , DataDescriptor dds ) { this . dds = dds ; this . type = StandardFields . findField ( center , dds . getFxyName ( ) ) ; if ( dds . getSubKeys ( ) != null ) { this . flds = new ArrayList <> ( dds . getSubKeys ( ) . size ( ) ) ; for ( DataDescriptor subdds : dds . getSubKeys ( ) ) { FieldConverter subfld = new FieldConverter ( center , subdds ) ; flds . add ( subfld ) ; } } } public String getName ( ) { return dds . getName ( ) ; } public String getDesc ( ) { return dds . getDesc ( ) ; } public String getUnits ( ) { return dds . getUnits ( ) ; } public short getFxy ( ) { return dds . getFxy ( ) ; } public String getFxyName ( ) { return dds . getFxyName ( ) ; } public BufrCdmIndexProto . FldAction getAction ( ) { return action ; } public BufrCdmIndexProto . FldType getType ( ) { return type ; } public List < FieldConverter > getChildren ( ) { return flds ; } public boolean isSeq ( ) { return isSeq ; } public int getMin ( ) { return min ; } public int getMax ( ) { return max ; } public int getScale ( ) { return dds . getScale ( ) ; } public int getReference ( ) { return dds . getRefVal ( ) ; } public int getBitWidth ( ) { return dds . getBitWidth ( ) ; } public void setAction ( String action ) { BufrCdmIndexProto . FldAction act = BufrCdmIndexProto . FldAction . valueOf ( action ) ; if ( act != null ) this . action = act ; } public void setAction ( BufrCdmIndexProto . FldAction action ) { this . action = action ; } FieldConverter findChild ( String want ) { for ( FieldConverter child : flds ) { String name = child . dds . getName ( ) ; if ( name != null && name . equals ( want ) ) return child ; } return null ; } FieldConverter findChildByFxyName ( String fxyName ) { for ( FieldConverter child : flds ) { String name = child . dds . getFxyName ( ) ; if ( name != null && name . equals ( fxyName ) ) return child ; } return null ; } public FieldConverter getChild ( int i ) { return flds . get ( i ) ; } void trackSeqCounts ( int n ) { isSeq = true ; if ( n > max ) max = n ; if ( n < min ) min = n ; } void showRange ( Formatter f ) { if ( ! isSeq ) return ; if ( max == min ) f . format ( \" isConstant='%d'\" , max ) ; else if ( max < 2 ) f . format ( \" isBinary='true'\" ) ; else f . format ( \" range='[%d,%d]'\" , min , max ) ; } BufrCdmIndexProto . FldAction makeAction ( ) { if ( ! isSeq ) return null ; if ( max == 0 ) return BufrCdmIndexProto . FldAction . remove ; if ( max < 2 ) return BufrCdmIndexProto . FldAction . asMissing ; else return BufrCdmIndexProto . FldAction . asArray ; } void show ( Formatter f , Indent indent , int index ) { boolean hasContent = false ; if ( isSeq ) f . format ( \"%s<fld idx='%d' name='%s'\" , indent , index , dds . getName ( ) ) ; else f . format ( \"%s<fld idx='%d' fxy='%s' name='%s' desc='%s' units='%s' bits='%d'\" , indent , index , dds . getFxyName ( ) , dds . getName ( ) , dds . getDesc ( ) , dds . getUnits ( ) , dds . getBitWidth ( ) ) ; if ( type != null ) f . format ( \" type='%s'\" , type ) ; showRange ( f ) ; f . format ( \" action='%s'\" , makeAction ( ) ) ; /* if (type != null) {\n        f.format(\">%n\");\n        indent.incr();\n        f.format(\"%s<type>%s</type>%n\", indent, type);\n        indent.decr();\n        hasContent = true;\n      } */ if ( flds != null ) { f . format ( \">%n\" ) ; indent . incr ( ) ; int subidx = 0 ; for ( FieldConverter cc : flds ) { cc . show ( f , indent , subidx ++ ) ; } indent . decr ( ) ; hasContent = true ; } if ( hasContent ) f . format ( \"%s</fld>%n\" , indent ) ; else f . format ( \" />%n\" ) ; } } ////////////////////////////////////////////////////////////////////////////////////////////////////// public void show  ( Formatter out ) { if ( standardFields != null ) out . format ( \"Standard Fields%n%s%n%n\" , standardFields ) ; Indent indent = new Indent ( 2 ) ; out . format ( \"<bufr2nc location='%s' hash='%s' featureType='%s'>%n\" , filename , Integer . toHexString ( messHash ) , featureType ) ; indent . incr ( ) ; int index = 0 ; for ( FieldConverter fld : rootConverter . flds ) { fld . show ( out , indent , index ++ ) ; } indent . decr ( ) ; out . format ( \"</bufr2nc>%n\" ) ; } public static void main  ( String [ ] args ) throws IOException { String filename = \"G:/work/manross/split/872d794d.bufr\" ; //String filename = \"Q:/cdmUnitTest/formats/bufr/US058MCUS-BUFtdp.SPOUT_00011_buoy_20091101021700.bufr\"; try ( RandomAccessFile raf = new RandomAccessFile ( filename , \"r\" ) ) { BufrConfig config = BufrConfig . scanEntireFile ( raf ) ; Formatter out = new Formatter ( ) ; config . show ( out ) ; System . out . printf ( \"%s%n\" , out ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message DataRoot { required string urlPath = 1 ; required string dirLocation = 2 ; required DataRootType type = 3 ; optional string catLocation = 4 ; // omit for simple dataset root } [CODESPLIT] public void writeExternal ( DataOutputStream out ) throws IOException { ConfigCatalogExtProto . DataRoot . Builder builder = ConfigCatalogExtProto . DataRoot . newBuilder ( ) ; builder . setUrlPath ( path ) ; builder . setDirLocation ( dirLocation ) ; builder . setType ( convertDataRootType ( type ) ) ; if ( type != DataRoot . Type . datasetRoot ) { builder . setCatLocation ( catLocation ) ; builder . setName ( name ) ; } if ( restrict != null ) builder . setRestrict ( restrict ) ; ConfigCatalogExtProto . DataRoot index = builder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; out . writeInt ( b . length ) ; out . write ( b ) ; total_count ++ ; total_nbytes += b . length + 4 ; if ( debug ) System . out . printf ( \" %d: DataRootExt.writeExternal len=%d total=%d%n\" , total_count , b . length , total_nbytes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Type { datasetRoot datasetScan catalogScan featureCollection } [CODESPLIT] static public DataRoot . Type convertDataRootType ( ConfigCatalogExtProto . DataRootType type ) { switch ( type ) { case datasetRoot : return DataRoot . Type . datasetRoot ; case datasetScan : return DataRoot . Type . datasetScan ; case catalogScan : return DataRoot . Type . catalogScan ; case featureCollection : return DataRoot . Type . featureCollection ; } throw new IllegalStateException ( \"illegal DataRootType \" + type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the parameters for the GDS [CODESPLIT] private void setParams ( ) { /* PS and CONF projection parameters */ double xrowi ; // row # of North Pole*10000 double xcoli ; // column # of North Pole* 10000 double xqlon ; // longitude parallel to columns double xspace ; // column spacing at standard latitude double yspace ; // row spacing at standard latitude double xt1 ; // standard latitude double xt2 ; // 2nd standard latitude double xh ; // double xfac ; // double xblat ; // /* Merc and pseudo_merc parameters */ double glamx ; // max latitude double glomx ; // max longitude double glamn ; // min latitude double glomn ; // min longitude double ginct ; // grid increment in latitude double gincn ; // grid increment in longitude try { GRIDnav nav = new GRIDnav ( vals ) ; int gridType = vals [ 33 ] ; int navType = gridType % 10 ; addParam ( \"Proj\" , String . valueOf ( navType ) ) ; boolean wierd = gridType / 10 == 1 ; int ny = vals [ 1 ] ; int nx = vals [ 2 ] ; addParam ( PROJ , getProjName ( navType ) ) ; addParam ( NX , String . valueOf ( nx ) ) ; addParam ( NY , String . valueOf ( ny ) ) ; double [ ] [ ] input ; if ( nav . isFlippedRowCoordinates ( ) ) { input = new double [ ] [ ] { { 1 , nx } , { 1 , ny } } ; } else { input = new double [ ] [ ] { { 1 , nx } , { ny , 1 } } ; } double [ ] [ ] llur = nav . toLatLon ( input ) ; /*\n            if (cnt == 0 && navType == 6) {\n                System.out.println(\"Proj = \" + getProjName(navType) + \":\" + navType);\n                System.out.println(\"isFlipped = \" + nav.isFlippedRowCoordinates());\n                ucar.unidata.util.Misc.printArray(\"input x\", input[0]);\n                ucar.unidata.util.Misc.printArray(\"input y\", input[1]);\n                ucar.unidata.util.Misc.printArray(\"lats\", llur[0]);\n                ucar.unidata.util.Misc.printArray(\"lons\", llur[1]);\n                cnt++;\n            }\n            */ addParam ( LA1 , String . valueOf ( llur [ 0 ] [ 0 ] ) ) ; addParam ( LO1 , String . valueOf ( llur [ 1 ] [ 0 ] ) ) ; addParam ( LA2 , String . valueOf ( llur [ 0 ] [ 1 ] ) ) ; addParam ( LO2 , String . valueOf ( llur [ 1 ] [ 1 ] ) ) ; switch ( navType ) { case PSEUDO_MERCATOR : case PSEUDO_MERCATOR_GENERAL : glamx = vals [ 34 ] / 10000. ; glomx = - vals [ 35 ] / 10000. ; glamn = vals [ 34 ] / 10000. ; glomn = - vals [ 35 ] / 10000. ; ginct = vals [ 38 ] / 10000. ; gincn = ( navType == PSEUDO_MERCATOR_GENERAL ) ? vals [ 39 ] / 10000. : ginct ; addParam ( \"Latin\" , String . valueOf ( 20 ) ) ; //addParam(DX, String.valueOf(gincn)); //addParam(DY, String.valueOf(ginct)); /*\n                  if (wierd) {\n                    double x = xnr;\n                    xnr = xnc;\n                    xnc = x;\n                  }\n                  */ break ; case PS_OR_LAMBERT_CONIC : xrowi = vals [ 34 ] / 10000. ; // row # of the North pole*10000 xcoli = vals [ 35 ] / 10000. ; // col # of the North pole*10000 xspace = vals [ 36 ] ; // column spacing at standard lat (m) xqlon = - vals [ 37 ] / 10000. ; // lon parallel to cols (deg*10000) xt1 = vals [ 38 ] / 10000. ; // first standard lat xt2 = vals [ 39 ] / 10000. ; // second standard lat addParam ( LATIN1 , String . valueOf ( xt1 ) ) ; addParam ( LOV , String . valueOf ( xqlon ) ) ; addParam ( LATIN2 , String . valueOf ( xt2 ) ) ; addParam ( DX , String . valueOf ( xspace ) ) ; addParam ( DY , String . valueOf ( xspace ) ) ; /*\n                  xh = (xt1 >= 0) ? 1. : -1.;\n                  xt1 =(90.-xh*xt1)*xrad;\n                  xt2 =(90.-xh*xt2)*xrad;\n                  xfac =1.0;\n                  if (xt1 != xt2)\n                     xfac = (Math.log(Math.sin(xt1))-Math.log(Math.sin(xt2)))/\n                            (Math.log(Math.tan(.5*xt1))-Math.log(Math.tan(.5*xt2)));\n                  xfac = 1.0/xfac;\n                  xblat = 6370. * Math.sin(xt1)/\n                           (xspace*xfac*(Math.pow(Math.tan(xt1*.5),xfac)));\n                  if (wierd) {\n                     double x=xnr;\n                     xnr=xnc;\n                     xnc=x;\n                     x=xcoli;\n                     xcoli=xrowi;\n                     xrowi=xnr-x+1.0;\n                     xqlon=xqlon+90.;\n                  }\n                  */ break ; case EQUIDISTANT : xrowi = 1. ; xcoli = 1. ; glamx = vals [ 34 ] / 10000. ; // lat of (1,1) degrees*10000 glomx = - vals [ 35 ] / 10000. ; // lon of (1,1) degrees*10000 //xrot  = -xrad*vals[36]/10000.; // clockwise rotation of col 1 xspace = vals [ 37 ] / 1000. ; // column spacing yspace = vals [ 38 ] / 1000. ; // row spacing addParam ( LA1 , String . valueOf ( glamx ) ) ; addParam ( LO1 , String . valueOf ( glomx ) ) ; addParam ( DX , String . valueOf ( xspace ) ) ; addParam ( DY , String . valueOf ( yspace ) ) ; /*\n                  xblat = EARTH_RADIUS*xrad/yspace;\n                  xblon = EARTH_RADIUS*xrad/xspace;\n\n                  if (wierd) {\n                    double x = xnr;\n                    xnr = xnc;\n                    xnc = x;\n                  }\n                  */ break ; case LAMBERT_CONFORMAL_TANGENT : xrowi = vals [ 34 ] / 10000. ; // lat at (1,1) xcoli = vals [ 35 ] / 10000. ; // lon at (1,1) xspace = vals [ 36 ] ; // column spacing at standard lat (m) xqlon = - vals [ 37 ] / 10000. ; // lon parallel to cols (deg*10000) xt1 = vals [ 38 ] / 10000. ; // standard lat 1 xt2 = vals [ 39 ] / 10000. ; // standard lat 2 if ( Double . compare ( xt2 , ( double ) McIDASUtil . MCMISSING ) == 0 || ( xt2 == 0 ) ) { // LOOK suspicious floating point point compare xt2 = xt1 ; } addParam ( LATIN1 , String . valueOf ( xt1 ) ) ; addParam ( LOV , String . valueOf ( xqlon ) ) ; addParam ( LATIN2 , String . valueOf ( xt2 ) ) ; addParam ( DX , String . valueOf ( xspace ) ) ; addParam ( DY , String . valueOf ( xspace ) ) ; /*\n                  xh = (xt1 >= 0) ? 1. : -1.;\n                  xt1 = (90. - xh * xt1) * xrad;\n                  xfac = Math.cos(xt1);\n                  xblat = EARTH_RADIUS * Math.tan(xt1) /\n                             (xspace * Math.pow(Math.tan(xt1*.5), xfac));\n                             */ break ; default : break ; } } catch ( McIDASException me ) { System . out . println ( \"couldn't set nav\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the name for the projection type [CODESPLIT] public String getProjName ( int type ) { String projName ; switch ( type ) { case PSEUDO_MERCATOR : case PSEUDO_MERCATOR_GENERAL : projName = \"MERC\" ; break ; case PS_OR_LAMBERT_CONIC : projName = ( vals [ 38 ] == vals [ 39 ] ) ? \"PS\" : \"CONF\" ; break ; case EQUIDISTANT : projName = \"EQUI\" ; break ; case LAMBERT_CONFORMAL_TANGENT : projName = \"CONF\" ; break ; default : projName = \"NAV\" + type ; } return projName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public void exit () { listen . exit () ; } [CODESPLIT] private void sendMessage ( int port , String message ) { Socket connection = null ; try { connection = new Socket ( \"localhost\" , port ) ; IO . writeContents ( message , connection . getOutputStream ( ) ) ; if ( debug ) System . out . println ( \" sent message \" + message ) ; } catch ( IOException e ) { System . err . println ( e ) ; e . printStackTrace ( ) ; } finally { try { if ( connection != null ) connection . close ( ) ; } catch ( IOException e ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////// [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( false ) { new SocketMessage ( 9999 , \"startNewServer\" ) ; raw = true ; } else { String url = \"http://localhost:8080/thredds/test/it\" // + EscapeStrings.escapeOGC(\"yabba/bad[0]/good\") + \"?\" + EscapeStrings . escapeOGC ( \"quuery[1]\" ) ; System . out . printf ( \"send '%s'%n\" , url ) ; try ( HTTPMethod method = HTTPFactory . Head ( url ) ) { method . execute ( ) ; int status = method . getStatusCode ( ) ; System . out . printf ( \"%d%n\" , status ) ; } // close method, close method internal session } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Erase the last rectangle and shift the rectangle and redraw deltax deltay : position from original position [CODESPLIT] public void move ( int deltax , int deltay ) { lastPt . x = stretchedPt . x ; lastPt . y = stretchedPt . y ; Graphics2D g = ( Graphics2D ) component . getGraphics ( ) ; if ( g != null ) { try { g . setXORMode ( component . getBackground ( ) ) ; if ( firstStretch == true ) firstStretch = false ; else drawLast ( g ) ; anchorPt . x = current . x + deltax ; anchorPt . y = current . y + deltay ; stretchedPt . x = current . x + current . width + deltax ; stretchedPt . y = current . y + current . height + deltay ; drawNext ( g ) ; } finally { g . dispose ( ) ; } // try } // if }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void compare ( Message m1 Message m2 Formatter f ) { Formatter f1 = new Formatter () ; Formatter f2 = new Formatter () ; m1 . dump ( f1 ) ; m1 . dump ( f2 ) ; [CODESPLIT] private void showDDS ( Message m1 ) { Formatter f1 = new Formatter ( ) ; m1 . dump ( f1 ) ; TextHistoryPane ta = new TextHistoryPane ( ) ; IndependentWindow info = new IndependentWindow ( \"Extra Information\" , BAMutil . getImage ( \"netcdfUI\" ) , ta ) ; info . setBounds ( ( Rectangle ) prefs . getBean ( \"InfoWindowBounds\" , new Rectangle ( 300 , 300 , 500 , 300 ) ) ) ; ta . appendLine ( f1 . toString ( ) ) ; ta . gotoTop ( ) ; info . show ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public void save ( ) { messageTable . saveState ( false ) ; ddsTable . saveState ( false ) ; obsTable . saveState ( false ) ; prefs . putBeanObject ( \"InfoWindowBounds\" , infoWindow . getBounds ( ) ) ; prefs . putBeanObject ( \"InfoWindowBounds2\" , infoWindow2 . getBounds ( ) ) ; prefs . putInt ( \"splitPos\" , split . getDividerLocation ( ) ) ; prefs . putInt ( \"splitPos2\" , split2 . getDividerLocation ( ) ) ; if ( fileChooser != null ) fileChooser . save ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the Stations within a bounding box . [CODESPLIT] public List getStations ( ucar . unidata . geoloc . LatLonRect boundingBox ) throws IOException { return typical . getStations ( boundingBox ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a Station by name [CODESPLIT] public ucar . unidata . geoloc . Station getStation ( String name ) { return typical . getStation ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all data for this Station . [CODESPLIT] public DataIterator getDataIterator ( ucar . unidata . geoloc . Station s ) throws IOException { return new StationDataIterator ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get data for this Station within the specified date range . [CODESPLIT] public DataIterator getDataIterator ( ucar . unidata . geoloc . Station s , Date start , Date end ) throws IOException { return new StationDateDataIterator ( s , start , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from this ray . [CODESPLIT] public void readData ( RandomAccessFile raf , String abbrev , Range gateRange , IndexIterator ii ) throws IOException { long offset = rayOffset ; offset += ( getDataOffset ( abbrev ) * 2 - 2 ) ; raf . seek ( offset ) ; byte [ ] b2 = new byte [ 2 ] ; int dataCount = getGateCount ( abbrev ) ; byte [ ] data = new byte [ dataCount * 2 ] ; raf . readFully ( data ) ; for ( int gateIdx : gateRange ) { if ( gateIdx >= dataCount ) ii . setShortNext ( uf_header2 . missing ) ; else { b2 [ 0 ] = data [ gateIdx * 2 ] ; b2 [ 1 ] = data [ gateIdx * 2 + 1 ] ; short value = getShort ( b2 , 0 ) ; ii . setShortNext ( value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of variables contained in this object . For simple and vector type variables it always returns 1 . To count the number of simple - type variable in the variable tree rooted at this variable set <code > leaves< / code > to <code > true< / code > . [CODESPLIT] public int elementCount ( boolean leaves ) { if ( ! leaves ) return vars . size ( ) ; else { int count = 0 ; for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; count += bt . elementCount ( leaves ) ; } return count ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the indexed variable . For a DStructure this returns the <code > BaseType< / code > from the <code > index< / code > th column from the internal storage <code > Vector< / code > . [CODESPLIT] public BaseType getVar ( int index ) throws NoSuchVariableException { if ( index < vars . size ( ) ) return ( ( BaseType ) vars . elementAt ( index ) ) ; else throw new NoSuchVariableException ( \"DStructure.getVariable(\" + index + \" - 1)\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( print_decl_p ) { printDecl ( os , space , false ) ; os . print ( \" = \" ) ; } os . print ( \"{ \" ) ; for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . printVal ( os , \"\" , false ) ; if ( e . hasMoreElements ( ) ) os . print ( \", \" ) ; } os . print ( \" }\" ) ; if ( print_decl_p ) os . println ( \";\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { if ( statusUI != null && statusUI . userCancelled ( ) ) throw new DataReadException ( \"User cancelled\" ) ; ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . deserialize ( source , sv , statusUI ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . externalize ( sink ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Structure< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DStructure s = ( DStructure ) super . cloneDAG ( map ) ; s . vars = new Vector ( ) ; for ( int i = 0 ; i < vars . size ( ) ; i ++ ) { BaseType bt = ( BaseType ) vars . elementAt ( i ) ; BaseType btclone = ( BaseType ) cloneDAG ( map , bt ) ; s . vars . addElement ( btclone ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { for ( int i = 0 ; i < vals . length ; i ++ ) { sink . writeFloat ( vals [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "isLatLon2D is true check parameter to see if its a 2D lat / lon coordinate [CODESPLIT] @ Nullable public static LatLon2DCoord getLatLon2DcoordType ( int discipline , int category , int parameter ) { if ( ( discipline != 0 ) || ( category != 2 ) || ( parameter < 198 || parameter > 203 ) ) return null ; switch ( parameter ) { case 198 : return LatLon2DCoord . U_Latitude ; case 199 : return LatLon2DCoord . U_Longitude ; case 200 : return LatLon2DCoord . V_Latitude ; case 201 : return LatLon2DCoord . V_Longitude ; case 202 : return LatLon2DCoord . P_Latitude ; case 203 : return LatLon2DCoord . P_Longitude ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This looks for snippets in the variable name / desc as to whether it wants U V or P 2D coordinates [CODESPLIT] public static LatLonCoordType getLatLon2DcoordType ( String desc ) { LatLonCoordType type ; if ( desc . contains ( \"u-component\" ) ) type = LatLonCoordType . U ; else if ( desc . contains ( \"v-component\" ) ) type = LatLonCoordType . V ; else if ( desc . contains ( \"Latitude of\" ) || desc . contains ( \"Longitude of\" ) ) type = null ; else type = LatLonCoordType . P ; return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare 2 tables print report . [CODESPLIT] public static void compareTables ( String name1 , String name2 , List < ? extends GribTables . Parameter > test , Grib2Tables reference , Formatter f ) { int extra = 0 ; int udunits = 0 ; int conflict = 0 ; f . format ( \"Table 1 : %s%n\" , name1 ) ; f . format ( \"Table 2 : %s%n\" , name2 ) ; for ( GribTables . Parameter p1 : test ) { GribTables . Parameter p2 = reference . getParameter ( p1 . getDiscipline ( ) , p1 . getCategory ( ) , p1 . getNumber ( ) ) ; if ( p2 == null ) { if ( p1 . getCategory ( ) < 192 && p1 . getNumber ( ) < 192 ) { extra ++ ; f . format ( \"  WMO missing %s%n\" , p1 ) ; } } else { String p1n = Util . cleanName ( p1 . getName ( ) ) ; String p2n = Util . cleanName ( p2 . getName ( ) ) ; if ( ! p1n . equalsIgnoreCase ( p2n ) ) { f . format ( \"  p1=%10s %40s %15s %15s %s%n\" , p1 . getId ( ) , p1 . getName ( ) , p1 . getUnit ( ) , p1 . getAbbrev ( ) , p1 . getDescription ( ) ) ; f . format ( \"  p2=%10s %40s %15s %15s %s%n%n\" , p2 . getId ( ) , p2 . getName ( ) , p2 . getUnit ( ) , p2 . getAbbrev ( ) , p2 . getDescription ( ) ) ; conflict ++ ; } if ( ! p1 . getUnit ( ) . equalsIgnoreCase ( p2 . getUnit ( ) ) ) { String cu1 = Util . cleanUnit ( p1 . getUnit ( ) ) ; String cu2 = Util . cleanUnit ( p2 . getUnit ( ) ) ; // eliminate common non-udunits\r boolean isUnitless1 = Util . isUnitless ( cu1 ) ; boolean isUnitless2 = Util . isUnitless ( cu2 ) ; if ( isUnitless1 != isUnitless2 ) { f . format ( \"  ud=%10s %s != %s for %s (%s)%n%n\" , p1 . getId ( ) , cu1 , cu2 , p1 . getId ( ) , p1 . getName ( ) ) ; udunits ++ ; } else if ( ! isUnitless1 ) { try { SimpleUnit su1 = SimpleUnit . factoryWithExceptions ( cu1 ) ; if ( ! su1 . isCompatible ( cu2 ) ) { f . format ( \"  ud=%10s %s (%s) != %s for %s (%s)%n%n\" , p1 . getId ( ) , cu1 , su1 , cu2 , p1 . getId ( ) , p1 . getName ( ) ) ; udunits ++ ; } } catch ( Exception e ) { f . format ( \"  udunits cant parse=%10s %15s %15s%n\" , p1 . getId ( ) , cu1 , cu2 ) ; } } } } } f . format ( \"Conflicts=%d extra=%d udunits=%d%n%n\" , conflict , extra , udunits ) ; f . format ( \"Parameters in %s not in %s%n\" , name1 , name2 ) ; int local = 0 ; for ( GribTables . Parameter p1 : test ) { GribTables . Parameter p2 = reference . getParameter ( p1 . getDiscipline ( ) , p1 . getCategory ( ) , p1 . getNumber ( ) ) ; if ( p2 == null ) { local ++ ; f . format ( \"  %s%n\" , p1 ) ; } } f . format ( \" missing=%d%n%n\" , local ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cos between two vectors = dot ( v ) / norm () * norm ( v ) [CODESPLIT] public double cos ( MAVector v ) { if ( nelems != v . getNelems ( ) ) throw new IllegalArgumentException ( \"MAVector.cos \" + nelems + \" != \" + v . getNelems ( ) ) ; double norm = norm ( ) ; double normV = v . norm ( ) ; if ( ( norm == 0.0 ) || ( normV == 0.0 ) ) return 0.0 ; else return dot ( v ) / ( norm * normV ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dot product of 2 vectors [CODESPLIT] public double dot ( MAVector v ) { if ( nelems != v . getNelems ( ) ) throw new IllegalArgumentException ( \"MAVector.dot \" + nelems + \" != \" + v . getNelems ( ) ) ; double sum = 0.0 ; for ( int k = 0 ; k < nelems ; k ++ ) sum += getDouble ( k ) * v . getDouble ( k ) ; return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the L2 norm of this vector . [CODESPLIT] public double norm ( ) { double sum = 0.0 ; for ( int k = 0 ; k < nelems ; k ++ ) { double val = getDouble ( k ) ; sum += val * val ; } return Math . sqrt ( sum ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize this vector so it has norm = 1 . 0 . [CODESPLIT] public void normalize ( ) { double norm = norm ( ) ; if ( norm <= 0.0 ) return ; for ( int k = 0 ; k < nelems ; k ++ ) { double val = getDouble ( k ) ; setDouble ( k , val / norm ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////// [CODESPLIT] public Catalog makeCatalog ( ) { setServices ( getDatasets ( ) ) ; Map < String , Object > flds = setFields ( ) ; return new Catalog ( baseURI , name , flds , datasetBuilders ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pull services out of the datasets and into the catalog [CODESPLIT] private void setServices ( Iterable < DatasetBuilder > dsIter ) { for ( DatasetBuilder dsb : dsIter ) { for ( Service s : dsb . getServices ( ) ) { addService ( s ) ; } setServices ( dsb . getDatasets ( ) ) ; // recurse } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void readXML ( String fileName ) throws IOException { try { StAXStreamBuilder staxBuilder = new StAXStreamBuilder () ; XMLInputFactory xmlInputFactory = XMLInputFactory . newInstance () ; XMLStreamReader xmlStreamReader = xmlInputFactory . createXMLStreamReader ( new FileInputStream ( fileName )) ; Document jdomDoc = staxBuilder . build ( xmlStreamReader ) ; readCatalog ( jdomDoc . getRootElement () ) ; [CODESPLIT] private void readXML ( String location ) throws IOException { try { SAXBuilder saxBuilder = new SAXBuilder ( ) ; Document jdomDoc = saxBuilder . build ( location ) ; readCatalog ( jdomDoc . getRootElement ( ) ) ; } catch ( Exception e ) { errlog . format ( \"failed to read catalog at '%s' err='%s'%n\" , location , e ) ; logger . error ( \"failed to read catalog at {}, {}\" , location , e . toString ( ) ) ; if ( logger . isTraceEnabled ( ) ) { e . printStackTrace ( ) ; } fatalError = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = catalog > <xsd : complexType > <xsd : sequence > <xsd : element ref = service minOccurs = 0 maxOccurs = unbounded / > <xsd : element ref = property minOccurs = 0 maxOccurs = unbounded / > <xsd : element ref = dataset minOccurs = 1 maxOccurs = unbounded / > < / xsd : sequence > [CODESPLIT] private void readCatalog ( Element catalogElem ) { String name = catalogElem . getAttributeValue ( \"name\" ) ; String catSpecifiedBaseURL = catalogElem . getAttributeValue ( \"base\" ) ; // LOOK what is this ?? String expiresS = catalogElem . getAttributeValue ( \"expires\" ) ; String version = catalogElem . getAttributeValue ( \"version\" ) ; CalendarDate expires = null ; if ( expiresS != null ) { try { expires = CalendarDateFormatter . isoStringToCalendarDate ( null , expiresS ) ; } catch ( Exception e ) { errlog . format ( \"bad expires date '%s' err='%s'%n\" , expiresS , e . getMessage ( ) ) ; logger . debug ( \"bad expires date '{}' err='{}'%n\" , expiresS , e . getMessage ( ) ) ; } } if ( catSpecifiedBaseURL != null ) { try { URI userSpecifiedBaseUri = new URI ( catSpecifiedBaseURL ) ; this . baseURI = userSpecifiedBaseUri ; } catch ( URISyntaxException e ) { errlog . format ( \"readCatalog(): bad catalog specified base URI='%s' %n\" , catSpecifiedBaseURL ) ; logger . debug ( \"bad catalog specified base URI='{}'\" ) ; } } setName ( name ) ; setExpires ( expires ) ; setVersion ( version ) ; // read top-level services java . util . List < Element > sList = catalogElem . getChildren ( \"service\" , Catalog . defNS ) ; for ( Element e : sList ) { addService ( readService ( e ) ) ; } // read top-level properties java . util . List < Element > pList = catalogElem . getChildren ( \"property\" , Catalog . defNS ) ; for ( Element e : pList ) { addProperty ( readProperty ( e ) ) ; } // look for top-level dataset and catalogRefs elements (keep them in order) java . util . List < Element > allChildren = catalogElem . getChildren ( ) ; for ( Element e : allChildren ) { if ( e . getName ( ) . equals ( \"dataset\" ) ) { addDataset ( readDataset ( null , e ) ) ; } else if ( e . getName ( ) . equals ( \"catalogRef\" ) ) { addDataset ( readCatalogRef ( null , e ) ) ; } else { addDataset ( buildOtherDataset ( null , e ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = access > <xsd : complexType > <xsd : sequence > <xsd : element ref = dataSize minOccurs = 0 / > // whyd we do that ? < / xsd : sequence > <xsd : attribute name = urlPath type = xsd : token use = required / > <xsd : attribute name = serviceName type = xsd : string / > <xsd : attribute name = dataFormat type = dataFormatTypes / > < / xsd : complexType > < / xsd : element > [CODESPLIT] protected AccessBuilder readAccess ( DatasetBuilder dataset , Element accessElem ) { String urlPath = accessElem . getAttributeValue ( \"urlPath\" ) ; String serviceName = accessElem . getAttributeValue ( \"serviceName\" ) ; String dataFormat = accessElem . getAttributeValue ( \"dataFormat\" ) ; Service s = serviceMap . get ( serviceName ) ; if ( s == null ) { errlog . format ( \"Cant find service name='%s'%n\" , serviceName ) ; logger . debug ( \"Can't find service name='{}'\" , serviceName ) ; } return new AccessBuilder ( dataset , urlPath , s , dataFormat , readDataSize ( accessElem ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = service > <xsd : complexType > <xsd : sequence > <xsd : element ref = property minOccurs = 0 maxOccurs = unbounded / > <xsd : element ref = service minOccurs = 0 maxOccurs = unbounded / > < / xsd : sequence > [CODESPLIT] protected Service readService ( Element s ) { String name = s . getAttributeValue ( \"name\" ) ; String typeS = s . getAttributeValue ( \"serviceType\" ) ; String serviceBase = s . getAttributeValue ( \"base\" ) ; String suffix = s . getAttributeValue ( \"suffix\" ) ; String desc = s . getAttributeValue ( \"desc\" ) ; String accessType = s . getAttributeValue ( \"accessType\" ) ; ServiceType type = ServiceType . getServiceTypeIgnoreCase ( typeS ) ; if ( type == null ) { errlog . format ( \" non-standard service type = '%s'%n\" , typeS ) ; logger . debug ( \" non-standard service type = '{}'\" , typeS ) ; } else { if ( desc == null ) { desc = type . getDescription ( ) ; } if ( accessType == null ) { accessType = type . getAccessType ( ) ; } } List < Property > properties = null ; List < Element > propertyList = s . getChildren ( \"property\" , Catalog . defNS ) ; for ( Element e : propertyList ) { if ( properties == null ) { properties = new ArrayList <> ( ) ; } properties . add ( readProperty ( e ) ) ; } // nested services List < Service > services = null ; java . util . List < Element > serviceList = s . getChildren ( \"service\" , Catalog . defNS ) ; for ( Element e : serviceList ) { if ( services == null ) { services = new ArrayList <> ( ) ; } services . add ( readService ( e ) ) ; } Service result = new Service ( name , serviceBase , typeS , desc , suffix , services , properties , accessType ) ; serviceMap . put ( name , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = catalogRef substitutionGroup = dataset > <xsd : complexType > <xsd : complexContent > <xsd : extension base = DatasetType > <xsd : attributeGroup ref = XLink / > <xsd : attribute name = useRemoteCatalogService type = xsd : boolean / > < / xsd : extension > < / xsd : complexContent > < / xsd : complexType > < / xsd : element > [CODESPLIT] protected DatasetBuilder readCatalogRef ( DatasetBuilder parent , Element catRefElem ) { String title = catRefElem . getAttributeValue ( \"title\" , Catalog . xlinkNS ) ; if ( title == null ) { title = catRefElem . getAttributeValue ( \"name\" ) ; } String href = catRefElem . getAttributeValue ( \"href\" , Catalog . xlinkNS ) ; CatalogRefBuilder catRef = new CatalogRefBuilder ( parent ) ; readDatasetInfo ( catRef , catRefElem ) ; catRef . setTitle ( title ) ; catRef . setHref ( href ) ; return catRef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : complexType name = DatasetType > <xsd : sequence > <xsd : group ref = threddsMetadataGroup minOccurs = 0 maxOccurs = unbounded / > [CODESPLIT] protected DatasetBuilder readDataset ( DatasetBuilder parent , Element dsElem ) { DatasetBuilder dataset = new DatasetBuilder ( parent ) ; readDatasetInfo ( dataset , dsElem ) ; // look for access elements java . util . List < Element > aList = dsElem . getChildren ( \"access\" , Catalog . defNS ) ; for ( Element e : aList ) { dataset . addAccess ( readAccess ( dataset , e ) ) ; } // look for nested dataset and catalogRefs elements (keep them in order) java . util . List < Element > allChildren = dsElem . getChildren ( ) ; for ( Element e : allChildren ) { if ( e . getName ( ) . equals ( \"dataset\" ) ) { dataset . addDataset ( readDataset ( dataset , e ) ) ; } else if ( e . getName ( ) . equals ( \"catalogRef\" ) ) { dataset . addDataset ( readCatalogRef ( dataset , e ) ) ; } else { dataset . addDataset ( buildOtherDataset ( dataset , e ) ) ; } } return dataset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <! -- group of elements can be used in a dataset or in metadata elements -- > <xsd : group name = threddsMetadataGroup > <xsd : choice > <xsd : element name = documentation type = documentationType / > <xsd : element ref = metadata / > <xsd : element ref = property / > [CODESPLIT] protected void readThreddsMetadataGroup ( Map < String , Object > flds , DatasetBuilder dataset , Element parent ) { List < Element > list ; // look for creators - kind of a Source list = parent . getChildren ( \"creator\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Creators , readSource ( e ) ) ; } // look for contributors list = parent . getChildren ( \"contributor\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Contributors , readContributor ( e ) ) ; } // look for dates list = parent . getChildren ( \"date\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Dates , readDate ( e , null ) ) ; } // look for documentation list = parent . getChildren ( \"documentation\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Documentation , readDocumentation ( e ) ) ; } // look for keywords - kind of a controlled vocabulary list = parent . getChildren ( \"keyword\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Keywords , readControlledVocabulary ( e ) ) ; } // look for metadata elements list = parent . getChildren ( \"metadata\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . MetadataOther , readMetadata ( flds , dataset , e ) ) ; } // look for projects - kind of a controlled vocabulary list = parent . getChildren ( \"project\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Projects , readControlledVocabulary ( e ) ) ; } // look for properties list = parent . getChildren ( \"property\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Properties , readProperty ( e ) ) ; } // look for publishers - kind of a Source list = parent . getChildren ( \"publisher\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Publishers , readSource ( e ) ) ; } // look for variables list = parent . getChildren ( \"variables\" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . VariableGroups , readVariables ( e ) ) ; } // can only be one each of these kinds ThreddsMetadata . GeospatialCoverage gc = readGeospatialCoverage ( parent . getChild ( \"geospatialCoverage\" , Catalog . defNS ) ) ; if ( gc != null ) { flds . put ( Dataset . GeospatialCoverage , gc ) ; } DateRange tc = readTimeCoverage ( parent . getChild ( \"timeCoverage\" , Catalog . defNS ) ) ; if ( tc != null ) { flds . put ( Dataset . TimeCoverage , tc ) ; } Element serviceNameElem = parent . getChild ( \"serviceName\" , Catalog . defNS ) ; if ( serviceNameElem != null ) { flds . put ( Dataset . ServiceName , serviceNameElem . getText ( ) ) ; } Element authElem = parent . getChild ( \"authority\" , Catalog . defNS ) ; if ( authElem != null ) { flds . put ( Dataset . Authority , authElem . getText ( ) ) ; } Element dataTypeElem = parent . getChild ( \"dataType\" , Catalog . defNS ) ; if ( dataTypeElem != null ) { String dataTypeName = dataTypeElem . getText ( ) ; flds . put ( Dataset . FeatureType , dataTypeName ) ; if ( ( dataTypeName != null ) && ( dataTypeName . length ( ) > 0 ) ) { FeatureType dataType = FeatureType . getType ( dataTypeName . toUpperCase ( ) ) ; if ( dataType == null ) { errlog . format ( \" ** warning: non-standard feature type = '%s'%n\" , dataTypeName ) ; logger . debug ( \" ** warning: non-standard feature type = '{}'\" , dataTypeName ) ; } } } Element dataFormatElem = parent . getChild ( \"dataFormat\" , Catalog . defNS ) ; if ( dataFormatElem != null ) { String dataFormatTypeName = dataFormatElem . getText ( ) ; if ( ( dataFormatTypeName != null ) && ( dataFormatTypeName . length ( ) > 0 ) ) { DataFormatType dataFormatType = DataFormatType . getType ( dataFormatTypeName ) ; if ( dataFormatType == null ) { errlog . format ( \" ** warning: non-standard dataFormat type = '%s'%n\" , dataFormatTypeName ) ; logger . debug ( \" ** warning: non-standard dataFormat type = '{}'\" , dataFormatTypeName ) ; } flds . put ( Dataset . DataFormatType , dataFormatTypeName ) ; } } long size = readDataSize ( parent ) ; if ( size > 0 ) { flds . put ( Dataset . DataSize , size ) ; } // LOOK: we seem to have put a variableMap element not contained by <variables> ThreddsMetadata . UriResolved mapUri = readUri ( parent . getChild ( \"variableMap\" , Catalog . defNS ) , \"variableMap\" ) ; if ( mapUri != null ) { flds . put ( Dataset . VariableMapLinkURI , mapUri ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected Documentation readDocumentation ( Element s ) { String href = s . getAttributeValue ( \"href\" , Catalog . xlinkNS ) ; String title = s . getAttributeValue ( \"title\" , Catalog . xlinkNS ) ; String type = s . getAttributeValue ( \"type\" ) ; // not XLink type String content = s . getTextNormalize ( ) ; URI uri = null ; if ( href != null ) { try { uri = Catalog . resolveUri ( baseURI , href ) ; } catch ( Exception e ) { errlog . format ( \" ** Invalid documentation href = '%s' err='%s'%n\" , href , e . getMessage ( ) ) ; logger . debug ( \" ** Invalid documentation href = '{}' err='{}'\" , href , e . getMessage ( ) ) ; } } return new Documentation ( href , uri , title , type , content ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = metadata > <xsd : complexType > <xsd : choice > <xsd : group ref = threddsMetadataGroup minOccurs = 0 maxOccurs = unbounded / > <xsd : any namespace = ##other minOccurs = 0 maxOccurs = unbounded processContents = lax / > < / xsd : choice > [CODESPLIT] protected ThreddsMetadata . MetadataOther readMetadata ( Map < String , Object > flds , DatasetBuilder dataset , Element mdataElement ) { // there are 6 cases to deal with: threddsNamespace vs not & inline vs Xlink & (if thredds) inherited or not Namespace namespace ; List inlineElements = mdataElement . getChildren ( ) ; if ( inlineElements . size ( ) > 0 ) { // look at the namespace of the children, if they exist namespace = ( ( Element ) inlineElements . get ( 0 ) ) . getNamespace ( ) ; } else { namespace = mdataElement . getNamespace ( ) ; // will be thredds } String mtype = mdataElement . getAttributeValue ( \"metadataType\" ) ; String href = mdataElement . getAttributeValue ( \"href\" , Catalog . xlinkNS ) ; String title = mdataElement . getAttributeValue ( \"title\" , Catalog . xlinkNS ) ; String inheritedS = mdataElement . getAttributeValue ( \"inherited\" ) ; boolean inherited = ( inheritedS != null ) && inheritedS . equalsIgnoreCase ( \"true\" ) ; boolean isThreddsNamespace = ( ( mtype == null ) || mtype . equalsIgnoreCase ( \"THREDDS\" ) ) && namespace . getURI ( ) . equals ( Catalog . CATALOG_NAMESPACE_10 ) ; // the case where its not ThreddsMetadata if ( ! isThreddsNamespace ) { if ( inlineElements . size ( ) > 0 ) { // just hold onto the jdom elements as the \"content\" return new ThreddsMetadata . MetadataOther ( mtype , namespace . getURI ( ) , namespace . getPrefix ( ) , inherited , mdataElement ) ; } else { // otherwise it must be an Xlink return new ThreddsMetadata . MetadataOther ( href , title , mtype , namespace . getURI ( ) , namespace . getPrefix ( ) , inherited ) ; } } // the case where its ThreddsMetadata Map < String , Object > useFlds ; if ( inherited ) { // the case where its inherited ThreddsMetadata: gonna put stuff in the tmi. ThreddsMetadata tmi = ( ThreddsMetadata ) dataset . get ( Dataset . ThreddsMetadataInheritable ) ; if ( tmi == null ) { tmi = new ThreddsMetadata ( ) ; dataset . put ( Dataset . ThreddsMetadataInheritable , tmi ) ; } useFlds = tmi . getFlds ( ) ; } else { // the case where its non-inherited ThreddsMetadata: gonna put stuff directly into the dataset useFlds = flds ; } readThreddsMetadataGroup ( useFlds , dataset , mdataElement ) ; // also need to capture any XLinks. see http://www.unidata.ucar.edu/software/thredds/v4.6/tds/catalog/InvCatalogSpec.html#metadataElement // in this case we just suck it in as if it was inline if ( href != null ) { try { URI xlinkUri = Catalog . resolveUri ( baseURI , href ) ; Element remoteMdata = readMetadataFromUrl ( xlinkUri ) ; return readMetadata ( useFlds , dataset , remoteMdata ) ; } catch ( Exception ioe ) { errlog . format ( \"Cant read in referenced metadata %s err=%s%n\" , href , ioe . getMessage ( ) ) ; logger . debug ( \"Can't read in referenced metadata {} err={}}\" , href , ioe . getMessage ( ) ) ; } } return null ; // ThreddsMetadata.MetadataOther was directly added }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : complexType name = sourceType > <xsd : sequence > <xsd : element name = name type = controlledVocabulary / > [CODESPLIT] protected ThreddsMetadata . Source readSource ( Element elem ) { if ( elem == null ) { return null ; } ThreddsMetadata . Vocab name = readControlledVocabulary ( elem . getChild ( \"name\" , Catalog . defNS ) ) ; Element contact = elem . getChild ( \"contact\" , Catalog . defNS ) ; if ( contact == null ) { errlog . format ( \" ** Parse error: Missing contact element in = '%s'%n\" , elem . getName ( ) ) ; logger . debug ( \" ** Parse error: Missing contact element in = '{}'\" , elem . getName ( ) ) ; return null ; } return new ThreddsMetadata . Source ( name , contact . getAttributeValue ( \"url\" ) , contact . getAttributeValue ( \"email\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : complexType name = timeCoverageType > <xsd : sequence > <xsd : attribute name = calendar type = xsd : string / > <xsd : choice minOccurs = 2 maxOccurs = 3 > <xsd : element name = start type = dateTypeFormatted / > <xsd : element name = end type = dateTypeFormatted / > <xsd : element name = duration type = duration / > < / xsd : choice > <xsd : element name = resolution type = duration minOccurs = 0 / > < / xsd : sequence > < / xsd : complexType > [CODESPLIT] protected DateRange readTimeCoverage ( Element tElem ) { if ( tElem == null ) { return null ; } Calendar calendar = readCalendar ( tElem . getAttributeValue ( \"calendar\" ) ) ; DateType start = readDate ( tElem . getChild ( \"start\" , Catalog . defNS ) , calendar ) ; DateType end = readDate ( tElem . getChild ( \"end\" , Catalog . defNS ) , calendar ) ; TimeDuration duration = readDuration ( tElem . getChild ( \"duration\" , Catalog . defNS ) ) ; TimeDuration resolution = readDuration ( tElem . getChild ( \"resolution\" , Catalog . defNS ) ) ; try { return new DateRange ( start , end , duration , resolution ) ; } catch ( java . lang . IllegalArgumentException e ) { errlog . format ( \" ** warning: TimeCoverage error ='%s'%n\" , e . getMessage ( ) ) ; logger . debug ( \" ** warning: TimeCoverage error ='{}'\" , e . getMessage ( ) ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <xsd : element name = variables > <xsd : complexType > <xsd : choice > <xsd : element ref = variable minOccurs = 0 maxOccurs = unbounded / > <xsd : element ref = variableMap minOccurs = 0 / > < / xsd : choice > <xsd : attribute name = vocabulary type = variableNameVocabulary use = optional / > <xsd : attributeGroup ref = XLink / > < / xsd : complexType > < / xsd : element > [CODESPLIT] protected ThreddsMetadata . VariableGroup readVariables ( Element varsElem ) { if ( varsElem == null ) { return null ; } String vocab = varsElem . getAttributeValue ( \"vocabulary\" ) ; ThreddsMetadata . UriResolved variableVocabUri = readUri ( varsElem , \"Variables vocabulary\" ) ; java . util . List < Element > vlist = varsElem . getChildren ( \"variable\" , Catalog . defNS ) ; ThreddsMetadata . UriResolved variableMap = readUri ( varsElem . getChild ( \"variableMap\" , Catalog . defNS ) , \"Variables Map\" ) ; if ( ( variableMap != null ) && vlist . size ( ) > 0 ) { // cant do both errlog . format ( \" ** Catalog error: cant have variableMap and variable in same element '%s'%n\" , varsElem ) ; } List < ThreddsMetadata . Variable > variables = new ArrayList <> ( ) ; for ( Element e : vlist ) { variables . add ( readVariable ( e ) ) ; } return new ThreddsMetadata . VariableGroup ( vocab , variableVocabUri , variableMap , variables ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A time span as defined in the W3C XML Schema 1 . 0 specification : PnYnMnDTnHnMnS where nY represents the number of years nM the number of months nD the number of days T is the date / time separator nH the number of hours nM the number of minutes and nS the number of seconds . The number of seconds can include decimal digits to arbitrary precision . [CODESPLIT] static public TimeDuration parseW3CDuration ( String text ) throws java . text . ParseException { TimeDuration td = new TimeDuration ( ) ; text = ( text == null ) ? \"\" : text . trim ( ) ; td . text = text ; try { DatatypeFactory factory = DatatypeFactory . newInstance ( ) ; Duration d = factory . newDuration ( text ) ; //long secs = d.getTimeInMillis(new Date()) / 1000; Calendar c = Calendar . getInstance ( ) ; c . set ( 1900 , 0 , 1 , 0 , 0 , 0 ) ; long secs = d . getTimeInMillis ( c . getTime ( ) ) / 1000 ; td . timeUnit = new TimeUnit ( secs + \" secs\" ) ; } catch ( Exception e ) { throw new java . text . ParseException ( e . getMessage ( ) , 0 ) ; } return td ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "test [CODESPLIT] private static void doDuration ( String s ) { try { System . out . println ( \"start = (\" + s + \")\" ) ; TimeDuration d = new TimeDuration ( s ) ; System . out . println ( \"duration = (\" + d . toString ( ) + \")\" ) ; } catch ( java . text . ParseException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public long sendData ( WritableByteChannel wbc StructureData sdata ) throws IOException { long size = 0 ; ByteBuffer bb = IospHelper . copyToByteBuffer ( sdata ) ; byte [] datab = bb . array () ; size + = writeBytes ( wbc NcStream . MAGIC_DATA ) ; // magic size + = NcStream . writeVInt ( wbc datab . length ) ; // data len size + = writeBytes ( wbc datab ) ; // data return size ; } [CODESPLIT] private int writeBytes ( WritableByteChannel wbc , byte [ ] b ) throws IOException { return wbc . write ( ByteBuffer . wrap ( b ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the parameter with id . If not found look in default table . [CODESPLIT] public Grib1Parameter getParameter ( int id ) { if ( parameters == null ) { parameters = readParameterTable ( ) ; } return parameters . get ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the parameter with id but dont look in default table . [CODESPLIT] public Grib1Parameter getLocalParameter ( int id ) { if ( parameters == null ) { parameters = readParameterTable ( ) ; } return parameters . get ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reading [CODESPLIT] private synchronized Map < Integer , Grib1Parameter > readParameterTable ( ) { if ( path == null ) { throw new IllegalStateException ( name ) ; } try { if ( name . startsWith ( \"table_2_\" ) || name . startsWith ( \"local_table_2_\" ) ) { return readParameterTableEcmwf ( ) ; // ecmwf } else if ( name . startsWith ( \"US058\" ) ) { return readParameterTableXml ( new FnmocParser ( ) ) ; // FNMOC } else if ( name . endsWith ( \".tab\" ) ) { return readParameterTableTab ( ) ; // wgrib format } else if ( name . endsWith ( \".wrf\" ) ) { return readParameterTableSplit ( \"\\\\|\" , new int [ ] { 0 , 3 , 1 , 2 } ) ; // WRF AMPS } else if ( name . endsWith ( \".h\" ) ) { return readParameterTableNcl ( ) ; // NCL } else if ( name . endsWith ( \".dss\" ) ) { return readParameterTableSplit ( \"\\t\" , new int [ ] { 0 , - 1 , 1 , 2 } ) ; // NCAR DSS } else if ( name . endsWith ( \".xml\" ) ) { return readParameterTableXml ( new DssParser ( Namespace . NO_NAMESPACE ) ) ; // NCAR DSS XML format } else if ( name . startsWith ( \"2.98\" ) ) { return readParameterTableEcmwfEcCodes ( ) ; // ecmwf from ecCodes package } else { throw new RuntimeException ( \"Grib1ParamTableReader: Dont know how to read \" + name + \" file=\" + path ) ; } } catch ( IOException ioError ) { logger . warn ( \"An error occurred in Grib1ParamTable while trying to open the parameter table {}:{}\" , path , ioError . getMessage ( ) ) ; throw new RuntimeException ( ioError ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * WMO standard table 2 : Version Number 3 . Codes and data units for FM 92 - X Ext . GRIB . ...................... 001 P Pressure Pa Pa ...................... 002 MSL Mean sea level pressure Pa Pa ...................... 003 None Pressure tendency Pa s ** - 1 Pa s ** - 1 ...................... 004 PV Potential vorticity K m ** 2 kg ** - 1 s ** - 1 K m ** 2 kg ** - 1 s ** - 1 ...................... 005 None ICAO Standard Atmosphere reference height m m [CODESPLIT] private Map < Integer , Grib1Parameter > readParameterTableEcmwf ( ) throws IOException { HashMap < Integer , Grib1Parameter > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { String line = br . readLine ( ) ; if ( line == null ) { throw new FileNotFoundException ( path + \" is empty\" ) ; } if ( ! line . startsWith ( \"...\" ) ) { this . desc = line ; // maybe ?? } while ( line != null && ! line . startsWith ( \"...\" ) ) { line = br . readLine ( ) ; // skip } while ( true ) { line = br . readLine ( ) ; if ( line == null ) { break ; // done with the file } if ( ( line . length ( ) == 0 ) || line . startsWith ( \"#\" ) ) { continue ; } if ( line . startsWith ( \"...\" ) ) { // ...  may have already been read line = br . readLine ( ) ; if ( line == null ) { break ; } } String num = line . trim ( ) ; line = br . readLine ( ) ; String name = ( line != null ) ? line . trim ( ) : null ; line = br . readLine ( ) ; String desc = ( line != null ) ? line . trim ( ) : null ; line = br . readLine ( ) ; String units1 = ( line != null ) ? line . trim ( ) : null ; // optional notes line = br . readLine ( ) ; String notes = ( line == null || line . startsWith ( \"...\" ) ) ? null : line . trim ( ) ; if ( desc != null && desc . equalsIgnoreCase ( \"undefined\" ) ) { continue ; // skip } int p1 ; try { p1 = Integer . parseInt ( num ) ; } catch ( Exception e ) { logger . warn ( \"Cant parse \" + num + \" in file \" + path ) ; continue ; } Grib1Parameter parameter = new Grib1Parameter ( this , p1 , name , desc , units1 ) ; result . put ( parameter . getNumber ( ) , parameter ) ; logger . debug ( \" %s (%s)%n\" , parameter , notes ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will read in ECMWF grib1 tables . Note that these tables are generated locally by Unidata and come directly from the ECMWF GRIB - API package localConcepts files . They are generated by : <p > ucar . nc2 . grib . grib1 . tables . EcmwfLocalConcepts <p > The original localConcepts files are located in : <p / > grib / src / main / sources / ecmwfEcCodes / <p / > Since we write the table file that are ultimately read by CDM the format is controled and is the following : <p > paramNum shortName [ description ] ( units ) <p > for example <p > 251 atte [ Adiabatic tendency of temperature ] ( K ) [CODESPLIT] private Map < Integer , Grib1Parameter > readParameterTableEcmwfEcCodes ( ) throws IOException { HashMap < Integer , Grib1Parameter > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { String line = br . readLine ( ) ; if ( line == null ) { throw new FileNotFoundException ( path + \" is empty\" ) ; } // create table name from file name String [ ] splitPath = path . split ( \"/\" ) ; String tableNum = splitPath [ splitPath . length - 1 ] . replace ( \".table\" , \"\" ) ; this . desc = \"ECMWF GRIB API TABLE \" + tableNum ; // skip header while ( line != null && ! line . startsWith ( \"#\" ) ) { line = br . readLine ( ) ; // skip } // keep going until the end of the file is reached (line == null) while ( true ) { // exmaple: 251 atte [Adiabatic tendency of temperature] (K) line = br . readLine ( ) ; if ( line == null ) { break ; // done with the file } if ( ( line . length ( ) == 0 ) || line . startsWith ( \"#\" ) ) { continue ; } // get unit - (K) String [ ] tmpUnitArray = line . split ( \"\\\\(\" ) ; String tmpUnit = tmpUnitArray [ tmpUnitArray . length - 1 ] ; int lastUnitIndex ; while ( ( lastUnitIndex = tmpUnit . lastIndexOf ( \")\" ) ) > 0 ) { tmpUnit = tmpUnit . substring ( 0 , lastUnitIndex ) . trim ( ) ; } String unit = tmpUnit . trim ( ) ; // unit = Util.cleanUnit(unit); // fixes some common unit mistakes  // jcaron - just use unit as it is // get parameter number - 251 String [ ] lineArray = line . trim ( ) . split ( \"\\\\s+\" ) ; // all and any white space String num = lineArray [ 0 ] ; // get shortName - atte String name = lineArray [ 1 ] . trim ( ) ; //if (name.equals(\"~\")) {}; - todo create name from long name(?) // get description. bracketed by [] - [Adiabatic Tendency of temperature] int startDesc = line . indexOf ( \"[\" ) ; int endDesc = line . indexOf ( \"]\" ) ; String desc = line . substring ( startDesc , endDesc ) . trim ( ) ; // stuff information into a Grib1Parameter object int p1 ; try { p1 = Integer . parseInt ( num ) ; } catch ( Exception e ) { logger . warn ( \"Cant parse \" + num + \" in file \" + path ) ; continue ; } Grib1Parameter parameter = new Grib1Parameter ( this , p1 , name , desc , unit ) ; result . put ( parameter . getNumber ( ) , parameter ) ; logger . debug ( \" %s%n\" , parameter ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "order : num name desc unit [CODESPLIT] private Map < Integer , Grib1Parameter > readParameterTableSplit ( String regexp , int [ ] order ) throws IOException { HashMap < Integer , Grib1Parameter > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { // rdg - added the 0 line length check to cover the case of blank lines at the end of the parameter table file. while ( true ) { String line = br . readLine ( ) ; if ( line == null ) { break ; } if ( ( line . length ( ) == 0 ) || line . startsWith ( \"#\" ) ) { continue ; } String [ ] flds = line . split ( regexp ) ; int p1 = Integer . parseInt ( flds [ order [ 0 ] ] . trim ( ) ) ; // must have a number String name = ( order [ 1 ] >= 0 ) ? flds [ order [ 1 ] ] . trim ( ) : null ; String desc = flds [ order [ 2 ] ] . trim ( ) ; String units = ( flds . length > order [ 3 ] ) ? flds [ order [ 3 ] ] . trim ( ) : \"\" ; Grib1Parameter parameter = new Grib1Parameter ( this , p1 , name , desc , units ) ; result . put ( parameter . getNumber ( ) , parameter ) ; logger . debug ( \" %s%n\" , parameter ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a prefix to the database by name . [CODESPLIT] public void addName ( final String name , final double value ) throws PrefixExistsException { final Prefix prefix = new PrefixName ( name , value ) ; nameSet . add ( prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a prefix symbol to the database . [CODESPLIT] public void addSymbol ( final String symbol , final double value ) throws PrefixExistsException { final Prefix prefix = new PrefixSymbol ( symbol , value ) ; symbolSet . add ( prefix ) ; valueMap . put ( new Double ( value ) , prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the prefix from the given set with the given identifier . [CODESPLIT] private static Prefix getPrefix ( final String string , final Set < Prefix > set ) { for ( final Iterator < Prefix > iter = set . iterator ( ) ; iter . hasNext ( ) ; ) { final Prefix prefix = iter . next ( ) ; final int comp = prefix . compareTo ( string ) ; if ( comp == 0 ) { return prefix ; } if ( comp > 0 ) { break ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check its an acceptable form of email [CODESPLIT] protected boolean emailOK ( ThreddsMetadata . Source p ) { String email = p . getEmail ( ) ; return email . indexOf ( ' ' ) >= 0 ; // should really do a regexp }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "test [CODESPLIT] private static void doOne ( InvCatalogFactory fac , String url ) { System . out . println ( \"***read \" + url ) ; try { InvCatalogImpl cat = fac . readXML ( url ) ; StringBuilder buff = new StringBuilder ( ) ; boolean isValid = cat . check ( buff , false ) ; System . out . println ( \"catalog <\" + cat . getName ( ) + \"> \" + ( isValid ? \"is\" : \"is not\" ) + \" valid\" ) ; System . out . println ( \" validation output=\\n\" + buff ) ; // System.out.println(\" catalog=\\n\" + fac.writeXML(cat)); ADNWriter w = new ADNWriter ( ) ; StringBuilder sbuff = new StringBuilder ( ) ; w . writeDatasetEntries ( cat , \"C:/temp/adn3\" , sbuff ) ; System . out . println ( \" messages=\\n\" + sbuff ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peek ahead [CODESPLIT] private char peek ( ) throws ParseException { try { reader . mark ( 10 ) ; int aChar = reader . read ( ) ; reader . reset ( ) ; if ( aChar < 0 ) { return ( char ) 0 ; } else { return ( char ) aChar ; } } catch ( java . io . IOException e1 ) { throw new ParseException ( \"Strange io error \" + e1 , position ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private char getChar ( ) throws ParseException { try { int val = reader . read ( ) ; position ++ ; if ( val < 0 ) { throw new ParseException ( \"unexpected eof of srtext\" , position ) ; } return ( char ) val ; } catch ( java . io . IOException e1 ) { throw new ParseException ( e1 . toString ( ) , position ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private void eatLiteral ( String literal ) throws ParseException { int n = literal . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char v = getChar ( ) ; if ( v != literal . charAt ( i ) ) { throw new ParseException ( \"bad srtext\" , position ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private double eatReal ( ) throws ParseException { StringBuilder b = new StringBuilder ( ) ; for ( ; ; ) { char t = peek ( ) ; if ( Character . isDigit ( t ) || ( t == ' ' ) || ( t == ' ' ) || ( t == ' ' ) || ( t == ' ' ) || ( t == ' ' ) ) { b . append ( getChar ( ) ) ; } else { break ; } } try { return Double . parseDouble ( b . toString ( ) ) ; } catch ( NumberFormatException e1 ) { throw new ParseException ( \"bad number\" + e1 , position ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private String eatString ( ) throws ParseException { StringBuilder b = new StringBuilder ( ) ; if ( getChar ( ) != ' ' ) { throw new ParseException ( \"expected string\" , position ) ; } for ( ; ; ) { char t = getChar ( ) ; if ( t == ' ' ) { break ; } b . append ( t ) ; } return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private String eatTerm ( ) throws ParseException { StringBuilder b = new StringBuilder ( ) ; for ( ; ; ) { char val = peek ( ) ; if ( ! Character . isJavaIdentifierPart ( val ) ) { break ; } b . append ( getChar ( ) ) ; } return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private void parseProjcs ( ) throws ParseException { eatLiteral ( \"PROJCS[\" ) ; projName = eatString ( ) ; eatComma ( ) ; parseGeogcs ( ) ; for ( ; ; ) { char next = getChar ( ) ; if ( next == ' ' ) { break ; } else if ( next != ' ' ) { throw new ParseException ( \"expected , or ]\" , position ) ; } else { String term = eatTerm ( ) ; if ( \"PARAMETER\" . equals ( term ) ) { eatParameter ( ) ; } else if ( \"UNIT\" . equals ( term ) ) { eatProjcsUnit ( ) ; } else if ( \"PROJECTION\" . equals ( term ) ) { eatProjectionType ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private void eatParameter ( ) throws ParseException { eatOpenBrace ( ) ; String parameterName = eatString ( ) ; eatComma ( ) ; Double value = eatReal ( ) ; eatCloseBrace ( ) ; parameters . put ( parameterName . toLowerCase ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private void parseGeogcs ( ) throws ParseException { eatLiteral ( \"GEOGCS[\" ) ; geogcsName = eatString ( ) ; for ( ; ; ) { char t = getChar ( ) ; if ( t == ' ' ) { break ; } else if ( t != ' ' ) { throw new ParseException ( \"expected , or ]\" , position ) ; } else { String term = eatTerm ( ) ; if ( \"DATUM\" . equals ( term ) ) { eatDatum ( ) ; } else if ( \"PRIMEM\" . equals ( term ) ) { eatPrimem ( ) ; } else if ( \"UNIT\" . equals ( term ) ) { eatUnit ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "_more_ [CODESPLIT] private void eatSpheroid ( ) throws ParseException { eatLiteral ( \"SPHEROID\" ) ; eatOpenBrace ( ) ; spheroidName = eatString ( ) ; eatComma ( ) ; majorAxis = eatReal ( ) ; eatComma ( ) ; inverseMinor = eatReal ( ) ; eatCloseBrace ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of the projection parameter . An IllegalArgument exception is thrown if the parameter is not found . [CODESPLIT] public double getParameter ( String name ) { Double val = ( Double ) parameters . get ( name . toLowerCase ( ) ) ; if ( val == null ) { throw new IllegalArgumentException ( \"no parameter called \" + name ) ; } return val . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert OGC spatial reference WKT to a ProjectionImpl . An IllegalArgumentException may be thrown if a parameter is missing . [CODESPLIT] public static ProjectionImpl convertWKTToProjection ( WKTParser srp ) { if ( ! srp . isPlanarProjection ( ) ) { return new ucar . unidata . geoloc . projection . LatLonProjection ( ) ; } else { String projectionType = srp . getProjectionType ( ) ; double falseEasting = 0 ; double falseNorthing = 0 ; ProjectionImpl proj = null ; if ( srp . hasParameter ( \"False_Easting\" ) ) { falseEasting = srp . getParameter ( \"False_Easting\" ) ; } if ( srp . hasParameter ( \"False_Northing\" ) ) { falseNorthing = srp . getParameter ( \"False_Northing\" ) ; } if ( ( falseEasting != 0.0 ) || ( falseNorthing != 0.0 ) ) { double scalef = 1.0 ; if ( srp . getProjUnitName ( ) != null ) { try { SimpleUnit unit = SimpleUnit . factoryWithExceptions ( srp . getProjUnitName ( ) ) ; scalef = unit . convertTo ( srp . getProjUnitValue ( ) , SimpleUnit . kmUnit ) ; } catch ( Exception e ) { System . out . println ( srp . getProjUnitValue ( ) + \" \" + srp . getProjUnitName ( ) + \" not convertible to km\" ) ; } } falseEasting *= scalef ; falseNorthing *= scalef ; } if ( srp . getProjName ( ) . contains ( \"UTM_Zone_\" ) ) return processUTM ( srp ) ; if ( \"Transverse_Mercator\" . equals ( projectionType ) ) { double lat0 = srp . getParameter ( \"Latitude_Of_Origin\" ) ; double scale = srp . getParameter ( \"Scale_Factor\" ) ; double tangentLon = srp . getParameter ( \"Central_Meridian\" ) ; proj = new TransverseMercator ( lat0 , tangentLon , scale , falseEasting , falseNorthing ) ; } else if ( \"Lambert_Conformal_Conic\" . equals ( projectionType ) ) { double lon0 = srp . getParameter ( \"Central_Meridian\" ) ; double par1 = srp . getParameter ( \"Standard_Parallel_1\" ) ; double par2 = par1 ; if ( srp . hasParameter ( \"Standard_Parallel_2\" ) ) { par2 = srp . getParameter ( \"Standard_Parallel_2\" ) ; } double lat0 = srp . getParameter ( \"Latitude_Of_Origin\" ) ; return new LambertConformal ( lat0 , lon0 , par1 , par2 , falseEasting , falseNorthing ) ; } else if ( \"Albers\" . equals ( projectionType ) ) { double lon0 = srp . getParameter ( \"Central_Meridian\" ) ; double par1 = srp . getParameter ( \"Standard_Parallel_1\" ) ; double par2 = par1 ; if ( srp . hasParameter ( \"Standard_Parallel_2\" ) ) { par2 = srp . getParameter ( \"Standard_Parallel_2\" ) ; } double lat0 = srp . getParameter ( \"Latitude_Of_Origin\" ) ; return new AlbersEqualArea ( lat0 , lon0 , par1 , par2 , falseEasting , falseNorthing ) ; } else if ( \"Stereographic\" . equals ( projectionType ) ) { double lont = srp . getParameter ( \"Central_Meridian\" ) ; double scale = srp . getParameter ( \"Scale_Factor\" ) ; double latt = srp . getParameter ( \"Latitude_Of_Origin\" ) ; return new Stereographic ( latt , lont , scale , falseEasting , falseNorthing ) ; } else if ( \"Mercator\" . equals ( projectionType ) ) { double lat0 = srp . getParameter ( \"Latitude_Of_Origin\" ) ; double lon0 = srp . getParameter ( \"Central_Meridian\" ) ; proj = new Mercator ( lon0 , lat0 , falseEasting , falseNorthing ) ; } else if ( \"Universal_Transverse_Mercator\" . equals ( projectionType ) ) { //throw new java.text.ParseException(\r //    \"UTM adapter not implemented yet\", 0);\r } return proj ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the CRC of the entire byte array [CODESPLIT] public long calcCRC ( ) { long crc ; if ( rawData == null ) crc = predefinedGridDefinitionCenter << 16 + predefinedGridDefinition ; else { CRC32 crc32 = new CRC32 ( ) ; crc32 . update ( rawData ) ; crc = crc32 . getValue ( ) ; } return crc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is a thin grid [CODESPLIT] public final boolean isThin ( ) { if ( rawData == null ) return false ; int octet5 = getOctet ( 5 ) ; int nv = getOctet ( 4 ) ; return ( octet5 != 255 ) && ( nv == 0 || nv == 255 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the number of points in each line for Quasi / Thin grids List of numbers of points in each row ( length = NROWS x 2 octets where NROWS is the total number of rows defined within the grid description ) [CODESPLIT] private int [ ] getNptsInLine ( Grib1Gds gds ) { int numPts ; if ( ( gds . getScanMode ( ) & 32 ) == 0 ) { // bit3 = 0 : Adjacent points in i direction are consecutive\r numPts = gds . getNy ( ) ; } else { // bit3 = 1 : Adjacent points in j direction are consecutive\r numPts = gds . getNx ( ) ; } int [ ] parallels = new int [ numPts ] ; int offset = getOctet ( 5 ) ; for ( int i = 0 ; i < numPts ; i ++ ) { parallels [ i ] = GribNumbers . int2 ( getOctet ( offset ++ ) , getOctet ( offset ++ ) ) ; } return parallels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////// [CODESPLIT] public boolean hasVerticalCoordinateParameters ( ) { if ( rawData == null ) return false ; int octet5 = getOctet ( 5 ) ; int nv = getOctet ( 4 ) ; return ( octet5 != 255 ) && ( nv != 0 && nv != 255 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selected DataCursor API overrides [CODESPLIT] @ Override public int fieldIndex ( String name ) throws DapException { DapStructure ds ; if ( getTemplate ( ) . getSort ( ) . isCompound ( ) ) ds = ( DapStructure ) getTemplate ( ) ; else if ( getTemplate ( ) . getSort ( ) . isVar ( ) && ( ( ( DapVariable ) getTemplate ( ) ) . getBaseType ( ) . getSort ( ) . isCompound ( ) ) ) ds = ( DapStructure ) ( ( DapVariable ) getTemplate ( ) ) . getBaseType ( ) ; else throw new DapException ( \"Attempt to get field name on non-compound object\" ) ; int i = ds . indexByName ( name ) ; if ( i < 0 ) throw new DapException ( \"Unknown field name: \" + name ) ; return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] static public Scheme schemeFor ( DapVariable field ) { DapType ftype = field . getBaseType ( ) ; Scheme scheme = null ; boolean isscalar = field . getRank ( ) == 0 ; if ( ftype . getTypeSort ( ) . isAtomic ( ) ) scheme = Scheme . ATOMIC ; else { if ( ftype . getTypeSort ( ) . isStructType ( ) ) scheme = Scheme . STRUCTARRAY ; else if ( ftype . getTypeSort ( ) . isSeqType ( ) ) scheme = Scheme . SEQARRAY ; } return scheme ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code true } if we should add 2D latitude & longitude variables to the output file . This method could return { @code false } for several reasons : [CODESPLIT] private boolean shouldAddLatLon2D ( boolean tryToAddLatLon2D , CoverageCollection subsetDataset ) { if ( ! tryToAddLatLon2D ) { // We don't even want 2D lat/lon vars. return false ; } HorizCoordSys horizCoordSys = subsetDataset . getHorizCoordSys ( ) ; if ( horizCoordSys . isLatLon2D ( ) ) { // We already have 2D lat/lon vars. return false ; } if ( ! horizCoordSys . isProjection ( ) ) { // CRS doesn't contain a projection, meaning we can't calc 2D lat/lon vars. return false ; } Projection proj = horizCoordSys . getTransform ( ) . getProjection ( ) ; if ( proj instanceof LatLonProjection ) { // Projection is a \"fake\"; we already have lat/lon. return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "code table 5 - 2010 edition of WMO manual on codes [CODESPLIT] public static String getTimeTypeName ( int timeRangeIndicator ) { String timeRange ; switch ( timeRangeIndicator ) { /* Forecast product valid for reference time + P1 (P1 > 0), or\r\n        Uninitialized analysis product for reference time (P1 = 0), or\r\n        Image product for reference time (P1 = 0) */ case 0 : timeRange = \"Uninitialized analysis / image product / forecast product valid for RT + P1\" ; break ; // Initialized analysis product for reference time (P1 = 0)\r case 1 : timeRange = \"Initialized analysis product for reference time\" ; break ; // Product with a valid time ranging between reference time + P1 and reference time + P2\r case 2 : timeRange = \"product valid, interval = (RT + P1) to (RT + P2)\" ; break ; // Average (reference time + P1 to reference time + P2)\r case 3 : timeRange = \"Average, interval = (RT + P1) to (RT + P2)\" ; break ; /* Accumulation  (reference  time  +  P1  to  reference  time  +  P2)  product  considered  valid  at\r\n        reference time + P2 */ case 4 : timeRange = \"Accumulation, interval = (RT + P1) to (RT + P2)\" ; break ; /* Difference  (reference  time  +  P2  minus  reference  time  +  P1)  product  considered  valid  at\r\n        reference time + P2 */ case 5 : timeRange = \"Difference, interval = (RT + P2) - (RT + P1)\" ; break ; // Average (reference time - P1 to reference time - P2)\r case 6 : timeRange = \"Average, interval = (RT - P1) to (RT - P2)\" ; break ; // Average (reference time - P1 to reference time + P2)\r case 7 : timeRange = \"Average, interval = (RT - P1) to (RT + P2)\" ; break ; // P1 occupies octets 19 and 20; product valid at reference time + P1\r case 10 : timeRange = \"product valid at RT + P1\" ; break ; /* Climatological  mean  value:  multiple  year  averages  of  quantities  which  are  themselves\r\n        means over some period of time (P2) less than a year. The reference time (R) indicates the\r\n        date and time of the start of a period of time, given by R to R + P2, over which a mean is\r\n        formed; N indicates the number of such period-means that are averaged together to form\r\n        the  climatological  value,  assuming  that  the  N  period-mean  fields  are  separated  by  one\r\n        year. The reference time indicates the start of the N-year climatology.\r\n\r\n        If P1 = 0 then the data averaged in the basic interval P2 are assumed to be continuous, i.e. all available data\r\n        are simply averaged together.\r\n\r\n        If P1 = 1 (the unit of time  octet 18, Code table 4  is not\r\n        relevant here) then the data averaged together in the basic interval P2 are valid only at the\r\n        time (hour, minute) given in the reference time, for all the days included in the P2 period.\r\n        The units of P2 are given by the contents of octet 18 and Code table 4 */ case 51 : timeRange = \"Climatological mean values from RT to (RT + P2)\" ; // if (p1 == 0) timeRange += \" continuous\";\r break ; /* Average  of  N  forecasts  (or  initialized  analyses);  each  product  has  forecast  period  of  P1\r\n        (P1 = 0 for initialized analyses); products have reference times at intervals of P2, beginning\r\n        at the given reference time */ case 113 : timeRange = \"Average of N forecasts, intervals = (refTime + i * P2, refTime + i * P2 + P1)\" ; break ; /* Accumulation of N forecasts (or initialized analyses); each product has forecast period of\r\n        P1  (P1  =  0  for  initialized  analyses);  products  have  reference  times  at  intervals  of  P2,\r\n        beginning at the given reference time */ case 114 : timeRange = \"Accumulation of N forecasts, intervals = (refTime + i * P2, refTime + i * P2 + P1)\" ; break ; /* Average of N forecasts, all with the same reference time; the first has a forecast period of\r\n         P1, the remaining forecasts follow at intervals of P2 */ case 115 : timeRange = \"Average of N forecasts, intervals = (refTime, refTime + P1 + i * P2)\" ; break ; /* Accumulation  of  N  forecasts,  all  with  the  same  reference  time;  the  first  has  a  forecast\r\n        period of P1, the remaining forecasts follow at intervals of P2 */ case 116 : timeRange = \"Accumulation of N forecasts, intervals = (refTime, refTime + P1 + i * P2)\" ; break ; /* Average of N forecasts; the first has a forecast period of P1, the subsequent ones have\r\n        forecast periods reduced from the previous one by an interval of P2; the reference time for\r\n        the first is given in octets 13 to 17, the subsequent ones have reference times increased\r\n        from the previous one by an interval of P2. Thus all the forecasts have the same valid time,\r\n        given by the initial reference time + P1 */ case 117 : timeRange = \"Average of N forecasts, intervals = (refTime + i * P2, refTime + P1)\" ; break ; /* Temporal  variance,  or  covariance,  of  N  initialized  analyses;  each  product  has  forecast\r\n        period of P1 = 0; products have reference times at intervals of P2, beginning at the given\r\n        reference time */ case 118 : timeRange = \"Temporal variance or covariance of N initialized analyses, timeCoord = (refTime + i * P2)\" ; break ; /* Standard deviation of N forecasts, all with the same reference time with respect to the time\r\n        average of forecasts; the first forecast has a forecast period of P1, the remaining forecasts\r\n        follow at intervals of P2 */ case 119 : timeRange = \"Standard Deviation of N forecasts, timeCoord = (refTime + P1 + i * P2)\" ; break ; // ECMWF \"Average of N Forecast\" added 11/21/2014. pretend its WMO standard. maybe should move to ecmwf ??\r // see \"http://emoslib.sourcearchive.com/documentation/000370.dfsg.2/grchk1_8F-source.html\"\r // C     Add Time range indicator = 120 Average of N Forecast. Each product\r // C             is an accumulation from forecast lenght P1 to forecast\r // C              lenght P2, with reference times at intervals P2-P1\r case 120 : timeRange = \"Average of N Forecasts (ECMWF), accumulation from forecast P1 to P2, with reference times at intervals P2-P1\" ; break ; // Average of N uninitialized analyses, starting at the reference time, at intervals of P2\r case 123 : timeRange = \"Average of N uninitialized analyses, intervals = (refTime, refTime + i * P2)\" ; break ; // Accumulation of N uninitialized analyses, starting at the reference time, at intervals of P2\r case 124 : timeRange = \"Accumulation of N uninitialized analyses, intervals = (refTime, refTime + i * P2)\" ; break ; /* Standard deviation of N forecasts, all with the same reference time with respect to time\r\n        average of the time tendency of forecasts; the first forecast has a forecast period of P1,\r\n        the remaining forecasts follow at intervals of P2 */ case 125 : timeRange = \"Standard deviation of N forecasts, intervals = (refTime, refTime + P1 + i * P2)\" ; break ; default : timeRange = \"Unknown Time Range Indicator \" + timeRangeIndicator ; } return timeRange ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A string representation of the time coordinate whether its an interval or not . [CODESPLIT] public String getTimeCoord ( ) { if ( isInterval ( ) ) { int [ ] intv = getInterval ( ) ; return intv [ 0 ] + \"-\" + intv [ 1 ] ; } return Integer . toString ( getForecastTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append an error message to the message log . Call check () to get the log when everything is done . [CODESPLIT] public void appendErrorMessage ( String message , boolean fatal ) { errLog . append ( message ) ; errLog . append ( \"\\n\" ) ; fatalError = fatalError || fatal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utilities [CODESPLIT] protected String [ ] getparamset ( String key ) throws IOException { String [ ] values = this . params . get ( key ) ; return ( values == null ? new String [ 0 ] : values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the offsets based on m . getSizeBytes () . Also sets members . setStructureSize () . [CODESPLIT] public static int setOffsets ( StructureMembers members ) { int offset = 0 ; for ( StructureMembers . Member m : members . getMembers ( ) ) { m . setDataParam ( offset ) ; offset += m . getSizeBytes ( ) ; // set inner offsets (starts again at 0)\r if ( m . getStructureMembers ( ) != null ) setOffsets ( m . getStructureMembers ( ) ) ; } members . setStructureSize ( offset ) ; return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the next polygon which make up the multipolygon which this polygon is a part of . If next is a CFPolygon automatically connects the other polygon to this polygon as well . [CODESPLIT] public void setNext ( Polygon next ) { if ( next instanceof CFPolygon ) { setNext ( ( CFPolygon ) next ) ; } else this . next = next ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the previous polygon which makes up the multipolygon which this polygon is a part of . If prev is a CFPolygon automatically connect the other polygon to this polygon as well . [CODESPLIT] public void setPrev ( Polygon prev ) { if ( prev instanceof CFPolygon ) { setPrev ( ( CFPolygon ) prev ) ; } else this . prev = prev ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a dataset variable and index automatically sets up a previously constructed polygon . If the specified polygon is not found in the dataset returns null [CODESPLIT] public Polygon setupPolygon ( NetcdfDataset dataset , Variable polyvar , int index ) { this . points . clear ( ) ; Array xPts = null ; Array yPts = null ; Variable nodeCounts = null ; Variable partNodeCounts = null ; Variable interiorRings = null ; List < CoordinateAxis > axes = dataset . getCoordinateAxes ( ) ; CoordinateAxis x = null ; CoordinateAxis y = null ; String [ ] nodeCoords = polyvar . findAttributeIgnoreCase ( CF . NODE_COORDINATES ) . getStringValue ( ) . split ( \" \" ) ; // Look for x and y\r for ( CoordinateAxis ax : axes ) { if ( ax . getFullName ( ) . equals ( nodeCoords [ 0 ] ) ) x = ax ; if ( ax . getFullName ( ) . equals ( nodeCoords [ 1 ] ) ) y = ax ; } // Affirm node counts\r String nodeCoStr = polyvar . findAttValueIgnoreCase ( CF . NODE_COUNT , \"\" ) ; if ( ! nodeCoStr . equals ( \"\" ) ) { nodeCounts = dataset . findVariable ( nodeCoStr ) ; } else return null ; // Affirm part node counts\r String pNodeCoStr = polyvar . findAttValueIgnoreCase ( CF . PART_NODE_COUNT , \"\" ) ; if ( ! pNodeCoStr . equals ( \"\" ) ) { partNodeCounts = dataset . findVariable ( pNodeCoStr ) ; } // Affirm interior rings\r String interiorRingsStr = polyvar . findAttValueIgnoreCase ( CF . PART_NODE_COUNT , \"\" ) ; if ( ! interiorRingsStr . equals ( \"\" ) ) { interiorRings = dataset . findVariable ( interiorRingsStr ) ; } SimpleGeometryIndexFinder indexFinder = new SimpleGeometryIndexFinder ( nodeCounts ) ; //Get beginning and ending indicies for this polygon\r int lower = indexFinder . getBeginning ( index ) ; int upper = indexFinder . getEnd ( index ) ; try { xPts = x . read ( lower + \":\" + upper ) . reduce ( ) ; yPts = y . read ( lower + \":\" + upper ) . reduce ( ) ; IndexIterator itrX = xPts . getIndexIterator ( ) ; IndexIterator itrY = yPts . getIndexIterator ( ) ; // No multipolygons just read in the whole thing\r if ( partNodeCounts == null ) { this . next = null ; this . prev = null ; this . isInteriorRing = false ; // x and y should have the same shape, will add some handling on this\r while ( itrX . hasNext ( ) ) { this . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; } switch ( polyvar . getRank ( ) ) { case 2 : this . setData ( polyvar . read ( CFSimpleGeometryHelper . getSubsetString ( polyvar , index ) ) . reduce ( ) ) ; break ; case 1 : this . setData ( polyvar . read ( \"\" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations\r } } // If there are multipolygons then take the upper and lower of it and divy it up\r else { Polygon tail = this ; Array pnc = partNodeCounts . read ( ) ; Array ir = null ; IndexIterator pncItr = pnc . getIndexIterator ( ) ; if ( interiorRings != null ) ir = interiorRings . read ( ) ; // In part node count search for the right index to begin looking for \"part node counts\"\r int pncInd = 0 ; int pncEnd = 0 ; while ( pncEnd < lower ) { pncEnd += pncItr . getIntNext ( ) ; pncInd ++ ; } // Now the index is found, use part node count and the index to find each part node count of each individual part\r while ( lower < upper ) { int smaller = pnc . getInt ( pncInd ) ; // Set interior ring if needed\r if ( interiorRings != null ) { int interiorRingValue = ir . getInt ( pncInd ) ; switch ( interiorRingValue ) { case 0 : this . setInteriorRing ( false ) ; break ; case 1 : this . setInteriorRing ( true ) ; break ; // will handle default case\r } } else this . isInteriorRing = false ; while ( smaller > 0 ) { tail . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; smaller -- ; } // Set data of each\r switch ( polyvar . getRank ( ) ) { case 2 : tail . setData ( polyvar . read ( CFSimpleGeometryHelper . getSubsetString ( polyvar , index ) ) . reduce ( ) ) ; break ; case 1 : tail . setData ( polyvar . read ( \"\" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations\r } lower += tail . getPoints ( ) . size ( ) ; pncInd ++ ; tail . setNext ( new CFPolygon ( ) ) ; tail = tail . getNext ( ) ; } //Clean up\r tail = tail . getPrev ( ) ; if ( tail != null ) tail . setNext ( null ) ; } } catch ( IOException | InvalidRangeException | InvalidDataseriesException e ) { cfpl . error ( e . getMessage ( ) ) ; return null ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get named property . [CODESPLIT] public String findProperty ( String name ) { InvProperty result = null ; for ( InvProperty p : properties ) { if ( p . getName ( ) . equals ( name ) ) result = p ; } return ( result == null ) ? null : result . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if the service Base is reletive [CODESPLIT] public boolean isRelativeBase ( ) { if ( getServiceType ( ) == ServiceType . COMPOUND ) return true ; if ( uri == null ) { try { uri = new java . net . URI ( base ) ; } catch ( java . net . URISyntaxException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } } return ! uri . isAbsolute ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set current projection if found else deselect [CODESPLIT] public void setCurrentProjection ( ProjectionImpl proj ) { int row ; if ( 0 <= ( row = model . search ( proj ) ) ) { if ( debug ) System . out . println ( \" PTsetCurrentProjection found = \" + row ) ; selectedRow = row ; setRowSelectionInterval ( row , row ) ; } else { if ( debug ) System . out . println ( \" PTsetCurrentProjection not found = \" + row ) ; selectedRow = - 1 ; clearSelection ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "normal case already handled this is the case where a time has been specified and only one runtime [CODESPLIT] public Optional < TimeOffsetAxis > subsetFromTime ( SubsetParams params , CalendarDate runDate ) { CoordAxisHelper helper = new CoordAxisHelper ( this ) ; CoverageCoordAxisBuilder builder = null ; if ( params . isTrue ( SubsetParams . timePresent ) ) { double offset = getOffsetInTimeUnits ( runDate , CalendarDate . present ( ) ) ; builder = helper . subsetClosest ( offset ) ; } CalendarDate dateWanted = ( CalendarDate ) params . get ( SubsetParams . time ) ; if ( dateWanted != null ) { // convertFrom, convertTo double offset = getOffsetInTimeUnits ( runDate , dateWanted ) ; builder = helper . subsetClosest ( offset ) ; } Integer stride = ( Integer ) params . get ( SubsetParams . timeStride ) ; if ( stride == null || stride < 0 ) stride = 1 ; CalendarDateRange dateRange = ( CalendarDateRange ) params . get ( SubsetParams . timeRange ) ; if ( dateRange != null ) { double min = getOffsetInTimeUnits ( runDate , dateRange . getStart ( ) ) ; double max = getOffsetInTimeUnits ( runDate , dateRange . getEnd ( ) ) ; Optional < CoverageCoordAxisBuilder > buildero = helper . subset ( min , max , stride ) ; if ( buildero . isPresent ( ) ) builder = buildero . get ( ) ; else return Optional . empty ( buildero . getErrorMessage ( ) ) ; } assert ( builder != null ) ; // all the offsets are reletive to rundate builder . setReferenceDate ( runDate ) ; return Optional . of ( new TimeOffsetAxis ( builder ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an IOServiceProvider using its class string name . [CODESPLIT] static public void registerIOProvider ( String className ) throws IllegalAccessException , InstantiationException , ClassNotFoundException { Class ioClass = NetcdfFile . class . getClassLoader ( ) . loadClass ( className ) ; registerIOProvider ( ioClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an IOServiceProvider . A new instance will be created when one of its files is opened . [CODESPLIT] static public void registerIOProvider ( Class iospClass , boolean last ) throws IllegalAccessException , InstantiationException { IOServiceProvider spi ; spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; // fail fast if ( userLoads && ! last ) registeredProviders . add ( 0 , spi ) ; // put user stuff first else registeredProviders . add ( spi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an IOServiceProvider . A new instance will be created when one of its files is opened . This differs from the above in that it specifically locates the target iosp and inserts the new one in front of it in order to override the target . If the iospclass is already registered remove it and reinsert . If the target class is not present then insert at front of the registry [CODESPLIT] static public void registerIOProviderPreferred ( Class iospClass , Class target ) throws IllegalAccessException , InstantiationException { iospDeRegister ( iospClass ) ; // forcibly de-register int pos = - 1 ; for ( int i = 0 ; i < registeredProviders . size ( ) ; i ++ ) { IOServiceProvider candidate = registeredProviders . get ( i ) ; if ( candidate . getClass ( ) == target ) { if ( pos < i ) pos = i ; break ; // this is where is must be placed } } if ( pos < 0 ) pos = 0 ; IOServiceProvider spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; // fail fast registeredProviders . add ( pos , spi ) ; // insert before target }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if a specific IOServiceProvider is registered [CODESPLIT] static public boolean iospRegistered ( Class iospClass ) { for ( IOServiceProvider spi : registeredProviders ) { if ( spi . getClass ( ) == iospClass ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if a specific IOServiceProvider is registered and if so remove it . [CODESPLIT] static public boolean iospDeRegister ( Class iospClass ) { for ( int i = 0 ; i < registeredProviders . size ( ) ; i ++ ) { IOServiceProvider spi = registeredProviders . get ( i ) ; if ( spi . getClass ( ) == iospClass ) { registeredProviders . remove ( i ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging [CODESPLIT] static public void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugSPI = debugFlag . isSet ( \"NetcdfFile/debugSPI\" ) ; debugCompress = debugFlag . isSet ( \"NetcdfFile/debugCompress\" ) ; debugStructureIterator = debugFlag . isSet ( \"NetcdfFile/structureIterator\" ) ; N3header . disallowFileTruncation = debugFlag . isSet ( \"NetcdfFile/disallowFileTruncation\" ) ; N3header . debugHeaderSize = debugFlag . isSet ( \"NetcdfFile/debugHeaderSize\" ) ; showRequest = debugFlag . isSet ( \"NetcdfFile/showRequest\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open an existing file ( read only ) with option of cancelling . [CODESPLIT] static public NetcdfFile open ( String location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return open ( location , - 1 , cancelTask ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open an existing file ( read only ) with option of cancelling setting the RandomAccessFile buffer size for efficiency with an optional special object for the iosp . [CODESPLIT] static public NetcdfFile open ( String location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object iospMessage ) throws IOException { ucar . unidata . io . RandomAccessFile raf = getRaf ( location , buffer_size ) ; try { return open ( raf , location , cancelTask , iospMessage ) ; } catch ( Throwable t ) { raf . close ( ) ; throw new IOException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find out if the file can be opened but dont actually open it . Experimental . [CODESPLIT] static public boolean canOpen ( String location ) throws IOException { ucar . unidata . io . RandomAccessFile raf = null ; try { raf = getRaf ( location , - 1 ) ; return ( raf != null ) && canOpen ( raf ) ; } finally { if ( raf != null ) raf . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open an existing file ( read only ) specifying which IOSP is to be used . [CODESPLIT] static public NetcdfFile open ( String location , String iospClassName , int bufferSize , CancelTask cancelTask , Object iospMessage ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , IOException { Class iospClass = NetcdfFile . class . getClassLoader ( ) . loadClass ( iospClassName ) ; IOServiceProvider spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; // fail fast // send before iosp is opened if ( iospMessage != null ) spi . sendIospMessage ( iospMessage ) ; if ( bufferSize <= 0 ) bufferSize = default_buffersize ; ucar . unidata . io . RandomAccessFile raf = ucar . unidata . io . RandomAccessFile . acquire ( canonicalizeUriString ( location ) , bufferSize ) ; NetcdfFile result = new NetcdfFile ( spi , raf , location , cancelTask ) ; // send after iosp is opened if ( iospMessage != null ) spi . sendIospMessage ( iospMessage ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the { @code file : } or { @code file : // } prefix from the location if necessary . Also replaces back slashes with forward slashes . [CODESPLIT] public static String canonicalizeUriString ( String location ) { // get rid of file prefix, if any String uriString = location . trim ( ) ; if ( uriString . startsWith ( \"file://\" ) ) uriString = uriString . substring ( 7 ) ; else if ( uriString . startsWith ( \"file:\" ) ) uriString = uriString . substring ( 5 ) ; // get rid of crappy microsnot \\ replace with happy / return StringUtil2 . replace ( uriString , ' ' , \"/\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open an in - memory netcdf file with a specific iosp . [CODESPLIT] public static NetcdfFile openInMemory ( String name , byte [ ] data , String iospClassName ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException { ucar . unidata . io . InMemoryRandomAccessFile raf = new ucar . unidata . io . InMemoryRandomAccessFile ( name , data ) ; Class iospClass = NetcdfFile . class . getClassLoader ( ) . loadClass ( iospClassName ) ; IOServiceProvider spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; return new NetcdfFile ( spi , raf , name , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open an in - memory netcdf file . [CODESPLIT] public static NetcdfFile openInMemory ( String name , byte [ ] data ) throws IOException { ucar . unidata . io . InMemoryRandomAccessFile raf = new ucar . unidata . io . InMemoryRandomAccessFile ( name , data ) ; return open ( raf , name , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a local CDM file into memory . All reads are then done from memory . [CODESPLIT] public static NetcdfFile openInMemory ( String filename ) throws IOException { File file = new File ( filename ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ( int ) file . length ( ) ) ; try ( InputStream in = new BufferedInputStream ( new FileInputStream ( filename ) ) ) { IO . copy ( in , bos ) ; } return openInMemory ( filename , bos . toByteArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a remote CDM file into memory . All reads are then done from memory . [CODESPLIT] public static NetcdfFile openInMemory ( URI uri ) throws IOException { URL url = uri . toURL ( ) ; byte [ ] contents = IO . readContentsToByteArray ( url . openStream ( ) ) ; return openInMemory ( uri . toString ( ) , contents ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close all resources ( files sockets etc ) associated with this file . If the underlying file was acquired it will be released otherwise closed . if isClosed () already nothing will happen [CODESPLIT] public synchronized void close ( ) throws java . io . IOException { if ( cache != null ) { if ( cache . release ( this ) ) return ; } try { if ( null != spi ) { // log.warn(\"NetcdfFile.close called for ncfile=\"+this.hashCode()+\" for iosp=\"+spi.hashCode()); spi . close ( ) ; } } finally { spi = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a Group with the specified ( full ) name . An embedded / is interpreted as separating group names . [CODESPLIT] public Group findGroup ( String fullName ) { if ( fullName == null || fullName . length ( ) == 0 ) return rootGroup ; Group g = rootGroup ; StringTokenizer stoke = new StringTokenizer ( fullName , \"/\" ) ; while ( stoke . hasMoreTokens ( ) ) { String groupName = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; g = g . findGroup ( groupName ) ; if ( g == null ) return null ; } return g ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a Variable with the specified ( escaped full ) name . It may possibly be nested in multiple groups and / or structures . An embedded . is interpreted as structure . member . An embedded / is interpreted as group / variable . If the name actually has a . you must escape it ( call NetcdfFile . escapeName ( varname )) Any other chars may also be escaped as they are removed before testing . [CODESPLIT] public Variable findVariable ( String fullNameEscaped ) { if ( fullNameEscaped == null || fullNameEscaped . isEmpty ( ) ) { return null ; } Group g = rootGroup ; String vars = fullNameEscaped ; // break into group/group and var.var int pos = fullNameEscaped . lastIndexOf ( ' ' ) ; if ( pos >= 0 ) { String groups = fullNameEscaped . substring ( 0 , pos ) ; vars = fullNameEscaped . substring ( pos + 1 ) ; StringTokenizer stoke = new StringTokenizer ( groups , \"/\" ) ; while ( stoke . hasMoreTokens ( ) ) { String token = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; g = g . findGroup ( token ) ; if ( g == null ) return null ; } } // heres var.var - tokenize respecting the possible escaped '.' List < String > snames = EscapeStrings . tokenizeEscapedName ( vars ) ; if ( snames . size ( ) == 0 ) return null ; String varShortName = NetcdfFile . makeNameUnescaped ( snames . get ( 0 ) ) ; Variable v = g . findVariable ( varShortName ) ; if ( v == null ) return null ; int memberCount = 1 ; while ( memberCount < snames . size ( ) ) { if ( ! ( v instanceof Structure ) ) return null ; String name = NetcdfFile . makeNameUnescaped ( snames . get ( memberCount ++ ) ) ; v = ( ( Structure ) v ) . findVariable ( name ) ; if ( v == null ) return null ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a Dimension with the specified full name . It may be nested in multiple groups . An embedded / is interpreted as a group separator . A leading slash indicates the root group . That slash may be omitted but the { @code fullName } will be treated as if it were there . In other words the first name token in { @code fullName } is treated as the short name of a Group or Dimension relative to the root group . [CODESPLIT] public Dimension findDimension ( String fullName ) { if ( fullName == null || fullName . isEmpty ( ) ) { return null ; } Group group = rootGroup ; String dimShortName = fullName ; // break into group/group and dim int pos = fullName . lastIndexOf ( ' ' ) ; if ( pos >= 0 ) { String groups = fullName . substring ( 0 , pos ) ; dimShortName = fullName . substring ( pos + 1 ) ; StringTokenizer stoke = new StringTokenizer ( groups , \"/\" ) ; while ( stoke . hasMoreTokens ( ) ) { String token = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; group = group . findGroup ( token ) ; if ( group == null ) { return null ; } } } return group . findDimensionLocal ( dimShortName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look up global Attribute by ( full ) name . [CODESPLIT] public Attribute findGlobalAttribute ( String name ) { for ( Attribute a : gattributes ) { if ( name . equals ( a . getShortName ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look up global Attribute by name ignore case . [CODESPLIT] public Attribute findGlobalAttributeIgnoreCase ( String name ) { for ( Attribute a : gattributes ) { if ( name . equalsIgnoreCase ( a . getShortName ( ) ) ) return a ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an attribute with the specified ( escaped full ) name . It may possibly be nested in multiple groups and / or structures . An embedded . is interpreted as structure . member . An embedded / is interpreted as group / group or group / variable . An embedded @ is interpreted as variable@attribute If the name actually has a . you must escape it ( call NetcdfFile . escapeName ( varname )) Any other chars may also be escaped as they are removed before testing . [CODESPLIT] public Attribute findAttribute ( String fullNameEscaped ) { if ( fullNameEscaped == null || fullNameEscaped . length ( ) == 0 ) { return null ; } int posAtt = fullNameEscaped . indexOf ( ' ' ) ; if ( posAtt < 0 || posAtt >= fullNameEscaped . length ( ) - 1 ) return null ; if ( posAtt == 0 ) { return findGlobalAttribute ( fullNameEscaped . substring ( 1 ) ) ; } String path = fullNameEscaped . substring ( 0 , posAtt ) ; String attName = fullNameEscaped . substring ( posAtt + 1 ) ; // find the group Group g = rootGroup ; int pos = path . lastIndexOf ( ' ' ) ; String varName = ( pos > 0 && pos < path . length ( ) - 1 ) ? path . substring ( pos + 1 ) : null ; if ( pos >= 0 ) { String groups = path . substring ( 0 , pos ) ; StringTokenizer stoke = new StringTokenizer ( groups , \"/\" ) ; while ( stoke . hasMoreTokens ( ) ) { String token = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; g = g . findGroup ( token ) ; if ( g == null ) return null ; } } if ( varName == null ) // group attribute return g . findAttribute ( attName ) ; // heres var.var - tokenize respecting the possible escaped '.' List < String > snames = EscapeStrings . tokenizeEscapedName ( varName ) ; if ( snames . size ( ) == 0 ) return null ; String varShortName = NetcdfFile . makeNameUnescaped ( snames . get ( 0 ) ) ; Variable v = g . findVariable ( varShortName ) ; if ( v == null ) return null ; int memberCount = 1 ; while ( memberCount < snames . size ( ) ) { if ( ! ( v instanceof Structure ) ) return null ; String name = NetcdfFile . makeNameUnescaped ( snames . get ( memberCount ++ ) ) ; v = ( ( Structure ) v ) . findVariable ( name ) ; if ( v == null ) return null ; } return v . findAttribute ( attName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a String - valued global or variable Attribute by Attribute name ( ignore case ) return the Value of the Attribute . If not found return defaultValue [CODESPLIT] public String findAttValueIgnoreCase ( Variable v , String attName , String defaultValue ) { String attValue = null ; Attribute att ; if ( v == null ) att = rootGroup . findAttributeIgnoreCase ( attName ) ; else att = v . findAttributeIgnoreCase ( attName ) ; if ( ( att != null ) && att . isString ( ) ) attValue = att . getStringValue ( ) ; if ( null == attValue ) // not found, use default attValue = defaultValue ; return attValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CDL representation of Netcdf header info non strict [CODESPLIT] public String toNcML ( String url ) throws IOException { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; ncmlWriter . setWriteVariablesPredicate ( NcMLWriter . writeNoVariablesPredicate ) ; Element netcdfElement = ncmlWriter . makeNetcdfElement ( this , url ) ; return ncmlWriter . writeToString ( netcdfElement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write CDL representation to OutputStream . [CODESPLIT] public void writeCDL ( OutputStream out , boolean strict ) { PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( out , CDM . utf8Charset ) ) ; toStringStart ( pw , strict ) ; toStringEnd ( pw ) ; pw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write CDL representation to PrintWriter . [CODESPLIT] public void writeCDL ( PrintWriter pw , boolean strict ) { toStringStart ( pw , strict ) ; toStringEnd ( pw ) ; pw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the actual work is here [CODESPLIT] protected void writeCDL ( Formatter f , Indent indent , boolean strict ) { toStringStart ( f , indent , strict ) ; f . format ( \"%s}%n\" , indent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the NcML representation : dont show coodinate values [CODESPLIT] public void writeNcML ( java . io . OutputStream os , String uri ) throws IOException { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; Element netcdfElem = ncmlWriter . makeNetcdfElement ( this , uri ) ; ncmlWriter . writeToStream ( netcdfElem , os ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the NcML representation : dont show coodinate values [CODESPLIT] public void writeNcML ( java . io . Writer writer , String uri ) throws IOException { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; Element netcdfElem = ncmlWriter . makeNetcdfElement ( this , uri ) ; ncmlWriter . writeToWriter ( netcdfElem , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Check if file has changed and reread metadata if needed . All previous object references ( variables dimensions etc ) may become invalid - you must re - obtain . DO NOT USE THIS ROUTINE YET - NOT FULLY TESTED [CODESPLIT] @ Override public long getLastModified ( ) { if ( spi != null && spi instanceof AbstractIOServiceProvider ) { AbstractIOServiceProvider aspi = ( AbstractIOServiceProvider ) spi ; return aspi . getLastModified ( ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an attribute to a group . [CODESPLIT] public Attribute addAttribute ( Group parent , Attribute att ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( parent == null ) parent = rootGroup ; parent . addAttribute ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add optional String attribute to a group . [CODESPLIT] public Attribute addAttribute ( Group parent , String name , String value ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( value == null ) return null ; if ( parent == null ) parent = rootGroup ; Attribute att = new Attribute ( name , value ) ; parent . addAttribute ( att ) ; return att ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a group to the parent group . [CODESPLIT] public Group addGroup ( Group parent , Group g ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( parent == null ) parent = rootGroup ; parent . addGroup ( g ) ; return g ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a shared Dimension to a Group . [CODESPLIT] public Dimension addDimension ( Group parent , Dimension d ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( parent == null ) parent = rootGroup ; parent . addDimension ( d ) ; return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a shared Dimension from a Group by name . [CODESPLIT] public boolean removeDimension ( Group g , String dimName ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( g == null ) g = rootGroup ; return g . removeDimension ( dimName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Variable to the given group . [CODESPLIT] public Variable addVariable ( Group g , Variable v ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( g == null ) g = rootGroup ; if ( v != null ) g . addVariable ( v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Variable and add to the given group . [CODESPLIT] public Variable addVariable ( Group g , String shortName , DataType dtype , String dims ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( g == null ) g = rootGroup ; Variable v = new Variable ( this , g , null , shortName ) ; v . setDataType ( dtype ) ; v . setDimensions ( dims ) ; g . addVariable ( v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Variable of type Datatype . CHAR and add to the given group . [CODESPLIT] public Variable addStringVariable ( Group g , String shortName , String dims , int strlen ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( g == null ) g = rootGroup ; String dimName = shortName + \"_strlen\" ; addDimension ( g , new Dimension ( dimName , strlen ) ) ; Variable v = new Variable ( this , g , null , shortName ) ; v . setDataType ( DataType . CHAR ) ; v . setDimensions ( dims + \" \" + dimName ) ; g . addVariable ( v ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a Variable from the given group by name . [CODESPLIT] public boolean removeVariable ( Group g , String varName ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( g == null ) g = rootGroup ; return g . removeVariable ( varName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic way to send a message to the underlying IOSP . This message is sent after the file is open . To affect the creation of the file you must send into the factory method . [CODESPLIT] public Object sendIospMessage ( Object message ) { if ( null == message ) return null ; if ( message == IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) { Variable v = rootGroup . findVariable ( \"record\" ) ; boolean gotit = ( v != null ) && ( v instanceof Structure ) ; return gotit || makeRecordStructure ( ) ; } else if ( message == IOSP_MESSAGE_REMOVE_RECORD_STRUCTURE ) { Variable v = rootGroup . findVariable ( \"record\" ) ; boolean gotit = ( v != null ) && ( v instanceof Structure ) ; if ( gotit ) { rootGroup . remove ( v ) ; variables . remove ( v ) ; removeRecordStructure ( ) ; } return ( gotit ) ; } if ( spi != null ) return spi . sendIospMessage ( message ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there is an unlimited dimension make all variables that use it into a Structure . A Variable called record is added . You can then access these through the record structure . [CODESPLIT] protected Boolean makeRecordStructure ( ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; Boolean didit = false ; if ( ( spi != null ) && ( spi instanceof N3iosp ) && hasUnlimitedDimension ( ) ) { didit = ( Boolean ) spi . sendIospMessage ( IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; } return didit ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make this immutable . [CODESPLIT] public NetcdfFile setImmutable ( ) { if ( immutable ) return this ; immutable = true ; setImmutable ( rootGroup ) ; variables = Collections . unmodifiableList ( variables ) ; dimensions = Collections . unmodifiableList ( dimensions ) ; gattributes = Collections . unmodifiableList ( gattributes ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completely empty the objects in the netcdf file . Used for rereading the file on a sync () . [CODESPLIT] public void empty ( ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; variables = new ArrayList <> ( ) ; gattributes = new ArrayList <> ( ) ; dimensions = new ArrayList <> ( ) ; rootGroup = makeRootGroup ( ) ; // addedRecordStructure = false; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finish constructing the object model . This construsts the global variables attributes and dimensions . It also looks for coordinate variables . [CODESPLIT] public void finish ( ) { if ( immutable ) throw new IllegalStateException ( \"Cant modify\" ) ; variables = new ArrayList <> ( ) ; dimensions = new ArrayList <> ( ) ; gattributes = new ArrayList <> ( ) ; finishGroup ( rootGroup ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Do not call this directly use Variable . read () !! Ranges must be filled ( no nulls ) [CODESPLIT] protected Array readData ( ucar . nc2 . Variable v , Section ranges ) throws IOException , InvalidRangeException { long start = 0 ; if ( showRequest ) { log . info ( \"Data request for variable: {} section {}...\" , v . getFullName ( ) , ranges ) ; start = System . currentTimeMillis ( ) ; } /* if (unlocked) {\n      String info = cache.getInfo(this);\n      throw new IllegalStateException(\"File is unlocked - cannot use\\n\" + info);\n    } */ if ( spi == null ) { throw new IOException ( \"spi is null, perhaps file has been closed. Trying to read variable \" + v . getFullName ( ) ) ; } Array result = spi . readData ( v , ranges ) ; if ( showRequest ) { long took = System . currentTimeMillis ( ) - start ; log . info ( \" ...took= {} msecs\" , took ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a variable using the given section specification . The result is always an array of the type of the innermost variable . Its shape is the accumulation of all the shapes of its parent structures . [CODESPLIT] public Array readSection ( String variableSection ) throws IOException , InvalidRangeException { /* if (unlocked)\n      throw new IllegalStateException(\"File is unlocked - cannot use\"); */ ParsedSectionSpec cer = ParsedSectionSpec . parseVariableSection ( this , variableSection ) ; if ( cer . child == null ) { return cer . v . read ( cer . section ) ; } if ( spi == null ) return IospHelper . readSection ( cer ) ; else // allow iosp to optimize return spi . readSection ( cer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from a top level Variable and send data to a WritableByteChannel . Experimental . [CODESPLIT] protected long readToByteChannel ( ucar . nc2 . Variable v , Section section , WritableByteChannel wbc ) throws java . io . IOException , ucar . ma2 . InvalidRangeException { //if (unlocked) //  throw new IllegalStateException(\"File is unlocked - cannot use\"); if ( ( spi == null ) || v . hasCachedData ( ) ) return IospHelper . copyToByteChannel ( v . read ( section ) , wbc ) ; return spi . readToByteChannel ( v , section , wbc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do a bulk read on a list of Variables and return a corresponding list of Array that contains the results of a full read on each Variable . This is mostly here so DODSNetcdf can override it with one call to the server . [CODESPLIT] public java . util . List < Array > readArrays ( java . util . List < Variable > variables ) throws IOException { java . util . List < Array > result = new java . util . ArrayList <> ( ) ; for ( Variable variable : variables ) result . ( variable . read ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a variable using the given section specification . [CODESPLIT] public Array read ( String variableSection , boolean flatten ) throws IOException , InvalidRangeException { if ( ! flatten ) throw new UnsupportedOperationException ( \"NetdfFile.read(String variableSection, boolean flatten=false)\" ) ; return readSection ( variableSection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging - do not use [CODESPLIT] public static void main ( String [ ] arg ) throws Exception { //NetcdfFile.registerIOProvider( ucar.nc2.grib.GribServiceProvider.class); int wide = 20 ; Formatter f = new Formatter ( System . out ) ; f . format ( \" %\" + wide + \"s %n\" , \"test\" ) ; f . format ( \" %20s %n\" , \"asiuasdipuasiud\" ) ; /*\n    try {\n      String filename = \"R:/testdata2/hdf5/npoess/ExampleFiles/AVAFO_NPP_d2003125_t10109_e101038_b9_c2005829155458_devl_Tst.h5\";\n      NetcdfFile ncfile = NetcdfFile.open(filename);\n      //Thread.currentThread().sleep( 60 * 60 * 1000); // pause to examine in profiler\n\n      ncfile.close();\n\n    } catch (Exception e) {\n      e.printStackTrace();\n    }            */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a valid CDM object name . Control chars ( < 0x20 ) are not allowed . Trailing and leading blanks are not allowed and are stripped off . A space is converted into an underscore _ . A forward slash / is converted into an underscore _ . [CODESPLIT] static public String makeValidCdmObjectName ( String shortName ) { if ( shortName == null ) return null ; return StringUtil2 . makeValidCdmObjectName ( shortName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a CDMNode create its full name with appropriate backslash escaping of the specified characters . [CODESPLIT] static protected String makeFullName ( CDMNode node , String reservedChars ) { Group parent = node . getParentGroup ( ) ; if ( ( ( parent == null ) || parent . isRoot ( ) ) && ! node . isMemberOfStructure ( ) ) // common case? return EscapeStrings . backslashEscape ( node . getShortName ( ) , reservedChars ) ; StringBuilder sbuff = new StringBuilder ( ) ; appendGroupName ( sbuff , parent , reservedChars ) ; appendStructureName ( sbuff , node , reservedChars ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a synthetic full name from a group plus a string [CODESPLIT] protected String makeFullNameWithString ( Group parent , String name ) { name = makeValidPathName ( name ) ; // escape for use in full name   StringBuilder sbuff = new StringBuilder ( ) ; appendGroupName ( sbuff , parent , null ) ; sbuff . append ( name ) ; return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "inclusion is an OR [CODESPLIT] private boolean include ( MFile mfile ) { if ( includeFilters == null ) return true ; for ( MFileFilter filter : includeFilters ) { if ( filter . accept ( mfile ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exclusion is an AND [CODESPLIT] private boolean exclude ( MFile mfile ) { if ( excludeFilters == null ) return false ; for ( MFileFilter filter : excludeFilters ) { if ( filter . accept ( mfile ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "all AND filters must be satisfied [CODESPLIT] private boolean andFilter ( MFile mfile ) { if ( andFilters == null ) return true ; for ( MFileFilter filter : andFilters ) { if ( ! filter . accept ( mfile ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accessors [CODESPLIT] public DAP_T get ( CDM_T cdm ) { cdm = ( CDM_T ) CDMNode . unwrap ( cdm ) ; int lh = cdm . localhash ( ) ; return dapmap . get ( lh ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a CDM_T < - > DAP_T pair insert into the maps [CODESPLIT] public void put ( CDM_T cdm , DAP_T dap ) { assert ( dap != null && cdm != null ) ; cdm = ( CDM_T ) CDMNode . unwrap ( cdm ) ; int lh = cdm . localhash ( ) ; dapmap . put ( lh , dap ) ; cdmmap . put ( dap , cdm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a DAP_T < - > CDM_T pair remove from the maps [CODESPLIT] public void remove ( CDM_T cdm , DAP_T dap ) { assert ( dap != null && cdm != null ) ; cdm = ( CDM_T ) CDMNode . unwrap ( cdm ) ; dapmap . remove ( cdm . localhash ( ) ) ; cdmmap . remove ( dap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the attribute type as a <code > String< / code > . [CODESPLIT] public final String getTypeString ( ) { switch ( type ) { case CONTAINER : return \"Container\" ; case ALIAS : return \"Alias\" ; case BYTE : return \"Byte\" ; case INT16 : return \"Int16\" ; case UINT16 : return \"UInt16\" ; case INT32 : return \"Int32\" ; case UINT32 : return \"UInt32\" ; case FLOAT32 : return \"Float32\" ; case FLOAT64 : return \"Float64\" ; case STRING : return \"String\" ; case URL : return \"Url\" ; //    case BOOLEAN: return \"Boolean\"; default : return \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the attribute type as a <code > String< / code > . [CODESPLIT] public static final int getTypeVal ( String s ) { if ( s . equalsIgnoreCase ( \"Container\" ) ) return CONTAINER ; else if ( s . equalsIgnoreCase ( \"Byte\" ) ) return BYTE ; else if ( s . equalsIgnoreCase ( \"Int16\" ) ) return INT16 ; else if ( s . equalsIgnoreCase ( \"UInt16\" ) ) return UINT16 ; else if ( s . equalsIgnoreCase ( \"Int32\" ) ) return INT32 ; else if ( s . equalsIgnoreCase ( \"UInt32\" ) ) return UINT32 ; else if ( s . equalsIgnoreCase ( \"Float32\" ) ) return FLOAT32 ; else if ( s . equalsIgnoreCase ( \"Float64\" ) ) return FLOAT64 ; else if ( s . equalsIgnoreCase ( \"String\" ) ) return STRING ; else if ( s . equalsIgnoreCase ( \"URL\" ) ) return URL ; else return UNKNOWN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the attribute value at <code > index< / code > . [CODESPLIT] public String getValueAt ( int index ) throws NoSuchAttributeException { checkVectorUsage ( ) ; return ( String ) ( ( Vector ) attr ) . elementAt ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the attribute value at <code > index< / code > . [CODESPLIT] public String getValueAtN ( int index ) { if ( ! ( attr instanceof Vector ) ) return null ; return ( String ) ( ( Vector ) attr ) . elementAt ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a value to this attribute . [CODESPLIT] public void appendValue ( String value , boolean check ) throws NoSuchAttributeException , AttributeBadValueException { checkVectorUsage ( ) ; if ( check ) value = forceValue ( type , value ) ; ( ( Vector ) attr ) . addElement ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the value is legal for a given type . [CODESPLIT] private static void dispatchCheckValue ( int type , String value ) throws AttributeBadValueException { switch ( type ) { case BYTE : if ( ! checkByte ( value ) ) throw new AttributeBadValueException ( \"`\" + value + \"' is not a Byte value.\" ) ; break ; case INT16 : if ( ! checkShort ( value ) ) throw new AttributeBadValueException ( \"`\" + value + \"' is not an Int16 value.\" ) ; break ; case UINT16 : if ( ! checkUShort ( value ) ) throw new AttributeBadValueException ( \"`\" + value + \"' is not an UInt16 value.\" ) ; break ; case INT32 : if ( ! checkInt ( value ) ) throw new AttributeBadValueException ( \"`\" + value + \"' is not an Int32 value.\" ) ; break ; case UINT32 : if ( ! checkUInt ( value ) ) throw new AttributeBadValueException ( \"`\" + value + \"' is not an UInt32 value.\" ) ; break ; case FLOAT32 : if ( ! checkFloat ( value ) ) throw new AttributeBadValueException ( \"`\" + value + \"' is not a Float32 value.\" ) ; break ; case FLOAT64 : if ( ! checkDouble ( value ) ) throw new AttributeBadValueException ( \"`\" + value + \"' is not a Float64 value.\" ) ; break ; //    case BOOLEAN: //      if(!checkBoolean(value)) //\tthrow new AttributeBadValueException(\"`\" + value + \"' is not a Boolean value.\"); //      break; default : // Assume UNKNOWN, CONTAINER, STRING, and URL are okay. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the value is legal for a given type and try to convert to specified type . [CODESPLIT] private static String forceValue ( int type , String value ) throws AttributeBadValueException { try { dispatchCheckValue ( type , value ) ; } catch ( AttributeBadValueException abe ) { if ( type == BYTE ) { // Try again: allow e.g. negative byte values short val = Short . parseShort ( value ) ; if ( val > 255 && val < - 128 ) throw new AttributeBadValueException ( \"Cannot convert to byte: \" + value ) ; value = Integer . toString ( ( val & 0xFF ) ) ; } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if string is a valid Byte . [CODESPLIT] private static final boolean checkByte ( String s ) throws AttributeBadValueException { try { // Byte.parseByte() can't be used because values > 127 are allowed short val = Short . parseShort ( s ) ; if ( DebugValueChecking ) { log . debug ( \"Attribute.checkByte() - string: '\" + s + \"'   value: \" + val ) ; } if ( val > 0xFF || val < 0 ) return false ; else return true ; } catch ( NumberFormatException e ) { throw new AttributeBadValueException ( \"`\" + s + \"' is not a Byte value.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if string is a valid Int16 . [CODESPLIT] private static final boolean checkShort ( String s ) { try { short val = Short . parseShort ( s ) ; if ( DebugValueChecking ) { DAPNode . log . debug ( \"Attribute.checkShort() - string: '\" + s + \"'   value: \" + val ) ; } return true ; } catch ( NumberFormatException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if string is a valid Int32 . [CODESPLIT] private static final boolean checkInt ( String s ) { try { //Coverity[FB.DLS_DEAD_LOCAL_STORE] int val = Integer . parseInt ( s ) ; if ( DebugValueChecking ) { DAPNode . log . debug ( \"Attribute.checkInt() - string: '\" + s + \"'   value: \" + val ) ; } return true ; } catch ( NumberFormatException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if string is a valid UInt32 . [CODESPLIT] private static final boolean checkUInt ( String s ) { // Note: Because there is no Unsigned class in Java, use Long instead. try { long val = Long . parseLong ( s ) ; if ( DebugValueChecking ) { DAPNode . log . debug ( \"Attribute.checkUInt() - string: '\" + s + \"'   value: \" + val ) ; } if ( val > 0xFFFFFFFF L ) return false ; else return true ; } catch ( NumberFormatException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if string is a valid Float32 . [CODESPLIT] private static final boolean checkFloat ( String s ) { try { //Coverity[FB.DLS_DEAD_LOCAL_STORE]= float val = Float . parseFloat ( s ) ; if ( DebugValueChecking ) { DAPNode . log . debug ( \"Attribute.checkFloat() - string: '\" + s + \"'   value: \" + val ) ; } return true ; } catch ( NumberFormatException e ) { if ( s . equalsIgnoreCase ( \"nan\" ) || s . equalsIgnoreCase ( \"inf\" ) ) return true ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if string is a valid Float64 . [CODESPLIT] private static final boolean checkDouble ( String s ) { try { //Coverity[FB.DLS_DEAD_LOCAL_STORE] double val = Double . parseDouble ( s ) ; if ( DebugValueChecking ) { DAPNode . log . debug ( \"Attribute.checkDouble() - string: '\" + s + \"'   value: \" + val ) ; } return true ; } catch ( NumberFormatException e ) { if ( s . equalsIgnoreCase ( \"nan\" ) || s . equalsIgnoreCase ( \"inf\" ) ) return true ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of this <code > Attribute< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { Attribute a = ( Attribute ) super . cloneDAG ( map ) ; // assume type, is_alias, and aliased_to have been cloned already if ( type == CONTAINER ) a . attr = ( AttributeTable ) cloneDAG ( map , ( ( AttributeTable ) attr ) ) ; else a . attr = ( ( Vector ) attr ) . clone ( ) ; // ok, attr is a vector of strings return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the data type of an attribute . Make it unsigned if the variable is unsigned . [CODESPLIT] private DataType getAttributeDataType ( Attribute attribute ) { DataType dataType = attribute . getDataType ( ) ; if ( signedness == Signedness . UNSIGNED ) { // If variable is unsigned, make its integral attributes unsigned too.\r dataType = dataType . withSignedness ( signedness ) ; } return dataType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a distinct integer for each of the { @link DataType#isNumeric () numeric } data types that can be used to ( roughly ) order them by the range of the DataType . { @code BYTE < UBYTE < SHORT < USHORT < INT < UINT < LONG < ULONG < FLOAT < DOUBLE } . { @code - 1 } will be returned for all non - numeric data types . [CODESPLIT] public static int rank ( DataType dataType ) { if ( dataType == null ) { return - 1 ; } switch ( dataType ) { case BYTE : return 0 ; case UBYTE : return 1 ; case SHORT : return 2 ; case USHORT : return 3 ; case INT : return 4 ; case UINT : return 5 ; case LONG : return 6 ; case ULONG : return 7 ; case FLOAT : return 8 ; case DOUBLE : return 9 ; default : return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the data type that is the largest among the arguments . Relative sizes of data types are determined via { @link #rank ( DataType ) } . [CODESPLIT] public static DataType largestOf ( DataType ... dataTypes ) { DataType widest = null ; for ( DataType dataType : dataTypes ) { if ( widest == null ) { widest = dataType ; } else if ( rank ( dataType ) > rank ( widest ) ) { widest = dataType ; } } return widest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the smallest numeric data type that : <ol > <li > can hold a larger integer than { @code dataType } can< / li > <li > if integral has the same signedness as { @code dataType } < / li > < / ol > The relative sizes of data types are determined in a manner consistent with { @link #rank ( DataType ) } . <p / > <table border = 1 > <tr > <th > Argument< / th > <th > Result< / th > < / tr > <tr > <td > BYTE< / td > <td > SHORT< / td > < / tr > <tr > <td > UBYTE< / td > <td > USHORT< / td > < / tr > <tr > <td > SHORT< / td > <td > INT< / td > < / tr > <tr > <td > USHORT< / td > <td > UINT< / td > < / tr > <tr > <td > INT< / td > <td > LONG< / td > < / tr > <tr > <td > UINT< / td > <td > ULONG< / td > < / tr > <tr > <td > LONG< / td > <td > DOUBLE< / td > < / tr > <tr > <td > ULONG< / td > <td > DOUBLE< / td > < / tr > <tr > <td > Any other data type< / td > <td > Just return argument< / td > < / tr > < / table > <p / > The returned type is intended to be just big enough to hold the result of performing an unsigned conversion of a value of the smaller type . For example the { @code byte } value { @code - 106 } equals { @code 150 } when interpreted as unsigned . That won t fit in a ( signed ) { @code byte } but it will fit in a { @code short } . [CODESPLIT] public static DataType nextLarger ( DataType dataType ) { switch ( dataType ) { case BYTE : return SHORT ; case UBYTE : return USHORT ; case SHORT : return INT ; case USHORT : return UINT ; case INT : return LONG ; case UINT : return ULONG ; case LONG : return DOUBLE ; case ULONG : return DOUBLE ; default : return dataType ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this is a gridded dataset that is accessible via WMS . [CODESPLIT] @ Override public boolean isViewable ( Dataset ds ) { Access access = ds . getAccess ( ServiceType . WMS ) ; return access != null && ( ThreddsConfig . getBoolean ( \"WMS.allow\" , false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String is a valid single - line String . <p > <p > A string will be considered a valid single - line string if it does not contain any characters from these Unicode general categories : <p > <ul > <li > Cc - Other Control< / li > <li > Cf - Other Format< / li > <li > Cs - Other Surrogate< / li > <li > Co - Other Private Use< / li > <li > Cn - Other Not Assigned< / li > <li > Zl - Separator Line< / li > <li > Zp - Separator Paragraph< / li > < / ul > <p > <p > Or in other words allow : Letters Numbers Marks Punctuation Symbols and Space separators . [CODESPLIT] public static boolean validSingleLineString ( String singleLineString ) { if ( singleLineString == null ) return false ; Matcher m = INVALID_CHARACTERS_FOR_SINGLE_LINE_STRING_PATTERN . matcher ( singleLineString ) ; return ! m . find ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String is a valid path . <p > <p > A String is considered a valid path if : <ul > <li > when passed to validSingleLineString ( String ) true is returned and <li > it does not contain any parent path segments ( .. / ) . < / li > < / li > < / ul > [CODESPLIT] @ SuppressWarnings ( { \"SimplifiableIfStatement\" } ) public static boolean validPath ( String path ) { if ( path == null ) return false ; // Don't allow \"..\" directories in path. if ( path . indexOf ( \"/../\" ) != - 1 || path . equals ( \"..\" ) || path . startsWith ( \"../\" ) || path . endsWith ( \"/..\" ) ) return false ; return validSingleLineString ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String is a valid File path . <p > <p > A String is considered a valid File path if : <ul > <li > when passed to validPath ( String ) true is returned ; and< / li > <li > it does not contain the Java File path separator ( java . io . File . pathSeparatorChar ) which is system dependant . < / li > < / ul > [CODESPLIT] @ SuppressWarnings ( { \"SimplifiableIfStatement\" } ) public static boolean validFilePath ( String path ) { if ( path == null ) return false ; if ( path . indexOf ( File . pathSeparatorChar ) != - 1 ) return false ; return validPath ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String is a valid ID string . <p > <p > A String is considered a valid ID string if : <ul > <li > it contains no space separator characters ( Unicode general category Zs - Separator Space ) ; and< / li > <li > true is returned when the string is passed to validSingleLineString ( String ) . < / li > < / ul > [CODESPLIT] public static boolean validIdString ( String id ) { if ( id == null ) return false ; Matcher m = INVALID_CHARACTERS_FOR_ID_STRING_PATTERN . matcher ( id ) ; return ! ( m . find ( ) || ! validSingleLineString ( id ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String contains any less than ( < ) or greater than ( > ) characters ; otherwise return false . [CODESPLIT] public static boolean containsAngleBracketCharacters ( String string ) { if ( string == null ) return false ; if ( string . indexOf ( \"<\" ) == - 1 && string . indexOf ( \">\" ) == - 1 ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String contains any ampersand ( & ) characters ; otherwise return false . [CODESPLIT] public static boolean containsAmpersandCharacters ( String string ) { if ( string == null ) return false ; if ( string . indexOf ( \"&\" ) == - 1 ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String contains any backslash ( \\ ) characters ; otherwise return false . [CODESPLIT] public static boolean containsBackslashCharacters ( String string ) { if ( string == null ) return false ; if ( string . indexOf ( \"\\\\\" ) == - 1 ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String is true or false ignoring case . [CODESPLIT] @ SuppressWarnings ( { \"SimplifiableIfStatement\" } ) public static boolean validBooleanString ( String boolString ) { if ( boolString == null ) return false ; Matcher m = VALID_CHARACTERS_FOR_BOOLEAN_STRING_PATTERN . matcher ( boolString ) ; if ( ! m . matches ( ) ) return false ; return boolString . equalsIgnoreCase ( \"true\" ) || boolString . equalsIgnoreCase ( \"false\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String is an alphanumeric string . [CODESPLIT] public static boolean validAlphanumericString ( String alphNumString ) { if ( alphNumString == null ) return false ; Matcher m = VALID_CHARACTERS_FOR_ALPHANUMERIC_STRING_PATTERN . matcher ( alphNumString ) ; return m . matches ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given String is an alphanumeric string and one of the valid strings in the constrained set . [CODESPLIT] public static boolean validAlphanumericStringConstrainedSet ( String alphNumString , String [ ] constrainedSet , boolean ignoreCase ) { if ( alphNumString == null || constrainedSet == null || constrainedSet . length == 0 ) return false ; Matcher m = VALID_CHARACTERS_FOR_ALPHANUMERIC_STRING_PATTERN . matcher ( alphNumString ) ; if ( ! m . matches ( ) ) return false ; for ( String s : constrainedSet ) { if ( ignoreCase ? alphNumString . equalsIgnoreCase ( s ) : alphNumString . equals ( s ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the given path does not ascend into parent directory . [CODESPLIT] @ SuppressWarnings ( { \"UnnecessaryContinue\" } ) public static boolean descendOnlyFilePath ( String path ) { String [ ] pathSegments = path . split ( \"/\" ) ; //String[] newPathSegments = new String[pathSegments.length]; int i = 0 ; for ( int indxOrigSegs = 0 ; indxOrigSegs < pathSegments . length ; indxOrigSegs ++ ) { String s = pathSegments [ indxOrigSegs ] ; if ( s . equals ( \".\" ) ) continue ; else if ( s . equals ( \"..\" ) ) { if ( i == 0 ) return false ; i -- ; } else { //newPathSegments[i] = s; i ++ ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that the given string is a valid percentHexOctets string . The string is considered valid if it only contains a sequence of % prefixed two character strings where each two character string is composed only of US - ASCII digits and upper - or lower - case A - F . <p > For example : %31%32 or %7b%7d%7E [CODESPLIT] public static boolean validPercentHexOctetsString ( String percentHexOctetsString ) { if ( percentHexOctetsString == null ) return false ; Matcher m = VALID_PERCENT_HEX_OCTETS_PATTERN . matcher ( percentHexOctetsString ) ; return m . matches ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the percentHexOctets string that represents the given Unicode code point in the given character set or null if the given character set cannot encode the given code point . [CODESPLIT] public static String unicodeCodePoint2PercentHexString ( int codePoint , String charsetName ) { if ( ! Character . isDefined ( codePoint ) ) throw new IllegalArgumentException ( String . format ( \"Given code point [U+%1$04X - %1$d] not assigned to an abstract character.\" , codePoint ) ) ; if ( Character . getType ( codePoint ) == Character . SURROGATE ) throw new IllegalArgumentException ( String . format ( \"Given code point [U+%1$04X - %1$d] is an unencodable (by itself) surrogate character.\" , codePoint ) ) ; Charset charset = Charset . availableCharsets ( ) . get ( charsetName ) ; if ( charset == null ) throw new IllegalArgumentException ( String . format ( \"Unsupported charset [%s].\" , charsetName ) ) ; char [ ] chars = Character . toChars ( codePoint ) ; ByteBuffer byteBuffer = null ; try { byteBuffer = charset . newEncoder ( ) . encode ( CharBuffer . wrap ( chars ) ) ; } catch ( CharacterCodingException e ) { String message = String . format ( \"Given code point [U+%1$04X - %1$d] cannot be encode in given charset [%2$s].\" , codePoint , charsetName ) ; throw new IllegalArgumentException ( message , e ) ; } byteBuffer . rewind ( ) ; StringBuilder encodedString = new StringBuilder ( ) ; for ( int i = 0 ; i < byteBuffer . limit ( ) ; i ++ ) { String asHex = Integer . toHexString ( byteBuffer . get ( ) & 0xFF ) ; encodedString . append ( \"%\" ) . append ( asHex . length ( ) == 1 ? \"0\" : \"\" ) . append ( asHex ) ; } return encodedString . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds a param and value . [CODESPLIT] public final void addParam ( String key , String value ) { //System.out.println(\" adding \" + key + \" = \" + value); paramStr . put ( key . trim ( ) , value ) ; paramsValues = paramsValues + \"\\t\" + key + \"\\t\" + value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds a param and value . [CODESPLIT] public final void addParam ( String key , int value ) { //System.out.println(\" adding \" + key + \" = \" + value); paramInt . put ( key , new Integer ( value ) ) ; paramStr . put ( key , Integer . toString ( value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds a param and value . [CODESPLIT] public final void addParam ( String key , float value ) { //System.out.println(\" adding \" + key + \" = \" + value); paramDbl . put ( key , new Double ( value ) ) ; paramStr . put ( key , Float . toString ( value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets a param and value . [CODESPLIT] public final String getParam ( String key ) { String value = paramStr . get ( key ) ; if ( value == null ) { // check the dbl and int tables Double result = paramDbl . get ( key ) ; if ( result != null ) { value = result . toString ( ) ; } else { Integer intResult = paramInt . get ( key ) ; if ( intResult != null ) { value = intResult . toString ( ) ; } } // save it back off to the string table for next time if ( value != null ) { paramStr . put ( key , value ) ; } } if ( debug && value == null ) { System . out . println ( key + \" value not found\" ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare GridDefRecords the numerics will use nearlyEquals so values that differ in 3 or 4th decimal places will return equal . This is being coded because the NDFD model dx differ in the 3 decimal place otherwise equal . [CODESPLIT] public static boolean compare ( GridDefRecord local , GridDefRecord other ) { java . util . Set < String > keys = local . getKeys ( ) ; java . util . Set < String > okeys = other . getKeys ( ) ; if ( keys . size ( ) != okeys . size ( ) ) return false ; for ( String key : keys ) { if ( key . equals ( WIND_FLAG ) || key . equals ( RESOLUTION ) || key . equals ( VECTOR_COMPONENT_FLAG ) || key . equals ( GDS_KEY ) ) continue ; String val = local . getParam ( key ) ; String oval = other . getParam ( key ) ; // if ( val . matches ( \"^[0-9]+\\\\.[0-9]*\" ) ) { //double double d = local . getDouble ( key ) ; double od = other . getDouble ( key ) ; if ( ! Misc . nearlyEquals ( d , od ) ) return false ; } else if ( val . matches ( \"^[0-9]+\" ) ) { // int if ( ! val . equals ( oval ) ) return false ; } else { // String if ( ! val . equals ( oval ) ) return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Step 1 - read and extract a Bufr Message [CODESPLIT] public void process ( InputStream is ) throws IOException { int pos = - 1 ; Buffer b = null ; while ( true ) { b = ( pos < 0 ) ? readBuffer ( is ) : readBuffer ( is , b , pos ) ; pos = process ( b , is ) ; if ( b . done ) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return where in the buffer we got to . [CODESPLIT] private int process ( Buffer b , InputStream is ) throws IOException { int start = 0 ; while ( start < b . have ) { int matchPos = matcher . indexOf ( b . buff , start , b . have - start ) ; // didnt find \"BUFR\" match if ( matchPos < 0 ) { if ( start == 0 ) // discard all but last 3 bytes return b . have - 3 ; else return start ; // indicates part of the buffer thats not processed } // do we have the length already read ?? if ( matchPos + 6 >= b . have ) { return start ; // this will save the end of the buffer and read more in. } // read BUFR message length int b1 = ( b . buff [ matchPos + 4 ] & 0xff ) ; int b2 = ( b . buff [ matchPos + 5 ] & 0xff ) ; int b3 = ( b . buff [ matchPos + 6 ] & 0xff ) ; int messLen = b1 << 16 | b2 << 8 | b3 ; // System.out.println(\"match at=\" + matchPos + \" len= \" + messLen); // create a task for this message //int headerLen = matchPos - start; MessageTask task = new MessageTask ( messLen ) ; task . header = extractHeader ( start , matchPos , b ) ; // copy message bytes into it int last = matchPos + messLen ; if ( last > b . have ) { task . have = b . have - matchPos ; System . arraycopy ( b . buff , matchPos , task . mess , 0 , task . have ) ; // read the rest of the message if ( ! readBuffer ( is , task . mess , task . have , task . len - task . have ) ) { System . out . println ( \"Failed to read remaining BUFR message\" ) ; break ; } } else { task . have = task . len ; System . arraycopy ( b . buff , matchPos , task . mess , 0 , task . have ) ; } boolean ok = true ; // check on ending for ( int i = task . len - 4 ; i < task . len ; i ++ ) { int bb = task . mess [ i ] ; if ( bb != 55 ) { //System.out.println(\"Missing End of BUFR message at pos=\" + i + \" \" + bb); ok = false ; bad_msgs ++ ; } } try { if ( ok ) messQ . put ( task ) ; total_msgs ++ ; //System.out.println(\" added message \" + task.id + \" start=\" + matchPos + \" end= \" + (matchPos + messLen)); } catch ( InterruptedException e ) { System . out . println ( \" interrupted queue put - assume process exit\" ) ; break ; } start = matchPos + messLen + 1 ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message DataRow { string fullName = 1 ; DataType dataType = 2 ; Section section = 3 ; bool bigend = 4 ; uint32 version = 5 ; bool isVlen = 7 ; uint32 nelems = 9 ; [CODESPLIT] public NcStreamProto . DataRow encodeData3 ( String name , boolean isVlen , Section section , Array data ) { NcStreamProto . DataRow . Builder builder = NcStreamProto . DataRow . newBuilder ( ) ; encodeData3 ( builder , name , isVlen , section , data ) ; return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * message Member { string shortName = 1 ; DataType dataType = 2 ; repeated uint32 shape = 3 ; // or section? bool isVlen = 4 ; } [CODESPLIT] NcStreamProto . ArrayStructureRow . Builder encodeStructureData ( String structName , Array data ) { assert data instanceof ArrayStructure ; ArrayStructure as = ( ArrayStructure ) data ; int nelems = ( int ) as . getSize ( ) ; List < MemberData > memberData = new ArrayList <> ( ) ; StructureMembers sm = as . getStructureMembers ( ) ; for ( StructureMembers . Member m : sm . getMembers ( ) ) { memberData . add ( new MemberData ( m , nelems ) ) ; } // use most efficient form of data extraction for ( int recno = 0 ; recno < nelems ; recno ++ ) { for ( MemberData md : memberData ) { if ( md . member . isVariableLength ( ) ) { md . vlenList . add ( as . getArray ( recno , md . member ) ) ; } else { extractData ( as , recno , md ) ; } } } NcStreamProto . ArrayStructureRow . Builder builder = NcStreamProto . ArrayStructureRow . newBuilder ( ) ; for ( MemberData md : memberData ) { NcStreamProto . Member . Builder member = NcStreamProto . Member . newBuilder ( ) ; member . setShortName ( md . member . getName ( ) ) ; member . setDataType ( NcStream . convertDataType ( md . member . getDataType ( ) ) ) ; /* LOOK\n      member.setNelems(md.nelems);\n      if (md.member.isVariableLength()) {\n        md.completeVlens();\n        nested.addAllVlens (md.vlens);\n        nested.setPrimdata(ByteString.copyFrom(md.bb));\n\n      } else if (md.member.getDataType() == DataType.STRING)\n        nested.addAllStringdata(md.stringList);\n      else if (md.member.getDataType() == DataType.OPAQUE)\n        nested.addAllOpaquedata(md.opaqueList);\n      else\n        nested.setPrimdata(ByteString.copyFrom(md.bb)); */ builder . addMembers ( member ) ; } return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked once on first request so that everything is available especially Spring stuff . [CODESPLIT] public void doonce ( HttpServletRequest req ) throws SendError { if ( once ) return ; super . initOnce ( req ) ; if ( this . uploaddir == null ) throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , \"Upload disabled\" ) ; this . uploaddirname = new File ( this . uploaddir ) . getName ( ) ; // Get the upload form File upform = null ; upform = tdsContext . getUploadForm ( ) ; if ( upform == null ) { // Look in WEB-INF directory File root = tdsContext . getServletRootDirectory ( ) ; upform = new File ( root , DEFAULTUPLOADFORM ) ; } try { this . uploadform = loadForm ( upform ) ; } catch ( IOException ioe ) { throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Controller entry point ( s ) [CODESPLIT] @ RequestMapping ( value = \"**\" , method = RequestMethod . GET ) public void doGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException { try { setup ( req , res ) ; switch ( this . params . command ) { case NONE : case UPLOAD : // Send back the upload form sendForm ( \"No files uploaded\" ) ; break ; case INQUIRE : String result = inquire ( ) ; // Send back the inquiry answers sendOK ( result ) ; break ; default : throw new SendError ( res . SC_BAD_REQUEST , \"Unknown command: \" + this . params . command ) ; } } catch ( SendError se ) { sendError ( se ) ; } catch ( Exception e ) { String msg = getStackTrace ( e ) ; sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , msg , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parser core [CODESPLIT] void projections ( Ceparse state , Object list0 ) throws ParseException { ast . projections = ( List < ASTprojection > ) list0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Selection Procedures [CODESPLIT] Object clauselist ( Ceparse state , Object list0 , Object decl ) throws ParseException { List < ASTclause > list = ( List < ASTclause > ) list0 ; if ( list == null ) list = new ArrayList < ASTclause > ( ) ; list . add ( ( ASTclause ) decl ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove double quotes from around a string . If there s not both start and ending quotes does nothing . [CODESPLIT] String removeQuotes ( String s ) { if ( s . startsWith ( \"\\\"\" ) && s . endsWith ( \"\\\"\" ) ) return s . substring ( 1 , s . length ( ) - 1 ) ; else return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a stack of BaseType variables mark these as part of the current projection . This function assumes that if the TOS contains a Ctor type variable all of its members are to be projected . Also assume all variables under the TOS are Ctor variables and only the ctor itself is to be projected ; the member within the Ctor that is part of the projection will be on the stack too . [CODESPLIT] void markStackedVariables ( Stack s ) { // Reverse the stack.\r Stack bts = new Stack ( ) ; // LogStream.err.println(\"Variables to be marked:\");\r while ( ! s . empty ( ) ) { // LogStream.err.println(((BaseType)s.peek()).getName());\r bts . push ( s . pop ( ) ) ; } // For each but the last stack element, set the projection.\r // setProject(true, false) for a ctor type sets the projection for\r // the ctor itself but *does not* set the projection for all its\r // children. Thus, if a user wants the variable S.X, and S contains Y\r // and Z too, S's projection will be set (so serialize will descend\r // into S) but X, Y and Z's projection remain clear. In this example,\r // X's projection is set by the code that follows the while loop.\r // 1/28/2000 jhrg\r while ( bts . size ( ) > 1 ) { ServerMethods ct = ( ServerMethods ) bts . pop ( ) ; ct . setProject ( true , false ) ; } // For the last element, project the entire variable.\r ServerMethods bt = ( ServerMethods ) bts . pop ( ) ; bt . setProject ( true , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This parses then fills in the evaluator from the AST [CODESPLIT] public boolean constraint_expression ( CEEvaluator ceEval , BaseTypeFactory factory , ClauseFactory clauseFactory ) throws DAP2Exception , ParseException { ServerDDS sdds = ceEval . getDDS ( ) ; if ( ! parse ( ) ) return false ; ast . init ( ceEval , factory , clauseFactory , sdds , getASTnodeset ( ) ) ; ast . walkConstraint ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write ncml from given dataset [CODESPLIT] boolean writeNcml ( String location ) { boolean err = false ; closeOpenFiles ( ) ; try { final String result ; ds = openDataset ( location , addCoords , null ) ; if ( ds == null ) { editor . setText ( \"Failed to open <\" + location + \">\" ) ; } else { final NcMLWriter ncmlWriter = new NcMLWriter ( ) ; final Element netcdfElem = ncmlWriter . makeNetcdfElement ( ds , null ) ; result = ncmlWriter . writeToString ( netcdfElem ) ; editor . setText ( result ) ; editor . setCaretPosition ( 0 ) ; } } catch ( Exception e ) { final StringWriter sw = new StringWriter ( 10000 ) ; e . printStackTrace ( ) ; e . printStackTrace ( new PrintWriter ( sw ) ) ; editor . setText ( sw . toString ( ) ) ; err = true ; } return ! err ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read text from textArea through NcMLReader then write it back out via resulting dataset [CODESPLIT] void doTransform ( String text ) { try { final StringReader reader = new StringReader ( text ) ; final NetcdfDataset ncd = NcMLReader . readNcML ( reader , null ) ; final StringWriter sw = new StringWriter ( 10000 ) ; ncd . writeNcML ( sw , null ) ; editor . setText ( sw . toString ( ) ) ; editor . setCaretPosition ( 0 ) ; JOptionPane . showMessageDialog ( this , \"File successfully transformed\" ) ; } catch ( IOException ioe ) { JOptionPane . showMessageDialog ( this , \"ERROR: \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read text from textArea through NcMLReader then write it back out via resulting dataset [CODESPLIT] private void checkNcml ( Formatter f ) { if ( ncmlLocation == null ) { return ; } try { NetcdfDataset ncd = NetcdfDataset . openDataset ( ncmlLocation ) ; ncd . check ( f ) ; } catch ( IOException ioe ) { JOptionPane . showMessageDialog ( this , \"ERROR: \" + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "static so can be called from static enum classes [CODESPLIT] private static String getValueFromThreddsConfig ( String key , String alternateKey , String defaultValue ) { String value = ThreddsConfig . get ( key , null ) ; if ( value == null && alternateKey != null ) value = ThreddsConfig . get ( alternateKey , null ) ; if ( value == null ) value = defaultValue ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read in the index index raf already open ; return null on failure [CODESPLIT] @ Nullable static PartitionCollectionMutable openMutablePCFromIndex ( String name , RandomAccessFile raf , FeatureCollectionConfig config , org . slf4j . Logger logger ) { Grib2PartitionBuilderFromIndex builder = new Grib2PartitionBuilderFromIndex ( name , config , logger ) ; if ( builder . readIndex ( raf ) ) return builder . pc ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * extend GribCollection { repeated Partition partitions = 100 ; required bool isPartitionOfPartitions = 101 ; repeated uint32 run2part = 102 ; // masterRuntime index to partition index } [CODESPLIT] @ Override protected boolean readExtensions ( GribCollectionProto . GribCollection proto ) { pc . isPartitionOfPartitions = proto . getIsPartitionOfPartitions ( ) ; List < Integer > list = proto . getRun2PartList ( ) ; pc . run2part = new int [ list . size ( ) ] ; int count = 0 ; for ( int partno : list ) pc . run2part [ count ++ ] = partno ; List < ucar . nc2 . grib . collection . GribCollectionProto . Partition > partList = proto . getPartitionsList ( ) ; for ( ucar . nc2 . grib . collection . GribCollectionProto . Partition partProto : partList ) makePartition ( partProto ) ; return partList . size ( ) > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private boolean IgnoreinRange ( int i ) { WARNING we do not have signed / unsigned info available if ( this . basetype == DataType . ENUM1 && ( i > = Byte . MIN_VALUE || i < = UBYTE_MAX )) return true ; else if ( this . basetype == DataType . ENUM2 && ( i > = Short . MIN_VALUE || i < = USHORT_MAX )) return true ; else if ( this . basetype == DataType . ENUM4 ) // always ok return true ; else return false ; } [CODESPLIT] public String lookupEnumString ( int e ) { String result = map . get ( e ) ; return ( result == null ) ? \"Unknown enum value=\" + e : result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "String representation . [CODESPLIT] public String writeCDL ( boolean strict ) { Formatter out = new Formatter ( ) ; writeCDL ( out , new Indent ( 2 ) , strict ) ; return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize the stationHelper . [CODESPLIT] @ Override protected StationHelper createStationHelper ( ) throws IOException { // read in all the stations with the \"stations\" query StationHelper stationHelper = new StationHelper ( ) ; try ( InputStream in = CdmRemote . sendQuery ( null , uri , \"req=stations\" ) ) { PointStream . MessageType mtype = PointStream . readMagic ( in ) ; if ( mtype != PointStream . MessageType . StationList ) { throw new RuntimeException ( \"Station Request: bad response\" ) ; } int len = NcStream . readVInt ( in ) ; byte [ ] b = new byte [ len ] ; NcStream . readFully ( in , b ) ; PointStreamProto . StationList stationsp = PointStreamProto . StationList . parseFrom ( b ) ; for ( ucar . nc2 . ft . point . remote . PointStreamProto . Station sp : stationsp . getStationsList ( ) ) { //        Station s = new StationImpl(sp.getId(), sp.getDesc(), sp.getWmoId(), sp.getLat(), sp.getLon(), sp.getAlt()); stationHelper . addStation ( new StationFeatureStream ( null , null ) ) ; // LOOK WRONG } return stationHelper ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "StationTimeSeriesFeatureCollection [CODESPLIT] @ Override public StationTimeSeriesFeatureCollection subset ( List < StationFeature > stations ) throws IOException { if ( stations == null ) return this ; //    List<StationFeature> subset = getStationHelper().getStationFeatures(stations); return new Subset ( this , null , null ) ; // LOOK WRONG }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NestedPointFeatureCollection [CODESPLIT] @ Override public PointFeatureCollection flatten ( LatLonRect boundingBox , CalendarDateRange dateRange ) throws IOException { //boolean restrictedList = false; //QueryMaker queryMaker = restrictedList ? new QueryByStationList() : null; PointFeatureCollection pfc = new PointCollectionStreamRemote ( uri , getTimeUnit ( ) , getAltUnits ( ) , null ) ; return pfc . subset ( boundingBox , dateRange ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate this ResultService object . Return true if valid false if invalid . [CODESPLIT] protected boolean validate ( StringBuilder out ) { this . isValid = true ; // If log from construction has content, append to validation output msg. if ( this . log . length ( ) > 0 ) { out . append ( this . log ) ; } // Check that 'accessPointHeader' attribute is not null. if ( this . getAccessPointHeader ( ) == null ) { this . isValid = false ; out . append ( \" ** ResultService (1): a null 'accessPointHeader' is invalid.\" ) ; } return ( this . isValid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double g = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double kPrime = Math . sqrt ( 2 / ( 1 + g ) ) ; toX = R * kPrime * Math . cos ( fromLat ) * Math . sin ( lonDiff ) + falseEasting ; toY = R * kPrime * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) + falseNorthing ; result . setLocation ( toX , toY ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double g = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double kPrime = Math . sqrt ( 2 / ( 1 + g ) ) ; toX = R * kPrime * Math . cos ( fromLat ) * Math . sin ( lonDiff ) + falseEasting ; toY = R * kPrime * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) + falseNorthing ; resultXA [ i ] = ( float ) toX ; resultYA [ i ] = ( float ) toY ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { int cnt = from [ 0 ] . length ; float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] toLatA = to [ INDEX_LAT ] ; float [ ] toLonA = to [ INDEX_LON ] ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] ; double fromY = fromYA [ i ] ; fromX = fromX - falseEasting ; fromY = fromY - falseNorthing ; double rho = Math . sqrt ( fromX * fromX + fromY * fromY ) ; double c = 2 * Math . asin ( rho / ( 2 * R ) ) ; toLon = lon0 ; double temp = 0 ; if ( Math . abs ( rho ) > TOLERANCE ) { toLat = Math . asin ( Math . cos ( c ) * sinLat0 + ( fromY * Math . sin ( c ) * cosLat0 / rho ) ) ; if ( Math . abs ( lat0 - PI_OVER_4 ) > TOLERANCE ) { // not 90 or -90\r temp = rho * cosLat0 * Math . cos ( c ) - fromY * sinLat0 * Math . sin ( c ) ; toLon = lon0 + Math . atan ( fromX * Math . sin ( c ) / temp ) ; } else if ( Double . compare ( lat0 , PI_OVER_4 ) == 0 ) { toLon = lon0 + Math . atan ( fromX / - fromY ) ; temp = - fromY ; } else { toLon = lon0 + Math . atan ( fromX / fromY ) ; temp = fromY ; } } else { toLat = lat0 ; } toLat = Math . toDegrees ( toLat ) ; toLon = Math . toDegrees ( toLon ) ; if ( temp < 0 ) { toLon += 180 ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; toLatA [ i ] = ( float ) toLat ; toLonA [ i ] = ( float ) toLon ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the azimuth in degrees [CODESPLIT] public float getAzimuth ( ) { if ( message_type != 1 ) return - 1.0f ; if ( Cinrad2IOServiceProvider . isSC ) return 360.0f * azimuth_ang / 65536.0f ; else if ( Cinrad2IOServiceProvider . isCC ) return 360.0f * azimuth_ang / 512.0f ; else if ( Cinrad2IOServiceProvider . isCC20 ) return azimuth_ang * 0.01f ; return 180.0f * azimuth_ang / 32768.0f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the elevation angle in degrees [CODESPLIT] public float getElevation ( ) { if ( message_type != 1 ) return - 1.0f ; if ( Cinrad2IOServiceProvider . isSC ) return 120.0f * elevation_ang / 65536.0f ; else if ( Cinrad2IOServiceProvider . isCC ) return elevation_ang * 0.01f ; else if ( Cinrad2IOServiceProvider . isCC20 ) return elevation_ang * 0.01f ; return 180.0f * elevation_ang / 32768.0f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unidata added [CODESPLIT] public Date [ ] getTimes ( ) { if ( myRYIBs == null ) return null ; Date [ ] times = new Date [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) times [ i ] = myRYIBs [ i ] . getRayTime ( ) ; return times ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array of per - ray latitudes . If we do not have per - ray position information null is returned . [CODESPLIT] public float [ ] getLatitudes ( ) { if ( myASIBs == null ) return null ; float [ ] lats = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) lats [ i ] = myASIBs [ i ] . getLatitude ( ) ; return lats ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array of per - ray longitudes . If we do not have per - ray position information null is returned . [CODESPLIT] public float [ ] getLongitudes ( ) { if ( myASIBs == null ) return null ; float [ ] lons = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) lons [ i ] = myASIBs [ i ] . getLongitude ( ) ; return lons ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array of per - ray altitudes . If we do not have per - ray position information null is returned . [CODESPLIT] public float [ ] getAltitudes ( ) { if ( myASIBs == null ) return null ; float [ ] alts = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) alts [ i ] = myASIBs [ i ] . getAltitude ( ) ; return alts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array of azimuths for this sweep . [CODESPLIT] public float [ ] getAzimuths ( ) { if ( azimuths == null ) { azimuths = new float [ nRays ] ; for ( int r = 0 ; r < nRays ; r ++ ) { azimuths [ r ] = myRYIBs [ r ] . getAzimuth ( ) ; } } return azimuths ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the array of elevations for this sweep . [CODESPLIT] public float [ ] getElevations ( ) { if ( elevations == null ) { elevations = new float [ nRays ] ; for ( int r = 0 ; r < nRays ; r ++ ) { elevations [ r ] = myRYIBs [ r ] . getElevation ( ) ; } } return elevations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a subset of the Structure consisting only of the given member variables [CODESPLIT] public Structure select ( List < String > memberNames ) { Structure result = ( Structure ) copy ( ) ; List < Variable > members = new ArrayList <> ( ) ; for ( String name : memberNames ) { Variable m = findVariable ( name ) ; if ( null != m ) members . add ( m ) ; } result . setMemberVariables ( members ) ; result . isSubset = true ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a subset of the Structure consisting only of the one member variable [CODESPLIT] public Structure select ( String varName ) { List < String > memberNames = new ArrayList <> ( 1 ) ; memberNames . add ( varName ) ; return select ( memberNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a member variable [CODESPLIT] public Variable addMemberVariable ( Variable v ) { if ( isImmutable ( ) ) throw new IllegalStateException ( \"Cant modify\" ) ; members . add ( v ) ; memberHash . put ( v . getShortName ( ) , v ) ; v . setParentStructure ( this ) ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the list of member variables . [CODESPLIT] public void setMemberVariables ( List < Variable > vars ) { if ( isImmutable ( ) ) throw new IllegalStateException ( \"Cant modify\" ) ; members = new ArrayList <> ( ) ; memberHash = new HashMap <> ( 2 * vars . size ( ) ) ; for ( Variable v : vars ) { addMemberVariable ( v ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a Variable : uses the Variable name to find it . [CODESPLIT] public boolean removeMemberVariable ( Variable v ) { if ( isImmutable ( ) ) throw new IllegalStateException ( \"Cant modify\" ) ; if ( v == null ) return false ; //smembers = null; java . util . Iterator < Variable > iter = members . iterator ( ) ; while ( iter . hasNext ( ) ) { Variable mv = iter . next ( ) ; if ( mv . getShortName ( ) . equals ( v . getShortName ( ) ) ) { iter . remove ( ) ; memberHash . remove ( v . getShortName ( ) ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace a Variable with another that has the same name : uses the variable name to find it . If old Var is not found just add the new one [CODESPLIT] public boolean replaceMemberVariable ( Variable newVar ) { if ( isImmutable ( ) ) throw new IllegalStateException ( \"Cant modify\" ) ; //smembers = null; boolean found = false ; for ( int i = 0 ; i < members . size ( ) ; i ++ ) { Variable v = members . get ( i ) ; if ( v . getShortName ( ) == null ) System . out . println ( \"BAD null short name\" ) ; // E:/work/ghansham/iasi_20110513_045057_metopa_23676_eps_o.l1_bufr if ( v . getShortName ( ) . equals ( newVar . getShortName ( ) ) ) { members . set ( i , newVar ) ; found = true ; } } if ( ! found ) members . add ( newVar ) ; return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the parent group of this Structure and all member variables . [CODESPLIT] @ Override public void setParentGroup ( Group group ) { if ( isImmutable ( ) ) throw new IllegalStateException ( \"Cant modify\" ) ; super . setParentGroup ( group ) ; if ( members != null ) { for ( Variable v : members ) { v . setParentGroup ( group ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the Variable member with the specified ( short ) name . [CODESPLIT] public Variable findVariable ( String shortName ) { if ( shortName == null ) return null ; return memberHash . get ( shortName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a StructureMembers object that describes this Structure . CAUTION : Do not use for iterating over a StructureData or ArrayStructure - get the StructureMembers object directly from the StructureData or ArrayStructure . [CODESPLIT] public StructureMembers makeStructureMembers ( ) { StructureMembers smembers = new StructureMembers ( getShortName ( ) ) ; for ( Variable v2 : getVariables ( ) ) { StructureMembers . Member m = smembers . addMember ( v2 . getShortName ( ) , v2 . getDescription ( ) , v2 . getUnitsString ( ) , v2 . getDataType ( ) , v2 . getShape ( ) ) ; if ( v2 instanceof Structure ) m . setStructureMembers ( ( ( Structure ) v2 ) . makeStructureMembers ( ) ) ; } return smembers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force recalculation of size of one element of this structure - equals the sum of sizes of its members . This is used only by low level classes like IOSPs . [CODESPLIT] public void calcElementSize ( ) { int total = 0 ; for ( Variable v : members ) { total += v . getElementSize ( ) * v . getSize ( ) ; } elementSize = total ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this when this is a scalar Structure . Its the same as read () but it extracts the single StructureData out of the Array . [CODESPLIT] public StructureData readStructure ( ) throws IOException { if ( getRank ( ) != 0 ) throw new java . lang . UnsupportedOperationException ( \"not a scalar structure\" ) ; Array dataArray = read ( ) ; ArrayStructure data = ( ArrayStructure ) dataArray ; return data . getStructureData ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this when this is a one dimensional array of Structures or you are doing the index calculation yourself for a multidimension array . This will read only the ith structure and return the data as a StructureData object . [CODESPLIT] public StructureData readStructure ( int index ) throws IOException , ucar . ma2 . InvalidRangeException { Section section = null ; // works for scalars i think if ( getRank ( ) == 1 ) { section = new Section ( ) . appendRange ( index , index ) ; } else if ( getRank ( ) > 1 ) { Index ii = Index . factory ( shape ) ; // convert to nD index ii . setCurrentCounter ( index ) ; int [ ] origin = ii . getCurrentCounter ( ) ; section = new Section ( ) ; for ( int anOrigin : origin ) section . appendRange ( anOrigin , anOrigin ) ; } Array dataArray = read ( section ) ; ArrayStructure data = ( ArrayStructure ) dataArray ; return data . getStructureData ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For rank 1 array of Structures read count Structures and return the data as an ArrayStructure . Use only when this is a one dimensional array of Structures . [CODESPLIT] public ArrayStructure readStructure ( int start , int count ) throws IOException , ucar . ma2 . InvalidRangeException { if ( getRank ( ) != 1 ) throw new java . lang . UnsupportedOperationException ( \"not a vector structure\" ) ; int [ ] origin = new int [ ] { start } ; int [ ] shape = new int [ ] { count } ; if ( NetcdfFile . debugStructureIterator ) System . out . println ( \"readStructure \" + start + \" \" + count ) ; return ( ArrayStructure ) read ( origin , shape ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an efficient iterator over all the data in the Structure . [CODESPLIT] public StructureDataIterator getStructureIterator ( int bufferSize ) throws java . io . IOException { return ( getRank ( ) < 2 ) ? new Structure . IteratorRank1 ( bufferSize ) : new Structure . Iterator ( bufferSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get String with name and attributes . Used in short descriptions like tooltips . [CODESPLIT] public String getNameAndAttributes ( ) { Formatter sbuff = new Formatter ( ) ; sbuff . format ( \"Structure \" ) ; getNameAndDimensions ( sbuff , false , true ) ; sbuff . format ( \"%n\" ) ; for ( Attribute att : attributes . getAttributes ( ) ) { sbuff . format ( \"  %s:%s;%n\" , getShortName ( ) , att . toString ( ) ) ; } return sbuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * <BUFR_19_1_1_TableA_en > <No > 27< / No > <CodeFigure > 28< / CodeFigure > <Meaning_en > Precision orbit ( satellite ) < / Meaning_en > <Status > Operational< / Status > < / BUFR_19_1_1_TableA_en > [CODESPLIT] static private void init ( ) { String filename = BufrTables . RESOURCE_PATH + TABLEA_FILENAME ; try ( InputStream is = CodeFlagTables . class . getResourceAsStream ( filename ) ) { HashMap < Integer , String > map = new HashMap <> ( 100 ) ; SAXBuilder builder = new SAXBuilder ( ) ; org . jdom2 . Document tdoc = builder . build ( is ) ; org . jdom2 . Element root = tdoc . getRootElement ( ) ; List < Element > elems = root . getChildren ( ) ; for ( Element elem : elems ) { String line = elem . getChildText ( \"No\" ) ; String codeS = elem . getChildText ( \"CodeFigure\" ) ; String desc = elem . getChildText ( \"Meaning_en\" ) ; try { int code = Integer . parseInt ( codeS ) ; map . put ( code , desc ) ; } catch ( NumberFormatException e ) { log . debug ( \"NumberFormatException on line \" + line + \" in \" + codeS ) ; } } tableA = map ; } catch ( Exception e ) { log . error ( \"Can't read BUFR code table \" + filename , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "data category name from table A [CODESPLIT] static public String getDataCategory ( int cat ) { if ( tableA == null ) init ( ) ; String result = tableA . get ( cat ) ; return result != null ? result : \"Unknown category=\" + cat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the name of the type of the projection . [CODESPLIT] public String getClassName ( ) { String className = getClass ( ) . getName ( ) ; int index = className . lastIndexOf ( \".\" ) ; if ( index >= 0 ) { className = className . substring ( index + 1 ) ; } return className ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an attribute to this projection [CODESPLIT] protected void addParameter ( String name , String value ) { atts . add ( new Parameter ( name , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a header for display . [CODESPLIT] public static String getHeader ( ) { StringBuilder headerB = new StringBuilder ( 60 ) ; headerB . append ( \"Name\" ) ; Format . tab ( headerB , 20 , true ) ; headerB . append ( \"Class\" ) ; Format . tab ( headerB , 40 , true ) ; headerB . append ( \"Parameters\" ) ; return headerB . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public double [ ] [ ] projToLatLon ( double [ ] [ ] from , double [ ] [ ] to ) { if ( ( from == null ) || ( from . length != 2 ) ) { throw new IllegalArgumentException ( \"ProjectionImpl.projToLatLon:\" + \"null array argument or wrong dimension (from)\" ) ; } if ( ( to == null ) || ( to . length != 2 ) ) { throw new IllegalArgumentException ( \"ProjectionImpl.projToLatLon:\" + \"null array argument or wrong dimension (to)\" ) ; } if ( from [ 0 ] . length != to [ 0 ] . length ) { throw new IllegalArgumentException ( \"ProjectionImpl.projToLatLon:\" + \"from array not same length as to array\" ) ; } for ( int i = 0 ; i < from [ 0 ] . length ; i ++ ) { LatLonPoint endL = projToLatLon ( from [ 0 ] [ i ] , from [ 1 ] [ i ] ) ; to [ 0 ] [ i ] = endL . getLatitude ( ) ; to [ 1 ] [ i ] = endL . getLongitude ( ) ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { if ( ( from == null ) || ( from . length != 2 ) ) { throw new IllegalArgumentException ( \"ProjectionImpl.projToLatLon:\" + \"null array argument or wrong dimension (from)\" ) ; } if ( ( to == null ) || ( to . length != 2 ) ) { throw new IllegalArgumentException ( \"ProjectionImpl.projToLatLon:\" + \"null array argument or wrong dimension (to)\" ) ; } if ( from [ 0 ] . length != to [ 0 ] . length ) { throw new IllegalArgumentException ( \"ProjectionImpl.projToLatLon:\" + \"from array not same length as to array\" ) ; } ProjectionPointImpl ppi = new ProjectionPointImpl ( ) ; LatLonPointImpl llpi = new LatLonPointImpl ( ) ; for ( int i = 0 ; i < from [ 0 ] . length ; i ++ ) { ppi . setLocation ( ( double ) from [ 0 ] [ i ] , ( double ) from [ 1 ] [ i ] ) ; projToLatLon ( ppi , llpi ) ; to [ 0 ] [ i ] = ( float ) llpi . getLatitude ( ) ; to [ 1 ] [ i ] = ( float ) llpi . getLongitude ( ) ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , int latIndex , int lonIndex ) { return latLonToProj ( from , new float [ 2 ] [ from [ 0 ] . length ] , latIndex , lonIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { //      ucar.unidata.util.Misc.printStack (\"latLonToProj-\" + this + \" size=\" + from[0].length, 4, null);\r if ( ( from == null ) || ( from . length != 2 ) ) { throw new IllegalArgumentException ( \"ProjectionImpl.latLonToProj:\" + \"null array argument or wrong dimension (from)\" ) ; } if ( ( to == null ) || ( to . length != 2 ) ) { throw new IllegalArgumentException ( \"ProjectionImpl.latLonToProj:\" + \"null array argument or wrong dimension (to)\" ) ; } if ( from [ 0 ] . length != to [ 0 ] . length ) { throw new IllegalArgumentException ( \"ProjectionImpl.latLonToProj:\" + \"from array not same length as to array\" ) ; } ProjectionPointImpl ppi = new ProjectionPointImpl ( ) ; LatLonPointImpl llpi = new LatLonPointImpl ( ) ; for ( int i = 0 ; i < from [ 0 ] . length ; i ++ ) { llpi . setLatitude ( from [ latIndex ] [ i ] ) ; llpi . setLongitude ( from [ lonIndex ] [ i ] ) ; latLonToProj ( llpi , ppi ) ; to [ 0 ] [ i ] = ( float ) ppi . getX ( ) ; to [ 1 ] [ i ] = ( float ) ppi . getY ( ) ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Alternate way to calculate latLonToProjBB originally in GridCoordSys . Difficult to do this in a general way . [CODESPLIT] ProjectionRect latLonToProjBB2 ( LatLonRect latlonRect ) { double minx , maxx , miny , maxy ; LatLonPointImpl llpt = latlonRect . getLowerLeftPoint ( ) ; LatLonPointImpl urpt = latlonRect . getUpperRightPoint ( ) ; LatLonPointImpl lrpt = latlonRect . getLowerRightPoint ( ) ; LatLonPointImpl ulpt = latlonRect . getUpperLeftPoint ( ) ; if ( isLatLon ( ) ) { minx = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; miny = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; maxx = getMinOrMaxLon ( urpt . getLongitude ( ) , lrpt . getLongitude ( ) , false ) ; maxy = Math . min ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; } else { ProjectionPoint ll = latLonToProj ( llpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint ur = latLonToProj ( urpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint lr = latLonToProj ( lrpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint ul = latLonToProj ( ulpt , new ProjectionPointImpl ( ) ) ; minx = Math . min ( ll . getX ( ) , ul . getX ( ) ) ; miny = Math . min ( ll . getY ( ) , lr . getY ( ) ) ; maxx = Math . max ( ur . getX ( ) , lr . getX ( ) ) ; maxy = Math . max ( ul . getY ( ) , ur . getY ( ) ) ; } return new ProjectionRect ( minx , miny , maxx , maxy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a lat / lon bounding box to a world coordinate bounding box by finding the minimum enclosing box . Handles lat / lon points that do not intersect the projection panel . [CODESPLIT] public ProjectionRect latLonToProjBB ( LatLonRect latlonRect ) { if ( isLatLon ) { LatLonProjection llp = ( LatLonProjection ) this ; llp . setCenterLon ( latlonRect . getCenterLon ( ) ) ; // LOOK side effect BAD !!\r } ProjectionPointImpl w1 = new ProjectionPointImpl ( ) ; ProjectionPointImpl w2 = new ProjectionPointImpl ( ) ; LatLonPoint ll = latlonRect . getLowerLeftPoint ( ) ; LatLonPoint ur = latlonRect . getUpperRightPoint ( ) ; latLonToProj ( ll , w1 ) ; latLonToProj ( ur , w2 ) ; //if (!isLatLon && crossSeam(w1, w2)) {\r //  log.warn(\"CROSS SEAM failure=\" + w1 + \" \" + w2+\" for \"+this, new Throwable());\r //}\r // make bounding box out of those two corners\r ProjectionRect world = new ProjectionRect ( w1 . getX ( ) , w1 . getY ( ) , w2 . getX ( ) , w2 . getY ( ) ) ; LatLonPointImpl la = new LatLonPointImpl ( ) ; LatLonPointImpl lb = new LatLonPointImpl ( ) ; // now extend if needed to the other two corners\r la . setLatitude ( ur . getLatitude ( ) ) ; la . setLongitude ( ll . getLongitude ( ) ) ; latLonToProj ( la , w1 ) ; world . add ( w1 ) ; lb . setLatitude ( ll . getLatitude ( ) ) ; lb . setLongitude ( ur . getLongitude ( ) ) ; latLonToProj ( lb , w2 ) ; world . add ( w2 ) ; return world ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a world coordinate bounding box to a lat / lon bounding box by finding the minimum enclosing box . [CODESPLIT] public LatLonRect projToLatLonBBold ( ProjectionRect world ) { //System.out.println(\"world = \" + world);\r ProjectionPoint min = world . getMinPoint ( ) ; ProjectionPoint max = world . getMaxPoint ( ) ; //System.out.println(\"min = \" + min);\r //System.out.println(\"max = \" + max);\r LatLonRect llbb ; LatLonPointImpl llmin = new LatLonPointImpl ( ) ; LatLonPointImpl llmax = new LatLonPointImpl ( ) ; // make bounding box out of the min, max corners\r projToLatLon ( min , llmin ) ; projToLatLon ( max , llmax ) ; llbb = new LatLonRect ( llmin , llmax ) ; //System.out.println(\"llbb = \" + llbb);\r /*\r\n   double lona = la.getLongitude();\r\n   double lonb = lb.getLongitude();\r\n\r\n   if (((lona < lonb) && (lonb - lona <= 180.0))\r\n           || ((lona > lonb) && (lona - lonb >= 180.0))) {\r\n       llbb = new LatLonRect(la, lb);\r\n   } else {\r\n       llbb = new LatLonRect(lb, la);\r\n   } */ ProjectionPointImpl w1 = new ProjectionPointImpl ( ) ; ProjectionPointImpl w2 = new ProjectionPointImpl ( ) ; // now extend if needed using the other two corners\r w1 . setLocation ( min . getX ( ) , max . getY ( ) ) ; projToLatLon ( w1 , llmin ) ; llbb . extend ( llmin ) ; w2 . setLocation ( max . getX ( ) , min . getY ( ) ) ; projToLatLon ( w2 , llmax ) ; llbb . extend ( llmax ) ; return llbb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute lat / lon bounding box from projection bounding box by finding the minimum enclosing box . [CODESPLIT] public LatLonRect projToLatLonBB ( ProjectionRect bb ) { // look at all 4 corners of the bounding box\r LatLonPoint llpt = projToLatLon ( bb . getLowerLeftPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPoint lrpt = projToLatLon ( bb . getLowerRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPoint urpt = projToLatLon ( bb . getUpperRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPoint ulpt = projToLatLon ( bb . getUpperLeftPoint ( ) , new LatLonPointImpl ( ) ) ; // Check if grid contains poles.\r boolean includesNorthPole = false ; /* int[] resultNP;\r\n    findXYindexFromLatLon(90.0, 0, resultNP);\r\n    if (resultNP[0] != -1 && resultNP[1] != -1)\r\n      includesNorthPole = true;      */ boolean includesSouthPole = false ; /* int[] resultSP = new int[2];\r\n    findXYindexFromLatLon(-90.0, 0, resultSP);\r\n    if (resultSP[0] != -1 && resultSP[1] != -1)\r\n      includesSouthPole = true; */ LatLonRect llbb ; if ( includesNorthPole && ! includesSouthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( 90.0 , 0.0 ) ) ; // ??? lon=???\r llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; // OR\r //llbb.extend( new LatLonRect( llpt, lrpt ));\r //llbb.extend( new LatLonRect( lrpt, urpt ) );\r //llbb.extend( new LatLonRect( urpt, ulpt ) );\r //llbb.extend( new LatLonRect( ulpt, llpt ) );\r } else if ( includesSouthPole && ! includesNorthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( - 90.0 , - 180.0 ) ) ; // ??? lon=???\r llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; } else { double latMin = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; double latMax = Math . max ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; // longitude is a bit tricky as usual\r double lonMin = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; double lonMax = getMinOrMaxLon ( lrpt . getLongitude ( ) , urpt . getLongitude ( ) , false ) ; LatLonPointImpl min = new LatLonPointImpl ( latMin , lonMin ) ; LatLonPointImpl max = new LatLonPointImpl ( latMax , lonMax ) ; llbb = new LatLonRect ( min , max ) ; } return llbb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For negative angles d should be negative m & s positive . [CODESPLIT] public static double dmsToRad ( double d , double m , double s ) { if ( d >= 0 ) return ( d + m / 60 + s / 3600 ) * Math . PI / 180.0 ; return ( d - m / 60 - s / 3600 ) * Math . PI / 180.0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For negative angles d should be negative m & s positive . [CODESPLIT] public static double dmsToDeg ( double d , double m , double s ) { if ( d >= 0 ) return ( d + m / 60 + s / 3600 ) ; return ( d - m / 60 - s / 3600 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public static void latLongToXYZ ( ProjectionPoint ll Point3D xyz ) { double c = Math . cos ( ll . y ) ; xyz . x = c * Math . cos ( ll . x ) ; xyz . y = c * Math . sin ( ll . x ) ; xyz . z = Math . sin ( ll . y ) ; } [CODESPLIT] public static double greatCircleDistance ( double lon1 , double lat1 , double lon2 , double lat2 ) { double dlat = Math . sin ( ( lat2 - lat1 ) / 2 ) ; double dlon = Math . sin ( ( lon2 - lon1 ) / 2 ) ; double r = Math . sqrt ( dlat * dlat + Math . cos ( lat1 ) * Math . cos ( lat2 ) * dlon * dlon ) ; return 2.0 * Math . asin ( r ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Java translation of Nice Numbers for Graph Labels by Paul Heckbert from Graphics Gems Academic Press 1990 [CODESPLIT] public static double niceNumber ( double x , boolean round ) { int expv ; /* exponent of x */ double f ; /* fractional part of x */ double nf ; /* nice, rounded fraction */ expv = ( int ) Math . floor ( Math . log ( x ) / Math . log ( 10 ) ) ; f = x / Math . pow ( 10. , expv ) ; /* between 1 and 10 */ if ( round ) { if ( f < 1.5 ) nf = 1. ; else if ( f < 3. ) nf = 2. ; else if ( f < 7. ) nf = 5. ; else nf = 10. ; } else if ( f <= 1. ) nf = 1. ; else if ( f <= 2. ) nf = 2. ; else if ( f <= 5. ) nf = 5. ; else nf = 10. ; return nf * Math . pow ( 10. , expv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "shared by all instances [CODESPLIT] protected VertCoordType getLevelType ( int code ) { VertCoordType result = wmoTable3 . get ( code ) ; if ( result == null ) result = new VertCoordType ( code , \"unknownLayer\" + code , null , \"unknownLayer\" + code , null , false , false ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get which CF version this is ie CF - 1 . x [CODESPLIT] public static int getVersion ( String hasConvName ) { int result = extractVersion ( hasConvName ) ; if ( result >= 0 ) return result ; List < String > names = breakupConventionNames ( hasConvName ) ; for ( String name : names ) { result = extractVersion ( name ) ; if ( result >= 0 ) return result ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Guess the value of ZisPositive based on z axis name and units [CODESPLIT] public static String getZisPositive ( String zaxisName , String vertCoordUnits ) { if ( vertCoordUnits == null ) return CF . POSITIVE_UP ; if ( vertCoordUnits . isEmpty ( ) ) return CF . POSITIVE_UP ; if ( SimpleUnit . isCompatible ( \"millibar\" , vertCoordUnits ) ) return CF . POSITIVE_DOWN ; if ( SimpleUnit . isCompatible ( \"m\" , vertCoordUnits ) ) return CF . POSITIVE_UP ; // dunno - make it up\r return CF . POSITIVE_UP ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this is here because it doesnt fit into the 3D array thing . [CODESPLIT] private void makeAtmLnCoordinate ( NetcdfDataset ds , Variable v ) { // get the formula attribute\r String formula = ds . findAttValueIgnoreCase ( v , CF . formula_terms , null ) ; if ( null == formula ) { String msg = \" Need attribute 'formula_terms' on Variable \" + v . getFullName ( ) + \"\\n\" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; return ; } // parse the formula string\r Variable p0Var = null , levelVar = null ; StringTokenizer stoke = new StringTokenizer ( formula , \" :\" ) ; while ( stoke . hasMoreTokens ( ) ) { String toke = stoke . nextToken ( ) ; if ( toke . equalsIgnoreCase ( \"p0\" ) ) { String name = stoke . nextToken ( ) ; p0Var = ds . findVariable ( name ) ; } else if ( toke . equalsIgnoreCase ( \"lev\" ) ) { String name = stoke . nextToken ( ) ; levelVar = ds . findVariable ( name ) ; } } if ( null == p0Var ) { String msg = \" Need p0:varName on Variable \" + v . getFullName ( ) + \" formula_terms\\n\" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; return ; } if ( null == levelVar ) { String msg = \" Need lev:varName on Variable \" + v . getFullName ( ) + \" formula_terms\\n\" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; return ; } String units = ds . findAttValueIgnoreCase ( p0Var , CDM . UNITS , \"hPa\" ) ; // create the data and the variable\r try { // p(k) = p0 * exp(-lev(k))\r double p0 = p0Var . readScalarDouble ( ) ; Array levelData = levelVar . read ( ) ; Array pressureData = Array . factory ( DataType . DOUBLE , levelData . getShape ( ) ) ; IndexIterator ii = levelData . getIndexIterator ( ) ; IndexIterator iip = pressureData . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) { double val = p0 * Math . exp ( - 1.0 * ii . getDoubleNext ( ) ) ; iip . setDoubleNext ( val ) ; } CoordinateAxis1D p = new CoordinateAxis1D ( ds , null , v . getShortName ( ) + \"_pressure\" , DataType . DOUBLE , levelVar . getDimensionsString ( ) , units , \"Vertical Pressure coordinate synthesized from atmosphere_ln_pressure_coordinate formula\" ) ; p . setCachedData ( pressureData , false ) ; p . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Pressure . toString ( ) ) ) ; p . addAttribute ( new Attribute ( _Coordinate . AliasForDimension , p . getDimensionsString ( ) ) ) ; ds . addVariable ( null , p ) ; parseInfo . format ( \" added Vertical Pressure coordinate %s from CF-1 %s%n\" , p . getFullName ( ) , CF . atmosphere_ln_pressure_coordinate ) ; } catch ( IOException e ) { String msg = \" Unable to read variables from \" + v . getFullName ( ) + \" formula_terms\\n\" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Augment COARDS axis type identification with Standard names ( including dimensionless vertical coordinates ) and CF . AXIS attributes [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ncDataset , VariableEnhanced v ) { // standard names for unitless vertical coords\r String sname = ncDataset . findAttValueIgnoreCase ( ( Variable ) v , CF . STANDARD_NAME , null ) ; if ( sname != null ) { sname = sname . trim ( ) ; for ( String vertical_coord : vertical_coords ) if ( sname . equalsIgnoreCase ( vertical_coord ) ) return AxisType . GeoZ ; } // COARDS - check units\r AxisType at = super . getAxisType ( ncDataset , v ) ; if ( at != null ) return at ; // standard names for X, Y : bug in CDO putting wrong standard name, so check units first (!)\r if ( sname != null ) { if ( sname . equalsIgnoreCase ( CF . ENSEMBLE ) ) return AxisType . Ensemble ; if ( sname . equalsIgnoreCase ( CF . LATITUDE ) ) return AxisType . Lat ; if ( sname . equalsIgnoreCase ( CF . LONGITUDE ) ) return AxisType . Lon ; if ( sname . equalsIgnoreCase ( CF . PROJECTION_X_COORDINATE ) || sname . equalsIgnoreCase ( CF . GRID_LONGITUDE ) || sname . equalsIgnoreCase ( \"rotated_longitude\" ) ) return AxisType . GeoX ; if ( sname . equalsIgnoreCase ( CF . PROJECTION_Y_COORDINATE ) || sname . equalsIgnoreCase ( CF . GRID_LATITUDE ) || sname . equalsIgnoreCase ( \"rotated_latitude\" ) ) return AxisType . GeoY ; if ( sname . equalsIgnoreCase ( CF . TIME_REFERENCE ) ) return AxisType . RunTime ; if ( sname . equalsIgnoreCase ( CF . TIME_OFFSET ) ) return AxisType . TimeOffset ; } // check axis attribute - only for X, Y, Z\r String axis = ncDataset . findAttValueIgnoreCase ( ( Variable ) v , CF . AXIS , null ) ; if ( axis != null ) { axis = axis . trim ( ) ; String unit = v . getUnitsString ( ) ; if ( axis . equalsIgnoreCase ( \"X\" ) ) { if ( SimpleUnit . isCompatible ( \"m\" , unit ) ) return AxisType . GeoX ; } else if ( axis . equalsIgnoreCase ( \"Y\" ) ) { if ( SimpleUnit . isCompatible ( \"m\" , unit ) ) return AxisType . GeoY ; } else if ( axis . equalsIgnoreCase ( \"Z\" ) ) { if ( unit == null ) return AxisType . GeoZ ; if ( SimpleUnit . isCompatible ( \"m\" , unit ) ) return AxisType . Height ; else if ( SimpleUnit . isCompatible ( \"mbar\" , unit ) ) return AxisType . Pressure ; else return AxisType . GeoZ ; } } if ( avhrr_oiv2 ) { if ( v . getShortName ( ) . equals ( \"zlev\" ) ) return AxisType . Height ; } try { String units = v . getUnitsString ( ) ; CalendarDateUnit cd = CalendarDateUnit . of ( null , units ) ; if ( cd != null ) return AxisType . Time ; } catch ( Throwable t ) { // ignore\r } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove last file [CODESPLIT] public boolean delete ( ) { if ( nextFile == null ) return false ; fileList . remove ( nextFile ) ; File f = new File ( \"C:/tmp/deleted/\" + nextFile . getName ( ) ) ; return nextFile . renameTo ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * set the Grid [CODESPLIT] public DataState setCoverage ( CoverageCollection coverageDataset , Coverage grid ) { this . dataState = new DataState ( coverageDataset , grid ) ; this . lastGrid = null ; isNewField = true ; return this . dataState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get the data value at this projection ( x y ) point . [CODESPLIT] public String getXYvalueStr ( ProjectionPoint loc ) { if ( ( lastGrid == null ) || ( geodata == null ) ) return \"\" ; // convert to dataProjection, where x and y are orthogonal if ( ! sameProjection ) { LatLonPoint llpt = drawProjection . projToLatLon ( loc ) ; loc = dataProjection . latLonToProj ( llpt ) ; } // find the grid indexes HorizCoordSys hcs = lastGrid . getCoordSys ( ) . getHorizCoordSys ( ) ; Optional < HorizCoordSys . CoordReturn > opt = hcs . findXYindexFromCoord ( loc . getX ( ) , loc . getY ( ) ) ; // get value, construct the string if ( ! opt . isPresent ( ) ) return opt . getErrorMessage ( ) ; else { HorizCoordSys . CoordReturn cr = opt . get ( ) ; try { Index imaH = geodata . getIndex ( ) ; double dataValue = geodata . getDouble ( imaH . set ( cr . y , cr . x ) ) ; // int wantz = (geocs.getZAxis() == null) ? -1 : lastLevel; return makeXYZvalueStr ( dataValue , cr ) ; } catch ( Exception e ) { return \"error \" + cr . x + \" \" + cr . y ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * get an x y z data volume for the given time private void makeDataVolume ( GridDatatype g int time ) { try { dataVolume = g . readVolumeData ( time ) ; } catch ( java . io . IOException e ) { System . out . println ( Error reading netcdf file + e ) ; dataVolume = null ; } lastGrid = g ; lastTime = time ; lastLevel = - 1 ; // invalidate lastSlice = - 1 ; // invalidate dataVolumeChanged = true ; } [CODESPLIT] private GeoReferencedArray readHSlice ( int level , int time , int ensemble , int runtime ) { /* make sure x, y exists\n    CoverageCS gcs = useG.getCoordinateSystem();\n    CoordinateAxis xaxis = gcs.getXHorizAxis();\n    CoordinateAxis yaxis = gcs.getYHorizAxis();\n    if ((xaxis == null) || (yaxis == null))    // doesnt exist\n      return null;\n    if ((xaxis.getSize() <= 1) || (yaxis.getSize() <= 1)) // LOOK ??\n      return null;   */ // make sure we need new one if ( dataState . grid . equals ( lastGrid ) && ( time == lastTime ) && ( level == lastLevel ) && ( horizStride == lastStride ) && ( ensemble == lastEnsemble ) && ( runtime == lastRunTime ) ) return dataH ; // nothing changed // get the data slice //dataH = useG.readDataSlice(runtime, ensemble, time, level, -1, -1); SubsetParams subset = new SubsetParams ( ) ; if ( level >= 0 && dataState . zaxis != null ) { double levelVal = dataState . zaxis . getCoordMidpoint ( level ) ; subset . set ( SubsetParams . vertCoord , levelVal ) ; } if ( time >= 0 && dataState . taxis != null ) { double timeVal = dataState . taxis . getCoordMidpoint ( time ) ; CalendarDate date = dataState . taxis . makeDate ( timeVal ) ; subset . set ( SubsetParams . time , date ) ; } if ( runtime >= 0 && dataState . rtaxis != null ) { double rtimeVal = dataState . rtaxis . getCoordMidpoint ( runtime ) ; CalendarDate date = dataState . rtaxis . makeDate ( rtimeVal ) ; subset . set ( SubsetParams . runtime , date ) ; } if ( ensemble >= 0 && dataState . ensaxis != null ) { double ensVal = dataState . ensaxis . getCoordMidpoint ( ensemble ) ; subset . set ( SubsetParams . ensCoord , ensVal ) ; } if ( horizStride != 1 ) subset . setHorizStride ( horizStride ) ; try { dataH = dataState . grid . readData ( subset ) ; geodata = dataH . getData ( ) . reduce ( ) ; // get rid of n=1 dimensions } catch ( IOException | InvalidRangeException e ) { e . printStackTrace ( ) ; } lastGrid = dataState . grid ; lastTime = time ; lastLevel = level ; lastEnsemble = ensemble ; lastRunTime = runtime ; lastStride = horizStride ; /*\n    CoordinateAxis1D zaxis = gcs.getVerticalAxis();\n    if ((zaxis == null) || (zaxis.getSize() < 1)) {\n      dataH = dataVolume;  // volume is xy plane\n    } else {\n      dataH = dataVolume.slice(0, level);  // if z exists, always first (logical) dimension\n    }\n\n    if (debugArrayShape) {\n      System.out.println(\"Horiz shape = \");\n      for (int i = 0; i < dataH.getRank(); i++)\n        System.out.println(\"   shape = \" + dataH.getShape()[i]);\n    } */ return dataH ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set colorscale limits missing data [CODESPLIT] private void setColorScaleParams ( ) { if ( dataMinMaxType == ColorScale . MinMaxType . hold && ! isNewField ) return ; isNewField = false ; GeoReferencedArray dataArr = readHSlice ( wantLevel , wantTime , wantEnsemble , wantRunTime ) ; //else //  dataArr = makeVSlice(stridedGrid, wantSlice, wantTime, wantEnsemble, wantRunTime); if ( dataArr != null ) { MAMath . MinMax minmax = MAMath . getMinMaxSkipMissingData ( dataArr . getData ( ) , dataState . grid ) ; colorScale . setMinMax ( minmax . min , minmax . max ) ; colorScale . setGeoGrid ( dataState . grid ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do the rendering to the given Graphics2D object . [CODESPLIT] public void renderPlanView ( java . awt . Graphics2D g , AffineTransform dFromN ) { if ( ( dataState . grid == null ) || ( colorScale == null ) || ( drawProjection == null ) ) return ; if ( ! drawGrid && ! drawContours ) return ; // no anitaliasing g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; dataH = readHSlice ( wantLevel , wantTime , wantEnsemble , wantRunTime ) ; if ( dataH == null ) return ; setColorScaleParams ( ) ; if ( drawGrid ) drawGridHoriz ( g , dataH ) ; //if (drawContours) //  drawContours(g, dataH.transpose(0, 1), dFromN); if ( drawGridLines ) drawGridLines ( g , dataH ) ; if ( drawBB ) drawGridBB ( g , this . dataState . coverageDataset . getLatlonBoundingBox ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * draw using GeneralPath shape private GeneralPath gp = new GeneralPath ( GeneralPath . WIND_EVEN_ODD 5 ) ; private Shape makeShape ( double lon1 double lat1 double lon2 double lat2 ) { gp . reset () ; ProjectionPoint pt = drawProjection . latLonToProj ( lat1 lon1 ) ; gp . moveTo ( ( float ) pt . getX () ( float ) pt . getY () ) ; [CODESPLIT] private void drawGridHorizRegular ( java . awt . Graphics2D g , GeoReferencedArray array ) { int count = 0 ; CoverageCoordSys gsys = array . getCoordSysForData ( ) ; CoverageCoordAxis1D xaxis = ( CoverageCoordAxis1D ) gsys . getXAxis ( ) ; CoverageCoordAxis1D yaxis = ( CoverageCoordAxis1D ) gsys . getYAxis ( ) ; Array data = array . getData ( ) . reduce ( ) ; if ( data . getRank ( ) != 2 ) { System . out . printf ( \"drawGridHorizRegular Rank equals %d, must be 2%n\" , data . getRank ( ) ) ; return ; } int nx = xaxis . getNcoords ( ) ; int ny = yaxis . getNcoords ( ) ; //// drawing optimizations sameProjection = drawProjection . equals ( dataProjection ) ; if ( drawProjection . isLatLon ( ) ) { projectll = ( LatLonProjection ) drawProjection ; double centerLon = projectll . getCenterLon ( ) ; if ( Debug . isSet ( \"projection/LatLonShift\" ) ) System . out . println ( \"projection/LatLonShift: gridDraw = \" + centerLon ) ; } // find the most common color and fill the entire area with it colorScale . resetHist ( ) ; IndexIterator iiter = array . getData ( ) . getIndexIterator ( ) ; while ( iiter . hasNext ( ) ) { double val = iiter . getDoubleNext ( ) ; colorScale . getIndexFromValue ( val ) ; // accum in histogram } int modeColor = colorScale . getHistMax ( ) ; if ( debugMiss ) System . out . println ( \"mode = \" + modeColor + \" sameProj= \" + sameProjection ) ; if ( sameProjection ) { double xmin = Math . min ( xaxis . getCoordEdge1 ( 0 ) , xaxis . getCoordEdgeLast ( ) ) ; double xmax = Math . max ( xaxis . getCoordEdge1 ( 0 ) , xaxis . getCoordEdgeLast ( ) ) ; double ymin = Math . min ( yaxis . getCoordEdge1 ( 0 ) , yaxis . getCoordEdgeLast ( ) ) ; double ymax = Math . max ( yaxis . getCoordEdge1 ( 0 ) , yaxis . getCoordEdgeLast ( ) ) ; // pre color the drawing area with the most used color count += drawRect ( g , modeColor , xmin , ymin , xmax , ymax , drawProjection . isLatLon ( ) ) ; } else if ( useModeForProjections ) drawPathShape ( g , modeColor , xaxis , yaxis ) ; debugPts = Debug . isSet ( \"GridRenderer/showPts\" ) ; // draw individual rects with run length Index imaH = data . getIndex ( ) ; for ( int y = 0 ; y < ny ; y ++ ) { double ybeg = yaxis . getCoordEdge1 ( y ) ; double yend = yaxis . getCoordEdge2 ( y ) ; int thisColor , lastColor = 0 ; int run = 0 ; int xbeg = 0 ; for ( int x = 0 ; x < nx ; x ++ ) { double val = data . getDouble ( imaH . set ( y , x ) ) ; thisColor = colorScale . getIndexFromValue ( val ) ; if ( ( run == 0 ) || ( lastColor == thisColor ) ) { // same color - keep running run ++ ; } else { if ( sameProjection ) { if ( lastColor != modeColor ) // dont have to draw these count += drawRect ( g , lastColor , xaxis . getCoordEdge1 ( xbeg ) , ybeg , xaxis . getCoordEdge2 ( x ) , yend , drawProjection . isLatLon ( ) ) ; } else { if ( ! useModeForProjections || ( lastColor != modeColor ) ) // dont have to draw mode count += drawPathRun ( g , lastColor , ybeg , yend , xaxis , xbeg , x - 1 , debugPts ) ; } xbeg = x ; } lastColor = thisColor ; } // get the ones at the end if ( sameProjection ) { if ( lastColor != modeColor ) count += drawRect ( g , lastColor , xaxis . getCoordEdge1 ( xbeg ) , ybeg , xaxis . getCoordEdgeLast ( ) , yend , drawProjection . isLatLon ( ) ) ; } else { if ( ! useModeForProjections || ( lastColor != modeColor ) ) count += drawPathRun ( g , lastColor , ybeg , yend , xaxis , xbeg , nx - 1 , false ) ; // needed ? } // if (debugPts) break; } if ( debugHorizDraw ) System . out . println ( \"debugHorizDraw = \" + count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is this a child of that ? [CODESPLIT] boolean isChildOf ( H5Group that ) { if ( parent == null ) return false ; if ( parent == that ) return true ; return parent . isChildOf ( that ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the MessageType that matches this name . [CODESPLIT] public static MessageType getType ( String name ) { if ( name == null ) return null ; return hash . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a message [CODESPLIT] int read ( long filePos , int version , boolean creationOrderPresent , String objectName ) throws IOException { this . start = filePos ; raf . seek ( filePos ) ; if ( debugPos ) { log . debug ( \"  --> Message Header starts at =\" + raf . getFilePointer ( ) ) ; } if ( version == 1 ) { type = raf . readShort ( ) ; size = DataType . unsignedShortToInt ( raf . readShort ( ) ) ; headerMessageFlags = raf . readByte ( ) ; raf . skipBytes ( 3 ) ; header_length = 8 ; } else { type = ( short ) raf . readByte ( ) ; size = DataType . unsignedShortToInt ( raf . readShort ( ) ) ; //if (size > Short.MAX_VALUE) //  log.debug(\"HEY\"); headerMessageFlags = raf . readByte ( ) ; header_length = 4 ; if ( creationOrderPresent ) { creationOrder = raf . readShort ( ) ; header_length += 2 ; } } mtype = MessageType . getType ( type ) ; if ( debug1 ) { log . debug ( \"  -->\" + mtype + \" messageSize=\" + size + \" flags = \" + Integer . toBinaryString ( headerMessageFlags ) ) ; if ( creationOrderPresent && debugCreationOrder ) { log . debug ( \"     creationOrder = \" + creationOrder ) ; } } if ( debugPos ) { log . debug ( \"  --> Message Data starts at=\" + raf . getFilePointer ( ) ) ; } if ( ( headerMessageFlags & 2 ) != 0 ) { // shared messData = getSharedDataObject ( mtype ) . mdt ; // eg a shared datatype, eg enums return header_length + size ; } if ( mtype == MessageType . NIL ) { // 0 // dont do nuttin } else if ( mtype == MessageType . SimpleDataspace ) { // 1 MessageDataspace data = new MessageDataspace ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . GroupNew ) { // 2 MessageGroupNew data = new MessageGroupNew ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Datatype ) { // 3 MessageDatatype data = new MessageDatatype ( ) ; data . read ( objectName ) ; messData = data ; } else if ( mtype == MessageType . FillValueOld ) { // 4 MessageFillValueOld data = new MessageFillValueOld ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . FillValue ) { // 5 MessageFillValue data = new MessageFillValue ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Link ) { // 6 MessageLink data = new MessageLink ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Layout ) { // 8 MessageLayout data = new MessageLayout ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . GroupInfo ) { // 10 MessageGroupInfo data = new MessageGroupInfo ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . FilterPipeline ) { // 11 MessageFilter data = new MessageFilter ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Attribute ) { // 12 MessageAttribute data = new MessageAttribute ( ) ; data . read ( raf . getFilePointer ( ) ) ; messData = data ; } else if ( mtype == MessageType . Comment ) { // 13 MessageComment data = new MessageComment ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . LastModifiedOld ) { // 14 MessageLastModifiedOld data = new MessageLastModifiedOld ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . ObjectHeaderContinuation ) { // 16 MessageContinue data = new MessageContinue ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Group ) { // 17 MessageGroup data = new MessageGroup ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . LastModified ) { // 18 MessageLastModified data = new MessageLastModified ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . AttributeInfo ) { // 21 MessageAttributeInfo data = new MessageAttributeInfo ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . ObjectReferenceCount ) { // 21 MessageObjectReferenceCount data = new MessageObjectReferenceCount ( ) ; data . read ( ) ; messData = data ; } else { log . debug ( \"****UNPROCESSED MESSAGE type = \" + mtype + \" raw = \" + type ) ; log . warn ( \"SKIP UNPROCESSED MESSAGE type = \" + mtype + \" raw = \" + type ) ; //throw new UnsupportedOperationException(\"****UNPROCESSED MESSAGE type = \" + mtype + \" raw = \" + type); } return header_length + size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "debugging [CODESPLIT] public void showCompression ( Formatter f ) { if ( mtype != H5header . MessageType . AttributeInfo ) { f . format ( \"No fractal heap\" ) ; return ; } MessageAttributeInfo info = ( MessageAttributeInfo ) messData ; info . showFractalHeap ( f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs alignment decorators in all of the table s columns . [CODESPLIT] public static void installInAllColumns ( JTable table , int alignment ) { // We don't want to set up completely new cell renderers: rather, we want to use the existing ones but just // change their alignment. for ( int colViewIndex = 0 ; colViewIndex < table . getColumnCount ( ) ; ++ colViewIndex ) { installInOneColumn ( table , colViewIndex , alignment ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs alignment decorators in the table column at { @code colViewIndex } . [CODESPLIT] public static void installInOneColumn ( JTable table , int colViewIndex , int alignment ) { TableColumn tableColumn = table . getColumnModel ( ) . getColumn ( colViewIndex ) ; TableCellRenderer headerRenderer = tableColumn . getHeaderRenderer ( ) ; if ( headerRenderer == null ) { headerRenderer = table . getTableHeader ( ) . getDefaultRenderer ( ) ; } if ( ! ( headerRenderer instanceof RendererAlignmentDecorator ) ) { // Don't install a redundant decorator. tableColumn . setHeaderRenderer ( new RendererAlignmentDecorator ( headerRenderer , alignment ) ) ; } TableCellRenderer cellRenderer = tableColumn . getCellRenderer ( ) ; if ( cellRenderer == null ) { cellRenderer = table . getDefaultRenderer ( table . getColumnClass ( colViewIndex ) ) ; } if ( ! ( cellRenderer instanceof RendererAlignmentDecorator ) ) { // Don't install a redundant decorator. tableColumn . setCellRenderer ( new RendererAlignmentDecorator ( cellRenderer , alignment ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the key adding a trailing { @link #S3_DELIMITER delimiter } . Returns { @code null } if the key is { @code null } . [CODESPLIT] public String getKeyWithTrailingDelimiter ( ) { if ( key == null ) { return null ; } else { assert ! key . endsWith ( S3_DELIMITER ) : \"Didn't we strip this in the ctor?\" ; return key + S3_DELIMITER ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the parent URI of this URI . The determination is completely text - based using the { @link #S3_DELIMITER delimiter } . If the key is { @code null } { @code null } is returned . If it is non - { @code null } but doesn t have a logical parent the returned URI will have a { @code null } key ( but the same bucket ) . For example the parent of { @code s3 : // my - bucket / my - key } ( bucket = my - bucket key = my - key ) will be { @code s3 : // my - bucket } ( bucket == my - bucket key = null ) . [CODESPLIT] public S3URI getParent ( ) { if ( key == null ) { return null ; } int lastDelimPos = key . lastIndexOf ( S3_DELIMITER ) ; if ( lastDelimPos == - 1 ) { return new S3URI ( bucket , null ) ; } else { return new S3URI ( bucket , key . substring ( 0 , lastDelimPos ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new URI by resolving the specified path relative to { @code this } . If { @code key == null } the key of the returned URI will simply be { @code relativePath } . [CODESPLIT] public S3URI getChild ( String relativePath ) throws IllegalArgumentException { Preconditions . checkNotNull ( relativePath , \"relativePath must be non-null.\" ) ; if ( relativePath . isEmpty ( ) ) { return this ; } else if ( relativePath . startsWith ( S3_DELIMITER ) ) { throw new IllegalArgumentException ( String . format ( \"Path '%s' should be relative but begins with the delimiter string '%s'.\" , relativePath , S3_DELIMITER ) ) ; } if ( key == null ) { return new S3URI ( bucket , relativePath ) ; } else { return new S3URI ( bucket , key + S3_DELIMITER + relativePath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a temporary file to which the content of the S3Object that this URI points to can be downloaded . The path of the file is { @code $ { java . io . tmpdir } / S3Objects / $ { hashCode () } / $ { getBaseName () }} . This method does not cause the file to be created ; we re just returning a suitable path . [CODESPLIT] public File getTempFile ( ) { // To avoid collisions of files with the same name, create a parent dir named after the S3URI's hashCode(). File parentDir = new File ( S3ObjectTempDir , String . valueOf ( hashCode ( ) ) ) ; return new File ( parentDir , getBaseName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the HMAC api key and secret to be used for authenticated requests [CODESPLIT] public CoinbaseBuilder withApiKey ( String api_key , String api_secret ) { this . api_key = api_key ; this . api_secret = api_secret ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cross - platform way of finding an executable in the $PATH . [CODESPLIT] static Stream < Path > which ( String program ) { return which ( program , Optional . ofNullable ( System . getenv ( \"PATH\" ) ) . orElse ( \"\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a simple label . Create newlines with \\ n . [CODESPLIT] public static Label of ( String value ) { return new Label ( value , false , false , false , false , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a simple multiline label . [CODESPLIT] public static Label lines ( Justification just , String ... lines ) { final String sep = just == LEFT ? \"\\\\l\" : just == RIGHT ? \"\\\\r\" : \"\\n\" ; final String value = Stream . of ( lines ) . map ( line -> line + sep ) . collect ( joining ( ) ) ; return new Label ( value , false , false , false , false , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a HTML label . [CODESPLIT] public static Label html ( String value ) { return new Label ( value , true , false , false , false , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a HTML label from markdown . The following patterns are allowed : <br > \\ n newline ** bold ** * italics * ~~strike through~~ _underlined_ ^overlined^ __subscript__ ^^superscript^^ . [CODESPLIT] public static Label markdown ( String value ) { return html ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( value . replace ( \"\\n\" , \"<br/>\" ) , \"\\\\*\\\\*\" , \"b\" ) , \"\\\\*\" , \"i\" ) , \"~~\" , \"s\" ) , \"__\" , \"sub\" ) , \"_\" , \"u\" ) , \"\\\\^\\\\^\" , \"sup\" ) , \"\\\\^\" , \"o\" ) . replaceAll ( \"\\\\\\\\([*~_^])\" , \"$1\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create either a simple HTML or markdown label . If the value is not surrounded by < and > a simple Label is created . Otherwise if value contains some HTML tags a HTML label is created . Otherwise a markdown label is created . [CODESPLIT] public static Label raw ( String value ) { final boolean isTagged = value . startsWith ( \"<\" ) && value . endsWith ( \">\" ) ; if ( ! isTagged ) { return of ( value ) ; } final String untagged = value . substring ( 1 , value . length ( ) - 1 ) ; final boolean hasTags = value . contains ( \"/>\" ) || value . contains ( \"</\" ) ; return hasTags ? html ( untagged ) : markdown ( untagged ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { [CODESPLIT] public static synchronized CoreSocketFactory getInstance ( ) { if ( coreSocketFactory == null ) { logger . info ( \"First Cloud SQL connection, generating RSA key pair.\" ) ; KeyPair keyPair = generateRsaKeyPair ( ) ; CredentialFactory credentialFactory ; if ( System . getProperty ( CredentialFactory . CREDENTIAL_FACTORY_PROPERTY ) != null ) { try { credentialFactory = ( CredentialFactory ) Class . forName ( System . getProperty ( CredentialFactory . CREDENTIAL_FACTORY_PROPERTY ) ) . newInstance ( ) ; } catch ( Exception err ) { throw new RuntimeException ( err ) ; } } else { credentialFactory = new ApplicationDefaultCredentialFactory ( ) ; } Credential credential = credentialFactory . create ( ) ; SQLAdmin adminApi = createAdminApiClient ( credential ) ; coreSocketFactory = new CoreSocketFactory ( new Clock ( ) , keyPair , credential , adminApi , DEFAULT_SERVER_PROXY_PORT ) ; } return coreSocketFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a socket representing a connection to a Cloud SQL instance . [CODESPLIT] public Socket connect ( Properties props , String socketPathFormat ) throws IOException { // Gather parameters final String csqlInstanceName = props . getProperty ( CLOUD_SQL_INSTANCE_PROPERTY ) ; final List < String > ipTypes = listIpTypes ( props . getProperty ( \"ipTypes\" , DEFAULT_IP_TYPES ) ) ; final boolean forceUnixSocket = System . getenv ( \"CLOUD_SQL_FORCE_UNIX_SOCKET\" ) != null ; // Validate parameters Preconditions . checkArgument ( csqlInstanceName != null , \"cloudSqlInstance property not set. Please specify this property in the JDBC URL or the \" + \"connection Properties with value in form \\\"project:region:instance\\\"\" ) ; // GAE Standard runtimes provide a connection path at \"/cloudsql/<CONNECTION_NAME>\" if ( forceUnixSocket || runningOnGaeStandard ( ) ) { logger . info ( String . format ( \"Connecting to Cloud SQL instance [%s] via unix socket.\" , csqlInstanceName ) ) ; UnixSocketAddress socketAddress = new UnixSocketAddress ( new File ( String . format ( socketPathFormat , csqlInstanceName ) ) ) ; return UnixSocketChannel . open ( socketAddress ) . socket ( ) ; } logger . info ( String . format ( \"Connecting to Cloud SQL instance [%s] via SSL socket.\" , csqlInstanceName ) ) ; return getInstance ( ) . createSslSocket ( csqlInstanceName , ipTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { [CODESPLIT] private boolean runningOnGaeStandard ( ) { // gaeEnv=\"standard\" indicates standard instances String gaeEnv = System . getenv ( \"GAE_ENV\" ) ; // runEnv=\"Production\" requires to rule out Java 8 emulated environments String runEnv = System . getProperty ( \"com.google.appengine.runtime.environment\" ) ; // gaeRuntime=\"java11\" in Java 11 environments (no emulated environments) String gaeRuntime = System . getenv ( \"GAE_RUNTIME\" ) ; return \"standard\" . equals ( gaeEnv ) && ( \"Production\" . equals ( runEnv ) || \"java11\" . equals ( gaeRuntime ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO ( berezv ) : separate creating socket and performing connection to make it easier to test [CODESPLIT] @ VisibleForTesting Socket createSslSocket ( String instanceName , List < String > ipTypes ) throws IOException { try { return createAndConfigureSocket ( instanceName , ipTypes , CertificateCaching . USE_CACHE ) ; } catch ( SSLHandshakeException err ) { logger . warning ( String . format ( \"SSL handshake failed for Cloud SQL instance [%s], \" + \"retrying with new certificate.\\n%s\" , instanceName , Throwables . getStackTraceAsString ( err ) ) ) ; if ( ! forcedRenewRateLimiter . tryAcquire ( ) ) { logger . warning ( String . format ( \"Renewing too often, rate limiting certificate renewal for Cloud SQL \" + \"instance [%s].\" , instanceName ) ) ; forcedRenewRateLimiter . acquire ( ) ; } return createAndConfigureSocket ( instanceName , ipTypes , CertificateCaching . BYPASS_CACHE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the string property of IP types to a list by splitting by commas and upper - casing . [CODESPLIT] private static List < String > listIpTypes ( String cloudSqlIpTypes ) { String [ ] rawTypes = cloudSqlIpTypes . split ( \",\" ) ; ArrayList < String > result = new ArrayList <> ( rawTypes . length ) ; for ( int i = 0 ; i < rawTypes . length ; i ++ ) { if ( rawTypes [ i ] . trim ( ) . equalsIgnoreCase ( \"PUBLIC\" ) ) { result . add ( i , \"PRIMARY\" ) ; } else { result . add ( i , rawTypes [ i ] . trim ( ) . toUpperCase ( ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO ( berezv ) : synchronize per instance instead of globally [CODESPLIT] @ VisibleForTesting synchronized InstanceSslInfo getInstanceSslInfo ( String instanceConnectionString , CertificateCaching certificateCaching ) { if ( certificateCaching . equals ( CertificateCaching . USE_CACHE ) ) { InstanceLookupResult lookupResult = cache . get ( instanceConnectionString ) ; if ( lookupResult != null ) { if ( ! lookupResult . isSuccessful ( ) && ( clock . now ( ) - lookupResult . getLastFailureMillis ( ) ) < 60 * 1000 ) { logger . warning ( \"Re-throwing cached exception due to attempt to refresh instance information too \" + \"soon after error.\" ) ; throw lookupResult . getException ( ) . get ( ) ; } else if ( lookupResult . isSuccessful ( ) ) { InstanceSslInfo details = lookupResult . getInstanceSslInfo ( ) . get ( ) ; // Check if the cached certificate is still valid. if ( details != null ) { GregorianCalendar calendar = new GregorianCalendar ( ) ; calendar . setTimeInMillis ( clock . now ( ) ) ; calendar . add ( Calendar . MINUTE , 5 ) ; try { details . getEphemeralCertificate ( ) . checkValidity ( calendar . getTime ( ) ) ; } catch ( CertificateException err ) { logger . info ( String . format ( \"Ephemeral certificate for Cloud SQL instance [%s] is about to expire, \" + \"obtaining new one.\" , instanceConnectionString ) ) ; details = null ; } } if ( details != null ) { return details ; } } } } String invalidInstanceError = String . format ( \"Invalid Cloud SQL instance [%s], expected value in form [project:region:name].\" , instanceConnectionString ) ; int beforeNameIndex = instanceConnectionString . lastIndexOf ( ' ' ) ; if ( beforeNameIndex <= 0 ) { throw new IllegalArgumentException ( invalidInstanceError ) ; } int beforeRegionIndex = instanceConnectionString . lastIndexOf ( ' ' , beforeNameIndex - 1 ) ; if ( beforeRegionIndex <= 0 ) { throw new IllegalArgumentException ( invalidInstanceError ) ; } String projectId = instanceConnectionString . substring ( 0 , beforeRegionIndex ) ; String region = instanceConnectionString . substring ( beforeRegionIndex + 1 , beforeNameIndex ) ; String instanceName = instanceConnectionString . substring ( beforeNameIndex + 1 ) ; InstanceLookupResult instanceLookupResult ; InstanceSslInfo details ; try { details = fetchInstanceSslInfo ( instanceConnectionString , projectId , region , instanceName ) ; instanceLookupResult = new InstanceLookupResult ( details ) ; cache . put ( instanceConnectionString , instanceLookupResult ) ; } catch ( RuntimeException err ) { instanceLookupResult = new InstanceLookupResult ( err ) ; cache . put ( instanceConnectionString , instanceLookupResult ) ; throw err ; } return details ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements the interface for com . mysql . cj . protocol . SocketFactory for mysql - connector - java prior to version 8 . 0 . 13 . This change is required for backwards compatibility . [CODESPLIT] public < T extends Closeable > T connect ( String host , int portNumber , Properties props , int loginTimeout ) throws IOException { @ SuppressWarnings ( \"unchecked\" ) T socket = ( T ) CoreSocketFactory . getInstance ( ) . connect ( props , CoreSocketFactory . MYSQL_SOCKET_FILE_FORMAT ) ; return socket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Purges an invalid logger from the cache . [CODESPLIT] protected synchronized void purgeLogger ( FluentLogger logger ) { Iterator < Entry < FluentLogger , String > > it = loggers . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . getKey ( ) == logger ) { it . remove ( ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile all sources [CODESPLIT] public Map < String , Class < ? > > compileAll ( ) throws Exception { if ( sourceCodes . size ( ) == 0 ) { throw new CompilationException ( \"No source code to compile\" ) ; } Collection < SourceCode > compilationUnits = sourceCodes . values ( ) ; CompiledCode [ ] code ; code = new CompiledCode [ compilationUnits . size ( ) ] ; Iterator < SourceCode > iter = compilationUnits . iterator ( ) ; for ( int i = 0 ; i < code . length ; i ++ ) { code [ i ] = new CompiledCode ( iter . next ( ) . getClassName ( ) ) ; } DiagnosticCollector < JavaFileObject > collector = new DiagnosticCollector <> ( ) ; ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager ( javac . getStandardFileManager ( null , null , null ) , classLoader ) ; JavaCompiler . CompilationTask task = javac . getTask ( null , fileManager , collector , options , null , compilationUnits ) ; boolean result = task . call ( ) ; if ( ! result || collector . getDiagnostics ( ) . size ( ) > 0 ) { StringBuffer exceptionMsg = new StringBuffer ( ) ; exceptionMsg . append ( \"Unable to compile the source\" ) ; boolean hasWarnings = false ; boolean hasErrors = false ; for ( Diagnostic < ? extends JavaFileObject > d : collector . getDiagnostics ( ) ) { switch ( d . getKind ( ) ) { case NOTE : case MANDATORY_WARNING : case WARNING : hasWarnings = true ; break ; case OTHER : case ERROR : default : hasErrors = true ; break ; } exceptionMsg . append ( \"\\n\" ) . append ( \"[kind=\" ) . append ( d . getKind ( ) ) ; exceptionMsg . append ( \", \" ) . append ( \"line=\" ) . append ( d . getLineNumber ( ) ) ; exceptionMsg . append ( \", \" ) . append ( \"message=\" ) . append ( d . getMessage ( Locale . US ) ) . append ( \"]\" ) ; } if ( hasWarnings && ! ignoreWarnings || hasErrors ) { throw new CompilationException ( exceptionMsg . toString ( ) ) ; } } Map < String , Class < ? > > classes = new HashMap < String , Class < ? > > ( ) ; for ( String className : sourceCodes . keySet ( ) ) { classes . put ( className , classLoader . loadClass ( className ) ) ; } return classes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile single source [CODESPLIT] public Class < ? > compile ( String className , String sourceCode ) throws Exception { return addSource ( className , sourceCode ) . compileAll ( ) . get ( className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add source code to the compiler [CODESPLIT] public InMemoryJavaCompiler addSource ( String className , String sourceCode ) throws Exception { sourceCodes . put ( className , new SourceCode ( className , sourceCode ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads Graphics Control Extension values . [CODESPLIT] private void readGraphicControlExt ( ) { // Block size. read ( ) ; // Packed fields. int packed = read ( ) ; // Disposal method. header . currentFrame . dispose = ( packed & 0x1c ) >> 2 ; if ( header . currentFrame . dispose == 0 ) { // Elect to keep old image if discretionary. header . currentFrame . dispose = 1 ; } header . currentFrame . transparency = ( packed & 1 ) != 0 ; // Delay in milliseconds. int delayInHundredthsOfASecond = readShort ( ) ; // TODO: consider allowing -1 to indicate show forever. if ( delayInHundredthsOfASecond < MIN_FRAME_DELAY ) { delayInHundredthsOfASecond = DEFAULT_FRAME_DELAY ; } header . currentFrame . delay = delayInHundredthsOfASecond * 10 ; // Transparent color index header . currentFrame . transIndex = read ( ) ; // Block terminator read ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads next variable length block from input . [CODESPLIT] private int readBlock ( ) { blockSize = read ( ) ; int n = 0 ; if ( blockSize > 0 ) { int count = 0 ; try { while ( n < blockSize ) { count = blockSize - n ; rawData . get ( block , n , count ) ; n += count ; } } catch ( Exception e ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , \"Error Reading Block n: \" + n + \" count: \" + count + \" blockSize: \" + blockSize , e ) ; } header . status = GifDecoder . STATUS_FORMAT_ERROR ; } } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the next frame in the animation sequence . [CODESPLIT] synchronized Bitmap getNextFrame ( ) { if ( header . frameCount <= 0 || framePointer < 0 ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , \"unable to decode frame, frameCount=\" + header . frameCount + \" framePointer=\" + framePointer ) ; } status = STATUS_FORMAT_ERROR ; } if ( status == STATUS_FORMAT_ERROR || status == STATUS_OPEN_ERROR ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , \"Unable to decode frame, status=\" + status ) ; } return null ; } status = STATUS_OK ; GifFrame currentFrame = header . frames . get ( framePointer ) ; GifFrame previousFrame = null ; int previousIndex = framePointer - 1 ; if ( previousIndex >= 0 ) { previousFrame = header . frames . get ( previousIndex ) ; } // Set the appropriate color table. act = currentFrame . lct != null ? currentFrame . lct : header . gct ; if ( act == null ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , \"No Valid Color Table for frame #\" + framePointer ) ; } // No color table defined. status = STATUS_FORMAT_ERROR ; return null ; } // Reset the transparent pixel in the color table if ( currentFrame . transparency ) { // Prepare local copy of color table (\"pct = act\"), see #1068 System . arraycopy ( act , 0 , pct , 0 , act . length ) ; // Forget about act reference from shared header object, use copied version act = pct ; // Set transparent color if specified. act [ currentFrame . transIndex ] = 0 ; } // Transfer pixel data to image. return setPixels ( currentFrame , previousFrame ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new frame image from current data ( and previous frames as specified by their disposition codes ) . [CODESPLIT] private Bitmap setPixels ( GifFrame currentFrame , GifFrame previousFrame ) { // Final location of blended pixels. final int [ ] dest = mainScratch ; // clear all pixels when meet first frame if ( previousFrame == null ) { Arrays . fill ( dest , 0 ) ; } // fill in starting image contents based on last image's dispose code if ( previousFrame != null && previousFrame . dispose > DISPOSAL_UNSPECIFIED ) { // We don't need to do anything for DISPOSAL_NONE, if it has the correct pixels so will our // mainScratch and therefore so will our dest array. if ( previousFrame . dispose == DISPOSAL_BACKGROUND ) { // Start with a canvas filled with the background color int c = 0 ; if ( ! currentFrame . transparency ) { c = header . bgColor ; if ( currentFrame . lct != null && header . bgIndex == currentFrame . transIndex ) { c = 0 ; } } else if ( framePointer == 0 ) { // TODO: We should check and see if all individual pixels are replaced. If they are, the // first frame isn't actually transparent. For now, it's simpler and safer to assume // drawing a transparent background means the GIF contains transparency. isFirstFrameTransparent = true ; } fillRect ( dest , previousFrame , c ) ; } else if ( previousFrame . dispose == DISPOSAL_PREVIOUS ) { if ( previousImage == null ) { fillRect ( dest , previousFrame , 0 ) ; } else { // Start with the previous frame int downsampledIH = previousFrame . ih / sampleSize ; int downsampledIY = previousFrame . iy / sampleSize ; int downsampledIW = previousFrame . iw / sampleSize ; int downsampledIX = previousFrame . ix / sampleSize ; int topLeft = downsampledIY * downsampledWidth + downsampledIX ; previousImage . getPixels ( dest , topLeft , downsampledWidth , downsampledIX , downsampledIY , downsampledIW , downsampledIH ) ; } } } // Decode pixels for this frame into the global pixels[] scratch. decodeBitmapData ( currentFrame ) ; int downsampledIH = currentFrame . ih / sampleSize ; int downsampledIY = currentFrame . iy / sampleSize ; int downsampledIW = currentFrame . iw / sampleSize ; int downsampledIX = currentFrame . ix / sampleSize ; // Copy each source line to the appropriate place in the destination. int pass = 1 ; int inc = 8 ; int iline = 0 ; boolean isFirstFrame = framePointer == 0 ; for ( int i = 0 ; i < downsampledIH ; i ++ ) { int line = i ; if ( currentFrame . interlace ) { if ( iline >= downsampledIH ) { pass ++ ; switch ( pass ) { case 2 : iline = 4 ; break ; case 3 : iline = 2 ; inc = 4 ; break ; case 4 : iline = 1 ; inc = 2 ; break ; default : break ; } } line = iline ; iline += inc ; } line += downsampledIY ; if ( line < downsampledHeight ) { int k = line * downsampledWidth ; // Start of line in dest. int dx = k + downsampledIX ; // End of dest line. int dlim = dx + downsampledIW ; if ( k + downsampledWidth < dlim ) { // Past dest edge. dlim = k + downsampledWidth ; } // Start of line in source. int sx = i * sampleSize * currentFrame . iw ; int maxPositionInSource = sx + ( ( dlim - dx ) * sampleSize ) ; while ( dx < dlim ) { // Map color and insert in destination. int averageColor ; if ( sampleSize == 1 ) { int currentColorIndex = ( ( int ) mainPixels [ sx ] ) & 0x000000ff ; averageColor = act [ currentColorIndex ] ; } else { // TODO: This is substantially slower (up to 50ms per frame) than just grabbing the // current color index above, even with a sample size of 1. averageColor = averageColorsNear ( sx , maxPositionInSource , currentFrame . iw ) ; } if ( averageColor != 0 ) { dest [ dx ] = averageColor ; } else if ( ! isFirstFrameTransparent && isFirstFrame ) { isFirstFrameTransparent = true ; } sx += sampleSize ; dx ++ ; } } } // Copy pixels into previous image if ( savePrevious && ( currentFrame . dispose == DISPOSAL_UNSPECIFIED || currentFrame . dispose == DISPOSAL_NONE ) ) { if ( previousImage == null ) { previousImage = getNextBitmap ( ) ; } previousImage . setPixels ( dest , 0 , downsampledWidth , 0 , 0 , downsampledWidth , downsampledHeight ) ; } // Set pixels for current image. Bitmap result = getNextBitmap ( ) ; result . setPixels ( dest , 0 , downsampledWidth , 0 , 0 , downsampledWidth , downsampledHeight ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads next variable length block from input . [CODESPLIT] private int readBlock ( ) { int blockSize = readByte ( ) ; if ( blockSize > 0 ) { try { if ( block == null ) { block = bitmapProvider . obtainByteArray ( 255 ) ; } final int remaining = workBufferSize - workBufferPosition ; if ( remaining >= blockSize ) { // Block can be read from the current work buffer. System . arraycopy ( workBuffer , workBufferPosition , block , 0 , blockSize ) ; workBufferPosition += blockSize ; } else if ( rawData . remaining ( ) + remaining >= blockSize ) { // Block can be read in two passes. System . arraycopy ( workBuffer , workBufferPosition , block , 0 , remaining ) ; workBufferPosition = workBufferSize ; readChunkIfNeeded ( ) ; final int secondHalfRemaining = blockSize - remaining ; System . arraycopy ( workBuffer , 0 , block , remaining , secondHalfRemaining ) ; workBufferPosition += secondHalfRemaining ; } else { status = STATUS_FORMAT_ERROR ; } } catch ( Exception e ) { Log . w ( TAG , \"Error Reading Block\" , e ) ; status = STATUS_FORMAT_ERROR ; } } return blockSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this method to initialize the show / hide listeners for the dialog . [CODESPLIT] public static void initDialog ( BooleanProperty openProperty , final Stage parentStage , Supplier < Parent > rootSupplier ) { final Stage dialogStage = new Stage ( StageStyle . UTILITY ) ; dialogStage . initOwner ( parentStage ) ; dialogStage . initModality ( Modality . APPLICATION_MODAL ) ; openProperty . addListener ( ( obs , oldValue , newValue ) -> { if ( newValue ) { // when it is the first time the dialog is made visible (and therefore no scene exists) ... if ( dialogStage . getScene ( ) == null ) { // ... we create a new scene and register it in the stage. Scene dialogScene = new Scene ( rootSupplier . get ( ) ) ; dialogScene . getStylesheets ( ) . add ( \"/contacts.css\" ) ; dialogStage . setScene ( dialogScene ) ; } else { // ... otherwise we simple bring the dialog to front. dialogStage . toFront ( ) ; } dialogStage . sizeToScene ( ) ; dialogStage . show ( ) ; } else { dialogStage . close ( ) ; } } ) ; // when the user clicks on the close button of the dialog window // we want to set the property to false dialogStage . setOnCloseRequest ( event -> openProperty . set ( false ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persons in string representation . [CODESPLIT] public SelectableStringList selectablePersonsProperty ( ) { if ( selectablePersons == null ) { selectablePersons = new SelectableItemList <> ( FXCollections . observableArrayList ( repository . getPersons ( ) ) , person -> person . getFirstName ( ) + \" \" + person . getLastName ( ) ) ; } return selectablePersons ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called by the javafx runtime when the application is initialized . See { @link Application#init () } for more details . <p > In this method the initialization of the guice container is done . For this reason this method is marked as final and cannot be overwritten by users . <p > Please use { @link #initMvvmfx () } for your own initialization logic . [CODESPLIT] public final void init ( ) throws Exception { List < Module > modules = new ArrayList <> ( ) ; modules . add ( new MvvmfxModule ( ) ) ; modules . add ( new AbstractModule ( ) { @ Override protected void configure ( ) { bind ( HostServices . class ) . toProvider ( MvvmfxGuiceApplication . this :: getHostServices ) ; bind ( Stage . class ) . toProvider ( ( ) -> primaryStage ) ; bind ( Parameters . class ) . toProvider ( MvvmfxGuiceApplication . this :: getParameters ) ; } } ) ; this . initGuiceModules ( modules ) ; final Injector injector = Guice . createInjector ( modules ) ; MvvmFX . setCustomDependencyInjector ( injector :: getInstance ) ; injector . injectMembers ( this ) ; this . initMvvmfx ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to inject the given { @link ResourceBundle } into the given target instance . [CODESPLIT] static void injectResourceBundle ( Object target , ResourceBundle resourceBundle ) { final List < Field > fieldsWithAnnotation = ReflectionUtils . getFieldsWithAnnotation ( target , InjectResourceBundle . class ) ; final boolean notAssignableFieldPresent = fieldsWithAnnotation . stream ( ) . anyMatch ( field -> ! field . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) ; if ( notAssignableFieldPresent ) { throw new IllegalStateException ( \"The class [\" + target + \"] has at least one field with the annotation @InjectResourceBundle but the field is not of type ResourceBundle.\" ) ; } // check whether the user has provided any resourceBundle or not if ( resourceBundle == null || resourceBundle . equals ( EMPTY_RESOURCE_BUNDLE ) ) { if ( ! fieldsWithAnnotation . isEmpty ( ) ) { final boolean nonOptionalFieldsPresent = fieldsWithAnnotation . stream ( ) . flatMap ( field -> Arrays . stream ( field . getAnnotationsByType ( InjectResourceBundle . class ) ) ) . anyMatch ( annotation -> ! annotation . optional ( ) ) ; // if all annotated fields are marked as \"optional\", no exception has to be thrown. if ( nonOptionalFieldsPresent ) { throw new IllegalStateException ( \"The class [\" + target + \"] expects a ResourceBundle to be injected but no ResourceBundle was defined while loading.\" ) ; } } } else { fieldsWithAnnotation . forEach ( field -> { if ( field . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) { ReflectionUtils . setField ( field , target , resourceBundle ) ; } else { throw new IllegalStateException ( \"The class [\" + target + \"] has a field with the @InjectResourceBundle annotation but the type of the field doesn't match ResourceBundle\" ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to set the clock to a fixed time . This is useful for tests . This way it s possible to create date / time instances with a predictable value for your tests . [CODESPLIT] public static void setFixedClock ( ZonedDateTime zonedDateTime ) { CentralClock . clock = Clock . fixed ( zonedDateTime . toInstant ( ) , ZoneId . systemDefault ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the message with the highest priority using the following algorithm : - if there are messages with { @link Severity#ERROR } take the first one . - otherwise if there are messages with { @link Severity#WARNING } take the first one . - otherwise an empty Optional is returned . [CODESPLIT] public Optional < ValidationMessage > getHighestMessage ( ) { final Optional < ValidationMessage > error = getMessages ( ) . stream ( ) . filter ( message -> message . getSeverity ( ) . equals ( Severity . ERROR ) ) . findFirst ( ) ; if ( error . isPresent ( ) ) { return error ; } else { final Optional < ValidationMessage > warning = getMessages ( ) . stream ( ) . filter ( message -> message . getSeverity ( ) . equals ( Severity . WARNING ) ) . findFirst ( ) ; return warning ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the provided ResourceBundle with the global one ( if any ) . [CODESPLIT] public ResourceBundle mergeWithGlobal ( ResourceBundle resourceBundle ) { if ( globalResourceBundle == null ) { if ( resourceBundle == null ) { return EMPTY_RESOURCE_BUNDLE ; } else { return new ResourceBundleWrapper ( resourceBundle ) ; } } else { if ( resourceBundle == null ) { return new ResourceBundleWrapper ( globalResourceBundle ) ; } else { return merge ( resourceBundle , globalResourceBundle ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the list of ResourceBundles with the global one ( if any ) . <p / > The global resourceBundle has a lower priority then the provided ones . If there is the same key defined in the global and in one of the provided resourceBundles the value from the provided resourceBundle will be used . <p / > The order of resourceBundles in the list defines the priority for resourceBundles . ResourceBundles at the start of the list have a <strong > lower< / strong > priority compared to bundles at the end of the list . This means that the last resourceBundle will overwrite values from previous resourceBundles ( including the global resourceBundle ( if any )) . * [CODESPLIT] public ResourceBundle mergeListWithGlobal ( List < ResourceBundle > bundles ) { if ( globalResourceBundle == null ) { if ( bundles == null ) { return EMPTY_RESOURCE_BUNDLE ; } else { return reduce ( bundles ) ; } } else { if ( bundles == null ) { return new ResourceBundleWrapper ( globalResourceBundle ) ; } else { final List < ResourceBundle > resourceBundles = new ArrayList <> ( ) ; resourceBundles . add ( globalResourceBundle ) ; resourceBundles . addAll ( bundles ) ; return reduce ( resourceBundles ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance of the given type . When there is a custom injector defined ( See : { @link #setCustomInjector ( javafx . util . Callback ) } ) then this injector is used . Otherwise a new instance of the desired type is created . This is done by a call to { @link Class#newInstance () } which means that all constraints of the newInstance method are also need to be satisfied . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > T getInstanceOf ( Class < ? extends T > type ) { if ( isCustomInjectorDefined ( ) ) { return ( T ) customInjector . call ( type ) ; } else { try { // use default creation return type . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new RuntimeException ( \"Can't create instance of type \" + type . getName ( ) + \". Make sure that the class has a public no-arg constructor.\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the list changed we want the recreate the targetType representation [CODESPLIT] private void initListEvents ( ) { this . listChangeListener = new ListChangeListener < SourceType > ( ) { @ Override public void onChanged ( Change < ? extends SourceType > listEvent ) { // We have to stage delete events, because if we process them // separately, there will be unwanted ChangeEvents on the // targetList List < TargetType > deleteStaging = new ArrayList <> ( ) ; while ( listEvent . next ( ) ) { if ( listEvent . wasUpdated ( ) ) { processUpdateEvent ( listEvent ) ; } else if ( listEvent . wasReplaced ( ) ) { processReplaceEvent ( listEvent , deleteStaging ) ; } else if ( listEvent . wasAdded ( ) ) { processAddEvent ( listEvent ) ; } else if ( listEvent . wasRemoved ( ) ) { processRemoveEvent ( listEvent , deleteStaging ) ; } } // Process the staged elements processStagingLists ( deleteStaging ) ; } } ; modelListProperty ( ) . addListener ( new WeakListChangeListener <> ( listChangeListener ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an add event of the model list to new elements of the { @link #viewModelList } . [CODESPLIT] private void processAddEvent ( ListChangeListener . Change < ? extends SourceType > listEvent ) { final List < TargetType > toAdd = new ArrayList <> ( ) ; for ( int index = listEvent . getFrom ( ) ; index < listEvent . getTo ( ) ; index ++ ) { final SourceType item = listEvent . getList ( ) . get ( index ) ; toAdd . add ( function . apply ( item ) ) ; } viewModelList . addAll ( listEvent . getFrom ( ) , toAdd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an remove event of the model list to new elements of the { @link #viewModelList } . [CODESPLIT] private void processRemoveEvent ( ListChangeListener . Change < ? extends SourceType > listEvent , List < TargetType > deleteStaging ) { for ( int i = 0 ; i < listEvent . getRemovedSize ( ) ; i ++ ) { deleteStaging . add ( viewModelList . get ( listEvent . getFrom ( ) + i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an update event of the model list to new elements of the { @link #viewModelList } . [CODESPLIT] private void processUpdateEvent ( ListChangeListener . Change < ? extends SourceType > listEvent ) { for ( int i = listEvent . getFrom ( ) ; i < listEvent . getTo ( ) ; i ++ ) { SourceType item = listEvent . getList ( ) . get ( i ) ; viewModelList . set ( i , ListTransformation . this . function . apply ( item ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps an replace event of the model list to new elements of the { @link #viewModelList } . [CODESPLIT] private void processReplaceEvent ( ListChangeListener . Change < ? extends SourceType > listEvent , List < TargetType > deletedStaging ) { processRemoveEvent ( listEvent , deletedStaging ) ; processStagingLists ( deletedStaging ) ; processAddEvent ( listEvent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a Person . s [CODESPLIT] public Person getPersonById ( final int id ) { for ( Person person : persons ) { if ( id == person . getId ( ) ) { return person ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new BuilderFactory instance that contains all custom factories of this instance combined with the list of factories passed as argument to this method . <br / > This instance of the builderFactory is not changed by this method . [CODESPLIT] public BuilderFactory mergeWith ( List < BuilderFactory > factories ) { GlobalBuilderFactory factory = new GlobalBuilderFactory ( ) ; factory . factories . addAll ( factories ) ; return factory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a new ( key value ) into the map . <p > [CODESPLIT] @ Override public Object put ( Object key , Object value ) { // If the map already contains an equivalent key, the new key // of a (key, value) pair is NOT stored in the map but the new // value only. But as the key is strongly referenced by the // map, it can not be removed from the garbage collector, even // if the key becomes weakly reachable due to the old // value. So, it isn't necessary to remove all garbage // collected values with their keys from the map before the // new entry is made. We only clean up here to distribute // clean up calls on different operations. processQueue ( ) ; WeakValue oldValue = ( WeakValue ) super . put ( key , WeakValue . create ( key , value , queue ) ) ; return getReferenceObject ( oldValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all garbage collected values with their keys from the map . Since we don t know how much the ReferenceQueue . poll () operation costs we should not call it every map operation . [CODESPLIT] private void processQueue ( ) { WeakValue wv = null ; while ( ( wv = ( WeakValue ) this . queue . poll ( ) ) != null ) { // \"super\" is not really necessary but use it // to be on the safe side super . remove ( wv . key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > Set< / code > view of the mappings in this map . <p > [CODESPLIT] @ Override public Set entrySet ( ) { if ( entrySet == null ) { hashEntrySet = super . entrySet ( ) ; entrySet = new EntrySet ( ) ; } return entrySet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > Collection< / code > view of the values contained in this map . <p > [CODESPLIT] @ Override public Collection values ( ) { // delegates to entrySet, because super method returns // WeakValues instead of value objects if ( values == null ) { values = new AbstractCollection ( ) { @ Override public Iterator iterator ( ) { return new Iterator ( ) { private final Iterator i = entrySet ( ) . iterator ( ) ; @ Override public boolean hasNext ( ) { return i . hasNext ( ) ; } @ Override public Object next ( ) { return ( ( Entry ) i . next ( ) ) . getValue ( ) ; } @ Override public void remove ( ) { i . remove ( ) ; } } ; } @ Override public int size ( ) { return WeakValueHashMap . this . size ( ) ; } @ Override public boolean contains ( Object v ) { return WeakValueHashMap . this . containsValue ( v ) ; } } ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a list of validation messages for the specified validator . [CODESPLIT] void addMessage ( Validator validator , List < ? extends ValidationMessage > messages ) { if ( messages . isEmpty ( ) ) { return ; } final int validatorHash = System . identityHashCode ( validator ) ; if ( ! validatorToMessagesMap . containsKey ( validatorHash ) ) { validatorToMessagesMap . put ( validatorHash , new ArrayList <> ( ) ) ; } final List < Integer > messageHashesOfThisValidator = validatorToMessagesMap . get ( validatorHash ) ; // add the hashCodes of the messages to the internal map messages . stream ( ) . map ( System :: identityHashCode ) . forEach ( messageHashesOfThisValidator :: add ) ; // add the actual messages to the message list so that they are accessible by the user. getMessagesInternal ( ) . addAll ( messages ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Remove all given messages for the given validator . [CODESPLIT] void removeMessage ( final Validator validator , final List < ? extends ValidationMessage > messages ) { if ( messages . isEmpty ( ) ) { return ; } final int validatorHash = System . identityHashCode ( validator ) ; // if the validator is unknown by the map we haven't stored any messages for it yet that could be removed if ( validatorToMessagesMap . containsKey ( validatorHash ) ) { final List < Integer > messageHashesOfThisValidator = validatorToMessagesMap . get ( validatorHash ) ; final List < Integer > hashesOfMessagesToRemove = messages . stream ( ) . filter ( m -> { // only those messages that are stored for this validator int hash = System . identityHashCode ( m ) ; return messageHashesOfThisValidator . contains ( hash ) ; } ) . map ( System :: identityHashCode ) // we only need the hashCode here . collect ( Collectors . toList ( ) ) ; // only remove those messages that we have the hashCode stored getMessagesInternal ( ) . removeIf ( message -> { int hash = System . identityHashCode ( message ) ; return hashesOfMessagesToRemove . contains ( hash ) ; } ) ; // we need to cleanup our internal map messageHashesOfThisValidator . removeAll ( hashesOfMessagesToRemove ) ; if ( messageHashesOfThisValidator . isEmpty ( ) ) { validatorToMessagesMap . remove ( validatorHash ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Remove all messages for this particular validator . [CODESPLIT] void removeMessage ( final Validator validator ) { final int validatorHash = System . identityHashCode ( validator ) ; if ( validatorToMessagesMap . containsKey ( validatorHash ) ) { final List < Integer > messageHashesOfThisValidator = validatorToMessagesMap . get ( validatorHash ) ; getMessagesInternal ( ) . removeIf ( message -> { int hash = System . identityHashCode ( message ) ; return messageHashesOfThisValidator . contains ( hash ) ; } ) ; validatorToMessagesMap . remove ( validatorHash ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set Person id for the screen [CODESPLIT] public void setPersonId ( int personId ) { person = repository . getPersonById ( personId ) ; StringBinding salutationBinding = Bindings . when ( person . genderProperty ( ) . isEqualTo ( Gender . NOT_SPECIFIED ) ) . then ( \"Herr/Frau/* \" ) . otherwise ( Bindings . when ( person . genderProperty ( ) . isEqualTo ( Gender . MALE ) ) . then ( \"Herr \" ) . otherwise ( \"Frau \" ) ) ; welcomeString . unbind ( ) ; welcomeString . bind ( Bindings . concat ( \"Willkommen \" , salutationBinding , person . firstNameProperty ( ) , \" \" , person . lastNameProperty ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the java written view of the given type and injects the ViewModel for this view . <br > If the given view type implements the { @link javafx . fxml . Initializable } interface the initialize method of this interface will be invoked . When this is not the case an implicit initialization will be done that is working similar to the way the { @link javafx . fxml . FXMLLoader } is working . <br > When there is a <strong > public< / strong > no - args method named initialize is available this method will be called . When there is a <strong > public< / strong > field of type { @link java . util . ResourceBundle } named resources is available this field will get the provided ResourceBundle injected . <br > The initialize method ( whether from the { @link javafx . fxml . Initializable } interface or implicit ) will be invoked <strong > after< / strong > the viewModel was injected . This way the user can create bindings to the viewModel in the initialize method . [CODESPLIT] public < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewTuple < ViewType , ViewModelType > loadJavaViewTuple ( Class < ? extends ViewType > viewType , ResourceBundle resourceBundle , final ViewModelType existingViewModel , ViewType codeBehind , Context parentContext , Collection < Scope > providedScopes ) { // FIXME Woanders hin?! ContextImpl context = ViewLoaderScopeUtils . prepareContext ( parentContext , providedScopes ) ; //////////////////////////// DependencyInjector injectionFacade = DependencyInjector . getInstance ( ) ; final ViewType view = codeBehind == null ? injectionFacade . getInstanceOf ( viewType ) : codeBehind ; if ( ! ( view instanceof Parent ) ) { throw new IllegalArgumentException ( \"Can not load java view! The view class has to extend from \" + Parent . class . getName ( ) + \" or one of it's subclasses\" ) ; } ViewModelType viewModel = null ; // when no viewmodel was provided by the user... if ( existingViewModel == null ) { // ... we create a new one (if possible) viewModel = ViewLoaderReflectionUtils . createViewModel ( view ) ; } else { viewModel = existingViewModel ; } ResourceBundleInjector . injectResourceBundle ( view , resourceBundle ) ; // if no ViewModel is available... if ( viewModel == null ) { // we need to check if the user is trying to inject a viewModel. final List < Field > viewModelFields = ViewLoaderReflectionUtils . getViewModelFields ( viewType ) ; if ( ! viewModelFields . isEmpty ( ) ) { throw new RuntimeException ( \"The given view of type <\" + view . getClass ( ) + \"> has no generic viewModel type declared but tries to inject a viewModel.\" ) ; } } else { ResourceBundleInjector . injectResourceBundle ( viewModel , resourceBundle ) ; // if the user has provided an existing ViewModel, we will not // (re-)initialize this existing instance ViewLoaderReflectionUtils . createAndInjectScopes ( viewModel , context ) ; if ( existingViewModel == null ) { ViewLoaderReflectionUtils . initializeViewModel ( viewModel ) ; } ViewLoaderReflectionUtils . injectViewModel ( view , viewModel ) ; } if ( view instanceof Initializable ) { Initializable initializable = ( Initializable ) view ; initializable . initialize ( null , resourceBundle ) ; } else { injectResourceBundle ( view , resourceBundle ) ; callInitialize ( view ) ; } return new ViewTuple <> ( view , ( Parent ) view , viewModel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is trying to invoke the initialize method of the given view by reflection . This is done to meet the conventions of the { @link javafx . fxml . FXMLLoader } . The conventions say that when there is a <strong > public< / strong > no - args method with the simple name initialize and the class does not implement the { @link javafx . fxml . Initializable } interface the initialize method will be invoked . <br > This method is package scoped for better testability . [CODESPLIT] < ViewModelType extends ViewModel > void callInitialize ( View < ? extends ViewModelType > view ) { try { final Method initializeMethod = view . getClass ( ) . getMethod ( NAMING_CONVENTION_INITIALIZE_IDENTIFIER ) ; AccessController . doPrivileged ( ( PrivilegedAction ) ( ) -> { try { return initializeMethod . invoke ( view ) ; } catch ( InvocationTargetException e ) { LOG . warn ( \"The '{}' method of the view {} has thrown an exception!\" , NAMING_CONVENTION_INITIALIZE_IDENTIFIER , view ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else { throw new RuntimeException ( cause ) ; } } catch ( IllegalAccessException e ) { LOG . warn ( \"Can't invoke the '{}' method of the view {} because it is not accessible\" , NAMING_CONVENTION_INITIALIZE_IDENTIFIER , view ) ; } return null ; } ) ; } catch ( NoSuchMethodException e ) { // This exception means that there is no initialize method declared. // While it's possible that the user has no such method by design, // normally and in most cases you need an initialize method in your // view (either with Initialize interface // or implicit). // So it's likely that the user has misspelled the method name or // uses a wrong naming convention. // For this reason we give the user the log message. LOG . debug ( \"There is no '{}' method declared at the view {}\" , NAMING_CONVENTION_INITIALIZE_IDENTIFIER , view ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects the given ResourceBundle into the given view using reflection . This is done to meet the conventions of the { @link javafx . fxml . FXMLLoader } . The resourceBundle is only injected when there is a <strong > public< / strong > field of the type { @link java . util . ResourceBundle } named resources . <br > This method is package scoped for better testability . [CODESPLIT] < ViewModelType extends ViewModel > void injectResourceBundle ( View < ? extends ViewModelType > view , ResourceBundle resourceBundle ) { try { Field resourcesField = view . getClass ( ) . getField ( NAMING_CONVENTION_RESOURCES_IDENTIFIER ) ; if ( resourcesField . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) { resourcesField . set ( view , resourceBundle ) ; } } catch ( NoSuchFieldException e ) { // This exception means that there is no field for the // ResourceBundle. // This is no exceptional case but is normal when you don't need a // resourceBundle in a specific view. // Therefore it's save to silently catch the exception. } catch ( IllegalAccessException e ) { LOG . warn ( \"Can't inject the ResourceBundle into the view {} because the field isn't accessible\" , view ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When the given source binding has a value of <code > null< / code > an empty string is used for the returned binding . Otherwise the value of the source binding is used . [CODESPLIT] private StringBinding emptyStringOnNull ( ObservableValue < String > source ) { return Bindings . createStringBinding ( ( ) -> { if ( source . getValue ( ) == null ) { return \"\" ; } else { return source . getValue ( ) ; } } , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link java . lang . reflect . Field } of the viewModel for a given view type and viewModel type . If there is no annotated field for the viewModel in the view the returned Optional will be empty . [CODESPLIT] public static Optional < Field > getViewModelField ( Class < ? extends View > viewType , Class < ? > viewModelType ) { List < Field > allViewModelFields = getViewModelFields ( viewType ) ; if ( allViewModelFields . isEmpty ( ) ) { return Optional . empty ( ) ; } if ( allViewModelFields . size ( ) > 1 ) { throw new RuntimeException ( \"The View <\" + viewType + \"> may only define one viewModel but there were <\" + allViewModelFields . size ( ) + \"> viewModel fields with the @InjectViewModel annotation!\" ) ; } Field field = allViewModelFields . get ( 0 ) ; if ( ! ViewModel . class . isAssignableFrom ( field . getType ( ) ) ) { throw new RuntimeException ( \"The View <\" + viewType + \"> has a field annotated with @InjectViewModel but the type of the field doesn't implement the 'ViewModel' interface!\" ) ; } if ( ! field . getType ( ) . isAssignableFrom ( viewModelType ) ) { throw new RuntimeException ( \"The View <\" + viewType + \"> has a field annotated with @InjectViewModel but the type of the field doesn't match the generic ViewModel type of the View class. \" + \"The declared generic type is <\" + viewModelType + \"> but the actual type of the field is <\" + field . getType ( ) + \">.\" ) ; } return Optional . of ( field ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to get the ViewModel instance of a given view / codeBehind . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewModelType getExistingViewModel ( ViewType view ) { final Class < ? > viewModelType = TypeResolver . resolveRawArgument ( View . class , view . getClass ( ) ) ; Optional < Field > fieldOptional = getViewModelField ( view . getClass ( ) , viewModelType ) ; if ( fieldOptional . isPresent ( ) ) { Field field = fieldOptional . get ( ) ; return ReflectionUtils . accessMember ( field , ( ) -> ( ViewModelType ) field . get ( view ) , \"Can't get the viewModel of type <\" + viewModelType + \">\" ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Injects the given viewModel instance into the given view . The injection will only happen when the class of the given view has a viewModel field that fulfills all requirements for the viewModel injection ( matching types no viewModel already existing ... ) . [CODESPLIT] public static void injectViewModel ( final View view , ViewModel viewModel ) { if ( viewModel == null ) { return ; } final Optional < Field > fieldOptional = getViewModelField ( view . getClass ( ) , viewModel . getClass ( ) ) ; if ( fieldOptional . isPresent ( ) ) { Field field = fieldOptional . get ( ) ; ReflectionUtils . accessMember ( field , ( ) -> { Object existingViewModel = field . get ( view ) ; if ( existingViewModel == null ) { field . set ( view , viewModel ) ; } } , \"Can't inject ViewModel of type <\" + viewModel . getClass ( ) + \"> into the view <\" + view + \">\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to create and inject the ViewModel for a given View instance . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < V extends View < ? extends VM > , VM extends ViewModel > void createAndInjectViewModel ( final V view , Consumer < ViewModel > newVmConsumer ) { final Class < ? > viewModelType = TypeResolver . resolveRawArgument ( View . class , view . getClass ( ) ) ; if ( viewModelType == ViewModel . class ) { // if no viewModel can be created, we have to check if the user has // tried to inject a ViewModel final List < Field > viewModelFields = ViewLoaderReflectionUtils . getViewModelFields ( view . getClass ( ) ) ; if ( ! viewModelFields . isEmpty ( ) ) { throw new RuntimeException ( \"The given view of type <\" + view . getClass ( ) + \"> has no generic viewModel type declared but tries to inject a viewModel.\" ) ; } return ; } if ( viewModelType == TypeResolver . Unknown . class ) { return ; } final Optional < Field > fieldOptional = getViewModelField ( view . getClass ( ) , viewModelType ) ; if ( fieldOptional . isPresent ( ) ) { Field field = fieldOptional . get ( ) ; ReflectionUtils . accessMember ( field , ( ) -> { Object existingViewModel = field . get ( view ) ; if ( existingViewModel == null ) { final Object newViewModel = DependencyInjector . getInstance ( ) . getInstanceOf ( viewModelType ) ; field . set ( view , newViewModel ) ; newVmConsumer . accept ( ( ViewModel ) newViewModel ) ; } } , \"Can't inject ViewModel of type <\" + viewModelType + \"> into the view <\" + view + \">\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a viewModel instance for a View type . The type of the view is determined by the given view instance . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewModelType createViewModel ( ViewType view ) { final Class < ? > viewModelType = TypeResolver . resolveRawArgument ( View . class , view . getClass ( ) ) ; if ( viewModelType == ViewModel . class ) { return null ; } if ( TypeResolver . Unknown . class == viewModelType ) { return null ; } return ( ViewModelType ) DependencyInjector . getInstance ( ) . getInstanceOf ( viewModelType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a ViewModel has a method annotated with { @link Initialize } or method with the signature <code > public void initialize () < / code > it will be invoked . If no such method is available nothing happens . [CODESPLIT] public static < ViewModelType extends ViewModel > void initializeViewModel ( ViewModelType viewModel ) { if ( viewModel == null ) { return ; } final Collection < Method > initializeMethods = getInitializeMethods ( viewModel . getClass ( ) ) ; initializeMethods . forEach ( initMethod -> { // if there is a @PostConstruct annotation, throw an exception to prevent double injection final boolean postConstructPresent = Arrays . stream ( initMethod . getAnnotations ( ) ) . map ( Annotation :: annotationType ) . map ( Class :: getName ) . anyMatch ( \"javax.annotation.PostConstruct\" :: equals ) ; if ( postConstructPresent ) { throw new IllegalStateException ( String . format ( \"initialize method of ViewModel [%s] is annotated with @PostConstruct. \" + \"This will lead to unexpected behaviour and duplicate initialization. \" + \"Please rename the method or remove the @PostConstruct annotation. \" + \"See mvvmFX wiki for more details: \" + \"https://github.com/sialcasa/mvvmFX/wiki/Dependency-Injection#lifecycle-postconstruct\" , viewModel ) ) ; } ReflectionUtils . accessMember ( initMethod , ( ) -> initMethod . invoke ( viewModel ) , \"mvvmFX wasn't able to call the initialize method of ViewModel [\" + viewModel + \"].\" ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection of { [CODESPLIT] private static Collection < Method > getInitializeMethods ( Class < ? > classType ) { final List < Method > initializeMethods = new ArrayList <> ( ) ; Arrays . stream ( classType . getMethods ( ) ) . filter ( method -> \"initialize\" . equals ( method . getName ( ) ) ) . filter ( method -> void . class . equals ( method . getReturnType ( ) ) ) . filter ( method -> method . getParameterCount ( ) == 0 ) . forEach ( initializeMethods :: add ) ; Arrays . stream ( classType . getDeclaredMethods ( ) ) . filter ( method -> method . isAnnotationPresent ( Initialize . class ) ) . forEach ( initializeMethods :: add ) ; return initializeMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method adds listeners for the { [CODESPLIT] static void addSceneLifecycleHooks ( ViewModel viewModel , ObservableBooleanValue viewInSceneProperty ) { if ( viewModel != null ) { if ( viewModel instanceof SceneLifecycle ) { SceneLifecycle lifecycleViewModel = ( SceneLifecycle ) viewModel ; PreventGarbageCollectionStore . getInstance ( ) . put ( viewInSceneProperty ) ; viewInSceneProperty . addListener ( ( observable , oldValue , newValue ) -> { if ( newValue ) { lifecycleViewModel . onViewAdded ( ) ; } else { lifecycleViewModel . onViewRemoved ( ) ; PreventGarbageCollectionStore . getInstance ( ) . remove ( viewInSceneProperty ) ; } } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to check if the given View instance has one or more fields that try to inject a scope with the { [CODESPLIT] static void checkScopesInView ( View codeBehind ) { List < Field > scopeFields = ReflectionUtils . getFieldsWithAnnotation ( codeBehind , InjectScope . class ) ; if ( ! scopeFields . isEmpty ( ) ) { throw new IllegalStateException ( \"The view class [\" + codeBehind . getClass ( ) . getSimpleName ( ) + \"] tries to inject a Scope with \" + \"@InjectScope. This would be a violation of the mvvm pattern. Scopes are only supported in ViewModels.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the currently selected country . This will lead to an update of the { @link #subdivisions () } observable list and the { @link #subdivisionLabel () } . [CODESPLIT] @ Override public void setCountry ( Country country ) { if ( country == null ) { subdivisionLabel . set ( null ) ; subdivisions . clear ( ) ; return ; } subdivisionLabel . set ( countryCodeSubdivisionNameMap . get ( country ) ) ; subdivisions . clear ( ) ; if ( countryCodeSubdivisionMap . containsKey ( country ) ) { subdivisions . addAll ( countryCodeSubdivisionMap . get ( country ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load all countries from the XML file source with DataFX . [CODESPLIT] void loadCountries ( ) { InputStream iso3166Resource = this . getClass ( ) . getResourceAsStream ( ISO_3166_LOCATION ) ; if ( iso3166Resource == null ) { throw new IllegalStateException ( \"Can't find the list of countries! Expected location was:\" + ISO_3166_LOCATION ) ; } XmlConverter < Country > countryConverter = new XmlConverter <> ( \"iso_3166_entry\" , Country . class ) ; try { DataReader < Country > dataSource = new InputStreamSource <> ( iso3166Resource , countryConverter ) ; ListDataProvider < Country > listDataProvider = new ListDataProvider <> ( dataSource ) ; listDataProvider . setResultObservableList ( countries ) ; Worker < ObservableList < Country > > worker = listDataProvider . retrieve ( ) ; // when the countries are loaded we start the loading of the subdivisions. worker . stateProperty ( ) . addListener ( obs -> { if ( worker . getState ( ) == Worker . State . SUCCEEDED ) { loadSubdivisions ( ) ; } } ) ; } catch ( IOException e ) { LOG . error ( \"A problem was detected while loading the XML file with the available countries.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load all subdivisions from the XML file source with DataFX . [CODESPLIT] void loadSubdivisions ( ) { InputStream iso3166_2Resource = this . getClass ( ) . getResourceAsStream ( ISO_3166_2_LOCATION ) ; if ( iso3166_2Resource == null ) { throw new IllegalStateException ( \"Can't find the list of subdivisions! Expected location was:\" + ISO_3166_2_LOCATION ) ; } XmlConverter < ISO3166_2_CountryEntity > converter = new XmlConverter <> ( \"iso_3166_country\" , ISO3166_2_CountryEntity . class ) ; ObservableList < ISO3166_2_CountryEntity > subdivisionsEntities = FXCollections . observableArrayList ( ) ; try { DataReader < ISO3166_2_CountryEntity > dataSource = new InputStreamSource <> ( iso3166_2Resource , converter ) ; ListDataProvider < ISO3166_2_CountryEntity > listDataProvider = new ListDataProvider <> ( dataSource ) ; listDataProvider . setResultObservableList ( subdivisionsEntities ) ; Worker < ObservableList < ISO3166_2_CountryEntity > > worker = listDataProvider . retrieve ( ) ; worker . stateProperty ( ) . addListener ( obs -> { if ( worker . getState ( ) == Worker . State . SUCCEEDED ) { subdivisionsEntities . forEach ( entity -> { if ( entity . subsets != null && ! entity . subsets . isEmpty ( ) ) { Country country = findCountryByCode ( entity . code ) ; if ( ! countryCodeSubdivisionMap . containsKey ( country ) ) { countryCodeSubdivisionMap . put ( country , new ArrayList <> ( ) ) ; } List < Subdivision > subdivisionList = countryCodeSubdivisionMap . get ( country ) ; entity . subsets . forEach ( subset -> { subset . entryList . forEach ( entry -> { subdivisionList . add ( new Subdivision ( entry . name , entry . code , country ) ) ; } ) ; } ) ; String subdivisionName = entity . subsets . stream ( ) . map ( subset -> subset . subdivisionType ) . collect ( Collectors . joining ( \"/\" ) ) ; countryCodeSubdivisionNameMap . put ( country , subdivisionName ) ; } } ) ; inProgress . set ( false ) ; } } ) ; } catch ( IOException e ) { LOG . error ( \"A problem was detected while loading the XML file with the available subdivisions.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This notification will be send to the UI - Thread ( if the UI - toolkit was bootstrapped ) . If no UI - Toolkit is available the notification will be directly published . This is typically the case in unit tests . [CODESPLIT] @ Override public void publish ( Object channel , String messageName , Object [ ] payload ) { if ( channelObserverMap . containsKey ( channel ) ) { final ObserverMap observerMap = channelObserverMap . get ( channel ) ; if ( shouldPublishInThisThread ( ) ) { publish ( messageName , payload , observerMap ) ; } else { try { Platform . runLater ( ( ) -> publish ( messageName , payload , observerMap ) ) ; } catch ( IllegalStateException e ) { // If the toolkit isn't initialized yet we will publish the notification directly. // In most cases this means that we are in a unit test and not JavaFX application is running. if ( e . getMessage ( ) . equals ( \"Toolkit not initialized\" ) ) { publish ( messageName , payload , observerMap ) ; } else { throw e ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Helper [CODESPLIT] private static void publish ( String messageName , Object [ ] payload , ObserverMap observerMap ) { Collection < NotificationObserver > notificationReceivers = observerMap . get ( messageName ) ; if ( notificationReceivers != null ) { // make a copy to prevent ConcurrentModificationException if inside of an observer a new observer is subscribed. for ( NotificationObserver observer : notificationReceivers ) { observer . receivedNotification ( messageName , payload ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is invoked when the javafx application is initialized . See { @link javafx . application . Application#init () } for more details . <p > Unlike the original init method in { @link javafx . application . Application } this method contains logic to initialize the Spring - Boot container . For this reason this method is now final to prevent unintended overriding . Please use { @link #initMvvmfx () } for you own initialization logic . [CODESPLIT] @ Override public final void init ( ) throws Exception { ctx = SpringApplication . run ( this . getClass ( ) ) ; MvvmFX . setCustomDependencyInjector ( ctx :: getBean ) ; ctx . getBeanFactory ( ) . autowireBean ( this ) ; initMvvmfx ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets all defined fields to their default values . <p > Default values can be defined as last argument of the overloaded field methods ( see { @link #field ( StringGetter StringSetter String ) } ) or by using the { @link #useCurrentValuesAsDefaults () } method . [CODESPLIT] public void reset ( ) { fields . forEach ( PropertyField :: resetToDefault ) ; immutableFields . forEach ( PropertyField :: resetToDefault ) ; calculateDifferenceFlag ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use all values that are currently present in the wrapped model object as new default values for respective fields . This overrides / updates the values that were set during the initialization of the field mappings . <p > Subsequent calls to { @link #reset () } will reset the values to this new default values . <p > Usage example : <pre > ModelWrapper { @code<Person > } wrapper = new ModelWrapper { @code< > } () ; [CODESPLIT] public void useCurrentValuesAsDefaults ( ) { M wrappedModelInstance = model . get ( ) ; if ( wrappedModelInstance != null ) { for ( final PropertyField < ? , M , ? > field : fields ) { field . updateDefault ( wrappedModelInstance ) ; } for ( final ImmutablePropertyField < ? , M , ? > field : immutableFields ) { field . updateDefault ( wrappedModelInstance ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take the current value of each property field and write it into the wrapped model element . <p > If no model element is defined then nothing will happen . <p > <b > Note : < / b > This method has no effects on the values of the defined property fields but will only change the state of the wrapped model element . [CODESPLIT] public void commit ( ) { if ( model . get ( ) != null ) { inCommitPhase = true ; fields . forEach ( field -> field . commit ( model . get ( ) ) ) ; if ( ! immutableFields . isEmpty ( ) ) { M tmp = model . get ( ) ; for ( ImmutablePropertyField < ? , M , ? > immutableField : immutableFields ) { tmp = immutableField . commitImmutable ( tmp ) ; } model . set ( tmp ) ; } inCommitPhase = false ; dirtyFlag . set ( false ) ; calculateDifferenceFlag ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take the current values from the wrapped model element and put them in the corresponding property fields . <p > If no model element is defined then nothing will happen . <p > <b > Note : < / b > This method has no effects on the wrapped model element but will only change the values of the defined property fields . [CODESPLIT] public void reload ( ) { M wrappedModelInstance = model . get ( ) ; if ( wrappedModelInstance != null ) { fields . forEach ( field -> field . reload ( wrappedModelInstance ) ) ; immutableFields . forEach ( field -> field . reload ( wrappedModelInstance ) ) ; dirtyFlag . set ( false ) ; calculateDifferenceFlag ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method can be used to copy all values of this { @link ModelWrapper } instance to the model instance provided as argument . Existing values in the provided model instance will be overwritten . <p > This method doesn t change the state of this modelWrapper or the wrapped model instance . [CODESPLIT] public void copyValuesTo ( M model ) { Objects . requireNonNull ( model ) ; fields . forEach ( field -> field . commit ( model ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new field of type String to this instance of the wrapper . This method is used for model elements that are following the normal Java - Beans - standard i . e . the model fields are only available via getter and setter methods and not as JavaFX Properties . [CODESPLIT] public StringProperty field ( StringGetter < M > getter , StringSetter < M > setter ) { return add ( new BeanPropertyField <> ( this :: propertyWasChanged , getter , setter , SimpleStringProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new immutable field of type String to this instance of the wrapper . This method is used for immutable model elements that have getters to get values for it s fields but not setters . Instead immutables have methods that take a new value for a field and return a new cloned instance of the model element with only this field updated to the new value . The old model instance isn t changed . [CODESPLIT] public StringProperty immutableField ( StringGetter < M > getter , StringImmutableSetter < M > immutableSetter ) { return addImmutable ( new ImmutableBeanPropertyField <> ( this :: propertyWasChanged , getter , immutableSetter , SimpleStringProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new field of type { @link String } to this instance of the wrapper . This method is used for model elements that are following the enhanced JavaFX - Beans - standard i . e . the model fields are available as JavaFX Properties . <p > [CODESPLIT] public StringProperty field ( StringPropertyAccessor < M > accessor ) { return add ( new FxPropertyField <> ( this :: propertyWasChanged , accessor , SimpleStringProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new field of type String to this instance of the wrapper . See { @link #field ( StringGetter StringSetter ) } . This method additionally takes a string identifier as first parameter . <p / > This identifier is used to return the same property instance even when the method is invoked multiple times . [CODESPLIT] public StringProperty field ( String identifier , StringGetter < M > getter , StringSetter < M > setter ) { return addIdentified ( identifier , new BeanPropertyField <> ( this :: propertyWasChanged , getter , setter , ( ) -> new SimpleStringProperty ( null , identifier ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new immutable field of type String to this instance of the wrapper . See { @link #immutableField ( StringGetter StringImmutableSetter } ) . This method additionally takes a string identifier as first parameter . <p / > This identifier is used to return the same property instance even when the method is invoked multiple times . [CODESPLIT] public StringProperty immutableField ( String identifier , StringGetter < M > getter , StringImmutableSetter < M > immutableSetter ) { return addIdentifiedImmutable ( identifier , new ImmutableBeanPropertyField <> ( this :: propertyWasChanged , getter , immutableSetter , ( ) -> new SimpleStringProperty ( null , identifier ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new field of type String to this instance of the wrapper . See { @link #field ( StringPropertyAccessor ) } . This method additionally takes a string identifier as first parameter . [CODESPLIT] public StringProperty field ( String identifier , StringPropertyAccessor < M > accessor ) { return addIdentified ( identifier , new FxPropertyField <> ( this :: propertyWasChanged , accessor , ( ) -> new SimpleStringProperty ( null , identifier ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type Boolean [CODESPLIT] public BooleanProperty field ( BooleanGetter < M > getter , BooleanSetter < M > setter ) { return add ( new BeanPropertyField <> ( this :: propertyWasChanged , getter , setter , SimpleBooleanProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type Double [CODESPLIT] public DoubleProperty field ( DoubleGetter < M > getter , DoubleSetter < M > setter ) { return add ( new BeanPropertyField <> ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . doubleValue ( ) ) , SimpleDoubleProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type Float [CODESPLIT] public FloatProperty field ( FloatGetter < M > getter , FloatSetter < M > setter ) { return add ( new BeanPropertyField <> ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . floatValue ( ) ) , SimpleFloatProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type Integer [CODESPLIT] public IntegerProperty field ( IntGetter < M > getter , IntSetter < M > setter ) { return add ( new BeanPropertyField <> ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . intValue ( ) ) , SimpleIntegerProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type Long [CODESPLIT] public LongProperty field ( LongGetter < M > getter , LongSetter < M > setter ) { return add ( new BeanPropertyField <> ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . longValue ( ) ) , SimpleLongProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type generic [CODESPLIT] public < T > ObjectProperty < T > field ( ObjectGetter < M , T > getter , ObjectSetter < M , T > setter ) { return add ( new BeanPropertyField <> ( this :: propertyWasChanged , getter , setter , SimpleObjectProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type list [CODESPLIT] public < E > ListProperty < E > field ( ListGetter < M , E > getter , ListSetter < M , E > setter ) { return add ( new BeanListPropertyField <> ( this :: propertyWasChanged , getter , ( m , list ) -> setter . accept ( m , FXCollections . observableArrayList ( list ) ) , SimpleListProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This helper method is needed because there is no equivalent of { [CODESPLIT] private static < T > ObservableSet < T > observableHashSet ( Set < T > source ) { return FXCollections . observableSet ( new HashSet <> ( source ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Field type map [CODESPLIT] public < K , V > MapProperty < K , V > field ( MapGetter < M , K , V > getter , MapSetter < M , K , V > setter ) { return add ( new BeanMapPropertyField <> ( this :: propertyWasChanged , getter , ( m , map ) -> setter . accept ( m , FXCollections . observableMap ( map ) ) , SimpleMapProperty :: new ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a rule for this validator . <p > The rule defines a condition that has to be fulfilled . <p > A rule is defined by an observable boolean value . If the rule has a value of <code > true< / code > the rule is fulfilled . If the rule has a value of <code > false< / code > the rule is violated . In this case the given message object will be added to the status of this validator . <p > There are some predefined rules for common use cases in the { @link ObservableRules } class that can be used . [CODESPLIT] public void addRule ( ObservableValue < Boolean > rule , ValidationMessage message ) { booleanRules . add ( rule ) ; rule . addListener ( ( observable , oldValue , newValue ) -> { validateBooleanRule ( newValue , message ) ; } ) ; validateBooleanRule ( rule . getValue ( ) , message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a complex rule for this validator . <p > The rule is defined by an { @link ObservableValue } . If this observable contains a { @link ValidationMessage } object the rule is considered to be violated and the { @link ValidationStatus } of this validator will contain the validation message object contained in the observable value . If the observable doesn t contain a value ( in other words it contains <code > null< / code > ) the rule is considered to be fulfilled and the validation status of this validator will be valid ( given that no other rule is violated ) . <p > [CODESPLIT] public void addRule ( ObservableValue < ValidationMessage > rule ) { complexRules . add ( rule ) ; rule . addListener ( ( observable , oldValue , newValue ) -> { if ( oldValue != null ) { validationStatus . removeMessage ( oldValue ) ; } if ( newValue != null ) { validationStatus . addMessage ( newValue ) ; } } ) ; if ( rule . getValue ( ) != null ) { validationStatus . addMessage ( rule . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an observable list that always has { [CODESPLIT] static ObservableList < String > createListWithNothingSelectedMarker ( ObservableList < String > source ) { final ObservableList < String > result = FXCollections . observableArrayList ( ) ; result . add ( NOTHING_SELECTED_MARKER ) ; result . addAll ( source ) ; // for sure there are better solutions for this but it's sufficient for our demo source . addListener ( ( ListChangeListener < String > ) c -> { result . clear ( ) ; result . add ( NOTHING_SELECTED_MARKER ) ; result . addAll ( source ) ; } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is the entry point of the Fluent API to load a java based view . [CODESPLIT] public static < ViewType extends JavaView < ? extends ViewModelType > , ViewModelType extends ViewModel > JavaViewStep < ViewType , ViewModelType > javaView ( Class < ? extends ViewType > viewType ) { return new JavaViewStep <> ( viewType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is the entry point of the Fluent API to load a fxml based View . [CODESPLIT] public static < ViewType extends FxmlView < ? extends ViewModelType > , ViewModelType extends ViewModel > FxmlViewStep < ViewType , ViewModelType > fxmlView ( Class < ? extends ViewType > viewType ) { return new FxmlViewStep <> ( viewType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the given { @link ChangeListener } to the { @link ObservableValue } . The listener is added to the observable and will be added for management so it can be cleaned up with the { @link #clean () } method . [CODESPLIT] public < T > void register ( ObservableValue < T > observable , ChangeListener < ? super T > listener ) { if ( ! simpleChangeListeners . containsKey ( observable ) ) { this . simpleChangeListeners . put ( observable , Collections . newSetFromMap ( new WeakHashMap <> ( ) ) ) ; } Set < ChangeListener > observers = this . simpleChangeListeners . get ( observable ) ; observers . add ( listener ) ; observable . addListener ( listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the given { @link ListChangeListener } to the { @link ObservableList } . The listener is added to the observable and will be added for management so it can be cleaned up with the { @link #clean () } method . [CODESPLIT] public < T > void register ( ObservableList < T > observable , ListChangeListener < ? super T > listener ) { if ( ! listChangeListeners . containsKey ( observable ) ) { this . listChangeListeners . put ( observable , Collections . newSetFromMap ( new WeakHashMap <> ( ) ) ) ; } Set < ListChangeListener > observers = this . listChangeListeners . get ( observable ) ; observers . add ( listener ) ; observable . addListener ( listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the given { @link InvalidationListener } to the { @link Observable } . The listener is added to the observable and will be added for management so it can be cleaned up with the { @link #clean () } method . [CODESPLIT] public void register ( Observable observable , InvalidationListener listener ) { if ( ! invalidationListeners . containsKey ( observable ) ) { this . invalidationListeners . put ( observable , Collections . newSetFromMap ( new WeakHashMap <> ( ) ) ) ; } Set < InvalidationListener > observers = this . invalidationListeners . get ( observable ) ; observers . add ( listener ) ; observable . addListener ( listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to clear the given map . To do this you need to implement a BiConsumer that calls the specific method to remove a listener from an observable . [CODESPLIT] private < T , U > void clearMap ( Map < T , Set < U > > map , BiConsumer < T , U > consumer ) { for ( T observable : map . keySet ( ) ) { for ( U listener : map . get ( observable ) ) { consumer . accept ( observable , listener ) ; } } map . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is overridden to initialize the mvvmFX framework . Override the { [CODESPLIT] @ Override public final void start ( Stage primaryStage ) throws Exception { producer . setPrimaryStage ( primaryStage ) ; startMvvmfx ( primaryStage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called when the javafx application is initialized . See { @link javafx . application . Application#init () } for more details . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public final void init ( ) throws Exception { ctx = beanManager . createCreationalContext ( null ) ; injectionTarget = beanManager . createInjectionTarget ( beanManager . createAnnotatedType ( ( Class < MvvmfxCdiApplication > ) this . getClass ( ) ) ) ; injectionTarget . inject ( this , ctx ) ; injectionTarget . postConstruct ( this ) ; producer . setApplicationParameters ( getParameters ( ) ) ; initMvvmfx ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called when the application should stop . See { @link javafx . application . Application#stop () } for more details . [CODESPLIT] @ Override public final void stop ( ) throws Exception { stopMvvmfx ( ) ; injectionTarget . preDestroy ( this ) ; injectionTarget . dispose ( this ) ; ctx . release ( ) ; container . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When the selected item changed we want to set the index property too [CODESPLIT] private void createIndexEvents ( ) { selectionModel . selectedIndexProperty ( ) . addListener ( ( bean , oldVal , newVal ) -> { int index = newVal . intValue ( ) ; ListType item = index == - 1 ? null : modelListProperty ( ) . get ( index ) ; selectedItem . set ( item ) ; } ) ; selectedItem . addListener ( ( observable , oldVal , newVal ) -> { // Item null if ( newVal == null ) { selectionModel . select ( - 1 ) ; selectedItem . set ( null ) ; } else { int index = modelListProperty ( ) . get ( ) . indexOf ( newVal ) ; // Item not found if ( index != - 1 ) { selectionModel . select ( index ) ; } else { // If item not found - Rollback selectedItem . set ( oldVal ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all fields with the given annotation . Only fields that are declared in the actual class of the instance are considered ( i . e . no fields from super classes ) . This includes private fields . [CODESPLIT] public static List < Field > getFieldsWithAnnotation ( Object target , Class < ? extends Annotation > annotationType ) { return ReflectionUtils . getFieldsFromClassHierarchy ( target . getClass ( ) ) . stream ( ) . filter ( field -> field . isAnnotationPresent ( annotationType ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all fields of the given type and all parent types ( except Object ) . <br > The difference to { @link Class#getFields () } is that getFields only returns public fields while this method will return all fields whatever the access modifier is . <br > [CODESPLIT] public static List < Field > getFieldsFromClassHierarchy ( Class < ? > type ) { final List < Field > classFields = new ArrayList <> ( ) ; classFields . addAll ( Arrays . asList ( type . getDeclaredFields ( ) ) ) ; final Class < ? > parentClass = type . getSuperclass ( ) ; if ( parentClass != null && ! ( parentClass . equals ( Object . class ) ) ) { List < Field > parentClassFields = getFieldsFromClassHierarchy ( parentClass ) ; classFields . addAll ( parentClassFields ) ; } return classFields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to execute a callback on a given member . This method encapsulates the error handling logic and the handling of accessibility of the member . [CODESPLIT] public static < T > T accessMember ( final AccessibleObject member , final Callable < T > callable , String errorMessage ) { if ( callable == null ) { return null ; } return AccessController . doPrivileged ( ( PrivilegedAction < T > ) ( ) -> { boolean wasAccessible = member . isAccessible ( ) ; try { member . setAccessible ( true ) ; return callable . call ( ) ; } catch ( Exception exception ) { throw new IllegalStateException ( errorMessage , exception ) ; } finally { member . setAccessible ( wasAccessible ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method can be used to set ( private / public ) fields to a given value by reflection . Handling of accessibility and errors is encapsulated . [CODESPLIT] public static void setField ( final Field field , Object target , Object value ) { accessMember ( field , ( ) -> field . set ( target , value ) , \"Cannot set the field [\" + field . getName ( ) + \"] of instance [\" + target + \"] to value [\" + value + \"]\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to execute a callback on a given member . This method encapsulates the error handling logic and the handling of accessibility of the member . The difference to { @link ReflectionUtils#accessMember ( AccessibleObject Callable String ) } is that this method takes a callback that doesn t return anything but only creates a sideeffect . [CODESPLIT] public static void accessMember ( final AccessibleObject member , final SideEffectWithException sideEffect , String errorMessage ) { if ( sideEffect == null ) { return ; } AccessController . doPrivileged ( ( PrivilegedAction < ? > ) ( ) -> { boolean wasAccessible = member . isAccessible ( ) ; try { member . setAccessible ( true ) ; sideEffect . call ( ) ; } catch ( Exception exception ) { throw new IllegalStateException ( errorMessage , exception ) ; } finally { member . setAccessible ( wasAccessible ) ; } return null ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the viewTuple by it s ViewType . [CODESPLIT] public < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewTuple < ViewType , ViewModelType > loadFxmlViewTuple ( Class < ? extends ViewType > viewType , ResourceBundle resourceBundle , ViewType codeBehind , Object root , ViewModelType viewModel , Context context , Collection < Scope > providedScopes , List < BuilderFactory > builderFactories ) { final String pathToFXML = createFxmlPath ( viewType ) ; return loadFxmlViewTuple ( viewType , pathToFXML , resourceBundle , codeBehind , root , viewModel , context , providedScopes , builderFactories ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to create a String with the path to the FXML file for a given View class . [CODESPLIT] private String createFxmlPath ( Class < ? > viewType ) { final StringBuilder pathBuilder = new StringBuilder ( ) ; final FxmlPath pathAnnotation = viewType . getDeclaredAnnotation ( FxmlPath . class ) ; //Get annotation from view final String fxmlPath = Optional . ofNullable ( pathAnnotation ) . map ( FxmlPath :: value ) . map ( String :: trim ) . orElse ( \"\" ) ; if ( fxmlPath . isEmpty ( ) ) { pathBuilder . append ( \"/\" ) ; if ( viewType . getPackage ( ) != null ) { pathBuilder . append ( viewType . getPackage ( ) . getName ( ) . replaceAll ( \"\\\\.\" , \"/\" ) ) ; pathBuilder . append ( \"/\" ) ; } pathBuilder . append ( viewType . getSimpleName ( ) ) ; pathBuilder . append ( \".fxml\" ) ; } else { pathBuilder . append ( fxmlPath ) ; } return pathBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the viewTuple by the path of the fxml file . [CODESPLIT] public < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewTuple < ViewType , ViewModelType > loadFxmlViewTuple ( final String resource , ResourceBundle resourceBundle , final ViewType codeBehind , final Object root , ViewModelType viewModel , Context parentContext , Collection < Scope > providedScopes , List < BuilderFactory > builderFactories ) { return loadFxmlViewTuple ( null , resource , resourceBundle , codeBehind , root , viewModel , parentContext , providedScopes , builderFactories ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the viewTuple by the path of the fxml file . [CODESPLIT] private < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewTuple < ViewType , ViewModelType > loadFxmlViewTuple ( final Class < ? > resourceLoader , final String resource , ResourceBundle resourceBundle , final ViewType codeBehind , final Object root , ViewModelType viewModel , Context parentContext , Collection < Scope > providedScopes , List < BuilderFactory > builderFactories ) { try { // FIXME Woanders hin? ContextImpl context = ViewLoaderScopeUtils . prepareContext ( parentContext , providedScopes ) ; ////////////////////////////////////////////////////////////////////// // for the SceneLifecycle we need to know when the view is put into the scene BooleanProperty viewInSceneProperty = new SimpleBooleanProperty ( ) ; final FXMLLoader loader = createFxmlLoader ( resourceLoader , resource , resourceBundle , codeBehind , root , viewModel , context , viewInSceneProperty , builderFactories ) ; loader . load ( ) ; final ViewType loadedController = loader . getController ( ) ; final Parent loadedRoot = loader . getRoot ( ) ; viewInSceneProperty . bind ( loadedRoot . sceneProperty ( ) . isNotNull ( ) ) ; if ( loadedController == null ) { throw new IOException ( \"Could not load the controller for the View \" + resource + \" maybe your missed the fx:controller in your fxml?\" ) ; } // the actually used ViewModel instance. We need this so we can // return it in the ViewTuple ViewModelType actualViewModel ; // FIXME CONTEXT // if no existing viewModel was provided... if ( viewModel == null ) { // ... we try to find the created ViewModel from the codeBehind. // this is only possible when the codeBehind has a field for the // VM and the VM was injected actualViewModel = ViewLoaderReflectionUtils . getExistingViewModel ( loadedController ) ; // otherwise we create a new ViewModel. This is needed because // the ViewTuple has to contain a VM even if // the codeBehind doesn't need one if ( actualViewModel == null ) { actualViewModel = ViewLoaderReflectionUtils . createViewModel ( loadedController ) ; // it is possible that no viewModel could be created (f.e. // when no generic VM type was specified) // otherwise we need to initialize the created ViewModel // instance. if ( actualViewModel != null ) { ViewLoaderReflectionUtils . initializeViewModel ( actualViewModel ) ; } } } else { actualViewModel = viewModel ; } if ( actualViewModel != null ) { // TODO: Create Testcase for this corner case: // If this view is the root view (the one that is loaded with // the FluentViewLoader) // but in the view there is no injection of the ViewModel // only in this case the scope has to be injected here, // If the viewModel was already injected in the View, it has // it's scopes already injected // ViewLoaderReflectionUtils.createAndInjectScopes(actualViewModel, // context); } return new ViewTuple <> ( loadedController , loadedRoot , actualViewModel ) ; } catch ( final IOException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for the style row from a style mapping row [CODESPLIT] public StyleRow queryForRow ( StyleMappingRow styleMappingRow ) { StyleRow styleRow = null ; AttributesRow attributesRow = queryForIdRow ( styleMappingRow . getRelatedId ( ) ) ; if ( attributesRow != null ) { styleRow = getRow ( attributesRow ) ; } return styleRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void setValue ( int index , Object value ) { if ( index == getGeometryColumnIndex ( ) && value instanceof byte [ ] ) { byte [ ] bytes = ( byte [ ] ) value ; value = new GeoPackageGeometryData ( bytes ) ; } super . setValue ( index , value ) ; } /**\n     * Get the geometry\n     *\n     * @return geometry data\n     */ public GeoPackageGeometryData getGeometry ( ) { GeoPackageGeometryData geometryData = null ; Object value = getValue ( getGeometryColumnIndex ( ) ) ; if ( value != null ) { geometryData = ( GeoPackageGeometryData ) value ; } return geometryData ; } /**\n     * Set the geometry data\n     *\n     * @param geometryData geometry data\n     */ public void setGeometry ( GeoPackageGeometryData geometryData ) { setValue ( getGeometryColumnIndex ( ) , geometryData ) ; } /**\n     * Get the simple features geometry value\n     *\n     * @return geometry\n     * @since 3.1.0\n     */ public Geometry getGeometryValue ( ) { GeoPackageGeometryData data = getGeometry ( ) ; Geometry geometry = null ; if ( data != null ) { geometry = data . getGeometry ( ) ; } return geometry ; } /**\n     * Get the simple features geometry type\n     *\n     * @return geometry type\n     * @since 3.2.0\n     */ public GeometryType getGeometryType ( ) { Geometry geometry = getGeometryValue ( ) ; GeometryType geometryType = null ; if ( geometry != null ) { geometryType = geometry . getGeometryType ( ) ; } return geometryType ; } /**\n     * Get the geometry envelope\n     *\n     * @return geometry envelope\n     * @since 3.1.0\n     */ public GeometryEnvelope getGeometryEnvelope ( ) { GeoPackageGeometryData data = getGeometry ( ) ; GeometryEnvelope envelope = null ; if ( data != null ) { envelope = data . getOrBuildEnvelope ( ) ; } return envelope ; } /**\n     * Copy the row\n     *\n     * @return row copy\n     * @since 3.0.1\n     */ public FeatureRow copy ( ) { return new FeatureRow ( this ) ; } /**\n     * {@inheritDoc}\n     * Handles geometry columns\n     */ @ Override protected Object copyValue ( FeatureColumn column , Object value ) { Object copyValue = null ; if ( column . isGeometry ( ) && value instanceof GeoPackageGeometryData ) { GeoPackageGeometryData geometryData = ( GeoPackageGeometryData ) value ; try { byte [ ] bytes = geometryData . toBytes ( ) ; byte [ ] copyBytes = Arrays . copyOf ( bytes , bytes . length ) ; copyValue = new GeoPackageGeometryData ( copyBytes ) ; } catch ( IOException e ) { throw new GeoPackageException ( \"Failed to copy Geometry Data bytes. column: \" + column . getName ( ) , e ) ; } } else { copyValue = super . copyValue ( column , value ) ; } return copyValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void columnToContentValue ( ContentValues contentValues , FeatureColumn column , Object value ) { if ( column . isGeometry ( ) ) { String columnName = column . getName ( ) ; if ( value instanceof GeoPackageGeometryData ) { GeoPackageGeometryData geometryData = ( GeoPackageGeometryData ) value ; try { contentValues . put ( columnName , geometryData . toBytes ( ) ) ; } catch ( IOException e ) { throw new GeoPackageException ( \"Failed to write Geometry Data bytes. column: \" + columnName , e ) ; } } else if ( value instanceof byte [ ] ) { contentValues . put ( columnName , ( byte [ ] ) value ) ; } else { throw new GeoPackageException ( \"Unsupported update geometry column value type. column: \" + columnName + \", value type: \" + value . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public double getValue ( GriddedTile griddedTile , TileRow tileRow , int x , int y ) { byte [ ] imageBytes = tileRow . getTileData ( ) ; double value = getValue ( griddedTile , imageBytes , x , y ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Double getValue ( GriddedTile griddedTile , CoverageDataPngImage image , int x , int y ) { Double value = null ; if ( image . getReader ( ) != null ) { int pixelValue = image . getPixel ( x , y ) ; value = getValue ( griddedTile , pixelValue ) ; } else { value = getValue ( griddedTile , image . getImageBytes ( ) , x , y ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pixel value as a 16 bit unsigned integer value [CODESPLIT] public int getPixelValue ( byte [ ] imageBytes , int x , int y ) { PngReaderInt reader = new PngReaderInt ( new ByteArrayInputStream ( imageBytes ) ) ; validateImageType ( reader ) ; ImageLineInt row = ( ImageLineInt ) reader . readRow ( y ) ; int pixelValue = row . getScanline ( ) [ x ] ; reader . close ( ) ; return pixelValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pixel values of the image as 16 bit unsigned integer values [CODESPLIT] public int [ ] getPixelValues ( byte [ ] imageBytes ) { PngReaderInt reader = new PngReaderInt ( new ByteArrayInputStream ( imageBytes ) ) ; validateImageType ( reader ) ; int [ ] pixels = new int [ reader . imgInfo . cols * reader . imgInfo . rows ] ; int rowNumber = 0 ; while ( reader . hasMoreRows ( ) ) { ImageLineInt row = reader . readRowInt ( ) ; int [ ] rowValues = row . getScanline ( ) ; System . arraycopy ( rowValues , 0 , pixels , rowNumber * reader . imgInfo . cols , rowValues . length ) ; rowNumber ++ ; } reader . close ( ) ; return pixels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that the image type is single channel 16 bit [CODESPLIT] public static void validateImageType ( PngReader reader ) { if ( reader == null ) { throw new GeoPackageException ( \"The image is null\" ) ; } if ( reader . imgInfo . channels != 1 || reader . imgInfo . bitDepth != 16 ) { throw new GeoPackageException ( \"The coverage data tile is expected to be a single channel 16 bit unsigned short, channels: \" + reader . imgInfo . channels + \", bits: \" + reader . imgInfo . bitDepth ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a coverage data tile from the double array of unsigned short pixel values formatted as short [ row ] [ width ] [CODESPLIT] public CoverageDataPngImage drawTile ( short [ ] [ ] pixelValues ) { int tileWidth = pixelValues [ 0 ] . length ; int tileHeight = pixelValues . length ; CoverageDataPngImage image = createImage ( tileWidth , tileHeight ) ; PngWriter writer = image . getWriter ( ) ; for ( int y = 0 ; y < tileHeight ; y ++ ) { ImageLineInt row = new ImageLineInt ( writer . imgInfo , new int [ tileWidth ] ) ; int [ ] rowLine = row . getScanline ( ) ; for ( int x = 0 ; x < tileWidth ; x ++ ) { short pixelValue = pixelValues [ y ] [ x ] ; setPixelValue ( rowLine , x , pixelValue ) ; } writer . writeRow ( row ) ; } writer . end ( ) ; image . flushStream ( ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a coverage data tile and format as PNG bytes from the double array of unsigned short pixel values formatted as short [ row ] [ width ] [CODESPLIT] public byte [ ] drawTileData ( short [ ] [ ] pixelValues ) { CoverageDataPngImage image = drawTile ( pixelValues ) ; byte [ ] bytes = image . getImageBytes ( ) ; return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a coverage data image tile and format as PNG bytes from the double array of unsigned 16 bit integer pixel values formatted as int [ row ] [ width ] [CODESPLIT] public byte [ ] drawTileData ( int [ ] [ ] unsignedPixelValues ) { CoverageDataPngImage image = drawTile ( unsignedPixelValues ) ; byte [ ] bytes = image . getImageBytes ( ) ; return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a coverage data image tile from the double array of unsigned coverage data values formatted as Double [ row ] [ width ] [CODESPLIT] public CoverageDataPngImage drawTile ( GriddedTile griddedTile , Double [ ] [ ] values ) { int tileWidth = values [ 0 ] . length ; int tileHeight = values . length ; CoverageDataPngImage image = createImage ( tileWidth , tileHeight ) ; PngWriter writer = image . getWriter ( ) ; for ( int y = 0 ; y < tileHeight ; y ++ ) { ImageLineInt row = new ImageLineInt ( writer . imgInfo , new int [ tileWidth ] ) ; int [ ] rowLine = row . getScanline ( ) ; for ( int x = 0 ; x < tileWidth ; x ++ ) { Double value = values [ y ] [ x ] ; short pixelValue = getPixelValue ( griddedTile , value ) ; setPixelValue ( rowLine , x , pixelValue ) ; } writer . writeRow ( row ) ; } writer . end ( ) ; image . flushStream ( ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new 16 bit single channel image [CODESPLIT] public CoverageDataPngImage createImage ( int tileWidth , int tileHeight ) { ImageInfo imageInfo = new ImageInfo ( tileWidth , tileHeight , 16 , false , true , false ) ; CoverageDataPngImage image = new CoverageDataPngImage ( imageInfo ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the pixel value [CODESPLIT] public void setPixelValue ( ImageLineInt row , int x , short pixelValue ) { setPixelValue ( row . getScanline ( ) , x , pixelValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the pixel value [CODESPLIT] public void setPixelValue ( ImageLineInt row , int x , int unsignedPixelValue ) { short pixelValue = getPixelValue ( unsignedPixelValue ) ; setPixelValue ( row , x , pixelValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the coverage data tile table with metadata and extension [CODESPLIT] public static CoverageDataPng createTileTableWithMetadata ( GeoPackage geoPackage , String tableName , BoundingBox contentsBoundingBox , long contentsSrsId , BoundingBox tileMatrixSetBoundingBox , long tileMatrixSetSrsId ) { CoverageDataPng coverageData = ( CoverageDataPng ) CoverageData . createTileTableWithMetadata ( geoPackage , tableName , contentsBoundingBox , contentsSrsId , tileMatrixSetBoundingBox , tileMatrixSetSrsId , GriddedCoverageDataType . INTEGER ) ; return coverageData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the tile data from a bitmap [CODESPLIT] public void setTileData ( Bitmap bitmap , CompressFormat format , int quality ) throws IOException { byte [ ] tileData = BitmapConverter . toBytes ( bitmap , format , quality ) ; setTileData ( tileData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int delete ( String table , String whereClause , String [ ] whereArgs ) { return db . delete ( table , whereClause , whereArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int count ( String table , String where , String [ ] args ) { StringBuilder countQuery = new StringBuilder ( ) ; countQuery . append ( \"select count(*) from \" ) . append ( CoreSQLUtils . quoteWrap ( table ) ) ; if ( where != null ) { countQuery . append ( \" where \" ) . append ( where ) ; } String sql = countQuery . toString ( ) ; int count = querySingleInteger ( sql , args , true ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean columnExists ( String tableName , String columnName ) { boolean exists = false ; Cursor cursor = rawQuery ( \"PRAGMA table_info(\" + CoreSQLUtils . quoteWrap ( tableName ) + \")\" , null ) ; try { int nameIndex = cursor . getColumnIndex ( NAME_COLUMN ) ; while ( cursor . moveToNext ( ) ) { String name = cursor . getString ( nameIndex ) ; if ( columnName . equals ( name ) ) { exists = true ; break ; } } } finally { cursor . close ( ) ; } return exists ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object querySingleResult ( String sql , String [ ] args , int column , GeoPackageDataType dataType ) { CursorResult result = wrapQuery ( sql , args ) ; Object value = ResultUtils . buildSingleResult ( result , column , dataType ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < Object > querySingleColumnResults ( String sql , String [ ] args , int column , GeoPackageDataType dataType , Integer limit ) { CursorResult result = wrapQuery ( sql , args ) ; List < Object > results = ResultUtils . buildSingleColumnResults ( result , column , dataType , limit ) ; return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < List < Object > > queryResults ( String sql , String [ ] args , GeoPackageDataType [ ] dataTypes , Integer limit ) { CursorResult result = wrapQuery ( sql , args ) ; List < List < Object > > results = ResultUtils . buildResults ( result , dataTypes , limit ) ; return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a raw database query [CODESPLIT] public Cursor rawQuery ( String sql , String [ ] args ) { return db . rawQuery ( sql , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the query and wrap as a result [CODESPLIT] public CursorResult wrapQuery ( String sql , String [ ] selectionArgs ) { return new CursorResult ( rawQuery ( sql , selectionArgs ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TResult rawQuery ( String sql , String [ ] selectionArgs ) { UserQuery query = new UserQuery ( sql , selectionArgs ) ; TResult result = query ( query ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TResult query ( String table , String [ ] columns , String selection , String [ ] selectionArgs , String groupBy , String having , String orderBy ) { UserQuery query = new UserQuery ( table , columns , selection , selectionArgs , groupBy , having , orderBy ) ; TResult result = query ( query ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query using the query from a previous query result [CODESPLIT] public TResult query ( TResult previousResult ) { UserQuery query = previousResult . getQuery ( ) ; TResult result = query ( query ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query using the user query arguments [CODESPLIT] public TResult query ( UserQuery query ) { Cursor cursor = null ; String [ ] selectionArgs = query . getSelectionArgs ( ) ; String sql = query . getSql ( ) ; if ( sql != null ) { cursor = database . rawQuery ( sql , selectionArgs ) ; } else { String table = query . getTable ( ) ; String [ ] columns = query . getColumns ( ) ; String selection = query . getSelection ( ) ; String groupBy = query . getGroupBy ( ) ; String having = query . getHaving ( ) ; String orderBy = query . getOrderBy ( ) ; String [ ] columnsAs = query . getColumnsAs ( ) ; String limit = query . getLimit ( ) ; if ( columnsAs != null && limit != null ) { cursor = database . query ( table , columns , columnsAs , selection , selectionArgs , groupBy , having , orderBy , limit ) ; } else if ( columnsAs != null ) { cursor = database . query ( table , columns , columnsAs , selection , selectionArgs , groupBy , having , orderBy ) ; } else if ( limit != null ) { cursor = database . query ( table , columns , selection , selectionArgs , groupBy , having , orderBy , limit ) ; } else { cursor = database . query ( table , columns , selection , selectionArgs , groupBy , having , orderBy ) ; } } TResult result = handleCursor ( cursor , query ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the cursor to the result type cursor [CODESPLIT] private TResult handleCursor ( Cursor cursor , UserQuery query ) { TResult result = convertCursor ( cursor ) ; result . setQuery ( query ) ; if ( table != null ) { result . setTable ( table ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature row . This method assumes that indexing has been completed and maintained as the last indexed time is updated . [CODESPLIT] public boolean index ( FeatureRow row ) { TableIndex tableIndex = getTableIndex ( ) ; if ( tableIndex == null ) { throw new GeoPackageException ( \"GeoPackage table is not indexed. GeoPackage: \" + getGeoPackage ( ) . getName ( ) + \", Table: \" + getTableName ( ) ) ; } boolean indexed = index ( tableIndex , row . getId ( ) , row . getGeometry ( ) ) ; // Update the last indexed time updateLastIndexed ( ) ; return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature rows in the cursor [CODESPLIT] private int indexRows ( TableIndex tableIndex , FeatureCursor cursor ) { int count = - 1 ; try { while ( ( progress == null || progress . isActive ( ) ) && cursor . moveToNext ( ) ) { if ( count < 0 ) { count ++ ; } try { FeatureRow row = cursor . getRow ( ) ; if ( row . isValid ( ) ) { boolean indexed = index ( tableIndex , row . getId ( ) , row . getGeometry ( ) ) ; if ( indexed ) { count ++ ; } if ( progress != null ) { progress . addProgress ( 1 ) ; } } } catch ( Exception e ) { Log . e ( FeatureTableIndex . class . getSimpleName ( ) , \"Failed to index feature. Table: \" + tableIndex . getTableName ( ) + \", Position: \" + cursor . getPosition ( ) , e ) ; } } } finally { cursor . close ( ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature row for the Geometry Index [CODESPLIT] public FeatureRow getFeatureRow ( GeometryIndex geometryIndex ) { long geomId = geometryIndex . getGeomId ( ) ; // Get the row or lock for reading FeatureRow row = featureRowSync . getRowOrLock ( geomId ) ; if ( row == null ) { // Query for the row and set in the sync try { row = featureDao . queryForIdRow ( geomId ) ; } finally { featureRowSync . setRow ( geomId , row ) ; } } return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Iterator < FeatureRow > iterator ( ) { return new Iterator < FeatureRow > ( ) { /**\n             * {@inheritDoc}\n             */ @ Override public boolean hasNext ( ) { return cursor . moveToNext ( ) ; } /**\n             * {@inheritDoc}\n             */ @ Override public FeatureRow next ( ) { return dao . getFeatureRow ( cursor ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Iterable < Long > ids ( ) { return new Iterable < Long > ( ) { /**\n             * {@inheritDoc}\n             */ @ Override public Iterator < Long > iterator ( ) { return new Iterator < Long > ( ) { /**\n                     * {@inheritDoc}\n                     */ @ Override public boolean hasNext ( ) { return cursor . moveToNext ( ) ; } /**\n                     * {@inheritDoc}\n                     */ @ Override public Long next ( ) { return dao . getRow ( cursor ) . getId ( ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a cursor wrapper for the provided table name . Database queries will wrap the returned cursor [CODESPLIT] public void registerTable ( String tableName , GeoPackageCursorWrapper cursorWrapper ) { // Remove an existing cursor wrapper tableCursors . remove ( tableName ) ; // Add the wrapper tableCursors . put ( tableName , cursorWrapper ) ; String quotedTableName = CoreSQLUtils . quoteWrap ( tableName ) ; tableCursors . put ( quotedTableName , cursorWrapper ) ; // The Android android.database.sqlite.SQLiteDatabase findEditTable method // finds the new cursor edit table name based upon the first space or comma. // Fix (hopefully temporary) to wrap with the expected cursor type int spacePosition = tableName . indexOf ( ' ' ) ; if ( spacePosition > 0 ) { tableCursors . put ( tableName . substring ( 0 , spacePosition ) , cursorWrapper ) ; tableCursors . put ( quotedTableName . substring ( 0 , quotedTableName . indexOf ( ' ' ) ) , cursorWrapper ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Cursor newCursor ( SQLiteDatabase db , SQLiteCursorDriver driver , String editTable , SQLiteQuery query ) { // Create a standard cursor Cursor cursor = new SQLiteCursor ( driver , editTable , query ) ; // Check if there is an edit table if ( editTable != null ) { // Check if the table has a cursor wrapper GeoPackageCursorWrapper cursorWrapper = tableCursors . get ( editTable ) ; if ( cursorWrapper != null ) { cursor = cursorWrapper . wrapCursor ( cursor ) ; } } return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean hasTile ( int x , int y , int zoom ) { return retrieveTileRow ( x , y , zoom ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public GeoPackageTile getTile ( int x , int y , int zoom ) { GeoPackageTile tile = null ; TileRow tileRow = retrieveTileRow ( x , y , zoom ) ; if ( tileRow != null ) { TileMatrix tileMatrix = tileDao . getTileMatrix ( zoom ) ; int tileWidth = ( int ) tileMatrix . getTileWidth ( ) ; int tileHeight = ( int ) tileMatrix . getTileHeight ( ) ; tile = new GeoPackageTile ( tileWidth , tileHeight , tileRow . getTileData ( ) ) ; } return tile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the tile row [CODESPLIT] private TileRow retrieveTileRow ( int x , int y , int zoom ) { return tileDao . queryForTile ( x , y , zoom ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Tiled Gridded Coverage Data [CODESPLIT] public static CoverageData < ? > getCoverageData ( GeoPackage geoPackage , TileDao tileDao , Integer width , Integer height , Projection requestProjection ) { TileMatrixSet tileMatrixSet = tileDao . getTileMatrixSet ( ) ; GriddedCoverageDao griddedCoverageDao = geoPackage . getGriddedCoverageDao ( ) ; GriddedCoverage griddedCoverage = null ; try { if ( griddedCoverageDao . isTableExists ( ) ) { griddedCoverage = griddedCoverageDao . query ( tileMatrixSet ) ; } } catch ( SQLException e ) { throw new GeoPackageException ( \"Failed to get Gridded Coverage for table name: \" + tileMatrixSet . getTableName ( ) , e ) ; } CoverageData < ? > coverageData = null ; GriddedCoverageDataType dataType = griddedCoverage . getDataType ( ) ; switch ( dataType ) { case INTEGER : coverageData = new CoverageDataPng ( geoPackage , tileDao , width , height , requestProjection ) ; break ; case FLOAT : coverageData = new CoverageDataTiff ( geoPackage , tileDao , width , height , requestProjection ) ; break ; default : throw new GeoPackageException ( \"Unsupported Gridded Coverage Data Type: \" + dataType ) ; } return coverageData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Tiled Gridded Coverage Data use the coverage data pixel tile size as the request size width and height [CODESPLIT] public static CoverageData < ? > getCoverageData ( GeoPackage geoPackage , TileDao tileDao ) { return getCoverageData ( geoPackage , tileDao , null , null , tileDao . getProjection ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Tiled Gridded Coverage Data use the coverage data pixel tile size as the request size width and height request as the specified projection [CODESPLIT] public static CoverageData < ? > getCoverageData ( GeoPackage geoPackage , TileDao tileDao , Projection requestProjection ) { return getCoverageData ( geoPackage , tileDao , null , null , requestProjection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the coverage data tile table with metadata and extension [CODESPLIT] public static CoverageData < ? > createTileTableWithMetadata ( GeoPackage geoPackage , String tableName , BoundingBox contentsBoundingBox , long contentsSrsId , BoundingBox tileMatrixSetBoundingBox , long tileMatrixSetSrsId , GriddedCoverageDataType dataType ) { TileMatrixSet tileMatrixSet = CoverageDataCore . createTileTableWithMetadata ( geoPackage , tableName , contentsBoundingBox , contentsSrsId , tileMatrixSetBoundingBox , tileMatrixSetSrsId ) ; TileDao tileDao = geoPackage . getTileDao ( tileMatrixSet ) ; CoverageData < ? > coverageData = null ; switch ( dataType ) { case INTEGER : coverageData = new CoverageDataPng ( geoPackage , tileDao ) ; break ; case FLOAT : coverageData = new CoverageDataTiff ( geoPackage , tileDao ) ; break ; default : throw new GeoPackageException ( \"Unsupported Gridded Coverage Data Type: \" + dataType ) ; } coverageData . getOrCreate ( ) ; return coverageData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public CoverageDataResults getValues ( CoverageDataRequest request , Integer width , Integer height ) { CoverageDataResults coverageDataResults = null ; // Transform to the projection of the coverage data tiles ProjectionTransform transformRequestToCoverage = null ; BoundingBox requestProjectedBoundingBox = request . getBoundingBox ( ) ; if ( ! sameProjection ) { transformRequestToCoverage = requestProjection . getTransformation ( coverageProjection ) ; requestProjectedBoundingBox = requestProjectedBoundingBox . transform ( transformRequestToCoverage ) ; } request . setProjectedBoundingBox ( requestProjectedBoundingBox ) ; // Determine how many overlapping pixels to store based upon the // algorithm int overlappingPixels ; switch ( algorithm ) { case BICUBIC : overlappingPixels = 3 ; break ; default : overlappingPixels = 1 ; } // Find the tile matrix and results CoverageDataTileMatrixResults results = getResults ( request , requestProjectedBoundingBox , overlappingPixels ) ; if ( results != null ) { TileMatrix tileMatrix = results . getTileMatrix ( ) ; TileCursor tileResults = results . getTileResults ( ) ; try { // Determine the requested coverage data dimensions, or use the // dimensions of a single tile matrix coverage data tile int requestedCoverageDataWidth = width != null ? width : ( int ) tileMatrix . getTileWidth ( ) ; int requestedCoverageDataHeight = height != null ? height : ( int ) tileMatrix . getTileHeight ( ) ; // Determine the size of the non projected coverage data results int tileWidth = requestedCoverageDataWidth ; int tileHeight = requestedCoverageDataHeight ; if ( ! sameProjection ) { int projectedWidth = ( int ) Math . round ( ( requestProjectedBoundingBox . getMaxLongitude ( ) - requestProjectedBoundingBox . getMinLongitude ( ) ) / tileMatrix . getPixelXSize ( ) ) ; if ( projectedWidth > 0 ) { tileWidth = projectedWidth ; } int projectedHeight = ( int ) Math . round ( ( requestProjectedBoundingBox . getMaxLatitude ( ) - requestProjectedBoundingBox . getMinLatitude ( ) ) / tileMatrix . getPixelYSize ( ) ) ; if ( projectedHeight > 0 ) { tileHeight = projectedHeight ; } } // Retrieve the coverage data from the results Double [ ] [ ] values = getValues ( tileMatrix , tileResults , request , tileWidth , tileHeight , overlappingPixels ) ; // Project the coverage data if needed if ( values != null && ! sameProjection && ! request . isPoint ( ) ) { values = reprojectCoverageData ( values , requestedCoverageDataWidth , requestedCoverageDataHeight , request . getBoundingBox ( ) , transformRequestToCoverage , requestProjectedBoundingBox ) ; } // Create the results if ( values != null ) { coverageDataResults = new CoverageDataResults ( values , tileMatrix ) ; } } finally { tileResults . close ( ) ; } } return coverageDataResults ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public CoverageDataResults getValuesUnbounded ( CoverageDataRequest request ) { CoverageDataResults coverageDataResults = null ; // Transform to the projection of the coverage data tiles ProjectionTransform transformRequestToCoverage = null ; BoundingBox requestProjectedBoundingBox = request . getBoundingBox ( ) ; if ( ! sameProjection ) { transformRequestToCoverage = requestProjection . getTransformation ( coverageProjection ) ; requestProjectedBoundingBox = requestProjectedBoundingBox . transform ( transformRequestToCoverage ) ; } request . setProjectedBoundingBox ( requestProjectedBoundingBox ) ; // Find the tile matrix and results CoverageDataTileMatrixResults results = getResults ( request , requestProjectedBoundingBox ) ; if ( results != null ) { TileMatrix tileMatrix = results . getTileMatrix ( ) ; TileCursor tileResults = results . getTileResults ( ) ; try { // Retrieve the coverage data values from the results Double [ ] [ ] values = getValuesUnbounded ( tileMatrix , tileResults , request ) ; // Project the coverage data if needed if ( values != null && ! sameProjection && ! request . isPoint ( ) ) { values = reprojectCoverageData ( values , values [ 0 ] . length , values . length , request . getBoundingBox ( ) , transformRequestToCoverage , requestProjectedBoundingBox ) ; } // Create the results if ( values != null ) { coverageDataResults = new CoverageDataResults ( values , tileMatrix ) ; } } finally { tileResults . close ( ) ; } } return coverageDataResults ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coverage data tile results by finding the tile matrix with values [CODESPLIT] private CoverageDataTileMatrixResults getResults ( CoverageDataRequest request , BoundingBox requestProjectedBoundingBox , int overlappingPixels ) { // Try to get the coverage data from the current zoom level TileMatrix tileMatrix = getTileMatrix ( request ) ; CoverageDataTileMatrixResults results = null ; if ( tileMatrix != null ) { results = getResults ( requestProjectedBoundingBox , tileMatrix , overlappingPixels ) ; // Try to zoom in or out to find a matching coverage data if ( results == null ) { results = getResultsZoom ( requestProjectedBoundingBox , tileMatrix , overlappingPixels ) ; } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coverage data tile results by zooming in or out as needed from the provided tile matrix to find values [CODESPLIT] private CoverageDataTileMatrixResults getResultsZoom ( BoundingBox requestProjectedBoundingBox , TileMatrix tileMatrix , int overlappingPixels ) { CoverageDataTileMatrixResults results = null ; if ( zoomIn && zoomInBeforeOut ) { results = getResultsZoomIn ( requestProjectedBoundingBox , tileMatrix , overlappingPixels ) ; } if ( results == null && zoomOut ) { results = getResultsZoomOut ( requestProjectedBoundingBox , tileMatrix , overlappingPixels ) ; } if ( results == null && zoomIn && ! zoomInBeforeOut ) { results = getResultsZoomIn ( requestProjectedBoundingBox , tileMatrix , overlappingPixels ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coverage data tile results by zooming in from the provided tile matrix [CODESPLIT] private CoverageDataTileMatrixResults getResultsZoomIn ( BoundingBox requestProjectedBoundingBox , TileMatrix tileMatrix , int overlappingPixels ) { CoverageDataTileMatrixResults results = null ; for ( long zoomLevel = tileMatrix . getZoomLevel ( ) + 1 ; zoomLevel <= tileDao . getMaxZoom ( ) ; zoomLevel ++ ) { TileMatrix zoomTileMatrix = tileDao . getTileMatrix ( zoomLevel ) ; if ( zoomTileMatrix != null ) { results = getResults ( requestProjectedBoundingBox , zoomTileMatrix , overlappingPixels ) ; if ( results != null ) { break ; } } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coverage data tile results by zooming out from the provided tile matrix [CODESPLIT] private CoverageDataTileMatrixResults getResultsZoomOut ( BoundingBox requestProjectedBoundingBox , TileMatrix tileMatrix , int overlappingPixels ) { CoverageDataTileMatrixResults results = null ; for ( long zoomLevel = tileMatrix . getZoomLevel ( ) - 1 ; zoomLevel >= tileDao . getMinZoom ( ) ; zoomLevel -- ) { TileMatrix zoomTileMatrix = tileDao . getTileMatrix ( zoomLevel ) ; if ( zoomTileMatrix != null ) { results = getResults ( requestProjectedBoundingBox , zoomTileMatrix , overlappingPixels ) ; if ( results != null ) { break ; } } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile matrix for the zoom level as defined by the area of the request [CODESPLIT] private TileMatrix getTileMatrix ( CoverageDataRequest request ) { TileMatrix tileMatrix = null ; // Check if the request overlaps coverage data bounding box if ( request . overlap ( coverageBoundingBox ) != null ) { // Get the tile distance BoundingBox projectedBoundingBox = request . getProjectedBoundingBox ( ) ; double distanceWidth = projectedBoundingBox . getMaxLongitude ( ) - projectedBoundingBox . getMinLongitude ( ) ; double distanceHeight = projectedBoundingBox . getMaxLatitude ( ) - projectedBoundingBox . getMinLatitude ( ) ; // Get the zoom level to request based upon the tile size Long zoomLevel = tileDao . getClosestZoomLevel ( distanceWidth , distanceHeight ) ; // If there is a matching zoom level if ( zoomLevel != null ) { tileMatrix = tileDao . getTileMatrix ( zoomLevel ) ; } } return tileMatrix ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the coverage data value of the pixel in the tile row image [CODESPLIT] public double getValue ( TileRow tileRow , int x , int y ) { GriddedTile griddedTile = getGriddedTile ( tileRow . getId ( ) ) ; double value = getValue ( griddedTile , tileRow , x , y ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the icon for the geometry type [CODESPLIT] public void setIcon ( IconRow iconRow , GeometryType geometryType ) { if ( geometryType != null ) { if ( iconRow != null ) { icons . put ( geometryType , iconRow ) ; } else { icons . remove ( geometryType ) ; } } else { defaultIcon = iconRow ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon for the geometry type [CODESPLIT] public IconRow getIcon ( GeometryType geometryType ) { IconRow iconRow = null ; if ( geometryType != null && ! icons . isEmpty ( ) ) { List < GeometryType > geometryTypes = GeometryUtils . parentHierarchy ( geometryType ) ; geometryTypes . add ( 0 , geometryType ) ; for ( GeometryType type : geometryTypes ) { iconRow = icons . get ( type ) ; if ( iconRow != null ) { break ; } } } if ( iconRow == null ) { iconRow = defaultIcon ; } if ( iconRow == null && geometryType == null && icons . size ( ) == 1 ) { iconRow = icons . values ( ) . iterator ( ) . next ( ) ; } return iconRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public UserCustomRow getRow ( int [ ] columnTypes , Object [ ] values ) { return new UserCustomRow ( getTable ( ) , columnTypes , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected UserInvalidCursor < UserCustomColumn , UserCustomTable , UserCustomRow , ? extends UserCursor < UserCustomColumn , UserCustomTable , UserCustomRow > , ? extends UserDao < UserCustomColumn , UserCustomTable , UserCustomRow , ? extends UserCursor < UserCustomColumn , UserCustomTable , UserCustomRow > > > createInvalidCursor ( UserDao dao , UserCursor cursor , List < Integer > invalidPositions , List < UserCustomColumn > blobColumns ) { return new UserCustomInvalidCursor ( ( UserCustomDao ) dao , ( UserCustomCursor ) cursor , invalidPositions , blobColumns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open or get a connection using the SQLite Android Bindings connection [CODESPLIT] public org . sqlite . database . sqlite . SQLiteDatabase openOrGetBindingsDb ( ) { if ( bindingsDb == null ) { synchronized ( db ) { if ( bindingsDb == null ) { System . loadLibrary ( \"sqliteX\" ) ; bindingsDb = org . sqlite . database . sqlite . SQLiteDatabase . openDatabase ( db . getPath ( ) , null , org . sqlite . database . sqlite . SQLiteDatabase . OPEN_READWRITE ) ; } } } return bindingsDb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode the bytes to a bitmap with options [CODESPLIT] public static Bitmap toBitmap ( byte [ ] bytes , Options options ) { Bitmap bitmap = BitmapFactory . decodeByteArray ( bytes , 0 , bytes . length , options ) ; return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compress the bitmap to a byte array [CODESPLIT] public static byte [ ] toBytes ( Bitmap bitmap , CompressFormat format , int quality ) throws IOException { byte [ ] bytes = null ; ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( ) ; try { bitmap . compress ( format , quality , byteStream ) ; bytes = byteStream . toByteArray ( ) ; } finally { byteStream . close ( ) ; } return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new table metadata [CODESPLIT] public void create ( TableMetadata metadata ) { ContentValues values = new ContentValues ( ) ; values . put ( TableMetadata . COLUMN_GEOPACKAGE_ID , metadata . getGeoPackageId ( ) ) ; values . put ( TableMetadata . COLUMN_TABLE_NAME , metadata . getTableName ( ) ) ; values . put ( TableMetadata . COLUMN_LAST_INDEXED , metadata . getLastIndexed ( ) ) ; long insertId = db . insert ( TableMetadata . TABLE_NAME , null , values ) ; if ( insertId == - 1 ) { throw new GeoPackageException ( \"Failed to insert table metadata. GeoPackage Id: \" + metadata . getGeoPackageId ( ) + \", Table Name: \" + metadata . getTableName ( ) + \", Last Indexed: \" + metadata . getLastIndexed ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the database table name [CODESPLIT] public boolean delete ( long geoPackageId , String tableName ) { GeometryMetadataDataSource geomDs = new GeometryMetadataDataSource ( db ) ; geomDs . delete ( geoPackageId , tableName ) ; String whereClause = TableMetadata . COLUMN_GEOPACKAGE_ID + \" = ? AND \" + TableMetadata . COLUMN_TABLE_NAME + \" = ?\" ; String [ ] whereArgs = new String [ ] { String . valueOf ( geoPackageId ) , tableName } ; int deleteCount = db . delete ( TableMetadata . TABLE_NAME , whereClause , whereArgs ) ; return deleteCount > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the last indexed time [CODESPLIT] public boolean updateLastIndexed ( TableMetadata metadata , long lastIndexed ) { boolean updated = updateLastIndexed ( metadata . getGeoPackageId ( ) , metadata . getTableName ( ) , lastIndexed ) ; if ( updated ) { metadata . setLastIndexed ( lastIndexed ) ; } return updated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the last indexed time [CODESPLIT] public boolean updateLastIndexed ( String geoPackage , String tableName , long lastIndexed ) { return updateLastIndexed ( getGeoPackageId ( geoPackage ) , tableName , lastIndexed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the last indexed time [CODESPLIT] public boolean updateLastIndexed ( long geoPackageId , String tableName , long lastIndexed ) { String whereClause = TableMetadata . COLUMN_GEOPACKAGE_ID + \" = ? AND \" + TableMetadata . COLUMN_TABLE_NAME + \" = ?\" ; String [ ] whereArgs = new String [ ] { String . valueOf ( geoPackageId ) , tableName } ; ContentValues values = new ContentValues ( ) ; values . put ( TableMetadata . COLUMN_LAST_INDEXED , lastIndexed ) ; int updateCount = db . update ( TableMetadata . TABLE_NAME , values , whereClause , whereArgs ) ; return updateCount > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a table metadata [CODESPLIT] public TableMetadata get ( String geoPackage , String tableName ) { return get ( getGeoPackageId ( geoPackage ) , tableName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a table metadata [CODESPLIT] public TableMetadata get ( long geoPackageId , String tableName ) { String selection = TableMetadata . COLUMN_GEOPACKAGE_ID + \" = ? AND \" + TableMetadata . COLUMN_TABLE_NAME + \" = ?\" ; String [ ] selectionArgs = new String [ ] { String . valueOf ( geoPackageId ) , tableName } ; Cursor cursor = db . query ( TableMetadata . TABLE_NAME , TableMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; TableMetadata metadata = null ; try { if ( cursor . moveToNext ( ) ) { metadata = createTableMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a table metadata or create if it does not exist [CODESPLIT] public TableMetadata getOrCreate ( String geoPackage , String tableName ) { GeoPackageMetadataDataSource ds = new GeoPackageMetadataDataSource ( db ) ; GeoPackageMetadata geoPackageMetadata = ds . getOrCreate ( geoPackage ) ; TableMetadata metadata = get ( geoPackageMetadata . getId ( ) , tableName ) ; if ( metadata == null ) { metadata = new TableMetadata ( ) ; metadata . setGeoPackageId ( geoPackageMetadata . getId ( ) ) ; metadata . setTableName ( tableName ) ; create ( metadata ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a GeoPackage id from the name [CODESPLIT] public long getGeoPackageId ( String geoPackage ) { long id = - 1 ; GeoPackageMetadataDataSource ds = new GeoPackageMetadataDataSource ( db ) ; GeoPackageMetadata metadata = ds . get ( geoPackage ) ; if ( metadata != null ) { id = metadata . getId ( ) ; } return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a table metadata from the current cursor location [CODESPLIT] private TableMetadata createTableMetadata ( Cursor cursor ) { TableMetadata metadata = new TableMetadata ( ) ; metadata . setGeoPackageId ( cursor . getLong ( 0 ) ) ; metadata . setTableName ( cursor . getString ( 1 ) ) ; if ( ! cursor . isNull ( 2 ) ) { metadata . setLastIndexed ( cursor . getLong ( 2 ) ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the RTree extension for the feature table [CODESPLIT] public Extensions create ( ) { Extensions extension = null ; if ( ! has ( ) ) { extension = rTree . create ( featureDao . getTable ( ) ) ; if ( progress != null ) { progress . addProgress ( count ( ) ) ; } } return extension ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature row from the RTree Index Table row [CODESPLIT] public FeatureRow getFeatureRow ( UserCustomCursor cursor ) { RTreeIndexTableRow row = getRow ( cursor ) ; return getFeatureRow ( row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a raw query [CODESPLIT] public UserCustomCursor rawQuery ( String sql , String [ ] selectionArgs ) { validateRTree ( ) ; Cursor cursor = database . rawQuery ( sql , selectionArgs ) ; UserCustomCursor customCursor = new UserCustomCursor ( getTable ( ) , cursor ) ; return customCursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public UserCustomCursor query ( String where , String [ ] whereArgs ) { StringBuilder query = new StringBuilder ( ) ; query . append ( \"select * from \" ) . append ( CoreSQLUtils . quoteWrap ( getTableName ( ) ) ) ; if ( where != null ) { query . append ( \" where \" ) . append ( where ) ; } String sql = query . toString ( ) ; UserCustomCursor customCursor = rawQuery ( sql , whereArgs ) ; return customCursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public int count ( String where , String [ ] args ) { int count = 0 ; StringBuilder countQuery = new StringBuilder ( ) ; countQuery . append ( \"select count(*) from \" ) . append ( CoreSQLUtils . quoteWrap ( getTableName ( ) ) ) ; if ( where != null ) { countQuery . append ( \" where \" ) . append ( where ) ; } String sql = countQuery . toString ( ) ; UserCustomCursor customCursor = rawQuery ( sql , args ) ; Object value = ResultUtils . buildSingleResult ( customCursor , 0 , GeoPackageDataType . MEDIUMINT ) ; if ( value != null ) { count = ( ( Number ) value ) . intValue ( ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BoundingBox getBoundingBox ( ) { BoundingBox boundingBox = null ; String sql = \"SELECT MIN(\" + RTreeIndexExtension . COLUMN_MIN_X + \"), MIN(\" + RTreeIndexExtension . COLUMN_MIN_Y + \"), MAX(\" + RTreeIndexExtension . COLUMN_MAX_X + \"), MAX(\" + RTreeIndexExtension . COLUMN_MAX_Y + \") FROM \" + CoreSQLUtils . quoteWrap ( getTableName ( ) ) ; UserCustomCursor customCursor = rawQuery ( sql , null ) ; List < List < Object > > results = ResultUtils . buildResults ( customCursor , new GeoPackageDataType [ ] { GeoPackageDataType . DOUBLE , GeoPackageDataType . DOUBLE , GeoPackageDataType . DOUBLE , GeoPackageDataType . DOUBLE } , 1 ) ; if ( ! results . isEmpty ( ) ) { List < Object > resultRow = results . get ( 0 ) ; boundingBox = new BoundingBox ( ( Double ) resultRow . get ( 0 ) , ( Double ) resultRow . get ( 1 ) , ( Double ) resultRow . get ( 2 ) , ( Double ) resultRow . get ( 3 ) ) ; } return boundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for rows within the bounding box in the provided projection [CODESPLIT] public UserCustomCursor query ( BoundingBox boundingBox , Projection projection ) { BoundingBox featureBoundingBox = projectBoundingBox ( boundingBox , projection ) ; return query ( featureBoundingBox ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for rows within the geometry envelope [CODESPLIT] public UserCustomCursor query ( GeometryEnvelope envelope ) { return query ( envelope . getMinX ( ) , envelope . getMinY ( ) , envelope . getMaxX ( ) , envelope . getMaxY ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the rows within the geometry envelope [CODESPLIT] public long count ( GeometryEnvelope envelope ) { return count ( envelope . getMinX ( ) , envelope . getMinY ( ) , envelope . getMaxX ( ) , envelope . getMaxY ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for rows within the bounds [CODESPLIT] public UserCustomCursor query ( double minX , double minY , double maxX , double maxY ) { String where = buildWhere ( minX , minY , maxX , maxY ) ; String [ ] whereArgs = buildWhereArgs ( minX , minY , maxX , maxY ) ; return query ( where , whereArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a where clause from the bounds for overlapping ranges [CODESPLIT] private String buildWhere ( double minX , double minY , double maxX , double maxY ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( RTreeIndexExtension . COLUMN_MIN_X , maxX , \"<=\" ) ) ; where . append ( \" AND \" ) ; where . append ( buildWhere ( RTreeIndexExtension . COLUMN_MIN_Y , maxY , \"<=\" ) ) ; where . append ( \" AND \" ) ; where . append ( buildWhere ( RTreeIndexExtension . COLUMN_MAX_X , minX , \">=\" ) ) ; where . append ( \" AND \" ) ; where . append ( buildWhere ( RTreeIndexExtension . COLUMN_MAX_Y , minY , \">=\" ) ) ; return where . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build where arguments from the bounds to match the order in { @link #buildWhereArgs ( double double double double ) } [CODESPLIT] private String [ ] buildWhereArgs ( double minX , double minY , double maxX , double maxY ) { minX -= tolerance ; maxX += tolerance ; minY -= tolerance ; maxY += tolerance ; return buildWhereArgs ( new Object [ ] { maxX , maxY , minX , minY } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manually query for rows within the bounding box in the provided projection [CODESPLIT] public ManualFeatureQueryResults query ( BoundingBox boundingBox , Projection projection ) { BoundingBox featureBoundingBox = featureDao . projectBoundingBox ( boundingBox , projection ) ; return query ( featureBoundingBox ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manually count the rows within the bounding box in the provided projection [CODESPLIT] public long count ( BoundingBox boundingBox , Projection projection ) { BoundingBox featureBoundingBox = featureDao . projectBoundingBox ( boundingBox , projection ) ; return count ( featureBoundingBox ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manually query for rows within the geometry envelope [CODESPLIT] public ManualFeatureQueryResults query ( GeometryEnvelope envelope ) { return query ( envelope . getMinX ( ) , envelope . getMinY ( ) , envelope . getMaxX ( ) , envelope . getMaxY ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manually query for rows within the bounds [CODESPLIT] public ManualFeatureQueryResults query ( double minX , double minY , double maxX , double maxY ) { List < Long > featureIds = new ArrayList <> ( ) ; long offset = 0 ; boolean hasResults = true ; minX -= tolerance ; maxX += tolerance ; minY -= tolerance ; maxY += tolerance ; while ( hasResults ) { hasResults = false ; FeatureCursor featureCursor = featureDao . queryForChunk ( chunkLimit , offset ) ; try { while ( featureCursor . moveToNext ( ) ) { hasResults = true ; FeatureRow featureRow = featureCursor . getRow ( ) ; GeometryEnvelope envelope = featureRow . getGeometryEnvelope ( ) ; if ( envelope != null ) { double minXMax = Math . max ( minX , envelope . getMinX ( ) ) ; double maxXMin = Math . min ( maxX , envelope . getMaxX ( ) ) ; double minYMax = Math . max ( minY , envelope . getMinY ( ) ) ; double maxYMin = Math . min ( maxY , envelope . getMaxY ( ) ) ; if ( minXMax <= maxXMin && minYMax <= maxYMin ) { featureIds . add ( featureRow . getId ( ) ) ; } } } } finally { featureCursor . close ( ) ; } offset += chunkLimit ; } ManualFeatureQueryResults results = new ManualFeatureQueryResults ( featureDao , featureIds ) ; return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manually count the rows within the bounds [CODESPLIT] public long count ( double minX , double minY , double maxX , double maxY ) { return query ( minX , minY , maxX , maxY ) . count ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Iterator < FeatureRow > iterator ( ) { return new Iterator < FeatureRow > ( ) { /**\n             * {@inheritDoc}\n             */ @ Override public boolean hasNext ( ) { return cursor . moveToNext ( ) ; } /**\n             * {@inheritDoc}\n             */ @ Override public FeatureRow next ( ) { return cursor . getRow ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the data bounds without allocating pixel memory . Access values using : { @link BitmapFactory . Options#outWidth } { @link BitmapFactory . Options#outHeight } { @link BitmapFactory . Options#outMimeType } { @link BitmapFactory . Options#outColorSpace } and { @link BitmapFactory . Options#outConfig } [CODESPLIT] public BitmapFactory . Options getDataBounds ( ) { BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; byte [ ] data = getData ( ) ; BitmapFactory . decodeByteArray ( data , 0 , data . length , options ) ; return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data from a full quality bitmap [CODESPLIT] public void setData ( Bitmap bitmap , Bitmap . CompressFormat format ) throws IOException { setData ( bitmap , format , 100 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the data from a bitmap [CODESPLIT] public void setData ( Bitmap bitmap , Bitmap . CompressFormat format , int quality ) throws IOException { setData ( BitmapConverter . toBytes ( bitmap , format , quality ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Bitmap Compress Config [CODESPLIT] public void setBitmapCompressionConfig ( Config config ) { if ( options == null ) { options = new Options ( ) ; } options . inPreferredConfig = config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile count of tiles to be generated [CODESPLIT] public int getTileCount ( ) { if ( tileCount == null ) { long count = 0 ; boolean degrees = projection . isUnit ( Units . DEGREES ) ; ProjectionTransform transformToWebMercator = null ; if ( ! degrees ) { transformToWebMercator = projection . getTransformation ( ProjectionConstants . EPSG_WEB_MERCATOR ) ; } for ( int zoom = minZoom ; zoom <= maxZoom ; zoom ++ ) { BoundingBox expandedBoundingBox = getBoundingBox ( zoom ) ; // Get the tile grid that includes the entire bounding box TileGrid tileGrid = null ; if ( degrees ) { tileGrid = TileBoundingBoxUtils . getTileGridWGS84 ( expandedBoundingBox , zoom ) ; } else { tileGrid = TileBoundingBoxUtils . getTileGrid ( expandedBoundingBox . transform ( transformToWebMercator ) , zoom ) ; } count += tileGrid . count ( ) ; tileGrids . put ( zoom , tileGrid ) ; tileBounds . put ( zoom , expandedBoundingBox ) ; } tileCount = ( int ) Math . min ( count , Integer . MAX_VALUE ) ; } return tileCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adjust the tile matrix set and bounds [CODESPLIT] private void adjustBounds ( BoundingBox boundingBox , int zoom ) { // Google Tile Format if ( googleTiles ) { adjustGoogleBounds ( ) ; } else if ( projection . isUnit ( Units . DEGREES ) ) { adjustGeoPackageBoundsWGS84 ( boundingBox , zoom ) ; } else { adjustGeoPackageBounds ( boundingBox , zoom ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adjust the tile matrix set and web mercator bounds for Google tile format [CODESPLIT] private void adjustGoogleBounds ( ) { // Set the tile matrix set bounding box to be the world BoundingBox standardWgs84Box = new BoundingBox ( - ProjectionConstants . WGS84_HALF_WORLD_LON_WIDTH , ProjectionConstants . WEB_MERCATOR_MIN_LAT_RANGE , ProjectionConstants . WGS84_HALF_WORLD_LON_WIDTH , ProjectionConstants . WEB_MERCATOR_MAX_LAT_RANGE ) ; ProjectionTransform wgs84ToWebMercatorTransform = ProjectionFactory . getProjection ( ProjectionConstants . EPSG_WORLD_GEODETIC_SYSTEM ) . getTransformation ( ProjectionConstants . EPSG_WEB_MERCATOR ) ; tileGridBoundingBox = standardWgs84Box . transform ( wgs84ToWebMercatorTransform ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adjust the tile matrix set and WGS84 bounds for GeoPackage format . Determine the tile grid width and height [CODESPLIT] private void adjustGeoPackageBoundsWGS84 ( BoundingBox boundingBox , int zoom ) { // Get the fitting tile grid and determine the bounding box that fits it TileGrid tileGrid = TileBoundingBoxUtils . getTileGridWGS84 ( boundingBox , zoom ) ; tileGridBoundingBox = TileBoundingBoxUtils . getWGS84BoundingBox ( tileGrid , zoom ) ; matrixWidth = tileGrid . getMaxX ( ) + 1 - tileGrid . getMinX ( ) ; matrixHeight = tileGrid . getMaxY ( ) + 1 - tileGrid . getMinY ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adjust the tile matrix set and web mercator bounds for GeoPackage format . Determine the tile grid width and height [CODESPLIT] private void adjustGeoPackageBounds ( BoundingBox requestWebMercatorBoundingBox , int zoom ) { // Get the fitting tile grid and determine the bounding box that // fits it TileGrid tileGrid = TileBoundingBoxUtils . getTileGrid ( requestWebMercatorBoundingBox , zoom ) ; tileGridBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( tileGrid , zoom ) ; matrixWidth = tileGrid . getMaxX ( ) + 1 - tileGrid . getMinX ( ) ; matrixHeight = tileGrid . getMaxY ( ) + 1 - tileGrid . getMinY ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the bounding box of tiles [CODESPLIT] public BoundingBox getBoundingBox ( long zoomLevel ) { BoundingBox boundingBox = null ; TileMatrix tileMatrix = getTileMatrix ( zoomLevel ) ; if ( tileMatrix != null ) { TileGrid tileGrid = queryForTileGrid ( zoomLevel ) ; if ( tileGrid != null ) { BoundingBox matrixSetBoundingBox = getBoundingBox ( ) ; boundingBox = TileBoundingBoxUtils . getBoundingBox ( matrixSetBoundingBox , tileMatrix , tileGrid ) ; } } return boundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile grid of the zoom level [CODESPLIT] public TileGrid getTileGrid ( long zoomLevel ) { TileGrid tileGrid = null ; TileMatrix tileMatrix = getTileMatrix ( zoomLevel ) ; if ( tileMatrix != null ) { tileGrid = new TileGrid ( 0 , 0 , tileMatrix . getMatrixWidth ( ) - 1 , tileMatrix . getMatrixHeight ( ) - 1 ) ; } return tileGrid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for a Tile [CODESPLIT] public TileRow queryForTile ( long column , long row , long zoomLevel ) { Map < String , Object > fieldValues = new HashMap < String , Object > ( ) ; fieldValues . put ( TileTable . COLUMN_TILE_COLUMN , column ) ; fieldValues . put ( TileTable . COLUMN_TILE_ROW , row ) ; fieldValues . put ( TileTable . COLUMN_ZOOM_LEVEL , zoomLevel ) ; TileCursor cursor = queryForFieldValues ( fieldValues ) ; TileRow tileRow = null ; try { if ( cursor . moveToNext ( ) ) { tileRow = cursor . getRow ( ) ; } } finally { cursor . close ( ) ; } return tileRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for Tiles at a zoom level in descending row and column order [CODESPLIT] public TileCursor queryForTileDescending ( long zoomLevel ) { return queryForEq ( TileTable . COLUMN_ZOOM_LEVEL , zoomLevel , null , null , TileTable . COLUMN_TILE_ROW + \" DESC, \" + TileTable . COLUMN_TILE_COLUMN + \" DESC\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the zoom level for the provided width and height in the default units [CODESPLIT] public Long getZoomLevel ( double length ) { Long zoomLevel = TileDaoUtils . getZoomLevel ( widths , heights , tileMatrices , length ) ; return zoomLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the zoom level for the provided width and height in the default units [CODESPLIT] public Long getZoomLevel ( double width , double height ) { Long zoomLevel = TileDaoUtils . getZoomLevel ( widths , heights , tileMatrices , width , height ) ; return zoomLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the closest zoom level for the provided width and height in the default units [CODESPLIT] public Long getClosestZoomLevel ( double length ) { Long zoomLevel = TileDaoUtils . getClosestZoomLevel ( widths , heights , tileMatrices , length ) ; return zoomLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the approximate zoom level for the provided length in the default units . Tiles may or may not exist for the returned zoom level . The approximate zoom level is determined using a factor of 2 from the zoom levels with tiles . [CODESPLIT] public Long getApproximateZoomLevel ( double length ) { Long zoomLevel = TileDaoUtils . getApproximateZoomLevel ( widths , heights , tileMatrices , length ) ; return zoomLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for the bounding [CODESPLIT] public TileGrid queryForTileGrid ( long zoomLevel ) { String where = buildWhere ( TileTable . COLUMN_ZOOM_LEVEL , zoomLevel ) ; String [ ] whereArgs = buildWhereArgs ( new Object [ ] { zoomLevel } ) ; Integer minX = min ( TileTable . COLUMN_TILE_COLUMN , where , whereArgs ) ; Integer maxX = max ( TileTable . COLUMN_TILE_COLUMN , where , whereArgs ) ; Integer minY = min ( TileTable . COLUMN_TILE_ROW , where , whereArgs ) ; Integer maxY = max ( TileTable . COLUMN_TILE_ROW , where , whereArgs ) ; TileGrid tileGrid = null ; if ( minX != null && maxX != null && minY != null && maxY != null ) { tileGrid = new TileGrid ( minX , minY , maxX , maxY ) ; } return tileGrid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a Tile [CODESPLIT] public int deleteTile ( long column , long row , long zoomLevel ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( TileTable . COLUMN_ZOOM_LEVEL , zoomLevel ) ) ; where . append ( \" AND \" ) ; where . append ( buildWhere ( TileTable . COLUMN_TILE_COLUMN , column ) ) ; where . append ( \" AND \" ) ; where . append ( buildWhere ( TileTable . COLUMN_TILE_ROW , row ) ) ; String [ ] whereArgs = buildWhereArgs ( new Object [ ] { zoomLevel , column , row } ) ; int deleted = delete ( where . toString ( ) , whereArgs ) ; return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count of Tiles at a zoom level [CODESPLIT] public int count ( long zoomLevel ) { String where = buildWhere ( TileTable . COLUMN_ZOOM_LEVEL , zoomLevel ) ; String [ ] whereArgs = buildWhereArgs ( zoomLevel ) ; return count ( where , whereArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the tiles are in the Google tile coordinate format [CODESPLIT] public boolean isGoogleTiles ( ) { // Convert the bounding box to wgs84 BoundingBox boundingBox = tileMatrixSet . getBoundingBox ( ) ; BoundingBox wgs84BoundingBox = boundingBox . transform ( projection . getTransformation ( ProjectionConstants . EPSG_WORLD_GEODETIC_SYSTEM ) ) ; boolean googleTiles = false ; // Verify the bounds are the entire world if ( wgs84BoundingBox . getMinLatitude ( ) <= ProjectionConstants . WEB_MERCATOR_MIN_LAT_RANGE && wgs84BoundingBox . getMaxLatitude ( ) >= ProjectionConstants . WEB_MERCATOR_MAX_LAT_RANGE && wgs84BoundingBox . getMinLongitude ( ) <= - ProjectionConstants . WGS84_HALF_WORLD_LON_WIDTH && wgs84BoundingBox . getMaxLongitude ( ) >= ProjectionConstants . WGS84_HALF_WORLD_LON_WIDTH ) { googleTiles = true ; // Verify each tile matrix is the correct width and height for ( TileMatrix tileMatrix : tileMatrices ) { long zoomLevel = tileMatrix . getZoomLevel ( ) ; long tilesPerSide = TileBoundingBoxUtils . tilesPerSide ( ( int ) zoomLevel ) ; if ( tileMatrix . getMatrixWidth ( ) != tilesPerSide || tileMatrix . getMatrixHeight ( ) != tilesPerSide ) { googleTiles = false ; break ; } } } return googleTiles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Double getValue ( GriddedTile griddedTile , CoverageDataTiffImage image , int x , int y ) { Double value = null ; if ( image . getDirectory ( ) != null ) { float pixelValue = image . getPixel ( x , y ) ; value = getValue ( griddedTile , pixelValue ) ; } else { value = getValue ( griddedTile , image . getImageBytes ( ) , x , y ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pixel value as a float from the image and the coordinate [CODESPLIT] public float getPixelValue ( byte [ ] imageBytes , int x , int y ) { TIFFImage tiffImage = TiffReader . readTiff ( imageBytes ) ; FileDirectory directory = tiffImage . getFileDirectory ( ) ; validateImageType ( directory ) ; Rasters rasters = directory . readRasters ( ) ; float pixelValue = rasters . getFirstPixelSample ( x , y ) . floatValue ( ) ; return pixelValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pixel values of the image as floats [CODESPLIT] public float [ ] getPixelValues ( byte [ ] imageBytes ) { TIFFImage tiffImage = TiffReader . readTiff ( imageBytes ) ; FileDirectory directory = tiffImage . getFileDirectory ( ) ; validateImageType ( directory ) ; Rasters rasters = directory . readRasters ( ) ; float [ ] pixels = new float [ rasters . getWidth ( ) * rasters . getHeight ( ) ] ; for ( int y = 0 ; y < rasters . getHeight ( ) ; y ++ ) { for ( int x = 0 ; x < rasters . getWidth ( ) ; x ++ ) { int index = rasters . getSampleIndex ( x , y ) ; pixels [ index ] = rasters . getPixelSample ( 0 , x , y ) . floatValue ( ) ; } } return pixels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate that the image type [CODESPLIT] public static void validateImageType ( FileDirectory directory ) { if ( directory == null ) { throw new GeoPackageException ( \"The image is null\" ) ; } int samplesPerPixel = directory . getSamplesPerPixel ( ) ; Integer bitsPerSample = null ; if ( directory . getBitsPerSample ( ) != null && ! directory . getBitsPerSample ( ) . isEmpty ( ) ) { bitsPerSample = directory . getBitsPerSample ( ) . get ( 0 ) ; } Integer sampleFormat = null ; if ( directory . getSampleFormat ( ) != null && ! directory . getSampleFormat ( ) . isEmpty ( ) ) { sampleFormat = directory . getSampleFormat ( ) . get ( 0 ) ; } if ( samplesPerPixel != SAMPLES_PER_PIXEL || bitsPerSample == null || bitsPerSample != BITS_PER_SAMPLE || sampleFormat == null || sampleFormat != TiffConstants . SAMPLE_FORMAT_FLOAT ) { throw new GeoPackageException ( \"The coverage data tile is expected to be a single sample 32 bit float. Samples Per Pixel: \" + samplesPerPixel + \", Bits Per Sample: \" + bitsPerSample + \", Sample Format: \" + sampleFormat ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Double getValue ( GriddedTile griddedTile , byte [ ] imageBytes , int x , int y ) { float pixelValue = getPixelValue ( imageBytes , x , y ) ; Double value = getValue ( griddedTile , pixelValue ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Double [ ] getValues ( GriddedTile griddedTile , byte [ ] imageBytes ) { float [ ] pixelValues = getPixelValues ( imageBytes ) ; Double [ ] values = getValues ( griddedTile , pixelValues ) ; return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a coverage data image tile from the flat array of float pixel values of length tileWidth * tileHeight where each pixel is at : ( y * tileWidth ) + x [CODESPLIT] public CoverageDataTiffImage drawTile ( float [ ] pixelValues , int tileWidth , int tileHeight ) { CoverageDataTiffImage image = createImage ( tileWidth , tileHeight ) ; for ( int y = 0 ; y < tileHeight ; y ++ ) { for ( int x = 0 ; x < tileWidth ; x ++ ) { float pixelValue = pixelValues [ ( y * tileWidth ) + x ] ; setPixelValue ( image , x , y , pixelValue ) ; } } image . writeTiff ( ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a coverage data image tile and format as TIFF bytes from the double array of float pixel values formatted as float [ row ] [ width ] [CODESPLIT] public byte [ ] drawTileData ( float [ ] [ ] pixelValues ) { CoverageDataTiffImage image = drawTile ( pixelValues ) ; byte [ ] bytes = image . getImageBytes ( ) ; return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a coverage data image tile from the flat array of coverage data values of length tileWidth * tileHeight where each coverage data value is at : ( y * tileWidth ) + x [CODESPLIT] public CoverageDataTiffImage drawTile ( GriddedTile griddedTile , Double [ ] values , int tileWidth , int tileHeight ) { CoverageDataTiffImage image = createImage ( tileWidth , tileHeight ) ; for ( int x = 0 ; x < tileWidth ; x ++ ) { for ( int y = 0 ; y < tileHeight ; y ++ ) { Double value = values [ ( y * tileWidth ) + x ] ; float pixelValue = getPixelValue ( griddedTile , value ) ; setPixelValue ( image , x , y , pixelValue ) ; } } image . writeTiff ( ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public byte [ ] drawTileData ( GriddedTile griddedTile , Double [ ] values , int tileWidth , int tileHeight ) { CoverageDataTiffImage image = drawTile ( griddedTile , values , tileWidth , tileHeight ) ; byte [ ] bytes = image . getImageBytes ( ) ; return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new image [CODESPLIT] public CoverageDataTiffImage createImage ( int tileWidth , int tileHeight ) { Rasters rasters = new Rasters ( tileWidth , tileHeight , 1 , BITS_PER_SAMPLE , TiffConstants . SAMPLE_FORMAT_FLOAT ) ; int rowsPerStrip = rasters . calculateRowsPerStrip ( TiffConstants . PLANAR_CONFIGURATION_CHUNKY ) ; FileDirectory fileDirectory = new FileDirectory ( ) ; fileDirectory . setImageWidth ( tileWidth ) ; fileDirectory . setImageHeight ( tileHeight ) ; fileDirectory . setBitsPerSample ( BITS_PER_SAMPLE ) ; fileDirectory . setCompression ( TiffConstants . COMPRESSION_NO ) ; fileDirectory . setPhotometricInterpretation ( TiffConstants . PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO ) ; fileDirectory . setSamplesPerPixel ( SAMPLES_PER_PIXEL ) ; fileDirectory . setRowsPerStrip ( rowsPerStrip ) ; fileDirectory . setPlanarConfiguration ( TiffConstants . PLANAR_CONFIGURATION_CHUNKY ) ; fileDirectory . setSampleFormat ( TiffConstants . SAMPLE_FORMAT_FLOAT ) ; fileDirectory . setWriteRasters ( rasters ) ; CoverageDataTiffImage image = new CoverageDataTiffImage ( fileDirectory ) ; return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the pixel value into the image [CODESPLIT] public void setPixelValue ( CoverageDataTiffImage image , int x , int y , float pixelValue ) { image . getRasters ( ) . setFirstPixelSample ( x , y , pixelValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the coverage data tile table with metadata and extension [CODESPLIT] public static CoverageDataTiff createTileTableWithMetadata ( GeoPackage geoPackage , String tableName , BoundingBox contentsBoundingBox , long contentsSrsId , BoundingBox tileMatrixSetBoundingBox , long tileMatrixSetSrsId ) { CoverageDataTiff coverageData = ( CoverageDataTiff ) CoverageData . createTileTableWithMetadata ( geoPackage , tableName , contentsBoundingBox , contentsSrsId , tileMatrixSetBoundingBox , tileMatrixSetSrsId , GriddedCoverageDataType . FLOAT ) ; return coverageData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a JSON compatible object [CODESPLIT] public Object jsonCompatible ( boolean includePoints , boolean includeGeometries ) { Map < String , Object > jsonValues = new HashMap <> ( ) ; for ( String key : values . keySet ( ) ) { Object jsonValue = null ; Object value = values . get ( key ) ; if ( key . equals ( geometryColumn ) ) { GeoPackageGeometryData geometryData = ( GeoPackageGeometryData ) value ; if ( geometryData . getGeometry ( ) != null ) { if ( includeGeometries || ( includePoints && geometryData . getGeometry ( ) . getGeometryType ( ) == GeometryType . POINT ) ) { jsonValue = FeatureConverter . toMap ( geometryData . getGeometry ( ) ) ; } } else { jsonValue = value ; } if ( jsonValue != null ) { jsonValues . put ( key , jsonValue ) ; } } } return jsonValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cached GeoPackage or open and cache the GeoPackage [CODESPLIT] private GeoPackage getOrOpen ( String name , boolean writable , boolean cache ) { GeoPackage geoPackage = get ( name ) ; if ( geoPackage == null ) { geoPackage = manager . open ( name , writable ) ; if ( cache ) { add ( geoPackage ) ; } } return geoPackage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object getValue ( TColumn column ) { return getValue ( column . getIndex ( ) , column . getDataType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TRow getRow ( ) { TRow row ; if ( invalidCursor == null ) { row = getCurrentRow ( ) ; } else { row = invalidCursor . getRow ( ) ; } return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current row [CODESPLIT] private TRow getCurrentRow ( ) { TRow row = null ; if ( table != null ) { int [ ] columnTypes = new int [ table . columnCount ( ) ] ; Object [ ] values = new Object [ table . columnCount ( ) ] ; boolean valid = true ; for ( TColumn column : table . getColumns ( ) ) { int index = column . getIndex ( ) ; int columnType = getType ( index ) ; if ( column . isPrimaryKey ( ) && columnType == FIELD_TYPE_NULL ) { valid = false ; } columnTypes [ index ] = columnType ; values [ index ] = getValue ( column ) ; } row = getRow ( columnTypes , values ) ; if ( ! valid ) { invalidPositions . add ( getPosition ( ) ) ; row . setValid ( false ) ; } } return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object getValue ( int index , GeoPackageDataType dataType ) { return ResultUtils . getValue ( invalidCursor == null ? this : invalidCursor , index , dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable requery attempt of invalid rows after iterating through original query rows . Only supported for { @link #moveToNext () } and { @link #getRow () } usage . [CODESPLIT] protected void enableInvalidRequery ( UserDao < TColumn , TTable , TRow , ? extends UserCursor < TColumn , TTable , TRow > > dao ) { this . dao = dao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move to the next position of invalid rows to requery . Perform the requery the first time . [CODESPLIT] private boolean moveToNextInvalid ( ) { boolean hasNext = false ; // If requery has not been performed, a requery dao has been set, and there are invalid positions if ( invalidCursor == null && dao != null && hasInvalidPositions ( ) ) { // Close the original cursor when performing an invalid cursor query super . close ( ) ; // Set the blob columns to return as null List < TColumn > blobColumns = dao . getTable ( ) . columnsOfType ( GeoPackageDataType . BLOB ) ; String [ ] columnsAs = dao . buildColumnsAsNull ( blobColumns ) ; query . set ( UserQueryParamType . COLUMNS_AS , columnsAs ) ; // Query without blob columns and create an invalid cursor UserCursor < TColumn , TTable , TRow > requeryCursor = dao . query ( query ) ; invalidCursor = createInvalidCursor ( dao , requeryCursor , getInvalidPositions ( ) , blobColumns ) ; } if ( invalidCursor != null ) { hasNext = invalidCursor . moveToNext ( ) ; } return hasNext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BoundingBox getBoundingBox ( Projection projection ) { Contents contents = geometryColumns . getContents ( ) ; BoundingBox boundingBox = contents . getBoundingBox ( projection ) ; return boundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a JSON compatible object [CODESPLIT] public Object jsonCompatible ( boolean includePoints , boolean includeGeometries ) { Object jsonObject = null ; if ( rows == null || rows . isEmpty ( ) ) { jsonObject = count ; } else { List < Object > jsonRows = new ArrayList <> ( ) ; for ( FeatureRowData row : rows ) { jsonRows . add ( row . jsonCompatible ( includePoints , includeGeometries ) ) ; } jsonObject = jsonRows ; } return jsonObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for style mappings by base id [CODESPLIT] public List < StyleMappingRow > queryByBaseFeatureId ( long id ) { List < StyleMappingRow > rows = new ArrayList <> ( ) ; UserCustomCursor cursor = queryByBaseId ( id ) ; try { while ( cursor . moveToNext ( ) ) { rows . add ( getRow ( cursor ) ) ; } } finally { cursor . close ( ) ; } return rows ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete by base is and geometry type [CODESPLIT] public int deleteByBaseId ( long id , GeometryType geometryType ) { String geometryTypeName = null ; if ( geometryType != null ) { geometryTypeName = geometryType . getName ( ) ; } StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( StyleMappingTable . COLUMN_BASE_ID , id ) ) ; where . append ( \" AND \" ) ; where . append ( buildWhere ( StyleMappingTable . COLUMN_GEOMETRY_TYPE_NAME , geometryTypeName ) ) ; List < Object > whereArguments = new ArrayList <> ( ) ; whereArguments . add ( id ) ; if ( geometryTypeName != null ) { whereArguments . add ( geometryTypeName ) ; } String [ ] whereArgs = buildWhereArgs ( whereArguments ) ; int deleted = delete ( where . toString ( ) , whereArgs ) ; return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a rectangle using the tile width height bounding box and the bounding box section within the outer box to build the rectangle from [CODESPLIT] public static Rect getRectangle ( long width , long height , BoundingBox boundingBox , BoundingBox boundingBoxSection ) { RectF rectF = getFloatRectangle ( width , height , boundingBox , boundingBoxSection ) ; Rect rect = new Rect ( Math . round ( rectF . left ) , Math . round ( rectF . top ) , Math . round ( rectF . right ) , Math . round ( rectF . bottom ) ) ; return rect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a rectangle with rounded floating point boundaries using the tile width height bounding box and the bounding box section within the outer box to build the rectangle from [CODESPLIT] public static RectF getRoundedFloatRectangle ( long width , long height , BoundingBox boundingBox , BoundingBox boundingBoxSection ) { Rect rect = getRectangle ( width , height , boundingBox , boundingBoxSection ) ; RectF rectF = new RectF ( rect ) ; return rectF ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the rectangle is valid [CODESPLIT] public static boolean isValid ( Rect rect ) { return rect . left < rect . right && rect . top < rect . bottom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the rectangle is valid allowing empty ranges [CODESPLIT] public static boolean isValidAllowEmpty ( Rect rect ) { return rect . left <= rect . right && rect . top <= rect . bottom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the rectangle is valid [CODESPLIT] public static boolean isValid ( RectF rectF ) { return rectF . left < rectF . right && rectF . top < rectF . bottom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the rectangle is valid allowing empty ranges [CODESPLIT] public static boolean isValidAllowEmpty ( RectF rectF ) { return rectF . left <= rectF . right && rectF . top <= rectF . bottom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < String > databases ( ) { Set < String > sortedDatabases = new TreeSet < String > ( ) ; addDatabases ( sortedDatabases ) ; List < String > databases = new ArrayList < String > ( ) ; databases . addAll ( sortedDatabases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < String > databasesLike ( String like ) { List < String > databases = null ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; databases = dataSource . getMetadataWhereNameLike ( like , GeoPackageMetadata . COLUMN_NAME ) ; } finally { metadataDb . close ( ) ; } databases = deleteMissingDatabases ( databases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < String > databasesNotLike ( String notLike ) { List < String > databases = null ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; databases = dataSource . getMetadataWhereNameNotLike ( notLike , GeoPackageMetadata . COLUMN_NAME ) ; } finally { metadataDb . close ( ) ; } databases = deleteMissingDatabases ( databases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete all databases that do not exist or the database file does not exist [CODESPLIT] private List < String > deleteMissingDatabases ( List < String > databases ) { List < String > filesExist = new ArrayList <> ( ) ; for ( String database : databases ) { if ( exists ( database ) ) { filesExist . add ( database ) ; } } return filesExist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < String > internalDatabases ( ) { Set < String > sortedDatabases = new TreeSet < String > ( ) ; addInternalDatabases ( sortedDatabases ) ; List < String > databases = new ArrayList < String > ( ) ; databases . addAll ( sortedDatabases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public List < String > externalDatabases ( ) { Set < String > sortedDatabases = new TreeSet < String > ( ) ; addExternalDatabases ( sortedDatabases ) ; List < String > databases = new ArrayList < String > ( ) ; databases . addAll ( sortedDatabases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Set < String > databaseSet ( ) { Set < String > databases = new HashSet < String > ( ) ; addDatabases ( databases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Set < String > internalDatabaseSet ( ) { Set < String > databases = new HashSet < String > ( ) ; addInternalDatabases ( databases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Set < String > externalDatabaseSet ( ) { Set < String > databases = new HashSet < String > ( ) ; addExternalDatabases ( databases ) ; return databases ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean exists ( String database ) { boolean exists = internalDatabaseSet ( ) . contains ( database ) ; if ( ! exists ) { GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; GeoPackageMetadata metadata = dataSource . get ( database ) ; if ( metadata != null ) { if ( metadata . getExternalPath ( ) != null && ! new File ( metadata . getExternalPath ( ) ) . exists ( ) ) { delete ( database ) ; } else { exists = true ; } } } finally { metadataDb . close ( ) ; } } return exists ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public long size ( String database ) { File dbFile = getFile ( database ) ; long size = dbFile . length ( ) ; return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean isExternal ( String database ) { boolean external = false ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; external = dataSource . isExternal ( database ) ; } finally { metadataDb . close ( ) ; } return external ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean existsAtExternalPath ( String path ) { GeoPackageMetadata metadata = getGeoPackageMetadataAtExternalPath ( path ) ; return metadata != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String getPath ( String database ) { File dbFile = getFile ( database ) ; String path = dbFile . getAbsolutePath ( ) ; return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public File getFile ( String database ) { File dbFile = null ; GeoPackageMetadata metadata = getGeoPackageMetadata ( database ) ; if ( metadata != null && metadata . isExternal ( ) ) { dbFile = new File ( metadata . getExternalPath ( ) ) ; } else { dbFile = context . getDatabasePath ( database ) ; } if ( dbFile == null || ! dbFile . exists ( ) ) { throw new GeoPackageException ( \"GeoPackage does not exist: \" + database ) ; } return dbFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String getDatabaseAtExternalPath ( String path ) { String database = null ; GeoPackageMetadata metadata = getGeoPackageMetadataAtExternalPath ( path ) ; if ( metadata != null ) { database = metadata . getName ( ) ; } return database ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String readableSize ( String database ) { long size = size ( database ) ; return GeoPackageIOUtils . formatBytes ( size ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean delete ( String database ) { boolean deleted = false ; boolean external = isExternal ( database ) ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; deleted = dataSource . delete ( database ) ; } finally { metadataDb . close ( ) ; } if ( ! external ) { deleted = context . deleteDatabase ( database ) ; } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean deleteAll ( ) { boolean deleted = true ; for ( String database : databaseSet ( ) ) { deleted = delete ( database ) && deleted ; } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean deleteAllExternal ( ) { boolean deleted = true ; for ( String database : externalDatabaseSet ( ) ) { deleted = delete ( database ) && deleted ; } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean deleteAllMissingExternal ( ) { boolean deleted = false ; List < GeoPackageMetadata > externalGeoPackages = getExternalGeoPackages ( ) ; for ( GeoPackageMetadata external : externalGeoPackages ) { if ( ! new File ( external . getExternalPath ( ) ) . exists ( ) ) { deleted = delete ( external . getName ( ) ) || deleted ; } } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean create ( String database ) { boolean created = false ; if ( exists ( database ) ) { throw new GeoPackageException ( \"GeoPackage already exists: \" + database ) ; } else { GeoPackageDatabase db = new GeoPackageDatabase ( context . openOrCreateDatabase ( database , Context . MODE_PRIVATE , null ) ) ; createAndCloseGeoPackage ( db ) ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; // Save in metadata GeoPackageMetadata metadata = new GeoPackageMetadata ( ) ; metadata . setName ( database ) ; dataSource . create ( metadata ) ; } finally { metadataDb . close ( ) ; } created = true ; } return created ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the required GeoPackage application id and tables in the newly created and open database connection . Then close the connection . [CODESPLIT] private void createAndCloseGeoPackage ( GeoPackageDatabase db ) { GeoPackageConnection connection = new GeoPackageConnection ( db ) ; // Set the GeoPackage application id and user version connection . setApplicationId ( ) ; connection . setUserVersion ( ) ; // Create the minimum required tables GeoPackageTableCreator tableCreator = new GeoPackageTableCreator ( connection ) ; tableCreator . createRequired ( ) ; connection . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean createAtPath ( String database , File path ) { // Create the absolute file path File file = new File ( path , database + \".\" + GeoPackageConstants . GEOPACKAGE_EXTENSION ) ; // Create the GeoPackage boolean created = createFile ( database , file ) ; return created ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean createFile ( File file ) { // Get the database name String database = GeoPackageIOUtils . getFileNameWithoutExtension ( file ) ; // Create the GeoPackage boolean created = createFile ( database , file ) ; return created ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean createFile ( String database , File file ) { boolean created = false ; if ( exists ( database ) ) { throw new GeoPackageException ( \"GeoPackage already exists: \" + database ) ; } else { // Check if the path is an absolute path to the GeoPackage file to create if ( ! GeoPackageValidate . hasGeoPackageExtension ( file ) ) { // Make sure this isn't a path to another file extension if ( GeoPackageIOUtils . getFileExtension ( file ) != null ) { throw new GeoPackageException ( \"File can not have a non GeoPackage extension. Invalid File: \" + file . getAbsolutePath ( ) ) ; } // Add the extension file = new File ( file . getParentFile ( ) , file . getName ( ) + \".\" + GeoPackageConstants . GEOPACKAGE_EXTENSION ) ; } // Make sure the file does not already exist if ( file . exists ( ) ) { throw new GeoPackageException ( \"GeoPackage file already exists: \" + file . getAbsolutePath ( ) ) ; } // Create the new GeoPackage file GeoPackageDatabase db = new GeoPackageDatabase ( SQLiteDatabase . openOrCreateDatabase ( file , null ) ) ; createAndCloseGeoPackage ( db ) ; // Import the GeoPackage created = importGeoPackageAsExternalLink ( file , database ) ; } return created ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String database , InputStream stream ) { return importGeoPackage ( database , stream , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String database , InputStream stream , GeoPackageProgress progress ) { return importGeoPackage ( database , stream , false , progress ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String database , InputStream stream , boolean override ) { return importGeoPackage ( database , stream , override , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String database , InputStream stream , boolean override , GeoPackageProgress progress ) { if ( progress != null ) { try { int streamLength = stream . available ( ) ; if ( streamLength > 0 ) { progress . setMax ( streamLength ) ; } } catch ( IOException e ) { Log . w ( GeoPackageManagerImpl . class . getSimpleName ( ) , \"Could not determine stream available size. Database: \" + database , e ) ; } } boolean success = importGeoPackage ( database , override , stream , progress ) ; return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String name , File file ) { return importGeoPackage ( name , file , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String name , File file , boolean override ) { // Verify the file has the right extension GeoPackageValidate . validateGeoPackageExtension ( file ) ; // Use the provided name or the base file name as the database name String database ; if ( name != null ) { database = name ; } else { database = GeoPackageIOUtils . getFileNameWithoutExtension ( file ) ; } boolean success = false ; try { FileInputStream geoPackageStream = new FileInputStream ( file ) ; success = importGeoPackage ( database , override , geoPackageStream , null ) ; } catch ( FileNotFoundException e ) { throw new GeoPackageException ( \"Failed read or write GeoPackage file '\" + file + \"' to database: '\" + database + \"'\" , e ) ; } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String name , URL url ) { return importGeoPackage ( name , url , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String name , URL url , GeoPackageProgress progress ) { return importGeoPackage ( name , url , false , progress ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String name , URL url , boolean override ) { return importGeoPackage ( name , url , override , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackage ( String name , URL url , boolean override , GeoPackageProgress progress ) { boolean success = false ; HttpURLConnection connection = null ; try { connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . connect ( ) ; int responseCode = connection . getResponseCode ( ) ; if ( responseCode == HttpURLConnection . HTTP_MOVED_PERM || responseCode == HttpURLConnection . HTTP_MOVED_TEMP || responseCode == HttpURLConnection . HTTP_SEE_OTHER ) { String redirect = connection . getHeaderField ( \"Location\" ) ; connection . disconnect ( ) ; url = new URL ( redirect ) ; connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . connect ( ) ; } if ( connection . getResponseCode ( ) != HttpURLConnection . HTTP_OK ) { throw new GeoPackageException ( \"Failed to import GeoPackage \" + name + \" from URL: '\" + url . toString ( ) + \"'. HTTP \" + connection . getResponseCode ( ) + \" \" + connection . getResponseMessage ( ) ) ; } int fileLength = connection . getContentLength ( ) ; if ( fileLength != - 1 && progress != null ) { progress . setMax ( fileLength ) ; } InputStream geoPackageStream = connection . getInputStream ( ) ; success = importGeoPackage ( name , override , geoPackageStream , progress ) ; } catch ( IOException e ) { throw new GeoPackageException ( \"Failed to import GeoPackage \" + name + \" from URL: '\" + url . toString ( ) + \"'\" , e ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void exportGeoPackage ( String database , File directory ) { exportGeoPackage ( database , database , directory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void exportGeoPackage ( String database , String name , File directory ) { File file = new File ( directory , name ) ; // Add the extension if not on the name if ( ! GeoPackageValidate . hasGeoPackageExtension ( file ) ) { name += \".\" + GeoPackageConstants . GEOPACKAGE_EXTENSION ; file = new File ( directory , name ) ; } // Copy the geopackage database to the new file location File dbFile = getFile ( database ) ; try { GeoPackageIOUtils . copyFile ( dbFile , file ) ; } catch ( IOException e ) { throw new GeoPackageException ( \"Failed read or write GeoPackage database '\" + database + \"' to file: '\" + file , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public GeoPackage open ( String database , boolean writable ) { GeoPackage db = null ; if ( exists ( database ) ) { GeoPackageCursorFactory cursorFactory = new GeoPackageCursorFactory ( ) ; String path = null ; SQLiteDatabase sqlite = null ; GeoPackageMetadata metadata = getGeoPackageMetadata ( database ) ; if ( metadata != null && metadata . isExternal ( ) ) { path = metadata . getExternalPath ( ) ; if ( writable ) { try { sqlite = SQLiteDatabase . openDatabase ( path , cursorFactory , SQLiteDatabase . OPEN_READWRITE | SQLiteDatabase . NO_LOCALIZED_COLLATORS ) ; } catch ( Exception e ) { Log . e ( GeoPackageManagerImpl . class . getSimpleName ( ) , \"Failed to open database as writable: \" + database , e ) ; } } if ( sqlite == null ) { sqlite = SQLiteDatabase . openDatabase ( path , cursorFactory , SQLiteDatabase . OPEN_READONLY | SQLiteDatabase . NO_LOCALIZED_COLLATORS ) ; writable = false ; } } else { sqlite = context . openOrCreateDatabase ( database , Context . MODE_PRIVATE , cursorFactory ) ; } if ( sqliteWriteAheadLogging ) { sqlite . enableWriteAheadLogging ( ) ; } else { sqlite . disableWriteAheadLogging ( ) ; } // Validate the database if validation is enabled validateDatabaseAndCloseOnError ( sqlite , openHeaderValidation , openIntegrityValidation ) ; GeoPackageConnection connection = new GeoPackageConnection ( new GeoPackageDatabase ( sqlite ) ) ; GeoPackageTableCreator tableCreator = new GeoPackageTableCreator ( connection ) ; db = new GeoPackageImpl ( context , database , path , connection , cursorFactory , tableCreator , writable ) ; // Validate the GeoPackage has the minimum required tables try { GeoPackageValidate . validateMinimumTables ( db ) ; } catch ( RuntimeException e ) { db . close ( ) ; throw e ; } } return db ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean validate ( String database ) { boolean valid = isValid ( database , true , true ) ; return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean validateHeader ( String database ) { boolean valid = isValid ( database , true , false ) ; return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean validateIntegrity ( String database ) { boolean valid = isValid ( database , false , true ) ; return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the GeoPackage database [CODESPLIT] private boolean isValid ( String database , boolean validateHeader , boolean validateIntegrity ) { boolean valid = false ; if ( exists ( database ) ) { GeoPackageCursorFactory cursorFactory = new GeoPackageCursorFactory ( ) ; String path = null ; SQLiteDatabase sqlite ; GeoPackageMetadata metadata = getGeoPackageMetadata ( database ) ; if ( metadata != null && metadata . isExternal ( ) ) { path = metadata . getExternalPath ( ) ; try { sqlite = SQLiteDatabase . openDatabase ( path , cursorFactory , SQLiteDatabase . OPEN_READWRITE | SQLiteDatabase . NO_LOCALIZED_COLLATORS ) ; } catch ( Exception e ) { sqlite = SQLiteDatabase . openDatabase ( path , cursorFactory , SQLiteDatabase . OPEN_READONLY | SQLiteDatabase . NO_LOCALIZED_COLLATORS ) ; } } else { path = context . getDatabasePath ( database ) . getAbsolutePath ( ) ; sqlite = context . openOrCreateDatabase ( database , Context . MODE_PRIVATE , cursorFactory ) ; } try { valid = ( ! validateHeader || isDatabaseHeaderValid ( sqlite ) ) && ( ! validateIntegrity || sqlite . isDatabaseIntegrityOk ( ) ) ; } catch ( Exception e ) { Log . e ( GeoPackageManagerImpl . class . getSimpleName ( ) , \"Failed to validate database\" , e ) ; } finally { sqlite . close ( ) ; } } return valid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean copy ( String database , String databaseCopy ) { // Copy the database as a new file File dbFile = getFile ( database ) ; File dbCopyFile = context . getDatabasePath ( databaseCopy ) ; try { GeoPackageIOUtils . copyFile ( dbFile , dbCopyFile ) ; } catch ( IOException e ) { throw new GeoPackageException ( \"Failed to copy GeoPackage database '\" + database + \"' to '\" + databaseCopy + \"'\" , e ) ; } return exists ( databaseCopy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean rename ( String database , String newDatabase ) { GeoPackageMetadata metadata = getGeoPackageMetadata ( database ) ; if ( metadata != null ) { GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; dataSource . rename ( metadata , newDatabase ) ; } finally { metadataDb . close ( ) ; } } if ( ( metadata == null || ! metadata . isExternal ( ) ) && copy ( database , newDatabase ) ) { delete ( database ) ; } return exists ( newDatabase ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackageAsExternalLink ( File path , String database ) { return importGeoPackageAsExternalLink ( path , database , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackageAsExternalLink ( File path , String database , boolean override ) { return importGeoPackageAsExternalLink ( path . getAbsolutePath ( ) , database , override ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean importGeoPackageAsExternalLink ( String path , String database , boolean override ) { if ( exists ( database ) ) { if ( override ) { if ( ! delete ( database ) ) { throw new GeoPackageException ( \"Failed to delete existing database: \" + database ) ; } } else { throw new GeoPackageException ( \"GeoPackage database already exists: \" + database ) ; } } // Verify the file is a database and can be opened try { SQLiteDatabase sqlite = SQLiteDatabase . openDatabase ( path , null , SQLiteDatabase . OPEN_READONLY | SQLiteDatabase . NO_LOCALIZED_COLLATORS ) ; validateDatabaseAndClose ( sqlite , importHeaderValidation , importIntegrityValidation ) ; } catch ( SQLiteException e ) { throw new GeoPackageException ( \"Failed to import GeoPackage database as external link: \" + database + \", Path: \" + path , e ) ; } GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; // Save the external link in metadata GeoPackageMetadata metadata = new GeoPackageMetadata ( ) ; metadata . setName ( database ) ; metadata . setExternalPath ( path ) ; dataSource . create ( metadata ) ; GeoPackage geoPackage = open ( database , false ) ; if ( geoPackage != null ) { try { GeoPackageValidate . validateMinimumTables ( geoPackage ) ; } catch ( RuntimeException e ) { dataSource . delete ( database ) ; throw e ; } finally { geoPackage . close ( ) ; } } else { dataSource . delete ( database ) ; throw new GeoPackageException ( \"Unable to open GeoPackage database. Database: \" + database ) ; } } finally { metadataDb . close ( ) ; } return exists ( database ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the database and close when validation fails . Throw an error when not valid . [CODESPLIT] private void validateDatabaseAndCloseOnError ( SQLiteDatabase sqliteDatabase , boolean validateHeader , boolean validateIntegrity ) { validateDatabase ( sqliteDatabase , validateHeader , validateIntegrity , false , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the database and close it . Throw an error when not valid . [CODESPLIT] private void validateDatabaseAndClose ( SQLiteDatabase sqliteDatabase , boolean validateHeader , boolean validateIntegrity ) { validateDatabase ( sqliteDatabase , validateHeader , validateIntegrity , true , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the database header and integrity . Throw an error when not valid . [CODESPLIT] private void validateDatabase ( SQLiteDatabase sqliteDatabase , boolean validateHeader , boolean validateIntegrity , boolean close , boolean closeOnError ) { try { if ( validateHeader ) { validateDatabaseHeader ( sqliteDatabase ) ; } if ( validateIntegrity ) { validateDatabaseIntegrity ( sqliteDatabase ) ; } } catch ( Exception e ) { if ( closeOnError ) { sqliteDatabase . close ( ) ; } throw e ; } if ( close ) { sqliteDatabase . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the header of the database file to verify it is a sqlite database [CODESPLIT] private void validateDatabaseHeader ( SQLiteDatabase sqliteDatabase ) { boolean validHeader = isDatabaseHeaderValid ( sqliteDatabase ) ; if ( ! validHeader ) { throw new GeoPackageException ( \"GeoPackage SQLite header is not valid: \" + sqliteDatabase . getPath ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the header of the database file is valid [CODESPLIT] private boolean isDatabaseHeaderValid ( SQLiteDatabase sqliteDatabase ) { boolean validHeader = false ; FileInputStream fis = null ; try { fis = new FileInputStream ( sqliteDatabase . getPath ( ) ) ; byte [ ] headerBytes = new byte [ 16 ] ; if ( fis . read ( headerBytes ) == 16 ) { ByteReader byteReader = new ByteReader ( headerBytes ) ; String header = byteReader . readString ( headerBytes . length ) ; String headerPrefix = header . substring ( 0 , GeoPackageConstants . SQLITE_HEADER_PREFIX . length ( ) ) ; validHeader = headerPrefix . equalsIgnoreCase ( GeoPackageConstants . SQLITE_HEADER_PREFIX ) ; } } catch ( Exception e ) { Log . e ( GeoPackageManagerImpl . class . getSimpleName ( ) , \"Failed to retrieve database header\" , e ) ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { // eat } } } return validHeader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all internal databases to the collection [CODESPLIT] private void addInternalDatabases ( Collection < String > databases ) { String [ ] databaseArray = context . databaseList ( ) ; for ( String database : databaseArray ) { if ( ! isTemporary ( database ) && ! database . equalsIgnoreCase ( GeoPackageMetadataDb . DATABASE_NAME ) ) { databases . add ( database ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all external databases to the collection [CODESPLIT] private void addExternalDatabases ( Collection < String > databases ) { // Get the external GeoPackages, adding those where the file exists and // deleting those with missing files List < GeoPackageMetadata > externalGeoPackages = getExternalGeoPackages ( ) ; for ( GeoPackageMetadata external : externalGeoPackages ) { if ( new File ( external . getExternalPath ( ) ) . exists ( ) ) { databases . add ( external . getName ( ) ) ; } else { delete ( external . getName ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Import the GeoPackage stream [CODESPLIT] private boolean importGeoPackage ( String database , boolean override , InputStream geoPackageStream , GeoPackageProgress progress ) { try { if ( exists ( database ) ) { if ( override ) { if ( ! delete ( database ) ) { throw new GeoPackageException ( \"Failed to delete existing database: \" + database ) ; } } else { throw new GeoPackageException ( \"GeoPackage database already exists: \" + database ) ; } } // Copy the geopackage over as a database File newDbFile = context . getDatabasePath ( database ) ; try { SQLiteDatabase db = context . openOrCreateDatabase ( database , Context . MODE_PRIVATE , null ) ; db . close ( ) ; GeoPackageIOUtils . copyStream ( geoPackageStream , newDbFile , progress ) ; } catch ( IOException e ) { throw new GeoPackageException ( \"Failed to import GeoPackage database: \" + database , e ) ; } } finally { GeoPackageIOUtils . closeQuietly ( geoPackageStream ) ; } if ( progress == null || progress . isActive ( ) ) { // Verify that the database is valid try { SQLiteDatabase sqlite = context . openOrCreateDatabase ( database , Context . MODE_PRIVATE , null , new DatabaseErrorHandler ( ) { @ Override public void onCorruption ( SQLiteDatabase dbObj ) { } } ) ; validateDatabaseAndClose ( sqlite , importHeaderValidation , importIntegrityValidation ) ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; // Save in metadata GeoPackageMetadata metadata = new GeoPackageMetadata ( ) ; metadata . setName ( database ) ; dataSource . create ( metadata ) ; } finally { metadataDb . close ( ) ; } } catch ( Exception e ) { delete ( database ) ; throw new GeoPackageException ( \"Invalid GeoPackage database file\" , e ) ; } GeoPackage geoPackage = open ( database , false ) ; if ( geoPackage != null ) { try { if ( ! geoPackage . getSpatialReferenceSystemDao ( ) . isTableExists ( ) || ! geoPackage . getContentsDao ( ) . isTableExists ( ) ) { delete ( database ) ; throw new GeoPackageException ( \"Invalid GeoPackage database file. Does not contain required tables: \" + SpatialReferenceSystem . TABLE_NAME + \" & \" + Contents . TABLE_NAME + \", Database: \" + database ) ; } } catch ( SQLException e ) { delete ( database ) ; throw new GeoPackageException ( \"Invalid GeoPackage database file. Could not verify existence of required tables: \" + SpatialReferenceSystem . TABLE_NAME + \" & \" + Contents . TABLE_NAME + \", Database: \" + database ) ; } finally { geoPackage . close ( ) ; } } else { delete ( database ) ; throw new GeoPackageException ( \"Unable to open GeoPackage database. Database: \" + database ) ; } } return exists ( database ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all external GeoPackage metadata [CODESPLIT] private List < GeoPackageMetadata > getExternalGeoPackages ( ) { List < GeoPackageMetadata > metadata = null ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; metadata = dataSource . getAllExternal ( ) ; } finally { metadataDb . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the GeoPackage metadata [CODESPLIT] private GeoPackageMetadata getGeoPackageMetadata ( String database ) { GeoPackageMetadata metadata = null ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; metadata = dataSource . get ( database ) ; } finally { metadataDb . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the GeoPackage metadata of the database at the external path [CODESPLIT] private GeoPackageMetadata getGeoPackageMetadataAtExternalPath ( String path ) { GeoPackageMetadata metadata = null ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; metadata = dataSource . getExternalAtPath ( path ) ; } finally { metadataDb . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the database is temporary ( rollback journal ) [CODESPLIT] private boolean isTemporary ( String database ) { return database . endsWith ( context . getString ( R . string . geopackage_db_rollback_journal_suffix ) ) || database . endsWith ( context . getString ( R . string . geopackage_db_write_ahead_log_suffix ) ) || database . endsWith ( context . getString ( R . string . geopackage_db_shared_memory_suffix ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new geometry metadata [CODESPLIT] public long create ( GeometryMetadata metadata ) { ContentValues values = new ContentValues ( ) ; values . put ( GeometryMetadata . COLUMN_GEOPACKAGE_ID , metadata . getGeoPackageId ( ) ) ; values . put ( GeometryMetadata . COLUMN_TABLE_NAME , metadata . getTableName ( ) ) ; values . put ( GeometryMetadata . COLUMN_ID , metadata . getId ( ) ) ; values . put ( GeometryMetadata . COLUMN_MIN_X , metadata . getMinX ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_X , metadata . getMaxX ( ) ) ; values . put ( GeometryMetadata . COLUMN_MIN_Y , metadata . getMinY ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_Y , metadata . getMaxY ( ) ) ; values . put ( GeometryMetadata . COLUMN_MIN_Z , metadata . getMinZ ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_Z , metadata . getMaxZ ( ) ) ; values . put ( GeometryMetadata . COLUMN_MIN_M , metadata . getMinM ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_M , metadata . getMaxM ( ) ) ; long insertId = db . insert ( GeometryMetadata . TABLE_NAME , null , values ) ; if ( insertId == - 1 ) { throw new GeoPackageException ( \"Failed to insert geometry metadata. GeoPackage Id: \" + metadata . getGeoPackageId ( ) + \", Table Name: \" + metadata . getTableName ( ) + \", Geometry Id: \" + metadata . getId ( ) ) ; } metadata . setId ( insertId ) ; return insertId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new geometry metadata from an envelope [CODESPLIT] public GeometryMetadata create ( String geoPackage , String tableName , long geomId , GeometryEnvelope envelope ) { return create ( getGeoPackageId ( geoPackage ) , tableName , geomId , envelope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new geometry metadata from an envelope [CODESPLIT] public GeometryMetadata create ( long geoPackageId , String tableName , long geomId , GeometryEnvelope envelope ) { GeometryMetadata metadata = populate ( geoPackageId , tableName , geomId , envelope ) ; create ( metadata ) ; return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate a new geometry metadata from an envelope [CODESPLIT] public GeometryMetadata populate ( long geoPackageId , String tableName , long geomId , GeometryEnvelope envelope ) { GeometryMetadata metadata = new GeometryMetadata ( ) ; metadata . setGeoPackageId ( geoPackageId ) ; metadata . setTableName ( tableName ) ; metadata . setId ( geomId ) ; metadata . setMinX ( envelope . getMinX ( ) ) ; metadata . setMaxX ( envelope . getMaxX ( ) ) ; metadata . setMinY ( envelope . getMinY ( ) ) ; metadata . setMaxY ( envelope . getMaxY ( ) ) ; if ( envelope . hasZ ( ) ) { metadata . setMinZ ( envelope . getMinZ ( ) ) ; metadata . setMaxZ ( envelope . getMaxZ ( ) ) ; } if ( envelope . hasM ( ) ) { metadata . setMinM ( envelope . getMinM ( ) ) ; metadata . setMaxM ( envelope . getMaxM ( ) ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the geometry metadata [CODESPLIT] public boolean delete ( GeometryMetadata metadata ) { return delete ( metadata . getGeoPackageId ( ) , metadata . getTableName ( ) , metadata . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete geometry metadata by database [CODESPLIT] public int delete ( long geoPackageId ) { String whereClause = GeometryMetadata . COLUMN_GEOPACKAGE_ID + \" = ?\" ; String [ ] whereArgs = new String [ ] { String . valueOf ( geoPackageId ) } ; int deleteCount = db . delete ( GeometryMetadata . TABLE_NAME , whereClause , whereArgs ) ; return deleteCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the geometry metadata [CODESPLIT] public boolean delete ( String geoPackage , String tableName , long id ) { return delete ( getGeoPackageId ( geoPackage ) , tableName , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the geometry metadata or update if it already exists [CODESPLIT] public boolean createOrUpdate ( GeometryMetadata metadata ) { boolean success = false ; if ( exists ( metadata ) ) { success = update ( metadata ) ; } else { create ( metadata ) ; success = true ; } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the geometry metadata [CODESPLIT] public boolean update ( GeometryMetadata metadata ) { String whereClause = GeometryMetadata . COLUMN_GEOPACKAGE_ID + \" = ? AND \" + GeometryMetadata . COLUMN_TABLE_NAME + \" = ? AND \" + GeometryMetadata . COLUMN_ID + \" = ?\" ; String [ ] whereArgs = new String [ ] { String . valueOf ( metadata . getGeoPackageId ( ) ) , metadata . getTableName ( ) , String . valueOf ( metadata . getId ( ) ) } ; ContentValues values = new ContentValues ( ) ; values . put ( GeometryMetadata . COLUMN_MIN_X , metadata . getMinX ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_X , metadata . getMaxX ( ) ) ; values . put ( GeometryMetadata . COLUMN_MIN_Y , metadata . getMinY ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_Y , metadata . getMaxY ( ) ) ; values . put ( GeometryMetadata . COLUMN_MIN_Z , metadata . getMinZ ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_Z , metadata . getMaxZ ( ) ) ; values . put ( GeometryMetadata . COLUMN_MIN_M , metadata . getMinM ( ) ) ; values . put ( GeometryMetadata . COLUMN_MAX_M , metadata . getMaxM ( ) ) ; int updateCount = db . update ( GeometryMetadata . TABLE_NAME , values , whereClause , whereArgs ) ; return updateCount > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a table metadata [CODESPLIT] public GeometryMetadata get ( GeometryMetadata metadata ) { return get ( metadata . getGeoPackageId ( ) , metadata . getTableName ( ) , metadata . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a table metadata [CODESPLIT] public GeometryMetadata get ( String geoPackage , String tableName , long id ) { return get ( getGeoPackageId ( geoPackage ) , tableName , id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a table metadata [CODESPLIT] public GeometryMetadata get ( long geoPackageId , String tableName , long id ) { String selection = GeometryMetadata . COLUMN_GEOPACKAGE_ID + \" = ? AND \" + GeometryMetadata . COLUMN_TABLE_NAME + \" = ? AND \" + GeometryMetadata . COLUMN_ID + \" = ?\" ; String [ ] selectionArgs = new String [ ] { String . valueOf ( geoPackageId ) , tableName , String . valueOf ( id ) } ; Cursor cursor = db . query ( GeometryMetadata . TABLE_NAME , GeometryMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; GeometryMetadata metadata = null ; try { if ( cursor . moveToNext ( ) ) { metadata = createGeometryMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata [CODESPLIT] public Cursor query ( String geoPackage , String tableName ) { return query ( getGeoPackageId ( geoPackage ) , tableName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for the bounds of the feature table index [CODESPLIT] public BoundingBox getBoundingBox ( String geoPackage , String tableName ) { return getBoundingBox ( getGeoPackageId ( geoPackage ) , tableName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for the bounds of the feature table index [CODESPLIT] public BoundingBox getBoundingBox ( long geoPackageId , String tableName ) { BoundingBox boundingBox = null ; Cursor result = db . rawQuery ( \"SELECT MIN(\" + GeometryMetadata . COLUMN_MIN_X + \"), MIN(\" + GeometryMetadata . COLUMN_MIN_Y + \"), MAX(\" + GeometryMetadata . COLUMN_MAX_X + \"), MAX(\" + GeometryMetadata . COLUMN_MAX_Y + \") FROM \" + GeometryMetadata . TABLE_NAME + \" WHERE \" + GeometryMetadata . COLUMN_GEOPACKAGE_ID + \" = ? AND \" + GeometryMetadata . COLUMN_TABLE_NAME + \" = ?\" , new String [ ] { String . valueOf ( geoPackageId ) , tableName } ) ; try { if ( result . moveToNext ( ) ) { boundingBox = new BoundingBox ( result . getDouble ( 0 ) , result . getDouble ( 1 ) , result . getDouble ( 2 ) , result . getDouble ( 3 ) ) ; } } finally { result . close ( ) ; } return boundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata [CODESPLIT] public Cursor query ( long geoPackageId , String tableName ) { String selection = GeometryMetadata . COLUMN_GEOPACKAGE_ID + \" = ? AND \" + GeometryMetadata . COLUMN_TABLE_NAME + \" = ?\" ; String [ ] selectionArgs = new String [ ] { String . valueOf ( geoPackageId ) , tableName } ; Cursor cursor = db . query ( GeometryMetadata . TABLE_NAME , GeometryMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata matching the bounding box in the same projection [CODESPLIT] public Cursor query ( String geoPackage , String tableName , BoundingBox boundingBox ) { return query ( getGeoPackageId ( geoPackage ) , tableName , boundingBox ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata count matching the bounding box in the same projection [CODESPLIT] public int count ( String geoPackage , String tableName , BoundingBox boundingBox ) { return count ( getGeoPackageId ( geoPackage ) , tableName , boundingBox ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata matching the bounding box in the same projection [CODESPLIT] public Cursor query ( long geoPackageId , String tableName , BoundingBox boundingBox ) { GeometryEnvelope envelope = new GeometryEnvelope ( ) ; envelope . setMinX ( boundingBox . getMinLongitude ( ) ) ; envelope . setMaxX ( boundingBox . getMaxLongitude ( ) ) ; envelope . setMinY ( boundingBox . getMinLatitude ( ) ) ; envelope . setMaxY ( boundingBox . getMaxLatitude ( ) ) ; return query ( geoPackageId , tableName , envelope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata matching the envelope [CODESPLIT] public Cursor query ( String geoPackage , String tableName , GeometryEnvelope envelope ) { return query ( getGeoPackageId ( geoPackage ) , tableName , envelope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata count matching the envelope [CODESPLIT] public int count ( String geoPackage , String tableName , GeometryEnvelope envelope ) { return count ( getGeoPackageId ( geoPackage ) , tableName , envelope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata matching the envelope [CODESPLIT] public Cursor query ( long geoPackageId , String tableName , GeometryEnvelope envelope ) { StringBuilder selection = new StringBuilder ( ) ; selection . append ( GeometryMetadata . COLUMN_GEOPACKAGE_ID ) . append ( \" = ? AND \" ) . append ( GeometryMetadata . COLUMN_TABLE_NAME ) . append ( \" = ?\" ) ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MIN_X ) . append ( \" <= ?\" ) ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MAX_X ) . append ( \" >= ?\" ) ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MIN_Y ) . append ( \" <= ?\" ) ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MAX_Y ) . append ( \" >= ?\" ) ; int args = 6 ; if ( envelope . hasZ ( ) ) { args += 2 ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MIN_Z ) . append ( \" <= ?\" ) ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MAX_Z ) . append ( \" >= ?\" ) ; } if ( envelope . hasM ( ) ) { args += 2 ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MIN_M ) . append ( \" <= ?\" ) ; selection . append ( \" AND \" ) . append ( GeometryMetadata . COLUMN_MAX_M ) . append ( \" >= ?\" ) ; } double minX = envelope . getMinX ( ) - tolerance ; double maxX = envelope . getMaxX ( ) + tolerance ; double minY = envelope . getMinY ( ) - tolerance ; double maxY = envelope . getMaxY ( ) + tolerance ; String [ ] selectionArgs = new String [ args ] ; int argCount = 0 ; selectionArgs [ argCount ++ ] = String . valueOf ( geoPackageId ) ; selectionArgs [ argCount ++ ] = tableName ; selectionArgs [ argCount ++ ] = String . valueOf ( maxX ) ; selectionArgs [ argCount ++ ] = String . valueOf ( minX ) ; selectionArgs [ argCount ++ ] = String . valueOf ( maxY ) ; selectionArgs [ argCount ++ ] = String . valueOf ( minY ) ; if ( envelope . hasZ ( ) ) { double minZ = envelope . getMinZ ( ) - tolerance ; double maxZ = envelope . getMaxZ ( ) + tolerance ; selectionArgs [ argCount ++ ] = String . valueOf ( maxZ ) ; selectionArgs [ argCount ++ ] = String . valueOf ( minZ ) ; } if ( envelope . hasM ( ) ) { double minM = envelope . getMinM ( ) - tolerance ; double maxM = envelope . getMaxM ( ) + tolerance ; selectionArgs [ argCount ++ ] = String . valueOf ( maxM ) ; selectionArgs [ argCount ++ ] = String . valueOf ( minM ) ; } Cursor cursor = db . query ( GeometryMetadata . TABLE_NAME , GeometryMetadata . COLUMNS , selection . toString ( ) , selectionArgs , null , null , null ) ; return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all table geometry metadata count matching the envelope [CODESPLIT] public int count ( long geoPackageId , String tableName , GeometryEnvelope envelope ) { Cursor cursor = query ( geoPackageId , tableName , envelope ) ; int count = cursor . getCount ( ) ; cursor . close ( ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a geometry metadata from the current cursor location [CODESPLIT] public static GeometryMetadata createGeometryMetadata ( Cursor cursor ) { GeometryMetadata metadata = new GeometryMetadata ( ) ; metadata . setGeoPackageId ( cursor . getLong ( 0 ) ) ; metadata . setTableName ( cursor . getString ( 1 ) ) ; metadata . setId ( cursor . getLong ( 2 ) ) ; metadata . setMinX ( cursor . getDouble ( 3 ) ) ; metadata . setMaxX ( cursor . getDouble ( 4 ) ) ; metadata . setMinY ( cursor . getDouble ( 5 ) ) ; metadata . setMaxY ( cursor . getDouble ( 6 ) ) ; if ( ! cursor . isNull ( 7 ) ) { metadata . setMinZ ( cursor . getDouble ( 7 ) ) ; } if ( ! cursor . isNull ( 8 ) ) { metadata . setMaxZ ( cursor . getDouble ( 8 ) ) ; } if ( ! cursor . isNull ( 9 ) ) { metadata . setMinM ( cursor . getDouble ( 9 ) ) ; } if ( ! cursor . isNull ( 10 ) ) { metadata . setMaxM ( cursor . getDouble ( 10 ) ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TRow queryForIdRow ( long id ) { TRow row = null ; TResult readCursor = queryForId ( id ) ; if ( readCursor . moveToNext ( ) ) { row = readCursor . getRow ( ) ; if ( ! row . isValid ( ) && readCursor . moveToNext ( ) ) { row = readCursor . getRow ( ) ; } } readCursor . close ( ) ; return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update all rows matching the where clause with the provided values [CODESPLIT] public int update ( ContentValues values , String whereClause , String [ ] whereArgs ) { return db . update ( getTableName ( ) , values , whereClause , whereArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public long insert ( TRow row ) { long id = db . insertOrThrow ( getTableName ( ) , null , row . toContentValues ( ) ) ; if ( row . hasIdColumn ( ) ) { row . setId ( id ) ; } return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Bitmap drawTile ( int tileWidth , int tileHeight , long tileFeatureCount , FeatureIndexResults featureIndexResults ) { String featureText = String . valueOf ( tileFeatureCount ) ; Bitmap bitmap = drawTile ( tileWidth , tileHeight , featureText ) ; return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Bitmap drawUnindexedTile ( int tileWidth , int tileHeight , long totalFeatureCount , FeatureCursor allFeatureResults ) { Bitmap bitmap = null ; if ( drawUnindexedTiles ) { // Draw a tile indicating we have no idea if there are features inside. // The table is not indexed and more features exist than the max feature count set. bitmap = drawTile ( tileWidth , tileHeight , \"?\" ) ; } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a tile with the provided text label in the middle [CODESPLIT] private Bitmap drawTile ( int tileWidth , int tileHeight , String text ) { // Create bitmap and canvas Bitmap bitmap = Bitmap . createBitmap ( tileWidth , tileHeight , Bitmap . Config . ARGB_8888 ) ; Canvas canvas = new Canvas ( bitmap ) ; // Draw the tile fill paint if ( tileFillPaint != null ) { canvas . drawRect ( 0 , 0 , tileWidth , tileHeight , tileFillPaint ) ; } // Draw the tile border if ( tileBorderPaint != null ) { canvas . drawRect ( 0 , 0 , tileWidth , tileHeight , tileBorderPaint ) ; } // Determine the text bounds Rect textBounds = new Rect ( ) ; textPaint . getTextBounds ( text , 0 , text . length ( ) , textBounds ) ; // Determine the center of the tile int centerX = ( int ) ( bitmap . getWidth ( ) / 2.0f ) ; int centerY = ( int ) ( bitmap . getHeight ( ) / 2.0f ) ; // Draw the circle if ( circlePaint != null || circleFillPaint != null ) { int diameter = Math . max ( textBounds . width ( ) , textBounds . height ( ) ) ; float radius = diameter / 2.0f ; radius = radius + ( diameter * circlePaddingPercentage ) ; // Draw the filled circle if ( circleFillPaint != null ) { canvas . drawCircle ( centerX , centerY , radius , circleFillPaint ) ; } // Draw the circle if ( circlePaint != null ) { canvas . drawCircle ( centerX , centerY , radius , circlePaint ) ; } } // Draw the text canvas . drawText ( text , centerX - textBounds . exactCenterX ( ) , centerY - textBounds . exactCenterY ( ) , textPaint ) ; return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the simple attributes rows that exist with the provided ids [CODESPLIT] public List < SimpleAttributesRow > getRows ( List < Long > ids ) { List < SimpleAttributesRow > simpleAttributesRows = new ArrayList <> ( ) ; for ( long id : ids ) { UserCustomRow userCustomRow = queryForIdRow ( id ) ; if ( userCustomRow != null ) { simpleAttributesRows . add ( getRow ( userCustomRow ) ) ; } } return simpleAttributesRows ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected BoundingBox getFeatureBoundingBox ( Projection projection , String table , boolean manual ) { BoundingBox boundingBox = null ; FeatureIndexManager indexManager = new FeatureIndexManager ( context , this , table ) ; try { if ( manual || indexManager . isIndexed ( ) ) { boundingBox = indexManager . getBoundingBox ( projection ) ; } } finally { indexManager . close ( ) ; } return boundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void registerCursorWrapper ( String table , GeoPackageCursorWrapper cursorWrapper ) { cursorFactory . registerTable ( table , cursorWrapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FeatureDao getFeatureDao ( GeometryColumns geometryColumns ) { if ( geometryColumns == null ) { throw new GeoPackageException ( \"Non null \" + GeometryColumns . class . getSimpleName ( ) + \" is required to create \" + FeatureDao . class . getSimpleName ( ) ) ; } // Read the existing table and create the dao FeatureTableReader tableReader = new FeatureTableReader ( geometryColumns ) ; final FeatureTable featureTable = tableReader . readTable ( new FeatureWrapperConnection ( database ) ) ; featureTable . setContents ( geometryColumns . getContents ( ) ) ; FeatureConnection userDb = new FeatureConnection ( database ) ; FeatureDao dao = new FeatureDao ( getName ( ) , database , userDb , geometryColumns , featureTable ) ; // Register the table name (with and without quotes) to wrap cursors with the feature cursor registerCursorWrapper ( geometryColumns . getTableName ( ) , new GeoPackageCursorWrapper ( ) { @ Override public Cursor wrapCursor ( Cursor cursor ) { return new FeatureCursor ( featureTable , cursor ) ; } } ) ; // If the GeoPackage is writable and the feature table has a RTree Index // extension, drop the RTree triggers.  User defined functions are currently not supported. if ( writable ) { RTreeIndexExtension rtree = new RTreeIndexExtension ( this ) ; rtree . dropTriggers ( featureTable ) ; } return dao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FeatureDao getFeatureDao ( Contents contents ) { if ( contents == null ) { throw new GeoPackageException ( \"Non null \" + Contents . class . getSimpleName ( ) + \" is required to create \" + FeatureDao . class . getSimpleName ( ) ) ; } GeometryColumns geometryColumns = contents . getGeometryColumns ( ) ; if ( geometryColumns == null ) { throw new GeoPackageException ( \"No \" + GeometryColumns . class . getSimpleName ( ) + \" exists for \" + Contents . class . getSimpleName ( ) + \" \" + contents . getId ( ) ) ; } return getFeatureDao ( geometryColumns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FeatureDao getFeatureDao ( String tableName ) { GeometryColumnsDao dao = getGeometryColumnsDao ( ) ; List < GeometryColumns > geometryColumnsList ; try { geometryColumnsList = dao . queryForEq ( GeometryColumns . COLUMN_TABLE_NAME , tableName ) ; } catch ( SQLException e ) { throw new GeoPackageException ( \"Failed to retrieve \" + FeatureDao . class . getSimpleName ( ) + \" for table name: \" + tableName + \". Exception retrieving \" + GeometryColumns . class . getSimpleName ( ) + \".\" , e ) ; } if ( geometryColumnsList . isEmpty ( ) ) { throw new GeoPackageException ( \"No Feature Table exists for table name: \" + tableName ) ; } else if ( geometryColumnsList . size ( ) > 1 ) { // This shouldn't happen with the table name unique constraint on // geometry columns throw new GeoPackageException ( \"Unexpected state. More than one \" + GeometryColumns . class . getSimpleName ( ) + \" matched for table name: \" + tableName + \", count: \" + geometryColumnsList . size ( ) ) ; } return getFeatureDao ( geometryColumnsList . get ( 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TileDao getTileDao ( Contents contents ) { if ( contents == null ) { throw new GeoPackageException ( \"Non null \" + Contents . class . getSimpleName ( ) + \" is required to create \" + TileDao . class . getSimpleName ( ) ) ; } TileMatrixSet tileMatrixSet = contents . getTileMatrixSet ( ) ; if ( tileMatrixSet == null ) { throw new GeoPackageException ( \"No \" + TileMatrixSet . class . getSimpleName ( ) + \" exists for \" + Contents . class . getSimpleName ( ) + \" \" + contents . getId ( ) ) ; } return getTileDao ( tileMatrixSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public AttributesDao getAttributesDao ( Contents contents ) { if ( contents == null ) { throw new GeoPackageException ( \"Non null \" + Contents . class . getSimpleName ( ) + \" is required to create \" + AttributesDao . class . getSimpleName ( ) ) ; } if ( contents . getDataType ( ) != ContentsDataType . ATTRIBUTES ) { throw new GeoPackageException ( Contents . class . getSimpleName ( ) + \" is required to be of type \" + ContentsDataType . ATTRIBUTES + \". Actual: \" + contents . getDataTypeString ( ) ) ; } // Read the existing table and create the dao AttributesTableReader tableReader = new AttributesTableReader ( contents . getTableName ( ) ) ; final AttributesTable attributesTable = tableReader . readTable ( new AttributesWrapperConnection ( database ) ) ; attributesTable . setContents ( contents ) ; AttributesConnection userDb = new AttributesConnection ( database ) ; AttributesDao dao = new AttributesDao ( getName ( ) , database , userDb , attributesTable ) ; // Register the table name (with and without quotes) to wrap cursors with the attributes cursor registerCursorWrapper ( attributesTable . getTableName ( ) , new GeoPackageCursorWrapper ( ) { @ Override public Cursor wrapCursor ( Cursor cursor ) { return new AttributesCursor ( attributesTable , cursor ) ; } } ) ; return dao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public AttributesDao getAttributesDao ( String tableName ) { ContentsDao dao = getContentsDao ( ) ; Contents contents = null ; try { contents = dao . queryForId ( tableName ) ; } catch ( SQLException e ) { throw new GeoPackageException ( \"Failed to retrieve \" + Contents . class . getSimpleName ( ) + \" for table name: \" + tableName , e ) ; } if ( contents == null ) { throw new GeoPackageException ( \"No Contents Table exists for table name: \" + tableName ) ; } return getAttributesDao ( contents ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Cursor rawQuery ( String sql , String [ ] args ) { return database . rawQuery ( sql , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Cursor foreignKeyCheck ( ) { Cursor cursor = rawQuery ( \"PRAGMA foreign_key_check\" , null ) ; if ( ! cursor . moveToNext ( ) ) { cursor . close ( ) ; cursor = null ; } return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the cursor returned from the integrity check to see if things are ok [CODESPLIT] private Cursor integrityCheck ( Cursor cursor ) { if ( cursor . moveToNext ( ) ) { String value = cursor . getString ( 0 ) ; if ( value . equals ( \"ok\" ) ) { cursor . close ( ) ; cursor = null ; } } return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String getPrimaryKeyColumnName ( String tableName ) { UserCustomTable table = UserCustomTableReader . readTable ( connection , tableName ) ; UserCustomColumn pkColumn = table . getPkColumn ( ) ; if ( pkColumn == null ) { throw new GeoPackageException ( \"Found no primary key for table \" + tableName ) ; } return pkColumn . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a User Mapping DAO from a table name [CODESPLIT] public UserMappingDao getMappingDao ( String tableName ) { UserMappingDao userMappingDao = new UserMappingDao ( getUserDao ( tableName ) ) ; userMappingDao . registerCursorWrapper ( getGeoPackage ( ) ) ; return userMappingDao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a related simple attributes table DAO [CODESPLIT] public SimpleAttributesDao getSimpleAttributesDao ( String tableName ) { SimpleAttributesDao simpleAttributesDao = new SimpleAttributesDao ( getUserDao ( tableName ) ) ; simpleAttributesDao . registerCursorWrapper ( getGeoPackage ( ) ) ; setContents ( simpleAttributesDao . getTable ( ) ) ; return simpleAttributesDao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the related id mappings for the base id [CODESPLIT] public List < Long > getMappingsForBase ( ExtendedRelation extendedRelation , long baseId ) { return getMappingsForBase ( extendedRelation . getMappingTableName ( ) , baseId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the base id mappings for the related id [CODESPLIT] public List < Long > getMappingsForRelated ( ExtendedRelation extendedRelation , long relatedId ) { return getMappingsForRelated ( extendedRelation . getMappingTableName ( ) , relatedId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the base id and related id mapping exists [CODESPLIT] public boolean hasMapping ( String tableName , long baseId , long relatedId ) { boolean has = false ; UserMappingDao userMappingDao = getMappingDao ( tableName ) ; UserCustomCursor cursor = userMappingDao . queryByIds ( baseId , relatedId ) ; try { has = cursor . getCount ( ) > 0 ; } finally { cursor . close ( ) ; } return has ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TileRow getRow ( int [ ] columnTypes , Object [ ] values ) { return new TileRow ( getTable ( ) , columnTypes , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected UserInvalidCursor < TileColumn , TileTable , TileRow , ? extends UserCursor < TileColumn , TileTable , TileRow > , ? extends UserDao < TileColumn , TileTable , TileRow , ? extends UserCursor < TileColumn , TileTable , TileRow > > > createInvalidCursor ( UserDao dao , UserCursor cursor , List < Integer > invalidPositions , List < TileColumn > blobColumns ) { return new TileInvalidCursor ( ( TileDao ) dao , ( TileCursor ) cursor , invalidPositions , blobColumns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the count of the cursor and close it [CODESPLIT] protected int count ( UserCustomCursor cursor ) { int count = 0 ; try { count = cursor . getCount ( ) ; } finally { cursor . close ( ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the cursor wrapper into the GeoPackage [CODESPLIT] public void registerCursorWrapper ( GeoPackage geoPackage ) { geoPackage . registerCursorWrapper ( getTableName ( ) , new GeoPackageCursorWrapper ( ) { @ Override public Cursor wrapCursor ( Cursor cursor ) { return new UserCustomCursor ( getTable ( ) , cursor ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the database table and create a DAO [CODESPLIT] public static UserCustomDao readTable ( GeoPackage geoPackage , String tableName ) { UserCustomConnection userDb = new UserCustomConnection ( geoPackage . getConnection ( ) ) ; final UserCustomTable userCustomTable = UserCustomTableReader . readTable ( geoPackage . getConnection ( ) , tableName ) ; UserCustomDao dao = new UserCustomDao ( geoPackage . getName ( ) , geoPackage . getConnection ( ) , userDb , userCustomTable ) ; dao . registerCursorWrapper ( geoPackage ) ; return dao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile from the request bounding box in the request projection [CODESPLIT] public GeoPackageTile getTile ( BoundingBox requestBoundingBox ) { GeoPackageTile tile = null ; // Transform to the projection of the tiles ProjectionTransform transformRequestToTiles = requestProjection . getTransformation ( tilesProjection ) ; BoundingBox tilesBoundingBox = requestBoundingBox . transform ( transformRequestToTiles ) ; List < TileMatrix > tileMatrices = getTileMatrices ( tilesBoundingBox ) ; for ( int i = 0 ; tile == null && i < tileMatrices . size ( ) ; i ++ ) { TileMatrix tileMatrix = tileMatrices . get ( i ) ; TileCursor tileResults = retrieveTileResults ( tilesBoundingBox , tileMatrix ) ; if ( tileResults != null ) { try { if ( tileResults . getCount ( ) > 0 ) { BoundingBox requestProjectedBoundingBox = requestBoundingBox . transform ( transformRequestToTiles ) ; // Determine the requested tile dimensions, or use the dimensions of a single tile matrix tile int requestedTileWidth = width != null ? width : ( int ) tileMatrix . getTileWidth ( ) ; int requestedTileHeight = height != null ? height : ( int ) tileMatrix . getTileHeight ( ) ; // Determine the size of the tile to initially draw int tileWidth = requestedTileWidth ; int tileHeight = requestedTileHeight ; if ( ! sameProjection ) { tileWidth = ( int ) Math . round ( ( requestProjectedBoundingBox . getMaxLongitude ( ) - requestProjectedBoundingBox . getMinLongitude ( ) ) / tileMatrix . getPixelXSize ( ) ) ; tileHeight = ( int ) Math . round ( ( requestProjectedBoundingBox . getMaxLatitude ( ) - requestProjectedBoundingBox . getMinLatitude ( ) ) / tileMatrix . getPixelYSize ( ) ) ; } // Draw the resulting bitmap with the matching tiles Bitmap tileBitmap = drawTile ( tileMatrix , tileResults , requestProjectedBoundingBox , tileWidth , tileHeight ) ; // Create the tile if ( tileBitmap != null ) { // Project the tile if needed if ( ! sameProjection ) { Bitmap reprojectTile = reprojectTile ( tileBitmap , requestedTileWidth , requestedTileHeight , requestBoundingBox , transformRequestToTiles , tilesBoundingBox ) ; tileBitmap . recycle ( ) ; tileBitmap = reprojectTile ; } try { byte [ ] tileData = BitmapConverter . toBytes ( tileBitmap , COMPRESS_FORMAT ) ; tileBitmap . recycle ( ) ; tile = new GeoPackageTile ( requestedTileWidth , requestedTileHeight , tileData ) ; } catch ( IOException e ) { Log . e ( TileCreator . class . getSimpleName ( ) , \"Failed to create tile. min lat: \" + requestBoundingBox . getMinLatitude ( ) + \", max lat: \" + requestBoundingBox . getMaxLatitude ( ) + \", min lon: \" + requestBoundingBox . getMinLongitude ( ) + \", max lon: \" + requestBoundingBox . getMaxLongitude ( ) , e ) ; } } } } finally { tileResults . close ( ) ; } } } return tile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw the tile from the tile results [CODESPLIT] private Bitmap drawTile ( TileMatrix tileMatrix , TileCursor tileResults , BoundingBox requestProjectedBoundingBox , int tileWidth , int tileHeight ) { // Draw the resulting bitmap with the matching tiles Bitmap tileBitmap = null ; Canvas canvas = null ; Paint paint = null ; while ( tileResults . moveToNext ( ) ) { // Get the next tile TileRow tileRow = tileResults . getRow ( ) ; Bitmap tileDataBitmap = tileRow . getTileDataBitmap ( ) ; // Get the bounding box of the tile BoundingBox tileBoundingBox = TileBoundingBoxUtils . getBoundingBox ( tileSetBoundingBox , tileMatrix , tileRow . getTileColumn ( ) , tileRow . getTileRow ( ) ) ; // Get the bounding box where the requested image and // tile overlap BoundingBox overlap = requestProjectedBoundingBox . overlap ( tileBoundingBox ) ; // If the tile overlaps with the requested box if ( overlap != null ) { // Get the rectangle of the tile image to draw Rect src = TileBoundingBoxAndroidUtils . getRectangle ( tileMatrix . getTileWidth ( ) , tileMatrix . getTileHeight ( ) , tileBoundingBox , overlap ) ; // Get the rectangle of where to draw the tile in // the resulting image RectF dest = TileBoundingBoxAndroidUtils . getRoundedFloatRectangle ( tileWidth , tileHeight , requestProjectedBoundingBox , overlap ) ; // Create the bitmap first time through if ( tileBitmap == null ) { tileBitmap = Bitmap . createBitmap ( tileWidth , tileHeight , Bitmap . Config . ARGB_8888 ) ; canvas = new Canvas ( tileBitmap ) ; paint = new Paint ( Paint . ANTI_ALIAS_FLAG ) ; } // Draw the tile to the bitmap canvas . drawBitmap ( tileDataBitmap , src , dest , paint ) ; } } return tileBitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reproject the tile to the requested projection [CODESPLIT] private Bitmap reprojectTile ( Bitmap tile , int requestedTileWidth , int requestedTileHeight , BoundingBox requestBoundingBox , ProjectionTransform transformRequestToTiles , BoundingBox tilesBoundingBox ) { final double requestedWidthUnitsPerPixel = ( requestBoundingBox . getMaxLongitude ( ) - requestBoundingBox . getMinLongitude ( ) ) / requestedTileWidth ; final double requestedHeightUnitsPerPixel = ( requestBoundingBox . getMaxLatitude ( ) - requestBoundingBox . getMinLatitude ( ) ) / requestedTileHeight ; final double tilesDistanceWidth = tilesBoundingBox . getMaxLongitude ( ) - tilesBoundingBox . getMinLongitude ( ) ; final double tilesDistanceHeight = tilesBoundingBox . getMaxLatitude ( ) - tilesBoundingBox . getMinLatitude ( ) ; final int width = tile . getWidth ( ) ; final int height = tile . getHeight ( ) ; // Tile pixels of the tile matrix tiles int [ ] pixels = new int [ width * height ] ; tile . getPixels ( pixels , 0 , width , 0 , 0 , width , height ) ; // Projected tile pixels to draw the reprojected tile int [ ] projectedPixels = new int [ requestedTileWidth * requestedTileHeight ] ; // Retrieve each pixel in the new tile from the unprojected tile for ( int y = 0 ; y < requestedTileHeight ; y ++ ) { for ( int x = 0 ; x < requestedTileWidth ; x ++ ) { double longitude = requestBoundingBox . getMinLongitude ( ) + ( x * requestedWidthUnitsPerPixel ) ; double latitude = requestBoundingBox . getMaxLatitude ( ) - ( y * requestedHeightUnitsPerPixel ) ; ProjCoordinate fromCoord = new ProjCoordinate ( longitude , latitude ) ; ProjCoordinate toCoord = transformRequestToTiles . transform ( fromCoord ) ; double projectedLongitude = toCoord . x ; double projectedLatitude = toCoord . y ; int xPixel = ( int ) Math . round ( ( ( projectedLongitude - tilesBoundingBox . getMinLongitude ( ) ) / tilesDistanceWidth ) * width ) ; int yPixel = ( int ) Math . round ( ( ( tilesBoundingBox . getMaxLatitude ( ) - projectedLatitude ) / tilesDistanceHeight ) * height ) ; xPixel = Math . max ( 0 , xPixel ) ; xPixel = Math . min ( width - 1 , xPixel ) ; yPixel = Math . max ( 0 , yPixel ) ; yPixel = Math . min ( height - 1 , yPixel ) ; int color = pixels [ ( yPixel * width ) + xPixel ] ; projectedPixels [ ( y * requestedTileWidth ) + x ] = color ; } } // Draw the new tile bitmap Bitmap projectedTileBitmap = Bitmap . createBitmap ( requestedTileWidth , requestedTileHeight , tile . getConfig ( ) ) ; projectedTileBitmap . setPixels ( projectedPixels , 0 , requestedTileWidth , 0 , 0 , requestedTileWidth , requestedTileHeight ) ; return projectedTileBitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile matrices that may contain the tiles for the bounding box matches against the bounding box and zoom level options [CODESPLIT] private List < TileMatrix > getTileMatrices ( BoundingBox projectedRequestBoundingBox ) { List < TileMatrix > tileMatrices = new ArrayList <> ( ) ; // Check if the request overlaps the tile matrix set if ( ! tileDao . getTileMatrices ( ) . isEmpty ( ) && projectedRequestBoundingBox . intersects ( tileSetBoundingBox ) ) { // Get the tile distance double distanceWidth = projectedRequestBoundingBox . getMaxLongitude ( ) - projectedRequestBoundingBox . getMinLongitude ( ) ; double distanceHeight = projectedRequestBoundingBox . getMaxLatitude ( ) - projectedRequestBoundingBox . getMinLatitude ( ) ; // Get the zoom level to request based upon the tile size Long requestZoomLevel = null ; if ( scaling != null ) { // When options are provided, get the approximate zoom level regardless of whether a tile level exists requestZoomLevel = tileDao . getApproximateZoomLevel ( distanceWidth , distanceHeight ) ; } else { // Get the closest existing zoom level requestZoomLevel = tileDao . getZoomLevel ( distanceWidth , distanceHeight ) ; } // If there is a matching zoom level if ( requestZoomLevel != null ) { List < Long > zoomLevels = null ; // If options are configured, build the possible zoom levels in order to request if ( scaling != null && scaling . getScalingType ( ) != null ) { // Find zoom in levels List < Long > zoomInLevels = new ArrayList <> ( ) ; if ( scaling . isZoomIn ( ) ) { long zoomIn = scaling . getZoomIn ( ) != null ? requestZoomLevel + scaling . getZoomIn ( ) : tileDao . getMaxZoom ( ) ; for ( long zoomLevel = requestZoomLevel + 1 ; zoomLevel <= zoomIn ; zoomLevel ++ ) { zoomInLevels . add ( zoomLevel ) ; } } // Find zoom out levels List < Long > zoomOutLevels = new ArrayList <> ( ) ; if ( scaling . isZoomOut ( ) ) { long zoomOut = scaling . getZoomOut ( ) != null ? requestZoomLevel - scaling . getZoomOut ( ) : tileDao . getMinZoom ( ) ; for ( long zoomLevel = requestZoomLevel - 1 ; zoomLevel >= zoomOut ; zoomLevel -- ) { zoomOutLevels . add ( zoomLevel ) ; } } if ( zoomInLevels . isEmpty ( ) ) { // Only zooming out zoomLevels = zoomOutLevels ; } else if ( zoomOutLevels . isEmpty ( ) ) { // Only zooming in zoomLevels = zoomInLevels ; } else { // Determine how to order the zoom in and zoom out levels TileScalingType type = scaling . getScalingType ( ) ; switch ( type ) { case IN : case IN_OUT : // Order zoom in levels before zoom out levels zoomLevels = zoomInLevels ; zoomLevels . addAll ( zoomOutLevels ) ; break ; case OUT : case OUT_IN : // Order zoom out levels before zoom in levels zoomLevels = zoomOutLevels ; zoomLevels . addAll ( zoomInLevels ) ; break ; case CLOSEST_IN_OUT : case CLOSEST_OUT_IN : // Alternate the zoom in and out levels List < Long > firstLevels ; List < Long > secondLevels ; if ( type == TileScalingType . CLOSEST_IN_OUT ) { // Alternate starting with zoom in firstLevels = zoomInLevels ; secondLevels = zoomOutLevels ; } else { // Alternate starting with zoom out firstLevels = zoomOutLevels ; secondLevels = zoomInLevels ; } zoomLevels = new ArrayList <> ( ) ; int maxLevels = Math . max ( firstLevels . size ( ) , secondLevels . size ( ) ) ; for ( int i = 0 ; i < maxLevels ; i ++ ) { if ( i < firstLevels . size ( ) ) { zoomLevels . add ( firstLevels . get ( i ) ) ; } if ( i < secondLevels . size ( ) ) { zoomLevels . add ( secondLevels . get ( i ) ) ; } } break ; default : throw new GeoPackageException ( \"Unsupported \" + TileScalingType . class . getSimpleName ( ) + \": \" + type ) ; } } } else { zoomLevels = new ArrayList <> ( ) ; } // Always check the request zoom level first zoomLevels . add ( 0 , requestZoomLevel ) ; // Build a list of tile matrices that exist for the zoom levels for ( long zoomLevel : zoomLevels ) { TileMatrix tileMatrix = tileDao . getTileMatrix ( zoomLevel ) ; if ( tileMatrix != null ) { tileMatrices . add ( tileMatrix ) ; } } } } return tileMatrices ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile row results of tiles needed to draw the requested bounding box tile [CODESPLIT] private TileCursor retrieveTileResults ( BoundingBox projectedRequestBoundingBox , TileMatrix tileMatrix ) { TileCursor tileResults = null ; if ( tileMatrix != null ) { // Get the tile grid TileGrid tileGrid = TileBoundingBoxUtils . getTileGrid ( tileSetBoundingBox , tileMatrix . getMatrixWidth ( ) , tileMatrix . getMatrixHeight ( ) , projectedRequestBoundingBox ) ; // Query for matching tiles in the tile grid tileResults = tileDao . queryByTileGrid ( tileGrid , tileMatrix . getZoomLevel ( ) ) ; } return tileResults ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call after making changes to the point icon point radius or paint stroke widths . Determines the pixel overlap between tiles [CODESPLIT] public void calculateDrawOverlap ( ) { if ( pointIcon != null ) { heightOverlap = this . density * pointIcon . getHeight ( ) ; widthOverlap = this . density * pointIcon . getWidth ( ) ; } else { heightOverlap = this . density * pointRadius ; widthOverlap = this . density * pointRadius ; } float linePaintHalfStroke = this . density * lineStrokeWidth / 2.0f ; heightOverlap = Math . max ( heightOverlap , linePaintHalfStroke ) ; widthOverlap = Math . max ( widthOverlap , linePaintHalfStroke ) ; float polygonPaintHalfStroke = this . density * polygonStrokeWidth / 2.0f ; heightOverlap = Math . max ( heightOverlap , polygonPaintHalfStroke ) ; widthOverlap = Math . max ( widthOverlap , polygonPaintHalfStroke ) ; if ( featureTableStyles != null && featureTableStyles . has ( ) ) { // Style Rows Set < Long > styleRowIds = new HashSet <> ( ) ; List < Long > tableStyleIds = featureTableStyles . getAllTableStyleIds ( ) ; if ( tableStyleIds != null ) { styleRowIds . addAll ( tableStyleIds ) ; } List < Long > styleIds = featureTableStyles . getAllStyleIds ( ) ; if ( styleIds != null ) { styleRowIds . addAll ( styleIds ) ; } StyleDao styleDao = featureTableStyles . getStyleDao ( ) ; for ( long styleRowId : styleRowIds ) { StyleRow styleRow = styleDao . getRow ( styleDao . queryForIdRow ( styleRowId ) ) ; float styleHalfWidth = this . density * ( float ) ( styleRow . getWidthOrDefault ( ) / 2.0f ) ; widthOverlap = Math . max ( widthOverlap , styleHalfWidth ) ; heightOverlap = Math . max ( heightOverlap , styleHalfWidth ) ; } // Icon Rows Set < Long > iconRowIds = new HashSet <> ( ) ; List < Long > tableIconIds = featureTableStyles . getAllTableIconIds ( ) ; if ( tableIconIds != null ) { iconRowIds . addAll ( tableIconIds ) ; } List < Long > iconIds = featureTableStyles . getAllIconIds ( ) ; if ( iconIds != null ) { iconRowIds . addAll ( iconIds ) ; } IconDao iconDao = featureTableStyles . getIconDao ( ) ; for ( long iconRowId : iconRowIds ) { IconRow iconRow = iconDao . getRow ( iconDao . queryForIdRow ( iconRowId ) ) ; double [ ] iconDimensions = iconRow . getDerivedDimensions ( ) ; float iconWidth = this . density * ( float ) Math . ceil ( iconDimensions [ 0 ] ) ; float iconHeight = this . density * ( float ) Math . ceil ( iconDimensions [ 1 ] ) ; widthOverlap = Math . max ( widthOverlap , iconWidth ) ; heightOverlap = Math . max ( heightOverlap , iconHeight ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the density [CODESPLIT] public void setDensity ( float density ) { this . density = density ; linePaint . setStrokeWidth ( this . density * lineStrokeWidth ) ; polygonPaint . setStrokeWidth ( this . density * polygonStrokeWidth ) ; featurePaintCache . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the line paint [CODESPLIT] public void setLinePaint ( Paint linePaint ) { if ( linePaint == null ) { throw new AssertionError ( \"Line Paint can not be null\" ) ; } this . linePaint = linePaint ; setLineStrokeWidth ( linePaint . getStrokeWidth ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the polygon paint [CODESPLIT] public void setPolygonPaint ( Paint polygonPaint ) { if ( polygonPaint == null ) { throw new AssertionError ( \"Polygon Paint can not be null\" ) ; } this . polygonPaint = polygonPaint ; setPolygonStrokeWidth ( polygonPaint . getStrokeWidth ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw the tile and get the bytes from the x y and zoom level [CODESPLIT] public byte [ ] drawTileBytes ( int x , int y , int zoom ) { Bitmap bitmap = drawTile ( x , y , zoom ) ; byte [ ] tileData = null ; // Convert the bitmap to bytes if ( bitmap != null ) { try { tileData = BitmapConverter . toBytes ( bitmap , compressFormat ) ; } catch ( IOException e ) { Log . e ( FeatureTiles . class . getSimpleName ( ) , \"Failed to create tile. x: \" + x + \", y: \" + y + \", zoom: \" + zoom , e ) ; } finally { bitmap . recycle ( ) ; } } return tileData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a tile bitmap from the x y and zoom level [CODESPLIT] public Bitmap drawTile ( int x , int y , int zoom ) { Bitmap bitmap ; if ( isIndexQuery ( ) ) { bitmap = drawTileQueryIndex ( x , y , zoom ) ; } else { bitmap = drawTileQueryAll ( x , y , zoom ) ; } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a tile bitmap from the x y and zoom level by querying features in the tile location [CODESPLIT] public Bitmap drawTileQueryIndex ( int x , int y , int zoom ) { // Get the web mercator bounding box BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; Bitmap bitmap = null ; // Query for geometries matching the bounds in the index FeatureIndexResults results = queryIndexedFeatures ( webMercatorBoundingBox ) ; try { long tileCount = results . count ( ) ; // Draw if at least one geometry exists if ( tileCount > 0 ) { if ( maxFeaturesPerTile == null || tileCount <= maxFeaturesPerTile . longValue ( ) ) { // Draw the tile bitmap bitmap = drawTile ( zoom , webMercatorBoundingBox , results ) ; } else if ( maxFeaturesTileDraw != null ) { // Draw the max features tile bitmap = maxFeaturesTileDraw . drawTile ( tileWidth , tileHeight , tileCount , results ) ; } } } finally { results . close ( ) ; } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for feature result count in the x y and zoom [CODESPLIT] public long queryIndexedFeaturesCount ( int x , int y , int zoom ) { // Get the web mercator bounding box BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; // Query for the count of geometries matching the bounds in the index long count = queryIndexedFeaturesCount ( webMercatorBoundingBox ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for feature result count in the bounding box [CODESPLIT] public long queryIndexedFeaturesCount ( BoundingBox webMercatorBoundingBox ) { // Query for geometries matching the bounds in the index FeatureIndexResults results = queryIndexedFeatures ( webMercatorBoundingBox ) ; long count = 0 ; try { count = results . count ( ) ; } finally { results . close ( ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for feature results in the x y and zoom level by querying features in the tile location [CODESPLIT] public FeatureIndexResults queryIndexedFeatures ( int x , int y , int zoom ) { // Get the web mercator bounding box BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; // Query for the geometries matching the bounds in the index return queryIndexedFeatures ( webMercatorBoundingBox ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for feature results in the bounding box [CODESPLIT] public FeatureIndexResults queryIndexedFeatures ( BoundingBox webMercatorBoundingBox ) { // Create an expanded bounding box to handle features outside the tile // that overlap BoundingBox expandedQueryBoundingBox = expandBoundingBox ( webMercatorBoundingBox ) ; // Query for geometries matching the bounds in the index FeatureIndexResults results = indexManager . query ( expandedQueryBoundingBox , WEB_MERCATOR_PROJECTION ) ; return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an expanded bounding box to handle features outside the tile that overlap [CODESPLIT] public BoundingBox expandBoundingBox ( BoundingBox boundingBox , Projection projection ) { BoundingBox expandedBoundingBox = boundingBox ; ProjectionTransform toWebMercator = projection . getTransformation ( ProjectionConstants . EPSG_WEB_MERCATOR ) ; if ( ! toWebMercator . isSameProjection ( ) ) { expandedBoundingBox = expandedBoundingBox . transform ( toWebMercator ) ; } expandedBoundingBox = expandBoundingBox ( expandedBoundingBox ) ; if ( ! toWebMercator . isSameProjection ( ) ) { ProjectionTransform fromWebMercator = toWebMercator . getInverseTransformation ( ) ; expandedBoundingBox = expandedBoundingBox . transform ( fromWebMercator ) ; } return expandedBoundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an expanded bounding box to handle features outside the tile that overlap [CODESPLIT] public BoundingBox expandBoundingBox ( BoundingBox webMercatorBoundingBox , BoundingBox tileWebMercatorBoundingBox ) { // Create an expanded bounding box to handle features outside the tile // that overlap double minLongitude = TileBoundingBoxUtils . getLongitudeFromPixel ( tileWidth , webMercatorBoundingBox , tileWebMercatorBoundingBox , 0 - widthOverlap ) ; double maxLongitude = TileBoundingBoxUtils . getLongitudeFromPixel ( tileWidth , webMercatorBoundingBox , tileWebMercatorBoundingBox , tileWidth + widthOverlap ) ; double maxLatitude = TileBoundingBoxUtils . getLatitudeFromPixel ( tileHeight , webMercatorBoundingBox , tileWebMercatorBoundingBox , 0 - heightOverlap ) ; double minLatitude = TileBoundingBoxUtils . getLatitudeFromPixel ( tileHeight , webMercatorBoundingBox , tileWebMercatorBoundingBox , tileHeight + heightOverlap ) ; // Choose the most expanded longitudes and latitudes minLongitude = Math . min ( minLongitude , webMercatorBoundingBox . getMinLongitude ( ) ) ; maxLongitude = Math . max ( maxLongitude , webMercatorBoundingBox . getMaxLongitude ( ) ) ; minLatitude = Math . min ( minLatitude , webMercatorBoundingBox . getMinLatitude ( ) ) ; maxLatitude = Math . max ( maxLatitude , webMercatorBoundingBox . getMaxLatitude ( ) ) ; // Bound with the web mercator limits minLongitude = Math . max ( minLongitude , - 1 * ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH ) ; maxLongitude = Math . min ( maxLongitude , ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH ) ; minLatitude = Math . max ( minLatitude , - 1 * ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH ) ; maxLatitude = Math . min ( maxLatitude , ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH ) ; BoundingBox expandedBoundingBox = new BoundingBox ( minLongitude , minLatitude , maxLongitude , maxLatitude ) ; return expandedBoundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw a tile bitmap from the x y and zoom level by querying all features . This could be very slow if there are a lot of features [CODESPLIT] public Bitmap drawTileQueryAll ( int x , int y , int zoom ) { BoundingBox boundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; Bitmap bitmap = null ; // Query for all features FeatureCursor cursor = featureDao . queryForAll ( ) ; try { int totalCount = cursor . getCount ( ) ; // Draw if at least one geometry exists if ( totalCount > 0 ) { if ( maxFeaturesPerTile == null || totalCount <= maxFeaturesPerTile ) { // Draw the tile bitmap bitmap = drawTile ( zoom , boundingBox , cursor ) ; } else if ( maxFeaturesTileDraw != null ) { // Draw the unindexed max features tile bitmap = maxFeaturesTileDraw . drawUnindexedTile ( tileWidth , tileHeight , totalCount , cursor ) ; } } } finally { cursor . close ( ) ; } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When the simplify tolerance is set simplify the points to a similar curve with fewer points . [CODESPLIT] protected List < Point > simplifyPoints ( double simplifyTolerance , List < Point > points ) { List < Point > simplifiedPoints = null ; if ( simplifyGeometries ) { // Reproject to web mercator if not in meters if ( projection != null && ! projection . isUnit ( Units . METRES ) ) { ProjectionTransform toWebMercator = projection . getTransformation ( WEB_MERCATOR_PROJECTION ) ; points = toWebMercator . transform ( points ) ; } // Simplify the points simplifiedPoints = GeometryUtils . simplifyPoints ( points , simplifyTolerance ) ; // Reproject back to the original projection if ( projection != null && ! projection . isUnit ( Units . METRES ) ) { ProjectionTransform fromWebMercator = WEB_MERCATOR_PROJECTION . getTransformation ( projection ) ; simplifiedPoints = fromWebMercator . transform ( simplifiedPoints ) ; } } else { simplifiedPoints = points ; } return simplifiedPoints ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature style for the feature row and geometry type [CODESPLIT] protected FeatureStyle getFeatureStyle ( FeatureRow featureRow ) { FeatureStyle featureStyle = null ; if ( featureTableStyles != null ) { featureStyle = featureTableStyles . getFeatureStyle ( featureRow ) ; } return featureStyle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature style for the feature row and geometry type [CODESPLIT] protected FeatureStyle getFeatureStyle ( FeatureRow featureRow , GeometryType geometryType ) { FeatureStyle featureStyle = null ; if ( featureTableStyles != null ) { featureStyle = featureTableStyles . getFeatureStyle ( featureRow , geometryType ) ; } return featureStyle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the point paint for the feature style or return the default paint [CODESPLIT] protected Paint getPointPaint ( FeatureStyle featureStyle ) { Paint paint = getFeatureStylePaint ( featureStyle , FeatureDrawType . CIRCLE ) ; if ( paint == null ) { paint = pointPaint ; } return paint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the line paint for the feature style or return the default paint [CODESPLIT] protected Paint getLinePaint ( FeatureStyle featureStyle ) { Paint paint = getFeatureStylePaint ( featureStyle , FeatureDrawType . STROKE ) ; if ( paint == null ) { paint = linePaint ; } return paint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the polygon paint for the feature style or return the default paint [CODESPLIT] protected Paint getPolygonPaint ( FeatureStyle featureStyle ) { Paint paint = getFeatureStylePaint ( featureStyle , FeatureDrawType . STROKE ) ; if ( paint == null ) { paint = polygonPaint ; } return paint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the polygon fill paint for the feature style or return the default paint [CODESPLIT] protected Paint getPolygonFillPaint ( FeatureStyle featureStyle ) { Paint paint = null ; boolean hasStyleColor = false ; if ( featureStyle != null ) { StyleRow style = featureStyle . getStyle ( ) ; if ( style != null ) { if ( style . hasFillColor ( ) ) { paint = getStylePaint ( style , FeatureDrawType . FILL ) ; } else { hasStyleColor = style . hasColor ( ) ; } } } if ( paint == null && ! hasStyleColor && fillPolygon ) { paint = polygonFillPaint ; } return paint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature style paint from cache or create and cache it [CODESPLIT] private Paint getFeatureStylePaint ( FeatureStyle featureStyle , FeatureDrawType drawType ) { Paint paint = null ; if ( featureStyle != null ) { StyleRow style = featureStyle . getStyle ( ) ; if ( style != null && style . hasColor ( ) ) { paint = getStylePaint ( style , drawType ) ; } } return paint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style paint from cache or create and cache it [CODESPLIT] private Paint getStylePaint ( StyleRow style , FeatureDrawType drawType ) { Paint paint = featurePaintCache . getPaint ( style , drawType ) ; if ( paint == null ) { Color color = null ; Style paintStyle = null ; Float strokeWidth = null ; switch ( drawType ) { case CIRCLE : color = style . getColorOrDefault ( ) ; paintStyle = Style . FILL ; break ; case STROKE : color = style . getColorOrDefault ( ) ; paintStyle = Style . STROKE ; strokeWidth = this . density * ( float ) style . getWidthOrDefault ( ) ; break ; case FILL : color = style . getFillColor ( ) ; paintStyle = Style . FILL ; strokeWidth = this . density * ( float ) style . getWidthOrDefault ( ) ; break ; default : throw new GeoPackageException ( \"Unsupported Draw Type: \" + drawType ) ; } Paint stylePaint = new Paint ( ) ; stylePaint . setAntiAlias ( true ) ; stylePaint . setStyle ( paintStyle ) ; stylePaint . setColor ( color . getColorWithAlpha ( ) ) ; if ( strokeWidth != null ) { stylePaint . setStrokeWidth ( strokeWidth ) ; } synchronized ( featurePaintCache ) { paint = featurePaintCache . getPaint ( style , drawType ) ; if ( paint == null ) { featurePaintCache . setPaint ( style , drawType , stylePaint ) ; paint = stylePaint ; } } } return paint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the bitmap was drawn upon ( non null and not transparent ) . Return the same bitmap if drawn else recycle non null bitmaps and return null [CODESPLIT] protected Bitmap checkIfDrawn ( Bitmap bitmap ) { if ( isTransparent ( bitmap ) ) { bitmap . recycle ( ) ; bitmap = null ; } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the paint for the style row and draw type [CODESPLIT] public Paint getPaint ( StyleRow styleRow , FeatureDrawType type ) { return getPaint ( styleRow . getId ( ) , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the paint for the style row id and draw type [CODESPLIT] public Paint getPaint ( long styleId , FeatureDrawType type ) { Paint paint = null ; FeaturePaint featurePaint = getFeaturePaint ( styleId ) ; if ( featurePaint != null ) { paint = featurePaint . getPaint ( type ) ; } return paint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the paint for the style id and draw type [CODESPLIT] public void setPaint ( StyleRow styleRow , FeatureDrawType type , Paint paint ) { setPaint ( styleRow . getId ( ) , type , paint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the paint for the style id and draw type [CODESPLIT] public void setPaint ( long styleId , FeatureDrawType type , Paint paint ) { FeaturePaint featurePaint = getFeaturePaint ( styleId ) ; if ( featurePaint == null ) { featurePaint = new FeaturePaint ( ) ; paintCache . put ( styleId , featurePaint ) ; } featurePaint . setPaint ( type , paint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cache the icon bitmap for the icon row [CODESPLIT] public Bitmap put ( IconRow iconRow , Bitmap bitmap ) { return put ( iconRow . getId ( ) , bitmap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create or retrieve from cache an icon bitmap for the icon row [CODESPLIT] public static Bitmap createIcon ( IconRow icon , float density , IconCache iconCache ) { Bitmap iconImage = null ; if ( icon != null ) { if ( iconCache != null ) { iconImage = iconCache . get ( icon . getId ( ) ) ; } if ( iconImage == null ) { BitmapFactory . Options options = icon . getDataBounds ( ) ; int dataWidth = options . outWidth ; int dataHeight = options . outHeight ; double styleWidth = dataWidth ; double styleHeight = dataHeight ; double widthDensity = DisplayMetrics . DENSITY_DEFAULT ; double heightDensity = DisplayMetrics . DENSITY_DEFAULT ; if ( icon . getWidth ( ) != null ) { styleWidth = icon . getWidth ( ) ; double widthRatio = dataWidth / styleWidth ; widthDensity *= widthRatio ; if ( icon . getHeight ( ) == null ) { heightDensity = widthDensity ; } } if ( icon . getHeight ( ) != null ) { styleHeight = icon . getHeight ( ) ; double heightRatio = dataHeight / styleHeight ; heightDensity *= heightRatio ; if ( icon . getWidth ( ) == null ) { widthDensity = heightDensity ; } } options = new BitmapFactory . Options ( ) ; options . inDensity = ( int ) ( Math . min ( widthDensity , heightDensity ) + 0.5f ) ; options . inTargetDensity = ( int ) ( DisplayMetrics . DENSITY_DEFAULT * density + 0.5f ) ; iconImage = icon . getDataBitmap ( options ) ; if ( widthDensity != heightDensity ) { int width = ( int ) ( styleWidth * density + 0.5f ) ; int height = ( int ) ( styleHeight * density + 0.5f ) ; if ( width != iconImage . getWidth ( ) || height != iconImage . getHeight ( ) ) { Bitmap scaledBitmap = Bitmap . createScaledBitmap ( iconImage , width , height , false ) ; iconImage . recycle ( ) ; iconImage = scaledBitmap ; } } if ( iconCache != null ) { iconCache . put ( icon . getId ( ) , iconImage ) ; } } } return iconImage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected FeatureTable createTable ( String tableName , List < FeatureColumn > columnList ) { return new FeatureTable ( tableName , columnList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected FeatureColumn createColumn ( FeatureCursor cursor , int index , String name , String type , Long max , boolean notNull , int defaultValueIndex , boolean primaryKey ) { boolean geometry = name . equalsIgnoreCase ( geometryColumns . getColumnName ( ) ) ; GeometryType geometryType = null ; GeoPackageDataType dataType = null ; if ( geometry ) { geometryType = GeometryType . fromName ( type ) ; dataType = GeoPackageDataType . BLOB ; } else { dataType = GeoPackageDataType . fromName ( type ) ; } Object defaultValue = cursor . getValue ( defaultValueIndex , dataType ) ; FeatureColumn column = new FeatureColumn ( index , name , dataType , max , notNull , defaultValue , primaryKey , geometryType ) ; return column ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Iterator < FeatureRow > iterator ( ) { return new Iterator < FeatureRow > ( ) { @ Override public boolean hasNext ( ) { return ! geometryMetadata . isLast ( ) ; } @ Override public FeatureRow next ( ) { geometryMetadata . moveToNext ( ) ; FeatureRow featureRow = featureIndexer . getFeatureRow ( geometryMetadata ) ; return featureRow ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Iterable < Long > ids ( ) { return new Iterable < Long > ( ) { /**\n             * {@inheritDoc}\n             */ @ Override public Iterator < Long > iterator ( ) { return new Iterator < Long > ( ) { /**\n                     * {@inheritDoc}\n                     */ @ Override public boolean hasNext ( ) { return ! geometryMetadata . isLast ( ) ; } /**\n                     * {@inheritDoc}\n                     */ @ Override public Long next ( ) { geometryMetadata . moveToNext ( ) ; return featureIndexer . getGeometryMetadata ( geometryMetadata ) . getId ( ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap the content values names in quotes [CODESPLIT] public static ContentValues quoteWrap ( ContentValues values ) { ContentValues quoteValues = null ; if ( values != null ) { Map < String , Object > quoteMap = new HashMap <> ( ) ; for ( Map . Entry < String , Object > value : values . valueSet ( ) ) { quoteMap . put ( CoreSQLUtils . quoteWrap ( value . getKey ( ) ) , value . getValue ( ) ) ; } Parcel parcel = Parcel . obtain ( ) ; parcel . writeMap ( quoteMap ) ; parcel . setDataPosition ( 0 ) ; quoteValues = ContentValues . CREATOR . createFromParcel ( parcel ) ; parcel . recycle ( ) ; } return quoteValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the final bitmap from the layers resets the layers [CODESPLIT] public Bitmap createBitmap ( ) { Bitmap bitmap = null ; Canvas canvas = null ; for ( int layer = 0 ; layer < 4 ; layer ++ ) { Bitmap layerBitmap = layeredBitmap [ layer ] ; if ( layerBitmap != null ) { if ( bitmap == null ) { bitmap = layerBitmap ; canvas = layeredCanvas [ layer ] ; } else { canvas . drawBitmap ( layerBitmap , new Matrix ( ) , null ) ; layerBitmap . recycle ( ) ; } layeredBitmap [ layer ] = null ; layeredCanvas [ layer ] = null ; } } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recycle the layered bitmaps [CODESPLIT] public void recycle ( ) { for ( int layer = 0 ; layer < 4 ; layer ++ ) { Bitmap bitmap = layeredBitmap [ layer ] ; if ( bitmap != null ) { bitmap . recycle ( ) ; layeredBitmap [ layer ] = null ; layeredCanvas [ layer ] = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the bitmap for the layer index [CODESPLIT] private Bitmap getBitmap ( int layer ) { Bitmap bitmap = layeredBitmap [ layer ] ; if ( bitmap == null ) { createBitmapAndCanvas ( layer ) ; bitmap = layeredBitmap [ layer ] ; } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the canvas for the layer index [CODESPLIT] private Canvas getCanvas ( int layer ) { Canvas canvas = layeredCanvas [ layer ] ; if ( canvas == null ) { createBitmapAndCanvas ( layer ) ; canvas = layeredCanvas [ layer ] ; } return canvas ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new empty Bitmap and Canvas [CODESPLIT] private void createBitmapAndCanvas ( int layer ) { layeredBitmap [ layer ] = Bitmap . createBitmap ( tileWidth , tileHeight , Bitmap . Config . ARGB_8888 ) ; layeredCanvas [ layer ] = new Canvas ( layeredBitmap [ layer ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Style Mapping DAO from a table name [CODESPLIT] private StyleMappingDao getMappingDao ( String tablePrefix , String featureTable ) { String tableName = tablePrefix + featureTable ; StyleMappingDao dao = null ; if ( geoPackage . isTable ( tableName ) ) { dao = new StyleMappingDao ( relatedTables . getUserDao ( tableName ) ) ; } return dao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a style DAO [CODESPLIT] public StyleDao getStyleDao ( ) { StyleDao styleDao = null ; if ( geoPackage . isTable ( StyleTable . TABLE_NAME ) ) { AttributesDao attributesDao = getGeoPackage ( ) . getAttributesDao ( StyleTable . TABLE_NAME ) ; styleDao = new StyleDao ( attributesDao ) ; relatedTables . setContents ( styleDao . getTable ( ) ) ; } return styleDao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a icon DAO [CODESPLIT] public IconDao getIconDao ( ) { IconDao iconDao = null ; if ( geoPackage . isTable ( IconTable . TABLE_NAME ) ) { iconDao = new IconDao ( relatedTables . getUserDao ( IconTable . TABLE_NAME ) ) ; relatedTables . setContents ( iconDao . getTable ( ) ) ; } return iconDao ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature table default feature styles [CODESPLIT] public FeatureStyles getTableFeatureStyles ( String featureTable ) { FeatureStyles featureStyles = null ; Long id = contentsId . getId ( featureTable ) ; if ( id != null ) { Styles styles = getTableStyles ( featureTable , id ) ; Icons icons = getTableIcons ( featureTable , id ) ; if ( styles != null || icons != null ) { featureStyles = new FeatureStyles ( styles , icons ) ; } } return featureStyles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature table default styles [CODESPLIT] public Styles getTableStyles ( String featureTable ) { Styles styles = null ; Long id = contentsId . getId ( featureTable ) ; if ( id != null ) { styles = getTableStyles ( featureTable , id ) ; } return styles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style of the feature table and geometry type [CODESPLIT] public StyleRow getTableStyle ( String featureTable , GeometryType geometryType ) { StyleRow styleRow = null ; Styles tableStyles = getTableStyles ( featureTable ) ; if ( tableStyles != null ) { styleRow = tableStyles . getStyle ( geometryType ) ; } return styleRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature table default icons [CODESPLIT] public Icons getTableIcons ( String featureTable ) { Icons icons = null ; Long id = contentsId . getId ( featureTable ) ; if ( id != null ) { icons = getTableIcons ( featureTable , id ) ; } return icons ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature table and geometry type [CODESPLIT] public IconRow getTableIcon ( String featureTable , GeometryType geometryType ) { IconRow iconRow = null ; Icons tableIcons = getTableIcons ( featureTable ) ; if ( tableIcons != null ) { iconRow = tableIcons . getIcon ( geometryType ) ; } return iconRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature styles for the feature row [CODESPLIT] public FeatureStyles getFeatureStyles ( FeatureRow featureRow ) { return getFeatureStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature styles for the feature table and feature id [CODESPLIT] public FeatureStyles getFeatureStyles ( String featureTable , long featureId ) { Styles styles = getStyles ( featureTable , featureId ) ; Icons icons = getIcons ( featureTable , featureId ) ; FeatureStyles featureStyles = null ; if ( styles != null || icons != null ) { featureStyles = new FeatureStyles ( styles , icons ) ; } return featureStyles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature style ( style and icon ) of the feature row with the provided geometry type searching in order : feature geometry type style or icon feature default style or icon table geometry type style or icon table default style or icon [CODESPLIT] public FeatureStyle getFeatureStyle ( FeatureRow featureRow , GeometryType geometryType ) { return getFeatureStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature style default ( style and icon ) of the feature row searching in order : feature default style or icon table default style or icon [CODESPLIT] public FeatureStyle getFeatureStyleDefault ( FeatureRow featureRow ) { return getFeatureStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the styles for the feature row [CODESPLIT] public Styles getStyles ( FeatureRow featureRow ) { return getStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style of the feature row with the provided geometry type searching in order : feature geometry type style feature default style table geometry type style table default style [CODESPLIT] public StyleRow getStyle ( FeatureRow featureRow , GeometryType geometryType ) { return getStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default style of the feature row searching in order : feature default style table default style [CODESPLIT] public StyleRow getStyleDefault ( FeatureRow featureRow ) { return getStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style of the feature searching in order : feature geometry type style feature default style table geometry type style table default style [CODESPLIT] public StyleRow getStyle ( String featureTable , long featureId , GeometryType geometryType ) { return getStyle ( featureTable , featureId , geometryType , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default style of the feature searching in order : feature default style table default style [CODESPLIT] public StyleRow getStyleDefault ( String featureTable , long featureId ) { return getStyle ( featureTable , featureId , null , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style of the feature searching in order : feature geometry type style feature default style when tableStyle enabled continue searching : table geometry type style table default style [CODESPLIT] public StyleRow getStyle ( String featureTable , long featureId , GeometryType geometryType , boolean tableStyle ) { StyleRow styleRow = null ; // Feature Style Styles styles = getStyles ( featureTable , featureId ) ; if ( styles != null ) { styleRow = styles . getStyle ( geometryType ) ; } if ( styleRow == null && tableStyle ) { // Table Style styleRow = getTableStyle ( featureTable , geometryType ) ; } return styleRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default style of the feature searching in order : feature default style when tableStyle enabled continue searching : table default style [CODESPLIT] public StyleRow getStyleDefault ( String featureTable , long featureId , boolean tableStyle ) { return getStyle ( featureTable , featureId , null , tableStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icons for the feature row [CODESPLIT] public Icons getIcons ( FeatureRow featureRow ) { return getIcons ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature row with the provided geometry type searching in order : feature geometry type icon feature default icon table geometry type icon table default icon [CODESPLIT] public IconRow getIcon ( FeatureRow featureRow , GeometryType geometryType ) { return getIcon ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default icon of the feature row searching in order : feature default icon table default icon [CODESPLIT] public IconRow getIconDefault ( FeatureRow featureRow ) { return getIcon ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature searching in order : feature geometry type icon feature default icon table geometry type icon table default icon [CODESPLIT] public IconRow getIcon ( String featureTable , long featureId , GeometryType geometryType ) { return getIcon ( featureTable , featureId , geometryType , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default icon of the feature searching in order : feature default icon table default icon [CODESPLIT] public IconRow getIconDefault ( String featureTable , long featureId ) { return getIcon ( featureTable , featureId , null , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature searching in order : feature geometry type icon feature default icon when tableIcon enabled continue searching : table geometry type icon table default icon [CODESPLIT] public IconRow getIcon ( String featureTable , long featureId , GeometryType geometryType , boolean tableIcon ) { IconRow iconRow = null ; // Feature Icon Icons icons = getIcons ( featureTable , featureId ) ; if ( icons != null ) { iconRow = icons . getIcon ( geometryType ) ; } if ( iconRow == null && tableIcon ) { // Table Icon iconRow = getTableIcon ( featureTable , geometryType ) ; } return iconRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default icon of the feature searching in order : feature default icon when tableIcon enabled continue searching : table default icon [CODESPLIT] public IconRow getIconDefault ( String featureTable , long featureId , boolean tableIcon ) { return getIcon ( featureTable , featureId , null , tableIcon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the styles for feature id from the style mapping dao [CODESPLIT] private Styles getStyles ( long featureId , StyleMappingDao mappingDao ) { Styles styles = null ; if ( mappingDao != null ) { StyleDao styleDao = getStyleDao ( ) ; if ( styleDao != null ) { List < StyleMappingRow > styleMappingRows = mappingDao . queryByBaseFeatureId ( featureId ) ; if ( ! styleMappingRows . isEmpty ( ) ) { for ( StyleMappingRow styleMappingRow : styleMappingRows ) { StyleRow styleRow = styleDao . queryForRow ( styleMappingRow ) ; if ( styleRow != null ) { if ( styles == null ) { styles = new Styles ( ) ; } styles . setStyle ( styleRow , styleMappingRow . getGeometryType ( ) ) ; } } } } } return styles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icons for feature id from the icon mapping dao [CODESPLIT] private Icons getIcons ( long featureId , StyleMappingDao mappingDao ) { Icons icons = null ; if ( mappingDao != null ) { IconDao iconDao = getIconDao ( ) ; if ( iconDao != null ) { List < StyleMappingRow > styleMappingRows = mappingDao . queryByBaseFeatureId ( featureId ) ; if ( ! styleMappingRows . isEmpty ( ) ) { for ( StyleMappingRow styleMappingRow : styleMappingRows ) { IconRow iconRow = iconDao . queryForRow ( styleMappingRow ) ; if ( iconRow != null ) { if ( icons == null ) { icons = new Icons ( ) ; } icons . setIcon ( iconRow , styleMappingRow . getGeometryType ( ) ) ; } } } } } return icons ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table default feature styles [CODESPLIT] public void setTableFeatureStyles ( String featureTable , FeatureStyles featureStyles ) { if ( featureStyles != null ) { setTableStyles ( featureTable , featureStyles . getStyles ( ) ) ; setTableIcons ( featureTable , featureStyles . getIcons ( ) ) ; } else { deleteTableFeatureStyles ( featureTable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table default styles [CODESPLIT] public void setTableStyles ( String featureTable , Styles styles ) { deleteTableStyles ( featureTable ) ; if ( styles != null ) { if ( styles . getDefault ( ) != null ) { setTableStyleDefault ( featureTable , styles . getDefault ( ) ) ; } for ( Entry < GeometryType , StyleRow > style : styles . getStyles ( ) . entrySet ( ) ) { setTableStyle ( featureTable , style . getKey ( ) , style . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table style for the geometry type [CODESPLIT] public void setTableStyle ( FeatureTable featureTable , GeometryType geometryType , StyleRow style ) { setTableStyle ( featureTable . getTableName ( ) , geometryType , style ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table style for the geometry type [CODESPLIT] public void setTableStyle ( String featureTable , GeometryType geometryType , StyleRow style ) { deleteTableStyle ( featureTable , geometryType ) ; if ( style != null ) { createTableStyleRelationship ( featureTable ) ; long featureContentsId = contentsId . getOrCreateId ( featureTable ) ; long styleId = getOrInsertStyle ( style ) ; StyleMappingDao mappingDao = getTableStyleMappingDao ( featureTable ) ; insertStyleMapping ( mappingDao , featureContentsId , styleId , geometryType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table default icons [CODESPLIT] public void setTableIcons ( String featureTable , Icons icons ) { deleteTableIcons ( featureTable ) ; if ( icons != null ) { if ( icons . getDefault ( ) != null ) { setTableIconDefault ( featureTable , icons . getDefault ( ) ) ; } for ( Entry < GeometryType , IconRow > icon : icons . getIcons ( ) . entrySet ( ) ) { setTableIcon ( featureTable , icon . getKey ( ) , icon . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table icon for the geometry type [CODESPLIT] public void setTableIcon ( FeatureTable featureTable , GeometryType geometryType , IconRow icon ) { setTableIcon ( featureTable . getTableName ( ) , geometryType , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table icon for the geometry type [CODESPLIT] public void setTableIcon ( String featureTable , GeometryType geometryType , IconRow icon ) { deleteTableIcon ( featureTable , geometryType ) ; if ( icon != null ) { createTableIconRelationship ( featureTable ) ; long featureContentsId = contentsId . getOrCreateId ( featureTable ) ; long iconId = getOrInsertIcon ( icon ) ; StyleMappingDao mappingDao = getTableIconMappingDao ( featureTable ) ; insertStyleMapping ( mappingDao , featureContentsId , iconId , geometryType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature styles for the feature row [CODESPLIT] public void setFeatureStyles ( FeatureRow featureRow , FeatureStyles featureStyles ) { setFeatureStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , featureStyles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature styles for the feature table and feature id [CODESPLIT] public void setFeatureStyles ( String featureTable , long featureId , FeatureStyles featureStyles ) { if ( featureStyles != null ) { setStyles ( featureTable , featureId , featureStyles . getStyles ( ) ) ; setIcons ( featureTable , featureId , featureStyles . getIcons ( ) ) ; } else { deleteStyles ( featureTable , featureId ) ; deleteIcons ( featureTable , featureId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature style ( style and icon ) of the feature row [CODESPLIT] public void setFeatureStyle ( FeatureRow featureRow , FeatureStyle featureStyle ) { setFeatureStyle ( featureRow , featureRow . getGeometryType ( ) , featureStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature style ( style and icon ) of the feature row for the specified geometry type [CODESPLIT] public void setFeatureStyle ( FeatureRow featureRow , GeometryType geometryType , FeatureStyle featureStyle ) { setFeatureStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType , featureStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature style default ( style and icon ) of the feature row [CODESPLIT] public void setFeatureStyleDefault ( FeatureRow featureRow , FeatureStyle featureStyle ) { setFeatureStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null , featureStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature style ( style and icon ) of the feature [CODESPLIT] public void setFeatureStyle ( String featureTable , long featureId , GeometryType geometryType , FeatureStyle featureStyle ) { if ( featureStyle != null ) { setStyle ( featureTable , featureId , geometryType , featureStyle . getStyle ( ) ) ; setIcon ( featureTable , featureId , geometryType , featureStyle . getIcon ( ) ) ; } else { deleteStyle ( featureTable , featureId , geometryType ) ; deleteIcon ( featureTable , featureId , geometryType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature style ( style and icon ) of the feature [CODESPLIT] public void setFeatureStyleDefault ( String featureTable , long featureId , FeatureStyle featureStyle ) { setFeatureStyle ( featureTable , featureId , null , featureStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the styles for the feature row [CODESPLIT] public void setStyles ( FeatureRow featureRow , Styles styles ) { setStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , styles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the styles for the feature table and feature id [CODESPLIT] public void setStyles ( String featureTable , long featureId , Styles styles ) { deleteStyles ( featureTable , featureId ) ; if ( styles != null ) { if ( styles . getDefault ( ) != null ) { setStyleDefault ( featureTable , featureId , styles . getDefault ( ) ) ; } for ( Entry < GeometryType , StyleRow > style : styles . getStyles ( ) . entrySet ( ) ) { setStyle ( featureTable , featureId , style . getKey ( ) , style . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the style of the feature row [CODESPLIT] public void setStyle ( FeatureRow featureRow , StyleRow style ) { setStyle ( featureRow , featureRow . getGeometryType ( ) , style ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the style of the feature row for the specified geometry type [CODESPLIT] public void setStyle ( FeatureRow featureRow , GeometryType geometryType , StyleRow style ) { setStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType , style ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default style of the feature row [CODESPLIT] public void setStyleDefault ( FeatureRow featureRow , StyleRow style ) { setStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null , style ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the style of the feature [CODESPLIT] public void setStyle ( String featureTable , long featureId , GeometryType geometryType , StyleRow style ) { deleteStyle ( featureTable , featureId , geometryType ) ; if ( style != null ) { createStyleRelationship ( featureTable ) ; long styleId = getOrInsertStyle ( style ) ; StyleMappingDao mappingDao = getStyleMappingDao ( featureTable ) ; insertStyleMapping ( mappingDao , featureId , styleId , geometryType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default style of the feature [CODESPLIT] public void setStyleDefault ( String featureTable , long featureId , StyleRow style ) { setStyle ( featureTable , featureId , null , style ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the icons for the feature row [CODESPLIT] public void setIcons ( FeatureRow featureRow , Icons icons ) { setIcons ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , icons ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the icons for the feature table and feature id [CODESPLIT] public void setIcons ( String featureTable , long featureId , Icons icons ) { deleteIcons ( featureTable , featureId ) ; if ( icons != null ) { if ( icons . getDefault ( ) != null ) { setIconDefault ( featureTable , featureId , icons . getDefault ( ) ) ; } for ( Entry < GeometryType , IconRow > icon : icons . getIcons ( ) . entrySet ( ) ) { setIcon ( featureTable , featureId , icon . getKey ( ) , icon . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the icon of the feature row [CODESPLIT] public void setIcon ( FeatureRow featureRow , IconRow icon ) { setIcon ( featureRow , featureRow . getGeometryType ( ) , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the icon of the feature row for the specified geometry type [CODESPLIT] public void setIcon ( FeatureRow featureRow , GeometryType geometryType , IconRow icon ) { setIcon ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default icon of the feature row [CODESPLIT] public void setIconDefault ( FeatureRow featureRow , IconRow icon ) { setIcon ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature searching in order : feature geometry type icon feature default icon table geometry type icon table default icon [CODESPLIT] public void setIcon ( String featureTable , long featureId , GeometryType geometryType , IconRow icon ) { deleteIcon ( featureTable , featureId , geometryType ) ; if ( icon != null ) { createIconRelationship ( featureTable ) ; long iconId = getOrInsertIcon ( icon ) ; StyleMappingDao mappingDao = getIconMappingDao ( featureTable ) ; insertStyleMapping ( mappingDao , featureId , iconId , geometryType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default icon of the feature [CODESPLIT] public void setIconDefault ( String featureTable , long featureId , IconRow icon ) { setIcon ( featureTable , featureId , null , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style id either from the existing style or by inserting a new one [CODESPLIT] private long getOrInsertStyle ( StyleRow style ) { long styleId ; if ( style . hasId ( ) ) { styleId = style . getId ( ) ; } else { StyleDao styleDao = getStyleDao ( ) ; styleId = styleDao . create ( style ) ; } return styleId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon id either from the existing icon or by inserting a new one [CODESPLIT] private long getOrInsertIcon ( IconRow icon ) { long iconId ; if ( icon . hasId ( ) ) { iconId = icon . getId ( ) ; } else { IconDao iconDao = getIconDao ( ) ; iconId = iconDao . create ( icon ) ; } return iconId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a style mapping row [CODESPLIT] private void insertStyleMapping ( StyleMappingDao mappingDao , long baseId , long relatedId , GeometryType geometryType ) { StyleMappingRow row = mappingDao . newRow ( ) ; row . setBaseId ( baseId ) ; row . setRelatedId ( relatedId ) ; row . setGeometryType ( geometryType ) ; mappingDao . insert ( row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature table style for the geometry type [CODESPLIT] public void deleteTableStyle ( String featureTable , GeometryType geometryType ) { deleteTableMapping ( getTableStyleMappingDao ( featureTable ) , featureTable , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature table icon for the geometry type [CODESPLIT] public void deleteTableIcon ( String featureTable , GeometryType geometryType ) { deleteTableMapping ( getTableIconMappingDao ( featureTable ) , featureTable , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the table style mappings [CODESPLIT] private void deleteTableMappings ( StyleMappingDao mappingDao , String featureTable ) { if ( mappingDao != null ) { Long featureContentsId = contentsId . getId ( featureTable ) ; if ( featureContentsId != null ) { mappingDao . deleteByBaseId ( featureContentsId ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the table style mapping with the geometry type value [CODESPLIT] private void deleteTableMapping ( StyleMappingDao mappingDao , String featureTable , GeometryType geometryType ) { if ( mappingDao != null ) { Long featureContentsId = contentsId . getId ( featureTable ) ; if ( featureContentsId != null ) { mappingDao . deleteByBaseId ( featureContentsId , geometryType ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature row style for the geometry type [CODESPLIT] public void deleteStyle ( FeatureRow featureRow , GeometryType geometryType ) { deleteStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature row style for the geometry type [CODESPLIT] public void deleteStyle ( String featureTable , long featureId , GeometryType geometryType ) { deleteMapping ( getStyleMappingDao ( featureTable ) , featureId , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature row icon for the geometry type [CODESPLIT] public void deleteIcon ( FeatureRow featureRow , GeometryType geometryType ) { deleteIcon ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature row icon for the geometry type [CODESPLIT] public void deleteIcon ( String featureTable , long featureId , GeometryType geometryType ) { deleteMapping ( getIconMappingDao ( featureTable ) , featureId , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the style mapping with the geometry type value [CODESPLIT] private void deleteMapping ( StyleMappingDao mappingDao , long featureId , GeometryType geometryType ) { if ( mappingDao != null ) { mappingDao . deleteByBaseId ( featureId , geometryType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the unique style row ids the table maps to [CODESPLIT] public List < Long > getAllTableStyleIds ( String featureTable ) { List < Long > styleIds = null ; StyleMappingDao mappingDao = getTableStyleMappingDao ( featureTable ) ; if ( mappingDao != null ) { styleIds = mappingDao . uniqueRelatedIds ( ) ; } return styleIds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the unique icon row ids the table maps to [CODESPLIT] public List < Long > getAllTableIconIds ( String featureTable ) { List < Long > iconIds = null ; StyleMappingDao mappingDao = getTableIconMappingDao ( featureTable ) ; if ( mappingDao != null ) { iconIds = mappingDao . uniqueRelatedIds ( ) ; } return iconIds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the unique style row ids the features map to [CODESPLIT] public List < Long > getAllStyleIds ( String featureTable ) { List < Long > styleIds = null ; StyleMappingDao mappingDao = getStyleMappingDao ( featureTable ) ; if ( mappingDao != null ) { styleIds = mappingDao . uniqueRelatedIds ( ) ; } return styleIds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the unique icon row ids the features map to [CODESPLIT] public List < Long > getAllIconIds ( String featureTable ) { List < Long > iconIds = null ; StyleMappingDao mappingDao = getIconMappingDao ( featureTable ) ; if ( mappingDao != null ) { iconIds = mappingDao . uniqueRelatedIds ( ) ; } return iconIds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the image bytes [CODESPLIT] public byte [ ] getImageBytes ( ) { byte [ ] bytes = null ; if ( imageBytes != null ) { bytes = imageBytes ; } else if ( outputStream != null ) { bytes = outputStream . toByteArray ( ) ; } return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flush the output stream and set the image bytes close the stream [CODESPLIT] public void flushStream ( ) { if ( outputStream != null ) { if ( imageBytes == null ) { imageBytes = outputStream . toByteArray ( ) ; } try { outputStream . close ( ) ; } catch ( IOException e ) { Log . w ( CoverageDataPngImage . class . getSimpleName ( ) , \"Failed to close output stream\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the pixel at the coordinate [CODESPLIT] public int getPixel ( int x , int y ) { int pixel = - 1 ; if ( pixels == null ) { readPixels ( ) ; } if ( pixels != null ) { pixel = pixels [ y ] [ x ] ; } else { throw new GeoPackageException ( \"Could not retrieve pixel value\" ) ; } return pixel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all the pixels from the image [CODESPLIT] private void readPixels ( ) { if ( reader != null ) { pixels = new int [ reader . imgInfo . rows ] [ reader . imgInfo . cols ] ; int rowCount = 0 ; while ( reader . hasMoreRows ( ) ) { ImageLineInt row = reader . readRowInt ( ) ; int [ ] columnValues = new int [ reader . imgInfo . cols ] ; System . arraycopy ( row . getScanline ( ) , 0 , columnValues , 0 , columnValues . length ) ; pixels [ rowCount ++ ] = columnValues ; } reader . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void onCreate ( SQLiteDatabase db ) { db . execSQL ( GeoPackageMetadata . CREATE_SQL ) ; db . execSQL ( TableMetadata . CREATE_SQL ) ; db . execSQL ( GeometryMetadata . CREATE_SQL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { db . execSQL ( \"DROP TABLE IF EXISTS \" + GeometryMetadata . TABLE_NAME ) ; db . execSQL ( \"DROP TABLE IF EXISTS \" + TableMetadata . TABLE_NAME ) ; db . execSQL ( \"DROP TABLE IF EXISTS \" + GeoPackageMetadata . TABLE_NAME ) ; onCreate ( db ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Bitmap drawTile ( int zoom , BoundingBox boundingBox , List < FeatureRow > featureRow ) { FeatureTileCanvas canvas = new FeatureTileCanvas ( tileWidth , tileHeight ) ; ProjectionTransform transform = getProjectionToWebMercatorTransform ( featureDao . getProjection ( ) ) ; BoundingBox expandedBoundingBox = expandBoundingBox ( boundingBox ) ; boolean drawn = false ; for ( FeatureRow row : featureRow ) { if ( drawFeature ( zoom , boundingBox , expandedBoundingBox , transform , canvas , row ) ) { drawn = true ; } } Bitmap bitmap = null ; if ( drawn ) { bitmap = canvas . createBitmap ( ) ; bitmap = checkIfDrawn ( bitmap ) ; } else { canvas . recycle ( ) ; } return bitmap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw the feature on the canvas [CODESPLIT] private boolean drawFeature ( int zoom , BoundingBox boundingBox , BoundingBox expandedBoundingBox , ProjectionTransform transform , FeatureTileCanvas canvas , FeatureRow row ) { boolean drawn = false ; try { GeoPackageGeometryData geomData = row . getGeometry ( ) ; if ( geomData != null ) { Geometry geometry = geomData . getGeometry ( ) ; if ( geometry != null ) { GeometryEnvelope envelope = geomData . getOrBuildEnvelope ( ) ; BoundingBox geometryBoundingBox = new BoundingBox ( envelope ) ; BoundingBox transformedBoundingBox = geometryBoundingBox . transform ( transform ) ; if ( expandedBoundingBox . intersects ( transformedBoundingBox , true ) ) { double simplifyTolerance = TileBoundingBoxUtils . toleranceDistance ( zoom , tileWidth , tileHeight ) ; drawn = drawShape ( simplifyTolerance , boundingBox , transform , canvas , row , geometry ) ; } } } } catch ( Exception e ) { Log . e ( DefaultFeatureTiles . class . getSimpleName ( ) , \"Failed to draw feature in tile. Table: \" + featureDao . getTableName ( ) , e ) ; } return drawn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw the geometry on the canvas [CODESPLIT] private boolean drawShape ( double simplifyTolerance , BoundingBox boundingBox , ProjectionTransform transform , FeatureTileCanvas canvas , FeatureRow featureRow , Geometry geometry ) { boolean drawn = false ; GeometryType geometryType = geometry . getGeometryType ( ) ; FeatureStyle featureStyle = getFeatureStyle ( featureRow , geometryType ) ; switch ( geometryType ) { case POINT : Point point = ( Point ) geometry ; drawn = drawPoint ( boundingBox , transform , canvas , point , featureStyle ) ; break ; case LINESTRING : case CIRCULARSTRING : LineString lineString = ( LineString ) geometry ; Path linePath = new Path ( ) ; addLineString ( simplifyTolerance , boundingBox , transform , linePath , lineString ) ; drawn = drawLinePath ( canvas , linePath , featureStyle ) ; break ; case POLYGON : case TRIANGLE : Polygon polygon = ( Polygon ) geometry ; Path polygonPath = new Path ( ) ; addPolygon ( simplifyTolerance , boundingBox , transform , polygonPath , polygon ) ; drawn = drawPolygonPath ( canvas , polygonPath , featureStyle ) ; break ; case MULTIPOINT : MultiPoint multiPoint = ( MultiPoint ) geometry ; for ( Point pointFromMulti : multiPoint . getPoints ( ) ) { drawn = drawPoint ( boundingBox , transform , canvas , pointFromMulti , featureStyle ) || drawn ; } break ; case MULTILINESTRING : MultiLineString multiLineString = ( MultiLineString ) geometry ; Path multiLinePath = new Path ( ) ; for ( LineString lineStringFromMulti : multiLineString . getLineStrings ( ) ) { addLineString ( simplifyTolerance , boundingBox , transform , multiLinePath , lineStringFromMulti ) ; } drawn = drawLinePath ( canvas , multiLinePath , featureStyle ) ; break ; case MULTIPOLYGON : MultiPolygon multiPolygon = ( MultiPolygon ) geometry ; Path multiPolygonPath = new Path ( ) ; for ( Polygon polygonFromMulti : multiPolygon . getPolygons ( ) ) { addPolygon ( simplifyTolerance , boundingBox , transform , multiPolygonPath , polygonFromMulti ) ; } drawn = drawPolygonPath ( canvas , multiPolygonPath , featureStyle ) ; break ; case COMPOUNDCURVE : CompoundCurve compoundCurve = ( CompoundCurve ) geometry ; Path compoundCurvePath = new Path ( ) ; for ( LineString lineStringFromCompoundCurve : compoundCurve . getLineStrings ( ) ) { addLineString ( simplifyTolerance , boundingBox , transform , compoundCurvePath , lineStringFromCompoundCurve ) ; } drawn = drawLinePath ( canvas , compoundCurvePath , featureStyle ) ; break ; case POLYHEDRALSURFACE : case TIN : PolyhedralSurface polyhedralSurface = ( PolyhedralSurface ) geometry ; Path polyhedralSurfacePath = new Path ( ) ; for ( Polygon polygonFromPolyhedralSurface : polyhedralSurface . getPolygons ( ) ) { addPolygon ( simplifyTolerance , boundingBox , transform , polyhedralSurfacePath , polygonFromPolyhedralSurface ) ; } drawn = drawPolygonPath ( canvas , polyhedralSurfacePath , featureStyle ) ; break ; case GEOMETRYCOLLECTION : @ SuppressWarnings ( \"unchecked\" ) GeometryCollection < Geometry > geometryCollection = ( GeometryCollection ) geometry ; List < Geometry > geometries = geometryCollection . getGeometries ( ) ; for ( Geometry geometryFromCollection : geometries ) { drawn = drawShape ( simplifyTolerance , boundingBox , transform , canvas , featureRow , geometryFromCollection ) || drawn ; } break ; default : throw new GeoPackageException ( \"Unsupported Geometry Type: \" + geometry . getGeometryType ( ) . getName ( ) ) ; } return drawn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw the line path on the canvas [CODESPLIT] private boolean drawLinePath ( FeatureTileCanvas canvas , Path path , FeatureStyle featureStyle ) { Canvas lineCanvas = canvas . getLineCanvas ( ) ; Paint pathPaint = getLinePaint ( featureStyle ) ; lineCanvas . drawPath ( path , pathPaint ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw the path on the canvas [CODESPLIT] private boolean drawPolygonPath ( FeatureTileCanvas canvas , Path path , FeatureStyle featureStyle ) { Canvas polygonCanvas = canvas . getPolygonCanvas ( ) ; Paint fillPaint = getPolygonFillPaint ( featureStyle ) ; if ( fillPaint != null ) { path . setFillType ( Path . FillType . EVEN_ODD ) ; polygonCanvas . drawPath ( path , fillPaint ) ; } Paint pathPaint = getPolygonPaint ( featureStyle ) ; polygonCanvas . drawPath ( path , pathPaint ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the linestring to the path [CODESPLIT] private void addLineString ( double simplifyTolerance , BoundingBox boundingBox , ProjectionTransform transform , Path path , LineString lineString ) { List < Point > points = lineString . getPoints ( ) ; if ( points . size ( ) >= 2 ) { // Try to simplify the number of points in the LineString points = simplifyPoints ( simplifyTolerance , points ) ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point point = points . get ( i ) ; Point webMercatorPoint = transform . transform ( point ) ; float x = TileBoundingBoxUtils . getXPixel ( tileWidth , boundingBox , webMercatorPoint . getX ( ) ) ; float y = TileBoundingBoxUtils . getYPixel ( tileHeight , boundingBox , webMercatorPoint . getY ( ) ) ; if ( i == 0 ) { path . moveTo ( x , y ) ; } else { path . lineTo ( x , y ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the polygon on the canvas [CODESPLIT] private void addPolygon ( double simplifyTolerance , BoundingBox boundingBox , ProjectionTransform transform , Path path , Polygon polygon ) { List < LineString > rings = polygon . getRings ( ) ; if ( ! rings . isEmpty ( ) ) { // Add the polygon points LineString polygonLineString = rings . get ( 0 ) ; List < Point > polygonPoints = polygonLineString . getPoints ( ) ; if ( polygonPoints . size ( ) >= 2 ) { addRing ( simplifyTolerance , boundingBox , transform , path , polygonPoints ) ; // Add the holes for ( int i = 1 ; i < rings . size ( ) ; i ++ ) { LineString holeLineString = rings . get ( i ) ; List < Point > holePoints = holeLineString . getPoints ( ) ; if ( holePoints . size ( ) >= 2 ) { addRing ( simplifyTolerance , boundingBox , transform , path , holePoints ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draw the point on the canvas [CODESPLIT] private boolean drawPoint ( BoundingBox boundingBox , ProjectionTransform transform , FeatureTileCanvas canvas , Point point , FeatureStyle featureStyle ) { boolean drawn = false ; Point webMercatorPoint = transform . transform ( point ) ; float x = TileBoundingBoxUtils . getXPixel ( tileWidth , boundingBox , webMercatorPoint . getX ( ) ) ; float y = TileBoundingBoxUtils . getYPixel ( tileHeight , boundingBox , webMercatorPoint . getY ( ) ) ; if ( featureStyle != null && featureStyle . hasIcon ( ) ) { IconRow iconRow = featureStyle . getIcon ( ) ; Bitmap icon = getIcon ( iconRow ) ; int width = icon . getWidth ( ) ; int height = icon . getHeight ( ) ; if ( x >= 0 - width && x <= tileWidth + width && y >= 0 - height && y <= tileHeight + height ) { float anchorU = ( float ) iconRow . getAnchorUOrDefault ( ) ; float anchorV = ( float ) iconRow . getAnchorVOrDefault ( ) ; float left = x - ( anchorU * width ) ; float right = left + width ; float top = y - ( anchorV * height ) ; float bottom = top + height ; RectF destination = new RectF ( left , top , right , bottom ) ; Canvas iconCanvas = canvas . getIconCanvas ( ) ; iconCanvas . drawBitmap ( icon , null , destination , pointPaint ) ; drawn = true ; } } else if ( pointIcon != null ) { float width = this . density * pointIcon . getWidth ( ) ; float height = this . density * pointIcon . getHeight ( ) ; if ( x >= 0 - width && x <= tileWidth + width && y >= 0 - height && y <= tileHeight + height ) { Canvas iconCanvas = canvas . getIconCanvas ( ) ; float left = x - this . density * pointIcon . getXOffset ( ) ; float top = y - this . density * pointIcon . getYOffset ( ) ; RectF rect = new RectF ( left , top , left + width , top + height ) ; iconCanvas . drawBitmap ( pointIcon . getIcon ( ) , null , rect , pointPaint ) ; drawn = true ; } } else { Float radius = null ; if ( featureStyle != null ) { StyleRow styleRow = featureStyle . getStyle ( ) ; if ( styleRow != null ) { radius = this . density * ( float ) ( styleRow . getWidthOrDefault ( ) / 2.0f ) ; } } if ( radius == null ) { radius = this . density * pointRadius ; } if ( x >= 0 - radius && x <= tileWidth + radius && y >= 0 - radius && y <= tileHeight + radius ) { Paint pointPaint = getPointPaint ( featureStyle ) ; Canvas pointCanvas = canvas . getPointCanvas ( ) ; pointCanvas . drawCircle ( x , y , radius , pointPaint ) ; drawn = true ; } } return drawn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get or create a feature row cache for the table name [CODESPLIT] public FeatureCache getCache ( String tableName ) { FeatureCache cache = tableCache . get ( tableName ) ; if ( cache == null ) { cache = new FeatureCache ( maxCacheSize ) ; tableCache . put ( tableName , cache ) ; } return cache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the cached feature row [CODESPLIT] public FeatureRow remove ( FeatureRow featureRow ) { return remove ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear and resize all caches and update the max cache size [CODESPLIT] public void clearAndResize ( int maxCacheSize ) { setMaxCacheSize ( maxCacheSize ) ; for ( FeatureCache cache : tableCache . values ( ) ) { cache . clearAndResize ( maxCacheSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cached table styles querying and caching if needed [CODESPLIT] public Styles getCachedTableStyles ( ) { Styles styles = cachedTableFeatureStyles . getStyles ( ) ; if ( styles == null ) { synchronized ( cachedTableFeatureStyles ) { styles = cachedTableFeatureStyles . getStyles ( ) ; if ( styles == null ) { styles = getTableStyles ( ) ; if ( styles == null ) { styles = new Styles ( ) ; } cachedTableFeatureStyles . setStyles ( styles ) ; } } } if ( styles . isEmpty ( ) ) { styles = null ; } return styles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cached table icons querying and caching if needed [CODESPLIT] public Icons getCachedTableIcons ( ) { Icons icons = cachedTableFeatureStyles . getIcons ( ) ; if ( icons == null ) { synchronized ( cachedTableFeatureStyles ) { icons = cachedTableFeatureStyles . getIcons ( ) ; if ( icons == null ) { icons = getTableIcons ( ) ; if ( icons == null ) { icons = new Icons ( ) ; } cachedTableFeatureStyles . setIcons ( icons ) ; } } } if ( icons . isEmpty ( ) ) { icons = null ; } return icons ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature style ( style and icon ) of the feature row with the provided geometry type searching in order : feature geometry type style or icon feature default style or icon table geometry type style or icon table default style or icon [CODESPLIT] public FeatureStyle getFeatureStyle ( FeatureRow featureRow , GeometryType geometryType ) { return getFeatureStyle ( featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature style ( style and icon ) of the feature searching in order : feature geometry type style or icon feature default style or icon table geometry type style or icon table default style or icon [CODESPLIT] public FeatureStyle getFeatureStyle ( long featureId , GeometryType geometryType ) { FeatureStyle featureStyle = null ; StyleRow style = getStyle ( featureId , geometryType ) ; IconRow icon = getIcon ( featureId , geometryType ) ; if ( style != null || icon != null ) { featureStyle = new FeatureStyle ( style , icon ) ; } return featureStyle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style of the feature row with the provided geometry type searching in order : feature geometry type style feature default style table geometry type style table default style [CODESPLIT] public StyleRow getStyle ( FeatureRow featureRow , GeometryType geometryType ) { return getStyle ( featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the style of the feature searching in order : feature geometry type style feature default style table geometry type style table default style [CODESPLIT] public StyleRow getStyle ( long featureId , GeometryType geometryType ) { StyleRow styleRow = featureStyleExtension . getStyle ( tableName , featureId , geometryType , false ) ; if ( styleRow == null ) { // Table Style Styles styles = getCachedTableStyles ( ) ; if ( styles != null ) { styleRow = styles . getStyle ( geometryType ) ; } } return styleRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature row with the provided geometry type searching in order : feature geometry type icon feature default icon table geometry type icon table default icon [CODESPLIT] public IconRow getIcon ( FeatureRow featureRow , GeometryType geometryType ) { return getIcon ( featureRow . getId ( ) , geometryType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature searching in order : feature geometry type icon feature default icon table geometry type icon table default icon [CODESPLIT] public IconRow getIcon ( long featureId , GeometryType geometryType ) { IconRow iconRow = featureStyleExtension . getIcon ( tableName , featureId , geometryType , false ) ; if ( iconRow == null ) { // Table Icon Icons icons = getCachedTableIcons ( ) ; if ( icons != null ) { iconRow = icons . getIcon ( geometryType ) ; } } return iconRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table style for the geometry type [CODESPLIT] public void setTableStyle ( GeometryType geometryType , StyleRow style ) { featureStyleExtension . setTableStyle ( tableName , geometryType , style ) ; clearCachedTableStyles ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature table icon for the geometry type [CODESPLIT] public void setTableIcon ( GeometryType geometryType , IconRow icon ) { featureStyleExtension . setTableIcon ( tableName , geometryType , icon ) ; clearCachedTableIcons ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature style ( style and icon ) of the feature row for the specified geometry type [CODESPLIT] public void setFeatureStyle ( FeatureRow featureRow , GeometryType geometryType , FeatureStyle featureStyle ) { featureStyleExtension . setFeatureStyle ( featureRow , geometryType , featureStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the feature style ( style and icon ) of the feature [CODESPLIT] public void setFeatureStyle ( long featureId , GeometryType geometryType , FeatureStyle featureStyle ) { featureStyleExtension . setFeatureStyle ( tableName , featureId , geometryType , featureStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the style of the feature row for the specified geometry type [CODESPLIT] public void setStyle ( FeatureRow featureRow , GeometryType geometryType , StyleRow style ) { featureStyleExtension . setStyle ( featureRow , geometryType , style ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the style of the feature [CODESPLIT] public void setStyle ( long featureId , GeometryType geometryType , StyleRow style ) { featureStyleExtension . setStyle ( tableName , featureId , geometryType , style ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the icon of the feature row for the specified geometry type [CODESPLIT] public void setIcon ( FeatureRow featureRow , GeometryType geometryType , IconRow icon ) { featureStyleExtension . setIcon ( featureRow , geometryType , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the icon of the feature searching in order : feature geometry type icon feature default icon table geometry type icon table default icon [CODESPLIT] public void setIcon ( long featureId , GeometryType geometryType , IconRow icon ) { featureStyleExtension . setIcon ( tableName , featureId , geometryType , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected TileTable createTable ( String tableName , List < TileColumn > columnList ) { return new TileTable ( tableName , columnList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected TileColumn createColumn ( TileCursor cursor , int index , String name , String type , Long max , boolean notNull , int defaultValueIndex , boolean primaryKey ) { GeoPackageDataType dataType = getDataType ( type ) ; Object defaultValue = cursor . getValue ( defaultValueIndex , dataType ) ; TileColumn column = new TileColumn ( index , name , dataType , max , notNull , defaultValue , primaryKey ) ; return column ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a RTree Index Table DAO for the feature dao [CODESPLIT] public RTreeIndexTableDao getTableDao ( FeatureDao featureDao ) { GeoPackageConnection connection = getGeoPackage ( ) . getConnection ( ) ; UserCustomConnection userDb = new UserCustomConnection ( connection ) ; UserCustomTable userCustomTable = getRTreeTable ( featureDao . getTable ( ) ) ; UserCustomDao userCustomDao = new UserCustomDao ( geoPackage . getName ( ) , connection , userDb , userCustomTable ) ; return new RTreeIndexTableDao ( this , userCustomDao , featureDao ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void executeSQL ( String sql , boolean trigger ) { if ( trigger ) { connection . execSQL ( sql ) ; } else { database . execSQL ( sql ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the width [CODESPLIT] public void setWidth ( Double width ) { if ( width != null && width < 0.0 ) { throw new GeoPackageException ( \"Width must be greater than or equal to 0.0, invalid value: \" + width ) ; } setValue ( getWidthColumnIndex ( ) , width ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the height [CODESPLIT] public void setHeight ( Double height ) { if ( height != null && height < 0.0 ) { throw new GeoPackageException ( \"Height must be greater than or equal to 0.0, invalid value: \" + height ) ; } setValue ( getHeightColumnIndex ( ) , height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the derived width and height from the values and icon data scaled as needed [CODESPLIT] public double [ ] getDerivedDimensions ( ) { Double width = getWidth ( ) ; Double height = getHeight ( ) ; if ( width == null || height == null ) { BitmapFactory . Options options = getDataBounds ( ) ; int dataWidth = options . outWidth ; int dataHeight = options . outHeight ; if ( width == null ) { width = ( double ) dataWidth ; if ( height != null ) { width *= ( height / dataHeight ) ; } } if ( height == null ) { height = ( double ) dataHeight ; if ( width != null ) { height *= ( width / dataWidth ) ; } } } return new double [ ] { width , height } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile side ( width and height ) dimension based upon the display density scale [CODESPLIT] public static int tileLength ( float density ) { int length ; if ( density < HIGH_DENSITY ) { length = TILE_PIXELS_DEFAULT ; } else { length = TILE_PIXELS_HIGH ; } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tile density based upon the display density scale and tile dimensions [CODESPLIT] public static float tileDensity ( float density , int tileWidth , int tileHeight ) { return tileDensity ( density , Math . min ( tileWidth , tileHeight ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean moveToNext ( ) { boolean hasNext = false ; currentPosition ++ ; if ( currentPosition < invalidPositions . size ( ) ) { int invalidPosition = invalidPositions . get ( currentPosition ) ; hasNext = cursor . moveToPosition ( invalidPosition ) ; } return hasNext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TRow getRow ( ) { TRow row = cursor . getRow ( ) ; if ( row . hasId ( ) ) { for ( UserColumn column : blobColumns ) { readBlobValue ( row , column ) ; } } return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the blob column value in chunks [CODESPLIT] private void readBlobValue ( UserRow row , UserColumn column ) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( ) ; try { byte [ ] blobChunk = new byte [ ] { 0 } ; for ( int i = 1 ; blobChunk . length > 0 ; i += CHUNK_SIZE ) { if ( i > 1 ) { byteStream . write ( blobChunk ) ; } blobChunk = new byte [ ] { } ; String query = \"select substr(\" + CoreSQLUtils . quoteWrap ( column . getName ( ) ) + \", \" + i + \", \" + CHUNK_SIZE + \") from \" + CoreSQLUtils . quoteWrap ( dao . getTableName ( ) ) + \" where \" + CoreSQLUtils . quoteWrap ( row . getPkColumn ( ) . getName ( ) ) + \" = \" + row . getId ( ) ; Cursor blobCursor = dao . getDatabaseConnection ( ) . getDb ( ) . rawQuery ( query , null ) ; try { if ( blobCursor . moveToNext ( ) ) { blobChunk = blobCursor . getBlob ( 0 ) ; } } finally { blobCursor . close ( ) ; } } byte [ ] blob = byteStream . toByteArray ( ) ; row . setValue ( column . getIndex ( ) , blob ) ; } catch ( IOException e ) { Log . e ( UserInvalidCursor . class . getSimpleName ( ) , \"Failed to read large blob value. Table: \" + dao . getTableName ( ) + \", Column: \" + column . getName ( ) + \", Position: \" + getPosition ( ) , e ) ; } finally { IOUtils . closeQuietly ( byteStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public TRow getRow ( int [ ] columnTypes , Object [ ] values ) { return cursor . getRow ( columnTypes , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object getValue ( int index , GeoPackageDataType dataType ) { return cursor . getValue ( index , dataType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean moveToPosition ( int position ) { boolean moved = false ; if ( position < invalidPositions . size ( ) ) { currentPosition = position ; int invalidPosition = invalidPositions . get ( currentPosition ) ; moved = cursor . moveToPosition ( invalidPosition ) ; } return moved ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected UserCustomTable createTable ( String tableName , List < UserCustomColumn > columnList ) { return new UserCustomTable ( tableName , columnList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the table [CODESPLIT] public static UserCustomTable readTable ( GeoPackageConnection connection , String tableName ) { UserCustomTableReader tableReader = new UserCustomTableReader ( tableName ) ; UserCustomTable customTable = tableReader . readTable ( new UserCustomWrapperConnection ( connection ) ) ; return customTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the color [CODESPLIT] public void setColor ( Color color ) { String hex = null ; Double opacity = null ; if ( color != null ) { hex = color . getColorHexShorthand ( ) ; opacity = new Double ( color . getOpacity ( ) ) ; } setColor ( hex ) ; setOpacity ( opacity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the color or default value [CODESPLIT] public Color getColorOrDefault ( ) { Color color = getColor ( ) ; if ( color == null ) { color = new Color ( ) ; } return color ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the color [CODESPLIT] public void setFillColor ( Color color ) { String hex = null ; Double opacity = null ; if ( color != null ) { hex = color . getColorHexShorthand ( ) ; opacity = new Double ( color . getOpacity ( ) ) ; } setFillColor ( hex ) ; setFillOpacity ( opacity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate and adjust the color value [CODESPLIT] private String validateColor ( String color ) { String validated = color ; if ( color != null ) { if ( ! color . startsWith ( \"#\" ) ) { validated = \"#\" + color ; } if ( ! colorPattern . matcher ( validated ) . matches ( ) ) { throw new GeoPackageException ( \"Color must be in hex format #RRGGBB or #RGB, invalid value: \" + color ) ; } validated = validated . toUpperCase ( ) ; } return validated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a color from the hex color and opacity [CODESPLIT] private Color createColor ( String hexColor , Double opacity ) { Color color = null ; if ( hexColor != null || opacity != null ) { color = new Color ( ) ; if ( hexColor != null ) { color . setColor ( hexColor ) ; } if ( opacity != null ) { color . setOpacity ( opacity . floatValue ( ) ) ; } } return color ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a GeoPackage Manager [CODESPLIT] public static GeoPackageManager getManager ( Context context ) { Thread . currentThread ( ) . setContextClassLoader ( GeoPackageManager . class . getClassLoader ( ) ) ; return new GeoPackageManagerImpl ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prioritize the query location order . All types are placed at the front of the query order in the order they are given . Omitting a location leaves it at it s current priority location . [CODESPLIT] public void prioritizeQueryLocation ( Collection < FeatureIndexType > types ) { prioritizeQueryLocation ( types . toArray ( new FeatureIndexType [ types . size ( ) ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prioritize the query location order . All types are placed at the front of the query order in the order they are given . Omitting a location leaves it at it s current priority location . [CODESPLIT] public void prioritizeQueryLocation ( FeatureIndexType ... types ) { // Create a new query order set Set < FeatureIndexType > queryOrder = new LinkedHashSet <> ( ) ; for ( FeatureIndexType type : types ) { if ( type != FeatureIndexType . NONE ) { queryOrder . add ( type ) ; } } // Add any locations not provided to this method queryOrder . addAll ( indexLocationQueryOrder ) ; // Update the query order set indexLocationQueryOrder = queryOrder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the index location order overriding all previously set types [CODESPLIT] public void setIndexLocationOrder ( Collection < FeatureIndexType > types ) { setIndexLocationOrder ( types . toArray ( new FeatureIndexType [ types . size ( ) ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the index location order overriding all previously set types [CODESPLIT] public void setIndexLocationOrder ( FeatureIndexType ... types ) { // Create a new query order set Set < FeatureIndexType > queryOrder = new LinkedHashSet <> ( ) ; for ( FeatureIndexType type : types ) { if ( type != FeatureIndexType . NONE ) { queryOrder . add ( type ) ; } } // Update the query order set indexLocationQueryOrder = queryOrder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the GeoPackage Progress [CODESPLIT] public void setProgress ( GeoPackageProgress progress ) { featureTableIndex . setProgress ( progress ) ; featureIndexer . setProgress ( progress ) ; rTreeIndexTableDao . setProgress ( progress ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature tables for the index types [CODESPLIT] public int index ( boolean force , List < FeatureIndexType > types ) { int count = 0 ; for ( FeatureIndexType type : types ) { int typeCount = index ( type , force ) ; count = Math . max ( count , typeCount ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature table [CODESPLIT] public int index ( FeatureIndexType type , boolean force ) { if ( type == null ) { throw new GeoPackageException ( \"FeatureIndexType is required to index\" ) ; } int count = 0 ; switch ( type ) { case GEOPACKAGE : count = featureTableIndex . index ( force ) ; break ; case METADATA : count = featureIndexer . index ( force ) ; break ; case RTREE : boolean rTreeIndexed = rTreeIndexTableDao . has ( ) ; if ( ! rTreeIndexed || force ) { if ( rTreeIndexed ) { rTreeIndexTableDao . delete ( ) ; } rTreeIndexTableDao . create ( ) ; count = rTreeIndexTableDao . count ( ) ; } break ; default : throw new GeoPackageException ( \"Unsupported FeatureIndexType: \" + type ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature row for the index types . This method assumes that indexing has been completed and maintained as the last indexed time is updated . [CODESPLIT] public boolean index ( FeatureRow row , List < FeatureIndexType > types ) { boolean indexed = false ; for ( FeatureIndexType type : types ) { if ( index ( type , row ) ) { indexed = true ; } } return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature row . This method assumes that indexing has been completed and maintained as the last indexed time is updated . [CODESPLIT] public boolean index ( FeatureIndexType type , FeatureRow row ) { boolean indexed = false ; if ( type == null ) { throw new GeoPackageException ( \"FeatureIndexType is required to index\" ) ; } switch ( type ) { case GEOPACKAGE : indexed = featureTableIndex . index ( row ) ; break ; case METADATA : indexed = featureIndexer . index ( row ) ; break ; case RTREE : // Updated by triggers, ignore for RTree indexed = true ; break ; default : throw new GeoPackageException ( \"Unsupported FeatureIndexType: \" + type ) ; } return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature index from the index types [CODESPLIT] public boolean deleteIndex ( Collection < FeatureIndexType > types ) { boolean deleted = false ; for ( FeatureIndexType type : types ) { if ( deleteIndex ( type ) ) { deleted = true ; } } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature index for the feature row from the index types [CODESPLIT] public boolean deleteIndex ( FeatureRow row , List < FeatureIndexType > types ) { boolean deleted = false ; for ( FeatureIndexType type : types ) { if ( deleteIndex ( type , row ) ) { deleted = true ; } } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature index for the geometry id from the index types [CODESPLIT] public boolean deleteIndex ( long geomId , List < FeatureIndexType > types ) { boolean deleted = false ; for ( FeatureIndexType type : types ) { if ( deleteIndex ( type , geomId ) ) { deleted = true ; } } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature index for the geometry id [CODESPLIT] public boolean deleteIndex ( FeatureIndexType type , long geomId ) { if ( type == null ) { throw new GeoPackageException ( \"FeatureIndexType is required to delete index\" ) ; } boolean deleted = false ; switch ( type ) { case GEOPACKAGE : deleted = featureTableIndex . deleteIndex ( geomId ) > 0 ; break ; case METADATA : deleted = featureIndexer . deleteIndex ( geomId ) ; break ; case RTREE : // Updated by triggers, ignore for RTree deleted = true ; break ; default : throw new GeoPackageException ( \"Unsupported FeatureIndexType: \" + type ) ; } return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retain the feature index from the index types and delete the others [CODESPLIT] public boolean retainIndex ( FeatureIndexType type ) { List < FeatureIndexType > retain = new ArrayList < FeatureIndexType > ( ) ; retain . add ( type ) ; return retainIndex ( retain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retain the feature index from the index types and delete the others [CODESPLIT] public boolean retainIndex ( Collection < FeatureIndexType > types ) { Set < FeatureIndexType > delete = new HashSet <> ( indexLocationQueryOrder ) ; delete . removeAll ( types ) ; return deleteIndex ( delete ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the feature table is indexed [CODESPLIT] public boolean isIndexed ( ) { boolean indexed = false ; for ( FeatureIndexType type : indexLocationQueryOrder ) { indexed = isIndexed ( type ) ; if ( indexed ) { break ; } } return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the indexed types that are currently indexed [CODESPLIT] public List < FeatureIndexType > getIndexedTypes ( ) { List < FeatureIndexType > indexed = new ArrayList <> ( ) ; for ( FeatureIndexType type : indexLocationQueryOrder ) { if ( isIndexed ( type ) ) { indexed . add ( type ) ; } } return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the date last indexed [CODESPLIT] public Date getLastIndexed ( ) { Date lastIndexed = null ; for ( FeatureIndexType type : indexLocationQueryOrder ) { lastIndexed = getLastIndexed ( type ) ; if ( lastIndexed != null ) { break ; } } return lastIndexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all feature index results [CODESPLIT] public FeatureIndexResults query ( ) { FeatureIndexResults results = null ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : long count = featureTableIndex . count ( ) ; CloseableIterator < GeometryIndex > geometryIndices = featureTableIndex . query ( ) ; results = new FeatureIndexGeoPackageResults ( featureTableIndex , count , geometryIndices ) ; break ; case METADATA : Cursor geometryMetadata = featureIndexer . query ( ) ; results = new FeatureIndexMetadataResults ( featureIndexer , geometryMetadata ) ; break ; case RTREE : UserCustomCursor cursor = rTreeIndexTableDao . queryForAll ( ) ; results = new FeatureIndexRTreeResults ( rTreeIndexTableDao , cursor ) ; break ; default : FeatureCursor featureCursor = featureDao . queryForAll ( ) ; results = new FeatureIndexFeatureResults ( featureCursor ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all feature index count [CODESPLIT] public long count ( ) { long count = 0 ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : count = featureTableIndex . count ( ) ; break ; case METADATA : count = featureIndexer . count ( ) ; break ; case RTREE : count = rTreeIndexTableDao . count ( ) ; break ; default : count = manualFeatureQuery . countWithGeometries ( ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for the feature index bounds [CODESPLIT] public BoundingBox getBoundingBox ( ) { BoundingBox bounds = null ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : bounds = featureTableIndex . getBoundingBox ( ) ; break ; case METADATA : bounds = featureIndexer . getBoundingBox ( ) ; break ; case RTREE : bounds = rTreeIndexTableDao . getBoundingBox ( ) ; break ; default : bounds = manualFeatureQuery . getBoundingBox ( ) ; } return bounds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for feature index results within the bounding box in the provided projection [CODESPLIT] public FeatureIndexResults query ( BoundingBox boundingBox , Projection projection ) { FeatureIndexResults results = null ; switch ( getIndexedType ( ) ) { case GEOPACKAGE : long count = featureTableIndex . count ( boundingBox , projection ) ; CloseableIterator < GeometryIndex > geometryIndices = featureTableIndex . query ( boundingBox , projection ) ; results = new FeatureIndexGeoPackageResults ( featureTableIndex , count , geometryIndices ) ; break ; case METADATA : Cursor geometryMetadata = featureIndexer . query ( boundingBox , projection ) ; results = new FeatureIndexMetadataResults ( featureIndexer , geometryMetadata ) ; break ; case RTREE : UserCustomCursor cursor = rTreeIndexTableDao . query ( boundingBox , projection ) ; results = new FeatureIndexRTreeResults ( rTreeIndexTableDao , cursor ) ; break ; default : results = manualFeatureQuery . query ( boundingBox , projection ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the indexed type or throw an error if not indexed [CODESPLIT] private FeatureIndexType getIndexedType ( ) { FeatureIndexType indexType = FeatureIndexType . NONE ; // Check for an indexed type for ( FeatureIndexType type : indexLocationQueryOrder ) { if ( isIndexed ( type ) ) { indexType = type ; break ; } } return indexType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean hasTile ( int x , int y , int zoom ) { // Get the bounding box of the requested tile BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; boolean hasTile = tileCreator . hasTile ( webMercatorBoundingBox ) ; return hasTile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public GeoPackageTile getTile ( int x , int y , int zoom ) { // Get the bounding box of the requested tile BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( x , y , zoom ) ; GeoPackageTile tile = tileCreator . getTile ( webMercatorBoundingBox ) ; return tile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the internal storage file for the file path [CODESPLIT] public static File getInternalFile ( Context context , String filePath ) { File internalFile = null ; if ( filePath != null ) { internalFile = new File ( context . getFilesDir ( ) , filePath ) ; } else { internalFile = context . getFilesDir ( ) ; } return internalFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the internal storage patch for the file path [CODESPLIT] public static String getInternalFilePath ( Context context , String filePath ) { return getInternalFile ( context , filePath ) . getAbsolutePath ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the geometry type [CODESPLIT] public GeometryType getGeometryType ( ) { GeometryType geometryType = null ; String geometryTypeName = getGeometryTypeName ( ) ; if ( geometryTypeName != null ) { geometryType = GeometryType . fromName ( geometryTypeName ) ; } return geometryType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the geometry type [CODESPLIT] public void setGeometryType ( GeometryType geometryType ) { String geometryTypeName = null ; if ( geometryType != null ) { geometryTypeName = geometryType . getName ( ) ; } setValue ( getGeometryTypeNameColumnIndex ( ) , geometryTypeName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the url has bounding box variables [CODESPLIT] private boolean hasBoundingBox ( String url ) { String replacedUrl = replaceBoundingBox ( url , boundingBox ) ; boolean hasBoundingBox = ! replacedUrl . equals ( url ) ; return hasBoundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace x y and z in the url [CODESPLIT] private String replaceXYZ ( String url , int z , long x , long y ) { url = url . replaceAll ( context . getString ( R . string . tile_generator_variable_z ) , String . valueOf ( z ) ) ; url = url . replaceAll ( context . getString ( R . string . tile_generator_variable_x ) , String . valueOf ( x ) ) ; url = url . replaceAll ( context . getString ( R . string . tile_generator_variable_y ) , String . valueOf ( y ) ) ; return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the url has x y or z variables [CODESPLIT] private boolean hasXYZ ( String url ) { String replacedUrl = replaceXYZ ( url , 0 , 0 , 0 ) ; boolean hasXYZ = ! replacedUrl . equals ( url ) ; return hasXYZ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the bounding box coordinates in the url [CODESPLIT] private String replaceBoundingBox ( String url , int z , long x , long y ) { BoundingBox boundingBox = TileBoundingBoxUtils . getProjectedBoundingBox ( projection , x , y , z ) ; url = replaceBoundingBox ( url , boundingBox ) ; return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the url parts with the bounding box [CODESPLIT] private String replaceBoundingBox ( String url , BoundingBox boundingBox ) { url = url . replaceAll ( context . getString ( R . string . tile_generator_variable_min_lat ) , String . valueOf ( boundingBox . getMinLatitude ( ) ) ) ; url = url . replaceAll ( context . getString ( R . string . tile_generator_variable_max_lat ) , String . valueOf ( boundingBox . getMaxLatitude ( ) ) ) ; url = url . replaceAll ( context . getString ( R . string . tile_generator_variable_min_lon ) , String . valueOf ( boundingBox . getMinLongitude ( ) ) ) ; url = url . replaceAll ( context . getString ( R . string . tile_generator_variable_max_lon ) , String . valueOf ( boundingBox . getMaxLongitude ( ) ) ) ; return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected byte [ ] createTile ( int z , long x , long y ) { byte [ ] bytes = null ; String zoomUrl = tileUrl ; // Replace x, y, and z if ( urlHasXYZ ) { long yRequest = y ; // If TMS, flip the y value if ( tms ) { yRequest = TileBoundingBoxUtils . getYAsOppositeTileFormat ( z , ( int ) y ) ; } zoomUrl = replaceXYZ ( zoomUrl , z , x , yRequest ) ; } // Replace bounding box if ( urlHasBoundingBox ) { zoomUrl = replaceBoundingBox ( zoomUrl , z , x , y ) ; } URL url ; try { url = new URL ( zoomUrl ) ; } catch ( MalformedURLException e ) { throw new GeoPackageException ( \"Failed to download tile. URL: \" + zoomUrl + \", z=\" + z + \", x=\" + x + \", y=\" + y , e ) ; } HttpURLConnection connection = null ; try { connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . connect ( ) ; int responseCode = connection . getResponseCode ( ) ; if ( responseCode == HttpURLConnection . HTTP_MOVED_PERM || responseCode == HttpURLConnection . HTTP_MOVED_TEMP || responseCode == HttpURLConnection . HTTP_SEE_OTHER ) { String redirect = connection . getHeaderField ( \"Location\" ) ; connection . disconnect ( ) ; url = new URL ( redirect ) ; connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . connect ( ) ; } if ( connection . getResponseCode ( ) != HttpURLConnection . HTTP_OK ) { throw new GeoPackageException ( \"Failed to download tile. URL: \" + zoomUrl + \", z=\" + z + \", x=\" + x + \", y=\" + y ) ; } InputStream geoPackageStream = connection . getInputStream ( ) ; bytes = GeoPackageIOUtils . streamBytes ( geoPackageStream ) ; } catch ( IOException e ) { throw new GeoPackageException ( \"Failed to download tile. URL: \" + zoomUrl + \", z=\" + z + \", x=\" + x + \", y=\" + y , e ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FeatureRow getRow ( int [ ] columnTypes , Object [ ] values ) { return new FeatureRow ( getTable ( ) , columnTypes , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Object getValue ( FeatureColumn column ) { Object value ; if ( column . isGeometry ( ) ) { value = getGeometry ( ) ; } else { value = super . getValue ( column ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the geometry [CODESPLIT] public GeoPackageGeometryData getGeometry ( ) { GeoPackageGeometryData geometry = null ; int columnIndex = getTable ( ) . getGeometryColumnIndex ( ) ; int type = getType ( columnIndex ) ; if ( type != FIELD_TYPE_NULL ) { byte [ ] geometryBytes = getBlob ( columnIndex ) ; if ( geometryBytes != null ) { geometry = new GeoPackageGeometryData ( geometryBytes ) ; } } return geometry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected UserInvalidCursor < FeatureColumn , FeatureTable , FeatureRow , ? extends UserCursor < FeatureColumn , FeatureTable , FeatureRow > , ? extends UserDao < FeatureColumn , FeatureTable , FeatureRow , ? extends UserCursor < FeatureColumn , FeatureTable , FeatureRow > > > createInvalidCursor ( UserDao dao , UserCursor cursor , List < Integer > invalidPositions , List < FeatureColumn > blobColumns ) { return new FeatureInvalidCursor ( ( FeatureDao ) dao , ( FeatureCursor ) cursor , invalidPositions , blobColumns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature row . This method assumes that indexing has been completed and maintained as the last indexed time is updated . [CODESPLIT] public boolean index ( FeatureRow row ) { long geoPackageId = geometryMetadataDataSource . getGeoPackageId ( featureDao . getDatabase ( ) ) ; boolean indexed = index ( geoPackageId , row , true ) ; // Update the last indexed time updateLastIndexed ( db , geoPackageId ) ; return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature table [CODESPLIT] private int indexTable ( ) { int count = 0 ; // Get or create the table metadata TableMetadataDataSource tableDs = new TableMetadataDataSource ( db ) ; TableMetadata metadata = tableDs . getOrCreate ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) ) ; // Delete existing index rows geometryMetadataDataSource . delete ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) ) ; long offset = 0 ; int chunkCount = 0 ; // Index all features while ( chunkCount >= 0 ) { FeatureCursor cursor = featureDao . queryForChunk ( chunkLimit , offset ) ; chunkCount = indexRows ( metadata . getGeoPackageId ( ) , cursor ) ; if ( chunkCount > 0 ) { count += chunkCount ; } offset += chunkLimit ; } // Update the last indexed time if ( progress == null || progress . isActive ( ) ) { updateLastIndexed ( db , metadata . getGeoPackageId ( ) ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature rows in the cursor [CODESPLIT] private int indexRows ( long geoPackageId , FeatureCursor cursor ) { int count = - 1 ; try { while ( ( progress == null || progress . isActive ( ) ) && cursor . moveToNext ( ) ) { if ( count < 0 ) { count ++ ; } try { FeatureRow row = cursor . getRow ( ) ; if ( row . isValid ( ) ) { boolean indexed = index ( geoPackageId , row , false ) ; if ( indexed ) { count ++ ; } if ( progress != null ) { progress . addProgress ( 1 ) ; } } } catch ( Exception e ) { Log . e ( FeatureIndexer . class . getSimpleName ( ) , \"Failed to index feature. Table: \" + featureDao . getTableName ( ) + \", Position: \" + cursor . getPosition ( ) , e ) ; } } } finally { cursor . close ( ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index the feature row [CODESPLIT] private boolean index ( long geoPackageId , FeatureRow row , boolean possibleUpdate ) { boolean indexed = false ; GeoPackageGeometryData geomData = row . getGeometry ( ) ; if ( geomData != null ) { // Get the envelope GeometryEnvelope envelope = geomData . getEnvelope ( ) ; // If no envelope, build one from the geometry if ( envelope == null ) { Geometry geometry = geomData . getGeometry ( ) ; if ( geometry != null ) { envelope = GeometryEnvelopeBuilder . buildEnvelope ( geometry ) ; } } // Create the new index row if ( envelope != null ) { GeometryMetadata metadata = geometryMetadataDataSource . populate ( geoPackageId , featureDao . getTableName ( ) , row . getId ( ) , envelope ) ; if ( possibleUpdate ) { geometryMetadataDataSource . createOrUpdate ( metadata ) ; } else { geometryMetadataDataSource . create ( metadata ) ; } indexed = true ; } } return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the least indexed time [CODESPLIT] private void updateLastIndexed ( GeoPackageMetadataDb db , long geoPackageId ) { long indexedTime = ( new Date ( ) ) . getTime ( ) ; TableMetadataDataSource ds = new TableMetadataDataSource ( db ) ; if ( ! ds . updateLastIndexed ( geoPackageId , featureDao . getTableName ( ) , indexedTime ) ) { throw new GeoPackageException ( \"Failed to update last indexed time. Table: GeoPackage Id: \" + geoPackageId + \", Table: \" + featureDao . getTableName ( ) + \", Last Indexed: \" + indexedTime ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the feature table index [CODESPLIT] public boolean deleteIndex ( ) { TableMetadataDataSource tableMetadataDataSource = new TableMetadataDataSource ( db ) ; boolean deleted = tableMetadataDataSource . delete ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) ) ; return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the index for the geometry id [CODESPLIT] public boolean deleteIndex ( long geomId ) { boolean deleted = geometryMetadataDataSource . delete ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) , geomId ) ; return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the database table is indexed after database modifications [CODESPLIT] public boolean isIndexed ( ) { boolean indexed = false ; Date lastIndexed = getLastIndexed ( ) ; if ( lastIndexed != null ) { Contents contents = featureDao . getGeometryColumns ( ) . getContents ( ) ; Date lastChange = contents . getLastChange ( ) ; indexed = lastIndexed . equals ( lastChange ) || lastIndexed . after ( lastChange ) ; } return indexed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the date last indexed [CODESPLIT] public Date getLastIndexed ( ) { Date date = null ; TableMetadataDataSource ds = new TableMetadataDataSource ( db ) ; TableMetadata metadata = ds . get ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) ) ; if ( metadata != null ) { Long lastIndexed = metadata . getLastIndexed ( ) ; if ( lastIndexed != null ) { date = new Date ( lastIndexed ) ; } } return date ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for all Geometry Metadata [CODESPLIT] public Cursor query ( ) { Cursor cursor = geometryMetadataDataSource . query ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) ) ; return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for Geometry Metadata within the bounding box projected correctly [CODESPLIT] public Cursor query ( BoundingBox boundingBox ) { Cursor cursor = geometryMetadataDataSource . query ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) , boundingBox ) ; return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for Geometry Metadata count within the bounding box projected correctly [CODESPLIT] public int count ( BoundingBox boundingBox ) { int count = geometryMetadataDataSource . count ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) , boundingBox ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for Geometry Metadata within the Geometry Envelope [CODESPLIT] public Cursor query ( GeometryEnvelope envelope ) { Cursor cursor = geometryMetadataDataSource . query ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) , envelope ) ; return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for Geometry Metadata count within the Geometry Envelope [CODESPLIT] public int count ( GeometryEnvelope envelope ) { int count = geometryMetadataDataSource . count ( featureDao . getDatabase ( ) , featureDao . getTableName ( ) , envelope ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for Geometry Metadata within the bounding box in the provided projection [CODESPLIT] public Cursor query ( BoundingBox boundingBox , Projection projection ) { BoundingBox featureBoundingBox = getFeatureBoundingBox ( boundingBox , projection ) ; Cursor cursor = query ( featureBoundingBox ) ; return cursor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for Geometry Metadata count within the bounding box in the provided projection [CODESPLIT] public long count ( BoundingBox boundingBox , Projection projection ) { BoundingBox featureBoundingBox = getFeatureBoundingBox ( boundingBox , projection ) ; long count = count ( featureBoundingBox ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the bounding box in the feature projection from the bounding box in the provided projection [CODESPLIT] private BoundingBox getFeatureBoundingBox ( BoundingBox boundingBox , Projection projection ) { ProjectionTransform projectionTransform = projection . getTransformation ( featureDao . getProjection ( ) ) ; BoundingBox featureBoundingBox = boundingBox . transform ( projectionTransform ) ; return featureBoundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Geometry Metadata for the current place in the cursor [CODESPLIT] public GeometryMetadata getGeometryMetadata ( Cursor cursor ) { GeometryMetadata geometryMetadata = GeometryMetadataDataSource . createGeometryMetadata ( cursor ) ; return geometryMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature row for the current place in the cursor [CODESPLIT] public FeatureRow getFeatureRow ( Cursor cursor ) { GeometryMetadata geometryMetadata = getGeometryMetadata ( cursor ) ; FeatureRow featureRow = getFeatureRow ( geometryMetadata ) ; return featureRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the feature row for the Geometry Metadata [CODESPLIT] public FeatureRow getFeatureRow ( GeometryMetadata geometryMetadata ) { long geomId = geometryMetadata . getId ( ) ; // Get the row or lock for reading FeatureRow row = featureRowSync . getRowOrLock ( geomId ) ; if ( row == null ) { // Query for the row and set in the sync try { row = featureDao . queryForIdRow ( geomId ) ; } finally { featureRowSync . setRow ( geomId , row ) ; } } return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for the tile tables linked to a feature table and return tile DAOs to those tables [CODESPLIT] public List < TileDao > getTileDaosForFeatureTable ( String featureTable ) { List < TileDao > tileDaos = new ArrayList < TileDao > ( ) ; List < String > tileTables = getTileTablesForFeatureTable ( featureTable ) ; for ( String tileTable : tileTables ) { if ( geoPackage . isTileTable ( tileTable ) ) { TileDao tileDao = geoPackage . getTileDao ( tileTable ) ; tileDaos . add ( tileDao ) ; } } return tileDaos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query for the feature tables linked to a tile table and return feature DAOs to those tables [CODESPLIT] public List < FeatureDao > getFeatureDaosForTileTable ( String tileTable ) { List < FeatureDao > featureDaos = new ArrayList < FeatureDao > ( ) ; List < String > featureTables = getFeatureTablesForTileTable ( tileTable ) ; for ( String featureTable : featureTables ) { if ( geoPackage . isFeatureTable ( featureTable ) ) { FeatureDao featureDao = geoPackage . getFeatureDao ( featureTable ) ; featureDaos . add ( featureDao ) ; } } return featureDaos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the bounding box for the feature tile generator from the provided and from the feature table [CODESPLIT] private static BoundingBox getBoundingBox ( GeoPackage geoPackage , FeatureTiles featureTiles , BoundingBox boundingBox , Projection projection ) { String tableName = featureTiles . getFeatureDao ( ) . getTableName ( ) ; boolean manualQuery = boundingBox == null ; BoundingBox featureBoundingBox = geoPackage . getBoundingBox ( projection , tableName , manualQuery ) ; if ( featureBoundingBox != null ) { if ( boundingBox == null ) { boundingBox = featureBoundingBox ; } else { boundingBox = boundingBox . overlap ( featureBoundingBox ) ; } } if ( boundingBox != null ) { boundingBox = featureTiles . expandBoundingBox ( boundingBox , projection ) ; } return boundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public BoundingBox getBoundingBox ( int zoom ) { ProjectionTransform projectionToWebMercator = projection . getTransformation ( ProjectionConstants . EPSG_WEB_MERCATOR ) ; BoundingBox webMercatorBoundingBox = boundingBox . transform ( projectionToWebMercator ) ; TileGrid tileGrid = TileBoundingBoxUtils . getTileGrid ( webMercatorBoundingBox , zoom ) ; BoundingBox tileBoundingBox = TileBoundingBoxUtils . getWebMercatorBoundingBox ( tileGrid . getMinX ( ) , tileGrid . getMinY ( ) , zoom ) ; BoundingBox expandedBoundingBox = featureTiles . expandBoundingBox ( webMercatorBoundingBox , tileBoundingBox ) ; BoundingBox zoomBoundingBox = expandedBoundingBox . transform ( projectionToWebMercator . getInverseTransformation ( ) ) ; return zoomBoundingBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void preTileGeneration ( ) { // Link the feature and tile table if they are in the same GeoPackage GeoPackage geoPackage = getGeoPackage ( ) ; String featureTable = featureTiles . getFeatureDao ( ) . getTableName ( ) ; String tileTable = getTableName ( ) ; if ( linkTables && geoPackage . isFeatureTable ( featureTable ) && geoPackage . isTileTable ( tileTable ) ) { FeatureTileTableLinker linker = new FeatureTileTableLinker ( geoPackage ) ; linker . link ( featureTable , tileTable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected byte [ ] createTile ( int z , long x , long y ) { byte [ ] tileData = featureTiles . drawTileBytes ( ( int ) x , ( int ) y , z ) ; return tileData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query by both base id and related id [CODESPLIT] public UserCustomCursor queryByIds ( long baseId , long relatedId ) { return query ( buildWhereIds ( baseId , relatedId ) , buildWhereIdsArgs ( baseId , relatedId ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the unique base ids [CODESPLIT] public List < Long > uniqueBaseIds ( ) { return querySingleColumnTypedResults ( \"SELECT DISTINCT \" + CoreSQLUtils . quoteWrap ( UserMappingTable . COLUMN_BASE_ID ) + \" FROM \" + CoreSQLUtils . quoteWrap ( getTableName ( ) ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the unique related ids [CODESPLIT] public List < Long > uniqueRelatedIds ( ) { return querySingleColumnTypedResults ( \"SELECT DISTINCT \" + CoreSQLUtils . quoteWrap ( UserMappingTable . COLUMN_RELATED_ID ) + \" FROM \" + CoreSQLUtils . quoteWrap ( getTableName ( ) ) , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete user mappings by base id [CODESPLIT] public int deleteByBaseId ( long baseId ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_BASE_ID , baseId ) ) ; String [ ] whereArgs = buildWhereArgs ( new Object [ ] { baseId } ) ; int deleted = delete ( where . toString ( ) , whereArgs ) ; return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete user mappings by related id [CODESPLIT] public int deleteByRelatedId ( long relatedId ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_RELATED_ID , relatedId ) ) ; String [ ] whereArgs = buildWhereArgs ( new Object [ ] { relatedId } ) ; int deleted = delete ( where . toString ( ) , whereArgs ) ; return deleted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete user mappings by both base id and related id [CODESPLIT] public int deleteByIds ( long baseId , long relatedId ) { return delete ( buildWhereIds ( baseId , relatedId ) , buildWhereIdsArgs ( baseId , relatedId ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the where ids clause [CODESPLIT] private String buildWhereIds ( long baseId , long relatedId ) { StringBuilder where = new StringBuilder ( ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_BASE_ID , baseId ) ) ; where . append ( \" AND \" ) ; where . append ( buildWhere ( UserMappingTable . COLUMN_RELATED_ID , relatedId ) ) ; return where . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new GeoPackage metadata [CODESPLIT] public void create ( GeoPackageMetadata metadata ) { ContentValues values = new ContentValues ( ) ; values . put ( GeoPackageMetadata . COLUMN_NAME , metadata . getName ( ) ) ; values . put ( GeoPackageMetadata . COLUMN_EXTERNAL_PATH , metadata . getExternalPath ( ) ) ; long insertId = db . insert ( GeoPackageMetadata . TABLE_NAME , null , values ) ; if ( insertId == - 1 ) { throw new GeoPackageException ( \"Failed to insert GeoPackage metadata. Name: \" + metadata . getName ( ) + \", External Path: \" + metadata . getExternalPath ( ) ) ; } metadata . setId ( insertId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the database [CODESPLIT] public boolean delete ( String database ) { GeoPackageMetadata metadata = get ( database ) ; if ( metadata != null ) { TableMetadataDataSource tableDs = new TableMetadataDataSource ( db ) ; tableDs . delete ( metadata . getId ( ) ) ; } String whereClause = GeoPackageMetadata . COLUMN_NAME + \" = ?\" ; String [ ] whereArgs = new String [ ] { database } ; int deleteCount = db . delete ( GeoPackageMetadata . TABLE_NAME , whereClause , whereArgs ) ; return deleteCount > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename the GeoPackage metadata to the new name [CODESPLIT] public boolean rename ( GeoPackageMetadata metadata , String newName ) { boolean renamed = rename ( metadata . getName ( ) , newName ) ; if ( renamed ) { metadata . setName ( newName ) ; } return renamed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rename the GeoPackage name to the new name [CODESPLIT] public boolean rename ( String name , String newName ) { String whereClause = GeoPackageMetadata . COLUMN_NAME + \" = ?\" ; String [ ] whereArgs = new String [ ] { name } ; ContentValues values = new ContentValues ( ) ; values . put ( GeoPackageMetadata . COLUMN_NAME , newName ) ; int updateCount = db . update ( GeoPackageMetadata . TABLE_NAME , values , whereClause , whereArgs ) ; return updateCount > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all GeoPackage metadata [CODESPLIT] public List < GeoPackageMetadata > getAll ( ) { List < GeoPackageMetadata > allMetadata = new ArrayList < GeoPackageMetadata > ( ) ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , null , null , null , null , null ) ; try { while ( cursor . moveToNext ( ) ) { GeoPackageMetadata metadata = createGeoPackageMetadata ( cursor ) ; allMetadata . add ( metadata ) ; } } finally { cursor . close ( ) ; } return allMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all external GeoPackage metadata [CODESPLIT] public List < GeoPackageMetadata > getAllExternal ( ) { List < GeoPackageMetadata > allMetadata = new ArrayList < GeoPackageMetadata > ( ) ; String selection = GeoPackageMetadata . COLUMN_EXTERNAL_PATH + \" IS NOT NULL\" ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , null , null , null , null ) ; try { while ( cursor . moveToNext ( ) ) { GeoPackageMetadata metadata = createGeoPackageMetadata ( cursor ) ; allMetadata . add ( metadata ) ; } } finally { cursor . close ( ) ; } return allMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get GeoPackage metadata by name [CODESPLIT] public GeoPackageMetadata get ( String database ) { GeoPackageMetadata metadata = null ; String selection = GeoPackageMetadata . COLUMN_NAME + \" = ?\" ; String [ ] selectionArgs = new String [ ] { database } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; try { if ( cursor . moveToNext ( ) ) { metadata = createGeoPackageMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get GeoPackage metadata by id [CODESPLIT] public GeoPackageMetadata get ( long id ) { GeoPackageMetadata metadata = null ; String selection = GeoPackageMetadata . COLUMN_ID + \" = ?\" ; String [ ] selectionArgs = new String [ ] { String . valueOf ( id ) } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; try { if ( cursor . moveToNext ( ) ) { metadata = createGeoPackageMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get GeoPackage metadata or create it if it does not exist [CODESPLIT] public GeoPackageMetadata getOrCreate ( String geoPackage ) { GeoPackageMetadata metadata = get ( geoPackage ) ; if ( metadata == null ) { metadata = new GeoPackageMetadata ( ) ; metadata . setName ( geoPackage ) ; create ( metadata ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the GeoPackage is external [CODESPLIT] public boolean isExternal ( String database ) { GeoPackageMetadata metadata = get ( database ) ; return get ( database ) != null && metadata . getExternalPath ( ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get external GeoPackage metadata by external path [CODESPLIT] public GeoPackageMetadata getExternalAtPath ( String path ) { GeoPackageMetadata metadata = null ; String selection = GeoPackageMetadata . COLUMN_EXTERNAL_PATH + \" = ?\" ; String [ ] selectionArgs = new String [ ] { path } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , GeoPackageMetadata . COLUMNS , selection , selectionArgs , null , null , null ) ; try { if ( cursor . moveToNext ( ) ) { metadata = createGeoPackageMetadata ( cursor ) ; } } finally { cursor . close ( ) ; } return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get metadata where the name is like [CODESPLIT] public List < String > getMetadataWhereNameLike ( String like , String sortColumn ) { return getMetadataWhereNameLike ( like , sortColumn , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get metadata where the name is not like [CODESPLIT] public List < String > getMetadataWhereNameNotLike ( String notLike , String sortColumn ) { return getMetadataWhereNameLike ( notLike , sortColumn , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get metadata where the name is like or not like [CODESPLIT] private List < String > getMetadataWhereNameLike ( String like , String sortColumn , boolean notLike ) { List < String > names = new ArrayList <> ( ) ; StringBuilder where = new StringBuilder ( GeoPackageMetadata . COLUMN_NAME ) ; if ( notLike ) { where . append ( \" not\" ) ; } where . append ( \" like ?\" ) ; String [ ] whereArgs = new String [ ] { like } ; Cursor cursor = db . query ( GeoPackageMetadata . TABLE_NAME , new String [ ] { GeoPackageMetadata . COLUMN_NAME } , where . toString ( ) , whereArgs , null , null , sortColumn ) ; try { while ( cursor . moveToNext ( ) ) { names . add ( cursor . getString ( 0 ) ) ; } } finally { cursor . close ( ) ; } return names ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a GeoPackage metadata from the current cursor location [CODESPLIT] private GeoPackageMetadata createGeoPackageMetadata ( Cursor cursor ) { GeoPackageMetadata metadata = new GeoPackageMetadata ( ) ; metadata . setId ( cursor . getLong ( 0 ) ) ; metadata . setName ( cursor . getString ( 1 ) ) ; metadata . setExternalPath ( cursor . getString ( 2 ) ) ; return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public AttributesRow getRow ( int [ ] columnTypes , Object [ ] values ) { return new AttributesRow ( getTable ( ) , columnTypes , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected UserInvalidCursor < AttributesColumn , AttributesTable , AttributesRow , ? extends UserCursor < AttributesColumn , AttributesTable , AttributesRow > , ? extends UserDao < AttributesColumn , AttributesTable , AttributesRow , ? extends UserCursor < AttributesColumn , AttributesTable , AttributesRow > > > createInvalidCursor ( UserDao dao , UserCursor cursor , List < Integer > invalidPositions , List < AttributesColumn > blobColumns ) { return new AttributesInvalidCursor ( ( AttributesDao ) dao , ( AttributesCursor ) cursor , invalidPositions , blobColumns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Iterator < FeatureRow > iterator ( ) { return new Iterator < FeatureRow > ( ) { /**\n             * {@inheritDoc}\n             */ @ Override public boolean hasNext ( ) { return geometryIndices . hasNext ( ) ; } /**\n             * {@inheritDoc}\n             */ @ Override public FeatureRow next ( ) { GeometryIndex geometryIndex = geometryIndices . next ( ) ; FeatureRow featureRow = featureTableIndex . getFeatureRow ( geometryIndex ) ; return featureRow ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Iterable < Long > ids ( ) { return new Iterable < Long > ( ) { /**\n             * {@inheritDoc}\n             */ @ Override public Iterator < Long > iterator ( ) { return featureIds . iterator ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle the created view [CODESPLIT] public View onViewCreated ( View view , Context context , AttributeSet attrs ) { if ( view == null ) { return null ; } view = onViewCreatedInternal ( view , context , attrs ) ; for ( OnViewCreatedListener listener : otherListeners ) { if ( listener != null ) { view = listener . onViewCreated ( view , context , attrs ) ; } } return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the { @link ViewPager . OnPageChangeListener } to the embedded { @link ViewPager } created by the container . [CODESPLIT] @ Deprecated protected void attachOnPageChangeListener ( ViewPager viewPager , ViewPager . OnPageChangeListener listener ) { viewPager . setOnPageChangeListener ( listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attach attributes in tag [CODESPLIT] private void addParallaxView ( View view , int pageIndex ) { if ( view instanceof ViewGroup ) { // recurse children ViewGroup viewGroup = ( ViewGroup ) view ; for ( int i = 0 , childCount = viewGroup . getChildCount ( ) ; i < childCount ; i ++ ) { addParallaxView ( viewGroup . getChildAt ( i ) , pageIndex ) ; } } ParallaxViewTag tag = ( ParallaxViewTag ) view . getTag ( R . id . parallax_view_tag ) ; if ( tag != null ) { // only track view if it has a parallax tag tag . index = pageIndex ; parallaxViews . add ( view ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The LayoutInflater onCreateView is the fourth port of call for LayoutInflation . BUT only for none CustomViews . Basically if this method doesn t inflate the View nothing probably will . [CODESPLIT] @ Override protected View onCreateView ( String name , AttributeSet attrs ) throws ClassNotFoundException { // This mimics the {@code PhoneLayoutInflater} in the way it tries to inflate the base // classes, if this fails its pretty certain the app will fail at this point. View view = null ; for ( String prefix : sClassPrefixList ) { try { view = createView ( name , prefix , attrs ) ; } catch ( ClassNotFoundException ignored ) { } } // In this case we want to let the base class take a crack // at it. if ( view == null ) { view = super . onCreateView ( name , attrs ) ; } return mParallaxFactory . onViewCreated ( view , view . getContext ( ) , attrs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Nasty method to inflate custom layouts that haven t been handled else where . If this fails it will fall back through to the PhoneLayoutInflater method of inflating custom views where Calligraphy will NOT have a hook into . [CODESPLIT] private View createCustomViewInternal ( View parent , View view , String name , Context context , AttributeSet attrs ) { // I by no means advise anyone to do this normally, but Google have locked down access to // the createView() method, so we never get a callback with attributes at the end of the // createViewFromTag chain (which would solve all this unnecessary rubbish). // We at the very least try to optimise this as much as possible. // We only call for customViews (As they are the ones that never go through onCreateView(...)). // We also maintain the Field reference and make it accessible which will make a pretty // significant difference to performance on Android 4.0+. // If CustomViewCreation is off skip this. if ( view == null && name . indexOf ( ' ' ) > - 1 ) { if ( mConstructorArgs == null ) { mConstructorArgs = ReflectionUtils . getField ( LayoutInflater . class , \"mConstructorArgs\" ) ; } final Object [ ] mConstructorArgsArr = ( Object [ ] ) ReflectionUtils . getValue ( mConstructorArgs , this ) ; final Object lastContext = mConstructorArgsArr [ 0 ] ; mConstructorArgsArr [ 0 ] = parent != null ? parent . getContext ( ) : context ; ReflectionUtils . setValue ( mConstructorArgs , this , mConstructorArgsArr ) ; try { view = createView ( name , null , attrs ) ; } catch ( ClassNotFoundException ignored ) { } finally { mConstructorArgsArr [ 0 ] = lastContext ; ReflectionUtils . setValue ( mConstructorArgs , this , mConstructorArgsArr ) ; } } return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_parallax ) ; if ( savedInstanceState == null ) { getSupportFragmentManager ( ) . beginTransaction ( ) . add ( R . id . content , new ParallaxFragment ( ) ) . commit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Convert a level to equivalent syslog severity . Only levels for printing methods i . e TRACE DEBUG WARN INFO and ERROR are converted . [CODESPLIT] static public int convert ( ILoggingEvent event ) { Level level = event . getLevel ( ) ; switch ( level . levelInt ) { case Level . ERROR_INT : return SyslogConstants . ERROR_SEVERITY ; case Level . WARN_INT : return SyslogConstants . WARNING_SEVERITY ; case Level . INFO_INT : return SyslogConstants . INFO_SEVERITY ; case Level . DEBUG_INT : case Level . TRACE_INT : return SyslogConstants . DEBUG_SEVERITY ; default : throw new IllegalArgumentException ( \"Level \" + level + \" is not a valid level for a printing method\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @link ch . qos . logback . core . net . AutoFlushingObjectWriter } instance . [CODESPLIT] public AutoFlushingObjectWriter newAutoFlushingObjectWriter ( OutputStream outputStream ) throws IOException { return new AutoFlushingObjectWriter ( new ObjectOutputStream ( outputStream ) , CoreConstants . OOS_RESET_FREQUENCY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform SMTPAppender specific appending actions mainly adding the event to a cyclic buffer . [CODESPLIT] protected void subAppend ( CyclicBuffer < ILoggingEvent > cb , ILoggingEvent event ) { if ( includeCallerData ) { event . getCallerData ( ) ; } event . prepareForDeferredProcessing ( ) ; cb . add ( event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a configuration file by system property [CODESPLIT] private URL findConfigFileFromSystemProperties ( boolean updateStatus ) { String logbackConfigFile = OptionHelper . getSystemProperty ( CONFIG_FILE_PROPERTY ) ; if ( logbackConfigFile != null ) { URL result = null ; try { File file = new File ( logbackConfigFile ) ; if ( file . exists ( ) && file . isFile ( ) ) { if ( updateStatus ) { statusOnResourceSearch ( logbackConfigFile , this . classLoader , logbackConfigFile ) ; } result = file . toURI ( ) . toURL ( ) ; } else { result = new URL ( logbackConfigFile ) ; } return result ; } catch ( MalformedURLException e ) { // so, resource is not a URL: // attempt to get the resource from the class path result = Loader . getResource ( logbackConfigFile , this . classLoader ) ; if ( result != null ) { return result ; } } finally { if ( updateStatus ) { statusOnResourceSearch ( logbackConfigFile , this . classLoader , result != null ? result . toString ( ) : null ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the given classloader to search for a resource [CODESPLIT] private URL getResource ( String filename , ClassLoader myClassLoader , boolean updateStatus ) { URL url = myClassLoader . getResource ( filename ) ; if ( updateStatus ) { String resourcePath = null ; if ( url != null ) { resourcePath = filename ; } statusOnResourceSearch ( filename , myClassLoader , resourcePath ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures logback with the first configuration found in the following search path . If no configuration found nothing is done and logging is disabled . [CODESPLIT] public void autoConfig ( ) throws JoranException { StatusListenerConfigHelper . installIfAsked ( loggerContext ) ; new AndroidContextUtil ( ) . setupProperties ( loggerContext ) ; boolean verbose = true ; boolean configured = false ; JoranConfigurator configurator = new JoranConfigurator ( ) ; configurator . setContext ( loggerContext ) ; // search system property if ( ! configured ) { URL url = findConfigFileFromSystemProperties ( verbose ) ; if ( url != null ) { configurator . doConfigure ( url ) ; configured = true ; } } // search assets if ( ! configured ) { URL assetsConfigUrl = findConfigFileURLFromAssets ( verbose ) ; if ( assetsConfigUrl != null ) { configurator . doConfigure ( assetsConfigUrl ) ; configured = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a status message for the result of the resource search [CODESPLIT] private void statusOnResourceSearch ( String resourceName , ClassLoader classLoader , String path ) { StatusManager sm = loggerContext . getStatusManager ( ) ; if ( path == null ) { sm . add ( new InfoStatus ( \"Could NOT find resource [\" + resourceName + \"]\" , loggerContext ) ) ; } else { sm . add ( new InfoStatus ( \"Found resource [\" + resourceName + \"] at [\" + path + \"]\" , loggerContext ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public T acceptClient ( ) throws IOException { Socket socket = serverSocket . accept ( ) ; return createClient ( socketAddressToString ( socket . getRemoteSocketAddress ( ) ) , socket ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a socket address to a reasonable display string . [CODESPLIT] private String socketAddressToString ( SocketAddress address ) { String addr = address . toString ( ) ; int i = addr . indexOf ( \"/\" ) ; if ( i >= 0 ) { addr = addr . substring ( i + 1 ) ; } return addr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an executor service suitable for use by logback components . [CODESPLIT] static public ExecutorService newExecutorService ( ) { return new ThreadPoolExecutor ( CoreConstants . CORE_POOL_SIZE , CoreConstants . MAX_POOL_SIZE , 0L , TimeUnit . MILLISECONDS , new SynchronousQueue < Runnable > ( ) , THREAD_FACTORY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start converters in the chain of converters . [CODESPLIT] public static < E > void startConverters ( Converter < E > head ) { Converter < E > c = head ; while ( c != null ) { // CompositeConverter is a subclass of  DynamicConverter if ( c instanceof CompositeConverter ) { CompositeConverter < E > cc = ( CompositeConverter < E > ) c ; Converter < E > childConverter = cc . childConverter ; startConverters ( childConverter ) ; cc . start ( ) ; } else if ( c instanceof DynamicConverter ) { DynamicConverter < E > dc = ( DynamicConverter < E > ) c ; dc . start ( ) ; } c = c . getNext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method differentiates RollingFileAppender from its super class . [CODESPLIT] @ Override protected void subAppend ( E event ) { // The roll-over check must precede actual writing. This is the // only correct behavior for time driven triggers. // We need to synchronize on triggeringPolicy so that only one rollover // occurs at a time synchronized ( triggeringPolicy ) { if ( triggeringPolicy . isTriggeringEvent ( currentlyActiveFile , event ) ) { rollover ( ) ; } } super . subAppend ( event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the rolling policy . In case the policy argument also implements { @link TriggeringPolicy } then the triggering policy for this appender is automatically set to be the policy argument . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void setRollingPolicy ( RollingPolicy policy ) { rollingPolicy = policy ; if ( rollingPolicy instanceof TriggeringPolicy ) { triggeringPolicy = ( TriggeringPolicy < E > ) policy ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a property to the properties of this execution context . If the property exists already it is overwritten . [CODESPLIT] public void addSubstitutionProperty ( String key , String value ) { if ( key == null || value == null ) { return ; } // values with leading or trailing spaces are bad. We remove them now. value = value . trim ( ) ; propertiesMap . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a key is found in propertiesMap then return it . Otherwise delegate to the context . [CODESPLIT] public String getProperty ( String key ) { String v = propertiesMap . get ( key ) ; if ( v != null ) { return v ; } else { return context . getProperty ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected ServerSocketFactory getServerSocketFactory ( ) throws Exception { if ( socketFactory == null ) { SSLContext sslContext = getSsl ( ) . createContext ( this ) ; SSLParametersConfiguration parameters = getSsl ( ) . getParameters ( ) ; parameters . setContext ( getContext ( ) ) ; socketFactory = new ConfigurableSSLServerSocketFactory ( parameters , sslContext . getServerSocketFactory ( ) ) ; } return socketFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method takes a string which may contain HTML tags ( ie &lt ; b&gt ; &lt ; table&gt ; etc ) and replaces any &lt ; &gt ; ... characters with respective predefined entity references . [CODESPLIT] public static String escapeTags ( final String input ) { if ( input == null || input . length ( ) == 0 || ! UNSAFE_XML_CHARS . matcher ( input ) . find ( ) ) { return input ; } StringBuffer buf = new StringBuffer ( input ) ; return escapeTags ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method takes a StringBuilder which may contain HTML tags ( ie &lt ; b&gt ; &lt ; table&gt ; etc ) and replaces any &lt ; and &gt ; characters with respective predefined entity references . [CODESPLIT] public static String escapeTags ( final StringBuffer buf ) { for ( int i = 0 ; i < buf . length ( ) ; i ++ ) { char ch = buf . charAt ( i ) ; switch ( ch ) { case ' ' : case ' ' : case ' ' : // These characters are below '\\u0020' but are allowed: break ; case ' ' : buf . replace ( i , i + 1 , \"&amp;\" ) ; break ; case ' ' : buf . replace ( i , i + 1 , \"&lt;\" ) ; break ; case ' ' : buf . replace ( i , i + 1 , \"&gt;\" ) ; break ; case ' ' : buf . replace ( i , i + 1 , \"&quot;\" ) ; break ; case ' ' : buf . replace ( i , i + 1 , \"&#39;\" ) ; break ; default : if ( ch < ' ' ) { // These characters are not allowed, // replace them with \"Object replacement character\": buf . replace ( i , i + 1 , \"\\uFFFD\" ) ; } break ; } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that embedded CDEnd strings ( ]] &gt ; ) are handled properly within message NDC and throwable tag text . [CODESPLIT] public static void appendEscapingCDATA ( StringBuilder output , String str ) { if ( str == null ) { return ; } int end = str . indexOf ( CDATA_END ) ; if ( end < 0 ) { output . append ( str ) ; return ; } int start = 0 ; while ( end > - 1 ) { output . append ( str . substring ( start , end ) ) ; output . append ( CDATA_EMBEDED_END ) ; start = end + CDATA_END_LEN ; if ( start < str . length ( ) ) { end = str . indexOf ( CDATA_END , start ) ; } else { return ; } } output . append ( str . substring ( start ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retains all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > This method is a convenience overload for { @link #retainMatching ( Collection Collection ) } . [CODESPLIT] public static void retainMatching ( Collection < String > values , String ... patterns ) { retainMatching ( values , Arrays . asList ( patterns ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retains all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > The semantics of this method are conceptually similar to { @link Collection#retainAll ( Collection ) } but uses pattern matching instead of exact matching . [CODESPLIT] public static void retainMatching ( Collection < String > values , Collection < String > patterns ) { if ( patterns . isEmpty ( ) ) return ; List < String > matches = new ArrayList < String > ( values . size ( ) ) ; for ( String p : patterns ) { Pattern pattern = Pattern . compile ( p ) ; for ( String value : values ) { if ( pattern . matcher ( value ) . matches ( ) ) { matches . add ( value ) ; } } } values . retainAll ( matches ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > This method is a convenience overload for { @link #removeMatching ( Collection Collection ) } . [CODESPLIT] public static void removeMatching ( Collection < String > values , String ... patterns ) { removeMatching ( values , Arrays . asList ( patterns ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all values in the subject collection that are matched by at least one of a collection of regular expressions . <p > The semantics of this method are conceptually similar to { @link Collection#removeAll ( Collection ) } but uses pattern matching instead of exact matching . [CODESPLIT] public static void removeMatching ( Collection < String > values , Collection < String > patterns ) { List < String > matches = new ArrayList < String > ( values . size ( ) ) ; for ( String p : patterns ) { Pattern pattern = Pattern . compile ( p ) ; for ( String value : values ) { if ( pattern . matcher ( value ) . matches ( ) ) { matches . add ( value ) ; } } } values . removeAll ( matches ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "big - endian [CODESPLIT] static void writeInt ( byte [ ] byteArray , int offset , int i ) { for ( int j = 0 ; j < 4 ; j ++ ) { int shift = 24 - j * 8 ; byteArray [ offset + j ] = ( byte ) ( i >>> shift ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "big - endian [CODESPLIT] static int readInt ( byte [ ] byteArray , int offset ) { int i = 0 ; for ( int j = 0 ; j < 4 ; j ++ ) { int shift = 24 - j * 8 ; i += ( byteArray [ offset + j ] & 0xFF ) << shift ; } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When the parsing step is done the Node list can be transformed into a converter chain . [CODESPLIT] public Converter < E > compile ( final Node top , Map < String , String > converterMap ) { Compiler < E > compiler = new Compiler < E > ( top , converterMap ) ; compiler . setContext ( context ) ; //compiler.setStatusManager(statusManager); return compiler . compile ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "E = TEopt [CODESPLIT] Node E ( ) throws ScanException { Node t = T ( ) ; if ( t == null ) { return null ; } Node eOpt = Eopt ( ) ; if ( eOpt != null ) { t . setNext ( eOpt ) ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Eopt = E|~ [CODESPLIT] Node Eopt ( ) throws ScanException { // System.out.println(\"in Eopt()\"); Token next = getCurentToken ( ) ; // System.out.println(\"Current token is \" + next); if ( next == null ) { return null ; } else { return E ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "T = LITERAL | % C | % FORMAT_MODIFIER C [CODESPLIT] Node T ( ) throws ScanException { Token t = getCurentToken ( ) ; expectNotNull ( t , \"a LITERAL or '%'\" ) ; switch ( t . getType ( ) ) { case Token . LITERAL : advanceTokenPointer ( ) ; return new Node ( Node . LITERAL , t . getValue ( ) ) ; case Token . PERCENT : advanceTokenPointer ( ) ; // System.out.println(\"% token found\"); FormatInfo fi ; Token u = getCurentToken ( ) ; FormattingNode c ; expectNotNull ( u , \"a FORMAT_MODIFIER, SIMPLE_KEYWORD or COMPOUND_KEYWORD\" ) ; if ( u . getType ( ) == Token . FORMAT_MODIFIER ) { fi = FormatInfo . valueOf ( ( String ) u . getValue ( ) ) ; advanceTokenPointer ( ) ; c = C ( ) ; c . setFormatInfo ( fi ) ; } else { c = C ( ) ; } return c ; default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a { [CODESPLIT] public String doLayout ( ILoggingEvent event ) { // Reset working buffer. If the buffer is too large, then we need a new // one in order to avoid the penalty of creating a large array. if ( buf . capacity ( ) > UPPER_LIMIT ) { buf = new StringBuilder ( DEFAULT_SIZE ) ; } else { buf . setLength ( 0 ) ; } // We yield to the \\r\\n heresy. buf . append ( \"<log4j:event logger=\\\"\" ) ; buf . append ( Transform . escapeTags ( event . getLoggerName ( ) ) ) ; buf . append ( \"\\\"\\r\\n\" ) ; buf . append ( \"             timestamp=\\\"\" ) ; buf . append ( event . getTimeStamp ( ) ) ; buf . append ( \"\\\" level=\\\"\" ) ; buf . append ( event . getLevel ( ) ) ; buf . append ( \"\\\" thread=\\\"\" ) ; buf . append ( Transform . escapeTags ( event . getThreadName ( ) ) ) ; buf . append ( \"\\\">\\r\\n\" ) ; buf . append ( \"  <log4j:message>\" ) ; buf . append ( Transform . escapeTags ( event . getFormattedMessage ( ) ) ) ; buf . append ( \"</log4j:message>\\r\\n\" ) ; // logback does not support NDC // String ndc = event.getNDC(); IThrowableProxy tp = event . getThrowableProxy ( ) ; if ( tp != null ) { StackTraceElementProxy [ ] stepArray = tp . getStackTraceElementProxyArray ( ) ; buf . append ( \"  <log4j:throwable><![CDATA[\" ) ; for ( StackTraceElementProxy step : stepArray ) { buf . append ( CoreConstants . TAB ) ; buf . append ( step . toString ( ) ) ; buf . append ( \"\\r\\n\" ) ; } buf . append ( \"]]></log4j:throwable>\\r\\n\" ) ; } if ( locationInfo ) { StackTraceElement [ ] callerDataArray = event . getCallerData ( ) ; if ( callerDataArray != null && callerDataArray . length > 0 ) { StackTraceElement immediateCallerData = callerDataArray [ 0 ] ; buf . append ( \"  <log4j:locationInfo class=\\\"\" ) ; buf . append ( immediateCallerData . getClassName ( ) ) ; buf . append ( \"\\\"\\r\\n\" ) ; buf . append ( \"                      method=\\\"\" ) ; buf . append ( Transform . escapeTags ( immediateCallerData . getMethodName ( ) ) ) ; buf . append ( \"\\\" file=\\\"\" ) ; buf . append ( Transform . escapeTags ( immediateCallerData . getFileName ( ) ) ) ; buf . append ( \"\\\" line=\\\"\" ) ; buf . append ( immediateCallerData . getLineNumber ( ) ) ; buf . append ( \"\\\"/>\\r\\n\" ) ; } } /*\n     * <log4j:properties> <log4j:data name=\"name\" value=\"value\"/>\n     * </log4j:properties>\n     */ if ( this . getProperties ( ) ) { Map < String , String > propertyMap = event . getMDCPropertyMap ( ) ; if ( ( propertyMap != null ) && ( propertyMap . size ( ) != 0 ) ) { Set < Entry < String , String > > entrySet = propertyMap . entrySet ( ) ; buf . append ( \"  <log4j:properties>\" ) ; for ( Entry < String , String > entry : entrySet ) { buf . append ( \"\\r\\n    <log4j:data\" ) ; buf . append ( \" name=\\\"\" + Transform . escapeTags ( entry . getKey ( ) ) + \"\\\"\" ) ; buf . append ( \" value=\\\"\" + Transform . escapeTags ( entry . getValue ( ) ) + \"\\\"\" ) ; buf . append ( \" />\" ) ; } buf . append ( \"\\r\\n  </log4j:properties>\" ) ; } } buf . append ( \"\\r\\n</log4j:event>\\r\\n\\r\\n\" ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do not perform any character escaping except for % and ) . [CODESPLIT] public void escape ( String escapeChars , StringBuffer buf , char next , int pointer ) { super . escape ( \"\" + CoreConstants . PERCENT_CHAR + CoreConstants . RIGHT_PARENTHESIS_CHAR , buf , next , pointer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given date convert this instance to a regular expression . [CODESPLIT] public String toRegexForFixedDate ( Date date ) { StringBuilder buf = new StringBuilder ( ) ; Converter < Object > p = headTokenConverter ; while ( p != null ) { if ( p instanceof LiteralConverter ) { buf . append ( p . convert ( null ) ) ; } else if ( p instanceof IntegerTokenConverter ) { buf . append ( FileFinder . regexEscapePath ( \"(\\\\d+)\" ) ) ; } else if ( p instanceof DateTokenConverter ) { DateTokenConverter < Object > dtc = ( DateTokenConverter < Object > ) p ; if ( dtc . isPrimary ( ) ) { buf . append ( p . convert ( date ) ) ; } else { buf . append ( FileFinder . regexEscapePath ( dtc . toRegex ( ) ) ) ; } } p = p . getNext ( ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public ServerSocket createServerSocket ( int port , int backlog ) throws IOException { SSLServerSocket socket = ( SSLServerSocket ) delegate . createServerSocket ( port , backlog ) ; parameters . configure ( new SSLConfigurableServerSocket ( socket ) ) ; return socket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates an evaluator of the given class and sets its name . [CODESPLIT] public void begin ( InterpretationContext ec , String name , Attributes attributes ) { // Let us forget about previous errors (in this instance) inError = false ; evaluator = null ; String className = attributes . getValue ( CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( className ) ) { className = defaultClassName ( ) ; addInfo ( \"Assuming default evaluator class [\" + className + \"]\" ) ; } if ( OptionHelper . isEmpty ( className ) ) { className = defaultClassName ( ) ; inError = true ; addError ( \"Mandatory \\\"\" + CLASS_ATTRIBUTE + \"\\\" attribute not set for <evaluator>\" ) ; return ; } String evaluatorName = attributes . getValue ( Action . NAME_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( evaluatorName ) ) { inError = true ; addError ( \"Mandatory \\\"\" + NAME_ATTRIBUTE + \"\\\" attribute not set for <evaluator>\" ) ; return ; } try { evaluator = ( EventEvaluator < ? > ) OptionHelper . instantiateByClassName ( className , ch . qos . logback . core . boolex . EventEvaluator . class , context ) ; evaluator . setContext ( this . context ) ; evaluator . setName ( evaluatorName ) ; ec . pushObject ( evaluator ) ; addInfo ( \"Adding evaluator named [\" + evaluatorName + \"] to the object stack\" ) ; } catch ( Exception oops ) { inError = true ; addError ( \"Could not create evaluator of type \" + className + \"].\" , oops ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Once the children elements are also parsed now is the time to activate the evaluator options . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void end ( InterpretationContext ec , String e ) { if ( inError ) { return ; } if ( evaluator instanceof LifeCycle ) { ( ( LifeCycle ) evaluator ) . start ( ) ; addInfo ( \"Starting evaluator named [\" + evaluator . getName ( ) + \"]\" ) ; } Object o = ec . peekObject ( ) ; if ( o != evaluator ) { addWarn ( \"The object on the top the of the stack is not the evaluator pushed earlier.\" ) ; } else { ec . popObject ( ) ; try { Map < String , EventEvaluator < ? > > evaluatorMap = ( Map < String , EventEvaluator < ? > > ) context . getObject ( CoreConstants . EVALUATOR_MAP ) ; if ( evaluatorMap == null ) { addError ( \"Could not find EvaluatorMap\" ) ; } else { evaluatorMap . put ( evaluator . getName ( ) , evaluator ) ; } } catch ( Exception ex ) { addError ( \"Could not set evaluator named [\" + evaluator + \"].\" , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FOR INTERNAL USE . This method is intended for use by StaticLoggerBinder . [CODESPLIT] public void init ( LoggerContext defaultLoggerContext , Object key ) throws ClassNotFoundException , NoSuchMethodException , InstantiationException , IllegalAccessException , InvocationTargetException { if ( this . key == null ) { this . key = key ; } else if ( this . key != key ) { throw new IllegalAccessException ( \"Only certain classes can access this method.\" ) ; } String contextSelectorStr = OptionHelper . getSystemProperty ( ClassicConstants . LOGBACK_CONTEXT_SELECTOR ) ; if ( contextSelectorStr == null ) { contextSelector = new DefaultContextSelector ( defaultLoggerContext ) ; } else if ( contextSelectorStr . equals ( \"JNDI\" ) ) { throw new RuntimeException ( \"JNDI not supported\" ) ; } else { contextSelector = dynamicalContextSelector ( defaultLoggerContext , contextSelectorStr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiate the context selector class designated by the user . The selector must have a constructor taking a LoggerContext instance as an argument . [CODESPLIT] static ContextSelector dynamicalContextSelector ( LoggerContext defaultLoggerContext , String contextSelectorStr ) throws ClassNotFoundException , SecurityException , NoSuchMethodException , IllegalArgumentException , InstantiationException , IllegalAccessException , InvocationTargetException { Class < ? > contextSelectorClass = Loader . loadClass ( contextSelectorStr ) ; Constructor cons = contextSelectorClass . getConstructor ( new Class [ ] { LoggerContext . class } ) ; return ( ContextSelector ) cons . newInstance ( defaultLoggerContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets properties for use in configs [CODESPLIT] public void setupProperties ( LoggerContext context ) { // legacy properties Properties props = new Properties ( ) ; props . setProperty ( CoreConstants . DATA_DIR_KEY , getFilesDirectoryPath ( ) ) ; final String extDir = getMountedExternalStorageDirectoryPath ( ) ; if ( extDir != null ) { props . setProperty ( CoreConstants . EXT_DIR_KEY , extDir ) ; } props . setProperty ( CoreConstants . PACKAGE_NAME_KEY , getPackageName ( ) ) ; props . setProperty ( CoreConstants . VERSION_CODE_KEY , getVersionCode ( ) ) ; props . setProperty ( CoreConstants . VERSION_NAME_KEY , getVersionName ( ) ) ; context . putProperties ( props ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the path to the external storage directory only if mounted . [CODESPLIT] public String getMountedExternalStorageDirectoryPath ( ) { String path = null ; String state = Environment . getExternalStorageState ( ) ; if ( state . equals ( Environment . MEDIA_MOUNTED ) || state . equals ( Environment . MEDIA_MOUNTED_READ_ONLY ) ) { path = absPath ( Environment . getExternalStorageDirectory ( ) ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute path to the directory on the Android filesystem similar to { @link #getFilesDirectoryPath () } . The difference is these files are excluded from automatic backup to remote storage by { @code android . app . backup . BackupAgent } . This API is only available on SDK 21 + . On older versions this function returns an empty string . [CODESPLIT] @ TargetApi ( 21 ) public String getNoBackupFilesDirectoryPath ( ) { return Build . VERSION . SDK_INT >= 21 && this . context != null ? absPath ( this . context . getNoBackupFilesDir ( ) ) : \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute path to the directory on the Android filesystem where databases are stored for the current application . [CODESPLIT] public String getDatabaseDirectoryPath ( ) { return this . context != null && this . context . getDatabasePath ( \"x\" ) != null ? this . context . getDatabasePath ( \"x\" ) . getParent ( ) : \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The <b > File< / b > property takes a string value which should be the name of the file to append to . [CODESPLIT] public void setFile ( String file ) { if ( file == null ) { fileName = null ; } else { // Trim spaces from both ends. The users probably does not want // trailing spaces in file names. fileName = file . trim ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the value of <b > File< / b > is not <code > null< / code > then { [CODESPLIT] public void start ( ) { int errors = 0 ; // Use getFile() instead of direct access to fileName because // the function is overridden in RollingFileAppender, which // returns a value that doesn't necessarily match fileName. String file = getFile ( ) ; if ( file != null ) { file = getAbsoluteFilePath ( file ) ; addInfo ( \"File property is set to [\" + file + \"]\" ) ; if ( prudent ) { if ( ! isAppend ( ) ) { setAppend ( true ) ; addWarn ( \"Setting \\\"Append\\\" property to true on account of \\\"Prudent\\\" mode\" ) ; } } if ( ! lazyInit ) { if ( checkForFileCollisionInPreviousFileAppenders ( ) ) { addError ( \"Collisions detected with FileAppender/RollingAppender instances defined earlier. Aborting.\" ) ; addError ( COLLISION_WITH_EARLIER_APPENDER_URL ) ; errors ++ ; } else { // file should be opened only if collision free try { openFile ( file ) ; } catch ( IOException e ) { errors ++ ; addError ( \"openFile(\" + file + \",\" + append + \") failed\" , e ) ; } } } else { // We'll initialize the file output stream later. Use a dummy for now // to satisfy OutputStreamAppender.start(). setOutputStream ( new NOPOutputStream ( ) ) ; } } else { errors ++ ; addError ( \"\\\"File\\\" property not set for appender named [\" + name + \"]\" ) ; } if ( errors == 0 ) { super . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets and <i > opens< / i > the file where the log output will go . The specified file must be writable . [CODESPLIT] protected boolean openFile ( String filename ) throws IOException { boolean successful = false ; filename = getAbsoluteFilePath ( filename ) ; lock . lock ( ) ; try { File file = new File ( filename ) ; boolean result = FileUtil . createMissingParentDirectories ( file ) ; if ( ! result ) { addError ( \"Failed to create parent directories for [\" + file . getAbsolutePath ( ) + \"]\" ) ; } ResilientFileOutputStream resilientFos = new ResilientFileOutputStream ( file , append , bufferSize . getSize ( ) ) ; resilientFos . setContext ( context ) ; setOutputStream ( resilientFos ) ; successful = true ; } finally { lock . unlock ( ) ; } return successful ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the absolute path to the filename starting from the app s files directory if it is not already an absolute path [CODESPLIT] private String getAbsoluteFilePath ( String filename ) { // In Android, relative paths created with File() are relative // to root, so fix it by prefixing the path to the app's \"files\" // directory. // This transformation is rather expensive, since it involves loading the // Android manifest from the APK (which is a ZIP file), and parsing it to // retrieve the application package name. This should be avoided if // possible as it may perceptibly delay the app launch time. if ( EnvUtil . isAndroidOS ( ) && ! new File ( filename ) . isAbsolute ( ) ) { String dataDir = context . getProperty ( CoreConstants . DATA_DIR_KEY ) ; filename = FileUtil . prefixRelativePath ( dataDir , filename ) ; } return filename ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if event passed as parameter has level ERROR or higher returns false otherwise . [CODESPLIT] public boolean evaluate ( ILoggingEvent event ) throws NullPointerException , EvaluationException { return event . getLevel ( ) . levelInt >= Level . ERROR_INT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value associated with an MDC entry designated by the Key property . If that value is null then return the value assigned to the DefaultValue property . [CODESPLIT] public String getDiscriminatingValue ( ILoggingEvent event ) { // http://jira.qos.ch/browse/LBCLASSIC-213 Map < String , String > mdcMap = event . getMDCPropertyMap ( ) ; if ( mdcMap == null ) { return defaultValue ; } String mdcValue = mdcMap . get ( key ) ; if ( mdcValue == null ) { return defaultValue ; } else { return mdcValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "update the mask so as to execute change detection code about once every 100 to 8000 milliseconds . [CODESPLIT] private void updateMaskIfNecessary ( long now ) { final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck ; lastMaskCheck = now ; if ( timeElapsedSinceLastMaskUpdateCheck < MASK_INCREASE_THRESHOLD && ( mask < MAX_MASK ) ) { mask = ( mask << 1 ) | 1 ; } else if ( timeElapsedSinceLastMaskUpdateCheck > MASK_DECREASE_THRESHOLD ) { mask = mask >>> 2 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loop through the filters in the list . As soon as a filter decides on ACCEPT or DENY then that value is returned . If all of the filters return NEUTRAL then NEUTRAL is returned . [CODESPLIT] public FilterReply getFilterChainDecision ( E event ) { final Filter < E > [ ] filterArrray = filterList . asTypedArray ( ) ; final int len = filterArrray . length ; for ( int i = 0 ; i < len ; i ++ ) { final FilterReply r = filterArrray [ i ] . decide ( event ) ; if ( r == FilterReply . DENY || r == FilterReply . ACCEPT ) { return r ; } } // no decision return FilterReply . NEUTRAL ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void run ( ) { addInfo ( clientId + \"connected\" ) ; ObjectOutputStream oos = null ; try { int counter = 0 ; oos = createObjectOutputStream ( ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { try { Serializable event = queue . take ( ) ; oos . writeObject ( event ) ; oos . flush ( ) ; if ( ++ counter >= CoreConstants . OOS_RESET_FREQUENCY ) { // failing to reset the stream periodically will result in a // serious memory leak (as noted in AbstractSocketAppender) counter = 0 ; oos . reset ( ) ; } } catch ( InterruptedException ex ) { Thread . currentThread ( ) . interrupt ( ) ; } } } catch ( SocketException ex ) { addInfo ( clientId + ex ) ; } catch ( IOException ex ) { addError ( clientId + ex ) ; } catch ( RuntimeException ex ) { addError ( clientId + ex ) ; } finally { if ( oos != null ) { CloseUtil . closeQuietly ( oos ) ; } close ( ) ; addInfo ( clientId + \"connection closed\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { [CODESPLIT] public SecureRandom createSecureRandom ( ) throws NoSuchProviderException , NoSuchAlgorithmException { try { return getProvider ( ) != null ? SecureRandom . getInstance ( getAlgorithm ( ) , getProvider ( ) ) : SecureRandom . getInstance ( getAlgorithm ( ) ) ; } catch ( NoSuchProviderException ex ) { throw new NoSuchProviderException ( \"no such secure random provider: \" + getProvider ( ) ) ; } catch ( NoSuchAlgorithmException ex ) { throw new NoSuchAlgorithmException ( \"no such secure random algorithm: \" + getAlgorithm ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates an layout of the given class and sets its name . [CODESPLIT] public void begin ( InterpretationContext ec , String localName , Attributes attributes ) { // Let us forget about previous errors (in this object) inError = false ; String errorMsg ; String pattern = attributes . getValue ( Action . PATTERN_ATTRIBUTE ) ; String actionClass = attributes . getValue ( Action . ACTION_CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( pattern ) ) { inError = true ; errorMsg = \"No 'pattern' attribute in <newRule>\" ; addError ( errorMsg ) ; return ; } if ( OptionHelper . isEmpty ( actionClass ) ) { inError = true ; errorMsg = \"No 'actionClass' attribute in <newRule>\" ; addError ( errorMsg ) ; return ; } try { addInfo ( \"About to add new Joran parsing rule [\" + pattern + \",\" + actionClass + \"].\" ) ; ec . getJoranInterpreter ( ) . getRuleStore ( ) . addRule ( new ElementSelector ( pattern ) , actionClass ) ; } catch ( Exception oops ) { inError = true ; errorMsg = \"Could not add new Joran parsing rule [\" + pattern + \",\" + actionClass + \"]\" ; addError ( errorMsg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { [CODESPLIT] public SSLContext createContext ( ContextAware context ) throws NoSuchProviderException , NoSuchAlgorithmException , KeyManagementException , UnrecoverableKeyException , KeyStoreException , CertificateException { SSLContext sslContext = getProvider ( ) != null ? SSLContext . getInstance ( getProtocol ( ) , getProvider ( ) ) : SSLContext . getInstance ( getProtocol ( ) ) ; context . addInfo ( \"SSL protocol '\" + sslContext . getProtocol ( ) + \"' provider '\" + sslContext . getProvider ( ) + \"'\" ) ; KeyManager [ ] keyManagers = createKeyManagers ( context ) ; TrustManager [ ] trustManagers = createTrustManagers ( context ) ; SecureRandom secureRandom = createSecureRandom ( context ) ; sslContext . init ( keyManagers , trustManagers , secureRandom ) ; return sslContext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates key managers using the receiver s key store configuration . [CODESPLIT] private KeyManager [ ] createKeyManagers ( ContextAware context ) throws NoSuchProviderException , NoSuchAlgorithmException , UnrecoverableKeyException , KeyStoreException { if ( getKeyStore ( ) == null ) return null ; KeyStore keyStore = getKeyStore ( ) . createKeyStore ( ) ; context . addInfo ( \"key store of type '\" + keyStore . getType ( ) + \"' provider '\" + keyStore . getProvider ( ) + \"': \" + getKeyStore ( ) . getLocation ( ) ) ; KeyManagerFactory kmf = getKeyManagerFactory ( ) . createKeyManagerFactory ( ) ; context . addInfo ( \"key manager algorithm '\" + kmf . getAlgorithm ( ) + \"' provider '\" + kmf . getProvider ( ) + \"'\" ) ; char [ ] passphrase = getKeyStore ( ) . getPassword ( ) . toCharArray ( ) ; kmf . init ( keyStore , passphrase ) ; return kmf . getKeyManagers ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates trust managers using the receiver s trust store configuration . [CODESPLIT] private TrustManager [ ] createTrustManagers ( ContextAware context ) throws NoSuchProviderException , NoSuchAlgorithmException , KeyStoreException { if ( getTrustStore ( ) == null ) return null ; KeyStore trustStore = getTrustStore ( ) . createKeyStore ( ) ; context . addInfo ( \"trust store of type '\" + trustStore . getType ( ) + \"' provider '\" + trustStore . getProvider ( ) + \"': \" + getTrustStore ( ) . getLocation ( ) ) ; TrustManagerFactory tmf = getTrustManagerFactory ( ) . createTrustManagerFactory ( ) ; context . addInfo ( \"trust manager algorithm '\" + tmf . getAlgorithm ( ) + \"' provider '\" + tmf . getProvider ( ) + \"'\" ) ; tmf . init ( trustStore ) ; return tmf . getTrustManagers ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a key store factory bean using JSSE system properties . [CODESPLIT] private KeyStoreFactoryBean keyStoreFromSystemProperties ( String property ) { if ( System . getProperty ( property ) == null ) return null ; KeyStoreFactoryBean keyStore = new KeyStoreFactoryBean ( ) ; keyStore . setLocation ( locationFromSystemProperty ( property ) ) ; keyStore . setProvider ( System . getProperty ( property + \"Provider\" ) ) ; keyStore . setPassword ( System . getProperty ( property + \"Password\" ) ) ; keyStore . setType ( System . getProperty ( property + \"Type\" ) ) ; return keyStore ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a resource location from a JSSE system property . [CODESPLIT] private String locationFromSystemProperty ( String name ) { String location = System . getProperty ( name ) ; if ( location != null && ! location . startsWith ( \"file:\" ) ) { location = \"file:\" + location ; } return location ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a string describing the location of a resource into a URL object . [CODESPLIT] public static URL urlForResource ( String location ) throws MalformedURLException , FileNotFoundException { if ( location == null ) { throw new NullPointerException ( \"location is required\" ) ; } URL url = null ; if ( ! location . matches ( SCHEME_PATTERN ) ) { url = Loader . getResourceBySelfClassLoader ( location ) ; } else if ( location . startsWith ( CLASSPATH_SCHEME ) ) { String path = location . substring ( CLASSPATH_SCHEME . length ( ) ) ; if ( path . startsWith ( \"/\" ) ) { path = path . substring ( 1 ) ; } if ( path . length ( ) == 0 ) { throw new MalformedURLException ( \"path is required\" ) ; } url = Loader . getResourceBySelfClassLoader ( path ) ; } else { url = new URL ( location ) ; } if ( url == null ) { throw new FileNotFoundException ( location ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates an layout of the given class and sets its name . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void begin ( InterpretationContext ec , String localName , Attributes attributes ) { // Let us forget about previous errors (in this object) inError = false ; String errorMsg ; String conversionWord = attributes . getValue ( ActionConst . CONVERSION_WORD_ATTRIBUTE ) ; String converterClass = attributes . getValue ( ActionConst . CONVERTER_CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( conversionWord ) ) { inError = true ; errorMsg = \"No 'conversionWord' attribute in <conversionRule>\" ; addError ( errorMsg ) ; return ; } if ( OptionHelper . isEmpty ( converterClass ) ) { inError = true ; errorMsg = \"No 'converterClass' attribute in <conversionRule>\" ; ec . addError ( errorMsg ) ; return ; } try { Map < String , String > ruleRegistry = ( Map < String , String > ) context . getObject ( CoreConstants . PATTERN_RULE_REGISTRY ) ; if ( ruleRegistry == null ) { ruleRegistry = new HashMap < String , String > ( ) ; context . putObject ( CoreConstants . PATTERN_RULE_REGISTRY , ruleRegistry ) ; } // put the new rule into the rule registry addInfo ( \"registering conversion word \" + conversionWord + \" with class [\" + converterClass + \"]\" ) ; ruleRegistry . put ( conversionWord , converterClass ) ; } catch ( Exception oops ) { inError = true ; errorMsg = \"Could not add conversion rule to PatternLayout.\" ; addError ( errorMsg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation checks if any of the converters in the chain handles exceptions . If not then this method adds a { @link ThrowableProxyConverter } instance to the end of the chain . <p > This allows appenders using this layout to output exception information event if the user forgets to add %ex to the pattern . Note that the appenders defined in the Core package are not aware of exceptions nor LoggingEvents . <p > If for some reason the user wishes to NOT print exceptions then she can add %nopex to the pattern . [CODESPLIT] public void process ( Context context , Converter < ILoggingEvent > head ) { if ( head == null ) { // this should never happen throw new IllegalArgumentException ( \"cannot process empty chain\" ) ; } if ( ! chainHandlesThrowable ( head ) ) { Converter < ILoggingEvent > tail = ConverterUtil . findTail ( head ) ; Converter < ILoggingEvent > exConverter = null ; LoggerContext loggerContext = ( LoggerContext ) context ; if ( loggerContext . isPackagingDataEnabled ( ) ) { exConverter = new ExtendedThrowableProxyConverter ( ) ; } else { exConverter = new ThrowableProxyConverter ( ) ; } tail . setNext ( exConverter ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method computes whether a chain of converters handles exceptions or not . [CODESPLIT] public boolean chainHandlesThrowable ( Converter < ILoggingEvent > head ) { Converter < ILoggingEvent > c = head ; while ( c != null ) { if ( c instanceof ThrowableHandlingConverter ) { return true ; } c = c . getNext ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default method for stopping the Logback context [CODESPLIT] protected void stop ( ) { addInfo ( \"Logback context being closed via shutdown hook\" ) ; Context hookContext = getContext ( ) ; if ( hookContext instanceof ContextBase ) { ContextBase context = ( ContextBase ) hookContext ; context . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the contents of the context status but only if they contain warnings or errors occurring later then the threshold . [CODESPLIT] public static void printInCaseOfErrorsOrWarnings ( Context context , long threshold ) { if ( context == null ) { throw new IllegalArgumentException ( \"Context argument cannot be null\" ) ; } StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) { ps . println ( \"WARN: Context named \\\"\" + context . getName ( ) + \"\\\" has no status manager\" ) ; } else { StatusUtil statusUtil = new StatusUtil ( context ) ; if ( statusUtil . getHighestLevel ( threshold ) >= ErrorStatus . WARN ) { print ( sm , threshold ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the contents of the context statuses but only if they contain errors . [CODESPLIT] public static void printIfErrorsOccured ( Context context ) { if ( context == null ) { throw new IllegalArgumentException ( \"Context argument cannot be null\" ) ; } StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) { ps . println ( \"WARN: Context named \\\"\" + context . getName ( ) + \"\\\" has no status manager\" ) ; } else { StatusUtil statusUtil = new StatusUtil ( context ) ; if ( statusUtil . getHighestLevel ( 0 ) == ErrorStatus . ERROR ) { print ( sm ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print context s status data with a timestamp higher than the threshold . [CODESPLIT] public static void print ( Context context , long threshold ) { if ( context == null ) { throw new IllegalArgumentException ( \"Context argument cannot be null\" ) ; } StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) { ps . println ( \"WARN: Context named \\\"\" + context . getName ( ) + \"\\\" has no status manager\" ) ; } else { print ( sm , threshold ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private static void appendThrowable ( StringBuilder sb , Throwable t ) { String [ ] stringRep = ThrowableToStringArray . convert ( t ) ; for ( String s : stringRep ) { if ( s . startsWith ( CoreConstants . CAUSED_BY ) ) { // nothing } else if ( Character . isDigit ( s . charAt ( 0 ) ) ) { // if line resembles \"48 common frames omitted\" sb . append ( \"\\t... \" ) ; } else { // most of the time. just add a tab+\"at\" sb . append ( \"\\tat \" ) ; } sb . append ( s ) . append ( CoreConstants . LINE_SEPARATOR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void start ( ) { if ( isStarted ( ) ) return ; int errorCount = 0 ; if ( port <= 0 ) { errorCount ++ ; addError ( \"No port was configured for appender\" + name + \" For more information, please visit http://logback.qos.ch/codes.html#socket_no_port\" ) ; } if ( remoteHost == null ) { errorCount ++ ; addError ( \"No remote host was configured for appender\" + name + \" For more information, please visit http://logback.qos.ch/codes.html#socket_no_host\" ) ; } if ( queueSize == 0 ) { addWarn ( \"Queue size of zero is deprecated, use a size of one to indicate synchronous processing\" ) ; } if ( queueSize < 0 ) { errorCount ++ ; addError ( \"Queue size must be greater than zero\" ) ; } if ( errorCount == 0 ) { try { address = InetAddress . getByName ( remoteHost ) ; } catch ( UnknownHostException ex ) { addError ( \"unknown host: \" + remoteHost ) ; errorCount ++ ; } } if ( errorCount == 0 ) { deque = queueFactory . newLinkedBlockingDeque ( queueSize ) ; peerId = \"remote peer \" + remoteHost + \":\" + port + \": \" ; connector = createConnector ( address , port , 0 , reconnectionDelay . getMilliseconds ( ) ) ; task = getContext ( ) . getScheduledExecutorService ( ) . submit ( new Runnable ( ) { public void run ( ) { connectSocketAndDispatchEvents ( ) ; } } ) ; super . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void stop ( ) { if ( ! isStarted ( ) ) return ; CloseUtil . closeQuietly ( socket ) ; task . cancel ( true ) ; super . stop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void append ( E event ) { if ( event == null || ! isStarted ( ) ) return ; try { final boolean inserted = deque . offer ( event , eventDelayLimit . getMilliseconds ( ) , TimeUnit . MILLISECONDS ) ; if ( ! inserted ) { addInfo ( \"Dropping event due to timeout limit of [\" + eventDelayLimit + \"] being exceeded\" ) ; } } catch ( InterruptedException e ) { addError ( \"Interrupted while appending event to SocketAppender\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void connectionFailed ( SocketConnector connector , Exception ex ) { if ( ex instanceof InterruptedException ) { addInfo ( \"connector interrupted\" ) ; } else if ( ex instanceof ConnectException ) { addInfo ( peerId + \"connection refused\" ) ; } else { addInfo ( peerId + ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a level to equivalent syslog severity . Only levels for printing methods i . e DEBUG WARN INFO and ERROR are converted . [CODESPLIT] @ Override public int getSeverityForEvent ( Object eventObject ) { ILoggingEvent event = ( ILoggingEvent ) eventObject ; return LevelToSyslogSeverity . convert ( event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LOGBACK - 411 and LOGBACK - 750 [CODESPLIT] private void handleThrowableFirstLine ( OutputStream sw , IThrowableProxy tp , String stackTracePrefix , boolean isRootException ) throws IOException { StringBuilder sb = new StringBuilder ( ) . append ( stackTracePrefix ) ; if ( ! isRootException ) { sb . append ( CoreConstants . CAUSED_BY ) ; } sb . append ( tp . getClassName ( ) ) . append ( \": \" ) . append ( tp . getMessage ( ) ) ; sw . write ( sb . toString ( ) . getBytes ( ) ) ; sw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an entry from the liveMap if not found search the lingerersMap . [CODESPLIT] private Entry < C > getFromEitherMap ( String key ) { Entry < C > entry = liveMap . get ( key ) ; if ( entry != null ) return entry ; else { return lingerersMap . get ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public synchronized C find ( String key ) { Entry < C > entry = getFromEitherMap ( key ) ; if ( entry == null ) return null ; else return entry . component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public synchronized C getOrCreate ( String key , long timestamp ) { Entry < C > entry = getFromEitherMap ( key ) ; if ( entry == null ) { C c = buildComponent ( key ) ; entry = new Entry < C > ( key , c , timestamp ) ; // new entries go into the main map liveMap . put ( key , entry ) ; } else { entry . setTimestamp ( timestamp ) ; } return entry . component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mark component identified by key as having reached its end - of - life . [CODESPLIT] public void endOfLife ( String key ) { Entry < C > entry = liveMap . remove ( key ) ; if ( entry == null ) return ; lingerersMap . put ( key , entry ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to parse a string such as 5 . 7 5 . 7 or - 5 . 7 into a FormatInfo . [CODESPLIT] public static FormatInfo valueOf ( String str ) throws IllegalArgumentException { if ( str == null ) { throw new NullPointerException ( \"Argument cannot be null\" ) ; } FormatInfo fi = new FormatInfo ( ) ; int indexOfDot = str . indexOf ( ' ' ) ; String minPart = null ; String maxPart = null ; if ( indexOfDot != - 1 ) { minPart = str . substring ( 0 , indexOfDot ) ; if ( indexOfDot + 1 == str . length ( ) ) { throw new IllegalArgumentException ( \"Formatting string [\" + str + \"] should not end with '.'\" ) ; } else { maxPart = str . substring ( indexOfDot + 1 ) ; } } else { minPart = str ; } if ( minPart != null && minPart . length ( ) > 0 ) { int min = Integer . parseInt ( minPart ) ; if ( min >= 0 ) { fi . min = min ; } else { fi . min = - min ; fi . leftPad = false ; } } if ( maxPart != null && maxPart . length ( ) > 0 ) { int max = Integer . parseInt ( maxPart ) ; if ( max >= 0 ) { fi . max = max ; } else { fi . max = - max ; fi . leftTruncate = false ; } } return fi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A relatively robust file renaming method which in case of failure due to src and target being on different volumes falls back onto renaming by copying . [CODESPLIT] public void rename ( String src , String target ) throws RolloverFailure { if ( src . equals ( target ) ) { addWarn ( \"Source and target files are the same [\" + src + \"]. Skipping.\" ) ; return ; } File srcFile = new File ( src ) ; if ( srcFile . exists ( ) ) { File targetFile = new File ( target ) ; createMissingTargetDirsIfNecessary ( targetFile ) ; addInfo ( \"Renaming file [\" + srcFile + \"] to [\" + targetFile + \"]\" ) ; boolean result = srcFile . renameTo ( targetFile ) ; if ( ! result ) { addWarn ( \"Failed to rename file [\" + srcFile + \"] as [\" + targetFile + \"].\" ) ; Boolean areOnDifferentVolumes = areOnDifferentVolumes ( srcFile , targetFile ) ; if ( Boolean . TRUE . equals ( areOnDifferentVolumes ) ) { addWarn ( \"Detected different file systems for source [\" + src + \"] and target [\" + target + \"]. Attempting rename by copying.\" ) ; renameByCopying ( src , target ) ; return ; } else { addWarn ( \"Please consider leaving the [file] option of \" + RollingFileAppender . class . getSimpleName ( ) + \" empty.\" ) ; addWarn ( \"See also \" + RENAMING_ERROR_URL ) ; } } } else { throw new RolloverFailure ( \"File [\" + src + \"] does not exist.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts tp determine whether both files are on different volumes . Returns true if we could determine that the files are on different volumes . Returns false otherwise or if an error occurred while doing the check . [CODESPLIT] Boolean areOnDifferentVolumes ( File srcFile , File targetFile ) throws RolloverFailure { if ( ! EnvUtil . isJDK7OrHigher ( ) ) { return false ; } // target file is not certain to exist but its parent has to exist given the call hierarchy of this method File parentOfTarget = targetFile . getAbsoluteFile ( ) . getParentFile ( ) ; if ( parentOfTarget == null ) { addWarn ( \"Parent of target file [\" + targetFile + \"] is null\" ) ; return null ; } if ( ! parentOfTarget . exists ( ) ) { addWarn ( \"Parent of target file [\" + targetFile + \"] does not exist\" ) ; return null ; } try { boolean onSameFileStore = FileStoreUtil . areOnSameFileStore ( srcFile , parentOfTarget ) ; return ! onSameFileStore ; } catch ( RolloverFailure rf ) { addWarn ( \"Error while checking file store equality\" , rf ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See http : // logback . qos . ch / manual / configuration . html#variableSubstitution [CODESPLIT] public static String substVars ( String input , PropertyContainer pc0 , PropertyContainer pc1 ) { try { return NodeToStringTransformer . substituteVariable ( input , pc0 , pc1 ) ; } catch ( ScanException e ) { throw new IllegalArgumentException ( \"Failed to parse input [\" + input + \"]\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Very similar to <code > System . getProperty< / code > except that the { @link SecurityException } is absorbed . [CODESPLIT] public static String getSystemProperty ( String key , String def ) { try { return System . getProperty ( key , def ) ; } catch ( SecurityException e ) { return def ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup a key from the environment . [CODESPLIT] public static String getEnv ( String key ) { try { return System . getenv ( key ) ; } catch ( SecurityException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an Android system property [CODESPLIT] public static String getAndroidSystemProperty ( String key ) { try { return SystemPropertiesProxy . getInstance ( ) . get ( key , null ) ; } catch ( IllegalArgumentException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Very similar to <code > System . getProperty< / code > except that the { @link SecurityException } is absorbed . Also checks Android system properties as a fallback . [CODESPLIT] public static String getSystemProperty ( String key ) { try { String prop = System . getProperty ( key ) ; return ( prop == null ) ? getAndroidSystemProperty ( key ) : prop ; } catch ( SecurityException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a String [] of size two . The first item containing the key part and the second item containing a default value specified by the user . The second item will be null if no default value is specified . [CODESPLIT] static public String [ ] extractDefaultReplacement ( String key ) { String [ ] result = new String [ 2 ] ; if ( key == null ) return result ; result [ 0 ] = key ; int d = key . indexOf ( DELIM_DEFAULT ) ; if ( d != - 1 ) { result [ 0 ] = key . substring ( 0 , d ) ; result [ 1 ] = key . substring ( d + DELIM_DEFAULT_LEN ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If <code > value< / code > is true then <code > true< / code > is returned . If <code > value< / code > is false then <code > true< / code > is returned . Otherwise <code > default< / code > is returned . <p > Case of value is unimportant . [CODESPLIT] public static boolean toBoolean ( String value , boolean defaultValue ) { if ( value == null ) { return defaultValue ; } String trimmedVal = value . trim ( ) ; if ( \"true\" . equalsIgnoreCase ( trimmedVal ) ) { return true ; } if ( \"false\" . equalsIgnoreCase ( trimmedVal ) ) { return false ; } return defaultValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method clears all internal properties except internal status messages closes all appenders removes any turboFilters fires an OnReset event removes all status listeners removes all context listeners ( except those which are reset resistant ) . <p > As mentioned above internal status messages survive resets . [CODESPLIT] @ Override public void reset ( ) { resetCount ++ ; super . reset ( ) ; initEvaluatorMap ( ) ; initCollisionMaps ( ) ; root . recursiveReset ( ) ; resetTurboFilterList ( ) ; cancelScheduledTasks ( ) ; fireOnReset ( ) ; resetListenersExceptResetResistant ( ) ; resetStatusListeners ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the caller information for this logging event . If caller information is null at the time of its invocation this method extracts location information . The collected information is cached for future use . <p > Note that after serialization it is impossible to correctly extract caller information . < / p > [CODESPLIT] public StackTraceElement [ ] getCallerData ( ) { if ( callerDataArray == null ) { callerDataArray = CallerData . extract ( new Throwable ( ) , fqnOfLoggerClass , loggerContext . getMaxCallerDataDepth ( ) , loggerContext . getFrameworkPackages ( ) ) ; } return callerDataArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the MDC map for this event . [CODESPLIT] public void setMDCPropertyMap ( Map < String , String > map ) { if ( mdcPropertyMap != null ) { throw new IllegalStateException ( \"The MDCPropertyMap has been already set for this event.\" ) ; } this . mdcPropertyMap = map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if no key is specified return all the values present in the MDC in the format k1 = v1 k2 = v2 ... [CODESPLIT] private String outputMDCForAllKeys ( Map < String , String > mdcPropertyMap ) { StringBuilder buf = new StringBuilder ( ) ; boolean first = true ; for ( Map . Entry < String , String > entry : mdcPropertyMap . entrySet ( ) ) { if ( first ) { first = false ; } else { buf . append ( \", \" ) ; } //format: key0=value0, key1=value1 buf . append ( entry . getKey ( ) ) . append ( ' ' ) . append ( entry . getValue ( ) ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the file specified by { @link #setPath ( String ) path } property exists . Returns false otherwise . [CODESPLIT] public String getPropertyValue ( ) { if ( OptionHelper . isEmpty ( path ) ) { addError ( \"The \\\"path\\\" property must be set.\" ) ; return null ; } File file = new File ( path ) ; return booleanAsStr ( file . exists ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected boolean configureClient ( RemoteReceiverClient client ) { client . setContext ( getContext ( ) ) ; client . setQueue ( new ArrayBlockingQueue < Serializable > ( clientQueueSize ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract caller data information as an array based on a Throwable passed as parameter [CODESPLIT] public static StackTraceElement [ ] extract ( Throwable t , String fqnOfInvokingClass , final int maxDepth , List < String > frameworkPackageList ) { if ( t == null ) { return null ; } StackTraceElement [ ] steArray = t . getStackTrace ( ) ; StackTraceElement [ ] callerDataArray ; int found = LINE_NA ; for ( int i = 0 ; i < steArray . length ; i ++ ) { if ( isInFrameworkSpace ( steArray [ i ] . getClassName ( ) , fqnOfInvokingClass , frameworkPackageList ) ) { // the caller is assumed to be the next stack frame, hence the +1. found = i + 1 ; } else { if ( found != LINE_NA ) { break ; } } } // we failed to extract caller data if ( found == LINE_NA ) { return EMPTY_CALLER_DATA_ARRAY ; } int availableDepth = steArray . length - found ; int desiredDepth = maxDepth < ( availableDepth ) ? maxDepth : availableDepth ; callerDataArray = new StackTraceElement [ desiredDepth ] ; for ( int i = 0 ; i < desiredDepth ; i ++ ) { callerDataArray [ i ] = steArray [ found + i ] ; } return callerDataArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is currentClass present in the list of packages considered part of the logging framework? [CODESPLIT] private static boolean isInFrameworkSpaceList ( String currentClass , List < String > frameworkPackageList ) { if ( frameworkPackageList == null ) return false ; for ( String s : frameworkPackageList ) { if ( currentClass . startsWith ( s ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new status object . [CODESPLIT] public void add ( Status newStatus ) { // LBCORE-72: fire event before the count check fireStatusAddEvent ( newStatus ) ; count ++ ; if ( newStatus . getLevel ( ) > level ) { level = newStatus . getLevel ( ) ; } synchronized ( statusListLock ) { if ( statusList . size ( ) < MAX_HEADER_COUNT ) { statusList . add ( newStatus ) ; } else { tailBuffer . add ( newStatus ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation does not allow duplicate installations of OnConsoleStatusListener [CODESPLIT] public boolean add ( StatusListener listener ) { synchronized ( statusListenerListLock ) { if ( listener instanceof OnConsoleStatusListener ) { boolean alreadyPresent = checkForPresence ( statusListenerList , listener . getClass ( ) ) ; if ( alreadyPresent ) { return false ; } } statusListenerList . add ( listener ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if any implicit actions are applicable . As soon as an applicable action is found it is returned . Thus the returned list will have at most one element . [CODESPLIT] List < Action > lookupImplicitAction ( ElementPath elementPath , Attributes attributes , InterpretationContext ec ) { int len = implicitActions . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { ImplicitAction ia = ( ImplicitAction ) implicitActions . get ( i ) ; if ( ia . isApplicable ( elementPath , attributes , ec ) ) { List < Action > actionList = new ArrayList < Action > ( 1 ) ; actionList . add ( ia ) ; return actionList ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the list of applicable patterns for this [CODESPLIT] List < Action > getApplicableActionList ( ElementPath elementPath , Attributes attributes ) { List < Action > applicableActionList = ruleStore . matchActions ( elementPath ) ; // logger.debug(\"set of applicable patterns: \" + applicableActionList); if ( applicableActionList == null ) { applicableActionList = lookupImplicitAction ( elementPath , attributes , interpretationContext ) ; } return applicableActionList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the classloader to lookup the class for android . os . SystemProperties [CODESPLIT] public void setClassLoader ( ClassLoader cl ) throws ClassNotFoundException , SecurityException , NoSuchMethodException { if ( cl == null ) cl = this . getClass ( ) . getClassLoader ( ) ; SystemProperties = cl . loadClass ( \"android.os.SystemProperties\" ) ; getString = SystemProperties . getMethod ( \"get\" , new Class [ ] { String . class , String . class } ) ; getBoolean = SystemProperties . getMethod ( \"getBoolean\" , new Class [ ] { String . class , boolean . class } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value for the given key in the Android system properties [CODESPLIT] public String get ( String key , String def ) throws IllegalArgumentException { if ( SystemProperties == null || getString == null ) return null ; String ret = null ; try { ret = ( String ) getString . invoke ( SystemProperties , new Object [ ] { key , def } ) ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e ) { } // if return value is null or empty, use the default // since neither of those are valid values if ( ret == null || ret . length ( ) == 0 ) { ret = def ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value for the given key in the Android system properties returned as a boolean . [CODESPLIT] public Boolean getBoolean ( String key , boolean def ) throws IllegalArgumentException { if ( SystemProperties == null || getBoolean == null ) return def ; Boolean ret = def ; try { ret = ( Boolean ) getBoolean . invoke ( SystemProperties , new Object [ ] { key , def } ) ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e ) { } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a name string s first letter to lowercase [CODESPLIT] static public String decapitalize ( String name ) { if ( name == null || name . length ( ) == 0 ) { return name ; } else { String nm = name . substring ( 0 , 1 ) . toLowerCase ( Locale . US ) ; if ( name . length ( ) > 1 ) { nm += name . substring ( 1 ) ; } return nm ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a class s method descriptors [CODESPLIT] static public MethodDescriptor [ ] getMethodDescriptors ( Class < ? > clazz ) { ArrayList < MethodDescriptor > methods = new ArrayList < MethodDescriptor > ( ) ; for ( Method m : clazz . getMethods ( ) ) { methods . add ( new MethodDescriptor ( m . getName ( ) , m ) ) ; } return methods . toArray ( new MethodDescriptor [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a class s property descriptors . All properties have methods whose name begins with set or get . The setters must have a single parameter and getters must have none . [CODESPLIT] static public PropertyDescriptor [ ] getPropertyDescriptors ( Class < ? > clazz ) { final String SETTER_PREFIX = \"set\" ; final String GETTER_PREFIX = \"get\" ; final int LEN_PREFIX = SETTER_PREFIX . length ( ) ; Map < String , PropertyDescriptor > map = new HashMap < String , PropertyDescriptor > ( ) ; for ( Method m : clazz . getMethods ( ) ) { PropertyDescriptor pd = null ; String mName = m . getName ( ) ; boolean isGet = mName . startsWith ( GETTER_PREFIX ) && ( mName . length ( ) > LEN_PREFIX ) ; boolean isSet = mName . startsWith ( SETTER_PREFIX ) && ( mName . length ( ) > LEN_PREFIX ) ; if ( isGet || isSet ) { String propName = decapitalize ( mName . substring ( LEN_PREFIX ) ) ; pd = map . get ( propName ) ; if ( pd == null ) { pd = new PropertyDescriptor ( propName ) ; map . put ( propName , pd ) ; } Class < ? > [ ] parmTypes = m . getParameterTypes ( ) ; if ( isSet ) { if ( parmTypes . length == 1 ) { // we only want the single-parm setter pd . setWriteMethod ( m ) ; pd . setPropertyType ( parmTypes [ 0 ] ) ; } } else if ( isGet ) { if ( parmTypes . length == 0 ) { // we only want the zero-parm getter pd . setReadMethod ( m ) ; // let setter's type take priority if ( pd . getPropertyType ( ) == null ) { pd . setPropertyType ( m . getReturnType ( ) ) ; } } } } } return map . values ( ) . toArray ( new PropertyDescriptor [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected boolean shouldStart ( ) { int errorCount = 0 ; if ( port == 0 ) { errorCount ++ ; addError ( \"No port was configured for receiver. \" + \"For more information, please visit http://logback.qos.ch/codes.html#receiver_no_port\" ) ; } if ( remoteHost == null ) { errorCount ++ ; addError ( \"No host name or address was configured for receiver. \" + \"For more information, please visit http://logback.qos.ch/codes.html#receiver_no_host\" ) ; } if ( reconnectionDelay == 0 ) { reconnectionDelay = AbstractSocketAppender . DEFAULT_RECONNECTION_DELAY ; } if ( errorCount == 0 ) { try { address = InetAddress . getByName ( remoteHost ) ; } catch ( UnknownHostException ex ) { addError ( \"unknown host: \" + remoteHost ) ; errorCount ++ ; } } if ( errorCount == 0 ) { receiverId = \"receiver \" + remoteHost + \":\" + port + \": \" ; } return errorCount == 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void run ( ) { try { LoggerContext lc = ( LoggerContext ) getContext ( ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { SocketConnector connector = createConnector ( address , port , 0 , reconnectionDelay ) ; connectorTask = activateConnector ( connector ) ; if ( connectorTask == null ) { break ; } socket = waitForConnectorToReturnASocket ( ) ; if ( socket == null ) break ; dispatchEvents ( lc ) ; } } catch ( InterruptedException ex ) { assert true ; // ok... we'll exit now } addInfo ( \"shutting down\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void connectionFailed ( SocketConnector connector , Exception ex ) { if ( ex instanceof InterruptedException ) { addWarn ( \"connector interrupted\" , ex ) ; } else if ( ex instanceof ConnectException ) { addWarn ( receiverId + \"connection refused\" , ex ) ; } else { addWarn ( receiverId + \"unspecified error\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the <b > Target< / b > option . Recognized values are System . out and System . err . Any other value will be ignored . [CODESPLIT] public void setTarget ( String value ) { @ SuppressWarnings ( \"deprecation\" ) ConsoleTarget t = ConsoleTarget . findByName ( value . trim ( ) ) ; if ( t == null ) { targetWarn ( value ) ; } else { target = t ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that requires parameters are set and if everything is in order activates this appender . [CODESPLIT] public void start ( ) { int errors = 0 ; if ( this . encoder == null ) { addStatus ( new ErrorStatus ( \"No encoder set for the appender named \\\"\" + name + \"\\\".\" , this ) ) ; errors ++ ; } if ( this . outputStream == null ) { addStatus ( new ErrorStatus ( \"No output stream set for the appender named \\\"\" + name + \"\\\".\" , this ) ) ; errors ++ ; } // only error free appenders should be activated if ( errors == 0 ) { super . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the underlying { [CODESPLIT] protected void closeOutputStream ( ) { if ( this . outputStream != null ) { try { // before closing we have to output out layout's footer encoderClose ( ) ; this . outputStream . close ( ) ; this . outputStream = null ; } catch ( IOException e ) { addStatus ( new ErrorStatus ( \"Could not close output stream for OutputStreamAppender.\" , this , e ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the @link OutputStream } where the log output will go . The specified <code > OutputStream< / code > must be opened by the user and be writable . The <code > OutputStream< / code > will be closed when the appender instance is closed . [CODESPLIT] public void setOutputStream ( OutputStream outputStream ) { lock . lock ( ) ; try { // close any previously opened output stream closeOutputStream ( ) ; this . outputStream = outputStream ; if ( encoder == null ) { addWarn ( \"Encoder has not been set. Cannot invoke its init method.\" ) ; return ; } encoderInit ( ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actual writing occurs here . <p > Most subclasses of <code > WriterAppender< / code > will need to override this method . [CODESPLIT] protected void subAppend ( E event ) { if ( ! isStarted ( ) ) { return ; } try { // this step avoids LBCLASSIC-139 if ( event instanceof DeferredProcessingAware ) { ( ( DeferredProcessingAware ) event ) . prepareForDeferredProcessing ( ) ; } // the synchronization prevents the OutputStream from being closed while we // are writing. It also prevents multiple threads from entering the same // converter. Converters assume that they are in a synchronized block. //lock.lock(); byte [ ] byteArray = this . encoder . encode ( event ) ; writeBytes ( byteArray ) ; } catch ( IOException ioe ) { // as soon as an exception occurs, move to non-started state // and add a single ErrorStatus to the SM. this . started = false ; addStatus ( new ErrorStatus ( \"IO failure in appender\" , this , ioe ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets this manager . <p > All registered components are stopped and removed from the manager . [CODESPLIT] public void reset ( ) { for ( LifeCycle component : components ) { if ( component . isStarted ( ) ) { component . stop ( ) ; } } components . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This utility method adds a new OnConsoleStatusListener to the context passed as parameter . [CODESPLIT] static public void addOnConsoleListenerInstance ( Context context , OnConsoleStatusListener onConsoleStatusListener ) { onConsoleStatusListener . setContext ( context ) ; boolean effectivelyAdded = context . getStatusManager ( ) . add ( onConsoleStatusListener ) ; if ( effectivelyAdded ) { onConsoleStatusListener . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Now property definer is initialized by all properties and we can put property value to context [CODESPLIT] public void end ( InterpretationContext ec , String name ) { if ( inError ) { return ; } Object o = ec . peekObject ( ) ; if ( o != definer ) { addWarn ( \"The object at the of the stack is not the property definer for property named [\" + propertyName + \"] pushed earlier.\" ) ; } else { addInfo ( \"Popping property definer for property named [\" + propertyName + \"] from the object stack\" ) ; ec . popObject ( ) ; // let's put defined property and value to context but only if it is // not null String propertyValue = definer . getPropertyValue ( ) ; if ( propertyValue != null ) { ActionUtil . setProperty ( ec , propertyName , propertyValue , scope ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the name of the current context name as found in the logging event . [CODESPLIT] public String getDiscriminatingValue ( ILoggingEvent event ) { String contextName = event . getLoggerContextVO ( ) . getName ( ) ; if ( contextName == null ) { return defaultValue ; } else { return contextName ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do not perform any character escaping . <p > Note that this method assumes that it is called after the escape character has been consumed . [CODESPLIT] public void escape ( String escapeChars , StringBuffer buf , char next , int pointer ) { // restitute the escape char (because it was consumed // before this method was called). buf . append ( \"\\\\\" ) ; // restitute the next character buf . append ( next ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Events of level TRACE DEBUG and INFO are deemed to be discardable . [CODESPLIT] protected boolean isDiscardable ( ILoggingEvent event ) { Level level = event . getLevel ( ) ; return level . toInt ( ) <= Level . INFO_INT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a shutdown hook of the given class and sets its name . [CODESPLIT] @ Override public void begin ( InterpretationContext ic , String name , Attributes attributes ) throws ActionException { hook = null ; inError = false ; String className = attributes . getValue ( CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( className ) ) { className = DefaultShutdownHook . class . getName ( ) ; addInfo ( \"Assuming className [\" + className + \"]\" ) ; } try { addInfo ( \"About to instantiate shutdown hook of type [\" + className + \"]\" ) ; hook = ( ShutdownHookBase ) OptionHelper . instantiateByClassName ( className , ShutdownHookBase . class , context ) ; hook . setContext ( context ) ; ic . pushObject ( hook ) ; } catch ( Exception e ) { inError = true ; addError ( \"Could not create a shutdown hook of type [\" + className + \"].\" , e ) ; throw new ActionException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Once the children elements are also parsed now is the time to activate the shutdown hook options . [CODESPLIT] @ Override public void end ( InterpretationContext ic , String name ) throws ActionException { if ( inError ) { return ; } Object o = ic . peekObject ( ) ; if ( o != hook ) { addWarn ( \"The object at the of the stack is not the hook pushed earlier.\" ) ; } else { ic . popObject ( ) ; Thread hookThread = new Thread ( hook , \"Logback shutdown hook [\" + context . getName ( ) + \"]\" ) ; addInfo ( \"Registering shutdown hook with JVM runtime\" ) ; context . putObject ( CoreConstants . SHUTDOWN_HOOK_THREAD , hookThread ) ; Runtime . getRuntime ( ) . addShutdownHook ( hookThread ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] public KeyManagerFactory createKeyManagerFactory ( ) throws NoSuchProviderException , NoSuchAlgorithmException { return getProvider ( ) != null ? KeyManagerFactory . getInstance ( getAlgorithm ( ) , getProvider ( ) ) : KeyManagerFactory . getInstance ( getAlgorithm ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes a closeable while suppressing any { [CODESPLIT] public static void closeQuietly ( Closeable closeable ) { if ( closeable == null ) return ; try { closeable . close ( ) ; } catch ( IOException ex ) { assert true ; // avoid an empty catch } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes a socket while suppressing any { [CODESPLIT] public static void closeQuietly ( Socket socket ) { if ( socket == null ) return ; try { socket . close ( ) ; } catch ( IOException ex ) { assert true ; // avoid an empty catch } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes a server socket while suppressing any { [CODESPLIT] public static void closeQuietly ( ServerSocket serverSocket ) { if ( serverSocket == null ) return ; try { serverSocket . close ( ) ; } catch ( IOException ex ) { assert true ; // avoid an empty catch } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures SSL parameters on an { [CODESPLIT] public void configure ( SSLConfigurable socket ) { socket . setEnabledProtocols ( enabledProtocols ( socket . getSupportedProtocols ( ) , socket . getDefaultProtocols ( ) ) ) ; socket . setEnabledCipherSuites ( enabledCipherSuites ( socket . getSupportedCipherSuites ( ) , socket . getDefaultCipherSuites ( ) ) ) ; if ( isNeedClientAuth ( ) != null ) { socket . setNeedClientAuth ( isNeedClientAuth ( ) ) ; } if ( isWantClientAuth ( ) != null ) { socket . setWantClientAuth ( isWantClientAuth ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the set of enabled protocols based on the configuration . [CODESPLIT] private String [ ] enabledProtocols ( String [ ] supportedProtocols , String [ ] defaultProtocols ) { if ( enabledProtocols == null ) { // we're assuming that the same engine is used for all configurables // so once we determine the enabled set, we won't do it again if ( OptionHelper . isEmpty ( getIncludedProtocols ( ) ) && OptionHelper . isEmpty ( getExcludedProtocols ( ) ) ) { enabledProtocols = Arrays . copyOf ( defaultProtocols , defaultProtocols . length ) ; } else { enabledProtocols = includedStrings ( supportedProtocols , getIncludedProtocols ( ) , getExcludedProtocols ( ) ) ; } for ( String protocol : enabledProtocols ) { addInfo ( \"enabled protocol: \" + protocol ) ; } } return enabledProtocols ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the set of enabled cipher suites based on the configuration . [CODESPLIT] private String [ ] enabledCipherSuites ( String [ ] supportedCipherSuites , String [ ] defaultCipherSuites ) { if ( enabledCipherSuites == null ) { // we're assuming that the same engine is used for all configurables // so once we determine the enabled set, we won't do it again if ( OptionHelper . isEmpty ( getIncludedCipherSuites ( ) ) && OptionHelper . isEmpty ( getExcludedCipherSuites ( ) ) ) { enabledCipherSuites = Arrays . copyOf ( defaultCipherSuites , defaultCipherSuites . length ) ; } else { enabledCipherSuites = includedStrings ( supportedCipherSuites , getIncludedCipherSuites ( ) , getExcludedCipherSuites ( ) ) ; } for ( String cipherSuite : enabledCipherSuites ) { addInfo ( \"enabled cipher suite: \" + cipherSuite ) ; } } return enabledCipherSuites ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies include and exclude patterns to an array of default string values to produce an array of strings included by the patterns . [CODESPLIT] private String [ ] includedStrings ( String [ ] defaults , String included , String excluded ) { List < String > values = new ArrayList < String > ( defaults . length ) ; values . addAll ( Arrays . asList ( defaults ) ) ; if ( included != null ) { StringCollectionUtil . retainMatching ( values , stringToArray ( included ) ) ; } if ( excluded != null ) { StringCollectionUtil . removeMatching ( values , stringToArray ( excluded ) ) ; } return values . toArray ( new String [ values . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @link LinkedBlockingDeque } with the given { @code capacity } . In case the given capacity is smaller than one it will automatically be converted to one . [CODESPLIT] public < E > LinkedBlockingDeque < E > newLinkedBlockingDeque ( int capacity ) { final int actualCapacity = capacity < 1 ? 1 : capacity ; return new LinkedBlockingDeque < E > ( actualCapacity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string into a scope . Scope . LOCAL is returned by default . [CODESPLIT] static public Scope stringToScope ( String scopeStr ) { if ( Scope . SYSTEM . toString ( ) . equalsIgnoreCase ( scopeStr ) ) return Scope . SYSTEM ; if ( Scope . CONTEXT . toString ( ) . equalsIgnoreCase ( scopeStr ) ) return Scope . CONTEXT ; return Scope . LOCAL ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all the properties found in the argument named props to an InterpretationContext . [CODESPLIT] static public void setProperties ( InterpretationContext ic , Properties props , Scope scope ) { switch ( scope ) { case LOCAL : ic . addSubstitutionProperties ( props ) ; break ; case CONTEXT : ContextUtil cu = new ContextUtil ( ic . getContext ( ) ) ; cu . addProperties ( props ) ; break ; case SYSTEM : OptionHelper . setSystemProperties ( ic , props ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attach an appender . If the appender is already in the list in won t be added again . [CODESPLIT] public void addAppender ( Appender < E > newAppender ) { if ( newAppender == null ) { throw new IllegalArgumentException ( \"Null argument disallowed\" ) ; } appenderList . addIfAbsent ( newAppender ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call the <code > doAppend< / code > method on all attached appenders . [CODESPLIT] public int appendLoopOnAppenders ( E e ) { int size = 0 ; final Appender < E > [ ] appenderArray = appenderList . asTypedArray ( ) ; final int len = appenderArray . length ; for ( int i = 0 ; i < len ; i ++ ) { appenderArray [ i ] . doAppend ( e ) ; size ++ ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the specified appender is in the list of attached appenders <code > false< / code > otherwise . [CODESPLIT] public boolean isAttached ( Appender < E > appender ) { if ( appender == null ) { return false ; } for ( Appender < E > a : appenderList ) { if ( a == appender ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the appender passed as parameter form the list of attached appenders . [CODESPLIT] public boolean detachAppender ( Appender < E > appender ) { if ( appender == null ) { return false ; } boolean result ; result = appenderList . remove ( appender ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the appender with the name passed as parameter form the list of appenders . [CODESPLIT] public boolean detachAppender ( String name ) { if ( name == null ) { return false ; } boolean removed = false ; for ( Appender < E > a : appenderList ) { if ( name . equals ( ( a ) . getName ( ) ) ) { removed = appenderList . remove ( a ) ; break ; } } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is invoked by parent logger to let this logger know that the prent s levelInt changed . [CODESPLIT] private synchronized void handleParentLevelChange ( int newParentLevelInt ) { // changes in the parent levelInt affect children only if their levelInt is // null if ( level == null ) { effectiveLevelInt = newParentLevelInt ; // propagate the parent levelInt change to this logger's children if ( childrenList != null ) { int len = childrenList . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { Logger child = ( Logger ) childrenList . get ( i ) ; child . handleParentLevelChange ( newParentLevelInt ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "details . [CODESPLIT] public synchronized void addAppender ( Appender < ILoggingEvent > newAppender ) { if ( aai == null ) { aai = new AppenderAttachableImpl < ILoggingEvent > ( ) ; } aai . addAppender ( newAppender ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke all the appenders of this logger . [CODESPLIT] public void callAppenders ( ILoggingEvent event ) { int writes = 0 ; for ( Logger l = this ; l != null ; l = l . parent ) { writes += l . appendLoopOnAppenders ( event ) ; if ( ! l . additive ) { break ; } } // No appenders in hierarchy if ( writes == 0 ) { loggerContext . noAppenderDefinedWarning ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the appender passed as parameter form the list of appenders . [CODESPLIT] public boolean detachAppender ( Appender < ILoggingEvent > appender ) { if ( aai == null ) { return false ; } return aai . detachAppender ( appender ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a child of this logger by suffix that is the part of the name extending this logger . For example if this logger is named x . y and the lastPart is z then the created child logger will be named x . y . z . [CODESPLIT] Logger createChildByLastNamePart ( final String lastPart ) { int i_index = LoggerNameUtil . getFirstSeparatorIndexOf ( lastPart ) ; if ( i_index != - 1 ) { throw new IllegalArgumentException ( \"Child name [\" + lastPart + \" passed as parameter, may not include [\" + CoreConstants . DOT + \"]\" ) ; } if ( childrenList == null ) { childrenList = new CopyOnWriteArrayList < Logger > ( ) ; } Logger childLogger ; if ( this . isRootLogger ( ) ) { childLogger = new Logger ( lastPart , this , this . loggerContext ) ; } else { childLogger = new Logger ( name + CoreConstants . DOT + lastPart , this , this . loggerContext ) ; } childrenList . add ( childLogger ) ; childLogger . effectiveLevelInt = this . effectiveLevelInt ; return childLogger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The next methods are not merged into one because of the time we gain by not creating a new Object [] with the params . This reduces the cost of not logging by about 20 nanoseconds . [CODESPLIT] private void filterAndLog_0_Or3Plus ( final String localFQCN , final Marker marker , final Level level , final String msg , final Object [ ] params , final Throwable t ) { final FilterReply decision = loggerContext . getTurboFilterChainDecision_0_3OrMore ( marker , this , level , msg , params , t ) ; if ( decision == FilterReply . NEUTRAL ) { if ( effectiveLevelInt > level . levelInt ) { return ; } } else if ( decision == FilterReply . DENY ) { return ; } buildLoggingEventAndAppend ( localFQCN , marker , level , msg , params , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that calls the attached TurboFilter objects based on the logger and the level . [CODESPLIT] private FilterReply callTurboFilters ( Marker marker , Level level ) { return loggerContext . getTurboFilterChainDecision_0_3OrMore ( marker , this , level , null , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support SLF4J interception during initialization as introduced in SLF4J version 1 . 7 . 15 [CODESPLIT] public void log ( org . slf4j . event . LoggingEvent slf4jEvent ) { Level level = Level . fromLocationAwareLoggerInteger ( slf4jEvent . getLevel ( ) . toInt ( ) ) ; filterAndLog_0_Or3Plus ( FQCN , slf4jEvent . getMarker ( ) , level , slf4jEvent . getMessage ( ) , slf4jEvent . getArgumentArray ( ) , slf4jEvent . getThrowable ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops until the desired connection is established and returns the resulting connector . [CODESPLIT] public Socket call ( ) throws InterruptedException { useDefaultsForMissingFields ( ) ; Socket socket = createSocket ( ) ; while ( socket == null && ! Thread . currentThread ( ) . isInterrupted ( ) ) { Thread . sleep ( delayStrategy . nextDelay ( ) ) ; socket = createSocket ( ) ; } return socket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the parent directories of a file . If parent directories not specified in file s path then nothing is done and this returns gracefully . [CODESPLIT] static public boolean createMissingParentDirectories ( File file ) { File parent = file . getParentFile ( ) ; if ( parent == null ) { // Parent directory not specified, therefore it's a request to // create nothing. Done! ;) return true ; } // File.mkdirs() creates the parent directories only if they don't // already exist; and it's okay if they do. parent . mkdirs ( ) ; return parent . exists ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepends a string to a path if the path is relative . If the path is already absolute the same path is returned ( nothing changed ) . This is useful for converting relative paths to absolute ones given the absolute directory path as a prefix . [CODESPLIT] public static String prefixRelativePath ( String prefix , String path ) { if ( prefix != null && ! OptionHelper . isEmpty ( prefix . trim ( ) ) && ! new File ( path ) . isAbsolute ( ) ) { path = prefix + \"/\" + path ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a Level to an Integer object . [CODESPLIT] public Integer toInteger ( ) { switch ( levelInt ) { case ALL_INT : return ALL_INTEGER ; case TRACE_INT : return TRACE_INTEGER ; case DEBUG_INT : return DEBUG_INTEGER ; case INFO_INT : return INFO_INTEGER ; case WARN_INT : return WARN_INTEGER ; case ERROR_INT : return ERROR_INTEGER ; case OFF_INT : return OFF_INTEGER ; default : throw new IllegalStateException ( \"Level \" + levelStr + \", \" + levelInt + \" is unknown.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an integer passed as argument to a Level . If the conversion fails then this method returns the specified default . [CODESPLIT] public static Level toLevel ( int val , Level defaultLevel ) { switch ( val ) { case ALL_INT : return ALL ; case TRACE_INT : return TRACE ; case DEBUG_INT : return DEBUG ; case INFO_INT : return INFO ; case WARN_INT : return WARN ; case ERROR_INT : return ERROR ; case OFF_INT : return OFF ; default : return defaultLevel ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the string passed as argument to a Level . If the conversion fails then this method returns the value of <code > defaultLevel< / code > . [CODESPLIT] public static Level toLevel ( final String sArg , Level defaultLevel ) { if ( sArg == null ) { return defaultLevel ; } final String in = sArg . trim ( ) ; if ( in . equalsIgnoreCase ( \"ALL\" ) ) { return Level . ALL ; } if ( in . equalsIgnoreCase ( \"TRACE\" ) ) { return Level . TRACE ; } if ( in . equalsIgnoreCase ( \"DEBUG\" ) ) { return Level . DEBUG ; } if ( in . equalsIgnoreCase ( \"INFO\" ) ) { return Level . INFO ; } if ( in . equalsIgnoreCase ( \"WARN\" ) ) { return Level . WARN ; } if ( in . equalsIgnoreCase ( \"ERROR\" ) ) { return Level . ERROR ; } if ( in . equalsIgnoreCase ( \"OFF\" ) ) { return Level . OFF ; } return defaultLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert one of the integer values defined in { @link LocationAwareLogger } interface to an instance of this class i . e . a Level . [CODESPLIT] public static Level fromLocationAwareLoggerInteger ( int levelInt ) { Level level ; switch ( levelInt ) { case LocationAwareLogger . TRACE_INT : level = TRACE ; break ; case LocationAwareLogger . DEBUG_INT : level = DEBUG ; break ; case LocationAwareLogger . INFO_INT : level = INFO ; break ; case LocationAwareLogger . WARN_INT : level = WARN ; break ; case LocationAwareLogger . ERROR_INT : level = ERROR ; break ; default : throw new IllegalArgumentException ( levelInt + \" not a valid level value\" ) ; } return level ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert this level instance to an integer value defined in the { @link LocationAwareLogger } interface . [CODESPLIT] public static int toLocationAwareLoggerInteger ( Level level ) { if ( level == null ) throw new IllegalArgumentException ( \"null level parameter is not admitted\" ) ; switch ( level . toInt ( ) ) { case Level . TRACE_INT : return LocationAwareLogger . TRACE_INT ; case Level . DEBUG_INT : return LocationAwareLogger . DEBUG_INT ; case Level . INFO_INT : return LocationAwareLogger . INFO_INT ; case Level . WARN_INT : return LocationAwareLogger . WARN_INT ; case Level . ERROR_INT : return LocationAwareLogger . ERROR_INT ; default : throw new IllegalArgumentException ( level + \" not a valid level value\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the class of the object o passed as parameter is * not * marked with the NoAutoStart annotation . Return true otherwise . [CODESPLIT] static public boolean notMarkedWithNoAutoStart ( Object o ) { if ( o == null ) { return false ; } Class < ? > clazz = o . getClass ( ) ; NoAutoStart a = clazz . getAnnotation ( NoAutoStart . class ) ; return a == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { [CODESPLIT] public KeyStore createKeyStore ( ) throws NoSuchProviderException , NoSuchAlgorithmException , KeyStoreException { if ( getLocation ( ) == null ) { throw new IllegalArgumentException ( \"location is required\" ) ; } InputStream inputStream = null ; try { URL url = LocationUtil . urlForResource ( getLocation ( ) ) ; inputStream = url . openStream ( ) ; KeyStore keyStore = newKeyStore ( ) ; keyStore . load ( inputStream , getPassword ( ) . toCharArray ( ) ) ; return keyStore ; } catch ( NoSuchProviderException ex ) { throw new NoSuchProviderException ( \"no such keystore provider: \" + getProvider ( ) ) ; } catch ( NoSuchAlgorithmException ex ) { throw new NoSuchAlgorithmException ( \"no such keystore type: \" + getType ( ) ) ; } catch ( FileNotFoundException ex ) { throw new KeyStoreException ( getLocation ( ) + \": file not found\" ) ; } catch ( Exception ex ) { throw new KeyStoreException ( getLocation ( ) + \": \" + ex . getMessage ( ) , ex ) ; } finally { try { if ( inputStream != null ) { inputStream . close ( ) ; } } catch ( IOException ex ) { ex . printStackTrace ( System . err ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the appropriate JCE factory method to obtain a new { [CODESPLIT] private KeyStore newKeyStore ( ) throws NoSuchAlgorithmException , NoSuchProviderException , KeyStoreException { return getProvider ( ) != null ? KeyStore . getInstance ( getType ( ) , getProvider ( ) ) : KeyStore . getInstance ( getType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the number of occurrences a resource can be found by a class loader . [CODESPLIT] public static Set < URL > getResourceOccurrenceCount ( String resource , ClassLoader classLoader ) throws IOException { // See LBCLASSIC-159 Set < URL > urlSet = new HashSet < URL > ( ) ; Enumeration < URL > urlEnum = classLoader . getResources ( resource ) ; while ( urlEnum . hasMoreElements ( ) ) { URL url = urlEnum . nextElement ( ) ; urlSet . add ( url ) ; } return urlSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for a resource using the classloader passed as parameter . [CODESPLIT] public static URL getResource ( String resource , ClassLoader classLoader ) { try { return classLoader . getResource ( resource ) ; } catch ( Throwable t ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the class loader of the object passed as argument . Return the system class loader if appropriate . [CODESPLIT] public static ClassLoader getClassLoaderOfObject ( Object o ) { if ( o == null ) { throw new NullPointerException ( \"Argument cannot be null\" ) ; } return getClassLoaderOfClass ( o . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the class loader of clazz in an access privileged section . [CODESPLIT] public static ClassLoader getClassLoaderAsPrivileged ( final Class < ? > clazz ) { if ( ! HAS_GET_CLASS_LOADER_PERMISSION ) return null ; else return AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { public ClassLoader run ( ) { return clazz . getClassLoader ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the class loader which loaded the class passed as argument . Return the system class loader if appropriate . [CODESPLIT] public static ClassLoader getClassLoaderOfClass ( final Class < ? > clazz ) { ClassLoader cl = clazz . getClassLoader ( ) ; if ( cl == null ) { return ClassLoader . getSystemClassLoader ( ) ; } else { return cl ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If running under JDK 1 . 2 load the specified class using the <code > Thread< / code > <code > contextClassLoader< / code > if that fails try Class . forname . Under JDK 1 . 1 only Class . forName is used . [CODESPLIT] public static Class < ? > loadClass ( String clazz ) throws ClassNotFoundException { // Just call Class.forName(clazz) if we are running under JDK 1.1 // or if we are instructed to ignore the TCL. if ( ignoreTCL ) { return Class . forName ( clazz ) ; } else { try { return getTCL ( ) . loadClass ( clazz ) ; } catch ( Throwable e ) { // we reached here because tcl was null or because of a // security exception, or because clazz could not be loaded... // In any case we now try one more time return Class . forName ( clazz ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that required parameters are set and if everything is in order activates this appender . [CODESPLIT] @ Override public void start ( ) { if ( ( this . encoder == null ) || ( this . encoder . getLayout ( ) == null ) ) { addError ( \"No layout set for the appender named [\" + name + \"].\" ) ; return ; } // tag encoder is optional but needs a layout if ( this . tagEncoder != null ) { final Layout < ? > layout = this . tagEncoder . getLayout ( ) ; if ( layout == null ) { addError ( \"No tag layout set for the appender named [\" + name + \"].\" ) ; return ; } // prevent stack traces from showing up in the tag // (which could lead to very confusing error messages) if ( layout instanceof PatternLayout ) { String pattern = this . tagEncoder . getPattern ( ) ; if ( ! pattern . contains ( \"%nopex\" ) ) { this . tagEncoder . stop ( ) ; this . tagEncoder . setPattern ( pattern + \"%nopex\" ) ; this . tagEncoder . start ( ) ; } PatternLayout tagLayout = ( PatternLayout ) layout ; tagLayout . setPostCompileProcessor ( null ) ; } } super . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an event to Android s logging mechanism ( logcat ) [CODESPLIT] public void append ( ILoggingEvent event ) { if ( ! isStarted ( ) ) { return ; } String tag = getTag ( event ) ; switch ( event . getLevel ( ) . levelInt ) { case Level . ALL_INT : case Level . TRACE_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . VERBOSE ) ) { Log . v ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . DEBUG_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . DEBUG ) ) { Log . d ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . INFO_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . INFO ) ) { Log . i ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . WARN_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . WARN ) ) { Log . w ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . ERROR_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . ERROR ) ) { Log . e ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . OFF_INT : default : break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the logcat tag string of a logging event [CODESPLIT] protected String getTag ( ILoggingEvent event ) { // format tag based on encoder layout; truncate if max length // exceeded (only necessary for isLoggable(), which throws // IllegalArgumentException) String tag = ( this . tagEncoder != null ) ? this . tagEncoder . getLayout ( ) . doLayout ( event ) : event . getLoggerName ( ) ; if ( checkLoggable && ( tag . length ( ) > MAX_TAG_LENGTH ) ) { tag = tag . substring ( 0 , MAX_TAG_LENGTH - 1 ) + \"*\" ; } return tag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setLoggerContext ( LoggerContext lc ) { this . lc = lc ; this . logger = lc . getLogger ( getClass ( ) . getPackage ( ) . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void run ( ) { logger . info ( this + \": connected\" ) ; HardenedObjectInputStream ois = null ; try { ois = createObjectInputStream ( ) ; while ( true ) { // read an event from the wire ILoggingEvent event = ( ILoggingEvent ) ois . readObject ( ) ; // get a logger from the hierarchy. The name of the logger is taken to // be the name contained in the event. Logger remoteLogger = lc . getLogger ( event . getLoggerName ( ) ) ; // apply the logger-level filter if ( remoteLogger . isEnabledFor ( event . getLevel ( ) ) ) { // finally log the event as if was generated locally remoteLogger . callAppenders ( event ) ; } } } catch ( EOFException ex ) { // this is normal and expected assert true ; } catch ( IOException ex ) { logger . info ( this + \": \" + ex ) ; } catch ( ClassNotFoundException ex ) { logger . error ( this + \": unknown event class\" ) ; } catch ( RuntimeException ex ) { logger . error ( this + \": \" + ex ) ; } finally { if ( ois != null ) { CloseUtil . closeQuietly ( ois ) ; } close ( ) ; logger . info ( this + \": connection closed\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a new property for the execution context by name value pair or adds all the properties found in the given file . [CODESPLIT] public void begin ( InterpretationContext ec , String localName , Attributes attributes ) { if ( \"substitutionProperty\" . equals ( localName ) ) { addWarn ( \"[substitutionProperty] element has been deprecated. Please use the [property] element instead.\" ) ; } String name = attributes . getValue ( NAME_ATTRIBUTE ) ; String value = attributes . getValue ( VALUE_ATTRIBUTE ) ; String scopeStr = attributes . getValue ( SCOPE_ATTRIBUTE ) ; Scope scope = ActionUtil . stringToScope ( scopeStr ) ; if ( checkFileAttributeSanity ( attributes ) ) { String file = attributes . getValue ( FILE_ATTRIBUTE ) ; file = ec . subst ( file ) ; try { FileInputStream istream = new FileInputStream ( file ) ; loadAndSetProperties ( ec , istream , scope ) ; } catch ( FileNotFoundException e ) { addError ( \"Could not find properties file [\" + file + \"].\" ) ; } catch ( IOException e1 ) { addError ( \"Could not read properties file [\" + file + \"].\" , e1 ) ; } } else if ( checkResourceAttributeSanity ( attributes ) ) { String resource = attributes . getValue ( RESOURCE_ATTRIBUTE ) ; resource = ec . subst ( resource ) ; URL resourceURL = Loader . getResourceBySelfClassLoader ( resource ) ; if ( resourceURL == null ) { addError ( \"Could not find resource [\" + resource + \"].\" ) ; } else { try { InputStream istream = resourceURL . openStream ( ) ; loadAndSetProperties ( ec , istream , scope ) ; } catch ( IOException e ) { addError ( \"Could not read resource file [\" + resource + \"].\" , e ) ; } } } else if ( checkValueNameAttributesSanity ( attributes ) ) { value = RegularEscapeUtil . basicEscape ( value ) ; // now remove both leading and trailing spaces value = value . trim ( ) ; value = ec . subst ( value ) ; ActionUtil . setProperty ( ec , name , value , scope ) ; } else { addError ( INVALID_ATTRIBUTES ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the position of the separator character if any starting at position fromIndex . [CODESPLIT] public static int getSeparatorIndexOf ( String name , int fromIndex ) { int dotIndex = name . indexOf ( CoreConstants . DOT , fromIndex ) ; int dollarIndex = name . indexOf ( CoreConstants . DOLLAR , fromIndex ) ; if ( dotIndex == - 1 && dollarIndex == - 1 ) return - 1 ; if ( dotIndex == - 1 ) return dollarIndex ; if ( dollarIndex == - 1 ) return dotIndex ; return dotIndex < dollarIndex ? dotIndex : dollarIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if event passed as parameter contains one of the specified user - markers . [CODESPLIT] public boolean evaluate ( ILoggingEvent event ) throws NullPointerException , EvaluationException { Marker eventsMarker = event . getMarker ( ) ; if ( eventsMarker == null ) { return false ; } for ( String markerStr : markerList ) { if ( eventsMarker . contains ( markerStr ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] public TrustManagerFactory createTrustManagerFactory ( ) throws NoSuchProviderException , NoSuchAlgorithmException { return getProvider ( ) != null ? TrustManagerFactory . getInstance ( getAlgorithm ( ) , getProvider ( ) ) : TrustManagerFactory . getInstance ( getAlgorithm ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a name to identify each client thread . [CODESPLIT] protected String getClientThreadName ( Socket socket ) { return String . format ( Locale . US , \"Logback SocketNode (client: %s)\" , socket . getRemoteSocketAddress ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method assumes that both files a and b exists . [CODESPLIT] static public boolean areOnSameFileStore ( File a , File b ) throws RolloverFailure { if ( ! a . exists ( ) ) { throw new IllegalArgumentException ( \"File [\" + a + \"] does not exist.\" ) ; } if ( ! b . exists ( ) ) { throw new IllegalArgumentException ( \"File [\" + b + \"] does not exist.\" ) ; } // Implements the following by reflection //    Path pathA = a.toPath(); //    Path pathB = b.toPath(); // //    FileStore fileStoreA = Files.getFileStore(pathA); //    FileStore fileStoreB = Files.getFileStore(pathB); // //    return fileStoreA.equals(fileStoreB); try { Class < ? > pathClass = Class . forName ( PATH_CLASS_STR ) ; Class < ? > filesClass = Class . forName ( FILES_CLASS_STR ) ; Method toPath = File . class . getMethod ( \"toPath\" ) ; Method getFileStoreMethod = filesClass . getMethod ( \"getFileStore\" , pathClass ) ; Object pathA = toPath . invoke ( a ) ; Object pathB = toPath . invoke ( b ) ; Object fileStoreA = getFileStoreMethod . invoke ( null , pathA ) ; Object fileStoreB = getFileStoreMethod . invoke ( null , pathB ) ; return fileStoreA . equals ( fileStoreB ) ; } catch ( Exception e ) { throw new RolloverFailure ( \"Failed to check file store equality for [\" + a + \"] and [\" + b + \"]\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the appender [CODESPLIT] public void start ( ) { if ( cbTracker == null ) { cbTracker = new CyclicBufferTracker < E > ( ) ; } session = buildSessionFromProperties ( ) ; if ( session == null ) { addError ( \"Failed to obtain javax.mail.Session. Cannot start.\" ) ; return ; } subjectLayout = makeSubjectLayout ( subjectStr ) ; started = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform SMTPAppender specific appending actions delegating some of them to a subclass and checking if the event triggers an e - mail to be sent . [CODESPLIT] protected void append ( E eventObject ) { if ( ! checkEntryConditions ( ) ) { return ; } String key = discriminator . getDiscriminatingValue ( eventObject ) ; long now = System . currentTimeMillis ( ) ; final CyclicBuffer < E > cb = cbTracker . getOrCreate ( key , now ) ; subAppend ( cb , eventObject ) ; try { if ( eventEvaluator . evaluate ( eventObject ) ) { // clone the CyclicBuffer before sending out asynchronously CyclicBuffer < E > cbClone = new CyclicBuffer < E > ( cb ) ; // see http://jira.qos.ch/browse/LBCLASSIC-221 cb . clear ( ) ; if ( asynchronousSending ) { // perform actual sending asynchronously SenderRunnable senderRunnable = new SenderRunnable ( cbClone , eventObject ) ; context . getScheduledExecutorService ( ) . execute ( senderRunnable ) ; } else { // synchronous sending sendBuffer ( cbClone , eventObject ) ; } } } catch ( EvaluationException ex ) { errorCount ++ ; if ( errorCount < CoreConstants . MAX_ERROR_COUNT ) { addError ( \"SMTPAppender's EventEvaluator threw an Exception-\" , ex ) ; } } // immediately remove the buffer if asked by the user if ( eventMarksEndOfLife ( eventObject ) ) { cbTracker . endOfLife ( key ) ; } cbTracker . removeStaleComponents ( now ) ; if ( lastTrackerStatusPrint + delayBetweenStatusMessages < now ) { addInfo ( \"SMTPAppender [\" + name + \"] is tracking [\" + cbTracker . getComponentCount ( ) + \"] buffers\" ) ; lastTrackerStatusPrint = now ; // quadruple 'delay' assuming less than max delay if ( delayBetweenStatusMessages < MAX_DELAY_BETWEEN_STATUS_MESSAGES ) { delayBetweenStatusMessages *= 4 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method determines if there is a sense in attempting to append . <p > It checks whether there is a set output target and also if there is a set layout . If these checks fail then the boolean value <code > false< / code > is returned . [CODESPLIT] public boolean checkEntryConditions ( ) { if ( ! this . started ) { addError ( \"Attempting to append to a non-started appender: \" + this . getName ( ) ) ; return false ; } if ( this . eventEvaluator == null ) { addError ( \"No EventEvaluator is set for appender [\" + name + \"].\" ) ; return false ; } if ( this . layout == null ) { addError ( \"No layout set for appender named [\" + name + \"]. For more information, please visit http://logback.qos.ch/codes.html#smtp_no_layout\" ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the contents of the cyclic buffer as an e - mail message . [CODESPLIT] protected void sendBuffer ( CyclicBuffer < E > cb , E lastEventObject ) { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize on 'cb'. try { MimeBodyPart part = new MimeBodyPart ( ) ; StringBuffer sbuf = new StringBuffer ( ) ; String header = layout . getFileHeader ( ) ; if ( header != null ) { sbuf . append ( header ) ; } String presentationHeader = layout . getPresentationHeader ( ) ; if ( presentationHeader != null ) { sbuf . append ( presentationHeader ) ; } fillBuffer ( cb , sbuf ) ; String presentationFooter = layout . getPresentationFooter ( ) ; if ( presentationFooter != null ) { sbuf . append ( presentationFooter ) ; } String footer = layout . getFileFooter ( ) ; if ( footer != null ) { sbuf . append ( footer ) ; } String subjectStr = \"Undefined subject\" ; if ( subjectLayout != null ) { subjectStr = subjectLayout . doLayout ( lastEventObject ) ; // The subject must not contain new-line characters, which cause // an SMTP error (LOGBACK-865). Truncate the string at the first // new-line character. int newLinePos = ( subjectStr != null ) ? subjectStr . indexOf ( ' ' ) : - 1 ; if ( newLinePos > - 1 ) { subjectStr = subjectStr . substring ( 0 , newLinePos ) ; } } MimeMessage mimeMsg = new MimeMessage ( session ) ; if ( from != null ) { mimeMsg . setFrom ( getAddress ( from ) ) ; } else { mimeMsg . setFrom ( ) ; } mimeMsg . setSubject ( subjectStr , charsetEncoding ) ; List < InternetAddress > destinationAddresses = parseAddress ( lastEventObject ) ; if ( destinationAddresses . isEmpty ( ) ) { addInfo ( \"Empty destination address. Aborting email transmission\" ) ; return ; } InternetAddress [ ] toAddressArray = destinationAddresses . toArray ( EMPTY_IA_ARRAY ) ; mimeMsg . setRecipients ( Message . RecipientType . TO , toAddressArray ) ; String contentType = layout . getContentType ( ) ; if ( ContentTypeUtil . isTextual ( contentType ) ) { part . setText ( sbuf . toString ( ) , charsetEncoding , ContentTypeUtil . getSubType ( contentType ) ) ; } else { part . setContent ( sbuf . toString ( ) , layout . getContentType ( ) ) ; } Multipart mp = new MimeMultipart ( ) ; mp . addBodyPart ( part ) ; mimeMsg . setContent ( mp ) ; updateMimeMsg ( mimeMsg , cb , lastEventObject ) ; mimeMsg . setSentDate ( new Date ( ) ) ; addInfo ( \"About to send out SMTP message \\\"\" + subjectStr + \"\\\" to \" + Arrays . toString ( toAddressArray ) ) ; Transport . send ( mimeMsg ) ; } catch ( Exception e ) { addError ( \"Error occurred while sending e-mail notification.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public void run ( ) { try { hardenedLoggingEventInputStream = new HardenedLoggingEventInputStream ( new BufferedInputStream ( socket . getInputStream ( ) ) ) ; } catch ( Exception e ) { logger . error ( \"Could not open ObjectInputStream to \" + socket , e ) ; closed = true ; } ILoggingEvent event ; Logger remoteLogger ; try { while ( ! closed ) { // read an event from the wire event = ( ILoggingEvent ) hardenedLoggingEventInputStream . readObject ( ) ; // get a logger from the hierarchy. The name of the logger is taken to // be the name contained in the event. remoteLogger = context . getLogger ( event . getLoggerName ( ) ) ; // apply the logger-level filter if ( remoteLogger . isEnabledFor ( event . getLevel ( ) ) ) { // finally log the event as if was generated locally remoteLogger . callAppenders ( event ) ; } } } catch ( java . io . EOFException e ) { logger . info ( \"Caught java.io.EOFException closing connection.\" ) ; } catch ( java . net . SocketException e ) { logger . info ( \"Caught java.net.SocketException closing connection.\" ) ; } catch ( IOException e ) { logger . info ( \"Caught java.io.IOException: \" + e ) ; logger . info ( \"Closing connection.\" ) ; } catch ( Exception e ) { logger . error ( \"Unexpected exception. Closing connection.\" , e ) ; } socketServer . socketNodeClosing ( this ) ; close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new MDCValuePair [CODESPLIT] public void addMDCValueLevelPair ( MDCValueLevelPair mdcValueLevelPair ) { if ( valueLevelMap . containsKey ( mdcValueLevelPair . getValue ( ) ) ) { addError ( mdcValueLevelPair . getValue ( ) + \" has been already set\" ) ; } else { valueLevelMap . put ( mdcValueLevelPair . getValue ( ) , mdcValueLevelPair . getLevel ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method first finds the MDC value for key . It then finds the level threshold associated with this MDC value from the list of MDCValueLevelPair passed to this filter . This value is stored in a variable called levelAssociatedWithMDCValue . If it null then it is set to the { @link #defaultThreshold } value . [CODESPLIT] @ Override public FilterReply decide ( Marker marker , Logger logger , Level level , String s , Object [ ] objects , Throwable throwable ) { String mdcValue = MDC . get ( this . key ) ; if ( ! isStarted ( ) ) { return FilterReply . NEUTRAL ; } Level levelAssociatedWithMDCValue = null ; if ( mdcValue != null ) { levelAssociatedWithMDCValue = valueLevelMap . get ( mdcValue ) ; } if ( levelAssociatedWithMDCValue == null ) { levelAssociatedWithMDCValue = defaultThreshold ; } if ( level . isGreaterOrEqual ( levelAssociatedWithMDCValue ) ) { return onHigherOrEqual ; } else { return onLower ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to create a converter using the information found in converterMap . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) DynamicConverter < E > createConverter ( SimpleKeywordNode kn ) { String keyword = ( String ) kn . getValue ( ) ; String converterClassStr = ( String ) converterMap . get ( keyword ) ; if ( converterClassStr != null ) { try { return ( DynamicConverter < E > ) OptionHelper . instantiateByClassName ( converterClassStr , DynamicConverter . class , context ) ; } catch ( Exception e ) { addError ( \"Failed to instantiate converter class [\" + converterClassStr + \"] for keyword [\" + keyword + \"]\" , e ) ; return null ; } } else { addError ( \"There is no conversion class registered for conversion word [\" + keyword + \"]\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to create a converter using the information found in compositeConverterMap . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) CompositeConverter < E > createCompositeConverter ( CompositeNode cn ) { String keyword = ( String ) cn . getValue ( ) ; String converterClassStr = ( String ) converterMap . get ( keyword ) ; if ( converterClassStr != null ) { try { return ( CompositeConverter < E > ) OptionHelper . instantiateByClassName ( converterClassStr , CompositeConverter . class , context ) ; } catch ( Exception e ) { addError ( \"Failed to instantiate converter class [\" + converterClassStr + \"] as a composite converter for keyword [\" + keyword + \"]\" , e ) ; return null ; } } else { addError ( \"There is no conversion class registered for composite conversion word [\" + keyword + \"]\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given the FileNamePattern string this method determines the compression mode depending on last letters of the fileNamePatternStr . Patterns ending with . gz imply GZIP compression endings with . zip imply ZIP compression . Otherwise and by default there is no compression . [CODESPLIT] protected void determineCompressionMode ( ) { if ( fileNamePatternStr . endsWith ( \".gz\" ) ) { addInfo ( \"Will use gz compression\" ) ; compressionMode = CompressionMode . GZ ; } else if ( fileNamePatternStr . endsWith ( \".zip\" ) ) { addInfo ( \"Will use zip compression\" ) ; compressionMode = CompressionMode . ZIP ; } else { addInfo ( \"No compression will be used\" ) ; compressionMode = CompressionMode . NONE ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures logback with the configuration XML read from a file located at the given URL [CODESPLIT] public final void doConfigure ( URL url ) throws JoranException { InputStream in = null ; try { informContextOfURLUsedForConfiguration ( getContext ( ) , url ) ; URLConnection urlConnection = url . openConnection ( ) ; // per http://jira.qos.ch/browse/LBCORE-105 // per http://jira.qos.ch/browse/LBCORE-127 urlConnection . setUseCaches ( false ) ; // this closes the stream for us in = urlConnection . getInputStream ( ) ; doConfigure ( in , url . toExternalForm ( ) ) ; } catch ( IOException ioe ) { String errMsg = \"Could not open URL [\" + url + \"].\" ; addError ( errMsg , ioe ) ; throw new JoranException ( errMsg , ioe ) ; } finally { CloseUtil . closeQuietly ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures logback with the configuration XML read from a given file [CODESPLIT] public final void doConfigure ( File file ) throws JoranException { FileInputStream fis = null ; try { URL url = file . toURI ( ) . toURL ( ) ; informContextOfURLUsedForConfiguration ( getContext ( ) , url ) ; fis = new FileInputStream ( file ) ; // this closes the stream for us doConfigure ( fis , url . toExternalForm ( ) ) ; } catch ( IOException ioe ) { String errMsg = \"Could not open [\" + file . getPath ( ) + \"].\" ; addError ( errMsg , ioe ) ; throw new JoranException ( errMsg , ioe ) ; } finally { CloseUtil . closeQuietly ( fis ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures logback with the configuraiton XML read from an input stream and then closes the stream [CODESPLIT] public final void doConfigure ( InputStream inputStream ) throws JoranException { try { doConfigure ( new InputSource ( inputStream ) ) ; } finally { try { inputStream . close ( ) ; } catch ( IOException ioe ) { String errMsg = \"Could not close the stream\" ; addError ( errMsg , ioe ) ; throw new JoranException ( errMsg , ioe ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a generic configuration - XML interpreter [CODESPLIT] protected void buildInterpreter ( ) { RuleStore rs = new SimpleRuleStore ( context ) ; addInstanceRules ( rs ) ; this . interpreter = new Interpreter ( context , rs , initialElementPath ( ) ) ; InterpretationContext interpretationContext = interpreter . getInterpretationContext ( ) ; interpretationContext . setContext ( context ) ; addImplicitRules ( interpreter ) ; addDefaultNestedComponentRegistryRules ( interpretationContext . getDefaultNestedComponentRegistry ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures logback with the configuration XML read from an input source . [CODESPLIT] private final void doConfigure ( final InputSource inputSource ) throws JoranException { long threshold = System . currentTimeMillis ( ) ; //    if (!ConfigurationWatchListUtil.wasConfigurationWatchListReset(context)) { //      informContextOfURLUsedForConfiguration(getContext(), null); //    } SaxEventRecorder recorder = new SaxEventRecorder ( context ) ; recorder . recordEvents ( inputSource ) ; doConfigure ( recorder . getSaxEventList ( ) ) ; // no exceptions a this level StatusUtil statusUtil = new StatusUtil ( context ) ; if ( statusUtil . noXMLParsingErrorsOccurred ( threshold ) ) { addInfo ( \"Registering current configuration as safe fallback point\" ) ; registerSafeConfiguration ( recorder . getSaxEventList ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures logback with SAX events of configuration XML [CODESPLIT] public void doConfigure ( final List < SaxEvent > eventList ) throws JoranException { buildInterpreter ( ) ; // disallow simultaneous configurations of the same context synchronized ( context . getConfigurationLock ( ) ) { interpreter . getEventPlayer ( ) . play ( eventList ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a key return the corresponding property value . If invoked with the special key CONTEXT_NAME the name of the context is returned . [CODESPLIT] public String getProperty ( String key ) { if ( CONTEXT_NAME_KEY . equals ( key ) ) return getName ( ) ; return ( String ) this . propertyMap . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The context name can be set only if it is not already set or if the current name is the default context name namely default or if the current name and the old name are the same . [CODESPLIT] public void setName ( String name ) throws IllegalStateException { if ( name != null && name . equals ( this . name ) ) { return ; // idempotent naming } if ( this . name == null || CoreConstants . DEFAULT_CONTEXT_NAME . equals ( this . name ) ) { this . name = name ; } else { throw new IllegalStateException ( \"Context has been already given a name\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the StatusManager associated with the context passed as parameter has one or more StatusListener instances registered . Returns false otherwise . [CODESPLIT] static public boolean contextHasStatusListener ( Context context ) { StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) return false ; List < StatusListener > listeners = sm . getCopyOfStatusListenerList ( ) ; if ( listeners == null || listeners . size ( ) == 0 ) return false ; else return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the time of last reset . - 1 if last reset time could not be found [CODESPLIT] public long timeOfLastReset ( ) { List < Status > statusList = sm . getCopyOfStatusList ( ) ; if ( statusList == null ) return - 1 ; int len = statusList . size ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { Status s = statusList . get ( i ) ; if ( CoreConstants . RESET_MSG_PREFIX . equals ( s . getMessage ( ) ) ) { return s . getDate ( ) ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an <code > event< / code > as the last event in the buffer . [CODESPLIT] public void add ( E event ) { ea [ last ] = event ; if ( ++ last == maxSize ) last = 0 ; if ( numElems < maxSize ) numElems ++ ; else if ( ++ first == maxSize ) first = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the <i > i< / i > th oldest event currently in the buffer . If <em > i< / em > is outside the range 0 to the number of elements currently in the buffer then <code > null< / code > is returned . [CODESPLIT] public E get ( int i ) { if ( i < 0 || i >= numElems ) return null ; return ea [ ( first + i ) % maxSize ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the oldest ( first ) element in the buffer . The oldest element is removed from the buffer . [CODESPLIT] public E get ( ) { E r = null ; if ( numElems > 0 ) { numElems -- ; r = ea [ first ] ; ea [ first ] = null ; if ( ++ first == maxSize ) first = 0 ; } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resize the cyclic buffer to <code > newSize< / code > . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void resize ( int newSize ) { if ( newSize < 0 ) { throw new IllegalArgumentException ( \"Negative array size [\" + newSize + \"] not allowed.\" ) ; } if ( newSize == numElems ) return ; // nothing to do // E [ ] temp = ( E [ ] ) new Object [ newSize ] ; int loopLen = newSize < numElems ? newSize : numElems ; for ( int i = 0 ; i < loopLen ; i ++ ) { temp [ i ] = ea [ first ] ; ea [ first ] = null ; if ( ++ first == numElems ) first = 0 ; } ea = temp ; first = 0 ; numElems = loopLen ; maxSize = newSize ; if ( loopLen == newSize ) { last = 0 ; } else { last = loopLen ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected RemoteReceiverClient createClient ( String id , Socket socket ) throws IOException { return new RemoteReceiverStreamClient ( id , socket ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Socket createSocket ( InetAddress address , int port , InetAddress localAddress , int localPort ) throws IOException { SSLSocket socket = ( SSLSocket ) delegate . createSocket ( address , port , localAddress , localPort ) ; parameters . configure ( new SSLConfigurableSocket ( socket ) ) ; return socket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Socket createSocket ( InetAddress host , int port ) throws IOException { SSLSocket socket = ( SSLSocket ) delegate . createSocket ( host , port ) ; parameters . configure ( new SSLConfigurableSocket ( socket ) ) ; return socket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static ConfigurationWatchList getConfigurationWatchList ( Context context ) { if ( context == null ) return null ; return ( ConfigurationWatchList ) context . getObject ( CoreConstants . CONFIGURATION_WATCH_LIST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the pattern and creates the Converter linked list . [CODESPLIT] @ Override public void start ( ) { int errorCount = 0 ; try { Parser < E > p = new Parser < E > ( pattern ) ; p . setContext ( getContext ( ) ) ; Node t = p . parse ( ) ; this . head = p . compile ( t , getEffectiveConverterMap ( ) ) ; ConverterUtil . startConverters ( this . head ) ; } catch ( ScanException ex ) { addError ( \"Incorrect pattern found\" , ex ) ; errorCount ++ ; } if ( errorCount == 0 ) { super . started = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a map where the default converter map is merged with the map contained in the context . [CODESPLIT] public Map < String , String > getEffectiveConverterMap ( ) { Map < String , String > effectiveMap = new HashMap < String , String > ( ) ; // add the least specific map fist Map < String , String > defaultMap = getDefaultConverterMap ( ) ; if ( defaultMap != null ) { effectiveMap . putAll ( defaultMap ) ; } // contextMap is more specific than the default map Context context = getContext ( ) ; if ( context != null ) { @ SuppressWarnings ( \"unchecked\" ) Map < String , String > contextMap = ( Map < String , String > ) context . getObject ( CoreConstants . PATTERN_RULE_REGISTRY ) ; if ( contextMap != null ) { effectiveMap . putAll ( contextMap ) ; } } return effectiveMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns appropriate HTML headers . [CODESPLIT] @ Override public String getFileHeader ( ) { StringBuilder sbuf = new StringBuilder ( ) ; sbuf . append ( \"<!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0 Strict//EN\\\"\" ) ; sbuf . append ( \" \\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\\\">\" ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( \"<html>\" ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( \"  <head>\" ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( \"    <title>\" ) ; sbuf . append ( title ) ; sbuf . append ( \"</title>\" ) ; sbuf . append ( LINE_SEPARATOR ) ; cssBuilder . addCss ( sbuf ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( \"  </head>\" ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( \"<body>\" ) ; sbuf . append ( LINE_SEPARATOR ) ; return sbuf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the appropriate HTML footers . [CODESPLIT] @ Override public String getFileFooter ( ) { StringBuilder sbuf = new StringBuilder ( ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( \"</body></html>\" ) ; return sbuf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates an appender of the given class and sets its name . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void begin ( InterpretationContext ec , String localName , Attributes attributes ) throws ActionException { // We are just beginning, reset variables appender = null ; inError = false ; String className = attributes . getValue ( CLASS_ATTRIBUTE ) ; if ( OptionHelper . isEmpty ( className ) ) { addError ( \"Missing class name for appender. Near [\" + localName + \"] line \" + getLineNumber ( ec ) ) ; inError = true ; return ; } try { addInfo ( \"About to instantiate appender of type [\" + className + \"]\" ) ; warnDeprecated ( className ) ; appender = ( Appender < E > ) OptionHelper . instantiateByClassName ( className , ch . qos . logback . core . Appender . class , context ) ; appender . setContext ( context ) ; String appenderName = ec . subst ( attributes . getValue ( NAME_ATTRIBUTE ) ) ; if ( OptionHelper . isEmpty ( appenderName ) ) { addWarn ( \"No appender name given for appender of type \" + className + \"].\" ) ; } else { appender . setName ( appenderName ) ; addInfo ( \"Naming appender as [\" + appenderName + \"]\" ) ; } // The execution context contains a bag which contains the appenders // created thus far. HashMap < String , Appender < E > > appenderBag = ( HashMap < String , Appender < E > > ) ec . getObjectMap ( ) . get ( ActionConst . APPENDER_BAG ) ; // add the appender just created to the appender bag. appenderBag . put ( appenderName , appender ) ; ec . pushObject ( appender ) ; } catch ( Exception oops ) { inError = true ; addError ( \"Could not create an Appender of type [\" + className + \"].\" , oops ) ; throw new ActionException ( oops ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Once the children elements are also parsed now is the time to activate the appender options . [CODESPLIT] public void end ( InterpretationContext ec , String name ) { if ( inError ) { return ; } if ( appender instanceof LifeCycle ) { ( ( LifeCycle ) appender ) . start ( ) ; } Object o = ec . peekObject ( ) ; if ( o != appender ) { addWarn ( \"The object at the of the stack is not the appender named [\" + appender . getName ( ) + \"] pushed earlier.\" ) ; } else { ec . popObject ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override final public boolean isTooSoon ( long currentTime ) { boolean maskMatch = ( ( invocationCounter ++ ) & mask ) == mask ; if ( maskMatch ) { if ( currentTime < this . lowerLimitForMaskMatch ) { increaseMask ( ) ; } updateLimits ( currentTime ) ; } else { if ( currentTime > this . upperLimitForNoMaskMatch ) { decreaseMask ( ) ; updateLimits ( currentTime ) ; return false ; } } return ! maskMatch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void stop ( ) throws IOException { listener . close ( ) ; accept ( new ClientVisitor < T > ( ) { public void visit ( T client ) { client . close ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( ClientVisitor < T > visitor ) { Collection < T > clients = copyClients ( ) ; for ( T client : clients ) { try { visitor . visit ( client ) ; } catch ( RuntimeException ex ) { addError ( client + \": \" + ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a copy of the collection of all clients that are presently being tracked by the server . [CODESPLIT] private Collection < T > copyClients ( ) { clientsLock . lock ( ) ; try { Collection < T > copy = new ArrayList < T > ( clients ) ; return copy ; } finally { clientsLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void run ( ) { setRunning ( true ) ; try { addInfo ( \"listening on \" + listener ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { T client = listener . acceptClient ( ) ; if ( ! configureClient ( client ) ) { addError ( client + \": connection dropped\" ) ; client . close ( ) ; continue ; } try { executor . execute ( new ClientWrapper ( client ) ) ; } catch ( RejectedExecutionException ex ) { addError ( client + \": connection dropped\" ) ; client . close ( ) ; } } } catch ( InterruptedException ex ) { assert true ; // ok... we'll shut down } catch ( Exception ex ) { addError ( \"listener: \" + ex ) ; } setRunning ( false ) ; addInfo ( \"shutting down\" ) ; listener . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a client to the collection of those being tracked by the server . [CODESPLIT] private void addClient ( T client ) { clientsLock . lock ( ) ; try { clients . add ( client ) ; } finally { clientsLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a client from the collection of those being tracked by the server . [CODESPLIT] private void removeClient ( T client ) { clientsLock . lock ( ) ; try { clients . remove ( client ) ; } finally { clientsLock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a context value ( the <code > val< / code > parameter ) as identified with the <code > key< / code > parameter into the current thread s context map . Note that contrary to log4j the <code > val< / code > parameter can be null . <p > If the current thread does not have a context map it is created as a side effect of this call . [CODESPLIT] public void put ( String key , String val ) throws IllegalArgumentException { if ( key == null ) { throw new IllegalArgumentException ( \"key cannot be null\" ) ; } Map < String , String > oldMap = copyOnThreadLocal . get ( ) ; Integer lastOp = getAndSetLastOperation ( WRITE_OPERATION ) ; if ( wasLastOpReadOrNull ( lastOp ) || oldMap == null ) { Map < String , String > newMap = duplicateAndInsertNewMap ( oldMap ) ; newMap . put ( key , val ) ; } else { oldMap . put ( key , val ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the the context identified by the <code > key< / code > parameter . [CODESPLIT] public void remove ( String key ) { if ( key == null ) { return ; } Map < String , String > oldMap = copyOnThreadLocal . get ( ) ; if ( oldMap == null ) return ; Integer lastOp = getAndSetLastOperation ( WRITE_OPERATION ) ; if ( wasLastOpReadOrNull ( lastOp ) ) { Map < String , String > newMap = duplicateAndInsertNewMap ( oldMap ) ; newMap . remove ( key ) ; } else { oldMap . remove ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the context identified by the <code > key< / code > parameter . [CODESPLIT] public String get ( String key ) { final Map < String , String > map = copyOnThreadLocal . get ( ) ; if ( ( map != null ) && ( key != null ) ) { return map . get ( key ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the keys in the MDC as a { [CODESPLIT] public Set < String > getKeys ( ) { Map < String , String > map = getPropertyMap ( ) ; if ( map != null ) { return map . keySet ( ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a copy of the current thread s context map . Returned value may be null . [CODESPLIT] public Map < String , String > getCopyOfContextMap ( ) { Map < String , String > hashMap = copyOnThreadLocal . get ( ) ; if ( hashMap == null ) { return null ; } else { return new HashMap < String , String > ( hashMap ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert <code > val< / code > a String parameter to an object of a given type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Object convertArg ( ContextAware ca , String val , Class < ? > type ) { if ( val == null ) { return null ; } String v = val . trim ( ) ; if ( String . class . isAssignableFrom ( type ) ) { return v ; } else if ( Integer . TYPE . isAssignableFrom ( type ) ) { return Integer . valueOf ( v ) ; } else if ( Long . TYPE . isAssignableFrom ( type ) ) { return Long . valueOf ( v ) ; } else if ( Float . TYPE . isAssignableFrom ( type ) ) { return Float . valueOf ( v ) ; } else if ( Double . TYPE . isAssignableFrom ( type ) ) { return Double . valueOf ( v ) ; } else if ( Boolean . TYPE . isAssignableFrom ( type ) ) { if ( \"true\" . equalsIgnoreCase ( v ) ) { return Boolean . TRUE ; } else if ( \"false\" . equalsIgnoreCase ( v ) ) { return Boolean . FALSE ; } } else if ( type . isEnum ( ) ) { return convertToEnum ( ca , v , ( Class < ? extends Enum < ? > > ) type ) ; } else if ( StringToObjectConverter . followsTheValueOfConvention ( type ) ) { return convertByValueOfMethod ( ca , type , v ) ; } else if ( isOfTypeCharset ( type ) ) { return convertToCharset ( ca , val ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returned value may be null and in most cases it is null . [CODESPLIT] public static Method getValueOfMethod ( Class < ? > type ) { try { return type . getMethod ( CoreConstants . VALUE_OF , STING_CLASS_PARAMETER ) ; } catch ( NoSuchMethodException e ) { return null ; } catch ( SecurityException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loop through the filters in the chain . As soon as a filter decides on ACCEPT or DENY then that value is returned . If all of the filters return NEUTRAL then NEUTRAL is returned . [CODESPLIT] public FilterReply getTurboFilterChainDecision ( final Marker marker , final Logger logger , final Level level , final String format , final Object [ ] params , final Throwable t ) { final int size = size ( ) ; //    if (size == 0) { //      return FilterReply.NEUTRAL; //    } if ( size == 1 ) { try { TurboFilter tf = get ( 0 ) ; return tf . decide ( marker , logger , level , format , params , t ) ; } catch ( IndexOutOfBoundsException iobe ) { return FilterReply . NEUTRAL ; } } Object [ ] tfa = toArray ( ) ; final int len = tfa . length ; for ( int i = 0 ; i < len ; i ++ ) { //for (TurboFilter tf : this) { final TurboFilter tf = ( TurboFilter ) tfa [ i ] ; final FilterReply r = tf . decide ( marker , logger , level , format , params , t ) ; if ( r == FilterReply . DENY || r == FilterReply . ACCEPT ) { return r ; } } return FilterReply . NEUTRAL ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected RemoteAppenderClient createClient ( String id , Socket socket ) throws IOException { return new RemoteAppenderStreamClient ( id , socket ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new rule i . e . a pattern action pair to the rule store . <p > Note that the added action s LoggerRepository will be set in the process . [CODESPLIT] public void addRule ( ElementSelector elementSelector , Action action ) { action . setContext ( context ) ; List < Action > a4p = rules . get ( elementSelector ) ; if ( a4p == null ) { a4p = new ArrayList < Action > ( ) ; rules . put ( elementSelector , a4p ) ; } a4p . add ( action ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "match for x / y / * has higher priority than matches for x / * [CODESPLIT] public List < Action > matchActions ( ElementPath elementPath ) { List < Action > actionList ; if ( ( actionList = fullPathMatch ( elementPath ) ) != null ) { return actionList ; } else if ( ( actionList = suffixMatch ( elementPath ) ) != null ) { return actionList ; } else if ( ( actionList = prefixMatch ( elementPath ) ) != null ) { return actionList ; } else if ( ( actionList = middleMatch ( elementPath ) ) != null ) { return actionList ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Suffix matches are matches of type * / x / y [CODESPLIT] List < Action > suffixMatch ( ElementPath elementPath ) { int max = 0 ; ElementSelector longestMatchingElementSelector = null ; for ( ElementSelector selector : rules . keySet ( ) ) { if ( isSuffixPattern ( selector ) ) { int r = selector . getTailMatchLength ( elementPath ) ; if ( r > max ) { max = r ; longestMatchingElementSelector = selector ; } } } if ( longestMatchingElementSelector != null ) { return rules . get ( longestMatchingElementSelector ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Heuristically determines whether the current OS is Android [CODESPLIT] static public boolean isAndroidOS ( ) { String osname = OptionHelper . getSystemProperty ( \"os.name\" ) ; String root = OptionHelper . getEnv ( \"ANDROID_ROOT\" ) ; String data = OptionHelper . getEnv ( \"ANDROID_DATA\" ) ; return osname != null && osname . contains ( \"Linux\" ) && root != null && root . contains ( \"/system\" ) && data != null && data . contains ( \"/data\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Package access for testing purposes . [CODESPLIT] void init ( ) { try { try { new ContextInitializer ( defaultLoggerContext ) . autoConfig ( ) ; } catch ( JoranException je ) { Util . report ( \"Failed to auto configure default logger context\" , je ) ; } // logback-292 if ( ! StatusUtil . contextHasStatusListener ( defaultLoggerContext ) ) { StatusPrinter . printInCaseOfErrorsOrWarnings ( defaultLoggerContext ) ; } contextSelectorBinder . init ( defaultLoggerContext , KEY ) ; initialized = true ; } catch ( Exception t ) { // see LOGBACK-1159 Util . report ( \"Failed to instantiate [\" + LoggerContext . class . getName ( ) + \"]\" , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the set of files matching the stemRegex as found in directory . A stemRegex does not contain any slash characters or any folder separators . [CODESPLIT] public static File [ ] filesInFolderMatchingStemRegex ( File file , final String stemRegex ) { if ( file == null ) { return new File [ 0 ] ; } if ( ! file . exists ( ) || ! file . isDirectory ( ) ) { return new File [ 0 ] ; } return file . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . matches ( stemRegex ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void start ( ) { if ( isStarted ( ) ) return ; if ( getContext ( ) == null ) { throw new IllegalStateException ( \"context not set\" ) ; } if ( shouldStart ( ) ) { getContext ( ) . getScheduledExecutorService ( ) . execute ( getRunnableTask ( ) ) ; started = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void stop ( ) { if ( ! isStarted ( ) ) return ; try { onStop ( ) ; } catch ( RuntimeException ex ) { addError ( \"on stop: \" + ex , ex ) ; } started = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( ) { try { SSLContext sslContext = getSsl ( ) . createContext ( this ) ; SSLParametersConfiguration parameters = getSsl ( ) . getParameters ( ) ; parameters . setContext ( getContext ( ) ) ; socketFactory = new ConfigurableSSLServerSocketFactory ( parameters , sslContext . getServerSocketFactory ( ) ) ; super . start ( ) ; } catch ( Exception ex ) { addError ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print status messages retrospectively [CODESPLIT] private void retrospectivePrint ( ) { if ( context == null ) return ; long now = System . currentTimeMillis ( ) ; StatusManager sm = context . getStatusManager ( ) ; List < Status > statusList = sm . getCopyOfStatusList ( ) ; for ( Status status : statusList ) { long timestampOfStatusMesage = status . getDate ( ) ; if ( isElapsedTimeLongerThanThreshold ( now , timestampOfStatusMesage ) ) { print ( status ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the integer value corresponding to the named syslog facility . [CODESPLIT] static public int facilityStringToint ( String facilityStr ) { if ( \"KERN\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_KERN ; } else if ( \"USER\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_USER ; } else if ( \"MAIL\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_MAIL ; } else if ( \"DAEMON\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_DAEMON ; } else if ( \"AUTH\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_AUTH ; } else if ( \"SYSLOG\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_SYSLOG ; } else if ( \"LPR\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LPR ; } else if ( \"NEWS\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_NEWS ; } else if ( \"UUCP\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_UUCP ; } else if ( \"CRON\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_CRON ; } else if ( \"AUTHPRIV\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_AUTHPRIV ; } else if ( \"FTP\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_FTP ; } else if ( \"NTP\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_NTP ; } else if ( \"AUDIT\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_AUDIT ; } else if ( \"ALERT\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_ALERT ; } else if ( \"CLOCK\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_CLOCK ; } else if ( \"LOCAL0\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL0 ; } else if ( \"LOCAL1\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL1 ; } else if ( \"LOCAL2\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL2 ; } else if ( \"LOCAL3\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL3 ; } else if ( \"LOCAL4\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL4 ; } else if ( \"LOCAL5\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL5 ; } else if ( \"LOCAL6\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL6 ; } else if ( \"LOCAL7\" . equalsIgnoreCase ( facilityStr ) ) { return SyslogConstants . LOG_LOCAL7 ; } else { throw new IllegalArgumentException ( facilityStr + \" is not a valid syslog facility string\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The <b > Facility< / b > option must be set one of the strings KERN USER MAIL DAEMON AUTH SYSLOG LPR NEWS UUCP CRON AUTHPRIV FTP NTP AUDIT ALERT CLOCK LOCAL0 LOCAL1 LOCAL2 LOCAL3 LOCAL4 LOCAL5 LOCAL6 LOCAL7 . Case is not important . [CODESPLIT] public void setFacility ( String facilityStr ) { if ( facilityStr != null ) { facilityStr = facilityStr . trim ( ) ; } this . facilityStr = facilityStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a node has already been visited already by checking the cycleDetectionStack for it s existence . This method is used -- rather than Stack . contains () -- because we want to ignore the Node s next attribute when comparing for equality . [CODESPLIT] private boolean haveVisitedNodeAlready ( Node node , Stack < Node > cycleDetectionStack ) { for ( Node cycleNode : cycleDetectionStack ) { if ( equalNodes ( node , cycleNode ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a file object from a file path to a SQLite database [CODESPLIT] public File getDatabaseFile ( String filename ) { File dbFile = null ; if ( filename != null && filename . trim ( ) . length ( ) > 0 ) { dbFile = new File ( filename ) ; } if ( dbFile == null || dbFile . isDirectory ( ) ) { dbFile = new File ( new AndroidContextUtil ( ) . getDatabasePath ( \"logback.db\" ) ) ; } return dbFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void start ( ) { this . started = false ; File dbfile = getDatabaseFile ( this . filename ) ; if ( dbfile == null ) { addError ( \"Cannot determine database filename\" ) ; return ; } boolean dbOpened = false ; try { dbfile . getParentFile ( ) . mkdirs ( ) ; addInfo ( \"db path: \" + dbfile . getAbsolutePath ( ) ) ; this . db = SQLiteDatabase . openOrCreateDatabase ( dbfile . getPath ( ) , null ) ; dbOpened = true ; } catch ( SQLiteException e ) { addError ( \"Cannot open database\" , e ) ; } if ( dbOpened ) { if ( dbNameResolver == null ) { dbNameResolver = new DefaultDBNameResolver ( ) ; } insertExceptionSQL = SQLBuilder . buildInsertExceptionSQL ( dbNameResolver ) ; insertPropertiesSQL = SQLBuilder . buildInsertPropertiesSQL ( dbNameResolver ) ; insertSQL = SQLBuilder . buildInsertSQL ( dbNameResolver ) ; try { this . db . execSQL ( SQLBuilder . buildCreateLoggingEventTableSQL ( dbNameResolver ) ) ; this . db . execSQL ( SQLBuilder . buildCreatePropertyTableSQL ( dbNameResolver ) ) ; this . db . execSQL ( SQLBuilder . buildCreateExceptionTableSQL ( dbNameResolver ) ) ; clearExpiredLogs ( this . db ) ; super . start ( ) ; this . started = true ; } catch ( SQLiteException e ) { addError ( \"Cannot create database tables\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes expired logs from the database [CODESPLIT] private void clearExpiredLogs ( SQLiteDatabase db ) { if ( lastCheckExpired ( this . maxHistory , this . lastCleanupTime ) ) { this . lastCleanupTime = this . clock . currentTimeMillis ( ) ; this . getLogCleaner ( ) . performLogCleanup ( db , this . maxHistory ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether it s time to clear expired logs [CODESPLIT] private boolean lastCheckExpired ( Duration expiry , long lastCleanupTime ) { boolean isExpired = false ; if ( expiry != null && expiry . getMilliseconds ( ) > 0 ) { final long now = this . clock . currentTimeMillis ( ) ; final long timeDiff = now - lastCleanupTime ; isExpired = ( lastCleanupTime <= 0 ) || ( timeDiff >= expiry . getMilliseconds ( ) ) ; } return isExpired ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the { [CODESPLIT] public SQLiteLogCleaner getLogCleaner ( ) { if ( this . logCleaner == null ) { final Clock thisClock = this . clock ; this . logCleaner = new SQLiteLogCleaner ( ) { public void performLogCleanup ( SQLiteDatabase db , Duration expiry ) { final long expiryMs = thisClock . currentTimeMillis ( ) - expiry . getMilliseconds ( ) ; final String deleteExpiredLogsSQL = SQLBuilder . buildDeleteExpiredLogsSQL ( dbNameResolver , expiryMs ) ; db . execSQL ( deleteExpiredLogsSQL ) ; } } ; } return this . logCleaner ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void append ( ILoggingEvent eventObject ) { if ( isStarted ( ) ) { try { clearExpiredLogs ( db ) ; SQLiteStatement stmt = db . compileStatement ( insertSQL ) ; try { db . beginTransaction ( ) ; long eventId = subAppend ( eventObject , stmt ) ; if ( eventId != - 1 ) { secondarySubAppend ( eventObject , eventId ) ; db . setTransactionSuccessful ( ) ; } } finally { if ( db . inTransaction ( ) ) { db . endTransaction ( ) ; } stmt . close ( ) ; } } catch ( Throwable e ) { addError ( \"Cannot append event\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the main details of a log event into the database [CODESPLIT] private long subAppend ( ILoggingEvent event , SQLiteStatement insertStatement ) throws SQLException { bindLoggingEvent ( insertStatement , event ) ; bindLoggingEventArguments ( insertStatement , event . getArgumentArray ( ) ) ; // This is expensive... should we do it every time? bindCallerData ( insertStatement , event . getCallerData ( ) ) ; long insertId = - 1 ; try { insertId = insertStatement . executeInsert ( ) ; } catch ( SQLiteException e ) { addWarn ( \"Failed to insert loggingEvent\" , e ) ; } return insertId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing row of an event with the secondary details of the event . This includes MDC properties and any exception information . [CODESPLIT] private void secondarySubAppend ( ILoggingEvent event , long eventId ) throws SQLException { Map < String , String > mergedMap = mergePropertyMaps ( event ) ; insertProperties ( mergedMap , eventId ) ; if ( event . getThrowableProxy ( ) != null ) { insertThrowable ( event . getThrowableProxy ( ) , eventId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the main details of a log event to a SQLite statement s parameters [CODESPLIT] private void bindLoggingEvent ( SQLiteStatement stmt , ILoggingEvent event ) throws SQLException { stmt . bindLong ( TIMESTMP_INDEX , event . getTimeStamp ( ) ) ; stmt . bindString ( FORMATTED_MESSAGE_INDEX , event . getFormattedMessage ( ) ) ; stmt . bindString ( LOGGER_NAME_INDEX , event . getLoggerName ( ) ) ; stmt . bindString ( LEVEL_STRING_INDEX , event . getLevel ( ) . toString ( ) ) ; stmt . bindString ( THREAD_NAME_INDEX , event . getThreadName ( ) ) ; stmt . bindLong ( REFERENCE_FLAG_INDEX , computeReferenceMask ( event ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a logging event s arguments ( e . g . <code > logger . debug ( x = {} y = {} arg1 arg2 ) < / code > ) to a SQLite statement s parameters [CODESPLIT] private void bindLoggingEventArguments ( SQLiteStatement stmt , Object [ ] argArray ) throws SQLException { int arrayLen = argArray != null ? argArray . length : 0 ; for ( int i = 0 ; i < arrayLen && i < 4 ; i ++ ) { stmt . bindString ( ARG0_INDEX + i , asStringTruncatedTo254 ( argArray [ i ] ) ) ; } // //    // set remaining columns to \"\" //    for (int i = arrayLen; i < 4; i++) { //      stmt.bindString(ARG0_INDEX+i, \"\"); //    } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the first 254 characters of an object s string representation . This is used to truncate a logging event s argument binding if necessary . [CODESPLIT] private String asStringTruncatedTo254 ( Object o ) { String s = null ; if ( o != null ) { s = o . toString ( ) ; } if ( s != null && s . length ( ) > 254 ) { s = s . substring ( 0 , 254 ) ; } return s == null ? \"\" : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the reference mask for a logging event including flags to indicate whether MDC properties or exception info is available for the event . [CODESPLIT] private static short computeReferenceMask ( ILoggingEvent event ) { short mask = 0 ; int mdcPropSize = 0 ; if ( event . getMDCPropertyMap ( ) != null ) { mdcPropSize = event . getMDCPropertyMap ( ) . keySet ( ) . size ( ) ; } int contextPropSize = 0 ; if ( event . getLoggerContextVO ( ) . getPropertyMap ( ) != null ) { contextPropSize = event . getLoggerContextVO ( ) . getPropertyMap ( ) . size ( ) ; } if ( mdcPropSize > 0 || contextPropSize > 0 ) { mask = PROPERTIES_EXIST ; } if ( event . getThrowableProxy ( ) != null ) { mask |= EXCEPTION_EXISTS ; } return mask ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges a log event s properties with the properties of the logger context . The context properties are first in the map and then the event s properties are appended . [CODESPLIT] private Map < String , String > mergePropertyMaps ( ILoggingEvent event ) { Map < String , String > mergedMap = new HashMap < String , String > ( ) ; // we add the context properties first, then the event properties, since // we consider that event-specific properties should have priority over // context-wide properties. Map < String , String > loggerContextMap = event . getLoggerContextVO ( ) . getPropertyMap ( ) ; if ( loggerContextMap != null ) { mergedMap . putAll ( loggerContextMap ) ; } Map < String , String > mdcMap = event . getMDCPropertyMap ( ) ; if ( mdcMap != null ) { mergedMap . putAll ( mdcMap ) ; } return mergedMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing row with property details ( context properties and event s properties ) . [CODESPLIT] private void insertProperties ( Map < String , String > mergedMap , long eventId ) throws SQLException { if ( mergedMap . size ( ) > 0 ) { SQLiteStatement stmt = db . compileStatement ( insertPropertiesSQL ) ; try { for ( Entry < String , String > entry : mergedMap . entrySet ( ) ) { stmt . bindLong ( 1 , eventId ) ; stmt . bindString ( 2 , entry . getKey ( ) ) ; stmt . bindString ( 3 , entry . getValue ( ) ) ; stmt . executeInsert ( ) ; } } finally { stmt . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the calling function s details ( filename line etc . ) to a SQLite statement s arguments [CODESPLIT] private void bindCallerData ( SQLiteStatement stmt , StackTraceElement [ ] callerDataArray ) throws SQLException { if ( callerDataArray != null && callerDataArray . length > 0 ) { StackTraceElement callerData = callerDataArray [ 0 ] ; if ( callerData != null ) { bindString ( stmt , CALLER_FILENAME_INDEX , callerData . getFileName ( ) ) ; bindString ( stmt , CALLER_CLASS_INDEX , callerData . getClassName ( ) ) ; bindString ( stmt , CALLER_METHOD_INDEX , callerData . getMethodName ( ) ) ; bindString ( stmt , CALLER_LINE_INDEX , Integer . toString ( callerData . getLineNumber ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts an exception into the logging_exceptions table [CODESPLIT] private void insertException ( SQLiteStatement stmt , String txt , short i , long eventId ) throws SQLException { stmt . bindLong ( 1 , eventId ) ; stmt . bindLong ( 2 , i ) ; stmt . bindString ( 3 , txt ) ; stmt . executeInsert ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of prefix components that this pattern has in common with the pattern p passed as parameter . By prefix components we mean the components at the beginning of the pattern . [CODESPLIT] public int getPrefixMatchLength ( ElementPath p ) { if ( p == null ) { return 0 ; } int lSize = this . partList . size ( ) ; int rSize = p . partList . size ( ) ; // no match possible for empty sets if ( ( lSize == 0 ) || ( rSize == 0 ) ) { return 0 ; } int minLen = ( lSize <= rSize ) ? lSize : rSize ; int match = 0 ; for ( int i = 0 ; i < minLen ; i ++ ) { String l = this . partList . get ( i ) ; String r = p . partList . get ( i ) ; if ( equalityCheck ( l , r ) ) { match ++ ; } else { break ; } } return match ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "different status objects lying on the same cycle [CODESPLIT] public synchronized int getEffectiveLevel ( ) { int result = level ; int effLevel ; Iterator it = iterator ( ) ; Status s ; while ( it . hasNext ( ) ) { s = ( Status ) it . next ( ) ; effLevel = s . getEffectiveLevel ( ) ; if ( effLevel > result ) { result = effLevel ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses JavaBeans { [CODESPLIT] protected void introspect ( ) { try { propertyDescriptors = Introspector . getPropertyDescriptors ( this . objClass ) ; methodDescriptors = Introspector . getMethodDescriptors ( this . objClass ) ; } catch ( IntrospectionException ex ) { addError ( \"Failed to introspect \" + obj + \": \" + ex . getMessage ( ) ) ; propertyDescriptors = new PropertyDescriptor [ 0 ] ; methodDescriptors = new MethodDescriptor [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a property on this PropertySetter s Object . If successful this method will invoke a setter method on the underlying Object . The setter is the one for the specified property name and the value is determined partly from the setter argument type and partly from the value specified in the call to this method . [CODESPLIT] public void setProperty ( String name , String value ) { if ( value == null ) { return ; } name = Introspector . decapitalize ( name ) ; PropertyDescriptor prop = getPropertyDescriptor ( name ) ; if ( prop == null ) { addWarn ( \"No such property [\" + name + \"] in \" + objClass . getName ( ) + \".\" ) ; } else { try { setProperty ( prop , name , value ) ; } catch ( PropertySetterException ex ) { addWarn ( \"Failed to set property [\" + name + \"] to value \\\"\" + value + \"\\\". \" , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the named property given a { @link PropertyDescriptor } . [CODESPLIT] public void setProperty ( PropertyDescriptor prop , String name , String value ) throws PropertySetterException { Method setter = prop . getWriteMethod ( ) ; if ( setter == null ) { throw new PropertySetterException ( \"No setter for property [\" + name + \"].\" ) ; } Class < ? > [ ] paramTypes = setter . getParameterTypes ( ) ; if ( paramTypes . length != 1 ) { throw new PropertySetterException ( \"#params for setter != 1\" ) ; } Object arg ; try { arg = StringToObjectConverter . convertArg ( this , value , paramTypes [ 0 ] ) ; } catch ( Throwable t ) { throw new PropertySetterException ( \"Conversion to type [\" + paramTypes [ 0 ] + \"] failed. \" , t ) ; } if ( arg == null ) { throw new PropertySetterException ( \"Conversion to type [\" + paramTypes [ 0 ] + \"] failed.\" ) ; } try { setter . invoke ( obj , arg ) ; } catch ( Exception ex ) { throw new PropertySetterException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Can the given clazz instantiable with certainty? [CODESPLIT] private boolean isUnequivocallyInstantiable ( Class < ? > clazz ) { if ( clazz . isInterface ( ) ) { return false ; } // checking for constructors would be more elegant, but in // classes without any declared constructors, Class.getConstructor() // returns null. Object o ; try { o = clazz . getDeclaredConstructor ( ) . newInstance ( ) ; if ( o != null ) { return true ; } else { return false ; } } catch ( InstantiationException e ) { return false ; } catch ( IllegalAccessException e ) { return false ; } catch ( NoSuchMethodException e ) { return false ; } catch ( InvocationTargetException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the string true if the { @link #setResource ( String ) resource } specified by the user is available on the class path false otherwise . [CODESPLIT] public String getPropertyValue ( ) { if ( OptionHelper . isEmpty ( resourceStr ) ) { addError ( \"The \\\"resource\\\" property must be set.\" ) ; return null ; } URL resourceURL = Loader . getResourceBySelfClassLoader ( resourceStr ) ; return booleanAsStr ( resourceURL != null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Child threads should get a copy of the parent s hashmap . [CODESPLIT] @ Override protected HashMap < String , String > childValue ( HashMap < String , String > parentValue ) { if ( parentValue == null ) { return null ; } else { return new HashMap < String , String > ( parentValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Eopt = E|~ [CODESPLIT] private Node Eopt ( ) throws ScanException { Token next = peekAtCurentToken ( ) ; if ( next == null ) { return null ; } else { return E ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "T = LITERAL | $ { V } [CODESPLIT] private Node T ( ) throws ScanException { Token t = peekAtCurentToken ( ) ; switch ( t . type ) { case LITERAL : advanceTokenPointer ( ) ; return makeNewLiteralNode ( t . payload ) ; case CURLY_LEFT : advanceTokenPointer ( ) ; Node innerNode = C ( ) ; Token right = peekAtCurentToken ( ) ; expectCurlyRight ( right ) ; advanceTokenPointer ( ) ; Node curlyLeft = makeNewLiteralNode ( CoreConstants . LEFT_ACCOLADE ) ; curlyLeft . append ( innerNode ) ; curlyLeft . append ( makeNewLiteralNode ( CoreConstants . RIGHT_ACCOLADE ) ) ; return curlyLeft ; case START : advanceTokenPointer ( ) ; Node v = V ( ) ; Token w = peekAtCurentToken ( ) ; expectCurlyRight ( w ) ; advanceTokenPointer ( ) ; return v ; default : return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "V = E ( : = E|~ ) [CODESPLIT] private Node V ( ) throws ScanException { Node e = E ( ) ; Node variable = new Node ( Node . Type . VARIABLE , e ) ; Token t = peekAtCurentToken ( ) ; if ( isDefaultToken ( t ) ) { advanceTokenPointer ( ) ; Node def = E ( ) ; variable . defaultPart = def ; } return variable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "C = E ( : = E|~ ) [CODESPLIT] private Node C ( ) throws ScanException { Node e0 = E ( ) ; Token t = peekAtCurentToken ( ) ; if ( isDefaultToken ( t ) ) { advanceTokenPointer ( ) ; Node literal = makeNewLiteralNode ( CoreConstants . DEFAULT_VALUE_SEPARATOR ) ; e0 . append ( literal ) ; Node e1 = E ( ) ; e0 . append ( e1 ) ; } return e0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes an include [CODESPLIT] @ Override protected void processInclude ( InterpretationContext ic , URL url ) throws JoranException { InputStream in = openURL ( url ) ; try { if ( in != null ) { // add URL to watch list in case the \"scan\" flag is true, in // which case this URL is periodically checked for changes ConfigurationWatchListUtil . addToWatchList ( getContext ( ) , url ) ; // parse the include SaxEventRecorder recorder = createRecorder ( in , url ) ; recorder . setContext ( getContext ( ) ) ; recorder . recordEvents ( in ) ; // remove the leading/trailing tags (<included> or <configuration>) trimHeadAndTail ( recorder ) ; ic . getJoranInterpreter ( ) . getEventPlayer ( ) . addEventsDynamically ( recorder . getSaxEventList ( ) , this . eventOffset ) ; } } catch ( JoranException e ) { optionalWarning ( \"Failed processing [\" + url . toString ( ) + \"]\" , e ) ; } finally { close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens the given URL logging any exceptions [CODESPLIT] private InputStream openURL ( URL url ) { try { return url . openStream ( ) ; } catch ( IOException e ) { optionalWarning ( \"Failed to open [\" + url . toString ( ) + \"]\" , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the head tag and tail tag if they are named either included or configuration [CODESPLIT] private void trimHeadAndTail ( SaxEventRecorder recorder ) { List < SaxEvent > saxEventList = recorder . getSaxEventList ( ) ; if ( saxEventList . size ( ) == 0 ) { return ; } boolean includedTagFound = false ; boolean configTagFound = false ; // find opening element SaxEvent first = saxEventList . get ( 0 ) ; if ( first != null ) { String elemName = getEventName ( first ) ; includedTagFound = INCLUDED_TAG . equalsIgnoreCase ( elemName ) ; configTagFound = CONFIG_TAG . equalsIgnoreCase ( elemName ) ; } // if opening element found, remove it, and then remove the closing element if ( includedTagFound || configTagFound ) { saxEventList . remove ( 0 ) ; final int listSize = saxEventList . size ( ) ; if ( listSize == 0 ) { return ; } final int lastIndex = listSize - 1 ; SaxEvent last = saxEventList . get ( lastIndex ) ; if ( last != null ) { String elemName = getEventName ( last ) ; if ( ( includedTagFound && INCLUDED_TAG . equalsIgnoreCase ( elemName ) ) || ( configTagFound && CONFIG_TAG . equalsIgnoreCase ( elemName ) ) ) { saxEventList . remove ( lastIndex ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the event name of a { [CODESPLIT] private String getEventName ( SaxEvent event ) { return event . qName . length ( ) > 0 ? event . qName : event . localName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the server . [CODESPLIT] protected boolean shouldStart ( ) { ServerSocket serverSocket = null ; try { serverSocket = getServerSocketFactory ( ) . createServerSocket ( getPort ( ) , getBacklog ( ) , getInetAddress ( ) ) ; ServerListener < RemoteAppenderClient > listener = createServerListener ( serverSocket ) ; runner = createServerRunner ( listener , getContext ( ) . getScheduledExecutorService ( ) ) ; runner . setContext ( getContext ( ) ) ; return true ; } catch ( Exception ex ) { addError ( \"server startup error: \" + ex , ex ) ; CloseUtil . closeQuietly ( serverSocket ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void onStop ( ) { try { if ( runner == null ) return ; runner . stop ( ) ; } catch ( IOException ex ) { addError ( \"server shutdown error: \" + ex , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test whether this error is transient . [CODESPLIT] public boolean isTransient ( ) { Throwable cause = getCause ( ) ; if ( cause == null ) { return isServerError ( statusCode ) ; } else if ( cause instanceof AlgoliaException ) { return ( ( AlgoliaException ) cause ) . isTransient ( ) ; } else if ( cause instanceof IOException ) { return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the default hosts for Algolia Places . [CODESPLIT] private void setDefaultHosts ( ) { List < String > fallbackHosts = Arrays . asList ( \"places-1.algolianet.com\" , \"places-2.algolianet.com\" , \"places-3.algolianet.com\" ) ; Collections . shuffle ( fallbackHosts ) ; List < String > hosts = new ArrayList <> ( fallbackHosts . size ( ) + 1 ) ; hosts . add ( \"places-dsn.algolia.net\" ) ; hosts . addAll ( fallbackHosts ) ; String [ ] hostsArray = hosts . toArray ( new String [ hosts . size ( ) ] ) ; setReadHosts ( hostsArray ) ; setWriteHosts ( hostsArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for places . [CODESPLIT] public Request searchAsync ( @ NonNull PlacesQuery params , @ NonNull CompletionHandler completionHandler ) { final PlacesQuery paramsCopy = new PlacesQuery ( params ) ; return new AsyncTaskRequest ( completionHandler ) { @ Override protected @ NonNull JSONObject run ( ) throws AlgoliaException { return search ( paramsCopy ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for places . [CODESPLIT] protected JSONObject search ( @ NonNull PlacesQuery params ) throws AlgoliaException { try { JSONObject body = new JSONObject ( ) . put ( \"params\" , params . build ( ) ) ; return postRequest ( \"/1/places/query\" , /* urlParameters: */ null , body . toString ( ) , true /* readOperation */ , /* requestOptions: */ null ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a place by its objectID . [CODESPLIT] public JSONObject getByObjectID ( @ NonNull String objectID ) throws AlgoliaException { return getRequest ( \"/1/places/\" + objectID , /* urlParameters: */ null , false , /* requestOptions: */ null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a data selection query to this index . NOTE : All queries are implicitly browse queries ( and not search queries ) . [CODESPLIT] public void addDataSelectionQuery ( @ NonNull DataSelectionQuery query ) { mirrorSettings . addQuery ( query ) ; mirrorSettings . setQueriesModificationDate ( new Date ( ) ) ; saveMirrorSettings ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all data selection queries associated to this index . [CODESPLIT] public void setDataSelectionQueries ( @ NonNull DataSelectionQuery ... queries ) { DataSelectionQuery [ ] oldQueries = mirrorSettings . getQueries ( ) ; if ( ! Arrays . equals ( oldQueries , queries ) ) { mirrorSettings . setQueries ( queries ) ; mirrorSettings . setQueriesModificationDate ( new Date ( ) ) ; saveMirrorSettings ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the delay after which data is considered to be obsolete . [CODESPLIT] public void setDelayBetweenSyncs ( long duration , @ NonNull TimeUnit unit ) { this . setDelayBetweenSyncs ( TimeUnit . MILLISECONDS . convert ( duration , unit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lazy instantiate the local index . [CODESPLIT] private synchronized void ensureLocalIndex ( ) { if ( localIndex == null ) { localIndex = new LocalIndex ( getClient ( ) . getRootDataDir ( ) . getAbsolutePath ( ) , getClient ( ) . getApplicationID ( ) , getRawIndexName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------- [CODESPLIT] private void saveMirrorSettings ( ) { File dataDir = getDataDir ( ) ; if ( ! dataDir . exists ( ) ) { dataDir . mkdirs ( ) ; } mirrorSettings . save ( getSettingsFile ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch a sync . If a sync is already running this call is ignored . Otherwise the sync is enqueued and runs in the background . [CODESPLIT] public void sync ( ) { if ( getDataSelectionQueries ( ) . length == 0 ) { throw new IllegalStateException ( \"Cannot sync with empty data selection queries\" ) ; } synchronized ( this ) { if ( syncing ) return ; syncing = true ; } getClient ( ) . localBuildExecutorService . submit ( new Runnable ( ) { @ Override public void run ( ) { _sync ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch a sync only if the data is obsolete . The data is obsolete if the last successful sync is older than the delay between syncs or if the data selection queries have been changed in the meantime . [CODESPLIT] public void syncIfNeeded ( ) { long currentDate = System . currentTimeMillis ( ) ; if ( currentDate - mirrorSettings . getLastSyncDate ( ) . getTime ( ) > delayBetweenSyncs || mirrorSettings . getQueriesModificationDate ( ) . compareTo ( mirrorSettings . getLastSyncDate ( ) ) > 0 ) { sync ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh the local mirror . WARNING : Should be called from a background thread . [CODESPLIT] private void _sync ( ) { if ( ! mirrored ) throw new IllegalArgumentException ( \"Mirroring not activated on this index\" ) ; // Reset statistics. stats = new SyncStats ( ) ; long startTime = System . currentTimeMillis ( ) ; // Notify listeners. getClient ( ) . completionExecutor . execute ( new Runnable ( ) { @ Override public void run ( ) { fireSyncDidStart ( ) ; } } ) ; try { // Create temporary directory. tmpDir = new File ( getClient ( ) . getTempDir ( ) , UUID . randomUUID ( ) . toString ( ) ) ; tmpDir . mkdirs ( ) ; // NOTE: We are doing everything sequentially, because this is a background job: we care more about // resource consumption than about how long it will take. // Fetch settings. { JSONObject settingsJSON = this . getSettings ( 1 , /* requestOptions: */ null ) ; settingsFile = new File ( tmpDir , \"settings.json\" ) ; String data = settingsJSON . toString ( ) ; Writer writer = new OutputStreamWriter ( new FileOutputStream ( settingsFile ) , \"UTF-8\" ) ; writer . write ( data ) ; writer . close ( ) ; } // Perform data selection queries. objectFiles = new ArrayList <> ( ) ; final DataSelectionQuery [ ] queries = mirrorSettings . getQueries ( ) ; for ( DataSelectionQuery query : queries ) { String cursor = null ; int retrievedObjects = 0 ; do { // Make next request. JSONObject objectsJSON = cursor == null ? this . browse ( query . query , /* requestOptions: */ null ) : this . browseFrom ( cursor , /* requestOptions: */ null ) ; // Write result to file. int objectFileNo = objectFiles . size ( ) ; File file = new File ( tmpDir , String . format ( \"%d.json\" , objectFileNo ) ) ; objectFiles . add ( file ) ; String data = objectsJSON . toString ( ) ; Writer writer = new OutputStreamWriter ( new FileOutputStream ( file ) , \"UTF-8\" ) ; writer . write ( data ) ; writer . close ( ) ; cursor = objectsJSON . optString ( \"cursor\" , null ) ; JSONArray hits = objectsJSON . optJSONArray ( \"hits\" ) ; if ( hits == null ) { // Something went wrong: // Report the error, and just abort this batch and proceed with the next query. Log . e ( this . getClass ( ) . getName ( ) , \"No hits in result for query: \" + query . query ) ; break ; } retrievedObjects += hits . length ( ) ; } while ( retrievedObjects < query . maxObjects && cursor != null ) ; stats . objectCount += retrievedObjects ; } // Update statistics. long afterFetchTime = System . currentTimeMillis ( ) ; stats . fetchTime = afterFetchTime - startTime ; stats . fileCount = objectFiles . size ( ) ; // Build the index. _buildOffline ( settingsFile , objectFiles . toArray ( new File [ objectFiles . size ( ) ] ) ) ; // Update statistics. long afterBuildTime = System . currentTimeMillis ( ) ; stats . buildTime = afterBuildTime - afterFetchTime ; stats . totalTime = afterBuildTime - startTime ; // Remember the last sync date. mirrorSettings . setLastSyncDate ( new Date ( ) ) ; saveMirrorSettings ( ) ; // Log statistics. Log . d ( this . getClass ( ) . getName ( ) , \"Sync stats: \" + stats ) ; } catch ( Exception e ) { Log . e ( this . getClass ( ) . getName ( ) , \"Sync failed\" , e ) ; error = e ; } finally { // Clean up. if ( tmpDir != null ) { FileUtils . deleteRecursive ( tmpDir ) ; tmpDir = null ; } settingsFile = null ; objectFiles = null ; // Mark sync as finished. synchronized ( this ) { syncing = false ; } // Notify listeners. getClient ( ) . completionExecutor . execute ( new Runnable ( ) { @ Override public void run ( ) { fireSyncDidFinish ( ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the online API falling back to the local mirror if enabled in case of error . [CODESPLIT] @ Override public Request searchAsync ( @ NonNull Query query , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { // A non-mirrored index behaves exactly as an online index. if ( ! mirrored ) { return super . searchAsync ( query , requestOptions , completionHandler ) ; } // A mirrored index launches a mixed offline/online request. else { final Query queryCopy = new Query ( query ) ; return new OnlineOfflineSearchRequest ( queryCopy , requestOptions , completionHandler ) . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the online API . [CODESPLIT] public Request searchOnlineAsync ( @ NonNull Query query , @ NonNull final CompletionHandler completionHandler ) { return searchOnlineAsync ( query , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the online API . [CODESPLIT] public Request searchOnlineAsync ( @ NonNull Query query , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return searchOnline ( queryCopy , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------- [CODESPLIT] @ Override public Request multipleQueriesAsync ( @ NonNull Collection < Query > queries , final Client . MultipleQueriesStrategy strategy , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { // A non-mirrored index behaves exactly as an online index. if ( ! mirrored ) { return super . multipleQueriesAsync ( queries , strategy , completionHandler ) ; } // A mirrored index launches a mixed offline/online request. else { final List < Query > queriesCopy = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { queriesCopy . add ( new Query ( query ) ) ; } return new OnlineOfflineMultipleQueriesRequest ( queriesCopy , strategy , requestOptions , completionHandler ) . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index explicitly targeting the online API . [CODESPLIT] public Request multipleQueriesOnlineAsync ( @ NonNull List < Query > queries , final Client . MultipleQueriesStrategy strategy , final @ NonNull CompletionHandler completionHandler ) { return multipleQueriesAsync ( queries , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index explicitly targeting the online API . [CODESPLIT] public Request multipleQueriesOnlineAsync ( @ NonNull List < Query > queries , final Client . MultipleQueriesStrategy strategy , @ Nullable final RequestOptions requestOptions , final @ NonNull CompletionHandler completionHandler ) { final List < Query > queriesCopy = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { queriesCopy . add ( new Query ( query ) ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return multipleQueriesOnline ( queriesCopy , strategy == null ? null : strategy . toString ( ) , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index explicitly targeting the offline mirror . [CODESPLIT] public Request multipleQueriesOfflineAsync ( final @ NonNull List < Query > queries , final Client . MultipleQueriesStrategy strategy , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( \"Offline requests are only available when the index is mirrored\" ) ; } final List < Query > queriesCopy = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { queriesCopy . add ( new Query ( query ) ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _multipleQueriesOffline ( queriesCopy , strategy == null ? null : strategy . toString ( ) ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index explicitly targeting the online API . [CODESPLIT] private JSONObject multipleQueriesOnline ( @ NonNull List < Query > queries , String strategy , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONObject content = super . multipleQueries ( queries , strategy , requestOptions ) ; content . put ( JSON_KEY_ORIGIN , JSON_VALUE_ORIGIN_REMOTE ) ; return content ; } catch ( JSONException e ) { throw new AlgoliaException ( \"Failed to patch JSON result\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index explicitly targeting the offline mirror . [CODESPLIT] private JSONObject _multipleQueriesOffline ( @ NonNull List < Query > queries , String strategy ) throws AlgoliaException { if ( ! mirrored ) { throw new IllegalStateException ( \"Cannot run offline search on a non-mirrored index\" ) ; } return new MultipleQueryEmulator ( this . getRawIndexName ( ) ) { @ Override protected JSONObject singleQuery ( @ NonNull Query query ) throws AlgoliaException { return _searchOffline ( query ) ; } } . multipleQueries ( queries , strategy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Browse the local mirror ( initial call ) . Same semantics as { @link Index#browseAsync } . [CODESPLIT] public Request browseMirrorAsync ( @ NonNull Query query , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( \"Mirroring not activated on this index\" ) ; } final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _browseMirror ( queryCopy ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Browse the local mirror ( subsequent calls ) . Same semantics as { @link Index#browseFromAsync } . [CODESPLIT] public Request browseMirrorFromAsync ( @ NonNull String cursor , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( \"Mirroring not activated on this index\" ) ; } final Query query = new Query ( ) . set ( \"cursor\" , cursor ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _browseMirror ( query ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an individual object from the online API falling back to the local mirror in case of error ( when enabled ) . [CODESPLIT] @ Override public Request getObjectAsync ( final @ NonNull String objectID , final @ Nullable Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { return super . getObjectAsync ( objectID , attributesToRetrieve , requestOptions , completionHandler ) ; } else { return new OnlineOfflineGetObjectRequest ( objectID , new ArrayList ( attributesToRetrieve ) , requestOptions , completionHandler ) . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an individual object explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectOnlineAsync ( @ NonNull final String objectID , final @ Nullable List < String > attributesToRetrieve , @ NonNull final CompletionHandler completionHandler ) { return getObjectOnlineAsync ( objectID , attributesToRetrieve , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an individual object explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectOnlineAsync ( @ NonNull final String objectID , final @ Nullable List < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { // TODO: Cannot perform origin tagging because it could conflict with the object's attributes return super . getObjectAsync ( objectID , attributesToRetrieve , requestOptions , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an individual object explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectOnlineAsync ( @ NonNull final String objectID , @ NonNull final CompletionHandler completionHandler ) { return getObjectOnlineAsync ( objectID , /* attributesToRetrieve: */ null , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an individual object explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectOfflineAsync ( @ NonNull final String objectID , final @ Nullable List < String > attributesToRetrieve , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( \"Mirroring not activated on this index\" ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _getObjectOffline ( objectID , attributesToRetrieve ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an individual object explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectOfflineAsync ( @ NonNull final String objectID , @ NonNull final CompletionHandler completionHandler ) { return getObjectOfflineAsync ( objectID , null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get individual objects from the online API falling back to the local mirror in case of error ( when enabled ) . [CODESPLIT] @ Override public Request getObjectsAsync ( final @ NonNull Collection < String > objectIDs , final @ Nullable Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { return super . getObjectsAsync ( objectIDs , attributesToRetrieve , requestOptions , completionHandler ) ; } else { return new OnlineOfflineGetObjectsRequest ( new ArrayList ( objectIDs ) , new ArrayList ( attributesToRetrieve ) , requestOptions , completionHandler ) . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get individual objects explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectsOnlineAsync ( @ NonNull final List < String > objectIDs , final @ Nullable List < String > attributesToRetrieve , @ NonNull final CompletionHandler completionHandler ) { return getObjectsOnlineAsync ( objectIDs , attributesToRetrieve , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get individual objects explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectsOnlineAsync ( @ NonNull final List < String > objectIDs , final @ Nullable List < String > attributesToRetrieve , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjectsOnline ( objectIDs , attributesToRetrieve , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get individual objects explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectsOnlineAsync ( @ NonNull final List < String > objectIDs , @ NonNull final CompletionHandler completionHandler ) { return getObjectsOnlineAsync ( objectIDs , /* attributesToRetrieve: */ null , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get individual objects explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectsOfflineAsync ( @ NonNull final List < String > objectIDs , final @ Nullable List < String > attributesToRetrieve , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( \"Mirroring not activated on this index\" ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _getObjectsOffline ( objectIDs , attributesToRetrieve ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get individual objects explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectsOfflineAsync ( @ NonNull final List < String > objectIDs , @ NonNull final CompletionHandler completionHandler ) { return getObjectsOfflineAsync ( objectIDs , null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------- [CODESPLIT] @ Override public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String text , @ Nullable Query query , @ Nullable RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { // A non-mirrored index behaves exactly as an online index. if ( ! mirrored ) { return super . searchForFacetValuesAsync ( facetName , text , query , requestOptions , completionHandler ) ; } // A mirrored index launches a mixed offline/online request. else { final Query queryCopy = query != null ? new Query ( query ) : null ; return new MixedFacetSearchRequest ( facetName , text , queryCopy , requestOptions , completionHandler ) . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for facet values explicitly targeting the online API not the offline mirror . Same parameters as { [CODESPLIT] public Request searchForFacetValuesOnline ( @ NonNull String facetName , @ NonNull String text , @ Nullable Query query , @ NonNull final CompletionHandler completionHandler ) { return searchForFacetValuesOnline ( facetName , text , query , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for facet values explicitly targeting the online API not the offline mirror . Same parameters as { [CODESPLIT] public Request searchForFacetValuesOnline ( @ NonNull String facetName , @ NonNull String text , @ Nullable Query query , @ Nullable RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { return super . searchForFacetValuesAsync ( facetName , text , query , requestOptions , new CompletionHandler ( ) { @ Override public void requestCompleted ( JSONObject content , AlgoliaException error ) { try { if ( content != null ) content . put ( JSON_KEY_ORIGIN , JSON_VALUE_ORIGIN_REMOTE ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } completionHandler . requestCompleted ( content , error ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for facet values explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request searchForFacetValuesOffline ( final @ NonNull String facetName , final @ NonNull String text , @ Nullable Query query , @ NonNull final CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( \"Offline requests are only available when the index is mirrored\" ) ; } final Query queryCopy = query != null ? new Query ( query ) : null ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _searchForFacetValuesOffline ( facetName , text , queryCopy ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches inside this index ( asynchronously ) . [CODESPLIT] public Request searchAsync ( @ Nullable Query query , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { final Query queryCopy = query != null ? new Query ( query ) : new Query ( ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return search ( queryCopy , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches inside this index ( synchronously ) . [CODESPLIT] public JSONObject searchSync ( @ Nullable Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return search ( query , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index with one API call . A variant of { @link Client#multipleQueriesAsync ( List Client . MultipleQueriesStrategy CompletionHandler ) } where the targeted index is always the receiver . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull Collection < Query > queries , final Client . MultipleQueriesStrategy strategy , @ Nullable CompletionHandler completionHandler ) { return multipleQueriesAsync ( queries , strategy , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches inside this index synchronously . [CODESPLIT] protected byte [ ] searchSyncRaw ( @ NonNull Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return searchRaw ( query , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] @ Override public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , ? extends Collection < String > > refinements , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { return new DisjunctiveFaceting ( ) { @ Override protected Request multipleQueriesAsync ( @ NonNull Collection < Query > queries , @ Nullable CompletionHandler completionHandler ) { return Index . this . multipleQueriesAsync ( queries , null , requestOptions , completionHandler ) ; } } . searchDisjunctiveFacetingAsync ( query , disjunctiveFacets , refinements , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , ? extends Collection < String > > refinements , @ NonNull final CompletionHandler completionHandler ) { return searchDisjunctiveFacetingAsync ( query , disjunctiveFacets , refinements , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches ( asynchronously ) for some text in a facet values . [CODESPLIT] public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String text , @ NonNull final CompletionHandler handler ) throws AlgoliaException { return searchForFacetValuesAsync ( facetName , text , /* requestOptions: */ null , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches for some text in a facet values optionally restricting the returned values to those contained in objects matching other ( regular ) search criteria . [CODESPLIT] public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String facetText , @ Nullable Query query , @ NonNull final CompletionHandler handler ) { return searchForFacetValuesAsync ( facetName , facetText , query , /* requestOptions: */ null , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches for some text in a facet values optionally restricting the returned values to those contained in objects matching other ( regular ) search criteria . [CODESPLIT] @ Override public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String facetText , @ Nullable Query query , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler handler ) { try { final String path = \"/1/indexes/\" + getEncodedIndexName ( ) + \"/facets/\" + URLEncoder . encode ( facetName , \"UTF-8\" ) + \"/query\" ; final Query params = ( query != null ? new Query ( query ) : new Query ( ) ) ; params . set ( \"facetQuery\" , facetText ) ; final JSONObject requestBody = new JSONObject ( ) . put ( \"params\" , params . build ( ) ) ; final Client client = getClient ( ) ; return client . new AsyncTaskRequest ( handler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return client . postRequest ( path , /* urlParameters: */ null , requestBody . toString ( ) , true , requestOptions ) ; } } . start ( ) ; } catch ( UnsupportedEncodingException | JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an object to this index ( asynchronously ) . <p > WARNING : For performance reasons the arguments are not cloned . Since the method is executed in the background you should not modify the object after it has been passed . < / p > [CODESPLIT] public Request addObjectAsync ( final @ NonNull JSONObject object , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return addObject ( object , /* requestOptions: */ null ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an object to this index assigning it the specified object ID ( asynchronously ) . If an object already exists with the same object ID the existing object will be overwritten . <p > WARNING : For performance reasons the arguments are not cloned . Since the method is executed in the background you should not modify the object after it has been passed . < / p > [CODESPLIT] public Request addObjectAsync ( final @ NonNull JSONObject object , final @ NonNull String objectID , @ Nullable CompletionHandler completionHandler ) { return addObjectAsync ( object , objectID , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an object to this index assigning it the specified object ID ( asynchronously ) . If an object already exists with the same object ID the existing object will be overwritten . <p > WARNING : For performance reasons the arguments are not cloned . Since the method is executed in the background you should not modify the object after it has been passed . < / p > [CODESPLIT] public Request addObjectAsync ( final @ NonNull JSONObject object , final @ NonNull String objectID , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return addObject ( object , objectID , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds several objects to this index ( asynchronously ) . [CODESPLIT] public Request addObjectsAsync ( final @ NonNull JSONArray objects , @ Nullable CompletionHandler completionHandler ) { return addObjectsAsync ( objects , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update several objects ( asynchronously ) . [CODESPLIT] public Request saveObjectsAsync ( final @ NonNull JSONArray objects , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return saveObjects ( objects , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Partially update an object ( asynchronously ) . <p > ** Note : ** This method will create the object if it does not exist already . If you don t wish to you can use { @link #partialUpdateObjectAsync ( JSONObject String boolean CompletionHandler ) } and specify false for the createIfNotExists argument . [CODESPLIT] public Request partialUpdateObjectAsync ( final @ NonNull JSONObject partialObject , final @ NonNull String objectID , @ Nullable CompletionHandler completionHandler ) { return partialUpdateObjectAsync ( partialObject , objectID , /* createIfNotExists: */ true , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Partially update an object ( asynchronously ) . [CODESPLIT] public Request partialUpdateObjectAsync ( final @ NonNull JSONObject partialObject , final @ NonNull String objectID , final boolean createIfNotExists , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return partialUpdateObject ( partialObject , objectID , createIfNotExists , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Partially update several objects ( asynchronously ) . <p > ** Note : ** This method will create the objects if they do not exist already . If you don t wish to you can use { @link #partialUpdateObjectsAsync ( JSONArray boolean CompletionHandler ) } and specify false for the createIfNotExists argument . [CODESPLIT] public Request partialUpdateObjectsAsync ( final @ NonNull JSONArray partialObjects , @ Nullable CompletionHandler completionHandler ) { return partialUpdateObjectsAsync ( partialObjects , /* createIfNotExists: */ true , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Partially update several objects ( asynchronously ) . [CODESPLIT] public Request partialUpdateObjectsAsync ( final @ NonNull JSONArray partialObjects , final boolean createIfNotExists , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return partialUpdateObjects ( partialObjects , createIfNotExists , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an object from this index optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectAsync ( final @ NonNull String objectID , final Collection < String > attributesToRetrieve , @ Nullable CompletionHandler completionHandler ) { return getObjectAsync ( objectID , attributesToRetrieve , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an object from this index optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectAsync ( final @ NonNull String objectID , final Collection < String > attributesToRetrieve , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObject ( objectID , attributesToRetrieve , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets several objects from this index ( asynchronously ) . [CODESPLIT] public Request getObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable CompletionHandler completionHandler ) { return getObjectsAsync ( objectIDs , /* attributesToRetrieve: */ null , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets several objects from this index ( asynchronously ) optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjects ( objectIDs , null , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait until the publication of a task on the server ( helper ) . All server tasks are asynchronous . This method helps you check that a task is published . [CODESPLIT] public Request waitTaskAsync ( final @ NonNull String taskID , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return waitTask ( taskID ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes an object from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectAsync ( final @ NonNull String objectID , @ Nullable CompletionHandler completionHandler ) { return deleteObjectAsync ( objectID , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes an object from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectAsync ( final @ NonNull String objectID , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteObject ( objectID , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes several objects from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable CompletionHandler completionHandler ) { return deleteObjectsAsync ( objectIDs , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes several objects from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteObjects ( objectIDs , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes all objects matching a query ( helper ) using browse and deleteObjects . [CODESPLIT] public Request deleteByQueryAsync ( @ NonNull Query query , @ Nullable CompletionHandler completionHandler ) { return deleteByQueryAsync ( query , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets this index s settings ( asynchronously ) . [CODESPLIT] public Request getSettingsAsync ( @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getSettings ( 2 , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this index s settings ( asynchronously ) . <p > Please refer to our <a href = https : // www . algolia . com / doc / android#index - settings > API documentation< / a > for the list of supported settings . [CODESPLIT] public Request setSettingsAsync ( final @ NonNull JSONObject settings , @ Nullable CompletionHandler completionHandler ) { return setSettingsAsync ( settings , /* forwardToReplicas: */ false , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this index s settings ( asynchronously ) . <p > Please refer to our <a href = https : // www . algolia . com / doc / android#index - settings > API documentation< / a > for the list of supported settings . [CODESPLIT] public Request setSettingsAsync ( final @ NonNull JSONObject settings , final boolean forwardToReplicas , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return setSettings ( settings , forwardToReplicas , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Browse the index from a cursor . This method should be called after an initial call to browseAsync () . It returns a cursor unless the end of the index has been reached . [CODESPLIT] public Request browseFromAsync ( final @ NonNull String cursor , @ Nullable CompletionHandler completionHandler ) { return browseFromAsync ( cursor , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Browse the index from a cursor . This method should be called after an initial call to browseAsync () . It returns a cursor unless the end of the index has been reached . [CODESPLIT] public Request browseFromAsync ( final @ NonNull String cursor , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return browseFrom ( cursor , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear this index . [CODESPLIT] public Request clearIndexAsync ( @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return clearIndex ( requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an object in this index . [CODESPLIT] public JSONObject addObject ( JSONObject obj , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return client . postRequest ( \"/1/indexes/\" + encodedIndexName , /* urlParameters: */ null , obj . toString ( ) , false , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Custom batch . [CODESPLIT] protected JSONObject batch ( JSONArray actions , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONObject content = new JSONObject ( ) ; content . put ( \"requests\" , actions ) ; return client . postRequest ( \"/1/indexes/\" + encodedIndexName + \"/batch\" , /* urlParameters: */ null , content . toString ( ) , false , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an object from this index . [CODESPLIT] public JSONObject getObject ( String objectID , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return client . getRequest ( \"/1/indexes/\" + encodedIndexName + \"/\" + URLEncoder . encode ( objectID , \"UTF-8\" ) , /* urlParameters: */ null , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an object from this index . [CODESPLIT] public JSONObject getObject ( String objectID , Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { String path = \"/1/indexes/\" + encodedIndexName + \"/\" + URLEncoder . encode ( objectID , \"UTF-8\" ) ; Map < String , String > urlParameters = new HashMap <> ( ) ; if ( attributesToRetrieve != null ) { urlParameters . put ( \"attributesToRetrieve\" , AbstractQuery . buildCommaArray ( attributesToRetrieve . toArray ( new String [ attributesToRetrieve . size ( ) ] ) ) ) ; } return client . getRequest ( path , urlParameters , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets several objects from this index . [CODESPLIT] public JSONObject getObjects ( Collection < String > objectIDs ) throws AlgoliaException { return getObjects ( objectIDs , /* attributesToRetrieve: */ null , /* requestOptions: */ null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets several objects from this index . [CODESPLIT] public JSONObject getObjects ( @ NonNull Collection < String > objectIDs , @ Nullable Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONArray requests = new JSONArray ( ) ; for ( String id : objectIDs ) { JSONObject request = new JSONObject ( ) ; request . put ( \"indexName\" , this . rawIndexName ) ; request . put ( \"objectID\" , id ) ; if ( attributesToRetrieve != null ) { request . put ( \"attributesToRetrieve\" , new JSONArray ( attributesToRetrieve ) ) ; } requests . put ( request ) ; } JSONObject body = new JSONObject ( ) ; body . put ( \"requests\" , requests ) ; return client . postRequest ( \"/1/indexes/*/objects\" , /* urlParameters: */ null , body . toString ( ) , true , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update partially an object ( only update attributes passed in argument ) . [CODESPLIT] public JSONObject partialUpdateObject ( JSONObject partialObject , String objectID , Boolean createIfNotExists , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { String path = \"/1/indexes/\" + encodedIndexName + \"/\" + URLEncoder . encode ( objectID , \"UTF-8\" ) + \"/partial\" ; Map < String , String > urlParameters = new HashMap <> ( ) ; if ( createIfNotExists != null ) { urlParameters . put ( \"createIfNotExists\" , createIfNotExists . toString ( ) ) ; } return client . postRequest ( path , urlParameters , partialObject . toString ( ) , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Partially Override the content of several objects . [CODESPLIT] public JSONObject partialUpdateObjects ( JSONArray inputArray , boolean createIfNotExists , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { final String action = createIfNotExists ? \"partialUpdateObject\" : \"partialUpdateObjectNoCreate\" ; JSONArray array = new JSONArray ( ) ; for ( int n = 0 ; n < inputArray . length ( ) ; n ++ ) { JSONObject obj = inputArray . getJSONObject ( n ) ; JSONObject operation = new JSONObject ( ) ; operation . put ( \"action\" , action ) ; operation . put ( \"objectID\" , obj . getString ( \"objectID\" ) ) ; operation . put ( \"body\" , obj ) ; array . put ( operation ) ; } return batch ( array , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the content of object . [CODESPLIT] public JSONObject saveObject ( JSONObject object , String objectID , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return client . putRequest ( \"/1/indexes/\" + encodedIndexName + \"/\" + URLEncoder . encode ( objectID , \"UTF-8\" ) , /* urlParameters: */ null , object . toString ( ) , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override the content of several objects . [CODESPLIT] public JSONObject saveObjects ( JSONArray inputArray , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONArray array = new JSONArray ( ) ; for ( int n = 0 ; n < inputArray . length ( ) ; n ++ ) { JSONObject obj = inputArray . getJSONObject ( n ) ; JSONObject action = new JSONObject ( ) ; action . put ( \"action\" , \"updateObject\" ) ; action . put ( \"objectID\" , obj . getString ( \"objectID\" ) ) ; action . put ( \"body\" , obj ) ; array . put ( action ) ; } return batch ( array , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes all objects matching a query using browse and deleteObjects . [CODESPLIT] @ Deprecated public void deleteByQuery ( @ NonNull Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { boolean hasMore ; do { // Browse index for the next batch of objects. // WARNING: Since deletion invalidates cursors, we always browse from the start. List < String > objectIDs = new ArrayList <> ( 1000 ) ; JSONObject content = browse ( query , requestOptions ) ; JSONArray hits = content . getJSONArray ( \"hits\" ) ; for ( int i = 0 ; i < hits . length ( ) ; ++ i ) { JSONObject hit = hits . getJSONObject ( i ) ; objectIDs . add ( hit . getString ( \"objectID\" ) ) ; } hasMore = content . optString ( \"cursor\" , null ) != null ; // Delete objects. JSONObject task = this . deleteObjects ( objectIDs , /* requestOptions: */ null ) ; this . waitTask ( task . getString ( \"taskID\" ) ) ; } while ( hasMore ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes all records matching the query . [CODESPLIT] public JSONObject deleteBy ( @ NonNull Query query , RequestOptions requestOptions ) throws AlgoliaException { try { return client . postRequest ( \"/1/indexes/\" + encodedIndexName + \"/deleteByQuery\" , query . getParameters ( ) , new JSONObject ( ) . put ( \"params\" , query . build ( ) ) . toString ( ) , false , requestOptions ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches inside the index . [CODESPLIT] public JSONObject search ( @ Nullable Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { if ( query == null ) { query = new Query ( ) ; } String cacheKey = null ; byte [ ] rawResponse = null ; if ( isCacheEnabled ) { cacheKey = query . build ( ) ; rawResponse = searchCache . get ( cacheKey ) ; } try { if ( rawResponse == null ) { rawResponse = searchRaw ( query , requestOptions ) ; if ( isCacheEnabled ) { searchCache . put ( cacheKey , rawResponse ) ; } } return Client . _getJSONObject ( rawResponse ) ; } catch ( UnsupportedEncodingException | JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches inside the index . [CODESPLIT] protected byte [ ] searchRaw ( @ Nullable Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { if ( query == null ) { query = new Query ( ) ; } try { String paramsString = query . build ( ) ; if ( paramsString . length ( ) > 0 ) { JSONObject body = new JSONObject ( ) ; body . put ( \"params\" , paramsString ) ; return client . postRequestRaw ( \"/1/indexes/\" + encodedIndexName + \"/query\" , /* urlParameters: */ null , body . toString ( ) , true , requestOptions ) ; } else { return client . getRequestRaw ( \"/1/indexes/\" + encodedIndexName , /* urlParameters: */ null , true , requestOptions ) ; } } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait the publication of a task on the server . All server task are asynchronous and you can check with this method that the task is published . [CODESPLIT] public JSONObject waitTask ( String taskID , long timeToWait ) throws AlgoliaException { try { while ( true ) { JSONObject obj = client . getRequest ( \"/1/indexes/\" + encodedIndexName + \"/task/\" + URLEncoder . encode ( taskID , \"UTF-8\" ) , /* urlParameters: */ null , false , /* requestOptions: */ null ) ; if ( obj . getString ( \"status\" ) . equals ( \"published\" ) ) { return obj ; } try { Thread . sleep ( timeToWait >= MAX_TIME_MS_TO_WAIT ? MAX_TIME_MS_TO_WAIT : timeToWait ) ; } catch ( InterruptedException e ) { continue ; } final long newTimeout = timeToWait * 2 ; timeToWait = ( newTimeout <= 0 || newTimeout >= MAX_TIME_MS_TO_WAIT ) ? MAX_TIME_MS_TO_WAIT : newTimeout ; } } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the settings of this index . [CODESPLIT] public JSONObject getSettings ( @ Nullable RequestOptions requestOptions ) throws AlgoliaException { Map < String , String > urlParameters = new HashMap <> ( ) ; urlParameters . put ( \"getVersion\" , Integer . toString ( DEFAULT_SETTINGS_VERSION ) ) ; return client . getRequest ( \"/1/indexes/\" + encodedIndexName + \"/settings\" , urlParameters , false , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set settings for this index . [CODESPLIT] public JSONObject setSettings ( JSONObject settings , boolean forwardToReplicas , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { Map < String , String > urlParameters = new HashMap <> ( ) ; urlParameters . put ( \"forwardToReplicas\" , Boolean . toString ( forwardToReplicas ) ) ; return client . putRequest ( \"/1/indexes/\" + encodedIndexName + \"/settings\" , urlParameters , settings . toString ( ) , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the index content without removing settings and index specific API keys . [CODESPLIT] public JSONObject clearIndex ( @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return client . postRequest ( \"/1/indexes/\" + encodedIndexName + \"/clear\" , /* urlParameters: */ null , \"\" , false , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index with one API call . A variant of { @link Client#multipleQueries ( List String RequestOptions ) } where all queries target this index . [CODESPLIT] protected JSONObject multipleQueries ( @ NonNull Collection < Query > queries , String strategy , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { List < IndexQuery > requests = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { requests . add ( new IndexQuery ( this , query ) ) ; } return client . multipleQueries ( requests , strategy , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a query string from a map of URL parameters . [CODESPLIT] static @ NonNull String build ( @ NonNull Map < String , String > parameters ) { StringBuilder stringBuilder = new StringBuilder ( ) ; try { for ( Map . Entry < String , String > entry : parameters . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( stringBuilder . length ( ) > 0 ) stringBuilder . append ( ' ' ) ; stringBuilder . append ( urlEncode ( key ) ) ; String value = entry . getValue ( ) ; if ( value != null ) { stringBuilder . append ( ' ' ) ; stringBuilder . append ( urlEncode ( value ) ) ; } } } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; // should never happen: UTF-8 is always supported } return stringBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a URL query parameter string and store the resulting parameters into this query . [CODESPLIT] public void parseFrom ( @ NonNull String queryParameters ) { try { String [ ] parameters = queryParameters . split ( \"&\" ) ; for ( String parameter : parameters ) { String [ ] components = parameter . split ( \"=\" ) ; if ( components . length < 1 || components . length > 2 ) continue ; // ignore invalid values String name = URLDecoder . decode ( components [ 0 ] , \"UTF-8\" ) ; String value = components . length >= 2 ? URLDecoder . decode ( components [ 1 ] , \"UTF-8\" ) : null ; set ( name , value ) ; } // for each parameter } catch ( UnsupportedEncodingException e ) { // Should never happen since UTF-8 is one of the default encodings. throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a parameter in an untyped fashion . This low - level accessor is intended to access parameters that this client does not yet support . [CODESPLIT] public @ NonNull AbstractQuery set ( @ NonNull String name , @ Nullable Object value ) { if ( value == null ) { parameters . remove ( name ) ; } else { parameters . put ( name , value . toString ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for entries around a given latitude / longitude . [CODESPLIT] public @ NonNull Query setAroundLatLng ( @ Nullable LatLng location ) { if ( location == null ) { return set ( KEY_AROUND_LAT_LNG , null ) ; } else { return set ( KEY_AROUND_LAT_LNG , location . lat + \",\" + location . lng ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change the radius for around latitude / longitude queries . [CODESPLIT] public @ NonNull Query setAroundRadius ( Integer radius ) { if ( radius == Query . RADIUS_ALL ) { return set ( KEY_AROUND_RADIUS , \"all\" ) ; } return set ( KEY_AROUND_RADIUS , radius ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deprecated use { [CODESPLIT] @ Deprecated public @ NonNull Query setAttributesToHighlight ( List < String > attributes ) { return set ( KEY_ATTRIBUTES_TO_HIGHLIGHT , buildJSONArray ( ( String [ ] ) attributes . toArray ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deprecated use { [CODESPLIT] @ Deprecated public @ NonNull Query setAttributesToRetrieve ( List < String > attributes ) { return set ( KEY_ATTRIBUTES_TO_RETRIEVE , buildJSONArray ( ( String [ ] ) attributes . toArray ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of <b > deprecated< / b > { @code facetFilters } parameter . [CODESPLIT] public @ Nullable JSONArray getFacetFilters ( ) { try { String value = get ( KEY_FACET_FILTERS ) ; if ( value != null ) { return new JSONArray ( value ) ; } } catch ( JSONException e ) { // Will return null } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A list of language codes for which plural won t be considered as a typo ( for example car / cars will be considered as equals ) . If empty or null this disables the feature . [CODESPLIT] public @ NonNull Query setIgnorePlurals ( @ Nullable Collection < String > languageISOCodes ) { return set ( KEY_IGNORE_PLURALS , new IgnorePlurals ( languageISOCodes ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for entries inside one area or the union of several areas defined by the two extreme points of a rectangle . [CODESPLIT] public @ NonNull Query setInsideBoundingBox ( @ Nullable GeoRect ... boxes ) { if ( boxes == null ) { set ( KEY_INSIDE_BOUNDING_BOX , null ) ; } else { StringBuilder sb = new StringBuilder ( ) ; for ( GeoRect box : boxes ) { if ( sb . length ( ) != 0 ) { sb . append ( ' ' ) ; } sb . append ( box . p1 . lat ) ; sb . append ( ' ' ) ; sb . append ( box . p1 . lng ) ; sb . append ( ' ' ) ; sb . append ( box . p2 . lat ) ; sb . append ( ' ' ) ; sb . append ( box . p2 . lng ) ; } set ( KEY_INSIDE_BOUNDING_BOX , sb . toString ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for entries inside a given area defined by the points of a polygon . [CODESPLIT] public @ NonNull Query setInsidePolygon ( @ Nullable LatLng ... points ) { set ( KEY_INSIDE_POLYGON , points == null ? null : new Polygon ( points ) . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for entries inside a given area defined by several polygons . [CODESPLIT] public @ NonNull Query setInsidePolygon ( @ Nullable Polygon ... polygons ) { String insidePolygon = null ; if ( polygons == null ) { insidePolygon = null ; } else if ( polygons . length == 1 ) { insidePolygon = polygons [ 0 ] . toString ( ) ; } else { for ( Polygon polygon : polygons ) { String polygonStr = \"[\" + polygon + \"]\" ; if ( insidePolygon == null ) { insidePolygon = \"[\" ; } else { insidePolygon += \",\" ; } insidePolygon += polygonStr ; } insidePolygon += \"]\" ; } set ( KEY_INSIDE_POLYGON , insidePolygon ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of <b > deprecated< / b > { @code facetFilters } parameter . [CODESPLIT] public @ Nullable JSONArray getNumericFilters ( ) { try { String value = get ( KEY_NUMERIC_FILTERS ) ; if ( value != null ) { return new JSONArray ( value ) ; } } catch ( JSONException e ) { // Will return null } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select how the query words are interpreted : [CODESPLIT] public @ NonNull Query setQueryType ( @ Nullable QueryType type ) { set ( KEY_QUERY_TYPE , type == null ? null : type . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable the removal of stop words disabled by default . In most use - cases we don’t recommend enabling this option . [CODESPLIT] public @ NonNull Query setRemoveStopWords ( Object removeStopWords ) throws AlgoliaException { if ( removeStopWords instanceof Boolean || removeStopWords instanceof String ) { return set ( KEY_REMOVE_STOP_WORDS , removeStopWords ) ; } throw new AlgoliaException ( \"removeStopWords should be a Boolean or a String.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select the strategy to adopt when a query does not return any result . [CODESPLIT] public @ NonNull Query setRemoveWordsIfNoResults ( @ Nullable RemoveWordsIfNoResults type ) { set ( KEY_REMOVE_WORDS_IF_NO_RESULT , type == null ? null : type . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a query object from a URL query parameter string . [CODESPLIT] protected static @ NonNull Query parse ( @ NonNull String queryParameters ) { Query query = new Query ( ) ; query . parseFrom ( queryParameters ) ; return query ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a search with disjunctive facets generating as many queries as number of disjunctive facets . [CODESPLIT] public < T extends Collection < String > > Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , T > refinements , @ NonNull final CompletionHandler completionHandler ) { final List < Query > queries = computeDisjunctiveFacetingQueries ( query , disjunctiveFacets , refinements ) ; return multipleQueriesAsync ( queries , new CompletionHandler ( ) { @ Override public void requestCompleted ( JSONObject content , AlgoliaException error ) { JSONObject aggregatedResults = null ; try { if ( content != null ) { aggregatedResults = aggregateDisjunctiveFacetingResults ( content , disjunctiveFacets , refinements ) ; } } catch ( AlgoliaException e ) { error = e ; } completionHandler . requestCompleted ( aggregatedResults , error ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter disjunctive refinements from generic refinements and a list of disjunctive facets . [CODESPLIT] static private @ NonNull < T extends Collection < String > > Map < String , T > filterDisjunctiveRefinements ( @ NonNull Collection < String > disjunctiveFacets , @ NonNull Map < String , T > refinements ) { Map < String , T > disjunctiveRefinements = new HashMap <> ( ) ; for ( Map . Entry < String , T > elt : refinements . entrySet ( ) ) { if ( disjunctiveFacets . contains ( elt . getKey ( ) ) ) { disjunctiveRefinements . put ( elt . getKey ( ) , elt . getValue ( ) ) ; } } return disjunctiveRefinements ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the queries to run to implement disjunctive faceting . [CODESPLIT] static private @ NonNull < T extends Collection < String > > List < Query > computeDisjunctiveFacetingQueries ( @ NonNull Query query , @ NonNull Collection < String > disjunctiveFacets , @ NonNull Map < String , T > refinements ) { // Retain only refinements corresponding to the disjunctive facets. Map < String , ? extends Collection < String > > disjunctiveRefinements = filterDisjunctiveRefinements ( disjunctiveFacets , refinements ) ; // build queries List < Query > queries = new ArrayList <> ( ) ; // first query: hits + regular facets JSONArray facetFilters = new JSONArray ( ) ; for ( Map . Entry < String , T > elt : refinements . entrySet ( ) ) { JSONArray orFilters = new JSONArray ( ) ; for ( String val : elt . getValue ( ) ) { // When already refined facet, or with existing refinements if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { orFilters . put ( formatFilter ( elt , val ) ) ; } else { facetFilters . put ( formatFilter ( elt , val ) ) ; } } // Add or if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { facetFilters . put ( orFilters ) ; } } //noinspection deprecation Deprecated for end-users queries . add ( new Query ( query ) . setFacetFilters ( facetFilters ) ) ; // one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet for ( String disjunctiveFacet : disjunctiveFacets ) { facetFilters = new JSONArray ( ) ; for ( Map . Entry < String , T > elt : refinements . entrySet ( ) ) { if ( disjunctiveFacet . equals ( elt . getKey ( ) ) ) { continue ; } JSONArray orFilters = new JSONArray ( ) ; for ( String val : elt . getValue ( ) ) { if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { orFilters . put ( formatFilter ( elt , val ) ) ; } else { facetFilters . put ( formatFilter ( elt , val ) ) ; } } // Add or if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { facetFilters . put ( orFilters ) ; } } String [ ] facets = new String [ ] { disjunctiveFacet } ; //noinspection deprecation Deprecated for end-users queries . add ( new Query ( query ) . setHitsPerPage ( 0 ) . setAnalytics ( false ) . setAttributesToRetrieve ( ) . setAttributesToHighlight ( ) . setAttributesToSnippet ( ) . setFacets ( facets ) . setFacetFilters ( facetFilters ) ) ; } return queries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Aggregate results from multiple queries into disjunctive faceting results . [CODESPLIT] static private < T extends Collection < String > > JSONObject aggregateDisjunctiveFacetingResults ( @ NonNull JSONObject answers , @ NonNull Collection < String > disjunctiveFacets , @ NonNull Map < String , T > refinements ) throws AlgoliaException { Map < String , T > disjunctiveRefinements = filterDisjunctiveRefinements ( disjunctiveFacets , refinements ) ; // aggregate answers // first answer stores the hits + regular facets try { boolean nonExhaustiveFacetsCount = false ; JSONArray results = answers . getJSONArray ( \"results\" ) ; JSONObject aggregatedAnswer = results . getJSONObject ( 0 ) ; JSONObject disjunctiveFacetsJSON = new JSONObject ( ) ; for ( int i = 1 ; i < results . length ( ) ; ++ i ) { if ( ! results . getJSONObject ( i ) . optBoolean ( \"exhaustiveFacetsCount\" ) ) { nonExhaustiveFacetsCount = true ; } JSONObject facets = results . getJSONObject ( i ) . getJSONObject ( \"facets\" ) ; @ SuppressWarnings ( \"unchecked\" ) Iterator < String > keys = facets . keys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; // Add the facet to the disjunctive facet hash disjunctiveFacetsJSON . put ( key , facets . getJSONObject ( key ) ) ; // concatenate missing refinements if ( ! disjunctiveRefinements . containsKey ( key ) ) { continue ; } for ( String refine : disjunctiveRefinements . get ( key ) ) { if ( ! disjunctiveFacetsJSON . getJSONObject ( key ) . has ( refine ) ) { disjunctiveFacetsJSON . getJSONObject ( key ) . put ( refine , 0 ) ; } } } } aggregatedAnswer . put ( \"disjunctiveFacets\" , disjunctiveFacetsJSON ) ; if ( nonExhaustiveFacetsCount ) { aggregatedAnswer . put ( \"exhaustiveFacetsCount\" , false ) ; } return aggregatedAnswer ; } catch ( JSONException e ) { throw new AlgoliaException ( \"Failed to aggregate results\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search inside this index ( asynchronously ) . [CODESPLIT] public Request searchAsync ( @ NonNull Query query , @ NonNull CompletionHandler completionHandler ) { final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return searchSync ( queryCopy ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search inside this index ( synchronously ) . [CODESPLIT] private JSONObject searchSync ( @ NonNull Query query ) throws AlgoliaException { return OfflineClient . parseSearchResults ( localIndex . search ( query . build ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries on this index with one API call . A variant of { @link Client#multipleQueriesAsync ( List Client . MultipleQueriesStrategy CompletionHandler ) } where the targeted index is always the receiver . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull List < Query > queries , @ Nullable final Client . MultipleQueriesStrategy strategy , @ NonNull CompletionHandler completionHandler ) { final List < Query > queriesCopy = new ArrayList <> ( queries ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return multipleQueriesSync ( queriesCopy , strategy ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an object from this index optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectAsync ( final @ NonNull String objectID , final List < String > attributesToRetrieve , @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjectSync ( objectID , attributesToRetrieve ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get several objects from this index ( asynchronously ) . [CODESPLIT] public Request getObjectsAsync ( final @ NonNull List < String > objectIDs , @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjectsSync ( objectIDs , null ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get this index s settings ( asynchronously ) . [CODESPLIT] public Request getSettingsAsync ( @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getSettingsSync ( ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Browse all index content ( initial call ) . This method should be called once to initiate a browse . It will return the first page of results and a cursor unless the end of the index has been reached . To retrieve subsequent pages call browseFromAsync with that cursor . [CODESPLIT] public Request browseAsync ( @ NonNull Query query , @ NonNull CompletionHandler completionHandler ) { final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return browseSync ( queryCopy ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Browse the index from a cursor . This method should be called after an initial call to browseAsync () . It returns a cursor unless the end of the index has been reached . [CODESPLIT] public Request browseFromAsync ( final @ NonNull String cursor , @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return browseFromSync ( cursor ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for facet values ( asynchronously ) . Same parameters as { [CODESPLIT] public Request searchForFacetValuesAsync ( final @ NonNull String facetName , final @ NonNull String facetQuery , @ Nullable Query query , @ NonNull CompletionHandler completionHandler ) { final Query queryCopy = query != null ? new Query ( query ) : null ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return searchForFacetValuesSync ( facetName , facetQuery , queryCopy ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for facet values ( synchronously ) . [CODESPLIT] private JSONObject searchForFacetValuesSync ( @ NonNull String facetName , @ NonNull String facetQuery , @ Nullable Query query ) throws AlgoliaException { return OfflineClient . parseSearchResults ( localIndex . searchForFacetValues ( facetName , facetQuery , query != null ? query . build ( ) : null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the index from local data stored on the filesystem . [CODESPLIT] public Request buildFromFiles ( @ NonNull final File settingsFile , @ NonNull final File [ ] objectFiles , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _build ( settingsFile , objectFiles ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the index from local data stored in raw resources . [CODESPLIT] public Request buildFromRawResources ( @ NonNull final Resources resources , @ NonNull final int settingsResId , @ NonNull final int [ ] objectsResIds , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _buildFromRawResources ( resources , settingsResId , objectsResIds ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final List < String > disjunctiveFacets , @ NonNull final Map < String , List < String > > refinements , @ NonNull final CompletionHandler completionHandler ) { return new DisjunctiveFaceting ( ) { @ Override protected Request multipleQueriesAsync ( @ NonNull Collection < Query > queries , @ NonNull CompletionHandler completionHandler ) { return OfflineIndex . this . multipleQueriesAsync ( new ArrayList ( queries ) , null , completionHandler ) ; } } . searchDisjunctiveFacetingAsync ( query , disjunctiveFacets , refinements , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete all objects matching a query ( helper ) . [CODESPLIT] public Request deleteByQueryAsync ( @ NonNull Query query , CompletionHandler completionHandler ) { final WriteTransaction transaction = newTransaction ( ) ; final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . transactionExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { try { Collection < String > deletedObjectIDs = deleteByQuerySync ( queryCopy , transaction ) ; transaction . commitSync ( ) ; return new JSONObject ( ) . put ( \"objectIDs\" , new JSONArray ( deletedObjectIDs ) ) . put ( \"updatedAt\" , DateUtils . iso8601String ( new Date ( ) ) ) . put ( \"taskID\" , transaction . id ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a copy of a JSON object with a specific <code > objectID< / code > attribute . [CODESPLIT] private static JSONObject objectWithID ( @ NonNull JSONObject object , @ NonNull String objectID ) { try { // WARNING: Could not find a better way to clone the object. JSONObject patchedObject = new JSONObject ( object . toString ( ) ) ; patchedObject . put ( \"objectID\" , objectID ) ; return patchedObject ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a temporary file containing a JSON object . [CODESPLIT] private @ NonNull File writeTmpJSONFile ( @ NonNull JSONObject object ) throws AlgoliaException { return writeTempFile ( object . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a temporary file containing JSON objects . The files are written as an array . [CODESPLIT] private File writeTmpJSONFile ( @ NonNull Collection < JSONObject > objects ) throws AlgoliaException { // TODO: Maybe split in several files if too big? // TODO: Stream writing. JSONArray array = new JSONArray ( ) ; for ( JSONObject object : objects ) { array . put ( object ) ; } return writeTempFile ( array . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a temporary file containing textual data in UTF - 8 encoding . [CODESPLIT] private File writeTempFile ( @ NonNull String data ) throws AlgoliaException { try { // Create temporary file. File tmpDir = client . getTempDir ( ) ; File tmpFile = File . createTempFile ( \"algolia.\" , \".json\" , tmpDir ) ; // Write to file. Writer writer = new OutputStreamWriter ( new FileOutputStream ( tmpFile ) , \"UTF-8\" ) ; writer . write ( data ) ; writer . close ( ) ; return tmpFile ; } catch ( IOException e ) { throw new AlgoliaException ( \"Could not create temporary file\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a mirrored index . Although this will always be an instance of { @link MirroredIndex } mirroring is deactivated by default . [CODESPLIT] @ Override public @ NonNull MirroredIndex getIndex ( @ NonNull String indexName ) { MirroredIndex index = null ; WeakReference < Object > existingIndex = indices . get ( indexName ) ; if ( existingIndex != null ) { index = ( MirroredIndex ) existingIndex . get ( ) ; } if ( index == null ) { index = new MirroredIndex ( this , indexName ) ; indices . put ( indexName , new WeakReference < Object > ( index ) ) ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a purely offline index . [CODESPLIT] public OfflineIndex getOfflineIndex ( @ NonNull String indexName ) { OfflineIndex index = null ; WeakReference < Object > existingIndex = indices . get ( indexName ) ; if ( existingIndex != null ) { index = ( OfflineIndex ) existingIndex . get ( ) ; } if ( index == null ) { index = new OfflineIndex ( this , indexName ) ; indices . put ( indexName , new WeakReference < Object > ( index ) ) ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if an index has offline data on disk . [CODESPLIT] public boolean hasOfflineData ( @ NonNull String name ) { // TODO: Suboptimal; we should be able to test existence without instantiating a `LocalIndex`. return new LocalIndex ( getRootDataDir ( ) . getAbsolutePath ( ) , getApplicationID ( ) , name ) . exists ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List existing offline indices . Only indices that * actually exist * on disk are listed . If an instance was created but never synced or written to it will not appear in the list . [CODESPLIT] public Request listIndexesOfflineAsync ( @ NonNull CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return listIndexesOfflineSync ( ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List existing offline indices . [CODESPLIT] private JSONObject listIndexesOfflineSync ( ) throws AlgoliaException { try { final String rootDataPath = getRootDataDir ( ) . getAbsolutePath ( ) ; final File appDir = getAppDir ( ) ; final File [ ] directories = appDir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { return pathname . isDirectory ( ) ; } } ) ; JSONObject response = new JSONObject ( ) ; JSONArray items = new JSONArray ( ) ; if ( directories != null ) { for ( File directory : directories ) { final String name = directory . getName ( ) ; if ( hasOfflineData ( name ) ) { items . put ( new JSONObject ( ) . put ( \"name\" , name ) ) ; // TODO: Do we need other data as in the online API? } } } response . put ( \"items\" , items ) ; return response ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an offline index . This deletes the data on disk . If the index does not exist this method does nothing . [CODESPLIT] public Request deleteIndexOfflineAsync ( final @ NonNull String indexName , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler , localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteIndexOfflineSync ( indexName ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an offline index . This deletes the data on disk . If the index does not exist this method does nothing . [CODESPLIT] private JSONObject deleteIndexOfflineSync ( final @ NonNull String indexName ) throws AlgoliaException { try { FileUtils . deleteRecursive ( getIndexDir ( indexName ) ) ; return new JSONObject ( ) . put ( \"deletedAt\" , DateUtils . iso8601String ( new Date ( ) ) ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move an existing offline index . [CODESPLIT] public Request moveIndexOfflineAsync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler , localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return moveIndexOfflineSync ( srcIndexName , dstIndexName ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move an existing offline index . [CODESPLIT] private JSONObject moveIndexOfflineSync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName ) throws AlgoliaException { try { final File srcDir = getIndexDir ( srcIndexName ) ; final File dstDir = getIndexDir ( dstIndexName ) ; if ( dstDir . exists ( ) ) { FileUtils . deleteRecursive ( dstDir ) ; } if ( srcDir . renameTo ( dstDir ) ) { return new JSONObject ( ) . put ( \"updatedAt\" , DateUtils . iso8601String ( new Date ( ) ) ) ; } else { throw new AlgoliaException ( \"Could not move index\" ) ; } } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------- [CODESPLIT] static protected JSONObject parseSearchResults ( Response searchResults ) throws AlgoliaException { try { if ( searchResults . getStatusCode ( ) == 200 ) { if ( searchResults . getData ( ) != null ) { String jsonString = new String ( searchResults . getData ( ) , \"UTF-8\" ) ; return new JSONObject ( jsonString ) ; } else { // may happen when building: no output return new JSONObject ( ) ; } } else { throw new AlgoliaException ( searchResults . getErrorMessage ( ) , searchResults . getStatusCode ( ) ) ; } } catch ( JSONException | UnsupportedEncodingException e ) { throw new AlgoliaException ( \"Offline Core returned invalid JSON\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a file or directory recursively deleting any descendant files / directories if it s a directory . [CODESPLIT] public static boolean deleteRecursive ( @ NonNull File item ) { boolean ok = true ; if ( item . isDirectory ( ) ) { for ( File child : item . listFiles ( ) ) { ok = ok && deleteRecursive ( child ) ; } } ok = ok && item . delete ( ) ; return ok ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a stream of bytes to a file . [CODESPLIT] public static void writeFile ( @ NonNull File destinationFile , @ NonNull InputStream content ) throws IOException { byte [ ] buffer = new byte [ 64 * 1024 ] ; // 64 kB buffer FileOutputStream outputStream = new FileOutputStream ( destinationFile ) ; try { int bytesRead ; while ( ( bytesRead = content . read ( buffer ) ) >= 0 ) { outputStream . write ( buffer , 0 , bytesRead ) ; } } finally { content . close ( ) ; outputStream . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a URL parameter ( untyped version ) . Whenever possible you should use a typed accessor . [CODESPLIT] public RequestOptions setUrlParameter ( @ NonNull String name , @ Nullable String value ) { if ( value == null ) { urlParameters . remove ( name ) ; } else { urlParameters . put ( name , value ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set an HTTP header that will be sent with every request . [CODESPLIT] public void setHeader ( @ NonNull String name , @ Nullable String value ) { if ( value == null ) { headers . remove ( name ) ; } else { headers . put ( name , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a software library to the list of user agents . [CODESPLIT] public void addUserAgent ( @ NonNull LibraryVersion userAgent ) { if ( ! userAgents . contains ( userAgent ) ) { userAgents . add ( userAgent ) ; } updateUserAgents ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the InputStream as UTF - 8 [CODESPLIT] private static String _toCharArray ( InputStream stream ) throws IOException { InputStreamReader is = new InputStreamReader ( stream , \"UTF-8\" ) ; StringBuilder builder = new StringBuilder ( ) ; char [ ] buf = new char [ 1000 ] ; int l = 0 ; while ( l >= 0 ) { builder . append ( buf , 0 , l ) ; l = is . read ( buf ) ; } is . close ( ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the InputStream into a byte array [CODESPLIT] private static byte [ ] _toByteArray ( InputStream stream ) throws AlgoliaException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; int read ; byte [ ] buffer = new byte [ 1024 ] ; try { while ( ( read = stream . read ( buffer , 0 , buffer . length ) ) != - 1 ) { out . write ( buffer , 0 , read ) ; } out . flush ( ) ; return out . toByteArray ( ) ; } catch ( IOException e ) { throw new AlgoliaException ( \"Error while reading stream: \" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the query according to parameters and returns its result as a JSONObject [CODESPLIT] private JSONObject _request ( @ NonNull Method m , @ NonNull String url , @ Nullable Map < String , String > urlParameters , @ Nullable String json , @ NonNull List < String > hostsArray , int connectTimeout , int readTimeout , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return _getJSONObject ( _requestRaw ( m , url , urlParameters , json , hostsArray , connectTimeout , readTimeout , requestOptions ) ) ; } catch ( JSONException e ) { throw new AlgoliaException ( \"JSON decode error:\" + e . getMessage ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new AlgoliaException ( \"UTF-8 decode error:\" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the query according to parameters and returns its result as a JSONObject [CODESPLIT] private byte [ ] _requestRaw ( @ NonNull Method m , @ NonNull String url , @ Nullable Map < String , String > urlParameters , @ Nullable String json , @ NonNull List < String > hostsArray , int connectTimeout , int readTimeout , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { String requestMethod ; List < Exception > errors = new ArrayList <> ( hostsArray . size ( ) ) ; // for each host for ( String host : hostsArray ) { switch ( m ) { case DELETE : requestMethod = \"DELETE\" ; break ; case GET : requestMethod = \"GET\" ; break ; case POST : requestMethod = \"POST\" ; break ; case PUT : requestMethod = \"PUT\" ; break ; default : throw new IllegalArgumentException ( \"Method \" + m + \" is not supported\" ) ; } InputStream stream = null ; HttpURLConnection hostConnection = null ; try { // Compute final URL parameters. final Map < String , String > parameters = new HashMap <> ( ) ; if ( urlParameters != null ) { parameters . putAll ( urlParameters ) ; } if ( requestOptions != null ) { parameters . putAll ( requestOptions . urlParameters ) ; } // Build URL. String urlString = \"https://\" + host + url ; if ( ! parameters . isEmpty ( ) ) { urlString += \"?\" + AbstractQuery . build ( parameters ) ; } URL hostURL = new URL ( urlString ) ; // Open connection. hostConnection = ( HttpURLConnection ) hostURL . openConnection ( ) ; //set timeouts hostConnection . setRequestMethod ( requestMethod ) ; hostConnection . setConnectTimeout ( connectTimeout ) ; hostConnection . setReadTimeout ( readTimeout ) ; // Headers hostConnection . setRequestProperty ( \"Accept-Encoding\" , \"gzip\" ) ; hostConnection . setRequestProperty ( \"X-Algolia-Application-Id\" , this . applicationID ) ; // If API key is too big, send it in the request's body (if applicable). if ( this . apiKey != null && this . apiKey . length ( ) > MAX_API_KEY_LENGTH && json != null ) { try { final JSONObject body = new JSONObject ( json ) ; body . put ( \"apiKey\" , this . apiKey ) ; json = body . toString ( ) ; } catch ( JSONException e ) { throw new AlgoliaException ( \"Failed to patch JSON body\" ) ; } } else { hostConnection . setRequestProperty ( \"X-Algolia-API-Key\" , this . apiKey ) ; } // Client-level headers for ( Map . Entry < String , String > entry : this . headers . entrySet ( ) ) { hostConnection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } // Request-level headers if ( requestOptions != null ) { for ( Map . Entry < String , String > entry : requestOptions . headers . entrySet ( ) ) { hostConnection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } // set user agent hostConnection . setRequestProperty ( \"User-Agent\" , userAgentRaw ) ; // write JSON entity if ( json != null ) { if ( ! ( requestMethod . equals ( \"PUT\" ) || requestMethod . equals ( \"POST\" ) ) ) { throw new IllegalArgumentException ( \"Method \" + m + \" cannot enclose entity\" ) ; } hostConnection . setRequestProperty ( \"Content-type\" , \"application/json; charset=UTF-8\" ) ; hostConnection . setDoOutput ( true ) ; OutputStreamWriter writer = new OutputStreamWriter ( hostConnection . getOutputStream ( ) , \"UTF-8\" ) ; writer . write ( json ) ; writer . close ( ) ; } // read response int code = hostConnection . getResponseCode ( ) ; final boolean codeIsError = code / 100 != 2 ; stream = codeIsError ? hostConnection . getErrorStream ( ) : hostConnection . getInputStream ( ) ; // As per the official Java docs (not the Android docs): // - `getErrorStream()` may return null => we have to handle this case. //   See <https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#getErrorStream()>. // - `getInputStream()` should never return null... but let's err on the side of caution. //   See <https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getInputStream()>. if ( stream == null ) { throw new IOException ( String . format ( \"Null stream when reading connection (status %d)\" , code ) ) ; } hostStatuses . put ( host , new HostStatus ( true ) ) ; final byte [ ] rawResponse ; String encoding = hostConnection . getContentEncoding ( ) ; if ( encoding != null && encoding . equals ( \"gzip\" ) ) { rawResponse = _toByteArray ( new GZIPInputStream ( stream ) ) ; } else { rawResponse = _toByteArray ( stream ) ; } // handle http errors if ( codeIsError ) { if ( code / 100 == 4 ) { consumeQuietly ( hostConnection ) ; throw new AlgoliaException ( _getJSONObject ( rawResponse ) . getString ( \"message\" ) , code ) ; } else { consumeQuietly ( hostConnection ) ; errors . add ( new AlgoliaException ( _toCharArray ( stream ) , code ) ) ; continue ; } } return rawResponse ; } catch ( JSONException e ) { // fatal consumeQuietly ( hostConnection ) ; throw new AlgoliaException ( \"Invalid JSON returned by server\" , e ) ; } catch ( UnsupportedEncodingException e ) { // fatal consumeQuietly ( hostConnection ) ; throw new AlgoliaException ( \"Invalid encoding returned by server\" , e ) ; } catch ( IOException e ) { // host error, continue on the next host hostStatuses . put ( host , new HostStatus ( false ) ) ; consumeQuietly ( hostConnection ) ; errors . add ( e ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } String errorMessage = \"All hosts failed: \" + Arrays . toString ( errors . toArray ( ) ) ; // When several errors occurred, use the last one as the cause for the returned exception. Throwable lastError = errors . get ( errors . size ( ) - 1 ) ; throw new AlgoliaException ( errorMessage , lastError ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the entity content is fully consumed and the content stream if exists is closed . [CODESPLIT] private static void consumeQuietly ( final HttpURLConnection connection ) { try { int read = 0 ; while ( read != - 1 ) { read = connection . getInputStream ( ) . read ( ) ; } connection . getInputStream ( ) . close ( ) ; read = 0 ; while ( read != - 1 ) { read = connection . getErrorStream ( ) . read ( ) ; } connection . getErrorStream ( ) . close ( ) ; connection . disconnect ( ) ; } catch ( IOException e ) { // no inputStream to close } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the hosts that are not considered down in a given list . [CODESPLIT] private List < String > hostsThatAreUp ( List < String > hosts ) { List < String > upHosts = new ArrayList <> ( ) ; for ( String host : hosts ) { if ( isUpOrCouldBeRetried ( host ) ) { upHosts . add ( host ) ; } } return upHosts . isEmpty ( ) ? hosts : upHosts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force to * first * search around a specific latitude / longitude . The default is to search around the location of the user determined via his IP address ( geoip ) . [CODESPLIT] public @ NonNull PlacesQuery setAroundLatLng ( LatLng location ) { if ( location == null ) { return set ( KEY_AROUND_LAT_LNG , null ) ; } else { return set ( KEY_AROUND_LAT_LNG , location . lat + \",\" + location . lng ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change the radius for around latitude / longitude queries . [CODESPLIT] public @ NonNull PlacesQuery setAroundRadius ( Integer radius ) { if ( radius == PlacesQuery . RADIUS_ALL ) { return set ( KEY_AROUND_RADIUS , \"all\" ) ; } return set ( KEY_AROUND_RADIUS , radius ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current radius for around latitude / longitude queries . [CODESPLIT] public Integer getAroundRadius ( ) { final String value = get ( KEY_AROUND_RADIUS ) ; if ( value != null && value . equals ( \"all\" ) ) { return PlacesQuery . RADIUS_ALL ; } return parseInt ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the type of place to search for . [CODESPLIT] public @ NonNull PlacesQuery setType ( Type type ) { if ( type == null ) { set ( KEY_TYPE , null ) ; } else { switch ( type ) { case CITY : set ( KEY_TYPE , \"city\" ) ; break ; case COUNTRY : set ( KEY_TYPE , \"country\" ) ; break ; case ADDRESS : set ( KEY_TYPE , \"address\" ) ; break ; case BUS_STOP : set ( KEY_TYPE , \"busStop\" ) ; break ; case TRAIN_STATION : set ( KEY_TYPE , \"trainStation\" ) ; break ; case TOWN_HALL : set ( KEY_TYPE , \"townhall\" ) ; break ; case AIRPORT : set ( KEY_TYPE , \"airport\" ) ; break ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a query object from a URL query parameter string . [CODESPLIT] protected static @ NonNull PlacesQuery parse ( @ NonNull String queryParameters ) { PlacesQuery query = new PlacesQuery ( ) ; query . parseFrom ( queryParameters ) ; return query ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a parameter in an untyped fashion . This low - level accessor is intended to access parameters that this client does not yet support . [CODESPLIT] @ Override public @ NonNull PlacesQuery set ( @ NonNull String name , @ Nullable Object value ) { return ( PlacesQuery ) super . set ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the iteration . [CODESPLIT] public void start ( ) { if ( started ) { throw new IllegalStateException ( ) ; } started = true ; request = index . browseAsync ( query , requestOptions , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search inside this index ( asynchronously ) . [CODESPLIT] public Request searchAsync ( @ Nullable Query query , @ Nullable CompletionHandler completionHandler ) { return searchAsync ( query , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , ? extends Collection < String > > refinements , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { throw new UnsupportedOperationException ( \"make sure to override searchDisjunctiveFacetingAsync for custom backend\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for some text in a facet values optionally restricting the returned values to those contained in objects matching other ( regular ) search criteria . [CODESPLIT] public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String facetText , @ Nullable Query query , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler handler ) { throw new UnsupportedOperationException ( \"make sure to override searchForFacetValuesAsync for custom backend\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List existing indexes . [CODESPLIT] public Request listIndexesAsync ( @ Nullable final RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return listIndexes ( requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an index . [CODESPLIT] public Request deleteIndexAsync ( final @ NonNull String indexName , @ Nullable final RequestOptions requestOptions , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteIndex ( indexName , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an index . [CODESPLIT] public Request deleteIndexAsync ( final @ NonNull String indexName , CompletionHandler completionHandler ) { return deleteIndexAsync ( indexName , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move an existing index . If the destination index already exists its specific API keys will be preserved and the source index specific API keys will be added . [CODESPLIT] public Request moveIndexAsync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName , @ Nullable final RequestOptions requestOptions , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return moveIndex ( srcIndexName , dstIndexName , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move an existing index . If the destination index already exists its specific API keys will be preserved and the source index specific API keys will be added . [CODESPLIT] public Request moveIndexAsync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName , CompletionHandler completionHandler ) { return moveIndexAsync ( srcIndexName , dstIndexName , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries potentially targeting multiple indexes with one API call . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull List < IndexQuery > queries , final MultipleQueriesStrategy strategy , @ Nullable final RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return multipleQueries ( queries , strategy == null ? null : strategy . toString ( ) , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run multiple queries potentially targeting multiple indexes with one API call . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull List < IndexQuery > queries , final MultipleQueriesStrategy strategy , @ NonNull CompletionHandler completionHandler ) { return multipleQueriesAsync ( queries , strategy , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch operations . [CODESPLIT] public Request batchAsync ( final @ NonNull JSONArray operations , @ Nullable final RequestOptions requestOptions , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return batch ( operations , requestOptions ) ; } } . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Batch operations . [CODESPLIT] public Request batchAsync ( final @ NonNull JSONArray operations , CompletionHandler completionHandler ) { return batchAsync ( operations , /* requestOptions: */ null , completionHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List all existing indexes [CODESPLIT] protected JSONObject listIndexes ( @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return getRequest ( \"/1/indexes/\" , /* urlParameters: */ null , false , requestOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an index [CODESPLIT] protected JSONObject deleteIndex ( String indexName , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return deleteRequest ( \"/1/indexes/\" + URLEncoder . encode ( indexName , \"UTF-8\" ) , /* urlParameters: */ null , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move an existing index . [CODESPLIT] protected JSONObject moveIndex ( String srcIndexName , String dstIndexName , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONObject content = new JSONObject ( ) ; content . put ( \"operation\" , \"move\" ) ; content . put ( \"destination\" , dstIndexName ) ; return postRequest ( \"/1/indexes/\" + URLEncoder . encode ( srcIndexName , \"UTF-8\" ) + \"/operation\" , /* urlParameters: */ null , content . toString ( ) , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a value in the cache computing an expiration time [CODESPLIT] public V put ( K key , V value ) { V previous = null ; synchronized ( this ) { long timeout = System . currentTimeMillis ( ) + TimeUnit . MILLISECONDS . convert ( expirationTimeout , expirationTimeUnit ) ; final Pair < V , Long > previousPair = lruCache . put ( key , new Pair <> ( value , timeout ) ) ; if ( previousPair != null ) { previous = previousPair . first ; } } return previous ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a value from the cache [CODESPLIT] synchronized public V get ( K key ) { final Pair < V , Long > cachePair = lruCache . get ( key ) ; if ( cachePair != null && cachePair . first != null ) { if ( cachePair . second > System . currentTimeMillis ( ) ) { return cachePair . first ; } else { lruCache . remove ( key ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the log processor with the currently provided arguments . [CODESPLIT] @ Override public void run ( ) { PrintStream timeIntervalLog = null ; PrintStream histogramPercentileLog = System . out ; Double firstStartTime = 0.0 ; boolean timeIntervalLogLegendWritten = false ; if ( config . listTags ) { Set < String > tags = new TreeSet < String > ( ) ; EncodableHistogram histogram ; boolean nullTagFound = false ; while ( ( histogram = getIntervalHistogram ( ) ) != null ) { String tag = histogram . getTag ( ) ; if ( tag != null ) { tags . add ( histogram . getTag ( ) ) ; } else { nullTagFound = true ; } } System . out . println ( \"Tags found in input file: \" ) ; if ( nullTagFound ) { System . out . println ( \"[NO TAG (default)]\" ) ; } for ( String tag : tags ) { System . out . println ( tag ) ; } // listtags does nothing other than list tags: return ; } final String logFormat = buildLogFormat ( config . logFormatCsv ) ; try { if ( config . outputFileName != null ) { try { timeIntervalLog = new PrintStream ( new FileOutputStream ( config . outputFileName ) , false , \"UTF-8\" ) ; outputTimeRange ( timeIntervalLog , \"Interval percentile log\" ) ; } catch ( FileNotFoundException ex ) { System . err . println ( \"Failed to open output file \" + config . outputFileName ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( \"Unsupported encoding: UTF-8\" ) ; } String hgrmOutputFileName = config . outputFileName + \".hgrm\" ; try { histogramPercentileLog = new PrintStream ( new FileOutputStream ( hgrmOutputFileName ) , false , \"UTF-8\" ) ; outputTimeRange ( histogramPercentileLog , \"Overall percentile distribution\" ) ; } catch ( FileNotFoundException ex ) { System . err . println ( \"Failed to open percentiles histogram output file \" + hgrmOutputFileName ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( \"Unsupported encoding: UTF-8\" ) ; } } EncodableHistogram intervalHistogram = getIntervalHistogram ( config . tag ) ; Histogram accumulatedRegularHistogram = null ; DoubleHistogram accumulatedDoubleHistogram = null ; if ( intervalHistogram != null ) { // Shape the accumulated histogram like the histograms in the log file (but clear their contents): if ( intervalHistogram instanceof DoubleHistogram ) { accumulatedDoubleHistogram = ( ( DoubleHistogram ) intervalHistogram ) . copy ( ) ; accumulatedDoubleHistogram . reset ( ) ; accumulatedDoubleHistogram . setAutoResize ( true ) ; } else { accumulatedRegularHistogram = ( ( Histogram ) intervalHistogram ) . copy ( ) ; accumulatedRegularHistogram . reset ( ) ; accumulatedRegularHistogram . setAutoResize ( true ) ; } } while ( intervalHistogram != null ) { if ( intervalHistogram instanceof DoubleHistogram ) { if ( accumulatedDoubleHistogram == null ) { throw new IllegalStateException ( \"Encountered a DoubleHistogram line in a log of Histograms.\" ) ; } accumulatedDoubleHistogram . add ( ( DoubleHistogram ) intervalHistogram ) ; } else { if ( accumulatedRegularHistogram == null ) { throw new IllegalStateException ( \"Encountered a Histogram line in a log of DoubleHistograms.\" ) ; } accumulatedRegularHistogram . add ( ( Histogram ) intervalHistogram ) ; } if ( ( firstStartTime == 0.0 ) && ( logReader . getStartTimeSec ( ) != 0.0 ) ) { firstStartTime = logReader . getStartTimeSec ( ) ; outputStartTime ( histogramPercentileLog , firstStartTime ) ; if ( timeIntervalLog != null ) { outputStartTime ( timeIntervalLog , firstStartTime ) ; } } if ( timeIntervalLog != null ) { if ( ! timeIntervalLogLegendWritten ) { timeIntervalLogLegendWritten = true ; timeIntervalLog . println ( buildLegend ( config . logFormatCsv ) ) ; } Object [ ] statistics = intervalHistogram instanceof DoubleHistogram ? buildDoubleHistogramStatistics ( ( DoubleHistogram ) intervalHistogram , accumulatedDoubleHistogram ) : buildRegularHistogramStatistics ( ( Histogram ) intervalHistogram , accumulatedRegularHistogram ) ; timeIntervalLog . format ( Locale . US , logFormat , statistics ) ; } intervalHistogram = getIntervalHistogram ( config . tag ) ; } if ( accumulatedDoubleHistogram != null ) { accumulatedDoubleHistogram . outputPercentileDistribution ( histogramPercentileLog , config . percentilesOutputTicksPerHalf , config . outputValueUnitRatio , config . logFormatCsv ) ; } else { if ( accumulatedRegularHistogram == null ) { // If there were no histograms in the log file, we still need an empty histogram for the // one line output (shape/range doesn't matter because it is empty): accumulatedRegularHistogram = new Histogram ( 1000000L , 2 ) ; } accumulatedRegularHistogram . outputPercentileDistribution ( histogramPercentileLog , config . percentilesOutputTicksPerHalf , config . outputValueUnitRatio , config . logFormatCsv ) ; } } finally { if ( config . outputFileName != null ) { closeQuietly ( timeIntervalLog ) ; closeQuietly ( histogramPercentileLog ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combines { @link PerformanceStats } instances e . g . from different Simulator Workers . <p > For the real - time performance monitor during the { @link TestPhase#RUN } the maximum value should be set so we get the maximum operation count and throughput values of all { @link PerformanceStats } instances of the last interval . <p > For the total performance number and the performance per Simulator Agent the added values should be set so we get the summed up operation count and throughput values . <p > The method always sets the maximum values for latency . [CODESPLIT] public void add ( PerformanceStats other , boolean addOperationCountAndThroughput ) { if ( other . isEmpty ( ) ) { return ; } if ( isEmpty ( ) ) { operationCount = other . operationCount ; intervalThroughput = other . intervalThroughput ; totalThroughput = other . totalThroughput ; intervalLatencyAvgNanos = other . intervalLatencyAvgNanos ; intervalLatency999PercentileNanos = other . intervalLatency999PercentileNanos ; intervalLatencyMaxNanos = other . intervalLatencyMaxNanos ; } else { if ( addOperationCountAndThroughput ) { operationCount += other . operationCount ; intervalThroughput += other . intervalThroughput ; totalThroughput += other . totalThroughput ; } else { operationCount = max ( operationCount , other . operationCount ) ; intervalThroughput = max ( intervalThroughput , other . intervalThroughput ) ; totalThroughput = max ( totalThroughput , other . totalThroughput ) ; } intervalLatencyAvgNanos = max ( intervalLatencyAvgNanos , other . intervalLatencyAvgNanos ) ; intervalLatency999PercentileNanos = max ( intervalLatency999PercentileNanos , other . intervalLatency999PercentileNanos ) ; intervalLatencyMaxNanos = max ( intervalLatencyMaxNanos , other . intervalLatencyMaxNanos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Spawns a new thread for the given { @link Runnable } . [CODESPLIT] public Thread spawn ( String namePrefix , Runnable runnable ) { checkNotNull ( namePrefix , \"namePrefix can't be null\" ) ; checkNotNull ( runnable , \"runnable can't be null\" ) ; String name = newName ( namePrefix ) ; Thread thread ; if ( throwException ) { thread = new ThrowExceptionThread ( name , runnable ) ; thread . setUncaughtExceptionHandler ( exceptionHandler ) ; } else { thread = new ReportExceptionThread ( testId , name , runnable ) ; } threads . add ( thread ) ; thread . start ( ) ; return thread ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for all threads to finish . [CODESPLIT] public void awaitCompletion ( ) { for ( Thread thread : threads ) { try { thread . join ( ) ; } catch ( InterruptedException e ) { throw rethrow ( e ) ; } } if ( caughtException != null ) { throw rethrow ( caughtException ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two version strings . [CODESPLIT] public static int versionCompare ( String firstVersionString , String secondVersionString ) { String [ ] firstVersion = parseVersionString ( firstVersionString ) ; String [ ] secondVersion = parseVersionString ( secondVersionString ) ; int i = 0 ; // set index to first non-equal ordinal or length of shortest version string while ( i < firstVersion . length && i < secondVersion . length && firstVersion [ i ] . equals ( secondVersion [ i ] ) ) { i ++ ; } if ( i < firstVersion . length && i < secondVersion . length ) { // compare first non-equal ordinal number int diff = Integer . valueOf ( firstVersion [ i ] ) . compareTo ( Integer . valueOf ( secondVersion [ i ] ) ) ; return Integer . signum ( diff ) ; } else { // the strings are equal or one string is a substring of the other // e.g. \"1.2.3\" = \"1.2.3\" or \"1.2.3\" < \"1.2.3.4\" return Integer . signum ( firstVersion . length - secondVersion . length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the cause to file . [CODESPLIT] public static void report ( String testId , Throwable cause ) { if ( cause == null ) { LOGGER . fatal ( \"Can't call report with a null exception\" ) ; return ; } long exceptionCount = FAILURE_ID . incrementAndGet ( ) ; if ( exceptionCount > MAX_EXCEPTION_COUNT ) { LOGGER . warn ( \"Exception #\" + exceptionCount + \" detected. The maximum number of exceptions has been exceeded, so it\" + \" won't be reported to the Agent.\" , cause ) ; return ; } LOGGER . warn ( \"Exception #\" + exceptionCount + \" detected\" , cause ) ; String targetFileName = exceptionCount + \".exception\" ; File dir = getUserDir ( ) ; File tmpFile = new File ( dir , targetFileName + \".tmp\" ) ; try { if ( ! tmpFile . createNewFile ( ) ) { throw new IOException ( \"Could not create tmp file: \" + tmpFile . getAbsolutePath ( ) ) ; } } catch ( IOException e ) { LOGGER . fatal ( \"Could not report exception; this means that this exception is not visible to the coordinator\" , e ) ; return ; } writeText ( testId + NEW_LINE + throwableToString ( cause ) , tmpFile ) ; File file = new File ( dir , targetFileName ) ; LOGGER . info ( file . getAbsolutePath ( ) ) ; rename ( tmpFile , file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies a directory recursively . [CODESPLIT] public static void copyDirectory ( File src , File target ) { checkNotNull ( src , \"src can't be null\" ) ; checkNotNull ( target , \"target can't be null\" ) ; File [ ] files = src . listFiles ( ) ; if ( files == null ) { return ; } for ( File srcFile : files ) { if ( srcFile . isDirectory ( ) ) { File targetChild = new File ( target , srcFile . getName ( ) ) ; ensureExistingDirectory ( targetChild ) ; copyDirectory ( srcFile , targetChild ) ; } else { copyFileToDirectory ( srcFile , target ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the SimulatorProperties with additional properties . [CODESPLIT] public SimulatorProperties init ( File file ) { if ( file == null ) { // if no file is explicitly given, we look in the working directory file = new File ( getUserDir ( ) , PROPERTIES_FILE_NAME ) ; if ( ! file . exists ( ) ) { LOGGER . info ( format ( \"Found no %s in working directory, relying on default properties\" , PROPERTIES_FILE_NAME ) ) ; return null ; } } LOGGER . info ( format ( \"Loading additional %s: %s\" , PROPERTIES_FILE_NAME , file . getAbsolutePath ( ) ) ) ; check ( file ) ; load ( file , false ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a single property contained in the { @link TestCase } instance onto the object instance . [CODESPLIT] public static boolean bind ( Object instance , TestCase testCase , String propertyName ) { String value = getValue ( testCase , propertyName ) ; if ( value == null ) { return false ; } return bind0 ( instance , propertyName , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a single property contained in the { @link TestCase } instance . [CODESPLIT] private static String getValue ( TestCase testCase , String propertyName ) { if ( testCase == null ) { return null ; } String propertyValue = testCase . getProperty ( propertyName ) ; if ( propertyValue == null || propertyValue . isEmpty ( ) ) { return null ; } return propertyValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value for a static field . [CODESPLIT] public static < E > E getStaticFieldValue ( Class clazz , String fieldName , Class fieldType ) { Field field = getField ( clazz , fieldName , fieldType ) ; if ( field == null ) { throw new ReflectionException ( format ( \"Field %s.%s is not found\" , clazz . getName ( ) , fieldName ) ) ; } field . setAccessible ( true ) ; return getFieldValue0 ( null , field , clazz . getName ( ) , fieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches a method by name . [CODESPLIT] public static Method getMethodByName ( Class clazz , String methodName ) { for ( Method method : clazz . getDeclaredMethods ( ) ) { if ( method . getName ( ) . equals ( methodName ) ) { return method ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "launching is done asynchronous so we don t block the calling thread ( messaging thread ) [CODESPLIT] public void launch ( CreateWorkerOperation op , Promise promise ) { WorkerParameters workerParameters = op . getWorkerParameters ( ) ; // we add the pid to the worker-parameters so the worker can check if the agent is still alive. workerParameters . set ( \"agent.pid\" , getPID ( ) ) ; WorkerProcessLauncher launcher = new WorkerProcessLauncher ( WorkerProcessManager . this , workerParameters ) ; LaunchSingleWorkerTask task = new LaunchSingleWorkerTask ( launcher , workerParameters , promise ) ; executorService . schedule ( task , op . getDelayMs ( ) , MILLISECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http : // stackoverflow . com / questions / 35842 / how - can - a - java - program - get - its - own - process - id [CODESPLIT] public static int getPID ( ) { Integer pid = getPidFromManagementBean ( ) ; if ( pid != null ) { return pid ; } pid = getPidViaReflection ( ) ; if ( pid != null ) { return pid ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sleeps a random amount of time . <p > The call is ignored if maxDelayNanos equals or smaller than zero . [CODESPLIT] public static void sleepRandomNanos ( Random random , long maxDelayNanos ) { if ( maxDelayNanos <= 0 ) { return ; } long randomValue = Math . abs ( random . nextLong ( ) + 1 ) ; sleepNanos ( randomValue % maxDelayNanos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a percentage of two numbers and adds padding to the left . [CODESPLIT] public static String formatPercentage ( long value , long baseValue ) { double percentage = ( baseValue > 0 ? ( ONE_HUNDRED * value ) / baseValue : 0 ) ; return formatDouble ( percentage , PERCENTAGE_FORMAT_LENGTH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a double number and adds padding to the left . [CODESPLIT] public static String formatDouble ( double number , int length ) { return padLeft ( format ( Locale . US , \"%,.2f\" , number ) , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats a long number and adds padding to the left . [CODESPLIT] public static String formatLong ( long number , int length ) { return padLeft ( format ( Locale . US , \"%,d\" , number ) , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the key store and our keys for encrypting / decrypting . Keys will be generated if we haven t done so yet and keys will be re - generated if the old ones have been invalidated . In both cases our K / V store will be cleared before continuing . [CODESPLIT] void prepareKeyStore ( ) { try { Key key = keyStore . getKey ( keyAlias , null ) ; Certificate certificate = keyStore . getCertificate ( keyAlias ) ; if ( key != null && certificate != null ) { try { createCipher ( ) . init ( Cipher . DECRYPT_MODE , key ) ; // We have a keys in the store and they're still valid. return ; } catch ( KeyPermanentlyInvalidatedException e ) { Log . d ( TAG , \"Key invalidated.\" ) ; } } storage . clear ( ) ; keyGenerator . initialize ( new KeyGenParameterSpec . Builder ( keyAlias , KeyProperties . PURPOSE_ENCRYPT | KeyProperties . PURPOSE_DECRYPT ) // . setBlockModes ( KeyProperties . BLOCK_MODE_ECB ) // . setUserAuthenticationRequired ( true ) // . setEncryptionPaddings ( KeyProperties . ENCRYPTION_PADDING_RSA_PKCS1 ) // . build ( ) ) ; keyGenerator . generateKeyPair ( ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "and JsonPairContext . read [CODESPLIT] protected void readJsonSyntaxChar ( byte [ ] b ) throws IOException { byte ch = reader . read ( ) ; if ( ch != b [ 0 ] ) { throw new ProtocolException ( \"Unexpected character:\" + ( char ) ch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "corresponding hex value [CODESPLIT] private static byte hexVal ( byte ch ) throws IOException { if ( ( ch >= ' ' ) && ( ch <= ' ' ) ) { return ( byte ) ( ( char ) ch - ' ' ) ; } else if ( ( ch >= ' ' ) && ( ch <= ' ' ) ) { return ( byte ) ( ( char ) ch - ' ' + 10 ) ; } else { throw new ProtocolException ( \"Expected hex character\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the bytes in array buf as a Json characters escaping as needed [CODESPLIT] private void writeJsonString ( byte [ ] b ) throws IOException { context . write ( ) ; transport . write ( QUOTE ) ; int len = b . length ; for ( int i = 0 ; i < len ; i ++ ) { if ( ( b [ i ] & 0x00FF ) >= 0x30 ) { if ( b [ i ] == BACKSLASH [ 0 ] ) { transport . write ( BACKSLASH ) ; transport . write ( BACKSLASH ) ; } else { transport . write ( b , i , 1 ) ; } } else { tmpbuf [ 0 ] = JSON_CHAR_TABLE [ b [ i ] ] ; if ( tmpbuf [ 0 ] == 1 ) { transport . write ( b , i , 1 ) ; } else if ( tmpbuf [ 0 ] > 1 ) { transport . write ( BACKSLASH ) ; transport . write ( tmpbuf , 0 , 1 ) ; } else { transport . write ( ESCSEQ ) ; tmpbuf [ 0 ] = hexChar ( ( byte ) ( b [ i ] >> 4 ) ) ; tmpbuf [ 1 ] = hexChar ( b [ i ] ) ; transport . write ( tmpbuf , 0 , 2 ) ; } } } transport . write ( QUOTE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wrapped in quotes to output as a Json string . [CODESPLIT] private void writeJsonInteger ( long num ) throws IOException { context . write ( ) ; String str = Long . toString ( num ) ; boolean escapeNum = context . escapeNum ( ) ; if ( escapeNum ) { transport . write ( QUOTE ) ; } try { byte [ ] buf = str . getBytes ( \"UTF-8\" ) ; transport . write ( buf ) ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } if ( escapeNum ) { transport . write ( QUOTE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "context dictates escaping write out as Json string . [CODESPLIT] private void writeJsonDouble ( double num ) throws IOException { context . write ( ) ; String str = Double . toString ( num ) ; boolean special = false ; switch ( str . charAt ( 0 ) ) { case ' ' : // NaN case ' ' : // Infinity special = true ; break ; case ' ' : if ( str . charAt ( 1 ) == ' ' ) { // -Infinity special = true ; } break ; default : break ; } boolean escapeNum = special || context . escapeNum ( ) ; if ( escapeNum ) { transport . write ( QUOTE ) ; } try { byte [ ] b = str . getBytes ( \"UTF-8\" ) ; transport . write ( b , 0 , b . length ) ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } if ( escapeNum ) { transport . write ( QUOTE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "context if skipContext is true . [CODESPLIT] private ByteString readJsonString ( boolean skipContext ) throws IOException { Buffer buffer = new Buffer ( ) ; ArrayList < Character > codeunits = new ArrayList <> ( ) ; if ( ! skipContext ) { context . read ( ) ; } readJsonSyntaxChar ( QUOTE ) ; while ( true ) { byte ch = reader . read ( ) ; if ( ch == QUOTE [ 0 ] ) { break ; } if ( ch == ESCSEQ [ 0 ] ) { ch = reader . read ( ) ; if ( ch == ESCSEQ [ 1 ] ) { transport . read ( tmpbuf , 0 , 4 ) ; short cu = ( short ) ( ( ( short ) hexVal ( tmpbuf [ 0 ] ) << 12 ) + ( ( short ) hexVal ( tmpbuf [ 1 ] ) << 8 ) + ( ( short ) hexVal ( tmpbuf [ 2 ] ) << 4 ) + ( short ) hexVal ( tmpbuf [ 3 ] ) ) ; try { if ( Character . isHighSurrogate ( ( char ) cu ) ) { if ( codeunits . size ( ) > 0 ) { throw new ProtocolException ( \"Expected low surrogate char\" ) ; } codeunits . add ( ( char ) cu ) ; } else if ( Character . isLowSurrogate ( ( char ) cu ) ) { if ( codeunits . size ( ) == 0 ) { throw new ProtocolException ( \"Expected high surrogate char\" ) ; } codeunits . add ( ( char ) cu ) ; buffer . write ( new String ( new int [ ] { codeunits . get ( 0 ) , codeunits . get ( 1 ) } , 0 , 2 ) . getBytes ( \"UTF-8\" ) ) ; codeunits . clear ( ) ; } else { buffer . write ( new String ( new int [ ] { cu } , 0 , 1 ) . getBytes ( \"UTF-8\" ) ) ; } continue ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } catch ( IOException ex ) { throw new ProtocolException ( \"Invalid unicode sequence\" ) ; } } else { int off = ESCAPE_CHARS . indexOf ( ch ) ; if ( off == - 1 ) { throw new ProtocolException ( \"Expected control char\" ) ; } ch = ESCAPE_CHAR_VALS [ off ] ; } } buffer . write ( new byte [ ] { ch } ) ; } return buffer . readByteString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not do a complete regex check to validate that this is actually a number . [CODESPLIT] private String readJsonNumericChars ( ) throws IOException { StringBuilder strbld = new StringBuilder ( ) ; while ( true ) { byte ch = reader . peek ( ) ; if ( ! isJsonNumeric ( ch ) ) { break ; } strbld . append ( ( char ) reader . read ( ) ) ; } return strbld . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in a Json number . If the context dictates read in enclosing quotes . [CODESPLIT] private long readJsonInteger ( ) throws IOException { context . read ( ) ; if ( context . escapeNum ( ) ) { readJsonSyntaxChar ( QUOTE ) ; } String str = readJsonNumericChars ( ) ; if ( context . escapeNum ( ) ) { readJsonSyntaxChar ( QUOTE ) ; } try { return Long . valueOf ( str ) ; } catch ( NumberFormatException ex ) { throw new ProtocolException ( \"Bad data encountered in numeric data\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "when expected or if wrapped in quotes when not expected . [CODESPLIT] private double readJsonDouble ( ) throws IOException { context . read ( ) ; if ( reader . peek ( ) == QUOTE [ 0 ] ) { ByteString str = readJsonString ( true ) ; double dub = Double . valueOf ( str . utf8 ( ) ) ; if ( ! context . escapeNum ( ) && ! Double . isNaN ( dub ) && ! Double . isInfinite ( dub ) ) { // Throw exception -- we should not be in a string in this case throw new ProtocolException ( \"Numeric data unexpectedly quoted\" ) ; } return dub ; } else { if ( context . escapeNum ( ) ) { // This will throw - we should have had a quote if escapeNum == true readJsonSyntaxChar ( QUOTE ) ; } try { return Double . valueOf ( readJsonNumericChars ( ) ) ; } catch ( NumberFormatException ex ) { throw new ProtocolException ( \"Bad data encountered in numeric data\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in a Json string containing base - 64 encoded data and decode it . [CODESPLIT] private ByteString readJsonBase64 ( ) throws IOException { ByteString str = readJsonString ( false ) ; return ByteString . decodeBase64 ( str . utf8 ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When invoked by a derived instance sends the given call to the server . [CODESPLIT] protected final Object execute ( MethodCall < ? > methodCall ) throws Exception { if ( ! running . get ( ) ) { throw new IllegalStateException ( \"Cannot write to a closed service client\" ) ; } try { return invokeRequest ( methodCall ) ; } catch ( ServerException e ) { throw e . thriftException ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the given call to the server . [CODESPLIT] final Object invokeRequest ( MethodCall < ? > call ) throws Exception { boolean isOneWay = call . callTypeId == TMessageType . ONEWAY ; int sid = seqId . incrementAndGet ( ) ; protocol . writeMessageBegin ( call . name , call . callTypeId , sid ) ; call . send ( protocol ) ; protocol . writeMessageEnd ( ) ; protocol . flush ( ) ; if ( isOneWay ) { // No response will be received return null ; } MessageMetadata metadata = protocol . readMessageBegin ( ) ; if ( metadata . seqId != sid ) { throw new ThriftException ( ThriftException . Kind . BAD_SEQUENCE_ID , \"Unrecognized sequence ID\" ) ; } if ( metadata . type == TMessageType . EXCEPTION ) { ThriftException e = ThriftException . read ( protocol ) ; protocol . readMessageEnd ( ) ; throw new ServerException ( e ) ; } else if ( metadata . type != TMessageType . REPLY ) { throw new ThriftException ( ThriftException . Kind . INVALID_MESSAGE_TYPE , \"Invalid message type: \" + metadata . type ) ; } if ( metadata . seqId != seqId . get ( ) ) { throw new ThriftException ( ThriftException . Kind . BAD_SEQUENCE_ID , \"Out-of-order response\" ) ; } if ( ! metadata . name . equals ( call . name ) ) { throw new ThriftException ( ThriftException . Kind . WRONG_METHOD_NAME , \"Unexpected method name in reply; expected \" + call . name + \" but received \" + metadata . name ) ; } try { Object result = call . receive ( protocol , metadata ) ; protocol . readMessageEnd ( ) ; return result ; } catch ( Exception e ) { if ( e instanceof Struct ) { // Business as usual protocol . readMessageEnd ( ) ; } throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////////////// [CODESPLIT] @ Override public MessageMetadata readMessageBegin ( ) throws IOException { int size = readI32 ( ) ; if ( size < 0 ) { int version = size & VERSION_MASK ; if ( version != VERSION_1 ) { throw new ProtocolException ( \"Bad version in readMessageBegin\" ) ; } return new MessageMetadata ( readString ( ) , ( byte ) ( size & 0xff ) , readI32 ( ) ) ; } else { if ( strictRead ) { throw new ProtocolException ( \"Missing version in readMessageBegin\" ) ; } return new MessageMetadata ( readStringWithSize ( size ) , readByte ( ) , readI32 ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When invoked by a derived instance places the given call in a queue to be sent to the server . [CODESPLIT] protected void enqueue ( MethodCall < ? > methodCall ) { if ( ! running . get ( ) ) { throw new IllegalStateException ( \"Cannot write to a closed service client\" ) ; } if ( ! pendingCalls . offer ( methodCall ) ) { // This should never happen with an unbounded queue throw new IllegalStateException ( \"Call queue is full\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves a file system location to an Eclipse workspace resource . [CODESPLIT] public static IFile getResourceFromFSPath ( String location ) { return Activator . getDefault ( ) . getWorkspace ( ) . getRoot ( ) . getFileForLocation ( new Path ( location ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Causes the platform to update Guvnor decoration notions . [CODESPLIT] public static void updateDecoration ( ) { final IWorkbench workbench = Activator . getDefault ( ) . getWorkbench ( ) ; workbench . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { IDecoratorManager manager = workbench . getDecoratorManager ( ) ; manager . update ( GuvnorDecorator . DECORATOR_ID ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Causes the Repository view to refresh if it is open . [CODESPLIT] public static void refreshRepositoryView ( ) { IWorkbenchWindow activeWindow = Activator . getDefault ( ) . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; // If there is no active workbench window, then there can be no Repository view if ( activeWindow == null ) { return ; } // If there is no active workbench page, then there can be no Repository view IWorkbenchPage page = activeWindow . getActivePage ( ) ; if ( page == null ) { return ; } RepositoryView view = ( RepositoryView ) page . findView ( IGuvnorConstants . REPVIEW_ID ) ; if ( view != null ) { view . refresh ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to find the Resource History view attempting to open it if necessary . [CODESPLIT] public static ResourceHistoryView getResourceHistoryView ( ) throws Exception { IWorkbenchWindow activeWindow = Activator . getDefault ( ) . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; // If there is no active workbench window, then there can be no Repository History view if ( activeWindow == null ) { return null ; } // If there is no active workbench page, then there can be no Repository History view IWorkbenchPage page = activeWindow . getActivePage ( ) ; if ( page == null ) { return null ; } return ( ResourceHistoryView ) page . showView ( IGuvnorConstants . RESHISTORYVIEW_ID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a read - only in - memory editor . [CODESPLIT] public static void openEditor ( String contents , String name ) { IWorkbenchWindow window = PlatformUI . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; IStorage storage = new StringStorage ( contents , name ) ; IStorageEditorInput input = new StringInput ( storage ) ; IWorkbenchPage page = window . getActivePage ( ) ; IEditorDescriptor desc = PlatformUI . getWorkbench ( ) . getEditorRegistry ( ) . getDefaultEditor ( name ) ; // If there is no editor associated with the given file name, we'll just // use the eclipse text editor as a default String editorId = desc != null ? desc . getId ( ) : \"org.eclipse.ui.DefaultTextEditor\" ; //$NON-NLS-1$ try { if ( page != null ) { page . openEditor ( input , editorId ) ; } } catch ( Exception e ) { Activator . getDefault ( ) . displayError ( IStatus . ERROR , e . getMessage ( ) , e , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for reporting log in failure [CODESPLIT] public static void reportAuthenticationFailure ( ) { Display display = PlatformUI . getWorkbench ( ) . getDisplay ( ) ; display . asyncExec ( new Runnable ( ) { public void run ( ) { Display display = Display . getCurrent ( ) ; Shell shell = display . getActiveShell ( ) ; MessageDialog . openError ( shell , Messages . getString ( \"login.failure.dialog.caption\" ) , //$NON-NLS-1$ Messages . getString ( \"login.failure.dialog.message\" ) ) ; //$NON-NLS-1$ } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prompts for user name and password for a given Guvnor repository . [CODESPLIT] public AuthPromptResults promptForAuthentication ( final String server ) { Display display = PlatformUI . getWorkbench ( ) . getDisplay ( ) ; AuthPromptRunnable op = new AuthPromptRunnable ( server ) ; display . syncExec ( op ) ; return op . getResults ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a buffer ( byte array ) of size <code > BUFFER_SIZE< / code > from the pool . When the buffer is no longer needed it should be put back in the pool for future use by calling <code > putBuffer< / code > . [CODESPLIT] public synchronized byte [ ] getBuffer ( ) { if ( pool . isEmpty ( ) ) return new byte [ BUFFER_SIZE ] ; byte [ ] buffer = ( byte [ ] ) pool . lastElement ( ) ; pool . removeElementAt ( pool . size ( ) - 1 ) ; return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the given buffer into the pool for future use . The size of the buffer must be <code > BUFFER_SIZE< / code > . [CODESPLIT] public synchronized void putBuffer ( byte [ ] buffer ) { Assert . isNotNull ( buffer ) ; Assert . isTrue ( buffer . length == BUFFER_SIZE ) ; if ( pool . size ( ) < MAX_BUFFERS ) pool . addElement ( buffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a page displayed when there are no servers defined . [CODESPLIT] private Control createDefaultPage ( FormToolkit kit ) { Form form = kit . createForm ( book ) ; Composite body = form . getBody ( ) ; GridLayout layout = new GridLayout ( 2 , false ) ; body . setLayout ( layout ) ; Link hlink = new Link ( body , SWT . NONE ) ; hlink . setText ( \"<a>Use the Servers View to create a new server...</a>\" ) ; hlink . setBackground ( book . getDisplay ( ) . getSystemColor ( SWT . COLOR_LIST_BACKGROUND ) ) ; GridData gd = new GridData ( SWT . LEFT , SWT . FILL , true , false ) ; hlink . setLayoutData ( gd ) ; hlink . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { // show Servers View ViewUtils . showServersView ( ) ; } } ) ; // Create the context menu for the default page final CommonViewer commonViewer = this . getCommonViewer ( ) ; if ( commonViewer != null ) { ICommonViewerSite commonViewerSite = CommonViewerSiteFactory . createCommonViewerSite ( this . getViewSite ( ) ) ; if ( commonViewerSite != null ) { // Note: actionService cannot be null final NavigatorActionService actionService = new NavigatorActionService ( commonViewerSite , commonViewer , commonViewer . getNavigatorContentService ( ) ) ; MenuManager menuManager = new MenuManager ( \"#PopupMenu\" ) ; menuManager . addMenuListener ( new IMenuListener ( ) { public void menuAboutToShow ( IMenuManager mgr ) { ISelection selection = commonViewer . getSelection ( ) ; actionService . setContext ( new ActionContext ( selection ) ) ; actionService . fillContextMenu ( mgr ) ; } } ) ; Menu menu = menuManager . createContextMenu ( body ) ; // It is necessary to set the menu in two places: // 1. The white space in the server view // 2. The text and link in the server view. If this menu is not // set, if the // user right clicks on the text or uses shortcut keys to open // the context menu, // the context menu will not come up body . setMenu ( menu ) ; hlink . setMenu ( menu ) ; } else { // if (Trace.FINEST) { // Trace.trace(Trace.STRING_FINEST, // \"The commonViewerSite is null\"); // } } } else { // if (Trace.FINEST) { // Trace.trace(Trace.STRING_FINEST, \"The commonViewer is null\"); // } } return form ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Switch between the servers and default / empty page . [CODESPLIT] void toggleDefaultPage ( ) { if ( treeViewer . getTree ( ) . getItemCount ( ) < 1 ) { book . showPage ( noServersPage ) ; } else { book . showPage ( mainPage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the animation thread [CODESPLIT] protected void startThread ( ) { if ( animationActive ) return ; stopAnimation = false ; final Display display = treeViewer == null ? Display . getDefault ( ) : treeViewer . getControl ( ) . getDisplay ( ) ; final int SLEEP = 200 ; final Runnable [ ] animator = new Runnable [ 1 ] ; animator [ 0 ] = new Runnable ( ) { public void run ( ) { if ( ! stopAnimation ) { try { int size = 0 ; String [ ] servers ; synchronized ( starting ) { size = starting . size ( ) ; servers = new String [ size ] ; starting . toArray ( servers ) ; } for ( int i = 0 ; i < size ; i ++ ) { IServer server = ServerCore . findServer ( servers [ i ] ) ; if ( server != null ) { // ServerDecorator.animate(); treeViewer . update ( server , new String [ ] { \"ICON\" } ) ; } } } catch ( Exception e ) { // if (Trace.FINEST) { // Trace.trace(Trace.STRING_FINEST, // \"Error in Servers view animation\", e); // } } display . timerExec ( SLEEP , animator [ 0 ] ) ; } } } ; Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { display . timerExec ( SLEEP , animator [ 0 ] ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given property href to this propertybehavior s list of live properties . The property href must not be <code > null< / code > and the form of this property behavior must not already be omit or keepAllAlive . [CODESPLIT] public void addProperty ( String propertyHref ) { Assert . isNotNull ( propertyHref ) ; Assert . isTrue ( getFirstChild ( root , \"omit\" ) == null ) ; //$NON-NLS-1$ Element keepalive = getFirstChild ( root , \"keepalive\" ) ; //$NON-NLS-1$ if ( keepalive == null ) keepalive = addChild ( root , \"keepalive\" , fgNamesKeepAlive , true ) ; //$NON-NLS-1$ else Assert . isTrue ( ! \"*\" . equals ( getFirstText ( keepalive ) ) ) ; //$NON-NLS-1$ addChild ( keepalive , \"href\" , //$NON-NLS-1$ encodeHref ( propertyHref ) , new String [ ] { \"href\" } , //$NON-NLS-1$ false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this propertybehavior s property hrefs . The methods <code > isMerge () < / code > and <code > isKeepAllAlive< / code > return false if this propertybehavior is in the keep some alive form . [CODESPLIT] public Enumeration getProperties ( ) throws MalformedElementException { Element keepalive = getFirstChild ( root , \"keepalive\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingKeealiveElmt\" ) , keepalive ) ; //$NON-NLS-1$ ensure ( ! \"*\" . equals ( getFirstText ( keepalive ) ) , //$NON-NLS-1$ Policy . bind ( \"ensure.wrongForm\" ) ) ; //$NON-NLS-1$ final Element firstHref = getFirstChild ( keepalive , \"href\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingHrefElmt\" ) , firstHref ) ; //$NON-NLS-1$ Enumeration e = new Enumeration ( ) { Element currentHref = firstHref ; public boolean hasMoreElements ( ) { return currentHref != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; String href = getFirstText ( currentHref ) ; currentHref = getTwin ( currentHref , true ) ; return decodeHref ( href ) ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if this propertybehavior is in the keep all alive form otherwise returns <code > false< / code > . [CODESPLIT] public boolean isKeepAllAlive ( ) throws MalformedElementException { Element child = getFirstChild ( root , childNames ) ; ensureNotNull ( Policy . bind ( \"ensure.expectingOmitOrKeepaliveElmt\" ) , child ) ; //$NON-NLS-1$ boolean isKeepAllAlive = false ; if ( isDAVElement ( child , \"keepalive\" ) ) { //$NON-NLS-1$ isKeepAllAlive = \"*\" . equals ( getFirstText ( child ) ) ; //$NON-NLS-1$ ensureNull ( Policy . bind ( \"ensure.conflictingHrefElmt\" ) , getFirstChild ( child , \"href\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } child = getNextSibling ( child , childNames ) ; ensureNull ( Policy . bind ( \"ensure.conflictingOmitOrKeepaliveElmt\" ) , child ) ; //$NON-NLS-1$ return isKeepAllAlive ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets whether this propertybehavior is in the keep all alive form or not . [CODESPLIT] public void setIsKeepAllAlive ( boolean isKeepAllAlive ) { Element child = getFirstChild ( root , childNames ) ; boolean isAlreadyKeepAllAlive = false ; if ( isDAVElement ( child , \"keepalive\" ) ) //$NON-NLS-1$ isAlreadyKeepAllAlive = \"*\" . equals ( getFirstText ( child ) ) ; //$NON-NLS-1$ if ( isKeepAllAlive ) { if ( ! isAlreadyKeepAllAlive ) { if ( child != null ) root . removeChild ( child ) ; appendChild ( root , \"keepalive\" , \"*\" ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } else if ( isAlreadyKeepAllAlive ) root . removeChild ( child ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets whether this propertybehavior is in the omit form or not . [CODESPLIT] public void setIsOmit ( boolean isOmit ) { Element child = getFirstChild ( root , childNames ) ; boolean isAlreadyOmit = isDAVElement ( child , \"omit\" ) ; //$NON-NLS-1$ if ( isOmit ) { if ( ! isAlreadyOmit ) { if ( child != null ) root . removeChild ( child ) ; appendChild ( root , \"omit\" ) ; //$NON-NLS-1$ } } else if ( isAlreadyOmit ) root . removeChild ( child ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given href to this activelock s locktoken . The href must not be <code > null< / code > . [CODESPLIT] public void addLockTokenHref ( String href ) { Assert . isNotNull ( href ) ; Element locktoken = getLastChild ( root , \"locktoken\" ) ; //$NON-NLS-1$ if ( locktoken == null ) locktoken = setChild ( root , \"locktoken\" , childNames , false ) ; //$NON-NLS-1$ appendChild ( locktoken , \"href\" , encodeHref ( href ) ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the depth of this activelock ; for example <code > Context . DEPTH_ZERO< / code > . [CODESPLIT] public String getDepth ( ) throws MalformedElementException { String depth = getChildText ( root , \"depth\" , false ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingDepthElmt\" ) , depth ) ; //$NON-NLS-1$ ensure ( depth . equals ( IContext . DEPTH_ZERO ) || depth . equals ( IContext . DEPTH_ONE ) || depth . equals ( IContext . DEPTH_INFINITY ) , Policy . bind ( \"ensure.invalidDepth\" , depth ) ) ; //$NON-NLS-1$ return depth ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > of <code > String< / code > s containing this activelock s lock token hrefs . [CODESPLIT] public Enumeration getLockTokenHrefs ( ) throws MalformedElementException { Element locktoken = getLastChild ( root , \"locktoken\" ) ; //$NON-NLS-1$ Element firstHref = null ; if ( locktoken != null ) { firstHref = getFirstChild ( locktoken , \"href\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingHrefElmt\" ) , firstHref ) ; //$NON-NLS-1$ } final Node node = firstHref ; Enumeration e = new Enumeration ( ) { Node currentHref = node ; public boolean hasMoreElements ( ) { return currentHref != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) { throw new NoSuchElementException ( ) ; } String href = getFirstText ( ( Element ) currentHref ) ; currentHref = getTwin ( ( Element ) currentHref , true ) ; return decodeHref ( href ) ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this activelock s owner or <code > null< / code > if this active lock has no owner . [CODESPLIT] public Owner getOwner ( ) throws MalformedElementException { Element owner = getLastChild ( root , \"owner\" ) ; //$NON-NLS-1$ if ( owner == null ) return null ; return new Owner ( owner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the depth of this activelock to the given depth . The depth must not be null and must be one of : <ul > <li > <code > Context . DEPTH_ZERO< / code > <li > <code > Context . DEPTH_ONE< / code > <li > <code > Context . DEPTH_INFINITY< / code > < / ul > [CODESPLIT] public void setDepth ( String depth ) { Assert . isNotNull ( depth ) ; Assert . isTrue ( depth . equals ( IContext . DEPTH_ZERO ) || depth . equals ( IContext . DEPTH_ONE ) || depth . equals ( IContext . DEPTH_INFINITY ) ) ; setChild ( root , \"depth\" , depth , childNames , false ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets whether this activelock is shared or exclusive . If isShared is <code > true< / code > the activelock is set as shared otherwise the activelock is set as exclusive . [CODESPLIT] public void setIsShared ( boolean isShared ) { Element lockscope = setChild ( root , \"lockscope\" , childNames , true ) ; //$NON-NLS-1$ if ( isShared ) appendChild ( lockscope , \"shared\" ) ; //$NON-NLS-1$ else appendChild ( lockscope , \"exclusive\" ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and sets an owner element on this activelock and returns an editor on it . [CODESPLIT] public Owner setOwner ( ) { Element owner = setChild ( root , \"owner\" , childNames , false ) ; //$NON-NLS-1$ Owner result = null ; try { result = new Owner ( owner ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the timeout on this activelock to the given timeout . If the timeout is <code > null< / code > the current timeout is removed . [CODESPLIT] public void setTimeout ( String timeout ) { if ( timeout == null ) { Element child = getLastChild ( root , \"timeout\" ) ; //$NON-NLS-1$ if ( child != null ) root . removeChild ( child ) ; } else setChild ( root , \"timeout\" , timeout , childNames , false ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public String getPreferenceName ( String name ) { String canonicalName = getCanonicalName ( getRoot ( ) . getName ( ) ) ; if ( name == null ) return canonicalName ; return canonicalName + IKieConstants . PREF_PATH_SEPARATOR + getCanonicalName ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new WebDAV lockinfo element and sets it as the root of the given document . Returns an editor on the new lockinfo element . The document must not be <code > null< / code > and must not already have a root element . [CODESPLIT] public static LockInfo create ( Document document ) { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getOwnerDocument ( ) == null ) ; Element element = create ( document , \"lockinfo\" ) ; //$NON-NLS-1$ Element locktype = appendChild ( element , \"locktype\" ) ; //$NON-NLS-1$ appendChild ( locktype , \"write\" ) ; //$NON-NLS-1$ LockInfo result = null ; try { result = new LockInfo ( element ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if this lockinfo is shared and <code > false< / code > if it is exclusive . [CODESPLIT] public boolean isShared ( ) throws MalformedElementException { Element lockscope = getFirstChild ( root , \"lockscope\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingLockscopeElmt\" ) , lockscope ) ; //$NON-NLS-1$ String [ ] names = new String [ ] { \"shared\" , \"exclusive\" } ; //$NON-NLS-1$ //$NON-NLS-2$ Element sharedOrExclusive = getFirstChild ( lockscope , names ) ; ensureNotNull ( Policy . bind ( \"ensure.missingSharedOrExclusiveElmt\" ) , sharedOrExclusive ) ; //$NON-NLS-1$ boolean isShared = isDAVElement ( sharedOrExclusive , \"shared\" ) ; //$NON-NLS-1$ ensure ( getNextSibling ( sharedOrExclusive , names ) == null , Policy . bind ( \"ensure.conflictingSharedOrExclusiveElmt\" ) ) ; //$NON-NLS-1$ return isShared ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a ConditionFactor to a ConditionTerm . [CODESPLIT] public void addConditionFactor ( ConditionFactor factor ) throws WebDAVException { if ( conditionFactors . contains ( factor ) ) throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseDuplicateEntry\" ) ) ; //$NON-NLS-1$ conditionFactors . addElement ( factor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ConditionTerm by parsing the given If header as defined by section 9 . 4 in the WebDAV spec . [CODESPLIT] public static ConditionTerm create ( StreamTokenizer tokenizer ) throws WebDAVException { ConditionTerm term = new ConditionTerm ( ) ; try { int token = tokenizer . ttype ; if ( token == ' ' ) token = tokenizer . nextToken ( ) ; else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \"(\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ while ( token == StreamTokenizer . TT_WORD || token == ' ' || token == ' ' ) { term . addConditionFactor ( ConditionFactor . create ( tokenizer ) ) ; token = tokenizer . ttype ; } if ( token == ' ' ) token = tokenizer . nextToken ( ) ; else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \")\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } catch ( IOException exc ) { // ignore or log? } if ( ! term . getConditionFactors ( ) . hasMoreElements ( ) ) throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissingStateOrEntity\" ) ) ; //$NON-NLS-1$ return term ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if this ConditionTerm matches the given ConditionTerm . This is an AND operation . All the factors in the ConditionTerm must match . [CODESPLIT] public boolean matches ( ConditionTerm conditionTerm ) { int numberOfItemsToMatch = 0 ; boolean match = true ; Enumeration factors = getConditionFactors ( ) ; while ( match && factors . hasMoreElements ( ) ) { ConditionFactor factor = ( ConditionFactor ) factors . nextElement ( ) ; if ( factor . not ( ) ) { match = ! conditionTerm . contains ( factor ) ; } else { match = conditionTerm . contains ( factor ) ; numberOfItemsToMatch ++ ; } } match = match && numberOfItemsToMatch == conditionTerm . numberOfFactors ( ) ; return match ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the appropriate content assistance for each partition . [CODESPLIT] public IContentAssistant getContentAssistant ( ISourceViewer sourceViewer ) { ContentAssistant assistant = new ContentAssistant ( ) ; assistant . setContentAssistProcessor ( new DefaultCompletionProcessor ( getEditor ( ) ) , IDocument . DEFAULT_CONTENT_TYPE ) ; assistant . setContentAssistProcessor ( new DSLRuleCompletionProcessor ( getEditor ( ) ) , DRLPartionScanner . RULE_PART_CONTENT ) ; assistant . setProposalPopupOrientation ( IContentAssistant . PROPOSAL_OVERLAY ) ; assistant . setAutoActivationDelay ( 0 ) ; return assistant ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void propertyChange ( PropertyChangeEvent evt ) { String prop = evt . getPropertyName ( ) ; if ( GraphicalVertex . SIZE_PROP . equals ( prop ) || GraphicalVertex . LOCATION_PROP . equals ( prop ) ) { refreshVisuals ( ) ; } else if ( GraphicalVertex . SOURCE_CONNECTIONS_PROP . equals ( prop ) ) { refreshSourceConnections ( ) ; } else if ( GraphicalVertex . TARGET_CONNECTIONS_PROP . equals ( prop ) ) { refreshTargetConnections ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] protected void refreshVisuals ( ) { Rectangle bounds = new Rectangle ( getCastedModel ( ) . getLocation ( ) , getCastedModel ( ) . getSize ( ) ) ; ( ( GraphicalEditPart ) getParent ( ) ) . setLayoutConstraint ( this , getFigure ( ) , bounds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getAdapter ( @ SuppressWarnings ( \"rawtypes\" ) Class key ) { if ( key == IPropertySource . class ) { return propertySource ; } return super . getAdapter ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "$NON - NLS - 1$ [CODESPLIT] @ Override public void initializeRuntimes ( List < RuntimeDefinition > serverDefinitions ) { IRuntime [ ] existingRuntimes = DroolsRuntimeManager . getDefault ( ) . getConfiguredRuntimes ( ) ; List < DroolsRuntime > droolsRuntimes = new ArrayList < DroolsRuntime > ( ) ; if ( existingRuntimes != null ) { for ( IRuntime runtime : existingRuntimes ) { if ( runtime instanceof DroolsRuntime ) droolsRuntimes . add ( ( DroolsRuntime ) runtime ) ; } } initializeInternal ( serverDefinitions , droolsRuntimes ) ; if ( droolsRuntimes . size ( ) > 0 ) { DroolsRuntime [ ] dra = droolsRuntimes . toArray ( new DroolsRuntime [ 0 ] ) ; DroolsRuntimeManager . getDefault ( ) . setRuntimes ( dra ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * create and returns a java project based on the current editor input or returns null [CODESPLIT] private IJavaProject getCurrentJavaProject ( ) { IEditorInput input = getEditor ( ) . getEditorInput ( ) ; if ( ! ( input instanceof IFileEditorInput ) ) { return null ; } IProject project = ( ( IFileEditorInput ) input ) . getFile ( ) . getProject ( ) ; IJavaProject javaProject = JavaCore . create ( project ) ; return javaProject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * do we already have a completion for that string that would be either a local variable or a field? [CODESPLIT] protected static boolean doesNotContainFieldCompletion ( String completion , List < ICompletionProposal > completions ) { if ( completion == null || completion . length ( ) == 0 || completions == null ) { return false ; } for ( Iterator < ICompletionProposal > iter = completions . iterator ( ) ; iter . hasNext ( ) ; ) { Object o = iter . next ( ) ; if ( o instanceof AbstractJavaCompletionProposal ) { AbstractJavaCompletionProposal prop = ( AbstractJavaCompletionProposal ) o ; String content = prop . getReplacementString ( ) ; if ( completion . equals ( content ) ) { IJavaElement javaElement = prop . getJavaElement ( ) ; if ( javaElement instanceof ILocalVariable || javaElement instanceof IField ) { return false ; } } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a reader to the DSL contents [CODESPLIT] public static Reader getDSLContent ( String ruleSource , IResource input ) throws CoreException { String dslFileName = findDSLConfigName ( ruleSource , input ) ; if ( dslFileName == null ) { return null ; } IResource res = findDSLResource ( input , dslFileName ) ; if ( res instanceof IFile ) { IFile dslConf = ( IFile ) res ; if ( dslConf . exists ( ) ) { return new InputStreamReader ( dslConf . getContents ( ) ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This does the hunting around the projec to find the . dsl file . [CODESPLIT] private void loadConfig ( IFile input ) { IResource res = findDSLResource ( input , dslConfigName ) ; if ( res instanceof IFile ) { IFile dslConf = ( IFile ) res ; if ( dslConf . exists ( ) ) { InputStream stream = null ; try { stream = dslConf . getContents ( ) ; readConfig ( stream ) ; valid = true ; } catch ( Exception e ) { throw new IllegalStateException ( \"Unable to open DSL config file. (Exception: \" + e . getMessage ( ) + \")\" ) ; } finally { closeStream ( stream ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will load in the DSL config file using the DSLMapping from drools - compiler [CODESPLIT] void readConfig ( InputStream stream ) throws IOException , CoreException { DSLTokenizedMappingFile file = new DSLTokenizedMappingFile ( ) ; file . parseAndLoad ( new InputStreamReader ( stream ) ) ; DSLMapping grammar = file . getMapping ( ) ; List < DSLMappingEntry > conditions = grammar . getEntries ( DSLMappingEntry . CONDITION ) ; List < DSLMappingEntry > consequences = grammar . getEntries ( DSLMappingEntry . CONSEQUENCE ) ; conditionProposals = buildProposals ( conditions ) ; consequenceProposals = buildProposals ( consequences ) ; dslTree . buildTree ( grammar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sniffs out the expander / DSL config name as best it can . [CODESPLIT] static String findDSLConfigName ( String content ) { String name = null ; Matcher matches = EXPANDER_PATTERN . matcher ( content ) ; if ( matches . find ( ) ) { name = matches . group ( 1 ) + \".dsl\" ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the given <code > URL< / code > with a trailing slash appended to it . If the <code > URL< / code > already has a trailing slash the <code > URL< / code > is returned unchanged . <table > <caption > Example< / caption > <tr > <th > Given URL< / th > <th > Returned URL< / th > <tr > <td > http : // hostname / folder < / td > <td > http : // hostname / folder / < / td > <tr > <td > http : // hostname / folder / < / td > <td > http : // hostname / folder / < / td > < / table > [CODESPLIT] public static URL appendTrailingSlash ( URL url ) { String file = url . getFile ( ) ; if ( file . endsWith ( \"/\" ) ) { //$NON-NLS-1$ return url ; } try { return new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , file + \"/\" ) ; //$NON-NLS-1$ } catch ( MalformedURLException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the child URL formed by joining the given member with the given parent URL . [CODESPLIT] public static URL getChild ( String parent , String member ) throws MalformedURLException { return getChild ( new URL ( parent ) , member ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the child URL formed by joining the given member with the given parent URL . [CODESPLIT] public static URL getChild ( URL parent , String member ) { String file = parent . getFile ( ) ; if ( ! file . endsWith ( \"/\" ) ) //$NON-NLS-1$ file = file + \"/\" ; //$NON-NLS-1$ try { return new URL ( parent . getProtocol ( ) , parent . getHost ( ) , parent . getPort ( ) , file + member ) ; } catch ( MalformedURLException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all elements in the given URLs path . <table > <caption > Example< / caption > <tr > <th > Given URL< / th > <th > Element< / th > <tr > <td > http : // hostname / < / td > <td > [] < / td > <tr > <td > http : // hostname / folder / < / td > <td > [ folder ] < / td > <tr > <td > http : // hostname / folder / file< / td > <td > [ folder file ] < / td > < / table > [CODESPLIT] public static Vector getElements ( URL url ) { Vector result = new Vector ( 5 ) ; String lastElement = null ; while ( ( lastElement = getLastElement ( url ) ) != null ) { result . insertElementAt ( lastElement , 0 ) ; url = getParent ( url ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last element in the given URLs path or <code > null< / code > if the URL is the root . <table > <caption > Example< / caption > <tr > <th > Given URL< / th > <th > Last Element< / th > <tr > <td > http : // hostname / < / td > <td > null< / td > <tr > <td > http : // hostname / folder / < / td > <td > folder< / td > <tr > <td > http : // hostname / folder / file< / td > <td > file< / td > < / table > [CODESPLIT] public static String getLastElement ( URL url ) { String file = url . getFile ( ) ; int len = file . length ( ) ; if ( len == 0 || len == 1 && file . charAt ( 0 ) == ' ' ) { return null ; } int lastSlashIndex = - 1 ; for ( int i = len - 2 ; lastSlashIndex == - 1 && i >= 0 ; -- i ) { if ( file . charAt ( i ) == ' ' ) { lastSlashIndex = i ; } } boolean isDirectory = file . charAt ( len - 1 ) == ' ' ; if ( lastSlashIndex == - 1 ) { if ( isDirectory ) return file . substring ( 0 , len - 1 ) ; return file ; } if ( isDirectory ) return file . substring ( lastSlashIndex + 1 , len - 1 ) ; return file . substring ( lastSlashIndex + 1 , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the parent URL of the given URL or <code > null< / code > if the given URL is the root . <table > <caption > Example< / caption > <tr > <th > Given URL< / th > <th > Parent URL< / th > <tr > <td > http : // hostname / < / td > <td > null< / td > <tr > <td > http : // hostname / folder / file< / td > <td > http : // hostname / folder / < / td > < / table > [CODESPLIT] public static URL getParent ( URL url ) { String file = url . getFile ( ) ; int len = file . length ( ) ; if ( len == 0 || len == 1 && file . charAt ( 0 ) == ' ' ) return null ; int lastSlashIndex = - 1 ; for ( int i = len - 2 ; lastSlashIndex == - 1 && i >= 0 ; -- i ) { if ( file . charAt ( i ) == ' ' ) lastSlashIndex = i ; } if ( lastSlashIndex == - 1 ) file = \"\" ; //$NON-NLS-1$ else file = file . substring ( 0 , lastSlashIndex + 1 ) ; try { url = new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , file ) ; } catch ( MalformedURLException e ) { Assert . isTrue ( false , e . getMessage ( ) ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the root URL of the given URL . <table > <caption > Example< / caption > <tr > <th > Given URL< / th > <th > Root URL< / th > <tr > <td > http : // hostname / < / td > <td > http : // hostname / < / td > <tr > <td > http : // hostname / folder / file< / td > <td > http : // hostname / < / td > < / table > [CODESPLIT] public static URL getRoot ( URL url ) { try { return new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ } catch ( MalformedURLException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the given URL with its trailing slash removed . If the URL has no trailing slash the URL is returned unchanged . <table > <caption > Example< / caption > <tr > <th > Given URL< / th > <th > Returned URL< / th > <tr > <td > http : // hostname / folder < / td > <td > http : // hostname / folder < / td > <tr > <td > http : // hostname / folder / < / td > <td > http : // hostname / folder < / td > < / table > [CODESPLIT] public static URL removeTrailingSlash ( URL url ) { String file = url . getFile ( ) ; if ( file . endsWith ( \"/\" ) ) { //$NON-NLS-1$ file = file . substring ( 0 , file . length ( ) - 1 ) ; try { return new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , file ) ; } catch ( MalformedURLException e ) { Assert . isTrue ( false , e . getMessage ( ) ) ; } } else { return url ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a boolean indicating whether the given URLs overlap . <table > <caption > Example< / caption > <tr > <th > First URL< / th > <th > Second URL< / th > <th > Do they overlap< / th > <tr > <td > http : // hostname / folder / < / td > <td > http : // hostname / folder / < / td > <td > true< / td > <tr > <td > http : // hostname / folder / < / td > <td > http : // hostname / folder / file < / td > <td > true< / td > <tr > <td > http : // hostname / folder / file < / td > <td > http : // hostname / folder / < / td > <td > true< / td > <tr > <td > http : // hostname / folder1 / < / td > <td > http : // hostname / folder2 / < / td > <td > false< / td > < / table > [CODESPLIT] public static boolean urlsOverlap ( String url1 , String url2 ) throws MalformedURLException { return urlsOverlap ( new URL ( url1 ) , new URL ( url2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a boolean indicating whether the given URLs overlap . <table > <caption > Example< / caption > <tr > <th > First URL< / th > <th > Second URL< / th > <th > Do they overlap< / th > <tr > <td > http : // hostname / folder / < / td > <td > http : // hostname / folder / < / td > <td > true< / td > <tr > <td > http : // hostname / folder / < / td > <td > http : // hostname / folder / file < / td > <td > true< / td > <tr > <td > http : // hostname / folder / file < / td > <td > http : // hostname / folder / < / td > <td > true< / td > <tr > <td > http : // hostname / folder1 / < / td > <td > http : // hostname / folder2 / < / td > <td > false< / td > <tr > <td > http : // hostname1 / folder / < / td > <td > http : // hostname2 / folder / < / td > <td > false< / td > < / table > [CODESPLIT] public static boolean urlsOverlap ( URL url1 , URL url2 ) { if ( ! getRoot ( url1 ) . equals ( getRoot ( url2 ) ) ) { return false ; } Vector elements1 = URLTool . getElements ( url1 ) ; Vector elements2 = URLTool . getElements ( url2 ) ; for ( int i = 0 ; i < elements1 . size ( ) && i < elements2 . size ( ) ; ++ i ) { String element1 = ( String ) elements1 . elementAt ( i ) ; String element2 = ( String ) elements2 . elementAt ( i ) ; if ( ! element1 . equals ( element2 ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a menu which launches the various wizards [CODESPLIT] public Menu getMenu ( Control parent ) { setMenu ( new Menu ( parent ) ) ; final Shell shell = parent . getShell ( ) ; addProjectWizard ( menu , shell ) ; addRuleWizard ( menu , shell ) ; addDSLWizard ( menu , shell ) ; addDTWizard ( menu , shell ) ; return menu ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the content length of this message s body or - 1 if the content length is unknown . [CODESPLIT] public long getContentLength ( ) { // Get the declared content length. long contentLength = context . getContentLength ( ) ; // If it is defined send the answer. if ( contentLength != - 1 ) return contentLength ; // Certain messages are defined as having zero length // message bodies. int statusCode = getStatusCode ( ) ; if ( statusCode == IResponse . SC_NO_CONTENT || statusCode == IResponse . SC_NOT_MODIFIED || statusCode >= 100 && statusCode < 200 ) return 0 ; // We don't know how long the body is. return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the content type of this response s body or <code > null< / code > if the content type is unknown . [CODESPLIT] public ContentType getContentType ( ) { String contentTypeString = context . getContentType ( ) ; if ( contentTypeString == null ) return null ; ContentType contentType = null ; try { contentType = new ContentType ( contentTypeString ) ; } catch ( IllegalArgumentException e ) { // ignore or log? } return contentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this response s body as a DOM <code > Document< / code > . This response must have a document body . [CODESPLIT] public Document getDocumentBody ( ) throws IOException { Assert . isTrue ( hasDocumentBody ) ; Assert . isTrue ( ! hasInputStream ) ; // Lazily parse the message body. if ( document == null ) { String characterEncoding = null ; ContentType contentType = getContentType ( ) ; if ( contentType != null ) { characterEncoding = contentType . getValue ( \"charset\" ) ; //$NON-NLS-1$ } if ( characterEncoding == null ) { characterEncoding = \"ASCII\" ; //$NON-NLS-1$ } IDocumentMarshaler marshaler = new DocumentMarshaler ( ) ; document = marshaler . parse ( new InputStreamReader ( is , characterEncoding ) ) ; } return document ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String getHtml ( ) { return NODE_NAME + \" : \" + this . node . getId ( ) + \" : \" + this . node . getQueryElement ( ) == null ? \"\" : this . node . getQueryElement ( ) . getQueryName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and adds a response element to this multistatus and returns an editor on it . [CODESPLIT] public ResponseBody addResponse ( ) { Element response = addChild ( root , \"response\" , childNames , true ) ; //$NON-NLS-1$ try { return new ResponseBody ( response ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new WebDAV multistatus element and sets it as the root of the given document . Returns an editor on the new multistatus element . <p > The document must not be <code > null< / code > and must not already have a root element . < / p > [CODESPLIT] public static MultiStatus create ( Document document ) { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getOwnerDocument ( ) == null ) ; Element element = create ( document , \"multistatus\" ) ; //$NON-NLS-1$ try { return new MultiStatus ( element ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this multistatus responses . [CODESPLIT] public Enumeration getResponses ( ) throws MalformedElementException { final Element firstResponse = getFirstChild ( root , \"response\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingResponseElmt\" ) , firstResponse ) ; //$NON-NLS-1$ Enumeration e = new Enumeration ( ) { Element currentResponse = firstResponse ; public boolean hasMoreElements ( ) { return currentResponse != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; ResponseBody responseBody = null ; try { responseBody = new ResponseBody ( currentResponse ) ; } catch ( MalformedElementException ex ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } currentResponse = getTwin ( currentResponse , true ) ; return responseBody ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "$NON - NLS - 1$ [CODESPLIT] private boolean isGuvnorResource ( Object element ) { if ( element instanceof IResource ) { return GuvnorMetadataUtils . findGuvnorMetadata ( ( IResource ) element ) != null ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given href to the end of the set of hrefs . If the href already exists it is not added . [CODESPLIT] public void addHref ( String href ) { String encodedHref = encodeHref ( href ) ; if ( isDuplicate ( encodedHref ) ) return ; appendChild ( root , \"href\" , encodedHref ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new href set element with the given name and sets it as the root of the given document . Returns an editor on the new href set element . The document must not be <code > null< / code > and must not already have a root element . [CODESPLIT] public static HrefSet create ( Document document , QualifiedName name ) { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getOwnerDocument ( ) == null ) ; Assert . isNotNull ( name ) ; Assert . isTrue ( DAV_NS . equals ( name . getQualifier ( ) ) ) ; Element element = create ( document , name . getLocalName ( ) ) ; try { return new HrefSet ( element , name ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over the set of hrefs . [CODESPLIT] public Enumeration getHrefs ( ) { final Element firstHref = getFirstChild ( root , \"href\" ) ; //$NON-NLS-1$ Enumeration e = new Enumeration ( ) { Element currentHref = firstHref ; public boolean hasMoreElements ( ) { return currentHref != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; String href = getFirstText ( currentHref ) ; currentHref = getNextSibling ( currentHref , \"href\" ) ; //$NON-NLS-1$ return decodeHref ( href ) ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the given newHref before the given refHref in the set of hrefs . If newHref already exists it is not inserted . [CODESPLIT] public void insertHrefBefore ( String newHref , String refHref ) { String refHrefEncoded = encodeHref ( refHref ) ; String newHrefEncoded = encodeHref ( newHref ) ; if ( isDuplicate ( newHrefEncoded ) ) return ; Element child = getFirstChild ( root , \"href\" ) ; //$NON-NLS-1$ while ( child != null ) { if ( refHrefEncoded . equals ( getFirstText ( child ) ) ) { insertBefore ( child , \"href\" , newHrefEncoded ) ; //$NON-NLS-1$ return ; } child = getNextSibling ( child , \"href\" ) ; //$NON-NLS-1$ } Assert . isTrue ( false , Policy . bind ( \"assert.noHrefRef\" ) ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given href from the set of hrefs . [CODESPLIT] public void removeHref ( String href ) { String encodedHref = encodeHref ( href ) ; Element child = getFirstChild ( root , \"href\" ) ; //$NON-NLS-1$ while ( child != null ) { if ( encodedHref . equals ( getFirstText ( child ) ) ) { root . removeChild ( child ) ; return ; } child = getNextSibling ( child , \"href\" ) ; //$NON-NLS-1$ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets this response s first propstat with the given status and adds an element created from the given property name as a property of the propstat s prop . If such a propstat does not exists it is created . The propstat s response description is set to the given response description or removed if the response description is <code > null< / code > . Returns the propstat . The property name must not be <code > null< / code > and its qualifier and local part must not be <code > null< / code > and must not be the empty string . The status must not be <code > null< / code > . This response must not already be in the status form . [CODESPLIT] public PropStat accumulatePropStat ( QualifiedName propertyName , String status , String responseDescription ) { Assert . isNotNull ( propertyName ) ; Assert . isNotNull ( status ) ; Element child = getFirstChild ( root , new String [ ] { \"href\" , \"status\" } ) ; //$NON-NLS-1$ //$NON-NLS-2$ Assert . isTrue ( child == null || isDAVElement ( child , \"href\" ) //$NON-NLS-1$ && getNextSibling ( child , new String [ ] { \"href\" , \"status\" } ) == null ) ; //$NON-NLS-1$ //$NON-NLS-2$ String nsName = propertyName . getQualifier ( ) ; Assert . isTrue ( ! \"\" . equals ( nsName ) ) ; //$NON-NLS-1$ String localName = propertyName . getLocalName ( ) ; Assert . isNotNull ( localName ) ; Assert . isTrue ( ! localName . equals ( \"\" ) ) ; //$NON-NLS-1$ Document document = root . getOwnerDocument ( ) ; Element element = document . createElement ( localName ) ; declareNS ( element , null , nsName ) ; try { return accumulatePropStat ( element , status , responseDescription ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets this response s first propstat with the given status and adds a clone of the given element as a property of its prop . If such a propstat does not exists it is created . The propstat s response description is set to the given response description or removed if the response description is <code > null< / code > . Returns the propstat . The element and status must not be <code > null< / code > . This response must not already be in the status form . [CODESPLIT] public PropStat accumulatePropStat ( Element element , String status , String responseDescription ) throws MalformedElementException { Assert . isNotNull ( element ) ; Assert . isNotNull ( status ) ; Element child = getFirstChild ( root , new String [ ] { \"href\" , \"status\" } ) ; //$NON-NLS-1$ //$NON-NLS-2$ Assert . isTrue ( child == null || isDAVElement ( child , \"href\" ) //$NON-NLS-1$ && getNextSibling ( child , new String [ ] { \"href\" , \"status\" } ) == null ) ; //$NON-NLS-1$ //$NON-NLS-2$ boolean found = false ; Element propstat = getFirstChild ( root , \"propstat\" ) ; //$NON-NLS-1$ while ( ! found && propstat != null ) { String text = getChildText ( propstat , \"status\" , false ) ; //$NON-NLS-1$ if ( text != null && text . equals ( status ) ) found = true ; else propstat = getTwin ( propstat , true ) ; } Element prop = null ; if ( propstat == null ) { propstat = addChild ( root , \"propstat\" , fgNamesPropStat , false ) ; //$NON-NLS-1$ prop = setChild ( propstat , \"prop\" , PropStat . childNames , true ) ; //$NON-NLS-1$ setChild ( propstat , \"status\" , status , PropStat . childNames , false ) ; //$NON-NLS-1$ } else { prop = getFirstChild ( propstat , \"prop\" ) ; //$NON-NLS-1$ if ( prop == null ) prop = setChild ( propstat , \"prop\" , PropStat . childNames , true ) ; //$NON-NLS-1$ } if ( responseDescription == null ) { Element responsedescription = getLastChild ( propstat , \"responsedescription\" ) ; //$NON-NLS-1$ if ( responsedescription != null ) propstat . removeChild ( responsedescription ) ; } else setChild ( propstat , \"responsedescription\" , //$NON-NLS-1$ responseDescription , PropStat . childNames , false ) ; extractNode ( prop , element ) ; try { return new PropStat ( propstat ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given href to this response . If <code > setHref ( String ) < / code > hasn t been called and no hrefs have been added this method sets the first href and is thus equivalent to <code > setHref ( String ) < / code > . The href must not be <code > null< / code > . This response must not already be in propstat form . [CODESPLIT] public void addHref ( String href ) { Assert . isNotNull ( href ) ; Assert . isTrue ( getLastChild ( root , \"propstat\" ) == null ) ; //$NON-NLS-1$ addChild ( root , \"href\" , encodeHref ( href ) , fgNamesStatus , false ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and adds a propstat element on this response and returns an editor on it . [CODESPLIT] public PropStat addPropStat ( ) { Element firstHref = getFirstChild ( root , \"href\" ) ; //$NON-NLS-1$ Assert . isTrue ( firstHref == null || getNextSibling ( firstHref , new String [ ] { \"href\" , \"status\" } ) == null ) ; //$NON-NLS-1$ //$NON-NLS-2$ Element element = addChild ( root , \"propstat\" , fgNamesPropStat , false ) ; //$NON-NLS-1$ try { return new PropStat ( element ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes all of this response s propstats with the given old status to have the given new status . In addition their response descriptions are changed to be the given response description or removed if the given response description is <code > null< / code > . The old status and new status must not be <code > null< / null > . This response must not be in the status form . [CODESPLIT] public void changePropStatStatus ( String oldStatus , String newStatus , String responseDescription ) { Assert . isNotNull ( oldStatus ) ; Assert . isNotNull ( newStatus ) ; Element firstHref = getFirstChild ( root , \"href\" ) ; //$NON-NLS-1$ Assert . isTrue ( firstHref == null || getNextSibling ( firstHref , new String [ ] { \"href\" , \"status\" } ) == null ) ; //$NON-NLS-1$ //$NON-NLS-2$ Element propstat = getFirstChild ( root , \"propstat\" ) ; //$NON-NLS-1$ while ( propstat != null ) { String status = getChildText ( propstat , \"status\" , true ) ; //$NON-NLS-1$ if ( oldStatus . equals ( status ) ) { setChild ( propstat , \"status\" , newStatus , PropStat . childNames , true ) ; //$NON-NLS-1$ if ( responseDescription == null ) { Element responsedescription = getLastChild ( propstat , \"responsedescription\" ) ; //$NON-NLS-1$ if ( responsedescription != null ) propstat . removeChild ( responsedescription ) ; } else setChild ( propstat , \"responsedescription\" , //$NON-NLS-1$ responseDescription , PropStat . childNames , false ) ; } propstat = getTwin ( propstat , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this response s first href . [CODESPLIT] public String getHref ( ) throws MalformedElementException { String href = getChildText ( root , \"href\" , true ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingHrefElmt\" ) , href ) ; //$NON-NLS-1$ return decodeHref ( href ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > of this response s hrefs ( not including the first href ) . [CODESPLIT] public Enumeration getHrefs ( ) throws MalformedElementException { final Node firstHref = getFirstChild ( root , \"href\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingHrefElmt\" ) , firstHref ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingStatusElmt\" ) , //$NON-NLS-1$ getNextSibling ( ( Element ) firstHref , \"status\" ) ) ; //$NON-NLS-1$ Enumeration e = new Enumeration ( ) { Node currentHref = getTwin ( ( Element ) firstHref , true ) ; public boolean hasMoreElements ( ) { return currentHref != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; String href = getFirstText ( ( Element ) currentHref ) ; currentHref = getTwin ( ( Element ) currentHref , true ) ; return decodeHref ( href ) ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > of this response s <code > Propstat< / code > s . [CODESPLIT] public Enumeration getPropStats ( ) throws MalformedElementException { final Element firstPropStat = getFirstChild ( root , \"propstat\" ) ; //$NON-NLS-1$ ensureNotNull ( \"ensure.missingPropstatElmt\" , firstPropStat ) ; //$NON-NLS-1$ Enumeration e = new Enumeration ( ) { Element currentPropStat = firstPropStat ; public boolean hasMoreElements ( ) { return currentPropStat != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; PropStat result = null ; try { result = new PropStat ( currentPropStat ) ; } catch ( MalformedElementException ex ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } currentPropStat = getTwin ( currentPropStat , true ) ; return result ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this response s status . [CODESPLIT] public String getStatus ( ) throws MalformedElementException { Element status = getFirstChild ( root , \"status\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingStatusElmt\" ) , status ) ; //$NON-NLS-1$ return getFirstText ( status ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if this response is in propstat form and <code > false< / code > if it is in status form . [CODESPLIT] public boolean isPropStat ( ) throws MalformedElementException { Element child = getFirstChild ( root , new String [ ] { \"status\" , \"propstat\" } ) ; //$NON-NLS-1$ //$NON-NLS-2$ ensureNotNull ( Policy . bind ( \"ensure.missingStatusOrPropstatElmt\" ) , child ) ; //$NON-NLS-1$ boolean isPropStat = isDAVElement ( child , \"propstat\" ) ; //$NON-NLS-1$ if ( isPropStat ) child = getNextSibling ( child , \"status\" ) ; //$NON-NLS-1$ else child = getNextSibling ( child , \"propstat\" ) ; //$NON-NLS-1$ ensureNull ( Policy . bind ( \"ensure.conflictingStatusOrPropstatElmt\" ) , child ) ; //$NON-NLS-1$ return isPropStat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets this response s response description to the given value . If the value is <code > null< / code > and a response description has already been set it is removed . [CODESPLIT] public void setResponseDescription ( Element value ) { Element child = getLastChild ( root , \"responsedescription\" ) ; //$NON-NLS-1$ if ( child != null ) root . removeChild ( child ) ; if ( value == null ) { child = setChild ( root , \"responsedescription\" , childNames , false ) ; //$NON-NLS-1$ child . appendChild ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the status on this response to the given status . The status must not be <code > null< / code > . This response must not already be in the propstat form . [CODESPLIT] public void setStatus ( String status ) { Assert . isNotNull ( status ) ; Assert . isTrue ( getLastChild ( root , \"propstat\" ) == null ) ; //$NON-NLS-1$ setChild ( root , \"status\" , status , fgNamesStatus , true ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends a new member to the end of this object with the specified name and the JSON representation of the specified string . <p > This method <strong > does not prevent duplicate names< / strong > . Calling this method with a name that already exists in the object will append another member with the same name . In order to replace existing members use the method <code > set ( name value ) < / code > instead . However <strong > <em > add< / em > is much faster than <em > set< / em > < / strong > ( because it does not need to search for existing members ) . Therefore <em > add< / em > should be preferred when constructing new objects . < / p > [CODESPLIT] public JsonObject add ( String name , String value ) { add ( name , valueOf ( value ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the member with the specified name to the JSON representation of the specified string . If this object does not contain a member with this name a new member is added at the end of the object . If this object contains multiple members with this name only the last one is changed . <p > This method should <strong > only be used to modify existing objects< / strong > . To fill a new object with members the method <code > add ( name value ) < / code > should be preferred which is much faster ( as it does not need to search for existing members ) . < / p > [CODESPLIT] public JsonObject set ( String name , String value ) { set ( name , valueOf ( value ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Basic authorization credentials for the given username and password . The credentials have the following form : <code > credentials = Basic basic - credentials basic - credentials = base64 - user - pass base64 - user - pass = &lt ; base64 encoding of user - pass except not limited to 76 char / line&gt ; user - pass = userid : password userid = * &lt ; TEXT excluding : &gt ; password = * TEXT < / code > <P > Userids might be case sensitive . <P > For example if the user s name is Aladdin and the user s password is open sesame the following credentials are supplied : <code > Basic QWxhZGRpbjpvcGVuIHN1c2FtZQ == < / code > [CODESPLIT] private String credentials ( String username , String password ) { Assert . isNotNull ( username ) ; Assert . isNotNull ( password ) ; String userpass = username + \":\" + password ; //$NON-NLS-1$ byte [ ] data = null ; try { data = userpass . getBytes ( \"UTF8\" ) ; //$NON-NLS-1$ } catch ( UnsupportedEncodingException e ) { data = userpass . getBytes ( ) ; } return \"Basic \" + Base64Encoder . encode ( data ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Report a property change to registered listeners ( for example edit parts ) . [CODESPLIT] protected void firePropertyChange ( String property , Object oldValue , Object newValue ) { if ( pcsDelegate . hasListeners ( property ) ) { pcsDelegate . firePropertyChange ( property , oldValue , newValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the current stack frame context or a valid stack frame for the given value . [CODESPLIT] public static IJavaStackFrame getStackFrame ( IValue value ) throws CoreException { IStatusHandler handler = getStackFrameProvider ( ) ; if ( handler != null ) { IJavaStackFrame stackFrame = ( IJavaStackFrame ) handler . handleStatus ( fgNeedStackFrame , value ) ; if ( stackFrame != null ) { return stackFrame ; } } IDebugTarget target = value . getDebugTarget ( ) ; IJavaDebugTarget javaTarget = ( IJavaDebugTarget ) target . getAdapter ( IJavaDebugTarget . class ) ; if ( javaTarget != null ) { IThread [ ] threads = javaTarget . getThreads ( ) ; for ( int i = 0 ; i < threads . length ; i ++ ) { IThread thread = threads [ i ] ; if ( thread . isSuspended ( ) ) { return ( IJavaStackFrame ) thread . getTopStackFrame ( ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the first class is the same or a subtype of the second class . [CODESPLIT] private boolean isSubtypeOf ( String class1 , String class2 ) { if ( class1 == null || class2 == null ) { return false ; } class1 = convertToNonPrimitiveClass ( class1 ) ; class2 = convertToNonPrimitiveClass ( class2 ) ; // TODO add code to take primitive types into account ClassTypeResolver resolver = new ClassTypeResolver ( getUniqueImports ( ) , ProjectClassLoader . getProjectClassLoader ( getEditor ( ) ) ) ; try { Class < ? > clazz1 = resolver . resolveType ( class1 ) ; Class < ? > clazz2 = resolver . resolveType ( class2 ) ; if ( clazz1 == null || clazz2 == null ) { return false ; } return clazz2 . isAssignableFrom ( clazz1 ) ; } catch ( ClassNotFoundException exc ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Completions for object instance members [CODESPLIT] private Collection < ICompletionProposal > getMvelInstanceCompletionsFromJDT ( final int documentOffset , final String prefix , Map < String , String > params , Class < ? > lastType , boolean settersOnly ) { if ( lastType == null ) { lastType = Object . class ; } //FIXME: there is a small chance of var name collision using this arbitrary mvdrlofc as a variable name. //ideally the variable name should be inferred from the last member of the expression final String syntheticVarName = \"mvdrlofc\" ; String javaText = \"\\n\" + lastType . getPackage ( ) . getName ( ) + \".\" + CompletionUtil . getSimpleClassName ( lastType ) + \" \" + syntheticVarName + \";\\n\" + syntheticVarName + \".\" ; final List < ICompletionProposal > list1 = new ArrayList < ICompletionProposal > ( ) ; requestJavaCompletionProposals ( javaText , prefix , documentOffset , params , list1 ) ; final List < ICompletionProposal > list = list1 ; Collection < ICompletionProposal > mvelList = RuleCompletionProcessor . mvelifyProposals ( list , settersOnly ) ; return mvelList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Completions for static Class members [CODESPLIT] private Collection < ICompletionProposal > getMvelClassCompletionsFromJDT ( final int documentOffset , final String prefix , Map < String , String > params , Class < ? > lastType ) { if ( lastType == null ) { lastType = Object . class ; } //FIXME: there is a small chance of var name collision using this arbitrary mvdrlofc as a variable name. //ideally the variable name should be inferred from the last member of the expression String javaText = \"\\n\" + CompletionUtil . getSimpleClassName ( lastType ) + \".\" ; final List < ICompletionProposal > list1 = new ArrayList < ICompletionProposal > ( ) ; requestJavaCompletionProposals ( javaText , prefix , documentOffset , params , list1 ) ; final List < ICompletionProposal > list = list1 ; Collection < ICompletionProposal > mvelList = RuleCompletionProcessor . mvelifyProposals ( list , false ) ; return mvelList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to compare proposals of different types based on the tokenized display string [CODESPLIT] public static boolean containsProposal ( final Collection < ICompletionProposal > proposals , String newProposal ) { for ( ICompletionProposal prop : proposals ) { String displayString = prop . getDisplayString ( ) ; String [ ] existings = displayString . split ( \" \" ) ; if ( existings . length == 0 ) { continue ; } String [ ] newProposals = newProposal . split ( \" \" ) ; if ( newProposals . length == 0 ) { continue ; } if ( existings [ 0 ] . equals ( newProposals [ 0 ] ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Filters accessor method proposals to replace them with their mvel expression equivalent For instance a completion for getStatus () would be replaced by a completion for status when asking for stters only then only setters or writable fields will be returned [CODESPLIT] public static Collection < ICompletionProposal > mvelifyProposals ( List < ICompletionProposal > list , boolean settersOnly ) { final Collection < ICompletionProposal > set = new HashSet < ICompletionProposal > ( ) ; for ( ICompletionProposal o : list ) { if ( o instanceof JavaMethodCompletionProposal ) { //methods processJavaMethodCompletionProposal ( list , settersOnly , set , o ) ; } else if ( o instanceof JavaCompletionProposal ) { //fields processesJavaCompletionProposal ( settersOnly , set , o ) ; } else if ( ! settersOnly ) { set . add ( o ) ; } } return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a WebDAV element with the given name and appends it as a child of the given parent . Returns the child element . The parent must not be <code > null< / code > and must be a WebDAV element . The name of the child must not be <code > null< / code > . [CODESPLIT] public static Element appendChild ( Element parent , String name ) { Assert . isTrue ( isDAVElement ( parent ) ) ; Assert . isNotNull ( name ) ; String nsPrefix = getNSPrefix ( parent ) ; String tagName = nsPrefix == null ? name : nsPrefix + \":\" + name ; //$NON-NLS-1$ Element child = parent . getOwnerDocument ( ) . createElement ( tagName ) ; parent . appendChild ( child ) ; return child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a WebDAV element with the given name and appends it as a child of the given parent . In addition a text node created from the given data is created and appended to the child . Returns the child element . The parent must not be <code > null< / code > and must be a WebDAV element . The name of the child must not be <code > null< / code > . The data must not be <code > null< / code > . [CODESPLIT] public static Element appendChild ( Element parent , String name , String data ) { Assert . isTrue ( isDAVElement ( parent ) ) ; Assert . isNotNull ( name ) ; Assert . isNotNull ( data ) ; Element child = appendChild ( parent , name ) ; child . appendChild ( child . getOwnerDocument ( ) . createTextNode ( data ) ) ; return child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a clone of the given node . The given document becomes the owner document of the clone . [CODESPLIT] public static Node cloneNode ( Document document , Node node ) { Node nodeClone = null ; switch ( node . getNodeType ( ) ) { case Node . ELEMENT_NODE : { nodeClone = document . createElement ( ( ( Element ) node ) . getTagName ( ) ) ; NamedNodeMap namedNodeMap = node . getAttributes ( ) ; for ( int i = 0 ; i < namedNodeMap . getLength ( ) ; ++ i ) { Attr attr = ( Attr ) namedNodeMap . item ( i ) ; Attr attrClone = document . createAttribute ( attr . getName ( ) ) ; attrClone . setValue ( attr . getValue ( ) ) ; ( ( Element ) nodeClone ) . setAttributeNode ( attrClone ) ; } } break ; case Node . TEXT_NODE : nodeClone = document . createTextNode ( ( ( CharacterData ) node ) . getData ( ) ) ; break ; case Node . CDATA_SECTION_NODE : nodeClone = document . createCDATASection ( ( ( CharacterData ) node ) . getData ( ) ) ; break ; case Node . ENTITY_REFERENCE_NODE : nodeClone = document . createEntityReference ( node . getNodeName ( ) ) ; break ; case Node . PROCESSING_INSTRUCTION_NODE : nodeClone = document . createProcessingInstruction ( ( ( ProcessingInstruction ) node ) . getTarget ( ) , ( ( ProcessingInstruction ) node ) . getData ( ) ) ; break ; case Node . COMMENT_NODE : nodeClone = document . createComment ( ( ( CharacterData ) node ) . getData ( ) ) ; break ; case Node . DOCUMENT_FRAGMENT_NODE : nodeClone = document . createDocumentFragment ( ) ; break ; case Node . DOCUMENT_NODE : case Node . DOCUMENT_TYPE_NODE : case Node . NOTATION_NODE : case Node . ATTRIBUTE_NODE : case Node . ENTITY_NODE : Assert . isTrue ( false , Policy . bind ( \"assert.notSupported\" ) ) ; //$NON-NLS-1$ break ; default : Assert . isTrue ( false , Policy . bind ( \"assert.unknownNodeType\" ) ) ; //$NON-NLS-1$ } return nodeClone ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a WebDAV element with the given name and adds it as the root of the given document . In addition the WebDAV namespace is declared on the new element . Returns the new element . The document must not be <code > null< / code > and must not already have a root element . The name of the element to be created must not be <code > null< / code > . [CODESPLIT] public static Element create ( Document document , String name ) { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getDocumentElement ( ) == null ) ; Assert . isNotNull ( name ) ; Element element = document . createElement ( name ) ; declareNS ( element , null , DAV_NS ) ; document . appendChild ( element ) ; return element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a namespace declaration to the given element . If only the prefix is <code > null< / code > a default namespace is declared . If the prefix and the namespaceUrl are <code > null< / code > the default namespace is removed . The element must not be <code > null< / code > . If the namespaceUrl is <code > null< / code > the <code > prefix< / code > must also be <code > null< / code > . [CODESPLIT] public static void declareNS ( Element element , String prefix , String namespaceUrl ) { Assert . isNotNull ( element ) ; Assert . isTrue ( namespaceUrl != null || prefix == null && namespaceUrl == null ) ; String name = XML_PREFIX + ( prefix == null ? \"\" : \":\" + prefix ) ; //$NON-NLS-1$ //$NON-NLS-2$ String value = namespaceUrl == null ? \"\" : namespaceUrl ; //$NON-NLS-1$ element . setAttribute ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the given node is a WebDAV element with the given name returning it as an <code > Element< / code > if it is . [CODESPLIT] protected static Element ensureDAVElement ( String message , Node node , String name ) throws MalformedElementException { Assert . isNotNull ( name ) ; if ( node == null || node . getNodeType ( ) != Node . ELEMENT_NODE ) throw new MalformedElementException ( message ) ; Element element = ( Element ) node ; if ( ! name . equals ( getNSLocalName ( element ) ) || ! DAV_NS . equals ( getNSName ( element ) ) ) throw new MalformedElementException ( message ) ; return element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the given object is not <code > null< / code > . [CODESPLIT] protected static void ensureNotNull ( String message , Object object ) throws MalformedElementException { if ( object == null ) throw new MalformedElementException ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the given object is <code > null< / code > . [CODESPLIT] protected static void ensureNull ( String message , Object object ) throws MalformedElementException { if ( object != null ) throw new MalformedElementException ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the given node is a text node returning it as a <code > Text< / code > node if it is . [CODESPLIT] protected static Text ensureText ( String message , Node node ) throws MalformedElementException { if ( node == null || node . getNodeType ( ) != Node . TEXT_NODE ) throw new MalformedElementException ( message ) ; return ( Text ) node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clones the given element and its subtrees and sets it as the root of the given document . Returns the cloned element . The document must not have a root and must not be <code > null< / code > . The element must not be <code > null< / code > . [CODESPLIT] public static Element extractElement ( Document document , Element element ) throws MalformedElementException { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getDocumentElement ( ) == null ) ; Assert . isNotNull ( element ) ; return ( Element ) extractNode ( document , element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clones the given node and its subtrees and sets it as the root of the given parent node . Returns the cloned node . The parent node and the node to be cloned must not be <code > null< / code > . [CODESPLIT] public static Node extractNode ( Node parent , Node node ) throws MalformedElementException { // Get a handle to the root of the parent node tree. Document document ; if ( parent . getNodeType ( ) == Node . DOCUMENT_NODE ) document = ( Document ) parent ; else document = parent . getOwnerDocument ( ) ; // Create a clone of the node owned by the document, and add to the parent. Node nodeClone = cloneNode ( document , node ) ; parent . appendChild ( nodeClone ) ; // If the node is an Element if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { // Figure out its namespace information. String nsPrefix = getNSPrefix ( ( Element ) node ) ; String nsName = getNSName ( ( Element ) node ) ; // Is this namespace already defined on the clone?  If not declare it. String nsNameClone = resolve ( nsPrefix , ( Element ) nodeClone ) ; if ( nsName != nsNameClone && ( nsName == null || ! nsName . equals ( nsNameClone ) ) ) declareNS ( ( Element ) nodeClone , nsPrefix , nsName ) ; // Do the same namespace fix-up for each of the node's attributes. NamedNodeMap nodeMap = nodeClone . getAttributes ( ) ; for ( int i = 0 ; i < nodeMap . getLength ( ) ; ++ i ) { Attr attr = ( Attr ) nodeMap . item ( i ) ; nsPrefix = getNSPrefix ( attr . getName ( ) ) ; if ( nsPrefix != null && ! nsPrefix . equals ( XML_PREFIX ) ) { nsName = resolve ( nsPrefix , ( Element ) node ) ; nsNameClone = resolve ( nsPrefix , ( Element ) nodeClone ) ; if ( nsName != nsNameClone && ( nsName == null || ! nsName . equals ( nsNameClone ) ) ) declareNS ( ( Element ) nodeClone , nsPrefix , nsName ) ; } } } // Recursively clone each of the node's children. Node child = node . getFirstChild ( ) ; while ( child != null ) { extractNode ( nodeClone , child ) ; child = child . getNextSibling ( ) ; } // Finished cloning this node. return nodeClone ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first child of the given parent that is a WebDAV element with one of the given names or <code > null< / code > if no such child exists . <p > If firstToLast is true the search for the child starts at the parent s first child otherwise the search starts at the parent s last child . The parent must not be <code > null< / code > and must be a WebDAV element . The names of children to search for must not be <code > null< / code > . < / p > [CODESPLIT] private static Element getChild ( Element parent , String [ ] names , boolean firstToLast ) { Assert . isTrue ( isDAVElement ( parent ) ) ; Assert . isNotNull ( names ) ; // Get the first candidate. Node child = null ; if ( firstToLast ) child = parent . getFirstChild ( ) ; else child = parent . getLastChild ( ) ; // While there are children left to consider. while ( child != null ) { // See if the child name matches any being sought. for ( int i = 0 ; i < names . length ; ++ i ) if ( isDAVElement ( child , names [ i ] ) ) return ( Element ) child ; // Try the next child. if ( firstToLast ) child = child . getNextSibling ( ) ; else child = child . getPreviousSibling ( ) ; } // A matching child was not found. return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the child WebDAV element of the given parent that is nearest in position to a WebDAV element with the given name or <code > null< / code > if no such child exists . <p > Children are expected to be in the order specified by the given names . If firstToLast is true the search for the child starts at the parent s first child otherwise the search starts at the parent s last child . <p > The parent must not be <code > null< / code > and must be a WebDAV element . The name of the child to search for must not be <code > null< / code > . The parent s valid child names must not be <code > null< / code > and must contain the name of the child being searched for . <p > The returned child is as follows : <ul > <li > Searching first to last< / li > <ul > <li > returns <code > null< / code > if an element with the given name should appear as the last child< / li > <li > returns the first occurring child if an element with the given name is a child< / li > <li > returns a child if an element with the given name would appear before it< / li > < / ul > <li > Searching last to first< / li > <ul > <li > returns <code > null< / code > if an element with the given name would appear as the first child< / li > <li > returns the last occurring child if an element with the given name is a child< / li > <li > returns a child if an element with the given name would appear after it< / li > < / ul > < / ul > [CODESPLIT] public static Element getChild ( Element parent , String name , String [ ] names , boolean firstToLast ) { Assert . isNotNull ( parent ) ; Assert . isNotNull ( name ) ; Assert . isNotNull ( names ) ; boolean found = false ; for ( int i = 0 ; ! found && i < names . length ; ++ i ) { found = names [ i ] . equals ( name ) ; } Assert . isTrue ( found ) ; int i ; Node child = null ; if ( firstToLast ) { i = 0 ; child = parent . getFirstChild ( ) ; } else { i = names . length - 1 ; child = parent . getLastChild ( ) ; } while ( child != null && ! names [ i ] . equals ( name ) ) { int mark = i ; while ( ! isDAVElement ( child , names [ i ] ) && ! names [ i ] . equals ( name ) ) { if ( firstToLast ) { ++ i ; } else { -- i ; } } if ( ! names [ i ] . equals ( name ) ) { if ( firstToLast ) { child = child . getNextSibling ( ) ; } else { child = child . getPreviousSibling ( ) ; } } else if ( ! isDAVElement ( child , names [ i ] ) ) { int pos = i ; found = false ; while ( ! found && ( pos >= 0 && pos < names . length ) ) { found = isDAVElement ( child , names [ pos ] ) ; if ( firstToLast ) { ++ pos ; } else { -- pos ; } } if ( ! found ) { i = mark ; if ( firstToLast ) { child = child . getNextSibling ( ) ; } else { child = child . getPreviousSibling ( ) ; } } } } return ( Element ) child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first child element of the given parent element or <code > null< / code > if no such child exists . If firstToLast is true the search for the child starts at the parent s first child otherwise the search starts at the parent s last child . The parent must not be <code > null< / code > . [CODESPLIT] public static Element getChildElement ( Element parent , boolean firstToLast ) { Assert . isNotNull ( parent ) ; Node child = null ; if ( firstToLast ) child = parent . getFirstChild ( ) ; else child = parent . getLastChild ( ) ; while ( child != null && ! isElement ( child ) ) { if ( firstToLast ) child = child . getNextSibling ( ) ; else child = child . getPreviousSibling ( ) ; } return ( Element ) child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the data of the first child text node of the first WebDAV child with the given name of the given parent or the empty <code > String< / code > if no such child text node exists or <code > null< / code > if no such child exists . If firstToLast is true the search for the child starts at the parent s first child otherwise the search starts at the parent s last child . The parent must not be <code > null< / code > and must be a WebDAV element . The name of the child must not be <code > null< / code > . [CODESPLIT] public static String getChildText ( Element parent , String name , boolean firstToLast ) { Assert . isTrue ( isDAVElement ( parent ) ) ; Assert . isNotNull ( name ) ; Element child ; if ( firstToLast ) child = getFirstChild ( parent , name ) ; else child = getLastChild ( parent , name ) ; if ( child != null ) return getText ( child , firstToLast ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first WebDAV child of the given parent or <code > null< / code > if no such child exists . The parent must not be <code > null< / code > and must be a WebDAV element . [CODESPLIT] public static Element getDAVChild ( Element parent ) { Assert . isTrue ( isDAVElement ( parent ) ) ; Node child = parent . getFirstChild ( ) ; while ( child != null && ! isDAVElement ( child ) ) child = child . getNextSibling ( ) ; return ( Element ) child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first child of the given parent that is a WebDAV element with one of the given names or <code > null< / code > if no such child exists . <p > The search for the child starts at the parent s first child . The parent must not be <code > null< / code > and must be a WebDAV element . The names of children to search for must not be <code > null< / code > . < / p > [CODESPLIT] public static Element getFirstChild ( Element parent , String [ ] names ) { return getChild ( parent , names , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first child of the given parent that is a WebDAV element with the given name or <code > null< / code > if no such child exists . <p > The search for the child starts at the parent s first child . The parent must not be <code > null< / code > and must be a DAV : namespace element . The name of the child to search for must not be <code > null< / code > . [CODESPLIT] public static Element getFirstChild ( Element parent , String name ) { Assert . isNotNull ( name ) ; return getChild ( parent , new String [ ] { name } , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the data of the given parent s first text node or the empty <code > String< / code > if no such text node exists . The search for the text node starts at the parent s first child . The parent must not be <code > null< / code > . [CODESPLIT] public static String getFirstText ( Element parent ) { Assert . isNotNull ( parent ) ; Node child = parent . getFirstChild ( ) ; while ( child != null && ! isText ( child ) ) child = child . getNextSibling ( ) ; if ( child == null ) return \"\" ; //$NON-NLS-1$ return ( ( Text ) child ) . getData ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last child of the given parent that is a WebDAV element with the given name or <code > null< / code > if no such child exists . <p > The search starts at the parent s last child . The parent must not be <code > null< / code > and must be a DAV : namespace element . The name of the child to search for must not be <code > null< / code > . [CODESPLIT] public static Element getLastChild ( Element parent , String name ) { Assert . isNotNull ( name ) ; return getChild ( parent , new String [ ] { name } , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the given element s namespace declarations . The element must not be <code > null< / code > . [CODESPLIT] public static Namespaces getNamespaces ( Element element ) { Assert . isNotNull ( element ) ; Node parent = element . getParentNode ( ) ; while ( parent != null && ! isElement ( parent ) ) parent = parent . getParentNode ( ) ; Namespaces namespaces = null ; if ( parent != null ) namespaces = getNamespaces ( ( Element ) parent ) ; return getNamespaces ( element , namespaces , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the given element s namespace declarations . The given namespace declarations should be the element s parent s or <code > null< / code > if the element has no parent . If removeDuplicateNSDeclarations is <code > true< / code > duplicate namespace declarations are removed from the element s attributes . The element must not be <code > null< / code > . [CODESPLIT] protected static Namespaces getNamespaces ( Element element , Namespaces namespaces , boolean removeDuplicateNSDeclarations ) { // Create a container to hold the new namespace definitions. Namespaces newNamespaces = null ; if ( namespaces == null ) newNamespaces = new Namespaces ( ) ; else newNamespaces = new Namespaces ( namespaces ) ; Vector oldAttributes = new Vector ( ) ; // For each attribute on the given element. NamedNodeMap nodeMap = element . getAttributes ( ) ; for ( int i = 0 ; i < nodeMap . getLength ( ) ; ++ i ) { Attr attr = ( Attr ) nodeMap . item ( i ) ; // Is it a name space declaration? String name = attr . getName ( ) ; if ( name . startsWith ( XML_PREFIX ) ) { String nsName = attr . getValue ( ) ; // Is it setting or clearing the default namespace? // (i.e. has no prefix part) if ( name . length ( ) == XML_PREFIX . length ( ) ) { if ( nsName . equals ( \"\" ) ) //$NON-NLS-1$ newNamespaces . setDefaultNSName ( null ) ; else newNamespaces . setDefaultNSName ( nsName ) ; } else if ( name . charAt ( XML_PREFIX . length ( ) ) == ' ' ) { // It is a namespace declaration. String nsPrefix = name . substring ( XML_PREFIX . length ( ) + 1 ) ; if ( nsPrefix . length ( ) > 0 && nsName . length ( ) > 0 ) { // Ensure it is in the new namespaces list. newNamespaces . putNSName ( nsPrefix , nsName ) ; boolean prefixExists = newNamespaces . getNSPrefix ( nsName ) != null ; if ( ! prefixExists ) newNamespaces . putNSPrefix ( nsName , nsPrefix ) ; // If it is due for removal, rememebr it in the oldAttributes list. if ( removeDuplicateNSDeclarations && ( prefixExists || nsName . equals ( newNamespaces . getDefaultNSName ( ) ) ) ) oldAttributes . addElement ( attr ) ; } } } } // Remove all the duplicates on the given element. Enumeration e = oldAttributes . elements ( ) ; while ( e . hasMoreElements ( ) ) element . removeAttributeNode ( ( Attr ) e . nextElement ( ) ) ; // Answer the new list of namespaces for this element. return newNamespaces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next sibling element of the given element or <code > null< / code > if no such sibling exists . Only the sibling s next children are searched . The element must not be <code > null< / code > . [CODESPLIT] public static Element getNextSibling ( Element element ) { Assert . isNotNull ( element ) ; Node sibling = element ; do { sibling = sibling . getNextSibling ( ) ; } while ( sibling != null && ! isElement ( sibling ) ) ; return ( Element ) sibling ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first WebDAV sibling of the given element that has one of the given names or <code > null< / code > if no such sibling exists . Only the sibling s next children ( not the previous children ) are searched . The element must not be <code > null< / code > and must be a WebDAV element . The possible names of the sibling to search for must not be <code > null< / code > . [CODESPLIT] public static Element getNextSibling ( Element element , String [ ] names ) { Assert . isTrue ( isDAVElement ( element ) ) ; Assert . isNotNull ( names ) ; Node sibling = element . getNextSibling ( ) ; while ( sibling != null ) { for ( int i = 0 ; i < names . length ; ++ i ) if ( isDAVElement ( sibling , names [ i ] ) ) return ( Element ) sibling ; sibling = sibling . getNextSibling ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next WebDAV sibling of the given element that has the given name or <code > null< / code > if no such sibling exists . Only the sibling s next children are searched . The element must not be <code > null< / code > and must be a WebDAV element . The name of the sibling to search for must not be <code > null< / code > . [CODESPLIT] public static Element getNextSibling ( Element element , String name ) { return getNextSibling ( element , new String [ ] { name } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the local part of the given name or <code > null< / code > if its name has no local part . The name must not be <code > null< / code > . <table > <caption > Example< / caption > <tr > <th > name< / th > <th > local name< / th > <tr > <td > D : foo< / td > <td > foo< / td > <tr > <td > foo< / td > <td > foo< / td > <tr > <td > D : < / td > <td > null< / td > <tr > <td > : foo< / td > <td > foo< / td > <tr > <td > : < / td > <td > null< / td > < / table > [CODESPLIT] public static String getNSLocalName ( String name ) { Assert . isNotNull ( name ) ; int p = name . lastIndexOf ( ' ' ) ; if ( p == - 1 ) return name ; if ( p == name . length ( ) - 1 ) return null ; return name . substring ( p + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the local part of the name of the given element or <code > null< / code > if its name has no local part . The element must not be <code > null< / code > . <table > <caption > Example< / caption > <tr > <th > tag name< / th > <th > local name< / th > <tr > <td > D : foo< / td > <td > foo< / td > <tr > <td > foo< / td > <td > foo< / td > <tr > <td > D : < / td > <td > null< / td > <tr > <td > : foo< / td > <td > foo< / td > <tr > <td > : < / td > <td > null< / td > < / table > [CODESPLIT] public static String getNSLocalName ( Element element ) { Assert . isNotNull ( element ) ; return getNSLocalName ( element . getTagName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the URL of the given element s namespace or <code > null< / code > if it has no namespace . The element must not be <code > null< / code > . [CODESPLIT] public static String getNSName ( Element element ) throws MalformedElementException { Assert . isNotNull ( element ) ; String nsPrefix = getNSPrefix ( element ) ; String nsName = resolve ( nsPrefix , element ) ; if ( nsPrefix != null && nsName == null ) throw new MalformedElementException ( Policy . bind ( \"exception.namespacePrefixNotResolved\" , nsPrefix ) ) ; //$NON-NLS-1$ return nsName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the namespace prefix part of the given name or <code > null< / code > if its name has no prefix . The name must not be <code > null< / code > . <table > <caption > Example< / caption > <tr > <th > name< / th > <th > namespace prefix< / th > <tr > <td > D : foo< / td > <td > D< / td > <tr > <td > foo< / td > <td > null< / td > <tr > <td > D : < / td > <td > D< / td > <tr > <td > : foo< / td > <td > null< / td > <tr > <td > : < / td > <td > null< / td > < / table > [CODESPLIT] public static String getNSPrefix ( String name ) { Assert . isNotNull ( name ) ; int p = name . lastIndexOf ( ' ' ) ; if ( p <= 0 ) return null ; return name . substring ( 0 , p ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the namespace prefix part of the name of the given element or <code > null< / code > if its name has no prefix . The element must not be <code > null< / code > . <table > <caption > Example< / caption > <tr > <th > tag name< / th > <th > namespace prefix< / th > <tr > <td > D : foo< / td > <td > D< / td > <tr > <td > foo< / td > <td > null< / td > <tr > <td > D : < / td > <td > D< / td > <tr > <td > : foo< / td > <td > null< / td > <tr > <td > : < / td > <td > null< / td > < / table > [CODESPLIT] public static String getNSPrefix ( Element element ) { Assert . isNotNull ( element ) ; return getNSPrefix ( element . getTagName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a qualified name that is formed from the given element s namespace name and namespace local name . The qualified name s qualifier is the element s namespace name and the qualified name s local name is the element s local name . The element must not be <code > null< / code > . [CODESPLIT] public static QualifiedName getQualifiedName ( Element element ) throws MalformedElementException { Assert . isNotNull ( element ) ; String nsName = getNSName ( element ) ; String nsLocalName = getNSLocalName ( element ) ; if ( nsLocalName == null ) throw new MalformedElementException ( Policy . bind ( \"exception.noLocalNameForElmt\" ) ) ; //$NON-NLS-1$ return new QualifiedNameImpl ( nsName , nsLocalName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first WebDAV sibling of the given element that has the given name or <code > null< / code > if no such sibling exists . If firstToLast is true only the sibling s next children are searched otherwise only the siblings previous children are searched . The element must not be <code > null< / code > and must be a WebDAV element . The name of the sibling to search for must not be <code > null< / code > . [CODESPLIT] public static Element getSibling ( Element element , String name , boolean firstToLast ) { Assert . isTrue ( isDAVElement ( element ) ) ; Assert . isNotNull ( name ) ; Node sibling = element ; do { if ( firstToLast ) sibling = sibling . getNextSibling ( ) ; else sibling = sibling . getPreviousSibling ( ) ; } while ( sibling != null && ! isDAVElement ( sibling , name ) ) ; return ( Element ) sibling ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the data of the given parent s first text node or the empty <code > String< / code > if no such text node exists . If firstToLast is true the search for the text node starts at the parent s first child otherwise the search starts at the parent s last child . The parent must not be <code > null< / code > . [CODESPLIT] public static String getText ( Element parent , boolean firstToLast ) { Assert . isNotNull ( parent ) ; Node child = null ; if ( firstToLast ) child = parent . getFirstChild ( ) ; else child = parent . getLastChild ( ) ; while ( child != null && ! isText ( child ) ) { if ( firstToLast ) child = child . getNextSibling ( ) ; else child = child . getPreviousSibling ( ) ; } if ( child != null ) return ( ( Text ) child ) . getData ( ) ; return \"\" ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first WebDAV sibling of the given element that has the same name as the element or <code > null< / code > if no such sibling exists . If firstToLast is true only the sibling s next children are searched otherwise only the siblings previous children are searched . The element must not be <code > null< / code > and must be a WebDAV element . [CODESPLIT] public static Element getTwin ( Element element , boolean firstToLast ) { Assert . isTrue ( isDAVElement ( element ) ) ; String name = getNSLocalName ( element ) ; return getSibling ( element , name , firstToLast ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a WebDAV element with the given name and inserts it before the given sibling . Returns the new sibling . The sibling must not be <code > null< / code > and must be a WebDAV element . The name of the new sibling must not be <code > null< / code > . [CODESPLIT] public static Element insertBefore ( Element sibling , String name ) { Assert . isTrue ( isDAVElement ( sibling ) ) ; Assert . isNotNull ( name ) ; String nsPrefix = getNSPrefix ( sibling ) ; String tagName = nsPrefix == null ? name : nsPrefix + \":\" + name ; //$NON-NLS-1$ Element newSibling = sibling . getOwnerDocument ( ) . createElement ( tagName ) ; sibling . getParentNode ( ) . insertBefore ( newSibling , sibling ) ; return newSibling ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a boolean indicating whether or not the given node is a WebDAV element . The node may be <code > null< / code > in which case <code > false< / code > is returned . [CODESPLIT] public static boolean isDAVElement ( Node node ) { if ( node == null || node . getNodeType ( ) != Node . ELEMENT_NODE ) return false ; try { if ( ! DAV_NS . equals ( getNSName ( ( Element ) node ) ) ) return false ; } catch ( MalformedElementException e ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a boolean indicating whether or not the given node is a WebDAV element with the given name . The node may be <code > null< / code > in which case <code > false< / code > is returned . The name must not be <code > null< / code > . [CODESPLIT] public static boolean isDAVElement ( Node node , String name ) { Assert . isNotNull ( name ) ; if ( node == null || node . getNodeType ( ) != Node . ELEMENT_NODE ) return false ; try { Element element = ( Element ) node ; if ( ! name . equals ( getNSLocalName ( element ) ) || ! DAV_NS . equals ( getNSName ( element ) ) ) { return false ; } } catch ( MalformedElementException e ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes redundant namespace declarations from the given node and all its children to maximum depth . The node must not be <code > null< / code > . [CODESPLIT] public static Node reduceNS ( Node node , Namespaces parentNamespaces ) throws MalformedElementException { Namespaces namespaces = parentNamespaces ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element element = ( Element ) node ; namespaces = getNamespaces ( element , parentNamespaces , false ) ; String nsPrefix = getNSPrefix ( element ) ; String nsLocalName = getNSLocalName ( element ) ; if ( nsPrefix != null ) { String nsName = namespaces . getNSName ( nsPrefix ) ; ensureNotNull ( Policy . bind ( \"ensure.missingNamespaceForPrefix\" , nsPrefix ) , nsName ) ; //$NON-NLS-1$ String tagName = null ; if ( nsName . equals ( namespaces . getDefaultNSName ( ) ) ) { tagName = nsLocalName ; } else { tagName = namespaces . getNSPrefix ( nsName ) + \":\" + nsLocalName ; //$NON-NLS-1$ } if ( ! tagName . equals ( element . getTagName ( ) ) ) { Document document = element . getOwnerDocument ( ) ; Element newElement = document . createElement ( tagName ) ; NamedNodeMap nodeMap = element . getAttributes ( ) ; for ( int i = 0 ; i < nodeMap . getLength ( ) ; ++ i ) { Attr attr = ( Attr ) nodeMap . item ( i ) ; newElement . setAttribute ( attr . getName ( ) , attr . getValue ( ) ) ; } Node child = element . getFirstChild ( ) ; while ( child != null ) { element . removeChild ( child ) ; newElement . appendChild ( child ) ; child = element . getFirstChild ( ) ; } element . getParentNode ( ) . replaceChild ( newElement , element ) ; element = newElement ; } } Vector oldAttributes = new Vector ( ) ; Vector newAttributes = new Vector ( ) ; NamedNodeMap nodeMap = element . getAttributes ( ) ; for ( int i = 0 ; i < nodeMap . getLength ( ) ; ++ i ) { Attr attr = ( Attr ) nodeMap . item ( i ) ; String name = attr . getName ( ) ; String value = attr . getValue ( ) ; String newName = name ; nsPrefix = getNSPrefix ( name ) ; nsLocalName = getNSLocalName ( name ) ; if ( nsPrefix != null && ! nsPrefix . equals ( XML_PREFIX ) ) { String nsName = namespaces . getNSName ( nsPrefix ) ; ensureNotNull ( Policy . bind ( \"ensure.missingNamespaceForPrefix\" , nsPrefix ) , nsName ) ; //$NON-NLS-1$ String newNSPrefix = namespaces . getNSPrefix ( nsName ) ; if ( ! newNSPrefix . equals ( nsPrefix ) ) { newName = newNSPrefix + \":\" + nsLocalName ; //$NON-NLS-1$ } } boolean newAttribute = true ; if ( parentNamespaces != null ) { if ( nsPrefix == null && XML_PREFIX . equals ( nsLocalName ) ) { if ( value . equals ( parentNamespaces . getDefaultNSName ( ) ) ) { newAttribute = false ; } } if ( nsPrefix != null && XML_PREFIX . equals ( nsPrefix ) ) { if ( parentNamespaces . getNSPrefix ( value ) != null ) { newAttribute = false ; } } } oldAttributes . addElement ( attr ) ; if ( newAttribute ) { newAttributes . addElement ( new String [ ] { newName , value } ) ; } } Enumeration oldAttrs = oldAttributes . elements ( ) ; while ( oldAttrs . hasMoreElements ( ) ) { element . removeAttributeNode ( ( Attr ) oldAttrs . nextElement ( ) ) ; } Enumeration newAttrs = newAttributes . elements ( ) ; while ( newAttrs . hasMoreElements ( ) ) { String [ ] newAttr = ( String [ ] ) newAttrs . nextElement ( ) ; element . setAttribute ( newAttr [ 0 ] , newAttr [ 1 ] ) ; } node = element ; } Node child = node . getFirstChild ( ) ; while ( child != null ) { child = reduceNS ( child , namespaces ) ; child = child . getNextSibling ( ) ; } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the given namespace prefix in the namespace of the given element . If the given prefix is <code > null< / code > the default namespace is resolved . Returns the URL of the namespace or <code > null< / code > if the prefix could not be resolved . [CODESPLIT] public static String resolve ( String prefix , Element element ) { Assert . isNotNull ( element ) ; /* The prefix xml is by definition bound to the namespace name\n         * <code>XML_NS_NAME</code>.\n         */ if ( XML_NS_PREFIX . equals ( prefix ) ) { return XML_NS_NAME ; } /* Search from given element up parent chain to root (document)\n         * looking for a XML namespace declaration (represented as\n         * an element attribute with a name beginning in\n         * XML_PREFIX (\"xmlns\")).\n         */ Node current = element ; do { NamedNodeMap attrs = current . getAttributes ( ) ; int n = attrs . getLength ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Attr attr = ( Attr ) attrs . item ( i ) ; String name = attr . getName ( ) ; if ( name . startsWith ( XML_PREFIX ) ) { if ( name . length ( ) == XML_PREFIX . length ( ) ) { // no prefix e.g., xmlns=\"foo:\" if ( prefix == null ) { String nsName = attr . getValue ( ) ; if ( nsName . equals ( \"\" ) ) { //$NON-NLS-1$ return null ; } return nsName ; } } else { if ( prefix != null && name . equals ( XML_PREFIX + \":\" + prefix ) ) { //$NON-NLS-1$ return attr . getValue ( ) ; } } } } do { current = current . getParentNode ( ) ; } while ( current != null && current . getNodeType ( ) != Node . ELEMENT_NODE ) ; } while ( current != null ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Creates a WebDAV element with the given name and sets it as a child of the given parent . Returns the child element . <p > Children are positioned in the order specified by the given names . If a child with the same name as the child already exist the child is replaced . If firstToLast is true the search for the child s position starts at the parent s first child otherwise the search starts at the parent s last child . <p > The parent must not be <code > null< / code > and must be a WebDAV element . The child s name must not be <code > null< / code > . The parent s valid child names must not be <code > null< / code > and must contain the name of the child . [CODESPLIT] public static Element setChild ( Element parent , String name , String [ ] names , boolean firstToLast ) { Assert . isTrue ( isDAVElement ( parent ) ) ; Assert . isNotNull ( name ) ; Assert . isNotNull ( names ) ; String nsPrefix = getNSPrefix ( parent ) ; String tagName = nsPrefix == null ? name : nsPrefix + \":\" + name ; //$NON-NLS-1$ Element child = parent . getOwnerDocument ( ) . createElement ( tagName ) ; setChild ( parent , child , names , firstToLast ) ; return child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the given child element as a child of the given parent . <p > Children are positioned in the order specified by the given names . If a child with the same name already exists it is replaced . If firstToLast is true the search for the child s position starts at the parent s first child otherwise the search starts at the parent s last child . <p > The parent must not be <code > null< / code > and must be a WebDAV element . The child must not be null and its namespace prefix must resolve to the WebDAV namespace URL in the parent . The parent s valid child names must not be <code > null< / code > and must contain the name of the child . [CODESPLIT] public static void setChild ( Element parent , Element child , String [ ] names , boolean firstToLast ) { Assert . isTrue ( isDAVElement ( parent ) ) ; Assert . isNotNull ( child ) ; Assert . isTrue ( DAV_NS . equals ( resolve ( getNSPrefix ( child ) , parent ) ) ) ; Assert . isNotNull ( names ) ; boolean found = false ; String name = getNSLocalName ( child ) ; for ( int i = 0 ; ! found && i < names . length ; ++ i ) { found = names [ i ] . equals ( name ) ; } Assert . isTrue ( found ) ; Node sibling = getChild ( parent , name , names , firstToLast ) ; if ( isDAVElement ( sibling , name ) ) { parent . replaceChild ( child , sibling ) ; } else if ( firstToLast ) { if ( sibling == null ) { parent . appendChild ( child ) ; } else { parent . insertBefore ( child , sibling ) ; } } else { Node refChild = null ; if ( sibling == null ) { refChild = parent . getFirstChild ( ) ; } else { refChild = sibling . getNextSibling ( ) ; } if ( refChild == null ) { parent . appendChild ( child ) ; } else { parent . insertBefore ( child , refChild ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the stream to its beginning so it can be read again . [CODESPLIT] public void reset ( ) throws IOException { if ( file == null ) { ( ( ByteArrayInputStream ) is ) . reset ( ) ; } else { if ( fos != null ) { while ( skip ( 4096 ) > 0 ) ; fos . close ( ) ; fos = null ; if ( length == - 1 ) { length = totalBytesRead ; } } is . close ( ) ; is = new FileInputStream ( file ) ; } totalBytesRead = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For user triggered content assistance [CODESPLIT] protected void createActions ( ) { super . createActions ( ) ; IAction a = new TextOperationAction ( RuleEditorMessages . getResourceBundle ( ) , \"ContentAssistProposal.\" , this , ISourceViewer . CONTENTASSIST_PROPOSALS ) ; a . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_PROPOSALS ) ; setAction ( \"ContentAssistProposal\" , a ) ; a = new TextOperationAction ( RuleEditorMessages . getResourceBundle ( ) , \"ContentAssistTip.\" , this , ISourceViewer . CONTENTASSIST_CONTEXT_INFORMATION ) ; //$NON-NLS-1$ a . setActionDefinitionId ( ITextEditorActionDefinitionIds . CONTENT_ASSIST_CONTEXT_INFORMATION ) ; setAction ( \"ContentAssistTip\" , a ) ; a = new ToggleBreakpointAction ( getSite ( ) . getPart ( ) , null , getVerticalRuler ( ) ) ; setAction ( ITextEditorActionConstants . RULER_DOUBLE_CLICK , a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an incoming or outgoing connection to this vertex . [CODESPLIT] public void addConnection ( Connection conn ) { if ( conn == null || conn . getSource ( ) == conn . getTarget ( ) ) { throw new IllegalArgumentException ( ) ; } if ( conn . getSource ( ) == this ) { sourceConnections . add ( conn ) ; firePropertyChange ( SOURCE_CONNECTIONS_PROP , null , conn ) ; } else if ( conn . getTarget ( ) == this ) { targetConnections . add ( conn ) ; firePropertyChange ( TARGET_CONNECTIONS_PROP , null , conn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the property value for the given propertyId or null . [CODESPLIT] public Object getPropertyValue ( Object propertyId ) { if ( XPOS_PROP . equals ( propertyId ) ) { return Integer . toString ( location . x ) ; } if ( YPOS_PROP . equals ( propertyId ) ) { return Integer . toString ( location . y ) ; } if ( HEIGHT_PROP . equals ( propertyId ) ) { return Integer . toString ( size . height ) ; } if ( WIDTH_PROP . equals ( propertyId ) ) { return Integer . toString ( size . width ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an incoming or outgoing connection from this vertex . [CODESPLIT] public void removeConnection ( Connection conn ) { if ( conn == null ) { throw new IllegalArgumentException ( ) ; } if ( conn . getSource ( ) == this ) { sourceConnections . remove ( conn ) ; firePropertyChange ( SOURCE_CONNECTIONS_PROP , null , conn ) ; } else if ( conn . getTarget ( ) == this ) { targetConnections . remove ( conn ) ; firePropertyChange ( TARGET_CONNECTIONS_PROP , null , conn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Location of this vertex . [CODESPLIT] public void setLocation ( Point newLocation ) { if ( newLocation == null ) { throw new IllegalArgumentException ( ) ; } location . setLocation ( newLocation ) ; firePropertyChange ( LOCATION_PROP , null , location ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the property value for the given property id . [CODESPLIT] public void setPropertyValue ( Object propertyId , Object value ) { if ( XPOS_PROP . equals ( propertyId ) ) { int x = Integer . parseInt ( ( String ) value ) ; setLocation ( new Point ( x , location . y ) ) ; } else if ( YPOS_PROP . equals ( propertyId ) ) { int y = Integer . parseInt ( ( String ) value ) ; setLocation ( new Point ( location . x , y ) ) ; } else if ( HEIGHT_PROP . equals ( propertyId ) ) { int height = Integer . parseInt ( ( String ) value ) ; setSize ( new Dimension ( size . width , height ) ) ; } else if ( WIDTH_PROP . equals ( propertyId ) ) { int width = Integer . parseInt ( ( String ) value ) ; setSize ( new Dimension ( width , size . height ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the Size of this vertex . Will not update the size if newSize is null . [CODESPLIT] public void setSize ( Dimension newSize ) { if ( newSize != null ) { size . setSize ( newSize ) ; firePropertyChange ( SIZE_PROP , null , size ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs constraints string [CODESPLIT] public static String dumpConstraints ( final Constraint [ ] constraints ) { if ( constraints == null ) { return null ; } final StringBuffer buffer = new StringBuffer ( ) ; for ( int i = 0 , length = constraints . length ; i < length ; i ++ ) { buffer . append ( constraints [ i ] . toString ( ) + \"<br>\" ) ; } return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces existing zoomManager with the new one . [CODESPLIT] public void setZoomManager ( ZoomManager newManager ) { if ( zoomManager != null ) { zoomManager . removeZoomListener ( this ) ; } zoomManager = newManager ; if ( zoomManager != null ) { zoomManager . addZoomListener ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "$NON - NLS - 1$ [CODESPLIT] public static Map < String , ResourceProperties > parseListing ( String base , InputStream is ) throws Exception { Map < String , ResourceProperties > res = new HashMap < String , ResourceProperties > ( ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder parser = factory . newDocumentBuilder ( ) ; Document doc = parser . parse ( is ) ; NodeList nl = doc . getElementsByTagNameNS ( DAV_NS , \"response\" ) ; //$NON-NLS-1$ for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Element oneElem = ( Element ) nl . item ( i ) ; NodeList resName = oneElem . getElementsByTagNameNS ( DAV_NS , \"href\" ) ; //$NON-NLS-1$ assert ( resName . getLength ( ) == 1 ) ; String bareName = extractOverlap ( base , URLDecoder . decode ( resName . item ( 0 ) . getTextContent ( ) , \"UTF-8\" ) ) ; if ( bareName . trim ( ) . length ( ) > 0 ) { ResourceProperties props = new ResourceProperties ( ) ; NodeList propList = oneElem . getElementsByTagNameNS ( DAV_NS , \"resourcetype\" ) ; //$NON-NLS-1$ assert ( propList . getLength ( ) == 1 ) ; NodeList resTypeList = ( ( Element ) propList . item ( 0 ) ) . getElementsByTagNameNS ( DAV_NS , \"collection\" ) ; //$NON-NLS-1$ assert ( resTypeList . getLength ( ) < 2 ) ; if ( resTypeList . getLength ( ) == 1 ) { props . setDirectory ( true ) ; } propList = oneElem . getElementsByTagNameNS ( DAV_NS , \"creationdate\" ) ; //$NON-NLS-1$ if ( propList . getLength ( ) > 0 ) { props . setCreationDate ( propList . item ( 0 ) . getTextContent ( ) ) ; } propList = oneElem . getElementsByTagNameNS ( DAV_NS , \"getlastmodified\" ) ; //$NON-NLS-1$ if ( propList . getLength ( ) > 0 ) { props . setLastModifiedDate ( propList . item ( 0 ) . getTextContent ( ) ) ; } String normBase = base . trim ( ) . endsWith ( \"/\" ) ? base . trim ( ) : base . trim ( ) + \"/\" ; //$NON-NLS-1$ //$NON-NLS-2$ props . setBase ( normBase ) ; res . put ( bareName , props ) ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) Method declared on ViewerSorter . [CODESPLIT] public int compare ( Viewer viewer , Object o1 , Object o2 ) { DSLMappingEntry item1 = ( DSLMappingEntry ) o1 ; DSLMappingEntry item2 = ( DSLMappingEntry ) o2 ; switch ( criteria ) { case OBJECT : return compareObject ( item1 , item2 ) ; case EXPRESSION : return compareExpressions ( item1 , item2 ) ; case MAPPING : return compareMappings ( item1 , item2 ) ; case SCOPE : return compareScope ( item1 , item2 ) ; default : return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new lockentry and adds it to this supported lock . Returns an editor on the new lockentry . [CODESPLIT] public LockEntry addLockEntry ( ) { Element lockentry = addChild ( root , \"lockentry\" , childNames , false ) ; //$NON-NLS-1$ Element locktype = appendChild ( lockentry , \"locktype\" ) ; //$NON-NLS-1$ appendChild ( locktype , \"write\" ) ; //$NON-NLS-1$ LockEntry result = null ; try { result = new LockEntry ( lockentry ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this supportedlock s <code > LockEntry< / code > s . [CODESPLIT] public Enumeration getLockEntries ( ) throws MalformedElementException { final Node firstLockEntry = getFirstChild ( root , \"lockentry\" ) ; //$NON-NLS-1$ Enumeration e = new Enumeration ( ) { Node currentLockEntry = firstLockEntry ; public boolean hasMoreElements ( ) { return currentLockEntry != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; LockEntry result = null ; try { result = new LockEntry ( ( Element ) currentLockEntry ) ; } catch ( MalformedElementException ex ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } currentLockEntry = getTwin ( ( Element ) currentLockEntry , true ) ; return result ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void createPartControl ( Composite parent ) { viewer = new TreeViewer ( parent , SWT . MULTI | SWT . H_SCROLL | SWT . V_SCROLL ) ; drillDownAdapter = new DrillDownAdapter ( viewer ) ; viewer . setContentProvider ( new RepositoryContentProvider ( ) ) ; viewer . setLabelProvider ( new RepositoryLabelProvider ( ) ) ; viewer . setSorter ( new NameSorter ( ) ) ; viewer . setInput ( viewer ) ; makeActions ( ) ; hookContextMenu ( ) ; hookDoubleClickAction ( ) ; contributeToActionBars ( ) ; Activator . getLocationManager ( ) . addRepositorySetListener ( new IRepositorySetListener ( ) { public void repositorySetChanged ( int type , List < GuvnorRepository > repList ) { // TODO: Just creating an entirely new content provider. //       Someday might update this to have incremental changes //       to existing content provider. viewer . setContentProvider ( new RepositoryContentProvider ( ) ) ; } } ) ; super . getSite ( ) . setSelectionProvider ( viewer ) ; addDragDropSupport ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add new BaseVertex to the graph [CODESPLIT] public boolean addChild ( BaseVertex vertex ) { if ( vertex != null && vertices . add ( vertex ) ) { firePropertyChange ( PROP_CHILD_ADDED , null , vertex ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a vertex from this graph [CODESPLIT] public boolean removeChild ( BaseVertex vertex ) { if ( vertex != null && vertices . remove ( vertex ) ) { firePropertyChange ( PROP_CHILD_REMOVED , null , vertex ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called upon plug - in activation [CODESPLIT] public void start ( BundleContext context ) throws Exception { super . start ( context ) ; IPreferenceStore preferenceStore = getPreferenceStore ( ) ; useCachePreference = preferenceStore . getBoolean ( IDroolsConstants . CACHE_PARSED_RULES ) ; preferenceStore . addPropertyChangeListener ( new IPropertyChangeListener ( ) { public void propertyChange ( PropertyChangeEvent event ) { if ( IDroolsConstants . CACHE_PARSED_RULES . equals ( event . getProperty ( ) ) ) { useCachePreference = ( ( Boolean ) event . getNewValue ( ) ) . booleanValue ( ) ; if ( ! useCachePreference ) { clearCache ( ) ; } } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called when the plug - in is stopped [CODESPLIT] public void stop ( BundleContext context ) throws Exception { super . stop ( context ) ; plugin = null ; resourceBundle = null ; parsedRules = null ; compiledRules = null ; processInfos = null ; processInfosById = null ; for ( Color color : colors . values ( ) ) { color . dispose ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the string from the plugin s resource bundle or key if not found . [CODESPLIT] public static String getResourceString ( String key ) { ResourceBundle bundle = DroolsEclipsePlugin . getDefault ( ) . getResourceBundle ( ) ; try { return ( bundle != null ) ? bundle . getString ( key ) : key ; } catch ( MissingResourceException e ) { return key ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the plugin s resource bundle [CODESPLIT] public ResourceBundle getResourceBundle ( ) { try { if ( resourceBundle == null ) resourceBundle = ResourceBundle . getBundle ( \"droolsIDE.DroolsIDEPluginResources\" ) ; } catch ( MissingResourceException x ) { resourceBundle = null ; } return resourceBundle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Form Colors default colors for now . [CODESPLIT] public FormColors getRuleBuilderFormColors ( Display display ) { if ( ruleBuilderFormColors == null ) { ruleBuilderFormColors = new FormColors ( display ) ; ruleBuilderFormColors . markShared ( ) ; } return ruleBuilderFormColors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do nothing if date format is not supported [CODESPLIT] public void setDateTime ( String date ) { String [ ] patterns = { RFC_1123_PATTERN , ISO_8601_UTC_PATTERN , ISO_8601_UTC_MILLIS_PATTERN , ISO_8601_PATTERN , ISO_8601_MILLIS_PATTERN , RFC_850_PATTERN , ASCTIME_PATTERN } ; for ( int i = 0 ; i < patterns . length ; i ++ ) { if ( setDateTime ( date , patterns [ i ] ) ) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do nothing if date format is not supported . [CODESPLIT] protected boolean setDateTime ( String date , String pattern ) { boolean dateChanged = true ; dateFormat . applyPattern ( pattern ) ; try { setDateTime ( dateFormat . parse ( date ) ) ; } catch ( ParseException e ) { dateChanged = false ; } return dateChanged ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "$NON - NLS - 1$ [CODESPLIT] public static String getDefaultRepositoryDir ( ) { String key = core_defaultRepositoryDir ; String dir = getDeprecatedRepoRootPreference ( ) ; IEclipsePreferences p = InstanceScope . INSTANCE . getNode ( egitPluginId ) ; if ( dir == null ) { dir = p . get ( key , getDefaultDefaultRepositoryDir ( ) ) ; } IStringVariableManager manager = VariablesPlugin . getDefault ( ) . getStringVariableManager ( ) ; String result ; try { result = manager . performStringSubstitution ( dir ) ; } catch ( CoreException e ) { result = \"\" ; //$NON-NLS-1$ } if ( result == null || result . isEmpty ( ) ) { result = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getRawLocation ( ) . toOSString ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void stop ( BundleContext bundleContext ) throws Exception { context = null ; instance = null ; super . stop ( bundleContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility to create an error status for this plug - in . [CODESPLIT] public static IStatus error ( final String message , final Throwable thr ) { return new Status ( IStatus . ERROR , PLUGIN_ID , 0 , message , thr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to log errors in the Egit plugin . [CODESPLIT] public static void logError ( final String message , final Throwable thr ) { getDefault ( ) . getLog ( ) . log ( error ( message , thr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given field editor to this page . [CODESPLIT] protected void addField ( FieldEditor editor ) { if ( fields == null ) { fields = new ArrayList < FieldEditor > ( ) ; } // Set the actual preference name based on the current selection // in the Kie Navigator tree view. The preference name is constructed // from the path to the selected tree node by getPreferenceName(). String name = editor . getPreferenceName ( ) ; editor . setPreferenceName ( getPreferenceName ( name ) ) ; fields . add ( editor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adjust the layout of the field editors so that they are properly aligned . [CODESPLIT] protected void adjustGridLayout ( ) { int numColumns = calcNumberOfColumns ( ) ; ( ( GridLayout ) fieldEditorParent . getLayout ( ) ) . numColumns = numColumns ; if ( fields != null ) { for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { FieldEditor fieldEditor = fields . get ( i ) ; fieldEditor . fillIntoGrid ( fieldEditorParent , numColumns ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applys the font to the field editors managed by this page . [CODESPLIT] protected void applyFont ( ) { if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; // pe.applyFont(); } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the number of columns needed to host all field editors . [CODESPLIT] private int calcNumberOfColumns ( ) { int result = 0 ; if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; result = Math . max ( result , pe . getNumberOfControls ( ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recomputes the page s error state by calling <code > isValid< / code > for every field editor . [CODESPLIT] protected void checkState ( ) { boolean valid = true ; invalidFieldEditor = null ; // The state can only be set to true if all // field editors contain a valid value. So we must check them all if ( fields != null ) { int size = fields . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { FieldEditor editor = fields . get ( i ) ; valid = valid && editor . isValid ( ) ; if ( ! valid ) { invalidFieldEditor = editor ; break ; } } } setValid ( valid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) Method declared on PreferencePage . [CODESPLIT] @ Override protected Control createContents ( Composite parent ) { fieldEditorParent = new Composite ( parent , SWT . NULL ) ; GridLayout layout = new GridLayout ( ) ; layout . numColumns = 1 ; layout . marginHeight = 0 ; layout . marginWidth = 0 ; fieldEditorParent . setLayout ( layout ) ; fieldEditorParent . setFont ( parent . getFont ( ) ) ; createFieldEditors ( ) ; if ( style == GRID ) { adjustGridLayout ( ) ; } initialize ( ) ; checkState ( ) ; return fieldEditorParent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The field editor preference page implementation of an <code > IDialogPage< / code > method disposes of this page s controls and images . Subclasses may override to release their own allocated SWT resources but must call <code > super . dispose< / code > . [CODESPLIT] @ Override public void dispose ( ) { super . dispose ( ) ; if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; pe . setPage ( null ) ; pe . setPropertyChangeListener ( null ) ; pe . setPreferenceStore ( null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a parent composite for a field editor . <p > This value must not be cached since a new parent may be created each time this method called . Thus this method must be called each time a field editor is constructed . < / p > [CODESPLIT] protected Composite getFieldEditorParent ( ) { if ( style == FLAT ) { // Create a new parent for each field editor Composite parent = new Composite ( fieldEditorParent , SWT . NULL ) ; parent . setLayoutData ( new GridData ( GridData . FILL_HORIZONTAL ) ) ; return parent ; } // Just return the parent return fieldEditorParent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes all field editors . [CODESPLIT] protected void initialize ( ) { if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; pe . setPage ( this ) ; pe . setPropertyChangeListener ( this ) ; pe . setPreferenceStore ( getPreferenceStore ( ) ) ; pe . load ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The field editor preference page implementation of a <code > PreferencePage< / code > method loads all the field editors with their default values . [CODESPLIT] @ Override protected void performDefaults ( ) { if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; pe . loadDefault ( ) ; } } // Force a recalculation of my error state. checkState ( ) ; super . performDefaults ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The field editor preference page implementation of this <code > PreferencePage< / code > method saves all field editors by calling <code > FieldEditor . store< / code > . Note that this method does not save the preference store itself ; it just stores the values back into the preference store . [CODESPLIT] @ Override public boolean performOk ( ) { if ( fields != null ) { Iterator < FieldEditor > e = fields . iterator ( ) ; while ( e . hasNext ( ) ) { FieldEditor pe = e . next ( ) ; pe . store ( ) ; // pe.setPresentsDefaultValue(false); } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The field editor preference page implementation of this <code > IPreferencePage< / code > ( and <code > IPropertyChangeListener< / code > ) method intercepts <code > IS_VALID< / code > events but passes other events on to its superclass . [CODESPLIT] @ Override public void propertyChange ( PropertyChangeEvent event ) { if ( event . getProperty ( ) . equals ( FieldEditor . IS_VALID ) ) { boolean newValue = ( ( Boolean ) event . getNewValue ( ) ) . booleanValue ( ) ; // If the new value is true then we must check all field editors. // If it is false, then the page is invalid in any case. if ( newValue ) { checkState ( ) ; } else { invalidFieldEditor = ( FieldEditor ) event . getSource ( ) ; setValid ( newValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) Method declared on IDialog . [CODESPLIT] @ Override public void setVisible ( boolean visible ) { super . setVisible ( visible ) ; if ( visible && invalidFieldEditor != null ) { invalidFieldEditor . setFocus ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean contains ( String name ) { JsonValue value = object . get ( name ) ; return value != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void firePropertyChangeEvent ( String name , Object oldValue , Object newValue ) { firePropertyChangeEvent ( this , name , oldValue , newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires a property change event with the given source property name old and new value . Used when the event source should be different from this mockup preference store . [CODESPLIT] public void firePropertyChangeEvent ( Object source , String name , Object oldValue , Object newValue ) { PropertyChangeEvent event = new PropertyChangeEvent ( source , name , oldValue , newValue ) ; Object [ ] listeners = fListeners . getListeners ( ) ; for ( int i = 0 ; i < listeners . length ; i ++ )  ( ( IPropertyChangeListener ) listeners [ i ] ) . propertyChange ( event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void putValue ( String name , String value ) { object . set ( name , value ) ; dirty = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setValue ( String name , String value ) { String oldValue = this . getString ( name ) ; putValue ( name , value ) ; firePropertyChangeEvent ( name , oldValue , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void run ( IAction action ) { if ( selectedFile == null || props == null || targetPart == null ) { return ; } VersionChooserDialog dialog = new VersionChooserDialog ( targetPart . getSite ( ) . getShell ( ) , selectedFile . getName ( ) , getVersionEntries ( ) ) ; if ( dialog . open ( ) == VersionChooserDialog . OK ) { compareWithSelectedVersion ( dialog . getSelectedEntry ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void init ( IActionBars bars , IWorkbenchPage page ) { contributor . init ( bars ) ; super . init ( bars , page ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setActivePage ( IEditorPart activeEditor ) { IActionBars bars = getActionBars ( ) ; if ( activeEditor instanceof ITextEditor ) { if ( bars != null ) { contributor . setActiveEditor ( activeEditor ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In addition to [CODESPLIT] public void setActiveEditor ( IEditorPart part ) { super . setActiveEditor ( part ) ; if ( part instanceof DRLRuleEditor2 ) { DRLRuleEditor2 p = ( DRLRuleEditor2 ) part ; p . setZoomComboContributionItem ( zitem ) ; p . setZoomInAction ( zoomIn ) ; p . setZoomOutAction ( zoomOut ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds Zoom - related contributions . [CODESPLIT] public void contributeToToolBar ( IToolBarManager toolBarManager ) { super . contributeToToolBar ( toolBarManager ) ; toolBarManager . add ( new Separator ( ) ) ; String [ ] zoomStrings = new String [ ] { ZoomManager . FIT_ALL , ZoomManager . FIT_HEIGHT , ZoomManager . FIT_WIDTH } ; zitem = new ZoomComboContributionItem ( getPage ( ) , zoomStrings ) ; zitem . setZoomManager ( null ) ; zitem . setVisible ( false ) ; zoomIn = new ZoomInAction2 ( ) ; zoomIn . setEnabled ( false ) ; zoomOut = new ZoomOutAction2 ( ) ; zoomOut . setEnabled ( false ) ; toolBarManager . add ( zitem ) ; toolBarManager . add ( zoomIn ) ; toolBarManager . add ( zoomOut ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "especially when parsing incomplete rules [CODESPLIT] private void determineDialect ( String backText ) { dialect = null ; boolean mvel = MVEL_DIALECT_PATTERN . matcher ( backText ) . matches ( ) ; boolean java = JAVA_DIALECT_PATTERN . matcher ( backText ) . matches ( ) ; if ( mvel ) { dialect = MVEL_DIALECT ; } else if ( java ) { dialect = JAVA_DIALECT ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the variables defined in the given rule ( fragment ) . The key is the name of the variable . The value is a list of 2 String : - the first one is the class name of the variable - the second one is the property of the given class that defines the type of this variable note that this property could be nested if this property is null then the given class is the type of the variable [CODESPLIT] public Map < String , String [ ] > getRuleParameters ( ) { Map < String , String [ ] > result = new HashMap < String , String [ ] > ( ) ; int i = 0 ; int lastLocation = - 1 ; for ( Object o : parserList ) { if ( o instanceof DroolsToken ) { DroolsToken token = ( DroolsToken ) o ; if ( DroolsEditorType . IDENTIFIER_VARIABLE . equals ( token . getEditorType ( ) ) || DroolsEditorType . IDENTIFIER_PATTERN . equals ( token . getEditorType ( ) ) ) { String variableName = token . getText ( ) ; if ( lastLocation == Location . LOCATION_LHS_BEGIN_OF_CONDITION ) { int j = i + 2 ; String className = \"\" ; while ( j < parserList . size ( ) ) { Object obj = parserList . get ( j ++ ) ; if ( obj instanceof DroolsToken ) { String s = ( ( DroolsToken ) obj ) . getText ( ) ; if ( \"(\" . equals ( s ) ) { result . put ( variableName , new String [ ] { className , null } ) ; break ; } else { className += s ; } } } } else if ( lastLocation == Location . LOCATION_LHS_INSIDE_CONDITION_START ) { int index = findTokenBack ( Location . LOCATION_LHS_BEGIN_OF_CONDITION , i ) ; int j = index + 3 ; String className = \"\" ; while ( j < i ) { Object obj = parserList . get ( j ++ ) ; if ( obj instanceof DroolsToken ) { String s = ( ( DroolsToken ) obj ) . getText ( ) ; if ( \"(\" . equals ( s ) ) { break ; } else { className += s ; } } } j = i + 2 ; String propertyName = \"\" ; while ( j < parserList . size ( ) ) { Object obj = parserList . get ( j ++ ) ; if ( obj instanceof DroolsToken ) { String s = ( ( DroolsToken ) obj ) . getText ( ) ; if ( \",\" . equals ( s ) || \")\" . equals ( s ) ) { result . put ( variableName , new String [ ] { className , propertyName } ) ; break ; } else { propertyName += s ; } } else { result . put ( variableName , new String [ ] { className , propertyName } ) ; } } } } } else if ( o instanceof Integer ) { lastLocation = ( Integer ) o ; } i ++ ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the given <code > URL< / code > from an <code > ASCII< / code > readable <code > URL< / code > that is safe for transport . Returns the result . [CODESPLIT] public static String decode ( String url ) { try { return decode ( new URL ( url ) ) . toString ( ) ; } catch ( MalformedURLException e ) { // ignore or log? } String file ; String ref = null ; int lastSlashIndex = url . lastIndexOf ( ' ' ) ; int lastHashIndex = url . lastIndexOf ( ' ' ) ; if ( ( lastHashIndex - lastSlashIndex > 1 ) && lastHashIndex < url . length ( ) - 1 ) { file = url . substring ( 0 , lastHashIndex ) ; ref = url . substring ( lastHashIndex + 1 , url . length ( ) ) ; } else { file = url ; } return decode ( file , ref ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the file and reference parts of a <code > URL< / code > from an <code > ASCII< / code > readable <code > URL< / code > that is safe for transport . Returns the result . [CODESPLIT] public static String decode ( String file , String ref ) { StringBuffer buf = new StringBuffer ( ) ; StringTokenizer tokenizer = new StringTokenizer ( file , \"/\" , true ) ; //$NON-NLS-1$ while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) ; if ( token . equals ( \"/\" ) ) { //$NON-NLS-1$ buf . append ( token ) ; } else { buf . append ( decodeSegment ( token ) ) ; } } if ( ref != null ) { buf . append ( ' ' ) ; buf . append ( decodeSegment ( ref ) ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the BASE64 encoded <code > String< / code > of the given data . [CODESPLIT] public static String encode ( byte [ ] data ) { Assert . isNotNull ( data ) ; StringBuffer buf = new StringBuffer ( ) ; byte b = 0 ; int bits = 2 ; for ( int i = 0 ; i < data . length ; ++ i ) { b = ( byte ) ( ( b | ( data [ i ] >> bits ) ) & 0x003f ) ; buf . append ( encode ( b ) ) ; b = ( byte ) ( ( data [ i ] << 6 - bits ) & 0x003f ) ; bits += 2 ; if ( bits == 8 ) { buf . append ( encode ( ( byte ) ( b & 0x003f ) ) ) ; b = 0 ; bits = 2 ; } } if ( bits == 4 ) { buf . append ( encode ( b ) ) ; buf . append ( \"==\" ) ; //$NON-NLS-1$ } else if ( bits == 6 ) { buf . append ( encode ( b ) ) ; buf . append ( ' ' ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new context that is based on the given context . [CODESPLIT] protected IContext newContext ( IContext userContext , ILocator locator ) throws MalformedURLException { Assert . isNotNull ( userContext ) ; Assert . isNotNull ( locator ) ; IContext context = davFactory . newContext ( userContext ) ; if ( locator . getLabel ( ) != null ) context . setLabel ( locator . getLabel ( ) ) ; return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for the sort field [CODESPLIT] public void doSave ( IProgressMonitor monitor ) { FileEditorInput input = ( FileEditorInput ) getEditorInput ( ) ; File outputFile = input . getFile ( ) . getLocation ( ) . toFile ( ) ; saveFile ( monitor , outputFile , input ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup table listeners for GUI events . [CODESPLIT] private void createTableListeners ( ) { //setup views into current selected table . addSelectionListener ( new SelectionListener ( ) { public void widgetSelected ( SelectionEvent e ) { populate ( ) ; } public void widgetDefaultSelected ( SelectionEvent e ) { populate ( ) ; } private void populate ( ) { DSLMappingEntry selected = getCurrentSelected ( ) ; exprText . setText ( selected . getMappingKey ( ) ) ; mappingText . setText ( selected . getMappingValue ( ) ) ; objText . setText ( selected . getMetaData ( ) . getMetaData ( ) == null ? \"\" : selected . getMetaData ( ) . getMetaData ( ) ) ; } } ) ; //double click support table . addMouseListener ( new MouseListener ( ) { public void mouseDoubleClick ( MouseEvent e ) { showEditPopup ( ) ; } public void mouseDown ( MouseEvent e ) { } public void mouseUp ( MouseEvent e ) { } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the Table [CODESPLIT] private void createTable ( Composite parent ) { int style = SWT . MULTI | SWT . BORDER | SWT . H_SCROLL | SWT . V_SCROLL | SWT . FULL_SELECTION | SWT . HIDE_SELECTION ; table = new Table ( parent , style ) ; GridData gridData = new GridData ( GridData . FILL_BOTH ) ; gridData . grabExcessVerticalSpace = true ; gridData . horizontalSpan = 3 ; table . setLayoutData ( gridData ) ; table . setLinesVisible ( true ) ; table . setHeaderVisible ( true ) ; TableColumn column ; //Expression col column = new TableColumn ( table , SWT . LEFT , 0 ) ; column . setText ( \"Language Expression\" ) ; column . setWidth ( 350 ) ; // Add listener to column so sorted when clicked  column . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { tableViewer . setSorter ( new DSLMappingSorter ( DSLMappingSorter . EXPRESSION ) ) ; } } ) ; // 3rd column with task Owner column = new TableColumn ( table , SWT . LEFT , 1 ) ; column . setText ( \"Rule Language Mapping\" ) ; column . setWidth ( 200 ) ; // Add listener to column so sorted when clicked column . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { tableViewer . setSorter ( new DSLMappingSorter ( DSLMappingSorter . MAPPING ) ) ; } } ) ; // 4th column with task PercentComplete  column = new TableColumn ( table , SWT . LEFT , 2 ) ; column . setText ( \"Object\" ) ; column . setWidth ( 80 ) ; // 5th column with task PercentComplete  column = new TableColumn ( table , SWT . LEFT , 3 ) ; column . setText ( \"Scope\" ) ; column . setWidth ( 80 ) ; //  Add listener to column so tasks are sorted when clicked column . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { tableViewer . setSorter ( new DSLMappingSorter ( DSLMappingSorter . SCOPE ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which the given URL is mapped to in the table . If the given URL not mapped to any value or is malformed returns <code > null< / code > . [CODESPLIT] public Object get ( String url ) throws MalformedURLException { Assert . isNotNull ( url ) ; return get ( new URL ( url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which the given <code > URL< / code > is mapped to in the table . If the given <code > URL< / code > not mapped to any value returns <code > null< / code > . [CODESPLIT] public Object get ( URL url ) { Assert . isNotNull ( url ) ; return get ( new URLKey ( url ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which the specified URL is mapped to in the table . If the specified URL is not mapped to any value returns <code > null< / code > . [CODESPLIT] private Object get ( URLKey url ) { Assert . isNotNull ( url ) ; return table . get ( url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over the keys in this <code > URLTable< / code > . [CODESPLIT] public Enumeration keys ( ) { final Enumeration keys = table . keys ( ) ; Enumeration e = new Enumeration ( ) { public boolean hasMoreElements ( ) { return keys . hasMoreElements ( ) ; } public Object nextElement ( ) { return ( ( URLKey ) keys . nextElement ( ) ) . getURL ( ) ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the given URL to the given value in this table . [CODESPLIT] public void put ( String url , Object value ) throws MalformedURLException { Assert . isNotNull ( url ) ; Assert . isNotNull ( value ) ; put ( new URL ( url ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the given <code > URL< / code > to the given value in this table . [CODESPLIT] public void put ( URL url , Object value ) { Assert . isNotNull ( url ) ; Assert . isNotNull ( value ) ; put ( new URLKey ( url ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the specified URL to the given value in this table . [CODESPLIT] private void put ( URLKey url , Object value ) { Assert . isNotNull ( url ) ; Assert . isNotNull ( value ) ; // Remove the old entry so the url key is replaced if ( table . get ( url ) != null ) table . remove ( url ) ; table . put ( url , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method will create a new Node instance and try to add it as a child node . If an Node with the same string token exists the method will return the existing node instead . [CODESPLIT] public Node addToken ( String token ) { Node newnode = new Node ( token ) ; // set the depth first newnode . setDepth ( depth + 1 ) ; // add the node as a child newnode = addChild ( newnode ) ; return newnode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method will check to see if a Node with the same string token already exists . If it doesn t it will add the token as a child and return the same node . [CODESPLIT] public Node addChild ( Node n ) { if ( ! this . children . containsKey ( n . getToken ( ) ) ) { this . children . put ( n . getToken ( ) , n ) ; n . setParent ( this ) ; return n ; } else { return ( Node ) this . children . get ( n . getToken ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "be used directly . Use DroolsModelBuilder instead . [CODESPLIT] void setFile ( IFile file , int offset , int length ) { this . file = file ; this . offset = offset ; this . length = length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean canExecute ( ) { Object type = request . getType ( ) ; return ( RequestConstants . REQ_MOVE . equals ( type ) || RequestConstants . REQ_MOVE_CHILDREN . equals ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Condition to this Precondition . Conditions are OR d together to check for a matching resource . [CODESPLIT] public void addCondition ( Condition condition ) throws WebDAVException { // a Resource URI can only be specified once in a Precondition Enumeration conditions = getConditions ( ) ; if ( condition . getResourceURI ( ) != null ) { while ( conditions . hasMoreElements ( ) ) { Condition existingCondition = ( Condition ) conditions . nextElement ( ) ; if ( existingCondition . getResourceURI ( ) != null && existingCondition . getResourceURI ( ) . equals ( condition . getResourceURI ( ) ) ) throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMultipleSpecification\" , condition . getResourceURI ( ) ) ) ; //$NON-NLS-1$ } } this . conditions . addElement ( condition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a condition created from the given URI and state token . This is a convenience method used primarily to create preconditions for lock tokens that must be provided in the resource context for methods that update the resource . [CODESPLIT] public void addStateTokenCondition ( String resourceURI , String stateToken ) throws WebDAVException { Condition condition = new Condition ( resourceURI ) ; ConditionTerm term = new ConditionTerm ( ) ; term . addConditionFactor ( new StateToken ( stateToken ) ) ; condition . addConditionTerm ( term ) ; addCondition ( condition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if this Precondition contains a matching Condition . [CODESPLIT] public boolean matches ( Condition condition ) { boolean match = false ; Enumeration conditions = getConditions ( ) ; while ( ! match && conditions . hasMoreElements ( ) ) { Condition existingCondition = ( Condition ) conditions . nextElement ( ) ; match = existingCondition . matches ( condition ) ; } return match ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts that the given object is not <code > null< / code > . If this is not the case some kind of unchecked exception is thrown . The given message is included in that exception to aid debugging . [CODESPLIT] static public void isNotNull ( Object o , String message ) { if ( o == null ) throw new AssertionFailedException ( Policy . bind ( \"assert.null\" , message ) ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts that the given boolean is <code > true< / code > . If this is not the case some kind of unchecked exception is thrown . The given message is included in that exception to aid debugging . [CODESPLIT] static public boolean isTrue ( boolean expression , String message ) { if ( ! expression ) throw new AssertionFailedException ( Policy . bind ( \"assert.fail\" , message ) ) ; //$NON-NLS-1$ return expression ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this propstat s prop . [CODESPLIT] public Prop getProp ( ) throws MalformedElementException { Element prop = getFirstChild ( root , \"prop\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingPropElmt\" ) , prop ) ; //$NON-NLS-1$ return new Prop ( prop ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this propstat s status . [CODESPLIT] public String getStatus ( ) throws MalformedElementException { String status = getChildText ( root , \"status\" , false ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingStatusElmt\" ) , status ) ; //$NON-NLS-1$ return status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and sets a new prop on this propstat and returns an editor on it . [CODESPLIT] public Prop setProp ( ) { Element prop = setChild ( root , \"prop\" , childNames , true ) ; //$NON-NLS-1$ try { return new Prop ( prop ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the status on this propstat to the given status . The status must not be <code > null< / code > . [CODESPLIT] public void setStatus ( String status ) { Assert . isNotNull ( status ) ; setChild ( root , \"status\" , status , childNames , true ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "because of how the backText works we need to get the last line so that we can pass it to the DSLUtility [CODESPLIT] public String getLastLine ( String backText ) { BufferedReader breader = new BufferedReader ( new StringReader ( backText ) ) ; String last = \"\" ; String line = null ; try { while ( ( line = breader . readLine ( ) ) != null ) { // only if the line has text do we set last to it if ( line . length ( ) > 0 ) { last = line ; } } } catch ( IOException e ) { DroolsEclipsePlugin . log ( e ) ; } // now that all the conditions for a single object are on the same line // we need to check for the left parenthesis if ( last . indexOf ( \"(\" ) > - 1 ) { last = last . substring ( last . lastIndexOf ( \"(\" ) + 1 ) ; } // if the string has a comma \",\" we get the substring starting from // the index after the last comma if ( last . indexOf ( \",\" ) > - 1 ) { last = last . substring ( last . lastIndexOf ( \",\" ) + 1 ) ; } // if the line ends with right parenthesis, we change it to zero length // string if ( last . endsWith ( \")\" ) ) { last = \"\" ; } return last ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last line that doesn t start with a dash [CODESPLIT] public String getLastNonDashLine ( String backText ) { BufferedReader breader = new BufferedReader ( new StringReader ( backText ) ) ; String last = \"\" ; String line = null ; try { while ( ( line = breader . readLine ( ) ) != null ) { // there may be blank lines, so we trim first line = line . trim ( ) ; // only if the line has text do we set last to it if ( line . length ( ) > 0 && ! line . startsWith ( \"-\" ) ) { last = line ; } } } catch ( IOException e ) { DroolsEclipsePlugin . log ( e ) ; } if ( last . indexOf ( \"(\" ) > - 1 && ! last . endsWith ( \")\" ) ) { last = last . substring ( 0 , last . indexOf ( \"(\" ) ) ; } else if ( last . indexOf ( \"(\" ) > - 1 && last . endsWith ( \")\" ) ) { last = \"\" ; } return last ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The DSLTree is configurable . It can either return just the child of the last token found or it can traverse the tree and generate all the combinations beneath the last matching node . TODO I don t know how to add configuration to the editor so it needs to be hooked up to the configuration for the editor later . [CODESPLIT] protected List < String > getProposals ( DSLAdapter adapter , String obj , String last , boolean firstLine ) { if ( last . length ( ) == 0 ) { last = \" \" ; } return adapter . getDSLTree ( ) . getChildrenList ( obj , last , true , firstLine ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup the message with the given ID in this catalog and bind its substitution locations with the given string . [CODESPLIT] public static String bind ( String id , String binding ) { return bind ( id , new String [ ] { binding } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup the message with the given ID in this catalog and bind its substitution locations with the given strings . [CODESPLIT] public static String bind ( String id , String binding1 , String binding2 ) { return bind ( id , new String [ ] { binding1 , binding2 } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup the message with the given ID in this catalog and bind its substitution locations with the given string values . [CODESPLIT] public static String bind ( String id , String [ ] bindings ) { if ( id == null ) return \"No message available\" ; //$NON-NLS-1$ String message = null ; try { message = bundle . getString ( id ) ; } catch ( MissingResourceException e ) { // If we got an exception looking for the message, fail gracefully by just returning // the id we were looking for.  In most cases this is semi-informative so is not too bad. return \"Missing message: \" + id + \"in: \" + bundleName ; //$NON-NLS-1$ //$NON-NLS-2$ } if ( bindings == null ) return message ; return MessageFormat . format ( message , bindings ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given file and reference parts of a <code > URL< / code > into an <code > ASCII< / code > readable <code > String< / code > that is safe for transport . Returns the result . [CODESPLIT] public static String encode ( String file , String ref ) { StringBuffer buf = new StringBuffer ( ) ; StringTokenizer tokenizer = new StringTokenizer ( file , \"/\" , true ) ; //$NON-NLS-1$ while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) ; if ( token . equals ( \"/\" ) ) { //$NON-NLS-1$ buf . append ( token ) ; } else { buf . append ( encodeSegment ( token ) ) ; } } if ( ref != null ) { buf . append ( ' ' ) ; buf . append ( encodeSegment ( ref ) ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given <code > URL< / code > into an <code > ASCII< / code > readable <code > URL< / code > that is safe for transport . Returns the result . [CODESPLIT] public static URL encode ( URL url ) { String file = url . getFile ( ) ; String ref = url . getRef ( ) ; try { return new URL ( url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , encode ( file , ref ) ) ; } catch ( MalformedURLException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] protected IFigure createFigure ( ) { PolylineConnection connection = new ConnectionFigure ( ) ; PolylineDecoration decoration = new PolylineDecoration ( ) ; connection . setTargetDecoration ( decoration ) ; return connection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the sample process file . [CODESPLIT] private void createProcess ( IJavaProject project , IProgressMonitor monitor , String exampleType ) throws CoreException , IOException { // create the process (sample.bpmn) file String fileName = \"org/jbpm/eclipse/wizard/project/\" + exampleType + \".bpmn.template\" ; IFolder folder = null ; folder = project . getProject ( ) . getFolder ( \"src/main/resources/com/sample\" ) ; FileUtils . createFolder ( folder , monitor ) ; IFile file = folder . getFile ( \"sample.bpmn\" ) ; InputStream inputstream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( fileName ) ; if ( ! file . exists ( ) ) { file . create ( inputstream , true , monitor ) ; } else { file . setContents ( inputstream , true , false , monitor ) ; } // create a Java main class to invoke the process fileName = \"org/jbpm/eclipse/wizard/project/ProcessMain-\" + exampleType + \".java\" ; IRuntime runtime = startPage . getRuntime ( ) ; if ( runtime . getVersion ( ) . getMajor ( ) == 5 ) { fileName += \".v5.template\" ; } else { fileName += \".template\" ; } folder = project . getProject ( ) . getFolder ( \"src/main/java\" ) ; IPackageFragmentRoot packageFragmentRoot = project . getPackageFragmentRoot ( folder ) ; IPackageFragment packageFragment = packageFragmentRoot . createPackageFragment ( \"com.sample\" , true , monitor ) ; inputstream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( fileName ) ; packageFragment . createCompilationUnit ( \"ProcessMain.java\" , new String ( FileUtils . readStream ( inputstream ) ) , true , monitor ) ; // create persistence.xml if ( runtime . getVersion ( ) . getMajor ( ) == 5 ) { if ( \"advanced\" . equals ( exampleType ) ) { folder = project . getProject ( ) . getFolder ( \"src/main/resources/META-INF\" ) ; FileUtils . createFolder ( folder , monitor ) ; inputstream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( \"org/jbpm/eclipse/wizard/project/ProcessLauncher-advanced-persistence.xml.template\" ) ; file = folder . getFile ( \"persistence.xml\" ) ; if ( ! file . exists ( ) ) { file . create ( inputstream , true , monitor ) ; } else { file . setContents ( inputstream , true , false , monitor ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the sample process junit test file . [CODESPLIT] private void createProcessSampleJUnit ( IJavaProject project , String exampleType , IProgressMonitor monitor ) throws JavaModelException , IOException { String s = \"org/jbpm/eclipse/wizard/project/ProcessJUnit-\" + exampleType + \".java\" ; IRuntime runtime = startPage . getRuntime ( ) ; if ( runtime . getVersion ( ) . getMajor ( ) == 5 ) { s += \".v5.template\" ; } else { s += \".template\" ; } IFolder folder = project . getProject ( ) . getFolder ( \"src/main/java\" ) ; IPackageFragmentRoot packageFragmentRoot = project . getPackageFragmentRoot ( folder ) ; IPackageFragment packageFragment = packageFragmentRoot . createPackageFragment ( \"com.sample\" , true , monitor ) ; InputStream inputstream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( s ) ; packageFragment . createCompilationUnit ( \"ProcessTest.java\" , new String ( FileUtils . readStream ( inputstream ) ) , true , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected IKieProjectWizardPage createOnlineExampleProjectPage ( String pageId ) { return new AbstractKieOnlineExampleProjectWizardPage ( ONLINE_EXAMPLE_PROJECT_PAGE ) { @ Override public String getTitle ( ) { return \"Create jBPM Projects from Online Examples\" ; } @ Override public String getDescription ( ) { return \"Select jBPM Example Projects\" ; } @ Override public IRuntimeManager getRuntimeManager ( ) { return JBPMRuntimeManager . getDefault ( ) ; } @ Override public String getProductId ( ) { return \"jbpm\" ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the version number of the KIE Workbench that is installed on the given server . If the server is not running or not responsive use a value from the Preference Store . [CODESPLIT] @ Override public String getRuntimeId ( ) { IPreferenceStore store = org . kie . eclipse . Activator . getDefault ( ) . getPreferenceStore ( ) ; String value = store . getString ( getKieVersionPreferenceKey ( ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public List < IKieRepositoryHandler > getRepositories ( IKieSpaceHandler space ) throws IOException { return getDelegate ( ) . getRepositories ( space ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public List < IKieProjectHandler > getProjects ( IKieRepositoryHandler repository ) throws IOException { return getDelegate ( ) . getProjects ( repository ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the index of the given object in the array starting at the given index . < / p > [CODESPLIT] public static int indexOf ( Object [ ] array , Object objectToFind , int startIndex ) { if ( array == null ) { return INDEX_NOT_FOUND ; } if ( startIndex < 0 ) { startIndex = 0 ; } if ( objectToFind == null ) { for ( int i = startIndex ; i < array . length ; i ++ ) { if ( array [ i ] == null ) { return i ; } } } else { for ( int i = startIndex ; i < array . length ; i ++ ) { if ( objectToFind . equals ( array [ i ] ) ) { return i ; } } } return INDEX_NOT_FOUND ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void run ( IAction action ) { String repositoryLoc = null ; String fullPath = null ; if ( selectedNode != null ) { repositoryLoc = selectedNode . getGuvnorRepository ( ) . getLocation ( ) ; fullPath = selectedNode . getFullPath ( ) ; } else { if ( selectedFile == null || props == null ) { return ; } repositoryLoc = props . getRepository ( ) ; fullPath = props . getFullpath ( ) ; } IResponse response = null ; try { IWebDavClient client = WebDavServerCache . getWebDavClient ( repositoryLoc ) ; if ( client == null ) { client = WebDavClientFactory . createClient ( new URL ( repositoryLoc ) ) ; WebDavServerCache . cacheWebDavClient ( repositoryLoc , client ) ; } InputStream ins = null ; try { response = client . getResourceVersions ( fullPath ) ; ins = response . getInputStream ( ) ; } catch ( WebDavException wde ) { if ( wde . getErrorCode ( ) != IResponse . SC_UNAUTHORIZED ) { // If not an authentication failure, we don't know what to do with it throw wde ; } boolean retry = PlatformUtils . getInstance ( ) . authenticateForServer ( repositoryLoc , client ) ; if ( retry ) { response = client . getResourceVersions ( fullPath ) ; ins = response . getInputStream ( ) ; } } if ( ins != null ) { Properties verProps = new Properties ( ) ; verProps . load ( ins ) ; ResourceHistoryView view = PlatformUtils . getResourceHistoryView ( ) ; if ( view != null ) { view . setEntries ( repositoryLoc , fullPath , verProps ) ; } } } catch ( Exception e ) { Activator . getDefault ( ) . displayError ( IStatus . ERROR , e . getMessage ( ) , e , true ) ; } finally { if ( response != null ) { try { response . close ( ) ; } catch ( IOException ioe ) { Activator . getDefault ( ) . writeLog ( IStatus . ERROR , ioe . getMessage ( ) , ioe ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void selectionChanged ( IAction action , ISelection selection ) { // Reset state to default selectedFile = null ; selectedNode = null ; props = null ; action . setEnabled ( false ) ; if ( ! ( selection instanceof IStructuredSelection ) ) { return ; } IStructuredSelection sel = ( IStructuredSelection ) selection ; if ( sel . size ( ) != 1 ) { return ; } if ( sel . getFirstElement ( ) instanceof IFile ) { try { props = GuvnorMetadataUtils . getGuvnorMetadata ( ( IFile ) sel . getFirstElement ( ) ) ; if ( props != null ) { selectedFile = ( IFile ) sel . getFirstElement ( ) ; action . setEnabled ( true ) ; } } catch ( Exception e ) { Activator . getDefault ( ) . writeLog ( IStatus . ERROR , e . getMessage ( ) , e ) ; } } if ( sel . getFirstElement ( ) instanceof TreeObject ) { if ( ( ( TreeObject ) sel . getFirstElement ( ) ) . getNodeType ( ) == TreeObject . Type . RESOURCE ) { selectedNode = ( TreeObject ) sel . getFirstElement ( ) ; action . setEnabled ( true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rete visits each of its ObjectTypeNodes . [CODESPLIT] public void visitRete ( final Rete rete ) { this . rootVertex = ( ReteVertex ) this . visitedNodes . get ( dotId ( rete ) ) ; if ( this . rootVertex == null ) { this . rootVertex = new ReteVertex ( rete ) ; this . visitedNodes . put ( dotId ( rete ) , this . rootVertex ) ; } this . graph . addChild ( this . rootVertex ) ; this . parentVertex = this . rootVertex ; for ( EntryPointNode node : rete . getEntryPointNodes ( ) . values ( ) ) { visit ( node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to ensure nodes are not visited more than once . [CODESPLIT] private void visitNode ( final Object node ) { Object realNode = node ; if ( node instanceof ObjectHashMap . ObjectEntry ) { ObjectHashMap . ObjectEntry entry = ( ObjectHashMap . ObjectEntry ) node ; realNode = entry . getValue ( ) ; } visit ( realNode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The identity hashCode for the given object is used as its unique DOT identifier . [CODESPLIT] private static String dotId ( final Object object ) { return Integer . toHexString ( System . identityHashCode ( object ) ) . toUpperCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a remove to the given propertyupdate and returns an editor on its prop . [CODESPLIT] public Prop addRemove ( ) { Element remove = appendChild ( root , \"remove\" ) ; //$NON-NLS-1$ Element prop = appendChild ( remove , \"prop\" ) ; //$NON-NLS-1$ Prop result = null ; try { result = new Prop ( prop ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a set to the given propertyupdate and returns an editor on its prop . [CODESPLIT] public Prop addSet ( ) { Element set = appendChild ( root , \"set\" ) ; //$NON-NLS-1$ Element prop = appendChild ( set , \"prop\" ) ; //$NON-NLS-1$ try { return new Prop ( prop ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this propertyupdate s set and remove property elements . [CODESPLIT] public Enumeration getSetsAndRemoves ( ) throws MalformedElementException { Node setOrRemove = getFirstChild ( root , new String [ ] { \"remove\" , \"set\" } ) ; //$NON-NLS-1$ //$NON-NLS-2$ ensureNotNull ( Policy . bind ( \"ensure.missingRemoveOrSetElmt\" ) , setOrRemove ) ; //$NON-NLS-1$ Node property = null ; while ( setOrRemove != null && property == null ) { Node prop = getFirstChild ( ( Element ) setOrRemove , \"prop\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingPropElmt\" ) , prop ) ; //$NON-NLS-1$ property = getChildElement ( ( Element ) prop , true ) ; if ( property == null ) setOrRemove = getNextSibling ( ( Element ) setOrRemove , new String [ ] { \"remove\" , \"set\" } ) ; //$NON-NLS-1$ //$NON-NLS-2$ } final Node a = setOrRemove ; final Node c = property ; Enumeration e = new Enumeration ( ) { Node currentSetOrRemove = a ; Node currentProperty = c ; public boolean hasMoreElements ( ) { return currentProperty != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; Directive result = null ; try { result = new Directive ( ( Element ) currentProperty ) ; } catch ( MalformedElementException ex ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } currentProperty = getNextSibling ( ( Element ) currentProperty ) ; while ( currentSetOrRemove != null && currentProperty == null ) { currentSetOrRemove = getNextSibling ( ( Element ) currentSetOrRemove , new String [ ] { \"remove\" , \"set\" } ) ; //$NON-NLS-1$ //$NON-NLS-2$ if ( currentSetOrRemove != null ) { Node prop = getFirstChild ( ( Element ) currentSetOrRemove , \"prop\" ) ; //$NON-NLS-1$ if ( prop != null ) currentProperty = getChildElement ( ( Element ) prop , true ) ; } } return result ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected Control createContents ( Composite parent ) { Control contents = super . createContents ( parent ) ; setTitle ( title ) ; validate ( ) ; return contents ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected Control createDialogArea ( Composite parent ) { Composite parentComposite = ( Composite ) super . createDialogArea ( parent ) ; Composite composite = new Composite ( parentComposite , SWT . NONE ) ; composite . setLayoutData ( new GridData ( SWT . FILL , SWT . FILL , true , true ) ) ; composite . setLayout ( new GridLayout ( 3 , false ) ) ; composite . setFont ( parent . getFont ( ) ) ; createFields ( composite ) ; return parentComposite ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected Control createHelpControl ( Composite parent ) { ( ( GridLayout ) parent . getLayout ( ) ) . numColumns ++ ; errorComposite = new Composite ( parent , SWT . NONE ) ; GridData gd = new GridData ( SWT . FILL , SWT . FILL , true , true ) ; errorComposite . setLayoutData ( gd ) ; errorComposite . setLayout ( new GridLayout ( 2 , false ) ) ; Label errorImage = new Label ( errorComposite , SWT . NONE ) ; errorImage . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . CENTER , false , false ) ) ; errorImage . setImage ( JFaceResources . getImage ( DLG_IMG_TITLE_ERROR ) ) ; errorText = new Label ( errorComposite , SWT . NONE ) ; gd = new GridData ( SWT . FILL , SWT . CENTER , true , false ) ; errorText . setLayoutData ( gd ) ; errorText . setText ( \"\" ) ; return errorComposite ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void setErrorMessage ( String newErrorMessage ) { if ( errorComposite != null && ! errorComposite . isDisposed ( ) ) { if ( newErrorMessage == null || newErrorMessage . isEmpty ( ) ) { errorComposite . setVisible ( false ) ; ( ( GridData ) errorComposite . getLayoutData ( ) ) . exclude = true ; errorText . setText ( \"\" ) ; } else { errorComposite . setVisible ( true ) ; ( ( GridData ) errorComposite . getLayoutData ( ) ) . exclude = false ; errorText . setText ( newErrorMessage ) ; } errorText . getParent ( ) . getParent ( ) . layout ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected Button createButton ( Composite parent , int id , String label , boolean defaultButton ) { Button button = super . createButton ( parent , id , label , defaultButton ) ; if ( id == IDialogConstants . OK_ID ) okButton = button ; return button ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Answer a new resource locator that identifies a particular server resource by it s URL and label . [CODESPLIT] public ILocator newLocator ( String resourceURL , String label ) { return locatorFactory . newLocator ( resourceURL , label ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define reconciler - this has to be done for each partition . Currently there are 3 partitions Inside rule outside rule and inside comment . [CODESPLIT] public IPresentationReconciler getPresentationReconciler ( ISourceViewer sourceViewer ) { PresentationReconciler reconciler = new PresentationReconciler ( ) ; //bucket partition... (everything else outside a rule) DefaultDamagerRepairer dr = new DefaultDamagerRepairer ( getScanner ( ) ) ; reconciler . setDamager ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; reconciler . setRepairer ( dr , IDocument . DEFAULT_CONTENT_TYPE ) ; //inside a rule partition dr = new DefaultDamagerRepairer ( getScanner ( ) ) ; reconciler . setDamager ( dr , DRLPartionScanner . RULE_PART_CONTENT ) ; reconciler . setRepairer ( dr , DRLPartionScanner . RULE_PART_CONTENT ) ; //finally, inside a multi line comment. dr = new DefaultDamagerRepairer ( new SingleTokenScanner ( new TextAttribute ( ColorManager . getInstance ( ) . getColor ( ColorManager . SINGLE_LINE_COMMENT ) ) ) ) ; reconciler . setDamager ( dr , DRLPartionScanner . RULE_COMMENT ) ; reconciler . setRepairer ( dr , DRLPartionScanner . RULE_COMMENT ) ; return reconciler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the appropriate content assistance for each partition . [CODESPLIT] public IContentAssistant getContentAssistant ( ISourceViewer sourceViewer ) { ContentAssistant assistant = new ContentAssistant ( ) ; //setup the content assistance, which is //sensitive to the partition that it is in. assistant . setContentAssistProcessor ( new DefaultCompletionProcessor ( editor ) , IDocument . DEFAULT_CONTENT_TYPE ) ; assistant . setContentAssistProcessor ( new RuleCompletionProcessor ( editor ) , DRLPartionScanner . RULE_PART_CONTENT ) ; assistant . setProposalPopupOrientation ( IContentAssistant . PROPOSAL_OVERLAY ) ; return assistant ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Answers whether the receiver and the argument are considered identical . To be identical the receiver and the argument must have the same status code message and extended status information . [CODESPLIT] public boolean sameAs ( Object obj ) { if ( obj == null || ! ( obj instanceof Status ) ) return false ; Status other = ( Status ) obj ; if ( other . code != code || ! other . message . equals ( message ) ) return false ; return other . extendedStatus . equals ( extendedStatus ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this Condition contain the given ConditionTerm? [CODESPLIT] public boolean contains ( ConditionTerm term ) { // iterate through the factors looking for a match boolean match = false ; Enumeration terms = getConditionTerms ( ) ; while ( ! match && terms . hasMoreElements ( ) ) { ConditionTerm t = ( ConditionTerm ) terms . nextElement ( ) ; match = term . matches ( t ) ; } return match ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Condition by parsing the given If header as defined by section 9 . 4 in the WebDAV spec . [CODESPLIT] public static Condition create ( StreamTokenizer tokenizer ) throws WebDAVException { Condition condition = new Condition ( ) ; try { int token = tokenizer . ttype ; if ( token == ' ' ) { token = tokenizer . nextToken ( ) ; if ( token == StreamTokenizer . TT_WORD ) { condition . setResourceURI ( tokenizer . sval ) ; } else { throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissingResource\" ) ) ; //$NON-NLS-1$ } token = tokenizer . nextToken ( ) ; if ( token == ' ' ) { token = tokenizer . nextToken ( ) ; } else { throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \">\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } if ( token == ' ' ) { while ( token == ' ' ) { condition . addConditionTerm ( ConditionTerm . create ( tokenizer ) ) ; token = tokenizer . ttype ; } } else { throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissingStart\" , String . valueOf ( token ) ) ) ; //$NON-NLS-1$ } } catch ( IOException exc ) { // ignore or log? } return condition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Condition by parsing the given If header as defined by section 9 . 4 in the WebDAV spec . [CODESPLIT] public static Condition create ( String ifHeader ) throws WebDAVException { StreamTokenizer tokenizer = new StreamTokenizer ( new StringReader ( ifHeader ) ) ; // URI characters tokenizer . wordChars ( ' ' , ' ' ) ; tokenizer . wordChars ( ' ' , ' ' ) ; tokenizer . ordinaryChar ( ' ' ) ; tokenizer . ordinaryChar ( ' ' ) ; tokenizer . ordinaryChar ( ' ' ) ; tokenizer . ordinaryChar ( ' ' ) ; tokenizer . ordinaryChar ( ' ' ) ; tokenizer . ordinaryChar ( ' ' ) ; tokenizer . quoteChar ( ' ' ) ; Condition condition = null ; try { int token = tokenizer . nextToken ( ) ; condition = Condition . create ( tokenizer ) ; token = tokenizer . ttype ; if ( token != StreamTokenizer . TT_EOF ) { throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \"EOF\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } catch ( IOException exc ) { // ignore or log? } return condition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a clone of the given element and adds it to this prop . The element must not be <code > null< / code > . [CODESPLIT] public void addProperty ( Element element ) throws MalformedElementException { Assert . isNotNull ( element ) ; extractNode ( root , element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new element with the given name and adds it to this prop . The name must not be <code > null< / code > and its qualifier and local name must not be <code > null< / code > and must not be the empty string . [CODESPLIT] public void addPropertyName ( QualifiedName name ) { Assert . isNotNull ( name ) ; String nsName = name . getQualifier ( ) ; Assert . isTrue ( ! \"\" . equals ( nsName ) ) ; //$NON-NLS-1$ String localName = name . getLocalName ( ) ; Assert . isNotNull ( localName ) ; Assert . isTrue ( ! localName . equals ( \"\" ) ) ; //$NON-NLS-1$ Document document = root . getOwnerDocument ( ) ; Element element = document . createElement ( localName ) ; declareNS ( element , null , nsName ) ; root . appendChild ( element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this prop s property <code > Element< / code > s . [CODESPLIT] public Enumeration getProperties ( ) throws MalformedElementException { Node firstChild = getChildElement ( root , true ) ; final Node firstElement = firstChild ; Enumeration e = new Enumeration ( ) { Node currentElement = firstElement ; public boolean hasMoreElements ( ) { return currentElement != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; Node nextElement = currentElement ; currentElement = getNextSibling ( ( Element ) currentElement ) ; return nextElement ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this prop s property <code > QualifiedName< / code > s . [CODESPLIT] public Enumeration getPropertyNames ( ) throws MalformedElementException { Node firstChild = getChildElement ( root , true ) ; final Node firstElement = firstChild ; Enumeration e = new Enumeration ( ) { Node currentElement = firstElement ; public boolean hasMoreElements ( ) { return currentElement != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; String nsName = null ; try { nsName = getNSName ( ( Element ) currentElement ) ; } catch ( MalformedElementException ex ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } String localName = getNSLocalName ( ( Element ) currentElement ) ; QualifiedNameImpl name = new QualifiedNameImpl ( nsName , localName ) ; currentElement = getNextSibling ( ( Element ) currentElement ) ; return name ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a StateToken by parsing the given If header as defined by section 9 . 4 in the WebDAV spec . [CODESPLIT] public static ConditionFactor create ( StreamTokenizer tokenizer ) throws WebDAVException { StateToken stateToken = new StateToken ( ) ; try { int token = tokenizer . ttype ; if ( token == ' ' ) token = tokenizer . nextToken ( ) ; else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \"<\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ if ( token == StreamTokenizer . TT_WORD ) { stateToken . setURI ( tokenizer . sval ) ; token = tokenizer . nextToken ( ) ; } else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissingURI\" , String . valueOf ( token ) ) ) ; //$NON-NLS-1$ if ( token == ' ' ) token = tokenizer . nextToken ( ) ; else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \">\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } catch ( IOException exc ) { // ignore or log? } return stateToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds Text Editor for rules and Rete graph viewer [CODESPLIT] protected void addPages ( ) { try { textEditor = new DRLRuleEditor ( ) { public void close ( boolean save ) { super . close ( save ) ; DRLRuleEditor2 . this . close ( save ) ; } protected void setPartName ( String partName ) { super . setPartName ( partName ) ; DRLRuleEditor2 . this . setPartName ( partName ) ; } } ; reteViewer = new ReteViewer ( textEditor ) ; int text = addPage ( textEditor , getEditorInput ( ) ) ; int rete = addPage ( reteViewer , getEditorInput ( ) ) ; setPageText ( text , \"Text Editor\" ) ; setPageText ( rete , \"Rete Tree\" ) ; textEditor . getDocumentProvider ( ) . getDocument ( getEditorInput ( ) ) . addDocumentListener ( new IDocumentListener ( ) { public void documentAboutToBeChanged ( DocumentEvent event ) { } public void documentChanged ( DocumentEvent event ) { reteViewer . fireDocumentChanged ( ) ; } } ) ; } catch ( PartInitException e ) { DroolsEclipsePlugin . log ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getAdapter ( @ SuppressWarnings ( \"rawtypes\" ) Class adapter ) { if ( adapter == ZoomManager . class ) { if ( getActiveEditor ( ) instanceof ReteViewer ) { return reteViewer . getAdapter ( adapter ) ; } else if ( getActiveEditor ( ) instanceof DRLRuleEditor ) { return null ; } } else if ( adapter == ZoomInAction2 . class ) { return zoomIn ; } else if ( adapter == ZoomOutAction2 . class ) { return zoomOut ; } else if ( adapter == ZoomComboContributionItem . class ) { return zitem ; } return textEditor . getAdapter ( adapter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send an HTTP DELETE request to the KIE console . [CODESPLIT] protected String httpDelete ( String request ) throws IOException { String host = getKieRESTUrl ( ) ; URL url = new URL ( host + \"/\" + request ) ; Activator . println ( \"[DELETE] \" + url . toString ( ) ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( \"DELETE\" ) ; conn . setRequestProperty ( \"Content\" , \"application/json\" ) ; setHttpCredentials ( conn ) ; String response = new BufferedReader ( new InputStreamReader ( ( conn . getInputStream ( ) ) ) ) . readLine ( ) ; Activator . println ( \"[DELETE] response: \" + response ) ; if ( conn . getResponseCode ( ) != HttpURLConnection . HTTP_ACCEPTED ) { throw new IOException ( \"HTTP DELETE failed : HTTP error code : \" + conn . getResponseCode ( ) ) ; } JsonObject jo = JsonObject . readFrom ( response ) ; String status = jo . get ( \"status\" ) . asString ( ) ; if ( status != null && ! status . isEmpty ( ) ) { if ( ! \"APPROVED\" . equals ( status ) ) throw new IOException ( \"HTTP DELETE failed : Request status code : \" + status ) ; } String jobId = jo . get ( \"jobId\" ) . asString ( ) ; if ( jobId != null && ! jobId . isEmpty ( ) ) return jobId ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send an HTTP POST request to the KIE console . [CODESPLIT] protected String httpPost ( String request , JsonObject body ) throws IOException , RuntimeException { String host = getKieRESTUrl ( ) ; URL url = new URL ( host + \"/\" + request ) ; Activator . println ( \"[POST] \" + url . toString ( ) + \" body: \" + body ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setDoOutput ( body != null ) ; conn . setRequestMethod ( \"POST\" ) ; conn . setRequestProperty ( \"Content-Type\" , \"application/json\" ) ; setHttpCredentials ( conn ) ; if ( body != null ) { java . io . OutputStream os = conn . getOutputStream ( ) ; Writer writer = new OutputStreamWriter ( os , \"UTF-8\" ) ; body . writeTo ( writer ) ; writer . close ( ) ; os . flush ( ) ; } String response = new BufferedReader ( new InputStreamReader ( ( conn . getInputStream ( ) ) ) ) . readLine ( ) ; Activator . println ( \"[POST] response: \" + response ) ; if ( conn . getResponseCode ( ) != HttpURLConnection . HTTP_ACCEPTED ) { throw new IOException ( \"HTTP POST failed : HTTP error code : \" + conn . getResponseCode ( ) ) ; } JsonObject jo = JsonObject . readFrom ( response ) ; String status = jo . get ( \"status\" ) . asString ( ) ; if ( status != null && ! status . isEmpty ( ) ) { if ( ! \"APPROVED\" . equals ( status ) ) throw new IOException ( \"HTTP POST failed : Request status code : \" + status ) ; } String jobId = jo . get ( \"jobId\" ) . asString ( ) ; if ( jobId != null && ! jobId . isEmpty ( ) ) return jobId ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a job status request to the KIE Server . [CODESPLIT] public String getJobStatus ( final String jobId , final String title ) throws IOException , InterruptedException { final AtomicReference < String > ar = new AtomicReference < String > ( ) ; IWorkbench wb = PlatformUI . getWorkbench ( ) ; IProgressService ps = wb . getProgressService ( ) ; try { ps . busyCursorWhile ( new IRunnableWithProgress ( ) { public void run ( IProgressMonitor pm ) throws InterruptedException { pm . beginTask ( \"Waiting for Job \" + jobId + \":\\n\\n\" + title , STATUS_REQUEST_TIMEOUT ) ; pm . subTask ( title ) ; long startTime = System . currentTimeMillis ( ) ; long stopTime = startTime ; do { try { // send a Job Status request every STATUS_REQUEST_DELAY milliseconds Thread . sleep ( STATUS_REQUEST_DELAY ) ; String response = httpGet ( \"jobs/\" + jobId ) ; JsonObject jo = JsonObject . readFrom ( response ) ; String status = jo . get ( \"status\" ) . asString ( ) ; String result = jo . get ( \"result\" ) . asString ( ) ; if ( \"null\" . equals ( result ) ) { if ( ! \"SUCCESS\" . equals ( status ) ) result = null ; } if ( status != null && result != null ) ar . set ( status + \":\" + result ) ; stopTime = System . currentTimeMillis ( ) ; pm . worked ( STATUS_REQUEST_DELAY ) ; Activator . println ( \"status=\" + status ) ; Activator . println ( \"result=\" + result ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } if ( pm . isCanceled ( ) ) throw new InterruptedException ( \"Operation canceled\" ) ; } while ( ar . get ( ) == null && stopTime - startTime < STATUS_REQUEST_TIMEOUT ) ; pm . done ( ) ; Activator . println ( \"\\n----------------------------------\\n\" + \"Job \" + jobId + \"\\n\" + title + \"\\ncompleted in \" + ( stopTime - startTime ) / 1000.0 + \" sec\\n\" + \"Status: \" + ar . get ( ) + \"\\n----------------------------------\\n\" ) ; } } ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; return null ; } return ar . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] protected void doubleClicked ( ) { super . doubleClicked ( ) ; // open custom editor pane if one exists WorkDefinition workDefinition = getWorkDefinition ( ) ; if ( workDefinition instanceof WorkDefinitionExtension ) { String editor = ( ( WorkDefinitionExtension ) workDefinition ) . getCustomEditor ( ) ; if ( editor != null ) { Work work = openEditor ( editor , workDefinition ) ; if ( work != null ) { SetWorkCommand setCommand = new SetWorkCommand ( ) ; setCommand . setPropertyValue ( work ) ; CommandStack stack = getViewer ( ) . getEditDomain ( ) . getCommandStack ( ) ; stack . execute ( setCommand ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void run ( IAction action ) { EditRepLocationWizard editWizard = new EditRepLocationWizard ( rep ) ; editWizard . init ( Activator . getDefault ( ) . getWorkbench ( ) , null ) ; WizardDialog dialog = new WizardDialog ( Display . getCurrent ( ) . getActiveShell ( ) , editWizard ) ; dialog . create ( ) ; dialog . open ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces existing zoomManager with the new one . [CODESPLIT] public void setZoomManager ( ZoomManager manager ) { if ( zoomManager != null ) { zoomManager . removeZoomListener ( this ) ; } zoomManager = manager ; if ( zoomManager != null ) { zoomManager . addZoomListener ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new WebDAV update element and sets it as the root of the given document . Returns an editor on the new element . <p > The document must not be <code > null< / code > and must not already have a root element . < / p > [CODESPLIT] public static Update createLabel ( Document document , String label ) { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getOwnerDocument ( ) == null ) ; Assert . isNotNull ( label ) ; Element element = create ( document , \"update\" ) ; //$NON-NLS-1$ try { Update editor = new Update ( element ) ; editor . setLabelName ( label ) ; return editor ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new WebDAV update element and sets it as the root of the given document . Returns an editor on the new element . <p > The document must not be <code > null< / code > and must not already have a root element . < / p > [CODESPLIT] public static Update createVersion ( Document document , String href ) { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getOwnerDocument ( ) == null ) ; Assert . isNotNull ( href ) ; Element element = create ( document , \"update\" ) ; //$NON-NLS-1$ try { Update editor = new Update ( element ) ; editor . setVersion ( href ) ; return editor ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; //  Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this response s first DAV : version child element . [CODESPLIT] public String getVersion ( ) throws MalformedElementException { Element version = getFirstChild ( root , \"version\" ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingVersionElmt\" ) , version ) ; //$NON-NLS-1$ String href = getChildText ( version , \"href\" , true ) ; //$NON-NLS-1$ ensureNotNull ( Policy . bind ( \"ensure.missingHrefElmt\" ) , href ) ; //$NON-NLS-1$ return decodeHref ( href ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the DAV : label child element . [CODESPLIT] public void setLabelName ( String label ) throws MalformedElementException { Element child = getFirstChild ( root , childNames ) ; // If there is a version child already there remove it. if ( isDAVElement ( child , \"version\" ) ) //$NON-NLS-1$ root . removeChild ( child ) ; // Add/update the label-name element. setChild ( child , \"label-name\" , label , new String [ ] { \"label-name\" } , true ) ; //$NON-NLS-1$ //$NON-NLS-2$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the DAV : version child element . [CODESPLIT] public void setVersion ( String href ) throws MalformedElementException { Element child = getFirstChild ( root , childNames ) ; // If there is a label-name child remove it. if ( isDAVElement ( child , \"label-name\" ) ) //$NON-NLS-1$ root . removeChild ( child ) ; // Add/update a version element with the href of the version target. Element newChild = setChild ( root , \"version\" , new String [ ] { \"version\" } , true ) ; //$NON-NLS-1$ //$NON-NLS-2$ setChild ( newChild , \"href\" , encodeHref ( href ) , new String [ ] { \"href\" } , true ) ; //$NON-NLS-1$ //$NON-NLS-2$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts this operation synchronously . [CODESPLIT] @ SuppressWarnings ( \"restriction\" ) public void execute ( IProgressMonitor monitor ) { try { pullOperation . execute ( monitor ) ; results . putAll ( pullOperation . getResults ( ) ) ; } catch ( CoreException e ) { if ( e . getStatus ( ) . getSeverity ( ) == IStatus . CANCEL ) results . putAll ( pullOperation . getResults ( ) ) ; else repoNode . handleException ( ( Throwable ) e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Post - process the pull results allowing the user to deal with uncommitted changes and re - pull if the initial pull failed because of these changes [CODESPLIT] private void handlePullResults ( final Map < Repository , Object > resultsMap ) { if ( tasksToWaitFor . decrementAndGet ( ) == 0 && ! results . isEmpty ( ) ) showResults ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the element at the specified position in this array with the JSON representation of the specified string . [CODESPLIT] public JsonArray set ( int index , String value ) { values . set ( index , valueOf ( value ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and adds a new activelock on this lockdiscovery and returns an editor on it . [CODESPLIT] public ActiveLock addActiveLock ( ) { Element activelock = addChild ( root , \"activelock\" , childNames , false ) ; //$NON-NLS-1$ Element locktype = appendChild ( activelock , \"locktype\" ) ; //$NON-NLS-1$ appendChild ( locktype , \"write\" ) ; //$NON-NLS-1$ ActiveLock result = null ; try { result = new ActiveLock ( activelock ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this lockdiscovery s <code > ActiveLock< / code > s . [CODESPLIT] public Enumeration getActiveLocks ( ) throws MalformedElementException { final Node firstActiveLock = getFirstChild ( root , \"activelock\" ) ; //$NON-NLS-1$ Enumeration e = new Enumeration ( ) { Node currentActiveLock = firstActiveLock ; public boolean hasMoreElements ( ) { return currentActiveLock != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; ActiveLock result = null ; try { result = new ActiveLock ( ( Element ) currentActiveLock ) ; } catch ( MalformedElementException ex ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ } currentActiveLock = getTwin ( ( Element ) currentActiveLock , true ) ; return result ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter out the proposals whose content does not start with the given prefix . [CODESPLIT] protected static void filterProposalsOnPrefix ( String prefix , List < ICompletionProposal > props ) { if ( prefix != null && prefix . trim ( ) . length ( ) > 0 ) { Iterator < ICompletionProposal > iterator = props . iterator ( ) ; String prefixLc = prefix . toLowerCase ( ) ; while ( iterator . hasNext ( ) ) { ICompletionProposal item = iterator . next ( ) ; String content = item . getDisplayString ( ) . toLowerCase ( ) ; if ( ! content . toLowerCase ( ) . startsWith ( prefixLc ) ) { iterator . remove ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read some text from behind the cursor position . This provides context to both filter what is shown based on what the user has typed in and also to provide more information for the list of suggestions based on context . [CODESPLIT] protected String readBackwards ( int documentOffset , IDocument doc ) throws BadLocationException { int startPart = doc . getPartition ( documentOffset ) . getOffset ( ) ; String prefix = doc . get ( startPart , documentOffset - startPart ) ; return prefix ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates layouting for provided graph . [CODESPLIT] public static RowList calculateReteRows ( BaseVertex root ) { RowList rowList = new RowList ( ) ; rowList . add ( 0 , root ) ; int curRow = 0 ; final Set < BaseVertex > seenVertices = new HashSet < BaseVertex > ( ) ; seenVertices . add ( root ) ; while ( curRow < rowList . getDepth ( ) ) { final List < BaseVertex > rowVertices = rowList . get ( curRow ) . getVertices ( ) ; for ( final Iterator < BaseVertex > rowNodeIter = rowVertices . iterator ( ) ; rowNodeIter . hasNext ( ) ; ) { final BaseVertex rowNode = rowNodeIter . next ( ) ; final List < Connection > edges = rowNode . getSourceConnections ( ) ; for ( final Iterator < Connection > edgeIter = edges . iterator ( ) ; edgeIter . hasNext ( ) ; ) { final Connection edge = edgeIter . next ( ) ; final BaseVertex destNode = edge . getOpposite ( rowNode ) ; if ( ! seenVertices . contains ( destNode ) ) { rowList . add ( curRow + 1 , destNode ) ; seenVertices . add ( destNode ) ; } } seenVertices . add ( rowNode ) ; } ++ curRow ; } rowList . optimize ( ) ; return rowList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Painting antialiased vertex [CODESPLIT] public void paint ( Graphics g ) { g . setAntialias ( SWT . ON ) ; Rectangle r = getBounds ( ) . getCopy ( ) ; g . translate ( r . getLocation ( ) ) ; g . setBackgroundColor ( backgroundColor ) ; g . setForegroundColor ( borderColor ) ; g . fillArc ( 0 , 0 , 15 , 15 , 0 , 360 ) ; g . drawArc ( 0 , 0 , 14 , 14 , 0 , 360 ) ; super . paint ( g ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EditPart createEditPart ( EditPart context , Object modelElement ) { // get EditPart for model element EditPart part = getPartForElement ( modelElement ) ; // store model element in EditPart part . setModel ( modelElement ) ; return part ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps object to EditPart . [CODESPLIT] private EditPart getPartForElement ( Object modelElement ) { if ( modelElement instanceof ReteGraph ) { return new DiagramEditPart ( ) ; } if ( modelElement instanceof BaseVertex ) { return new VertexEditPart ( ) ; } if ( modelElement instanceof Connection ) { return new ConnectionEditPart ( ) ; } DroolsEclipsePlugin . log ( new Exception ( \"Can't create part for model element: \" + ( ( modelElement != null ) ? modelElement . getClass ( ) . getName ( ) : \"null\" ) ) ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an image descriptor for the image file at the given plug - in relative path . Uses the plug ins image registry to cache it . [CODESPLIT] public static ImageDescriptor getImageDescriptor ( String path ) { JBPMEclipsePlugin plugin = getDefault ( ) ; ImageRegistry reg = plugin . getImageRegistry ( ) ; ImageDescriptor des = reg . getDescriptor ( path ) ; if ( des == null ) { des = AbstractUIPlugin . imageDescriptorFromPlugin ( \"org.jbpm.eclipse\" , path ) ; reg . put ( path , des ) ; } return des ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declare an Image in the registry table . [CODESPLIT] public final static void declareRegistryImage ( String key , String path ) { ImageDescriptor desc = ImageDescriptor . getMissingImageDescriptor ( ) ; try { desc = ImageDescriptor . createFromURL ( makeIconFileURL ( path ) ) ; } catch ( MalformedURLException e ) { DroolsEclipsePlugin . log ( e ) ; } imageRegistry . put ( key , desc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Digest authorization credentials for the given directives . The credentials have the following form : <code > credentials = Digest digest - response digest - response = 1# ( username | realm | nonce | digest - uri | response | [ algorithm ] | [ cnonce ] | [ opaque ] | [ message - qop ] | [ nonce - count ] | [ auth - param ] ) username = username = username - value username - value = quoted - string realm = realm = realm - value realm - value = quoted - string nonce = nonce = nonce - value nonce - value = quoted - string digest - uri = uri = digest - uri - value digest - uri - value = request - uri ; As specified by HTTP / 1 . 1 response = response = request - digest request - digest = &lt ; &gt ; 32LHEX &lt ; &gt ; LHEX = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f algorithm = algorithm = ( MD5 | MD5 - sess | token ) cnonce = cnonce = cnonce - value cnonce - value = nonce - value opaque = opaque = quoted - string message - qop = qop = qop - value nonce - count = nc = nc - value nc - value = 8LHEX < / code > <P > If the qop value is auth or auth - int : <code > request - digest = &lt ; &gt ; &lt ; KD ( H ( A1 ) unq ( nonce - value ) : nc - value : unq ( cnonce - value ) : unq ( qop - value ) : H ( A2 ) ) &lt ; &gt ; KD ( secret data ) = H ( concat ( secret : data )) H ( data ) = MD5 ( data ) unq ( data ) = unqouted ( data ) < / code > <P > If the qop directive is not present : <code > request - digest = &lt ; &gt ; &lt ; KD ( H ( A1 ) unq ( nonce - value ) : H ( A2 ) ) &lt ; &gt ; < / code > <P > If the algorithm directive s value is MD5 or is unspecified then A1 is : <code > A1 = unq ( username - value ) : unq ( realm - value ) : passwd passwd = &lt ; user s password &gt ; < / code > <P > If the algorithm directive s value is MD5 - sess then A1 is : <code > A1 = H ( unq ( username - value ) : unq ( realm - value ) : passwd ) : unq ( nonce - value ) : unq ( cnonce - value ) < / code > <P > If the qop directive s value is auth or is unspecified then A2 is : <code > A2 = Method : digest - uri - value < / code > <P > If the qop value is auth - int then A2 is : <code > A2 = Method : digest - uri - value : H ( entity - body ) < / code > [CODESPLIT] private String credentials ( Request request , String realm , String username , String password , String algorithm , String messageQop , String nonce , String nonceCount , String opaque , String cnonce , String method , String digestUri ) throws Exception { Assert . isNotNull ( request ) ; Assert . isNotNull ( realm ) ; Assert . isNotNull ( username ) ; Assert . isNotNull ( password ) ; Assert . isNotNull ( nonce ) ; Assert . isNotNull ( method ) ; Assert . isNotNull ( digestUri ) ; StringBuffer buf = new StringBuffer ( ) ; buf . append ( \"Digest username=\\\"\" ) ; //$NON-NLS-1$ buf . append ( username ) ; buf . append ( \"\\\"\" ) ; //$NON-NLS-1$ buf . append ( \", realm=\" ) ; //$NON-NLS-1$ buf . append ( realm ) ; if ( messageQop != null ) { buf . append ( \", qop=\\\"\" ) ; //$NON-NLS-1$ buf . append ( messageQop ) ; buf . append ( \"\\\"\" ) ; //$NON-NLS-1$ } if ( algorithm != null ) { buf . append ( \", algorithm=\" ) ; //$NON-NLS-1$ buf . append ( algorithm ) ; } buf . append ( \", uri=\\\"\" ) ; //$NON-NLS-1$ buf . append ( digestUri ) ; buf . append ( \"\\\"\" ) ; //$NON-NLS-1$ buf . append ( \", nonce=\" ) ; //$NON-NLS-1$ buf . append ( nonce ) ; if ( nonceCount != null ) { buf . append ( \", nc=\" ) ; //$NON-NLS-1$ buf . append ( nonceCount ) ; } if ( cnonce != null ) { buf . append ( \", cnonce=\\\"\" ) ; //$NON-NLS-1$ buf . append ( cnonce ) ; buf . append ( \"\\\"\" ) ; //$NON-NLS-1$ } if ( opaque != null ) { buf . append ( \", opaque=\" ) ; //$NON-NLS-1$ buf . append ( opaque ) ; } String response = response ( request , realm , username , password , algorithm , messageQop , nonce , nonceCount , cnonce , method , digestUri ) ; if ( response == null ) { return null ; } buf . append ( \", response=\\\"\" ) ; //$NON-NLS-1$ buf . append ( response ) ; buf . append ( \"\\\"\" ) ; //$NON-NLS-1$ return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds new vertex to specified depth [CODESPLIT] public void add ( final int depth , final BaseVertex vertex ) { if ( this . rows . size ( ) < ( depth + 1 ) ) { final int addRows = depth - this . rows . size ( ) + 1 ; for ( int i = 0 ; i < addRows ; ++ i ) { this . rows . add ( new Row ( ( depth - addRows ) + i ) ) ; } } ( ( Row ) this . rows . get ( depth ) ) . add ( vertex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds specified vertex from the rows . [CODESPLIT] public int getRow ( final BaseVertex vertex ) { final int numRows = this . rows . size ( ) ; for ( int i = 0 ; i < numRows ; ++ i ) { if ( ( ( Row ) this . rows . get ( i ) ) . contains ( vertex ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the longest row width . [CODESPLIT] public int getWidth ( ) { int width = 0 ; for ( final Iterator < Row > rowIter = this . rows . iterator ( ) ; rowIter . hasNext ( ) ; ) { final Row row = rowIter . next ( ) ; final int rowWidth = row . getWidth ( ) ; if ( rowWidth > width ) { width = rowWidth ; } } return width ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dumps all row vertices to System . err [CODESPLIT] public void dump ( ) { final int numRows = this . rows . size ( ) ; for ( int i = 0 ; i < numRows ; ++ i ) { System . err . println ( i + \": \" + get ( i ) . getVertices ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Optimizes all rows for optimal presentation [CODESPLIT] public void optimize ( ) { final int numRows = this . rows . size ( ) ; for ( int i = 0 ; i < numRows ; ++ i ) { get ( i ) . optimize ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Search the Native way to find the SourceField IFile [CODESPLIT] private IFile getSourceFieldIFile ( ) { Field fReferences ; try { fReferences = processor . getClass ( ) . getDeclaredField ( \"fReferences\" ) ; fReferences . setAccessible ( true ) ; SearchResultGroup object [ ] = ( SearchResultGroup [ ] ) fReferences . get ( processor ) ; for ( SearchResultGroup searchResultGroup : object ) { if ( searchResultGroup . getResource ( ) instanceof IFile ) return ( IFile ) searchResultGroup . getResource ( ) ; } } catch ( SecurityException e ) { return null ; } catch ( NoSuchFieldException e ) { return null ; } catch ( IllegalArgumentException e ) { return null ; } catch ( IllegalAccessException e ) { return null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] protected void configureGraphicalViewer ( ) { super . configureGraphicalViewer ( ) ; GraphicalViewer viewer = getGraphicalViewer ( ) ; viewer . getControl ( ) . setBackground ( ColorConstants . white ) ; viewer . setEditPartFactory ( new VertexEditPartFactory ( ) ) ; viewer . setRootEditPart ( rootEditPart ) ; viewer . setKeyHandler ( new GraphicalViewerKeyHandler ( viewer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getAdapter ( @ SuppressWarnings ( \"rawtypes\" ) Class type ) { if ( type == ZoomManager . class ) return ( ( ScalableFreeformRootEditPart ) getGraphicalViewer ( ) . getRootEditPart ( ) ) . getZoomManager ( ) ; if ( type == GraphicalViewer . class ) return getGraphicalViewer ( ) ; if ( type == EditPart . class && getGraphicalViewer ( ) != null ) return getGraphicalViewer ( ) . getRootEditPart ( ) ; if ( type == IFigure . class && getGraphicalViewer ( ) != null ) return ( ( GraphicalEditPart ) getGraphicalViewer ( ) . getRootEditPart ( ) ) . getFigure ( ) ; return super . getAdapter ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads model from rule base calculates rete view and initializes diagram model . [CODESPLIT] public ReteGraph loadReteModel ( IProgressMonitor monitor , String contents ) throws Throwable { if ( relayoutRequired == false ) { return diagram ; } ReteGraph newDiagram = new ReteGraph ( ) ; try { monitor . beginTask ( \"Loading RETE Tree\" , 100 ) ; monitor . subTask ( \"Loading Rule Base\" ) ; InternalKnowledgeBase ruleBase = null ; try { IResource resource = drlEditor . getResource ( ) ; ClassLoader newLoader = DroolsBuilder . class . getClassLoader ( ) ; if ( resource . getProject ( ) . getNature ( \"org.eclipse.jdt.core.javanature\" ) != null ) { IJavaProject project = JavaCore . create ( resource . getProject ( ) ) ; newLoader = ProjectClassLoader . getProjectClassLoader ( project ) ; } DRLInfo drlInfo = DroolsEclipsePlugin . getDefault ( ) . parseResource ( drlEditor , true , true ) ; if ( drlInfo == null ) { throw new Exception ( \"Could not find DRL info\" ) ; } if ( drlInfo . getBuilderErrors ( ) . length > 0 ) { throw new Exception ( drlInfo . getBuilderErrors ( ) . length + \" build errors\" ) ; } if ( drlInfo . getParserErrors ( ) . size ( ) > 0 ) { throw new Exception ( drlInfo . getParserErrors ( ) . size ( ) + \" parser errors\" ) ; } InternalKnowledgePackage pkg = drlInfo . getPackage ( ) ; RuleBaseConfiguration config = new RuleBaseConfiguration ( ) ; config . setClassLoader ( newLoader ) ; ruleBase = KnowledgeBaseFactory . newKnowledgeBase ( config ) ; if ( pkg != null ) { ruleBase . addPackage ( pkg ) ; } } catch ( Throwable t ) { DroolsEclipsePlugin . log ( t ) ; throw new Exception ( MSG_PARSE_ERROR + \" \" + t . getMessage ( ) ) ; } monitor . worked ( 50 ) ; if ( monitor . isCanceled ( ) ) { throw new InterruptedException ( ) ; } monitor . subTask ( \"Building RETE Tree\" ) ; final ReteooVisitor visitor = new ReteooVisitor ( newDiagram ) ; visitor . visitInternalKnowledgeBase ( ruleBase ) ; monitor . worked ( 30 ) ; if ( monitor . isCanceled ( ) ) { throw new InterruptedException ( ) ; } monitor . subTask ( \"Calculating RETE Tree Layout\" ) ; BaseVertex rootVertex = visitor . getRootVertex ( ) ; RowList rowList = ReteooLayoutFactory . calculateReteRows ( rootVertex ) ; ReteooLayoutFactory . layoutRowList ( newDiagram , rowList ) ; zeroBaseDiagram ( newDiagram ) ; monitor . worked ( 20 ) ; if ( monitor . isCanceled ( ) ) { throw new InterruptedException ( ) ; } monitor . done ( ) ; } catch ( Throwable t ) { if ( ! ( t instanceof InterruptedException ) ) { DroolsEclipsePlugin . log ( t ) ; } throw t ; } relayoutRequired = false ; return newDiagram ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads Rete model and initializes zoom manager . [CODESPLIT] protected void initializeGraphicalViewer ( ) { ZoomManager zoomManager = rootEditPart . getZoomManager ( ) ; //List<String> List < String > zoomLevels = new ArrayList < String > ( 3 ) ; zoomLevels . add ( ZoomManager . FIT_ALL ) ; zoomLevels . add ( ZoomManager . FIT_HEIGHT ) ; zoomLevels . add ( ZoomManager . FIT_WIDTH ) ; zoomManager . setZoomLevelContributions ( zoomLevels ) ; // Zoom mousewheel - Ctrl+Mousewheel for zoom in/out getGraphicalViewer ( ) . setProperty ( MouseWheelHandler . KeyGenerator . getKey ( SWT . MOD1 ) , MouseWheelZoomHandler . SINGLETON ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves all <code > diagram< / code > nodes to upper left corner and shifting to right if neccessary to get rid of negative XY coordinates . [CODESPLIT] private void zeroBaseDiagram ( ReteGraph graph ) { Dimension dim = rootEditPart . getContentPane ( ) . getSize ( ) ; int minx = 0 , miny = 0 , maxx = 0 , x = dim . width ; final Iterator < BaseVertex > nodeIter = graph . getChildren ( ) . iterator ( ) ; while ( nodeIter . hasNext ( ) ) { Point loc = nodeIter . next ( ) . getLocation ( ) ; minx = Math . min ( loc . x , minx ) ; maxx = Math . max ( loc . x , maxx ) ; miny = Math . min ( loc . y , miny ) ; } int delta = ( x - ( maxx - minx + 20 ) ) / 2 ; minx = minx - ( delta ) ; final Iterator < BaseVertex > nodeIter2 = graph . getChildren ( ) . iterator ( ) ; while ( nodeIter2 . hasNext ( ) ) { final BaseVertex vertex = nodeIter2 . next ( ) ; Point loc = vertex . getLocation ( ) ; vertex . setLocation ( new Point ( loc . x - minx , loc . y - miny ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws graph . [CODESPLIT] public void drawGraph ( ReteGraph newGraph ) { LayerManager manager = ( LayerManager ) getGraphicalViewer ( ) . getEditPartRegistry ( ) . get ( LayerManager . ID ) ; ConnectionLayer connLayer = ( ConnectionLayer ) manager . getLayer ( LayerConstants . CONNECTION_LAYER ) ; // Lazy-init model initialization if ( getGraphicalViewer ( ) . getContents ( ) == null ) { getGraphicalViewer ( ) . setContents ( getModel ( ) ) ; } final boolean isNewDiagram = newGraph != null && newGraph != diagram ; if ( isNewDiagram ) { diagram . removeAll ( ) ; } // Update connection router according to new model size ConnectionRouter router ; if ( ( isNewDiagram && newGraph . getChildren ( ) . size ( ) < SIMPLE_ROUTER_MIN_NODES ) || ( ! isNewDiagram && getModel ( ) . getChildren ( ) . size ( ) < SIMPLE_ROUTER_MIN_NODES ) ) { router = new ShortestPathConnectionRouter ( ( IFigure ) rootEditPart . getContentPane ( ) . getChildren ( ) . get ( 0 ) ) ; } else { router = ConnectionRouter . NULL ; } connLayer . setConnectionRouter ( router ) ; if ( newGraph != null && newGraph != diagram ) { diagram . addAll ( newGraph . getChildren ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to find a match for the provided breakpoint information from the list of registered breakpoints . For stepping and possibly other purposes it returns also a breakpoint for cases where exactly the same line was not found . [CODESPLIT] public DroolsLineBreakpoint getDroolsBreakpoint ( String source ) { if ( source == null ) { return null ; } Iterator < IBreakpoint > iterator = getBreakpoints ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { IJavaBreakpoint element = ( IJavaBreakpoint ) iterator . next ( ) ; if ( element instanceof DroolsLineBreakpoint && ( ( DroolsLineBreakpoint ) element ) . getDialectName ( ) . equals ( \"mvel\" ) ) { DroolsLineBreakpoint l = ( DroolsLineBreakpoint ) element ; try { int matchLine = l . getLineNumber ( ) ; String matchSource = l . getRuleName ( ) ; if ( source . equals ( matchSource ) || l . getFileRuleMappings ( ) . containsKey ( source ) ) { return l ; } } catch ( CoreException e ) { logError ( e ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void run ( IAction action ) { if ( selectedNode == null ) { return ; } IWorkbenchBrowserSupport browserSupport = Activator . getDefault ( ) . getWorkbench ( ) . getBrowserSupport ( ) ; try { URL consoleURL = new URL ( extractGuvnorConsoleUrl ( selectedNode . getGuvnorRepository ( ) . getLocation ( ) ) ) ; if ( browserSupport . isInternalWebBrowserAvailable ( ) ) { browserSupport . createBrowser ( null ) . openURL ( consoleURL ) ; } else { browserSupport . getExternalBrowser ( ) . openURL ( consoleURL ) ; } } catch ( Exception e ) { Activator . getDefault ( ) . displayError ( IStatus . ERROR , e . getMessage ( ) , e , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void selectionChanged ( IAction action , ISelection selection ) { action . setEnabled ( false ) ; if ( ! ( selection instanceof IStructuredSelection ) ) { return ; } IStructuredSelection sel = ( IStructuredSelection ) selection ; if ( sel . size ( ) != 1 ) { return ; } if ( sel . getFirstElement ( ) instanceof TreeObject ) { if ( ( ( TreeObject ) sel . getFirstElement ( ) ) . getNodeType ( ) == TreeObject . Type . REPOSITORY ) { selectedNode = ( TreeObject ) sel . getFirstElement ( ) ; action . setEnabled ( true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pass in a NLMapping item for display / edits . Changes will be applied to this object only if the user clicks OK . [CODESPLIT] public void setNLMappingItem ( DSLMappingEntry item ) { model = item ; setSection ( model . getSection ( ) ) ; exprText . setText ( model . getMappingKey ( ) == null ? \"\" : model . getMappingKey ( ) ) ; mappingText . setText ( model . getMappingValue ( ) == null ? \"\" : model . getMappingValue ( ) ) ; objText . setText ( model . getMetaData ( ) . getMetaData ( ) == null ? \"\" : model . getMetaData ( ) . getMetaData ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets this baseline control elment description to the given href . [CODESPLIT] public void setHref ( String href ) { Assert . isNotNull ( href ) ; setChild ( root , \"href\" , encodeHref ( href ) , childNames , true ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a boolean value indicating whether or not the server for this resource is DAV compliant . [CODESPLIT] public boolean canTalkDAV ( ) throws DAVException { IResponse response = null ; try { // Send an options request. response = davClient . options ( locator , newContext ( ) ) ; examineResponse ( response ) ; // Check for at least DAV level 1. String davHeader = response . getContext ( ) . getDAV ( ) ; return ! ( ( davHeader == null ) || ( davHeader . indexOf ( \"1\" ) == - 1 ) ) ; //$NON-NLS-1$ } catch ( IOException exception ) { throw new SystemException ( exception ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to close a response from the server . <p > Note that the argument MAY be <code > null< / code > in which case the call has no effect . < / p > [CODESPLIT] protected void closeResponse ( IResponse response ) throws SystemException { if ( response == null ) return ; try { response . close ( ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a copy of this resource and place it at the location defined by the given locator . <p > Uses default values of depth : infinity and overwrite : false for the copy . < / p > [CODESPLIT] public void copy ( ILocator destination ) throws DAVException { copy ( destination , IContext . DEPTH_INFINITY , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a copy of this resource and place it at the location specified by the given destination locator . [CODESPLIT] public void copy ( ILocator destination , String depth , boolean overwrite , Collection propertyNames ) throws DAVException { // Define the request context. IContext context = newContext ( ) ; context . setDepth ( depth ) ; context . setOverwrite ( overwrite ) ; // Set up the request body to specify which properties should be kept alive. Document document = newDocument ( ) ; PropertyBehavior propertyBehavior = PropertyBehavior . create ( document ) ; if ( propertyNames == null ) propertyBehavior . setIsKeepAllAlive ( true ) ; else { Iterator namesItr = propertyNames . iterator ( ) ; while ( namesItr . hasNext ( ) ) { QualifiedName name = ( QualifiedName ) namesItr . next ( ) ; String nameURI = name . getQualifier ( ) + \"/\" + name . getLocalName ( ) ; //$NON-NLS-1$ propertyBehavior . addProperty ( nameURI ) ; } // end-while } // end-if // Call the server to perform the copy. IResponse response = null ; try { response = davClient . copy ( locator , destination , context , document ) ; examineResponse ( response ) ; examineMultiStatusResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given response contains a multistatus body the bodies status are checked for errors . If an error is found an exception is thrown . [CODESPLIT] protected void examineMultiStatusResponse ( IResponse response ) throws DAVException { // If it is not a multistatus we don't look at it. if ( response . getStatusCode ( ) != IResponse . SC_MULTI_STATUS ) return ; // It is declared a multistatus, so if there is no response body // then that is a problem. if ( ! response . hasDocumentBody ( ) ) throw new DAVException ( Policy . bind ( \"exception.responseMustHaveDocBody\" ) ) ; //$NON-NLS-1$ // Extract the XML document from the response. Element documentElement ; try { documentElement = response . getDocumentBody ( ) . getDocumentElement ( ) ; if ( documentElement == null ) throw new DAVException ( Policy . bind ( \"exception.invalidDoc\" ) ) ; //$NON-NLS-1$ } catch ( IOException exception ) { throw new SystemException ( exception ) ; } // Enumerate all the responses in the multistat and check that // they are indicating success (i.e. are 200-series response codes). try { MultiStatus multistatus = new MultiStatus ( documentElement ) ; Enumeration responseEnum = multistatus . getResponses ( ) ; while ( responseEnum . hasMoreElements ( ) ) { ResponseBody responseBody = ( ResponseBody ) responseEnum . nextElement ( ) ; Enumeration propstatEnum = responseBody . getPropStats ( ) ; while ( propstatEnum . hasMoreElements ( ) ) { PropStat propstat = ( PropStat ) propstatEnum . nextElement ( ) ; examineStatusCode ( propstat . getStatusCode ( ) , propstat . getResponseDescription ( ) ) ; } // end-while } // end-while } catch ( MalformedElementException e ) { throw new SystemException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to extract the property status response from a multi status reponse and populate a URLTable with the results . [CODESPLIT] protected URLTable extractPropStats ( MultiStatus multiStatus ) throws IOException , MalformedElementException { // Construct a URLTable to return to the user. URLTable reply = new URLTable ( ) ; // For each response (resource). Enumeration responses = multiStatus . getResponses ( ) ; while ( responses . hasMoreElements ( ) ) { ResponseBody responseBody = ( ResponseBody ) responses . nextElement ( ) ; String href = responseBody . getHref ( ) ; // The href may be relative to the request URL. URL resourceURL = new URL ( new URL ( locator . getResourceURL ( ) ) , href ) ; Hashtable properties = new Hashtable ( ) ; reply . put ( resourceURL , properties ) ; // For each property status grouping. Enumeration propstats = responseBody . getPropStats ( ) ; while ( propstats . hasMoreElements ( ) ) { PropStat propstat = ( PropStat ) propstats . nextElement ( ) ; org . eclipse . webdav . dom . Status status = new org . eclipse . webdav . dom . Status ( propstat . getStatus ( ) ) ; // For each property with this status. Enumeration elements = propstat . getProp ( ) . getProperties ( ) ; while ( elements . hasMoreElements ( ) ) { Element element = ( Element ) elements . nextElement ( ) ; QualifiedName name = ElementEditor . getQualifiedName ( element ) ; // Add a property status object to the result set. PropertyStatus propertyStatus = new PropertyStatus ( element , status . getStatusCode ( ) , status . getStatusMessage ( ) ) ; properties . put ( name , propertyStatus ) ; } // end-while } // end-while } // end-while return reply ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the content of this resource as an input stream . The input stream should be closed by the user . [CODESPLIT] public ResponseInputStream getContent ( ) throws DAVException { IResponse response = null ; try { response = davClient . get ( locator , newContext ( ) ) ; examineResponse ( response ) ; } catch ( IOException e ) { closeResponse ( response ) ; throw new SystemException ( e ) ; } return new ResponseInputStream ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an Enumeration over ActiveLocks which lists the locks currently held on this resource . Return an empty enumeration if the lock discovery property is not found on the resource . [CODESPLIT] public Enumeration getLocks ( ) throws DAVException { LockDiscovery lockdiscovery = null ; try { Element element = getProperty ( DAV_LOCK_DISCOVERY ) . getProperty ( ) ; lockdiscovery = new LockDiscovery ( element ) ; return lockdiscovery . getActiveLocks ( ) ; } catch ( WebDAVException exception ) { if ( exception . getStatusCode ( ) == IResponse . SC_NOT_FOUND ) return new EmptyEnumeration ( ) ; throw exception ; } catch ( MalformedElementException elemException ) { throw new SystemException ( elemException ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection handle for the parent of this resource . <p > Note that this method does NOT perform a method call to the server to ensure that the collection exists . < / p > <p > Returns <code > null< / code > if this resource is the root . [CODESPLIT] public CollectionHandle getParent ( ) throws DAVException { Assert . isTrue ( locator . getLabel ( ) == null ) ; Assert . isTrue ( ! locator . isStable ( ) ) ; try { URL url = URLTool . getParent ( locator . getResourceURL ( ) ) ; if ( url == null ) return null ; String parentName = url . toString ( ) ; ILocator parentLocator = davClient . getDAVFactory ( ) . newLocator ( parentName ) ; return new CollectionHandle ( davClient , parentLocator ) ; } catch ( MalformedURLException e ) { throw new SystemException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches and returns the specified properties for this resource and its children to the given depth . The returned table is a URLTable of hashtables . The keys in the first table are the <code > URL< / code > s of the resources . The nested table is a table where the keys are the names ( <code > QualifiedName< / code > ) of the properties and the values are the properties values ( <code > PropertyStatus< / code > ) . [CODESPLIT] public URLTable getProperties ( Collection propertyNames , String depth ) throws DAVException { // Set up the request context. IContext context = newContext ( ) ; context . setDepth ( depth ) ; // Set up the request body. Document document = newDocument ( ) ; PropFind propfind = PropFind . create ( document ) ; // null is a special value meaning 'all properties'. if ( propertyNames == null ) propfind . setIsAllProp ( true ) ; else { // Add all the property names to the request body. Prop prop = propfind . setProp ( ) ; Iterator namesItr = propertyNames . iterator ( ) ; while ( namesItr . hasNext ( ) ) prop . addPropertyName ( ( QualifiedName ) namesItr . next ( ) ) ; } // Were ready to make the server call. IResponse response = null ; try { // This contacts the server. response = davClient . propfind ( locator , context , document ) ; examineResponse ( response ) ; // Create a multi-status element editor on the response. if ( ! response . hasDocumentBody ( ) ) throw new DAVException ( Policy . bind ( \"exception.respMustShareXMLDoc\" ) ) ; //$NON-NLS-1$ Element documentElement = response . getDocumentBody ( ) . getDocumentElement ( ) ; if ( documentElement == null ) throw new DAVException ( Policy . bind ( \"exception.respHasInvalidDoc\" ) ) ; //$NON-NLS-1$ MultiStatus multiStatus = new MultiStatus ( documentElement ) ; // Construct a URLTable of results to return to the user. return extractPropStats ( multiStatus ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } catch ( MalformedElementException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the property status for the property with the given name . [CODESPLIT] public PropertyStatus getProperty ( QualifiedName propertyName ) throws DAVException { Collection names = new HashSet ( ) ; names . add ( propertyName ) ; URLTable result = getProperties ( names , IContext . DEPTH_ZERO ) ; URL url = null ; try { url = new URL ( locator . getResourceURL ( ) ) ; } catch ( MalformedURLException e ) { throw new SystemException ( e ) ; } Hashtable propTable = ( Hashtable ) result . get ( url ) ; if ( propTable == null ) throw new DAVException ( Policy . bind ( \"exception.lookup\" , url . toExternalForm ( ) ) ) ; //$NON-NLS-1$ return ( PropertyStatus ) propTable . get ( propertyName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch and return the property names for the resource and the children resources to the specified depth . Returns <code > URLTable< / code > mapping resource URLs to enumerations over the property names for that resource . [CODESPLIT] public URLTable getPropertyNames ( String depth ) throws DAVException { // create and send the request IContext context = newContext ( ) ; context . setDepth ( depth ) ; IResponse response = null ; try { Document document = newDocument ( ) ; PropFind propfind = PropFind . create ( document ) ; propfind . setIsPropName ( true ) ; response = davClient . propfind ( locator , context , document ) ; examineResponse ( response ) ; if ( ! response . hasDocumentBody ( ) ) { throw new DAVException ( Policy . bind ( \"exception.respMustHaveElmtBody\" ) ) ; //$NON-NLS-1$ } Element documentElement = response . getDocumentBody ( ) . getDocumentElement ( ) ; if ( documentElement == null ) { throw new DAVException ( Policy . bind ( \"exception.bodyMustHaveElmt\" ) ) ; //$NON-NLS-1$ } MultiStatus multistatus = new MultiStatus ( documentElement ) ; //construct the URLTable to return to the user URLTable reply = new URLTable ( 10 ) ; Enumeration responses = multistatus . getResponses ( ) ; while ( responses . hasMoreElements ( ) ) { ResponseBody responseBody = ( ResponseBody ) responses . nextElement ( ) ; String href = responseBody . getHref ( ) ; URL resourceUrl = new URL ( new URL ( locator . getResourceURL ( ) ) , href ) ; Enumeration propstats = responseBody . getPropStats ( ) ; Vector vector = new Vector ( ) ; while ( propstats . hasMoreElements ( ) ) { PropStat propstat = ( PropStat ) propstats . nextElement ( ) ; Prop prop = propstat . getProp ( ) ; Enumeration names = prop . getPropertyNames ( ) ; while ( names . hasMoreElements ( ) ) { QualifiedName dname = ( QualifiedName ) names . nextElement ( ) ; vector . addElement ( dname ) ; } } reply . put ( resourceUrl , vector . elements ( ) ) ; } return reply ; } catch ( IOException e ) { throw new SystemException ( e ) ; } catch ( MalformedElementException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the version tree infomration for the receiver assuming that the receiver is a version or a version - controlled resource . <p > The version tree info comprises a <code > URLTable< / code > whose keys are the <code > URL< / code > s of each version in the version history and whose values are <code > Vector< / code > s of the resource s immediate predecessor <code > URL< / code > s . Note that the root version is ( uniquely ) identified by an empty set of predecessors . < / p > [CODESPLIT] public URLTable getVersionTree ( ) throws DAVException { // Issue a version tree report against the receiver to retrieve // the successor set of all the versions. Document document = newDocument ( ) ; Element root = ElementEditor . create ( document , \"version-tree\" ) ; //$NON-NLS-1$ Element propElement = ElementEditor . appendChild ( root , \"prop\" ) ; //$NON-NLS-1$ ElementEditor . appendChild ( propElement , \"predecessor-set\" ) ; //$NON-NLS-1$ IResponse response = null ; try { // Run the REPORT and check for errors. response = davClient . report ( locator , newContext ( ) , document ) ; examineResponse ( response ) ; if ( ! response . hasDocumentBody ( ) ) throw new DAVException ( Policy . bind ( \"exception.respMustHaveElmtBody\" ) ) ; //$NON-NLS-1$ // Get the body as a MultiStatus. Element documentElement = response . getDocumentBody ( ) . getDocumentElement ( ) ; if ( documentElement == null ) throw new DAVException ( Policy . bind ( \"exception.bodyMustHaveElmt\" ) ) ; //$NON-NLS-1$ MultiStatus multistatus = new MultiStatus ( documentElement ) ; // Construct the predecessor table. // This will contain the result. URLTable predecessorTable = new URLTable ( ) ; // For each response. Enumeration responses = multistatus . getResponses ( ) ; while ( responses . hasMoreElements ( ) ) { ResponseBody responseBody = ( ResponseBody ) responses . nextElement ( ) ; // Get the absolute URL of the resource. String href = responseBody . getHref ( ) ; URL resourceURL = new URL ( new URL ( locator . getResourceURL ( ) ) , href ) ; // Add an entry to the predecessor table. Vector predecessors = new Vector ( ) ; predecessorTable . put ( resourceURL , predecessors ) ; // For each propstat. Enumeration propstats = responseBody . getPropStats ( ) ; while ( propstats . hasMoreElements ( ) ) { PropStat propstat = ( PropStat ) propstats . nextElement ( ) ; // We are going to assume that the status is OK, or error out. if ( propstat . getStatusCode ( ) != IResponse . SC_OK ) throw new DAVException ( Policy . bind ( \"exception.errorRetrievingProp\" ) ) ; //$NON-NLS-1$ // For each property in the prop (there should only be one). Prop prop = propstat . getProp ( ) ; Enumeration elements = prop . getProperties ( ) ; while ( elements . hasMoreElements ( ) ) { Element element = ( Element ) elements . nextElement ( ) ; //  Look explicitly for the DAV:predecessor-set QualifiedName name = ElementEditor . getQualifiedName ( element ) ; if ( name . equals ( DAV_PREDECESSOR_SET ) ) { Enumeration e = new HrefSet ( element , DAV_PREDECESSOR_SET ) . getHrefs ( ) ; while ( e . hasMoreElements ( ) ) { URL predURL = new URL ( ( String ) e . nextElement ( ) ) ; predecessors . add ( predURL ) ; } // end-while } //end-if } // end-while } // end-while } //end-while // Phew, were done. return predecessorTable ; } catch ( IOException e ) { throw new SystemException ( e ) ; } catch ( MalformedElementException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the header from a message send to the server . [CODESPLIT] public IContext head ( ) throws DAVException { IResponse response = null ; try { response = davClient . head ( locator , newContext ( ) ) ; examineResponse ( response ) ; return response . getContext ( ) ; } catch ( IOException exception ) { throw new SystemException ( exception ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lock this resource using the specified parameters . [CODESPLIT] public LockToken lock ( boolean isShared , String depth , int timeout , String owner ) throws DAVException { // Define the request context. IContext context = newContext ( ) ; context . setDepth ( depth ) ; context . setTimeout ( timeout ) ; // Create the request body. Document document = newDocument ( ) ; LockInfo lockinfo = LockInfo . create ( document ) ; lockinfo . setIsShared ( isShared ) ; // Add the owner if it is given. if ( owner != null ) { Owner ownerEditor = lockinfo . setOwner ( ) ; ownerEditor . getElement ( ) . appendChild ( document . createTextNode ( owner ) ) ; } // Send the lock request. IResponse response = null ; try { response = davClient . lock ( locator , context , document ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } // Extract the token from the resulting context. LockToken token = new LockToken ( response . getContext ( ) . getLockToken ( ) ) ; //fServerManager.addLock(newURL(fLocator.getResourceURL()), token, depth); return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move this resource to the location specified by the given locator . If a resource already exists at the destination and the overwrite boolean is true then write over top of the existing resource . Otherwise do not . The enumeration is over qualified names which are the names of the properties to move . [CODESPLIT] public void move ( ILocator destination , boolean overwrite , Enumeration names ) throws DAVException { IContext context = newContext ( ) ; context . setOverwrite ( overwrite ) ; Document document = newDocument ( ) ; PropertyBehavior propertyBehavior = PropertyBehavior . create ( document ) ; if ( names == null ) { propertyBehavior . setIsKeepAllAlive ( true ) ; } else { while ( names . hasMoreElements ( ) ) { Object obj = names . nextElement ( ) ; Assert . isTrue ( obj instanceof QualifiedName , Policy . bind ( \"assert.propNameMustBeEnumOverQual\" ) ) ; //$NON-NLS-1$ // fix this...can we really add property names to href elements? propertyBehavior . addProperty ( ( ( QualifiedName ) obj ) . getLocalName ( ) ) ; } } IResponse response = null ; try { response = davClient . move ( locator , destination , context , document ) ; examineResponse ( response ) ; examineMultiStatusResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check in the receiver and answer a new Locator on the resulting version resource . [CODESPLIT] protected ILocator protectedCheckIn ( ) throws DAVException { IResponse response = null ; try { response = davClient . checkin ( locator , newContext ( ) , null ) ; examineResponse ( response ) ; String versionUrl = response . getContext ( ) . getLocation ( ) ; return davClient . getDAVFactory ( ) . newStableLocator ( versionUrl ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check out the receiver and answer a new Locator on the resulting checked out resource . The result MAY be the same as the receiver s Locator if the server did not create a new resource as a consequence of the check out ( i . e . if it was checking out a vesion - controlled resource rather than a version ) . [CODESPLIT] protected ILocator protectedCheckOut ( ) throws DAVException { IResponse response = null ; try { response = davClient . checkout ( locator , newContext ( ) , null ) ; examineResponse ( response ) ; String resourceUrl = response . getContext ( ) . getLocation ( ) ; return davClient . getDAVFactory ( ) . newStableLocator ( resourceUrl ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh the lock on this resource with the given lock token . Use the specified timeout value . [CODESPLIT] public void refreshLock ( LockToken lockToken , int timeout ) throws DAVException { // Set up the request in the context. IContext context = newContext ( ) ; context . setTimeout ( timeout ) ; context . setLockToken ( lockToken . getToken ( ) ) ; // Send the request to the server. IResponse response = null ; try { response = davClient . lock ( locator , context , null ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the properties with the given names from this resource . [CODESPLIT] public void removeProperties ( Collection propertyNames ) throws DAVException { Assert . isNotNull ( propertyNames ) ; // Removing no properties is easy. if ( propertyNames . isEmpty ( ) ) return ; // Add the names of the properties to remove to the request body. Document document = newDocument ( ) ; PropertyUpdate propertyUpdate = PropertyUpdate . create ( document ) ; Prop prop = propertyUpdate . addRemove ( ) ; Iterator namesItr = propertyNames . iterator ( ) ; while ( namesItr . hasNext ( ) ) prop . addPropertyName ( ( QualifiedName ) namesItr . next ( ) ) ; // Send the PROPPATCH request. IResponse response = null ; try { response = davClient . proppatch ( locator , newContext ( ) , document ) ; examineResponse ( response ) ; examineMultiStatusResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the property with the given name from this resource . [CODESPLIT] public void removeProperty ( QualifiedName propertyName ) throws DAVException { Collection propertyNames = new Vector ( 1 ) ; propertyNames . add ( propertyName ) ; removeProperties ( propertyNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the content of this resource to be the data stored in the given input stream . The type encoding is given in the content type argument and should be in the media format described by RFC2616 Sec 3 . 7 . The stream will automatically be closed after the data is consumed . If the resource does not exist it is created with the given content . [CODESPLIT] public void setContent ( String contentType , InputStream input ) throws DAVException { IResponse response = null ; try { IContext context = newContext ( ) ; context . setContentType ( contentType ) ; response = davClient . put ( locator , context , input ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the given properties on this resource . [CODESPLIT] public void setProperties ( Collection properties ) throws DAVException { Assert . isNotNull ( properties ) ; // Setting no properties is a no-op. if ( properties . isEmpty ( ) ) return ; // Build the request body to describe the properties to set. Document document = newDocument ( ) ; PropertyUpdate propertyUpdate = PropertyUpdate . create ( document ) ; Prop prop = propertyUpdate . addSet ( ) ; Iterator propertiesItr = properties . iterator ( ) ; while ( propertiesItr . hasNext ( ) ) { Element element = ( Element ) propertiesItr . next ( ) ; try { prop . addProperty ( element ) ; } catch ( MalformedElementException exception ) { throw new SystemException ( exception ) ; } } // end-while // Send the request to the server and examine the response for failures. IResponse response = null ; try { response = davClient . proppatch ( locator , newContext ( ) , document ) ; examineResponse ( response ) ; examineMultiStatusResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the given property on this resource . [CODESPLIT] public void setProperty ( Element property ) throws DAVException { Collection properties = new Vector ( 1 ) ; properties . add ( property ) ; setProperties ( properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unlock this resource with the given lock token . [CODESPLIT] public void unlock ( LockToken token ) throws DAVException { // Send the lock token in the header of the request. IContext context = newContext ( ) ; context . setLockToken ( \"<\" + token . getToken ( ) + \">\" ) ; //$NON-NLS-1$ //$NON-NLS-2$ IResponse response = null ; try { response = davClient . unlock ( locator , context ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform an UPDATE on the receiver to set the version it is based upon . [CODESPLIT] public void update ( ILocator version ) throws DAVException { Document document = newDocument ( ) ; Update . createVersion ( document , version . getResourceURL ( ) ) ; IResponse response = null ; try { response = davClient . update ( locator , newContext ( ) , document ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bring the receiver under version control . This means that the receiver is replaced by a version - controlled resource . Note that the client may send version control to a resource that is already under version control with no adverse effects . [CODESPLIT] public void versionControl ( ) throws DAVException { IResponse response = null ; try { response = davClient . versionControl ( locator , newContext ( ) , null ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete this resource from the repository optionally succeeding in the delete if the resource was not found on the server . [CODESPLIT] public void delete ( boolean mustExist ) throws DAVException { IResponse response = null ; try { response = davClient . delete ( locator , newContext ( ) ) ; if ( ! mustExist && ( response . getStatusCode ( ) == IResponse . SC_NOT_FOUND ) ) return ; examineResponse ( response ) ; examineMultiStatusResponse ( response ) ; } catch ( IOException exception ) { throw new SystemException ( exception ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the given status code and throw a WebDAV exception if the code indicates failure . If the code is success this method does nothing . [CODESPLIT] protected void examineStatusCode ( int code , String message ) throws WebDAVException { if ( code >= 300 && code <= 399 ) throw new RedirectionException ( code , message ) ; if ( code >= 400 && code <= 499 ) throw new ClientException ( code , message ) ; if ( code >= 500 && code <= 599 ) throw new ServerException ( code , message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a boolean value indicating whether or not this resource exists on the server . <p > This implementation uses the HTTP HEAD method so the URL may or may not exist in the DAV namespace . The DAV RESOURCE_TYPE property is NOT checked . < / p > [CODESPLIT] public boolean exists ( ) throws DAVException { // Test existance by issuing a HEAD request. IResponse response = null ; try { response = davClient . head ( locator , newContext ( ) ) ; // If the resource was not found, then that answers the question. if ( response . getStatusCode ( ) == IResponse . SC_NOT_FOUND ) return false ; // Otherwise check for errors. examineResponse ( response ) ; // No problems by this point, so the resource is there and OK. return true ; } catch ( IOException exception ) { throw new SystemException ( exception ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check to see if the resource is a working resource . <p > The resource is a working resource if it has &lt ; DAV : checked - out&gt ; and does not have &lt ; DAV : auto - checkout&gt ; in the &lt ; DAV : supported - live - properties - set&gt ; . < / p > [CODESPLIT] public boolean isWorkingResource ( ) throws DAVException { PropertyStatus propertyStat = getProperty ( DAV_SUPPORTED_LIVE_PROPERTY_SET ) ; // If the live-property-set is not supported, then the answer is 'no'. if ( propertyStat . getStatusCode ( ) == IResponse . SC_NOT_FOUND ) return false ; // If there was a problem getting the live property set, throw an exception. examineStatusCode ( propertyStat . getStatusCode ( ) , propertyStat . getStatusMessage ( ) ) ; // Check to see if the required properties are/are not in the supported set. try { Element propertySet = propertyStat . getProperty ( ) ; return ( ( ElementEditor . hasChild ( propertySet , DAV_CHECKED_OUT ) ) && ! ( ElementEditor . hasChild ( propertySet , DAV_AUTO_CHECKOUT ) ) ) ; } catch ( MalformedElementException exception ) { throw new SystemException ( exception ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a helper method to check to see if the resource has a property with the given name that in turn has a child with a given name . [CODESPLIT] protected boolean propertyHasChild ( QualifiedName propertyName , QualifiedName childName ) throws DAVException { // If the property is not found, then the answer is 'no'. PropertyStatus propertyStat = getProperty ( propertyName ) ; if ( propertyStat . getStatusCode ( ) == IResponse . SC_NOT_FOUND ) return false ; // If there was a problem getting the property, throw an exception. examineStatusCode ( propertyStat . getStatusCode ( ) , propertyStat . getStatusMessage ( ) ) ; // Check to see if the named child is in the retrieved property. try { return ElementEditor . hasChild ( propertyStat . getProperty ( ) , childName ) ; } catch ( MalformedElementException exception ) { throw new SystemException ( exception ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified binding to this editor s bindings element . The given href and segment must not be <code > null< / code > . [CODESPLIT] public void addBinding ( String href , String segment ) { Assert . isNotNull ( href ) ; Assert . isNotNull ( segment ) ; appendChild ( root , \"href\" , encodeHref ( href ) ) ; //$NON-NLS-1$ appendChild ( root , \"segment\" , segment ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over this bindings <code > Binding< / code > s . [CODESPLIT] public Enumeration getBindings ( ) throws MalformedElementException { final Node firstHref = getFirstChild ( root , \"href\" ) ; //$NON-NLS-1$ Node segment = null ; if ( firstHref != null ) segment = getNextSibling ( ( Element ) firstHref , \"segment\" ) ; //$NON-NLS-1$ final Node firstSegment = segment ; Enumeration e = new Enumeration ( ) { Node fCurrentHref = firstHref ; Node fCurrentSegment = firstSegment ; public boolean hasMoreElements ( ) { return fCurrentHref != null && fCurrentSegment != null ; } public Object nextElement ( ) { if ( ! hasMoreElements ( ) ) throw new NoSuchElementException ( ) ; String nextHref = getFirstText ( ( Element ) fCurrentHref ) ; String nextSegment = getFirstText ( ( Element ) fCurrentSegment ) ; Binding nextBinding = new Binding ( decodeHref ( nextHref ) , nextSegment ) ; fCurrentHref = getNextSibling ( ( Element ) fCurrentSegment , \"href\" ) ; //$NON-NLS-1$ fCurrentSegment = null ; if ( fCurrentHref != null ) fCurrentSegment = getNextSibling ( ( Element ) fCurrentHref , \"segment\" ) ; //$NON-NLS-1$ return nextBinding ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Answer a DOM <code > Element< / code > that represents a set of <code > String< / code > . <p > The set is represented by a single <code > Element< / code > whose name is given as the <code > setName< / code > argument . Each member of the set is a child <code > Element< / code > named <code > memberName< / code > that has text taken from the <code > memberEnum< / code > an <code > Enumeration< / code > of <code > String< / code > . [CODESPLIT] public Element newDAVElementSet ( QualifiedName setName , QualifiedName memberName , Enumeration memberEnum ) { Element setElement = newDAVElement ( setName ) ; while ( memberEnum . hasMoreElements ( ) ) { String member = ( String ) memberEnum . nextElement ( ) ; Element memberElement = newDAVTextElement ( memberName , member ) ; setElement . appendChild ( memberElement ) ; } return setElement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] protected IFigure createFigure ( ) { Figure f = new FreeformLayer ( ) ; f . setBorder ( new MarginBorder ( 3 ) ) ; f . setLayoutManager ( new FreeformLayout ( ) ) ; return f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void propertyChange ( PropertyChangeEvent evt ) { String prop = evt . getPropertyName ( ) ; if ( ReteGraph . PROP_CHILD_ADDED . equals ( prop ) || ReteGraph . PROP_CHILD_REMOVED . equals ( prop ) ) { refreshChildren ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the content length of this message s body or - 1 if the content length is unknown . [CODESPLIT] public long getContentLength ( ) { long contentLength = super . getContentLength ( ) ; if ( contentLength != - 1 ) return contentLength ; if ( requestBodyWriter == null ) return ( ( RequestInputStream ) is ) . length ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes this request s body to the given output stream . This method may be called more than once during the lifetime of this request . [CODESPLIT] public void write ( OutputStream os ) throws IOException { if ( requestBodyWriter == null ) { if ( inputRead ) { is . reset ( ) ; inputRead = false ; } super . write ( os ) ; } else { requestBodyWriter . writeRequestBody ( os ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the given byte array to its equivalent hexadecimal string and returns the result . [CODESPLIT] public static String toHex ( byte [ ] arr ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = 0 ; i < arr . length ; ++ i ) { buf . append ( Integer . toHexString ( ( arr [ i ] >> 4 ) & 0x0f ) ) ; buf . append ( Integer . toHexString ( arr [ i ] & 0x0f ) ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the given int array to its equivalent hexadecimal string and returns the result . [CODESPLIT] public static String toHex ( int [ ] arr ) { StringBuffer buf = new StringBuffer ( ) ; for ( int i = 0 ; i < arr . length ; ++ i ) { buf . append ( Integer . toHexString ( ( arr [ i ] >> 28 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 24 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 20 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 16 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 12 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 8 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] >> 4 ) & 0x0000000f ) ) ; buf . append ( Integer . toHexString ( ( arr [ i ] ) & 0x0000000f ) ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void inputChanged ( Viewer v , Object oldInput , Object newInput ) { if ( v instanceof AbstractTreeViewer ) { viewer = ( AbstractTreeViewer ) v ; manager = new DeferredTreeContentManager ( this , viewer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object [ ] getElements ( Object parent ) { if ( parent . equals ( viewer ) ) { if ( invisibleRoot == null ) initialize ( ) ; return getChildren ( invisibleRoot ) ; } return getChildren ( parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getParent ( Object child ) { if ( child instanceof TreeObject ) { return ( ( TreeObject ) child ) . getParent ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object [ ] getChildren ( Object parent ) { if ( parent == invisibleRoot ) { return ( ( TreeParent ) invisibleRoot ) . getChildren ( ) ; } else if ( parent instanceof TreeParent ) { return manager . getChildren ( parent ) ; } return new Object [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new WebDAV propfind element and sets it as the root of the given document . Returns an editor on the new propfind element . The document must not be <code > null< / code > and must not already have a root element . [CODESPLIT] public static PropFind create ( Document document ) { Assert . isNotNull ( document ) ; Assert . isTrue ( document . getDocumentElement ( ) == null ) ; Element element = create ( document , \"propfind\" ) ; //$NON-NLS-1$ try { return new PropFind ( element ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > iff this propfind is in the all prop form . [CODESPLIT] public boolean isAllProp ( ) throws MalformedElementException { Element child = getFirstChild ( root , childNames ) ; ensureNotNull ( Policy . bind ( \"ensure.missingAllpropOrPropnameOrPropElmt\" ) , child ) ; //$NON-NLS-1$ boolean isAllProp = isDAVElement ( child , \"allprop\" ) ; //$NON-NLS-1$ child = getNextSibling ( child , childNames ) ; ensureNull ( Policy . bind ( \"ensure.conflictingAllpropOrPropnameOrPropElmt\" ) , child ) ; //$NON-NLS-1$ return isAllProp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets whether this propfind is in the all prop form . [CODESPLIT] public void setIsAllProp ( boolean isAllProp ) { Element child = getFirstChild ( root , childNames ) ; boolean isAlreadyAllProp = isDAVElement ( child , \"allprop\" ) ; //$NON-NLS-1$ if ( isAllProp ) { if ( ! isAlreadyAllProp ) { if ( child != null ) root . removeChild ( child ) ; appendChild ( root , \"allprop\" ) ; //$NON-NLS-1$ } } else if ( isAlreadyAllProp ) root . removeChild ( child ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets whether this propfind is in the prop name form . [CODESPLIT] public void setIsPropName ( boolean isPropName ) { Element child = getFirstChild ( root , childNames ) ; boolean isAlreadyPropName = isDAVElement ( child , \"propname\" ) ; //$NON-NLS-1$ if ( isPropName ) { if ( ! isAlreadyPropName ) { if ( child != null ) root . removeChild ( child ) ; appendChild ( root , \"propname\" ) ; //$NON-NLS-1$ } } else if ( isAlreadyPropName ) root . removeChild ( child ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and sets a new prop on this propfind and returns an editor on it . This propfind must not already be in the all prop or prop name form . [CODESPLIT] public Prop setProp ( ) { Assert . isTrue ( getFirstChild ( root , new String [ ] { \"allprop\" , \"propname\" } ) == null ) ; //$NON-NLS-1$ //$NON-NLS-2$ Element prop = setChild ( root , \"prop\" , new String [ ] { \"prop\" } , true ) ; //$NON-NLS-1$ //$NON-NLS-2$ try { return new Prop ( prop ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( \"assert.internalError\" ) ) ; //$NON-NLS-1$ return null ; // Never reached. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks behind gets stuff after the white space . Basically ripping out the last word . [CODESPLIT] public static String stripLastWord ( String prefix ) { if ( \"\" . equals ( prefix ) ) { return prefix ; } if ( prefix . charAt ( prefix . length ( ) - 1 ) == ' ' ) { return \"\" ; } else { char [ ] c = prefix . toCharArray ( ) ; int start = 0 ; for ( int i = c . length - 1 ; i >= 0 ; i -- ) { if ( Character . isWhitespace ( c [ i ] ) || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' || c [ i ] == ' ' ) { start = i + 1 ; break ; } } prefix = prefix . substring ( start , prefix . length ( ) ) ; return prefix ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to enhance a consequence backtext such that it should compile in MVEL @param backText @return a substring of the back text that should be compilable without syntax errors by the mvel compiler [CODESPLIT] public static String getCompilableText ( String backText ) { String trimed = backText . trim ( ) ; if ( trimed . endsWith ( \";\" ) ) { // RHS expression should compile if it ends with ; but to get the last object, // we do no want it, to simulate a return statement return backText . substring ( 0 , backText . length ( ) - 1 ) ; } else if ( trimed . endsWith ( \".\" ) || trimed . endsWith ( \",\" ) ) { // RHS expression should compile if it ends with no dot or comma return backText . substring ( 0 , backText . length ( ) - 1 ) ; } else if ( CompletionUtil . COMPLETED_MVEL_EXPRESSION . matcher ( backText ) . matches ( ) ) { // RHS expression should compile if closed. just need to close the // statement return backText + \";\" ; //        } else if ( INCOMPLETED_MVEL_EXPRESSION.matcher( backText ).matches() ) { //            // remove the last char and close the statement //            return backText.substring( 0, //                                       backText.length() - 1 ); } else { //TODO: support completion within with {} blocks //TODO: support completion within nested expression. return backText ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * propertyname extraction and bean convention methods names checks [CODESPLIT] public static boolean isGetter ( String methodName , int argCount , String returnedType ) { return isAccessor ( methodName , argCount , 0 , \"get\" , returnedType , Signature . SIG_VOID , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a data depicting a method ( name # or params / args returned type key ) tries to return a bean property name derived from that method . If a bean property name is not found the initial method name is returned [CODESPLIT] public static String getPropertyName ( String methodName , int parameterCount , String returnType ) { if ( methodName == null ) { return null ; } String simpleName = methodName . replaceAll ( \"\\\\(\\\\)\" , \"\" ) ; int prefixLength = 0 ; if ( isIsGetter ( simpleName , parameterCount , returnType ) ) { prefixLength = 2 ; } else if ( isGetter ( simpleName , parameterCount , returnType ) // || isSetter ( simpleName , parameterCount , returnType ) ) { prefixLength = 3 ; } else { return methodName ; } char firstChar = Character . toLowerCase ( simpleName . charAt ( prefixLength ) ) ; String propertyName = firstChar + simpleName . substring ( prefixLength + 1 ) ; return propertyName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a data depicting a method ( name # or params / args returned type key ) tries to return a writable bean property name derived from that method . If a writable ( ie setter ) bean property name is not found the initial method name is returned [CODESPLIT] public static String getWritablePropertyName ( String methodName , int parameterCount , String returnType ) { if ( methodName == null ) { return null ; } String simpleName = methodName . replaceAll ( \"\\\\(\\\\)\" , \"\" ) ; if ( ! isSetter ( simpleName , parameterCount , returnType ) ) { return methodName ; } int prefixLength = 3 ; char firstChar = Character . toLowerCase ( simpleName . charAt ( prefixLength ) ) ; String propertyName = firstChar + simpleName . substring ( prefixLength + 1 ) ; return propertyName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given method is a bean accessor ( ie getter / setter ) [CODESPLIT] private static boolean isAccessor ( String methodName , int actualParameterCount , int requiredParameterCount , String prefix , String returnType , String requiredReturnType , boolean includeType ) { //must be longer than the accessor prefix if ( methodName . length ( ) < prefix . length ( ) + 1 ) { return false ; } //start with get, set or is if ( ! methodName . startsWith ( prefix ) ) { return false ; } if ( actualParameterCount != requiredParameterCount ) { return false ; } //if we check for the returned type, verify that the returned type is of the cirrect type signature if ( includeType ) { if ( ! requiredReturnType . equals ( returnType ) ) { return false ; } } else { if ( requiredReturnType . equals ( returnType ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "COMPENSATES FOR LACK OF getSimpleName IN java . lang . Class Borrowed and adpated from MVEL s org . mvel . util . ParseTools . getSimpleClassName ( Class ) [CODESPLIT] public static String getSimpleClassName ( Class < ? > cls ) { int lastIndex = cls . getName ( ) . lastIndexOf ( ' ' ) ; if ( lastIndex < 0 ) { lastIndex = cls . getName ( ) . lastIndexOf ( ' ' ) ; } if ( cls . isArray ( ) ) { return cls . getName ( ) . substring ( lastIndex + 1 ) + \"[]\" ; } else { return cls . getName ( ) . substring ( lastIndex + 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the outline page . [CODESPLIT] public void update ( ) { TreeViewer viewer = getTreeViewer ( ) ; if ( viewer != null ) { Control control = viewer . getControl ( ) ; if ( control != null && ! control . isDisposed ( ) ) { initRules ( ) ; populatePackageTreeNode ( ) ; viewer . refresh ( ) ; control . setRedraw ( false ) ; viewer . expandToLevel ( 2 ) ; control . setRedraw ( true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the content length of this message s body or - 1 if the content length is unknown . [CODESPLIT] public long getContentLength ( ) { long contentLength = context . getContentLength ( ) ; if ( contentLength != - 1 ) return contentLength ; if ( is instanceof ByteArrayInputStream ) return ( ( ByteArrayInputStream ) is ) . available ( ) ; return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes this messages body to the given output stream . This method may only be called once during the lifetime of this message . [CODESPLIT] public void write ( OutputStream os ) throws IOException { Assert . isTrue ( ! inputRead ) ; Assert . isTrue ( ! hasInputStream ) ; int bytesRead = 0 ; int totalBytesRead = 0 ; byte [ ] buffer = bufferPool . getBuffer ( ) ; long contentLength = getContentLength ( ) ; try { while ( bytesRead != - 1 && ( contentLength == - 1 || contentLength > totalBytesRead ) ) { if ( contentLength == - 1 ) { bytesRead = is . read ( buffer ) ; } else { bytesRead = is . read ( buffer , 0 , ( int ) Math . min ( buffer . length , contentLength - totalBytesRead ) ) ; } if ( bytesRead == - 1 ) { if ( contentLength >= 0 ) { throw new IOException ( Policy . bind ( \"exception.unexpectedEndStream\" ) ) ; //$NON-NLS-1$ } } else { totalBytesRead += bytesRead ; os . write ( buffer , 0 , bytesRead ) ; } } } finally { bufferPool . putBuffer ( buffer ) ; inputRead = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "I don t see the need for any of this custom stepOver stuff why is it here? [CODESPLIT] public synchronized void stepOver ( ) throws DebugException { // Detection for active stackframe if ( ! ( getTopStackFrame ( ) instanceof MVELStackFrame ) ) { super . stepOver ( ) ; return ; } //MVEL step over MVELStackFrame mvelStack = ( MVELStackFrame ) getTopStackFrame ( ) ; if ( ! canStepOver ( ) || ! mvelStack . canStepOver ( ) ) { return ; } if ( ! setRemoteOnBreakReturn ( Debugger . STEP ) ) { return ; } setRunning ( true ) ; preserveStackFrames ( ) ; fireEvent ( new DebugEvent ( this , DebugEvent . RESUME , DebugEvent . STEP_OVER ) ) ; try { getUnderlyingThread ( ) . resume ( ) ; } catch ( RuntimeException e ) { //stepEnd(); targetRequestFailed ( MessageFormat . format ( JDIDebugModelMessages . JDIThread_exception_stepping , e . toString ( ) ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will create markers for parse errors . Parse errors mean that antlr has picked up some major typos in the input source . [CODESPLIT] protected void markParseErrors ( List < DroolsBuildMarker > markers , List < BaseKnowledgeBuilderResultImpl > parserErrors ) { for ( Iterator < BaseKnowledgeBuilderResultImpl > iter = parserErrors . iterator ( ) ; iter . hasNext ( ) ; ) { Object error = iter . next ( ) ; if ( error instanceof ParserError ) { ParserError err = ( ParserError ) error ; markers . add ( new DroolsBuildMarker ( err . getMessage ( ) , err . getRow ( ) ) ) ; } else if ( error instanceof KnowledgeBuilderResult ) { KnowledgeBuilderResult res = ( KnowledgeBuilderResult ) error ; int [ ] errorLines = res . getLines ( ) ; markers . add ( new DroolsBuildMarker ( res . getMessage ( ) , errorLines != null && errorLines . length > 0 ? errorLines [ 0 ] : - 1 ) ) ; } else if ( error instanceof ExpanderException ) { ExpanderException exc = ( ExpanderException ) error ; // TODO line mapping is incorrect markers . add ( new DroolsBuildMarker ( exc . getMessage ( ) , - 1 ) ) ; } else { markers . add ( new DroolsBuildMarker ( error . toString ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This will create markers for build errors that happen AFTER parsing . [CODESPLIT] private void markOtherErrors ( List < DroolsBuildMarker > markers , DroolsError [ ] buildErrors ) { // TODO are there warnings too? for ( int i = 0 ; i < buildErrors . length ; i ++ ) { DroolsError error = buildErrors [ i ] ; if ( error instanceof GlobalError ) { GlobalError globalError = ( GlobalError ) error ; markers . add ( new DroolsBuildMarker ( \"Global error: \" + globalError . getGlobal ( ) , - 1 ) ) ; } else if ( error instanceof RuleBuildError ) { RuleBuildError ruleError = ( RuleBuildError ) error ; // TODO try to retrieve line number (or even character start-end) // disabled for now because line number are those of the rule class, // not the rule file itself if ( ruleError . getObject ( ) instanceof CompilationProblem [ ] ) { CompilationProblem [ ] problems = ( CompilationProblem [ ] ) ruleError . getObject ( ) ; for ( int j = 0 ; j < problems . length ; j ++ ) { markers . add ( new DroolsBuildMarker ( problems [ j ] . getMessage ( ) , ruleError . getLine ( ) ) ) ; } } else { markers . add ( new DroolsBuildMarker ( ruleError . getRule ( ) . getName ( ) + \":\" + ruleError . getMessage ( ) , ruleError . getLine ( ) ) ) ; } } else if ( error instanceof ParserError ) { ParserError parserError = ( ParserError ) error ; // TODO try to retrieve character start-end markers . add ( new DroolsBuildMarker ( parserError . getMessage ( ) , parserError . getRow ( ) ) ) ; } else if ( error instanceof FunctionError ) { FunctionError functionError = ( FunctionError ) error ; // TODO add line to function error // TODO try to retrieve character start-end if ( functionError . getObject ( ) instanceof CompilationProblem [ ] ) { CompilationProblem [ ] problems = ( CompilationProblem [ ] ) functionError . getObject ( ) ; for ( int j = 0 ; j < problems . length ; j ++ ) { markers . add ( new DroolsBuildMarker ( problems [ j ] . getMessage ( ) , functionError . getLines ( ) [ j ] ) ) ; } } else { markers . add ( new DroolsBuildMarker ( functionError . getFunctionDescr ( ) . getName ( ) + \":\" + functionError . getMessage ( ) , - 1 ) ) ; } } else if ( error instanceof FieldTemplateError ) { markers . add ( new DroolsBuildMarker ( error . getMessage ( ) , ( ( FieldTemplateError ) error ) . getLine ( ) ) ) ; } else if ( error instanceof FactTemplateError ) { markers . add ( new DroolsBuildMarker ( error . getMessage ( ) , ( ( FactTemplateError ) error ) . getLine ( ) ) ) ; } else if ( error instanceof ImportError ) { markers . add ( new DroolsBuildMarker ( \"ImportError: \" + error . getMessage ( ) ) ) ; } else if ( error instanceof DescrBuildError ) { markers . add ( new DroolsBuildMarker ( \"BuildError: \" + error . getMessage ( ) , ( ( DescrBuildError ) error ) . getLine ( ) ) ) ; } else { markers . add ( new DroolsBuildMarker ( \"Unknown DroolsError \" + error . getClass ( ) + \": \" + error ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips the next character in s if it matches c otherwise a <code > ParserException< / code > is thrown . [CODESPLIT] public void match ( char c ) throws ParserException { checkPosition ( ) ; if ( s . charAt ( pos ) != c ) throw new ParserException ( ) ; ++ pos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next quoted string is s ( quotes included ) . Throws a <code > ParserException< / code > if the next substring in s is not a quoted string . [CODESPLIT] public String nextQuotedString ( ) throws ParserException { int start = pos ; match ( ' ' ) ; checkPosition ( ) ; while ( s . charAt ( pos ) != ' ' ) { ++ pos ; checkPosition ( ) ; } match ( ' ' ) ; return s . substring ( start , pos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next token in s . Throws a <code > ParserException< / code > if the next substring in s is not a token . [CODESPLIT] public String nextToken ( ) throws ParserException { int start = pos ; checkPosition ( ) ; boolean done = false ; while ( ! done && pos < s . length ( ) ) { int c = s . charAt ( pos ) ; if ( c <= 31 // || c == 127 // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || c == ' ' // || Character . isWhitespace ( ( char ) c ) ) { done = true ; } else { ++ pos ; } } if ( start == pos ) { throw new ParserException ( ) ; } return s . substring ( start , pos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips the next sequence of white space in s . An exception is not thrown if there is no matching white space . [CODESPLIT] public void skipWhiteSpace ( ) { while ( pos < s . length ( ) && Character . isWhitespace ( s . charAt ( pos ) ) ) ++ pos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the local Guvnor metadata file associated with a given resource . [CODESPLIT] public static IFile findGuvnorMetadata ( IResource resource ) { IFile res = null ; IPath dir = resource . getFullPath ( ) . removeLastSegments ( 1 ) ; IPath mdpath = dir . append ( \".guvnorinfo\" ) . append ( \".\" + resource . getName ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ IResource mdResource = resource . getWorkspace ( ) . getRoot ( ) . findMember ( mdpath ) ; if ( mdResource != null && mdResource . exists ( ) && mdResource instanceof IFile ) { res = ( IFile ) mdResource ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a resource to Guvnor . [CODESPLIT] public static boolean addResourceToGuvnor ( String repLoc , String targetLoc , IFile selectedFile ) { boolean res = false ; try { String fullPath = targetLoc + selectedFile . getName ( ) ; IWebDavClient client = WebDavServerCache . getWebDavClient ( repLoc ) ; if ( client == null ) { client = WebDavClientFactory . createClient ( new URL ( repLoc ) ) ; WebDavServerCache . cacheWebDavClient ( repLoc , client ) ; } try { //                res = client.createResource(fullPath, selectedFile.getContents(), false); // Hack: When creating a file, if the actual contents are passed first, // the client hangs for about 20 seconds when closing the InputStream. // Don't know why... // But, if the file is created with empty contents, and then the contents // set, the operation is fast (less than a couple of seconds) res = client . createResource ( fullPath , new ByteArrayInputStream ( new byte [ 0 ] ) , false ) ; if ( res ) { client . putResource ( fullPath , selectedFile . getContents ( ) ) ; } } catch ( WebDavException wde ) { if ( wde . getErrorCode ( ) != IResponse . SC_UNAUTHORIZED ) { // If not an authentication failure, we don't know what to do with it throw wde ; } boolean retry = PlatformUtils . getInstance ( ) . authenticateForServer ( repLoc , client ) ; if ( retry ) { //                    res = client.createResource(fullPath, selectedFile.getContents(), false); // See Hack note immediately above... res = client . createResource ( fullPath , new ByteArrayInputStream ( new byte [ 0 ] ) , false ) ; if ( res ) { client . putResource ( fullPath , selectedFile . getContents ( ) ) ; } } } if ( res ) { GuvnorMetadataUtils . markCurrentGuvnorResource ( selectedFile ) ; ResourceProperties resProps = client . queryProperties ( fullPath ) ; GuvnorMetadataProps mdProps = new GuvnorMetadataProps ( selectedFile . getName ( ) , repLoc , fullPath , resProps . getLastModifiedDate ( ) , resProps . getRevision ( ) ) ; GuvnorMetadataUtils . setGuvnorMetadataProps ( selectedFile . getFullPath ( ) , mdProps ) ; } } catch ( Exception e ) { Activator . getDefault ( ) . displayError ( IStatus . ERROR , e . getMessage ( ) , e , true ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commits changes to Guvnor . [CODESPLIT] public static void commitFileChanges ( IFile selectedFile ) { try { GuvnorMetadataProps props = GuvnorMetadataUtils . getGuvnorMetadata ( selectedFile ) ; IWebDavClient client = WebDavServerCache . getWebDavClient ( props . getRepository ( ) ) ; if ( client == null ) { client = WebDavClientFactory . createClient ( new URL ( props . getRepository ( ) ) ) ; WebDavServerCache . cacheWebDavClient ( props . getRepository ( ) , client ) ; } ResourceProperties remoteProps = null ; try { remoteProps = client . queryProperties ( props . getFullpath ( ) ) ; } catch ( WebDavException wde ) { if ( wde . getErrorCode ( ) != IResponse . SC_UNAUTHORIZED ) { // If not an authentication failure, we don't know what to do with it throw wde ; } boolean retry = PlatformUtils . getInstance ( ) . authenticateForServer ( props . getRepository ( ) , client ) ; if ( retry ) { remoteProps = client . queryProperties ( props . getFullpath ( ) ) ; } } if ( remoteProps == null ) { throw new Exception ( \"Could not retrieve server version of \" + props . getFullpath ( ) ) ; //$NON-NLS-1$ } // Check to make sure that the version in the repository is the same as the base // version for the local copy boolean proceed = true ; if ( ! props . getRevision ( ) . equals ( remoteProps . getRevision ( ) ) ) { String msg = MessageFormat . format ( Messages . getString ( \"overwrite.confirmation\" ) , //$NON-NLS-1$ new Object [ ] { selectedFile . getName ( ) , remoteProps . getRevision ( ) , props . getRevision ( ) } ) ; Display display = PlatformUI . getWorkbench ( ) . getDisplay ( ) ; proceed = MessageDialog . openQuestion ( display . getActiveShell ( ) , Messages . getString ( \"overwrite.confirmation.caption\" ) , msg ) ; //$NON-NLS-1$ } if ( proceed ) { client . putResource ( props . getFullpath ( ) , selectedFile . getContents ( ) ) ; GuvnorMetadataUtils . markCurrentGuvnorResource ( selectedFile ) ; ResourceProperties resProps = client . queryProperties ( props . getFullpath ( ) ) ; GuvnorMetadataProps mdProps = GuvnorMetadataUtils . getGuvnorMetadata ( selectedFile ) ; mdProps . setVersion ( resProps . getLastModifiedDate ( ) ) ; mdProps . setRevision ( resProps . getRevision ( ) ) ; GuvnorMetadataUtils . setGuvnorMetadataProps ( selectedFile . getFullPath ( ) , mdProps ) ; } } catch ( Exception e ) { Activator . getDefault ( ) . displayError ( IStatus . ERROR , e . getMessage ( ) , e , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the local Guvnor metadata file associated with a given resource . [CODESPLIT] public static IFile findGuvnorMetadata ( IPath resource ) { IFile res = null ; IPath dir = resource . removeLastSegments ( 1 ) ; IPath mdpath = dir . append ( \".guvnorinfo\" ) . append ( \".\" + resource . lastSegment ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ IResource mdResource = Activator . getDefault ( ) . getWorkspace ( ) . getRoot ( ) . findMember ( mdpath ) ; if ( mdResource != null && mdResource . exists ( ) && mdResource instanceof IFile ) { res = ( IFile ) mdResource ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy all the default values into the receiver . [CODESPLIT] public void collapse ( ) { if ( defaults != null ) { Enumeration keysEnum = defaults . keys ( ) ; while ( keysEnum . hasMoreElements ( ) ) { String key = ( String ) keysEnum . nextElement ( ) ; put ( key , get ( key ) ) ; } defaults = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value for the given key . [CODESPLIT] public String get ( String key ) { String value = ( String ) properties . get ( new ContextKey ( key ) ) ; if ( value == null && defaults != null ) return defaults . get ( key ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the sender s estimate of the time since the response was generated . Return the int value for the AGE key . Return - 1 if the value is not set . [CODESPLIT] public int getAge ( ) { String ageString = get ( AGE ) ; return ( ageString == null ) ? - 1 : Integer . parseInt ( ageString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the content length in bytes of the entity body . Return the value for the CONTENT_LENGTH key . Returns - 1 if the Content - Length has not been set . [CODESPLIT] public long getContentLength ( ) { String lengthString = get ( CONTENT_LENGTH ) ; return ( lengthString == null ) ? - 1 : Long . parseLong ( lengthString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the integer value for the MAX_FORWARDS key . [CODESPLIT] public int getMaxForwards ( ) { String s = get ( MAX_FORWARDS ) ; return s == null ? - 1 : Integer . parseInt ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the flag that indicates if copy or move should overwrite an existing destination . Return the boolean value for the OVERWRITE key . [CODESPLIT] public boolean getOverwrite ( ) { String overwriteString = get ( OVERWRITE ) ; return overwriteString == null ? false : overwriteString . equalsIgnoreCase ( \"T\" ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the boolean value for the PASSTHROUGH key . [CODESPLIT] public boolean getPassthrough ( ) { String s = get ( PASSTHROUGH ) ; return s == null ? false : s . equalsIgnoreCase ( \"T\" ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the lock timeout value . The value - 1 means that the value was not set the value - 2 means that the value was Infinity . Return the integer value for the TIMEOUT key . [CODESPLIT] public int getTimeout ( ) { String timeoutString = get ( TIMEOUT ) ; if ( timeoutString == null ) return - 1 ; if ( timeoutString . equalsIgnoreCase ( DEPTH_INFINITY ) ) return - 2 ; if ( timeoutString . regionMatches ( true , 1 , \"Second-\" , 1 , 7 ) ) //$NON-NLS-1$ return Integer . parseInt ( timeoutString . substring ( 7 ) ) ; // ignore all other cases, and use infinite timeout return - 2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an enumeration over the context s keys . ( recursively computes the keys based on keys defaults as well ) [CODESPLIT] public Enumeration keys ( ) { if ( defaults == null ) return new ContextKeyToStringEnum ( properties . keys ( ) ) ; Enumeration allKeys = new MergedEnumeration ( new ContextKeyToStringEnum ( properties . keys ( ) ) , defaults . keys ( ) ) ; Hashtable keysSet = new Hashtable ( ) ; while ( allKeys . hasMoreElements ( ) ) keysSet . put ( allKeys . nextElement ( ) , \"ignored\" ) ; //$NON-NLS-1$ return keysSet . keys ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put the given key - value pair into the context . [CODESPLIT] public void put ( String key , String value ) { ContextKey ckey = new ContextKey ( key ) ; if ( ( value == null ) || ( value . length ( ) == 0 ) ) properties . remove ( ckey ) ; else properties . put ( ckey , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the lock timeout value in seconds . Pass - 1 to clear the value pass - 2 to set Infinity . Set the integer value for the TIMEOUT key . [CODESPLIT] public void setTimeout ( int value ) { if ( value == - 1 ) put ( TIMEOUT , \"\" ) ; //$NON-NLS-1$ else put ( TIMEOUT , ( value == - 2 ) ? DEPTH_INFINITY : \"Second-\" + Integer . toString ( value ) ) ; //$NON-NLS-1$ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method will create a BufferedReader to read the file . [CODESPLIT] protected BufferedReader openDSLFile ( String filename ) { try { FileReader reader = new FileReader ( filename ) ; BufferedReader breader = new BufferedReader ( reader ) ; return breader ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method will use the BufferedReader to read the contents of the file . It calls other methods to parse the line and build the tree . [CODESPLIT] protected void parseFile ( BufferedReader reader ) { String line = null ; try { while ( ( line = reader . readLine ( ) ) != null ) { Section section = getSection ( line ) ; String nl = stripHeadingAndCode ( line ) ; String objname = this . getObjMetadata ( nl ) ; nl = this . stripObjMetadata ( nl ) ; addEntry ( section , nl , objname ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method will strip out the when then * at the beginning of each line and the mapped drl expression [CODESPLIT] protected String stripHeadingAndCode ( String text ) { if ( text . startsWith ( DSLMappingEntry . CONDITION . getSymbol ( ) ) ) { return text . substring ( DSLMappingEntry . CONDITION . getSymbol ( ) . length ( ) + 2 , text . indexOf ( \"=\" ) ) ; } else if ( text . startsWith ( DSLMappingEntry . CONSEQUENCE . getSymbol ( ) ) ) { return text . substring ( DSLMappingEntry . CONSEQUENCE . getSymbol ( ) . length ( ) + 2 , text . indexOf ( \"=\" ) ) ; } else if ( text . startsWith ( DSLMappingEntry . ANY . getSymbol ( ) ) ) { return text . substring ( DSLMappingEntry . ANY . getSymbol ( ) . length ( ) + 2 , text . indexOf ( \"=\" ) ) ; } else if ( text . startsWith ( \"#\" ) ) { return \"\" ; } else { return text ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method will return just the object metadata [CODESPLIT] protected String getObjMetadata ( String text ) { if ( text . startsWith ( \"[\" ) ) { return text . substring ( 1 , text . lastIndexOf ( \"]\" ) ) ; } else { return \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method will strip the metadata from the text string [CODESPLIT] protected String stripObjMetadata ( String text ) { if ( text . startsWith ( \"[\" ) ) { return text . substring ( text . lastIndexOf ( \"]\" ) + 1 ) ; } else { return text ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method is different than addTokens ( StringTokenizer ) . this method expects additional metadata . It expects to get an object name or * meaning all . If the metadata is a wildcard all it will add the tokens to all the top level nodes that are immediate child of root . [CODESPLIT] public void addTokens ( String metadata , StringTokenizer tokens ) { Node mnode = this . rootCond . addToken ( metadata ) ; Node thenode = mnode ; while ( tokens . hasMoreTokens ( ) ) { Node newnode = thenode . addToken ( tokens . nextToken ( ) ) ; thenode = newnode ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method adds the token to root [CODESPLIT] public void addTokens ( String [ ] tokens , Node rootNode ) { Node thenode = rootNode ; for ( int i = 0 ; i < tokens . length ; i ++ ) { Node newnode = thenode . addToken ( tokens [ i ] ) ; thenode = newnode ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the method will tokenize the text and try to find the node that matches and return the children . the method will traverse down the network as far as it can and return the children at that level . [CODESPLIT] public Node [ ] getConditionChildren ( String text ) { Node thenode = this . rootCond ; if ( text . length ( ) > 0 ) { StringTokenizer tokenz = new StringTokenizer ( text ) ; this . last = this . current ; while ( tokenz . hasMoreTokens ( ) ) { String strtk = tokenz . nextToken ( ) ; Node ch = thenode . getChild ( strtk ) ; // if a child is found, we set thenode to the child Node if ( ch != null ) { thenode = ch ; } else { break ; } } if ( thenode != this . rootCond ) { this . current = thenode ; } } Collection < Node > children = thenode . getChildren ( ) ; Node [ ] nchild = new Node [ children . size ( ) ] ; return children . toArray ( nchild ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the method expects the caller to pass the object [CODESPLIT] public Node [ ] getChildren ( String obj , String text ) { Node thenode = this . rootCond . getChild ( obj ) ; if ( thenode == null ) { for ( Node child : this . rootCond . getChildren ( ) ) { String tokenText = child . getToken ( ) ; if ( tokenText != null ) { int index = tokenText . indexOf ( \"{\" ) ; if ( index != - 1 ) { String substring = tokenText . substring ( 0 , index ) ; if ( obj != null && obj . startsWith ( substring ) ) { thenode = child ; } } } } } if ( thenode != null && text . length ( ) > 0 ) { StringTokenizer tokenz = new StringTokenizer ( text ) ; this . last = this . current ; while ( tokenz . hasMoreTokens ( ) ) { String strtk = tokenz . nextToken ( ) ; Node ch = thenode . getChild ( strtk ) ; // if a child is found, we set thenode to the child Node if ( ch != null ) { thenode = ch ; } else { break ; } } if ( thenode != this . rootCond ) { this . current = thenode ; } } if ( thenode == null ) { return null ; // thenode = this.rootCond; } Collection < Node > children = thenode . getChildren ( ) ; Node [ ] nchild = new Node [ children . size ( ) ] ; return children . toArray ( nchild ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for convienance the method will return a list of strings that are children of the last node found . If the editor wants to generate the children strings call the method with true [CODESPLIT] public ArrayList < String > getConditionChildrenList ( String text , boolean addChildren ) { Node [ ] c = getConditionChildren ( text ) ; this . suggestions . clear ( ) ; for ( int idx = 0 ; idx < c . length ; idx ++ ) { this . suggestions . add ( c [ idx ] . getToken ( ) ) ; if ( addChildren ) { this . addChildToList ( c [ idx ] , c [ idx ] . getToken ( ) , this . suggestions ) ; } } return this . suggestions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "for convienance the method will return a list of strings that are children of the last node found . If the editor wants to generate the children strings call the method with true [CODESPLIT] public ArrayList < String > getConsequenceChildrenList ( String text , boolean addChildren ) { Node [ ] c = getConsequenceChildren ( text ) ; this . suggestions . clear ( ) ; for ( int idx = 0 ; idx < c . length ; idx ++ ) { if ( addChildren ) { this . addChildToList ( c [ idx ] , c [ idx ] . getToken ( ) , this . suggestions ) ; } else { this . suggestions . add ( c [ idx ] . getToken ( ) ) ; } } return this . suggestions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method will prepend the parent text to the child and generate the possible combinations in text format . [CODESPLIT] public void addChildToList ( Node n , String prefix , ArrayList < String > list ) { if ( n . getChildren ( ) . size ( ) > 0 ) { for ( Node child : n . getChildren ( ) ) { if ( prefix != null && \"-\" . equals ( child . getToken ( ) ) ) { if ( ! list . contains ( prefix ) ) { list . add ( prefix ) ; } return ; } String text = ( prefix == null ? \"\" : prefix + \" \" ) + child . getToken ( ) ; // list.add(text); addChildToList ( child , text , list ) ; } } else { if ( ! list . contains ( prefix ) ) { list . add ( prefix ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method will print the DSLTree to System . out in text format . [CODESPLIT] public void printTree ( ) { System . out . println ( \"ROOT\" ) ; for ( Node n : rootCond . getChildren ( ) ) { printNode ( n ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method will print the node and then iterate over the children [CODESPLIT] protected void printNode ( Node n ) { printTabs ( n . getDepth ( ) ) ; System . out . println ( \"- \\\"\" + n . getToken ( ) + \"\\\"\" ) ; for ( Node c : n . getChildren ( ) ) { printNode ( c ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method will print n number of tabs [CODESPLIT] protected void printTabs ( int count ) { for ( int idx = 0 ; idx < count ; idx ++ ) { System . out . print ( tab ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a JSON value from the given string . [CODESPLIT] public static JsonValue readFrom ( String text ) { try { return new JsonParser ( text ) . parse ( ) ; } catch ( IOException exception ) { // JsonParser does not throw IOException for String throw new RuntimeException ( exception ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a JsonValue instance that represents the given <code > float< / code > value . [CODESPLIT] public static JsonValue valueOf ( float value ) { if ( Float . isInfinite ( value ) || Float . isNaN ( value ) ) { throw new IllegalArgumentException ( \"Infinite and NaN values not permitted in JSON\" ) ; } return new JsonNumber ( cutOffPointZero ( Float . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void fetchDeferredChildren ( Object object , IElementCollector collector , IProgressMonitor monitor ) { if ( ! ( object instanceof TreeParent ) ) { return ; } TreeParent node = ( TreeParent ) object ; if ( node . getNodeType ( ) == Type . NONE ) { List < GuvnorRepository > reps = Activator . getLocationManager ( ) . getRepositories ( ) ; monitor . beginTask ( Messages . getString ( \"pending\" ) , reps . size ( ) ) ; //$NON-NLS-1$ for ( int i = 0 ; i < reps . size ( ) ; i ++ ) { TreeParent p = new TreeParent ( reps . get ( i ) . getLocation ( ) , Type . REPOSITORY ) ; p . setParent ( node ) ; p . setGuvnorRepository ( reps . get ( i ) ) ; ResourceProperties props = new ResourceProperties ( ) ; props . setBase ( \"\" ) ; //$NON-NLS-1$ p . setResourceProps ( props ) ; collector . add ( p , monitor ) ; monitor . worked ( 1 ) ; } monitor . done ( ) ; } if ( EnumSet . of ( Type . REPOSITORY , Type . GLOBALS , Type . PACKAGES , Type . SNAPSHOTS , Type . PACKAGE , Type . SNAPSHOT_PACKAGE ) . contains ( node . getNodeType ( ) ) ) { listDirectory ( node , collector , monitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a directory listing . [CODESPLIT] public void listDirectory ( TreeParent node , IElementCollector collector , IProgressMonitor monitor ) { monitor . beginTask ( Messages . getString ( \"pending\" ) , 1 ) ; //$NON-NLS-1$ monitor . worked ( 1 ) ; GuvnorRepository rep = node . getGuvnorRepository ( ) ; try { IWebDavClient webdav = WebDavServerCache . getWebDavClient ( rep . getLocation ( ) ) ; if ( webdav == null ) { webdav = WebDavClientFactory . createClient ( new URL ( rep . getLocation ( ) ) ) ; WebDavServerCache . cacheWebDavClient ( rep . getLocation ( ) , webdav ) ; } Map < String , ResourceProperties > listing = null ; try { listing = webdav . listDirectory ( node . getFullPath ( ) ) ; } catch ( WebDavException wde ) { if ( wde . getErrorCode ( ) != IResponse . SC_UNAUTHORIZED ) { // If not an authentication failure, we don't know what to do with it throw wde ; } boolean retry = PlatformUtils . getInstance ( ) . authenticateForServer ( node . getGuvnorRepository ( ) . getLocation ( ) , webdav ) ; if ( retry ) { listing = webdav . listDirectory ( node . getFullPath ( ) ) ; } } if ( listing != null ) { for ( String s : listing . keySet ( ) ) { ResourceProperties resProps = listing . get ( s ) ; TreeObject o = null ; if ( resProps . isDirectory ( ) ) { Type childType ; switch ( getNodeType ( ) ) { case REPOSITORY : if ( s . startsWith ( \"snapshot\" ) ) { childType = Type . SNAPSHOTS ; } else if ( s . startsWith ( \"packages\" ) ) { childType = Type . PACKAGES ; } else if ( s . startsWith ( \"globalarea\" ) ) { childType = Type . GLOBALS ; } else { childType = Type . PACKAGE ; } break ; case SNAPSHOTS : childType = Type . SNAPSHOT_PACKAGE ; break ; case SNAPSHOT_PACKAGE : childType = Type . SNAPSHOT ; break ; default : childType = Type . PACKAGE ; } o = new TreeParent ( s , childType ) ; } else { o = new TreeObject ( s , Type . RESOURCE ) ; } o . setGuvnorRepository ( rep ) ; o . setResourceProps ( resProps ) ; node . addChild ( o ) ; collector . add ( o , monitor ) ; } } monitor . worked ( 1 ) ; } catch ( WebDavException e ) { if ( e . getErrorCode ( ) == IResponse . SC_UNAUTHORIZED ) { PlatformUtils . reportAuthenticationFailure ( ) ; } else { if ( e . getErrorCode ( ) == IResponse . SC_NOT_IMPLEMENTED ) { Activator . getDefault ( ) . displayMessage ( IStatus . ERROR , Messages . getString ( \"rep.connect.fail\" ) ) ; //$NON-NLS-1$ } else { Activator . getDefault ( ) . displayError ( IStatus . ERROR , e . getMessage ( ) , e , true ) ; } } } catch ( ConnectException ce ) { Activator . getDefault ( ) . displayMessage ( IStatus . ERROR , Messages . getString ( \"rep.connect.fail\" ) ) ; //$NON-NLS-1$ } catch ( Exception e ) { Activator . getDefault ( ) . displayError ( IStatus . ERROR , e . getMessage ( ) , e , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getParent ( Object o ) { if ( o instanceof TreeObject ) { return ( ( TreeObject ) o ) . getParent ( ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void start ( BundleContext context ) throws Exception { super . start ( context ) ; plugin = this ; getWorkspace ( ) . addResourceChangeListener ( rcListner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void stop ( BundleContext context ) throws Exception { plugin = null ; super . stop ( context ) ; getWorkspace ( ) . removeResourceChangeListener ( rcListner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an image descriptor for the image file at the given plug - in relative path [CODESPLIT] public static ImageDescriptor getImageDescriptor ( String id ) { ImageDescriptor retVal = getDefault ( ) . getImageRegistry ( ) . getDescriptor ( id ) ; if ( retVal == null ) { retVal = loadImageDescriptor ( id ) ; getDefault ( ) . getImageRegistry ( ) . put ( id , retVal ) ; } return retVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given proxy server exception pattern to this client . Origin servers whose hostname match the pattern do not communicate through the defualt proxy server . The pattern must contain zero or one stars ( * ) . A star must appear at either the beginning or the end of the pattern . A star matches zero or more characters . The following are valid patterns : <ul > <li > www . company . com : 80< / li > <li > * . company . com< / li > <li > www . company . * < / li > < / ul > [CODESPLIT] public void addProxyServerException ( String pattern ) { Assert . isNotNull ( pattern ) ; proxyServerExceptions . put ( pattern , pattern ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the context for the origin server at the given <code > URL< / code > . [CODESPLIT] public IContext getContext ( URL originServerUrl ) { Assert . isNotNull ( originServerUrl ) ; return ( IContext ) contexts . get ( originServerUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an <code > Enumeration< / code > over the origin server <code > URL< / code > s known to this client . The known origin server <code > URL< / code > s are gleaned from this client s mapped contexts and mapped proxy server <code > URL< / code > s . [CODESPLIT] public Enumeration getOriginServerUrls ( ) { final Enumeration enum1 = contexts . keys ( ) ; final Enumeration enum2 = proxyServerUrls . keys ( ) ; Enumeration e = new Enumeration ( ) { public boolean hasMoreElements ( ) { return enum1 . hasMoreElements ( ) || enum2 . hasMoreElements ( ) ; } public Object nextElement ( ) { if ( enum1 . hasMoreElements ( ) ) return enum1 . nextElement ( ) ; return enum2 . nextElement ( ) ; } } ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <code > URL< / code > of the proxy server that the origin server at the given <code > URL< / code > uses or <code > null< / code > if no proxy server is used . [CODESPLIT] public URL getProxyServerUrl ( URL originServerUrl ) { Assert . isNotNull ( originServerUrl ) ; return ( URL ) proxyServerUrls . get ( originServerUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends the given request to the server and returns the server s response . [CODESPLIT] public Response invoke ( Request request ) throws IOException { Assert . isNotNull ( request ) ; try { open ( ) ; URL resourceUrl = request . getResourceUrl ( ) ; URL originServerUrl = new URL ( resourceUrl . getProtocol ( ) , resourceUrl . getHost ( ) , resourceUrl . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ URL proxyServerUrl = getProxyServerUrl ( originServerUrl ) ; if ( proxyServerUrl == null && ! matchesProxyServerException ( originServerUrl ) ) { proxyServerUrl = getDefaultProxyServerUrl ( ) ; } IContext context = webDAVFactory . newContext ( request . getContext ( ) ) ; IContext defaultContext = getContext ( originServerUrl ) ; if ( defaultContext == null ) { defaultContext = getDefaultContext ( ) ; } if ( defaultContext != null ) { Enumeration e = defaultContext . keys ( ) ; while ( e . hasMoreElements ( ) ) { String key = ( String ) e . nextElement ( ) ; context . put ( key , defaultContext . get ( key ) ) ; } } if ( authority != null ) { authority . authorize ( request , null , context , proxyServerUrl , true ) ; authority . authorize ( request , null , context , proxyServerUrl , false ) ; } return invoke1 ( request , context , proxyServerUrl , originServerUrl , 0 , 0 ) ; } finally { request . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the context for the origin server at the given <code > URL< / code > . If the given context is <code > null< / code > the context for the specified origin server is removed . [CODESPLIT] public void setContext ( URL originServerUrl , IContext context ) { Assert . isNotNull ( originServerUrl ) ; if ( context == null ) contexts . remove ( originServerUrl ) ; else contexts . put ( originServerUrl , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the <code > URL< / code > of the proxy server that this client uses to communicate with the origin server at the given <code > URL< / code > . If the proxy server <code > URL< / code > is <code > null< / code > the default proxy server is used if the specified origin server does not match a proxy server exception pattern . [CODESPLIT] public void setProxyServerUrl ( URL originServerUrl , URL proxyServerUrl ) { Assert . isNotNull ( originServerUrl ) ; if ( proxyServerUrl == null ) proxyServerUrls . remove ( originServerUrl ) ; else proxyServerUrls . put ( originServerUrl , proxyServerUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this connection s <code > InputStream< / code > . [CODESPLIT] public InputStream getInputStream ( ) throws IOException { if ( is != null ) return is ; sendRequest ( ) ; String transferEncoding = responseHeader . getFieldValue ( \"Transfer-Encoding\" ) ; //$NON-NLS-1$ String contentLength = responseHeader . getFieldValue ( \"Content-Length\" ) ; //$NON-NLS-1$ if ( \"chunked\" . equalsIgnoreCase ( transferEncoding ) ) { //$NON-NLS-1$ is = new ChunkedInputStream ( ) ; } else if ( method . equals ( \"HEAD\" ) && statusCode == HTTP_OK ) { //$NON-NLS-1$ is = new LimitedInputStream ( 0 ) ; } else if ( contentLength != null ) { try { is = new LimitedInputStream ( Integer . parseInt ( contentLength ) ) ; } catch ( NumberFormatException e ) { throw new IOException ( e . getMessage ( ) ) ; } } else if ( ( statusCode >= 100 && statusCode < 200 ) || statusCode == HTTP_NO_CONTENT || statusCode == HTTP_NOT_MODIFIED ) { is = new LimitedInputStream ( 0 ) ; } else { closeConnection = true ; is = socketIn ; } return is ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this connection s <code > OutputStream< / code > . [CODESPLIT] public OutputStream getOutputStream ( ) throws IOException { if ( os != null ) return os ; String contentLength = requestHeader . getFieldValue ( \"Content-Length\" ) ; //$NON-NLS-1$ if ( sendChunked && httpVersion > 1.0 ) { os = new ChunkedOutputStream ( ) ; } else if ( contentLength != null ) { try { os = new LimitedOutputStream ( Integer . parseInt ( contentLength ) ) ; } catch ( NumberFormatException e ) { throw new IOException ( Policy . bind ( \"exception.malformedContentLength\" ) ) ; //$NON-NLS-1$ } } else { os = new CachedOutputStream ( ) ; return os ; } sendRequest ( ) ; return os ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the request header value associated with the given field name or <code > null< / code > if there is no such field name . [CODESPLIT] public String getRequestHeaderFieldValue ( String fieldName ) { Assert . isNotNull ( fieldName ) ; return requestHeader . getFieldValue ( fieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the response header field name at the given position or <code > null< / code > if there is no field name at that position . [CODESPLIT] public String getResponseHeaderFieldName ( int position ) throws IOException { Assert . isTrue ( position >= 0 ) ; sendRequest ( ) ; return responseHeader . getFieldName ( position ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the response header field value at the given position or <code > null< / code > if there is no value at that position . [CODESPLIT] public String getResponseHeaderFieldValue ( int position ) throws IOException { Assert . isTrue ( position >= 0 ) ; sendRequest ( ) ; return responseHeader . getFieldValue ( position ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the response header field value that is associated with the given field name or <code > null< / code > if there is no value associated with that field name . [CODESPLIT] public String getResponseHeaderFieldValue ( String fieldName ) throws IOException { Assert . isNotNull ( fieldName ) ; sendRequest ( ) ; return responseHeader . getFieldValue ( fieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the <code > URL< / code > of the proxy server this connection uses to communicate with the origin server . If <code > null< / code > is given no proxy server is used . [CODESPLIT] public void setProxyServerUrl ( URL proxyServerUrl ) { endRequest ( ) ; if ( proxyServerUrl == null && this . proxyServerUrl == null ) return ; boolean closeConnection = true ; if ( proxyServerUrl != null && this . proxyServerUrl != null ) { URL oldProxyServerUrl = null ; URL newProxyServerUrl = null ; try { oldProxyServerUrl = new URL ( this . proxyServerUrl . getProtocol ( ) , this . proxyServerUrl . getHost ( ) , this . proxyServerUrl . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ newProxyServerUrl = new URL ( proxyServerUrl . getProtocol ( ) , proxyServerUrl . getHost ( ) , proxyServerUrl . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ } catch ( MalformedURLException e ) { // ignore or log? } if ( oldProxyServerUrl . equals ( newProxyServerUrl ) ) { closeConnection = false ; } } if ( closeConnection ) { try { close ( ) ; } catch ( IOException e ) { // ignore or log? } } this . proxyServerUrl = proxyServerUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the request header value associated with the given field . [CODESPLIT] public void setRequestHeaderField ( String fieldName , String fieldValue ) { Assert . isNotNull ( fieldName ) ; Assert . isNotNull ( fieldValue ) ; endRequest ( ) ; requestHeader . addField ( fieldName , fieldValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the <code > URL< / code > of this connection s resource . [CODESPLIT] public void setResourceUrl ( URL resourceUrl ) { Assert . isNotNull ( resourceUrl ) ; endRequest ( ) ; URL oldOriginServerUrl = null ; URL newOriginServerUrl = null ; try { oldOriginServerUrl = new URL ( this . resourceUrl . getProtocol ( ) , this . resourceUrl . getHost ( ) , this . resourceUrl . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ newOriginServerUrl = new URL ( resourceUrl . getProtocol ( ) , resourceUrl . getHost ( ) , resourceUrl . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ } catch ( MalformedURLException e ) { // ignore? } if ( ! oldOriginServerUrl . equals ( newOriginServerUrl ) ) { try { close ( ) ; } catch ( IOException e ) { // ignore? } } this . resourceUrl = resourceUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the factory this connection uses to create sockets . If the given socket factory is <code > null< / code > the default socket is used . [CODESPLIT] public void setSocketFactory ( ISocketFactory socketFactory ) { endRequest ( ) ; if ( socketFactory == this . socketFactory ) return ; try { close ( ) ; } catch ( IOException e ) { // ignore? } this . socketFactory = socketFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the sample rule launcher file . [CODESPLIT] private void createRuleSampleLauncher ( IJavaProject project ) throws JavaModelException , IOException { Version version = startPage . getRuntime ( ) . getVersion ( ) ; if ( version . getMajor ( ) == 4 ) { createProjectJavaFile ( project , \"org/drools/eclipse/wizard/project/RuleLauncherSample_4.java.template\" , \"DroolsTest.java\" ) ; } else if ( version . getMajor ( ) == 5 ) { createProjectJavaFile ( project , \"org/drools/eclipse/wizard/project/RuleLauncherSample_5.java.template\" , \"DroolsTest.java\" ) ; } else if ( version . getMajor ( ) >= 6 ) { createProjectJavaFile ( project , \"org/drools/eclipse/wizard/project/RuleLauncherSample_6.java.template\" , \"DroolsTest.java\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the sample rule file . [CODESPLIT] private void createRule ( IJavaProject project , IProgressMonitor monitor ) throws CoreException { if ( startPage . getRuntime ( ) . getVersion ( ) . getMajor ( ) >= 6 ) { FileUtils . createFolder ( project , \"src/main/resources/com/sample/rules\" , monitor ) ; createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/Sample.drl.template\" , \"src/main/resources/com/sample/rules\" , \"Sample.drl\" ) ; } else { createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/Sample.drl.template\" , \"src/main/rules\" , \"Sample.drl\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the sample RuleFlow file . [CODESPLIT] private void createRuleFlow ( IJavaProject project , IProgressMonitor monitor ) throws CoreException { Version version = startPage . getRuntime ( ) . getVersion ( ) ; if ( version . getMajor ( ) == 4 ) { createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/ruleflow_4.rf.template\" , \"src/main/rules\" , \"ruleflow.rf\" ) ; createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/ruleflow_4.rfm.template\" , \"src/main/rules\" , \"ruleflow.rfm\" ) ; createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/ruleflow_4.drl.template\" , \"src/main/rules\" , \"ruleflow.drl\" ) ; } else if ( version . getMajor ( ) == 5 && version . getMinor ( ) == 0 ) { createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/ruleflow.rf.template\" , \"src/main/rules\" , \"ruleflow.rf\" ) ; } else if ( version . getMajor ( ) == 5 ) { createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/sample.bpmn.template\" , \"src/main/rules\" , \"sample.bpmn\" ) ; } else { FileUtils . createFolder ( project , \"src/main/resources/com/sample/process\" , monitor ) ; createProjectFile ( project , monitor , \"org/drools/eclipse/wizard/project/sample.bpmn.template\" , \"src/main/resources/com/sample/process\" , \"sample.bpmn\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the sample RuleFlow launcher file . [CODESPLIT] private void createRuleFlowSampleLauncher ( IJavaProject project ) throws JavaModelException , IOException { String s ; Version version = startPage . getRuntime ( ) . getVersion ( ) ; if ( version . getMajor ( ) == 4 ) { s = \"org/drools/eclipse/wizard/project/RuleFlowLauncherSample_4.java.template\" ; } else if ( version . getMajor ( ) == 5 && version . getMinor ( ) == 0 ) { s = \"org/drools/eclipse/wizard/project/RuleFlowLauncherSample.java.template\" ; } else if ( version . getMajor ( ) == 5 ) { s = \"org/drools/eclipse/wizard/project/ProcessLauncherSample_bpmn_5.java.template\" ; } else { s = \"org/drools/eclipse/wizard/project/ProcessLauncherSample_bpmn_6.java.template\" ; } createProjectJavaFile ( project , s , \"ProcessTest.java\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected IKieProjectWizardPage createStartPage ( String pageId ) { return new AbstractKieProjectStartWizardPage ( pageId ) { @ Override public String getTitle ( ) { return \"Create New Drools Project\" ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns only the installable units that are features ignoring feature groups . [CODESPLIT] public List < IInstallableUnit > getSelectedIUs ( ) { List < IInstallableUnit > result = new ArrayList < IInstallableUnit > ( ) ; for ( Object o : getCheckedElements ( ) ) { if ( o instanceof IUTreeItem ) { IUTreeItem item = ( IUTreeItem ) o ; if ( item . parent != null ) result . add ( item . iu ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void run ( IAction action ) { assert ( targetPart != null && selectedItems != null ) ; AddResourceWizard wiz = new AddResourceWizard ( ) ; wiz . init ( Activator . getDefault ( ) . getWorkbench ( ) , selectedItems ) ; WizardDialog dialog = new WizardDialog ( targetPart . getSite ( ) . getShell ( ) , wiz ) ; dialog . create ( ) ; if ( dialog . open ( ) == WizardDialog . OK ) { PlatformUtils . refreshRepositoryView ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the content of this editor to the given stream . Possible formats are for example SWT . IMAGE_BMP IMAGE_GIF IMAGE_JPEG IMAGE_PNG . [CODESPLIT] public void createImage ( OutputStream stream , int format ) { SWTGraphics g = null ; GC gc = null ; Image image = null ; LayerManager layerManager = ( LayerManager ) getGraphicalViewer ( ) . getEditPartRegistry ( ) . get ( LayerManager . ID ) ; IFigure figure = layerManager . getLayer ( LayerConstants . PRINTABLE_LAYERS ) ; Rectangle r = figure . getBounds ( ) ; try { image = new Image ( Display . getDefault ( ) , r . width , r . height ) ; gc = new GC ( image ) ; g = new SWTGraphics ( gc ) ; g . translate ( r . x * - 1 , r . y * - 1 ) ; figure . paint ( g ) ; ImageLoader imageLoader = new ImageLoader ( ) ; imageLoader . data = new ImageData [ ] { image . getImageData ( ) } ; imageLoader . save ( stream , format ) ; } catch ( Throwable t ) { DroolsEclipsePlugin . log ( t ) ; } finally { if ( g != null ) { g . dispose ( ) ; } if ( gc != null ) { gc . dispose ( ) ; } if ( image != null ) { image . dispose ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy all the default values into the receiver . [CODESPLIT] public void collapse ( ) { if ( defaults != null ) { Enumeration keysEnum = defaults . keys ( ) ; while ( keysEnum . hasMoreElements ( ) ) { Object key = keysEnum . nextElement ( ) ; localValues . put ( key , defaults . get ( key ) ) ; } defaults = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value for the given key . [CODESPLIT] public Object get ( Object key ) { Object value = localValues . get ( key ) ; if ( value == null && defaults != null ) return defaults . get ( key ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an enumeration over the context s keys . ( recursively computes the keys based on keys defaults as well ) [CODESPLIT] public Enumeration keys ( ) { if ( defaults == null ) return localValues . keys ( ) ; return new MergedEnumeration ( localValues . keys ( ) , defaults . keys ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void run ( IAction action ) { assert ( selectedItems != null ) ; for ( Iterator it = selectedItems . iterator ( ) ; it . hasNext ( ) ; ) { Object oneItem = it . next ( ) ; if ( oneItem instanceof IFile ) { processUpdate ( ( IFile ) oneItem ) ; } } PlatformUtils . updateDecoration ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Object loadAdapter ( Class adapter , IProgressMonitor monitor ) { // TODO Auto-generated method stub return server . loadAdapter ( adapter , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public IStatus canModifyModules ( IModule [ ] add , IModule [ ] remove , IProgressMonitor monitor ) { // TODO Auto-generated method stub return server . canModifyModules ( add , remove , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public String getAttribute ( String attributeName , String defaultValue ) { // TODO Auto-generated method stub return server . getAttribute ( attributeName , defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Map getAttribute ( String attributeName , Map defaultValue ) { // TODO Auto-generated method stub return server . getAttribute ( attributeName , defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public IModule [ ] getChildModules ( IModule [ ] module , IProgressMonitor monitor ) { // TODO Auto-generated method stub return server . getChildModules ( module , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public IModule [ ] getRootModules ( IModule module , IProgressMonitor monitor ) throws CoreException { // TODO Auto-generated method stub return server . getRootModules ( module , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public IStatus publish ( int kind , IProgressMonitor monitor ) { // TODO Auto-generated method stub return server . publish ( kind , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void publish ( int kind , List < IModule [ ] > modules , IAdaptable info , IOperationListener listener ) { // TODO Auto-generated method stub server . publish ( kind , modules , info , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void start ( String launchMode , IProgressMonitor monitor ) throws CoreException { // TODO Auto-generated method stub server . start ( launchMode , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void start ( String launchMode , IOperationListener listener ) { // TODO Auto-generated method stub server . start ( launchMode , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void restart ( String launchMode , IProgressMonitor monitor ) { // TODO Auto-generated method stub server . restart ( launchMode , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void restart ( String launchMode , IOperationListener listener ) { // TODO Auto-generated method stub server . restart ( launchMode , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public IStatus canControlModule ( IModule [ ] module , IProgressMonitor monitor ) { // TODO Auto-generated method stub return server . canControlModule ( module , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public IStatus canRestartModule ( IModule [ ] module , IProgressMonitor monitor ) { // TODO Auto-generated method stub return server . canRestartModule ( module , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public IStatus canPublishModule ( IModule [ ] module , IProgressMonitor monitor ) { // TODO Auto-generated method stub return server . canPublishModule ( module , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void startModule ( IModule [ ] module , IOperationListener listener ) { // TODO Auto-generated method stub server . startModule ( module , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void stopModule ( IModule [ ] module , IOperationListener listener ) { // TODO Auto-generated method stub server . stopModule ( module , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void restartModule ( IModule [ ] module , IOperationListener listener ) { // TODO Auto-generated method stub server . restartModule ( module , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public ILaunchConfiguration getLaunchConfiguration ( boolean create , IProgressMonitor monitor ) throws CoreException { // TODO Auto-generated method stub return server . getLaunchConfiguration ( create , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void synchronousStart ( String launchMode , IProgressMonitor monitor ) throws CoreException { // TODO Auto-generated method stub server . synchronousStart ( launchMode , monitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String getHtml ( ) { AlphaNodeFieldConstraint constraint = this . node . getConstraint ( ) ; if ( constraint instanceof MvelConstraint ) { MvelConstraint mvelConstraint = ( MvelConstraint ) constraint ; return NODE_NAME + \"<BR/>expression : \" + mvelConstraint . toString ( ) ; } return NODE_NAME + \"<BR/>\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constraint has field extractor and this method is returning fieldName it . [CODESPLIT] public String getFieldName ( ) { AlphaNodeFieldConstraint constraint = this . node . getConstraint ( ) ; if ( constraint instanceof MvelConstraint ) { MvelConstraint mvelConstraint = ( MvelConstraint ) constraint ; InternalReadAccessor accessor = mvelConstraint . getFieldExtractor ( ) ; if ( accessor instanceof ClassFieldReader ) { return ( ( ClassFieldReader ) accessor ) . getFieldName ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constraint s evaluator string [CODESPLIT] public String getEvaluator ( ) { AlphaNodeFieldConstraint constraint = this . node . getConstraint ( ) ; if ( constraint instanceof MvelConstraint ) { MvelConstraint mvelConstraint = ( MvelConstraint ) constraint ; return mvelConstraint . toString ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constraint field string [CODESPLIT] public String getValue ( ) { AlphaNodeFieldConstraint constraint = this . node . getConstraint ( ) ; if ( constraint instanceof MvelConstraint ) { MvelConstraint mvelConstraint = ( MvelConstraint ) constraint ; FieldValue field = mvelConstraint . getField ( ) ; return field != null ? field . toString ( ) : null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void run ( IAction action ) { assert ( selectedItems != null ) ; for ( Iterator it = selectedItems . iterator ( ) ; it . hasNext ( ) ; ) { Object oneSelection = it . next ( ) ; if ( oneSelection instanceof IFile ) { GuvnorMetadataUtils . commitFileChanges ( ( IFile ) oneSelection ) ; } } PlatformUtils . updateDecoration ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void selectionChanged ( IAction action , ISelection selection ) { boolean validResourceSet = ActionUtils . checkResourceSet ( selection , true ) && ActionUtils . areFilesDirty ( selection ) ; if ( validResourceSet ) { action . setEnabled ( true ) ; selectedItems = ( IStructuredSelection ) selection ; } else { action . setEnabled ( false ) ; selectedItems = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setSessionAuthenticator ( IAuthenticator sessionAuthen ) { if ( sessionAuthen != null ) { client . getHttpClient ( ) . setAuthenticator ( sessionAuthen ) ; } else { client . getHttpClient ( ) . setAuthenticator ( platformAuthenticator ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public IContext createContext ( ) { IContext context = WebDAVFactory . contextFactory . newContext ( ) ; // Need to make sure the USER-AGENT header is present for Guvnor context . put ( \"USER-AGENT\" , \"guvnor\" ) ; //$NON-NLS-1$ //$NON-NLS-2$ return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Map < String , ResourceProperties > listDirectory ( String path ) throws Exception { IResponse response = null ; try { IContext context = createContext ( ) ; context . put ( \"Depth\" , \"1\" ) ; //$NON-NLS-1$ //$NON-NLS-2$ ILocator locator = WebDAVFactory . locatorFactory . newLocator ( path ) ; response = client . propfind ( locator , context , null ) ; if ( response . getStatusCode ( ) != IResponse . SC_MULTI_STATUS ) { throw new WebDavException ( response ) ; } Map < String , ResourceProperties > res = StreamProcessingUtils . parseListing ( path , response . getInputStream ( ) ) ; addGuvnorResourceProperties ( res , path ) ; return res ; } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ResourceProperties queryProperties ( String resource ) throws Exception { IResponse response = null ; try { IContext context = createContext ( ) ; context . put ( \"Depth\" , \"1\" ) ; //$NON-NLS-1$ //$NON-NLS-2$ ILocator locator = WebDAVFactory . locatorFactory . newLocator ( resource ) ; response = client . propfind ( locator , context , null ) ; if ( response . getStatusCode ( ) != IResponse . SC_MULTI_STATUS && response . getStatusCode ( ) != IResponse . SC_OK ) { throw new WebDavException ( response ) ; } Map < String , ResourceProperties > props = StreamProcessingUtils . parseListing ( \"\" , response . getInputStream ( ) ) ; //$NON-NLS-1$ if ( props . keySet ( ) . size ( ) != 1 ) { throw new Exception ( props . keySet ( ) . size ( ) + \" entries found for \" + resource ) ; //$NON-NLS-1$ } String fullpath = props . keySet ( ) . iterator ( ) . next ( ) ; ResourceProperties res = props . get ( fullpath ) ; String filename = new Path ( fullpath ) . lastSegment ( ) ; addGuvnorResourceProperties ( res , filename , resource ) ; return res ; } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds Guvnor - specific resource properties to the collection . [CODESPLIT] private void addGuvnorResourceProperties ( ResourceProperties props , String filename , String resource ) throws Exception { if ( props == null ) { return ; } IResponse response = null ; try { String path = resource . substring ( 0 , resource . lastIndexOf ( ' ' ) ) ; String apiVer = changeToAPICall ( path ) ; Properties guvProps = new Properties ( ) ; response = getResourceInputStream ( apiVer ) ; guvProps . load ( response . getInputStream ( ) ) ; String val = guvProps . getProperty ( filename ) ; if ( val != null ) { StringTokenizer tokens = new StringTokenizer ( val , \",\" ) ; //$NON-NLS-1$ //                String dateStamp = tokens.nextToken(); //                String revision = tokens.nextToken(); if ( tokens . hasMoreElements ( ) ) { props . setLastModifiedDate ( tokens . nextToken ( ) ) ; } if ( tokens . hasMoreElements ( ) ) { props . setRevision ( tokens . nextToken ( ) ) ; } } else { Exception nfe = new Exception ( \"Failed to get Guvnor properties for \" + filename ) ; //$NON-NLS-1$ Activator . getDefault ( ) . writeLog ( IStatus . WARNING , nfe . getMessage ( ) , nfe ) ; } } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String getResourceContents ( String resource ) throws Exception { IResponse response = null ; try { response = getResourceInputStream ( resource ) ; return StreamProcessingUtils . getStreamContents ( response . getInputStream ( ) ) ; } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String getResourceVersionContents ( String resource , String version ) throws Exception { String apiVer = changeToAPICall ( resource ) + \"?version=\" + version ; //$NON-NLS-1$ return getResourceContents ( apiVer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public IResponse getResourceInputStream ( String resource ) throws Exception { ILocator locator = WebDAVFactory . locatorFactory . newLocator ( resource ) ; IResponse response = client . get ( locator , createContext ( ) ) ; if ( response . getStatusCode ( ) != IResponse . SC_OK ) { throw new WebDavException ( response ) ; } return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public IResponse getResourceVersionInputStream ( String resource , String version ) throws Exception { String apiVer = changeToAPICall ( resource ) + \"?version=\" + version ; //$NON-NLS-1$ return getResourceInputStream ( apiVer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean createResource ( String resource , InputStream is ) throws Exception { return createResource ( resource , is , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean createResource ( String resource , InputStream is , boolean overwrite ) throws Exception { boolean res = true ; if ( ! overwrite ) { try { if ( queryProperties ( resource ) != null ) { res = false ; } } catch ( WebDavException e ) { if ( e . getErrorCode ( ) != IResponse . SC_NOT_FOUND ) { throw e ; } } } IResponse response = null ; try { if ( res ) { ILocator locator = WebDAVFactory . locatorFactory . newLocator ( resource ) ; response = client . put ( locator , createContext ( ) , is ) ; if ( response . getStatusCode ( ) != IResponse . SC_OK && response . getStatusCode ( ) != IResponse . SC_CREATED ) { throw new WebDavException ( response ) ; } } } finally { if ( response != null ) { response . close ( ) ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void putResource ( String resource , InputStream is ) throws Exception { IResponse response = null ; try { ILocator locator = WebDAVFactory . locatorFactory . newLocator ( resource ) ; response = client . put ( locator , createContext ( ) , is ) ; if ( response . getStatusCode ( ) != IResponse . SC_OK && response . getStatusCode ( ) != IResponse . SC_NO_CONTENT && response . getStatusCode ( ) != IResponse . SC_CREATED ) { throw new WebDavException ( response ) ; } } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public IResponse getResourceVersions ( String resource ) throws Exception { String apiVer = changeToAPICall ( resource ) + \"?version=all\" ; //$NON-NLS-1$ return getResourceInputStream ( apiVer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void deleteResource ( String resource ) throws Exception { IResponse response = null ; try { ILocator locator = WebDAVFactory . locatorFactory . newLocator ( resource ) ; response = client . delete ( locator , createContext ( ) ) ; if ( response . getStatusCode ( ) != IResponse . SC_NO_CONTENT && response . getStatusCode ( ) != IResponse . SC_OK ) { throw new WebDavException ( response ) ; } } finally { if ( response != null ) { response . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void run ( IAction action ) { if ( selectedItems == null ) { return ; } String msg = null ; if ( selectedItems . size ( ) == 1 ) { msg = MessageFormat . format ( Messages . getString ( \"delete.singlefile.confirmation\" ) , //$NON-NLS-1$ new Object [ ] { ( ( IFile ) selectedItems . getFirstElement ( ) ) . getName ( ) } ) ; } else { msg = MessageFormat . format ( Messages . getString ( \"delete.multifile.confirmation\" ) , //$NON-NLS-1$ new Object [ ] { String . valueOf ( selectedItems . size ( ) ) } ) ; } if ( ! MessageDialog . openConfirm ( targetPart . getSite ( ) . getShell ( ) , Messages . getString ( \"delete.confirmation.dialog.caption\" ) , msg ) ) { //$NON-NLS-1$ return ; } for ( Iterator it = selectedItems . iterator ( ) ; it . hasNext ( ) ; ) { Object oneItem = it . next ( ) ; if ( oneItem instanceof IFile ) { processDelete ( ( IFile ) oneItem ) ; } } DisconnectAction dsAction = new DisconnectAction ( ) ; dsAction . disconnect ( selectedItems ) ; PlatformUtils . updateDecoration ( ) ; PlatformUtils . refreshRepositoryView ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new version - controlled configuration on the given baseline . [CODESPLIT] public void baselineControl ( ILocator baseline ) throws DAVException { Assert . isNotNull ( baseline ) ; // Build the document body to describe the baseline control element. Document document = newDocument ( ) ; Element root = ElementEditor . create ( document , \"baseline-control\" ) ; //$NON-NLS-1$ ElementEditor . addChild ( root , \"baseline\" , //$NON-NLS-1$ baseline . getResourceURL ( ) , new String [ ] { \"baseline\" } , //$NON-NLS-1$ true ) ; // Send the baseline control method to the server and check the response. IResponse response = null ; try { response = davClient . baselineControl ( locator , newContext ( ) , document ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the given member in this collection to the resource identified by the given source locator . If the member already exists or is already bound to a resource it is not replaced . [CODESPLIT] public void bind ( String member , ILocator source ) throws DAVException { bind ( member , source , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the given member in this collection to the resource identified by the given source locator . If overwrite is <code > false< / code > and such a member already exists or such a member is already bound to a resource it is not replaced . Otherwise if overwrite is <code > true< / code > and such a member already exists or such a member is already bound to a resource it is replaced . [CODESPLIT] public void bind ( String member , ILocator source , boolean overwrite ) throws DAVException { IContext context = newContext ( ) ; context . setOverwrite ( overwrite ) ; ILocator destination = getMember ( member ) ; IResponse response = null ; try { response = davClient . bind ( source , destination , context ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the locator of the member of this collection with the given name . Does NOT perform a call to the server to check the existence of the member . [CODESPLIT] public ILocator getMember ( String memberName ) { Assert . isTrue ( locator . getLabel ( ) == null ) ; Assert . isTrue ( ! locator . isStable ( ) ) ; String parentName = locator . getResourceURL ( ) ; String childName ; if ( parentName . endsWith ( \"/\" ) ) //$NON-NLS-1$ childName = parentName + memberName ; else childName = parentName + \"/\" + memberName ; //$NON-NLS-1$ return davClient . getDAVFactory ( ) . newLocator ( childName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a set of handles representing the members of this collection . <p > Each member of the set will be typed to be a <code > ResourceHandle< / code > or a <code > CollectionHandle< / code > depending upon whether it implements collection semantics . Note that workspaces will be returned as regular collection handles and should be converted to workspace handles if required ( test using isWorkspace () ) . < / p > [CODESPLIT] public Set getMembers ( ) throws DAVException { // Query the DAV:resource-type property to depth one. Collection querySet = new Vector ( ) ; querySet . add ( DAV_RESOURCE_TYPE ) ; URLTable resourceTable = getProperties ( querySet , IContext . DEPTH_ONE ) ; // Create a collection for the reply, and remove // ourselves from the answer. Set reply = new HashSet ( ) ; try { resourceTable . remove ( locator . getResourceURL ( ) ) ; } catch ( MalformedURLException exception ) { throw new DAVException ( Policy . bind ( \"exception.malformedLocator\" ) ) ; //$NON-NLS-1$ } // The keys of the result correspond to the receiver's internal members. Enumeration resourceNameEnum = resourceTable . keys ( ) ; while ( resourceNameEnum . hasMoreElements ( ) ) { URL url = ( URL ) resourceNameEnum . nextElement ( ) ; // Get the props for that resource Hashtable propertyTable = ( Hashtable ) resourceTable . get ( url ) ; Assert . isNotNull ( propertyTable ) ; PropertyStatus propertyStatus = ( PropertyStatus ) propertyTable . get ( DAV_RESOURCE_TYPE ) ; Assert . isNotNull ( propertyStatus ) ; // If we have a DAV:collection element, then create a collection handle, // all other resource types are created as regular resource handles. ILocator newLocator = davClient . getDAVFactory ( ) . newLocator ( url . toString ( ) ) ; Element property = propertyStatus . getProperty ( ) ; try { if ( ElementEditor . hasChild ( property , DAV_COLLECTION_RESOURCE_TYPE ) ) reply . add ( new CollectionHandle ( davClient , newLocator ) ) ; else reply . add ( new ResourceHandle ( davClient , newLocator ) ) ; } catch ( MalformedElementException exception ) { throw new SystemException ( exception ) ; } } // end-while return reply ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Optimizing vertices for optimal presentation [CODESPLIT] public void optimize ( ) { final List < BaseVertex > sorted = new ArrayList < BaseVertex > ( this . vertices ) ; Collections . sort ( sorted , new Comparator < BaseVertex > ( ) { public int compare ( final BaseVertex v1 , final BaseVertex v2 ) { int v1OutDegree = v1 . getSourceConnections ( ) . size ( ) ; int v2OutDegree = v2 . getSourceConnections ( ) . size ( ) ; if ( v1OutDegree < v2OutDegree ) { return 1 ; } if ( v1OutDegree > v2OutDegree ) { return - 1 ; } return 0 ; } } ) ; final LinkedList < BaseVertex > optimized = new LinkedList < BaseVertex > ( ) ; boolean front = false ; for ( final Iterator < BaseVertex > vertexIter = sorted . iterator ( ) ; vertexIter . hasNext ( ) ; ) { final BaseVertex vertex = vertexIter . next ( ) ; if ( front ) { optimized . addFirst ( vertex ) ; } else { optimized . addLast ( vertex ) ; } front = ! front ; } this . vertices = optimized ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authorizes the given request by setting its authorization credentials in the given context . If the given response is not <code > null< / code > it is assumed to contain an authenticate challenge that is used to derive the authorization credentials . Returns true if the authorization succeeds and false otherwise . [CODESPLIT] public boolean authorize ( Request request , IResponse response , IContext context , URL proxyServerUrl , boolean isProxyAuthorization ) { Assert . isNotNull ( request ) ; Assert . isNotNull ( context ) ; URL serverUrl = null ; URL protectionSpaceUrl = null ; if ( isProxyAuthorization ) { if ( proxyServerUrl == null ) { return false ; } serverUrl = proxyServerUrl ; protectionSpaceUrl = proxyServerUrl ; } else { URL resourceUrl = request . getResourceUrl ( ) ; try { serverUrl = new URL ( resourceUrl . getProtocol ( ) , resourceUrl . getHost ( ) , resourceUrl . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ } catch ( MalformedURLException e ) { return false ; } protectionSpaceUrl = resourceUrl ; } if ( response != null ) { String challengeString = null ; if ( isProxyAuthorization ) { challengeString = response . getContext ( ) . getProxyAuthenticate ( ) ; } else { challengeString = response . getContext ( ) . getWWWAuthenticate ( ) ; } if ( challengeString == null ) { return false ; } AuthenticateChallenge challenge = null ; try { challenge = new AuthenticateChallenge ( challengeString ) ; } catch ( ParserException e ) { return false ; } String authScheme = challenge . getAuthScheme ( ) ; String realm = challenge . getRealm ( ) ; AuthorizationAuthority authority = getAuthorizationAuthority ( authScheme ) ; if ( authority == null ) { return false ; } Map oldInfo = authenticatorStore . getAuthenticationInfo ( serverUrl , realm , authScheme ) ; Map info = authority . getAuthenticationInfo ( challenge , oldInfo , serverUrl , protectionSpaceUrl ) ; if ( info == null ) { return false ; } authenticatorStore . addAuthenticationInfo ( serverUrl , realm , authScheme , info ) ; authenticatorStore . addProtectionSpace ( protectionSpaceUrl , realm ) ; } String realm = authenticatorStore . getProtectionSpace ( protectionSpaceUrl ) ; if ( realm == null ) { return false ; } Map info = null ; String authScheme = null ; for ( int i = 0 ; i < authenticationSchemes . length ; ++ i ) { authScheme = authenticationSchemes [ i ] ; info = authenticatorStore . getAuthenticationInfo ( serverUrl , realm , authScheme ) ; if ( info != null ) { break ; } } if ( info == null ) { return false ; } AuthorizationAuthority authority = getAuthorizationAuthority ( authScheme ) ; if ( authority == null ) { return false ; } String authorization = authority . getAuthorization ( request , info , serverUrl , protectionSpaceUrl , proxyServerUrl ) ; if ( authorization == null ) { return false ; } if ( isProxyAuthorization ) { if ( authorization . equals ( context . getProxyAuthorization ( ) ) ) return false ; // we already had that auth so it must've failed context . setProxyAuthorization ( authorization ) ; } else { if ( authorization . equals ( context . getAuthorization ( ) ) ) return false ; // we already had that auth so it must've failed context . setAuthorization ( authorization ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Confirms whether the given response is valid by proving the server knows the client s authentication secret ( password ) . Moreover the server may wish to communicate some authentication information in the response for the purposes of authorizing future request . [CODESPLIT] public boolean confirm ( Request request , IResponse response , URL proxyServerUrl ) { Assert . isNotNull ( request ) ; Assert . isNotNull ( response ) ; URL resourceUrl = request . getResourceUrl ( ) ; URL serverUrl = null ; try { serverUrl = new URL ( resourceUrl . getProtocol ( ) , resourceUrl . getHost ( ) , resourceUrl . getPort ( ) , \"/\" ) ; //$NON-NLS-1$ } catch ( MalformedURLException e ) { return false ; } String realm = authenticatorStore . getProtectionSpace ( resourceUrl ) ; if ( realm == null ) { return false ; } Map info = null ; String authScheme = null ; for ( int i = 0 ; i < authenticationSchemes . length ; ++ i ) { authScheme = authenticationSchemes [ i ] ; info = authenticatorStore . getAuthenticationInfo ( serverUrl , realm , authScheme ) ; if ( info != null ) { break ; } } if ( info == null ) { return false ; } AuthorizationAuthority authority = getAuthorizationAuthority ( authScheme ) ; if ( authority == null ) { return false ; } return authority . confirmResponse ( request , response , proxyServerUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Confirms whether the given response is valid by proving the server knows the client s authentication secret ( password ) . Moreover the server may wish to communicate some authentication information in the response for the purposes of authorizing future request . <p > This method should be overridden by schema specific authenticators . [CODESPLIT] protected boolean confirmResponse ( Request request , IResponse response , URL proxyServerUrl ) { Assert . isNotNull ( request ) ; Assert . isNotNull ( response ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the new authentication information gleaned from the given authenticate challenge and the given old authentication information . The old authentication information may be <code > null< / code > . The authentication information usually contains directives such as usernames and passwords . <p > This method should be overridden by schema specific authenticators . [CODESPLIT] protected Map getAuthenticationInfo ( AuthenticateChallenge challenge , Map oldInfo , URL serverUrl , URL protectionSpaceUrl ) { Assert . isNotNull ( challenge ) ; Assert . isNotNull ( serverUrl ) ; Assert . isNotNull ( protectionSpaceUrl ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the authorization credentials for the given request . The authorization credentials are derived from the given authentication info . The authentication info may contain directives such as usernames and passwords . <p > This method should be overridden by schema specific authenticators . [CODESPLIT] protected String getAuthorization ( Request request , Map info , URL serverUrl , URL protectionSpaceUrl , URL proxyServerUrl ) { Assert . isNotNull ( request ) ; Assert . isNotNull ( info ) ; Assert . isNotNull ( serverUrl ) ; Assert . isNotNull ( protectionSpaceUrl ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an authorization authority for the given authentication scheme or <code > null< / code > if there is no such authority . [CODESPLIT] private AuthorizationAuthority getAuthorizationAuthority ( String scheme ) { try { scheme = Character . toUpperCase ( scheme . charAt ( 0 ) ) + scheme . substring ( 1 ) . toLowerCase ( ) ; String packageName = \"org.eclipse.webdav.internal.authentication\" ; //$NON-NLS-1$ String className = scheme + \"Authority\" ; //$NON-NLS-1$ Class clazz = Class . forName ( packageName + \".\" + className ) ; //$NON-NLS-1$ Constructor constructor = clazz . getConstructor ( new Class [ ] { IAuthenticator . class } ) ; return ( AuthorizationAuthority ) constructor . newInstance ( new Object [ ] { authenticatorStore } ) ; } catch ( ClassCastException e ) { // ignore or log? } catch ( Exception e ) { // ignore or log? } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the MD5 hash value of the given <code > String< / code > and returns the result as a HEX <code > String< / code > . [CODESPLIT] protected String md5 ( String s ) throws NoSuchAlgorithmException , UnsupportedEncodingException { MessageDigest md5 = MessageDigest . getInstance ( \"MD5\" ) ; //$NON-NLS-1$ byte [ ] hash = md5 . digest ( s . getBytes ( \"UTF8\" ) ) ; //$NON-NLS-1$ return HexConverter . toHex ( hash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the MD5 hash value of the body of the given request and returns the result as a HEX <code > String< / code > . [CODESPLIT] protected String md5 ( Request request ) throws NoSuchAlgorithmException , IOException { DigestOutputStream dos = new DigestOutputStream ( \"MD5\" ) ; //$NON-NLS-1$ request . write ( dos ) ; String result = HexConverter . toHex ( dos . digest ( ) ) ; dos . close ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the given <code > String< / code > with its quotes removed . [CODESPLIT] protected String unquote ( String s ) { if ( s . charAt ( 0 ) == ' ' && s . charAt ( s . length ( ) - 1 ) == ' ' ) //$NON-NLS-1$ //$NON-NLS-2$ return s . substring ( 1 , s . length ( ) - 1 ) ; return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ConditionFactor ( either a StateToken or EntityTag ) by parsing the tokenizer contining an If header value . [CODESPLIT] public static ConditionFactor create ( StreamTokenizer tokenizer ) throws WebDAVException { boolean not = false ; ConditionFactor factor = null ; try { int token = tokenizer . ttype ; if ( token == StreamTokenizer . TT_WORD ) { if ( tokenizer . sval . equalsIgnoreCase ( \"Not\" ) ) { //$NON-NLS-1$ not = true ; } else { throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissingNot\" ) ) ; //$NON-NLS-1$ } token = tokenizer . nextToken ( ) ; } switch ( token ) { case ' ' : factor = StateToken . create ( tokenizer ) ; break ; case ' ' : factor = EntityTag . create ( tokenizer ) ; break ; default : throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissingOpen\" , String . valueOf ( token ) ) ) ; //$NON-NLS-1$ } } catch ( IOException exc ) { // ignore or log? } factor . setNot ( not ) ; return factor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repository [CODESPLIT] @ Override public void createRepository ( final IKieRepositoryHandler repository ) throws IOException { runJob ( \"Request to create repository '\" + repository . getName ( ) + \"'\" , new Requester . Action ( ) { @ Override public String execute ( ) throws IOException { return httpPost ( \"spaces/\" + repository . getParent ( ) . getName ( ) + \"/projects/\" , repository . getProperties ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the controls of this dialog . [CODESPLIT] private void initializeControls ( ) { if ( originalFile != null ) { resourceGroup . setContainerFullPath ( originalFile . getParent ( ) . getFullPath ( ) ) ; String fileName = originalFile . getName ( ) ; int index = fileName . lastIndexOf ( \".\" ) ; if ( index != - 1 ) { fileName = fileName . substring ( 0 , index ) ; } fileName += \"-image.png\" ; resourceGroup . setResource ( fileName ) ; } else if ( originalName != null ) { resourceGroup . setResource ( originalName ) ; } setDialogComplete ( validatePage ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) Method declared on Dialog . [CODESPLIT] protected void okPressed ( ) { // Get new path. IPath path = resourceGroup . getContainerFullPath ( ) . append ( resourceGroup . getResource ( ) ) ; //If the user does not supply a file extension and if the save  //as dialog was provided a default file name append the extension  //of the default filename to the new name if ( path . getFileExtension ( ) == null ) { if ( originalFile != null && originalFile . getFileExtension ( ) != null ) { path = path . addFileExtension ( originalFile . getFileExtension ( ) ) ; } else if ( originalName != null ) { int pos = originalName . lastIndexOf ( ' ' ) ; if ( ++ pos > 0 && pos < originalName . length ( ) ) { path = path . addFileExtension ( originalName . substring ( pos ) ) ; } } } // If the path already exists then confirm overwrite. IFile file = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getFile ( path ) ; if ( file . exists ( ) ) { String [ ] buttons = new String [ ] { IDialogConstants . YES_LABEL , IDialogConstants . NO_LABEL , IDialogConstants . CANCEL_LABEL } ; String question = NLS . bind ( IDEWorkbenchMessages . SaveAsDialog_overwriteQuestion , path . toString ( ) ) ; MessageDialog d = new MessageDialog ( getShell ( ) , IDEWorkbenchMessages . Question , null , question , MessageDialog . QUESTION , buttons , 0 ) ; int overwrite = d . open ( ) ; switch ( overwrite ) { case 0 : // Yes break ; case 1 : // No return ; case 2 : // Cancel default : cancelPressed ( ) ; return ; } } // Store path and close. result = path ; close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether this page s visual components all contain valid values . [CODESPLIT] private boolean validatePage ( ) { if ( ! resourceGroup . areAllValuesValid ( ) ) { if ( ! resourceGroup . getResource ( ) . equals ( \"\" ) ) { //$NON-NLS-1$ setErrorMessage ( resourceGroup . getProblemMessage ( ) ) ; } else { setErrorMessage ( null ) ; } return false ; } String resourceName = resourceGroup . getResource ( ) ; IWorkspace workspace = ResourcesPlugin . getWorkspace ( ) ; // Do not allow a closed project to be selected IPath fullPath = resourceGroup . getContainerFullPath ( ) ; if ( fullPath != null ) { String projectName = fullPath . segment ( 0 ) ; IStatus isValidProjectName = workspace . validateName ( projectName , IResource . PROJECT ) ; if ( isValidProjectName . isOK ( ) ) { IProject project = workspace . getRoot ( ) . getProject ( projectName ) ; if ( ! project . isOpen ( ) ) { setErrorMessage ( IDEWorkbenchMessages . SaveAsDialog_closedProjectMessage ) ; return false ; } } } IStatus result = workspace . validateName ( resourceName , IResource . FILE ) ; if ( ! result . isOK ( ) ) { setErrorMessage ( result . getMessage ( ) ) ; return false ; } setErrorMessage ( null ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) @see org . eclipse . jface . window . Dialog#getDialogBoundsSettings () [CODESPLIT] protected IDialogSettings getDialogBoundsSettings ( ) { IDialogSettings settings = IDEWorkbenchPlugin . getDefault ( ) . getDialogSettings ( ) ; IDialogSettings section = settings . getSection ( DIALOG_SETTINGS_SECTION ) ; if ( section == null ) { section = settings . addNewSection ( DIALOG_SETTINGS_SECTION ) ; } return section ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an EntityTag by parsing the given If header as defined by section 3 . 11 of the HTTP / 1 . 1 spec . [CODESPLIT] public static ConditionFactor create ( StreamTokenizer tokenizer ) throws WebDAVException { EntityTag entityTag = new EntityTag ( ) ; try { int token = tokenizer . ttype ; if ( token == ' ' ) token = tokenizer . nextToken ( ) ; else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \"[\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ if ( token == ' ' ) { //$NON-NLS-1$ entityTag . setETag ( tokenizer . sval ) ; token = tokenizer . nextToken ( ) ; } else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissingQuotedString\" , String . valueOf ( token ) ) ) ; //$NON-NLS-1$ if ( token == ' ' ) token = tokenizer . nextToken ( ) ; else throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( \"error.parseMissing\" , String . valueOf ( token ) , \"]\" ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } catch ( IOException exc ) { // ignore or log? } return entityTag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a unique EntityTag . The tag is constructed by concatening the current time with the current thread s hash code . [CODESPLIT] public static EntityTag generateEntityTag ( ) { String xx = basetime + \":\" + Integer . toHexString ( Thread . currentThread ( ) . hashCode ( ) ) ; //$NON-NLS-1$ bcnt ++ ; xx += \":\" + bcnt ; //$NON-NLS-1$ return new EntityTag ( xx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new workspace in the location described by this handle . <p > A new workspace is created using a MKWORKSPACE method call . < / p > [CODESPLIT] public void create ( ) throws DAVException { Document document = newDocument ( ) ; Mkworkspace . create ( document ) ; IResponse response = null ; try { response = davClient . mkworkspace ( locator , newContext ( ) , document ) ; examineResponse ( response ) ; } catch ( IOException e ) { throw new SystemException ( e ) ; } finally { closeResponse ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets opposite of specified vertex . [CODESPLIT] public BaseVertex getOpposite ( BaseVertex vertex ) { // If null or not part of this connection if ( vertex == null || ( ! vertex . equals ( getSource ( ) ) && ! vertex . equals ( getTarget ( ) ) ) ) { return null ; } if ( vertex . equals ( getSource ( ) ) ) { return getTarget ( ) ; } return getSource ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成ECC密钥对 [CODESPLIT] public static AsymmetricCipherKeyPair generateKeyPairParameter ( ECDomainParameters domainParameters , SecureRandom random ) { ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters ( domainParameters , random ) ; ECKeyPairGenerator keyGen = new ECKeyPairGenerator ( ) ; keyGen . init ( keyGenerationParams ) ; return keyGen . generateKeyPair ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将ECC私钥转换为PKCS8标准的字节流 [CODESPLIT] public static byte [ ] convertECPrivateKeyToPKCS8 ( ECPrivateKeyParameters priKey , ECPublicKeyParameters pubKey ) { ECDomainParameters domainParams = priKey . getParameters ( ) ; ECParameterSpec spec = new ECParameterSpec ( domainParams . getCurve ( ) , domainParams . getG ( ) , domainParams . getN ( ) , domainParams . getH ( ) ) ; BCECPublicKey publicKey = null ; if ( pubKey != null ) { publicKey = new BCECPublicKey ( ALGO_NAME_EC , pubKey , spec , BouncyCastleProvider . CONFIGURATION ) ; } BCECPrivateKey privateKey = new BCECPrivateKey ( ALGO_NAME_EC , priKey , publicKey , spec , BouncyCastleProvider . CONFIGURATION ) ; return privateKey . getEncoded ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将PKCS8标准的私钥字节流转换为私钥对象 [CODESPLIT] public static BCECPrivateKey convertPKCS8ToECPrivateKey ( byte [ ] pkcs8Key ) throws NoSuchAlgorithmException , NoSuchProviderException , InvalidKeySpecException { PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec ( pkcs8Key ) ; KeyFactory kf = KeyFactory . getInstance ( ALGO_NAME_EC , BouncyCastleProvider . PROVIDER_NAME ) ; return ( BCECPrivateKey ) kf . generatePrivate ( peks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将ECC私钥转换为SEC1标准的字节流 openssl d2i_ECPrivateKey函数要求的DER编码的私钥也是SEC1标准的， 这个工具函数的主要目的就是为了能生成一个openssl可以直接“识别”的ECC私钥 . 相对RSA私钥的PKCS1标准，ECC私钥的标准为SEC1 [CODESPLIT] public static byte [ ] convertECPrivateKeyToSEC1 ( ECPrivateKeyParameters priKey , ECPublicKeyParameters pubKey ) throws IOException { byte [ ] pkcs8Bytes = convertECPrivateKeyToPKCS8 ( priKey , pubKey ) ; PrivateKeyInfo pki = PrivateKeyInfo . getInstance ( pkcs8Bytes ) ; ASN1Encodable encodable = pki . parsePrivateKey ( ) ; ASN1Primitive primitive = encodable . toASN1Primitive ( ) ; byte [ ] sec1Bytes = primitive . getEncoded ( ) ; return sec1Bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将SEC1标准的私钥字节流恢复为PKCS8标准的字节流 [CODESPLIT] public static byte [ ] convertECPrivateKeySEC1ToPKCS8 ( byte [ ] sec1Key ) throws IOException { /**\n         * 参考org.bouncycastle.asn1.pkcs.PrivateKeyInfo和\n         * org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey，逆向拼装\n         */ X962Parameters params = getDomainParametersFromName ( SM2Util . JDK_EC_SPEC , false ) ; ASN1OctetString privKey = new DEROctetString ( sec1Key ) ; ASN1EncodableVector v = new ASN1EncodableVector ( ) ; v . add ( new ASN1Integer ( 0 ) ) ; //版本号 v . add ( new AlgorithmIdentifier ( X9ObjectIdentifiers . id_ecPublicKey , params ) ) ; //算法标识 v . add ( privKey ) ; DERSequence ds = new DERSequence ( v ) ; return ds . getEncoded ( ASN1Encoding . DER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将SEC1标准的私钥字节流转为BCECPrivateKey对象 [CODESPLIT] public static BCECPrivateKey convertSEC1ToBCECPrivateKey ( byte [ ] sec1Key ) throws NoSuchAlgorithmException , NoSuchProviderException , InvalidKeySpecException , IOException { PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec ( convertECPrivateKeySEC1ToPKCS8 ( sec1Key ) ) ; KeyFactory kf = KeyFactory . getInstance ( ALGO_NAME_EC , BouncyCastleProvider . PROVIDER_NAME ) ; return ( BCECPrivateKey ) kf . generatePrivate ( peks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将SEC1标准的私钥字节流转为ECPrivateKeyParameters对象 openssl i2d_ECPrivateKey函数生成的DER编码的ecc私钥是：SEC1标准的、带有EC_GROUP、带有公钥的， 这个工具函数的主要目的就是为了使Java程序能够“识别”openssl生成的ECC私钥 [CODESPLIT] public static ECPrivateKeyParameters convertSEC1ToECPrivateKey ( byte [ ] sec1Key ) throws NoSuchAlgorithmException , NoSuchProviderException , InvalidKeySpecException , IOException { BCECPrivateKey privateKey = convertSEC1ToBCECPrivateKey ( sec1Key ) ; return convertPrivateKeyToParameters ( privateKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将ECC公钥对象转换为X509标准的字节流 [CODESPLIT] public static byte [ ] convertECPublicKeyToX509 ( ECPublicKeyParameters pubKey ) { ECDomainParameters domainParams = pubKey . getParameters ( ) ; ECParameterSpec spec = new ECParameterSpec ( domainParams . getCurve ( ) , domainParams . getG ( ) , domainParams . getN ( ) , domainParams . getH ( ) ) ; BCECPublicKey publicKey = new BCECPublicKey ( ALGO_NAME_EC , pubKey , spec , BouncyCastleProvider . CONFIGURATION ) ; return publicKey . getEncoded ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将X509标准的公钥字节流转为公钥对象 [CODESPLIT] public static BCECPublicKey convertX509ToECPublicKey ( byte [ ] x509Bytes ) throws NoSuchProviderException , NoSuchAlgorithmException , InvalidKeySpecException { X509EncodedKeySpec eks = new X509EncodedKeySpec ( x509Bytes ) ; KeyFactory kf = KeyFactory . getInstance ( \"EC\" , BouncyCastleProvider . PROVIDER_NAME ) ; return ( BCECPublicKey ) kf . generatePublic ( eks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from BC [CODESPLIT] public static X9ECParameters getDomainParametersFromName ( String curveName ) { X9ECParameters domainParameters ; try { if ( curveName . charAt ( 0 ) >= ' ' && curveName . charAt ( 0 ) <= ' ' ) { ASN1ObjectIdentifier oidID = new ASN1ObjectIdentifier ( curveName ) ; domainParameters = ECUtil . getNamedCurveByOid ( oidID ) ; } else { if ( curveName . indexOf ( ' ' ) > 0 ) { curveName = curveName . substring ( curveName . indexOf ( ' ' ) + 1 ) ; domainParameters = ECUtil . getNamedCurveByName ( curveName ) ; } else { domainParameters = ECUtil . getNamedCurveByName ( curveName ) ; } } } catch ( IllegalArgumentException ex ) { domainParameters = ECUtil . getNamedCurveByName ( curveName ) ; } return domainParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy from BC [CODESPLIT] public static X962Parameters getDomainParametersFromName ( java . security . spec . ECParameterSpec ecSpec , boolean withCompression ) { X962Parameters params ; if ( ecSpec instanceof ECNamedCurveSpec ) { ASN1ObjectIdentifier curveOid = ECUtil . getNamedCurveOid ( ( ( ECNamedCurveSpec ) ecSpec ) . getName ( ) ) ; if ( curveOid == null ) { curveOid = new ASN1ObjectIdentifier ( ( ( ECNamedCurveSpec ) ecSpec ) . getName ( ) ) ; } params = new X962Parameters ( curveOid ) ; } else if ( ecSpec == null ) { params = new X962Parameters ( DERNull . INSTANCE ) ; } else { ECCurve curve = EC5Util . convertCurve ( ecSpec . getCurve ( ) ) ; X9ECParameters ecP = new X9ECParameters ( curve , EC5Util . convertPoint ( curve , ecSpec . getGenerator ( ) , withCompression ) , ecSpec . getOrder ( ) , BigInteger . valueOf ( ecSpec . getCofactor ( ) ) , ecSpec . getCurve ( ) . getSeed ( ) ) ; params = new X962Parameters ( ecP ) ; } return params ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加密数据 [CODESPLIT] public static byte [ ] encrypt ( String srcData , String publicKey ) throws Exception { if ( RUNNING_PUBLIC_KEY == null ) { try { LOCK . lock ( ) ; if ( RUNNING_PUBLIC_KEY == null ) { ECPoint ecPoint = CURVE . decodePoint ( Base64 . decode ( publicKey . toCharArray ( ) ) ) ; RUNNING_PUBLIC_KEY = new ECPublicKeyParameters ( ecPoint , DOMAIN_PARAMS ) ; } } catch ( Exception e ) { throw new RuntimeException ( \"init public key error\" , e ) ; } finally { LOCK . unlock ( ) ; } } return encrypt ( RUNNING_PUBLIC_KEY , srcData . getBytes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "只获取公钥里的XY分量，64字节 [CODESPLIT] public static byte [ ] getRawPublicKey ( BCECPublicKey publicKey ) { byte [ ] src65 = publicKey . getQ ( ) . getEncoded ( false ) ; byte [ ] rawXY = new byte [ CURVE_LEN * 2 ] ; //SM2的话这里应该是64字节 System . arraycopy ( src65 , 1 , rawXY , 0 , rawXY . length ) ; return rawXY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ECC公钥加密 [CODESPLIT] public static byte [ ] encrypt ( ECPublicKeyParameters pubKeyParameters , byte [ ] srcData ) throws InvalidCipherTextException { SM2Engine engine = new SM2Engine ( ) ; ParametersWithRandom pwr = new ParametersWithRandom ( pubKeyParameters , new SecureRandom ( ) ) ; engine . init ( true , pwr ) ; return engine . processBlock ( srcData , 0 , srcData . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ECC私钥解密 [CODESPLIT] public static byte [ ] decrypt ( ECPrivateKeyParameters priKeyParameters , byte [ ] sm2Cipher ) throws InvalidCipherTextException { SM2Engine engine = new SM2Engine ( ) ; engine . init ( false , priKeyParameters ) ; return engine . processBlock ( sm2Cipher , 0 , sm2Cipher . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sums two { [CODESPLIT] public static InsertMetrics sum ( InsertMetrics m1 , InsertMetrics m2 ) { long totalDocsInserted = m1 . numberOfDocumentsInserted + m2 . numberOfDocumentsInserted ; Duration totalTimeTaken = m1 . timeTaken . plus ( m2 . timeTaken ) ; double totalRequestUnitsConsumed = m1 . requestUnitsConsumed + m2 . requestUnitsConsumed ; long totalNumberOfThrottles = m1 . numberOfThrottles + m2 . numberOfThrottles ; return new InsertMetrics ( totalDocsInserted , totalTimeTaken , totalRequestUnitsConsumed , totalNumberOfThrottles ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Releases any internal resources . It is responsibility of the caller to close { [CODESPLIT] @ Override public void close ( ) { // disable submission of new tasks listeningExecutorService . shutdown ( ) ; try { // wait for existing tasks to terminate if ( ! listeningExecutorService . awaitTermination ( 60 , TimeUnit . SECONDS ) ) { // cancel any currently running executing tasks listeningExecutorService . shutdownNow ( ) ; // wait for cancelled tasks to terminate if ( ! listeningExecutorService . awaitTermination ( 60 , TimeUnit . SECONDS ) ) { logger . error ( \"some tasks did not terminate\" ) ; } } } catch ( InterruptedException e ) { listeningExecutorService . shutdownNow ( ) ; Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes { [CODESPLIT] private void initialize ( ) throws DocumentClientException { logger . debug ( \"Initializing ...\" ) ; this . bulkImportStoredProcLink = String . format ( \"%s/sprocs/%s\" , collectionLink , BULK_IMPORT_STORED_PROCECURE_NAME ) ; logger . trace ( \"Fetching partition map of collection\" ) ; Range < String > fullRange = new Range < String > ( PartitionKeyInternal . MinimumInclusiveEffectivePartitionKey , PartitionKeyInternal . MaximumExclusiveEffectivePartitionKey , true , false ) ; this . collectionRoutingMap = getCollectionRoutingMap ( client ) ; Collection < PartitionKeyRange > partitionKeyRanges = this . collectionRoutingMap . getOverlappingRanges ( fullRange ) ; this . partitionKeyRangeIds = partitionKeyRanges . stream ( ) . map ( partitionKeyRange -> partitionKeyRange . getId ( ) ) . collect ( Collectors . toList ( ) ) ; logger . debug ( \"Initialization completed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a bulk import in the Azure Cosmos DB database service . <blockquote > <pre > { @code ConnectionPolicy connectionPolicy = new ConnectionPolicy () ; RetryOptions retryOptions = new RetryOptions () ; // set to 0 to let bulk importer handles throttling retryOptions . setMaxRetryAttemptsOnThrottledRequests ( 0 ) ; connectionPolicy . setRetryOptions ( retryOptions ) ; connectionPolicy . setMaxPoolSize ( 200 ) ; [CODESPLIT] public BulkImportResponse importAll ( Collection < String > documents , boolean isUpsert ) throws DocumentClientException { return executeBulkImportInternal ( documents , isUpsert ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts effective { [CODESPLIT] public static PartitionKeyInternal extractPartitionKeyValue ( String documentAsString , PartitionKeyDefinition partitionKeyDefinition ) { if ( partitionKeyDefinition == null || partitionKeyDefinition . getPaths ( ) . size ( ) == 0 ) { return PartitionKeyInternal . getEmpty ( ) ; } return DocumentAnalyzer . extractPartitionKeyValueInternal ( documentAsString , partitionKeyDefinition ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean abort ( ) throws LoginException { log . trace ( \"In abort()\" ) ; for ( YubikeyPrincipal p : this . principals ) { this . subject . getPrincipals ( ) . remove ( p ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean commit ( ) throws LoginException { log . trace ( \"In commit()\" ) ; for ( YubikeyPrincipal p : this . principals ) { log . debug ( \"Committing principal {}\" , p ) ; this . subject . getPrincipals ( ) . add ( p ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean logout ( ) throws LoginException { log . trace ( \"In logout()\" ) ; for ( YubikeyPrincipal p : this . principals ) { this . subject . getPrincipals ( ) . remove ( p ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void initialize ( Subject newSubject , CallbackHandler newCallbackHandler , Map < String , ? > sharedState , Map < String , ? > options ) { log . debug ( \"Initializing YubikeyLoginModule\" ) ; this . subject = newSubject ; this . callbackHandler = newCallbackHandler ; /* Yubico verification client */ Integer clientId = Integer . parseInt ( options . get ( OPTION_YUBICO_CLIENT_ID ) . toString ( ) ) ; String clientKey = options . get ( OPTION_YUBICO_CLIENT_KEY ) . toString ( ) ; this . yc = YubicoClient . getClient ( clientId , clientKey ) ; /* Realm of principals added after authentication */ if ( options . containsKey ( OPTION_YUBICO_ID_REALM ) ) { this . idRealm = options . get ( OPTION_YUBICO_ID_REALM ) . toString ( ) ; } /* Should this JAAS module be ignored when no OTPs are supplied? */ if ( options . containsKey ( OPTION_YUBICO_SOFT_FAIL_NO_OTPS ) ) { if ( \"true\" . equals ( options . get ( OPTION_YUBICO_SOFT_FAIL_NO_OTPS ) . toString ( ) ) ) { this . soft_fail_on_no_otps = true ; } } /* Should this JAAS module uses j_otp form to pick up otp */ if ( options . containsKey ( OPTION_YUBICO_JACC ) ) { if ( \"true\" . equals ( options . get ( OPTION_YUBICO_JACC ) . toString ( ) ) ) { this . jacc = true ; } } /* User-provided URLs to the Yubico validation service, separated by \"|\". */ if ( options . containsKey ( OPTION_YUBICO_WSAPI_URLS ) ) { String in = options . get ( OPTION_YUBICO_WSAPI_URLS ) . toString ( ) ; String l [ ] = in . split ( \"\\\\|\" ) ; this . yc . setWsapiUrls ( l ) ; } if ( options . containsKey ( OPTION_YUBICO_SYNC_POLICY ) ) { this . yc . setSync ( Integer . parseInt ( options . get ( OPTION_YUBICO_SYNC_POLICY ) . toString ( ) ) ) ; } /* Instantiate the specified usermap implementation. */ String usermap_class_name = null ; if ( options . containsKey ( OPTION_YUBICO_USERMAP_CLASS ) ) { usermap_class_name = options . get ( OPTION_YUBICO_USERMAP_CLASS ) . toString ( ) ; } else { usermap_class_name = \"com.yubico.jaas.impl.YubikeyToUserMapImpl\" ; // Default implementation } try { log . debug ( \"Trying to instantiate {}\" , usermap_class_name ) ; this . ykmap = ( YubikeyToUserMap ) Class . forName ( usermap_class_name ) . newInstance ( ) ; this . ykmap . setOptions ( options ) ; } catch ( ClassNotFoundException ex ) { log . error ( \"Could not create usermap from class \" + usermap_class_name , ex ) ; } catch ( InstantiationException ex ) { log . error ( \"Could not create usermap from class \" + usermap_class_name , ex ) ; } catch ( IllegalAccessException ex ) { log . error ( \"Could not create usermap from class \" + usermap_class_name , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean login ( ) throws LoginException { NameCallback nameCb = new NameCallback ( \"Enter username: \" ) ; log . debug ( \"Begin OTP login\" ) ; if ( callbackHandler == null ) { throw new LoginException ( \"No callback handler available in login()\" ) ; } List < String > otps = get_tokens ( nameCb ) ; if ( otps . size ( ) == 0 ) { if ( this . soft_fail_on_no_otps ) { log . debug ( \"No OTPs found, and soft-fail is on. Making JAAS ignore this module.\" ) ; return false ; } throw new LoginException ( \"YubiKey OTP authentication failed - no OTPs supplied\" ) ; } if ( validate_otps ( otps , nameCb ) ) { return true ; } log . info ( \"None out of {} possible YubiKey OTPs for user {} validated successful\" , otps . size ( ) , nameCb . getName ( ) ) ; throw new LoginException ( \"YubiKey OTP authentication failed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to validate all the OTPs provided . [CODESPLIT] private boolean validate_otps ( List < String > otps , NameCallback nameCb ) throws LoginException { boolean validated = false ; for ( String otp : otps ) { log . trace ( \"Checking OTP {}\" , otp ) ; VerificationResponse ykr ; try { ykr = this . yc . verify ( otp ) ; } catch ( YubicoVerificationException e ) { log . warn ( \"Errors during validation: \" , e ) ; throw new LoginException ( \"Errors during validation: \" + e . getMessage ( ) ) ; } catch ( YubicoValidationFailure e ) { log . warn ( \"Something went very wrong during authentication: \" , e ) ; throw new LoginException ( \"Something went very wrong during authentication: \" + e . getMessage ( ) ) ; } if ( ykr != null ) { log . trace ( \"OTP {} verify result : {}\" , otp , ykr . getStatus ( ) . toString ( ) ) ; if ( ykr . getStatus ( ) == ResponseStatus . OK ) { String publicId = YubicoClient . getPublicId ( otp ) ; log . info ( \"OTP verified successfully (YubiKey id {})\" , publicId ) ; if ( is_right_user ( nameCb . getName ( ) , publicId ) ) { this . principals . add ( new YubikeyPrincipal ( publicId , this . idRealm ) ) ; /* Don't just return here, we want to \"consume\" all OTPs if\n\t\t\t\t\t\t * more than one is provided.\n\t\t\t\t\t\t */ validated = true ; } } else { log . debug ( \"OTP validation returned {}\" , ykr . getStatus ( ) . toString ( ) ) ; } } } return validated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After validation of an OTP check that it came from a YubiKey that actually belongs to the user trying to authenticate . [CODESPLIT] private boolean is_right_user ( String username , String publicId ) { log . debug ( \"Check if YubiKey {} belongs to user {}\" , publicId , username ) ; return this . ykmap . is_right_user ( username , publicId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get username and token ( s ) from the application using the javax . security . auth . callback . CallbackHandler passed to our initialize () function . [CODESPLIT] private List < String > get_tokens ( NameCallback nameCb ) { MultiValuePasswordCallback mv_passCb = new MultiValuePasswordCallback ( \"Enter authentication tokens: \" , false ) ; List < String > result = new ArrayList < String > ( ) ; try { /* Fetch a password using the callbackHandler */ callbackHandler . handle ( new Callback [ ] { nameCb , mv_passCb } ) ; for ( char [ ] c : mv_passCb . getSecrets ( ) ) { String s = new String ( c ) ; /* Check that OTP is at least 32 chars before we verify it. User might have entered\n\t\t\t\t * some other password instead of an OTP, and we don't want to send that, possibly\n\t\t\t\t * in clear text, over the network.\n\t\t\t\t */ if ( s . length ( ) < 32 ) { log . debug ( \"Skipping token, not a valid YubiKey OTP (too short, {} < 32)\" , s . length ( ) ) ; } else { result . add ( s ) ; } } } catch ( UnsupportedCallbackException ex ) { log . error ( \"Callback type not supported\" , ex ) ; } catch ( IOException ex ) { log . error ( \"CallbackHandler failed\" , ex ) ; } if ( jacc ) { // This is JACC specific mechanism try { HttpServletRequest request = ( HttpServletRequest ) PolicyContext . getContext ( JACC_ATTR_WEB_REQUEST_KEY ) ; String j_otp = request . getParameter ( HTTP_REQUEST_ATTR_TOTP ) ; if ( j_otp == null || j_otp . length ( ) < 32 ) { log . debug ( \"Skipping token from j_otp, not a valid YubiKey OTP (too short, {} < 32)\" , j_otp == null ? 0 : j_otp . length ( ) ) ; } else { result . add ( j_otp ) ; } log . debug ( \"OTP from j_otp token : {}\" , j_otp ) ; } catch ( PolicyContextException e ) { log . debug ( \"No OTP from j_otp token)\" ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void setOptions ( Map < String , ? > options ) { /* Is verification of YubiKey owners enabled? */ this . verify_yubikey_owner = true ; if ( options . get ( OPTION_YUBICO_VERIFY_YK_OWNER ) != null ) { if ( \"false\" . equals ( options . get ( OPTION_YUBICO_VERIFY_YK_OWNER ) . toString ( ) ) ) { this . verify_yubikey_owner = false ; } } /* id2name text file */ if ( options . get ( OPTION_YUBICO_ID2NAME_TEXTFILE ) != null ) { this . id2name_textfile = options . get ( OPTION_YUBICO_ID2NAME_TEXTFILE ) . toString ( ) ; } /* should we automatically assign new yubikeys to users? */ if ( options . get ( OPTION_YUBICO_AUTO_PROVISION ) != null ) { if ( \"true\" . equals ( options . get ( OPTION_YUBICO_AUTO_PROVISION ) . toString ( ) ) ) { this . auto_provision_owners = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean is_right_user ( String username , String publicId ) { if ( ! this . verify_yubikey_owner ) { log . debug ( \"YubiKey owner verification disabled, returning 'true'\" ) ; return true ; } if ( this . id2name_textfile == null ) { log . debug ( \"No id2name configuration. Defaulting to {}.\" , this . verify_yubikey_owner ) ; return this . verify_yubikey_owner ; } String ykuser ; try { ykuser = get_username_for_id ( publicId , this . id2name_textfile ) ; } catch ( FileNotFoundException ex ) { log . error ( \"Yubikey to username textfile {} not found\" , this . id2name_textfile ) ; return false ; } if ( ykuser != null ) { if ( ! ykuser . equals ( username ) ) { log . info ( \"YubiKey \" + publicId + \" registered to user {}, NOT {}\" , ykuser , username ) ; return false ; } return true ; } else { if ( this . auto_provision_owners ) { log . info ( \"Registering new YubiKey \" + publicId + \" as belonging to {}\" , username ) ; add_yubikey_to_user ( publicId , username , this . id2name_textfile ) ; return true ; } log . debug ( \"No record of YubiKey {} found. Returning 'false'.\" , publicId ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given publicId vvcccccfhc scans filename for a line like yk . vvcccccfhc . user = alice and returns alice if found . Null is returned in case there is no matching line in file . [CODESPLIT] private String get_username_for_id ( String publicId , String filename ) throws FileNotFoundException { Scanner sc = null ; File file = new File ( filename ) ; try { sc = new Scanner ( file ) ; while ( sc . hasNextLine ( ) ) { String line = sc . nextLine ( ) ; if ( line . startsWith ( \"yk.\" + publicId + \".user\" ) ) { String ykuser = line . split ( \"=\" ) [ 1 ] . trim ( ) ; return ykuser ; } } } finally { if ( sc != null ) { sc . close ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores an association between username and YubiKey publicId in filename . [CODESPLIT] private void add_yubikey_to_user ( String publicId , String username , String filename ) { try { File file = new File ( filename ) ; FileWriter writer = new FileWriter ( file , true ) ; writer . write ( \"yk.\" + publicId + \".user = \" + username + System . getProperty ( \"line.separator\" ) ) ; writer . close ( ) ; } catch ( IOException ex ) { log . error ( \"Failed appending entry to file {}\" , filename , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public VerificationResponse verify ( String otp ) throws YubicoVerificationException , YubicoValidationFailure { if ( ! isValidOTPFormat ( otp ) ) { throw new IllegalArgumentException ( \"The OTP is not a valid format\" ) ; } Map < String , String > requestMap = new TreeMap < String , String > ( ) ; String nonce = UUID . randomUUID ( ) . toString ( ) . replaceAll ( \"-\" , \"\" ) ; requestMap . put ( \"nonce\" , nonce ) ; requestMap . put ( \"id\" , clientId . toString ( ) ) ; requestMap . put ( \"otp\" , otp ) ; requestMap . put ( \"timestamp\" , \"1\" ) ; if ( sync != null ) { requestMap . put ( \"sl\" , sync . toString ( ) ) ; } String queryString ; try { queryString = toQueryString ( requestMap ) ; } catch ( UnsupportedEncodingException e ) { throw new YubicoVerificationException ( \"Failed to encode parameter.\" , e ) ; } if ( key != null ) { queryString = sign ( queryString ) ; } String [ ] wsapiUrls = this . getWsapiUrls ( ) ; List < String > validationUrls = new ArrayList < String > ( ) ; for ( String wsapiUrl : wsapiUrls ) { warnIfDeprecatedUrl ( wsapiUrl ) ; validationUrls . add ( wsapiUrl + \"?\" + queryString ) ; } VerificationResponse response = validationService . fetch ( validationUrls , userAgent ) ; if ( key != null ) { verifySignature ( response ) ; } // NONCE/OTP fields are not returned to the client when sending error codes. // If there is an error response, don't need to check them. if ( ! response . getStatus ( ) . isError ( ) ) { if ( response . getOtp ( ) == null || ! otp . equals ( response . getOtp ( ) ) ) { throw new YubicoValidationFailure ( \"OTP mismatch in response, is there a man-in-the-middle?\" ) ; } if ( response . getNonce ( ) == null || ! nonce . equals ( response . getNonce ( ) ) ) { throw new YubicoValidationFailure ( \"Nonce mismatch in response, is there a man-in-the-middle?\" ) ; } } return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean is_right_user ( String username , String publicId ) { log . trace ( \"In is_right_user()\" ) ; if ( ! this . verify_yubikey_owner ) { log . debug ( \"YubiKey owner verification disabled, returning 'true'\" ) ; return true ; } String ykuser = null ; try { SearchFilter filter = new SearchFilter ( \"({0}={1})\" , new String [ ] { this . publicid_attribute , publicId } ) ; log . debug ( \"Searching for YubiKey publicId with filter: {}\" , filter . toString ( ) ) ; Iterator < SearchResult > results = ldap . search ( filter , new String [ ] { this . username_attribute } ) ; if ( results . hasNext ( ) ) { Attributes results_attributes = results . next ( ) . getAttributes ( ) ; log . debug ( \"Found attributes: {}\" , results_attributes . toString ( ) ) ; ykuser = results_attributes . get ( this . username_attribute ) . get ( ) . toString ( ) ; } else { log . debug ( \"No search results\" ) ; } } catch ( NamingException ex ) { log . error ( ex . getMessage ( ) , ex ) ; return false ; } if ( ykuser != null ) { if ( ! ykuser . equals ( username ) ) { log . info ( \"YubiKey \" + publicId + \" registered to user {}, NOT {}\" , ykuser , username ) ; return false ; } else { log . info ( \"YubiKey \" + publicId + \" registered to user {}\" , ykuser ) ; return true ; } } else { log . info ( \"No record of YubiKey {} found. Returning 'false'.\" , publicId ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void setOptions ( Map < String , ? > options ) { /* Is verification of YubiKey owners enabled? */ this . verify_yubikey_owner = true ; if ( options . get ( OPTION_YUBICO_VERIFY_YK_OWNER ) != null ) { if ( \"false\" . equals ( options . get ( OPTION_YUBICO_VERIFY_YK_OWNER ) . toString ( ) ) ) { this . verify_yubikey_owner = false ; } } if ( options . get ( OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE ) != null ) { this . publicid_attribute = options . get ( OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE ) . toString ( ) ; } if ( options . get ( OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE ) != null ) { this . username_attribute = options . get ( OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE ) . toString ( ) ; } if ( options . get ( OPTION_LDAP_URL ) != null ) { this . ldap_url = options . get ( OPTION_LDAP_URL ) . toString ( ) ; } if ( options . get ( OPTION_LDAP_BASE_DN ) != null ) { this . ldap_base_dn = options . get ( OPTION_LDAP_BASE_DN ) . toString ( ) ; } if ( options . get ( OPTION_LDAP_BIND_DN ) != null ) { this . ldap_bind_dn = options . get ( OPTION_LDAP_BIND_DN ) . toString ( ) ; } if ( options . get ( OPTION_LDAP_BIND_CREDENTIAL ) != null ) { this . ldap_bind_credential = options . get ( OPTION_LDAP_BIND_CREDENTIAL ) . toString ( ) ; } LdapConfig config = new LdapConfig ( this . ldap_url , this . ldap_base_dn ) ; config . setBindDn ( this . ldap_bind_dn ) ; config . setBindCredential ( this . ldap_bind_credential ) ; this . ldap = new Ldap ( config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void initialize ( Subject newSubject , CallbackHandler newCallbackHandler , Map < String , ? > sharedState , Map < String , ? > options ) { log . trace ( \"Initializing HTTP OATH OTP LoginModule\" ) ; this . subject = newSubject ; this . callbackHandler = newCallbackHandler ; this . protectedUrl = options . get ( OPTION_HTTPOATHOTP_PROTECTED_URL ) . toString ( ) ; if ( options . get ( OPTION_HTTPOATHOTP_EXPECTED_OUTPUT ) != null ) { this . expectedOutput = options . get ( OPTION_HTTPOATHOTP_EXPECTED_OUTPUT ) . toString ( ) ; } if ( options . get ( OPTION_HTTPOATHOTP_MIN_LENGTH ) != null ) { this . minLength = Integer . parseInt ( options . get ( OPTION_HTTPOATHOTP_MIN_LENGTH ) . toString ( ) ) ; } if ( options . get ( OPTION_HTTPOATHOTP_MAX_LENGTH ) != null ) { this . maxLength = Integer . parseInt ( options . get ( OPTION_HTTPOATHOTP_MAX_LENGTH ) . toString ( ) ) ; } if ( options . get ( OPTION_HTTPOATHOTP_REQUIRE_ALL_DIGITS ) != null ) { String s = options . get ( OPTION_HTTPOATHOTP_REQUIRE_ALL_DIGITS ) . toString ( ) ; if ( s . equals ( \"true\" ) ) { this . requireAllDigits = true ; } else if ( s . equals ( \"false\" ) ) { this . requireAllDigits = false ; } else { log . error ( \"Bad value for option {}\" , OPTION_HTTPOATHOTP_REQUIRE_ALL_DIGITS ) ; } } /* Realm of principals added after authentication */ if ( options . get ( OPTION_HTTPOATHOTP_ID_REALM ) != null ) { this . idRealm = options . get ( OPTION_HTTPOATHOTP_ID_REALM ) . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean login ( ) throws LoginException { log . trace ( \"Begin OATH OTP login\" ) ; if ( callbackHandler == null ) { throw new LoginException ( \"No callback handler available in login()\" ) ; } NameCallback nameCb = new NameCallback ( \"Enter username: \" ) ; List < String > otps = get_tokens ( nameCb ) ; for ( String otp : otps ) { String userName = nameCb . getName ( ) ; log . trace ( \"Checking OATH OTP for user {}\" , userName ) ; if ( verify_otp ( userName , otp ) ) { log . info ( \"OATH OTP verified successfully\" ) ; principal = new YubikeyPrincipal ( userName , this . idRealm ) ; return true ; } log . info ( \"OATH OTP did NOT verify\" ) ; } throw new LoginException ( \"OATH OTP verification failed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Access protectedUrl using userName and otp for basic auth . Check if what we get back contains expectedOutput . [CODESPLIT] boolean verify_otp ( String userName , String otp ) { try { String authString = userName + \":\" + otp ; String authStringEnc = Base64 . encodeBase64URLSafeString ( authString . getBytes ( ) ) ; BufferedReader in = attemptAuthentication ( authStringEnc ) ; String inputLine ; while ( ( inputLine = in . readLine ( ) ) != null ) { if ( inputLine . contains ( expectedOutput ) ) { return true ; } } } catch ( Exception ex ) { log . error ( \"Failed verifying OATH OTP :\" , ex ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to clear all the passwords from memory . [CODESPLIT] public void clearPassword ( ) { for ( char pw [ ] : this . secrets ) { for ( int i = 0 ; i < pw . length ; i ++ ) { pw [ i ] = 0 ; } } /* Now discard the list. */ this . secrets = new ArrayList < char [ ] > ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires off a validation request to each url in the list returning the first one that is not { @link ResponseStatus#REPLAYED_REQUEST } [CODESPLIT] public VerificationResponse fetch ( List < String > urls , String userAgent ) throws YubicoVerificationException { List < Future < VerificationResponse >> tasks = new ArrayList < Future < VerificationResponse > > ( ) ; for ( String url : urls ) { tasks . add ( completionService . submit ( createTask ( userAgent , url ) ) ) ; } VerificationResponse response = null ; try { int tasksDone = 0 ; Throwable savedException = null ; Future < VerificationResponse > futureResponse = completionService . poll ( 1L , MINUTES ) ; while ( futureResponse != null ) { try { tasksDone ++ ; tasks . remove ( futureResponse ) ; response = futureResponse . get ( ) ; /**\n\t\t\t\t\t * If the response returned is REPLAYED_REQUEST keep looking at responses\n\t\t\t\t\t * and hope we get something else. REPLAYED_REQUEST will be returned if a\n\t\t\t\t\t * validation server got sync before it parsed our query (otp and nonce is\n\t\t\t\t\t * the same).\n\t\t\t\t\t * @see https://forum.yubico.com/viewtopic21be.html\n\t\t\t\t\t *\n\t\t\t\t\t * Also if the response is BACKEND_ERROR, keep looking for a server that\n\t\t\t\t\t * sends a valid response\n\t\t\t\t\t * @see https://github.com/Yubico/yubico-java-client/issues/12\n\t\t\t\t\t */ if ( ! response . getStatus ( ) . equals ( REPLAYED_REQUEST ) && ! response . getStatus ( ) . equals ( BACKEND_ERROR ) ) { break ; } } catch ( CancellationException ignored ) { // this would be thrown by old cancelled calls. tasksDone -- ; } catch ( ExecutionException e ) { // tuck the real exception away and use it if we don't get any valid answers. savedException = e . getCause ( ) ; } if ( tasksDone >= urls . size ( ) ) { break ; } futureResponse = completionService . poll ( 1L , MINUTES ) ; } if ( futureResponse == null || response == null ) { if ( savedException != null ) { throw new YubicoVerificationException ( \"Exception while executing validation.\" , savedException ) ; } else { throw new YubicoVerificationException ( \"Validation timeout.\" ) ; } } } catch ( InterruptedException e ) { throw new YubicoVerificationException ( \"Validation interrupted.\" , e ) ; } for ( Future < VerificationResponse > task : tasks ) { task . cancel ( true ) ; } return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure what URLs to use for validating OTPs . These URLs will have all the necessary parameters appended to them . Example : { https : // api . yubico . com / wsapi / 2 . 0 / verify } [CODESPLIT] public void setWsapiUrls ( String [ ] wsapi ) { for ( String url : wsapi ) { warnIfDeprecatedUrl ( url ) ; } this . wsapi_urls = wsapi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the public ID of a YubiKey from an OTP it generated . [CODESPLIT] public static String getPublicId ( String otp ) { if ( ( otp == null ) || ( otp . length ( ) < OTP_MIN_LEN ) ) { //not a valid OTP format, throw an exception throw new IllegalArgumentException ( \"The OTP is too short to be valid\" ) ; } Integer len = otp . length ( ) ; /* The OTP part is always the last 32 bytes of otp. Whatever is before that\n\t\t * (if anything) is the public ID of the YubiKey. The ID can be set to ''\n\t\t * through personalization.\n\t\t */ return otp . substring ( 0 , len - 32 ) . toLowerCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether a given OTP is of the correct length and only contains printable characters as per the recommendation . [CODESPLIT] public static boolean isValidOTPFormat ( String otp ) { if ( otp == null ) { return false ; } int len = otp . length ( ) ; for ( char c : otp . toCharArray ( ) ) { if ( c < 0x20 || c > 0x7E ) { return false ; } } return OTP_MIN_LEN <= len && len <= OTP_MAX_LEN ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Evaluation that contains the node source and whether it is a set operation . If there are no Evaluation objects in the pool one is created and returned . [CODESPLIT] public Evaluation create ( SimpleNode node , Object source ) { return create ( node , source , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Evaluation that contains the node source and whether it is a set operation . [CODESPLIT] public Evaluation create ( SimpleNode node , Object source , boolean setOperation ) { // synchronization is removed as we do not rely anymore on the in-house object pooling return new Evaluation ( node , source , setOperation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this property is described by an IndexedPropertyDescriptor and that if followed by an index specifier it will call the index get / set methods rather than go through property accessors . [CODESPLIT] public int getIndexedPropertyType ( OgnlContext context , Object source ) throws OgnlException { Class type = context . getCurrentType ( ) ; Class prevType = context . getPreviousType ( ) ; try { if ( ! isIndexedAccess ( ) ) { Object property = getProperty ( context , source ) ; if ( property instanceof String ) { return OgnlRuntime . getIndexedPropertyType ( context , ( source == null ) ? null : OgnlRuntime . getCompiler ( ) . getInterfaceClass ( source . getClass ( ) ) , ( String ) property ) ; } } return OgnlRuntime . INDEXED_PROPERTY_NONE ; } finally { context . setCurrentObject ( source ) ; context . setCurrentType ( type ) ; context . setPreviousType ( prevType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * MethodAccessor interface [CODESPLIT] public Object callStaticMethod ( Map context , Class targetClass , String methodName , Object [ ] args ) throws MethodFailedException { List methods = OgnlRuntime . getMethods ( targetClass , methodName , true ) ; return OgnlRuntime . callAppropriateMethod ( ( OgnlContext ) context , targetClass , null , methodName , null , methods , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears all of the cached reflection information normally used to improve the speed of expressions that operate on the same classes or are executed multiple times . [CODESPLIT] public static void clearCache ( ) { _methodParameterTypesCache . clear ( ) ; _ctorParameterTypesCache . clear ( ) ; _propertyDescriptorCache . clear ( ) ; _constructorCache . clear ( ) ; _staticMethodCache . clear ( ) ; _instanceMethodCache . clear ( ) ; _invokePermissionCache . clear ( ) ; _fieldCache . clear ( ) ; _superclasses . clear ( ) ; _declaredMethods [ 0 ] . clear ( ) ; _declaredMethods [ 1 ] . clear ( ) ; _methodAccessCache . clear ( ) ; _methodPermCache . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the current jvm is java language > = 1 . 5 compatible . [CODESPLIT] public static boolean isJdk15 ( ) { if ( _jdkChecked ) return _jdk15 ; try { Class . forName ( \"java.lang.annotation.Annotation\" ) ; _jdk15 = true ; } catch ( Exception e ) { /* ignore */ } _jdkChecked = true ; return _jdk15 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the target class of an object for looking up accessors that are registered on the target . If the object is a Class object this will return the Class itself else it will return object s getClass () result . [CODESPLIT] public static Class getTargetClass ( Object o ) { return ( o == null ) ? null : ( ( o instanceof Class ) ? ( Class ) o : o . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the base name ( the class name without the package name prepended ) of the object given . [CODESPLIT] public static String getBaseName ( Object o ) { return ( o == null ) ? null : getClassBaseName ( o . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the base name ( the class name without the package name prepended ) of the class given . [CODESPLIT] public static String getClassBaseName ( Class c ) { String s = c . getName ( ) ; return s . substring ( s . lastIndexOf ( ' ' ) + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the package name of the object s class . [CODESPLIT] public static String getPackageName ( Object o ) { return ( o == null ) ? null : getClassPackageName ( o . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the package name of the class given . [CODESPLIT] public static String getClassPackageName ( Class c ) { String s = c . getName ( ) ; int i = s . lastIndexOf ( ' ' ) ; return ( i < 0 ) ? null : s . substring ( 0 , i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a pointer string in the usual format for these things - 0x<hex digits > . [CODESPLIT] public static String getPointerString ( int num ) { StringBuffer result = new StringBuffer ( ) ; String hex = Integer . toHexString ( num ) , pad ; Integer l = new Integer ( hex . length ( ) ) ; // result.append(HEX_PREFIX); if ( ( pad = ( String ) HEX_PADDING . get ( l ) ) == null ) { StringBuffer pb = new StringBuffer ( ) ; for ( int i = hex . length ( ) ; i < HEX_LENGTH ; i ++ ) { pb . append ( ' ' ) ; } pad = new String ( pb ) ; HEX_PADDING . put ( l , pad ) ; } result . append ( pad ) ; result . append ( hex ) ; return new String ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a pointer string in the usual format for these things - 0x<hex digits > for the object given . This will always return a unique value for each object . [CODESPLIT] public static String getPointerString ( Object o ) { return getPointerString ( ( o == null ) ? 0 : System . identityHashCode ( o ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a unique descriptor string that includes the object s class and a unique integer identifier . If fullyQualified is true then the class name will be fully qualified to include the package name else it will be just the class base name . [CODESPLIT] public static String getUniqueDescriptor ( Object object , boolean fullyQualified ) { StringBuffer result = new StringBuffer ( ) ; if ( object != null ) { if ( object instanceof Proxy ) { Class interfaceClass = object . getClass ( ) . getInterfaces ( ) [ 0 ] ; result . append ( getClassName ( interfaceClass , fullyQualified ) ) ; result . append ( ' ' ) ; object = Proxy . getInvocationHandler ( object ) ; } result . append ( getClassName ( object , fullyQualified ) ) ; result . append ( ' ' ) ; result . append ( getPointerString ( object ) ) ; } else { result . append ( NULL_OBJECT_STRING ) ; } return new String ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility to convert a List into an Object [] array . If the list is zero elements this will return a constant array ; toArray () on List always returns a new object and this is wasteful for our purposes . [CODESPLIT] public static Object [ ] toArray ( List list ) { Object [ ] result ; int size = list . size ( ) ; if ( size == 0 ) { result = NoArguments ; } else { result = getObjectArrayPool ( ) . create ( list . size ( ) ) ; for ( int i = 0 ; i < size ; i ++ ) { result [ i ] = list . get ( i ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the parameter types of the given method . [CODESPLIT] public static Class [ ] getParameterTypes ( Method m ) { synchronized ( _methodParameterTypesCache ) { Class [ ] result ; if ( ( result = ( Class [ ] ) _methodParameterTypesCache . get ( m ) ) == null ) { _methodParameterTypesCache . put ( m , result = m . getParameterTypes ( ) ) ; } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the appropriate parameter types for the given { @link Method } and { @link Class } instance of the type the method is associated with . Correctly finds generic types if running in > = 1 . 5 jre as well . [CODESPLIT] public static Class [ ] findParameterTypes ( Class type , Method m ) { Type [ ] genTypes = m . getGenericParameterTypes ( ) ; Class [ ] types = new Class [ genTypes . length ] ; ; boolean noGenericParameter = true ; for ( int i = 0 ; i < genTypes . length ; i ++ ) { if ( Class . class . isInstance ( genTypes [ i ] ) ) { types [ i ] = ( Class ) genTypes [ i ] ; continue ; } noGenericParameter = false ; break ; } if ( noGenericParameter ) { return types ; } if ( type == null || ! isJdk15 ( ) ) { return getParameterTypes ( m ) ; } final Type typeGenericSuperclass = type . getGenericSuperclass ( ) ; if ( typeGenericSuperclass == null || ! ParameterizedType . class . isInstance ( typeGenericSuperclass ) || m . getDeclaringClass ( ) . getTypeParameters ( ) == null ) { return getParameterTypes ( m ) ; } if ( ( types = ( Class [ ] ) _genericMethodParameterTypesCache . get ( m ) ) != null ) { ParameterizedType genericSuperclass = ( ParameterizedType ) typeGenericSuperclass ; if ( Arrays . equals ( types , genericSuperclass . getActualTypeArguments ( ) ) ) { return types ; } } ParameterizedType param = ( ParameterizedType ) typeGenericSuperclass ; TypeVariable [ ] declaredTypes = m . getDeclaringClass ( ) . getTypeParameters ( ) ; types = new Class [ genTypes . length ] ; for ( int i = 0 ; i < genTypes . length ; i ++ ) { TypeVariable paramType = null ; if ( TypeVariable . class . isInstance ( genTypes [ i ] ) ) { paramType = ( TypeVariable ) genTypes [ i ] ; } else if ( GenericArrayType . class . isInstance ( genTypes [ i ] ) ) { paramType = ( TypeVariable ) ( ( GenericArrayType ) genTypes [ i ] ) . getGenericComponentType ( ) ; } else if ( ParameterizedType . class . isInstance ( genTypes [ i ] ) ) { types [ i ] = ( Class ) ( ( ParameterizedType ) genTypes [ i ] ) . getRawType ( ) ; continue ; } else if ( Class . class . isInstance ( genTypes [ i ] ) ) { types [ i ] = ( Class ) genTypes [ i ] ; continue ; } Class resolved = resolveType ( param , paramType , declaredTypes ) ; if ( resolved != null ) { if ( GenericArrayType . class . isInstance ( genTypes [ i ] ) ) { resolved = Array . newInstance ( resolved , 0 ) . getClass ( ) ; } types [ i ] = resolved ; continue ; } types [ i ] = m . getParameterTypes ( ) [ i ] ; } synchronized ( _genericMethodParameterTypesCache ) { _genericMethodParameterTypesCache . put ( m , types ) ; } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the parameter types of the given method . [CODESPLIT] public static Class [ ] getParameterTypes ( Constructor c ) { Class [ ] result ; if ( ( result = ( Class [ ] ) _ctorParameterTypesCache . get ( c ) ) == null ) { synchronized ( _ctorParameterTypesCache ) { if ( ( result = ( Class [ ] ) _ctorParameterTypesCache . get ( c ) ) == null ) { _ctorParameterTypesCache . put ( c , result = c . getParameterTypes ( ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Permission will be named invoke . <declaring - class > . <method - name > . [CODESPLIT] public static Permission getPermission ( Method method ) { Permission result ; Class mc = method . getDeclaringClass ( ) ; synchronized ( _invokePermissionCache ) { Map permissions = ( Map ) _invokePermissionCache . get ( mc ) ; if ( permissions == null ) { _invokePermissionCache . put ( mc , permissions = new HashMap ( 101 ) ) ; } if ( ( result = ( Permission ) permissions . get ( method . getName ( ) ) ) == null ) { result = new OgnlInvokePermission ( \"invoke.\" + mc . getName ( ) + \".\" + method . getName ( ) ) ; permissions . put ( method . getName ( ) , result ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the class for a method argument that is appropriate for looking up methods by reflection by looking for the standard primitive wrapper classes and exchanging for them their underlying primitive class objects . Other classes are passed through unchanged . [CODESPLIT] public static final Class getArgClass ( Object arg ) { if ( arg == null ) return null ; Class c = arg . getClass ( ) ; if ( c == Boolean . class ) return Boolean . TYPE ; else if ( c . getSuperclass ( ) == Number . class ) { if ( c == Integer . class ) return Integer . TYPE ; if ( c == Double . class ) return Double . TYPE ; if ( c == Byte . class ) return Byte . TYPE ; if ( c == Long . class ) return Long . TYPE ; if ( c == Float . class ) return Float . TYPE ; if ( c == Short . class ) return Short . TYPE ; } else if ( c == Character . class ) return Character . TYPE ; return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tells whether the given object is compatible with the given class --- that is whether the given object can be passed as an argument to a method or constructor whose parameter type is the given class . If object is null this will return true because null is compatible with any type . [CODESPLIT] public static final boolean isTypeCompatible ( Object object , Class c ) { if ( object == null ) return true ; ArgsCompatbilityReport report = new ArgsCompatbilityReport ( 0 , new boolean [ 1 ] ) ; if ( ! isTypeCompatible ( getArgClass ( object ) , c , 0 , report ) ) return false ; if ( report . conversionNeeded [ 0 ] ) return false ; // we don't allow conversions during this path... return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tells whether the first array of classes is more specific than the second . Assumes that the two arrays are of the same length . [CODESPLIT] public static final boolean isMoreSpecific ( Class [ ] classes1 , Class [ ] classes2 ) { for ( int index = 0 , count = classes1 . length ; index < count ; ++ index ) { Class c1 = classes1 [ index ] , c2 = classes2 [ index ] ; if ( c1 == c2 ) continue ; else if ( c1 . isPrimitive ( ) ) return true ; else if ( c1 . isAssignableFrom ( c2 ) ) return false ; else if ( c2 . isAssignableFrom ( c1 ) ) return true ; } // They are the same! So the first is not more specific than the second. return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the appropriate method to be called for the given target method name and arguments . If successful this method will return the Method within the target that can be called and the converted arguments in actualArgs . If unsuccessful this method will return null and the actualArgs will be empty . [CODESPLIT] public static Method getAppropriateMethod ( OgnlContext context , Object source , Object target , String propertyName , String methodName , List methods , Object [ ] args , Object [ ] actualArgs ) { Method result = null ; if ( methods != null ) { Class typeClass = target != null ? target . getClass ( ) : null ; if ( typeClass == null && source != null && Class . class . isInstance ( source ) ) { typeClass = ( Class ) source ; } Class [ ] argClasses = getArgClasses ( args ) ; MatchingMethod mm = findBestMethod ( methods , typeClass , methodName , argClasses ) ; if ( mm != null ) { result = mm . mMethod ; Class [ ] mParameterTypes = mm . mParameterTypes ; System . arraycopy ( args , 0 , actualArgs , 0 , args . length ) ; for ( int j = 0 ; j < mParameterTypes . length ; j ++ ) { Class type = mParameterTypes [ j ] ; if ( mm . report . conversionNeeded [ j ] || ( type . isPrimitive ( ) && ( actualArgs [ j ] == null ) ) ) { actualArgs [ j ] = getConvertedType ( context , source , result , propertyName , args [ j ] , type ) ; } } } } if ( result == null ) { result = getConvertedMethodAndArgs ( context , target , propertyName , methods , args , actualArgs ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the specified method against the target object . [CODESPLIT] public static Object callMethod ( OgnlContext context , Object target , String methodName , String propertyName , Object [ ] args ) throws OgnlException { return callMethod ( context , target , methodName == null ? propertyName : methodName , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the specified method against the target object . [CODESPLIT] public static Object callMethod ( OgnlContext context , Object target , String methodName , Object [ ] args ) throws OgnlException { if ( target == null ) throw new NullPointerException ( \"target is null for method \" + methodName ) ; return getMethodAccessor ( target . getClass ( ) ) . callMethod ( context , target , methodName , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the checkAccessAndExistence flag is true this method will check to see if the method exists and if it is accessible according to the context s MemberAccess . If neither test passes this will return NotFound . [CODESPLIT] public static final Object getMethodValue ( OgnlContext context , Object target , String propertyName , boolean checkAccessAndExistence ) throws OgnlException , IllegalAccessException , NoSuchMethodException , IntrospectionException { Object result = null ; Method m = getGetMethod ( context , ( target == null ) ? null : target . getClass ( ) , propertyName ) ; if ( m == null ) m = getReadMethod ( ( target == null ) ? null : target . getClass ( ) , propertyName , null ) ; if ( checkAccessAndExistence ) { if ( ( m == null ) || ! context . getMemberAccess ( ) . isAccessible ( context , target , m , propertyName ) ) { result = NotFound ; } } if ( result == null ) { if ( m != null ) { try { result = invokeMethod ( target , m , NoArguments ) ; } catch ( InvocationTargetException ex ) { throw new OgnlException ( propertyName , ex . getTargetException ( ) ) ; } } else { throw new NoSuchMethodException ( propertyName ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Don t use this method as it doesn t check member access rights via { [CODESPLIT] @ Deprecated public static boolean setMethodValue ( OgnlContext context , Object target , String propertyName , Object value ) throws OgnlException , IllegalAccessException , NoSuchMethodException , IntrospectionException { return setMethodValue ( context , target , propertyName , value , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the property descriptors for the given class as a Map . [CODESPLIT] public static Map getPropertyDescriptors ( Class targetClass ) throws IntrospectionException , OgnlException { Map result ; if ( ( result = ( Map ) _propertyDescriptorCache . get ( targetClass ) ) == null ) { synchronized ( _propertyDescriptorCache ) { if ( ( result = ( Map ) _propertyDescriptorCache . get ( targetClass ) ) == null ) { PropertyDescriptor [ ] pda = Introspector . getBeanInfo ( targetClass ) . getPropertyDescriptors ( ) ; result = new HashMap ( 101 ) ; for ( int i = 0 , icount = pda . length ; i < icount ; i ++ ) { // workaround for Introspector bug 6528714 (bugs.sun.com) if ( pda [ i ] . getReadMethod ( ) != null && ! isMethodCallable ( pda [ i ] . getReadMethod ( ) ) ) { pda [ i ] . setReadMethod ( findClosestMatchingMethod ( targetClass , pda [ i ] . getReadMethod ( ) , pda [ i ] . getName ( ) , pda [ i ] . getPropertyType ( ) , true ) ) ; } if ( pda [ i ] . getWriteMethod ( ) != null && ! isMethodCallable ( pda [ i ] . getWriteMethod ( ) ) ) { pda [ i ] . setWriteMethod ( findClosestMatchingMethod ( targetClass , pda [ i ] . getWriteMethod ( ) , pda [ i ] . getName ( ) , pda [ i ] . getPropertyType ( ) , false ) ) ; } result . put ( pda [ i ] . getName ( ) , pda [ i ] ) ; } findObjectIndexedPropertyDescriptors ( targetClass , result ) ; _propertyDescriptorCache . put ( targetClass , result ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns a PropertyDescriptor for the given class and property name using a Map lookup ( using getPropertyDescriptorsMap () ) . [CODESPLIT] public static PropertyDescriptor getPropertyDescriptor ( Class targetClass , String propertyName ) throws IntrospectionException , OgnlException { if ( targetClass == null ) return null ; return ( PropertyDescriptor ) getPropertyDescriptors ( targetClass ) . get ( propertyName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the property descriptor with the given name for the target class given . [CODESPLIT] public static PropertyDescriptor getPropertyDescriptorFromArray ( Class targetClass , String name ) throws IntrospectionException { PropertyDescriptor result = null ; PropertyDescriptor [ ] pda = getPropertyDescriptorsArray ( targetClass ) ; for ( int i = 0 , icount = pda . length ; ( result == null ) && ( i < icount ) ; i ++ ) { if ( pda [ i ] . getName ( ) . compareTo ( name ) == 0 ) { result = pda [ i ] ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines the index property type if any . Returns <code > INDEXED_PROPERTY_NONE< / code > if the property is not index - accessible as determined by OGNL or JavaBeans . If it is indexable then this will return whether it is a JavaBeans indexed property conforming to the indexed property patterns ( returns <code > INDEXED_PROPERTY_INT< / code > ) or if it conforms to the OGNL arbitrary object indexable ( returns <code > INDEXED_PROPERTY_OBJECT< / code > ) . [CODESPLIT] public static int getIndexedPropertyType ( OgnlContext context , Class sourceClass , String name ) throws OgnlException { int result = INDEXED_PROPERTY_NONE ; try { PropertyDescriptor pd = getPropertyDescriptor ( sourceClass , name ) ; if ( pd != null ) { if ( pd instanceof IndexedPropertyDescriptor ) { result = INDEXED_PROPERTY_INT ; } else { if ( pd instanceof ObjectIndexedPropertyDescriptor ) { result = INDEXED_PROPERTY_OBJECT ; } } } } catch ( Exception ex ) { throw new OgnlException ( \"problem determining if '\" + name + \"' is an indexed property\" , ex ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the specified { @link ClassCacheInspector } with all class reflection based internal caches . This may have a significant performance impact so be careful using this in production scenarios . [CODESPLIT] public static void setClassCacheInspector ( ClassCacheInspector inspector ) { _cacheInspector = inspector ; _propertyDescriptorCache . setClassInspector ( _cacheInspector ) ; _constructorCache . setClassInspector ( _cacheInspector ) ; _staticMethodCache . setClassInspector ( _cacheInspector ) ; _instanceMethodCache . setClassInspector ( _cacheInspector ) ; _invokePermissionCache . setClassInspector ( _cacheInspector ) ; _fieldCache . setClassInspector ( _cacheInspector ) ; _declaredMethods [ 0 ] . setClassInspector ( _cacheInspector ) ; _declaredMethods [ 1 ] . setClassInspector ( _cacheInspector ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the best possible match for a method on the specified target class with a matching name . [CODESPLIT] public static Method getReadMethod ( Class target , String name ) { return getReadMethod ( target , name , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the { @link OgnlContext#getCurrentType () } and { @link OgnlContext#getPreviousType () } class types on the stack to determine if a numeric expression should force object conversion . <p / > <p / > Normally used in conjunction with the <code > forceConversion< / code > parameter of { @link OgnlRuntime#getChildSource ( OgnlContext Object Node boolean ) } . < / p > [CODESPLIT] public static boolean shouldConvertNumericTypes ( OgnlContext context ) { if ( context . getCurrentType ( ) == null || context . getPreviousType ( ) == null ) return true ; if ( context . getCurrentType ( ) == context . getPreviousType ( ) && context . getCurrentType ( ) . isPrimitive ( ) && context . getPreviousType ( ) . isPrimitive ( ) ) return false ; return context . getCurrentType ( ) != null && ! context . getCurrentType ( ) . isArray ( ) && context . getPreviousType ( ) != null && ! context . getPreviousType ( ) . isArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to get the java source string represented by the specific child expression via the { @link JavaSource#toGetSourceString ( OgnlContext Object ) } interface method . [CODESPLIT] public static String getChildSource ( OgnlContext context , Object target , Node child ) throws OgnlException { return getChildSource ( context , target , child , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to get the java source string represented by the specific child expression via the { @link JavaSource#toGetSourceString ( OgnlContext Object ) } interface method . [CODESPLIT] public static String getChildSource ( OgnlContext context , Object target , Node child , boolean forceConversion ) throws OgnlException { String pre = ( String ) context . get ( \"_currentChain\" ) ; if ( pre == null ) pre = \"\" ; try { child . getValue ( context , target ) ; } catch ( NullPointerException e ) { // ignore } catch ( ArithmeticException e ) { context . setCurrentType ( int . class ) ; return \"0\" ; } catch ( Throwable t ) { throw OgnlOps . castToRuntime ( t ) ; } String source = null ; try { source = child . toGetSourceString ( context , target ) ; } catch ( Throwable t ) { throw OgnlOps . castToRuntime ( t ) ; } // handle root / method expressions that may not have proper root java source access if ( ! ASTConst . class . isInstance ( child ) && ( target == null || context . getRoot ( ) != target ) ) { source = pre + source ; } if ( context . getRoot ( ) != null ) { source = ExpressionCompiler . getRootExpression ( child , context . getRoot ( ) , context ) + source ; context . setCurrentAccessor ( context . getRoot ( ) . getClass ( ) ) ; } if ( ASTChain . class . isInstance ( child ) ) { String cast = ( String ) context . remove ( ExpressionCompiler . PRE_CAST ) ; if ( cast == null ) cast = \"\" ; source = cast + source ; } if ( source == null || source . trim ( ) . length ( ) < 1 ) source = \"null\" ; return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the stack trace for this ( and possibly the encapsulated ) exception on the given print stream . [CODESPLIT] public void printStackTrace ( java . io . PrintStream s ) { synchronized ( s ) { super . printStackTrace ( s ) ; if ( _reason != null ) { s . println ( \"/-- Encapsulated exception ------------\\\\\" ) ; _reason . printStackTrace ( s ) ; s . println ( \"\\\\--------------------------------------/\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the stack trace for this ( and possibly the encapsulated ) exception on the given print writer . [CODESPLIT] public void printStackTrace ( java . io . PrintWriter s ) { synchronized ( s ) { super . printStackTrace ( s ) ; if ( _reason != null ) { s . println ( \"/-- Encapsulated exception ------------\\\\\" ) ; _reason . printStackTrace ( s ) ; s . println ( \"\\\\--------------------------------------/\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * NullHandler interface [CODESPLIT] public Object nullMethodResult ( Map context , Object target , String methodName , Object [ ] args ) { return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a character . [CODESPLIT] public char readChar ( ) throws java . io . IOException { if ( inBuf > 0 ) { -- inBuf ; if ( ++ bufpos == bufsize ) bufpos = 0 ; return buffer [ bufpos ] ; } char c ; if ( ++ bufpos == available ) AdjustBuffSize ( ) ; if ( ( buffer [ bufpos ] = c = ReadByte ( ) ) == ' ' ) { UpdateLineColumn ( c ) ; int backSlashCnt = 1 ; for ( ; ; ) // Read all the backslashes { if ( ++ bufpos == available ) AdjustBuffSize ( ) ; try { if ( ( buffer [ bufpos ] = c = ReadByte ( ) ) != ' ' ) { UpdateLineColumn ( c ) ; // found a non-backslash char. if ( ( c == ' ' ) && ( ( backSlashCnt & 1 ) == 1 ) ) { if ( -- bufpos < 0 ) bufpos = bufsize - 1 ; break ; } backup ( backSlashCnt ) ; return ' ' ; } } catch ( java . io . IOException e ) { if ( backSlashCnt > 1 ) backup ( backSlashCnt - 1 ) ; return ' ' ; } UpdateLineColumn ( c ) ; backSlashCnt ++ ; } // Here, we have seen an odd number of backslash's followed by a 'u' try { while ( ( c = ReadByte ( ) ) == ' ' ) ++ column ; buffer [ bufpos ] = c = ( char ) ( hexval ( c ) << 12 | hexval ( ReadByte ( ) ) << 8 | hexval ( ReadByte ( ) ) << 4 | hexval ( ReadByte ( ) ) ) ; column += 4 ; } catch ( java . io . IOException e ) { throw new Error ( \"Invalid escape character at line \" + line + \" column \" + column + \".\" ) ; } if ( backSlashCnt == 1 ) return c ; else { backup ( backSlashCnt - 1 ) ; return ' ' ; } } else { UpdateLineColumn ( c ) ; return c ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sequence ( level 14 ) [CODESPLIT] final public void expression ( ) throws ParseException { assignmentExpression ( ) ; label_1 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 1 : ; break ; default : jj_la1 [ 0 ] = jj_gen ; break label_1 ; } jj_consume_token ( 1 ) ; ASTSequence jjtn001 = new ASTSequence ( JJTSEQUENCE ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { assignmentExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assignment expression ( level 13 ) [CODESPLIT] final public void assignmentExpression ( ) throws ParseException { conditionalTestExpression ( ) ; switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 2 : jj_consume_token ( 2 ) ; ASTAssign jjtn001 = new ASTAssign ( JJTASSIGN ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { assignmentExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } break ; default : jj_la1 [ 1 ] = jj_gen ; ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "logical or ( || ) ( level 11 ) [CODESPLIT] final public void logicalOrExpression ( ) throws ParseException { logicalAndExpression ( ) ; label_2 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 5 : case 6 : ; break ; default : jj_la1 [ 3 ] = jj_gen ; break label_2 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 5 : jj_consume_token ( 5 ) ; break ; case 6 : jj_consume_token ( 6 ) ; break ; default : jj_la1 [ 4 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTOr jjtn001 = new ASTOr ( JJTOR ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { logicalAndExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "logical and ( && ) ( level 10 ) [CODESPLIT] final public void logicalAndExpression ( ) throws ParseException { inclusiveOrExpression ( ) ; label_3 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 7 : case 8 : ; break ; default : jj_la1 [ 5 ] = jj_gen ; break label_3 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 7 : jj_consume_token ( 7 ) ; break ; case 8 : jj_consume_token ( 8 ) ; break ; default : jj_la1 [ 6 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTAnd jjtn001 = new ASTAnd ( JJTAND ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { inclusiveOrExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bitwise or non - short - circuiting or ( | ) ( level 9 ) [CODESPLIT] final public void inclusiveOrExpression ( ) throws ParseException { exclusiveOrExpression ( ) ; label_4 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 9 : case 10 : ; break ; default : jj_la1 [ 7 ] = jj_gen ; break label_4 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 9 : jj_consume_token ( 9 ) ; break ; case 10 : jj_consume_token ( 10 ) ; break ; default : jj_la1 [ 8 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTBitOr jjtn001 = new ASTBitOr ( JJTBITOR ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { exclusiveOrExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exclusive or ( ^ ) ( level 8 ) [CODESPLIT] final public void exclusiveOrExpression ( ) throws ParseException { andExpression ( ) ; label_5 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 11 : case 12 : ; break ; default : jj_la1 [ 9 ] = jj_gen ; break label_5 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 11 : jj_consume_token ( 11 ) ; break ; case 12 : jj_consume_token ( 12 ) ; break ; default : jj_la1 [ 10 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTXor jjtn001 = new ASTXor ( JJTXOR ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { andExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bitwise or non - short - circuiting and ( & ) ( level 7 ) [CODESPLIT] final public void andExpression ( ) throws ParseException { equalityExpression ( ) ; label_6 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 13 : case 14 : ; break ; default : jj_la1 [ 11 ] = jj_gen ; break label_6 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 13 : jj_consume_token ( 13 ) ; break ; case 14 : jj_consume_token ( 14 ) ; break ; default : jj_la1 [ 12 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTBitAnd jjtn001 = new ASTBitAnd ( JJTBITAND ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { equalityExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "equality / inequality ( == / ! = ) ( level 6 ) [CODESPLIT] final public void equalityExpression ( ) throws ParseException { relationalExpression ( ) ; label_7 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 15 : case 16 : case 17 : case 18 : ; break ; default : jj_la1 [ 13 ] = jj_gen ; break label_7 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 15 : case 16 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 15 : jj_consume_token ( 15 ) ; break ; case 16 : jj_consume_token ( 16 ) ; break ; default : jj_la1 [ 14 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTEq jjtn001 = new ASTEq ( JJTEQ ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { relationalExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } break ; case 17 : case 18 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 17 : jj_consume_token ( 17 ) ; break ; case 18 : jj_consume_token ( 18 ) ; break ; default : jj_la1 [ 15 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTNotEq jjtn002 = new ASTNotEq ( JJTNOTEQ ) ; boolean jjtc002 = true ; jjtree . openNodeScope ( jjtn002 ) ; try { relationalExpression ( ) ; } catch ( Throwable jjte002 ) { if ( jjtc002 ) { jjtree . clearNodeScope ( jjtn002 ) ; jjtc002 = false ; } else { jjtree . popNode ( ) ; } if ( jjte002 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte002 ; } } if ( jjte002 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte002 ; } } { if ( true ) throw ( Error ) jjte002 ; } } finally { if ( jjtc002 ) { jjtree . closeNodeScope ( jjtn002 , 2 ) ; } } break ; default : jj_la1 [ 16 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "boolean relational expressions ( level 5 ) [CODESPLIT] final public void relationalExpression ( ) throws ParseException { shiftExpression ( ) ; label_8 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 19 : case 20 : case 21 : case 22 : case 23 : case 24 : case 25 : case 26 : case 27 : case 28 : ; break ; default : jj_la1 [ 17 ] = jj_gen ; break label_8 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 19 : case 20 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 19 : jj_consume_token ( 19 ) ; break ; case 20 : jj_consume_token ( 20 ) ; break ; default : jj_la1 [ 18 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTLess jjtn001 = new ASTLess ( JJTLESS ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { shiftExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } break ; case 21 : case 22 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 21 : jj_consume_token ( 21 ) ; break ; case 22 : jj_consume_token ( 22 ) ; break ; default : jj_la1 [ 19 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTGreater jjtn002 = new ASTGreater ( JJTGREATER ) ; boolean jjtc002 = true ; jjtree . openNodeScope ( jjtn002 ) ; try { shiftExpression ( ) ; } catch ( Throwable jjte002 ) { if ( jjtc002 ) { jjtree . clearNodeScope ( jjtn002 ) ; jjtc002 = false ; } else { jjtree . popNode ( ) ; } if ( jjte002 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte002 ; } } if ( jjte002 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte002 ; } } { if ( true ) throw ( Error ) jjte002 ; } } finally { if ( jjtc002 ) { jjtree . closeNodeScope ( jjtn002 , 2 ) ; } } break ; case 23 : case 24 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 23 : jj_consume_token ( 23 ) ; break ; case 24 : jj_consume_token ( 24 ) ; break ; default : jj_la1 [ 20 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTLessEq jjtn003 = new ASTLessEq ( JJTLESSEQ ) ; boolean jjtc003 = true ; jjtree . openNodeScope ( jjtn003 ) ; try { shiftExpression ( ) ; } catch ( Throwable jjte003 ) { if ( jjtc003 ) { jjtree . clearNodeScope ( jjtn003 ) ; jjtc003 = false ; } else { jjtree . popNode ( ) ; } if ( jjte003 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte003 ; } } if ( jjte003 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte003 ; } } { if ( true ) throw ( Error ) jjte003 ; } } finally { if ( jjtc003 ) { jjtree . closeNodeScope ( jjtn003 , 2 ) ; } } break ; case 25 : case 26 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 25 : jj_consume_token ( 25 ) ; break ; case 26 : jj_consume_token ( 26 ) ; break ; default : jj_la1 [ 21 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTGreaterEq jjtn004 = new ASTGreaterEq ( JJTGREATEREQ ) ; boolean jjtc004 = true ; jjtree . openNodeScope ( jjtn004 ) ; try { shiftExpression ( ) ; } catch ( Throwable jjte004 ) { if ( jjtc004 ) { jjtree . clearNodeScope ( jjtn004 ) ; jjtc004 = false ; } else { jjtree . popNode ( ) ; } if ( jjte004 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte004 ; } } if ( jjte004 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte004 ; } } { if ( true ) throw ( Error ) jjte004 ; } } finally { if ( jjtc004 ) { jjtree . closeNodeScope ( jjtn004 , 2 ) ; } } break ; case 27 : jj_consume_token ( 27 ) ; ASTIn jjtn005 = new ASTIn ( JJTIN ) ; boolean jjtc005 = true ; jjtree . openNodeScope ( jjtn005 ) ; try { shiftExpression ( ) ; } catch ( Throwable jjte005 ) { if ( jjtc005 ) { jjtree . clearNodeScope ( jjtn005 ) ; jjtc005 = false ; } else { jjtree . popNode ( ) ; } if ( jjte005 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte005 ; } } if ( jjte005 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte005 ; } } { if ( true ) throw ( Error ) jjte005 ; } } finally { if ( jjtc005 ) { jjtree . closeNodeScope ( jjtn005 , 2 ) ; } } break ; case 28 : jj_consume_token ( 28 ) ; jj_consume_token ( 27 ) ; ASTNotIn jjtn006 = new ASTNotIn ( JJTNOTIN ) ; boolean jjtc006 = true ; jjtree . openNodeScope ( jjtn006 ) ; try { shiftExpression ( ) ; } catch ( Throwable jjte006 ) { if ( jjtc006 ) { jjtree . clearNodeScope ( jjtn006 ) ; jjtc006 = false ; } else { jjtree . popNode ( ) ; } if ( jjte006 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte006 ; } } if ( jjte006 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte006 ; } } { if ( true ) throw ( Error ) jjte006 ; } } finally { if ( jjtc006 ) { jjtree . closeNodeScope ( jjtn006 , 2 ) ; } } break ; default : jj_la1 [ 22 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bit shift expressions ( level 4 ) [CODESPLIT] final public void shiftExpression ( ) throws ParseException { additiveExpression ( ) ; label_9 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 29 : case 30 : case 31 : case 32 : case 33 : case 34 : ; break ; default : jj_la1 [ 23 ] = jj_gen ; break label_9 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 29 : case 30 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 29 : jj_consume_token ( 29 ) ; break ; case 30 : jj_consume_token ( 30 ) ; break ; default : jj_la1 [ 24 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTShiftLeft jjtn001 = new ASTShiftLeft ( JJTSHIFTLEFT ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { additiveExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } break ; case 31 : case 32 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 31 : jj_consume_token ( 31 ) ; break ; case 32 : jj_consume_token ( 32 ) ; break ; default : jj_la1 [ 25 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTShiftRight jjtn002 = new ASTShiftRight ( JJTSHIFTRIGHT ) ; boolean jjtc002 = true ; jjtree . openNodeScope ( jjtn002 ) ; try { additiveExpression ( ) ; } catch ( Throwable jjte002 ) { if ( jjtc002 ) { jjtree . clearNodeScope ( jjtn002 ) ; jjtc002 = false ; } else { jjtree . popNode ( ) ; } if ( jjte002 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte002 ; } } if ( jjte002 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte002 ; } } { if ( true ) throw ( Error ) jjte002 ; } } finally { if ( jjtc002 ) { jjtree . closeNodeScope ( jjtn002 , 2 ) ; } } break ; case 33 : case 34 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 33 : jj_consume_token ( 33 ) ; break ; case 34 : jj_consume_token ( 34 ) ; break ; default : jj_la1 [ 26 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTUnsignedShiftRight jjtn003 = new ASTUnsignedShiftRight ( JJTUNSIGNEDSHIFTRIGHT ) ; boolean jjtc003 = true ; jjtree . openNodeScope ( jjtn003 ) ; try { additiveExpression ( ) ; } catch ( Throwable jjte003 ) { if ( jjtc003 ) { jjtree . clearNodeScope ( jjtn003 ) ; jjtc003 = false ; } else { jjtree . popNode ( ) ; } if ( jjte003 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte003 ; } } if ( jjte003 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte003 ; } } { if ( true ) throw ( Error ) jjte003 ; } } finally { if ( jjtc003 ) { jjtree . closeNodeScope ( jjtn003 , 2 ) ; } } break ; default : jj_la1 [ 27 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "binary addition / subtraction ( level 3 ) [CODESPLIT] final public void additiveExpression ( ) throws ParseException { multiplicativeExpression ( ) ; label_10 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 35 : case 36 : ; break ; default : jj_la1 [ 28 ] = jj_gen ; break label_10 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 35 : jj_consume_token ( 35 ) ; ASTAdd jjtn001 = new ASTAdd ( JJTADD ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { multiplicativeExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } break ; case 36 : jj_consume_token ( 36 ) ; ASTSubtract jjtn002 = new ASTSubtract ( JJTSUBTRACT ) ; boolean jjtc002 = true ; jjtree . openNodeScope ( jjtn002 ) ; try { multiplicativeExpression ( ) ; } catch ( Throwable jjte002 ) { if ( jjtc002 ) { jjtree . clearNodeScope ( jjtn002 ) ; jjtc002 = false ; } else { jjtree . popNode ( ) ; } if ( jjte002 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte002 ; } } if ( jjte002 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte002 ; } } { if ( true ) throw ( Error ) jjte002 ; } } finally { if ( jjtc002 ) { jjtree . closeNodeScope ( jjtn002 , 2 ) ; } } break ; default : jj_la1 [ 29 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "multiplication / division / remainder ( level 2 ) [CODESPLIT] final public void multiplicativeExpression ( ) throws ParseException { unaryExpression ( ) ; label_11 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 37 : case 38 : case 39 : ; break ; default : jj_la1 [ 30 ] = jj_gen ; break label_11 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 37 : jj_consume_token ( 37 ) ; ASTMultiply jjtn001 = new ASTMultiply ( JJTMULTIPLY ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { unaryExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } break ; case 38 : jj_consume_token ( 38 ) ; ASTDivide jjtn002 = new ASTDivide ( JJTDIVIDE ) ; boolean jjtc002 = true ; jjtree . openNodeScope ( jjtn002 ) ; try { unaryExpression ( ) ; } catch ( Throwable jjte002 ) { if ( jjtc002 ) { jjtree . clearNodeScope ( jjtn002 ) ; jjtc002 = false ; } else { jjtree . popNode ( ) ; } if ( jjte002 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte002 ; } } if ( jjte002 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte002 ; } } { if ( true ) throw ( Error ) jjte002 ; } } finally { if ( jjtc002 ) { jjtree . closeNodeScope ( jjtn002 , 2 ) ; } } break ; case 39 : jj_consume_token ( 39 ) ; ASTRemainder jjtn003 = new ASTRemainder ( JJTREMAINDER ) ; boolean jjtc003 = true ; jjtree . openNodeScope ( jjtn003 ) ; try { unaryExpression ( ) ; } catch ( Throwable jjte003 ) { if ( jjtc003 ) { jjtree . clearNodeScope ( jjtn003 ) ; jjtc003 = false ; } else { jjtree . popNode ( ) ; } if ( jjte003 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte003 ; } } if ( jjte003 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte003 ; } } { if ( true ) throw ( Error ) jjte003 ; } } finally { if ( jjtc003 ) { jjtree . closeNodeScope ( jjtn003 , 2 ) ; } } break ; default : jj_la1 [ 31 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unary ( level 1 ) [CODESPLIT] final public void unaryExpression ( ) throws ParseException { StringBuffer sb ; Token t ; ASTInstanceof ionode ; switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 36 : jj_consume_token ( 36 ) ; ASTNegate jjtn001 = new ASTNegate ( JJTNEGATE ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { unaryExpression ( ) ; } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 1 ) ; } } break ; case 35 : jj_consume_token ( 35 ) ; unaryExpression ( ) ; break ; case 40 : jj_consume_token ( 40 ) ; ASTBitNegate jjtn002 = new ASTBitNegate ( JJTBITNEGATE ) ; boolean jjtc002 = true ; jjtree . openNodeScope ( jjtn002 ) ; try { unaryExpression ( ) ; } catch ( Throwable jjte002 ) { if ( jjtc002 ) { jjtree . clearNodeScope ( jjtn002 ) ; jjtc002 = false ; } else { jjtree . popNode ( ) ; } if ( jjte002 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte002 ; } } if ( jjte002 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte002 ; } } { if ( true ) throw ( Error ) jjte002 ; } } finally { if ( jjtc002 ) { jjtree . closeNodeScope ( jjtn002 , 1 ) ; } } break ; case 28 : case 41 : switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 41 : jj_consume_token ( 41 ) ; break ; case 28 : jj_consume_token ( 28 ) ; break ; default : jj_la1 [ 32 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } ASTNot jjtn003 = new ASTNot ( JJTNOT ) ; boolean jjtc003 = true ; jjtree . openNodeScope ( jjtn003 ) ; try { unaryExpression ( ) ; } catch ( Throwable jjte003 ) { if ( jjtc003 ) { jjtree . clearNodeScope ( jjtn003 ) ; jjtc003 = false ; } else { jjtree . popNode ( ) ; } if ( jjte003 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte003 ; } } if ( jjte003 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte003 ; } } { if ( true ) throw ( Error ) jjte003 ; } } finally { if ( jjtc003 ) { jjtree . closeNodeScope ( jjtn003 , 1 ) ; } } break ; case 4 : case 44 : case 46 : case 47 : case 48 : case 49 : case 50 : case 51 : case 52 : case 54 : case 56 : case 57 : case IDENT : case DYNAMIC_SUBSCRIPT : case CHAR_LITERAL : case BACK_CHAR_LITERAL : case STRING_LITERAL : case INT_LITERAL : case FLT_LITERAL : navigationChain ( ) ; switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 42 : jj_consume_token ( 42 ) ; t = jj_consume_token ( IDENT ) ; ASTInstanceof jjtn004 = new ASTInstanceof ( JJTINSTANCEOF ) ; boolean jjtc004 = true ; jjtree . openNodeScope ( jjtn004 ) ; try { jjtree . closeNodeScope ( jjtn004 , 1 ) ; jjtc004 = false ; sb = new StringBuffer ( t . image ) ; ionode = jjtn004 ; } finally { if ( jjtc004 ) { jjtree . closeNodeScope ( jjtn004 , 1 ) ; } } label_12 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 43 : ; break ; default : jj_la1 [ 33 ] = jj_gen ; break label_12 ; } jj_consume_token ( 43 ) ; t = jj_consume_token ( IDENT ) ; sb . append ( ' ' ) . append ( t . image ) ; } ionode . setTargetType ( new String ( sb ) ) ; break ; default : jj_la1 [ 34 ] = jj_gen ; ; } break ; default : jj_la1 [ 35 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "navigation chain : property references method calls projections selections etc . [CODESPLIT] final public void navigationChain ( ) throws ParseException { primaryExpression ( ) ; label_13 : while ( true ) { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 43 : case 44 : case 52 : case DYNAMIC_SUBSCRIPT : ; break ; default : jj_la1 [ 36 ] = jj_gen ; break label_13 ; } switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 43 : jj_consume_token ( 43 ) ; ASTChain jjtn001 = new ASTChain ( JJTCHAIN ) ; boolean jjtc001 = true ; jjtree . openNodeScope ( jjtn001 ) ; try { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case IDENT : if ( jj_2_1 ( 2 ) ) { methodCall ( ) ; } else { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case IDENT : propertyName ( ) ; break ; default : jj_la1 [ 37 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } break ; case 54 : if ( jj_2_2 ( 2 ) ) { projection ( ) ; } else { switch ( ( jj_ntk == - 1 ) ? jj_ntk ( ) : jj_ntk ) { case 54 : selection ( ) ; break ; default : jj_la1 [ 38 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } break ; case 44 : jj_consume_token ( 44 ) ; expression ( ) ; jj_consume_token ( 45 ) ; break ; default : jj_la1 [ 39 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } catch ( Throwable jjte001 ) { if ( jjtc001 ) { jjtree . clearNodeScope ( jjtn001 ) ; jjtc001 = false ; } else { jjtree . popNode ( ) ; } if ( jjte001 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte001 ; } } if ( jjte001 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte001 ; } } { if ( true ) throw ( Error ) jjte001 ; } } finally { if ( jjtc001 ) { jjtree . closeNodeScope ( jjtn001 , 2 ) ; } } break ; case 52 : case DYNAMIC_SUBSCRIPT : ASTChain jjtn002 = new ASTChain ( JJTCHAIN ) ; boolean jjtc002 = true ; jjtree . openNodeScope ( jjtn002 ) ; try { index ( ) ; } catch ( Throwable jjte002 ) { if ( jjtc002 ) { jjtree . clearNodeScope ( jjtn002 ) ; jjtc002 = false ; } else { jjtree . popNode ( ) ; } if ( jjte002 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte002 ; } } if ( jjte002 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte002 ; } } { if ( true ) throw ( Error ) jjte002 ; } } finally { if ( jjtc002 ) { jjtree . closeNodeScope ( jjtn002 , 2 ) ; } } break ; case 44 : jj_consume_token ( 44 ) ; expression ( ) ; ASTEval jjtn003 = new ASTEval ( JJTEVAL ) ; boolean jjtc003 = true ; jjtree . openNodeScope ( jjtn003 ) ; try { jj_consume_token ( 45 ) ; } finally { if ( jjtc003 ) { jjtree . closeNodeScope ( jjtn003 , 2 ) ; } } break ; default : jj_la1 [ 40 ] = jj_gen ; jj_consume_token ( - 1 ) ; throw new ParseException ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply an expression to all elements of a collection creating a new collection as the result . [CODESPLIT] final public void projection ( ) throws ParseException { /*@bgen(jjtree) Project */ ASTProject jjtn000 = new ASTProject ( JJTPROJECT ) ; boolean jjtc000 = true ; jjtree . openNodeScope ( jjtn000 ) ; try { jj_consume_token ( 54 ) ; expression ( ) ; jj_consume_token ( 55 ) ; } catch ( Throwable jjte000 ) { if ( jjtc000 ) { jjtree . clearNodeScope ( jjtn000 ) ; jjtc000 = false ; } else { jjtree . popNode ( ) ; } if ( jjte000 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte000 ; } } if ( jjte000 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte000 ; } } { if ( true ) throw ( Error ) jjte000 ; } } finally { if ( jjtc000 ) { jjtree . closeNodeScope ( jjtn000 , true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply a boolean expression to all elements of a collection creating a new collection containing those elements for which the expression returned true . [CODESPLIT] final public void selectAll ( ) throws ParseException { /*@bgen(jjtree) Select */ ASTSelect jjtn000 = new ASTSelect ( JJTSELECT ) ; boolean jjtc000 = true ; jjtree . openNodeScope ( jjtn000 ) ; try { jj_consume_token ( 54 ) ; jj_consume_token ( 3 ) ; expression ( ) ; jj_consume_token ( 55 ) ; } catch ( Throwable jjte000 ) { if ( jjtc000 ) { jjtree . clearNodeScope ( jjtn000 ) ; jjtc000 = false ; } else { jjtree . popNode ( ) ; } if ( jjte000 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte000 ; } } if ( jjte000 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte000 ; } } { if ( true ) throw ( Error ) jjte000 ; } } finally { if ( jjtc000 ) { jjtree . closeNodeScope ( jjtn000 , true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply a boolean expression to all elements of a collection creating a new collection containing those elements for the first element for which the expression returned true . [CODESPLIT] final public void selectFirst ( ) throws ParseException { /*@bgen(jjtree) SelectFirst */ ASTSelectFirst jjtn000 = new ASTSelectFirst ( JJTSELECTFIRST ) ; boolean jjtc000 = true ; jjtree . openNodeScope ( jjtn000 ) ; try { jj_consume_token ( 54 ) ; jj_consume_token ( 11 ) ; expression ( ) ; jj_consume_token ( 55 ) ; } catch ( Throwable jjte000 ) { if ( jjtc000 ) { jjtree . clearNodeScope ( jjtn000 ) ; jjtc000 = false ; } else { jjtree . popNode ( ) ; } if ( jjte000 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte000 ; } } if ( jjte000 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte000 ; } } { if ( true ) throw ( Error ) jjte000 ; } } finally { if ( jjtc000 ) { jjtree . closeNodeScope ( jjtn000 , true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply a boolean expression to all elements of a collection creating a new collection containing those elements for the first element for which the expression returned true . [CODESPLIT] final public void selectLast ( ) throws ParseException { /*@bgen(jjtree) SelectLast */ ASTSelectLast jjtn000 = new ASTSelectLast ( JJTSELECTLAST ) ; boolean jjtc000 = true ; jjtree . openNodeScope ( jjtn000 ) ; try { jj_consume_token ( 54 ) ; jj_consume_token ( 58 ) ; expression ( ) ; jj_consume_token ( 55 ) ; } catch ( Throwable jjte000 ) { if ( jjtc000 ) { jjtree . clearNodeScope ( jjtn000 ) ; jjtc000 = false ; } else { jjtree . popNode ( ) ; } if ( jjte000 instanceof RuntimeException ) { { if ( true ) throw ( RuntimeException ) jjte000 ; } } if ( jjte000 instanceof ParseException ) { { if ( true ) throw ( ParseException ) jjte000 ; } } { if ( true ) throw ( Error ) jjte000 ; } } finally { if ( jjtc000 ) { jjtree . closeNodeScope ( jjtn000 , true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two objects for equality even if it has to convert one of them to the other type . If both objects are numeric they are converted to the widest type and compared . If one is non - numeric and one is numeric the non - numeric is converted to double and compared to the double numeric value . If both are non - numeric and Comparable and the types are compatible ( i . e . v1 is of the same or superclass of v2 s type ) they are compared with Comparable . compareTo () . If both values are non - numeric and not Comparable or of incompatible classes this will throw and IllegalArgumentException . [CODESPLIT] public static int compareWithConversion ( Object v1 , Object v2 ) { int result ; if ( v1 == v2 ) { result = 0 ; } else { int t1 = getNumericType ( v1 ) , t2 = getNumericType ( v2 ) , type = getNumericType ( t1 , t2 , true ) ; switch ( type ) { case BIGINT : result = bigIntValue ( v1 ) . compareTo ( bigIntValue ( v2 ) ) ; break ; case BIGDEC : result = bigDecValue ( v1 ) . compareTo ( bigDecValue ( v2 ) ) ; break ; case NONNUMERIC : if ( ( t1 == NONNUMERIC ) && ( t2 == NONNUMERIC ) ) { if ( ( v1 instanceof Comparable ) && v1 . getClass ( ) . isAssignableFrom ( v2 . getClass ( ) ) ) { result = ( ( Comparable ) v1 ) . compareTo ( v2 ) ; break ; } else { throw new IllegalArgumentException ( \"invalid comparison: \" + v1 . getClass ( ) . getName ( ) + \" and \" + v2 . getClass ( ) . getName ( ) ) ; } } // else fall through case FLOAT : case DOUBLE : double dv1 = doubleValue ( v1 ) , dv2 = doubleValue ( v2 ) ; return ( dv1 == dv2 ) ? 0 : ( ( dv1 < dv2 ) ? - 1 : 1 ) ; default : long lv1 = longValue ( v1 ) , lv2 = longValue ( v2 ) ; return ( lv1 == lv2 ) ? 0 : ( ( lv1 < lv2 ) ? - 1 : 1 ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if object1 is equal to object2 in either the sense that they are the same object or if both are non - null if they are equal in the <CODE > equals () < / CODE > sense . [CODESPLIT] public static boolean isEqual ( Object object1 , Object object2 ) { boolean result = false ; if ( object1 == object2 ) { result = true ; } else { if ( ( object1 != null ) && object1 . getClass ( ) . isArray ( ) ) { if ( ( object2 != null ) && object2 . getClass ( ) . isArray ( ) && ( object2 . getClass ( ) == object1 . getClass ( ) ) ) { result = ( Array . getLength ( object1 ) == Array . getLength ( object2 ) ) ; if ( result ) { for ( int i = 0 , icount = Array . getLength ( object1 ) ; result && ( i < icount ) ; i ++ ) { result = isEqual ( Array . get ( object1 , i ) , Array . get ( object2 , i ) ) ; } } } } else { // Check for converted equivalence first, then equals() equivalence result = ( object1 != null ) && ( object2 != null ) && ( object1 . equals ( object2 ) || ( compareWithConversion ( object1 , object2 ) == 0 ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given object as a boolean : if it is a Boolean object it s easy ; if it s a Number or a Character returns true for non - zero objects ; and otherwise returns true for non - null objects . [CODESPLIT] public static boolean booleanValue ( Object value ) { if ( value == null ) return false ; Class c = value . getClass ( ) ; if ( c == Boolean . class ) return ( ( Boolean ) value ) . booleanValue ( ) ; if ( c == String . class ) return Boolean . parseBoolean ( String . valueOf ( value ) ) ; if ( c == Character . class ) return ( ( Character ) value ) . charValue ( ) != 0 ; if ( value instanceof Number ) return ( ( Number ) value ) . doubleValue ( ) != 0 ; return true ; // non-null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given object as a long integer . [CODESPLIT] public static long longValue ( Object value ) throws NumberFormatException { if ( value == null ) return 0L ; Class c = value . getClass ( ) ; if ( c . getSuperclass ( ) == Number . class ) return ( ( Number ) value ) . longValue ( ) ; if ( c == Boolean . class ) return ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ; if ( c == Character . class ) return ( ( Character ) value ) . charValue ( ) ; return Long . parseLong ( stringValue ( value , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given object as a double - precision floating - point number . [CODESPLIT] public static double doubleValue ( Object value ) throws NumberFormatException { if ( value == null ) return 0.0 ; Class c = value . getClass ( ) ; if ( c . getSuperclass ( ) == Number . class ) return ( ( Number ) value ) . doubleValue ( ) ; if ( c == Boolean . class ) return ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ; if ( c == Character . class ) return ( ( Character ) value ) . charValue ( ) ; String s = stringValue ( value , true ) ; return ( s . length ( ) == 0 ) ? 0.0 : Double . parseDouble ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given object as a BigInteger . [CODESPLIT] public static BigInteger bigIntValue ( Object value ) throws NumberFormatException { if ( value == null ) return BigInteger . valueOf ( 0L ) ; Class c = value . getClass ( ) ; if ( c == BigInteger . class ) return ( BigInteger ) value ; if ( c == BigDecimal . class ) return ( ( BigDecimal ) value ) . toBigInteger ( ) ; if ( c . getSuperclass ( ) == Number . class ) return BigInteger . valueOf ( ( ( Number ) value ) . longValue ( ) ) ; if ( c == Boolean . class ) return BigInteger . valueOf ( ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ) ; if ( c == Character . class ) return BigInteger . valueOf ( ( ( Character ) value ) . charValue ( ) ) ; return new BigInteger ( stringValue ( value , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given object as a BigDecimal . [CODESPLIT] public static BigDecimal bigDecValue ( Object value ) throws NumberFormatException { if ( value == null ) return BigDecimal . valueOf ( 0L ) ; Class c = value . getClass ( ) ; if ( c == BigDecimal . class ) return ( BigDecimal ) value ; if ( c == BigInteger . class ) return new BigDecimal ( ( BigInteger ) value ) ; if ( c == Boolean . class ) return BigDecimal . valueOf ( ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ) ; if ( c == Character . class ) return BigDecimal . valueOf ( ( ( Character ) value ) . charValue ( ) ) ; return new BigDecimal ( stringValue ( value , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given object as a String and trims it if the trim flag is true . [CODESPLIT] public static String stringValue ( Object value , boolean trim ) { String result ; if ( value == null ) { result = OgnlRuntime . NULL_STRING ; } else { result = value . toString ( ) ; if ( trim ) { result = result . trim ( ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a constant from the NumericTypes interface that represents the numeric type of the given object . [CODESPLIT] public static int getNumericType ( Object value ) { if ( value != null ) { Class c = value . getClass ( ) ; if ( c == Integer . class ) return INT ; if ( c == Double . class ) return DOUBLE ; if ( c == Boolean . class ) return BOOL ; if ( c == Byte . class ) return BYTE ; if ( c == Character . class ) return CHAR ; if ( c == Short . class ) return SHORT ; if ( c == Long . class ) return LONG ; if ( c == Float . class ) return FLOAT ; if ( c == BigInteger . class ) return BIGINT ; if ( c == BigDecimal . class ) return BIGDEC ; } return NONNUMERIC ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////// [CODESPLIT] public static Object convertValue ( char value , Class toType , boolean preventNull ) { return convertValue ( new Character ( value ) , toType , preventNull ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/////////////////////////////////////////////////////////////// [CODESPLIT] public static Object toArray ( char value , Class toType , boolean preventNull ) { return toArray ( new Character ( value ) , toType , preventNull ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value converted numerically to the given class type This method also detects when arrays are being converted and converts the components of one array to the type of the other . [CODESPLIT] public static Object convertValue ( Object value , Class toType ) { return convertValue ( value , toType , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the specified value to a primitive integer value . [CODESPLIT] public static int getIntValue ( Object value ) { try { if ( value == null ) return - 1 ; if ( Number . class . isInstance ( value ) ) { return ( ( Number ) value ) . intValue ( ) ; } String str = String . class . isInstance ( value ) ? ( String ) value : value . toString ( ) ; return Integer . parseInt ( str ) ; } catch ( Throwable t ) { throw new RuntimeException ( \"Error converting \" + value + \" to integer:\" , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the constant from the NumericTypes interface that best expresses the type of an operation which can be either numeric or not on the two given types . [CODESPLIT] public static int getNumericType ( int t1 , int t2 , boolean canBeNonNumeric ) { if ( t1 == t2 ) return t1 ; if ( canBeNonNumeric && ( t1 == NONNUMERIC || t2 == NONNUMERIC || t1 == CHAR || t2 == CHAR ) ) return NONNUMERIC ; if ( t1 == NONNUMERIC ) t1 = DOUBLE ; // Try to interpret strings as doubles... if ( t2 == NONNUMERIC ) t2 = DOUBLE ; // Try to interpret strings as doubles... if ( t1 >= MIN_REAL_TYPE ) { if ( t2 >= MIN_REAL_TYPE ) return Math . max ( t1 , t2 ) ; if ( t2 < INT ) return t1 ; if ( t2 == BIGINT ) return BIGDEC ; return Math . max ( DOUBLE , t1 ) ; } else if ( t2 >= MIN_REAL_TYPE ) { if ( t1 < INT ) return t2 ; if ( t1 == BIGINT ) return BIGDEC ; return Math . max ( DOUBLE , t2 ) ; } else return Math . max ( t1 , t2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the constant from the NumericTypes interface that best expresses the type of an operation which can be either numeric or not on the two given objects . [CODESPLIT] public static int getNumericType ( Object v1 , Object v2 , boolean canBeNonNumeric ) { return getNumericType ( getNumericType ( v1 ) , getNumericType ( v2 ) , canBeNonNumeric ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new Number object of an appropriate type to hold the given integer value . The type of the returned object is consistent with the given type argument which is a constant from the NumericTypes interface . [CODESPLIT] public static Number newInteger ( int type , long value ) { switch ( type ) { case BOOL : case CHAR : case INT : return new Integer ( ( int ) value ) ; case FLOAT : if ( ( long ) ( float ) value == value ) { return new Float ( ( float ) value ) ; } // else fall through: case DOUBLE : if ( ( long ) ( double ) value == value ) { return new Double ( ( double ) value ) ; } // else fall through: case LONG : return new Long ( value ) ; case BYTE : return new Byte ( ( byte ) value ) ; case SHORT : return new Short ( ( short ) value ) ; default : return BigInteger . valueOf ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new Number object of an appropriate type to hold the given real value . The type of the returned object is always either Float or Double and is only Float if the given type tag ( a constant from the NumericTypes interface ) is FLOAT . [CODESPLIT] public static Number newReal ( int type , double value ) { if ( type == FLOAT ) return new Float ( ( float ) value ) ; return new Double ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method that converts incoming exceptions to { @link RuntimeException } instances - or casts them if they already are . [CODESPLIT] public static RuntimeException castToRuntime ( Throwable t ) { if ( RuntimeException . class . isInstance ( t ) ) return ( RuntimeException ) t ; if ( OgnlException . class . isInstance ( t ) ) throw new UnsupportedCompilationException ( \"Error evluating expression: \" + t . getMessage ( ) , t ) ; return new RuntimeException ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * =================================================================== Overridden methods =================================================================== [CODESPLIT] public Class defineClass ( String enhancedClassName , byte [ ] byteCode ) { return defineClass ( enhancedClassName , byteCode , 0 , byteCode . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current class type being evaluated on the stack as set by { @link #setCurrentType ( Class ) } . [CODESPLIT] public Class getCurrentType ( ) { if ( _typeStack . isEmpty ( ) ) return null ; return ( Class ) _typeStack . get ( _typeStack . size ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Represents the last known object type on the evaluation stack will be the value of the last known { @link #getCurrentType () } . [CODESPLIT] public Class getPreviousType ( ) { if ( _typeStack . isEmpty ( ) ) return null ; if ( _typeStack . size ( ) > 1 ) return _typeStack . get ( _typeStack . size ( ) - 2 ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Evaluation at the relative index given . This should be zero or a negative number as a relative reference back up the evaluation stack . Therefore getEvaluation ( 0 ) returns the current Evaluation . [CODESPLIT] public Evaluation getEvaluation ( int relativeIndex ) { Evaluation result = null ; if ( relativeIndex <= 0 ) { result = _currentEvaluation ; while ( ( ++ relativeIndex < 0 ) && ( result != null ) ) { result = result . getParent ( ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes a new Evaluation onto the stack . This is done before a node evaluates . When evaluation is complete it should be popped from the stack via <code > popEvaluation () < / code > . [CODESPLIT] public void pushEvaluation ( Evaluation value ) { if ( _currentEvaluation != null ) { _currentEvaluation . addChild ( value ) ; } else { setRootEvaluation ( value ) ; } setCurrentEvaluation ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops the current Evaluation off of the top of the stack . This is done after a node has completed its evaluation . [CODESPLIT] public Evaluation popEvaluation ( ) { Evaluation result ; result = _currentEvaluation ; setCurrentEvaluation ( result . getParent ( ) ) ; if ( _currentEvaluation == null ) { setLastEvaluation ( getKeepLastEvaluation ( ) ? result : null ) ; setRootEvaluation ( null ) ; setCurrentNode ( null ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by { @link #castExpression ( ognl . OgnlContext ognl . Node String ) } to store the cast java source string in to the current { @link OgnlContext } . This will either add to the existing string present if it already exists or create a new instance and store it using the static key of { @link #PRE_CAST } . [CODESPLIT] public static void addCastString ( OgnlContext context , String cast ) { String value = ( String ) context . get ( PRE_CAST ) ; if ( value != null ) value = cast + value ; else value = cast ; context . put ( PRE_CAST , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the appropriate casting expression ( minus parens ) for the specified class type . [CODESPLIT] public static String getCastString ( Class type ) { if ( type == null ) return null ; return type . isArray ( ) ? type . getComponentType ( ) . getName ( ) + \"[]\" : type . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method called by many different property / method resolving AST types to get a root expression resolving string for the given node . The callers are mostly ignorant and rely on this method to properly determine if the expression should be cast at all and take the appropriate actions if it should . [CODESPLIT] public static String getRootExpression ( Node expression , Object root , OgnlContext context ) { String rootExpr = \"\" ; if ( ! shouldCast ( expression ) ) return rootExpr ; if ( ( ! ASTList . class . isInstance ( expression ) && ! ASTVarRef . class . isInstance ( expression ) && ! ASTStaticMethod . class . isInstance ( expression ) && ! ASTStaticField . class . isInstance ( expression ) && ! ASTConst . class . isInstance ( expression ) && ! ExpressionNode . class . isInstance ( expression ) && ! ASTCtor . class . isInstance ( expression ) && ! ASTStaticMethod . class . isInstance ( expression ) && root != null ) || ( root != null && ASTRootVarRef . class . isInstance ( expression ) ) ) { Class castClass = OgnlRuntime . getCompiler ( ) . getRootExpressionClass ( expression , context ) ; if ( castClass . isArray ( ) || ASTRootVarRef . class . isInstance ( expression ) || ASTThisVarRef . class . isInstance ( expression ) ) { rootExpr = \"((\" + getCastString ( castClass ) + \")$2)\" ; if ( ASTProperty . class . isInstance ( expression ) && ! ( ( ASTProperty ) expression ) . isIndexedAccess ( ) ) rootExpr += \".\" ; } else if ( ( ASTProperty . class . isInstance ( expression ) && ( ( ASTProperty ) expression ) . isIndexedAccess ( ) ) || ASTChain . class . isInstance ( expression ) ) { rootExpr = \"((\" + getCastString ( castClass ) + \")$2)\" ; } else { rootExpr = \"((\" + getCastString ( castClass ) + \")$2).\" ; } } return rootExpr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used by { @link #getRootExpression ( ognl . Node Object ognl . OgnlContext ) } to determine if the expression needs to be cast at all . [CODESPLIT] public static boolean shouldCast ( Node expression ) { if ( ASTChain . class . isInstance ( expression ) ) { Node child = expression . jjtGetChild ( 0 ) ; if ( ASTConst . class . isInstance ( child ) || ASTStaticMethod . class . isInstance ( child ) || ASTStaticField . class . isInstance ( child ) || ( ASTVarRef . class . isInstance ( child ) && ! ASTRootVarRef . class . isInstance ( child ) ) ) return false ; } return ! ASTConst . class . isInstance ( expression ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper utility method used by compiler to help resolve class - > method mappings during method calls to { @link OgnlExpressionCompiler#getSuperOrInterfaceClass ( java . lang . reflect . Method Class ) } . [CODESPLIT] public boolean containsMethod ( Method m , Class clazz ) { Method [ ] methods = clazz . getMethods ( ) ; if ( methods == null ) return false ; for ( int i = 0 ; i < methods . length ; i ++ ) { if ( methods [ i ] . getName ( ) . equals ( m . getName ( ) ) && methods [ i ] . getReturnType ( ) == m . getReturnType ( ) ) { Class [ ] parms = m . getParameterTypes ( ) ; if ( parms == null ) continue ; Class [ ] mparms = methods [ i ] . getParameterTypes ( ) ; if ( mparms == null || mparms . length != parms . length ) continue ; boolean parmsMatch = true ; for ( int p = 0 ; p < parms . length ; p ++ ) { if ( parms [ p ] != mparms [ p ] ) { parmsMatch = false ; break ; } } if ( ! parmsMatch ) continue ; Class [ ] exceptions = m . getExceptionTypes ( ) ; if ( exceptions == null ) continue ; Class [ ] mexceptions = methods [ i ] . getExceptionTypes ( ) ; if ( mexceptions == null || mexceptions . length != exceptions . length ) continue ; boolean exceptionsMatch = true ; for ( int e = 0 ; e < exceptions . length ; e ++ ) { if ( exceptions [ e ] != mexceptions [ e ] ) { exceptionsMatch = false ; break ; } } if ( ! exceptionsMatch ) continue ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void compileExpression ( OgnlContext context , Node expression , Object root ) throws Exception { //        System.out.println(\"Compiling expr class \" + expression.getClass().getName() + \" and root \" + root); if ( expression . getAccessor ( ) != null ) return ; String getBody , setBody ; EnhancedClassLoader loader = getClassLoader ( context ) ; ClassPool pool = getClassPool ( context , loader ) ; CtClass newClass = pool . makeClass ( expression . getClass ( ) . getName ( ) + expression . hashCode ( ) + _classCounter ++ + \"Accessor\" ) ; newClass . addInterface ( getCtClass ( ExpressionAccessor . class ) ) ; CtClass ognlClass = getCtClass ( OgnlContext . class ) ; CtClass objClass = getCtClass ( Object . class ) ; CtMethod valueGetter = new CtMethod ( objClass , \"get\" , new CtClass [ ] { ognlClass , objClass } , newClass ) ; CtMethod valueSetter = new CtMethod ( CtClass . voidType , \"set\" , new CtClass [ ] { ognlClass , objClass , objClass } , newClass ) ; CtField nodeMember = null ; // will only be set if uncompilable exception is thrown CtClass nodeClass = getCtClass ( Node . class ) ; CtMethod setExpression = null ; try { getBody = generateGetter ( context , newClass , objClass , pool , valueGetter , expression , root ) ; } catch ( UnsupportedCompilationException uc ) { //uc.printStackTrace(); nodeMember = new CtField ( nodeClass , \"_node\" , newClass ) ; newClass . addField ( nodeMember ) ; getBody = generateOgnlGetter ( newClass , valueGetter , nodeMember ) ; if ( setExpression == null ) { setExpression = CtNewMethod . setter ( \"setExpression\" , nodeMember ) ; newClass . addMethod ( setExpression ) ; } } try { setBody = generateSetter ( context , newClass , objClass , pool , valueSetter , expression , root ) ; } catch ( UnsupportedCompilationException uc ) { //uc.printStackTrace(); if ( nodeMember == null ) { nodeMember = new CtField ( nodeClass , \"_node\" , newClass ) ; newClass . addField ( nodeMember ) ; } setBody = generateOgnlSetter ( newClass , valueSetter , nodeMember ) ; if ( setExpression == null ) { setExpression = CtNewMethod . setter ( \"setExpression\" , nodeMember ) ; newClass . addMethod ( setExpression ) ; } } try { newClass . addConstructor ( CtNewConstructor . defaultConstructor ( newClass ) ) ; Class clazz = pool . toClass ( newClass ) ; newClass . detach ( ) ; expression . setAccessor ( ( ExpressionAccessor ) clazz . newInstance ( ) ) ; // need to set expression on node if the field was just defined. if ( nodeMember != null ) { expression . getAccessor ( ) . setExpression ( expression ) ; } } catch ( Throwable t ) { //t.printStackTrace(); throw new RuntimeException ( \"Error compiling expression on object \" + root + \" with expression node \" + expression + \" getter body: \" + getBody + \" setter body: \" + setBody , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fail safe getter creation when normal compilation fails . [CODESPLIT] protected String generateOgnlGetter ( CtClass clazz , CtMethod valueGetter , CtField node ) throws Exception { String body = \"return \" + node . getName ( ) + \".getValue($1, $2);\" ; valueGetter . setBody ( body ) ; clazz . addMethod ( valueGetter ) ; return body ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fail safe setter creation when normal compilation fails . [CODESPLIT] protected String generateOgnlSetter ( CtClass clazz , CtMethod valueSetter , CtField node ) throws Exception { String body = node . getName ( ) + \".setValue($1, $2, $3);\" ; valueSetter . setBody ( body ) ; clazz . addMethod ( valueSetter ) ; return body ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ClassLoader } instance compatible with the javassist classloader and normal OGNL class resolving semantics . [CODESPLIT] protected EnhancedClassLoader getClassLoader ( OgnlContext context ) { EnhancedClassLoader ret = ( EnhancedClassLoader ) _loaders . get ( context . getClassResolver ( ) ) ; if ( ret != null ) return ret ; ClassLoader classLoader = new ContextClassLoader ( OgnlContext . class . getClassLoader ( ) , context ) ; ret = new EnhancedClassLoader ( classLoader ) ; _loaders . put ( context . getClassResolver ( ) , ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets either a new or existing { @link ClassPool } for use in compiling javassist classes . A new class path object is inserted in to the returned { @link ClassPool } using the passed in <code > loader< / code > instance if a new pool needs to be created . [CODESPLIT] protected ClassPool getClassPool ( OgnlContext context , EnhancedClassLoader loader ) { if ( _pool != null ) return _pool ; _pool = ClassPool . getDefault ( ) ; _pool . insertClassPath ( new LoaderClassPath ( loader . getParent ( ) ) ) ; return _pool ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the node on the top of the stack and remove it from the stack . [CODESPLIT] public Node popNode ( ) { if ( -- sp < mk ) { mk = ( ( Integer ) marks . remove ( marks . size ( ) - 1 ) ) . intValue ( ) ; } return ( Node ) nodes . remove ( nodes . size ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Override this method if you want to customize how the node dumps out its children . [CODESPLIT] public void dump ( PrintWriter writer , String prefix ) { writer . println ( toString ( prefix ) ) ; if ( _children != null ) { for ( int i = 0 ; i < _children . length ; ++ i ) { SimpleNode n = ( SimpleNode ) _children [ i ] ; if ( n != null ) { n . dump ( writer , prefix + \"  \" ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method may be called from subclasses jjtClose methods . It flattens the tree under this node by eliminating any children that are of the same class as this node and copying their children to this node . [CODESPLIT] protected void flattenTree ( ) { boolean shouldFlatten = false ; int newSize = 0 ; for ( int i = 0 ; i < _children . length ; ++ i ) if ( _children [ i ] . getClass ( ) == getClass ( ) ) { shouldFlatten = true ; newSize += _children [ i ] . jjtGetNumChildren ( ) ; } else ++ newSize ; if ( shouldFlatten ) { Node [ ] newChildren = new Node [ newSize ] ; int j = 0 ; for ( int i = 0 ; i < _children . length ; ++ i ) { Node c = _children [ i ] ; if ( c . getClass ( ) == getClass ( ) ) { for ( int k = 0 ; k < c . jjtGetNumChildren ( ) ; ++ k ) newChildren [ j ++ ] = . jjtGetChild ( k ) ; } else newChildren [ j ++ ] = c ; } if ( j != newSize ) throw new Error ( \"Assertion error: \" + j + \" != \" + newSize ) ; _children = newChildren ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns OgnlRuntime . NotFound if the property does not exist . [CODESPLIT] public Object getPossibleProperty ( Map context , Object target , String name ) throws OgnlException { Object result ; OgnlContext ognlContext = ( OgnlContext ) context ; try { if ( ( result = OgnlRuntime . getMethodValue ( ognlContext , target , name , true ) ) == OgnlRuntime . NotFound ) { result = OgnlRuntime . getFieldValue ( ognlContext , target , name , true ) ; } } catch ( IntrospectionException ex ) { throw new OgnlException ( name , ex ) ; } catch ( OgnlException ex ) { throw ex ; } catch ( Exception ex ) { throw new OgnlException ( name , ex ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns OgnlRuntime . NotFound if the property does not exist . [CODESPLIT] public Object setPossibleProperty ( Map context , Object target , String name , Object value ) throws OgnlException { Object result = null ; OgnlContext ognlContext = ( OgnlContext ) context ; try { if ( ! OgnlRuntime . setMethodValue ( ognlContext , target , name , value , true ) ) { result = OgnlRuntime . setFieldValue ( ognlContext , target , name , value ) ? null : OgnlRuntime . NotFound ; } if ( result == OgnlRuntime . NotFound ) { Method m = OgnlRuntime . getWriteMethod ( target . getClass ( ) , name ) ; if ( m != null ) { result = m . invoke ( target , new Object [ ] { value } ) ; } } } catch ( IntrospectionException ex ) { throw new OgnlException ( name , ex ) ; } catch ( OgnlException ex ) { throw ex ; } catch ( Exception ex ) { throw new OgnlException ( name , ex ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a child to the list of children of this evaluation . The parent of the child is set to the receiver and the children references are modified in the receiver to reflect the new child . The lastChild of the receiver is set to the child and the firstChild is set also if child is the first ( or only ) child . [CODESPLIT] public void addChild ( Evaluation child ) { if ( firstChild == null ) { firstChild = lastChild = child ; } else { if ( firstChild == lastChild ) { firstChild . next = child ; lastChild = child ; lastChild . previous = firstChild ; } else { child . previous = lastChild ; lastChild . next = child ; lastChild = child ; } } child . parent = this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reinitializes this Evaluation to the parameters specified . [CODESPLIT] public void init ( SimpleNode node , Object source , boolean setOperation ) { this . node = node ; this . source = source ; this . setOperation = setOperation ; result = null ; exception = null ; parent = null ; next = null ; previous = null ; firstChild = null ; lastChild = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * =================================================================== Overridden methods =================================================================== [CODESPLIT] protected Class findClass ( String name ) throws ClassNotFoundException { if ( ( context != null ) && ( context . getClassResolver ( ) != null ) ) { return context . getClassResolver ( ) . classForName ( name , context ) ; } return super . findClass ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * =================================================================== Protected methods =================================================================== [CODESPLIT] protected void rehash ( ) { int oldCapacity = table . length ; Entry oldTable [ ] = table ; int newCapacity = oldCapacity * 2 + 1 ; Entry newTable [ ] = new Entry [ newCapacity ] ; threshold = ( int ) ( newCapacity * loadFactor ) ; table = newTable ; for ( int i = oldCapacity ; i -- > 0 ; ) { for ( Entry old = oldTable [ i ] ; old != null ; ) { Entry e = old ; int index = ( e . hash & 0x7FFFFFFF ) % newCapacity ; old = old . next ; e . next = newTable [ index ] ; newTable [ index ] = e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an escape sequence into a character value . [CODESPLIT] private char escapeChar ( ) { int ofs = image . length ( ) - 1 ; switch ( image . charAt ( ofs ) ) { case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; case ' ' : return ' ' ; } // Otherwise, it's an octal number.  Find the backslash and convert. while ( image . charAt ( -- ofs ) != ' ' ) { } int value = 0 ; while ( ++ ofs < image . length ( ) ) value = ( value << 3 ) | ( image . charAt ( ofs ) - ' ' ) ; return ( char ) value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given OGNL expression and returns a tree representation of the expression that can be used by <CODE > Ognl< / CODE > static methods . [CODESPLIT] public static Object parseExpression ( String expression ) throws OgnlException { try { OgnlParser parser = new OgnlParser ( new StringReader ( expression ) ) ; return parser . topLevelExpression ( ) ; } catch ( ParseException e ) { throw new ExpressionSyntaxException ( expression , e ) ; } catch ( TokenMgrError e ) { throw new ExpressionSyntaxException ( expression , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses and compiles the given expression using the { @link ognl . enhance . OgnlExpressionCompiler } returned from { @link ognl . OgnlRuntime#getCompiler () } . [CODESPLIT] public static Node compileExpression ( OgnlContext context , Object root , String expression ) throws Exception { Node expr = ( Node ) Ognl . parseExpression ( expression ) ; OgnlRuntime . compileExpression ( context , expr , root ) ; return expr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new standard naming context for evaluating an OGNL expression . [CODESPLIT] @ Deprecated public static Map createDefaultContext ( Object root ) { return addDefaultContext ( root , null , null , null , new OgnlContext ( null , null , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new standard naming context for evaluating an OGNL expression . [CODESPLIT] @ Deprecated public static Map createDefaultContext ( Object root , ClassResolver classResolver ) { return addDefaultContext ( root , null , classResolver , null , new OgnlContext ( classResolver , null , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new standard naming context for evaluating an OGNL expression . [CODESPLIT] public static Map createDefaultContext ( Object root , MemberAccess memberAccess , ClassResolver classResolver , TypeConverter converter ) { return addDefaultContext ( root , memberAccess , classResolver , converter , new OgnlContext ( classResolver , converter , memberAccess ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new standard naming context for evaluating an OGNL expression . [CODESPLIT] public static Map createDefaultContext ( Object root , MemberAccess memberAccess ) { return addDefaultContext ( root , memberAccess , null , null , new OgnlContext ( null , null , memberAccess ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the standard naming context for evaluating an OGNL expression into the context given so that cached maps can be used as a context . [CODESPLIT] @ Deprecated public static Map addDefaultContext ( Object root , Map context ) { return addDefaultContext ( root , null , null , null , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the standard naming context for evaluating an OGNL expression into the context given so that cached maps can be used as a context . [CODESPLIT] public static Map addDefaultContext ( Object root , ClassResolver classResolver , Map context ) { return addDefaultContext ( root , null , classResolver , null , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the standard naming context for evaluating an OGNL expression into the context given so that cached maps can be used as a context . [CODESPLIT] public static Map addDefaultContext ( Object root , MemberAccess memberAccess , ClassResolver classResolver , TypeConverter converter , Map context ) { OgnlContext result ; if ( context instanceof OgnlContext ) { result = ( OgnlContext ) context ; } else { result = new OgnlContext ( memberAccess , classResolver , converter , context ) ; } result . setRoot ( root ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the currently configured { @link TypeConverter } for the given context - if any . [CODESPLIT] public static TypeConverter getTypeConverter ( Map context ) { if ( context instanceof OgnlContext ) { return ( ( OgnlContext ) context ) . getTypeConverter ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the root object to use for all expressions in the given context - doesn t necessarily replace root object instances explicitly passed in to other expression resolving methods on this class . [CODESPLIT] public static void setRoot ( Map context , Object root ) { context . put ( OgnlContext . ROOT_CONTEXT_KEY , root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given OGNL expression tree to extract a value from the given root object . The default context is set for the given context and root via <CODE > addDefaultContext () < / CODE > . [CODESPLIT] public static Object getValue ( Object tree , Map context , Object root ) throws OgnlException { return getValue ( tree , context , root , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given OGNL expression tree to extract a value from the given root object . The default context is set for the given context and root via <CODE > addDefaultContext () < / CODE > . [CODESPLIT] public static Object getValue ( Object tree , Map context , Object root , Class resultType ) throws OgnlException { Object result ; OgnlContext ognlContext = ( OgnlContext ) addDefaultContext ( root , context ) ; Node node = ( Node ) tree ; if ( node . getAccessor ( ) != null ) result = node . getAccessor ( ) . get ( ognlContext , root ) ; else result = node . getValue ( ognlContext , root ) ; if ( resultType != null ) { result = getTypeConverter ( context ) . convertValue ( context , root , null , null , result , resultType ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value represented by the given pre - compiled expression on the specified root object . [CODESPLIT] public static Object getValue ( ExpressionAccessor expression , OgnlContext context , Object root ) { return expression . get ( context , root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value represented by the given pre - compiled expression on the specified root object . [CODESPLIT] public static Object getValue ( ExpressionAccessor expression , OgnlContext context , Object root , Class resultType ) { return getTypeConverter ( context ) . convertValue ( context , root , null , null , expression . get ( context , root ) , resultType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given OGNL expression to extract a value from the given root object in a given context [CODESPLIT] public static Object getValue ( String expression , Map context , Object root ) throws OgnlException { return getValue ( expression , context , root , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given OGNL expression tree to extract a value from the given root object . [CODESPLIT] @ Deprecated public static Object getValue ( Object tree , Object root ) throws OgnlException { return getValue ( tree , root , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given OGNL expression tree to extract a value from the given root object . [CODESPLIT] public static Object getValue ( Object tree , Object root , Class resultType ) throws OgnlException { return getValue ( tree , createDefaultContext ( root ) , root , resultType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method that combines calls to <code > parseExpression < / code > and <code > getValue< / code > . [CODESPLIT] public static Object getValue ( String expression , Object root ) throws OgnlException { return getValue ( expression , root , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method that combines calls to <code > parseExpression < / code > and <code > getValue< / code > . [CODESPLIT] public static Object getValue ( String expression , Object root , Class resultType ) throws OgnlException { return getValue ( parseExpression ( expression ) , root , resultType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given OGNL expression tree to insert a value into the object graph rooted at the given root object . The default context is set for the given context and root via <CODE > addDefaultContext () < / CODE > . [CODESPLIT] public static void setValue ( Object tree , Map context , Object root , Object value ) throws OgnlException { OgnlContext ognlContext = ( OgnlContext ) addDefaultContext ( root , context ) ; Node n = ( Node ) tree ; if ( n . getAccessor ( ) != null ) { n . getAccessor ( ) . set ( ognlContext , root , value ) ; return ; } n . setValue ( ognlContext , root , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value given using the pre - compiled expression on the specified root object . [CODESPLIT] public static void setValue ( ExpressionAccessor expression , OgnlContext context , Object root , Object value ) { expression . set ( context , root , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given OGNL expression tree to insert a value into the object graph rooted at the given root object . [CODESPLIT] public static void setValue ( Object tree , Object root , Object value ) throws OgnlException { setValue ( tree , createDefaultContext ( root ) , root , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method that combines calls to <code > parseExpression < / code > and <code > setValue< / code > . [CODESPLIT] public static void setValue ( String expression , Object root , Object value ) throws OgnlException { setValue ( parseExpression ( expression ) , root , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the specified { @link Node } instance represents a constant expression . [CODESPLIT] public static boolean isConstant ( Object tree , Map context ) throws OgnlException { return ( ( SimpleNode ) tree ) . isConstant ( ( OgnlContext ) addDefaultContext ( null , context ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the specified expression represents a constant expression . [CODESPLIT] public static boolean isConstant ( String expression , Map context ) throws OgnlException { return isConstant ( parseExpression ( expression ) , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns default watch service identifier based on operating system . [CODESPLIT] public static String getDefaultWatchServiceId ( ) { String result = \"polling\" ; String osName = System . getProperty ( \"os.name\" ) ; if ( osName != null ) { osName = osName . toLowerCase ( Locale . ENGLISH ) ; if ( osName . contains ( \"windows\" ) || osName . contains ( \"linux\" ) ) { result = isAtLeastJava7 ( ) ? \"jdk7\" : \"jnotify\" ; } else if ( osName . contains ( \"mac\" ) ) { result = \"jnotify\" ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "startTimeout in milliseconds [CODESPLIT] protected void waitForServerStarted ( String rootUrl , JavaRunnable runner , int startTimeout , boolean spawned ) throws MojoExecutionException , IOException { long endTimeMillis = startTimeout > 0 ? System . currentTimeMillis ( ) + startTimeout : 0L ; boolean started = false ; URL connectUrl = new URL ( rootUrl ) ; int verifyWaitDelay = 1000 ; while ( ! started ) { if ( startTimeout > 0 && endTimeMillis - System . currentTimeMillis ( ) < 0L ) { if ( spawned ) { InternalPlay2StopMojo internalStop = new InternalPlay2StopMojo ( ) ; internalStop . project = project ; try { internalStop . execute ( ) ; } catch ( MojoExecutionException e ) { // just ignore } catch ( MojoFailureException e ) { // just ignore } } throw new MojoExecutionException ( String . format ( \"Failed to start Play! server in %d ms\" , Integer . valueOf ( startTimeout ) ) ) ; } BuildException runnerException = runner . getException ( ) ; if ( runnerException != null ) { throw new MojoExecutionException ( \"Play! server start exception\" , runnerException ) ; } try { URLConnection conn = connectUrl . openConnection ( ) ; if ( startTimeout > 0 ) { int connectTimeOut = Long . valueOf ( Math . min ( endTimeMillis - System . currentTimeMillis ( ) , Integer . valueOf ( Integer . MAX_VALUE ) . longValue ( ) ) ) . intValue ( ) ; if ( connectTimeOut > 0 ) { conn . setConnectTimeout ( connectTimeOut ) ; } } connectUrl . openConnection ( ) . getContent ( ) ; started = true ; } catch ( Exception e ) { // return false; } if ( ! started ) { long sleepTime = verifyWaitDelay ; if ( startTimeout > 0 ) { sleepTime = Math . min ( sleepTime , endTimeMillis - System . currentTimeMillis ( ) ) ; } if ( sleepTime > 0 ) { try { Thread . sleep ( sleepTime ) ; } catch ( InterruptedException e ) { throw new MojoExecutionException ( \"?\" , e ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FileWatcher watch ( List < File > filesToWatch , FileWatchCallback watchCallback ) throws FileWatchException { List < File > dirsToWatch = new ArrayList < File > ( filesToWatch . size ( ) ) ; for ( File file : filesToWatch ) { if ( file . exists ( ) ) { if ( file . isDirectory ( ) ) { dirsToWatch . add ( file ) ; } else { if ( log != null && log . isWarnEnabled ( ) ) { log . warn ( String . format ( \"[jdk7] \\\"%s\\\" is not a directory, will not be watched.\" , file . getAbsolutePath ( ) ) ) ; } } } else { if ( log != null && log . isWarnEnabled ( ) ) { log . warn ( String . format ( \"[jdk7] \\\"%s\\\" does not exist, will not be watched.\" , file . getAbsolutePath ( ) ) ) ; } } } try { JDK7FileWatcher result = new JDK7FileWatcher ( log , dirsToWatch , watchCallback ) ; Thread thread = new Thread ( result , \"jdk7-play-watch-service\" ) ; thread . setDaemon ( true ) ; thread . start ( ) ; return result ; } catch ( IOException e ) { throw new FileWatchException ( \"JDK7FileWatcher initialization failed\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs mapping from the position in generated source file to the position in { @code routes } file it was generated from . <br > <br > Returns : <ul > <li > position in { @code routes } file< / li > <li > { @code null } value if file of the input position is not recognized as generated from { @code routes } file< / li > < / ul > [CODESPLIT] @ Override public SourcePosition map ( SourcePosition p ) throws IOException { SourcePosition result = null ; File generatedFile = p . getFile ( ) ; if ( generatedFile != null && generatedFile . isFile ( ) ) { String [ ] generatedFileLines = readFileAsString ( generatedFile ) . split ( \"\\n\" ) ; if ( generatedFileLines [ 0 ] . startsWith ( Play2RoutesGeneratedSource . SOURCE_PREFIX ) // play 2.2.x - 2.3.x || Arrays . asList ( generatedFileLines ) . contains ( GENERATOR_LINE ) ) // play 2.4.x + { Play2RoutesGeneratedSource generatedSource = new Play2RoutesGeneratedSource ( generatedFileLines ) ; String sourceFileName = generatedSource . getSourceFileName ( ) ; if ( sourceFileName != null ) { File sourceFile = new File ( sourceFileName ) ; if ( sourceFile . isFile ( ) ) { int sourceLine = generatedSource . mapLine ( p . getLine ( ) ) ; String [ ] sourceFileLines = readFileAsString ( sourceFile ) . split ( \"\\n\" ) ; if ( sourceFileLines . length >= sourceLine ) { String sourceLineContent = sourceFileLines [ sourceLine - 1 ] ; if ( sourceLineContent . endsWith ( \"\\r\" ) ) // remove trailing CR (on Windows) { sourceLineContent = sourceLineContent . substring ( 0 , sourceLineContent . length ( ) - 1 ) ; } result = new Play2RoutesSourcePosition ( sourceLine , sourceLineContent , sourceFile ) ; } } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copied from AbstractPlay2SourcePositionMapper . java [CODESPLIT] private String readFileAsString ( ) throws IOException { FileInputStream is = new FileInputStream ( e . source ( ) ) ; try { byte [ ] buffer = new byte [ 8192 ] ; int len = is . read ( buffer ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( len != - 1 ) { out . write ( buffer , 0 , len ) ; len = is . read ( buffer ) ; } return charsetName != null ? new String ( out . toByteArray ( ) , charsetName ) : new String ( out . toByteArray ( ) ) ; } finally { is . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Contrary to its name this doesn t necessarily reload the app . It is invoked on every request and will only trigger a reload of the app if something has changed . [CODESPLIT] @ Override /* BuildLink interface */ public synchronized Object reload ( ) { Object result = null ; try { boolean reloadRequired = buildLink . build ( ) ; if ( reloadRequired ) { int version = ++ classLoaderVersion ; String name = \"ReloadableClassLoader(v\" + version + \")\" ; currentApplicationClassLoader = new DelegatedResourcesClassLoader ( name , toUrls ( outputDirectories ) , baseLoader ) ; result = currentApplicationClassLoader ; } } catch ( MalformedURLException e ) { throw new UnexpectedException ( \"Unexpected reloader exception\" , e ) ; //?? } catch ( Play2BuildFailure e ) { result = new CompilationException ( e . getMessage ( ) , e . line ( ) , e . position ( ) , e . source ( ) != null ? e . source ( ) . getAbsolutePath ( ) : null , e . input ( ) ) ; } catch ( Play2BuildError e ) { result = new UnexpectedException ( e . getMessage ( ) , e . getCause ( ) ) ; //?? } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from Less script must be public [CODESPLIT] public static String readContent ( File file ) throws IOException { String result = null ; BufferedReader is = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , \"UTF-8\" ) ) ; try { StringBuilder sb = new StringBuilder ( ) ; String line = is . readLine ( ) ; while ( line != null ) { sb . append ( line ) . append ( ' ' ) ; line = is . readLine ( ) ; } result = sb . toString ( ) ; } finally { is . close ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from Less script must be public [CODESPLIT] public static File resolve ( File originalSource , String imported ) { return new File ( originalSource . getParentFile ( ) , imported ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all the comma delimited list of packages . <p > Package names are effectively converted into a directory on the file system and the class files are found and processed . < / p > [CODESPLIT] public List < File > collectClassFilesToEnhance ( long lastEnhanced , File outputDirectory , String packageNames ) { if ( packageNames == null || packageNames . isEmpty ( ) ) { return collectClassFilesToEnhanceFromPackage ( lastEnhanced , outputDirectory , \"\" , true ) ; // return; } List < File > result = new ArrayList < File > ( ) ; String [ ] pkgs = packageNames . split ( \",\" ) ; for ( int i = 0 ; i < pkgs . length ; i ++ ) { String pkg = pkgs [ i ] . trim ( ) . replace ( ' ' , ' ' ) ; boolean recurse = false ; if ( pkg . endsWith ( \"**\" ) ) { recurse = true ; pkg = pkg . substring ( 0 , pkg . length ( ) - 2 ) ; } else if ( pkg . endsWith ( \"*\" ) ) { recurse = true ; pkg = pkg . substring ( 0 , pkg . length ( ) - 1 ) ; } pkg = trimSlash ( pkg ) ; result . addAll ( collectClassFilesToEnhanceFromPackage ( lastEnhanced , outputDirectory , pkg , recurse ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns preconfigured archiver [CODESPLIT] protected Archiver getArchiver ( String archiverName ) throws NoSuchArchiverException { Archiver result = archiverManager . getArchiver ( archiverName ) ; result . setDuplicateBehavior ( Archiver . DUPLICATES_FAIL ) ; // Just in case return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for potential Duplicate file exception before archive processing starts [CODESPLIT] protected void checkArchiverForProblems ( Archiver archiver ) { for ( ResourceIterator iter = archiver . getResources ( ) ; iter . hasNext ( ) ; ) { iter . next ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private utility methods [CODESPLIT] protected /*private*/ Set < Artifact > getResolvedArtifact ( String groupId , String artifactId , String version ) throws ArtifactResolutionException { return getResolvedArtifact ( groupId , artifactId , version , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the content of the file to a string . [CODESPLIT] protected String readFileAsString ( File file ) throws IOException { FileInputStream is = new FileInputStream ( file ) ; try { byte [ ] buffer = new byte [ 8192 ] ; int len = is . read ( buffer ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( len != - 1 ) { out . write ( buffer , 0 , len ) ; len = is . read ( buffer ) ; } return charsetName != null ? new String ( out . toByteArray ( ) , charsetName ) : new String ( out . toByteArray ( ) ) ; } finally { is . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=== TEST =================================================================================== [CODESPLIT] private List < MavenProject > calculateProjectsToBuild ( Set < String > changedFilePaths ) { Set < MavenProject > changedProjects = new HashSet < MavenProject > ( projects . size ( ) ) ; for ( String path : changedFilePaths ) { MavenProject p = findProjectFor ( path ) ; changedProjects . add ( p ) ; } Set < MavenProject > changedAndDependentProjects = new HashSet < MavenProject > ( projects . size ( ) ) ; for ( MavenProject p : changedProjects ) { changedAndDependentProjects . add ( p ) ; List < MavenProject > deps = session . getProjectDependencyGraph ( ) . getDownstreamProjects ( p , true /*transitive*/ ) ; for ( MavenProject depP : deps ) { if ( projects . contains ( depP ) ) { changedAndDependentProjects . addAll ( deps ) ; } } } List < MavenProject > result = new ArrayList < MavenProject > ( changedAndDependentProjects . size ( ) ) ; for ( MavenProject p : projects ) { if ( changedAndDependentProjects . contains ( p ) ) { result . add ( p ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( FileWatchLogger log ) throws FileWatchException { super . initialize ( log ) ; pollInterval = DEFAULT_POLL_INTERVAL ; String pollIntervalProp = System . getProperty ( \"play2.pollInterval\" ) ; if ( pollIntervalProp != null ) { try { pollInterval = Integer . parseInt ( pollIntervalProp ) ; } catch ( NumberFormatException e ) { log . warn ( String . format ( \"Unparsable property value \\\"%s\\\", using default poll interval %d ms\" , pollIntervalProp , Integer . valueOf ( DEFAULT_POLL_INTERVAL ) ) ) ; // throw new FileWatchException( \"PollingFileWatcher initialization failed\", e ); } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FileWatcher watch ( List < File > filesToWatch , FileWatchCallback watchCallback ) { PollingFileWatcher result = new PollingFileWatcher ( log , filesToWatch , watchCallback , pollInterval ) ; Thread thread = new Thread ( result , \"polling-play-watch-service\" ) ; thread . setDaemon ( true ) ; thread . start ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and configures Ant project for Java task . [CODESPLIT] protected Project createProject ( ) { final Project antProject = new Project ( ) ; final ProjectHelper helper = ProjectHelper . getProjectHelper ( ) ; antProject . addReference ( ProjectHelper . PROJECTHELPER_REFERENCE , helper ) ; helper . getImportStack ( ) . addElement ( \"AntBuilder\" ) ; // import checks that stack is not empty final BuildLogger logger = new NoBannerLogger ( ) ; logger . setMessageOutputLevel ( Project . MSG_INFO ) ; logger . setOutputPrintStream ( System . out ) ; logger . setErrorPrintStream ( System . err ) ; antProject . addBuildListener ( logger ) ; antProject . init ( ) ; antProject . getBaseDir ( ) ; return antProject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds string type system property to Ant Java task . [CODESPLIT] protected void addSystemProperty ( Java java , String propertyName , String propertyValue ) { Environment . Variable sysPropPlayHome = new Environment . Variable ( ) ; sysPropPlayHome . setKey ( propertyName ) ; sysPropPlayHome . setValue ( propertyValue ) ; java . addSysproperty ( sysPropPlayHome ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds file type system property to Ant Java task . [CODESPLIT] protected void addSystemProperty ( Java java , String propertyName , File propertyValue ) { Environment . Variable sysPropPlayHome = new Environment . Variable ( ) ; sysPropPlayHome . setKey ( propertyName ) ; sysPropPlayHome . setFile ( propertyValue ) ; java . addSysproperty ( sysPropPlayHome ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void initialize ( FileWatchLogger log ) throws FileWatchException { super . initialize ( log ) ; File nativeLibsDirectory = new File ( \".\" ) ; // maybe change to temporary directory? String nativeLibsDirectoryProp = System . getProperty ( \"play2.nativeLibsDirectory\" ) ; if ( nativeLibsDirectoryProp != null && ! \"\" . equals ( nativeLibsDirectoryProp ) ) { nativeLibsDirectory = new File ( nativeLibsDirectoryProp ) ; } else { String targetDirectoryProp = System . getProperty ( \"project.build.directory\" ) ; if ( targetDirectoryProp != null && ! \"\" . equals ( targetDirectoryProp ) ) { File targetDirectory = new File ( targetDirectoryProp ) ; nativeLibsDirectory = new File ( targetDirectory , \"native_libraries\" ) ; } } String nativeLibsPath = nativeLibsDirectory . getAbsolutePath ( ) ; if ( ! nativeLibsDirectory . exists ( ) && ! nativeLibsDirectory . mkdirs ( ) ) { throw new FileWatchException ( String . format ( \"Cannot create \\\"%s\\\" directory\" , nativeLibsPath ) ) ; } String libraryOS = null ; String libraryName = \"jnotify\" ; String osName = System . getProperty ( \"os.name\" ) ; if ( osName != null ) { osName = osName . toLowerCase ( Locale . ENGLISH ) ; String architecture = System . getProperty ( \"sun.arch.data.model\" ) ; if ( osName . startsWith ( \"windows\" ) ) { libraryOS = \"windows\" + architecture ; if ( \"amd64\" . equals ( System . getProperty ( \"os.arch\" ) ) ) { libraryName = \"jnotify_64bit\" ; } } else if ( osName . equals ( \"linux\" ) ) { libraryOS = \"linux\" + architecture ; } else if ( osName . startsWith ( \"mac os x\" ) ) { libraryOS = \"osx\" ; } } if ( libraryOS == null ) { throw new FileWatchException ( String . format ( \"JNotifyFileWatchService initialization failed - unsupported OS \\\"%s\\\"\" , osName ) ) ; } String libraryResourceName = System . mapLibraryName ( libraryName ) ; libraryResourceName = libraryResourceName . replace ( \".dylib\" , \".jnilib\" ) ; // fix for JDK-7134701 bug File outputFile = new File ( nativeLibsDirectory , libraryResourceName ) ; if ( ! outputFile . exists ( ) ) { try { copyResourceToFile ( \"META-INF/native/\" + libraryOS , libraryResourceName , nativeLibsDirectory ) ; } catch ( IOException e ) { throw new FileWatchException ( \"JNotifyFileWatchService initialization failed\" , e ) ; } } // hack to update java.library.path try { String javaLibraryPath = System . getProperty ( \"java.library.path\" ) ; javaLibraryPath = javaLibraryPath != null ? javaLibraryPath + File . pathSeparator + nativeLibsPath : nativeLibsPath ; System . setProperty ( \"java.library.path\" , javaLibraryPath ) ; Field fieldSysPath = ClassLoader . class . getDeclaredField ( \"sys_paths\" ) ; fieldSysPath . setAccessible ( true ) ; fieldSysPath . set ( null , null ) ; } catch ( Exception e ) { throw new FileWatchException ( \"JNotifyFileWatchService initialization failed\" , e ) ; } // initialize JNotify try { JNotify . removeWatch ( 0 ) ; } catch ( JNotifyException e ) { throw new FileWatchException ( \"JNotifyFileWatchService initialization failed\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public FileWatcher watch ( List < File > filesToWatch , FileWatchCallback watchCallback ) throws FileWatchException { try { return new JNotifyFileWatcher ( log , filesToWatch , watchCallback ) ; } catch ( JNotifyException e ) { throw new FileWatchException ( \"JNotifyFileWatcher initialization failed\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs mapping from the position in generated source file to the position in Twirl template file it was generated from . <br > <br > Returns : <ul > <li > position in Twirl template file< / li > <li > { @code null } value if file of the input position is not recognized as generated from Twirl template file< / li > < / ul > [CODESPLIT] @ Override public SourcePosition map ( SourcePosition p ) throws IOException { SourcePosition result = null ; File generatedFile = p . getFile ( ) ; int generatedOffset = p . getOffset ( ) ; if ( generatedFile != null && generatedFile . isFile ( ) && generatedOffset >= 0 ) { Play2TemplateGeneratedSource generated = getGeneratedSource ( generatedFile ) ; if ( generated != null ) { String sourceFileName = generated . getSourceFileName ( ) ; if ( sourceFileName != null ) { File sourceFile = new File ( sourceFileName ) ; if ( sourceFile . isFile ( ) ) { int sourceOffset = generated . mapPosition ( generatedOffset ) ; String sourceFileContent = readFileAsString ( sourceFile ) ; if ( sourceFileContent . length ( ) > sourceOffset ) { String [ ] sourceFileLines = sourceFileContent . split ( \"\\n\" ) ; Play2TemplateLocation sourceLocation = new Play2TemplateMapping ( sourceFileLines ) . location ( sourceOffset ) ; //if ( sourceLocation != null ) //{ result = new Play2TemplateSourcePosition ( sourceFile , sourceLocation ) ; //} } } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public void set ( String fileName , Collection < String > dependencies ) { allDependencies . put ( fileName , new TreeSet < String > ( dependencies ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increment the counter in the current bucket by one for the given { @link NumerusRollingNumberEvent } type . <p > The { @link NumerusRollingNumberEvent } must be a counter type <code > HystrixRollingNumberEvent . isCounter () == true< / code > . [CODESPLIT] public void increment ( NumerusRollingNumberEvent type , Boolean doNotBlock ) { Bucket lastBucket = getCurrentBucket ( doNotBlock ) ; if ( lastBucket == null ) return ; lastBucket . getAdder ( type ) . increment ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the sum of all buckets in the rolling counter for the given { @link NumerusRollingNumberEvent } type . <p > The { @link NumerusRollingNumberEvent } must be a counter type <code > HystrixRollingNumberEvent . isCounter () == true< / code > . [CODESPLIT] public long getRollingSum ( NumerusRollingNumberEvent type , Boolean doNotBlock ) { Bucket lastBucket = getCurrentBucket ( doNotBlock ) ; if ( lastBucket == null ) return 0 ; long sum = 0 ; for ( Bucket b : buckets ) { sum += b . getAdder ( type ) . sum ( ) ; } return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array of values for all buckets in the rolling counter for the given { @link NumerusRollingNumberEvent } type . <p > Index 0 is the oldest bucket . <p > The { @link NumerusRollingNumberEvent } must be a counter type <code > HystrixRollingNumberEvent . isCounter () == true< / code > . [CODESPLIT] public long [ ] getValues ( NumerusRollingNumberEvent type ) { Bucket lastBucket = getCurrentBucket ( ) ; if ( lastBucket == null ) return new long [ 0 ] ; // get buckets as an array (which is a copy of the current state at this point in time) Bucket [ ] bucketArray = buckets . getArray ( ) ; // we have bucket data so we'll return an array of values for all buckets long values [ ] = new long [ bucketArray . length ] ; int i = 0 ; for ( Bucket bucket : bucketArray ) { if ( type . isCounter ( ) ) { values [ i ++ ] = bucket . getAdder ( type ) . sum ( ) ; } else if ( type . isMaxUpdater ( ) ) { values [ i ++ ] = bucket . getMaxUpdater ( type ) . max ( ) ; } } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the max value of values in all buckets for the given { @link NumerusRollingNumberEvent } type . <p > The { @link NumerusRollingNumberEvent } must be a max updater type <code > HystrixRollingNumberEvent . isMaxUpdater () == true< / code > . [CODESPLIT] public long getRollingMaxValue ( NumerusRollingNumberEvent type ) { long values [ ] = getValues ( type ) ; if ( values . length == 0 ) { return 0 ; } else { Arrays . sort ( values ) ; return values [ values . length - 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package for testing [CODESPLIT] Bucket getCurrentBucket ( Boolean doNotBlock ) { long currentTime = time . getCurrentTimeInMillis ( ) ; /* a shortcut to try and get the most common result of immediately finding the current bucket */ /**\n         * Retrieve the latest bucket if the given time is BEFORE the end of the bucket window, otherwise it returns NULL.\n         * \n         * NOTE: This is thread-safe because it's accessing 'buckets' which is a LinkedBlockingDeque\n         */ Bucket currentBucket = buckets . peekLast ( ) ; if ( currentBucket != null && currentTime < currentBucket . windowStart + getBucketSizeInMilliseconds ( ) ) { // if we're within the bucket 'window of time' return the current one // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur, // we'll just use the latest as long as we're not AFTER the window return currentBucket ; } /* if we didn't find the current bucket above, then we have to create one */ /**\n         * The following needs to be synchronized/locked even with a synchronized/thread-safe data structure such as LinkedBlockingDeque because\n         * the logic involves multiple steps to check existence, create an object then insert the object. The 'check' or 'insertion' themselves\n         * are thread-safe by themselves but not the aggregate algorithm, thus we put this entire block of logic inside synchronized.\n         * \n         * I am using a tryLock if/then (http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html#tryLock())\n         * so that a single thread will get the lock and as soon as one thread gets the lock all others will go the 'else' block\n         * and just return the currentBucket until the newBucket is created. This should allow the throughput to be far higher\n         * and only slow down 1 thread instead of blocking all of them in each cycle of creating a new bucket based on some testing\n         * (and it makes sense that it should as well).\n         * \n         * This means the timing won't be exact to the millisecond as to what data ends up in a bucket, but that's acceptable.\n         * It's not critical to have exact precision to the millisecond, as long as it's rolling, if we can instead reduce the impact synchronization.\n         * \n         * More importantly though it means that the 'if' block within the lock needs to be careful about what it changes that can still\n         * be accessed concurrently in the 'else' block since we're not completely synchronizing access.\n         * \n         * For example, we can't have a multi-step process to add a bucket, remove a bucket, then update the sum since the 'else' block of code\n         * can retrieve the sum while this is all happening. The trade-off is that we don't maintain the rolling sum and let readers just iterate\n         * bucket to calculate the sum themselves. This is an example of favoring write-performance instead of read-performance and how the tryLock\n         * versus a synchronized block needs to be accommodated.\n         */ if ( newBucketLock . tryLock ( ) ) { try { if ( buckets . peekLast ( ) == null ) { // the list is empty so create the first bucket Bucket newBucket = new Bucket ( events , currentTime ) ; buckets . addLast ( newBucket ) ; return newBucket ; } else { // We go into a loop so that it will create as many buckets as needed to catch up to the current time // as we want the buckets complete even if we don't have transactions during a period of time. for ( int i = 0 ; i < numberOfBuckets . get ( ) ; i ++ ) { // we have at least 1 bucket so retrieve it Bucket lastBucket = buckets . peekLast ( ) ; if ( currentTime < lastBucket . windowStart + getBucketSizeInMilliseconds ( ) ) { // if we're within the bucket 'window of time' return the current one // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur, // we'll just use the latest as long as we're not AFTER the window return lastBucket ; } else if ( currentTime - ( lastBucket . windowStart + getBucketSizeInMilliseconds ( ) ) > timeInMilliseconds . get ( ) ) { // the time passed is greater than the entire rolling counter so we want to clear it all and start from scratch reset ( ) ; // recursively call getCurrentBucket which will create a new bucket and return it return getCurrentBucket ( ) ; } else { // we're past the window so we need to create a new bucket // create a new bucket and add it as the new 'last' buckets . addLast ( new Bucket ( events , lastBucket . windowStart + getBucketSizeInMilliseconds ( ) ) ) ; // add the lastBucket values to the cumulativeSum cumulativeSum . addBucket ( lastBucket ) ; } } // we have finished the for-loop and created all of the buckets, so return the lastBucket now return buckets . peekLast ( ) ; } } finally { newBucketLock . unlock ( ) ; } } else { currentBucket = buckets . peekLast ( ) ; if ( currentBucket != null ) { // we didn't get the lock so just return the latest bucket while another thread creates the next one return currentBucket ; } else { // the rare scenario where multiple threads raced to create the very first bucket // wait slightly and then use recursion while the other thread finishes creating a bucket if ( doNotBlock ) { // caller indicates doNotBlock return null ; } try { Thread . sleep ( 5 ) ; } catch ( Exception e ) { // ignore } return getCurrentBucket ( false ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add value ( or values ) to current bucket . [CODESPLIT] public void addValue ( int ... value ) { /* no-op if disabled */ if ( ! enabled . get ( ) ) return ; for ( int v : value ) { getCurrentBucket ( ) . data . addValue ( v ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the current maximum . The returned value is <em > NOT< / em > an atomic snapshot : Invocation in the absence of concurrent updates returns an accurate result but concurrent updates that occur while the value is being calculated might not be incorporated . [CODESPLIT] public long max ( ) { Cell [ ] as = cells ; long max = base ; if ( as != null ) { int n = as . length ; long v ; for ( int i = 0 ; i < n ; ++ i ) { Cell a = as [ i ] ; if ( a != null && ( v = a . value ) > max ) max = v ; } } return max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] void setupActionBar ( ) { // there might not be an ActionBar, for example when started in Theme.Holo.Dialog.NoActionBar theme @ SuppressLint ( \"AppCompatMethod\" ) final ActionBar actionBar = getActionBar ( ) ; if ( actionBar != null ) { actionBar . setDisplayHomeAsUpEnabled ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To create the config make use of the provided { @link DirectoryChooserConfig#builder () } . [CODESPLIT] public static DirectoryChooserFragment newInstance ( @ NonNull final DirectoryChooserConfig config ) { final DirectoryChooserFragment fragment = new DirectoryChooserFragment ( ) ; final Bundle args = new Bundle ( ) ; args . putParcelable ( ARG_CONFIG , config ) ; fragment . setArguments ( args ) ; return fragment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows a confirmation dialog that asks the user if he wants to create a new folder . User can modify provided name if it was not disallowed . [CODESPLIT] private void openNewFolderDialog ( ) { @ SuppressLint ( \"InflateParams\" ) final View dialogView = getActivity ( ) . getLayoutInflater ( ) . inflate ( R . layout . dialog_new_folder , null ) ; final TextView msgView = ( TextView ) dialogView . findViewById ( R . id . msgText ) ; final EditText editText = ( EditText ) dialogView . findViewById ( R . id . editText ) ; editText . setText ( mNewDirectoryName ) ; msgView . setText ( getString ( R . string . create_folder_msg , mNewDirectoryName ) ) ; final AlertDialog alertDialog = new AlertDialog . Builder ( getActivity ( ) ) . setTitle ( R . string . create_folder_label ) . setView ( dialogView ) . setNegativeButton ( R . string . cancel_label , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( final DialogInterface dialog , final int which ) { dialog . dismiss ( ) ; } } ) . setPositiveButton ( R . string . confirm_label , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( final DialogInterface dialog , final int which ) { dialog . dismiss ( ) ; mNewDirectoryName = editText . getText ( ) . toString ( ) ; final int msg = createFolder ( ) ; Toast . makeText ( getActivity ( ) , msg , Toast . LENGTH_SHORT ) . show ( ) ; } } ) . show ( ) ; alertDialog . getButton ( DialogInterface . BUTTON_POSITIVE ) . setEnabled ( editText . getText ( ) . length ( ) != 0 ) ; editText . addTextChangedListener ( new TextWatcher ( ) { @ Override public void beforeTextChanged ( final CharSequence charSequence , final int i , final int i2 , final int i3 ) { } @ Override public void onTextChanged ( final CharSequence charSequence , final int i , final int i2 , final int i3 ) { final boolean textNotEmpty = charSequence . length ( ) != 0 ; alertDialog . getButton ( DialogInterface . BUTTON_POSITIVE ) . setEnabled ( textNotEmpty ) ; msgView . setText ( getString ( R . string . create_folder_msg , charSequence . toString ( ) ) ) ; } @ Override public void afterTextChanged ( final Editable editable ) { } } ) ; editText . setVisibility ( mConfig . allowNewDirectoryNameModification ( ) ? View . VISIBLE : View . GONE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change the directory that is currently being displayed . [CODESPLIT] private void changeDirectory ( final File dir ) { if ( dir == null ) { debug ( \"Could not change folder: dir was null\" ) ; } else if ( ! dir . isDirectory ( ) ) { debug ( \"Could not change folder: dir is no directory\" ) ; } else { final File [ ] contents = dir . listFiles ( ) ; if ( contents != null ) { int numDirectories = 0 ; for ( final File f : contents ) { if ( f . isDirectory ( ) ) { numDirectories ++ ; } } mFilesInDir = new File [ numDirectories ] ; mFilenames . clear ( ) ; for ( int i = 0 , counter = 0 ; i < numDirectories ; counter ++ ) { if ( contents [ counter ] . isDirectory ( ) ) { mFilesInDir [ i ] = contents [ counter ] ; mFilenames . add ( contents [ counter ] . getName ( ) ) ; i ++ ; } } Arrays . sort ( mFilesInDir ) ; Collections . sort ( mFilenames ) ; mSelectedDir = dir ; mTxtvSelectedFolder . setText ( dir . getAbsolutePath ( ) ) ; mListDirectoriesAdapter . notifyDataSetChanged ( ) ; mFileObserver = createFileObserver ( dir . getAbsolutePath ( ) ) ; mFileObserver . startWatching ( ) ; debug ( \"Changed directory to %s\" , dir . getAbsolutePath ( ) ) ; } else { debug ( \"Could not change folder: contents of dir were null\" ) ; } } refreshButtonState ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the state of the buttons depending on the currently selected file or folder . [CODESPLIT] private void refreshButtonState ( ) { final Activity activity = getActivity ( ) ; if ( activity != null && mSelectedDir != null ) { mBtnConfirm . setEnabled ( isValidFile ( mSelectedDir ) ) ; getActivity ( ) . invalidateOptionsMenu ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up a FileObserver to watch the current directory . [CODESPLIT] private FileObserver createFileObserver ( final String path ) { return new FileObserver ( path , FileObserver . CREATE | FileObserver . DELETE | FileObserver . MOVED_FROM | FileObserver . MOVED_TO ) { @ Override public void onEvent ( final int event , final String path ) { debug ( \"FileObserver received event %d\" , event ) ; final Activity activity = getActivity ( ) ; if ( activity != null ) { activity . runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { refreshDirectory ( ) ; } } ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the selected folder as a result to the activity the fragment s attached to . The selected folder can also be null . [CODESPLIT] private void returnSelectedFolder ( ) { if ( mSelectedDir != null ) { debug ( \"Returning %s as result\" , mSelectedDir . getAbsolutePath ( ) ) ; mListener . foreach ( new UnitFunction < OnFragmentInteractionListener > ( ) { @ Override public void apply ( final OnFragmentInteractionListener f ) { f . onSelectDirectory ( mSelectedDir . getAbsolutePath ( ) ) ; } } ) ; } else { mListener . foreach ( new UnitFunction < OnFragmentInteractionListener > ( ) { @ Override public void apply ( final OnFragmentInteractionListener f ) { f . onCancelChooser ( ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new folder in the current directory with the name CREATE_DIRECTORY_NAME . [CODESPLIT] private int createFolder ( ) { if ( mNewDirectoryName != null && mSelectedDir != null && mSelectedDir . canWrite ( ) ) { final File newDir = new File ( mSelectedDir , mNewDirectoryName ) ; if ( newDir . exists ( ) ) { return R . string . create_folder_error_already_exists ; } else { final boolean result = newDir . mkdir ( ) ; if ( result ) { return R . string . create_folder_success ; } else { return R . string . create_folder_error ; } } } else if ( mSelectedDir != null && ! mSelectedDir . canWrite ( ) ) { return R . string . create_folder_error_no_write_access ; } else { return R . string . create_folder_error ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the selected file or directory would be valid selection . [CODESPLIT] private boolean isValidFile ( final File file ) { return ( file != null && file . isDirectory ( ) && file . canRead ( ) && ( mConfig . allowReadOnlyDirectory ( ) || file . canWrite ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the activity is first created . [CODESPLIT] @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . main ) ; mDirectoryTextView = ( TextView ) findViewById ( R . id . textDirectory ) ; // Set up click handler for \"Choose Directory\" button findViewById ( R . id . btnChoose ) . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { final Intent chooserIntent = new Intent ( DirChooserSample . this , DirectoryChooserActivity . class ) ; final DirectoryChooserConfig config = DirectoryChooserConfig . builder ( ) . newDirectoryName ( \"DirChooserSample\" ) . allowReadOnlyDirectory ( true ) . allowNewDirectoryNameModification ( true ) . build ( ) ; chooserIntent . putExtra ( DirectoryChooserActivity . EXTRA_CONFIG , config ) ; startActivityForResult ( chooserIntent , REQUEST_DIRECTORY ) ; } } ) ; findViewById ( R . id . btnChange ) . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { final Intent fragmentSampleIntent = new Intent ( DirChooserSample . this , DirChooserFragmentSample . class ) ; startActivity ( fragmentSampleIntent ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the specified <code > String< / code > parses as a valid domain name with a recognized top - level domain . The parsing is case - insensitive . [CODESPLIT] public boolean isValid ( String domain ) { if ( domain == null ) { return false ; } domain = unicodeToASCII ( domain ) ; // hosts must be equally reachable via punycode and Unicode; // Unicode is never shorter than punycode, so check punycode // if domain did not convert, then it will be caught by ASCII // checks in the regexes below if ( domain . length ( ) > 253 ) { return false ; } String [ ] groups = domainRegex . match ( domain ) ; if ( groups != null && groups . length > 0 ) { return isValidTld ( groups [ 0 ] ) ; } return allowLocal && hostnameRegex . isValid ( domain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the specified <code > String< / code > matches any IANA - defined infrastructure top - level domain . Leading dots are ignored if present . The search is case - insensitive . [CODESPLIT] public boolean isValidInfrastructureTld ( String iTld ) { iTld = unicodeToASCII ( iTld ) ; return Arrays . binarySearch ( INFRASTRUCTURE_TLDS , ( chompLeadingDot ( iTld . toLowerCase ( Locale . ENGLISH ) ) ) ) >= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the specified <code > String< / code > matches any IANA - defined generic top - level domain . Leading dots are ignored if present . The search is case - insensitive . [CODESPLIT] public boolean isValidGenericTld ( String gTld ) { gTld = unicodeToASCII ( gTld ) ; return Arrays . binarySearch ( GENERIC_TLDS , chompLeadingDot ( gTld . toLowerCase ( Locale . ENGLISH ) ) ) >= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the specified <code > String< / code > matches any IANA - defined country code top - level domain . Leading dots are ignored if present . The search is case - insensitive . [CODESPLIT] public boolean isValidCountryCodeTld ( String ccTld ) { ccTld = unicodeToASCII ( ccTld ) ; return Arrays . binarySearch ( COUNTRY_CODE_TLDS , chompLeadingDot ( ccTld . toLowerCase ( Locale . ENGLISH ) ) ) >= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the specified <code > String< / code > matches any widely used local domains ( localhost or localdomain ) . Leading dots are ignored if present . The search is case - insensitive . [CODESPLIT] public boolean isValidLocalTld ( String lTld ) { lTld = unicodeToASCII ( lTld ) ; return Arrays . binarySearch ( LOCAL_TLDS , chompLeadingDot ( lTld . toLowerCase ( Locale . ENGLISH ) ) ) >= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Helper method to invoke java . net . IDN . toAscii ( String ) . Allows code to be compiled with Java 1 . 4 and 1 . 5 [CODESPLIT] private static final String toASCII ( String line ) throws IllegalArgumentException { //        java.net.IDN.toASCII(line); // Java 1.6+ // implementation for Java 1.4 and 1.5 // effectively this is done by IDN.toASCII but we want to skip the entire call if ( isOnlyASCII ( line ) ) { return line ; } Method m = IDNHolder . JAVA_NET_IDN_TO_ASCII ; if ( m == null ) { // avoid NPE return line ; } try { return ( String ) m . invoke ( null , new String [ ] { line . toLowerCase ( Locale . ENGLISH ) } ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; // Should not happen } catch ( InvocationTargetException e ) { Throwable t = e . getCause ( ) ; if ( t instanceof IllegalArgumentException ) { // this is expected from toASCII method throw ( IllegalArgumentException ) t ; } throw new RuntimeException ( e ) ; // Should not happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Lifecycle Methods ******************************************* [CODESPLIT] @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; // set theme setTheme ( RTApi . useDarkTheme ( ) ? R . style . RTE_BaseThemeDark : R . style . RTE_BaseThemeLight ) ; if ( ! isFinishing ( ) ) { mHandler = new Handler ( ) ; for ( LifeCycleListener listener : mListeners ) { listener . onActivityCreated ( this ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start a foreground job showing a progress bar as long as the job runs . A foreground job shows a modal dialog that can t be cancelled while the app does some processing . This should be used for short jobs only that block the ui . Of course this contradicts many of the Android guidelines but with short jobs we mean < 1 second and only in rare cases should it me more ( e . g . when the garbage collector kicks in which would normally lead to stuttering ) . Using foreground jobs gives a better user experience in these rare cases . The user has to wait but he / she knows it because there s a progess bar . [CODESPLIT] public < T > T startForegroundJob ( int msgId , ForegroundJob < T > job ) { // make the progress dialog uncancelable, so that we can guarantee // that the thread is done before the activity gets destroyed ProgressDialog dialog = ProgressDialog . show ( this , null , getString ( msgId ) , true , false ) ; Job < T > managedJob = new Job < T > ( job , dialog ) ; return managedJob . runForegroundJob ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start a background job showing a progress bar as long as the job runs . This seems contradictory but with background job we mean one that runs off the ui thread to prevent an ANR . We still have to wait for the processing to be done because we need the result . [CODESPLIT] public void startBackgroundJob ( int msgId , Runnable runnable ) { // make the progress dialog uncancelable, so that we can guarantee // that the thread is done before the activity gets destroyed ProgressDialog dialog = ProgressDialog . show ( this , null , getString ( msgId ) , true , false ) ; Job < Object > managedJob = new Job < Object > ( runnable , dialog ) ; managedJob . runBackgroundJob ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Handle Tags ******************************************* [CODESPLIT] private void handleStartTag ( String tag , Attributes attributes ) { if ( tag . equalsIgnoreCase ( \"br\" ) ) { // We don't need to handle this. TagSoup will ensure that there's a </br> for each <br> // so we can safely omit the line breaks when we handle the close tag. } else if ( tag . equalsIgnoreCase ( \"p\" ) ) { handleP ( ) ; } else if ( tag . equalsIgnoreCase ( \"div\" ) ) { startDiv ( attributes ) ; } else if ( tag . equalsIgnoreCase ( \"ul\" ) ) { startList ( false , attributes ) ; } else if ( tag . equalsIgnoreCase ( \"ol\" ) ) { startList ( true , attributes ) ; } else if ( tag . equalsIgnoreCase ( \"li\" ) ) { startList ( attributes ) ; } else if ( tag . equalsIgnoreCase ( \"strong\" ) ) { start ( new Bold ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"b\" ) ) { start ( new Bold ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"em\" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"cite\" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"dfn\" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"i\" ) ) { start ( new Italic ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"strike\" ) ) { start ( new Strikethrough ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"del\" ) ) { start ( new Strikethrough ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"big\" ) ) { start ( new Big ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"small\" ) ) { start ( new Small ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"font\" ) ) { startFont ( attributes ) ; } else if ( tag . equalsIgnoreCase ( \"blockquote\" ) ) { handleP ( ) ; start ( new Blockquote ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"tt\" ) ) { start ( new Monospace ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"a\" ) ) { startAHref ( attributes ) ; } else if ( tag . equalsIgnoreCase ( \"u\" ) ) { start ( new Underline ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"sup\" ) ) { start ( new Super ( ) ) ; } else if ( tag . equalsIgnoreCase ( \"sub\" ) ) { start ( new Sub ( ) ) ; } else if ( tag . length ( ) == 2 && Character . toLowerCase ( tag . charAt ( 0 ) ) == ' ' && tag . charAt ( 1 ) >= ' ' && tag . charAt ( 1 ) <= ' ' ) { handleP ( ) ; start ( new Header ( tag . charAt ( 1 ) - ' ' ) ) ; } else if ( tag . equalsIgnoreCase ( \"img\" ) ) { startImg ( attributes ) ; } else if ( tag . equalsIgnoreCase ( \"video\" ) ) { startVideo ( attributes ) ; } else if ( tag . equalsIgnoreCase ( \"embed\" ) ) { startAudio ( attributes ) ; } else if ( sIgnoreTags . contains ( tag . toLowerCase ( Locale . getDefault ( ) ) ) ) { mIgnoreContent = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles OL and UL start tags [CODESPLIT] private void startList ( boolean isOrderedList , Attributes attributes ) { boolean isIndentation = isIndentation ( attributes ) ; ParagraphType newType = isIndentation && isOrderedList ? ParagraphType . INDENTATION_OL : isIndentation && ! isOrderedList ? ParagraphType . INDENTATION_UL : isOrderedList ? ParagraphType . NUMBERING : ParagraphType . BULLET ; AccumulatedParagraphStyle currentStyle = mParagraphStyles . isEmpty ( ) ? null : mParagraphStyles . peek ( ) ; if ( currentStyle == null ) { // no previous style found -> create new AccumulatedParagraphStyle with indentations of 1 AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle ( newType , 1 , 1 ) ; mParagraphStyles . push ( newStyle ) ; } else if ( currentStyle . getType ( ) == newType ) { // same style found -> increase indentations by 1 currentStyle . setAbsoluteIndent ( currentStyle . getAbsoluteIndent ( ) + 1 ) ; currentStyle . setRelativeIndent ( currentStyle . getRelativeIndent ( ) + 1 ) ; } else { // different style found -> create new AccumulatedParagraphStyle with incremented indentations AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle ( newType , currentStyle . getAbsoluteIndent ( ) + 1 , 1 ) ; mParagraphStyles . push ( newStyle ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles OL and UL end tags [CODESPLIT] private void endList ( boolean orderedList ) { if ( ! mParagraphStyles . isEmpty ( ) ) { AccumulatedParagraphStyle style = mParagraphStyles . peek ( ) ; ParagraphType type = style . getType ( ) ; if ( ( orderedList && ( type . isNumbering ( ) || type == ParagraphType . INDENTATION_OL ) ) || ( ! orderedList && ( type . isBullet ( ) || type == ParagraphType . INDENTATION_UL ) ) ) { // the end tag matches the current style int indent = style . getRelativeIndent ( ) ; if ( indent > 1 ) { style . setRelativeIndent ( indent - 1 ) ; style . setAbsoluteIndent ( style . getAbsoluteIndent ( ) - 1 ) ; } else { mParagraphStyles . pop ( ) ; } } else { // the end tag doesn't match the current style mParagraphStyles . pop ( ) ; endList ( orderedList ) ; // find the next matching style } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles LI tags [CODESPLIT] private void startList ( Attributes attributes ) { List listTag = null ; if ( ! mParagraphStyles . isEmpty ( ) ) { AccumulatedParagraphStyle currentStyle = mParagraphStyles . peek ( ) ; ParagraphType type = currentStyle . getType ( ) ; int indent = currentStyle . getAbsoluteIndent ( ) ; boolean isIndentation = isIndentation ( attributes ) ; if ( type . isIndentation ( ) || isIndentation ) { listTag = new UL ( indent , true ) ; } else if ( type . isNumbering ( ) ) { listTag = new OL ( indent , false ) ; } else if ( type . isBullet ( ) ) { listTag = new UL ( indent , false ) ; } } else { listTag = new UL ( 0 , false ) ; } if ( listTag != null ) start ( listTag ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles LI tags [CODESPLIT] private void endList ( ) { List list = ( List ) getLast ( List . class ) ; if ( list != null ) { if ( mResult . length ( ) == 0 || mResult . charAt ( mResult . length ( ) - 1 ) != ' ' ) { mResult . append ( ' ' ) ; } int start = mResult . getSpanStart ( list ) ; int end = mResult . length ( ) ; int nrOfIndents = list . mNrOfIndents ; if ( ! list . mIsIndentation ) { nrOfIndents -- ; int margin = Helper . getLeadingMarging ( ) ; // use SPAN_EXCLUSIVE_EXCLUSIVE here, will be replaced later anyway when the cleanup function is called Object span = list instanceof UL ? new BulletSpan ( margin , start == end , false , false ) : new NumberSpan ( 1 , margin , start == end , false , false ) ; mResult . setSpan ( span , start , end , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } if ( nrOfIndents > 0 ) { int margin = nrOfIndents * Helper . getLeadingMarging ( ) ; // use SPAN_EXCLUSIVE_EXCLUSIVE here, will be replaced later anyway when the cleanup function is called IndentationSpan span = new IndentationSpan ( margin , start == end , false , false ) ; mResult . setSpan ( span , start , end , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } mResult . removeSpan ( list ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an HTML color ( named or numeric ) to an integer RGB value . [CODESPLIT] @ SuppressLint ( \"DefaultLocale\" ) private static int getHtmlColor ( String color ) { Integer i = COLORS . get ( color . toLowerCase ( ) ) ; if ( i != null ) { return i ; } else { try { return convertValueToInt ( color , - 1 ) ; } catch ( NumberFormatException nfe ) { return - 1 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines which edges are hit by touching at ( x y ) . [CODESPLIT] public int getHit ( float x , float y ) { Rect r = computeLayout ( ) ; final float hysteresis = 20F ; int retval = GROW_NONE ; if ( mCircle ) { float distX = x - r . centerX ( ) ; float distY = y - r . centerY ( ) ; int distanceFromCenter = ( int ) Math . sqrt ( distX * distX + distY * distY ) ; int radius = mDrawRect . width ( ) / 2 ; int delta = distanceFromCenter - radius ; if ( Math . abs ( delta ) <= hysteresis ) { if ( Math . abs ( distY ) > Math . abs ( distX ) ) { if ( distY < 0 ) { retval = GROW_TOP_EDGE ; } else { retval = GROW_BOTTOM_EDGE ; } } else { if ( distX < 0 ) { retval = GROW_LEFT_EDGE ; } else { retval = GROW_RIGHT_EDGE ; } } } else if ( distanceFromCenter < radius ) { retval = MOVE ; } else { retval = GROW_NONE ; } } else { // verticalCheck makes sure the position is between the top and // the bottom edge (with some tolerance). Similar for horizCheck. boolean verticalCheck = ( y >= r . top - hysteresis ) && ( y < r . bottom + hysteresis ) ; boolean horizCheck = ( x >= r . left - hysteresis ) && ( x < r . right + hysteresis ) ; // Check whether the position is near some edge(s). if ( ( Math . abs ( r . left - x ) < hysteresis ) && verticalCheck ) { retval |= GROW_LEFT_EDGE ; } if ( ( Math . abs ( r . right - x ) < hysteresis ) && verticalCheck ) { retval |= GROW_RIGHT_EDGE ; } if ( ( Math . abs ( r . top - y ) < hysteresis ) && horizCheck ) { retval |= GROW_TOP_EDGE ; } if ( ( Math . abs ( r . bottom - y ) < hysteresis ) && horizCheck ) { retval |= GROW_BOTTOM_EDGE ; } // Not near any edge but inside the rectangle: move. if ( retval == GROW_NONE && r . contains ( ( int ) x , ( int ) y ) ) { retval = MOVE ; } } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The edge parameter specifies which edges the user is dragging . [CODESPLIT] void handleMotion ( int edge , float dx , float dy ) { Rect r = computeLayout ( ) ; if ( edge == GROW_NONE ) { return ; } else if ( edge == MOVE ) { // Convert to image space before sending to moveBy(). moveBy ( dx * ( mCropRect . width ( ) / r . width ( ) ) , dy * ( mCropRect . height ( ) / r . height ( ) ) ) ; } else { if ( ( ( GROW_LEFT_EDGE | GROW_RIGHT_EDGE ) & edge ) == 0 ) { dx = 0 ; } if ( ( ( GROW_TOP_EDGE | GROW_BOTTOM_EDGE ) & edge ) == 0 ) { dy = 0 ; } // Convert to image space before sending to growBy(). float xDelta = dx * ( mCropRect . width ( ) / r . width ( ) ) ; float yDelta = dy * ( mCropRect . height ( ) / r . height ( ) ) ; growBy ( ( ( ( edge & GROW_LEFT_EDGE ) != 0 ) ? - 1 : 1 ) * xDelta , ( ( ( edge & GROW_TOP_EDGE ) != 0 ) ? - 1 : 1 ) * yDelta ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grows the cropping rectange by ( dx dy ) in image space . [CODESPLIT] void moveBy ( float dx , float dy ) { Rect invalRect = new Rect ( mDrawRect ) ; mCropRect . offset ( dx , dy ) ; // Put the cropping rectangle inside image rectangle. mCropRect . offset ( Math . max ( 0 , mImageRect . left - mCropRect . left ) , Math . max ( 0 , mImageRect . top - mCropRect . top ) ) ; mCropRect . offset ( Math . min ( 0 , mImageRect . right - mCropRect . right ) , Math . min ( 0 , mImageRect . bottom - mCropRect . bottom ) ) ; mDrawRect = computeLayout ( ) ; invalRect . union ( mDrawRect ) ; invalRect . inset ( - 10 , - 10 ) ; mContext . invalidate ( invalRect ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grows the cropping rectange by ( dx dy ) in image space . [CODESPLIT] void growBy ( float dx , float dy ) { if ( mMaintainAspectRatio ) { if ( dx != 0 ) { dy = dx / mInitialAspectRatio ; } else if ( dy != 0 ) { dx = dy * mInitialAspectRatio ; } } // Don't let the cropping rectangle grow too fast. // Grow at most half of the difference between the image rectangle and // the cropping rectangle. RectF r = new RectF ( mCropRect ) ; if ( dx > 0F && r . width ( ) + 2 * dx > mImageRect . width ( ) ) { float adjustment = ( mImageRect . width ( ) - r . width ( ) ) / 2F ; dx = adjustment ; if ( mMaintainAspectRatio ) { dy = dx / mInitialAspectRatio ; } } if ( dy > 0F && r . height ( ) + 2 * dy > mImageRect . height ( ) ) { float adjustment = ( mImageRect . height ( ) - r . height ( ) ) / 2F ; dy = adjustment ; if ( mMaintainAspectRatio ) { dx = dy * mInitialAspectRatio ; } } r . inset ( - dx , - dy ) ; // Don't let the cropping rectangle shrink too fast. final float widthCap = 25F ; if ( r . width ( ) < widthCap ) { r . inset ( - ( widthCap - r . width ( ) ) / 2F , 0F ) ; } float heightCap = mMaintainAspectRatio ? ( widthCap / mInitialAspectRatio ) : widthCap ; if ( r . height ( ) < heightCap ) { r . inset ( 0F , - ( heightCap - r . height ( ) ) / 2F ) ; } // Put the cropping rectangle inside the image rectangle. if ( r . left < mImageRect . left ) { r . offset ( mImageRect . left - r . left , 0F ) ; } else if ( r . right > mImageRect . right ) { r . offset ( - ( r . right - mImageRect . right ) , 0 ) ; } if ( r . top < mImageRect . top ) { r . offset ( 0F , mImageRect . top - r . top ) ; } else if ( r . bottom > mImageRect . bottom ) { r . offset ( 0F , - ( r . bottom - mImageRect . bottom ) ) ; } mCropRect . set ( r ) ; mDrawRect = computeLayout ( ) ; mContext . invalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the cropping rectangle in image space . [CODESPLIT] public Rect getCropRect ( ) { return new Rect ( ( int ) mCropRect . left , ( int ) mCropRect . top , ( int ) mCropRect . right , ( int ) mCropRect . bottom ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the cropping rectangle from image space to screen space . [CODESPLIT] private Rect computeLayout ( ) { RectF r = new RectF ( mCropRect . left , mCropRect . top , mCropRect . right , mCropRect . bottom ) ; mMatrix . mapRect ( r ) ; return new Rect ( Math . round ( r . left ) , Math . round ( r . top ) , Math . round ( r . right ) , Math . round ( r . bottom ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This needs to be called before anything else because we need the media factory . [CODESPLIT] void register ( RTEditTextListener listener , RTMediaFactory < RTImage , RTAudio , RTVideo > mediaFactory ) { mListener = listener ; mMediaFactory = mediaFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the start and end of the paragraph ( s ) encompassing the current selection . A paragraph spans from one \\ n ( exclusive ) to the next one ( inclusive ) [CODESPLIT] public Selection getParagraphsInSelection ( ) { RTLayout layout = getRTLayout ( ) ; Selection selection = new Selection ( this ) ; int firstLine = layout . getLineForOffset ( selection . start ( ) ) ; int end = selection . isEmpty ( ) ? selection . end ( ) : selection . end ( ) - 1 ; int lastLine = layout . getLineForOffset ( end ) ; return new Selection ( layout . getLineStart ( firstLine ) , layout . getLineEnd ( lastLine ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the edit mode to plain or rich text . The text will be converted automatically to rich / plain text if autoConvert is True . [CODESPLIT] public void setRichTextEditing ( boolean useRTFormatting , boolean autoConvert ) { assertRegistration ( ) ; if ( useRTFormatting != mUseRTFormatting ) { mUseRTFormatting = useRTFormatting ; if ( autoConvert ) { RTFormat targetFormat = useRTFormatting ? RTFormat . PLAIN_TEXT : RTFormat . HTML ; setText ( getRichText ( targetFormat ) ) ; } if ( mListener != null ) { mListener . onRichTextEditingChanged ( this , mUseRTFormatting ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the edit mode to plain or rich text and updates the content at the same time . The caller needs to make sure the content matches the correct format ( if you pass in html code as plain text the editor will show the html code ) . [CODESPLIT] public void setRichTextEditing ( boolean useRTFormatting , String content ) { assertRegistration ( ) ; if ( useRTFormatting != mUseRTFormatting ) { mUseRTFormatting = useRTFormatting ; if ( mListener != null ) { mListener . onRichTextEditingChanged ( this , mUseRTFormatting ) ; } } RTText rtText = useRTFormatting ? new RTHtml < RTImage , RTAudio , RTVideo > ( RTFormat . HTML , content ) : new RTPlainText ( content ) ; setText ( rtText ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the text for this editor . <p > It will convert the text from rich text to plain text if the editor s mode is set to use plain text . or to a spanned text ( only supported formatting ) if the editor s mode is set to use rich text <p > We need to prevent onSelectionChanged () to do anything as long as setText () hasn t finished because the Layout doesn t seem to update before setText has finished but onSelectionChanged will still be called during setText and will receive the out - dated Layout which doesn t allow us to apply styles and such . [CODESPLIT] public void setText ( RTText rtText ) { assertRegistration ( ) ; if ( rtText . getFormat ( ) instanceof RTFormat . Html ) { if ( mUseRTFormatting ) { RTText rtSpanned = rtText . convertTo ( RTFormat . SPANNED , mMediaFactory ) ; super . setText ( rtSpanned . getText ( ) , TextView . BufferType . EDITABLE ) ; addSpanWatcher ( ) ; // collect all current media Spannable text = getText ( ) ; for ( MediaSpan span : text . getSpans ( 0 , text . length ( ) , MediaSpan . class ) ) { mOriginalMedia . add ( span . getMedia ( ) ) ; } Effects . cleanupParagraphs ( this ) ; } else { RTText rtPlainText = rtText . convertTo ( RTFormat . PLAIN_TEXT , mMediaFactory ) ; super . setText ( rtPlainText . getText ( ) ) ; } } else if ( rtText . getFormat ( ) instanceof RTFormat . PlainText ) { CharSequence text = rtText . getText ( ) ; super . setText ( text == null ? \"\" : text . toString ( ) ) ; } onSelectionChanged ( 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as String getText ( RTFormat format ) but this method returns the RTText instead of just the actual text . [CODESPLIT] public RTText getRichText ( RTFormat format ) { assertRegistration ( ) ; RTEditable rtEditable = new RTEditable ( this ) ; return rtEditable . convertTo ( format , mMediaFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a SpanWatcher for the Changeable implementation [CODESPLIT] private void addSpanWatcher ( ) { Spannable spannable = getText ( ) ; if ( spannable . getSpans ( 0 , spannable . length ( ) , getClass ( ) ) != null ) { spannable . setSpan ( this , 0 , spannable . length ( ) , Spanned . SPAN_INCLUSIVE_INCLUSIVE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this to have an effect applied to the current selection . You get the Effect object via the static data members ( e . g . RTEditText . BOLD ) . The value for most effects is a Boolean indicating whether to add or remove the effect . [CODESPLIT] public < V extends Object , C extends RTSpan < V > > void applyEffect ( Effect < V , C > effect , V value ) { if ( mUseRTFormatting && ! mIsSelectionChanging && ! mIsSaving ) { Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable ( ) ; effect . applyToSelection ( this , value ) ; synchronized ( this ) { if ( mListener != null && ! mIgnoreTextChanges ) { Spannable newSpannable = cloneSpannable ( ) ; mListener . onTextChanged ( this , oldSpannable , newSpannable , getSelectionStart ( ) , getSelectionEnd ( ) , getSelectionStart ( ) , getSelectionEnd ( ) ) ; } mLayoutChanged = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "space [CODESPLIT] public static RTPlainText convert ( RTHtml < ? extends RTImage , ? extends RTAudio , ? extends RTVideo > input ) { String result = Html . fromHtml ( input . getText ( ) , null , new HtmlToTextTagHandler ( ) ) . toString ( ) . replace ( PREVIEW_OBJECT_CHARACTER , PREVIEW_OBJECT_REPLACEMENT ) . replace ( NBSP_CHARACTER , NBSP_REPLACEMENT ) ; return new RTPlainText ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts this rich text to another rich text . The default implementation doesn t support any conversion except the one to itself ( which is technically no conversion ) . <p > The method has to make sure that the original rich text isn t modified . It does however not make sure that the returned RTText isn t referencing the original RTText meaning modifying the resulting object might also modify the original object . [CODESPLIT] public RTText convertTo ( RTFormat destFormat , RTMediaFactory < RTImage , RTAudio , RTVideo > mediaFactory ) { if ( destFormat == mRTFormat ) { return this ; } throw new UnsupportedOperationException ( \"Can't convert from \" + mRTFormat . getClass ( ) . getSimpleName ( ) + \" to \" + destFormat . getClass ( ) . getSimpleName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** SpannableString Methods ******************************************* [CODESPLIT] @ Override public void setSpan ( Object what , int start , int end , int flags ) { if ( mSpanCount + 1 >= mSpans . length ) { int newsize = mSpanCount + 10 ; Object [ ] newtags = new Object [ newsize ] ; int [ ] newdata = new int [ newsize * 3 ] ; System . arraycopy ( mSpans , 0 , newtags , 0 , mSpanCount ) ; System . arraycopy ( mSpanData , 0 , newdata , 0 , mSpanCount * 3 ) ; mSpans = newtags ; mSpanData = newdata ; } mSpans [ mSpanCount ] = what ; mSpanData [ mSpanCount * COLUMNS + START ] = start ; mSpanData [ mSpanCount * COLUMNS + END ] = end ; mSpanData [ mSpanCount * COLUMNS + FLAGS ] = flags ; mSpanCount ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the spinner view [CODESPLIT] @ SuppressLint ( \"ViewHolder\" ) @ Override public final View getView ( int position , View convertView , ViewGroup parent ) { View spinnerView = mInflater . inflate ( mSpinnerId , parent , false ) ; mParent = parent ; TextView spinnerTitleView = ( TextView ) spinnerView . findViewById ( R . id . title ) ; updateSpinnerTitle ( spinnerTitleView ) ; return spinnerView ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the spinner entry view [CODESPLIT] @ SuppressLint ( \"InlinedApi\" ) @ Override public View getDropDownView ( int position , View convertView , ViewGroup parent ) { SpinnerItem spinnerItem = mItems . get ( position ) ; spinnerItem . setOnChangedListener ( this , position ) ; // we can't use the convertView because it keeps handing us spinner layouts (mSpinnerId) View spinnerItemView = mInflater . inflate ( mSpinnerItemId , parent , false ) ; int key = ( position << 16 ) + getItemViewType ( position ) ; mViewCache . put ( key , spinnerItemView ) ; bindView ( position , spinnerItemView , spinnerItem ) ; return spinnerItemView ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a spanned text to HTML [CODESPLIT] public RTHtml < RTImage , RTAudio , RTVideo > convert ( final Spanned text , RTFormat . Html rtFormat ) { mText = text ; mRTFormat = rtFormat ; mOut = new StringBuilder ( ) ; mImages = new ArrayList <> ( ) ; mParagraphStyles . clear ( ) ; // convert paragraphs convertParagraphs ( ) ; return new RTHtml <> ( rtFormat , mOut . toString ( ) , mImages ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Process Paragraphs ******************************************* [CODESPLIT] private void convertParagraphs ( ) { RTLayout rtLayout = new RTLayout ( mText ) ; // a manual for loop is faster than the for-each loop for an ArrayList: // see https://developer.android.com/training/articles/perf-tips.html#Loops ArrayList < Paragraph > paragraphs = rtLayout . getParagraphs ( ) ; for ( int i = 0 , size = paragraphs . size ( ) ; i < size ; i ++ ) { Paragraph paragraph = paragraphs . get ( i ) ; // retrieve all spans for this paragraph Set < SingleParagraphStyle > styles = getParagraphStyles ( mText , paragraph ) ; // get the alignment span if there is any ParagraphType alignmentType = null ; for ( SingleParagraphStyle style : styles ) { if ( style . getType ( ) . isAlignment ( ) ) { alignmentType = style . getType ( ) ; break ; } } /*\n             * start tag: bullet points, numbering and indentation\n             */ int newIndent = 0 ; ParagraphType newType = ParagraphType . NONE ; for ( SingleParagraphStyle style : styles ) { newIndent += style . getIndentation ( ) ; ParagraphType type = style . getType ( ) ; newType = type . isBullet ( ) ? ParagraphType . BULLET : type . isNumbering ( ) ? ParagraphType . NUMBERING : type . isIndentation ( ) && newType . isUndefined ( ) ? ParagraphType . INDENTATION_UL : newType ; } // process leading margin style processLeadingMarginStyle ( new AccumulatedParagraphStyle ( newType , newIndent , 0 ) ) ; // add start list tag mOut . append ( newType . getListStartTag ( ) ) ; /*\n             * start tag: alignment (left, center, right)\n             */ if ( alignmentType != null ) { mOut . append ( alignmentType . getStartTag ( ) ) ; } /*\n             * Convert the plain text\n             */ withinParagraph ( mText , paragraph . start ( ) , paragraph . end ( ) ) ; /*\n             * end tag: alignment (left, center, right)\n             */ if ( alignmentType != null ) { removeTrailingLineBreak ( alignmentType ) ; mOut . append ( alignmentType . getEndTag ( ) ) ; } // add end list tag removeTrailingLineBreak ( newType ) ; mOut . append ( newType . getListEndTag ( ) ) ; } /*\n         * end tag: bullet points and indentation\n         */ while ( ! mParagraphStyles . isEmpty ( ) ) { removeParagraph ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a spanned text within a paragraph [CODESPLIT] private void withinParagraph ( final Spanned text , int start , int end ) { // create sorted set of CharacterStyles SortedSet < CharacterStyle > sortedSpans = new TreeSet <> ( ( s1 , s2 ) -> { int start1 = text . getSpanStart ( s1 ) ; int start2 = text . getSpanStart ( s2 ) ; if ( start1 != start2 ) return start1 - start2 ; // span which starts first comes first int end1 = text . getSpanEnd ( s1 ) ; int end2 = text . getSpanEnd ( s2 ) ; if ( end1 != end2 ) return end2 - end1 ; // longer span comes first // if the paragraphs have the same span [start, end] we compare their name // compare the name only because local + anonymous classes have no canonical name return s1 . getClass ( ) . getName ( ) . compareTo ( s2 . getClass ( ) . getName ( ) ) ; } ) ; List < CharacterStyle > spanList = Arrays . asList ( text . getSpans ( start , end , CharacterStyle . class ) ) ; sortedSpans . addAll ( spanList ) ; // process paragraphs/divs convertText ( text , start , end , sortedSpans ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape plain text parts : < > & Space -- > ^lt ; &gt ; etc . [CODESPLIT] private void escape ( CharSequence text , int start , int end ) { for ( int i = start ; i < end ; i ++ ) { char c = text . charAt ( i ) ; if ( c == ' ' ) { mOut . append ( BR ) ; } else if ( c == ' ' ) { mOut . append ( LT ) ; } else if ( c == ' ' ) { mOut . append ( GT ) ; } else if ( c == ' ' ) { mOut . append ( AMP ) ; } else if ( c == ' ' ) { while ( i + 1 < end && text . charAt ( i + 1 ) == ' ' ) { mOut . append ( NBSP ) ; i ++ ; } mOut . append ( ' ' ) ; } // removed the c > 0x7E check to leave emoji unaltered else if ( /*c > 0x7E || */ c < ' ' ) { mOut . append ( \"&#\" + ( ( int ) c ) + \";\" ) ; } else { mOut . append ( c ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a file with a non - conflicting file name in a specified folder based on an existing file name . [CODESPLIT] public static File createUniqueFile ( File targetFolder , String originalFile , boolean keepOriginal ) { String mimeType = MimeTypeMap . getSingleton ( ) . getMimeTypeFromExtension ( originalFile ) ; return createUniqueFile ( targetFolder , originalFile , mimeType , keepOriginal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a file Uri for a file defined by its absolute path . The method can handle the case of an absolute path ( e . g . / data / data .... ) and a Uri path containing the file : // scheme ( e . g . file : /// data / data ... ) [CODESPLIT] public static Uri createFileUri ( String path ) { if ( path . startsWith ( \"file://\" ) ) { return Uri . parse ( path ) ; } return Uri . fromFile ( new File ( path ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve local file path for an arbitrary Uri [CODESPLIT] public static String determineOriginalFile ( Context context , Uri uri ) throws IllegalArgumentException { String originalFile = null ; if ( uri != null ) { // Picasa on Android >= 3.0 or other files using content providers if ( uri . getScheme ( ) . startsWith ( \"content\" ) ) { originalFile = getPathFromUri ( context , uri ) ; } // Picasa on Android < 3.0 if ( uri . toString ( ) . matches ( \"https?://\\\\w+\\\\.googleusercontent\\\\.com/.+\" ) ) { originalFile = uri . toString ( ) ; } // local storage if ( uri . getScheme ( ) . startsWith ( \"file\" ) ) { originalFile = uri . toString ( ) . substring ( 7 ) ; } if ( isNullOrEmpty ( originalFile ) ) { throw new IllegalArgumentException ( \"File path was null\" ) ; } } else { throw new IllegalArgumentException ( \"Image Uri was null!\" ) ; } return originalFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a namespace name from a Qname . The attribute flag tells us whether to return an empty namespace name if there is no prefix or use the schema default instead . [CODESPLIT] public String namespace ( String name , boolean attribute ) { int colon = name . indexOf ( ' ' ) ; if ( colon == - 1 ) { return attribute ? \"\" : theSchema . getURI ( ) ; } String prefix = name . substring ( 0 , colon ) ; if ( prefix . equals ( \"xml\" ) ) { return \"http://www.w3.org/XML/1998/namespace\" ; } else { return ( \"urn:x-prefix:\" + prefix ) . intern ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a local name from a Qname . [CODESPLIT] public String localName ( String name ) { int colon = name . indexOf ( ' ' ) ; if ( colon == - 1 ) { return name ; } else { return name . substring ( colon + 1 ) . intern ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets an attribute and its value into an AttributesImpl object . Attempts to set a namespace declaration are ignored . [CODESPLIT] public void setAttribute ( AttributesImpl atts , String name , String type , String value ) { if ( name . equals ( \"xmlns\" ) || name . startsWith ( \"xmlns:\" ) ) { return ; } ; String namespace = namespace ( name , true ) ; String localName = localName ( name ) ; int i = atts . getIndex ( name ) ; if ( i == - 1 ) { name = name . intern ( ) ; if ( type == null ) type = \"CDATA\" ; if ( ! type . equals ( \"CDATA\" ) ) value = normalize ( value ) ; atts . addAttribute ( namespace , localName , name , type , value ) ; } else { if ( type == null ) type = atts . getType ( i ) ; if ( ! type . equals ( \"CDATA\" ) ) value = normalize ( value ) ; atts . setAttribute ( i , namespace , localName , name , type , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize an attribute value ( ID - style ) . CDATA - style attribute normalization is already done . [CODESPLIT] public static String normalize ( String value ) { if ( value == null ) return value ; value = value . trim ( ) ; if ( value . indexOf ( \"  \" ) == - 1 ) return value ; boolean space = false ; int len = value . length ( ) ; StringBuffer b = new StringBuffer ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { char v = value . charAt ( i ) ; if ( v == ' ' ) { if ( ! space ) b . append ( v ) ; space = true ; } else { b . append ( v ) ; space = false ; } } return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets an attribute and its value into this element type . [CODESPLIT] public void setAttribute ( String name , String type , String value ) { setAttribute ( theAtts , name , type , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append a portion of a character sequence to the { @link StringBuilder } . [CODESPLIT] @ Override public Writer append ( CharSequence value , int start , int end ) { builder . append ( value , start , end ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a portion of a character array to the { @link StringBuilder } . [CODESPLIT] @ Override public void write ( char [ ] value , int offset , int length ) { if ( value != null ) { builder . append ( value , offset , length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the file name for a system font . [CODESPLIT] static String getFontName ( String filePath ) { TTFRandomAccessFile in = null ; try { RandomAccessFile file = new RandomAccessFile ( filePath , \"r\" ) ; in = new TTFRandomAccessFile ( file ) ; return getTTFFontName ( in , filePath ) ; } catch ( IOException e ) { return null ; // Missing permissions or corrupted font file? } finally { IOUtils . closeQuietly ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the file name for a font in the asset folder . [CODESPLIT] static String getFontName ( AssetManager assets , String filePath ) { TTFAssetInputStream in = null ; try { InputStream file = assets . open ( filePath , AssetManager . ACCESS_RANDOM ) ; in = new TTFAssetInputStream ( file ) ; return getTTFFontName ( in , filePath ) ; } catch ( FileNotFoundException e ) { return null ; // Missing permissions? } catch ( IOException e ) { return null ; // Corrupted font file? } finally { IOUtils . closeQuietly ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a new buffer available either by allocating a new one or re - cycling an existing one . [CODESPLIT] private void needNewBuffer ( int newcount ) { if ( currentBufferIndex < buffers . size ( ) - 1 ) { //Recycling old buffer filledBufferSum += currentBuffer . length ; currentBufferIndex ++ ; currentBuffer = buffers . get ( currentBufferIndex ) ; } else { //Creating new buffer int newBufferSize ; if ( currentBuffer == null ) { newBufferSize = newcount ; filledBufferSum = 0 ; } else { newBufferSize = Math . max ( currentBuffer . length << 1 , newcount - filledBufferSum ) ; filledBufferSum += currentBuffer . length ; } currentBufferIndex ++ ; currentBuffer = new byte [ newBufferSize ] ; buffers . add ( currentBuffer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the bytes to byte array . [CODESPLIT] @ Override public void write ( byte [ ] b , int off , int len ) { if ( ( off < 0 ) || ( off > b . length ) || ( len < 0 ) || ( ( off + len ) > b . length ) || ( ( off + len ) < 0 ) ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return ; } synchronized ( this ) { int newcount = count + len ; int remaining = len ; int inBufferPos = count - filledBufferSum ; while ( remaining > 0 ) { int part = Math . min ( remaining , currentBuffer . length - inBufferPos ) ; System . arraycopy ( b , off + len - remaining , currentBuffer , inBufferPos , part ) ; remaining -= part ; if ( remaining > 0 ) { needNewBuffer ( newcount ) ; inBufferPos = 0 ; } } count = newcount ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a byte to byte array . [CODESPLIT] @ Override public synchronized void write ( int b ) { int inBufferPos = count - filledBufferSum ; if ( inBufferPos == currentBuffer . length ) { needNewBuffer ( count + 1 ) ; inBufferPos = 0 ; } currentBuffer [ inBufferPos ] = ( byte ) b ; count ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the entire contents of the specified input stream to this byte stream . Bytes from the input stream are read directly into the internal buffers of this streams . [CODESPLIT] public synchronized int write ( InputStream in ) throws IOException { int readCount = 0 ; int inBufferPos = count - filledBufferSum ; int n = in . read ( currentBuffer , inBufferPos , currentBuffer . length - inBufferPos ) ; while ( n != - 1 ) { readCount += n ; inBufferPos += n ; count += n ; if ( inBufferPos == currentBuffer . length ) { needNewBuffer ( currentBuffer . length ) ; inBufferPos = 0 ; } n = in . read ( currentBuffer , inBufferPos , currentBuffer . length - inBufferPos ) ; } return readCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the entire contents of this byte stream to the specified output stream . [CODESPLIT] public synchronized void writeTo ( OutputStream out ) throws IOException { int remaining = count ; for ( byte [ ] buf : buffers ) { int c = Math . min ( buf . length , remaining ) ; out . write ( buf , 0 , c ) ; remaining -= c ; if ( remaining == 0 ) { break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches entire contents of an <code > InputStream< / code > and represent same data as result InputStream . <p > This method is useful where <ul > <li > Source InputStream is slow . < / li > <li > It has network resources associated so we cannot keep it open for long time . < / li > <li > It has network timeout associated . < / li > < / ul > It can be used in favor of { @link #toByteArray () } since it avoids unnecessary allocation and copy of byte [] . <br > This method buffers the input internally so there is no need to use a <code > BufferedInputStream< / code > . [CODESPLIT] public static InputStream toBufferedInputStream ( InputStream input ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; output . write ( input ) ; return output . toBufferedInputStream ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current contents of this byte stream as a Input Stream . The returned stream is backed by buffers of <code > this< / code > stream avoiding memory allocation and copy thus saving space and time . <br > [CODESPLIT] private InputStream toBufferedInputStream ( ) { int remaining = count ; if ( remaining == 0 ) { return new ClosedInputStream ( ) ; } List < ByteArrayInputStream > list = new ArrayList < ByteArrayInputStream > ( buffers . size ( ) ) ; for ( byte [ ] buf : buffers ) { int c = Math . min ( buf . length , remaining ) ; list . add ( new ByteArrayInputStream ( buf , 0 , c ) ) ; remaining -= c ; if ( remaining == 0 ) { break ; } } return new SequenceInputStream ( Collections . enumeration ( list ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the curent contents of this byte stream as a byte array . The result is independent of this stream . [CODESPLIT] public synchronized byte [ ] toByteArray ( ) { int remaining = count ; if ( remaining == 0 ) { return EMPTY_BYTE_ARRAY ; } byte newbuf [ ] = new byte [ remaining ] ; int pos = 0 ; for ( byte [ ] buf : buffers ) { int c = Math . min ( buf . length , remaining ) ; System . arraycopy ( buf , 0 , newbuf , pos , c ) ; pos += c ; remaining -= c ; if ( remaining == 0 ) { break ; } } return newbuf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the text size . [CODESPLIT] @ Override public void setFontSize ( int size ) { if ( mFontSize != null ) { if ( size <= 0 ) { mFontSizeAdapter . updateSpinnerTitle ( \"\" ) ; mFontSizeAdapter . setSelectedItem ( 0 ) ; mFontSize . setSelection ( 0 ) ; } else { size = Helper . convertSpToPx ( size ) ; mFontSizeAdapter . updateSpinnerTitle ( Integer . toString ( size ) ) ; for ( int pos = 0 ; pos < mFontSizeAdapter . getCount ( ) ; pos ++ ) { FontSizeSpinnerItem item = mFontSizeAdapter . getItem ( pos ) ; if ( size == item . getFontSize ( ) ) { mFontSizeAdapter . setSelectedItem ( pos ) ; mFontSize . setSelection ( pos ) ; break ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes a path removing double and single dot path steps and removing any final directory separator . <p > This method normalizes a path to a standard format . The input may contain separators in either Unix or Windows format . The output will contain separators in the format specified . <p > A trailing slash will be removed . A double slash will be merged to a single slash ( but UNC names are handled ) . A single dot path segment will be removed . A double dot will cause that path segment and the one before to be removed . If the double dot has no parent path segment to work with { @code null } is returned . <p > The output will be the same on both Unix and Windows including the separator character . <pre > / foo // -- > / foo / foo / . / -- > / foo / foo / .. / bar -- > / bar / foo / .. / bar / -- > / bar / foo / .. / bar / .. / baz -- > / baz // foo // . / bar -- > / foo / bar / .. / -- > null .. / foo -- > null foo / bar / .. -- > foo foo / .. / .. / bar -- > null foo / .. / bar -- > bar // server / foo / .. / bar -- > // server / bar // server / .. / bar -- > null C : \\ foo \\ .. \\ bar -- > C : \\ bar C : \\ .. \\ bar -- > null ~ / foo / .. / bar / -- > ~ / bar ~ / .. / bar -- > null < / pre > [CODESPLIT] public static String normalizeNoEndSeparator ( String filename , boolean unixSeparator ) { char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR ; return doNormalize ( filename , separator , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal method to perform the normalization . [CODESPLIT] private static String doNormalize ( String filename , char separator , boolean keepSeparator ) { if ( filename == null ) { return null ; } int size = filename . length ( ) ; if ( size == 0 ) { return filename ; } int prefix = getPrefixLength ( filename ) ; if ( prefix < 0 ) { return null ; } char [ ] array = new char [ size + 2 ] ; // +1 for possible extra slash, +2 for arraycopy filename . getChars ( 0 , filename . length ( ) , array , 0 ) ; // fix separators throughout char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == otherSeparator ) { array [ i ] = separator ; } } // add extra separator on the end to simplify code below boolean lastIsDirectory = true ; if ( array [ size - 1 ] != separator ) { array [ size ++ ] = separator ; lastIsDirectory = false ; } // adjoining slashes for ( int i = prefix + 1 ; i < size ; i ++ ) { if ( array [ i ] == separator && array [ i - 1 ] == separator ) { System . arraycopy ( array , i , array , i - 1 , size - i ) ; size -- ; i -- ; } } // dot slash for ( int i = prefix + 1 ; i < size ; i ++ ) { if ( array [ i ] == separator && array [ i - 1 ] == ' ' && ( i == prefix + 1 || array [ i - 2 ] == separator ) ) { if ( i == size - 1 ) { lastIsDirectory = true ; } System . arraycopy ( array , i + 1 , array , i - 1 , size - i ) ; size -= 2 ; i -- ; } } // double dot slash outer : for ( int i = prefix + 2 ; i < size ; i ++ ) { if ( array [ i ] == separator && array [ i - 1 ] == ' ' && array [ i - 2 ] == ' ' && ( i == prefix + 2 || array [ i - 3 ] == separator ) ) { if ( i == prefix + 2 ) { return null ; } if ( i == size - 1 ) { lastIsDirectory = true ; } int j ; for ( j = i - 4 ; j >= prefix ; j -- ) { if ( array [ j ] == separator ) { // remove b/../ from a/b/../c System . arraycopy ( array , i + 1 , array , j + 1 , size - i ) ; size -= i - j ; i = j + 1 ; continue outer ; } } // remove a/../ from a/../c System . arraycopy ( array , i + 1 , array , prefix , size - i ) ; size -= i + 1 - prefix ; i = prefix + 1 ; } } if ( size <= 0 ) { // should never be less than 0 return \"\" ; } if ( size <= prefix ) { // should never be less than prefix return new String ( array , 0 , size ) ; } if ( lastIsDirectory && keepSeparator ) { return new String ( array , 0 , size ) ; // keep trailing separator } return new String ( array , 0 , size - 1 ) ; // lose trailing separator }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts all separators to the Unix separator of forward slash . [CODESPLIT] public static String separatorsToUnix ( String path ) { if ( path == null || path . indexOf ( WINDOWS_SEPARATOR ) == - 1 ) { return path ; } return path . replace ( WINDOWS_SEPARATOR , UNIX_SEPARATOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the index of the last extension separator character which is a dot . <p > This method also checks that there is no directory separator after the last dot . To do this it uses { @link #indexOfLastSeparator ( String ) } which will handle a file in either Unix or Windows format . <p > The output will be the same irrespective of the machine that the code is running on . [CODESPLIT] public static int indexOfExtension ( String filename ) { if ( filename == null ) { return - 1 ; } int extensionPos = filename . lastIndexOf ( EXTENSION_SEPARATOR ) ; int lastSeparator = indexOfLastSeparator ( filename ) ; return lastSeparator > extensionPos ? - 1 : extensionPos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an array of the markup objects attached to the specified slice of a Spannable and whose type is the specified type or a subclass of it ( see Spanned . getSpans ( int int Class<T > )) . [CODESPLIT] final protected RTSpan < V > [ ] getSpansAndroid ( Spannable str , int selStart , int selEnd ) { RTSpan < V > [ ] spans = str . getSpans ( selStart , selEnd , mSpanClazz ) ; return spans == null ? ( RTSpan < V > [ ] ) Array . newInstance ( mSpanClazz ) : spans ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hitting cropping rectangle . [CODESPLIT] private void recomputeFocus ( MotionEvent event ) { for ( int i = 0 ; i < mHighlightViews . size ( ) ; i ++ ) { HighlightView hv = mHighlightViews . get ( i ) ; hv . setFocus ( false ) ; hv . invalidate ( ) ; } for ( int i = 0 ; i < mHighlightViews . size ( ) ; i ++ ) { HighlightView hv = mHighlightViews . get ( i ) ; int edge = hv . getHit ( event . getX ( ) , event . getY ( ) ) ; if ( edge != HighlightView . GROW_NONE ) { if ( ! hv . hasFocus ( ) ) { hv . setFocus ( true ) ; hv . invalidate ( ) ; } break ; } } invalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pan the displayed image to make sure the cropping rectangle is visible . [CODESPLIT] private void ensureVisible ( HighlightView hv ) { Rect r = hv . mDrawRect ; int panDeltaX1 = Math . max ( 0 , mLeft - r . left ) ; int panDeltaX2 = Math . min ( 0 , mRight - r . right ) ; int panDeltaY1 = Math . max ( 0 , mTop - r . top ) ; int panDeltaY2 = Math . min ( 0 , mBottom - r . bottom ) ; int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2 ; int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2 ; if ( panDeltaX != 0 || panDeltaY != 0 ) { panBy ( panDeltaX , panDeltaY ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "view s center and scale according to the cropping rectangle . [CODESPLIT] private void centerBasedOnHighlightView ( HighlightView hv ) { Rect drawRect = hv . mDrawRect ; float width = drawRect . width ( ) ; float height = drawRect . height ( ) ; float thisWidth = getWidth ( ) ; float thisHeight = getHeight ( ) ; float z1 = thisWidth / width * .8F ; float z2 = thisHeight / height * .8F ; float zoom = Math . min ( z1 , z2 ) ; zoom = zoom * this . getScale ( ) ; zoom = Math . max ( 1F , zoom ) ; if ( ( Math . abs ( zoom - getScale ( ) ) / zoom ) > .1 ) { float [ ] coordinates = new float [ ] { hv . mCropRect . centerX ( ) , hv . mCropRect . centerY ( ) } ; getImageMatrix ( ) . mapPoints ( coordinates ) ; zoomTo ( zoom , coordinates [ 0 ] , coordinates [ 1 ] , 300F ) ; } ensureVisible ( hv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset document locator supplying systemid and publicid . [CODESPLIT] public void resetDocumentLocator ( String publicid , String systemid ) { thePublicid = publicid ; theSystemid = systemid ; theLastLine = theLastColumn = theCurrentLine = theCurrentColumn = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan HTML source reporting lexical events . [CODESPLIT] public void scan ( Reader r0 , ScanHandler h ) throws IOException , SAXException { theState = S_PCDATA ; PushbackReader r ; if ( r0 instanceof PushbackReader ) { r = ( PushbackReader ) r0 ; } else if ( r0 instanceof BufferedReader ) { r = new PushbackReader ( r0 ) ; } else { r = new PushbackReader ( new BufferedReader ( r0 , 200 ) ) ; } int firstChar = r . read ( ) ; // Remove any leading BOM if ( firstChar != ' ' ) unread ( r , firstChar ) ; while ( theState != S_DONE ) { int c1 = r . read ( ) ; char c = ( char ) c1 ; boolean is32BitChar = Character . isHighSurrogate ( c ) ; int c2 = is32BitChar ? r . read ( ) : - 1 ; String s = is32BitChar ? new StringBuffer ( ) . append ( c ) . append ( ( char ) c2 ) . toString ( ) : null ; // Process control characters if ( ! is32BitChar && c1 >= 0x80 && c1 <= 0x9F ) c1 = theWinMap [ c1 - 0x80 ] ; if ( ! is32BitChar && c1 == ' ' ) { c1 = r . read ( ) ; // expect LF next if ( c1 != ' ' ) { unread ( r , c1 ) ; // nope c1 = ' ' ; } } if ( ! is32BitChar && c1 == ' ' ) { theCurrentLine ++ ; theCurrentColumn = 0 ; } else { theCurrentColumn ++ ; } if ( ! ! is32BitChar && ! ( c1 >= 0x20 || c1 == ' ' || c1 == ' ' || c1 == - 1 ) ) continue ; // Search state table int action = 0 ; for ( int i = 0 ; i < statetable . length ; i += 4 ) { if ( theState != statetable [ i ] ) { if ( action != 0 ) break ; continue ; } if ( statetable [ i + 1 ] == 0 ) { action = statetable [ i + 2 ] ; theNextState = statetable [ i + 3 ] ; } else if ( ! is32BitChar && statetable [ i + 1 ] == c1 ) { action = statetable [ i + 2 ] ; theNextState = statetable [ i + 3 ] ; break ; } } switch ( action ) { case 0 : throw new Error ( \"HTMLScanner can't cope with \" + Integer . toString ( c1 ) + \" in state \" + Integer . toString ( theState ) ) ; case A_ADUP : h . adup ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_ADUP_SAVE : h . adup ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; if ( s != null ) save ( s , c1 , h ) ; break ; case A_ADUP_STAGC : h . adup ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_ANAME : h . aname ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_ANAME_ADUP : h . aname ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . adup ( theOutputBuffer , 0 , theSize ) ; break ; case A_ANAME_ADUP_STAGC : h . aname ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . adup ( theOutputBuffer , 0 , theSize ) ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_AVAL : h . aval ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_AVAL_STAGC : h . aval ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_CDATA : mark ( ) ; // suppress the final \"]]\" in the buffer if ( theSize > 1 ) theSize -= 2 ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_ENTITY_START : h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; save ( s , c1 , h ) ; break ; case A_ENTITY : mark ( ) ; if ( theState == S_ENT && c == ' ' ) { theNextState = S_NCR ; save ( s , c1 , h ) ; break ; } else if ( theState == S_NCR && ( c == ' ' || c == ' ' ) ) { theNextState = S_XNCR ; save ( s , c1 , h ) ; break ; } else if ( theState == S_ENT && Character . isLetterOrDigit ( c ) ) { save ( s , c1 , h ) ; break ; } else if ( theState == S_NCR && Character . isDigit ( c ) ) { save ( s , c1 , h ) ; break ; } else if ( theState == S_XNCR && ( Character . isDigit ( c ) || \"abcdefABCDEF\" . indexOf ( c ) != - 1 ) ) { save ( s , c1 , h ) ; break ; } // The whole entity reference has been collected h . entity ( theOutputBuffer , 1 , theSize - 1 ) ; int ent = h . getEntity ( ) ; if ( ent != 0 ) { theSize = 0 ; if ( ent >= 0x80 && ent <= 0x9F ) { ent = theWinMap [ ent - 0x80 ] ; } if ( ent < 0x20 ) { // Control becomes space ent = 0x20 ; } else if ( ent >= 0xD800 && ent <= 0xDFFF ) { // Surrogates get dropped ent = 0 ; } else if ( ent <= 0xFFFF ) { // BMP character save ( ent , h ) ; } else { // Astral converted to two surrogates ent -= 0x10000 ; save ( ( ent >> 10 ) + 0xD800 , h ) ; save ( ( ent & 0x3FF ) + 0xDC00 , h ) ; } if ( is32BitChar || c1 != ' ' ) { if ( is32BitChar ) { unread ( r , c2 ) ; theCurrentColumn -- ; } unread ( r , c1 ) ; theCurrentColumn -- ; } } else { if ( is32BitChar ) { unread ( r , c2 ) ; theCurrentColumn -- ; } unread ( r , c1 ) ; theCurrentColumn -- ; } theNextState = S_PCDATA ; break ; case A_ETAG : h . etag ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_DECL : h . decl ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_GI : h . gi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_GI_STAGC : h . gi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stagc ( theOutputBuffer , 0 , theSize ) ; break ; case A_LT : mark ( ) ; save ( ' ' , h ) ; save ( s , c1 , h ) ; break ; case A_LT_PCDATA : mark ( ) ; save ( ' ' , h ) ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_PCDATA : mark ( ) ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_CMNT : mark ( ) ; h . cmnt ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_MINUS3 : save ( ' ' , h ) ; save ( ' ' , h ) ; break ; case A_MINUS2 : save ( ' ' , h ) ; save ( ' ' , h ) ; // fall through into A_MINUS case A_MINUS : save ( ' ' , h ) ; save ( s , c1 , h ) ; break ; case A_PI : mark ( ) ; h . pi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_PITARGET : h . pitarget ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_PITARGET_PI : h . pitarget ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . pi ( theOutputBuffer , 0 , theSize ) ; break ; case A_SAVE : save ( s , c1 , h ) ; break ; case A_SKIP : break ; case A_SP : save ( ' ' , h ) ; break ; case A_STAGC : h . stagc ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; case A_EMPTYTAG : mark ( ) ; if ( theSize > 0 ) h . gi ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; h . stage ( theOutputBuffer , 0 , theSize ) ; break ; case A_UNGET : unread ( r , c1 ) ; theCurrentColumn -- ; break ; case A_UNSAVE_PCDATA : if ( theSize > 0 ) theSize -- ; h . pcdata ( theOutputBuffer , 0 , theSize ) ; theSize = 0 ; break ; default : throw new Error ( \"Can't process state \" + action ) ; } theState = theNextState ; } h . eof ( theOutputBuffer , 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate a value against the set of regular expressions returning a String value of the aggregated groups . [CODESPLIT] public String validate ( String value ) { if ( value == null ) { return null ; } for ( int i = 0 ; i < patterns . length ; i ++ ) { Matcher matcher = patterns [ i ] . matcher ( value ) ; if ( matcher . matches ( ) ) { int count = matcher . groupCount ( ) ; if ( count == 1 ) { return matcher . group ( 1 ) ; } StringBuffer buffer = new StringBuffer ( ) ; for ( int j = 0 ; j < count ; j ++ ) { String component = matcher . group ( j + 1 ) ; if ( component != null ) { buffer . append ( component ) ; } } return buffer . toString ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The paragraph is selected by the Selection if : <p > - they have at least one character in common - the selection is a point within the paragraph ( 01 \\ n - > 0 till 2 intersects while the span is [ 0 3 ] ) - the selection is a point within or at the end of the LAST paragraph ( 01 - > 0 till 2 intersects while the span is [ 0 2 ] ) e . g . [ 10 10 ] will intersect the paragraph [ 0 10 ] only if it s the last paragraph [CODESPLIT] public boolean isSelected ( Selection sel ) { if ( sel == null ) { return false ; } if ( sel . isEmpty ( ) ) { // selection is a point boolean isCompletelyWithin = sel . start ( ) >= start ( ) && sel . end ( ) < end ( ) ; // selection is completely within paragraph (not at the end) boolean isWithin = sel . start ( ) >= start ( ) && sel . end ( ) <= end ( ) ; // selection is within or at the end of the paragraph return isCompletelyWithin || ( isWithin && mIsLast ) ; } else { // selection is a range --> at least one character in common int start = Math . max ( start ( ) , sel . start ( ) ) ; int end = Math . min ( end ( ) , sel . end ( ) ) ; return start < end ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates whether the <code > Reader< / code > has more lines . If there is an <code > IOException< / code > then { @link #close () } will be called on this instance . [CODESPLIT] public boolean hasNext ( ) { if ( cachedLine != null ) { return true ; } else if ( finished ) { return false ; } else { try { while ( true ) { String line = bufferedReader . readLine ( ) ; if ( line == null ) { finished = true ; return false ; } else if ( isValidLine ( line ) ) { cachedLine = line ; return true ; } } } catch ( IOException ioe ) { close ( ) ; throw new IllegalStateException ( ioe ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next line in the wrapped <code > Reader< / code > . [CODESPLIT] public String nextLine ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( \"No more lines\" ) ; } String currentLine = cachedLine ; cachedLine = null ; return currentLine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add or replace an element type for this schema . [CODESPLIT] @ SuppressLint ( \"DefaultLocale\" ) public void elementType ( String name , int model , int memberOf , int flags ) { ElementType e = new ElementType ( name , model , memberOf , flags , this ) ; theElementTypes . put ( name . toLowerCase ( ) , e ) ; if ( memberOf == M_ROOT ) theRoot = e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add or replace a default attribute for an element type in this schema . [CODESPLIT] public void attribute ( String elemName , String attrName , String type , String value ) { ElementType e = getElementType ( elemName ) ; if ( e == null ) { throw new Error ( \"Attribute \" + attrName + \" specified for unknown element type \" + elemName ) ; } e . setAttribute ( attrName , type , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify natural parent of an element in this schema . [CODESPLIT] public void parent ( String name , String parentName ) { ElementType child = getElementType ( name ) ; ElementType parent = getElementType ( parentName ) ; if ( child == null ) { throw new Error ( \"No child \" + name + \" for parent \" + parentName ) ; } if ( parent == null ) { throw new Error ( \"No parent \" + parentName + \" for child \" + name ) ; } child . setParent ( parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an ElementType by name . [CODESPLIT] @ SuppressLint ( \"DefaultLocale\" ) public ElementType getElementType ( String name ) { return ( ElementType ) ( theElementTypes . get ( name . toLowerCase ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an entity value by name . [CODESPLIT] public int getEntity ( String name ) { // System.err.println(\"%% Looking up entity \" + name); Integer ch = ( Integer ) theEntities . get ( name ) ; if ( ch == null ) return 0 ; return ch . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : on Android M we need to ask the WRITE_EXTERNAL_STORAGE permission explicitly [CODESPLIT] private boolean takePicture ( ) { try { // Create an image file name (must be in \"public area\" or the camera app might not be able to access the file) File imagePath = Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) ; File imageFile = MediaUtils . createUniqueFile ( imagePath , CAPTURED_IMAGE_TEMPLATE , false ) ; imagePath . mkdirs ( ) ; if ( imagePath . exists ( ) && imageFile . createNewFile ( ) ) { setOriginalFile ( imageFile . getAbsolutePath ( ) ) ; Uri uriForCamera ; if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . LOLLIPOP ) { // There are compatibility issues with FileProvider Uris on lower versions uriForCamera = Uri . fromFile ( imageFile ) ; } else { uriForCamera = FileProvider . getUriForFile ( mActivity , \"com.onegravity.rteditor.fileprovider\" , imageFile ) ; } Intent intent = new Intent ( MediaStore . ACTION_IMAGE_CAPTURE ) . putExtra ( MediaStore . EXTRA_OUTPUT , uriForCamera ) ; startActivity ( intent ) ; } else { Toast . makeText ( mActivity , \"Can't take picture without an sdcard\" , Toast . LENGTH_SHORT ) . show ( ) ; return false ; } } catch ( Exception e ) { Log . e ( getClass ( ) . getSimpleName ( ) , e . getMessage ( ) , e ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the authority is properly formatted . An authority is the combination of hostname and port . A <code > null< / code > authority value is considered invalid . Note : this implementation validates the domain unless a RegexValidator was provided . If a RegexValidator was supplied and it matches then the authority is regarded as valid with no further checks otherwise the method checks against the AUTHORITY_PATTERN and the DomainValidator ( ALLOW_LOCAL_URLS ) [CODESPLIT] protected boolean isValidAuthority ( String authority ) { if ( authority == null ) { return false ; } // check manual authority validation if specified if ( authorityValidator != null && authorityValidator . isValid ( authority ) ) { return true ; } // convert to ASCII if possible final String authorityASCII = DomainValidator . unicodeToASCII ( authority ) ; Matcher authorityMatcher = AUTHORITY_PATTERN . matcher ( authorityASCII ) ; if ( ! authorityMatcher . matches ( ) ) { return false ; } String hostLocation = authorityMatcher . group ( PARSE_AUTHORITY_HOST_IP ) ; // check if authority is hostname or IP address: // try a hostname first since that's much more likely DomainValidator domainValidator = DomainValidator . getInstance ( isOn ( ALLOW_LOCAL_URLS ) ) ; if ( ! domainValidator . isValid ( hostLocation ) ) { // try an IP address InetAddressValidator inetAddressValidator = InetAddressValidator . getInstance ( ) ; if ( ! inetAddressValidator . isValid ( hostLocation ) ) { // isn't either one, so the URL is invalid return false ; } } String port = authorityMatcher . group ( PARSE_AUTHORITY_PORT ) ; if ( port != null && ! PORT_PATTERN . matcher ( port ) . matches ( ) ) { return false ; } String extra = authorityMatcher . group ( PARSE_AUTHORITY_EXTRA ) ; if ( extra != null && extra . trim ( ) . length ( ) > 0 ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the path is valid . A <code > null< / code > value is considered invalid . [CODESPLIT] protected boolean isValidPath ( String path ) { if ( path == null ) { return false ; } if ( ! PATH_PATTERN . matcher ( path ) . matches ( ) ) { return false ; } int slash2Count = countToken ( \"//\" , path ) ; if ( isOff ( ALLOW_2_SLASHES ) && ( slash2Count > 0 ) ) { return false ; } int slashCount = countToken ( \"/\" , path ) ; int dot2Count = countToken ( \"..\" , path ) ; if ( dot2Count > 0 && ( slashCount - slash2Count - 1 ) <= dot2Count ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This important method makes sure that all paragraph effects are applied to whole paragraphs . While it s optimized for performance it s still an expensive operation so it shouldn t be called too often . [CODESPLIT] public static void cleanupParagraphs ( RTEditText editor , Effect ... exclude ) { cleanupParagraphs ( editor , Effects . ALIGNMENT , exclude ) ; cleanupParagraphs ( editor , Effects . INDENTATION , exclude ) ; cleanupParagraphs ( editor , Effects . BULLET , exclude ) ; cleanupParagraphs ( editor , Effects . NUMBER , exclude ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute file path for a certain RTMediaType . <p > The media type specific path as provided by RTMediaType is appended to the storage path ( e . g . <storage area > / images for image files ) . [CODESPLIT] protected String getAbsolutePath ( RTMediaType mediaType ) { File mediaPath = new File ( mStoragePath . getAbsolutePath ( ) , mediaType . mediaPath ( ) ) ; if ( ! mediaPath . exists ( ) ) { mediaPath . mkdirs ( ) ; } return mediaPath . getAbsolutePath ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Use case 1 : Inserting media objects into the rich text editor . [CODESPLIT] @ Override /* @inheritDoc */ public RTImage createImage ( RTMediaSource mediaSource ) { File targetFile = loadMedia ( mediaSource ) ; return targetFile == null ? null : new RTImageImpl ( targetFile . getAbsolutePath ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply this effect to the selection . If value is Null then the effect will be removed from the current selection . [CODESPLIT] public void applyToSelection ( RTEditText editor , V value ) { Selection selection = getSelection ( editor ) ; // SPAN_INCLUSIVE_INCLUSIVE is default for empty spans int flags = selection . isEmpty ( ) ? Spanned . SPAN_INCLUSIVE_INCLUSIVE : Spanned . SPAN_EXCLUSIVE_INCLUSIVE ; Spannable str = editor . getText ( ) ; for ( RTSpan < V > span : getSpans ( str , selection , SpanCollectMode . SPAN_FLAGS ) ) { boolean sameSpan = span . getValue ( ) . equals ( value ) ; int spanStart = str . getSpanStart ( span ) ; if ( spanStart < selection . start ( ) ) { // process preceding spans if ( sameSpan ) { // we have a preceding span --> use SPAN_EXCLUSIVE_INCLUSIVE instead of SPAN_INCLUSIVE_INCLUSIVE flags = Spanned . SPAN_EXCLUSIVE_INCLUSIVE ; selection . offset ( selection . start ( ) - spanStart , 0 ) ; } else { str . setSpan ( newSpan ( span . getValue ( ) ) , spanStart , selection . start ( ) , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } } int spanEnd = str . getSpanEnd ( span ) ; if ( spanEnd > selection . end ( ) ) { // process succeeding spans if ( sameSpan ) { selection . offset ( 0 , spanEnd - selection . end ( ) ) ; } else { str . setSpan ( newSpan ( span . getValue ( ) ) , selection . end ( ) , spanEnd , Spanned . SPAN_EXCLUSIVE_INCLUSIVE ) ; } } str . removeSpan ( span ) ; } if ( value != null ) { RTSpan < V > newSpan = newSpan ( value ) ; if ( newSpan != null ) { str . setSpan ( newSpan , selection . start ( ) , selection . end ( ) , flags ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Checks if a field has a valid e - mail address . < / p > [CODESPLIT] public boolean isValid ( String email ) { if ( email == null ) { return false ; } if ( email . endsWith ( \".\" ) ) { // check this first - it's cheap! return false ; } // Check the whole email address structure Matcher emailMatcher = EMAIL_PATTERN . matcher ( email ) ; if ( ! emailMatcher . matches ( ) ) { return false ; } if ( ! isValidUser ( emailMatcher . group ( 1 ) ) ) { return false ; } if ( ! isValidDomain ( emailMatcher . group ( 2 ) ) ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the domain component of an email address is valid . [CODESPLIT] protected boolean isValidDomain ( String domain ) { // see if domain is an IP address in brackets Matcher ipDomainMatcher = IP_DOMAIN_PATTERN . matcher ( domain ) ; if ( ipDomainMatcher . matches ( ) ) { InetAddressValidator inetAddressValidator = InetAddressValidator . getInstance ( ) ; return inetAddressValidator . isValid ( ipDomainMatcher . group ( 1 ) ) ; } // Domain is symbolic name DomainValidator domainValidator = DomainValidator . getInstance ( allowLocal ) ; return domainValidator . isValid ( domain ) || domainValidator . isValidTld ( domain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO finding links doesn t work with right alignment and potentially other formatting options [CODESPLIT] private int getCharIndexAt ( TextView textView , MotionEvent event ) { // get coordinates int x = ( int ) event . getX ( ) ; int y = ( int ) event . getY ( ) ; x -= textView . getTotalPaddingLeft ( ) ; y -= textView . getTotalPaddingTop ( ) ; x += textView . getScrollX ( ) ; y += textView . getScrollY ( ) ; /*\n         * Fail-fast check of the line bound.\n         * If we're not within the line bound no character was touched\n         */ Layout layout = textView . getLayout ( ) ; int line = layout . getLineForVertical ( y ) ; synchronized ( sLineBounds ) { layout . getLineBounds ( line , sLineBounds ) ; if ( ! sLineBounds . contains ( x , y ) ) { return - 1 ; } } // retrieve line text Spanned text = ( Spanned ) textView . getText ( ) ; int lineStart = layout . getLineStart ( line ) ; int lineEnd = layout . getLineEnd ( line ) ; int lineLength = lineEnd - lineStart ; if ( lineLength == 0 ) { return - 1 ; } Spanned lineText = ( Spanned ) text . subSequence ( lineStart , lineEnd ) ; // compute leading margin and subtract it from the x coordinate int margin = 0 ; LeadingMarginSpan [ ] marginSpans = lineText . getSpans ( 0 , lineLength , LeadingMarginSpan . class ) ; if ( marginSpans != null ) { for ( LeadingMarginSpan span : marginSpans ) { margin += span . getLeadingMargin ( true ) ; } } x -= margin ; // retrieve text widths float [ ] widths = new float [ lineLength ] ; TextPaint paint = textView . getPaint ( ) ; paint . getTextWidths ( lineText , 0 , lineLength , widths ) ; // scale text widths by relative font size (absolute size / default size) final float defaultSize = textView . getTextSize ( ) ; float scaleFactor = 1f ; AbsoluteSizeSpan [ ] absSpans = lineText . getSpans ( 0 , lineLength , AbsoluteSizeSpan . class ) ; if ( absSpans != null ) { for ( AbsoluteSizeSpan span : absSpans ) { int spanStart = lineText . getSpanStart ( span ) ; int spanEnd = lineText . getSpanEnd ( span ) ; scaleFactor = span . getSize ( ) / defaultSize ; int start = Math . max ( lineStart , spanStart ) ; int end = Math . min ( lineEnd , spanEnd ) ; for ( int i = start ; i < end ; i ++ ) { widths [ i ] *= scaleFactor ; } } } // find index of touched character float startChar = 0 ; float endChar = 0 ; for ( int i = 0 ; i < lineLength ; i ++ ) { startChar = endChar ; endChar += widths [ i ] ; if ( endChar >= x ) { // which \"end\" is closer to x, the start or the end of the character? int index = lineStart + ( x - startChar < endChar - x ? i : i + 1 ) ; //Logger.e(Logger.LOG_TAG, \"Found character: \" + (text.length()>index ? text.charAt(index) : \"\")); return index ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call this when an operation is performed to add it to the undo stack . [CODESPLIT] synchronized void executed ( RTEditText editor , Operation op ) { Stack < Operation > undoStack = getUndoStack ( editor ) ; Stack < Operation > redoStack = getRedoStack ( editor ) ; // if operations are executed in a quick succession we \"merge\" them to have but one // -> saves memory and makes more sense from a user perspective (each key stroke an undo? -> no way) while ( ! undoStack . empty ( ) && op . canMerge ( undoStack . peek ( ) ) ) { Operation previousOp = undoStack . pop ( ) ; op . merge ( previousOp ) ; } push ( op , undoStack ) ; redoStack . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - do the last undone operation for a specific rich text editor [CODESPLIT] synchronized void redo ( RTEditText editor ) { Stack < Operation > redoStack = getRedoStack ( editor ) ; if ( ! redoStack . empty ( ) ) { Stack < Operation > undoStack = getUndoStack ( editor ) ; Operation op = redoStack . pop ( ) ; push ( op , undoStack ) ; op . redo ( editor ) ; while ( ! redoStack . empty ( ) && op . canMerge ( redoStack . peek ( ) ) ) { op = redoStack . pop ( ) ; push ( op , undoStack ) ; op . redo ( editor ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flush all operations for a specific rich text editor ( method unused at the moment ) [CODESPLIT] synchronized void flushOperations ( RTEditText editor ) { Stack < Operation > undoStack = getUndoStack ( editor ) ; Stack < Operation > redoStack = getRedoStack ( editor ) ; undoStack . clear ( ) ; redoStack . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Private Methods ******************************************* [CODESPLIT] private void push ( Operation op , Stack < Operation > stack ) { if ( stack . size ( ) >= MAX_NR_OF_OPERATIONS ) { stack . remove ( 0 ) ; } stack . push ( op ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A memory optimized algorithm for String . replaceAll [CODESPLIT] private static String replaceAll ( String source , String search , String replace ) { if ( USE_REPLACE_ALL ) { return source . replaceAll ( search , replace ) ; } else { Pattern p = Pattern . compile ( search ) ; Matcher m = p . matcher ( source ) ; StringBuffer sb = new StringBuffer ( ) ; boolean atLeastOneFound = false ; while ( m . find ( ) ) { m . appendReplacement ( sb , replace ) ; atLeastOneFound = true ; } if ( atLeastOneFound ) { m . appendTail ( sb ) ; return sb . toString ( ) ; } else { return source ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get thread status and create one if specified . [CODESPLIT] private synchronized ThreadStatus getOrCreateThreadStatus ( Thread t ) { ThreadStatus status = mThreadStatus . get ( t ) ; if ( status == null ) { status = new ThreadStatus ( ) ; mThreadStatus . put ( t , status ) ; } return status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The following three methods are used to keep track of BitmapFaction . Options used for decoding and cancelling . [CODESPLIT] private synchronized void setDecodingOptions ( Thread t , BitmapFactory . Options options ) { getOrCreateThreadStatus ( t ) . mOptions = options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The following three methods are used to keep track of which thread is being disabled for bitmap decoding . [CODESPLIT] public synchronized boolean canThreadDecoding ( Thread t ) { ThreadStatus status = mThreadStatus . get ( t ) ; if ( status == null ) { // allow decoding by default return true ; } return ( status . mState != State . CANCEL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The real place to delegate bitmap decoding to BitmapFactory . [CODESPLIT] public Bitmap decodeFileDescriptor ( FileDescriptor fd , BitmapFactory . Options options ) { if ( options . mCancel ) { return null ; } Thread thread = Thread . currentThread ( ) ; if ( ! canThreadDecoding ( thread ) ) { return null ; } setDecodingOptions ( thread , options ) ; Bitmap b = BitmapFactory . decodeFileDescriptor ( fd , null , options ) ; removeDecodingOptions ( thread ) ; return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this method to preload fonts asynchronously e . g . when the app starts up . [CODESPLIT] public static void preLoadFonts ( final Context context ) { new Thread ( ( ) -> { synchronized ( ASSET_FONTS_BY_NAME ) { getAssetFonts ( context ) ; } synchronized ( SYSTEM_FONTS_BY_NAME ) { getSystemFonts ( ) ; } } ) . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the fonts from the asset and the system folder . [CODESPLIT] public static SortedSet < RTTypeface > getFonts ( Context context ) { /*\n         * Fonts from the assets folder\n         */ Map < String , String > assetFonts = getAssetFonts ( context ) ; AssetManager assets = context . getResources ( ) . getAssets ( ) ; for ( String fontName : assetFonts . keySet ( ) ) { String filePath = assetFonts . get ( fontName ) ; if ( ! ALL_FONTS . contains ( fontName ) ) { try { Typeface typeface = Typeface . createFromAsset ( assets , filePath ) ; ALL_FONTS . add ( new RTTypeface ( fontName , typeface ) ) ; } catch ( Exception e ) { // this can happen if we don't have access to the font or it's not a font or... } } } /*\n         * Fonts from the system\n         */ Map < String , String > systemFonts = getSystemFonts ( ) ; for ( String fontName : systemFonts . keySet ( ) ) { String filePath = systemFonts . get ( fontName ) ; if ( ! ALL_FONTS . contains ( fontName ) ) { try { Typeface typeface = Typeface . createFromFile ( filePath ) ; ALL_FONTS . add ( new RTTypeface ( fontName , typeface ) ) ; } catch ( Exception e ) { // this can happen if we don't have access to the font or it's not a font or... } } } return ALL_FONTS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the fonts from the asset folder . [CODESPLIT] private static Map < String , String > getAssetFonts ( Context context ) { synchronized ( ASSET_FONTS_BY_NAME ) { /*\n             * Let's do this only once because it's expensive and the result won't change in any case.\n             */ if ( ASSET_FONTS_BY_NAME . isEmpty ( ) ) { AssetManager assets = context . getResources ( ) . getAssets ( ) ; Collection < String > fontFiles = AssetIndex . getAssetIndex ( context ) ; if ( fontFiles == null || fontFiles . isEmpty ( ) ) { fontFiles = listFontFiles ( context . getResources ( ) ) ; } for ( String filePath : fontFiles ) { if ( filePath . toLowerCase ( Locale . getDefault ( ) ) . endsWith ( \"ttf\" ) ) { String fontName = TTFAnalyzer . getFontName ( assets , filePath ) ; if ( fontName == null ) { fontName = getFileName ( filePath ) ; } ASSET_FONTS_BY_NAME . put ( fontName , filePath ) ; } } } return ASSET_FONTS_BY_NAME ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the fonts from the system folders . [CODESPLIT] private static Map < String , String > getSystemFonts ( ) { synchronized ( SYSTEM_FONTS_BY_NAME ) { for ( String fontDir : FONT_DIRS ) { File dir = new File ( fontDir ) ; if ( ! dir . exists ( ) ) continue ; File [ ] files = dir . listFiles ( ) ; if ( files == null ) continue ; for ( File file : files ) { String filePath = file . getAbsolutePath ( ) ; if ( ! SYSTEM_FONTS_BY_PATH . containsKey ( filePath ) ) { String fontName = TTFAnalyzer . getFontName ( file . getAbsolutePath ( ) ) ; if ( fontName == null ) { fontName = getFileName ( filePath ) ; } SYSTEM_FONTS_BY_PATH . put ( filePath , fontName ) ; SYSTEM_FONTS_BY_NAME . put ( fontName , filePath ) ; } } } return SYSTEM_FONTS_BY_NAME ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get contents of an <code > InputStream< / code > as a <code > byte [] < / code > . Use this method instead of <code > toByteArray ( InputStream ) < / code > when <code > InputStream< / code > size is known . <b > NOTE : < / b > the method checks that the length can safely be cast to an int without truncation before using { @link IOUtils#toByteArray ( java . io . InputStream int ) } to read into the byte array . ( Arrays can have no more than Integer . MAX_VALUE entries anyway ) [CODESPLIT] public static byte [ ] toByteArray ( InputStream input , long size ) throws IOException { if ( size > Integer . MAX_VALUE ) { throw new IllegalArgumentException ( \"Size cannot be greater than Integer max value: \" + size ) ; } return toByteArray ( input , ( int ) size ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of an <code > InputStream< / code > as a <code > byte [] < / code > . Use this method instead of <code > toByteArray ( InputStream ) < / code > when <code > InputStream< / code > size is known [CODESPLIT] public static byte [ ] toByteArray ( InputStream input , int size ) throws IOException { if ( size < 0 ) { throw new IllegalArgumentException ( \"Size must be equal or greater than zero: \" + size ) ; } if ( size == 0 ) { return new byte [ 0 ] ; } byte [ ] data = new byte [ size ] ; int offset = 0 ; int readed ; while ( offset < size && ( readed = input . read ( data , offset , size - offset ) ) != EOF ) { offset += readed ; } if ( offset != size ) { throw new IOException ( \"Unexpected readed size. current: \" + offset + \", excepted: \" + size ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of a <code > Reader< / code > as a <code > byte [] < / code > using the specified character encoding . <p / > This method buffers the input internally so there is no need to use a <code > BufferedReader< / code > . [CODESPLIT] public static byte [ ] toByteArray ( Reader input , Charset encoding ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; copy ( input , output , encoding ) ; return output . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of a <code > Reader< / code > as a <code > byte [] < / code > using the specified character encoding . <p / > Character encoding names can be found at <a href = http : // www . iana . org / assignments / character - sets > IANA< / a > . <p / > This method buffers the input internally so there is no need to use a <code > BufferedReader< / code > . [CODESPLIT] public static byte [ ] toByteArray ( Reader input , String encoding ) throws IOException { return toByteArray ( input , Charsets . toCharset ( encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of a <code > URL< / code > as a <code > byte [] < / code > . [CODESPLIT] public static byte [ ] toByteArray ( URL url ) throws IOException { URLConnection conn = url . openConnection ( ) ; try { return IOUtils . toByteArray ( conn ) ; } finally { close ( conn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of a <code > URLConnection< / code > as a <code > byte [] < / code > . [CODESPLIT] public static byte [ ] toByteArray ( URLConnection urlConn ) throws IOException { InputStream inputStream = urlConn . getInputStream ( ) ; try { return IOUtils . toByteArray ( inputStream ) ; } finally { inputStream . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of an <code > InputStream< / code > as a character array using the specified character encoding . <p / > This method buffers the input internally so there is no need to use a <code > BufferedInputStream< / code > . [CODESPLIT] public static char [ ] toCharArray ( InputStream is , Charset encoding ) throws IOException { CharArrayWriter output = new CharArrayWriter ( ) ; copy ( is , output , encoding ) ; return output . toCharArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of an <code > InputStream< / code > as a character array using the specified character encoding . <p / > Character encoding names can be found at <a href = http : // www . iana . org / assignments / character - sets > IANA< / a > . <p / > This method buffers the input internally so there is no need to use a <code > BufferedInputStream< / code > . [CODESPLIT] public static char [ ] toCharArray ( InputStream is , String encoding ) throws IOException { return toCharArray ( is , Charsets . toCharset ( encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of a <code > Reader< / code > as a character array . <p / > This method buffers the input internally so there is no need to use a <code > BufferedReader< / code > . [CODESPLIT] public static char [ ] toCharArray ( Reader input ) throws IOException { CharArrayWriter sw = new CharArrayWriter ( ) ; copy ( input , sw ) ; return sw . toCharArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of an <code > InputStream< / code > as a list of Strings one entry per line using the specified character encoding . <p / > This method buffers the input internally so there is no need to use a <code > BufferedInputStream< / code > . [CODESPLIT] public static List < String > readLines ( InputStream input , Charset encoding ) throws IOException { InputStreamReader reader = new InputStreamReader ( input , Charsets . toCharset ( encoding ) ) ; return readLines ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the contents of an <code > InputStream< / code > as a list of Strings one entry per line using the specified character encoding . <p / > Character encoding names can be found at <a href = http : // www . iana . org / assignments / character - sets > IANA< / a > . <p / > This method buffers the input internally so there is no need to use a <code > BufferedInputStream< / code > . [CODESPLIT] public static List < String > readLines ( InputStream input , String encoding ) throws IOException { return readLines ( input , Charsets . toCharset ( encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an Iterator for the lines in an <code > InputStream< / code > using the character encoding specified ( or default encoding if null ) . <p / > <code > LineIterator< / code > holds a reference to the open <code > InputStream< / code > specified here . When you have finished with the iterator you should close the stream to free internal resources . This can be done by closing the stream directly or by calling <p / > The recommended usage pattern is : <pre > try { LineIterator it = IOUtils . lineIterator ( stream charset ) ; while ( it . hasNext () ) { String line = it . nextLine () ; /// do something with line } } finally { IOUtils . closeQuietly ( stream ) ; } < / pre > [CODESPLIT] public static LineIterator lineIterator ( InputStream input , Charset encoding ) throws IOException { return new LineIterator ( new InputStreamReader ( input , Charsets . toCharset ( encoding ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an Iterator for the lines in an <code > InputStream< / code > using the character encoding specified ( or default encoding if null ) . <p / > <code > LineIterator< / code > holds a reference to the open <code > InputStream< / code > specified here . When you have finished with the iterator you should close the stream to free internal resources . This can be done by closing the stream directly or by calling { @link LineIterator#close () } or { @link LineIterator#closeQuietly ( LineIterator ) } . <p / > The recommended usage pattern is : <pre > try { LineIterator it = IOUtils . lineIterator ( stream UTF - 8 ) ; while ( it . hasNext () ) { String line = it . nextLine () ; /// do something with line } } finally { IOUtils . closeQuietly ( stream ) ; } < / pre > [CODESPLIT] public static LineIterator lineIterator ( InputStream input , String encoding ) throws IOException { return lineIterator ( input , Charsets . toCharset ( encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes bytes from a <code > byte [] < / code > to chars on a <code > Writer< / code > using the default character encoding of the platform . <p / > This method uses { @link String#String ( byte [] ) } . [CODESPLIT] public static void write ( byte [ ] data , Writer output ) throws IOException { write ( data , output , Charset . defaultCharset ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes bytes from a <code > byte [] < / code > to chars on a <code > Writer< / code > using the specified character encoding . <p / > This method uses { @link String#String ( byte [] String ) } . [CODESPLIT] public static void write ( byte [ ] data , Writer output , Charset encoding ) throws IOException { if ( data != null ) { output . write ( new String ( data , Charsets . toCharset ( encoding ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes chars from a <code > char [] < / code > to bytes on an <code > OutputStream< / code > using the specified character encoding . <p / > This method uses { @link String#String ( char [] ) } and { @link String#getBytes ( String ) } . [CODESPLIT] public static void write ( char [ ] data , OutputStream output , Charset encoding ) throws IOException { if ( data != null ) { output . write ( new String ( data ) . getBytes ( Charsets . toCharset ( encoding ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes chars from a <code > CharSequence< / code > to bytes on an <code > OutputStream< / code > using the default character encoding of the platform . <p / > This method uses { @link String#getBytes () } . [CODESPLIT] public static void write ( CharSequence data , OutputStream output ) throws IOException { write ( data , output , Charset . defaultCharset ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes chars from a <code > CharSequence< / code > to bytes on an <code > OutputStream< / code > using the specified character encoding . <p / > This method uses { @link String#getBytes ( String ) } . [CODESPLIT] public static void write ( CharSequence data , OutputStream output , Charset encoding ) throws IOException { if ( data != null ) { write ( data . toString ( ) , output , encoding ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes chars from a <code > StringBuffer< / code > to a <code > Writer< / code > . [CODESPLIT] @ Deprecated public static void write ( StringBuffer data , Writer output ) throws IOException { if ( data != null ) { output . write ( data . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes chars from a <code > StringBuffer< / code > to bytes on an <code > OutputStream< / code > using the default character encoding of the platform . <p / > This method uses { @link String#getBytes () } . [CODESPLIT] @ Deprecated public static void write ( StringBuffer data , OutputStream output ) throws IOException { write ( data , output , ( String ) null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes chars from a <code > StringBuffer< / code > to bytes on an <code > OutputStream< / code > using the specified character encoding . <p / > Character encoding names can be found at <a href = http : // www . iana . org / assignments / character - sets > IANA< / a > . <p / > This method uses { @link String#getBytes ( String ) } . [CODESPLIT] @ Deprecated public static void write ( StringBuffer data , OutputStream output , String encoding ) throws IOException { if ( data != null ) { output . write ( data . toString ( ) . getBytes ( Charsets . toCharset ( encoding ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the <code > toString () < / code > value of each item in a collection to an <code > OutputStream< / code > line by line using the default character encoding of the platform and the specified line ending . [CODESPLIT] public static void writeLines ( Collection < ? > lines , String lineEnding , OutputStream output ) throws IOException { writeLines ( lines , lineEnding , output , Charset . defaultCharset ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the <code > toString () < / code > value of each item in a collection to an <code > OutputStream< / code > line by line using the specified character encoding and the specified line ending . [CODESPLIT] public static void writeLines ( Collection < ? > lines , String lineEnding , OutputStream output , Charset encoding ) throws IOException { if ( lines == null ) { return ; } if ( lineEnding == null ) { lineEnding = LINE_SEPARATOR ; } Charset cs = Charsets . toCharset ( encoding ) ; for ( Object line : lines ) { if ( line != null ) { output . write ( line . toString ( ) . getBytes ( cs ) ) ; } output . write ( lineEnding . getBytes ( cs ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the <code > toString () < / code > value of each item in a collection to an <code > OutputStream< / code > line by line using the specified character encoding and the specified line ending . <p / > Character encoding names can be found at <a href = http : // www . iana . org / assignments / character - sets > IANA< / a > . [CODESPLIT] public static void writeLines ( Collection < ? > lines , String lineEnding , OutputStream output , String encoding ) throws IOException { writeLines ( lines , lineEnding , output , Charsets . toCharset ( encoding ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the <code > toString () < / code > value of each item in a collection to a <code > Writer< / code > line by line using the specified line ending . [CODESPLIT] public static void writeLines ( Collection < ? > lines , String lineEnding , Writer writer ) throws IOException { if ( lines == null ) { return ; } if ( lineEnding == null ) { lineEnding = LINE_SEPARATOR ; } for ( Object line : lines ) { if ( line != null ) { writer . write ( line . toString ( ) ) ; } writer . write ( lineEnding ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy some or all chars from a large ( over 2GB ) <code > InputStream< / code > to an <code > OutputStream< / code > optionally skipping input chars . <p / > This method uses the provided buffer so there is no need to use a <code > BufferedReader< / code > . <p / > [CODESPLIT] public static long copyLarge ( Reader input , Writer output , final long inputOffset , final long length , char [ ] buffer ) throws IOException { if ( inputOffset > 0 ) { skipFully ( input , inputOffset ) ; } if ( length == 0 ) { return 0 ; } int bytesToRead = buffer . length ; if ( length > 0 && length < buffer . length ) { bytesToRead = ( int ) length ; } int read ; long totalRead = 0 ; while ( bytesToRead > 0 && EOF != ( read = input . read ( buffer , 0 , bytesToRead ) ) ) { output . write ( buffer , 0 , read ) ; totalRead += read ; if ( length > 0 ) { // only adjust length if not reading to the end // Note the cast must work because buffer.length is an integer bytesToRead = ( int ) Math . min ( length - totalRead , buffer . length ) ; } } return totalRead ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare the contents of two Readers to determine if they are equal or not . <p / > This method buffers the input internally using <code > BufferedReader< / code > if they are not already buffered . [CODESPLIT] public static boolean contentEquals ( Reader input1 , Reader input2 ) throws IOException { input1 = toBufferedReader ( input1 ) ; input2 = toBufferedReader ( input2 ) ; int ch = input1 . read ( ) ; while ( EOF != ch ) { int ch2 = input2 . read ( ) ; if ( ch != ch2 ) { return false ; } ch = input1 . read ( ) ; } int ch2 = input2 . read ( ) ; return ch2 == EOF ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare the contents of two Readers to determine if they are equal or not ignoring EOL characters . <p / > This method buffers the input internally using <code > BufferedReader< / code > if they are not already buffered . [CODESPLIT] public static boolean contentEqualsIgnoreEOL ( Reader input1 , Reader input2 ) throws IOException { BufferedReader br1 = toBufferedReader ( input1 ) ; BufferedReader br2 = toBufferedReader ( input2 ) ; String line1 = br1 . readLine ( ) ; String line2 = br2 . readLine ( ) ; while ( line1 != null && line2 != null && line1 . equals ( line2 ) ) { line1 = br1 . readLine ( ) ; line2 = br2 . readLine ( ) ; } return line1 == null ? line2 == null ? true : false : line1 . equals ( line2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean translate ( final int codepoint , final Writer out ) throws IOException { if ( between ) { if ( codepoint < below || codepoint > above ) { return false ; } } else { if ( codepoint >= below && codepoint <= above ) { return false ; } } out . write ( \"&#\" ) ; out . write ( Integer . toString ( codepoint , 10 ) ) ; out . write ( ' ' ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up instance variables that haven t been set by setFeature [CODESPLIT] private void setup ( ) { if ( theSchema == null ) theSchema = new HTMLSchema ( ) ; if ( theScanner == null ) theScanner = new HTMLScanner ( ) ; if ( theAutoDetector == null ) { theAutoDetector = new AutoDetector ( ) { public Reader autoDetectingReader ( InputStream i ) { return new InputStreamReader ( i ) ; } } ; } theStack = new Element ( theSchema . getElementType ( \"<root>\" ) , defaultAttributes ) ; thePCDATA = new Element ( theSchema . getElementType ( \"<pcdata>\" ) , defaultAttributes ) ; theNewElement = null ; theAttributeName = null ; thePITarget = null ; theSaved = null ; theEntity = 0 ; virginStack = true ; theDoctypeName = theDoctypePublicId = theDoctypeSystemId = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Buffer both the InputStream and the Reader [CODESPLIT] private Reader getReader ( InputSource s ) throws SAXException , IOException { Reader r = s . getCharacterStream ( ) ; InputStream i = s . getByteStream ( ) ; String encoding = s . getEncoding ( ) ; String publicid = s . getPublicId ( ) ; String systemid = s . getSystemId ( ) ; if ( r == null ) { if ( i == null ) i = getInputStream ( publicid , systemid ) ; // i = new BufferedInputStream(i); if ( encoding == null ) { r = theAutoDetector . autoDetectingReader ( i ) ; } else { try { r = new InputStreamReader ( i , encoding ) ; } catch ( UnsupportedEncodingException e ) { r = new InputStreamReader ( i ) ; } } } // r = new BufferedReader(r); return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an InputStream based on a publicid and a systemid [CODESPLIT] private InputStream getInputStream ( String publicid , String systemid ) throws IOException , SAXException { URL basis = new URL ( \"file\" , \"\" , System . getProperty ( \"user.dir\" ) + \"/.\" ) ; URL url = new URL ( basis , systemid ) ; URLConnection c = url . openConnection ( ) ; return c . getInputStream ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "needs to support chars past U + FFFF [CODESPLIT] @ Override public void adup ( char [ ] buff , int offset , int length ) throws SAXException { if ( theNewElement != null && theAttributeName != null ) { theNewElement . setAttribute ( theAttributeName , null , theAttributeName ) ; theAttributeName = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "with a semicolon . [CODESPLIT] private String expandEntities ( String src ) { int refStart = - 1 ; int len = src . length ( ) ; char [ ] dst = new char [ len ] ; int dstlen = 0 ; for ( int i = 0 ; i < len ; i ++ ) { char ch = src . charAt ( i ) ; dst [ dstlen ++ ] = ch ; if ( ch == ' ' && refStart == - 1 ) { // start of a ref excluding & refStart = dstlen ; } else if ( refStart == - 1 ) { // not in a ref } else if ( Character . isLetter ( ch ) || Character . isDigit ( ch ) || ch == ' ' ) { // valid entity char } else if ( ch == ' ' ) { // properly terminated ref int ent = lookupEntity ( dst , refStart , dstlen - refStart - 1 ) ; if ( ent > 0xFFFF ) { ent -= 0x10000 ; dst [ refStart - 1 ] = ( char ) ( ( ent >> 10 ) + 0xD800 ) ; dst [ refStart ] = ( char ) ( ( ent & 0x3FF ) + 0xDC00 ) ; dstlen = refStart + 1 ; } else if ( ent != 0 ) { dst [ refStart - 1 ] = ( char ) ent ; dstlen = refStart ; } refStart = - 1 ; } else { // improperly terminated ref refStart = - 1 ; } } return new String ( dst , 0 , dstlen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deferring to the schema for named ones . [CODESPLIT] private int lookupEntity ( char [ ] buff , int offset , int length ) { int result = 0 ; if ( length < 1 ) return result ; // length) + \"]\"); if ( buff [ offset ] == ' ' ) { if ( length > 1 && ( buff [ offset + 1 ] == ' ' || buff [ offset + 1 ] == ' ' ) ) { try { return Integer . parseInt ( new String ( buff , offset + 2 , length - 2 ) , 16 ) ; } catch ( NumberFormatException e ) { return 0 ; } } try { return Integer . parseInt ( new String ( buff , offset + 1 , length - 1 ) , 10 ) ; } catch ( NumberFormatException e ) { return 0 ; } } return theSchema . getEntity ( new String ( buff , offset , length ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "e is the next element to be started if we know what it is [CODESPLIT] private void restart ( Element e ) throws SAXException { while ( theSaved != null && theStack . canContain ( theSaved ) && ( e == null || theSaved . canContain ( e ) ) ) { Element next = theSaved . next ( ) ; push ( theSaved ) ; theSaved = next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pop the stack irrevocably [CODESPLIT] private void pop ( ) throws SAXException { if ( theStack == null ) return ; // empty stack String name = theStack . name ( ) ; String localName = theStack . localName ( ) ; String namespace = theStack . namespace ( ) ; String prefix = prefixOf ( name ) ; if ( ! namespaces ) namespace = localName = \"\" ; theContentHandler . endElement ( namespace , localName , name ) ; if ( foreign ( prefix , namespace ) ) { theContentHandler . endPrefixMapping ( prefix ) ; // \"] for elements to \" + namespace); } Attributes atts = theStack . atts ( ) ; for ( int i = atts . getLength ( ) - 1 ; i >= 0 ; i -- ) { String attNamespace = atts . getURI ( i ) ; String attPrefix = prefixOf ( atts . getQName ( i ) ) ; if ( foreign ( attPrefix , attNamespace ) ) { theContentHandler . endPrefixMapping ( attPrefix ) ; // \"] for attributes to \" + attNamespace); } } theStack = theStack . next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pop the stack restartably [CODESPLIT] private void restartablyPop ( ) throws SAXException { Element popped = theStack ; pop ( ) ; if ( restartElements && ( popped . flags ( ) & Schema . F_RESTART ) != 0 ) { popped . anonymize ( ) ; popped . setNext ( theSaved ) ; theSaved = popped ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the prefix from a QName [CODESPLIT] private String prefixOf ( String name ) { int i = name . indexOf ( ' ' ) ; String prefix = \"\" ; if ( i != - 1 ) prefix = name . substring ( 0 , i ) ; return prefix ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if we have a foreign name [CODESPLIT] private boolean foreign ( String prefix , String namespace ) { // \" for foreignness -- \"); boolean foreign = ! ( prefix . equals ( \"\" ) || namespace . equals ( \"\" ) || namespace . equals ( theSchema . getURI ( ) ) ) ; return foreign ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parsing the complete XML Document Type Definition is way too complex but for many simple cases we can extract something useful from it . <p > doctypedecl :: = <!DOCTYPE S Name ( S ExternalID ) ? S? ( [ intSubset ] S? ) ? > DeclSep :: = PEReference | S intSubset :: = ( markupdecl | DeclSep ) * markupdecl :: = elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment ExternalID :: = SYSTEM S SystemLiteral | PUBLIC S PubidLiteral S SystemLiteral [CODESPLIT] @ Override public void decl ( char [ ] buff , int offset , int length ) throws SAXException { String s = new String ( buff , offset , length ) ; String name = null ; String systemid = null ; String publicid = null ; String [ ] v = split ( s ) ; if ( v . length > 0 && \"DOCTYPE\" . equalsIgnoreCase ( v [ 0 ] ) ) { if ( theDoctypeIsPresent ) return ; // one doctype only! theDoctypeIsPresent = true ; if ( v . length > 1 ) { name = v [ 1 ] ; if ( v . length > 3 && \"SYSTEM\" . equals ( v [ 2 ] ) ) { systemid = v [ 3 ] ; } else if ( v . length > 3 && \"PUBLIC\" . equals ( v [ 2 ] ) ) { publicid = v [ 3 ] ; if ( v . length > 4 ) { systemid = v [ 4 ] ; } else { systemid = \"\" ; } } } } publicid = trimquotes ( publicid ) ; systemid = trimquotes ( systemid ) ; if ( name != null ) { publicid = cleanPublicid ( publicid ) ; theLexicalHandler . startDTD ( name , publicid , systemid ) ; theLexicalHandler . endDTD ( ) ; theDoctypeName = name ; theDoctypePublicId = publicid ; if ( theScanner instanceof Locator ) { // Must resolve systemid theDoctypeSystemId = ( ( Locator ) theScanner ) . getSystemId ( ) ; try { theDoctypeSystemId = new URL ( new URL ( theDoctypeSystemId ) , systemid ) . toString ( ) ; } catch ( Exception ignore ) { } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the String is quoted trim the quotes . [CODESPLIT] private static String trimquotes ( String in ) { if ( in == null ) return in ; int length = in . length ( ) ; if ( length == 0 ) return in ; char s = in . charAt ( 0 ) ; char e = in . charAt ( length - 1 ) ; if ( s == e && ( s == ' ' || s == ' ' ) ) { in = in . substring ( 1 , in . length ( ) - 1 ) ; } return in ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recognises quotes around a phrase and doesn t split it . [CODESPLIT] private static String [ ] split ( String val ) throws IllegalArgumentException { val = val . trim ( ) ; if ( val . length ( ) == 0 ) { return new String [ 0 ] ; } else { ArrayList < String > l = new ArrayList < String > ( ) ; int s = 0 ; int e = 0 ; boolean sq = false ; // single quote boolean dq = false ; // double quote char lastc = 0 ; int len = val . length ( ) ; for ( e = 0 ; e < len ; e ++ ) { char c = val . charAt ( e ) ; if ( ! dq && c == ' ' && lastc != ' ' ) { sq = ! sq ; if ( s < 0 ) s = e ; } else if ( ! sq && c == ' ' && lastc != ' ' ) { dq = ! dq ; if ( s < 0 ) s = e ; } else if ( ! sq && ! dq ) { if ( Character . isWhitespace ( c ) ) { if ( s >= 0 ) l . add ( val . substring ( s , e ) ) ; s = - 1 ; } else if ( s < 0 && c != ' ' ) { s = e ; } } lastc = c ; } l . add ( val . substring ( s , e ) ) ; return ( String [ ] ) l . toArray ( new String [ 0 ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "so that the argument can be safely pushed [CODESPLIT] private void rectify ( Element e ) throws SAXException { Element sp ; while ( true ) { for ( sp = theStack ; sp != null ; sp = sp . next ( ) ) { if ( sp . canContain ( e ) ) break ; } if ( sp != null ) break ; ElementType parentType = e . parent ( ) ; if ( parentType == null ) break ; Element parent = new Element ( parentType , defaultAttributes ) ; // parent.name()); parent . setNext ( e ) ; e = parent ; } if ( sp == null ) return ; // don't know what to do while ( theStack != sp ) { if ( theStack == null || theStack . next ( ) == null || theStack . next ( ) . next ( ) == null ) break ; restartablyPop ( ) ; } while ( e != null ) { Element nexte = e . next ( ) ; if ( ! e . name ( ) . equals ( \"<pcdata>\" ) ) push ( e ) ; e = nexte ; restart ( e ) ; } theNewElement = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "canonicalize case . [CODESPLIT] private String makeName ( char [ ] buff , int offset , int length ) { StringBuffer dst = new StringBuffer ( length + 2 ) ; boolean seenColon = false ; boolean start = true ; // String src = new String(buff, offset, length); // DEBUG for ( ; length -- > 0 ; offset ++ ) { char ch = buff [ offset ] ; if ( Character . isLetter ( ch ) || ch == ' ' ) { start = false ; dst . append ( ch ) ; } else if ( Character . isDigit ( ch ) || ch == ' ' || ch == ' ' ) { if ( start ) dst . append ( ' ' ) ; start = false ; dst . append ( ch ) ; } else if ( ch == ' ' && ! seenColon ) { seenColon = true ; if ( start ) dst . append ( ' ' ) ; start = true ; dst . append ( translateColons ? ' ' : ch ) ; } } int dstLength = dst . length ( ) ; if ( dstLength == 0 || dst . charAt ( dstLength - 1 ) == ' ' ) dst . append ( ' ' ) ; return dst . toString ( ) . intern ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called to retrieve per - instance state before being killed so that the state can be restored in the constructor . [CODESPLIT] public void onSaveInstanceState ( Bundle outState ) { outState . putString ( \"mToolbarVisibility\" , mToolbarVisibility . name ( ) ) ; outState . putBoolean ( \"mToolbarIsVisible\" , mToolbarIsVisible ) ; outState . putInt ( \"mActiveEditor\" , mActiveEditor ) ; if ( mLinkSelection != null ) { outState . putSerializable ( \"mLinkSelection\" , mLinkSelection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform any final cleanup before the component is destroyed . [CODESPLIT] public void onDestroy ( boolean isSaved ) { EventBus . getDefault ( ) . unregister ( this ) ; for ( RTEditText editor : mEditors . values ( ) ) { editor . unregister ( ) ; editor . onDestroy ( isSaved ) ; } mEditors . clear ( ) ; for ( RTToolbar toolbar : mToolbars . values ( ) ) { toolbar . removeToolbarListener ( ) ; } mToolbars . clear ( ) ; mRTApi = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a rich text editor . <p > Before using the editor it needs to be registered to an RTManager . Using means any calls to the editor ( setText will fail if the editor isn t registered ) ! MUST be called from the ui thread . [CODESPLIT] public void registerEditor ( RTEditText editor , boolean useRichTextEditing ) { mEditors . put ( editor . getId ( ) , editor ) ; editor . register ( this , mRTApi ) ; editor . setRichTextEditing ( useRichTextEditing , false ) ; updateToolbarVisibility ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregister a rich text editor . <p > This method may be called before the component is destroyed to stop any interaction with the editor . Not doing so may result in ( asynchronous ) calls coming through when the Activity / Fragment is already stopping its operation . <p > Must be called from the ui thread . <p > Important : calling this method is obsolete once the onDestroy ( boolean ) is called [CODESPLIT] public void unregisterEditor ( RTEditText editor ) { mEditors . remove ( editor . getId ( ) ) ; editor . unregister ( ) ; updateToolbarVisibility ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a toolbar . <p > Only after doing that can it be used in conjunction with a rich text editor . Must be called from the ui thread . [CODESPLIT] public void registerToolbar ( ViewGroup toolbarContainer , RTToolbar toolbar ) { mToolbars . put ( toolbar . getId ( ) , toolbar ) ; toolbar . setToolbarListener ( this ) ; toolbar . setToolbarContainer ( toolbarContainer ) ; updateToolbarVisibility ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregister a toolbar . <p > This method may be called before the component is destroyed to stop any interaction with the toolbar . Not doing so may result in ( asynchronous ) calls coming through when the Activity / Fragment is already stopping its operation . <p > Must be called from the ui thread . <p > Important : calling this method is obsolete once the onDestroy ( boolean ) is called [CODESPLIT] public void unregisterToolbar ( RTToolbar toolbar ) { mToolbars . remove ( toolbar . getId ( ) ) ; toolbar . removeToolbarListener ( ) ; updateToolbarVisibility ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** RTToolbarListener ******************************************* [CODESPLIT] @ Override /* @inheritDoc */ public < V , C extends RTSpan < V > > void onEffectSelected ( Effect < V , C > effect , V value ) { RTEditText editor = getActiveEditor ( ) ; if ( editor != null ) { editor . applyEffect ( effect , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * called from onEventMainThread ( MediaEvent ) [CODESPLIT] private void insertImage ( final RTEditText editor , final RTImage image ) { if ( image != null && editor != null ) { Selection selection = new Selection ( editor ) ; Editable str = editor . getText ( ) ; // Unicode Character 'OBJECT REPLACEMENT CHARACTER' (U+FFFC) // see http://www.fileformat.info/info/unicode/char/fffc/index.htm str . insert ( selection . start ( ) , \"\\uFFFC\" ) ; try { // now add the actual image and inform the RTOperationManager about the operation Spannable oldSpannable = editor . cloneSpannable ( ) ; ImageSpan imageSpan = new ImageSpan ( image , false ) ; str . setSpan ( imageSpan , selection . start ( ) , selection . end ( ) + 1 , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; int selStartAfter = editor . getSelectionStart ( ) ; int selEndAfter = editor . getSelectionEnd ( ) ; editor . onAddMedia ( image ) ; Spannable newSpannable = editor . cloneSpannable ( ) ; mOPManager . executed ( editor , new RTOperationManager . TextChangeOperation ( oldSpannable , newSpannable , selection . start ( ) , selection . end ( ) , selStartAfter , selEndAfter ) ) ; } catch ( OutOfMemoryError e ) { str . delete ( selection . start ( ) , selection . end ( ) + 1 ) ; mRTApi . makeText ( R . string . rte_add_image_error , Toast . LENGTH_LONG ) . show ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** RTEditTextListener ******************************************* [CODESPLIT] @ Override public void onRestoredInstanceState ( RTEditText editor ) { /*\n         * We need to process pending sticky MediaEvents once the editors are registered with the\n         * RTManager and are fully restored.\n         */ MediaEvent event = EventBus . getDefault ( ) . getStickyEvent ( MediaEvent . class ) ; if ( event != null ) { onEventMainThread ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Media file was picked - > process the result . [CODESPLIT] @ Subscribe ( sticky = true , threadMode = ThreadMode . MAIN ) public void onEventMainThread ( MediaEvent event ) { RTEditText editor = mEditors . get ( mActiveEditor ) ; RTMedia media = event . getMedia ( ) ; if ( editor != null && media instanceof RTImage ) { insertImage ( editor , ( RTImage ) media ) ; EventBus . getDefault ( ) . removeStickyEvent ( event ) ; mActiveEditor = Integer . MAX_VALUE ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LinkFragment has closed - > process the result . [CODESPLIT] @ Subscribe ( threadMode = ThreadMode . MAIN ) public void onEventMainThread ( LinkEvent event ) { final String fragmentTag = event . getFragmentTag ( ) ; mRTApi . removeFragment ( fragmentTag ) ; if ( ! event . wasCancelled ( ) && ID_01_LINK_FRAGMENT . equals ( fragmentTag ) ) { RTEditText editor = getActiveEditor ( ) ; if ( editor != null ) { Link link = event . getLink ( ) ; String url = null ; if ( link != null && link . isValid ( ) ) { // the mLinkSelection.end() <= editor.length() check is necessary since // the editor text can change when the link fragment is open Selection selection = mLinkSelection != null && mLinkSelection . end ( ) <= editor . length ( ) ? mLinkSelection : new Selection ( editor ) ; String linkText = link . getLinkText ( ) ; // if no text is selected this inserts the entered link text // if text is selected we replace it by the link text Editable str = editor . getText ( ) ; str . replace ( selection . start ( ) , selection . end ( ) , linkText ) ; editor . setSelection ( selection . start ( ) , selection . start ( ) + linkText . length ( ) ) ; url = link . getUrl ( ) ; } editor . applyEffect ( Effects . LINK , url ) ; // if url == null -> remove the link } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "then translate it back into view ( i . e . eliminate black bars ) . [CODESPLIT] protected void center ( boolean horizontal , boolean vertical ) { if ( mBitmapDisplayed . getBitmap ( ) == null ) { return ; } Matrix m = getImageViewMatrix ( ) ; RectF rect = new RectF ( 0 , 0 , mBitmapDisplayed . getBitmap ( ) . getWidth ( ) , mBitmapDisplayed . getBitmap ( ) . getHeight ( ) ) ; m . mapRect ( rect ) ; float height = rect . height ( ) ; float width = rect . width ( ) ; float deltaX = 0 , deltaY = 0 ; if ( vertical ) { int viewHeight = getHeight ( ) ; if ( height < viewHeight ) { deltaY = ( viewHeight - height ) / 2 - rect . top ; } else if ( rect . top > 0 ) { deltaY = - rect . top ; } else if ( rect . bottom < viewHeight ) { deltaY = getHeight ( ) - rect . bottom ; } } if ( horizontal ) { int viewWidth = getWidth ( ) ; if ( width < viewWidth ) { deltaX = ( viewWidth - width ) / 2 - rect . left ; } else if ( rect . left > 0 ) { deltaX = - rect . left ; } else if ( rect . right < viewWidth ) { deltaX = viewWidth - rect . right ; } } postTranslate ( deltaX , deltaY ) ; setImageMatrix ( getImageViewMatrix ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup the base matrix so that the image is centered and scaled properly . [CODESPLIT] private void getProperBaseMatrix ( RotateBitmap bitmap , Matrix matrix ) { float viewWidth = getWidth ( ) ; float viewHeight = getHeight ( ) ; float w = bitmap . getWidth ( ) ; float h = bitmap . getHeight ( ) ; matrix . reset ( ) ; // We limit up-scaling to 2x otherwise the result may look bad if it's // a small icon. float widthScale = Math . min ( viewWidth / w , 2.0f ) ; float heightScale = Math . min ( viewHeight / h , 2.0f ) ; float scale = Math . min ( widthScale , heightScale ) ; matrix . postConcat ( bitmap . getRotateMatrix ( ) ) ; matrix . postScale ( scale , scale ) ; matrix . postTranslate ( ( viewWidth - w * scale ) / 2F , ( viewHeight - h * scale ) / 2F ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rather than the current 1024x768 this should be changed down to 200% . [CODESPLIT] protected float maxZoom ( ) { if ( mBitmapDisplayed . getBitmap ( ) == null ) { return 1F ; } float fw = ( float ) mBitmapDisplayed . getWidth ( ) / ( float ) mThisWidth ; float fh = ( float ) mBitmapDisplayed . getHeight ( ) / ( float ) mThisHeight ; float max = Math . max ( fw , fh ) * 4 ; return max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the effect exists in the currently selected text of the active RTEditText . [CODESPLIT] final public boolean existsInSelection ( RTEditText editor ) { Selection selection = getSelection ( editor ) ; List < RTSpan < V > > spans = getSpans ( editor . getText ( ) , selection , SpanCollectMode . SPAN_FLAGS ) ; return ! spans . isEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value ( s ) of this effect in the currently selected text of the active RTEditText . [CODESPLIT] final public List < V > valuesInSelection ( RTEditText editor ) { List < V > result = new ArrayList < V > ( ) ; Selection selection = getSelection ( editor ) ; List < RTSpan < V > > spans = getSpans ( editor . getText ( ) , selection , SpanCollectMode . SPAN_FLAGS ) ; for ( RTSpan < V > span : spans ) { result . add ( span . getValue ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all effects of this type from the currently selected text of the active RTEditText . If the selection is empty ( cursor ) formatting for the whole text is removed . [CODESPLIT] final public void clearFormattingInSelection ( RTEditText editor ) { Spannable text = editor . getText ( ) ; // if no selection --> select the whole text // otherwise use the getSelection method (implented by sub classes) Selection selection = new Selection ( editor ) ; selection = selection . isEmpty ( ) ? new Selection ( 0 , text . length ( ) ) : getSelection ( editor ) ; List < RTSpan < V > > spans = getSpans ( text , selection , SpanCollectMode . EXACT ) ; for ( Object span : spans ) { editor . getText ( ) . removeSpan ( span ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Equivalent to the Spanned . getSpans ( int int Class<T > ) method . Return the markup objects ( spans ) attached to the specified slice of a Spannable . The type of the spans is defined in the SpanCollector . [CODESPLIT] final public List < RTSpan < V > > getSpans ( Spannable str , Selection selection , SpanCollectMode mode ) { if ( mSpanCollector == null ) { // lazy initialize the SpanCollector Type [ ] types = ( ( ParameterizedType ) getClass ( ) . getGenericSuperclass ( ) ) . getActualTypeArguments ( ) ; Class < ? extends RTSpan < V > > spanClazz = ( Class < ? extends RTSpan < V > > ) types [ types . length - 1 ] ; mSpanCollector = newSpanCollector ( spanClazz ) ; } return mSpanCollector . getSpans ( str , selection , mode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make sure applyToSelection works on whole paragraphs and call Effects . cleanupParagraphs ( RTEditText ) afterwards . [CODESPLIT] @ Override public final void applyToSelection ( RTEditText editor , V value ) { Selection selection = getSelection ( editor ) ; applyToSelection ( editor , selection , value ) ; Effects . cleanupParagraphs ( editor , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find spans within that paragraph and add them to the ParagraphSpanProcessor to be removed once the ParagraphSpanProcessor processes its spans . [CODESPLIT] protected void findSpans2Remove ( Spannable str , Paragraph paragraph , ParagraphSpanProcessor < V > spanProcessor ) { List < RTSpan < V >> spans = getSpans ( str , paragraph , SpanCollectMode . EXACT ) ; spanProcessor . removeSpans ( spans , paragraph ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method encodes the query part of an url [CODESPLIT] public static String encodeUrl ( String url ) { Uri uri = Uri . parse ( url ) ; try { Map < String , List < String > > splitQuery = splitQuery ( uri ) ; StringBuilder encodedQuery = new StringBuilder ( ) ; for ( String key : splitQuery . keySet ( ) ) { for ( String value : splitQuery . get ( key ) ) { if ( encodedQuery . length ( ) > 0 ) { encodedQuery . append ( \"&\" ) ; } encodedQuery . append ( key + \"=\" + URLEncoder . encode ( value , \"UTF-8\" ) ) ; } } String queryString = encodedQuery != null && encodedQuery . length ( ) > 0 ? \"?\" + encodedQuery : \"\" ; URI baseUri = new URI ( uri . getScheme ( ) , uri . getAuthority ( ) , uri . getPath ( ) , null , uri . getFragment ( ) ) ; return baseUri + queryString ; } catch ( UnsupportedEncodingException ignore ) { } catch ( URISyntaxException ignore ) { } return uri . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method decodes an url with encoded query string [CODESPLIT] public static String decodeQuery ( String url ) { try { return URLDecoder . decode ( url , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException ignore ) { } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method determines if the direction of a substring is right - to - left . If the string is empty that determination is based on the default system language Locale . getDefault () . The method can handle invalid substring definitions ( start > end etc . ) in which case the method returns False . [CODESPLIT] public static boolean isRTL ( CharSequence s , int start , int end ) { if ( s == null || s . length ( ) == 0 ) { // empty string --> determine the direction from the default language return isRTL ( Locale . getDefault ( ) ) ; } if ( start == end ) { // if no character is selected we need to expand the selection start = Math . max ( 0 , -- start ) ; if ( start == end ) { end = Math . min ( s . length ( ) , ++ end ) ; } } try { Bidi bidi = new Bidi ( s . subSequence ( start , end ) . toString ( ) , Bidi . DIRECTION_DEFAULT_LEFT_TO_RIGHT ) ; return ! bidi . baseIsLeftToRight ( ) ; } catch ( IndexOutOfBoundsException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to open a known file browsers to pick a directory . [CODESPLIT] public static boolean pickDirectory ( Activity activity , File startPath , int requestCode ) { PackageManager packageMgr = activity . getPackageManager ( ) ; for ( String [ ] intent : PICK_DIRECTORY_INTENTS ) { String intentAction = intent [ 0 ] ; String uriPrefix = intent [ 1 ] ; Intent startIntent = new Intent ( intentAction ) . putExtra ( \"org.openintents.extra.TITLE\" , activity . getString ( R . string . save_as ) ) . setData ( Uri . parse ( uriPrefix + startPath . getPath ( ) ) ) ; try { if ( startIntent . resolveActivity ( packageMgr ) != null ) { activity . startActivityForResult ( startIntent , requestCode ) ; return true ; } } catch ( ActivityNotFoundException e ) { showNoFilePickerError ( activity , e ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Lifecycle Methods ******************************************* [CODESPLIT] @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . rte_crop_image ) ; mImageView = ( CropImageView ) findViewById ( R . id . image ) ; Intent intent = getIntent ( ) ; Bundle extras = intent . getExtras ( ) ; if ( extras != null ) { if ( extras . getString ( CIRCLE_CROP ) != null ) { mImageView . setLayerType ( View . LAYER_TYPE_SOFTWARE , null ) ; mCircleCrop = true ; mAspectX = 1 ; mAspectY = 1 ; } mImageSource = extras . getString ( IMAGE_SOURCE_FILE ) ; mBitmap = getBitmap ( mImageSource ) ; mImageDest = extras . getString ( IMAGE_DESTINATION_FILE ) ; if ( mImageDest == null ) { mImageDest = mImageSource ; } mSaveUri = Uri . fromFile ( new File ( mImageDest ) ) ; if ( extras . containsKey ( ASPECT_X ) && extras . get ( ASPECT_X ) instanceof Integer ) { mAspectX = extras . getInt ( ASPECT_X ) ; } else { throw new IllegalArgumentException ( \"aspect_x must be integer\" ) ; } if ( extras . containsKey ( ASPECT_Y ) && extras . get ( ASPECT_Y ) instanceof Integer ) { mAspectY = extras . getInt ( ASPECT_Y ) ; } else { throw new IllegalArgumentException ( \"aspect_y must be integer\" ) ; } mOutputX = extras . getInt ( OUTPUT_X ) ; mOutputY = extras . getInt ( OUTPUT_Y ) ; mScale = extras . getBoolean ( SCALE , true ) ; mScaleUp = extras . getBoolean ( SCALE_UP_IF_NEEDED , true ) ; } if ( mBitmap == null ) { finish ( ) ; return ; } startFaceDetection ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Private Methods ******************************************* [CODESPLIT] private Bitmap getBitmap ( String path ) { Uri uri = MediaUtils . createFileUri ( path ) ; InputStream in = null ; try { in = getContentResolver ( ) . openInputStream ( uri ) ; // Decode image size BitmapFactory . Options options = new BitmapFactory . Options ( ) ; options . inJustDecodeBounds = true ; BitmapFactory . decodeStream ( in , null , options ) ; Helper . closeQuietly ( in ) ; // compute scale factor to ensure that the image is smaller than // IMAGE_MAX_SIZE float maxSize = Math . max ( options . outWidth , options . outHeight ) ; float scale = maxSize > IMAGE_MAX_SIZE ? maxSize / IMAGE_MAX_SIZE : 1.0f ; while ( ( maxSize / scale ) > 8 ) { try { return getBitmap ( in , uri , scale ) ; } catch ( Throwable e ) { Log . w ( getClass ( ) . getSimpleName ( ) , \"bitmap could not be created (probably out of memory), decreasing size and retrying\" ) ; scale *= 2f ; } } } catch ( IOException e ) { Log . e ( getClass ( ) . getSimpleName ( ) , \"file \" + path + \" not found\" ) ; } catch ( Exception e ) { Log . e ( getClass ( ) . getSimpleName ( ) , \"error while opening image\" , e ) ; } finally { Helper . closeQuietly ( in ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Compute the sample size as a function of minSideLength and maxNumOfPixels . minSideLength is used to specify that minimal width or height of a bitmap . maxNumOfPixels is used to specify the maximal size in pixels that are tolerable in terms of memory usage . [CODESPLIT] private Bitmap transform ( Matrix scaler , Bitmap source , int targetWidth , int targetHeight , boolean scaleUp ) { int deltaX = source . getWidth ( ) - targetWidth ; int deltaY = source . getHeight ( ) - targetHeight ; if ( ! scaleUp && ( deltaX < 0 || deltaY < 0 ) ) { /*\n             * In this case the bitmap is smaller, at least in one dimension,\n             * than the target. Transform it by placing as much of the image as\n             * possible into the target and leaving the top/bottom or left/right\n             * (or both) black.\n             */ Bitmap b2 = Bitmap . createBitmap ( targetWidth , targetHeight , Bitmap . Config . ARGB_8888 ) ; Canvas c = new Canvas ( b2 ) ; int deltaXHalf = Math . max ( 0 , deltaX / 2 ) ; int deltaYHalf = Math . max ( 0 , deltaY / 2 ) ; Rect src = new Rect ( deltaXHalf , deltaYHalf , deltaXHalf + Math . min ( targetWidth , source . getWidth ( ) ) , deltaYHalf + Math . min ( targetHeight , source . getHeight ( ) ) ) ; int dstX = ( targetWidth - src . width ( ) ) / 2 ; int dstY = ( targetHeight - src . height ( ) ) / 2 ; Rect dst = new Rect ( dstX , dstY , targetWidth - dstX , targetHeight - dstY ) ; c . drawBitmap ( source , src , dst , null ) ; return b2 ; } float bitmapWidthF = source . getWidth ( ) ; float bitmapHeightF = source . getHeight ( ) ; float bitmapAspect = bitmapWidthF / bitmapHeightF ; float viewAspect = ( float ) targetWidth / targetHeight ; if ( bitmapAspect > viewAspect ) { float scale = targetHeight / bitmapHeightF ; if ( scale < .9F || scale > 1F ) { scaler . setScale ( scale , scale ) ; } else { scaler = null ; } } else { float scale = targetWidth / bitmapWidthF ; if ( scale < .9F || scale > 1F ) { scaler . setScale ( scale , scale ) ; } else { scaler = null ; } } Bitmap b1 ; if ( scaler != null ) { // this is used for minithumb and crop, so we want to mFilter here. b1 = Bitmap . createBitmap ( source , 0 , 0 , source . getWidth ( ) , source . getHeight ( ) , scaler , true ) ; } else { b1 = source ; } int dx1 = Math . max ( 0 , b1 . getWidth ( ) - targetWidth ) ; int dy1 = Math . max ( 0 , b1 . getHeight ( ) - targetHeight ) ; Bitmap b2 = Bitmap . createBitmap ( b1 , dx1 / 2 , dy1 / 2 , targetWidth , targetHeight ) ; if ( b1 != source ) { b1 . recycle ( ) ; } return b2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Thong added for rotate [CODESPLIT] private Bitmap rotateImage ( Bitmap src , float degree ) { // create new matrix Matrix matrix = new Matrix ( ) ; // setup rotation degree matrix . postRotate ( degree ) ; Bitmap bmp = Bitmap . createBitmap ( src , 0 , 0 , src . getWidth ( ) , src . getHeight ( ) , matrix , true ) ; return bmp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Lifecycle Methods ******************************************* [CODESPLIT] @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; Bundle extras = getIntent ( ) . getExtras ( ) ; if ( extras != null ) { String mediaAction = extras . getString ( EXTRA_MEDIA_ACTION ) ; mMediaAction = mediaAction == null ? null : MediaAction . valueOf ( mediaAction ) ; mMediaFactory = ( RTMediaFactory < RTImage , RTAudio , RTVideo > ) extras . getSerializable ( EXTRA_MEDIA_FACTORY ) ; } if ( mMediaAction != null ) { // retrieve parameters if ( savedInstanceState != null ) { mSelectedMedia = ( RTMedia ) savedInstanceState . getSerializable ( \"mSelectedMedia\" ) ; } switch ( mMediaAction ) { case PICK_PICTURE : case CAPTURE_PICTURE : mMediaChooserMgr = new ImageChooserManager ( this , mMediaAction , mMediaFactory , this , savedInstanceState ) ; break ; case PICK_VIDEO : case CAPTURE_VIDEO : mMediaChooserMgr = new VideoChooserManager ( this , mMediaAction , mMediaFactory , this , savedInstanceState ) ; break ; case PICK_AUDIO : case CAPTURE_AUDIO : mMediaChooserMgr = new AudioChooserManager ( this , mMediaAction , mMediaFactory , this , savedInstanceState ) ; break ; } if ( mMediaChooserMgr == null ) { finish ( ) ; } else if ( ! isWorkInProgress ( ) ) { setWorkInProgress ( true ) ; if ( ! mMediaChooserMgr . chooseMedia ( ) ) { finish ( ) ; } } } else { finish ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "****************************************** Listener Methods ******************************************* [CODESPLIT] @ Override public void onActivityResult ( int requestCode , int resultCode , Intent data ) { if ( resultCode == Activity . RESULT_OK ) { if ( requestCode == MediaAction . PICK_PICTURE . requestCode ( ) && data != null ) { mMediaChooserMgr . processMedia ( MediaAction . PICK_PICTURE , data ) ; } else if ( requestCode == MediaAction . CAPTURE_PICTURE . requestCode ( ) ) { mMediaChooserMgr . processMedia ( MediaAction . CAPTURE_PICTURE , data ) ; // data may be null here } else if ( requestCode == Constants . CROP_IMAGE ) { String path = data . getStringExtra ( CropImageActivity . IMAGE_DESTINATION_FILE ) ; if ( path != null && mSelectedMedia instanceof RTImage ) { EventBus . getDefault ( ) . postSticky ( new MediaEvent ( mSelectedMedia ) ) ; finish ( ) ; } } } else { setResult ( RESULT_CANCELED ) ; finish ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a new output destination for the document . [CODESPLIT] public void setOutput ( Writer writer ) { if ( writer == null ) { output = new OutputStreamWriter ( System . out ) ; } else { output = writer ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force a Namespace declaration with a preferred prefix . <p > <p > This is a convenience method that invokes { @link #setPrefix setPrefix } then { @link #forceNSDecl ( java . lang . String ) forceNSDecl } . < / p > [CODESPLIT] public void forceNSDecl ( String uri , String prefix ) { setPrefix ( uri , prefix ) ; forceNSDecl ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the XML declaration at the beginning of the document . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] public void startDocument ( ) throws SAXException { writeText4Links ( ) ; reset ( ) ; if ( ! ( \"yes\" . equals ( outputProperties . getProperty ( OMIT_XML_DECLARATION , \"no\" ) ) ) ) { write ( \"<?xml\" ) ; if ( version == null ) { write ( \" version=\\\"1.0\\\"\" ) ; } else { write ( \" version=\\\"\" ) ; write ( version ) ; write ( \"\\\"\" ) ; } if ( outputEncoding != null && outputEncoding != \"\" ) { write ( \" encoding=\\\"\" ) ; write ( outputEncoding ) ; write ( \"\\\"\" ) ; } if ( standalone == null ) { write ( \" standalone=\\\"yes\\\"?>\\n\" ) ; } else { write ( \" standalone=\\\"\" ) ; write ( standalone ) ; write ( \"\\\"\" ) ; } } super . startDocument ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a newline at the end of the document . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] public void endDocument ( ) throws SAXException { writeText4Links ( ) ; write ( ' ' ) ; super . endDocument ( ) ; try { flush ( ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a start tag . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void startElement ( String uri , String localName , String qName , Attributes atts ) throws SAXException { writeText4Links ( ) ; if ( ! ignoreElement ( uri , localName , qName , atts ) ) { elementLevel ++ ; nsSupport . pushContext ( ) ; if ( forceDTD && ! hasOutputDTD ) { startDTD ( localName == null ? qName : localName , \"\" , \"\" ) ; } write ( ' ' ) ; writeName ( uri , localName , qName , true ) ; writeAttributes ( atts ) ; if ( elementLevel == 1 ) { forceNSDecls ( ) ; } if ( ! mOmitXHTMLNamespace || ! \"html\" . equalsIgnoreCase ( localName ) ) { writeNSDecls ( ) ; } write ( ' ' ) ; if ( htmlMode && ( qName . equals ( \"script\" ) || qName . equals ( \"style\" ) ) ) { cdataElement = true ; } if ( htmlMode && localName . equals ( \"a\" ) ) { mIgnoreChars = true ; } super . startElement ( uri , localName , qName , atts ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an end tag . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void endElement ( String uri , String localName , String qName ) throws SAXException { writeText4Links ( ) ; if ( ! mIgnoredTags . isEmpty ( ) && mIgnoredTags . peek ( ) . equalsIgnoreCase ( qName ) ) { mIgnoredTags . pop ( ) ; } else { if ( ! ( htmlMode && ( uri . equals ( \"http://www.w3.org/1999/xhtml\" ) || uri . equals ( \"\" ) ) && ( qName . equals ( \"area\" ) || qName . equals ( \"base\" ) || qName . equals ( \"basefont\" ) || qName . equals ( \"br\" ) || qName . equals ( \"col\" ) || qName . equals ( \"frame\" ) || qName . equals ( \"hr\" ) || qName . equals ( \"img\" ) || qName . equals ( \"input\" ) || qName . equals ( \"isindex\" ) || qName . equals ( \"link\" ) || qName . equals ( \"meta\" ) || qName . equals ( \"param\" ) ) ) ) { write ( \"</\" ) ; writeName ( uri , localName , qName , true ) ; write ( ' ' ) ; } if ( elementLevel == 1 ) { write ( ' ' ) ; } if ( htmlMode && localName . equals ( \"a\" ) ) { mIgnoreChars = false ; } cdataElement = false ; super . endElement ( uri , localName , qName ) ; nsSupport . popContext ( ) ; elementLevel -- ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write character data . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void characters ( char ch [ ] , int start , int len ) throws SAXException { if ( ! cdataElement ) { if ( mIgnoreChars ) { writeText4Links ( ) ; writeEscUTF16 ( new String ( ch ) , start , len , false ) ; } else { collectText4Links ( ch , start , len ) ; } } else { writeText4Links ( ) ; for ( int i = start ; i < start + len ; i ++ ) { write ( ch [ i ] ) ; } } super . characters ( ch , start , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write ignorable whitespace . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void ignorableWhitespace ( char ch [ ] , int start , int length ) throws SAXException { writeText4Links ( ) ; writeEscUTF16 ( new String ( ch ) , start , length , false ) ; super . ignorableWhitespace ( ch , start , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a processing instruction . <p > Pass the event on down the filter chain for further processing . [CODESPLIT] @ Override public void processingInstruction ( String target , String data ) throws SAXException { writeText4Links ( ) ; write ( \"<?\" ) ; write ( target ) ; write ( ' ' ) ; write ( data ) ; write ( \"?>\" ) ; if ( elementLevel < 1 ) { write ( ' ' ) ; } super . processingInstruction ( target , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force all Namespaces to be declared . <p > This method is used on the root element to ensure that the predeclared Namespaces all appear . [CODESPLIT] private void forceNSDecls ( ) { Enumeration < String > prefixes = forcedDeclTable . keys ( ) ; while ( prefixes . hasMoreElements ( ) ) { String prefix = ( String ) prefixes . nextElement ( ) ; doPrefix ( prefix , null , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the prefix for an element or attribute name . <p > [CODESPLIT] private String doPrefix ( String uri , String qName , boolean isElement ) { String defaultNS = nsSupport . getURI ( \"\" ) ; if ( \"\" . equals ( uri ) ) { if ( isElement && defaultNS != null ) nsSupport . declarePrefix ( \"\" , \"\" ) ; return null ; } String prefix ; if ( isElement && defaultNS != null && uri . equals ( defaultNS ) ) { prefix = \"\" ; } else { prefix = nsSupport . getPrefix ( uri ) ; } if ( prefix != null ) { return prefix ; } prefix = ( String ) doneDeclTable . get ( uri ) ; if ( prefix != null && ( ( ! isElement || defaultNS != null ) && \"\" . equals ( prefix ) || nsSupport . getURI ( prefix ) != null ) ) { prefix = null ; } if ( prefix == null ) { prefix = ( String ) prefixTable . get ( uri ) ; if ( prefix != null && ( ( ! isElement || defaultNS != null ) && \"\" . equals ( prefix ) || nsSupport . getURI ( prefix ) != null ) ) { prefix = null ; } } if ( prefix == null && qName != null && ! \"\" . equals ( qName ) ) { int i = qName . indexOf ( ' ' ) ; if ( i == - 1 ) { if ( isElement && defaultNS == null ) { prefix = \"\" ; } } else { prefix = qName . substring ( 0 , i ) ; } } for ( ; prefix == null || nsSupport . getURI ( prefix ) != null ; prefix = \"__NS\" + ++ prefixCounter ) ; nsSupport . declarePrefix ( prefix , uri ) ; doneDeclTable . put ( uri , prefix ) ; return prefix ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a raw character . [CODESPLIT] private void write ( char c ) throws SAXException { try { output . write ( c ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a raw string . [CODESPLIT] private void write ( String s ) throws SAXException { try { output . write ( s ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out an attribute list escaping values . <p > The names will have prefixes added to them . [CODESPLIT] private void writeAttributes ( Attributes atts ) throws SAXException { int len = atts . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { write ( ' ' ) ; writeName ( atts . getURI ( i ) , atts . getLocalName ( i ) , atts . getQName ( i ) , false ) ; if ( htmlMode && booleanAttribute ( atts . getLocalName ( i ) , atts . getQName ( i ) , atts . getValue ( i ) ) ) break ; write ( \"=\\\"\" ) ; String s = atts . getValue ( i ) ; writeEscUTF16 ( s , 0 , s . length ( ) , true ) ; write ( ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the attribute is an HTML boolean from the above list . [CODESPLIT] private boolean booleanAttribute ( String localName , String qName , String value ) { String name = localName ; if ( name == null ) { int i = qName . indexOf ( ' ' ) ; if ( i != - 1 ) name = qName . substring ( i + 1 , qName . length ( ) ) ; } if ( ! name . equals ( value ) ) return false ; for ( int j = 0 ; j < booleans . length ; j ++ ) { if ( name . equals ( booleans [ j ] ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an array of data characters with escaping . [CODESPLIT] private void writeEscUTF16 ( String s , int start , int length , boolean isAttVal ) throws SAXException { String subString = s . substring ( start , start + length ) ; write ( StringEscapeUtils . escapeHtml4 ( subString ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out the list of Namespace declarations . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void writeNSDecls ( ) throws SAXException { Enumeration < String > prefixes = ( Enumeration < String > ) nsSupport . getDeclaredPrefixes ( ) ; while ( prefixes . hasMoreElements ( ) ) { String prefix = ( String ) prefixes . nextElement ( ) ; String uri = nsSupport . getURI ( prefix ) ; if ( uri == null ) { uri = \"\" ; } write ( ' ' ) ; if ( \"\" . equals ( prefix ) ) { write ( \"xmlns=\\\"\" ) ; } else { write ( \"xmlns:\" ) ; write ( prefix ) ; write ( \"=\\\"\" ) ; } writeEscUTF16 ( uri , 0 , uri . length ( ) , true ) ; write ( ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an element or attribute name . [CODESPLIT] private void writeName ( String uri , String localName , String qName , boolean isElement ) throws SAXException { String prefix = doPrefix ( uri , qName , isElement ) ; if ( prefix != null && ! \"\" . equals ( prefix ) ) { write ( prefix ) ; write ( ' ' ) ; } if ( localName != null && ! \"\" . equals ( localName ) ) { write ( localName ) ; } else { int i = qName . indexOf ( ' ' ) ; write ( qName . substring ( i + 1 , qName . length ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public void comment ( char [ ] ch , int start , int length ) throws SAXException { write ( \"<!--\" ) ; for ( int i = start ; i < start + length ; i ++ ) { write ( ch [ i ] ) ; if ( ch [ i ] == ' ' && i + 1 <= start + length && ch [ i + 1 ] == ' ' ) write ( ' ' ) ; } write ( \"-->\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make this element anonymous . Remove any <tt > id< / tt > or <tt > name< / tt > attribute present in the element s attributes . [CODESPLIT] public void anonymize ( ) { for ( int i = theAtts . getLength ( ) - 1 ; i >= 0 ; i -- ) { if ( theAtts . getType ( i ) . equals ( \"ID\" ) || theAtts . getQName ( i ) . equals ( \"name\" ) ) { theAtts . removeAttribute ( i ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean the attributes of this element . Attributes with null name ( the name was ill - formed ) or null value ( the attribute was present in the element type but not in this actual element ) are removed . [CODESPLIT] public void clean ( ) { for ( int i = theAtts . getLength ( ) - 1 ; i >= 0 ; i -- ) { String name = theAtts . getLocalName ( i ) ; if ( theAtts . getValue ( i ) == null || name == null || name . length ( ) == 0 ) { theAtts . removeAttribute ( i ) ; continue ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a AmazonKinesis client configured with some optional properties ( can also be configured using environment variables ) : [CODESPLIT] public static AmazonKinesis buildKinesisClient ( @ Nullable String accessKey , @ Nullable String secretKey , // @ Nullable String endpoint , @ Nullable Integer port , @ Nullable String region ) { AmazonKinesisClientBuilder builder = AmazonKinesisClientBuilder . standard ( ) ; setAws ( builder , accessKey , secretKey , endpoint , port , region ) ; return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure that the Kinesis Stream exists ( creates it if does not exist ) . [CODESPLIT] public static void ensureStreamExists ( AmazonKinesis kinesisClient , String streamName ) { createStreamIfNotExists ( kinesisClient , streamName , 1 ) ; waitStreamActivation ( kinesisClient , streamName , MIN_3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a stream if it does not already exist . [CODESPLIT] private static void createStreamIfNotExists ( AmazonKinesis kinesis , String streamName , int shardCount ) { performAmazonActionWithRetry ( \"createStream\" , ( ) -> { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( streamName ) . withLimit ( 1 ) ; try { kinesis . describeStream ( describeStreamRequest ) ; } catch ( ResourceNotFoundException e ) { kinesis . createStream ( streamName , shardCount ) ; } return null ; } , DEFAULT_RETRY_COUNT , DEFAULT_RETRY_DURATION_IN_MILLIS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits that the stream has been created . [CODESPLIT] private static void waitStreamActivation ( AmazonKinesis consumer , String streamName , long streamCreationTimeoutMillis ) { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( streamName ) . withLimit ( 1 ) ; DescribeStreamResult describeStreamResult = null ; String streamStatus = null ; long endTime = System . currentTimeMillis ( ) + streamCreationTimeoutMillis ; do { try { describeStreamResult = consumer . describeStream ( describeStreamRequest ) ; streamStatus = describeStreamResult . getStreamDescription ( ) . getStreamStatus ( ) ; if ( ACTIVE_STREAM_STATUS . equals ( streamStatus ) ) { break ; } Thread . sleep ( 100 ) ; } catch ( ResourceNotFoundException | LimitExceededException ignored ) { // ignored } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new AwsKinesisException ( \"Thread interrupted while waiting for stream activation\" , args -> args . add ( \"streamName\" , streamName ) , e ) ; } } while ( System . currentTimeMillis ( ) < endTime ) ; if ( describeStreamResult == null || streamStatus == null || ! streamStatus . equals ( ACTIVE_STREAM_STATUS ) ) { throw new AwsKinesisException ( \"Stream never went active\" , args -> args . add ( \"streamName\" , streamName ) . add ( \"streamCreationTimeoutMillis\" , streamCreationTimeoutMillis ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO very ugly fix [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > TypeConverter < T > getTypeConverter ( Class < T > clazz ) { TypeConverter < T > converter = ( TypeConverter < T > ) TYPE_CONVERTERS . get ( clazz ) ; if ( converter == null ) { converter = value -> ( T ) value ; } return converter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method has to be called in the default implementation of an entity interface to declare that a relation is the reciprocal of another relation : <ul > <li > the straight relation is defined from the { @code TAIL } entity to the { @code HEAD } entity . It must not have a default implementation< / li > <li > the reverse relation is defined from the { @code HEAD } entity to the { @code TAIL } entity . It must have a default implementation that call this method< / li > < / ul > <p > At runtime this call is only issued during the model analysis . The entity instances proxies overrides this default implementation to return the needed information . <br > [CODESPLIT] public static < TAIL , HEAD > Collection < TAIL > reciprocalManyRelation ( Class < TAIL > tailEntityClass , Accessor < TAIL , HEAD > relationAccessor ) { return THREAD_LOCAL_DSL_HELPER . get ( ) . reciprocalManyRelation ( tailEntityClass , relationAccessor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete snapshot N with lacking instance snapshots from snapshot N - 1 [CODESPLIT] private static void completeStoreSnapshotWithMissingInstanceSnapshots ( Path targetStoresPath ) { String transactionIdRegexAlone = \"\\\"transactionId\\\"\\\\s*:\\\\s*\\\\d+\\\\s*,\" ; String transactionIdRegexReplace = \"(.*\\\"transactionId\\\"\\\\s*:\\\\s*)\\\\d+(\\\\s*,.*)\" ; Pattern transactionIdPattern = compile ( transactionIdRegexAlone ) ; Set < File > previousSnapshots = new HashSet <> ( ) ; Arrays . stream ( targetStoresPath . resolve ( SNAPSHOT_DIRECTORY_NAME ) . toFile ( ) . listFiles ( ) ) . sorted ( ) . forEach ( snapshot -> { Set < String > snapshotNames = Arrays . stream ( snapshot . listFiles ( ) ) . map ( File :: getName ) . collect ( toSet ( ) ) ; previousSnapshots . stream ( ) . filter ( previousSnapshot -> ! snapshotNames . contains ( previousSnapshot . getName ( ) ) ) . forEach ( previousSnapshot -> { try { Path targetPath = snapshot . toPath ( ) . resolve ( previousSnapshot . getName ( ) ) ; Path sourcePath = previousSnapshot . toPath ( ) ; long count = countTransactionId ( transactionIdPattern , sourcePath ) ; if ( count != 1L ) { throw new StoreException ( \"transactionId not found once\" , args -> args . add ( \"found count\" , count ) ) ; } BigInteger newTransactionId = new BigInteger ( snapshot . getName ( ) ) ; replaceTransactionIdValue ( transactionIdRegexReplace , sourcePath , targetPath , newTransactionId . toString ( ) ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } ) ; previousSnapshots . clear ( ) ; previousSnapshots . addAll ( Arrays . stream ( snapshot . listFiles ( ) ) . collect ( toSet ( ) ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the single created shard ( stream has a single shard ) . [CODESPLIT] private Shard getUniqueShard ( ) { DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest ( ) . withStreamName ( m_streamName ) . withLimit ( 1 ) ; DescribeStreamResult describeStreamResult = performAmazonActionWithRetry ( \"describe stream \" + m_streamName , ( ) -> m_kinesis . describeStream ( describeStreamRequest ) , DEFAULT_RETRY_COUNT , DEFAULT_RETRY_DURATION_IN_MILLIS ) ; String streamStatus = describeStreamResult . getStreamDescription ( ) . getStreamStatus ( ) ; if ( streamStatus == null || ! streamStatus . equals ( ACTIVE_STREAM_STATUS ) ) { throw new AwsKinesisException ( \"Stream does not exist\" , args -> args . add ( \"streamName\" , m_streamName ) ) ; } List < Shard > shards = describeStreamResult . getStreamDescription ( ) . getShards ( ) ; checkState ( shards . size ( ) == 1 , \"Kinesis Stream should contain only one shard\" , args -> args . add ( \"streamName\" , m_streamName ) . add ( \"shardCount\" , shards . size ( ) ) ) ; return shards . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait that the minimum duration between two GetShardIteratorRequests has elapsed . [CODESPLIT] private boolean waitTheMinimalDurationToExecuteTheNextProvisioningRequest ( ) { if ( m_lastGetShardIteratorRequestTime != null ) { long delay = m_durationBetweenRequests . get ( ) - ( System . currentTimeMillis ( ) - m_lastGetShardIteratorRequestTime ) ; if ( delay > 0 ) { try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return false ; } } } m_lastGetShardIteratorRequestTime = System . currentTimeMillis ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves records corresponding to the request . [CODESPLIT] @ Nullable private List < Record > getRecords ( GetRecordsRequest getRecordsRequest ) { return tryAmazonAction ( \"\" , ( ) -> { GetRecordsResult getRecordsResult = m_kinesis . getRecords ( getRecordsRequest ) ; m_shardIterator = getRecordsResult . getNextShardIterator ( ) ; List < Record > records = getRecordsResult . getRecords ( ) ; LOG . trace ( \"Get records\" , args -> args . add ( \"streamName\" , m_streamName ) . add ( \"record number\" , records . size ( ) ) . add ( \"millisBehindLatest\" , getRecordsResult . getMillisBehindLatest ( ) ) ) ; return records ; } , m_durationBetweenRequests ) . orElse ( List . of ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle retry for amazon quotas [CODESPLIT] public static < T > T performAmazonActionWithRetry ( String actionLabel , Supplier < T > action , int retryLimit , int durationInMillis ) { int retryCount = 0 ; do { try { return action . get ( ) ; } catch ( LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e ) { // We should just wait a little time before trying again int remainingRetries = retryLimit - retryCount ; LOG . debug ( \"Amazon exception caught\" , args -> args . add ( \"exception\" , e . getClass ( ) . getName ( ) ) . add ( \"action\" , actionLabel ) . add ( \"remainingRetryCount\" , remainingRetries ) ) ; } sleepUntilInterrupted ( actionLabel , durationInMillis ) ; } while ( retryCount ++ < retryLimit ) ; throw new AwsException ( \"Limit exceeded, all retries failed\" , args -> args . add ( \"action\" , actionLabel ) . add ( \"retryLimit\" , retryLimit ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to perform an Amazon action and increase the duration between requests if some exception is exceeding resource usage exception is thrown . [CODESPLIT] public static < T > Optional < T > tryAmazonAction ( String actionLabel , Supplier < T > action , AtomicLong durationBetweenRequests ) { try { return of ( action . get ( ) ) ; } catch ( LimitExceededException | ProvisionedThroughputExceededException | KMSThrottlingException e ) { int durationRandomModifier = 1 + RANDOM . nextInt ( 64 ) ; // random duration to make readers out of sync, avoiding simultaneous readings long updatedDuration = durationBetweenRequests . updateAndGet ( duration -> duration * 2 // twice the duration + duration * 2 / durationRandomModifier ) ; // add random duration to avoid simultaneous reads LOG . debug ( \"Update of minimal duration between two get shard iterator requests\" , args -> args . add ( \"actionLabel\" , actionLabel ) . add ( \"new minimalDurationBetweenTwoGetShardIteratorRequests\" , updatedDuration ) ) ; } return empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a AwsS3SnapshotStore with some properties set to configure S3 client : ( + ) to configure the access both access key and secret key must be provided . ( * ) to configure the endpoint URL the endpoint the port and the region must be provided . [CODESPLIT] public static AmazonS3 buildS3Client ( @ Nullable String accessKey , @ Nullable String secretKey , // @ Nullable String endpoint , @ Nullable Integer port , @ Nullable String region ) { AmazonS3ClientBuilder builder = AmazonS3ClientBuilder . standard ( ) ; setAws ( builder , accessKey , secretKey , endpoint , port , region ) ; return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws an exception if the bucket does not exist or is not readable . [CODESPLIT] static String checkBucketIsAccessible ( AmazonS3 amazonS3 , String bucketName ) { HeadBucketRequest headBucketRequest = new HeadBucketRequest ( bucketName ) ; try { amazonS3 . headBucket ( headBucketRequest ) ; } catch ( AmazonServiceException e ) { throw new AwsS3Exception ( \"Bucket is not accessible\" , args -> args . add ( \"bucketName\" , bucketName ) , e ) ; } return bucketName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method don t use cache . Use with care . <br > If caching is required then use { @link #getMethodName ( Class Accessor ) } [CODESPLIT] public static < T > Method retrieveMethod ( Class < T > clazz , Accessor < T , ? > accessor ) { MethodCallRecorder methodCallRecorder = new MethodCallRecorder ( ) ; T accessorInstance = ProxyFactoryBuilder . < MethodCallRecorder > newProxyFactoryBuilder ( ) // . defaultObjectMethods ( ) // . unhandled ( ( context , proxy , method , args ) -> { context . setMethod ( method ) ; return DEFAULT_VALUES . get ( method . getReturnType ( ) ) ; } ) // . build ( clazz ) . createProxy ( methodCallRecorder ) ; accessor . get ( accessorInstance ) ; Method method = methodCallRecorder . getMethod ( ) ; if ( method == null ) { throw new StoreException ( \"Method reference didn't call any method on the class\" , args -> args . add ( \"className\" , clazz . getName ( ) ) ) ; } return method ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the stores . [CODESPLIT] Optional < BigInteger > loadStores ( Function < String , EntityStores > entityStoresByStoreName , BiFunction < SerializableSnapshot , String , SerializableSnapshot > snapshotPostProcessor ) { Optional < BigInteger > latestSnapshotTxId ; try { latestSnapshotTxId = m_snapshotStore . listSnapshots ( ) . stream ( ) . max ( BigInteger :: compareTo ) ; } catch ( IOException e ) { throw new UnrecoverableStoreException ( \"Error occurred when recovering from latest snapshot\" , e ) ; } latestSnapshotTxId . ifPresent ( lastTx -> { LOG . info ( \"Recovering store from snapshot\" , args -> args . add ( \"transactionId\" , lastTx ) ) ; var postProcess = new SnapshotPostProcessor ( snapshotPostProcessor ) ; try { Flowable . fromPublisher ( m_snapshotStore . createSnapshotReader ( lastTx ) ) // . blockingForEach ( reader -> { String storeName = reader . storeName ( ) ; EntityStores entityStores = entityStoresByStoreName . apply ( storeName ) ; SerializableSnapshot serializableSnapshot ; try ( InputStream is = reader . inputStream ( ) ) { serializableSnapshot = m_snapshotSerializer . deserializeSnapshot ( storeName , is ) ; } if ( serializableSnapshot . getSnapshotModelVersion ( ) != SNAPSHOT_MODEL_VERSION ) { throw new UnrecoverableStoreException ( \"Snapshot serializable model version is not supported\" , args -> args . add ( \"version\" , serializableSnapshot . getSnapshotModelVersion ( ) ) . add ( \"expectedVersion\" , SNAPSHOT_MODEL_VERSION ) ) ; } if ( ! lastTx . equals ( serializableSnapshot . getTransactionId ( ) ) ) { throw new UnrecoverableStoreException ( \"Snapshot transaction id  mismatch with request transaction id\" , args -> args . add ( \"snapshotTransactionId\" , serializableSnapshot . getTransactionId ( ) ) . add ( \"requestTransactionId\" , lastTx ) ) ; } SerializableSnapshot finalSnapshot = postProcess . apply ( storeName , serializableSnapshot ) ; finalSnapshot . getEntities ( ) . forEach ( serializableEntityInstances -> { String entityName = serializableEntityInstances . getEntityName ( ) ; EntityStore < ? > entityStore = entityStores . getEntityStore ( entityName ) ; checkArgument ( entityStore != null , \"Entity has not be registered in the store\" , args -> args . add ( \"entityName\" , entityName ) ) ; entityStore . recover ( serializableEntityInstances ) ; } ) ; } ) ; } catch ( Exception e ) { throw new UnrecoverableStoreException ( \"Error occurred when recovering from latest snapshot\" , e ) ; } // update the applicationModelVersion if any consistent load/update m_applicationModelVersion = postProcess . getConsistentApplicationModelVersion ( ) ; } ) ; if ( ! latestSnapshotTxId . isPresent ( ) ) { LOG . info ( \"Store has no snapshot, store is empty, creating it's first snapshot\" ) ; } return latestSnapshotTxId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public InputStream locateStream ( final String uri , final File folder ) throws IOException { final Collection < File > files = findMatchedFiles ( new WildcardContext ( uri , folder ) ) ; final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; for ( final File file : files ) { if ( file . isFile ( ) ) { final InputStream is = new FileInputStream ( file ) ; IOUtils . copy ( is , out ) ; is . close ( ) ; } else { LOG . debug ( \"Ignoring folder: \" + file ) ; } } return new BufferedInputStream ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link IOFileFilter } which collects found files into a collection and also populates a map with found resources and corresponding files . [CODESPLIT] @ SuppressWarnings ( \"serial\" ) private IOFileFilter createWildcardCollectorFileFilter ( final WildcardContext wildcardContext , final Collection < File > allFiles ) { notNull ( wildcardContext ) ; notNull ( allFiles ) ; return new WildcardFileFilter ( wildcardContext . getWildcard ( ) ) { @ Override public boolean accept ( final File file ) { final boolean accept = super . accept ( file ) ; if ( accept ) { LOG . debug ( \"\\tfound resource: {}\" , file . getPath ( ) ) ; allFiles . add ( file ) ; } return accept ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates arguments used by { @link DefaultWildcardStreamLocator#findMatchedFiles ( String File ) } method . [CODESPLIT] private void validate ( final WildcardContext wildcardContext ) throws IOException { notNull ( wildcardContext ) ; final String uri = wildcardContext . getUri ( ) ; final File folder = wildcardContext . getFolder ( ) ; if ( uri == null || folder == null || ! folder . isDirectory ( ) ) { final StringBuffer message = new StringBuffer ( \"Invalid folder provided\" ) ; if ( folder != null ) { message . append ( \", with path: \" ) . append ( folder . getPath ( ) ) ; } message . append ( \", with fileNameWithWildcard: \" ) . append ( uri ) ; throw new IOException ( message . toString ( ) ) ; } if ( ! hasWildcard ( uri ) ) { throw new IOException ( \"No wildcard detected for the uri: \" + uri ) ; } LOG . debug ( \"uri: {}\" , uri ) ; LOG . debug ( \"folder: {}\" , folder . getPath ( ) ) ; LOG . debug ( \"wildcard: {}\" , wildcardContext . getWildcard ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the wildcardExpanderHandler to process all found files and directories . [CODESPLIT] void triggerWildcardExpander ( final Collection < File > allFiles , final WildcardContext wildcardContext ) throws IOException { LOG . debug ( \"wildcard resources: {}\" , allFiles ) ; if ( allFiles . isEmpty ( ) ) { final String message = String . format ( \"No resource found for wildcard: %s\" , wildcardContext . getWildcard ( ) ) ; LOG . warn ( message ) ; throw new IOException ( message ) ; } if ( wildcardExpanderHandler != null ) { try { wildcardExpanderHandler . apply ( allFiles ) ; } catch ( final IOException e ) { // preserve exception type if the exception is already an IOException\r throw e ; } catch ( final Exception e ) { LOG . debug ( \"wildcard expanding error. Reporting original exception\" , e ) ; throw new IOException ( \"Exception during expanding wildcard: \" + e . getMessage ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all occurrences of a substring within a string with another string . [CODESPLIT] private static String replace ( final String inString , final String oldPattern , final String newPattern ) { if ( ! hasLength ( inString ) || ! hasLength ( oldPattern ) || newPattern == null ) { return inString ; } final StringBuffer sbuf = new StringBuffer ( ) ; // output StringBuffer we'll build up int pos = 0 ; // our position in the old string int index = inString . indexOf ( oldPattern ) ; // the index of an occurrence we've found, or -1 final int patLen = oldPattern . length ( ) ; while ( index >= 0 ) { sbuf . append ( inString . substring ( pos , index ) ) ; sbuf . append ( newPattern ) ; pos = index + patLen ; index = inString . indexOf ( oldPattern , pos ) ; } sbuf . append ( inString . substring ( pos ) ) ; // remember to append any characters to the right of a match return sbuf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method to return a Collection as a delimited ( e . g . CSV ) String . E . g . useful for <code > toString () < / code > implementations . [CODESPLIT] private static String collectionToDelimitedString ( final Collection < String > coll , final String delim ) { return collectionToDelimitedString ( coll , delim , EMPTY , EMPTY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete any character in a given String . [CODESPLIT] private static String deleteAny ( final String inString , final String charsToDelete ) { if ( ! hasLength ( inString ) || ! hasLength ( charsToDelete ) ) { return inString ; } final StringBuffer out = new StringBuffer ( ) ; for ( int i = 0 ; i < inString . length ( ) ; i ++ ) { final char c = inString . charAt ( i ) ; if ( charsToDelete . indexOf ( c ) == - 1 ) { out . append ( c ) ; } } return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { LOG . debug ( \"processing resource: {}\" , resource ) ; final String content = IOUtils . toString ( reader ) ; final TypeScriptCompiler compiler = enginePool . getObject ( ) ; try { writer . write ( compiler . compile ( content ) ) ; } catch ( final Exception e ) { onException ( e , content ) ; } finally { // return for later reuse enginePool . returnObject ( compiler ) ; reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected String getArgument ( final Resource resource ) { final String name = resource == null ? \"\" : FilenameUtils . getBaseName ( resource . getUri ( ) ) ; return String . format ( \"'%s'\" , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] private RequestHandlerFactory newRequestHandlerFactory ( ) { final SimpleRequestHandlerFactory factory = new SimpleRequestHandlerFactory ( ) ; final List < RequestHandler > requestHandlers = getConfiguredStrategies ( ) ; for ( final RequestHandler requestHandler : requestHandlers ) { factory . addHandler ( requestHandler ) ; } // use default when none provided if ( requestHandlers . isEmpty ( ) ) { LOG . debug ( \"No locators configured. Using Default locator factory.\" ) ; return new DefaultRequestHandlerFactory ( ) ; } return factory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a single lint report to underlying collection . [CODESPLIT] public LintReport < T > addReport ( final ResourceLintReport < T > resourceLintReport ) { Validate . notNull ( resourceLintReport ) ; reports . add ( resourceLintReport ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { if ( builder == null ) { builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( DEFINE_WINDOW , \"window\" ) . evaluateChain ( getScriptAsStream ( ) , \"linter.js\" ) ; } return builder ; } catch ( final IOException e ) { throw new WroRuntimeException ( \"Failed reading init script\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates a js using jsHint and throws { @link LinterException } if the js is invalid . If no exception is thrown the js is valid . [CODESPLIT] public void validate ( final String data ) throws LinterException { final StopWatch watch = new StopWatch ( ) ; watch . start ( \"init\" ) ; final RhinoScriptBuilder builder = initScriptBuilder ( ) ; watch . stop ( ) ; watch . start ( \"lint\" ) ; final String packIt = buildLinterScript ( WroUtil . toJSMultiLineString ( data ) , getOptions ( ) ) ; final boolean valid = Boolean . parseBoolean ( builder . evaluate ( packIt , \"check\" ) . toString ( ) ) ; if ( ! valid ) { final String json = builder . addJSON ( ) . evaluate ( String . format ( \"JSON.stringify(JSON.decycle(%s.errors))\" , getLinterName ( ) ) , \"stringify errors\" ) . toString ( ) ; LOG . debug ( \"json {}\" , json ) ; final Type type = new TypeToken < List < LinterError > > ( ) { } . getType ( ) ; final List < LinterError > errors = new Gson ( ) . fromJson ( json , type ) ; LOG . debug ( \"errors {}\" , errors ) ; throw new LinterException ( ) . setErrors ( errors ) ; } LOG . debug ( \"result: {}\" , valid ) ; watch . stop ( ) ; LOG . debug ( watch . prettyPrint ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO this method is duplicated in { @link CssLint } . Extract and reuse it . [CODESPLIT] private String buildLinterScript ( final String data , final String options ) { return String . format ( \"%s(%s,%s);\" , getLinterName ( ) , data , optionsBuilder . buildFromCsv ( options ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reuse { [CODESPLIT] @ Override protected ProcessorsFactory newProcessorsFactory ( ) { return new ConfigurableProcessorsFactory ( ) { @ Override protected Properties newProperties ( ) { final Properties props = new Properties ( ) ; updatePropertiesWithConfiguration ( props , ConfigurableProcessorsFactory . PARAM_PRE_PROCESSORS ) ; updatePropertiesWithConfiguration ( props , ConfigurableProcessorsFactory . PARAM_POST_PROCESSORS ) ; return props ; } @ Override protected Map < String , ResourcePostProcessor > getPostProcessorStrategies ( final ProcessorProvider provider ) { final Map < String , ResourcePostProcessor > map = super . getPostProcessorStrategies ( provider ) ; contributePostProcessors ( map ) ; return map ; } @ Override protected Map < String , ResourcePreProcessor > getPreProcessorStrategies ( final ProcessorProvider provider ) { final Map < String , ResourcePreProcessor > map = super . getPreProcessorStrategies ( provider ) ; contributePreProcessors ( map ) ; return map ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add to properties a new key with value extracted either from filterConfig or from configurable properties file . This method helps to ensure backward compatibility of the filterConfig vs configProperties configuration . [CODESPLIT] private void updatePropertiesWithConfiguration ( final Properties props , final String key ) { final FilterConfig filterConfig = Context . get ( ) . getFilterConfig ( ) ; // first, retrieve value from init-param for backward compatibility final String valuesAsString = filterConfig . getInitParameter ( key ) ; if ( valuesAsString != null ) { props . setProperty ( key , valuesAsString ) ; } else { // retrieve value from configProperties file final String value = getConfigProperties ( ) . getProperty ( key ) ; if ( value != null ) { props . setProperty ( key , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this method rather than accessing the field directly because it will create a default one if none is provided . [CODESPLIT] private Properties getConfigProperties ( ) { if ( configProperties == null ) { configProperties = newConfigProperties ( ) ; if ( additionalConfigProperties != null ) { configProperties . putAll ( additionalConfigProperties ) ; } } return configProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override this method to provide a different config properties file location . It is very likely that you would like it to be the same as the one used by the { @link FilterConfigWroConfigurationFactory } . The default properties file location is / WEB - INF / wro . properties . [CODESPLIT] protected Properties newConfigProperties ( ) { // default location is /WEB-INF/wro.properties final Properties props = new Properties ( ) ; try { return new ServletContextPropertyWroConfigurationFactory ( Context . get ( ) . getServletContext ( ) ) . createProperties ( ) ; } catch ( final Exception e ) { LOG . warn ( \"No configuration property file found. Using default values.\" , e ) ; } return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be used for internal usage . Ensure that returned object is not null . [CODESPLIT] private Map < String , ResourcePreProcessor > getPreProcessorsMap ( ) { if ( this . preProcessorsMap == null ) { synchronized ( this ) { if ( this . preProcessorsMap == null ) { this . preProcessorsMap = newPreProcessorsMap ( ) ; } } } return this . preProcessorsMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be used for internal usage . Ensure that returned object is not null . [CODESPLIT] private Map < String , ResourcePostProcessor > getPostProcessorsMap ( ) { if ( this . postProcessorsMap == null ) { synchronized ( this ) { if ( this . postProcessorsMap == null ) { this . postProcessorsMap = newPostProcessorsMap ( ) ; } } } return this . postProcessorsMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public synchronized WroModel create ( ) { final StopWatch stopWatch = new StopWatch ( \"Create Wro Model from Groovy\" ) ; try { stopWatch . start ( \"createModel\" ) ; final Type type = new TypeToken < WroModel > ( ) { } . getType ( ) ; final InputStream is = getModelResourceAsStream ( ) ; if ( is == null ) { throw new WroRuntimeException ( \"Invalid model stream provided!\" ) ; } final WroModel model = new Gson ( ) . fromJson ( new InputStreamReader ( new AutoCloseInputStream ( is ) ) , type ) ; LOG . debug ( \"json model: {}\" , model ) ; if ( model == null ) { throw new WroRuntimeException ( \"Invalid content provided, cannot build model!\" ) ; } return model ; } catch ( final Exception e ) { throw new WroRuntimeException ( \"Invalid model found!\" , e ) ; } finally { stopWatch . stop ( ) ; LOG . debug ( stopWatch . prettyPrint ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this factory method when you want to use the { [CODESPLIT] public static SmartWroModelFactory createFromStandaloneContext ( final StandaloneContext context ) { notNull ( context ) ; final boolean autoDetectWroFile = WroUtil . normalize ( context . getWroFile ( ) . getPath ( ) ) . contains ( WroUtil . normalize ( DEFAULT_WRO_FILE ) ) ; if ( ! autoDetectWroFile ) { LOG . debug ( \"autoDetect is \" + autoDetectWroFile + \" because wroFile: \" + context . getWroFile ( ) + \" is not the same as the default one: \" + DEFAULT_WRO_FILE ) ; } return new SmartWroModelFactory ( ) . setWroFile ( context . getWroFile ( ) ) . setAutoDetectWroFile ( autoDetectWroFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the resource model auto detection . [CODESPLIT] private InputStream createAutoDetectedStream ( final String defaultFileName ) throws IOException { try { Validate . notNull ( wroFile , \"Cannot call this method if wroFile is null!\" ) ; if ( autoDetectWroFile ) { final File file = new File ( wroFile . getParentFile ( ) , defaultFileName ) ; LOG . debug ( \"\\tloading autodetected wro file: \" + file ) ; return new FileInputStream ( file ) ; } LOG . debug ( \"loading wroFile: \" + wroFile ) ; return new FileInputStream ( wroFile ) ; } catch ( final FileNotFoundException e ) { // When auto detect is turned on, do not skip trying.. because the auto detection assume that the wro file name\r // can be wrong.\r if ( autoDetectWroFile ) { throw e ; } throw new WroRuntimeException ( \"The wroFile doesn't exist. Skip trying with other wro model factories\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public WroModel create ( ) { if ( factoryList == null ) { factoryList = newWroModelFactoryFactoryList ( ) ; } if ( factoryList != null ) { // Holds the details about model creation which are logged only when no model can be created\r final StringBuffer logMessageBuffer = new StringBuffer ( ) ; for ( final WroModelFactory factory : factoryList ) { try { // use injector for aggregated modelFactories\r injector . inject ( factory ) ; final Class < ? extends WroModelFactory > factoryClass = factory . getClass ( ) . asSubclass ( WroModelFactory . class ) ; logMessageBuffer . append ( \" Using \" + getClassName ( factoryClass ) + \" for model creation..\\n\" ) ; return factory . create ( ) ; } catch ( final WroRuntimeException e ) { LOG . debug ( \"[FAIL] creating model... will try another factory: {}\" , e . getCause ( ) ) ; logMessageBuffer . append ( \"[FAIL] Model creation using \" + getClassName ( factory . getClass ( ) ) + \" failed. Trying another ...\\n\" ) ; logMessageBuffer . append ( \"[FAIL] Exception occured while building the model using: \" + getClassName ( factory . getClass ( ) ) + \" \" + e . getMessage ( ) ) ; // stop trying with other factories if the reason is IOException\r if ( ! autoDetectWroFile && e . getCause ( ) instanceof IOException ) { throw e ; } } } LOG . error ( logMessageBuffer . toString ( ) ) ; } throw new WroRuntimeException ( \"Cannot create model using any of provided factories\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all [CODESPLIT] public final String removeImportStatements ( ) { final StringBuffer sb = new StringBuffer ( ) ; while ( matcher . find ( ) ) { // replace @import with empty string matcher . appendReplacement ( sb , StringUtils . EMPTY ) ; } matcher . appendTail ( sb ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Map < String , ResourcePreProcessor > providePreProcessors ( ) { final Map < String , ResourcePreProcessor > map = new HashMap < String , ResourcePreProcessor > ( ) ; populateProcessorsMap ( map ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a map of postProcessors form a map of preProcessors . This method will be removed in 1 . 5 . 0 release when there will be no differences between pre & post processor interface . [CODESPLIT] private Map < String , ResourcePostProcessor > toPostProcessors ( final Map < String , ResourcePreProcessor > preProcessorsMap ) { final Map < String , ResourcePostProcessor > map = new HashMap < String , ResourcePostProcessor > ( ) ; for ( final Entry < String , ResourcePreProcessor > entry : preProcessorsMap . entrySet ( ) ) { map . put ( entry . getKey ( ) , new ProcessorDecorator ( entry . getValue ( ) ) ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The implementation uses jsr166 ForkJoinPool implementation in case it is available and can be used otherwise the default { @link ExecutorService } is used . [CODESPLIT] protected ExecutorService newExecutor ( ) { try { final ExecutorService executor = ( ExecutorService ) Class . forName ( \"java.util.concurrent.ForkJoinPool\" ) . newInstance ( ) ; LOG . debug ( \"Using ForkJoinPool as task executor.\" ) ; return executor ; } catch ( final Exception e ) { LOG . debug ( \"ForkJoinPool class is not available, using default executor.\" , e ) ; return Executors . newFixedThreadPool ( Runtime . getRuntime ( ) . availableProcessors ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO rename to submitAll . <p / > Submits a chunk of jobs for parallel execution . This is a blocking operation - it will end execution when all submitted tasks are finished . [CODESPLIT] public void submit ( final Collection < Callable < T > > callables ) throws Exception { Validate . notNull ( callables ) ; final StopWatch watch = new StopWatch ( ) ; watch . start ( \"init\" ) ; final long start = System . currentTimeMillis ( ) ; final AtomicLong totalTime = new AtomicLong ( ) ; LOG . debug ( \"running {} tasks\" , callables . size ( ) ) ; if ( callables . size ( ) == 1 ) { final T result = callables . iterator ( ) . next ( ) . call ( ) ; onResultAvailable ( result ) ; } else { LOG . debug ( \"Running tasks in parallel\" ) ; watch . stop ( ) ; watch . start ( \"submit tasks\" ) ; for ( final Callable < T > callable : callables ) { getCompletionService ( ) . submit ( decorate ( callable , totalTime ) ) ; } watch . stop ( ) ; watch . start ( \"consume results\" ) ; for ( int i = 0 ; i < callables . size ( ) ; i ++ ) { doConsumeResult ( ) ; } } watch . stop ( ) ; destroy ( ) ; LOG . debug ( \"Number of Tasks: {}\" , callables . size ( ) ) ; final long averageExecutionTime = callables . size ( ) != 0 ? totalTime . longValue ( ) / callables . size ( ) : 0 ; LOG . debug ( \"Average Execution Time: {}\" , averageExecutionTime ) ; LOG . debug ( \"Total Task Time: {}\" , totalTime ) ; LOG . debug ( \"Grand Total Execution Time: {}\" , System . currentTimeMillis ( ) - start ) ; LOG . debug ( watch . prettyPrint ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String content = IOUtils . toString ( reader ) ; final StringBuffer result = new JawrCssMinifier ( ) . minifyCSS ( new StringBuffer ( content ) ) ; writer . write ( result . toString ( ) ) ; writer . flush ( ) ; } catch ( final Exception e ) { final String resourceUri = resource == null ? StringUtils . EMPTY : \"[\" + resource . getUri ( ) + \"]\" ; String message = \"Exception while applying \" + getClass ( ) . getSimpleName ( ) + \" processor on the \" + resourceUri + \" resource\" ; LOG . error ( message , e ) ; throw new IOException ( message ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the javascript template into plain javascript . [CODESPLIT] public String compile ( final String content , final String optionalArgument ) { final RhinoScriptBuilder builder = initScriptBuilder ( ) ; final String argStr = createArgStr ( optionalArgument ) + createArgStr ( getArguments ( ) ) ; final String compileScript = String . format ( \"%s(%s%s);\" , getCompileCommand ( ) , WroUtil . toJSMultiLineString ( content ) , argStr ) ; return ( String ) builder . evaluate ( compileScript , getCompileCommand ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final AbstractJsTemplateCompiler jsCompiler = enginePool . getObject ( ) ; try { writer . write ( jsCompiler . compile ( content , getArgument ( resource ) ) ) ; } finally { enginePool . returnObject ( jsCompiler ) ; reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace provided url with the new url if needed . [CODESPLIT] @ Override protected String replaceImageUrl ( final String cssUri , final String imageUrl ) { Validate . notNull ( uriLocatorFactory ) ; LOG . debug ( \"replace url for image: {} from css: {}\" , imageUrl , cssUri ) ; final String cleanImageUrl = cleanImageUrl ( imageUrl ) ; final String fileName = FilenameUtils . getName ( imageUrl ) ; String fullPath = cleanImageUrl ; /**\r\n     * Allow dataUri transformation of absolute url's using http(s) protocol. All url's protocol are intentionally not\r\n     * allowed, because it could be a potential security issue. For instance:\r\n     *\r\n     * <pre>\r\n     * .class {\r\n     *   background: url(file:/path/to/secure/file.png);\r\n     * }\r\n     * </pre>\r\n     *\r\n     * This should not be allowed.\r\n     */ if ( isImageUrlChangeRequired ( cleanImageUrl ) ) { fullPath = WroUtil . getFullPath ( cssUri ) + cleanImageUrl ; } String result = imageUrl ; InputStream is = null ; try { is = uriLocatorFactory . locate ( fullPath ) ; final String dataUri = getDataUriGenerator ( ) . generateDataURI ( is , fileName ) ; if ( isReplaceAccepted ( dataUri ) ) { result = dataUri ; LOG . debug ( \"dataUri replacement: {}\" , StringUtils . abbreviate ( dataUri , 30 ) ) ; } } catch ( final IOException e ) { LOG . warn ( \"[FAIL] extract dataUri from: {}, because: {}. \" + \"A possible cause: using CssUrlRewritingProcessor before CssDataUriPreProcessor.\" , fullPath , e . getMessage ( ) ) ; } finally { IOUtils . closeQuietly ( is ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Similar to { @link CssDataUriPreProcessor#isReplaceAccepted ( String ) } but decides whether the computed dataUri should replace the image url . It is useful when you want to limit the dataUri size . By default the size of dataUri is limited to 32KB ( because IE8 has a 32KB limitation ) . [CODESPLIT] protected boolean isReplaceAccepted ( final String dataUri ) { try { final byte [ ] bytes = dataUri . getBytes ( CharEncoding . UTF_8 ) ; final boolean exceedLimit = bytes . length >= SIZE_LIMIT ; LOG . debug ( \"dataUri size: {}KB, limit exceeded: {}\" , bytes . length / 1024 , exceedLimit ) ; return ! exceedLimit ; } catch ( final UnsupportedEncodingException e ) { throw new WroRuntimeException ( \"Should never happen\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String content = IOUtils . toString ( reader ) ; final Matcher originalMatcher = PATTERN_COPYRIGHT . matcher ( content ) ; final StringBuffer copyrightBuffer = new StringBuffer ( ) ; while ( originalMatcher . find ( ) ) { LOG . debug ( \"found copyright comment\" ) ; // add copyright header to the buffer.\r copyrightBuffer . append ( originalMatcher . group ( ) ) ; } LOG . debug ( \"buffer: {}\" , copyrightBuffer ) ; final Writer processedWriter = new StringWriter ( ) ; getDecoratedObject ( ) . process ( resource , new StringReader ( content ) , processedWriter ) ; final Matcher processedMatcher = PATTERN_COPYRIGHT . matcher ( processedWriter . toString ( ) ) ; if ( ! processedMatcher . find ( ) ) { writer . write ( copyrightBuffer . toString ( ) ) ; } writer . write ( processedWriter . toString ( ) ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected ObjectFactory < WroConfiguration > newWroConfigurationFactory ( final FilterConfig filterConfig ) { if ( properties == null ) { // when no\r properties = new Properties ( ) ; properties . setProperty ( ConfigConstants . debug . name ( ) , String . valueOf ( debug ) ) ; properties . setProperty ( ConfigConstants . gzipResources . name ( ) , String . valueOf ( gzipEnabled ) ) ; properties . setProperty ( ConfigConstants . jmxEnabled . name ( ) , String . valueOf ( jmxEnabled ) ) ; properties . setProperty ( ConfigConstants . cacheUpdatePeriod . name ( ) , String . valueOf ( cacheUpdatePeriod ) ) ; properties . setProperty ( ConfigConstants . modelUpdatePeriod . name ( ) , String . valueOf ( modelUpdatePeriod ) ) ; properties . setProperty ( ConfigConstants . disableCache . name ( ) , String . valueOf ( disableCache ) ) ; if ( encoding != null ) { properties . setProperty ( ConfigConstants . encoding . name ( ) , encoding ) ; } if ( mbeanName != null ) { properties . setProperty ( ConfigConstants . mbeanName . name ( ) , mbeanName ) ; } } return new PropertyWroConfigurationFactory ( properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public WroModel create ( ) { WroModel newModel = null ; try { newModel = super . create ( ) ; } catch ( final WroRuntimeException e ) { LOG . error ( \"Error while creating the model\" , e ) ; } if ( newModel == null ) { LOG . warn ( \"Couldn't load new model, reusing last Valid Model!\" ) ; if ( lastValidModel == null ) { throw new WroRuntimeException ( \"No valid model was found!\" ) ; } return lastValidModel ; } lastValidModel = newModel ; return lastValidModel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String resourceContent = IOUtils . toString ( reader ) ; final Reader innerReader = new StringReader ( resourceContent ) ; final StringWriter innerWriter = new StringWriter ( ) ; try { super . process ( resource , innerReader , innerWriter ) ; writer . write ( innerWriter . toString ( ) ) ; } catch ( final Exception e ) { final String processorName = toString ( ) ; if ( isIgnoreFailingProcessor ( ) ) { LOG . debug ( \"Ignoring failed processor. Original Exception\" , e ) ; writer . write ( resourceContent ) ; // don't wrap exception unless required } else { LOG . error ( \"Failed to process the resource: {} using processor: {}. Reason: {}\" , resource , processorName , e . getMessage ( ) ) ; final String resourceUri = resource != null ? resource . getUri ( ) : null ; throw WroRuntimeException . wrap ( e , \"The processor: \" + processorName + \" faile while processing uri: \" + resourceUri ) . setResource ( resource ) ; } } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String encodeGroupUrl ( final String groupName , final ResourceType resourceType , final boolean minimize ) { return decorated . encodeGroupUrl ( groupName , resourceType , minimize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify all listeners about cachePeriod property changed . If passed newValue is null the oldValue is taken as new value . This is the case when the reloadCache is invoked . [CODESPLIT] private void reloadCacheWithNewValue ( final Long newValue ) { final long newValueAsPrimitive = newValue == null ? getCacheUpdatePeriod ( ) : newValue ; LOG . debug ( \"invoking {} listeners\" , cacheUpdatePeriodListeners . size ( ) ) ; for ( final PropertyChangeListener listener : cacheUpdatePeriodListeners ) { final PropertyChangeEvent event = new PropertyChangeEvent ( this , \"cache\" , getCacheUpdatePeriod ( ) , newValueAsPrimitive ) ; listener . propertyChange ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify all listeners about cachePeriod property changed . If passed newValue is null the oldValue is taken as new value . This is the case when the reloadModel is invoked . [CODESPLIT] private void reloadModelWithNewValue ( final Long newValue ) { final long newValueAsPrimitive = newValue == null ? getModelUpdatePeriod ( ) : newValue ; for ( final PropertyChangeListener listener : modelUpdatePeriodListeners ) { final PropertyChangeEvent event = new PropertyChangeEvent ( this , \"model\" , getModelUpdatePeriod ( ) , newValueAsPrimitive ) ; listener . propertyChange ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Map < String , ResourcePostProcessor > providePostProcessors ( ) { final Map < String , ResourcePostProcessor > resultMap = new HashMap < String , ResourcePostProcessor > ( ) ; /**\n     * Created to overcome the difference between {@link ResourcePreProcessor} and {@link ResourcePostProcessor}\n     * interfaces which will be resolved in next major version.\n     */ final Map < String , ResourcePreProcessor > preProcessorsMap = createMap ( ) ; for ( final Entry < String , ResourcePreProcessor > entry : preProcessorsMap . entrySet ( ) ) { resultMap . put ( entry . getKey ( ) , new ProcessorDecorator ( entry . getValue ( ) ) ) ; } return resultMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method . Creates a { @link SchedulerHelper } which consumes a factory providing a runnable . This approach allows lazy runnable initialization . [CODESPLIT] public static SchedulerHelper create ( final LazyInitializer < Runnable > runnableFactory , final String name ) { return new SchedulerHelper ( runnableFactory , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the scheduler with the provided period of time . If the scheduler is already started it will be stopped ( not before the running job is complete ) . [CODESPLIT] public SchedulerHelper scheduleWithPeriod ( final long period , final TimeUnit timeUnit ) { notNull ( timeUnit ) ; LOG . debug ( \"period: {} [{}]\" , period , timeUnit ) ; if ( this . period != period ) { this . period = period ; if ( ! poolInitializer . get ( ) . isShutdown ( ) ) { startScheduler ( period , timeUnit ) ; } else { LOG . warn ( \"Cannot schedule because destroy was already called!\" ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The following method shuts down an ExecutorService in two phases first by calling shutdown to reject incoming tasks and then calling shutdownNow if necessary to cancel any lingering tasks : [CODESPLIT] private synchronized void destroyScheduler ( ) { if ( ! poolInitializer . get ( ) . isShutdown ( ) ) { // Disable new tasks from being submitted poolInitializer . get ( ) . shutdown ( ) ; if ( future != null ) { future . cancel ( true ) ; } try { while ( ! poolInitializer . get ( ) . awaitTermination ( 5 , TimeUnit . SECONDS ) ) { LOG . debug ( \"Termination awaited: {}\" , name ) ; poolInitializer . get ( ) . shutdownNow ( ) ; } } catch ( final InterruptedException e ) { LOG . debug ( \"Interrupted Exception occured during scheduler destroy\" , e ) ; // (Re-)Cancel if current thread also interrupted poolInitializer . get ( ) . shutdownNow ( ) ; // Preserve interrupt status Thread . currentThread ( ) . interrupt ( ) ; } finally { LOG . debug ( \"[STOP] Scheduler terminated successfully! {}\" , name ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ ** When using JBoss Portal and it has some funny quirks ... actually a portal application have several small web application behind it . So when it intercepts a requests for portal then it start bombing the the application behind the portal with multiple threads ( web requests ) that are combined with threads for wro4j . [CODESPLIT] public InputStream getInputStream ( final HttpServletRequest request , final HttpServletResponse response , final String location ) throws IOException { if ( request == null || response == null || location == null ) { throw new IOException ( \"Cannot get stream for location: \" + location + \" because either request, response or location is not available\" ) ; } // where to write the bytes of the stream\r final ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; boolean warnOnEmptyStream = false ; try { final RequestDispatcher dispatcher = request . getRequestDispatcher ( location ) ; if ( dispatcher != null ) { // Wrap request\r final ServletRequest servletRequest = getWrappedServletRequest ( request , location ) ; // Wrap response\r final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper ( os , response ) ; LOG . debug ( \"dispatching request to location: {}\" , location ) ; // use dispatcher\r dispatcher . include ( servletRequest , servletResponse ) ; warnOnEmptyStream = true ; // force flushing - the content will be written to BytArrayOutputStream.\r // Otherwise exactly 32K of data will be written.\r servletResponse . getWriter ( ) . flush ( ) ; os . close ( ) ; } } catch ( final Exception e ) { LOG . debug ( \"Could not dispatch request for location {}\" , location ) ; // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside\r // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are\r // included.\r return locateExternal ( request , location ) ; } try { // fallback to external resource locator if the dispatcher is empty\r if ( os . size ( ) == 0 ) { return locateExternal ( request , location ) ; } } finally { if ( warnOnEmptyStream && os . size ( ) == 0 ) { LOG . debug ( \"Wrong or empty resource with location: {}\" , location ) ; } } return new ByteArrayInputStream ( os . toByteArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a wrapped servlet request which will be used for dispatching . [CODESPLIT] private ServletRequest getWrappedServletRequest ( final HttpServletRequest request , final String location ) { final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper ( request ) { @ Override public String getRequestURI ( ) { return getContextPath ( ) + location ; } @ Override public String getPathInfo ( ) { return WroUtil . getPathInfoFromLocation ( this , location ) ; } @ Override public String getServletPath ( ) { return WroUtil . getServletPathFromLocation ( this , location ) ; } } ; // add an attribute to mark this request as included from wro\r wrappedRequest . setAttribute ( ATTRIBUTE_INCLUDED_BY_DISPATCHER , Boolean . TRUE ) ; return wrappedRequest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setResourcePreProcessors ( final Collection < ResourcePreProcessor > processors ) { preProcessors . clear ( ) ; if ( processors != null ) { preProcessors . addAll ( processors ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setResourcePostProcessors ( final Collection < ResourcePostProcessor > processors ) { postProcessors . clear ( ) ; if ( processors != null ) { postProcessors . addAll ( processors ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { [CODESPLIT] public SimpleProcessorsFactory addPostProcessor ( final ResourcePostProcessor processor ) { if ( processor . getClass ( ) . isAnnotationPresent ( Minimize . class ) ) { //TODO move large messages to properties file\r LOG . warn ( \"It is recommended to add minimize aware processors to \" + \"pre processors instead of post processor, otherwise you \" + \"won't be able to disable minimization on specific resources \" + \"using minimize='false' attribute.\" ) ; } postProcessors . add ( processor ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { return RhinoScriptBuilder . newClientSideAwareChain ( ) . addJSON ( ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_JS ) ; } catch ( final Exception e ) { LOG . error ( \"Processing error:\" + e . getMessage ( ) , e ) ; throw new WroRuntimeException ( \"Processing error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ProviderFinder } which will find providers of type provided as argument .. [CODESPLIT] public static < T > ProviderFinder < T > of ( final Class < T > type ) { return new ProviderFinder < T > ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects also providers of type { @link ConfigurableProvider } if the T type is a supertype of { @link ConfigurableProvider } . If the type is already { @link ConfigurableProvider } it will be ignored to avoid adding of duplicate providers . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void collectConfigurableProviders ( final List < T > providers ) { if ( type . isAssignableFrom ( ConfigurableProvider . class ) && ( type != ConfigurableProvider . class ) ) { final Iterator < ConfigurableProvider > iterator = lookupProviders ( ConfigurableProvider . class ) ; for ( ; iterator . hasNext ( ) ; ) { final T provider = ( T ) iterator . next ( ) ; LOG . debug ( \"found provider: {}\" , provider ) ; providers . add ( provider ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is useful for mocking the lookup operation . The implementation will try to use java . util . ServiceLoader by default ( available in jdk6 ) and will fallback to ServiceRegistry for earlier JDK versions . The reason for this is to support GAE environment which doesn t contain the ServiceRegistry in its whitelist . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) < P > Iterator < P > lookupProviders ( final Class < P > providerClass ) { LOG . debug ( \"searching for providers of type : {}\" , providerClass ) ; try { final Class < ? > serviceLoader = getClass ( ) . getClassLoader ( ) . loadClass ( \"java.util.ServiceLoader\" ) ; LOG . debug ( \"using {} to lookupProviders\" , serviceLoader . getName ( ) ) ; return ( ( Iterable < P > ) serviceLoader . getMethod ( \"load\" , Class . class ) . invoke ( serviceLoader , providerClass ) ) . iterator ( ) ; } catch ( final Exception e ) { LOG . debug ( \"ServiceLoader is not available. Falling back to ServiceRegistry.\" , e ) ; } LOG . debug ( \"using {} to lookupProviders\" , ServiceRegistry . class . getName ( ) ) ; return ServiceRegistry . lookupProviders ( providerClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void doInit ( final FilterConfig filterConfig ) throws ServletException { String targetBeanName = filterConfig . getInitParameter ( PARAM_TARGET_BEAN_NAME ) ; // apply default targetBeanName targetBeanName = StringUtils . isEmpty ( targetBeanName ) ? DEFAULT_TARGET_BEAN_NAME : targetBeanName ; final WebApplicationContext ctx = WebApplicationContextUtils . getWebApplicationContext ( filterConfig . getServletContext ( ) ) ; factory = ( WroManagerFactory ) ctx . getBean ( targetBeanName , WroManagerFactory . class ) ; if ( factory == null ) { throw new WroRuntimeException ( \"Could not locate: \" + WroManagerFactory . class . getName ( ) + \" instance in applicationContext with bean name: \" + targetBeanName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The idea is to compute the aggregatedFolderPath based on a root folder . The root folder is determined by comparing the cssTargetFolder ( the folder where aggregated css files are located ) with build directory or contextFolder . If rootFolder is null then the result is also null ( equivalent to using the cssTargetFolder the same as the root folder . [CODESPLIT] public String resolve ( ) { notNull ( buildDirectory , \"Build directory cannot be null!\" ) ; notNull ( log , \"Logger cannot be null!\" ) ; String result = null ; final File cssTargetFolder = cssDestinationFolder == null ? destinationFolder : cssDestinationFolder ; File rootFolder = null ; notNull ( cssTargetFolder , \"cssTargetFolder cannot be null!\" ) ; if ( buildFinalName != null && cssTargetFolder . getPath ( ) . startsWith ( buildFinalName . getPath ( ) ) ) { rootFolder = buildFinalName ; } else if ( cssTargetFolder . getPath ( ) . startsWith ( buildDirectory . getPath ( ) ) ) { rootFolder = buildDirectory ; } else { // find first best match for ( final String contextFolder : getContextFolders ( ) ) { if ( cssTargetFolder . getPath ( ) . startsWith ( contextFolder ) ) { rootFolder = new File ( contextFolder ) ; break ; } } } log . debug ( \"buildDirectory: \" + buildDirectory ) ; log . debug ( \"contextFolders: \" + contextFoldersAsCSV ) ; log . debug ( \"cssTargetFolder: \" + cssTargetFolder ) ; log . debug ( \"rootFolder: \" + rootFolder ) ; if ( rootFolder != null ) { result = StringUtils . removeStart ( cssTargetFolder . getPath ( ) , rootFolder . getPath ( ) ) ; } log . debug ( \"computedAggregatedFolderPath: \" + result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use { [CODESPLIT] private String [ ] getContextFolders ( ) { final StandaloneContext context = new StandaloneContext ( ) ; context . setContextFoldersAsCSV ( contextFoldersAsCSV ) ; return context . getContextFolders ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] public static Transformer < String > extensionTransformer ( final String newExtension ) { return new Transformer < String > ( ) { public String transform ( final String input ) { return FilenameUtils . getBaseName ( input ) + \".\" + newExtension ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends a suffix to the source baseName . [CODESPLIT] public static Transformer < String > baseNameSuffixTransformer ( final String suffix ) { return new Transformer < String > ( ) { public String transform ( final String input ) { final String baseName = FilenameUtils . getBaseName ( input ) ; final String extension = FilenameUtils . getExtension ( input ) ; return baseName + suffix + \".\" + extension ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "action -- do something! What you do is determined by the argument : <ul > <li > 1 Output A . Copy B to A . Get the next B . < / li > <li > 2 Copy B to A . Get the next B . ( Delete A ) . < / li > <li > 3 Get the next B . ( Delete B ) . < / li > < / ul > action treats a string as a single character . Wow!<br / > action recognizes a regular expression if it is preceded by ( or or = . [CODESPLIT] void action ( final int d ) throws IOException , UnterminatedRegExpLiteralException , UnterminatedCommentException , UnterminatedStringLiteralException { switch ( d ) { case 1 : out . write ( theA ) ; if ( theA == theB && ( theA == ' ' || theA == ' ' ) && theY != theA ) { out . write ( ' ' ) ; } case 2 : theA = theB ; if ( theA == ' ' || theA == ' ' || theA == ' ' ) { for ( ; ; ) { out . write ( theA ) ; theA = get ( ) ; if ( theA == theB ) { break ; } if ( theA <= ' ' ) { throw new UnterminatedStringLiteralException ( ) ; } if ( theA == ' ' ) { out . write ( theA ) ; theA = get ( ) ; } } } case 3 : theB = next ( ) ; if ( theB == ' ' && ( theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' || theA == ' ' ) ) { out . write ( theA ) ; if ( theA == ' ' || theA == ' ' ) { out . write ( ' ' ) ; } out . write ( theB ) ; for ( ; ; ) { theA = get ( ) ; if ( theA == ' ' ) { for ( ; ; ) { out . write ( theA ) ; theA = get ( ) ; if ( theA == ' ' ) { break ; } if ( theA == ' ' ) { out . write ( theA ) ; theA = get ( ) ; } if ( theA <= ' ' ) { throw new UnterminatedRegExpLiteralException ( ) ; } } } else if ( theA == ' ' ) { switch ( peek ( ) ) { case ' ' : case ' ' : throw new UnterminatedRegExpLiteralException ( ) ; } break ; } else if ( theA == ' ' ) { out . write ( theA ) ; theA = get ( ) ; } else if ( theA <= ' ' ) { throw new UnterminatedRegExpLiteralException ( ) ; } out . write ( theA ) ; } theB = next ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a valid HTTP contentType s for a given filename . It first relies on the custom defaultContentTypeMap and if not found it will fall back to defaultFileTypeMap from javax . activation . FileTypeMap . Examples : - somefile . css resolves to text / css . - somefile . js . png resolves to image / png - / blah / index . html resolves to text / html . <p / > The implementation uses reflection to load <code > javax . activation . FileTypeMap< / code > class ( available in jdk6 ) in order to be compatible with jdk5 . If this class is not available the default content type is returned . [CODESPLIT] public static String get ( final String fileName ) { final String extension = FilenameUtils . getExtension ( WroUtil . removeQueryString ( fileName . toLowerCase ( ) ) ) ; if ( defaultContentTypeMap . containsKey ( extension ) ) { return defaultContentTypeMap . get ( extension ) ; } try { final Class < ? > fileTypeMapClass = ClassLoader . getSystemClassLoader ( ) . loadClass ( \"javax.activation.FileTypeMap\" ) ; LOG . debug ( \"using {} to resolve contentType\" , fileTypeMapClass . getName ( ) ) ; final Object fileTypeMap = fileTypeMapClass . getMethod ( \"getDefaultFileTypeMap\" ) . invoke ( fileTypeMapClass ) ; return ( String ) fileTypeMapClass . getMethod ( \"getContentType\" , String . class ) . invoke ( fileTypeMap , fileName ) ; } catch ( final Exception e ) { LOG . debug ( \"FileTypeMap is not available (probably jdk5 is used). Exception {}, with message: {}\" , e . getClass ( ) , e . getMessage ( ) ) ; LOG . debug ( \"Will use default content type: {} for fileName: {}\" , DEFAULT_CONTENT_TYPE , fileName ) ; } return DEFAULT_CONTENT_TYPE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a valid HTTP contentType s for a given filename with charset . It first relies on the custom defaultContentTypeMap and if not found it will fall back to defaultFileTypeMap from javax . activation . FileTypeMap . Examples : - ( somefile . css UTF - 8 ) resolves to text / css ; charset = UTF - 8 . - ( somefile . js . png UTF - 8 ) resolves to image / png - ( / blah / index . html UTF - 8 ) resolves to text / html ; charset = 8 [CODESPLIT] public static String get ( final String fileName , final String encoding ) { final String contentType = get ( fileName ) ; if ( requiresCharset . contains ( contentType ) ) { return contentType + \"; charset=\" + encoding ; } return contentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public InputStream locate ( final String uri ) throws IOException { Validate . notNull ( uri , \"URI cannot be NULL!\" ) ; // replace prefix & clean path by removing '..' characters if exists and // normalizing the location to use. String location = StringUtils . cleanPath ( uri . replaceFirst ( PREFIX , \"\" ) ) . trim ( ) ; if ( getWildcardStreamLocator ( ) . hasWildcard ( location ) ) { try { return locateWildcardStream ( uri , location ) ; } catch ( final IOException e ) { if ( location . contains ( \"?\" ) ) { location = DefaultWildcardStreamLocator . stripQueryPath ( location ) ; LOG . debug ( \"Trying fallback location: {}\" , location ) ; } } } final InputStream is = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( location ) ; if ( is == null ) { throw new IOException ( \"Couldn't get InputStream from this resource: \" + uri ) ; } return is ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a { [CODESPLIT] @ Override public WildcardStreamLocator newWildcardStreamLocator ( ) { return new JarWildcardStreamLocator ( ) { @ Override public boolean hasWildcard ( final String uri ) { return isEnableWildcards ( ) && super . hasWildcard ( uri ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Map < String , NamingStrategy > provideNamingStrategies ( ) { final Map < String , NamingStrategy > map = new HashMap < String , NamingStrategy > ( ) ; map . put ( TimestampNamingStrategy . ALIAS , new TimestampNamingStrategy ( ) ) ; map . put ( NoOpNamingStrategy . ALIAS , new NoOpNamingStrategy ( ) ) ; map . put ( DefaultHashEncoderNamingStrategy . ALIAS , new DefaultHashEncoderNamingStrategy ( ) ) ; map . put ( FolderHashEncoderNamingStrategy . ALIAS , new FolderHashEncoderNamingStrategy ( ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use an empty stream to avoid container writing unwanted message when a resource is missing . [CODESPLIT] private void onError ( final int sc , final String msg ) { LOG . debug ( \"Error detected with code: {} and message: {}\" , sc , msg ) ; final OutputStream emptyStream = new ByteArrayOutputStream ( ) ; printWriter = new PrintWriter ( emptyStream ) ; servletOutputStream = new DelegatingServletOutputStream ( emptyStream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "By default redirect does not allow writing to output stream its content . In order to support this use - case we need to open a new connection and read the content manually . [CODESPLIT] @ Override public void sendRedirect ( final String location ) throws IOException { try { LOG . debug ( \"redirecting to: {}\" , location ) ; final InputStream is = externalResourceLocator . locate ( location ) ; IOUtils . copy ( is , servletOutputStream ) ; is . close ( ) ; servletOutputStream . close ( ) ; } catch ( final IOException e ) { LOG . warn ( \"{}: Invalid response for location: {}\" , e . getClass ( ) . getName ( ) , location ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public synchronized WroModel transform ( final WroModel input ) { final WroModel model = input ; for ( final Group group : model . getGroups ( ) ) { final List < Resource > resources = group . getResources ( ) ; for ( final Resource resource : resources ) { processResource ( group , resource ) ; } } LOG . debug ( \"Transformed model: {}\" , model ) ; return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process each resource and replace it with a collection of resources if it contains wildcard . [CODESPLIT] private void processResource ( final Group group , final Resource resource ) { final UriLocator uriLocator = locatorFactory . getInstance ( resource . getUri ( ) ) ; if ( uriLocator instanceof WildcardUriLocatorSupport ) { final WildcardStreamLocator wildcardStreamLocator = ( ( WildcardUriLocatorSupport ) uriLocator ) . getWildcardStreamLocator ( ) ; // TODO should we probably handle the situation when wildcard is present, but the implementation is not // expandedHandledAware? if ( wildcardStreamLocator . hasWildcard ( resource . getUri ( ) ) && wildcardStreamLocator instanceof WildcardExpanderHandlerAware ) { final WildcardExpanderHandlerAware expandedHandler = ( WildcardExpanderHandlerAware ) wildcardStreamLocator ; LOG . debug ( \"Expanding resource: {}\" , resource . getUri ( ) ) ; final String baseNameFolder = computeBaseNameFolder ( resource , uriLocator , expandedHandler ) ; LOG . debug ( \"baseNameFolder: {}\" , baseNameFolder ) ; expandedHandler . setWildcardExpanderHandler ( createExpanderHandler ( group , resource , baseNameFolder ) ) ; try { // trigger the wildcard replacement uriLocator . locate ( resource . getUri ( ) ) ; } catch ( final IOException e ) { // log only LOG . debug ( \"[FAIL] problem while trying to expand wildcard for the following resource uri: {}\" , resource . getUri ( ) ) ; } finally { // remove the handler, it is not needed anymore expandedHandler . setWildcardExpanderHandler ( null ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the file name of the folder where the resource is located . The implementation uses a trick by invoking the { [CODESPLIT] private String computeBaseNameFolder ( final Resource resource , final UriLocator uriLocator , final WildcardExpanderHandlerAware expandedHandler ) { // Find the baseName // add a recursive wildcard to trigger the wildcard detection. The simple wildcard ('*') is not enough because it // won't work for folders containing only directories with no files. LOG . debug ( \"computeBaseNameFolder for resource {}\" , resource ) ; final String resourcePath = FilenameUtils . getFullPath ( resource . getUri ( ) ) + DefaultWildcardStreamLocator . RECURSIVE_WILDCARD ; LOG . debug ( \"resourcePath: {}\" , resourcePath ) ; // use thread local because we need to assign a File inside an anonymous class and it fits perfectly final ThreadLocal < String > baseNameFolderHolder = new ThreadLocal < String > ( ) ; expandedHandler . setWildcardExpanderHandler ( createBaseNameComputerFunction ( baseNameFolderHolder ) ) ; try { uriLocator . locate ( resourcePath ) ; } catch ( final Exception e ) { LOG . debug ( \"[FAIL] Exception caught during wildcard expanding for resource: {}\\n with exception message {}\" , resourcePath , e . getMessage ( ) ) ; } if ( baseNameFolderHolder . get ( ) == null ) { LOG . debug ( \"[FAIL] Cannot compute baseName folder for resource: {}\" , resource ) ; } return baseNameFolderHolder . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create the handler which expand the resources containing wildcard . [CODESPLIT] public Function < Collection < File > , Void > createExpanderHandler ( final Group group , final Resource resource , final String baseNameFolder ) { LOG . debug ( \"createExpanderHandler using baseNameFolder: {}\\n for resource {}\" , baseNameFolder , resource ) ; return new Function < Collection < File > , Void > ( ) { public Void apply ( final Collection < File > files ) { if ( baseNameFolder == null ) { // replacing group with empty list since the original uri has no associated resources. // No BaseNameFolder found LOG . warn ( \"The resource {} is probably invalid, removing it from the group.\" , resource ) ; group . replace ( resource , new ArrayList < Resource > ( ) ) ; } else { final List < Resource > expandedResources = new ArrayList < Resource > ( ) ; LOG . debug ( \"baseNameFolder: {}\" , baseNameFolder ) ; for ( final File file : files ) { final String resourcePath = getFullPathNoEndSeparator ( resource ) ; LOG . debug ( \"\\tresourcePath: {}\" , resourcePath ) ; LOG . debug ( \"\\tfile path: {}\" , file . getPath ( ) ) ; final String computedResourceUri = resourcePath + StringUtils . removeStart ( file . getPath ( ) , baseNameFolder ) . replace ( ' ' , ' ' ) ; final Resource expandedResource = Resource . create ( computedResourceUri , resource . getType ( ) ) ; LOG . debug ( \"\\texpanded resource: {}\" , expandedResource ) ; expandedResources . add ( expandedResource ) ; } LOG . debug ( \"\\treplace resource {}\" , resource ) ; group . replace ( resource , expandedResources ) ; } return null ; } /**\n       * This method fixes the problem when a resource in a group uses deep wildcard and starts at the root.\n       * <p/>\n       * Find more details <a href=\"https://github.com/alexo/wro4j/pull/44\">here</a>.\n       */ private String getFullPathNoEndSeparator ( final Resource resource1 ) { final String result = FilenameUtils . getFullPathNoEndSeparator ( resource1 . getUri ( ) ) ; if ( result != null && 1 == result . length ( ) && 0 == FilenameUtils . indexOfLastSeparator ( result ) ) { return \"\" ; } return result ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace provided url with the new url if needed . [CODESPLIT] @ Override protected final String replaceImageUrl ( final String cssUri , final String imageUrl ) { if ( ! imageUrls . contains ( imageUrl ) ) { imageUrls . add ( imageUrl ) ; return super . replaceImageUrl ( cssUri , imageUrl ) ; } LOG . debug ( \"duplicate Image url detected: '{}', skipping dataUri replacement\" , imageUrl ) ; return imageUrl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates an InputStream for the given uri . [CODESPLIT] public final InputStream locate ( final String uri ) throws IOException { final UriLocator uriLocator = getInstance ( uri ) ; if ( uriLocator == null ) { throw new WroRuntimeException ( \"No locator is capable of handling uri: \" + uri ) ; } LOG . debug ( \"[OK] locating {} using locator: {}\" , uri , uriLocator . getClass ( ) . getSimpleName ( ) ) ; return new AutoCloseInputStream ( uriLocator . locate ( uri ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { RhinoScriptBuilder builder = null ; if ( scope == null ) { builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( getCoffeeScriptAsStream ( ) , DEFAULT_COFFE_SCRIPT ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final IOException ex ) { throw new IllegalStateException ( \"Failed reading init script\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates a js using jsHint and throws { @link LinterException } if the js is invalid . If no exception is thrown the js is valid . [CODESPLIT] public String compile ( final String data ) { final RhinoScriptBuilder builder = initScriptBuilder ( ) ; final String compileScript = String . format ( \"CoffeeScript.compile(%s, %s);\" , WroUtil . toJSMultiLineString ( data ) , buildOptions ( ) ) ; return ( String ) builder . evaluate ( compileScript , \"CoffeeScript.compile\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates configuration by looking up in servletContext attributes . If none is found a new one will be created using the configuration factory . [CODESPLIT] private WroConfiguration createConfiguration ( ) { // Extract config from servletContext (if already configured) // TODO use a named helper final WroConfiguration configAttribute = ServletContextAttributeHelper . create ( filterConfig ) . getWroConfiguration ( ) ; if ( configAttribute != null ) { setConfiguration ( configAttribute ) ; } return getWroConfigurationFactory ( ) . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { [CODESPLIT] private WroManagerFactory createWroManagerFactory ( ) { if ( wroManagerFactory == null ) { final WroManagerFactory managerFactoryAttribute = ServletContextAttributeHelper . create ( filterConfig ) . getManagerFactory ( ) ; LOG . debug ( \"managerFactory attribute: {}\" , managerFactoryAttribute ) ; wroManagerFactory = managerFactoryAttribute != null ? managerFactoryAttribute : newWroManagerFactory ( ) ; } LOG . debug ( \"created managerFactory: {}\" , wroManagerFactory ) ; return wroManagerFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expose MBean to tell JMX infrastructure about our MBean ( only if jmxEnabled is true ) . [CODESPLIT] private void registerMBean ( ) { if ( wroConfiguration . isJmxEnabled ( ) ) { try { mbeanServer = getMBeanServer ( ) ; final ObjectName name = getMBeanObjectName ( ) ; if ( ! mbeanServer . isRegistered ( name ) ) { mbeanServer . registerMBean ( wroConfiguration , name ) ; } } catch ( final JMException e ) { LOG . error ( \"Exception occured while registering MBean\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register property change listeners . [CODESPLIT] private void registerChangeListeners ( ) { wroConfiguration . registerCacheUpdatePeriodChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( final PropertyChangeEvent event ) { // reset cache headers when any property is changed in order to avoid browser caching headersConfigurer = newResponseHeadersConfigurer ( ) ; wroManagerFactory . onCachePeriodChanged ( valueAsLong ( event . getNewValue ( ) ) ) ; } } ) ; wroConfiguration . registerModelUpdatePeriodChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( final PropertyChangeEvent event ) { headersConfigurer = newResponseHeadersConfigurer ( ) ; wroManagerFactory . onModelPeriodChanged ( valueAsLong ( event . getNewValue ( ) ) ) ; } } ) ; LOG . debug ( \"Cache & Model change listeners were registered\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform actual processing . [CODESPLIT] private void processRequest ( final HttpServletRequest request , final HttpServletResponse response ) throws ServletException , IOException { setResponseHeaders ( response ) ; // process the uri using manager wroManagerFactory . create ( ) . process ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when a { @link Exception } is thrown . Allows custom exception handling . The default implementation proceeds with filter chaining when exception is thrown . [CODESPLIT] protected void onException ( final Exception e , final HttpServletResponse response , final FilterChain chain ) { LOG . error ( \"Exception occured\" , e ) ; try { LOG . warn ( \"Cannot process. Proceeding with chain execution.\" ) ; chain . doFilter ( Context . get ( ) . getRequest ( ) , response ) ; } catch ( final Exception ex ) { // should never happen (use debug level to suppress unuseful logs) LOG . debug ( \"Error while chaining the request\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Once set this configuration will be used instead of the one built by the factory . [CODESPLIT] public final void setConfiguration ( final WroConfiguration config ) { notNull ( config ) ; wroConfigurationFactory = new ObjectFactory < WroConfiguration > ( ) { public WroConfiguration create ( ) { return config ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void destroy ( ) { //Avoid memory leak by unregistering mBean on destroy unregisterMBean ( ) ; if ( wroManagerFactory != null ) { wroManagerFactory . destroy ( ) ; } if ( wroConfiguration != null ) { wroConfiguration . destroy ( ) ; } Context . destroy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify duplicate group names . [CODESPLIT] private void identifyDuplicateGroupNames ( final Collection < Group > groups ) { LOG . debug ( \"identifyDuplicateGroupNames\" ) ; final List < String > groupNames = new ArrayList < String > ( ) ; for ( final Group group : groups ) { if ( groupNames . contains ( group . getName ( ) ) ) { throw new WroRuntimeException ( \"Duplicate group name detected: \" + group . getName ( ) ) ; } groupNames . add ( group . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge this model with another model . This is useful for supporting model imports . [CODESPLIT] public void merge ( final WroModel importedModel ) { Validate . notNull ( importedModel , \"imported model cannot be null!\" ) ; LOG . debug ( \"merging importedModel: {}\" , importedModel ) ; for ( final String groupName : new WroModelInspector ( importedModel ) . getGroupNames ( ) ) { if ( new WroModelInspector ( this ) . getGroupNames ( ) . contains ( groupName ) ) { throw new WroRuntimeException ( \"Duplicate group name detected: \" + groupName ) ; } final Group importedGroup = new WroModelInspector ( importedModel ) . getGroupByName ( groupName ) ; addGroup ( importedGroup ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final PackerJs packerJs = enginePool . getObject ( ) ; try { writer . write ( packerJs . pack ( content ) ) ; } catch ( final WroRuntimeException e ) { onException ( e ) ; final String resourceUri = resource == null ? StringUtils . EMPTY : \"[\" + resource . getUri ( ) + \"]\" ; LOG . warn ( \"Exception while applying \" + getClass ( ) . getSimpleName ( ) + \" processor on the \" + resourceUri + \" resource, no processing applied...\" , e ) ; } finally { reader . close ( ) ; writer . close ( ) ; enginePool . returnObject ( packerJs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation shows the problem with current design of locator implementation . Needs to be changed . [CODESPLIT] public InputStream locate ( final String uri ) throws IOException { final UriLocator locator = getInstance ( uri ) ; if ( locator == null ) { return getDecoratedObject ( ) . locate ( uri ) ; } return locator . locate ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final InputStream is = new ProxyInputStream ( new ReaderInputStream ( reader , getEncoding ( ) ) ) { } ; final OutputStream os = new ProxyOutputStream ( new WriterOutputStream ( writer , getEncoding ( ) ) ) ; try { new JSMin ( is , os ) . jsmin ( ) ; is . close ( ) ; os . close ( ) ; } catch ( final Exception e ) { throw WroRuntimeException . wrap ( e ) ; } finally { IOUtils . closeQuietly ( is ) ; IOUtils . closeQuietly ( os ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply resourcePostProcessors . [CODESPLIT] private String applyPostProcessors ( final CacheKey cacheKey , final String content ) throws IOException { final Collection < ResourcePostProcessor > processors = processorsFactory . getPostProcessors ( ) ; LOG . debug ( \"appying post processors: {}\" , processors ) ; if ( processors . isEmpty ( ) ) { return content ; } final Resource resource = Resource . create ( cacheKey . getGroupName ( ) , cacheKey . getType ( ) ) ; Reader reader = new StringReader ( content . toString ( ) ) ; Writer writer = null ; for ( final ResourcePostProcessor processor : processors ) { final ResourcePreProcessor decoratedProcessor = decorateProcessor ( processor , cacheKey . isMinimize ( ) ) ; writer = new StringWriter ( ) ; decoratedProcessor . process ( resource , reader , writer ) ; reader = new StringReader ( writer . toString ( ) ) ; } return writer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is synchronized to ensure that processor is injected before it is being used by other thread . [CODESPLIT] private synchronized ProcessorDecorator decorateProcessor ( final ResourcePostProcessor processor , final boolean minimize ) { final ProcessorDecorator decorated = new DefaultProcessorDecorator ( processor , minimize ) { @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { callbackRegistry . onBeforePostProcess ( ) ; super . process ( resource , reader , writer ) ; } finally { callbackRegistry . onAfterPostProcess ( ) ; } } } ; injector . inject ( decorated ) ; return decorated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void doFilter ( final ServletRequest req , final ServletResponse res , final FilterChain chain ) throws IOException , ServletException { final HttpServletRequest request = ( HttpServletRequest ) req ; final HttpServletResponse response = ( HttpServletResponse ) res ; //preserve current correlationId to ensure proper clean up during nested requests.\r final String originalCorrelationId = Context . isContextSet ( ) ? Context . getCorrelationId ( ) : null ; Context . set ( Context . webContext ( request , response , this . filterConfig ) , getWroConfiguration ( ) ) ; final String correlationId = Context . getCorrelationId ( ) ; try { chain . doFilter ( request , response ) ; } finally { Context . setCorrelationId ( correlationId ) ; Context . unset ( ) ; if ( originalCorrelationId != null ) { Context . setCorrelationId ( originalCorrelationId ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void doFilter ( final ServletRequest req , final ServletResponse res , final FilterChain chain ) throws IOException , ServletException { final HttpServletRequest request = ( HttpServletRequest ) req ; final HttpServletResponse response = ( HttpServletResponse ) res ; try { // add request, response & servletContext to thread local Context . set ( Context . webContext ( request , response , filterConfig ) ) ; final ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; final HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper ( os , response ) ; chain . doFilter ( request , wrappedResponse ) ; final Reader reader = new StringReader ( new String ( os . toByteArray ( ) , Context . get ( ) . getConfig ( ) . getEncoding ( ) ) ) ; final StringWriter writer = new StringWriter ( ) ; final String requestUri = request . getRequestURI ( ) . replaceFirst ( request . getContextPath ( ) , \"\" ) ; doProcess ( requestUri , reader , writer ) ; // it is important to update the contentLength to new value, otherwise the transfer can be closed without all // bytes being read. Some browsers (chrome) complains with the following message: ERR_CONNECTION_CLOSED final int contentLength = writer . getBuffer ( ) . length ( ) ; response . setContentLength ( contentLength ) ; // Content length can be 0 when the 30x (not modified) status code is returned. if ( contentLength > 0 ) { IOUtils . write ( writer . toString ( ) , response . getOutputStream ( ) ) ; } } catch ( final RuntimeException e ) { onRuntimeException ( e , response , chain ) ; } finally { Context . unset ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies configured processor on the intercepted stream . [CODESPLIT] private void doProcess ( final String requestUri , final Reader reader , final Writer writer ) throws IOException { Reader input = reader ; Writer output = null ; LOG . debug ( \"processing resource: {}\" , requestUri ) ; try { final StopWatch stopWatch = new StopWatch ( ) ; final Injector injector = InjectorBuilder . create ( new BaseWroManagerFactory ( ) ) . build ( ) ; final List < ResourcePreProcessor > processors = getProcessorsList ( ) ; if ( processors == null || processors . isEmpty ( ) ) { IOUtils . copy ( reader , writer ) ; } else { for ( final ResourcePreProcessor processor : processors ) { stopWatch . start ( \"Using \" + processor . getClass ( ) . getSimpleName ( ) ) ; // inject all required properties injector . inject ( processor ) ; output = new StringWriter ( ) ; LOG . debug ( \"Using {} processor\" , processor ) ; processor . process ( createResource ( requestUri ) , input , output ) ; input = new StringReader ( output . toString ( ) ) ; stopWatch . stop ( ) ; } LOG . debug ( stopWatch . prettyPrint ( ) ) ; if ( output != null ) { writer . write ( output . toString ( ) ) ; } } } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when a { @link RuntimeException } is thrown . Allows custom exception handling . The default implementation redirects to 404 for a specific { @link WroRuntimeException } exception when in DEPLOYMENT mode . [CODESPLIT] protected void onRuntimeException ( final RuntimeException e , final HttpServletResponse response , final FilterChain chain ) { LOG . debug ( \"RuntimeException occured\" , e ) ; try { LOG . debug ( \"Cannot process. Proceeding with chain execution.\" ) ; chain . doFilter ( Context . get ( ) . getRequest ( ) , response ) ; } catch ( final Exception ex ) { // should never happen LOG . error ( \"Error while chaining the request.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split multiple options into an array of options . [CODESPLIT] public String [ ] splitOptions ( final String optionAsString ) { return optionAsString == null ? ArrayUtils . EMPTY_STRING_ARRAY : optionAsString . split ( \"(?ims),(?![^\\\\[\\\\]]*\\\\])\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { RhinoScriptBuilder builder = null ; if ( scope == null ) { builder = RhinoScriptBuilder . newClientSideAwareChain ( ) . addJSON ( ) . evaluateChain ( getScriptAsStream ( ) , \"cjson.js\" ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final Exception e ) { LOG . error ( \"Processing error:\" + e . getMessage ( ) , e ) ; throw new WroRuntimeException ( \"Processing error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { RhinoScriptBuilder builder = null ; if ( scope == null ) { final InputStream initStream = LessCss . class . getResourceAsStream ( SCRIPT_INIT ) ; builder = RhinoScriptBuilder . newClientSideAwareChain ( ) . evaluateChain ( initStream , SCRIPT_INIT ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_LESS_JS ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final IOException ex ) { throw new IllegalStateException ( \"Failed reading javascript less.js\" , ex ) ; } catch ( final Exception e ) { LOG . error ( \"Processing error:\" + e . getMessage ( ) , e ) ; throw new WroRuntimeException ( \"Processing error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the properties from the stream . The implementation will handle comments properly by removing them before properties are loaded . [CODESPLIT] public Properties load ( final InputStream inputStream ) throws IOException { Validate . notNull ( inputStream ) ; final String rawContent = IOUtils . toString ( inputStream , CharEncoding . UTF_8 ) ; parseProperties ( rawContent . replaceAll ( REGEX_COMMENTS , \"\" ) ) ; return this . properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse the properties from the provided string containing a raw properties [CODESPLIT] private void parseProperties ( final String propertiesAsString ) { //should work also \\r?\\n final String [ ] propertyEntries = propertiesAsString . split ( \"\\\\r?\\\\n\" ) ; for ( final String entry : propertyEntries ) { readPropertyEntry ( entry ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] private StandaloneContext createStandaloneContext ( ) { final StandaloneContext runContext = new StandaloneContext ( ) ; runContext . setContextFoldersAsCSV ( getContextFoldersAsCSV ( ) ) ; runContext . setMinimize ( isMinimize ( ) ) ; runContext . setWroFile ( getWroFile ( ) ) ; runContext . setIgnoreMissingResourcesAsString ( isIgnoreMissingResources ( ) ) ; return runContext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will ensure that you have a right and initialized instance of { @link StandaloneContextAware } . [CODESPLIT] protected final WroManagerFactory getManagerFactory ( ) { if ( managerFactory == null ) { try { managerFactory = wroManagerFactory != null ? createCustomManagerFactory ( ) : newWroManagerFactory ( ) ; onAfterCreate ( managerFactory ) ; } catch ( final MojoExecutionException e ) { throw WroRuntimeException . wrap ( e ) ; } } return managerFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a custom instance of Manager factory . The wroManagerFactory parameter value is used to identify the manager class . [CODESPLIT] private WroManagerFactory createCustomManagerFactory ( ) throws MojoExecutionException { WroManagerFactory factory = null ; try { final Class < ? > wroManagerFactoryClass = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( wroManagerFactory . trim ( ) ) ; factory = ( WroManagerFactory ) wroManagerFactoryClass . newInstance ( ) ; } catch ( final Exception e ) { throw new MojoExecutionException ( \"Invalid wroManagerFactoryClass, called: \" + wroManagerFactory , e ) ; } return factory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows explicitly to override the default implementation of the factory assuming { [CODESPLIT] protected WroManagerFactory newWroManagerFactory ( ) throws MojoExecutionException { WroManagerFactory factory = null ; if ( wroManagerFactory == null ) { factory = new ConfigurableWroManagerFactory ( ) ; } getLog ( ) . info ( \"wroManagerFactory class: \" + factory . getClass ( ) . getName ( ) ) ; return factory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the created { [CODESPLIT] private void onAfterCreate ( final WroManagerFactory factory ) throws MojoExecutionException { if ( factory instanceof ExtraConfigFileAware ) { if ( extraConfigFile == null ) { throw new MojoExecutionException ( \"The \" + factory . getClass ( ) + \" requires a valid extraConfigFile!\" ) ; } getLog ( ) . debug ( \"Using extraConfigFile: \" + extraConfigFile . getAbsolutePath ( ) ) ; ( ( ExtraConfigFileAware ) factory ) . setExtraConfigFile ( extraConfigFile ) ; } // initialize before process. if ( factory instanceof StandaloneContextAware ) { ( ( StandaloneContextAware ) factory ) . initialize ( createStandaloneContext ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store digest for all resources contained inside the list of provided groups . [CODESPLIT] private void persistResourceFingerprints ( final List < String > groupNames ) { final WroModelInspector modelInspector = new WroModelInspector ( getModel ( ) ) ; for ( final String groupName : groupNames ) { final Group group = modelInspector . getGroupByName ( groupName ) ; if ( group != null ) { for ( final Resource resource : group . getResources ( ) ) { getResourceChangeHandler ( ) . remember ( resource ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the provided group is a target group . [CODESPLIT] private boolean isTargetGroup ( final Group group ) { notNull ( group ) ; final String targetGroups = getTargetGroups ( ) ; // null, means all groups are target groups return targetGroups == null || targetGroups . contains ( group . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the classpath . [CODESPLIT] protected final void extendPluginClasspath ( ) throws MojoExecutionException { // this code is inspired from http://teleal.org/weblog/Extending%20the%20Maven%20plugin%20classpath.html final List < String > classpathElements = new ArrayList < String > ( ) ; try { classpathElements . addAll ( mavenProject . getRuntimeClasspathElements ( ) ) ; } catch ( final DependencyResolutionRequiredException e ) { throw new MojoExecutionException ( \"Could not get compile classpath elements\" , e ) ; } final ClassLoader classLoader = createClassLoader ( classpathElements ) ; Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected boolean isEnabled ( final Resource resource ) { // apply processor only when minimize is required or the processor is not minimize aware final boolean applyProcessor = ( resource != null && resource . isMinimize ( ) && minimize ) || ( resource == null && minimize ) || ! isMinimize ( ) ; return super . isEnabled ( resource ) && applyProcessor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override this method in order to provide different xml definition file name . [CODESPLIT] protected InputStream getModelResourceAsStream ( ) throws IOException { final ServletContext servletContext = context . getServletContext ( ) ; // Don't allow NPE, throw a more detailed exception\r if ( servletContext == null ) { throw new WroRuntimeException ( \"No servletContext is available. Probably you are running this code outside of the request cycle!\" ) ; } final String resourceLocation = \"/WEB-INF/\" + getDefaultModelFilename ( ) ; final InputStream stream = servletContext . getResourceAsStream ( resourceLocation ) ; if ( stream == null ) { throw new IOException ( \"Invalid resource requested: \" + resourceLocation ) ; } return stream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a resource and set the correct { @link ResourceType } based on uri extension . If resourceType cannot be identified an exception is thrown . [CODESPLIT] public static Resource create ( final String uri ) { final String resourceExtension = FilenameUtils . getExtension ( uri ) ; final ResourceType type = ResourceType . get ( resourceExtension ) ; return new Resource ( uri , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a cleaning of the uri by trimming it and removing last / character if exists . [CODESPLIT] private static String cleanUri ( final String uri ) { String result = uri . trim ( ) ; //handle empty uri\r if ( ! StringUtils . isEmpty ( uri ) ) { final int endIndex = result . length ( ) - 1 ; if ( result . lastIndexOf ( ' ' ) == endIndex ) { result = result . substring ( 0 , endIndex ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public InputStream locate ( final String uri ) throws IOException { notNull ( uri , \"uri cannot be NULL!\" ) ; if ( getWildcardStreamLocator ( ) . hasWildcard ( uri ) ) { final String fullPath = FilenameUtils . getFullPath ( uri ) ; final URL url = new URL ( fullPath ) ; return getWildcardStreamLocator ( ) . locateStream ( uri , new File ( URLDecoder . decode ( url . getFile ( ) , \"UTF-8\" ) ) ) ; } final URL url = new URL ( uri ) ; final URLConnection connection = url . openConnection ( ) ; // avoid jar file locking on Windows. connection . setUseCaches ( false ) ; //add explicit user agent header. This is required by some cdn resources which otherwise would return 403 status code. connection . setRequestProperty ( \"User-Agent\" , \"java\" ) ; // setting these timeouts ensures the client does not deadlock indefinitely // when the server has problems. connection . setConnectTimeout ( timeout ) ; connection . setReadTimeout ( timeout ) ; return new BufferedInputStream ( connection . getInputStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String content = IOUtils . toString ( reader ) ; String result = ConsoleStripperProcessor . PATTERN . matcher ( content ) . replaceAll ( \"\" ) ; writer . write ( result ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A factory method which uses { @link WroConfiguration } to get the configured wroManager className . [CODESPLIT] public static DefaultWroManagerFactory create ( final WroConfiguration configuration ) { return create ( new ObjectFactory < WroConfiguration > ( ) { public WroConfiguration create ( ) { return configuration ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialized inner factory based on provided configuration . [CODESPLIT] private WroManagerFactory initFactory ( final Properties properties ) { WroManagerFactory factory = null ; final String wroManagerClassName = properties . getProperty ( ConfigConstants . managerFactoryClassName . name ( ) ) ; if ( StringUtils . isEmpty ( wroManagerClassName ) ) { // If no context param was specified we return the default factory factory = newManagerFactory ( ) ; } else { // Try to find the specified factory class Class < ? > factoryClass = null ; try { factoryClass = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( wroManagerClassName ) ; factory = ( WroManagerFactory ) factoryClass . newInstance ( ) ; } catch ( final Exception e ) { throw new WroRuntimeException ( \"Exception while loading WroManagerFactory class:\" + wroManagerClassName , e ) ; } } // add properties if required if ( factory instanceof ConfigurableWroManagerFactory ) { ( ( ConfigurableWroManagerFactory ) factory ) . addConfigProperties ( properties ) ; } return factory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { return RhinoScriptBuilder . newChain ( ) . evaluateChain ( getStreamForBase2 ( ) , \"base2.min.js\" ) . evaluateChain ( getStreamForPacker ( ) , \"packer.min.js\" ) ; } catch ( final IOException ex ) { throw new IllegalStateException ( \"Failed reading init script\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a list of transformers to apply on decorated model factory . [CODESPLIT] public ModelTransformerFactory setTransformers ( final List < Transformer < WroModel > > modelTransformers ) { Validate . notNull ( modelTransformers ) ; this . modelTransformers = modelTransformers ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public WroModel create ( ) { WroModel model = super . create ( ) ; LOG . debug ( \"using {} transformers\" , modelTransformers ) ; for ( final Transformer < WroModel > transformer : modelTransformers ) { injector . inject ( transformer ) ; LOG . debug ( \"using transformer: {}\" , transformer . getClass ( ) ) ; try { model = transformer . transform ( model ) ; } catch ( final Exception e ) { throw new WroRuntimeException ( \"Exception during model transformation\" , e ) ; } } return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "visible for testing the init of a HandlebarsJs template [CODESPLIT] @ Override public String compile ( final String content , final String name ) { final String precompiledFunction = super . compile ( content , \"\" ) ; return String . format ( \"(function() {Ember.TEMPLATES[%s] = Ember.Handlebars.template(%s)})();\" , name , precompiledFunction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected InputStream getCompilerAsStream ( ) throws IOException { final Vector < InputStream > inputStreams = new Vector < InputStream > ( ) ; inputStreams . add ( getWebjarLocator ( ) . locate ( WebjarUriLocator . createUri ( \"jquery.js\" ) ) ) ; inputStreams . add ( getWebjarLocator ( ) . locate ( WebjarUriLocator . createUri ( \"handlebars.js\" ) ) ) ; inputStreams . add ( getWebjarLocator ( ) . locate ( WebjarUriLocator . createUri ( \"ember.js\" ) ) ) ; inputStreams . add ( EmberJs . class . getResourceAsStream ( DEFAULT_HEADLESS_RHINO_JS ) ) ; return new SequenceInputStream ( inputStreams . elements ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if url must be replaced or not . The replacement is not needed if the url of the image is absolute ( can be resolved by urlResourceLocator ) or if the url is a data uri ( base64 encoded value ) . [CODESPLIT] protected boolean isReplaceNeeded ( final String url ) { return ! ( UrlUriLocator . isValid ( url ) || DataUriGenerator . isDataUri ( url . trim ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply preProcessors on resources and merge them after all preProcessors are applied . [CODESPLIT] public String processAndMerge ( final List < Resource > resources , final boolean minimize ) throws IOException { return processAndMerge ( resources , ProcessingCriteria . create ( ProcessingType . ALL , minimize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply preProcessors on resources and merge them . [CODESPLIT] public String processAndMerge ( final List < Resource > resources , final ProcessingCriteria criteria ) throws IOException { notNull ( criteria ) ; LOG . debug ( \"criteria: {}\" , criteria ) ; callbackRegistry . onBeforeMerge ( ) ; try { notNull ( resources ) ; LOG . debug ( \"process and merge resources: {}\" , resources ) ; final StringBuffer result = new StringBuffer ( ) ; if ( shouldRunInParallel ( resources ) ) { result . append ( runInParallel ( resources , criteria ) ) ; } else { for ( final Resource resource : resources ) { LOG . debug ( \"\\tmerging resource: {}\" , resource ) ; result . append ( applyPreProcessors ( resource , criteria ) ) ; } } return result . toString ( ) ; } finally { callbackRegistry . onAfterMerge ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "runs the pre processors in parallel . [CODESPLIT] private String runInParallel ( final List < Resource > resources , final ProcessingCriteria criteria ) throws IOException { LOG . debug ( \"Running preProcessing in Parallel\" ) ; final StringBuffer result = new StringBuffer ( ) ; final List < Callable < String > > callables = new ArrayList < Callable < String > > ( ) ; for ( final Resource resource : resources ) { callables . add ( new Callable < String > ( ) { public String call ( ) throws Exception { LOG . debug ( \"Callable started for resource: {} ...\" , resource ) ; return applyPreProcessors ( resource , criteria ) ; } } ) ; } final ExecutorService exec = getExecutorService ( ) ; final List < Future < String > > futures = new ArrayList < Future < String > > ( ) ; for ( final Callable < String > callable : callables ) { // decorate with ContextPropagatingCallable in order to allow spawn threads to access the Context final Callable < String > decoratedCallable = new ContextPropagatingCallable < String > ( callable ) ; futures . add ( exec . submit ( decoratedCallable ) ) ; } for ( final Future < String > future : futures ) { try { result . append ( future . get ( ) ) ; } catch ( final Exception e ) { // propagate original cause final Throwable cause = e . getCause ( ) ; if ( cause instanceof WroRuntimeException ) { throw ( WroRuntimeException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else { throw new WroRuntimeException ( \"Problem during parallel pre processing\" , e ) ; } } } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply a list of preprocessors on a resource . [CODESPLIT] private String applyPreProcessors ( final Resource resource , final ProcessingCriteria criteria ) throws IOException { final Collection < ResourcePreProcessor > processors = processorsFactory . getPreProcessors ( ) ; LOG . debug ( \"applying preProcessors: {}\" , processors ) ; String resourceContent = null ; try { resourceContent = getResourceContent ( resource ) ; } catch ( final IOException e ) { LOG . debug ( \"Invalid resource found: {}\" , resource ) ; if ( Context . get ( ) . getConfig ( ) . isIgnoreMissingResources ( ) ) { return StringUtils . EMPTY ; } else { LOG . error ( \"Cannot ignore missing resource:  {}\" , resource ) ; throw e ; } } if ( ! processors . isEmpty ( ) ) { Writer writer = null ; for ( final ResourcePreProcessor processor : processors ) { final ResourcePreProcessor decoratedProcessor = decoratePreProcessor ( processor , criteria ) ; writer = new StringWriter ( ) ; final Reader reader = new StringReader ( resourceContent ) ; // decorate and process decoratedProcessor . process ( resource , reader , writer ) ; // use the outcome for next input resourceContent = writer . toString ( ) ; } } // add explicitly new line at the end to avoid unexpected comment issue return String . format ( \"%s%n\" , resourceContent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorates preProcessor with mandatory decorators . This method is synchronized to ensure that processor is injected before it is being used by other thread . [CODESPLIT] private synchronized ResourcePreProcessor decoratePreProcessor ( final ResourcePreProcessor processor , final ProcessingCriteria criteria ) { final ResourcePreProcessor decorated = new DefaultProcessorDecorator ( processor , criteria ) { @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { callbackRegistry . onBeforePreProcess ( ) ; super . process ( resource , reader , writer ) ; } finally { callbackRegistry . onAfterPreProcess ( ) ; } } } ; injector . inject ( decorated ) ; return decorated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onBeforeModelCreated ( ) { forEachCallbackDo ( new Function < LifecycleCallback , Void > ( ) { public Void apply ( final LifecycleCallback input ) throws Exception { input . onBeforeModelCreated ( ) ; return null ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persist the fallbackStorage to the fallbackStorageFile . This method should be invoked only once during build since it is relatively expensive . Not invoking it would break the incremental build feature . [CODESPLIT] public void persist ( ) { OutputStream os = null ; try { os = new FileOutputStream ( fallbackStorageFile ) ; fallbackStorage . store ( os , \"Generated\" ) ; LOG . debug ( \"fallback storage written to {}\" , fallbackStorageFile ) ; } catch ( final IOException e ) { LOG . warn ( \"Cannot persist fallback storage: {}.\" , fallbackStorageFile , e ) ; } finally { IOUtils . closeQuietly ( os ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans the object and inject the supported values into the fields having @Inject annotation present . [CODESPLIT] public < T > T inject ( final T object ) { notNull ( object ) ; //    if (!Context.isContextSet()) {\r //      throw new WroRuntimeException(\"No Context Set\");\r //    }\r if ( ! injectedObjects . containsKey ( computeKey ( object ) ) ) { injectedObjects . put ( computeKey ( object ) , true ) ; processInjectAnnotation ( object ) ; } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for each field from the passed object if @Inject annotation is present & inject the required field if supported otherwise warns about invalid usage . [CODESPLIT] private void processInjectAnnotation ( final Object object ) { try { final Collection < Field > fields = getAllFields ( object ) ; for ( final Field field : fields ) { if ( field . isAnnotationPresent ( Inject . class ) ) { if ( ! acceptAnnotatedField ( object , field ) ) { final String message = String . format ( \"@Inject cannot be applied on object: %s to field of type: %s using injector %s\" , object , field . getType ( ) , this ) ; LOG . error ( message + \". Supported types are: {}\" , map . keySet ( ) ) ; throw new WroRuntimeException ( message ) ; } } } // handle special cases like decorators. Perform recursive injection\r if ( object instanceof ObjectDecorator ) { processInjectAnnotation ( ( ( ObjectDecorator < ? > ) object ) . getDecoratedObject ( ) ) ; } } catch ( final Exception e ) { LOG . error ( \"Error while scanning @Inject annotation\" , e ) ; throw WroRuntimeException . wrap ( e , \"Exception while trying to process @Inject annotation on object: \" + object ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all fields for given object also those from the super classes . [CODESPLIT] private Collection < Field > getAllFields ( final Object object ) { final Collection < Field > fields = new ArrayList < Field > ( ) ; fields . addAll ( Arrays . asList ( object . getClass ( ) . getDeclaredFields ( ) ) ) ; // inspect super classes\r Class < ? > superClass = object . getClass ( ) . getSuperclass ( ) ; while ( superClass != null ) { fields . addAll ( Arrays . asList ( superClass . getDeclaredFields ( ) ) ) ; superClass = superClass . getSuperclass ( ) ; } return fields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyze the field containing { @link Inject } annotation and set its value to appropriate value . Override this method if you want to inject something else but uriLocatorFactory . [CODESPLIT] private boolean acceptAnnotatedField ( final Object object , final Field field ) throws IllegalAccessException { boolean accept = false ; // accept private modifiers\r field . setAccessible ( true ) ; for ( final Map . Entry < Class < ? > , Object > entry : map . entrySet ( ) ) { if ( entry . getKey ( ) . isAssignableFrom ( field . getType ( ) ) ) { Object value = entry . getValue ( ) ; // treat factories as a special case for lazy load of the objects.\r if ( value instanceof InjectorObjectFactory ) { value = ( ( InjectorObjectFactory < ? > ) value ) . create ( ) ; inject ( value ) ; } field . set ( object , value ) ; accept = true ; break ; } } return accept ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the url of the image to be replaced in a css resource . [CODESPLIT] public String rewrite ( final String cssUri , final String imageUrl ) { notNull ( cssUri ) ; notNull ( imageUrl ) ; if ( StringUtils . isEmpty ( imageUrl ) ) { return imageUrl ; } if ( ServletContextUriLocator . isValid ( cssUri ) ) { if ( ServletContextUriLocator . isValid ( imageUrl ) ) { return prependContextPath ( imageUrl ) ; } // Treat WEB-INF special case if ( ServletContextUriLocator . isProtectedResource ( cssUri ) ) { return context . proxyPrefix + computeNewImageLocation ( cssUri , imageUrl ) ; } // Compute the folder where the final css is located. This is important for computing image location after url // rewriting. // Prefix of the path to the overwritten image url. This will be of the following type: \"../\" or \"../..\" depending // on the depth of the aggregatedFolderPath. final String aggregatedPathPrefix = computeAggregationPathPrefix ( context . aggregatedFolderPath ) ; LOG . debug ( \"computed aggregatedPathPrefix {}\" , aggregatedPathPrefix ) ; String newImageLocation = computeNewImageLocation ( aggregatedPathPrefix + cssUri , imageUrl ) ; if ( newImageLocation . startsWith ( ServletContextUriLocator . PREFIX ) ) { newImageLocation = prependContextPath ( newImageLocation ) ; } LOG . debug ( \"newImageLocation: {}\" , newImageLocation ) ; return newImageLocation ; } if ( ClasspathUriLocator . isValid ( cssUri ) ) { final String proxyUrl = context . proxyPrefix + computeNewImageLocation ( cssUri , imageUrl ) ; final String contextRelativeUrl = prependContextPath ( imageUrl ) ; //final String contextRelativeUrl = context.contextPath + imageUrl; // leave imageUrl unchanged if it is a servlet context relative resource return ( ServletContextUriLocator . isValid ( imageUrl ) ? contextRelativeUrl : proxyUrl ) ; } if ( UrlUriLocator . isValid ( cssUri ) ) { final String computedCssUri = ServletContextUriLocator . isValid ( imageUrl ) ? computeCssUriForExternalServer ( cssUri ) : cssUri ; return computeNewImageLocation ( computedCssUri , imageUrl ) ; } throw new WroRuntimeException ( \"Could not replace imageUrl: \" + imageUrl + \", contained at location: \" + cssUri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Css files hosted on external server should use its host as the root context when rewriting image url s starting with / character . [CODESPLIT] private String computeCssUriForExternalServer ( final String cssUri ) { String exernalServerCssUri = cssUri ; try { // compute the host of the external server (with protocol & port). final String serverHost = cssUri . replace ( new URL ( cssUri ) . getPath ( ) , StringUtils . EMPTY ) ; // the uri should end mandatory with / exernalServerCssUri = serverHost + ServletContextUriLocator . PREFIX ; LOG . debug ( \"using {} host as cssUri\" , exernalServerCssUri ) ; } catch ( final MalformedURLException e ) { // should never happen } return exernalServerCssUri ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates cssUri and imageUrl after few changes are applied to both input parameters . [CODESPLIT] private String computeNewImageLocation ( final String cssUri , final String imageUrl ) { LOG . debug ( \"cssUri: {}, imageUrl {}\" , cssUri , imageUrl ) ; final String cleanImageUrl = cleanImageUrl ( imageUrl ) ; // TODO move to ServletContextUriLocator as a helper method? // for the following input: /a/b/c/1.css => /a/b/c/ int idxLastSeparator = cssUri . lastIndexOf ( ServletContextUriLocator . PREFIX ) ; if ( idxLastSeparator == - 1 ) { if ( ClasspathUriLocator . isValid ( cssUri ) ) { idxLastSeparator = cssUri . lastIndexOf ( ClasspathUriLocator . PREFIX ) ; // find the index of ':' character used by classpath prefix if ( idxLastSeparator >= 0 ) { idxLastSeparator += ClasspathUriLocator . PREFIX . length ( ) - 1 ; } } if ( idxLastSeparator < 0 ) { throw new IllegalStateException ( \"Invalid cssUri: \" + cssUri + \". Should contain at least one '/' character!\" ) ; } } final String cssUriFolder = cssUri . substring ( 0 , idxLastSeparator + 1 ) ; // remove '/' from imageUrl if it starts with one. final String processedImageUrl = cleanImageUrl . startsWith ( ServletContextUriLocator . PREFIX ) ? cleanImageUrl . substring ( 1 ) : cleanImageUrl ; final String computedImageLocation = cleanPath ( cssUriFolder + processedImageUrl ) ; LOG . debug ( \"computedImageLocation: {}\" , computedImageLocation ) ; return computedImageLocation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a custom key - value pair attribute . Each pair is added to an internal map . The custom attributes can be used to make the key more fine grained ( Ex : based on browser version or a request parameter ) . Both elements of the attribute ( key & value ) should be not null . If any of these are null the attribute won t be added . [CODESPLIT] public CacheKey addAttribute ( final String key , final String value ) { if ( key != null && value != null ) { map . put ( key , value ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final YuiCssCompressor compressor = new YuiCssCompressor ( reader ) ; compressor . compress ( writer , linebreakpos ) ; } catch ( final Exception e ) { LOG . error ( \"Exception occured while processing resource: \" + resource + \" using processor: \" + ALIAS ) ; onException ( e ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onCachePeriodChanged ( final long period ) { try { managerInitializer . get ( ) . onCachePeriodChanged ( period ) ; } catch ( final WroRuntimeException e ) { LOG . warn ( \"[FAIL] Unable to reload cache, probably because invoked outside of context\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onModelPeriodChanged ( final long period ) { try { managerInitializer . get ( ) . onModelPeriodChanged ( period ) ; } catch ( final WroRuntimeException e ) { LOG . warn ( \"[FAIL] Unable to reload model, probably because invoked outside of context\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a single model transformer . [CODESPLIT] public BaseWroManagerFactory addModelTransformer ( final Transformer < WroModel > modelTransformer ) { if ( modelTransformers == null ) { modelTransformers = new ArrayList < Transformer < WroModel > > ( ) ; } this . modelTransformers . add ( modelTransformer ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write to stream the content of the processed resource bundle . [CODESPLIT] public void serveProcessedBundle ( ) throws IOException { final WroConfiguration configuration = context . getConfig ( ) ; final HttpServletRequest request = context . getRequest ( ) ; final HttpServletResponse response = context . getResponse ( ) ; OutputStream os = null ; try { final CacheKey cacheKey = getSafeCacheKey ( request ) ; initAggregatedFolderPath ( request , cacheKey . getType ( ) ) ; final CacheValue cacheValue = cacheStrategy . get ( cacheKey ) ; // TODO move ETag check in wroManagerFactory final String ifNoneMatch = request . getHeader ( HttpHeader . IF_NONE_MATCH . toString ( ) ) ; // enclose etag value in quotes to be compliant with the RFC final String etagValue = String . format ( \"\\\"%s\\\"\" , cacheValue . getHash ( ) ) ; if ( etagValue != null && etagValue . equals ( ifNoneMatch ) ) { LOG . debug ( \"ETag hash detected: {}. Sending {} status code\" , etagValue , HttpServletResponse . SC_NOT_MODIFIED ) ; response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; // because we cannot return null, return a stream containing nothing. // TODO close output stream? return ; } /**\n       * Set contentType before actual content is written, solves <br/>\n       * <a href=\"http://code.google.com/p/wro4j/issues/detail?id=341\">issue341</a>\n       */ response . setContentType ( cacheKey . getType ( ) . getContentType ( ) + \"; charset=\" + configuration . getEncoding ( ) ) ; // set ETag header response . setHeader ( HttpHeader . ETAG . toString ( ) , etagValue ) ; os = response . getOutputStream ( ) ; if ( cacheValue . getRawContent ( ) != null ) { // use gziped response if supported & Set content length based on gzip flag if ( isGzipAllowed ( ) ) { response . setContentLength ( cacheValue . getGzippedContent ( ) . length ) ; // add gzip header and gzip response response . setHeader ( HttpHeader . CONTENT_ENCODING . toString ( ) , \"gzip\" ) ; response . setHeader ( \"Vary\" , \"Accept-Encoding\" ) ; IOUtils . write ( cacheValue . getGzippedContent ( ) , os ) ; } else { //using getRawContent().length() is not the same and can return 2Bytes smaller size. response . setContentLength ( cacheValue . getRawContent ( ) . getBytes ( configuration . getEncoding ( ) ) . length ) ; IOUtils . write ( cacheValue . getRawContent ( ) , os , configuration . getEncoding ( ) ) ; } } } finally { if ( os != null ) { IOUtils . closeQuietly ( os ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the aggregatedFolderPath if required . [CODESPLIT] private void initAggregatedFolderPath ( final HttpServletRequest request , final ResourceType type ) { if ( ResourceType . CSS == type && context . getAggregatedFolderPath ( ) == null ) { final String requestUri = request . getRequestURI ( ) ; final String cssFolder = StringUtils . removeEnd ( requestUri , FilenameUtils . getName ( requestUri ) ) ; final String aggregatedFolder = StringUtils . removeStart ( cssFolder , request . getContextPath ( ) ) ; LOG . debug ( \"set aggregatedFolderPath: {}\" , aggregatedFolder ) ; Context . get ( ) . setAggregatedFolderPath ( aggregatedFolder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract variables map from variables body . [CODESPLIT] private Map < String , String > extractVariables ( final String variablesBody ) { final Map < String , String > map = new HashMap < String , String > ( ) ; final Matcher m = PATTERN_VARIABLES_BODY . matcher ( variablesBody ) ; LOG . debug ( \"parsing variables body\" ) ; while ( m . find ( ) ) { final String key = m . group ( 1 ) ; final String value = m . group ( 2 ) ; if ( map . containsKey ( key ) ) { LOG . warn ( \"A duplicate variable name found with name: {} and value: {}.\" , key , value ) ; } map . put ( key , value ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String css = IOUtils . toString ( reader ) ; final String result = parseCss ( css ) ; writer . write ( result ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse css find all defined variables & replace them . [CODESPLIT] private String parseCss ( final String css ) { // map containing variables & their values\r final Map < String , String > map = new HashMap < String , String > ( ) ; final StringBuffer sb = new StringBuffer ( ) ; final Matcher m = PATTERN_VARIABLES_DEFINITION . matcher ( css ) ; while ( m . find ( ) ) { final String variablesBody = m . group ( 1 ) ; // LOG.debug(\"variables body: \" + variablesBody);\r // extract variables\r map . putAll ( extractVariables ( variablesBody ) ) ; // remove variables definition\r m . appendReplacement ( sb , \"\" ) ; } m . appendTail ( sb ) ; // LOG.debug(\"replaced variables: \" + result);\r return replaceVariables ( sb . toString ( ) , map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace variables from css with provided variables map . [CODESPLIT] private String replaceVariables ( final String css , final Map < String , String > variables ) { final StringBuffer sb = new StringBuffer ( ) ; final Matcher m = PATTERN_VARIABLE_HOLDER . matcher ( css ) ; while ( m . find ( ) ) { final String oldMatch = m . group ( ) ; final String variableName = m . group ( 1 ) ; final String variableValue = variables . get ( variableName ) ; if ( variableValue != null ) { final String newReplacement = oldMatch . replace ( oldMatch , variableValue ) ; m . appendReplacement ( sb , newReplacement . trim ( ) ) ; } else { LOG . warn ( \"No variable with name \" + variableName + \" was found!\" ) ; } } m . appendTail ( sb ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { super . process ( resource , reader , writer ) ; } finally { IOUtils . closeQuietly ( reader ) ; IOUtils . closeQuietly ( writer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected boolean isEnabled ( final Resource resource ) { final boolean isApplicable = resource != null ? isEligible ( criteria . isMinimize ( ) , resource . getType ( ) ) : true ; return super . isEnabled ( resource ) && isApplicable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String rename ( final String originalName , final InputStream inputStream ) { final String baseName = FilenameUtils . getBaseName ( originalName ) ; final String extension = FilenameUtils . getExtension ( originalName ) ; final long timestamp = getTimestamp ( ) ; final StringBuilder sb = new StringBuilder ( baseName ) . append ( \"-\" ) . append ( timestamp ) ; if ( ! StringUtils . isEmpty ( extension ) ) { sb . append ( \".\" ) . append ( extension ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected Map < String , CacheStrategy < CacheKey , CacheValue > > getStrategies ( final CacheStrategyProvider provider ) { return provider . provideCacheStrategies ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms a post processor into pre processor . [CODESPLIT] private static ResourcePreProcessor toPreProcessor ( final ResourcePostProcessor postProcessor ) { return new AbstractProcessorDecoratorSupport < ResourcePostProcessor > ( postProcessor ) { public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { postProcessor . process ( reader , writer ) ; } @ Override protected boolean isMinimizeInternal ( ) { return isMinimizeForProcessor ( postProcessor ) ; } @ Override protected SupportedResourceType getSupportedResourceTypeInternal ( ) { return getSupportedResourceTypeForProcessor ( postProcessor ) ; } @ Override public String toString ( ) { return postProcessor . toString ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if the processor is eligible for usage based on provided criteria . [CODESPLIT] public final boolean isEligible ( final boolean minimize , final ResourceType searchedType ) { Validate . notNull ( searchedType ) ; final SupportedResourceType supportedType = getSupportedResourceType ( ) ; final boolean isTypeSatisfied = supportedType == null || ( supportedType != null && searchedType == supportedType . value ( ) ) ; final boolean isMinimizedSatisfied = minimize == true || ! isMinimize ( ) ; return isTypeSatisfied && isMinimizedSatisfied ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when { @link LinterException } is thrown . Allows subclasses to re - throw this exception as a { @link RuntimeException } or handle it differently . The default implementation simply logs the errors . [CODESPLIT] protected void onLinterException ( final LinterException e , final Resource resource ) { LOG . error ( \"The following resource: \" + resource + \" has \" + e . getErrors ( ) . size ( ) + \" errors.\" , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void contextInitialized ( final ServletContextEvent event ) { this . servletContext = event . getServletContext ( ) ; attributeHelper = new ServletContextAttributeHelper ( this . servletContext , getListenerName ( ) ) ; initListener ( event . getServletContext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final StopWatch watch = new StopWatch ( ) ; watch . start ( \"pack\" ) ; //initialize rhino context\r Context . enter ( ) ; try { final String script = IOUtils . toString ( reader ) ; final String stripConsole = null ; //normal, warn, all\r LOG . debug ( \"compressing script: {}\" , StringUtils . abbreviate ( script , 40 ) ) ; final String out = Compressor . compressScript ( script , 0 , 0 , stripConsole ) ; writer . write ( out ) ; } finally { Context . exit ( ) ; reader . close ( ) ; writer . close ( ) ; watch . stop ( ) ; LOG . debug ( watch . prettyPrint ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { StopWatch stopWatch = null ; if ( isDebug ( ) ) { stopWatch = new StopWatch ( ) ; before ( stopWatch ) ; } try { super . process ( resource , reader , writer ) ; } finally { if ( isDebug ( ) ) { after ( stopWatch ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] private UriLocatorFactory newLocatorFactory ( ) { final SimpleUriLocatorFactory factory = new SimpleUriLocatorFactory ( ) ; final List < UriLocator > locators = getConfiguredStrategies ( ) ; for ( final UriLocator locator : locators ) { factory . addLocator ( locator ) ; } // use default when none provided if ( locators . isEmpty ( ) ) { LOG . debug ( \"No locators configured. Using Default locator factory.\" ) ; return new DefaultUriLocatorFactory ( ) ; } return factory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean accept ( final String url ) { if ( url == null ) return false ; final String extension = FilenameUtils . getExtension ( url ) ; // scss file have either no extension or scss // maybe check for the \"_\"? if ( \"\" . equals ( extension ) || \"scss\" . equals ( extension ) ) { boolean result = getScssFile ( url ) != null ; if ( ! result ) { LOG . debug ( \"Possible scss file not found {}\" , url ) ; } return result ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public InputStream locate ( final String uri ) throws IOException { Validate . notNull ( uri , \"URI cannot be NULL!\" ) ; LOG . debug ( \"loading  scss file: {}\" , uri ) ; return new FileInputStream ( getScssFile ( uri ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroy the initialized object . This will trigger the re - initialization when { [CODESPLIT] public void destroy ( ) { if ( isInitialized ( ) ) { if ( get ( ) instanceof Destroyable ) { try { ( ( Destroyable ) get ( ) ) . destroy ( ) ; } catch ( final Exception e ) { LOG . error ( \"destroy operation failed\" , e ) ; } } } object = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected String replaceDeclaration ( final String originalDeclaration , final String modifiedDeclaration ) { return originalDeclaration . equals ( modifiedDeclaration ) ? modifiedDeclaration : computeNewDeclaration ( originalDeclaration , modifiedDeclaration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void doFilter ( final ServletRequest req , final ServletResponse res , final FilterChain chain ) throws IOException , ServletException { final HttpServletRequest request = ( HttpServletRequest ) req ; final HttpServletResponse response = ( HttpServletResponse ) res ; if ( isGzipAllowed ( request ) ) { doGzipResponse ( request , response , chain ) ; } else { LOG . debug ( \"Gzip not allowed. Proceeding with chain.\" ) ; chain . doFilter ( request , response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs actual gzip of the filtered content . [CODESPLIT] private void doGzipResponse ( final HttpServletRequest req , final HttpServletResponse response , final FilterChain chain ) throws IOException , ServletException { LOG . debug ( \"Applying gzip on resource: \" + req . getRequestURI ( ) ) ; response . setHeader ( HttpHeader . CONTENT_ENCODING . toString ( ) , \"gzip\" ) ; final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final CountingOutputStream countingStream = new CountingOutputStream ( new GZIPOutputStream ( new BufferedOutputStream ( baos ) ) ) ; // final GZIPOutputStream gzout = new GZIPOutputStream(new BufferedOutputStream(baos)); // Perform gzip operation in-memory before sending response final HttpServletResponseWrapper wrappedResponse = new RedirectedStreamServletResponseWrapper ( countingStream , response ) ; chain . doFilter ( req , wrappedResponse ) ; // close underlying stream countingStream . close ( ) ; response . setContentLength ( countingStream . getCount ( ) ) ; // avoid NO CONTENT error thrown by jetty when gzipping empty response if ( countingStream . getCount ( ) > 0 ) { IOUtils . write ( baos . toByteArray ( ) , response . getOutputStream ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorates a processor which will be applied on provided patterns . [CODESPLIT] public static PathPatternProcessorDecorator include ( final Object processor , final String ... patterns ) { return new PathPatternProcessorDecorator ( processor , true , patterns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorates a processor which will not be applied on provided patterns . [CODESPLIT] public static PathPatternProcessorDecorator exclude ( final Object processor , final String ... patterns ) { return new PathPatternProcessorDecorator ( processor , false , patterns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { if ( resource != null ) { final String uri = resource . getUri ( ) ; LOG . debug ( \"matching uri: {}\" , uri ) ; if ( includes ) { // Match (p1 OR p2 OR .. pn) for ( String pattern : patterns ) { if ( matcher . match ( pattern , uri ) ) { LOG . debug ( \"Processing resource: {}. Match found: {}\" , uri , toString ( ) ) ; getDecoratedObject ( ) . process ( resource , reader , writer ) ; return ; } } } else { boolean process = true ; // Match !(p1 AND p2 AND .. pn) for ( String pattern : patterns ) { if ( matcher . match ( pattern , uri ) ) { process = false ; break ; } } if ( process ) { LOG . debug ( \"Processing resource: {}. Match found: {}\" , uri , toString ( ) ) ; getDecoratedObject ( ) . process ( resource , reader , writer ) ; return ; } } LOG . debug ( \"Skipping {} from {}. No match found: {}\" , new Object [ ] { uri , getDecoratedObject ( ) , toString ( ) } ) ; WroUtil . safeCopy ( reader , writer ) ; } else { throw new WroRuntimeException ( \"Wrong usage of \" + toString ( ) + \". Please use it as a pre-processor.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method which requires all mandatory fields . [CODESPLIT] public static ResourceChangeHandler create ( final WroManagerFactory managerFactory , final Log log ) { notNull ( managerFactory , \"WroManagerFactory was not set\" ) ; notNull ( log , \"Log was not set\" ) ; return new ResourceChangeHandler ( ) . setManagerFactory ( managerFactory ) . setLog ( log ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will persist the information regarding the provided resource in some internal store . This information will be used later to check if the resource is changed . [CODESPLIT] public void remember ( final Resource resource ) { final WroManager manager = getManagerFactory ( ) . create ( ) ; final HashStrategy hashStrategy = manager . getHashStrategy ( ) ; final UriLocatorFactory locatorFactory = manager . getUriLocatorFactory ( ) ; if ( rememberedSet . contains ( resource . getUri ( ) ) ) { // only calculate fingerprints and check imports if not already done getLog ( ) . debug ( \"Resource with uri '\" + resource . getUri ( ) + \"' has already been updated in this run.\" ) ; } else { try { final String fingerprint = hashStrategy . getHash ( locatorFactory . locate ( resource . getUri ( ) ) ) ; getBuildContextHolder ( ) . setValue ( resource . getUri ( ) , fingerprint ) ; rememberedSet . add ( resource . getUri ( ) ) ; getLog ( ) . debug ( \"Persist fingerprint for resource '\" + resource . getUri ( ) + \"' : \" + fingerprint ) ; if ( resource . getType ( ) == ResourceType . CSS ) { final Reader reader = new InputStreamReader ( locatorFactory . locate ( resource . getUri ( ) ) ) ; getLog ( ) . debug ( \"Check @import directive from \" + resource ) ; // persist fingerprints in imported resources. persistFingerprintsForCssImports ( resource , reader ) ; } } catch ( final IOException e ) { getLog ( ) . debug ( \"could not check fingerprint of resource: \" + resource ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the provided function for each detected css import . [CODESPLIT] private void forEachCssImportApply ( final Function < String , ChangeStatus > func , final Resource resource , final Reader reader ) throws IOException { final ResourcePreProcessor processor = createCssImportProcessor ( func ) ; InjectorBuilder . create ( getManagerFactory ( ) ) . build ( ) . inject ( processor ) ; processor . process ( resource , reader , new StringWriter ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "After invoking this method on a resource the next invocation of { @link #isResourceChanged ( Resource ) } will return true . [CODESPLIT] public void forget ( final Resource resource ) { if ( resource != null ) { getBuildContextHolder ( ) . setValue ( resource . getUri ( ) , null ) ; rememberedSet . remove ( resource . getUri ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String getHash ( final InputStream inputStream ) throws IOException { try { return getConfiguredStrategy ( ) . getHash ( inputStream ) ; } finally { IOUtils . closeQuietly ( inputStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for creating a { @link ResourceLintReport } instance . [CODESPLIT] public static < T > ResourceLintReport < T > create ( final String resourcePath , final Collection < T > lints ) { return new ResourceLintReport < T > ( resourcePath , lints ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This filtering is required in order to ensure that no nulls are passed ( which happens when using gson for deserializing json collection . [CODESPLIT] private List < T > filter ( final Collection < T > collection ) { final List < T > nullFreeList = new ArrayList < T > ( ) ; if ( collection != null ) { for ( final T item : collection ) { if ( item != null ) { nullFreeList . add ( item ) ; } } } return nullFreeList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String getGroupName ( final HttpServletRequest request ) { Validate . notNull ( request ) ; String uri = request . getRequestURI ( ) ; // check if include or uri path are present and use one of these as request uri. final String includeUriPath = ( String ) request . getAttribute ( ATTR_INCLUDE_PATH ) ; uri = includeUriPath != null ? includeUriPath : uri ; final String groupName = FilenameUtils . getBaseName ( stripSessionID ( uri ) ) ; return StringUtils . isEmpty ( groupName ) ? null : groupName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the resource type by parsing the uri & finds the extension . If extension is valid ( css or js ) returns corresponding ResourceType otherwise throws exception . <p > Valid examples of uri are : <code > / context / somePath / test . js< / code > or <code > / context / somePath / test . css< / code > { [CODESPLIT] public ResourceType getResourceType ( final HttpServletRequest request ) { Validate . notNull ( request ) ; final String uri = request . getRequestURI ( ) ; Validate . notNull ( uri ) ; ResourceType type = null ; try { type = ResourceType . get ( FilenameUtils . getExtension ( stripSessionID ( uri ) ) ) ; } catch ( final IllegalArgumentException e ) { LOG . debug ( \"[FAIL] Cannot identify resourceType for uri: {}\" , uri ) ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String encodeGroupUrl ( final String groupName , final ResourceType resourceType , final boolean minimize ) { return String . format ( \"%s.%s?\" + PARAM_MINIMIZE + \"=%s\" , groupName , resourceType . name ( ) . toLowerCase ( ) , minimize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The minimization is can be switched off only in debug mode . [CODESPLIT] public boolean isMinimized ( final HttpServletRequest request ) { Validate . notNull ( request ) ; final String minimizeAsString = request . getParameter ( PARAM_MINIMIZE ) ; return ! ( Context . get ( ) . getConfig ( ) . isDebug ( ) && \"false\" . equalsIgnoreCase ( minimizeAsString ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String script = IOUtils . toString ( reader ) ; writer . write ( script ) ; if ( isSemicolonNeeded ( script ) ) { writer . write ( ' ' ) ; } } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; try { writer . write ( doProcess ( content ) ) ; } catch ( final WroRuntimeException e ) { onException ( e ) ; final String resourceUri = resource == null ? StringUtils . EMPTY : \"[\" + resource . getUri ( ) + \"]\" ; LOG . warn ( \"Exception while applying hpack processor on the \" + resourceUri + \" resource, no processing applied...\" , e ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public final void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { LOG . debug ( \"Applying {} processor\" , toString ( ) ) ; validate ( ) ; try { final String result = parseCss ( resource , IOUtils . toString ( reader ) ) ; writer . write ( result ) ; } finally { //imkportant to avoid memory leak clearProcessedImports ( ) ; reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a set of imported resources inside a given resource . [CODESPLIT] private List < Resource > findImportedResources ( final String resourceUri , final String cssContent ) throws IOException { // it should be sorted final List < Resource > imports = new ArrayList < Resource > ( ) ; final String css = cssContent ; final List < String > foundImports = findImports ( css ) ; for ( final String importUrl : foundImports ) { final Resource importedResource = createImportedResource ( resourceUri , importUrl ) ; // check if already exist if ( imports . contains ( importedResource ) ) { LOG . debug ( \"[WARN] Duplicate imported resource: {}\" , importedResource ) ; } else { imports . add ( importedResource ) ; onImportDetected ( importedResource . getUri ( ) ) ; } } return imports ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a { [CODESPLIT] private Resource createImportedResource ( final String resourceUri , final String importUrl ) { final String absoluteUrl = uriLocatorFactory . getInstance ( importUrl ) != null ? importUrl : computeAbsoluteUrl ( resourceUri , importUrl ) ; return Resource . create ( absoluteUrl , ResourceType . CSS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes absolute url of the imported resource . [CODESPLIT] private String computeAbsoluteUrl ( final String relativeResourceUri , final String importUrl ) { final String folder = WroUtil . getFullPath ( relativeResourceUri ) ; // remove '../' & normalize the path. return StringUtils . cleanPath ( folder + importUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to identify whether the { @link HttpServletResponse#SC_NOT_MODIFIED } or { @link HttpServletResponse#SC_OK } should be returned . Currently a single timestamp is used to detect the change for all resources . This might be no accurate but at least it allows sending NOT_MODIFIED header much often resulting in less load on the server . <p / > Override this method if a different way detecting change is required . [CODESPLIT] protected boolean isResourceChanged ( final HttpServletRequest request ) { try { final long ifModifiedSince = request . getDateHeader ( HttpHeader . IF_MODIFIED_SINCE . toString ( ) ) ; return ifModifiedSince < getHeadersConfigurer ( ) . getLastModifiedTimestamp ( ) ; } catch ( final Exception e ) { LOG . warn ( \"Could not extract IF_MODIFIED_SINCE header for request: \" + request . getRequestURI ( ) + \". Assuming content is changed. \" , e ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the request path for this request handler using the assumption that { @link WroFilter } has a mapping ending with a <code > * < / code > character . [CODESPLIT] public static String createProxyPath ( final String requestUri , final String resourceId ) { notNull ( requestUri ) ; notNull ( resourceId ) ; return requestUri + getRequestHandlerPath ( resourceId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a comma separated list of items . [CODESPLIT] public static String createItemsAsString ( final String ... items ) { final StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < items . length ; i ++ ) { sb . append ( items [ i ] ) ; if ( i < items . length - 1 ) { sb . append ( TOKEN_DELIMITER ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a list of aliases based on provided string containing comma separated values of aliases . [CODESPLIT] private List < String > getAliasList ( final String aliasCsv ) { LOG . debug ( \"configured aliases: {}\" , aliasCsv ) ; final List < String > list = new ArrayList < String > ( ) ; if ( ! StringUtils . isEmpty ( aliasCsv ) ) { final String [ ] tokens = aliasCsv . split ( TOKEN_DELIMITER ) ; for ( final String token : tokens ) { list . add ( token . trim ( ) ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the context . [CODESPLIT] private ScriptableObject createContext ( final ScriptableObject initialScope ) { final Context context = getContext ( ) ; context . setOptimizationLevel ( - 1 ) ; // TODO redirect errors from System.err to LOG.error()\r context . setErrorReporter ( new ToolErrorReporter ( false ) ) ; context . setLanguageVersion ( Context . VERSION_1_8 ) ; InputStream script = null ; final ScriptableObject scriptCommon = ( ScriptableObject ) context . initStandardObjects ( initialScope ) ; try { script = new AutoCloseInputStream ( getClass ( ) . getResourceAsStream ( \"commons.js\" ) ) ; context . evaluateReader ( scriptCommon , new InputStreamReader ( script ) , \"commons.js\" , 1 , null ) ; } catch ( final IOException e ) { throw new RuntimeException ( \"Problem while evaluationg commons script.\" , e ) ; } finally { IOUtils . closeQuietly ( script ) ; } return scriptCommon ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a client side environment to the script context ( client - side aware ) . [CODESPLIT] public RhinoScriptBuilder addClientSideEnvironment ( ) { try { //final InputStream scriptEnv = getClass().getResourceAsStream(SCRIPT_ENV);\r final InputStream scriptEnv = new WebjarUriLocator ( ) . locate ( \"env.rhino.js\" ) ; evaluateChain ( scriptEnv , SCRIPT_ENV ) ; return this ; } catch ( final IOException e ) { throw new RuntimeException ( \"Couldn't initialize env.rhino script\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will load JSON utility and aslo a Douglas Crockford s <a href = https : // github . com / douglascrockford / JSON - js / blob / master / cycle . js > utility< / a > required for decycling objects which would fail otherwise when using JSON . stringify . [CODESPLIT] public RhinoScriptBuilder addJSON ( ) { try { final InputStream script = new AutoCloseInputStream ( new WebjarUriLocator ( ) . locate ( WebjarUriLocator . createUri ( \"20110223/json2.js\" ) ) ) ; final InputStream scriptCycle = getClass ( ) . getResourceAsStream ( SCRIPT_CYCLE ) ; evaluateChain ( script , SCRIPT_JSON ) ; evaluateChain ( scriptCycle , SCRIPT_CYCLE ) ; return this ; } catch ( final IOException e ) { throw new RuntimeException ( \"Couldn't initialize json2.min.js script\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a script and return { @link RhinoScriptBuilder } for a chained script evaluation . [CODESPLIT] public RhinoScriptBuilder evaluateChain ( final InputStream stream , final String sourceName ) throws IOException { notNull ( stream ) ; try { getContext ( ) . evaluateReader ( scope , new InputStreamReader ( stream ) , sourceName , 1 , null ) ; return this ; } catch ( final RhinoException e ) { if ( e instanceof RhinoException ) { LOG . error ( \"RhinoException: {}\" , RhinoUtils . createExceptionMessage ( e ) ) ; } throw e ; } catch ( final RuntimeException e ) { LOG . error ( \"Exception caught\" , e ) ; throw e ; } finally { stream . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a script and return { @link RhinoScriptBuilder } for a chained script evaluation . [CODESPLIT] public RhinoScriptBuilder evaluateChain ( final String script , final String sourceName ) { notNull ( script ) ; getContext ( ) . evaluateString ( scope , script , sourceName , 1 , null ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a script from a reader . [CODESPLIT] public Object evaluate ( final Reader reader , final String sourceName ) throws IOException { notNull ( reader ) ; try { return evaluate ( IOUtils . toString ( reader ) , sourceName ) ; } finally { reader . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a script . [CODESPLIT] public Object evaluate ( final String script , final String sourceName ) { notNull ( script ) ; // make sure we have a context associated with current thread\r try { return getContext ( ) . evaluateString ( scope , script , sourceName , 1 , null ) ; } catch ( final RhinoException e ) { final String message = RhinoUtils . createExceptionMessage ( e ) ; LOG . error ( \"JavaScriptException occured: {}\" , message ) ; throw new WroRuntimeException ( message ) ; } finally { // Rhino throws an exception when trying to exit twice. Make sure we don't get any exception\r if ( Context . getCurrentContext ( ) != null ) { Context . exit ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform processing of the uri . [CODESPLIT] public final void process ( ) throws IOException { // reschedule cache & model updates final WroConfiguration config = Context . get ( ) . getConfig ( ) ; cacheSchedulerHelper . scheduleWithPeriod ( config . getCacheUpdatePeriod ( ) ) ; modelSchedulerHelper . scheduleWithPeriod ( config . getModelUpdatePeriod ( ) ) ; resourceBundleProcessor . serveProcessedBundle ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a fingerprint of the resource into the path . The result may look like this : $ { fingerprint } / myGroup . js [CODESPLIT] public final String encodeVersionIntoGroupPath ( final String groupName , final ResourceType resourceType , final boolean minimize ) { // TODO use CacheKeyFactory final CacheKey key = new CacheKey ( groupName , resourceType , minimize ) ; final CacheValue cacheValue = cacheStrategy . get ( key ) ; final String groupUrl = groupExtractor . encodeGroupUrl ( groupName , resourceType , minimize ) ; // encode the fingerprint of the resource into the resource path return formatVersionedResource ( cacheValue . getHash ( ) , groupUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format the version of the resource in the path . Default implementation use hash as a folder : <hash > / groupName . js . The implementation can be changed to follow a different versioning style like version parameter : / groupName . js?version = <hash > [CODESPLIT] protected String formatVersionedResource ( final String hash , final String resourcePath ) { return String . format ( \"%s/%s\" , hash , resourcePath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when { [CODESPLIT] public final void destroy ( ) { try { cacheSchedulerHelper . destroy ( ) ; modelSchedulerHelper . destroy ( ) ; cacheStrategy . destroy ( ) ; modelFactory . destroy ( ) ; resourceWatcher . destroy ( ) ; destroyProcessors ( ) ; } catch ( final Exception e ) { LOG . error ( \"Exception occured during manager destroy!\" , e ) ; } finally { LOG . debug ( \"WroManager destroyed\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes destroy method on all { [CODESPLIT] private void destroyProcessors ( ) throws Exception { for ( final ResourcePreProcessor processor : processorsFactory . getPreProcessors ( ) ) { if ( processor instanceof Destroyable ) { ( ( Destroyable ) processor ) . destroy ( ) ; } } for ( final ResourcePostProcessor processor : processorsFactory . getPostProcessors ( ) ) { if ( processor instanceof Destroyable ) { ( ( Destroyable ) processor ) . destroy ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Map < String , CacheStrategy < CacheKey , CacheValue > > provideCacheStrategies ( ) { return new HashMap < String , CacheStrategy < CacheKey , CacheValue > > ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the provided url is a resource proxy request . [CODESPLIT] private boolean isHandlerRequest ( final HttpServletRequest request ) { String apiHandlerValue = request . getParameter ( PATH_API ) ; return PATH_HANDLER . equals ( apiHandlerValue ) && retrieveCacheKey ( request ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the servlet context relative url to call this handler using a server - side invocation . Hides the details about creating a valid url and providing the authorization key required to invoke this handler . [CODESPLIT] public static String createHandlerRequestPath ( final CacheKey cacheKey , final HttpServletRequest request ) { final String handlerQueryPath = getRequestHandlerPath ( cacheKey . getGroupName ( ) , cacheKey . getType ( ) ) ; return request . getServletPath ( ) + handlerQueryPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a version using some logic . [CODESPLIT] private String rename ( final String group , final InputStream input ) throws Exception { try { final String newName = getManagerFactory ( ) . create ( ) . getNamingStrategy ( ) . rename ( group , input ) ; groupNames . setProperty ( group , newName ) ; return newName ; } catch ( final IOException e ) { throw new MojoExecutionException ( \"Error occured during renaming\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the destination folder based on resource type . [CODESPLIT] private File computeDestinationFolder ( final ResourceType resourceType ) throws MojoExecutionException { File folder = destinationFolder ; if ( resourceType == ResourceType . JS ) { if ( jsDestinationFolder != null ) { folder = jsDestinationFolder ; } } if ( resourceType == ResourceType . CSS ) { if ( cssDestinationFolder != null ) { folder = cssDestinationFolder ; } } getLog ( ) . info ( \"folder: \" + folder ) ; if ( folder == null ) { throw new MojoExecutionException ( \"Couldn't compute destination folder for resourceType: \" + resourceType + \". That means that you didn't define one of the following parameters: \" + \"destinationFolder, cssDestinationFolder, jsDestinationFolder\" ) ; } if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } return folder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a single group . [CODESPLIT] private void processGroup ( final String group , final File parentFoder ) throws Exception { ByteArrayOutputStream resultOutputStream = null ; InputStream resultInputStream = null ; try { getLog ( ) . info ( \"processing group: \" + group ) ; // mock request final HttpServletRequest request = Mockito . mock ( HttpServletRequest . class ) ; Mockito . when ( request . getContextPath ( ) ) . thenReturn ( normalizeContextPath ( contextPath ) ) ; Mockito . when ( request . getRequestURI ( ) ) . thenReturn ( group ) ; // mock response final HttpServletResponse response = Mockito . mock ( HttpServletResponse . class ) ; resultOutputStream = new ByteArrayOutputStream ( ) ; Mockito . when ( response . getOutputStream ( ) ) . thenReturn ( new DelegatingServletOutputStream ( resultOutputStream ) ) ; // init context final WroConfiguration config = Context . get ( ) . getConfig ( ) ; // the maven plugin should ignore empty groups, since it will try to process all types of resources. config . setIgnoreEmptyGroup ( true ) ; Context . set ( Context . webContext ( request , response , Mockito . mock ( FilterConfig . class ) ) , config ) ; Context . get ( ) . setAggregatedFolderPath ( getAggregatedPathResolver ( ) . resolve ( ) ) ; // perform processing getManagerFactory ( ) . create ( ) . process ( ) ; // encode version & write result to file resultInputStream = new UnclosableBufferedInputStream ( resultOutputStream . toByteArray ( ) ) ; final File destinationFile = new File ( parentFoder , rename ( group , resultInputStream ) ) ; final File parentFolder = destinationFile . getParentFile ( ) ; if ( ! parentFolder . exists ( ) ) { // make directories if required parentFolder . mkdirs ( ) ; } destinationFile . createNewFile ( ) ; // allow the same stream to be read again resultInputStream . reset ( ) ; getLog ( ) . debug ( \"Created file: \" + destinationFile . getName ( ) ) ; final OutputStream fos = new FileOutputStream ( destinationFile ) ; // use reader to detect encoding IOUtils . copy ( resultInputStream , fos ) ; fos . close ( ) ; // delete empty files if ( destinationFile . length ( ) == 0 ) { getLog ( ) . debug ( \"No content found for group: \" + group ) ; destinationFile . delete ( ) ; } else { getLog ( ) . info ( \"file size: \" + destinationFile . getName ( ) + \" -> \" + destinationFile . length ( ) + \" bytes\" ) ; getLog ( ) . info ( destinationFile . getAbsolutePath ( ) + \" (\" + destinationFile . length ( ) + \" bytes\" + \")\" ) ; } } finally { // instruct the build about the change in context of incremental build if ( getBuildContext ( ) != null ) { getBuildContext ( ) . refresh ( parentFoder ) ; } if ( resultOutputStream != null ) { resultOutputStream . close ( ) ; } if ( resultInputStream != null ) { resultInputStream . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps original exception into { @link WroRuntimeException } and throw it . [CODESPLIT] public static WroRuntimeException wrap ( final Exception e , final String message ) { if ( e instanceof WroRuntimeException ) { return ( WroRuntimeException ) e ; } return new WroRuntimeException ( message , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final CompilerOptions compilerOptions = optionsPool . getObject ( ) ; final Compiler compiler = newCompiler ( compilerOptions ) ; try { final String fileName = resource == null ? \"wro4j-processed-file.js\" : resource . getUri ( ) ; final SourceFile [ ] input = new SourceFile [ ] { SourceFile . fromInputStream ( fileName , new ByteArrayInputStream ( content . getBytes ( getEncoding ( ) ) ) ) } ; SourceFile [ ] externs = getExterns ( resource ) ; if ( externs == null ) { // fallback to empty array when null is provided.\r externs = new SourceFile [ ] { } ; } Result result = null ; result = compiler . compile ( Arrays . asList ( externs ) , Arrays . asList ( input ) , compilerOptions ) ; if ( result . success ) { writer . write ( compiler . toSource ( ) ) ; } else { throw new WroRuntimeException ( \"Compilation has errors: \" + Arrays . asList ( result . errors ) ) ; } } catch ( final Exception e ) { onException ( e ) ; } finally { reader . close ( ) ; writer . close ( ) ; optionsPool . returnObject ( compilerOptions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes { [CODESPLIT] final SupportedResourceType getSupportedResourceTypeForProcessor ( final Object processor ) { SupportedResourceType supportedType = processor . getClass ( ) . getAnnotation ( SupportedResourceType . class ) ; /**\n     * This is a special case for processors which implement {@link SupportedResourceTypeProvider} interface. This is\n     * useful for decorator processors which needs to \"inherit\" the {@link SupportedResourceType} of the decorated\n     * processor.\n     */ if ( processor instanceof SupportedResourceTypeAware ) { supportedType = ( ( SupportedResourceTypeAware ) processor ) . getSupportedResourceType ( ) ; } return supportedType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if an uri from a particular group has changed . [CODESPLIT] public boolean checkChangeForGroup ( final String uri , final String groupName ) throws IOException { notNull ( uri ) ; notNull ( groupName ) ; LOG . debug ( \"group={}, uri={}\" , groupName , uri ) ; final ResourceChangeInfo resourceInfo = changeInfoMap . get ( uri ) ; if ( resourceInfo . isCheckRequiredForGroup ( groupName ) ) { final InputStream inputStream = locatorFactory . locate ( uri ) ; try { final String currentHash = hashStrategy . getHash ( inputStream ) ; resourceInfo . updateHashForGroup ( currentHash , groupName ) ; } finally { IOUtils . closeQuietly ( inputStream ) ; } } return resourceInfo . isChanged ( groupName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A getter used for lazy loading overrides RubySassEngine#getEngine () and ensure the bourbon gem is imported ( required ) . [CODESPLIT] @ Override protected RubySassEngine newEngine ( ) { final RubySassEngine engine = super . newEngine ( ) ; engine . addRequire ( BOURBON_GEM_REQUIRE ) ; return engine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String compile ( final String content , final String name ) { return HANDLEBARS_JS_TEMPLATES_INIT + \"templates[\" + name + \"] = template(\" + super . compile ( content , \"\" ) + \" ); })();\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { RhinoScriptBuilder builder = null ; if ( scope == null ) { final String scriptInit = \"var exports = {};\" ; builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( scriptInit , \"initSass\" ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_SASS_JS ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final IOException ex ) { throw new WroRuntimeException ( \"Failed reading javascript sass.js\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This implementation will try to locate the provided resource inside contextFolder configured by standaloneContext . If a resource cannot be located the next contextFolder from the list will be tried . The first successful result will be returned . [CODESPLIT] @ Override public InputStream locate ( final String uri ) throws IOException { validState ( standaloneContext != null , \"Locator was not initialized properly. StandaloneContext missing.\" ) ; Exception lastException = null ; final String [ ] contextFolders = standaloneContext . getContextFolders ( ) ; for ( final String contextFolder : contextFolders ) { try { return locateStreamWithContextFolder ( uri , contextFolder ) ; } catch ( final IOException e ) { lastException = e ; LOG . debug ( \"Could not locate: {} using contextFolder: {}\" , uri , contextFolder ) ; } } final String exceptionMessage = String . format ( \"No valid resource '%s' found inside any of contextFolders: %s\" , uri , Arrays . toString ( standaloneContext . getContextFolders ( ) ) ) ; throw new IOException ( exceptionMessage , lastException ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO this is duplicated code ( from super ) - > find a way to reuse it . [CODESPLIT] private InputStream locateStreamWithContextFolder ( final String uri , final String contextFolder ) throws IOException , FileNotFoundException { if ( getWildcardStreamLocator ( ) . hasWildcard ( uri ) ) { final String fullPath = WroUtil . getFullPath ( uri ) ; final String realPath = contextFolder + fullPath ; return getWildcardStreamLocator ( ) . locateStream ( uri , new File ( realPath ) ) ; } final String uriWithoutPrefix = uri . replaceFirst ( PREFIX , EMPTY ) ; final File file = new File ( contextFolder , uriWithoutPrefix ) ; LOG . debug ( \"Opening file: \" + file . getPath ( ) ) ; return new FileInputStream ( file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { try { RhinoScriptBuilder builder = null ; if ( scope == null ) { builder = RhinoScriptBuilder . newChain ( ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_CSSLINT_JS ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final IOException ex ) { throw new IllegalStateException ( \"Failed reading init script\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates a css resource using cssLint and throws { @link CssLintException } if the resource is invalid . If no exception is thrown the resource is valid . [CODESPLIT] public void validate ( final String data ) throws CssLintException { final StopWatch watch = new StopWatch ( ) ; watch . start ( \"init\" ) ; final RhinoScriptBuilder builder = initScriptBuilder ( ) ; watch . stop ( ) ; watch . start ( \"cssLint\" ) ; LOG . debug ( \"options: {}\" , this . options ) ; final String script = buildCssLintScript ( WroUtil . toJSMultiLineString ( data ) ) ; LOG . debug ( \"script: {}\" , script ) ; builder . evaluate ( script , \"CSSLint.verify\" ) . toString ( ) ; final boolean valid = Boolean . parseBoolean ( builder . evaluate ( \"result.length == 0\" , \"checkNoErrors\" ) . toString ( ) ) ; if ( ! valid ) { final String json = builder . addJSON ( ) . evaluate ( \"JSON.stringify(result)\" , \"CssLint messages\" ) . toString ( ) ; LOG . debug ( \"json {}\" , json ) ; final Type type = new TypeToken < List < CssLintError > > ( ) { } . getType ( ) ; final List < CssLintError > errors = new Gson ( ) . fromJson ( json , type ) ; LOG . debug ( \"Errors: {}\" , errors ) ; throw new CssLintException ( ) . setErrors ( errors ) ; } LOG . debug ( \"isValid: {}\" , valid ) ; watch . stop ( ) ; LOG . debug ( watch . prettyPrint ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure that a not null pool will be created . [CODESPLIT] private GenericObjectPool < T > createObjectPool ( final ObjectFactory < T > objectFactory ) { final GenericObjectPool < T > pool = newObjectPool ( objectFactory ) ; notNull ( pool ) ; return pool ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] protected GenericObjectPool < T > newObjectPool ( final ObjectFactory < T > objectFactory ) { final int maxActive = Math . max ( 2 , Runtime . getRuntime ( ) . availableProcessors ( ) ) ; final GenericObjectPool < T > pool = new GenericObjectPool < T > ( new BasePoolableObjectFactory < T > ( ) { @ Override public T makeObject ( ) throws Exception { return objectFactory . create ( ) ; } } ) ; pool . setMaxActive ( maxActive ) ; pool . setMaxIdle ( MAX_IDLE ) ; pool . setMaxWait ( MAX_WAIT ) ; /**\r\n     * Use WHEN_EXHAUSTED_GROW strategy, otherwise the pool object retrieval can fail. More details here:\r\n     * <a>http://code.google.com/p/wro4j/issues/detail?id=364</a>\r\n     */ pool . setWhenExhaustedAction ( GenericObjectPool . WHEN_EXHAUSTED_GROW ) ; // make object eligible for eviction after a predefined amount of time.\r pool . setSoftMinEvictableIdleTimeMillis ( EVICTABLE_IDLE_TIME ) ; pool . setTimeBetweenEvictionRunsMillis ( EVICTABLE_IDLE_TIME ) ; return pool ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final Matcher matcher = PATTERN_PLACEHOLDER . matcher ( content ) ; final StringBuffer sb = new StringBuffer ( ) ; Properties properties = null ; if ( propertiesFactory != null ) { properties = propertiesFactory . create ( ) ; } //be sure that properties will never be null;\r if ( properties == null ) { properties = EMPTY_PROPERTIES ; } while ( matcher . find ( ) ) { final String variableName = matcher . group ( 1 ) ; LOG . debug ( \"found placeholder: {}\" , variableName ) ; matcher . appendReplacement ( sb , replaceVariable ( properties , variableName ) ) ; } matcher . appendTail ( sb ) ; writer . write ( sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { getProcessorDecorator ( ) . process ( resource , reader , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Reader reader , final Writer writer ) throws IOException { getProcessorDecorator ( ) . process ( reader , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public JsonElement serialize ( final Resource resource , final Type type , final JsonSerializationContext context ) { final JsonObject jsonObject = new JsonObject ( ) ; final String uri = resource . getUri ( ) ; jsonObject . add ( \"type\" , new JsonPrimitive ( resource . getType ( ) . toString ( ) ) ) ; jsonObject . add ( \"minimize\" , new JsonPrimitive ( resource . isMinimize ( ) ) ) ; jsonObject . add ( \"uri\" , new JsonPrimitive ( uri ) ) ; jsonObject . add ( \"proxyUri\" , new JsonPrimitive ( getExternalUri ( uri ) ) ) ; return jsonObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the specified URI pattern inside a JAR file . If the specified file isn t a valid JAR default strategy will be used instead . [CODESPLIT] @ Override public InputStream locateStream ( final String uri , final File folder ) throws IOException { notNull ( folder ) ; final File jarPath = getJarFile ( folder ) ; if ( isSupported ( jarPath ) ) { return locateStreamFromJar ( uri , jarPath ) ; } return super . locateStream ( uri , folder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens the specified JAR file and returns a valid handle . [CODESPLIT] JarFile open ( final File jarFile ) throws IOException { isTrue ( jarFile . exists ( ) , \"The JAR file must exists.\" ) ; return new JarFile ( jarFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the specified wildcard - URI resource ( s ) inside a JAR file and returns an { @link InputStream } to read a bundle of matching resources . [CODESPLIT] private InputStream locateStreamFromJar ( final String uri , final File jarPath ) throws IOException { JarFile jarFile = null ; try { LOG . debug ( \"Locating stream from jar: {}\" , jarPath ) ; final WildcardContext wildcardContext = new WildcardContext ( uri , jarPath ) ; String classPath = FilenameUtils . getPath ( uri ) ; if ( classPath . startsWith ( ClasspathUriLocator . PREFIX ) ) { classPath = substringAfter ( classPath , ClasspathUriLocator . PREFIX ) ; } jarFile = open ( jarPath ) ; final List < JarEntry > jarEntryList = Collections . list ( jarFile . entries ( ) ) ; final List < JarEntry > filteredJarEntryList = new ArrayList < JarEntry > ( ) ; final List < File > allFiles = new ArrayList < File > ( ) ; for ( final JarEntry entry : jarEntryList ) { final String entryName = entry . getName ( ) ; // ignore the parent folder itself and accept only child resources final boolean isSupportedEntry = entryName . startsWith ( classPath ) && ! entryName . equals ( classPath ) && accept ( entryName , wildcardContext . getWildcard ( ) ) ; if ( isSupportedEntry ) { allFiles . add ( new File ( entryName ) ) ; LOG . debug ( \"\\tfound jar entry: {}\" , entryName ) ; filteredJarEntryList . add ( entry ) ; } } final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; triggerWildcardExpander ( allFiles , wildcardContext ) ; for ( final JarEntry entry : filteredJarEntryList ) { final InputStream is = jarFile . getInputStream ( entry ) ; IOUtils . copy ( is , out ) ; is . close ( ) ; } return new BufferedInputStream ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; } finally { IOUtils . closeQuietly ( jarFile ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the protocol specific prefix and removes the query path if it exist since it should not be accepted . [CODESPLIT] private String extractPath ( final String uri ) { return DefaultWildcardStreamLocator . stripQueryPath ( uri . replace ( PREFIX , StringUtils . EMPTY ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public CacheKey create ( final HttpServletRequest request ) { notNull ( request ) ; CacheKey key = null ; final String groupName = groupExtractor . getGroupName ( request ) ; final ResourceType resourceType = groupExtractor . getResourceType ( request ) ; final boolean minimize = isMinimized ( request ) ; if ( groupName != null && resourceType != null ) { key = new CacheKey ( groupName , resourceType , minimize ) ; } return key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses isMinimizeEnabled configuration to compute minimize value . [CODESPLIT] private boolean isMinimized ( final HttpServletRequest request ) { return context . getConfig ( ) . isMinimizeEnabled ( ) ? groupExtractor . isMinimized ( request ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "write the content to the { [CODESPLIT] private void writeReport ( final OutputStream outputStream ) { Transformer transformer ; try { transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . transform ( new DOMSource ( doc ) , new StreamResult ( outputStream ) ) ; } catch ( Exception e ) { throw WroRuntimeException . wrap ( e , \"Problem during Document transformation\" ) . logError ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public WroModel create ( ) { final StopWatch stopWatch = new StopWatch ( \"Create Wro Model from Groovy\" ) ; final Script script ; try { stopWatch . start ( \"parseStream\" ) ; script = new GroovyShell ( ) . parse ( new InputStreamReader ( new AutoCloseInputStream ( getModelResourceAsStream ( ) ) ) ) ; LOG . debug ( \"Parsing groovy script to build the model\" ) ; stopWatch . stop ( ) ; stopWatch . start ( \"parseScript\" ) ; final WroModel model = GroovyModelParser . parse ( script ) ; stopWatch . stop ( ) ; LOG . debug ( \"groovy model: {}\" , model ) ; if ( model == null ) { throw new WroRuntimeException ( \"Invalid content provided, cannot build model!\" ) ; } return model ; } catch ( final IOException e ) { throw new WroRuntimeException ( \"Invalid model found!\" , e ) ; } finally { LOG . debug ( stopWatch . prettyPrint ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow adding more than one uriLocators . [CODESPLIT] public final SimpleUriLocatorFactory addLocator ( final UriLocator ... locators ) { for ( final UriLocator locator : locators ) { uriLocators . add ( locator ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method which takes care of redundant decoration . [CODESPLIT] public static WroModelFactory decorate ( final WroModelFactory decorated , final List < Transformer < WroModel > > modelTransformers ) { return decorated instanceof DefaultWroModelFactoryDecorator ? decorated : new DefaultWroModelFactoryDecorator ( decorated , modelTransformers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { try { final String result = new Lessify ( ) . variablizeColors ( IOUtils . toString ( reader ) ) ; writer . write ( result ) ; } finally { reader . close ( ) ; writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a ruby require to the ruby script to be run by this RubySassEngine . It s safe to add the same require twice . [CODESPLIT] public void addRequire ( final String require ) { if ( require != null && require . trim ( ) . length ( ) > 0 ) { requires . add ( require . trim ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms a sass content into css using Sass ruby engine . This method is synchronized because the engine itself is not thread - safe . [CODESPLIT] public String process ( final String content ) { if ( isEmpty ( content ) ) { return StringUtils . EMPTY ; } try { synchronized ( this ) { return engineInitializer . get ( ) . eval ( buildUpdateScript ( content ) ) . toString ( ) ; } } catch ( final ScriptException e ) { throw new WroRuntimeException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String getHash ( final InputStream input ) throws IOException { if ( input == null ) { throw new IllegalArgumentException ( \"Content cannot be null!\" ) ; } try { LOG . debug ( \"creating hash using CRC32 algorithm\" ) ; final Checksum checksum = new CRC32 ( ) ; final byte [ ] bytes = new byte [ 1024 ] ; int len = 0 ; while ( ( len = input . read ( bytes ) ) >= 0 ) { checksum . update ( bytes , 0 , len ) ; } final String hash = new BigInteger ( Long . toString ( checksum . getValue ( ) ) ) . toString ( 16 ) ; LOG . debug ( \"CRC32 hash: {}\" , hash ) ; return hash ; } finally { IOUtils . closeQuietly ( input ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs the summary as it was collected at this point . [CODESPLIT] public void logSummary ( ) { final String message = totalFoundErrors == 0 ? \"No lint errors found.\" : String . format ( \"Found %s errors in %s files.\" , totalFoundErrors , totalResourcesWithErrors ) ; log . info ( \"----------------------------------------\" ) ; log . info ( String . format ( \"Total resources: %s\" , totalResources ) ) ; log . info ( message ) ; log . info ( \"----------------------------------------\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A method which should be invoked on each new resource processing having as a side effect an increment of the counter holding the number of total processed resources . [CODESPLIT] public synchronized void onProcessingResource ( final Resource resource ) { totalResources ++ ; log . debug ( \"processing resource: \" + resource . getUri ( ) ) ; if ( isLogRequired ( ) ) { log . info ( \"Processed until now: \" + getTotalResources ( ) + \". Last processed: \" + resource . getUri ( ) ) ; updateLastInvocation ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final ResourcePreProcessor decoratedProcessor = getDecoratedObject ( ) ; if ( decoratedProcessor instanceof SupportAware ) { if ( ! ( ( SupportAware ) decoratedProcessor ) . isSupported ( ) ) { throw new WroRuntimeException ( toString ( ) + \" processor is not supported on this environment\" ) ; } } super . process ( resource , reader , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure that the returned lock will never be null . [CODESPLIT] private ReadWriteLock getLockForKey ( final K key ) { final ReadWriteLock lock = locks . putIfAbsent ( key , new ReentrantReadWriteLock ( ) ) ; return lock == null ? locks . get ( key ) : lock ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when { @link CssLintException } is thrown . Allows subclasses to re - throw this exception as a { @link RuntimeException } or handle it differently . [CODESPLIT] protected void onCssLintException ( final CssLintException e , final Resource resource ) { final String uri = resource == null ? StringUtils . EMPTY : resource . getUri ( ) ; LOG . error ( \"The following resource: \" + uri + \" has \" + e . getErrors ( ) . size ( ) + \" errors.\" ) ; for ( final CssLintError x : e . getErrors ( ) ) { LOG . error ( uri + \" line \" + x . getLine ( ) + \" column \" + x . getCol ( ) + \": \" + x . getType ( ) + \" \" + x . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates process responsible for running lessc shell command by reading the file content from the sourceFilePath [CODESPLIT] private Process createProcess ( final File sourceFile ) throws IOException { notNull ( sourceFile ) ; final String [ ] commandLine = getCommandLine ( sourceFile . getPath ( ) ) ; LOG . debug ( \"CommandLine arguments: {}\" , Arrays . asList ( commandLine ) ) ; return new ProcessBuilder ( commandLine ) . redirectErrorStream ( true ) . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Map < String , WroModelFactory > provideModelFactories ( ) { final Map < String , WroModelFactory > map = new HashMap < String , WroModelFactory > ( ) ; map . put ( GroovyModelFactory . ALIAS , new GroovyModelFactory ( ) ) ; map . put ( JsonModelFactory . ALIAS , new JsonModelFactory ( ) ) ; map . put ( SmartWroModelFactory . ALIAS , new SmartWroModelFactory ( ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected InputStream getCompilerAsStream ( ) throws IOException { final String compilerPath = System . getProperty ( PARAM_COMPILER_PATH ) ; LOG . debug ( \"compilerPath: {}\" , compilerPath ) ; return StringUtils . isEmpty ( compilerPath ) ? getDefaultCompilerStream ( ) : new FileInputStream ( compilerPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String compile ( final String content , final String optionalArgument ) { return String . format ( \"Hogan.cache['%s'] = %s;\" , optionalArgument , super . compile ( content , \"\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Map < String , WroModelFactory > provideModelFactories ( ) { final Map < String , WroModelFactory > map = new HashMap < String , WroModelFactory > ( ) ; map . put ( XmlModelFactory . ALIAS , new XmlModelFactory ( ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses out the properties of a selector s body . [CODESPLIT] private Property [ ] parseProperties ( final String contents ) { final String [ ] parts = contents . split ( \";\" ) ; final List < Property > resultsAsList = new ArrayList < Property > ( ) ; for ( String part : parts ) { try { // ignore empty parts if ( ! StringUtils . isEmpty ( part . trim ( ) ) ) { resultsAsList . add ( new Property ( part ) ) ; } } catch ( final Exception e ) { LOG . warn ( e . getMessage ( ) , e ) ; } } return resultsAsList . toArray ( new Property [ resultsAsList . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an array of the data for tasks performed . [CODESPLIT] public TaskInfo [ ] getTaskInfo ( ) { if ( ! this . keepTaskList ) { throw new UnsupportedOperationException ( \"Task info is not being kept!\" ) ; } return ( TaskInfo [ ] ) this . taskList . toArray ( new TaskInfo [ this . taskList . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a string with a table describing all tasks performed . For custom reporting call getTaskInfo () and use the task info directly . [CODESPLIT] public String prettyPrint ( ) { final StringBuffer sb = new StringBuffer ( shortSummary ( ) ) ; sb . append ( ' ' ) ; if ( ! this . keepTaskList ) { sb . append ( \"No task info kept\" ) ; } else { final TaskInfo [ ] tasks = getTaskInfo ( ) ; sb . append ( \"-----------------------------------------\\n\" ) ; sb . append ( \"ms     %     Task name\\n\" ) ; sb . append ( \"-----------------------------------------\\n\" ) ; final NumberFormat nf = NumberFormat . getNumberInstance ( ) ; nf . setMinimumIntegerDigits ( 5 ) ; nf . setGroupingUsed ( false ) ; final NumberFormat pf = NumberFormat . getPercentInstance ( ) ; pf . setMinimumIntegerDigits ( 3 ) ; pf . setGroupingUsed ( false ) ; for ( final TaskInfo task : tasks ) { sb . append ( nf . format ( task . getTimeMillis ( ) ) + \"  \" ) ; final double totalTimeSeconds = getTotalTimeSeconds ( ) ; final double percentage = totalTimeSeconds == 0 ? 0 : task . getTimeSeconds ( ) / totalTimeSeconds ; sb . append ( pf . format ( percentage ) + \"  \" ) ; sb . append ( task . getTaskName ( ) + \"\\n\" ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates compilation command for provided typescript input . [CODESPLIT] private String getCompilationCommand ( final String input ) { return String . format ( \"compilerWrapper.compile(%s, %s)\" , WroUtil . toJSMultiLineString ( input ) , ecmaScriptVersion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method which creates a { [CODESPLIT] public static ResponseHeadersConfigurer noCache ( ) { return new ResponseHeadersConfigurer ( ) { @ Override public void configureDefaultHeaders ( final Map < String , String > map ) { addNoCacheHeaders ( map ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method which creates a { [CODESPLIT] public static ResponseHeadersConfigurer fromConfig ( final WroConfiguration config ) { return new ResponseHeadersConfigurer ( config . getHeader ( ) ) { @ Override public void configureDefaultHeaders ( final Map < String , String > map ) { if ( config . isDebug ( ) ) { // prevent caching when in development mode addNoCacheHeaders ( map ) ; } else { final Calendar cal = Calendar . getInstance ( ) ; cal . roll ( Calendar . YEAR , 1 ) ; map . put ( HttpHeader . CACHE_CONTROL . toString ( ) , DEFAULT_CACHE_CONTROL_VALUE ) ; map . put ( HttpHeader . EXPIRES . toString ( ) , WroUtil . toDateAsString ( cal . getTimeInMillis ( ) ) ) ; // TODO probably this is not a good idea to set this field which will have a different value when there will be // more than one instance of wro4j. map . put ( HttpHeader . LAST_MODIFIED . toString ( ) , WroUtil . toDateAsString ( getLastModifiedTimestamp ( ) ) ) ; } } ; } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse header value & puts the found values in headersMap field . [CODESPLIT] private void parseHeader ( final String header ) { LOG . debug ( \"parseHeader: {}\" , header ) ; final String headerName = header . substring ( 0 , header . indexOf ( \":\" ) ) ; if ( ! headersMap . containsKey ( headerName ) ) { final String value = header . substring ( header . indexOf ( \":\" ) + 1 ) ; headersMap . put ( headerName , StringUtils . trim ( value ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates the map with headers used to disable cache . [CODESPLIT] private static void addNoCacheHeaders ( final Map < String , String > map ) { map . put ( HttpHeader . PRAGMA . toString ( ) , \"no-cache\" ) ; map . put ( HttpHeader . CACHE_CONTROL . toString ( ) , \"no-cache\" ) ; map . put ( HttpHeader . EXPIRES . toString ( ) , \"0\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method called for each request and responsible for setting response headers used mostly for cache control . Override this method if you want to change the way headers are set . <br > [CODESPLIT] public void setHeaders ( final HttpServletResponse response ) { // Force resource caching as best as possible for ( final Map . Entry < String , String > entry : headersMap . entrySet ( ) ) { response . setHeader ( entry . getKey ( ) , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void process ( final Resource resource , final Reader reader , final Writer writer ) throws IOException { final String content = IOUtils . toString ( reader ) ; final CoffeeScript coffeeScript = enginePool . getObject ( ) ; try { writer . write ( coffeeScript . compile ( content ) ) ; } catch ( final Exception e ) { onException ( e ) ; final String resourceUri = resource == null ? StringUtils . EMPTY : \"[\" + resource . getUri ( ) + \"]\" ; LOG . error ( \"Exception while applying \" + getClass ( ) . getSimpleName ( ) + \" processor on the \" + resourceUri + \" resource, no processing applied...\" , e ) ; } finally { reader . close ( ) ; writer . close ( ) ; enginePool . returnObject ( coffeeScript ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Properties createProperties ( ) { //Merge Properties file content with the filterConfig content. final Properties merged = new Properties ( ) ; try { final Properties props = newDefaultProperties ( ) ; if ( props != null ) { merged . putAll ( props ) ; } } catch ( final Exception e ) { LOG . warn ( \"Cannot load properties from default location. Load propertis from filterConfig\" , e ) ; } final Properties props = createPropertiesFromFilterConfig ( ) ; merged . putAll ( props ) ; return merged ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a more detailed message based on { @link RhinoException } thrown by rhino execution . The message will contain a detailed description of the problem by inspecting the JSON value provided by exception . [CODESPLIT] public static String createExceptionMessage ( final RhinoException e ) { StringBuffer message = new StringBuffer ( \"Could not execute the script because: \\n\" ) ; if ( e instanceof JavaScriptException ) { message . append ( toJson ( ( ( JavaScriptException ) e ) . getValue ( ) ) ) ; } else if ( e instanceof EcmaError ) { final EcmaError ecmaError = ( EcmaError ) e ; message . append ( String . format ( \"Error message: %s at line: %s. \\nSource: %s\" , ecmaError . getErrorMessage ( ) , ecmaError . lineNumber ( ) , ecmaError . lineSource ( ) ) ) ; } else { message . append ( e . getMessage ( ) ) ; } return message . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively convert from native Rhino to JSON . <p > Recognizes JavaScript objects arrays and primitives . <p > Special support for JavaScript dates : converts to { $date : timestamp } in JSON . <p > Special support for MongoDB ObjectId : converts to { $oid : objectid } in JSON . <p > Also recognizes JVM types : java . util . Map java . util . Collection java . util . Date . [CODESPLIT] public static String toJson ( final Object object , final boolean indent ) { final StringBuilder s = new StringBuilder ( ) ; encode ( s , object , indent , indent ? 0 : - 1 ) ; return s . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve pathInfo from a given location . [CODESPLIT] public static String getPathInfoFromLocation ( final HttpServletRequest request , final String location ) { if ( StringUtils . isEmpty ( location ) ) { throw new IllegalArgumentException ( \"Location cannot be empty string!\" ) ; } final String contextPath = request . getContextPath ( ) ; if ( contextPath != null ) { if ( startsWithIgnoreCase ( location , contextPath ) ) { return location . substring ( contextPath . length ( ) ) ; } else { return location ; } } final String noSlash = location . substring ( 1 ) ; final int nextSlash = noSlash . indexOf ( ' ' ) ; if ( nextSlash == - 1 ) { return \"\" ; } return noSlash . substring ( nextSlash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a folder like implementation for a class . Ex : com . mycompany . MyClass - > com / mycompany / [CODESPLIT] public static String toPackageAsFolder ( final Class < ? > clazz ) { Validate . notNull ( clazz , \"Class cannot be null!\" ) ; return clazz . getPackage ( ) . getName ( ) . replace ( ' ' , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Check if a String starts with a specified prefix ( optionally case insensitive ) . < / p > [CODESPLIT] private static boolean startsWith ( final String str , final String prefix , final boolean ignoreCase ) { if ( str == null || prefix == null ) { return ( str == null && prefix == null ) ; } if ( prefix . length ( ) > str . length ( ) ) { return false ; } return str . regionMatches ( ignoreCase , 0 , prefix , 0 , prefix . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve servletPath from a given location . [CODESPLIT] public static String getServletPathFromLocation ( final HttpServletRequest request , final String location ) { return location . replace ( getPathInfoFromLocation ( request , location ) , StringUtils . EMPTY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Analyze headers of the request and searches for mangled ( by proxy ) for Accept - Encoding header and its mangled variations and gzip header value and its mangled variations . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static boolean isGzipSupported ( final HttpServletRequest request ) { if ( request != null ) { final Enumeration < String > headerNames = request . getHeaderNames ( ) ; if ( headerNames != null ) { while ( headerNames . hasMoreElements ( ) ) { final String headerName = headerNames . nextElement ( ) ; final Matcher m = PATTERN_ACCEPT_ENCODING . matcher ( headerName ) ; if ( m . find ( ) ) { final String headerValue = request . getHeader ( headerName ) ; final Matcher mValue = PATTERN_GZIP . matcher ( headerValue ) ; return mValue . find ( ) ; } } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms a java multi - line string into javascript multi - line string . This technique was found at { @link http : // stackoverflow . com / questions / 805107 / multiline - strings - in - javascript / } [CODESPLIT] public static String toJSMultiLineString ( final String data ) { final StringBuffer result = new StringBuffer ( \"[\" ) ; if ( data != null ) { final String [ ] lines = data . split ( \"\\n\" ) ; if ( lines . length == 0 ) { result . append ( \"\\\"\\\"\" ) ; } for ( int i = 0 ; i < lines . length ; i ++ ) { final String line = lines [ i ] ; result . append ( \"\\\"\" ) ; result . append ( line . replace ( SEPARATOR_WINDOWS , \"\\\\\\\\\" ) . replace ( \"\\\"\" , \"\\\\\\\"\" ) . replaceAll ( \"\\\\r|\\\\n\" , \"\" ) ) ; // this is used to force a single line to have at least one new line (otherwise cssLint fails).\r if ( lines . length == 1 ) { result . append ( \"\\\\n\" ) ; } result . append ( \"\\\"\" ) ; if ( i < lines . length - 1 ) { result . append ( \",\" ) ; } } } result . append ( \"].join(\\\"\\\\n\\\")\" ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility used to verify that requestURI matches provided path [CODESPLIT] public static boolean matchesUrl ( final HttpServletRequest request , final String path ) { final Pattern pattern = Pattern . compile ( \".*\" + path + \"[/]?\" , Pattern . CASE_INSENSITIVE ) ; if ( request . getRequestURI ( ) != null ) { final Matcher m = pattern . matcher ( request . getRequestURI ( ) ) ; return m . matches ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A factory method for creating a { @link ResourceProcessor } based on provided { @link ResourcePreProcessor } . [CODESPLIT] public static ResourcePostProcessor newResourceProcessor ( final Resource resource , final ResourcePreProcessor preProcessor ) { return new ResourcePostProcessor ( ) { public void process ( final Reader reader , final Writer writer ) throws IOException { preProcessor . process ( resource , reader , writer ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the regular expression stored in in regexp . properties resource file . [CODESPLIT] public static String loadRegexpWithKey ( final String key ) { InputStream stream = null ; try { stream = WroUtil . class . getResourceAsStream ( \"regexp.properties\" ) ; final Properties props = new RegexpProperties ( ) . load ( stream ) ; return props . getProperty ( key ) ; } catch ( final IOException e ) { throw new WroRuntimeException ( \"Could not load pattern with key: \" + key + \" from property file\" , e ) ; } finally { closeQuietly ( stream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy and close the reader and writer streams . [CODESPLIT] public static void safeCopy ( final Reader reader , final Writer writer ) throws IOException { try { IOUtils . copy ( reader , writer ) ; } finally { IOUtils . closeQuietly ( reader ) ; IOUtils . closeQuietly ( writer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a temp file which has a certain extension . [CODESPLIT] public static File createTempFile ( final String extension ) { try { final String fileName = String . format ( \"wro4j-%s.%s\" , UUID . randomUUID ( ) . toString ( ) , extension ) ; final File file = new File ( createTempDirectory ( ) , fileName ) ; file . createNewFile ( ) ; return file ; } catch ( final IOException e ) { throw WroRuntimeException . wrap ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join two paths ( using unix separator ) and make sure to use exactly one separator ( by adding or removing one if required ) . [CODESPLIT] public static String joinPath ( final String left , final String right ) { String leftHand = left ; if ( ! left . endsWith ( SEPARATOR_UNIX ) ) { leftHand += SEPARATOR_UNIX ; } return leftHand + right . replaceFirst ( \"^/(.*)\" , \"$1\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans the image url by trimming result and removing \\ or \\ characters if such exists . [CODESPLIT] public static final String cleanImageUrl ( final String imageUrl ) { notNull ( imageUrl ) ; return imageUrl . replace ( ' ' , ' ' ) . replace ( ' ' , ' ' ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Similar to { @link FilenameUtils#getFullPath ( String ) } but fixes the problem with Windows platform for situations when the path starts with / ( servlet context relative resources ) which are resolved to \\ on windows . [CODESPLIT] public static final String getFullPath ( final String path ) { final String fullPath = FilenameUtils . getFullPath ( path ) ; return replaceWithServletContextSeparatorIfNedded ( fullPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Similar to { @link FilenameUtils#normalize ( String ) } but fixes the problem with Windows platform for situations when the path starts with / ( servlet context relative resources ) which are resolved to \\ on windows . [CODESPLIT] public static final String normalize ( final String path ) { final String normalized = FilenameUtils . normalize ( path ) ; return replaceWithServletContextSeparatorIfNedded ( normalized ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method which uses default name for storing / retrieving attributes in { [CODESPLIT] public static ServletContextAttributeHelper create ( final FilterConfig filterConfig ) { Validate . notNull ( filterConfig ) ; final String nameFromParam = filterConfig . getInitParameter ( INIT_PARAM_NAME ) ; final String name = nameFromParam != null ? nameFromParam : DEFAULT_NAME ; return new ServletContextAttributeHelper ( filterConfig . getServletContext ( ) , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a unique name used as a key to store the attribute in { @link ServletContext } . [CODESPLIT] final String getAttributeName ( final Attribute attribute ) { Validate . notNull ( attribute ) ; return WroServletContextListener . class . getName ( ) + \"-\" + attribute . name ( ) + \"-\" + this . name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the attribute into the servlet context . The name of the attribute will be computed for you . [CODESPLIT] final void setAttribute ( final Attribute attribute , final Object object ) { Validate . notNull ( attribute ) ; LOG . debug ( \"setting attribute: {} with value: {}\" , attribute , object ) ; Validate . isTrue ( attribute . isValid ( object ) , object + \" is not of valid subType for attribute: \" + attribute ) ; servletContext . setAttribute ( getAttributeName ( attribute ) , object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all attributes from { [CODESPLIT] public void clear ( ) { LOG . debug ( \"destroying servletContext: {}\" , this . name ) ; for ( Attribute attribute : Attribute . values ( ) ) { servletContext . removeAttribute ( getAttributeName ( attribute ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the dataUri as string associated to the passed InputStream with encoding & type based on provided fileName . [CODESPLIT] public String generateDataURI ( final InputStream inputStream , final String fileName ) throws IOException { final StringWriter writer = new StringWriter ( ) ; final byte [ ] bytes = IOUtils . toByteArray ( inputStream ) ; inputStream . close ( ) ; final String mimeType = getMimeType ( fileName ) ; // actually write generateDataURI ( bytes , writer , mimeType ) ; return writer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a data URI from a byte array and outputs to the given writer . [CODESPLIT] private void generateDataURI ( final byte [ ] bytes , final Writer out , final String mimeType ) throws IOException { // create the output final StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( DATA_URI_PREFIX ) ; // add MIME type buffer . append ( mimeType ) ; // output base64-encoding buffer . append ( \";base64,\" ) ; buffer . append ( Base64 . encodeBytes ( bytes ) ) ; // output to writer out . write ( buffer . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for creating { @link ReportXmlFormatter } . [CODESPLIT] public static ReportXmlFormatter create ( final LintReport < LintItem > lintReport , final FormatterType formatterType ) { return new ReportXmlFormatter ( lintReport , formatterType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a report which handles the adaptation of type <F > to { @link LintItem } . [CODESPLIT] private static < F > ReportXmlFormatter createInternal ( final LintReport < F > lintReport , final FormatterType formatterType , final Function < F , LintItem > adapter ) { Validate . notNull ( lintReport ) ; final LintReport < LintItem > report = new LintReport < LintItem > ( ) ; for ( final ResourceLintReport < F > reportItem : lintReport . getReports ( ) ) { final Collection < LintItem > lintItems = new ArrayList < LintItem > ( ) ; for ( final F lint : reportItem . getLints ( ) ) { try { LOG . debug ( \"Adding lint: {}\" , lint ) ; lintItems . add ( adapter . apply ( lint ) ) ; } catch ( final Exception e ) { throw WroRuntimeException . wrap ( e , \"Problem while adapting lint item\" ) ; } } report . addReport ( ResourceLintReport . create ( reportItem . getResourcePath ( ) , lintItems ) ) ; } return new ReportXmlFormatter ( report , formatterType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void buildDocument ( ) { final Element rootElement = getDocument ( ) . createElement ( formatterType . rootElementName ) ; getDocument ( ) . appendChild ( rootElement ) ; for ( final ResourceLintReport < LintItem > resourceErrors : getLintReport ( ) . getReports ( ) ) { rootElement . appendChild ( createFileElement ( resourceErrors ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] private Node createFileElement ( final ResourceLintReport < LintItem > resourceErrors ) { final Element fileElement = getDocument ( ) . createElement ( ELEMENT_FILE ) ; fileElement . setAttribute ( ATTR_NAME , resourceErrors . getResourcePath ( ) ) ; for ( final LintItem error : resourceErrors . getLints ( ) ) { fileElement . appendChild ( createIssueElement ( error ) ) ; } return fileElement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] private Node createIssueElement ( final LintItem error ) { final Element issueElement = getDocument ( ) . createElement ( getIssueElementName ( ) ) ; final String column = String . valueOf ( error . getColumn ( ) ) ; if ( StringUtils . isNotBlank ( column ) ) { issueElement . setAttribute ( getColumnAttributeName ( ) , column ) ; } final String evidence = error . getEvidence ( ) ; if ( StringUtils . isNotBlank ( evidence ) ) { issueElement . setAttribute ( ATTR_EVIDENCE , evidence ) ; } final String line = String . valueOf ( error . getLine ( ) ) ; if ( StringUtils . isNotBlank ( line ) ) { issueElement . setAttribute ( ATTR_LINE , line ) ; } final String reason = error . getReason ( ) ; if ( StringUtils . isNotBlank ( reason ) ) { issueElement . setAttribute ( getReasonAttributeName ( ) , reason ) ; } final String severity = error . getSeverity ( ) ; if ( StringUtils . isNotBlank ( severity ) ) { issueElement . setAttribute ( ATTR_SEVERITY , severity ) ; } return issueElement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A context useful for running in web context ( inside a servlet container ) . [CODESPLIT] public static Context webContext ( final HttpServletRequest request , final HttpServletResponse response , final FilterConfig filterConfig ) { return new Context ( request , response , filterConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associate a context with the CURRENT request cycle . [CODESPLIT] public static void set ( final Context context , final WroConfiguration config ) { notNull ( context ) ; notNull ( config ) ; context . setConfig ( config ) ; final String correlationId = generateCorrelationId ( ) ; CORRELATION_ID . set ( correlationId ) ; CONTEXT_MAP . put ( correlationId , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove context from the local thread . [CODESPLIT] public static void unset ( ) { final String correlationId = CORRELATION_ID . get ( ) ; if ( correlationId != null ) { CONTEXT_MAP . remove ( correlationId ) ; } CORRELATION_ID . remove ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorates a callable with { @link ContextPropagatingCallable } making it possible to access the { @link Context } from within the decorated callable . [CODESPLIT] public static < T > Callable < T > decorate ( final Callable < T > callable ) { return new ContextPropagatingCallable < T > ( callable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorates the provided { [CODESPLIT] public static CacheStrategy < CacheKey , CacheValue > decorate ( final CacheStrategy < CacheKey , CacheValue > decorated ) { return decorated instanceof DefaultSynchronizedCacheStrategyDecorator ? decorated : new DefaultSynchronizedCacheStrategyDecorator ( decorated ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { [CODESPLIT] private CacheValue computeCacheValueByContent ( final String content ) { String hash = null ; try { if ( content != null ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Content to fingerprint: [{}]\" , StringUtils . abbreviate ( content , 30 ) ) ; } hash = hashStrategy . getHash ( new ByteArrayInputStream ( content . getBytes ( ) ) ) ; } final CacheValue entry = CacheValue . valueOf ( content , hash ) ; LOG . debug ( \"computed entry: {}\" , entry ) ; return entry ; } catch ( final IOException e ) { throw new RuntimeException ( \"Should never happen\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will try an asynchronous check if the async configuration is enabled . If async check is not configured a synchronous check will be performed . The async check assumes that the { @link ResourceWatcherRequestHandler } is enabled . <p / > If the async check is not allowed ( the request was not passed through { @link WroFilter } ) - no check will be performed . This is important for use - cases when wro resource is included using a taglib which performs a wro api call directly without being invoked through { @link WroFilter } . [CODESPLIT] public boolean tryAsyncCheck ( final CacheKey cacheKey ) { boolean checkInvoked = false ; if ( context . getConfig ( ) . isResourceWatcherAsync ( ) ) { if ( isAsyncCheckAllowed ( ) ) { LOG . debug ( \"Checking resourceWatcher asynchronously...\" ) ; final Callable < Void > callable = createAsyncCheckCallable ( cacheKey ) ; submit ( callable ) ; checkInvoked = true ; } } else { LOG . debug ( \"Async check not allowed. Falling back to sync check.\" ) ; check ( cacheKey ) ; checkInvoked = true ; } return checkInvoked ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if resources from a group were changed . If a change is detected the changeListener will be invoked . [CODESPLIT] public void check ( final CacheKey cacheKey , final Callback callback ) { notNull ( cacheKey ) ; LOG . debug ( \"started\" ) ; final StopWatch watch = new StopWatch ( ) ; watch . start ( \"detect changes\" ) ; try { final Group group = new WroModelInspector ( modelFactory . create ( ) ) . getGroupByName ( cacheKey . getGroupName ( ) ) ; if ( isGroupChanged ( group . collectResourcesOfType ( cacheKey . getType ( ) ) , callback ) ) { callback . onGroupChanged ( cacheKey ) ; cacheStrategy . put ( cacheKey , null ) ; } resourceChangeDetector . reset ( ) ; } catch ( final Exception e ) { onException ( e ) ; } finally { watch . stop ( ) ; LOG . debug ( \"resource watcher info: {}\" , watch . prettyPrint ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when exception occurs . [CODESPLIT] protected void onException ( final Exception e ) { // not using ERROR log intentionally, since this error is not that important LOG . info ( \"Could not check for resource changes because: {}\" , e . getMessage ( ) ) ; LOG . debug ( \"[FAIL] detecting resource change \" , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will check if a given resource was changed and will invoke the appropriate callback . [CODESPLIT] private void checkResourceChange ( final Resource resource , final Group group , final Callback callback , final AtomicBoolean isChanged ) throws Exception { if ( isChanged ( resource , group . getName ( ) ) ) { isChanged . compareAndSet ( false , true ) ; callback . onResourceChanged ( resource ) ; lifecycleCallback . onResourceChanged ( resource ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the resource was changed from previous run . The implementation uses resource content digest ( hash ) to check for change . [CODESPLIT] private boolean isChanged ( final Resource resource , final String groupName ) { boolean changed = false ; try { final String uri = resource . getUri ( ) ; // using AtomicBoolean because we need to mutate this variable inside an anonymous class. final AtomicBoolean changeDetected = new AtomicBoolean ( resourceChangeDetector . checkChangeForGroup ( uri , groupName ) ) ; if ( ! changeDetected . get ( ) && resource . getType ( ) == ResourceType . CSS ) { final Reader reader = new InputStreamReader ( locatorFactory . locate ( uri ) ) ; LOG . debug ( \"\\tCheck @import directive from {}\" , resource ) ; createCssImportProcessor ( changeDetected , groupName ) . process ( resource , reader , new StringWriter ( ) ) ; } changed = changeDetected . get ( ) ; } catch ( final IOException e ) { LOG . debug ( \"[FAIL] Cannot check {} resource (Exception message: {}). Assuming it is unchanged...\" , resource , e . getMessage ( ) ) ; } LOG . debug ( \"resource={}, changed={}\" , resource . getUri ( ) , changed ) ; return changed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the hash associated with the resource for a give groupName . [CODESPLIT] public void updateHashForGroup ( final String hash , final String groupName ) { notNull ( groupName ) ; this . currentHash = hash ; if ( isChangedHash ( ) ) { LOG . debug ( \"Group {} has changed\" , groupName ) ; //remove all persisted groups. Starting over.. groups . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the group has at least one resource of some type . [CODESPLIT] public final boolean hasResourcesOfType ( final ResourceType resourceType ) { notNull ( resourceType , \"ResourceType cannot be null!\" ) ; for ( final Resource resource : resources ) { if ( resourceType . equals ( resource . getType ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace one resource with a list of other resources . The use case is related to wildcard expander functionality when resources containing wildcard are replaced with a list of wildcard - free resources . The order of resources is preserved . <p / > The implementation is synchronized because it mutates the collection . [CODESPLIT] public void replace ( final Resource resource , final List < Resource > expandedResources ) { LOG . debug ( \"replacing resource {} with expanded resources: {}\" , resource , expandedResources ) ; notNull ( resource ) ; notNull ( expandedResources ) ; synchronized ( this ) { boolean found = false ; // use set to avoid duplicates\r final Set < Resource > result = new LinkedHashSet < Resource > ( ) ; for ( final Resource resourceItem : resources ) { if ( resourceItem . equals ( resource ) ) { found = true ; for ( final Resource expandedResource : expandedResources ) { // preserve minimize flag.\r expandedResource . setMinimize ( resource . isMinimize ( ) ) ; result . add ( expandedResource ) ; } } else { result . add ( resourceItem ) ; } } // if no resources found, an invalid replace is performed\r if ( ! found ) { throw new IllegalArgumentException ( \"Cannot replace resource: \" + resource + \" for group: \" + this + \" because the resource is not a part of this group.\" ) ; } // update resources with newly built list.\r setResources ( new ArrayList < Resource > ( result ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { @link Resource } to the collection of resources associated with this group . <p / > The implementation is synchronized because it mutates the collection . [CODESPLIT] public Group addResource ( final Resource resource ) { notNull ( resource ) ; synchronized ( this ) { if ( ! hasResource ( resource ) ) { resources . add ( resource ) ; } else { LOG . debug ( \"Resource {} is already contained in this group, skipping it.\" , resource ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will replace all earlier defined resources with the provided list of resources . <p / > The implementation is synchronized because it mutates the collection . [CODESPLIT] public final void setResources ( final List < Resource > resources ) { notNull ( resources ) ; synchronized ( this ) { this . resources . clear ( ) ; for ( final Resource resource : resources ) { addResource ( resource ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method which copies all entries from source into target . Entries with the same keys from target will be overridden with entries from source . This operation is similar to { @link Map#putAll ( Map ) } but it doesn t require changing generics to construction like [CODESPLIT] protected final void copyAll ( final Map < String , S > source , final Map < String , S > target ) { notNull ( source ) ; notNull ( target ) ; for ( final Map . Entry < String , S > entry : source . entrySet ( ) ) { target . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates process responsible for running tsc shell command by reading the file content from the sourceFilePath [CODESPLIT] private Process createProcess ( final File sourceFile , final File destFile ) throws IOException { notNull ( sourceFile ) ; final String [ ] commandLine = getCommandLine ( sourceFile . getPath ( ) , destFile . getPath ( ) ) ; LOG . debug ( \"CommandLine arguments: {}\" , Arrays . asList ( commandLine ) ) ; final Process process = new ProcessBuilder ( commandLine ) . redirectErrorStream ( true ) . start ( ) ; //Gobblers responsible for reading stream to avoid blocking of the process when the buffer is full. final StreamGobbler errorGobbler = new StreamGobbler ( process . getErrorStream ( ) , \"ERROR\" ) ; // any output? final StreamGobbler outputGobbler = new StreamGobbler ( process . getInputStream ( ) , \"OUTPUT\" ) ; // kick them off errorGobbler . start ( ) ; outputGobbler . start ( ) ; return process ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the platform specific arguments to run the <code > tsc< / code > shell utility . Default implementation handles windows and unix platforms . [CODESPLIT] protected String [ ] getCommandLine ( final String filePath , final String outFilePath ) { return isWindows ? buildArgumentsForWindows ( filePath , outFilePath ) : buildArgumentsForUnix ( filePath , outFilePath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize script builder for evaluation . [CODESPLIT] private RhinoScriptBuilder initScriptBuilder ( ) { // TODO: Find a way to encapsulate this code\r RhinoScriptBuilder builder = null ; try { if ( scope == null ) { builder = RhinoScriptBuilder . newChain ( ) . addJSON ( ) . evaluateChain ( UglifyJs . class . getResourceAsStream ( \"init.js\" ) , \"initScript\" ) . evaluateChain ( getScriptAsStream ( ) , DEFAULT_UGLIFY_JS ) ; scope = builder . getScope ( ) ; } else { builder = RhinoScriptBuilder . newChain ( scope ) ; } return builder ; } catch ( final Exception ex ) { throw new IllegalStateException ( \"Failed initializing js\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs Base64 encoding on the <code > raw< / code > ByteBuffer writing it to the <code > encoded< / code > CharBuffer . This is an experimental feature . Currently it does not pass along any options ( such as { @link #DO_BREAK_LINES } or { @link #GZIP } . [CODESPLIT] public static void encode ( final java . nio . ByteBuffer raw , final java . nio . CharBuffer encoded ) { final byte [ ] raw3 = new byte [ 3 ] ; final byte [ ] enc4 = new byte [ 4 ] ; while ( raw . hasRemaining ( ) ) { final int rem = Math . min ( 3 , raw . remaining ( ) ) ; raw . get ( raw3 , 0 , rem ) ; Base64 . encode3to4 ( enc4 , raw3 , rem , Base64 . NO_OPTIONS ) ; for ( int i = 0 ; i < 4 ; i ++ ) { encoded . put ( ( char ) ( enc4 [ i ] & 0xFF ) ) ; } } // end input remaining\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes an object and returns the Base64 - encoded version of that serialized object . [CODESPLIT] public static String encodeObject ( final java . io . Serializable serializableObject ) throws java . io . IOException { return encodeObject ( serializableObject , NO_OPTIONS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the map [CODESPLIT] private void processGroups ( final Document document ) { // handle imports\r final NodeList groupNodeList = document . getElementsByTagName ( TAG_GROUP ) ; for ( int i = 0 ; i < groupNodeList . getLength ( ) ; i ++ ) { final Element groupElement = ( Element ) groupNodeList . item ( i ) ; final String name = groupElement . getAttribute ( ATTR_GROUP_NAME ) ; allGroupElements . put ( name , groupElement ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive method . Add the parsed element group to the group collection . If the group contains group - ref element parse recursively this group . [CODESPLIT] private Collection < Resource > parseGroup ( final Element element ) { final String name = element . getAttribute ( ATTR_GROUP_NAME ) ; final String isAbstractAsString = element . getAttribute ( ATTR_GROUP_ABSTRACT ) ; final boolean isAbstractGroup = StringUtils . isNotEmpty ( isAbstractAsString ) && Boolean . valueOf ( isAbstractAsString ) ; if ( groupsInProcess . contains ( name ) ) { throw new RecursiveGroupDefinitionException ( \"Infinite Recursion detected for the group: \" + name + \". Recursion path: \" + groupsInProcess ) ; } LOG . debug ( \"\\tadding group: {}\" , name ) ; groupsInProcess . add ( name ) ; // skip if this group is already parsed\r final Group parsedGroup = new WroModelInspector ( model ) . getGroupByName ( name ) ; if ( parsedGroup != null ) { // remove before returning\r // this group is parsed, remove from unparsed groups collection\r groupsInProcess . remove ( name ) ; return parsedGroup . getResources ( ) ; } final Group group = createGroup ( element ) ; // this group is parsed, remove from unparsed collection\r groupsInProcess . remove ( name ) ; if ( ! isAbstractGroup ) { // add only non abstract groups\r model . addGroup ( group ) ; } return group . getResources ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a group and all its associated resources . [CODESPLIT] protected Group createGroup ( final Element element ) { final String name = element . getAttribute ( ATTR_GROUP_NAME ) ; final Group group = new Group ( name ) ; final List < Resource > resources = new ArrayList < Resource > ( ) ; final NodeList resourceNodeList = element . getChildNodes ( ) ; for ( int i = 0 ; i < resourceNodeList . getLength ( ) ; i ++ ) { final Node node = resourceNodeList . item ( i ) ; if ( node instanceof Element ) { final Element resourceElement = ( Element ) node ; parseResource ( resourceElement , resources ) ; } } group . setResources ( resources ) ; return group ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a resource from a given resourceElement . It can be css js . If resource tag name is group - ref the method will start a recursive computation . [CODESPLIT] private void parseResource ( final Element resourceElement , final Collection < Resource > resources ) { final String tagName = resourceElement . getTagName ( ) ; final String uri = resourceElement . getTextContent ( ) ; if ( TAG_GROUP_REF . equals ( tagName ) ) { // uri in this case is the group name\r resources . addAll ( getResourcesForGroup ( uri ) ) ; } if ( getResourceType ( resourceElement ) != null ) { final Resource resource = createResource ( resourceElement ) ; LOG . debug ( \"\\t\\tadding resource: {}\" , resource ) ; resources . add ( resource ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a resource from a given resourceElement . The element is guaranteed to be of a simple non - recursive type ( i . e . css or js ) . [CODESPLIT] protected Resource createResource ( final Element resourceElement ) { final String uri = resourceElement . getTextContent ( ) ; final String minimizeAsString = resourceElement . getAttribute ( ATTR_MINIMIZE ) ; final boolean minimize = StringUtils . isEmpty ( minimizeAsString ) || Boolean . valueOf ( minimizeAsString ) ; final Resource resource = Resource . create ( uri , getResourceType ( resourceElement ) ) ; resource . setMinimize ( minimize ) ; return resource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for all resources for a group with a given name . [CODESPLIT] private Collection < Resource > getResourcesForGroup ( final String groupName ) { final WroModelInspector modelInspector = new WroModelInspector ( model ) ; final Group foundGroup = modelInspector . getGroupByName ( groupName ) ; if ( foundGroup == null ) { final Element groupElement = allGroupElements . get ( groupName ) ; if ( groupElement == null ) { throw new WroRuntimeException ( \"Invalid group-ref: \" + groupName ) ; } return parseGroup ( groupElement ) ; } return foundGroup . getResources ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Map < String , HashStrategy > provideHashStrategies ( ) { final Map < String , HashStrategy > map = new HashMap < String , HashStrategy > ( ) ; map . put ( CRC32HashStrategy . ALIAS , new CRC32HashStrategy ( ) ) ; map . put ( MD5HashStrategy . ALIAS , new MD5HashStrategy ( ) ) ; map . put ( SHA1HashStrategy . ALIAS , new SHA1HashStrategy ( ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected ResourcePreProcessor createFallbackProcessor ( ) { LOG . debug ( \"Node CoffeeScript is not supported. Using fallback Rhino processor\" ) ; return new LazyProcessorDecorator ( new LazyInitializer < ResourcePreProcessor > ( ) { @ Override protected ResourcePreProcessor initialize ( ) { return new RhinoCoffeeScriptProcessor ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace provided url with the new url if needed . [CODESPLIT] @ Override protected String replaceImageUrl ( final String cssUri , final String imageUrl ) { //Can be null when using standalone context.\r final String contextPath = context . getRequest ( ) != null ? context . getRequest ( ) . getContextPath ( ) : null ; final RewriterContext rewriterContext = new RewriterContext ( ) . setAggregatedFolderPath ( context . getAggregatedFolderPath ( ) ) . setProxyPrefix ( getUrlPrefix ( ) ) . setContextPath ( contextPath ) ; return new ImageUrlRewriter ( rewriterContext ) . rewrite ( cssUri , imageUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "use { [CODESPLIT] @ Deprecated public static < T , K , U , M extends Multimap < K , U > > Collector < T , ? , M > toMultimap ( Function < ? super T , ? extends K > keyMapper , Function < ? super T , ? extends U > valueMapper , Supplier < M > supplier ) { BiConsumer < M , T > accumulator = ( multimap , element ) -> multimap . put ( keyMapper . apply ( element ) , valueMapper . apply ( element ) ) ; BinaryOperator < M > finisher = ( m1 , m2 ) -> { m1 . putAll ( m2 ) ; return m1 ; } ; return new CollectorImpl <> ( supplier , accumulator , finisher , CH_ID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mainly use for { [CODESPLIT] public static < R , X extends Throwable > R supplyParallel ( ForkJoinPool pool , ThrowableSupplier < R , X > func ) throws X { checkNotNull ( pool ) ; Throwable [ ] throwable = { null } ; ForkJoinTask < R > task = pool . submit ( ( ) -> { try { return func . get ( ) ; } catch ( Throwable e ) { throwable [ 0 ] = e ; return null ; } } ) ; R r ; try { r = task . get ( ) ; } catch ( ExecutionException | InterruptedException impossible ) { throw new AssertionError ( impossible ) ; } if ( throwable [ 0 ] != null ) { //noinspection unchecked throw ( X ) throwable [ 0 ] ; } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@see #tryWait ( Iterable long TimeUnit ) [CODESPLIT] @ Nonnull public static < F extends Future < V > , V > Map < F , V > tryWait ( @ Nonnull Iterable < F > futures , @ Nonnull Duration duration ) throws TryWaitFutureUncheckedException { checkNotNull ( futures ) ; checkNotNull ( duration ) ; return tryWait ( futures , duration . toNanos ( ) , NANOSECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A typical usage : { @code <pre > // a fail - safe example List<Future<User >> list = doSomeAsyncTasks () ; Map<Future<User > User > success ; try { success = tryWait ( list 1 SECONDS ) ; } catch ( TryWaitUncheckedException e ) { success = e . getSuccess () ; // there are still some success } [CODESPLIT] @ Nonnull public static < F extends Future < V > , V > Map < F , V > tryWait ( @ Nonnull Iterable < F > futures , @ Nonnegative long timeout , @ Nonnull TimeUnit unit ) throws TryWaitFutureUncheckedException { checkNotNull ( futures ) ; checkArgument ( timeout > 0 ) ; checkNotNull ( unit ) ; return tryWait ( futures , timeout , unit , it -> it , TryWaitFutureUncheckedException :: new ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@see #tryWait ( Iterable long TimeUnit ThrowableFunction ) [CODESPLIT] @ Nonnull public static < K , V , X extends Throwable > Map < K , V > tryWait ( @ Nonnull Iterable < K > keys , @ Nonnull Duration duration , @ Nonnull ThrowableFunction < K , Future < V > , X > asyncFunc ) throws X , TryWaitUncheckedException { checkNotNull ( keys ) ; checkNotNull ( duration ) ; checkNotNull ( asyncFunc ) ; return tryWait ( keys , duration . toNanos ( ) , NANOSECONDS , asyncFunc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A typical usage : { @code <pre > // a fail - safe example List<Integer > list = getSomeIds () ; Map<Integer User > success ; try { success = tryWait ( list 1 SECONDS id - > executor . submit (( ) - > retrieve ( id ))) ; } catch ( TryWaitUncheckedException e ) { success = e . getSuccess () ; // there are still some success } [CODESPLIT] @ Nonnull public static < K , V , X extends Throwable > Map < K , V > tryWait ( @ Nonnull Iterable < K > keys , @ Nonnegative long timeout , @ Nonnull TimeUnit unit , @ Nonnull ThrowableFunction < K , Future < V > , X > asyncFunc ) throws X , TryWaitUncheckedException { return tryWait ( keys , timeout , unit , asyncFunc , TryWaitUncheckedException :: new ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ConcurrentExecutor } with the given name ( used as a prefix for creating thread ) and given timeout for running threads . If a thread did not process a job within the given timeout the thread is terminated . [CODESPLIT] public static ConcurrentExecutor create ( String name , long timeout , TimeUnit unit ) { return new ConcurrentExecutorImpl ( name , timeout , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print logging information for the timer . The log only shows the recorded time of the completed start - stop cycles . If the timer is still running then it will not be stopped to add the currently measured time to the output but a warning will be logged . [CODESPLIT] public void log ( Logger logger , LogLevel priority ) { if ( LoggerWrap . isEnabledFor ( logger , priority ) ) { String timerLabel ; if ( threadId != 0 ) { timerLabel = name + \" (thread \" + threadId + \")\" ; } else if ( threadCount > 1 ) { timerLabel = name + \" (over \" + threadCount + \" threads)\" ; } else { timerLabel = name ; } if ( todoFlags == RECORD_NONE ) { LoggerWrap . log ( logger , priority , \"Timer \" + timerLabel + \" recorded \" + measurements + \" run(s), no times taken\" ) ; } else { String labels = \"\" ; String values = \"\" ; String separator ; if ( ( todoFlags & RECORD_CPUTIME ) != 0 && threadId != 0 ) { labels += \"CPU\" ; values += totalCpuTime / 1000000 ; separator = \"/\" ; } else { separator = \"\" ; } if ( ( todoFlags & RECORD_WALLTIME ) != 0 ) { labels += separator + \"Wall\" ; values += separator + totalWallTime / 1000000 ; } if ( ( todoFlags & RECORD_CPUTIME ) != 0 && threadId != 0 ) { labels += \"/CPU avg\" ; values += \"/\" + ( float ) ( totalCpuTime ) / measurements / 1000000 ; } if ( ( todoFlags & RECORD_WALLTIME ) != 0 ) { labels += \"/Wall avg\" ; values += \"/\" + ( float ) ( totalWallTime ) / measurements / 1000000 ; } if ( threadCount > 1 ) { if ( ( todoFlags & RECORD_CPUTIME ) != 0 && threadId != 0 ) { labels += \"/CPU per thread\" ; values += \"/\" + ( float ) ( totalCpuTime ) / threadCount / 1000000 ; } if ( ( todoFlags & RECORD_WALLTIME ) != 0 ) { labels += \"/Wall per thread\" ; values += \"/\" + ( float ) ( totalWallTime ) / threadCount / 1000000 ; } } LoggerWrap . log ( logger , priority , \"Time for \" + timerLabel + \" for \" + measurements + \" run(s) \" + labels + \" (ms): \" + values ) ; } if ( isRunning ) { logger . warn ( \"Timer \" + timerLabel + \" logged while it was still running\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop a timer of the given string name for the given thread . If no such timer exists - 1 will be returned . Otherwise the return value is the CPU time that was measured . [CODESPLIT] public static long stopNamedTimer ( String timerName , int todoFlags , long threadId ) { ElkTimer key = new ElkTimer ( timerName , todoFlags , threadId ) ; if ( registeredTimers . containsKey ( key ) ) { return registeredTimers . get ( key ) . stop ( ) ; } else { return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a timer of the given string name that takes all possible times ( todos ) for the current thread . If no such timer exists yet then it will be newly created . [CODESPLIT] public static ElkTimer getNamedTimer ( String timerName ) { return getNamedTimer ( timerName , RECORD_ALL , Thread . currentThread ( ) . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a timer of the given string name and todos for the current thread . If no such timer exists yet then it will be newly created . [CODESPLIT] public static ElkTimer getNamedTimer ( String timerName , int todoFlags ) { return getNamedTimer ( timerName , todoFlags , Thread . currentThread ( ) . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a timer of the given string name for the given thread . If no such timer exists yet then it will be newly created . [CODESPLIT] public static ElkTimer getNamedTimer ( String timerName , int todoFlags , long threadId ) { ElkTimer key = new ElkTimer ( timerName , todoFlags , threadId ) ; ElkTimer previous = registeredTimers . putIfAbsent ( key , key ) ; if ( previous != null ) { return previous ; } // else return key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print statistics about the saturation [CODESPLIT] public void printStatistics ( ) { ruleApplicationFactory_ . getSaturationStatistics ( ) . print ( LOGGER_ ) ; if ( LOGGER_ . isDebugEnabled ( ) ) { if ( aggregatedStats_ . jobsSubmittedNo > 0 ) LOGGER_ . debug ( \"Saturation Jobs Submitted=Done+Processed: {}={}+{}\" , aggregatedStats_ . jobsSubmittedNo , aggregatedStats_ . jobsAlreadyDoneNo , aggregatedStats_ . jobsProcessedNo ) ; LOGGER_ . debug ( \"Locks: \" + aggregatedStats_ . locks ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "waking up all workers waiting for new saturated contexts [CODESPLIT] private void wakeUpWorkers ( ) { if ( ! workersWaiting_ ) { return ; } stopWorkersLock_ . lock ( ) ; try { workersWaiting_ = false ; thereAreContextsToProcess_ . signalAll ( ) ; } finally { stopWorkersLock_ . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the counter for processed contexts and jobs [CODESPLIT] private void updateProcessedCounters ( int snapshotFinishedWorkers ) { if ( isInterrupted ( ) ) { wakeUpWorkers ( ) ; return ; } if ( countStartedWorkers_ . get ( ) > snapshotFinishedWorkers ) { /*\n\t\t\t * We are not the last worker processing the saturation state, so\n\t\t\t * the current jobs and contexts may not be processed yet.\n\t\t\t */ return ; } /*\n\t\t * Otherwise we were the last worker processing the saturation state;\n\t\t * take the values for current jobs and contexts and verify that we are\n\t\t * still the last worker (thus the order is important here).\n\t\t */ int snapshotCountJobsSubmitted = countJobsSubmittedUpper_ . get ( ) ; int snapshotCountContextNonSaturated = saturationState_ . getContextMarkNonSaturatedCount ( ) ; int snapshotCountStartedWorkers = countStartedWorkers_ . get ( ) ; if ( snapshotCountStartedWorkers > snapshotFinishedWorkers ) { /* no longer the last worker */ return ; } /*\n\t\t * If we arrive here, #snapshotCountJobsSubmitted and\n\t\t * #snapshotCountContextNonSaturated represents at least the number of\n\t\t * jobs processed and saturated contexts. Furthermore, since we took\n\t\t * them in this order, we know that all contexts for the processed jobs\n\t\t * were created, saturated, and counted. Now, we updated the\n\t\t * corresponding counters for the processed contexts and jobs but in the\n\t\t * reversed order to make sure that for every job considered to be\n\t\t * processed all contexts were already considered to be processed.\n\t\t */ if ( updateIfSmaller ( countContextsSaturatedLower_ , snapshotCountContextNonSaturated ) ) { /*\n\t\t\t * Sleeping workers can now take new inputs.\n\t\t\t */ wakeUpWorkers ( ) ; } updateIfSmaller ( countJobsProcessedLower_ , snapshotCountJobsSubmitted ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the counter for saturated contexts and processed jobs can be increased and post - process the finished jobs [CODESPLIT] private void updateFinishedCounters ( ThisStatistics localStatistics ) throws InterruptedException { int snapshotJobsProcessed = countJobsProcessedLower_ . get ( ) ; /*\n\t\t * ensure that all contexts for processed jobs are marked as saturated\n\t\t */ for ( ; ; ) { int snapshotCountContextsSaturatedLower = countContextsSaturatedLower_ . get ( ) ; saturationState_ . setContextsSaturated ( snapshotCountContextsSaturatedLower ) ; if ( saturationState_ . getContextSetSaturatedCount ( ) < snapshotCountContextsSaturatedLower ) { /*\n\t\t\t\t * this means that some other worker also sets contexts as\n\t\t\t\t * saturated, then it will mark the finished jobs instead\n\t\t\t\t */ return ; } /*\n\t\t\t * ensure that the counter for processed jobs is still up to date\n\t\t\t */ int updatedSnapshotJobsProcessed = countJobsProcessedLower_ . get ( ) ; if ( updatedSnapshotJobsProcessed == snapshotJobsProcessed ) { break ; } /* else refresh counters */ snapshotJobsProcessed = updatedSnapshotJobsProcessed ; } /*\n\t\t * ensure that all processed jobs are finished\n\t\t */ for ( ; ; ) { int snapshotJobsFinished = countJobsFinishedUpper_ . get ( ) ; if ( snapshotJobsFinished >= snapshotJobsProcessed ) { break ; } /*\n\t\t\t * update the finished context counter at least to the taken\n\t\t\t * snapshot value and mark the corresponding number of jobs as\n\t\t\t * processed\n\t\t\t */ if ( ! countJobsFinishedUpper_ . compareAndSet ( snapshotJobsFinished , snapshotJobsFinished + 1 ) ) { /* retry */ continue ; } // else J nextJob = jobsInProgress_ . poll ( ) ; IndexedContextRoot root = nextJob . getInput ( ) ; Context rootSaturation = saturationState_ . getContext ( root ) ; if ( rootSaturation . isInitialized ( ) && ! rootSaturation . isSaturated ( ) ) { LOGGER_ . error ( \"{}: context for a finished job not saturated!\" , rootSaturation ) ; } nextJob . setOutput ( rootSaturation ) ; LOGGER_ . trace ( \"{}: saturation finished\" , root ) ; localStatistics . jobsProcessedNo ++ ; listener_ . notifyFinished ( nextJob ) ; // can be interrupted } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the counter to the value provided it is greater . Regardless of the returned value it is guaranteed that the value of the counter after execution will be at least the input value . [CODESPLIT] private static boolean updateIfSmaller ( AtomicInteger counter , int value ) { for ( ; ; ) { int snapshotCoutner = counter . get ( ) ; if ( snapshotCoutner >= value ) return false ; if ( counter . compareAndSet ( snapshotCoutner , value ) ) return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { @link BackwardLinkChainFromBackwardLinkRule } inferences for the given { @link ForwardLink } in the given { @link Context } [CODESPLIT] public static boolean addRuleFor ( ForwardLink link , Context context ) { BackwardLinkChainFromBackwardLinkRule rule = context . getBackwardLinkRuleChain ( ) . getCreate ( MATCHER_ , FACTORY_ ) ; return rule . forwardLinksByObjectProperty_ . add ( link . getChain ( ) , link . getTarget ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a { @link BackwardLinkChainFromBackwardLinkRule } inferences for the given { @link ForwardLink } from the given { @link Context } [CODESPLIT] public static boolean removeRuleFor ( ForwardLink link , Context context ) { BackwardLinkChainFromBackwardLinkRule rule = context . getBackwardLinkRuleChain ( ) . find ( MATCHER_ ) ; return rule == null ? false : rule . forwardLinksByObjectProperty_ . remove ( link . getChain ( ) , link . getTarget ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if a { @link BackwardLinkChainFromBackwardLinkRule } inferences for the given { @link ForwardLink } is present in the given { @link Context } [CODESPLIT] public static boolean containsRuleFor ( ForwardLink link , Context context ) { BackwardLinkChainFromBackwardLinkRule rule = context . getBackwardLinkRuleChain ( ) . find ( MATCHER_ ) ; return rule == null ? false : rule . forwardLinksByObjectProperty_ . contains ( link . getChain ( ) , link . getTarget ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default implementation of all methods [CODESPLIT] protected < P > O defaultVisit ( Rule < P > rule , P premise , ContextPremises premises , ClassInferenceProducer producer ) { if ( LOGGER_ . isTraceEnabled ( ) ) { LOGGER_ . trace ( \"ignore {} by {} in {}\" , premise , rule , premises ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes all sub - { @link IndexedPropertyChain } s of the given { @link IndexedPropertyChain } if not computing before recording all { @link ObjectPropertyInference } s using the provided { @link Producer } . It is ensured that all { @link ObjectPropertyInference } s are applied only once even if the method is called multiple times . [CODESPLIT] static Set < IndexedPropertyChain > getSubPropertyChains ( IndexedPropertyChain input , Producer < ? super SubPropertyChainInference > inferenceProducer , final PropertyHierarchyCompositionState . Dispatcher dispatcher ) { return computeSubProperties ( input , inferenceProducer , dispatcher ) . getSubPropertyChains ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes all sub - { @link IndexedObjectProperty } s of the given { @link IndexedPropertyChain } if not computing before recording all { @link ObjectPropertyInference } s using the provided { @link Producer } . It is ensured that all { @link ObjectPropertyInference } s are applied only once even if the method is called multiple times . [CODESPLIT] static Set < IndexedObjectProperty > getSubProperties ( IndexedPropertyChain input , Producer < ? super SubPropertyChainInference > inferenceProducer , final PropertyHierarchyCompositionState . Dispatcher dispatcher ) { return computeSubProperties ( input , inferenceProducer , dispatcher ) . getSubProperties ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given an { @link IndexedObjectProperty } Computes a { @link Multimap } from { @link IndexedObjectProperty } s to { @link IndexedObjectProperty } consisting of the the assignments T - > S such that both S and ObjectPropertyChain ( S T ) are sub - properties of the given { @link IndexedObjectProperty } . The provided { @link Producer } is used to record all { @link ObjectPropertyInference } s that are applied in this computation of sub - { @link IndexedPropertyChain } s involved . It is ensured that the computation is performed only once . [CODESPLIT] static Multimap < IndexedObjectProperty , IndexedObjectProperty > getLeftSubComposableSubPropertiesByRightProperties ( IndexedObjectProperty input , Producer < ? super SubPropertyChainInference > inferenceProducer , final PropertyHierarchyCompositionState . Dispatcher dispatcher ) { SaturatedPropertyChain saturation = input . getSaturated ( ) ; if ( saturation . leftSubComposableSubPropertiesByRightPropertiesComputed ) return saturation . leftSubComposableSubPropertiesByRightProperties ; // else synchronized ( saturation ) { if ( saturation . leftSubComposableSubPropertiesByRightProperties == null ) saturation . leftSubComposableSubPropertiesByRightProperties = new HashSetMultimap < IndexedObjectProperty , IndexedObjectProperty > ( ) ; } synchronized ( saturation . leftSubComposableSubPropertiesByRightProperties ) { if ( saturation . leftSubComposableSubPropertiesByRightPropertiesComputed ) return saturation . leftSubComposableSubPropertiesByRightProperties ; // else compute it Set < IndexedObjectProperty > subProperties = getSubProperties ( input , inferenceProducer , dispatcher ) ; for ( IndexedPropertyChain subPropertyChain : getSubPropertyChains ( input , inferenceProducer , dispatcher ) ) { if ( subPropertyChain instanceof IndexedComplexPropertyChain ) { IndexedComplexPropertyChain composition = ( IndexedComplexPropertyChain ) subPropertyChain ; Set < IndexedObjectProperty > leftSubProperties = getSubProperties ( composition . getFirstProperty ( ) , inferenceProducer , dispatcher ) ; Set < IndexedObjectProperty > commonSubProperties = new LazySetIntersection < IndexedObjectProperty > ( subProperties , leftSubProperties ) ; if ( commonSubProperties . isEmpty ( ) ) continue ; // else for ( IndexedObjectProperty rightSubProperty : getSubProperties ( composition . getSuffixChain ( ) , inferenceProducer , dispatcher ) ) for ( IndexedObjectProperty commonLeft : commonSubProperties ) saturation . leftSubComposableSubPropertiesByRightProperties . ( rightSubProperty , commonLeft ) ; } } saturation . leftSubComposableSubPropertiesByRightPropertiesComputed = true ; } return saturation . leftSubComposableSubPropertiesByRightProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified object property into the taxonomy if it is not in it yet and sets its direct sub - properties if not set yet . [CODESPLIT] private void instertIntoTaxonomy ( final IndexedObjectProperty property ) { /* \n\t\t * @formatter:off\n\t\t * \n\t\t * Transitive reduction and taxonomy computation\n\t\t * \tif sub-properties of a sub-property contain this property,\n\t\t * \t\tthey are equivalent\n\t\t * \tif a property is a strict sub-property of another strict sub-property,\n\t\t * \t\tit is not direct\n\t\t * \n\t\t * @formatter:on\n\t\t */ final Map < IndexedObjectProperty , ElkObjectProperty > equivalent = collectEquivalent ( property ) ; if ( equivalent == null ) { // Equivalent to top. return ; } final Map < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > subEquivalent = new ArrayHashMap < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > ( ) ; final Set < IndexedObjectProperty > indirect = new ArrayHashSet < IndexedObjectProperty > ( ) ; for ( final IndexedObjectProperty subProperty : property . getSaturated ( ) . getSubProperties ( ) ) { if ( equivalent . containsKey ( subProperty ) ) { // subProperty is not strict continue ; } // subProperty is strict final Map < IndexedObjectProperty , ElkObjectProperty > subEq = collectEquivalent ( subProperty ) ; // should not be null, because top cannot be a strict sub-property subEquivalent . put ( subProperty , subEq . values ( ) ) ; for ( final IndexedObjectProperty subSubProperty : subProperty . getSaturated ( ) . getSubProperties ( ) ) { if ( ! subEq . containsKey ( subSubProperty ) ) { // strict indirect . add ( subSubProperty ) ; } } } /*\n\t\t * If property is not equivalent to bottom and there are no strict sub\n\t\t * properties, add the bottom as a default sub property.\n\t\t */ if ( subEquivalent . isEmpty ( ) && ( indexedBottomProperty_ == null || ! equivalent . containsKey ( indexedBottomProperty_ ) ) ) { outputProcessor_ . visit ( new TransitiveReductionOutputEquivalentDirectImpl < ElkObjectProperty > ( equivalent . values ( ) , defaultDirectSubproperties_ ) ) ; return ; } // else final Collection < Collection < ? extends ElkObjectProperty > > direct = Operations . map ( subEquivalent . entrySet ( ) , new Operations . Transformation < Map . Entry < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > , Collection < ? extends ElkObjectProperty > > ( ) { @ Override public Collection < ? extends ElkObjectProperty > transform ( final Entry < IndexedObjectProperty , Collection < ? extends ElkObjectProperty > > element ) { if ( indirect . contains ( element . getKey ( ) ) ) { return null ; } else { return element . getValue ( ) ; } } } ) ; outputProcessor_ . visit ( new TransitiveReductionOutputEquivalentDirectImpl < ElkObjectProperty > ( equivalent . values ( ) , direct ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects sub - properties of <code > property< / code > that are equivalent to it . Returns <code > null< / code > if <code > property< / code > is equivalent to the top property . [CODESPLIT] private Map < IndexedObjectProperty , ElkObjectProperty > collectEquivalent ( final IndexedObjectProperty property ) { final Set < IndexedObjectProperty > subProperties = property . getSaturated ( ) . getSubProperties ( ) ; final Map < IndexedObjectProperty , ElkObjectProperty > equivalent = new ArrayHashMap < IndexedObjectProperty , ElkObjectProperty > ( ) ; for ( final IndexedObjectProperty subProperty : subProperties ) { if ( subProperty . equals ( indexedTopProperty_ ) ) { outputProcessor_ . visit ( new TransitiveReductionOutputExtremeImpl < ElkObjectProperty > ( property . getElkEntity ( ) ) ) ; return null ; } if ( subProperty . getSaturated ( ) . getSubProperties ( ) . contains ( property ) || property . equals ( indexedBottomProperty_ ) ) { equivalent . put ( subProperty , subProperty . getElkEntity ( ) ) ; } } if ( indexedBottomProperty_ . getSaturated ( ) . getSubProperties ( ) . contains ( property ) ) { equivalent . put ( indexedBottomProperty_ , indexedBottomProperty_ . getElkEntity ( ) ) ; } return equivalent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flushes index if needed and completes loading if there is new input . Incremental mode should be changed only during completing loading . [CODESPLIT] public synchronized void ensureLoading ( ) throws ElkException { if ( ! isLoadingFinished ( ) ) { if ( isIncrementalMode ( ) ) { if ( ! stageManager . incrementalAdditionStage . isCompleted ( ) ) { complete ( stageManager . incrementalAdditionStage ) ; } } else { if ( ! stageManager . contextInitializationStage . isCompleted ( ) ) { complete ( stageManager . contextInitializationStage ) ; } } LOGGER_ . trace ( \"Reset axiom loading\" ) ; stageManager . inputLoadingStage . invalidateRecursive ( ) ; // Invalidate stages at the beginnings of the dependency chains. stageManager . contextInitializationStage . invalidateRecursive ( ) ; stageManager . incrementalCompletionStage . invalidateRecursive ( ) ; } complete ( stageManager . inputLoadingStage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that saturation is restored and taxonomies are cleaned . Also invalidates stages that depend on the saturation if it changed . [CODESPLIT] private void restoreSaturation ( ) throws ElkException { ensureLoading ( ) ; final boolean changed ; if ( isIncrementalMode ( ) ) { changed = ! stageManager . incrementalTaxonomyCleaningStage . isCompleted ( ) ; complete ( stageManager . incrementalTaxonomyCleaningStage ) ; } else { changed = ! stageManager . contextInitializationStage . isCompleted ( ) ; complete ( stageManager . contextInitializationStage ) ; } if ( changed ) { stageManager . consistencyCheckingStage . invalidateRecursive ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check consistency of the current ontology if this has not been done yet . [CODESPLIT] public synchronized boolean isInconsistent ( ) throws ElkException { restoreConsistencyCheck ( ) ; if ( ! consistencyCheckingState . isInconsistent ( ) ) { incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; } return consistencyCheckingState . isInconsistent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete the taxonomy computation stage and the stages it depends on if it has not been done yet . [CODESPLIT] protected Taxonomy < ElkClass > restoreTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { ruleAndConclusionStats . reset ( ) ; // also restores saturation and cleans the taxonomy if necessary restoreConsistencyCheck ( ) ; if ( consistencyCheckingState . isInconsistent ( ) ) { throw new ElkInconsistentOntologyException ( ) ; } complete ( stageManager . classTaxonomyComputationStage ) ; return classTaxonomyState . getTaxonomy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the inferred taxonomy of the named classes for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkClass > getTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { restoreTaxonomy ( ) ; incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; return classTaxonomyState . getTaxonomy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the inferred taxonomy of the named classes for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkClass > getTaxonomyQuietly ( ) throws ElkException { Taxonomy < ElkClass > result ; try { result = getTaxonomy ( ) ; } catch ( ElkInconsistentOntologyException e ) { LOGGER_ . debug ( \"Ontology is inconsistent\" ) ; result = new SingletoneTaxonomy < ElkClass , OrphanTaxonomyNode < ElkClass > > ( ElkClassKeyProvider . INSTANCE , getAllClasses ( ) , new TaxonomyNodeFactory < ElkClass , OrphanTaxonomyNode < ElkClass > , Taxonomy < ElkClass > > ( ) { @ Override public OrphanTaxonomyNode < ElkClass > createNode ( final Iterable < ? extends ElkClass > members , final int size , final Taxonomy < ElkClass > taxonomy ) { return new OrphanTaxonomyNode < ElkClass > ( members , size , elkFactory_ . getOwlNothing ( ) , taxonomy ) ; } } ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completes instance taxonomy computation stage and the stages that it depends on if this has not been done yet . [CODESPLIT] protected InstanceTaxonomy < ElkClass , ElkNamedIndividual > restoreInstanceTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { ruleAndConclusionStats . reset ( ) ; // also restores saturation and cleans the taxonomy if necessary restoreConsistencyCheck ( ) ; if ( consistencyCheckingState . isInconsistent ( ) ) { throw new ElkInconsistentOntologyException ( ) ; } complete ( stageManager . instanceTaxonomyComputationStage ) ; return instanceTaxonomyState . getTaxonomy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the inferred taxonomy of the named classes with instances if this has not been done yet . [CODESPLIT] public synchronized InstanceTaxonomy < ElkClass , ElkNamedIndividual > getInstanceTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { restoreInstanceTaxonomy ( ) ; incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; return instanceTaxonomyState . getTaxonomy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the inferred taxonomy of the named classes with instances if this has not been done yet . [CODESPLIT] public synchronized InstanceTaxonomy < ElkClass , ElkNamedIndividual > getInstanceTaxonomyQuietly ( ) throws ElkException { InstanceTaxonomy < ElkClass , ElkNamedIndividual > result ; try { result = getInstanceTaxonomy ( ) ; } catch ( ElkInconsistentOntologyException e ) { LOGGER_ . debug ( \"Ontology is inconsistent\" ) ; result = new SingletoneInstanceTaxonomy < ElkClass , ElkNamedIndividual , OrphanTypeNode < ElkClass , ElkNamedIndividual > > ( ElkClassKeyProvider . INSTANCE , getAllClasses ( ) , new TaxonomyNodeFactory < ElkClass , OrphanTypeNode < ElkClass , ElkNamedIndividual > , Taxonomy < ElkClass > > ( ) { @ Override public OrphanTypeNode < ElkClass , ElkNamedIndividual > createNode ( final Iterable < ? extends ElkClass > members , final int size , final Taxonomy < ElkClass > taxonomy ) { final OrphanTypeNode < ElkClass , ElkNamedIndividual > node = new OrphanTypeNode < ElkClass , ElkNamedIndividual > ( members , size , elkFactory_ . getOwlNothing ( ) , taxonomy , 1 ) ; final Set < ElkNamedIndividual > allNamedIndividuals = getAllNamedIndividuals ( ) ; final Iterator < ElkNamedIndividual > namedIndividualIterator = allNamedIndividuals . iterator ( ) ; if ( namedIndividualIterator . hasNext ( ) ) { // there is at least one individual node . addInstanceNode ( new OrphanInstanceNode < ElkClass , ElkNamedIndividual > ( allNamedIndividuals , allNamedIndividuals . size ( ) , namedIndividualIterator . next ( ) , ElkIndividualKeyProvider . INSTANCE , node ) ) ; } return node ; } } , ElkIndividualKeyProvider . INSTANCE ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the inferred taxonomy of the object properties for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkObjectProperty > getObjectPropertyTaxonomy ( ) throws ElkInconsistentOntologyException , ElkException { ruleAndConclusionStats . reset ( ) ; restoreConsistencyCheck ( ) ; if ( consistencyCheckingState . isInconsistent ( ) ) { throw new ElkInconsistentOntologyException ( ) ; } LOGGER_ . trace ( \"Property hierarchy computation\" ) ; complete ( stageManager . objectPropertyTaxonomyComputationStage ) ; incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassification ( ) ) ; return objectPropertyTaxonomyState . getTaxonomy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the inferred taxonomy of the object properties for the given ontology if it has not been done yet . [CODESPLIT] public synchronized Taxonomy < ElkObjectProperty > getObjectPropertyTaxonomyQuietly ( ) throws ElkException { Taxonomy < ElkObjectProperty > result ; try { result = getObjectPropertyTaxonomy ( ) ; } catch ( ElkInconsistentOntologyException e ) { LOGGER_ . debug ( \"Ontology is inconsistent\" ) ; result = new SingletoneTaxonomy < ElkObjectProperty , OrphanTaxonomyNode < ElkObjectProperty > > ( ElkObjectPropertyKeyProvider . INSTANCE , getAllObjectProperties ( ) , new TaxonomyNodeFactory < ElkObjectProperty , OrphanTaxonomyNode < ElkObjectProperty > , Taxonomy < ElkObjectProperty > > ( ) { @ Override public OrphanTaxonomyNode < ElkObjectProperty > createNode ( final Iterable < ? extends ElkObjectProperty > members , final int size , final Taxonomy < ElkObjectProperty > taxonomy ) { return new OrphanTaxonomyNode < ElkObjectProperty > ( members , size , elkFactory_ . getOwlBottomObjectProperty ( ) , taxonomy ) ; } } ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the query results are not cached yet indexes the supplied class expression and if successful computes the query so that the results for this expressions are ready in { @link #classExpressionQueryState_ } . [CODESPLIT] private boolean computeQuery ( final ElkClassExpression classExpression , final boolean computeInstanceTaxonomy ) throws ElkInconsistentOntologyException , ElkException { // Load the query classExpressionQueryState_ . registerQuery ( classExpression ) ; ensureLoading ( ) ; // Complete all stages if ( computeInstanceTaxonomy ) { restoreInstanceTaxonomy ( ) ; } else { restoreTaxonomy ( ) ; } if ( ! classExpressionQueryState_ . isIndexed ( classExpression ) ) { return false ; } /*\n\t\t * If query result is cashed, but there were some changes to the\n\t\t * ontology, it may not be up to date. Whether it is is checked during\n\t\t * stages that clean contexts. These are run, if necessary, by the call\n\t\t * above.\n\t\t */ if ( classExpressionQueryState_ . isComputed ( classExpression ) ) { return true ; } stageManager . classExpressionQueryStage . invalidateRecursive ( ) ; try { complete ( stageManager . classExpressionQueryStage ) ; } catch ( final ElkInterruptedException e ) { if ( classExpressionQueryState_ . isComputed ( classExpression ) ) { /*\n\t\t\t\t * If the stage was interrupted, but the query is already\n\t\t\t\t * computed, completing the stage will not be attempted during\n\t\t\t\t * the next call. We need to call postExecute() manually, so\n\t\t\t\t * that the stage wouldn't stay initialized with computation\n\t\t\t\t * that already processed all its inputs (or at least the\n\t\t\t\t * queried class).\n\t\t\t\t */ stageManager . classExpressionQueryStage . postExecute ( ) ; } else { throw e ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides whether the supplied ( possibly complex ) class expression is satisfiable . The query state is updated accordingly . [CODESPLIT] protected boolean querySatisfiability ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final boolean result ; if ( computeQuery ( classExpression , false ) ) { result = classExpressionQueryState_ . isSatisfiable ( classExpression ) ; } else { // classExpression couldn't be indexed; pretend it is a fresh class result = true ; } // If classExpression is unsatisfiable, the result is complete. if ( result ) { incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes all atomic classes that are equivalent to the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Node < ElkClass > queryEquivalentClasses ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Node < ElkClass > result ; if ( computeQuery ( classExpression , false ) ) { final Node < ElkClass > r = classExpressionQueryState_ . getEquivalentClasses ( classExpression ) ; if ( r == null ) { result = classTaxonomyState . getTaxonomy ( ) . getBottomNode ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = new QueryNode < ElkClass > ( ElkClassKeyProvider . INSTANCE ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes all atomic direct super - classes of the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Set < ? extends Node < ElkClass > > queryDirectSuperClasses ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Set < ? extends Node < ElkClass > > result ; if ( computeQuery ( classExpression , false ) ) { final Set < ? extends Node < ElkClass > > r = classExpressionQueryState_ . getDirectSuperClasses ( classExpression ) ; if ( r == null ) { result = classTaxonomyState . getTaxonomy ( ) . getBottomNode ( ) . getDirectSuperNodes ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = Collections . singleton ( classTaxonomyState . getTaxonomy ( ) . getTopNode ( ) ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes all atomic direct sub - classes of the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Set < ? extends Node < ElkClass > > queryDirectSubClasses ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Set < ? extends Node < ElkClass > > result ; if ( computeQuery ( classExpression , false ) ) { final Taxonomy < ElkClass > taxonomy = classTaxonomyState . getTaxonomy ( ) ; final Set < ? extends Node < ElkClass > > r = classExpressionQueryState_ . getDirectSubClasses ( classExpression , taxonomy ) ; if ( r == null ) { result = taxonomy . getBottomNode ( ) . getDirectSubNodes ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = Collections . singleton ( classTaxonomyState . getTaxonomy ( ) . getBottomNode ( ) ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes all direct instances of the supplied ( possibly complex ) class expression . The query state is updated accordingly . [CODESPLIT] protected Set < ? extends Node < ElkNamedIndividual > > queryDirectInstances ( final ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { final Set < ? extends Node < ElkNamedIndividual > > result ; if ( computeQuery ( classExpression , true ) ) { final InstanceTaxonomy < ElkClass , ElkNamedIndividual > taxonomy = instanceTaxonomyState . getTaxonomy ( ) ; final Set < ? extends Node < ElkNamedIndividual > > r = classExpressionQueryState_ . getDirectInstances ( classExpression , taxonomy ) ; if ( r == null ) { result = taxonomy . getBottomNode ( ) . getDirectInstanceNodes ( ) ; } else { result = r ; } } else { // classExpression couldn't be indexed; pretend it is a fresh class result = Collections . emptySet ( ) ; } incompleteness_ . log ( incompleteness_ . getIncompletenessMonitorForClassExpressionQuery ( classExpressionQueryState_ . getOccurrenceStore ( classExpression ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides whether the supplied { @code axioms } are entailed by the currently loaded ontology . [CODESPLIT] public synchronized Map < ElkAxiom , EntailmentQueryResult > isEntailed ( final Iterable < ? extends ElkAxiom > axioms ) throws ElkException { entailmentQueryState_ . registerQueries ( axioms ) ; restoreSaturation ( ) ; stageManager . entailmentQueryStage . invalidateRecursive ( ) ; complete ( stageManager . entailmentQueryStage ) ; return entailmentQueryState_ . isEntailed ( axioms ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides whether the supplied { @code axiom } is entailed by the currently loaded ontology . [CODESPLIT] public synchronized EntailmentQueryResult isEntailed ( final ElkAxiom axiom ) throws ElkException { return isEntailed ( Collections . singleton ( axiom ) ) . get ( axiom ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public Set < ? extends Integer > getSubsumerPositions ( IndexedClassExpressionList disjoint ) { if ( disjointnessAxioms_ == null ) { return null ; } return disjointnessAxioms_ . get ( disjoint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes from { @link #toDoEntities_ } the entities which no longer occur in the ontology or for the context is already saturated ( thus consistency is already checked ) [CODESPLIT] private int pruneToDo ( ) { int size = 0 ; Iterator < IndexedClassEntity > itr = toDoEntities_ . iterator ( ) ; while ( itr . hasNext ( ) ) { IndexedClassEntity next = itr . next ( ) ; if ( ! next . occurs ( ) ) { itr . remove ( ) ; continue ; } // else Context context = saturationState_ . getContext ( next ) ; if ( context != null && context . isSaturated ( ) ) { itr . remove ( ) ; } else { size ++ ; } } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Explains why an ontology inconsistency is entailed . If it is not entailed the returned proof is empty . [CODESPLIT] public Proof < ? extends EntailmentInference > getEvidence ( final boolean atMostOne ) { return new Proof < EntailmentInference > ( ) { @ SuppressWarnings ( \"unchecked\" ) @ Override public Collection < OntologyInconsistencyEntailmentInference > getInferences ( final Object conclusion ) { if ( ! OntologyInconsistencyImpl . INSTANCE . equals ( conclusion ) ) { return Collections . emptyList ( ) ; } // else final Collection < ? extends IndexedIndividual > inconsistentIndividuals = getInconsistentIndividuals ( ) ; Iterable < OntologyInconsistencyEntailmentInference > result = Operations . map ( inconsistentIndividuals , INDIVIDUAL_TO_ENTAILMENT_INFERENCE ) ; int size = inconsistentIndividuals . size ( ) ; if ( isTopObjectPropertyInBottom_ ) { result = Operations . concat ( Operations . < OntologyInconsistencyEntailmentInference > singleton ( new TopObjectPropertyInBottomEntailsOntologyInconsistencyImpl ( conclusionFactory_ . getSubPropertyChain ( topProperty_ , bottomProperty_ ) ) ) , result ) ; size ++ ; } if ( isOwlThingInconsistent_ ) { result = Operations . concat ( Operations . < OntologyInconsistencyEntailmentInference > singleton ( new OwlThingInconsistencyEntailsOntologyInconsistencyImpl ( conclusionFactory_ . getContradiction ( owlThing_ ) ) ) , result ) ; size ++ ; } if ( atMostOne ) { final Iterator < OntologyInconsistencyEntailmentInference > iter = result . iterator ( ) ; if ( ! iter . hasNext ( ) ) { return Collections . emptyList ( ) ; } // else return Collections . singleton ( iter . next ( ) ) ; } // else return Operations . getCollection ( result , size ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the supplied axioms for querying . If all necessary stages are run after calling this method for some axioms neither { @link #isEntailed ( Iterable ) } nor a { @link org . semanticweb . elk . reasoner . query . ProperEntailmentQueryResult ProperEntailmentQueryResult } for any of these axioms will throw { @link ElkQueryException } . [CODESPLIT] void registerQueries ( final Iterable < ? extends ElkAxiom > axioms ) { lastQueries_ . clear ( ) ; for ( final ElkAxiom axiom : axioms ) { LOGGER_ . trace ( \"entailment query registered {}\" , axiom ) ; lastQueries_ . add ( axiom ) ; QueryState state = queried_ . get ( axiom ) ; if ( state != null ) { queriedEvictor_ . add ( state ) ; continue ; } // Create query state. state = new QueryState ( axiom ) ; queried_ . put ( axiom , state ) ; queriedEvictor_ . add ( state ) ; toLoad_ . offer ( axiom ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides whether the supplied { @code axioms } are entailed . If some of the supplied axioms was not registered by { @link #registerQueries ( Iterable ) } . [CODESPLIT] Map < ElkAxiom , EntailmentQueryResult > isEntailed ( final Iterable < ? extends ElkAxiom > axioms ) throws ElkQueryException { final Map < ElkAxiom , EntailmentQueryResult > results = new ArrayHashMap < ElkAxiom , EntailmentQueryResult > ( ) ; for ( final ElkAxiom axiom : axioms ) { if ( ! EntailmentQueryConverter . isEntailmentCheckingSupported ( axiom . getClass ( ) ) ) { results . put ( axiom , new UnsupportedQueryTypeEntailmentQueryResultImpl ( axiom ) ) ; continue ; } // else final QueryState state = queried_ . get ( axiom ) ; if ( state == null ) { throw new ElkQueryException ( \"Query was not registered: \" + axiom ) ; } // else if ( state . indexed == null ) { results . put ( axiom , new UnsupportedIndexingEntailmentQueryResultImpl ( axiom ) ) ; continue ; } // else state . lock ( ) ; results . put ( axiom , state ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the parameters of the computation for this stage ; this is the first thing to be done before stage is executed [CODESPLIT] @ Override public boolean preExecute ( ) { if ( isInitialized_ ) return false ; LOGGER_ . trace ( \"{}: initialized\" , this ) ; this . workerNo = reasoner . getNumberOfWorkers ( ) ; return isInitialized_ = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear the parameters of the computation for this stage ; this is the last thing to be done when the stage is executed * [CODESPLIT] @ Override public boolean postExecute ( ) { if ( ! isInitialized_ ) return false ; LOGGER_ . trace ( \"{}: done\" , this ) ; this . isCompleted_ = true ; this . workerNo = 0 ; this . isInitialized_ = false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marks this { @link AbstractReasonerStage } as not completed ; this will require its execution next time unless { @link #setCompleted () } is called [CODESPLIT] boolean invalidate ( ) { if ( ! isCompleted_ && ! isInitialized_ ) { return false ; } LOGGER_ . trace ( \"{}: invalidated\" , this ) ; isCompleted_ = false ; isInitialized_ = false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invalidates this stage and all subsequent stages if not already done so [CODESPLIT] public void invalidateRecursive ( ) { Queue < AbstractReasonerStage > toInvalidate_ = new LinkedList < AbstractReasonerStage > ( ) ; toInvalidate_ . add ( this ) ; AbstractReasonerStage next ; while ( ( next = toInvalidate_ . poll ( ) ) != null ) { if ( next . invalidate ( ) ) { for ( AbstractReasonerStage postStage : next . postStages_ ) { toInvalidate_ . add ( postStage ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the hash for an entity node . This method implements a simple cache for nodes with unusually large numbers of members . This mainly covers the case where a huge number of classes is equal to owl : Nothing due to modelling errors . [CODESPLIT] @ Override public int hash ( Node < ? extends ElkEntity > node ) { if ( node . size ( ) >= cacheNodeMemberNo ) { if ( hashCache . containsKey ( node ) ) { return hashCache . get ( node ) ; } // else int hash = HashGenerator . combineMultisetHash ( true , node , elkEntityHasher ) ; hashCache . put ( node , hash ) ; return hash ; } // else return HashGenerator . combineMultisetHash ( true , node , elkEntityHasher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prunes { @link #toAdd_ } . <p > <strong > { @code taxonomy_ } must not be { @code null } !< / strong > [CODESPLIT] private int pruneToAdd ( ) { final Iterator < IndexedIndividual > iter = toAdd_ . iterator ( ) ; int size = 0 ; while ( iter . hasNext ( ) ) { final IndexedIndividual ind = iter . next ( ) ; /* @formatter:off\n\t\t\t * \n\t\t\t * Should be pruned when:\n\t\t\t * it is not in ontology, or\n\t\t\t * it has types in taxonomy.\n\t\t\t * \n\t\t\t * @formatter:on\n\t\t\t */ if ( ! ind . occurs ( ) ) { iter . remove ( ) ; continue ; } // else final Context context = saturationState_ . getContext ( ind ) ; if ( context == null || ! context . isInitialized ( ) || ! context . isSaturated ( ) ) { // it is not saturated. size ++ ; continue ; } // else final InstanceNode < ElkClass , ElkNamedIndividual > node = taxonomy_ . getInstanceNode ( ind . getElkEntity ( ) ) ; if ( node == null ) { // it is not in taxonomy size ++ ; continue ; } // else if ( ! node . getDirectTypeNodes ( ) . isEmpty ( ) ) { iter . remove ( ) ; continue ; } // else size ++ ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns collection that contains at least all individuals that are in ontology but either are removed from taxonomy or their type nodes in taxonomy were removed . [CODESPLIT] Collection < IndexedIndividual > getToAdd ( ) { if ( taxonomy_ == null ) { // No individual can be pruned. return toAdd_ ; } // else final int size = pruneToAdd ( ) ; /*\n\t\t * since getting the size of the queue is a linear operation, use the\n\t\t * computed size\n\t\t */ return Operations . getCollection ( toAdd_ , size ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prunes { @link #toRemove_ } . <p > <strong > { @code taxonomy_ } must not be { @code null } !< / strong > [CODESPLIT] private int pruneToRemove ( ) { final Iterator < IndexedIndividual > iter = toRemove_ . iterator ( ) ; int size = 0 ; while ( iter . hasNext ( ) ) { final IndexedIndividual cls = iter . next ( ) ; /* @formatter:off\n\t\t\t * \n\t\t\t * Should be pruned when\n\t\t\t * it is not in taxonomy.\n\t\t\t * \n\t\t\t * @formatter:on\n\t\t\t */ final InstanceNode < ElkClass , ElkNamedIndividual > node = taxonomy_ . getInstanceNode ( cls . getElkEntity ( ) ) ; if ( node == null ) { iter . remove ( ) ; continue ; } // else size ++ ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns collection that contains at least all individuals that are in taxonomy but either are removed from ontology or their context became not saturated . [CODESPLIT] Collection < IndexedIndividual > getToRemove ( ) { if ( taxonomy_ == null ) { // TODO: Never set taxonomy_ to null !!! // no individuals are in taxonomy toRemove_ . clear ( ) ; return Collections . emptyList ( ) ; } // else final int size = pruneToRemove ( ) ; /*\n\t\t * since getting the size of the queue is a linear operation, use the\n\t\t * computed size\n\t\t */ return Operations . getCollection ( toRemove_ , size ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a { @link TypeNode } object for a given { @link ElkClass } or { @code null } if none assigned . [CODESPLIT] @ Override public IndividualNode . Projection < ElkClass , ElkNamedIndividual > getInstanceNode ( final ElkNamedIndividual individual ) { return individualNodeStore_ . getNode ( individual ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param factory the factory for creating conclusions [CODESPLIT] public BackwardLink getConclusion ( BackwardLink . Factory factory ) { return factory . getBackwardLink ( getDestination ( ) , conclusionRelation_ , conclusionSource_ ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs a warning message for unsupported OWL API method [CODESPLIT] private static UnsupportedOperationException unsupportedOwlApiMethod ( String method ) { String message = \"OWL API reasoner method is not implemented: \" + method + \".\" ; /*\n\t\t * TODO: The method String can be used to create more specific message\n\t\t * types, but with the current large amount of unsupported methods and\n\t\t * non-persistent settings for ignoring them, we better use only one\n\t\t * message type to make it easier to ignore them.\n\t\t */ LoggerWrap . log ( LOGGER_ , LogLevel . WARN , MARKER_UNSUPPORTED_METHOD_ , message ) ; return new UnsupportedOperationException ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Methods required by the OWLReasoner interface [CODESPLIT] @ Override public void dispose ( ) { LOGGER_ . trace ( \"dispose()\" ) ; owlOntologymanager_ . removeOntologyChangeListener ( ontologyChangeListener_ ) ; owlOntologymanager_ . removeOntologyChangeProgessListener ( ontologyChangeProgressListener_ ) ; try { for ( ; ; ) { try { if ( ! reasoner_ . shutdown ( ) ) throw new ReasonerInternalException ( \"Failed to shut down ELK!\" ) ; break ; } catch ( InterruptedException e ) { continue ; } } } catch ( ElkRuntimeException e ) { throw elkConverter_ . convert ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the initial capacity of the table for storing elements . The capacity is the largest power of two that does not exceed the given value or { @link #MAXIMUM_CAPACITY } . [CODESPLIT] static int getInitialCapacity ( int capacity ) { if ( capacity < 0 ) throw new IllegalArgumentException ( \"Illegal Capacity: \" + capacity ) ; if ( capacity > LinearProbing . MAXIMUM_CAPACITY ) capacity = LinearProbing . MAXIMUM_CAPACITY ; // Find a power of 2 >= initialCapacity int result = 1 ; while ( result < capacity ) result <<= 1 ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the element at the given position of the table shifting if necessary other elements so that all elements can be found by linear probing . [CODESPLIT] static < E > void remove ( E [ ] d , int pos ) { for ( ; ; ) { int next = getMovedPosition ( d , pos ) ; E moved = d [ pos ] = d [ next ] ; if ( moved == null ) return ; // else pos = next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the element at the given position of the table and the corresponding value at the same position shifting if necessary other elements and values so that all elements can be found by linear probing . [CODESPLIT] static < K , V > void remove ( K [ ] k , V [ ] v , int pos ) { for ( ; ; ) { int next = getMovedPosition ( k , pos ) ; K moved = k [ pos ] = k [ next ] ; v [ pos ] = v [ next ] ; if ( moved == null ) return ; // else pos = next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the position of the next element starting from the given position that would not be found by linear probing if the element at the given position are deleted . This should be the element whose index is smaller than this position . [CODESPLIT] static < E > int getMovedPosition ( E [ ] d , int del ) { int j = del ; for ( ; ; ) { if ( ++ j == d . length ) j = 0 ; // invariant: interval ]del, j] contains only non-null elements // whose index is in ]del, j] E test = d [ j ] ; if ( test == null ) return j ; int k = getIndex ( test , d . length ) ; // check if k is in ]del, j] (this interval can wrap over) if ( ( del < j ) ? ( del < k ) && ( k <= j ) : ( del < k ) || ( k <= j ) ) // the test element should not be shifted continue ; // else it should be shifted return j ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if the set represented by given data array contains a given object . [CODESPLIT] static < E > boolean contains ( E [ ] d , Object o ) { int pos = getPosition ( d , o ) ; if ( d [ pos ] == null ) return false ; // else return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the element to the set represented by given data array if it did not contain there already . [CODESPLIT] static < E > boolean add ( E [ ] d , E e ) { int pos = getPosition ( d , e ) ; if ( d [ pos ] == null ) { d [ pos ] = e ; return true ; } // else the element is already there return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verifies that occurrence numbers are not negative [CODESPLIT] public final void checkOccurrenceNumbers ( ) { if ( LOGGER_ . isTraceEnabled ( ) ) LOGGER_ . trace ( toString ( ) + \" occurences: \" + printOccurrenceNumbers ( ) ) ; if ( positiveOccurrenceNo < 0 || negativeOccurrenceNo < 0 ) throw new ElkUnexpectedIndexingException ( toString ( ) + \" has a negative occurrence: \" + printOccurrenceNumbers ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : perhaps convert using some visitor [CODESPLIT] public OWLRuntimeException convert ( ElkException e ) { if ( e instanceof ElkFreshEntitiesException ) return convert ( ( ElkFreshEntitiesException ) e ) ; else if ( e instanceof ElkInconsistentOntologyException ) return convert ( ( ElkInconsistentOntologyException ) e ) ; else if ( e instanceof ElkInterruptedException ) return convert ( ( ElkInterruptedException ) e ) ; else return new OWLRuntimeException ( e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all timers of the argument to the corresponding counters of this object . The timers should not be directly modified other than using this method during this operation . The timers in the argument will be reseted after this operation . [CODESPLIT] public synchronized void add ( ClassConclusionTimer timer ) { this . timeComposedSubsumers += timer . timeComposedSubsumers ; this . timeDecomposedSubsumers += timer . timeDecomposedSubsumers ; this . timeBackwardLinks += timer . timeBackwardLinks ; this . timeForwardLinks += timer . timeForwardLinks ; this . timeContradictions += timer . timeContradictions ; this . timePropagations += timer . timePropagations ; this . timeDisjointSubsumers += timer . timeDisjointSubsumers ; this . timeContextInitializations += timer . timeContextInitializations ; this . timeSubContextInitializations += timer . timeSubContextInitializations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : simplify the implementation to use just one weak wrapper [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override protected < C extends ElkObject > C filter ( C candidate ) { if ( candidate instanceof ElkEntity ) return ( C ) getCanonicalElkEntity ( ( ElkEntity ) candidate ) ; else return candidate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the values the corresponding values of the given timer [CODESPLIT] public synchronized void add ( RuleApplicationTimer timer ) { timeOwlThingContextInitRule += timer . timeOwlThingContextInitRule ; timeRootContextInitializationRule += timer . timeRootContextInitializationRule ; timeDisjointSubsumerFromMemberRule += timer . timeDisjointSubsumerFromMemberRule ; timeContradictionFromNegationRule += timer . timeContradictionFromNegationRule ; timeObjectIntersectionFromFirstConjunctRule += timer . timeObjectIntersectionFromFirstConjunctRule ; timeObjectIntersectionFromSecondConjunctRule += timer . timeObjectIntersectionFromSecondConjunctRule ; timeSuperClassFromSubClassRule += timer . timeSuperClassFromSubClassRule ; timePropagationFromExistentialFillerRule += timer . timePropagationFromExistentialFillerRule ; timeObjectUnionFromDisjunctRule += timer . timeObjectUnionFromDisjunctRule ; timeBackwardLinkChainFromBackwardLinkRule += timer . timeBackwardLinkChainFromBackwardLinkRule ; timeReflexiveBackwardLinkCompositionRule += timer . timeReflexiveBackwardLinkCompositionRule ; timeNonReflexiveBackwardLinkCompositionRule += timer . timeNonReflexiveBackwardLinkCompositionRule ; timeSubsumerBackwardLinkRule += timer . timeSubsumerBackwardLinkRule ; timeContradictionOverBackwardLinkRule += timer . timeContradictionOverBackwardLinkRule ; timeContradictionPropagationRule += timer . timeContradictionPropagationRule ; timeContradictionCompositionRule += timer . timeContradictionCompositionRule ; timeIndexedObjectIntersectionOfDecomposition += timer . timeIndexedObjectIntersectionOfDecomposition ; timeIndexedObjectSomeValuesFromDecomposition += timer . timeIndexedObjectSomeValuesFromDecomposition ; timeIndexedObjectComplementOfDecomposition += timer . timeIndexedObjectComplementOfDecomposition ; timeIndexedObjectHasSelfDecomposition += timer . timeIndexedObjectHasSelfDecomposition ; timeContradictionFromOwlNothingRule += timer . timeContradictionFromOwlNothingRule ; timeSubsumerPropagationRule += timer . timeSubsumerPropagationRule ; timePropagationInitializationRule += timer . timePropagationInitializationRule ; timeBackwardLinkFromForwardLinkRule += timer . timeBackwardLinkFromForwardLinkRule ; timeComposedFromDecomposedSubsumerRule += timer . timeComposedFromDecomposedSubsumerRule ; timeIndexedClassDecompositionRule += timer . timeIndexedClassDecompositionRule ; timeIndexedClassFromDefinitionRule += timer . timeIndexedClassFromDefinitionRule ; timeEquivalentClassFirstFromSecondRule += timer . timeEquivalentClassFirstFromSecondRule ; timeEquivalentClassSecondFromFirstRule += timer . timeEquivalentClassSecondFromFirstRule ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "logging is switched off [CODESPLIT] @ Override protected Boolean defaultVisit ( ClassConclusion conclusion ) { ClassConclusionSet conclusions = conclusionsRef_ . get ( ) ; boolean result = conclusions == null ? false : conclusions . containsConclusion ( conclusion ) ; if ( LOGGER_ . isTraceEnabled ( ) ) { LOGGER_ . trace ( \"{}: check occurrence of {}: {}\" , conclusions , conclusion , result ? \"success\" : \"failure\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates stage that computes object property taxonomy . [CODESPLIT] AbstractReasonerStage createStage ( final AbstractReasonerState reasoner , final AbstractReasonerStage ... preStages ) { return new AbstractReasonerStage ( reasoner , preStages ) { /**\n\t\t\t * The computation used for this stage.\n\t\t\t */ private ObjectPropertyTaxonomyComputation computation_ = null ; @ Override public String getName ( ) { return \"Object Property Taxonomy Computation\" ; } @ Override public boolean preExecute ( ) { if ( ! super . preExecute ( ) ) { return false ; } resetTaxonomy ( ) ; computation_ = new ObjectPropertyTaxonomyComputation ( reasoner . ontologyIndex , reasoner . getInterrupter ( ) , transitiveReductionOutputProcessor_ , reasoner . getElkFactory ( ) , reasoner . getProcessExecutor ( ) , workerNo , reasoner . getProgressMonitor ( ) ) ; return true ; } @ Override void executeStage ( ) throws ElkException { computation_ . process ( ) ; } @ Override public boolean postExecute ( ) { if ( ! super . postExecute ( ) ) { return false ; } this . computation_ = null ; return true ; } @ Override public void printInfo ( ) { // TODO Auto-generated method stub } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param factory the factory for creating conclusions [CODESPLIT] public ForwardLink getConclusion ( ForwardLink . Factory factory ) { return factory . getForwardLink ( getDestination ( ) , existential_ . getProperty ( ) , getOrigin ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an { @link OwlThingContextInitRule } to the given { @link ModifiableOntologyIndex } [CODESPLIT] public static boolean addRuleFor ( IndexedClass owlThing , ModifiableOntologyIndex index ) { LOGGER_ . trace ( \"{}: adding {}\" , owlThing , NAME ) ; return index . addContextInitRule ( new OwlThingContextInitRule ( owlThing ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes an { @link OwlThingContextInitRule } from the given { @link ModifiableOntologyIndex } [CODESPLIT] public static boolean removeRuleFor ( IndexedClass owlThing , ModifiableOntologyIndex index ) { LOGGER_ . trace ( \"{}: removing {}\" , owlThing , NAME ) ; return index . removeContextInitRule ( new OwlThingContextInitRule ( owlThing ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the given key with the given value in the map defined by the keys and value arrays . If an entry with the key equal to the given one already exists in the map the value for this key will be overwritten with the given value . [CODESPLIT] private static < K , V > V putKeyValue ( K [ ] keys , V [ ] values , K key , V value ) { int pos = LinearProbing . getPosition ( keys , key ) ; if ( keys [ pos ] == null ) { keys [ pos ] = key ; values [ pos ] = value ; return null ; } // else V oldValue = values [ pos ] ; values [ pos ] = value ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the entry in the keys and values such that the key of the entry is equal to the given object according to the equality function . [CODESPLIT] private static < K , V > V removeEntry ( K [ ] keys , V [ ] values , Object key ) { int pos = LinearProbing . getPosition ( keys , key ) ; if ( keys [ pos ] == null ) return null ; // else V result = values [ pos ] ; LinearProbing . remove ( keys , values , pos ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increasing the capacity of the map [CODESPLIT] private void enlarge ( ) { int oldCapacity = keys . length ; if ( oldCapacity == LinearProbing . MAXIMUM_CAPACITY ) throw new IllegalArgumentException ( \"Map cannot grow beyond capacity: \" + LinearProbing . MAXIMUM_CAPACITY ) ; K oldKeys [ ] = keys ; V oldValues [ ] = values ; int newCapacity = oldCapacity << 1 ; @ SuppressWarnings ( \"unchecked\" ) K newKeys [ ] = ( K [ ] ) new Object [ newCapacity ] ; @ SuppressWarnings ( \"unchecked\" ) V newValues [ ] = ( V [ ] ) new Object [ newCapacity ] ; for ( int i = 0 ; i < oldCapacity ; i ++ ) { K key = oldKeys [ i ] ; if ( key != null ) putKeyValue ( newKeys , newValues , key , oldValues [ i ] ) ; } this . keys = newKeys ; this . values = newValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decreasing the capacity of the map [CODESPLIT] private void shrink ( ) { int oldCapacity = keys . length ; if ( oldCapacity <= LinearProbing . DEFAULT_INITIAL_CAPACITY ) return ; K oldKeys [ ] = keys ; V oldValues [ ] = values ; int newCapacity = oldCapacity >> 1 ; @ SuppressWarnings ( \"unchecked\" ) K newKeys [ ] = ( K [ ] ) new Object [ newCapacity ] ; @ SuppressWarnings ( \"unchecked\" ) V newValues [ ] = ( V [ ] ) new Object [ newCapacity ] ; for ( int i = 0 ; i < oldCapacity ; i ++ ) { K key = oldKeys [ i ] ; if ( key != null ) putKeyValue ( newKeys , newValues , key , oldValues [ i ] ) ; } this . keys = newKeys ; this . values = newValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Not a thread - safe method . Shouldn t be invoked concurrently . [CODESPLIT] public void saveConfiguration ( File configOnDisk , BaseConfiguration config ) throws ConfigurationException , IOException { /*\n\t\t * Unfortunately, we can't directly write the config on disk because the\n\t\t * parameters in it may be just a subset of those on disk. So we load it\n\t\t * first (alternatively one may use a singleton, which I typically try\n\t\t * to avoid). It should work reasonably well unless there're too many\n\t\t * parameters (in which case we should think of a mini key-value store).\n\t\t */ InputStream stream = null ; BaseConfiguration loadedConfig = null ; Properties diskProps = new Properties ( ) ; try { stream = new FileInputStream ( configOnDisk ) ; loadedConfig = getConfiguration ( stream , \"\" , config . getClass ( ) ) ; // copy parameters copyParameters ( loadedConfig , diskProps ) ; } catch ( Throwable e ) { LOGGER_ . info ( \"Overwriting configuration since it can't be loaded (perhaps doesn't exist?)\" ) ; } finally { IOUtils . closeQuietly ( stream ) ; } copyParameters ( config , diskProps ) ; // now save it to the file saveProperties ( diskProps , configOnDisk ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches for the next non - { @code null } element after the given position before the start position [CODESPLIT] int seekNext ( int pos ) { for ( ; ; ) { if ( ++ pos == dataSnapshot . length ) pos = 0 ; if ( pos == start_ || isOccupied ( pos ) ) return pos ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prints SubClassOf ( A owl : Thing ) for all direct subclasses of owl : Thing [CODESPLIT] static void printClassTaxonomy ( Taxonomy < ElkClass > taxonomy , File out ) throws IOException { FileWriter fstream = null ; BufferedWriter writer = null ; try { fstream = new FileWriter ( out ) ; writer = new BufferedWriter ( fstream ) ; writer . append ( \"Ontology(\\n\" ) ; processTaxomomy ( taxonomy , writer ) ; writer . append ( \")\\n\" ) ; writer . flush ( ) ; } finally { IOUtils . closeQuietly ( fstream ) ; IOUtils . closeQuietly ( writer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints class declarations [CODESPLIT] protected static void printDeclarations ( Taxonomy < ElkClass > classTaxonomy , ElkObject . Factory objectFactory , Appendable writer ) throws IOException { List < ElkClass > classes = new ArrayList < ElkClass > ( classTaxonomy . getNodes ( ) . size ( ) * 2 ) ; for ( TaxonomyNode < ElkClass > classNode : classTaxonomy . getNodes ( ) ) { for ( ElkClass clazz : classNode ) { if ( ! clazz . getIri ( ) . equals ( PredefinedElkIris . OWL_THING ) && ! clazz . getIri ( ) . equals ( PredefinedElkIris . OWL_NOTHING ) ) { classes . add ( clazz ) ; } } } Collections . sort ( classes , CLASS_COMPARATOR ) ; for ( ElkClass clazz : classes ) { ElkDeclarationAxiom decl = objectFactory . getDeclarationAxiom ( clazz ) ; OwlFunctionalStylePrinter . append ( writer , decl , true ) ; writer . append ( ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all super - nodes of a node whose direct super - nodes are <code > direct< / code > . [CODESPLIT] public static < T extends ElkEntity , N extends GenericTaxonomyNode < T , N > > Set < ? extends N > getAllSuperNodes ( final Collection < ? extends N > direct ) { return getAllReachable ( direct , new Functor < N , Set < ? extends N > > ( ) { @ Override public Set < ? extends N > apply ( final N node ) { return node . getDirectSuperNodes ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all sub - nodes of a node whose direct sub - nodes are <code > direct< / code > . [CODESPLIT] public static < T extends ElkEntity , N extends GenericTaxonomyNode < T , N > > Set < ? extends N > getAllSubNodes ( final Collection < ? extends N > direct ) { return getAllReachable ( direct , new Functor < N , Set < ? extends N > > ( ) { @ Override public Set < ? extends N > apply ( final N node ) { return node . getDirectSubNodes ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all instance nodes of the specified type node and all its sub - nodes . [CODESPLIT] public static < T extends ElkEntity , I extends ElkEntity , TN extends GenericTypeNode < T , I , TN , IN > , IN extends GenericInstanceNode < T , I , TN , IN > > Set < ? extends IN > getAllInstanceNodes ( final GenericTypeNode < T , I , TN , IN > node ) { return TaxonomyNodeUtils . collectFromAllReachable ( node . getDirectSubNodes ( ) , node . getDirectInstanceNodes ( ) , new Operations . Functor < GenericTypeNode < T , I , TN , IN > , Set < ? extends GenericTypeNode < T , I , TN , IN > > > ( ) { @ Override public Set < ? extends TN > apply ( final GenericTypeNode < T , I , TN , IN > node ) { return node . getDirectSubNodes ( ) ; } } , new Operations . Functor < GenericTypeNode < T , I , TN , IN > , Set < ? extends IN > > ( ) { @ Override public Set < ? extends IN > apply ( final GenericTypeNode < T , I , TN , IN > node ) { return node . getDirectInstanceNodes ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Chain } view of the value associated with the given key in the given { @link Map } . The values of the map must be instances of the type that can be used in the { @link Chain } interface . All operations with the returned { @link Chain } such as addition or removal will be reflected accordingly in the corresponding value in the { @link Map } . [CODESPLIT] public static < K , T extends ModifiableLink < T > > Chain < T > getMapBackedChain ( final Map < K , T > map , final K key ) { return new AbstractChain < T > ( ) { @ Override public T next ( ) { return map . get ( key ) ; } @ Override public void setNext ( T next ) { if ( next == null ) map . remove ( key ) ; else map . put ( key , next ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and returns the entry in set that is structurally equal to the input entry if there is one . Equality of entries is decided using { @link Entry#structuralHashCode () } and { @link Entry#structuralEquals ( Object ) } methods . [CODESPLIT] public < T extends Entry < T , ? > > T findStructural ( Entry < T , ? > entry ) { int h = entry . structuralHashCode ( ) ; int i = indexFor ( h , buckets . length ) ; T result = null ; for ( E r = buckets [ i ] ; r != null ; r = r . getNext ( ) ) { if ( r . structuralHashCode ( ) == h && ( result = entry . structuralEquals ( r ) ) != null ) return result ; } // else fail return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given entry to this collection ; the entry is added even if a structurally equal entry ( modulo { @link Entry#structuralHashCode () } and { @link Entry#structuralEquals ( Object ) } ) is already present in the collection [CODESPLIT] public void addStructural ( E entry ) { if ( entry . getNext ( ) != null ) throw new IllegalArgumentException ( \"The given entry should be fresh!\" ) ; int h = entry . structuralHashCode ( ) ; int i = indexFor ( h , buckets . length ) ; modCount ++ ; E e = buckets [ i ] ; entry . setNext ( e ) ; buckets [ i ] = entry ; if ( size ++ >= oversize ) resize ( 2 * buckets . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes and returns the entry in the set that is structurally equal to the specified entry . Returns { @code null } if the set contains no such entry . Equality of entries is decided using { @link Entry#structuralHashCode () } and { @link Entry#structuralEquals ( Object ) } methods . [CODESPLIT] public < T extends Entry < T , ? > > T removeStructural ( Entry < T , ? > entry ) { int h = entry . structuralHashCode ( ) ; int i = indexFor ( h , buckets . length ) ; E prev = buckets [ i ] ; E r = prev ; T result = null ; while ( r != null ) { E next = r . getNext ( ) ; if ( r . structuralHashCode ( ) == h && ( result = entry . structuralEquals ( r ) ) != null ) { modCount ++ ; if ( prev == r ) buckets [ i ] = next ; else prev . setNext ( next ) ; if ( size -- <= undersize && buckets . length >= 2 * minsize ) resize ( buckets . length / 2 ) ; return result ; } prev = r ; r = next ; } // not found return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rehashes the contents of this map into a new array with a new capacity . This method is called automatically when the number of entries in this set becomes below the { @link #undersize } or above the { @link #oversize } . [CODESPLIT] void resize ( int newCapacity ) { E [ ] oldTable = buckets ; int oldCapacity = oldTable . length ; if ( oldCapacity == MAXIMUM_CAPACITY ) { oversize = Integer . MAX_VALUE ; oversize = ( int ) ( newCapacity * overloadFactor ) ; return ; } @ SuppressWarnings ( \"unchecked\" ) E [ ] newTable = ( E [ ] ) new Entry [ newCapacity ] ; transfer ( newTable ) ; buckets = newTable ; undersize = ( int ) ( newCapacity * underloadFactor ) ; oversize = ( int ) ( newCapacity * overloadFactor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all entries from this set . The set will be empty after this call returns . [CODESPLIT] @ Override public void clear ( ) { modCount ++ ; E [ ] tab = buckets ; for ( int i = 0 ; i < tab . length ; i ++ ) tab [ i ] = null ; size = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "logging is switched off [CODESPLIT] @ Override protected Boolean defaultVisit ( ClassConclusion conclusion ) { ClassConclusionSet conclusions = conclusionsRef . get ( ) ; boolean result = conclusions . removeConclusion ( conclusion ) ; if ( LOGGER_ . isTraceEnabled ( ) ) { LOGGER_ . trace ( \"{}: deleting {}: {}\" , conclusions , conclusion , result ? \"success\" : \"failure\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param factory the factory for creating conclusions [CODESPLIT] public final Propagation getConclusion ( Propagation . Factory factory ) { return factory . getPropagation ( getDestination ( ) , getRelation ( ) , getCarry ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the combined hash code of several objects using their { @link #hashCode () } functions . The combined hash code depends on the order in which the objects are listed . [CODESPLIT] public static int combinedHashCode ( Object ... objects ) { int result = 0 ; for ( Object obj : objects ) { int h = obj . hashCode ( ) ; result += h ; result += ( h << 10 ) ; result ^= ( h >> 6 ) ; } result += ( result << 3 ) ; result ^= ( result >> 11 ) ; result += ( result << 15 ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine many hash codes with an associative commutative hash function . Associativity ensures that the result of this functions can be further combined with other hash codes for getting the same result as if all hash codes had been combined in one step . [CODESPLIT] public static int combineMultisetHash ( boolean finalize , int ... hashes ) { int hash = 0 ; for ( int h : hashes ) { hash = hash + h ; } if ( finalize ) { hash = combineListHash ( hash ) ; } return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the hash codes of a collection of objects with an associative commutative hash function . Associativity ensures that the result of this functions can be further combined with other hash codes for getting the same result as if all hash codes had been combined in one step . [CODESPLIT] public static < T > int combineMultisetHash ( boolean finalize , Iterable < ? extends T > hashObjects , Hasher < T > hasher ) { return combineMultisetHash ( finalize , hashObjects . iterator ( ) , hasher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the hash codes of a collection of objects with an associative commutative hash function . Associativity ensures that the result of this functions can be further combined with other hash codes for getting the same result as if all hash codes had been combined in one step . [CODESPLIT] public static < T > int combineMultisetHash ( boolean finalize , Iterator < ? extends T > hashObjectIterator , Hasher < T > hasher ) { int hash = 0 ; while ( hashObjectIterator . hasNext ( ) ) { hash += hasher . hash ( hashObjectIterator . next ( ) ) ; } if ( finalize ) { hash = combineListHash ( hash ) ; } return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine many hash codes into one in a way that depends on their order . [CODESPLIT] public static int combineListHash ( int ... hashes ) { int hash = 0 ; for ( int h : hashes ) { hash += h ; hash += ( hash << 10 ) ; hash ^= ( hash >> 6 ) ; } hash += ( hash << 3 ) ; hash ^= ( hash >> 11 ) ; hash += ( hash << 15 ) ; return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the hash codes of a collection of objects into one in a way that depends on their order . [CODESPLIT] public static < T > int combineListHash ( List < ? extends T > hashObjects , Hasher < T > hasher ) { return combineListHash ( hashObjects . iterator ( ) , hasher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the hash codes of a collection of objects into one in a way that depends on their order . [CODESPLIT] public static < T > int combineListHash ( Iterator < ? extends T > hashObjectIterator , Hasher < T > hasher ) { int hash = 0 ; while ( hashObjectIterator . hasNext ( ) ) { hash += hasher . hash ( hashObjectIterator . next ( ) ) ; hash += ( hash << 10 ) ; hash ^= ( hash >> 6 ) ; } hash += ( hash << 3 ) ; hash ^= ( hash >> 11 ) ; hash += ( hash << 15 ) ; return hash ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies bytes from the input stream to the output stream [CODESPLIT] public static int copy ( InputStream input , OutputStream output ) throws IOException { byte [ ] buffer = new byte [ BUFFER_SIZE ] ; BufferedInputStream in = new BufferedInputStream ( input , BUFFER_SIZE ) ; BufferedOutputStream out = new BufferedOutputStream ( output , BUFFER_SIZE ) ; int count = 0 , n = 0 ; try { while ( ( n = in . read ( buffer , 0 , BUFFER_SIZE ) ) != - 1 ) { out . write ( buffer , 0 , n ) ; count += n ; } out . flush ( ) ; } finally { IOUtils . closeQuietly ( in ) ; IOUtils . closeQuietly ( out ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a set of resource names from a JAR file ( the code source for the given Java class ) [CODESPLIT] public static List < String > getResourceNamesFromJAR ( String path , String extension , Class < ? > clazz ) throws IOException { CodeSource src = clazz . getProtectionDomain ( ) . getCodeSource ( ) ; List < String > testResources = new ArrayList < String > ( ) ; ZipInputStream zip = null ; if ( src != null ) { URL jar = src . getLocation ( ) ; ZipEntry ze = null ; try { zip = new ZipInputStream ( jar . openStream ( ) ) ; while ( ( ze = zip . getNextEntry ( ) ) != null ) { String entryName = ze . getName ( ) ; if ( entryName . startsWith ( path ) && entryName . endsWith ( \".\" + extension ) ) { testResources . add ( entryName ) ; } } } finally { closeQuietly ( zip ) ; } } else { throw new IOException ( \"Unable to get code source for \" + clazz . getSimpleName ( ) ) ; } return testResources ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param factory the factory for creating conclusions [CODESPLIT] public ForwardLink getConclusion ( ClassConclusion . Factory factory ) { return factory . getForwardLink ( getDestination ( ) , existential_ . getProperty ( ) , IndexedObjectSomeValuesFrom . Helper . getTarget ( existential_ ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the given input concurrently using the provided input processor . If the process has been interrupted this method can be called again to continue the computation . [CODESPLIT] public void process ( ) { if ( ! start ( ) ) { String message = \"Could not start workers required for reasoner computation!\" ; LOGGER_ . error ( message ) ; throw new ElkRuntimeException ( message ) ; } try { // submit the leftover from the previous run if ( nextInput != null ) { if ( ! processNextInput ( ) ) return ; } // repeatedly submit the next inputs from todo while ( todo . hasNext ( ) ) { nextInput = todo . next ( ) ; if ( ! processNextInput ( ) ) return ; } finish ( ) ; } catch ( InterruptedException e ) { // restore interrupt status Thread . currentThread ( ) . interrupt ( ) ; throw new ElkRuntimeException ( \"Reasoner computation interrupted externally!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combines the provided partial incompleteness monitors into the top - level monitor for reasoning tasks . [CODESPLIT] public IncompletenessMonitor getReasonerIncompletenessMonitor ( final IncompletenessMonitor ... additionalMonitors ) { final List < IncompletenessMonitor > monitors = new ArrayList < IncompletenessMonitor > ( additionalMonitors . length + 1 ) ; monitors . add ( getIncompletenessDueToStatedAxiomsMonitor ( ) ) ; monitors . addAll ( Arrays . asList ( additionalMonitors ) ) ; return new DelegatingIncompletenessMonitor ( monitors ) { @ Override public boolean logNewIncompletenessReasons ( final Logger logger ) { final boolean result = super . logNewIncompletenessReasons ( logger ) ; if ( result ) { LoggerWrap . log ( logger , LogLevel . WARN , MARKER_ , \"Reasoning may be incomplete! See log level INFO for more details.\" ) ; } return result ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : parentheses and precedence of symbols [CODESPLIT] @ Override public String visit ( IndexedClass element ) { ElkClass entity = element . getElkEntity ( ) ; if ( entity . getIri ( ) . equals ( PredefinedElkIris . OWL_THING ) ) { return \"⊤\";  } // else if ( entity . getIri ( ) . equals ( PredefinedElkIris . OWL_NOTHING ) ) { return \"⊥\";  } // else return entity . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * read - write methods [CODESPLIT] @ Override public void add ( CachedIndexedObject < ? > input ) { if ( ! incrementalMode ) { super . add ( input ) ; return ; } // else incrementalMode LOGGER_ . trace ( \"{}: to add\" , input ) ; if ( input instanceof IndexedEntity ) ( ( IndexedEntity ) input ) . accept ( entityInsertionListener_ ) ; if ( todoDeletions_ . remove ( input ) ) return ; // else super . add ( input ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the deleted rules from this { [CODESPLIT] public void clearDeletedRules ( ) { for ( CachedIndexedObject < ? > deletion : todoDeletions_ ) { LOGGER_ . trace ( \"{}: comitting removal\" , deletion ) ; super . remove ( deletion ) ; } initDeletions ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Commits the added rules to the main index and removes them from this { [CODESPLIT] public void commitAddedRules ( ) { // commit changes in the context initialization rules ChainableContextInitRule nextContextInitRule ; Chain < ChainableContextInitRule > contextInitRuleChain ; nextContextInitRule = addedContextInitRules_ ; contextInitRuleChain = getContextInitRuleChain ( ) ; while ( nextContextInitRule != null ) { nextContextInitRule . addTo ( contextInitRuleChain ) ; nextContextInitRule = nextContextInitRule . next ( ) ; } // commit changes in rules for IndexedClassExpression ChainableSubsumerRule nextClassExpressionRule ; Chain < ChainableSubsumerRule > classExpressionRuleChain ; for ( ModifiableIndexedClassExpression target : addedContextRuleHeadByClassExpressions_ . keySet ( ) ) { LOGGER_ . trace ( \"{}: committing context rule additions\" , target ) ; nextClassExpressionRule = addedContextRuleHeadByClassExpressions_ . get ( target ) ; classExpressionRuleChain = target . getCompositionRuleChain ( ) ; while ( nextClassExpressionRule != null ) { nextClassExpressionRule . addTo ( classExpressionRuleChain ) ; nextClassExpressionRule = nextClassExpressionRule . next ( ) ; } } for ( ModifiableIndexedClass target : addedDefinitions_ . keySet ( ) ) { ModifiableIndexedClassExpression definition = addedDefinitions_ . get ( target ) ; ElkAxiom reason = addedDefinitionReasons_ . get ( target ) ; LOGGER_ . trace ( \"{}: committing definition addition {}\" , target , definition ) ; if ( ! target . setDefinition ( definition , reason ) ) throw new ElkUnexpectedIndexingException ( target ) ; } initAdditions ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the incremental mode for this { @code DifferentialIndex } . [CODESPLIT] public void setIncrementalMode ( boolean incremental ) { if ( this . incrementalMode == incremental ) // already set return ; LOGGER_ . trace ( \"set incremental mode: \" + incremental ) ; this . incrementalMode = incremental ; if ( ! incremental ) { clearDeletedRules ( ) ; commitAddedRules ( ) ; initClassChanges ( ) ; initIndividualChanges ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add { @link ObjectIntersectionFromFirstConjunctRule } s for the given { @link ModifiableIndexedObjectIntersectionOf } in the given { @link ModifiableOntologyIndex } [CODESPLIT] public static boolean addRulesFor ( ModifiableIndexedObjectIntersectionOf conjunction , ModifiableOntologyIndex index ) { return index . add ( conjunction . getSecondConjunct ( ) , new ObjectIntersectionFromFirstConjunctRule ( conjunction . getFirstConjunct ( ) , conjunction ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes { @link ObjectIntersectionFromFirstConjunctRule } s for the given { @link ModifiableIndexedObjectIntersectionOf } in the given { @link ModifiableOntologyIndex } [CODESPLIT] public static boolean removeRulesFor ( ModifiableIndexedObjectIntersectionOf conjunction , ModifiableOntologyIndex index ) { return index . remove ( conjunction . getSecondConjunct ( ) , new ObjectIntersectionFromFirstConjunctRule ( conjunction . getFirstConjunct ( ) , conjunction ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : create a generic method for this operation ( used in other places ) [CODESPLIT] private int indexOf ( IndexedPropertyChain subChain , ElkAxiom reason ) { for ( int i = 0 ; i < toldSubChains_ . size ( ) ; i ++ ) { if ( toldSubChains_ . get ( i ) . equals ( subChain ) && toldSubChainsReasons_ . get ( i ) . equals ( reason ) ) return i ; } // else not found return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param factory the factory for creating conclusions [CODESPLIT] public final DisjointSubsumer getConclusion ( DisjointSubsumer . Factory factory ) { return factory . getDisjointSubsumer ( getDestination ( ) , getDisjointExpressions ( ) , getPosition ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One - parameter public non - static methods called visit and declared in this class enumerate subclasses of { @link ElkAxiom } ( parameter ) for which entailment queries are supported . This method returns { @code true } iff the subclass of { @link ElkAxiom } specified as the parameter is a parameter type of some of these methods e . g . whether entailment query of such an { @link ElkAxiom } is supported . [CODESPLIT] public static boolean isEntailmentCheckingSupported ( final Class < ? extends ElkAxiom > axiomClass ) { for ( final Method declaredMethod : EntailmentQueryConverter . class . getDeclaredMethods ( ) ) { final int mod = declaredMethod . getModifiers ( ) ; final Class < ? > [ ] parameterTypes = declaredMethod . getParameterTypes ( ) ; if ( \"visit\" . equals ( declaredMethod . getName ( ) ) && Modifier . isPublic ( mod ) && ! Modifier . isStatic ( mod ) && parameterTypes . length == 1 && parameterTypes [ 0 ] . isAssignableFrom ( axiomClass ) ) { // There is a declared visit method that accepts axiomClass return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for printing a { @link Taxonomy } to a file at the given location . [CODESPLIT] public static void dumpTaxomomyToFile ( final Taxonomy < ? extends ElkEntity > taxonomy , final String fileName , final boolean addHash ) throws IOException { final FileWriter fstream = new FileWriter ( fileName ) ; final BufferedWriter writer = new BufferedWriter ( fstream ) ; try { dumpTaxomomy ( taxonomy , writer , addHash ) ; } finally { writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the contents of the given { @link Taxonomy } to the specified Writer . Expressions are ordered for generating the output ensuring that the output is deterministic . [CODESPLIT] public static void dumpTaxomomy ( final Taxonomy < ? extends ElkEntity > taxonomy , final Writer writer , final boolean addHash ) throws IOException { writer . append ( \"Ontology(\\n\" ) ; processTaxomomy ( taxonomy , writer ) ; writer . append ( \")\\n\" ) ; if ( addHash ) { writer . append ( \"\\n# Hash code: \" + getHashString ( taxonomy ) + \"\\n\" ) ; } writer . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for printing an { @link InstanceTaxonomy } to a file at the given location . [CODESPLIT] public static void dumpInstanceTaxomomyToFile ( final InstanceTaxonomy < ? extends ElkEntity , ? extends ElkEntity > taxonomy , final String fileName , final boolean addHash ) throws IOException { final FileWriter fstream = new FileWriter ( fileName ) ; final BufferedWriter writer = new BufferedWriter ( fstream ) ; try { dumpInstanceTaxomomy ( taxonomy , writer , addHash ) ; } finally { writer . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the contents of the given { @link InstanceTaxonomy } to the specified Writer . Expressions are ordered for generating the output ensuring that the output is deterministic . [CODESPLIT] public static void dumpInstanceTaxomomy ( final InstanceTaxonomy < ? extends ElkEntity , ? extends ElkEntity > taxonomy , final Writer writer , final boolean addHash ) throws IOException { writer . write ( \"Ontology(\\n\" ) ; processInstanceTaxomomy ( taxonomy , writer ) ; writer . write ( \")\\n\" ) ; if ( addHash ) { writer . write ( \"\\n# Hash code: \" + getInstanceHashString ( taxonomy ) + \"\\n\" ) ; } writer . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a has string for the given { @link Taxonomy } . Besides possible hash collisions ( which have very low probability ) the hash string is the same for two inputs if and only if the inputs describe the same taxonomy . So it can be used to compare classification results . [CODESPLIT] public static String getHashString ( Taxonomy < ? extends ElkEntity > taxonomy ) { return Integer . toHexString ( TaxonomyHasher . hash ( taxonomy ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a taxonomy and write a normalized serialization . [CODESPLIT] protected static < T extends ElkEntity > void processTaxomomy ( final Taxonomy < T > taxonomy , final Appendable writer ) throws IOException { final ElkObject . Factory factory = new ElkObjectEntityRecyclingFactory ( ) ; // Declarations. final List < T > members = new ArrayList < T > ( taxonomy . getNodes ( ) . size ( ) * 2 ) ; for ( final TaxonomyNode < T > node : taxonomy . getNodes ( ) ) { for ( final T member : node ) { // TODO: this should check whether IRIs are predefined! if ( ! member . getIri ( ) . equals ( taxonomy . getTopNode ( ) . getCanonicalMember ( ) . getIri ( ) ) && ! member . getIri ( ) . equals ( taxonomy . getBottomNode ( ) . getCanonicalMember ( ) . getIri ( ) ) ) { members . add ( member ) ; } } } Collections . sort ( members , taxonomy . getKeyProvider ( ) . getComparator ( ) ) ; printDeclarations ( members , factory , writer ) ; // Relations. final TreeSet < T > canonicalMembers = new TreeSet < T > ( taxonomy . getKeyProvider ( ) . getComparator ( ) ) ; for ( final TaxonomyNode < T > node : taxonomy . getNodes ( ) ) { canonicalMembers . add ( node . getCanonicalMember ( ) ) ; } for ( final T canonicalMember : canonicalMembers ) { final TaxonomyNode < T > node = taxonomy . getNode ( canonicalMember ) ; final ArrayList < T > orderedEquivalentMembers = new ArrayList < T > ( node . size ( ) ) ; for ( final T member : node ) { orderedEquivalentMembers . add ( member ) ; } Collections . sort ( orderedEquivalentMembers , taxonomy . getKeyProvider ( ) . getComparator ( ) ) ; final TreeSet < T > orderedSuperMembers = new TreeSet < T > ( taxonomy . getKeyProvider ( ) . getComparator ( ) ) ; for ( final TaxonomyNode < T > superNode : node . getDirectSuperNodes ( ) ) { orderedSuperMembers . add ( superNode . getCanonicalMember ( ) ) ; } printMemberAxioms ( canonicalMember , orderedEquivalentMembers , orderedSuperMembers , taxonomy , factory , writer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process axioms related to one member of { [CODESPLIT] protected static < T extends ElkEntity , I extends ElkEntity > void printMemberAxioms ( final I member , final List < I > equivalentMembers , final SortedSet < T > directSuperMembers , final Taxonomy < T > taxonomy , final ElkObject . Factory factory , final Appendable writer ) throws IOException { if ( equivalentMembers . size ( ) > 1 ) { final ElkAxiom axiom = member . accept ( getEquivalentAxiomProvider ( equivalentMembers , factory ) ) ; OwlFunctionalStylePrinter . append ( writer , axiom , true ) ; writer . append ( ' ' ) ; } // TODO: this should exclude implicit axioms as owl:Thing ⊑ owl:Nothing if ( ! member . equals ( taxonomy . getBottomNode ( ) . getCanonicalMember ( ) ) ) { for ( final T superMember : directSuperMembers ) { if ( ! superMember . equals ( taxonomy . getTopNode ( ) . getCanonicalMember ( ) ) ) { final ElkAxiom axiom = member . accept ( getSubAxiomProvider ( superMember , factory ) ) ; OwlFunctionalStylePrinter . append ( writer , axiom , true ) ; writer . append ( ' ' ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records that the given { @link ClassInference } has the given premise { @code ClassConclusion } that is not a conclusion of any inference in { @link #output_ } that do not use the conclusion of this { @link ClassInference } as one of the premises [CODESPLIT] private void block ( ClassInference inference , ClassConclusion conclusion ) { List < ClassInference > blockedForConclusion = blocked_ . get ( conclusion ) ; if ( blockedForConclusion == null ) { blockedForConclusion = new ArrayList < ClassInference > ( ) ; blocked_ . put ( conclusion , blockedForConclusion ) ; } blockedForConclusion . add ( inference ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the hash code of a taxonomy . [CODESPLIT] public static int hash ( InstanceTaxonomy < ? extends ElkEntity , ? extends ElkEntity > taxonomy ) { int typeHash = HashGenerator . combineMultisetHash ( true , taxonomy . getNodes ( ) , TypeNodeHasher . INSTANCE ) ; int instanceHash = HashGenerator . combineMultisetHash ( true , taxonomy . getInstanceNodes ( ) , InstanceNodeHasher . INSTANCE ) ; return HashGenerator . combineListHash ( typeHash , instanceHash ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces propagations of { @link IndexedObjectSomeValuesFrom } over the given { @link IndexedObjectProperty } in the given { @link Context } [CODESPLIT] void applyForProperty ( IndexedObjectProperty property , ContextPremises premises , ClassInferenceProducer producer ) { for ( IndexedObjectSomeValuesFrom e : negExistentials_ ) { if ( e . getProperty ( ) . getSaturated ( ) . getSubPropertyChains ( ) . contains ( property ) ) { producer . produce ( new PropagationGenerated ( premises . getRoot ( ) , property , e ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submitting a new input for processing . Submitted input jobs are first buffered and then concurrently processed by workers . If the buffer is full the method blocks until new space is available . [CODESPLIT] public synchronized boolean submit ( I input ) throws InterruptedException { if ( termination || isInterrupted ( ) ) return false ; buffer_ . put ( input ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Printing an ELK Object through an appender . [CODESPLIT] public static void append ( Appendable appender , ElkObject elkObject ) throws IOException { append ( appender , elkObject , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear all derived information for this { [CODESPLIT] public void clear ( ) { derivedSubProperties = null ; derivedSubProperyChains = null ; derivedSubPropertiesComputed = false ; derivedRanges = null ; derivedRangesComputed = false ; leftSubComposableSubPropertiesByRightProperties = null ; leftSubComposableSubPropertiesByRightPropertiesComputed = false ; nonRedundantCompositionsByLeftSubProperty = null ; redundantCompositionsByLeftSubProperty = null ; nonRedundantCompositionsByRightSubProperty = null ; redundantCompositionsByRightSubProperty = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints differences with other { @link SaturatedPropertyChain } [CODESPLIT] public void dumpDiff ( SaturatedPropertyChain other , Writer writer ) throws IOException { // comparing roots if ( this . root != other . root ) writer . append ( \"this root: \" + root + \"; other root: \" + other . root + \"\\n\" ) ; // comparing derived sub-properties Operations . dumpDiff ( this . getSubPropertyChains ( ) , other . getSubPropertyChains ( ) , writer , root + \": this sub-property not in other: \" ) ; Operations . dumpDiff ( other . getSubPropertyChains ( ) , this . getSubPropertyChains ( ) , writer , root + \": other sub-property not in this: \" ) ; // comparing derived compositions Operations . dumpDiff ( this . getNonRedundantCompositionsByLeftSubProperty ( ) , other . getNonRedundantCompositionsByLeftSubProperty ( ) , writer , root + \": this non-redundant left composition not in other: \" ) ; Operations . dumpDiff ( this . getRedundantCompositionsByLeftSubProperty ( ) , other . getRedundantCompositionsByLeftSubProperty ( ) , writer , root + \": this redundant left composition not in other: \" ) ; Operations . dumpDiff ( other . getNonRedundantCompositionsByLeftSubProperty ( ) , this . getNonRedundantCompositionsByLeftSubProperty ( ) , writer , root + \": other non-redundant left composition not in this: \" ) ; Operations . dumpDiff ( other . getRedundantCompositionsByLeftSubProperty ( ) , this . getRedundantCompositionsByLeftSubProperty ( ) , writer , root + \": other redundant left composition not in this: \" ) ; Operations . dumpDiff ( this . getNonRedundantCompositionsByRightSubProperty ( ) , other . getNonRedundantCompositionsByRightSubProperty ( ) , writer , root + \": this non-redundant right composition not in other: \" ) ; Operations . dumpDiff ( this . getRedundantCompositionsByRightSubProperty ( ) , other . getRedundantCompositionsByRightSubProperty ( ) , writer , root + \": this redundant right composition not in other: \" ) ; Operations . dumpDiff ( other . getNonRedundantCompositionsByRightSubProperty ( ) , this . getNonRedundantCompositionsByRightSubProperty ( ) , writer , root + \": other non-redundant right composition not in this: \" ) ; Operations . dumpDiff ( other . getRedundantCompositionsByRightSubProperty ( ) , this . getRedundantCompositionsByRightSubProperty ( ) , writer , root + \": other redundant right composition not in this: \" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increasing the capacity of the table [CODESPLIT] private void enlarge ( ) { int oldCapacity = data . length ; if ( oldCapacity == LinearProbing . MAXIMUM_CAPACITY ) throw new IllegalArgumentException ( \"The set cannot grow beyond the capacity: \" + LinearProbing . MAXIMUM_CAPACITY ) ; E [ ] oldData = data ; int newCapacity = oldCapacity << 1 ; @ SuppressWarnings ( \"unchecked\" ) E [ ] newData = ( E [ ] ) new Object [ newCapacity ] ; for ( int i = 0 ; i < oldCapacity ; i ++ ) { E e = oldData [ i ] ; if ( e != null ) LinearProbing . add ( newData , e ) ; } this . data = newData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decreasing the capacity of the table [CODESPLIT] private void shrink ( ) { int oldCapacity = data . length ; if ( oldCapacity == 1 ) return ; E [ ] oldData = data ; int newCapacity = oldCapacity >> 1 ; @ SuppressWarnings ( \"unchecked\" ) E [ ] newData = ( E [ ] ) new Object [ newCapacity ] ; for ( int i = 0 ; i < oldCapacity ; i ++ ) { E e = oldData [ i ] ; if ( e != null ) LinearProbing . add ( newData , e ) ; } this . data = newData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks that all System properties are set . We use System properties ( other than cmd args ) because they re easier to pass parameters into maven tests ( via Surefire or Failsafe plugins ) [CODESPLIT] public static Map < String , String > getSystemProperties ( String ... names ) { Map < String , String > propMap = new HashMap < String , String > ( ) ; for ( String name : names ) { checkIfSet ( name , propMap ) ; } return propMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * A macro method reads system properties instantiates the task and runs it [CODESPLIT] public static void runTask ( ) throws Exception { Map < String , String > propMap = BenchmarkUtils . getSystemProperties ( new String [ ] { Constants . TASK_CLASS_NAME , Constants . WARM_UPS , Constants . RUNS , Constants . TASK_PARAMS } ) ; // First, need to instantiate the task Task task = TaskFactory . createTask ( propMap . get ( Constants . TASK_CLASS_NAME ) , BenchmarkUtils . getCommaSeparatedParameter ( Constants . TASK_PARAMS ) ) ; TaskRunner runner = new TaskRunner ( Integer . valueOf ( propMap . get ( Constants . WARM_UPS ) ) , Integer . valueOf ( propMap . get ( Constants . RUNS ) ) ) ; runner . run ( task ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * A macro method reads system properties instantiates the task collection and runs it [CODESPLIT] public static void runTaskCollection ( ) throws Exception { Map < String , String > propMap = BenchmarkUtils . getSystemProperties ( new String [ ] { Constants . TASK_CLASS_NAME , Constants . WARM_UPS , Constants . RUNS , Constants . TASK_PARAMS } ) ; TaskCollection collection = TaskFactory . createTaskCollection ( propMap . get ( Constants . TASK_CLASS_NAME ) , BenchmarkUtils . getCommaSeparatedParameter ( Constants . TASK_PARAMS ) ) ; RepeatEachTaskRunner runner = new RepeatEachTaskRunner ( Integer . valueOf ( propMap . get ( Constants . WARM_UPS ) ) , Integer . valueOf ( propMap . get ( Constants . RUNS ) ) ) ; runner . run ( collection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO need a better name [CODESPLIT] public static void runTaskCollection2 ( String taskClass , int warmups , int runs , String [ ] params ) throws Exception { VisitorTaskCollection collection = TaskFactory . createTaskCollection2 ( taskClass , params ) ; RunAllOnceThenRepeatRunner runner = new RunAllOnceThenRepeatRunner ( warmups , runs ) ; try { runner . run ( collection ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param factory the factory for creating conclusions [CODESPLIT] public final ForwardLink getConclusion ( ForwardLink . Factory factory ) { return factory . getForwardLink ( getDestination ( ) , getChain ( ) , getTarget ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] @ Override public final < O > O accept ( TracingInference . Visitor < O > visitor ) { return accept ( ( ObjectPropertyInference . Visitor < O > ) visitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One - parameter public non - static methods called convert and declared in this class specify mapping between { @link OWLObject } subclasses ( parameter ) and { @link ElkObject } subclasses ( return type ) . This method returns a subclass of { @link ElkObject } to which the subclass of { @link OWLObject } specified as the parameter is mapped or { @code null } if it is not mapped . [CODESPLIT] public static Class < ? extends ElkObject > convertType ( final Class < ? > owlClass ) { if ( ! OWLObject . class . isAssignableFrom ( owlClass ) ) { return null ; } for ( final Method declaredMethod : OwlConverter . class . getDeclaredMethods ( ) ) { final int mod = declaredMethod . getModifiers ( ) ; final Class < ? > [ ] parameterTypes = declaredMethod . getParameterTypes ( ) ; final Class < ? > returnType = declaredMethod . getReturnType ( ) ; if ( \"convert\" . equals ( declaredMethod . getName ( ) ) && Modifier . isPublic ( mod ) && ! Modifier . isStatic ( mod ) && parameterTypes . length == 1 && parameterTypes [ 0 ] . equals ( owlClass ) && ElkObject . class . isAssignableFrom ( returnType ) ) { return returnType . asSubclass ( ElkObject . class ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param visitor @return A { @link RuleVisitor } that delegates the calls to the provided { @link RuleVisitor } when for the { @link Rule } which accepts this visitor { @link Rule#isTracingRule () } returns { @code true } . Otherwise the { @link RuleVisitor } returns { @code null } . [CODESPLIT] public static < O > RuleVisitor < O > getTracingVisitor ( RuleVisitor < O > visitor ) { return new ConditionalRuleVisitor < O > ( visitor , LOCALITY_CHECKER_ ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param visitor the { @link SubsumerDecompositionVisitor } used to execute the methods @param timer the { @link RuleApplicationTimer } used to mesure the time spent within the methods [CODESPLIT] public static < O > RuleVisitor < O > getTimedVisitor ( RuleVisitor < O > visitor , RuleApplicationTimer timer ) { return new RuleApplicationTimerVisitor < O > ( visitor , timer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all pending { @link ClassInference } s of the given { @link Context } [CODESPLIT] void process ( Context context ) { activeContext_ . set ( context ) ; // at this point workerLocalTodo_ must be empty workerLocalTodo_ . setActiveRoot ( context . getRoot ( ) ) ; for ( ; ; ) { ClassInference inference = workerLocalTodo_ . poll ( ) ; if ( inference == null ) { inference = context . takeToDo ( ) ; if ( inference == null ) return ; } LOGGER_ . trace ( \"{}: processing inference {}\" , context , inference ) ; inference . accept ( inferenceProcessor_ ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the specified query was added to the index this method marks it as computed . Does <strong > not< / strong > modify the cached query results . [CODESPLIT] private QueryState markComputed ( final IndexedClassExpression queryClass ) { final QueryState state = indexed_ . get ( queryClass ) ; if ( state == null || state . isComputed ) { return null ; } state . isComputed = true ; LOGGER_ . trace ( \"query computed {}\" , queryClass ) ; return state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the specified query was added to the index this method marks it as not - computed and deletes the query results . [CODESPLIT] private QueryState markNotComputed ( final IndexedClassExpression queryClass ) { final QueryState state = indexed_ . get ( queryClass ) ; if ( state == null || ! state . isComputed ) { return null ; } state . isComputed = false ; if ( state . node != null ) { removeAllRelated ( queryClass , state . node ) ; state . node = null ; } return state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the supplied class expression for querying . If the expression has already been registered returns { @code false } . Otherwise if this state did not keep track of the expression yet returns { @code true } . If all necessary stages are run after doing this the result retrieval methods e . g . { @link #isSatisfiable ( ElkClassExpression ) } will not throw { @link ElkQueryException } . [CODESPLIT] boolean registerQuery ( final ElkClassExpression classExpression ) { LOGGER_ . trace ( \"class expression query registered {}\" , classExpression ) ; lastQueries_ . clear ( ) ; queriedEvictor_ . add ( classExpression ) ; lastQueries_ . add ( classExpression ) ; QueryState state = queried_ . get ( classExpression ) ; if ( state != null ) { return false ; } // Create query state. state = new QueryState ( ) ; queried_ . put ( classExpression , state ) ; toLoad_ . offer ( classExpression ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the supplied class expression is satisfiable if the result was already computed . If the class expression was not registered by { @link #registerQuery ( ElkClassExpression ) } or the appropriate stage was not completed yet throws { @link ElkQueryException } . [CODESPLIT] boolean isSatisfiable ( final ElkClassExpression classExpression ) throws ElkQueryException { final QueryState state = checkComputed ( classExpression ) ; return state . node != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @link Node } containing all { @link ElkClass } es equivalent to the supplied class expression if it is satisfiable . Returns <code > null< / code > otherwise . If the class expression was not registered by { @link #registerQuery ( ElkClassExpression ) } or the appropriate stage was not completed yet throws { @link ElkQueryException } . [CODESPLIT] Node < ElkClass > getEquivalentClasses ( final ElkClassExpression classExpression ) throws ElkQueryException { final QueryState state = checkComputed ( classExpression ) ; return state . node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns set of { @link Node } s containing all { @link ElkClass } es that are direct strict super - classes of the supplied class expression if it is satisfiable . Returns <code > null< / code > otherwise . If the class expression was not registered by { @link #registerQuery ( ElkClassExpression ) } or the appropriate stage was not completed yet throws { @link ElkQueryException } . [CODESPLIT] Set < ? extends Node < ElkClass > > getDirectSuperClasses ( final ElkClassExpression classExpression ) throws ElkQueryException { final QueryState state = checkComputed ( classExpression ) ; if ( state . node == null ) { return null ; } else { return state . node . getDirectSuperNodes ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns set of { @link Node } s containing all { @link ElkClass } es that are direct strict sub - classes of the supplied class expression if it is satisfiable . Returns <code > null< / code > otherwise . If the class expression was not registered by { @link #registerQuery ( ElkClassExpression ) } or the appropriate stage was not completed yet throws { @link ElkQueryException } . [CODESPLIT] Set < ? extends Node < ElkClass > > getDirectSubClasses ( final ElkClassExpression classExpression , final Taxonomy < ElkClass > taxonomy ) throws ElkQueryException { final QueryState state = checkComputed ( classExpression ) ; if ( state . node == null ) { return null ; } // else final Iterator < ElkClass > iter = state . node . iterator ( ) ; if ( iter . hasNext ( ) ) { final ElkClass cls = iter . next ( ) ; return taxonomy . getNode ( cls ) . getDirectSubNodes ( ) ; } /*\n\t\t * Else, if classExpression is not equivalent to any atomic class,\n\t\t * direct atomic sub-classes of classExpression are atomic classes that\n\t\t * have classExpression among their subsumers, but no other of their\n\t\t * strict subsumers have classExpression among its subsumers.\n\t\t */ final Collection < ? extends IndexedClass > allClasses = saturationState_ . getOntologyIndex ( ) . getClasses ( ) ; final Set < IndexedClass > strictSubclasses = new ArrayHashSet < IndexedClass > ( allClasses . size ( ) ) ; for ( final IndexedClass ic : allClasses ) { final Set < IndexedClassExpression > subsumers = ic . getContext ( ) . getComposedSubsumers ( ) ; if ( subsumers . contains ( state . indexed ) && state . indexed . getContext ( ) . getComposedSubsumers ( ) . size ( ) != subsumers . size ( ) ) { // is subclass, but not equivalent strictSubclasses . add ( ic ) ; } } final Set < TaxonomyNode < ElkClass > > result = new ArrayHashSet < TaxonomyNode < ElkClass > > ( ) ; for ( final IndexedClass strictSubclass : strictSubclasses ) { /*\n\t\t\t * If some strict superclass of strictSubclass is a strict subclass\n\t\t\t * of classExpression, strictSubclass is not direct.\n\t\t\t * \n\t\t\t * It is sufficient to check only direct superclasses of\n\t\t\t * strictSubclass.\n\t\t\t */ boolean isDirect = true ; for ( final TaxonomyNode < ElkClass > superNode : taxonomy . getNode ( strictSubclass . getElkEntity ( ) ) . getDirectSuperNodes ( ) ) { final IndexedClassExpression superClass = superNode . getCanonicalMember ( ) . accept ( resolvingExpressionConverter_ ) ; if ( strictSubclasses . contains ( superClass ) ) { isDirect = false ; break ; } } if ( isDirect ) { result . add ( taxonomy . getNode ( strictSubclass . getElkEntity ( ) ) ) ; } } if ( result . isEmpty ( ) ) { /*\n\t\t\t * No indexed class has classExpression among its subsumers and\n\t\t\t * classExpression is not equivalent to any atomic class, so the\n\t\t\t * only subclass of classExpression is Nothing and it is direct.\n\t\t\t */ result . add ( taxonomy . getBottomNode ( ) ) ; } return Collections . unmodifiableSet ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns set of { @link Node } s containing all { @link ElkNamedIndividual } s that are direct instances of the supplied class expression if it is satisfiable . Returns <code > null< / code > otherwise . If the class expression was not registered by { @link #registerQuery ( ElkClassExpression ) } or the appropriate stage was not completed yet throws { @link ElkQueryException } . [CODESPLIT] Set < ? extends Node < ElkNamedIndividual > > getDirectInstances ( final ElkClassExpression classExpression , final InstanceTaxonomy < ElkClass , ElkNamedIndividual > taxonomy ) throws ElkQueryException { final QueryState state = checkComputed ( classExpression ) ; if ( state . node == null ) { return null ; } // else final Iterator < ElkClass > iter = state . node . iterator ( ) ; if ( iter . hasNext ( ) ) { final ElkClass cls = iter . next ( ) ; return taxonomy . getNode ( cls ) . getDirectInstanceNodes ( ) ; } /*\n\t\t * Else, if classExpression is not equivalent to any atomic class,\n\t\t * direct instances of classExpression are instances that have\n\t\t * classExpression among their subsumers, but no other of their strict\n\t\t * subsumers have classExpression among its subsumers.\n\t\t */ final Collection < ? extends IndexedIndividual > allIndividuals = saturationState_ . getOntologyIndex ( ) . getIndividuals ( ) ; final Set < IndexedIndividual > instances = new ArrayHashSet < IndexedIndividual > ( allIndividuals . size ( ) ) ; for ( final IndexedIndividual ii : allIndividuals ) { final Set < IndexedClassExpression > subsumers = ii . getContext ( ) . getComposedSubsumers ( ) ; if ( subsumers . contains ( state . indexed ) ) { instances . add ( ii ) ; } } final Set < InstanceNode < ElkClass , ElkNamedIndividual > > result = new ArrayHashSet < InstanceNode < ElkClass , ElkNamedIndividual > > ( ) ; for ( final IndexedIndividual instance : instances ) { /*\n\t\t\t * If some type of instance is a strict subclass of classExpression,\n\t\t\t * instance is not direct.\n\t\t\t * \n\t\t\t * It is sufficient to check only direct types of instance.\n\t\t\t */ boolean isDirect = true ; for ( final TypeNode < ElkClass , ElkNamedIndividual > typeNode : taxonomy . getInstanceNode ( instance . getElkEntity ( ) ) . getDirectTypeNodes ( ) ) { final IndexedClassExpression type = typeNode . getCanonicalMember ( ) . accept ( resolvingExpressionConverter_ ) ; final Set < IndexedClassExpression > subsumers = type . getContext ( ) . getComposedSubsumers ( ) ; if ( subsumers . contains ( state . indexed ) && state . indexed . getContext ( ) . getComposedSubsumers ( ) . size ( ) != subsumers . size ( ) ) { // is subclass, but not equivalent isDirect = false ; break ; } } if ( isDirect ) { result . add ( taxonomy . getInstanceNode ( instance . getElkEntity ( ) ) ) ; } } return Collections . unmodifiableSet ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "logging is switched off [CODESPLIT] @ Override protected Boolean defaultVisit ( ClassConclusion conclusion ) { Context context = get ( ) ; boolean result = context . addConclusion ( conclusion ) ; if ( LOGGER_ . isTraceEnabled ( ) ) { LOGGER_ . trace ( \"{}: inserting {}: {}\" , context , conclusion , result ? \"success\" : \"failure\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * can return a smaller subset than requested because one axiom can be randomly picked more than once [CODESPLIT] protected Set < ElkAxiom > getRandomSubset ( List < ElkAxiom > axioms , Random rnd ) { int size = axiomsToChange > 0 ? axiomsToChange : Math . max ( 1 , axioms . size ( ) / 100 ) ; Set < ElkAxiom > subset = new ArrayHashSet < ElkAxiom > ( size ) ; if ( size >= axioms . size ( ) ) { subset . addAll ( axioms ) ; } else { for ( int i = 0 ; i < size ; i ++ ) { ElkAxiom axiom = axioms . get ( rnd . nextInt ( size ) ) ; subset . add ( axiom ) ; } } return subset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the hash code of a taxonomy . [CODESPLIT] public static int hash ( Taxonomy < ? extends ElkEntity > taxonomy ) { return HashGenerator . combineMultisetHash ( true , taxonomy . getNodes ( ) , TaxonomyNodeHasher . INSTANCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a direct super - class node . This method is not thread safe . [CODESPLIT] @ Override public synchronized void addDirectTypeNode ( final UTN typeNode ) { LOGGER_ . trace ( \"{}: new direct type-node {}\" , this , typeNode ) ; directTypeNodes_ . add ( typeNode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new primary { @link SaturationStateWriter } for the { @link SaturationState } to be used by an engine of this { @link RuleApplicationFactory } . This { @link SaturationStateWriter } can be further extended and optimized . [CODESPLIT] SaturationStateWriter < ? extends C > getBaseWriter ( ContextCreationListener creationListener , ContextModificationListener modificationListener ) { // by default the writer can create new contexts return saturationState_ . getContextCreatingWriter ( creationListener , modificationListener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "some methods for checking correctness of arguments [CODESPLIT] protected static void checkChainMatch ( final ElkSubObjectPropertyExpression fullChain , final int startPos ) { // verifies that start position exists in full chain fullChain . accept ( new ElkSubObjectPropertyExpressionVisitor < Void > ( ) { void fail ( ) { throw new IllegalArgumentException ( fullChain + \", \" + startPos ) ; } Void defaultVisit ( ElkObjectPropertyExpression expression ) { if ( startPos != 0 ) { fail ( ) ; } return null ; } @ Override public Void visit ( ElkObjectPropertyChain expression ) { if ( startPos < 0 || startPos >= expression . getObjectPropertyExpressions ( ) . size ( ) ) fail ( ) ; return null ; } @ Override public Void visit ( ElkObjectInverseOf expression ) { return defaultVisit ( expression ) ; } @ Override public Void visit ( ElkObjectProperty expression ) { return defaultVisit ( expression ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates several { @link Iterable } s into one [CODESPLIT] public static < T > Iterable < T > concat ( final Iterable < ? extends Iterable < ? extends T > > inputs ) { assert inputs != null ; return new Iterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return new Iterator < T > ( ) { Iterator < ? extends Iterable < ? extends T > > outer = inputs . iterator ( ) ; Iterator < ? extends T > inner ; boolean hasNext = advance ( ) ; @ Override public boolean hasNext ( ) { return hasNext ; } @ Override public T next ( ) { if ( hasNext ) { T result = inner . next ( ) ; hasNext = advance ( ) ; return result ; } throw new NoSuchElementException ( ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } boolean advance ( ) { while ( true ) { if ( inner != null && inner . hasNext ( ) ) return true ; if ( outer . hasNext ( ) ) inner = outer . next ( ) . iterator ( ) ; else return false ; } } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits the input { @link Iterable } on batches with at most given number of elements . [CODESPLIT] public static < T > Iterable < ArrayList < T > > split ( final Iterable < ? extends T > elements , final int batchSize ) { return new Iterable < ArrayList < T > > ( ) { @ Override public Iterator < ArrayList < T > > iterator ( ) { return new Iterator < ArrayList < T > > ( ) { final Iterator < ? extends T > elementsIterator = elements . iterator ( ) ; @ Override public boolean hasNext ( ) { return elementsIterator . hasNext ( ) ; } @ Override public ArrayList < T > next ( ) { final ArrayList < T > nextBatch = new ArrayList < T > ( batchSize ) ; int count = 0 ; while ( count ++ < batchSize && elementsIterator . hasNext ( ) ) { nextBatch . add ( elementsIterator . next ( ) ) ; } return nextBatch ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( \"Deletion is not supported\" ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits the input { @link Collection } on batches with at most given number of elements . [CODESPLIT] public static < T > Collection < ArrayList < T > > split ( final Collection < ? extends T > elements , final int batchSize ) { return new AbstractCollection < ArrayList < T > > ( ) { @ Override public Iterator < ArrayList < T > > iterator ( ) { return split ( ( Iterable < ? extends T > ) elements , batchSize ) . iterator ( ) ; } @ Override public int size ( ) { // rounding up return ( elements . size ( ) + batchSize - 1 ) / batchSize ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns read - only view of the given set consisting of the elements satisfying a given condition if the number of such elements is known [CODESPLIT] public static < T > Set < T > filter ( final Set < ? extends T > input , final Condition < ? super T > condition , final int size ) { return new Set < T > ( ) { @ Override public int size ( ) { return size ; } @ Override public boolean isEmpty ( ) { return size == 0 ; } @ Override @ SuppressWarnings ( \"unchecked\" ) public boolean contains ( Object o ) { if ( ! input . contains ( o ) ) return false ; T elem = null ; try { elem = ( T ) o ; } catch ( ClassCastException cce ) { return false ; } /*\n\t\t\t\t * here's why the condition must be consistent with equals(): we\n\t\t\t\t * check it on the passed element while we really need to check\n\t\t\t\t * it on the element which is in the underlying set (and is\n\t\t\t\t * equal to o according to equals()). However, as long as the\n\t\t\t\t * condition is consistent, the result will be the same.\n\t\t\t\t */ return condition . holds ( elem ) ; } @ Override public Iterator < T > iterator ( ) { return filter ( input , condition ) . iterator ( ) ; } @ Override public Object [ ] toArray ( ) { Object [ ] result = new Object [ size ] ; int i = 0 ; for ( Object o : filter ( input , condition ) ) { result [ i ++ ] = o ; } return result ; } @ Override public < S > S [ ] toArray ( S [ ] a ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean add ( T e ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean remove ( Object o ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean containsAll ( Collection < ? > c ) { for ( Object o : c ) { if ( contains ( o ) ) return false ; } return true ; } @ Override public boolean addAll ( Collection < ? extends T > c ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean retainAll ( Collection < ? > c ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean removeAll ( Collection < ? > c ) { throw new UnsupportedOperationException ( ) ; } @ Override public void clear ( ) { throw new UnsupportedOperationException ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints key - value entries present in the first { @link Multimap } but not in the second { @link Multimap } using the given { @link Writer } and prefixing all messages with a given prefix . [CODESPLIT] public static < K , V > void dumpDiff ( Multimap < K , V > first , Multimap < K , V > second , Writer writer , String prefix ) throws IOException { for ( K key : first . keySet ( ) ) { Collection < V > firstValues = first . get ( key ) ; Collection < V > secondValues = second . get ( key ) ; dumpDiff ( firstValues , secondValues , writer , prefix + key + \"->\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the elements present in the first { @link Collection } but not in the second { @link Collection } using the given { @link Writer } and prefixing all messages with a given prefix . [CODESPLIT] public static < T > void dumpDiff ( Collection < T > first , Collection < T > second , Writer writer , String prefix ) throws IOException { for ( T element : first ) if ( ! second . contains ( element ) ) writer . append ( prefix + element + \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A simple second - order map function for sets [CODESPLIT] public static < I , O > Set < O > map ( final Set < ? extends I > input , final FunctorEx < I , O > functor ) { return new AbstractSet < O > ( ) { @ Override public Iterator < O > iterator ( ) { return new MapIterator < I , O > ( input . iterator ( ) , functor ) ; } @ Override public boolean contains ( Object o ) { I element = functor . deapply ( o ) ; return element == null ? false : input . contains ( element ) ; } @ Override public int size ( ) { return input . size ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the bit fragment that encodes the membership of an element for the given position in slices . The returned fragment is an integer whose lower bits correspond to whether an element occurs in the slice or not ( the lowest bit corresponds to the membership in slice = 0 next bit in slice = 1 etc ) [CODESPLIT] static int getFragment ( byte sl , int [ ] masks , int pos ) { /*\n\t\t * one element of the masks table stores fragments for 32/(2^sl)\n\t\t * elements; since it is a power of 2, we can divide on this value and\n\t\t * compute the remainder efficiently\n\t\t */ int shift = ( 5 - sl ) ; int p = pos >> shift ; // = pos / (32/(2^sl)) int r = ( p << shift ) ^ pos ; // the remainder after the devision // extract the r-th fragment of the length 2^sl return ( masks [ p ] >> ( r << sl ) ) & MSK_ [ sl ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the fragment that corresponds to the encoding of membership of an element at the given position . The change is specified by the bits of the last parameter : bit 1 means the corresponding value of the fragment should flip bit 0 means it should stay the same . [CODESPLIT] static void changeFragment ( byte sl , int [ ] masks , int pos , int diff ) { int shift = ( 5 - sl ) ; int p = pos >> shift ; int r = ( p << shift ) ^ pos ; masks [ p ] ^= diff << ( r << sl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increasing the capacity of the table [CODESPLIT] private void enlarge ( ) { int oldCapacity = data . length ; if ( oldCapacity == LinearProbing . MAXIMUM_CAPACITY ) throw new IllegalArgumentException ( \"The set cannot grow beyond the capacity: \" + LinearProbing . MAXIMUM_CAPACITY ) ; E [ ] oldData = data ; int [ ] oldMasks = masks ; int newCapacity = oldCapacity << 1 ; @ SuppressWarnings ( \"unchecked\" ) E [ ] newData = ( E [ ] ) new Object [ newCapacity ] ; int [ ] newMasks = new int [ getMaskCapacity ( logs , newCapacity ) ] ; for ( int i = 0 ; i < oldCapacity ; i ++ ) { E e = oldData [ i ] ; if ( e != null ) addMask ( logs , newData , newMasks , e , getFragment ( logs , oldMasks , i ) ) ; } this . data = newData ; this . masks = newMasks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decreasing the capacity of the table [CODESPLIT] private void shrink ( ) { int oldCapacity = data . length ; if ( oldCapacity == 1 ) return ; E [ ] oldData = data ; int [ ] oldMasks = masks ; int newCapacity = oldCapacity >> 1 ; @ SuppressWarnings ( \"unchecked\" ) E [ ] newData = ( E [ ] ) new Object [ newCapacity ] ; int [ ] newMasks = new int [ getMaskCapacity ( logs , newCapacity ) ] ; for ( int i = 0 ; i < oldCapacity ; i ++ ) { E e = oldData [ i ] ; if ( e != null ) addMask ( logs , newData , newMasks , e , getFragment ( logs , oldMasks , i ) ) ; } this . data = newData ; this . masks = newMasks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a given element into the given slice [CODESPLIT] public boolean add ( int s , E e ) { if ( e == null ) throw new NullPointerException ( ) ; int mask = ( 1 << s ) ; int oldMask = addMask ( logs , data , masks , e , mask ) ; int newMask = oldMask | mask ; if ( newMask == oldMask ) return false ; else if ( oldMask == 0 && ++ occupied == LinearProbing . getUpperSize ( data . length ) ) enlarge ( ) ; sizes [ s ] ++ ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the given object from the given slice [CODESPLIT] public boolean remove ( int s , Object o ) { if ( o == null ) throw new NullPointerException ( ) ; int mask = 1 << s ; int oldMask = removeMask ( logs , data , masks , o , mask ) ; int newMask = oldMask & ~ mask ; if ( newMask == oldMask ) return false ; // else if ( newMask == 0 && -- occupied == LinearProbing . getLowerSize ( data . length ) ) shrink ( ) ; sizes [ s ] -- ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears all slices of this { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void clear ( ) { int capacity = data . length >> 2 ; if ( capacity == 0 ) capacity = 1 ; initSizes ( ) ; this . data = ( E [ ] ) new Object [ capacity ] ; this . masks = new int [ getMaskCapacity ( logs , capacity ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates inferences for SubClassInclusion ( extendedRootMatchExpression rootMatchExpression ) where the arguments correspond to the values of respectively extendedRootMatch and rootMatch under { @link #toElkExpression ( IndexedContextRootMatch ) } [CODESPLIT] private void deriveInclusion ( IndexedContextRootMatch extendedRootMatch , IndexedContextRootMatch rootMatch ) { if ( rootMatch . equals ( extendedRootMatch ) ) { // nothing to do return ; } List < ? extends ElkClassExpression > rootFillers = getFillerRanges ( rootMatch ) ; List < ? extends ElkClassExpression > extendedRootFillers = getFillerRanges ( extendedRootMatch ) ; int rootFillersCount = rootFillers . size ( ) ; if ( rootFillersCount == 1 ) { elkInferenceFactory_ . getElkClassInclusionObjectIntersectionOfDecomposition ( extendedRootFillers , 0 ) ; } else { List < Integer > positions = new ArrayList < Integer > ( rootFillersCount ) ; for ( int i = 0 ; i < rootFillersCount ; i ++ ) { positions . add ( i ) ; } elkInferenceFactory_ . getElkClassInclusionObjectIntersectionOfInclusion ( extendedRootFillers , positions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all counters of the argument to the corresponding counters of this object . The counters should not be directly modified other than using this method during this operation . The counter in the argument will be reseted after this operation . [CODESPLIT] public synchronized void add ( ClassConclusionCounter counter ) { this . countSubClassInclusionDecomposed += counter . countSubClassInclusionDecomposed ; this . countSubClassInclusionComposed += counter . countSubClassInclusionComposed ; this . countBackwardLink += counter . countBackwardLink ; this . countForwardLink += counter . countForwardLink ; this . countContradiction += counter . countContradiction ; this . countPropagation += counter . countPropagation ; this . countDisjointSubsumer += counter . countDisjointSubsumer ; this . countContextInitialization += counter . countContextInitialization ; this . countSubContextInitialization += counter . countSubContextInitialization ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the start of a particular operation with INFO priority . This method should be used for long - running tasks and is mainly intended . Multiple threads can independently log operations of the same name but ( obviously ) no single thread should use the same operation name to record the start and end of overlapping code . [CODESPLIT] public static void logOperationStart ( String operationName , Logger logger ) { logOperationStart ( operationName , logger , LogLevel . INFO ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the start of a particular operation with the given priority . This method should be used for long - running tasks and is mainly intended . Multiple threads can independently log operations of the same name but ( obviously ) no single thread should use the same operation name to record the start and end of overlapping code . [CODESPLIT] public static void logOperationStart ( String operationName , Logger logger , LogLevel priority ) { if ( LoggerWrap . isEnabledFor ( logger , priority ) ) { LoggerWrap . log ( logger , priority , operationName + \" started\" ) ; ElkTimer timer = ElkTimer . getNamedTimer ( operationName , ElkTimer . RECORD_WALLTIME ) ; timer . reset ( ) ; // needed in case this was done before timer . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the end of a particular operation the beginning of which has been logged using logOperationStart () using INFO priority . [CODESPLIT] public static void logOperationFinish ( String operationName , Logger logger ) { logOperationFinish ( operationName , logger , LogLevel . INFO ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the end of a particular operation the beginning of which has been logged using logOperationStart () using the given logging priority . [CODESPLIT] public static void logOperationFinish ( String operationName , Logger logger , LogLevel priority ) { if ( LoggerWrap . isEnabledFor ( logger , priority ) ) { ElkTimer timer = ElkTimer . getNamedTimer ( operationName , ElkTimer . RECORD_WALLTIME ) ; timer . stop ( ) ; LoggerWrap . log ( logger , priority , operationName + \" took \" + timer . getTotalWallTime ( ) / 1000000 + \" ms\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the current total memory usage with the specified priority . [CODESPLIT] public static void logMemoryUsage ( Logger logger , LogLevel priority ) { if ( LoggerWrap . isEnabledFor ( logger , priority ) ) { // Getting the runtime reference from system Runtime runtime = Runtime . getRuntime ( ) ; LoggerWrap . log ( logger , priority , \"Memory (MB) Used/Total/Max: \" + ( runtime . totalMemory ( ) - runtime . freeMemory ( ) ) / megaBytes + \"/\" + runtime . totalMemory ( ) / megaBytes + \"/\" + runtime . maxMemory ( ) / megaBytes ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This supposed to be the central place where the reasoner gets its configuration options [CODESPLIT] public synchronized void setConfigurationOptions ( ReasonerConfiguration config ) { this . workerNo_ = config . getParameterAsInt ( ReasonerConfiguration . NUM_OF_WORKING_THREADS ) ; setAllowIncrementalMode ( config . getParameterAsBoolean ( ReasonerConfiguration . INCREMENTAL_MODE_ALLOWED ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to shut down the reasoner within the specified time [CODESPLIT] public synchronized boolean shutdown ( long timeout , TimeUnit unit ) throws InterruptedException { boolean success = true ; if ( success ) { LOGGER_ . info ( \"ELK reasoner has shut down\" ) ; } else { LOGGER_ . error ( \"ELK reasoner failed to shut down!\" ) ; } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get a { @link TaxonomyNode } from the taxonomy . [CODESPLIT] protected TaxonomyNode < ElkClass > getTaxonomyNode ( ElkClass elkClass ) throws ElkException { final Taxonomy < ElkClass > taxonomy = getTaxonomy ( ) ; final TaxonomyNode < ElkClass > node = taxonomy . getNode ( elkClass ) ; if ( node != null ) return node ; // else if ( allowFreshEntities ) return new FreshTaxonomyNode < ElkClass > ( elkClass , taxonomy ) ; // else throw new ElkFreshEntitiesException ( elkClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get an { @link InstanceNode } from the taxonomy . [CODESPLIT] protected InstanceNode < ElkClass , ElkNamedIndividual > getInstanceNode ( ElkNamedIndividual elkNamedIndividual ) throws ElkException { final InstanceTaxonomy < ElkClass , ElkNamedIndividual > instanceTaxonomy = getInstanceTaxonomy ( ) ; final InstanceNode < ElkClass , ElkNamedIndividual > node = instanceTaxonomy . getInstanceNode ( elkNamedIndividual ) ; if ( node != null ) return node ; // else if ( allowFreshEntities ) return new FreshInstanceNode < ElkClass , ElkNamedIndividual > ( elkNamedIndividual , instanceTaxonomy ) ; // else throw new ElkFreshEntitiesException ( elkNamedIndividual ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get a { @link TypeNode } from the taxonomy . [CODESPLIT] protected TypeNode < ElkClass , ElkNamedIndividual > getTypeNode ( ElkClass elkClass ) throws ElkException { final InstanceTaxonomy < ElkClass , ElkNamedIndividual > instanceTaxonomy = getInstanceTaxonomy ( ) ; final TypeNode < ElkClass , ElkNamedIndividual > node = instanceTaxonomy . getNode ( elkClass ) ; if ( node != null ) return node ; // else if ( allowFreshEntities ) return new FreshTypeNode < ElkClass , ElkNamedIndividual > ( elkClass , instanceTaxonomy ) ; // else throw new ElkFreshEntitiesException ( elkClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get a { @link TaxonomyNode } from the property taxonomy . [CODESPLIT] protected TaxonomyNode < ElkObjectProperty > getObjectPropertyTaxonomyNode ( final ElkObjectProperty elkProperty ) throws ElkException { final Taxonomy < ElkObjectProperty > propertyTaxonomy = getObjectPropertyTaxonomy ( ) ; final TaxonomyNode < ElkObjectProperty > node = propertyTaxonomy . getNode ( elkProperty ) ; if ( node != null ) { return node ; } // else if ( allowFreshEntities ) { return new FreshTaxonomyNode < ElkObjectProperty > ( elkProperty , propertyTaxonomy ) ; } // else throw new ElkFreshEntitiesException ( elkProperty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the { @code Node } containing equivalent classes of the given { @link ElkClassExpression } . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Node < ElkClass > getEquivalentClasses ( ElkClassExpression classExpression ) throws ElkInconsistentOntologyException , ElkException { if ( classExpression instanceof ElkClass ) { return getTaxonomyNode ( ( ElkClass ) classExpression ) ; } // else return queryEquivalentClasses ( classExpression ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the { @code Node } containing equivalent classes of the given { @link ElkClassExpression } . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Node < ElkClass > getEquivalentClassesQuietly ( ElkClassExpression classExpression ) throws ElkException { try { return getEquivalentClasses ( classExpression ) ; } catch ( final ElkInconsistentOntologyException e ) { // All classes are equivalent to each other, so also to owl:Nothing. return getTaxonomyQuietly ( ) . getBottomNode ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) subclasses of the given { @link ElkClassExpression } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalent class of subclasses . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkClass > > getSubClasses ( ElkClassExpression classExpression , boolean direct ) throws ElkInconsistentOntologyException , ElkException { if ( classExpression instanceof ElkClass ) { final TaxonomyNode < ElkClass > queryNode = getTaxonomyNode ( ( ElkClass ) classExpression ) ; return direct ? queryNode . getDirectSubNodes ( ) : queryNode . getAllSubNodes ( ) ; } else { final Set < ? extends Node < ElkClass > > subNodes = queryDirectSubClasses ( classExpression ) ; if ( direct ) { return subNodes ; } // else all nodes final Taxonomy < ElkClass > taxonomy = restoreTaxonomy ( ) ; return TaxonomyNodeUtils . getAllReachable ( Operations . map ( subNodes , new Operations . Transformation < Node < ElkClass > , TaxonomyNode < ElkClass > > ( ) { @ Override public TaxonomyNode < ElkClass > transform ( final Node < ElkClass > node ) { return taxonomy . getNode ( node . getCanonicalMember ( ) ) ; } } ) , new Operations . Functor < TaxonomyNode < ElkClass > , Set < ? extends TaxonomyNode < ElkClass > > > ( ) { @ Override public Set < ? extends TaxonomyNode < ElkClass > > apply ( final TaxonomyNode < ElkClass > node ) { return node . getDirectSubNodes ( ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) subclasses of the given { @link ElkClassExpression } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalent class of subclasses . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkClass > > getSubClassesQuietly ( final ElkClassExpression classExpression , final boolean direct ) throws ElkException { try { return getSubClasses ( classExpression , direct ) ; } catch ( final ElkInconsistentOntologyException e ) { // All classes are equivalent to each other, so also to owl:Nothing. final TaxonomyNode < ElkClass > node = getTaxonomyQuietly ( ) . getBottomNode ( ) ; return direct ? node . getDirectSubNodes ( ) : node . getAllSubNodes ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) superclasses of the given { @link ElkClassExpression } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalent class of superclasses . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkClass > > getSuperClasses ( ElkClassExpression classExpression , boolean direct ) throws ElkInconsistentOntologyException , ElkException { if ( classExpression instanceof ElkClass ) { final TaxonomyNode < ElkClass > queryNode = getTaxonomyNode ( ( ElkClass ) classExpression ) ; return direct ? queryNode . getDirectSuperNodes ( ) : queryNode . getAllSuperNodes ( ) ; } else { final Set < ? extends Node < ElkClass > > superNodes = queryDirectSuperClasses ( classExpression ) ; if ( direct ) { return superNodes ; } // else all nodes final Taxonomy < ElkClass > taxonomy = restoreTaxonomy ( ) ; return TaxonomyNodeUtils . getAllReachable ( Operations . map ( superNodes , new Operations . Transformation < Node < ElkClass > , TaxonomyNode < ElkClass > > ( ) { @ Override public TaxonomyNode < ElkClass > transform ( final Node < ElkClass > node ) { return taxonomy . getNode ( node . getCanonicalMember ( ) ) ; } } ) , new Operations . Functor < TaxonomyNode < ElkClass > , Set < ? extends TaxonomyNode < ElkClass > > > ( ) { @ Override public Set < ? extends TaxonomyNode < ElkClass > > apply ( final TaxonomyNode < ElkClass > node ) { return node . getDirectSuperNodes ( ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) superclasses of the given { @link ElkClassExpression } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalent class of superclasses . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkClass > > getSuperClassesQuietly ( ElkClassExpression classExpression , boolean direct ) throws ElkException { try { return getSuperClasses ( classExpression , direct ) ; } catch ( final ElkInconsistentOntologyException e ) { // All classes are equivalent to each other, so also to owl:Nothing. final TaxonomyNode < ElkClass > node = getTaxonomyQuietly ( ) . getBottomNode ( ) ; return direct ? node . getDirectSuperNodes ( ) : node . getAllSuperNodes ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) sub - properties of the given { @link ElkObjectProperty } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalence class of sub - properties . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkObjectProperty > > getSubObjectProperties ( final ElkObjectProperty property , final boolean direct ) throws ElkException { final TaxonomyNode < ElkObjectProperty > queryNode = getObjectPropertyNode ( property ) ; return ( direct ) ? queryNode . getDirectSubNodes ( ) : queryNode . getAllSubNodes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) super - properties of the given { @link ElkObjectProperty } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalence class of super - properties . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkObjectProperty > > getSuperObjectProperties ( final ElkObjectProperty property , final boolean direct ) throws ElkException { TaxonomyNode < ElkObjectProperty > queryNode = getObjectPropertyNode ( property ) ; return ( direct ) ? queryNode . getDirectSuperNodes ( ) : queryNode . getAllSuperNodes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) instances of the given { @link ElkClassExpression } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalent class of instances . Calling of this method may trigger the computation of the realization if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkNamedIndividual > > getInstances ( ElkClassExpression classExpression , boolean direct ) throws ElkInconsistentOntologyException , ElkException { if ( classExpression instanceof ElkClass ) { final TypeNode < ElkClass , ElkNamedIndividual > queryNode = getTypeNode ( ( ElkClass ) classExpression ) ; return direct ? queryNode . getDirectInstanceNodes ( ) : queryNode . getAllInstanceNodes ( ) ; } final Set < ? extends Node < ElkNamedIndividual > > instances = queryDirectInstances ( classExpression ) ; if ( direct ) { return instances ; } // else all instances final Set < ? extends Node < ElkClass > > subNodes = queryDirectSubClasses ( classExpression ) ; final InstanceTaxonomy < ElkClass , ElkNamedIndividual > taxonomy = restoreInstanceTaxonomy ( ) ; return TaxonomyNodeUtils . collectFromAllReachable ( Operations . map ( subNodes , new Operations . Transformation < Node < ElkClass > , TypeNode < ElkClass , ElkNamedIndividual > > ( ) { @ Override public TypeNode < ElkClass , ElkNamedIndividual > transform ( final Node < ElkClass > node ) { return taxonomy . getNode ( node . getCanonicalMember ( ) ) ; } } ) , Operations . map ( instances , new Operations . Transformation < Node < ElkNamedIndividual > , InstanceNode < ElkClass , ElkNamedIndividual > > ( ) { @ Override public InstanceNode < ElkClass , ElkNamedIndividual > transform ( final Node < ElkNamedIndividual > node ) { return taxonomy . getInstanceNode ( node . getCanonicalMember ( ) ) ; } } ) , new Operations . Functor < TypeNode < ElkClass , ElkNamedIndividual > , Set < ? extends TypeNode < ElkClass , ElkNamedIndividual > > > ( ) { @ Override public Set < ? extends TypeNode < ElkClass , ElkNamedIndividual > > apply ( final TypeNode < ElkClass , ElkNamedIndividual > node ) { return node . getDirectSubNodes ( ) ; } } , new Operations . Functor < TypeNode < ElkClass , ElkNamedIndividual > , Set < ? extends InstanceNode < ElkClass , ElkNamedIndividual > > > ( ) { @ Override public Set < ? extends InstanceNode < ElkClass , ElkNamedIndividual > > apply ( final TypeNode < ElkClass , ElkNamedIndividual > node ) { return node . getDirectInstanceNodes ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) instances of the given { @link ElkClassExpression } as specified by the parameter . The method returns a set of { @link Node } s each of which representing an equivalent class of instances . Calling of this method may trigger the computation of the realization if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkNamedIndividual > > getInstancesQuietly ( ElkClassExpression classExpression , boolean direct ) throws ElkException { try { return getInstances ( classExpression , direct ) ; } catch ( final ElkInconsistentOntologyException e ) { // All classes are equivalent to each other, so also to owl:Nothing. final TypeNode < ElkClass , ElkNamedIndividual > node = getInstanceTaxonomyQuietly ( ) . getBottomNode ( ) ; return direct ? node . getDirectInstanceNodes ( ) : node . getAllInstanceNodes ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the ( direct or indirect ) types of the given { @link ElkNamedIndividual } . The method returns a set of { @link Node } s each of which representing an equivalent class of types . Calling of this method may trigger the computation of the realization if it has not been done yet . [CODESPLIT] public synchronized Set < ? extends Node < ElkClass > > getTypes ( ElkNamedIndividual elkNamedIndividual , boolean direct ) throws ElkException { InstanceNode < ElkClass , ElkNamedIndividual > node = getInstanceNode ( elkNamedIndividual ) ; return direct ? node . getDirectTypeNodes ( ) : node . getAllTypeNodes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given { @link ElkClassExpression } is satisfiable that is if it can possibly have instances . { @link ElkClassExpression } s are not satisfiable if they are equivalent to { @code owl : Nothing } . A satisfiable { @link ElkClassExpression } is also called consistent or coherent . Calling of this method may trigger the computation of the taxonomy if it has not been done yet . [CODESPLIT] public synchronized boolean isSatisfiable ( ElkClassExpression classExpression ) throws ElkException { if ( classExpression instanceof ElkClass ) { final TaxonomyNode < ElkClass > queryNode = getTaxonomyNode ( ( ElkClass ) classExpression ) ; return ! queryNode . contains ( getElkFactory ( ) . getOwlNothing ( ) ) ; } return querySatisfiability ( classExpression ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the heading together with the separators [CODESPLIT] public void printHeader ( ) { printSeparator ( ) ; addPadding ( ' ' , headerParams_ ) ; logger_ . debug ( String . format ( headerFormat_ , headerParams_ ) ) ; printSeparator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends a string consisting of the given character to the first value so that when the values when formatted have in total { @value #FORMAT_WIDTH_ } characters [CODESPLIT] Object [ ] addPadding ( char c , Object ... values ) { String firstValue = values [ 0 ] . toString ( ) ; int paddingLength = maxPaddingWidth_ - firstValue . length ( ) ; if ( paddingLength > 0 ) { String padding = getString ( c , paddingLength ) ; values [ 0 ] = firstValue + padding ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Formats and the given values adding padding symbols if necessary . The given array may be modified but the values themselves are not modified . [CODESPLIT] public void print ( Object ... values ) { addPadding ( ' ' , values ) ; logger_ . debug ( String . format ( valuesFormat_ , values ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a string of the given length consisting of the given character [CODESPLIT] static String getString ( char c , int n ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < n ; i ++ ) { sb . append ( c ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines an ordering on IRIs starting with { @link #OWL_NOTHING } { @link #OWL_THING } followed by the remaining IRIs in alphabetical order . [CODESPLIT] public static int compare ( ElkIri firstIri , ElkIri secondIri ) { boolean isOwl0 = firstIri . equals ( OWL_THING ) || firstIri . equals ( OWL_NOTHING ) ; boolean isOwl1 = secondIri . equals ( OWL_THING ) || secondIri . equals ( OWL_NOTHING ) ; if ( isOwl0 == isOwl1 ) return firstIri . compareTo ( secondIri ) ; // else return isOwl0 ? - 1 : 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Arguments are as follows : 0 - name of the reasoning task ( SAT query classification consistency ) 1 - ontology path 2 - output path 3 - concept URI in case of SAT [CODESPLIT] public static void main ( String [ ] args ) throws Exception { Task task = validateArgs ( args ) ; // help if ( task == null ) { printHelp ( ) ; return ; } NativeRunner runner = new NativeRunner ( ) ; runner . run ( args , task ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if { @link ProofStep } is derived by { @link ElkClassInclusionExistentialComposition } inference where the last premise is derived from { @link ElkPropertyInclusionOfTransitiveObjectProperty } [CODESPLIT] static ProofNode < OWLAxiom > canConvertStep ( ProofStep < OWLAxiom > step ) { if ( step . getName ( ) != ElkClassInclusionExistentialComposition . NAME ) { return null ; } List < ? extends ProofNode < OWLAxiom > > premises = step . getPremises ( ) ; ProofNode < OWLAxiom > lastPremise = premises . get ( premises . size ( ) - 1 ) ; Collection < ? extends ProofStep < OWLAxiom > > lastPremiseSteps = lastPremise . getInferences ( ) ; if ( lastPremiseSteps . size ( ) != 1 ) { return null ; } // else for ( ProofStep < OWLAxiom > lastPremiseStep : lastPremiseSteps ) { if ( lastPremiseStep . getName ( ) == ElkPropertyInclusionOfTransitiveObjectProperty . NAME ) { return lastPremiseStep . getPremises ( ) . get ( 0 ) ; } } // else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prunes { @link #toAdd_ } . <p > <strong > { @code taxonomy_ } must not be { @code null } !< / strong > [CODESPLIT] private int pruneToAdd ( ) { final Iterator < IndexedClass > iter = toAdd_ . iterator ( ) ; int size = 0 ; while ( iter . hasNext ( ) ) { final IndexedClass cls = iter . next ( ) ; /* @formatter:off\n\t\t\t * \n\t\t\t * Should be pruned when:\n\t\t\t * it is not in ontology, or\n\t\t\t * it is in the top node, or\n\t\t\t * it has super-nodes in taxonomy.\n\t\t\t * \n\t\t\t * @formatter:on\n\t\t\t */ if ( ! cls . occurs ( ) ) { iter . remove ( ) ; continue ; } // else final Context context = saturationState_ . getContext ( cls ) ; if ( context == null || ! context . isInitialized ( ) || ! context . isSaturated ( ) ) { // it is not saturated. size ++ ; continue ; } // else final TaxonomyNode < ElkClass > node = taxonomy_ . getNode ( cls . getElkEntity ( ) ) ; if ( node == null ) { // it is not in taxonomy size ++ ; continue ; } // else if ( node . equals ( taxonomy_ . getTopNode ( ) ) ) { iter . remove ( ) ; continue ; } // else if ( ! node . getDirectSuperNodes ( ) . isEmpty ( ) ) { iter . remove ( ) ; continue ; } // else size ++ ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prunes { @link #toRemove_ } . <p > <strong > { @code taxonomy_ } must not be { @code null } !< / strong > [CODESPLIT] private int pruneToRemove ( ) { final Iterator < IndexedClass > iter = toRemove_ . iterator ( ) ; int size = 0 ; while ( iter . hasNext ( ) ) { final IndexedClass cls = iter . next ( ) ; /* @formatter:off\n\t\t\t * \n\t\t\t * Should be pruned when\n\t\t\t * it is not in taxonomy, or\n\t\t\t * it is in the bottom class.\n\t\t\t * \n\t\t\t * @formatter:on\n\t\t\t */ final TaxonomyNode < ElkClass > node = taxonomy_ . getNode ( cls . getElkEntity ( ) ) ; if ( node == null ) { iter . remove ( ) ; continue ; } // else if ( cls == ontologyIndex_ . getOwlNothing ( ) ) { iter . remove ( ) ; continue ; } size ++ ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the values the corresponding values of the given counter [CODESPLIT] public synchronized void add ( RuleCounter counter ) { countOwlThingContextInitRule += counter . countOwlThingContextInitRule ; countRootContextInitializationRule += counter . countRootContextInitializationRule ; countDisjointSubsumerFromMemberRule += counter . countDisjointSubsumerFromMemberRule ; countContradictionFromNegationRule += counter . countContradictionFromNegationRule ; countObjectIntersectionFromFirstConjunctRule += counter . countObjectIntersectionFromFirstConjunctRule ; countObjectIntersectionFromSecondConjunctRule += counter . countObjectIntersectionFromSecondConjunctRule ; countSuperClassFromSubClassRule += counter . countSuperClassFromSubClassRule ; countPropagationFromExistentialFillerRule += counter . countPropagationFromExistentialFillerRule ; countObjectUnionFromDisjunctRule += counter . countObjectUnionFromDisjunctRule ; countBackwardLinkChainFromBackwardLinkRule += counter . countBackwardLinkChainFromBackwardLinkRule ; countSubsumerBackwardLinkRule += counter . countSubsumerBackwardLinkRule ; countContradictionOverBackwardLinkRule += counter . countContradictionOverBackwardLinkRule ; countContradictionPropagationRule += counter . countContradictionPropagationRule ; countContradictionCompositionRule += counter . countContradictionCompositionRule ; countNonReflexiveBackwardLinkCompositionRule += counter . countNonReflexiveBackwardLinkCompositionRule ; countIndexedObjectIntersectionOfDecomposition += counter . countIndexedObjectIntersectionOfDecomposition ; countIndexedObjectSomeValuesFromDecomposition += counter . countIndexedObjectSomeValuesFromDecomposition ; countIndexedObjectComplementOfDecomposition += counter . countIndexedObjectComplementOfDecomposition ; countIndexedObjectHasSelfDecomposition += counter . countIndexedObjectHasSelfDecomposition ; countContradictionFromOwlNothingRule += counter . countContradictionFromOwlNothingRule ; countSubsumerPropagationRule += counter . countSubsumerPropagationRule ; countReflexiveBackwardLinkCompositionRule += counter . countReflexiveBackwardLinkCompositionRule ; countPropagationInitializationRule += counter . countPropagationInitializationRule ; countBackwardLinkFromForwardLinkRule += counter . countBackwardLinkFromForwardLinkRule ; countComposedFromDecomposedSubsumerRule += counter . countComposedFromDecomposedSubsumerRule ; countIndexedClassDecompositionRule += counter . countIndexedClassDecompositionRule ; countIndexedClassFromDefinitionRule += counter . countIndexedClassFromDefinitionRule ; countEquivalentClassFirstFromSecondRule += counter . countEquivalentClassFirstFromSecondRule ; countEquivalentClassSecondFromFirstRule += counter . countEquivalentClassSecondFromFirstRule ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the given input concurrently using the provided input processor . If the process has been interrupted this method can be called again to continue the computation . [CODESPLIT] public void process ( ) { if ( ! start ( ) ) { String message = \"Could not start workers required for reasoner computation!\" ; LOGGER_ . error ( message ) ; throw new ElkRuntimeException ( message ) ; } try { finish ( ) ; } catch ( InterruptedException e ) { // restore interrupt status Thread . currentThread ( ) . interrupt ( ) ; throw new ElkRuntimeException ( \"Reasoner computation interrupted externally!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "From { [CODESPLIT] private InputStream getBodyFromServletRequestParameters ( HttpServletRequest request , String charset ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( 1024 ) ; Writer writer = new OutputStreamWriter ( bos , charset ) ; @ SuppressWarnings ( \"unchecked\" ) Map < String , String [ ] > form = request . getParameterMap ( ) ; for ( Iterator < String > nameIterator = form . keySet ( ) . iterator ( ) ; nameIterator . hasNext ( ) ; ) { String name = nameIterator . next ( ) ; List < String > values = Arrays . asList ( form . get ( name ) ) ; for ( Iterator < String > valueIterator = values . iterator ( ) ; valueIterator . hasNext ( ) ; ) { String value = valueIterator . next ( ) ; writer . write ( URLEncoder . encode ( name , charset ) ) ; if ( value != null ) { writer . write ( ' ' ) ; writer . write ( URLEncoder . encode ( value , charset ) ) ; if ( valueIterator . hasNext ( ) ) { writer . write ( ' ' ) ; } } } if ( nameIterator . hasNext ( ) ) { writer . append ( ' ' ) ; } } writer . flush ( ) ; return new ByteArrayInputStream ( bos . toByteArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively converts object to xhtml data . [CODESPLIT] private void writeResource ( XhtmlWriter writer , Object object ) { if ( object == null ) { return ; } try { if ( object instanceof Resource ) { Resource < ? > resource = ( Resource < ? > ) object ; writer . beginListItem ( ) ; writeResource ( writer , resource . getContent ( ) ) ; writer . writeLinks ( resource . getLinks ( ) ) ; writer . endListItem ( ) ; } else if ( object instanceof Resources ) { Resources < ? > resources = ( Resources < ? > ) object ; // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar writer . beginListItem ( ) ; writer . beginUnorderedList ( ) ; Collection < ? > content = resources . getContent ( ) ; writeResource ( writer , content ) ; writer . endUnorderedList ( ) ; writer . writeLinks ( resources . getLinks ( ) ) ; writer . endListItem ( ) ; } else if ( object instanceof ResourceSupport ) { ResourceSupport resource = ( ResourceSupport ) object ; writer . beginListItem ( ) ; writeObject ( writer , resource ) ; writer . writeLinks ( resource . getLinks ( ) ) ; writer . endListItem ( ) ; } else if ( object instanceof Collection ) { Collection < ? > collection = ( Collection < ? > ) object ; for ( Object item : collection ) { writeResource ( writer , item ) ; } } else { // TODO: write li for simple objects in Resources Collection writeObject ( writer , object ) ; } } catch ( Exception ex ) { throw new RuntimeException ( \"failed to transform object \" + object , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets input parameter info which is part of the URL mapping be it request parameters path variables or request body attributes . [CODESPLIT] @ Override public ActionInputParameter getActionInputParameter ( String name ) { ActionInputParameter ret = requestParams . get ( name ) ; if ( ret == null ) { ret = pathVariables . get ( name ) ; } if ( ret == null ) { for ( ActionInputParameter annotatedParameter : getInputParameters ( ) ) { // TODO create ActionInputParameter for bean property at property path // TODO field access in addition to bean? PropertyDescriptor pd = getPropertyDescriptorForPropertyPath ( name , annotatedParameter . getParameterType ( ) ) ; if ( pd != null ) { if ( pd . getWriteMethod ( ) != null ) { Object callValue = annotatedParameter . getValue ( ) ; Object propertyValue = null ; if ( callValue != null ) { BeanWrapper beanWrapper = PropertyAccessorFactory . forBeanPropertyAccess ( callValue ) ; propertyValue = beanWrapper . getPropertyValue ( name ) ; } ret = new SpringActionInputParameter ( new MethodParameter ( pd . getWriteMethod ( ) , 0 ) , propertyValue ) ; } break ; } } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively navigate to return a BeanWrapper for the nested property path . [CODESPLIT] PropertyDescriptor getPropertyDescriptorForPropertyPath ( String propertyPath , Class < ? > propertyType ) { int pos = PropertyAccessorUtils . getFirstNestedPropertySeparatorIndex ( propertyPath ) ; // Handle nested properties recursively. if ( pos > - 1 ) { String nestedProperty = propertyPath . substring ( 0 , pos ) ; String nestedPath = propertyPath . substring ( pos + 1 ) ; PropertyDescriptor propertyDescriptor = BeanUtils . getPropertyDescriptor ( propertyType , nestedProperty ) ; //            BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty); return getPropertyDescriptorForPropertyPath ( nestedPath , propertyDescriptor . getPropertyType ( ) ) ; } else { return BeanUtils . getPropertyDescriptor ( propertyType , propertyPath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines action input parameters for required url variables . [CODESPLIT] @ Override public Map < String , ActionInputParameter > getRequiredParameters ( ) { Map < String , ActionInputParameter > ret = new HashMap < String , ActionInputParameter > ( ) ; for ( Map . Entry < String , ActionInputParameter > entry : requestParams . entrySet ( ) ) { ActionInputParameter annotatedParameter = entry . getValue ( ) ; if ( annotatedParameter . isRequired ( ) ) { ret . put ( entry . getKey ( ) , annotatedParameter ) ; } } for ( Map . Entry < String , ActionInputParameter > entry : pathVariables . entrySet ( ) ) { ActionInputParameter annotatedParameter = entry . getValue ( ) ; ret . put ( entry . getKey ( ) , annotatedParameter ) ; } // requestBody not supported, would have to use exploded modifier return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the given class holds only one data item . Can be useful to determine if a value should be rendered as scalar . [CODESPLIT] public static boolean isSingleValueType ( Class < ? > clazz ) { boolean ret ; if ( isNumber ( clazz ) || isBoolean ( clazz ) || isString ( clazz ) || isEnum ( clazz ) || isDate ( clazz ) || isCalendar ( clazz ) || isCurrency ( clazz ) ) { ret = true ; } else { ret = false ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the given string contains only 0 - 9 [ ISO - LATIN - 1 ] or an optional leading + / - sign . [CODESPLIT] public static boolean isIsoLatin1Number ( String str ) { if ( str == null ) return false ; char [ ] data = str . toCharArray ( ) ; if ( data . length == 0 ) return false ; int index = 0 ; if ( data . length > 1 && ( data [ 0 ] == ' ' || data [ 0 ] == ' ' ) ) index = 1 ; for ( ; index < data . length ; index ++ ) { if ( data [ index ] < ' ' || data [ index ] > ' ' ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The relation type of the link . [CODESPLIT] public void addRel ( String rel ) { Assert . hasLength ( rel ) ; linkParams . add ( REL . paramName , rel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The type parameter when present is a hint indicating what the media type of the result of dereferencing the link should be . Note that this is only a hint ; for example it does not override the Content - Type header of a HTTP response obtained by actually following the link . There MUST NOT be more than one type parameter in a link - value . [CODESPLIT] public void setType ( String mediaType ) { if ( mediaType != null ) linkParams . set ( TYPE . paramName , mediaType ) ; else linkParams . remove ( TYPE . paramName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The hreflang parameter when present is a hint indicating what the language of the result of dereferencing the link should be . Note that this is only a hint ; for example it does not override the Content - Language header of a HTTP response obtained by actually following the link . Multiple hreflang parameters on a single link - value indicate that multiple languages are available from the indicated resource . [CODESPLIT] public void addHreflang ( String hreflang ) { Assert . hasLength ( hreflang ) ; linkParams . add ( HREFLANG . paramName , hreflang ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The title parameter when present is used to label the destination of a link such that it can be used as a human - readable identifier ( e . g . a menu entry ) in the language indicated by the Content - Language header ( if present ) . The title parameter MUST NOT appear more than once in a given link - value ; occurrences after the first MUST be ignored by parsers . [CODESPLIT] public void setTitle ( String title ) { if ( title != null ) linkParams . set ( TITLE . paramName , title ) ; else { linkParams . remove ( TITLE . paramName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The title * parameter can be used to encode the title label in a different character set and / or contain language information as per <a href = https : // tools . ietf . org / html / rfc5987 > RFC - 5987< / a > . The title * parameter MUST NOT appear more than once in a given link - value ; occurrences after the first MUST be ignored by parsers . If the parameter does not contain language information its language is indicated by the Content - Language header ( when present ) . <p > If both the title and title * parameters appear in a link - value processors SHOULD use the title * parameter s value . <p > The example below shows an instance of the Link header encoding a link title using <a href = https : // tools . ietf . org / html / rfc2231 > RFC - 2231< / a > encoding to encode both non - ASCII characters and language information . < / p > <pre > Link : &lt ; / TheBook / chapter2&gt ; rel = next ; title * = UTF - 8 de n%c3%a4chstes%20Kapitel < / pre > [CODESPLIT] public void setTitleStar ( String titleStar ) { if ( titleStar != null ) linkParams . set ( TITLE_STAR . paramName , titleStar ) ; else linkParams . remove ( TITLE_STAR . paramName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The media parameter when present is used to indicate intended destination medium or media for style information ( see [ W3C . REC - html401 - 19991224 ] Section 6 . 13 ) . Note that this may be updated by [ W3C . CR - css3 - mediaqueries - 20090915 ] ) . Its value MUST be quoted if it contains a semicolon ( ; ) or comma ( ) and there MUST NOT be more than one media parameter in a link - value . [CODESPLIT] public void setMedia ( String mediaDesc ) { if ( mediaDesc != null ) linkParams . set ( MEDIA . paramName , mediaDesc ) ; else linkParams . remove ( MEDIA . paramName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The rev parameter has been used in the past to indicate that the semantics of the relationship are in the reverse direction . That is a link from A to B with REL = X expresses the same relationship as a link from B to A with REV = X . rev is deprecated by this specification because it often confuses authors and readers ; in most cases using a separate relation type is preferable . [CODESPLIT] public void addRev ( String rev ) { Assert . hasLength ( rev ) ; linkParams . add ( REV . paramName , rev ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "By default the context of a link conveyed in the Link header field is the IRI of the requested resource . <p > When present the anchor parameter overrides this with another URI such as a fragment of this resource or a third resource ( i . e . when the anchor value is an absolute URI ) . If the anchor parameter s value is a relative URI parsers MUST resolve it as per [ RFC3986 ] Section 5 . Note that any base URI from the body s content is not applied . [CODESPLIT] public void setAnchor ( String anchor ) { if ( anchor != null ) linkParams . set ( ANCHOR . paramName , anchor ) ; else linkParams . remove ( ANCHOR . paramName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds link - extension params i . e . custom params which are not described in the web linking rfc . [CODESPLIT] public void addLinkParam ( String paramName , String ... values ) { Assert . notEmpty ( values ) ; for ( String value : values ) { Assert . hasLength ( value ) ; linkParams . add ( paramName , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Affordance represented as http link header value . Note that the href may be templated for convenience you can use { @link #getHeaderName () } to ensure a Link or Link - Header is produced appropriately . [CODESPLIT] public String asHeader ( ) { StringBuilder result = new StringBuilder ( ) ; for ( Map . Entry < String , List < String > > linkParamEntry : linkParams . entrySet ( ) ) { if ( result . length ( ) != 0 ) { result . append ( \"; \" ) ; } String linkParamEntryKey = linkParamEntry . getKey ( ) ; if ( REL . paramName . equals ( linkParamEntryKey ) || REV . paramName . equals ( linkParamEntryKey ) ) { result . append ( linkParamEntryKey ) . append ( \"=\" ) ; result . append ( \"\\\"\" ) . append ( StringUtils . collectionToDelimitedString ( linkParamEntry . getValue ( ) , \" \" ) ) . append ( \"\\\"\" ) ; } else { StringBuilder linkParams = new StringBuilder ( ) ; for ( String value : linkParamEntry . getValue ( ) ) { if ( linkParams . length ( ) != 0 ) { linkParams . append ( \"; \" ) ; } linkParams . append ( linkParamEntryKey ) . append ( \"=\" ) ; linkParams . append ( \"\\\"\" ) . append ( value ) . append ( \"\\\"\" ) ; } result . append ( linkParams ) ; } } String linkHeader = \"<\" + partialUriTemplate . asComponents ( ) . toString ( ) + \">; \" ; return result . insert ( 0 , linkHeader ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands template variables arguments must satisfy all required template variables unsatisfied optional arguments will be removed . [CODESPLIT] @ Override public Affordance expand ( Map < String , ? extends Object > arguments ) { UriTemplate template = new UriTemplate ( partialUriTemplate . asComponents ( ) . toString ( ) ) ; String expanded = template . expand ( arguments ) . toASCIIString ( ) ; return new Affordance ( expanded , linkParams , actionDescriptors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands template variables as far as possible unsatisfied variables will remain variables . This is primarily for manually created affordances . If the Affordance has been created with linkTo - methodOn it should not be necessary to expand the affordance again . [CODESPLIT] public Affordance expandPartially ( Object ... arguments ) { return new Affordance ( partialUriTemplate . expand ( arguments ) . toString ( ) , linkParams , actionDescriptors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands template variables as far as possible unsatisfied variables will remain variables . This is primarily for manually created affordances . If the Affordance has been created with linkTo - methodOn it should not be necessary to expand the affordance again . [CODESPLIT] public Affordance expandPartially ( Map < String , ? extends Object > arguments ) { return new Affordance ( partialUriTemplate . expand ( ( Map < String , Object > ) arguments ) . toString ( ) , linkParams , actionDescriptors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows to retrieve all rels defined for this affordance . [CODESPLIT] @ JsonIgnore public List < String > getRels ( ) { final List < String > rels = linkParams . get ( REL . paramName ) ; return rels == null ? Collections . < String > emptyList ( ) : Collections . unmodifiableList ( rels ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all revs for this affordance . [CODESPLIT] @ JsonIgnore public List < String > getRevs ( ) { final List < String > revs = linkParams . get ( REV . paramName ) ; return revs == null ? Collections . < String > emptyList ( ) : Collections . unmodifiableList ( revs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the affordance has unsatisfied required variables . This allows to decide if the affordance can also be treated as a plain Link without template variables if the caller omits all optional variables . Serializers can use this to render it as a resource with optional search features . [CODESPLIT] @ JsonIgnore public boolean hasUnsatisfiedRequiredVariables ( ) { for ( ActionDescriptor actionDescriptor : actionDescriptors ) { Map < String , ActionInputParameter > requiredParameters = actionDescriptor . getRequiredParameters ( ) ; for ( ActionInputParameter annotatedParameter : requiredParameters . values ( ) ) { if ( ! annotatedParameter . hasValue ( ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @link ForwardedHeader } from the given source . [CODESPLIT] public static ForwardedHeader of ( String source ) { if ( ! StringUtils . hasText ( source ) ) { return NO_HEADER ; } Map < String , String > elements = new HashMap < String , String > ( ) ; for ( String part : source . split ( \";\" ) ) { String [ ] keyValue = part . split ( \"=\" ) ; if ( keyValue . length != 2 ) { continue ; } elements . put ( keyValue [ 0 ] . trim ( ) , keyValue [ 1 ] . trim ( ) ) ; } Assert . notNull ( elements , \"Forwarded elements must not be null!\" ) ; Assert . isTrue ( ! elements . isEmpty ( ) , \"At least one forwarded element needs to be present!\" ) ; return new ForwardedHeader ( elements ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The value of the parameter at sample invocation time formatted according to conversion configuration . [CODESPLIT] public String getValueFormatted ( ) { String ret ; if ( value == null ) { ret = null ; } else { ret = ( String ) conversionService . convert ( value , typeDescriptor , TypeDescriptor . valueOf ( String . class ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets HTML5 parameter type for input field according to { @link Type } annotation . [CODESPLIT] @ Override public Type getHtmlInputFieldType ( ) { final Type ret ; if ( inputAnnotation == null || inputAnnotation . value ( ) == Type . FROM_JAVA ) { if ( isArrayOrCollection ( ) || isRequestBody ( ) ) { ret = null ; } else if ( DataType . isNumber ( getParameterType ( ) ) ) { ret = Type . NUMBER ; } else { ret = Type . TEXT ; } } else { ret = inputAnnotation . value ( ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if request body input parameter has a hidden input property . [CODESPLIT] @ Override public boolean isHidden ( String property ) { Annotation [ ] paramAnnotations = methodParameter . getParameterAnnotations ( ) ; Input inputAnnotation = methodParameter . getParameterAnnotation ( Input . class ) ; return inputAnnotation != null && arrayContains ( inputAnnotation . hidden ( ) , property ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find out if property is included by searching through all annotations . [CODESPLIT] private boolean containsPropertyIncludeValue ( String property ) { return arrayContains ( inputAnnotation . readOnly ( ) , property ) || arrayContains ( inputAnnotation . hidden ( ) , property ) || arrayContains ( inputAnnotation . include ( ) , property ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Has any explicit include value or might have implicit includes because there is a hidden or readOnly flag . [CODESPLIT] private boolean hasExplicitOrImplicitPropertyIncludeValue ( ) { // TODO maybe not a useful optimization return inputAnnotation != null && inputAnnotation . readOnly ( ) . length > 0 || inputAnnotation . hidden ( ) . length > 0 || inputAnnotation . include ( ) . length > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if request body input parameter should be excluded considering { @link Input#exclude } . [CODESPLIT] @ Override public boolean isExcluded ( String property ) { return inputAnnotation != null && arrayContains ( inputAnnotation . exclude ( ) , property ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is this action input parameter required based on the presence of a default value the parameter annotations and the kind of input parameter . [CODESPLIT] public boolean isRequired ( ) { boolean ret ; if ( isRequestBody ( ) ) { ret = requestBody . required ( ) ; } else if ( isRequestParam ( ) ) { ret = ! ( isDefined ( requestParam . defaultValue ( ) ) || ! requestParam . required ( ) ) ; } else if ( isRequestHeader ( ) ) { ret = ! ( isDefined ( requestHeader . defaultValue ( ) ) || ! requestHeader . required ( ) ) ; } else { ret = true ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines default value of request param or request header if available . [CODESPLIT] public String getDefaultValue ( ) { String ret ; if ( isRequestParam ( ) ) { ret = isDefined ( requestParam . defaultValue ( ) ) ? requestParam . defaultValue ( ) : null ; } else if ( isRequestHeader ( ) ) { ret = ! ( ValueConstants . DEFAULT_NONE . equals ( requestHeader . defaultValue ( ) ) ) ? requestHeader . defaultValue ( ) : null ; } else { ret = null ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows convenient access to multiple call values in case that this input parameter is an array or collection . Make sure to check { @link #isArrayOrCollection () } before calling this method . [CODESPLIT] public Object [ ] getValues ( ) { Object [ ] callValues ; if ( ! isArrayOrCollection ( ) ) { throw new UnsupportedOperationException ( \"parameter is not an array or collection\" ) ; } Object callValue = getValue ( ) ; if ( callValue == null ) { callValues = new Object [ 0 ] ; } else { Class < ? > parameterType = getParameterType ( ) ; if ( parameterType . isArray ( ) ) { callValues = ( Object [ ] ) callValue ; } else { callValues = ( ( Collection < ? > ) callValue ) . toArray ( ) ; } } return callValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets request parameter name of this action input parameter . [CODESPLIT] @ Override public String getParameterName ( ) { String ret = null ; if ( requestParam != null ) { String requestParamName = requestParam . value ( ) ; if ( ! requestParamName . isEmpty ( ) ) ret = requestParamName ; } if ( pathVariable != null ) { String pathVariableName = pathVariable . value ( ) ; if ( ! pathVariableName . isEmpty ( ) ) ret = pathVariableName ; } if ( ret == null ) { String parameterName = methodParameter . getParameterName ( ) ; if ( parameterName == null ) { methodParameter . initParameterNameDiscovery ( new LocalVariableTableParameterNameDiscoverer ( ) ) ; ret = methodParameter . getParameterName ( ) ; } else { ret = parameterName ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes bean description recursively . [CODESPLIT] private void recurseSupportedProperties ( JsonGenerator jgen , String currentVocab , Class < ? > valueType , ActionDescriptor allRootParameters , ActionInputParameter rootParameter , Object currentCallValue , String propertyPath ) throws IntrospectionException , IOException { Map < String , ActionInputParameter > properties = new HashMap < String , ActionInputParameter > ( ) ; // collect supported properties from ctor Constructor [ ] constructors = valueType . getConstructors ( ) ; // find default ctor Constructor constructor = PropertyUtils . findDefaultCtor ( constructors ) ; // find ctor with JsonCreator ann if ( constructor == null ) { constructor = PropertyUtils . findJsonCreator ( constructors , JsonCreator . class ) ; } if ( constructor == null ) { // TODO this can be a generic collection, find a way to describe it LOG . warn ( \"can't describe supported properties, no default constructor or JsonCreator found for type \" + valueType . getName ( ) ) ; return ; } int parameterCount = constructor . getParameterTypes ( ) . length ; if ( parameterCount > 0 ) { Annotation [ ] [ ] annotationsOnParameters = constructor . getParameterAnnotations ( ) ; Class [ ] parameters = constructor . getParameterTypes ( ) ; int paramIndex = 0 ; for ( Annotation [ ] annotationsOnParameter : annotationsOnParameters ) { for ( Annotation annotation : annotationsOnParameter ) { if ( JsonProperty . class == annotation . annotationType ( ) ) { JsonProperty jsonProperty = ( JsonProperty ) annotation ; // TODO use required attribute of JsonProperty String paramName = jsonProperty . value ( ) ; Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , paramName ) ; ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter ( new MethodParameter ( constructor , paramIndex ) , propertyValue ) ; // TODO collect ctor params, setter params and process // TODO then handle single, collection and bean for both properties . put ( paramName , constructorParamInputParameter ) ; paramIndex ++ ; // increase for each @JsonProperty } } } Assert . isTrue ( parameters . length == paramIndex , \"not all constructor arguments of @JsonCreator \" + constructor . getName ( ) + \" are annotated with @JsonProperty\" ) ; } // collect supported properties from setters // TODO support Option provider by other method args? final BeanInfo beanInfo = Introspector . getBeanInfo ( valueType ) ; final PropertyDescriptor [ ] propertyDescriptors = beanInfo . getPropertyDescriptors ( ) ; // TODO collection and map // TODO distinguish which properties should be printed as supported - now just setters for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { final Method writeMethod = propertyDescriptor . getWriteMethod ( ) ; if ( writeMethod == null ) { continue ; } // TODO: the property name must be a valid URI - need to check context for terms? String propertyName = getWritableExposedPropertyOrPropertyName ( propertyDescriptor ) ; Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , propertyDescriptor . getName ( ) ) ; MethodParameter methodParameter = new MethodParameter ( propertyDescriptor . getWriteMethod ( ) , 0 ) ; ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter ( methodParameter , propertyValue ) ; properties . put ( propertyName , propertySetterInputParameter ) ; } // write all supported properties // TODO we are using the annotatedParameter.parameterName but should use the key of properties here: for ( ActionInputParameter annotatedParameter : properties . values ( ) ) { String nextPropertyPathLevel = propertyPath . isEmpty ( ) ? annotatedParameter . getParameterName ( ) : propertyPath + ' ' + annotatedParameter . getParameterName ( ) ; Class < ? > parameterType = annotatedParameter . getParameterType ( ) ; if ( DataType . isSingleValueType ( parameterType ) ) { final Object [ ] possiblePropertyValues = rootParameter . getPossibleValues ( allRootParameters ) ; if ( rootParameter . isIncluded ( nextPropertyPathLevel ) && ! rootParameter . isExcluded ( nextPropertyPathLevel ) ) { writeSupportedProperty ( jgen , currentVocab , annotatedParameter , annotatedParameter . getParameterName ( ) , possiblePropertyValues ) ; } // TODO collections? //                        } else if (DataType.isArrayOrCollection(parameterType)) { //                            Object[] callValues = rootParameter.getValues(); //                            int items = callValues.length; //                            for (int i = 0; i < items; i++) { //                                Object value; //                                if (i < callValues.length) { //                                    value = callValues[i]; //                                } else { //                                    value = null; //                                } //                                recurseSupportedProperties(jgen, currentVocab, rootParameter // .getParameterType(), //                                        allRootParameters, rootParameter, value); //                            } } else { jgen . writeStartObject ( ) ; jgen . writeStringField ( \"hydra:property\" , annotatedParameter . getParameterName ( ) ) ; // TODO: is the property required -> for bean props we need the Access annotation to express that Expose expose = AnnotationUtils . getAnnotation ( parameterType , Expose . class ) ; String subClass = null ; if ( expose != null ) { subClass = expose . value ( ) ; } else { if ( List . class . isAssignableFrom ( parameterType ) ) { Type genericParameterType = annotatedParameter . getGenericParameterType ( ) ; if ( genericParameterType instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) genericParameterType ; Type [ ] actualTypeArguments = parameterizedType . getActualTypeArguments ( ) ; if ( actualTypeArguments . length == 1 ) { Type actualTypeArgument = actualTypeArguments [ 0 ] ; if ( actualTypeArgument instanceof Class ) { parameterType = ( Class < ? > ) actualTypeArgument ; subClass = parameterType . getSimpleName ( ) ; } else if ( actualTypeArgument instanceof ParameterizedType ) { ParameterizedType genericItemType = ( ParameterizedType ) actualTypeArgument ; Type rawType = genericItemType . getRawType ( ) ; if ( rawType instanceof Class ) { parameterType = ( Class < ? > ) rawType ; subClass = parameterType . getSimpleName ( ) ; } } } } if ( subClass != null ) { String multipleValueProp = getPropertyOrClassNameInVocab ( currentVocab , \"multipleValues\" , LdContextFactory . HTTP_SCHEMA_ORG , \"schema:\" ) ; jgen . writeBooleanField ( multipleValueProp , true ) ; } } } if ( subClass == null ) { subClass = parameterType . getSimpleName ( ) ; } jgen . writeObjectFieldStart ( getPropertyOrClassNameInVocab ( currentVocab , \"rangeIncludes\" , LdContextFactory . HTTP_SCHEMA_ORG , \"schema:\" ) ) ; jgen . writeStringField ( getPropertyOrClassNameInVocab ( currentVocab , \"subClassOf\" , \"http://www.w3.org/2000/01/rdf-schema#\" , \"rdfs:\" ) , subClass ) ; jgen . writeArrayFieldStart ( \"hydra:supportedProperty\" ) ; // TODO let defaultValue be an filled list, if needed Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , annotatedParameter . getParameterName ( ) ) ; recurseSupportedProperties ( jgen , currentVocab , parameterType , allRootParameters , rootParameter , propertyValue , nextPropertyPathLevel ) ; jgen . writeEndArray ( ) ; jgen . writeEndObject ( ) ; jgen . writeEndObject ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets property or class name in the current context either without prefix if the current vocab is the given vocabulary or prefixed otherwise . [CODESPLIT] private String getPropertyOrClassNameInVocab ( @ Nullable String currentVocab , String propertyOrClassName , String vocabulary , String vocabularyPrefixWithColon ) { Assert . notNull ( vocabulary ) ; String ret ; if ( vocabulary . equals ( currentVocab ) ) { ret = propertyOrClassName ; } else { ret = vocabularyPrefixWithColon + propertyOrClassName ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private void writeHydraVariableMapping ( JsonGenerator jgen , @ Nullable ActionDescriptor annotatedParameters , Collection < String > variableNames ) throws IOException { if ( annotatedParameters != null ) { for ( String variableName : variableNames ) { // TODO: find also @Input ActionInputParameter annotatedParameter = annotatedParameters . getActionInputParameter ( variableName ) ; // TODO access @Input parameter, too // only unsatisfied parameters become hydra variables if ( annotatedParameter != null && annotatedParameter . getValue ( ) == null ) { jgen . writeStartObject ( ) ; jgen . writeStringField ( \"@type\" , \"hydra:IriTemplateMapping\" ) ; jgen . writeStringField ( \"hydra:variable\" , annotatedParameter . getParameterName ( ) ) ; jgen . writeBooleanField ( \"hydra:required\" , annotatedParameter . isRequired ( ) ) ; jgen . writeStringField ( \"hydra:property\" , getExposedPropertyOrParamName ( annotatedParameter ) ) ; jgen . writeEndObject ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets exposed property or parameter name . [CODESPLIT] private String getExposedPropertyOrParamName ( ActionInputParameter inputParameter ) { final Expose expose = inputParameter . getAnnotation ( Expose . class ) ; String property ; if ( expose != null ) { property = expose . value ( ) ; } else { property = inputParameter . getParameterName ( ) ; } return property ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets exposed property or parameter name for properties with an appropriate setter ( = write ) method . [CODESPLIT] private String getWritableExposedPropertyOrPropertyName ( PropertyDescriptor inputParameter ) { final Method writeMethod = inputParameter . getWriteMethod ( ) ; final Expose expose = writeMethod . getAnnotation ( Expose . class ) ; String propertyName ; if ( expose != null ) { propertyName = expose . value ( ) ; } else { propertyName = inputParameter . getName ( ) ; } return propertyName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively converts object to nodes of uber data . [CODESPLIT] public static void toUberData ( AbstractUberNode objectNode , Object object ) { Set < String > filtered = FILTER_RESOURCE_SUPPORT ; if ( object == null ) { return ; } try { // TODO: move all returns to else branch of property descriptor handling if ( object instanceof Resource ) { Resource < ? > resource = ( Resource < ? > ) object ; objectNode . addLinks ( resource . getLinks ( ) ) ; toUberData ( objectNode , resource . getContent ( ) ) ; return ; } else if ( object instanceof Resources ) { Resources < ? > resources = ( Resources < ? > ) object ; // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar objectNode . addLinks ( resources . getLinks ( ) ) ; Collection < ? > content = resources . getContent ( ) ; toUberData ( objectNode , content ) ; return ; } else if ( object instanceof ResourceSupport ) { ResourceSupport resource = ( ResourceSupport ) object ; objectNode . addLinks ( resource . getLinks ( ) ) ; // wrap object attributes below to avoid endless loop } else if ( object instanceof Collection ) { Collection < ? > collection = ( Collection < ? > ) object ; for ( Object item : collection ) { // TODO name must be repeated for each collection item UberNode itemNode = new UberNode ( ) ; objectNode . addData ( itemNode ) ; toUberData ( itemNode , item ) ; } return ; } if ( object instanceof Map ) { Map < ? , ? > map = ( Map < ? , ? > ) object ; for ( Entry < ? , ? > entry : map . entrySet ( ) ) { String key = entry . getKey ( ) . toString ( ) ; Object content = entry . getValue ( ) ; Object value = getContentAsScalarValue ( content ) ; UberNode entryNode = new UberNode ( ) ; objectNode . addData ( entryNode ) ; entryNode . setName ( key ) ; if ( value != null ) { entryNode . setValue ( value ) ; } else { toUberData ( entryNode , content ) ; } } } else { Map < String , PropertyDescriptor > propertyDescriptors = PropertyUtils . getPropertyDescriptors ( object ) ; for ( PropertyDescriptor propertyDescriptor : propertyDescriptors . values ( ) ) { String name = propertyDescriptor . getName ( ) ; if ( filtered . contains ( name ) ) { continue ; } UberNode propertyNode = new UberNode ( ) ; Object content = propertyDescriptor . getReadMethod ( ) . invoke ( object ) ; if ( isEmptyCollectionOrMap ( content , propertyDescriptor . getPropertyType ( ) ) ) { continue ; } Object value = getContentAsScalarValue ( content ) ; propertyNode . setName ( name ) ; objectNode . addData ( propertyNode ) ; if ( value != null ) { // for each scalar property of a simple bean, add valuepair nodes to data propertyNode . setValue ( value ) ; } else { toUberData ( propertyNode , content ) ; } } Field [ ] fields = object . getClass ( ) . getFields ( ) ; for ( Field field : fields ) { String name = field . getName ( ) ; if ( ! propertyDescriptors . containsKey ( name ) ) { Object content = field . get ( object ) ; Class < ? > type = field . getType ( ) ; if ( isEmptyCollectionOrMap ( content , type ) ) { continue ; } UberNode propertyNode = new UberNode ( ) ; Object value = getContentAsScalarValue ( content ) ; propertyNode . setName ( name ) ; objectNode . addData ( propertyNode ) ; if ( value != null ) { // for each scalar property of a simple bean, add valuepair nodes to data propertyNode . setValue ( value ) ; } else { toUberData ( propertyNode , content ) ; } } } } } catch ( Exception ex ) { throw new RuntimeException ( \"failed to transform object \" + object , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts single link to uber node . [CODESPLIT] public static UberNode toUberLink ( String href , ActionDescriptor actionDescriptor , String ... rels ) { return toUberLink ( href , actionDescriptor , Arrays . asList ( rels ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts single link to uber node . [CODESPLIT] public static UberNode toUberLink ( String href , ActionDescriptor actionDescriptor , List < String > rels ) { Assert . notNull ( actionDescriptor , \"actionDescriptor must not be null\" ) ; UberNode uberLink = new UberNode ( ) ; uberLink . setRel ( rels ) ; PartialUriTemplateComponents partialUriTemplateComponents = new PartialUriTemplate ( href ) . expand ( Collections . < String , Object > emptyMap ( ) ) ; uberLink . setUrl ( partialUriTemplateComponents . toString ( ) ) ; uberLink . setTemplated ( partialUriTemplateComponents . hasVariables ( ) ? Boolean . TRUE : null ) ; uberLink . setModel ( getModelProperty ( href , actionDescriptor ) ) ; if ( actionDescriptor != null ) { RequestMethod requestMethod = RequestMethod . valueOf ( actionDescriptor . getHttpMethod ( ) ) ; uberLink . setAction ( UberAction . forRequestMethod ( requestMethod ) ) ; } return uberLink ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders input fields for bean properties of bean to add or update or patch . [CODESPLIT] private static void recurseBeanCreationParams ( List < UberField > uberFields , Class < ? > beanType , ActionDescriptor annotatedParameters , ActionInputParameter annotatedParameter , Object currentCallValue , String parentParamName , Set < String > knownFields ) { // TODO collection, map and object node creation are only describable by an annotation, not via type reflection if ( ObjectNode . class . isAssignableFrom ( beanType ) || Map . class . isAssignableFrom ( beanType ) || Collection . class . isAssignableFrom ( beanType ) || beanType . isArray ( ) ) { return ; // use @Input(include) to list parameter names, at least? Or mix with hdiv's form builder? } try { Constructor [ ] constructors = beanType . getConstructors ( ) ; // find default ctor Constructor constructor = PropertyUtils . findDefaultCtor ( constructors ) ; // find ctor with JsonCreator ann if ( constructor == null ) { constructor = PropertyUtils . findJsonCreator ( constructors , JsonCreator . class ) ; } Assert . notNull ( constructor , \"no default constructor or JsonCreator found for type \" + beanType . getName ( ) ) ; int parameterCount = constructor . getParameterTypes ( ) . length ; if ( parameterCount > 0 ) { Annotation [ ] [ ] annotationsOnParameters = constructor . getParameterAnnotations ( ) ; Class [ ] parameters = constructor . getParameterTypes ( ) ; int paramIndex = 0 ; for ( Annotation [ ] annotationsOnParameter : annotationsOnParameters ) { for ( Annotation annotation : annotationsOnParameter ) { if ( JsonProperty . class == annotation . annotationType ( ) ) { JsonProperty jsonProperty = ( JsonProperty ) annotation ; // TODO use required attribute of JsonProperty for required fields String paramName = jsonProperty . value ( ) ; Class parameterType = parameters [ paramIndex ] ; Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , paramName ) ; MethodParameter methodParameter = new MethodParameter ( constructor , paramIndex ) ; addUberFieldsForMethodParameter ( uberFields , methodParameter , annotatedParameter , annotatedParameters , parentParamName , paramName , parameterType , propertyValue , knownFields ) ; paramIndex ++ ; // increase for each @JsonProperty } } } Assert . isTrue ( parameters . length == paramIndex , \"not all constructor arguments of @JsonCreator \" + constructor . getName ( ) + \" are annotated with @JsonProperty\" ) ; } Set < String > knownConstructorFields = new HashSet < String > ( uberFields . size ( ) ) ; for ( UberField sirenField : uberFields ) { knownConstructorFields . add ( sirenField . getName ( ) ) ; } // TODO support Option provider by other method args? Map < String , PropertyDescriptor > propertyDescriptors = PropertyUtils . getPropertyDescriptors ( beanType ) ; // add input field for every setter for ( PropertyDescriptor propertyDescriptor : propertyDescriptors . values ( ) ) { final Method writeMethod = propertyDescriptor . getWriteMethod ( ) ; String propertyName = propertyDescriptor . getName ( ) ; if ( writeMethod == null || knownFields . contains ( parentParamName + propertyName ) ) { continue ; } final Class < ? > propertyType = propertyDescriptor . getPropertyType ( ) ; Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , propertyName ) ; MethodParameter methodParameter = new MethodParameter ( propertyDescriptor . getWriteMethod ( ) , 0 ) ; addUberFieldsForMethodParameter ( uberFields , methodParameter , annotatedParameter , annotatedParameters , parentParamName , propertyName , propertyType , propertyValue , knownConstructorFields ) ; } } catch ( Exception e ) { throw new RuntimeException ( \"Failed to write input fields for constructor\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @link ActionInputParameter } s contained in the method link . [CODESPLIT] private static Map < String , ActionInputParameter > getActionInputParameters ( Class < ? extends Annotation > annotation , Method method , Object ... arguments ) { Assert . notNull ( method , \"MethodInvocation must not be null!\" ) ; MethodParameters parameters = new MethodParameters ( method ) ; Map < String , ActionInputParameter > result = new HashMap < String , ActionInputParameter > ( ) ; for ( MethodParameter parameter : parameters . getParametersWith ( annotation ) ) { final int parameterIndex = parameter . getParameterIndex ( ) ; final Object argument ; if ( parameterIndex < arguments . length ) { argument = arguments [ parameterIndex ] ; } else { argument = null ; } ActionInputParameter inputParameter = new SpringActionInputParameter ( parameter , argument ) ; result . put ( inputParameter . getParameterName ( ) , inputParameter ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO move to PropertyUtil and remove current method for propertyDescriptors cache search results [CODESPLIT] public static Object getPropertyOrFieldValue ( Object currentCallValue , String propertyOrFieldName ) { if ( currentCallValue == null ) { return null ; } Object propertyValue = getBeanPropertyValue ( currentCallValue , propertyOrFieldName ) ; if ( propertyValue == null ) { propertyValue = getFieldValue ( currentCallValue , propertyOrFieldName ) ; } return propertyValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets vocab for given bean . [CODESPLIT] public String getVocab ( MixinSource mixinSource , Object bean , Class < ? > mixInClass ) { if ( proxyUnwrapper != null ) { bean = proxyUnwrapper . unwrapProxy ( bean ) ; } // determine vocab in context String classVocab = bean == null ? null : vocabFromClassOrPackage ( bean . getClass ( ) ) ; final Vocab mixinVocab = findAnnotation ( mixInClass , Vocab . class ) ; Object nestedContextProviderFromMixin = getNestedContextProviderFromMixin ( mixinSource , bean , mixInClass ) ; String contextProviderVocab = null ; if ( nestedContextProviderFromMixin != null ) { contextProviderVocab = getVocab ( mixinSource , nestedContextProviderFromMixin , null ) ; } String vocab ; if ( mixinVocab != null ) { vocab = mixinVocab . value ( ) ; // wins over class } else if ( classVocab != null ) { vocab = classVocab ; // wins over context provider } else if ( contextProviderVocab != null ) { vocab = contextProviderVocab ; // wins over last resort } else { vocab = HTTP_SCHEMA_ORG ; } return vocab ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets explicitly defined terms e . g . on package class or mixin . [CODESPLIT] private Map < String , Object > getAnnotatedTerms ( AnnotatedElement annotatedElement , String name ) { final Terms annotatedTerms = findAnnotation ( annotatedElement , Terms . class ) ; final Term annotatedTerm = findAnnotation ( annotatedElement , Term . class ) ; if ( annotatedTerms != null && annotatedTerm != null ) { throw new IllegalStateException ( \"found both @Terms and @Term in \" + name + \", use either one or the other\" ) ; } Map < String , Object > annotatedTermsMap = new LinkedHashMap < String , Object > ( ) ; if ( annotatedTerms != null ) { final Term [ ] terms = annotatedTerms . value ( ) ; for ( Term term : terms ) { collectTerms ( name , annotatedTermsMap , term ) ; } } else if ( annotatedTerm != null ) { // only one term collectTerms ( name , annotatedTermsMap , annotatedTerm ) ; } return annotatedTermsMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] @ RequestMapping ( method = RequestMethod . GET ) @ ResponseBody public ResponseEntity < Resources < Event > > findEvents ( @ RequestParam ( required = false ) String name ) { List < Event > events = assembler . toResources ( eventBackend . getEvents ( ) ) ; List < Event > matches = new ArrayList < Event > ( ) ; for ( Event event : events ) { if ( name == null || event . workPerformed . getContent ( ) . name . equals ( name ) ) { addAffordances ( event ) ; matches . add ( event ) ; } } Resources < Event > eventResources = new Resources < Event > ( matches ) ; eventResources . add ( AffordanceBuilder . linkTo ( AffordanceBuilder . methodOn ( EventController . class ) . addEvent ( new Event ( null , new CreativeWork ( null ) , null , EventStatusType . EVENT_SCHEDULED ) ) ) . withSelfRel ( ) ) ; eventResources . add ( AffordanceBuilder . linkTo ( AffordanceBuilder . methodOn ( EventController . class ) . findEvents ( null ) ) . withRel ( \"hydra:search\" ) ) ; return new ResponseEntity < Resources < Event > > ( eventResources , HttpStatus . OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query consisting of expanded parameters and unexpanded parameters . [CODESPLIT] public String getQuery ( ) { StringBuilder query = new StringBuilder ( ) ; if ( queryTail . length ( ) > 0 ) { if ( queryHead . length ( ) == 0 ) { query . append ( \"{?\" ) . append ( queryTail ) . append ( \"}\" ) ; } else if ( queryHead . length ( ) > 0 ) { query . append ( queryHead ) . append ( \"{&\" ) . append ( queryTail ) . append ( \"}\" ) ; } } else { query . append ( queryHead ) ; } return query . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends form and squashes non - GET or POST to POST . If required adds _method field for handling by an appropriate filter such as Spring s HiddenHttpMethodFilter . [CODESPLIT] private void appendForm ( Affordance affordance , ActionDescriptor actionDescriptor ) throws IOException { String formName = actionDescriptor . getActionName ( ) ; RequestMethod httpMethod = RequestMethod . valueOf ( actionDescriptor . getHttpMethod ( ) ) ; // Link's expand method removes non-required variables from URL String actionUrl = affordance . expand ( ) . getHref ( ) ; beginForm ( OptionalAttributes . attr ( \"action\" , actionUrl ) . and ( \"method\" , getHtmlConformingHttpMethod ( httpMethod ) ) . and ( \"name\" , formName ) ) ; write ( \"<h4>\" ) ; write ( \"Form \" + formName ) ; write ( \"</h4>\" ) ; writeHiddenHttpMethodField ( httpMethod ) ; // build the form if ( actionDescriptor . hasRequestBody ( ) ) { // parameter bean ActionInputParameter requestBody = actionDescriptor . getRequestBody ( ) ; Class < ? > parameterType = requestBody . getParameterType ( ) ; recurseBeanProperties ( parameterType , actionDescriptor , requestBody , requestBody . getValue ( ) , \"\" ) ; } else { // plain parameter list Collection < String > requestParams = actionDescriptor . getRequestParamNames ( ) ; for ( String requestParamName : requestParams ) { ActionInputParameter actionInputParameter = actionDescriptor . getActionInputParameter ( requestParamName ) ; Object [ ] possibleValues = actionInputParameter . getPossibleValues ( actionDescriptor ) ; // TODO duplication with appendInputOrSelect if ( possibleValues . length > 0 ) { if ( actionInputParameter . isArrayOrCollection ( ) ) { appendSelectMulti ( requestParamName , possibleValues , actionInputParameter ) ; } else { appendSelectOne ( requestParamName , possibleValues , actionInputParameter ) ; } } else { if ( actionInputParameter . isArrayOrCollection ( ) ) { // have as many inputs as there are call values, list of 5 nulls gives you five input fields // TODO support for free list input instead, code on demand? Object [ ] callValues = actionInputParameter . getValues ( ) ; int items = callValues . length ; for ( int i = 0 ; i < items ; i ++ ) { Object value ; if ( i < callValues . length ) { value = callValues [ i ] ; } else { value = null ; } appendInput ( requestParamName , actionInputParameter , value , actionInputParameter . isReadOnly ( requestParamName ) ) ; // not readonly } } else { String callValueFormatted = actionInputParameter . getValueFormatted ( ) ; appendInput ( requestParamName , actionInputParameter , callValueFormatted , actionInputParameter . isReadOnly ( requestParamName ) ) ; // not readonly } } } } inputButton ( Type . SUBMIT , capitalize ( httpMethod . name ( ) . toLowerCase ( ) ) ) ; endForm ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Classic submit or reset button . [CODESPLIT] private void inputButton ( Type type , String value ) throws IOException { write ( \"<input type=\\\"\" ) ; write ( type . toString ( ) ) ; write ( \"\\\" \" ) ; write ( \"value\" ) ; write ( \"=\" ) ; quote ( ) ; write ( value ) ; quote ( ) ; write ( \"/>\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders input fields for bean properties of bean to add or update or patch . [CODESPLIT] private void recurseBeanProperties ( Class < ? > beanType , ActionDescriptor actionDescriptor , ActionInputParameter actionInputParameter , Object currentCallValue , String parentParamName ) throws IOException { // TODO support Option provider by other method args? final BeanInfo beanInfo = getBeanInfo ( beanType ) ; final PropertyDescriptor [ ] propertyDescriptors = beanInfo . getPropertyDescriptors ( ) ; // TODO collection and map // TODO: do not add two inputs for setter and ctor // TODO almost duplicate of HtmlResourceMessageConverter.recursivelyCreateObject if ( RequestMethod . POST == RequestMethod . valueOf ( actionDescriptor . getHttpMethod ( ) ) ) { try { Constructor [ ] constructors = beanType . getConstructors ( ) ; // find default ctor Constructor constructor = PropertyUtils . findDefaultCtor ( constructors ) ; // find ctor with JsonCreator ann if ( constructor == null ) { constructor = PropertyUtils . findJsonCreator ( constructors , JsonCreator . class ) ; } Assert . notNull ( constructor , \"no default constructor or JsonCreator found for type \" + beanType . getName ( ) ) ; int parameterCount = constructor . getParameterTypes ( ) . length ; if ( parameterCount > 0 ) { Annotation [ ] [ ] annotationsOnParameters = constructor . getParameterAnnotations ( ) ; Class [ ] parameters = constructor . getParameterTypes ( ) ; int paramIndex = 0 ; for ( Annotation [ ] annotationsOnParameter : annotationsOnParameters ) { for ( Annotation annotation : annotationsOnParameter ) { if ( JsonProperty . class == annotation . annotationType ( ) ) { JsonProperty jsonProperty = ( JsonProperty ) annotation ; // TODO use required attribute of JsonProperty String paramName = jsonProperty . value ( ) ; Class parameterType = parameters [ paramIndex ] ; // TODO duplicate below for PropertyDescriptors and in appendForm if ( DataType . isSingleValueType ( parameterType ) ) { if ( actionInputParameter . isIncluded ( paramName ) ) { Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , paramName ) ; ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter ( new MethodParameter ( constructor , paramIndex ) , propertyValue ) ; final Object [ ] possibleValues = actionInputParameter . getPossibleValues ( constructor , paramIndex , actionDescriptor ) ; appendInputOrSelect ( actionInputParameter , parentParamName + paramName , constructorParamInputParameter , possibleValues ) ; } } else if ( DataType . isArrayOrCollection ( parameterType ) ) { Object [ ] callValues = actionInputParameter . getValues ( ) ; int items = callValues . length ; for ( int i = 0 ; i < items ; i ++ ) { Object value ; if ( i < callValues . length ) { value = callValues [ i ] ; } else { value = null ; } recurseBeanProperties ( actionInputParameter . getParameterType ( ) , actionDescriptor , actionInputParameter , value , parentParamName ) ; } } else { beginDiv ( ) ; write ( paramName + \":\" ) ; Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , paramName ) ; recurseBeanProperties ( parameterType , actionDescriptor , actionInputParameter , propertyValue , paramName + \".\" ) ; endDiv ( ) ; } paramIndex ++ ; // increase for each @JsonProperty } } } Assert . isTrue ( parameters . length == paramIndex , \"not all constructor arguments of @JsonCreator \" + constructor . getName ( ) + \" are annotated with @JsonProperty\" ) ; } } catch ( Exception e ) { throw new RuntimeException ( \"Failed to write input fields for constructor\" , e ) ; } } else { // non-POST // TODO non-writable properties and public fields: make sure the inputs are part of a form // write input field for every setter for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { final Method writeMethod = propertyDescriptor . getWriteMethod ( ) ; if ( writeMethod == null ) { continue ; } final Class < ? > propertyType = propertyDescriptor . getPropertyType ( ) ; String propertyName = propertyDescriptor . getName ( ) ; if ( DataType . isSingleValueType ( propertyType ) ) { final Property property = new Property ( beanType , propertyDescriptor . getReadMethod ( ) , propertyDescriptor . getWriteMethod ( ) , propertyDescriptor . getName ( ) ) ; Object propertyValue = PropertyUtils . getPropertyOrFieldValue ( currentCallValue , propertyName ) ; MethodParameter methodParameter = new MethodParameter ( propertyDescriptor . getWriteMethod ( ) , 0 ) ; ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter ( methodParameter , propertyValue ) ; final Object [ ] possibleValues = actionInputParameter . getPossibleValues ( propertyDescriptor . getWriteMethod ( ) , 0 , actionDescriptor ) ; appendInputOrSelect ( actionInputParameter , propertyName , propertySetterInputParameter , possibleValues ) ; } else if ( actionInputParameter . isArrayOrCollection ( ) ) { Object [ ] callValues = actionInputParameter . getValues ( ) ; int items = callValues . length ; for ( int i = 0 ; i < items ; i ++ ) { Object value ; if ( i < callValues . length ) { value = callValues [ i ] ; } else { value = null ; } recurseBeanProperties ( actionInputParameter . getParameterType ( ) , actionDescriptor , actionInputParameter , value , parentParamName ) ; } } else { beginDiv ( ) ; write ( propertyName + \":\" ) ; Object propertyValue = PropertyUtils . getPropertyValue ( currentCallValue , propertyDescriptor ) ; recurseBeanProperties ( propertyType , actionDescriptor , actionInputParameter , propertyValue , parentParamName ) ; endDiv ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends simple input or select depending on availability of possible values . [CODESPLIT] private void appendInputOrSelect ( ActionInputParameter parentInputParameter , String paramName , ActionInputParameter childInputParameter , Object [ ] possibleValues ) throws IOException { if ( possibleValues . length > 0 ) { if ( childInputParameter . isArrayOrCollection ( ) ) { // TODO multiple formatted callvalues appendSelectMulti ( paramName , possibleValues , childInputParameter ) ; } else { appendSelectOne ( paramName , possibleValues , childInputParameter ) ; } } else { appendInput ( paramName , childInputParameter , childInputParameter . getValue ( ) , parentInputParameter . isReadOnly ( paramName ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @link AffordanceBuilder } with a base of the mapping annotated to the given controller class . The additional parameters are used to fill up potentially available path variables in the class scope request mapping . [CODESPLIT] public static AffordanceBuilder linkTo ( Class < ? > controller , Object ... parameters ) { return FACTORY . linkTo ( controller , parameters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @link AffordanceBuilder } with a base of the mapping annotated to the given controller class . The additional parameters are used to fill up potentially available path variables in the class scop request mapping . [CODESPLIT] public static AffordanceBuilder linkTo ( Class < ? > controller , Map < String , ? > parameters ) { return FACTORY . linkTo ( controller , parameters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds affordance with one or multiple rels which must have been defined previously using { @link #rel ( String ) } or { @link #reverseRel ( String String ) } . <p > The motivation for multiple rels is this statement in the web linking rfc - 5988 : &quot ; Note that link - values can convey multiple links between the same target and context IRIs ; for example : < / p > <pre > Link : &lt ; http : // example . org / &gt ; rel = start http : // example . net / relation / other < / pre > Here the link to http : // example . org / has the registered relation type start and the extension relation type http : // example . net / relation / other . &quot ; [CODESPLIT] public Affordance build ( ) { Assert . state ( ! ( rels . isEmpty ( ) && reverseRels . isEmpty ( ) ) , \"no rels or reverse rels found, call rel() or rev() before building the affordance\" ) ; final Affordance affordance ; affordance = new Affordance ( new PartialUriTemplate ( this . toString ( ) ) , actionDescriptors , rels . toArray ( new String [ rels . size ( ) ] ) ) ; for ( Map . Entry < String , List < String > > linkParamEntry : linkParams . entrySet ( ) ) { final List < String > values = linkParamEntry . getValue ( ) ; for ( String value : values ) { affordance . addLinkParam ( linkParamEntry . getKey ( ) , value ) ; } } for ( String reverseRel : reverseRels ) { affordance . addRev ( reverseRel ) ; } affordance . setCollectionHolder ( collectionHolder ) ; return affordance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows to define one or more reverse link relations ( a rev in terms of rfc - 5988 ) where the resource that has the affordance will be considered the object in a subject - predicate - object statement . <p > E . g . if you had a rel <code > ex : parent< / code > which connects a child to its father you could also use ex : parent on the father to point to the child by reverting the direction of ex : parent . This is mainly useful when you have no other way to express in your context that the direction of a relationship is inverted . < / p > [CODESPLIT] public AffordanceBuilder reverseRel ( String rev , String revertedRel ) { this . rels . add ( revertedRel ) ; this . reverseRels . add ( rev ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows to define one or more reverse link relations ( a rev in terms of rfc - 5988 ) to collections in cases where the resource that has the affordance is not the object in a subject - predicate - object statement about each collection item . See { @link #rel ( TypedResource String ) } for explanation . [CODESPLIT] public AffordanceBuilder reverseRel ( String rev , String revertedRel , TypedResource object ) { this . collectionHolder = object ; this . rels . add ( 0 , revertedRel ) ; this . reverseRels . add ( rev ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows to define one or more link relations for affordances that point to collections in cases where the resource that has the affordance is not the subject in a subject - predicate - object statement about each collection item . E . g . a product might have a loose relationship to ordered items where it can be POSTed but the ordered items do not belong to the product but to an order . You can express that by saying : <pre > TypedResource order = new TypedResource ( http : // schema . org / Order ) ; // holds the ordered items Resource&lt ; Product&gt ; product = new Resource&lt ; &gt ; () ; // has a loose relationship to ordered items product . add ( linkTo ( methodOn ( OrderController . class ) . postOrderedItem () . rel ( order orderedItem )) ; // order has ordered items not product has ordered items < / pre > If the order doesn t exist yet it cannot be identified . In that case you may pass null to express that [CODESPLIT] public AffordanceBuilder rel ( TypedResource subject , String rel ) { this . collectionHolder = subject ; this . rels . add ( rel ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows to define link header params ( not UriTemplate variables ) . [CODESPLIT] public AffordanceBuilder withLinkParam ( String name , String value ) { this . linkParams . add ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link UriComponentsBuilder } obtained from the current servlet mapping with scheme tweaked in case the request contains an { @code X - Forwarded - Ssl } header which is not ( yet ) supported by the underlying { @link UriComponentsBuilder } . If no { @link RequestContextHolder } exists ( you re outside a Spring Web call ) fall back to relative URIs . [CODESPLIT] static UriComponentsBuilder getBuilder ( ) { if ( RequestContextHolder . getRequestAttributes ( ) == null ) { return UriComponentsBuilder . fromPath ( \"/\" ) ; } HttpServletRequest request = getCurrentRequest ( ) ; UriComponentsBuilder builder = ServletUriComponentsBuilder . fromServletMapping ( request ) ; // special case handling for X-Forwarded-Ssl: // apply it, but only if X-Forwarded-Proto is unset. String forwardedSsl = request . getHeader ( \"X-Forwarded-Ssl\" ) ; ForwardedHeader forwarded = ForwardedHeader . of ( request . getHeader ( ForwardedHeader . NAME ) ) ; String proto = hasText ( forwarded . getProto ( ) ) ? forwarded . getProto ( ) : request . getHeader ( \"X-Forwarded-Proto\" ) ; if ( ! hasText ( proto ) && hasText ( forwardedSsl ) && forwardedSsl . equalsIgnoreCase ( \"on\" ) ) { builder . scheme ( \"https\" ) ; } return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy of { @link ServletUriComponentsBuilder#getCurrentRequest () } until SPR - 10110 gets fixed . [CODESPLIT] private static HttpServletRequest getCurrentRequest ( ) { RequestAttributes requestAttributes = RequestContextHolder . getRequestAttributes ( ) ; Assert . state ( requestAttributes != null , \"Could not find current request via RequestContextHolder\" ) ; Assert . isInstanceOf ( ServletRequestAttributes . class , requestAttributes ) ; HttpServletRequest servletRequest = ( ( ServletRequestAttributes ) requestAttributes ) . getRequest ( ) ; Assert . state ( servletRequest != null , \"Could not find current HttpServletRequest\" ) ; return servletRequest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds actionDescriptors of the given AffordanceBuilder to this affordanceBuilder . [CODESPLIT] public AffordanceBuilder and ( AffordanceBuilder affordanceBuilder ) { for ( ActionDescriptor actionDescriptor : affordanceBuilder . actionDescriptors ) { this . actionDescriptors . add ( actionDescriptor ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the template as uri components without variable expansion . [CODESPLIT] public PartialUriTemplateComponents asComponents ( ) { return getUriTemplateComponents ( Collections . < String , Object > emptyMap ( ) , Collections . < String > emptyList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands the template using given parameters [CODESPLIT] public PartialUriTemplateComponents expand ( Object ... parameters ) { List < String > variableNames = getVariableNames ( ) ; Map < String , Object > parameterMap = new LinkedHashMap < String , Object > ( ) ; int i = 0 ; for ( String variableName : variableNames ) { if ( i < parameters . length ) { parameterMap . put ( variableName , parameters [ i ++ ] ) ; } else { break ; } } return getUriTemplateComponents ( parameterMap , Collections . < String > emptyList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands the template using given parameters [CODESPLIT] public PartialUriTemplateComponents expand ( Map < String , ? > parameters ) { return getUriTemplateComponents ( parameters , Collections . < String > emptyList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies parameters to template variables . [CODESPLIT] private PartialUriTemplateComponents getUriTemplateComponents ( Map < String , ? > parameters , List < String > requiredArgs ) { Assert . notNull ( parameters , \"Parameters must not be null!\" ) ; final StringBuilder baseUrl = new StringBuilder ( urlComponents . get ( 0 ) ) ; final StringBuilder queryHead = new StringBuilder ( ) ; final StringBuilder queryTail = new StringBuilder ( ) ; final StringBuilder fragmentIdentifier = new StringBuilder ( ) ; for ( int i = 1 ; i < urlComponents . size ( ) ; i ++ ) { final String part = urlComponents . get ( i ) ; final List < Integer > variablesInPart = variableIndices . get ( i ) ; if ( variablesInPart . isEmpty ( ) ) { if ( part . startsWith ( \"?\" ) || part . startsWith ( \"&\" ) ) { queryHead . append ( part ) ; } else if ( part . startsWith ( \"#\" ) ) { fragmentIdentifier . append ( part ) ; } else { baseUrl . append ( part ) ; } } else { for ( Integer variableInPart : variablesInPart ) { final TemplateVariable variable = variables . get ( variableInPart ) ; final Object value = parameters . get ( variable . getName ( ) ) ; if ( value == null ) { switch ( variable . getType ( ) ) { case REQUEST_PARAM : case REQUEST_PARAM_CONTINUED : if ( requiredArgs . isEmpty ( ) || requiredArgs . contains ( variable . getName ( ) ) ) { // query vars without value always go last (query tail) if ( queryTail . length ( ) > 0 ) { queryTail . append ( ' ' ) ; } queryTail . append ( variable . getName ( ) ) ; } break ; case FRAGMENT : fragmentIdentifier . append ( variable . toString ( ) ) ; break ; case PATH_VARIABLE : if ( queryHead . length ( ) != 0 ) { // level 1 variable in query queryHead . append ( variable . toString ( ) ) ; } else { baseUrl . append ( variable . toString ( ) ) ; } break ; case SEGMENT : baseUrl . append ( variable . toString ( ) ) ; } } else { switch ( variable . getType ( ) ) { case REQUEST_PARAM : case REQUEST_PARAM_CONTINUED : if ( queryHead . length ( ) == 0 ) { queryHead . append ( ' ' ) ; } else { queryHead . append ( ' ' ) ; } queryHead . append ( variable . getName ( ) ) . append ( ' ' ) . append ( urlEncode ( value . toString ( ) ) ) ; break ; case SEGMENT : baseUrl . append ( ' ' ) ; // fall through case PATH_VARIABLE : if ( queryHead . length ( ) != 0 ) { // level 1 variable in query queryHead . append ( urlEncode ( value . toString ( ) ) ) ; } else { baseUrl . append ( urlEncode ( value . toString ( ) ) ) ; } break ; case FRAGMENT : fragmentIdentifier . append ( ' ' ) ; fragmentIdentifier . append ( urlEncode ( value . toString ( ) ) ) ; break ; } } } } } return new PartialUriTemplateComponents ( baseUrl . toString ( ) , queryHead . toString ( ) , queryTail . toString ( ) , fragmentIdentifier . toString ( ) , variableNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips all variables which are not required by any of the given action descriptors . If no action descriptors are given nothing will be stripped . [CODESPLIT] public PartialUriTemplateComponents stripOptionalVariables ( List < ActionDescriptor > actionDescriptors ) { return getUriTemplateComponents ( Collections . < String , Object > emptyMap ( ) , getRequiredArgNames ( actionDescriptors ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets first child of this uber node having the given name attribute . [CODESPLIT] public UberNode getFirstByName ( String name ) { // TODO consider less naive impl UberNode ret = null ; for ( UberNode node : data ) { if ( name . equals ( node . getName ( ) ) ) { ret = node ; break ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets first child of this uber node having the given rel attribute . [CODESPLIT] public UberNode getFirstByRel ( String rel ) { // TODO consider less naive impl for ( UberNode node : data ) { List < String > myRels = node . getRel ( ) ; if ( myRels != null ) { for ( String myRel : myRels ) { if ( rel . equals ( myRel ) ) { return node ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows iterating over children of this uber node which have a data attribute . [CODESPLIT] @ Override public Iterator < UberNode > iterator ( ) { return new Iterator < UberNode > ( ) { int index = 0 ; @ Override public void remove ( ) { throw new UnsupportedOperationException ( \"removing from uber node is not supported\" ) ; } @ Override public UberNode next ( ) { index = findNextChildWithData ( ) ; return data . get ( index ++ ) ; } @ Override public boolean hasNext ( ) { return findNextChildWithData ( ) != - 1 ; } private int findNextChildWithData ( ) { for ( int i = index ; i < data . size ( ) ; i ++ ) { if ( ! data . get ( i ) . getData ( ) . isEmpty ( ) ) { return i ; } } return - 1 ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Works around some type inference limitations of Java 8 . [CODESPLIT] public static < E > MutableHashSet < E > emptyMutable ( Equator < E > eq ) { return empty ( eq ) . mutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentHashSet of the values . The vararg version of this method is { @link org . organicdesign . fp . StaticImports#set ( Object ... ) } If the input contains duplicate elements later values overwrite earlier ones . [CODESPLIT] public static < E > PersistentHashSet < E > of ( Iterable < E > elements ) { PersistentHashSet < E > empty = empty ( ) ; MutableSet < E > ret = empty . mutable ( ) ; for ( E e : elements ) { ret . put ( e ) ; } return ( PersistentHashSet < E > ) ret . immutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Works around some type inference limitations of Java 8 . [CODESPLIT] public static < K , V > MutableHashMap < K , V > emptyMutable ( ) { return PersistentHashMap . < K , V > empty ( ) . mutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Works around some type inference limitations of Java 8 . [CODESPLIT] public static < K , V > MutableHashMap < K , V > emptyMutable ( Equator < K > e ) { return PersistentHashMap . < K , V > empty ( e ) . mutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentHashMap of the given keys and their paired values skipping any null Entries . [CODESPLIT] @ SuppressWarnings ( \"WeakerAccess\" ) public static < K , V > PersistentHashMap < K , V > ofEq ( Equator < K > eq , Iterable < Map . Entry < K , V > > es ) { if ( es == null ) { return empty ( eq ) ; } MutableHashMap < K , V > map = emptyMutable ( eq ) ; for ( Map . Entry < K , V > entry : es ) { if ( entry != null ) { map . assoc ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return map . immutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentHashMap of the given keys and their paired values . There is also a varargs version of this method : { @link org . organicdesign . fp . StaticImports#map ( Map . Entry ... ) } . Use the { @link org . organicdesign . fp . StaticImports#tup ( Object Object ) } method to define key / value pairs briefly and easily . [CODESPLIT] public static < K , V > PersistentHashMap < K , V > of ( Iterable < Map . Entry < K , V > > kvPairs ) { if ( kvPairs == null ) { return empty ( ) ; } PersistentHashMap < K , V > m = empty ( ) ; MutableHashMap < K , V > map = m . mutable ( ) ; for ( Map . Entry < K , V > entry : kvPairs ) { if ( entry != null ) { map . assoc ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return map . immutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public static void main ( String [] args ) { try { ArrayList words = new ArrayList () ; Scanner s = new Scanner ( new File ( args [ 0 ] )) ; s . useDelimiter ( Pattern . compile ( \\\\ W )) ; while ( s . hasNext () ) { String word = s . next () ; words . add ( word ) ; } System . out . println ( words : + words . size () ) ; ImMap map = PersistentHashMap . EMPTY ; ImMap map = new PersistentHashMap () ; Map ht = new Hashtable () ; Map ht = new HashMap () ; Random rand ; [CODESPLIT] private static < K , V > INode < K , V > [ ] cloneAndSet ( INode < K , V > [ ] array , int i , INode < K , V > a ) { INode < K , V > [ ] clone = array . clone ( ) ; clone [ i ] = a ; return clone ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static String ordinal ( final int origI ) { final int i = ( origI < 0 ) ? - origI : origI ; final int modTen = i % 10 ; if ( ( modTen < 4 ) && ( modTen > 0 ) ) { int modHundred = i % 100 ; if ( ( modHundred < 21 ) && ( modHundred > 3 ) ) { return Integer . toString ( origI ) + \"th\" ; } switch ( modTen ) { case 1 : return Integer . toString ( origI ) + \"st\" ; case 2 : return Integer . toString ( origI ) + \"nd\" ; case 3 : return Integer . toString ( origI ) + \"rd\" ; } } return Integer . toString ( origI ) + \"th\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeMap of the given comparable keys and their paired values skipping any null Entries . [CODESPLIT] public static < K extends Comparable < K > , V > PersistentTreeMap < K , V > of ( Iterable < Map . Entry < K , V > > es ) { if ( es == null ) { return empty ( ) ; } PersistentTreeMap < K , V > map = new PersistentTreeMap <> ( Equator . defaultComparator ( ) , null , 0 ) ; for ( Map . Entry < K , V > entry : es ) { if ( entry != null ) { map = map . assoc ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeMap of the specified comparator and the given key / value pairs . [CODESPLIT] public static < K , V > PersistentTreeMap < K , V > ofComp ( Comparator < ? super K > comp , Iterable < Map . Entry < K , V > > kvPairs ) { if ( kvPairs == null ) { return new PersistentTreeMap <> ( comp , null , 0 ) ; } PersistentTreeMap < K , V > map = new PersistentTreeMap <> ( comp , null , 0 ) ; for ( Map . Entry < K , V > entry : kvPairs ) { if ( entry != null ) { map = map . assoc ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Be extremely careful with this because it uses the default comparator which only works for items that implement Comparable ( have a natural ordering ) . An attempt to use it with other items will blow up at runtime . Either a withComparator () method will be added or this will be removed . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < K extends Comparable < K > , V > PersistentTreeMap < K , V > empty ( ) { return ( PersistentTreeMap < K , V > ) EMPTY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new empty PersistentTreeMap that will use the specified comparator . [CODESPLIT] public static < K , V > PersistentTreeMap < K , V > empty ( Comparator < ? super K > c ) { return new PersistentTreeMap <> ( c , null , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a view of the mappings contained in this map . The set should actually contain UnmodMap . UnEntry items but that return signature is illegal in Java so you ll just have to remember . [CODESPLIT] @ Override public ImSortedSet < Entry < K , V > > entrySet ( ) { // This is the pretty way to do it. return this . fold ( PersistentTreeSet . ofComp ( new KeyComparator <> ( comp ) ) , PersistentTreeSet :: put ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public ImSortedMap < K , V > subMap ( K fromKey , K toKey ) { int diff = comp . compare ( fromKey , toKey ) ; if ( diff > 0 ) { throw new IllegalArgumentException ( \"fromKey is greater than toKey\" ) ; } UnEntry < K , V > last = last ( ) ; K lastKey = last . getKey ( ) ; int compFromKeyLastKey = comp . compare ( fromKey , lastKey ) ; // If no intersect, return empty. We aren't checking the toKey vs. the firstKey() because // that's a single pass through the iterator loop which is probably as cheap as checking // here. if ( ( diff == 0 ) || ( compFromKeyLastKey > 0 ) ) { return new PersistentTreeMap <> ( comp , null , 0 ) ; } // If map is entirely contained, just return it. if ( ( comp . compare ( fromKey , firstKey ( ) ) <= 0 ) && ( comp . compare ( toKey , lastKey ) > 0 ) ) { return this ; } // Don't iterate through entire map for only the last item. if ( compFromKeyLastKey == 0 ) { return ofComp ( comp , Collections . singletonList ( last ) ) ; } ImSortedMap < K , V > ret = new PersistentTreeMap <> ( comp , null , 0 ) ; UnmodIterator < UnEntry < K , V > > iter = this . iterator ( ) ; while ( iter . hasNext ( ) ) { UnEntry < K , V > next = iter . next ( ) ; K key = next . getKey ( ) ; if ( comp . compare ( toKey , key ) <= 0 ) { break ; } if ( comp . compare ( fromKey , key ) > 0 ) { continue ; } ret = ret . assoc ( key , next . getValue ( ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Option < UnEntry < K , V > > head ( ) { Node < K , V > t = tree ; if ( t != null ) { while ( t . left ( ) != null ) { t = t . left ( ) ; } } return Option . some ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the comparator used to order the keys in this map or null if it uses Fn2 . DEFAULT_COMPARATOR ( for compatibility with java . util . SortedMap ) . [CODESPLIT] @ Override public Comparator < ? super K > comparator ( ) { return ( comp == Equator . Comp . DEFAULT ) ? null : comp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public PersistentTreeMap < K , V > assoc ( K key , V val ) { Box < Node < K , V > > found = new Box <> ( null ) ; Node < K , V > t = add ( tree , key , val , found ) ; //null == already contains key if ( t == null ) { Node < K , V > foundNode = found . val ; //note only get same collection on identity of val, not equals() if ( foundNode . getValue ( ) == val ) { return this ; } return new PersistentTreeMap <> ( comp , replace ( tree , key , val ) , size ) ; } return new PersistentTreeMap <> ( comp , t . blacken ( ) , size + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public PersistentTreeMap < K , V > without ( K key ) { Box < Node < K , V > > found = new Box <> ( null ) ; Node < K , V > t = remove ( tree , key , found ) ; if ( t == null ) { //null == doesn't contain key if ( found . val == null ) { return this ; } //empty return new PersistentTreeMap <> ( comp , null , 0 ) ; } return new PersistentTreeMap <> ( comp , t . blacken ( ) , size - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last key in this map or throws a NoSuchElementException if the map is empty . [CODESPLIT] @ Override public K lastKey ( ) { UnEntry < K , V > max = last ( ) ; if ( max == null ) { throw new NoSuchElementException ( \"this map is empty\" ) ; } return max . getKey ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last key / value pair in this map or null if the map is empty . [CODESPLIT] public UnEntry < K , V > last ( ) { Node < K , V > t = tree ; if ( t != null ) { while ( t . right ( ) != null ) t = t . right ( ) ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Option of the key / value pair matching the given key or Option . none () if the key is not found . [CODESPLIT] @ Override public Option < UnmodMap . UnEntry < K , V > > entry ( K key ) { Node < K , V > t = tree ; while ( t != null ) { int c = comp . compare ( key , t . getKey ( ) ) ; if ( c == 0 ) return Option . some ( t ) ; else if ( c < 0 ) t = t . left ( ) ; else t = t . right ( ) ; } return Option . none ( ) ; // t; // t is always null }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private Node < K , V > add ( Node < K , V > t , K key , V val , Box < Node < K , V > > found ) { if ( t == null ) { //            if (val == null) //                return new Red<>(key); return new Red <> ( key , val ) ; } int c = comp . compare ( key , t . getKey ( ) ) ; if ( c == 0 ) { found . val = t ; return null ; } Node < K , V > ins = add ( c < 0 ? t . left ( ) : t . right ( ) , key , val , found ) ; if ( ins == null ) //found below return null ; if ( c < 0 ) return t . addLeft ( ins ) ; return t . addRight ( ins ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Node<K V > concat ( Node<K1 V1 > left Node<K2 V2 > right ) { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static < K , V > Node < K , V > append ( Node < ? extends K , ? extends V > left , Node < ? extends K , ? extends V > right ) { if ( left == null ) return ( Node < K , V > ) right ; else if ( right == null ) return ( Node < K , V > ) left ; else if ( left instanceof PersistentTreeMap . Red ) { if ( right instanceof PersistentTreeMap . Red ) { Node < K , V > app = append ( left . right ( ) , right . left ( ) ) ; if ( app instanceof PersistentTreeMap . Red ) return red ( app . getKey ( ) , app . getValue ( ) , red ( left . getKey ( ) , left . getValue ( ) , left . left ( ) , app . left ( ) ) , red ( right . getKey ( ) , right . getValue ( ) , app . right ( ) , right . right ( ) ) ) ; else return red ( left . getKey ( ) , left . getValue ( ) , left . left ( ) , red ( right . getKey ( ) , right . getValue ( ) , app , right . right ( ) ) ) ; } else return red ( left . getKey ( ) , left . getValue ( ) , left . left ( ) , append ( left . right ( ) , right ) ) ; } else if ( right instanceof PersistentTreeMap . Red ) return red ( right . getKey ( ) , right . getValue ( ) , append ( left , right . left ( ) ) , right . right ( ) ) ; else //black/black { Node < K , V > app = append ( left . right ( ) , right . left ( ) ) ; if ( app instanceof PersistentTreeMap . Red ) return red ( app . getKey ( ) , app . getValue ( ) , black ( left . getKey ( ) , left . getValue ( ) , left . left ( ) , app . left ( ) ) , black ( right . getKey ( ) , right . getValue ( ) , app . right ( ) , right . right ( ) ) ) ; else return balanceLeftDel ( left . getKey ( ) , left . getValue ( ) , left . left ( ) , black ( right . getKey ( ) , right . getValue ( ) , app , right . right ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static factory methods [CODESPLIT] public static < T > Xform < T > of ( Iterable < ? extends T > list ) { if ( list == null ) { return empty ( ) ; } return new SourceProviderIterableDesc <> ( list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "than lazily evaluated and cached linked - list Sequence model . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static < H > H _fold ( Iterable source , Operation [ ] ops , int opIdx , H ident , Fn2 reducer ) { Object ret = ident ; // This is a label - the first one I have used in Java in years, or maybe ever. // I'm assuming this is fast, but will have to test to confirm it. sourceLoop : for ( Object o : source ) { for ( int j = opIdx ; j < ops . length ; j ++ ) { Operation op = ops [ j ] ; if ( ( op . filter != null ) && ! op . filter . apply ( o ) ) { // stop processing this source item and go to the next one. continue sourceLoop ; } if ( op . map != null ) { o = op . map . apply ( o ) ; // This is how map can handle takeWhile, take, and other termination marker // roles.  Remember, the fewer functions we have to check for, the faster this // will execute. if ( o == TERMINATE ) { return ( H ) ret ; } } else if ( op . flatMap != null ) { ret = _fold ( op . flatMap . apply ( o ) , ops , j + 1 , ( H ) ret , reducer ) ; // stop processing this source item and go to the next one. continue sourceLoop ; } //                    if ( (op.terminate != null) && op.terminate.apply(o) ) { //                        return (G) ret; //                    } } // Here, the item made it through all the operations.  Combine it with the result. ret = reducer . apply ( ret , o ) ; } return ( H ) ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] @ Override public Xform < A > concat ( Iterable < ? extends A > list ) { if ( list == null ) { throw new IllegalArgumentException ( \"Can't concat a null iterable\" ) ; } return new AppendIterDesc <> ( this , new SourceProviderIterableDesc <> ( list ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] @ Override public Xform < A > precat ( Iterable < ? extends A > list ) { if ( list == null ) { throw new IllegalArgumentException ( \"Can't precat a null iterable\" ) ; } return new AppendIterDesc <> ( of ( list ) , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The number of items to drop from the beginning of the output . [CODESPLIT] @ Override public Xform < A > dropWhile ( Fn1 < ? super A , Boolean > predicate ) { if ( predicate == null ) { throw new IllegalArgumentException ( \"Can't dropWhile without a function.\" ) ; } return new DropWhileDesc <> ( this , predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a way to collect the results of the transformation . [CODESPLIT] @ Override public < B > B fold ( B ident , Fn2 < ? super B , ? super A , B > reducer ) { if ( reducer == null ) { throw new IllegalArgumentException ( \"Can't fold with a null reduction function.\" ) ; } // Construct an optimized array of OpRuns (mutable operations for this run) RunList runList = toRunList ( ) ; return _fold ( runList , runList . opArray ( ) , 0 , ident , reducer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Thit implementation should be correct but could be slow in the case where previous operations are slow and the terminateWhen operation is fast and terminates early . It actually renders items to a mutable List then runs through the list performing the requested reduction checking for early termination on the result . If you can to a takeWhile () or take () earlier in the transform chain instead of doing it here always do that . If you really need early termination based on the * result * of a fold and the operations are expensive or the input is huge try using a View instead . If you don t care about those things then this method is perfect for you . [CODESPLIT] @ Override public < G , B > Or < G , B > foldUntil ( G accum , Fn2 < ? super G , ? super A , B > terminator , Fn2 < ? super G , ? super A , G > reducer ) { if ( terminator == null ) { return Or . good ( fold ( accum , reducer ) ) ; } if ( reducer == null ) { throw new IllegalArgumentException ( \"Can't fold with a null reduction function.\" ) ; } // Yes, this is a cheap plastic imitation of what you'd hope for if you really need this // method.  The trouble is that when I implemented it correctly in _fold, I found // it was going to be incredibly difficult, or more likely impossible to implement // when the previous operation was flatMap, since you don't have the right result type to // check against when you recurse in to the flat mapping function, and if you check the // return from the recursion, it may have too many elements already. // In XformTest.java, there's something marked \"Early termination test\" that illustrates // this exact problem. List < A > as = this . toMutableList ( ) ; for ( A a : as ) { B term = terminator . apply ( accum , a ) ; if ( term != null ) { return Or . bad ( term ) ; } accum = reducer . apply ( accum , a ) ; } return Or . good ( accum ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeSet of the given comparator . Always use this instead of starting with empty () because there is no way to assign a comparator to an existing set . [CODESPLIT] public static < T > PersistentTreeSet < T > ofComp ( Comparator < ? super T > comp ) { return new PersistentTreeSet <> ( PersistentTreeMap . empty ( comp ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeSet of the given comparator and items . [CODESPLIT] public static < T > PersistentTreeSet < T > ofComp ( Comparator < ? super T > comp , Iterable < T > elements ) { PersistentTreeSet < T > ret = new PersistentTreeSet <> ( PersistentTreeMap . empty ( comp ) ) ; if ( elements == null ) { return ret ; } for ( T element : elements ) { ret = ret . put ( element ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeSet of the given comparable items . [CODESPLIT] public static < T extends Comparable < T > > PersistentTreeSet < T > of ( Iterable < T > items ) { // empty() uses default comparator if ( items == null ) { return empty ( ) ; } PersistentTreeSet < T > ret = empty ( ) ; for ( T item : items ) { ret = ret . put ( item ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public PersistentTreeSet < E > without ( E key ) { return ( impl . containsKey ( key ) ) ? new PersistentTreeSet <> ( impl . without ( key ) ) : this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public UnmodSortedIterator < E > iterator ( ) { return new UnmodSortedIterator < E > ( ) { UnmodSortedIterator < ? extends UnmodMap . UnEntry < E , ? > > iter = impl . iterator ( ) ; @ Override public boolean hasNext ( ) { return iter . hasNext ( ) ; } @ Override public E next ( ) { UnmodMap . UnEntry < E , ? > e = iter . next ( ) ; return e == null ? null : e . getKey ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Option < E > head ( ) { return size ( ) > 0 ? Option . some ( impl . firstKey ( ) ) : Option . none ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public PersistentTreeSet < E > put ( E e ) { return ( impl . containsKey ( e ) ) ? this : new PersistentTreeSet <> ( impl . assoc ( e , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public ImSortedSet < E > subSet ( E fromElement , E toElement ) { return PersistentTreeSet . ofMap ( impl . subMap ( fromElement , toElement ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public ImSortedSet < E > tailSet ( E fromElement ) { return PersistentTreeSet . ofMap ( impl . tailMap ( fromElement ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public < U > U match ( Fn1 < T , U > has , Fn0 < U > hasNot ) { return hasNot . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public static factory method [CODESPLIT] public static < A , B > Tuple2 < A , B > of ( A a , B b ) { return new Tuple2 <> ( a , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map . Entry factory method [CODESPLIT] public static < K , V > Tuple2 < K , V > of ( Map . Entry < K , V > entry ) { // Protect against multiple-instantiation if ( entry instanceof Tuple2 ) { return ( Tuple2 < K , V > ) entry ; } return new Tuple2 <> ( entry . getKey ( ) , entry . getValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new RrbTree minus the given item ( all items to the right are shifted left one ) This is O ( log n ) . [CODESPLIT] public RrbTree < E > without ( int index ) { if ( ( index > 0 ) && ( index < size ( ) - 1 ) ) { Tuple2 < ? extends RrbTree < E > , ? extends RrbTree < E > > s1 = split ( index ) ; Tuple2 < ? extends RrbTree < E > , ? extends RrbTree < E > > s2 = s1 . _2 ( ) . split ( 1 ) ; return s1 . _1 ( ) . join ( s2 . _2 ( ) ) ; } else if ( index == 0 ) { return split ( 1 ) . _2 ( ) ; } else if ( index == size ( ) - 1 ) { return split ( size ( ) - 1 ) . _1 ( ) ; } else { throw new IndexOutOfBoundsException ( \"Failed test: 0 <= index < size\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to avoid type warnings . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static < T > Node < T > [ ] genericNodeArray ( int size ) { return ( Node < T > [ ] ) new Node < ? > [ size ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "=============================== Debugging and pretty - printing =============================== [CODESPLIT] private static StringBuilder showSubNodes ( StringBuilder sB , Object [ ] items , int nextIndent ) { boolean isFirst = true ; for ( Object n : items ) { if ( isFirst ) { isFirst = false ; } else { //                sB.append(\" \"); if ( items [ 0 ] instanceof Leaf ) { sB . append ( \" \" ) ; } else { sB . append ( \"\\n\" ) . append ( indentSpace ( nextIndent ) ) ; } } sB . append ( ( ( Node ) n ) . indentedStr ( nextIndent ) ) ; } return sB ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If sel is managed correctly it ensures that the cast is accurate . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < R > R match ( Fn1 < A , R > fa , Fn1 < B , R > fb , Fn1 < C , R > fc ) { if ( sel == 0 ) { return fa . apply ( ( A ) item ) ; } else if ( sel == 1 ) { return fb . apply ( ( B ) item ) ; } else { return fc . apply ( ( C ) item ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static RangeOfInt of ( Number s , Number e ) { if ( ( s == null ) || ( e == null ) ) { throw new IllegalArgumentException ( \"Nulls not allowed\" ) ; } if ( e . longValue ( ) < s . longValue ( ) ) { throw new IllegalArgumentException ( \"end of range must be >= start of range\" ) ; } return new RangeOfInt ( s . intValue ( ) , e . intValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Though this overrides List . contains ( Object o ) it is effectively a convenience method for calling contains ( int i ) . Therefore it only accepts Integers Longs BigIntegers and Strings that parse as signed decimal Integers . It does not accept Numbers since they can t easily be checked for truncation and floating - point might not round properly with respect to bounds or might not make sense if you are using your range to define a set of integers . Handles truncation ( returns false ) for the types it accepts . Throws exceptions for types it does not accept . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) @ Override public boolean contains ( Object o ) { // Only accept classes where we can convert to an integer while preventing // overflow/underflow.  If there were a way to reliably test for overflow/underflow in // Numbers, we could accept them too, but with the rounding errors of floats and doubles // that's impractical. if ( o instanceof Integer ) { return contains ( ( ( Integer ) o ) . intValue ( ) ) ; } else if ( o instanceof Long ) { long l = ( Long ) o ; return ( l <= ( ( long ) Integer . MAX_VALUE ) ) && ( l >= ( ( long ) Integer . MIN_VALUE ) ) && contains ( ( int ) l ) ; } else if ( o instanceof BigInteger ) { try { // Throws an exception if it's more than 32 bits. return contains ( ( ( BigInteger ) o ) . intValueExact ( ) ) ; } catch ( ArithmeticException ignore ) { return false ; } } else if ( o instanceof String ) { return contains ( Integer . valueOf ( ( String ) o ) ) ; } else { throw new IllegalArgumentException ( \"Don't know how to convert to a primitive int\" + \" without risking accidental truncation.  Pass an\" + \" Integer, Long, BigInteger, or String that parses\" + \" within Integer bounds instead.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unlike most implementations of List this method has excellent O ( 1 ) performance! { [CODESPLIT] @ Override public int indexOf ( Object o ) { if ( o instanceof Number ) { int i = ( ( Number ) o ) . intValue ( ) ; if ( ( i >= start ) && ( i < end ) ) { return i - start ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public UnmodListIterator < Integer > listIterator ( final int startIdx ) { if ( ( startIdx < 0 ) || ( startIdx > size ) ) { // To match ArrayList and other java.util.List expectations throw new IndexOutOfBoundsException ( \"Index: \" + startIdx ) ; } return new UnmodListIterator < Integer > ( ) { int val = start + startIdx ; @ Override public boolean hasNext ( ) { return val < end ; } @ Override public Integer next ( ) { if ( val >= end ) { // To match ArrayList and other java.util.List expectations throw new NoSuchElementException ( ) ; } Integer t = val ; val = val + 1 ; return t ; } @ Override public boolean hasPrevious ( ) { return val > start ; } @ Override public Integer previous ( ) { if ( val <= start ) { // To match ArrayList and other java.util.List expectations throw new NoSuchElementException ( ) ; } val = val - 1 ; return val ; } @ Override public int nextIndex ( ) { return val - start ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public RangeOfInt subList ( int fromIndex , int toIndex ) { if ( ( fromIndex == 0 ) && ( toIndex == size ) ) { return this ; } // Note that this is an IllegalArgumentException, not IndexOutOfBoundsException in order to // match ArrayList. if ( fromIndex > toIndex ) { throw new IllegalArgumentException ( \"fromIndex(\" + fromIndex + \") > toIndex(\" + toIndex + \")\" ) ; } // The text of this matches ArrayList if ( fromIndex < 0 ) { throw new IndexOutOfBoundsException ( \"fromIndex = \" + fromIndex ) ; } if ( toIndex > size ) { throw new IndexOutOfBoundsException ( \"toIndex = \" + toIndex ) ; } // Look very closely at the second parameter because the bounds checking is *different* // from the get() method.  get(toIndex) can throw an exception if toIndex >= start+size. // But since a range is exclusive of it's right-bound, we can create a new sub-range // with a right bound index of size, as opposed to size minus 1.  I spent hours // understanding this before fixing a bug with it.  In the end, subList should do the same // thing on a Range that it does on the equivalent ArrayList.  I made tests for the same. return RangeOfInt . of ( start + fromIndex , start + toIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use this to prevent duplicate runtime types . [CODESPLIT] public static ImList < Class > registerClasses ( Class ... cs ) { if ( cs == null ) { throw new IllegalArgumentException ( \"Can't register a null type array\" ) ; } if ( cs . length == 0 ) { throw new IllegalArgumentException ( \"Can't register a zero-length type array\" ) ; } for ( Class c : cs ) { if ( c == null ) { throw new IllegalArgumentException ( \"There shouldn't be any null types in this array!\" ) ; } } ArrayHolder < Class > ah = new ArrayHolder <> ( cs ) ; ImList < Class > registeredTypes ; synchronized ( Lock . INSTANCE ) { registeredTypes = typeMap . get ( ah ) ; if ( registeredTypes == null ) { ImList < Class > vecCs = vec ( cs ) ; typeMap . put ( ah , vecCs ) ; registeredTypes = vecCs ; } } // We are returning the original array.  If we returned our safe copy, it could be modified! return registeredTypes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public static factory method [CODESPLIT] public static < A , B , C , D , E , F , G > Tuple7 < A , B , C , D , E , F , G > of ( A a , B b , C c , D d , E e , F f , G g ) { return new Tuple7 <> ( a , b , c , d , e , f , g ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new mutable vector . For some reason calling empty () . mutable () sometimes requires an explicit type parameter in Java so this convenience method works around that . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > MutableVector < T > emptyMutable ( ) { PersistentVector < T > e = empty ( ) ; return e . mutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public static factory method to create a vector from an Iterable . A varargs version of this method is : { [CODESPLIT] static public < T > PersistentVector < T > ofIter ( Iterable < T > items ) { MutableVector < T > ret = emptyMutable ( ) ; for ( T item : items ) { ret . append ( item ) ; } return ret . immutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the array ( of type E ) from the leaf node indicated by the given index . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private E [ ] leafNodeArrayFor ( int i ) { // i is the index into this vector.  Each 5 bits represent an index into an array.  The // highest 5 bits (that are less than the shift value) are the index into the top-level // array. The lowest 5 bits index the the leaf.  The guts of this method indexes into the // array at each level, finally indexing into the leaf node. if ( i >= 0 && i < size ) { if ( i >= tailoff ( ) ) { return tail ; } Node node = root ; for ( int level = shift ; level > 0 ; level -= NODE_LENGTH_POW_2 ) { node = ( Node ) node . array [ ( i >>> level ) & LOW_BITS ] ; } return ( E [ ] ) node . array ; } throw new IndexOutOfBoundsException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the item specified by the given index . [CODESPLIT] @ Override public E get ( int i ) { E [ ] node = leafNodeArrayFor ( i ) ; return node [ i & LOW_BITS ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public PersistentVector < E > replace ( int i , E val ) { if ( i >= 0 && i < size ) { if ( i >= tailoff ( ) ) { Object [ ] newTail = new Object [ tail . length ] ; System . arraycopy ( tail , 0 , newTail , 0 , tail . length ) ; newTail [ i & LOW_BITS ] = val ; return new PersistentVector <> ( size , shift , root , ( E [ ] ) newTail ) ; } return new PersistentVector <> ( size , shift , doAssoc ( shift , root , i , val ) , tail ) ; } if ( i == size ) { return append ( val ) ; } throw new IndexOutOfBoundsException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a new item at the end of the Vecsicle . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public PersistentVector < E > append ( E val ) { //room in tail? //\tif(tail.length < MAX_NODE_LENGTH) if ( size - tailoff ( ) < MAX_NODE_LENGTH ) { E [ ] newTail = ( E [ ] ) new Object [ tail . length + 1 ] ; System . arraycopy ( tail , 0 , newTail , 0 , tail . length ) ; newTail [ tail . length ] = val ; return new PersistentVector <> ( size + 1 , shift , root , newTail ) ; } //full tail, push into tree Node newroot ; Node tailnode = new Node ( root . edit , tail ) ; int newshift = shift ; //overflow root? if ( ( size >>> NODE_LENGTH_POW_2 ) > ( 1 << shift ) ) { newroot = new Node ( root . edit ) ; newroot . array [ 0 ] = root ; newroot . array [ 1 ] = newPath ( root . edit , shift , tailnode ) ; newshift += NODE_LENGTH_POW_2 ; } else { newroot = pushTail ( shift , root , tailnode ) ; } return new PersistentVector <> ( size + 1 , newshift , newroot , ( E [ ] ) new Object [ ] { val } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Efficiently adds items to the end of this PersistentVector . [CODESPLIT] @ Override public PersistentVector < E > concat ( Iterable < ? extends E > items ) { return ( PersistentVector < E > ) ImList . super . concat ( items ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public UnmodListIterator < E > listIterator ( int index ) { if ( ( index < 0 ) || ( index > size ) ) { // To match ArrayList and other java.util.List expectations throw new IndexOutOfBoundsException ( \"Index: \" + index ) ; } return new UnmodListIterator < E > ( ) { private int i = index ; private int base = i - ( i % MAX_NODE_LENGTH ) ; private E [ ] array = ( index < size ( ) ) ? leafNodeArrayFor ( i ) : null ; /** {@inheritDoc} */ @ Override public boolean hasNext ( ) { return i < size ( ) ; } /** {@inheritDoc} */ @ Override public boolean hasPrevious ( ) { return i > 0 ; } /** {@inheritDoc} */ @ Override public E next ( ) { if ( i >= size ) { // To match ArrayList and other java.util.List expectations // If we didn't catch this, it would be an ArrayIndexOutOfBoundsException. throw new NoSuchElementException ( ) ; } if ( i - base == MAX_NODE_LENGTH ) { array = leafNodeArrayFor ( i ) ; base += MAX_NODE_LENGTH ; } return array [ i ++ & LOW_BITS ] ; } /** {@inheritDoc} */ @ Override public int nextIndex ( ) { return i ; } /** {@inheritDoc} */ @ Override public E previous ( ) { // To match contract of ListIterator and implementation of ArrayList if ( i < 1 ) { // To match ArrayList and other java.util.List expectations. throw new NoSuchElementException ( ) ; } if ( i - base == 0 ) { //                    System.out.println(\"i - base was zero\"); array = leafNodeArrayFor ( i - 1 ) ; base -= MAX_NODE_LENGTH ; } else if ( i == size ) { // Can start with index past array. array = leafNodeArrayFor ( i - 1 ) ; base = i - ( i % MAX_NODE_LENGTH ) ; } return array [ -- i & LOW_BITS ] ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private static Node doAssoc ( int level , Node node , int i , Object val ) { Node ret = new Node ( node . edit , node . array . clone ( ) ) ; if ( level == 0 ) { ret . array [ i & LOW_BITS ] = val ; } else { int subidx = ( i >>> level ) & LOW_BITS ; ret . array [ subidx ] = doAssoc ( level - NODE_LENGTH_POW_2 , ( Node ) node . array [ subidx ] , i , val ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public static factory method [CODESPLIT] public static < A , B , C , D , E , F , G , H , I > Tuple9 < A , B , C , D , E , F , G , H , I > of ( A a , B b , C c , D d , E e , F f , G g , H h , I i ) { return new Tuple9 <> ( a , b , c , d , e , f , g , h , i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentHashMap of the given keys and their paired values . Use the { @link StaticImports#tup ( Object Object ) } method to define those key / value pairs briefly and easily . This data definition method is one of the few methods in this project that support varargs . [CODESPLIT] @ SafeVarargs public static < K , V > ImMap < K , V > map ( Map . Entry < K , V > ... kvPairs ) { if ( ( kvPairs == null ) || ( kvPairs . length < 1 ) ) { return PersistentHashMap . empty ( ) ; } return PersistentHashMap . of ( Arrays . asList ( kvPairs ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new MutableMap of the given keys and their paired values . Use the { @link StaticImports#tup ( Object Object ) } method to define those key / value pairs briefly and easily . This data definition method is one of the few methods in this project that support varargs . [CODESPLIT] @ SafeVarargs public static < K , V > MutableMap < K , V > mutableMap ( Map . Entry < K , V > ... kvPairs ) { MutableMap < K , V > ret = PersistentHashMap . emptyMutable ( ) ; if ( kvPairs == null ) { return ret ; } for ( Map . Entry < K , V > me : kvPairs ) { ret . assoc ( me ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a mutable RRB Tree { [CODESPLIT] @ SafeVarargs static public < T > MutableRrbt < T > mutableRrb ( T ... items ) { if ( ( items == null ) || ( items . length < 1 ) ) { return RrbTree . emptyMutable ( ) ; } return RrbTree . < T > emptyMutable ( ) . concat ( Arrays . asList ( items ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new MutableSet of the values . This data definition method is one of the few methods in this project that support varargs . If the input contains duplicate elements later values overwrite earlier ones . [CODESPLIT] @ SafeVarargs public static < T > MutableSet < T > mutableSet ( T ... items ) { MutableSet < T > ret = PersistentHashSet . emptyMutable ( ) ; if ( items == null ) { return ret ; } for ( T t : items ) { ret . put ( t ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a MutableVector of the given items . This data definition method is one of the few methods in this project that support varargs . [CODESPLIT] @ SafeVarargs public static < T > MutableList < T > mutableVec ( T ... items ) { MutableList < T > ret = PersistentVector . emptyMutable ( ) ; if ( items == null ) { return ret ; } for ( T t : items ) { ret . append ( t ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new immutable RRB Tree { @link ImRrbt } of the given items . An RRB Tree is an immutable list that supports random inserts split and join ( the PersistentVector does not ) . If you build it entirely with random inserts then the RRB tree get () method may be about 5x slower . Otherwise performance is about the same . [CODESPLIT] @ SafeVarargs static public < T > ImRrbt < T > rrb ( T ... items ) { if ( ( items == null ) || ( items . length < 1 ) ) { return RrbTree . empty ( ) ; } return mutableRrb ( items ) . immutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentHashSet of the values . This data definition method is one of the few methods in this project that support varargs . If the input contains duplicate elements later values overwrite earlier ones . [CODESPLIT] @ SafeVarargs public static < T > ImSet < T > set ( T ... items ) { if ( ( items == null ) || ( items . length < 1 ) ) { return PersistentHashSet . empty ( ) ; } return PersistentHashSet . of ( Arrays . asList ( items ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeMap of the specified comparator and the given key / value pairs . Use the tup () method to define those key / value pairs briefly and easily . The keys are sorted according to the comparator you provide . [CODESPLIT] public static < K , V > ImSortedMap < K , V > sortedMap ( Comparator < ? super K > comp , Iterable < Map . Entry < K , V > > kvPairs ) { return PersistentTreeMap . ofComp ( comp , kvPairs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeSet of the given comparator and items . [CODESPLIT] public static < T > ImSortedSet < T > sortedSet ( Comparator < ? super T > comp , Iterable < T > elements ) { return Xform . of ( elements ) . toImSortedSet ( comp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentTreeSet of the given comparable items . [CODESPLIT] public static < T extends Comparable < T > > ImSortedSet < T > sortedSet ( Iterable < T > items ) { return PersistentTreeSet . of ( items ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new PersistentVector of the given items . This data definition method is one of the few methods in this project that support varargs . [CODESPLIT] @ SafeVarargs static public < T > ImList < T > vec ( T ... items ) { if ( ( items == null ) || ( items . length < 1 ) ) { return PersistentVector . empty ( ) ; } return mutableVec ( items ) . immutable ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If you need to wrap a regular Java array outside this project to perform a transformation on it this method is the most convenient efficient way to do so . [CODESPLIT] @ SafeVarargs public static < T > UnmodIterable < T > xformArray ( T ... items ) { return Xform . of ( Arrays . asList ( items ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap a String ( or CharSequence ) to perform a Character - by - Character transformation on it . [CODESPLIT] public static UnmodIterable < Character > xformChars ( CharSequence seq ) { //noinspection Convert2Lambda return new UnmodIterable < Character > ( ) { @ Override public UnmodIterator < Character > iterator ( ) { return new UnmodIterator < Character > ( ) { private int idx = 0 ; @ Override public boolean hasNext ( ) { return idx < seq . length ( ) ; } @ Override public Character next ( ) { int nextIdx = idx + 1 ; Character c = seq . charAt ( idx ) ; idx = nextIdx ; return c ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new StringBuilder with the given number of spaces and returns it . [CODESPLIT] public static StringBuilder indentSpace ( int len ) { StringBuilder sB = new StringBuilder ( ) ; if ( len < 1 ) { return sB ; } while ( len > SPACES_LENGTH_MINUS_ONE ) { sB . append ( SPACES [ SPACES_LENGTH_MINUS_ONE ] ) ; len = len - SPACES_LENGTH_MINUS_ONE ; } return sB . append ( SPACES [ len ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There is Arrays . toString but this is intended to produce Cymling code some day . [CODESPLIT] public static < T > String arrayString ( T [ ] items ) { StringBuilder sB = new StringBuilder ( \"A[\" ) ; boolean isFirst = true ; for ( T item : items ) { if ( isFirst ) { isFirst = false ; } else { sB . append ( \" \" ) ; } if ( item instanceof String ) { sB . append ( \"\\\"\" ) . append ( item ) . append ( \"\\\"\" ) ; } else { sB . append ( item ) ; } } return sB . append ( \"]\" ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : We need one of these for each type of primitive for pretty - printing without commas . [CODESPLIT] public static String arrayString ( int [ ] items ) { StringBuilder sB = new StringBuilder ( \"i[\" ) ; boolean isFirst = true ; for ( int item : items ) { if ( isFirst ) { isFirst = false ; } else { sB . append ( \" \" ) ; } sB . append ( item ) ; } return sB . append ( \"]\" ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a LazyRef from the given initialization function . [CODESPLIT] public static < T > LazyRef < T > of ( Fn0 < T > producer ) { if ( producer == null ) { throw new IllegalArgumentException ( \"The producer function cannot be null (the value it returns can)\" ) ; } return new LazyRef <> ( producer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This whole method is synchronized on the advice of Goetz2006 p . 347 [CODESPLIT] public synchronized T applyEx ( ) { // Have we produced our value yet? if ( producer != null ) { // produce our value. value = producer . apply ( ) ; // Delete the producer to 1. mark the work done and 2. free resources. producer = null ; } // We're clear to return the lazily computed value. return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to avoid type warnings . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T [ ] singleElementArray ( T elem , Class < T > tClass ) { if ( tClass == null ) { return ( T [ ] ) new Object [ ] { elem } ; } T [ ] newItems = ( T [ ] ) Array . newInstance ( tClass , 1 ) ; newItems [ 0 ] = elem ; return newItems ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array one longer than the given one with the specified item inserted at the specified index . [CODESPLIT] public static < T > T [ ] insertIntoArrayAt ( T item , T [ ] items , int idx , Class < T > tClass ) { // Make an array that's one bigger.  It's too bad that the JVM bothers to // initialize this with nulls. @ SuppressWarnings ( \"unchecked\" ) T [ ] newItems = ( T [ ] ) ( ( tClass == null ) ? new Object [ items . length + 1 ] : Array . newInstance ( tClass , items . length + 1 ) ) ; // If we aren't inserting at the first item, array-copy the items before the insert // point. if ( idx > 0 ) { System . arraycopy ( items , 0 , newItems , 0 , idx ) ; } // Insert the new item. newItems [ idx ] = item ; // If we aren't inserting at the last item, array-copy the items after the insert // point. if ( idx < items . length ) { System . arraycopy ( items , idx , newItems , idx + 1 , items . length - idx ) ; } return newItems ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array containing the first n items of the given array . [CODESPLIT] public static < T > T [ ] arrayCopy ( T [ ] items , int length , Class < T > tClass ) { // Make an array of the appropriate size.  It's too bad that the JVM bothers to // initialize this with nulls. @ SuppressWarnings ( \"unchecked\" ) T [ ] newItems = ( T [ ] ) ( ( tClass == null ) ? new Object [ length ] : Array . newInstance ( tClass , length ) ) ; // array-copy the items up to the new length. if ( length > 0 ) { System . arraycopy ( items , 0 , newItems , 0 , items . length < length ? items . length : length ) ; } return newItems ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called splice but handles precat ( idx = 0 ) and concat ( idx = origItems . length ) . [CODESPLIT] public static < A > A [ ] spliceIntoArrayAt ( A [ ] insertedItems , A [ ] origItems , int idx , Class < A > tClass ) { // Make an array that big enough.  It's too bad that the JVM bothers to // initialize this with nulls. @ SuppressWarnings ( \"unchecked\" ) A [ ] newItems = tClass == null ? ( A [ ] ) new Object [ insertedItems . length + origItems . length ] : ( A [ ] ) Array . newInstance ( tClass , insertedItems . length + origItems . length ) ; // If we aren't inserting at the first item, array-copy the items before the insert // point. if ( idx > 0 ) { //               src,  srcPos, dest,destPos,length System . arraycopy ( origItems , 0 , newItems , 0 , idx ) ; } // Insert the new items //               src,      srcPos,     dest, destPos, length System . arraycopy ( insertedItems , 0 , newItems , idx , insertedItems . length ) ; // If we aren't inserting at the last item, array-copy the items after the insert // point. if ( idx < origItems . length ) { System . arraycopy ( origItems , idx , newItems , idx + insertedItems . length , origItems . length - idx ) ; } return newItems ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static < T > T [ ] replaceInArrayAt ( T replacedItem , T [ ] origItems , int idx , Class < T > tClass ) { // Make an array that big enough.  It's too bad that the JVM bothers to // initialize this with nulls. @ SuppressWarnings ( \"unchecked\" ) T [ ] newItems = ( T [ ] ) ( ( tClass == null ) ? new Object [ origItems . length ] : Array . newInstance ( tClass , origItems . length ) ) ; System . arraycopy ( origItems , 0 , newItems , 0 , origItems . length ) ; newItems [ idx ] = replacedItem ; return newItems ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only call this if the array actually needs to be split ( 0 &lt ; splitPoint &lt ; orig . length ) . [CODESPLIT] public static < T > Tuple2 < T [ ] , T [ ] > splitArray ( T [ ] orig , int splitIndex ) { //, Class<T> tClass) { //        if (splitIndex < 1) { //            throw new IllegalArgumentException(\"Called split when splitIndex < 1\"); //        } //        if (splitIndex > orig.length - 1) { //            throw new IllegalArgumentException(\"Called split when splitIndex > orig.length - 1\"); //        } // NOTE: // I sort of suspect that generic 2D array creation where the two arrays are of a different // length is not possible in Java, or if it is, it's not likely to be much faster than // what we have here.  I'd just copy the Arrays.copyOf code everywhere this function is used // if you want more speed. //        int rightLength = orig.length - splitIndex; //        Class<T> tClass = (Class<T>) orig.getClass().getComponentType(); //        Tuple2<T[],T[]> split = Tuple2.of((T[]) Array.newInstance(tClass, splitIndex), //                                          (T[]) Array.newInstance(tClass, rightLength)); // // Tuple2<T[],T[]> split = return Tuple2 . of ( Arrays . copyOf ( orig , splitIndex ) , Arrays . copyOfRange ( orig , splitIndex , orig . length ) ) ; //        // original array, offset, newArray, offset, length //        System.arraycopy(orig, 0, split._1(), 0, splitIndex); // //        System.arraycopy(orig, splitIndex, split._2(), 0, rightLength); //        return split; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only call this if the array actually needs to be split ( 0 &lt ; splitPoint &lt ; orig . length ) . [CODESPLIT] public static int [ ] [ ] splitArray ( int [ ] orig , int splitIndex ) { // This function started an exact duplicate of the one above, but for ints. //        if (splitIndex < 1) { //            throw new IllegalArgumentException(\"Called split when splitIndex < 1\"); //        } //        if (splitIndex > orig.length - 1) { //            throw new IllegalArgumentException(\"Called split when splitIndex > orig.length - 1\"); //        } int rightLength = orig . length - splitIndex ; int [ ] [ ] split = new int [ ] [ ] { new int [ splitIndex ] , new int [ rightLength ] } ; // original array, offset, newArray, offset, length System . arraycopy ( orig , 0 , split [ 0 ] , 0 , splitIndex ) ; System . arraycopy ( orig , splitIndex , split [ 1 ] , 0 , rightLength ) ; return split ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public DeployableUnitDescriptorImpl parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . du . DeployableUnit ) { return new DeployableUnitDescriptorImpl ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . du . DeployableUnit ) jaxbPojo ) ; } else if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee . du . DeployableUnit ) { return new DeployableUnitDescriptorImpl ( ( org . mobicents . slee . container . component . deployment . jaxb . slee . du . DeployableUnit ) jaxbPojo ) ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some operations require that the transaction be suspended [CODESPLIT] private void suspendIfAssoaciatedWithThread ( ) throws SystemException { // if there is a tx associated with this thread and it is this one // then suspend it to dissociate the thread (dumb feature?!?! of jboss ts) final SleeTransaction currentThreadTransaction = transactionManager . getSleeTransaction ( ) ; if ( currentThreadTransaction != null && currentThreadTransaction . equals ( this ) ) { // lets use the real tx manager directly, to avoid any other procedures transactionManager . getRealTransactionManager ( ) . suspend ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if the wrapped transaction is active and if dissociates it from the thread if needed [CODESPLIT] private void beforeAsyncOperation ( ) throws IllegalStateException , SecurityException { try { int status = transaction . getStatus ( ) ; if ( asyncOperationInitiated . getAndSet ( true ) || ( status != Status . STATUS_ACTIVE && status != Status . STATUS_MARKED_ROLLBACK ) ) { throw new IllegalStateException ( \"There is no active tx, tx is in state: \" + status ) ; } suspendIfAssoaciatedWithThread ( ) ; } catch ( SystemException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void asyncCommit ( CommitListener commitListener ) throws IllegalStateException , SecurityException { beforeAsyncOperation ( ) ; transactionManager . getExecutorService ( ) . submit ( new AsyncTransactionCommitRunnable ( commitListener , transaction ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void asyncRollback ( RollbackListener rollbackListener ) throws IllegalStateException , SecurityException { beforeAsyncOperation ( ) ; transactionManager . getExecutorService ( ) . submit ( new AsyncTransactionRollbackRunnable ( rollbackListener , transaction ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean delistResource ( XAResource arg0 , int arg1 ) throws IllegalStateException , SystemException { return transaction . delistResource ( arg0 , arg1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean enlistResource ( XAResource arg0 ) throws IllegalStateException , RollbackException { try { return transaction . enlistResource ( arg0 ) ; } catch ( SystemException e ) { // this should be a bug in slee 1.1 api, the exceptions thrown // should match jta transaction interface throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void commit ( ) throws RollbackException , HeuristicMixedException , HeuristicRollbackException , SecurityException , IllegalStateException , SystemException { if ( asyncOperationInitiated . get ( ) ) { throw new IllegalStateException ( ) ; } try { transaction . commit ( ) ; } finally { suspendIfAssoaciatedWithThread ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > ResourceAdaptorEntityState< / code > object from an integer value . [CODESPLIT] public static ResourceAdaptorEntityState fromInt ( int state ) throws IllegalArgumentException { switch ( state ) { case ENTITY_INACTIVE : return INACTIVE ; case ENTITY_ACTIVE : return ACTIVE ; case ENTITY_STOPPING : return STOPPING ; default : throw new IllegalArgumentException ( \"Invalid state: \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a service component contained in the specified du jar file with the specified and adds it to the specified deployable unit . [CODESPLIT] public List < ServiceComponentImpl > buildComponents ( String serviceDescriptorFileName , JarFile deployableUnitJar ) throws DeploymentException { // make component jar entry JarEntry componentDescriptor = deployableUnitJar . getJarEntry ( serviceDescriptorFileName ) ; InputStream componentDescriptorInputStream = null ; List < ServiceComponentImpl > result = new ArrayList < ServiceComponentImpl > ( ) ; try { componentDescriptorInputStream = deployableUnitJar . getInputStream ( componentDescriptor ) ; ServiceDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getServiceDescriptorFactory ( ) ; for ( ServiceDescriptorImpl descriptor : descriptorFactory . parse ( componentDescriptorInputStream ) ) { result . add ( new ServiceComponentImpl ( descriptor ) ) ; } } catch ( IOException e ) { throw new DeploymentException ( \"failed to parse service descriptor from \" + componentDescriptor . getName ( ) , e ) ; } finally { if ( componentDescriptorInputStream != null ) { try { componentDescriptorInputStream . close ( ) ; } catch ( IOException e ) { logger . error ( \"failed to close inputstream of descriptor for jar \" + componentDescriptor . getName ( ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively walk a directory tree and return a List of all jars Files found ; the List is sorted using File . compareTo . [CODESPLIT] static public List getJarsFileListing ( File aStartingDir ) throws FileNotFoundException { validateDirectory ( aStartingDir ) ; List result = new ArrayList ( ) ; File [ ] filesAndDirs = aStartingDir . listFiles ( new FileFilter ( ) { public boolean accept ( File pathname ) { if ( pathname . getName ( ) . endsWith ( \".jar\" ) ) return true ; return false ; } } ) ; List filesDirs = Arrays . asList ( filesAndDirs ) ; Iterator filesIter = filesDirs . iterator ( ) ; File file = null ; while ( filesIter . hasNext ( ) ) { file = ( File ) filesIter . next ( ) ; result . add ( file ) ; // always add, even if directory\r if ( ! file . isFile ( ) ) { // must be a directory\r // recursive call!\r List deeperList = getJarsFileListing ( file ) ; result . addAll ( deeperList ) ; } } Collections . sort ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Directory is valid if it exists does not represent a file and can be read . [CODESPLIT] static private void validateDirectory ( File aDirectory ) throws FileNotFoundException { if ( aDirectory == null ) { throw new IllegalArgumentException ( \"Directory should not be null.\" ) ; } if ( ! aDirectory . exists ( ) ) { throw new FileNotFoundException ( \"Directory does not exist: \" + aDirectory ) ; } if ( ! aDirectory . isDirectory ( ) ) { throw new IllegalArgumentException ( \"Is not a directory: \" + aDirectory ) ; } if ( ! aDirectory . canRead ( ) ) { throw new IllegalArgumentException ( \"Directory cannot be read: \" + aDirectory ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the links with possible interfaces [CODESPLIT] public static void createInterfaceLinks ( CtClass concreteClass , CtClass [ ] interfaces ) { if ( interfaces != null ) concreteClass . setInterfaces ( interfaces ) ; else return ; for ( int i = 0 ; i < interfaces . length ; i ++ ) { logger . trace ( concreteClass . getName ( ) + \" Implements link with \" + interfaces [ i ] . getName ( ) + \" interface created\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the inheritance link with the sbb absract class provided by the sbb developer [CODESPLIT] public static void createInheritanceLink ( CtClass concreteClass , CtClass superClass ) { if ( superClass == null ) return ; try { concreteClass . setSuperclass ( superClass ) ; logger . trace ( concreteClass . getName ( ) + \" Inheritance link with \" + superClass . getName ( ) + \" class created\" ) ; } catch ( CannotCompileException cce ) { cce . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a concrete method invoking the interceptor <B > interceptorName < / B > with the same parameters name return type as the method <B > method < / B > [CODESPLIT] public static void addInterceptedMethod ( CtClass concreteClass , CtMethod method , String interceptorName , boolean callSuperMethod ) { if ( method == null ) throw new InvalidParameterException ( \"Intercepted method should not be null\" ) ; if ( interceptorName == null ) throw new InvalidParameterException ( \"Interceptor class name should not be null\" ) ; String methodToAdd = \"public \" ; //Add the return type\r boolean hasReturn = false ; CtClass returnType = null ; try { returnType = method . getReturnType ( ) ; methodToAdd = methodToAdd . concat ( returnType . getName ( ) + \" \" ) ; hasReturn = true ; } catch ( NotFoundException nfe ) { //nfe.printStackTrace();\r logger . trace ( \"No return type -- assuming return type is void \" ) ; methodToAdd = methodToAdd + \"void \" ; } //Add the method name\r methodToAdd = methodToAdd . concat ( method . getName ( ) + \"(\" ) ; //Add the parameters\r CtClass [ ] parameterTypes = null ; ; String parametersInit = \"Object[] args=null;\" ; String argsInit = \"Class[] classes=null;\" ; try { parameterTypes = method . getParameterTypes ( ) ; parametersInit = parametersInit + \"args=new Object[\" + parameterTypes . length + \"];\" ; argsInit = argsInit + \"classes=new Class[\" + parameterTypes . length + \"];\" ; for ( int argNumber = 0 ; argNumber < parameterTypes . length ; argNumber ++ ) { methodToAdd = methodToAdd . concat ( parameterTypes [ argNumber ] . getName ( ) + \" arg_\" + argNumber ) ; //handle the primitive types\r if ( ! parameterTypes [ argNumber ] . isPrimitive ( ) ) parametersInit = parametersInit + \" args[\" + argNumber + \"]=arg_\" + argNumber + \";\" ; else parametersInit = parametersInit + \" args[\" + argNumber + \"]=\" + ClassUtils . getObjectFromPrimitiveType ( parameterTypes [ argNumber ] . getName ( ) , \"arg_\" + argNumber ) + \";\" ; String typeClass = parameterTypes [ argNumber ] . getName ( ) ; //handle the primitive types\r if ( ! parameterTypes [ argNumber ] . isPrimitive ( ) ) { if ( parameterTypes [ argNumber ] . isArray ( ) ) { String arrayClassRepresentation = toArray ( parameterTypes [ argNumber ] ) ; if ( arrayClassRepresentation != null ) argsInit = argsInit + \"classes[\" + argNumber + \"]=\" + SleeContainerUtils . class . getName ( ) + \".getCurrentThreadClassLoader().loadClass(\\\"\" + arrayClassRepresentation + \"\\\");\" ; } else argsInit = argsInit + \"classes[\" + argNumber + \"]=\" + SleeContainerUtils . class . getName ( ) + \".getCurrentThreadClassLoader().loadClass(\\\"\" + typeClass + \"\\\");\" ; } else argsInit = argsInit + \"classes[\" + argNumber + \"]=\" + ClassUtils . getClassFromPrimitiveType ( typeClass ) + \".TYPE;\" ; if ( argNumber + 1 < parameterTypes . length ) methodToAdd = methodToAdd + \",\" ; } methodToAdd += \") \" ; // Add method exceptions\r if ( method . getExceptionTypes ( ) . length > 0 ) { CtClass [ ] exceptions = method . getExceptionTypes ( ) ; methodToAdd += \" throws \" ; for ( int i = 0 ; i < exceptions . length - 1 ; i ++ ) { String exName = exceptions [ i ] . getName ( ) ; methodToAdd += exName + \", \" ; } methodToAdd += exceptions [ exceptions . length - 1 ] . getName ( ) ; } } catch ( NotFoundException nfe ) { nfe . printStackTrace ( ) ; throw new SLEEException ( \"Failed creating concrete Profile MBean implementation class\" , nfe ) ; } // Start adding method body\r methodToAdd += \" { \" ; methodToAdd += \"\" + parametersInit ; methodToAdd += \"\" + argsInit ; methodToAdd += \"Class clazz=this.getClass();\" ; methodToAdd += \"Object result=null;\" ; methodToAdd += \"try{\" ; //call the super method\r if ( callSuperMethod ) { if ( method . getName ( ) . equals ( \"profileStore\" ) ) { methodToAdd = methodToAdd + \"super.\" + method . getName ( ) + \"(\" ; if ( parameterTypes != null && parameterTypes . length > 0 ) { for ( int argNumber = 0 ; argNumber < parameterTypes . length ; argNumber ++ ) { methodToAdd = methodToAdd + \"arg_\" + argNumber ; if ( argNumber + 1 < parameterTypes . length ) methodToAdd = methodToAdd + \",\" ; } } methodToAdd = methodToAdd + \");\" ; } } methodToAdd = methodToAdd + \"java.lang.reflect.Method method=clazz.getDeclaredMethod(\\\"\" + method . getName ( ) + \"\\\",classes\" + \");\" ; methodToAdd = methodToAdd + \"result=\" + interceptorName + \".invoke(this,method,args); \" ; methodToAdd = methodToAdd + \"}catch(RuntimeException t){t.printStackTrace(); throw (t); \" + \" } catch (Exception ex1) { ex1.printStackTrace(); throw (ex1); }\" ; //call the super method\r if ( callSuperMethod ) { if ( ! method . getName ( ) . equals ( \"profileStore\" ) ) { methodToAdd = methodToAdd + \"super.\" + method . getName ( ) + \"(\" ; if ( parameterTypes != null && parameterTypes . length > 0 ) { for ( int argNumber = 0 ; argNumber < parameterTypes . length ; argNumber ++ ) { methodToAdd = methodToAdd + \"arg_\" + argNumber ; if ( argNumber + 1 < parameterTypes . length ) methodToAdd += \",\" ; } } methodToAdd += \");\" ; } } //handle the primitive types\r if ( hasReturn ) { if ( ! returnType . getName ( ) . equalsIgnoreCase ( \"void\" ) ) { if ( ! returnType . isPrimitive ( ) ) methodToAdd = methodToAdd + \"return (\" + returnType . getName ( ) + \")result;\" ; else methodToAdd = methodToAdd + \"return \" + ClassUtils . getPrimitiveTypeFromObject ( returnType . getName ( ) , \"result\" ) + \";\" ; } } methodToAdd += \"}\" ; //Add the implementation code\r logger . trace ( \"Method \" + methodToAdd + \" added\" ) ; CtMethod methodTest ; try { methodTest = CtNewMethod . make ( methodToAdd , concreteClass ) ; concreteClass . addMethod ( methodTest ) ; } catch ( CannotCompileException cce ) { throw new SLEEException ( \"Cannot compile method \" + method . getName ( ) , cce ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform an array class to its string representation <BR > example : String [] - > [ Ljava . lang . String ; [CODESPLIT] public static String toArray ( CtClass typeClass ) { StringTokenizer st = new StringTokenizer ( typeClass . getName ( ) , \"[\" ) ; String name = null ; CtClass arrayClass ; try { arrayClass = typeClass . getComponentType ( ) ; if ( ! arrayClass . isPrimitive ( ) ) name = \"L\" + arrayClass . getName ( ) . replace ( ' ' , ' ' ) + \";\" ; else name = toJvmRepresentation ( arrayClass . getName ( ) ) ; st . nextToken ( ) ; while ( st . hasMoreTokens ( ) ) { st . nextToken ( ) ; name = \"[\" + name ; } } catch ( NotFoundException e ) { e . printStackTrace ( ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the jvm representation of the primitives types <BR > Exemple : int - > I boolean - > Z and so on ... [CODESPLIT] public static String toJvmRepresentation ( String primitiveTypeName ) { if ( primitiveTypeName . equals ( \"int\" ) ) return \"I\" ; if ( primitiveTypeName . equals ( \"boolean\" ) ) return \"Z\" ; if ( primitiveTypeName . equals ( \"byte\" ) ) return \"B\" ; if ( primitiveTypeName . equals ( \"char\" ) ) return \"C\" ; if ( primitiveTypeName . equals ( \"double\" ) ) return \"D\" ; if ( primitiveTypeName . equals ( \"float\" ) ) return \"F\" ; if ( primitiveTypeName . equals ( \"long\" ) ) return \"J\" ; if ( primitiveTypeName . equals ( \"short\" ) ) return \"S\" ; if ( primitiveTypeName . equals ( \"void\" ) ) return \"V\" ; return primitiveTypeName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy declared methods from one class to another [CODESPLIT] public static void copyMethods ( CtClass source , CtClass destination , CtClass [ ] exceptions ) { copyMethods ( source . getDeclaredMethods ( ) , destination , exceptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy methods to a class [CODESPLIT] public static void copyMethods ( CtMethod [ ] methods , CtClass destination , CtClass [ ] exceptions ) { CtMethod methodCopy = null ; for ( CtMethod method : methods ) { try { methodCopy = new CtMethod ( method , destination , null ) ; if ( exceptions != null ) { try { methodCopy . setExceptionTypes ( exceptions ) ; } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } destination . addMethod ( methodCopy ) ; } catch ( CannotCompileException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ServiceActivity getActivity ( ) throws TransactionRequiredLocalException , FactoryException { final SleeContainer sleeContainer = serviceManagement . getSleeContainer ( ) ; final SleeTransactionManager stm = sleeContainer . getTransactionManager ( ) ; stm . mandateTransaction ( ) ; ServiceID serviceID = SleeThreadLocals . getInvokingService ( ) ; if ( serviceID == null ) { throw new FactoryException ( \"unable to find out the invoking service id\" ) ; } return new ServiceActivityImpl ( serviceID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser for the deployment descriptor . Minimal version obtained from Container . [CODESPLIT] private Collection < DeployableComponent > parseDescriptor ( ) throws IOException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing Descriptor for \" + this . diURL . toString ( ) ) ; } Collection < DeployableComponent > deployableComponents = new ArrayList < DeployableComponent > ( ) ; SleeContainer sleeContainer = SleeContainer . lookupFromJndi ( ) ; ComponentDescriptorFactory componentDescriptorFactory = sleeContainer . getComponentManagement ( ) . getComponentDescriptorFactory ( ) ; // Special case for the services...\r if ( this . diShortName . endsWith ( \".xml\" ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing Service Descriptor.\" ) ; } InputStream is = null ; try { is = diURL . openStream ( ) ; ServiceDescriptorFactory sdf = componentDescriptorFactory . getServiceDescriptorFactory ( ) ; List < ? extends ServiceDescriptor > serviceDescriptors = sdf . parse ( is ) ; for ( ServiceDescriptor sd : serviceDescriptors ) { DeployableComponent dc = new DeployableComponent ( this , sleeContainerDeployer ) ; dc . componentType = SERVICE_COMPONENT ; dc . componentID = sd . getServiceID ( ) ; dc . componentKey = getComponentIdAsString ( dc . componentID ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Component ID: \" + dc . componentKey ) ; logger . trace ( \"------------------------------ Dependencies ------------------------------\" ) ; } // Get the set of this sbb dependencies\r Set < ComponentID > serviceDependencies = sd . getDependenciesSet ( ) ; // Iterate through dependencies set\r for ( ComponentID dependencyId : serviceDependencies ) { // Add the dependency\r dc . dependencies . add ( getComponentIdAsString ( dependencyId ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( getComponentIdAsString ( dependencyId ) ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"--------------------------- End of Dependencies --------------------------\" ) ; } dc . installActions . add ( new ActivateServiceAction ( ( ServiceID ) dc . componentID , sleeContainerDeployer . getSleeContainer ( ) . getServiceManagement ( ) ) ) ; dc . uninstallActions . add ( new DeactivateServiceAction ( ( ServiceID ) dc . componentID , sleeContainerDeployer . getSleeContainer ( ) . getServiceManagement ( ) ) ) ; deployableComponents . add ( dc ) ; } return deployableComponents ; } catch ( Exception e ) { logger . error ( \"\" , e ) ; return null ; } finally { // Clean up!\r if ( is != null ) { try { is . close ( ) ; } finally { is = null ; } } } } try { URL descriptorXML = null ; // Determine whether the type of this instance is an sbb, event, RA\r // type, etc.\r if ( ( descriptorXML = duWrapper . getEntry ( \"META-INF/sbb-jar.xml\" ) ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing SBB Descriptor.\" ) ; } InputStream is = null ; try { is = descriptorXML . openStream ( ) ; // Parse the descriptor using the factory\r SbbDescriptorFactory sbbdf = componentDescriptorFactory . getSbbDescriptorFactory ( ) ; List < ? extends SbbDescriptor > sbbDescriptors = sbbdf . parse ( is ) ; if ( sbbDescriptors . isEmpty ( ) ) { logger . warn ( \"The \" + duWrapper . getFileName ( ) + \" deployment descriptor contains no sbb definitions\" ) ; return null ; } for ( SbbDescriptor sbbDescriptor : sbbDescriptors ) { DeployableComponent dc = new DeployableComponent ( this , sleeContainerDeployer ) ; dc . componentType = SBB_COMPONENT ; // Get the Component ID\r dc . componentID = sbbDescriptor . getSbbID ( ) ; // Get the Component Key\r dc . componentKey = getComponentIdAsString ( dc . componentID ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Component ID: \" + dc . componentKey ) ; logger . trace ( \"------------------------------ Dependencies ------------------------------\" ) ; } // Get the set of this sbb dependencies\r Set < ComponentID > sbbDependencies = sbbDescriptor . getDependenciesSet ( ) ; // Iterate through dependencies set\r for ( ComponentID dependencyId : sbbDependencies ) { // Add the dependency\r dc . dependencies . add ( getComponentIdAsString ( dependencyId ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( getComponentIdAsString ( dependencyId ) ) ; } } // FIXME: This is special case for Links. Maybe it\r // should be treated in SbbDescriptorImpl?\r for ( ResourceAdaptorTypeBindingDescriptor raTypeBinding : sbbDescriptor . getResourceAdaptorTypeBindings ( ) ) { for ( ResourceAdaptorEntityBindingDescriptor raEntityBinding : raTypeBinding . getResourceAdaptorEntityBinding ( ) ) { String raLink = raEntityBinding . getResourceAdaptorEntityLink ( ) ; // Add the dependency\r dc . dependencies . add ( raLink ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( raLink ) ; } } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"--------------------------- End of Dependencies --------------------------\" ) ; } deployableComponents . add ( dc ) ; } } catch ( Exception e ) { logger . error ( \"\" , e ) ; } finally { // Clean up!\r if ( is != null ) { try { is . close ( ) ; } finally { is = null ; } } } } else if ( ( descriptorXML = duWrapper . getEntry ( \"META-INF/profile-spec-jar.xml\" ) ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing Profile Specification Descriptor.\" ) ; } InputStream is = null ; try { // Get the InputStream\r is = descriptorXML . openStream ( ) ; // Parse the descriptor using the factory\r ProfileSpecificationDescriptorFactory psdf = componentDescriptorFactory . getProfileSpecificationDescriptorFactory ( ) ; List < ? extends ProfileSpecificationDescriptor > psDescriptors = psdf . parse ( is ) ; // Get a list of the profile specifications in the\r // deployable unit.\r if ( psDescriptors . isEmpty ( ) ) { logger . warn ( \"The \" + duWrapper . getFileName ( ) + \" deployment descriptor contains no profile-spec definitions\" ) ; return null ; } // Iterate through the profile spec nodes\r for ( ProfileSpecificationDescriptor psDescriptor : psDescriptors ) { DeployableComponent dc = new DeployableComponent ( this , sleeContainerDeployer ) ; // Set Component Type\r dc . componentType = PROFILESPEC_COMPONENT ; // Get the Component ID\r dc . componentID = psDescriptor . getProfileSpecificationID ( ) ; // Get the Component Key\r dc . componentKey = getComponentIdAsString ( dc . componentID ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Component ID: \" + dc . componentKey ) ; logger . trace ( \"------------------------------ Dependencies ------------------------------\" ) ; } // Get the set of this sbb dependencies\r Set < ComponentID > psDependencies = psDescriptor . getDependenciesSet ( ) ; // Iterate through dependencies set\r for ( ComponentID dependencyId : psDependencies ) { // Add the dependency\r dc . dependencies . add ( getComponentIdAsString ( dependencyId ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( getComponentIdAsString ( dependencyId ) ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"--------------------------- End of Dependencies --------------------------\" ) ; } deployableComponents . add ( dc ) ; } } catch ( Exception e ) { logger . error ( \"\" , e ) ; } finally { // Clean up!\r if ( is != null ) { try { is . close ( ) ; } finally { is = null ; } } } } else if ( ( descriptorXML = duWrapper . getEntry ( \"META-INF/event-jar.xml\" ) ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing Event Definition Descriptor.\" ) ; } InputStream is = null ; try { // Get the InputStream\r is = descriptorXML . openStream ( ) ; // Parse the descriptor using the factory\r EventTypeDescriptorFactory etdf = componentDescriptorFactory . getEventTypeDescriptorFactory ( ) ; List < ? extends EventTypeDescriptor > etDescriptors = etdf . parse ( is ) ; if ( etDescriptors == null || etDescriptors . isEmpty ( ) ) { logger . warn ( \"The \" + duWrapper . getFileName ( ) + \" deployment descriptor contains no event-type definitions\" ) ; return null ; } for ( EventTypeDescriptor etDescriptor : etDescriptors ) { DeployableComponent dc = new DeployableComponent ( this , sleeContainerDeployer ) ; // Set Component Type\r dc . componentType = EVENTTYPE_COMPONENT ; // Get the Component ID\r dc . componentID = etDescriptor . getEventTypeID ( ) ; // Get the Component Key\r dc . componentKey = getComponentIdAsString ( dc . componentID ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Component ID: \" + dc . componentKey ) ; logger . trace ( \"------------------------------ Dependencies ------------------------------\" ) ; } // Get the set of this sbb dependencies\r Set < ComponentID > etDependencies = etDescriptor . getDependenciesSet ( ) ; // Iterate through dependencies set\r for ( ComponentID dependencyId : etDependencies ) { // Add the dependency\r dc . dependencies . add ( getComponentIdAsString ( dependencyId ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( getComponentIdAsString ( dependencyId ) ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"--------------------------- End of Dependencies --------------------------\" ) ; } deployableComponents . add ( dc ) ; } } catch ( Exception e ) { logger . error ( \"\" , e ) ; } finally { // Clean up!\r if ( is != null ) { try { is . close ( ) ; } finally { is = null ; } } } } else if ( ( descriptorXML = duWrapper . getEntry ( \"META-INF/resource-adaptor-type-jar.xml\" ) ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing Resource Adaptor Type Descriptor.\" ) ; } InputStream is = null ; try { // Get the InputStream\r is = descriptorXML . openStream ( ) ; // Parse the descriptor using the factory\r ResourceAdaptorTypeDescriptorFactory ratdf = componentDescriptorFactory . getResourceAdaptorTypeDescriptorFactory ( ) ; List < ? extends ResourceAdaptorTypeDescriptor > ratDescriptors = ratdf . parse ( is ) ; if ( ratDescriptors == null || ratDescriptors . isEmpty ( ) ) { logger . warn ( \"The \" + duWrapper . getFileName ( ) + \" deployment descriptor contains no resource-adaptor-type definitions\" ) ; return null ; } // Go through all the Resource Adaptor Type Elements\r for ( ResourceAdaptorTypeDescriptor ratDescriptor : ratDescriptors ) { DeployableComponent dc = new DeployableComponent ( this , sleeContainerDeployer ) ; // Set Component Type\r dc . componentType = RATYPE_COMPONENT ; // Get the Component ID\r dc . componentID = ratDescriptor . getResourceAdaptorTypeID ( ) ; // Get the Component Key\r dc . componentKey = getComponentIdAsString ( dc . componentID ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Component ID: \" + dc . componentKey ) ; logger . trace ( \"------------------------------ Dependencies ------------------------------\" ) ; } // Get the set of this sbb dependencies\r Set < ComponentID > ratDependencies = ratDescriptor . getDependenciesSet ( ) ; // Iterate through dependencies set\r for ( ComponentID dependencyId : ratDependencies ) { // Add the dependency\r dc . dependencies . add ( getComponentIdAsString ( dependencyId ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( getComponentIdAsString ( dependencyId ) ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"--------------------------- End of Dependencies --------------------------\" ) ; } deployableComponents . add ( dc ) ; } } catch ( Exception e ) { logger . error ( \"\" , e ) ; } finally { // Clean up!\r if ( is != null ) { try { is . close ( ) ; } finally { is = null ; } } } } else if ( ( descriptorXML = duWrapper . getEntry ( \"META-INF/resource-adaptor-jar.xml\" ) ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing Resource Adaptor Descriptor.\" ) ; } InputStream is = null ; try { // Get the InputStream\r is = descriptorXML . openStream ( ) ; // Parse the descriptor using the factory\r ResourceAdaptorDescriptorFactory radf = componentDescriptorFactory . getResourceAdaptorDescriptorFactory ( ) ; List < ? extends ResourceAdaptorDescriptor > raDescriptors = radf . parse ( is ) ; DeployConfigParser sleeDeployConfigParser = sleeContainerDeployer . getSLEEDeployConfigParser ( ) ; // Go through all the Resource Adaptor Elements\r for ( ResourceAdaptorDescriptor raDescriptor : raDescriptors ) { DeployableComponent dc = new DeployableComponent ( this , sleeContainerDeployer ) ; // Set Component Type\r dc . componentType = RA_COMPONENT ; // Set the Component ID\r dc . componentID = raDescriptor . getResourceAdaptorID ( ) ; // Set the Component Key\r dc . componentKey = getComponentIdAsString ( dc . componentID ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Component ID: \" + dc . componentKey ) ; logger . trace ( \"------------------------------ Dependencies ------------------------------\" ) ; } // Get the set of this sbb dependencies\r Set < ComponentID > raDependencies = raDescriptor . getDependenciesSet ( ) ; // Iterate through dependencies set\r for ( ComponentID dependencyId : raDependencies ) { // Add the dependency\r dc . dependencies . add ( getComponentIdAsString ( dependencyId ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( getComponentIdAsString ( dependencyId ) ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"--------------------------- End of Dependencies --------------------------\" ) ; } // get management actions for this ra, in SLEE's deploy config\r if ( sleeDeployConfigParser != null ) { Collection < ManagementAction > managementActions = sleeDeployConfigParser . getPostInstallActions ( ) . get ( dc . getComponentKey ( ) ) ; if ( managementActions != null ) { dc . installActions . addAll ( managementActions ) ; } managementActions = sleeDeployConfigParser . getPreUninstallActions ( ) . get ( dc . getComponentKey ( ) ) ; if ( managementActions != null ) { dc . uninstallActions . addAll ( managementActions ) ; } } deployableComponents . add ( dc ) ; } } catch ( Exception e ) { logger . error ( \"\" , e ) ; } finally { // Clean up!\r if ( is != null ) { try { is . close ( ) ; } finally { is = null ; } } } } else if ( ( descriptorXML = duWrapper . getEntry ( \"META-INF/library-jar.xml\" ) ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Parsing Library Descriptor.\" ) ; } InputStream is = null ; try { // Get the InputStream\r is = descriptorXML . openStream ( ) ; // Parse the descriptor using the factory\r LibraryDescriptorFactory ldf = componentDescriptorFactory . getLibraryDescriptorFactory ( ) ; List < ? extends LibraryDescriptor > libraryDescriptors = ldf . parse ( is ) ; // Go through all the Resource Adaptor Elements\r for ( LibraryDescriptor libraryDescriptor : libraryDescriptors ) { DeployableComponent dc = new DeployableComponent ( this , sleeContainerDeployer ) ; // Set Component Type\r dc . componentType = LIBRARY_COMPONENT ; // Set the Component ID\r dc . componentID = libraryDescriptor . getLibraryID ( ) ; // Set the Component Key\r dc . componentKey = getComponentIdAsString ( dc . componentID ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Component ID: \" + dc . componentKey ) ; logger . trace ( \"------------------------------ Dependencies ------------------------------\" ) ; } // Get the set of this sbb dependencies\r Set < ComponentID > libraryDependencies = libraryDescriptor . getDependenciesSet ( ) ; // Iterate through dependencies set\r for ( ComponentID dependencyId : libraryDependencies ) { // Add the dependency\r dc . dependencies . add ( getComponentIdAsString ( dependencyId ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( getComponentIdAsString ( dependencyId ) ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"--------------------------- End of Dependencies --------------------------\" ) ; } deployableComponents . add ( dc ) ; } } catch ( Exception e ) { logger . error ( \"\" , e ) ; } finally { // Clean up!\r if ( is != null ) { try { is . close ( ) ; } finally { is = null ; } } } } else { logger . warn ( \"\\r\\n--------------------------------------------------------------------------------\\r\\n\" + \"No Component Descriptor found in '\" + duWrapper . getFileName ( ) + \"'.\\r\\n\" + \"--------------------------------------------------------------------------------\" ) ; return new ArrayList < DeployableComponent > ( ) ; } } finally { } return deployableComponents ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AddressPlan< / code > object from an integer value . [CODESPLIT] public static AddressPlan fromInt ( int plan ) throws IllegalArgumentException { switch ( plan ) { case ADDRESS_PLAN_NOT_PRESENT : return NOT_PRESENT ; case ADDRESS_PLAN_UNDEFINED : return UNDEFINED ; case ADDRESS_PLAN_IP : return IP ; case ADDRESS_PLAN_MULTICAST : return MULTICAST ; case ADDRESS_PLAN_UNICAST : return UNICAST ; case ADDRESS_PLAN_E164 : return E164 ; case ADDRESS_PLAN_AESA : return AESA ; case ADDRESS_PLAN_URI : return URI ; case ADDRESS_PLAN_NSAP : return NSAP ; case ADDRESS_PLAN_SMTP : return SMTP ; case ADDRESS_PLAN_X400 : return X400 ; case ADDRESS_PLAN_SIP : return SIP ; case ADDRESS_PLAN_E164_MOBILE : return E164_MOBILE ; case ADDRESS_PLAN_H323 : return H323 ; case ADDRESS_PLAN_GT : return GT ; case ADDRESS_PLAN_SSN : return SSN ; case ADDRESS_PLAN_SLEE_PROFILE_TABLE : return SLEE_PROFILE_TABLE ; case ADDRESS_PLAN_SLEE_PROFILE : return SLEE_PROFILE ; default : throw new IllegalArgumentException ( \"Invalid address plan: \" + plan ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AddressPlan< / code > object from a string value . [CODESPLIT] public static AddressPlan fromString ( String plan ) throws NullPointerException , IllegalArgumentException { if ( plan == null ) throw new NullPointerException ( \"plan is null\" ) ; if ( plan . equalsIgnoreCase ( NOT_PRESENT_STRING ) ) return NOT_PRESENT ; if ( plan . equalsIgnoreCase ( UNDEFINED_STRING ) ) return UNDEFINED ; if ( plan . equalsIgnoreCase ( IP_STRING ) ) return IP ; if ( plan . equalsIgnoreCase ( MULTICAST_STRING ) ) return MULTICAST ; if ( plan . equalsIgnoreCase ( UNICAST_STRING ) ) return UNICAST ; if ( plan . equalsIgnoreCase ( E164_STRING ) ) return E164 ; if ( plan . equalsIgnoreCase ( AESA_STRING ) ) return AESA ; if ( plan . equalsIgnoreCase ( URI_STRING ) ) return URI ; if ( plan . equalsIgnoreCase ( NSAP_STRING ) ) return NSAP ; if ( plan . equalsIgnoreCase ( SMTP_STRING ) ) return SMTP ; if ( plan . equalsIgnoreCase ( X400_STRING ) ) return X400 ; if ( plan . equalsIgnoreCase ( SIP_STRING ) ) return SIP ; if ( plan . equalsIgnoreCase ( E164_MOBILE_STRING ) ) return E164_MOBILE ; if ( plan . equalsIgnoreCase ( H323_STRING ) ) return H323 ; if ( plan . equalsIgnoreCase ( GT_STRING ) ) return GT ; if ( plan . equalsIgnoreCase ( SSN_STRING ) ) return SSN ; if ( plan . equalsIgnoreCase ( SLEE_PROFILE_TABLE_STRING ) ) return SLEE_PROFILE_TABLE ; if ( plan . equalsIgnoreCase ( SLEE_PROFILE_STRING ) ) return SLEE_PROFILE ; throw new IllegalArgumentException ( \"Invalid address plan: \" + plan ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public TimerID setTimer ( ActivityContextInterface aci , Address address , long startTime , TimerOptions timerOptions ) throws NullPointerException , IllegalArgumentException , FacilityException { return setTimer ( aci , address , startTime , Long . MAX_VALUE , 1 , timerOptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public TimerID setTimer ( ActivityContextInterface aci , Address address , long startTime , long period , int numRepetitions , TimerOptions timerOptions ) throws NullPointerException , IllegalArgumentException , TransactionRolledbackLocalException , FacilityException { if ( aci == null ) throw new NullPointerException ( \"Null ActivityContextInterface\" ) ; if ( startTime < 0 ) throw new IllegalArgumentException ( \"startTime < 0\" ) ; if ( period <= 0 ) throw new IllegalArgumentException ( \"period <= 0\" ) ; if ( timerOptions == null ) throw new NullPointerException ( \"Null TimerOptions\" ) ; if ( timerOptions . getTimeout ( ) > period ) throw new IllegalArgumentException ( \"timeout > period\" ) ; if ( timerOptions . getTimeout ( ) < this . getResolution ( ) ) timerOptions . setTimeout ( Math . min ( period , this . getResolution ( ) ) ) ; if ( period == Long . MAX_VALUE && numRepetitions == 1 ) { // non periodic value, the framework expects it to be negative instead\r period = - 1 ; } // when numRepetitions == 0 the timer repeats infinitely or until\r // canceled\r if ( numRepetitions < 0 ) throw new IllegalArgumentException ( \"numRepetitions < 0\" ) ; SleeTransactionManager txMgr = sleeContainer . getTransactionManager ( ) ; boolean startedTx = txMgr . requireTransaction ( ) ; TimerIDImpl timerID = new TimerIDImpl ( sleeContainer . getUuidGenerator ( ) . createUUID ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"setTimer: timerID = \" + timerID + \" , startTime = \" + startTime + \" period = \" + period + \" numRepetitions = \" + numRepetitions + \" timeroptions =\" + timerOptions ) ; } // Attach to activity context\r org . mobicents . slee . container . activity . ActivityContextInterface aciImpl = ( org . mobicents . slee . container . activity . ActivityContextInterface ) aci ; aciImpl . getActivityContext ( ) . attachTimer ( timerID ) ; // schedule timer task\r TimerFacilityTimerTaskData taskData = new TimerFacilityTimerTaskData ( timerID , aciImpl . getActivityContext ( ) . getActivityContextHandle ( ) , address , startTime , period , numRepetitions , timerOptions ) ; final TimerFacilityTimerTask task = new TimerFacilityTimerTask ( taskData ) ; if ( configuration . getTaskExecutionWaitsForTxCommitConfirmation ( ) ) { final CountDownLatch countDownLatch = new CountDownLatch ( 1 ) ; task . setCountDownLatch ( countDownLatch ) ; TransactionalAction action = new TransactionalAction ( ) { @ Override public void execute ( ) { countDownLatch . countDown ( ) ; } } ; TransactionContext txContext = txMgr . getTransactionContext ( ) ; txContext . getAfterCommitActions ( ) . add ( action ) ; txContext . getAfterRollbackActions ( ) . add ( action ) ; } scheduler . schedule ( task ) ; // If we started a tx for this operation, we commit it now\r if ( startedTx ) { try { txMgr . commit ( ) ; } catch ( Exception e ) { throw new TransactionRolledbackLocalException ( \"Failed to commit transaction\" ) ; } } return timerID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void cancelTimer ( TimerID timerID ) throws NullPointerException , TransactionRolledbackLocalException , FacilityException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"cancelTimer: timerID = \" + timerID ) ; } if ( timerID == null ) throw new NullPointerException ( \"Null TimerID\" ) ; SleeTransactionManager txMgr = sleeContainer . getTransactionManager ( ) ; boolean terminateTx = txMgr . requireTransaction ( ) ; boolean doRollback = true ; try { cancelTimer ( timerID , true ) ; doRollback = false ; } finally { try { txMgr . requireTransactionEnd ( terminateTx , doRollback ) ; } catch ( Throwable e ) { throw new TransactionRolledbackLocalException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ActivityContextInterface getActivityContextInterface ( TimerID timerID ) throws NullPointerException , TransactionRequiredLocalException , FacilityException { if ( timerID == null ) { throw new NullPointerException ( \"null timerID\" ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; TimerFacilityTimerTaskData taskData = ( TimerFacilityTimerTaskData ) scheduler . getTimerTaskData ( timerID ) ; if ( taskData != null ) { try { return sleeContainer . getActivityContextFactory ( ) . getActivityContext ( taskData . getActivityContextHandle ( ) ) . getActivityContextInterface ( ) ; } catch ( Exception e ) { throw new FacilityException ( e . getMessage ( ) , e ) ; } } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the specified notification should be delivered to notification listeners using this notification filter . [CODESPLIT] public boolean isNotificationEnabled ( Notification notification ) { if ( ! ( notification instanceof AlarmNotification ) ) return false ; if ( minLevel_10 != null ) { // SLEE 1.0 comparison Level alarmLevel = ( ( AlarmNotification ) notification ) . getLevel ( ) ; return alarmLevel != null && ! minLevel_10 . isHigherLevel ( alarmLevel ) ; } else { // SLEE 1.1 comparison AlarmLevel alarmLevel = ( ( AlarmNotification ) notification ) . getAlarmLevel ( ) ; return alarmLevel != null && ! minLevel_11 . isHigherLevel ( alarmLevel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a list of { [CODESPLIT] public List < SbbDescriptorImpl > parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; List < SbbDescriptorImpl > result = new ArrayList < SbbDescriptorImpl > ( ) ; boolean isSlee11 = false ; MSbbJar mSbbJar = null ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee . sbb . SbbJar ) { mSbbJar = new MSbbJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee . sbb . SbbJar ) jaxbPojo ) ; } else if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . sbb . SbbJar ) { mSbbJar = new MSbbJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . sbb . SbbJar ) jaxbPojo ) ; isSlee11 = true ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } MSecurityPermissions mSbbJarSecurityPermissions = mSbbJar . getSecurityPermissions ( ) ; for ( MSbb mSbb : mSbbJar . getSbb ( ) ) { result . add ( new SbbDescriptorImpl ( mSbb , mSbbJarSecurityPermissions , isSlee11 ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TMP DEV METHODS [CODESPLIT] private TreeItem doTree ( FQDNNode localRoot ) { TreeItem localLeaf = new TreeItem ( ) ; LogTreeNode logTreeNode = new LogTreeNode ( browseContainer , localRoot . getShortName ( ) , localRoot . getFqdName ( ) , localRoot . isWasLeaf ( ) , this ) ; localLeaf . setWidget ( logTreeNode ) ; if ( localRoot . getChildren ( ) . size ( ) > 0 ) { Tree t = new Tree ( ) ; ArrayList names = new ArrayList ( localRoot . getChildrenNames ( ) ) ; Collections . sort ( names ) ; Iterator it = names . iterator ( ) ; while ( it . hasNext ( ) ) { t . addItem ( doTree ( localRoot . getChild ( ( String ) it . next ( ) ) ) ) ; } localLeaf . addItem ( t ) ; } return localLeaf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { serviceID = new ServiceID ( in . readUTF ( ) , in . readUTF ( ) , in . readUTF ( ) ) ; convergenceName = in . readUTF ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { out . writeUTF ( serviceID . getName ( ) ) ; out . writeUTF ( serviceID . getVendor ( ) ) ; out . writeUTF ( serviceID . getVersion ( ) ) ; out . writeUTF ( convergenceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void serviceInstall ( ServiceComponent serviceComponent ) { // create object pools for ( SbbID sbbID : serviceComponent . getSbbIDs ( sleeContainer . getComponentRepository ( ) ) ) { // create the pool for the given SbbID sbbPoolManagement . createObjectPool ( serviceComponent . getServiceID ( ) , sleeContainer . getComponentRepository ( ) . getComponentByID ( sbbID ) , sleeContainer . getTransactionManager ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void serviceUninstall ( ServiceComponent serviceComponent ) { // remove sbb object pools for ( SbbID sbbID : serviceComponent . getSbbIDs ( sleeContainer . getComponentRepository ( ) ) ) { // remove the pool for the given SbbID sbbPoolManagement . removeObjectPool ( serviceComponent . getServiceID ( ) , sleeContainer . getComponentRepository ( ) . getComponentByID ( sbbID ) , sleeContainer . getTransactionManager ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SbbObjectPoolImpl getObjectPool ( ServiceID serviceID , SbbID sbbID ) { return sbbPoolManagement . getObjectPool ( serviceID , sbbID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void installSbb ( final SbbComponent sbbComponent ) throws Exception { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Installing \" + sbbComponent ) ; } final SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; sleeTransactionManager . mandateTransaction ( ) ; // change classloader ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( sbbComponent . getClassLoader ( ) ) ; // Set up the comp/env naming context for the Sbb. JndiManagement jndiManagement = sleeContainer . getJndiManagement ( ) ; jndiManagement . componentInstall ( sbbComponent ) ; jndiManagement . pushJndiContext ( sbbComponent ) ; try { setupSbbEnvironment ( sbbComponent ) ; } finally { jndiManagement . popJndiContext ( ) ; } // generate class code for the sbb new SbbClassCodeGenerator ( ) . process ( sbbComponent ) ; //FIXME: this will erase stack trace.\t //} catch (Exception ex) { //\tthrow ex; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } // Set 1.0 Trace to off sleeContainer . getTraceManagement ( ) . getTraceFacility ( ) . setTraceLevelOnTransaction ( sbbComponent . getSbbID ( ) , Level . OFF ) ; sleeContainer . getAlarmManagement ( ) . registerComponent ( sbbComponent . getSbbID ( ) ) ; // if we are in cluster mode we need to add the sbb class loader domain to the replication class loader if ( ! sleeContainer . getCluster ( ) . getMobicentsCache ( ) . isLocalMode ( ) ) { final ReplicationClassLoader replicationClassLoader = sleeContainer . getReplicationClassLoader ( ) ; replicationClassLoader . addDomain ( sbbComponent . getClassLoaderDomain ( ) ) ; TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { replicationClassLoader . removeDomain ( sbbComponent . getClassLoaderDomain ( ) ) ; } } ; sleeTransactionManager . getTransactionContext ( ) . getAfterRollbackActions ( ) . add ( action ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void uninstallSbb ( final SbbComponent sbbComponent ) throws SystemException , Exception , NamingException { final SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; sleeTransactionManager . mandateTransaction ( ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( \"Uninstalling \" + sbbComponent ) ; // remove sbb from trace and alarm facilities sleeContainer . getTraceManagement ( ) . getTraceFacility ( ) . unSetTraceLevel ( sbbComponent . getSbbID ( ) ) ; sleeContainer . getAlarmManagement ( ) . unRegisterComponent ( sbbComponent . getSbbID ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Removed SBB \" + sbbComponent . getSbbID ( ) + \" from trace and alarm facilities\" ) ; } sleeContainer . getJndiManagement ( ) . componentUninstall ( sbbComponent ) ; // if we are in cluster mode we need to remove the sbb class loader domain from the replication class loader if ( ! sleeContainer . getCluster ( ) . getMobicentsCache ( ) . isLocalMode ( ) ) { final ReplicationClassLoader replicationClassLoader = sleeContainer . getReplicationClassLoader ( ) ; TransactionalAction action2 = new TransactionalAction ( ) { public void execute ( ) { replicationClassLoader . removeDomain ( sbbComponent . getClassLoaderDomain ( ) ) ; } } ; sleeTransactionManager . getTransactionContext ( ) . getAfterCommitActions ( ) . add ( action2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified sbb entity but without changing to sbb s class loader first . [CODESPLIT] private void removeSbbEntityWithCurrentClassLoader ( final SbbEntity sbbEntity ) { // remove entity\r sbbEntity . remove ( ) ; // remove from tx data\r final TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; final SbbEntityID sbbEntityID = sbbEntity . getSbbEntityId ( ) ; txContext . getData ( ) . remove ( sbbEntityID ) ; // if sbb entity is root add a tx action to ensure lock is removed\r if ( sbbEntityID . isRootSbbEntity ( ) ) { TransactionalAction txAction = new TransactionalAction ( ) { @ Override public void execute ( ) { lockFacility . remove ( sbbEntityID ) ; } } ; txContext . getAfterCommitActions ( ) . add ( txAction ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public DeployableUnitID install ( String url ) throws NullPointerException , MalformedURLException , AlreadyDeployedException , DeploymentException , ManagementException { try { final SleeContainer sleeContainer = getSleeContainer ( ) ; final DeployableUnitBuilder deployableUnitBuilder = sleeContainer . getDeployableUnitManagement ( ) . getDeployableUnitBuilder ( ) ; final SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; final ComponentRepository componentRepositoryImpl = sleeContainer . getComponentRepository ( ) ; final DeployableUnitManagement deployableUnitManagement = sleeContainer . getDeployableUnitManagement ( ) ; synchronized ( sleeContainer . getManagementMonitor ( ) ) { DeployableUnitID deployableUnitID = new DeployableUnitID ( url ) ; logger . info ( \"Installing \" + deployableUnitID ) ; if ( deployableUnitManagement . getDeployableUnit ( deployableUnitID ) != null ) { throw new AlreadyDeployedException ( \"there is already a DU deployed for url \" + url ) ; } DeployableUnit deployableUnit = null ; Thread currentThread = Thread . currentThread ( ) ; ClassLoader currentClassLoader = currentThread . getContextClassLoader ( ) ; Set < SleeComponent > componentsInstalled = new HashSet < SleeComponent > ( ) ; boolean rollback = true ; try { // start transaction sleeTransactionManager . begin ( ) ; // build du deployableUnit = deployableUnitBuilder . build ( url , tempDUJarsDeploymentRoot , componentRepositoryImpl ) ; // install each component built for ( LibraryComponent component : deployableUnit . getLibraryComponents ( ) . values ( ) ) { componentRepositoryImpl . putComponent ( component ) ; updateSecurityPermissions ( component , false ) ; logger . info ( \"Installed \" + component ) ; } for ( EventTypeComponent component : deployableUnit . getEventTypeComponents ( ) . values ( ) ) { componentRepositoryImpl . putComponent ( component ) ; logger . info ( \"Installed \" + component ) ; } for ( ResourceAdaptorTypeComponent component : deployableUnit . getResourceAdaptorTypeComponents ( ) . values ( ) ) { componentRepositoryImpl . putComponent ( component ) ; currentThread . setContextClassLoader ( component . getClassLoader ( ) ) ; sleeContainer . getResourceManagement ( ) . installResourceAdaptorType ( component ) ; componentsInstalled . add ( component ) ; logger . info ( \"Installed \" + component ) ; } // before executing the logic to install an profile spec, ra // or sbb insert the components in the repo, a component can // require that another is already in repo for ( ProfileSpecificationComponent component : deployableUnit . getProfileSpecificationComponents ( ) . values ( ) ) { componentRepositoryImpl . putComponent ( component ) ; } for ( ResourceAdaptorComponent component : deployableUnit . getResourceAdaptorComponents ( ) . values ( ) ) { componentRepositoryImpl . putComponent ( component ) ; } for ( SbbComponent component : deployableUnit . getSbbComponents ( ) . values ( ) ) { componentRepositoryImpl . putComponent ( component ) ; } // run the install logic to install an profile spec, ra or // sbb for ( ProfileSpecificationComponent component : deployableUnit . getProfileSpecificationComponents ( ) . values ( ) ) { currentThread . setContextClassLoader ( component . getClassLoader ( ) ) ; sleeContainer . getSleeProfileTableManager ( ) . installProfileSpecification ( component ) ; componentsInstalled . add ( component ) ; updateSecurityPermissions ( component , false ) ; logger . info ( \"Installed \" + component ) ; } for ( ResourceAdaptorComponent component : deployableUnit . getResourceAdaptorComponents ( ) . values ( ) ) { currentThread . setContextClassLoader ( component . getClassLoader ( ) ) ; sleeContainer . getResourceManagement ( ) . installResourceAdaptor ( component ) ; componentsInstalled . add ( component ) ; updateSecurityPermissions ( component , false ) ; logger . info ( \"Installed \" + component ) ; } for ( SbbComponent component : deployableUnit . getSbbComponents ( ) . values ( ) ) { currentThread . setContextClassLoader ( component . getClassLoader ( ) ) ; sleeContainer . getSbbManagement ( ) . installSbb ( component ) ; componentsInstalled . add ( component ) ; updateSecurityPermissions ( component , false ) ; logger . info ( \"Installed \" + component ) ; } // finally install the services currentThread . setContextClassLoader ( currentClassLoader ) ; for ( ServiceComponent component : deployableUnit . getServiceComponents ( ) . values ( ) ) { componentRepositoryImpl . putComponent ( component ) ; sleeContainer . getServiceManagement ( ) . installService ( component ) ; componentsInstalled . add ( component ) ; logger . info ( \"Installed \" + component + \". Root sbb is \" + component . getRootSbbComponent ( ) ) ; } deployableUnitManagement . addDeployableUnit ( deployableUnit ) ; logger . info ( \"Installed \" + deployableUnitID ) ; updateSecurityPermissions ( null , true ) ; rollback = false ; return deployableUnitID ; } finally { currentThread . setContextClassLoader ( currentClassLoader ) ; try { if ( rollback ) { if ( deployableUnit != null ) { // remove all components added to repo // put all components in the repo again for ( LibraryComponent component : deployableUnit . getLibraryComponents ( ) . values ( ) ) { removeSecurityPermissions ( component , false ) ; componentRepositoryImpl . removeComponent ( component . getLibraryID ( ) ) ; logger . info ( \"Uninstalled \" + component + \" due to tx rollback\" ) ; } for ( EventTypeComponent component : deployableUnit . getEventTypeComponents ( ) . values ( ) ) { componentRepositoryImpl . removeComponent ( component . getEventTypeID ( ) ) ; logger . info ( \"Uninstalled \" + component + \" due to tx rollback\" ) ; } for ( ResourceAdaptorTypeComponent component : deployableUnit . getResourceAdaptorTypeComponents ( ) . values ( ) ) { removeSecurityPermissions ( component , false ) ; if ( componentsInstalled . contains ( component ) ) { sleeContainer . getResourceManagement ( ) . uninstallResourceAdaptorType ( component ) ; } componentRepositoryImpl . removeComponent ( component . getResourceAdaptorTypeID ( ) ) ; logger . info ( \"Uninstalled \" + component + \" due to tx rollback\" ) ; } for ( ProfileSpecificationComponent component : deployableUnit . getProfileSpecificationComponents ( ) . values ( ) ) { if ( componentsInstalled . contains ( component ) ) { sleeContainer . getSleeProfileTableManager ( ) . uninstallProfileSpecification ( component ) ; } componentRepositoryImpl . removeComponent ( component . getProfileSpecificationID ( ) ) ; logger . info ( \"Uninstalled \" + component + \" due to tx rollback\" ) ; } for ( ResourceAdaptorComponent component : deployableUnit . getResourceAdaptorComponents ( ) . values ( ) ) { removeSecurityPermissions ( component , false ) ; if ( componentsInstalled . contains ( component ) ) { sleeContainer . getResourceManagement ( ) . uninstallResourceAdaptor ( component ) ; } componentRepositoryImpl . removeComponent ( component . getResourceAdaptorID ( ) ) ; logger . info ( \"Uninstalled \" + component + \" due to tx rollback\" ) ; } for ( SbbComponent component : deployableUnit . getSbbComponents ( ) . values ( ) ) { removeSecurityPermissions ( component , false ) ; if ( componentsInstalled . contains ( component ) ) { sleeContainer . getSbbManagement ( ) . uninstallSbb ( component ) ; } componentRepositoryImpl . removeComponent ( component . getSbbID ( ) ) ; logger . info ( \"Uninstalled \" + component + \" due to tx rollback\" ) ; } for ( ServiceComponent component : deployableUnit . getServiceComponents ( ) . values ( ) ) { if ( componentsInstalled . contains ( component ) ) { sleeContainer . getServiceManagement ( ) . uninstallService ( component ) ; } componentRepositoryImpl . removeComponent ( component . getServiceID ( ) ) ; logger . info ( \"Uninstalled \" + component + \" due to tx rollback\" ) ; } removeSecurityPermissions ( null , true ) ; // undeploy the unit deployableUnit . undeploy ( ) ; } sleeTransactionManager . rollback ( ) ; } else { sleeTransactionManager . commit ( ) ; } } catch ( Exception ex ) { throw new ManagementException ( \"Exception while completing transaction\" , ex ) ; } } } } catch ( AlreadyDeployedException e ) { throw e ; } catch ( DeploymentException e ) { // This will remove stack trace; // throw e; throw new DeploymentException ( \"Failure encountered during deploy process.\" , e ) ; } catch ( Throwable e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( e . getMessage ( ) , e ) ; } throw new ManagementException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void uninstall ( DeployableUnitID deployableUnitID ) throws NullPointerException , UnrecognizedDeployableUnitException , DependencyException , InvalidStateException , ManagementException { logger . info ( \"Uninstalling \" + deployableUnitID ) ; final SleeContainer sleeContainer = getSleeContainer ( ) ; final SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; final ServiceManagement serviceManagement = sleeContainer . getServiceManagement ( ) ; final ResourceManagement resourceManagement = sleeContainer . getResourceManagement ( ) ; final DeployableUnitManagement deployableUnitManagement = sleeContainer . getDeployableUnitManagement ( ) ; final ComponentRepository componentRepositoryImpl = sleeContainer . getComponentRepository ( ) ; // we sync on the container's monitor object synchronized ( sleeContainer . getManagementMonitor ( ) ) { if ( this . isInstalled ( deployableUnitID ) ) { Thread currentThread = Thread . currentThread ( ) ; ClassLoader currentClassLoader = currentThread . getContextClassLoader ( ) ; DeployableUnit deployableUnit = null ; boolean rollback = true ; try { // start transaction sleeTransactionManager . begin ( ) ; // get du deployableUnit = deployableUnitManagement . getDeployableUnit ( deployableUnitID ) ; // Check if its safe to remove the deployable unit. for ( SleeComponent sleeComponent : deployableUnit . getDeployableUnitComponents ( ) ) { for ( SleeComponent referringComponent : sleeContainer . getComponentRepository ( ) . getReferringComponents ( sleeComponent ) ) { if ( ! referringComponent . getDeployableUnit ( ) . getDeployableUnitID ( ) . equals ( deployableUnitID ) ) { throw new DependencyException ( \"Component \" + referringComponent + \" refers DU component \" + sleeComponent ) ; } } } for ( ServiceComponent component : deployableUnit . getServiceComponents ( ) . values ( ) ) { serviceManagement . uninstallService ( component ) ; componentRepositoryImpl . removeComponent ( component . getServiceID ( ) ) ; logger . info ( \"Uninstalled \" + component ) ; } for ( SbbComponent component : deployableUnit . getSbbComponents ( ) . values ( ) ) { currentThread . setContextClassLoader ( component . getClassLoader ( ) ) ; removeSecurityPermissions ( component , false ) ; sleeContainer . getSbbManagement ( ) . uninstallSbb ( component ) ; componentRepositoryImpl . removeComponent ( component . getSbbID ( ) ) ; logger . info ( \"Uninstalled \" + component ) ; } for ( ResourceAdaptorComponent component : deployableUnit . getResourceAdaptorComponents ( ) . values ( ) ) { removeSecurityPermissions ( component , false ) ; resourceManagement . uninstallResourceAdaptor ( component ) ; componentRepositoryImpl . removeComponent ( component . getResourceAdaptorID ( ) ) ; logger . info ( \"Uninstalled \" + component ) ; } for ( ProfileSpecificationComponent component : deployableUnit . getProfileSpecificationComponents ( ) . values ( ) ) { currentThread . setContextClassLoader ( component . getClassLoader ( ) ) ; removeSecurityPermissions ( component , false ) ; sleeContainer . getSleeProfileTableManager ( ) . uninstallProfileSpecification ( component ) ; componentRepositoryImpl . removeComponent ( component . getProfileSpecificationID ( ) ) ; logger . info ( \"Uninstalled \" + component ) ; } for ( ResourceAdaptorTypeComponent component : deployableUnit . getResourceAdaptorTypeComponents ( ) . values ( ) ) { resourceManagement . uninstallResourceAdaptorType ( component ) ; componentRepositoryImpl . removeComponent ( component . getResourceAdaptorTypeID ( ) ) ; logger . info ( \"Uninstalled \" + component ) ; } for ( EventTypeID componentID : deployableUnit . getEventTypeComponents ( ) . keySet ( ) ) { componentRepositoryImpl . removeComponent ( componentID ) ; logger . info ( \"Uninstalled \" + componentID ) ; } for ( LibraryID componentID : deployableUnit . getLibraryComponents ( ) . keySet ( ) ) { removeSecurityPermissions ( componentRepositoryImpl . getComponentByID ( componentID ) , false ) ; componentRepositoryImpl . removeComponent ( componentID ) ; logger . info ( \"Uninstalled \" + componentID ) ; } removeSecurityPermissions ( null , true ) ; // remove du deployableUnitManagement . removeDeployableUnit ( deployableUnitID ) ; rollback = false ; logger . info ( \"Uninstalled \" + deployableUnitID ) ; } catch ( InvalidStateException ex ) { logger . error ( ex . getMessage ( ) , ex ) ; throw ex ; } catch ( DependencyException ex ) { logger . error ( ex . getMessage ( ) , ex ) ; throw ex ; } catch ( Throwable ex ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( ex . getMessage ( ) , ex ) ; throw new ManagementException ( \"Exception removing deployable Unit \" , ex ) ; } finally { currentThread . setContextClassLoader ( currentClassLoader ) ; try { if ( rollback ) { if ( deployableUnit != null ) { // put all components in the repo again for ( LibraryComponent component : deployableUnit . getLibraryComponents ( ) . values ( ) ) { if ( componentRepositoryImpl . putComponent ( component ) ) { updateSecurityPermissions ( component , false ) ; logger . info ( \"Reinstalled \" + component + \" due to tx rollback\" ) ; } } for ( EventTypeComponent component : deployableUnit . getEventTypeComponents ( ) . values ( ) ) { if ( componentRepositoryImpl . putComponent ( component ) ) { logger . info ( \"Reinstalled \" + component + \" due to tx rollback\" ) ; } } for ( ResourceAdaptorTypeComponent component : deployableUnit . getResourceAdaptorTypeComponents ( ) . values ( ) ) { if ( componentRepositoryImpl . putComponent ( component ) ) { logger . info ( \"Reinstalled \" + component + \" due to tx rollback\" ) ; } } for ( ProfileSpecificationComponent component : deployableUnit . getProfileSpecificationComponents ( ) . values ( ) ) { if ( componentRepositoryImpl . putComponent ( component ) ) { updateSecurityPermissions ( component , false ) ; logger . info ( \"Reinstalled \" + component + \" due to tx rollback\" ) ; } } for ( ResourceAdaptorComponent component : deployableUnit . getResourceAdaptorComponents ( ) . values ( ) ) { if ( componentRepositoryImpl . putComponent ( component ) ) { updateSecurityPermissions ( component , false ) ; logger . info ( \"Reinstalled \" + component + \" due to tx rollback\" ) ; } } for ( SbbComponent component : deployableUnit . getSbbComponents ( ) . values ( ) ) { if ( componentRepositoryImpl . putComponent ( component ) ) { updateSecurityPermissions ( component , false ) ; logger . info ( \"Reinstalled \" + component + \" due to tx rollback\" ) ; } } for ( ServiceComponent component : deployableUnit . getServiceComponents ( ) . values ( ) ) { if ( componentRepositoryImpl . putComponent ( component ) ) { logger . info ( \"Reinstalled \" + component + \" due to tx rollback\" ) ; } } updateSecurityPermissions ( null , true ) ; deployableUnitManagement . addDeployableUnit ( deployableUnit ) ; } sleeTransactionManager . rollback ( ) ; } else { sleeTransactionManager . commit ( ) ; // FIXME: For JBoss 7.2.0.Final: // we have a problem with org.hibernate.service.UnknownServiceException: // Unknown service requested [org.hibernate.event.service.spi.EventListenerRegistry] // see https://hibernate.atlassian.net/browse/HHH-8586 for ( ProfileSpecificationComponent component : deployableUnit . getProfileSpecificationComponents ( ) . values ( ) ) { currentThread . setContextClassLoader ( component . getClassLoader ( ) ) ; removeSecurityPermissions ( component , false ) ; sleeContainer . getSleeProfileTableManager ( ) . closeEntityManagerFactory ( component ) ; logger . info ( \"Finalized \" + component ) ; } // Clean up all the class files. deployableUnit . undeploy ( ) ; } } catch ( Throwable ex ) { throw new ManagementException ( \"Exception while completing transaction\" , ex ) ; } } } else { throw new UnrecognizedDeployableUnitException ( \"deployable unit \" + deployableUnitID ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public DeployableUnitID getDeployableUnit ( String deploymentUrl ) throws NullPointerException , UnrecognizedDeployableUnitException , ManagementException { DeployableUnitID deployableUnitID = new DeployableUnitID ( deploymentUrl ) ; boolean duExists = true ; try { if ( getSleeContainer ( ) . getDeployableUnitManagement ( ) . getDeployableUnit ( deployableUnitID ) == null ) { duExists = false ; } } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } if ( duExists ) { return deployableUnitID ; } else { throw new UnrecognizedDeployableUnitException ( deploymentUrl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public DeployableUnitID [ ] getDeployableUnits ( ) throws ManagementException { try { return getSleeContainer ( ) . getDeployableUnitManagement ( ) . getDeployableUnits ( ) ; } catch ( Throwable e ) { throw new ManagementException ( \"failed to get deployable units\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SbbID [ ] getSbbs ( ) throws ManagementException { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getSbbs()\" ) ; } return getSleeContainer ( ) . getComponentRepository ( ) . getSbbIDs ( ) . toArray ( new SbbID [ 0 ] ) ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventTypeID [ ] getEventTypes ( ) throws ManagementException { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getEventTypes()\" ) ; } return getSleeContainer ( ) . getComponentRepository ( ) . getEventComponentIDs ( ) . toArray ( new EventTypeID [ 0 ] ) ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileSpecificationID [ ] getProfileSpecifications ( ) throws ManagementException { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfileSpecifications()\" ) ; } return getSleeContainer ( ) . getComponentRepository ( ) . getProfileSpecificationIDs ( ) . toArray ( new ProfileSpecificationID [ 0 ] ) ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ServiceID [ ] getServices ( ) throws ManagementException { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getServices()\" ) ; } return getSleeContainer ( ) . getComponentRepository ( ) . getServiceIDs ( ) . toArray ( new ServiceID [ 0 ] ) ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ResourceAdaptorTypeID [ ] getResourceAdaptorTypes ( ) throws ManagementException { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getResourceAdaptorTypes()\" ) ; } return getSleeContainer ( ) . getComponentRepository ( ) . getResourceAdaptorTypeIDs ( ) . toArray ( new ResourceAdaptorTypeID [ 0 ] ) ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ResourceAdaptorID [ ] getResourceAdaptors ( ) throws ManagementException { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getResourceAdaptors()\" ) ; } return getSleeContainer ( ) . getComponentRepository ( ) . getResourceAdaptorIDs ( ) . toArray ( new ResourceAdaptorID [ 0 ] ) ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ComponentID [ ] getReferringComponents ( ComponentID componentId ) throws NullPointerException , UnrecognizedComponentException , ManagementException { try { return getSleeContainer ( ) . getComponentRepository ( ) . getReferringComponents ( componentId ) ; } catch ( NullPointerException ex ) { throw ex ; } catch ( UnrecognizedComponentException ex ) { throw ex ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public DeployableUnitDescriptor getDescriptor ( DeployableUnitID deployableUnitID ) throws NullPointerException , UnrecognizedDeployableUnitException , ManagementException { if ( deployableUnitID == null ) throw new NullPointerException ( \"deployableUnitID should not be null\" ) ; DeployableUnitDescriptor dud = null ; try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getDescriptor \" + deployableUnitID ) ; } DeployableUnit du = getSleeContainer ( ) . getDeployableUnitManagement ( ) . getDeployableUnit ( deployableUnitID ) ; if ( du != null ) { dud = du . getSpecsDeployableUnitDescriptor ( ) ; } } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } if ( dud == null ) { throw new UnrecognizedDeployableUnitException ( \"unrecognized deployable unit \" + deployableUnitID ) ; } else { return dud ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public DeployableUnitDescriptor [ ] getDescriptors ( DeployableUnitID [ ] duIds ) throws NullPointerException , ManagementException { if ( duIds == null ) throw new NullPointerException ( \"Null arg!\" ) ; final DeployableUnitManagement deployableUnitManagement = getSleeContainer ( ) . getDeployableUnitManagement ( ) ; try { Set < DeployableUnitDescriptor > result = new HashSet < DeployableUnitDescriptor > ( ) ; for ( DeployableUnitID deployableUnitID : deployableUnitManagement . getDeployableUnits ( ) ) { DeployableUnit deployableUnit = deployableUnitManagement . getDeployableUnit ( deployableUnitID ) ; result . add ( deployableUnit . getSpecsDeployableUnitDescriptor ( ) ) ; } return result . toArray ( new DeployableUnitDescriptor [ 0 ] ) ; } catch ( Throwable ex ) { throw new ManagementException ( \"Error in tx manager \" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ComponentDescriptor getDescriptor ( ComponentID componentID ) throws NullPointerException , UnrecognizedComponentException , ManagementException { if ( componentID == null ) throw new NullPointerException ( \"null component ID\" ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getDescriptor: componentID \" + componentID ) ; } try { ComponentRepository componentRepositoryImpl = getSleeContainer ( ) . getComponentRepository ( ) ; SleeComponent component = null ; if ( componentID instanceof EventTypeID ) { component = componentRepositoryImpl . getComponentByID ( ( EventTypeID ) componentID ) ; } else if ( componentID instanceof LibraryID ) { component = componentRepositoryImpl . getComponentByID ( ( LibraryID ) componentID ) ; } else if ( componentID instanceof ProfileSpecificationID ) { component = componentRepositoryImpl . getComponentByID ( ( ProfileSpecificationID ) componentID ) ; } else if ( componentID instanceof ResourceAdaptorID ) { component = componentRepositoryImpl . getComponentByID ( ( ResourceAdaptorID ) componentID ) ; } else if ( componentID instanceof ResourceAdaptorTypeID ) { component = componentRepositoryImpl . getComponentByID ( ( ResourceAdaptorTypeID ) componentID ) ; } else if ( componentID instanceof SbbID ) { component = componentRepositoryImpl . getComponentByID ( ( SbbID ) componentID ) ; } else if ( componentID instanceof ServiceID ) { component = componentRepositoryImpl . getComponentByID ( ( ServiceID ) componentID ) ; } if ( component != null ) return component . getComponentDescriptor ( ) ; else return null ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ComponentDescriptor [ ] getDescriptors ( ComponentID [ ] componentIds ) throws NullPointerException , ManagementException { if ( componentIds == null ) throw new NullPointerException ( \"null component ids\" ) ; try { ComponentDescriptor [ ] descriptors = new ComponentDescriptor [ componentIds . length ] ; for ( int i = 0 ; i < descriptors . length ; i ++ ) { descriptors [ i ] = getDescriptor ( componentIds [ i ] ) ; } return descriptors ; } catch ( ManagementException ex ) { throw ex ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean isInstalled ( DeployableUnitID deployableUnitID ) throws NullPointerException , ManagementException { if ( deployableUnitID == null ) throw new NullPointerException ( \"null deployableUnitID\" ) ; try { return getSleeContainer ( ) . getDeployableUnitManagement ( ) . getDeployableUnit ( deployableUnitID ) != null ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean isInstalled ( ComponentID componentID ) throws NullPointerException , ManagementException { if ( componentID == null ) throw new NullPointerException ( \"null componentID\" ) ; try { return getSleeContainer ( ) . getComponentRepository ( ) . isInstalled ( componentID ) ; } catch ( Throwable ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int getActivitiesMapped ( ) { int result = 0 ; for ( int i = 0 ; i < getExecutors ( ) . length ; i ++ ) { result += getActivitiesMapped ( i ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int getActivitiesMapped ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getActivitiesMapped ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getAverageEventRoutingTime ( ) { long time = 0L ; long events = 0L ; for ( EventTypeID eventTypeID : eventRouter . getSleeContainer ( ) . getComponentManagement ( ) . getComponentRepository ( ) . getEventComponentIDs ( ) ) { for ( int i = 0 ; i < getExecutors ( ) . length ; i ++ ) { final EventRouterExecutorStatistics eventRouterExecutorStatistics = getEventRouterExecutorStatistics ( i ) ; if ( eventRouterExecutorStatistics != null ) { EventTypeRoutingStatistics eventTypeRoutingStatistics = eventRouterExecutorStatistics . getEventTypeRoutingStatistics ( eventTypeID ) ; if ( eventTypeRoutingStatistics != null ) { time += eventTypeRoutingStatistics . getRoutingTime ( ) ; events += eventTypeRoutingStatistics . getEventsRouted ( ) ; } } } } return time == 0L ? 0L : time / events ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getAverageEventRoutingTime ( EventTypeID eventTypeID ) { long time = 0L ; long events = 0L ; for ( int i = 0 ; i < getExecutors ( ) . length ; i ++ ) { final EventRouterExecutorStatistics eventRouterExecutorStatistics = getEventRouterExecutorStatistics ( i ) ; if ( eventRouterExecutorStatistics != null ) { EventTypeRoutingStatistics eventTypeRoutingStatistics = eventRouterExecutorStatistics . getEventTypeRoutingStatistics ( eventTypeID ) ; if ( eventTypeRoutingStatistics != null ) { time += eventTypeRoutingStatistics . getRoutingTime ( ) ; events += eventTypeRoutingStatistics . getEventsRouted ( ) ; } } } return time == 0L ? 0L : time / events ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getAverageEventRoutingTime ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getAverageEventRoutingTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getEventsRouted ( EventTypeID eventTypeID ) { long result = 0L ; for ( int i = 0 ; i < getExecutors ( ) . length ; i ++ ) { result += getEventsRouted ( i , eventTypeID ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getEventsRouted ( int executor , EventTypeID eventTypeID ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getEventsRouted ( eventTypeID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getExecutedTasks ( ) { long result = 0L ; for ( int i = 0 ; i < getExecutors ( ) . length ; i ++ ) { result += getExecutedTasks ( i ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getExecutedTasks ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getExecutedTasks ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getExecutingTime ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getExecutingTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getIdleTime ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getIdleTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getMiscTasksExecuted ( ) { long result = 0L ; for ( int i = 0 ; i < getExecutors ( ) . length ; i ++ ) { result += getMiscTasksExecuted ( i ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getMiscTasksExecuted ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getMiscTasksExecuted ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getMiscTasksExecutingTime ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getMiscTasksExecutingTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getRoutingTime ( EventTypeID eventTypeID ) { long result = 0L ; for ( int i = 0 ; i < getExecutors ( ) . length ; i ++ ) { result += getRoutingTime ( i , eventTypeID ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public int getWorkingQueueSize ( int executor ) { final EventRouterExecutorStatistics executorStats = getExecutors ( ) [ executor ] . getStatistics ( ) ; return executorStats == null ? 0 : executorStats . getWorkingQueueSize ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates if notifications are enabled for the specified parameter name [CODESPLIT] public boolean getNotificationsEnabled ( String paramName ) { Boolean areNotificationsEnabled = paramNames . get ( paramName ) ; if ( ! isSlee11 ) { if ( areNotificationsEnabled == null || areNotificationsEnabled . booleanValue ( ) ) { // considering that notifications are enabled, by default, for each // param return true ; } else { return false ; } } else { if ( areNotificationsEnabled != null && areNotificationsEnabled . booleanValue ( ) ) { // considering that notifications are enabled, by default, for each // param return true ; } else { return false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ServiceState getState ( ServiceID serviceID ) throws NullPointerException , UnrecognizedServiceException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Service.getState \" + serviceID ) ; } if ( serviceID == null ) throw new NullPointerException ( \"Null service ID!\" ) ; final ServiceComponent serviceComponent = componentRepositoryImpl . getComponentByID ( serviceID ) ; if ( serviceComponent == null ) throw new UnrecognizedServiceException ( serviceID . toString ( ) ) ; return serviceComponent . getServiceState ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ServiceID [ ] getServices ( ServiceState serviceState ) throws NullPointerException , ManagementException { if ( serviceState == null ) throw new NullPointerException ( \"Passed a null state\" ) ; try { ArrayList < ServiceID > retval = new ArrayList < ServiceID > ( ) ; for ( ServiceID serviceID : componentRepositoryImpl . getServiceIDs ( ) ) { ServiceComponent service = componentRepositoryImpl . getComponentByID ( serviceID ) ; if ( service == null ) { throw new UnrecognizedServiceException ( serviceID . toString ( ) ) ; } if ( service . getServiceState ( ) . equals ( serviceState ) ) { retval . add ( serviceID ) ; } } return retval . toArray ( new ServiceID [ retval . size ( ) ] ) ; } catch ( Exception e ) { throw new ManagementException ( \"Error getting services by state!\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the set of ra entity link names referenced by the service componen which do not exist [CODESPLIT] public Set < String > getReferencedRAEntityLinksWhichNotExists ( ServiceComponent serviceComponent ) { Set < String > result = new HashSet < String > ( ) ; Set < String > raLinkNames = sleeContainer . getResourceManagement ( ) . getLinkNamesSet ( ) ; for ( String raLink : serviceComponent . getResourceAdaptorEntityLinks ( componentRepositoryImpl ) ) { if ( ! raLinkNames . contains ( raLink ) ) { result . add ( raLink ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void activate ( ServiceID serviceID ) throws NullPointerException , UnrecognizedServiceException , InvalidStateException , InvalidLinkNameBindingStateException { activate ( serviceID , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void activate ( ServiceID [ ] serviceIDs ) throws NullPointerException , InvalidArgumentException , UnrecognizedServiceException , InvalidStateException , ManagementException { if ( serviceIDs . length == 0 ) { throw new InvalidArgumentException ( \"InvalidArgumentException\" ) ; } for ( int i = 0 ; i < serviceIDs . length ; i ++ ) { if ( serviceIDs [ i ] == null ) { throw new InvalidArgumentException ( \"InvalidArgumentException\" ) ; } } for ( int i = 0 ; i < serviceIDs . length - 1 ; i ++ ) for ( int j = i + 1 ; j < serviceIDs . length ; j ++ ) if ( serviceIDs [ i ] == ( serviceIDs [ j ] ) ) { throw new InvalidArgumentException ( \"InvalidArgumentException\" ) ; } for ( int i = 0 ; i < serviceIDs . length ; i ++ ) { activate ( serviceIDs [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void deactivate ( final ServiceID serviceID ) throws NullPointerException , UnrecognizedServiceException , InvalidStateException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Deactivating \" + serviceID ) ; } if ( serviceID == null ) throw new NullPointerException ( \"NullPointerException\" ) ; synchronized ( sleeContainer . getManagementMonitor ( ) ) { final ServiceComponent serviceComponent = componentRepositoryImpl . getComponentByID ( serviceID ) ; if ( serviceComponent == null ) throw new UnrecognizedServiceException ( \"Service not found for \" + serviceID ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( serviceID . toString ( ) + \" state = \" + serviceComponent . getServiceState ( ) ) ; final SleeState sleeState = sleeContainer . getSleeState ( ) ; if ( serviceComponent . getServiceState ( ) == ServiceState . STOPPING ) throw new InvalidStateException ( \"Service is STOPPING\" ) ; if ( serviceComponent . getServiceState ( ) == ServiceState . INACTIVE ) { throw new InvalidStateException ( \"Service already deactivated\" ) ; } serviceComponent . setServiceState ( ServiceState . STOPPING ) ; // warn ra entities about state change final ResourceManagement resourceManagement = sleeContainer . getResourceManagement ( ) ; for ( String raEntityName : resourceManagement . getResourceAdaptorEntities ( ) ) { resourceManagement . getResourceAdaptorEntity ( raEntityName ) . serviceStopping ( serviceID ) ; } // only end activity if slee was running and is single node in // cluster, otherwise not needed (cluster) or // slee already did it if ( sleeContainer . getCluster ( ) . isSingleMember ( ) && ( sleeState == SleeState . RUNNING || sleeState == SleeState . STOPPING ) ) { if ( sleeState == SleeState . RUNNING ) { endServiceActivity ( serviceID ) ; } else { // chance of concurrency with activity end synchronized ( serviceComponent ) { if ( serviceComponent . isActivityEnded ( ) ) { // activity already ended but service was not in stopping state completeServiceStop ( serviceComponent ) ; } } } } else { serviceComponent . setServiceState ( ServiceState . INACTIVE ) ; // warn ra entities about state change for ( String raEntityName : resourceManagement . getResourceAdaptorEntities ( ) ) { resourceManagement . getResourceAdaptorEntity ( raEntityName ) . serviceInactive ( serviceID ) ; } logger . info ( \"Deactivated \" + serviceID ) ; } // remove runtime cache related with this service for ( EventEntryDescriptor mEventEntry : serviceComponent . getRootSbbComponent ( ) . getDescriptor ( ) . getEventEntries ( ) . values ( ) ) { if ( mEventEntry . isInitialEvent ( ) ) { EventTypeComponent eventTypeComponent = componentRepositoryImpl . getComponentByID ( mEventEntry . getEventReference ( ) ) ; eventTypeComponent . deactivatedServiceWhichDefineEventAsInitial ( serviceComponent ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void deactivate ( ServiceID [ ] arg0 ) throws NullPointerException , InvalidArgumentException , UnrecognizedServiceException , InvalidStateException , ManagementException { if ( arg0 . length == 0 ) { throw new InvalidArgumentException ( \"InvalidArgumentException\" ) ; } for ( int i = 0 ; i < arg0 . length ; i ++ ) { if ( arg0 [ i ] == null ) { throw new InvalidArgumentException ( \"InvalidArgumentException\" ) ; } } for ( int i = 0 ; i < arg0 . length - 1 ; i ++ ) for ( int j = i + 1 ; j < arg0 . length ; j ++ ) if ( arg0 [ i ] == ( arg0 [ j ] ) ) { throw new InvalidArgumentException ( \"InvalidArgumentException\" ) ; } try { for ( int i = 0 ; i < arg0 . length ; i ++ ) { deactivate ( arg0 [ i ] ) ; } } catch ( InvalidStateException ise ) { throw ise ; } catch ( Exception ex ) { throw new ManagementException ( \"system exception starting service\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void deactivateAndActivate ( ServiceID arg0 , ServiceID arg1 ) throws NullPointerException , InvalidArgumentException , UnrecognizedServiceException , InvalidStateException , ManagementException { if ( logger . isInfoEnabled ( ) ) logger . debug ( \"deactivateAndActivate (\" + arg0 + \" , \" + arg1 ) ; if ( arg0 == arg1 ) throw new InvalidArgumentException ( \"Activating and deactivating the same service!\" ) ; if ( ( arg0 == null ) || ( arg1 == null ) ) throw new InvalidArgumentException ( \"The service(s) are null!\" ) ; try { ServiceComponent serviceToDeactivate = componentRepositoryImpl . getComponentByID ( arg0 ) ; if ( serviceToDeactivate == null ) { throw new UnrecognizedServiceException ( ) ; } else { activate ( arg1 , arg0 ) ; deactivate ( arg0 ) ; } } catch ( InvalidStateException ise ) { throw ise ; } catch ( Exception ex ) { throw new ManagementException ( \"exception in deactivating/activating service ! \" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void deactivateAndActivate ( ServiceID [ ] arg0 , ServiceID [ ] arg1 ) throws NullPointerException , InvalidArgumentException , UnrecognizedServiceException , InvalidStateException , ManagementException { if ( arg0 . length == 0 || arg1 . length == 0 ) throw new InvalidArgumentException ( \"The parameter array(s) must not be empty.\" ) ; if ( arg0 . length != arg1 . length ) throw new InvalidArgumentException ( \"The parameter arrays must have same lenght.\" ) ; Set < ServiceID > services = new HashSet < ServiceID > ( ) ; for ( int i = 0 ; i < arg0 . length - 1 ; i ++ ) { if ( arg0 [ i ] == null || arg1 [ i ] == null ) { throw new InvalidArgumentException ( \"Null entry found in parameter array(s).\" ) ; } if ( ! services . add ( arg0 [ i ] ) || ! services . add ( arg1 [ i ] ) ) { throw new InvalidArgumentException ( \"Repeated entry found in parameter array(s).\" ) ; } } try { for ( int i = 0 ; i < arg0 . length ; i ++ ) { deactivateAndActivate ( arg0 [ i ] , arg1 [ i ] ) ; } } catch ( InvalidStateException ise ) { throw ise ; } catch ( ManagementException me ) { throw me ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName getServiceUsageMBean ( ServiceID serviceID ) throws NullPointerException , UnrecognizedServiceException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getServiceUsageMBean \" + serviceID ) ; } final ServiceComponent serviceComponent = componentRepositoryImpl . getComponentByID ( serviceID ) ; if ( serviceComponent != null ) { return serviceComponent . getServiceUsageMBean ( ) . getObjectName ( ) ; } else { throw new UnrecognizedServiceException ( serviceID . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Install a service into SLEE [CODESPLIT] public void installService ( final ServiceComponent serviceComponent ) throws Exception { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Installing Service \" + serviceComponent ) ; } // creates and registers the service usage mbean final ServiceUsageMBean serviceUsageMBean = sleeContainer . getUsageParametersManagement ( ) . newServiceUsageMBean ( serviceComponent ) ; // add rollback action to remove state created TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { try { serviceUsageMBean . remove ( ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } ; final TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; txContext . getAfterRollbackActions ( ) . add ( action ) ; // register notification sources for all sbbs // final TraceManagement traceMBeanImpl = sleeContainer . getTraceManagement ( ) ; for ( final SbbID sbbID : serviceComponent . getSbbIDs ( componentRepositoryImpl ) ) { // Tracer must be available for both 1.1 and 1.0 sbb components // SbbComponent sbbComponent = // componentRepositoryImpl.getComponentByID(sbbID); // if(sbbComponent.isSlee11()) { traceMBeanImpl . registerNotificationSource ( new SbbNotification ( serviceComponent . getServiceID ( ) , sbbID ) ) ; // add rollback action to remove state created action = new TransactionalAction ( ) { public void execute ( ) { // remove notification sources for all sbbs traceMBeanImpl . deregisterNotificationSource ( new SbbNotification ( serviceComponent . getServiceID ( ) , sbbID ) ) ; } } ; txContext . getAfterRollbackActions ( ) . add ( action ) ; } // this might be used not only by 1.1 sbbs... NotificationSourceWrapperImpl sbbMNotificationSource = new NotificationSourceWrapperImpl ( new SbbNotification ( serviceComponent . getServiceID ( ) , sbbID ) ) ; serviceComponent . getAlarmNotificationSources ( ) . putIfAbsent ( sbbID , sbbMNotificationSource ) ; } sleeContainer . getSbbManagement ( ) . serviceInstall ( serviceComponent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uninstall a service . [CODESPLIT] public void uninstallService ( final ServiceComponent serviceComponent ) throws SystemException , UnrecognizedServiceException , InstanceNotFoundException , MBeanRegistrationException , NullPointerException , UnrecognizedResourceAdaptorEntityException , ManagementException , InvalidStateException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Uninstalling service with id \" + serviceComponent . getServiceID ( ) ) ; } if ( serviceComponent . getServiceState ( ) . isStopping ( ) ) { // let's be friendly and give it a few secs for ( int i = 0 ; i < 15 ; i ++ ) { try { Thread . sleep ( 1000 ) ; logger . info ( \"Waiting for \" + serviceComponent . getServiceID ( ) + \" to stop, current state is \" + serviceComponent . getServiceState ( ) ) ; if ( serviceComponent . getServiceState ( ) . isInactive ( ) ) { break ; } } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } if ( ! serviceComponent . getServiceState ( ) . isInactive ( ) ) { throw new InvalidStateException ( serviceComponent . toString ( ) + \" is not inactive\" ) ; } final TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Closing Usage MBean of service \" + serviceComponent . getServiceID ( ) ) ; } ServiceUsageMBean serviceUsageMBean = serviceComponent . getServiceUsageMBean ( ) ; if ( serviceUsageMBean != null ) { serviceUsageMBean . remove ( ) ; // add rollback action to re-create the mbean // FIXME this doesn't make sense, this restore looses all old data, // it shoudl only remove on // commit but as it is right now, the needed sbb components are // already removed TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { try { sleeContainer . getUsageParametersManagement ( ) . newServiceUsageMBean ( serviceComponent ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } ; txContext . getAfterRollbackActions ( ) . add ( action ) ; } // register notification sources for all sbbs final TraceManagement traceMBeanImpl = sleeContainer . getTraceManagement ( ) ; for ( final SbbID sbbID : serviceComponent . getSbbIDs ( componentRepositoryImpl ) ) { // Tracer must be available for both 1.1 and 1.0 sbb components // SbbComponent sbbComponent = // componentRepositoryImpl.getComponentByID(sbbID); // if(sbbComponent.isSlee11()) { traceMBeanImpl . deregisterNotificationSource ( new SbbNotification ( serviceComponent . getServiceID ( ) , sbbID ) ) ; // add rollback action to re-add state removed TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { // remove notification sources for all sbbs traceMBeanImpl . registerNotificationSource ( new SbbNotification ( serviceComponent . getServiceID ( ) , sbbID ) ) ; } } ; txContext . getAfterRollbackActions ( ) . add ( action ) ; } } // warn sbb management that the service is being uninstalled, giving it // the option to clear any related resources sleeContainer . getSbbManagement ( ) . serviceUninstall ( serviceComponent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if the specified ra entity link name is referenced by a non inactive service . [CODESPLIT] public boolean isRAEntityLinkNameReferenced ( String raLinkName ) { if ( raLinkName == null ) { throw new NullPointerException ( \"null ra link name\" ) ; } boolean b = false ; try { b = transactionManager . requireTransaction ( ) ; for ( ServiceID serviceID : componentRepositoryImpl . getServiceIDs ( ) ) { ServiceComponent serviceComponent = componentRepositoryImpl . getComponentByID ( serviceID ) ; if ( serviceComponent . getServiceState ( ) != ServiceState . INACTIVE && serviceComponent . getResourceAdaptorEntityLinks ( componentRepositoryImpl ) . contains ( raLinkName ) ) { return true ; } } return false ; } finally { try { transactionManager . requireTransactionEnd ( b , false ) ; } catch ( Throwable ex ) { throw new SLEEException ( ex . getMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void activityEnded ( final ServiceActivityHandle activityHandle ) { // do this only on tx commit and in a new thread, to escape the tx context final Runnable r = new Runnable ( ) { public void run ( ) { final ServiceID serviceID = activityHandle . getServiceID ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Activity end for \" + serviceID ) ; } // remove and cancel the timer task to force activity ending ScheduledFuture < ? > scheduledFuture = activityEndingTasks . remove ( serviceID ) ; if ( scheduledFuture != null ) { scheduledFuture . cancel ( true ) ; } // get stopping service final ServiceComponent serviceComponent = componentRepositoryImpl . getComponentByID ( serviceID ) ; if ( serviceComponent != null ) { synchronized ( serviceComponent ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Service is in \" + serviceComponent . getServiceState ( ) + \" state.\" ) ; } if ( serviceComponent . getServiceState ( ) . isStopping ( ) ) { completeServiceStop ( serviceComponent ) ; } serviceComponent . setActivityEnded ( true ) ; } } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( serviceID . toString ( ) + \" activity ended, but component not found, removed concurrently?\" ) ; } } } } ; final ExecutorService executorService = Executors . newSingleThreadExecutor ( SLEE_THREAD_FACTORY ) ; TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; if ( txContext != null ) { TransactionalAction txAction = new TransactionalAction ( ) { public void execute ( ) { try { executorService . execute ( r ) ; } catch ( Exception e ) { logger . error ( \"failed to execute task to complete service deactivation\" , e ) ; } executorService . shutdown ( ) ; } } ; txContext . getAfterCommitActions ( ) . add ( txAction ) ; } else { try { executorService . execute ( r ) ; } catch ( Exception e ) { logger . error ( \"failed to execute task to complete service deactivation\" , e ) ; } executorService . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the time for an event routing with a specific { @link EventTypeID } . [CODESPLIT] public void eventRouted ( EventTypeID eventTypeID , long routingTime ) { EventTypeRoutingStatisticsImpl eventTypeRoutingStatistics = eventTypeRoutingStatisticsMap . get ( eventTypeID ) ; if ( eventTypeRoutingStatistics == null ) { synchronized ( eventTypeRoutingStatisticsMap ) { eventTypeRoutingStatistics = new EventTypeRoutingStatisticsImpl ( eventTypeID ) ; eventTypeRoutingStatisticsMap . put ( eventTypeID , eventTypeRoutingStatistics ) ; } } eventTypeRoutingStatistics . eventRouted ( routingTime ) ; taskExecuted ( routingTime ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getAverageEventRoutingTime ( ) { long time = 0L ; long events = 0L ; for ( EventTypeRoutingStatistics eventTypeRoutingStatistics : eventTypeRoutingStatisticsMap . values ( ) ) { time += eventTypeRoutingStatistics . getRoutingTime ( ) ; events += eventTypeRoutingStatistics . getEventsRouted ( ) ; } return time == 0L ? 0L : time / events ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getAverageEventRoutingTime ( EventTypeID eventTypeID ) { final EventTypeRoutingStatistics eventTypeRoutingStatistics = getEventTypeRoutingStatistics ( eventTypeID ) ; return eventTypeRoutingStatistics == null ? 0L : eventTypeRoutingStatistics . getAverageEventRoutingTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getEventsRouted ( EventTypeID eventTypeID ) { final EventTypeRoutingStatistics eventTypeRoutingStatistics = getEventTypeRoutingStatistics ( eventTypeID ) ; return eventTypeRoutingStatistics == null ? 0L : eventTypeRoutingStatistics . getEventsRouted ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public long getRoutingTime ( EventTypeID eventTypeID ) { final EventTypeRoutingStatistics eventTypeRoutingStatistics = getEventTypeRoutingStatistics ( eventTypeID ) ; return eventTypeRoutingStatistics == null ? 0L : eventTypeRoutingStatistics . getRoutingTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AlarmLevel< / code > object from an integer value . [CODESPLIT] public static AlarmLevel fromInt ( int level ) throws IllegalArgumentException { switch ( level ) { case LEVEL_CLEAR : return CLEAR ; case LEVEL_CRITICAL : return CRITICAL ; case LEVEL_MAJOR : return MAJOR ; case LEVEL_WARNING : return WARNING ; case LEVEL_INDETERMINATE : return INDETERMINATE ; case LEVEL_MINOR : return MINOR ; default : throw new IllegalArgumentException ( \"Invalid level: \" + level ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AlarmLevel< / code > object from a string value . [CODESPLIT] public static AlarmLevel fromString ( String level ) throws NullPointerException , IllegalArgumentException { if ( level == null ) throw new NullPointerException ( \"level is null\" ) ; if ( level . equalsIgnoreCase ( CLEAR_STRING ) ) return CLEAR ; if ( level . equalsIgnoreCase ( CRITICAL_STRING ) ) return CRITICAL ; if ( level . equalsIgnoreCase ( MAJOR_STRING ) ) return MAJOR ; if ( level . equalsIgnoreCase ( WARNING_STRING ) ) return WARNING ; if ( level . equalsIgnoreCase ( INDETERMINATE_STRING ) ) return INDETERMINATE ; if ( level . equalsIgnoreCase ( MINOR_STRING ) ) return MINOR ; throw new IllegalArgumentException ( \"Invalid level: \" + level ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this AlarmLevel object represents a level that is higher than some other AlarmLevel object . For the purposes of the comparison the following order from highest to lowest severity is assumed for alarm levels : <ul > <li > CLEAR <li > CRITICAL <li > MAJOR <li > WARNING <li > INDETERMINATE <li > MINOR < / ul > [CODESPLIT] public boolean isHigherLevel ( AlarmLevel other ) throws NullPointerException { if ( other == null ) throw new NullPointerException ( \"other is null\" ) ; return this . level < other . level ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public EventTypeID [ ] getEventTypes ( ) throws ManagementConsoleException { try { EventTypeID [ ] IDs = ( EventTypeID [ ] ) mbeanServer . getAttribute ( deploymentMBean , \"EventTypes\" ) ; // ManagementConsole.getInstance().getComponentIDMap().put(IDs);\r return IDs ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ActivityContextImpl createActivityContext ( final ActivityContextHandle ach , int activityFlags ) throws ActivityAlreadyExistsException { if ( sleeContainer . getCongestionControl ( ) . refuseStartActivity ( ) ) { throw new SLEEException ( \"congestion control refused activity start\" ) ; } // create ac\r ActivityContextCacheData activityContextCacheData = new ActivityContextCacheData ( ach , sleeContainer . getCluster ( ) ) ; if ( activityContextCacheData . exists ( ) ) { throw new ActivityAlreadyExistsException ( ach . toString ( ) ) ; } ActivityContextImpl ac = new ActivityContextImpl ( ach , activityContextCacheData , tracksIdleTime ( ach , true ) , Integer . valueOf ( activityFlags ) , this ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Created activity context with handle \" + ach ) ; } return ac ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void eventProcessingFailed ( FailureReason failureReason ) { raEntity . getResourceAdaptorObject ( ) . eventProcessingFailed ( activityHandle , fireableEventType , failureReason , address , receivableService , eventFlags , failureReason ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void eventProcessingSucceed ( boolean sbbProcessedEvent ) { int flags = sbbProcessedEvent ? EventFlags . setSbbProcessedEvent ( eventFlags ) : eventFlags ; raEntity . getResourceAdaptorObject ( ) . eventProcessingSuccessful ( activityHandle , fireableEventType , event , address , receivableService , flags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void eventUnreferenced ( ) { raEntity . getResourceAdaptorObject ( ) . eventUnreferenced ( activityHandle , fireableEventType , event , address , receivableService , eventFlags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void processArguments ( String [ ] args ) throws CommandException { //String sopts = \":lyi:u:d:sr:\";\r String sopts = \":lyi:u:dr:\" ; LongOpt [ ] lopts = { new LongOpt ( \"list\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //options\r new LongOpt ( \"sbbs\" , LongOpt . OPTIONAL_ARGUMENT , null , ListOperation . sbbs ) , new LongOpt ( \"services\" , LongOpt . NO_ARGUMENT , null , ListOperation . services ) , new LongOpt ( \"libraries\" , LongOpt . NO_ARGUMENT , null , ListOperation . libraries ) , new LongOpt ( \"events\" , LongOpt . NO_ARGUMENT , null , ListOperation . events ) , new LongOpt ( \"ra-types\" , LongOpt . NO_ARGUMENT , null , ListOperation . ra_types ) , new LongOpt ( \"ras\" , LongOpt . NO_ARGUMENT , null , ListOperation . ras ) , new LongOpt ( \"dus\" , LongOpt . NO_ARGUMENT , null , ListOperation . dus ) , new LongOpt ( \"profile-spec\" , LongOpt . NO_ARGUMENT , null , ListOperation . profile_specs ) , new LongOpt ( \"installed\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"cid\" , LongOpt . REQUIRED_ARGUMENT , null , IsInstalledOperation . cid ) , new LongOpt ( \"duid\" , LongOpt . REQUIRED_ARGUMENT , null , IsInstalledOperation . duid ) , new LongOpt ( \"install\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"un-install\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , //new LongOpt(\"duid\", LongOpt.REQUIRED_ARGUMENT, null, 'd'),\r new LongOpt ( \"desc\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //new LongOpt(\"cid\", LongOpt.REQUIRED_ARGUMENT, null, GetDescriptorsOperation.cid),\r //new LongOpt(\"duid\", LongOpt.REQUIRED_ARGUMENT, null, GetDescriptorsOperation.duid),\r new LongOpt ( \"ref\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , } ; Getopt getopt = new Getopt ( null , args , sopts , lopts ) ; getopt . setOpterr ( false ) ; int code ; while ( ( code = getopt . getopt ( ) ) != - 1 ) { switch ( code ) { case ' ' : throw new CommandException ( \"Option requires an argument: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : throw new CommandException ( \"Invalid (or ambiguous) option: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : super . operation = new ListOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new IsInstalledOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new InstallOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new UninstallOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //super.operation = new DeployableUnitIDOperation(super.context, super.log, this);\r //super.operation.buildOperation(getopt, args);\r //break;\r //case 's':\r super . operation = new GetDescriptorsOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new GetReferringComponentsOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\", found unexpected opt: \" + args [ getopt . getOptind ( ) - 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void createUsageParameterSet ( SbbID sbbId , String name ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , UsageParameterSetNameAlreadyExistsException , ManagementException { if ( name == null ) throw new NullPointerException ( \"Sbb usage param set is null\" ) ; if ( name . length ( ) == 0 ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; if ( ! isValidUsageParameterName ( name ) ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; _createUsageParameterSet ( sbbId , name , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * creates the default usage parameter set [CODESPLIT] public void createUsageParameterSet ( SbbID sbbId ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , UsageParameterSetNameAlreadyExistsException , ManagementException { _createUsageParameterSet ( sbbId , null , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] private synchronized void _createUsageParameterSet ( SbbID sbbId , String name , boolean failIfSbbHasNoUsageParamSet ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , UsageParameterSetNameAlreadyExistsException , ManagementException { if ( sbbId == null ) throw new NullPointerException ( \"Sbb ID is null!\" ) ; // get the sbb component\r SbbComponent sbbComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( sbbId ) ; if ( sbbComponent == null ) { throw new UnrecognizedSbbException ( sbbId . toString ( ) ) ; } // get service component and check if the sbb belongs to the service\r ServiceComponent serviceComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( getService ( ) ) ; if ( ! serviceComponent . getSbbIDs ( sleeContainer . getComponentRepository ( ) ) . contains ( sbbId ) ) { throw new UnrecognizedSbbException ( sbbId . toString ( ) + \" is not part of \" + getService ( ) ) ; } // get sbb usage parameter class\r Class < ? > usageParameterClass = sbbComponent . getUsageParametersConcreteClass ( ) ; if ( usageParameterClass == null ) { if ( failIfSbbHasNoUsageParamSet ) { throw new InvalidArgumentException ( sbbId . toString ( ) + \" does not define a usage parameters interface\" ) ; } else { return ; } } // check if the usage parameter name set already exists\r SbbUsageMBeanMapKey mapKey = new SbbUsageMBeanMapKey ( sbbId , name ) ; if ( this . usageMBeans . containsKey ( mapKey ) ) { throw new UsageParameterSetNameAlreadyExistsException ( \"name \" + name + \" already exists for service \" + serviceComponent + \" and sbb \" + sbbComponent ) ; } UsageMBeanImpl usageMbean = null ; UsageNotificationManagerMBeanImpl usageNotificationManagerMBean = null ; Thread currentThread = Thread . currentThread ( ) ; ClassLoader currentThreadClassLoader = currentThread . getContextClassLoader ( ) ; try { // change class loader\r currentThread . setContextClassLoader ( sbbComponent . getClassLoader ( ) ) ; // create the actual usage parameter instance and map it in the\r // mbean\r SbbNotification sbbNotification = new SbbNotification ( serviceID , sbbId ) ; AbstractUsageParameterSet installedUsageParameterSet = ( AbstractUsageParameterSet ) AbstractUsageParameterSet . newInstance ( usageParameterClass , sbbNotification , name , sleeContainer ) ; // create and register the usage mbean\r Class < ? > usageParameterMBeanClass = sbbComponent . getUsageParametersMBeanImplConcreteClass ( ) ; Constructor < ? > constructor = null ; if ( sbbComponent . isSlee11 ( ) ) { constructor = usageParameterMBeanClass . getConstructor ( new Class [ ] { Class . class , NotificationSource . class } ) ; } else { constructor = usageParameterMBeanClass . getConstructor ( new Class [ ] { Class . class , SbbNotification . class } ) ; } ObjectName usageParameterMBeanObjectName = generateUsageParametersMBeanObjectName ( name , sbbId , sbbComponent . isSlee11 ( ) ) ; usageMbean = ( UsageMBeanImpl ) constructor . newInstance ( new Object [ ] { sbbComponent . getUsageParametersMBeanConcreteInterface ( ) , sbbNotification } ) ; usageMbean . setObjectName ( usageParameterMBeanObjectName ) ; usageMbean . setParent ( this ) ; sleeContainer . getMBeanServer ( ) . registerMBean ( usageMbean , usageParameterMBeanObjectName ) ; // set the usage param data related with the mbean\r installedUsageParameterSet . setUsageMBean ( usageMbean ) ; usageMbean . setUsageParameter ( installedUsageParameterSet ) ; // store the mbean\r this . usageMBeans . put ( mapKey , usageMbean ) ; // if it's the default usage param set and it's an slee 1.1. sbb\r // then we have to create the notification manager too\r if ( sbbComponent . isSlee11 ( ) && name == null ) { Class < ? > usageNotificationManagerMBeanClass = sbbComponent . getUsageNotificationManagerMBeanImplConcreteClass ( ) ; constructor = usageNotificationManagerMBeanClass . getConstructor ( new Class [ ] { Class . class , NotificationSource . class , SleeComponentWithUsageParametersInterface . class } ) ; usageNotificationManagerMBean = ( UsageNotificationManagerMBeanImpl ) constructor . newInstance ( new Object [ ] { sbbComponent . getUsageNotificationManagerMBeanConcreteInterface ( ) , sbbNotification , sbbComponent } ) ; ObjectName usageNotificationManagerMBeanObjectName = generateUsageNotificationManagerMBeanObjectName ( sbbId ) ; usageNotificationManagerMBean . setObjectName ( usageNotificationManagerMBeanObjectName ) ; sleeContainer . getMBeanServer ( ) . registerMBean ( usageNotificationManagerMBean , usageNotificationManagerMBeanObjectName ) ; this . notificationManagers . put ( sbbId , usageNotificationManagerMBean ) ; } } catch ( Throwable e ) { if ( mapKey != null && usageMbean != null ) { this . usageMBeans . remove ( mapKey ) ; try { sleeContainer . getMBeanServer ( ) . unregisterMBean ( usageMbean . getObjectName ( ) ) ; } catch ( Throwable f ) { logger . error ( \"failed to unregister usage parameter mbean \" + usageMbean . getObjectName ( ) ) ; } } if ( usageNotificationManagerMBean != null ) { this . notificationManagers . remove ( sbbId ) ; try { sleeContainer . getMBeanServer ( ) . unregisterMBean ( usageNotificationManagerMBean . getObjectName ( ) ) ; } catch ( Throwable f ) { logger . error ( \"failed to unregister usage notification manager mbean \" + usageNotificationManagerMBean . getObjectName ( ) ) ; } } throw new ManagementException ( e . getMessage ( ) , e ) ; } finally { currentThread . setContextClassLoader ( currentThreadClassLoader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void removeUsageParameterSet ( SbbID sbbId , String name ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , UnrecognizedUsageParameterSetNameException , ManagementException { if ( name == null ) throw new NullPointerException ( \"Sbb usage param set is null\" ) ; if ( name . length ( ) == 0 ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; if ( ! isValidUsageParameterName ( name ) ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; _removeUsageParameterSet ( sbbId , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns a list containing the names of the named SBB usage parameter sets that belong to the SBB specified by the sbbID argument and the Service represented by the ServiceUsageMBean object . [CODESPLIT] public synchronized String [ ] getUsageParameterSets ( SbbID sbbId ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , ManagementException { if ( sbbId == null ) throw new NullPointerException ( \"Sbb ID is null!\" ) ; // get the sbb component\r SbbComponent sbbComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( sbbId ) ; if ( sbbComponent == null ) { throw new UnrecognizedSbbException ( sbbId . toString ( ) ) ; } else { if ( sbbComponent . getUsageParametersInterface ( ) == null ) { throw new InvalidArgumentException ( \"no usage parameter interface for \" + sbbId ) ; } } // get service component and check if the sbb belongs to the service\r ServiceComponent serviceComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( getService ( ) ) ; if ( ! serviceComponent . getSbbIDs ( sleeContainer . getComponentRepository ( ) ) . contains ( sbbId ) ) { throw new UnrecognizedSbbException ( sbbId . toString ( ) + \" is not part of \" + getService ( ) ) ; } Set < String > resultSet = new HashSet < String > ( ) ; for ( UsageMBeanImpl usageMBeanImpl : usageMBeans . values ( ) ) { if ( ( ( SbbNotification ) usageMBeanImpl . getNotificationSource ( ) ) . getSbb ( ) . equals ( sbbId ) ) { String name = usageMBeanImpl . getUsageParameterSet ( ) ; if ( name != null ) { resultSet . add ( name ) ; } } } return resultSet . toArray ( new String [ resultSet . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName getSbbUsageMBean ( SbbID sbbId ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , ManagementException { try { return _getSbbUsageMBean ( sbbId , null ) ; } catch ( UnrecognizedUsageParameterSetNameException e ) { throw new ManagementException ( \"default usage parameter name not found\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName getSbbUsageMBean ( SbbID sbbId , String name ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , UnrecognizedUsageParameterSetNameException , ManagementException { if ( name == null ) throw new NullPointerException ( \"Sbb usage param set is null\" ) ; if ( name . length ( ) == 0 ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; if ( ! isValidUsageParameterName ( name ) ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; return _getSbbUsageMBean ( sbbId , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the usage parameters of only the SBB specified by the sbbID argument argument ( within the Service represented by the ServiceUsageMBean object ) . [CODESPLIT] public synchronized void resetAllUsageParameters ( SbbID sbbId ) throws NullPointerException , UnrecognizedSbbException , InvalidArgumentException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"resetAllUsageParameters: \" + sbbId ) ; } if ( sbbId == null ) throw new NullPointerException ( \"Sbb ID is null!\" ) ; // get the sbb component\r SbbComponent sbbComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( sbbId ) ; if ( sbbComponent == null ) { throw new UnrecognizedSbbException ( sbbId . toString ( ) ) ; } else { if ( sbbComponent . getUsageParametersInterface ( ) == null ) { throw new InvalidArgumentException ( \"no usage parameter interface for \" + sbbId ) ; } } // get service component and check if the sbb belongs to the service\r ServiceComponent serviceComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( getService ( ) ) ; if ( ! serviceComponent . getSbbIDs ( sleeContainer . getComponentRepository ( ) ) . contains ( sbbId ) ) { throw new UnrecognizedSbbException ( sbbId . toString ( ) + \" is not part of \" + getService ( ) ) ; } for ( UsageMBeanImpl usageMBeanImpl : usageMBeans . values ( ) ) { SbbNotification sbbNotification = ( SbbNotification ) usageMBeanImpl . getNotificationSource ( ) ; if ( sbbNotification . getSbb ( ) . equals ( sbbId ) ) { usageMBeanImpl . resetAllUsageParameters ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the usage parameters of all SBBs within the Service represented by the ServiceUsageMBean object . The SLEE sets counter - type usage parameters to zero and removes all samples from sample - type usage parameters . [CODESPLIT] public synchronized void resetAllUsageParameters ( ) throws ManagementException { try { //FIXME: hmm, how to check here for clustered... ghmp\r for ( UsageMBeanImpl usageMBeanImpl : usageMBeans . values ( ) ) { usageMBeanImpl . resetAllUsageParameters ( ) ; } } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method to retrieve the { @link AbstractUsageParameterSet } for the specified sbb and name [CODESPLIT] public AbstractUsageParameterSet getInstalledUsageParameterSet ( SbbID sbbID , String name ) throws UnrecognizedUsageParameterSetNameException { if ( name == null ) { throw new NullPointerException ( \"null name\" ) ; } AbstractUsageParameterSet installedUsageParameterSet = _getInstalledUsageParameterSet ( sbbID , name ) ; if ( installedUsageParameterSet == null ) { throw new UnrecognizedUsageParameterSetNameException ( name ) ; } return installedUsageParameterSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lifecycle methods [CODESPLIT] public void setResourceAdaptorContext ( ResourceAdaptorContext raContext ) { this . raContext = raContext ; this . tracer = raContext . getTracer ( StatisticsResourceAdaptor . class . getSimpleName ( ) ) ; this . sleeContainer = SleeContainer . lookupFromJndi ( ) ; if ( this . sleeContainer != null ) { this . resourceManagement = sleeContainer . getResourceManagement ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sbb abstract class ( general rule � methods cannot start neither with �ejb� nor �sbb� ) <ul > <li > ( 1 . 1 ? ) must have package declaration <li > must implement in some way javax . slee . Sbb ( only methods from interface can have �sbb� prefix ) <ul > <li > each method defined must be implemented as public � not abstract final or static < / ul > <li > must be public and abstract <li > must have public no arg constructor <li > must implement sbbExceptionThrown method <ul > <li > public not abstract final or static no return type 3 arguments : java . lang . Exception java . lang . Object javax . slee . ActivityContextInterface < / ul > <li > must implement sbbRolledBack <ul > <li > method must be public not abstract final or static <li > no return type <li > with single argument - javax . slee . RoledBackContext < / ul > <li > there is no finalize method < / ul > [CODESPLIT] boolean validateAbstractClassConstraints ( Map < String , Method > concreteMethods , Map < String , Method > concreteSuperClassesMethods ) { String errorBuffer = new String ( \"\" ) ; boolean passed = true ; // Presence of those classes must be checked elsewhere\r Class sbbAbstractClass = this . component . getAbstractSbbClass ( ) ; // Must be public and abstract\r int modifiers = sbbAbstractClass . getModifiers ( ) ; // check that the class modifiers contain abstratc and public\r if ( ! Modifier . isAbstract ( modifiers ) || ! Modifier . isPublic ( modifiers ) ) { errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class must be public and abstract\" , \"6.1\" , errorBuffer ) ; } // 1.1 - must be in package\r if ( this . component . isSlee11 ( ) ) { Package declaredPackage = sbbAbstractClass . getPackage ( ) ; if ( declaredPackage == null || declaredPackage . getName ( ) . compareTo ( \"\" ) == 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class must be defined inside package space\" , \"6.1\" , errorBuffer ) ; } } // Public no arg constructor - can it have more ?\r // sbbAbstractClass.getConstructor\r // FIXME: no arg constructor has signature \"()V\" when added from\r // javaassist we check for such constructor and if its public\r try { Constructor constructor = sbbAbstractClass . getConstructor ( ) ; int conMod = constructor . getModifiers ( ) ; if ( ! Modifier . isPublic ( conMod ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class must have public constructor \" , \"6.1\" , errorBuffer ) ; } } catch ( SecurityException e ) { e . printStackTrace ( ) ; passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class must have no arg constructor, error:\" + e . getMessage ( ) , \"6.1\" , errorBuffer ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class must have no arg constructor, error:\" + e . getMessage ( ) , \"6.1\" , errorBuffer ) ; } // Must implements javax.slee.Sbb - and each method there defined, only\r // those methods and two above can have \"sbb\" prefix\r // those methods MUST be in concrete methods map, later we will use them\r // to see if there is ant \"sbbXXXX\" method\r // Check if we implement javax.slee.Sbb - either directly or from super\r // class\r Class javaxSleeSbbInterface = ClassUtils . checkInterfaces ( sbbAbstractClass , \"javax.slee.Sbb\" ) ; // sbbAbstractClass.getI\r if ( javaxSleeSbbInterface == null ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class  must implement, directly or indirectly, the javax.slee.Sbb interface.\" , \"6.1\" , errorBuffer ) ; } // FIXME: add check for finalize method\r // Now we have to check methods from javax.slee.Sbb\r // This takes care of method throws clauses\r if ( javaxSleeSbbInterface != null ) { // if it is, we dont have those methods for sure, or maybe we do,\r // implemnted by hand\r // either way its a failure\r // We want only java.slee.Sbb methods :)\r Method [ ] sbbLifecycleMethods = javaxSleeSbbInterface . getDeclaredMethods ( ) ; for ( Method lifecycleMehtod : sbbLifecycleMethods ) { // It must be implemented - so only in concrete methods, if we\r // are left with one not checked bang, its an error\r String methodKey = ClassUtils . getMethodKey ( lifecycleMehtod ) ; Method concreteLifeCycleImpl = null ; if ( concreteMethods . containsKey ( methodKey ) ) { concreteLifeCycleImpl = concreteMethods . remove ( methodKey ) ; } else if ( concreteSuperClassesMethods . containsKey ( methodKey ) ) { concreteLifeCycleImpl = concreteSuperClassesMethods . remove ( methodKey ) ; } else { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class must implement life cycle methods, it lacks concrete implementation of: \" + lifecycleMehtod . getName ( ) , \"6.1.1\" , errorBuffer ) ; continue ; } // now we now there is such method, its not private and abstract\r // If we are here its not null\r int lifeCycleModifier = concreteLifeCycleImpl . getModifiers ( ) ; if ( ! Modifier . isPublic ( lifeCycleModifier ) || Modifier . isStatic ( lifeCycleModifier ) || Modifier . isFinal ( lifeCycleModifier ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class must implement life cycle methods, which can not be static, final or not public, method: \" + lifecycleMehtod . getName ( ) , \"6.1.1\" , errorBuffer ) ; } } } // there can not be any method which start with ejb/sbb - we removed\r // every from concrete, lets iterate over those sets\r for ( Method concreteMethod : concreteMethods . values ( ) ) { if ( concreteMethod . getName ( ) . startsWith ( \"ejb\" ) || concreteMethod . getName ( ) . startsWith ( \"sbb\" ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" with method:  \" + concreteMethod . getName ( ) , \"6.12\" , errorBuffer ) ; } if ( concreteMethod . getName ( ) . compareTo ( \"finalize\" ) == 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class  must not implement \\\"finalize\\\" method.\" , \"6.1\" , errorBuffer ) ; } } for ( Method concreteMethod : concreteSuperClassesMethods . values ( ) ) { if ( concreteMethod . getName ( ) . startsWith ( \"ejb\" ) || concreteMethod . getName ( ) . startsWith ( \"sbb\" ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" with method from super classes:  \" + concreteMethod . getName ( ) , \"6.12\" , errorBuffer ) ; } if ( concreteMethod . getName ( ) . compareTo ( \"finalize\" ) == 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \"sbb abstract class  must not implement \\\"finalize\\\" method. Its implemented by super class.\" , \"6.1\" , errorBuffer ) ; } } if ( ! passed ) { logger . error ( errorBuffer ) ; } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method checks for presence of [CODESPLIT] boolean validateSbbActivityContextInterface ( Map < String , Method > sbbAbstractClassAbstraMethod , Map < String , Method > sbbAbstractClassAbstraMethodFromSuperClasses ) { if ( this . component . getDescriptor ( ) . getSbbActivityContextInterface ( ) == null ) { // FIXME: add check for asSbbActivityContextInteface method ? This\r // will be catched at the end of check anyway\r if ( logger . isTraceEnabled ( ) ) { logger . trace ( this . component . getDescriptor ( ) . getSbbID ( ) + \" : No Sbb activity context interface defined\" ) ; } return true ; } String errorBuffer = new String ( \"\" ) ; boolean passed = true ; Method asACIMethod = null ; // lets go through methods of sbbAbstract class,\r Iterator < Method > it = sbbAbstractClassAbstraMethod . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Method someMethod = it . next ( ) ; if ( someMethod . getName ( ) . compareTo ( _SBB_AS_SBB_ACTIVITY_CONTEXT_INTERFACE ) == 0 ) { // we have a winner, possibly - we have to check parameter\r // list, cause someone can create abstract method(or crap,\r // it can be concrete) with different parametrs, in case its\r // abstract, it will fail later on\t\r if ( someMethod . getParameterTypes ( ) . length == 1 && someMethod . getParameterTypes ( ) [ 0 ] . getName ( ) . compareTo ( \"javax.slee.ActivityContextInterface\" ) == 0 ) { asACIMethod = someMethod ; it . remove ( ) ; break ; } } } if ( asACIMethod == null ) it = sbbAbstractClassAbstraMethodFromSuperClasses . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Method someMethod = it . next ( ) ; if ( someMethod . getName ( ) . compareTo ( _SBB_AS_SBB_ACTIVITY_CONTEXT_INTERFACE ) == 0 ) { // we have a winner, possibly - we have to check\r // parameter\r // list, cause someone can create abstract method(or\r // crap,\r // it can be concrete) with different parametrs, in case\r // its\r // abstract, it will fail later on\r if ( someMethod . getParameterTypes ( ) . length == 1 && someMethod . getParameterTypes ( ) [ 0 ] . getName ( ) . compareTo ( \"javax.slee.ActivityContextInterface\" ) == 0 ) { asACIMethod = someMethod ; it . remove ( ) ; break ; } } } if ( asACIMethod == null ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" must imlement narrow method asSbbActivityContextInterface\" , \"7.7.2\" , errorBuffer ) ; } else { // must be public, abstract? FIXME: not native?\r int asACIMethodModifiers = asACIMethod . getModifiers ( ) ; if ( ! Modifier . isPublic ( asACIMethodModifiers ) || ! Modifier . isAbstract ( asACIMethodModifiers ) || Modifier . isNative ( asACIMethodModifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" narrow method asSbbActivityContextInterface must be public,abstract and not native.\" , \"7.7.2\" , errorBuffer ) ; } // now this misery comes to play, return type check\r Class returnType = asACIMethod . getReturnType ( ) ; // Must return something from Sbb defined aci class inheritance\r // tree\r Class definedReturnType = this . component . getActivityContextInterface ( ) ; if ( returnType . getName ( ) . compareTo ( \"void\" ) == 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" narrow method asSbbActivityContextInterface must have return type.\" , \"7.7.2\" , errorBuffer ) ; } else if ( returnType . equals ( definedReturnType ) ) { // its ok\r // } else if (ClassUtils.checkInterfaces(definedReturnType,\r // returnType\r // .getName()) != null) {\r } else { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" narrow method asSbbActivityContextInterface has wrong return type: \" + returnType , \"7.7.2\" , errorBuffer ) ; } // no throws clause\r if ( asACIMethod . getExceptionTypes ( ) != null && asACIMethod . getExceptionTypes ( ) . length > 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" narrow method asSbbActivityContextInterface must not have throws clause.\" , \"7.7.2\" , errorBuffer ) ; } } // Even if we fail above we can do some checks on ACI if its present.\r // this has to be present\r Class sbbActivityContextInterface = this . component . getActivityContextInterface ( ) ; // ACI VALIDATION\r // (1.1) = must be declared in package\r if ( this . component . isSlee11 ( ) && sbbActivityContextInterface . getPackage ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface must be declared in package.\" , \"7.5\" , errorBuffer ) ; } if ( ! Modifier . isPublic ( sbbActivityContextInterface . getModifiers ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface must be declared as public.\" , \"7.5\" , errorBuffer ) ; } // We can have here ACI objects and java primitives, ugh, both methods\r // dont have to be shown\r passed = checkSbbAciFieldsConstraints ( this . component . getActivityContextInterface ( ) ) ; // finally lets remove asSbb method form abstract lists, this is used\r // later to determine methods that didnt match any sbb definition\r if ( asACIMethod != null ) { sbbAbstractClassAbstraMethod . remove ( ClassUtils . getMethodKey ( asACIMethod ) ) ; sbbAbstractClassAbstraMethodFromSuperClasses . remove ( ClassUtils . getMethodKey ( asACIMethod ) ) ; } if ( ! passed ) { logger . error ( errorBuffer ) ; } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method validates all methods in ACI interface : <ul > <li > set / get methods and parameter names as in CMP fields decalration <li > methods must <ul > <li > be public abstract <li > setters must have one param <li > getters return type must match setter type <li > allowe types are : primitives and serilizable types < / ul > < / ul > <br > Sbb descriptor provides method to obtain aci field names if this test passes it means that all fields there should be correct and can be used to verify aliases [CODESPLIT] boolean checkSbbAciFieldsConstraints ( Class sbbAciInterface ) { boolean passed = true ; String errorBuffer = new String ( \"\" ) ; try { if ( ! sbbAciInterface . isInterface ( ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface MUST be an interface.\" , \"7.5\" , errorBuffer ) ; return passed ; } // here we need all fields :)\r HashSet < String > ignore = new HashSet < String > ( ) ; ignore . add ( ActivityContextInterfaceExt . class . getName ( ) ) ; ignore . add ( ActivityContextInterface . class . getName ( ) ) ; // FIXME: we could go other way, run this for each super interface\r // we\r // have???\r Map < String , Method > aciInterfacesDefinedMethods = ClassUtils . getAllInterfacesMethods ( sbbAciInterface , ignore ) ; // Here we will store fields name-type - if there is getter and\r // setter,\r // type must match!!!\r Map < String , Class > localNameToType = new HashMap < String , Class > ( ) ; for ( String methodKey : aciInterfacesDefinedMethods . keySet ( ) ) { Method fieldMethod = aciInterfacesDefinedMethods . get ( methodKey ) ; String methodName = fieldMethod . getName ( ) ; if ( ! ( methodName . startsWith ( \"get\" ) || methodName . startsWith ( \"set\" ) ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface can have only getter/setter  methods.\" , \"7.5.1\" , errorBuffer ) ; continue ; } // let us get field name:\r String fieldName = methodName . replaceFirst ( \"set\" , \"\" ) . replaceFirst ( \"get\" , \"\" ) ; if ( ! Character . isUpperCase ( fieldName . charAt ( 0 ) ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface can have only getter/setter  methods - 4th char in those methods must be capital.\" , \"7.5.1\" , errorBuffer ) ; } // check throws clause.\r // number of parameters\r if ( fieldMethod . getExceptionTypes ( ) . length > 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface getter method must have empty throws clause: \" + fieldMethod . getName ( ) , \"7.5.1\" , errorBuffer ) ; } boolean isGetter = methodName . startsWith ( \"get\" ) ; Class fieldType = null ; if ( isGetter ) { // no params\r if ( fieldMethod . getParameterTypes ( ) != null && fieldMethod . getParameterTypes ( ) . length > 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface getter method must not have parameters: \" + fieldMethod . getName ( ) , \"7.5.1\" , errorBuffer ) ; } fieldType = fieldMethod . getReturnType ( ) ; if ( fieldType . getName ( ) . compareTo ( \"void\" ) == 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface getter method must have return type: \" + fieldMethod . getName ( ) , \"7.5.1\" , errorBuffer ) ; } } else { if ( fieldMethod . getParameterTypes ( ) != null && fieldMethod . getParameterTypes ( ) . length != 1 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface setter method must single parameter: \" + fieldMethod . getName ( ) , \"7.5.1\" , errorBuffer ) ; // Here we quick fail\r continue ; } fieldType = fieldMethod . getParameterTypes ( ) [ 0 ] ; if ( fieldMethod . getReturnType ( ) . getName ( ) . compareTo ( \"void\" ) != 0 ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface setter method must not have return type: \" + fieldMethod . getName ( ) , \"7.5.1\" , errorBuffer ) ; } } // Field type can be primitive and serialzable\r if ( ! ( _PRIMITIVES . contains ( fieldType . getName ( ) ) || ClassUtils . checkInterfaces ( fieldType , \"java.io.Serializable\" ) != null ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface field(\" + fieldName + \") has wrong type, only primitives and serializable: \" + fieldType , \"7.5.1\" , errorBuffer ) ; // we fail here\r continue ; } if ( localNameToType . containsKey ( fieldName ) ) { Class storedType = localNameToType . get ( fieldName ) ; if ( ! storedType . equals ( fieldType ) ) { passed = false ; errorBuffer = appendToBuffer ( this . component . getAbstractSbbClass ( ) + \" sbb activity context interface has wrong definition of parameter - setter and getter types do not match: \" + fieldName + \", type1: \" + fieldType . getName ( ) + \" typ2:\" + storedType . getName ( ) , \"7.5.1\" , errorBuffer ) ; // we fail here\r continue ; } } else { // simply store\r localNameToType . put ( fieldName , fieldType ) ; } } // FIXME: add check against components get aci fields ?\r } finally { if ( ! passed ) { logger . error ( errorBuffer ) ; } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See section 1 . 3 of jslee 1 . 1 specs [CODESPLIT] boolean validateCompatibilityReferenceConstraints ( ) { boolean passed = true ; String errorBuffer = new String ( \"\" ) ; try { if ( ! this . component . isSlee11 ( ) ) { // A 1.0 SBB must not reference or use a 1.1 Profile\r // Specification. This must be enforced by a 1.1\r // JAIN SLEE.\r for ( ProfileSpecRefDescriptor profileReference : this . component . getDescriptor ( ) . getProfileSpecRefs ( ) ) { ProfileSpecificationComponent specComponent = this . repository . getComponentByID ( profileReference . getComponentID ( ) ) ; if ( specComponent == null ) { // should not happen\r passed = false ; errorBuffer = appendToBuffer ( \"Referenced \" + profileReference . getComponentID ( ) + \" was not found in component repository, this should not happen since dependencies were already verified\" , \"1.3\" , errorBuffer ) ; } else { if ( specComponent . isSlee11 ( ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Sbb is following 1.0 JSLEE contract, it must not reference 1.1 profile specification: \" + profileReference . getComponentID ( ) , \"1.3\" , errorBuffer ) ; } } } } } finally { if ( ! passed ) { if ( logger . isEnabledFor ( Level . ERROR ) ) { logger . error ( errorBuffer ) ; } } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventContext createActivityEndEventContext ( ActivityContext ac , EventUnreferencedCallback unreferencedCallback ) { final EventReferencesHandlerImpl referencesHandler = new EventReferencesHandlerImpl ( ) ; final EventContextData data = dataSource . newEventContextData ( ActivityEndEventImpl . EVENT_TYPE_ID , ActivityEndEventImpl . SINGLETON , ac , null , null , null , null , unreferencedCallback , referencesHandler ) ; final EventContextImpl eventContext = new ActivityEndEventContextImpl ( data , this ) ; referencesHandler . setEventContext ( eventContext ) ; return eventContext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventContext createEventContext ( EventTypeID eventTypeId , Object eventObject , ActivityContext ac , Address address , ServiceID serviceID , EventProcessingSucceedCallback succeedCallback , EventProcessingFailedCallback failedCallback , EventUnreferencedCallback unreferencedCallback ) { final EventReferencesHandlerImpl referencesHandler = new EventReferencesHandlerImpl ( ) ; final EventContextData data = dataSource . newEventContextData ( eventTypeId , eventObject , ac , address , serviceID , succeedCallback , failedCallback , unreferencedCallback , referencesHandler ) ; final EventContextImpl eventContext = new EventContextImpl ( data , this ) ; referencesHandler . setEventContext ( eventContext ) ; return eventContext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection getProfileTables ( ) throws ManagementConsoleException { try { return ( Collection ) mbeanServer . invoke ( profileProvisioningMBean , \"getProfileTables\" , new Object [ ] { } , new String [ ] { } ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection getProfilesByIndexedAttribute ( String arg0 , String arg1 , Object arg2 ) throws ManagementConsoleException { // TODO Auto-generated method stub\r return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > ServiceState< / code > object from an integer value . [CODESPLIT] public static ServiceState fromInt ( int state ) throws IllegalArgumentException { switch ( state ) { case SERVICE_INACTIVE : return INACTIVE ; case SERVICE_ACTIVE : return ACTIVE ; case SERVICE_STOPPING : return STOPPING ; default : throw new IllegalArgumentException ( \"Invalid state: \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > ServiceState< / code > object from an integer value . [CODESPLIT] public static ServiceState fromString ( String state ) throws NullPointerException , IllegalArgumentException { if ( state == null ) throw new NullPointerException ( \"state is null\" ) ; if ( state . equalsIgnoreCase ( INACTIVE_STRING ) ) return INACTIVE ; if ( state . equalsIgnoreCase ( ACTIVE_STRING ) ) return ACTIVE ; if ( state . equalsIgnoreCase ( STOPPING_STRING ) ) return STOPPING ; throw new IllegalArgumentException ( \"Invalid state: \" + state ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an instance of a <code > SleeProvider< / code > peer class . This method is equivalent to { [CODESPLIT] public static SleeProvider getSleeProvider ( String peerClassName ) throws NullPointerException , PeerUnavailableException { ClassLoader classloader = SleeProviderFactory . class . getClassLoader ( ) ; if ( classloader == null ) classloader = ClassLoader . getSystemClassLoader ( ) ; return getSleeProvider ( peerClassName , classloader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an instance of a <code > SleeProvider< / code > peer class using the specified class loader . [CODESPLIT] public static SleeProvider getSleeProvider ( String peerClassName , ClassLoader classloader ) throws NullPointerException , PeerUnavailableException { if ( peerClassName == null ) throw new NullPointerException ( \"peerClassName is null\" ) ; if ( peerClassName . length ( ) == 0 ) throw new PeerUnavailableException ( \"peerClassName is zero-length\" ) ; try { return ( SleeProvider ) classloader . loadClass ( peerClassName ) . newInstance ( ) ; } catch ( Throwable t ) { throw new PeerUnavailableException ( \"Peer class could not be instantiated\" , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "special handling of serialization [CODESPLIT] private void writeObject ( ObjectOutputStream out ) throws IOException { VendorExtensionUtils . writeObject ( out , vendorDataSerializationEnabled ? vendorData : null ) ; if ( cause != null ) { out . writeBoolean ( true ) ; // serialize the cause inside a marshalled object to isolate // the serialized data for it in the stream out . writeObject ( new MarshalledObject ( cause ) ) ; // serialize a text form of the stack trace StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; cause . printStackTrace ( pw ) ; pw . flush ( ) ; out . writeUTF ( sw . getBuffer ( ) . toString ( ) ) ; } else { out . writeBoolean ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "special handling of deserialization [CODESPLIT] private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { vendorData = VendorExtensionUtils . readObject ( in , vendorDataDeserializationEnabled ) ; if ( in . readBoolean ( ) ) { // attempt to deserialize the cause try { cause = ( Throwable ) ( ( MarshalledObject ) in . readObject ( ) ) . get ( ) ; } catch ( ClassNotFoundException cnfe ) { // must have been a class not in standard classloaders and not remotely loadable // do nothing now, we'll replace it with the string version included next in the stream } String causeString = in . readUTF ( ) ; if ( cause == null ) { // replace the cause with a generic exception // that includes the original stack trace in its message cause = new Exception ( \"Undeserializable cause, original cause stack trace follows: \" + causeString ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a collection of ProfileID objects that identify all the profiles contained in the specified profile table . The collection returned is immutable . Any attempt to modify it either directly or indirectly will result in a java . lang . UnsupportedOperationException being thrown . [CODESPLIT] public Collection < ProfileID > getProfiles ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , TransactionRolledbackLocalException , FacilityException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"getProfiles( profileTableName = \" + profileTableName + \" )\" ) ; } profileManagement . getSleeContainer ( ) . getTransactionManager ( ) . mandateTransaction ( ) ; try { return profileManagement . getProfileTable ( profileTableName ) . getProfiles ( ) ; } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( Throwable e ) { throw new FacilityException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a ProfileTableActivity object for a profile table . [CODESPLIT] public ProfileTableActivity getProfileTableActivity ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , TransactionRolledbackLocalException , FacilityException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"getProfileTableActivity( profileTableName = \" + profileTableName + \" )\" ) ; } final SleeTransactionManager sleeTransactionManager = profileManagement . getSleeContainer ( ) . getTransactionManager ( ) ; boolean terminateTx = sleeTransactionManager . requireTransaction ( ) ; try { return profileManagement . getProfileTable ( profileTableName ) . getActivity ( ) ; } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( Throwable e ) { throw new FacilityException ( \"Failed to obtain profile table.\" , e ) ; } finally { // never rollback\r try { sleeTransactionManager . requireTransactionEnd ( terminateTx , false ) ; } catch ( Throwable e ) { throw new FacilityException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a ProfileID object that identifies the profile contained in the specified profile table where the specified profile attribute is set to the specified value . In the case of a profile attribute of an array type the type of the specified value must be the base component type of the array not the array type itself and the SLEE will return the profile identifier of any profile that contains the value within the array . [CODESPLIT] public ProfileID getProfileByIndexedAttribute ( java . lang . String profileTableName , java . lang . String attributeName , java . lang . Object attributeValue ) throws NullPointerException , UnrecognizedProfileTableNameException , UnrecognizedAttributeException , AttributeNotIndexedException , AttributeTypeMismatchException , TransactionRolledbackLocalException , FacilityException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"getProfileByIndexedAttribute( profileTableName = \" + profileTableName + \" , attributeName = \" + attributeName + \" , attributeValue = \" + attributeValue + \" )\" ) ; } profileManagement . getSleeContainer ( ) . getTransactionManager ( ) . mandateTransaction ( ) ; try { ProfileTableImpl profileTable = profileManagement . getProfileTable ( profileTableName ) ; if ( profileTable . getProfileSpecificationComponent ( ) . isSlee11 ( ) ) { throw new FacilityException ( \"JAIN SLEE 1.1 Specs forbidden the usage of this method on SLEE 1.1 Profile Tables\" ) ; } Collection < ProfileID > profileIDs = profileTable . getProfilesByAttribute ( attributeName , attributeValue , false ) ; if ( profileIDs . isEmpty ( ) ) { return null ; } else { return profileIDs . iterator ( ) . next ( ) ; } } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( UnrecognizedAttributeException e ) { throw e ; } catch ( AttributeNotIndexedException e ) { throw e ; } catch ( AttributeTypeMismatchException e ) { throw e ; } catch ( Throwable e ) { throw new FacilityException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public List < ProfileSpecificationDescriptorImpl > parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; List < ProfileSpecificationDescriptorImpl > result = new ArrayList < ProfileSpecificationDescriptorImpl > ( ) ; boolean isSlee11 = false ; MProfileSpecJar mProfileSpecJar = null ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee . profile . ProfileSpecJar ) { mProfileSpecJar = new MProfileSpecJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee . profile . ProfileSpecJar ) jaxbPojo ) ; } else if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . profile . ProfileSpecJar ) { mProfileSpecJar = new MProfileSpecJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . profile . ProfileSpecJar ) jaxbPojo ) ; isSlee11 = true ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } MSecurityPermissions securityPermissions = mProfileSpecJar . getSecurityPermissions ( ) ; for ( MProfileSpec mProfileSpec : mProfileSpecJar . getProfileSpec ( ) ) { result . add ( new ProfileSpecificationDescriptorImpl ( mProfileSpec , securityPermissions , isSlee11 ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to display result of operation . [CODESPLIT] public void displayResult ( ) { //default impl of display;\r if ( ! context . isQuiet ( ) ) { // Translate the result to text\r String resultText = prepareResultText ( ) ; // render results to out\r PrintWriter out = context . getWriter ( ) ; out . println ( resultText ) ; out . flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default implementation . [CODESPLIT] protected String unfoldArray ( String prefix , Object [ ] array , PropertyEditor editor ) { //StringBuffer sb = new StringBuffer(\"\\n\");\r StringBuffer sb = new StringBuffer ( \"[\" ) ; for ( int index = 0 ; index < array . length ; index ++ ) { if ( editor != null ) { editor . setValue ( array [ index ] ) ; sb . append ( editor . getAsText ( ) ) ; } else { sb . append ( array [ index ] . toString ( ) ) ; } if ( index < array . length - 1 ) { sb . append ( CID_SEPARATOR ) ; //sb.append(\"\\n\");\r } } sb . append ( \"]\" ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int compareTo ( Object obj ) { if ( obj == this ) return 0 ; if ( obj == null ) throw new NullPointerException ( ) ; if ( obj . getClass ( ) == this . getClass ( ) ) { return ( ( CongestionControlNotification ) obj ) . localAddress . compareTo ( this . localAddress ) ; } else { return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the specified notification should be delivered to notification listeners using this notification filter . [CODESPLIT] public boolean isNotificationEnabled ( Notification notification ) { if ( ! ( notification instanceof AlarmNotification ) ) return false ; synchronized ( knownAlarms ) { clearStaleTimeouts ( ) ; if ( knownAlarms . containsKey ( notification ) ) return false ; // we've not seen this alarm before, or the period has expired since // the first notification knownAlarms . put ( notification , new Long ( System . currentTimeMillis ( ) ) ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private [CODESPLIT] private void clearStaleTimeouts ( ) { Iterator iterator = knownAlarms . values ( ) . iterator ( ) ; long currentTime = System . currentTimeMillis ( ) ; while ( iterator . hasNext ( ) ) { Long firstSeenTime = ( Long ) iterator . next ( ) ; // if period has expired remove reference to the notification if ( ( firstSeenTime . longValue ( ) + period ) < currentTime ) { iterator . remove ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the specified notification should be delivered to notification listeners using this notification filter . [CODESPLIT] public boolean isNotificationEnabled ( Notification notification ) { if ( ! ( notification instanceof UsageNotification ) ) return false ; UsageNotification usageNotification = ( UsageNotification ) notification ; if ( service != null ) { // SLEE 1.0 comparison if ( ! service . equals ( usageNotification . getService ( ) ) ) return false ; if ( ! sbb . equals ( usageNotification . getSbb ( ) ) ) return false ; } else { // SLEE 1.1 comparison if ( ! notificationSource . equals ( usageNotification . getNotificationSource ( ) ) ) return false ; } if ( ! usageNotification . getUsageParameterName ( ) . equals ( paramName ) ) return false ; long current = usageNotification . getValue ( ) ; try { return ( previous != threshold ) ? ( ( previous < threshold && current > threshold ) || // crossed +ve dir ( previous > threshold && current < threshold ) ) // crossed -ve dir : ( getDirection ( previous , current ) == lastDir ) ; // crossed in last dir } finally { if ( previous != current ) { lastDir = getDirection ( previous , current ) ; previous = current ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a non transacted fire event operation . [CODESPLIT] void execute ( final ActivityHandle realHandle , final ActivityHandle refHandle , final FireableEventType eventType , final Object event , final Address address , final ReceivableService receivableService , final int eventFlags ) throws ActivityIsEndingException , FireEventException , SLEEException , UnrecognizedActivityHandleException { final SleeTransaction tx = super . suspendTransaction ( ) ; try { sleeEndpoint . _fireEvent ( realHandle , refHandle , eventType , event , address , receivableService , eventFlags , tx ) ; } finally { if ( tx != null ) { super . resumeTransaction ( tx ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Generates the profile entity factory class [CODESPLIT] public Class < ? > generateClass ( ) { CtClass ctClass = null ; try { ClassPool classPool = profileComponent . getClassPool ( ) ; Collection < ProfileAttribute > profileAttributes = profileComponent . getProfileAttributes ( ) . values ( ) ; String className = profileEntityClass . getName ( ) + \"F\" ; ctClass = classPool . makeClass ( className ) ; CtClass profileEntityFactoryClass = classPool . get ( ProfileEntityFactory . class . getName ( ) ) ; CtClass [ ] interfaces = new CtClass [ ] { profileEntityFactoryClass } ; ctClass . setInterfaces ( interfaces ) ; // copy newInstance method from interface and generate body CtMethod newInstanceMethod = profileEntityFactoryClass . getDeclaredMethod ( \"newInstance\" ) ; CtMethod newInstanceMethodCopy = CtNewMethod . copy ( newInstanceMethod , ctClass , null ) ; String newInstanceMethodCopyBody = \"{ \" + profileEntityClass . getName ( ) + \" profileEntity = new \" + profileEntityClass . getName ( ) + \"();\" + \" profileEntity.setTableName($1); \" + \" profileEntity.setProfileName($2); \" + \" return profileEntity; \" + \"}\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"\\nAdding method named \" + newInstanceMethodCopy . getName ( ) + \" with body \" + newInstanceMethodCopy + \" , into class \" + className ) ; } newInstanceMethodCopy . setBody ( newInstanceMethodCopyBody ) ; ctClass . addMethod ( newInstanceMethodCopy ) ; // copy copyAttributes method from interface and generate body CtMethod copyAttributesMethod = profileEntityFactoryClass . getDeclaredMethod ( \"copyAttributes\" ) ; CtMethod copyAttributesMethodCopy = CtNewMethod . copy ( copyAttributesMethod , ctClass , null ) ; // body header String copyAttributesMethodCopyBody = \"{ \" + profileEntityClass . getName ( ) + \" newProfileEntity = (\" + profileEntityClass . getName ( ) + \") $2; \" + profileEntityClass . getName ( ) + \" oldProfileEntity = (\" + profileEntityClass . getName ( ) + \") $1; \" ; // process fields copy String profileEntityAttributeArrayValueClassName = null ; if ( System . getSecurityManager ( ) == null ) { for ( ProfileAttribute profileAttribute : profileAttributes ) { String accessorMethodSufix = ClassGeneratorUtils . getPojoCmpAccessorSufix ( profileAttribute . getName ( ) ) ; if ( profileAttribute . isArray ( ) ) { profileEntityAttributeArrayValueClassName = profileEntityAttributeArrayValueClasses . get ( profileAttribute . getName ( ) ) . getName ( ) ; copyAttributesMethodCopyBody += \"if (oldProfileEntity.get\" + accessorMethodSufix + \"() != null) { \" + // if the target list already exists then empty it so elements get deleted, otherwise create new List . class . getName ( ) + \" new\" + profileAttribute . getName ( ) + \" = newProfileEntity.get\" + accessorMethodSufix + \"(); \" + \"if (new\" + profileAttribute . getName ( ) + \" == null) { new\" + profileAttribute . getName ( ) + \" = new \" + LinkedList . class . getName ( ) + \"(); } else { new\" + profileAttribute . getName ( ) + \".clear(); } \" + // extract list to copy List . class . getName ( ) + \" old\" + profileAttribute . getName ( ) + \" = oldProfileEntity.get\" + accessorMethodSufix + \"(); \" + // iterate each list element \"for (\" + Iterator . class . getName ( ) + \" i = old\" + profileAttribute . getName ( ) + \".iterator(); i.hasNext();) { \" + profileEntityAttributeArrayValueClassName + \" oldArrayValue = (\" + profileEntityAttributeArrayValueClassName + \") i.next(); \" + profileEntityAttributeArrayValueClassName + \" newArrayValue = new \" + profileEntityAttributeArrayValueClassName + \"(); \" + // link to profile entity \"newArrayValue.setOwner( newProfileEntity ); \" + // copy fields \"newArrayValue.setString( oldArrayValue.getString() ); \" + \"newArrayValue.setSerializable( (\" + Serializable . class . getName ( ) + \") \" + ObjectCloner . class . getName ( ) + \".makeDeepCopy(oldArrayValue.getSerializable()) ); \" + \"new\" + profileAttribute . getName ( ) + \".add(newArrayValue); \" + \"} \" + \"newProfileEntity.set\" + accessorMethodSufix + \"(new\" + profileAttribute . getName ( ) + \"); };\" ; } else { if ( profileAttribute . isPrimitive ( ) ) { // just copy value copyAttributesMethodCopyBody += \" newProfileEntity.set\" + accessorMethodSufix + \"(oldProfileEntity.get\" + accessorMethodSufix + \"()); \" ; } else { // just copy value but do a deep copy copyAttributesMethodCopyBody += \" if (oldProfileEntity.get\" + accessorMethodSufix + \"() != null) { newProfileEntity.set\" + accessorMethodSufix + \"((\" + profileAttribute . getType ( ) . getName ( ) + \")\" + ObjectCloner . class . getName ( ) + \".makeDeepCopy(oldProfileEntity.get\" + accessorMethodSufix + \"())); }; \" ; } } } } else { for ( ProfileAttribute profileAttribute : profileAttributes ) { String accessorMethodSufix = ClassGeneratorUtils . getPojoCmpAccessorSufix ( profileAttribute . getName ( ) ) ; if ( profileAttribute . isArray ( ) ) { profileEntityAttributeArrayValueClassName = profileEntityAttributeArrayValueClasses . get ( profileAttribute . getName ( ) ) . getName ( ) ; copyAttributesMethodCopyBody += \"if (\" + Utility . class . getName ( ) + \".makeSafeProxyCall(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\",null,null) != null) {\" + \"\" + // if the target list already exists then empty it so elements get deleted, otherwise create new List . class . getName ( ) + \" new\" + profileAttribute . getName ( ) + \" = newProfileEntity.get\" + accessorMethodSufix + \"(); \" + \"if (new\" + profileAttribute . getName ( ) + \" == null) { new\" + profileAttribute . getName ( ) + \" = new \" + LinkedList . class . getName ( ) + \"(); } else { new\" + profileAttribute . getName ( ) + \".clear(); } \" + // extract list to copy //List.class.getName() + \" old\"+ profileAttribute.getName() + \" = oldProfileEntity.get\" + accessorMethodSufix + \"(); \" + List . class . getName ( ) + \" old\" + profileAttribute . getName ( ) + \" = (\" + List . class . getName ( ) + \")\" + Utility . class . getName ( ) + \".makeSafeProxyCall(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\",null,null);\" + // iterate each list element  Iterator . class . getName ( ) + \" i = \" + Utility . class . getName ( ) + \".makeSafeProxyCall(old\" + profileAttribute . getName ( ) + \",\\\"iterator\\\",null,null);\" + \"for (; \" + Utility . class . getName ( ) + \".evaluateNext(i);) { \" + profileEntityAttributeArrayValueClassName + \" oldArrayValue = (\" + profileEntityAttributeArrayValueClassName + \") i.next();\" + profileEntityAttributeArrayValueClassName + \" newArrayValue = new \" + profileEntityAttributeArrayValueClassName + \"(); \" + // link to profile entity \"newArrayValue.setOwner( newProfileEntity ); \" + // copy fields \"newArrayValue.setString( oldArrayValue.getString() ); \" + \"newArrayValue.setSerializable( (\" + Serializable . class . getName ( ) + \") \" + ObjectCloner . class . getName ( ) + \".makeDeepCopy(oldArrayValue.getSerializable()) ); \" + \"new\" + profileAttribute . getName ( ) + \".add(newArrayValue); \" + \"} \" + //\"newProfileEntity.set\"+accessorMethodSufix+\"(new\"+profileAttribute.getName()+\"); };\"; Utility . class . getName ( ) + \".makeSafeProxyCall(newProfileEntity,\\\"set\" + accessorMethodSufix + \"\\\",new Class[]{\" + Utility . class . getName ( ) + \".getReturnType(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\")},new Object[]{new\" + profileAttribute . getName ( ) + \"});}\" ; } else { if ( profileAttribute . isPrimitive ( ) ) { // just copy value //copyAttributesMethodCopyBody +=  //\t  \" newProfileEntity.set\"+accessorMethodSufix+\"(oldProfileEntity.get\"+accessorMethodSufix+\"()); \"; copyAttributesMethodCopyBody += \"Object value = \" + Utility . class . getName ( ) + \".makeSafeProxyCall(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\",null,null);\" ; copyAttributesMethodCopyBody += Utility . class . getName ( ) + \".makeSafeProxyCall(newProfileEntity,\\\"set\" + accessorMethodSufix + \"\\\",new Class[]{\" + Utility . class . getName ( ) + \".getReturnType(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\")},new Object[]{value});\" ; } else { // just copy value but do a deep copy copyAttributesMethodCopyBody += \"if (\" + Utility . class . getName ( ) + \".makeSafeProxyCall(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\",null,null) != null)  \" + \"{ Object value = \" + Utility . class . getName ( ) + \".makeSafeProxyCall(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\",null,null);\" //+\"newProfileEntity.set\"+accessorMethodSufix+\"((\"+profileAttribute.getType().getName()+\")\"+ObjectCloner.class.getName()+\".makeDeepCopy(value)); }; \" + Utility . class . getName ( ) + \".makeSafeProxyCall(newProfileEntity,\\\"set\" + accessorMethodSufix + \"\\\",new Class[]{\" + Utility . class . getName ( ) + \".getReturnType(oldProfileEntity,\\\"get\" + accessorMethodSufix + \"\\\")},new Object[]{\" + ObjectCloner . class . getName ( ) + \".makeDeepCopy(value)});\" + \"}\" ; } } } } // body footer copyAttributesMethodCopyBody += \" }\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"\\nAdding method named \" + copyAttributesMethodCopy . getName ( ) + \" with body \" + copyAttributesMethodCopyBody + \" , into class \" + className ) ; } copyAttributesMethodCopy . setBody ( copyAttributesMethodCopyBody ) ; ctClass . addMethod ( copyAttributesMethodCopy ) ; String deployDir = profileComponent . getDeploymentDir ( ) . getAbsolutePath ( ) ; // write class if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Writing ProfileEntityFactory generated class ( \" + ctClass . getName ( ) + \" ) to: \" + deployDir ) ; } ctClass . writeFile ( deployDir ) ; return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } finally { if ( ctClass != null ) { try { ctClass . defrost ( ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the specified aci name with the specified activity context handle [CODESPLIT] public void bindName ( Object ach , String name ) throws NameAlreadyBoundException { final Node node = getNode ( ) ; if ( node . hasChild ( name ) ) { throw new NameAlreadyBoundException ( \"name already bound\" ) ; } else { node . addChild ( Fqn . fromElements ( name ) ) . put ( CACHE_NODE_MAP_KEY , ach ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbinds the specified aci name with the specified activity context id [CODESPLIT] public Object unbindName ( String name ) throws NameNotBoundException { final Node node = getNode ( ) ; final Node childNode = node . getChild ( name ) ; if ( childNode == null ) { throw new NameNotBoundException ( \"name not bound\" ) ; } else { final Object ach = childNode . get ( CACHE_NODE_MAP_KEY ) ; node . removeChild ( name ) ; return ach ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup of the activity context id bound to the specified aci name [CODESPLIT] public Object lookupName ( String name ) { final Node childNode = getNode ( ) . getChild ( name ) ; if ( childNode == null ) { return null ; } else { return childNode . get ( CACHE_NODE_MAP_KEY ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a map of the bindings . Key is the aci name and Value is the activity context handle [CODESPLIT] public Map getNameBindings ( ) { Map result = new HashMap ( ) ; Node childNode = null ; Object name = null ; for ( Object obj : getNode ( ) . getChildren ( ) ) { childNode = ( Node ) obj ; name = childNode . getFqn ( ) . getLastElement ( ) ; result . put ( name , childNode . get ( CACHE_NODE_MAP_KEY ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName preRegister ( MBeanServer mbs , ObjectName oname ) throws Exception { this . objectName = oname ; this . server = mbs ; return oname ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the next sbb entity to handle the event . [CODESPLIT] public Result next ( ActivityContext ac , EventContext sleeEvent , Set < SbbEntityID > sbbEntitiesThatHandledCurrentEvent , SleeContainer sleeContainer ) { SbbEntityID sbbEntityId = null ; SbbEntity sbbEntity = null ; EventEntryDescriptor mEventEntry = null ; // get the highest priority sbb from sbb entities attached to AC for ( Iterator < SbbEntityID > iter = ac . getSortedSbbAttachmentSet ( sbbEntitiesThatHandledCurrentEvent ) . iterator ( ) ; iter . hasNext ( ) ; ) { sbbEntityId = iter . next ( ) ; sbbEntity = sleeContainer . getSbbEntityFactory ( ) . getSbbEntity ( sbbEntityId , true ) ; if ( sbbEntity == null ) { // ignore, sbb entity has been removed continue ; } if ( eventRouterConfiguration . isConfirmSbbEntityAttachement ( ) && ! sbbEntity . isAttached ( ac . getActivityContextHandle ( ) ) ) { // detached by a concurrent tx, see Issue 2313 \t\t\t\t continue ; } if ( sleeEvent . getService ( ) != null && ! sleeEvent . getService ( ) . equals ( sbbEntityId . getServiceID ( ) ) ) { if ( ! sleeEvent . isActivityEndEvent ( ) ) { continue ; } else { return new Result ( sbbEntity , false ) ; } } // check event is allowed to be handled by the sbb mEventEntry = sbbEntity . getSbbComponent ( ) . getDescriptor ( ) . getEventEntries ( ) . get ( sleeEvent . getEventTypeId ( ) ) ; if ( mEventEntry != null && mEventEntry . isReceived ( ) ) { return new Result ( sbbEntity , true ) ; } else { if ( ! sleeEvent . isActivityEndEvent ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Event is not received by sbb descriptor of entity \" + sbbEntityId + \", will not deliver event to sbb entity ...\" ) ; } continue ; } else { return new Result ( sbbEntity , false ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > TraceLevel< / code > object from an integer value . [CODESPLIT] public static TraceLevel fromInt ( int level ) throws IllegalArgumentException { switch ( level ) { case LEVEL_OFF : return OFF ; case LEVEL_SEVERE : return SEVERE ; case LEVEL_WARNING : return WARNING ; case LEVEL_INFO : return INFO ; case LEVEL_CONFIG : return CONFIG ; case LEVEL_FINE : return FINE ; case LEVEL_FINER : return FINER ; case LEVEL_FINEST : return FINEST ; default : throw new IllegalArgumentException ( \"Invalid level: \" + level ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > TraceLevel< / code > object from a string value . [CODESPLIT] public static TraceLevel fromString ( String level ) throws NullPointerException , IllegalArgumentException { if ( level == null ) throw new NullPointerException ( \"level is null\" ) ; if ( level . equalsIgnoreCase ( OFF_STRING ) ) return OFF ; if ( level . equalsIgnoreCase ( SEVERE_STRING ) ) return SEVERE ; if ( level . equalsIgnoreCase ( WARNING_STRING ) ) return WARNING ; if ( level . equalsIgnoreCase ( INFO_STRING ) ) return INFO ; if ( level . equalsIgnoreCase ( CONFIG_STRING ) ) return CONFIG ; if ( level . equalsIgnoreCase ( FINE_STRING ) ) return FINE ; if ( level . equalsIgnoreCase ( FINER_STRING ) ) return FINER ; if ( level . equalsIgnoreCase ( FINEST_STRING ) ) return FINEST ; throw new IllegalArgumentException ( \"Invalid level: \" + level ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this TraceLevel object represents a level that is higher than some other TraceLevel object . For the purposes of the comparison OFF is considered a higher level than SEVERE and FINEST is the lowest level . [CODESPLIT] public boolean isHigherLevel ( TraceLevel other ) throws NullPointerException { if ( other == null ) throw new NullPointerException ( \"other is null\" ) ; return this . level < other . level ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void installProfileSpecification ( ProfileSpecificationComponent component ) throws DeploymentException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Installing \" + component ) ; } try { JndiManagement jndiManagement = sleeContainer . getJndiManagement ( ) ; logger . debug ( \"JndiManagement: \" + jndiManagement + \" for ProfileSpecificationComponent: \" + component ) ; jndiManagement . componentInstall ( component ) ; jndiManagement . pushJndiContext ( component ) ; try { this . createJndiSpace ( component ) ; } finally { jndiManagement . popJndiContext ( ) ; } // FIXME: we wont use trace and alarm in 1.0 way wont we? ProfileEntityFramework profileEntityFramework = new JPAProfileEntityFramework ( component , configuration , sleeContainer . getTransactionManager ( ) ) ; profileEntityFramework . install ( ) ; sleeProfileClassCodeGenerator . process ( component ) ; profileTableFramework . loadProfileTables ( component ) ; } catch ( DeploymentException de ) { throw de ; } catch ( Throwable t ) { t . printStackTrace ( ) ; throw new SLEEException ( t . getMessage ( ) , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void uninstallProfileSpecification ( ProfileSpecificationComponent component ) throws UnrecognizedProfileSpecificationException { Collection < String > profileTableNames = getDeclaredProfileTableNames ( component . getProfileSpecificationID ( ) ) ; for ( String profileTableName : profileTableNames ) { try { this . removeProfileTable ( profileTableName , true ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } // FIXME: For JBoss 7.2.0.Final: // we have a problem with org.hibernate.service.UnknownServiceException: // Unknown service requested [org.hibernate.event.service.spi.EventListenerRegistry] // see https://hibernate.atlassian.net/browse/HHH-8586 //component.getProfileEntityFramework().uninstall(); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileTableImpl getProfileTable ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException { if ( profileTableName == null ) throw new NullPointerException ( \"profile table name is null\" ) ; ProfileTableImpl profileTable = null ; if ( sleeContainer . getCluster ( ) . getMobicentsCache ( ) . isLocalMode ( ) ) { // no replication, table may only exist in local resources profileTable = profileTablesLocalObjects . get ( profileTableName ) ; if ( profileTable == null ) { throw new UnrecognizedProfileTableNameException ( profileTableName ) ; } } else { if ( ! profileTableFramework . getConfiguration ( ) . isClusteredProfiles ( ) ) { // profiles are not clustered, table may only exist in local resources profileTable = profileTablesLocalObjects . get ( profileTableName ) ; if ( profileTable == null ) { throw new UnrecognizedProfileTableNameException ( ) ; } } else { // profiles are clustered, table may exist \"remotely\" and not in local resources, due to runtime creation in another cluster node, we need to go to database first final ProfileSpecificationID profileSpecificationID = profileTableFramework . getProfileSpecificationID ( profileTableName ) ; if ( profileSpecificationID != null ) { // exists in database profileTable = profileTablesLocalObjects . get ( profileTableName ) ; if ( profileTable == null ) { // local resource does not exists, create it ProfileSpecificationComponent component = sleeContainer . getComponentRepository ( ) . getComponentByID ( profileSpecificationID ) ; if ( component != null ) { profileTable = addProfileTableLocally ( createProfileTableInstance ( profileTableName , component ) , false , false ) ; } } } else { // does not exists in database, ensure it is not in local objects profileTablesLocalObjects . remove ( profileTableName ) ; } } } if ( profileTable == null ) throw new UnrecognizedProfileTableNameException ( ) ; else return profileTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventContextHandle getEventContextHandle ( ) { if ( handle == null ) { handle = new EventContextHandleImpl ( factory . getSleeContainer ( ) . getUuidGenerator ( ) . createUUID ( ) ) ; factory . getDataSource ( ) . addEventContext ( handle , this ) ; } return handle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check which combination ( see JSLEE 1 . 0 spec section 10 . 5 . 2 ) matches the Sbb Developer s Profile Specification [CODESPLIT] public static int checkCombination ( ProfileSpecificationComponent component ) { Object profileCmpInterface = component . getDescriptor ( ) . getProfileCMPInterface ( ) ; Object profileManagementInterface = component . getDescriptor ( ) . getProfileManagementInterface ( ) ; Object profileManagementAbstractClass = component . getDescriptor ( ) . getProfileAbstractClass ( ) ; //Object profileManagementLocalObjectInterface = compoenent.getDescriptor().getProfileLocalInterface();\r // if the Profile Specification has no Profile CMP interface, it is incorrect\r if ( profileCmpInterface == null ) return - 1 ; //    if (compoenent.isSlee11()) {\r //      if (profileCmpInterface != null && profileManagementLocalObjectInterface != null && profileManagementAbstractClass != null)\r //        return 4;\r //      if (profileCmpInterface != null && profileManagementAbstractClass != null)\r //        return 3;\r //      if (profileCmpInterface != null && profileManagementLocalObjectInterface != null)\r //        return 2;\r //\r //      return 1;\r //    }\r //    else\r //    {\r if ( profileCmpInterface != null && profileManagementInterface != null && profileManagementAbstractClass != null ) return 4 ; if ( profileCmpInterface != null && profileManagementAbstractClass != null ) return 3 ; if ( profileCmpInterface != null && profileManagementInterface != null ) return 2 ; return 1 ; //    }\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates an invocation of the { @link SbbLocalObject } . [CODESPLIT] private void validateInvocation ( ) throws TransactionRolledbackLocalException , NoSuchObjectLocalException , SLEEException { // validate tx sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; // validate object if ( this . rollbackOnly ) { try { sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; } catch ( SystemException ex ) { throw new SLEEException ( \"unable to set rollbackOnly in transaction manager\" , ex ) ; } throw new TransactionRolledbackLocalException ( \"Unable to proceed, transaction is set to rollback\" ) ; } if ( this . isRemoved ) throw new NoSuchObjectLocalException ( \"sbb local object is removed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean isIdentical ( javax . slee . SbbLocalObject obj ) throws TransactionRequiredLocalException , SLEEException { validateInvocation ( ) ; return this . equals ( obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void remove ( ) throws TransactionRequiredLocalException , NoSuchObjectLocalException , SLEEException { if ( trace ) logger . trace ( \"remove()\" ) ; validateInvocation ( ) ; if ( ! sbbEntity . isReentrant ( ) && sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) . getInvokedNonReentrantSbbEntities ( ) . contains ( sbbEntity . getSbbEntityId ( ) ) ) throw new SLEEException ( \" re-entrancy not allowed \" ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"nonSleeInitiatedCascadingRemoval : \" + sbbEntity . getSbbId ( ) + \" entityID = \" + sbbEntity . getSbbEntityId ( ) ) ; } try { sleeContainer . getSbbEntityFactory ( ) . removeSbbEntity ( sbbEntity , false ) ; } catch ( Throwable e ) { throw new SLEEException ( \"Removal of the sbb entity failed\" , e ) ; } try { if ( sleeContainer . getTransactionManager ( ) . getRollbackOnly ( ) ) { final TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; EventRoutingTransactionData ertd = txContext . getEventRoutingTransactionData ( ) ; txContext . getAfterRollbackActions ( ) . add ( new RolledBackAction ( sbbEntity . getSbbEntityId ( ) , ertd . getEventBeingDelivered ( ) . getEvent ( ) , ertd . getAciReceivingEvent ( ) , true ) ) ; } } catch ( Exception e ) { throw new SLEEException ( \"Failed to check and possibly set rollback context of entity \" + sbbEntity . getSbbEntityId ( ) , e ) ; } // I Think this should set isRemoved only to true but then test 323 // will fail. // :-( // Ralf: see above this . rollbackOnly = true ; this . isRemoved = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setSbbPriority ( byte priority ) throws TransactionRequiredLocalException , NoSuchObjectLocalException , SLEEException { if ( trace ) logger . trace ( \"setSbbPriority( priority = \" + priority + \" )\" ) ; validateInvocation ( ) ; sbbEntity . setPriority ( priority ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the DU component from a jar with the specified file name contained in the specified DU jar file . The component is built in the specified deployment dir . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) public List < AbstractSleeComponent > buildComponents ( String componentJarFileName , JarFile deployableUnitJar , File deploymentDir ) throws DeploymentException { // extract the component jar from the DU jar, to the temp du dir File extractedFile = extractFile ( componentJarFileName , deployableUnitJar , deploymentDir ) ; JarFile componentJarFile = null ; try { componentJarFile = new JarFile ( extractedFile ) ; } catch ( IOException e ) { throw new DeploymentException ( \"failed to create jar file for extracted file \" + extractedFile ) ; } InputStream componentDescriptorInputStream = null ; List < AbstractSleeComponent > components = new ArrayList < AbstractSleeComponent > ( ) ; try { // now extract the jar file to a new dir File componentJarDeploymentDir = new File ( deploymentDir , componentJarFileName + \"-contents\" ) ; if ( ! componentJarDeploymentDir . exists ( ) ) { // the jar may not be on root of DU, create additional dirs if needed LinkedList < File > dirsToCreate = new LinkedList < File > ( ) ; File dir = componentJarDeploymentDir . getParentFile ( ) ; while ( ! dir . equals ( deploymentDir ) ) { dirsToCreate . addFirst ( dir ) ; dir = dir . getParentFile ( ) ; } for ( File f : dirsToCreate ) { f . mkdir ( ) ; } // now create the dir for the component jar if ( ! componentJarDeploymentDir . mkdir ( ) ) { throw new SLEEException ( \"dir for jar \" + componentJarFileName + \" not created in \" + deploymentDir ) ; } } else { throw new SLEEException ( \"dir for jar \" + componentJarFileName + \" already exists in \" + deploymentDir ) ; } extractJar ( componentJarFile , componentJarDeploymentDir ) ; // create components from descriptor JarEntry componentDescriptor = null ; if ( ( componentDescriptor = componentJarFile . getJarEntry ( \"META-INF/sbb-jar.xml\" ) ) != null ) { // create class loader domain shared by all components URLClassLoaderDomainImpl classLoaderDomain = componentManagement . getClassLoaderFactory ( ) . newClassLoaderDomain ( new URL [ ] { componentJarDeploymentDir . toURL ( ) } , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; // parse descriptor componentDescriptorInputStream = componentJarFile . getInputStream ( componentDescriptor ) ; SbbDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getSbbDescriptorFactory ( ) ; List < SbbDescriptorImpl > descriptors = descriptorFactory . parse ( componentDescriptorInputStream ) ; // create components for ( SbbDescriptorImpl descriptor : descriptors ) { PreferredPackagesBuilder . buildPreferredPackages ( descriptor , classLoaderDomain ) ; SbbComponentImpl component = new SbbComponentImpl ( descriptor ) ; component . setDeploymentDir ( componentJarDeploymentDir ) ; component . setClassLoaderDomain ( classLoaderDomain ) ; components . add ( component ) ; } } else if ( ( componentDescriptor = componentJarFile . getJarEntry ( \"META-INF/profile-spec-jar.xml\" ) ) != null ) { // create class loader domain shared by all components URLClassLoaderDomainImpl classLoaderDomain = componentManagement . getClassLoaderFactory ( ) . newClassLoaderDomain ( new URL [ ] { componentJarDeploymentDir . toURL ( ) } , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; // parse descriptor componentDescriptorInputStream = componentJarFile . getInputStream ( componentDescriptor ) ; ProfileSpecificationDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getProfileSpecificationDescriptorFactory ( ) ; List < ProfileSpecificationDescriptorImpl > descriptors = descriptorFactory . parse ( componentDescriptorInputStream ) ; // create components for ( ProfileSpecificationDescriptorImpl descriptor : descriptors ) { ProfileSpecificationComponentImpl component = new ProfileSpecificationComponentImpl ( descriptor ) ; component . setDeploymentDir ( componentJarDeploymentDir ) ; component . setClassLoaderDomain ( classLoaderDomain ) ; components . add ( component ) ; } } else if ( ( componentDescriptor = componentJarFile . getJarEntry ( \"META-INF/library-jar.xml\" ) ) != null ) { Set < LibraryComponentImpl > libraryComponents = new HashSet < LibraryComponentImpl > ( ) ; // we need to gather all URLs for the shared class loader domain // to watch Set < URL > classLoaderDomainURLs = new HashSet < URL > ( ) ; classLoaderDomainURLs . add ( componentJarDeploymentDir . toURL ( ) ) ; // parse the descriptor componentDescriptorInputStream = componentJarFile . getInputStream ( componentDescriptor ) ; LibraryDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getLibraryDescriptorFactory ( ) ; List < LibraryDescriptorImpl > descriptors = descriptorFactory . parse ( componentDescriptorInputStream ) ; // create components for ( LibraryDescriptorImpl descriptor : descriptors ) { LibraryComponentImpl component = new LibraryComponentImpl ( descriptor ) ; for ( JarDescriptor mJar : descriptor . getJars ( ) ) { classLoaderDomainURLs . add ( new File ( componentJarDeploymentDir , mJar . getJarName ( ) ) . toURL ( ) ) ; } // set deploy dir and cl domain component . setDeploymentDir ( componentJarDeploymentDir ) ; components . add ( component ) ; libraryComponents . add ( component ) ; } // create shared url domain URLClassLoaderDomainImpl classLoaderDomain = componentManagement . getClassLoaderFactory ( ) . newClassLoaderDomain ( classLoaderDomainURLs . toArray ( new URL [ classLoaderDomainURLs . size ( ) ] ) , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; // add it to each component for ( LibraryComponentImpl component : libraryComponents ) { component . setClassLoaderDomain ( classLoaderDomain ) ; } } else if ( ( componentDescriptor = componentJarFile . getJarEntry ( \"META-INF/event-jar.xml\" ) ) != null ) { // create class loader domain shared by all components URLClassLoaderDomainImpl classLoaderDomain = componentManagement . getClassLoaderFactory ( ) . newClassLoaderDomain ( new URL [ ] { componentJarDeploymentDir . toURL ( ) } , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; // parse descriptor componentDescriptorInputStream = componentJarFile . getInputStream ( componentDescriptor ) ; EventTypeDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getEventTypeDescriptorFactory ( ) ; List < EventTypeDescriptorImpl > descriptors = descriptorFactory . parse ( componentDescriptorInputStream ) ; // create components for ( EventTypeDescriptorImpl descriptor : descriptors ) { EventTypeComponentImpl component = new EventTypeComponentImpl ( descriptor ) ; component . setDeploymentDir ( componentJarDeploymentDir ) ; component . setClassLoaderDomain ( classLoaderDomain ) ; components . add ( component ) ; } } else if ( ( componentDescriptor = componentJarFile . getJarEntry ( \"META-INF/resource-adaptor-type-jar.xml\" ) ) != null ) { // create class loader domain shared by all components URLClassLoaderDomainImpl classLoaderDomain = componentManagement . getClassLoaderFactory ( ) . newClassLoaderDomain ( new URL [ ] { componentJarDeploymentDir . toURL ( ) } , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; // parse descriptor componentDescriptorInputStream = componentJarFile . getInputStream ( componentDescriptor ) ; ResourceAdaptorTypeDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getResourceAdaptorTypeDescriptorFactory ( ) ; List < ResourceAdaptorTypeDescriptorImpl > descriptors = descriptorFactory . parse ( componentDescriptorInputStream ) ; // create components for ( ResourceAdaptorTypeDescriptorImpl descriptor : descriptors ) { ResourceAdaptorTypeComponentImpl component = new ResourceAdaptorTypeComponentImpl ( descriptor ) ; component . setDeploymentDir ( componentJarDeploymentDir ) ; component . setClassLoaderDomain ( classLoaderDomain ) ; components . add ( component ) ; } } else if ( ( componentDescriptor = componentJarFile . getJarEntry ( \"META-INF/resource-adaptor-jar.xml\" ) ) != null ) { // create class loader domain shared by all components URLClassLoaderDomainImpl classLoaderDomain = componentManagement . getClassLoaderFactory ( ) . newClassLoaderDomain ( new URL [ ] { componentJarDeploymentDir . toURL ( ) } , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; // parse descriptor componentDescriptorInputStream = componentJarFile . getInputStream ( componentDescriptor ) ; ResourceAdaptorDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getResourceAdaptorDescriptorFactory ( ) ; List < ResourceAdaptorDescriptorImpl > descriptors = descriptorFactory . parse ( componentDescriptorInputStream ) ; // create components for ( ResourceAdaptorDescriptorImpl descriptor : descriptors ) { ResourceAdaptorComponentImpl component = new ResourceAdaptorComponentImpl ( descriptor ) ; component . setDeploymentDir ( componentJarDeploymentDir ) ; component . setClassLoaderDomain ( classLoaderDomain ) ; components . add ( component ) ; } } else { throw new DeploymentException ( \"No Deployment Descriptor found in the \" + componentJarFile . getName ( ) + \" entry of a deployable unit.\" ) ; } } catch ( IOException e ) { throw new DeploymentException ( \"failed to parse jar descriptor from \" + componentJarFile . getName ( ) , e ) ; } finally { if ( componentDescriptorInputStream != null ) { try { componentDescriptorInputStream . close ( ) ; } catch ( IOException e ) { logger . error ( \"failed to close inputstream of descriptor for jar \" + componentJarFile ) ; } } } // close component jar file try { componentJarFile . close ( ) ; } catch ( IOException e ) { logger . error ( \"failed to close component jar file\" , e ) ; } // and delete the extracted jar file, we don't need it anymore if ( ! extractedFile . delete ( ) ) { logger . warn ( \"failed to delete \" + extractedFile ) ; } return components ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the file with name <code > fileName< / code > out of the <code > containingJar< / code > archive and stores it in <code > dstDir< / code > . [CODESPLIT] private File extractFile ( String fileName , JarFile containingJar , File dstDir ) throws DeploymentException { ZipEntry zipFileEntry = containingJar . getEntry ( fileName ) ; logger . trace ( \"Extracting file \" + fileName + \" from \" + containingJar . getName ( ) ) ; if ( zipFileEntry == null ) { throw new DeploymentException ( \"Error extracting jar file  \" + fileName + \" from \" + containingJar . getName ( ) ) ; } File extractedFile = new File ( dstDir , new File ( zipFileEntry . getName ( ) ) . getName ( ) ) ; try { pipeStream ( containingJar . getInputStream ( zipFileEntry ) , new FileOutputStream ( extractedFile ) ) ; } catch ( FileNotFoundException e ) { throw new DeploymentException ( \"file \" + fileName + \" not found in \" + containingJar . getName ( ) , e ) ; } catch ( IOException e ) { throw new DeploymentException ( \"erro extracting file \" + fileName + \" from \" + containingJar . getName ( ) , e ) ; } logger . debug ( \"Extracted file \" + extractedFile . getName ( ) ) ; return extractedFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will extract all the files in the jar file [CODESPLIT] private void extractJar ( JarFile jarFile , File dstDir ) throws DeploymentException { // Extract jar contents to a classpath location JarInputStream jarIs = null ; try { jarIs = new JarInputStream ( new BufferedInputStream ( new FileInputStream ( jarFile . getName ( ) ) ) ) ; for ( JarEntry entry = jarIs . getNextJarEntry ( ) ; jarIs . available ( ) > 0 && entry != null ; entry = jarIs . getNextJarEntry ( ) ) { logger . trace ( \"jar entry = \" + entry . getName ( ) ) ; if ( entry . isDirectory ( ) ) { // Create jar directories. File dir = new File ( dstDir , entry . getName ( ) ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) { logger . debug ( \"Failed to create directory \" + dir . getAbsolutePath ( ) ) ; throw new IOException ( \"Failed to create directory \" + dir . getAbsolutePath ( ) ) ; } } else logger . trace ( \"Created directory\" + dir . getAbsolutePath ( ) ) ; } else // unzip files { File file = new File ( dstDir , entry . getName ( ) ) ; File dir = file . getParentFile ( ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) { logger . debug ( \"Failed to create directory \" + dir . getAbsolutePath ( ) ) ; throw new IOException ( \"Failed to create directory \" + dir . getAbsolutePath ( ) ) ; } else logger . trace ( \"Created directory\" + dir . getAbsolutePath ( ) ) ; } pipeStream ( jarFile . getInputStream ( entry ) , new FileOutputStream ( file ) ) ; } } } catch ( Exception e ) { throw new DeploymentException ( \"failed to extract jar file \" + jarFile . getName ( ) ) ; } finally { if ( jarIs != null ) { try { jarIs . close ( ) ; } catch ( IOException e ) { logger . error ( \"failed to close jar input stream\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pipes data from the input stream into the output stream . [CODESPLIT] private void pipeStream ( InputStream is , OutputStream os ) throws IOException { synchronized ( buffer ) { try { for ( int bytesRead = is . read ( buffer ) ; bytesRead != - 1 ; bytesRead = is . read ( buffer ) ) os . write ( buffer , 0 , bytesRead ) ; is . close ( ) ; os . close ( ) ; } catch ( IOException ioe ) { try { is . close ( ) ; } catch ( Exception ioexc ) { /* do sth? */ } try { os . close ( ) ; } catch ( Exception ioexc ) { /* do sth? */ } throw ioe ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts an object in cache data [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Object putObject ( Object key , Object value ) { return getNode ( ) . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to attaches an sbb entity [CODESPLIT] public boolean attachSbbEntity ( SbbEntityID sbbEntityId ) { final Node node = getAttachedSbbsNode ( true ) ; if ( ! node . hasChild ( sbbEntityId ) ) { node . addChild ( Fqn . fromElements ( sbbEntityId ) ) ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detaches an sbb entity [CODESPLIT] public boolean detachSbbEntity ( SbbEntityID sbbEntityId ) { final Node node = getAttachedSbbsNode ( false ) ; return node != null ? node . removeChild ( sbbEntityId ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if there at least one sbb entity attached [CODESPLIT] public boolean noSbbEntitiesAttached ( ) { final Node node = getAttachedSbbsNode ( false ) ; return node != null ? node . getChildrenNames ( ) . isEmpty ( ) : true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a set with all sbb entities attached . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Set < SbbEntityID > getSbbEntitiesAttached ( ) { final Node node = getAttachedSbbsNode ( false ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attaches a timer [CODESPLIT] public boolean attachTimer ( TimerID timerID ) { final Node node = getAttachedTimersNode ( true ) ; if ( ! node . hasChild ( timerID ) ) { node . addChild ( Fqn . fromElements ( timerID ) ) ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detaches a timer [CODESPLIT] public boolean detachTimer ( TimerID timerID ) { final Node node = getAttachedTimersNode ( false ) ; return node != null ? node . removeChild ( timerID ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if there at least one timer attached [CODESPLIT] public boolean noTimersAttached ( ) { final Node node = getAttachedTimersNode ( false ) ; return node != null ? node . getChildrenNames ( ) . isEmpty ( ) : true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the set of timers attached to the ac [CODESPLIT] public Set getAttachedTimers ( ) { final Node node = getAttachedTimersNode ( false ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified name to the set of names bound to the ac [CODESPLIT] public void nameBound ( String name ) { final Node node = getNamesBoundNode ( true ) ; if ( ! node . hasChild ( name ) ) { node . addChild ( Fqn . fromElements ( name ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified name from the set of names bound to the ac [CODESPLIT] public boolean nameUnbound ( String name ) { final Node node = getNamesBoundNode ( false ) ; return node != null ? node . removeChild ( name ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if there at least one name bound to the ac [CODESPLIT] public boolean noNamesBound ( ) { final Node node = getNamesBoundNode ( false ) ; return node != null ? node . getChildrenNames ( ) . isEmpty ( ) : true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the set of names bound to the ac [CODESPLIT] public Set getNamesBoundCopy ( ) { final Node node = getNamesBoundNode ( false ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the aci cmp attribute [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void setCmpAttribute ( String attrName , Object attrValue ) { final Node node = getCmpAttributesNode ( true ) ; Node cmpNode = node . getChild ( attrName ) ; if ( cmpNode == null ) { cmpNode = node . addChild ( Fqn . fromElements ( attrName ) ) ; } cmpNode . put ( CMP_ATTRIBUTES_NODE_MAP_KEY , attrValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the aci cmp attribute [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Object getCmpAttribute ( String attrName ) { final Node node = getCmpAttributesNode ( false ) ; if ( node == null ) { return null ; } else { final Node cmpNode = node . getChild ( attrName ) ; if ( cmpNode != null ) { return cmpNode . get ( CMP_ATTRIBUTES_NODE_MAP_KEY ) ; } else { return null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a map copy of the aci attributes set [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Map getCmpAttributesCopy ( ) { final Node node = getCmpAttributesNode ( false ) ; if ( node == null ) { return Collections . emptyMap ( ) ; } else { Map result = new HashMap ( ) ; Node cmpNode = null ; for ( Object obj : node . getChildren ( ) ) { cmpNode = ( Node ) obj ; result . put ( cmpNode . getFqn ( ) . getLastElement ( ) , cmpNode . get ( CMP_ATTRIBUTES_NODE_MAP_KEY ) ) ; } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FIXME : add check for access? [CODESPLIT] protected String appendToBuffer ( String message , String section , String buffer ) { buffer += ( this . component . getDescriptor ( ) . getResourceAdaptorID ( ) + \" : violates section \" + section + \" of jSLEE 1.1 specification : \" + message + \"\\n\" ) ; return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void processArguments ( String [ ] args ) throws CommandException { String sopts = \":a:f:sug\" ; LongOpt [ ] lopts = { new LongOpt ( \"tracers-used\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"tracers-set\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"set-level\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"cid\" , LongOpt . REQUIRED_ARGUMENT , null , SetLevelOperation . cid ) , new LongOpt ( \"nsrc\" , LongOpt . REQUIRED_ARGUMENT , null , SetLevelOperation . nsrc ) , new LongOpt ( \"name\" , LongOpt . REQUIRED_ARGUMENT , null , SetLevelOperation . name ) , new LongOpt ( \"level\" , LongOpt . REQUIRED_ARGUMENT , null , SetLevelOperation . level ) , new LongOpt ( \"un-set-level\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"nsrc\" , LongOpt . REQUIRED_ARGUMENT , null , UnsetLevelOperation . nsrc ) , new LongOpt ( \"name\" , LongOpt . REQUIRED_ARGUMENT , null , UnsetLevelOperation . name ) , new LongOpt ( \"get-level\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"cid\" , LongOpt . REQUIRED_ARGUMENT , null , GetLevelOperation . cid ) , new LongOpt ( \"nsrc\" , LongOpt . REQUIRED_ARGUMENT , null , GetLevelOperation . nsrc ) , new LongOpt ( \"name\" , LongOpt . REQUIRED_ARGUMENT , null , GetLevelOperation . name ) , } ; Getopt getopt = new Getopt ( null , args , sopts , lopts ) ; // getopt.setOpterr(false);\r int code ; while ( ( code = getopt . getopt ( ) ) != - 1 ) { switch ( code ) { case ' ' : throw new CommandException ( \"Option requires an argument: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : throw new CommandException ( \"Invalid (or ambiguous) option: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : super . operation = new GetTracersUsedOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new GetTracersSetOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new SetLevelOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new UnsetLevelOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new GetLevelOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\", found unexpected opt: \" + args [ getopt . getOptind ( ) - 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ActivityContextInterface getActivityContextInterface ( ProfileTableActivity profileTableActivity ) throws NullPointerException , TransactionRequiredLocalException , UnrecognizedActivityException , FactoryException { if ( profileTableActivity == null || profileTableActivity . getProfileTableName ( ) == null ) { throw new NullPointerException ( \"null profile table activity\" ) ; } serviceContainer . getTransactionManager ( ) . mandateTransaction ( ) ; ProfileTableImpl profileTableImpl = null ; try { // check if this is an assigned profile table // name. profileTableImpl = profileManagementImpl . getProfileTable ( profileTableActivity . getProfileTableName ( ) ) ; } catch ( UnrecognizedProfileTableNameException e ) { throw new UnrecognizedActivityException ( profileTableActivity . getProfileTableName ( ) , e ) ; } ActivityContext ac = profileTableImpl . getActivityContext ( ) ; if ( ac == null ) { throw new UnrecognizedActivityException ( \"No resource for: \" + profileTableActivity . getProfileTableName ( ) , profileTableActivity ) ; } return ac . getActivityContextInterface ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiates the notification info for usage mbeans [CODESPLIT] private static MBeanNotificationInfo [ ] initNotificationInfo ( ) { String [ ] notificationTypes = new String [ ] { ProfileTableNotification . USAGE_NOTIFICATION_TYPE , ResourceAdaptorEntityNotification . USAGE_NOTIFICATION_TYPE , SbbNotification . USAGE_NOTIFICATION_TYPE , SubsystemNotification . USAGE_NOTIFICATION_TYPE } ; return new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( notificationTypes , UsageNotification . class . getName ( ) , \"JAIN SLEE 1.1 Usage MBean Notification\" ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the notification . [CODESPLIT] public void sendUsageNotification ( long value , long seqno , String usageParameterSetName , String usageParameterName , boolean isCounter ) { UsageNotificationManagerMBeanImpl notificationManager = parent . getUsageNotificationManagerMBean ( notificationSource ) ; if ( notificationManager == null || notificationManager . getNotificationsEnabled ( usageParameterName ) ) { // if the notification manager is null we consider the notification // can be sent UsageNotification notification = createUsageNotification ( value , seqno , usageParameterSetName , usageParameterName , isCounter ) ; for ( ListenerFilterHandbackTriplet triplet : listeners . values ( ) ) { if ( triplet . notificationFilter == null || triplet . notificationFilter . isNotificationEnabled ( notification ) ) { triplet . notificationListener . handleNotification ( notification , triplet . handbackObject ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of an { @link UsageNotification } for the specified args . This operation is exposed to allow it be overriden by { @link SbbUsageMBean } impl . [CODESPLIT] protected UsageNotification createUsageNotification ( long value , long seqno , String usageParameterSetName , String usageParameterName , boolean isCounter ) { return new UsageNotification ( notificationSource . getUsageNotificationType ( ) , this , notificationSource , usageParameterSetName , usageParameterName , isCounter , value , seqno , System . currentTimeMillis ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JAIN SLEE specs descriptor [CODESPLIT] public javax . slee . resource . ResourceAdaptorTypeDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { final LibraryID [ ] libraryIDs = descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) ; final String [ ] activityTypes = descriptor . getActivityTypes ( ) . toArray ( new String [ descriptor . getActivityTypes ( ) . size ( ) ] ) ; final EventTypeID [ ] eventTypes = descriptor . getEventTypeRefs ( ) . toArray ( new EventTypeID [ descriptor . getEventTypeRefs ( ) . size ( ) ] ) ; String raInterface = descriptor . getResourceAdaptorInterface ( ) == null ? null : descriptor . getResourceAdaptorInterface ( ) ; specsDescriptor = new javax . slee . resource . ResourceAdaptorTypeDescriptor ( getResourceAdaptorTypeID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , libraryIDs , activityTypes , raInterface , eventTypes ) ; } return specsDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void processArguments ( String [ ] args ) throws CommandException { String sopts = \":lcrng\" ; LongOpt [ ] lopts = { new LongOpt ( \"list\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"table\" , LongOpt . OPTIONAL_ARGUMENT , null , ListOperation . table ) , new LongOpt ( \"profile\" , LongOpt . REQUIRED_ARGUMENT , null , ListOperation . profile ) , new LongOpt ( \"create\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //those are also for remove\r new LongOpt ( \"profile-name\" , LongOpt . REQUIRED_ARGUMENT , null , CreateOperation . profile_name ) , new LongOpt ( \"table-name\" , LongOpt . REQUIRED_ARGUMENT , null , CreateOperation . table_name ) , new LongOpt ( \"profile-spec\" , LongOpt . REQUIRED_ARGUMENT , null , CreateOperation . profile_spec ) , new LongOpt ( \"remove\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //covered above\r new LongOpt ( \"rename\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"current-name\" , LongOpt . REQUIRED_ARGUMENT , null , RenameOperation . current_name ) , new LongOpt ( \"new-name\" , LongOpt . REQUIRED_ARGUMENT , null , RenameOperation . new_name ) , new LongOpt ( \"get\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //new LongOpt(\"profile-name\", LongOpt.REQUIRED_ARGUMENT, null, GetOperation.profile_name),\r new LongOpt ( \"profile-spec\" , LongOpt . REQUIRED_ARGUMENT , null , GetOperation . profile_spec ) , //new LongOpt(\"profile\", LongOpt.REQUIRED_ARGUMENT, null, GetOperation.profile),\r } ; Getopt getopt = new Getopt ( null , args , sopts , lopts ) ; getopt . setOpterr ( false ) ; int code ; while ( ( code = getopt . getopt ( ) ) != - 1 ) { switch ( code ) { case ' ' : throw new CommandException ( \"Option requires an argument: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : throw new CommandException ( \"Invalid (or ambiguous) option: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : super . operation = new ListOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new CreateOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new RemoveOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new RenameOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new GetOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\", found unexpected opt: \" + args [ getopt . getOptind ( ) - 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void persistentInstall ( URL deployableUnitURL ) throws DeploymentException { try { doPersistentInstall ( deployableUnitURL , deployDir ) ; } catch ( Exception e ) { throw new DeploymentException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void persistentUninstall ( URL deployableUnitURL ) throws DeploymentException { try { // All we really care is for the filename\r String fullPath = deployableUnitURL . getFile ( ) ; String filename = fullPath . substring ( fullPath . lastIndexOf ( ' ' ) + 1 ) ; // Here's what we want to delete\r String filePath = deployDir + File . separator + filename ; // Delete it\r if ( ! new File ( filePath ) . delete ( ) ) { throw new DeploymentException ( \"Failed to delete \" + filePath ) ; } } catch ( Exception e ) { throw new DeploymentException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void clusterInstall ( URL deployableUnitURL ) throws DeploymentException { try { doPersistentInstall ( deployableUnitURL , farmDeployDir ) ; } catch ( Exception e ) { throw new DeploymentException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void clusterUninstall ( URL deployableUnitURL ) throws DeploymentException { try { // All we really care is for the filename\r String fullPath = deployableUnitURL . getFile ( ) ; String filename = fullPath . substring ( fullPath . lastIndexOf ( ' ' ) + 1 ) ; // Here's what we want to delete\r String filePath = farmDeployDir + File . separator + filename ; // Delete it\r if ( ! new File ( filePath ) . delete ( ) ) { throw new DeploymentException ( \"Failed to delete \" + filePath ) ; } } catch ( Exception e ) { throw new DeploymentException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downloads a remote DU to a local folder [CODESPLIT] private File downloadRemoteDU ( URL duURL , File deploymentRoot ) throws Exception { InputStream in = null ; OutputStream out = null ; try { // Get the filename out of the URL\r String filename = new File ( duURL . getPath ( ) ) . getName ( ) ; // Prepare for creating the file at deploy folder\r File tempFile = new File ( deploymentRoot , filename ) ; out = new BufferedOutputStream ( new FileOutputStream ( tempFile ) ) ; URLConnection conn = duURL . openConnection ( ) ; in = conn . getInputStream ( ) ; // Get the data\r byte [ ] buffer = new byte [ 1024 ] ; int numRead ; while ( ( numRead = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , numRead ) ; } // Done! Successful.\r return tempFile ; } finally { // Do the clean up.\r try { if ( in != null ) { in . close ( ) ; in = null ; } if ( out != null ) { out . close ( ) ; out = null ; } } catch ( IOException ioe ) { // Shouldn't happen, let's ignore.\r } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the list of components already deployed to SLEE . [CODESPLIT] public void updateDeployedComponents ( ) { try { // Get the SLEE Component Repo ComponentRepository componentRepository = sleeContainerDeployer . getSleeContainer ( ) . getComponentRepository ( ) ; // First we'll put the components in a temp Collection ConcurrentLinkedQueue < String > newDeployedComponents = new ConcurrentLinkedQueue < String > ( ) ; // Get the deployed Profile Specifications for ( ComponentID componentID : componentRepository . getProfileSpecificationIDs ( ) ) { newDeployedComponents . add ( componentID . toString ( ) ) ; } // Get the deployed Event Types for ( ComponentID componentID : componentRepository . getEventComponentIDs ( ) ) { newDeployedComponents . add ( componentID . toString ( ) ) ; } // Get the deployed Resource Adaptor Types for ( ComponentID componentID : componentRepository . getResourceAdaptorTypeIDs ( ) ) { newDeployedComponents . add ( componentID . toString ( ) ) ; } // Get the deployed Resource Adaptors for ( ComponentID componentID : componentRepository . getResourceAdaptorIDs ( ) ) { newDeployedComponents . add ( componentID . toString ( ) ) ; } // Get the deployed Service Building Blocks (SBBs) for ( ComponentID componentID : componentRepository . getSbbIDs ( ) ) { newDeployedComponents . add ( componentID . toString ( ) ) ; } // Get the deployed Services for ( ComponentID componentID : componentRepository . getServiceIDs ( ) ) { newDeployedComponents . add ( componentID . toString ( ) ) ; } // Get the deployed Libraries for ( ComponentID componentID : componentRepository . getLibraryIDs ( ) ) { newDeployedComponents . add ( componentID . toString ( ) ) ; } ResourceManagement resourceManagement = sleeContainerDeployer . getSleeContainer ( ) . getResourceManagement ( ) ; // Get the existing Resource Adaptor Entity links String [ ] entityNames = resourceManagement . getResourceAdaptorEntities ( ) ; for ( String entityName : entityNames ) { newDeployedComponents . addAll ( Arrays . asList ( resourceManagement . getLinkNames ( entityName ) ) ) ; } // All good.. Make the temp the good one. deployedComponents = newDeployedComponents ; } catch ( Exception e ) { logger . warn ( \"Failure while updating deployed components.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for installing a Deployable Unit into SLEE . [CODESPLIT] public void installDeployableUnit ( DeployableUnit du ) throws Exception { // Update the deployed components from SLEE updateDeployedComponents ( ) ; // Check if the DU is ready to be installed if ( du . isReadyToInstall ( true ) ) { // Get and Run the actions needed for installing this DU sciAction ( du . getInstallActions ( ) , du ) ; // Set the DU as installed du . setInstalled ( true ) ; // Add the DU to the installed list deployedDUs . add ( du ) ; // Update the deployed components from SLEE updateDeployedComponents ( ) ; // Go through the remaining DUs waiting for installation Iterator < DeployableUnit > duIt = waitingForInstallDUs . iterator ( ) ; while ( duIt . hasNext ( ) ) { DeployableUnit waitingDU = duIt . next ( ) ; // If it is ready for installation, follow the same procedure if ( waitingDU . isReadyToInstall ( false ) ) { // Get and Run the actions needed for installing this DU sciAction ( waitingDU . getInstallActions ( ) , waitingDU ) ; // Set the DU as installed waitingDU . setInstalled ( true ) ; // Add the DU to the installed list deployedDUs . add ( waitingDU ) ; // Update the deployed components from SLEE updateDeployedComponents ( ) ; // Remove the DU from the waiting list. waitingForInstallDUs . remove ( waitingDU ) ; // Let's start all over.. :) duIt = waitingForInstallDUs . iterator ( ) ; } } } else { logger . warn ( \"Unable to INSTALL \" + du . getDeploymentInfoShortName ( ) + \" right now. Waiting for dependencies to be resolved.\" ) ; // The DU can't be installed now, let's wait... waitingForInstallDUs . add ( du ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for uninstalling a Deployable Unit into SLEE . [CODESPLIT] public void uninstallDeployableUnit ( DeployableUnit du ) throws Exception { // Update the deployed components from SLEE updateDeployedComponents ( ) ; // It isn't installed? if ( ! du . isInstalled ( ) ) { // Then it should be in the waiting list... remove and we're done. if ( waitingForInstallDUs . remove ( du ) ) { logger . info ( du . getDeploymentInfoShortName ( ) + \" wasn't deployed. Removing from waiting list.\" ) ; } } // Check if DU components are still present  else if ( ! du . areComponentsStillPresent ( ) ) { logger . info ( du . getDeploymentInfoShortName ( ) + \" components already removed. Removing DU info.\" ) ; // Process internals of undeployment... processInternalUndeploy ( du ) ; } // Check if the DU is ready to be uninstalled else if ( du . isReadyToUninstall ( ) ) { // Get and Run the actions needed for uninstalling this DU sciAction ( du . getUninstallActions ( ) , du ) ; // Process internals of undeployment... processInternalUndeploy ( du ) ; } else { // Have we been her already? If so, don't flood user with log messages... if ( ! waitingForUninstallDUs . contains ( du ) ) { // Add it to the waiting list. waitingForUninstallDUs . add ( du ) ; logger . warn ( \"Unable to UNINSTALL \" + du . getDeploymentInfoShortName ( ) + \" right now. Waiting for dependents to be removed.\" ) ; } throw new DependencyException ( \"Unable to undeploy \" + du . getDeploymentInfoShortName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the DU as not installed and remove it from waiting list if present there . Also tries to undeploy DU s waiting for dependencies to be removed . [CODESPLIT] private void processInternalUndeploy ( DeployableUnit du ) throws Exception { // Set the DU as not installed du . setInstalled ( false ) ; // Remove if it was present in waiting list waitingForUninstallDUs . remove ( du ) ; // Update the deployed components from SLEE updateDeployedComponents ( ) ; // Go through the remaining DUs waiting for uninstallation Iterator < DeployableUnit > duIt = waitingForUninstallDUs . iterator ( ) ; while ( duIt . hasNext ( ) ) { DeployableUnit waitingDU = duIt . next ( ) ; // If it is ready for being uninstalled, follow the same procedure if ( waitingDU . isReadyToUninstall ( ) ) { // Schedule removal sleeContainerDeployer . getSleeSubDeployer ( ) . stop ( waitingDU . getURL ( ) , waitingDU . getDeploymentInfoShortName ( ) ) ; // Remove the DU from the waiting list. If it fails, will go back. waitingForUninstallDUs . remove ( waitingDU ) ; // Let's start all over.. :) duIt = waitingForUninstallDUs . iterator ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for performing the actions needed for ( un ) deployment . [CODESPLIT] private void sciAction ( Collection < ManagementAction > actions , DeployableUnit du ) throws Exception { // For each action, get the params.. for ( ManagementAction action : actions ) { // Shall we skip this action? if ( actionsToAvoidByDU . get ( du ) != null && actionsToAvoidByDU . get ( du ) . remove ( action ) ) { // Clean if it was the last one. if ( actionsToAvoidByDU . get ( du ) . size ( ) == 0 ) { actionsToAvoidByDU . remove ( du ) ; } continue ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Invoking \" + action ) ; } // We are isolating each action, so it won't affect the whole proccess try { // Invoke it. action . invoke ( ) ; // We need to wait for service/entity to deactivate... /*if(action instanceof DeactivateServiceAction) {\n          waitForServiceDeactivation((DeactivateServiceAction) action);\n        }\n        else if (action instanceof DeactivateResourceAdaptorEntityAction) {\n          waitForResourceAdaptorEntityDeactivation((DeactivateResourceAdaptorEntityAction) action);\n        }*/ } catch ( Exception e ) { // We might expect some exceptions... if ( e . getCause ( ) instanceof ResourceAdaptorEntityAlreadyExistsException || ( e . getCause ( ) instanceof InvalidStateException && action instanceof ActivateResourceAdaptorEntityAction ) ) { Class < ? extends ManagementAction > actionToAvoid = null ; // If the activate/create failed then we don't want to deactivate/remove if ( action instanceof ActivateResourceAdaptorEntityAction ) { actionToAvoid = DeactivateResourceAdaptorEntityAction . class ; } else if ( action instanceof CreateResourceAdaptorEntityAction ) { actionToAvoid = RemoveResourceAdaptorEntityAction . class ; } Collection < Class < ? extends ManagementAction > > actionsToAvoid ; if ( ( actionsToAvoid = actionsToAvoidByDU . get ( du ) ) == null ) { actionsToAvoid = new ArrayList < Class < ? extends ManagementAction > > ( ) ; // Add it to the list of actions to skip on undeploy actionsToAvoid . add ( actionToAvoid ) ; // And put it to the map actionsToAvoidByDU . put ( du , actionsToAvoid ) ; } else { // Add it to the list of actions to skip on undeploy actionsToAvoid . add ( actionToAvoid ) ; } logger . warn ( e . getCause ( ) . getMessage ( ) ) ; } else if ( e . getCause ( ) instanceof InvalidStateException && action instanceof DeactivateServiceAction ) { logger . info ( \"Delaying uninstall due to service deactivation not complete.\" ) ; } else if ( e . getCause ( ) instanceof InvalidStateException && action instanceof DeactivateResourceAdaptorEntityAction ) { // ignore this... someone has already deactivated the link. } else if ( e . getCause ( ) instanceof UnrecognizedLinkNameException && action instanceof UnbindLinkNameAction ) { // ignore this... someone has already removed the link. } else if ( action . getType ( ) == ManagementAction . Type . DEPLOY_MANAGEMENT ) { logger . error ( \"Failure invoking '\" + action , e ) ; } else { throw e ; } } // Wait a little while just to make sure it finishes Thread . sleep ( waitTimeBetweenOperations ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for showing current status of the Deployment Manager . [CODESPLIT] public String showStatus ( ) { // Update the currently deployed components. updateDeployedComponents ( ) ; String output = \"\" ; output += \"<p>Deployable Units Waiting For Install:</p>\" ; for ( DeployableUnit waitingDU : waitingForInstallDUs ) { output += \"+-- \" + waitingDU . getDeploymentInfoShortName ( ) + \"<br>\" ; for ( String dependency : waitingDU . getExternalDependencies ( ) ) { if ( ! deployedComponents . contains ( dependency ) ) dependency += \" <strong>MISSING!</strong>\" ; output += \"  +-- depends on \" + dependency + \"<br>\" ; } } output += \"<p>Deployable Units Waiting For Uninstall:</p>\" ; for ( DeployableUnit waitingDU : waitingForUninstallDUs ) { output += \"+-- \" + waitingDU . getDeploymentInfoShortName ( ) + \"<br>\" ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback for { [CODESPLIT] public void sleeShutdown ( ) { logger . info ( \"Undeploying all Deployable Units due to SLEE shutdown\" ) ; // undeploy each DU in reverse order  while ( ! deployedDUs . isEmpty ( ) ) { DeployableUnit du = deployedDUs . removeLast ( ) ; try { uninstallDeployableUnit ( du ) ; } catch ( Exception e ) { logger . error ( \"Failed to uninstall DU, in SLEE shutdown\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the message should be logged convert the JDK 1 . 4 LogRecord to a Log4J message . [CODESPLIT] public boolean isLoggable ( LogRecord record ) { Logger logger = getLogger ( record ) ; if ( record . getThrown ( ) != null ) { logWithThrowable ( logger , record ) ; } else { logWithoutThrowable ( logger , record ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the Log4J logger corresponding to the java . util . logger . LogRecord [CODESPLIT] private Logger getLogger ( LogRecord record ) { String loggerName = record . getLoggerName ( ) ; Logger logger = loggerCache . get ( loggerName ) ; if ( logger == null ) { logger = Logger . getLogger ( loggerName ) ; loggerCache . put ( loggerName , logger ) ; } return logger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the component ids for components that refers the specified component [CODESPLIT] public Set < SleeComponent > getReferringComponents ( SleeComponent component ) { Set < SleeComponent > result = new HashSet < SleeComponent > ( ) ; for ( EventTypeComponent otherComponent : eventTypeComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( LibraryComponent otherComponent : libraryComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ProfileSpecificationComponent otherComponent : profileSpecificationComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ResourceAdaptorComponent otherComponent : resourceAdaptorComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ResourceAdaptorTypeComponent otherComponent : resourceAdaptorTypeComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( SbbComponent otherComponent : sbbComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } for ( ServiceComponent otherComponent : serviceComponents . values ( ) ) { if ( ! otherComponent . getComponentID ( ) . equals ( component . getComponentID ( ) ) ) { if ( otherComponent . getDependenciesSet ( ) . contains ( component . getComponentID ( ) ) ) { result . add ( otherComponent ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void displayHelp ( ) { PrintWriter out = context . getWriter ( ) ; out . println ( desc ) ; // out.println(\"usage: \" + name +\r // \" <-tprofileTableName> [-pprofileName] <operation> <arg>*\");\r addHeaderDescription ( out ) ; out . println ( \"'SetID' refers to SetName or SbbID and SetName.\" ) ; out . println ( ) ; out . println ( \"operation:\" ) ; out . println ( \"    -l, --list                     Lists certain information about parameters sets. Requires one of options to be present:\" ) ; out . println ( \"           --sets                  Instructs command to list declared parameter sets. Does not require argument.\" ) ; out . println ( \"           --parameters            Instructs command to list parameters of parameter set. Does not require argument.\" ) ; //TODO: make 'list' also list notification mngr conf for resource set.\r out . println ( \"    -g, --get                      Fetches value of certain parameter in set. Does not take argument.\" ) ; out . println ( \"                                   Requires '--name' option to be present. Following options are supported: \" ) ; out . println ( \"           --name                  Specifies name of parameter in a set for get operation. Requires parameter name as argument. This option is mandatory.\" ) ; out . println ( \"           --rst                   If present, indicates that 'get' operation should reset parameter value. Does not require argument.\" ) ; out . println ( \"    -r, --reset                    Resets assets in 'Usage' realm. Does not take argument. If 'SetID' is specified, reset command resets specific set, otherwise it acts on default one.\" ) ; out . println ( \"                                   If it is not present, reset command performs operation on default set. Following option is supported:\" ) ; out . println ( \"           --all                   Resets ALL parameters for 'ResourceName', ignores 'SetID'.\" ) ; out . println ( \"    -c, --create                   Creates usage parameter set for given 'SetID'. Does not require argument.\" ) ; out . println ( \"    -d, --delete                   Deletes usage parameter set with given 'SetID'. Does not require argument.\" ) ; out . println ( \"    -n, --notify                   This operation either turn on/off notifications for parameter or queries about state of notifications.\" ) ; out . println ( \"                                   Does not take parameter, supports following options:\" ) ; out . println ( \"           --name                  Specifies name of parameter. Requires parameter name as argument. It is mandatory.\" ) ; out . println ( \"           --value                 Specifies value of parameter. Requires boolean argument.\" ) ; out . println ( \"           --is                    Request information about notification(if its enabled). Does not require argument.\" ) ; //out.println(\"    -i, --is-notify                Checks if notification is on for certain parameter in set. Following options are supported:\");\r //out.println(\"           --name                  Specifies name of parameter. Requires parameter name as argument. It is mandatory.\");\r out . println ( \"\" ) ; out . println ( \"Examples: \" ) ; addExamples ( out ) ; out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void processArguments ( String [ ] args ) throws CommandException { //String sopts = \"-:lgrcdni\";\r String sopts = \"-:lgrcdn\" ; LongOpt [ ] lopts = { new LongOpt ( \"noprefix\" , LongOpt . NO_ARGUMENT , null , 0x1000 ) , // operration part\r new LongOpt ( \"list\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"sets\" , LongOpt . NO_ARGUMENT , null , ListOperation . sets ) , new LongOpt ( \"parameters\" , LongOpt . NO_ARGUMENT , null , ListOperation . parameters ) , new LongOpt ( \"get\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"name\" , LongOpt . REQUIRED_ARGUMENT , null , GetOperation . name ) , new LongOpt ( \"rst\" , LongOpt . NO_ARGUMENT , null , GetOperation . rst ) , new LongOpt ( \"reset\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"all\" , LongOpt . NO_ARGUMENT , null , ResetOperation . all ) , new LongOpt ( \"create\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"delete\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //mgmt\r new LongOpt ( \"notify\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"value\" , LongOpt . REQUIRED_ARGUMENT , null , NotifyOperation . value ) , new LongOpt ( \"is-notify\" , LongOpt . NO_ARGUMENT , null , NotifyOperation . is ) , } ; Getopt getopt = new Getopt ( null , args , sopts , lopts ) ; getopt . setOpterr ( false ) ; int nonOptArgIndex = 0 ; int code ; while ( ( code = getopt . getopt ( ) ) != - 1 ) { switch ( code ) { case ' ' : throw new CommandException ( \"Option requires an argument: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : throw new CommandException ( \"Invalid (or ambiguous) option: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case 0x1000 : break ; case 1 : // non opt args, table and profile name(maybe)\r switch ( nonOptArgIndex ) { case 0 : resourceName = getopt . getOptarg ( ) ; if ( resourceName . startsWith ( PREFIX_SERVICEID ) ) { try { editor . setAsText ( resourceName ) ; } catch ( Exception e ) { throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\" failed to parse ServiceID.\" , e ) ; } this . serviceID = ( ServiceID ) editor . getValue ( ) ; this . resourceName = null ; } nonOptArgIndex ++ ; break ; case 1 : if ( this . serviceID != null ) { try { this . editor . setAsText ( getopt . getOptarg ( ) ) ; } catch ( Exception e ) { throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\" failed to parse SbbID.\" , e ) ; } this . sbbID = ( SbbID ) this . editor . getValue ( ) ; } else { usageSetName = getopt . getOptarg ( ) ; } nonOptArgIndex ++ ; break ; case 2 : if ( this . serviceID == null ) { throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\" expects at most two non opt arguments!\" ) ; } usageSetName = getopt . getOptarg ( ) ; nonOptArgIndex ++ ; break ; default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\" expects at most three non opt arguments!\" ) ; } break ; case ' ' : // list\r super . operation = new ListOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : // get\r super . operation = new GetOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : // reset\r super . operation = new ResetOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : // create\r super . operation = new CreateOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : // delete\r super . operation = new DeleteOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : // notify mngr\r super . operation = new NotifyOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; //\t\t\tcase 'i':\r //\t\t\t\t// check notify\r //\t\t\t\tsuper.operation = new IsNotifyOperation(super.context, super.log, this);\r //\t\t\t\tprepareCommand();\r //\t\t\t\tsuper.operation.buildOperation(getopt, args);\r //\t\t\t\tbreak;\t\r default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\", found unexpected opt: \" + args [ getopt . getOptind ( ) - 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > TimerPreserveMissed< / code > object from an integer value . [CODESPLIT] public static TimerPreserveMissed fromInt ( int option ) throws IllegalArgumentException { switch ( option ) { case PRESERVE_NONE : return NONE ; case PRESERVE_ALL : return ALL ; case PRESERVE_LAST : return LAST ; default : throw new IllegalArgumentException ( \"Invalid preserve-missed value: \" + option ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > TimerPreserveMissed< / code > object from a string value . [CODESPLIT] public static TimerPreserveMissed fromString ( String option ) throws NullPointerException , IllegalArgumentException { if ( option == null ) throw new NullPointerException ( \"option is null\" ) ; if ( option . equalsIgnoreCase ( NONE_STRING ) ) return NONE ; if ( option . equalsIgnoreCase ( ALL_STRING ) ) return ALL ; if ( option . equalsIgnoreCase ( LAST_STRING ) ) return LAST ; throw new IllegalArgumentException ( \"Invalid preserve-missed value: \" + option ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a set containing sbb entity ids in the factory cache data [CODESPLIT] public Set < SbbEntityID > getSbbEntities ( ) { final Node node = getNode ( ) ; if ( node == null ) { return Collections . emptySet ( ) ; } HashSet < SbbEntityID > result = new HashSet < SbbEntityID > ( ) ; ServiceID serviceID = null ; for ( Object obj : node . getChildrenNames ( ) ) { serviceID = ( ServiceID ) obj ; for ( SbbEntityID sbbEntityID : getRootSbbEntityIDs ( serviceID ) ) { result . add ( sbbEntityID ) ; collectSbbEntities ( sbbEntityID , result ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ActivityContextInterface [ ] getActivities ( ) throws TransactionRequiredLocalException , IllegalStateException , SLEEException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"getActivities() \" + this . sbbObject . getState ( ) ) ; } if ( SbbObjectState . READY != this . sbbObject . getState ( ) ) { throw new IllegalStateException ( \"Cannot call SbbContext.getActivities() in \" + this . sbbObject . getState ( ) ) ; } ActivityContextFactory acf = sleeContainer . getActivityContextFactory ( ) ; List < ActivityContextInterface > result = new ArrayList < ActivityContextInterface > ( ) ; ActivityContext ac = null ; for ( ActivityContextHandle ach : sbbObject . getSbbEntity ( ) . getActivityContexts ( ) ) { ac = acf . getActivityContext ( ach ) ; if ( ac != null ) { result . add ( ac . getActivityContextInterface ( ) ) ; } } return result . toArray ( EMPTY_ACI_ARRAY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean getRollbackOnly ( ) throws TransactionRequiredLocalException , SLEEException { SleeTransactionManager txMgr = sleeContainer . getTransactionManager ( ) ; txMgr . mandateTransaction ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"in getRollbackOnly on \" + this ) ; } try { return txMgr . getRollbackOnly ( ) ; } catch ( SystemException e ) { throw new SLEEException ( \"Problem with the tx manager!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SbbLocalObject getSbbLocalObject ( ) throws TransactionRequiredLocalException , IllegalStateException , SLEEException { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; if ( this . sbbObject . getState ( ) != SbbObjectState . READY ) throw new IllegalStateException ( \"Bad state : \" + this . sbbObject . getState ( ) ) ; return sbbObject . getSbbEntity ( ) . getSbbLocalObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void maskEvent ( String [ ] eventNames , ActivityContextInterface aci ) throws NullPointerException , TransactionRequiredLocalException , IllegalStateException , UnrecognizedEventException , NotAttachedException , SLEEException { if ( SbbObjectState . READY != this . sbbObject . getState ( ) ) { throw new IllegalStateException ( \"Cannot call SbbContext maskEvent in \" + this . sbbObject . getState ( ) ) ; } if ( this . sbbObject . getSbbEntity ( ) == null ) { // this shouldnt happen since SbbObject state ready shoudl be set // when its fully setup, but.... throw new IllegalStateException ( \"Wrong state! SbbEntity is not assigned\" ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; ActivityContextHandle ach = ( ( org . mobicents . slee . container . activity . ActivityContextInterface ) aci ) . getActivityContext ( ) . getActivityContextHandle ( ) ; if ( ! sbbObject . getSbbEntity ( ) . isAttached ( ach ) ) throw new NotAttachedException ( \"ACI is not attached to SBB \" ) ; sbbObject . getSbbEntity ( ) . setEventMask ( ach , eventNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setRollbackOnly ( ) throws TransactionRequiredLocalException , SLEEException { final SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; sleeTransactionManager . mandateTransaction ( ) ; try { sleeTransactionManager . setRollbackOnly ( ) ; } catch ( SystemException e ) { throw new SLEEException ( \"failed to mark tx for rollback\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getActivityContextInterfaceFactory ( ResourceAdaptorTypeID raTypeID ) throws NullPointerException , IllegalArgumentException { if ( raTypeID == null ) { throw new NullPointerException ( \"null ra type id\" ) ; } if ( ! sbbObject . getSbbComponent ( ) . getDependenciesSet ( ) . contains ( raTypeID ) ) { throw new IllegalArgumentException ( \"ra type \" + raTypeID + \" not referred by the sbb.\" ) ; } return sleeContainer . getComponentRepository ( ) . getComponentByID ( raTypeID ) . getActivityContextInterfaceFactory ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getResourceAdaptorInterface ( ResourceAdaptorTypeID raTypeID , String raLink ) throws NullPointerException , IllegalArgumentException { if ( raTypeID == null ) { throw new NullPointerException ( \"null ra type id\" ) ; } if ( raLink == null ) { throw new NullPointerException ( \"null ra link\" ) ; } if ( ! sbbObject . getSbbComponent ( ) . getDependenciesSet ( ) . contains ( raTypeID ) ) { throw new IllegalArgumentException ( \"ra type \" + raTypeID + \" not referred by the sbb.\" ) ; } final ResourceManagement resourceManagement = sleeContainer . getResourceManagement ( ) ; String raEntityName = null ; try { raEntityName = resourceManagement . getResourceAdaptorEntityName ( raLink ) ; } catch ( UnrecognizedLinkNameException e ) { throw new IllegalArgumentException ( \"ra link \" + raLink + \" not found.\" ) ; } return resourceManagement . getResourceAdaptorEntity ( raEntityName ) . getResourceAdaptorInterface ( raTypeID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "special handling of serialization [CODESPLIT] private void writeObject ( ObjectOutputStream out ) throws IOException { VendorExtensionUtils . writeObject ( out , vendorDataSerializationEnabled ? vendorData : null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "special handling of deserialization [CODESPLIT] private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { vendorData = VendorExtensionUtils . readObject ( in , vendorDataDeserializationEnabled ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public List < EventTypeDescriptorImpl > parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; List < EventTypeDescriptorImpl > result = new ArrayList < EventTypeDescriptorImpl > ( ) ; boolean isSlee11 = false ; MEventJar mEventJar = null ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee . event . EventJar ) { mEventJar = new MEventJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee . event . EventJar ) jaxbPojo ) ; } else if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . event . EventJar ) { mEventJar = new MEventJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . event . EventJar ) jaxbPojo ) ; isSlee11 = true ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } List < LibraryID > libraryRefs = mEventJar . getLibraryRef ( ) ; for ( MEventDefinition mEventDefinition : mEventJar . getEventDefinition ( ) ) { result . add ( new EventTypeDescriptorImpl ( mEventDefinition , libraryRefs , isSlee11 ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generic for all calls [CODESPLIT] private Permissions getPermissions ( Permissions permissions , final CodeSource cs , Principal [ ] principals ) { List < PolicyHolderEntry > entries = this . currentPolicy . get ( ) . policyHolderEntries ; for ( PolicyHolderEntry phe : entries ) { // general selectPermissions ( permissions , cs , principals , phe ) ; // FIXME: certs? } return permissions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "newGlobalPolicyHolder ) { [CODESPLIT] private boolean loadPolicy ( String policyURLString , GlobalPolicyHolder newGlobalPolicyHolder ) { // System.err.println(\"Load policy: \" + policyURLString); try { URI policyURI = null ; if ( policyURLString . startsWith ( _PROTOCOL_FILE ) ) { File policyFile = new File ( policyURLString . replaceFirst ( _PROTOCOL_FILE_PREFIX , \"\" ) ) ; if ( ! policyFile . exists ( ) || ! policyFile . isFile ( ) || ! policyFile . canRead ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Could not load file: \" + policyURLString + \", exists[\" + policyFile . exists ( ) + \"] isFile[\" + policyFile . isFile ( ) + \"] canRead[\" + policyFile . canRead ( ) + \"] \" ) ; } // Hmm... return false ; } else { policyURI = policyFile . toURI ( ) . normalize ( ) ; } } else { policyURI = new URI ( policyURLString ) ; } PolicyParser pp = new PolicyParser ( true ) ; InputStream is = getStream ( policyURI ) ; InputStreamReader reader = new InputStreamReader ( is ) ; pp . read ( reader ) ; reader . close ( ) ; // KeyStore ks = ..... FIXME: KeyStore ks = null ; Enumeration < PolicyParser . GrantEntry > grantEntries = pp . grantElements ( ) ; while ( grantEntries . hasMoreElements ( ) ) { parseGrantEntry ( grantEntries . nextElement ( ) , ks , newGlobalPolicyHolder ) ; } } catch ( Exception e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Failed to read policy file due to some error.\" ) ; e . printStackTrace ( ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private InputStream getStream ( URL url ) throws IOException { [CODESPLIT] private InputStream getStream ( URI uri ) throws IOException { try { if ( uri . toURL ( ) . getProtocol ( ) . equals ( _PROTOCOL_FILE ) ) { String path = uri . toURL ( ) . getFile ( ) . replace ( ' ' , File . separatorChar ) ; return new FileInputStream ( path ) ; } else { return uri . toURL ( ) . openStream ( ) ; } } catch ( java . lang . IllegalArgumentException e ) { // this happens if url is relative, meaning a file? return new FileInputStream ( new File ( uri ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function MUST convert code source passed . Meaning it must normalize URL . For instance security framework may pass url that conceptualy matches pat specified policy files but comparison wont match . See url belowe . <ul > <li > <b > 1 - < / b > jar : file : / D : / java / servers / jboss - 5 . 0 . 0 . GA / server / default / deploy / restcomm . sar / lib / jar . jar! / < / li > <li > <b > 2 - < / b > file : / D : / java / servers / jboss - 5 . 0 . 0 . GA / server / default / deploy / - < / li > < / ul > URL 1 is passed from security framework as source of loaded classes . However it is not matched by second one ( and is should ) [CODESPLIT] CodeSource performUrlConversion ( CodeSource cs , boolean extractSignerCerts ) { String path = null ; CodeSource parsedCodeSource = null ; URL locationURL = cs . getLocation ( ) ; if ( locationURL != null ) { // can happen for default. Permission urlAccessPermission = null ; try { urlAccessPermission = locationURL . openConnection ( ) . getPermission ( ) ; } catch ( IOException e ) { } if ( urlAccessPermission != null && urlAccessPermission instanceof FilePermission ) { path = ( ( FilePermission ) urlAccessPermission ) . getName ( ) ; } else if ( ( urlAccessPermission == null ) && ( locationURL . getProtocol ( ) . equals ( \"file\" ) ) ) { path = locationURL . getFile ( ) . replace ( \"/\" , File . separator ) ; // FIXME: do more? } else { // FIXME: ?? } } if ( path == null ) { if ( extractSignerCerts ) { parsedCodeSource = new CodeSource ( cs . getLocation ( ) , getSignerCertificates ( cs ) ) ; } } else { try { // Sun says it fails if ( path . endsWith ( \"*\" ) ) { // remove trailing '*' because it causes // canonicaization // to fail on win32 path = path . substring ( 0 , path . length ( ) - 1 ) ; boolean removeTrailingFileSep = false ; if ( path . endsWith ( File . separator ) ) removeTrailingFileSep = true ; if ( path . equals ( \"\" ) ) { path = System . getProperty ( \"user.dir\" ) ; } File f = new File ( path ) ; path = f . getCanonicalPath ( ) ; StringBuffer sb = new StringBuffer ( path ) ; // reappend '*' to canonicalized filename (note that // canonicalization may have removed trailing file // separator, so we have to check for that, too) if ( ! path . endsWith ( File . separator ) && removeTrailingFileSep ) sb . append ( File . separator ) ; sb . append ( ' ' ) ; path = sb . toString ( ) ; } else if ( path . endsWith ( File . separator ) ) { // this is xxxx/x.jar!/ case..... path = path . substring ( 0 , path . length ( ) - 1 ) ; if ( path . endsWith ( \"!\" ) ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } } else { path = new File ( path ) . getCanonicalPath ( ) ; } // FIXME: possible convert URL? what is check this in // rfc locationURL = fileToEncodedURL ( new File ( path ) ) ; //locationURL = new URL(\"file\", \"\", path); if ( extractSignerCerts ) { parsedCodeSource = new CodeSource ( locationURL , getSignerCertificates ( cs ) ) ; } else { parsedCodeSource = new CodeSource ( locationURL , cs . getCertificates ( ) ) ; } } catch ( IOException ioe ) { // leave codesource as it is, unless we have to extract // its // signer certificates if ( extractSignerCerts ) { parsedCodeSource = new CodeSource ( cs . getLocation ( ) , getSignerCertificates ( cs ) ) ; } } } return parsedCodeSource ; // CodeSource o = AccessController.doPrivileged(new // PerformURLConversionAction(extractSignerCerts,cs)); // return o; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some methods to expose info about what is goign on . [CODESPLIT] public String getCodeSources ( ) { List < String > css = new ArrayList < String > ( ) ; for ( PolicyHolderEntry phe : this . currentPolicy . get ( ) . policyHolderEntries ) { css . add ( phe . getCodeSource ( ) . getLocation ( ) == null ? \"default\" : phe . getCodeSource ( ) . getLocation ( ) . toString ( ) ) ; } return Arrays . toString ( css . toArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void dataRemoved ( FqnWrapper fqnWrapper ) { final Fqn fqn = fqnWrapper . getFqn ( ) ; ra . dataRemoved ( ( K ) fqn . getLastElement ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance of this object and set the SbbContext This places it into the object pool . [CODESPLIT] public Object makeObject ( ) { SbbObject retval ; if ( doTraceLogs ) { logger . trace ( \"makeObject() for \" + serviceID + \" and \" + sbbComponent ) ; } final ClassLoader oldClassLoader = SleeContainerUtils . getCurrentThreadClassLoader ( ) ; try { final ClassLoader cl = sbbComponent . getClassLoader ( ) ; if ( System . getSecurityManager ( ) != null ) AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; return null ; } } ) ; else Thread . currentThread ( ) . setContextClassLoader ( cl ) ; retval = new SbbObjectImpl ( serviceID , sbbComponent ) ; } finally { if ( System . getSecurityManager ( ) != null ) AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; return null ; } } ) ; else Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } retval . setState ( SbbObjectState . POOLED ) ; return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileLocalObject create ( String profileName ) throws NullPointerException , IllegalArgumentException , TransactionRequiredLocalException , ReadOnlyProfileException , ProfileAlreadyExistsException , CreateException , SLEEException { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; checkProfileSpecIsNotReadOnly ( ) ; ProfileObjectImpl profileObject = createProfile ( profileName ) ; profileObject . profilePersist ( ) ; return profileObject . getProfileLocalObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileLocalObject find ( String profileName ) throws NullPointerException , TransactionRequiredLocalException , SLEEException { if ( profileName == null ) { throw new NullPointerException ( ) ; } ProfileObjectImpl profileObject = getProfile ( profileName ) ; return profileObject == null ? null : profileObject . getProfileLocalObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < ProfileLocalObject > findAll ( ) throws TransactionRequiredLocalException , SLEEException { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; Collection < ProfileLocalObject > result = new ArrayList < ProfileLocalObject > ( ) ; for ( ProfileEntity profileEntity : component . getProfileEntityFramework ( ) . findAll ( this . getProfileTableName ( ) ) ) { result . add ( transactionView . getProfile ( profileEntity ) . getProfileLocalObject ( ) ) ; } return Collections . unmodifiableCollection ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean remove ( String profileName ) throws NullPointerException , ReadOnlyProfileException , TransactionRequiredLocalException , SLEEException { if ( profileName == null ) { throw new NullPointerException ( \"Profile name must not be null\" ) ; } checkProfileSpecIsNotReadOnly ( ) ; return this . removeProfile ( profileName , true , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileLocalObject findProfileByAttribute ( String attributeName , Object attributeValue ) throws NullPointerException , IllegalArgumentException , TransactionRequiredLocalException , SLEEException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"findProfileByAttribute( attributeName = \" + attributeName + \" , attributeValue = \" + attributeValue + \" )\" ) ; } Collection < ProfileLocalObject > plocs = findProfilesByAttribute ( attributeName , attributeValue ) ; if ( plocs . size ( ) == 0 ) { return null ; } else { return plocs . iterator ( ) . next ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < ProfileLocalObject > findProfilesByAttribute ( String attributeName , Object attributeValue ) throws NullPointerException , IllegalArgumentException , TransactionRequiredLocalException , SLEEException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"findProfilesByAttribute( attributeName = \" + attributeName + \" , attributeValue = \" + attributeValue + \" )\" ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; // We get profile entities Collection < ProfileEntity > profileEntities = null ; try { profileEntities = getProfileEntitiesByAttribute ( attributeName , attributeValue , true ) ; } catch ( AttributeNotIndexedException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } catch ( UnrecognizedAttributeException e ) { throw new IllegalArgumentException ( e ) ; } catch ( AttributeTypeMismatchException e ) { throw new IllegalArgumentException ( e ) ; } // We need ProfileLocalObjects ArrayList < ProfileLocalObject > plocs = new ArrayList < ProfileLocalObject > ( ) ; for ( ProfileEntity profileEntity : profileEntities ) { plocs . add ( transactionView . getProfile ( profileEntity ) . getProfileLocalObject ( ) ) ; } return Collections . unmodifiableCollection ( plocs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] public Collection < ProfileID > getProfilesByAttribute ( String attributeName , Object attributeValue , boolean isSlee11 ) throws UnrecognizedAttributeException , AttributeNotIndexedException , AttributeTypeMismatchException , SLEEException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfilesByAttribute( attributeName = \" + attributeName + \" , attributeValue = \" + attributeValue + \" , isSlee11 = \" + isSlee11 + \" )\" ) ; } // We get profile entities Collection < ProfileEntity > profileEntities = getProfileEntitiesByAttribute ( attributeName , attributeValue , isSlee11 ) ; // We need ProfileIDs Collection < ProfileID > profileIDs = new ArrayList < ProfileID > ( ) ; for ( ProfileEntity profileEntity : profileEntities ) { profileIDs . add ( new ProfileID ( profileEntity . getTableName ( ) , profileEntity . getProfileName ( ) ) ) ; } return Collections . unmodifiableCollection ( profileIDs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { [CODESPLIT] private Collection < ProfileEntity > getProfileEntitiesByAttribute ( String attributeName , Object attributeValue , boolean isSlee11 ) throws UnrecognizedAttributeException , AttributeNotIndexedException , AttributeTypeMismatchException , SLEEException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfileEntitiesByAttribute( attributeName = \" + attributeName + \" , attributeValue = \" + attributeValue + \" , isSlee11 = \" + isSlee11 + \" )\" ) ; } ProfileAttribute profileAttribute = getProfileAttribute ( attributeName , attributeValue ) ; if ( isSlee11 ) { // validate attr value type if ( ! ProfileTableImpl . PROFILE_ATTR_ALLOWED_TYPES . contains ( attributeValue . getClass ( ) . getName ( ) ) ) { throw new AttributeTypeMismatchException ( attributeValue . getClass ( ) + \" is not a valid profile attribute value type\" ) ; } } else { if ( ! profileAttribute . isIndex ( ) ) { throw new AttributeNotIndexedException ( component . toString ( ) + \" defines an attribute named \" + attributeName + \" but not indexed\" ) ; } } return component . getProfileEntityFramework ( ) . findProfilesByAttribute ( this . getProfileTableName ( ) , profileAttribute , attributeValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { [CODESPLIT] private ProfileAttribute getProfileAttribute ( String attributeName , Object attributeValue ) throws NullPointerException , UnrecognizedAttributeException , AttributeTypeMismatchException { if ( attributeName == null ) { throw new NullPointerException ( \"attribute name is null\" ) ; } if ( attributeValue == null ) { throw new NullPointerException ( \"attribute value is null\" ) ; } ProfileAttribute profileAttribute = component . getProfileAttributes ( ) . get ( attributeName ) ; if ( profileAttribute == null ) { throw new UnrecognizedAttributeException ( component . toString ( ) + \" does not defines an attribute named \" + attributeName ) ; } else { Class < ? > allowedProfileAttributeType = profileAttribute . getNonPrimitiveType ( ) . isArray ( ) ? profileAttribute . getNonPrimitiveType ( ) . getComponentType ( ) : profileAttribute . getNonPrimitiveType ( ) ; if ( ! allowedProfileAttributeType . getName ( ) . equals ( attributeValue . getClass ( ) . getName ( ) ) ) { throw new AttributeTypeMismatchException ( component . toString ( ) + \" defines an attribute named \" + attributeName + \" with value type \" + profileAttribute . getType ( ) + \", the specified value is of type \" + attributeValue . getClass ( ) ) ; } else { return profileAttribute ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if profile is in back end storage == visible to other compoenents than MBean if null is passed as argumetn it must check for any other than defualt? [CODESPLIT] public boolean profileExists ( String profileName ) { boolean result = component . getProfileEntityFramework ( ) . findProfile ( this . getProfileTableName ( ) , profileName ) != null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Profile named \" + profileName + ( result ? \"\" : \" does not\" ) + \" exists on table named \" + this . getProfileTableName ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method renames Profile Table in backend storage . NOTE : It should not be called directly use SleeProfileTableManager instead! [CODESPLIT] public void rename ( String newProfileTableName ) { //we have to do this like that cause once JPA is done, those profiles wont exist, since we do UPDATE of a table name, not a copy //thus no profiles will be returned on this call later on. ouch :) Collection < ProfileID > profileIDs = this . getProfiles ( ) ; component . getProfileEntityFramework ( ) . renameProfileTable ( this . profileTableName , newProfileTableName ) ; //here we remove beans. for ( ProfileID pid : profileIDs ) { try { AbstractProfileMBeanImpl . close ( pid . getProfileTableName ( ) , pid . getProfileName ( ) ) ; } catch ( Exception e ) { if ( logger . isEnabledFor ( Level . WARN ) ) { logger . warn ( \"Unexpected behaviour on MBean deregistration.\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers remove operation on this profile table . [CODESPLIT] public void remove ( boolean isUninstall ) throws SLEEException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"removeProfileTable: removing profileTable=\" + profileTableName ) ; } // remove the table profiles, at this stage they may use notification source, lets leave it. for ( ProfileID profileID : getProfiles ( ) ) { // don't invoke the profile concrete object, to avoid evil profile lifecycle impls  // that rollbacks tx, as Test1110251Test this . removeProfile ( profileID . getProfileName ( ) , false , isUninstall ) ; } // remove default profile if ( getDefaultProfileEntity ( ) != null ) { this . removeProfile ( null , false , false ) ; } // add action after commit to remove tracer and close uncommitted mbeans TransactionalAction commitAction = new TransactionalAction ( ) { public void execute ( ) { // remove notification sources for profile table final TraceManagement traceMBeanImpl = sleeContainer . getTraceManagement ( ) ; traceMBeanImpl . deregisterNotificationSource ( new ProfileTableNotification ( profileTableName ) ) ; // close uncommitted mbeans closeUncommittedProfileMBeans ( ) ; } } ; sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) . getAfterCommitActions ( ) . add ( commitAction ) ; if ( sleeContainer . getSleeState ( ) == SleeState . RUNNING ) { endActivity ( ) ; } // unregister mbean unregisterUsageMBean ( ) ; // remove object pool profileManagement . getObjectPoolManagement ( ) . removeObjectPool ( this , sleeContainer . getTransactionManager ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JAIN SLEE specs descriptor [CODESPLIT] public javax . slee . management . SbbDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { final LibraryID [ ] libraryIDs = descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) ; Set < SbbID > sbbIDSet = new HashSet < SbbID > ( ) ; for ( SbbRefDescriptor mSbbRef : descriptor . getSbbRefs ( ) ) { sbbIDSet . add ( mSbbRef . getComponentID ( ) ) ; } SbbID [ ] sbbIDs = sbbIDSet . toArray ( new SbbID [ sbbIDSet . size ( ) ] ) ; Set < ProfileSpecificationID > profileSpecSet = new HashSet < ProfileSpecificationID > ( ) ; for ( ProfileSpecRefDescriptor mProfileSpecRef : descriptor . getProfileSpecRefs ( ) ) { profileSpecSet . add ( mProfileSpecRef . getComponentID ( ) ) ; } ProfileSpecificationID [ ] profileSpecs = profileSpecSet . toArray ( new ProfileSpecificationID [ profileSpecSet . size ( ) ] ) ; Set < EventTypeID > eventTypeSet = new HashSet < EventTypeID > ( ) ; for ( EventEntryDescriptor mEventEntry : descriptor . getEventEntries ( ) . values ( ) ) { eventTypeSet . add ( mEventEntry . getEventReference ( ) ) ; } EventTypeID [ ] eventTypes = eventTypeSet . toArray ( new EventTypeID [ eventTypeSet . size ( ) ] ) ; Set < ResourceAdaptorTypeID > raTypeIDSet = new HashSet < ResourceAdaptorTypeID > ( ) ; Set < String > raLinksSet = new HashSet < String > ( ) ; for ( ResourceAdaptorTypeBindingDescriptor mResourceAdaptorTypeBinding : descriptor . getResourceAdaptorTypeBindings ( ) ) { raTypeIDSet . add ( mResourceAdaptorTypeBinding . getResourceAdaptorTypeRef ( ) ) ; for ( ResourceAdaptorEntityBindingDescriptor mResourceAdaptorEntityBinding : mResourceAdaptorTypeBinding . getResourceAdaptorEntityBinding ( ) ) { raLinksSet . add ( mResourceAdaptorEntityBinding . getResourceAdaptorEntityLink ( ) ) ; } } ResourceAdaptorTypeID [ ] raTypeIDs = raTypeIDSet . toArray ( new ResourceAdaptorTypeID [ raTypeIDSet . size ( ) ] ) ; String [ ] raLinks = raLinksSet . toArray ( new String [ raLinksSet . size ( ) ] ) ; specsDescriptor = new javax . slee . management . SbbDescriptor ( getSbbID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , libraryIDs , sbbIDs , eventTypes , profileSpecs , descriptor . getAddressProfileSpecRef ( ) , raTypeIDs , raLinks ) ; } return specsDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getActivity ( ) throws TransactionRequiredLocalException , SLEEException { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; return activityContext . getActivityContextHandle ( ) . getActivityObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void attach ( SbbLocalObject sbbLocalObject ) throws NullPointerException , TransactionRequiredLocalException , TransactionRolledbackLocalException , SLEEException { if ( doTraceLogs ) { logger . trace ( \"attach( ac = \" + activityContext + \" , sbbLocalObject = \" + sbbLocalObject + \" )\" ) ; } if ( sbbLocalObject == null ) throw new NullPointerException ( \"null SbbLocalObject !\" ) ; sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; org . mobicents . slee . container . sbb . SbbLocalObject sbbLocalObjectImpl = ( org . mobicents . slee . container . sbb . SbbLocalObject ) sbbLocalObject ; SbbEntity sbbEntity = sbbLocalObjectImpl . getSbbEntity ( ) ; boolean attached = getActivityContext ( ) . attachSbbEntity ( sbbEntity . getSbbEntityId ( ) ) ; boolean setRollbackAndThrowException = false ; if ( attached ) { try { if ( sbbEntity . isRemoved ( ) ) { setRollbackAndThrowException = true ; } else { // attach entity from ac sbbEntity . afterACAttach ( getActivityContext ( ) . getActivityContextHandle ( ) ) ; } } catch ( Exception e ) { setRollbackAndThrowException = true ; } } if ( setRollbackAndThrowException ) { try { sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; } catch ( SystemException e ) { logger . warn ( \"failed to set rollback flag while asserting valid sbb entity\" , e ) ; } throw new TransactionRolledbackLocalException ( \"Failed to attach invalid sbb entity. SbbID \" + sbbEntity . getSbbEntityId ( ) ) ; } if ( attached ) { //            \tJSLEE 1.0 Spec, Section 8.5.8 excerpt: //        \t\tThe SLEE delivers the event to an SBB entity that stays attached once. The SLEE may deliver the //        \t\tevent to the same SBB entity more than once if it has been detached and then re -attached.  final EventRoutingTask routingTask = activityContext . getLocalActivityContext ( ) . getCurrentEventRoutingTask ( ) ; EventContext eventContextImpl = routingTask != null ? routingTask . getEventContext ( ) : null ; if ( eventContextImpl != null && eventContextImpl . getSbbEntitiesThatHandledEvent ( ) . remove ( sbbEntity . getSbbEntityId ( ) ) ) { if ( doTraceLogs ) { logger . trace ( \"Removed the SBB Entity [\" + sbbEntity . getSbbEntityId ( ) + \"] from the delivered set of activity context [\" + getActivityContext ( ) . getActivityContextHandle ( ) + \"]. Seems to be a reattachment after detachment in the same event delivery transaction. See JSLEE 1.0 Spec, Section 8.5.8.\" ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void detach ( SbbLocalObject sbbLocalObject ) throws NullPointerException , TransactionRequiredLocalException , TransactionRolledbackLocalException , SLEEException { if ( doTraceLogs ) { logger . trace ( \"detach( ac = \" + activityContext + \" , sbbLocalObject = \" + sbbLocalObject + \" )\" ) ; } if ( sbbLocalObject == null ) throw new NullPointerException ( \"null SbbLocalObject !\" ) ; sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; org . mobicents . slee . container . sbb . SbbLocalObject sbbLocalObjectImpl = ( org . mobicents . slee . container . sbb . SbbLocalObject ) sbbLocalObject ; SbbEntity sbbEntity = sbbLocalObjectImpl . getSbbEntity ( ) ; // detach ac from entity final ActivityContext ac = getActivityContext ( ) ; ac . detachSbbEntity ( sbbEntity . getSbbEntityId ( ) ) ; boolean setRollbackAndThrowException = false ; try { if ( sbbEntity . isRemoved ( ) ) { setRollbackAndThrowException = true ; } else { // detach entity from ac sbbEntity . afterACDetach ( getActivityContext ( ) . getActivityContextHandle ( ) ) ; } } catch ( Exception e ) { setRollbackAndThrowException = true ; } if ( setRollbackAndThrowException ) { try { sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; } catch ( SystemException e ) { logger . warn ( \"failed to set rollback flag while asserting valid sbb entity\" , e ) ; } throw new TransactionRolledbackLocalException ( \"Failed to detach invalid sbb entity. SbbID \" + sbbEntity . getSbbEntityId ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean isAttached ( SbbLocalObject sbbLocalObject ) throws NullPointerException , TransactionRequiredLocalException , TransactionRolledbackLocalException , SLEEException { if ( sbbLocalObject == null ) { throw new NullPointerException ( \"null sbbLocalObject\" ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; if ( sbbLocalObject instanceof org . mobicents . slee . container . sbb . SbbLocalObject ) { org . mobicents . slee . container . sbb . SbbLocalObject sbbLocalObjectImpl = ( org . mobicents . slee . container . sbb . SbbLocalObject ) sbbLocalObject ; SbbEntity sbbEntity = sbbLocalObjectImpl . getSbbEntity ( ) ; if ( sbbEntity != null && ! sbbEntity . isRemoved ( ) ) { return sbbEntity . isAttached ( activityContext . getActivityContextHandle ( ) ) ; } } try { sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; } catch ( Exception e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } throw new TransactionRolledbackLocalException ( \"the sbbLocalObject argument must represent a valid SBB entity\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void addDeployableUnit ( final DeployableUnit deployableUnit ) { if ( deployableUnit == null ) throw new NullPointerException ( \"null deployableUnit\" ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Adding DU :  \" + deployableUnit . getDeployableUnitID ( ) ) ; } deployableUnits . put ( deployableUnit . getDeployableUnitID ( ) , ( DeployableUnitImpl ) deployableUnit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public DeployableUnitID [ ] getDeployableUnits ( ) { Set < DeployableUnitID > deployableUnitIDs = deployableUnits . keySet ( ) ; return deployableUnitIDs . toArray ( new DeployableUnitID [ deployableUnitIDs . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void removeDeployableUnit ( DeployableUnitID deployableUnitID ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Removing DU with id:  \" + deployableUnitID ) ; } if ( deployableUnitID == null ) throw new NullPointerException ( \"null id\" ) ; deployableUnits . remove ( deployableUnitID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the ra entity config properties [CODESPLIT] public void updateConfigurationProperties ( ConfigProperties properties ) throws InvalidConfigurationException , InvalidStateException { if ( ! component . getDescriptor ( ) . getSupportsActiveReconfiguration ( ) && ( sleeContainer . getSleeState ( ) != SleeState . STOPPED ) && ( state == ResourceAdaptorEntityState . ACTIVE || state == ResourceAdaptorEntityState . STOPPING ) ) { throw new InvalidStateException ( \"the value of the supports-active-reconfiguration attribute of the resource-adaptor-class element in the deployment descriptor of the Resource Adaptor of the resource adaptor entity is False and the resource adaptor entity is in the Active or Stopping state and the SLEE is in the Starting, Running, or Stopping state\" ) ; } else { object . raConfigurationUpdate ( properties ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals that the container is in RUNNING state [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public void sleeRunning ( ) throws InvalidStateException { // if entity is active then activate the ra object\r if ( this . state . isActive ( ) ) { if ( setFTContext ) { setFTContext = false ; if ( object . isFaultTolerant ( ) ) { // set fault tolerant context, it is a ft ra\r try { this . ftResourceAdaptorContext = new FaultTolerantResourceAdaptorContextImpl ( name , sleeContainer , ( FaultTolerantResourceAdaptor ) object . getResourceAdaptorObject ( ) ) ; object . setFaultTolerantResourceAdaptorContext ( ftResourceAdaptorContext ) ; } catch ( Throwable t ) { logger . error ( \"Got exception invoking setFaultTolerantResourceAdaptorContext(...) for entity \" + name , t ) ; } } } try { object . raActive ( ) ; } catch ( Throwable t ) { logger . error ( \"Got exception invoking raActive() for entity \" + name , t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals that the container is in STOPPING state [CODESPLIT] public void sleeStopping ( ) throws InvalidStateException , TransactionRequiredLocalException { if ( state != null && state . isActive ( ) ) { try { object . raStopping ( ) ; } catch ( Throwable t ) { logger . error ( \"Got exception from RA object\" , t ) ; } scheduleAllActivitiesEnd ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Activates the ra entity [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public void activate ( ) throws InvalidStateException { if ( ! this . state . isInactive ( ) ) { throw new InvalidStateException ( \"entity \" + name + \" is in state: \" + this . state ) ; } this . state = ResourceAdaptorEntityState . ACTIVE ; // if slee is running then activate ra object\r if ( sleeContainer . getSleeState ( ) == SleeState . RUNNING ) { if ( setFTContext ) { setFTContext = false ; if ( object . isFaultTolerant ( ) ) { // set fault tolerant context, it is a ft ra\r try { this . ftResourceAdaptorContext = new FaultTolerantResourceAdaptorContextImpl ( name , sleeContainer , ( FaultTolerantResourceAdaptor ) object . getResourceAdaptorObject ( ) ) ; object . setFaultTolerantResourceAdaptorContext ( ftResourceAdaptorContext ) ; } catch ( Throwable t ) { logger . error ( \"Got exception invoking setFaultTolerantResourceAdaptorContext(...) for entity \" + name , t ) ; } } } try { object . raActive ( ) ; } catch ( Throwable t ) { logger . error ( \"Got exception invoking raActive() for entity \" + name , t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deactivates the ra entity [CODESPLIT] public void deactivate ( ) throws InvalidStateException , TransactionRequiredLocalException { if ( ! this . state . isActive ( ) ) { throw new InvalidStateException ( \"entity \" + name + \" is in state: \" + this . state ) ; } this . state = ResourceAdaptorEntityState . STOPPING ; if ( object . getState ( ) == ResourceAdaptorObjectState . ACTIVE ) { object . raStopping ( ) ; } // tck requires that the method returns with stopping state so do\r // all deactivation logic half a sec later\r TimerTask t = new TimerTask ( ) { @ Override public void run ( ) { try { cancel ( ) ; if ( state == ResourceAdaptorEntityState . STOPPING ) { if ( object . getState ( ) == ResourceAdaptorObjectState . STOPPING ) { scheduleAllActivitiesEnd ( ) ; } else { allActivitiesEnded ( ) ; } } } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } ; resourceAdaptorContext . getTimer ( ) . schedule ( t , 500 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "schedules the ending of all the entity activities this is needed on ra entity deactivation or slee container stop once the process ends it will invoke allActivitiesEnded to complete those processes [CODESPLIT] private void scheduleAllActivitiesEnd ( ) throws TransactionRequiredLocalException { // schedule the end of all activities if the node is the single member of the cluster\r boolean skipActivityEnding = ! sleeContainer . getCluster ( ) . isSingleMember ( ) ; if ( ! skipActivityEnding && hasActivities ( ) ) { logger . info ( \"RA entity \" + name + \" activities end scheduled.\" ) ; timerTask = new EndAllActivitiesRAEntityTimerTask ( this , sleeContainer ) ; } else { allActivitiesEnded ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the entity has activities besides the one passed as parameter ( if not null ) . [CODESPLIT] private boolean hasActivities ( ) { try { for ( ActivityContextHandle handle : sleeContainer . getActivityContextFactory ( ) . getAllActivityContextsHandles ( ) ) { if ( handle . getActivityType ( ) == ActivityType . RA ) { ResourceAdaptorActivityContextHandle raHandle = ( ResourceAdaptorActivityContextHandle ) handle ; if ( raHandle . getResourceAdaptorEntity ( ) . equals ( this ) ) { logger . debug ( \"**** AllActivityContextsHandles: \" + sleeContainer . getActivityContextFactory ( ) . getAllActivityContextsHandles ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"RA entity \" + name + \" has (at least) activity \" + handle . getActivityHandle ( ) ) ; } //return true;\r logger . warn ( \"WORKAROUND USAGE: ENDING RESOURCE ADAPTOR ACTIVITIES\" ) ; sleeContainer . getActivityContextFactory ( ) . WAremove ( \"RA\" ) ; return false ; } } } } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the entity it will unconfigure and unset the ra context the entity object can not be reused [CODESPLIT] public void remove ( ) throws InvalidStateException { if ( ! this . state . isInactive ( ) ) { throw new InvalidStateException ( \"entity \" + name + \" is in state: \" + this . state ) ; } object . raUnconfigure ( ) ; if ( object . isFaultTolerant ( ) ) { object . unsetFaultTolerantResourceAdaptorContext ( ) ; ftResourceAdaptorContext . shutdown ( ) ; } object . unsetResourceAdaptorContext ( ) ; this . sleeContainer . getTraceManagement ( ) . deregisterNotificationSource ( this . getNotificationSource ( ) ) ; state = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the ra interface for this entity and the specified ra type [CODESPLIT] public Object getResourceAdaptorInterface ( ResourceAdaptorTypeID raType ) { return object . getResourceAdaptorInterface ( sleeContainer . getComponentRepository ( ) . getComponentByID ( raType ) . getDescriptor ( ) . getResourceAdaptorInterface ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates a service was activated the entity will forward this notification to the ra object . [CODESPLIT] public void serviceActive ( ServiceID serviceID ) { try { ReceivableService receivableService = resourceAdaptorContext . getServiceLookupFacility ( ) . getReceivableService ( serviceID ) ; if ( receivableService . getReceivableEvents ( ) . length > 0 ) { object . serviceActive ( receivableService ) ; } } catch ( Throwable e ) { logger . warn ( \"invocation resulted in unchecked exception\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if it is a handle reference it gets the referred handle [CODESPLIT] ActivityHandle derreferActivityHandle ( ActivityHandle handle ) { ActivityHandle ah = null ; if ( resourceManagement . getHandleReferenceFactory ( ) != null && handle . getClass ( ) == ActivityHandleReference . class ) { ActivityHandleReference ahReference = ( ActivityHandleReference ) handle ; ah = resourceManagement . getHandleReferenceFactory ( ) . getActivityHandle ( ahReference ) ; } else { ah = handle ; } return ah ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback to notify the entity and possibly the ra object informing activity handled ended . [CODESPLIT] public void activityEnded ( final ActivityHandle handle , int activityFlags ) { logger . trace ( \"activityEnded( handle = \" + handle + \" )\" ) ; ActivityHandle ah = null ; if ( handle instanceof ActivityHandleReference ) { // handle is a ref, derrefer and remove the ref\r ah = resourceManagement . getHandleReferenceFactory ( ) . removeActivityHandleReference ( ( ActivityHandleReference ) handle ) ; } else { // handle is not a reference\r ah = handle ; } if ( ah != null && ActivityFlags . hasRequestEndedCallback ( activityFlags ) ) { object . activityEnded ( ah ) ; } if ( object . getState ( ) == ResourceAdaptorObjectState . STOPPING ) { synchronized ( this ) { // the ra object is stopping, check if the timer task is still\r // needed\r if ( ! hasActivities ( ) ) { if ( timerTask != null ) { timerTask . cancel ( ) ; } allActivitiesEnded ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void activate ( ServiceID serviceID ) throws NullPointerException , UnrecognizedServiceException , InvalidStateException , InvalidLinkNameBindingStateException , ManagementException { try { serviceManagement . activate ( serviceID ) ; } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedServiceException e ) { throw e ; } catch ( InvalidLinkNameBindingStateException e ) { throw e ; } catch ( InvalidStateException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void activate ( ServiceID [ ] serviceIDs ) throws NullPointerException , InvalidArgumentException , UnrecognizedServiceException , InvalidStateException , InvalidLinkNameBindingStateException , ManagementException { try { serviceManagement . activate ( serviceIDs ) ; } catch ( NullPointerException e ) { throw e ; } catch ( InvalidArgumentException e ) { throw e ; } catch ( UnrecognizedServiceException e ) { throw e ; } catch ( InvalidLinkNameBindingStateException e ) { throw e ; } catch ( InvalidStateException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setResourceAdaptorContext ( ResourceAdaptorContext context ) throws InvalidStateException { if ( doTraceLogs ) { logger . trace ( \"setResourceAdaptorContext( context = \" + context + \" )\" ) ; } if ( state == null ) { state = ResourceAdaptorObjectState . UNCONFIGURED ; object . setResourceAdaptorContext ( context ) ; } else { throw new InvalidStateException ( \"ra object is in state \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void setFaultTolerantResourceAdaptorContext ( FaultTolerantResourceAdaptorContext < Serializable , Serializable > context ) throws IllegalArgumentException { if ( doTraceLogs ) { logger . trace ( \"setFaultTolerantResourceAdaptorContext( context = \" + context + \" )\" ) ; } if ( isFaultTolerant ( ) ) { ( ( FaultTolerantResourceAdaptor < Serializable , Serializable > ) this . object ) . setFaultTolerantResourceAdaptorContext ( context ) ; } else { throw new IllegalArgumentException ( \"RA Object is not fault tolerant!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void raConfigure ( ConfigProperties properties ) throws InvalidConfigurationException { if ( doTraceLogs ) { logger . trace ( \"raConfigure( properties = \" + properties + \" )\" ) ; } verifyConfigProperties ( properties ) ; object . raConfigure ( configProperties ) ; if ( state == ResourceAdaptorObjectState . UNCONFIGURED ) { state = ResourceAdaptorObjectState . INACTIVE ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the ra configuration . [CODESPLIT] public void raConfigurationUpdate ( ConfigProperties properties ) throws InvalidConfigurationException { if ( doTraceLogs ) { logger . trace ( \"raConfigurationUpdate( properties = \" + properties + \" )\" ) ; } verifyConfigProperties ( properties ) ; object . raConfigurationUpdate ( configProperties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the current properties values with the new ones and uses the ra to verify the configuration [CODESPLIT] private void verifyConfigProperties ( ConfigProperties newProperties ) throws InvalidConfigurationException { if ( doTraceLogs ) { logger . trace ( \"verifyConfigProperties( newProperties = \" + newProperties + \" )\" ) ; } // merge properties for ( ConfigProperties . Property configProperty : configProperties . getProperties ( ) ) { if ( newProperties . getProperty ( configProperty . getName ( ) ) == null ) { newProperties . addProperty ( configProperty ) ; } } // validate result for ( ConfigProperties . Property entityProperty : newProperties . getProperties ( ) ) { if ( entityProperty . getValue ( ) == null ) { throw new InvalidConfigurationException ( \"the property \" + entityProperty . getName ( ) + \" has null value\" ) ; } } // validate in ra object object . raVerifyConfiguration ( newProperties ) ; // ok, switch config configProperties = newProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void raActive ( ) throws InvalidStateException { if ( doTraceLogs ) { logger . trace ( \"raActive()\" ) ; } if ( state == ResourceAdaptorObjectState . INACTIVE ) { state = ResourceAdaptorObjectState . ACTIVE ; object . raActive ( ) ; } else { throw new InvalidStateException ( \"ra object is in state \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests the stopping of the ra object . If the operation succeeds the ra will transition to STOPPING state . [CODESPLIT] public void raStopping ( ) throws InvalidStateException { if ( doTraceLogs ) { logger . trace ( \"raStopping()\" ) ; } if ( state == ResourceAdaptorObjectState . ACTIVE ) { state = ResourceAdaptorObjectState . STOPPING ; object . raStopping ( ) ; } else { throw new InvalidStateException ( \"ra object is in state \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests the deactivation of the ra object . If the operation succeeds the ra will transition to INACTIVE state . [CODESPLIT] public void raInactive ( ) throws InvalidStateException { if ( doTraceLogs ) { logger . trace ( \"raInactive()\" ) ; } if ( state == ResourceAdaptorObjectState . STOPPING ) { state = ResourceAdaptorObjectState . INACTIVE ; object . raInactive ( ) ; } else { throw new InvalidStateException ( \"ra object is in state \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unconfigures the ra object [CODESPLIT] public void raUnconfigure ( ) throws InvalidStateException { if ( doTraceLogs ) { logger . trace ( \"raUnconfigure()\" ) ; } if ( state == ResourceAdaptorObjectState . INACTIVE ) { state = ResourceAdaptorObjectState . UNCONFIGURED ; object . raUnconfigure ( ) ; } else { throw new InvalidStateException ( \"ra object is in state \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unsets the context of the ra object . [CODESPLIT] public void unsetResourceAdaptorContext ( ) throws InvalidStateException { if ( doTraceLogs ) { logger . trace ( \"unsetResourceAdaptorContext()\" ) ; } if ( state == ResourceAdaptorObjectState . UNCONFIGURED ) { object . unsetResourceAdaptorContext ( ) ; state = null ; } else { throw new InvalidStateException ( \"ra object is in state \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unsets the ft context of the ra object . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void unsetFaultTolerantResourceAdaptorContext ( ) throws IllegalArgumentException { if ( doTraceLogs ) { logger . trace ( \"unsetFaultTolerantResourceAdaptorContext()\" ) ; } if ( isFaultTolerant ( ) ) { ( ( FaultTolerantResourceAdaptor < Serializable , Serializable > ) this . object ) . unsetFaultTolerantResourceAdaptorContext ( ) ; } else { throw new IllegalArgumentException ( \"RA Object is not fault tolerant!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the profile attribute map using the cmp interface class [CODESPLIT] private void buildProfileAttributeMap ( ) throws DeploymentException { HashMap < String , ProfileAttribute > map = new HashMap < String , ProfileAttribute > ( ) ; Class < ? > cmpInterface = getProfileCmpInterfaceClass ( ) ; String attributeGetterMethodPrefix = \"get\" ; for ( Method method : cmpInterface . getMethods ( ) ) { if ( ! method . getDeclaringClass ( ) . equals ( Object . class ) && method . getName ( ) . startsWith ( attributeGetterMethodPrefix ) ) { String attributeName = method . getName ( ) . substring ( attributeGetterMethodPrefix . length ( ) ) ; switch ( attributeName . length ( ) ) { case 0 : throw new DeploymentException ( \"the profile cmp interface class has an invalid attribute getter method name > \" + method . getName ( ) ) ; case 1 : attributeName = attributeName . toLowerCase ( ) ; break ; default : attributeName = attributeName . substring ( 0 , 1 ) . toLowerCase ( ) + attributeName . substring ( 1 ) ; break ; } ProfileAttributeImpl profileAttribute = null ; try { profileAttribute = new ProfileAttributeImpl ( attributeName , method . getReturnType ( ) ) ; } catch ( Throwable e ) { throw new DeploymentException ( \"Invalid profile cmp interface attribute getter method definition ( name = \" + attributeName + \" , type = \" + method . getReturnType ( ) + \" )\" , e ) ; } if ( isSlee11 ( ) ) { for ( ProfileCMPFieldDescriptor cmpField : getDescriptor ( ) . getProfileCMPInterface ( ) . getCmpFields ( ) ) { if ( cmpField . getCmpFieldName ( ) . equals ( attributeName ) ) { // TODO add index hints ?\r profileAttribute . setUnique ( cmpField . isUnique ( ) ) ; } } } else { for ( ProfileIndexDescriptor profileIndex : getDescriptor ( ) . getIndexedAttributes ( ) ) { if ( profileIndex . getName ( ) . equals ( attributeName ) ) { profileAttribute . setIndex ( true ) ; profileAttribute . setUnique ( profileIndex . getUnique ( ) ) ; } } } map . put ( attributeName , profileAttribute ) ; } } profileAttributeMap = Collections . unmodifiableMap ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JAIN SLEE specs descriptor [CODESPLIT] public javax . slee . profile . ProfileSpecificationDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { final LibraryID [ ] libraryIDs = descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) ; final ProfileSpecificationID [ ] profileSpecs = new ProfileSpecificationID [ descriptor . getProfileSpecRefs ( ) . size ( ) ] ; for ( int i = 0 ; i < profileSpecs . length ; i ++ ) { profileSpecs [ i ] = descriptor . getProfileSpecRefs ( ) . get ( i ) . getComponentID ( ) ; } specsDescriptor = new javax . slee . profile . ProfileSpecificationDescriptor ( getProfileSpecificationID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , libraryIDs , profileSpecs , getDescriptor ( ) . getProfileCMPInterface ( ) . getProfileCmpInterfaceName ( ) ) ; } return specsDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the real logic to resume the event context [CODESPLIT] private void resume ( ) { // create runnable to resume the event context Runnable runnable = new Runnable ( ) { public void run ( ) { if ( scheduledFuture == null ) { // already resumed return ; } // cancel timer task scheduledFuture . cancel ( false ) ; scheduledFuture = null ; // send events frozen to event router again, will be processed only after this one ends (this one is already being executed) for ( EventContext ec : barriedEvents ) { ec . getLocalActivityContext ( ) . getExecutorService ( ) . routeEvent ( ec ) ; } barriedEvents = null ; // remove barrier on activity event queue event . getLocalActivityContext ( ) . getEventQueueManager ( ) . removeBarrier ( transaction ) ; // remove suspension suspended = false ; // continue routing the event related with this context event . getLocalActivityContext ( ) . getCurrentEventRoutingTask ( ) . run ( ) ; } } ; // run it using the activity executor service to avoid thread concurrency event . getLocalActivityContext ( ) . getExecutorService ( ) . execute ( runnable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void wonOwnership ( ClusteredCacheData clusteredCacheData ) { ra . failOver ( ( K ) clusteredCacheData . getNodeFqn ( ) . getLastElement ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a set containing all activity context handles in the factory s cache data [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Set < ActivityContextHandle > getActivityContextHandles ( ) { final Node node = getNode ( ) ; return node != null ? node . getChildrenNames ( ) : Collections . emptySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public TimerTask newTimerTask ( TimerTaskData data ) { FaultTolerantTimerTaskDataWrapper dataWrapper = ( FaultTolerantTimerTaskDataWrapper ) data ; FaultTolerantTimerTask task = taskFactory . getTask ( dataWrapper . getWrappedData ( ) ) ; return new FaultTolerantTimerTaskWrapper ( task , dataWrapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare this notification source with the specified object for order . Returns a negative integer zero or a positive integer if this object is less than equal to or greater than the specified object . <p > If <code > obj< / code > is a <code > ProfileTableNotification< / code > order is determined by comparing the encapsulated profile table name . Otherwise if <code > obj< / code > is a <code > NotificationSource< / code > ordering is determined by comparing the class name of this class with the class name of <code > obj< / code > . [CODESPLIT] public int compareTo ( Object obj ) { // can't compare with null if ( obj == null ) throw new NullPointerException ( \"obj is null\" ) ; if ( obj == this ) return 0 ; if ( obj instanceof ProfileTableNotification ) { // compare the profile table name ProfileTableNotification that = ( ProfileTableNotification ) obj ; return this . profileTableName . compareTo ( that . profileTableName ) ; } else { return super . compareTo ( TYPE , obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance of this object and set the SbbContext This places it into the object pool . [CODESPLIT] public Object makeObject ( ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"makeObject()\" ) ; } ProfileObjectImpl profileObject = new ProfileObjectImpl ( profileTable ) ; profileObject . setProfileContext ( new ProfileContextImpl ( profileTable ) ) ; return profileObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public List < LibraryDescriptorImpl > parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; List < LibraryDescriptorImpl > result = new ArrayList < LibraryDescriptorImpl > ( ) ; // Only exists in JAIN SLEE 1.1 boolean isSlee11 = true ; MLibraryJar mLibraryJar = null ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . library . LibraryJar ) { mLibraryJar = new MLibraryJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . library . LibraryJar ) jaxbPojo ) ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } MSecurityPermissions securityPermissions = mLibraryJar . getSecurityPermissions ( ) ; for ( MLibrary mLibrary : mLibraryJar . getLibrary ( ) ) { result . add ( new LibraryDescriptorImpl ( mLibrary , securityPermissions , isSlee11 ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileTableUsageMBean newProfileTableUsageMBean ( String profileTableName , ProfileSpecificationComponent component ) throws NotCompliantMBeanException , MalformedObjectNameException , NullPointerException { return new ProfileTableUsageMBeanImpl ( profileTableName , component , sleeContainer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ResourceUsageMBean newResourceUsageMBean ( String entityName , ResourceAdaptorComponent component ) throws NotCompliantMBeanException , MalformedObjectNameException , NullPointerException { return new ResourceUsageMBeanImpl ( entityName , component , sleeContainer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ServiceUsageMBean newServiceUsageMBean ( ServiceComponent component ) throws NotCompliantMBeanException , MalformedObjectNameException , NullPointerException { return new ServiceUsageMBeanImpl ( component , sleeContainer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the mbean [CODESPLIT] public void remove ( ) { Logger logger = getLogger ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Closing \" + toString ( ) ) ; } final MBeanServer mbeanServer = sleeContainer . getMBeanServer ( ) ; try { mbeanServer . unregisterMBean ( getObjectName ( ) ) ; } catch ( Exception e ) { logger . error ( \"failed to remove \" + toString ( ) , e ) ; } // remove all usage param if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Removing all named usage parameters of \" + toString ( ) ) ; } for ( String name : usageMBeans . keySet ( ) ) { try { _removeUsageParameterSet ( name , false ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } // also remove the default try { removeUsageParameterSet ( ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the usage param ( and its mbean ) for the specified name [CODESPLIT] public void createUsageParameterSet ( String paramSetName ) throws NullPointerException , InvalidArgumentException , UsageParameterSetNameAlreadyExistsException , ManagementException { if ( paramSetName == null ) throw new NullPointerException ( \"usage param set is null\" ) ; if ( paramSetName . length ( ) == 0 ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; if ( ! isValidUsageParameterName ( paramSetName ) ) throw new InvalidArgumentException ( \"The lenght of the Usage Parameter Set Name is zero!\" ) ; _createUsageParameterSet ( paramSetName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the object name for the usage param mbean with the specified name [CODESPLIT] public ObjectName getUsageMBean ( String paramSetName ) throws NullPointerException , UnrecognizedUsageParameterSetNameException , ManagementException { if ( paramSetName == null ) throw new NullPointerException ( \"Sbb usage param set is null\" ) ; return _getUsageMBean ( paramSetName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the usage param ( and its mbean ) for the specified name [CODESPLIT] public void removeUsageParameterSet ( String paramSetName ) throws NullPointerException , UnrecognizedUsageParameterSetNameException , ManagementException { if ( paramSetName == null ) throw new NullPointerException ( \"usage param set is null\" ) ; //FIXME: should we recreate beans here as well ? _removeUsageParameterSet ( paramSetName , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method to retrieve the { @link AbstractUsageParameterSet } for the specified param set name . [CODESPLIT] public AbstractUsageParameterSet getInstalledUsageParameterSet ( String name ) { if ( name == null ) { return getDefaultInstalledUsageParameterSet ( ) ; } else { UsageMBeanImpl usageMBean = usageMBeans . get ( name ) ; if ( usageMBean == null ) { return null ; } else { return usageMBean . getUsageParameter ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public List < ResourceAdaptorDescriptorImpl > parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; List < ResourceAdaptorDescriptorImpl > result = new ArrayList < ResourceAdaptorDescriptorImpl > ( ) ; boolean isSlee11 = false ; MResourceAdaptorJar mResourceAdaptorJar = null ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee . ra . ResourceAdaptorJar ) { mResourceAdaptorJar = new MResourceAdaptorJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee . ra . ResourceAdaptorJar ) jaxbPojo ) ; } else if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . ra . ResourceAdaptorJar ) { mResourceAdaptorJar = new MResourceAdaptorJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . ra . ResourceAdaptorJar ) jaxbPojo ) ; isSlee11 = true ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } MSecurityPermissions securityPermissions = mResourceAdaptorJar . getSecurityPermissions ( ) ; for ( MResourceAdaptor mResourceAdaptor : mResourceAdaptorJar . getResourceAdaptor ( ) ) { result . add ( new ResourceAdaptorDescriptorImpl ( mResourceAdaptor , securityPermissions , isSlee11 ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorate the abstract Class [CODESPLIT] public boolean decorateAbstractClass ( ) throws DeploymentException { ClassPool pool = component . getClassPool ( ) ; ProfileAbstractClassDescriptor abstractClass = component . getDescriptor ( ) . getProfileAbstractClass ( ) ; if ( abstractClass == null ) { return false ; } String abstractClassName = abstractClass . getProfileAbstractClassName ( ) ; try { ctClass = pool . get ( abstractClassName ) ; } catch ( NotFoundException nfe ) { throw new DeploymentException ( \"Could not find Abstract Class: \" + abstractClassName , nfe ) ; } decorateClassJNDIAddToEnvironmentCalls ( ) ; if ( isAbstractClassDecorated ) { try { String deployDir = component . getDeploymentDir ( ) . getAbsolutePath ( ) ; ctClass . writeFile ( deployDir ) ; ctClass . detach ( ) ; // the file on disk is now in sync with the latest in-memory version\r if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Modified Abstract Class \" + ctClass . getName ( ) + \" generated in the following path \" + deployDir ) ; } } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } finally { ctClass . defrost ( ) ; } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean create ( ) { ConcurrentHashMap < String , UsageParamSetLocalData > notificationSourceUsageParamSets = notificationSourceUsageParamSetsMap . get ( notificationSource ) ; if ( notificationSourceUsageParamSets == null ) { ConcurrentHashMap < String , UsageParamSetLocalData > newNotificationSourceUsageParamSets = new ConcurrentHashMap < String , UsageParamSetLocalData > ( ) ; notificationSourceUsageParamSets = notificationSourceUsageParamSetsMap . putIfAbsent ( notificationSource , newNotificationSourceUsageParamSets ) ; if ( notificationSourceUsageParamSets == null ) { notificationSourceUsageParamSets = newNotificationSourceUsageParamSets ; } } if ( ! notificationSourceUsageParamSets . containsKey ( usageParameterSetName ) ) { return notificationSourceUsageParamSets . putIfAbsent ( usageParameterSetName , new UsageParamSetLocalData ( usageParameterSetName ) ) == null ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public UsageParameter getParameter ( String parameterName ) { Map < String , UsageParamSetLocalData > notificationSourceUsageParamSets = notificationSourceUsageParamSetsMap . get ( notificationSource ) ; if ( notificationSourceUsageParamSets != null ) { UsageParamSetLocalData data = notificationSourceUsageParamSets . get ( usageParameterSetName ) ; if ( data != null ) { return data . getUsageParam ( parameterName ) ; } else { return null ; } } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < String > getParameterNames ( ) { Map < String , UsageParamSetLocalData > notificationSourceUsageParamSets = notificationSourceUsageParamSetsMap . get ( notificationSource ) ; if ( notificationSourceUsageParamSets != null ) { UsageParamSetLocalData data = notificationSourceUsageParamSets . get ( usageParameterSetName ) ; if ( data != null ) { return data . getParameterNames ( ) ; } else { throw new IllegalStateException ( \"Usage param set not found ( notification source = \" + notificationSource + \" , usage param set name = \" + usageParameterSetName + \" ) \" ) ; } } else { throw new IllegalStateException ( \"Notification source usage param sets not found ( notification source = \" + notificationSource + \" ) \" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean remove ( ) { final Map < String , UsageParamSetLocalData > notificationSourceUsageParamSets = notificationSourceUsageParamSetsMap . get ( notificationSource ) ; if ( notificationSourceUsageParamSets != null ) { return notificationSourceUsageParamSets . remove ( usageParameterSetName ) != null ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setParameter ( String parameterName , UsageParameter usageParameter ) { final Map < String , UsageParamSetLocalData > notificationSourceUsageParamSets = notificationSourceUsageParamSetsMap . get ( notificationSource ) ; if ( notificationSourceUsageParamSets != null ) { UsageParamSetLocalData data = notificationSourceUsageParamSets . get ( usageParameterSetName ) ; if ( data != null ) { data . setUsageParam ( parameterName , usageParameter ) ; } else { throw new IllegalStateException ( \"Usage param set not found ( notification source = \" + notificationSource + \" , usage param set name = \" + usageParameterSetName + \" ) \" ) ; } } else { throw new IllegalStateException ( \"Notification source usage param sets not found ( notification source = \" + notificationSource + \" ) \" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { [CODESPLIT] public static ChildRelation getChildRelation ( SbbEntity sbbEntity , String childRelationMethodName ) { if ( sbbEntity . getSbbObject ( ) . getState ( ) != SbbObjectState . READY ) throw new IllegalStateException ( \"Could not invoke getChildRelation Method, Sbb Object is not in the READY state!\" ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"ChildRelation Interceptor:\" + childRelationMethodName ) ; } return sbbEntity . getChildRelation ( childRelationMethodName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The logic to fire an event from an SLEE 1 . 0 Sbb [CODESPLIT] public static void fireEvent ( SbbEntity sbbEntity , EventTypeID eventTypeID , Object eventObject , ActivityContextInterface aci , Address address ) { fireEvent ( sbbEntity , eventTypeID , eventObject , aci , address , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The logic to fire an event from an SLEE 1 . 1 Sbb [CODESPLIT] public static void fireEvent ( SbbEntity sbbEntity , EventTypeID eventTypeID , Object eventObject , ActivityContextInterface aci , Address address , ServiceID serviceID ) { if ( sleeContainer . getCongestionControl ( ) . refuseFireEvent ( ) ) { throw new SLEEException ( \"congestion control refused event\" ) ; } // JAIN SLEE (TM) specs - Section 8.4.1 // The SBB object must have an assigned SBB entity when it invokes this // method. // Otherwise, this method throws a java.lang.IllegalStateException. if ( sbbEntity == null || sbbEntity . getSbbObject ( ) == null || sbbEntity . getSbbObject ( ) . getState ( ) != SbbObjectState . READY ) throw new IllegalStateException ( \"SbbObject not assigned!\" ) ; // JAIN SLEE (TM) specs - Section 8.4.1 // The event ... cannot be null. If ... argument is null, the fire // event method throws a java.lang.NullPointerException. if ( eventObject == null ) throw new NullPointerException ( \"JAIN SLEE (TM) specs - Section 8.4.1: The event ... cannot be null. If ... argument is null, the fire event method throws a java.lang.NullPointerException.\" ) ; // JAIN SLEE (TM) specs - Section 8.4.1 // The activity ... cannot be null. If ... argument is null, the fire // event method throws a java.lang.NullPointerException. if ( aci == null ) throw new NullPointerException ( \"JAIN SLEE (TM) specs - Section 8.4.1: The activity ... cannot be null. If ... argument is null, the fire event method throws a java.lang.NullPointerException.\" ) ; // JAIN SLEE (TM) specs - Section 8.4.1 // It is a mandatory transactional method (see Section 9.6.1). final SleeTransactionManager txManager = sleeContainer . getTransactionManager ( ) ; txManager . mandateTransaction ( ) ; // rebuild the ac from the aci in the 2nd argument of the invoked // method, check it's state ActivityContext ac = ( ( org . mobicents . slee . container . activity . ActivityContextInterface ) aci ) . getActivityContext ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"invoke(): firing event on \" + ac ) ; } // exception not in specs by mandated by // tests/activities/activitycontext/Test560Test.xml , it's preferable to // do double check on here than have the aci fire method throwing it and // the ra slee endpoint having to translate it to activity ending // exception, it is not common to have custom event firing in sbbs if ( ac . isEnding ( ) ) { throw new IllegalStateException ( \"activity context \" + ac . getActivityContextHandle ( ) + \" is ending\" ) ; } final EventRoutingTransactionData transactionData = txManager . getTransactionContext ( ) . getEventRoutingTransactionData ( ) ; if ( transactionData != null ) { final EventContext eventBeingDelivered = transactionData . getEventBeingDelivered ( ) ; if ( eventBeingDelivered != null && eventBeingDelivered . getEvent ( ) == eventObject ) { // there is an event being delivered by this tx and it matches the event being fired, lets copy the ref handler // fire the event ac . fireEvent ( eventTypeID , eventObject , ( Address ) address , serviceID , eventBeingDelivered ) ; return ; } } // seems it is not a refire ac . fireEvent ( eventTypeID , eventObject , ( Address ) address , serviceID , null , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a profile given the cmp method name and profile id [CODESPLIT] public static Object getProfileCMPMethod ( SbbEntity sbbEntity , String getProfileCMPMethodName , ProfileID profileID ) throws UnrecognizedProfileTableNameException , UnrecognizedProfileNameException { GetProfileCMPMethodDescriptor mGetProfileCMPMethod = sbbEntity . getSbbComponent ( ) . getDescriptor ( ) . getGetProfileCMPMethods ( ) . get ( getProfileCMPMethodName ) ; if ( mGetProfileCMPMethod == null ) throw new AbstractMethodError ( \"Profile CMP Method not found\" ) ; if ( sbbEntity . getSbbObject ( ) . getState ( ) != SbbObjectState . READY ) { throw new IllegalStateException ( \"Could not invoke getProfileCMP Method, Sbb Object is not in the READY state!\" ) ; } ProfileManagement sleeProfileManager = sleeContainer . getSleeProfileTableManager ( ) ; ProfileTable profileTable = sleeProfileManager . getProfileTable ( profileID . getProfileTableName ( ) ) ; if ( ! profileTable . profileExists ( profileID . getProfileName ( ) ) ) { throw new UnrecognizedProfileNameException ( profileID . toString ( ) ) ; } return profileTable . getProfile ( profileID . getProfileName ( ) ) . getProfileCmpSlee10Wrapper ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SBB USAGE PARAMS [CODESPLIT] public static Object getSbbUsageParameterSet ( SbbEntity sbbEntity , String name ) throws UnrecognizedUsageParameterSetNameException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"getSbbUsageParameterSet(): serviceId = \" + sbbEntity . getSbbEntityId ( ) . getServiceID ( ) + \" , sbbID = \" + sbbEntity . getSbbId ( ) + \" , name = \" + name ) ; } return getServiceUsageMBeanImpl ( sbbEntity . getSbbEntityId ( ) . getServiceID ( ) ) . getInstalledUsageParameterSet ( sbbEntity . getSbbId ( ) , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public NullActivityImpl createNullActivity ( NullActivityHandle nullActivityHandle , boolean mandateTransaction ) throws TransactionRequiredLocalException , FactoryException { // check mandated by SLEE TCK test CreateActivityWhileStoppingTest\r if ( sleeContainer . getSleeState ( ) != SleeState . RUNNING ) { return null ; } if ( mandateTransaction ) { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; } // create activity\r NullActivityImpl nullActivity = new NullActivityImpl ( nullActivityHandle ) ; // get an activity context for it\r try { sleeContainer . getActivityContextFactory ( ) . createActivityContext ( new NullActivityContextHandle ( nullActivityHandle ) , ActivityFlags . REQUEST_ACTIVITY_UNREFERENCED_CALLBACK ) ; } catch ( ActivityAlreadyExistsException e ) { throw new FactoryException ( e . getMessage ( ) , e ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"NullActivityFactory.createNullActivity() Created null activity \" + nullActivity ) ; } return nullActivity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void afterCompletion ( int status ) { TransactionContextThreadLocal . setTransactionContext ( null ) ; switch ( status ) { case Status . STATUS_COMMITTED : if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Completed commit of tx \" + tx ) ; } txContext . executeAfterCommitPriorityActions ( ) ; txContext . executeAfterCommitActions ( ) ; break ; case Status . STATUS_ROLLEDBACK : if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Completed rollback of tx \" + tx ) ; } txContext . executeAfterRollbackActions ( ) ; break ; default : throw new IllegalStateException ( \"Unexpected transaction state \" + status ) ; } txContext . cleanup ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute a convergence name for the Sbb for the given Slee event . Convergence names are used to instantiate the Sbb . I really ought to move this to SleeContainer . java [CODESPLIT] private String computeConvergenceName ( EventContext eventContext , ServiceComponent serviceComponent , SleeContainer sleeContainer ) throws Exception { final SbbComponent sbbComponent = serviceComponent . getRootSbbComponent ( ) ; final EventEntryDescriptor eventEntryDescriptor = sbbComponent . getDescriptor ( ) . getEventEntries ( ) . get ( eventContext . getEventTypeId ( ) ) ; StringBuilder buff = null ; /*\n\t\t * An initial-event-selector-method-name element. This element is\n\t\t * optional and is meaningful only if initial-event is true. It\n\t\t * identifies an in itial event selector method. The SLEE invokes this\n\t\t * optional method to d etermine if an event of the specified event type\n\t\t * is an initial event if the SBB is a root SBB of a Service (see\n\t\t * Section 8.5.4). Note that this method is not static. You can either\n\t\t * used a pooled instance of the object or create a new instance of the\n\t\t * object to run the specified method.\n\t\t */ if ( eventEntryDescriptor . getInitialEventSelectorMethod ( ) != null ) { // IES METHOD DEFINED // invoke method InitialEventSelectorImpl selector = new InitialEventSelectorImpl ( eventContext , eventEntryDescriptor ) ; SbbObjectPool pool = sleeContainer . getSbbManagement ( ) . getObjectPool ( serviceComponent . getServiceID ( ) , sbbComponent . getSbbID ( ) ) ; SbbObject sbbObject = pool . borrowObject ( ) ; Object [ ] args = new Object [ ] { selector } ; ClassLoader oldCl = Thread . currentThread ( ) . getContextClassLoader ( ) ; final JndiManagement jndiManagement = sleeContainer . getJndiManagement ( ) ; jndiManagement . pushJndiContext ( sbbComponent ) ; try { Thread . currentThread ( ) . setContextClassLoader ( sbbComponent . getClassLoader ( ) ) ; final Method m = sbbComponent . getInitialEventSelectorMethods ( ) . get ( eventEntryDescriptor . getInitialEventSelectorMethod ( ) ) ; selector = ( InitialEventSelectorImpl ) m . invoke ( sbbObject . getSbbConcrete ( ) , args ) ; if ( selector == null ) { return null ; } if ( ! selector . isInitialEvent ( ) ) { return null ; } } finally { jndiManagement . popJndiContext ( ) ; Thread . currentThread ( ) . setContextClassLoader ( oldCl ) ; pool . returnObject ( sbbObject ) ; } // build convergence name // AC VARIABLE if ( selector . isActivityContextSelected ( ) ) { buff = new StringBuilder ( eventContext . getLocalActivityContext ( ) . getStringId ( ) ) ; } else { buff = new StringBuilder ( NOT_SELECTED_STRING ) ; } // ADDRESS VARIABLE if ( selector . isAddressSelected ( ) && selector . getAddress ( ) != null ) { buff . append ( selector . getAddress ( ) . toString ( ) ) ; } else { buff . append ( NOT_SELECTED ) ; } // EVENT TYPE if ( selector . isEventTypeSelected ( ) ) { buff . append ( eventContext . getEventTypeId ( ) ) ; } else { buff . append ( NOT_SELECTED ) ; } // EVENT if ( selector . isEventSelected ( ) ) { buff . append ( eventContext . getEventContextHandle ( ) . getId ( ) ) ; } else { buff . append ( NOT_SELECTED ) ; } // ADDRESS PROFILE if ( selector . isAddressProfileSelected ( ) && selector . getAddress ( ) != null ) { final Collection < ProfileID > profileIDs = getAddressProfilesMatching ( selector . getAddress ( ) , serviceComponent , sbbComponent , sleeContainer ) ; if ( profileIDs . isEmpty ( ) ) // no profiles located return null ; else { buff . append ( profileIDs . iterator ( ) . next ( ) ) ; } } else { buff . append ( NOT_SELECTED ) ; } // CUSTOM NAME if ( selector . getCustomName ( ) != null ) { buff . append ( selector . getCustomName ( ) ) ; } } else { // NO IES METHOD DEFINED // build convergence name considering the variabes selected in sbb's xml descriptor // AC VARIABLE final InitialEventSelectorVariables initialEventSelectorVariables = eventEntryDescriptor . getInitialEventSelectVariables ( ) ; if ( initialEventSelectorVariables . isActivityContextSelected ( ) ) { if ( initialEventSelectorVariables . isActivityContextOnlySelected ( ) ) { // special most used case where convergence name is only bound to activity context return new StringBuilder ( eventContext . getLocalActivityContext ( ) . getStringId ( ) ) . append ( ALL_NOT_SELECTED_EXCEPT_AC ) . toString ( ) ; } else { buff = new StringBuilder ( eventContext . getLocalActivityContext ( ) . getStringId ( ) ) ; } } else { buff = new StringBuilder ( NOT_SELECTED_STRING ) ; } // ADDRESS VARIABLE if ( initialEventSelectorVariables . isAddressSelected ( ) && eventContext . getAddress ( ) != null ) { buff . append ( eventContext . getAddress ( ) . toString ( ) ) ; } else { buff . append ( NOT_SELECTED ) ; } // EVENT TYPE if ( initialEventSelectorVariables . isEventTypeSelected ( ) ) { buff . append ( eventContext . getEventTypeId ( ) ) ; } else { buff . append ( NOT_SELECTED ) ; } // EVENT if ( initialEventSelectorVariables . isEventSelected ( ) ) { buff . append ( eventContext . getEventContextHandle ( ) . getId ( ) ) ; } else { buff . append ( NOT_SELECTED ) ; } // ADDRESS PROFILE if ( initialEventSelectorVariables . isAddressProfileSelected ( ) && eventContext . getAddress ( ) != null ) { final Collection < ProfileID > profileIDs = getAddressProfilesMatching ( eventContext . getAddress ( ) , serviceComponent , sbbComponent , sleeContainer ) ; if ( profileIDs . isEmpty ( ) ) // no profiles located return null ; else { buff . append ( profileIDs . iterator ( ) . next ( ) ) ; } } else { buff . append ( NOT_SELECTED ) ; } } return buff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the set of names representing valid full access ( read&write ) JavaBean properties declared in the given class . NOTE : the implementation is not as strict as in Introspector ( @see java . beans . Introspector#getTargetPropertyInfo () ) . It probably should be . [CODESPLIT] public static Set getCMPFields ( CtClass clazz ) { Set properties = new HashSet ( ) ; // Apply some reflection to the current class. // First get an array of all the public methods at this level Set methods = getPublicAbstractMethods ( clazz ) ; // remove non-public methods Iterator iter = methods . iterator ( ) ; // the key in the getter/setter tables will be method name HashMap getters = new HashMap ( ) ; HashMap setters = new HashMap ( ) ; // split out getters and setters; ignore the rest while ( iter . hasNext ( ) ) { CtMethod method = ( CtMethod ) iter . next ( ) ; String mname = method . getName ( ) ; // skip static methods if ( Modifier . isStatic ( method . getModifiers ( ) ) ) continue ; String property = \"\" ; try { // skip methods, which throw exceptions if ( method . getExceptionTypes ( ) . length > 0 ) continue ; if ( mname . startsWith ( GET_PREFIX ) ) { property = mname . substring ( GET_PREFIX . length ( ) ) ; getters . put ( property , method ) ; } else if ( mname . startsWith ( IS_PREFIX ) && method . getReturnType ( ) . equals ( CtClass . booleanType ) ) { property = mname . substring ( IS_PREFIX . length ( ) ) ; getters . put ( property , method ) ; } else if ( mname . startsWith ( SET_PREFIX ) ) { property = mname . substring ( SET_PREFIX . length ( ) ) ; setters . put ( property , method ) ; } } catch ( NotFoundException e ) { logger . warn ( e ) ; } if ( property . length ( ) == 0 || ! Character . isUpperCase ( property . charAt ( 0 ) ) || property . equals ( PUBLIC_IDENTIFIER ) ) { logger . warn ( \"Method \" + mname + \" has a non-capitalized first character of the JavaBean property.\" ) ; getters . remove ( property ) ; setters . remove ( property ) ; } } // iterate over getters and find matching setters iter = getters . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; String property = ( String ) entry . getKey ( ) ; CtMethod getter = ( CtMethod ) entry . getValue ( ) ; // find matching setter CtMethod setter = ( CtMethod ) setters . get ( property ) ; // if setter is null, the property is not full access (read&write), therefore ignored  try { if ( setter != null ) { CtClass [ ] sparams = setter . getParameterTypes ( ) ; if ( sparams . length == 1 && sparams [ 0 ] . equals ( getter . getReturnType ( ) ) ) { properties . add ( property ) ; } } } catch ( NotFoundException e ) { logger . warn ( e ) ; } } return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the String allowing one to create an Object ( Integer Boolean Byte ... ) from a primitive type given in parameter . [CODESPLIT] public static String getObjectFromPrimitiveType ( String argumentType , String argument ) { if ( argumentType . equals ( \"int\" ) ) return \"new Integer(\" + argument + \")\" ; if ( argumentType . equals ( \"boolean\" ) ) return \"new Boolean(\" + argument + \")\" ; if ( argumentType . equals ( \"byte\" ) ) return \"new Byte(\" + argument + \")\" ; if ( argumentType . equals ( \"char\" ) ) return \"new Character(\" + argument + \")\" ; if ( argumentType . equals ( \"double\" ) ) return \"new Double(\" + argument + \")\" ; if ( argumentType . equals ( \"float\" ) ) return \"new Float(\" + argument + \")\" ; if ( argumentType . equals ( \"long\" ) ) return \"new Long(\" + argument + \")\" ; if ( argumentType . equals ( \"short\" ) ) return \"new Short(\" + argument + \")\" ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the String allowing one to create an Object ( Integer Boolean Byte ... ) from a primitive type given in parameter . [CODESPLIT] public static String getClassFromPrimitiveType ( String argumentType ) { if ( argumentType . equals ( \"int\" ) ) return \"java.lang.Integer\" ; if ( argumentType . equals ( \"boolean\" ) ) return \"java.lang.Boolean\" ; if ( argumentType . equals ( \"byte\" ) ) return \"java.lang.Byte\" ; if ( argumentType . equals ( \"char\" ) ) return \"java.lang.Character\" ; if ( argumentType . equals ( \"double\" ) ) return \"java.lang.Double\" ; if ( argumentType . equals ( \"float\" ) ) return \"java.lang.Float\" ; if ( argumentType . equals ( \"long\" ) ) return \"java.lang.Long\" ; if ( argumentType . equals ( \"short\" ) ) return \"java.lang.Short\" ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the String allowing one to create a primitive type ( Integer Boolean Byte ... ) from a primitive type given in parameter . [CODESPLIT] public static String getPrimitiveTypeFromObject ( String argumentType , String argument ) { if ( argumentType . equals ( \"int\" ) ) return \"((Integer)\" + argument + \").intValue()\" ; if ( argumentType . equals ( \"boolean\" ) ) return \"((Boolean)\" + argument + \").booleanValue()\" ; if ( argumentType . equals ( \"byte\" ) ) return \"((Byte)\" + argument + \").byteValue()\" ; if ( argumentType . equals ( \"char\" ) ) return \"((Character)\" + argument + \").charValue()\" ; if ( argumentType . equals ( \"double\" ) ) return \"((Double)\" + argument + \").doubleValue()\" ; if ( argumentType . equals ( \"float\" ) ) return \"((Float)\" + argument + \").floatValue()\" ; if ( argumentType . equals ( \"long\" ) ) return \"((Long)\" + argument + \").longValue()\" ; if ( argumentType . equals ( \"short\" ) ) return \"((Short)\" + argument + \").shortValue()\" ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all abstract methods from a class [CODESPLIT] public static Map getAbstractMethodsFromClass ( CtClass sbbAbstractClass ) { HashMap abstractMethods = new HashMap ( ) ; CtMethod [ ] methods = sbbAbstractClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { if ( Modifier . isAbstract ( methods [ i ] . getModifiers ( ) ) ) { abstractMethods . put ( methods [ i ] . getName ( ) , methods [ i ] ) ; } } return abstractMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all concrete ( non - abstract and non - native ) methods from a class Stored under key Name + signature [CODESPLIT] public static Map getConcreteMethodsFromClass ( CtClass sbbClass ) { HashMap concreteMethods = new HashMap ( ) ; CtMethod [ ] methods = sbbClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { int mods = methods [ i ] . getModifiers ( ) ; if ( ! Modifier . isAbstract ( mods ) && ! Modifier . isNative ( mods ) ) { concreteMethods . put ( getMethodKey ( methods [ i ] ) , methods [ i ] ) ; } } return concreteMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all concrete ( non - abstract and non - native ) methods names from a class [CODESPLIT] public static Set getConcreteMethodsNamesFromClass ( CtClass sbbClass ) { Set concreteMethods = new HashSet ( ) ; CtMethod [ ] methods = sbbClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { int mods = methods [ i ] . getModifiers ( ) ; if ( ! Modifier . isAbstract ( mods ) && ! Modifier . isNative ( mods ) ) { concreteMethods . add ( methods [ i ] . getName ( ) ) ; } } return concreteMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all methods of the interfaces implemented / extended by the specified { [CODESPLIT] public static Map getSuperClassesAbstractMethodsFromInterface ( CtClass sbbAbstractClass ) { HashMap abstractMethods = new HashMap ( ) ; CtMethod [ ] methods = null ; ArrayList < CtClass > superClasses = new ArrayList < CtClass > ( ) ; superClasses . add ( sbbAbstractClass ) ; ArrayList < CtClass > superClassesProcessed = new ArrayList < CtClass > ( ) ; try { while ( ! superClasses . isEmpty ( ) ) { // remove head CtClass ctClass = superClasses . remove ( 0 ) ; superClassesProcessed . add ( ctClass ) ; // get its methods methods = ctClass . getDeclaredMethods ( ) ; for ( CtMethod ctMethod : methods ) { abstractMethods . put ( getMethodKey ( ctMethod ) , ctMethod ) ; } // get super interfaces for ( CtClass anotherCtClass : ctClass . getInterfaces ( ) ) { if ( ! superClassesProcessed . contains ( anotherCtClass ) ) { superClasses . add ( anotherCtClass ) ; } } try { ctClass . detach ( ) ; } catch ( Exception e ) { // ignore } } } catch ( NotFoundException e ) { logger . error ( e ) ; } return abstractMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all methods from an interface including super interfaces except the ones specified in the provided map [CODESPLIT] public static Map getInterfaceMethodsFromInterface ( CtClass interfaceClass , Map exceptMethods ) { HashMap interfaceMethods = new HashMap ( ) ; CtMethod [ ] methods = interfaceClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { if ( exceptMethods . get ( methods [ i ] . getName ( ) ) == null ) { ConcreteClassGeneratorUtils . logger . trace ( methods [ i ] . getName ( ) ) ; interfaceMethods . put ( getMethodKey ( methods [ i ] ) , methods [ i ] ) ; } } Map temp = getSuperClassesAbstractMethodsFromInterface ( interfaceClass ) ; for ( Iterator i = temp . keySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { String key = ( String ) i . next ( ) ; if ( ! exceptMethods . containsKey ( key ) ) { interfaceMethods . put ( key , temp . get ( key ) ) ; } } return interfaceMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object pool for the specified profile table . If a transaction manager is used then and if the tx rollbacks the pool will be removed . [CODESPLIT] public void createObjectPool ( final ProfileTableImpl profileTable , final SleeTransactionManager sleeTransactionManager ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Creating Pool for \" + profileTable ) ; } createObjectPool ( profileTable ) ; if ( sleeTransactionManager != null ) { // add a rollback action to remove sbb object pool TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Due to tx rollback, removing pool for \" + profileTable ) ; } try { removeObjectPool ( profileTable ) ; } catch ( Throwable e ) { logger . error ( \"Failed to remove table's \" + profileTable + \" object pool\" , e ) ; } } } ; sleeTransactionManager . getTransactionContext ( ) . getAfterRollbackActions ( ) . add ( action ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the object pool for the specified profile table . If a transaction manager is used then the removal is only after the tx commit . [CODESPLIT] public void removeObjectPool ( final ProfileTableImpl profileTable , final SleeTransactionManager sleeTransactionManager ) { TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Removing Pool for \" + profileTable ) ; } removeObjectPool ( profileTable ) ; } } ; if ( sleeTransactionManager != null ) { sleeTransactionManager . getTransactionContext ( ) . getAfterCommitActions ( ) . add ( action ) ; } else { action . execute ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the pool for the specified ids [CODESPLIT] private void removeObjectPool ( final ProfileTableImpl profileTable ) { final ProfileObjectPool objectPool = pools . remove ( profileTable . getProfileTableName ( ) ) ; if ( objectPool != null ) { try { objectPool . close ( ) ; } catch ( Exception e ) { logger . error ( \"failed to close pool\" , e ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Removed Pool for \" + profileTable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---- MBEAN METHODS [CODESPLIT] public void register ( ) { MBeanServer mBeanServer = sleeContainer . getMBeanServer ( ) ; try { mBeanServer . registerMBean ( this , new ObjectName ( MBEAN_NAME ) ) ; } catch ( Exception e ) { logger . error ( \"Failed to register\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private class DataRemovaClusterListener implements DataRemovalListener { [CODESPLIT] @ CacheEntryRemoved public void onNodeRemovedEvent ( CacheEntryRemovedEvent event ) { if ( ! event . isOriginLocal ( ) && ! event . isPre ( ) ) { // remote node removal Fqn fqn = ( ( NodeKey ) event . getKey ( ) ) . getFqn ( ) ; if ( fqn != null ) { if ( doInfoLogs ) { logger . info ( \"onNodeRemovedEvent( fqn = \" + fqn + \", size = \" + fqn . size ( ) + \" )\" ) ; } if ( fqn . get ( 0 ) . equals ( SbbEntityFactoryCacheData . SBB_ENTITY_FACTORY_FQN_NAME ) ) { // is child of sbb entity factory cache data, i.e., /sbbe int fqnSize = fqn . size ( ) ; if ( fqnSize < 3 ) { return ; } SbbEntityID sbbEntityID = null ; if ( fqnSize == 3 ) { // /sbbe/serviceid/convergenceName root sbb entity ServiceID serviceID = ( ServiceID ) fqn . get ( 1 ) ; String convergenceName = ( String ) fqn . get ( 2 ) ; sbbEntityID = new RootSbbEntityID ( serviceID , convergenceName ) ; if ( doInfoLogs ) { logger . info ( \"Root sbb entity \" + sbbEntityID + \" was remotely removed, ensuring there is no local lock\" ) ; } } else { // must end as /chd/chdRelationName/childId if ( ! fqn . get ( fqnSize - 3 ) . equals ( SbbEntityCacheData . CHILD_RELATIONs_CHILD_NODE_NAME ) ) { return ; } // let get the party started and rebuild the sbb entity id! ServiceID serviceID = ( ServiceID ) fqn . get ( 1 ) ; String convergenceName = ( String ) fqn . get ( 2 ) ; sbbEntityID = new RootSbbEntityID ( serviceID , convergenceName ) ; int i = 3 ; while ( fqnSize >= i + 3 ) { // fqn get(i) is chd, skip String childRelationName = ( String ) fqn . get ( i + 1 ) ; String childId = ( String ) fqn . get ( i + 2 ) ; sbbEntityID = new NonRootSbbEntityID ( sbbEntityID , childRelationName , childId ) ; i += 3 ; } if ( doInfoLogs ) { logger . info ( \"Non root sbb entity \" + sbbEntityID + \" was remotely removed, ensuring there is no local lock\" ) ; } } if ( locks . remove ( sbbEntityID ) != null ) { if ( doInfoLogs ) { logger . info ( \"Remotely removed lock for \" + sbbEntityID ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void undeployed ( ) { super . undeployed ( ) ; usageNotificationManagerMBeanConcreteInterface = null ; usageNotificationManagerMBeanImplConcreteClass = null ; usageParametersConcreteClass = null ; usageParametersInterface = null ; usageParametersMBeanConcreteInterface = null ; usageParametersMBeanImplConcreteClass = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected void populateModel ( ModelNode operation , ModelNode model ) throws OperationFailedException { log . info ( \"Populating the model\" ) ; //model.setEmptyObject(); for ( AttributeDefinition ad : SleeSubsystemDefinition . ATTRIBUTES ) { ad . validateAndSet ( operation , model ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void performBoottime ( OperationContext context , ModelNode operation , ModelNode model , ServiceVerificationHandler verificationHandler , List < ServiceController < ? > > newControllers ) throws OperationFailedException { // Add deployment processors here // Remove this if you don't need to hook into the deployers, or you can add as many as you like // see SubDeploymentProcessor for explanation of the phases context . addStep ( new AbstractDeploymentChainStep ( ) { public void execute ( DeploymentProcessorTarget processorTarget ) { processorTarget . addDeploymentProcessor ( SleeExtension . SUBSYSTEM_NAME , SleeDeploymentParseProcessor . PHASE , SleeDeploymentParseProcessor . PRIORITY , new SleeDeploymentParseProcessor ( ) ) ; processorTarget . addDeploymentProcessor ( SleeExtension . SUBSYSTEM_NAME , SleeDeploymentInstallProcessor . PHASE , SleeDeploymentInstallProcessor . PRIORITY , new SleeDeploymentInstallProcessor ( ) ) ; } } , OperationContext . Stage . RUNTIME ) ; ModelNode fullModel = Resource . Tools . readModel ( context . readResource ( PathAddress . EMPTY_ADDRESS ) ) ; final ModelNode cacheConfigModel = SleeSubsystemDefinition . CACHE_CONFIG . resolveModelAttribute ( context , model ) ; final String cacheConfig = cacheConfigModel . isDefined ( ) ? cacheConfigModel . asString ( ) : null ; // Installs the msc service which builds the SleeContainer instance and its modules final ServiceTarget target = context . getServiceTarget ( ) ; final SleeContainerService sleeContainerService = new SleeContainerService ( fullModel , cacheConfig ) ; String dbConfigMBean = getPropertyString ( fullModel , \"ProfileManagement\" , \"dbConfigMBean\" , \"H2DBConfig\" ) ; String datasourceServiceName = getPropertyString ( fullModel , dbConfigMBean , \"datasourceServiceName\" , \"ExampleDS\" ) ; final ServiceBuilder < ? > sleeContainerServiceBuilder = target . addService ( SleeServiceNames . SLEE_CONTAINER , sleeContainerService ) . addDependency ( PathManagerService . SERVICE_NAME , PathManager . class , sleeContainerService . getPathManagerInjector ( ) ) . addDependency ( MBeanServerService . SERVICE_NAME , MBeanServer . class , sleeContainerService . getMbeanServer ( ) ) . addDependency ( TransactionManagerService . SERVICE_NAME , TransactionManager . class , sleeContainerService . getTransactionManager ( ) ) . addDependency ( DataSourceReferenceFactoryService . SERVICE_NAME_BASE . append ( datasourceServiceName ) , ManagedReferenceFactory . class , sleeContainerService . getManagedReferenceFactory ( ) ) ; newControllers . add ( sleeContainerServiceBuilder . setInitialMode ( Mode . ACTIVE ) . install ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the specified notification should be delivered to notification listeners using this notification filter . [CODESPLIT] public boolean isNotificationEnabled ( Notification notification ) { if ( ! ( notification instanceof UsageNotification ) ) return false ; UsageNotification usageNotification = ( UsageNotification ) notification ; if ( service != null ) { // SLEE 1.0 comparison return service . equals ( usageNotification . getService ( ) ) && sbb . equals ( usageNotification . getSbb ( ) ) && paramName . equals ( usageNotification . getUsageParameterName ( ) ) && ( usageNotification . getValue ( ) < lowValue || usageNotification . getValue ( ) > highValue ) ; } else { // SLEE 1.1 comparison return notificationSource . equals ( usageNotification . getNotificationSource ( ) ) && paramName . equals ( usageNotification . getUsageParameterName ( ) ) && ( usageNotification . getValue ( ) < lowValue || usageNotification . getValue ( ) > highValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AddressPresentation< / code > object from an integer value . [CODESPLIT] public static AddressPresentation fromInt ( int value ) throws IllegalArgumentException { switch ( value ) { case ADDRESS_PRESENTATION_UNDEFINED : return UNDEFINED ; case ADDRESS_PRESENTATION_ALLOWED : return ALLOWED ; case ADDRESS_PRESENTATION_RESTRICTED : return RESTRICTED ; case ADDRESS_PRESENTATION_ADDRESS_NOT_AVAILABLE : return ADDRESS_NOT_AVAILABLE ; default : throw new IllegalArgumentException ( \"Invalid value: \" + value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AddressPresentation< / code > object from a string value . [CODESPLIT] public static AddressPresentation fromString ( String value ) throws NullPointerException , IllegalArgumentException { if ( value == null ) throw new NullPointerException ( \"value is null\" ) ; if ( value . equalsIgnoreCase ( UNDEFINED_STRING ) ) return UNDEFINED ; if ( value . equalsIgnoreCase ( ALLOWED_STRING ) ) return ALLOWED ; if ( value . equalsIgnoreCase ( RESTRICTED_STRING ) ) return RESTRICTED ; if ( value . equalsIgnoreCase ( ADDRESS_NOT_AVAILABLE_STRING ) ) return ADDRESS_NOT_AVAILABLE ; throw new IllegalArgumentException ( \"Invalid value: \" + value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean clearAlarm ( String alarmID ) throws NullPointerException , ManagementException { if ( alarmID == null ) { throw new NullPointerException ( \"AlarmID must not be null\" ) ; } AlarmPlaceHolder aph = alarmIdToAlarm . remove ( alarmID ) ; placeHolderToNotificationSource . remove ( aph ) ; if ( aph == null ) { return false ; } else { // we clear?\r try { generateNotification ( aph , true ) ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to clear alarm due to: \" + e ) ; } return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int clearAlarms ( NotificationSource notificationSource ) throws NullPointerException , UnrecognizedNotificationSourceException , ManagementException { if ( notificationSource == null ) { throw new NullPointerException ( \"NotificationSource must not be null\" ) ; } mandateSource ( notificationSource ) ; int count = 0 ; try { for ( Map . Entry < AlarmPlaceHolder , NotificationSource > e : placeHolderToNotificationSource . entrySet ( ) ) { if ( e . getValue ( ) . equals ( notificationSource ) ) { if ( clearAlarm ( e . getKey ( ) . getAlarm ( ) . getAlarmID ( ) ) ) { count ++ ; } } } } catch ( Exception e ) { throw new ManagementException ( \"Failed to get alarm id list due to: \" , e ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String [ ] getAlarms ( ) throws ManagementException { try { Set < String > ids = new HashSet < String > ( ) ; ids . addAll ( alarmIdToAlarm . keySet ( ) ) ; return ids . toArray ( new String [ ids . size ( ) ] ) ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to get list of active alarms due to.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String [ ] getAlarms ( NotificationSource notificationSource ) throws NullPointerException , UnrecognizedNotificationSourceException , ManagementException { if ( notificationSource == null ) { throw new NullPointerException ( \"NotificationSource must not be null\" ) ; } mandateSource ( notificationSource ) ; try { Set < String > ids = new HashSet < String > ( ) ; for ( Map . Entry < AlarmPlaceHolder , NotificationSource > e : placeHolderToNotificationSource . entrySet ( ) ) { if ( e . getValue ( ) . equals ( notificationSource ) ) { ids . add ( e . getKey ( ) . getAlarm ( ) . getAlarmID ( ) ) ; } } return ids . toArray ( new String [ ids . size ( ) ] ) ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to get alarm id list due to: \" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Alarm getDescriptor ( String alarmID ) throws NullPointerException , ManagementException { if ( alarmID == null ) { throw new NullPointerException ( \"AlarmID must not be null\" ) ; } AlarmPlaceHolder aph = this . alarmIdToAlarm . get ( alarmID ) ; if ( aph == null ) return null ; return aph . getAlarm ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Alarm [ ] getDescriptors ( String [ ] alarmIDs ) throws NullPointerException , ManagementException { if ( alarmIDs == null ) { throw new NullPointerException ( \"AlarmID[] must not be null\" ) ; } Set < Alarm > alarms = new HashSet < Alarm > ( ) ; try { for ( String id : alarmIDs ) { Alarm a = getDescriptor ( id ) ; if ( a != null ) alarms . add ( a ) ; } return alarms . toArray ( new Alarm [ alarms . size ( ) ] ) ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to get desciptors.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "NON MBEAN - used only internal those methods are not exposed via jmx [CODESPLIT] public boolean isSourceOwnerOfAlarm ( NotificationSourceWrapper notificationSource , String alarmID ) { AlarmPlaceHolder aph = this . alarmIdToAlarm . get ( alarmID ) ; if ( aph == null ) return false ; return aph . getNotificationSource ( ) . getNotificationSource ( ) . equals ( notificationSource . getNotificationSource ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "THis methods raises alarm . It MUST not receive AlarmLevel . CLEAR it has to be filtered . [CODESPLIT] public String raiseAlarm ( NotificationSourceWrapper notificationSource , String alarmType , String instanceID , AlarmLevel level , String message , Throwable cause ) { synchronized ( notificationSource ) { if ( isAlarmAlive ( notificationSource , alarmType , instanceID ) ) { // Alarm a = this.placeHolderToAlarm.get(new\r // AlarmPlaceHolder(notificationSource, alarmType, instanceID));\r Alarm a = null ; // unconveniant....\r try { AlarmPlaceHolder localAPH = new AlarmPlaceHolder ( notificationSource , alarmType , instanceID ) ; for ( Map . Entry < String , AlarmPlaceHolder > e : this . alarmIdToAlarm . entrySet ( ) ) { if ( e . getValue ( ) . equals ( localAPH ) ) { a = e . getValue ( ) . getAlarm ( ) ; break ; } } } catch ( Exception e ) { // ignore\r } if ( a != null ) { return a . getAlarmID ( ) ; } else { return this . raiseAlarm ( notificationSource , alarmType , instanceID , level , message , cause ) ; } } else { Alarm a = new Alarm ( UUID . randomUUID ( ) . toString ( ) , notificationSource . getNotificationSource ( ) , alarmType , instanceID , level , message , cause , System . currentTimeMillis ( ) ) ; AlarmPlaceHolder aph = new AlarmPlaceHolder ( notificationSource , alarmType , instanceID , a ) ; this . alarmIdToAlarm . put ( a . getAlarmID ( ) , aph ) ; // this.placeHolderToAlarm.put(aph, a);\r this . placeHolderToNotificationSource . put ( aph , aph . getNotificationSource ( ) . getNotificationSource ( ) ) ; generateNotification ( aph , false ) ; return a . getAlarmID ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Usage methods . Here we can be static for sure . Rest must be tested . [CODESPLIT] public static Object getUsageParameterSet ( ProfileObjectImpl profileObject , String name ) throws UnrecognizedUsageParameterSetNameException { if ( logger . isDebugEnabled ( ) ) { logger . info ( \"[getUsageParameterSet(\" + name + \")] @ \" + profileObject ) ; } if ( name == null ) { throw new NullPointerException ( \"UsageParameterSet name must not be null.\" ) ; } ProfileTableImpl profileTable = profileObject . getProfileTable ( ) ; Object result = profileTable . getProfileTableUsageMBean ( ) . getInstalledUsageParameterSet ( name ) ; if ( result == null ) { throw new UnrecognizedUsageParameterSetNameException ( ) ; } else { return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { this . activityHandle = new NullActivityHandleImpl ( in . readUTF ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { out . writeUTF ( ( ( NullActivityHandleImpl ) activityHandle ) . getId ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JAIN SLEE specs event type descriptor [CODESPLIT] public javax . slee . management . EventTypeDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { specsDescriptor = new javax . slee . management . EventTypeDescriptor ( getEventTypeID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) , getDescriptor ( ) . getEventClassName ( ) ) ; } return specsDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals that the specified { [CODESPLIT] public void activatedServiceWhichDefineEventAsInitial ( ServiceComponent serviceComponent ) { // create new ordered set\r SortedSet < ServiceComponent > activeServicesWhichDefineEventAsInitial = new TreeSet < ServiceComponent > ( new ActiveServicesWhichDefineEventAsInitialComparator ( ) ) ; // add all existent active services, except old version, this allows smooth service upgrade\r ServiceID oldVersion = serviceComponent . getOldVersion ( ) ; if ( oldVersion == null ) { activeServicesWhichDefineEventAsInitial . addAll ( this . activeServicesWhichDefineEventAsInitial ) ; } else { for ( ServiceComponent existentServiceComponent : this . activeServicesWhichDefineEventAsInitial ) { if ( ! existentServiceComponent . getServiceID ( ) . equals ( oldVersion ) ) { activeServicesWhichDefineEventAsInitial . add ( existentServiceComponent ) ; } } } // add new service\r activeServicesWhichDefineEventAsInitial . add ( serviceComponent ) ; // replace old set\r this . activeServicesWhichDefineEventAsInitial = activeServicesWhichDefineEventAsInitial ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals that the specified { [CODESPLIT] public void deactivatedServiceWhichDefineEventAsInitial ( ServiceComponent serviceComponent ) { // create new ordered set\r SortedSet < ServiceComponent > activeServicesWhichDefineEventAsInitial = new TreeSet < ServiceComponent > ( new ActiveServicesWhichDefineEventAsInitialComparator ( ) ) ; // add all existent active services, except one deactivated\r for ( ServiceComponent existentServiceComponent : this . activeServicesWhichDefineEventAsInitial ) { if ( ! existentServiceComponent . equals ( serviceComponent ) ) { activeServicesWhichDefineEventAsInitial . add ( existentServiceComponent ) ; } } // replace old set\r this . activeServicesWhichDefineEventAsInitial = activeServicesWhichDefineEventAsInitial ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for deciding whether or not to accept the file . [CODESPLIT] public boolean accepts ( URL deployableUnitURL , String deployableUnitName ) { DeployableUnitWrapper du = new DeployableUnitWrapper ( deployableUnitURL , deployableUnitName ) ; URL url = du . getUrl ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Method accepts called for \" + url + \" [DU: \" + deployableUnitName + \"]\" ) ; } try { String fullPath = url . getFile ( ) ; String fileName = fullPath . substring ( fullPath . lastIndexOf ( ' ' ) + 1 , fullPath . length ( ) ) ; // Is it in the toAccept list ? Direct accept. if ( toAccept . containsKey ( fileName ) ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Accepting \" + url . toString ( ) + \".\" ) ; } return true ; } // If not it the accept list but it's a jar might be a DU jar... else if ( fileName . endsWith ( \".jar\" ) ) { JarFile duJarFile = null ; try { // Try to obtain the DU descriptor, if we got it, we're // accepting it! if ( du . getEntry ( \"META-INF/deployable-unit.xml\" ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Accepting \" + url . toString ( ) + \".\" ) ; } return true ; } } finally { // Clean up! if ( duJarFile != null ) { try { duJarFile . close ( ) ; } catch ( IOException ignore ) { } finally { duJarFile = null ; } } } } } catch ( Exception ignore ) { // Ignore.. will reject. } // Uh-oh.. looks like it will stay outside. return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializer method for accepted files . Will parse descriptors at this point . [CODESPLIT] public void init ( URL deployableUnitURL , String deployableUnitName ) throws DeploymentException { URL url = deployableUnitURL ; DeployableUnitWrapper du = new DeployableUnitWrapper ( deployableUnitURL , deployableUnitName ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Method init called for \" + deployableUnitURL + \" [DU: \" + deployableUnitName + \"]\" ) ; } // Get the full path and filename for this du String fullPath = du . getFullPath ( ) ; String fileName = du . getFileName ( ) ; try { DeployableUnitWrapper duWrapper = null ; // If we're able to remove it from toAccept was because it was // there! if ( ( duWrapper = toAccept . remove ( fileName ) ) != null ) { // Create a new Deployable Component from this DI. DeployableComponent dc = new DeployableComponent ( du , url , fileName , sleeContainerDeployer ) ; // Also get the deployable unit for this (it exists, we've // checked!) DeployableUnit deployerDU = deployableUnits . get ( duWrapper . getFileName ( ) ) ; for ( DeployableComponent subDC : dc . getSubComponents ( ) ) { // Add the sub-component to the DU object. deployerDU . addComponent ( subDC ) ; } } // If the DU for this component doesn't exists.. it's a new DU! else if ( fileName . endsWith ( \".jar\" ) ) { JarFile duJarFile = null ; try { // Get a reference to the DU jar file duJarFile = new JarFile ( fullPath ) ; // Try to get the Deployable Unit descriptor JarEntry duXmlEntry = duJarFile . getJarEntry ( \"META-INF/deployable-unit.xml\" ) ; // Got descriptor? if ( duXmlEntry != null ) { // Create a new Deployable Unit object. DeployableUnit deployerDU = new DeployableUnit ( du , sleeContainerDeployer ) ; // Let's parse the descriptor to see what we've got... DeployableUnitDescriptorFactory dudf = sleeContainerDeployer . getSleeContainer ( ) . getComponentManagement ( ) . getDeployableUnitManagement ( ) . getDeployableUnitDescriptorFactory ( ) ; DeployableUnitDescriptor duDesc = dudf . parse ( duJarFile . getInputStream ( duXmlEntry ) ) ; // If the filename is present, an undeploy in on the way... let's wait while ( deployableUnits . containsKey ( fileName ) ) { Thread . sleep ( getWaitTimeBetweenOperations ( ) ) ; } // Add it to the deployable units map. deployableUnits . put ( fileName , deployerDU ) ; // Go through each jar entry in the DU descriptor for ( String componentJarName : duDesc . getJarEntries ( ) ) { // Might have path... strip it! int beginIndex ; if ( ( beginIndex = componentJarName . lastIndexOf ( ' ' ) ) == - 1 ) beginIndex = componentJarName . lastIndexOf ( ' ' ) ; beginIndex ++ ; // Got a clean jar name, no paths. componentJarName = componentJarName . substring ( beginIndex , componentJarName . length ( ) ) ; // Put it in the accept list. toAccept . put ( componentJarName , du ) ; } // Do the same as above... but for services for ( String serviceXMLName : duDesc . getServiceEntries ( ) ) { // Might have path... strip it! int beginIndex ; if ( ( beginIndex = serviceXMLName . lastIndexOf ( ' ' ) ) == - 1 ) beginIndex = serviceXMLName . lastIndexOf ( ' ' ) ; beginIndex ++ ; // Got a clean XML filename serviceXMLName = serviceXMLName . substring ( beginIndex , serviceXMLName . length ( ) ) ; // Add it to the accept list. toAccept . put ( serviceXMLName , du ) ; } } } finally { // Clean up! if ( duJarFile != null ) { try { duJarFile . close ( ) ; } catch ( IOException ignore ) { } finally { duJarFile = null ; } } } } } catch ( Exception e ) { // Something went wrong... logger . error ( \"Deployment of \" + fileName + \" failed. \" , e ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is where the fun begins . Time to deploy! [CODESPLIT] public void start ( URL deployableUnitURL , String deployableUnitName ) throws DeploymentException { DeployableUnitWrapper du = new DeployableUnitWrapper ( deployableUnitURL , deployableUnitName ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Method start called for \" + du . getUrl ( ) + \" [DU: \" + deployableUnitName + \"]\" ) ; } try { // Get the deployable unit object DeployableUnit realDU = deployableUnits . get ( du . getFileName ( ) ) ; // If it exists, install it. if ( realDU != null ) { while ( isInUndeployList ( du . getFileName ( ) ) ) { Thread . sleep ( getWaitTimeBetweenOperations ( ) ) ; } sleeContainerDeployer . getDeploymentManager ( ) . installDeployableUnit ( realDU ) ; } } catch ( Exception e ) { logger . error ( \"\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fun has ended . Time to undeploy . [CODESPLIT] public void stop ( URL deployableUnitURL , String deployableUnitName ) throws DeploymentException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"stop( deployableUnitURL = : \" + deployableUnitURL + \" )\" ) ; } DeployableUnitWrapper du = new DeployableUnitWrapper ( deployableUnitURL , deployableUnitName ) ; DeployableUnit realDU = null ; String fileName = du . getFileName ( ) ; if ( ( realDU = deployableUnits . get ( du . getFileName ( ) ) ) != null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Got DU: \" + realDU . getDeploymentInfoShortName ( ) ) ; } if ( ! isInUndeployList ( fileName ) ) { addToUndeployList ( fileName ) ; } try { // Uninstall it sleeContainerDeployer . getDeploymentManager ( ) . uninstallDeployableUnit ( realDU ) ; // Remove it from list if successful deployableUnits . remove ( fileName ) ; removeFromUndeployList ( fileName ) ; } catch ( DependencyException e ) { // ignore, will be tried again once there is another undeployment } catch ( Exception e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof InvalidStateException ) { logger . warn ( cause . getLocalizedMessage ( ) + \"... WAITING ...\" ) ; } else if ( e instanceof DeploymentException ) { throw new IllegalStateException ( e . getLocalizedMessage ( ) , e ) ; } else { logger . error ( e . getMessage ( ) , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MBean operation for getting Deployer status . [CODESPLIT] public String showStatus ( ) throws DeploymentException { String output = \"\" ; output += \"<p>Deployable Units List:</p>\" ; for ( String key : deployableUnits . keySet ( ) ) { output += \"&lt;\" + key + \"&gt; [\" + deployableUnits . get ( key ) + \"]<br>\" ; for ( String duComponent : deployableUnits . get ( key ) . getComponents ( ) ) { output += \"+-- \" + duComponent + \"<br>\" ; } } output += \"<p>To Accept List:</p>\" ; for ( String key : toAccept . keySet ( ) ) { output += \"&lt;\" + key + \"&gt; [\" + toAccept . get ( key ) + \"]<br>\" ; } output += \"<p>Undeployments running:</p>\" ; for ( String undeploy : undeploys ) { output += \"+-- \" + undeploy + \"<br>\" ; } output += \"<p>Deployment Manager Status</p>\" ; output += sleeContainerDeployer . getDeploymentManager ( ) . showStatus ( ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------ [CODESPLIT] private boolean addToUndeployList ( String du ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Adding \" + du + \" to running undeployments list ...\" ) ; logger . trace ( \"Current Undeploy List: \" + undeploys . toString ( ) ) ; } boolean added = undeploys . add ( du ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Added  \" + du + \" to running undeployments list = \" + added ) ; logger . trace ( \"Current Undeploy List: \" + undeploys . toString ( ) ) ; } return added ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void mandateTransaction ( ) throws TransactionRequiredLocalException { try { final Transaction tx = getTransaction ( ) ; if ( tx == null ) throw new TransactionRequiredLocalException ( \"Transaction Mandatory\" ) ; final int status = tx . getStatus ( ) ; if ( status != Status . STATUS_ACTIVE && status != Status . STATUS_MARKED_ROLLBACK ) { throw new IllegalStateException ( \"There is no active tx, tx is in state: \" + status ) ; } } catch ( SystemException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean requireTransaction ( ) { try { final Transaction tx = getTransaction ( ) ; if ( tx == null ) { begin ( ) ; return true ; } else { final int status = tx . getStatus ( ) ; if ( status != Status . STATUS_ACTIVE && status != Status . STATUS_MARKED_ROLLBACK ) { begin ( ) ; return true ; } } } catch ( NotSupportedException e ) { logger . error ( \"Exception creating transaction\" , e ) ; } catch ( SystemException e ) { logger . error ( \"Caught SystemException in checking transaction\" , e ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void requireTransactionEnd ( boolean terminateTx , boolean doRollback ) throws IllegalStateException , SecurityException , SystemException , RollbackException , HeuristicMixedException , HeuristicRollbackException { if ( terminateTx ) { if ( doRollback ) { rollback ( ) ; } else { commit ( ) ; } } else { if ( doRollback ) { setRollbackOnly ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void asyncCommit ( CommitListener commitListener ) throws IllegalStateException , SecurityException { if ( doTraceLogs ) { logger . trace ( \"asyncCommit( commitListener = \" + commitListener + \" )\" ) ; } try { final SleeTransaction sleeTransaction = getSleeTransaction ( ) ; if ( sleeTransaction == null ) { throw new IllegalStateException ( \"no transaction\" ) ; } else { sleeTransaction . asyncCommit ( commitListener ) ; } } catch ( SystemException e ) { if ( commitListener != null ) { commitListener . systemException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void asyncRollback ( RollbackListener rollbackListener ) throws IllegalStateException , SecurityException { if ( doTraceLogs ) { logger . trace ( \"asyncRollback( rollbackListener = \" + rollbackListener + \" )\" ) ; } try { final SleeTransaction sleeTransaction = getSleeTransaction ( ) ; if ( sleeTransaction == null ) { throw new IllegalStateException ( \"no transaction\" ) ; } else { sleeTransaction . asyncRollback ( rollbackListener ) ; } } catch ( SystemException e ) { if ( rollbackListener != null ) { rollbackListener . systemException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SleeTransaction beginSleeTransaction ( ) throws NotSupportedException , SystemException { // begin transaction transactionManager . begin ( ) ; // get tx does the rest return getAsSleeTransaction ( transactionManager . getTransaction ( ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SleeTransaction asSleeTransaction ( Transaction transaction ) throws NullPointerException , IllegalArgumentException , SystemException { if ( transaction == null ) { throw new NullPointerException ( \"null transaction\" ) ; } if ( transaction . getClass ( ) == SleeTransactionImpl . class ) { return ( SleeTransaction ) transaction ; } if ( transaction instanceof TransactionImple ) { return new SleeTransactionImpl ( ( TransactionImple ) transaction , getTransactionContext ( ) , this ) ; } throw new IllegalArgumentException ( \"unexpected transaction class type \" + transaction . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void commit ( ) throws RollbackException , HeuristicMixedException , HeuristicRollbackException , SecurityException , IllegalStateException , SystemException { if ( doTraceLogs ) { logger . trace ( \"Starting commit of tx \" + transactionManager . getTransaction ( ) ) ; } transactionManager . commit ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void resume ( Transaction transaction ) throws InvalidTransactionException , IllegalStateException , SystemException { if ( transaction . getClass ( ) == SleeTransactionImpl . class ) { final SleeTransactionImpl sleeTransactionImpl = ( SleeTransactionImpl ) transaction ; if ( doTraceLogs ) { logger . trace ( \"Resuming tx \" + sleeTransactionImpl . getWrappedTransaction ( ) ) ; } // resume wrapped tx transactionManager . resume ( sleeTransactionImpl . getWrappedTransaction ( ) ) ; // store tx context in thread  TransactionContextThreadLocal . setTransactionContext ( sleeTransactionImpl . getTransactionContext ( ) ) ; } else { throw new InvalidTransactionException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void rollback ( ) throws IllegalStateException , SecurityException , SystemException { if ( doTraceLogs ) { logger . trace ( \"Starting rollback of tx \" + transactionManager . getTransaction ( ) ) ; } transactionManager . rollback ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setRollbackOnly ( ) throws IllegalStateException , SystemException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Marking tx \" + transactionManager . getTransaction ( ) + \" for rollback.\" ) ; } transactionManager . setRollbackOnly ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Transaction suspend ( ) throws SystemException { if ( doTraceLogs ) { logger . trace ( \"Suspending tx \" + transactionManager . getTransaction ( ) ) ; } final Transaction tx = getAsSleeTransaction ( transactionManager . suspend ( ) , false ) ; if ( tx != null ) { // remove tx context from thread TransactionContextThreadLocal . setTransactionContext ( null ) ; return tx ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public TransactionContext getTransactionContext ( ) { TransactionContext txContext = TransactionContextThreadLocal . getTransactionContext ( ) ; if ( txContext == null ) { try { final Transaction tx = transactionManager . getTransaction ( ) ; if ( tx != null && tx . getStatus ( ) == Status . STATUS_ACTIVE ) { // a tx was started with the real tx manager, lets try to hook the sync handler and a new tx context txContext = bindToTransaction ( tx ) ; } } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } return txContext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes actions scheduled after commit succeeds [CODESPLIT] protected void executeAfterCommitActions ( ) { if ( afterCommitActions != null ) { if ( trace ) { logger . trace ( \"Executing after commit actions\" ) ; } executeActions ( afterCommitActions , trace ) ; afterCommitActions = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes actions scheduled to run first after commit succeeds [CODESPLIT] protected void executeAfterCommitPriorityActions ( ) { if ( afterCommitPriorityActions != null ) { if ( trace ) { logger . trace ( \"Executing after commit priority actions\" ) ; } executeActions ( afterCommitPriorityActions , trace ) ; afterCommitPriorityActions = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes actions scheduled for after a rollback [CODESPLIT] protected void executeAfterRollbackActions ( ) { if ( afterRollbackActions != null ) { if ( trace ) { logger . trace ( \"Executing rollback actions\" ) ; } executeActions ( afterRollbackActions , trace ) ; afterRollbackActions = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes actions scheduled for before commit [CODESPLIT] protected void executeBeforeCommitActions ( ) { if ( beforeCommitActions != null ) { if ( trace ) { logger . trace ( \"Executing before commit actions\" ) ; } executeActions ( beforeCommitActions , trace ) ; beforeCommitActions = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes actions scheduled for before commit at first [CODESPLIT] protected void executeBeforeCommitPriorityActions ( ) { if ( beforeCommitPriorityActions != null ) { if ( trace ) { logger . trace ( \"Executing before commit priority actions\" ) ; } executeActions ( beforeCommitPriorityActions , trace ) ; beforeCommitPriorityActions = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method raturns tracer names of tracers that have been requested directly from NotificationSource ( like through SbbContext RAContext etc ) [CODESPLIT] public String [ ] getRequestedTracerNames ( ) { Set < String > names = new HashSet < String > ( ) ; for ( TracerImpl t : this . tracers . values ( ) ) { if ( t . isRequestedBySource ( ) ) names . add ( t . getTracerName ( ) ) ; } if ( names . isEmpty ( ) ) return new String [ 0 ] ; return names . toArray ( new String [ names . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns tracer names that have been defined explicitly via setTraceLevel from TraceMBean [CODESPLIT] public String [ ] getDefinedTracerNames ( ) { Set < String > names = new HashSet < String > ( ) ; for ( TracerImpl t : this . tracers . values ( ) ) { if ( t . isExplicitlySetTracerLevel ( ) ) names . add ( t . getTracerName ( ) ) ; } if ( names . isEmpty ( ) ) return new String [ 0 ] ; return names . toArray ( new String [ names . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method can be called multiple times . [CODESPLIT] public Tracer createTracer ( String tracerName , boolean requestedBySource ) { TracerImpl tparent = null ; TracerImpl t = tracers . get ( tracerName ) ; if ( t == null ) { String [ ] split = tracerName . split ( \"\\\\.\" ) ; String currentName = \"\" ; for ( String s : split ) { if ( tparent == null ) { // first loop tparent = rootTracer ; currentName = s ; } else { currentName = currentName + \".\" + s ; } t = tracers . get ( currentName ) ; if ( t == null ) { t = new TracerImpl ( currentName , tparent , this . notificationSource , this . traceFacility ) ; final TracerImpl u = tracers . putIfAbsent ( t . getTracerName ( ) , t ) ; if ( u != null ) { t = u ; } } tparent = t ; } } if ( requestedBySource ) t . setRequestedBySource ( requestedBySource ) ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void bind ( ActivityContextInterface aci , String aciName ) throws NullPointerException , IllegalArgumentException , TransactionRequiredLocalException , NameAlreadyBoundException , FacilityException { // Check if we are in the context of a transaction. sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; if ( aciName == null ) throw new NullPointerException ( \"null aci name\" ) ; else if ( aciName . equals ( \"\" ) ) throw new IllegalArgumentException ( \"empty name\" ) ; else if ( aci == null ) throw new NullPointerException ( \"Null ACI! \" ) ; try { org . mobicents . slee . container . activity . ActivityContextInterface sleeAci = ( org . mobicents . slee . container . activity . ActivityContextInterface ) aci ; ActivityContext ac = sleeAci . getActivityContext ( ) ; ActivityContextHandle ach = ac . getActivityContextHandle ( ) ; cacheData . bindName ( ach , aciName ) ; ac . addNameBinding ( aciName ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"aci name \" + aciName + \" bound to \" + ach + \" . Tx is \" + sleeContainer . getTransactionManager ( ) . getTransaction ( ) ) ; } } catch ( NameAlreadyBoundException ex ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"name already bound \" + aciName ) ; } throw ex ; } catch ( Exception e ) { throw new FacilityException ( \"Failed to put ac name binding in cache\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void unbind ( String aciName ) throws NullPointerException , TransactionRequiredLocalException , NameNotBoundException , FacilityException { //Check if we are in the context of a transaction. sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; if ( aciName == null ) throw new NullPointerException ( \"null activity context name!\" ) ; try { ActivityContextHandle ach = ( ActivityContextHandle ) cacheData . unbindName ( aciName ) ; ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac != null ) ac . removeNameBinding ( aciName ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"aci name \" + aciName + \" unbound from \" + ach + \" . Tx is \" + sleeContainer . getTransactionManager ( ) . getTransaction ( ) ) ; } } catch ( NameNotBoundException ex ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Name not bound \" + aciName ) ; } throw ex ; } catch ( Exception e ) { throw new FacilityException ( \"Failed to remove ac name binding from cache\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ActivityContextInterface lookup ( String acName ) throws NullPointerException , TransactionRequiredLocalException , FacilityException { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; if ( acName == null ) throw new NullPointerException ( \"null ac name\" ) ; try { ActivityContextHandle ach = ( ActivityContextHandle ) cacheData . lookupName ( acName ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"lookup of aci name \" + acName + \" result is \" + ach + \" . Tx is \" + sleeContainer . getTransactionManager ( ) . getTransaction ( ) ) ; } if ( ach == null ) { return null ; } ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac == null ) { cacheData . unbindName ( acName ) ; throw new FacilityException ( \"name found but unable to retrieve activity context\" ) ; } return ac . getActivityContextInterface ( ) ; } catch ( Exception e ) { throw new FacilityException ( \"Failed to look-up ac name binding\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the Profile MBean interface [CODESPLIT] public void generateProfileMBeanInterface ( ) throws Exception { if ( SleeProfileClassCodeGenerator . checkCombination ( component ) == - 1 ) { throw new DeploymentException ( \"Profile Specification doesn't match any combination \" + \"from the JSLEE spec 1.0 section 10.5.2\" ) ; } String profileMBeanConcreteInterfaceName = cmpProfileInterfaceName + \"MBean\" ; profileMBeanConcreteInterface = pool . makeInterface ( profileMBeanConcreteInterfaceName ) ; try { cmpProfileInterface = pool . get ( cmpProfileInterfaceName ) ; profileManagementInterface = profileManagementInterfaceName != null ? pool . get ( profileManagementInterfaceName ) : null ; } catch ( NotFoundException nfe ) { throw new DeploymentException ( \"Failed to locate CMP/Management Interface for \" + component , nfe ) ; } // set interface\r try { profileMBeanConcreteInterface . addInterface ( pool . get ( AbstractProfileMBean . class . getName ( ) ) ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } // gather exceptions that the mbean methods may throw\r CtClass [ ] managementMethodExceptions = new CtClass [ 3 ] ; try { managementMethodExceptions [ 0 ] = pool . get ( ManagementException . class . getName ( ) ) ; managementMethodExceptions [ 1 ] = pool . get ( InvalidStateException . class . getName ( ) ) ; managementMethodExceptions [ 2 ] = pool . get ( ProfileImplementationException . class . getName ( ) ) ; } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } CtClass [ ] cmpGetAcessorMethodExceptions = new CtClass [ ] { managementMethodExceptions [ 0 ] } ; CtClass [ ] cmpSetAcessorMethodExceptions = new CtClass [ ] { managementMethodExceptions [ 0 ] , managementMethodExceptions [ 1 ] } ; // gather all Object class methods, we don't want those in the mbean\r Set < CtMethod > objectMethods = new HashSet < CtMethod > ( ) ; try { CtClass objectClass = pool . get ( Object . class . getName ( ) ) ; for ( CtMethod ctMethod : objectClass . getMethods ( ) ) { objectMethods . add ( ctMethod ) ; } } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } // gather methods to copy\r Set < CtMethod > cmpAcessorMethods = new HashSet < CtMethod > ( ) ; Set < CtMethod > managementMethods = new HashSet < CtMethod > ( ) ; if ( profileManagementInterface != null ) { // If the Profile Specification defines a Profile Management Interface, the profileMBean interface has the same methods\r // 1. gather all methods from management interface\r for ( CtMethod ctMethod : profileManagementInterface . getMethods ( ) ) { if ( ! objectMethods . contains ( ctMethod ) ) { managementMethods . add ( ctMethod ) ; } } // 2. gather all methods present also in cmp interface, removing those from the ones gather from management interface\r for ( CtMethod ctMethod : cmpProfileInterface . getMethods ( ) ) { if ( ! objectMethods . contains ( ctMethod ) ) { if ( managementMethods . remove ( ctMethod ) ) { cmpAcessorMethods . add ( ctMethod ) ; } } } } else { for ( CtMethod ctMethod : cmpProfileInterface . getMethods ( ) ) { if ( ! objectMethods . contains ( ctMethod ) ) { cmpAcessorMethods . add ( ctMethod ) ; } } } // copy cmp acessor & mngt methods\r for ( CtMethod ctMethod : cmpAcessorMethods ) { // copy method\r CtMethod methodCopy = new CtMethod ( ctMethod , profileMBeanConcreteInterface , null ) ; // set exceptions\r CtClass [ ] exceptions = null ; if ( ctMethod . getName ( ) . startsWith ( \"set\" ) ) { exceptions = cmpSetAcessorMethodExceptions ; } else if ( ctMethod . getName ( ) . startsWith ( \"get\" ) ) { exceptions = cmpGetAcessorMethodExceptions ; } else { throw new DeploymentException ( \"unexpected method in profile cmp interface \" + ctMethod ) ; } methodCopy . setExceptionTypes ( exceptions ) ; // add to class\r profileMBeanConcreteInterface . addMethod ( methodCopy ) ; // store in set to be used in mbean impl\r mBeanCmpAcessorMethods . add ( methodCopy ) ; } for ( CtMethod ctMethod : managementMethods ) { // copy method\r CtMethod methodCopy = new CtMethod ( ctMethod , profileMBeanConcreteInterface , null ) ; // set exceptions\r methodCopy . setExceptionTypes ( managementMethodExceptions ) ; // add to class\r profileMBeanConcreteInterface . addMethod ( methodCopy ) ; // store in set to be used in mbean impl\r mBeanManagementMethods . add ( methodCopy ) ; } // write class file\r try { profileMBeanConcreteInterface . writeFile ( this . component . getDeploymentDir ( ) . getAbsolutePath ( ) ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } finally { profileMBeanConcreteInterface . defrost ( ) ; } // and load it to the component\r try { this . component . setProfileMBeanConcreteInterfaceClass ( Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( profileMBeanConcreteInterfaceName ) ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method generates concrete class of MBean impl [CODESPLIT] public void generateProfileMBean ( ) throws Exception { if ( SleeProfileClassCodeGenerator . checkCombination ( component ) == - 1 ) { throw new DeploymentException ( \"Profile Specification doesn't match any combination \" + \"from the JSLEE spec 1.0 section 10.5.2\" ) ; } String profileMBeanConcreteClassName = profileMBeanConcreteInterface . getName ( ) + \"Impl\" ; profileMBeanConcreteClass = pool . makeClass ( profileMBeanConcreteClassName ) ; // set interface & super class\r try { profileMBeanConcreteClass . setInterfaces ( new CtClass [ ] { profileMBeanConcreteInterface } ) ; profileMBeanConcreteClass . setSuperclass ( pool . get ( AbstractProfileMBeanImpl . class . getName ( ) ) ) ; } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } // implement cmp acessor & management methods gather in the mbean interface building\r for ( CtMethod method : mBeanCmpAcessorMethods ) { // copy method & remove abstract modifier\t\t\t\r CtMethod newMethod = CtNewMethod . copy ( method , profileMBeanConcreteClass , null ) ; // generate body\r String body = null ; if ( method . getName ( ) . startsWith ( \"set\" ) ) { body = \"{ \" + \"\tbeforeSetCmpField();\" + \"\ttry { \" + \"\t\t((\" + component . getProfileCmpConcreteClass ( ) . getName ( ) + \")getProfileObject().getProfileConcrete()).\" + method . getName ( ) + \"($1);\" + \"\t} finally {\" + \"\t\tafterSetCmpField();\" + \"\t}\" + \"}\" ; } else { body = \"{ \" + \"\tboolean activatedTransaction = beforeGetCmpField();\" + \"\ttry { \" + \"\t\treturn ($r) ((\" + component . getProfileCmpConcreteClass ( ) . getName ( ) + \")getProfileObject().getProfileConcrete()).\" + method . getName ( ) + \"();\" + \"\t} finally {\" + \"\t\tafterGetCmpField(activatedTransaction);\" + \"\t}\" + \"}\" ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Implemented profile mbean method named \" + method . getName ( ) + \", with body:\\n\" + body ) ; } newMethod . setBody ( body ) ; profileMBeanConcreteClass . addMethod ( newMethod ) ; } for ( CtMethod method : mBeanManagementMethods ) { // copy method & remove abstract modifier\t\t\t\r CtMethod newMethod = CtNewMethod . copy ( method , profileMBeanConcreteClass , null ) ; // generate body\r boolean voidReturnType = newMethod . getReturnType ( ) . equals ( CtClass . voidType ) ; String body = \"{ boolean activatedTransaction = beforeManagementMethodInvocation(); try { \" ; if ( ! voidReturnType ) { body += \"return ($r) \" ; } body += \"((\" + component . getProfileCmpConcreteClass ( ) . getName ( ) + \")getProfileObject().getProfileConcrete()).\" + method . getName ( ) + \"($$); } catch(Throwable t) { throwableOnManagementMethodInvocation(t); } finally { afterManagementMethodInvocation(activatedTransaction); }\" ; if ( ! voidReturnType ) { body += \"throw new \" + SLEEException . class . getName ( ) + \"(\\\"bad code generated\\\");\" ; } body += \" }\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Implemented profile mbean method named \" + method . getName ( ) + \", with body:\\n\" + body ) ; } newMethod . setBody ( body ) ; profileMBeanConcreteClass . addMethod ( newMethod ) ; } try { profileMBeanConcreteClass . writeFile ( this . component . getDeploymentDir ( ) . getAbsolutePath ( ) ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } finally { profileMBeanConcreteClass . defrost ( ) ; } try { component . setProfileMBeanConcreteImplClass ( Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( profileMBeanConcreteClassName ) ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ReplicatedDataWithFailover < K , V > getReplicatedDataWithFailover ( boolean activateDataRemovedCallback ) { if ( replicatedDataWithFailover == null ) { replicatedDataWithFailover = new ReplicatedDataWithFailoverImpl < K , V > ( REPLICATED_DATA_WITH_FAILOVER_NAME , raEntity , sleeContainer . getCluster ( ) , ra , activateDataRemovedCallback ) ; } return replicatedDataWithFailover ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ReplicatedData < K , V > getReplicateData ( boolean activateDataRemovedCallback ) { if ( replicatedData == null ) { replicatedData = new ReplicatedDataImpl < K , V > ( REPLICATED_DATA_NAME , raEntity , sleeContainer . getCluster ( ) , ra , activateDataRemovedCallback ) ; } return replicatedData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public MemberAddress [ ] getMembers ( ) { final Address [ ] addresses = sleeContainer . getCluster ( ) . getClusterMembers ( ) . toArray ( EMPTY_ADDRESS_ARRAY ) ; final MemberAddressImpl [ ] members = new MemberAddressImpl [ addresses . length ] ; for ( int i = 0 ; i < members . length ; i ++ ) { members [ i ] = new MemberAddressImpl ( addresses [ i ] ) ; } return members ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public MemberAddress getLocalAddress ( ) { Address localAddress = sleeContainer . getCluster ( ) . getLocalAddress ( ) ; return localAddress != null ? new MemberAddressImpl ( localAddress ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all replicated data [CODESPLIT] public void removeReplicateData ( ) { if ( replicatedDataWithFailover != null ) { replicatedDataWithFailover . remove ( ) ; replicatedDataWithFailover = null ; } if ( replicatedData != null ) { replicatedData . remove ( ) ; replicatedData = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the property editors for jboss jmx console so non string SLEE api types can be used in specs mbeans methods as args [CODESPLIT] public void register ( ) { PropertyEditorManager . registerEditor ( ComponentID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( EventTypeID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( LibraryID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ProfileSpecificationID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ResourceAdaptorID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ResourceAdaptorTypeID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( SbbID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ServiceID . class , ComponentIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ComponentID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( EventTypeID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( LibraryID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ProfileSpecificationID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ResourceAdaptorID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ResourceAdaptorTypeID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( SbbID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ServiceID [ ] . class , ComponentIDArrayPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( DeployableUnitID . class , DeployableUnitIDPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( Level . class , LevelPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( TraceLevel . class , TraceLevelPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ConfigProperties . class , ConfigPropertiesPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( NotificationSource . class , NotificationSourcePropertyEditor . class ) ; PropertyEditorManager . registerEditor ( Object . class , ObjectPropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ServiceState . class , ServiceStatePropertyEditor . class ) ; PropertyEditorManager . registerEditor ( ResourceAdaptorEntityState . class , ResourceAdaptorEntityStatePropertyEditor . class ) ; PropertyEditorManager . registerEditor ( Address . class , AddressPropertyEditor . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates classes for a slee component which defines usage parameters [CODESPLIT] public void process ( SleeComponentWithUsageParametersInterface component ) throws DeploymentException { ClassPool classPool = component . getClassPool ( ) ; String deploymentDir = component . getDeploymentDir ( ) . getAbsolutePath ( ) ; Class < ? > usageParametersInterface = component . getUsageParametersInterface ( ) ; if ( usageParametersInterface != null ) { try { // generate the concrete usage param set class component . setUsageParametersConcreteClass ( new ConcreteUsageParameterClassGenerator ( usageParametersInterface . getName ( ) , deploymentDir , classPool ) . generateConcreteUsageParameterClass ( ) ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( \"Generated usage parameter impl class for \" + component ) ; } // generate the mbeans new ConcreteUsageParameterMBeanGenerator ( component ) . generateConcreteUsageParameterMBean ( ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( \"Generated usage mbean (interface and impl) for \" + component ) ; } } catch ( DeploymentException ex ) { throw ex ; } catch ( Exception ex ) { throw new DeploymentException ( \"Failed to generate \" + component + \" usage parameter class\" , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare this component identifier with the specified component identifier for order . Returns a negative integer zero or a positive integer if this object is less than equal to or greater than the specified object . <p > Component ordering is determined by comparing the component identifier attributes in the following order : <ol > <li > component type ( nb . any subclass of <code > ComponentID< / code > may be safely compared without causing a <code > ClassCastException< / code > ) <li > component name <li > component vendor <li > component version < / ol > [CODESPLIT] protected final int compareTo ( String thisClassName , ComponentID that ) { int typeComparison = thisClassName . compareTo ( that . getClassName ( ) ) ; if ( typeComparison != 0 ) return typeComparison ; int nameComparison = this . name . compareTo ( that . name ) ; if ( nameComparison != 0 ) return nameComparison ; int vendorComparison = this . vendor . compareTo ( that . vendor ) ; if ( vendorComparison != 0 ) return vendorComparison ; return this . version . compareTo ( that . version ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private [CODESPLIT] private int rotateLeft ( int value , int bits ) { long l = value & 0x00000000ffffffff  L ; l <<= bits ; return ( int ) l | ( int ) ( l >> 32 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the object pool for the specified sbb and service . [CODESPLIT] public SbbObjectPoolImpl getObjectPool ( ServiceID serviceID , SbbID sbbID ) { return pools . get ( new ObjectPoolMapKey ( serviceID , sbbID ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object pool for the specified service and sbb . If a transaction manager is used then and if the tx rollbacks the pool will be removed . [CODESPLIT] public void createObjectPool ( final ServiceID serviceID , final SbbComponent sbbComponent , final SleeTransactionManager sleeTransactionManager ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Creating Pool for  \" + serviceID + \" and \" + sbbComponent ) ; } createObjectPool ( serviceID , sbbComponent ) ; if ( sleeTransactionManager != null && sleeTransactionManager . getTransactionContext ( ) != null ) { // add a rollback action to remove sbb object pool TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Due to tx rollback, removing pool for \" + serviceID + \" and \" + sbbComponent ) ; } try { removeObjectPool ( serviceID , sbbComponent . getSbbID ( ) ) ; } catch ( Throwable e ) { logger . error ( \"Failed to remove \" + serviceID + \" and \" + sbbComponent + \" object pool\" , e ) ; } } } ; sleeTransactionManager . getTransactionContext ( ) . getAfterRollbackActions ( ) . add ( action ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the pool for the specified ids [CODESPLIT] private void removeObjectPool ( final ServiceID serviceID , final SbbID sbbID ) { ObjectPoolMapKey key = new ObjectPoolMapKey ( serviceID , sbbID ) ; final SbbObjectPoolImpl objectPool = pools . remove ( key ) ; if ( objectPool != null ) { try { objectPool . close ( ) ; } catch ( Exception e ) { logger . error ( \"failed to close pool\" , e ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Removed Pool for \" + key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ActivityContextInterface getActivityContextInterface ( ServiceActivity serviceActivityImpl ) throws NullPointerException , TransactionRequiredLocalException , UnrecognizedActivityException , FactoryException { ActivityContextHandle ach = new ServiceActivityContextHandle ( new ServiceActivityHandleImpl ( ( ( ServiceActivityImpl ) serviceActivityImpl ) . getServiceID ( ) ) ) ; ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac == null ) { throw new UnrecognizedActivityException ( serviceActivityImpl ) ; } return ac . getActivityContextInterface ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a non transacted End Activity operation . [CODESPLIT] void execute ( final ActivityHandle handle ) throws UnrecognizedActivityHandleException { final SleeTransaction tx = super . suspendTransaction ( ) ; try { sleeEndpoint . _endActivity ( handle , tx ) ; } finally { if ( tx != null ) { super . resumeTransaction ( tx ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void startActivity ( ActivityHandle handle , Object activity ) throws NullPointerException , IllegalStateException , ActivityAlreadyExistsException , StartActivityException , SLEEException { startActivity ( handle , activity , ActivityFlags . NO_FLAGS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void startActivity ( final ActivityHandle handle , Object activity , final int activityFlags ) throws NullPointerException , IllegalStateException , ActivityAlreadyExistsException , StartActivityException , SLEEException { if ( doTraceLogs ) { logger . trace ( \"startActivity( handle = \" + handle + \" , activity = \" + activity + \" , flags = \" + activityFlags + \" )\" ) ; } checkStartActivityParameters ( handle , activity ) ; startActivityNotTransactedExecutor . execute ( handle , activityFlags , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void startActivitySuspended ( ActivityHandle handle , Object activity ) throws NullPointerException , IllegalStateException , TransactionRequiredLocalException , ActivityAlreadyExistsException , StartActivityException , SLEEException { startActivitySuspended ( handle , activity , ActivityFlags . NO_FLAGS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void startActivitySuspended ( ActivityHandle handle , Object activity , int activityFlags ) throws NullPointerException , IllegalStateException , TransactionRequiredLocalException , ActivityAlreadyExistsException , StartActivityException , SLEEException { if ( doTraceLogs ) { logger . trace ( \"startActivitySuspended( handle = \" + handle + \" , activity = \" + activity + \" , flags = \" + activityFlags + \" )\" ) ; } // need to check tx before doing out of tx scope activity start txManager . mandateTransaction ( ) ; checkStartActivityParameters ( handle , activity ) ; startActivityNotTransactedExecutor . execute ( handle , activityFlags , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void startActivityTransacted ( ActivityHandle handle , Object activity , int activityFlags ) throws NullPointerException , IllegalStateException , TransactionRequiredLocalException , ActivityAlreadyExistsException , StartActivityException , SLEEException { if ( doTraceLogs ) { logger . trace ( \"startActivityTransacted( handle = \" + handle + \" , activity = \" + activity + \" , flags = \" + activityFlags + \" )\" ) ; } checkStartActivityParameters ( handle , activity ) ; // check tx state txManager . mandateTransaction ( ) ; _startActivity ( handle , activityFlags , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the parameters of startActivity * methods [CODESPLIT] private void checkStartActivityParameters ( ActivityHandle handle , Object activity ) throws NullPointerException , IllegalStateException { // check args if ( handle == null ) { throw new NullPointerException ( \"null handle\" ) ; } if ( activity == null ) { throw new NullPointerException ( \"null activity\" ) ; } // check ra state if ( raEntity . getResourceAdaptorObject ( ) . getState ( ) != ResourceAdaptorObjectState . ACTIVE ) { throw new IllegalStateException ( \"ra is in state \" + raEntity . getResourceAdaptorObject ( ) . getState ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start activity logic independent of transaction management . [CODESPLIT] ActivityContextHandle _startActivity ( ActivityHandle handle , int activityFlags , final SleeTransaction barrierTx ) { ActivityContext ac = null ; if ( raEntity . getHandleReferenceFactory ( ) != null && ! ActivityFlags . hasSleeMayMarshal ( activityFlags ) ) { final ActivityHandleReference reference = raEntity . getHandleReferenceFactory ( ) . createActivityHandleReference ( handle ) ; try { // create activity context with ref instead ac = acFactory . createActivityContext ( new ResourceAdaptorActivityContextHandleImpl ( raEntity , reference ) , activityFlags ) ; } catch ( ActivityAlreadyExistsException e ) { throw e ; } catch ( RuntimeException e ) { raEntity . getHandleReferenceFactory ( ) . removeActivityHandleReference ( reference ) ; throw e ; } } else { // create activity context ac = acFactory . createActivityContext ( new ResourceAdaptorActivityContextHandleImpl ( raEntity , handle ) , activityFlags ) ; } // suspend activity if needed if ( barrierTx != null && ac != null ) { final ActivityEventQueueManager aeqm = ac . getLocalActivityContext ( ) . getEventQueueManager ( ) ; aeqm . createBarrier ( barrierTx ) ; TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { aeqm . removeBarrier ( barrierTx ) ; } } ; final TransactionContext tc = barrierTx . getTransactionContext ( ) ; tc . getAfterCommitActions ( ) . add ( action ) ; tc . getAfterRollbackActions ( ) . add ( action ) ; } return ac . getActivityContextHandle ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "End activity logic independent of transaction management . [CODESPLIT] void _endActivity ( ActivityHandle handle , final SleeTransaction barrierTx ) throws UnrecognizedActivityHandleException { final ActivityContextHandle ach = new ResourceAdaptorActivityContextHandleImpl ( raEntity , handle ) ; // get ac final ActivityContext ac = acFactory . getActivityContext ( ach ) ; if ( ac != null ) { // suspend activity if needed if ( barrierTx != null ) { final ActivityEventQueueManager aeqm = ac . getLocalActivityContext ( ) . getEventQueueManager ( ) ; aeqm . createBarrier ( barrierTx ) ; TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { aeqm . removeBarrier ( barrierTx ) ; } } ; final TransactionContext tc = barrierTx . getTransactionContext ( ) ; tc . getAfterCommitActions ( ) . add ( action ) ; tc . getAfterRollbackActions ( ) . add ( action ) ; } // end the activity ac . endActivity ( ) ; } else { throw new UnrecognizedActivityHandleException ( handle . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void fireEvent ( ActivityHandle handle , FireableEventType eventType , Object event , Address address , ReceivableService receivableService ) throws NullPointerException , UnrecognizedActivityHandleException , IllegalEventException , ActivityIsEndingException , FireEventException , SLEEException { fireEvent ( handle , eventType , event , address , receivableService , EventFlags . NO_FLAGS , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that fire event methods can be invoked [CODESPLIT] private void checkFireEventPreconditions ( ActivityHandle handle , FireableEventType eventType , Object event ) throws NullPointerException , IllegalEventException , IllegalStateException { if ( event == null ) throw new NullPointerException ( \"event is null\" ) ; if ( handle == null ) throw new NullPointerException ( \"handle is null\" ) ; if ( eventType == null ) { throw new NullPointerException ( \"eventType is null\" ) ; } final EventTypeComponent eventTypeComponent = componentRepository . getComponentByID ( eventType . getEventType ( ) ) ; if ( eventTypeComponent == null ) { throw new IllegalEventException ( \"event type not installed (more on SLEE 1.1 specs 15.14.8)\" ) ; } if ( ! eventTypeComponent . getEventTypeClass ( ) . isAssignableFrom ( event . getClass ( ) ) ) { throw new IllegalEventException ( \"the class of the event object fired is not assignable to the event class of the event type (more on SLEE 1.1 specs 15.14.8) \" ) ; } if ( eventType . getClass ( ) != FireableEventTypeImpl . class ) { throw new IllegalEventException ( \"unknown implementation of FireableEventType\" ) ; } if ( raEntity . getAllowedEventTypes ( ) != null && ! raEntity . getAllowedEventTypes ( ) . contains ( eventType . getEventType ( ) ) ) { throw new IllegalEventException ( \"Resource Adaptor configured to not ignore ra type event checking and the event \" + eventType . getEventType ( ) + \" does not belongs to any of the ra types implemented by the resource adaptor\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event firing logic independent of transaction management . [CODESPLIT] void _fireEvent ( ActivityHandle realHandle , ActivityHandle refHandle , FireableEventType eventType , Object event , Address address , ReceivableService receivableService , int eventFlags , final SleeTransaction barrierTx ) throws ActivityIsEndingException , SLEEException { final ActivityContextHandle ach = new ResourceAdaptorActivityContextHandleImpl ( raEntity , refHandle ) ; // get ac final ActivityContext ac = acFactory . getActivityContext ( ach ) ; if ( ac == null ) { throw new UnrecognizedActivityHandleException ( \"Unable to fire \" + eventType . getEventType ( ) + \" on activity handle \" + realHandle + \" , the handle is not mapped to an activity context\" ) ; } else { // suspend activity if needed if ( barrierTx != null ) { final ActivityEventQueueManager aeqm = ac . getLocalActivityContext ( ) . getEventQueueManager ( ) ; aeqm . createBarrier ( barrierTx ) ; TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { aeqm . removeBarrier ( barrierTx ) ; } } ; final TransactionContext tc = barrierTx . getTransactionContext ( ) ; tc . getAfterCommitActions ( ) . add ( action ) ; tc . getAfterRollbackActions ( ) . add ( action ) ; } final EventProcessingCallbacks callbacks = new EventProcessingCallbacks ( realHandle , eventType , event , address , receivableService , eventFlags , raEntity ) ; final EventProcessingSucceedCallback succeedCallback = EventFlags . hasRequestProcessingSuccessfulCallback ( eventFlags ) ? callbacks : null ; final EventProcessingFailedCallback failedCallback = EventFlags . hasRequestProcessingFailedCallback ( eventFlags ) ? callbacks : null ; final EventUnreferencedCallback unreferencedCallback = EventFlags . hasRequestEventReferenceReleasedCallback ( eventFlags ) ? callbacks : null ; ac . fireEvent ( eventType . getEventType ( ) , event , address , receivableService == null ? null : receivableService . getService ( ) , succeedCallback , failedCallback , unreferencedCallback ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void suspendActivity ( ActivityHandle handle ) throws NullPointerException , TransactionRequiredLocalException , UnrecognizedActivityHandleException , SLEEException { suspendActivity ( handle , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void suspendReplicatedActivity ( ActivityHandle handle ) throws NullPointerException , TransactionRequiredLocalException , UnrecognizedActivityHandleException , SLEEException { suspendActivity ( handle , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the Sbb Local Object Class [CODESPLIT] public Class generateSbbLocalObjectConcreteClass ( ) { //Generates the implements link if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"generateSbbLocalObjectConcreteClass: sbbLocalObjectInterface = \" + sbbLocalObjectName + \" deployPath = \" + deployPath ) ; } try { concreteSbbLocalObject = pool . makeClass ( ConcreteClassGeneratorUtils . SBB_LOCAL_OBJECT_CLASS_NAME_PREFIX + sbbLocalObjectName + ConcreteClassGeneratorUtils . SBB_LOCAL_OBJECT_CLASS_NAME_SUFFIX ) ; try { sleeSbbLocalObject = pool . get ( SbbLocalObjectImpl . class . getName ( ) ) ; sbbLocalObjectInterface = pool . get ( sbbLocalObjectName ) ; } catch ( NotFoundException nfe ) { nfe . printStackTrace ( ) ; String s = \"Problem with pool \" ; logger . error ( s , nfe ) ; throw new RuntimeException ( s , nfe ) ; } // This is our implementation interface. CtClass concreteClassInterface ; try { concreteClassInterface = pool . get ( SbbLocalObjectConcrete . class . getName ( ) ) ; } catch ( NotFoundException nfe ) { nfe . printStackTrace ( ) ; String s = \"Problem with the pool! \" ; logger . error ( s , nfe ) ; throw new RuntimeException ( s , nfe ) ; } ConcreteClassGeneratorUtils . createInterfaceLinks ( concreteSbbLocalObject , new CtClass [ ] { sbbLocalObjectInterface , concreteClassInterface } ) ; //Generates an inheritance link to the slee implementation of the // SbbLocalObject interface ConcreteClassGeneratorUtils . createInheritanceLink ( concreteSbbLocalObject , sleeSbbLocalObject ) ; //Generates the methods to implement from the interface Map interfaceMethods = ClassUtils . getInterfaceMethodsFromInterface ( sbbLocalObjectInterface ) ; generateConcreteMethods ( interfaceMethods , sbbAbstractClassName ) ; try { concreteSbbLocalObject . writeFile ( deployPath ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Concrete Class \" + concreteSbbLocalObject . getName ( ) + \" generated in the following path \" + deployPath ) ; } } catch ( CannotCompileException e ) { String s = \" Unexpected exception ! \" ; logger . fatal ( s , e ) ; throw new RuntimeException ( s , e ) ; } catch ( IOException e ) { String s = \"IO Exception!\" ; logger . error ( s , e ) ; return null ; } //load the class try { return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( concreteSbbLocalObject . getName ( ) ) ; } catch ( ClassNotFoundException e ) { logger . error ( \"unable to load sbb local object impl class\" , e ) ; return null ; } } finally { if ( this . concreteSbbLocalObject != null ) this . concreteSbbLocalObject . defrost ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the concrete methods of the class [CODESPLIT] private void generateConcreteMethods ( Map interfaceMethods , String sbbAbstractClassName ) { if ( interfaceMethods == null ) return ; Iterator it = interfaceMethods . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { CtMethod interfaceMethod = ( CtMethod ) it . next ( ) ; if ( interfaceMethod == null ) return ; // The following methods are implemented in the superclass if ( interfaceMethod . getName ( ) . equals ( \"isIdentical\" ) || interfaceMethod . getName ( ) . equals ( \"equals\" ) || interfaceMethod . getName ( ) . equals ( \"hashCode\" ) || interfaceMethod . getName ( ) . equals ( \"getSbbPriority\" ) || interfaceMethod . getName ( ) . equals ( \"remove\" ) || interfaceMethod . getName ( ) . equals ( \"setSbbPriority\" ) || interfaceMethod . getName ( ) . equals ( \"getName\" ) || interfaceMethod . getName ( ) . equals ( \"getChildRelation\" ) || interfaceMethod . getName ( ) . equals ( \"getParent\" ) ) continue ; String methodToAdd = \"public \" ; //Add the return type boolean hasReturn = false ; CtClass returnType = null ; try { // There's probably a more elegant way to do this. returnType = interfaceMethod . getReturnType ( ) ; if ( returnType . equals ( CtClass . voidType ) ) { methodToAdd += \"void \" ; } else { methodToAdd = methodToAdd . concat ( returnType . getName ( ) + \" \" ) ; hasReturn = true ; } } catch ( NotFoundException nfe ) { nfe . printStackTrace ( ) ; methodToAdd = methodToAdd + \"void \" ; } //Add the method name methodToAdd += interfaceMethod . getName ( ) + \"(\" ; //Add the parameters CtClass [ ] parameterTypes = null ; ; try { parameterTypes = interfaceMethod . getParameterTypes ( ) ; for ( int argNumber = 0 ; argNumber < parameterTypes . length ; argNumber ++ ) { methodToAdd = methodToAdd . concat ( parameterTypes [ argNumber ] . getName ( ) + \" arg_\" + argNumber ) ; if ( argNumber + 1 < parameterTypes . length ) methodToAdd = methodToAdd + \",\" ; } } catch ( NotFoundException nfe ) { nfe . printStackTrace ( ) ; throw new RuntimeException ( \"unexpected Exception ! \" , nfe ) ; } methodToAdd = methodToAdd + \") { \" ; // We need to do this in a type neutral way ! methodToAdd += SbbConcrete . class . getName ( ) + \" concrete = \" + \" getSbbEntity().getSbbObject().getSbbConcrete();\" ; //These methods are delegated to superclass. // Note the convoluted code here because finally is not supported // yet by javaassist. methodToAdd += \"Object[] args = new Object [\" + parameterTypes . length + \"];\" ; methodToAdd += \"Class[] types = new Class [\" + parameterTypes . length + \"];\" ; if ( parameterTypes != null && parameterTypes . length > 0 ) { for ( int argNumber = 0 ; argNumber < parameterTypes . length ; argNumber ++ ) { methodToAdd += \"args[\" + argNumber + \"]  = \" ; // Check if parameter type is primitive and add the wrapper // types. if ( parameterTypes [ argNumber ] . isPrimitive ( ) ) { CtClass ptype = parameterTypes [ argNumber ] ; if ( ptype . equals ( CtClass . intType ) ) { methodToAdd += \"Integer.valueOf(\" + \"arg_\" + argNumber + \");\" ; } else if ( ptype . equals ( CtClass . booleanType ) ) { methodToAdd += \"Boolean.valueOf(\" + \"arg_\" + argNumber + \");\" ; } else if ( ptype . equals ( CtClass . longType ) ) { methodToAdd += \"Long.valueOf(\" + \"arg_\" + argNumber + \");\" ; } else if ( ptype . equals ( CtClass . shortType ) ) { methodToAdd += \"Short.valueOf(\" + \"arg_\" + argNumber + \");\" ; } else if ( ptype . equals ( CtClass . floatType ) ) { methodToAdd += \"Float.valueOf(\" + \"arg_\" + argNumber + \");\" ; } else if ( ptype . equals ( CtClass . doubleType ) ) { methodToAdd += \"Double.valueOf(\" + \"arg_\" + argNumber + \");\" ; } else if ( ptype . equals ( CtClass . charType ) ) { methodToAdd += \"Character.valueOf(\" + \"arg_\" + argNumber + \");\" ; } } else { methodToAdd += \"arg_\" + argNumber + \";\" ; } } for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { methodToAdd += \"types[\" + i + \"] = \" ; if ( parameterTypes [ i ] . isPrimitive ( ) ) { CtClass ptype = parameterTypes [ i ] ; if ( ptype . equals ( CtClass . intType ) ) { methodToAdd += \"Integer.TYPE;\" ; } else if ( ptype . equals ( CtClass . booleanType ) ) { methodToAdd += \"Boolean.TYPE;\" ; } else if ( ptype . equals ( CtClass . longType ) ) { methodToAdd += \"Long.TYPE;\" ; } else if ( ptype . equals ( CtClass . shortType ) ) { methodToAdd += \"Short.TYPE;\" ; } else if ( ptype . equals ( CtClass . floatType ) ) { methodToAdd += \"Float.TYPE;\" ; } else if ( ptype . equals ( CtClass . doubleType ) ) { methodToAdd += \"Double.TYPE;\" ; } else if ( ptype . equals ( CtClass . charType ) ) { methodToAdd += \"Character.TYPE;\" ; } } else { methodToAdd += parameterTypes [ i ] . getName ( ) + \".class; \" ; } } } if ( hasReturn ) { methodToAdd += \" return  \" + \"(\" + returnType . getName ( ) + \")\" ; } if ( returnType . isPrimitive ( ) ) { methodToAdd += \"sbbLocalObjectInterceptor.invokeAndReturn\" + returnType . getSimpleName ( ) + \"(concrete,\" + \"\\\"\" + interfaceMethod . getName ( ) + \"\\\"\" + \", args, types); \" ; } else { methodToAdd += \"sbbLocalObjectInterceptor.invokeAndReturnObject(concrete,\" + \"\\\"\" + interfaceMethod . getName ( ) + \"\\\"\" + \", args, types );\" ; } methodToAdd += \"}\" ; //Add the implementation code if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Method \" + methodToAdd + \" added\" ) ; } CtMethod methodTest ; try { methodTest = CtNewMethod . make ( methodToAdd , concreteSbbLocalObject ) ; concreteSbbLocalObject . addMethod ( methodTest ) ; } catch ( CannotCompileException cce ) { cce . printStackTrace ( ) ; throw new RuntimeException ( \"error generating method \" , cce ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "User should overide it to provide different name for instance for boolean \\ is \\ prefix [CODESPLIT] protected void makeGetter ( ) { if ( fieldClass . equals ( boolean . class ) || fieldClass . equals ( Boolean . class ) ) { super . operationName = \"is\" + this . beanFieldName ; } else { super . operationName = \"get\" + this . beanFieldName ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called to convert optArg from string form if no conversion is needed it should return passed object . [CODESPLIT] protected Object convert ( String optArg ) throws SecurityException , NoSuchMethodException , IllegalArgumentException , InstantiationException , IllegalAccessException , InvocationTargetException , CommandException { if ( fieldClass . isPrimitive ( ) ) { // TODO: to optimize, to rework new to valueOf\r if ( fieldClass . equals ( int . class ) ) { return new Integer ( optArg ) ; } else if ( fieldClass . equals ( long . class ) ) { return new Long ( optArg ) ; } else if ( fieldClass . equals ( int . class ) ) { return new Integer ( optArg ) ; } else if ( fieldClass . equals ( byte . class ) ) { return new Byte ( optArg ) ; } else if ( fieldClass . equals ( short . class ) ) { return new Short ( optArg ) ; } else if ( fieldClass . equals ( float . class ) ) { return new Float ( optArg ) ; } else if ( fieldClass . equals ( double . class ) ) { return new Double ( optArg ) ; } else if ( fieldClass . equals ( boolean . class ) ) { return new Boolean ( optArg ) ; } else if ( fieldClass . equals ( char . class ) ) { return new Character ( optArg . charAt ( 0 ) ) ; } //?\r throw new CommandException ( \"Unpredicted place. Please report.\" ) ; } else if ( isClassNumber ( ) ) { //Handle Long, Integer, .., Boolean\r Constructor < ? > con = fieldClass . getConstructor ( String . class ) ; return con . newInstance ( optArg ) ; } return optArg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Set < K > getLocalKeyset ( ) { Set < K > set = new HashSet < K > ( ) ; ReplicatedDataKeyClusteredCacheData < K , V > handleCacheData = null ; Address handleCacheDataClusterNode = null ; for ( K handle : cacheData . getAllKeys ( ) ) { handleCacheData = new ReplicatedDataKeyClusteredCacheData < K , V > ( cacheData , handle , cluster ) ; handleCacheDataClusterNode = handleCacheData . getClusterNodeAddress ( ) ; if ( handleCacheDataClusterNode == null || handleCacheDataClusterNode . equals ( cluster . getLocalAddress ( ) ) ) { set . add ( handle ) ; } } return Collections . unmodifiableSet ( set ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean put ( K key , V value ) { final ReplicatedDataKeyClusteredCacheData < K , V > keyCacheData = new ReplicatedDataKeyClusteredCacheData < K , V > ( cacheData , key , cluster ) ; boolean created = keyCacheData . create ( ) ; if ( value != null ) { keyCacheData . setValue ( value ) ; } return created ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public V get ( K key ) { final ReplicatedDataKeyClusteredCacheData < K , V > handleCacheData = new ReplicatedDataKeyClusteredCacheData < K , V > ( cacheData , key , cluster ) ; return handleCacheData . exists ( ) ? handleCacheData . getValue ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean contains ( K key ) { return new ReplicatedDataKeyClusteredCacheData < K , V > ( cacheData , key , cluster ) . exists ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean remove ( K key ) { return new ReplicatedDataKeyClusteredCacheData < K , V > ( cacheData , key , cluster ) . remove ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the specified notification should be delivered to notification listeners using this notification filter . [CODESPLIT] public boolean isNotificationEnabled ( Notification notification ) { if ( ! ( notification instanceof TraceNotification ) ) return false ; if ( minLevel_10 != null ) { // SLEE 1.0 comparison Level traceLevel = ( ( TraceNotification ) notification ) . getLevel ( ) ; return traceLevel != null && ! minLevel_10 . isHigherLevel ( traceLevel ) ; } else { // SLEE 1.1 comparison TraceLevel traceLevel = ( ( TraceNotification ) notification ) . getTraceLevel ( ) ; return traceLevel != null && ! minLevel_11 . isHigherLevel ( traceLevel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the profile table and profile referenced by this profile identifier to new values . [CODESPLIT] public final void setProfileID ( String profileTableName , String profileName ) throws NullPointerException , IllegalArgumentException { if ( profileTableName == null ) throw new NullPointerException ( \"profileTableName is null\" ) ; if ( profileName == null ) throw new NullPointerException ( \"profileName is null\" ) ; if ( profileTableName . indexOf ( ' ' ) >= 0 ) throw new IllegalArgumentException ( \"profileTableName cannot contain the '/' character\" ) ; this . profileTableName = profileTableName ; this . profileName = profileName ; this . address = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > Address< / code > object containing the address form of the profile identified by this profile identifier . [CODESPLIT] public Address toAddress ( ) { if ( address == null ) { address = new Address ( AddressPlan . SLEE_PROFILE , profileTableName + ' ' + profileName ) ; } return address ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void barrierEvent ( EventContext eventContext ) { if ( barriedEvents == null ) { barriedEvents = new LinkedList < EventContext > ( ) ; } barriedEvents . add ( eventContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventContext [ ] removeEventsBarried ( ) { // this is safe because adding events and calling this is ever done by // same executor/thread final EventContext [ ] result = barriedEvents . toArray ( new EventContext [ barriedEvents . size ( ) ] ) ; barriedEvents = null ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public EventRouterExecutor getExecutor ( ActivityContextHandle activityContextHandle ) { return executors [ ( activityContextHandle . hashCode ( ) & Integer . MAX_VALUE ) % executors . length ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > SleeState< / code > object from an integer value . [CODESPLIT] public static SleeState fromInt ( int state ) throws IllegalArgumentException { switch ( state ) { case SLEE_STOPPED : return STOPPED ; case SLEE_STARTING : return STARTING ; case SLEE_RUNNING : return RUNNING ; case SLEE_STOPPING : return STOPPING ; default : throw new IllegalArgumentException ( \"Invalid state: \" + state ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > SleeState< / code > object from a string value . [CODESPLIT] public static SleeState fromString ( String state ) throws NullPointerException , IllegalArgumentException { if ( state == null ) throw new NullPointerException ( \"state is null\" ) ; if ( state . equalsIgnoreCase ( STOPPED_STRING ) ) return STOPPED ; if ( state . equalsIgnoreCase ( STARTING_STRING ) ) return STARTING ; if ( state . equalsIgnoreCase ( RUNNING_STRING ) ) return RUNNING ; if ( state . equalsIgnoreCase ( STOPPING_STRING ) ) return STOPPING ; throw new IllegalArgumentException ( \"Invalid state: \" + state ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "protected DeployableUnitsCard deployableUnitsCard ; [CODESPLIT] private String extractMessage ( String result ) { // Fix:\r // Firefox 2 encapsulates the text inside <pre> tag\r String startPreTag = \"<pre>\" ; String endPreTag = \"</pre>\" ; result = result . trim ( ) ; if ( result . startsWith ( startPreTag ) && result . endsWith ( endPreTag ) ) { result = result . substring ( startPreTag . length ( ) , result . length ( ) - endPreTag . length ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the specified notification should be delivered to notification listeners using this notification filter . [CODESPLIT] public boolean isNotificationEnabled ( Notification notification ) { if ( ! ( notification instanceof AlarmNotification ) ) return false ; synchronized ( knownAlarms ) { clearStaleTimeouts ( ) ; NotificationInfo info = ( NotificationInfo ) knownAlarms . get ( notification ) ; if ( info == null ) { // we've not seen this alarm before, or the period has expired since // the first notification knownAlarms . put ( notification , new NotificationInfo ( System . currentTimeMillis ( ) ) ) ; return false ; } if ( ++ info . count == threshold ) { // passed threshold knownAlarms . remove ( notification ) ; return true ; } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private [CODESPLIT] private void clearStaleTimeouts ( ) { Iterator iterator = knownAlarms . values ( ) . iterator ( ) ; long currentTime = System . currentTimeMillis ( ) ; while ( iterator . hasNext ( ) ) { NotificationInfo info = ( NotificationInfo ) iterator . next ( ) ; // if period has expired remove reference to the notification if ( ( info . firstSeenTime + period ) < currentTime ) { iterator . remove ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs the specified { [CODESPLIT] public void installResourceAdaptorType ( ResourceAdaptorTypeComponent component ) throws DeploymentException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Installing \" + component ) ; } // generate code for aci factory new ResourceAdaptorTypeClassCodeGenerator ( ) . process ( component ) ; // create instance of aci factory and store it in the // component if ( component . getActivityContextInterfaceFactoryConcreteClass ( ) != null ) { try { Constructor < ? > constructor = component . getActivityContextInterfaceFactoryConcreteClass ( ) . getConstructor ( new Class [ ] { SleeContainer . class , ResourceAdaptorTypeID . class } ) ; Object aciFactory = constructor . newInstance ( new Object [ ] { sleeContainer , component . getResourceAdaptorTypeID ( ) } ) ; component . setActivityContextInterfaceFactory ( aciFactory ) ; } catch ( Throwable e ) { throw new SLEEException ( \"unable to create ra type aci factory instance\" , e ) ; } } final ResourceAdaptorTypeID resourceAdaptorTypeID = component . getResourceAdaptorTypeID ( ) ; entitiesPerType . put ( resourceAdaptorTypeID , new HashSet < ResourceAdaptorEntity > ( ) ) ; TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { entitiesPerType . remove ( resourceAdaptorTypeID ) ; } } ; sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) . getAfterRollbackActions ( ) . add ( action ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs the specified { [CODESPLIT] public void installResourceAdaptor ( final ResourceAdaptorComponent component ) throws DeploymentException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Installing \" + component ) ; } new ResourceAdaptorClassCodeGenerator ( ) . process ( component ) ; // if we are in cluster mode we need to add the RA class loader domain to the replication class loader if ( ! sleeContainer . getCluster ( ) . getMobicentsCache ( ) . isLocalMode ( ) ) { final ReplicationClassLoader replicationClassLoader = sleeContainer . getReplicationClassLoader ( ) ; replicationClassLoader . addDomain ( component . getClassLoaderDomain ( ) ) ; final TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; if ( txContext != null ) { TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { replicationClassLoader . removeDomain ( component . getClassLoaderDomain ( ) ) ; } } ; txContext . getAfterRollbackActions ( ) . add ( action ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uninstalls the specified { [CODESPLIT] public void uninstallResourceAdaptorType ( final ResourceAdaptorTypeComponent component ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Uninstalling \" + component ) ; } final ResourceAdaptorTypeID resourceAdaptorTypeID = component . getResourceAdaptorTypeID ( ) ; final TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; TransactionalAction action1 = new TransactionalAction ( ) { public void execute ( ) { entitiesPerType . remove ( resourceAdaptorTypeID ) ; } } ; if ( txContext != null ) { txContext . getAfterCommitActions ( ) . add ( action1 ) ; } else { action1 . execute ( ) ; } // if we are in cluster mode we need to remove the RA class loader domain from the replication class loader if ( ! sleeContainer . getCluster ( ) . getMobicentsCache ( ) . isLocalMode ( ) ) { final ReplicationClassLoader replicationClassLoader = sleeContainer . getReplicationClassLoader ( ) ; TransactionalAction action2 = new TransactionalAction ( ) { public void execute ( ) { replicationClassLoader . removeDomain ( component . getClassLoaderDomain ( ) ) ; } } ; if ( txContext != null ) { txContext . getAfterCommitActions ( ) . add ( action2 ) ; } else { action2 . execute ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uninstalls the specified { [CODESPLIT] public void uninstallResourceAdaptor ( ResourceAdaptorComponent component ) throws DependencyException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Uninstalling \" + component ) ; } for ( ResourceAdaptorEntity raEntity : resourceAdaptorEntities . values ( ) ) { if ( raEntity . getResourceAdaptorID ( ) . equals ( component . getResourceAdaptorID ( ) ) ) { throw new DependencyException ( \"can't uninstall \" + component . getResourceAdaptorID ( ) + \" since ra entity \" + raEntity . getName ( ) + \" refers it\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The contains method . This method returns true if the SBB entity represented by the SBB local object specified by the input argument is a member of this child relation . If the method argument is not an SBB local object is an invalid SBB local object or is an SBB local object whose underlying SBB entity is not a member of this child relation then this method returns false . [CODESPLIT] public boolean contains ( Object object ) { if ( ! ( object instanceof SbbLocalObject ) ) return false ; final SbbLocalObjectImpl sbblocal = ( SbbLocalObjectImpl ) object ; final SbbEntityID sbbEntityId = sbblocal . getSbbEntityId ( ) ; if ( ! idBelongsToChildRelation ( sbbEntityId ) ) { return false ; } return new SbbEntityCacheData ( sbbEntityId , sleeContainer . getCluster ( ) . getMobicentsCache ( ) ) . exists ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public void clear ( ) { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; for ( Iterator it = iterator ( ) ; it . hasNext ( ) ; ) { it . next ( ) ; it . remove ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Spec page 62 The remove methods : clear remove removeAll and retainAll . o These methods may remove SBB entities from the child relation . The input argument specifies which SBB entities will be removed from the child relation or retained in the child relation by specifying the SBB local object or collection of SBB local objects that represent the SBB entities to be removed or retained . o Removing an SBB entity from a child relation initiates a cascading removal of the SBB entity tree rooted by the SBB entity similar to invoking the remove method on an SBB local object that represents the SBB entity . [CODESPLIT] public boolean remove ( Object object ) { sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"removing sbb local object \" + object ) ; } if ( object == null ) throw new NullPointerException ( \"Null arg for remove \" ) ; if ( ! ( object instanceof SbbLocalObject ) ) return false ; final SbbLocalObjectImpl sbbLocalObjectImpl = ( SbbLocalObjectImpl ) object ; if ( ! idBelongsToChildRelation ( sbbLocalObjectImpl . getSbbEntityId ( ) ) && ! sbbLocalObjectImpl . getSbbEntity ( ) . isRemoved ( ) ) { return false ; } else { sbbLocalObjectImpl . remove ( ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns true if all SBB entities represented by the SBB local objects in the collection specified by the input argument are members of this child relation . If the collection contains an object that is not an SBB local object an SBB local object that is invalid or an SBB local object whose underlying SBB entity is not a member of this child relation then this method returns false . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public boolean containsAll ( Collection c ) { if ( c == null ) throw new NullPointerException ( \"null collection!\" ) ; for ( Iterator it = c . iterator ( ) ; it . hasNext ( ) ; ) { if ( ! contains ( it . next ( ) ) ) { return false ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"containsAll : collection = \" + c + \" > all in child relation\" ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removing an SBB entity from a child relation initiates a cascading removal of the SBB entity tree rooted by the SBB entity similar to invoking the remove method on an SBB local object that represents the SBB entity . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public boolean removeAll ( Collection c ) { boolean flag = true ; if ( c == null ) throw new NullPointerException ( \" null collection ! \" ) ; for ( Iterator it = c . iterator ( ) ; it . hasNext ( ) ; ) { flag &= this . remove ( it . next ( ) ) ; } return flag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public boolean retainAll ( Collection c ) { boolean flag = false ; if ( c == null ) throw new NullPointerException ( \" null arg! \" ) ; for ( Iterator it = this . iterator ( ) ; it . hasNext ( ) ; ) { if ( ! c . contains ( it . next ( ) ) ) { flag = true ; it . remove ( ) ; } } return flag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) public Object [ ] toArray ( Object [ ] a ) { if ( a == null ) throw new NullPointerException ( \"null arg!\" ) ; HashSet localObjects = this . getLocalObjects ( ) ; return localObjects . toArray ( a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extension methods [CODESPLIT] private void validateChildName ( String childName ) throws IllegalArgumentException , NullPointerException { if ( childName == null ) { throw new NullPointerException ( \"null child name\" ) ; } if ( childName . isEmpty ( ) ) { throw new IllegalArgumentException ( \"empty child name\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void processArguments ( String [ ] args ) throws CommandException { String sopts = \":rsdi\" ; LongOpt [ ] lopts = { new LongOpt ( \"start\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"stopt\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"shutdown\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"info\" , LongOpt . NO_ARGUMENT , null , ' ' ) , } ; Getopt getopt = new Getopt ( null , args , sopts , lopts ) ; // getopt.setOpterr(false);\r int code ; while ( ( code = getopt . getopt ( ) ) != - 1 ) { switch ( code ) { case ' ' : throw new CommandException ( \"Option requires an argument: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : throw new CommandException ( \"Invalid (or ambiguous) option: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : super . operation = new StartOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new StopOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new ShutdownOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new InfoOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\", found unexpected opt: \" + args [ getopt . getOptind ( ) - 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a <code > FailureReason< / code > object from an integer value . <p > This method returns the singleton objects for the failure reasons defined in this class . For all vendor - defined reason codes ( those greater than 0 in value ) a non - unique <code > FailureReason< / code > object is return encapsulating that value . [CODESPLIT] public static FailureReason fromInt ( int reason ) throws IllegalArgumentException { switch ( reason ) { case REASON_OTHER_REASON : return OTHER_REASON ; case REASON_EVENT_QUEUE_FULL : return EVENT_QUEUE_FULL ; case REASON_EVENT_QUEUE_TIMEOUT : return EVENT_QUEUE_TIMEOUT ; case REASON_SYSTEM_OVERLOAD : return SYSTEM_OVERLOAD ; case REASON_EVENT_MARSHALING_ERROR : return EVENT_MARSHALING_ERROR ; case REASON_FIRING_TRANSACTION_ROLLED_BACK : return FIRING_TRANSACTION_ROLLED_BACK ; default : if ( reason > 0 ) return new FailureReason ( reason ) ; else throw new IllegalArgumentException ( \"Invalid failure reason: \" + reason ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a JMX Object Name property string that uniquely identifies the specified SLEE internal component or subsystem suitable for inclusion in the Object Name of a Usage MBean . This method makes use of the { [CODESPLIT] public static String getUsageMBeanProperties ( String subsystemName ) { if ( subsystemName == null ) throw new NullPointerException ( \"subsystemName is null\" ) ; return SUBSYSTEM_NAME_KEY + ' ' + ObjectName . quote ( subsystemName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare this notification source with the specified object for order . Returns a negative integer zero or a positive integer if this object is less than equal to or greater than the specified object . <p > If <code > obj< / code > is a <code > SubsystemNotification< / code > order is determined by comparing the encapsulated subsystem name . Otherwise if <code > obj< / code > is a <code > NotificationSource< / code > ordering is determined by comparing the class name of this class with the class name of <code > obj< / code > . <p > [CODESPLIT] public int compareTo ( Object obj ) { // can't compare with null if ( obj == null ) throw new NullPointerException ( \"obj is null\" ) ; if ( obj == this ) return 0 ; if ( obj instanceof SubsystemNotification ) { // compare the profile table name SubsystemNotification that = ( SubsystemNotification ) obj ; return this . subsystemName . compareTo ( that . subsystemName ) ; } else { return super . compareTo ( TYPE , obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setBoolean ( Boolean attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setByte ( Byte attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setCharacter ( Character attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setDouble ( Double attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setFloat ( Float attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setInteger ( Integer attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setLong ( Long attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setShort ( Short attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores the attr value converting and storing in the string field of the entity [CODESPLIT] public void setAddress ( Address attrValue ) { if ( attrValue != null ) { setString ( attrValue . toString ( ) ) ; } else { setString ( null ) ; } setSerializable ( attrValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setTimerThreads ( int value ) { if ( this . timerThreads == null ) { logger . info ( \"SLEE Timer facility initiated with \" + value + \" threads.\" ) ; } else { logger . warn ( \"Setting timer facility threads to \" + value + \". If called with server running a stop and start is need to apply changes.\" ) ; } this . timerThreads = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if this Level object represents a level that is higher or more severe that some other Level object . For the purposes of the comparison OFF is considered a higher level than SEVERE . [CODESPLIT] public boolean isHigherLevel ( Level other ) throws NullPointerException { if ( other == null ) throw new NullPointerException ( \"other is null\" ) ; return this . level < other . level ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve deserialisation references so that the singleton property of each enumerated object is preserved . [CODESPLIT] private Object readResolve ( ) throws StreamCorruptedException { if ( level == LEVEL_OFF ) return OFF ; if ( level == LEVEL_SEVERE ) return SEVERE ; if ( level == LEVEL_WARNING ) return WARNING ; if ( level == LEVEL_INFO ) return INFO ; if ( level == LEVEL_CONFIG ) return CONFIG ; if ( level == LEVEL_FINE ) return FINE ; if ( level == LEVEL_FINER ) return FINER ; if ( level == LEVEL_FINEST ) return FINEST ; throw new StreamCorruptedException ( \"Invalid internal state found\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser for the deployment config xml . [CODESPLIT] private void parseDeployConfig ( InputStream deployConfigInputStream , ResourceManagement resourceManagement ) throws SAXException , ParserConfigurationException , IOException { if ( deployConfigInputStream == null ) { throw new NullPointerException ( \"null deploy config input stream\" ) ; } Document doc = null ; try { // Read the file into a Document SchemaFactory schemaFactory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; Schema schema = schemaFactory . newSchema ( DeployConfigParser . class . getClassLoader ( ) . getResource ( \"deploy-config.xsd\" ) ) ; DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; // factory.setValidating(false); factory . setSchema ( schema ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; builder . setErrorHandler ( new ErrorHandler ( ) { public void error ( SAXParseException e ) throws SAXException { logger . error ( \"Error parsing deploy-config.xml\" , e ) ; return ; } public void fatalError ( SAXParseException e ) throws SAXException { logger . error ( \"Fatal error parsing deploy-config.xml\" , e ) ; return ; } public void warning ( SAXParseException e ) throws SAXException { logger . warn ( \"Warning parsing deploy-config.xml\" , e ) ; return ; } } ) ; doc = builder . parse ( deployConfigInputStream ) ; } finally { try { deployConfigInputStream . close ( ) ; } catch ( IOException e ) { logger . error ( \"failed to close deploy config input stream\" , e ) ; } } Map < String , Collection < ManagementAction > > postInstallActions = new HashMap < String , Collection < ManagementAction > > ( ) ; Map < String , Collection < ManagementAction > > preUninstallActions = new HashMap < String , Collection < ManagementAction > > ( ) ; // By now we only care about <ra-entity> nodes NodeList raEntities = doc . getElementsByTagName ( \"ra-entity\" ) ; // The RA identifier String raId = null ; // The collection of Post-Install Actions Collection < ManagementAction > cPostInstallActions = new ArrayList < ManagementAction > ( ) ; // The collection of Pre-Uninstall Actions Collection < ManagementAction > cPreUninstallActions = new ArrayList < ManagementAction > ( ) ; // Iterate through each ra-entity node for ( int i = 0 ; i < raEntities . getLength ( ) ; i ++ ) { Element raEntity = ( Element ) raEntities . item ( i ) ; // Get the component ID ComponentIDPropertyEditor cidpe = new ComponentIDPropertyEditor ( ) ; cidpe . setAsText ( raEntity . getAttribute ( \"resource-adaptor-id\" ) ) ; raId = cidpe . getValue ( ) . toString ( ) ; // The RA Entity Name String entityName = raEntity . getAttribute ( \"entity-name\" ) ; // Select the properties node NodeList propsNodeList = raEntity . getElementsByTagName ( \"properties\" ) ; if ( propsNodeList . getLength ( ) > 1 ) { logger . warn ( \"Invalid ra-entity element, has more than one properties child. Reading only first.\" ) ; } // The properties for this RA ConfigProperties props = new ConfigProperties ( ) ; Element propsNode = ( Element ) propsNodeList . item ( 0 ) ; // Do we have any properties at all? if ( propsNode != null ) { // Select the property elements NodeList propsList = propsNode . getElementsByTagName ( \"property\" ) ; // For each element, add it to the Properties object for ( int j = 0 ; j < propsList . getLength ( ) ; j ++ ) { Element property = ( Element ) propsList . item ( j ) ; String propertyName = property . getAttribute ( \"name\" ) ; String propertyType = property . getAttribute ( \"type\" ) ; String propertyValue = property . getAttribute ( \"value\" ) ; props . addProperty ( new ConfigProperties . Property ( propertyName , propertyType , ConfigProperties . Property . toObject ( propertyType , propertyValue ) ) ) ; } } // Create the Resource Adaptor ID cidpe . setAsText ( raEntity . getAttribute ( \"resource-adaptor-id\" ) ) ; ResourceAdaptorID componentID = ( ResourceAdaptorID ) cidpe . getValue ( ) ; // Add the Create and Activate RA Entity actions to the Post-Install // Actions cPostInstallActions . add ( new CreateResourceAdaptorEntityAction ( componentID , entityName , props , resourceManagement ) ) ; cPostInstallActions . add ( new ActivateResourceAdaptorEntityAction ( entityName , resourceManagement ) ) ; // Each RA might have zero or more links.. get them NodeList links = raEntity . getElementsByTagName ( \"ra-link\" ) ; for ( int j = 0 ; j < links . getLength ( ) ; j ++ ) { String linkName = ( ( Element ) links . item ( j ) ) . getAttribute ( \"name\" ) ; cPostInstallActions . add ( new BindLinkNameAction ( linkName , entityName , resourceManagement ) ) ; cPreUninstallActions . add ( new UnbindLinkNameAction ( linkName , resourceManagement ) ) ; } // Add the Deactivate and Remove RA Entity actions to the // Pre-Uninstall Actions cPreUninstallActions . add ( new DeactivateResourceAdaptorEntityAction ( entityName , resourceManagement ) ) ; cPreUninstallActions . add ( new RemoveResourceAdaptorEntityAction ( entityName , resourceManagement ) ) ; // Finally add the actions to the respective hashmap. if ( raId != null ) { // We need to check if we are updating or adding new ones. if ( postInstallActions . containsKey ( raId ) ) { postInstallActions . get ( raId ) . addAll ( cPostInstallActions ) ; } else { postInstallActions . put ( raId , cPostInstallActions ) ; } // Same here... if ( preUninstallActions . containsKey ( raId ) ) { preUninstallActions . get ( raId ) . addAll ( cPreUninstallActions ) ; } else { preUninstallActions . put ( raId , cPreUninstallActions ) ; } } // recreate the lists for the next round (might come a new RA ID)... cPostInstallActions = new ArrayList < ManagementAction > ( ) ; cPreUninstallActions = new ArrayList < ManagementAction > ( ) ; raId = null ; } this . postInstallActions = Collections . unmodifiableMap ( postInstallActions ) ; this . preUninstallActions = Collections . unmodifiableMap ( preUninstallActions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a list of { [CODESPLIT] public List < ServiceDescriptorImpl > parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; List < ServiceDescriptorImpl > result = new ArrayList < ServiceDescriptorImpl > ( ) ; MServiceXML serviceXML = null ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee . service . ServiceXml ) { serviceXML = new MServiceXML ( ( org . mobicents . slee . container . component . deployment . jaxb . slee . service . ServiceXml ) jaxbPojo ) ; } else if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . service . ServiceXml ) { serviceXML = new MServiceXML ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . service . ServiceXml ) jaxbPojo ) ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } for ( MService mService : serviceXML . getMServices ( ) ) { result . add ( new ServiceDescriptorImpl ( mService ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cleans up the class pool cache [CODESPLIT] public void clean ( ) { for ( ClassPath classPath : classPaths ) { classPool . removeClassPath ( classPath ) ; } for ( String classMade : classesMade ) { try { classPool . get ( classMade ) . detach ( ) ; } catch ( NotFoundException e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Failed to detach class \" + classMade + \" from class pool\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ExternalActivityHandle createActivityHandle ( ) throws ResourceException { if ( sleeContainer == null ) { throw new ResourceException ( \"Connection is in closed state\" ) ; } if ( sleeContainer . getSleeState ( ) != SleeState . RUNNING ) { throw new ResourceException ( \"Container is not in running state.\" ) ; } return sleeContainer . getNullActivityFactory ( ) . createNullActivityHandle ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void fireEvent ( Object event , EventTypeID eventType , ExternalActivityHandle activityHandle , Address address ) throws NullPointerException , UnrecognizedActivityException , UnrecognizedEventException , ResourceException { if ( sleeContainer == null ) { throw new ResourceException ( \"Connection is in closed state\" ) ; } if ( sleeContainer . getSleeState ( ) != SleeState . RUNNING ) { throw new ResourceException ( \"Container is not in running state.\" ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"fireEvent(event=\" + event + \",eventType=\" + eventType + \",activityHandle=\" + activityHandle + \",address=\" + address + \")\" ) ; } if ( event == null ) { throw new NullPointerException ( \"event is null\" ) ; } if ( eventType == null ) { throw new NullPointerException ( \"event type is null\" ) ; } if ( activityHandle == null ) { throw new NullPointerException ( \"activity handle is null\" ) ; } EventTypeComponent eventTypeComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( eventType ) ; if ( eventTypeComponent == null ) { throw new UnrecognizedEventException ( \"event type not installed\" ) ; } if ( ! eventTypeComponent . getEventTypeClass ( ) . isAssignableFrom ( event . getClass ( ) ) ) { logger . info ( \"\" + eventTypeComponent . getEventTypeClass ( ) . toString ( ) ) ; logger . info ( \"\" + eventTypeComponent . getEventTypeClass ( ) . getCanonicalName ( ) ) ; logger . info ( \"\" + Arrays . toString ( eventTypeComponent . getEventTypeClass ( ) . getDeclaredMethods ( ) ) ) ; logger . info ( \"\" + eventTypeComponent . getEventTypeClass ( ) . getClass ( ) . toString ( ) ) ; logger . info ( \"\" + eventTypeComponent . getEventTypeClass ( ) . getClass ( ) . getCanonicalName ( ) ) ; logger . info ( \"\" + event . getClass ( ) . toString ( ) ) ; logger . info ( \"\" + event . getClass ( ) . getCanonicalName ( ) ) ; logger . info ( \"\" + Arrays . toString ( event . getClass ( ) . getDeclaredMethods ( ) ) ) ; logger . info ( \"*\" + eventTypeComponent ) ; logger . info ( \"*\" + eventTypeComponent . getEventTypeID ( ) ) ; logger . info ( \"*\" + event ) ; logger . info ( \"&\" + eventTypeComponent . getClassLoader ( ) ) ; logger . info ( \"&\" + eventTypeComponent . getEventTypeClass ( ) . getClassLoader ( ) ) ; logger . info ( \"&\" + event . getClass ( ) . getClassLoader ( ) ) ; //throw new UnrecognizedEventException(\r //\t\"the class of the event object fired is not assignable to the event class of the event type.\\n\" +\r //\t\" EventClass: \"+event.getClass()+\", component class: \"+eventTypeComponent.getEventTypeClass());\r } if ( ! ( activityHandle instanceof NullActivityHandle ) ) { throw new UnrecognizedActivityException ( activityHandle ) ; } // check container state is running\r SleeContainer sleeContainer = SleeContainer . lookupFromJndi ( ) ; if ( sleeContainer . getSleeState ( ) != SleeState . RUNNING ) { throw new IllegalStateException ( \"Container is not running\" ) ; } SleeTransactionManager txMgr = sleeContainer . getTransactionManager ( ) ; boolean newTx = txMgr . requireTransaction ( ) ; boolean rollback = true ; try { final NullActivityHandle nullActivityHandle = ( NullActivityHandle ) activityHandle ; final ActivityContextHandle ach = nullActivityHandle . getActivityContextHandle ( ) ; ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac == null ) { sleeContainer . getNullActivityFactory ( ) . createNullActivity ( nullActivityHandle , false ) ; ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac == null ) { throw new SLEEException ( \"unable to create null ac for external activity handle \" + activityHandle ) ; } } ac . fireEvent ( eventType , event , address , null , null , null , null ) ; rollback = false ; } catch ( Throwable ex ) { logger . error ( \"Exception in fireEvent!\" , ex ) ; } finally { if ( newTx ) { if ( rollback ) { try { txMgr . rollback ( ) ; } catch ( Throwable e ) { logger . error ( \"failed to rollback implicit tx\" , e ) ; } } else { try { txMgr . commit ( ) ; } catch ( Throwable e ) { logger . error ( \"failed to commit implicit tx\" , e ) ; } } } // else ignore, specs say there is no need to rollback a tx if event\r // queuing failed\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventTypeID getEventTypeID ( String name , String vendor , String version ) throws UnrecognizedEventException , ResourceException { if ( sleeContainer == null ) { throw new ResourceException ( \"Connection is in closed state\" ) ; } if ( sleeContainer . getSleeState ( ) != SleeState . RUNNING ) { throw new ResourceException ( \"Container is not in running state.\" ) ; } EventTypeID eventTypeID = new EventTypeID ( name , vendor , version ) ; EventTypeComponent eventTypeComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( eventTypeID ) ; if ( eventTypeComponent == null ) { throw new UnrecognizedEventException ( \"event type not installed\" ) ; } else { return eventTypeID ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { parentSbbEntityID = ( SbbEntityID ) in . readObject ( ) ; parentChildRelation = in . readUTF ( ) ; childID = in . readUTF ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { out . writeObject ( parentSbbEntityID ) ; out . writeUTF ( parentChildRelation ) ; out . writeUTF ( childID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void processArguments ( String [ ] args ) throws CommandException { //first, we must get atleast -t, possibly -p, depending on those we call different method on ProfileProvisioningMBean\r //String sopts = \":t:p:ldwecrog:s\";\r String sopts = \"-:l:xdwecrog:s\" ; LongOpt [ ] lopts = { //conf part\r //new LongOpt(\"table\", LongOpt.REQUIRED_ARGUMENT, null, 't'),\r //new LongOpt(\"profile\", LongOpt.REQUIRED_ARGUMENT, null, 'p'),\r new LongOpt ( \"noprefix\" , LongOpt . NO_ARGUMENT , null , 0x1000 ) , //operration part\r new LongOpt ( \"list\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"extlist\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"dirty\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"write\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"edit\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"commit\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"restore\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"close\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //get,set,bussines\r new LongOpt ( \"get\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"set\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //options for set\r new LongOpt ( \"name\" , LongOpt . REQUIRED_ARGUMENT , null , SetAttributeOperation . name ) , new LongOpt ( \"separator\" , LongOpt . OPTIONAL_ARGUMENT , null , SetAttributeOperation . separator ) , new LongOpt ( \"value\" , LongOpt . OPTIONAL_ARGUMENT , null , SetAttributeOperation . value ) , //new LongOpt(\"bussines\", LongOpt.NO_ARGUMENT, null, 'b'),\r } ; Getopt getopt = new Getopt ( null , args , sopts , lopts ) ; getopt . setOpterr ( false ) ; int nonOptArgIndex = 0 ; int code ; while ( ( code = getopt . getopt ( ) ) != - 1 ) { switch ( code ) { case ' ' : throw new CommandException ( \"Option requires an argument: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : throw new CommandException ( \"Invalid (or ambiguous) option: \" + args [ getopt . getOptind ( ) - 1 ] ) ; //CONF PART\r //\t\t\tcase 't':\r //\t\t\t\tthis.profileTableName = getopt.getOptarg();\r //\t\t\t\tbreak;\r //\t\t\tcase 'p':\r //\t\t\t\tthis.profileName = getopt.getOptarg();\r //\t\t\t\tbreak;\r // OPERATION PART\r case 0x1000 : break ; case 1 : //non opt args, table and profile name(maybe)\r switch ( nonOptArgIndex ) { case 0 : profileTableName = getopt . getOptarg ( ) ; nonOptArgIndex ++ ; break ; case 1 : profileName = getopt . getOptarg ( ) ; nonOptArgIndex ++ ; break ; default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\" expects at most two non opt arguments!\" ) ; } break ; case ' ' : //list\r super . operation = new ListOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //extlist\r super . operation = new ExtListOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //dirt\r super . operation = new SimpleInvokeOperation ( super . context , super . log , this , \"isProfileDirty\" ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //write\r super . operation = new SimpleInvokeOperation ( super . context , super . log , this , \"isProfileWriteable\" ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //edit\r super . operation = new SimpleInvokeOperation ( super . context , super . log , this , \"editProfile\" ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //commit\r super . operation = new SimpleInvokeOperation ( super . context , super . log , this , \"commitProfile\" ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //restore\r super . operation = new SimpleInvokeOperation ( super . context , super . log , this , \"restoreProfile\" ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //close\r super . operation = new SimpleInvokeOperation ( super . context , super . log , this , \"closeProfile\" ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //get\r super . operation = new GetAttributeOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : //set\r super . operation = new SetAttributeOperation ( super . context , super . log , this ) ; prepareCommand ( ) ; super . operation . buildOperation ( getopt , args ) ; break ; //\t\t\tcase 'b':\r //\t\t\t\t//bussines\r //\t\t\t\tsuper.operation = new BussinesMethodOperation(super.context, super.log, this);\r //\t\t\t\tsuper.operation.buildOperation(getopt, args);\r //\t\t\t\tbreak;\t\r default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\", found unexpected opt: \" + args [ getopt . getOptind ( ) - 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds call to this profile . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static void addProfileCall ( ProfileObjectImpl po ) throws SLEEException { SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; try { if ( sleeTransactionManager . getTransaction ( ) == null ) { return ; } } catch ( SystemException se ) { throw new SLEEException ( \"Unable to verify SLEE Transaction.\" , se ) ; } String key = makeKey ( po ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Recording call to profile. Key[\" + key + \"]\" ) ; } final TransactionContext txContext = sleeTransactionManager . getTransactionContext ( ) ; ProfileCallRecorderTransactionData data = ( ProfileCallRecorderTransactionData ) txContext . getData ( ) . get ( TRANSACTION_CONTEXT_KEY ) ; // If data does not exist, create it\r if ( data == null ) { data = new ProfileCallRecorderTransactionData ( ) ; txContext . getData ( ) . put ( TRANSACTION_CONTEXT_KEY , data ) ; } if ( ! po . isProfileReentrant ( ) ) { // we need to check\r if ( data . invokedProfiles . contains ( key ) && data . invokedProfiles . getLast ( ) . compareTo ( key ) != 0 ) { throw new SLEEException ( \"Detected loopback call. Call sequence: \" + data . invokedProfiles ) ; } data . invokedProfiles . add ( key ) ; data . invokedProfileTablesNames . add ( po . getProfileTable ( ) . getProfileTableName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a profile object for the table and specified profile name there is only one profile object per profile entity per transaction [CODESPLIT] public ProfileObjectImpl getProfile ( String profileName ) throws TransactionRequiredLocalException , SLEEException { Map txData = getTxData ( ) ; ProfileTransactionID key = new ProfileTransactionID ( profileName , profileTable . getProfileTableName ( ) ) ; ProfileObjectImpl value = ( ProfileObjectImpl ) txData . get ( key ) ; if ( value == null ) { ProfileObjectPool pool = profileTable . getProfileManagement ( ) . getObjectPoolManagement ( ) . getObjectPool ( profileTable . getProfileTableName ( ) ) ; value = pool . borrowObject ( ) ; passivateProfileObjectOnTxEnd ( profileTable . getSleeContainer ( ) . getTransactionManager ( ) , value , pool ) ; try { value . profileActivate ( profileName ) ; } catch ( UnrecognizedProfileNameException e ) { value . invalidateObject ( ) ; pool . invalidateObject ( value ) ; return null ; } txData . put ( key , value ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds transactional actions to the active transaction to passivate a profile object . [CODESPLIT] public static void passivateProfileObjectOnTxEnd ( SleeTransactionManager txManager , final ProfileObjectImpl profileObject , final ProfileObjectPool pool ) { TransactionalAction afterRollbackAction = new TransactionalAction ( ) { public void execute ( ) { profileObject . invalidateObject ( ) ; pool . returnObject ( profileObject ) ; } } ; TransactionalAction beforeCommitAction = new TransactionalAction ( ) { public void execute ( ) { if ( profileObject . getState ( ) == ProfileObjectState . READY ) { if ( ! profileObject . getProfileEntity ( ) . isRemove ( ) ) { profileObject . fireAddOrUpdatedEventIfNeeded ( ) ; profileObject . profilePassivate ( ) ; } else { profileObject . profileRemove ( true , false ) ; } pool . returnObject ( profileObject ) ; } } } ; final TransactionContext txContext = txManager . getTransactionContext ( ) ; txContext . getAfterRollbackActions ( ) . add ( afterRollbackAction ) ; txContext . getBeforeCommitActions ( ) . add ( beforeCommitAction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean validate ( ) { boolean passed = true ; try { if ( ! validateDescriptor ( ) ) { // this is quick fail\r passed = false ; return passed ; } // we cant validate some parts on fail here\r if ( ! validateCMPInterface ( ) ) { passed = false ; } else { if ( ! validateProfileTableInterface ( ) ) { passed = false ; } } if ( ! validateProfileLocalInterface ( ) ) { passed = false ; } if ( ! validateProfileManagementInterface ( ) ) { passed = false ; } if ( ! validateAbstractClass ( ) ) { passed = false ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should not be called when CMP interface validation fails cause it depends on result of it [CODESPLIT] boolean validateProfileManagementInterface ( ) { // this is optional\r boolean passed = true ; String errorBuffer = new String ( \"\" ) ; if ( this . component . getProfileManagementInterfaceClass ( ) == null ) { // it can hapen when its not present\r return passed ; } try { Class profileManagementInterfaceClass = this . component . getProfileManagementInterfaceClass ( ) ; if ( ! profileManagementInterfaceClass . isInterface ( ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management interface is not an interface class!!!\" , \"10.10\" , errorBuffer ) ; return passed ; } if ( this . component . isSlee11 ( ) && profileManagementInterfaceClass . getPackage ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management interface must be declared within named package.\" , \"10.10\" , errorBuffer ) ; } if ( ! Modifier . isPublic ( profileManagementInterfaceClass . getModifiers ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management interface must be declaredas public.\" , \"10.10\" , errorBuffer ) ; } // now here comes the fun. methods are subject to restrictions form\r // 10.17 and 10.18, BUT interface may implement or just define CMPs\r // that MUST reasemlbe CMPs definition from CMP interface - that is\r // all getter/setter methods defined\r Set < String > ignore = new HashSet < String > ( ) ; ignore . add ( \"java.lang.Object\" ) ; Map < String , Method > cmpInterfaceMethods = ClassUtils . getAllInterfacesMethods ( this . component . getProfileCmpInterfaceClass ( ) , ignore ) ; Map < String , Method > managementInterfaceMethods = ClassUtils . getAllInterfacesMethods ( profileManagementInterfaceClass , ignore ) ; // we cant simply remove all methods from\r // managementInterfaceMethods.removeAll(cmpInterfaceMethods) since\r // with abstract classes it becomes comp;licated\r // we can have doubling definition with for instance return type or\r // throws clause (as diff) which until concrete class wont be\r // noticed - and is an error....\r // FIXME: does mgmt interface have to define both CMP accessors?\r Iterator < Entry < String , Method > > entryIterator = managementInterfaceMethods . entrySet ( ) . iterator ( ) ; while ( entryIterator . hasNext ( ) ) { Entry < String , Method > entry = entryIterator . next ( ) ; String key = entry . getKey ( ) ; if ( cmpInterfaceMethods . containsKey ( key ) ) { // FIXME: possibly we shoudl iterate over names?\r if ( ! compareMethod ( entry . getValue ( ) , cmpInterfaceMethods . get ( key ) ) ) { // return type or throws clause, or modifiers differ\r passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management interface declares method which has signature simlar to CMP method, but it has different throws clause, return type or modifiers, which is wrong.\" , \"10.10\" , errorBuffer ) ; } } else { // we can have setter/getter like as stand alone ?\r if ( _FORBIDEN_METHODS . contains ( key ) ) { // this is forrbiden, section 10.18\r passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management interface declares method from forbiden list, method: \" + entry . getKey ( ) , \"10.18\" , errorBuffer ) ; continue ; } // is this the right place? This tells validator\r // wheather it should require profile abstract class in\r // case of 1.1\r requiredProfileAbstractClass = true ; // we know that name is ok.\r // FIXME: SPECS Are weird - Management methods may not\r // have the same name and arguments as a Profile CMP\r // field get or set accessor method. <---- ITS CMP\r // METHOD< SIGNATURE IS NAME AND\r // PARAMETERS and its implemented if its doubled from\r // CMP or this interface extends CMP\r // interface.....!!!!!!!!!!!!!!!!!!\r if ( key . startsWith ( \"ejb\" ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management interface declares method with wrong prefix, method: \" + entry . getKey ( ) , \"10.18\" , errorBuffer ) ; continue ; } // there are no reqs other than parameters?\r Class [ ] params = entry . getValue ( ) . getParameterTypes ( ) ; for ( int index = 0 ; index < params . length ; index ++ ) { if ( _ALLOWED_MANAGEMENT_TYPES . contains ( params [ index ] . toString ( ) ) || ClassUtils . checkInterfaces ( params [ index ] , \"java.io.Serializable\" ) != null ) { } else { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management interface declares management method with wrong parameter at index[\" + index + \"], method: \" + entry . getKey ( ) , \"10.18\" , errorBuffer ) ; } } } } } finally { if ( ! passed ) { if ( logger . isEnabledFor ( Level . ERROR ) ) logger . error ( errorBuffer ) ; //System.err.println(errorBuffer);\r } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "shoudl not be run if other interfaces vaildation fails . [CODESPLIT] boolean validateAbstractClass ( ) { boolean passed = true ; String errorBuffer = new String ( \"\" ) ; try { if ( this . component . getDescriptor ( ) . getProfileAbstractClass ( ) == null ) { if ( this . requiredProfileAbstractClass ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management abstract class must be present\" , \"3.X\" , errorBuffer ) ; return passed ; } } else { if ( this . component . getProfileAbstractClass ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile management abstract class has not been loaded\" , \"3.X\" , errorBuffer ) ; return passed ; } } Class profileAbstractClass = this . component . getProfileAbstractClass ( ) ; // FIXME: Alexandre: Added this, was making some tests fail. Review!\r if ( profileAbstractClass == null ) { return passed ; } // if (profileAbstractClass.isInterface()\r // || profileAbstractClass.isEnum()) {\r // passed = false;\r // errorBuffer = appendToBuffer(\r // \"Profile specification profile abstract class in not a clas.\",\r // \"10.11\", errorBuffer);\r // return passed;\r // }\r if ( this . component . isSlee11 ( ) ) { if ( profileAbstractClass . getPackage ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must be defined in package.\" , \"10.11\" , errorBuffer ) ; } // FIXME: what about 1.0 ?\r // public, no arg constructor without throws clause\r Constructor c = null ; try { c = profileAbstractClass . getConstructor ( null ) ; } catch ( Exception e ) { // TODO Auto-generated catch block\r // e.printStackTrace();\r } if ( c == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must define public no arg constructor.\" , \"10.11\" , errorBuffer ) ; } else { if ( ! Modifier . isPublic ( c . getModifiers ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must define public no arg constructor.\" , \"10.11\" , errorBuffer ) ; } if ( c . getExceptionTypes ( ) . length > 0 ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must define public no arg constructor without throws clause.\" , \"10.11\" , errorBuffer ) ; } } } int modifiers = profileAbstractClass . getModifiers ( ) ; if ( ! Modifier . isAbstract ( modifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must be defined abstract.\" , \"10.11\" , errorBuffer ) ; } if ( ! Modifier . isPublic ( modifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must be defined public.\" , \"10.11\" , errorBuffer ) ; } // in case of 1.0 it has to implement as concrete methods from\r // javax.slee.profile.ProfileManagement - section 10.8 of 1.0 specs\r Map < String , Method > requiredLifeCycleMethods = null ; Set < String > ignore = new HashSet < String > ( ) ; ignore . add ( \"java.lang.Object\" ) ; if ( this . component . isSlee11 ( ) ) { Class javaxSleeProfileProfileClass = ClassUtils . checkInterfaces ( profileAbstractClass , \"javax.slee.profile.Profile\" ) ; if ( javaxSleeProfileProfileClass == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement javax.slee.profile.Profile.\" , \"10.11\" , errorBuffer ) ; requiredLifeCycleMethods = ClassUtils . getAllInterfacesMethods ( javax . slee . profile . ProfileLocalObject . class , ignore ) ; } else { requiredLifeCycleMethods = ClassUtils . getAllInterfacesMethods ( javaxSleeProfileProfileClass , ignore ) ; } } else { Class javaxSleeProfileProfileManagement = ClassUtils . checkInterfaces ( profileAbstractClass , \"javax.slee.profile.ProfileManagement\" ) ; if ( javaxSleeProfileProfileManagement == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement javax.slee.profile.ProfileManagement.\" , \"10.8\" , errorBuffer ) ; requiredLifeCycleMethods = ClassUtils . getAllInterfacesMethods ( javax . slee . profile . ProfileManagement . class , ignore ) ; } else { requiredLifeCycleMethods = ClassUtils . getAllInterfacesMethods ( javaxSleeProfileProfileManagement , ignore ) ; } } Map < String , Method > abstractMethods = ClassUtils . getAbstractMethodsFromClass ( profileAbstractClass ) ; Map < String , Method > abstractMethodsFromSuperClasses = ClassUtils . getAbstractMethodsFromSuperClasses ( profileAbstractClass ) ; Map < String , Method > concreteMethods = ClassUtils . getConcreteMethodsFromClass ( profileAbstractClass ) ; Map < String , Method > concreteMethodsFromSuperClasses = ClassUtils . getConcreteMethodsFromSuperClasses ( profileAbstractClass ) ; // FIXME: Alexandre: Verify if this is correct\r // The isProfileDirty, markProfileDirty and  isProfileValid methods must not be \r // implemented as they are implemented by the SLEE. These three methods are implemented by the \r // SLEE at deployment time.  \r Set < String > toBeImplementedBySlee = new HashSet < String > ( ) ; toBeImplementedBySlee . add ( \"isProfileDirty\" ) ; toBeImplementedBySlee . add ( \"markProfileDirty\" ) ; toBeImplementedBySlee . add ( \"isProfileValid\" ) ; for ( Entry < String , Method > entry : requiredLifeCycleMethods . entrySet ( ) ) { Method m = entry . getValue ( ) ; //\r Method methodFromClass = ClassUtils . getMethodFromMap ( m . getName ( ) , m . getParameterTypes ( ) , concreteMethods , concreteMethodsFromSuperClasses ) ; if ( methodFromClass == null ) { if ( this . component . isSlee11 ( ) || ( ! this . component . isSlee11 ( ) && ! toBeImplementedBySlee . contains ( m . getName ( ) ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement certain lifecycle methods. Method not found in concrete(non private) methods: \" + m . getName ( ) , \"10.11\" , errorBuffer ) ; } continue ; } if ( methodFromClass != null && toBeImplementedBySlee . contains ( m . getName ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"[JAIN SLEE 1.0] The \" + m . getName ( ) + \" method must not be implemented as they are implemented by the SLEE.\" , \"10.11\" , errorBuffer ) ; continue ; } // it concrete - must check return type\r if ( ! m . getReturnType ( ) . getName ( ) . equals ( methodFromClass . getReturnType ( ) . getName ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement certain lifecycle methods. Method with name: \" + m . getName ( ) + \" found in concrete(non private) methods has different return type: \" + methodFromClass . getReturnType ( ) + \", than one declared in interface: \" + m . getReturnType ( ) , \"10.11\" , errorBuffer ) ; } if ( ! Arrays . equals ( m . getExceptionTypes ( ) , methodFromClass . getExceptionTypes ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement certain lifecycle methods. Method with name: \" + m . getName ( ) + \" found in concrete(non private) methods has different throws clause than one found in class.\" , \"10.11\" , errorBuffer ) ; } // must be public, not abstract, not final, not static\r modifiers = methodFromClass . getModifiers ( ) ; if ( ! Modifier . isPublic ( modifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement certain lifecycle methods. Method with name: \" + m . getName ( ) + \" found in concrete(non private) methods must be public.\" , \"10.11\" , errorBuffer ) ; } if ( Modifier . isStatic ( modifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement certain lifecycle methods. Method with name: \" + m . getName ( ) + \" found in concrete(non private) methods must not be static.\" , \"10.11\" , errorBuffer ) ; } if ( Modifier . isFinal ( modifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement certain lifecycle methods. Method with name: \" + m . getName ( ) + \" found in concrete(non private) methods must not be final.\" , \"10.11\" , errorBuffer ) ; } // FIXME: native?\r } // in 1.1 and 1.0 it must implement CMP interfaces, but methods\r // defined there MUST stay abstract\r Class profileCMPInterface = ClassUtils . checkInterfaces ( profileAbstractClass , this . component . getProfileCmpInterfaceClass ( ) . getName ( ) ) ; if ( profileCMPInterface == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement profile CMP interface.\" , \"10.11\" , errorBuffer ) ; return passed ; } // abstract class implements CMP Interface, but leaves all methods\r // as abstract\r Map < String , Method > cmpInterfaceMethods = ClassUtils . getAllInterfacesMethods ( profileCMPInterface , ignore ) ; if ( profileCMPInterface == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement defined profile CMP interface.\" , \"10.11\" , errorBuffer ) ; } else { for ( Entry < String , Method > entry : cmpInterfaceMethods . entrySet ( ) ) { Method m = entry . getValue ( ) ; //\r Method methodFromClass = ClassUtils . getMethodFromMap ( m . getName ( ) , m . getParameterTypes ( ) , concreteMethods , concreteMethodsFromSuperClasses ) ; if ( methodFromClass != null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must leave CMP interface methods as abstract, it can not be concrete: \" + m . getName ( ) , \"10.11\" , errorBuffer ) ; continue ; } methodFromClass = ClassUtils . getMethodFromMap ( m . getName ( ) , m . getParameterTypes ( ) , abstractMethods , abstractMethodsFromSuperClasses ) ; // it concrete - must check return type\r if ( m . getReturnType ( ) . getName ( ) . compareTo ( methodFromClass . getReturnType ( ) . getName ( ) ) != 0 ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must not decalre methods from CMP interface with different return type. Method with name: \" + m . getName ( ) + \" found in (non private) class methods has different return type: \" + methodFromClass . getReturnType ( ) + \", than one declared in interface: \" + m . getReturnType ( ) , \"10.11\" , errorBuffer ) ; } if ( ! Arrays . equals ( m . getExceptionTypes ( ) , methodFromClass . getExceptionTypes ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must not change throws clause. Method with name: \" + m . getName ( ) + \" found in (non private) class methods has different throws clause than one found in class.\" , \"10.11\" , errorBuffer ) ; } // FIXME: should we do that?\r abstractMethods . remove ( entry . getKey ( ) ) ; abstractMethodsFromSuperClasses . remove ( entry . getKey ( ) ) ; } } // those checks are......\r // 1.0 and 1.1 if we define management interface we have to\r // implement it, and all methods that are not CMPs\r if ( this . component . getDescriptor ( ) . getProfileManagementInterface ( ) != null ) { Class profileManagementInterfaceClass = this . component . getProfileManagementInterfaceClass ( ) ; // if abstract class and management interface are both defined than abstract class must implement the management interface\r if ( this . component . getProfileAbstractClass ( ) != null && ! profileManagementInterfaceClass . isAssignableFrom ( this . component . getProfileAbstractClass ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile abstract class must implement profile management interface if both are specified\" , \"10.11\" , errorBuffer ) ; } Map < String , Method > profileManagementInterfaceMethods = ClassUtils . getAllInterfacesMethods ( profileManagementInterfaceClass , ignore ) ; // methods except those defined in CMP interface must be\r // concrete\r for ( Entry < String , Method > entry : profileManagementInterfaceMethods . entrySet ( ) ) { Method m = entry . getValue ( ) ; // CMP methods must stay abstract\r // check if this method is the same as in CMP interface is\r // done elsewhere\r // that check shoudl be ok to run this one!!! XXX\r if ( cmpInterfaceMethods . containsKey ( entry . getKey ( ) ) ) { // we do nothing, cmp interface is validate above\r } else { // 10.8/10.11\r Method concreteMethodFromAbstractClass = ClassUtils . getMethodFromMap ( m . getName ( ) , m . getParameterTypes ( ) , concreteMethods , concreteMethodsFromSuperClasses ) ; if ( concreteMethodFromAbstractClass == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement as non private methods from profile management interface other than CMP methods\" , \"10.11\" , errorBuffer ) ; continue ; } int concreteMethodModifiers = concreteMethodFromAbstractClass . getModifiers ( ) ; // public, and cannot be static,abstract, or final.\r if ( ! Modifier . isPublic ( concreteMethodModifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement methods from profile management interface as public, offending method: \" + concreteMethodFromAbstractClass . getName ( ) , \"10.11\" , errorBuffer ) ; } if ( Modifier . isStatic ( concreteMethodModifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement methods from profile management interface as not static, offending method: \" + concreteMethodFromAbstractClass . getName ( ) , \"10.11\" , errorBuffer ) ; } if ( Modifier . isFinal ( concreteMethodModifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement methods from profile management interface as not final, offending method: \" + concreteMethodFromAbstractClass . getName ( ) , \"10.11\" , errorBuffer ) ; } } } } if ( this . component . isSlee11 ( ) ) { // ProfileLocalObject and UsageInterface are domains of 1.1\r // uff, ProfileLocal again that stupid check cross two\r // interfaces and one abstract class.....\r if ( this . component . getDescriptor ( ) . getProfileLocalInterface ( ) != null ) { // abstract class MUST NOT implement it\r if ( ClassUtils . checkInterfaces ( profileAbstractClass , this . component . getDescriptor ( ) . getProfileLocalInterface ( ) . getProfileLocalInterfaceName ( ) ) != null || ClassUtils . checkInterfaces ( profileAbstractClass , \"javax.slee.profile.ProfileLocalObject\" ) != null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must not implement profile local interface in any way(only methods must be implemented)\" , \"10.11\" , errorBuffer ) ; } Class profileLocalObjectClass = this . component . getProfileLocalInterfaceClass ( ) ; ignore . add ( \"javax.slee.profile.ProfileLocalObject\" ) ; Map < String , Method > profileLocalObjectInterfaceMethods = ClassUtils . getAllInterfacesMethods ( profileLocalObjectClass , ignore ) ; ignore . remove ( \"javax.slee.profile.ProfileLocalObject\" ) ; // methods except those defined in CMP interface must be\r // concrete\r for ( Entry < String , Method > entry : profileLocalObjectInterfaceMethods . entrySet ( ) ) { Method m = entry . getValue ( ) ; // CMP methods must stay abstract\r // check if this method is the same as in CMP interface\r // is done elsewhere\r // that check shoudl be ok to run this one!!! XXX\r if ( cmpInterfaceMethods . containsKey ( entry . getKey ( ) ) ) { // we do nothing, cmp interface is validate above\r } else { // 10.8/10.11\r Method concreteMethodFromAbstractClass = ClassUtils . getMethodFromMap ( m . getName ( ) , m . getParameterTypes ( ) , concreteMethods , concreteMethodsFromSuperClasses ) ; if ( concreteMethodFromAbstractClass == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement as non private methods from profile local interface other than CMP methods\" , \"10.11\" , errorBuffer ) ; continue ; } int concreteMethodModifiers = concreteMethodFromAbstractClass . getModifiers ( ) ; // public, and cannot be static,abstract, or final.\r if ( ! Modifier . isPublic ( concreteMethodModifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement methods from profile local interface as public, offending method: \" + concreteMethodFromAbstractClass . getName ( ) , \"10.11\" , errorBuffer ) ; } if ( Modifier . isStatic ( concreteMethodModifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement methods from profile local interface as not static, offending method: \" + concreteMethodFromAbstractClass . getName ( ) , \"10.11\" , errorBuffer ) ; } if ( Modifier . isFinal ( concreteMethodModifiers ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification profile abstract class must implement methods from profile management interface as not final, offending method: \" + concreteMethodFromAbstractClass . getName ( ) , \"10.11\" , errorBuffer ) ; } } } } // usage parameters\r if ( this . component . getDescriptor ( ) . getProfileUsageParameterInterface ( ) != null ) { if ( ! validateProfileUsageInterface ( abstractMethods , abstractMethodsFromSuperClasses ) ) { passed = false ; } } } // FIXME: add check on abstract methods same as in SBB ?\r } finally { if ( ! passed ) { if ( logger . isEnabledFor ( Level . ERROR ) ) logger . error ( errorBuffer ) ; //System.err.println(errorBuffer);\r } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validated descriptor against some basic constraints : all references are correct some fields are declaredproperly no double definitions if proper elements are present - for instance some elements exclude others . [CODESPLIT] boolean validateDescriptor ( ) { boolean passed = true ; String errorBuffer = new String ( \"\" ) ; if ( ! this . component . isSlee11 ( ) ) { return passed ; // there is not much we can do for those oldies.\r } try { HashSet < String > collatorAlliases = new HashSet < String > ( ) ; ProfileSpecificationDescriptorImpl desc = this . component . getDescriptor ( ) ; for ( CollatorDescriptor mc : desc . getCollators ( ) ) { if ( collatorAlliases . contains ( mc . getCollatorAlias ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares collator alias twice: \" + mc . getCollatorAlias ( ) , \"3.3.7\" , errorBuffer ) ; } else { collatorAlliases . add ( mc . getCollatorAlias ( ) ) ; } } // double deifnition of refs is allowed.\r Map < String , ProfileCMPFieldDescriptor > cmpName2Field = new HashMap < String , ProfileCMPFieldDescriptor > ( ) ; for ( ProfileCMPFieldDescriptor c : desc . getProfileCMPInterface ( ) . getCmpFields ( ) ) { if ( ! Character . isLowerCase ( c . getCmpFieldName ( ) . charAt ( 0 ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares wrong cmp field name, first char is not lower case, field: \" + c . getCmpFieldName ( ) , \"3.3.7\" , errorBuffer ) ; } if ( cmpName2Field . containsKey ( c . getCmpFieldName ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares cmp field twice: \" + c . getCmpFieldName ( ) , \"3.3.7\" , errorBuffer ) ; } else { cmpName2Field . put ( c . getCmpFieldName ( ) , c ) ; } if ( c . getUniqueCollatorRef ( ) != null && ! collatorAlliases . contains ( c . getUniqueCollatorRef ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares cmp field: \" + c . getCmpFieldName ( ) + \", with wrong collator reference: \" + c . getUniqueCollatorRef ( ) , \"3.3.7\" , errorBuffer ) ; } for ( IndexHintDescriptor indexHint : c . getIndexHints ( ) ) { if ( indexHint . getCollatorRef ( ) != null && ! collatorAlliases . contains ( indexHint . getCollatorRef ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares cmp field: \" + c . getCmpFieldName ( ) + \", with index hint declaring wrong collator reference: \" + c . getUniqueCollatorRef ( ) , \"3.3.7\" , errorBuffer ) ; } } } Set < String > queriesNames = new HashSet < String > ( ) ; for ( QueryDescriptor mq : desc . getQueryElements ( ) ) { if ( queriesNames . contains ( mq . getName ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares queries with the same name: \" + mq . getName ( ) , \"3.3.7\" , errorBuffer ) ; } else { // FIXME: all declaredparameters have to be used in\r // expressions?\r HashSet < String > decalredParameters = new HashSet < String > ( ) ; HashSet < String > usedParameters = new HashSet < String > ( ) ; for ( QueryParameterDescriptor mqp : mq . getQueryParameters ( ) ) { if ( decalredParameters . contains ( mqp . getName ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares query parameter twice, parameter name: \" + mqp . getName ( ) + \", in query: \" + mq . getName ( ) , \"3.3.7\" , errorBuffer ) ; } else { decalredParameters . add ( mqp . getName ( ) ) ; } } if ( ! validateExpression ( mq . getName ( ) , mq . getQueryExpression ( ) , usedParameters , cmpName2Field . keySet ( ) , collatorAlliases ) ) { passed = false ; } if ( ! usedParameters . containsAll ( decalredParameters ) && ! decalredParameters . containsAll ( usedParameters ) ) { passed = false ; decalredParameters . retainAll ( usedParameters ) ; errorBuffer = appendToBuffer ( \"Profile specification declares query parameter that are not used, in query: \" + mq . getName ( ) + \", not used parameters: \" + Arrays . toString ( decalredParameters . toArray ( ) ) , \"3.3.7\" , errorBuffer ) ; } } } // FIXME: this should be here or not?\r if ( ! validateEnvEntries ( ) ) { passed = false ; } } finally { if ( ! passed ) { if ( logger . isEnabledFor ( Level . ERROR ) ) logger . error ( errorBuffer ) ; //System.err.println(errorBuffer);\r } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks expression to check if collator refs and cmp fields are referenced correctly . type constraints are checked later . Since in case of lack of parameter we have to relly totaly on CMP field type . Additionaly this check if parameter and value are present together . [CODESPLIT] boolean validateExpression ( String queryName , QueryExpressionDescriptor expression , Set < String > usedQueryParameter , Set < String > cmpFieldNames , Set < String > collatorAliasses ) { boolean passed = true ; String attributeName = null ; String collatorRef = null ; String parameter = null ; String value = null ; boolean ignoreAbsence = false ; // We dont have access to type of cmp, we just simply check parameter\r String errorBuffer = new String ( \"\" ) ; try { switch ( expression . getType ( ) ) { // \"complex types\"\r case And : for ( QueryExpressionDescriptor mqe : expression . getAnd ( ) ) { if ( ! validateExpression ( queryName , mqe , usedQueryParameter , cmpFieldNames , collatorAliasses ) ) { passed = false ; } } break ; case Or : for ( QueryExpressionDescriptor mqe : expression . getOr ( ) ) { if ( ! validateExpression ( queryName , mqe , usedQueryParameter , cmpFieldNames , collatorAliasses ) ) { passed = false ; } } break ; // \"simple\" types\r case Not : // this is one akward case :)\r if ( ! validateExpression ( queryName , expression . getNot ( ) , usedQueryParameter , cmpFieldNames , collatorAliasses ) ) { passed = false ; } break ; case Compare : attributeName = expression . getCompare ( ) . getAttributeName ( ) ; collatorRef = expression . getCompare ( ) . getCollatorRef ( ) ; parameter = expression . getCompare ( ) . getParameter ( ) ; value = expression . getCompare ( ) . getValue ( ) ; break ; case HasPrefix : attributeName = expression . getHasPrefix ( ) . getAttributeName ( ) ; collatorRef = expression . getHasPrefix ( ) . getCollatorRef ( ) ; parameter = expression . getHasPrefix ( ) . getParameter ( ) ; value = expression . getHasPrefix ( ) . getValue ( ) ; break ; case LongestPrefixMatch : attributeName = expression . getLongestPrefixMatch ( ) . getAttributeName ( ) ; collatorRef = expression . getLongestPrefixMatch ( ) . getCollatorRef ( ) ; parameter = expression . getLongestPrefixMatch ( ) . getParameter ( ) ; value = expression . getLongestPrefixMatch ( ) . getValue ( ) ; break ; case RangeMatch : attributeName = expression . getRangeMatch ( ) . getAttributeName ( ) ; collatorRef = expression . getRangeMatch ( ) . getCollatorRef ( ) ; RangeMatchDescriptor mrm = expression . getRangeMatch ( ) ; ignoreAbsence = true ; if ( mrm . getFromParameter ( ) == null && mrm . getFromValue ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query wrong properties, either fromValue or fromParameter can be present, query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( mrm . getFromParameter ( ) != null && mrm . getFromValue ( ) != null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query wrong properties, either fromValue or fromParameter can be present, not both, query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( mrm . getToParameter ( ) == null && mrm . getToValue ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query wrong properties, either toValue or toParameter can be present, query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( mrm . getToParameter ( ) != null && mrm . getToValue ( ) != null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query wrong properties, either toValue or toParameter can be present, not both, query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( mrm . getFromParameter ( ) != null ) { usedQueryParameter . add ( mrm . getFromParameter ( ) ) ; } if ( mrm . getToParameter ( ) != null ) { usedQueryParameter . add ( mrm . getToParameter ( ) ) ; } break ; } //This will hapen for Not,And, Or operators\r if ( attributeName != null ) { if ( ! Character . isLowerCase ( attributeName . charAt ( 0 ) ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query usage of cmp attribute that is not valid cmp identifier, declared cmp field: \" + attributeName + \", query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } else if ( ! cmpFieldNames . contains ( attributeName ) && ! checkForCmpMethodFromFieldName ( attributeName ) ) { //we have to check this. stupid specs for profile cmps are not so strict..... You can defined CMP methods but not define them in descriptor.....!!!!!!!\r passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query usage of cmp field that does not exist(its not declared in descritpro and in cmp interface), declared cmp field: \" + attributeName + \", query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( collatorRef != null && ! collatorAliasses . contains ( collatorRef ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query usage of collator that is not aliased, collator alias: \" + collatorRef + \", query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( ! ignoreAbsence && parameter != null && value != null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query wrong properties, value and parameter can not be present at the same time, query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( ! ignoreAbsence && parameter == null && value == null ) { passed = false ; errorBuffer = appendToBuffer ( \"Profile specification declares in static query wrong properties, either value or parameter must be present, query name: \" + queryName , \"10.20.2\" , errorBuffer ) ; } if ( parameter != null ) { usedQueryParameter . add ( parameter ) ; } } } finally { if ( ! passed ) { if ( logger . isEnabledFor ( Level . ERROR ) ) logger . error ( errorBuffer ) ; //System.err.println(errorBuffer);\r } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the element as text value parse it and setValue . The separator is CID_SEPARATOR [CODESPLIT] public void setAsText ( String text ) { if ( text == null || text . equals ( \"\" ) ) { super . setValue ( new ComponentID [ 0 ] ) ; } else { java . util . ArrayList results = new java . util . ArrayList ( ) ; // the format for component ID is name vendor version.\r java . util . StringTokenizer st = new java . util . StringTokenizer ( text , CID_SEPARATOR , true ) ; ComponentIDPropertyEditor cidPropEditor = new ComponentIDPropertyEditor ( ) ; while ( st . hasMoreTokens ( ) ) { cidPropEditor . setAsText ( st . nextToken ( ) ) ; if ( st . hasMoreTokens ( ) ) { st . nextToken ( ) ; } results . add ( cidPropEditor . getValue ( ) ) ; } ComponentID [ ] cid = new ComponentID [ results . size ( ) ] ; results . toArray ( cid ) ; this . setValue ( cid ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void execute ( Runnable task ) { if ( stats == null ) { executor . execute ( task ) ; } else { executor . execute ( new MiscTaskStatsCollector ( task ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void executeNow ( Runnable task ) throws InterruptedException , ExecutionException { if ( stats == null ) { executor . submit ( task ) . get ( ) ; } else { executor . submit ( new MiscTaskStatsCollector ( task ) ) . get ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void routeEvent ( EventContext event ) { final EventRoutingTaskImpl eventRoutingTask = new EventRoutingTaskImpl ( event , sleeContainer ) ; if ( stats == null ) { executor . execute ( eventRoutingTask ) ; } else { executor . execute ( new EventRoutingTaskStatsCollector ( eventRoutingTask ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------- MANAGEMENT OPERATIONS [CODESPLIT] public void createResourceAdaptorEntity ( ResourceAdaptorID id , String entityName , ConfigProperties properties ) throws NullPointerException , InvalidArgumentException , UnrecognizedResourceAdaptorException , ResourceAdaptorEntityAlreadyExistsException , InvalidConfigurationException , ManagementException { try { synchronized ( getSleeContainer ( ) . getManagementMonitor ( ) ) { resourceManagement . createResourceAdaptorEntity ( id , entityName , properties ) ; } } catch ( NullPointerException e ) { throw e ; } catch ( InvalidArgumentException e ) { throw e ; } catch ( UnrecognizedResourceAdaptorException e ) { throw e ; } catch ( ResourceAdaptorEntityAlreadyExistsException e ) { throw e ; } catch ( InvalidConfigurationException e ) { throw e ; } catch ( Throwable e ) { String s = \"failed to create RA entity with name \" + entityName ; logger . error ( s , e ) ; throw new ManagementException ( s , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the Activity Context Interface Class [CODESPLIT] public Class generateActivityContextInterfaceConcreteClass ( ) throws DeploymentException { String tmpClassName = ConcreteClassGeneratorUtils . CONCRETE_ACTIVITY_INTERFACE_CLASS_NAME_PREFIX + activityContextInterfaceName + ConcreteClassGeneratorUtils . CONCRETE_ACTIVITY_INTERFACE_CLASS_NAME_SUFFIX ; concreteActivityContextInterface = pool . makeClass ( tmpClassName ) ; CtClass sbbActivityContextInterface = null ; try { activityContextInterface = pool . get ( activityContextInterfaceName ) ; sbbActivityContextInterface = pool . get ( SbbActivityContextInterfaceImpl . class . getName ( ) ) ; } catch ( NotFoundException nfe ) { throw new DeploymentException ( \"Could not find aci \" + activityContextInterfaceName , nfe ) ; } // Generates the extends link\r ConcreteClassGeneratorUtils . createInheritanceLink ( concreteActivityContextInterface , sbbActivityContextInterface ) ; // Generates the implements link\r ConcreteClassGeneratorUtils . createInterfaceLinks ( concreteActivityContextInterface , new CtClass [ ] { activityContextInterface } ) ; // Generates the methods to implement from the interface\r Map interfaceMethods = ClassUtils . getInterfaceMethodsFromInterface ( activityContextInterface ) ; generateConcreteMethods ( interfaceMethods ) ; // generates the class\r String sbbDeploymentPathStr = deployDir ; try { concreteActivityContextInterface . writeFile ( sbbDeploymentPathStr ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Concrete Class \" + tmpClassName + \" generated in the following path \" + sbbDeploymentPathStr ) ; } } catch ( Exception e ) { logger . error ( \"problem generating concrete class\" , e ) ; throw new DeploymentException ( \"problem generating concrete class! \" , e ) ; } // load the class\r Class clazz = null ; try { clazz = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( tmpClassName ) ; } catch ( Exception e1 ) { logger . error ( \"problem loading generated class\" , e1 ) ; throw new DeploymentException ( \"problem loading the generated class! \" , e1 ) ; } this . concreteActivityContextInterface . defrost ( ) ; return clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the concrete methods of the class It generates a specific method implementation for the javax . slee . ActivityContextInterface methods for the methods coming from the ActivityContextInterface developer the call is routed to the base asbtract class [CODESPLIT] private void generateConcreteMethods ( Map interfaceMethods ) { if ( interfaceMethods == null ) return ; Iterator it = interfaceMethods . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { CtMethod interfaceMethod = ( CtMethod ) it . next ( ) ; if ( interfaceMethod != null //&& isBaseInterfaceMethod(interfaceMethod.getName()))\r && ( interfaceMethod . getDeclaringClass ( ) . getName ( ) . equals ( javax . slee . ActivityContextInterface . class . getName ( ) ) || interfaceMethod . getDeclaringClass ( ) . getName ( ) . equals ( ActivityContextInterfaceExt . class . getName ( ) ) ) ) continue ; // @todo: need to check args also\r try { // copy method from abstract to concrete class\r CtMethod concreteMethod = CtNewMethod . copy ( interfaceMethod , concreteActivityContextInterface , null ) ; // create the method body\r String fieldName = interfaceMethod . getName ( ) . substring ( 3 ) ; fieldName = fieldName . substring ( 0 , 1 ) . toLowerCase ( ) + fieldName . substring ( 1 ) ; String concreteMethodBody = null ; if ( interfaceMethod . getName ( ) . startsWith ( \"get\" ) ) { concreteMethodBody = \"{ return ($r)getFieldValue(\\\"\" + fieldName + \"\\\",\" + concreteMethod . getReturnType ( ) . getName ( ) + \".class); }\" ; } else if ( interfaceMethod . getName ( ) . startsWith ( \"set\" ) ) { concreteMethodBody = \"{ setFieldValue(\\\"\" + fieldName + \"\\\",$1); }\" ; } else { throw new SLEEException ( \"unexpected method name <\" + interfaceMethod . getName ( ) + \"> to implement in sbb aci interface\" ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Generated method \" + interfaceMethod . getName ( ) + \" , body = \" + concreteMethodBody ) ; } concreteMethod . setBody ( concreteMethodBody ) ; concreteActivityContextInterface . addMethod ( concreteMethod ) ; } catch ( Exception cce ) { throw new SLEEException ( \"Cannot compile method \" + interfaceMethod . getName ( ) , cce ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO [CODESPLIT] private static ProfileEntityArrayAttributeValue newProfileEntityArrayAttributeValueInstance ( Class < ? > profileAttrArrayValueClass , ProfileEntity owner ) { ProfileEntityArrayAttributeValue profileAttrArrayValue = null ; try { profileAttrArrayValue = ( ProfileEntityArrayAttributeValue ) profileAttrArrayValueClass . newInstance ( ) ; profileAttrArrayValue . setProfileEntity ( owner ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } return profileAttrArrayValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String getLoggingConfiguration ( String profile ) throws ManagementException { try { return readFile ( getLog4jPath ( profile )) ; } catch ( IOException ioe ) { throw new ManagementException ( Failed to read log4j configuration file for profile + profile + . Does it exists? ioe ) ; } } [CODESPLIT] private String getLog4jPath ( String profile ) { return ( profile == null || profile . equals ( \"\" ) || profile . equalsIgnoreCase ( \"current\" ) ) ? log4jConfigFilePath : log4jTemplatesPath + profile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare this alarm with the specified object for order . Returns a negative integer zero or a positive integer if this object is less than equal to or greater than the specified object . <p > Alarm ordering is determined by comparing unique the alarm identifier . [CODESPLIT] public int compareTo ( Object obj ) { if ( obj == this ) return 0 ; if ( ! ( obj instanceof Alarm ) ) throw new ClassCastException ( \"Not a javax.slee.management.Alarm: \" + obj ) ; Alarm that = ( Alarm ) obj ; // compare alarm identifiers return this . alarmID . compareTo ( that . alarmID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JAIN SLEE specs descriptor [CODESPLIT] public javax . slee . resource . ResourceAdaptorDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { final LibraryID [ ] libraryIDs = descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) ; final ResourceAdaptorTypeID [ ] raTypeIDs = descriptor . getResourceAdaptorTypeRefs ( ) . toArray ( new ResourceAdaptorTypeID [ descriptor . getResourceAdaptorTypeRefs ( ) . size ( ) ] ) ; Set < ProfileSpecificationID > profileSpecSet = new HashSet < ProfileSpecificationID > ( ) ; for ( ProfileSpecRefDescriptor mProfileSpecRef : descriptor . getProfileSpecRefs ( ) ) { profileSpecSet . add ( mProfileSpecRef . getComponentID ( ) ) ; } ProfileSpecificationID [ ] profileSpecs = profileSpecSet . toArray ( new ProfileSpecificationID [ profileSpecSet . size ( ) ] ) ; specsDescriptor = new javax . slee . resource . ResourceAdaptorDescriptor ( getResourceAdaptorID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , libraryIDs , raTypeIDs , profileSpecs , getDescriptor ( ) . getSupportsActiveReconfiguration ( ) ) ; } return specsDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of the { @link ConfigProperties } for this component [CODESPLIT] public ConfigProperties getDefaultConfigPropertiesInstance ( ) { ConfigProperties defaultProperties = new ConfigProperties ( ) ; for ( ConfigPropertyDescriptor mConfigProperty : getDescriptor ( ) . getConfigProperties ( ) ) { Object configPropertyValue = mConfigProperty . getConfigPropertyValue ( ) == null ? null : ConfigProperties . Property . toObject ( mConfigProperty . getConfigPropertyType ( ) , mConfigProperty . getConfigPropertyValue ( ) ) ; defaultProperties . addProperty ( new ConfigProperties . Property ( mConfigProperty . getConfigPropertyName ( ) , mConfigProperty . getConfigPropertyType ( ) , configPropertyValue ) ) ; } return defaultProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the { @link ActivityFlags } for this activity context [CODESPLIT] public int getActivityFlags ( ) { if ( flags == null ) { // instance has no flags stored, check local ac if ( localActivityContext != null ) { flags = localActivityContext . getActivityFlags ( ) ; } else { // local ac does not exists, get from cache flags = ( Integer ) cacheData . getObject ( NODE_MAP_KEY_ACTIVITY_FLAGS ) ; } } return flags != null ? flags : ActivityFlags . NO_FLAGS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a shared data item for the ACI [CODESPLIT] public void setDataAttribute ( String key , Object newValue ) { cacheData . setCmpAttribute ( key , newValue ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Activity context with handle \" + getActivityContextHandle ( ) + \" set cmp attribute named \" + key + \" to value \" + newValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a naming binding to this activity context . [CODESPLIT] public void addNameBinding ( String aciName ) { cacheData . nameBound ( aciName ) ; if ( acReferencesHandler != null ) { acReferencesHandler . nameReferenceCreated ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is called to release all the name bindings after the activity end event is delivered to the sbb . [CODESPLIT] private void removeNamingBindings ( ) { ActivityContextNamingFacility acf = sleeContainer . getActivityContextNamingFacility ( ) ; for ( Object obj : cacheData . getNamesBoundCopy ( ) ) { String aciName = ( String ) obj ; try { acf . removeName ( aciName ) ; } catch ( Exception e ) { logger . warn ( \"failed to unbind name: \" + aciName + \" from ac:\" + getActivityContextHandle ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the given name to the set of activity context names that we are bound to . The AC Naming facility implicitly ends the activity after all names are unbound . [CODESPLIT] public boolean removeNameBinding ( String aciName ) { boolean removed = cacheData . nameUnbound ( aciName ) ; if ( removed && acReferencesHandler != null ) { acReferencesHandler . nameReferenceRemoved ( ) ; } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attach the given timer to the current activity context . [CODESPLIT] public boolean attachTimer ( TimerID timerID ) { if ( cacheData . attachTimer ( timerID ) ) { if ( acReferencesHandler != null ) { acReferencesHandler . timerReferenceCreated ( ) ; } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detach timer [CODESPLIT] public boolean detachTimer ( TimerID timerID ) { boolean detached = cacheData . detachTimer ( timerID ) ; if ( detached && acReferencesHandler != null ) { acReferencesHandler . timerReferenceRemoved ( ) ; } return detached ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "End Event has been delivered on the Activity Context . [CODESPLIT] private void removeFromTimers ( ) { TimerFacility timerFacility = sleeContainer . getTimerFacility ( ) ; // Iterate through the attached timers, telling the timer facility to // remove them for ( Object obj : cacheData . getAttachedTimers ( ) ) { timerFacility . cancelTimer ( ( TimerID ) obj , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "attach an sbb entity to this AC . [CODESPLIT] public boolean attachSbbEntity ( SbbEntityID sbbEntityId ) { boolean attached = cacheData . attachSbbEntity ( sbbEntityId ) ; if ( attached ) { if ( acReferencesHandler != null ) { acReferencesHandler . sbbeReferenceCreated ( false ) ; } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Attachement from sbb entity \" + sbbEntityId + \" to AC \" + getActivityContextHandle ( ) + \" result: \" + attached ) ; } return attached ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detach the sbb entity [CODESPLIT] public void detachSbbEntity ( SbbEntityID sbbEntityId ) throws javax . slee . TransactionRequiredLocalException { boolean detached = cacheData . detachSbbEntity ( sbbEntityId ) ; if ( detached && acReferencesHandler != null && ! isEnding ( ) ) { acReferencesHandler . sbbeReferenceRemoved ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Detached sbb entity \" + sbbEntityId + \" from AC with handle \" + getActivityContextHandle ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get an ordered copy of the set of SBBs attached to this ac . The ordering is by SBB priority . [CODESPLIT] public Set < SbbEntityID > getSortedSbbAttachmentSet ( Set < SbbEntityID > excludeSet ) { final Set < SbbEntityID > sbbAttachementSet = cacheData . getSbbEntitiesAttached ( ) ; Set < SbbEntityID > result = new HashSet < SbbEntityID > ( ) ; for ( SbbEntityID sbbEntityId : sbbAttachementSet ) { if ( ! excludeSet . contains ( sbbEntityId ) ) { result . add ( sbbEntityId ) ; } } if ( result . size ( ) > 1 ) { result = sleeContainer . getSbbEntityFactory ( ) . sortByPriority ( result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- private helpers [CODESPLIT] private void updateLastAccessTime ( boolean creation ) { if ( creation ) { cacheData . putObject ( NODE_MAP_KEY_LAST_ACCESS , Long . valueOf ( System . currentTimeMillis ( ) ) ) ; } else { ActivityManagementConfiguration configuration = factory . getConfiguration ( ) ; Long lastUpdate = ( Long ) cacheData . getObject ( NODE_MAP_KEY_LAST_ACCESS ) ; if ( lastUpdate != null ) { final long now = System . currentTimeMillis ( ) ; if ( ( now - configuration . getMinTimeBetweenUpdatesInMs ( ) ) > lastUpdate . longValue ( ) ) { // last update if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Updating access time for AC with handle \" + getActivityContextHandle ( ) ) ; } cacheData . putObject ( NODE_MAP_KEY_LAST_ACCESS , Long . valueOf ( now ) ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Skipping update of access time for AC with handle \" + getActivityContextHandle ( ) ) ; } } } else { cacheData . putObject ( NODE_MAP_KEY_LAST_ACCESS , Long . valueOf ( System . currentTimeMillis ( ) ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Updating access time for AC with handle \" + getActivityContextHandle ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void fireEvent ( EventTypeID eventTypeId , Object event , Address address , ServiceID serviceID , EventProcessingSucceedCallback succeedCallback , EventProcessingFailedCallback failedCallback , EventUnreferencedCallback unreferencedCallback ) throws ActivityIsEndingException , SLEEException { if ( isEnding ( ) ) { throw new ActivityIsEndingException ( getActivityContextHandle ( ) . toString ( ) ) ; } if ( acReferencesHandler != null ) { acReferencesHandler . eventReferenceCreated ( ) ; } fireEvent ( sleeContainer . getEventContextFactory ( ) . createEventContext ( eventTypeId , event , this , address , serviceID , succeedCallback , failedCallback , unreferencedCallback ) , sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ends the activity context . [CODESPLIT] public void endActivity ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Ending activity context with handle \" + getActivityContextHandle ( ) ) ; } if ( cacheData . setEnding ( true ) ) { fireEvent ( sleeContainer . getEventContextFactory ( ) . createActivityEndEventContext ( this , new ActivityEndEventUnreferencedCallback ( getActivityContextHandle ( ) , factory ) ) , sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adder method for a Deployable Component . [CODESPLIT] public void addComponent ( DeployableComponent dc ) { if ( logger . isTraceEnabled ( ) ) logger . trace ( \"Adding Component \" + dc . getComponentKey ( ) ) ; // Add the component ..\r components . add ( dc ) ; // .. the key ..\r componentIDs . add ( dc . getComponentKey ( ) ) ; // .. the dependencies ..\r dependencies . addAll ( dc . getDependencies ( ) ) ; // .. the install actions to be taken ..\r installActions . addAll ( dc . getInstallActions ( ) ) ; // .. post-install actions (if any) ..\r Collection < ManagementAction > postInstallActionsStrings = postInstallActions . remove ( dc . getComponentKey ( ) ) ; if ( postInstallActionsStrings != null && ! postInstallActionsStrings . isEmpty ( ) ) { installActions . addAll ( postInstallActionsStrings ) ; } // .. pre-uninstall actions (if any) ..\r Collection < ManagementAction > preUninstallActionsStrings = preUninstallActions . remove ( dc . getComponentKey ( ) ) ; if ( preUninstallActionsStrings != null ) uninstallActions . addAll ( preUninstallActionsStrings ) ; // .. and finally the uninstall actions to the DU.\r uninstallActions . addAll ( dc . getUninstallActions ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for obtaining the external dependencies for this DU if any . [CODESPLIT] public Collection < String > getExternalDependencies ( ) { // Take all dependencies...\r Collection < String > externalDependencies = new HashSet < String > ( dependencies ) ; // Remove those which are contained in this DU\r externalDependencies . removeAll ( componentIDs ) ; // Return what's left.\r return externalDependencies ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for checking if the DU has all the dependencies needed to be deployed . [CODESPLIT] public boolean hasDependenciesSatisfied ( boolean showMissing ) { // First of all check if it is self-sufficient\r if ( isSelfSufficient ( ) ) return true ; // If not self-sufficient, get the remaining dependencies\r Collection < String > externalDependencies = getExternalDependencies ( ) ; // Remove those that are already installed...\r externalDependencies . removeAll ( sleeContainerDeployer . getDeploymentManager ( ) . getDeployedComponents ( ) ) ; // Some remaining?\r if ( ! externalDependencies . isEmpty ( ) ) { if ( showMissing ) { // List them to the user...\r String missingDepList = \"\" ; for ( String missingDep : externalDependencies ) missingDepList += \" \\ r \\ n + -- \" + missingDep ; logger . info ( \"Missing dependencies for \" + this . diShortName + \":\" + missingDepList ) ; } // Return dependencies not satified.\r return false ; } // OK, dependencies satisfied!\r return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for checking if this DU contains any component that is already deployed . [CODESPLIT] public boolean hasDuplicates ( ) { ArrayList < String > duplicates = new ArrayList < String > ( ) ; // For each component in the DU ..\r for ( String componentId : componentIDs ) { // Check if it is already deployed\r if ( sleeContainerDeployer . getDeploymentManager ( ) . getDeployedComponents ( ) . contains ( componentId ) ) { duplicates . add ( componentId ) ; } } if ( ! duplicates . isEmpty ( ) ) { logger . warn ( \"The deployable unit '\" + this . diShortName + \"' contains components that are already deployed. The following are already installed:\" ) ; for ( String dupComponent : duplicates ) { logger . warn ( \" - \" + dupComponent ) ; } return true ; } // If we got here, there's no dups.\r return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Getter for the Install Actions . [CODESPLIT] public Collection < ManagementAction > getInstallActions ( ) { ArrayList < ManagementAction > iActions = new ArrayList < ManagementAction > ( ) ; // if we have some remaining post install actions it means it is actions related with components already installed\r // thus should be executed first\r if ( ! postInstallActions . values ( ) . isEmpty ( ) ) { for ( String componentId : postInstallActions . keySet ( ) ) { iActions . addAll ( postInstallActions . get ( componentId ) ) ; } } iActions . addAll ( installActions ) ; return iActions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Getter for the Uninstall Actions . [CODESPLIT] public Collection < ManagementAction > getUninstallActions ( ) { Collection < ManagementAction > uActions = new ArrayList < ManagementAction > ( uninstallActions ) ; // ensures uninstall is the last action related with DU components\r uActions . add ( new UninstallDeployableUnitAction ( diURL . toString ( ) , sleeContainerDeployer . getDeploymentMBean ( ) ) ) ; // if we have some remaining uninstall actions it means it is actions related with components not in DU\r // thus should be executed last\r if ( ! preUninstallActions . values ( ) . isEmpty ( ) ) { for ( String componentId : preUninstallActions . keySet ( ) ) { uActions . addAll ( preUninstallActions . get ( componentId ) ) ; } } return uActions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for checking if this DU components are referred by any others . [CODESPLIT] private boolean hasReferringDU ( ) throws Exception { // Get SleeContainer instance from JNDI\r SleeContainer sC = SleeContainer . lookupFromJndi ( ) ; for ( String componentIdString : this . getComponents ( ) ) { ComponentIDPropertyEditor cidpe = new ComponentIDPropertyEditor ( ) ; cidpe . setAsText ( componentIdString ) ; ComponentID componentId = ( ComponentID ) cidpe . getValue ( ) ; for ( ComponentID referringComponentId : sC . getComponentRepository ( ) . getReferringComponents ( componentId ) ) { ComponentIDPropertyEditor rcidpe = new ComponentIDPropertyEditor ( ) ; rcidpe . setValue ( referringComponentId ) ; String referringComponentIdString = rcidpe . getAsText ( ) ; if ( ! this . getComponents ( ) . contains ( referringComponentIdString ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser for the deployment config xml . [CODESPLIT] private void parseDUDeployConfig ( ) throws Exception { JarFile componentJarFile = new JarFile ( diURL . getFile ( ) ) ; try { // Get the JarEntry for the deploy-config.xml\r JarEntry deployInfoXML = componentJarFile . getJarEntry ( \"META-INF/deploy-config.xml\" ) ; if ( deployInfoXML != null ) { DeployConfigParser deployConfigParser = new DeployConfigParser ( componentJarFile . getInputStream ( deployInfoXML ) , sleeContainerDeployer . getSleeContainer ( ) . getResourceManagement ( ) ) ; for ( Entry < String , Collection < ManagementAction > > e : deployConfigParser . getPostInstallActions ( ) . entrySet ( ) ) { postInstallActions . put ( e . getKey ( ) , e . getValue ( ) ) ; } for ( Entry < String , Collection < ManagementAction > > e : deployConfigParser . getPreUninstallActions ( ) . entrySet ( ) ) { preUninstallActions . put ( e . getKey ( ) , e . getValue ( ) ) ; } } } finally { componentJarFile . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes and unregisters the mbean for the specified profile if exists [CODESPLIT] public static void close ( String profileTableName , String profileName ) { final ObjectName objectName = getObjectName ( profileTableName , profileName ) ; if ( sleeContainer . getMBeanServer ( ) . isRegistered ( objectName ) ) { Runnable r = new Runnable ( ) { public void run ( ) { try { sleeContainer . getMBeanServer ( ) . invoke ( objectName , \"close\" , new Object [ ] { } , new String [ ] { } ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } ; Thread t = new Thread ( r ) ; t . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JMX ObjectName for a profile given its profile name and profile table name [CODESPLIT] public static ObjectName getObjectName ( String profileTableName , String profileName ) { // FIXME use only the \"quoted\" version when issue is fully solved at the JMX Console side try { return new ObjectName ( ProfileMBean . BASE_OBJECT_NAME + ' ' + ProfileMBean . PROFILE_TABLE_NAME_KEY + ' ' + profileTableName + ' ' + ProfileMBean . PROFILE_NAME_KEY + ' ' + ( profileName != null ? profileName : \"\" ) ) ; } catch ( Throwable e ) { try { return new ObjectName ( ProfileMBean . BASE_OBJECT_NAME + ' ' + ProfileMBean . PROFILE_TABLE_NAME_KEY + ' ' + ObjectName . quote ( profileTableName ) + ' ' + ProfileMBean . PROFILE_NAME_KEY + ' ' + ObjectName . quote ( profileName != null ? profileName : \"\" ) ) ; } catch ( Throwable f ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves to the write mode using specified object . The current java transaction will be suspended . [CODESPLIT] private void writeMode ( ) throws SLEEException , ManagementException { if ( ! isProfileWriteable ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Changing state to read-write, for profile mbean with name \" + profileName + \", from table with name \" + this . profileTable . getProfileTableName ( ) ) ; } // get object & make it writable ProfileObjectImpl profileObject = profileTable . getProfile ( profileName ) ; profileObject . getProfileEntity ( ) . setReadOnly ( false ) ; // change state state = State . write ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Already in write state, for profile mbean with name \" + profileName + \", from table with name \" + this . profileTable . getProfileTableName ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void closeProfile ( ) throws InvalidStateException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"closeProfile() on: \" + profileName + \", from table:\" + profileTable . getProfileTableName ( ) ) ; } // The closeProfile method must throw a javax.slee.InvalidStateException if the Profile MBean object is in the read-write state. if ( this . isProfileWriteable ( ) ) throw new InvalidStateException ( ) ; // unregister mbean unregister ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) @see javax . slee . profile . ProfileMBean#commitProfile () [CODESPLIT] public void commitProfile ( ) throws InvalidStateException , ProfileVerificationException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"commitProfile() on: \" + profileName + \", from table:\" + profileTable . getProfileTableName ( ) ) ; } if ( ! this . isProfileWriteable ( ) ) throw new InvalidStateException ( \"not in write state\" ) ; final SleeTransactionManager txManager = sleeContainer . getTransactionManager ( ) ; ProfileEntity profileEntity = null ; try { // resume tx txManager . resume ( this . transaction ) ; // verify state ProfileObjectImpl profileObject = getProfileObject ( ) ; profileObject . profileVerify ( ) ; // check if the tx is marked for rollback if ( txManager . getRollbackOnly ( ) ) { // FIXME can't undertsand why the rollback and change of state, perhaps tests/profiles/lifecycle/Test1110227Test.xml is faulty?? // FIXME: Do we need to close EntityManager here? EntityManager em = getEntityManager ( txManager ) ; txManager . rollback ( ) ; if ( em != null && em . isOpen ( ) ) { em . close ( ) ; } readMode ( ) ; this . transaction = null ; throw new RollbackException ( \"the tx is marked for rollback, can't proceeed with commit\" ) ; } // \"save\" profile entity, we may need to recover its current state profileEntity = profileObject . getProfileEntity ( ) ; // commit tx this . transaction = null ; txManager . commit ( ) ; // change mode readMode ( ) ; } catch ( ProfileVerificationException e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( e . getMessage ( ) , e ) ; } throw e ; } catch ( RollbackException e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( e . getMessage ( ) , e ) ; } if ( e . getCause ( ) instanceof PersistenceException && e . getCause ( ) . getCause ( ) instanceof ConstraintViolationException ) { throw new ProfileVerificationException ( e . getCause ( ) . getMessage ( ) , e ) ; } else if ( e . getCause ( ) != null && e . getCause ( ) . getClass ( ) == Throwable . class && e . getCause ( ) . getMessage ( ) != null && e . getCause ( ) . getMessage ( ) . equals ( \"setRollbackOnly called from:\" ) ) { // workaround for issue with jboss AS 5.1.0 GA / Hibernate Entity Manager 3.4.0.GA / JBoss TS 4.6.1.GA, the persistentexception is not thrown throw new ProfileVerificationException ( e . getCause ( ) . getMessage ( ) , e ) ; } else { throw new ManagementException ( e . getMessage ( ) , e ) ; } } catch ( Throwable e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( e . getMessage ( ) , e ) ; } throw new ManagementException ( e . getMessage ( ) , e ) ; } finally { if ( this . transaction == null ) { if ( isProfileWriteable ( ) ) { // still in write mode if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"The tx commit failed, recreating tx with current profile entity state\" ) ; } try { txManager . begin ( ) ; this . transaction = txManager . getTransaction ( ) ; ProfileEntity newTxProfileEntity = profileEntity . isCreate ( ) ? profileTable . createProfile ( profileName ) . getProfileEntity ( ) : getProfileObject ( ) . getProfileEntity ( ) ; profileTable . getProfileSpecificationComponent ( ) . getProfileEntityFramework ( ) . getProfileEntityFactory ( ) . copyAttributes ( profileEntity , newTxProfileEntity ) ; newTxProfileEntity . setReadOnly ( false ) ; txManager . suspend ( ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } } else { // tx still valid try { txManager . suspend ( ) ; } catch ( Throwable f ) { logger . error ( f . getMessage ( ) , f ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logic to execute before invoking a cmp setter method on the mbean [CODESPLIT] protected void beforeSetCmpField ( ) throws ManagementException , InvalidStateException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"beforeSetCmpField() on profile with name \" + profileName + \" of table \" + profileTable . getProfileTableName ( ) ) ; } if ( isProfileWriteable ( ) ) { try { sleeContainer . getTransactionManager ( ) . resume ( transaction ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } else { throw new InvalidStateException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logic to execute after invoking a cmp setter method on the mbean [CODESPLIT] protected void afterSetCmpField ( ) throws ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"afterSetCmpField() on profile with name \" + profileName + \" of table \" + profileTable . getProfileTableName ( ) ) ; } try { sleeContainer . getTransactionManager ( ) . suspend ( ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logic to execute before invoking a cmp getter method on the mbean [CODESPLIT] protected boolean beforeGetCmpField ( ) throws ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"beforeGetCmpField() on profile with name \" + profileName + \" of table \" + profileTable . getProfileTableName ( ) ) ; } return beforeNonSetCmpField ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logic to execute after invoking a cmp getter method on the mbean [CODESPLIT] protected void afterGetCmpField ( boolean activatedTransaction ) throws ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"afterGetCmpField( activatedTransaction = \" + activatedTransaction + \" ) on profile with name \" + profileName + \" of table \" + profileTable . getProfileTableName ( ) ) ; } afterNonSetCmpField ( activatedTransaction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logic to execute before invoking a management method on the mbean [CODESPLIT] protected boolean beforeManagementMethodInvocation ( ) throws ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"beforeManagementMethodInvocation() on profile with name \" + profileName + \" of table \" + profileTable . getProfileTableName ( ) ) ; } jndiManagement = sleeContainer . getJndiManagement ( ) ; jndiManagement . pushJndiContext ( profileTable . getProfileSpecificationComponent ( ) ) ; return beforeNonSetCmpField ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logic to execute after invoking a management method on the mbean [CODESPLIT] protected void afterManagementMethodInvocation ( boolean activatedTransaction ) throws ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"afterManagementMethodInvocation( activatedTransaction = \" + activatedTransaction + \" ) on profile with name \" + profileName + \" of table \" + profileTable . getProfileTableName ( ) ) ; } afterNonSetCmpField ( activatedTransaction ) ; jndiManagement . popJndiContext ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles a { @link Throwable } which was the result of a management method invocation [CODESPLIT] protected void throwableOnManagementMethodInvocation ( Throwable t ) throws ProfileImplementationException , InvalidStateException , ManagementException { if ( t instanceof ProfileImplementationException ) { throw ( ProfileImplementationException ) t ; } else if ( t instanceof InvalidStateException ) { throw ( InvalidStateException ) t ; } else if ( t instanceof ReadOnlyProfileException ) { throw new InvalidStateException ( t . getMessage ( ) ) ; } else if ( t instanceof ManagementException ) { throw ( ManagementException ) t ; } else if ( t instanceof RuntimeException ) { try { getProfileObject ( ) . invalidateObject ( ) ; sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } throw new ProfileImplementationException ( t ) ; } else { // checked exception throw new ProfileImplementationException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void suspendDelivery ( int arg0 ) throws IllegalArgumentException , IllegalStateException , TransactionRequiredLocalException , SLEEException { suspensionHandlerLazyInit ( ) ; suspensionHandler . suspendDelivery ( arg0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void eventProcessingFailed ( FailureReason reason ) { if ( data . getFailedCallback ( ) != null ) { try { data . getFailedCallback ( ) . eventProcessingFailed ( reason ) ; } catch ( Throwable e ) { // ignore } } canceled ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void eventProcessingSucceed ( boolean sbbProcessedEvent ) { if ( data . getSucceedCallback ( ) != null ) { data . getSucceedCallback ( ) . eventProcessingSucceed ( sbbProcessedEvent ) ; // ensure failed never gets called, even if event is refired data . unsetFailedCallback ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean routedRequiresTransaction ( ) { final EventUnreferencedCallback unreferencedCallback = data . getUnreferencedCallback ( ) ; if ( unreferencedCallback == null ) { return false ; } else { return unreferencedCallback . requiresTransaction ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a JMX Object Name property string that uniquely identifies the specified resource adaptor entity suitable for inclusion in the Object Name of a Usage MBean . This method makes use of the { [CODESPLIT] public static String getUsageMBeanProperties ( String entityName ) { if ( entityName == null ) throw new NullPointerException ( \"entityName is null\" ) ; return RESOURCE_ADAPTOR_ENTITY_NAME_KEY + ' ' + ObjectName . quote ( entityName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare this notification source with the specified object for order . Returns a negative integer zero or a positive integer if this object is less than equal to or greater than the specified object . <p > If <code > obj< / code > is a <code > ResourceAdaptorEntityNotification< / code > order is determined by comparing the encapsulated resource adaptor entity name . Otherwise if <code > obj< / code > is a <code > NotificationSource< / code > ordering is determined by comparing the class name of this class with the class name of <code > obj< / code > . [CODESPLIT] public int compareTo ( Object obj ) { // can't compare with null if ( obj == null ) throw new NullPointerException ( \"obj is null\" ) ; if ( obj == this ) return 0 ; if ( obj instanceof ResourceAdaptorEntityNotification ) { // compare the entity name ResourceAdaptorEntityNotification that = ( ResourceAdaptorEntityNotification ) obj ; return this . entityName . compareTo ( that . entityName ) ; } else { return super . compareTo ( TYPE , obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a JMX Object Name property string that uniquely identifies the specified service and SBB suitable for inclusion in the Object Name of a Usage MBean . This method makes use of the { [CODESPLIT] public static String getUsageMBeanProperties ( ServiceID service , SbbID sbb ) { if ( service == null ) throw new NullPointerException ( \"service is null\" ) ; if ( sbb == null ) throw new NullPointerException ( \"sbb is null\" ) ; StringBuffer buf = new StringBuffer ( ) ; buf . append ( SERVICE_NAME_KEY ) . append ( ' ' ) . append ( ObjectName . quote ( service . getName ( ) ) ) . append ( ' ' ) ; buf . append ( SERVICE_VENDOR_KEY ) . append ( ' ' ) . append ( ObjectName . quote ( service . getVendor ( ) ) ) . append ( ' ' ) ; buf . append ( SERVICE_VERSION_KEY ) . append ( ' ' ) . append ( ObjectName . quote ( service . getVersion ( ) ) ) . append ( ' ' ) ; buf . append ( SBB_NAME_KEY ) . append ( ' ' ) . append ( ObjectName . quote ( sbb . getName ( ) ) ) . append ( ' ' ) ; buf . append ( SBB_VENDOR_KEY ) . append ( ' ' ) . append ( ObjectName . quote ( sbb . getVendor ( ) ) ) . append ( ' ' ) ; buf . append ( SBB_VERSION_KEY ) . append ( ' ' ) . append ( ObjectName . quote ( sbb . getVersion ( ) ) ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare this notification source with the specified object for order . Returns a negative integer zero or a positive integer if this object is less than equal to or greater than the specified object . <p > If <code > obj< / code > is an <code > SbbNotification< / code > order is determined by comparing first the encapsulated service component identifier and then if the service component identifiers are equal the encapsulated SBB component identifier . Otherwise if <code > obj< / code > is a <code > NotificationSource< / code > ordering is determined by comparing the class name of this class with the class name of <code > obj< / code > . [CODESPLIT] public int compareTo ( Object obj ) { // can't compare with null if ( obj == null ) throw new NullPointerException ( \"obj is null\" ) ; if ( obj == this ) return 0 ; if ( obj instanceof SbbNotification ) { // compare the service id then the sbb id SbbNotification that = ( SbbNotification ) obj ; int serviceComparison = this . service . compareTo ( that . service ) ; return serviceComparison != 0 ? serviceComparison : this . sbb . compareTo ( that . sbb ) ; } else { return super . compareTo ( TYPE , obj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an unmodifiable set with all { @link AbstractSleeComponent } s of the deployable unit . [CODESPLIT] public Set < SleeComponent > getDeployableUnitComponents ( ) { Set < SleeComponent > result = new HashSet < SleeComponent > ( ) ; result . addAll ( getEventTypeComponents ( ) . values ( ) ) ; result . addAll ( getLibraryComponents ( ) . values ( ) ) ; result . addAll ( getProfileSpecificationComponents ( ) . values ( ) ) ; result . addAll ( getResourceAdaptorComponents ( ) . values ( ) ) ; result . addAll ( getResourceAdaptorTypeComponents ( ) . values ( ) ) ; result . addAll ( getSbbComponents ( ) . values ( ) ) ; result . addAll ( getServiceComponents ( ) . values ( ) ) ; return Collections . unmodifiableSet ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deletes the whole path going through directories [CODESPLIT] private void deletePath ( File path ) { if ( path . isDirectory ( ) ) { File [ ] files = path . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { deletePath ( file ) ; } } } path . delete ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link DeployableUnitDescriptor } for this deployable unit . [CODESPLIT] public javax . slee . management . DeployableUnitDescriptor getSpecsDeployableUnitDescriptor ( ) { Set < ComponentID > componentIDs = new HashSet < ComponentID > ( ) ; for ( SleeComponent component : getDeployableUnitComponents ( ) ) { componentIDs . add ( component . getComponentID ( ) ) ; } return new DeployableUnitDescriptor ( getDeployableUnitID ( ) , date , componentIDs . toArray ( new ComponentID [ 0 ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void eventUnreferenced ( ) { ActivityContextImpl ac = factory . getActivityContext ( ach ) ; if ( ac != null ) { ac . activityEnded ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { this . activityHandle = new ProfileTableActivityHandleImpl ( in . readUTF ( ) , ( Address ) in . readObject ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { out . writeUTF ( activityHandle . getProfileTable ( ) ) ; out . writeObject ( activityHandle . getClusterLocalAddress ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a constructor . This method simply records the input parameters in appropriately named fields . [CODESPLIT] private void createConstructor ( CtClass concreteClass , CtClass usageMBeanInterface , CtClass notificationSource , CtClass usageComponent ) throws Exception { CtConstructor ctCons = new CtConstructor ( new CtClass [ ] { usageMBeanInterface , notificationSource , usageComponent } , concreteClass ) ; ctCons . setBody ( \"{ super($1,$2,$3); }\" ) ; concreteClass . addConstructor ( ctCons ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setMinFreeMemoryToTurnOn ( int minFreeMemoryToTurnOn ) throws IllegalArgumentException { if ( minFreeMemoryToTurnOn < 0 || minFreeMemoryToTurnOn > 100 ) { throw new IllegalArgumentException ( \"param value must be within 0 - 100%\" ) ; } this . minFreeMemoryToTurnOn = minFreeMemoryToTurnOn ; if ( congestureControl != null ) { congestureControl . configurationUpdate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setMinFreeMemoryToTurnOff ( int minFreeMemoryToTurnOff ) throws IllegalArgumentException { if ( minFreeMemoryToTurnOff < 0 || minFreeMemoryToTurnOff > 100 ) { throw new IllegalArgumentException ( \"param value must be within 0 - 100%\" ) ; } this . minFreeMemoryToTurnOff = minFreeMemoryToTurnOff ; if ( congestureControl != null ) { congestureControl . configurationUpdate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setPeriodBetweenChecks ( int periodBetweenChecks ) throws IllegalArgumentException { if ( periodBetweenChecks < 0 ) { throw new IllegalArgumentException ( \"param value must not be negative\" ) ; } this . periodBetweenChecks = periodBetweenChecks ; if ( congestureControl != null ) { congestureControl . configurationUpdate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the concrete sbb Class [CODESPLIT] public void generateConcreteSbb ( ) throws DeploymentException { String sbbAbstractClassName = sbbComponent . getAbstractSbbClass ( ) . getName ( ) ; String sbbConcreteClassName = ConcreteClassGeneratorUtils . getSbbConcreteClassName ( sbbAbstractClassName ) ; sbbConcreteClass = pool . makeClass ( sbbConcreteClassName ) ; try { try { sbbAbstractClass = pool . get ( sbbAbstractClassName ) ; } catch ( NotFoundException nfe ) { throw new DeploymentException ( nfe . getMessage ( ) , nfe ) ; } generateAbstractSbbClassInfo ( ) ; try { ConcreteClassGeneratorUtils . createInterfaceLinks ( sbbConcreteClass , new CtClass [ ] { pool . get ( SbbConcrete . class . getName ( ) ) } ) ; } catch ( NotFoundException nfe ) { throw new DeploymentException ( nfe . getMessage ( ) , nfe ) ; } ConcreteClassGeneratorUtils . createInheritanceLink ( sbbConcreteClass , sbbAbstractClass ) ; abstractMethods = ClassUtils . getAbstractMethodsFromClass ( sbbAbstractClass ) ; superClassesAbstractMethods = ClassUtils . getSuperClassesAbstractMethodsFromClass ( sbbAbstractClass ) ; try { createFields ( new CtClass [ ] { pool . get ( SbbEntity . class . getName ( ) ) , pool . get ( SbbObjectState . class . getName ( ) ) } ) ; CtClass [ ] parameters = new CtClass [ ] { pool . get ( SbbEntity . class . getName ( ) ) } ; createSbbEntityGetterAndSetter ( sbbConcreteClass ) ; createDefaultUsageParameterGetter ( sbbConcreteClass ) ; createNamedUsageParameterGetter ( sbbConcreteClass ) ; createDefaultConstructor ( ) ; createConstructorWithParameter ( parameters ) ; } catch ( NotFoundException nfe ) { logger . error ( \"Constructor With Parameter not created\" ) ; throw new DeploymentException ( \"Constructor not created.\" , nfe ) ; } SbbAbstractClassDescriptor mSbbAbstractClass = sbbComponent . getDescriptor ( ) . getSbbAbstractClass ( ) ; createCMPAccessors ( mSbbAbstractClass . getCmpFields ( ) ) ; createGetChildRelationsMethod ( mSbbAbstractClass . getChildRelationMethods ( ) . values ( ) ) ; createGetProfileCMPMethods ( mSbbAbstractClass . getProfileCMPMethods ( ) . values ( ) ) ; createFireEventMethods ( sbbComponent . getDescriptor ( ) . getEventEntries ( ) . values ( ) ) ; // GetUsageParametersMethod[] usageParameters= // sbbDeploymentDescriptor.getUsageParametersMethods(); // if the activity context interface has been defined in the // descriptor // file // then generates the concrete class of the activity context // interface // and implements the narrow method if ( sbbComponent . getDescriptor ( ) . getSbbActivityContextInterface ( ) != null ) { Class < ? > activityContextInterfaceClass = null ; try { activityContextInterfaceClass = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( sbbComponent . getDescriptor ( ) . getSbbActivityContextInterface ( ) ) ; } catch ( ClassNotFoundException e2 ) { String s = \"Error creating constructor -  class not found\" ; logger . error ( s , e2 ) ; throw new DeploymentException ( s , e2 ) ; } // Check the activity context interface for illegal method // names. Method [ ] methods = activityContextInterfaceClass . getMethods ( ) ; ArrayList < String > allSetters = new ArrayList < String > ( ) ; ArrayList < String > missingSetters = new ArrayList < String > ( ) ; if ( methods != null ) { for ( int i = 0 ; i < methods . length ; i ++ ) { if ( ! methods [ i ] . getDeclaringClass ( ) . getName ( ) . equals ( javax . slee . ActivityContextInterface . class . getName ( ) ) && ! methods [ i ] . getDeclaringClass ( ) . getName ( ) . equals ( ActivityContextInterfaceExt . class . getName ( ) ) ) { String methodName = methods [ i ] . getName ( ) ; // setters should have a single parameter and should // return void type. if ( methodName . startsWith ( \"set\" ) ) { Class < ? > [ ] args = methods [ i ] . getParameterTypes ( ) ; // setter should only have one argument if ( args . length != 1 ) throw new DeploymentException ( \"Setter method '\" + methodName + \"' should only have one argument.\" ) ; // setter return type should be void Class < ? > returnClass = methods [ i ] . getReturnType ( ) ; if ( ! returnClass . equals ( Void . TYPE ) ) throw new DeploymentException ( \"Setter method '\" + methodName + \"' return type should be void.\" ) ; allSetters . add ( methodName ) ; } else if ( methodName . startsWith ( \"get\" ) ) { Class < ? > [ ] args = methods [ i ] . getParameterTypes ( ) ; // getter should have no parameters. if ( args != null && args . length != 0 ) throw new DeploymentException ( \"Getter method '\" + methodName + \"' should have no parameters.\" ) ; // getter return type should not be void if ( methods [ i ] . getReturnType ( ) . equals ( Void . TYPE ) ) throw new DeploymentException ( \"Getter method '\" + methodName + \"' return type cannot be void.\" ) ; String setterName = methodName . replaceFirst ( \"get\" , \"set\" ) ; try { activityContextInterfaceClass . getMethod ( setterName , methods [ i ] . getReturnType ( ) ) ; } catch ( NoSuchMethodException nsme ) { missingSetters . add ( setterName ) ; } } else { throw new DeploymentException ( \"Invalid method '\" + methodName + \"' in SBB Activity Context Interface.\" ) ; } } } // Check if the missing setters aren't defined with // different arg for ( String setter : missingSetters ) if ( allSetters . contains ( setter ) ) throw new DeploymentException ( \"Getter argument type and\" + \" setter return type for attribute '\" + setter . replaceFirst ( \"set\" , \"\" ) . toLowerCase ( ) + \"' must be the same.\" ) ; } /*\n\t\t\t\t * CtMethod[] abstractClassMethods =\n\t\t\t\t * sbbAbstractClass.getDeclaredMethods();\n\t\t\t\t * \n\t\t\t\t * for ( int i = 0; i < abstractClassMethods.length; i ++ ) {\n\t\t\t\t * CtMethod ctMethod = abstractClassMethods[i]; if ( !\n\t\t\t\t * Modifier.isAbstract(ctMethod.getModifiers())) {\n\t\t\t\t * this.createMethodWrapper(sbbConcreteClass,ctMethod); } }\n\t\t\t\t */ // check if the concrete class has already been generated. // if that the case, the guess is that the concrete class is a // safe // one // and so it is not generated again // avoid also problems of class already loaded from the class // loader //   CtClass activityContextInterface = null ; try { activityContextInterface = pool . get ( activityContextInterfaceClass . getName ( ) ) ; createField ( activityContextInterface , \"sbbActivityContextInterface\" ) ; this . createSetActivityContextInterfaceMethod ( activityContextInterface ) ; ConcreteActivityContextInterfaceGenerator concreteActivityContextInterfaceGenerator = new ConcreteActivityContextInterfaceGenerator ( activityContextInterfaceClass . getName ( ) , deployDir , pool ) ; Class < ? > concreteActivityContextInterfaceClass = concreteActivityContextInterfaceGenerator . generateActivityContextInterfaceConcreteClass ( ) ; createGetSbbActivityContextInterfaceMethod ( activityContextInterface , concreteActivityContextInterfaceClass ) ; // set the concrete activity context interface class in // the // descriptor if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"SETTING ACI concrete class  \" + concreteActivityContextInterfaceClass + \" in \" + sbbComponent ) ; } sbbComponent . setActivityContextInterfaceConcreteClass ( concreteActivityContextInterfaceClass ) ; } catch ( NotFoundException nfe ) { logger . error ( \"Narrow Activity context interface method and \" + \"activity context interface concrete class not created\" ) ; throw new DeploymentException ( nfe . getMessage ( ) , nfe ) ; } finally { /*\n\t\t\t\t\t * if (activityContextInterface != null) {\n\t\t\t\t\t * activityContextInterface.detach(); }\n\t\t\t\t\t */ } } // if the sbb local object has been defined in the descriptor file // then generates the concrete class of the sbb local object // and implements the narrow method Class < ? > sbbLocalInterfaceClass = sbbComponent . getSbbLocalInterfaceClass ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Sbb Local Object interface :\" + sbbLocalInterfaceClass ) ; } if ( sbbLocalInterfaceClass != null && ! sbbLocalInterfaceClass . getName ( ) . equals ( \"javax.slee.SbbLocalObject\" ) ) { try { pool . get ( sbbLocalInterfaceClass . getName ( ) ) ; ConcreteSbbLocalObjectGenerator concreteSbbLocalObjectGenerator = new ConcreteSbbLocalObjectGenerator ( sbbLocalInterfaceClass . getName ( ) , sbbAbstractClassName , this . deployDir , pool ) ; Class < ? > concreteSbbLocalObjectClass = concreteSbbLocalObjectGenerator . generateSbbLocalObjectConcreteClass ( ) ; // set the sbb Local object class in the descriptor sbbComponent . setSbbLocalInterfaceConcreteClass ( concreteSbbLocalObjectClass ) ; } catch ( NotFoundException nfe ) { String s = \"sbb Local Object concrete class not created for interface \" + sbbLocalInterfaceClass . getName ( ) ; throw new DeploymentException ( s , nfe ) ; } } // if there is no interface defined in the descriptor for sbb local // object // then the slee implementation is taken else { try { sbbComponent . setSbbLocalInterfaceClass ( SbbLocalObject . class ) ; sbbComponent . setSbbLocalInterfaceConcreteClass ( SbbLocalObjectImpl . class ) ; } catch ( Exception e ) { throw new DeploymentException ( e . getMessage ( ) , e ) ; } } try { sbbConcreteClass . writeFile ( deployDir ) ; // @@2.4+ -> 3.4+ // pool.writeFile(sbbConcreteClassName, deployPath); if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Concrete Class \" + sbbConcreteClassName + \" generated in the following path \" + deployDir ) ; } } catch ( Exception e ) { String s = \"Error generating concrete class\" ; throw new DeploymentException ( s , e ) ; } Class < ? > clazz = null ; try { clazz = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( sbbConcreteClassName ) ; } catch ( ClassNotFoundException e1 ) { String s = \"What the heck?! Could not find generated class. Is it under the chair?\" ; throw new DeploymentException ( s , e1 ) ; } // set the concrete class in the descriptor sbbComponent . setConcreteSbbClass ( clazz ) ; } finally { if ( sbbConcreteClass != null ) { sbbConcreteClass . defrost ( ) ; } } // uh uh if ( sbbComponent . getConcreteSbbClass ( ) == null ) { throw new DeploymentException ( \"concrete sbb class generation failed and I don't know why, bug bug ?!? :)\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates info that indicates if a method from { [CODESPLIT] private void generateAbstractSbbClassInfo ( ) { CtClass sbbClass = null ; try { sbbClass = pool . get ( Sbb . class . getName ( ) ) ; } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } AbstractSbbClassInfo abstractSbbClassInfo = sbbComponent . getAbstractSbbClassInfo ( ) ; for ( CtMethod sbbClassMethod : sbbClass . getDeclaredMethods ( ) ) { for ( CtMethod sbbAbstractClassMethod : sbbAbstractClass . getMethods ( ) ) { if ( sbbAbstractClassMethod . getName ( ) . equals ( sbbClassMethod . getName ( ) ) && sbbAbstractClassMethod . getSignature ( ) . equals ( sbbClassMethod . getSignature ( ) ) ) { // match, save info abstractSbbClassInfo . setInvokeInfo ( sbbAbstractClassMethod . getMethodInfo ( ) . getName ( ) , ! sbbAbstractClassMethod . isEmpty ( ) ) ; break ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a constructor with parameters <BR > For every parameter a field of the same class is created in the concrete class And each field is gonna be initialized with the corresponding parameter [CODESPLIT] protected void createConstructorWithParameter ( CtClass [ ] parameters ) throws DeploymentException { CtConstructor constructorWithParameter = new CtConstructor ( parameters , sbbConcreteClass ) ; String constructorBody = \"{\" + \"this();\" ; /*\n\t\t * for (int i = 0; i < parameters.length; i++) { String parameterName =\n\t\t * parameters[i].getName(); parameterName =\n\t\t * parameterName.substring(parameterName .lastIndexOf(\".\") + 1); String\n\t\t * firstCharLowerCase = parameterName.substring(0, 1) .toLowerCase();\n\t\t * parameterName = firstCharLowerCase.concat(parameterName\n\t\t * .substring(1));\n\t\t * \n\t\t * int paramNumber = i + 1; constructorBody += parameterName + \"=$\" +\n\t\t * paramNumber + \";\"; }\n\t\t */ constructorBody += \"this.setSbbEntity($1);\" ; constructorBody += \"}\" ; try { sbbConcreteClass . addConstructor ( constructorWithParameter ) ; constructorWithParameter . setBody ( constructorBody ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"ConstructorWithParameter created\" ) ; } } catch ( CannotCompileException e ) { throw new DeploymentException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a default constructor on the Sbb Concrete Class [CODESPLIT] protected void createDefaultConstructor ( ) throws DeploymentException { CtConstructor defaultConstructor = new CtConstructor ( null , sbbConcreteClass ) ; // We need a \"do nothing\" constructor because the // convergence name creation method may need to actually // create the object instance to run the method that // creates the convergence name. String constructorBody = \"{ }\" ; try { defaultConstructor . setBody ( constructorBody ) ; sbbConcreteClass . addConstructor ( defaultConstructor ) ; logger . trace ( \"DefaultConstructor created\" ) ; } catch ( CannotCompileException e ) { throw new DeploymentException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a default usage parameter getter and setter . [CODESPLIT] private void createDefaultUsageParameterGetter ( CtClass sbbConcrete ) throws DeploymentException { String methodName = \"getDefaultSbbUsageParameterSet\" ; CtMethod method = ( CtMethod ) abstractMethods . get ( methodName ) ; if ( method == null ) { method = ( CtMethod ) superClassesAbstractMethods . get ( methodName ) ; } if ( method != null ) { try { // copy method from abstract to concrete class CtMethod concreteMethod = CtNewMethod . copy ( method , sbbConcreteClass , null ) ; // create the method body String concreteMethodBody = \"{ return ($r)\" + SbbAbstractMethodHandler . class . getName ( ) + \".getDefaultSbbUsageParameterSet(sbbEntity); }\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Generated method \" + methodName + \" , body = \" + concreteMethodBody ) ; } concreteMethod . setBody ( concreteMethodBody ) ; sbbConcreteClass . addMethod ( concreteMethod ) ; } catch ( CannotCompileException cce ) { throw new SLEEException ( \"Cannot compile method \" + method . getName ( ) , cce ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a method to retrive the entity from the SbbObject . [CODESPLIT] private void createSbbEntityGetterAndSetter ( CtClass sbbConcrete ) throws DeploymentException { try { CtMethod getSbbEntity = CtNewMethod . make ( \"public \" + SbbEntity . class . getName ( ) + \" getSbbEntity() { return this.sbbEntity; }\" , sbbConcrete ) ; getSbbEntity . setModifiers ( Modifier . PUBLIC ) ; sbbConcrete . addMethod ( getSbbEntity ) ; CtMethod setSbbEntity = CtNewMethod . make ( \"public void setSbbEntity ( \" + SbbEntity . class . getName ( ) + \" sbbEntity )\" + \"{\" + \"this.sbbEntity = sbbEntity;\" + \"}\" , sbbConcrete ) ; setSbbEntity . setModifiers ( Modifier . PUBLIC ) ; sbbConcrete . addMethod ( setSbbEntity ) ; } catch ( Exception e ) { throw new DeploymentException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the cmp field setters and getters [CODESPLIT] protected void createCMPAccessors ( Collection < CMPFieldDescriptor > cmps ) throws DeploymentException { for ( CMPFieldDescriptor cmp : cmps ) { String fieldName = cmp . getCmpFieldName ( ) ; // Set the first char of the accessor to UpperCase to follow the // javabean requirements fieldName = fieldName . substring ( 0 , 1 ) . toUpperCase ( ) + fieldName . substring ( 1 ) ; String getterMethodName = \"get\" + fieldName ; CtMethod getterMethod = ( CtMethod ) abstractMethods . get ( getterMethodName ) ; if ( getterMethod == null ) { getterMethod = ( CtMethod ) this . superClassesAbstractMethods . get ( getterMethodName ) ; } if ( getterMethod == null ) { throw new SLEEException ( \"can't find abstract method \" + getterMethodName ) ; } // generate the acessor method name sufix from type String getterHandlerMethodName = \"getCMPFieldOfType\" ; boolean getterHandlerMethodNeedResultCast = false ; String setterHandlerMethodName = \"setCMPFieldOfType\" ; try { CtClass ctClassCmpType = getterMethod . getReturnType ( ) ; if ( ctClassCmpType . isPrimitive ( ) ) { // boolean, byte, char, short, int, long, float, double String ctClassCmpTypeName = ctClassCmpType . getName ( ) ; if ( ctClassCmpTypeName . equals ( boolean . class . getName ( ) ) ) { getterHandlerMethodName += \"Boolean\" ; } else if ( ctClassCmpTypeName . equals ( byte . class . getName ( ) ) ) { getterHandlerMethodName += \"Byte\" ; } else if ( ctClassCmpTypeName . equals ( char . class . getName ( ) ) ) { getterHandlerMethodName += \"Char\" ; } else if ( ctClassCmpTypeName . equals ( short . class . getName ( ) ) ) { getterHandlerMethodName += \"Short\" ; } else if ( ctClassCmpTypeName . equals ( int . class . getName ( ) ) ) { getterHandlerMethodName += \"Integer\" ; } else if ( ctClassCmpTypeName . equals ( long . class . getName ( ) ) ) { getterHandlerMethodName += \"Long\" ; } else if ( ctClassCmpTypeName . equals ( float . class . getName ( ) ) ) { getterHandlerMethodName += \"Float\" ; } else if ( ctClassCmpTypeName . equals ( double . class . getName ( ) ) ) { getterHandlerMethodName += \"Double\" ; } else { throw new SLEEException ( \"unexpected primitive type \" + ctClassCmpTypeName ) ; } getterHandlerMethodNeedResultCast = true ; setterHandlerMethodName += \"PrimitiveOrUnknown\" ; } else { // aci, event context, sbb local object, profile local object, Boolean, Byte, Char, Short, Integer, Long, Float, Double, unknown, array, enum, annotation if ( ! ctClassCmpType . isArray ( ) && ! ctClassCmpType . isEnum ( ) && ! ctClassCmpType . isAnnotation ( ) ) { // aci, event context, sbb local object, profile local object, Boolean, Byte, Char, Short, Integer, Long, Float, Double, unknown Class < ? > classCmpType = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( ctClassCmpType . getName ( ) ) ; if ( javax . slee . ActivityContextInterface . class . isAssignableFrom ( classCmpType ) ) { getterHandlerMethodName += \"ActivityContextInterface\" ; setterHandlerMethodName += \"ActivityContextInterface\" ; } else if ( EventContext . class . isAssignableFrom ( classCmpType ) ) { getterHandlerMethodName += \"EventContext\" ; setterHandlerMethodName += \"EventContext\" ; } else if ( ProfileLocalObject . class . isAssignableFrom ( classCmpType ) ) { getterHandlerMethodName += \"ProfileLocalObject\" ; setterHandlerMethodName += \"ProfileLocalObject\" ; } else if ( SbbLocalObject . class . isAssignableFrom ( classCmpType ) ) { getterHandlerMethodName += \"SbbLocalObject\" ; setterHandlerMethodName += \"SbbLocalObject\" ; } else { // Boolean, Byte, Char, Short, Integer, Long, Float, Double, unknown if ( this . initializeReferenceDataTypesWithNull ) { getterHandlerMethodName += \"Unknown\" ; getterHandlerMethodNeedResultCast = true ; } else { // initialized with 0 String ctClassCmpTypeName = ctClassCmpType . getName ( ) ; if ( ctClassCmpTypeName . equals ( Boolean . class . getName ( ) ) ) { getterHandlerMethodName += \"Boolean\" ; } else if ( ctClassCmpTypeName . equals ( Byte . class . getName ( ) ) ) { getterHandlerMethodName += \"Byte\" ; } else if ( ctClassCmpTypeName . equals ( Character . class . getName ( ) ) ) { getterHandlerMethodName += \"Char\" ; } else if ( ctClassCmpTypeName . equals ( Short . class . getName ( ) ) ) { getterHandlerMethodName += \"Short\" ; } else if ( ctClassCmpTypeName . equals ( Integer . class . getName ( ) ) ) { getterHandlerMethodName += \"Integer\" ; } else if ( ctClassCmpTypeName . equals ( Long . class . getName ( ) ) ) { getterHandlerMethodName += \"Long\" ; } else if ( ctClassCmpTypeName . equals ( Float . class . getName ( ) ) ) { getterHandlerMethodName += \"Float\" ; } else if ( ctClassCmpTypeName . equals ( Double . class . getName ( ) ) ) { getterHandlerMethodName += \"Double\" ; } else { getterHandlerMethodName += \"Unknown\" ; getterHandlerMethodNeedResultCast = true ; } } setterHandlerMethodName += \"PrimitiveOrUnknown\" ; } } else { // array, enum, annotation == same as unknown getterHandlerMethodName += \"Unknown\" ; getterHandlerMethodNeedResultCast = true ; setterHandlerMethodName += \"PrimitiveOrUnknown\" ; } } } catch ( Exception cce ) { throw new SLEEException ( \"Cannot determine the cmp type for cmp field named \" + fieldName , cce ) ; } try { // copy method from abstract to concrete class CtMethod concreteGetterMethod = CtNewMethod . copy ( getterMethod , sbbConcreteClass , null ) ; // create the method body // FIXED: NPE when accessing not initialized CMP // see https://github.com/RestComm/jain-slee/issues/87 String concreteGetterMethodBody = \"{ \" + \"if (sbbEntity == null) \" + \"    throw new TransactionRequiredLocalException(\\\"Cannot get CMP field. SBB entity is null\\\");\" + \"return \" + ( getterHandlerMethodNeedResultCast ? \"($r)\" : \"\" ) + SbbAbstractMethodHandler . class . getName ( ) + \".\" + getterHandlerMethodName + \"(sbbEntity,\\\"\" + cmp . getCmpFieldName ( ) + \"\\\");\" + \" }\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Generated method \" + getterMethodName + \" , body = \" + concreteGetterMethodBody ) ; } concreteGetterMethod . setBody ( concreteGetterMethodBody ) ; sbbConcreteClass . addMethod ( concreteGetterMethod ) ; } catch ( Exception cce ) { throw new SLEEException ( \"Cannot compile method \" + getterMethod . getName ( ) , cce ) ; } String setterMethodName = \"set\" + fieldName ; CtMethod setterMethod = ( CtMethod ) abstractMethods . get ( setterMethodName ) ; if ( setterMethod == null ) { setterMethod = ( CtMethod ) this . superClassesAbstractMethods . get ( setterMethodName ) ; } if ( setterMethod == null ) { throw new SLEEException ( \"can't find abstract method \" + setterMethodName ) ; } try { // copy method from abstract to concrete class CtMethod concreteSetterMethod = CtNewMethod . copy ( setterMethod , sbbConcreteClass , null ) ; // create the method body // FIXED: NPE when accessing not initialized CMP // see https://github.com/RestComm/jain-slee/issues/87 String concreteSetterMethodBody = \"{ \" + \"if (sbbEntity == null) \" + \"    throw new TransactionRequiredLocalException(\\\"Cannot set CMP field. SBB entity is null\\\");\" + SbbAbstractMethodHandler . class . getName ( ) + \".\" + setterHandlerMethodName + \"(sbbEntity,\\\"\" + cmp . getCmpFieldName ( ) + \"\\\",$1); }\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Generated method \" + setterMethodName + \" , body = \" + concreteSetterMethodBody ) ; } concreteSetterMethod . setBody ( concreteSetterMethodBody ) ; sbbConcreteClass . addMethod ( concreteSetterMethod ) ; } catch ( CannotCompileException cce ) { throw new SLEEException ( \"Cannot compile method \" + getterMethod . getName ( ) , cce ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the implementation of the fire event methods [CODESPLIT] protected void createFireEventMethods ( Collection < EventEntryDescriptor > mEventEntries ) { if ( mEventEntries == null ) return ; for ( EventEntryDescriptor mEventEntry : mEventEntries ) { if ( mEventEntry . isFired ( ) ) { String methodName = \"fire\" + mEventEntry . getEventName ( ) ; CtMethod method = ( CtMethod ) abstractMethods . get ( methodName ) ; if ( method == null ) { method = ( CtMethod ) superClassesAbstractMethods . get ( methodName ) ; } if ( method != null ) { try { // copy method from abstract to concrete class CtMethod concreteMethod = CtNewMethod . copy ( method , sbbConcreteClass , null ) ; // create the method body String concreteMethodBody = \"{\" ; concreteMethodBody += getEventTypeIDInstantionString ( mEventEntry ) ; concreteMethodBody += SbbAbstractMethodHandler . class . getName ( ) + \".fireEvent(sbbEntity,eventTypeID\" ; for ( int i = 0 ; i < method . getParameterTypes ( ) . length ; i ++ ) { concreteMethodBody += \",$\" + ( i + 1 ) ; } concreteMethodBody += \");}\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Generated method \" + methodName + \" , body = \" + concreteMethodBody ) ; } concreteMethod . setBody ( concreteMethodBody ) ; sbbConcreteClass . addMethod ( concreteMethod ) ; } catch ( Exception e ) { throw new SLEEException ( \"Cannot compile method \" + method . getName ( ) , e ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the get child relation method ( this method redirects the call to a child relation interceptor ) [CODESPLIT] protected void createGetChildRelationsMethod ( Collection < GetChildRelationMethodDescriptor > childRelations ) { if ( childRelations == null ) return ; for ( GetChildRelationMethodDescriptor childRelation : childRelations ) { String methodName = childRelation . getChildRelationMethodName ( ) ; CtMethod method = ( CtMethod ) abstractMethods . get ( methodName ) ; if ( method == null ) { method = ( CtMethod ) superClassesAbstractMethods . get ( methodName ) ; } if ( method != null ) { try { // copy method from abstract to concrete class CtMethod concreteMethod = CtNewMethod . copy ( method , sbbConcreteClass , null ) ; // create the method body String concreteMethodBody = \"{ return \" + SbbAbstractMethodHandler . class . getName ( ) + \".getChildRelation(sbbEntity,\\\"\" + methodName + \"\\\"); }\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Generated method \" + methodName + \" , body = \" + concreteMethodBody ) ; } concreteMethod . setBody ( concreteMethodBody ) ; sbbConcreteClass . addMethod ( concreteMethod ) ; } catch ( CannotCompileException cce ) { throw new SLEEException ( \"Cannot compile method \" + method . getName ( ) , cce ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the get profile CMP method ( this method redirects the call to a profile cmp interceptor ) [CODESPLIT] protected void createGetProfileCMPMethods ( Collection < GetProfileCMPMethodDescriptor > cmpProfiles ) { if ( cmpProfiles == null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"no CMP Profile method implementation to generate.\" ) ; } return ; } for ( GetProfileCMPMethodDescriptor cmpProfile : cmpProfiles ) { String methodName = cmpProfile . getProfileCmpMethodName ( ) ; CtMethod method = ( CtMethod ) abstractMethods . get ( methodName ) ; if ( method == null ) method = ( CtMethod ) superClassesAbstractMethods . get ( methodName ) ; if ( method != null ) try { // copy method from abstract to concrete class CtMethod concreteMethod = CtNewMethod . copy ( method , sbbConcreteClass , null ) ; // create the method body String concreteMethodBody = \"{ return \" + SbbAbstractMethodHandler . class . getName ( ) + \".getProfileCMPMethod(sbbEntity,\\\"\" + methodName + \"\\\",$1); }\" ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Generated method \" + methodName + \" , body = \" + concreteMethodBody ) ; } concreteMethod . setBody ( concreteMethodBody ) ; sbbConcreteClass . addMethod ( concreteMethod ) ; } catch ( CannotCompileException cce ) { throw new SLEEException ( \"Cannot compile method \" + method . getName ( ) , cce ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the narrow method to get the activity context interface [CODESPLIT] protected void createGetSbbActivityContextInterfaceMethod ( CtClass activityContextInterface , Class < ? > concreteActivityContextInterfaceClass ) throws DeploymentException { String methodToAdd = \"public \" + activityContextInterface . getName ( ) + \" asSbbActivityContextInterface(javax.slee.ActivityContextInterface aci) {\" + \"if(aci==null)\" + \"     throw new \" + IllegalStateException . class . getName ( ) + \"(\\\"Passed argument can not be of null value.\\\");\" + \" if(sbbEntity == null || sbbEntity.getSbbObject().getState() != \" + SbbObjectState . class . getName ( ) + \".READY) { throw new \" + IllegalStateException . class . getName ( ) + \"(\\\"Cannot call asSbbActivityContextInterface\\\"); } \" + \"else if ( aci instanceof \" + concreteActivityContextInterfaceClass . getName ( ) + \") return aci;\" + \"else return  new \" + concreteActivityContextInterfaceClass . getName ( ) + \" ( (\" + ActivityContextInterface . class . getName ( ) + \") $1, \" + \"sbbEntity.getSbbComponent());\" + \"}\" ; CtMethod methodTest ; try { methodTest = CtNewMethod . make ( methodToAdd , sbbConcreteClass ) ; sbbConcreteClass . addMethod ( methodTest ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Method \" + methodToAdd + \" added\" ) ; } } catch ( CannotCompileException e ) { throw new DeploymentException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a query expression to this composite expression . [CODESPLIT] protected final void add ( QueryExpression expr ) throws NullPointerException , IllegalArgumentException { if ( expr == null ) throw new NullPointerException ( \"expr is null\" ) ; // check for cycles if ( expr instanceof CompositeQueryExpression ) { ( ( CompositeQueryExpression ) expr ) . checkForCycles ( this ) ; } else if ( expr instanceof Not ) { ( ( Not ) expr ) . checkForCycles ( this ) ; } // no cycles, so add the expression to the list exprs . add ( expr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the specified expression contains a reference either direct or indirect to this expression . [CODESPLIT] void checkForCycles ( QueryExpression expr ) throws IllegalArgumentException { // is the expression argument equal to this? if ( expr == this ) throw new IllegalArgumentException ( \"Cyclic expression detected\" ) ; // recurse through all nested expressions that are composite expressions for ( int i = 0 ; i < exprs . size ( ) ; i ++ ) { QueryExpression nested = ( QueryExpression ) exprs . get ( i ) ; if ( nested instanceof CompositeQueryExpression ) { ( ( CompositeQueryExpression ) nested ) . checkForCycles ( expr ) ; } else if ( nested instanceof Not ) { ( ( Not ) nested ) . checkForCycles ( expr ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Place an object into the NonSerializableFactory namespace for subsequent access by getObject . There cannot be an already existing binding for key . [CODESPLIT] public static synchronized void bind ( String key , Object target ) throws NameAlreadyBoundException { if ( wrapperMap . containsKey ( key ) == true ) throw new NameAlreadyBoundException ( key + \" already exists in the NonSerializableFactory map\" ) ; wrapperMap . put ( key , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a binding from the NonSerializableFactory map . [CODESPLIT] public static void unbind ( String key ) throws NameNotFoundException { if ( wrapperMap . remove ( key ) == null ) throw new NameNotFoundException ( key + \" was not found in the NonSerializableFactory map\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a binding from the NonSerializableFactory map . [CODESPLIT] public static void unbind ( Name name ) throws NameNotFoundException { String key = name . toString ( ) ; if ( wrapperMap . remove ( key ) == null ) throw new NameNotFoundException ( key + \" was not found in the NonSerializableFactory map\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A convience method that simplifies the process of rebinding a non - zerializable object into a JNDI context . This version binds the target object into the default IntitialContext using name path . [CODESPLIT] public static synchronized void rebind ( Name name , Object target ) throws NamingException { rebind ( name , target , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- End ObjectFactory interface methods [CODESPLIT] private static Context createSubcontext ( Context ctx , Name name ) throws NamingException { Context subctx = ctx ; for ( int pos = 0 ; pos < name . size ( ) ; pos ++ ) { String ctxName = name . get ( pos ) ; try { subctx = ( Context ) ctx . lookup ( ctxName ) ; } catch ( NameNotFoundException e ) { subctx = ctx . createSubcontext ( ctxName ) ; } // The current subctx will be the ctx for the next name component\r ctx = subctx ; } return subctx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setLoggerLevel ( String loggerName , String level ) throws ManagementConsoleException { sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . setLoggerLevel ( loggerName , level ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public LoggerInfo fetchLoggerInfo ( String loggerName ) throws ManagementConsoleException { if ( ! sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getLoggerNames ( null ) . contains ( loggerName ) ) sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . addLogger ( loggerName , Level . OFF ) ; int handlerNum = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . numberOfHandlers ( loggerName ) ; String _name = loggerName ; String _level = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getLoggerLevel ( loggerName ) ; boolean _parent = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getUseParentHandlersFlag ( loggerName ) ; String _filter = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getLoggerFilterClassName ( loggerName ) ; HandlerInfo [ ] hInfos = new HandlerInfo [ handlerNum ] ; for ( int i = 0 ; i < handlerNum ; i ++ ) { String _formatterClass = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getGenericHandlerFormatterClassName ( loggerName , i ) ; String _filterClass = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getGenericHandlerFilterClassName ( loggerName , i ) ; String _h_level = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getGenericHandlerLevel ( loggerName , i ) ; String _h_name = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getHandlerName ( loggerName , i ) ; String _h_className = sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . getHandlerClassName ( loggerName , i ) ; // Add fetch for other options\r HandlerInfo hi = new HandlerInfo ( i , ( _h_name == null ? \"\" : _h_name ) , _filterClass , _formatterClass , _h_className , _h_level , new HashMap ( ) ) ; hInfos [ i ] = hi ; } return new LoggerInfo ( _parent , _name , _filter , _level , hInfos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setUseParentHandlers ( String loggerName , boolean value ) throws ManagementConsoleException { sleeConnection . getSleeManagementMBeanUtils ( ) . getLogManagementMBeanUtils ( ) . setUseParentHandlersFlag ( loggerName , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Level getTraceLevel ( ComponentID componentId ) throws NullPointerException , UnrecognizedComponentException , FacilityException { checkComponentID ( componentId ) ; return this . traceLevelTable . get ( componentId ) . getLevel ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void createTrace ( ComponentID componentId , Level level , String messageType , String message , long timeStamp ) throws NullPointerException , IllegalArgumentException , UnrecognizedComponentException , FacilityException { if ( log . isDebugEnabled ( ) ) { log . debug ( \"createTrace: \" + componentId + \" level = \" + level + \" messageType \" + messageType + \" message \" + message + \" timeStamp \" + timeStamp ) ; } checkComponentID ( componentId ) ; MTraceLevel tl = this . traceLevelTable . get ( componentId ) ; this . notificationTypes . add ( messageType ) ; if ( tl == null ) throw new UnrecognizedComponentException ( \"Could not find \" + componentId ) ; Level lev = tl . getLevel ( ) ; int seqno = tl . getSeqno ( ) ; if ( lev . isOff ( ) ) return ; // Check if we should log this message.\r // if (level.isHigherLevel(lev)) {\r if ( ! lev . isHigherLevel ( level ) ) { TraceNotification traceNotification = new TraceNotification ( traceMBeanImpl , messageType , componentId , level , message , null , seqno , timeStamp ) ; this . traceMBeanImpl . sendNotification ( traceNotification ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private ------------------------------------------------------- [CODESPLIT] private void gatherInfoFromURL ( URL url ) throws MalformedURLException { // Weird VFS behavior... returns jar:file:...jar!/\r if ( url . getProtocol ( ) . equals ( \"jar\" ) ) { this . url = new URL ( url . getFile ( ) . replaceFirst ( \"!/\" , \"/\" ) ) ; } else { this . url = url ; } this . fullPath = this . url . getFile ( ) ; this . fileName = getFileNameInternal ( fullPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { if ( this . serializedEvent == null ) { throw new IOException ( \"No serialized event set.\" ) ; } // add id?\r out . writeInt ( this . serializedEvent . length ) ; out . write ( this . serializedEvent ) ; out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { int len = in . readInt ( ) ; this . serializedEvent = new byte [ len ] ; in . readFully ( serializedEvent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void endActivity ( ) throws TransactionRequiredLocalException , SLEEException { // Check if in valid context.\r if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"NullActivity.endActivity()\" ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; sleeContainer . getActivityContextFactory ( ) . getActivityContext ( new NullActivityContextHandle ( handle ) ) . endActivity ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the specified expression contains a reference either direct or indirect to this expression . [CODESPLIT] void checkForCycles ( QueryExpression expr ) throws IllegalArgumentException { // is the expression argument equal to this? if ( expr == this ) throw new IllegalArgumentException ( \"Cyclic expression detected\" ) ; // recurse through nested expression if it's a composite expression QueryExpression nested = this . expr ; if ( nested instanceof CompositeQueryExpression ) { ( ( CompositeQueryExpression ) nested ) . checkForCycles ( expr ) ; } else if ( nested instanceof Not ) { ( ( Not ) nested ) . checkForCycles ( expr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decorate the abstract sbb Class [CODESPLIT] public boolean decorateAbstractSbb ( ) throws DeploymentException { ClassPool pool = component . getClassPool ( ) ; String sbbAbstractClassName = component . getDescriptor ( ) . getSbbAbstractClass ( ) . getSbbAbstractClassName ( ) ; try { sbbAbstractClass = pool . get ( sbbAbstractClassName ) ; } catch ( NotFoundException nfe ) { throw new DeploymentException ( \"Could not find Abstract Sbb Class: \" + sbbAbstractClassName , nfe ) ; } // populate the list of concrete methods. It will be needed by the\r // decorating methods.\r concreteMethods = new HashMap ( ) ; CtMethod [ ] methods = sbbAbstractClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { int mods = methods [ i ] . getModifiers ( ) ; if ( ! Modifier . isAbstract ( mods ) && ! Modifier . isNative ( mods ) ) { concreteMethods . put ( methods [ i ] . getName ( ) + methods [ i ] . getSignature ( ) , methods [ i ] ) ; } } decorateENCBindCalls ( ) ; decorateNewThreadCalls ( ) ; if ( isAbstractSbbClassDecorated ) { try { String deployDir = component . getDeploymentDir ( ) . getAbsolutePath ( ) ; sbbAbstractClass . writeFile ( deployDir ) ; sbbAbstractClass . detach ( ) ; // the file on disk is now in sync with the latest in-memory version\r if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Modified Abstract Class \" + sbbAbstractClass . getName ( ) + \" generated in the following path \" + deployDir ) ; } //} catch (NotFoundException e) {\r //    String s = \"Error writing modified abstract sbb class\";\r //    logger.error(s,e);\r //    throw new DeploymentException (s,e);\r } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } finally { sbbAbstractClass . defrost ( ) ; } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokers for the simple types [CODESPLIT] public void invokeAndReturnvoid ( SbbConcrete proxy , String methodName , Object [ ] args , Class < ? > [ ] argTypes ) throws Exception { invokeAndReturnObject ( proxy , methodName , args , argTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a constructor . This method simply records the input parameters in appropriately named fields . [CODESPLIT] private void createConstructor ( CtClass concreteClass , CtClass sleeContainerClass , CtClass resourceAdaptorTypeIDClass ) throws Exception { CtConstructor ctCons = new CtConstructor ( new CtClass [ ] { sleeContainerClass , resourceAdaptorTypeIDClass } , concreteClass ) ; ctCons . setBody ( \"{ super($1,$2); }\" ) ; concreteClass . addConstructor ( ctCons ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setTimeBetweenLivenessQueries ( long set ) { acFactory . getConfiguration ( ) . setTimeBetweenLivenessQueries ( set ) ; if ( set == 0 ) { cancelLivenessQuery ( ) ; } else { if ( scheduledFuture == null ) { scheduleLivenessQuery ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--- OPERATIONS [CODESPLIT] public void endActivity ( ActivityContextHandle ach ) throws ManagementException { // Again this is tx method\r logger . info ( \"Trying to stop null activity[\" + ach + \"]!!\" ) ; ActivityContext ac = acFactory . getActivityContext ( ach ) ; if ( ac == null ) { logger . debug ( \"There is no ac associated with given acID[\" + ach + \"]!!\" ) ; throw new ManagementException ( \"Can not find AC for given ID[\" + ach + \"], try again!!!\" ) ; } if ( ac . getActivityContextHandle ( ) . getActivityType ( ) == ActivityType . NULL ) { logger . debug ( \"Scheduling activity end for acID[\" + ach + \"]\" ) ; NullActivity nullActivity = ( NullActivity ) ac . getActivityContextHandle ( ) . getActivityObject ( ) ; if ( nullActivity != null ) { nullActivity . endActivity ( ) ; } } else { logger . debug ( \"AC is not null activity context\" ) ; throw new IllegalArgumentException ( \"Given ID[\" + ach + \"] does not point to NullActivity\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is main place where SLEE is accessed . This functions lists AC in various different ways . It can either return Object [] of arrays representing AC of simple Object [] that in fact contains String objects representing IDs of Activity Contexts [CODESPLIT] private Object [ ] listWithCriteria ( boolean listIDsOnly , boolean inDetails , int criteria , String comparisonCriteria ) { logger . info ( \"Listing with criteria[\" + criteria + \"] with details[\" + inDetails + \"] only IDS[\" + listIDsOnly + \"]\" ) ; Iterator < ActivityContextHandle > it = this . acFactory . getAllActivityContextsHandles ( ) . iterator ( ) ; ArrayList < Object > lst = new ArrayList < Object > ( ) ; // Needed by LIST_BY_SBBID\r HashMap < SbbEntityID , SbbID > sbbEntityIdToSbbID = new HashMap < SbbEntityID , SbbID > ( ) ; while ( it . hasNext ( ) ) { ActivityContextHandle achOrig = it . next ( ) ; //JmxActivityContextHandle ach = ActivityContextHandleSerializer.encode(achOrig);\r ActivityContextImpl ac = this . acFactory . getActivityContext ( achOrig ) ; if ( ac == null ) { continue ; } Object activity = achOrig . getActivityObject ( ) ; if ( activity != null ) { String acId = ac . getStringID ( ) ; String acSource = achOrig . getActivityType ( ) == ActivityType . RA ? ( ( ResourceAdaptorActivityContextHandle ) achOrig ) . getResourceAdaptorEntity ( ) . getName ( ) : \"\" ; switch ( criteria ) { case LIST_BY_ACTIVITY_CLASS : if ( ! activity . getClass ( ) . getCanonicalName ( ) . equals ( comparisonCriteria ) ) { ac = null ; // we dont want this one here\r } break ; case LIST_BY_RAENTITY : if ( achOrig . getActivityType ( ) == ActivityType . RA ) { if ( ! acSource . equals ( comparisonCriteria ) ) ac = null ; } else ac = null ; break ; case LIST_BY_SBBENTITY : for ( SbbEntityID sbbEntityID : ac . getSbbAttachmentSet ( ) ) { if ( sbbEntityID . toString ( ) . equals ( comparisonCriteria ) ) { break ; } } ac = null ; break ; case LIST_BY_SBBID : ComponentIDPropertyEditor propertyEditor = new ComponentIDPropertyEditor ( ) ; propertyEditor . setAsText ( comparisonCriteria ) ; SbbID idBeingLookedUp = ( SbbID ) propertyEditor . getValue ( ) ; boolean match = false ; SbbID implSbbID = null ; for ( SbbEntityID sbbEntityID : ac . getSbbAttachmentSet ( ) ) { if ( sbbEntityIdToSbbID . containsKey ( sbbEntityID ) ) { implSbbID = sbbEntityIdToSbbID . get ( sbbEntityID ) ; } else { SbbEntity sbbe = sbbEntityFactory . getSbbEntity ( sbbEntityID , false ) ; if ( sbbe == null ) { continue ; } implSbbID = sbbe . getSbbId ( ) ; sbbEntityIdToSbbID . put ( sbbEntityID , implSbbID ) ; } if ( ! implSbbID . equals ( idBeingLookedUp ) ) { match = false ; continue ; } else { match = true ; break ; } } if ( ! match ) { ac = null ; } break ; case LIST_BY_NO_CRITERIA : break ; default : continue ; } if ( ac == null ) continue ; // Now we have to check - if we want only IDS\r Object singleResult = null ; if ( ! listIDsOnly ) { logger . debug ( \"Adding AC[\" + acId + \"]\" ) ; Object [ ] o = getDetails ( ac ) ; if ( ! inDetails ) { // This is stupid, but can save some bandwith, not sure if\r // we\r // should care. But Console is java script, and\r // sometimes that can be pain, so lets ease it\r o [ SBB_ATTACHMENTS ] = Integer . toString ( ( ( Object [ ] ) o [ SBB_ATTACHMENTS ] ) . length ) ; o [ NAMES_BOUND_TO ] = Integer . toString ( ( ( Object [ ] ) o [ NAMES_BOUND_TO ] ) . length ) ; o [ TIMERS_ATTACHED ] = Integer . toString ( ( ( Object [ ] ) o [ TIMERS_ATTACHED ] ) . length ) ; o [ DATA_PROPERTIES ] = Integer . toString ( ( ( Object [ ] ) o [ DATA_PROPERTIES ] ) . length ) ; } singleResult = o ; } else { singleResult = acId ; } lst . add ( singleResult ) ; } } if ( lst . isEmpty ( ) ) return null ; logger . info ( \"RETURN SIZE[\" + lst . size ( ) + \"]\" ) ; Object [ ] ret = new Object [ lst . size ( ) ] ; ret = lst . toArray ( ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * FIXME uncomment code when everything is commited [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) private Object [ ] getDetails ( ActivityContextImpl ac ) { logger . debug ( \"Retrieveing details for acID[\" + ac . getActivityContextHandle ( ) + \"]\" ) ; Object [ ] o = new Object [ ARRAY_SIZE ] ; ActivityContextHandle achOrig = ac . getActivityContextHandle ( ) ; //JmxActivityContextHandle ach = ActivityContextHandleSerializer.encode(achOrig);\r String acId = ac . getStringID ( ) ; o [ ActivityManagementMBeanImplMBean . AC_ID ] = acId ; logger . debug ( \"======[getDetails][\" + o [ ActivityManagementMBeanImplMBean . AC_ID ] + \"][\" + ac . hashCode ( ) + \"]\" ) ; if ( achOrig . getActivityType ( ) == ActivityType . RA ) { o [ RA ] = ( ( ResourceAdaptorActivityContextHandle ) achOrig ) . getResourceAdaptorEntity ( ) . getName ( ) ; } o [ ACTIVITY_CLASS ] = achOrig . getActivityObject ( ) . getClass ( ) . getName ( ) ; logger . debug ( \"======[getDetails][ACTIVITY_CLASS][\" + o [ ACTIVITY_CLASS ] + \"]\" ) ; // Date d = new Date(ac.getLastAccessTime());\r // o[LAST_ACCESS_TIME] = d;\r o [ LAST_ACCESS_TIME ] = ac . getLastAccessTime ( ) + \"\" ; logger . debug ( \"======[getDetails][LAST_ACCESS_TIME][\" + o [ LAST_ACCESS_TIME ] + \"][\" + new Date ( Long . parseLong ( ( String ) o [ LAST_ACCESS_TIME ] ) ) + \"]\" ) ; Set < SbbEntityID > sbbAttachmentSet = ac . getSbbAttachmentSet ( ) ; String [ ] tmp = new String [ sbbAttachmentSet . size ( ) ] ; Iterator < ? > it = sbbAttachmentSet . iterator ( ) ; int counter = 0 ; while ( it . hasNext ( ) ) { tmp [ counter ++ ] = it . next ( ) . toString ( ) ; } o [ SBB_ATTACHMENTS ] = tmp ; Set < String > nameBindindsSet = ac . getNamingBindings ( ) ; tmp = new String [ nameBindindsSet . size ( ) ] ; tmp = nameBindindsSet . toArray ( tmp ) ; o [ NAMES_BOUND_TO ] = tmp ; Set < TimerID > attachedTimersSet = ac . getAttachedTimers ( ) ; tmp = new String [ attachedTimersSet . size ( ) ] ; it = attachedTimersSet . iterator ( ) ; counter = 0 ; while ( it . hasNext ( ) ) { tmp [ counter ++ ] = ( ( TimerID ) it . next ( ) ) . toString ( ) ; } o [ TIMERS_ATTACHED ] = tmp ; Map m = ac . getDataAttributes ( ) ; tmp = new String [ m . size ( ) ] ; it = m . keySet ( ) . iterator ( ) ; counter = 0 ; while ( it . hasNext ( ) ) { Object k = it . next ( ) ; Object v = m . get ( k ) ; tmp [ counter ++ ] = k + \"=\" + v ; } o [ DATA_PROPERTIES ] = tmp ; return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not exist? [CODESPLIT] public Object [ ] retrieveActivityContextIDByActivityType ( String fullQualifiedActivityClassName ) { logger . info ( \"Retrieving AC by activity class name[\" + fullQualifiedActivityClassName + \"]\" ) ; return listWithCriteria ( true , true , LIST_BY_ACTIVITY_CLASS , fullQualifiedActivityClassName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the real aci data field name [CODESPLIT] private String getRealFieldName ( String fieldName ) { String realFieldName = sbbComponent . getDescriptor ( ) . getActivityContextAttributeAliases ( ) . get ( fieldName ) ; if ( realFieldName == null ) { // not there then it has no alias, lets set one based on sbb id realFieldName = sbbComponent . getSbbID ( ) . toString ( ) + \".\" + fieldName ; final Map < String , String > aliases = sbbComponent . getDescriptor ( ) . getActivityContextAttributeAliases ( ) ; synchronized ( aliases ) { aliases . put ( fieldName , realFieldName ) ; } } return realFieldName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets an sbb aci data field value [CODESPLIT] public void setFieldValue ( String fieldName , Object value ) { String realFieldName = getRealFieldName ( fieldName ) ; aciImpl . getActivityContext ( ) . setDataAttribute ( realFieldName , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves an sbb aci data field value [CODESPLIT] public Object getFieldValue ( String fieldName , Class < ? > returnType ) { String realFieldName = getRealFieldName ( fieldName ) ; Object value = aciImpl . getActivityContext ( ) . getDataAttribute ( realFieldName ) ; if ( value == null ) { if ( returnType . isPrimitive ( ) ) { if ( returnType . equals ( Integer . TYPE ) ) { return Integer . valueOf ( 0 ) ; } else if ( returnType . equals ( Boolean . TYPE ) ) { return Boolean . FALSE ; } else if ( returnType . equals ( Long . TYPE ) ) { return Long . valueOf ( 0 ) ; } else if ( returnType . equals ( Double . TYPE ) ) { return Double . valueOf ( 0 ) ; } else if ( returnType . equals ( Float . TYPE ) ) { return Float . valueOf ( 0 ) ; } } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void fireEvent ( Object event , EventTypeID eventType , ExternalActivityHandle activityHandle , Address address ) throws NullPointerException , UnrecognizedActivityException , UnrecognizedEventException , ResourceException { if ( service == null ) { throw new ResourceException ( \"Connection is in closed state\" ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"fireEvent(event=\" + event + \",eventType=\" + eventType + \",activityHandle=\" + activityHandle + \",address=\" + address + \")\" ) ; } this . service . fireEvent ( event , eventType , activityHandle , address ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventTypeID getEventTypeID ( String name , String vendor , String version ) throws UnrecognizedEventException , ResourceException { if ( service == null ) { throw new ResourceException ( \"Connection is in closed state\" ) ; } return service . getEventTypeID ( name , vendor , version ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SleeConnection getConnection ( ) throws ResourceException { //this method is listed as MBean method, upon lookup in jmx console it will create connection, its a possible leak \r //with list.\r synchronized ( connectionList ) { SleeConnectionImpl conn ; if ( connectionList . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Using connection from pool.\" ) ; } conn = ( SleeConnectionImpl ) connectionList . remove ( 0 ) ; conn . start ( this . service ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Creating new connection.\" ) ; } conn = new SleeConnectionImpl ( this . service , this ) ; } return conn ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked from pool . [CODESPLIT] public void setProfileContext ( ProfileContextImpl profileContext ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"[setProfileContext] \" + this ) ; } if ( profileContext == null ) { throw new NullPointerException ( \"Passed context must not be null.\" ) ; } if ( state != ProfileObjectState . DOES_NOT_EXIST ) { throw new IllegalStateException ( \"Wrong state: \" + this . state + \",on profile set context operation, for profile table: \" + this . profileTable . getProfileTableName ( ) + \" with specification: \" + this . profileTable . getProfileSpecificationComponent ( ) . getProfileSpecificationID ( ) ) ; } this . profileContext = profileContext ; this . profileContext . setProfileObject ( this ) ; if ( profileConcreteClassInfo . isInvokeSetProfileContext ( ) ) { final ClassLoader oldClassLoader = SleeContainerUtils . getCurrentThreadClassLoader ( ) ; try { final ClassLoader cl = this . profileTable . getProfileSpecificationComponent ( ) . getClassLoader ( ) ; if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; } try { if ( isSlee11 ) { try { profileConcrete . setProfileContext ( profileContext ) ; } catch ( RuntimeException e ) { runtimeExceptionOnProfileInvocation ( e ) ; } } } catch ( Exception e ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( \"Exception encountered while setting profile context for profile table: \" + this . profileTable . getProfileTableName ( ) + \" with specification: \" + this . profileTable . getProfileSpecificationComponent ( ) . getProfileSpecificationID ( ) , e ) ; } } finally { if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } } } state = ProfileObjectState . POOLED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initialize state from default profile [CODESPLIT] private void profileInitialize ( String profileName ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"[profileInitialize] \" + this + \" , profileName = \" + profileName ) ; } if ( this . state != ProfileObjectState . POOLED ) { throw new SLEEException ( this . toString ( ) ) ; } if ( profileName == null ) { // default profile creation // create instance of entity profileEntity = profileEntityFramework . getProfileEntityFactory ( ) . newInstance ( profileTable . getProfileTableName ( ) , null ) ; // change state this . state = ProfileObjectState . PROFILE_INITIALIZATION ; // invoke life cycle method on profile if ( profileConcreteClassInfo . isInvokeProfileInitialize ( ) ) { try { profileConcrete . profileInitialize ( ) ; } catch ( RuntimeException e ) { runtimeExceptionOnProfileInvocation ( e ) ; } } } else { // load the default profile entity if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Copying state from default profile on object \" + this ) ; } profileEntity = cloneEntity ( profileTable . getDefaultProfileEntity ( ) ) ; profileEntity . setProfileName ( profileName ) ; } // mark entity as dirty and for creation profileEntity . create ( ) ; profileEntity . setDirty ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when pool removes object [CODESPLIT] public void unsetProfileContext ( ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"[unsetProfileContext] \" + this ) ; } if ( state == ProfileObjectState . POOLED && profileConcreteClassInfo . isInvokeUnsetProfileContext ( ) ) { final ClassLoader oldClassLoader = SleeContainerUtils . getCurrentThreadClassLoader ( ) ; try { final ClassLoader cl = profileTable . getProfileSpecificationComponent ( ) . getClassLoader ( ) ; if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( cl ) ; } if ( isSlee11 ) { try { profileConcrete . unsetProfileContext ( ) ; } catch ( RuntimeException e ) { runtimeExceptionOnProfileInvocation ( e ) ; } } profileContext . setProfileObject ( null ) ; state = ProfileObjectState . DOES_NOT_EXIST ; } finally { if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; return null ; } } ) ; } else { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the local representation for this profile object [CODESPLIT] public ProfileLocalObject getProfileLocalObject ( ) { final Class < ? > profileLocalObjectConcreteClass = profileTable . getProfileSpecificationComponent ( ) . getProfileLocalObjectConcreteClass ( ) ; ProfileLocalObject profileLocalObject = null ; if ( profileLocalObjectConcreteClass == null ) { profileLocalObject = new ProfileLocalObjectImpl ( this ) ; } else { try { profileLocalObject = ( ProfileLocalObject ) profileLocalObjectConcreteClass . getConstructor ( ProfileObjectImpl . class ) . newInstance ( this ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } return profileLocalObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires a profile added or updated event if the profile object state is ready and the persistent state is dirty [CODESPLIT] public void fireAddOrUpdatedEventIfNeeded ( ) { if ( state == ProfileObjectState . READY ) { if ( profileEntity . isDirty ( ) ) { // check the table fires events and the object is not assigned to a default profile if ( profileTable . doesFireEvents ( ) && profileEntity . getProfileName ( ) != null && profileTable . getSleeContainer ( ) . getSleeState ( ) == SleeState . RUNNING ) { // Fire a Profile Added or Updated Event ActivityContext ac = profileTable . getActivityContext ( ) ; AbstractProfileEvent event = null ; if ( profileEntity . isCreate ( ) ) { if ( persisted ) { event = new ProfileAddedEventImpl ( profileEntity , profileTable . getProfileManagement ( ) ) ; persisted = false ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"firing profile added event for profile named \" + profileEntity ) ; } } else { return ; } } else { event = new ProfileUpdatedEventImpl ( profileEntitySnapshot , profileEntity , profileTable . getProfileManagement ( ) ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"firing profile updated event for profile named \" + profileEntity ) ; } } ac . fireEvent ( event . getEventTypeID ( ) , event , event . getProfileAddress ( ) , null , null , null , null ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the profile cmp slee 1 . 0 wrapper for this profile object [CODESPLIT] public AbstractProfileCmpSlee10Wrapper getProfileCmpSlee10Wrapper ( ) { if ( profileCmpSlee10Wrapper == null ) { try { profileCmpSlee10Wrapper = ( AbstractProfileCmpSlee10Wrapper ) profileTable . getProfileSpecificationComponent ( ) . getProfileCmpSlee10WrapperClass ( ) . getConstructor ( ProfileObjectImpl . class ) . newInstance ( this ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } return profileCmpSlee10Wrapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { final ServiceID serviceID = new ServiceID ( in . readUTF ( ) , in . readUTF ( ) , in . readUTF ( ) ) ; activityHandle = new ServiceActivityHandleImpl ( serviceID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { final ServiceID serviceID = activityHandle . getServiceID ( ) ; out . writeUTF ( serviceID . getName ( ) ) ; out . writeUTF ( serviceID . getVendor ( ) ) ; out . writeUTF ( serviceID . getVersion ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JAIN SLEE specs descriptor [CODESPLIT] public javax . slee . management . LibraryDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { final LibraryID [ ] libraryIDs = descriptor . getLibraryRefs ( ) . toArray ( new LibraryID [ descriptor . getLibraryRefs ( ) . size ( ) ] ) ; final JarDescriptor [ ] jars = descriptor . getJars ( ) . toArray ( new JarDescriptor [ descriptor . getJars ( ) . size ( ) ] ) ; String [ ] libraryJars = new String [ jars . length ] ; int i = 0 ; for ( JarDescriptor jar : jars ) { libraryJars [ i ++ ] = jar . getJarName ( ) ; } specsDescriptor = new javax . slee . management . LibraryDescriptor ( getLibraryID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , libraryIDs , libraryJars ) ; } return specsDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a class with the desired name and linked to the mentioned interfaces . [CODESPLIT] public static CtClass createClass ( String className , String [ ] interfaces ) throws Exception { if ( className == null ) { throw new NullPointerException ( \"Class name cannot be null\" ) ; } CtClass clazz = classPool . makeClass ( className ) ; if ( interfaces != null && interfaces . length > 0 ) { clazz . setInterfaces ( classPool . get ( interfaces ) ) ; } return clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the links with possible interfaces [CODESPLIT] public static void createInterfaceLinks ( CtClass concreteClass , String [ ] interfaceNames ) { if ( interfaceNames != null && interfaceNames . length > 0 ) { try { for ( String interfaceName : interfaceNames ) { boolean found = false ; for ( CtClass existingInterfaces : concreteClass . getInterfaces ( ) ) { if ( existingInterfaces . getName ( ) . equals ( interfaceName ) ) found = true ; } if ( ! found ) concreteClass . addInterface ( classPool . get ( interfaceName ) ) ; } } catch ( NotFoundException e ) { e . printStackTrace ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the inheritance link with the absract class provided by the developer [CODESPLIT] public static void createInheritanceLink ( CtClass concreteClass , String superClassName ) { if ( superClassName != null && superClassName . length ( ) >= 0 ) { try { concreteClass . setSuperclass ( classPool . get ( superClassName ) ) ; } catch ( CannotCompileException e ) { e . printStackTrace ( ) ; } catch ( NotFoundException e ) { e . printStackTrace ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a field of the desired type to the declaring class . [CODESPLIT] public static CtField addField ( CtClass fieldType , String fieldName , CtClass declaringClass ) throws CannotCompileException { return addField ( fieldType , fieldName , declaringClass , Modifier . PRIVATE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a field of the desired type to the declaring class . [CODESPLIT] public static CtField addField ( CtClass fieldType , String fieldName , CtClass declaringClass , int modifier ) throws CannotCompileException { return addField ( fieldType , fieldName , declaringClass , modifier , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a field of the desired type to the declaring class . [CODESPLIT] public static CtField addField ( CtClass fieldType , String fieldName , CtClass declaringClass , int modifier , String initializerExpr ) throws CannotCompileException { CtField field = new CtField ( fieldType , decapitalize ( fieldName ) , declaringClass ) ; field . setModifiers ( modifier ) ; if ( initializerExpr != null ) { declaringClass . addField ( field , CtField . Initializer . byExpr ( initializerExpr ) ) ; } else { declaringClass . addField ( field ) ; } return field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a getter for the field ( get<FieldName > ) and adds it to the declaring class . [CODESPLIT] public static CtMethod generateGetter ( CtField field , String interceptorAccess ) throws NotFoundException , CannotCompileException { String getterName = \"get\" + capitalize ( field . getName ( ) ) ; CtMethod getter = CtNewMethod . getter ( getterName , field ) ; if ( interceptorAccess != null ) getter . setBody ( interceptorAccess + \".\" + getterName + \"($$);\" ) ; field . getDeclaringClass ( ) . addMethod ( getter ) ; return getter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a setter for the field ( get<FieldName > ) and adds it to the declaring class . [CODESPLIT] public static CtMethod generateSetter ( CtField field , String interceptorAccess ) throws NotFoundException , CannotCompileException { String setterName = \"set\" + capitalize ( field . getName ( ) ) ; CtMethod setter = CtNewMethod . setter ( setterName , field ) ; if ( interceptorAccess != null ) setter . setBody ( interceptorAccess + \".\" + setterName + \"($$);\" ) ; field . getDeclaringClass ( ) . addMethod ( setter ) ; return setter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates getter and setter for the field ( get / set<FieldName > ) and adds them to the declaring class . [CODESPLIT] public static void generateGetterAndSetter ( CtField field , String interceptorAccess ) throws NotFoundException , CannotCompileException { generateGetter ( field , interceptorAccess ) ; generateSetter ( field , interceptorAccess ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the selected annotation to the Object along with the specified memberValues . [CODESPLIT] public static void addAnnotation ( String annotation , LinkedHashMap < String , Object > memberValues , Object toAnnotate ) { if ( toAnnotate instanceof CtClass ) { CtClass classToAnnotate = ( CtClass ) toAnnotate ; ClassFile cf = classToAnnotate . getClassFile ( ) ; ConstPool cp = cf . getConstPool ( ) ; AnnotationsAttribute attr = ( AnnotationsAttribute ) cf . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( attr == null ) { attr = new AnnotationsAttribute ( cp , AnnotationsAttribute . visibleTag ) ; } Annotation a = new Annotation ( annotation , cp ) ; if ( memberValues != null ) { addMemberValuesToAnnotation ( a , cp , memberValues ) ; } attr . addAnnotation ( a ) ; cf . addAttribute ( attr ) ; } else if ( toAnnotate instanceof CtMethod ) { CtMethod methodToAnnotate = ( CtMethod ) toAnnotate ; MethodInfo mi = methodToAnnotate . getMethodInfo ( ) ; ConstPool cp = mi . getConstPool ( ) ; AnnotationsAttribute attr = ( AnnotationsAttribute ) mi . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( attr == null ) { attr = new AnnotationsAttribute ( cp , AnnotationsAttribute . visibleTag ) ; } Annotation a = new Annotation ( annotation , cp ) ; if ( memberValues != null ) { addMemberValuesToAnnotation ( a , cp , memberValues ) ; } attr . addAnnotation ( a ) ; mi . addAttribute ( attr ) ; } else if ( toAnnotate instanceof CtField ) { CtField fieldToAnnotate = ( CtField ) toAnnotate ; FieldInfo fi = fieldToAnnotate . getFieldInfo ( ) ; ConstPool cp = fi . getConstPool ( ) ; AnnotationsAttribute attr = ( AnnotationsAttribute ) fi . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( attr == null ) { attr = new AnnotationsAttribute ( cp , AnnotationsAttribute . visibleTag ) ; } Annotation a = new Annotation ( annotation , cp ) ; if ( memberValues != null ) { addMemberValuesToAnnotation ( a , cp , memberValues ) ; } attr . addAnnotation ( a ) ; fi . addAttribute ( attr ) ; } else { throw new UnsupportedOperationException ( \"Unknown object type: \" + toAnnotate . getClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private method to add member values to annotation [CODESPLIT] private static void addMemberValuesToAnnotation ( Annotation annotation , ConstPool cp , LinkedHashMap < String , Object > memberValues ) { // Get the member value object for ( String mvName : memberValues . keySet ( ) ) { Object mvValue = memberValues . get ( mvName ) ; MemberValue mv = getMemberValue ( mvValue , cp ) ; annotation . addMemberValue ( mvName , mv ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns the aci for the specified activity if exists it should be invoked by each impl of methods of an ra type aci factory . [CODESPLIT] protected ActivityContextInterface getACI ( Object activity ) throws NullPointerException , UnrecognizedActivityException , FactoryException { if ( activity == null ) { throw new NullPointerException ( \"null activity object\" ) ; } ActivityHandle handle = null ; for ( ResourceAdaptorEntity raEntity : sleeContainer . getResourceManagement ( ) . getResourceAdaptorEntitiesPerType ( resourceAdaptorTypeID ) ) { handle = raEntity . getResourceAdaptorObject ( ) . getActivityHandle ( activity ) ; if ( handle != null ) { ActivityContextHandle ach = new ResourceAdaptorActivityContextHandleImpl ( raEntity , handle ) ; ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac != null ) { return ac . getActivityContextInterface ( ) ; } break ; } } throw new UnrecognizedActivityException ( activity . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the component javassist class pool [CODESPLIT] public ClassPool getClassPool ( ) { if ( classPool == null ) { if ( classLoader == null ) { throw new IllegalStateException ( \"can't init javassit classpool, there is no class loader set for the component\" ) ; } classPool = new ClassPool ( ) ; // add class path for domain and dependencies classPool . appendClassPath ( new LoaderClassPath ( classLoaderDomain ) ) ; for ( ClassLoader domainDependencies : classLoaderDomain . getAllDependencies ( ) ) { classPool . appendClassPath ( new LoaderClassPath ( domainDependencies ) ) ; } // add class path also for slee  classPool . appendClassPath ( new LoaderClassPath ( classLoaderDomain . getParent ( ) ) ) ; } return classPool ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the the Deployable Unit this component belongs . This method also sets the reverse relation adding the component to the deployable unit [CODESPLIT] public void setDeployableUnit ( DeployableUnit deployableUnit ) throws AlreadyDeployedException { if ( this . deployableUnit != null ) { throw new IllegalStateException ( \"deployable unit already set. du = \" + this . deployableUnit ) ; } this . deployableUnit = deployableUnit ; if ( ! addToDeployableUnit ( ) ) { throw new AlreadyDeployedException ( \"unable to install du having multiple components with id \" + getComponentID ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates that the component was undeployed and thus should clean up any resources [CODESPLIT] public void undeployed ( ) { classLoader = null ; if ( classLoaderDomain != null ) { classLoaderDomain . clear ( ) ; classLoaderDomain = null ; } if ( classPool != null ) { classPool . clean ( ) ; classPool = null ; } if ( permissions != null ) { permissions . clear ( ) ; permissions = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void init ( URL deployableUnitURL , String deployableUnitName ) throws DeploymentException { synchronized ( this ) { if ( ! shutdown ) { sleeSubDeployer . init ( deployableUnitURL , deployableUnitName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void start ( URL deployableUnitURL , String deployableUnitName ) throws DeploymentException { synchronized ( this ) { if ( ! shutdown ) { sleeSubDeployer . start ( deployableUnitURL , deployableUnitName ) ; } else { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( \"Ignoring deploy invoked from external deployer, SLEE in shutdown\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ReceivableServiceImpl } instance from the specified service component [CODESPLIT] private ReceivableService createReceivableService ( ServiceComponent serviceComponent ) { ComponentRepository componentRepository = container . getComponentRepository ( ) ; HashSet < ReceivableEvent > resultSet = new HashSet < ReceivableEvent > ( ) ; for ( SbbID sbbID : serviceComponent . getSbbIDs ( componentRepository ) ) { SbbComponent sbbComponent = componentRepository . getComponentByID ( sbbID ) ; for ( EventEntryDescriptor eventEntry : sbbComponent . getDescriptor ( ) . getEventEntries ( ) . values ( ) ) { EventTypeID eventTypeID = eventEntry . getEventReference ( ) ; final Set < EventTypeID > allowedEventTypes = raEntity . getAllowedEventTypes ( ) ; if ( allowedEventTypes == null || allowedEventTypes . contains ( eventTypeID ) ) { /*\n\t\t\t\t\t * The Service Lookup Facility will only return Service\n\t\t\t\t\t * event type information forthe event types referenced by\n\t\t\t\t\t * the resource adaptor types implemented by the Resource\n\t\t\t\t\t * Adaptor.\n\t\t\t\t\t */ ReceivableEventImpl receivableEventImpl = new ReceivableEventImpl ( eventTypeID , eventEntry . getResourceOption ( ) , eventEntry . isInitialEvent ( ) ) ; // add it if it's not in the set or if it is but initial // event is set (this way if there is a conflict the one // with initial as true wins) if ( ! resultSet . contains ( receivableEventImpl ) || receivableEventImpl . isInitialEvent ( ) ) { resultSet . add ( receivableEventImpl ) ; } } } } return new ReceivableServiceImpl ( serviceComponent . getServiceID ( ) , resultSet . toArray ( new ReceivableEventImpl [ resultSet . size ( ) ] ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a non transacted start activity operation . [CODESPLIT] void execute ( final ActivityHandle handle , final int activityFlags , boolean suspendActivity ) throws SLEEException { final SleeTransaction tx = super . suspendTransaction ( ) ; ActivityContextHandle ach = null ; try { ach = sleeEndpoint . _startActivity ( handle , activityFlags , suspendActivity ? tx : null ) ; } finally { if ( tx != null ) { super . resumeTransaction ( tx ) ; // the activity was started out of the tx but it will be suspended, if the flags request the unreferenced callback then // we can load the ac now, which will schedule a check for references in the end of the tx, this ensures that the callback is received if no events are fired or  // events are fired but not handled, that is, no reference is ever ever created if ( ach != null && ActivityFlags . hasRequestSleeActivityGCCallback ( activityFlags ) ) { acFactory . getActivityContext ( ach ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the { [CODESPLIT] public Collator getCollator ( ) { if ( collator == null ) { collator = Collator . getInstance ( locale ) ; if ( hasStrength ) collator . setStrength ( strength ) ; if ( hasDecomposition ) collator . setDecomposition ( decomposition ) ; } return collator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "##################### [CODESPLIT] public static QueryWrapper parseDynamicQuery ( QueryExpression query ) { ArrayList < Object > params = new ArrayList < Object > ( ) ; long s = System . currentTimeMillis ( ) ; String sqlQuery = \"SELECT * \" + parseDynamicQuery ( query , 0 , null , params ) ; logger . info ( \"Query :: SQL[\" + sqlQuery + \"]\" ) ; long e = System . currentTimeMillis ( ) ; logger . info ( \"Query :: Parsed in \" + ( e - s ) + \"ms.\" ) ; return new QueryWrapper ( sqlQuery , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "###################### [CODESPLIT] private static String replaceLast ( String sourceString , String toBeReplaced , String replacement ) { StringBuilder x = new StringBuilder ( sourceString ) ; int liof = x . lastIndexOf ( toBeReplaced ) ; if ( liof >= 0 ) x . replace ( liof , liof + 4 , replacement ) ; return new String ( x ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This methods validate component which has usage parameter interface . Its interface for methods . In case of 1 . 1 components parameters list must match evey method defined . In case of 1 . 0 components parameters list MUST be empty . It does not validate get usage method those [CODESPLIT] static boolean validateUsageParameterInterface ( ComponentID id , boolean isSlee11 , Class < ? > usageInterface , List < UsageParameterDescriptor > parameters ) { boolean passed = true ; String errorBuffer = new String ( \"\" ) ; try { if ( ! usageInterface . isInterface ( ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Usage parameter interface class is not an interface\" , \"11.2\" , errorBuffer ) ; return passed ; } // Interface constraints\r if ( isSlee11 && usageInterface . getPackage ( ) == null ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Usage parameter interface must be declared in pacakge name space.\" , \"11.2\" , errorBuffer ) ; } if ( ! Modifier . isPublic ( usageInterface . getModifiers ( ) ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Usage parameter interface must be declared as public.\" , \"11.2\" , errorBuffer ) ; } // parameters check\r Set < String > ignore = new HashSet < String > ( ) ; ignore . add ( \"java.lang.Object\" ) ; Map < String , Method > interfaceMethods = ClassUtils . getAllInterfacesMethods ( usageInterface , ignore ) ; Map < String , UsageParameterDescriptor > localParametersMap = new HashMap < String , UsageParameterDescriptor > ( ) ; Set < String > identifiedIncrement = new HashSet < String > ( ) ; Set < String > identifiedGetIncrement = new HashSet < String > ( ) ; Set < String > identifiedSample = new HashSet < String > ( ) ; Set < String > identifiedGetSample = new HashSet < String > ( ) ; // this is for 1.1, get and increment methods must match with type\r // validate parameter names if we are slee11\r if ( isSlee11 ) for ( UsageParameterDescriptor usage : parameters ) { char c = usage . getName ( ) . charAt ( 0 ) ; if ( ! Character . isLowerCase ( c ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Parameter name must start with lower case character and be start of valid jva identifier, parameter name from descriptor: \" + usage . getName ( ) , \"11.2\" , errorBuffer ) ; } localParametersMap . put ( usage . getName ( ) , usage ) ; } // at the end we have to have empty list\r for ( Entry < String , Method > entry : interfaceMethods . entrySet ( ) ) { // String declaredLongMethodName = entry.getKey();\r Method m = entry . getValue ( ) ; String declaredMethodName = m . getName ( ) ; String declaredPrameterName = null ; Character c = null ; // he we just do checks, methods against constraints\r // we remove them from parameters map, there is something left\r // or not present in map in case of 1.1\r // some variable that we need to store info about method\r boolean isIncrement = false ; boolean isGetIncrement = false ; boolean isGetSample = false ; boolean isSample = false ; // 1.0 comp\r if ( declaredMethodName . startsWith ( _SAMPLE_METHOD_PREFIX ) ) { declaredPrameterName = declaredMethodName . replaceFirst ( _SAMPLE_METHOD_PREFIX , \"\" ) ; c = declaredPrameterName . charAt ( 0 ) ; isSample = true ; // 1.0 comp\r } else if ( declaredMethodName . startsWith ( _INCREMENT_METHOD_PREFIX ) ) { declaredPrameterName = declaredMethodName . replaceFirst ( _INCREMENT_METHOD_PREFIX , \"\" ) ; c = declaredPrameterName . charAt ( 0 ) ; isIncrement = true ; // 1.1 only\r } else if ( declaredMethodName . startsWith ( _GET_METHOD_PREFIX ) ) { declaredPrameterName = declaredMethodName . replaceFirst ( _GET_METHOD_PREFIX , \"\" ) ; c = declaredPrameterName . charAt ( 0 ) ; if ( ! isSlee11 ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Wrong method declared in parameter usage interface. Get method for counter parameter types are allowed only in JSLEE 1.1, method: \" + declaredMethodName , \"11.2.X\" , errorBuffer ) ; } if ( m . getReturnType ( ) . getName ( ) . compareTo ( \"javax.slee.usage.SampleStatistics\" ) == 0 ) { isGetSample = true ; } else { // we asume thats increment get\r isGetIncrement = true ; } } else { passed = false ; errorBuffer = appendToBuffer ( id , \"Wrong method decalred in parameter usage interface. Methods must start with either \\\"get\\\", \\\"sample\\\" or \\\"increment\\\", method: \" + declaredMethodName , \"11.2.X\" , errorBuffer ) ; continue ; } if ( ! Character . isUpperCase ( c ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Method stripped of prefix, either \\\"get\\\", \\\"sample\\\" or \\\"increment\\\", must have following upper case character,method: \" + declaredMethodName , \"11.2\" , errorBuffer ) ; } declaredPrameterName = Introspector . decapitalize ( declaredPrameterName ) ; if ( ! isValidJavaIdentifier ( declaredPrameterName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Parameter name must be valid java identifier: \" + declaredPrameterName , \"11.2\" , errorBuffer ) ; } // well we have indentified parameter, lets store;\r if ( isIncrement ) { if ( identifiedIncrement . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: \" + declaredMethodName , \"11.2\" , errorBuffer ) ; } else { identifiedIncrement . add ( declaredPrameterName ) ; if ( ! validateParameterSetterSignatureMethod ( id , m , \"11.2.3\" ) ) { passed = false ; } } } else if ( isGetIncrement ) { if ( identifiedGetIncrement . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: \" + declaredMethodName , \"11.2\" , errorBuffer ) ; } else { identifiedGetIncrement . add ( declaredPrameterName ) ; if ( ! validateParameterGetterSignatureMethod ( id , m , \"11.2.2\" , Long . TYPE ) ) { passed = false ; } } } else if ( isGetSample ) { if ( identifiedGetSample . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: \" + declaredMethodName , \"11.2\" , errorBuffer ) ; } else { identifiedGetSample . add ( declaredPrameterName ) ; if ( ! validateParameterGetterSignatureMethod ( id , m , \"11.2.4\" , javax . slee . usage . SampleStatistics . class ) ) { passed = false ; } } } else if ( isSample ) { if ( identifiedSample . contains ( declaredMethodName ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: \" + declaredMethodName , \"11.2\" , errorBuffer ) ; } else { identifiedSample . add ( declaredPrameterName ) ; if ( ! validateParameterSetterSignatureMethod ( id , m , \"11.2.1\" ) ) { passed = false ; errorBuffer = appendToBuffer ( id , \"Duplicate declaration of usage parameter, possibly twe methods with the same name and different signature, method: \" + declaredMethodName , \"11.2\" , errorBuffer ) ; } } } // UFFF, lets start the play\r // /uh its a bit complicated\r } // we siganture here is ok, return types also, no duplicates, left:\r // 1. cross check field types that we found - sample vs increments -\r // there cant be doubles\r // 2. remove all from list, if something is left, bam, we lack one\r // method or have to many :)\r Set < String > agregatedIncrement = new HashSet < String > ( ) ; Set < String > agregatedSample = new HashSet < String > ( ) ; agregatedIncrement . addAll ( identifiedGetIncrement ) ; agregatedIncrement . addAll ( identifiedIncrement ) ; agregatedSample . addAll ( identifiedGetSample ) ; agregatedSample . addAll ( identifiedSample ) ; Set < String > tmp = new HashSet < String > ( agregatedSample ) ; tmp . retainAll ( agregatedIncrement ) ; if ( ! tmp . isEmpty ( ) ) { // ugh, its the end\r passed = false ; errorBuffer = appendToBuffer ( id , \"Usage parameters can be associated only with single type - increment or sample, offending parameters: \" + Arrays . toString ( tmp . toArray ( ) ) , \"11.2\" , errorBuffer ) ; return passed ; } if ( isSlee11 ) { tmp . clear ( ) ; tmp . addAll ( agregatedSample ) ; tmp . addAll ( agregatedIncrement ) ; // localParametersMap.size()!=0 - cause we can have zero of them\r // - usage-parameter may not be present so its generation is\r // turned off\r if ( localParametersMap . size ( ) != tmp . size ( ) && localParametersMap . size ( ) != 0 ) { passed = false ; String errorPart = null ; if ( localParametersMap . size ( ) > tmp . size ( ) ) { // is there any bettter way?\r for ( String s : localParametersMap . keySet ( ) ) tmp . remove ( s ) ; errorPart = \"More parameters are defined in descriptor, offending parameters: \" + Arrays . toString ( tmp . toArray ( ) ) ; } else { for ( String s : tmp ) localParametersMap . remove ( s ) ; errorPart = \"More parameters are defined in descriptor, offending parameters: \" + Arrays . toString ( localParametersMap . keySet ( ) . toArray ( ) ) ; } errorBuffer = appendToBuffer ( id , \"Failed to map descriptor defined usage parameters against interface class methods. \" + errorPart , \"11.2\" , errorBuffer ) ; } } } finally { if ( ! passed ) { logger . error ( errorBuffer ) ; // System.err.println(errorBuffer);\r } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches for provided interface in passed Class object - it can be class or interface . If it finds it return instance of it . [CODESPLIT] public static Class checkInterfaces ( Class classOrInterfaceWithInterfaces , String interfaceSearched ) { Class returnValue = null ; if ( classOrInterfaceWithInterfaces . getName ( ) . compareTo ( interfaceSearched ) == 0 ) { return classOrInterfaceWithInterfaces ; } // we do check only on get interfaces for ( Class iface : classOrInterfaceWithInterfaces . getInterfaces ( ) ) { if ( iface . getName ( ) . compareTo ( interfaceSearched ) == 0 ) { returnValue = iface ; } else { returnValue = checkInterfaces ( iface , interfaceSearched ) ; } if ( returnValue != null ) break ; } if ( ! classOrInterfaceWithInterfaces . isInterface ( ) && returnValue == null ) { Class superClass = classOrInterfaceWithInterfaces . getSuperclass ( ) ; if ( superClass != null ) { returnValue = checkInterfaces ( superClass , interfaceSearched ) ; } } return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns methods of this interface and all super interfaces [CODESPLIT] public static Map < String , Method > getAllInterfacesMethods ( Class xInterfaceClass , Set < String > ignore ) { HashMap < String , Method > abstractMethods = new HashMap < String , Method > ( ) ; Method [ ] methods = null ; Class [ ] superInterfaces ; superInterfaces = xInterfaceClass . getInterfaces ( ) ; for ( Class superInterface : superInterfaces ) { if ( ! ignore . contains ( superInterface . getName ( ) ) ) abstractMethods . putAll ( getAllInterfacesMethods ( superInterface , ignore ) ) ; } methods = xInterfaceClass . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { abstractMethods . put ( getMethodKey ( methods [ i ] ) , methods [ i ] ) ; } return abstractMethods ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static Method getMethodFromMap ( String name , Class [ ] parameters , Map < String , Method > ... methods ) { String key = name + Arrays . toString ( parameters ) ; for ( Map < String , Method > m : methods ) { if ( m . containsKey ( key ) ) { return m . get ( key ) ; } else { } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an InputSource with a SystemID corresponding to a local dtd file . [CODESPLIT] public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { URL resourceURL = resources . get ( publicId ) ; if ( resourceURL != null ) { InputStream resourceStream = resourceURL . openStream ( ) ; InputSource is = new InputSource ( resourceStream ) ; is . setPublicId ( publicId ) ; is . setSystemId ( resourceURL . toExternalForm ( ) ) ; return is ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setTraceLevel ( ComponentID componentId , Level level ) throws NullPointerException , UnrecognizedComponentException , ManagementException { if ( componentId == null ) throw new NullPointerException ( \"null component Id\" ) ; this . traceFacility . checkComponentID ( componentId ) ; this . traceFacility . setTraceLevel ( componentId , level ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Level getTraceLevel ( ComponentID componentId ) throws NullPointerException , UnrecognizedComponentException , ManagementException { if ( componentId == null ) throw new NullPointerException ( \" null component Id \" ) ; return this . traceFacility . getTraceLevel ( componentId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public MBeanNotificationInfo [ ] getNotificationInfo ( ) { if ( this . traceFacility == null ) return null ; String [ ] notificationTypes = this . traceFacility . getNotificationTypes ( ) ; return new MBeanNotificationInfo [ ] { new MBeanNotificationInfo ( notificationTypes , TraceMBean . TRACE_NOTIFICATION_TYPE , \"SLEE Spec 1.0, #13.4. SBBs use the Trace Facility to generate trace messages intended for \" + \"consumption by external management clients, such as a network management console or a management policy engine.\" ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public TraceLevel getTraceLevel ( NotificationSource src , String tracerName ) throws NullPointerException , InvalidArgumentException , UnrecognizedNotificationSourceException , ManagementException { if ( src == null ) { throw new NullPointerException ( \"NotificationSource must not be null!\" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( \"Notification source not recognized: \" + src ) ; } TracerImpl . checkTracerName ( tracerName , src ) ; if ( ! this . isTracerDefined ( src , tracerName ) ) { //FIXME: what is valid tracer name? JDOC contradicts that not existing tracer name is invalid\r this . createTracer ( src , tracerName , false ) ; } TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( \"NotificationSource has been uninstalled from SLEE. Can not create tracer.\" ) ; } try { return ts . getTracerLevel ( tracerName ) ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to get trace level due to: \" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String [ ] getTracersSet ( NotificationSource src ) throws NullPointerException , UnrecognizedNotificationSourceException , ManagementException { if ( src == null ) { throw new NullPointerException ( \"NotificationSource must nto be null!\" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( \"Notification source not recognized: \" + src ) ; } TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( \"NotificationSource has been uninstalled from SLEE. Can not create tracer.\" ) ; } return ts . getDefinedTracerNames ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String [ ] getTracersUsed ( NotificationSource src ) throws NullPointerException , UnrecognizedNotificationSourceException , ManagementException { if ( src == null ) { throw new NullPointerException ( \"NotificationSource must nto be null!\" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( \"Notification source not recognized: \" + src ) ; } TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( \"NotificationSource has been uninstalled from SLEE. Can not create tracer.\" ) ; } return ts . getRequestedTracerNames ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setTraceLevel ( NotificationSource src , final String tracerName , TraceLevel lvl ) throws NullPointerException , UnrecognizedNotificationSourceException , InvalidArgumentException , ManagementException { if ( src == null ) { throw new NullPointerException ( \"NotificationSource must nto be null!\" ) ; } if ( lvl == null ) { throw new NullPointerException ( \"TraceLevel must not be null!\" ) ; } if ( ! this . isNotificationSourceDefined ( src ) ) { throw new UnrecognizedNotificationSourceException ( \"Notification source not recognized: \" + src ) ; } TracerImpl . checkTracerName ( tracerName , src ) ; if ( ! this . isTracerDefined ( src , tracerName ) ) { //FIXME: what is valid tracer name? JDOC contradicts that not existing tracer name is invalid\r this . createTracer ( src , tracerName , false ) ; } final TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( \"NotificationSource has been uninstalled from SLEE. Can not create tracer.\" ) ; } try { try { final SleeTransactionManager sleeTransactionManager = sleeContainer . getTransactionManager ( ) ; if ( sleeTransactionManager . getTransaction ( ) != null ) { final TraceLevel _oldLevel = ts . getTracerLevel ( tracerName ) ; TransactionalAction action = new TransactionalAction ( ) { TraceLevel oldLevel = _oldLevel ; public void execute ( ) { try { ts . setTracerLevel ( oldLevel , tracerName ) ; } catch ( InvalidArgumentException e ) { logger . error ( e . getMessage ( ) , e ) ; } } } ; sleeTransactionManager . getTransactionContext ( ) . getAfterRollbackActions ( ) . add ( action ) ; } } catch ( SystemException e ) { e . printStackTrace ( ) ; } ts . setTracerLevel ( lvl , tracerName ) ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to set trace level due to: \" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This checks if tracer name is ok . It must not be null ; [CODESPLIT] public static void checkTracerName ( String tracerName , NotificationSource notificationSource ) throws IllegalArgumentException { if ( tracerName . compareTo ( \"\" ) == 0 ) { // This is root\r return ; } // String[] splitName = tracerName.split(\"\\\\.\");\r StringTokenizer stringTokenizer = new StringTokenizer ( tracerName , \".\" , true ) ; int fqdnPartIndex = 0 ; // if(splitName.length==0)\r // {\r // throw new IllegalArgumentException(\"Passed tracer:\" + tracerName +\r // \", name for source: \" + notificationSource + \", is illegal\");\r // }\r String lastToken = null ; while ( stringTokenizer . hasMoreTokens ( ) ) { String token = stringTokenizer . nextToken ( ) ; if ( lastToken == null ) { // this is start\r lastToken = token ; } if ( lastToken . compareTo ( token ) == 0 && token . compareTo ( \".\" ) == 0 ) { throw new IllegalArgumentException ( \"Passed tracer:\" + tracerName + \", name for source: \" + notificationSource + \", is illegal\" ) ; } if ( token . compareTo ( \".\" ) != 0 ) { for ( int charIndex = 0 ; charIndex < token . length ( ) ; charIndex ++ ) { Character c = token . charAt ( charIndex ) ; if ( Character . isLetter ( c ) || Character . isDigit ( c ) ) { // Its ok?\r } else { throw new IllegalArgumentException ( \"Passed tracer:\" + tracerName + \" Token[\" + token + \"], name for source: \" + notificationSource + \", is illegal, contains illegal character: \" + charIndex ) ; } } fqdnPartIndex ++ ; } lastToken = token ; } if ( lastToken . compareTo ( \".\" ) == 0 ) { throw new IllegalArgumentException ( \"Passed tracer:\" + tracerName + \", name for source: \" + notificationSource + \", is illegal\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void registerNotificationSource ( final NotificationSource src ) { if ( ! this . tracerStorage . containsKey ( src ) ) { TracerStorage ts = new TracerStorage ( src , this ) ; this . tracerStorage . put ( src , ts ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean isTracerDefined ( NotificationSource src , String tracerName ) throws ManagementException { TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new ManagementException ( \"NotificationSource has been uninstalled from SLEE. Can not create tracer.\" ) ; } return ts . isTracerDefined ( tracerName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Tracer createTracer ( NotificationSource src , String tracerName , boolean createdBySource ) throws NullPointerException , InvalidArgumentException { TracerImpl . checkTracerName ( tracerName , src ) ; TracerStorage ts = this . tracerStorage . get ( src ) ; if ( ts == null ) { throw new IllegalStateException ( \"NotificationSource has been uninstalled from SLEE. Can not create tracer.\" ) ; } return ts . createTracer ( tracerName , createdBySource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that does lookup and creates PLOs [CODESPLIT] public static Collection < ProfileLocalObject > handle ( ProfileTableImpl profileTable , String queryName , Object [ ] arguments ) throws NullPointerException , TransactionRequiredLocalException , SLEEException , UnrecognizedQueryNameException , AttributeTypeMismatchException , InvalidArgumentException { return profileTable . getProfilesByStaticQuery ( queryName , arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs a JAIN SLEE DU . [CODESPLIT] public DeployableUnitImpl build ( String url , File deploymentRoot , ComponentRepository componentRepository ) throws DeploymentException , AlreadyDeployedException , MalformedURLException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Building DU from \" + url ) ; } DeployableUnitID deployableUnitID = new DeployableUnitID ( url ) ; if ( deploymentRoot == null ) { throw new NullPointerException ( \"null deploymentRoot\" ) ; } URL sourceUrl = new URL ( url ) ; // support remote deployment\r if ( sourceUrl . getProtocol ( ) . equals ( \"http\" ) || sourceUrl . getProtocol ( ) . equals ( \"https\" ) ) { try { // Fetch the remote file to a temporary location\r File downloadedFile = downloadRemoteDU ( sourceUrl , deploymentRoot ) ; // Update the pointers from URL and String\r sourceUrl = downloadedFile . toURI ( ) . toURL ( ) ; url = sourceUrl . toString ( ) ; } catch ( Exception e ) { throw new DeploymentException ( \"Failed to retrieve remote DU file : \" + sourceUrl . getFile ( ) , e ) ; } } // create jar file\r JarFile deployableUnitJar = null ; try { deployableUnitJar = new JarFile ( sourceUrl . getFile ( ) ) ; } catch ( IOException e ) { throw new DeploymentException ( \"Failed to open DU file as JAR file: \" + sourceUrl . getFile ( ) , e ) ; } // get and parse du descriptor\r JarEntry duXmlEntry = deployableUnitJar . getJarEntry ( \"META-INF/deployable-unit.xml\" ) ; if ( duXmlEntry == null ) { throw new DeploymentException ( \"META-INF/deployable-unit.xml was not found in \" + deployableUnitJar . getName ( ) ) ; } DeployableUnitDescriptorFactoryImpl descriptorFactory = componentManagement . getComponentDescriptorFactory ( ) . getDeployableUnitDescriptorFactory ( ) ; DeployableUnitDescriptorImpl deployableUnitDescriptor = null ; try { deployableUnitDescriptor = descriptorFactory . parse ( deployableUnitJar . getInputStream ( duXmlEntry ) ) ; } catch ( IOException e ) { try { deployableUnitJar . close ( ) ; } catch ( IOException e1 ) { logger . error ( e . getMessage ( ) , e ) ; } throw new DeploymentException ( \"Failed to get DU descriptor DU inputstream from JAR file \" + sourceUrl . getFile ( ) , e ) ; } // create the du dir\r File deploymentDir = createTempDUDeploymentDir ( deploymentRoot , deployableUnitID ) ; // build du object\r DeployableUnitImpl deployableUnit = null ; try { deployableUnit = new DeployableUnitImpl ( deployableUnitID , deployableUnitDescriptor , componentRepository , deploymentDir ) ; // build each du jar component\r for ( String jarFileName : deployableUnitDescriptor . getJarEntries ( ) ) { for ( SleeComponent sleeComponent : duComponentBuilder . buildComponents ( jarFileName , deployableUnitJar , deployableUnit . getDeploymentDir ( ) ) ) { sleeComponent . setDeployableUnit ( deployableUnit ) ; if ( componentRepository . isInstalled ( sleeComponent . getComponentID ( ) ) ) { throw new AlreadyDeployedException ( \"Component \" + sleeComponent . getComponentID ( ) + \" already deployed\" ) ; } sleeComponent . setDeploymentUnitSource ( jarFileName ) ; } } // build each du service component\r for ( String serviceDescriptorFileName : deployableUnitDescriptor . getServiceEntries ( ) ) { for ( ServiceComponentImpl serviceComponent : duServiceComponentBuilder . buildComponents ( serviceDescriptorFileName , deployableUnitJar ) ) { serviceComponent . setDeployableUnit ( deployableUnit ) ; if ( componentRepository . isInstalled ( serviceComponent . getComponentID ( ) ) ) { throw new AlreadyDeployedException ( \"Component \" + serviceComponent . getComponentID ( ) + \" already deployed\" ) ; } // set the direct reference to the sbb component\r serviceComponent . setRootSbbComponent ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( serviceComponent . getDescriptor ( ) . getRootSbbID ( ) ) ) ; serviceComponent . setDeploymentUnitSource ( serviceDescriptorFileName ) ; } } // get a set with all components of the DU\r Set < SleeComponent > duComponentsSet = deployableUnit . getDeployableUnitComponents ( ) ; // now that all components are built we need to\r for ( SleeComponent sleeComponent : duComponentsSet ) { // check if all\r // dependencies are available\r checkDependencies ( sleeComponent , deployableUnit ) ; // build its class loader\r createClassLoader ( ( AbstractSleeComponent ) sleeComponent ) ; } // load the provided classes for the component\r for ( SleeComponent sleeComponent : duComponentsSet ) { loadAndSetNonGeneratedComponentClasses ( ( AbstractSleeComponent ) sleeComponent ) ; } //boolean secEnabled = SleeContainer.isSecurityEnabled();\r // validate each component\r for ( SleeComponent sleeComponent : duComponentsSet ) { ClassLoader componentClassLoader = sleeComponent . getClassLoader ( ) ; ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { if ( componentClassLoader != null ) { Thread . currentThread ( ) . setContextClassLoader ( componentClassLoader ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Validating \" + sleeComponent ) ; } if ( ! sleeComponent . validate ( ) ) { throw new DeploymentException ( sleeComponent . toString ( ) + \" validation failed, check logs for errors found\" ) ; } //Make permissions object, this instruments codebase etc, and store POJOs in component.\r //if(secEnabled)\r //{\r sleeComponent . processSecurityPermissions ( ) ; //}\r } catch ( Throwable e ) { throw new DeploymentException ( \"failed to validate \" + sleeComponent , e ) ; } finally { if ( componentClassLoader != null ) { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } } } try { deployableUnitJar . close ( ) ; } catch ( IOException e ) { logger . error ( \"failed to close deployable jar from \" + url , e ) ; } return deployableUnit ; } catch ( Throwable e ) { if ( deployableUnit == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Deleting deployable unit temp dir \" + deploymentDir ) ; } deploymentDir . delete ( ) ; } if ( e instanceof DeploymentException ) { throw ( DeploymentException ) e ; } else if ( e instanceof AlreadyDeployedException ) { throw ( AlreadyDeployedException ) e ; } else { throw new DeploymentException ( \"failed to build deployable unit\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads all non SLEE generated classes from the component class loader to the component those will be needed for validation or runtime purposes [CODESPLIT] private void loadAndSetNonGeneratedComponentClasses ( AbstractSleeComponent sleeComponent ) throws DeploymentException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Loading classes for component \" + sleeComponent ) ; } ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { ComponentClassLoaderImpl componentClassLoader = sleeComponent . getClassLoader ( ) ; if ( componentClassLoader != null ) { // change class loader\r Thread . currentThread ( ) . setContextClassLoader ( componentClassLoader ) ; // load and set non generated component classes\r if ( sleeComponent instanceof EventTypeComponentImpl ) { EventTypeComponentImpl component = ( EventTypeComponentImpl ) sleeComponent ; Class < ? > eventTypeClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getEventClassName ( ) ) ; component . setEventTypeClass ( eventTypeClass ) ; } else if ( sleeComponent instanceof ProfileSpecificationComponentImpl ) { ProfileSpecificationComponentImpl component = ( ProfileSpecificationComponentImpl ) sleeComponent ; Class < ? > profileCmpInterfaceClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileCMPInterface ( ) . getProfileCmpInterfaceName ( ) ) ; component . setProfileCmpInterfaceClass ( profileCmpInterfaceClass ) ; if ( component . getDescriptor ( ) . getProfileLocalInterface ( ) != null ) { Class < ? > profileLocalInterfaceClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileLocalInterface ( ) . getProfileLocalInterfaceName ( ) ) ; component . setProfileLocalInterfaceClass ( profileLocalInterfaceClass ) ; } if ( component . getDescriptor ( ) . getProfileManagementInterface ( ) != null ) { Class < ? > profileManagementInterfaceClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileManagementInterface ( ) ) ; component . setProfileManagementInterfaceClass ( profileManagementInterfaceClass ) ; } if ( component . getDescriptor ( ) . getProfileAbstractClass ( ) != null ) { boolean decoratedClass = new ProfileAbstractClassDecorator ( component ) . decorateAbstractClass ( ) ; Class < ? > profileAbstractClass = null ; if ( decoratedClass ) { // need to ensure we load the class from disk, not one coming from SLEE shared class loading domain\r profileAbstractClass = componentClassLoader . loadClassLocally ( component . getDescriptor ( ) . getProfileAbstractClass ( ) . getProfileAbstractClassName ( ) ) ; } else { profileAbstractClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getProfileAbstractClass ( ) . getProfileAbstractClassName ( ) ) ; } component . setProfileAbstractClass ( profileAbstractClass ) ; } String mProfileTableInterface = component . getDescriptor ( ) . getProfileTableInterface ( ) ; if ( mProfileTableInterface != null ) { component . setProfileTableInterfaceClass ( componentClassLoader . loadClass ( mProfileTableInterface ) ) ; } UsageParametersInterfaceDescriptor mUsageParametersInterface = component . getDescriptor ( ) . getProfileUsageParameterInterface ( ) ; if ( mUsageParametersInterface != null ) { component . setUsageParametersInterface ( componentClassLoader . loadClass ( mUsageParametersInterface . getUsageParametersInterfaceName ( ) ) ) ; } } else if ( sleeComponent instanceof ResourceAdaptorComponentImpl ) { ResourceAdaptorComponentImpl component = ( ResourceAdaptorComponentImpl ) sleeComponent ; Class < ? > resourceAdaptorClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getResourceAdaptorClassName ( ) ) ; component . setResourceAdaptorClass ( resourceAdaptorClass ) ; MUsageParametersInterface mUsageParametersInterface = component . getDescriptor ( ) . getResourceAdaptorUsageParametersInterface ( ) ; if ( mUsageParametersInterface != null ) { component . setUsageParametersInterface ( componentClassLoader . loadClass ( mUsageParametersInterface . getUsageParametersInterfaceName ( ) ) ) ; } } else if ( sleeComponent instanceof ResourceAdaptorTypeComponentImpl ) { ResourceAdaptorTypeComponentImpl component = ( ResourceAdaptorTypeComponentImpl ) sleeComponent ; if ( component . getDescriptor ( ) . getActivityContextInterfaceFactoryInterface ( ) != null ) { Class < ? > activityContextInterfaceFactoryInterface = componentClassLoader . loadClass ( component . getDescriptor ( ) . getActivityContextInterfaceFactoryInterface ( ) ) ; component . setActivityContextInterfaceFactoryInterface ( activityContextInterfaceFactoryInterface ) ; } } else if ( sleeComponent instanceof SbbComponentImpl ) { SbbComponentImpl component = ( SbbComponentImpl ) sleeComponent ; // before loading the abstract class, we may have to decorate it\r boolean decoratedClass = new SbbAbstractClassDecorator ( component ) . decorateAbstractSbb ( ) ; Class < ? > abstractSbbClass = null ; if ( decoratedClass ) { // need to ensure we load the class from disk, not one coming from SLEE shared class loading domain\r abstractSbbClass = componentClassLoader . loadClassLocally ( component . getDescriptor ( ) . getSbbAbstractClass ( ) . getSbbAbstractClassName ( ) ) ; } else { abstractSbbClass = componentClassLoader . loadClass ( component . getDescriptor ( ) . getSbbAbstractClass ( ) . getSbbAbstractClassName ( ) ) ; } component . setAbstractSbbClass ( abstractSbbClass ) ; SbbLocalInterfaceDescriptor mSbbLocalInterface = component . getDescriptor ( ) . getSbbLocalInterface ( ) ; if ( mSbbLocalInterface != null ) { component . setSbbLocalInterfaceClass ( componentClassLoader . loadClass ( mSbbLocalInterface . getSbbLocalInterfaceName ( ) ) ) ; } String mSbbActivityContextInterface = component . getDescriptor ( ) . getSbbActivityContextInterface ( ) ; if ( mSbbActivityContextInterface != null ) { component . setActivityContextInterface ( componentClassLoader . loadClass ( mSbbActivityContextInterface ) ) ; } UsageParametersInterfaceDescriptor mUsageParametersInterface = component . getDescriptor ( ) . getSbbUsageParametersInterface ( ) ; if ( mUsageParametersInterface != null ) { component . setUsageParametersInterface ( componentClassLoader . loadClass ( mUsageParametersInterface . getUsageParametersInterfaceName ( ) ) ) ; } } } } catch ( NoClassDefFoundError e ) { throw new DeploymentException ( \"Component \" + sleeComponent . getComponentID ( ) + \" requires a class that was not found\" , e ) ; } catch ( ClassNotFoundException e ) { throw new DeploymentException ( \"Component \" + sleeComponent . getComponentID ( ) + \" requires a class that was not found\" , e ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if all dependencies of a DU component exists [CODESPLIT] private void checkDependencies ( SleeComponent sleeComponent , DeployableUnitImpl deployableUnit ) throws DependencyException { for ( ComponentID componentID : sleeComponent . getDependenciesSet ( ) ) { if ( componentID instanceof EventTypeID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( EventTypeID ) componentID ) == null ) { throw new DependencyException ( \"Component \" + sleeComponent . getComponentID ( ) + \" depends on \" + componentID + \" which is not available in the component repository or in the deployable unit\" ) ; } } else if ( componentID instanceof LibraryID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( LibraryID ) componentID ) == null ) { throw new DependencyException ( \"Component \" + sleeComponent . getComponentID ( ) + \" depends on \" + componentID + \" which is not available in the component repository or in the deployable unit\" ) ; } } else if ( componentID instanceof ProfileSpecificationID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( ProfileSpecificationID ) componentID ) == null ) { throw new DependencyException ( \"Component \" + sleeComponent . getComponentID ( ) + \" depends on \" + componentID + \" which is not available in the component repository or in the deployable unit\" ) ; } } else if ( componentID instanceof ResourceAdaptorID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( ResourceAdaptorID ) componentID ) == null ) { throw new DependencyException ( \"Component \" + sleeComponent . getComponentID ( ) + \" depends on \" + componentID + \" which is not available in the component repository or in the deployable unit\" ) ; } } else if ( componentID instanceof ResourceAdaptorTypeID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( ResourceAdaptorTypeID ) componentID ) == null ) { throw new DependencyException ( \"Component \" + sleeComponent . getComponentID ( ) + \" depends on \" + componentID + \" which is not available in the component repository or in the deployable unit\" ) ; } } else if ( componentID instanceof SbbID ) { if ( deployableUnit . getDeployableUnitRepository ( ) . getComponentByID ( ( SbbID ) componentID ) == null ) { throw new DependencyException ( \"Component \" + sleeComponent . getComponentID ( ) + \" depends on \" + componentID + \" which is not available in the component repository or in the deployable unit\" ) ; } } else if ( componentID instanceof ServiceID ) { throw new SLEEException ( \"Component \" + sleeComponent . getComponentID ( ) + \" depends on a service component \" + componentID + \" which is not available in the component repository or in the deployable unit\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the directory that will be used for unpacking the child jars for a given DU . [CODESPLIT] private File createTempDUDeploymentDir ( File deploymentRoot , DeployableUnitID deployableUnitID ) { try { // first create a dummy file to gurantee uniqueness. I would have\r // been nice if the File class had a createTempDir() method\r // IVELIN -- do not use jarName here because windows cannot see the\r // path (exceeds system limit)\r File tempFile = File . createTempFile ( \"restcomm-slee-du-\" , \"\" , deploymentRoot ) ; File tempDUDeploymentDir = new File ( tempFile . getAbsolutePath ( ) + \"-contents\" ) ; if ( ! tempDUDeploymentDir . exists ( ) ) { tempDUDeploymentDir . mkdirs ( ) ; } else { throw new SLEEException ( \"Dir \" + tempDUDeploymentDir + \" already exists, unable to create deployment dir for DU \" + deployableUnitID ) ; } tempFile . delete ( ) ; return tempDUDeploymentDir ; } catch ( IOException e ) { throw new SLEEException ( \"Failed to create deployment dir for DU \" + deployableUnitID , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void addEventContext ( EventContextHandle handle , EventContext eventContext ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Adding event context \" + eventContext + \" to datasource. Event context handle is \" + handle ) ; } dataSource . put ( handle , eventContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventContextData newEventContextData ( EventTypeID eventTypeId , Object event , ActivityContext ac , Address address , ServiceID serviceID , EventProcessingSucceedCallback succeedCallback , EventProcessingFailedCallback failedCallback , EventUnreferencedCallback unreferencedCallback , ReferencesHandler referencesHandler ) { return new DefaultEventContextData ( eventTypeId , event , ac , address , serviceID , succeedCallback , failedCallback , unreferencedCallback , referencesHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void removeEventContext ( EventContextHandle handle ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Removing event context from datasource. Event context handle is \" + handle ) ; } dataSource . remove ( handle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void run ( ) { if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedAction < Object > ( ) { public Object run ( ) { routeQueuedEvent ( ) ; return null ; } } ) ; } else { routeQueuedEvent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delivers to SBBs an event off the top of the queue for an activity context [CODESPLIT] private void routeQueuedEvent ( ) { boolean debugLogging = logger . isDebugEnabled ( ) ; final SleeTransactionManager txMgr = container . getTransactionManager ( ) ; ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { final LocalActivityContext lac = eventContext . getLocalActivityContext ( ) ; final EventRoutingTask activityCurrentEventRoutingTask = lac . getCurrentEventRoutingTask ( ) ; EventContext activityCurrentEventContext = activityCurrentEventRoutingTask == null ? null : activityCurrentEventRoutingTask . getEventContext ( ) ; if ( activityCurrentEventContext == null ) { if ( debugLogging ) logger . debug ( \"\\n\\n\\nStarting routing for \" + eventContext ) ; activityCurrentEventContext = eventContext ; // activity has no event routing task set  lac . setCurrentEventRoutingTask ( this ) ; EventTypeComponent eventTypeComponent = container . getComponentRepository ( ) . getComponentByID ( eventContext . getEventTypeId ( ) ) ; if ( eventTypeComponent == null ) { logger . error ( \"Unable to route event, the related component is not installed\" ) ; eventContext . eventProcessingFailed ( FailureReason . OTHER_REASON ) ; return ; } // setup initial event processing if ( eventContext . getService ( ) != null ) { ServiceComponent serviceComponent = container . getComponentRepository ( ) . getComponentByID ( eventContext . getService ( ) ) ; if ( eventTypeComponent . getActiveServicesWhichDefineEventAsInitial ( ) . contains ( serviceComponent ) ) { activityCurrentEventContext . getActiveServicesToProcessEventAsInitial ( ) . add ( serviceComponent ) ; } } else { Set < ServiceComponent > services = eventTypeComponent . getActiveServicesWhichDefineEventAsInitial ( ) ; if ( services != null ) { activityCurrentEventContext . getActiveServicesToProcessEventAsInitial ( ) . addAll ( services ) ; } } } else { if ( activityCurrentEventContext . isSuspendedNotTransacted ( ) ) { if ( debugLogging ) logger . debug ( \"\\n\\n\\nFreezing (due to suspended context) the routing for \" + eventContext ) ; activityCurrentEventContext . barrierEvent ( eventContext ) ; return ; } else { if ( debugLogging ) logger . debug ( \"\\n\\n\\nResuming the routing for\" + eventContext ) ; // needed to ensure tests/events/eventcontext/Test1108039Test.xml passes // the test must be fixed Thread . sleep ( 10 ) ; } } LinkedList < ServiceComponent > serviceComponents = activityCurrentEventContext . getActiveServicesToProcessEventAsInitial ( ) ; if ( debugLogging ) logger . debug ( \"Active services which define \" + eventContext . getEventTypeId ( ) + \" as initial: \" + serviceComponents ) ; boolean finished ; SbbEntityID rootSbbEntityId ; ClassLoader invokerClassLoader ; SbbEntity sbbEntity ; SbbObject sbbObject ; ServiceComponent serviceComponent ; boolean keepSbbEntityIfTxRollbacks ; NextSbbEntityFinder . Result nextSbbEntityFinderResult ; ActivityContext ac = null ; Exception caught = null ; Set < SbbEntityID > sbbEntitiesThatHandledCurrentEvent ; boolean deliverEvent ; boolean rollbackTx ; boolean rollbackOnlySet ; boolean sbbHandledEvent = false ; do { // For each SBB that is attached to this activity context and active service to process event as initial rootSbbEntityId = null ; invokerClassLoader = null ; sbbEntity = null ; sbbObject = null ; serviceComponent = null ; keepSbbEntityIfTxRollbacks = false ; nextSbbEntityFinderResult = null ; finished = false ; ac = null ; caught = null ; deliverEvent = true ; rollbackTx = true ; rollbackOnlySet = false ; try { /*\n\t\t\t\t\t * Start of SLEE Originated Invocation Sequence\n\t\t\t\t\t * ============================================== This\n\t\t\t\t\t * sequence consists of either: 1) One \"Op Only\" SLEE\n\t\t\t\t\t * Originated Invocation - in the case that it's a\n\t\t\t\t\t * straightforward event routing for the sbb entity. 2) One\n\t\t\t\t\t * \"Op and Remove\" SLEE Originated Invocation - in the case\n\t\t\t\t\t * it's an event routing to a root sbb entity that ends up\n\t\t\t\t\t * in a remove to the same entity since the attachment count\n\t\t\t\t\t * goes to zero after the event invocation 3) One \"Op Only\"\n\t\t\t\t\t * followed by one \"Remove Only\" SLEE Originated Invocation -\n\t\t\t\t\t * in the case it's an event routing to a non-root sbb\n\t\t\t\t\t * entity that ends up in a remove to the corresponding root\n\t\t\t\t\t * entity since the root attachment count goes to zero after\n\t\t\t\t\t * the event invocation Each Invocation Sequence is handled\n\t\t\t\t\t * in it's own transaction. All exception handling for each\n\t\t\t\t\t * invocation sequence is handled here. Any exceptions that\n\t\t\t\t\t * propagate up aren't necessary to be caught. -Tim\n\t\t\t\t\t */ // If this fails then we propagate up since there's nothing to roll-back anyway txMgr . begin ( ) ; sbbEntitiesThatHandledCurrentEvent = activityCurrentEventContext . getSbbEntitiesThatHandledEvent ( ) ; try { // load ac ac = container . getActivityContextFactory ( ) . getActivityContext ( eventContext . getActivityContextHandle ( ) , true ) ; if ( ac == null ) { logger . error ( \"Unable to route event \" + eventContext + \". The activity context is gone\" ) ; try { eventContext . eventProcessingFailed ( FailureReason . OTHER_REASON ) ; txMgr . commit ( ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } return ; } if ( routingPhase == RoutingPhase . DELIVERING ) { // calculate highest priority attached sbb entity that needs to handle the event try { nextSbbEntityFinderResult = nextSbbEntityFinder . next ( ac , eventContext , sbbEntitiesThatHandledCurrentEvent , container ) ; } catch ( Exception e ) { logger . warn ( \"Failed to find next sbb entity to deliver the event \" + eventContext + \" in \" + ac . getActivityContextHandle ( ) , e ) ; } // calculate highest priority service to process event as initial if ( ! serviceComponents . isEmpty ( ) ) { serviceComponent = serviceComponents . getFirst ( ) ; } // compare highest priority sbb entity already attached with highest priority service to process event as initial if ( nextSbbEntityFinderResult == null ) { if ( serviceComponent != null ) { if ( debugLogging ) logger . debug ( \"No sbb entities attached, which didn't already route the event, but \" + serviceComponent + \" defines the event type as initial, starting initial event processing\" ) ; // let the service process event as initial serviceComponents . removeFirst ( ) ; sbbEntity = initialEventProcessor . processInitialEvent ( serviceComponent , eventContext , container , ac ) ; // if service returned no sbb entity and there are no more service components we are done if ( sbbEntity == null && serviceComponents . isEmpty ( ) ) { finished = true ; } } else { // nothing else to route finished = true ; if ( debugLogging ) logger . debug ( \"No sbb entities attached, which didn't already route the event, and no services left to process the event as initial\" ) ; } } else { if ( serviceComponent != null && serviceComponent . getDescriptor ( ) . getDefaultPriority ( ) >= nextSbbEntityFinderResult . sbbEntity . getPriority ( ) ) { if ( debugLogging ) logger . debug ( \"Found an sbb entity attached, which didn't already route the event, but \" + serviceComponent + \" defines the event type as initial and has the same or higher priority, starting initial event processing\" ) ; // the service has higher or equal priority as the sbb entity, let the service process the eventas initial serviceComponents . removeFirst ( ) ; sbbEntity = initialEventProcessor . processInitialEvent ( serviceComponent , eventContext , container , ac ) ; } else { if ( debugLogging ) logger . debug ( \"Found an sbb entity attached, which didn't already route the event, and either there are no more services, which defines the event type as initial, or their priorities is lower than the attached sbb entity found\" ) ; sbbEntity = nextSbbEntityFinderResult . sbbEntity ; // in this case it needs to find out if the sbb entity should receive the event or not // it may be an activity end event and the attached sbb entity does not receives such event deliverEvent = nextSbbEntityFinderResult . deliverEvent ; } } } if ( sbbEntity != null ) { sbbEntitiesThatHandledCurrentEvent . add ( sbbEntity . getSbbEntityId ( ) ) ; if ( debugLogging ) { logger . debug ( \"Highest priority SBB entity, which is attached to the ac \" + eventContext . getActivityContextHandle ( ) + \" , to deliver the event: \" + sbbEntity . getSbbEntityId ( ) ) ; } // CHANGE CLASS LOADER invokerClassLoader = sbbEntity . getSbbComponent ( ) . getClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( invokerClassLoader ) ; if ( ! sbbEntity . getSbbEntityId ( ) . isRootSbbEntity ( ) ) { rootSbbEntityId = sbbEntity . getSbbEntityId ( ) . getRootSBBEntityID ( ) ; } SleeThreadLocals . setInvokingService ( sbbEntity . getSbbEntityId ( ) . getServiceID ( ) ) ; // we deliver the event in case it is an initial // event processing or if the highest priority // attached sbb entity should do it (in activity // end event it may not if the service id was // set in the event firing, or if the sbb entity // does not declares the event in sbb descriptor if ( deliverEvent ) { sbbEntity . assignSbbObject ( ) ; sbbObject = sbbEntity . getSbbObject ( ) ; if ( sbbEntity . isCreated ( ) && ! txMgr . getRollbackOnly ( ) ) { keepSbbEntityIfTxRollbacks = true ; } // GET AND CHECK EVENT MASK FOR THIS SBB ENTITY Set < EventTypeID > eventMask = sbbEntity . getMaskedEventTypes ( eventContext . getActivityContextHandle ( ) ) ; if ( eventMask == null || ! eventMask . contains ( eventContext . getEventTypeId ( ) ) ) { // TIME TO INVOKE THE EVENT HANDLER METHOD sbbObject . setSbbInvocationState ( SbbInvocationState . INVOKING_EVENT_HANDLER ) ; ac . beforeDeliveringEvent ( eventContext ) ; if ( debugLogging ) { logger . debug ( \"---> Invoking event handler: ac=\" + eventContext . getActivityContextHandle ( ) + \" , sbbEntity=\" + sbbEntity . getSbbEntityId ( ) + \" , sbbObject=\" + sbbObject ) ; } sbbEntity . invokeEventHandler ( eventContext , ac , activityCurrentEventContext ) ; sbbHandledEvent = true ; if ( debugLogging ) { logger . debug ( \"<--- Invoked event handler: ac=\" + eventContext . getActivityContextHandle ( ) + \" , sbbEntity=\" + sbbEntity . getSbbEntityId ( ) + \" , sbbObject=\" + sbbObject ) ; } // check to see if the transaction is marked for // rollback if it is then we need to get out of // here soon as we can. rollbackOnlySet = txMgr . getRollbackOnly ( ) ; if ( ! rollbackOnlySet ) { // TODO understand why the invoking state is not changed if rollback is set sbbObject . setSbbInvocationState ( SbbInvocationState . NOT_INVOKING ) ; } } else { if ( debugLogging ) { logger . debug ( \"Not invoking event handler since event is masked\" ) ; } } } if ( ! rollbackOnlySet ) { // IF IT'S AN ACTIVITY END EVENT DETACH SBB ENTITY HERE if ( eventContext . isActivityEndEvent ( ) && activityCurrentEventContext . getSbbEntitiesThatHandledEvent ( ) . contains ( sbbEntity . getSbbEntityId ( ) ) ) { if ( debugLogging ) { logger . debug ( \"The event is an activity end event, detaching ac=\" + eventContext . getActivityContextHandle ( ) + \" , sbbEntity=\" + sbbEntity . getSbbEntityId ( ) ) ; } ac . detachSbbEntity ( sbbEntity . getSbbEntityId ( ) ) ; sbbEntity . afterACDetach ( eventContext . getActivityContextHandle ( ) ) ; } // CHECK IF WE CAN CLAIM THE ROOT SBB ENTITY if ( rootSbbEntityId != null ) { SbbEntity rootSbbEntity = container . getSbbEntityFactory ( ) . getSbbEntity ( rootSbbEntityId , false ) ; if ( rootSbbEntity == null || rootSbbEntity . getAttachmentCount ( ) != 0 ) { if ( debugLogging ) { logger . debug ( \"Not removing sbb entity \" + sbbEntity . getSbbEntityId ( ) + \" , the attachment count is not 0\" ) ; } // the root sbb entity is not be claimed rootSbbEntityId = null ; } } else { // it's a root sbb if ( ! sbbEntity . isRemoved ( ) && sbbEntity . getAttachmentCount ( ) == 0 ) { if ( debugLogging ) { logger . debug ( \"Removing sbb entity \" + sbbEntity . getSbbEntityId ( ) + \" , the attachment count is not 0\" ) ; } // If it's the same entity then this is an // \"Op and // Remove Invocation Sequence\" // so we do the remove in the same // invocation // sequence as the Op container . getSbbEntityFactory ( ) . removeSbbEntity ( sbbEntity , true ) ; } } } } } catch ( Exception e ) { logger . error ( \"Caught exception while routing \" + eventContext , e ) ; if ( sbbEntity != null ) { sbbObject = sbbEntity . getSbbObject ( ) ; } caught = e ; } catch ( Throwable e ) { // not an exception, wrap it in exception so sbb learns about it logger . error ( \"Caught throwable while routing \" + eventContext , e ) ; if ( sbbEntity != null ) { sbbObject = sbbEntity . getSbbObject ( ) ; } caught = new SLEEException ( \"Caught throwable!\" , e ) ; } // do a final check to see if there is another SBB to // deliver. // We don't want to waste another loop. Note that // rollback // will not has any impact on this because the // ac.DeliveredSet // is not in the cache. if ( ! finished ) { if ( serviceComponents . isEmpty ( ) ) { // no more services to process event as initial try { if ( nextSbbEntityFinder . next ( ac , eventContext , sbbEntitiesThatHandledCurrentEvent , container ) == null ) { //if (nextSbbEntityFinder.next(ac, de.getEventTypeId(),de.getService(),sbbEntitiesThatHandledCurrentEvent) == null && sbbEntitiesThatHandledCurrentEvent.contains(sbbEntity.getSbbEntityID())) { // no more attached sbb entities to route the event finished = true ; } } catch ( Throwable e ) { if ( debugLogging ) { logger . debug ( \"failed to get next attached sbb entity to handle event\" , e ) ; } } } } boolean invokeSbbRolledBack = handleRollback . handleRollback ( sbbObject , caught , invokerClassLoader , txMgr ) ; boolean invokeSbbRolledBackRemove = false ; ClassLoader rootInvokerClassLoader = null ; SbbEntity rootSbbEntity = null ; if ( ! invokeSbbRolledBack && rootSbbEntityId != null ) { /*\n\t\t\t\t\t\t * If we get here this means that we need to do a\n\t\t\t\t\t\t * cascading remove of the root sbb entity - since the\n\t\t\t\t\t\t * original invocation was done on a non-root sbb entity\n\t\t\t\t\t\t * then this is done in a different SLEE originated\n\t\t\t\t\t\t * invocation, but inside the same SLEE originated\n\t\t\t\t\t\t * invocation sequence. Confused yet? This is case 3) in\n\t\t\t\t\t\t * my previous comment - the SLEE originated invocation\n\t\t\t\t\t\t * sequence contains two SLEE originated invocations:\n\t\t\t\t\t\t * One \"Op Only\" and One \"Remove Only\" This is the\n\t\t\t\t\t\t * \"Remove Only\" part. We don't bother doing this if we\n\t\t\t\t\t\t * already need to rollback\n\t\t\t\t\t\t */ caught = null ; try { rootSbbEntity = container . getSbbEntityFactory ( ) . getSbbEntity ( rootSbbEntityId , false ) ; if ( rootSbbEntity != null ) { container . getSbbEntityFactory ( ) . removeSbbEntity ( rootSbbEntity , false ) ; } } catch ( Exception e ) { logger . error ( \"Failure while routing event; third phase. Event Posting [\" + eventContext + \"]\" , e ) ; caught = e ; } // We have no target sbb object in a Remove Only SLEE // originated invocation // FIXME emmartins review invokeSbbRolledBackRemove = handleRollback . handleRollback ( null , caught , rootSbbEntity . getSbbComponent ( ) . getClassLoader ( ) , txMgr ) ; } /*\n\t\t\t\t\t * We are now coming to the end of the SLEE originated\n\t\t\t\t\t * invocation sequence We may need to run sbbRolledBack This\n\t\t\t\t\t * is done in the same tx if there is no target sbb entity\n\t\t\t\t\t * in any of the SLEE originated invocations making up this\n\t\t\t\t\t * SLEE originated invocation sequence Otherwise we do it in\n\t\t\t\t\t * a separate tx for each SLEE originated invocation that\n\t\t\t\t\t * has a target sbb entity. In other words we might have a\n\t\t\t\t\t * maximum of 2 sbbrolledback callbacks invoked in separate\n\t\t\t\t\t * tx in the case this SLEE Originated Invocation Sequence\n\t\t\t\t\t * contained an Op Only and a Remove Only (since these have\n\t\t\t\t\t * different target sbb entities) Pretty obvious really! ;)\n\t\t\t\t\t */ if ( invokeSbbRolledBack && sbbEntity == null ) { // We do it in this tx handleSbbRollback . handleSbbRolledBack ( null , sbbObject , null , null , invokerClassLoader , false , container , false ) ; } else if ( sbbEntity != null && ! txMgr . getRollbackOnly ( ) && sbbEntity . getSbbObject ( ) != null ) { sbbEntity . passivateAndReleaseSbbObject ( ) ; //fixes https://github.com/RestComm/jain-slee/issues/53 /* add new tx action before tx commit in which\n\t\t\t\t\t\t * get all sbb entities in the tx context except target sbb entity\n\t\t\t\t\t\t * and invoke passivateAndReleaseSbbObject method if the sbb object is not null\n\t\t\t\t\t\t */ final Collection coll = txMgr . getTransactionContext ( ) . getData ( ) . keySet ( ) ; final SbbEntityID ongoingEntID = sbbEntity . getSbbEntityId ( ) ; TransactionalAction removeLoadedSBBAction = new TransactionalAction ( ) { @ Override public void execute ( ) { for ( Object obj : coll ) { if ( obj instanceof SbbEntityID ) { if ( ! obj . equals ( ongoingEntID ) ) { SbbEntity currentEntity = ( SbbEntity ) txMgr . getTransactionContext ( ) . getData ( ) . get ( obj ) ; if ( currentEntity . getSbbObject ( ) != null ) { currentEntity . passivateAndReleaseSbbObject ( ) ; } } } } } } ; txMgr . getTransactionContext ( ) . getBeforeCommitPriorityActions ( ) . add ( removeLoadedSBBAction ) ; } if ( txMgr . getRollbackOnly ( ) ) { if ( debugLogging ) { logger . trace ( \"Rolling back SLEE Originated Invocation Sequence\" ) ; } txMgr . rollback ( ) ; } else { if ( finished ) { switch ( routingPhase ) { case DELIVERING : // last tx for this event delivering and it is going to commit (hopefully) // if it has a unrefrenced callback which is tx aware try to take advantage of that  // and do post processing in this tx, in the worst (and unexpected) scenario // the tx will rollback and we will do another spin, due to setting gotSbb as true if ( eventContext . routedRequiresTransaction ( ) ) { finished = false ; routingPhase = RoutingPhase . DELIVERED ; eventContext . routed ( ) ; } break ; case DELIVERED : if ( eventContext . routedRequiresTransaction ( ) ) { // we had bad luck and last tx rollbacked, repeat action finished = false ; eventContext . routed ( ) ; } break ; default : logger . error ( \"Unknown routing phase!!!\" ) ; break ; } } if ( debugLogging ) { logger . trace ( \"Committing SLEE Originated Invocation Sequence\" ) ; } txMgr . commit ( ) ; // if we are not in delivering mode anymore and tx commits then we allow the loop to exit if ( routingPhase != RoutingPhase . DELIVERING ) { finished = true ; } } /*\n\t\t\t\t\t * Now we invoke sbbRolledBack for each SLEE originated\n\t\t\t\t\t * invocation that had a target sbb entity in a new tx - the\n\t\t\t\t\t * new tx creating is handled inside the handleSbbRolledBack\n\t\t\t\t\t * method\n\t\t\t\t\t */ if ( invokeSbbRolledBack && sbbEntity != null ) { // Firstly for the \"Op only\" or \"Op and Remove\" part if ( debugLogging ) { logger . trace ( \"Invoking sbbRolledBack for Op Only or Op and Remove\" ) ; } //FIXME: baranowb: de is passed for test: tests/sbb/abstractclass/SbbRolledBackNewTransaction.xml handleSbbRollback . handleSbbRolledBack ( sbbEntity , null , eventContext , ac , invokerClassLoader , false , container , keepSbbEntityIfTxRollbacks ) ; } if ( invokeSbbRolledBackRemove ) { // Now for the \"Remove Only\" if appropriate handleSbbRollback . handleSbbRolledBack ( rootSbbEntity , null , null , null , rootInvokerClassLoader , true , container , keepSbbEntityIfTxRollbacks ) ; } /*\n\t\t\t\t\t * A note on exception handling here- Any exceptions thrown\n\t\t\t\t\t * further further up that need to be caught in order to\n\t\t\t\t\t * handle rollback or otherwise maintain consistency of the\n\t\t\t\t\t * SLEE state are all handled further up I.e. We *do not*\n\t\t\t\t\t * need to call rollback here. So any exceptions that get\n\t\t\t\t\t * here do not result in the SLEE being in an inconsistent\n\t\t\t\t\t * state, therefore we just log them and carry on.\n\t\t\t\t\t */ rollbackTx = false ; } catch ( RuntimeException e ) { logger . error ( \"Unhandled RuntimeException in event router: \" , e ) ; } catch ( Exception e ) { logger . error ( \"Unhandled Exception in event router: \" , e ) ; } catch ( Error e ) { logger . error ( \"Unhandled Error in event router: \" , e ) ; throw e ; // Always rethrow errors } catch ( Throwable t ) { logger . error ( \"Unhandled Throwable in event router: \" , t ) ; } finally { try { // FIXME this should not be possible, check if this is ever called by tck!!! final Transaction forgottenTx = txMgr . getTransaction ( ) ; if ( forgottenTx != null ) { logger . error ( \"HOUSTON WE HAVE A PROBLEM! Transaction \" + forgottenTx + \" left open in event routing.\" ) ; if ( rollbackTx ) { txMgr . rollback ( ) ; } else { txMgr . commit ( ) ; } } } catch ( SystemException se ) { logger . error ( se . getMessage ( ) , se ) ; } if ( sbbEntity != null ) { if ( debugLogging ) { logger . debug ( \"Finished routing for \" + eventContext + \"\\n\\n\\n\" ) ; } } } SleeThreadLocals . setInvokingService ( null ) ; if ( activityCurrentEventContext . isSuspendedNotTransacted ( ) ) { if ( debugLogging ) logger . debug ( \"Suspended routing for \" + eventContext + \"\\n\\n\\n\" ) ; return ; } } while ( ! finished ) ; /*\n\t\t\t * End of SLEE Originated Invocation Sequence\n\t\t\t * ==========================================\n\t\t\t * \n\t\t\t */ eventContext . eventProcessingSucceed ( sbbHandledEvent ) ; // we got to the end of the event routing, remove from local ac lac . setCurrentEventRoutingTask ( null ) ; if ( ! eventContext . routedRequiresTransaction ( ) ) { eventContext . routed ( ) ; } } catch ( Exception e ) { logger . error ( \"Unhandled Exception in event router top try\" , e ) ; } Thread . currentThread ( ) . setContextClassLoader ( oldClassLoader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void readExternal ( ObjectInput in ) throws IOException , ClassNotFoundException { // read ra entity name final String raEntityName = in . readUTF ( ) ; // read activity handle this . raEntity = SleeContainer . lookupFromJndi ( ) . getResourceManagement ( ) . getResourceAdaptorEntity ( raEntityName ) ; if ( raEntity == null ) { throw new IOException ( \"RA Entity with name \" + raEntityName + \" not found.\" ) ; } // read activity handle boolean handleReference = in . readBoolean ( ) ; if ( handleReference ) { // a reference activityHandle = new ActivityHandleReference ( null , ( Address ) in . readObject ( ) , in . readUTF ( ) ) ; } else { final Marshaler marshaler = raEntity . getMarshaler ( ) ; if ( marshaler != null ) { activityHandle = marshaler . unmarshalHandle ( in ) ; } else { throw new IOException ( \"marshaller from RA is null\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void writeExternal ( ObjectOutput out ) throws IOException { // write ra entity name out . writeUTF ( raEntity . getName ( ) ) ; // write activity handle if ( activityHandle . getClass ( ) == ActivityHandleReference . class ) { // a reference out . writeBoolean ( true ) ; final ActivityHandleReference reference = ( ActivityHandleReference ) activityHandle ; out . writeObject ( reference . getAddress ( ) ) ; out . writeUTF ( reference . getId ( ) ) ; } else { out . writeBoolean ( false ) ; final Marshaler marshaler = raEntity . getMarshaler ( ) ; if ( marshaler != null ) { marshaler . marshalHandle ( activityHandle , out ) ; } else { throw new IOException ( \"marshaller from RA is null\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the concrete profile entity class and a profile entity array attr value class for each attribute that is an array [CODESPLIT] public void generateClasses ( ) { try { ProfileSpecificationDescriptor profileDescriptor = profileComponent . getDescriptor ( ) ; String deployDir = profileComponent . getDeploymentDir ( ) . getAbsolutePath ( ) ; ProfileCMPInterfaceDescriptor cmpInterface = profileDescriptor . getProfileCMPInterface ( ) ; // define the concrete profile entity class name String concreteProfileEntityClassName = cmpInterface . getProfileCmpInterfaceName ( ) + \"_PE\" ; // create javassist class CtClass concreteProfileEntityClass = ClassGeneratorUtils . createClass ( concreteProfileEntityClassName , new String [ ] { cmpInterface . getProfileCmpInterfaceName ( ) , Serializable . class . getName ( ) } ) ; // set inheritance ClassGeneratorUtils . createInheritanceLink ( concreteProfileEntityClass , ProfileEntity . class . getName ( ) ) ; // annotate with @Entity ClassGeneratorUtils . addAnnotation ( Entity . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , concreteProfileEntityClass ) ; // annotate the @IdClass LinkedHashMap < String , Object > idClassMVs = new LinkedHashMap < String , Object > ( ) ; idClassMVs . put ( \"value\" , JPAProfileId . class ) ; ClassGeneratorUtils . addAnnotation ( IdClass . class . getName ( ) , idClassMVs , concreteProfileEntityClass ) ; Set < String > uniqueConstraints = new HashSet < String > ( ) ; // override @id & @basic getter methods String getProfileNameMethodSrc = \"public String getProfileName() { return super.getProfileName(); }\" ; CtMethod getProfileNameMethod = CtNewMethod . make ( getProfileNameMethodSrc , concreteProfileEntityClass ) ; ClassGeneratorUtils . addAnnotation ( Id . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , getProfileNameMethod ) ; concreteProfileEntityClass . addMethod ( getProfileNameMethod ) ; String getTableNameMethodSrc = \"public String getTableName() { return super.getTableName(); }\" ; CtMethod getTableNameMethod = CtNewMethod . make ( getTableNameMethodSrc , concreteProfileEntityClass ) ; ClassGeneratorUtils . addAnnotation ( Id . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , getTableNameMethod ) ; concreteProfileEntityClass . addMethod ( getTableNameMethod ) ; // generate the getters/setters in the profile entity // gather the fieldNames of array type attributes ClassPool pool = profileComponent . getClassPool ( ) ; CtClass cmpInterfaceClass = pool . get ( cmpInterface . getProfileCmpInterfaceName ( ) ) ; CtClass listClass = pool . get ( List . class . getName ( ) ) ; Map < String , Class < ? > > profileEntityArrayAttrValueClassMap = new HashMap < String , Class < ? > > ( ) ; for ( CtMethod method : cmpInterfaceClass . getMethods ( ) ) { if ( ! method . getDeclaringClass ( ) . getName ( ) . equals ( Object . class . getName ( ) ) && method . getName ( ) . startsWith ( \"get\" ) ) { String fieldName = Introspector . decapitalize ( method . getName ( ) . replaceFirst ( \"get\" , \"\" ) ) ; boolean array = method . getReturnType ( ) . isArray ( ) ; CtClass returnType = array ? listClass : method . getReturnType ( ) ; CtField genField = ClassGeneratorUtils . addField ( returnType , fieldName , concreteProfileEntityClass ) ; // see issue #23: [Profiles] getting correct fieldName from method of ProfileCMP interface fieldName = genField . getName ( ) ; String pojoCmpAccessorSufix = ClassGeneratorUtils . getPojoCmpAccessorSufix ( genField . getName ( ) ) ; // create the getter CtMethod ctMethod = CtNewMethod . getter ( \"get\" + pojoCmpAccessorSufix , genField ) ; ProfileAttribute profileAttribute = profileComponent . getProfileAttributes ( ) . get ( fieldName ) ; concreteProfileEntityClass . addMethod ( ctMethod ) ; if ( array ) { // we need to generate a class for this attribute, to hold the one to many relation Class < ? > profileAttributeArrayValueClass = generateProfileAttributeArrayValueClass ( concreteProfileEntityClass , fieldName , profileAttribute . isUnique ( ) ) ; profileEntityArrayAttrValueClassMap . put ( fieldName , profileAttributeArrayValueClass ) ; // add the annotations of one to many association with array attr value class LinkedHashMap < String , Object > map = new LinkedHashMap < String , Object > ( ) ; map . put ( \"targetEntity\" , profileAttributeArrayValueClass ) ; // FIXME see comment on generation of avv, it is possible to work wituout a join table but needs more work // THE MAPPEDBY IS REQUIRED FOR THE RELATION WITHOUT A JOIN TABLE map . put ( \"mappedBy\" , \"owner\" ) ; map . put ( \"cascade\" , new CascadeType [ ] { CascadeType . ALL } ) ; ClassGeneratorUtils . addAnnotation ( OneToMany . class . getName ( ) , map , ctMethod ) ; // we need to add a special hibernate annotation because the jpa cascade delete only deletes from join table, not the orphan row at the PEAAV table map = new LinkedHashMap < String , Object > ( ) ; map . put ( \"value\" , new org . hibernate . annotations . CascadeType [ ] { org . hibernate . annotations . CascadeType . DELETE_ORPHAN } ) ; ClassGeneratorUtils . addAnnotation ( Cascade . class . getName ( ) , map , ctMethod ) ; // make setter from src /*String setterSrc = \n    \t\t\t\t  \"public void set\"+ pojoCmpAccessorSufix + \"(\"+List.class.getName()+\" value) {\" +\n    \t\t\t\t  \"  System.out.println(\\\"PEAAV setter: \"+genField.getName()+\" = \\\"+this.\"+genField.getName()+\"+\\\" value = \\\"+value);\" +\n    \t\t\t\t  \"  if (this.\"+genField.getName()+\" != null) { \" +\n    \t\t\t\t  \"    this.\"+genField.getName()+\".clear(); \" +\n    \t\t\t\t  \"    if (value != null) { \" +\n\t\t\t\t\t  \"      for (\"+Iterator.class.getName()+\" i = value.iterator(); i.hasNext();) { \" +\n\t\t\t\t\t  \"        \" + profileAttributeArrayValueClass.getName()+\" otherArrayValue = (\"+profileAttributeArrayValueClass.getName()+\") i.next(); \" +\n\t\t\t\t\t  \"        \" + profileAttributeArrayValueClass.getName()+\" thisArrayValue = new \"+profileAttributeArrayValueClass.getName()+\"(); \" +\n\t\t\t\t\t  \"        thisArrayValue.setString( otherArrayValue.getString() ); \" +\n\t\t\t\t\t  \"        thisArrayValue.setSerializable( (\"+Serializable.class.getName()+\") \"+ObjectCloner.class.getName()+\".makeDeepCopy(otherArrayValue.getSerializable()) ); \" +\n\t\t\t\t\t  \"        this.\"+genField.getName()+\".add(thisArrayValue); \" +   \t\t\t\t  \n\t\t\t\t\t  \"      }\" +\n\t\t\t\t\t  \"    }\" +\n    \t\t          \"  } else { \" +\n    \t\t          \"    this.\"+genField.getName()+\" = value; \" +\n    \t\t          \"  }\" +\n\t\t\t\t\t  \"}\";\n    \t\t\t  ctMethod = CtMethod.make(setterSrc, concreteProfileEntityClass);\n    \t\t\t  concreteProfileEntityClass.addMethod(ctMethod);\n    \t\t\t  */ } else { // not an array, just add column annotation with or without unique constraint if ( profileAttribute . isUnique ( ) ) { // just collect uniqueConstraints attributtes uniqueConstraints . add ( Introspector . decapitalize ( pojoCmpAccessorSufix ) ) ; } //String , primitive types , Array , Date will not be modified , only serialized data LinkedHashMap < String , Object > map = new LinkedHashMap < String , Object > ( ) ; if ( ! returnType . isPrimitive ( ) && ! returnType . getName ( ) . equals ( \"java.lang.String\" ) ) map . put ( \"length\" , 512 ) ; ClassGeneratorUtils . addAnnotation ( Column . class . getName ( ) , map , ctMethod ) ; } // add usual setter ctMethod = CtNewMethod . setter ( \"set\" + pojoCmpAccessorSufix , genField ) ; concreteProfileEntityClass . addMethod ( ctMethod ) ; } } String tableName = \"SLEE_PE_\" + profileComponent . getProfileCmpInterfaceClass ( ) . getSimpleName ( ) + \"_\" + Math . abs ( ( long ) profileComponent . getComponentID ( ) . hashCode ( ) ) ; addTableAnnotation ( tableName , uniqueConstraints , concreteProfileEntityClass ) ; jpaProfileDataSource . setProfileEntityArrayAttrValueClassMap ( profileEntityArrayAttrValueClassMap ) ; // write and load profile entity class if ( logger . isDebugEnabled ( ) ) logger . debug ( \"Writing PROFILE ENTITY CONCRETE CLASS ( \" + concreteProfileEntityClass . getName ( ) + \" ) to: \" + deployDir ) ; concreteProfileEntityClass . writeFile ( deployDir ) ; jpaProfileDataSource . setProfileEntityClass ( Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( concreteProfileEntityClass . getName ( ) ) ) ; concreteProfileEntityClass . defrost ( ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a class that extends { [CODESPLIT] private Class < ? > generateProfileAttributeArrayValueClass ( CtClass concreteProfileEntityClass , String profileAttributeName , boolean unique ) { CtClass concreteArrayValueClass = null ; try { // define the concrete profile attribute array value class name String concreteArrayValueClassName = profileComponent . getProfileCmpInterfaceClass ( ) . getName ( ) + \"PEAAV_\" + ClassGeneratorUtils . capitalize ( profileAttributeName ) ; // create javassist class concreteArrayValueClass = ClassGeneratorUtils . createClass ( concreteArrayValueClassName , new String [ ] { Serializable . class . getName ( ) } ) ; // set inheritance ClassGeneratorUtils . createInheritanceLink ( concreteArrayValueClass , ProfileEntityArrayAttributeValue . class . getName ( ) ) ; // annotate class with @Entity ClassGeneratorUtils . addAnnotation ( Entity . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , concreteArrayValueClass ) ; // generate a random table name addTableAnnotationToPEAAV ( \"SLEE_PEAAV_\" + profileComponent . getProfileCmpInterfaceClass ( ) . getSimpleName ( ) + \"_\" + Math . abs ( ( long ) profileComponent . getComponentID ( ) . hashCode ( ) ) + profileAttributeName , unique , concreteArrayValueClass ) ; // override @id String getIdNameMethodSrc = \"public long getId() { return super.getId(); }\" ; CtMethod getIdNameMethod = CtNewMethod . make ( getIdNameMethodSrc , concreteArrayValueClass ) ; ClassGeneratorUtils . addAnnotation ( Id . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , getIdNameMethod ) ; ClassGeneratorUtils . addAnnotation ( GeneratedValue . class . getName ( ) , new LinkedHashMap < String , Object > ( ) , getIdNameMethod ) ; concreteArrayValueClass . addMethod ( getIdNameMethod ) ; // override getter methods String getSerializableMethodSrc = \"public \" + Serializable . class . getName ( ) + \" getSerializable() { return super.getSerializable(); }\" ; CtMethod getSerializableMethod = CtNewMethod . make ( getSerializableMethodSrc , concreteArrayValueClass ) ; LinkedHashMap < String , Object > map = new LinkedHashMap < String , Object > ( ) ; map . put ( \"name\" , \"serializable\" ) ; map . put ( \"length\" , 512 ) ; //if (unique)map.put(\"unique\", true); ClassGeneratorUtils . addAnnotation ( Column . class . getName ( ) , map , getSerializableMethod ) ; concreteArrayValueClass . addMethod ( getSerializableMethod ) ; String getStringMethodSrc = \"public String getString() { return super.getString(); }\" ; CtMethod getStringMethod = CtNewMethod . make ( getStringMethodSrc , concreteArrayValueClass ) ; map = new LinkedHashMap < String , Object > ( ) ; map . put ( \"name\" , \"string\" ) ; //if (unique)map.put(\"unique\", true); ClassGeneratorUtils . addAnnotation ( Column . class . getName ( ) , map , getStringMethod ) ; concreteArrayValueClass . addMethod ( getStringMethod ) ; // FIXME add join columns here or in profile entity class to make // the relation without a join table, atm if this is changed, the // inserts on this table go with profile and table name as null %) // THE PROFILENTITY FIELD IN AAV CLASS IS REQUIRED FOR THE RELATION WITH PROFILE ENTITY CLASS WITHOUT A JOIN TABLE // add join column regarding the relation from array attr value to profile entity CtField ctField = ClassGeneratorUtils . addField ( concreteProfileEntityClass , \"owner\" , concreteArrayValueClass ) ; ClassGeneratorUtils . generateSetter ( ctField , null ) ; CtMethod getter = ClassGeneratorUtils . generateGetter ( ctField , null ) ; //ClassGeneratorUtils.addAnnotation(ManyToOne.class.getName(), new LinkedHashMap<String, Object>(), getter); // ---- ConstPool cp = getter . getMethodInfo ( ) . getConstPool ( ) ; AnnotationsAttribute attr = ( AnnotationsAttribute ) getter . getMethodInfo ( ) . getAttribute ( AnnotationsAttribute . visibleTag ) ; if ( attr == null ) { attr = new AnnotationsAttribute ( cp , AnnotationsAttribute . visibleTag ) ; } Annotation manyToOne = new Annotation ( ManyToOne . class . getName ( ) , cp ) ; manyToOne . addMemberValue ( \"optional\" , new BooleanMemberValue ( false , cp ) ) ; attr . addAnnotation ( manyToOne ) ; Annotation joinColumns = new Annotation ( JoinColumns . class . getName ( ) , cp ) ; Annotation joinColumn1 = new Annotation ( JoinColumn . class . getName ( ) , cp ) ; joinColumn1 . addMemberValue ( \"name\" , new StringMemberValue ( \"owner_tableName\" , cp ) ) ; joinColumn1 . addMemberValue ( \"referencedColumnName\" , new StringMemberValue ( \"tableName\" , cp ) ) ; Annotation joinColumn2 = new Annotation ( JoinColumn . class . getName ( ) , cp ) ; joinColumn2 . addMemberValue ( \"name\" , new StringMemberValue ( \"owner_profileName\" , cp ) ) ; joinColumn2 . addMemberValue ( \"referencedColumnName\" , new StringMemberValue ( \"profileName\" , cp ) ) ; ArrayMemberValue joinColumnsMemberValue = new ArrayMemberValue ( cp ) ; joinColumnsMemberValue . setValue ( new MemberValue [ ] { new AnnotationMemberValue ( joinColumn1 , cp ) , new AnnotationMemberValue ( joinColumn2 , cp ) } ) ; joinColumns . addMemberValue ( \"value\" , joinColumnsMemberValue ) ; attr . addAnnotation ( joinColumns ) ; getter . getMethodInfo ( ) . addAttribute ( attr ) ; // generate concrete setProfileEntity method String setProfileEntityMethodSrc = \"public void setProfileEntity(\" + ProfileEntity . class . getName ( ) + \" profileEntity){ setOwner((\" + concreteProfileEntityClass . getName ( ) + \")profileEntity); }\" ; CtMethod setProfileEntityMethod = CtMethod . make ( setProfileEntityMethodSrc , concreteArrayValueClass ) ; concreteArrayValueClass . addMethod ( setProfileEntityMethod ) ; // write and load the attr array value class String deployDir = profileComponent . getDeploymentDir ( ) . getAbsolutePath ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Writing PROFILE ATTR ARRAY VALUE CONCRETE CLASS ( \" + concreteArrayValueClass . getName ( ) + \" ) to: \" + deployDir ) ; } concreteArrayValueClass . writeFile ( deployDir ) ; return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( concreteArrayValueClass . getName ( ) ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } finally { if ( concreteArrayValueClass != null ) { concreteArrayValueClass . defrost ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int compare ( SbbEntityID sbbEntityID1 , SbbEntityID sbbEntityID2 ) { if ( sbbEntityID1 == sbbEntityID2 ) { return 0 ; } if ( sbbEntityID1 == null ) { return 1 ; } if ( sbbEntityID2 == null ) { return - 1 ; } return higherPrioritySbb ( sbbEntityID1 , sbbEntityID2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Collection < ProfileEntity > findProfilesByAttribute ( String profileTable , ProfileAttribute profileAttribute , Object attributeValue ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"findProfilesByAttribute( profileTable = \" + profileTable + \" , profileAttribute = \" + profileAttribute + \" , attributeValue = \" + attributeValue + \" )\" ) ; } EntityManager em = getEntityManager ( ) ; Query query = null ; if ( profileAttribute == null ) { query = em . createQuery ( \"SELECT x FROM \" + profileEntityClassName + \" x WHERE x.tableName = :tableName\" ) . setParameter ( \"tableName\" , profileTable ) ; } else { if ( profileAttribute . isArray ( ) ) { query = em . createQuery ( \"SELECT x FROM \" + profileEntityClassName + \" x , IN (x.c\" + profileAttribute . getName ( ) + \") y WHERE x.tableName = :tableName AND y.string = :attrValue\" ) . setParameter ( \"tableName\" , profileTable ) . setParameter ( \"attrValue\" , attributeValue . toString ( ) ) ; } else { // TODO handle Address objects in this use case, they can't be // binary for search query = em . createQuery ( \"SELECT x FROM \" + profileEntityClassName + \" x WHERE x.tableName = :tableName AND x.c\" + profileAttribute . getName ( ) + \" = :attrValue\" ) . setParameter ( \"tableName\" , profileTable ) . setParameter ( \"attrValue\" , attributeValue ) ; } } Collection < ProfileEntity > result = query . getResultList ( ) ; /*\n\t\tif (logger.isDebugEnabled()) {\n\t\t\tlogger.debug(\"findProfilesByAttribute : query = \"\n\t\t\t\t\t+ ((org.hibernate.ejb.QueryImpl) query).getHibernateQuery().getQueryString()\n\t\t\t\t\t+ \" , result = \" + result);\n\t\t}\n\t\t*/ return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileEntity findProfile ( String profileTable , String profileName ) { EntityManager em = getEntityManager ( ) ; Query query = em . createQuery ( \"FROM \" + profileEntityClassName + \" WHERE tableName = ?1 AND profileName = ?2\" ) . setParameter ( 1 , profileTable ) . setParameter ( 2 , profileName ) ; List < ? > resultList = query . getResultList ( ) ; if ( resultList . isEmpty ( ) ) { return null ; } else { return ( ProfileEntity ) resultList . get ( 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Collection < ProfileEntity > getProfilesByStaticQuery ( String profileTable , String queryName , final Object [ ] parameters ) throws NullPointerException , UnrecognizedQueryNameException , AttributeTypeMismatchException , InvalidArgumentException { // TODO check for exceptions final QueryWrapper wQuery = JPAQueryBuilder . getQuery ( queryName ) ; final EntityManager em = getEntityManager ( ) ; if ( System . getSecurityManager ( ) == null ) { Query staticQuery = em . createQuery ( wQuery . getQuerySQL ( profileEntityClassName ) ) ; if ( wQuery . getMaxMatches ( ) > 0 ) staticQuery . setMaxResults ( ( int ) wQuery . getMaxMatches ( ) ) ; for ( int i = 0 ; i < parameters . length ; i ++ ) { try { staticQuery . setParameter ( i + 1 , parameters [ i ] ) ; } catch ( Exception ignore ) { // We don't care, it's because there's no such parameter. } } return staticQuery . getResultList ( ) ; } else { try { return AccessController . doPrivileged ( new PrivilegedExceptionAction < Collection < ProfileEntity > > ( ) { public Collection < ProfileEntity > run ( ) throws Exception { Query staticQuery = em . createQuery ( wQuery . getQuerySQL ( profileEntityClassName ) ) ; if ( wQuery . getMaxMatches ( ) > 0 ) staticQuery . setMaxResults ( ( int ) wQuery . getMaxMatches ( ) ) ; for ( int i = 0 ; i < parameters . length ; i ++ ) { try { staticQuery . setParameter ( i + 1 , parameters [ i ] ) ; } catch ( Exception ignore ) { // We don't care, it's because there's no such parameter. } } return staticQuery . getResultList ( ) ; } } ) ; } catch ( PrivilegedActionException e ) { Throwable t = e . getCause ( ) ; if ( t instanceof NullPointerException ) throw ( NullPointerException ) t ; if ( t instanceof UnrecognizedQueryNameException ) throw ( UnrecognizedQueryNameException ) t ; if ( t instanceof AttributeTypeMismatchException ) throw ( AttributeTypeMismatchException ) t ; if ( t instanceof InvalidArgumentException ) throw ( InvalidArgumentException ) t ; //? throw new SLEEException ( \"\" , t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Collection < ProfileEntity > getProfilesByDynamicQuery ( String profileTable , QueryExpression expr ) throws UnrecognizedAttributeException , AttributeTypeMismatchException { // TODO check for exceptions QueryWrapper wQuery = JPAQueryBuilder . parseDynamicQuery ( expr ) ; EntityManager em = getEntityManager ( ) ; Query dynamicQuery = em . createQuery ( wQuery . getQuerySQL ( profileEntityClassName ) ) ; int i = 1 ; for ( Object param : wQuery . getDynamicParameters ( ) ) { dynamicQuery . setParameter ( i ++ , param ) ; } if ( wQuery . getMaxMatches ( ) > 0 ) dynamicQuery . setMaxResults ( ( int ) wQuery . getMaxMatches ( ) ) ; return dynamicQuery . getResultList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void persistProfile ( ProfileEntity profileEntity ) { EntityManager em = null ; // if(checkUniqueFields(profileObject)) // { em = getEntityManager ( ) ; em . persist ( profileEntity ) ; /*\n\t\t * } else { // FIXME: We need to throw this PVException! //throw new\n\t\t * ProfileVerificationException\n\t\t * (\"Failed to persist profile due to uniqueness constraint.\"); throw\n\t\t * new\n\t\t * SLEEException(\"Failed to persist profile due to uniqueness constraint.\"\n\t\t * ); }\n\t\t */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileEntity retrieveProfile ( String profileTable , String profileName ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"retrieveProfile( profileTableName = \" + profileTable + \" , profileName = \" + profileName + \" )\" ) ; } if ( profileName == null ) { profileName = DEFAULT_PROFILE_NAME ; } EntityManager em = getEntityManager ( ) ; final Query q = em . createQuery ( \"FROM \" + profileEntityClassName + \" WHERE tableName = ?1 AND profileName = ?2\" ) . setParameter ( 1 , profileTable ) . setParameter ( 2 , profileName ) ; if ( System . getSecurityManager ( ) == null ) { List < ? > resultList = q . getResultList ( ) ; if ( resultList . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"ProfileEntity retrieved -> \" + resultList . get ( 0 ) ) ; } return ( ProfileEntity ) resultList . get ( 0 ) ; } else { return null ; } } else { return AccessController . doPrivileged ( new PrivilegedAction < ProfileEntity > ( ) { public ProfileEntity run ( ) { List < ? > resultList = q . getResultList ( ) ; if ( resultList . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"ProfileEntity retrieved -> \" + resultList . get ( 0 ) ) ; } return ( ProfileEntity ) resultList . get ( 0 ) ; } else { return null ; } } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void renameProfileTable ( String oldProfileTableName , String newProfileTableName ) { EntityManager em = getEntityManager ( ) ; final Query q = em . createQuery ( \"UPDATE \" + profileEntityClassName + \" SET tableName = ?1 WHERE tableName = ?2\" ) . setParameter ( 1 , newProfileTableName ) . setParameter ( 2 , oldProfileTableName ) ; q . executeUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void install ( ) { synchronized ( this ) { // generate profile entity & related classes new ConcreteProfileEntityGenerator ( component , this ) . generateClasses ( ) ; // this one is just a runtime optimization for faster query building // now, later to use named queries profileEntityClassName = profileEntityClass . getName ( ) ; profileEntityFactoryClass = new ConcreteProfileEntityFactoryGenerator ( component , profileEntityClass , profileEntityArrayAttrValueClassMap ) . generateClass ( ) ; try { profileEntityFactory = ( ProfileEntityFactory ) profileEntityFactoryClass . newInstance ( ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } // 1. Generate CMP Interface Impl with JPA Annotations component . setProfileCmpConcreteClass ( new ConcreteProfileGenerator ( component ) . generateConcreteProfile ( ) ) ; // 2. Create the corresponding JPA PU -- FIXME: Should be somewhere // else? createPersistenceUnit ( component ) ; new JPAQueryBuilder ( component ) . parseStaticQueries ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void uninstall ( ) { synchronized ( this ) { Transaction tx = null ; try { tx = sleeTransactionManager . suspend ( ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } if ( entityManagerFactory != null ) { entityManagerFactory . close ( ) ; } try { sleeTransactionManager . resume ( tx ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } //component.setProfileEntityFramework(null); } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the entity manager for the current tx and the framework profile spec [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private EntityManager getEntityManager ( ) { if ( txDataKey == null ) { txDataKey = new StringBuilder ( \"jpapef.em.\" ) . append ( component . getProfileSpecificationID ( ) ) . toString ( ) ; } final TransactionContext txContext = sleeTransactionManager . getTransactionContext ( ) ; // look in tx Map transactionContextData = txContext . getData ( ) ; EntityManager result = ( EntityManager ) transactionContextData . get ( txDataKey ) ; if ( result == null ) { // create using factory result = entityManagerFactory . createEntityManager ( ) ; // store in tx context data transactionContextData . put ( txDataKey , result ) ; // add a tx action to close it before tx commits // FIXME: Do we need this after-rollback action here /*\n\t\t\tfinal EntityManager em = result;\n\t\t\tTransactionalAction action = new TransactionalAction() {\n\t\t\t\tpublic void execute() {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tem.close();\n\t\t\t\t\t} catch (Throwable e) {\n\t\t\t\t\t\tlogger.error(e.getMessage(), e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttxContext.getAfterRollbackActions().add(action);\n\t\t\t*/ } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the SLEE container [CODESPLIT] public void start ( ) throws InvalidStateException , ManagementException { try { // request to change to STARTING\r final SleeStateChangeRequest startingRequest = new SleeStateChangeRequest ( ) { @ Override public void stateChanged ( SleeState oldState ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( generateMessageWithLogo ( \"starting\" ) ) ; } notifyStateChange ( oldState , getNewState ( ) ) ; } @ Override public void requestCompleted ( ) { // inner request, executed when the parent completes, to change to RUNNING\r final SleeStateChangeRequest runningRequest = new SleeStateChangeRequest ( ) { private SleeState oldState ; @ Override public void stateChanged ( SleeState oldState ) { logger . info ( generateMessageWithLogo ( \"started\" ) ) ; this . oldState = oldState ; } @ Override public void requestCompleted ( ) { notifyStateChange ( oldState , getNewState ( ) ) ; } @ Override public boolean isBlockingRequest ( ) { return true ; } @ Override public SleeState getNewState ( ) { return SleeState . RUNNING ; } } ; try { sleeContainer . setSleeState ( runningRequest ) ; } catch ( Throwable e ) { logger . error ( \"Failed to set container in RUNNING state\" , e ) ; try { stop ( false ) ; } catch ( Throwable f ) { logger . error ( \"Failed to set container in STOPPED state, after failure to set in RUNNING state\" , e ) ; } } } @ Override public boolean isBlockingRequest ( ) { // should be false, but the tck doesn't like it\r return true ; } @ Override public SleeState getNewState ( ) { return SleeState . STARTING ; } } ; sleeContainer . setSleeState ( startingRequest ) ; } catch ( InvalidStateException ex ) { throw ex ; } catch ( Exception ex ) { throw new ManagementException ( ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdown the SLEE processes . The spec requires that System . exit () be called before this methods returns . We are not convinced this is necessary yet . A trivial implementation would be to make a call to the JBoss server shutdown () [CODESPLIT] public void shutdown ( ) throws InvalidStateException , ManagementException { logger . info ( generateMessageWithLogo ( \"shutdown\" ) ) ; try { sleeContainer . shutdownSlee ( ) ; } catch ( InvalidStateException ex ) { throw ex ; } catch ( Exception ex ) { throw new ManagementException ( ex . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void addNotificationListener ( NotificationListener listener , NotificationFilter filter , Object handback ) throws IllegalArgumentException { notificationBroadcaster . addNotificationListener ( listener , filter , handback ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See section 1 . 3 of jslee 1 . 1 specs [CODESPLIT] boolean validateCompatibilityReferenceConstraints ( ) { boolean passed = true ; String errorBuffer = new String ( \"\" ) ; try { if ( ! this . component . isSlee11 ( ) ) { // A 1.0 SBB must not reference or use a 1.1 Profile\r // Specification. This must be enforced by a 1.1\r // JAIN SLEE.\r ServiceComponent specComponent = this . repository . getComponentByID ( this . component . getServiceID ( ) ) ; if ( specComponent == null ) { // should not happen\r passed = false ; errorBuffer = appendToBuffer ( \"Referenced \" + this . component . getServiceID ( ) + \" was not found in component repository, this should not happen since dependencies were already verified\" , \"1.3\" , errorBuffer ) ; } else { if ( specComponent . isSlee11 ( ) ) { passed = false ; errorBuffer = appendToBuffer ( \"Service is following 1.0 JSLEE contract, it must not reference 1.1 Sbb as root: \" + this . component . getServiceID ( ) , \"1.3\" , errorBuffer ) ; } } } } finally { if ( ! passed ) { if ( logger . isEnabledFor ( Level . ERROR ) ) { logger . error ( errorBuffer ) ; } } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void processArguments ( String [ ] args ) throws CommandException { String sopts = \":bu:a:d:cr:plg\" ; LongOpt [ ] lopts = { new LongOpt ( \"bind\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //common options\r new LongOpt ( \"link-name\" , LongOpt . REQUIRED_ARGUMENT , null , BindOperation . ra_link_name ) , new LongOpt ( \"entity-name\" , LongOpt . REQUIRED_ARGUMENT , null , BindOperation . ra_entity_name ) , new LongOpt ( \"unbind\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"activate\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"deactivate\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"create\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //entity-name is covered\r new LongOpt ( \"ra-id\" , LongOpt . REQUIRED_ARGUMENT , null , CreateOperation . ra_id ) , new LongOpt ( \"config\" , LongOpt . REQUIRED_ARGUMENT , null , CreateOperation . config ) , new LongOpt ( \"remove\" , LongOpt . REQUIRED_ARGUMENT , null , ' ' ) , new LongOpt ( \"update-config\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //entity-name and config are already covered\r new LongOpt ( \"list\" , LongOpt . NO_ARGUMENT , null , ' ' ) , new LongOpt ( \"ra-entities\" , LongOpt . OPTIONAL_ARGUMENT , null , ListOperation . ra_entities ) , new LongOpt ( \"ra-entities-in-state\" , LongOpt . REQUIRED_ARGUMENT , null , ListOperation . ra_entities_in_state ) , new LongOpt ( \"ra-entities-by-link\" , LongOpt . REQUIRED_ARGUMENT , null , ListOperation . ra_entities_by_link ) , new LongOpt ( \"links\" , LongOpt . OPTIONAL_ARGUMENT , null , ListOperation . links ) , new LongOpt ( \"sbbs\" , LongOpt . REQUIRED_ARGUMENT , null , ListOperation . sbbs ) , new LongOpt ( \"get\" , LongOpt . NO_ARGUMENT , null , ' ' ) , //ra-id is covered\r new LongOpt ( \"state\" , LongOpt . REQUIRED_ARGUMENT , null , GetOperation . state ) , new LongOpt ( \"config-by-id\" , LongOpt . REQUIRED_ARGUMENT , null , GetOperation . config_by_id ) , new LongOpt ( \"config-by-name\" , LongOpt . REQUIRED_ARGUMENT , null , GetOperation . config_by_name ) , //new LongOpt(\"usage-mbean\", LongOpt.REQUIRED_ARGUMENT, null, GetOperation.usage_mbean),\r } ; Getopt getopt = new Getopt ( null , args , sopts , lopts ) ; // getopt.setOpterr(false);\r int code ; while ( ( code = getopt . getopt ( ) ) != - 1 ) { switch ( code ) { case ' ' : throw new CommandException ( \"Option requires an argument: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : throw new CommandException ( \"Invalid (or ambiguous) option: \" + args [ getopt . getOptind ( ) - 1 ] ) ; case ' ' : super . operation = new BindOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new UnBindOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new ActivateOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new DeactivateOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new CreateOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new RemoveOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new UpdateConfigOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new ListOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; case ' ' : super . operation = new GetOperation ( super . context , super . log , this ) ; super . operation . buildOperation ( getopt , args ) ; break ; default : throw new CommandException ( \"Command: \\\"\" + getName ( ) + \"\\\", found unexpected opt: \" + args [ getopt . getOptind ( ) - 1 ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method depending if SecurityManger is present switches class loader using priviledged action this is requried as some action may be initiated by unsecure domains . [CODESPLIT] public static ClassLoader switchSafelyClassLoader ( final ClassLoader cl , final ProfileObject po ) { ClassLoader _cl = null ; if ( System . getSecurityManager ( ) != null ) { _cl = ( ClassLoader ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { return _switchSafelyClassLoader ( cl , po ) ; } } ) ; } else { _cl = _switchSafelyClassLoader ( cl , po ) ; } return _cl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Its used to embed calls in AccessController in case of insturmented code cause javassist does not support anonmous inner class . [CODESPLIT] public static Object makeSafeProxyCall ( final Object proxy , final String methodToCallname , final Class [ ] signature , final Object [ ] values ) throws PrivilegedActionException { //Here we execute in sbb/profile or any other slee component domain // so no security calls can be made try { //AccessControlContext acc = new AccessControlContext(new ProtectionDomain[]{proxy.getClass().getProtectionDomain()}); return AccessController . doPrivileged ( new PrivilegedExceptionAction ( ) { public Object run ( ) throws Exception { final Method m = proxy . getClass ( ) . getMethod ( methodToCallname , signature ) ; //Here we cross to org.mobicents domain, with all perms, once m.invoke is called, we go into proxy object domain, effective rightsd are cross section of All + proxy object domain permissions //This is used when isolate security permissions is set to true; return m . invoke ( proxy , values ) ; //}},acc); } } ) ; } catch ( SecurityException e ) { // TODO Auto-generated catch block e . printStackTrace ( ) ; } catch ( PrivilegedActionException e ) { e . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean isIdentical ( javax . slee . profile . ProfileLocalObject other ) throws SLEEException { if ( ! ( other instanceof ProfileLocalObjectImpl ) ) { return false ; } return this . _equals ( other ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void remove ( ) throws TransactionRequiredLocalException , TransactionRolledbackLocalException , SLEEException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"removing profile with name \" + getProfileName ( ) + \" from table with name \" + getProfileTableName ( ) ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; try { ProfileEntity profileEntity = profileObject . getProfileEntity ( ) ; if ( profileEntity != null ) { // confirm it is still the same tx\r checkTransaction ( ) ; // remove\r profileEntity . remove ( ) ; } else { // there is no profile assigned to the object\r if ( getProfileTable ( ) . find ( getProfileName ( ) ) == null ) { // this exception has priority\r throw new NoSuchObjectLocalException ( \"the profile with name \" + getProfileName ( ) + \" was not found on table with name \" + getProfileTableName ( ) ) ; } else { throw new IllegalStateException ( \"the profile object is no longer valid\" ) ; } } } catch ( RuntimeException e ) { try { profileObject . invalidateObject ( ) ; sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; } catch ( SystemException e1 ) { throw new SLEEException ( e1 . getMessage ( ) , e1 ) ; } ; throw new TransactionRolledbackLocalException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies that the current transaction is still the one used to create the object [CODESPLIT] protected void checkTransaction ( ) throws IllegalStateException { try { if ( ! sleeContainer . getTransactionManager ( ) . getTransaction ( ) . equals ( this . transaction ) ) { throw new IllegalStateException ( ) ; } } catch ( SystemException e ) { throw new IllegalStateException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a { [CODESPLIT] protected void processRuntimeException ( RuntimeException e ) throws SLEEException , TransactionRolledbackLocalException { try { profileObject . invalidateObject ( ) ; sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; } catch ( SystemException e1 ) { throw new SLEEException ( e1 . getMessage ( ) , e1 ) ; } throw new TransactionRolledbackLocalException ( e . getMessage ( ) , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a { [CODESPLIT] protected void processPrivilegedActionException ( PrivilegedActionException e ) throws Exception , TransactionRolledbackLocalException { if ( e . getCause ( ) instanceof RuntimeException ) { processRuntimeException ( ( RuntimeException ) e . getCause ( ) ) ; } else if ( e . getCause ( ) instanceof Exception ) { throw ( Exception ) e . getCause ( ) ; } else { throw new SLEEException ( \"unexpected type of cause\" , e . getCause ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the Activity TTL [CODESPLIT] private static String toTTL ( String lastAccess , long timeout ) { Long ttl = timeout - ( ( System . currentTimeMillis ( ) - Long . parseLong ( lastAccess ) ) / 1000 ) ; return ttl . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if the specified class can be loaded by current thread class loader [CODESPLIT] boolean isProfileClassVisible ( ) { try { Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( profileAfterAction . getClass ( ) . getName ( ) ) ; return true ; } catch ( Throwable e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a local object valid for thus current transaction . [CODESPLIT] ProfileObjectImpl getProfileObjectValidInCurrentTransaction ( ProfileEntity profileEntity ) throws TransactionRequiredLocalException { // check tx\r final SleeTransactionManager txManager = profileManagement . getSleeContainer ( ) . getTransactionManager ( ) ; txManager . mandateTransaction ( ) ; // look for an assigned object in local map\r if ( txData == null ) { txData = new HashMap < ProfileEntity , ProfileObjectImpl > ( ) ; } ProfileObjectImpl profileObject = ( ProfileObjectImpl ) txData . get ( profileEntity ) ; if ( profileObject == null ) { // get an object from the table\r profileEntity . setReadOnly ( true ) ; profileEntity . setDirty ( false ) ; ProfileObjectPool pool = profileManagement . getObjectPoolManagement ( ) . getObjectPool ( profileEntity . getTableName ( ) ) ; profileObject = pool . borrowObject ( ) ; profileObject . profileActivate ( profileEntity ) ; ProfileTableTransactionView . passivateProfileObjectOnTxEnd ( txManager , profileObject , pool ) ; txData . put ( profileEntity , profileObject ) ; } return profileObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SImilar to LoggingMXBean return list of available loggers . Filter is string that has to occur in loggers name . [CODESPLIT] public List < String > getLoggerNames ( String regex ) throws ManagementConsoleException { try { return ( List < String > ) this . mbeanServer . invoke ( logMgmtMBeanName , \"getLoggerNames\" , new Object [ ] { regex } , new String [ ] { \"java.lang.String\" } ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets all loggers level to default one [CODESPLIT] public void resetLoggerLevels ( ) throws ManagementConsoleException { try { this . mbeanServer . invoke ( logMgmtMBeanName , \"resetLoggerLevels\" , null , null ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all loggers under certain branch . [CODESPLIT] public void clearLoggers ( String name ) throws ManagementConsoleException { try { this . mbeanServer . invoke ( logMgmtMBeanName , \"clearLoggers\" , new Object [ ] { name } , new String [ ] { \"java.lang.String\" } ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to add logger if it doesnt exist [CODESPLIT] public boolean addLogger ( String name , Level level ) throws NullPointerException , ManagementConsoleException { try { return ( ( Boolean ) this . mbeanServer . invoke ( logMgmtMBeanName , \"addLogger\" , new Object [ ] { name , level } , new String [ ] { \"java.lang.String\" , \"java.util.logging.Level\" } ) ) . booleanValue ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds SocketHandler to certain logger this logger must exist prior this function is called [CODESPLIT] public void addSocketHandler ( String loggerName , Level handlerLevel , String handlerName , String formaterClassName , String filterClassName , String host , int port ) throws ManagementConsoleException { try { this . mbeanServer . invoke ( logMgmtMBeanName , \"addSocketHandler\" , new Object [ ] { loggerName , handlerLevel , handlerName , formaterClassName , filterClassName , host , port } , new String [ ] { \"java.lang.String\" , \"java.util.logging.Level\" , \"java.lang.String\" , \"java.lang.String\" , \"java.lang.String\" , \"java.lang.String\" , \"int\" } ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to remove handler from logger . [CODESPLIT] public boolean removeHandler ( String loggerName , String handlerName ) throws ManagementConsoleException { try { return ( ( Boolean ) this . mbeanServer . invoke ( logMgmtMBeanName , \"removeHandler\" , new Object [ ] { loggerName , handlerName } , new String [ ] { \"java.lang.String\" , \"java.lang.String\" } ) ) . booleanValue ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds notification handler to logger if it exists . Its name is set to <b > NOTIFICATION< / b > . There can be only one notification handler . This handler holds reference to up to numberOfEntries log entries and fires notification . Notification can be triggered prematurely in case when someone calls fetchLogContent function this will cause notification to be fired along with log entries return as outcome of invocation . [CODESPLIT] public void addNotificationHandler ( String loggerName , int numberOfEntries , Level level , String formaterClassName , String filterClassName ) throws IllegalArgumentException , IllegalStateException , NullPointerException , ManagementConsoleException { try { this . mbeanServer . invoke ( logMgmtMBeanName , \"addNotificationHandler\" , new Object [ ] { loggerName , numberOfEntries , level , formaterClassName , filterClassName } , new String [ ] { \"java.lang.String\" , \"int\" , \"java.util.logging.Logger\" , \"java.lang.String\" , \"java.lang.String\" } ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new ManagementConsoleException ( SleeManagementMBeanUtils . doMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void onShow ( ) { ListPanel operations = new ListPanel ( ) ; operations . setWidth ( \"100%\" ) ; this . display . setHorizontalAlignment ( DockPanel . ALIGN_CENTER ) ; this . display . setVerticalAlignment ( DockPanel . ALIGN_TOP ) ; this . display . add ( operations , DockPanel . CENTER ) ; this . display . setCellHeight ( operations , \"100%\" ) ; this . display . setCellWidth ( operations , \"100%\" ) ; operations . setHeader ( 0 , \"Operation name\" ) ; operations . setHeader ( 1 , \"Parameters\" ) ; operations . setHeader ( 2 , \"Operation trigger\" ) ; // operations.setHeader(3, \"Operation detials\");\r operations . setColumnWidth ( 0 , \"33%\" ) ; operations . setColumnWidth ( 1 , \"33%\" ) ; operations . setColumnWidth ( 2 , \"33%\" ) ; // operations.setColumnWidth(3, \"55%\");\r // Operations\r // Set degault logger level\r operations . setCellText ( 1 , 0 , \"Default logger level\" ) ; operations . setCell ( 1 , 1 , null ) ; operations . setCell ( 1 , 2 , _defaultLoggerLevel ) ; // operations.setCellText(1, 3, _ll_Explanation);\r _defaultLoggerLevel . setTitle ( _ll_Explanation ) ; // Set default handler level\r operations . setCellText ( 2 , 0 , \"Default handler level\" ) ; operations . setCell ( 2 , 1 , null ) ; operations . setCell ( 2 , 2 , _defaultHandlerLevel ) ; // operations.setCell(2, 3, new Label(_hl_Explanation,true));\r _defaultHandlerLevel . setTitle ( _hl_Explanation ) ; // read cfg\r Hyperlink readLink = new Hyperlink ( \"Trigger\" , null ) ; // final TextBox uri=new TextBox();\r operations . setCellText ( 3 , 0 , \"Read logger cfg\" ) ; operations . setCell ( 3 , 1 , _readUri ) ; operations . setCell ( 3 , 2 , readLink ) ; // operations.setCellText(3, 3, _cfg_Explanation);\r readLink . setTitle ( _cfg_Explanation ) ; // reset loggers\r Hyperlink resetLink = new Hyperlink ( \"Trigger\" , null ) ; // final TextBox resetRegex=new TextBox();\r operations . setCellText ( 4 , 0 , \"Reset loggers level\" ) ; operations . setCell ( 4 , 1 , _resetLoggerList ) ; operations . setCell ( 4 , 2 , resetLink ) ; resetLink . setTitle ( _reset_Explanation ) ; // clear loggers loggers\r Hyperlink clearLink = new Hyperlink ( \"Trigger\" , null ) ; // final TextBox clearRegex=new TextBox();\r operations . setCellText ( 5 , 0 , \"Turns off loggers\" ) ; operations . setCell ( 5 , 1 , _clearLoggerList ) ; operations . setCell ( 5 , 2 , clearLink ) ; clearLink . setTitle ( _cclear_Explanation ) ; // clear loggers loggers\r Hyperlink addLogger = new Hyperlink ( \"Trigger\" , null ) ; // final TextBox clearRegex = new TextBox();\r operations . setCellText ( 6 , 0 , \"Add logger\" ) ; operations . setCell ( 6 , 1 , _newLoggerName ) ; operations . setCell ( 6 , 2 , addLogger ) ; addLogger . setTitle ( _add_Logger_Explanation ) ; Hyperlink setInterval = new Hyperlink ( \"Trigger\" , null ) ; // final TextBox clearRegex = new TextBox();\r operations . setCellText ( 7 , 0 , \"Default notification\" ) ; operations . setCell ( 7 , 1 , _defaultNotificationInterval ) ; operations . setCell ( 7 , 2 , setInterval ) ; // clearLink.setTitle(_add_Logger_Explanation);\r // Click listeners\r _defaultLoggerLevel . addClickListener ( new ClickListener ( ) { public void onClick ( Widget arg0 ) { ServerConnection . logServiceAsync . setDefaultLoggerLevel ( _defaultLoggerLevel . getItemText ( _defaultLoggerLevel . getSelectedIndex ( ) ) , new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to set value due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { // TODO Auto-generated method stub\r } } ) ; } } ) ; _defaultHandlerLevel . addClickListener ( new ClickListener ( ) { public void onClick ( Widget arg0 ) { ServerConnection . logServiceAsync . setDefaultHandlerLevel ( _defaultHandlerLevel . getItemText ( _defaultHandlerLevel . getSelectedIndex ( ) ) , new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to set value due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { // TODO Auto-generated method stub\r } } ) ; } } ) ; readLink . addClickListener ( new ClickListener ( ) { public void onClick ( Widget arg0 ) { ServerConnection . logServiceAsync . reReadConf ( _readUri . getText ( ) , new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to set value due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { logStructureTreePanel . refreshData ( ) ; } } ) ; } } ) ; resetLink . addClickListener ( new ClickListener ( ) { public void onClick ( Widget arg0 ) { ServerConnection . logServiceAsync . resetLoggerLevel ( _resetLoggerList . getText ( ) , new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to set value due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { logStructureTreePanel . refreshData ( ) ; } } ) ; } } ) ; clearLink . addClickListener ( new ClickListener ( ) { public void onClick ( Widget arg0 ) { ServerConnection . logServiceAsync . clearLoggers ( _clearLoggerList . getText ( ) , new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to set value due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { logStructureTreePanel . refreshData ( ) ; } } ) ; } } ) ; addLogger . addClickListener ( new ClickListener ( ) { public void onClick ( Widget arg0 ) { ServerConnection . logServiceAsync . addLogger ( _newLoggerName . getText ( ) , _defaultLoggerLevel . getItemText ( _defaultLoggerLevel . getSelectedIndex ( ) ) , new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to set value due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { logStructureTreePanel . refreshData ( ) ; } } ) ; } } ) ; setInterval . addClickListener ( new ClickListener ( ) { public void onClick ( Widget arg0 ) { int di = - 1 ; try { di = Integer . valueOf ( _defaultNotificationInterval . getText ( ) ) . intValue ( ) ; } catch ( Exception e ) { UserInterface . getLogPanel ( ) . error ( \"Failed to parse due:\" + e . getMessage ( ) ) ; return ; } ServerConnection . logServiceAsync . setDefaultNotificationInterval ( di , new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to set value due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { // TODO Auto-generated method stub\r } } ) ; } } ) ; // Some fetches:\r ServerConnection . logServiceAsync . getDefaultNotificationInterval ( new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to get value of default notification interval due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object o ) { _defaultNotificationInterval . setText ( o + \"\" ) ; } } ) ; ServerConnection . logServiceAsync . getDefaultHandlerLevel ( new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to get value of default handler level due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { setValue ( ( String ) arg0 , _defaultHandlerLevel ) ; } } ) ; ServerConnection . logServiceAsync . getDefaultLoggerLevel ( new AsyncCallback ( ) { public void onFailure ( Throwable t ) { UserInterface . getLogPanel ( ) . error ( \"Failed to get value of default handler level due to:\" + t . getMessage ( ) ) ; } public void onSuccess ( Object arg0 ) { setValue ( ( String ) arg0 , _defaultLoggerLevel ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AddressScreening< / code > object from an integer value . [CODESPLIT] public static AddressScreening fromInt ( int value ) throws IllegalArgumentException { switch ( value ) { case ADDRESS_SCREENING_UNDEFINED : return UNDEFINED ; case ADDRESS_SCREENING_USER_NOT_VERIFIED : return USER_NOT_VERIFIED ; case ADDRESS_SCREENING_USER_VERIFIED_PASSED : return USER_VERIFIED_PASSED ; case ADDRESS_SCREENING_USER_VERIFIED_FAILED : return USER_VERIFIED_FAILED ; case ADDRESS_SCREENING_NETWORK : return NETWORK ; default : throw new IllegalArgumentException ( \"Invalid value: \" + value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an <code > AddressScreening< / code > object from a string value . [CODESPLIT] public AddressScreening fromString ( String value ) throws NullPointerException , IllegalArgumentException { if ( value == null ) throw new NullPointerException ( \"value is null\" ) ; if ( value . equalsIgnoreCase ( UNDEFINED_STRING ) ) return UNDEFINED ; if ( value . equalsIgnoreCase ( USER_NOT_VERIFIED_STRING ) ) return USER_NOT_VERIFIED ; if ( value . equalsIgnoreCase ( USER_VERIFIED_PASSED_STRING ) ) return USER_VERIFIED_PASSED ; if ( value . equalsIgnoreCase ( USER_VERIFIED_FAILED_STRING ) ) return USER_VERIFIED_FAILED ; if ( value . equalsIgnoreCase ( NETWORK_STRING ) ) return NETWORK ; throw new IllegalArgumentException ( \"Invalid value: \" + value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public List < ResourceAdaptorTypeDescriptorImpl > parse ( InputStream inputStream ) throws DeploymentException { Object jaxbPojo = buildJAXBPojo ( inputStream ) ; List < ResourceAdaptorTypeDescriptorImpl > result = new ArrayList < ResourceAdaptorTypeDescriptorImpl > ( ) ; boolean isSlee11 = false ; MResourceAdaptorTypeJar mResourceAdaptorTypeJar = null ; if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee . ratype . ResourceAdaptorTypeJar ) { mResourceAdaptorTypeJar = new MResourceAdaptorTypeJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee . ratype . ResourceAdaptorTypeJar ) jaxbPojo ) ; } else if ( jaxbPojo instanceof org . mobicents . slee . container . component . deployment . jaxb . slee11 . ratype . ResourceAdaptorTypeJar ) { mResourceAdaptorTypeJar = new MResourceAdaptorTypeJar ( ( org . mobicents . slee . container . component . deployment . jaxb . slee11 . ratype . ResourceAdaptorTypeJar ) jaxbPojo ) ; isSlee11 = true ; } else { throw new SLEEException ( \"unexpected class of jaxb pojo built: \" + ( jaxbPojo != null ? jaxbPojo . getClass ( ) : null ) ) ; } for ( MResourceAdaptorType mResourceAdaptorType : mResourceAdaptorTypeJar . getResourceAdaptorType ( ) ) { result . add ( new ResourceAdaptorTypeDescriptorImpl ( mResourceAdaptorType , isSlee11 ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Object getCMPField ( String cmpFieldName ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Sbb entity \" + getSbbEntityId ( ) + \" getting cmp field \" + cmpFieldName ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; return cacheData . getCmpField ( cmpFieldName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setCMPField ( String cmpFieldName , Object cmpFieldValue ) { if ( log . isDebugEnabled ( ) ) { log . debug ( \"Sbb entity \" + getSbbEntityId ( ) + \" setting cmp field \" + cmpFieldName + \" to value \" + cmpFieldValue ) ; } sleeContainer . getTransactionManager ( ) . mandateTransaction ( ) ; cacheData . setCmpField ( cmpFieldName , cmpFieldValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void afterACAttach ( ActivityContextHandle ach ) { // add to cache cacheData . attachActivityContext ( ach ) ; // update event mask Set < EventTypeID > maskedEvents = getSbbComponent ( ) . getDescriptor ( ) . getDefaultEventMask ( ) ; if ( maskedEvents != null && ! maskedEvents . isEmpty ( ) ) { cacheData . updateEventMask ( ach , new HashSet < EventTypeID > ( maskedEvents ) ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( \"Sbb entity \" + getSbbEntityId ( ) + \" attached to AC with handle \" + ach + \" , events added to current mask: \" + maskedEvents ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void afterACDetach ( ActivityContextHandle ach ) { // remove from cache cacheData . detachActivityContext ( ach ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Sbb entity \" + getSbbEntityId ( ) + \" detached from AC with handle \" + ach ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public byte getPriority ( ) { if ( priority == null ) { priority = cacheData . getPriority ( ) ; } if ( priority == null ) { // TODO check if alternative to fetch default priority and have non null only for custom performs good return 0 ; } return priority . byteValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setPriority ( byte value ) { priority = Byte . valueOf ( value ) ; cacheData . setPriority ( priority ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Sbb entity \" + getSbbEntityId ( ) + \" priority set to \" + priority ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void remove ( ) { if ( doTraceLogs ) { log . trace ( \"remove()\" ) ; } // removes the SBB entity from all Activity Contexts. for ( Iterator < ActivityContextHandle > i = this . getActivityContexts ( ) . iterator ( ) ; i . hasNext ( ) ; ) { ActivityContextHandle ach = i . next ( ) ; // get ac ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; // remove the sbb entity from the attachment set. if ( ac != null && ! ac . isEnding ( ) ) { ac . detachSbbEntity ( this . sbbeId ) ; } // no need to remove ac from entity because the entity is being // removed } // It invokes the appropriate life cycle methods (see Section 6.3) of an // SBB object that caches the SBB entity state. boolean invokingServiceSet = SleeThreadLocals . getInvokingService ( ) != null ; if ( ! invokingServiceSet ) { SleeThreadLocals . setInvokingService ( getServiceId ( ) ) ; } try { if ( this . sbbObject == null ) { this . assignSbbObject ( ) ; } removeAndReleaseSbbObject ( ) ; } catch ( Exception e ) { try { sleeContainer . getTransactionManager ( ) . setRollbackOnly ( ) ; this . trashObject ( ) ; } catch ( Exception e2 ) { throw new RuntimeException ( \"Transaction Failure.\" , e2 ) ; } } finally { if ( ! invokingServiceSet ) { SleeThreadLocals . setInvokingService ( null ) ; } } // remove children for ( SbbEntityID childSbbEntityId : cacheData . getAllChildSbbEntities ( ) ) { SbbEntity childSbbEntity = sbbEntityFactory . getSbbEntity ( childSbbEntityId , false ) ; if ( childSbbEntity != null ) { // recreate the sbb entity and remove it sbbEntityFactory . removeSbbEntity ( childSbbEntity , false ) ; } } cacheData . remove ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Removed sbb entity \" + getSbbEntityId ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void trashObject ( ) { try { // FIXME shouldn't just return the object to the pool? getObjectPool ( ) . returnObject ( sbbObject ) ; this . sbbObject = null ; } catch ( Exception e ) { throw new RuntimeException ( \"Unexpected exception \" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void sbbRolledBack ( Object event , ActivityContextInterface activityContextInterface , boolean removeRollback ) { if ( sbbObject != null ) { sbbObject . sbbRolledBack ( event , activityContextInterface , removeRollback ) ; passivateAndReleaseSbbObject ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SbbID getSbbId ( ) { if ( _sbbID == null ) { ServiceComponent serviceComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( getServiceId ( ) ) ; SbbComponent sbbComponent = null ; if ( sbbeId . isRootSbbEntity ( ) ) { _sbbID = serviceComponent . getRootSbbComponent ( ) . getSbbID ( ) ; } else { // put chain of parent sbb entity ids in a stack  final LinkedList < SbbEntityID > stack = new LinkedList < SbbEntityID > ( ) ; SbbEntityID sbbEntityID = sbbeId . getParentSBBEntityID ( ) ; while ( ! sbbEntityID . isRootSbbEntity ( ) ) { stack . push ( sbbEntityID ) ; sbbEntityID = sbbEntityID . getParentSBBEntityID ( ) ; } // now find out the sbb component of the parent sbbComponent = serviceComponent . getRootSbbComponent ( ) ; GetChildRelationMethodDescriptor getChildRelationMethodDescriptor = null ; while ( ! stack . isEmpty ( ) ) { sbbEntityID = stack . pop ( ) ; getChildRelationMethodDescriptor = sbbComponent . getDescriptor ( ) . getGetChildRelationMethodsMap ( ) . get ( sbbEntityID . getParentChildRelation ( ) ) ; sbbComponent = sleeContainer . getComponentRepository ( ) . getComponentByID ( getChildRelationMethodDescriptor . getSbbID ( ) ) ; } getChildRelationMethodDescriptor = sbbComponent . getDescriptor ( ) . getGetChildRelationMethodsMap ( ) . get ( sbbeId . getParentChildRelation ( ) ) ; _sbbID = getChildRelationMethodDescriptor . getSbbID ( ) ; } } return _sbbID ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void invokeEventHandler ( EventContext sleeEvent , ActivityContext ac , EventContext eventContextImpl ) throws Exception { // get event handler method final SbbComponent sbbComponent = getSbbComponent ( ) ; final EventHandlerMethod eventHandlerMethod = sbbComponent . getEventHandlerMethods ( ) . get ( sleeEvent . getEventTypeId ( ) ) ; // build aci ActivityContextInterface aci = asSbbActivityContextInterface ( ac . getActivityContextInterface ( ) ) ; // now build the param array final Object [ ] parameters ; if ( eventHandlerMethod . getHasEventContextParam ( ) ) { parameters = new Object [ ] { sleeEvent . getEvent ( ) , aci , eventContextImpl } ; } else { parameters = new Object [ ] { sleeEvent . getEvent ( ) , aci } ; } // store some info about the invocation in the tx context final EventRoutingTransactionData data = new EventRoutingTransactionDataImpl ( sleeEvent , aci ) ; final TransactionContext txContext = sleeContainer . getTransactionManager ( ) . getTransactionContext ( ) ; txContext . setEventRoutingTransactionData ( data ) ; // track sbb entity invocations if reentrant Set < SbbEntityID > invokedSbbentities = null ; if ( ! isReentrant ( ) ) { invokedSbbentities = txContext . getInvokedNonReentrantSbbEntities ( ) ; invokedSbbentities . add ( sbbeId ) ; } final JndiManagement jndiManagement = sleeContainer . getJndiManagement ( ) ; jndiManagement . pushJndiContext ( sbbComponent ) ; // invoke method try { //This is required. Since domain chain may indicate RA for instance, or SLEE deployer. If we dont do that test: tests/runtime/security/Test1112012Test.xml and second one, w //will fail because domain of SLEE tck ra is too restrictive (or we have bad desgin taht allows this to happen?) if ( System . getSecurityManager ( ) != null ) { AccessController . doPrivileged ( new PrivilegedExceptionAction < Object > ( ) { public Object run ( ) throws IllegalAccessException , InvocationTargetException { eventHandlerMethod . getEventHandlerMethod ( ) . invoke ( sbbObject . getSbbConcrete ( ) , parameters ) ; return null ; } } ) ; } else { eventHandlerMethod . getEventHandlerMethod ( ) . invoke ( sbbObject . getSbbConcrete ( ) , parameters ) ; } } catch ( PrivilegedActionException pae ) { Throwable cause = pae . getException ( ) ; if ( cause instanceof IllegalAccessException ) { throw new RuntimeException ( cause ) ; } else if ( cause instanceof InvocationTargetException ) { // Remember the actual exception is hidden inside the // InvocationTarget exception when you use reflection! Throwable realException = cause . getCause ( ) ; if ( realException instanceof RuntimeException ) { throw ( RuntimeException ) realException ; } else if ( realException instanceof Error ) { throw ( Error ) realException ; } else if ( realException instanceof Exception ) { throw ( Exception ) realException ; } } else { pae . printStackTrace ( ) ; } } catch ( IllegalAccessException iae ) { throw new RuntimeException ( iae ) ; } catch ( InvocationTargetException ite ) { Throwable realException = ite . getCause ( ) ; if ( realException instanceof RuntimeException ) { throw ( RuntimeException ) realException ; } else if ( realException instanceof Error ) { throw ( Error ) realException ; } else if ( realException instanceof Exception ) { throw ( Exception ) realException ; } } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } finally { jndiManagement . popJndiContext ( ) ; if ( invokedSbbentities != null ) { invokedSbbentities . remove ( sbbeId ) ; } } // remove data from tx context txContext . setEventRoutingTransactionData ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void passivateAndReleaseSbbObject ( ) { this . sbbObject . sbbStore ( ) ; this . sbbObject . sbbPassivate ( ) ; this . sbbObject . setState ( SbbObjectState . POOLED ) ; this . sbbObject . setSbbEntity ( null ) ; try { getObjectPool ( ) . returnObject ( this . sbbObject ) ; } catch ( Exception e ) { log . error ( \"failed to return sbb object \" + sbbObject + \" to pool\" , e ) ; } this . sbbObject = null ; if ( childsWithSbbObjects != null ) { for ( Iterator < SbbEntity > i = childsWithSbbObjects . iterator ( ) ; i . hasNext ( ) ; ) { SbbEntity childSbbEntity = i . next ( ) ; if ( childSbbEntity . getSbbObject ( ) != null ) { Thread t = Thread . currentThread ( ) ; ClassLoader cl = t . getContextClassLoader ( ) ; t . setContextClassLoader ( childSbbEntity . getSbbComponent ( ) . getClassLoader ( ) ) ; try { childSbbEntity . passivateAndReleaseSbbObject ( ) ; } finally { t . setContextClassLoader ( cl ) ; } } i . remove ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SbbObjectPool getObjectPool ( ) { if ( _pool == null ) { _pool = sleeContainer . getSbbManagement ( ) . getObjectPool ( getServiceId ( ) , getSbbId ( ) ) ; } return this . _pool ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ChildRelationImpl getChildRelation ( String accessorName ) { return new ChildRelationImpl ( this . getSbbComponent ( ) . getDescriptor ( ) . getGetChildRelationMethodsMap ( ) . get ( accessorName ) , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO improve with sbb local object storage [CODESPLIT] public SbbLocalObjectImpl getSbbLocalObject ( ) { if ( doTraceLogs ) log . trace ( \"getSbbLocalObject()\" ) ; // The concrete class generated in ConcreteLocalObjectGenerator final Class < ? > sbbLocalClass = getSbbComponent ( ) . getSbbLocalInterfaceConcreteClass ( ) ; if ( sbbLocalClass != null ) { Object [ ] objs = { this } ; Constructor < ? > constructor = getSbbComponent ( ) . getSbbLocalObjectClassConstructor ( ) ; if ( constructor == null ) { final Class < ? > [ ] types = { SbbEntityImpl . class } ; try { constructor = sbbLocalClass . getConstructor ( types ) ; } catch ( Throwable e ) { throw new SLEEException ( \"Unable to retrieve sbb local object generated class constructor\" , e ) ; } getSbbComponent ( ) . setSbbLocalObjectClassConstructor ( constructor ) ; } try { return ( SbbLocalObjectImpl ) constructor . newInstance ( objs ) ; } catch ( Throwable e ) { throw new SLEEException ( \"Failed to create Sbb Local Interface.\" , e ) ; } } else { return new SbbLocalObjectImpl ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void assignSbbObject ( ) throws Exception { try { // get one object from the pool this . sbbObject = getObjectPool ( ) . borrowObject ( ) ; // invoke the appropriate sbb life-cycle methods this . sbbObject . setSbbEntity ( this ) ; if ( created ) { this . sbbObject . sbbCreate ( ) ; this . sbbObject . setState ( SbbObjectState . READY ) ; this . sbbObject . sbbPostCreate ( ) ; } else { this . sbbObject . sbbActivate ( ) ; this . sbbObject . setState ( SbbObjectState . READY ) ; } this . sbbObject . sbbLoad ( ) ; } catch ( Exception e ) { log . error ( \"Failed to assign and create sbb object\" , e ) ; if ( created ) { removeFromCache ( ) ; } throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the index of the next executor to retrieve . Adaptation of the { @link AtomicInteger } incrementAndGet () code . [CODESPLIT] private int getNextIndex ( ) { for ( ; ; ) { int current = index . get ( ) ; int next = ( current == executors . length ? 1 : current + 1 ) ; if ( index . compareAndSet ( current , next ) ) return next - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void addExamples ( PrintWriter out ) { out . println ( \"\" ) ; out . println ( \"     1. List usage parameters type for profile table:\" ) ; out . println ( \"\" + name + \" CallControlTableName -l --parameters\" ) ; out . println ( \"\" ) ; out . println ( \"     2. List existing usage parameters sets:\" ) ; out . println ( \"\" + name + \" CallControlTableName -l --sets\" ) ; out . println ( \"\" ) ; out . println ( \"     3. Get value of parameter in certain set:\" ) ; out . println ( \"\" + name + \" CallControlTableName CertainSetWithValue -g --name=CookiesCount\" ) ; out . println ( \"\" ) ; out . println ( \"     4. Get value of parameter in certain set and reset value:\" ) ; out . println ( \"\" + name + \" CallControlTableName CertainSetWithValue -g --name=CookiesCount --rst\" ) ; out . println ( \"\" ) ; out . println ( \"     5. Reset all parameters in default parameter set of table:\" ) ; out . println ( \"\" + name + \" CallControlTableName --reset\" ) ; out . println ( \"\" ) ; out . println ( \"     6. Create parameter set:\" ) ; out . println ( \"\" + name + \" CallControlTableName NewSet --create\" ) ; out . println ( \"\" ) ; out . println ( \"     7. Enable notification generation for parameter:\" ) ; out . println ( \"\" + name + \" CallControlTableName -n --name=CookiesCount --value=true\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the log4j logger name for the tracer with specified named and notification source . [CODESPLIT] private String tracerNameToLog4JLoggerName ( String tracerName , NotificationSource notificationSource ) { final StringBuilder sb = new StringBuilder ( \"javax.slee.\" ) . append ( notificationSource . toString ( ) ) ; if ( ! tracerName . equals ( ROOT_TRACER_NAME ) ) { sb . append ( ' ' ) . append ( tracerName ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "syncs the slee tracer level with the one that related logger has in log4j [CODESPLIT] void syncLevelWithLog4j ( ) { // get the level from log4j, only the root one uses effective level\r Level log4jLevel = parent == null ? logger . getEffectiveLevel ( ) : logger . getLevel ( ) ; if ( level == null ) { // set the level\r assignLog4JLevel ( log4jLevel ) ; } else { // set the level only if differs, otherwise we may loose levels not present in log4j\r if ( tracerToLog4JLevel ( level ) != log4jLevel ) { assignLog4JLevel ( log4jLevel ) ; } } // the root must always have a level\r if ( parent == null && level == null ) { // defaults to INFO\r logger . setLevel ( Level . INFO ) ; level = TraceLevel . INFO ; } // reset the flags\r resetCacheFlags ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assigns the equiv log4j level to the tracer [CODESPLIT] private void assignLog4JLevel ( Level log4jLevel ) { if ( log4jLevel == null ) { return ; } if ( log4jLevel == Level . DEBUG ) { level = TraceLevel . FINE ; } else if ( log4jLevel == Level . INFO ) { level = TraceLevel . INFO ; } else if ( log4jLevel == Level . WARN ) { level = TraceLevel . WARNING ; } else if ( log4jLevel == Level . ERROR ) { level = TraceLevel . SEVERE ; } else if ( log4jLevel == Level . TRACE ) { level = TraceLevel . FINEST ; } else if ( log4jLevel == Level . OFF ) { level = TraceLevel . OFF ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "manages the flags which cache if levels are enabled [CODESPLIT] void resetCacheFlags ( boolean resetChilds ) { if ( isTraceable ( TraceLevel . FINEST ) ) { finestEnabled = true ; finerEnabled = true ; fineEnabled = true ; configEnabled = true ; infoEnabled = true ; warningEnabled = true ; severeEnabled = true ; } else { finestEnabled = false ; if ( isTraceable ( TraceLevel . FINER ) ) { finerEnabled = true ; fineEnabled = true ; configEnabled = true ; infoEnabled = true ; warningEnabled = true ; severeEnabled = true ; } else { finerEnabled = false ; if ( isTraceable ( TraceLevel . FINE ) ) { fineEnabled = true ; configEnabled = true ; infoEnabled = true ; warningEnabled = true ; severeEnabled = true ; } else { fineEnabled = false ; if ( isTraceable ( TraceLevel . CONFIG ) ) { configEnabled = true ; infoEnabled = true ; warningEnabled = true ; severeEnabled = true ; } else { if ( isTraceable ( TraceLevel . INFO ) ) { infoEnabled = true ; warningEnabled = true ; severeEnabled = true ; } else { infoEnabled = false ; if ( isTraceable ( TraceLevel . WARNING ) ) { warningEnabled = true ; severeEnabled = true ; } else { warningEnabled = false ; if ( isTraceable ( TraceLevel . SEVERE ) ) { severeEnabled = true ; } else { severeEnabled = false ; } } } } } } } if ( resetChilds ) { // implicit change of level demands that we update reset flags on childs without level\r for ( TracerImpl child : childs ) { if ( child . level == null ) { child . resetCacheFlags ( true ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void config ( String message ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . CONFIG , message , null ) ; logger . info ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void config ( String message , Throwable t ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . CONFIG , message , t ) ; logger . info ( message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void fine ( String message ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . FINE , message , null ) ; logger . debug ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void fine ( String message , Throwable t ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . FINE , message , t ) ; logger . debug ( message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void finer ( String message ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . FINER , message , null ) ; logger . debug ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void finer ( String message , Throwable t ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . FINER , message , t ) ; logger . debug ( message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void finest ( String message ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . FINEST , message , null ) ; logger . trace ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void finest ( String message , Throwable t ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . FINEST , message , t ) ; logger . trace ( message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void info ( String message ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . INFO , message , null ) ; logger . info ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void info ( String message , Throwable t ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . INFO , message , t ) ; logger . info ( message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void severe ( String message ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . SEVERE , message , null ) ; logger . error ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void severe ( String message , Throwable t ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . SEVERE , message , t ) ; logger . error ( message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void trace ( TraceLevel traceLevel , String message , Throwable t ) throws NullPointerException , IllegalArgumentException , FacilityException { sendNotification ( traceLevel , message , t ) ; logger . log ( tracerToLog4JLevel ( traceLevel ) , message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void warning ( String message ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . WARNING , message , null ) ; logger . warn ( message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void warning ( String message , Throwable t ) throws NullPointerException , FacilityException { sendNotification ( TraceLevel . WARNING , message , t ) ; logger . warn ( message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "THis is internaly called by 1 . 1 tracers [CODESPLIT] void sendNotification ( javax . slee . facilities . TraceLevel level , String message , Throwable t ) { if ( ! isTraceable ( level ) ) { return ; } traceMBean . sendNotification ( new TraceNotification ( notificationSource . getNotificationSource ( ) . getTraceNotificationType ( ) , traceMBean , notificationSource . getNotificationSource ( ) , getTracerName ( ) , level , message , t , notificationSource . getNextSequence ( ) , System . currentTimeMillis ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This checks if the specified tracer name is ok . [CODESPLIT] public static void checkTracerName ( String tracerName , NotificationSource notificationSource ) throws NullPointerException , InvalidArgumentException { if ( tracerName . equals ( \"\" ) ) { // This is root\r return ; } StringTokenizer stringTokenizer = new StringTokenizer ( tracerName , \".\" , true ) ; String lastToken = null ; while ( stringTokenizer . hasMoreTokens ( ) ) { String token = stringTokenizer . nextToken ( ) ; if ( lastToken == null ) { // this is start\r lastToken = token ; } if ( lastToken . equals ( token ) && token . equals ( \".\" ) ) { throw new InvalidArgumentException ( \"Passed tracer:\" + tracerName + \", name for source: \" + notificationSource + \", is illegal\" ) ; } lastToken = token ; } if ( lastToken . equals ( \".\" ) ) { throw new IllegalArgumentException ( \"Passed tracer:\" + tracerName + \", name for source: \" + notificationSource + \", is illegal\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the current object and vendor - specific data to the output stream . [CODESPLIT] public static void writeObject ( ObjectOutputStream out , Object vendorData ) throws IOException { // write non-transient fields out . defaultWriteObject ( ) ; // check if should we serialize vendor data? if ( vendorData != null ) { // serialize the vendor data out . writeBoolean ( true ) ; // write the vendor data in a marshalled object so deserialization can be deferred out . writeObject ( new MarshalledObject ( vendorData ) ) ; } else out . writeBoolean ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the current object in the input stream from the stream optionally deserializing any vendor - specific data in the stream . [CODESPLIT] public static Object readObject ( ObjectInputStream in , boolean vendorDataDeserializationEnabled ) throws IOException , ClassNotFoundException { // read non-transient fields in . defaultReadObject ( ) ; // read any possible marshalled vendor data from the stream MarshalledObject vendorData = in . readBoolean ( ) ? ( MarshalledObject ) in . readObject ( ) : null ; // now figure out what to return return ( vendorData != null && vendorDataDeserializationEnabled ) ? vendorData . get ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a direct dependency to this domain . Direct dependencies are other domains which the domain depends on . [CODESPLIT] public void addDirectDependency ( URLClassLoaderDomainImpl domain ) { if ( logger . isTraceEnabled ( ) ) logger . trace ( toString ( ) + \" adding domain \" + domain + \" to direct dependencies\" ) ; directDependencies . add ( domain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a flat list containing all dependencies for the domain i . e . all direct dependencies and their own dependencies . [CODESPLIT] public List < URLClassLoaderDomainImpl > getAllDependencies ( ) { List < URLClassLoaderDomainImpl > result = new ArrayList < URLClassLoaderDomainImpl > ( ) ; this . getAllDependencies ( result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a class locally i . e . in the URLs managed by the extended URLClassLoader . [CODESPLIT] protected Class < ? > findClassLocally ( String name ) throws ClassNotFoundException { if ( logger . isTraceEnabled ( ) ) { logger . trace ( toString ( ) + \" findClassLocally: \" + name ) ; } final boolean acquiredLock = acquireGlobalLock ( ) ; try { return findClassLocallyLocked ( name ) ; } finally { if ( acquiredLock ) { releaseGlobalLock ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a resource locally i . e . in the URLs managed by the extended URLClassLoader . [CODESPLIT] protected URL findResourceLocally ( String name ) { if ( logger . isTraceEnabled ( ) ) logger . trace ( toString ( ) + \" findResourceLocally: \" + name ) ; return super . findResource ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds resources locally i . e . in the URLs managed by the extended URLClassLoader . [CODESPLIT] protected Enumeration < URL > findResourcesLocally ( String name ) throws IOException { if ( logger . isTraceEnabled ( ) ) logger . trace ( toString ( ) + \" findResourcesLocally: \" + name ) ; return super . findResources ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName createProfile ( java . lang . String profileTableName , java . lang . String profileName ) throws java . lang . NullPointerException , UnrecognizedProfileTableNameException , InvalidArgumentException , ProfileAlreadyExistsException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"createProfile( profileTable = \" + profileTableName + \" , profile = \" + profileName + \" )\" ) ; } try { ProfileTableImpl . validateProfileName ( profileName ) ; ProfileTableImpl . validateProfileTableName ( profileTableName ) ; } catch ( IllegalArgumentException e ) { throw new InvalidArgumentException ( e . getMessage ( ) ) ; } Transaction transaction = null ; boolean rollback = true ; try { // begin tx\r sleeTransactionManagement . begin ( ) ; transaction = sleeTransactionManagement . getTransaction ( ) ; // This checks if profile table exists - throws SLEEException in\r // case of system level and UnrecognizedProfileTableNameException in\r // case of no such table\r final ProfileTableImpl profileTable = this . sleeProfileManagement . getProfileTable ( profileTableName ) ; // create profile\r profileTable . createProfile ( profileName ) ; if ( sleeTransactionManagement . getRollbackOnly ( ) ) { throw new ManagementException ( \"Transaction used in profile creation rolled back\" ) ; } else { // create mbean and registers it\r final AbstractProfileMBeanImpl profileMBean = createAndRegisterProfileMBean ( profileName , profileTable ) ; // keep track of the mbean existence\r profileTable . addUncommittedProfileMBean ( profileMBean ) ; TransactionalAction action = new TransactionalAction ( ) { public void execute ( ) { profileTable . removeUncommittedProfileMBean ( profileMBean ) ; } } ; final TransactionContext txContext = sleeTransactionManagement . getTransactionContext ( ) ; txContext . getAfterCommitActions ( ) . add ( action ) ; txContext . getAfterRollbackActions ( ) . add ( action ) ; // indicate profile creation\r profileMBean . createProfile ( ) ; rollback = false ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"createProfile( profileTable = \" + profileTableName + \" , profile = \" + profileName + \" ) result is \" + profileMBean . getObjectName ( ) ) ; } return profileMBean . getObjectName ( ) ; } } catch ( TransactionRequiredLocalException e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } catch ( SLEEException e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } catch ( CreateException e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } catch ( NotSupportedException e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } catch ( SystemException e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } finally { if ( rollback ) { try { if ( sleeTransactionManagement . getTransaction ( ) == null ) { // the tx was suspended, resume it\r sleeTransactionManagement . resume ( transaction ) ; } sleeTransactionManagement . rollback ( ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and registers a profile mbean for the specified object . [CODESPLIT] private AbstractProfileMBeanImpl createAndRegisterProfileMBean ( String profileName , ProfileTableImpl profileTable ) throws ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"createAndRegisterProfileMBean( profileTable = \" + profileTable + \" , profileName = \" + profileName + \" )\" ) ; } try { ProfileSpecificationComponent component = profileTable . getProfileSpecificationComponent ( ) ; Constructor < ? > constructor = component . getProfileMBeanConcreteImplClass ( ) . getConstructor ( Class . class , String . class , ProfileTableImpl . class ) ; final AbstractProfileMBeanImpl profileMBean = ( AbstractProfileMBeanImpl ) constructor . newInstance ( component . getProfileMBeanConcreteInterfaceClass ( ) , profileName , profileTable ) ; profileMBean . register ( ) ; // add a rollback action to unregister the mbean\r TransactionalAction rollbackAction = new TransactionalAction ( ) { public void execute ( ) { try { profileMBean . unregister ( ) ; } catch ( Throwable e ) { logger . error ( e . getMessage ( ) , e ) ; } } } ; sleeTransactionManagement . getTransactionContext ( ) . getAfterRollbackActions ( ) . add ( rollbackAction ) ; return profileMBean ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void createProfileTable ( ProfileSpecificationID specificationID , String profileTableName ) throws NullPointerException , UnrecognizedProfileSpecificationException , InvalidArgumentException , ProfileTableAlreadyExistsException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"createProfileTable( profileTable = \" + profileTableName + \" , specificationID = \" + specificationID + \" )\" ) ; } try { ProfileTableImpl . validateProfileTableName ( profileTableName ) ; } catch ( IllegalArgumentException e ) { throw new InvalidArgumentException ( e . getMessage ( ) ) ; } final SleeContainer sleeContainer = getSleeContainer ( ) ; if ( sleeContainer . getSleeState ( ) != SleeState . RUNNING ) return ; ProfileSpecificationComponent component = sleeContainer . getComponentRepository ( ) . getComponentByID ( specificationID ) ; if ( component == null ) throw new UnrecognizedProfileSpecificationException ( ) ; ClassLoader currentClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; boolean terminateTx = sleeTransactionManagement . requireTransaction ( ) ; boolean doRollback = true ; try { Thread . currentThread ( ) . setContextClassLoader ( component . getClassLoader ( ) ) ; sleeProfileManagement . addProfileTable ( profileTableName , component ) ; doRollback = false ; } catch ( ProfileTableAlreadyExistsException e ) { throw e ; } catch ( Throwable e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( e . getMessage ( ) , e ) ; } throw new ManagementException ( e . getMessage ( ) , e ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( currentClassLoader ) ; try { sleeTransactionManagement . requireTransactionEnd ( terminateTx , doRollback ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName getDefaultProfile ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getDefaultProfile( profileTable = \" + profileTableName + \" )\" ) ; } try { return _getProfile ( profileTableName , null ) ; } catch ( UnrecognizedProfileNameException e ) { // can't happen\r throw new ManagementException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName getProfile ( java . lang . String profileTableName , java . lang . String profileName ) throws NullPointerException , UnrecognizedProfileTableNameException , UnrecognizedProfileNameException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfile( profileTable = \" + profileTableName + \" , profile = \" + profileName + \" )\" ) ; } ProfileTableImpl . validateProfileName ( profileName ) ; ObjectName objectName = _getProfile ( profileTableName , profileName ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfile( profileTable = \" + profileTableName + \" , profile = \" + profileName + \" ) result is \" + objectName ) ; } return objectName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileSpecificationID getProfileSpecification ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfileSpecification( profileTableName = \" + profileTableName + \" )\" ) ; } if ( profileTableName == null ) throw new NullPointerException ( \"Argument[ProfileTableName] must not be null\" ) ; boolean b = false ; try { b = this . sleeTransactionManagement . requireTransaction ( ) ; ProfileTableImpl profileTable = this . sleeProfileManagement . getProfileTable ( profileTableName ) ; return profileTable . getProfileSpecificationComponent ( ) . getProfileSpecificationID ( ) ; } catch ( SLEEException e ) { throw new ManagementException ( \"Failed to obtain ProfileSpecID name for ProfileTable: \" + profileTableName , e ) ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to obtain ProfileSpecID name for ProfileTable: \" + profileTableName , e ) ; } finally { // never rollbacks\r try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ObjectName getProfileTableUsageMBean ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , InvalidArgumentException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfileTableUsageMBean( profileTableName = \" + profileTableName + \" )\" ) ; } if ( profileTableName == null ) throw new NullPointerException ( \"Argument[ProfileTableName] must not be null\" ) ; boolean b = this . sleeTransactionManagement . requireTransaction ( ) ; try { ProfileTableUsageMBean usageMBeanImpl = this . sleeProfileManagement . getProfileTable ( profileTableName ) . getProfileTableUsageMBean ( ) ; if ( usageMBeanImpl == null ) { throw new InvalidArgumentException ( ) ; } else { // ensure it is open\r usageMBeanImpl . open ( ) ; // return its object name\t\t\t\t\r return usageMBeanImpl . getObjectName ( ) ; } } catch ( SLEEException e ) { throw new ManagementException ( \"Failed to obtain ProfileSpecID name for ProfileTable: \" + profileTableName , e ) ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( InvalidArgumentException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( \"Failed to obtain ProfileSpecID name for ProfileTable: \" + profileTableName , e ) ; } finally { // never rollbacks\r try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < String > getProfileTables ( ) throws ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfileTables()\" ) ; } boolean b = sleeTransactionManagement . requireTransaction ( ) ; try { return sleeProfileManagement . getDeclaredProfileTableNames ( ) ; } catch ( Exception x ) { if ( x instanceof ManagementException ) throw ( ManagementException ) x ; else throw new ManagementException ( \"Failed getProfileTable\" , x ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < String > getProfileTables ( ProfileSpecificationID id ) throws java . lang . NullPointerException , UnrecognizedProfileSpecificationException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfileTables( id = \" + id + \" )\" ) ; } if ( id == null ) { throw new NullPointerException ( \"null profile spec id\" ) ; } boolean b = sleeTransactionManagement . requireTransaction ( ) ; try { return sleeProfileManagement . getDeclaredProfileTableNames ( id ) ; } catch ( UnrecognizedProfileSpecificationException x ) { throw x ; } catch ( Throwable x ) { throw new ManagementException ( \"Failed createProfileTable\" , x ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < ProfileID > getProfiles ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfiles( profileTableName = \" + profileTableName + \" )\" ) ; } boolean b = sleeTransactionManagement . requireTransaction ( ) ; try { return sleeProfileManagement . getProfileTable ( profileTableName ) . getProfiles ( ) ; } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < ProfileID > getProfilesByAttribute ( String profileTableName , String attributeName , Object attributeValue ) throws NullPointerException , UnrecognizedProfileTableNameException , UnrecognizedAttributeException , AttributeTypeMismatchException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfilesByAttribute( profileTableName = \" + profileTableName + \" , attributeName = \" + attributeName + \" , attributeValue = \" + attributeValue + \" )\" ) ; } boolean b = sleeTransactionManagement . requireTransaction ( ) ; try { ProfileTableImpl profileTable = sleeProfileManagement . getProfileTable ( profileTableName ) ; if ( ! profileTable . getProfileSpecificationComponent ( ) . isSlee11 ( ) ) { throw new UnsupportedOperationException ( \"JAIN SLEE 1.1 Specs forbiddens the usage of this method on SLEE 1.0 Profile Tables\" ) ; } else { return profileTable . getProfilesByAttribute ( attributeName , attributeValue , true ) ; } } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( UnrecognizedAttributeException e ) { throw e ; } catch ( AttributeTypeMismatchException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < ProfileID > getProfilesByDynamicQuery ( String profileTableName , QueryExpression queryExpression ) throws NullPointerException , UnrecognizedProfileTableNameException , UnrecognizedAttributeException , AttributeTypeMismatchException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfilesByDynamicQuery( profileTableName = \" + profileTableName + \" , queryExpression = \" + queryExpression + \" )\" ) ; } if ( queryExpression == null ) { throw new NullPointerException ( \"queryExpression is null\" ) ; } boolean b = sleeTransactionManagement . requireTransaction ( ) ; Collection < ProfileID > profileIDs = new ArrayList < ProfileID > ( ) ; try { ProfileTableImpl profileTable = sleeProfileManagement . getProfileTable ( profileTableName ) ; if ( ! profileTable . getProfileSpecificationComponent ( ) . isSlee11 ( ) ) { throw new UnsupportedOperationException ( \"JAIN SLEE 1.1 Specs forbiddens the usage of this method on SLEE 1.0 Profile Tables\" ) ; } for ( ProfileEntity profileEntity : profileTable . getProfileSpecificationComponent ( ) . getProfileEntityFramework ( ) . getProfilesByDynamicQuery ( profileTableName , queryExpression ) ) { profileIDs . add ( new ProfileID ( profileEntity . getTableName ( ) , profileEntity . getProfileName ( ) ) ) ; } } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( UnrecognizedAttributeException e ) { throw e ; } catch ( AttributeTypeMismatchException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( \"Failed to obtain ProfileNames for ProfileTable: \" + profileTableName , e ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } return profileIDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Collection < ProfileID > getProfilesByStaticQuery ( String profileTableName , String queryName , Object [ ] parameters ) throws NullPointerException , UnrecognizedProfileTableNameException , UnrecognizedQueryNameException , InvalidArgumentException , AttributeTypeMismatchException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"getProfilesByStaticQuery( profileTableName = \" + profileTableName + \" , queryName = \" + queryName + \" , parameters = \" + Arrays . asList ( parameters ) + \" )\" ) ; } if ( queryName == null ) { throw new NullPointerException ( \"queryName is null\" ) ; } boolean b = sleeTransactionManagement . requireTransaction ( ) ; Collection < ProfileID > profileIDs = new ArrayList < ProfileID > ( ) ; try { ProfileTableImpl profileTable = sleeProfileManagement . getProfileTable ( profileTableName ) ; if ( ! profileTable . getProfileSpecificationComponent ( ) . isSlee11 ( ) ) { throw new UnsupportedOperationException ( \"JAIN SLEE 1.1 Specs forbiddens the usage of this method on SLEE 1.0 Profile Tables\" ) ; } for ( ProfileEntity profileEntity : profileTable . getProfileSpecificationComponent ( ) . getProfileEntityFramework ( ) . getProfilesByStaticQuery ( profileTableName , queryName , parameters ) ) { profileIDs . add ( new ProfileID ( profileEntity . getTableName ( ) , profileEntity . getProfileName ( ) ) ) ; } } catch ( NullPointerException e ) { throw e ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( UnrecognizedQueryNameException e ) { throw e ; } catch ( InvalidArgumentException e ) { throw e ; } catch ( AttributeTypeMismatchException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( \"Failed to obtain ProfileNames for ProfileTable: \" + profileTableName , e ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , false ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } return profileIDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void removeProfile ( java . lang . String profileTableName , java . lang . String profileName ) throws java . lang . NullPointerException , UnrecognizedProfileTableNameException , UnrecognizedProfileNameException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"removeProfile( profileTableName = \" + profileTableName + \" , profileName = \" + profileName + \" )\" ) ; } if ( profileTableName == null ) throw new NullPointerException ( \"Argument[ProfileTableName] must nto be null\" ) ; if ( profileName == null ) throw new NullPointerException ( \"Argument[ProfileName] must nto be null\" ) ; boolean b = this . sleeTransactionManagement . requireTransaction ( ) ; boolean rb = true ; try { ProfileTableImpl profileTable = this . sleeProfileManagement . getProfileTable ( profileTableName ) ; if ( ! profileTable . profileExists ( profileName ) ) { throw new UnrecognizedProfileNameException ( \"There is no such profile: \" + profileName + \", in profile table: \" + profileTableName ) ; } profileTable . removeProfile ( profileName , true , false ) ; if ( ! sleeTransactionManagement . getRollbackOnly ( ) ) { rb = false ; } else { throw new ManagementException ( \"Transaction used in profile removal rolled back\" ) ; } } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( UnrecognizedProfileNameException e ) { throw e ; } catch ( Exception e ) { throw new ManagementException ( \"Failed to remove due to system level failure.\" , e ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , rb ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void removeProfileTable ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"removeProfileTable( profileTableName = \" + profileTableName + \" )\" ) ; } if ( profileTableName == null ) throw new NullPointerException ( \"profileTableName is null\" ) ; boolean b = this . sleeTransactionManagement . requireTransaction ( ) ; boolean rb = false ; try { this . sleeProfileManagement . removeProfileTable ( profileTableName ) ; } catch ( UnrecognizedProfileTableNameException e ) { rb = true ; throw e ; } catch ( Throwable e ) { rb = true ; throw new ManagementException ( \"Failed to remove due to system level failure.\" , e ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , rb ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void renameProfileTable ( java . lang . String oldProfileTableName , java . lang . String newProfileTableName ) throws java . lang . NullPointerException , UnrecognizedProfileTableNameException , InvalidArgumentException , ProfileTableAlreadyExistsException , ManagementException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"renameProfileTable( oldProfileTableName = \" + oldProfileTableName + \" , newProfileTableName = \" + newProfileTableName + \" )\" ) ; } if ( oldProfileTableName == null ) throw new NullPointerException ( \"Argument[OldProfileTableName] must nto be null\" ) ; if ( newProfileTableName == null ) throw new NullPointerException ( \"Argument[NewProfileTableName] must nto be null\" ) ; ProfileTableImpl . validateProfileTableName ( newProfileTableName ) ; boolean b = this . sleeTransactionManagement . requireTransaction ( ) ; boolean rb = true ; try { this . sleeProfileManagement . renameProfileTable ( oldProfileTableName , newProfileTableName ) ; rb = false ; } catch ( UnrecognizedProfileTableNameException e ) { throw e ; } catch ( ProfileTableAlreadyExistsException e ) { throw e ; } catch ( Throwable e ) { throw new ManagementException ( \"Failed to remove due to system level failure.\" , e ) ; } finally { try { sleeTransactionManagement . requireTransactionEnd ( b , rb ) ; } catch ( Throwable e ) { throw new ManagementException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method to create new instance of concrete impl class of { @link AbstractUsageParameterSet } . [CODESPLIT] public static final AbstractUsageParameterSet newInstance ( Class < ? > concreteClass , NotificationSource notificationSource , String parameterSetName , SleeContainer sleeContainer ) throws SecurityException , NoSuchMethodException , IllegalArgumentException , InstantiationException , IllegalAccessException , InvocationTargetException { Constructor < ? > constructor = concreteClass . getConstructor ( NotificationSource . class , String . class , SleeContainer . class ) ; return ( AbstractUsageParameterSet ) constructor . newInstance ( notificationSource , parameterSetName , sleeContainer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Suspends the current tx ( if exists ) . [CODESPLIT] SleeTransaction suspendTransaction ( ) throws SLEEException { try { final SleeTransaction tx = txManager . getTransaction ( ) ; if ( tx != null ) { txManager . suspend ( ) ; } return tx ; } catch ( SystemException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resumes the specified tx . If it is null nothing is done . [CODESPLIT] void resumeTransaction ( SleeTransaction transaction ) throws SLEEException { if ( transaction != null ) { try { txManager . resume ( transaction ) ; } catch ( Throwable e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ComponentClassLoaderImpl newComponentClassLoader ( ComponentID componentID , URLClassLoaderDomain parent ) { return new ComponentClassLoaderImpl ( componentID , ( URLClassLoaderDomainImpl ) parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the JAIN SLEE specs descriptor [CODESPLIT] public javax . slee . management . ServiceDescriptor getSpecsDescriptor ( ) { if ( specsDescriptor == null ) { specsDescriptor = new javax . slee . management . ServiceDescriptor ( getServiceID ( ) , getDeployableUnit ( ) . getDeployableUnitID ( ) , getDeploymentUnitSource ( ) , descriptor . getRootSbbID ( ) , descriptor . getAddressProfileTable ( ) , descriptor . getResourceInfoProfileTable ( ) ) ; } return specsDescriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the set of sbbs used by this service [CODESPLIT] public Set < SbbID > getSbbIDs ( ComponentRepository componentRepository ) { Set < SbbID > result = new HashSet < SbbID > ( ) ; buildSbbTree ( descriptor . getRootSbbID ( ) , result , componentRepository ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the set of ra entity links referenced by the sbbs related with the service . [CODESPLIT] public Set < String > getResourceAdaptorEntityLinks ( ComponentRepository componentRepository ) { Set < String > result = new HashSet < String > ( ) ; for ( SbbID sbbID : getSbbIDs ( componentRepository ) ) { SbbComponent sbbComponent = componentRepository . getComponentByID ( sbbID ) ; for ( ResourceAdaptorTypeBindingDescriptor raTypeBinding : sbbComponent . getDescriptor ( ) . getResourceAdaptorTypeBindings ( ) ) { for ( ResourceAdaptorEntityBindingDescriptor raEntityBinding : raTypeBinding . getResourceAdaptorEntityBinding ( ) ) { result . add ( raEntityBinding . getResourceAdaptorEntityLink ( ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a URL to the specified resource ( as returned by the system classloader ) . to the resource table of the resolver . [CODESPLIT] private void registerResource ( String publicID , String resourceName ) { URL url = this . getClass ( ) . getClassLoader ( ) . getResource ( resourceName ) ; if ( url != null ) { resources . put ( publicID , url ) ; } else { //All the slee dtds should be packaged locally in sar of slee itself\r throw new IllegalStateException ( \"Cannot find resource:\" + resourceName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumps the container state as a string useful for debug / profiling [CODESPLIT] public String dumpState ( ) { return componentManagement + \"\\n\" + resourceManagement + \"\\n\" + timerFacility + \"\\n\" + traceMBeanImpl + \"\\n\" + sleeProfileTableManager + \"\\n\" + activityContextFactory + \"\\n\" + activityContextNamingFacility + \"\\n\" + nullActivityFactory + \"\\n\" + getEventRouter ( ) + \"\\n\" + getEventContextFactory ( ) + \"\\n\" + getTransactionManager ( ) + \"\\n\" ; //+ cluster.getMobicentsCache().getCacheContent(); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiates the SLEE container [CODESPLIT] public void initSlee ( ) throws InvalidStateException { if ( sleeState != null ) { throw new InvalidStateException ( \"slee in \" + sleeState + \" state\" ) ; } // slee init beforeModulesInitialization ( ) ; for ( Iterator < SleeContainerModule > i = modules . iterator ( ) ; i . hasNext ( ) ; ) { i . next ( ) . sleeInitialization ( ) ; } afterModulesInitialization ( ) ; sleeState = SleeState . STOPPED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdown of the SLEE container [CODESPLIT] public void shutdownSlee ( ) throws InvalidStateException { if ( sleeState != SleeState . STOPPED ) { throw new InvalidStateException ( \"slee in \" + sleeState + \" state\" ) ; } // slee shutdown beforeModulesShutdown ( ) ; for ( Iterator < SleeContainerModule > i = modules . descendingIterator ( ) ; i . hasNext ( ) ; ) { i . next ( ) . sleeShutdown ( ) ; } afterModulesShutdown ( ) ; sleeState = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures the standard SLEE lifecycle . [CODESPLIT] private void validateStateTransition ( SleeState oldState , SleeState newState ) throws InvalidStateException { if ( oldState == SleeState . STOPPED ) { if ( newState == SleeState . STARTING ) { return ; } } else if ( oldState == SleeState . STARTING ) { if ( newState == SleeState . RUNNING || newState == SleeState . STOPPING ) { return ; } } else if ( oldState == SleeState . RUNNING ) { if ( newState == SleeState . STOPPING ) { return ; } } else if ( oldState == SleeState . STOPPING ) { if ( newState == SleeState . STOPPED ) { return ; } } throw new InvalidStateException ( \"illegal slee state transition: \" + oldState + \" -> \" + newState ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void setExecutorMapperClassName ( String className ) throws ClassNotFoundException { Class . forName ( className ) ; if ( this . executorMapperClassName != null ) { logger . warn ( \"Setting executorMapperClassName property to \" + className + \". If called with server running a stop and start is need to apply changes.\" ) ; } this . executorMapperClassName = className ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileLocalObject getProfileLocalObject ( ) throws IllegalStateException , SLEEException { // check state\r if ( profileObject == null || profileObject . getState ( ) == ProfileObjectState . PROFILE_INITIALIZATION || profileObject . getProfileEntity ( ) == null ) { throw new IllegalStateException ( ) ; } // check if it is default profile\r if ( profileObject . getProfileEntity ( ) . getProfileName ( ) == null ) { throw new IllegalStateException ( ) ; } return profileObject . getProfileLocalObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String getProfileName ( ) throws IllegalStateException , SLEEException { doGeneralChecks ( ) ; if ( profileObject == null || profileObject . getState ( ) == ProfileObjectState . PROFILE_INITIALIZATION || profileObject . getProfileEntity ( ) == null ) { throw new IllegalStateException ( ) ; } return this . profileObject . getProfileEntity ( ) . getProfileName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileTable getProfileTable ( String profileTableName ) throws NullPointerException , UnrecognizedProfileTableNameException , SLEEException { return this . profileTable . getSleeContainer ( ) . getSleeProfileTableManager ( ) . getProfileTable ( profileTableName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String getProfileTableName ( ) throws SLEEException { doGeneralChecks ( ) ; try { return this . profileTable . getProfileTableName ( ) ; } catch ( Exception e ) { throw new SLEEException ( \"Operaion failed.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean getRollbackOnly ( ) throws TransactionRequiredLocalException , SLEEException { doGeneralChecks ( ) ; final SleeTransactionManager txMgr = profileTable . getSleeContainer ( ) . getTransactionManager ( ) ; txMgr . mandateTransaction ( ) ; try { return txMgr . getRollbackOnly ( ) ; } catch ( SystemException e ) { throw new SLEEException ( \"Problem with the tx manager!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Tracer getTracer ( String tracerName ) throws NullPointerException , IllegalArgumentException , SLEEException { doGeneralChecks ( ) ; try { TracerImpl . checkTracerName ( tracerName , this . profileTable . getProfileTableNotification ( ) . getNotificationSource ( ) ) ; } catch ( InvalidArgumentException e1 ) { throw new IllegalArgumentException ( e1 ) ; } try { return profileTable . getSleeContainer ( ) . getTraceManagement ( ) . createTracer ( this . profileTable . getProfileTableNotification ( ) . getNotificationSource ( ) , tracerName , true ) ; } catch ( Exception e ) { throw new SLEEException ( \"Failed to obtain tracer\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public EventTypeComponent getComponentByID ( EventTypeID id ) { // get from repository EventTypeComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository, get it from deployable unit component = deployableUnit . getEventTypeComponents ( ) . get ( id ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ProfileSpecificationComponent getComponentByID ( ProfileSpecificationID id ) { // get from repository ProfileSpecificationComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository, get it from deployable unit component = deployableUnit . getProfileSpecificationComponents ( ) . get ( id ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public LibraryComponent getComponentByID ( LibraryID id ) { // get from repository LibraryComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository, get it from deployable unit component = deployableUnit . getLibraryComponents ( ) . get ( id ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ResourceAdaptorComponent getComponentByID ( ResourceAdaptorID id ) { // get from repository ResourceAdaptorComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository, get it from deployable unit component = deployableUnit . getResourceAdaptorComponents ( ) . get ( id ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ResourceAdaptorTypeComponent getComponentByID ( ResourceAdaptorTypeID id ) { // get from repository ResourceAdaptorTypeComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository, get it from deployable unit component = deployableUnit . getResourceAdaptorTypeComponents ( ) . get ( id ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public SbbComponent getComponentByID ( SbbID id ) { // get from repository SbbComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository, get it from deployable unit component = deployableUnit . getSbbComponents ( ) . get ( id ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ServiceComponent getComponentByID ( ServiceID id ) { // get from repository ServiceComponent component = componentRepository . getComponentByID ( id ) ; if ( component == null ) { // not found in repository, get it from deployable unit component = deployableUnit . getServiceComponents ( ) . get ( id ) ; } return component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a named usage parameter getter . [CODESPLIT] private void generateNamedUsageParameterGetter ( CtClass profileConcreteClass ) { String methodName = \"getUsageParameterSet\" ; for ( CtMethod ctMethod : profileConcreteClass . getMethods ( ) ) { if ( ctMethod . getName ( ) . equals ( methodName ) ) { try { // copy method, we can't just add body becase it is in super\r // class and does not sees profileObject field\r CtMethod ctMethodCopy = CtNewMethod . copy ( ctMethod , profileConcreteClass , null ) ; // create the method body\r String methodBody = \"{ return ($r)\" + ClassGeneratorUtils . MANAGEMENT_HANDLER + \".getUsageParameterSet(profileObject,$1); }\" ; if ( logger . isTraceEnabled ( ) ) logger . trace ( \"Implemented method \" + methodName + \" , body = \" + methodBody ) ; ctMethodCopy . setBody ( methodBody ) ; profileConcreteClass . addMethod ( ctMethodCopy ) ; } catch ( CannotCompileException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates info that indicates if a method from { [CODESPLIT] private void generateProfileConcreteClassInfo ( CtClass profileConcreteClass ) { final ClassPool pool = profileComponent . getClassPool ( ) ; CtClass profileClass = null ; try { profileClass = pool . get ( Profile . class . getName ( ) ) ; } catch ( NotFoundException e ) { throw new SLEEException ( e . getMessage ( ) , e ) ; } ProfileConcreteClassInfo profileConcreteClassInfo = profileComponent . getProfileConcreteClassInfo ( ) ; for ( CtMethod method : profileClass . getDeclaredMethods ( ) ) { for ( CtMethod profileConcreteMethod : profileConcreteClass . getMethods ( ) ) { if ( profileConcreteMethod . getName ( ) . equals ( method . getName ( ) ) && profileConcreteMethod . getSignature ( ) . equals ( method . getSignature ( ) ) ) { // match, save info\r profileConcreteClassInfo . setInvokeInfo ( profileConcreteMethod . getMethodInfo ( ) . getName ( ) , ! profileConcreteMethod . isEmpty ( ) ) ; break ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public ActivityContextInterface getActivityContextInterface ( NullActivity nullActivity ) throws NullPointerException , TransactionRequiredLocalException , UnrecognizedActivityException , FactoryException { if ( nullActivity == null ) throw new NullPointerException ( \"null NullActivity ! huh!!\" ) ; if ( ! ( nullActivity instanceof NullActivityImpl ) ) throw new UnrecognizedActivityException ( \"unrecognized activity\" ) ; NullActivityImpl nullActivityImpl = ( NullActivityImpl ) nullActivity ; ActivityContextHandle ach = new NullActivityContextHandle ( nullActivityImpl . getHandle ( ) ) ; ActivityContext ac = sleeContainer . getActivityContextFactory ( ) . getActivityContext ( ach ) ; if ( ac == null ) { throw new UnrecognizedActivityException ( nullActivity ) ; } return ac . getActivityContextInterface ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find unique entry uses { [CODESPLIT] public < T > T queryUnique ( final SelectQuery query , final ObjectMapper < T > mapper ) { return runner . run ( new TransactionWrapper < T > ( ) { public T perform ( QueryRunner queryRunner ) { return queryRunner . queryUnique ( query , mapper ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve list uses { [CODESPLIT] public < T > List < T > queryList ( final SelectQuery query , final ObjectMapper < T > mapper ) { return runner . run ( new TransactionWrapper < List < T > > ( ) { public List < T > perform ( QueryRunner queryRunner ) { return queryRunner . queryList ( query , mapper ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve set uses { [CODESPLIT] public < T > Set < T > querySet ( final SelectQuery query , final ObjectMapper < T > mapper ) { return runner . run ( new TransactionWrapper < Set < T > > ( ) { public Set < T > perform ( QueryRunner queryRunner ) { return queryRunner . querySet ( query , mapper ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if any result exists for query uses { [CODESPLIT] public boolean queryExistence ( final SelectQuery query ) { return runner . run ( new TransactionWrapper < Boolean > ( ) { public Boolean perform ( QueryRunner queryRunner ) { return queryRunner . queryExistence ( query ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run insert query uses { [CODESPLIT] public long insert ( final InsertQuery query ) { return runner . run ( new TransactionWrapper < Long > ( ) { public Long perform ( QueryRunner queryRunner ) { return queryRunner . insert ( query ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run update query uses { [CODESPLIT] public int update ( final UpdateQuery query ) { return runner . run ( new TransactionWrapper < Integer > ( ) { public Integer perform ( QueryRunner queryRunner ) { return queryRunner . update ( query ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set column to update . Object is automatically translated onto matching JDBC type . [CODESPLIT] public UpdateQuery set ( String fieldName , Object value ) { String updatedFieldName = \"update_\" + fieldName ; values . append ( fieldName ) . append ( \" = :\" ) . append ( updatedFieldName ) . append ( \", \" ) ; query . setArgument ( updatedFieldName , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets value for placeholder defined in query . Placeholder name should not start with <b > : < / b > it is stripped off . Based on passed object type appropriate JDBC type is chosen . [CODESPLIT] public UpdateQuery withArgument ( String argumentName , Object object ) { query . setArgument ( argumentName , object ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets value for placeholder defined in query . Placeholder name should not start with <b > : < / b > it is stripped off . Based on passed object type appropriate JDBC type is chosen . [CODESPLIT] public DeleteQuery withArgument ( String argumentName , Object object ) { query . setArgument ( argumentName , object ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return new PolyJDBC instance . [CODESPLIT] public PolyJDBC build ( ) { TransactionManager manager ; if ( dataSource != null ) { manager = new DataSourceTransactionManager ( dataSource ) ; } else { manager = new ExternalTransactionManager ( connectionProvider ) ; } return new DefaultPolyJDBC ( dialect , schemaName , new ColumnTypeMapper ( customMappings ) , manager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register custom mapping from clazz to SQL type . SqlType should be one of { @link java . sql . Types } . If you need to add some transformations register custom implementation of { @link org . polyjdbc . core . type . TypeWrapper } . [CODESPLIT] public PolyJDBCBuilder withCustomMapping ( Class < ? > clazz , SqlType sqlType ) { this . customMappings . put ( clazz , sqlType ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create <b > ORDER BY< / b > clause for given column can be used multiple times with multiple columns . [CODESPLIT] public SelectQuery orderBy ( String name , Order order ) { if ( orderBy == null ) { orderBy = new StringBuilder ( ORDER_BY_LENGTH ) ; orderBy . append ( \" ORDER BY \" ) ; } orderBy . append ( name ) . append ( \" \" ) . append ( order . getStringCode ( ) ) . append ( \", \" ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets value for placeholder defined in query . Placeholder name should not start with <b > : < / b > it is stripped off . Based on passed object type appropriate JDBC type is chosen . [CODESPLIT] public SelectQuery withArgument ( String argumentName , Object object ) { query . setArgument ( argumentName , object ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert value into column of given name . Object is automatically translated onto matching JDBC type . [CODESPLIT] public InsertQuery value ( String fieldName , Object value ) { valueNames . append ( fieldName ) . append ( \", \" ) ; values . append ( \":\" ) . append ( fieldName ) . append ( \", \" ) ; setArgument ( fieldName , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run specified operations in safe transaction block . [CODESPLIT] public < T > T run ( TransactionWrapper < T > operation ) { QueryRunner runner = null ; try { runner = queryRunnerFactory . create ( ) ; T result = operation . perform ( runner ) ; runner . commit ( ) ; return result ; } catch ( Throwable throwable ) { TheCloser . rollback ( runner ) ; throw new TransactionInterruptedException ( throwable ) ; } finally { TheCloser . close ( runner ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the list of containing resources . Must all be instances of { @link SearchLayer } [CODESPLIT] @ JsonDeserialize ( contentAs = SearchLayer . class ) @ Override public void setWithin ( List < Resource > within ) throws IllegalArgumentException { if ( within . stream ( ) . anyMatch ( r -> ! ( r instanceof SearchLayer ) ) ) { throw new IllegalArgumentException ( \"SearchResult can only be within a SearchLayer.\" ) ; } super . setWithin ( within ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new containing resource . Must be an instance of { @link SearchLayer } [CODESPLIT] @ Override public SearchResult addWithin ( Resource first , Resource ... rest ) throws IllegalArgumentException { if ( ! ( first instanceof SearchLayer ) || Arrays . stream ( rest ) . anyMatch ( r -> ! ( r instanceof SearchLayer ) ) ) { throw new IllegalArgumentException ( \"SearchResult can only be within a SearchLayer.\" ) ; } super . addWithin ( first , rest ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an IIIF Image API compliant region request string [CODESPLIT] @ JsonCreator public static RegionRequest fromString ( String str ) throws ResolvingException { if ( str . equals ( \"full\" ) ) { return new RegionRequest ( ) ; } if ( str . equals ( \"square\" ) ) { return new RegionRequest ( true ) ; } Matcher matcher = PARSE_PAT . matcher ( str ) ; if ( ! matcher . matches ( ) ) { throw new ResolvingException ( \"Bad format: \" + str ) ; } if ( matcher . group ( 1 ) == null ) { return new RegionRequest ( Integer . valueOf ( matcher . group ( 2 ) ) , Integer . valueOf ( matcher . group ( 3 ) ) , Integer . valueOf ( matcher . group ( 4 ) ) , Integer . valueOf ( matcher . group ( 5 ) ) ) ; } else { return new RegionRequest ( new BigDecimal ( matcher . group ( 2 ) ) , new BigDecimal ( matcher . group ( 3 ) ) , new BigDecimal ( matcher . group ( 4 ) ) , new BigDecimal ( matcher . group ( 5 ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the requested region [CODESPLIT] public Rectangle2D getRegion ( ) { if ( isRelative ( ) ) { return new Rectangle2D . Double ( relativeBox . x . doubleValue ( ) , relativeBox . y . doubleValue ( ) , relativeBox . w . doubleValue ( ) , relativeBox . h . doubleValue ( ) ) ; } else { return absoluteBox ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve the region request into an actual region that can be used for cropping the image [CODESPLIT] public Rectangle resolve ( Dimension imageDims ) throws ResolvingException { if ( square ) { if ( imageDims . width > imageDims . height ) { return new Rectangle ( ( imageDims . width - imageDims . height ) / 2 , 0 , imageDims . height , imageDims . height ) ; } else if ( imageDims . height > imageDims . width ) { return new Rectangle ( 0 , ( imageDims . height - imageDims . width ) / 2 , imageDims . width , imageDims . width ) ; } } if ( absoluteBox == null && relativeBox == null ) { return new Rectangle ( 0 , 0 , imageDims . width , imageDims . height ) ; } Rectangle rect ; if ( isRelative ( ) ) { rect = new Rectangle ( ( int ) Math . round ( relativeBox . x . doubleValue ( ) / 100. * imageDims . getWidth ( ) ) , ( int ) Math . round ( relativeBox . y . doubleValue ( ) / 100. * imageDims . getHeight ( ) ) , ( int ) Math . round ( relativeBox . w . doubleValue ( ) / 100. * imageDims . getWidth ( ) ) , ( int ) Math . round ( relativeBox . h . doubleValue ( ) / 100. * imageDims . getHeight ( ) ) ) ; } else { rect = absoluteBox ; } if ( rect . x >= imageDims . width || rect . y >= imageDims . height ) { throw new ResolvingException ( \"X and Y must be smaller than the native width/height\" ) ; } if ( rect . x + rect . width > imageDims . width ) { rect . width = imageDims . width - rect . x ; } if ( rect . y + rect . height > imageDims . height ) { rect . height = imageDims . height - rect . y ; } return rect ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The spec says we have to urlencode values but only characters outside of the US ASCII range and gen - delims from RFC3986 . However our URL library can only encode the full set of gen - delims ( EXCEPT the colon ) and sub - delims which iswhy we have to manually decode the encoded sub - delims ... Great and pragmatic choice for readability more code for us : - ) [CODESPLIT] private static String urlEncode ( String str ) { Set < String > excluded = ImmutableSet . of ( \":\" , \"!\" , \"$\" , \"&\" , \"'\" , \"(\" , \")\" , \"*\" , \"+\" , \",\" , \";\" , \"=\" ) ; String encoded = new Encoded ( str ) . toString ( ) ; for ( String ex : excluded ) { encoded = encoded . replaceAll ( new Encoded ( ex ) . toString ( ) , ex ) ; } return encoded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the canonical of the Image API request . See http : // iiif . io / api / image / 2 . 1 / #canonical - uri - syntax [CODESPLIT] public String getCanonicalForm ( Dimension nativeSize , ImageApiProfile profile , Quality defaultQuality ) throws ResolvingException { Dimension scaleReference = nativeSize ; Rectangle2D canonicalRegion = RegionRequest . fromString ( region . getCanonicalForm ( nativeSize ) ) . getRegion ( ) ; if ( canonicalRegion != null ) { scaleReference = new Dimension ( ( int ) canonicalRegion . getWidth ( ) , ( int ) canonicalRegion . getHeight ( ) ) ; } return String . format ( \"%s%s/%s/%s/%s.%s\" , identifier != null ? urlEncode ( identifier ) + \"/\" : \"\" , region . getCanonicalForm ( nativeSize ) , size . getCanonicalForm ( scaleReference , profile ) , rotation . toString ( ) , quality . equals ( defaultQuality ) ? \"default\" : quality . toString ( ) , format . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get type for on values that are plain URIs by deducing the type from their parent . [CODESPLIT] private String getOnType ( DeserializationContext ctxt ) { // Easiest way: The parser has already constructed an annotation object with a motivation. // This is highly dependendant on the order of keys in the JSON, i.e. if \"on\" is the first key in the annotation // object, this won't work. Object curVal = ctxt . getParser ( ) . getCurrentValue ( ) ; boolean isPaintingAnno = ( curVal != null && curVal instanceof Annotation && ( ( Annotation ) curVal ) . getMotivation ( ) != null && ( ( Annotation ) curVal ) . getMotivation ( ) . equals ( Motivation . PAINTING ) ) ; if ( isPaintingAnno ) { return \"sc:Canvas\" ; } // More reliable way: Walk up the parsing context until we hit a IIIF resource that we can deduce the type from // Usually this shouldn't be more than two levels up JsonStreamContext parent = ctxt . getParser ( ) . getParsingContext ( ) . getParent ( ) ; while ( parent != null && ( parent . getCurrentValue ( ) == null || ! ( parent . getCurrentValue ( ) instanceof Resource ) ) ) { parent = parent . getParent ( ) ; } if ( parent != null ) { Resource parentObj = ( Resource ) parent . getCurrentValue ( ) ; return parentObj . getType ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the completeness ( i . e . empty id and type it type and label id only or complex ) of a IIIF resource . Can be useful for determining how to serialize the resource e . g . often resources with only an id are serialized as a string . [CODESPLIT] public static Completeness getCompleteness ( Object res , Class < ? > type ) { Set < Method > getters = ReflectionUtils . getAllMethods ( type , ReflectionUtils . withModifier ( Modifier . PUBLIC ) , ReflectionUtils . withPrefix ( \"get\" ) ) ; Set < String > gettersWithValues = getters . stream ( ) . filter ( g -> g . getAnnotation ( JsonIgnore . class ) == null ) // Only JSON-serializable fields . filter ( g -> returnsValue ( g , res ) ) . map ( Method :: getName ) . collect ( Collectors . toSet ( ) ) ; boolean hasOnlyTypeAndId = ( gettersWithValues . size ( ) == 2 && Stream . of ( \"getType\" , \"getIdentifier\" ) . allMatch ( gettersWithValues :: contains ) ) ; if ( gettersWithValues . isEmpty ( ) ) { return Completeness . EMPTY ; } else if ( containsOnly ( gettersWithValues , \"getType\" , \"getIdentifier\" ) ) { return Completeness . ID_AND_TYPE ; } else if ( containsOnly ( gettersWithValues , \"getType\" , \"getIdentifier\" , \"getLabels\" ) ) { return Completeness . ID_AND_TYPE_AND_LABEL ; } else if ( containsOnly ( gettersWithValues , \"getIdentifier\" ) ) { return Completeness . ID_ONLY ; } else { return Completeness . COMPLEX ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the viewing hints for this resource . [CODESPLIT] public void setViewingHints ( List < ViewingHint > viewingHints ) throws IllegalArgumentException { for ( ViewingHint hint : viewingHints ) { boolean supportsHint = ( hint . getType ( ) == ViewingHint . Type . OTHER || this . getSupportedViewingHintTypes ( ) . contains ( hint . getType ( ) ) ) ; if ( ! supportsHint ) { throw new IllegalArgumentException ( String . format ( \"Resources of type '%s' do not support the '%s' viewing hint.\" , this . getType ( ) , hint . toString ( ) ) ) ; } } this . viewingHints = viewingHints ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add one or more viewing hints for this resource . [CODESPLIT] public Resource addViewingHint ( ViewingHint first , ViewingHint ... rest ) throws IllegalArgumentException { List < ViewingHint > hints = this . viewingHints ; if ( hints == null ) { hints = new ArrayList <> ( ) ; } hints . addAll ( Lists . asList ( first , rest ) ) ; this . setViewingHints ( hints ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the renderings . All renderings must have both a profile and a format . [CODESPLIT] public void setRenderings ( List < OtherContent > renderings ) throws IllegalArgumentException { renderings . forEach ( this :: verifyRendering ) ; this . renderings = renderings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add one or more renderings . All renderings must have both a profile and a format . [CODESPLIT] public Resource addRendering ( OtherContent first , OtherContent ... rest ) { if ( renderings == null ) { this . renderings = new ArrayList <> ( ) ; } List < OtherContent > renderingsToAdd = Lists . asList ( first , rest ) ; renderingsToAdd . forEach ( this :: verifyRendering ) ; this . renderings . addAll ( renderingsToAdd ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge multiple profiles into one . Useful for image servers that want to consolidate the limits given in a info . json . [CODESPLIT] public static ImageApiProfile merge ( List < Profile > profiles ) { return profiles . stream ( ) . filter ( ImageApiProfile . class :: isInstance ) . map ( ImageApiProfile . class :: cast ) . reduce ( new ImageApiProfile ( ) , ImageApiProfile :: merge ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge two profiles . [CODESPLIT] public ImageApiProfile merge ( ImageApiProfile other ) { ImageApiProfile merged = new ImageApiProfile ( ) ; streamNotNull ( this . features ) . forEach ( merged :: addFeature ) ; streamNotNull ( other . features ) . forEach ( merged :: addFeature ) ; streamNotNull ( this . formats ) . forEach ( merged :: addFormat ) ; streamNotNull ( other . formats ) . forEach ( merged :: addFormat ) ; streamNotNull ( this . qualities ) . forEach ( merged :: addQuality ) ; streamNotNull ( other . qualities ) . forEach ( merged :: addQuality ) ; if ( this . maxWidth != null && other . maxWidth == null ) { merged . maxWidth = this . maxWidth ; } else if ( this . maxWidth == null && other . maxWidth != null ) { merged . maxWidth = other . maxWidth ; } else if ( this . maxWidth != null ) { merged . maxWidth = Math . min ( this . maxWidth , other . maxWidth ) ; } if ( this . maxHeight != null && other . maxHeight == null ) { merged . maxHeight = this . maxHeight ; } else if ( this . maxHeight == null && other . maxHeight != null ) { merged . maxHeight = other . maxHeight ; } else if ( this . maxHeight != null ) { merged . maxHeight = Math . min ( this . maxHeight , other . maxHeight ) ; } if ( this . maxArea != null && other . maxArea == null ) { merged . maxArea = this . maxArea ; } else if ( this . maxArea == null && other . maxArea != null ) { merged . maxArea = other . maxArea ; } else if ( this . maxArea != null ) { merged . maxArea = Math . min ( this . maxArea , other . maxArea ) ; } return merged ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a rotation request from an IIIF Image API compliant rotation string . [CODESPLIT] @ JsonCreator public static RotationRequest fromString ( String str ) throws ResolvingException { Matcher matcher = PATTERN . matcher ( str ) ; if ( ! matcher . matches ( ) ) { throw new ResolvingException ( \"Bad format: \" + str ) ; } return new RotationRequest ( new BigDecimal ( matcher . group ( 2 ) ) , ! ( matcher . group ( 1 ) == null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to create Converter from lambda * [CODESPLIT] private < T > Converter < String , T > fromString ( Function < String , ? extends T > fun ) { return new StdConverter < String , T > ( ) { @ Override public T convert ( String value ) { return fun . apply ( value ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds one or more member resources . Must be either instances of { @link Manifest } or { @link Collection } . All { @link Collection } members must have at least one { @link de . digitalcollections . iiif . model . enums . ViewingHint } . [CODESPLIT] public Collection addMember ( Resource first , Resource ... rest ) { if ( this . members == null ) { this . members = new ArrayList <> ( ) ; checkMember ( first ) ; stream ( rest ) . forEach ( this :: checkMember ) ; } this . members . addAll ( Lists . asList ( first , rest ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds one or more member resources . Must be either instances of { @link Range } or { @link Canvas } . All members must have an identifier and a label . [CODESPLIT] public Range addMember ( Resource first , Resource ... rest ) throws IllegalArgumentException { if ( this . members == null ) { this . members = new ArrayList <> ( ) ; } List < Resource > membersToAdd = Lists . asList ( first , rest ) ; membersToAdd . forEach ( this :: checkMember ) ; this . members . addAll ( membersToAdd ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * see http : // iiif . io / api / presentation / 2 . 1 / #language - of - property - values example : { description : { @value : Here is a longer description of the object @language : en }} [CODESPLIT] public String getFirstValue ( Locale locale ) { List < String > values = getValues ( locale ) ; if ( values == null ) { return getFirstValue ( ) ; } else { return values . get ( 0 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an IIIF Image API compliant size request string [CODESPLIT] @ JsonCreator public static SizeRequest fromString ( String str ) throws ResolvingException { if ( str . equals ( \"full\" ) ) { return new SizeRequest ( ) ; } if ( str . equals ( \"max\" ) ) { return new SizeRequest ( true ) ; } Matcher matcher = PARSE_PAT . matcher ( str ) ; if ( ! matcher . matches ( ) ) { throw new ResolvingException ( \"Bad format: \" + str ) ; } if ( matcher . group ( 1 ) != null ) { if ( matcher . group ( 1 ) . equals ( \"!\" ) ) { return new SizeRequest ( Integer . valueOf ( matcher . group ( 2 ) ) , Integer . valueOf ( matcher . group ( 3 ) ) , true ) ; } else if ( matcher . group ( 1 ) . equals ( \"pct:\" ) ) { return new SizeRequest ( new BigDecimal ( matcher . group ( 4 ) ) ) ; } } Integer width = null ; Integer height = null ; if ( matcher . group ( 2 ) != null ) { width = Integer . parseInt ( matcher . group ( 2 ) ) ; } if ( matcher . group ( 3 ) != null ) { height = Integer . parseInt ( matcher . group ( 3 ) ) ; } return new SizeRequest ( width , height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the canonical form of this request . @see <a href = http : // iiif . io / api / image / 2 . 1 / #canonical - uri - syntax > IIIF Image API specification< / a > [CODESPLIT] public String getCanonicalForm ( Dimension nativeSize , ImageApiProfile profile ) throws ResolvingException { Dimension resolved = this . resolve ( nativeSize , profile ) ; // \"w,\" requests are already canonical double nativeRatio = nativeSize . getWidth ( ) / nativeSize . getHeight ( ) ; double resolvedRatio = resolved . getWidth ( ) / resolved . getHeight ( ) ; if ( resolved . equals ( nativeSize ) ) { return \"full\" ; } else if ( this . width != null && this . height == null ) { return this . toString ( ) ; } else if ( Math . floor ( resolvedRatio * nativeSize . getHeight ( ) ) == nativeSize . getWidth ( ) || Math . ceil ( resolvedRatio * nativeSize . getHeight ( ) ) == nativeSize . getWidth ( ) ) { return String . format ( \"%d,\" , resolved . width ) ; } else { return String . format ( \"%d,%d\" , resolved . width , resolved . height ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve the request to dimensions that can be used for scaling based on the native size of the image region and the available profile . [CODESPLIT] public Dimension resolve ( Dimension nativeSize , List < Dimension > availableSizes , ImageApiProfile profile ) throws ResolvingException { double aspect = ( double ) nativeSize . width / ( double ) nativeSize . height ; // \"max\" if ( max ) { // By default, identical to the largest available size or the native size if no sizes were specified Dimension dim = availableSizes . stream ( ) // Avoid upscaling when dealing with region requests . filter ( s -> s . width <= nativeSize . width && s . height <= nativeSize . height ) // Select the largest available size . max ( Comparator . comparing ( Dimension :: getWidth ) . thenComparing ( Dimension :: getHeight ) ) // Otherwise, fall back to the native size . orElse ( new Dimension ( nativeSize . width , nativeSize . height ) ) ; if ( profile != null && profile . maxWidth != null ) { if ( dim . width > profile . maxWidth ) { // If maximum width is set, width cannot exceed it dim . width = profile . maxWidth ; dim . height = ( int ) ( profile . maxWidth / aspect ) ; } int maxHeight = profile . maxHeight != null ? profile . maxHeight : profile . maxWidth ; if ( dim . height > maxHeight ) { // Adjust height if it exceeds maximum height dim . height = maxHeight ; dim . width = ( int ) ( aspect * dim . height ) ; } } if ( profile != null && profile . maxArea != null ) { // Fit width and height into the maximum available area, preserving the aspect ratio long currentArea = ( long ) dim . width * ( long ) dim . height ; if ( currentArea > profile . maxArea ) { dim . width = ( int ) Math . sqrt ( aspect * ( double ) profile . maxArea ) ; dim . height = ( int ) ( dim . width / aspect ) ; if ( dim . width <= 0 || dim . height <= 0 ) { throw new ResolvingException ( String . format ( \"Cannot fit image with dimensions %dx%d into maximum area of %d pixels.\" , nativeSize . width , nativeSize . height , profile . maxArea ) ) ; } } } return dim ; } Dimension out ; if ( percentage != null || bestFit ) { // \"pct:\" double ratio ; if ( percentage != null ) { ratio = percentage . doubleValue ( ) / 100.0 ; } else { ratio = Math . min ( width / nativeSize . getWidth ( ) , height / nativeSize . getHeight ( ) ) ; } out = new Dimension ( ( int ) ( ratio * nativeSize . width ) , ( int ) ( ratio * nativeSize . height ) ) ; } else if ( width == null && height == null ) { // \"full\" out = nativeSize ; } else { out = new Dimension ( ) ; if ( width != null ) { out . width = width ; } if ( height != null ) { out . height = height ; } if ( width == null ) { // \",h\" out . width = ( int ) ( out . height * aspect ) ; } if ( height == null ) { // \"w,\" out . height = ( int ) ( out . width / aspect ) ; } } Integer maxHeight = profile . maxHeight != null ? profile . maxHeight : profile . maxWidth ; if ( profile . maxWidth != null && out . width > profile . maxWidth ) { throw new ResolvingException ( String . format ( \"Requested width (%d) exceeds maximum width (%d) as specified in the profile.\" , out . width , profile . maxWidth ) ) ; } else if ( maxHeight != null && out . height > maxHeight ) { throw new ResolvingException ( String . format ( \"Requested height (%d) exceeds maximum height (%d) as specified in the profile.\" , out . height , maxHeight ) ) ; } else if ( profile . maxArea != null && out . height * out . width > profile . maxArea ) { throw new ResolvingException ( String . format ( \"Requested area (%d*%d = %d) exceeds maximum area (%d) as specified in the profile\" , out . width , out . height , out . width * out . height , profile . maxArea ) ) ; } else if ( ( profile . features == null || ! profile . features . contains ( ImageApiProfile . Feature . SIZE_ABOVE_FULL ) ) && ( out . width > nativeSize . width || out . height > nativeSize . height ) ) { throw new ResolvingException ( String . format ( \"Requested dimensions (%dx%d) exceed native dimensions (%dx%d), profile states that upscaling is not supported.\" , out . width , out . height , nativeSize . width , nativeSize . height ) ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like { @link #resolve ( Dimension ImageApiProfile ) } but can be used with a { @link Rectangle } e . g . as returned from { @link RegionRequest#resolve ( Dimension ) } . [CODESPLIT] public Dimension resolve ( Rectangle region , ImageApiProfile profile ) throws ResolvingException { return resolve ( new Dimension ( region . width , region . height ) , profile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call once [CODESPLIT] public void initAndroidDevices ( boolean shouldKeepAdbAlive ) throws AndroidDeviceException { //        DdmPreferences.setLogLevel(LogLevel.VERBOSE.getStringValue()); DdmPreferences . setInitialThreadUpdate ( true ) ; DdmPreferences . setInitialHeapUpdate ( true ) ; this . initializeAdbConnection ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the AndroidDebugBridge and registers the DefaultHardwareDeviceManager with the AndroidDebugBridge device change listener . [CODESPLIT] protected void initializeAdbConnection ( ) { // Get a device bridge instance. Initialize, create and restart. try { AndroidDebugBridge . init ( true ) ; } catch ( IllegalStateException e ) { // When we keep the adb connection alive the AndroidDebugBridge may // have been already // initialized at this point and it generates an exception. Do not // print it. if ( ! shouldKeepAdbAlive ) { logger . error ( \"The IllegalStateException is not a show \" + \"stopper. It has been handled. This is just debug spew. Please proceed.\" , e ) ; throw new NestedException ( \"ADB init failed\" , e ) ; } } bridge = AndroidDebugBridge . getBridge ( ) ; if ( bridge == null ) { bridge = AndroidDebugBridge . createBridge ( AndroidSdk . adb ( ) . getAbsolutePath ( ) , false ) ; } long timeout = System . currentTimeMillis ( ) + 60000 ; while ( ! bridge . hasInitialDeviceList ( ) && System . currentTimeMillis ( ) < timeout ) { try { Thread . sleep ( 50 ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } // Add the existing devices to the list of devices we are tracking. IDevice [ ] devices = bridge . getDevices ( ) ; logger . info ( \"initialDeviceList size {}\" , devices . length ) ; for ( int i = 0 ; i < devices . length ; i ++ ) { logger . info ( \"devices state: {},{} \" , devices [ i ] . getName ( ) , devices [ i ] . getState ( ) ) ; connectedDevices . put ( devices [ i ] , new DefaultHardwareDevice ( devices [ i ] ) ) ; } bridge . addDeviceChangeListener ( new DeviceChangeListener ( connectedDevices ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether this exception contains an exception of the given type : either it is of the given class itself or it contains a nested cause of the given type . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public boolean contains ( Class exType ) { if ( exType == null ) { return false ; } if ( exType . isInstance ( this ) ) { return true ; } Throwable cause = getCause ( ) ; if ( cause == this ) { return false ; } if ( cause instanceof NestedException ) { return ( ( NestedException ) cause ) . contains ( exType ) ; } else { while ( cause != null ) { if ( exType . isInstance ( cause ) ) { return true ; } if ( cause . getCause ( ) == cause ) { break ; } cause = cause . getCause ( ) ; } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ugly implementation [CODESPLIT] @ Override public boolean isScreenOn ( ) { CommandLine command = adbCommand ( \"shell\" , \"dumpsys power\" ) ; try { String powerState = ShellCommand . exec ( command ) . toLowerCase ( ) ; if ( powerState . indexOf ( \"mscreenon=true\" ) > - 1 || powerState . indexOf ( \"mpowerstate=0\" ) == - 1 ) { return true ; } } catch ( ShellCommandException e ) { log . info ( \"Could not get property init.svc.bootanim\" , e ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get current android page s dump file [CODESPLIT] public String getDump ( ) { pushAutomator2Device ( ) ; runtest ( ) ; String path = pullDump2PC ( ) ; String xml = \"\" ; try { FileInputStream fileInputStream = new FileInputStream ( path ) ; @ SuppressWarnings ( \"resource\" ) BufferedReader in = new BufferedReader ( new InputStreamReader ( fileInputStream ) ) ; StringBuffer buffer = new StringBuffer ( ) ; String line = \"\" ; while ( ( line = in . readLine ( ) ) != null ) { buffer . append ( line ) ; } xml = buffer . toString ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return xml ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "try to click GPS Popup window [CODESPLIT] public boolean handlePopBox ( String deviceBrand ) { pushHandleGps2Device ( ) ; CommandLine exeCommand = null ; if ( deviceBrand . contains ( \"HTC\" ) ) { exeCommand = adbCommand ( \"shell\" , \"uiautomator\" , \"runtest\" , \"/data/local/tmp/handlePopBox.jar\" , \"-c\" , \"com.test.device.gps.HTCGPSTest\" ) ; } else if ( deviceBrand . contains ( \"Meizu\" ) ) { exeCommand = adbCommand ( \"shell\" , \"uiautomator\" , \"runtest\" , \"/data/local/tmp/handlePopBox.jar\" , \"-c\" , \"com.test.device.gps.MeizuGPSTest\" ) ; } String output = executeCommandQuietly ( exeCommand ) ; log . debug ( \"run test {}\" , output ) ; try { // give it a second to recover from the activity start Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } return output . contains ( \"OK\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push handlePopBox . jar to android tmp folder [CODESPLIT] private boolean pushHandleGps2Device ( ) { InputStream io = AbstractDevice . class . getResourceAsStream ( \"handlePopBox.jar\" ) ; File dest = new File ( FileUtils . getTempDirectory ( ) , \"handlePopBox.jar\" ) ; try { FileUtils . copyInputStreamToFile ( io , dest ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } CommandLine pushcommand = adbCommand ( \"push \" , dest . getAbsolutePath ( ) , \"/data/local/tmp/\" ) ; String outputPush = executeCommandQuietly ( pushcommand ) ; log . debug ( \"Push automator.jar to device {}\" , outputPush ) ; try { // give it a second to recover from the activity start Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } return outputPush . contains ( \"KB/s\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clean file dump . xml qian . xml uidump . xml in tmp folder [CODESPLIT] public void cleanTemp ( ) { CommandLine dumpcommand = adbCommand ( \"shell\" , \"rm\" , \"-r\" , \"/data/local/tmp/local/tmp/dump.xml\" ) ; executeCommandQuietly ( dumpcommand ) ; try { // give it a second to recover from the activity start Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } CommandLine qiancommand = adbCommand ( \"shell\" , \"rm\" , \"-r\" , \"/data/local/tmp/local/tmp/qian.xml\" ) ; String output = executeCommandQuietly ( qiancommand ) ; log . debug ( \"Delete file qian.xml: {}\" , output ) ; try { // give it a second to recover from the activity start Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } CommandLine command = adbCommand ( \"shell\" , \"rm\" , \"-r\" , \"/data/local/tmp/uidump.xml\" ) ; executeCommandQuietly ( command ) ; try { // give it a second to recover from the activity start Thread . sleep ( 1000 ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pull dump file from android device to pc [CODESPLIT] public String pullDump2PC ( ) { String serial = device . getSerialNumber ( ) ; File dest = new File ( FileUtils . getTempDirectory ( ) , serial + \".xml\" ) ; String path = dest . getPath ( ) ; log . debug ( \"pull dump file to pc's path {}\" , path ) ; CommandLine commandpull = adbCommand ( \"pull\" , \"/data/local/tmp/local/tmp/qian.xml\" , path ) ; String out = executeCommandQuietly ( commandpull ) ; log . debug ( \"pull dump file to pc's result {}\" , out ) ; return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use adb to send a keyevent to the device . <p > Full list of keys available here : http : // developer . android . com / reference / android / view / KeyEvent . html [CODESPLIT] public void inputKeyevent ( int value ) { executeCommandQuietly ( adbCommand ( \"shell\" , \"input\" , \"keyevent\" , \"\" + value ) ) ; // need to wait a beat for the UI to respond try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e ) { log . warn ( \"\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get crash log from AUT [CODESPLIT] public String getCrashLog ( ) { String crashLogFileName = null ; File crashLogFile = new File ( getExternalStoragePath ( ) , crashLogFileName ) ; // the \"test\" utility doesn't exist on all devices so we'll check the // output of ls. CommandLine directoryListCommand = adbCommand ( \"shell\" , \"ls\" , crashLogFile . getParentFile ( ) . getAbsolutePath ( ) ) ; String directoryList = executeCommandQuietly ( directoryListCommand ) ; if ( directoryList . contains ( crashLogFileName ) ) { return executeCommandQuietly ( adbCommand ( \"shell\" , \"cat\" , crashLogFile . getAbsolutePath ( ) ) ) ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all occurrences of the regular expression with the replacement . The replacement string can contain $1 $2 etc . referring to matched groups in the regular expression . [CODESPLIT] public TextEditor replaceAll ( String regex , String replacement ) { if ( text . length ( ) > 0 ) { final String r = replacement ; Pattern p = Pattern . compile ( regex , Pattern . MULTILINE ) ; Matcher m = p . matcher ( text ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { m . appendReplacement ( sb , r ) ; } m . appendTail ( sb ) ; text = new StringBuilder ( sb . toString ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as replaceAll ( String String ) but does not interpret $1 $2 etc . in the replacement string . [CODESPLIT] public TextEditor replaceAllLiteral ( String regex , final String replacement ) { return replaceAll ( Pattern . compile ( regex , Pattern . MULTILINE ) , new Replacement ( ) { public String replacement ( Matcher m ) { return replacement ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all occurrences of the Pattern . The Replacement object s replace () method is called on each match and it provides a replacement which is placed literally ( i . e . without interpreting $1 $2 etc . ) [CODESPLIT] public TextEditor replaceAll ( Pattern pattern , Replacement replacement ) { Matcher m = pattern . matcher ( text ) ; int lastIndex = 0 ; StringBuilder sb = new StringBuilder ( ) ; while ( m . find ( ) ) { sb . append ( text . subSequence ( lastIndex , m . start ( ) ) ) ; sb . append ( replacement . replacement ( m ) ) ; lastIndex = m . end ( ) ; } sb . append ( text . subSequence ( lastIndex , text . length ( ) ) ) ; text = sb ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert tabs to spaces . [CODESPLIT] public TextEditor detabify ( final int tabWidth ) { replaceAll ( Pattern . compile ( \"(.*?)\\\\t\" ) , new Replacement ( ) { public String replacement ( Matcher m ) { String lineSoFar = m . group ( 1 ) ; int width = lineSoFar . length ( ) ; StringBuilder replacement = new StringBuilder ( lineSoFar ) ; do { replacement . append ( ' ' ) ; ++ width ; } while ( width % tabWidth != 0 ) ; return replacement . toString ( ) ; } } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Introduce a number of spaces at the start of each line . [CODESPLIT] public TextEditor indent ( int spaces ) { StringBuilder sb = new StringBuilder ( spaces ) ; for ( int i = 0 ; i < spaces ; i ++ ) { sb . append ( ' ' ) ; } return replaceAll ( \"^\" , sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse HTML tags returning a Collection of HTMLToken objects . [CODESPLIT] public Collection < HTMLToken > tokenizeHTML ( ) { List < HTMLToken > tokens = new ArrayList < HTMLToken > ( ) ; String nestedTags = nestedTagsRegex ( 6 ) ; Pattern p = Pattern . compile ( \"\" + \"(?s:<!(--.*?--\\\\s*)+>)\" + \"|\" + \"(?s:<\\\\?.*?\\\\?>)\" + \"|\" + nestedTags + \"\" , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( text ) ; int lastPos = 0 ; while ( m . find ( ) ) { if ( lastPos < m . start ( ) ) { tokens . add ( HTMLToken . text ( text . substring ( lastPos , m . start ( ) ) ) ) ; } tokens . add ( HTMLToken . tag ( text . substring ( m . start ( ) , m . end ( ) ) ) ) ; lastPos = m . end ( ) ; } if ( lastPos < text . length ( ) ) { tokens . add ( HTMLToken . text ( text . substring ( lastPos , text . length ( ) ) ) ) ; } return tokens ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the conversion from Markdown to HTML . [CODESPLIT] public String markdown ( String txt ) { if ( txt == null ) { txt = \"\" ; } TextEditor text = new TextEditor ( txt ) ; // Standardize line endings: text . replaceAll ( \"\\\\r\\\\n\" , \"\\n\" ) ; // DOS to Unix text . replaceAll ( \"\\\\r\" , \"\\n\" ) ; // Mac to Unix text . replaceAll ( \"^[ \\\\t]+$\" , \"\" ) ; // Make sure $text ends with a couple of newlines: text . append ( \"\\n\\n\" ) ; text . detabify ( ) ; text . deleteAll ( \"^[ ]+$\" ) ; hashHTMLBlocks ( text ) ; stripLinkDefinitions ( text ) ; text = runBlockGamut ( text ) ; unEscapeSpecialChars ( text ) ; text . append ( \"\\n\" ) ; return text . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "escape special characters [CODESPLIT] private TextEditor escapeSpecialCharsWithinTagAttributes ( TextEditor text ) { Collection < HTMLToken > tokens = text . tokenizeHTML ( ) ; TextEditor newText = new TextEditor ( \"\" ) ; for ( HTMLToken token : tokens ) { String value = token . getText ( ) ; if ( token . isTag ( ) ) { value = value . replaceAll ( \"\\\\\\\\\" , CHAR_PROTECTOR . encode ( \"\\\\\" ) ) ; value = value . replaceAll ( \"`\" , CHAR_PROTECTOR . encode ( \"`\" ) ) ; value = value . replaceAll ( \"\\\\*\" , CHAR_PROTECTOR . encode ( \"*\" ) ) ; value = value . replaceAll ( \"_\" , CHAR_PROTECTOR . encode ( \"_\" ) ) ; } newText . append ( value ) ; } return newText ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////// getProxyConnection ( ... ) ////////////// [CODESPLIT] public Connection getProxyConnection ( long timeoutMs ) throws SQLException { int attempt = 1 ; ConnHolder connHolder = null ; SQLException sqlException = null ; long startNanoTime = System . nanoTime ( ) ; while ( connHolder == null ) { try { connHolder = getConnHolder ( timeoutMs ) ; } catch ( ViburDBCPException e ) { // thrown only if we can retry the operation, see getConnHolder(...) sqlException = chainSQLException ( e . unwrapSQLException ( ) , sqlException ) ; if ( attempt ++ > dataSource . getAcquireRetryAttempts ( ) ) { // check the max retries limit throw sqlException ; } if ( timeoutMs > 0 ) { // check the time limit if applicable timeoutMs = NANOSECONDS . toMillis ( connectionTimeoutInNanos - ( System . nanoTime ( ) - startNanoTime ) ) - dataSource . getAcquireRetryDelayInMs ( ) ; // calculates the remaining timeout if ( timeoutMs <= 0 ) { throw sqlException ; } } try { MILLISECONDS . sleep ( dataSource . getAcquireRetryDelayInMs ( ) ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; throw chainSQLException ( new SQLException ( ie ) , sqlException ) ; } } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Taking rawConnection {}\" , connHolder . rawConnection ( ) ) ; } Connection proxy = newProxyConnection ( connHolder , this , dataSource ) ; if ( dataSource . isPoolEnableConnectionTracking ( ) ) { connHolder . setProxyConnection ( proxy ) ; } return proxy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to take a { @code ConnHolder } object from the underlying object pool . If successful never returns { @code null } . [CODESPLIT] private ConnHolder getConnHolder ( long timeoutMs ) throws SQLException , ViburDBCPException { Hook . GetConnection [ ] onGet = ( ( ConnHooksAccessor ) dataSource . getConnHooks ( ) ) . onGet ( ) ; ConnHolder connHolder = null ; long [ ] waitedNanos = NO_WAIT ; SQLException sqlException = null ; ViburDBCPException viburException = null ; try { if ( onGet . length > 0 ) { waitedNanos = new long [ 1 ] ; connHolder = timeoutMs > 0 ? poolService . tryTake ( timeoutMs , MILLISECONDS , waitedNanos ) : poolService . take ( waitedNanos ) ; } else { connHolder = timeoutMs > 0 ? poolService . tryTake ( timeoutMs , MILLISECONDS ) : poolService . take ( ) ; } if ( connHolder == null ) { // we were *not* able to obtain a connection from the pool sqlException = createSQLException ( onGet . length > 0 ? waitedNanos [ 0 ] : MILLISECONDS . toNanos ( timeoutMs ) ) ; } } catch ( ViburDBCPException e ) { // thrown (indirectly) by the ConnectionFactory.create() methods viburException = e ; sqlException = e . unwrapSQLException ( ) ; // currently all such errors are treated as recoverable, i.e., can be retried } finally { Connection rawConnection = connHolder != null ? connHolder . rawConnection ( ) : null ; try { for ( Hook . GetConnection hook : onGet ) { hook . on ( rawConnection , waitedNanos [ 0 ] ) ; } } catch ( SQLException e ) { sqlException = chainSQLException ( sqlException , e ) ; } } if ( viburException != null ) { throw viburException ; // a recoverable error } if ( sqlException != null ) { throw sqlException ; // a non-recoverable error } return connHolder ; // never null if we reach this point }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "//////////// restore ( ... ) ////////////// [CODESPLIT] public void restore ( ConnHolder connHolder , boolean valid , SQLException [ ] exceptions ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Restoring rawConnection {}\" , connHolder . rawConnection ( ) ) ; } boolean reusable = valid && exceptions . length == 0 && connHolder . version ( ) == connectionFactory . version ( ) ; poolService . restore ( connHolder , reusable ) ; processSQLExceptions ( connHolder , exceptions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes SQL exceptions that have occurred on the given JDBC Connection ( wrapped in a { @code ConnHolder } ) . [CODESPLIT] private void processSQLExceptions ( ConnHolder connHolder , SQLException [ ] exceptions ) { int connVersion = connHolder . version ( ) ; SQLException criticalException = getCriticalSQLException ( exceptions ) ; if ( criticalException != null && connectionFactory . compareAndSetVersion ( connVersion , connVersion + 1 ) ) { int destroyed = poolService . drainCreated ( ) ; // destroys all connections in the pool logger . error ( \"Critical SQLState {} occurred, destroyed {} connections from pool {}, current connection version is {}.\" , criticalException . getSQLState ( ) , destroyed , getPoolName ( dataSource ) , connectionFactory . version ( ) , criticalException ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<b > NOTE : < / b > the pool name can be set only once ; pool renaming is not supported . [CODESPLIT] public void setName ( String name ) { if ( name == null || ( name = name . trim ( ) ) . length ( ) == 0 ) { logger . error ( \"Invalid pool name {}\" , name ) ; return ; } if ( ! defaultName . equals ( this . name ) || defaultName . equals ( name ) ) { logger . error ( \"Pool name is already set or duplicated, existing name = {}, incoming name = {}\" , this . name , name ) ; return ; } this . name = name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method will be called when an operation invoked on a JDBC object throws an SQLException . It will accumulate a list of all non - transient SQL exceptions . [CODESPLIT] final void addException ( SQLException exception ) { if ( ! ( exception instanceof SQLTimeoutException ) && ! ( exception instanceof SQLTransactionRollbackException ) ) { getOrInit ( ) . offer ( exception ) ; // SQLExceptions from the above two sub-types are not stored } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of all SQL exceptions collected by { [CODESPLIT] final SQLException [ ] getExceptions ( ) { Queue < SQLException > ex = exceptions ; if ( ex == null ) { return NO_EXCEPTIONS ; } return ex . toArray ( NO_EXCEPTIONS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new EvictionListener for the CLHM . It is worth noting that this EvictionListener is called in the context of the thread that has executed an insert ( putIfAbsent ) operation which has increased the CLHM size above its maxSize - in which case the CLHM evicts its LRU entry . [CODESPLIT] private static EvictionListener < StatementMethod , StatementHolder > getListener ( ) { return new EvictionListener < StatementMethod , StatementHolder > ( ) { @ Override public void onEviction ( StatementMethod statementMethod , StatementHolder statementHolder ) { if ( statementHolder . state ( ) . getAndSet ( EVICTED ) == AVAILABLE ) { quietClose ( statementHolder . rawStatement ( ) ) ; } if ( logger . isTraceEnabled ( ) ) { logger . trace ( \"Evicted {}\" , statementHolder . rawStatement ( ) ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes this ClhmStatementCache and removes all entries from it . [CODESPLIT] @ Override public void close ( ) { if ( closed . getAndSet ( true ) ) { return ; } for ( Map . Entry < StatementMethod , StatementHolder > entry : statementCache . entrySet ( ) ) { StatementHolder value = entry . getValue ( ) ; statementCache . remove ( entry . getKey ( ) , value ) ; quietClose ( value . rawStatement ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See { [CODESPLIT] public TakenConnection [ ] getTakenConnections ( ) { ConnHolder [ ] takenConns = getTaken ( new ConnHolder [ config . getPoolMaxSize ( ) ] ) ; if ( takenConns . length == 0 ) { return NO_TAKEN_CONNECTIONS ; } return Arrays . copyOf ( takenConns , takenConns . length , TakenConnection [ ] . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public void start ( ) throws ViburDBCPException { try { doStart ( ) ; logger . info ( \"Started {}\" , this ) ; } catch ( IllegalStateException e ) { throw new ViburDBCPException ( e ) ; } catch ( IllegalArgumentException | NullPointerException | ViburDBCPException e ) { logger . error ( \"Unable to start {} due to:\" , this , e ) ; terminate ( ) ; throw e instanceof ViburDBCPException ? e : new ViburDBCPException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <i > a possibly< / i > cached StatementHolder object for the given proxied Connection object and the invoked on it prepare ... Method with the given args . [CODESPLIT] private StatementHolder getCachedStatement ( Method method , Object [ ] args ) throws SQLException { if ( statementCache != null ) { return statementCache . take ( new StatementMethod ( getTarget ( ) , this , method , args ) ) ; } return getUncachedStatement ( method , args , ( String ) args [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////// The StatementCreator implementation : //////// [CODESPLIT] @ Override public PreparedStatement newStatement ( Method method , Object [ ] args ) throws SQLException { String methodName = method . getName ( ) ; if ( methodName != \"prepareStatement\" && methodName != \"prepareCall\" ) { throw new ViburDBCPException ( \"Unexpected method passed to newStatement() \" + method ) ; } return ( PreparedStatement ) targetInvoke ( method , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////// The StatementProceedingPoint implementation : //////// [CODESPLIT] @ Override public Object on ( Statement proxy , Method method , Object [ ] args , String sqlQuery , List < Object [ ] > sqlQueryParams , StatementProceedingPoint proceed ) throws SQLException { if ( ++ hookIdx < executionHooks . length ) { // invoke the next statement execution hook, if any\r return executionHooks [ hookIdx ] . on ( proxy , method , args , sqlQuery , sqlQueryParams , this ) ; } return doProcessExecute ( proxy , method , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles all unrestricted method invocations that we can process before passing through the { @link #restrictedAccessEntry } . This method will be overridden in the { @code AbstractInvocationHandler } subclasses and will be the place to implement the specific to these subclasses logic for unrestricted method invocations handling . When the invoked { @code method } is not an unrestricted method the default implementation returns { @link #NO_RESULT } to indicate this . [CODESPLIT] Object unrestrictedInvoke ( T proxy , Method method , Object [ ] args ) throws SQLException { String methodName = method . getName ( ) ; if ( methodName == \"equals\" ) { // comparing with == as the Method names are interned Strings\r return proxy == args [ 0 ] ; } if ( methodName == \"hashCode\" ) { return System . identityHashCode ( proxy ) ; } if ( methodName == \"toString\" ) { return \"Vibur proxy for: \" + target ; } // getClass(), notify(), notifyAll(), and wait() method calls are not intercepted by the dynamic proxies\r if ( methodName == \"unwrap\" ) { @ SuppressWarnings ( \"unchecked\" ) Class < T > iface = ( Class < T > ) args [ 0 ] ; return unwrap ( iface ) ; } if ( methodName == \"isWrapperFor\" ) { return isWrapperFor ( ( Class < ? > ) args [ 0 ] ) ; } return NO_RESULT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles all restricted method invocations that occur after ( and if ) we have passed through the { @link #restrictedAccessEntry } . This method will be overridden in the { @code AbstractInvocationHandler } subclasses and will be the place to implement the specific to these subclasses logic for restricted method invocations handling . The default implementation simply forwards the call to the original method of the proxied object . [CODESPLIT] Object restrictedInvoke ( T proxy , Method method , Object [ ] args ) throws SQLException { return targetInvoke ( method , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public static void setDefaultValues ( Connection rawConnection , ViburConfig config ) throws SQLException { if ( config . getDefaultAutoCommit ( ) != null ) { rawConnection . setAutoCommit ( config . getDefaultAutoCommit ( ) ) ; } if ( config . getDefaultReadOnly ( ) != null ) { rawConnection . setReadOnly ( config . getDefaultReadOnly ( ) ) ; } if ( config . getDefaultTransactionIsolationIntValue ( ) != null ) { // noinspection MagicConstant - the int value is checked/ set during Vibur config validation rawConnection . setTransactionIsolation ( config . getDefaultTransactionIsolationIntValue ( ) ) ; } if ( config . getDefaultCatalog ( ) != null ) { rawConnection . setCatalog ( config . getDefaultCatalog ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates / initializes the given { @code rawConnection } via executing the given { @code sqlQuery } . [CODESPLIT] public static boolean validateOrInitialize ( Connection rawConnection , String sqlQuery , ViburConfig config ) { if ( sqlQuery == null ) { return true ; } try { if ( sqlQuery . equals ( IS_VALID_QUERY ) ) { return rawConnection . isValid ( config . getValidateTimeoutInSeconds ( ) ) ; } executeSqlQuery ( rawConnection , sqlQuery , config ) ; return true ; } catch ( SQLException e ) { logger . debug ( \"Couldn't validate/ initialize rawConnection {}\" , rawConnection , e ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public static SQLException chainSQLException ( SQLException main , SQLException next ) { if ( main == null ) { return next ; } main . setNextException ( next ) ; return main ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the extended pool name formatted as : <blockquote > { @code poolName@hashCode ( currentlyTakenConns / remainingCreatedConns / poolMaxSize / poolState / threadInterruptedStatus ) } < / blockquote > For example { @code p1@2db7a79b ( 1 / 1 / 10 / w / n ) } . [CODESPLIT] public static String getPoolName ( ViburConfig config ) { BasePool pool = config . getPool ( ) ; boolean initialState = pool . isTerminated ( ) ; String result = config . getName ( ) + ' ' + toHexString ( config . hashCode ( ) ) + ' ' + pool . taken ( ) + ' ' + pool . remainingCreated ( ) + ' ' + pool . maxSize ( ) + ' ' + ( ! initialState ? ' ' : ' ' ) // poolState: w == working, t == terminated\r + ' ' + ( Thread . currentThread ( ) . isInterrupted ( ) ? ' ' : ' ' ) + ' ' ; if ( initialState == pool . isTerminated ( ) ) { // make sure the pool state has not changed in the meantime\r return result ; } return getPoolName ( config ) ; // this is one level of recursion only, pool state changes only once\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all garbage collected values with their keys from the map . Since we don t know how much the ReferenceQueue . poll () operation costs we should call it only in the add () method . [CODESPLIT] private void processQueue ( ) { WeakElement wv = null ; while ( ( wv = ( WeakElement ) this . queue . poll ( ) ) != null ) { super . remove ( wv ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the parent barbershop type in the supplied set if any . [CODESPLIT] private String findParentFqcn ( TypeElement typeElement , Set < String > parents ) { TypeMirror type ; while ( true ) { type = typeElement . getSuperclass ( ) ; if ( type . getKind ( ) == TypeKind . NONE ) { return null ; } typeElement = ( TypeElement ) ( ( DeclaredType ) type ) . asElement ( ) ; if ( parents . contains ( typeElement . toString ( ) ) ) { String packageName = getPackageName ( typeElement ) ; return packageName + \".\" + getClassName ( typeElement , packageName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches for $$Barbershop class for the given instance cached for efficiency . [CODESPLIT] private static IBarbershop < Object > findBarbershopForClass ( Class < ? > cls ) { IBarbershop < Object > barbershop = BARBERSHOPS . get ( cls ) ; if ( barbershop != null ) { if ( debug ) Log . d ( TAG , \"HIT: Cached in barbershop map.\" ) ; return barbershop ; } String clsName = cls . getName ( ) ; if ( clsName . startsWith ( ANDROID_PREFIX ) || clsName . startsWith ( JAVA_PREFIX ) ) { if ( debug ) { Log . d ( TAG , \"MISS: Reached framework class. Abandoning search.\" ) ; } return NO_OP ; } //noinspection TryWithIdenticalCatches try { Class < ? > barbershopClass = Class . forName ( clsName + SUFFIX ) ; //noinspection unchecked barbershop = ( IBarbershop < Object > ) barbershopClass . newInstance ( ) ; if ( debug ) { Log . d ( TAG , \"HIT: Class loaded barbershop class.\" ) ; } } catch ( ClassNotFoundException e ) { if ( debug ) { Log . d ( TAG , \"Not found. Trying superclass \" + cls . getSuperclass ( ) . getName ( ) ) ; } barbershop = findBarbershopForClass ( cls . getSuperclass ( ) ) ; } catch ( InstantiationException e ) { Log . e ( TAG , e . getMessage ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( TAG , e . getMessage ( ) ) ; } BARBERSHOPS . put ( cls , barbershop ) ; return barbershop ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the class code and writes to a new source file . [CODESPLIT] void writeToFiler ( Filer filer ) throws IOException { ClassName targetClassName = ClassName . get ( classPackage , targetClass ) ; TypeSpec . Builder barberShop = TypeSpec . classBuilder ( className ) . addModifiers ( Modifier . PUBLIC ) . addTypeVariable ( TypeVariableName . get ( \"T\" , targetClassName ) ) . addMethod ( generateStyleMethod ( ) ) . addMethod ( generateCheckParentMethod ( ) ) ; if ( parentBarbershop == null ) { barberShop . addSuperinterface ( ParameterizedTypeName . get ( ClassName . get ( Barber . IBarbershop . class ) , TypeVariableName . get ( \"T\" ) ) ) ; barberShop . addField ( FieldSpec . builder ( WeakHashSet . class , \"lastStyledTargets\" , Modifier . PROTECTED ) . initializer ( \"new $T()\" , WeakHashSet . class ) . build ( ) ) ; } else { barberShop . superclass ( ParameterizedTypeName . get ( ClassName . bestGuess ( parentBarbershop ) , TypeVariableName . get ( \"T\" ) ) ) ; } JavaFile javaFile = JavaFile . builder ( classPackage , barberShop . build ( ) ) . build ( ) ; javaFile . writeTo ( filer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This generates the actual style () method implementation for the $$Barbershop class [CODESPLIT] private MethodSpec generateStyleMethod ( ) { MethodSpec . Builder builder = MethodSpec . methodBuilder ( \"style\" ) . addAnnotation ( Override . class ) . addModifiers ( Modifier . PUBLIC ) . returns ( void . class ) . addParameter ( TypeVariableName . get ( \"T\" ) , \"target\" , Modifier . FINAL ) . addParameter ( AttributeSet . class , \"set\" , Modifier . FINAL ) . addParameter ( int [ ] . class , \"attrs\" , Modifier . FINAL ) . addParameter ( int . class , \"defStyleAttr\" , Modifier . FINAL ) . addParameter ( int . class , \"defStyleRes\" , Modifier . FINAL ) ; if ( parentBarbershop != null ) { builder . beginControlFlow ( \"if (!super.hasStyled(target))\" ) . addStatement ( \"super.style(target, set, attrs, defStyleAttr, defStyleRes)\" ) . addStatement ( \"return\" ) . endControlFlow ( ) ; } // Update our latest target builder . addStatement ( \"this.lastStyledTargets.add(target)\" ) ; // Don't do anything if there's no AttributeSet instance builder . beginControlFlow ( \"if (set == null)\" ) . addStatement ( \"return\" ) . endControlFlow ( ) ; if ( ! styleableBindings . isEmpty ( ) ) { if ( hasDefaults ) { builder . addStatement ( \"$T res = target.getContext().getResources()\" , Resources . class ) ; } // Proceed with obtaining the TypedArray if we got here builder . addStatement ( \"$T a = target.getContext().obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes)\" , TypedArray . class ) ; builder . addCode ( \"// Retrieve custom attributes\\n\" ) ; for ( StyleableBinding binding : styleableBindings . values ( ) ) { if ( binding . kind == RES_ID && binding . hasDefaultValue ( ) && ! binding . isRequired ) { // No overhead in resource retrieval for these, so no need to wrap in a hasValue check builder . addStatement ( generateSetterStatement ( binding ) , binding . name , binding . getFormattedStatement ( \"a.\" ) ) ; continue ; } // Wrap the styling with if-statement to check if there's a value first, this way we can // keep existing default values if there isn't one and don't overwrite them. builder . beginControlFlow ( \"if (a.hasValue($L))\" , binding . id ) ; builder . addStatement ( generateSetterStatement ( binding ) , binding . name , binding . getFormattedStatement ( \"a.\" ) ) ; if ( binding . isRequired ) { builder . nextControlFlow ( \"else\" ) ; builder . addStatement ( \"throw new $T(\\\"Missing required attribute \\'$L\\' while styling \\'$L\\'\\\")\" , IllegalStateException . class , binding . name , targetClass ) ; } else if ( binding . hasDefaultValue ( ) ) { builder . nextControlFlow ( \"else\" ) ; if ( binding . kind != FRACTION && binding . kind != DIMEN && ( \"float\" . equals ( binding . type ) || \"java.lang.Float\" . equals ( binding . type ) ) ) { // Getting a float from resources is nasty builder . addStatement ( generateSetterStatement ( binding ) , binding . name , \"Barber.resolveFloatResource(res, \" + binding . defaultValue + \")\" ) ; } else if ( \"android.graphics.drawable.Drawable\" . equals ( binding . type ) ) { // Compatibility using ResourcesCompat.getDrawable(...) builder . addStatement ( generateSetterStatement ( binding ) , binding . name , \"android.support.v4.content.res.ResourcesCompat.getDrawable(res, \" + binding . defaultValue + \", target.getContext().getTheme())\" ) ; } else { builder . addStatement ( generateSetterStatement ( binding ) , binding . name , generateResourceStatement ( binding , \"res.\" , true ) ) ; } } builder . endControlFlow ( ) ; } builder . addStatement ( \"a.recycle()\" ) ; } if ( ! androidAttrBindings . isEmpty ( ) ) { builder . addCode ( \"// Retrieve android attr values\\n\" ) ; for ( AndroidAttrBinding binding : androidAttrBindings . values ( ) ) { builder . addStatement ( generateSetterStatement ( binding ) , binding . name , binding . getFormattedStatement ( \"set.\" ) ) ; } } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the last param if there are multiple used for when we want to adapt a resource getter to one used with { [CODESPLIT] private static String chompLastParam ( String input ) { int lastCommaIndex = input . lastIndexOf ( ' ' ) ; if ( lastCommaIndex == - 1 ) { return input ; } else { return input . substring ( 0 , lastCommaIndex ) + \")\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write BitVector01Divider to OutputStream . This method doesn t care about r0 and r1 . Caller must write these bvs . [CODESPLIT] public void writeBitVector01Divider ( BitVector01Divider divider ) throws IOException { dos . writeBoolean ( divider . isFirst ( ) ) ; dos . writeBoolean ( divider . isZeroCounting ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append bits from bit string . The bit string is the array of string that contains 8 characters which is 0 or 1 . [CODESPLIT] public static void appendBitStrings ( BitVector bv , String [ ] bs ) { for ( String s : bs ) { if ( s . length ( ) != 8 ) throw new RuntimeException ( \"The length of bit string must be 8  while \" + s . length ( ) ) ; for ( char c : s . toCharArray ( ) ) { if ( c == ' ' ) bv . append0 ( ) ; else if ( c == ' ' ) bv . append1 ( ) ; else throw new RuntimeException ( \"invalid char '\" + c + \"' for bit string.\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ [CODESPLIT] private static void enumLetters ( org . trie4j . Node node , String prefix , List < String > letters ) { org . trie4j . Node [ ] children = node . getChildren ( ) ; if ( children == null ) return ; for ( org . trie4j . Node child : children ) { String text = prefix + new String ( child . getLetters ( ) ) ; if ( child . isTerminate ( ) ) letters . add ( text ) ; enumLetters ( child , text , letters ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read data from InputStream . This method doesn t care about r0 and r1 . Caller must load these bvs and set through setR0 and setR1 . [CODESPLIT] public void readFrom ( InputStream is ) throws IOException { DataInputStream dis = new DataInputStream ( is ) ; first = dis . readBoolean ( ) ; zeroCounting = dis . readBoolean ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an HTTP GET request to the given path and map the object under the given key in the JSON of the response to the Java { @link Class } of type { @link TYPE } . [CODESPLIT] protected static < TYPE > TYPE get ( String path , String key , Class < TYPE > expectedClass ) { Gson deserializer = new GsonBuilder ( ) . create ( ) ; JsonObject jsonObject = getJsonObject ( path , deserializer ) . get ( 0 ) ; return deserializer . fromJson ( jsonObject . get ( key ) , expectedClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an HTTP GET request to the given path and map the array under the given key in the JSON of the response to a { @link List } of type { @link TYPE } . [CODESPLIT] protected static < TYPE > List < TYPE > getList ( String path , String key , Class < TYPE > expectedClass ) { Gson deserializer = new GsonBuilder ( ) . create ( ) ; List < TYPE > toReturn = new ArrayList <> ( ) ; List < JsonObject > jsonObjectList = getJsonObject ( path , deserializer ) ; for ( JsonObject jsonObject : jsonObjectList ) { for ( JsonElement jsonElement : jsonObject . get ( key ) . getAsJsonArray ( ) ) { toReturn . add ( deserializer . fromJson ( jsonElement , expectedClass ) ) ; } } return toReturn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize the object to the type expected . [CODESPLIT] private static List < JsonObject > getJsonObject ( String path , Gson deserializer ) { String url = String . format ( \"%s/%s\" , ENDPOINT , path ) ; Request request = new Request . Builder ( ) . url ( url ) . build ( ) ; Response response ; try { response = CLIENT . newCall ( request ) . execute ( ) ; ArrayList < JsonObject > objectList = new ArrayList <> ( ) ; String linkHeader = response . headers ( ) . get ( \"Link\" ) ; if ( linkHeader == null || linkHeader . isEmpty ( ) || path . contains ( \"page=\" ) ) { objectList . add ( deserializer . fromJson ( response . body ( ) . string ( ) , JsonObject . class ) ) ; return objectList ; } else { int numberOfPages = 0 ; String [ ] linkStrings = linkHeader . split ( DELIM_LINK ) ; List < String [ ] > paramList = new ArrayList <> ( ) ; for ( String link : linkStrings ) { paramList . add ( link . split ( DELIM_LINK_PARAM ) ) ; } for ( String [ ] params : paramList ) { if ( params [ 1 ] . contains ( \"last\" ) ) { Matcher matcher = Pattern . compile ( \"page=[0-9]+\" ) . matcher ( params [ 0 ] ) ; numberOfPages = ( matcher . find ( ) ) ? Integer . parseInt ( matcher . group ( ) . substring ( 5 ) ) : 0 ; } } objectList . add ( deserializer . fromJson ( response . body ( ) . string ( ) , JsonObject . class ) ) ; if ( ! url . contains ( \"?\" ) ) { url += \"?\" ; } for ( int i = 1 ; i <= numberOfPages ; i ++ ) { request = new Request . Builder ( ) . url ( url + \"&page=\" + i ) . build ( ) ; response = CLIENT . newCall ( request ) . execute ( ) ; objectList . add ( deserializer . fromJson ( response . body ( ) . string ( ) , JsonObject . class ) ) ; } return objectList ; } } catch ( IOException e ) { throw new HttpRequestFailedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of objects with a filter if there is anything that matches the filters . [CODESPLIT] protected static < TYPE > List < TYPE > getList ( String path , String key , Class < TYPE > expectedClass , List < String > filters ) { StringBuilder tempPath = new StringBuilder ( path ) ; tempPath . append ( \"?\" ) ; for ( String filter : filters ) { tempPath . append ( filter ) . append ( ' ' ) ; } return getList ( tempPath . substring ( 0 , tempPath . length ( ) - 1 ) , key , expectedClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all the { @link Card } that match a certain filter . @param filters List of filters supported by the web API @return List of all matching { @link Card } s . [CODESPLIT] public static List < Card > getAllCards ( List < String > filters ) { return getList ( RESOURCE_PATH , \"cards\" , Card . class , filters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { [CODESPLIT] public static MtgSet getSet ( String setCode ) { String path = String . format ( \"%s/%s/\" , RESOURCE_PATH , setCode ) ; MtgSet returnSet = get ( path , \"set\" , MtgSet . class ) ; if ( returnSet != null ) { returnSet . setCards ( CardAPI . getAllCards ( new LinkedList <> ( Collections . singletonList ( \"set=\" + setCode ) ) ) ) ; } return returnSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The method that will generate a booster for the selected { [CODESPLIT] public static List < Card > getBooster ( String setCode ) { String path = String . format ( \"%s/%s/%s/\" , RESOURCE_PATH , setCode , \"booster\" ) ; return getList ( path , \"cards\" , Card . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a list of { [CODESPLIT] public static List < MtgSet > getAllSets ( List < String > filters ) { return getList ( RESOURCE_PATH , \"sets\" , MtgSet . class , filters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a list of { [CODESPLIT] public static List < MtgSet > getAllSetsWithCards ( ) { List < MtgSet > returnList = getList ( RESOURCE_PATH , \"sets\" , MtgSet . class ) ; for ( MtgSet set : returnList ) { set . setCards ( CardAPI . getAllCards ( new LinkedList <> ( Collections . singletonList ( \"set=\" + set . getCode ( ) ) ) ) ) ; } return returnList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When running cucumber tests in parallel Klov reporter should be attached only once in order to avoid duplicate builds on klov server . [CODESPLIT] private static synchronized void setKlovReport ( ) { if ( extentReports == null ) { //Extent reports object not found. call setExtentReport() first return ; } ExtentProperties extentProperties = ExtentProperties . INSTANCE ; //if reporter is not null that means it is already attached if ( klovReporter != null ) { //Already attached, attaching it again will create a new build/klov report return ; } if ( extentProperties . getKlovServerUrl ( ) != null ) { String hostname = extentProperties . getMongodbHost ( ) ; int port = extentProperties . getMongodbPort ( ) ; String database = extentProperties . getMongodbDatabase ( ) ; String username = extentProperties . getMongodbUsername ( ) ; String password = extentProperties . getMongodbPassword ( ) ; try { //Create a new KlovReporter object klovReporter = new KlovReporter ( ) ; if ( username != null && password != null ) { MongoClientURI uri = new MongoClientURI ( \"mongodb://\" + username + \":\" + password + \"@\" + hostname + \":\" + port + \"/?authSource=\" + database ) ; klovReporter . initMongoDbConnection ( uri ) ; } else { klovReporter . initMongoDbConnection ( hostname , port ) ; } klovReporter . setProjectName ( extentProperties . getKlovProjectName ( ) ) ; klovReporter . setReportName ( extentProperties . getKlovReportName ( ) ) ; klovReporter . setKlovUrl ( extentProperties . getKlovServerUrl ( ) ) ; extentReports . attachReporter ( klovReporter ) ; } catch ( Exception ex ) { klovReporter = null ; throw new IllegalArgumentException ( \"Error setting up Klov Reporter\" , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the screenshot from the given path with the given title to the current step [CODESPLIT] public static void addScreenCaptureFromPath ( String imagePath , String title ) throws IOException { getCurrentStep ( ) . addScreenCaptureFromPath ( imagePath , title ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the system information with the given key value pair [CODESPLIT] public static void setSystemInfo ( String key , String value ) { if ( systemInfoKeyMap . isEmpty ( ) || ! systemInfoKeyMap . containsKey ( key ) ) { systemInfoKeyMap . put ( key , false ) ; } if ( systemInfoKeyMap . get ( key ) ) { return ; } getExtentReport ( ) . setSystemInfo ( key , value ) ; systemInfoKeyMap . put ( key , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a level to equivalent syslog severity . Only levels for printing methods i . e DEBUG WARN INFO and ERROR are converted . [CODESPLIT] public int getSeverityForEvent ( Object eventObject ) { if ( eventObject instanceof ILoggingEvent ) { ILoggingEvent event = ( ILoggingEvent ) eventObject ; return LevelToSyslogSeverity . convert ( event ) ; } else { return SyslogIF . LEVEL_INFO ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a primitive list based on an input list and a property path [CODESPLIT] public static FloatList toFloatList ( Collection < ? > inputList , String propertyPath ) { if ( inputList . size ( ) == 0 ) { return new FloatList ( 0 ) ; } FloatList outputList = new FloatList ( inputList . size ( ) ) ; if ( propertyPath . contains ( \".\" ) || propertyPath . contains ( \"[\" ) ) { String [ ] properties = StringScanner . splitByDelimiters ( propertyPath , \".[]\" ) ; for ( Object o : inputList ) { outputList . add ( BeanUtils . getPropertyFloat ( o , properties ) ) ; } } else { Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( inputList . iterator ( ) . next ( ) ) ; FieldAccess fieldAccess = fields . get ( propertyPath ) ; for ( Object o : inputList ) { outputList . add ( fieldAccess . getFloat ( o ) ) ; } } return outputList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new value to the list but don t employ a wrapper . [CODESPLIT] public FloatList add ( float integer ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value in the list . [CODESPLIT] @ Override public Float set ( int index , Float element ) { float oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value in the list . [CODESPLIT] public float idx ( int index , float element ) { float oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value in the list . [CODESPLIT] public float atIndex ( int index , float element ) { float oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set in a new value no wrapper [CODESPLIT] public float setFloat ( int index , float element ) { float oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This would be a good opportunity to reintroduce dynamic invoke [CODESPLIT] public double reduceBy ( Object function , String name ) { return Flt . reduceBy ( values , end , function , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs collections from the results . [CODESPLIT] public static void collectFrom ( List < Selector > selectors , Collection < ? > results ) { if ( results . size ( ) == 0 ) { return ; } Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( results . iterator ( ) . next ( ) ) ; collectFrom ( selectors , results , fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs collections from the results . [CODESPLIT] public static void collectFrom ( List < Selector > selectors , Collection < ? > results , Map < String , FieldAccess > fields ) { for ( Selector s : selectors ) { s . handleStart ( results ) ; } int index = 0 ; for ( Object item : results ) { for ( Selector s : selectors ) { s . handleRow ( index , null , item , fields ) ; } index ++ ; } for ( Selector s : selectors ) { s . handleComplete ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the actual selection from the results . [CODESPLIT] public static < ITEM > List < Map < String , Object > > selectFrom ( List < Selector > selectors , Collection < ITEM > results ) { if ( results . size ( ) == 0 ) { return Collections . EMPTY_LIST ; } Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( results . iterator ( ) . next ( ) ) ; return selectFrom ( selectors , results , fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the actual selection from the results . [CODESPLIT] public static < ITEM > List < Map < String , Object > > selectFrom ( List < Selector > selectors , Collection < ITEM > results , Map < String , FieldAccess > fields ) { List < Map < String , Object > > rows = new ArrayList <> ( results . size ( ) ) ; for ( Selector s : selectors ) { s . handleStart ( results ) ; } int index = 0 ; for ( ITEM item : results ) { Map < String , Object > row = new LinkedHashMap <> ( ) ; for ( Selector s : selectors ) { s . handleRow ( index , row , item , fields ) ; } index ++ ; rows . add ( row ) ; } for ( Selector s : selectors ) { s . handleComplete ( rows ) ; } return rows ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows you to select a property or property path . [CODESPLIT] public static Selector select ( final String propName ) { return new Selector ( propName , propName ) { @ Override public void handleRow ( int index , Map < String , Object > row , Object item , Map < String , FieldAccess > fields ) { getPropertyValueAndPutIntoRow ( row , item , fields ) ; } @ Override public void handleStart ( Collection < ? > results ) { } @ Override public void handleComplete ( List < Map < String , Object > > rows ) { } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects but allows having a different alias for the output . [CODESPLIT] public static Selector selectAs ( final String propName , final String alias , final Function transform ) { return new Selector ( propName , alias ) { @ Override public void handleRow ( int index , Map < String , Object > row , Object item , Map < String , FieldAccess > fields ) { if ( ! path && fields != null ) { row . put ( this . name , transform . apply ( fields . get ( this . name ) . getValue ( item ) ) ) ; } else { row . put ( alias , transform . apply ( BeanUtils . atIndex ( item , propName ) ) ) ; } } @ Override public void handleStart ( Collection < ? > results ) { } @ Override public void handleComplete ( List < Map < String , Object > > rows ) { } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects but allows having a different alias for the output . \\ * [CODESPLIT] public static Selector selectAsTemplate ( final String alias , final String template , final Template transform ) { return new Selector ( alias , alias ) { @ Override public void handleRow ( int index , Map < String , Object > row , Object item , Map < String , FieldAccess > fields ) { if ( ! path && fields != null ) { row . put ( this . name , transform . replace ( template , item ) ) ; } else { row . put ( alias , transform . replace ( template , item ) ) ; } } @ Override public void handleStart ( Collection < ? > results ) { } @ Override public void handleComplete ( List < Map < String , Object > > rows ) { } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will flush to secondary storage if needed . This is used mostly by REMOTE_DB at the moment . [CODESPLIT] protected void flushReadsIfNeeded ( ) throws InterruptedException { long now = timer . time ( ) ; /* Every 250 ms flush the read queue. */ if ( now - lastReadFlushTime > flushQueueInterval && readList . size ( ) > 0 ) { if ( ! loadQueue . offer ( new ArrayList <> ( readList ) ) ) { logger . warn ( \"MySQL LOAD QUEUE IS FULL\" , loadQueue . size ( ) ) ; } else { readList . clear ( ) ; } lastReadFlushTime = now ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will flush to secondary storage if needed . This is used mostly by REMOTE_DB at the moment . [CODESPLIT] protected void flushWritesIfNeeded ( ) throws InterruptedException { long now = timer . time ( ) ; /* Every 30 seconds  flush the write queue. */ if ( now - lastWriteFlushTime > dataStoreConfig . dbWriteFlushQueueIntervalMS ( ) ) { if ( outputMap . size ( ) > 0 ) { if ( ! writeQueue . offer ( new LinkedHashMap ( outputMap ) ) ) { logger . warn ( \"MySQL STORE QUEUE IS FULL\" , writeQueue . size ( ) ) ; } else { outputMap . clear ( ) ; } lastWriteFlushTime = now ; } if ( removeList . size ( ) > 0 ) { if ( ! writeQueue . offer ( new ArrayList <> ( removeList ) ) ) { logger . warn ( \"MySQL LOAD QUEUE IS FULL\" , writeQueue . size ( ) ) ; } else { removeList . clear ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an annotation data list . [CODESPLIT] public static List < AnnotationData > extractValidationAnnotationData ( Annotation [ ] annotations , Set < String > allowedPackages ) { List < AnnotationData > annotationsList = new ArrayList <> ( ) ; for ( Annotation annotation : annotations ) { AnnotationData annotationData = new AnnotationData ( annotation , allowedPackages ) ; if ( annotationData . isAllowed ( ) ) { annotationsList . add ( annotationData ) ; } } return annotationsList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract all annotation for a given property . Searches current class and if none found searches super class for annotation . We do this because the class could be proxied with AOP . [CODESPLIT] private static Annotation [ ] extractAllAnnotationsForProperty ( Class < ? > clazz , String propertyName , boolean useRead ) { try { Annotation [ ] annotations = findPropertyAnnotations ( clazz , propertyName , useRead ) ; /* In the land of dynamic proxied AOP classes,\n             * this class could be a proxy. This seems like a bug\n             * waiting to happen. So far it has worked... */ if ( annotations . length == 0 ) { annotations = findPropertyAnnotations ( clazz . getSuperclass ( ) , propertyName , useRead ) ; } return annotations ; } catch ( Exception ex ) { return Exceptions . handle ( Annotation [ ] . class , sputs ( \"Unable to extract annotation for property\" , propertyName , \" of class \" , clazz , \"  useRead \" , useRead ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find annotation given a particular property name and clazz . This figures out the writeMethod for the property and uses the write method to look up the annotation . [CODESPLIT] private static Annotation [ ] findPropertyAnnotations ( Class < ? > clazz , String propertyName , boolean useRead ) throws IntrospectionException { PropertyDescriptor propertyDescriptor = getPropertyDescriptor ( clazz , propertyName ) ; if ( propertyDescriptor == null ) { return new Annotation [ ] { } ; } Method accessMethod = null ; if ( useRead ) { accessMethod = propertyDescriptor . getReadMethod ( ) ; } else { accessMethod = propertyDescriptor . getWriteMethod ( ) ; } if ( accessMethod != null ) { Annotation [ ] annotations = accessMethod . getAnnotations ( ) ; return annotations ; } else { return new Annotation [ ] { } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This needs to be refactored and put into Reflection or something . [CODESPLIT] private static PropertyDescriptor doGetPropertyDescriptor ( final Class < ? > type , final String propertyName ) { try { BeanInfo beanInfo = Introspector . getBeanInfo ( type ) ; PropertyDescriptor [ ] propertyDescriptors = beanInfo . getPropertyDescriptors ( ) ; for ( PropertyDescriptor pd : propertyDescriptors ) { if ( pd . getName ( ) . equals ( propertyName ) ) { return pd ; } } Class < ? > superclass = type . getSuperclass ( ) ; if ( superclass != null ) { return doGetPropertyDescriptor ( superclass , propertyName ) ; } return null ; } catch ( Exception ex ) { throw new RuntimeException ( \"Unable to get property \" + propertyName + \" for class \" + type , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Everything that has a cache you need to hold on to should use this so they can all be stuffed into application context of web - app or ear if you use Java EE . [CODESPLIT] public static Object contextToHold ( ) { return Lists . list ( Reflection . contextToHold ( ) , Annotations . contextToHold ( ) , Logging . contextToHold ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup an object and supply a default value . [CODESPLIT] private Object doLookup ( String objectExpression , Object defaultValue , boolean searchChildren ) { if ( Str . isEmpty ( objectExpression ) ) { return defaultValue ; } char firstChar = Str . idx ( objectExpression , 0 ) ; char secondChar = Str . idx ( objectExpression , 1 ) ; char lastChar = Str . idx ( objectExpression , - 1 ) ; boolean escape = false ; switch ( firstChar ) { case ' ' : if ( lastChar == ' ' ) { objectExpression = slc ( objectExpression , 2 , - 1 ) ; } else { objectExpression = slc ( objectExpression , 1 ) ; } break ; case ' ' : if ( secondChar == ' ' && lastChar == ' ' ) { char thirdChar = Str . idx ( objectExpression , 2 ) ; if ( thirdChar == ' ' ) { escape = true ; objectExpression = slc ( objectExpression , 3 , - 3 ) ; } else { objectExpression = slc ( objectExpression , 2 , - 2 ) ; } } else { if ( lastChar == ' ' ) { return jsonParser . parse ( objectExpression ) ; } else { escape = true ; objectExpression = slc ( objectExpression , 1 ) ; } } break ; case ' ' : return jsonParser . parse ( objectExpression ) ; case ' ' : if ( secondChar == ' ' ) { String newExp = slc ( objectExpression , 2 ) ; return parent . doLookup ( newExp , newExp , false ) ; } } Object value ; lastChar = Str . idx ( objectExpression , - 1 ) ; if ( lastChar == ' ' ) { value = handleFunction ( objectExpression , searchChildren ) ; } else { value = findProperty ( objectExpression , searchChildren ) ; value = value == null ? defaultValue : value ; } if ( ! escape ) { return value ; } else { return StandardFunctions . escapeXml ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * THIS IS THE DELEGATE FOR SETTING DATA . For instance set ( SetRequest request ) and setSource ( SetRequest request ) will both call this method instead of processing the set themself therefore providing a common and consistent way to handle the set - SFF [CODESPLIT] protected void _set ( DataStoreSource source , SetRequest request ) { switch ( source ) { case MEMORY : _setMemory ( request ) ; break ; case LOCAL_DB : _setLocal ( request , true ) ; break ; case REMOTE_DB : _setRemote ( request , true ) ; break ; case TRANSACTION_LOG : _setTransactionLog ( request ) ; break ; case LOCAL_STORES : _setMemory ( request ) ; _setLocal ( request , true ) ; break ; case ALL : _setTransactionLog ( request ) ; _setReplication ( request ) ; _setMemory ( request ) ; _setLocal ( request , false ) ; _setRemote ( request , false ) ; break ; case REPLICATION : _setMemory ( request ) ; _setLocal ( request , false ) ; _setRemote ( request , false ) ; break ; default : queueInvalidSource ( request ) ; logger . error ( \"Master Data Store:: Unable to handle Set Source\" , request ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an item from a list into a class using the classes constructor . [CODESPLIT] public static < T > T fromList ( List < ? > argList , Class < T > clazz ) { return mapper . fromList ( argList , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an item from a list into a class using the classes constructor . [CODESPLIT] public static < T > T fromList ( boolean respectIgnore , String view , FieldsAccessor fieldsAccessor , List < ? > argList , Class < T > clazz , Set < String > ignoreSet ) { return new MapperComplex ( fieldsAccessor , ignoreSet , view , respectIgnore ) . fromList ( argList , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an item from a list into a class using the classes constructor . [CODESPLIT] public static < T > T fromList ( FieldsAccessor fieldsAccessor , List < ? > argList , Class < T > clazz ) { return new MapperComplex ( fieldsAccessor , null , null , false ) . fromList ( argList , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "From map . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T fromMap ( Map < String , Object > map , Class < T > clazz ) { return mapper . fromMap ( map , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fromMap converts a map into a java object . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T fromMap ( Map < String , Object > map , Class < T > clazz , String ... excludeProperties ) { Set < String > ignoreProps = excludeProperties . length > 0 ? Sets . set ( excludeProperties ) : null ; return new MapperComplex ( FieldAccessMode . FIELD_THEN_PROPERTY . create ( false ) , ignoreProps , null , true ) . fromMap ( map , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fromMap converts a map into a java object [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T fromMap ( boolean respectIgnore , String view , FieldsAccessor fieldsAccessor , Map < String , Object > map , Class < T > cls , Set < String > ignoreSet ) { Mapper mapper = new MapperComplex ( ignoreSet , view , respectIgnore ) ; return mapper . fromMap ( map , cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an object from a value map . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T fromValueMap ( boolean respectIgnore , String view , final FieldsAccessor fieldsAccessor , final Map < String , Value > valueMap , final Class < T > cls , Set < String > ignoreSet ) { Mapper mapper = new MapperComplex ( fieldsAccessor , ignoreSet , view , respectIgnore ) ; return mapper . fromValueMap ( valueMap , cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Basic toMap to create an object into a map . [CODESPLIT] public static Map < String , Object > toMap ( final Object object , final String ... ignore ) { return toMap ( object , Sets . set ( ignore ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This could be refactored to use core . TypeType class and it would run faster . Converts an object into a map [CODESPLIT] public static Map < String , Object > toMap ( final Object object , Set < String > ignore ) { return new MapperComplex ( ignore ) . toMap ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts a list of maps to objects . I always forget that this exists . I need to remember . [CODESPLIT] public static < T > List < T > convertListOfMapsToObjects ( boolean respectIgnore , String view , FieldsAccessor fieldsAccessor , Class < T > componentType , List < Map > list , Set < String > ignoreProperties ) { return new MapperComplex ( fieldsAccessor , ignoreProperties , view , respectIgnore ) . convertListOfMapsToObjects ( list , componentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a list of maps from a list of class instances . [CODESPLIT] public static List < Map < String , Object > > toListOfMaps ( Collection < ? > collection ) { return mapper . toListOfMaps ( collection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the values from the annotation . We use reflection to turn the annotation into a simple HashMap of values . [CODESPLIT] Map < String , Object > doGetValues ( Annotation annotation ) { /* Holds the value map. */ Map < String , Object > values = new HashMap < String , Object > ( ) ; /* Get the declared staticMethodMap from the actual annotation. */ Method [ ] methods = annotation . annotationType ( ) . getDeclaredMethods ( ) ; final Object [ ] noargs = ( Object [ ] ) null ; /* Iterate through declared staticMethodMap and extract values\n         * by invoking decalared staticMethodMap if they are no arg staticMethodMap.\n         */ for ( Method method : methods ) { /* If it is a no arg method assume it is an annoation value. */ if ( method . getParameterTypes ( ) . length == 0 ) { try { /* Get the value. */ Object value = method . invoke ( annotation , noargs ) ; if ( value instanceof Enum ) { Enum enumVal = ( Enum ) value ; value = enumVal . name ( ) ; } values . put ( method . getName ( ) , value ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the validator by looking it up in the ObjectRegistry and then populating it with values from the meta - data list . [CODESPLIT] protected CompositeValidator createValidator ( List < ValidatorMetaData > validationMetaDataList ) { /*\n         * A field (property) can be associated with many validators so we use a\n         * CompositeValidator to hold all of the validators associated with this\n         * validator.\n         */ CompositeValidator compositeValidator = new CompositeValidator ( ) ; // hold // all // of // the // validators // associated // with // the // field. /*\n         * Lookup the list of validators for the current field and initialize\n         * them with validation meta-data properties.\n         */ List < FieldValidator > validatorsList = lookupTheListOfValidatorsAndInitializeThemWithMetaDataProperties ( validationMetaDataList ) ; compositeValidator . setValidatorList ( validatorsList ) ; return compositeValidator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup the list of validators for the current field and initialize them with validation meta - data properties . [CODESPLIT] private List < FieldValidator > lookupTheListOfValidatorsAndInitializeThemWithMetaDataProperties ( List < ValidatorMetaData > validationMetaDataList ) { List < FieldValidator > validatorsList = new ArrayList <> ( ) ; /*\n         * Look up the crank validators and then apply the properties from the\n         * validationMetaData to them.\n         */ for ( ValidatorMetaData validationMetaData : validationMetaDataList ) { /* Look up the FieldValidator. */ FieldValidator validator = lookupValidatorInRegistry ( validationMetaData . getName ( ) ) ; /*\n             * Apply the properties from the validationMetaData to the\n             * validator.\n             */ applyValidationMetaDataPropertiesToValidator ( validationMetaData , validator ) ; validatorsList . add ( validator ) ; } return validatorsList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method looks up the validator in the registry . [CODESPLIT] private FieldValidator lookupValidatorInRegistry ( String validationMetaDataName ) { Map < String , Object > applicationContext = ValidationContext . get ( ) . getObjectRegistry ( ) ; Exceptions . requireNonNull ( applicationContext ) ; return ( FieldValidator ) applicationContext . get ( \"/org/boon/validator/\" + validationMetaDataName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method applies the properties from the validationMetaData to the validator uses Spring s BeanWrapperImpl . [CODESPLIT] private void applyValidationMetaDataPropertiesToValidator ( ValidatorMetaData metaData , FieldValidator validator ) { Map < String , Object > properties = metaData . getProperties ( ) ; ifPropertyBlankRemove ( properties , \"detailMessage\" ) ; ifPropertyBlankRemove ( properties , \"summaryMessage\" ) ; BeanUtils . copyProperties ( validator , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a property if it is null or an empty string . This allows the property to have a null or emtpy string in the meta - data but we don t copy it to the validator if the property is not set . [CODESPLIT] private void ifPropertyBlankRemove ( Map < String , Object > properties , String property ) { Object object = properties . get ( property ) ; if ( object == null ) { properties . remove ( property ) ; } else if ( object instanceof String ) { String string = ( String ) object ; if ( \"\" . equals ( string . trim ( ) ) ) { properties . remove ( property ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the listFromClassLoader [CODESPLIT] public static List < String > listFromClassLoader ( ClassLoader loader , String resource ) { final List < URL > resourceURLs = Classpaths . classpathResources ( loader , resource ) ; final List < String > resourcePaths = Lists . list ( String . class ) ; final Map < URI , FileSystem > pathToZipFileSystems = new HashMap <> ( ) ; //So you don't have to keep loading the same jar/zip file. for ( URL resourceURL : resourceURLs ) { if ( resourceURL . getProtocol ( ) . equals ( \"jar\" ) ) { resourcesFromJar ( resourcePaths , resourceURL , pathToZipFileSystems ) ; } else { resourcesFromFileSystem ( resourcePaths , resourceURL ) ; } } return resourcePaths ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the listFromClassLoader [CODESPLIT] public static List < Path > pathsFromClassLoader ( ClassLoader loader , String resource ) { final List < URL > resourceURLs = Classpaths . classpathResources ( loader , resource ) ; final List < Path > resourcePaths = Lists . list ( Path . class ) ; final Map < URI , FileSystem > pathToZipFileSystems = new HashMap <> ( ) ; //So you don't have to keep loading the same jar/zip file. for ( URL resourceURL : resourceURLs ) { if ( resourceURL . getProtocol ( ) . equals ( \"jar\" ) ) { pathsFromJar ( resourcePaths , resourceURL , pathToZipFileSystems ) ; } else { pathsFromFileSystem ( resourcePaths , resourceURL ) ; } } return resourcePaths ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate utc time . This gets called every 20 mili - seconds or so . [CODESPLIT] @ Override public void tick ( long time ) { this . time . set ( time ) ; /*Foreign thread    every 20 or so mili-seconds so we don't spend too\n         much time figuring out utc time. */ approxTime . set ( Dates . utcNow ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the size of the cache . This is not 100% accurate if cache is being concurrenly accessed . [CODESPLIT] @ Override public int size ( ) { int size = 0 ; for ( SimpleCache < K , V > cache : cacheRegions ) { size += cache . size ( ) ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the hash . [CODESPLIT] private final int hash ( Object k ) { int h = hashSeed ; h ^= k . hashCode ( ) ; h ^= ( h >>> 20 ) ^ ( h >>> 12 ) ; return h ^ ( h >>> 7 ) ^ ( h >>> 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures default options . [CODESPLIT] private Options defaultOptions ( ) { Options options = new Options ( ) ; options . createIfMissing ( true ) ; options . blockSize ( 32_768 ) ; //32K options . cacheSize ( 67_108_864 ) ; //64MB return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens the database [CODESPLIT] private boolean openDB ( File file , Options options ) { try { database = JniDBFactory . factory . open ( file , options ) ; logger . info ( \"Using JNI Level DB\" ) ; return true ; } catch ( IOException ex1 ) { try { database = Iq80DBFactory . factory . open ( file , options ) ; logger . info ( \"Using Java Level DB\" ) ; return false ; } catch ( IOException ex2 ) { return Exceptions . handle ( Boolean . class , ex2 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts values into the key value store in batch mode [CODESPLIT] @ Override public void putAll ( Map < byte [ ] , byte [ ] > values ) { WriteBatch batch = database . createWriteBatch ( ) ; try { for ( Map . Entry < byte [ ] , byte [ ] > entry : values . entrySet ( ) ) { batch . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } if ( putAllWriteCount . addAndGet ( values . size ( ) ) > 10_000 ) { putAllWriteCount . set ( 0 ) ; database . write ( batch , flush ) ; } else { database . write ( batch , writeOptions ) ; } } finally { closeBatch ( batch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all of the keys passed . [CODESPLIT] @ Override public void removeAll ( Iterable < byte [ ] > keys ) { WriteBatch batch = database . createWriteBatch ( ) ; try { for ( byte [ ] key : keys ) { batch . delete ( key ) ; } database . write ( batch ) ; } finally { closeBatch ( batch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search to a certain location . [CODESPLIT] @ Override public KeyValueIterable < byte [ ] , byte [ ] > search ( byte [ ] startKey ) { final DBIterator iterator = database . iterator ( ) ; iterator . seek ( startKey ) ; return new KeyValueIterable < byte [ ] , byte [ ] > ( ) { @ Override public void close ( ) { closeIterator ( iterator ) ; } @ Override public Iterator < Entry < byte [ ] , byte [ ] > > iterator ( ) { return new Iterator < Entry < byte [ ] , byte [ ] > > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public Entry < byte [ ] , byte [ ] > next ( ) { Map . Entry < byte [ ] , byte [ ] > next = iterator . next ( ) ; return new Entry <> ( next . getKey ( ) , next . getValue ( ) ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load all of the key / values from the store . [CODESPLIT] @ Override public KeyValueIterable < byte [ ] , byte [ ] > loadAll ( ) { final DBIterator iterator = database . iterator ( ) ; iterator . seekToFirst ( ) ; return new KeyValueIterable < byte [ ] , byte [ ] > ( ) { @ Override public void close ( ) { closeIterator ( iterator ) ; } @ Override public Iterator < Entry < byte [ ] , byte [ ] > > iterator ( ) { return new Iterator < Entry < byte [ ] , byte [ ] > > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public Entry < byte [ ] , byte [ ] > next ( ) { Map . Entry < byte [ ] , byte [ ] > next = iterator . next ( ) ; return new Entry <> ( next . getKey ( ) , next . getValue ( ) ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keys are expected to be sorted [CODESPLIT] @ Override public Map < byte [ ] , byte [ ] > loadAllByKeys ( Collection < byte [ ] > keys ) { if ( keys == null || keys . size ( ) == 0 ) { return Collections . EMPTY_MAP ; } Map < byte [ ] , byte [ ] > results = new LinkedHashMap <> ( keys . size ( ) ) ; DBIterator iterator = null ; try { iterator = database . iterator ( ) ; iterator . seek ( keys . iterator ( ) . next ( ) ) ; while ( iterator . hasNext ( ) ) { final Map . Entry < byte [ ] , byte [ ] > next = iterator . next ( ) ; results . put ( next . getKey ( ) , next . getValue ( ) ) ; } } finally { try { if ( iterator != null ) { iterator . close ( ) ; } } catch ( IOException e ) { Exceptions . handle ( e ) ; } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the database connection . [CODESPLIT] @ Override public void close ( ) { try { flush ( ) ; database . close ( ) ; } catch ( Exception e ) { Exceptions . handle ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * End universal methods . [CODESPLIT] private static int calculateEndIndex ( double [ ] array , int originalIndex ) { final int length = array . length ; Exceptions . requireNonNull ( array , \"array cannot be null\" ) ; int index = originalIndex ; /* Adjust for reading from the right as in\n        -1 reads the 4th element if the length is 5\n         */ if ( index < 0 ) { index = length + index ; } /* Bounds check\n            if it is still less than 0, then they\n            have an negative index that is greater than length\n         */ /* Bounds check\n            if it is still less than 0, then they\n            have an negative index that is greater than length\n         */ if ( index < 0 ) { index = 0 ; } if ( index > length ) { index = length ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reduce by functional support for int arrays . [CODESPLIT] public static < T > double reduceBy ( final double [ ] array , T object ) { if ( object . getClass ( ) . isAnonymousClass ( ) ) { return reduceByR ( array , object ) ; } try { ConstantCallSite callSite = Invoker . invokeReducerLongIntReturnLongMethodHandle ( object ) ; MethodHandle methodHandle = callSite . dynamicInvoker ( ) ; try { double sum = 0 ; for ( double v : array ) { sum = ( double ) methodHandle . invokeExact ( sum , v ) ; } return sum ; } catch ( Throwable throwable ) { return handle ( Long . class , throwable , \"Unable to perform reduceBy\" ) ; } } catch ( Exception ex ) { return reduceByR ( array , object ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fallback to reflection if the call - site will not work or did not work [CODESPLIT] private static < T > double reduceByR ( final double [ ] array , T object ) { try { Method method = Invoker . invokeReducerLongIntReturnLongMethod ( object ) ; double sum = 0 ; for ( double v : array ) { sum = ( double ) method . invoke ( object , sum , v ) ; } return sum ; } catch ( Throwable throwable ) { return handle ( Long . class , throwable , \"Unable to perform reduceBy\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Min [CODESPLIT] public static double min ( double [ ] values , final int start , final int length ) { double min = Float . MAX_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] < min ) min = values [ index ] ; } return min ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate Variance . [CODESPLIT] public static double varianceDouble ( double [ ] values , final int start , final int length ) { double mean = mean ( values , start , length ) ; double temp = 0 ; for ( int index = start ; index < length ; index ++ ) { double a = values [ index ] ; temp += ( mean - a ) * ( mean - a ) ; } return temp / length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * End universal methods . [CODESPLIT] private static int calculateIndex ( long [ ] array , int originalIndex ) { final int length = array . length ; Exceptions . requireNonNull ( array , \"array cannot be null\" ) ; int index = originalIndex ; /* Adjust for reading from the right as in\n        -1 reads the 4th element if the length is 5\n         */ if ( index < 0 ) { index = length + index ; } /* Bounds check\n            if it is still less than 0, then they\n            have an negative index that is greater than length\n         */ /* Bounds check\n            if it is still less than 0, then they\n            have an negative index that is greater than length\n         */ if ( index < 0 ) { index = 0 ; } if ( index >= length ) { index = length - 1 ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max [CODESPLIT] public static long max ( long [ ] values , final int start , final int length ) { long max = Long . MIN_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] > max ) { max = values [ index ] ; } } return max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Min [CODESPLIT] public static long min ( long [ ] values , final int start , final int length ) { long min = Long . MAX_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] < min ) min = values [ index ] ; } return min ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Average [CODESPLIT] public static long mean ( long [ ] values , final int start , final int length ) { return ( long ) Math . round ( meanDouble ( values , start , length ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates variance [CODESPLIT] public static long variance ( long [ ] values , final int start , final int length ) { return ( long ) Math . round ( varianceDouble ( values , start , length ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used internally to avoid loss and rounding errors a bit . [CODESPLIT] public static double meanDouble ( long [ ] values , final int start , final int length ) { double mean = ( ( double ) sum ( values , start , length ) ) / ( ( double ) length ) ; return mean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate Median [CODESPLIT] public static long median ( long [ ] values , final int start , final int length ) { long [ ] sorted = new long [ length ] ; System . arraycopy ( values , start , sorted , 0 , length ) ; Arrays . sort ( sorted ) ; if ( length % 2 == 0 ) { int middle = sorted . length / 2 ; double median = ( sorted [ middle - 1 ] + sorted [ middle ] ) / 2.0 ; return Math . round ( median ) ; } else { return sorted [ sorted . length / 2 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main entry into system . <p / > <p / > <p / > If you are debugging something not coming into the system . <p / > Start here! [CODESPLIT] @ ServiceMethod public void mainRequestHandler ( DataStoreRequest dataStoreRequest ) { if ( verbose || debug ) { logger . info ( \"RequestHandler::mainRequestHandler\" , dataStoreRequest ) ; } switch ( dataStoreRequest . action ( ) ) { case GET : masterDataStore . get ( ( GetRequest ) dataStoreRequest ) ; break ; case GET_LOCAL_DB : handleGetLocalDbVerb ( dataStoreRequest ) ; break ; case GET_MEM : handleGetMemVerb ( dataStoreRequest ) ; break ; case SET : masterDataStore . set ( ( SetRequest ) dataStoreRequest ) ; break ; case SET_BROADCAST : handleSetAndBroadCastVerb ( dataStoreRequest ) ; break ; case SET_IF_NOT_EXIST : handleSetIfNotExistsVerb ( dataStoreRequest ) ; break ; case SET_BATCH : handleSetBatch ( dataStoreRequest ) ; break ; case SET_BATCH_IF_NOT_EXISTS : handleSetBatchIfNotExists ( dataStoreRequest ) ; break ; case SET_SOURCE : handleSetSource ( dataStoreRequest ) ; break ; case GET_SOURCE : handleGetSource ( dataStoreRequest ) ; break ; case BATCH_READ : handleBatchRead ( dataStoreRequest ) ; break ; case CLEAR_STATS : handleClearStats ( dataStoreRequest ) ; break ; case GET_STATS : handleGetStats ( dataStoreRequest ) ; break ; case REMOVE : handleRemove ( dataStoreRequest ) ; break ; case REMOVE_SOURCE : handleRemoveSource ( dataStoreRequest ) ; break ; case METHOD_CALL : handleMethodCall ( ( MethodCall ) dataStoreRequest ) ; break ; case SEARCH : handleSearchVerb ( dataStoreRequest ) ; break ; default : puts ( dataStoreRequest ) ; } trackCall ( dataStoreRequest . action ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Allows this base class to be initialized by the subclasses . [CODESPLIT] protected void init ( Comparable min , Comparable max ) { this . realMin = min ; this . realMax = max ; assert min . compareTo ( max ) < 0 ; isInitialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes method from list or map depending on what the Object arg is . [CODESPLIT] public static Object invokeMethodFromObjectArg ( Object object , MethodAccess method , Object args ) { return invokeMethodFromObjectArg ( false , null , null , object , method , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A very fast reduce by . If performance is your thing this seems to be as fast a plain for loop when benchmarking with JMH . [CODESPLIT] public static double reduceBy ( final float [ ] array , ReduceBy reduceBy ) { double sum = 0 ; for ( float v : array ) { sum = reduceBy . reduce ( sum , v ) ; } return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Big Sum [CODESPLIT] public static double bigSum ( float [ ] values , int start , int length ) { double sum = 0 ; for ( int index = start ; index < length ; index ++ ) { sum += values [ index ] ; } return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max [CODESPLIT] public static float max ( float [ ] values , final int start , final int length ) { float max = Float . MIN_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] > max ) { max = values [ index ] ; } } return max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate standard deviation . [CODESPLIT] public static float standardDeviation ( float [ ] values , final int start , final int length ) { double variance = varianceDouble ( values , start , length ) ; return ( float ) Math . sqrt ( variance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Useful for generated file names and generated work directories . [CODESPLIT] public static String euroUTCSystemDateString ( long timestamp ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( timestamp ) ; calendar . setTimeZone ( UTC_TIME_ZONE ) ; int day = calendar . get ( Calendar . DAY_OF_MONTH ) ; int month = calendar . get ( Calendar . MONTH ) ; int year = calendar . get ( Calendar . YEAR ) ; int hour = calendar . get ( Calendar . HOUR_OF_DAY ) ; int minute = calendar . get ( Calendar . MINUTE ) ; int second = calendar . get ( Calendar . SECOND ) ; CharBuf buf = CharBuf . create ( 16 ) ; buf . add ( Str . zfill ( day , 2 ) ) . add ( ' ' ) ; buf . add ( Str . zfill ( month , 2 ) ) . add ( ' ' ) ; buf . add ( year ) . add ( ' ' ) ; buf . add ( Str . zfill ( hour , 2 ) ) . add ( ' ' ) ; buf . add ( Str . zfill ( minute , 2 ) ) . add ( ' ' ) ; buf . add ( Str . zfill ( second , 2 ) ) . add ( \"_utc_euro\" ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the object match this expression . An expression is a collection of criteria . [CODESPLIT] public static boolean matches ( Object obj , Criteria ... exp ) { return ObjectFilter . and ( exp ) . test ( obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This has to convert values to field type . [CODESPLIT] public static Criterion notIn ( final Object name , final Object ... values ) { return new Criterion < Object > ( name . toString ( ) , Operator . NOT_IN , values ) { @ Override public boolean resolve ( Object owner ) { Object fieldValue = fieldValue ( ) ; if ( value == null ) { return false ; } return ! valueSet ( ) . contains ( fieldValue ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static Criterion ltLong ( final Object name , final long compareValue ) { return new Criterion ( name . toString ( ) , Operator . LESS_THAN , compareValue ) { @ Override public boolean resolve ( final Object owner ) { long value = fieldLong ( ) ; return value < compareValue ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make criteria configurable [CODESPLIT] public static Criteria createCriteria ( String name , Operator operator , TypeType type , Class < Object > classType , List < ? > values ) { okOrDie ( \"Values must be passed\" , values ) ; Object value = values . get ( 0 ) ; switch ( operator ) { case EQUAL : switch ( type ) { case CHAR : return eqChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return eqByte ( name , Conversions . toByte ( value ) ) ; case BOOLEAN : return eqBoolean ( name , Conversions . toBoolean ( value ) ) ; case INT : return eqInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return eqFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return eqShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return eqDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return eqLong ( name , Conversions . toLong ( value ) ) ; default : return eq ( name , Conversions . coerce ( classType , value ) ) ; } case NOT_EQUAL : switch ( type ) { case CHAR : return notEqChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return notEqByte ( name , Conversions . toByte ( value ) ) ; case BOOLEAN : return notEqBoolean ( name , Conversions . toBoolean ( value ) ) ; case INT : return notEqInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return notEqFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return notEqShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return notEqDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return notEqLong ( name , Conversions . toLong ( value ) ) ; default : return notEq ( name , Conversions . coerce ( classType , value ) ) ; } case GREATER_THAN : switch ( type ) { case CHAR : return gtChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return gtByte ( name , Conversions . toByte ( value ) ) ; case INT : return gtInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return gtFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return gtShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return gtDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return gtLong ( name , Conversions . toLong ( value ) ) ; default : return gt ( name , Conversions . coerce ( classType , value ) ) ; } case LESS_THAN : switch ( type ) { case CHAR : return ltChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return ltByte ( name , Conversions . toByte ( value ) ) ; case INT : return ltInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return ltFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return ltShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return ltDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return ltLong ( name , Conversions . toLong ( value ) ) ; default : return lt ( name , Conversions . coerce ( classType , value ) ) ; } case GREATER_THAN_EQUAL : switch ( type ) { case CHAR : return gteChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return gteByte ( name , Conversions . toByte ( value ) ) ; case INT : return gteInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return gteFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return gteShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return gteDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return gteLong ( name , Conversions . toLong ( value ) ) ; default : return gte ( name , Conversions . coerce ( classType , value ) ) ; } case LESS_THAN_EQUAL : switch ( type ) { case CHAR : return lteChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return lteByte ( name , Conversions . toByte ( value ) ) ; case INT : return lteInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return lteFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return lteShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return lteDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return lteLong ( name , Conversions . toLong ( value ) ) ; default : return lte ( name , Conversions . coerce ( classType , value ) ) ; } case BETWEEN : okOrDie ( \"Values must be at least 2 in size\" , values . size ( ) > 1 ) ; Object value2 = values . get ( 1 ) ; switch ( type ) { case CHAR : return betweenChar ( name , Conversions . toChar ( value ) , Conversions . toChar ( value2 ) ) ; case BYTE : return betweenByte ( name , Conversions . toByte ( value ) , Conversions . toByte ( value2 ) ) ; case INT : return betweenInt ( name , Conversions . toInt ( value ) , Conversions . toInt ( value2 ) ) ; case FLOAT : return betweenFloat ( name , Conversions . toFloat ( value ) , Conversions . toFloat ( value2 ) ) ; case SHORT : return betweenShort ( name , Conversions . toShort ( value ) , Conversions . toShort ( value2 ) ) ; case DOUBLE : return betweenDouble ( name , Conversions . toDouble ( value ) , Conversions . toDouble ( value2 ) ) ; case LONG : return betweenLong ( name , Conversions . toLong ( value ) , Conversions . toLong ( value2 ) ) ; default : return between ( name , Conversions . coerce ( classType , value ) , Conversions . coerce ( classType , value2 ) ) ; } case IN : switch ( type ) { case CHAR : return inChars ( name , Conversions . carray ( values ) ) ; case BYTE : return inBytes ( name , Conversions . barray ( values ) ) ; case INT : return inInts ( name , Conversions . iarray ( values ) ) ; case FLOAT : return inFloats ( name , Conversions . farray ( values ) ) ; case SHORT : return inShorts ( name , Conversions . sarray ( values ) ) ; case DOUBLE : return inDoubles ( name , Conversions . darray ( values ) ) ; case LONG : return inLongs ( name , Conversions . larray ( values ) ) ; default : return in ( name , Conversions . toArray ( classType , ( List < Object > ) values ) ) ; } case NOT_IN : switch ( type ) { case CHAR : return notInChars ( name , Conversions . carray ( values ) ) ; case BYTE : return notInBytes ( name , Conversions . barray ( values ) ) ; case INT : return notInInts ( name , Conversions . iarray ( values ) ) ; case FLOAT : return notInFloats ( name , Conversions . farray ( values ) ) ; case SHORT : return notInShorts ( name , Conversions . sarray ( values ) ) ; case DOUBLE : return notInDoubles ( name , Conversions . darray ( values ) ) ; case LONG : return notInLongs ( name , Conversions . larray ( values ) ) ; default : return notIn ( name , Conversions . toArray ( classType , ( List < Object > ) values ) ) ; } case CONTAINS : return contains ( name , Conversions . coerce ( classType , value ) ) ; case NOT_CONTAINS : return notContains ( name , Conversions . coerce ( classType , value ) ) ; case STARTS_WITH : return startsWith ( name , value ) ; case ENDS_WITH : return endsWith ( name , value ) ; case NOT_EMPTY : return notEmpty ( name ) ; case IS_EMPTY : return empty ( name ) ; } return die ( Criteria . class , \"Not Found\" , name , operator , type , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make criteria configurable [CODESPLIT] public static Criteria createCriteriaFromClass ( String name , Class < ? > cls , Operator operator , List < ? > values ) { if ( operator == Operator . AND ) { return new Group . And ( cls , values ) ; } else if ( operator == Operator . OR ) { return new Group . Or ( cls , values ) ; } else { FieldAccess fieldAccess = BeanUtils . idxField ( cls , name ) ; return createCriteria ( name , operator , fieldAccess . typeEnum ( ) , ( Class < Object > ) fieldAccess . type ( ) , values ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates criteria from a list . This is used to configure Criteria in JSON . [CODESPLIT] public static Criteria criteriaFromList ( List < ? > list ) { List < Object > args = new ArrayList ( list ) ; Object o = atIndex ( args , - 1 ) ; if ( ! ( o instanceof List ) ) { atIndex ( args , - 1 , Collections . singletonList ( o ) ) ; } return ( Criteria ) Invoker . invokeFromList ( ObjectFilter . class , \"createCriteriaFromClass\" , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a JSON string into a Criteria . [CODESPLIT] public static Criteria criteriaFromJson ( String json ) { return ( Criteria ) Invoker . invokeFromObject ( ObjectFilter . class , \"createCriteriaFromClass\" , fromJson ( json ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a primitive list based on an input list and a property path [CODESPLIT] public static DoubleList toDoubleList ( Collection < ? > inputList , String propertyPath ) { if ( inputList . size ( ) == 0 ) { return new DoubleList ( 0 ) ; } DoubleList outputList = new DoubleList ( inputList . size ( ) ) ; if ( propertyPath . contains ( \".\" ) || propertyPath . contains ( \"[\" ) ) { String [ ] properties = StringScanner . splitByDelimiters ( propertyPath , \".[]\" ) ; for ( Object o : inputList ) { outputList . add ( BeanUtils . getPropertyDouble ( o , properties ) ) ; } } else { Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( inputList . iterator ( ) . next ( ) ) ; FieldAccess fieldAccess = fields . get ( propertyPath ) ; for ( Object o : inputList ) { outputList . add ( fieldAccess . getDouble ( o ) ) ; } } return outputList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new value to the list but don t employ a wrapper . [CODESPLIT] public boolean addFloat ( double value ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = value ; end ++ ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new value to the list but don t employ a wrapper . [CODESPLIT] public DoubleList add ( double integer ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new array to the list . [CODESPLIT] public boolean addArray ( double ... integers ) { if ( end + integers . length >= values . length ) { values = grow ( values , ( values . length + integers . length ) * 2 ) ; } System . arraycopy ( integers , 0 , values , end , integers . length ) ; end += integers . length ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value in the list . [CODESPLIT] @ Override public Double set ( int index , Double element ) { double oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This would be a good opportunity to reintroduce dynamic invoke [CODESPLIT] public double reduceBy ( Object function , String name ) { return Dbl . reduceBy ( values , end , function , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does a binary search [CODESPLIT] public static < T > T search ( List < T > list , T item ) { if ( list . size ( ) > 1 ) { Object o = list ; int index = Collections . binarySearch ( ( List < ? extends Comparable < ? super T > > ) o , item ) ; return list . get ( index ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does a binary search [CODESPLIT] public static int searchForIndex ( List < ? > list , Object item ) { if ( list . size ( ) > 1 ) { Object o = list ; return Collections . binarySearch ( ( List < ? extends Comparable < ? super Object > > ) o , item ) ; } else { return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the max item from the array . Sorts the list descending first . [CODESPLIT] public static < T > T max ( T [ ] array ) { if ( array . length > 1 ) { Sorting . sortDesc ( array ) ; return array [ 0 ] ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "From the sorts this is the first few items . [CODESPLIT] public static < T > List < T > firstOf ( List < T > list , int count , Sort ... sorts ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list , sorts ) ; return Lists . sliceOf ( list , 0 , count ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grabs the last items after the sort . [CODESPLIT] public static < T > T lastOf ( List < T > list , Sort ... sorts ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list , sorts ) ; return list . get ( list . size ( ) - 1 ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grabs the last few items from the list . [CODESPLIT] public static < T > List < T > lastOf ( List < T > list , int count , Sort ... sorts ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list , sorts ) ; return Lists . endSliceOf ( list , count * - 1 ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the max value of the object with the property given . [CODESPLIT] public static < T > T max ( List < T > list , String sortBy ) { if ( list . size ( ) > 1 ) { Sorting . sortDesc ( list , sortBy ) ; return list . get ( 0 ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the max value of the object with the property given . [CODESPLIT] public static < T > T max ( T [ ] array , String sortBy ) { if ( array . length > 1 ) { Sorting . sortDesc ( array , sortBy ) ; return array [ 0 ] ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the least few . [CODESPLIT] public static < T > List < T > least ( List < T > list , int count ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list ) ; return Lists . sliceOf ( list , 0 , count ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the min value using a natural sort . [CODESPLIT] public static < T > T min ( List < T > list ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list ) ; return list . get ( 0 ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the max value of the object with the property given . [CODESPLIT] public static < T > T min ( T [ ] array ) { if ( array . length > 1 ) { Sorting . sort ( array ) ; return array [ 0 ] ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the min value of the object with the property given . [CODESPLIT] public static < T > T min ( T [ ] array , String sortBy ) { if ( array . length > 1 ) { Sorting . sort ( array , sortBy ) ; return array [ 0 ] ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts a list of maps to objects . I always forget that this exists . I need to remember . [CODESPLIT] @ Override public < T > List < T > convertListOfMapsToObjects ( List < Map > list , Class < T > componentType ) { List < Object > newList = new ArrayList <> ( list . size ( ) ) ; for ( Object obj : list ) { if ( obj instanceof Value ) { obj = ( ( Value ) obj ) . toValue ( ) ; } if ( obj instanceof Map ) { Map map = ( Map ) obj ; if ( map instanceof ValueMapImpl ) { newList . add ( fromValueMap ( ( Map < String , Value > ) map , componentType ) ) ; } else { newList . add ( fromMap ( map , componentType ) ) ; } } else { newList . add ( Conversions . coerce ( componentType , obj ) ) ; } } return ( List < T > ) newList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes an array of maps . [CODESPLIT] private void processArrayOfMaps ( Object newInstance , FieldAccess field , Map < String , Object > [ ] maps ) { List < Map < String , Object > > list = Lists . list ( maps ) ; handleCollectionOfMaps ( newInstance , field , list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes an collection of maps . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void handleCollectionOfMaps ( Object newInstance , FieldAccess field , Collection < Map < String , Object > > collectionOfMaps ) { Collection < Object > newCollection = Conversions . createCollection ( field . type ( ) , collectionOfMaps . size ( ) ) ; Class < ? > componentClass = field . getComponentClass ( ) ; if ( componentClass != null ) { for ( Map < String , Object > mapComponent : collectionOfMaps ) { newCollection . add ( fromMap ( mapComponent , componentClass ) ) ; } field . setObject ( newInstance , newCollection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This converts / coerce a constructor argument to the given parameter type . [CODESPLIT] private boolean matchAndConvertArgs ( List < Object > convertedArgumentList , BaseAccess methodAccess , Class [ ] parameterTypes , int index , boolean [ ] flag , boolean loose ) { Object value = null ; try { Class parameterClass ; Object item ; parameterClass = parameterTypes [ index ] ; item = convertedArgumentList . get ( index ) ; final TypeType parameterType = TypeType . getType ( parameterClass ) ; if ( item instanceof ValueContainer ) { item = ( ( ValueContainer ) item ) . toValue ( ) ; convertedArgumentList . set ( index , item ) ; } if ( item == null ) { return true ; } switch ( parameterType ) { case INT : case SHORT : case BYTE : case BOOLEAN : case CHAR : case FLOAT : case DOUBLE : case LONG : if ( item == null ) { return false ; } case INTEGER_WRAPPER : case BYTE_WRAPPER : case SHORT_WRAPPER : case BOOLEAN_WRAPPER : case CHAR_WRAPPER : case FLOAT_WRAPPER : case DOUBLE_WRAPPER : case CHAR_SEQUENCE : case NUMBER : case LONG_WRAPPER : if ( ! loose ) { if ( item instanceof Number ) { value = Conversions . coerceWithFlag ( parameterType , parameterClass , flag , item ) ; convertedArgumentList . set ( index , value ) ; return flag [ 0 ] ; } else { return false ; } } else { value = Conversions . coerceWithFlag ( parameterType , parameterClass , flag , item ) ; convertedArgumentList . set ( index , value ) ; return flag [ 0 ] ; } case ENUM : if ( item instanceof Enum ) { return true ; } if ( item instanceof CharSequence ) { value = toEnum ( parameterClass , item . toString ( ) ) ; convertedArgumentList . set ( index , value ) ; return value != null ; } else if ( item instanceof Number ) { value = toEnum ( parameterClass , ( ( Number ) item ) . intValue ( ) ) ; convertedArgumentList . set ( index , value ) ; return value != null ; } else { return false ; } case CLASS : if ( item instanceof Class ) { return true ; } value = Conversions . coerceWithFlag ( parameterType , parameterClass , flag , item ) ; convertedArgumentList . set ( index , value ) ; return flag [ 0 ] ; case STRING : if ( item instanceof String ) { return true ; } if ( item instanceof CharSequence ) { value = item . toString ( ) ; convertedArgumentList . set ( index , value ) ; return true ; } else if ( loose ) { value = item . toString ( ) ; convertedArgumentList . set ( index , value ) ; return true ; } else { return false ; } case MAP : case VALUE_MAP : if ( item instanceof Map ) { Map itemMap = ( Map ) item ; /* This code creates a map based on the parameterized types of the constructor arg.\n                     *  This does ninja level generics manipulations and needs to be captured in some\n                     *  reusable way.\n                      * */ Type type = methodAccess . getGenericParameterTypes ( ) [ index ] ; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Class < ? > keyType = ( Class < ? > ) pType . getActualTypeArguments ( ) [ 0 ] ; Class < ? > valueType = ( Class < ? > ) pType . getActualTypeArguments ( ) [ 1 ] ; Map newMap = Conversions . createMap ( parameterClass , itemMap . size ( ) ) ; /* Iterate through the map items and convert the keys/values to match\n                    the parameterized constructor parameter args.\n                     */ for ( Object o : itemMap . entrySet ( ) ) { Map . Entry entry = ( Map . Entry ) o ; Object key = entry . getKey ( ) ; value = entry . getValue ( ) ; key = ValueContainer . toObject ( key ) ; value = ValueContainer . toObject ( value ) ; /* Here is the actual conversion from a list or a map of some object.\n                        This can be captured in helper method the duplication is obvious.\n                         */ if ( value instanceof List ) { value = fromList ( ( List ) value , valueType ) ; } else if ( value instanceof Map ) { value = fromMap ( ( Map ) value , valueType ) ; } else { value = coerce ( valueType , value ) ; } if ( key instanceof List ) { key = fromList ( ( List ) key , keyType ) ; } else if ( value instanceof Map ) { key = fromMap ( ( Map ) key , keyType ) ; } else { key = coerce ( keyType , key ) ; } newMap . put ( key , value ) ; } convertedArgumentList . set ( index , newMap ) ; return true ; } } break ; case INSTANCE : if ( parameterClass . isInstance ( item ) ) { return true ; } if ( item instanceof Map ) { item = fromMap ( ( Map < String , Object > ) item , parameterClass ) ; convertedArgumentList . set ( index , item ) ; return true ; } else if ( item instanceof List ) { List < Object > listItem = null ; listItem = ( List < Object > ) item ; value = fromList ( listItem , parameterClass ) ; convertedArgumentList . set ( index , value ) ; return true ; } else { convertedArgumentList . set ( index , coerce ( parameterClass , item ) ) ; return true ; } //break; case INTERFACE : case ABSTRACT : if ( parameterClass . isInstance ( item ) ) { return true ; } if ( item instanceof Map ) { /** Handle conversion of user define interfaces. */ String className = ( String ) ( ( Map ) item ) . get ( \"class\" ) ; if ( className != null ) { item = fromMap ( ( Map < String , Object > ) item , Reflection . loadClass ( className ) ) ; convertedArgumentList . set ( index , item ) ; return true ; } else { return false ; } } break ; case ARRAY : case ARRAY_INT : case ARRAY_BYTE : case ARRAY_SHORT : case ARRAY_FLOAT : case ARRAY_DOUBLE : case ARRAY_LONG : case ARRAY_STRING : case ARRAY_OBJECT : item = Conversions . toList ( item ) ; case SET : case COLLECTION : case LIST : if ( item instanceof List ) { List < Object > itemList = ( List < Object > ) item ; /* Items have stuff in it, the item is a list of lists.\n                         * This is like we did earlier with the map.\n                         * Here is some more ninja generics Java programming that needs to be captured in one place.\n                         * */ if ( itemList . size ( ) > 0 && ( itemList . get ( 0 ) instanceof List || itemList . get ( 0 ) instanceof ValueContainer ) ) { /** Grab the generic type of the list. */ Type type = methodAccess . getGenericParameterTypes ( ) [ index ] ; /*  Try to pull the generic type information out so you can create\n                               a strongly typed list to inject.\n                             */ if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Class < ? > componentType ; if ( ! ( pType . getActualTypeArguments ( ) [ 0 ] instanceof Class ) ) { componentType = Object . class ; } else { componentType = ( Class < ? > ) pType . getActualTypeArguments ( ) [ 0 ] ; } Collection newList = Conversions . createCollection ( parameterClass , itemList . size ( ) ) ; for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ) . toValue ( ) ; } if ( componentType == Object . class ) { newList . add ( o ) ; } else { List fromList = ( List ) o ; o = fromList ( fromList , componentType ) ; newList . add ( o ) ; } } convertedArgumentList . set ( index , newList ) ; return true ; } } else { /* Just a list not a list of lists so see if it has generics and pull out the\n                        * type information and created a strong typed list. This looks a bit familiar.\n                        * There is a big opportunity for some reuse here. */ Type type = methodAccess . getGenericParameterTypes ( ) [ index ] ; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Class < ? > componentType = pType . getActualTypeArguments ( ) [ 0 ] instanceof Class ? ( Class < ? > ) pType . getActualTypeArguments ( ) [ 0 ] : Object . class ; Collection newList = Conversions . createCollection ( parameterClass , itemList . size ( ) ) ; for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ) . toValue ( ) ; } if ( o instanceof List ) { if ( componentType != Object . class ) { List fromList = ( List ) o ; o = fromList ( fromList , componentType ) ; } newList . add ( o ) ; } else if ( o instanceof Map ) { Map fromMap = ( Map ) o ; o = fromMap ( fromMap , componentType ) ; newList . add ( o ) ; } else { newList . add ( Conversions . coerce ( componentType , o ) ) ; } } convertedArgumentList . set ( index , newList ) ; return true ; } } } return false ; default : final TypeType itemType = TypeType . getInstanceType ( item ) ; switch ( itemType ) { case LIST : convertedArgumentList . set ( index , fromList ( ( List < Object > ) item , parameterClass ) ) ; return true ; case MAP : case VALUE_MAP : convertedArgumentList . set ( index , fromMap ( ( Map < String , Object > ) item , parameterClass ) ) ; return true ; case NUMBER : case BOOLEAN : case INT : case SHORT : case BYTE : case FLOAT : case DOUBLE : case LONG : case DOUBLE_WRAPPER : case FLOAT_WRAPPER : case INTEGER_WRAPPER : case SHORT_WRAPPER : case BOOLEAN_WRAPPER : case BYTE_WRAPPER : case LONG_WRAPPER : case CLASS : case VALUE : value = Conversions . coerceWithFlag ( parameterClass , flag , item ) ; if ( flag [ 0 ] == false ) { return false ; } convertedArgumentList . set ( index , value ) ; return true ; case CHAR_SEQUENCE : case STRING : value = Conversions . coerceWithFlag ( parameterClass , flag , item ) ; if ( flag [ 0 ] == false ) { return false ; } convertedArgumentList . set ( index , value ) ; return true ; } } if ( parameterClass . isInstance ( item ) ) { return true ; } } catch ( Exception ex ) { Boon . error ( ex , \"PROBLEM WITH oldMatchAndConvertArgs\" , \"fieldsAccessor\" , fieldsAccessor , \"list\" , convertedArgumentList , \"constructor\" , methodAccess , \"parameters\" , parameterTypes , \"index\" , index ) ; return false ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes an collection of maps . This can inject into an array and appears to be using some of the TypeType lib . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void handleCollectionOfValues ( Object newInstance , FieldAccess field , Collection < Value > acollectionOfValues ) { Collection collectionOfValues = acollectionOfValues ; if ( null == collectionOfValues ) { field . setObject ( newInstance , null ) ; return ; } if ( field . typeEnum ( ) == INSTANCE ) { field . setObject ( newInstance , fromList ( ( List ) acollectionOfValues , field . type ( ) ) ) ; return ; } if ( collectionOfValues instanceof ValueList ) { collectionOfValues = ( ( ValueList ) collectionOfValues ) . list ( ) ; } Class < ? > componentClass = field . getComponentClass ( ) ; /** If the field is a collection than try to convert the items in the collection to\n         * the field type.\n         */ switch ( field . typeEnum ( ) ) { case LIST : case SET : case COLLECTION : Collection < Object > newCollection = Conversions . createCollection ( field . type ( ) , collectionOfValues . size ( ) ) ; for ( Value value : ( List < Value > ) collectionOfValues ) { if ( value . isContainer ( ) ) { Object oValue = value . toValue ( ) ; if ( oValue instanceof Map ) { newCollection . add ( fromValueMap ( ( Map ) oValue , componentClass ) ) ; } } else { newCollection . add ( Conversions . coerce ( componentClass , value . toValue ( ) ) ) ; } } field . setObject ( newInstance , newCollection ) ; break ; case ARRAY : case ARRAY_INT : case ARRAY_BYTE : case ARRAY_SHORT : case ARRAY_FLOAT : case ARRAY_DOUBLE : case ARRAY_LONG : case ARRAY_STRING : case ARRAY_OBJECT : TypeType componentType = field . componentType ( ) ; int index = 0 ; switch ( componentType ) { case INT : int [ ] iarray = new int [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { iarray [ index ] = value . intValue ( ) ; index ++ ; } field . setObject ( newInstance , iarray ) ; return ; case SHORT : short [ ] sarray = new short [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { sarray [ index ] = value . shortValue ( ) ; index ++ ; } field . setObject ( newInstance , sarray ) ; return ; case DOUBLE : double [ ] darray = new double [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { darray [ index ] = value . doubleValue ( ) ; index ++ ; } field . setObject ( newInstance , darray ) ; return ; case FLOAT : float [ ] farray = new float [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { farray [ index ] = value . floatValue ( ) ; index ++ ; } field . setObject ( newInstance , farray ) ; return ; case LONG : long [ ] larray = new long [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { larray [ index ] = value . longValue ( ) ; index ++ ; } field . setObject ( newInstance , larray ) ; return ; case BYTE : byte [ ] barray = new byte [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { barray [ index ] = value . byteValue ( ) ; index ++ ; } field . setObject ( newInstance , barray ) ; return ; case CHAR : char [ ] chars = new char [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { chars [ index ] = value . charValue ( ) ; index ++ ; } field . setObject ( newInstance , chars ) ; return ; case STRING : CharBuf buffer = CharBuf . create ( 100 ) ; String [ ] strings = new String [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { strings [ index ] = value . stringValue ( buffer ) ; index ++ ; } field . setObject ( newInstance , strings ) ; return ; default : Object array = Array . newInstance ( componentClass , collectionOfValues . size ( ) ) ; Object o ; for ( Value value : ( List < Value > ) collectionOfValues ) { if ( value instanceof ValueContainer ) { o = value . toValue ( ) ; if ( o instanceof List ) { o = fromList ( ( List ) o , componentClass ) ; if ( componentClass . isInstance ( o ) ) { Array . set ( array , index , o ) ; } else { break ; } } else if ( o instanceof Map ) { o = fromMap ( ( Map ) o , componentClass ) ; if ( componentClass . isInstance ( o ) ) { Array . set ( array , index , o ) ; } else { break ; } } } else { o = value . toValue ( ) ; if ( componentClass . isInstance ( o ) ) { Array . set ( array , index , o ) ; } else { Array . set ( array , index , Conversions . coerce ( componentClass , o ) ) ; } } index ++ ; } field . setValue ( newInstance , array ) ; } break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to extract collection of values into some field collection . REFACTOR : This could be refactored to use the org . boon . core . TypeType system which should be faster . REFACTOR [CODESPLIT] private void processCollectionFromMapUsingFields ( final Object newInstance , final FieldAccess field , final Collection < ? > collection ) { final Class < ? > fieldComponentClass = field . getComponentClass ( ) ; final Class < ? > valueComponentClass = Reflection . getComponentType ( collection ) ; /** See if we have a collection of maps because if we do, then we have some\n         * recursive processing to do.\n         */ if ( Typ . isMap ( valueComponentClass ) ) { handleCollectionOfMaps ( newInstance , field , ( Collection < Map < String , Object > > ) collection ) ; return ; } /** See if this is a value object of some sort. */ if ( Typ . isValue ( valueComponentClass ) ) { handleCollectionOfValues ( newInstance , field , ( Collection < Value > ) collection ) ; return ; } /**\n         * See if the collection implements the same type as the field.\n         * I saw a few places that could have used this helper method earlier in the file but were not.\n         */ if ( Typ . implementsInterface ( collection . getClass ( ) , field . type ( ) ) ) { if ( fieldComponentClass != null && fieldComponentClass . isAssignableFrom ( valueComponentClass ) ) { field . setValue ( newInstance , collection ) ; return ; } } /** See if this is some sort of collection.\n         * TODO we need a coerce that needs a respectIgnore\n         *\n         * REFACTOR:\n         * Note we are assuming it is a collection of instances.\n         * We don't handle enums here.\n         *\n         * We do in other places.\n         *\n         * We handle all sorts of generics but not here.\n         *\n         * REFACTOR\n         *\n         **/ if ( ! field . typeEnum ( ) . isCollection ( ) ) { if ( collection instanceof List ) { try { Object value = fromList ( ( List ) collection , field . getComponentClass ( ) ) ; field . setValue ( newInstance , value ) ; } catch ( Exception ex ) { //There is an edge case that needs this. We need a coerce that takes respectIngore, etc. field . setValue ( newInstance , collection ) ; } } else { field . setValue ( newInstance , collection ) ; } return ; } /**\n         * Create a new collection. if the types already match then just copy them over.\n         * Note that this is currently untyped in the null case.\n         * We are relying on the fact that the field.setValue calls the Conversion.coerce.\n         */ Collection < Object > newCollection = Conversions . createCollection ( field . type ( ) , collection . size ( ) ) ; if ( fieldComponentClass == null || fieldComponentClass . isAssignableFrom ( valueComponentClass ) ) { newCollection . addAll ( collection ) ; field . setValue ( newInstance , newCollection ) ; return ; } /* Here we try to do the coercion for each individual collection item. */ for ( Object itemValue : collection ) { newCollection . add ( Conversions . coerce ( fieldComponentClass , itemValue ) ) ; field . setValue ( newInstance , newCollection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fromMap converts a map into a Java object . This version will see if there is a class parameter in the map and dies if there is not . [CODESPLIT] @ Override public Object fromMap ( Map < String , Object > map ) { String clazz = ( String ) map . get ( \"class\" ) ; Class cls = Reflection . loadClass ( clazz ) ; return fromMap ( map , cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a list of maps from a list of class instances . [CODESPLIT] @ Override public List < Map < String , Object > > toListOfMaps ( Collection < ? > collection ) { List < Map < String , Object > > list = new ArrayList <> ( ) ; for ( Object o : collection ) { list . add ( toMap ( o ) ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Key [CODESPLIT] @ Override public void put ( KEY key , VALUE value ) { VALUE oldValue = map . put ( key , value ) ; if ( oldValue != null ) { removeThenAddKey ( key ) ; } else { addKey ( key ) ; } if ( map . size ( ) > limit ) { map . remove ( removeLast ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value at key [CODESPLIT] @ Override public VALUE get ( KEY key ) { removeThenAddKey ( key ) ; return map . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the field label . [CODESPLIT] public static String getLabel ( final String fieldName , final ResourceBundle bundle ) { String label ; /** Look for fieldName, e.g., firstName. */ try { label = bundle . getString ( fieldName ) ; } catch ( MissingResourceException mre ) { label = generateLabelValue ( fieldName ) ; } return label ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the field label . [CODESPLIT] public static String createLabelWithNameSpace ( final String namespace , final String fieldName , final ResourceBundle bundle ) { String label ; try { try { /** Look for name-space + . + fieldName, e.g., Employee.firstName. */ label = bundle . getString ( namespace + ' ' + fieldName ) ; } catch ( MissingResourceException mre ) { /** Look for fieldName only, e.g., firstName. */ label = bundle . getString ( fieldName ) ; } } catch ( MissingResourceException mre ) { /** If you can't find the label, generate it thus, \"firstName\" becomes \"First Name\".*/ label = generateLabelValue ( fieldName ) ; } return label ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the tool tip . [CODESPLIT] public static String createToolTipWithNameSpace ( final String namespace , final String fieldName , final ResourceBundle bundle , final String toolTipType ) { String toolTip = null ; try { try { /** Look for name-space + . + fieldName, e.g., Employee.firstName.toolTip. */ toolTip = bundle . getString ( namespace + ' ' + fieldName + ' ' + toolTipType ) ; } catch ( MissingResourceException mre ) { /** Look for fieldName only, e.g., firstName.toolTip. */ toolTip = bundle . getString ( fieldName + ' ' + toolTipType ) ; } } catch ( MissingResourceException mre ) { } return toolTip ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate the field . Transforms firstName into First Name . This allows reasonable defaults for labels . [CODESPLIT] public static String generateLabelValue ( final String fieldName ) { final StringBuilder buffer = new StringBuilder ( fieldName . length ( ) * 2 ) ; class GenerationCommand { boolean capNextChar = false ; boolean lastCharWasUpperCase = false ; boolean lastCharWasNumber = false ; boolean lastCharWasSpecial = false ; boolean shouldContinue = true ; char [ ] chars = fieldName . toCharArray ( ) ; void processFieldName ( ) { for ( int index = 0 ; index < chars . length ; index ++ ) { char cchar = chars [ index ] ; shouldContinue = true ; processCharWasNumber ( buffer , index , cchar ) ; if ( ! shouldContinue ) { continue ; } processCharWasUpperCase ( buffer , index , cchar ) ; if ( ! shouldContinue ) { continue ; } processSpecialChars ( buffer , cchar ) ; if ( ! shouldContinue ) { continue ; } cchar = processCapitalizeCommand ( cchar ) ; cchar = processFirstCharacterCheck ( buffer , index , cchar ) ; if ( ! shouldContinue ) { continue ; } buffer . append ( cchar ) ; } } private void processCharWasNumber ( StringBuilder buffer , int index , char cchar ) { if ( lastCharWasSpecial ) { return ; } if ( Character . isDigit ( cchar ) ) { if ( index != 0 && ! lastCharWasNumber ) { buffer . append ( ' ' ) ; } lastCharWasNumber = true ; buffer . append ( cchar ) ; this . shouldContinue = false ; } else { lastCharWasNumber = false ; } } private char processFirstCharacterCheck ( final StringBuilder buffer , int index , char cchar ) { /* Always capitalize the first character. */ if ( index == 0 ) { cchar = Character . toUpperCase ( cchar ) ; buffer . append ( cchar ) ; this . shouldContinue = false ; } return cchar ; } private char processCapitalizeCommand ( char cchar ) { /* Capitalize the character. */ if ( capNextChar ) { capNextChar = false ; cchar = Character . toUpperCase ( cchar ) ; } return cchar ; } private void processSpecialChars ( final StringBuilder buffer , char cchar ) { lastCharWasSpecial = false ; /* If the character is '.' or '_' then append a space and mark\n                 * the next iteration to capitalize.\n\t\t\t\t */ if ( cchar == ' ' || cchar == ' ' ) { buffer . append ( ' ' ) ; capNextChar = true ; lastCharWasSpecial = false ; this . shouldContinue = false ; } } private void processCharWasUpperCase ( final StringBuilder buffer , int index , char cchar ) { /* If the character is uppercase, append a space and keep track\n                 * that the last character was uppercase for the next iteration.\n\t\t\t\t */ if ( Character . isUpperCase ( cchar ) ) { if ( index != 0 && ! lastCharWasUpperCase ) { buffer . append ( ' ' ) ; } lastCharWasUpperCase = true ; buffer . append ( cchar ) ; this . shouldContinue = false ; } else { lastCharWasUpperCase = false ; } } } GenerationCommand gc = new GenerationCommand ( ) ; gc . processFieldName ( ) ; /* This is a hack to get address.line_1 to work. */ return buffer . toString ( ) . replace ( \"  \" , \" \" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turn a single bytes into two hex character representation . [CODESPLIT] public CharSequence addHex ( final int decoded ) { int _location = location ; char [ ] _buffer = buffer ; int _capacity = capacity ; if ( 2 + _location > _capacity ) { _buffer = Chr . grow ( _buffer ) ; _capacity = _buffer . length ; } _buffer [ _location ] = ( char ) encodeNibbleToHexAsciiCharByte ( ( decoded >> 4 ) & 0x0F ) ; _location ++ ; _buffer [ _location ] = ( char ) encodeNibbleToHexAsciiCharByte ( decoded & 0x0F ) ; ; _location ++ ; location = _location ; buffer = _buffer ; capacity = _capacity ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RESPONSES FROM SERVER . [CODESPLIT] private void handleMessageFromServer ( String textResponse ) { if ( verbose ) { puts ( \"RESPONSE\" , url , ProtocolConstants . prettyPrintMessage ( textResponse ) ) ; puts ( \"RESPONSE\" , url ) ; puts ( ProtocolConstants . prettyPrintMessageWithLinesTabs ( textResponse ) ) ; } if ( textResponse . startsWith ( Action . GET . response ( ) . startsWith ( ) ) || textResponse . startsWith ( Action . SET_BROADCAST . response ( ) . startsWith ( ) ) ) { queue . put ( SingleResult . fromTextMessage ( textResponse ) ) ; } else if ( textResponse . startsWith ( Action . BATCH_READ . response ( ) . startsWith ( ) ) ) { queue . put ( BatchResult . fromTextMessage ( textResponse ) ) ; } else if ( textResponse . startsWith ( Action . GET_STATS . response ( ) . startsWith ( ) ) ) { queue . put ( StatsResults . fromTextMessage ( textResponse ) ) ; } else { if ( verbose ) { puts ( textResponse ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public SetRequest ( DataStoreSource source Action action long id String clientId long version long createTimeStamp long updateTimeStamp String key String payload ) { [CODESPLIT] @ Override public void set ( DataStoreSource source , String key , Object value ) { SetRequest request = new SetRequest ( source , Action . SET_SOURCE , messageId , clientId , 0 , 0 , 0 , key , serializer . serialize ( value ) . toString ( ) ) ; send ( request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for a key in the key / value store . [CODESPLIT] public KeyValueIterable < K , V > search ( K startKey ) { final KeyValueIterable < String , byte [ ] > search = store . search ( toKeyString ( startKey ) ) ; final Iterator < Entry < String , byte [ ] > > iterator = search . iterator ( ) ; return new KeyValueIterable < K , V > ( ) { @ Override public void close ( ) { search . close ( ) ; } @ Override public Iterator < Entry < K , V > > iterator ( ) { return new Iterator < Entry < K , V > > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public Entry < K , V > next ( ) { final Entry < String , byte [ ] > next = iterator . next ( ) ; return new Entry <> ( toKeyObject ( next . key ( ) ) , toValueObject ( next . value ( ) ) ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a value in the key / value store . [CODESPLIT] public void put ( K key , V value ) { store . put ( toKeyString ( key ) , toValueBytes ( value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all of these values from the key value store . [CODESPLIT] public void removeAll ( Iterable < K > keys ) { List < String > list = new ArrayList <> ( ) ; for ( K key : keys ) { list . add ( toKeyString ( key ) ) ; } store . removeAll ( list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from worker thread . [CODESPLIT] private void processReadQueue ( ) throws InterruptedException { ReadStatus readStatus = new ReadStatus ( ) ; while ( true ) { DataStoreRequest request = readOperationsQueue . poll ( dataStoreConfig . pollTimeoutMS ( ) , TimeUnit . MILLISECONDS ) ; while ( request != null ) { readStatus . tracker . addCall ( request , outputDataQueue ) ; readOperationsBatch . add ( request ) ; if ( readOperationsBatch . size ( ) > dataStoreConfig . processQueueMaxBatchSize ( ) ) { break ; } request = readOperationsQueue . poll ( ) ; } if ( readOperationsBatch . size ( ) > 0 ) { try { recievedReadBatch ( new ArrayList <> ( readOperationsBatch ) ) ; } finally { readOperationsBatch . clear ( ) ; } } else { flushReadsIfNeeded ( ) ; } if ( readStatus . readBatchSize . size ( ) > 1_000 ) { StatCount count ; final long now = Timer . timer ( ) . time ( ) ; count = new StatCount ( now , DataStoreSource . SERVER , Action . GET_STATS , \"Thread TIME USER  BaseDataStore \" + Thread . currentThread ( ) . getName ( ) , Sys . threadUserTime ( ) ) ; this . outputDataQueue . put ( count ) ; count = new StatCount ( now , DataStoreSource . SERVER , Action . GET_STATS , \"Thread TIME CPU  BaseDataStore \" + Thread . currentThread ( ) . getName ( ) , Sys . threadCPUTime ( ) ) ; this . outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , \"BaseDataStore readStatus.readBatchSize.max\" , readStatus . readBatchSize . max ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , \"BaseDataStore readStatus.readBatchSize.min\" , readStatus . readBatchSize . min ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , \"BaseDataStore readStatus.readBatchSize.median\" , readStatus . readBatchSize . median ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , \"BaseDataStore readStatus.readBatchSize.mean\" , readStatus . readBatchSize . mean ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , \"BaseDataStore readStatus.readBatchSize.standardDeviation\" , readStatus . readBatchSize . standardDeviation ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , \"BaseDataStore readStatus.readBatchSize.variance\" , readStatus . readBatchSize . variance ( ) ) ; outputDataQueue . put ( count ) ; readStatus . readBatchSize . clear ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called from worker thread . Processes the incoming queue for read and writes . [CODESPLIT] private void processWriteQueue ( ) throws InterruptedException { WriteStatus status = new WriteStatus ( ) ; while ( true ) { DataStoreRequest operation = writeOperationsQueue . poll ( dataStoreConfig . pollTimeoutMS ( ) , TimeUnit . MILLISECONDS ) ; while ( operation != null ) { status . tracker . addCall ( operation , outputDataQueue ) ; writeOperationsBatch . add ( operation ) ; if ( writeOperationsBatch . size ( ) > dataStoreConfig . processQueueMaxBatchSize ( ) ) { break ; } operation = writeOperationsQueue . poll ( ) ; } if ( writeOperationsBatch . size ( ) > 0 ) { try { status . writeBatchSize . add ( writeOperationsBatch . size ( ) ) ; recievedWriteBatch ( new ArrayList <> ( writeOperationsBatch ) ) ; } finally { writeOperationsBatch . clear ( ) ; } } else { flushWritesIfNeeded ( ) ; } if ( status . writeBatchSize . size ( ) > 1000 ) { status . sendBatchSize ( source , outputDataQueue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start up the queue handlers . [CODESPLIT] public void start ( ) { scheduledExecutorService = Executors . newScheduledThreadPool ( 2 , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable ) ; thread . setName ( \" DataQueue Process \" + source ) ; return thread ; } } ) ; future = scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { if ( stop . get ( ) ) { return ; } try { processWriteQueue ( ) ; } catch ( InterruptedException ex ) { //let it restart or stop } catch ( Exception ex ) { logger . fatal ( ex ) ; } } } , 0 , dataStoreConfig . threadErrorResumeTimeMS ( ) , TimeUnit . MILLISECONDS ) ; future = scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { if ( stop . get ( ) ) { return ; } try { processReadQueue ( ) ; } catch ( InterruptedException ex ) { //let it restart or stop } catch ( Exception ex ) { logger . fatal ( ex , \"Problem with base data store running scheduled job\" ) ; } } } , 0 , dataStoreConfig . threadErrorResumeTimeMS ( ) , TimeUnit . MILLISECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts character at index [CODESPLIT] @ Universal public static String atIndex ( String str , int index , char c ) { return idx ( str , index , c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets slice of a string . [CODESPLIT] @ Universal public static String slc ( String str , int start ) { return FastStringUtils . noCopyStringFromChars ( Chr . slc ( FastStringUtils . toCharArray ( str ) , start ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if chars is in another string [CODESPLIT] @ Universal public static boolean in ( char [ ] chars , String str ) { return Chr . in ( chars , FastStringUtils . toCharArray ( str ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a char to a string [CODESPLIT] @ Universal public static String add ( String str , char c ) { return FastStringUtils . noCopyStringFromChars ( Chr . add ( FastStringUtils . toCharArray ( str ) , c ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add many objects converted to strings together . Null are ignored so be careful . [CODESPLIT] public static String addObjects ( Object ... objects ) { int length = 0 ; for ( Object obj : objects ) { if ( obj == null ) { continue ; } length += obj . toString ( ) . length ( ) ; } CharBuf builder = CharBuf . createExact ( length ) ; for ( Object str : objects ) { if ( str == null ) { continue ; } builder . add ( str . toString ( ) ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets rid of null characters lurking in the string [CODESPLIT] public static String compact ( String str ) { return FastStringUtils . noCopyStringFromChars ( Chr . compact ( FastStringUtils . toCharArray ( str ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string [CODESPLIT] public static String [ ] split ( String str ) { char [ ] [ ] split = Chr . split ( FastStringUtils . toCharArray ( str ) ) ; return fromCharArrayOfArrayToStringArray ( split ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string by space [CODESPLIT] public static String [ ] splitBySpace ( String str ) { char [ ] [ ] split = CharScanner . splitBySpace ( FastStringUtils . toCharArray ( str ) ) ; return fromCharArrayOfArrayToStringArray ( split ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split a string by pipe [CODESPLIT] public static String [ ] splitByPipe ( String str ) { char [ ] [ ] split = CharScanner . splitByPipe ( FastStringUtils . toCharArray ( str ) ) ; return fromCharArrayOfArrayToStringArray ( split ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert arrays of chars to arrays of strings [CODESPLIT] public static String [ ] fromCharArrayOfArrayToStringArray ( char [ ] [ ] split ) { String [ ] results = new String [ split . length ] ; char [ ] array ; for ( int index = 0 ; index < split . length ; index ++ ) { array = split [ index ] ; results [ index ] = array . length == 0 ? EMPTY_STRING : FastStringUtils . noCopyStringFromChars ( array ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert to camel case and pass upper or lower [CODESPLIT] public static String camelCase ( String inStr , boolean upper ) { char [ ] in = FastStringUtils . toCharArray ( inStr ) ; char [ ] out = Chr . camelCase ( in , upper ) ; return FastStringUtils . noCopyStringFromChars ( out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if a string is inside of another [CODESPLIT] public static boolean insideOf ( String start , String inStr , String end ) { return Chr . insideOf ( FastStringUtils . toCharArray ( start ) , FastStringUtils . toCharArray ( inStr ) , FastStringUtils . toCharArray ( end ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert to under bar case [CODESPLIT] public static String underBarCase ( String inStr ) { char [ ] in = FastStringUtils . toCharArray ( inStr ) ; char [ ] out = Chr . underBarCase ( in ) ; return FastStringUtils . noCopyStringFromChars ( out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if they are equal or die [CODESPLIT] public static void equalsOrDie ( CharSequence a , CharSequence b ) { char [ ] ac = FastStringUtils . toCharArray ( a ) ; char [ ] bc = FastStringUtils . toCharArray ( b ) ; Chr . equalsOrDie ( ac , bc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if they are equal or die [CODESPLIT] public static void equalsOrDie ( String a , String b ) { if ( a == null && b == null ) { return ; } if ( a == null || b == null ) { die ( \"Values not equal value a=\" , a , \"value b=\" , b ) ; } char [ ] ac = FastStringUtils . toCharArray ( a ) ; char [ ] bc = FastStringUtils . toCharArray ( b ) ; Chr . equalsOrDie ( ac , bc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do a nice pretty print of a number . Add commas and such . [CODESPLIT] public static String num ( Number count ) { if ( count == null ) { return \"\" ; } if ( count instanceof Double || count instanceof BigDecimal ) { String s = count . toString ( ) ; if ( idx ( s , 1 ) == ' ' && s . length ( ) > 7 ) { s = slc ( s , 0 , 5 ) ; return s ; } else { return s ; } } else if ( count instanceof Integer || count instanceof Long || count instanceof Short || count instanceof BigInteger ) { String s = count . toString ( ) ; s = new StringBuilder ( s ) . reverse ( ) . toString ( ) ; CharBuf buf = CharBuf . create ( s . length ( ) ) ; int index = 0 ; for ( char c : s . toCharArray ( ) ) { index ++ ; buf . add ( c ) ; if ( index % 3 == 0 ) { buf . add ( ' ' ) ; } } if ( buf . lastChar ( ) == ' ' ) { buf . removeLastChar ( ) ; } s = buf . toString ( ) ; s = new StringBuilder ( s ) . reverse ( ) . toString ( ) ; return s ; } return count . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create a Sort that is a composite of other sorts . [CODESPLIT] public static Sort sorts ( Sort ... sorts ) { if ( sorts == null || sorts . length == 0 ) { return null ; } Sort main = sorts [ 0 ] ; for ( int index = 1 ; index < sorts . length ; index ++ ) { main . then ( sorts [ index ] ) ; } return main ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort if you already know the reflection fields . [CODESPLIT] public void sort ( List list , Map < String , FieldAccess > fields ) { Collections . sort ( list , this . comparator ( fields ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort and you look up the reflection fields . [CODESPLIT] public void sort ( List list ) { if ( list == null || list . size ( ) == 0 ) { return ; } Object item = list . iterator ( ) . next ( ) ; Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( item ) ; Collections . sort ( list , this . comparator ( fields ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort and you look up the reflection fields . [CODESPLIT] public < T > Collection < T > sort ( Class < T > componentClass , Collection < T > collection ) { if ( collection instanceof List ) { sort ( ( List ) collection ) ; return collection ; } if ( collection == null || collection . size ( ) == 0 ) { return Collections . EMPTY_LIST ; } Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( componentClass ) ; T [ ] array = toArray ( componentClass , collection ) ; Arrays . sort ( array , this . comparator ( fields ) ) ; if ( collection instanceof Set ) { return new LinkedHashSet <> ( Lists . list ( array ) ) ; } else { return Lists . list ( array ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort and you look up the reflection fields . [CODESPLIT] public < T > Iterable < T > sort ( Class < T > componentClass , Iterable < T > iterable ) { if ( iterable instanceof List ) { sort ( ( List ) iterable ) ; return iterable ; } if ( iterable instanceof Collection ) { return sort ( componentClass , ( Collection ) iterable ) ; } if ( iterable == null ) { return Collections . EMPTY_LIST ; } List < T > list = Lists . list ( iterable ) ; sort ( list ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort and you look up the reflection fields . [CODESPLIT] public < T > void sort ( T [ ] array ) { if ( array == null || array . length == 0 ) { return ; } Object item = array [ 0 ] ; Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( item ) ; Arrays . sort ( array , this . comparator ( fields ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is what really does the magic . This is the comparator creator . [CODESPLIT] public Comparator comparator ( Map < String , FieldAccess > fields ) { if ( comparator == null ) { comparator = universalComparator ( this . getName ( ) , fields , this . getType ( ) , this . childComparators ( fields ) ) ; } return comparator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This creates a list of children comparators based on the child list . [CODESPLIT] private List < Comparator > childComparators ( Map < String , FieldAccess > fields ) { if ( this . comparators == null ) { this . comparators = new ArrayList <> ( this . sorts . size ( ) + 1 ) ; for ( Sort sort : sorts ) { Comparator comparator = universalComparator ( sort . getName ( ) , fields , sort . getType ( ) , sort . childComparators ( fields ) ) ; this . comparators . add ( comparator ) ; } } return this . comparators ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grabs the last value from a tree map ( Navigable map ) . [CODESPLIT] @ Universal public static < K , V > V last ( NavigableMap < K , V > map ) { return map . lastEntry ( ) . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grabs the value after this key from a tree map ( Navigable map ) . [CODESPLIT] @ Universal public static < K , V > V after ( NavigableMap < K , V > map , final K index ) { return map . get ( map . higherKey ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grabs the value before this key from a tree map ( Navigable map ) . [CODESPLIT] @ Universal public static < K , V > V before ( NavigableMap < K , V > map , final K index ) { return map . get ( map . lowerKey ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "End universal methods . [CODESPLIT] public static < K , V > boolean valueIn ( V value , Map < K , V > map ) { return map . containsValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if two values are the same [CODESPLIT] public static boolean equalsOrDie ( int expected , int got ) { if ( expected != got ) { return die ( Boolean . class , \"Expected was\" , expected , \"but we got \" , got ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if two arrays are equals [CODESPLIT] public static boolean equalsOrDie ( int [ ] expected , int [ ] got ) { if ( expected . length != got . length ) { die ( \"Lengths did not match, expected length\" , expected . length , \"but got\" , got . length ) ; } for ( int index = 0 ; index < expected . length ; index ++ ) { if ( expected [ index ] != got [ index ] ) { die ( \"value at index did not match index\" , index , \"expected value\" , expected [ index ] , \"but got\" , got [ index ] ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sum Provides overflow protection . [CODESPLIT] public static int sum ( int [ ] values , int start , int length ) { long sum = 0 ; for ( int index = start ; index < length ; index ++ ) { sum += values [ index ] ; } if ( sum < Integer . MIN_VALUE ) { die ( \"overflow the sum is too small\" , sum ) ; } if ( sum > Integer . MAX_VALUE ) { die ( \"overflow the sum is too big\" , sum ) ; } return ( int ) sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Max [CODESPLIT] public static int max ( int [ ] values , final int start , final int length ) { int max = Integer . MIN_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] > max ) { max = values [ index ] ; } } return max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Min [CODESPLIT] public static int min ( int [ ] values , final int start , final int length ) { int min = Integer . MAX_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] < min ) min = values [ index ] ; } return min ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate standard deviation . [CODESPLIT] public static double standardDeviation ( Collection < ? > inputList , String propertyPath ) { double variance = variance ( inputList , propertyPath ) ; return Math . round ( Math . sqrt ( variance ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate standard deviation . [CODESPLIT] public static int median ( Collection < ? > inputList , String propertyPath ) { return IntList . toIntList ( inputList , propertyPath ) . median ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Round up to the nearest power of 2 [CODESPLIT] public static int roundUpToPowerOf2 ( int number ) { int rounded = number >= 1_000 ? 1_000 : ( rounded = Integer . highestOneBit ( number ) ) != 0 ? ( Integer . bitCount ( number ) > 1 ) ? rounded << 1 : rounded : 1 ; return rounded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The doGetMessageFromBundle does a bit of magic . If the message starts with { than it assumes it is an i18N message and looks it up in the resource bundle . If it starts with # { it assumes it is an expression and uses OGNL JSF EL or the Universal EL to look up the expression in the context . [CODESPLIT] private String doGetMessageFromBundle ( String key ) { if ( resourceBundleLocator == null ) { return null ; } /* Find the resourceBundle. */ ResourceBundle bundle = this . resourceBundleLocator . getBundle ( ) ; if ( bundle == null ) { return null ; } String message = null ; //holds the message\r /* If the message starts with an i18nMarker look it up\r\n         * in the resource bundle.\r\n    \t */ if ( key . startsWith ( this . i18nMarker ) ) { try { key = key . substring ( 1 , key . length ( ) - 1 ) ; message = lookupMessageInBundle ( key , bundle , message ) ; } catch ( MissingResourceException mre ) { message = key ; } } else { /*\r\n             * If it does not start with those markers see if it has a \".\". If\r\n\t\t\t * it has a dot, try to look it up. If it is not found then just\r\n\t\t\t * return the key as the message.\r\n\t\t\t */ if ( key . contains ( \".\" ) ) { try { message = lookupMessageInBundle ( key , bundle , message ) ; } catch ( MissingResourceException mre ) { message = key ; } } else { message = key ; } } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the work horse . It does all of the sorting work for the simple cases . Nulls are last by default . [CODESPLIT] public static void sort ( List list , String sortBy , Map < String , FieldAccess > fields , boolean ascending ) { sort ( list , sortBy , fields , ascending , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the work horse . It does all of the sorting work for the simple cases . [CODESPLIT] public static void sort ( List list , String sortBy , Map < String , FieldAccess > fields , boolean ascending , boolean nullsFirst ) { try { /* If this list is null or empty, we have nothing to do so return. */ if ( list == null || list . size ( ) == 0 ) { return ; } /* Grab the first item in the list and see what it is. */ Object o = list . get ( 0 ) ; /* if the sort by string is is this, and the object is comparable then use the objects\n            themselves for the sort.\n             */ if ( sortBy . equals ( \"this\" ) ) { Collections . sort ( list , thisUniversalComparator ( ascending , nullsFirst ) ) ; return ; } /* If you did not sort by \"this\", then sort by the field. */ final FieldAccess field = fields . get ( sortBy ) ; if ( field != null ) { Collections . sort ( list , Sorting . universalComparator ( field , ascending , nullsFirst ) ) ; } } catch ( Exception ex ) { Exceptions . handle ( ex , \"list\" , list , \"\\nsortBy\" , sortBy , \"fields\" , fields , \"ascending\" , ascending , \"nullFirst\" , nullsFirst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main exit from system . <p / > <p / > If you are debugging something not coming out of the system . Start here . [CODESPLIT] private void handleResponseFromDataStore ( Result result ) { if ( debug ) { logger . info ( \"ResponseHandler::handleResponseFromDataStore\" , result ) ; } if ( result instanceof SingleResult ) { SingleResult singleResult = ( SingleResult ) result ; int size = handleSingleResult ( singleResult ) ; counter ( size , singleResult . source ( ) ) ; } else if ( result instanceof SearchBatchResult ) { SearchBatchResult searchBatchResult = ( SearchBatchResult ) result ; sendBatchResponse ( ( BatchResult ) result ) ; int size = searchBatchResult . getResults ( ) . size ( ) ; counter ( size , searchBatchResult . source ( ) ) ; } else if ( result instanceof BatchResult ) { BatchResult batchResult = ( BatchResult ) result ; int size = handleBatchResult ( batchResult ) ; counter ( size , batchResult . source ( ) ) ; } else if ( result instanceof ErrorResult ) { ErrorResult errorResult = ( ErrorResult ) result ; int size = handleErrorResult ( errorResult ) ; counter ( size , errorResult . source ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fromMap converts a map into a java object [CODESPLIT] @ Override public < T > T fromMap ( final Map < String , Object > map , final Class < T > cls ) { T toObject = Reflection . newInstance ( cls ) ; Map < String , FieldAccess > fields = fieldsAccessor . getFields ( toObject . getClass ( ) ) ; Set < Map . Entry < String , Object > > mapKeyValuesEntrySet = map . entrySet ( ) ; /* Iterate through the map keys/values. */ for ( Map . Entry < String , Object > mapEntry : mapKeyValuesEntrySet ) { /* Get the field name. */ String key = mapEntry . getKey ( ) ; if ( ignoreSet != null ) { if ( ignoreSet . contains ( key ) ) { continue ; } } /* Get the field and if it missing then ignore this map entry. */ FieldAccess field = fields . get ( fieldsAccessor . isCaseInsensitive ( ) ? key . toLowerCase ( ) : key ) ; if ( field == null ) { continue ; } /* Check the view if it is active. */ if ( view != null ) { if ( ! field . isViewActive ( view ) ) { continue ; } } /* Check respects ignore is active.\n             * Then needs to be a chain of responsibilities.\n             * */ if ( respectIgnore ) { if ( field . ignore ( ) ) { continue ; } } /* Get the value from the map. */ Object value = mapEntry . getValue ( ) ; /* If the value is a Value (a index overlay), then convert ensure it is not a container and inject\n            it into the field, and we are done so continue.\n             */ if ( value instanceof Value ) { if ( ( ( Value ) value ) . isContainer ( ) ) { value = ( ( Value ) value ) . toValue ( ) ; } else { field . setFromValue ( toObject , ( Value ) value ) ; continue ; } } /* If the value is null, then inject an null value into the field.\n            * Notice we do not check to see if the field is a primitive, if\n            * it is we die which is the expected behavior.\n            */ if ( value == null ) { field . setObject ( toObject , null ) ; continue ; } /* if the value's type and the field type are the same or\n            the field just takes an object, then inject what we have as is.\n             */ if ( value . getClass ( ) == field . type ( ) || field . type ( ) == Object . class ) { field . setValue ( toObject , value ) ; } else if ( Typ . isBasicType ( value ) ) { field . setValue ( toObject , value ) ; } /* See if it is a map<string, object>, and if it is then process it.\n             *  REFACTOR:\n             *  It looks like we are using some utility classes here that we could have used in\n             *  oldMatchAndConvertArgs.\n             *  REFACTOR\n              * */ else if ( value instanceof Map ) { setFieldValueFromMap ( toObject , field , ( Map ) value ) ; } else if ( value instanceof Collection ) { /*It is a collection so process it that way. */ processCollectionFromMapUsingFields ( toObject , field , ( Collection ) value ) ; } else if ( value instanceof Map [ ] ) { /* It is an array of maps so, we need to process it as such. */ processArrayOfMaps ( toObject , field , ( Map < String , Object > [ ] ) value ) ; } else { /* If we could not determine how to convert it into some field\n                object then we just go ahead an inject it using setValue which\n                will call Conversion.coerce.\n                 */ field . setValue ( toObject , value ) ; } } return toObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject a map into an object s field . [CODESPLIT] private void setFieldValueFromMap ( final Object parentObject , final FieldAccess field , final Map mapInner ) { Class < ? > fieldClassType = field . type ( ) ; Object value = null ; /* Is the field not a map. */ if ( ! Typ . isMap ( fieldClassType ) ) { if ( ! fieldClassType . isInterface ( ) && ! Typ . isAbstract ( fieldClassType ) ) { value = fromMap ( mapInner , field . type ( ) ) ; } else { Object oClassName = mapInner . get ( \"class\" ) ; if ( oClassName != null ) { value = fromMap ( mapInner , Reflection . loadClass ( oClassName . toString ( ) ) ) ; } else { value = null ; } } /*\n           REFACTOR:\n           This is at least the third time that I have seen this code in the class.\n            It was either cut and pasted or I forgot I wrote it three times.\n           REFACTOR:\n             */ } else if ( Typ . isMap ( fieldClassType ) ) { Class keyType = ( Class ) field . getParameterizedType ( ) . getActualTypeArguments ( ) [ 0 ] ; Class valueType = ( Class ) field . getParameterizedType ( ) . getActualTypeArguments ( ) [ 1 ] ; Set < Map . Entry > set = mapInner . entrySet ( ) ; Map newMap = new LinkedHashMap ( ) ; for ( Map . Entry entry : set ) { Object evalue = entry . getValue ( ) ; Object key = entry . getKey ( ) ; if ( evalue instanceof ValueContainer ) { evalue = ( ( ValueContainer ) evalue ) . toValue ( ) ; } key = Conversions . coerce ( keyType , key ) ; evalue = Conversions . coerce ( valueType , evalue ) ; newMap . put ( key , evalue ) ; } value = newMap ; } field . setValue ( parentObject , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an object to a list . [CODESPLIT] @ Override public List < ? > toList ( Object object ) { TypeType instanceType = TypeType . getInstanceType ( object ) ; switch ( instanceType ) { case NULL : return Lists . list ( ( Object ) null ) ; case ARRAY : case ARRAY_INT : case ARRAY_BYTE : case ARRAY_SHORT : case ARRAY_FLOAT : case ARRAY_DOUBLE : case ARRAY_LONG : case ARRAY_STRING : case ARRAY_OBJECT : return Conversions . toList ( object ) ; case INSTANCE : if ( Reflection . respondsTo ( object , \"toList\" ) ) { return ( List < ? > ) Reflection . invoke ( object , \"toList\" ) ; } break ; } return Lists . list ( object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles a match . [CODESPLIT] private Pattern compileRegex ( String match ) { Pattern pattern = compiledRegexCache . get ( match ) ; if ( pattern == null ) { pattern = Pattern . compile ( match ) ; compiledRegexCache . put ( match , pattern ) ; } return pattern ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override public KeyValueIterable < String , VersionedEntry < String , byte [ ] > > loadAll ( ) { if ( debug ) logger . info ( \"LOAD ALL  \" ) ; initIfNeeded ( ) ; try { final ResultSet resultSet = loadAll . executeQuery ( ) ; return new KeyValueIterable < String , VersionedEntry < String , byte [ ] > > ( ) { @ Override public void close ( ) { closeResultSet ( resultSet ) ; } @ Override public Iterator < Entry < String , VersionedEntry < String , byte [ ] > > > iterator ( ) { return new Iterator < Entry < String , VersionedEntry < String , byte [ ] > > > ( ) { @ Override public boolean hasNext ( ) { return resultSetNext ( resultSet ) ; } @ Override public Entry < String , VersionedEntry < String , byte [ ] > > next ( ) { try { String key = resultSet . getString ( KEY_POS ) ; byte [ ] value = getValueColumn ( VALUE_POS , resultSet ) ; long version = resultSet . getLong ( VERSION_POS ) ; long update = resultSet . getLong ( UPDATE_POS ) ; long create = resultSet . getLong ( CREATE_POS ) ; VersionedEntry < String , byte [ ] > returnValue = new VersionedEntry <> ( key , value ) ; returnValue . setCreateTimestamp ( create ) ; returnValue . setUpdateTimestamp ( update ) ; returnValue . setVersion ( version ) ; return new Entry <> ( key , returnValue ) ; } catch ( SQLException e ) { handle ( \"Unable to extract values for loadAllByKeys query\" , e ) ; return null ; } } @ Override public void remove ( ) { } } ; } } ; } catch ( SQLException e ) { handle ( \"Unable to load all records\" , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create load all keys SQL . [CODESPLIT] protected void createLoadAllVersionDataSQL ( String table ) { CharBuf buf = CharBuf . create ( 100 ) ; buf . add ( \"select kv_key, 1, version, update_timestamp, create_timestamp from `\" ) ; buf . add ( table ) ; buf . add ( \"` where kv_key in (\" ) ; buf . multiply ( \"?,\" , this . loadKeyCount ) ; buf . removeLastChar ( ) ; buf . add ( \");\" ) ; this . loadAllVersionDataByKeysSQL = buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clones each list item into a new instance with copied fields . It is like doing a clone operation . [CODESPLIT] @ Universal public static < V > List < V > deepCopy ( List < V > list ) { if ( list instanceof LinkedList ) { return deepCopyToList ( list , new LinkedList < V > ( ) ) ; } else if ( list instanceof CopyOnWriteArrayList ) { return deepCopyToList ( list , new CopyOnWriteArrayList < V > ( ) ) ; } else { return deepCopy ( ( Collection ) list ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * End universal methods . [CODESPLIT] private static < T > int calculateIndex ( List < T > list , int originalIndex ) { final int length = list . size ( ) ; int index = originalIndex ; /* Adjust for reading from the right as in\n        -1 reads the 4th element if the length is 5\n         */ if ( index < 0 ) { index = ( length + index ) ; } /* Bounds check\n            if it is still less than 0, then they\n            have an negative index that is greater than length\n         */ if ( index < 0 ) { index = 0 ; } if ( index > length ) { index = length ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if we have a string field . [CODESPLIT] public static boolean hasStringField ( final Object value1 , final String name ) { Class < ? > clz = value1 . getClass ( ) ; return classHasStringField ( clz , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if this class has a string field . [CODESPLIT] public static boolean classHasStringField ( Class < ? > clz , String name ) { List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( field . getType ( ) . equals ( Typ . string ) && field . getName ( ) . equals ( name ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if a class has a field . [CODESPLIT] public static boolean classHasField ( Class < ? > clz , String name ) { List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( field . getName ( ) . equals ( name ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This can be used for default sort . [CODESPLIT] public static String getFirstComparableOrPrimitiveFromClass ( Class < ? > clz ) { List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( ( field . getType ( ) . isPrimitive ( ) || Typ . isComparable ( field . getType ( ) ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) ) { return field . getName ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getFirstStringFieldNameEndsWith [CODESPLIT] public static String getFirstStringFieldNameEndsWith ( Object value , String name ) { return getFirstStringFieldNameEndsWithFromClass ( value . getClass ( ) , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getFirstStringFieldNameEndsWithFromClass [CODESPLIT] public static String getFirstStringFieldNameEndsWithFromClass ( Class < ? > clz , String name ) { List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( field . getName ( ) . endsWith ( name ) && field . getType ( ) . equals ( Typ . string ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) { return field . getName ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the first sortable fields found . [CODESPLIT] public static String getSortableField ( Object value1 ) { if ( value1 instanceof Map ) { return getSortableFieldFromMap ( ( Map < String , ? > ) value1 ) ; } else { return getSortableFieldFromClass ( value1 . getClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Comparison of entries this determines what we will order the cache by which determines which type of cache it is . [CODESPLIT] @ Override public final int compareTo ( CacheEntry other ) { switch ( type ) { case LFU : return compareToLFU ( other ) ; case LRU : return compareToLRU ( other ) ; case FIFO : return compareToFIFO ( other ) ; default : die ( ) ; return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare the time . [CODESPLIT] private final int compareTime ( CacheEntry other ) { if ( time > other . time ) { //this time stamp is  greater so it has higher priority return 1 ; } else if ( time < other . time ) { //this time stamp is lower so it has lower priority return - 1 ; } else if ( time == other . time ) { //equal priority return 0 ; } die ( ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a list an an array or sorts [CODESPLIT] public static void sort ( List list , Sort ... sorts ) { Sort . sorts ( sorts ) . sort ( list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort a list . [CODESPLIT] public static void sort ( List list , String sortBy , boolean ascending , boolean nullsFirst ) { if ( list == null || list . size ( ) == 0 ) { return ; } if ( sortBy . equals ( \"this\" ) ) { Collections . sort ( list , thisUniversalComparator ( ascending , nullsFirst ) ) ; return ; } Iterator iterator = list . iterator ( ) ; Object object = iterator . next ( ) ; Map < String , FieldAccess > fields = null ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; } else { while ( iterator . hasNext ( ) ) { object = iterator . next ( ) ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; break ; } } } if ( fields != null ) { final FieldAccess field = fields . get ( sortBy ) ; if ( field != null ) { Collections . sort ( list , Sorting . universalComparator ( field , ascending , nullsFirst ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort collection . [CODESPLIT] public static < V > Collection < V > sort ( Class < V > componentType , Collection < V > collection , String sortBy , boolean ascending , boolean nullsFirst ) { if ( collection instanceof List ) { sort ( ( List ) collection , sortBy , ascending , nullsFirst ) ; return collection ; } else { V [ ] array = toArray ( componentType , collection ) ; sort ( array , sortBy , ascending , nullsFirst ) ; if ( collection instanceof LinkedHashSet ) { return new LinkedHashSet <> ( Lists . list ( array ) ) ; } else { return Lists . list ( array ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort map entries . [CODESPLIT] public static < K , V > Collection < Map . Entry < K , V > > sortEntries ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { return sort ( ( Class ) componentType , ( Collection ) map . entrySet ( ) , sortBy , ascending , nullsFirst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort map values . [CODESPLIT] public static < K , V > Collection < Map . Entry < K , V > > sortValues ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { return sort ( ( Class ) componentType , ( Collection ) map . values ( ) , sortBy , ascending , nullsFirst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort map keys . [CODESPLIT] public static < K , V > Collection < Map . Entry < K , V > > sortKeys ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { return sort ( ( Class ) componentType , ( Collection ) map . keySet ( ) , sortBy , ascending , nullsFirst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort collection . [CODESPLIT] public static < V > Iterable < V > sort ( Class < V > componentType , Iterable < V > iterable , String sortBy , boolean ascending , boolean nullsFirst ) { if ( iterable instanceof List ) { sort ( ( List ) iterable , sortBy , ascending , nullsFirst ) ; return iterable ; } else if ( iterable instanceof Collection ) { return sort ( componentType , ( Collection < V > ) iterable , sortBy , ascending , nullsFirst ) ; } else { List < V > list = Lists . list ( iterable ) ; sort ( list , sortBy , ascending , nullsFirst ) ; return list ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sort an array . [CODESPLIT] public static < T > void sort ( T [ ] array , String sortBy , boolean ascending , boolean nullsFirst ) { if ( array == null || array . length == 0 ) { return ; } if ( sortBy . equals ( \"this\" ) ) { Arrays . sort ( array , thisUniversalComparator ( ascending , nullsFirst ) ) ; return ; } Object object = array [ 0 ] ; Map < String , FieldAccess > fields = null ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; } else { for ( int index = 1 ; index < array . length ; index ++ ) { object = array [ index ] ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; break ; } } } if ( fields != null ) { final FieldAccess field = fields . get ( sortBy ) ; if ( field != null ) { Arrays . sort ( array , Sorting . universalComparator ( field , ascending , nullsFirst ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This creates the universal comparator object which is used by the sort work horse . [CODESPLIT] public static Comparator universalComparator ( final FieldAccess field , final boolean ascending , final boolean nullsFirst ) { return new Comparator ( ) { @ Override public int compare ( Object o1 , Object o2 ) { Object value1 = null ; Object value2 = null ; if ( ascending ) { value1 = field . getValue ( o1 ) ; value2 = field . getValue ( o2 ) ; } else { value1 = field . getValue ( o2 ) ; value2 = field . getValue ( o1 ) ; } return Sorting . compare ( value1 , value2 , nullsFirst ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This creates the universal comparator object used for this . [CODESPLIT] public static Comparator thisUniversalComparator ( final boolean ascending , final boolean nullsFirst ) { return new Comparator ( ) { @ Override public int compare ( Object o1 , Object o2 ) { Object value1 ; Object value2 ; if ( ascending ) { value1 = ( o1 ) ; value2 = ( o2 ) ; } else { value1 = ( o2 ) ; value2 = ( o1 ) ; } return Sorting . compare ( value1 , value2 , nullsFirst ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This compares two values . If the objects are strings ( CharSequence ) they are always compared lexicographically . If the objects are comparable they are always compared using a natural order . [CODESPLIT] public static int compare ( Object value1 , Object value2 , boolean nullsLast ) { if ( value1 == null && value2 == null ) { return 0 ; } else if ( value1 == null && value2 != null ) { return nullsLast ? - 1 : 1 ; } else if ( value1 != null && value2 == null ) { return nullsLast ? 1 : - 1 ; } /** Objects are string like so compare using collator. */ if ( value1 instanceof CharSequence ) { String str1 = Conversions . toString ( value1 ) ; String str2 = Conversions . toString ( value2 ) ; Collator collator = Collator . getInstance ( ) ; return collator . compare ( str1 , str2 ) ; /** Objects are comparable, yeah! */ } else if ( Typ . isComparable ( value1 ) && value1 . getClass ( ) == value2 . getClass ( ) ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Integer && value2 instanceof Integer ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Double && value2 instanceof Double ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Long && value2 instanceof Long ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Number && value2 instanceof Number ) { Double c1 = Conversions . toDouble ( value1 ) ; Double c2 = Conversions . toDouble ( value2 ) ; return c1 . compareTo ( c2 ) ; } else { /** Object are neither String like or comparable.\n             * Ours it not to reason why, ours it to do or die.\n             * Find the first sortable field and sort by that.\n             * */ String name = Fields . getSortableField ( value1 ) ; String sv1 = ( String ) BeanUtils . getPropByPath ( value1 , name ) ; String sv2 = ( String ) BeanUtils . getPropByPath ( value2 , name ) ; return Sorting . compare ( sv1 , sv2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value from the cache . It does not touch the lock so reads are fast . This does not touch the order list so it is fast . [CODESPLIT] public VALUE get ( KEY key ) { CacheEntry < KEY , VALUE > cacheEntry = map . get ( key ) ; if ( cacheEntry != null ) { cacheEntry . readCount . incrementAndGet ( ) ; return cacheEntry . value ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used for testing as it gets the value without updating stats [CODESPLIT] public VALUE getSilent ( KEY key ) { CacheEntry < KEY , VALUE > cacheEntry = map . get ( key ) ; if ( cacheEntry != null ) { return cacheEntry . value ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the key . This touches the lock . So removes are ** not ** fast . [CODESPLIT] @ Override public void remove ( KEY key ) { CacheEntry < KEY , VALUE > entry = map . remove ( key ) ; if ( entry != null ) { list . remove ( entry ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put the value . This touches the lock so puts are ** not ** fast . [CODESPLIT] public void put ( KEY key , VALUE value ) { CacheEntry < KEY , VALUE > entry = map . get ( key ) ; if ( entry == null ) { entry = new CacheEntry <> ( key , value , order ( ) , type , time ( ) ) ; list . add ( entry ) ; map . put ( key , entry ) ; } else { entry . readCount . incrementAndGet ( ) ; entry . value = value ; } evictIfNeeded ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Avoid overflow . [CODESPLIT] private final int order ( ) { int order = count . incrementAndGet ( ) ; if ( order > Integer . MAX_VALUE - 100 ) { count . set ( 0 ) ; } return order ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evict if we are over the size limit . [CODESPLIT] private final void evictIfNeeded ( ) { if ( list . size ( ) > evictSize ) { final List < CacheEntry < KEY , VALUE > > killList = list . sortAndReturnPurgeList ( 0.1f ) ; for ( CacheEntry < KEY , VALUE > cacheEntry : killList ) { map . remove ( cacheEntry . key ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the actual validation . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public ValidatorMessageHolder validate ( Object fieldValue , String fieldLabel ) { ValidatorMessage validatorMessage = new ValidatorMessage ( ) ; if ( fieldValue == null ) { return validatorMessage ; } dynamicallyInitIfNeeded ( fieldValue ) ; if ( ! super . isValueGreaterThanMin ( ( Comparable ) fieldValue ) ) { populateMessage ( underMin , validatorMessage , fieldLabel , min ) ; } else if ( ! super . isValueLessThanMax ( ( Comparable ) fieldValue ) ) { populateMessage ( overMax , validatorMessage , fieldLabel , max ) ; } return validatorMessage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Initialize this instance . [CODESPLIT] public void init ( ) { /* If the underMin message was not injected, create a default. */ if ( underMin == null ) { underMin = new MessageSpecification ( ) ; underMin . setDetailMessage ( \"{validator.range.underMin.detail}\" ) ; underMin . setSummaryMessage ( \"{validator.range.underMin.summary}\" ) ; } /* If the overMax message was not injected, create a default. */ if ( overMax == null ) { overMax = new MessageSpecification ( ) ; overMax . setDetailMessage ( \"{validator.range.overMax.detail}\" ) ; overMax . setSummaryMessage ( \"{validator.range.overMax.summary\" ) ; } /* If the type was not injected, stop initialization. */ if ( type == null ) { return ; } /* Initialize based on type for all Integer value\r\n         * so that LongRangeValidator can be used\r\n    \t * for int, short, byte, and long. */ if ( ! isInitialized ( ) ) { if ( type . equals ( Integer . class ) ) { init ( new Integer ( min . intValue ( ) ) , new Integer ( max . intValue ( ) ) ) ; } else if ( type . equals ( Byte . class ) ) { init ( new Byte ( min . byteValue ( ) ) , new Byte ( max . byteValue ( ) ) ) ; } else if ( type . equals ( Short . class ) ) { init ( new Short ( min . byteValue ( ) ) , new Short ( max . byteValue ( ) ) ) ; } else { init ( min , max ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the type was not initialized we can still figure it out at runtime . [CODESPLIT] private void dynamicallyInitIfNeeded ( Object value ) { /* Check to see if this class was already initialized,\r\n         * if not, initialize it based on the type of the value.\r\n\t\t */ if ( ! isInitialized ( ) ) { if ( value instanceof Integer ) { init ( new Integer ( min . intValue ( ) ) , new Integer ( max . intValue ( ) ) ) ; } else if ( value instanceof Byte ) { init ( new Byte ( min . byteValue ( ) ) , new Byte ( max . byteValue ( ) ) ) ; } else if ( value instanceof Short ) { init ( new Short ( min . shortValue ( ) ) , new Short ( max . shortValue ( ) ) ) ; } else { init ( min , max ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static < V > V [ ] array ( Class < V > type , final Collection < V > array ) { return Conversions . toArray ( type , array ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This flattens a list . [CODESPLIT] public static Object unifyListOrArray ( Object o , List list ) { if ( o == null ) { return null ; } boolean isArray = o . getClass ( ) . isArray ( ) ; if ( list == null && ! isArray && ! ( o instanceof Iterable ) ) { return o ; } if ( list == null ) { list = new LinkedList ( ) ; } if ( isArray ) { int length = Array . getLength ( o ) ; for ( int index = 0 ; index < length ; index ++ ) { Object o1 = Array . get ( o , index ) ; if ( o1 instanceof Iterable || o . getClass ( ) . isArray ( ) ) { unifyListOrArray ( o1 , list ) ; } else { list . add ( o1 ) ; } } } else if ( o instanceof Collection ) { Collection i = ( ( Collection ) o ) ; for ( Object item : i ) { if ( item instanceof Iterable || o . getClass ( ) . isArray ( ) ) { unifyListOrArray ( item , list ) ; } else { list . add ( item ) ; } } } else { list . add ( o ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This flattens a list . [CODESPLIT] public static Object unifyList ( Object o , List list ) { if ( o == null ) { return null ; } if ( list == null ) { list = new ArrayList ( ) ; } if ( o instanceof Iterable ) { Iterable i = ( ( Iterable ) o ) ; for ( Object item : i ) { unifyListOrArray ( item , list ) ; } } else { list . add ( o ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This gets called from the http post handler or event bus handler . [CODESPLIT] public final ByteBuffer allocateBuffer ( int size ) { if ( RECYCLE_BUFFER ) { ByteBuffer spentBuffer = recycleChannel . poll ( ) ; if ( spentBuffer == null ) { spentBuffer = ByteBuffer . allocateDirect ( size ) ; } spentBuffer . clear ( ) ; return spentBuffer ; } else { return ByteBuffer . allocateDirect ( size ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if it is time to stop We have been interrupted . Should we ignore it or break out of the loop . [CODESPLIT] private boolean determineIfWeShouldExit ( ) { boolean shouldStop = stop . get ( ) ; if ( ! shouldStop ) { Thread . interrupted ( ) ; } else { System . out . println ( \"Exiting processing loop as requested\" ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queue and batch writer main logic . This is where the magic happens . [CODESPLIT] private void manageInputWriterChannel ( ) throws InterruptedException { try { ByteBuffer dataToWriteToFile ; dataToWriteToFile = inputChannel . poll ( ) ; //no wait //If it is null, it means the inputChannel is empty and we need to flush. if ( dataToWriteToFile == null ) { queueEmptyMaybeFlush ( ) ; dataToWriteToFile = inputChannel . poll ( ) ; } //If it is still null, this means that we need to wait //for more items to show up in the inputChannel. if ( dataToWriteToFile == null ) { dataToWriteToFile = waitForNextDataToWrite ( ) ; } //We have to check for null again because we could have been interrupted. if ( dataToWriteToFile != null ) { //Write it writer . nextBufferToWrite ( dataToWriteToFile ) ; //Then give it back if ( RECYCLE_BUFFER ) { recycleChannel . offer ( dataToWriteToFile ) ; } } } catch ( InterruptedException ex ) { throw ex ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; ex . printStackTrace ( System . err ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If we detect that the in - coming transfer outputDataQueue channel is empty then it could be an excellent time to sync to disk . [CODESPLIT] private void queueEmptyMaybeFlush ( ) { if ( PERIODIC_FORCE_FLUSH ) { long currentTime = time . get ( ) ; /* Try not to flush more than once every x times per mili-seconds time period. */ if ( ( currentTime - lastFlushTime ) > FORCE_FLUSH_AFTER_THIS_MANY_MILI_SECONDS ) { /* If the writer had things to flush, and we flushed then\n                increment the number of flushes.\n                 */ if ( writer . syncToDisk ( ) ) { //could take 100 ms to 1 second this . numberOfFlushesTotal . incrementAndGet ( ) ; } /* We update the flush time no matter what. */ lastFlushTime = time . get ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If we don t have any data and we have flushed then we can wait on the outputDataQueue . There is no sense spin - locking . The poll ( time timeunit ) call will block until there is something to do or until the timeout . [CODESPLIT] private ByteBuffer waitForNextDataToWrite ( ) throws InterruptedException { ByteBuffer dataToWriteToFile ; dataToWriteToFile = inputChannel . poll ( FORCE_FLUSH_AFTER_THIS_MANY_MILI_SECONDS , TimeUnit . MILLISECONDS ) ; return dataToWriteToFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start up the health monitor . [CODESPLIT] private void startMonitor ( ) { final ScheduledExecutorService monitor = Executors . newScheduledThreadPool ( 2 , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable ) ; thread . setPriority ( Thread . NORM_PRIORITY + 1 ) ; return thread ; } } ) ; monitorFuture = monitor . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { monitor ( ) ; } } , MONITOR_INTERVAL_SECONDS , MONITOR_INTERVAL_SECONDS , TimeUnit . SECONDS ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( new Runnable ( ) { @ Override public void run ( ) { System . err . println ( \"shutting down....\" ) ; monitor ( ) ; } } ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts up the batch writer . [CODESPLIT] public void start ( final TimeAware receiver ) { //This starts itself up again every 1/2 second if something really bad //happens like disk full. As soon as the problem gets corrected //then things start working again...happy day.    Only // one is running per instance of CollectionManagerImpl. writerFuture = scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { processWrites ( ) ; } } , 0 , 500 , TimeUnit . MILLISECONDS ) ; startMonitor ( ) ; tickTock = this . scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { long time = System . nanoTime ( ) / 1_000_000 ; if ( receiver != null ) { receiver . tick ( time ) ; } tick ( time ) ; } } , 0 , 20 , TimeUnit . MILLISECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the item by key from the mapping . [CODESPLIT] @ Override public final Object get ( Object key ) { Object object = null ; /* if the map is null, then we create it. */ if ( map == null ) { buildMap ( ) ; } object = map . get ( key ) ; lazyChopIfNeeded ( object ) ; return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the actual validation . [CODESPLIT] public ValidatorMessageHolder validate ( Object fieldValue , String fieldLabel ) { ValidatorMessage validatorMessage = new ValidatorMessage ( ) ; if ( fieldValue == null ) { return validatorMessage ; } int len = Boon . len ( fieldValue ) ; if ( ! ( len >= min && len <= max ) ) { populateMessage ( validatorMessage , fieldLabel , min , max ) ; } return validatorMessage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the main criteria plan in case the name was not obvious . [CODESPLIT] private ResultSet mainQueryPlan ( Criteria [ ] expressions ) { ResultSetInternal results = new ResultSetImpl ( this . fields ) ; if ( expressions == null || expressions . length == 0 ) { results . addResults ( searchableCollection . all ( ) ) ; } /* I am sure this looked easy to read when I wrote it.\n         * If there is only one expression and first expression is a group then\n         * the group is that first expression otherwise wrap\n         * all of the expressions in an and clause. */ Group group = expressions . length == 1 && expressions [ 0 ] instanceof Group ? ( Group ) expressions [ 0 ] : ObjectFilter . and ( expressions ) ; /**\n         * Run the filter on the group.\n         */ doFilterGroup ( group , results ) ; return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the filter on the group . [CODESPLIT] private void doFilterGroup ( Group group , ResultSetInternal results ) { /* The group was n or group so handle it that way. */ if ( group . getGrouping ( ) == Grouping . OR ) { /* nice short method name, or. */ or ( group . getExpressions ( ) , fields , results ) ; } else { /* create a result internal (why?), wrap the fields in the result set\n            internal, and pass that to the and method.\n             */ ResultSetInternal resultsForAnd = new ResultSetImpl ( fields ) ; and ( group . getExpressions ( ) , fields , resultsForAnd ) ; results . addResults ( resultsForAnd . asList ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private void applyGroups ( Set < Criteria > expressionSet , ResultSetInternal resultSet ) { if ( expressionSet . size ( ) == 0 ) { return ; } for ( Criteria expression : expressionSet ) { if ( expression instanceof Group ) { doFilterGroup ( ( Group ) expression , resultSet ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creation [CODESPLIT] public static < V > Set < V > set ( Collection < V > collection ) { if ( collection instanceof Set ) { return ( Set < V > ) collection ; } if ( collection == null ) { return Collections . EMPTY_SET ; } return new LinkedHashSet <> ( collection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end universal [CODESPLIT] public static List < Map < String , Object > > toListOfMaps ( Set < ? > set ) { return MapObjectConversion . toListOfMaps ( set ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recieves a tick from our clock . [CODESPLIT] public void tick ( long time ) { this . time . set ( time ) ; long startTime = fileStartTime . get ( ) ; long duration = time - startTime ; if ( duration > FILE_TIMEOUT_MILISECONDS ) { fileTimeOut . set ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "flush to disk . [CODESPLIT] public boolean syncToDisk ( ) { /** if we have a stream and we are dirty then flush. */ if ( outputStream != null && dirty ) { try { //outputStream.flush (); if ( outputStream instanceof FileChannel ) { FileChannel channel = ( FileChannel ) outputStream ; channel . force ( true ) ; } dirty = false ; return true ; } catch ( Exception ex ) { cleanupOutputStream ( ) ; return false ; } } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to close down log stream . [CODESPLIT] private void cleanupOutputStream ( ) { if ( outputStream != null ) { try { outputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( System . err ) ; } finally { outputStream = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a buffer of data to the log system . [CODESPLIT] public void nextBufferToWrite ( final ByteBuffer bufferOut ) throws InterruptedException { dirty = true ; final int size = bufferOut . limit ( ) ; write ( bufferOut ) ; /* only increment bytes transferred after a successful write. */ if ( ! error . get ( ) ) { totalBytesTransferred += size ; bytesTransferred += size ; bytesSinceLastFlush += size ; buffersSent ++ ; } if ( this . bytesTransferred >= FILE_SIZE_BYTES || fileTimeOut . get ( ) ) { try { outputStream . close ( ) ; } catch ( IOException e ) { cleanupOutputStream ( ) ; e . printStackTrace ( System . err ) ; } finally { outputStream = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the actual data to disk . [CODESPLIT] private void write ( final ByteBuffer bufferOut ) throws InterruptedException { initOutputStream ( ) ; try { if ( outputStream != null ) { outputStream . write ( bufferOut ) ; } else { error . set ( true ) ; } if ( bytesSinceLastFlush > FLUSH_EVERY_N_BYTES ) { syncToDisk ( ) ; bytesSinceLastFlush = 0 ; } } catch ( ClosedByInterruptException cbie ) { throw new InterruptedException ( \"File closed by interruption\" ) ; } catch ( Exception e ) { cleanupOutputStream ( ) ; error . set ( true ) ; e . printStackTrace ( System . err ) ; diagnose ( ) ; Exceptions . handle ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the output stream . [CODESPLIT] private void initOutputStream ( ) { long time = this . time . get ( ) ; if ( error . get ( ) || this . totalBytesTransferred == 0 ) { cleanupOutputStream ( ) ; error . set ( false ) ; time = System . nanoTime ( ) / 1_000_000 ; } if ( outputStream != null ) { return ; } fileName = LogFilesConfig . getLogFileName ( FORMAT_PATTERN , outputDirPath ( ) , numFiles , time , SERVER_NAME ) ; try { fileTimeOut . set ( false ) ; outputStream = streamCreator ( ) ; fileStartTime . set ( time ) ; bytesTransferred = 0 ; bytesSinceLastFlush = 0 ; } catch ( Exception ex ) { cleanupOutputStream ( ) ; error . set ( true ) ; Exceptions . handle ( ex ) ; } finally { numFiles ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a value from the key value store . [CODESPLIT] public V load ( K key ) { final String value = store . load ( toKeyString ( key ) ) ; if ( value != null ) { return toValueObject ( value ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a value in the key / value store . [CODESPLIT] public void put ( K key , V value ) { store . put ( toKeyString ( key ) , toValueString ( value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put all of these values in the key value store . [CODESPLIT] public void putAll ( Map < K , V > values ) { Set < Map . Entry < K , V > > entries = values . entrySet ( ) ; Map < String , String > map = new HashMap <> ( values . size ( ) ) ; for ( Map . Entry < K , V > entry : entries ) { map . put ( toKeyString ( entry . getKey ( ) ) , toValueString ( entry . getValue ( ) ) ) ; } store . putAll ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Never let the drift get greater than 200 ms . [CODESPLIT] private long checkForDrift ( long time ) { long delta = Math . abs ( System . currentTimeMillis ( ) - time ) ; long lastDelta = lastDeltaTime . getAndSet ( delta ) ; if ( delta > lastDelta + 200 ) { return getTheTime ( time ) ; } return time ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a value from the key value store . [CODESPLIT] public V load ( K key ) { final byte [ ] bytes = store . load ( toKeyBytes ( key ) ) ; if ( bytes != null ) { return toValueObject ( bytes ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a String key to bytes . [CODESPLIT] protected byte [ ] toKeyBytes ( K key ) { byte [ ] keyBytes = keyCache . get ( key ) ; if ( keyBytes == null ) { keyBytes = this . keyToByteArrayConverter . apply ( key ) ; keyCache . put ( key , keyBytes ) ; } return keyBytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a value in the key / value store . [CODESPLIT] public void put ( K key , V value ) { store . put ( toKeyBytes ( key ) , toValueBytes ( value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all of these values from the key value store . [CODESPLIT] public void removeAll ( Iterable < K > keys ) { List < byte [ ] > list = new ArrayList <> ( ) ; for ( K key : keys ) { list . add ( toKeyBytes ( key ) ) ; } store . removeAll ( list ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the meta - data from a properties file . [CODESPLIT] public List < ValidatorMetaData > readMetaData ( Class < ? > clazz , String propertyName ) { /* Load the properties file. */ Properties props = loadMetaDataPropsFile ( clazz ) ; /* Get the raw validation data for the given property. */ String unparsedString = props . getProperty ( propertyName ) ; /* Parse the string into a list of ValidationMetaData. */ return extractMetaDataFromString ( clazz , propertyName , unparsedString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method loads the MetaData properties file . The Properties are cached in <b > metaDataPropsCache< / b > and will not be reloaded twice . [CODESPLIT] private Properties loadMetaDataPropsFile ( Class < ? > clazzWhoseValidationMetaDataWeAreReading ) { String className = clazzWhoseValidationMetaDataWeAreReading . getName ( ) ; /*\r\n         * If the class is proxied there will be a $CGLIB on the end of it.\r\n         * Remove this.\r\n         */ className = className . split ( \"[$]\" ) [ 0 ] ; /*\r\n         * The resourceName is as follows: If the class name is com.foo.Foo Then\r\n         * the resource name is com.foo.Foo.properties.\r\n         */ String [ ] sourceParts = className . split ( \"[.]\" ) ; String resourceName = ( sourceParts [ sourceParts . length - 1 ] ) + \".properties\" ; /* Check to see if this properties file was already loaded. */ Properties validationMetaDataProps = metaDataPropsCache . get ( resourceName ) ; /* If the properties file was not loaded, then load it. */ if ( validationMetaDataProps == null ) { validationMetaDataProps = new Properties ( ) ; try { /*\r\n                 * Try to load the properties file that contains the validation\r\n                 * meta-data.\r\n                 */ validationMetaDataProps . load ( this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( resourceName ) ) ; } catch ( IOException ioex ) { /*\r\n                 * This can happen and is not an error. It just means there is\r\n                 * no validation for this guy. Maybe we should log this.\r\n                 * Note self... addObject logging capability to this project!.\r\n                 */ } /*\r\n             * Put the properties file into the cache so we don't have to read\r\n             * it again.\r\n             */ metaDataPropsCache . put ( resourceName , validationMetaDataProps ) ; } assert validationMetaDataProps != null : \"Properties for validation meta-data were loaded\" ; return validationMetaDataProps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method extracts meta - data from a string . [CODESPLIT] private List < ValidatorMetaData > extractMetaDataFromString ( Class < ? > clazz , String propertyName , String unparsedString ) { String propertyKey = clazz . getName ( ) + \".\" + propertyName ; /* See if we parsed this bad boy already. */ List < ValidatorMetaData > validatorMetaDataList = metaDataCache . get ( propertyKey ) ; /* If we did not find the list, then we have some work to do.*/ if ( validatorMetaDataList == null ) { /* Initialize a new list. */ validatorMetaDataList = new ArrayList < ValidatorMetaData > ( ) ; /* Remember we have a string that looks like this:\r\n             * required; length min=10, max=100\r\n             * So we need to split on semi-colon.\r\n             */ String [ ] validatorsParts = unparsedString . split ( \"[;]\" ) ; /* Now we have the two strings as follows:\r\n             *  [\"required\",\r\n             *  [\"length min=10, max=100\"]\r\n             *\r\n             */ for ( String validatorString : validatorsParts ) { ValidatorMetaData validatorMetaData = new ValidatorMetaData ( ) ; validatorMetaDataList . add ( validatorMetaData ) ; /* Now we split one of the string (we will use length) \r\n                 * as follows: \r\n                 * parts=[\"length\", \"min=10\", \"max=100\"]\r\n                 * */ String [ ] parts = validatorString . trim ( ) . split ( \"[ ,]\" ) ; /* The first part is the name of the validation, \r\n                 * e.g., \"length\".\r\n                 * \r\n                 */ validatorMetaData . setName ( parts [ 0 ] ) ; /* If the string has more than one part, then there must\r\n                 * be arguments as in: [\"min=10\", \"max=100\"]\r\n                 * \r\n                 * Parse the arguments and addObject them to the list as well.\r\n                 */ if ( parts . length > 1 ) { /* This line converts:\r\n                     * \r\n                     * [\"length\", \"min=10\", \"max=100\"]\r\n                     * \r\n                     * into: \r\n                     * \r\n                     * [\"min=10\", \"max=100\"]\r\n                     */ List < String > values = Arrays . asList ( parts ) . subList ( 1 , parts . length ) ; /* For each value convert it into name value pairs. */ for ( String value : values ) { if ( value . indexOf ( \"=\" ) != - 1 ) { /* Split \"min=10\" into [\"min\", \"10\"] */ String [ ] valueParts = value . split ( \"[=]\" ) ; /* Stick this value into validatorMetaData's\r\n                             * list of properties. \r\n                             */ validatorMetaData . getProperties ( ) . put ( valueParts [ 0 ] , valueParts [ 1 ] ) ; } } } } metaDataCache . put ( propertyKey , validatorMetaDataList ) ; } return validatorMetaDataList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the meta - data from annotation . This copies the meta - data from the annotation into a POJO . It first checks the meta - data cache if the meta data is not found in the cache it then reads it from the class . [CODESPLIT] public List < ValidatorMetaData > readMetaData ( Class < ? > clazz , String propertyName ) { /* Generate a key to the cache based on the classname and the propertyName. */ String propertyKey = clazz . getName ( ) + \".\" + propertyName ; /* Look up the validation meta data in the cache. */ List < ValidatorMetaData > validatorMetaDataList = metaDataCache . get ( propertyKey ) ; /* If the meta-data was not found, then generate it. */ if ( validatorMetaDataList == null ) { // if not found\r validatorMetaDataList = extractValidatorMetaData ( clazz , propertyName , validatorMetaDataList ) ; /* Put it in the cache to avoid the processing in the future.\r\n             * Design notes: The processing does a lot of reflection, there\r\n             * is no need to do this each time.\r\n             */ metaDataCache . put ( propertyKey , validatorMetaDataList ) ; } return validatorMetaDataList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract BaseValidator Meta Data . [CODESPLIT] private List < ValidatorMetaData > extractValidatorMetaData ( Class < ? > clazz , String propertyName , List < ValidatorMetaData > validatorMetaDataList ) { /* If the meta-data was not found, then generate it. */ if ( validatorMetaDataList == null ) { // if not found\r /* Read the annotation from the class based on the property name. */ Collection < AnnotationData > annotations = Annotations . getAnnotationDataForFieldAndProperty ( clazz , propertyName , this . validationAnnotationPackages ) ; /* Extract the POJO based meta-data from the annotation. */ validatorMetaDataList = extractMetaDataFromAnnotations ( annotations ) ; } return validatorMetaDataList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract meta - data from the annotationData we collected thus far . [CODESPLIT] private List < ValidatorMetaData > extractMetaDataFromAnnotations ( Collection < AnnotationData > annotations ) { List < ValidatorMetaData > list = new ArrayList < ValidatorMetaData > ( ) ; for ( AnnotationData annotationData : annotations ) { ValidatorMetaData validatorMetaData = convertAnnotationDataToValidatorMetaData ( annotationData ) ; list . add ( validatorMetaData ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an AnnotationData into a ValidatorMetaData POJO . [CODESPLIT] private ValidatorMetaData convertAnnotationDataToValidatorMetaData ( AnnotationData annotationData ) { ValidatorMetaData metaData = new ValidatorMetaData ( ) ; metaData . setName ( annotationData . getName ( ) ) ; metaData . setProperties ( annotationData . getValues ( ) ) ; return metaData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles a match . [CODESPLIT] private Pattern compileRegex ( ) { Pattern pattern = compiledRegexCache . get ( getMatch ( ) ) ; if ( pattern == null ) { pattern = Pattern . compile ( getMatch ( ) ) ; compiledRegexCache . put ( getMatch ( ) , pattern ) ; } return pattern ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a string into many parts [CODESPLIT] public static String [ ] split ( final String string , final char split , final int limit ) { char [ ] [ ] comps = CharScanner . split ( FastStringUtils . toCharArray ( string ) , split , limit ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split string by white space [CODESPLIT] public static String [ ] splitByWhiteSpace ( final String string ) { char [ ] [ ] comps = CharScanner . splitByChars ( FastStringUtils . toCharArray ( string ) , WHITE_SPACE ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split string by a list of delimiters [CODESPLIT] public static String [ ] splitByDelimiters ( final String string , final String delimiters ) { char [ ] [ ] comps = CharScanner . splitByChars ( FastStringUtils . toCharArray ( string ) , delimiters . toCharArray ( ) ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove chars from a string [CODESPLIT] public static String removeChars ( final String string , final char ... delimiters ) { char [ ] [ ] comps = CharScanner . splitByCharsNoneEmpty ( FastStringUtils . toCharArray ( string ) , delimiters ) ; return new String ( Chr . add ( comps ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split string by a list of delimiters but none are empty within a range [CODESPLIT] public static String [ ] splitByCharsNoneEmpty ( final String string , int start , int end , final char ... delimiters ) { Exceptions . requireNonNull ( string ) ; char [ ] [ ] comps = CharScanner . splitByCharsNoneEmpty ( FastStringUtils . toCharArray ( string ) , start , end , delimiters ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse float [CODESPLIT] public static float parseFloat ( String buffer , int from , int to ) { return CharScanner . parseFloat ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse a double [CODESPLIT] public static double parseDouble ( String buffer , int from , int to ) { return CharScanner . parseDouble ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse an int within a range [CODESPLIT] public static int parseInt ( String buffer , int from , int to ) { return CharScanner . parseInt ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse an long within a range [CODESPLIT] public static long parseLong ( String buffer , int from , int to ) { return CharScanner . parseLong ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a primitive list based on an input list and a property path [CODESPLIT] public static LongList toLongList ( Collection < ? > inputList , String propertyPath ) { if ( inputList . size ( ) == 0 ) { return new LongList ( 0 ) ; } LongList outputList = new LongList ( inputList . size ( ) ) ; if ( propertyPath . contains ( \".\" ) || propertyPath . contains ( \"[\" ) ) { String [ ] properties = StringScanner . splitByDelimiters ( propertyPath , \".[]\" ) ; for ( Object o : inputList ) { outputList . add ( BeanUtils . getPropertyLong ( o , properties ) ) ; } } else { Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( inputList . iterator ( ) . next ( ) ) ; FieldAccess fieldAccess = fields . get ( propertyPath ) ; for ( Object o : inputList ) { outputList . add ( fieldAccess . getLong ( o ) ) ; } } return outputList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new value to the list but don t employ a wrapper . [CODESPLIT] public boolean addLong ( long integer ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new value to the list but don t employ a wrapper . [CODESPLIT] public LongList add ( long integer ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set in a new value no wrapper [CODESPLIT] public long setLong ( int index , int element ) { long oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a primitive list based on an input list and a property path [CODESPLIT] public static IntList toIntList ( Collection < ? > inputList , String propertyPath ) { if ( inputList . size ( ) == 0 ) { return new IntList ( 0 ) ; } IntList outputList = new IntList ( inputList . size ( ) ) ; if ( propertyPath . contains ( \".\" ) || propertyPath . contains ( \"[\" ) ) { String [ ] properties = StringScanner . splitByDelimiters ( propertyPath , \".[]\" ) ; for ( Object o : inputList ) { outputList . add ( BeanUtils . getPropertyInt ( o , properties ) ) ; } } else { Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( inputList . iterator ( ) . next ( ) ) ; FieldAccess fieldAccess = fields . get ( propertyPath ) ; for ( Object o : inputList ) { outputList . add ( fieldAccess . getInt ( o ) ) ; } } return outputList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new value to the list but don t employ a wrapper . [CODESPLIT] public boolean addInt ( int integer ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new value to the list but don t employ a wrapper . [CODESPLIT] public IntList add ( int integer ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a value in the list . [CODESPLIT] @ Override public Integer set ( int index , Integer element ) { int oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set in a new value no wrapper [CODESPLIT] public int setInt ( int index , int element ) { int oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This would be a good opportunity to reintroduce dynamic invoke [CODESPLIT] public long reduceBy ( Object function , String name ) { return Int . reduceBy ( values , end , function , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "RESPONSES FROM SERVER . [CODESPLIT] private void handleMessageFromServer ( String message ) { if ( verbose ) { puts ( \"WEBSOCKET RESPONSE\" , ProtocolConstants . prettyPrintMessage ( message ) ) ; puts ( \"WEBSOCKET RESPONSE\" ) ; puts ( ProtocolConstants . prettyPrintMessageWithLinesTabs ( message ) ) ; } try { if ( message . startsWith ( Action . GET . response ( ) . startsWith ( ) ) || message . startsWith ( Action . SET_BROADCAST . response ( ) . startsWith ( ) ) ) { final SingleResult singleResult = SingleResult . fromTextMessage ( message ) ; queue . put ( singleResult ) ; } else if ( message . startsWith ( Action . BATCH_READ . response ( ) . startsWith ( ) ) ) { queue . put ( BatchResult . fromTextMessage ( message ) ) ; } else { if ( verbose ) { puts ( \"Unknown action\" , message ) ; } } } catch ( Exception ex ) { logger . error ( ex , \"ServerProxy::handleMessageFromServer\\n\" , message ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the field value . [CODESPLIT] public FieldAccess field ( ) { FieldAccess field ; if ( path ) { field = BeanUtils . idxField ( objectUnderTest , name . toString ( ) ) ; if ( field == null ) { return fakeField ( ) ; } return field ; } if ( name instanceof Enum ) { name = Str . camelCaseLower ( name . toString ( ) ) ; } field = fields ( ) . get ( name ) ; return field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the field value . [CODESPLIT] public Object fieldValue ( ) { if ( ! path ) { FieldAccess field1 = this . field ( ) ; return field1 . getValue ( objectUnderTest ) ; } else { return BeanUtils . atIndex ( objectUnderTest , name . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the field value . [CODESPLIT] public Object value ( ) { if ( ! convert1st ) { FieldAccess field = field ( ) ; if ( field != null ) { switch ( field . typeEnum ( ) ) { case NUMBER : this . value = ( VALUE ) Conversions . coerce ( field . type ( ) , this . value ) ; return new MyNumber ( this . value ) ; case ARRAY : case ARRAY_INT : case ARRAY_BYTE : case ARRAY_SHORT : case ARRAY_FLOAT : case ARRAY_DOUBLE : case ARRAY_LONG : case ARRAY_STRING : case ARRAY_OBJECT : case COLLECTION : case SET : case LIST : this . value = ( VALUE ) Conversions . coerce ( field . getComponentClass ( ) , this . value ) ; break ; default : this . value = ( VALUE ) Conversions . coerce ( field . type ( ) , this . value ) ; } } convert1st = true ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the field value . [CODESPLIT] public Object value2 ( ) { if ( ! convert2nd ) { FieldAccess field = this . field ( ) ; this . value2 = ( VALUE ) Conversions . coerce ( field . type ( ) , this . value2 ) ; convert2nd = true ; } return value2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method handles walking lists of lists . [CODESPLIT] public static Object getPropByPath ( Object item , String ... path ) { Object o = item ; for ( int index = 0 ; index < path . length ; index ++ ) { String propName = path [ index ] ; if ( o == null ) { return null ; } else if ( o . getClass ( ) . isArray ( ) || o instanceof Collection ) { o = getCollectionProp ( o , propName , index , path ) ; break ; } else { o = getProp ( o , propName ) ; } } return Conversions . unifyListOrArray ( o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get fields from object or Map . Allows maps to act like they have fields . [CODESPLIT] public static Map < String , FieldAccess > getFieldsFromObject ( Object object ) { try { Map < String , FieldAccess > fields ; if ( object instanceof Map ) { fields = getFieldsFromMap ( ( Map < String , Object > ) object ) ; } else { fields = getPropertyFieldAccessMap ( object . getClass ( ) ) ; } return fields ; } catch ( Exception ex ) { requireNonNull ( object , \"Item cannot be null\" ) ; return handle ( Map . class , ex , \"Unable to get fields from object\" , className ( object ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get fields from map . [CODESPLIT] private static Map < String , FieldAccess > getFieldsFromMap ( final Map < String , Object > map ) { return new Map < String , FieldAccess > ( ) { @ Override public int size ( ) { return map . size ( ) ; } @ Override public boolean isEmpty ( ) { return map . isEmpty ( ) ; } @ Override public boolean containsKey ( Object key ) { return map . containsKey ( key ) ; } @ Override public boolean containsValue ( Object value ) { return true ; } @ Override public FieldAccess get ( final Object key ) { return new FieldAccess ( ) { @ Override public boolean injectable ( ) { return false ; } @ Override public boolean requiresInjection ( ) { return false ; } @ Override public boolean isNamed ( ) { return false ; } @ Override public boolean hasAlias ( ) { return false ; } @ Override public String alias ( ) { return null ; } @ Override public String named ( ) { return key . toString ( ) ; } @ Override public String name ( ) { return key . toString ( ) ; } @ Override public Object getValue ( Object obj ) { return map . get ( key ) ; } @ Override public void setValue ( Object obj , Object value ) { map . put ( key . toString ( ) , value ) ; } @ Override public void setFromValue ( Object obj , Value value ) { map . put ( key . toString ( ) , value . toValue ( ) ) ; } @ Override public boolean getBoolean ( Object obj ) { return Conversions . toBoolean ( getValue ( key ) ) ; } @ Override public void setBoolean ( Object obj , boolean value ) { setValue ( map , value ) ; } @ Override public int getInt ( Object obj ) { return Conversions . toInt ( getValue ( key ) ) ; } @ Override public void setInt ( Object obj , int value ) { setValue ( map , value ) ; } @ Override public short getShort ( Object obj ) { return Conversions . toShort ( getValue ( key ) ) ; } @ Override public void setShort ( Object obj , short value ) { setValue ( map , value ) ; } @ Override public char getChar ( Object obj ) { return Conversions . toChar ( getValue ( key ) ) ; } @ Override public void setChar ( Object obj , char value ) { setValue ( map , value ) ; } @ Override public long getLong ( Object obj ) { return Conversions . toChar ( getValue ( key ) ) ; } @ Override public void setLong ( Object obj , long value ) { setValue ( map , value ) ; } @ Override public double getDouble ( Object obj ) { return Conversions . toDouble ( getValue ( key ) ) ; } @ Override public void setDouble ( Object obj , double value ) { setValue ( map , value ) ; } @ Override public float getFloat ( Object obj ) { return Conversions . toFloat ( getValue ( key ) ) ; } @ Override public void setFloat ( Object obj , float value ) { setValue ( map , value ) ; } @ Override public byte getByte ( Object obj ) { return Conversions . toByte ( getValue ( key ) ) ; } @ Override public void setByte ( Object obj , byte value ) { setValue ( map , value ) ; } @ Override public Object getObject ( Object obj ) { return getValue ( obj ) ; } @ Override public void setObject ( Object obj , Object value ) { this . setValue ( obj , value ) ; } @ Override public TypeType typeEnum ( ) { return TypeType . OBJECT ; } @ Override public boolean isPrimitive ( ) { return false ; } @ Override public boolean isFinal ( ) { return false ; } @ Override public boolean isStatic ( ) { return false ; } @ Override public boolean isVolatile ( ) { return false ; } @ Override public boolean isQualified ( ) { return false ; } @ Override public boolean isReadOnly ( ) { return false ; } @ Override public boolean isWriteOnly ( ) { return false ; } @ Override public Class < ? > type ( ) { return Object . class ; } @ Override public Class < ? > declaringParent ( ) { return null ; } @ Override public Object parent ( ) { return map ; } @ Override public Field getField ( ) { return null ; } @ Override public boolean include ( ) { return true ; } @ Override public boolean ignore ( ) { return false ; } @ Override public ParameterizedType getParameterizedType ( ) { return null ; } @ Override public Class < ? > getComponentClass ( ) { return null ; } @ Override public boolean hasAnnotation ( String annotationName ) { return false ; } @ Override public Map < String , Object > getAnnotationData ( String annotationName ) { return null ; } @ Override public boolean isViewActive ( String activeView ) { return false ; } @ Override public void setStaticValue ( Object newValue ) { } @ Override public TypeType componentType ( ) { return null ; } } ; } @ Override public FieldAccess put ( String key , FieldAccess value ) { return null ; } @ Override public FieldAccess remove ( Object key ) { return null ; } @ Override public void putAll ( Map < ? extends String , ? extends FieldAccess > m ) { } @ Override public void clear ( ) { } @ Override public Set < String > keySet ( ) { return null ; } @ Override public Collection < FieldAccess > values ( ) { return null ; } @ Override public Set < Entry < String , FieldAccess > > entrySet ( ) { return null ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get property value loads nested properties [CODESPLIT] public static Class < ? > getPropertyType ( final Object root , final String property ) { Map < String , FieldAccess > fields = getPropertyFieldAccessMap ( root . getClass ( ) ) ; FieldAccess field = fields . get ( property ) ; return field . type ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get property value [CODESPLIT] public static Object idx ( Object object , String path ) { String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyValue ( object , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get property value [CODESPLIT] public static Object atIndex ( Object object , String path ) { String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyValue ( object , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set property value to simulate dependency injection . [CODESPLIT] public static void injectIntoProperty ( Object object , String path , Object value ) { String [ ] properties = propertyPathAsStringArray ( path ) ; setPropertyValue ( object , value , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a static value [CODESPLIT] public static void idx ( Class < ? > cls , String path , Object value ) { String [ ] properties = propertyPathAsStringArray ( path ) ; setPropertyValue ( cls , value , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is an amazing little recursive method . It walks a fanout of nested collection to pull out the leaf nodes [CODESPLIT] private static Object getCollectionProp ( Object o , String propName , int index , String [ ] path ) { o = _getFieldValuesFromCollectionOrArray ( o , propName ) ; if ( index + 1 == path . length ) { return o ; } else { index ++ ; return getCollectionProp ( o , path [ index ] , index , path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is one is forgiving of null paths . This works with getters first i . e . properties . [CODESPLIT] public static Object getProp ( Object object , final String property ) { if ( object == null ) { return null ; } if ( isDigits ( property ) ) { /* We can index numbers and names. */ object = idx ( object , StringScanner . parseInt ( property ) ) ; } Class < ? > cls = object . getClass ( ) ; /** Tries the getters first. */ Map < String , FieldAccess > fields = Reflection . getPropertyFieldAccessors ( cls ) ; if ( ! fields . containsKey ( property ) ) { fields = Reflection . getAllAccessorFields ( cls ) ; } if ( ! fields . containsKey ( property ) ) { return null ; } else { return fields . get ( property ) . getValue ( object ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an int property . [CODESPLIT] public static int getPropertyInt ( final Object root , final String ... properties ) { final String lastProperty = properties [ properties . length - 1 ] ; if ( isDigits ( lastProperty ) ) { return Conversions . toInt ( getPropertyValue ( root , properties ) ) ; } Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; FieldAccess field = fields . get ( lastProperty ) ; if ( field . type ( ) == Typ . intgr ) { return field . getInt ( object ) ; } else { return Conversions . toInt ( field . getValue ( object ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get property value [CODESPLIT] public static int idxInt ( Object object , String path ) { String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyInt ( object , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get property value [CODESPLIT] public static String idxStr ( Object object , String path ) { final Object val = idx ( object , path ) ; return Conversions . toString ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Property Path TypeType [CODESPLIT] public static Class < ? > getPropertyPathType ( final Object root , final String ... properties ) { Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field . type ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Property Path TypeType [CODESPLIT] public static FieldAccess getPropertyPathField ( final Object root , final String ... properties ) { Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Property Path TypeType [CODESPLIT] public static FieldAccess getPropertyPathField ( final Class root , final String ... properties ) { Class cls = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( cls ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Manages weak references . [CODESPLIT] static Context context ( ) { if ( _context != null ) { return _context ; } else { Context context = weakContext . get ( ) ; if ( context == null ) { context = new Context ( ) ; weakContext = new WeakReference <> ( context ) ; } return context ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a list of fields merges with properties if field is not found . [CODESPLIT] public static Map < String , FieldAccess > getPropertyFieldAccessMapFieldFirst ( Class < ? > clazz ) { Map < String , FieldAccess > combinedFieldsFieldFirst = getCombinedFieldsFieldFirst ( clazz ) ; if ( combinedFieldsFieldFirst != null ) { return combinedFieldsFieldFirst ; } else { /* Fallback map. */ Map < String , FieldAccess > fieldsFallbacks = null ; /* Primary merge into this one. */ Map < String , FieldAccess > fieldsPrimary = null ; /* Try to find the fields first if this is set. */ fieldsPrimary = Reflection . getAllAccessorFields ( clazz , true ) ; fieldsFallbacks = Reflection . getPropertyFieldAccessors ( clazz ) ; combineFieldMaps ( fieldsFallbacks , fieldsPrimary ) ; combinedFieldsFieldFirst = fieldsPrimary ; putCombinedFieldsFieldFirst ( clazz , combinedFieldsFieldFirst ) ; return combinedFieldsFieldFirst ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a list of fields merges with properties if field is not found . [CODESPLIT] public static Map < String , FieldAccess > getPropertyFieldAccessMapFieldFirstForSerializer ( Class < ? > clazz ) { Map < String , FieldAccess > combinedFieldsFieldFirst = getCombinedFieldsFieldFirstForSerializer ( clazz ) ; if ( combinedFieldsFieldFirst != null ) { return combinedFieldsFieldFirst ; } else { /* Fallback map. */ Map < String , FieldAccess > fieldsFallbacks = null ; /* Primary merge into this one. */ Map < String , FieldAccess > fieldsPrimary = null ; /* Try to find the fields first if this is set. */ fieldsPrimary = Reflection . getAllAccessorFields ( clazz , true ) ; fieldsFallbacks = Reflection . getPropertyFieldAccessors ( clazz ) ; fieldsPrimary = removeNonSerializable ( fieldsPrimary ) ; fieldsFallbacks = removeNonSerializable ( fieldsFallbacks ) ; combineFieldMaps ( fieldsFallbacks , fieldsPrimary ) ; combinedFieldsFieldFirst = fieldsPrimary ; putCombinedFieldsFieldFirstForSerializer ( clazz , combinedFieldsFieldFirst ) ; return combinedFieldsFieldFirst ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The init method tries to generate the message keys . You should only call the init method if you don t inject values into the detailMessage and summaryMessage . [CODESPLIT] public void init ( ) { /* If the parent and name are equal to null,\n         * use the classname to load listFromClassLoader.\n    \t * */ if ( name == null && parent == null ) { this . setDetailMessage ( \"{\" + this . getClass ( ) . getName ( ) + DETAIL_KEY + \"}\" ) ; this . setSummaryMessage ( \"{\" + this . getClass ( ) . getName ( ) + SUMMARY_KEY + \"}\" ) ; /* If the parent is null and the name is not,\n         * use the name to load listFromClassLoader.\n         */ } else if ( name != null && parent == null ) { this . setDetailMessage ( \"{\" + \"message.\" + getName ( ) + DETAIL_KEY + \"}\" ) ; this . setSummaryMessage ( \"{\" + \"message.\" + getName ( ) + SUMMARY_KEY + \"}\" ) ; /* If the parent is present, initialize the message keys\n         * with the parent name.\n         */ } else if ( parent != null ) { this . setDetailMessage ( \"{\" + \"message.\" + parent + DETAIL_KEY + \"}\" ) ; this . setSummaryMessage ( \"{\" + \"message.\" + parent + SUMMARY_KEY + \"}\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a message . [CODESPLIT] public String createMessage ( String key , List < String > argKeys , Object ... args ) { /* Look up the message. */ String message = getMessage ( key ) ; /* Holds the actual arguments. */ Object [ ] actualArgs ; /* If they passed arguments, \n         * then use this as the actual arguments. */ if ( args . length > 0 ) { actualArgs = args ; /* If they did not pass arguments, use the configured ones. */ } else if ( argKeys != null ) { /* Convert the keys to values. */ actualArgs = keysToValues ( argKeys ) ; } else { actualArgs = new Object [ ] { } ; } return doCreateMessage ( message , actualArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actually creates the message . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private String doCreateMessage ( String message , Object [ ] actualArgs ) { return ValidationContext . get ( ) . createMessage ( message , getSubject ( ) , actualArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the keys to values . [CODESPLIT] private Object [ ] keysToValues ( List < String > argKeys ) { List < String > values = new ArrayList <> ( ) ; for ( String key : argKeys ) { values . add ( getMessage ( key ) ) ; } return values . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current subject or the configured subject if the current subject is not found . [CODESPLIT] public String getSubject ( ) { return ValidationContext . get ( ) . getCurrentSubject ( ) == null ? this . subject : ValidationContext . get ( ) . getCurrentSubject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a text representation of a JSON data structure [CODESPLIT] public Object parseText ( String text ) { if ( text == null || text . length ( ) == 0 ) { throw new IllegalArgumentException ( \"The JSON input text should neither be null nor empty.\" ) ; } return JsonFactory . create ( ) . fromJson ( text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This actually sends the request . [CODESPLIT] private void sendHttpRequest ( final Request request , final org . boon . core . Handler < Response > responseHandler ) { final HttpClientRequest httpClientRequest = httpClient . request ( request . getMethod ( ) , request . uri ( ) , handleResponse ( request , responseHandler ) ) ; final Runnable runnable = new Runnable ( ) { @ Override public void run ( ) { if ( ! request . getMethod ( ) . equals ( \"GET\" ) ) { httpClientRequest . putHeader ( \"Content-Type\" , \"application/x-www-form-urlencoded\" ) . end ( request . paramBody ( ) ) ; } else { httpClientRequest . end ( ) ; } } } ; if ( closed . get ( ) ) { this . scheduledExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { connect ( ) ; int retry = 0 ; while ( closed . get ( ) ) { Sys . sleep ( 1000 ) ; if ( ! closed . get ( ) ) { break ; } retry ++ ; if ( retry > 10 ) { break ; } if ( retry % 3 == 0 ) { connect ( ) ; } } if ( ! closed . get ( ) ) { runnable . run ( ) ; } else { responseHandler . handle ( new Response ( \"TIMEOUT\" , - 1 , new Error ( - 1 , \"Timeout\" , \"Timeout\" , - 1L ) ) ) ; } } } , 10 , TimeUnit . MILLISECONDS ) ; } else { runnable . run ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests CouchDB deletes a database . [CODESPLIT] public void deleteDB ( String dbName , String confirm ) { assertNotEmpty ( dbName , \"dbName\" ) ; if ( ! \"delete database\" . equals ( confirm ) ) throw new IllegalArgumentException ( \"Invalid confirm!\" ) ; dbc . delete ( buildUri ( dbc . getBaseUri ( ) ) . path ( dbName ) . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests CouchDB creates a new database ; if one doesn t exist . [CODESPLIT] public void createDB ( String dbName ) { assertNotEmpty ( dbName , \"dbName\" ) ; InputStream getresp = null ; HttpResponse putresp = null ; final URI uri = buildUri ( dbc . getBaseUri ( ) ) . path ( dbName ) . build ( ) ; try { getresp = dbc . get ( uri ) ; } catch ( NoDocumentException e ) { // db doesn't exist final HttpPut put = new HttpPut ( uri ) ; putresp = dbc . executeRequest ( put ) ; log . info ( String . format ( \"Created Database: '%s'\" , dbName ) ) ; } finally { close ( getresp ) ; close ( putresp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a database <i > compact< / i > request . [CODESPLIT] public void compact ( ) { HttpResponse response = null ; try { response = dbc . post ( buildUri ( dbc . getDBUri ( ) ) . path ( \"_compact\" ) . build ( ) , \"\" ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Request a database sends a list of UUIDs . [CODESPLIT] public List < String > uuids ( long count ) { final String uri = String . format ( \"%s_uuids?count=%d\" , dbc . getBaseUri ( ) , count ) ; final JsonObject json = dbc . findAny ( JsonObject . class , uri ) ; return dbc . getGson ( ) . fromJson ( json . get ( \"uuids\" ) . toString ( ) , new TypeToken < List < String > > ( ) { } . getType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds request / response interceptors for logging and validation . [CODESPLIT] private void registerInterceptors ( HttpClientBuilder clientBuilder ) { clientBuilder . addInterceptorFirst ( new HttpRequestInterceptor ( ) { public void process ( final HttpRequest request , final HttpContext context ) throws IOException { if ( log . isInfoEnabled ( ) ) { RequestLine req = request . getRequestLine ( ) ; log . info ( \"> \" + req . getMethod ( ) + \" \" + URLDecoder . decode ( req . getUri ( ) , \"UTF-8\" ) ) ; } } } ) ; clientBuilder . addInterceptorFirst ( new HttpResponseInterceptor ( ) { public void process ( final HttpResponse response , final HttpContext context ) throws IOException { if ( log . isInfoEnabled ( ) ) { log . info ( \"< Status: \" + response . getStatusLine ( ) . getStatusCode ( ) ) ; } validate ( response ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JSON [CODESPLIT] public static < T > T JsonToObject ( Gson gson , JsonElement elem , String key , Class < T > classType ) { return gson . fromJson ( elem . getAsJsonObject ( ) . get ( key ) , classType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List directory contents for a resource folder . Not recursive . This is basically a brute - force implementation . Works for regular files and also JARs . [CODESPLIT] public static List < String > listResources ( String path ) { try { Class < CouchDbUtil > clazz = CouchDbUtil . class ; URL dirURL = clazz . getClassLoader ( ) . getResource ( path ) ; if ( dirURL != null && dirURL . getProtocol ( ) . equals ( \"file\" ) ) { return Arrays . asList ( new File ( dirURL . toURI ( ) ) . list ( ) ) ; } if ( dirURL != null && dirURL . getProtocol ( ) . equals ( \"jar\" ) ) { String jarPath = dirURL . getPath ( ) . substring ( 5 , dirURL . getPath ( ) . indexOf ( \"!\" ) ) ; JarFile jar = new JarFile ( URLDecoder . decode ( jarPath , \"UTF-8\" ) ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; Set < String > result = new HashSet < String > ( ) ; while ( entries . hasMoreElements ( ) ) { String name = entries . nextElement ( ) . getName ( ) ; if ( name . startsWith ( SPRING_BOOT_DIR ) ) { name = name . substring ( SPRING_BOOT_DIR . length ( ) ) ; } if ( name . startsWith ( path ) ) { String entry = name . substring ( path . length ( ) ) ; int checkSubdir = entry . indexOf ( \"/\" ) ; if ( checkSubdir >= 0 ) { entry = entry . substring ( 0 , checkSubdir ) ; } if ( entry . length ( ) > 0 ) { result . add ( entry ) ; } } } close ( jar ) ; return new ArrayList < String > ( result ) ; } return null ; } catch ( Exception e ) { throw new CouchDbException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a replication request . [CODESPLIT] public ReplicationResult trigger ( ) { assertNotEmpty ( source , \"Source\" ) ; assertNotEmpty ( target , \"Target\" ) ; HttpResponse response = null ; try { JsonObject json = createJson ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( json ) ; } final URI uri = buildUri ( dbc . getBaseUri ( ) ) . path ( \"_replicate\" ) . build ( ) ; response = dbc . post ( uri , json . toString ( ) ) ; final InputStreamReader reader = new InputStreamReader ( getStream ( response ) , Charsets . UTF_8 ) ; return dbc . getGson ( ) . fromJson ( reader , ReplicationResult . class ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper [CODESPLIT] private JsonObject createJson ( ) { JsonObject json = new JsonObject ( ) ; addProperty ( json , \"source\" , source ) ; addProperty ( json , \"cancel\" , cancel ) ; addProperty ( json , \"continuous\" , continuous ) ; addProperty ( json , \"filter\" , filter ) ; if ( queryParams != null ) json . add ( \"query_params\" , queryParams ) ; if ( docIds != null ) json . add ( \"doc_ids\" , dbc . getGson ( ) . toJsonTree ( docIds , String [ ] . class ) ) ; addProperty ( json , \"proxy\" , proxy ) ; addProperty ( json , \"since_seq\" , sinceSeq ) ; addProperty ( json , \"create_target\" , createTarget ) ; if ( targetOauth != null ) { JsonObject auth = new JsonObject ( ) ; JsonObject oauth = new JsonObject ( ) ; addProperty ( oauth , \"consumer_secret\" , consumerSecret ) ; addProperty ( oauth , \"consumer_key\" , consumerKey ) ; addProperty ( oauth , \"token_secret\" , tokenSecret ) ; addProperty ( oauth , \"token\" , token ) ; addProperty ( targetOauth , \"url\" , target ) ; auth . add ( \"oauth\" , oauth ) ; targetOauth . add ( \"auth\" , auth ) ; json . add ( \"target\" , targetOauth ) ; } else { addProperty ( json , \"target\" , target ) ; } return json ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queries a view as an { [CODESPLIT] public InputStream queryForStream ( ) { URI uri = uriBuilder . build ( ) ; if ( allDocsKeys != null ) { // bulk docs return getStream ( dbc . post ( uri , allDocsKeys ) ) ; } return dbc . get ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queries a view . [CODESPLIT] public < T > List < T > query ( Class < T > classOfT ) { InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( ) , Charsets . UTF_8 ) ; JsonArray jsonArray = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . getAsJsonArray ( \"rows\" ) ; List < T > list = new ArrayList < T > ( ) ; for ( JsonElement jsonElem : jsonArray ) { JsonElement elem = jsonElem . getAsJsonObject ( ) ; if ( Boolean . TRUE . equals ( this . includeDocs ) ) { elem = jsonElem . getAsJsonObject ( ) . get ( \"doc\" ) ; } T t = this . gson . fromJson ( elem , classOfT ) ; list . add ( t ) ; } return list ; } finally { close ( instream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queries a view . [CODESPLIT] public < K , V , T > ViewResult < K , V , T > queryView ( Class < K > classOfK , Class < V > classOfV , Class < T > classOfT ) { InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( ) , Charsets . UTF_8 ) ; JsonObject json = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) ; ViewResult < K , V , T > vr = new ViewResult < K , V , T > ( ) ; vr . setTotalRows ( getAsLong ( json , \"total_rows\" ) ) ; vr . setOffset ( getAsInt ( json , \"offset\" ) ) ; vr . setUpdateSeq ( getAsString ( json , \"update_seq\" ) ) ; JsonArray jsonArray = json . getAsJsonArray ( \"rows\" ) ; for ( JsonElement e : jsonArray ) { ViewResult < K , V , T > . Rows row = vr . new Rows ( ) ; row . setId ( JsonToObject ( gson , e , \"id\" , String . class ) ) ; if ( classOfK != null ) { row . setKey ( JsonToObject ( gson , e , \"key\" , classOfK ) ) ; } if ( classOfV != null ) { row . setValue ( JsonToObject ( gson , e , \"value\" , classOfV ) ) ; } if ( Boolean . TRUE . equals ( this . includeDocs ) ) { row . setDoc ( JsonToObject ( gson , e , \"doc\" , classOfT ) ) ; } vr . getRows ( ) . add ( row ) ; } return vr ; } finally { close ( instream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queries for scalar values . Internal use . [CODESPLIT] private < V > V queryValue ( Class < V > classOfV ) { InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( ) , Charsets . UTF_8 ) ; JsonArray array = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . get ( \"rows\" ) . getAsJsonArray ( ) ; if ( array . size ( ) != 1 ) { throw new NoDocumentException ( \"Expecting a single result but was: \" + array . size ( ) ) ; } return JsonToObject ( gson , array . get ( 0 ) , \"value\" , classOfV ) ; } finally { close ( instream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queries a view for pagination returns a next or a previous page this method figures out which page to return based on the given param that is generated by an earlier call to this method quering the first page is done by passing a { [CODESPLIT] public < T > Page < T > queryPage ( int rowsPerPage , String param , Class < T > classOfT ) { if ( param == null ) { // assume first page return queryNextPage ( rowsPerPage , null , null , null , null , classOfT ) ; } String currentStartKey ; String currentStartKeyDocId ; String startKey ; String startKeyDocId ; String action ; try { // extract fields from the returned HEXed JSON object final JsonObject json = new JsonParser ( ) . parse ( new String ( Base64 . decodeBase64 ( param . getBytes ( ) ) ) ) . getAsJsonObject ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"Paging Param Decoded = \" + json ) ; } final JsonObject jsonCurrent = json . getAsJsonObject ( CURRENT_KEYS ) ; currentStartKey = jsonCurrent . get ( CURRENT_START_KEY ) . getAsString ( ) ; currentStartKeyDocId = jsonCurrent . get ( CURRENT_START_KEY_DOC_ID ) . getAsString ( ) ; startKey = json . get ( START_KEY ) . getAsString ( ) ; startKeyDocId = json . get ( START_KEY_DOC_ID ) . getAsString ( ) ; action = json . get ( ACTION ) . getAsString ( ) ; } catch ( Exception e ) { throw new CouchDbException ( \"could not parse the given param!\" , e ) ; } if ( PREVIOUS . equals ( action ) ) { // previous return queryPreviousPage ( rowsPerPage , currentStartKey , currentStartKeyDocId , startKey , startKeyDocId , classOfT ) ; } else { // next return queryNextPage ( rowsPerPage , currentStartKey , currentStartKeyDocId , startKey , startKeyDocId , classOfT ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverses the reading direction not the sort order . [CODESPLIT] public View descending ( Boolean descending ) { this . descending = Boolean . valueOf ( gson . toJson ( descending ) ) ; uriBuilder . query ( \"descending\" , this . descending ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supplies a key list when calling <tt > _all_docs< / tt > View . [CODESPLIT] public View keys ( List < ? > keys ) { this . allDocsKeys = String . format ( \"{%s:%s}\" , gson . toJson ( \"keys\" ) , gson . toJson ( keys ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronizes a design document to the Database . <p > This method will first try to find a document in the database with the same id as the given document if it is not found then the given document will be saved to the database . <p > If the document was found in the database it will be compared with the given document using { [CODESPLIT] public Response synchronizeWithDb ( DesignDocument document ) { assertNotEmpty ( document , \"Document\" ) ; DesignDocument documentFromDb = null ; try { documentFromDb = getFromDb ( document . getId ( ) ) ; } catch ( NoDocumentException e ) { return dbc . save ( document ) ; } if ( ! document . equals ( documentFromDb ) ) { document . setRevision ( documentFromDb . getRevision ( ) ) ; return dbc . update ( document ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronize all design documents on desk to the database . [CODESPLIT] public void synchronizeAllWithDb ( ) { List < DesignDocument > documents = getAllFromDesk ( ) ; for ( DesignDocument dd : documents ) { synchronizeWithDb ( dd ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a design document from the database . [CODESPLIT] public DesignDocument getFromDb ( String id ) { assertNotEmpty ( id , \"id\" ) ; final URI uri = buildUri ( dbc . getDBUri ( ) ) . path ( id ) . build ( ) ; return dbc . get ( uri , DesignDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets all design documents from desk . [CODESPLIT] public List < DesignDocument > getAllFromDesk ( ) { final List < DesignDocument > designDocsList = new ArrayList < DesignDocument > ( ) ; for ( String docName : listResources ( format ( \"%s/\" , DESIGN_DOCS_DIR ) ) ) { designDocsList . add ( getFromDesk ( docName ) ) ; } return designDocsList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a design document from desk . [CODESPLIT] public DesignDocument getFromDesk ( String id ) { assertNotEmpty ( id , \"id\" ) ; final DesignDocument dd = new DesignDocument ( ) ; final String rootPath = format ( \"%s/%s/\" , DESIGN_DOCS_DIR , id ) ; final List < String > elements = listResources ( rootPath ) ; if ( elements == null ) { throw new IllegalArgumentException ( \"Design docs directory cannot be empty.\" ) ; } // Views Map < String , MapReduce > views = null ; if ( elements . contains ( VIEWS ) ) { views = new HashMap < String , MapReduce > ( ) ; final String viewsPath = format ( \"%s%s/\" , rootPath , VIEWS ) ; for ( String viewDirName : listResources ( viewsPath ) ) { // views sub-dirs final MapReduce mr = new MapReduce ( ) ; final String viewPath = format ( \"%s%s/\" , viewsPath , viewDirName ) ; final List < String > dirList = listResources ( viewPath ) ; for ( String fileName : dirList ) { // view files final String def = readFile ( format ( \"/%s%s\" , viewPath , fileName ) ) ; if ( MAP_JS . equals ( fileName ) ) mr . setMap ( def ) ; else if ( REDUCE_JS . equals ( fileName ) ) mr . setReduce ( def ) ; } // /foreach view files views . put ( viewDirName , mr ) ; } // /foreach views sub-dirs } // /views dd . setId ( DESIGN_PREFIX + id ) ; dd . setLanguage ( JAVASCRIPT ) ; dd . setViews ( views ) ; dd . setFilters ( populateMap ( rootPath , elements , FILTERS ) ) ; dd . setShows ( populateMap ( rootPath , elements , SHOWS ) ) ; dd . setLists ( populateMap ( rootPath , elements , LISTS ) ) ; dd . setUpdates ( populateMap ( rootPath , elements , UPDATES ) ) ; dd . setValidateDocUpdate ( readContent ( elements , rootPath , VALIDATE_DOC ) ) ; dd . setRewrites ( dbc . getGson ( ) . fromJson ( readContent ( elements , rootPath , REWRITES ) , JsonArray . class ) ) ; dd . setFulltext ( dbc . getGson ( ) . fromJson ( readContent ( elements , rootPath , FULLTEXT ) , JsonObject . class ) ) ; dd . setIndexes ( dbc . getGson ( ) . fromJson ( readContent ( elements , rootPath , INDEXES ) , JsonObject . class ) ) ; return dd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new document to the replicator database . [CODESPLIT] public Response save ( ) { assertNotEmpty ( replicatorDoc . getSource ( ) , \"Source\" ) ; assertNotEmpty ( replicatorDoc . getTarget ( ) , \"Target\" ) ; if ( userCtxName != null ) { UserCtx ctx = replicatorDoc . new UserCtx ( ) ; ctx . setName ( userCtxName ) ; ctx . setRoles ( userCtxRoles ) ; replicatorDoc . setUserCtx ( ctx ) ; } return dbc . put ( dbURI , replicatorDoc , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a document in the replicator database . [CODESPLIT] public ReplicatorDocument find ( ) { assertNotEmpty ( replicatorDoc . getId ( ) , \"Doc id\" ) ; final URI uri = buildUri ( dbURI ) . path ( replicatorDoc . getId ( ) ) . query ( \"rev\" , replicatorDoc . getRevision ( ) ) . build ( ) ; return dbc . get ( uri , ReplicatorDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all documents in the replicator database . [CODESPLIT] public List < ReplicatorDocument > findAll ( ) { InputStream instream = null ; try { final URI uri = buildUri ( dbURI ) . path ( \"_all_docs\" ) . query ( \"include_docs\" , \"true\" ) . build ( ) ; final Reader reader = new InputStreamReader ( instream = dbc . get ( uri ) , Charsets . UTF_8 ) ; final JsonArray jsonArray = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . getAsJsonArray ( \"rows\" ) ; final List < ReplicatorDocument > list = new ArrayList < ReplicatorDocument > ( ) ; for ( JsonElement jsonElem : jsonArray ) { JsonElement elem = jsonElem . getAsJsonObject ( ) . get ( \"doc\" ) ; if ( ! getAsString ( elem . getAsJsonObject ( ) , \"_id\" ) . startsWith ( \"_design\" ) ) { // skip design docs ReplicatorDocument rd = dbc . getGson ( ) . fromJson ( elem , ReplicatorDocument . class ) ; list . add ( rd ) ; } } return list ; } finally { close ( instream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a document from the replicator database . [CODESPLIT] public Response remove ( ) { assertNotEmpty ( replicatorDoc . getId ( ) , \"Doc id\" ) ; assertNotEmpty ( replicatorDoc . getRevision ( ) , \"Doc rev\" ) ; final URI uri = buildUri ( dbURI ) . path ( replicatorDoc . getId ( ) ) . query ( \"rev\" , replicatorDoc . getRevision ( ) ) . build ( ) ; return dbc . delete ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds an Object of the specified type . [CODESPLIT] public < T > T find ( Class < T > classType , String id , Params params ) { assertNotEmpty ( classType , \"Class\" ) ; assertNotEmpty ( id , \"id\" ) ; final URI uri = buildUri ( getDBUri ( ) ) . pathEncoded ( id ) . query ( params ) . build ( ) ; return get ( uri , classType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a document and return the result as { [CODESPLIT] public InputStream find ( String id ) { assertNotEmpty ( id , \"id\" ) ; return get ( buildUri ( getDBUri ( ) ) . path ( id ) . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a document given id and revision and returns the result as { [CODESPLIT] public InputStream find ( String id , String rev ) { assertNotEmpty ( id , \"id\" ) ; assertNotEmpty ( rev , \"rev\" ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( id ) . query ( \"rev\" , rev ) . build ( ) ; return get ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find documents using a declarative JSON querying syntax . [CODESPLIT] public < T > List < T > findDocs ( String jsonQuery , Class < T > classOfT ) { assertNotEmpty ( jsonQuery , \"jsonQuery\" ) ; HttpResponse response = null ; try { response = post ( buildUri ( getDBUri ( ) ) . path ( \"_find\" ) . build ( ) , jsonQuery ) ; Reader reader = new InputStreamReader ( getStream ( response ) , Charsets . UTF_8 ) ; JsonArray jsonArray = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . getAsJsonArray ( \"docs\" ) ; List < T > list = new ArrayList < T > ( ) ; for ( JsonElement jsonElem : jsonArray ) { JsonElement elem = jsonElem . getAsJsonObject ( ) ; T t = this . gson . fromJson ( elem , classOfT ) ; list . add ( t ) ; } return list ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a document exist in the database . [CODESPLIT] public boolean contains ( String id ) { assertNotEmpty ( id , \"id\" ) ; HttpResponse response = null ; try { response = head ( buildUri ( getDBUri ( ) ) . pathEncoded ( id ) . build ( ) ) ; } catch ( NoDocumentException e ) { return false ; } finally { close ( response ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an object in the database using HTTP <tt > POST< / tt > request . <p > The database will be responsible for generating the document id . [CODESPLIT] public Response post ( Object object ) { assertNotEmpty ( object , \"object\" ) ; HttpResponse response = null ; try { URI uri = buildUri ( getDBUri ( ) ) . build ( ) ; response = post ( uri , getGson ( ) . toJson ( object ) ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves a document with <tt > batch = ok< / tt > query param . [CODESPLIT] public void batch ( Object object ) { assertNotEmpty ( object , \"object\" ) ; HttpResponse response = null ; try { URI uri = buildUri ( getDBUri ( ) ) . query ( \"batch\" , \"ok\" ) . build ( ) ; response = post ( uri , getGson ( ) . toJson ( object ) ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a document from the database given both a document <code > _id< / code > and <code > _rev< / code > values . [CODESPLIT] public Response remove ( String id , String rev ) { assertNotEmpty ( id , \"id\" ) ; assertNotEmpty ( rev , \"rev\" ) ; final URI uri = buildUri ( getDBUri ( ) ) . pathEncoded ( id ) . query ( \"rev\" , rev ) . build ( ) ; return delete ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs bulk documents create and update request . [CODESPLIT] public List < Response > bulk ( List < ? > objects , boolean newEdits ) { assertNotEmpty ( objects , \"objects\" ) ; HttpResponse response = null ; try { final String newEditsVal = newEdits ? \"\\\"new_edits\\\": true, \" : \"\\\"new_edits\\\": false, \" ; final String json = String . format ( \"{%s%s%s}\" , newEditsVal , \"\\\"docs\\\": \" , getGson ( ) . toJson ( objects ) ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( \"_bulk_docs\" ) . build ( ) ; response = post ( uri , json ) ; return getResponseList ( response ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an attachment to a new document with a generated <tt > UUID< / tt > as the document id . <p > To retrieve an attachment see { [CODESPLIT] public Response saveAttachment ( InputStream in , String name , String contentType ) { assertNotEmpty ( in , \"in\" ) ; assertNotEmpty ( name , \"name\" ) ; assertNotEmpty ( contentType , \"ContentType\" ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( generateUUID ( ) ) . path ( \"/\" ) . path ( name ) . build ( ) ; return put ( uri , in , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an attachment to an existing document given both a document id and revision or save to a new document given only the id and rev as { [CODESPLIT] public Response saveAttachment ( InputStream in , String name , String contentType , String docId , String docRev ) { assertNotEmpty ( in , \"in\" ) ; assertNotEmpty ( name , \"name\" ) ; assertNotEmpty ( contentType , \"ContentType\" ) ; assertNotEmpty ( docId , \"docId\" ) ; final URI uri = buildUri ( getDBUri ( ) ) . pathEncoded ( docId ) . path ( \"/\" ) . path ( name ) . query ( \"rev\" , docRev ) . build ( ) ; return put ( uri , in , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes an Update Handler . <pre > Params params = new Params () . addParam ( field foo ) . addParam ( value bar ) ; String output = dbClient . invokeUpdateHandler ( designDoc / update1 docId params ) ; < / pre > [CODESPLIT] public String invokeUpdateHandler ( String updateHandlerUri , String docId , Params params ) { assertNotEmpty ( updateHandlerUri , \"uri\" ) ; assertNotEmpty ( docId , \"docId\" ) ; final String [ ] v = updateHandlerUri . split ( \"/\" ) ; final String path = String . format ( \"_design/%s/_update/%s/\" , v [ 0 ] , v [ 1 ] ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( path ) . path ( docId ) . query ( params ) . build ( ) ; final HttpResponse response = executeRequest ( new HttpPut ( uri ) ) ; return streamToString ( getStream ( response ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a HTTP request . <p > <b > Note< / b > : The response must be closed after use to release the connection . [CODESPLIT] public HttpResponse executeRequest ( HttpRequestBase request ) { try { return httpClient . execute ( host , request , createContext ( ) ) ; } catch ( IOException e ) { request . abort ( ) ; throw new CouchDbException ( \"Error executing request. \" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP GET request . [CODESPLIT] InputStream get ( HttpGet httpGet ) { HttpResponse response = executeRequest ( httpGet ) ; return getStream ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP GET request . [CODESPLIT] InputStream get ( URI uri ) { HttpGet get = new HttpGet ( uri ) ; get . addHeader ( \"Accept\" , \"application/json\" ) ; return get ( get ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP GET request . [CODESPLIT] < T > T get ( URI uri , Class < T > classType ) { InputStream in = null ; try { in = get ( uri ) ; return getGson ( ) . fromJson ( new InputStreamReader ( in , \"UTF-8\" ) , classType ) ; } catch ( UnsupportedEncodingException e ) { throw new CouchDbException ( e ) ; } finally { close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP PUT request saves or updates a document . [CODESPLIT] Response put ( URI uri , Object object , boolean newEntity ) { assertNotEmpty ( object , \"object\" ) ; HttpResponse response = null ; try { final JsonObject json = getGson ( ) . toJsonTree ( object ) . getAsJsonObject ( ) ; String id = getAsString ( json , \"_id\" ) ; String rev = getAsString ( json , \"_rev\" ) ; if ( newEntity ) { // save assertNull ( rev , \"rev\" ) ; id = ( id == null ) ? generateUUID ( ) : id ; } else { // update assertNotEmpty ( id , \"id\" ) ; assertNotEmpty ( rev , \"rev\" ) ; } final HttpPut put = new HttpPut ( buildUri ( uri ) . pathEncoded ( id ) . build ( ) ) ; setEntity ( put , json . toString ( ) ) ; response = executeRequest ( put ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP PUT request saves an attachment . [CODESPLIT] Response put ( URI uri , InputStream instream , String contentType ) { HttpResponse response = null ; try { final HttpPut httpPut = new HttpPut ( uri ) ; final InputStreamEntity entity = new InputStreamEntity ( instream , - 1 ) ; entity . setContentType ( contentType ) ; httpPut . setEntity ( entity ) ; response = executeRequest ( httpPut ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP POST request . [CODESPLIT] HttpResponse post ( URI uri , String json ) { HttpPost post = new HttpPost ( uri ) ; setEntity ( post , json ) ; return executeRequest ( post ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP DELETE request . [CODESPLIT] Response delete ( URI uri ) { HttpResponse response = null ; try { HttpDelete delete = new HttpDelete ( uri ) ; response = executeRequest ( delete ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates a HTTP response ; on error cases logs status and throws relevant exceptions . [CODESPLIT] void validate ( HttpResponse response ) throws IOException { final int code = response . getStatusLine ( ) . getStatusCode ( ) ; if ( code == 200 || code == 201 || code == 202 ) { // success (ok | created | accepted) return ; } String reason = response . getStatusLine ( ) . getReasonPhrase ( ) ; switch ( code ) { case HttpStatus . SC_NOT_FOUND : { throw new NoDocumentException ( reason ) ; } case HttpStatus . SC_CONFLICT : { throw new DocumentConflictException ( reason ) ; } default : { // other errors: 400 | 401 | 500 etc. throw new CouchDbException ( reason += EntityUtils . toString ( response . getEntity ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a JSON String as a request entity . [CODESPLIT] private void setEntity ( HttpEntityEnclosingRequestBase httpRequest , String json ) { StringEntity entity = new StringEntity ( json , \"UTF-8\" ) ; entity . setContentType ( \"application/json\" ) ; httpRequest . setEntity ( entity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds { [CODESPLIT] private Gson initGson ( GsonBuilder gsonBuilder ) { gsonBuilder . registerTypeAdapter ( JsonObject . class , new JsonDeserializer < JsonObject > ( ) { public JsonObject deserialize ( JsonElement json , Type typeOfT , JsonDeserializationContext context ) throws JsonParseException { return json . getAsJsonObject ( ) ; } } ) ; gsonBuilder . registerTypeAdapter ( JsonObject . class , new JsonSerializer < JsonObject > ( ) { public JsonElement serialize ( JsonObject src , Type typeOfSrc , JsonSerializationContext context ) { return src . getAsJsonObject ( ) ; } } ) ; return gsonBuilder . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an in - line document attachment . [CODESPLIT] public void addAttachment ( String name , Attachment attachment ) { if ( attachments == null ) attachments = new HashMap < String , Attachment > ( ) ; attachments . put ( name , attachment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests Change notifications of feed type continuous . <p > Feed notifications are accessed in an <i > iterator< / i > style . [CODESPLIT] public Changes continuousChanges ( ) { final URI uri = uriBuilder . query ( \"feed\" , \"continuous\" ) . build ( ) ; httpGet = new HttpGet ( uri ) ; final InputStream in = dbc . get ( httpGet ) ; final InputStreamReader is = new InputStreamReader ( in , Charsets . UTF_8 ) ; setReader ( new BufferedReader ( is ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests Change notifications of feed type normal . [CODESPLIT] public ChangesResult getChanges ( ) { final URI uri = uriBuilder . query ( \"feed\" , \"normal\" ) . build ( ) ; return dbc . get ( uri , ChangesResult . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads and sets the next feed in the stream . [CODESPLIT] private boolean readNextRow ( ) { boolean hasNext = false ; try { if ( ! stop ) { String row = \"\" ; do { row = getReader ( ) . readLine ( ) ; } while ( row . length ( ) == 0 ) ; if ( ! row . startsWith ( \"{\\\"last_seq\\\":\" ) ) { setNextRow ( gson . fromJson ( row , Row . class ) ) ; hasNext = true ; } } } catch ( Exception e ) { terminate ( ) ; throw new CouchDbException ( \"Error reading continuous stream.\" , e ) ; } if ( ! hasNext ) terminate ( ) ; return hasNext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<editor - fold defaultstate = collapsed desc = Generated Code > // GEN - BEGIN : initComponents [CODESPLIT] private void initComponents ( ) { jTabbedPane6 = new javax . swing . JTabbedPane ( ) ; jPanel2 = new javax . swing . JPanel ( ) ; jTabbedPane3 = new javax . swing . JTabbedPane ( ) ; jScrollPane7 = new javax . swing . JScrollPane ( ) ; jTextArea7 = new javax . swing . JTextArea ( ) ; jTabbedPane1 = new javax . swing . JTabbedPane ( ) ; jScrollPane3 = new javax . swing . JScrollPane ( ) ; jTextArea1 = new javax . swing . JTextArea ( ) ; jLabel2 = new javax . swing . JLabel ( ) ; jTabbedPane2 = new javax . swing . JTabbedPane ( ) ; jScrollPane4 = new javax . swing . JScrollPane ( ) ; jTextArea4 = new javax . swing . JTextArea ( ) ; jTabbedPane4 = new javax . swing . JTabbedPane ( ) ; jScrollPane5 = new javax . swing . JScrollPane ( ) ; jTextArea5 = new javax . swing . JTextArea ( ) ; jTabbedPane5 = new javax . swing . JTabbedPane ( ) ; jScrollPane6 = new javax . swing . JScrollPane ( ) ; jTextArea6 = new javax . swing . JTextArea ( ) ; jButton2 = new javax . swing . JButton ( ) ; jTextField1 = new HistoryComboBox ( ) ; jButton4 = new javax . swing . JButton ( ) ; jButton5 = new javax . swing . JButton ( ) ; jButton6 = new javax . swing . JButton ( ) ; jButton8 = new javax . swing . JButton ( ) ; jButton9 = new javax . swing . JButton ( ) ; jPanel1 = new javax . swing . JPanel ( ) ; jLabel1 = new javax . swing . JLabel ( ) ; jComboBox1 = new javax . swing . JComboBox ( ) ; jLabel3 = new javax . swing . JLabel ( ) ; jLabel4 = new javax . swing . JLabel ( ) ; jComboBox2 = new javax . swing . JComboBox ( ) ; jComboBox3 = new javax . swing . JComboBox ( ) ; jLabel5 = new javax . swing . JLabel ( ) ; jComboBox4 = new javax . swing . JComboBox ( ) ; jLabel6 = new javax . swing . JLabel ( ) ; jComboBox5 = new javax . swing . JComboBox ( ) ; jLabel7 = new javax . swing . JLabel ( ) ; jComboBox6 = new javax . swing . JComboBox ( ) ; jLabel12 = new javax . swing . JLabel ( ) ; jTextField5 = new javax . swing . JTextField ( ) ; jLabel10 = new javax . swing . JLabel ( ) ; jLabel9 = new javax . swing . JLabel ( ) ; jTextField3 = new javax . swing . JTextField ( ) ; jTextField2 = new javax . swing . JTextField ( ) ; jLabel11 = new javax . swing . JLabel ( ) ; jLabel8 = new javax . swing . JLabel ( ) ; jTextField4 = new javax . swing . JTextField ( ) ; jLabel13 = new javax . swing . JLabel ( ) ; jTextField7 = new javax . swing . JTextField ( ) ; jTextField6 = new javax . swing . JTextField ( ) ; jLabel14 = new javax . swing . JLabel ( ) ; jComboBox7 = new javax . swing . JComboBox ( ) ; jLabel15 = new javax . swing . JLabel ( ) ; jComboBox8 = new javax . swing . JComboBox ( ) ; jPanel3 = new javax . swing . JPanel ( ) ; jTabbedPane7 = new javax . swing . JTabbedPane ( ) ; jScrollPane1 = new javax . swing . JScrollPane ( ) ; jTextPane1 = new javax . swing . JTextPane ( ) ; jScrollPane17 = new javax . swing . JScrollPane ( ) ; jTextPane12 = new javax . swing . JTextPane ( ) ; jScrollPane16 = new javax . swing . JScrollPane ( ) ; jTextPane11 = new javax . swing . JTextPane ( ) ; jScrollPane2 = new javax . swing . JScrollPane ( ) ; jTextPane2 = new javax . swing . JTextPane ( ) ; jScrollPane15 = new javax . swing . JScrollPane ( ) ; jTextPane10 = new javax . swing . JTextPane ( ) ; jScrollPane8 = new javax . swing . JScrollPane ( ) ; jTextPane3 = new javax . swing . JTextPane ( ) ; jScrollPane9 = new javax . swing . JScrollPane ( ) ; jTextPane4 = new javax . swing . JTextPane ( ) ; jScrollPane10 = new javax . swing . JScrollPane ( ) ; jTextPane5 = new javax . swing . JTextPane ( ) ; jScrollPane11 = new javax . swing . JScrollPane ( ) ; jTextPane6 = new javax . swing . JTextPane ( ) ; jScrollPane12 = new javax . swing . JScrollPane ( ) ; jTextPane7 = new javax . swing . JTextPane ( ) ; jScrollPane13 = new javax . swing . JScrollPane ( ) ; jTextPane8 = new javax . swing . JTextPane ( ) ; jScrollPane14 = new javax . swing . JScrollPane ( ) ; jTextPane9 = new javax . swing . JTextPane ( ) ; setDefaultCloseOperation ( javax . swing . WindowConstants . EXIT_ON_CLOSE ) ; java . util . ResourceBundle bundle = java . util . ResourceBundle . getBundle ( \"com/github/moneytostr/messages_ru\" ) ; // NOI18N setTitle ( bundle . getString ( \"MONEYTOSTR\" ) ) ; // NOI18N jPanel2 . setBorder ( javax . swing . BorderFactory . createTitledBorder ( \"\" ) ) ; jPanel2 . setMaximumSize ( new java . awt . Dimension ( 610 , 444 ) ) ; jPanel2 . setPreferredSize ( new java . awt . Dimension ( 662 , 447 ) ) ; jScrollPane7 . setVerticalScrollBarPolicy ( javax . swing . ScrollPaneConstants . VERTICAL_SCROLLBAR_NEVER ) ; jTextArea7 . setColumns ( 20 ) ; jTextArea7 . setRows ( 5 ) ; jScrollPane7 . setViewportView ( jTextArea7 ) ; jTabbedPane3 . addTab ( bundle . getString ( \"fromCapitalLetter\" ) , jScrollPane7 ) ; // NOI18N jScrollPane3 . setVerticalScrollBarPolicy ( javax . swing . ScrollPaneConstants . VERTICAL_SCROLLBAR_NEVER ) ; jTextArea1 . setColumns ( 20 ) ; jTextArea1 . setRows ( 5 ) ; jScrollPane3 . setViewportView ( jTextArea1 ) ; jTabbedPane1 . addTab ( bundle . getString ( \"result\" ) , jScrollPane3 ) ; // NOI18N jLabel2 . setText ( bundle . getString ( \"enterTheDigitalAmount\" ) ) ; // NOI18N jScrollPane4 . setVerticalScrollBarPolicy ( javax . swing . ScrollPaneConstants . VERTICAL_SCROLLBAR_NEVER ) ; jTextArea4 . setColumns ( 20 ) ; jTextArea4 . setRows ( 5 ) ; jScrollPane4 . setViewportView ( jTextArea4 ) ; jTabbedPane2 . addTab ( bundle . getString ( \"penniesByDigits\" ) , jScrollPane4 ) ; // NOI18N jScrollPane5 . setVerticalScrollBarPolicy ( javax . swing . ScrollPaneConstants . VERTICAL_SCROLLBAR_NEVER ) ; jTextArea5 . setColumns ( 20 ) ; jTextArea5 . setRows ( 5 ) ; jScrollPane5 . setViewportView ( jTextArea5 ) ; jTabbedPane4 . addTab ( bundle . getString ( \"withVat\" ) , jScrollPane5 ) ; // NOI18N jScrollPane6 . setVerticalScrollBarPolicy ( javax . swing . ScrollPaneConstants . VERTICAL_SCROLLBAR_NEVER ) ; jTextArea6 . setColumns ( 20 ) ; jTextArea6 . setRows ( 5 ) ; jScrollPane6 . setViewportView ( jTextArea6 ) ; jTabbedPane5 . addTab ( bundle . getString ( \"withVatByString\" ) , jScrollPane6 ) ; // NOI18N jButton2 . setText ( \"*\" ) ; jButton2 . setBorder ( new javax . swing . border . SoftBevelBorder ( javax . swing . border . BevelBorder . RAISED ) ) ; jButton2 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton2ActionPerformed ( evt ) ; } } ) ; jTextField1 . setEditable ( true ) ; jTextField1 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jTextField1ActionPerformed ( evt ) ; } } ) ; jButton4 . setIcon ( new javax . swing . ImageIcon ( getClass ( ) . getResource ( \"/com/github/moneytostr/copy.png\" ) ) ) ; // NOI18N jButton4 . setToolTipText ( bundle . getString ( \"copyToTheBuffer\" ) ) ; // NOI18N jButton4 . setBorder ( new javax . swing . border . SoftBevelBorder ( javax . swing . border . BevelBorder . RAISED ) ) ; jButton4 . setFocusable ( false ) ; jButton4 . setMaximumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton4 . setMinimumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton4 . setPreferredSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton4 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton4ActionPerformed ( evt ) ; } } ) ; jButton5 . setIcon ( new javax . swing . ImageIcon ( getClass ( ) . getResource ( \"/com/github/moneytostr/copy.png\" ) ) ) ; // NOI18N jButton5 . setToolTipText ( bundle . getString ( \"copyToTheBuffer\" ) ) ; // NOI18N jButton5 . setBorder ( new javax . swing . border . SoftBevelBorder ( javax . swing . border . BevelBorder . RAISED ) ) ; jButton5 . setFocusable ( false ) ; jButton5 . setMaximumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton5 . setMinimumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton5 . setPreferredSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton5 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton5ActionPerformed ( evt ) ; } } ) ; jButton6 . setIcon ( new javax . swing . ImageIcon ( getClass ( ) . getResource ( \"/com/github/moneytostr/copy.png\" ) ) ) ; // NOI18N jButton6 . setToolTipText ( bundle . getString ( \"copyToTheBuffer\" ) ) ; // NOI18N jButton6 . setBorder ( new javax . swing . border . SoftBevelBorder ( javax . swing . border . BevelBorder . RAISED ) ) ; jButton6 . setFocusable ( false ) ; jButton6 . setMaximumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton6 . setMinimumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton6 . setPreferredSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton6 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton6ActionPerformed ( evt ) ; } } ) ; jButton8 . setIcon ( new javax . swing . ImageIcon ( getClass ( ) . getResource ( \"/com/github/moneytostr/copy.png\" ) ) ) ; // NOI18N jButton8 . setToolTipText ( bundle . getString ( \"copyToTheBuffer\" ) ) ; // NOI18N jButton8 . setBorder ( new javax . swing . border . SoftBevelBorder ( javax . swing . border . BevelBorder . RAISED ) ) ; jButton8 . setFocusable ( false ) ; jButton8 . setMaximumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton8 . setMinimumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton8 . setPreferredSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton8 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton8ActionPerformed ( evt ) ; } } ) ; jButton9 . setIcon ( new javax . swing . ImageIcon ( getClass ( ) . getResource ( \"/com/github/moneytostr/copy.png\" ) ) ) ; // NOI18N jButton9 . setToolTipText ( bundle . getString ( \"copyToTheBuffer\" ) ) ; // NOI18N jButton9 . setBorder ( new javax . swing . border . SoftBevelBorder ( javax . swing . border . BevelBorder . RAISED ) ) ; jButton9 . setFocusable ( false ) ; jButton9 . setMaximumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton9 . setMinimumSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton9 . setPreferredSize ( new java . awt . Dimension ( 30 , 30 ) ) ; jButton9 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton9ActionPerformed ( evt ) ; } } ) ; org . jdesktop . layout . GroupLayout jPanel2Layout = new org . jdesktop . layout . GroupLayout ( jPanel2 ) ; jPanel2 . setLayout ( jPanel2Layout ) ; jPanel2Layout . setHorizontalGroup ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jPanel2Layout . createSequentialGroup ( ) . addContainerGap ( ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . TRAILING ) . add ( jTabbedPane2 ) . add ( org . jdesktop . layout . GroupLayout . LEADING , jTabbedPane5 ) . add ( org . jdesktop . layout . GroupLayout . LEADING , jTabbedPane4 ) . add ( org . jdesktop . layout . GroupLayout . LEADING , jTabbedPane3 ) . add ( org . jdesktop . layout . GroupLayout . LEADING , jPanel2Layout . createSequentialGroup ( ) . add ( jLabel2 ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jTextField1 , 0 , 636 , Short . MAX_VALUE ) ) . add ( org . jdesktop . layout . GroupLayout . LEADING , jTabbedPane1 ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jButton8 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 29 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jButton2 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 29 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jButton4 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 29 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . add ( jButton5 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 29 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jButton6 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 29 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . add ( jButton9 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 29 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addContainerGap ( ) ) ) ; jPanel2Layout . setVerticalGroup ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jPanel2Layout . createSequentialGroup ( ) . addContainerGap ( ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel2 ) . add ( jButton2 ) . add ( jTextField1 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane1 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 112 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jPanel2Layout . createSequentialGroup ( ) . add ( 23 , 23 , 23 ) . add ( jButton4 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . UNRELATED ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane3 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 106 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jPanel2Layout . createSequentialGroup ( ) . add ( jButton6 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( 52 , 52 , 52 ) ) ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane4 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 107 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jPanel2Layout . createSequentialGroup ( ) . add ( jButton5 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( 53 , 53 , 53 ) ) ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane5 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 112 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jPanel2Layout . createSequentialGroup ( ) . add ( jButton8 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( 57 , 57 , 57 ) ) ) . add ( jPanel2Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane2 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , 112 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jPanel2Layout . createSequentialGroup ( ) . add ( jButton9 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( 58 , 58 , 58 ) ) ) . addContainerGap ( org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) ; jTabbedPane6 . addTab ( bundle . getString ( \"converter\" ) , jPanel2 ) ; // NOI18N jLabel1 . setText ( bundle . getString ( \"language\" ) ) ; // NOI18N jComboBox1 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"Русский\", \"Укра и ский\", \"Английсикй\" }) )      jComboBox1 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox1ActionPerformed ( evt ) ; } } ) ; jLabel3 . setText ( bundle . getString ( \"currency\" ) ) ; // NOI18N jLabel4 . setText ( bundle . getString ( \"pennies\" ) ) ; // NOI18N jComboBox2 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"RUR\" , \"UAH\" , \"USD\" , \"Custom\" } ) ) ; jComboBox2 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox2ActionPerformed ( evt ) ; } } ) ; jComboBox3 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"Цифрами\", \"Проп и ью\" }));     jComboBox3 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox3ActionPerformed ( evt ) ; } } ) ; jLabel5 . setText ( bundle . getString ( \"toCopyToTheBuffer\" ) ) ; // NOI18N jComboBox4 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"не копировать\", \"Результат \"  \"С заглавной буквы\" , \"С НДС\", \"С НДС прописью\", \"Копейк и цифрами\" }) )        jComboBox4 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox4ActionPerformed ( evt ) ; } } ) ; jLabel6 . setText ( bundle . getString ( \"vat\" ) ) ; // NOI18N jComboBox5 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"10%\" , \"12%\" , \"18%\" , \"20%\" , \"22%\" , \"25%\" } ) ) ; jComboBox5 . setSelectedIndex ( 2 ) ; jComboBox5 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox5ActionPerformed ( evt ) ; } } ) ; jLabel7 . setText ( bundle . getString ( \"interfaceLanguage\" ) ) ; // NOI18N jComboBox6 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"Русский\", \"Укра и ский\" }));     jComboBox6 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox6ActionPerformed ( evt ) ; } } ) ; jLabel12 . setText ( bundle . getString ( \"kopTwoUnit\" ) ) ; // NOI18N jTextField5 . setText ( \"евроцент\");   jTextField5 . addKeyListener ( new java . awt . event . KeyAdapter ( ) { public void keyTyped ( java . awt . event . KeyEvent evt ) { jTextField5KeyTyped ( evt ) ; } } ) ; jLabel10 . setText ( bundle . getString ( \"rubFiveUnit\" ) ) ; // NOI18N jLabel9 . setText ( bundle . getString ( \"rubTwoUnit\" ) ) ; // NOI18N jTextField3 . setText ( \"евро\");   jTextField3 . addKeyListener ( new java . awt . event . KeyAdapter ( ) { public void keyTyped ( java . awt . event . KeyEvent evt ) { jTextField3KeyTyped ( evt ) ; } } ) ; jTextField2 . setText ( \"евро\");   jTextField2 . addKeyListener ( new java . awt . event . KeyAdapter ( ) { public void keyTyped ( java . awt . event . KeyEvent evt ) { jTextField2KeyTyped ( evt ) ; } } ) ; jLabel11 . setText ( bundle . getString ( \"kopOneUnit\" ) ) ; // NOI18N jLabel8 . setText ( bundle . getString ( \"rubOneUnit\" ) ) ; // NOI18N jTextField4 . setText ( \"евро\");   jTextField4 . addKeyListener ( new java . awt . event . KeyAdapter ( ) { public void keyTyped ( java . awt . event . KeyEvent evt ) { jTextField4KeyTyped ( evt ) ; } } ) ; jLabel13 . setText ( bundle . getString ( \"kopFiveUnit\" ) ) ; // NOI18N jTextField7 . setText ( \"евроцентов\");   jTextField7 . addKeyListener ( new java . awt . event . KeyAdapter ( ) { public void keyTyped ( java . awt . event . KeyEvent evt ) { jTextField7KeyTyped ( evt ) ; } } ) ; jTextField6 . setText ( \"евроцента\");   jTextField6 . addKeyListener ( new java . awt . event . KeyAdapter ( ) { public void keyTyped ( java . awt . event . KeyEvent evt ) { jTextField6KeyTyped ( evt ) ; } } ) ; jLabel14 . setText ( bundle . getString ( \"rubSex\" ) ) ; // NOI18N jComboBox7 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"M\" , \"F\" } ) ) ; jComboBox7 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox7ActionPerformed ( evt ) ; } } ) ; jLabel15 . setText ( bundle . getString ( \"kopSex\" ) ) ; // NOI18N jComboBox8 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { \"M\" , \"F\" } ) ) ; jComboBox8 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox8ActionPerformed ( evt ) ; } } ) ; org . jdesktop . layout . GroupLayout jPanel1Layout = new org . jdesktop . layout . GroupLayout ( jPanel1 ) ; jPanel1 . setLayout ( jPanel1Layout ) ; jPanel1Layout . setHorizontalGroup ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jPanel1Layout . createSequentialGroup ( ) . add ( 23 , 23 , 23 ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jPanel1Layout . createSequentialGroup ( ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel1 ) . add ( jLabel3 ) . add ( jLabel4 ) . add ( jLabel5 ) . add ( jLabel6 ) . add ( jLabel7 ) ) . add ( 29 , 29 , 29 ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jComboBox5 , 0 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . add ( jComboBox2 , 0 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jComboBox3 , 0 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . add ( org . jdesktop . layout . GroupLayout . TRAILING , jComboBox4 , 0 , 658 , Short . MAX_VALUE ) . add ( jComboBox1 , 0 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . add ( jComboBox6 , 0 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) . add ( jPanel1Layout . createSequentialGroup ( ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel9 ) . add ( jLabel8 ) . add ( jLabel10 ) . add ( jLabel11 ) . add ( jLabel12 ) . add ( jLabel13 ) . add ( jLabel14 ) . add ( jLabel15 ) ) . add ( 25 , 25 , 25 ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTextField7 ) . add ( jTextField6 ) . add ( jTextField5 ) . add ( jTextField4 ) . add ( jTextField2 ) . add ( jTextField3 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , 659 , Short . MAX_VALUE ) . add ( jPanel1Layout . createSequentialGroup ( ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jComboBox8 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jComboBox7 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . add ( 0 , 0 , Short . MAX_VALUE ) ) ) ) ) . addContainerGap ( ) ) ) ; jPanel1Layout . setVerticalGroup ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jPanel1Layout . createSequentialGroup ( ) . add ( 23 , 23 , 23 ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel1 ) . add ( jComboBox1 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . UNRELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel3 ) . add ( jComboBox2 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel8 ) . add ( jTextField2 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel9 ) . add ( jTextField3 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel10 ) . add ( jTextField4 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . add ( 10 , 10 , 10 ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jComboBox7 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) . add ( jLabel14 ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel11 ) . add ( jTextField5 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel12 ) . add ( jTextField6 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel13 ) . add ( jTextField7 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . RELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel15 ) . add ( jComboBox8 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . add ( 8 , 8 , 8 ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel4 ) . add ( jComboBox3 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . UNRELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jLabel5 ) . add ( jComboBox4 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . UNRELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel6 ) . add ( jComboBox5 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( org . jdesktop . layout . LayoutStyle . UNRELATED ) . add ( jPanel1Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . BASELINE ) . add ( jLabel7 ) . add ( jComboBox6 , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , org . jdesktop . layout . GroupLayout . PREFERRED_SIZE ) ) . addContainerGap ( 207 , Short . MAX_VALUE ) ) ) ; jTabbedPane6 . addTab ( bundle . getString ( \"settings\" ) , jPanel1 ) ; // NOI18N jTabbedPane7 . setTabPlacement ( javax . swing . JTabbedPane . LEFT ) ; jScrollPane1 . setBorder ( null ) ; jTextPane1 . setEditable ( false ) ; jTextPane1 . setBorder ( null ) ; jTextPane1 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane1 . setViewportView ( jTextPane1 ) ; jTabbedPane7 . addTab ( \"c#\" , jScrollPane1 ) ; jScrollPane17 . setBorder ( null ) ; jTextPane12 . setEditable ( false ) ; jTextPane12 . setBorder ( null ) ; jTextPane12 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane17 . setViewportView ( jTextPane12 ) ; jTabbedPane7 . addTab ( \"c++\" , jScrollPane17 ) ; jScrollPane16 . setBorder ( null ) ; jTextPane11 . setEditable ( false ) ; jTextPane11 . setBorder ( null ) ; jTextPane11 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane16 . setViewportView ( jTextPane11 ) ; jTabbedPane7 . addTab ( \"coffeescript\" , jScrollPane16 ) ; jScrollPane2 . setBorder ( null ) ; jTextPane2 . setEditable ( false ) ; jTextPane2 . setBorder ( null ) ; jTextPane2 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane2 . setViewportView ( jTextPane2 ) ; jTabbedPane7 . addTab ( \"dart\" , jScrollPane2 ) ; jScrollPane15 . setBorder ( null ) ; jTextPane10 . setEditable ( false ) ; jTextPane10 . setBorder ( null ) ; jTextPane10 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane15 . setViewportView ( jTextPane10 ) ; jTabbedPane7 . addTab ( \"groovy\" , jScrollPane15 ) ; jScrollPane8 . setBorder ( null ) ; jTextPane3 . setEditable ( false ) ; jTextPane3 . setBorder ( null ) ; jTextPane3 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane8 . setViewportView ( jTextPane3 ) ; jTabbedPane7 . addTab ( \"java\" , jScrollPane8 ) ; jScrollPane9 . setBorder ( null ) ; jTextPane4 . setEditable ( false ) ; jTextPane4 . setBorder ( null ) ; jTextPane4 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane9 . setViewportView ( jTextPane4 ) ; jTabbedPane7 . addTab ( \"js\" , jScrollPane9 ) ; jScrollPane10 . setBorder ( null ) ; jTextPane5 . setEditable ( false ) ; jTextPane5 . setBorder ( null ) ; jTextPane5 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane10 . setViewportView ( jTextPane5 ) ; jTabbedPane7 . addTab ( \"php\" , jScrollPane10 ) ; jScrollPane11 . setBorder ( null ) ; jTextPane6 . setEditable ( false ) ; jTextPane6 . setBorder ( null ) ; jTextPane6 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane11 . setViewportView ( jTextPane6 ) ; jTabbedPane7 . addTab ( \"python\" , jScrollPane11 ) ; jScrollPane12 . setBorder ( null ) ; jTextPane7 . setEditable ( false ) ; jTextPane7 . setBorder ( null ) ; jTextPane7 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane12 . setViewportView ( jTextPane7 ) ; jTabbedPane7 . addTab ( \"ruby\" , jScrollPane12 ) ; jScrollPane13 . setBorder ( null ) ; jTextPane8 . setEditable ( false ) ; jTextPane8 . setBorder ( null ) ; jTextPane8 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane13 . setViewportView ( jTextPane8 ) ; jTabbedPane7 . addTab ( \"scala\" , jScrollPane13 ) ; jScrollPane14 . setBorder ( null ) ; jTextPane9 . setEditable ( false ) ; jTextPane9 . setBorder ( null ) ; jTextPane9 . setFont ( new java . awt . Font ( \"SansSerif\" , 0 , 14 ) ) ; // NOI18N jScrollPane14 . setViewportView ( jTextPane9 ) ; jTabbedPane7 . addTab ( \"typescript\" , jScrollPane14 ) ; org . jdesktop . layout . GroupLayout jPanel3Layout = new org . jdesktop . layout . GroupLayout ( jPanel3 ) ; jPanel3 . setLayout ( jPanel3Layout ) ; jPanel3Layout . setHorizontalGroup ( jPanel3Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane7 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , 825 , Short . MAX_VALUE ) ) ; jPanel3Layout . setVerticalGroup ( jPanel3Layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane7 , org . jdesktop . layout . GroupLayout . DEFAULT_SIZE , 614 , Short . MAX_VALUE ) ) ; jTabbedPane6 . addTab ( bundle . getString ( \"sourceCodes\" ) , jPanel3 ) ; // NOI18N org . jdesktop . layout . GroupLayout layout = new org . jdesktop . layout . GroupLayout ( getContentPane ( ) ) ; getContentPane ( ) . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane6 ) ) ; layout . setVerticalGroup ( layout . createParallelGroup ( org . jdesktop . layout . GroupLayout . LEADING ) . add ( jTabbedPane6 ) ) ; pack ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jButton2ActionPerformed [CODESPLIT] private void jTextField1ActionPerformed ( java . awt . event . ActionEvent evt ) { //GEN-FIRST:event_jTextField1ActionPerformed Object obj = jTextField1 . getSelectedItem ( ) ; if ( obj != null && evt . getActionCommand ( ) . equals ( \"comboBoxEdited\" ) ) { generateResult ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jComboBox3ActionPerformed [CODESPLIT] private void jButton4ActionPerformed ( java . awt . event . ActionEvent evt ) { //GEN-FIRST:event_jButton4ActionPerformed StringSelection ss = new StringSelection ( jTextArea1 . getText ( ) ) ; Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . setContents ( ss , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jButton4ActionPerformed [CODESPLIT] private void jButton5ActionPerformed ( java . awt . event . ActionEvent evt ) { //GEN-FIRST:event_jButton5ActionPerformed StringSelection ss = new StringSelection ( jTextArea5 . getText ( ) ) ; Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . setContents ( ss , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jButton5ActionPerformed [CODESPLIT] private void jButton6ActionPerformed ( java . awt . event . ActionEvent evt ) { //GEN-FIRST:event_jButton6ActionPerformed StringSelection ss = new StringSelection ( jTextArea7 . getText ( ) ) ; Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . setContents ( ss , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jButton6ActionPerformed [CODESPLIT] private void jButton8ActionPerformed ( java . awt . event . ActionEvent evt ) { //GEN-FIRST:event_jButton8ActionPerformed StringSelection ss = new StringSelection ( jTextArea6 . getText ( ) ) ; Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . setContents ( ss , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jButton8ActionPerformed [CODESPLIT] private void jButton9ActionPerformed ( java . awt . event . ActionEvent evt ) { //GEN-FIRST:event_jButton9ActionPerformed StringSelection ss = new StringSelection ( jTextArea4 . getText ( ) ) ; Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) . setContents ( ss , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jComboBox5ActionPerformed [CODESPLIT] private void jComboBox6ActionPerformed ( java . awt . event . ActionEvent evt ) { //GEN-FIRST:event_jComboBox6ActionPerformed int selected = ( ( javax . swing . JComboBox ) evt . getSource ( ) ) . getSelectedIndex ( ) ; setupLanguage ( selected ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "GEN - LAST : event_jTextField7KeyTyped [CODESPLIT] private void setupMoneyToStrVariables ( ) { moneyToStrTxt = new MoneyToStr ( MoneyToStr . Currency . values ( ) [ jComboBox2 . getSelectedIndex ( ) ] , MoneyToStr . Language . values ( ) [ jComboBox1 . getSelectedIndex ( ) ] , MoneyToStr . Pennies . values ( ) [ jComboBox3 . getSelectedIndex ( ) ] ) ; moneyToStrNum = new MoneyToStr ( MoneyToStr . Currency . values ( ) [ jComboBox2 . getSelectedIndex ( ) ] , MoneyToStr . Language . values ( ) [ jComboBox1 . getSelectedIndex ( ) ] , MoneyToStr . Pennies . NUMBER ) ; if ( jComboBox2 . getSelectedIndex ( ) == 3 ) { String [ ] names = new String [ 8 ] ; names [ 0 ] = jTextField2 . getText ( ) ; names [ 1 ] = jTextField3 . getText ( ) ; names [ 2 ] = jTextField4 . getText ( ) ; names [ 3 ] = jComboBox7 . getModel ( ) . getSelectedItem ( ) . toString ( ) ; names [ 4 ] = jTextField5 . getText ( ) ; names [ 5 ] = jTextField6 . getText ( ) ; names [ 6 ] = jTextField7 . getText ( ) ; names [ 7 ] = jComboBox8 . getModel ( ) . getSelectedItem ( ) . toString ( ) ; moneyToStrTxt = new MoneyToStr ( MoneyToStr . Currency . values ( ) [ jComboBox2 . getSelectedIndex ( ) ] , MoneyToStr . Language . values ( ) [ jComboBox1 . getSelectedIndex ( ) ] , MoneyToStr . Pennies . values ( ) [ jComboBox3 . getSelectedIndex ( ) ] , names ) ; moneyToStrNum = new MoneyToStr ( MoneyToStr . Currency . values ( ) [ jComboBox2 . getSelectedIndex ( ) ] , MoneyToStr . Language . values ( ) [ jComboBox1 . getSelectedIndex ( ) ] , MoneyToStr . Pennies . NUMBER , names ) ; } boolean isCustomCurrency = jComboBox2 . getSelectedIndex ( ) == 3 ; jTextField2 . setEnabled ( isCustomCurrency ) ; jTextField3 . setEnabled ( isCustomCurrency ) ; jTextField4 . setEnabled ( isCustomCurrency ) ; jComboBox7 . setEnabled ( isCustomCurrency ) ; jTextField5 . setEnabled ( isCustomCurrency ) ; jTextField6 . setEnabled ( isCustomCurrency ) ; jTextField7 . setEnabled ( isCustomCurrency ) ; jComboBox8 . setEnabled ( isCustomCurrency ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts percent to string . [CODESPLIT] public static String percentToStr ( Double amount , Language lang ) { return percentToStr ( amount , lang , Pennies . TEXT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts percent to string . [CODESPLIT] public static String percentToStr ( Double amount , Language lang , Pennies pennies ) { if ( amount == null ) { throw new IllegalArgumentException ( \"amount is null\" ) ; } if ( lang == null ) { throw new IllegalArgumentException ( \"language is null\" ) ; } if ( pennies == null ) { throw new IllegalArgumentException ( \"pennies is null\" ) ; } Long intPart = amount . longValue ( ) ; Long fractPart = 0L ; String result ; if ( amount . floatValue ( ) == amount . intValue ( ) ) { result = new MoneyToStr ( Currency . PER10 , lang , pennies ) . convert ( amount . longValue ( ) , 0L ) ; } else if ( Double . valueOf ( amount * NUM10 ) . floatValue ( ) == Double . valueOf ( amount * NUM10 ) . intValue ( ) ) { fractPart = Math . round ( ( amount - intPart ) * NUM10 ) ; result = new MoneyToStr ( Currency . PER10 , lang , pennies ) . convert ( intPart , fractPart ) ; } else if ( Double . valueOf ( amount * NUM100 ) . floatValue ( ) == Double . valueOf ( amount * NUM100 ) . intValue ( ) ) { fractPart = Math . round ( ( amount - intPart ) * NUM100 ) ; result = new MoneyToStr ( Currency . PER100 , lang , pennies ) . convert ( intPart , fractPart ) ; } else if ( Double . valueOf ( amount * NUM1000 ) . floatValue ( ) == Double . valueOf ( amount * NUM1000 ) . intValue ( ) ) { fractPart = Math . round ( ( amount - intPart ) * NUM1000 ) ; result = new MoneyToStr ( Currency . PER1000 , lang , pennies ) . convert ( intPart , fractPart ) ; } else { fractPart = Math . round ( ( amount - intPart ) * NUM10000 ) ; result = new MoneyToStr ( Currency . PER10000 , lang , pennies ) . convert ( intPart , fractPart ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts double value to the text description . [CODESPLIT] public String convert ( Double theMoney ) { if ( theMoney == null ) { throw new IllegalArgumentException ( \"theMoney is null\" ) ; } Long intPart = theMoney . longValue ( ) ; Long fractPart = Math . round ( ( theMoney - intPart ) * NUM100 ) ; if ( currency == Currency . PER1000 ) { fractPart = Math . round ( ( theMoney - intPart ) * NUM1000 ) ; } return convert ( intPart , fractPart ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts amount to words . Usage : MoneyToStr moneyToStr = new MoneyToStr ( MoneyToStr . Currency . UAH MoneyToStr . Language . UKR MoneyToStr . Pennies . NUMBER ) ; String result = moneyToStr . convert ( 123D ) ; Expected : result = сто двадцять три гривні 00 копійок [CODESPLIT] public String convert ( Long theMoney , Long theKopeiki ) { if ( theMoney == null ) { throw new IllegalArgumentException ( \"theMoney is null\" ) ; } if ( theKopeiki == null ) { throw new IllegalArgumentException ( \"theKopeiki is null\" ) ; } StringBuilder money2str = new StringBuilder ( ) ; Long triadNum = 0L ; Long theTriad ; Long intPart = theMoney ; if ( intPart == 0 ) { money2str . append ( messages . get ( \"0\" ) [ 0 ] + \" \" ) ; } do { theTriad = intPart % NUM1000 ; money2str . insert ( 0 , triad2Word ( theTriad , triadNum , rubSex ) ) ; if ( triadNum == 0 ) { if ( ( theTriad % NUM100 ) / NUM10 == NUM1 ) { money2str . append ( rubFiveUnit ) ; } else { switch ( Long . valueOf ( theTriad % NUM10 ) . byteValue ( ) ) { case NUM1 : money2str . append ( rubOneUnit ) ; break ; case NUM2 : case NUM3 : case NUM4 : money2str . append ( rubTwoUnit ) ; break ; default : money2str . append ( rubFiveUnit ) ; break ; } } } intPart /= NUM1000 ; triadNum ++ ; } while ( intPart > 0 ) ; if ( pennies == Pennies . TEXT ) { money2str . append ( language == Language . ENG ? \" and \" : \" \" ) . append ( theKopeiki == 0 ? messages . get ( \"0\" ) [ 0 ] + \" \" : triad2Word ( theKopeiki , 0L , kopSex ) ) ; } else { money2str . append ( \" \" + ( theKopeiki < 10 ? \"0\" + theKopeiki : theKopeiki ) + \" \" ) ; } if ( theKopeiki >= NUM11 && theKopeiki <= NUM14 ) { money2str . append ( kopFiveUnit ) ; } else { switch ( ( byte ) ( theKopeiki % NUM10 ) ) { case NUM1 : money2str . append ( kopOneUnit ) ; break ; case NUM2 : case NUM3 : case NUM4 : money2str . append ( kopTwoUnit ) ; break ; default : money2str . append ( kopFiveUnit ) ; break ; } } return money2str . toString ( ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to release any locks on shutdown so that other clients can obtain those locks without having to wait for them to expire . [CODESPLIT] public void shutdown ( ) { try { locksExecutor . shutdown ( ) ; locksExecutor . awaitTermination ( 5 , TimeUnit . SECONDS ) ; CountDownLatch latch = new CountDownLatch ( 1 ) ; activeLocksLock . writeLock ( ) . lock ( ) ; Observable . from ( activeLocks . entrySet ( ) ) . map ( Map . Entry :: getValue ) . flatMap ( lock -> releaseLock ( lock . getName ( ) , lock . getValue ( ) ) . map ( released -> new Lock ( lock . getName ( ) , lock . getValue ( ) , lock . getExpiration ( ) , lock . getRenewalRate ( ) , ! released ) ) ) . subscribe ( lock -> { if ( lock . isLocked ( ) ) { logger . infof ( \"Failed to release lock %s\" , lock . getName ( ) ) ; } } , t -> { logger . info ( \"There was an error while releasing locks\" , t ) ; latch . countDown ( ) ; } , latch :: countDown ) ; latch . await ( ) ; logger . info ( \"Shutdown complete\" ) ; } catch ( InterruptedException e ) { logger . debug ( \"Shutdown was interrupted. Some locks may not have been released but they will still expire.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Observes { @link ServletOutputStream } . [CODESPLIT] public static Observable < Void > create ( final ServletOutputStream out ) { return Observable . unsafeCreate ( subscriber -> { final ServletWriteListener listener = new ServletWriteListener ( subscriber , out ) ; out . setWriteListener ( listener ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the given Observable data to ServletOutputStream . [CODESPLIT] public static Observable < Void > write ( final Observable < byte [ ] > data , final ServletOutputStream out ) { return Observable . create ( new Observable . OnSubscribe < Void > ( ) { @ Override public void call ( Subscriber < ? super Void > subscriber ) { Observable < Void > events = create ( out ) . onBackpressureBuffer ( ) ; Observable < Void > writeobs = Observable . zip ( data , events , ( b , aVoid ) -> { try { out . write ( b ) ; } catch ( IOException ioe ) { Exceptions . propagate ( ioe ) ; } return null ; } ) ; writeobs . subscribe ( subscriber ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "functionality into a separate class . [CODESPLIT] @ Override public Observable < Void > addTags ( Metric < ? > metric , Map < String , String > tags ) { try { checkArgument ( tags != null , \"Missing tags\" ) ; checkArgument ( isValidTagMap ( tags ) , \"Invalid tags; tag key is required\" ) ; } catch ( Exception e ) { return Observable . error ( e ) ; } return dataAccess . insertIntoMetricsTagsIndex ( metric , tags ) . concatWith ( dataAccess . addTags ( metric , tags ) ) . toList ( ) . map ( l -> null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Intended to be used at the startup of the MetricsServiceImpl to ensure we have enough tables for processing [CODESPLIT] public void verifyAndCreateTempTables ( ) { ZonedDateTime currentBlock = ZonedDateTime . ofInstant ( Instant . ofEpochMilli ( DateTimeService . now . get ( ) . getMillis ( ) ) , UTC ) . with ( DateTimeService . startOfPreviousEvenHour ( ) ) ; ZonedDateTime lastStartupBlock = currentBlock . plus ( 6 , ChronoUnit . HOURS ) ; verifyAndCreateTempTables ( currentBlock , lastStartupBlock ) . await ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the namespace id for a particular namespace name [CODESPLIT] public String getNamespaceId ( String namespaceName ) { return namespaces . computeIfAbsent ( namespaceName , n -> getProjectId ( namespaceName , token ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns if the request is a query request eg to perform a READ [CODESPLIT] private boolean isQuery ( HttpServerExchange serverExchange ) { if ( serverExchange . getRequestMethod ( ) . toString ( ) . equalsIgnoreCase ( \"GET\" ) || serverExchange . getRequestMethod ( ) . toString ( ) . equalsIgnoreCase ( \"HEAD\" ) ) { // all GET requests are considered queries return true ; } else if ( serverExchange . getRequestMethod ( ) . toString ( ) . equalsIgnoreCase ( \"POST\" ) ) { // some POST requests may be queries we need to check. if ( postQuery != null && postQuery . matcher ( serverExchange . getRelativePath ( ) ) . find ( ) ) { return true ; } else { return false ; } } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executed when a pooled connection is acquired . [CODESPLIT] private void sendAuthenticationRequest ( HttpServerExchange serverExchange , PooledConnection connection ) { AuthContext context = serverExchange . getAttachment ( AUTH_CONTEXT_KEY ) ; String verb = getVerb ( serverExchange ) ; String resource ; // if we are not dealing with a query if ( ! isQuery ( serverExchange ) ) { // is USER_WRITE_ACCESS is disabled, then use the legacy check. // Otherwise check using the actual resource (eg 'hawkular-metrics', 'hawkular-alerts', etc) if ( USER_WRITE_ACCESS . equalsIgnoreCase ( \"true\" ) ) { resource = RESOURCE ; } else { resource = resourceName ; } } else { resource = RESOURCE ; } context . subjectAccessReview = generateSubjectAccessReview ( context . tenant , verb , resource ) ; ClientRequest request = buildClientRequest ( context ) ; context . clientRequestStarting ( ) ; connection . sendRequest ( request , new RequestReadyCallback ( serverExchange , connection ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the verb we should apply based on the HTTP method being requested . [CODESPLIT] private String getVerb ( HttpServerExchange serverExchange ) { // if its a query type verb, then treat as a GET type call. if ( isQuery ( serverExchange ) ) { return VERBS . get ( GET ) ; } else { String verb = VERBS . get ( serverExchange . getRequestMethod ( ) ) ; if ( verb == null ) { log . debugf ( \"Unhandled http method '%s'. Checking for read access.\" , serverExchange . getRequestMethod ( ) ) ; verb = VERBS_DEFAULT ; } return verb ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a SubjectAccessReview object used to request if a user has a certain permission or not . [CODESPLIT] private String generateSubjectAccessReview ( String namespace , String verb , String resource ) { ObjectNode objectNode = objectMapper . createObjectNode ( ) ; objectNode . put ( \"apiVersion\" , \"v1\" ) ; objectNode . put ( \"kind\" , KIND ) ; objectNode . put ( \"resource\" , resource ) ; objectNode . put ( \"verb\" , verb ) ; objectNode . put ( \"namespace\" , namespace ) ; return objectNode . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when the Kubernetes master server reponse has been inspected . [CODESPLIT] private void onRequestResult ( HttpServerExchange serverExchange , PooledConnection connection , boolean allowed ) { connectionPools . get ( serverExchange . getIoThread ( ) ) . release ( connection ) ; // Remove attachment early to make it eligible for GC AuthContext context = serverExchange . removeAttachment ( AUTH_CONTEXT_KEY ) ; apiLatency . update ( context . getClientResponseTime ( ) , NANOSECONDS ) ; authLatency . update ( context . getLatency ( ) , NANOSECONDS ) ; if ( allowed ) { serverExchange . dispatch ( containerHandler ) ; } else { endExchange ( serverExchange , FORBIDDEN ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called if an exception occurs at any stage in the process . [CODESPLIT] private void onRequestFailure ( HttpServerExchange serverExchange , PooledConnection connection , IOException e , boolean retry ) { log . debug ( \"Client request failure\" , e ) ; IoUtils . safeClose ( connection ) ; ConnectionPool connectionPool = connectionPools . get ( serverExchange . getIoThread ( ) ) ; connectionPool . release ( connection ) ; AuthContext context = serverExchange . getAttachment ( AUTH_CONTEXT_KEY ) ; if ( context . retries < MAX_RETRY && retry ) { context . retries ++ ; PooledConnectionWaiter waiter = createWaiter ( serverExchange ) ; if ( ! connectionPool . offer ( waiter ) ) { endExchange ( serverExchange , INTERNAL_SERVER_ERROR , TOO_MANY_PENDING_REQUESTS ) ; } } else { endExchange ( serverExchange , INTERNAL_SERVER_ERROR , CLIENT_REQUEST_FAILURE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eventually I would like service initialization async . [CODESPLIT] public void init ( RxSession session ) { this . session = session ; findConfigurationGroup = session . getSession ( ) . prepare ( \"SELECT name, value FROM sys_config WHERE config_id = ?\" ) . setConsistencyLevel ( ConsistencyLevel . LOCAL_QUORUM ) ; findConfigurationValue = session . getSession ( ) . prepare ( \"SELECT value FROM sys_config WHERE config_id = ? AND name= ?\" ) . setConsistencyLevel ( ConsistencyLevel . LOCAL_QUORUM ) ; updateConfigurationValue = session . getSession ( ) . prepare ( \"INSERT INTO sys_config (config_id, name, value) VALUES (?, ?, ?)\" ) . setConsistencyLevel ( ConsistencyLevel . LOCAL_QUORUM ) ; deleteConfigurationValue = session . getSession ( ) . prepare ( \"DELETE FROM sys_config WHERE config_id =? and name = ?\" ) . setConsistencyLevel ( ConsistencyLevel . LOCAL_QUORUM ) ; deleteConfiguration = session . getSession ( ) . prepare ( \"DELETE FROM sys_config WHERE config_id = ?\" ) . setConsistencyLevel ( ConsistencyLevel . LOCAL_QUORUM ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a job is single execution then this is a no - op ; otherwise the scheduled jobs index and jobs tables are updated with the next execution time / details . If the job has missed its next execution it will get scheduled in the next available time slice . The job scheduler will actually execute the job immediately when the job falls behind but we still want to persist the scheduling update for durability . [CODESPLIT] private Single < JobExecutionState > reschedule ( JobExecutionState executionState ) { Trigger nextTrigger = executionState . currentDetails . getTrigger ( ) . nextTrigger ( ) ; if ( nextTrigger == null ) { logger . debugf ( \"No more scheduled executions for %s\" , executionState . currentDetails ) ; return Single . just ( executionState ) ; } JobDetailsImpl details = executionState . currentDetails ; JobDetailsImpl newDetails = new JobDetailsImpl ( details , nextTrigger ) ; if ( nextTrigger . getTriggerTime ( ) <= now . get ( ) . getMillis ( ) ) { logger . infof ( \"%s missed its next execution at %d. It will be rescheduled for immediate execution.\" , details , nextTrigger . getTriggerTime ( ) ) ; AtomicLong nextTimeSlice = new AtomicLong ( currentMinute ( ) . getMillis ( ) ) ; Observable < Lock > scheduled = Observable . defer ( ( ) -> lockManager . acquireLock ( QUEUE_LOCK_PREFIX + nextTimeSlice . addAndGet ( 60000L ) , SCHEDULING_LOCK , SCHEDULING_LOCK_TIMEOUT_IN_SEC , false ) ) . map ( lock -> { if ( ! lock . isLocked ( ) ) { throw new RuntimeException ( ) ; } return lock ; } ) . retry ( ) ; return scheduled . map ( lock -> new JobExecutionState ( executionState . currentDetails , executionState . timeSlice , newDetails , new Date ( nextTimeSlice . get ( ) ) , executionState . activeJobs ) ) . flatMap ( state -> jobsService . insert ( state . nextTimeSlice , state . nextDetails ) . map ( updated -> state ) ) . doOnNext ( state -> logger . debugf ( \"Rescheduled %s to execute in time slice %s with trigger time \" + \"of %s\" , state . nextDetails . getJobName ( ) , state . nextTimeSlice , new Date ( state . nextDetails . getTrigger ( ) . getTriggerTime ( ) ) ) ) . toSingle ( ) ; } logger . debugf ( \"Scheduling %s for next execution at %s\" , newDetails , new Date ( nextTrigger . getTriggerTime ( ) ) ) ; JobExecutionState newState = new JobExecutionState ( details , executionState . timeSlice , newDetails , new Date ( nextTrigger . getTriggerTime ( ) ) , executionState . activeJobs ) ; return jobsService . insert ( newState . nextTimeSlice , newState . nextDetails ) . map ( updated -> newState ) . toSingle ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is currently unused . [CODESPLIT] public Observable < JobDetails > findScheduledJobs ( Date timeSlice , rx . Scheduler scheduler ) { return session . executeAndFetch ( findAllScheduled . bind ( ) , scheduler ) . filter ( filterNullJobs ) . filter ( row -> row . getTimestamp ( 0 ) . compareTo ( timeSlice ) <= 0 ) . map ( row -> createJobDetails ( row . getUUID ( 1 ) , row . getString ( 2 ) , row . getString ( 3 ) , row . getMap ( 4 , String . class , String . class ) , getTrigger ( row . getUDTValue ( 5 ) ) , JobStatus . fromCode ( row . getByte ( 6 ) ) , timeSlice ) ) . collect ( HashMap :: new , ( Map < UUID , SortedSet < JobDetails > > map , JobDetails details ) -> { SortedSet < JobDetails > set = map . get ( details . getJobId ( ) ) ; if ( set == null ) { set = new TreeSet <> ( ( JobDetails d1 , JobDetails d2 ) -> Long . compare ( d1 . getTrigger ( ) . getTriggerTime ( ) , d2 . getTrigger ( ) . getTriggerTime ( ) ) ) ; } set . add ( details ) ; map . put ( details . getJobId ( ) , set ) ; } ) . flatMap ( map -> Observable . from ( map . entrySet ( ) ) ) . map ( entry -> entry . getValue ( ) . first ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts bucket points indexed by start time into a list ordered by start time . Blanks will be filled with empty bucket points . [CODESPLIT] public static < T extends BucketPoint > List < T > toList ( Map < Long , T > pointMap , Buckets buckets , BiFunction < Long , Long , T > emptyBucketFactory ) { List < T > result = new ArrayList <> ( buckets . getCount ( ) ) ; for ( int index = 0 ; index < buckets . getCount ( ) ; index ++ ) { long from = buckets . getBucketStart ( index ) ; T bucketPoint = pointMap . get ( from ) ; if ( bucketPoint == null ) { long to = from + buckets . getStep ( ) ; bucketPoint = emptyBucketFactory . apply ( from , to ) ; } result . add ( bucketPoint ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JMX management [CODESPLIT] private void submitCompressJob ( Map < String , String > parameters ) { String jobName = String . format ( \"%s_single_%s\" , CompressData . JOB_NAME , parameters . get ( CompressData . TARGET_TIME ) ) ; // Blocking to ensure it is actually scheduled.. scheduler . scheduleJob ( CompressData . JOB_NAME , jobName , parameters , new SingleExecutionTrigger . Builder ( ) . withDelay ( 1 , TimeUnit . MINUTES ) . build ( ) ) . toBlocking ( ) . value ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allow special cases to Pattern matching such as * - > . * and ! indicating the match shouldn t happen . The first ! indicates the rest of the pattern should not match . [CODESPLIT] public static Pattern filterPattern ( String inputRegexp ) { if ( inputRegexp . equals ( \"*\" ) ) { inputRegexp = \".*\" ; } else if ( inputRegexp . startsWith ( \"!\" ) ) { inputRegexp = inputRegexp . substring ( 1 ) ; } return Pattern . compile ( inputRegexp ) ; // Catch incorrect patterns.. }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously performs gc_grace_seconds updates if necessary . This method should <strong > not< / strong > be called until schema updates have finished . [CODESPLIT] public void maybeUpdateGCGraceSeconds ( ) { logger . info ( \"Checking tables in \" + keyspace + \" to see if gc_grace_seconds needs to be updated\" ) ; Stopwatch stopwatch = Stopwatch . createStarted ( ) ; Map < String , String > replication = session . getCluster ( ) . getMetadata ( ) . getKeyspace ( keyspace ) . getReplication ( ) ; String replicationFactor = replication . get ( \"replication_factor\" ) ; Completable check ; if ( getClusterSize ( ) == 1 || replicationFactor . equals ( \"1\" ) ) { check = updateAllGCGraceSeconds ( 0 ) ; } else { // Need to call Completable.merge in order for subscriptions to happen correctly. See https://goo.gl/l15CRV check = Completable . merge ( configurationService . load ( \"org.hawkular.metrics\" , \"gcGraceSeconds\" ) . switchIfEmpty ( Observable . just ( Integer . toString ( DEFAULT_GC_GRACE_SECONDS ) ) ) . map ( property -> { int gcGraceSeconds = Integer . parseInt ( property ) ; return updateAllGCGraceSeconds ( gcGraceSeconds ) ; } ) ) ; } check . subscribe ( ( ) -> { stopwatch . stop ( ) ; logger . info ( \"Finished gc_grace_seconds updates in \" + stopwatch . elapsed ( TimeUnit . MILLISECONDS ) + \" ms\" ) ; updatesFinished . ifPresent ( subject -> subject . onNext ( null ) ) ; } , t -> { logger . warn ( \"There was an error checking and updating gc_grace_seconds\" ) ; updatesFinished . ifPresent ( subject -> subject . onNext ( t ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the status code of the response sets the HTTP reason phrase and ends the exchange . [CODESPLIT] public static void endExchange ( HttpServerExchange exchange , int statusCode , String reasonPhrase ) { exchange . setStatusCode ( statusCode ) ; if ( reasonPhrase != null ) { exchange . setReasonPhrase ( reasonPhrase ) ; } exchange . endExchange ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the string into an interval . The string must match the regular expression ( \\ d + ) ( min|hr|d ) ; otherwise an exception is thrown . [CODESPLIT] public static Interval parse ( String s ) { if ( s . isEmpty ( ) ) { return NONE ; } Matcher matcher = INTERVAL_PATTERN . matcher ( s ) ; if ( ! ( matcher . matches ( ) && matcher . groupCount ( ) == 2 ) ) { throw new IllegalArgumentException ( s + \" is not a valid interval. It must follow the pattern \" + INTERVAL_PATTERN . pattern ( ) ) ; } return new Interval ( Integer . parseInt ( matcher . group ( 1 ) ) , Units . fromCode ( matcher . group ( 2 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch all the data from a temporary table for the compression job . Using TokenRanges avoids fetching first all the metrics partition keys and then requesting them . [CODESPLIT] @ Override public Observable < Observable < Row > > findAllDataFromBucket ( long timestamp , int pageSize , int maxConcurrency ) { PreparedStatement ts = getTempStatement ( MetricType . UNDEFINED , TempStatement . SCAN_WITH_TOKEN_RANGES , timestamp ) ; // The table does not exists - case such as when starting Hawkular-Metrics for the first time just before // compression kicks in. if ( ts == null || prepMap . floorKey ( timestamp ) == 0L ) { return Observable . empty ( ) ; } return Observable . from ( getTokenRanges ( ) ) . map ( tr -> rxSession . executeAndFetch ( ts . bind ( ) . setToken ( 0 , tr . getStart ( ) ) . setToken ( 1 , tr . getEnd ( ) ) . setFetchSize ( pageSize ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Applies micro - batching capabilities by taking advantage of token ranges in the Cassandra [CODESPLIT] private Observable . Transformer < BoundStatement , Integer > applyMicroBatching ( ) { return tObservable -> tObservable . groupBy ( b -> { ByteBuffer routingKey = b . getRoutingKey ( ProtocolVersion . NEWEST_SUPPORTED , codecRegistry ) ; Token token = metadata . newToken ( routingKey ) ; for ( TokenRange tokenRange : session . getCluster ( ) . getMetadata ( ) . getTokenRanges ( ) ) { if ( tokenRange . contains ( token ) ) { return tokenRange ; } } log . warn ( \"Unable to find any Cassandra node to insert token \" + token . toString ( ) ) ; return session . getCluster ( ) . getMetadata ( ) . getTokenRanges ( ) . iterator ( ) . next ( ) ; } ) . flatMap ( g -> g . compose ( new BoundBatchStatementTransformer ( ) ) ) . flatMap ( batch -> rxSession . execute ( batch ) . compose ( applyInsertRetryPolicy ( ) ) . map ( resultSet -> batch . size ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Apply our current retry policy to the insert behavior [CODESPLIT] private < T > Observable . Transformer < T , T > applyInsertRetryPolicy ( ) { return tObservable -> tObservable . retryWhen ( errors -> { Observable < Integer > range = Observable . range ( 1 , 2 ) ; return errors . zipWith ( range , ( t , i ) -> { if ( t instanceof DriverException ) { return i ; } throw Exceptions . propagate ( t ) ; } ) . flatMap ( retryCount -> { long delay = ( long ) Math . min ( Math . pow ( 2 , retryCount ) * 1000 , 3000 ) ; log . debug ( \"Retrying batch insert in \" + delay + \" ms\" ) ; return Observable . timer ( delay , TimeUnit . MILLISECONDS ) ; } ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force bucket count . This method does not guarantee that the last bucket includes the { @code end } value . [CODESPLIT] public static Buckets fromCount ( long start , long end , int count ) { checkTimeRange ( start , end ) ; checkArgument ( count > 0 , \"count is not positive: %s\" , count ) ; long quotient = ( end - start ) / count ; long remainder = ( end - start ) % count ; long step ; // count * quotient + remainder = end - start // If the remainder is greater than zero, we should try with (quotient + 1), provided that this greater step // does not make the number of buckets smaller than the expected count if ( remainder != 0 && ( count - 1 ) * ( quotient + 1 ) < ( end - start ) ) { step = quotient + 1 ; } else { step = quotient ; } checkArgument ( step > 0 , \"Computed step is equal to zero\" ) ; return new Buckets ( start , step , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force bucket step . [CODESPLIT] public static Buckets fromStep ( long start , long end , long step ) { checkTimeRange ( start , end ) ; checkArgument ( step > 0 , \"step is not positive: %s\" , step ) ; if ( step > ( end - start ) ) { return new Buckets ( start , step , 1 ) ; } long quotient = ( end - start ) / step ; long remainder = ( end - start ) % step ; long count ; if ( remainder == 0 ) { count = quotient ; } else { count = quotient + 1 ; } checkArgument ( count <= Integer . MAX_VALUE , \"Computed number of buckets is too big: %s\" , count ) ; return new Buckets ( start , step , ( int ) count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "send msg . [CODESPLIT] public boolean sendMsg ( Message msg ) { SendResult sendResult = null ; try { sendResult = producer . send ( msg ) ; } catch ( Exception e ) { logger . error ( \"send msg error\" , e ) ; } return sendResult != null && sendResult . getSendStatus ( ) == SendStatus . SEND_OK ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sene one way msg . [CODESPLIT] public void sendOneWayMsg ( Message msg ) { try { producer . sendOneway ( msg ) ; } catch ( Exception e ) { logger . error ( \"send msg error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "send delay msg . [CODESPLIT] public boolean sendDelayMsg ( String topic , String tag , Message msg , int delayLevel ) { msg . setDelayTimeLevel ( delayLevel ) ; SendResult sendResult = null ; try { sendResult = producer . send ( msg ) ; } catch ( Exception e ) { logger . error ( \"send msg error\" , e ) ; } return sendResult != null && sendResult . getSendStatus ( ) == SendStatus . SEND_OK ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In this simple proposal we re not testing complex iterations of scan cursor . SCAN is simply a wrapper for KEYS and the result is given in one single response no matter the COUNT argument . [CODESPLIT] @ Override public ScanResult < String > scan ( String cursor , ScanParams params ) { // We need to extract the MATCH argument from the scan params Collection < byte [ ] > rawParams = params . getParams ( ) ; // Raw collection is a list of byte[], made of: key1, value1, key2, value2, etc. boolean isKey = true ; String match = null ; boolean foundMatchKey = false ; // So, we run over the list, where any even index is a key, and the following data is its value. for ( byte [ ] raw : rawParams ) { if ( isKey ) { String key = new String ( raw ) ; if ( key . equals ( new String ( MATCH . raw ) ) ) { // What really interests us is the MATCH key. foundMatchKey = true ; } } // As soon as we've found the MATCH key, we can stop searching. else if ( foundMatchKey ) { match = new String ( raw ) ; break ; } isKey = ! isKey ; } // Our simple implementation of SCAN is really a plain wrapper for KEYS, // relying on the current mock implementation of the pattern search. return new ScanResult < String > ( \"0\" , new ArrayList < String > ( keys ( match ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a wildcard matching for the text and pattern provided . Source : http : // www . adarshr . com / papers / wildcard [CODESPLIT] public boolean match ( String text , final String pattern ) { // Create the cards by splitting using a RegEx. If more speed // is desired, a simpler character based splitting can be done. final String [ ] cards = REGEX_STAR . split ( pattern ) ; final int numCards = cards . length ; // Iterate over the cards. for ( int i = 0 ; i < numCards ; ++ i ) { final String card = cards [ i ] ; final int idx = text . indexOf ( card ) ; // Card not detected in the text. if ( idx == - 1 ) { return false ; } if ( idx != 0 && i == 0 ) { return false ; // test needs to start from 'card' } // Move ahead, towards the right of the text. text = text . substring ( idx + card . length ( ) ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // confluence . atlassian . com / bamboo / bamboo - variables - 289277087 . html [CODESPLIT] private static CIEnvironment detectBamboo ( Map < String , String > env ) { String revision = env . get ( \"bamboo_planRepository_revision\" ) ; String branch = env . get ( \"bamboo_repository_git_branch\" ) ; if ( revision == null || branch == null ) return null ; String tag = null ; String projectName = env . get ( \"bamboo_planRepository_name\" ) ; return new CIEnvironment ( \"Bamboo\" , revision , branch , tag , projectName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "https : // docs . travis - ci . com / user / environment - variables / #Default - Environment - Variables [CODESPLIT] private static CIEnvironment detectTravis ( Map < String , String > env ) { String revision = env . get ( \"TRAVIS_COMMIT\" ) ; String branch = env . get ( \"TRAVIS_BRANCH\" ) ; if ( revision == null || branch == null ) return null ; String tag = null ; String repoSlug = env . get ( \"TRAVIS_REPO_SLUG\" ) ; String projectName = repoSlug . split ( \"/\" ) [ 1 ] ; return new CIEnvironment ( \"Travis CI\" , revision , branch , tag , projectName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use by loaders [CODESPLIT] public void setValue ( String property , Value value ) { this . valueByProperty . put ( property . toLowerCase ( ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a file to the ZIP . [CODESPLIT] public String add ( File file , boolean preserveExternalFileName ) { File existingFile = checkFileExists ( file ) ; String result = zipPathFor ( existingFile , preserveExternalFileName ) ; entries . put ( existingFile , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the contents of a file with a different text . [CODESPLIT] public void replace ( File file , boolean preserveExternalFileName , String text ) { String path = entries . containsKey ( file ) ? entries . remove ( file ) : zipPathFor ( file , preserveExternalFileName ) ; entries . put ( text , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a ZIP file containing the added entries . [CODESPLIT] public File build ( ) throws IOException { if ( entries . isEmpty ( ) ) { throw new EmptyZipException ( ) ; } String fileName = \"import_configuration\" + System . currentTimeMillis ( ) + \".zip\" ; File result = new File ( TEMP_DIR . toFile ( ) , fileName ) ; try ( ZipOutputStream zip = new ZipOutputStream ( Files . newOutputStream ( result . toPath ( ) , StandardOpenOption . CREATE_NEW ) ) ) { customization . init ( entries . values ( ) , this :: streamFor ) ; for ( Entry < Object , String > entry : entries . entrySet ( ) ) { try ( InputStream input = toInputStream ( entry . getKey ( ) ) ) { addEntry ( ExtraZipEntry . of ( entry . getValue ( ) , customization . customize ( entry . getValue ( ) , input ) ) , zip ) ; } } customization . extraEntries ( ) . forEach ( entry -> addEntry ( entry , zip ) ) ; zip . closeEntry ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a product by assembling components . [CODESPLIT] public Metrics generate ( Iterable < C > components , DataBuffer product ) throws IOException { return generate ( components . iterator ( ) , product ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a product by assembling components . [CODESPLIT] public Metrics generate ( Iterator < C > components , DataBuffer product ) throws IOException { assembler . start ( product ) ; try { while ( components . hasNext ( ) ) { assembler . add ( components . next ( ) ) ; } } finally { assembler . end ( ) ; } return assembler . getMetrics ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a product by assembling components . [CODESPLIT] public Metrics generate ( Enumeration < C > components , DataBuffer product ) throws IOException { return generate ( new EnumerationIterator < C > ( components ) , product ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a product from a single piece . [CODESPLIT] public Metrics generate ( C component , DataBuffer product ) throws IOException { return generate ( Collections . singletonList ( component ) , product ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the content for the specified content id . [CODESPLIT] @ Override @ Deprecated public ContentResult fetchContent ( String contentId ) throws IOException { try { String contentResource = resourceCache . getCiResourceUri ( ) ; URIBuilder builder = new URIBuilder ( contentResource ) ; builder . setParameter ( \"cid\" , contentId ) ; URI uri = builder . build ( ) ; return restClient . get ( uri . toString ( ) , contentResultFactory ) ; } catch ( URISyntaxException e ) { throw new IllegalStateException ( \"Failed to create content resource uri.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the content for the specified order item . [CODESPLIT] @ Override @ Deprecated public ContentResult fetchOrderContent ( OrderItem orderItem ) throws IOException { String downloadUri = Objects . requireNonNull ( Objects . requireNonNull ( orderItem , \"Missing order item\" ) . getUri ( LINK_DOWNLOAD ) , \"Missing download URI\" ) ; String fetchUri = restClient . uri ( downloadUri ) . addParameter ( \"downloadToken\" , \"\" ) . build ( ) ; return restClient . get ( fetchUri , contentResultFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upload the transformation zip with the stylesheet into Archive . [CODESPLIT] @ Override @ Deprecated public LinkContainer uploadTransformation ( ExportTransformation exportTransformation , InputStream zip ) throws IOException { String uri = exportTransformation . getUri ( LINK_EXPORT_TRANSFORMATION_ZIP ) ; return restClient . post ( uri , LinkContainer . class , new BinaryPart ( \"file\" , zip , \"stylesheet.zip\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a file by assembling components . [CODESPLIT] public FileGenerationMetrics generate ( Iterator < C > components ) throws IOException { File result = fileSupplier . get ( ) ; return new FileGenerationMetrics ( result , generate ( components , new FileBuffer ( result ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new directory in the given parent directory . [CODESPLIT] public static File in ( File parentDir ) { File result = new File ( parentDir , UUID . randomUUID ( ) . toString ( ) ) ; if ( ! result . mkdirs ( ) ) { throw new RuntimeIoException ( new IOException ( \"Could not create directory: \" + result ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "End this builder . [CODESPLIT] public P end ( ) { parent . addChildObject ( English . plural ( object . getType ( ) ) , object ) ; return parent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares a group by adding renderers adaptors and sub templates . Override this if you want to add additional renderers . By default adds : <ul > <li > an { [CODESPLIT] protected void prepareGroup ( STGroup group ) { registerAdaptor ( group , Map . class , new MapModelAdaptor ( ) ) ; registerRenderer ( group , Date . class , new XmlDateRenderer ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a ModelAdaptor with the group . Override this method if you want to suppress one OOTB adaptor but not all . [CODESPLIT] protected < S > void registerAdaptor ( STGroup group , Class < S > type , ModelAdaptor adaptor ) { group . registerModelAdaptor ( type , adaptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a renderer with the group . Override this method if you want to suppress one OOTB renderer but not all . [CODESPLIT] protected < S > void registerRenderer ( STGroup group , Class < S > type , AttributeRenderer attributeRenderer ) { group . registerRenderer ( type , attributeRenderer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares the template by adding the variables . [CODESPLIT] protected ST prepareTemplate ( ST prototype , D domainObject , Map < String , ContentInfo > contentInfo ) { ST template = new ST ( prototype ) ; template . add ( MODEL_VARIABLE , domainObject ) ; template . add ( CONTENT_VARIABLE , contentInfo ) ; return template ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a domain object to the batch of SIPs . [CODESPLIT] public synchronized void add ( D domainObject ) throws IOException { if ( shouldStartNewSip ( domainObject ) ) { startSip ( ) ; } assembler . add ( domainObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value of a property . [CODESPLIT] public void setProperty ( String name , Object value ) { properties . put ( name , toJsonValue ( value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an object that is to be owned by this object . [CODESPLIT] public void addChildObject ( String collection , ConfigurationObject childObject ) { childObjects . computeIfAbsent ( collection , ignored -> new ArrayList <> ( ) ) . add ( childObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a date to <a href = https : // tools . ietf . org / html / rfc3339#section - 5 . 6 > ISO 8601 dateTime< / a > format . [CODESPLIT] @ Nullable public static String toIso ( Date dateTime ) { if ( dateTime == null ) { return null ; } Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( dateTime ) ; return DatatypeConverter . printDateTime ( calendar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert an <a href = https : // tools . ietf . org / html / rfc3339#section - 5 . 6 > ISO 8601 dateTime< / a > string to a date . [CODESPLIT] @ Nullable public static Date fromIso ( String dateTime ) { if ( dateTime == null ) { return null ; } return DatatypeConverter . parseDateTime ( dateTime ) . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a supplier that creates sequentially named files in the given directory . [CODESPLIT] public static Supplier < File > fromDirectory ( File dir , String prefix , String suffix ) { return new Supplier < File > ( ) { private int count ; @ Override public File get ( ) { return new File ( ensureDir ( dir ) , String . format ( \"%s%d%s\" , prefix , ++ count , suffix ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdi ( PackagingInformation prototype , Assembler < HashedContents < D > > pdiAssembler ) { return forPdiWithHashing ( prototype , pdiAssembler , new NoHashAssembler ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdi ( PackagingInformationFactory factory , Assembler < HashedContents < D > > pdiAssembler ) { return forPdiWithHashing ( factory , pdiAssembler , new NoHashAssembler ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiWithHashing ( PackagingInformation prototype , Assembler < HashedContents < D > > pdiAssembler , HashAssembler pdiHashAssembler ) { return forPdiAndContentWithHashing ( prototype , pdiAssembler , pdiHashAssembler , ContentAssembler . ignoreContent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiWithHashing ( PackagingInformationFactory factory , Assembler < HashedContents < D > > pdiAssembler , HashAssembler pdiHashAssembler ) { return forPdiAndContentWithHashing ( factory , pdiAssembler , pdiHashAssembler , ContentAssembler . ignoreContent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContent ( PackagingInformation prototype , Assembler < HashedContents < D > > pdiAssembler , DigitalObjectsExtraction < D > contentsExtraction ) { HashAssembler noHashAssembler = new NoHashAssembler ( ) ; return forPdiAndContentWithHashing ( prototype , pdiAssembler , noHashAssembler , contentsExtraction , noHashAssembler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContent ( PackagingInformation prototype , Assembler < HashedContents < D > > pdiAssembler , ContentAssembler < D > contentAssembler ) { HashAssembler noHashAssembler = new NoHashAssembler ( ) ; return forPdiAndContentWithHashing ( prototype , pdiAssembler , noHashAssembler , contentAssembler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContent ( PackagingInformationFactory factory , Assembler < HashedContents < D > > pdiAssembler , ContentAssembler < D > contentAssembler ) { HashAssembler noHashAssembler = new NoHashAssembler ( ) ; return forPdiAndContentWithHashing ( factory , pdiAssembler , noHashAssembler , contentAssembler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContent ( PackagingInformationFactory factory , Assembler < HashedContents < D > > pdiAssembler , DigitalObjectsExtraction < D > contentsExtraction ) { HashAssembler noHashAssembler = new NoHashAssembler ( ) ; return forPdiAndContentWithHashing ( factory , pdiAssembler , noHashAssembler , ContentAssembler . noDedup ( contentsExtraction , noHashAssembler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContentWithContentHashing ( PackagingInformation prototype , Assembler < HashedContents < D > > pdiAssembler , DigitalObjectsExtraction < D > contentsExtraction , HashAssembler contentHashAssembler ) { return forPdiAndContentWithHashing ( prototype , pdiAssembler , new NoHashAssembler ( ) , contentsExtraction , contentHashAssembler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that contains only structured data and is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContentWithContentHashing ( PackagingInformationFactory factory , Assembler < HashedContents < D > > pdiAssembler , DigitalObjectsExtraction < D > contentsExtraction , HashAssembler contentHashAssembler ) { return forPdiAndContentWithHashing ( factory , pdiAssembler , new NoHashAssembler ( ) , new ContentAssemblerDefault < D > ( contentsExtraction , contentHashAssembler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContentWithHashing ( PackagingInformation prototype , Assembler < HashedContents < D > > pdiAssembler , HashAssembler pdiHashAssembler , DigitalObjectsExtraction < D > contentsExtraction , HashAssembler contentHashAssembler ) { return new SipAssembler <> ( new DefaultPackagingInformationFactory ( prototype ) , pdiAssembler , pdiHashAssembler , new DataBufferSupplier <> ( MemoryBuffer . class ) , new ContentAssemblerDefault < D > ( contentsExtraction , contentHashAssembler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContentWithHashing ( PackagingInformation prototype , Assembler < HashedContents < D > > pdiAssembler , HashAssembler pdiHashAssembler , ContentAssembler < D > contentAssembler ) { return new SipAssembler <> ( new DefaultPackagingInformationFactory ( prototype ) , pdiAssembler , pdiHashAssembler , new DataBufferSupplier <> ( MemoryBuffer . class ) , contentAssembler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble a SIP that is the only SIP in its DSS . [CODESPLIT] public static < D > SipAssembler < D > forPdiAndContentWithHashing ( PackagingInformationFactory factory , Assembler < HashedContents < D > > pdiAssembler , HashAssembler pdiHashAssembler , ContentAssembler < D > contentAssembler ) { return new SipAssembler <> ( factory , pdiAssembler , pdiHashAssembler , new DataBufferSupplier <> ( MemoryBuffer . class ) , contentAssembler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to copy the bytes from an InputStream to an OutputStream while also assembling a hash value in the process . [CODESPLIT] public static void copy ( InputStream in , OutputStream out , int bufferSize , HashAssembler hashAssembler ) throws IOException { byte [ ] buffer = new byte [ bufferSize ] ; int numRead = Objects . requireNonNull ( in , \"Missing input\" ) . read ( buffer ) ; if ( numRead == 0 ) { throw new IllegalArgumentException ( \"Missing content\" ) ; } Objects . requireNonNull ( out , \"Missing output\" ) ; while ( numRead > 0 ) { out . write ( buffer , 0 , numRead ) ; hashAssembler . add ( buffer , numRead ) ; numRead = in . read ( buffer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new factory for building XML documents that is configured to operate securely . The factory also supports <a href = http : // www . w3 . org / TR / REC - xml - names / > XML namespaces< / a > and validation . [CODESPLIT] public static DocumentBuilderFactory newSecureDocumentBuilderFactory ( ) { try { DocumentBuilderFactory result = DocumentBuilderFactory . newInstance ( ) ; result . setFeature ( \"http://javax.xml.XMLConstants/feature/secure-processing\" , true ) ; result . setFeature ( \"http://xml.org/sax/features/external-general-entities\" , false ) ; result . setFeature ( \"http://xml.org/sax/features/external-parameter-entities\" , false ) ; result . setNamespaceAware ( true ) ; result . setValidating ( true ) ; return result ; } catch ( ParserConfigurationException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the content of a given file into an XML document . [CODESPLIT] public static Document parse ( File file ) { if ( ! file . isFile ( ) ) { throw new IllegalArgumentException ( \"Missing file: \" + file . getAbsolutePath ( ) ) ; } try { try ( InputStream stream = Files . newInputStream ( file . toPath ( ) , StandardOpenOption . READ ) ) { return parse ( stream ) ; } } catch ( IOException e ) { throw new IllegalArgumentException ( \"Failed to parse \" + file . getAbsolutePath ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the content of a given reader into an XML document . [CODESPLIT] public static Document parse ( Reader reader ) { DocumentBuilder documentBuilder = getDocumentBuilder ( ) ; try { return documentBuilder . parse ( new InputSource ( reader ) ) ; } catch ( SAXException | IOException e ) { throw new IllegalArgumentException ( \"Failed to parse XML document\" , e ) ; } finally { documentBuilder . reset ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the elements under a given parent element . [CODESPLIT] public static Stream < Element > elementsIn ( Element parent ) { return nodesIn ( parent ) . filter ( n -> n . getNodeType ( ) == Node . ELEMENT_NODE ) . map ( n -> ( Element ) n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the nodes under a given parent element . [CODESPLIT] public static Stream < Node > nodesIn ( Element parent ) { return StreamSupport . stream ( new ChildNodesSpliterator ( parent ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the first child element of a given parent element whose tag matches any of the given names . When no child names are given the first child element is returned . [CODESPLIT] public static Element getFirstChildElement ( Element parent , String ... childNames ) { return firstOf ( namedElementsIn ( parent , childNames ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the elements under a given parent element whose tag matches any of the given names . When no child names are given all child elements are returned . [CODESPLIT] public static Stream < Element > namedElementsIn ( Element parent , String ... childNames ) { return elementsIn ( parent ) . filter ( e -> isName ( e , childNames ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate an XML document against an XML Schema document . [CODESPLIT] public static void validate ( InputStream xml , InputStream xmlSchema , String humanFriendlyDocumentType ) throws IOException { try { newXmlSchemaValidator ( xmlSchema ) . validate ( new StreamSource ( Objects . requireNonNull ( xml ) ) ) ; } catch ( SAXException e ) { throw new ValidationException ( \"Invalid \" + humanFriendlyDocumentType , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { [CODESPLIT] public static ArchiveClient configuringApplicationUsing ( ApplicationConfigurer configurer , ArchiveConnection connection ) throws IOException { configurer . configure ( connection ) ; return usingAlreadyConfiguredApplication ( configurer . getApplicationName ( ) , connection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { [CODESPLIT] public static ArchiveClient usingAlreadyConfiguredApplication ( String applicationName , ArchiveConnection connection ) throws IOException { RestClient restClient = connection . getRestClient ( ) ; return new InfoArchiveRestClient ( restClient , appResourceCache ( applicationName , connection , restClient ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given YAML . [CODESPLIT] public static YamlMap from ( String yaml ) { assertNotNull ( yaml ) ; try ( InputStream input = streamOf ( yaml ) ) { return from ( input ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( \"Failed to parse YAML string\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given YAML . [CODESPLIT] public static YamlMap from ( File yaml ) throws IOException { assertNotNull ( yaml ) ; if ( ! yaml . isFile ( ) ) { return new YamlMap ( ) ; } try ( InputStream input = Files . newInputStream ( yaml . toPath ( ) ) ) { return from ( input ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a SIP archive from all files in a given directory tree . [CODESPLIT] public static void main ( String [ ] args ) { try { Arguments arguments = new Arguments ( args ) ; File root = new File ( arguments . next ( \"content\" ) ) ; if ( ! root . isDirectory ( ) ) { root = new File ( \".\" ) ; } String rootPath = root . getCanonicalPath ( ) ; String sip = arguments . next ( \"build/files.zip\" ) ; new FileArchiver ( ) . run ( rootPath , sip ) ; } catch ( IOException e ) { e . printStackTrace ( System . out ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the content . [CODESPLIT] public ContentBuilder < P > as ( InputStream content ) { try { return as ( IOUtils . toString ( content , StandardCharsets . UTF_8 ) ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( \"Failed to read content\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the content from a named resource . [CODESPLIT] public ContentBuilder < P > fromResource ( String name ) { try ( InputStream content = ContentBuilder . class . getResourceAsStream ( name ) ) { return as ( content ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( \"Failed to read resource: \" + name , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process a named entry in the ZIP file . [CODESPLIT] public < T > T andProcessEntry ( String entry , Function < InputStream , T > processor ) { try ( ZipFile zipFile = new ZipFile ( zip ) ) { return processEntry ( zipFile , entry , processor ) ; } catch ( IOException e ) { throw new RuntimeIoException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Chinese characters transform [CODESPLIT] public static String asciiCharactersEncoding ( String str ) throws QSException { if ( QSStringUtil . isEmpty ( str ) ) { return \"\" ; } try { String encoded = URLEncoder . encode ( str , QSConstant . ENCODING_UTF8 ) ; encoded = encoded . replace ( \"%2F\" , \"/\" ) ; encoded = encoded . replace ( \"%3D\" , \"=\" ) ; encoded = encoded . replace ( \"+\" , \"%20\" ) ; encoded = encoded . replace ( \"%3A\" , \":\" ) ; return encoded ; } catch ( UnsupportedEncodingException e ) { throw new QSException ( \"UnsupportedEncodingException:\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate signature for request against QingStor . [CODESPLIT] public static String generateAuthorization ( String accessKey , String secretKey , String method , String requestURI , Map < String , String > params , Map < String , String > headers ) { String signature = generateSignature ( secretKey , method , requestURI , params , headers ) ; return String . format ( \"QS %s:%s\" , accessKey , signature ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate signature for request against QingStor . [CODESPLIT] public static String generateAuthorization ( String accessKey , String secretKey , String strToSign ) { String signature = generateSignature ( secretKey , strToSign ) ; return String . format ( \"QS %s:%s\" , accessKey , signature ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate signature for request against QingStor . [CODESPLIT] public static String generateSignature ( String secretKey , String method , String requestURI , Map < String , String > params , Map < String , String > headers ) { String signature = \"\" ; String strToSign = getStringToSignature ( method , requestURI , params , headers ) ; logger . log ( Level . INFO , \"== String to sign ==\\n\" + strToSign + \"\\n\" ) ; signature = generateSignature ( secretKey , strToSign ) ; return signature ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate signature for request against QingStor . [CODESPLIT] public static String generateAuthorization ( String accessKey , String secretKey , String strToSign ) { return QSSignatureUtil . generateAuthorization ( accessKey , secretKey , strToSign ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate signature for request against QingStor . [CODESPLIT] public static String generateSignature ( String secretKey , String strToSign ) { return QSSignatureUtil . generateSignature ( secretKey , strToSign ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > OkHttp will use Accept - Encoding : gzip as default header which may not get Content - Length form server when download . < / p > [CODESPLIT] private void checkDownloadRequest ( ) { if ( outputClass == null ) return ; boolean isDownloadRequest = false ; Field [ ] declaredField = outputClass . getDeclaredFields ( ) ; for ( Field field : declaredField ) { String methodName = \"get\" + QSParamInvokeUtil . capitalize ( field . getName ( ) ) ; Method [ ] methods = outputClass . getDeclaredMethods ( ) ; for ( Method m : methods ) { if ( m . getName ( ) . equalsIgnoreCase ( methodName ) ) { ParamAnnotation annotation = m . getAnnotation ( ParamAnnotation . class ) ; if ( annotation == null ) continue ; if ( \"BodyInputStream\" . equals ( annotation . paramName ( ) ) ) { isDownloadRequest = true ; break ; } } } } if ( isDownloadRequest ) { getBuilder ( ) . setHeader ( \"Accept-Encoding\" , \"identity\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set signature and server time . [CODESPLIT] public void setSignature ( String accessKey , String signature , String gmtTime ) throws QSException { builder . setHeader ( QSConstant . HEADER_PARAM_KEY_DATE , gmtTime ) ; setSignature ( accessKey , signature ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes hex octects into Base64 [CODESPLIT] public static String encode ( byte [ ] binaryData ) { if ( binaryData == null ) { return null ; } int lengthDataBits = binaryData . length * EIGHTBIT ; if ( lengthDataBits == 0 ) { return \"\" ; } int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP ; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP ; int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets ; char encodedData [ ] = null ; encodedData = new char [ numberQuartet * 4 ] ; byte k = 0 , l = 0 , b1 = 0 , b2 = 0 , b3 = 0 ; int encodedIndex = 0 ; int dataIndex = 0 ; for ( int i = 0 ; i < numberTriplets ; i ++ ) { b1 = binaryData [ dataIndex ++ ] ; b2 = binaryData [ dataIndex ++ ] ; b3 = binaryData [ dataIndex ++ ] ; l = ( byte ) ( b2 & 0x0f ) ; k = ( byte ) ( b1 & 0x03 ) ; byte val1 = ( ( b1 & SIGN ) == 0 ) ? ( byte ) ( b1 >> 2 ) : ( byte ) ( ( b1 ) >> 2 ^ 0xc0 ) ; byte val2 = ( ( b2 & SIGN ) == 0 ) ? ( byte ) ( b2 >> 4 ) : ( byte ) ( ( b2 ) >> 4 ^ 0xf0 ) ; byte val3 = ( ( b3 & SIGN ) == 0 ) ? ( byte ) ( b3 >> 6 ) : ( byte ) ( ( b3 ) >> 6 ^ 0xfc ) ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ val1 ] ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ val2 | ( k << 4 ) ] ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ ( l << 2 ) | val3 ] ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ b3 & 0x3f ] ; } // form integral number of 6-bit groups if ( fewerThan24bits == EIGHTBIT ) { b1 = binaryData [ dataIndex ] ; k = ( byte ) ( b1 & 0x03 ) ; byte val1 = ( ( b1 & SIGN ) == 0 ) ? ( byte ) ( b1 >> 2 ) : ( byte ) ( ( b1 ) >> 2 ^ 0xc0 ) ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ val1 ] ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ k << 4 ] ; encodedData [ encodedIndex ++ ] = PAD ; encodedData [ encodedIndex ++ ] = PAD ; } else if ( fewerThan24bits == SIXTEENBIT ) { b1 = binaryData [ dataIndex ] ; b2 = binaryData [ dataIndex + 1 ] ; l = ( byte ) ( b2 & 0x0f ) ; k = ( byte ) ( b1 & 0x03 ) ; byte val1 = ( ( b1 & SIGN ) == 0 ) ? ( byte ) ( b1 >> 2 ) : ( byte ) ( ( b1 ) >> 2 ^ 0xc0 ) ; byte val2 = ( ( b2 & SIGN ) == 0 ) ? ( byte ) ( b2 >> 4 ) : ( byte ) ( ( b2 ) >> 4 ^ 0xf0 ) ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ val1 ] ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ val2 | ( k << 4 ) ] ; encodedData [ encodedIndex ++ ] = lookUpBase64Alphabet [ l << 2 ] ; encodedData [ encodedIndex ++ ] = PAD ; } return new String ( encodedData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes Base64 data into octects [CODESPLIT] public static byte [ ] decode ( String encoded ) { if ( encoded == null ) { return null ; } char [ ] base64Data = encoded . toCharArray ( ) ; // remove white spaces int len = removeWhiteSpace ( base64Data ) ; if ( len % FOURBYTE != 0 ) { return null ; // should be divisible by four } int numberQuadruple = ( len / FOURBYTE ) ; if ( numberQuadruple == 0 ) { return new byte [ 0 ] ; } byte decodedData [ ] = null ; byte b1 = 0 , b2 = 0 , b3 = 0 , b4 = 0 ; char d1 = 0 , d2 = 0 , d3 = 0 , d4 = 0 ; int i = 0 ; int encodedIndex = 0 ; int dataIndex = 0 ; decodedData = new byte [ ( numberQuadruple ) * 3 ] ; for ( ; i < numberQuadruple - 1 ; i ++ ) { if ( ! isData ( ( d1 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d2 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d3 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d4 = base64Data [ dataIndex ++ ] ) ) ) { return null ; } // if found \"no data\" just return null b1 = base64Alphabet [ d1 ] ; b2 = base64Alphabet [ d2 ] ; b3 = base64Alphabet [ d3 ] ; b4 = base64Alphabet [ d4 ] ; decodedData [ encodedIndex ++ ] = ( byte ) ( b1 << 2 | b2 >> 4 ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 >> 2 ) & 0xf ) ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( b3 << 6 | b4 ) ; } if ( ! isData ( ( d1 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d2 = base64Data [ dataIndex ++ ] ) ) ) { return null ; // if found \"no data\" just return null } b1 = base64Alphabet [ d1 ] ; b2 = base64Alphabet [ d2 ] ; d3 = base64Data [ dataIndex ++ ] ; d4 = base64Data [ dataIndex ++ ] ; if ( ! isData ( ( d3 ) ) || ! isData ( ( d4 ) ) ) { // Check if they are PAD characters if ( isPad ( d3 ) && isPad ( d4 ) ) { if ( ( b2 & 0xf ) != 0 ) // last 4 bits should be zero { return null ; } byte [ ] tmp = new byte [ i * 3 + 1 ] ; System . arraycopy ( decodedData , 0 , tmp , 0 , i * 3 ) ; tmp [ encodedIndex ] = ( byte ) ( b1 << 2 | b2 >> 4 ) ; return tmp ; } else if ( ! isPad ( d3 ) && isPad ( d4 ) ) { b3 = base64Alphabet [ d3 ] ; if ( ( b3 & 0x3 ) != 0 ) // last 2 bits should be zero { return null ; } byte [ ] tmp = new byte [ i * 3 + 2 ] ; System . arraycopy ( decodedData , 0 , tmp , 0 , i * 3 ) ; tmp [ encodedIndex ++ ] = ( byte ) ( b1 << 2 | b2 >> 4 ) ; tmp [ encodedIndex ] = ( byte ) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 >> 2 ) & 0xf ) ) ; return tmp ; } else { return null ; } } else { // No PAD e.g 3cQl b3 = base64Alphabet [ d3 ] ; b4 = base64Alphabet [ d4 ] ; decodedData [ encodedIndex ++ ] = ( byte ) ( b1 << 2 | b2 >> 4 ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 >> 2 ) & 0xf ) ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( b3 << 6 | b4 ) ; } return decodedData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove WhiteSpace from MIME containing encoded Base64 data . [CODESPLIT] private static int removeWhiteSpace ( char [ ] data ) { if ( data == null ) { return 0 ; } // count characters that's not whitespace int newSize = 0 ; int len = data . length ; for ( int i = 0 ; i < len ; i ++ ) { if ( ! isWhiteSpace ( data [ i ] ) ) { data [ newSize ++ ] = data [ i ] ; } } return newSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upload a file with a sync request . [CODESPLIT] public void put ( File file ) throws QSException { if ( ! file . exists ( ) || file . isDirectory ( ) ) throw new QSException ( \"File does not exist or it is a directory.\" ) ; put ( file , file . getName ( ) , null , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upload a file with a sync request . [CODESPLIT] public void put ( File file , String objectKey , String fileName , String eTag ) throws QSException { // Check the file does exist or not. if ( ! file . exists ( ) || file . isDirectory ( ) ) throw new QSException ( \"File does not exist or it is a directory.\" ) ; // Check file's length. long length = file . length ( ) ; if ( length < 1 ) throw new QSException ( \"The size of file cannot be smaller than 1 byte.\" ) ; if ( length <= partSize ) { partCounts = 1 ; putFile ( file , objectKey , fileName , length ) ; } else { // Do multi uploads. // Calculate part counts. if ( length / partSize > MAX_PART_COUNTS ) { partSize = length / MAX_PART_COUNTS ; partCounts = MAX_PART_COUNTS ; // Check every part's size(max 5GB). if ( partSize > 5 * 1024 * 1024 * 1024L ) throw new QSException ( \"The size of file is too large.\" ) ; } else { partCounts = ( int ) ( length / partSize ) ; if ( length % partSize > 0 ) partCounts += 1 ; } putFileMulti ( file , objectKey , fileName , eTag , length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upload a file with a multi upload as a sync request . [CODESPLIT] public void putFileMulti ( File file , final String objectKey , String fileName , String eTag , final long length ) throws QSException { if ( partSize < 4 * 1024 * 1024 ) { throw new QSException ( \"Every part of the file can not smaller than 4 MB.\" ) ; } if ( recorder == null || recorder . get ( objectKey ) == null ) { Bucket . InitiateMultipartUploadInput inputInit = new Bucket . InitiateMultipartUploadInput ( ) ; Bucket . InitiateMultipartUploadOutput initOutput = bucket . initiateMultipartUpload ( objectKey , inputInit ) ; int code = initOutput . getStatueCode ( ) ; // Initiate occurs an error. if ( code < 200 || code >= 300 ) { if ( callBack != null ) { OutputModel outputModel = new OutputModel ( ) ; outputModel . setStatueCode ( code ) ; outputModel . setMessage ( initOutput . getMessage ( ) ) ; callBack . onAPIResponse ( objectKey , outputModel ) ; } return ; } uploadModel = new UploadModel ( ) ; uploadModel . setTotalSize ( length ) ; uploadModel . setUploadID ( initOutput . getUploadID ( ) ) ; } else { byte [ ] bytes = recorder . get ( objectKey ) ; String json = new String ( bytes ) ; uploadModel = new Gson ( ) . fromJson ( json , UploadModel . class ) ; // Check status of the task. if ( uploadModel . isUploadComplete ( ) ) { if ( callBack != null ) { OutputModel outputModel = new OutputModel ( ) ; outputModel . setStatueCode ( 201 ) ; outputModel . setMessage ( \"This task has been uploaded.\" ) ; callBack . onAPIResponse ( objectKey , outputModel ) ; } return ; } } uploadModel . setTotalSize ( length ) ; // Check if all parts have been completely uploaded. if ( uploadModel . isFileComplete ( ) ) { completeMultiUpload ( objectKey , fileName , eTag , uploadModel . getUploadID ( ) , length ) ; } else { for ( int i = uploadModel . getCurrentPart ( ) ; i < partCounts ; i ++ ) { // Make records when a new part starts to upload. uploadModel . setCurrentPart ( i ) ; uploadModel . setBytesWritten ( i * partSize ) ; setData ( objectKey , recorder ) ; // Request cancelled. Stop upload other parts. if ( cancellationHandler != null && cancellationHandler . isCancelled ( ) ) { // Keep parts data into the upload. setData ( objectKey , recorder ) ; break ; } long contentLength = Math . min ( partSize , ( file . length ( ) - uploadModel . getCurrentPart ( ) * partSize ) ) ; Bucket . UploadMultipartInput input = new Bucket . UploadMultipartInput ( ) ; input . setBodyInputFilePart ( file ) ; input . setFileOffset ( i * partSize ) ; input . setContentLength ( contentLength ) ; input . setPartNumber ( i ) ; input . setUploadID ( uploadModel . getUploadID ( ) ) ; // Create request to upload a part. RequestHandler requestHandler = bucket . uploadMultipartRequest ( objectKey , input ) ; // Progress listener if ( progressListener != null ) { requestHandler . setProgressListener ( new BodyProgressListener ( ) { @ Override public void onProgress ( long len , long size ) { long bytesWritten = uploadModel . getCurrentPart ( ) * partSize + len ; progressListener . onProgress ( objectKey , bytesWritten , length ) ; } } ) ; } // Cancellation handler. requestHandler . setCancellationHandler ( cancellationHandler ) ; // Sign with server if needed. sign ( requestHandler ) ; // Send the request. OutputModel send = requestHandler . send ( ) ; // Check response. if ( send . getStatueCode ( ) != 200 && send . getStatueCode ( ) != 201 ) { // Failed. setData ( objectKey , recorder ) ; // On upload failed if ( callBack != null ) callBack . onAPIResponse ( objectKey , send ) ; // Once failed, break the circle. break ; } else if ( i == partCounts - 1 ) { // Success and it is the last part of th file. // Make a record in the upload. uploadModel . setBytesWritten ( length ) ; uploadModel . setFileComplete ( true ) ; setData ( objectKey , recorder ) ; } } // Finally check. if ( uploadModel . isFileComplete ( ) ) { completeMultiUpload ( objectKey , fileName , eTag , uploadModel . getUploadID ( ) , length ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When sending a request will call this method to sign with server . [CODESPLIT] private void sign ( RequestHandler requestHandler ) throws QSException { if ( callBack != null ) { String signed = callBack . onSignature ( requestHandler . getStringToSignature ( ) ) ; if ( ! QSStringUtil . isEmpty ( signed ) ) requestHandler . setSignature ( callBack . onAccessKey ( ) , signed ) ; String correctTime = callBack . onCorrectTime ( requestHandler . getStringToSignature ( ) ) ; if ( correctTime != null && correctTime . trim ( ) . length ( ) > 0 ) requestHandler . getBuilder ( ) . setHeader ( QSConstant . HEADER_PARAM_KEY_DATE , correctTime ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set data in the upload with a recorder . [CODESPLIT] private void setData ( String objectKey , Recorder recorder ) { if ( recorder == null ) return ; String upload = new Gson ( ) . toJson ( uploadModel ) ; recorder . set ( objectKey , upload . getBytes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete the multi upload . [CODESPLIT] private void completeMultiUpload ( String objectKey , String fileName , String eTag , String uploadID , long length ) throws QSException { CompleteMultipartUploadInput completeMultipartUploadInput = new CompleteMultipartUploadInput ( uploadID , partCounts , 0 ) ; completeMultipartUploadInput . setContentLength ( length ) ; // Set content disposition to the object. if ( ! QSStringUtil . isEmpty ( fileName ) ) { try { String keyName = QSStringUtil . percentEncode ( fileName , \"UTF-8\" ) ; completeMultipartUploadInput . setContentDisposition ( String . format ( \"attachment; filename=\\\"%s\\\"; filename*=utf-8''%s\" , keyName , keyName ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } // Set the Md5 info to the object. if ( ! QSStringUtil . isEmpty ( eTag ) ) { completeMultipartUploadInput . setETag ( eTag ) ; } RequestHandler requestHandler = bucket . completeMultipartUploadRequest ( objectKey , completeMultipartUploadInput ) ; sign ( requestHandler ) ; Bucket . CompleteMultipartUploadOutput send = ( Bucket . CompleteMultipartUploadOutput ) requestHandler . send ( ) ; if ( send . getStatueCode ( ) == 200 || send . getStatueCode ( ) == 201 ) { uploadModel . setUploadComplete ( true ) ; setData ( objectKey , recorder ) ; } // Response callback. if ( callBack != null ) callBack . onAPIResponse ( objectKey , send ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upload a file with a simple put object upload as a sync request . <br > If a file s size is less than { [CODESPLIT] public void putFile ( File file , final String objectKey , String fileName , long length ) throws QSException { PutObjectInput input = new PutObjectInput ( ) ; input . setContentLength ( length ) ; input . setBodyInputFile ( file ) ; // Set content disposition to the object. if ( ! QSStringUtil . isEmpty ( fileName ) ) { try { String keyName = QSStringUtil . percentEncode ( fileName , \"UTF-8\" ) ; input . setContentDisposition ( String . format ( \"attachment; filename=\\\"%s\\\"; filename*=utf-8''%s\" , keyName , keyName ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } RequestHandler requestHandler = bucket . putObjectRequest ( objectKey , input ) ; // Set progress listener. if ( progressListener != null ) { requestHandler . setProgressListener ( new BodyProgressListener ( ) { @ Override public void onProgress ( long len , long size ) { progressListener . onProgress ( objectKey , len , size ) ; } } ) ; } // Cancellation handler. requestHandler . setCancellationHandler ( cancellationHandler ) ; // Sign if needed. sign ( requestHandler ) ; OutputModel outputModel = requestHandler . send ( ) ; if ( callBack != null ) callBack . onAPIResponse ( objectKey , outputModel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoking a FavoriteAction toggles it . [CODESPLIT] @ Override public void invoke ( final ActionRequest req , final ActionResponse res ) throws IOException { final NotificationEntry entry = getTarget ( ) ; final String notificationId = entry . getId ( ) ; final Set < String > favoriteNotices = this . getFavoriteNotices ( req ) ; if ( favoriteNotices . contains ( notificationId ) ) { favoriteNotices . remove ( notificationId ) ; } else { favoriteNotices . add ( notificationId ) ; } setFavoriteNotices ( req , favoriteNotices ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package - private [CODESPLIT] Set < String > getFavoriteNotices ( final PortletRequest req ) { final HashSet < String > rslt = new HashSet < String > ( ) ; final PortletPreferences prefs = req . getPreferences ( ) ; final String [ ] ids = prefs . getValues ( FAVORITE_NOTIFICATION_IDS_PREFERENCE , new String [ 0 ] ) ; for ( int i = 0 ; i < ids . length ; i ++ ) { rslt . add ( ids [ i ] ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package - private [CODESPLIT] void setFavoriteNotices ( final PortletRequest req , final Set < String > favoriteNotices ) { final String [ ] ids = favoriteNotices . toArray ( new String [ favoriteNotices . size ( ) ] ) ; final PortletPreferences prefs = req . getPreferences ( ) ; try { prefs . setValues ( FAVORITE_NOTIFICATION_IDS_PREFERENCE , ids ) ; prefs . store ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private static Comparator < NotificationEntry > chooseConfiguredComparator ( HttpServletRequest req ) { final String strategyName = req . getParameter ( SORT_STRATEGY_PARAMETER_NAME ) ; if ( strategyName == null ) { // No strategy means \"natural\" ordering;  we won't be sorting... return null ; } // We WILL be sorting;  work out the details... try { final SortStrategy strategy = SortStrategy . valueOf ( strategyName . toUpperCase ( ) ) ; // tolerant of case mismatch final String orderName = req . getParameter ( SORT_ORDER_PARAMETER_NAME ) ; final SortOrder order = StringUtils . isNotBlank ( orderName ) ? SortOrder . valueOf ( orderName . toUpperCase ( ) ) // tolerant of case mismatch : SortOrder . valueOf ( SORT_ORDER_DEFAULT ) ; return order . equals ( SortOrder . ASCENDING ) ? strategy . getComparator ( ) // Default/ascending order : Collections . reverseOrder ( strategy . getComparator ( ) ) ; // Descending order } catch ( IllegalArgumentException e ) { LOGGER . warn ( \"Unable to sort based on parameters {}='{}' and {}='{}'\" , SORT_STRATEGY_PARAMETER_NAME , strategyName , SORT_ORDER_PARAMETER_NAME , req . getParameter ( SORT_ORDER_PARAMETER_NAME ) ) ; } // We didn't succeed in selecting a strategy & order return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Caller must insure that the state being set has not already been added to the entry to avoid multiple events with the same state . [CODESPLIT] public void addEntryState ( PortletRequest req , String entryId , NotificationState state ) { if ( usernameFinder . isAuthenticated ( req ) ) { final String username = usernameFinder . findUsername ( req ) ; String idStr = entryId . replaceAll ( ID_PREFIX , \"\" ) ; // remove the prefix JpaEntry jpaEntry = notificationDao . getEntry ( Long . parseLong ( idStr ) ) ; if ( jpaEntry != null ) { JpaEvent event = new JpaEvent ( ) ; event . setEntry ( jpaEntry ) ; event . setState ( state ) ; event . setTimestamp ( new Timestamp ( new Date ( ) . getTime ( ) ) ) ; event . setUsername ( username ) ; notificationDao . createOrUpdateEvent ( event ) ; } else { throw new IllegalArgumentException ( \"JpaEntry not found\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private NotificationResponse prepareResponse ( Set < JpaEntry > entries , String username ) { Map < String , NotificationCategory > categories = new HashMap <> ( ) ; for ( JpaEntry entry : entries ) { // Choose a category title final String categryTitle = ! StringUtils . isBlank ( entry . getCategory ( ) ) ? entry . getCategory ( ) : messages . getMessage ( UNCATEGORIZED_MESSAGE_CODE , null , UNCATEGORIZED_DEFAULT_MESSAGE , Locale . getDefault ( ) ) ; // Obtain the category object matching the title NotificationCategory category = categories . get ( categryTitle ) ; if ( category == null ) { category = new NotificationCategory ( ) ; category . setTitle ( categryTitle ) ; categories . put ( categryTitle , category ) ; } // Prepare a NotificationEntry NotificationEntry y = prepareEntry ( entry , username ) ; if ( y != null ) { category . addEntries ( Collections . singletonList ( y ) ) ; } } // Create & load the response final List < NotificationCategory > cList = new ArrayList <> ( categories . values ( ) ) ; final List < NotificationError > eList = Collections . emptyList ( ) ; // Anything here? return new NotificationResponse ( cList , eList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link NotificationEntry } from a { @link JpaEntry } but will return null if that process cannot be performed in a valid way . [CODESPLIT] private NotificationEntry prepareEntry ( JpaEntry entry , String username ) { /*\n         * Implementation Note:  Most notification fields are optional.  This\n         * method impl avoids setting fields within the NotificationEntry when\n         * those fields are (essentially) unspecified on the JpaEntry in order\n         * not to run afoul of any logic (present or future) that may trigger\n         * when a field is set (e.g. validation, virtual members, change\n         * tracking).\n         */ NotificationEntry rslt = new NotificationEntry ( ) ; // Id & title will always be present rslt . setId ( ID_PREFIX + entry . getId ( ) ) ; final String title = entry . getTitle ( ) ; if ( StringUtils . isBlank ( title ) ) { log . warn ( \"User '\" + username + \"' had a notification with an empty title:  \" + entry . toString ( ) ) ; return null ; } rslt . setTitle ( title ) ; // But these fields are optional if ( ! StringUtils . isBlank ( entry . getBody ( ) ) ) { // Body rslt . setBody ( entry . getBody ( ) ) ; } if ( entry . getDueDate ( ) != null ) { // Due date rslt . setDueDate ( entry . getDueDate ( ) ) ; } if ( ! StringUtils . isBlank ( entry . getImage ( ) ) ) { // Image rslt . setImage ( entry . getImage ( ) ) ; } if ( ! StringUtils . isBlank ( entry . getLinkText ( ) ) ) { // Link text rslt . setLinkText ( entry . getLinkText ( ) ) ; } if ( entry . getPriority ( ) != 0 ) { // Priority rslt . setPriority ( entry . getPriority ( ) ) ; } if ( ! StringUtils . isBlank ( entry . getSource ( ) ) ) { // Source rslt . setSource ( entry . getSource ( ) ) ; } if ( ! StringUtils . isBlank ( entry . getUrl ( ) ) ) { // Url rslt . setUrl ( entry . getUrl ( ) ) ; } // States (transaction log) Map < NotificationState , Date > states = prepareStates ( entry , username ) ; rslt . setStates ( states ) ; // Collections of items... if ( ! entry . getAttributes ( ) . isEmpty ( ) ) { // Attributes List < NotificationAttribute > attributes = prepareAttributes ( entry . getAttributes ( ) ) ; rslt . setAttributes ( attributes ) ; } if ( ! entry . getActions ( ) . isEmpty ( ) ) { // Actions List < NotificationAction > actions = prepareActions ( entry . getActions ( ) , username ) ; rslt . setAvailableActions ( actions ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to determine if an SSPToken has expired . [CODESPLIT] public boolean hasExpired ( ) { long now = System . currentTimeMillis ( ) ; if ( created + ( expiresIn * 1000 ) + TIMEOUT_BUFFER > now ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Is the { [CODESPLIT] public boolean contains ( NotificationEntry entry ) { return StringUtils . isNotBlank ( entry . getId ( ) ) && entry . getId ( ) . startsWith ( JpaNotificationService . ID_PREFIX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides the known history of status changes for the specified user and notification <strong > in chronological order< / strong > . [CODESPLIT] @ Override public List < EventDTO > getHistory ( NotificationEntry entry , String username ) { List < EventDTO > rslt = Collections . emptyList ( ) ; // default /*\n         * The JPA system owns status tracking, but it only tracks status for\n         * entries that it owns.  If the entry is not already a JPA-backed\n         * entry, we would use a JPA-side \"proxy.\"\n         */ final EntryDTO entryDto = contains ( entry ) ? jpaNotificationRestService . getNotification ( entry , false ) : fetchJpaProxyIfAvailable ( entry ) ; // There can't be history if there isn't (yet) a proxy if ( entryDto != null ) { rslt = jpaNotificationRestService . getEventsByNotificationAndUser ( entryDto . getId ( ) , username ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private EntryDTO fetchJpaProxyIfAvailable ( NotificationEntry entry ) { EntryDTO rslt = null ; // default final List < EntryDTO > list = jpaNotificationRestService . getNotificationsBySourceAndCustomAttribute ( PROXY_SOURCE_NAME , PROXY_ID_ATTRIBUTE , entry . getId ( ) ) ; logger . debug ( \"Search for JPA-backed entry with id='{}' returned the following:  {}\" , entry . getId ( ) , list ) ; switch ( list . size ( ) ) { case 1 : // Cool;  we have one... rslt = list . get ( 0 ) ; break ; case 0 : // Also cool;  we don't have one... break ; default : // Not cool... throw new IllegalStateException ( \"More than one JPA-back entry exists for id=\" + entry . getId ( ) ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add all entries from the notification category to the <code > allEntries< / code > list after adding an attribute category that contains the category . That allows UIs that want the convenience of an uncategorized list such as dataTables to obtain the data in a simple format that requires no additional processing but maintains the knowledge of the category of the entries . [CODESPLIT] private void addAndCategorizeEntries ( List < NotificationEntry > allEntries , NotificationCategory notificationCategory ) { for ( NotificationEntry entry : notificationCategory . getEntries ( ) ) { List < NotificationAttribute > attrs = new ArrayList <> ( entry . getAttributes ( ) ) ; attrs . add ( new NotificationAttribute ( \"category\" , notificationCategory . getTitle ( ) ) ) ; entry . setAttributes ( attrs ) ; allEntries . add ( entry ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of notifications . Supports optional ( and recommended! ) paging [CODESPLIT] @ RequestMapping ( method = RequestMethod . GET ) @ ResponseBody public List < EntryDTO > getNotifications ( @ RequestParam ( value = \"page\" , required = false ) Integer page , @ RequestParam ( value = \"pageSize\" , required = false ) Integer pageSize ) { return restService . getNotifications ( page , pageSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a notification . [CODESPLIT] @ RequestMapping ( method = RequestMethod . POST ) @ ResponseStatus ( HttpStatus . CREATED ) @ ResponseBody public EntryDTO createNotification ( HttpServletRequest req , HttpServletResponse response , @ RequestBody EntryDTO entry ) { EntryDTO persisted = restService . createNotification ( entry ) ; String url = getSingleNotificationRESTUrl ( req , persisted . getId ( ) ) ; response . addHeader ( \"Location\" , url ) ; return persisted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get 1 notification by id . [CODESPLIT] @ RequestMapping ( value = \"/{notificationId}\" , method = RequestMethod . GET ) @ ResponseBody public EntryDTO getNotification ( HttpServletResponse response , @ PathVariable ( \"notificationId\" ) long id , @ RequestParam ( value = \"full\" , required = false , defaultValue = \"false\" ) boolean full ) { EntryDTO notification = restService . getNotification ( id , full ) ; if ( notification == null ) { response . setStatus ( HttpStatus . NOT_FOUND . value ( ) ) ; return null ; } return notification ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the set of addressees for a notification . [CODESPLIT] @ RequestMapping ( value = \"/{notificationId}/addressees\" , method = RequestMethod . GET ) @ ResponseBody public Set < AddresseeDTO > getAddressees ( @ PathVariable ( \"notificationId\" ) long id ) { return restService . getAddressees ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new addressee for a notification . [CODESPLIT] @ RequestMapping ( value = \"/{notificationId}/addressees\" , method = RequestMethod . POST ) @ ResponseBody @ ResponseStatus ( HttpStatus . CREATED ) public AddresseeDTO addAddressee ( HttpServletRequest req , HttpServletResponse resp , @ PathVariable ( \"notificationId\" ) long id , @ RequestBody AddresseeDTO addressee ) { AddresseeDTO dto = restService . createAddressee ( id , addressee ) ; if ( dto == null ) { resp . setStatus ( HttpStatus . NOT_FOUND . value ( ) ) ; return null ; } String url = getSingleNotificationRESTUrl ( req , id ) + \"/addressee/\" + dto . getId ( ) ; resp . addHeader ( \"Location\" , url ) ; return dto ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specific addressee [CODESPLIT] @ RequestMapping ( value = \"/{notificationId}/addressees/{addresseeId}\" , method = RequestMethod . GET ) @ ResponseBody public AddresseeDTO getAddressee ( HttpServletResponse resp , @ PathVariable ( \"notificationId\" ) long notificationId , @ PathVariable ( \"addresseeId\" ) long addresseeId ) { AddresseeDTO dto = restService . getAddressee ( addresseeId ) ; if ( dto == null ) { resp . setStatus ( HttpStatus . NOT_FOUND . value ( ) ) ; return null ; } return dto ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of events for a notification . [CODESPLIT] @ RequestMapping ( value = \"/{notificationId}/events\" , method = RequestMethod . GET ) @ ResponseBody public List < EventDTO > getEventsByNotification ( @ PathVariable ( \"notificationId\" ) long id ) { return restService . getEventsByNotification ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a specific event . [CODESPLIT] @ RequestMapping ( value = \"/{notificationId}/events/{eventId}\" , method = RequestMethod . GET ) @ ResponseBody public EventDTO getEvent ( HttpServletResponse response , @ PathVariable ( \"notificationId\" ) long notificationId , @ PathVariable ( \"eventId\" ) long eventId ) { EventDTO event = restService . getEvent ( eventId ) ; if ( event == null ) { response . setStatus ( HttpStatus . NOT_FOUND . value ( ) ) ; return null ; } return event ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new event . [CODESPLIT] @ RequestMapping ( value = \"/{notificationId}/events\" , method = RequestMethod . POST ) @ ResponseStatus ( HttpStatus . CREATED ) @ ResponseBody public EventDTO createEvent ( HttpServletRequest req , HttpServletResponse resp , @ PathVariable ( \"notificationId\" ) long notificationId , @ RequestBody EventDTO event ) { EventDTO dto = restService . createEvent ( notificationId , event ) ; if ( dto == null ) { resp . setStatus ( HttpStatus . NOT_FOUND . value ( ) ) ; return null ; } String url = getSingleNotificationRESTUrl ( req , notificationId ) + \"/state/\" + dto . getId ( ) ; resp . addHeader ( \"Location\" , url ) ; return dto ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the URL for a specific notification . [CODESPLIT] private String getSingleNotificationRESTUrl ( HttpServletRequest request , long id ) { String path = request . getContextPath ( ) + REQUEST_ROOT + id ; try { URL url = new URL ( request . getScheme ( ) , request . getServerName ( ) , request . getServerPort ( ) , path ) ; return url . toExternalForm ( ) ; } catch ( MalformedURLException e ) { // if it fails, just return a relative path.  Not ideal, but better than nothing... log . warn ( \"Error building Location header\" , e ) ; return path ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a complete transaction log for a notification and a single recipient <strong > in chronological order< / strong > . [CODESPLIT] @ Override @ Transactional ( readOnly = true ) public List < EventDTO > getEventsByNotificationAndUser ( long notificationId , String username ) { final List < JpaEvent > events = notificationDao . getEvents ( notificationId , username ) ; return notificationMapper . toEventList ( events ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private NotificationResponse doFetch ( List < String > feedUrls , String username ) { final List < NotificationCategory > categories = new ArrayList <> ( ) ; final List < NotificationError > errors = new ArrayList <> ( ) ; for ( String item : feedUrls ) { // It's okay to pull a response from cache, if we have one, since refresh happens in invoke() final Element m = cache . get ( item ) ; if ( m != null ) { // ## CACHE HIT ## if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Feed cache HIT for url:  \" + item ) ; } final NotificationCategory category = ( NotificationCategory ) m . getObjectValue ( ) ; categories . add ( category ) ; } else { // ## CACHE MISS ## if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Feed cache MISS for url:  \" + item ) ; logger . debug ( \"Checking the following feed URL for notifications for user '\" + username + \"' -- \" + item ) ; } final NotificationCategory category = fetchFromSourceUrl ( item ) ; if ( category != null ) { cache . put ( new Element ( item , category ) ) ; categories . add ( category ) ; } else { final NotificationError error = new NotificationError ( ) ; error . setError ( \"Service Unavailable\" ) ; error . setSource ( getName ( ) ) ; errors . add ( error ) ; } } } final NotificationResponse rslt = new NotificationResponse ( ) ; rslt . setCategories ( categories ) ; rslt . setErrors ( errors ) ; return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search for a JpaEntry with the specified Id . If the entry exists in the persistence context it is returned ; otherwise null is returned . [CODESPLIT] @ Override @ Transactional ( readOnly = true ) public JpaEntry getEntry ( long entryId ) { Validate . isTrue ( entryId > 0 , \"Invalid entryId:  \" + entryId ) ; JpaEntry rslt = entityManager . find ( JpaEntry . class , entryId ) ; return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains information about the user from the Authorization header in the form of an OIDC Id token . In the future it would be better to provide a standard tool ( bean ) for this job in the <code > uPortal - soffit - renderer< / code > component . [CODESPLIT] private Jws < Claims > parseOidcToken ( HttpServletRequest req ) { final String authHeader = req . getHeader ( HttpHeaders . AUTHORIZATION ) ; if ( StringUtils . isBlank ( authHeader ) || ! authHeader . startsWith ( Headers . BEARER_TOKEN_PREFIX ) ) { /*\n             * No OIDC token available\n             */ return null ; } final String bearerToken = authHeader . substring ( Headers . BEARER_TOKEN_PREFIX . length ( ) ) ; try { // Validate & parse the JWT final Jws < Claims > rslt = Jwts . parser ( ) . setSigningKey ( signatureKey ) . parseClaimsJws ( bearerToken ) ; logger . debug ( \"Found the following OIDC Id token:  {}\" , rslt . toString ( ) ) ; return rslt ; } catch ( Exception e ) { logger . info ( \"The following Bearer token is unusable:  '{}'\" , bearerToken ) ; logger . debug ( \"Failed to validate and/or parse the specified Bearer token\" , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subclasses <em > must< / em > call <code > super . init () < / code > . [CODESPLIT] @ PostConstruct public void init ( ) { super . init ( ) ; // Very important! try { nonEmptyResponse = objectMapper . readValue ( jsonResource . getURL ( ) , NotificationResponse . class ) ; } catch ( IOException ioe ) { final String msg = \"Failed to load JSON from resource:  \" + jsonResource ; throw new RuntimeException ( msg , ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the SSP API Context . Note : this method will ensure that that the API context starts with / and ensures that it does not end with a / . [CODESPLIT] @ Value ( \"${studentSuccessPlanService.sspContext:/ssp}\" ) public void setSspContext ( String sspContext ) { // ensure leading '/' if ( ! sspContext . startsWith ( \"/\" ) ) { sspContext = \"/\" + sspContext ; } // remove any trailing '/' if ( sspContext . endsWith ( \"/\" ) ) { sspContext = sspContext . replaceAll ( \"/*$\" , \"\" ) ; } this . sspContext = sspContext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public < T > ResponseEntity < T > doRequest ( SSPApiRequest < T > request ) throws MalformedURLException , RestClientException { SSPToken token = getAuthenticationToken ( false ) ; request . setHeader ( AUTHORIZATION , token . getTokenType ( ) + \" \" + token . getAccessToken ( ) ) ; URL url = getSSPUrl ( request . getUrlFragment ( ) , true ) ; ResponseEntity < T > response = restTemplate . exchange ( url . toExternalForm ( ) , request . getMethod ( ) , request . getRequestEntity ( ) , request . getResponseClass ( ) , request . getUriParameters ( ) ) ; // if we get a 401, the token may have unexpectedly expired (eg. ssp server restart). // Clear it, get a new token and replay the request one time. if ( response . getStatusCode ( ) == HttpStatus . UNAUTHORIZED ) { token = getAuthenticationToken ( true ) ; request . setHeader ( AUTHORIZATION , token . getTokenType ( ) + \" \" + token . getAccessToken ( ) ) ; return restTemplate . exchange ( url . toExternalForm ( ) , request . getMethod ( ) , request . getRequestEntity ( ) , request . getResponseClass ( ) , request . getUriParameters ( ) ) ; } return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public URL getSSPUrl ( String urlFragment , boolean useContext ) throws MalformedURLException { String path = ( useContext ) ? sspContext + urlFragment : urlFragment ; return new URL ( sspProtocol , sspHost , sspPort , path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the authentication token to use . [CODESPLIT] private synchronized SSPToken getAuthenticationToken ( boolean forceUpdate ) throws MalformedURLException , RestClientException { if ( authenticationToken != null && ! authenticationToken . hasExpired ( ) && ! forceUpdate ) { return authenticationToken ; } String authString = getClientId ( ) + \":\" + getClientSecret ( ) ; String authentication = new Base64 ( ) . encodeToString ( authString . getBytes ( ) ) ; HttpHeaders headers = new HttpHeaders ( ) ; headers . add ( AUTHORIZATION , BASIC + \" \" + authentication ) ; // form encode the grant_type... MultiValueMap < String , String > form = new LinkedMultiValueMap <> ( ) ; form . add ( GRANT_TYPE , CLIENT_CREDENTIALS ) ; HttpEntity < MultiValueMap < String , String > > request = new HttpEntity <> ( form , headers ) ; URL authURL = getAuthenticationURL ( ) ; authenticationToken = restTemplate . postForObject ( authURL . toExternalForm ( ) , request , SSPToken . class ) ; return authenticationToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { [CODESPLIT] public NotificationEntry findNotificationEntryById ( final String notificationId ) { // Assertions if ( notificationId == null ) { String msg = \"Argument 'notificationId' cannot be null\" ; throw new IllegalArgumentException ( msg ) ; } // Providing a brute-force implementation for  // now;  we can improve it if it becomes important. NotificationEntry rslt = null ; // default -- means not present for ( NotificationCategory category : categories ) { for ( NotificationEntry entry : category . getEntries ( ) ) { if ( notificationId . equals ( entry . getId ( ) ) ) { rslt = entry ; break ; } } if ( rslt != null ) { break ; } } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the contents of this response with the provided response and return a <b > new instance< / b > of { @link NotificationResponse } . The original instances are unchanged . [CODESPLIT] public NotificationResponse combine ( NotificationResponse response ) { NotificationResponse rslt = new NotificationResponse ( this ) ; rslt . addCategories ( response . getCategories ( ) ) ; rslt . addErrors ( response . getErrors ( ) ) ; return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a <b > new instance< / b > of { @link NotificationResponse } from which the specified errors have been removed . The original instances are unchanged . [CODESPLIT] public NotificationResponse filterErrors ( Set < Integer > hiddenErrorKeys ) { NotificationResponse rslt = new NotificationResponse ( this ) ; List < NotificationError > filteredErrors = new ArrayList <> ( ) ; for ( NotificationError r : errors ) { if ( ! hiddenErrorKeys . contains ( r . getKey ( ) ) ) { filteredErrors . add ( r ) ; } } rslt . setErrors ( filteredErrors ) ; // deep copy return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a <b > new instance< / b > of { [CODESPLIT] public NotificationResponse filter ( Predicate < NotificationEntry > predicate ) { final List < NotificationCategory > filteredCategories = categories . stream ( ) . map ( category -> { final List < NotificationEntry > filteredEntries = category . getEntries ( ) . stream ( ) . filter ( predicate ) . collect ( Collectors . toList ( ) ) ; return filteredEntries . size ( ) > 0 ? new NotificationCategory ( category . getTitle ( ) , filteredEntries ) : null ; } ) . filter ( value -> value != null ) . collect ( Collectors . toList ( ) ) ; return new NotificationResponse ( filteredCategories , getErrors ( ) ) ; // deep copy }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides the total number of notifications contained in the response . [CODESPLIT] @ JsonIgnore @ XmlTransient public int size ( ) { return categories . stream ( ) . map ( NotificationCategory :: getEntries ) . mapToInt ( List :: size ) . sum ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert the given categories and their entries into the any existing categories of the same title . If a category doesn t match an existing one add it to the list . [CODESPLIT] private void addCategories ( List < NotificationCategory > newCategories ) { if ( newCategories == null ) { return ; } // Start with a deep copy of the method parameter to simplify remaining logic newCategories = newCategories . parallelStream ( ) . map ( NotificationCategory :: cloneNoExceptions ) . collect ( Collectors . toList ( ) ) ; // Create a map of current categories by title for processing Map < String , NotificationCategory > catsByName = this . categories . parallelStream ( ) . collect ( toMap ( c -> c . getTitle ( ) . toLowerCase ( ) , c -> c ) ) ; // Split new categories between those that match an existing category and those that are completely new Map < Boolean , List < NotificationCategory > > matchingNewCats = newCategories . stream ( ) . collect ( partitioningBy ( c -> catsByName . containsKey ( c . getTitle ( ) . toLowerCase ( ) ) ) ) ; // Add new entries to existing categories matchingNewCats . get ( Boolean . TRUE ) . stream ( ) . forEachOrdered ( c -> catsByName . get ( c . getTitle ( ) . toLowerCase ( ) ) . addEntries ( c . getEntries ( ) ) ) ; // Add new categories this . categories . addAll ( matchingNewCats . get ( Boolean . FALSE ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Best guess as to the reason this method exists : beans that produce fresh { [CODESPLIT] public NotificationResponse cloneIfNotCloned ( ) { try { return isCloned ( ) ? this : ( NotificationResponse ) this . clone ( ) ; } catch ( CloneNotSupportedException e ) { log . error ( \"Failed to clone() the sourceResponse\" , e ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an empty collection and logs the event . All concrete implementations of { [CODESPLIT] @ Override public NotificationResponse fetch ( HttpServletRequest request ) { logger . warn ( \"Notification service '{}' was invoked by the portlet-agnostic API, but it \" + \"doesn't override fetch(HttpServletRequest)\" , getName ( ) ) ; return NotificationResponse . EMPTY_RESPONSE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch the set of SSP tasks for the uPortal user . [CODESPLIT] @ Override public NotificationResponse fetch ( PortletRequest req ) { PortletPreferences preferences = req . getPreferences ( ) ; String enabled = preferences . getValue ( SSP_NOTIFICATIONS_ENABLED , \"false\" ) ; if ( ! \"true\" . equalsIgnoreCase ( enabled ) ) { return new NotificationResponse ( ) ; } String personId = getPersonId ( req ) ; if ( personId == null ) { // Not all students will have active SSP records, // so if no entry is found in SSP, just return an // empty response set. return new NotificationResponse ( ) ; } String urlFragment = getActiveTaskUrl ( ) ; SSPApiRequest < String > request = new SSPApiRequest <> ( urlFragment , String . class ) . addUriParameter ( \"personId\" , personId ) ; ResponseEntity < String > response ; try { response = sspApi . doRequest ( request ) ; } catch ( Exception e ) { log . error ( \"Error reading SSP Notifications: \" + e . getMessage ( ) ) ; return notificationError ( e . getMessage ( ) ) ; } if ( response . getStatusCode ( ) . series ( ) != HttpStatus . Series . SUCCESSFUL ) { log . error ( \"Error reading SSP Notifications: \" + response ) ; return notificationError ( response . getBody ( ) ) ; } NotificationResponse notification = mapToNotificationResponse ( req , response ) ; return notification ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Error handler . [CODESPLIT] private NotificationResponse notificationError ( String errorMsg ) { NotificationError error = new NotificationError ( ) ; error . setError ( errorMsg ) ; error . setSource ( getClass ( ) . getSimpleName ( ) ) ; NotificationResponse notification = new NotificationResponse ( ) ; notification . setErrors ( Arrays . asList ( error ) ) ; return notification ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map and SSP Response to a NotificationResponse . [CODESPLIT] private NotificationResponse mapToNotificationResponse ( PortletRequest request , ResponseEntity < String > response ) { Configuration config = Configuration . builder ( ) . options ( Option . DEFAULT_PATH_LEAF_TO_NULL ) . build ( ) ; ReadContext readContext = JsonPath . using ( config ) . parse ( response . getBody ( ) ) ; // check the status embedded in the response too... String success = readContext . read ( SUCCESS_QUERY ) ; // grr. SSP returns this as a string... if ( ! \"true\" . equalsIgnoreCase ( success ) ) { String error = readContext . read ( MESSAGE_QUERY ) ; return notificationError ( error ) ; } // read the actual tasks... Object rows = readContext . read ( ROWS_QUERY ) ; if ( ! ( rows instanceof JSONArray ) ) { throw new RuntimeException ( \"Expected 'rows' to be an array of tasks\" ) ; } String source = getNotificationSource ( request ) ; List < NotificationEntry > list = new ArrayList <> ( ) ; for ( int i = 0 ; i < ( ( JSONArray ) rows ) . size ( ) ; i ++ ) { NotificationEntry entry = mapNotificationEntry ( readContext , i , source ) ; if ( entry != null ) { attachActions ( request , entry ) ; list . add ( entry ) ; } } // build the notification response... NotificationResponse notification = new NotificationResponse ( ) ; if ( ! list . isEmpty ( ) ) { NotificationCategory category = getNotificationCategory ( request ) ; category . addEntries ( list ) ; notification . setCategories ( Arrays . asList ( category ) ) ; } return notification ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map a single notification entry . [CODESPLIT] private NotificationEntry mapNotificationEntry ( ReadContext readContext , int index , String source ) { boolean completed = readContext . read ( format ( ROW_COMPLETED_QUERY_FMT , index ) , Boolean . class ) ; if ( completed ) { return null ; } NotificationEntry entry = new NotificationEntry ( ) ; entry . setSource ( source ) ; String id = readContext . read ( format ( ROW_ID_QUERY_FMT , index ) ) ; entry . setId ( id ) ; String title = readContext . read ( format ( ROW_NAME_QUERY_FMT , index ) ) ; entry . setTitle ( title ) ; String desc = readContext . read ( format ( ROW_DESCRIPTION_QUERY_FMT , index ) ) ; entry . setBody ( desc ) ; String link = readContext . read ( format ( ROW_LINK_QUERY_FMT , index ) ) ; URL fixedLink = normalizeLink ( link ) ; if ( fixedLink != null ) { entry . setUrl ( fixedLink . toExternalForm ( ) ) ; } Date createDate = readContext . read ( format ( \"$.rows[%d].createdDate\" , index ) , Date . class ) ; Map < NotificationState , Date > states = new HashMap <> ( ) ; states . put ( NotificationState . ISSUED , createDate ) ; try { // the date is in an odd format, need to parse by hand... String dateStr = readContext . read ( format ( ROW_DUE_DATE_QUERY_FMT , index ) ) ; if ( ! StringUtils . isBlank ( dateStr ) ) { synchronized ( dateFormat ) { Date dueDate = dateFormat . parse ( dateStr ) ; entry . setDueDate ( dueDate ) ; } } } catch ( Exception e ) { log . warn ( \"Error parsing due date.  Ignoring\" , e ) ; } return entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attach any SSP specific actions to this entry if enabled . [CODESPLIT] private void attachActions ( PortletRequest request , NotificationEntry entry ) { PortletPreferences prefs = request . getPreferences ( ) ; String stringVal = prefs . getValue ( SSP_NOTIFICATIONS_ENABLE_MARK_COMPLETED , \"false\" ) ; boolean enableMarkCompleted = ( \"true\" . equalsIgnoreCase ( stringVal ) ) ; List < NotificationAction > actions = new ArrayList <> ( ) ; if ( enableMarkCompleted ) { MarkTaskCompletedAction action = new MarkTaskCompletedAction ( entry . getId ( ) ) ; actions . add ( action ) ; } entry . setAvailableActions ( actions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some of the links I have seen from SSP are not well formed . Try to convert any URLs to a usable form . [CODESPLIT] private URL normalizeLink ( String link ) { try { if ( StringUtils . isEmpty ( link ) ) { return null ; } if ( link . startsWith ( \"/\" ) ) { return sspApi . getSSPUrl ( link , true ) ; } if ( link . startsWith ( \"http://\" ) || link . startsWith ( \"https://\" ) ) { return new URL ( link ) ; } // if all else fails, just tack on http:// and see if the URL parser can handle // it.  Perhaps, not ideal... return new URL ( \"http://\" + link ) ; } catch ( MalformedURLException e ) { log . warn ( \"Bad URL from SSP Entry: \" + link , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the category name to use for SSP notifications . [CODESPLIT] private NotificationCategory getNotificationCategory ( PortletRequest request ) { PortletPreferences preferences = request . getPreferences ( ) ; String title = preferences . getValue ( NOTIFICATION_CATEGORY_PREF , DEFAULT_CATEGORY ) ; NotificationCategory category = new NotificationCategory ( ) ; category . setTitle ( title ) ; return category ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the source value to use for a Notification entry . [CODESPLIT] private String getNotificationSource ( PortletRequest req ) { PortletPreferences preferences = req . getPreferences ( ) ; String source = preferences . getValue ( NOTIFICATION_SOURCE_PREF , DEFAULT_NOTIFICATION_SOURCE ) ; return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private String evaluateRedirectUri ( ActionRequest req ) { // Default response -- specify a relative URI, allowing the protocol to be inferred String rslt = req . getContextPath ( ) + SUCCESS_PATH ; final PortletPreferences prefs = req . getPreferences ( ) ; final String protocol = prefs . getValue ( INVOKE_REDIRECT_PROTOCOL_PREFERENCE , null ) ; if ( protocol != null ) { // Specify an absolute URI.  Apparently we need to insist on a protoco (usually HTTPS) String portPart = \"\" ; // default final String port = prefs . getValue ( INVOKE_REDIRECT_PORT_PREFERENCE , null ) ; if ( port != null ) { portPart = \":\" + port ; } rslt = protocol . toLowerCase ( ) + \"://\" + req . getServerName ( ) // Server hostname + portPart // Server port (blank, with any luck) + rslt ; // Remainder of the URI (as above) } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoking a ReadAction toggles it . [CODESPLIT] @ Override public void invoke ( final ActionRequest req , final ActionResponse res ) throws IOException { final NotificationEntry entry = getTarget ( ) ; final String notificationId = entry . getId ( ) ; final Set < String > readNotices = this . getReadNotices ( req ) ; if ( readNotices . contains ( notificationId ) ) { readNotices . remove ( notificationId ) ; } else { readNotices . add ( notificationId ) ; } setReadNotices ( req , readNotices ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package - private [CODESPLIT] Set < String > getReadNotices ( final PortletRequest req ) { final HashSet < String > rslt = new HashSet <> ( ) ; final PortletPreferences prefs = req . getPreferences ( ) ; final String [ ] ids = prefs . getValues ( READ_NOTIFICATION_IDS_PREFERENCE , new String [ 0 ] ) ; for ( int i = 0 ; i < ids . length ; i ++ ) { rslt . add ( ids [ i ] ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When invoke is called a configured notification state is set for the entry if it has not already been set . { @link JpaNotificationService } and { @link CacheNotificationService } are used here to add the entry state and clear the cache for the user . This class is not managed by Spring so these objects must be obtained using the Spring context that { @code SpringContext } provides . [CODESPLIT] @ Override public void invoke ( final ActionRequest req , final ActionResponse res ) throws IOException { JpaNotificationService jpaService = ( JpaNotificationService ) SpringContext . getApplicationContext ( ) . getBean ( \"jpaNotificationService\" ) ; final NotificationEntry entry = getTarget ( ) ; Map < NotificationState , Date > stateMap = entry . getStates ( ) ; if ( stateMap != null && ! stateMap . containsKey ( NotificationState . COMPLETED ) ) { jpaService . addEntryState ( req , entry . getId ( ) , NotificationState . COMPLETED ) ; } res . sendRedirect ( entry . getUrl ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private NotificationResponse fetchFromClasspath ( List < String > locations ) { if ( locations . isEmpty ( ) ) { return NotificationResponse . EMPTY_RESPONSE ; } NotificationResponse rslt ; final Element m = cache . get ( locations ) ; if ( m != null ) { // ## CACHE HIT ## rslt = ( NotificationResponse ) m . getObjectValue ( ) ; logger . debug ( \"Locations cache HIT for collection {};  size={}\" , locations , rslt . size ( ) ) ; } else { // ## CACHE MISS ## rslt = new NotificationResponse ( ) ; for ( String loc : locations ) { final NotificationResponse response = readFromFile ( loc ) ; rslt = rslt . combine ( response ) ; } logger . debug ( \"Locations cache MISS for collection {};  size={}\" , locations , rslt . size ( ) ) ; cache . put ( new Element ( locations , rslt ) ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize the given JSON formatted file back into a object . [CODESPLIT] private NotificationResponse readFromFile ( String filename ) { NotificationResponse rslt ; logger . debug ( \"Preparing to read from file:  {}\" , filename ) ; URL location = getClass ( ) . getClassLoader ( ) . getResource ( filename ) ; if ( location != null ) { try { File f = new File ( location . toURI ( ) ) ; rslt = mapper . readValue ( f , NotificationResponse . class ) ; } catch ( Exception e ) { String msg = \"Failed to read the data file:  \" + location ; logger . error ( msg , e ) ; rslt = prepareErrorResponse ( getName ( ) , msg ) ; } } else { String msg = \"Data file not found:  \" + filename ; rslt = prepareErrorResponse ( getName ( ) , msg ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private NotificationResponse getResponseFromService ( PortletRequest req , INotificationService service ) { NotificationResponse rslt ; try { rslt = service . fetch ( req ) ; } catch ( Exception e ) { final String msg = \"Failed to invoke the specified service:  \" + service . getName ( ) ; logger . error ( msg , e ) ; rslt = prepareErrorResponse ( getName ( ) , msg ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String lookupPersonId ( PortletRequest request ) { String studentId = getSchoolId ( request ) ; if ( StringUtils . isBlank ( studentId ) ) { return null ; } Element element = cache . get ( studentId ) ; if ( element != null ) { return ( String ) element . getObjectValue ( ) ; } String url = getPersonSearchURL ( ) ; SSPApiRequest sspReq = new SSPApiRequest ( url , String . class ) . addUriParameter ( \"schoolId\" , studentId ) ; try { ResponseEntity < String > response = sspApi . doRequest ( sspReq ) ; String userId = extractUserId ( studentId , response ) ; Element cacheElement = new Element ( studentId , userId ) ; cache . put ( cacheElement ) ; return userId ; } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the schoolId value from the request . [CODESPLIT] private String getSchoolId ( PortletRequest request ) { PortletPreferences prefs = request . getPreferences ( ) ; String schoolIdAttributeName = prefs . getValue ( \"SSPTaskNotificationService.schoolIdAttribute\" , \"schoolId\" ) ; Map < String , String > userInfo = ( Map < String , String > ) request . getAttribute ( PortletRequest . USER_INFO ) ; String studentId = userInfo . get ( schoolIdAttributeName ) ; if ( ! StringUtils . isEmpty ( studentId ) ) { return studentId ; } // if not found, fall back to username. studentId = userInfo . get ( USERNAME_ATTRIBUTE ) ; return studentId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the person lookup response from SSP . [CODESPLIT] private String extractUserId ( String studentId , ResponseEntity < String > response ) { Configuration config = Configuration . builder ( ) . options ( Option . DEFAULT_PATH_LEAF_TO_NULL ) . build ( ) ; ReadContext readContext = JsonPath . using ( config ) . parse ( response . getBody ( ) ) ; String success = readContext . read ( SUCCESS_QUERY ) ; // SSP passes this as a string... if ( ! \"true\" . equalsIgnoreCase ( success ) ) { return null ; } int count = readContext . read ( RESULTS_QUERY , Integer . class ) ; if ( count != 1 ) { // couldn't find a single unique result.  Bail now... log . warn ( \"Expected a single unique result for \" + studentId + \".  Found \" + count ) ; return null ; } String id = readContext . read ( STUDENT_ID_QUERY ) ; return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This { @link INotificationService } is fundamentally about Java Portlets and there is nothing it can offer to this overload of <code > fetch< / code > . [CODESPLIT] @ Override public NotificationResponse fetch ( HttpServletRequest request ) { logger . trace ( \"{} invoked for user '{}', but there is nothing to do\" , getClass ( ) . getSimpleName ( ) , usernameFinder . findUsername ( request ) ) ; return NotificationResponse . EMPTY_RESPONSE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoking a HideAction toggles it . [CODESPLIT] @ Override public void invoke ( final ActionRequest req , final ActionResponse res ) throws IOException { final NotificationEntry entry = getTarget ( ) ; /*\n         * The HideAction works like a toggle\n         */ if ( ! isEntrySnoozed ( entry , req ) ) { // Hide it... hide ( entry , req ) ; } else { // Un-hide it... unhide ( entry , req ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package - private [CODESPLIT] long calculateHideDurationMillis ( final NotificationEntry entry , final PortletRequest req ) { /*\n         * A notification may specify it's own duration as an attribute;\n         * if it doesn't, there is a default from the (portlet) publication record.\n         */ final PortletPreferences prefs = req . getPreferences ( ) ; // This is the default String hideDurationHours = prefs . getValue ( HideNotificationServiceDecorator . HIDE_DURATION_HOURS_PREFERENCE , null ) ; // Duration specified on the entry itself will trump final Map < String , List < String > > attributes = entry . getAttributesMap ( ) ; if ( attributes . containsKey ( HIDE_DURATION_HOURS_ATTRIBUTE_NAME ) ) { final List < String > values = attributes . get ( HIDE_DURATION_HOURS_ATTRIBUTE_NAME ) ; if ( values . size ( ) != 0 ) { hideDurationHours = values . get ( 0 ) ; // First is the only one that matters } } final long rslt = hideDurationHours != null ? Long . parseLong ( hideDurationHours ) * MILLIS_IN_ONE_HOUR : HideNotificationServiceDecorator . HIDE_DURATION_NONE ; logger . debug ( \"Calculated calculateHideDurationMillis={} for entry with id='{}', title='{}'\" , rslt , entry . getId ( ) , entry . getTitle ( ) ) ; return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package - private [CODESPLIT] boolean isEntrySnoozed ( NotificationEntry entry , PortletRequest req ) { // An id is required for hide behavior if ( StringUtils . isBlank ( entry . getId ( ) ) ) { return false ; } boolean rslt = false ; // default (clearly) final long snoozeDurationMillis = calculateHideDurationMillis ( entry , req ) ; // An entry with a negative snooze duration cannot be snoozed if ( snoozeDurationMillis > HideNotificationServiceDecorator . HIDE_DURATION_NONE ) { final JpaServices jpaServices = ( JpaServices ) SpringContext . getApplicationContext ( ) . getBean ( \"jpaServices\" ) ; final List < EventDTO > history = jpaServices . getHistory ( entry , req . getRemoteUser ( ) ) ; logger . debug ( \"List<EventDTO> within getNotificationsBySourceAndCustomAttribute contains {} elements\" , history . size ( ) ) ; // Review the history... for ( EventDTO event : history ) { switch ( event . getState ( ) ) { case SNOOZED : logger . debug ( \"Found a SNOOZED event:  {}\" , event ) ; // Nice, but it only counts if it isn't expired... if ( event . getTimestamp ( ) . getTime ( ) + snoozeDurationMillis > System . currentTimeMillis ( ) ) { rslt = true ; } break ; case ISSUED : logger . debug ( \"Found an ISSUED event:  {}\" , event ) ; // Re-issuing a notification un-snoozes it... rslt = false ; break ; default : // We don't care about any other events in the SNOOZED evaluation... break ; } } } logger . debug ( \"Returning SNOOZED='{}' for the following notification:  {}\" , rslt , entry ) ; return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Implementation [CODESPLIT] private void hide ( NotificationEntry entry , ActionRequest req ) { final JpaServices jpaServices = ( JpaServices ) SpringContext . getApplicationContext ( ) . getBean ( \"jpaServices\" ) ; jpaServices . applyState ( entry , req . getRemoteUser ( ) , NotificationState . SNOOZED ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for obtaining the attributes in a more usable collection . [CODESPLIT] @ JsonIgnore public Map < String , List < String > > getAttributesMap ( ) { Map < String , List < String > > rslt = new HashMap <> ( ) ; for ( NotificationAttribute a : attributes ) { rslt . put ( a . getName ( ) , a . getValues ( ) ) ; } return rslt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes the point such that the Frobenius norm is 1 . [CODESPLIT] public static void normalize ( GeoTuple3D_F64 p ) { double n = p . norm ( ) ; p . x /= n ; p . y /= n ; p . z /= n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the point is contained inside the box . The point is considered to be inside the box if the following test passes for each dimension . box . p0 . x &le ; point . x { @code < } box . p1 . x + box . lengthX [CODESPLIT] public static boolean contained ( Box3D_I32 box , Point3D_I32 point ) { return ( box . p0 . x <= point . x && point . x < box . p1 . x && box . p0 . y <= point . y && point . y < box . p1 . y && box . p0 . z <= point . z && point . z < box . p1 . z ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if boxB is contained inside of or is identical to boxA . [CODESPLIT] public static boolean contained ( Box3D_I32 boxA , Box3D_I32 boxB ) { return ( boxA . p0 . x <= boxB . p0 . x && boxA . p1 . x >= boxB . p1 . x && boxA . p0 . y <= boxB . p0 . y && boxA . p1 . y >= boxB . p1 . y && boxA . p0 . z <= boxB . p0 . z && boxA . p1 . z >= boxB . p1 . z ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the closest point on the triangle to P . [CODESPLIT] public void closestPoint ( Point3D_F64 P , Point3D_F64 closestPt ) { // D = B-P GeometryMath_F64 . sub ( B , P , D ) ; a = E0 . dot ( E0 ) ; b = E0 . dot ( E1 ) ; c = E1 . dot ( E1 ) ; d = E0 . dot ( D ) ; e = E1 . dot ( D ) ; double det = a * c - b * b ; s = b * e - c * d ; t = b * d - a * e ; if ( s + t <= det ) { if ( s < 0 ) { if ( t < 0 ) { region4 ( ) ; } else { region3 ( ) ; } } else if ( t < 0 ) { region5 ( ) ; } else { region0 ( det ) ; } } else { if ( s < 0 ) { region2 ( ) ; } else if ( t < 0 ) { region6 ( ) ; } else { region1 ( ) ; } } closestPt . x = B . x + s * E0 . x + t * E1 . x ; closestPt . y = B . y + s * E0 . y + t * E1 . y ; closestPt . z = B . z + s * E0 . z + t * E1 . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the signed of the vector . If its in front it will be positive and negative if behind . In front is defined as being on the same side as the cross product of p2 - p0 and p1 - p0 . [CODESPLIT] public double sign ( Point3D_F64 P ) { GeometryMath_F64 . cross ( E1 , E0 , N ) ; // dot product of double d = N . x * ( P . x - B . x ) + N . y * ( P . y - B . y ) + N . z * ( P . z - B . z ) ; return Math . signum ( d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set s this Se3_F64 to be identical to the provided transform . [CODESPLIT] public void set ( Se3_F64 se ) { R . set ( se . getR ( ) ) ; T . set ( se . getT ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fully specify the transform using Euler angles [CODESPLIT] public void set ( double x , double y , double z , EulerType type , double rotA , double rotB , double rotC ) { T . set ( x , y , z ) ; ConvertRotation3D_F64 . eulerToMatrix ( type , rotA , rotB , rotC , R ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fully specifies the transform using Rodrigues ( axis angle ) or Quaternions . If Rodrigues then A = axisX B = axisY C = axisZ D = theta . If Quaternion then A = w B = x C = y D = z . [CODESPLIT] public void set ( double x , double y , double z , RotationType type , double A , double B , double C , double D ) { T . set ( x , y , z ) ; switch ( type ) { case RODRIGUES : ConvertRotation3D_F64 . rodriguesToMatrix ( A , B , C , D , R ) ; break ; case QUATERNION : ConvertRotation3D_F64 . quaternionToMatrix ( A , B , C , D , R ) ; break ; default : throw new IllegalArgumentException ( \"Type is not supported. \" + type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the transform to the src point and stores the result in dst . src and dst can be the same instance [CODESPLIT] public Point3D_F64 transform ( Point3D_F64 src , @ Nullable Point3D_F64 dst ) { return SePointOps_F64 . transform ( this , src , dst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the reverse transform to the src point and stores the result in dst . src and dst can be the same instance [CODESPLIT] public Point3D_F64 transformReverse ( Point3D_F64 src , @ Nullable Point3D_F64 dst ) { return SePointOps_F64 . transformReverse ( this , src , dst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the rotation to the src vector and stores the result in dst . src and dst can be the same instance [CODESPLIT] public Vector3D_F64 transform ( Vector3D_F64 src , @ Nullable Vector3D_F64 dst ) { return GeometryMath_F64 . mult ( R , src , dst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the reverse rotation to the src vector and stores the result in dst . src and dst can be the same instance [CODESPLIT] public Vector3D_F64 transformReverse ( Vector3D_F64 src , @ Nullable Vector3D_F64 dst ) { return GeometryMath_F64 . multTran ( R , src , dst ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a rectangle into a quadrilateral [CODESPLIT] public static void convert ( Rectangle2D_F64 input , Quadrilateral_F64 output ) { output . a . x = input . p0 . x ; output . a . y = input . p0 . y ; output . b . x = input . p1 . x ; output . b . y = input . p0 . y ; output . c . x = input . p1 . x ; output . c . y = input . p1 . y ; output . d . x = input . p0 . x ; output . d . y = input . p1 . y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a rectangle into a polygon [CODESPLIT] public static void convert ( Rectangle2D_F64 input , Polygon2D_F64 output ) { if ( output . size ( ) != 4 ) throw new IllegalArgumentException ( \"polygon of order 4 expected\" ) ; output . get ( 0 ) . set ( input . p0 . x , input . p0 . y ) ; output . get ( 1 ) . set ( input . p1 . x , input . p0 . y ) ; output . get ( 2 ) . set ( input . p1 . x , input . p1 . y ) ; output . get ( 3 ) . set ( input . p0 . x , input . p1 . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a polygon into a quadrilateral [CODESPLIT] public static void convert ( Polygon2D_F64 input , Quadrilateral_F64 output ) { if ( input . size ( ) != 4 ) throw new IllegalArgumentException ( \"Expected 4-sided polygon as input\" ) ; output . a . set ( input . get ( 0 ) ) ; output . b . set ( input . get ( 1 ) ) ; output . c . set ( input . get ( 2 ) ) ; output . d . set ( input . get ( 3 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a rectangle into a quadrilateral [CODESPLIT] public static void convert ( RectangleLength2D_I32 input , Quadrilateral_F64 output ) { output . a . x = input . x0 ; output . a . y = input . y0 ; output . b . x = input . x0 + input . width - 1 ; output . b . y = input . y0 ; output . c . x = input . x0 + input . width - 1 ; output . c . y = input . y0 + input . height - 1 ; output . d . x = input . x0 ; output . d . y = input . y0 + input . height - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the minimum area bounding rectangle around the quadrilateral . [CODESPLIT] public static void bounding ( Quadrilateral_F64 quad , Rectangle2D_F64 rectangle ) { rectangle . p0 . x = Math . min ( quad . a . x , quad . b . x ) ; rectangle . p0 . x = Math . min ( rectangle . p0 . x , quad . c . x ) ; rectangle . p0 . x = Math . min ( rectangle . p0 . x , quad . d . x ) ; rectangle . p0 . y = Math . min ( quad . a . y , quad . b . y ) ; rectangle . p0 . y = Math . min ( rectangle . p0 . y , quad . c . y ) ; rectangle . p0 . y = Math . min ( rectangle . p0 . y , quad . d . y ) ; rectangle . p1 . x = Math . max ( quad . a . x , quad . b . x ) ; rectangle . p1 . x = Math . max ( rectangle . p1 . x , quad . c . x ) ; rectangle . p1 . x = Math . max ( rectangle . p1 . x , quad . d . x ) ; rectangle . p1 . y = Math . max ( quad . a . y , quad . b . y ) ; rectangle . p1 . y = Math . max ( rectangle . p1 . y , quad . c . y ) ; rectangle . p1 . y = Math . max ( rectangle . p1 . y , quad . d . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the minimum area bounding rectangle around the quadrilateral that is aligned with coordinate system axises . [CODESPLIT] public static void bounding ( Polygon2D_F64 polygon , Rectangle2D_F64 rectangle ) { rectangle . p0 . set ( polygon . get ( 0 ) ) ; rectangle . p1 . set ( polygon . get ( 0 ) ) ; for ( int i = 0 ; i < polygon . size ( ) ; i ++ ) { Point2D_F64 p = polygon . get ( i ) ; if ( p . x < rectangle . p0 . x ) { rectangle . p0 . x = p . x ; } else if ( p . x > rectangle . p1 . x ) { rectangle . p1 . x = p . x ; } if ( p . y < rectangle . p0 . y ) { rectangle . p0 . y = p . y ; } else if ( p . y > rectangle . p1 . y ) { rectangle . p1 . y = p . y ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the center or average point in the quadrilateral . [CODESPLIT] public static Point2D_F64 center ( Quadrilateral_F64 quad , Point2D_F64 center ) { if ( center == null ) center = new Point2D_F64 ( ) ; center . x = quad . a . x + quad . b . x + quad . c . x + quad . d . x ; center . y = quad . a . y + quad . b . y + quad . c . y + quad . d . y ; center . x /= 4.0 ; center . y /= 4.0 ; return center ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the polygon is ordered in a counter - clockwise order . This is done by summing up the interior angles . [CODESPLIT] public static boolean isCCW ( List < Point2D_F64 > polygon ) { final int N = polygon . size ( ) ; int sign = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int j = ( i + 1 ) % N ; int k = ( i + 2 ) % N ; Point2D_F64 a = polygon . get ( i ) ; Point2D_F64 b = polygon . get ( j ) ; Point2D_F64 c = polygon . get ( k ) ; double dx0 = a . x - b . x ; double dy0 = a . y - b . y ; double dx1 = c . x - b . x ; double dy1 = c . y - b . y ; double z = dx0 * dy1 - dy0 * dx1 ; if ( z > 0 ) sign ++ ; else sign -- ; } return sign < 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the average of all the vertexes [CODESPLIT] public static void vertexAverage ( Polygon2D_F64 input , Point2D_F64 average ) { average . setIdx ( 0 , 0 ) ; for ( int i = 0 ; i < input . size ( ) ; i ++ ) { Point2D_F64 v = input . vertexes . data [ i ] ; average . x += v . x ; average . y += v . y ; } average . x /= input . size ( ) ; average . y /= input . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the vertexes of the two polygon s are the same up to the specified tolerance [CODESPLIT] public static boolean isIdentical ( Polygon2D_F64 a , Polygon2D_F64 b , double tol ) { if ( a . size ( ) != b . size ( ) ) return false ; double tol2 = tol * tol ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( a . get ( i ) . distance2 ( b . get ( i ) ) > tol2 ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the vertexes of the two polygon s are the same up to the specified tolerance and allows for a shift in their order [CODESPLIT] public static boolean isEquivalent ( Polygon2D_F64 a , Polygon2D_F64 b , double tol ) { if ( a . size ( ) != b . size ( ) ) return false ; double tol2 = tol * tol ; // first find two vertexes which are the same Point2D_F64 a0 = a . get ( 0 ) ; int match = - 1 ; for ( int i = 0 ; i < b . size ( ) ; i ++ ) { if ( a0 . distance2 ( b . get ( i ) ) <= tol2 ) { match = i ; break ; } } if ( match < 0 ) return false ; // now go in a circle and see if they all line up for ( int i = 1 ; i < b . size ( ) ; i ++ ) { Point2D_F64 ai = a . get ( i ) ; Point2D_F64 bi = b . get ( ( match + i ) % b . size ( ) ) ; if ( ai . distance2 ( bi ) > tol2 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flips the order of points inside the polygon . The first index will remain the same will otherwise be reversed [CODESPLIT] public static void flip ( Polygon2D_F64 a ) { int N = a . size ( ) ; int H = N / 2 ; for ( int i = 1 ; i <= H ; i ++ ) { int j = N - i ; Point2D_F64 tmp = a . vertexes . data [ i ] ; a . vertexes . data [ i ] = a . vertexes . data [ j ] ; a . vertexes . data [ j ] = tmp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shifts all the vertexes in the polygon up one element . Wraps around at the end [CODESPLIT] public static void shiftUp ( Polygon2D_F64 a ) { final int N = a . size ( ) ; Point2D_F64 first = a . get ( 0 ) ; for ( int i = 0 ; i < N - 1 ; i ++ ) { a . vertexes . data [ i ] = a . vertexes . data [ i + 1 ] ; } a . vertexes . data [ N - 1 ] = first ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shifts all the vertexes in the polygon up one element . Wraps around at the end [CODESPLIT] public static void shiftDown ( Polygon2D_F64 a ) { final int N = a . size ( ) ; Point2D_F64 last = a . get ( N - 1 ) ; for ( int i = N - 1 ; i > 0 ; i -- ) { a . vertexes . data [ i ] = a . vertexes . data [ i - 1 ] ; } a . vertexes . data [ 0 ] = last ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the convex hull of the set of points . [CODESPLIT] public static void convexHull ( List < Point2D_F64 > points , Polygon2D_F64 hull ) { Point2D_F64 [ ] array = new Point2D_F64 [ points . size ( ) ] ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { array [ i ] = points . get ( i ) ; } AndrewMonotoneConvexHull_F64 andrew = new AndrewMonotoneConvexHull_F64 ( ) ; andrew . process ( array , array . length , hull ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a node from a polygon if the two lines its attached two are almost parallel [CODESPLIT] public static void removeAlmostParallel ( Polygon2D_F64 polygon , double tol ) { for ( int i = 0 ; i < polygon . vertexes . size ( ) ; ) { int j = ( i + 1 ) % polygon . vertexes . size ( ) ; int k = ( i + 2 ) % polygon . vertexes . size ( ) ; Point2D_F64 p0 = polygon . vertexes . get ( i ) ; Point2D_F64 p1 = polygon . vertexes . get ( j ) ; Point2D_F64 p2 = polygon . vertexes . get ( k ) ; double angle = UtilVector2D_F64 . acute ( p1 . x - p0 . x , p1 . y - p0 . y , p2 . x - p1 . x , p2 . y - p1 . y ) ; if ( angle <= tol ) { polygon . vertexes . remove ( j ) ; if ( j < i ) i = polygon . vertexes . size ( ) - 1 ; } else { i ++ ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a point if it s identical to a neighbor [CODESPLIT] public static void removeAdjacentDuplicates ( Polygon2D_F64 polygon , double tol ) { for ( int i = polygon . vertexes . size ( ) - 1 , j = 0 ; i >= 0 && polygon . size ( ) > 1 ; j = i , i -- ) { if ( polygon . get ( i ) . isIdentical ( polygon . get ( j ) , tol ) ) { polygon . vertexes . remove ( i ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a point if it s identical to a neighbor [CODESPLIT] public static boolean hasAdjacentDuplicates ( Polygon2D_F64 polygon , double tol ) { for ( int i = polygon . vertexes . size ( ) - 1 , j = 0 ; i >= 0 && polygon . size ( ) > 1 ; j = i , i -- ) { if ( polygon . get ( i ) . isIdentical ( polygon . get ( j ) , tol ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the error as a function of the distance between the model and target . The target is sampled at regular intervals and for each of these points the closest point on the model is found . The returned metric is the average of difference between paired points . [CODESPLIT] public static double averageOfClosestPointError ( Polygon2D_F64 model , Polygon2D_F64 target , int numberOfSamples ) { LineSegment2D_F64 line = new LineSegment2D_F64 ( ) ; double cornerLocationsB [ ] = new double [ target . size ( ) + 1 ] ; double totalLength = 0 ; for ( int i = 0 ; i < target . size ( ) ; i ++ ) { Point2D_F64 b0 = target . get ( i % target . size ( ) ) ; Point2D_F64 b1 = target . get ( ( i + 1 ) % target . size ( ) ) ; cornerLocationsB [ i ] = totalLength ; totalLength += b0 . distance ( b1 ) ; } cornerLocationsB [ target . size ( ) ] = totalLength ; Point2D_F64 pointOnB = new Point2D_F64 ( ) ; double error = 0 ; int cornerB = 0 ; for ( int k = 0 ; k < numberOfSamples ; k ++ ) { // Find the point on B to match to a point on A double location = totalLength * k / numberOfSamples ; while ( location > cornerLocationsB [ cornerB + 1 ] ) { cornerB ++ ; } Point2D_F64 b0 = target . get ( cornerB ) ; Point2D_F64 b1 = target . get ( ( cornerB + 1 ) % target . size ( ) ) ; double locationCornerB = cornerLocationsB [ cornerB ] ; double fraction = ( location - locationCornerB ) / ( cornerLocationsB [ cornerB + 1 ] - locationCornerB ) ; pointOnB . x = ( b1 . x - b0 . x ) * fraction + b0 . x ; pointOnB . y = ( b1 . y - b0 . y ) * fraction + b0 . y ; // find the best fit point on A to the point in B double best = Double . MAX_VALUE ; for ( int i = 0 ; i < model . size ( ) + 1 ; i ++ ) { line . a = model . get ( i % model . size ( ) ) ; line . b = model . get ( ( i + 1 ) % model . size ( ) ) ; double d = Distance2D_F64 . distance ( line , pointOnB ) ; if ( d < best ) { best = d ; } } error += best ; } return error / numberOfSamples ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the provided 3x3 matrix into a { @link Homography2D_F64 } . [CODESPLIT] public static Homography2D_F64 convert ( DMatrixRMaj m , Homography2D_F64 ret ) { if ( m . numCols != 3 || m . numRows != 3 ) throw new IllegalArgumentException ( \"Expected a 3 by 3 matrix.\" ) ; if ( ret == null ) ret = new Homography2D_F64 ( ) ; ret . a11 = m . unsafe_get ( 0 , 0 ) ; ret . a12 = m . unsafe_get ( 0 , 1 ) ; ret . a13 = m . unsafe_get ( 0 , 2 ) ; ret . a21 = m . unsafe_get ( 1 , 0 ) ; ret . a22 = m . unsafe_get ( 1 , 1 ) ; ret . a23 = m . unsafe_get ( 1 , 2 ) ; ret . a31 = m . unsafe_get ( 2 , 0 ) ; ret . a32 = m . unsafe_get ( 2 , 1 ) ; ret . a33 = m . unsafe_get ( 2 , 2 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link Homography2D_F64 } into a 3x3 matrix . [CODESPLIT] public static DMatrixRMaj convert ( Homography2D_F64 m , DMatrixRMaj ret ) { if ( ret == null ) { ret = new DMatrixRMaj ( 3 , 3 ) ; } else if ( ret . numCols != 3 || ret . numRows != 3 ) throw new IllegalArgumentException ( \"Expected a 3 by 3 matrix.\" ) ; ret . unsafe_set ( 0 , 0 , m . a11 ) ; ret . unsafe_set ( 0 , 1 , m . a12 ) ; ret . unsafe_set ( 0 , 2 , m . a13 ) ; ret . unsafe_set ( 1 , 0 , m . a21 ) ; ret . unsafe_set ( 1 , 1 , m . a22 ) ; ret . unsafe_set ( 1 , 2 , m . a23 ) ; ret . unsafe_set ( 2 , 0 , m . a31 ) ; ret . unsafe_set ( 2 , 1 , m . a32 ) ; ret . unsafe_set ( 2 , 2 , m . a33 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the area of the intersection between the two polygons . [CODESPLIT] public double computeArea ( Polygon2D_F64 a , Polygon2D_F64 b ) { ssss = 0 ; sclx = 0 ; scly = 0 ; return inter ( a , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------- [CODESPLIT] private double inter ( Polygon2D_F64 a , Polygon2D_F64 b ) { if ( a . size ( ) < 3 || b . size ( ) < 3 ) return 0 ; //\t\tint na = a.size(); //\t\tint nb = b.size(); Vertex [ ] ipa = new Vertex [ a . size ( ) + 1 ] ; Vertex [ ] ipb = new Vertex [ b . size ( ) + 1 ] ; Rectangle2D_F64 bbox = new Rectangle2D_F64 ( Double . MAX_VALUE , Double . MAX_VALUE , - Double . MAX_VALUE , - Double . MAX_VALUE ) ; range ( a , bbox ) ; range ( b , bbox ) ; double rngx = bbox . p1 . x - bbox . p0 . x ; sclx = gamut / rngx ; double rngy = bbox . p1 . y - bbox . p0 . y ; scly = gamut / rngy ; double ascale = sclx * scly ; fit ( a , ipa , 0 , bbox ) ; fit ( b , ipb , 2 , bbox ) ; for ( int j = 0 ; j < a . size ( ) ; ++ j ) { for ( int k = 0 ; k < b . size ( ) ; ++ k ) { if ( ovl ( ipa [ j ] . rx , ipb [ k ] . rx ) && ovl ( ipa [ j ] . ry , ipb [ k ] . ry ) ) { long a1 = - area ( ipa [ j ] . ip , ipb [ k ] . ip , ipb [ k + 1 ] . ip ) ; long a2 = area ( ipa [ j + 1 ] . ip , ipb [ k ] . ip , ipb [ k + 1 ] . ip ) ; boolean o = a1 < 0 ; if ( o == a2 < 0 ) { long a3 = area ( ipb [ k ] . ip , ipa [ j ] . ip , ipa [ j + 1 ] . ip ) ; long a4 = - area ( ipb [ k + 1 ] . ip , ipa [ j ] . ip , ipa [ j + 1 ] . ip ) ; if ( a3 < 0 == a4 < 0 ) { if ( o ) cross ( ipa [ j ] , ipa [ j + 1 ] , ipb [ k ] , ipb [ k + 1 ] , a1 , a2 , a3 , a4 ) ; else cross ( ipb [ k ] , ipb [ k + 1 ] , ipa [ j ] , ipa [ j + 1 ] , a3 , a4 , a1 , a2 ) ; } } } } } inness ( ipa , a . size ( ) , ipb , b . size ( ) ) ; inness ( ipb , b . size ( ) , ipa , a . size ( ) ) ; return ssss / ascale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a point along the line . See parametric equation in class description . [CODESPLIT] public Point2D_F64 getPointOnLine ( double t ) { return new Point2D_F64 ( slopeX * t + p . x , slopeY * t + p . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http : // www . ecse . rpi . edu / Homepages / wrf / Research / Short_Notes / pnpoly . html [CODESPLIT] public static boolean containConvex ( Polygon2D_F64 polygon , Point2D_F64 pt ) { final int N = polygon . size ( ) ; boolean c = false ; for ( int i = 0 , j = N - 1 ; i < N ; j = i ++ ) { Point2D_F64 a = polygon . vertexes . data [ i ] ; Point2D_F64 b = polygon . vertexes . data [ j ] ; if ( ( ( a . y > pt . y ) != ( b . y > pt . y ) ) && ( pt . x < ( b . x - a . x ) * ( pt . y - a . y ) / ( b . y - a . y ) + a . x ) ) c = ! c ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the point is contained inside the concave polygon . [CODESPLIT] public static boolean containConcave ( Polygon2D_F64 polygon , Point2D_F64 pt ) { final int N = polygon . size ( ) ; int left = 0 ; int right = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { Point2D_F64 a = polygon . vertexes . data [ i ] ; Point2D_F64 b = polygon . vertexes . data [ i + 1 ] ; if ( ( pt . y >= a . y && pt . y < b . y ) || ( pt . y >= b . y && pt . y < a . y ) ) { // location of line segment along x-axis at y = pt.y double x = b . y == a . y ? pt . x : ( pt . y - a . y ) * ( b . x - a . x ) / ( b . y - a . y ) + a . x ; if ( x <= pt . x ) left ++ ; else if ( x > pt . x ) right ++ ; } } Point2D_F64 a = polygon . vertexes . data [ N - 1 ] ; Point2D_F64 b = polygon . vertexes . data [ 0 ] ; if ( ( pt . y >= a . y && pt . y < b . y ) || ( pt . y >= b . y && pt . y < a . y ) ) { // location of line segment along x-axis at y = pt.y double x = b . y == a . y ? pt . x : ( pt . y - pt . y ) * ( b . x - a . x ) / ( b . y - a . y ) + a . x ; if ( x <= pt . x ) left ++ ; else if ( x > pt . x ) right ++ ; } return ( left % 2 == 1 && right % 2 == 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "True if the point is contained inside the quadrilateral . [CODESPLIT] public static boolean contains ( Quadrilateral_F64 quad , Point2D_F64 pt ) { return containTriangle ( quad . a , quad . b , quad . d , pt ) || containTriangle ( quad . b , quad . c , quad . d , pt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true of the the point is inside the triangle . [CODESPLIT] public static boolean containTriangle ( Point2D_F64 a , Point2D_F64 b , Point2D_F64 c , Point2D_F64 pt ) { boolean ret = false ; if ( ( ( a . y > pt . y ) != ( b . y > pt . y ) ) && ( pt . x < ( b . x - a . x ) * ( pt . y - a . y ) / ( b . y - a . y ) + a . x ) ) ret = true ; if ( ( ( b . y > pt . y ) != ( c . y > pt . y ) ) && ( pt . x < ( c . x - b . x ) * ( pt . y - b . y ) / ( c . y - b . y ) + b . x ) ) ret = ! ret ; if ( ( ( c . y > pt . y ) != ( a . y > pt . y ) ) && ( pt . x < ( a . x - c . x ) * ( pt . y - c . y ) / ( a . y - c . y ) + c . x ) ) ret = ! ret ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point of intersection between two lines and returns the point . [CODESPLIT] public static Point2D_F64 intersection ( LineParametric2D_F64 a , LineParametric2D_F64 b , Point2D_F64 ret ) { double t_b = a . getSlopeX ( ) * ( b . getY ( ) - a . getY ( ) ) - a . getSlopeY ( ) * ( b . getX ( ) - a . getX ( ) ) ; double bottom = a . getSlopeY ( ) * b . getSlopeX ( ) - b . getSlopeY ( ) * a . getSlopeX ( ) ; if ( bottom == 0 ) return null ; t_b /= bottom ; double x = b . getSlopeX ( ) * t_b + b . getX ( ) ; double y = b . getSlopeY ( ) * t_b + b . getY ( ) ; if ( ret == null ) ret = new Point2D_F64 ( ) ; ret . set ( x , y ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point of intersection between two lines . The point of intersection is specified as a point along the parametric line a . ( x y ) = ( x_0 y_0 ) + t * ( slope_x slope_y ) where t is the location returned . [CODESPLIT] public static double intersection ( LineParametric2D_F64 a , LineParametric2D_F64 b ) { double t_a = b . getSlopeX ( ) * ( a . getY ( ) - b . getY ( ) ) - b . getSlopeY ( ) * ( a . getX ( ) - b . getX ( ) ) ; double bottom = b . getSlopeY ( ) * a . getSlopeX ( ) - a . getSlopeY ( ) * b . getSlopeX ( ) ; if ( bottom == 0 ) return Double . NaN ; return t_a / bottom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point of intersection between two lines segments . [CODESPLIT] public static Point2D_F64 intersection ( LineSegment2D_F64 l_0 , LineSegment2D_F64 l_1 , Point2D_F64 ret ) { double a0 = l_0 . b . x - l_0 . a . x ; double b0 = l_0 . b . y - l_0 . a . y ; double a1 = l_1 . b . x - l_1 . a . x ; double b1 = l_1 . b . y - l_1 . a . y ; double top = b0 * ( l_1 . a . x - l_0 . a . x ) + a0 * ( l_0 . a . y - l_1 . a . y ) ; double bottom = a0 * b1 - b0 * a1 ; if ( bottom == 0 ) return null ; double t_1 = top / bottom ; // does not intersect along the second line segment if ( t_1 < 0 || t_1 > 1 ) return null ; top = b1 * ( l_0 . a . x - l_1 . a . x ) + a1 * ( l_1 . a . y - l_0 . a . y ) ; bottom = a1 * b0 - b1 * a0 ; double t_0 = top / bottom ; // does not intersect along the first line segment if ( t_0 < 0 || t_0 > 1 ) return null ; if ( ret == null ) { ret = new Point2D_F64 ( ) ; } ret . set ( l_1 . a . x + a1 * t_1 , l_1 . a . y + b1 * t_1 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the intersection of two lines as a 2D point in homogeneous coordinates . Because the solution is found in homogeneous coordinates it can even handle parallel lines which intersect at infinity . < / p > [CODESPLIT] public static Point3D_F64 intersection ( LineGeneral2D_F64 a , LineGeneral2D_F64 b , Point3D_F64 ret ) { if ( ret == null ) ret = new Point3D_F64 ( ) ; // compute the intersection as the cross product of 'a' and 'b' ret . x = a . B * b . C - a . C * b . B ; ret . y = a . C * b . A - a . A * b . C ; ret . z = a . A * b . B - a . B * b . A ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point of intersection between the two lines defined by the set sets of points passed in . [CODESPLIT] public static Point2D_F64 intersection ( Point2D_F64 lineA0 , Point2D_F64 lineA1 , Point2D_F64 lineB0 , Point2D_F64 lineB1 , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double slopeAx = lineA1 . x - lineA0 . x ; double slopeAy = lineA1 . y - lineA0 . y ; double slopeBx = lineB1 . x - lineB0 . x ; double slopeBy = lineB1 . y - lineB0 . y ; double top = slopeAy * ( lineB0 . x - lineA0 . x ) + slopeAx * ( lineA0 . y - lineB0 . y ) ; double bottom = slopeAx * slopeBy - slopeAy * slopeBx ; if ( bottom == 0 ) return null ; double t = top / bottom ; output . x = lineB0 . x + t * slopeBx ; output . y = lineB0 . y + t * slopeBy ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point of intersection between a line and a line segment . The point of intersection is specified as the distance along the parametric line . If no intersection is found then Double . NaN is returned . [CODESPLIT] public static double intersection ( LineParametric2D_F64 target , LineSegment2D_F64 l ) { double a1 = l . b . x - l . a . x ; double b1 = l . b . y - l . a . y ; double top = target . slope . y * ( l . a . x - target . p . x ) + target . slope . x * ( target . p . y - l . a . y ) ; double bottom = target . slope . x * b1 - target . slope . y * a1 ; if ( bottom == 0 ) return Double . NaN ; double t_1 = top / bottom ; // does not intersect along the second line segment if ( t_1 < 0 || t_1 > 1 ) return Double . NaN ; top = b1 * ( target . p . x - l . a . x ) + a1 * ( l . a . y - target . p . y ) ; bottom = a1 * target . slope . y - b1 * target . slope . x ; return top / bottom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the area of the intersection of two polygons . [CODESPLIT] public static double intersection ( Polygon2D_F64 a , Polygon2D_F64 b ) { AreaIntersectionPolygon2D_F64 alg = new AreaIntersectionPolygon2D_F64 ( ) ; return Math . abs ( alg . computeArea ( a , b ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Checks to see if the specified point is inside the rectangle . A point is inside if it is &ge ; the lower extend and &lt ; the upper extent . < / p > <p > inside = x &ge ; x0 AND x &le ; x1 AND y &ge ; y0 AND y &le ; y1 < / p > [CODESPLIT] public static boolean contains ( Rectangle2D_F64 a , double x , double y ) { return ( a . p0 . x <= x && a . p1 . x > x && a . p0 . y <= y && a . p1 . y > y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Checks to see if the specified point is inside the rectangle . A point is inside if it is &ge ; the lower extend and &le ; the upper extent . < / p > <p > inside = x &ge ; x0 AND x &le ; x1 AND y &ge ; y0 AND y &le ; y1 < / p > [CODESPLIT] public static boolean contains2 ( Rectangle2D_F64 a , double x , double y ) { return ( a . p0 . x <= x && a . p1 . x >= x && a . p0 . y <= y && a . p1 . y >= y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests to see if the provided point lies on or is contained inside the ellipse [CODESPLIT] public static boolean contains ( EllipseRotated_F64 ellipse , double x , double y ) { return ( UtilEllipse_F64 . evaluate ( x , y , ellipse ) <= 1.0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the two rectangles intersect each other [CODESPLIT] public static boolean intersects ( Rectangle2D_F64 a , Rectangle2D_F64 b ) { return ( a . p0 . x < b . p1 . x && a . p1 . x > b . p0 . x && a . p0 . y < b . p1 . y && a . p1 . y > b . p0 . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the intersection between two rectangles . If the rectangles don t intersect then false is returned . [CODESPLIT] public static boolean intersection ( Rectangle2D_F64 a , Rectangle2D_F64 b , Rectangle2D_F64 result ) { if ( ! intersects ( a , b ) ) return false ; result . p0 . x = Math . max ( a . p0 . x , b . p0 . x ) ; result . p1 . x = Math . min ( a . p1 . x , b . p1 . x ) ; result . p0 . y = Math . max ( a . p0 . y , b . p0 . y ) ; result . p1 . y = Math . min ( a . p1 . y , b . p1 . y ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the area of the intersection of two rectangles . [CODESPLIT] public static double intersectionArea ( Rectangle2D_F64 a , Rectangle2D_F64 b ) { if ( ! intersects ( a , b ) ) return 0 ; double x0 = Math . max ( a . p0 . x , b . p0 . x ) ; double x1 = Math . min ( a . p1 . x , b . p1 . x ) ; double y0 = Math . max ( a . p0 . y , b . p0 . y ) ; double y1 = Math . min ( a . p1 . y , b . p1 . y ) ; return ( x1 - x0 ) * ( y1 - y0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines the location ( s ) that a line and ellipse intersect . Returns the number of intersections found . NOTE : Due to floating point errors it s possible for a single solution to returned as two points . [CODESPLIT] public static int intersection ( LineGeneral2D_F64 line , EllipseRotated_F64 ellipse , Point2D_F64 intersection0 , Point2D_F64 intersection1 , double EPS ) { if ( EPS < 0 ) { EPS = GrlConstants . EPS ; } // First translate the line so that coordinate origin is the same as the ellipse double C = line . C + ( line . A * ellipse . center . x + line . B * ellipse . center . y ) ; // Now rotate the line double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; double A = line . A * cphi + line . B * sphi ; double B = - line . A * sphi + line . B * cphi ; // Now solve for the intersections with the coordinate system centered and aligned to the ellipse // There are two different ways to solve for this.  Pick the axis with the largest slope // to avoid the pathological case double a2 = ellipse . a * ellipse . a ; double b2 = ellipse . b * ellipse . b ; double x0 , y0 ; double x1 , y1 ; int totalIntersections ; if ( Math . abs ( A ) > Math . abs ( B ) ) { double alpha = - C / A ; double beta = - B / A ; double aa = beta * beta / a2 + 1.0 / b2 ; double bb = 2.0 * alpha * beta / a2 ; double cc = alpha * alpha / a2 - 1.0 ; double inner = bb * bb - 4.0 * aa * cc ; if ( Math . abs ( inner / aa ) < EPS ) { // divide by aa for scale invariance totalIntersections = 1 ; inner = inner < 0 ? 0 : inner ; } else if ( inner < 0 ) { return 0 ; } else { totalIntersections = 2 ; } double right = Math . sqrt ( inner ) ; y0 = ( - bb + right ) / ( 2.0 * aa ) ; y1 = ( - bb - right ) / ( 2.0 * aa ) ; x0 = - ( C + B * y0 ) / A ; x1 = - ( C + B * y1 ) / A ; } else { double alpha = - C / B ; double beta = - A / B ; double aa = beta * beta / b2 + 1.0 / a2 ; double bb = 2.0 * alpha * beta / b2 ; double cc = alpha * alpha / b2 - 1.0 ; double inner = bb * bb - 4.0 * aa * cc ; if ( Math . abs ( inner / aa ) < EPS ) { // divide by aa for scale invariance totalIntersections = 1 ; inner = inner < 0 ? 0 : inner ; } else if ( inner < 0 ) { return 0 ; } else { totalIntersections = 2 ; } double right = Math . sqrt ( inner ) ; x0 = ( - bb + right ) / ( 2.0 * aa ) ; x1 = ( - bb - right ) / ( 2.0 * aa ) ; y0 = - ( A * x0 + C ) / B ; y1 = - ( A * x1 + C ) / B ; } // go back into world coordinate system intersection0 . x = x0 * cphi - y0 * sphi + ellipse . center . x ; intersection0 . y = x0 * sphi + y0 * cphi + ellipse . center . y ; intersection1 . x = x1 * cphi - y1 * sphi + ellipse . center . x ; intersection1 . y = x1 * sphi + y1 * cphi + ellipse . center . y ; return totalIntersections ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts { @link georegression . struct . so . Rodrigues_F64 } into a rotation matrix . [CODESPLIT] public static DMatrixRMaj rodriguesToMatrix ( Rodrigues_F64 rodrigues , DMatrixRMaj R ) { return rodriguesToMatrix ( rodrigues . unitAxisRotation . x , rodrigues . unitAxisRotation . y , rodrigues . unitAxisRotation . z , rodrigues . theta , R ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts axis angle ( { @link Rodrigues_F64 } ) into a rotation matrix with out needing to declare a storage variable . [CODESPLIT] public static DMatrixRMaj rodriguesToMatrix ( double axisX , double axisY , double axisZ , double theta , DMatrixRMaj R ) { R = checkDeclare3x3 ( R ) ; //noinspection UnnecessaryLocalVariable double x = axisX , y = axisY , z = axisZ ; double c = Math . cos ( theta ) ; double s = Math . sin ( theta ) ; double oc = 1.0 - c ; R . data [ 0 ] = c + x * x * oc ; R . data [ 1 ] = x * y * oc - z * s ; R . data [ 2 ] = x * z * oc + y * s ; R . data [ 3 ] = y * x * oc + z * s ; R . data [ 4 ] = c + y * y * oc ; R . data [ 5 ] = y * z * oc - x * s ; R . data [ 6 ] = z * x * oc - y * s ; R . data [ 7 ] = z * y * oc + x * s ; R . data [ 8 ] = c + z * z * oc ; return R ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Converts { @link georegression . struct . so . Rodrigues_F64 } into an euler rotation of different types< / p > [CODESPLIT] public static double [ ] rodriguesToEuler ( Rodrigues_F64 rodrigues , EulerType type , double [ ] euler ) { DMatrixRMaj R = rodriguesToMatrix ( rodrigues , null ) ; return matrixToEuler ( R , type , euler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Converts { @link georegression . struct . so . Rodrigues_F64 } into a unit { @link georegression . struct . so . Quaternion_F64 } . < / p > [CODESPLIT] public static Quaternion_F64 rodriguesToQuaternion ( Rodrigues_F64 rodrigues , Quaternion_F64 quat ) { if ( quat == null ) quat = new Quaternion_F64 ( ) ; quat . w = Math . cos ( rodrigues . theta / 2.0 ) ; double s = Math . sin ( rodrigues . theta / 2.0 ) ; quat . x = rodrigues . unitAxisRotation . x * s ; quat . y = rodrigues . unitAxisRotation . y * s ; quat . z = rodrigues . unitAxisRotation . z * s ; return quat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a unit { [CODESPLIT] public static Rodrigues_F64 quaternionToRodrigues ( Quaternion_F64 quat , Rodrigues_F64 rodrigues ) { if ( rodrigues == null ) rodrigues = new Rodrigues_F64 ( ) ; rodrigues . unitAxisRotation . set ( quat . x , quat . y , quat . z ) ; rodrigues . unitAxisRotation . normalize ( ) ; rodrigues . theta = 2.0 * Math . acos ( quat . w ) ; return rodrigues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Converts a quaternion into an euler rotation of different types< / p > [CODESPLIT] public static double [ ] quaternionToEuler ( Quaternion_F64 q , EulerType type , double [ ] euler ) { DMatrixRMaj R = quaternionToMatrix ( q , null ) ; return matrixToEuler ( R , type , euler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Converts a rotation matrix into an Euler angle of different types< / p > [CODESPLIT] public static double [ ] matrixToEuler ( DMatrixRMaj R , EulerType type , double [ ] euler ) { if ( euler == null ) euler = new double [ 3 ] ; switch ( type ) { case ZYX : TanSinTan ( - 2 , 1 , 3 , - 6 , 9 , 5 , - 7 , 4 , 8 , R , euler ) ; break ; case ZYZ : TanCosTan ( 8 , - 7 , 9 , 6 , 3 , 5 , - 7 , 4 , 8 , R , euler ) ; break ; case ZXY : TanSinTan ( 4 , 5 , - 6 , 3 , 9 , 1 , 8 , - 2 , 7 , R , euler ) ; break ; case ZXZ : TanCosTan ( 7 , 8 , 9 , 3 , - 6 , 1 , 8 , - 2 , 7 , R , euler ) ; break ; case YXZ : TanSinTan ( - 7 , 9 , 8 , - 2 , 5 , 1 , - 6 , 3 , 4 , R , euler ) ; break ; case YXY : TanCosTan ( 4 , - 6 , 5 , 2 , 8 , 1 , - 6 , 3 , 4 , R , euler ) ; break ; case YZX : TanSinTan ( 3 , 1 , - 2 , 8 , 5 , 9 , 4 , - 7 , 6 , R , euler ) ; break ; case YZY : TanCosTan ( 6 , 4 , 5 , 8 , - 2 , 9 , 4 , - 7 , 6 , R , euler ) ; break ; case XYZ : TanSinTan ( 8 , 9 , - 7 , 4 , 1 , 5 , 3 , - 6 , 2 , R , euler ) ; break ; case XYX : TanCosTan ( 2 , 3 , 1 , 4 , - 7 , 5 , 3 , - 6 , 2 , R , euler ) ; break ; case XZY : TanSinTan ( - 6 , 5 , 4 , - 7 , 1 , 9 , - 2 , 8 , 3 , R , euler ) ; break ; case XZX : TanCosTan ( 3 , - 2 , 1 , 7 , 4 , 9 , - 2 , 8 , 3 , R , euler ) ; break ; default : throw new IllegalArgumentException ( \"Unknown rotation sequence\" ) ; } return euler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the index is negative it returns the negative of the value at - index . Starts at 0 [CODESPLIT] private static double get ( DMatrixRMaj M , int index ) { if ( index < 0 ) { return - M . data [ - index - 1 ] ; } else { return M . data [ index - 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts quaternions from the provided rotation matrix . [CODESPLIT] public static Quaternion_F64 matrixToQuaternion ( DMatrixRMaj R , Quaternion_F64 quat ) { if ( quat == null ) quat = new Quaternion_F64 ( ) ; // algorithm from: // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ // // Designed to minimize numerical error by not dividing by very small numbers double m00 = R . unsafe_get ( 0 , 0 ) ; double m01 = R . unsafe_get ( 0 , 1 ) ; double m02 = R . unsafe_get ( 0 , 2 ) ; double m10 = R . unsafe_get ( 1 , 0 ) ; double m11 = R . unsafe_get ( 1 , 1 ) ; double m12 = R . unsafe_get ( 1 , 2 ) ; double m20 = R . unsafe_get ( 2 , 0 ) ; double m21 = R . unsafe_get ( 2 , 1 ) ; double m22 = R . unsafe_get ( 2 , 2 ) ; double trace = m00 + m11 + m22 ; if ( trace > 0 ) { double S = Math . sqrt ( trace + 1.0 ) * 2 ; // S=4*qw quat . w = 0.25 * S ; quat . x = ( m21 - m12 ) / S ; quat . y = ( m02 - m20 ) / S ; quat . z = ( m10 - m01 ) / S ; } else if ( ( m00 > m11 ) & ( m00 > m22 ) ) { double S = Math . sqrt ( 1.0 + m00 - m11 - m22 ) * 2 ; // S=4*qx quat . w = ( m21 - m12 ) / S ; quat . x = 0.25 * S ; quat . y = ( m01 + m10 ) / S ; quat . z = ( m02 + m20 ) / S ; } else if ( m11 > m22 ) { double S = Math . sqrt ( 1.0 + m11 - m00 - m22 ) * 2 ; // S=4*qy quat . w = ( m02 - m20 ) / S ; quat . x = ( m01 + m10 ) / S ; quat . y = 0.25 * S ; quat . z = ( m12 + m21 ) / S ; } else { double S = Math . sqrt ( 1.0 + m22 - m00 - m11 ) * 2 ; // S=4*qz quat . w = ( m10 - m01 ) / S ; quat . x = ( m02 + m20 ) / S ; quat . y = ( m12 + m21 ) / S ; quat . z = 0.25 * S ; } return quat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a rotation matrix into { @link georegression . struct . so . Rodrigues_F64 } . [CODESPLIT] public static Rodrigues_F64 matrixToRodrigues ( DMatrixRMaj R , Rodrigues_F64 rodrigues ) { if ( rodrigues == null ) { rodrigues = new Rodrigues_F64 ( ) ; } // parts of this are from wikipedia // http://en.wikipedia.org/wiki/Rotation_representation_%28mathematics%29#Rotation_matrix_.E2.86.94_Euler_axis.2Fangle double diagSum = ( ( R . unsafe_get ( 0 , 0 ) + R . unsafe_get ( 1 , 1 ) + R . unsafe_get ( 2 , 2 ) ) - 1.0 ) / 2.0 ; double absDiagSum = Math . abs ( diagSum ) ; if ( absDiagSum <= 1.0 && 1.0 - absDiagSum > 10.0 * GrlConstants . EPS ) { // if numerically stable use a faster technique rodrigues . theta = Math . acos ( diagSum ) ; double bottom = 2.0 * Math . sin ( rodrigues . theta ) ; // in cases where bottom is close to zero that means theta is also close to zero and the vector // doesn't matter that much rodrigues . unitAxisRotation . x = ( R . unsafe_get ( 2 , 1 ) - R . unsafe_get ( 1 , 2 ) ) / bottom ; rodrigues . unitAxisRotation . y = ( R . unsafe_get ( 0 , 2 ) - R . unsafe_get ( 2 , 0 ) ) / bottom ; rodrigues . unitAxisRotation . z = ( R . unsafe_get ( 1 , 0 ) - R . unsafe_get ( 0 , 1 ) ) / bottom ; // in extreme underflow situations the result can be unnormalized rodrigues . unitAxisRotation . normalize ( ) ; // In theory this might be more stable // rotationAxis( R, rodrigues.unitAxisRotation); } else { // this handles the special case where the bottom is very very small or equal to zero if ( diagSum >= 1.0 ) rodrigues . theta = 0 ; else if ( diagSum <= - 1.0 ) rodrigues . theta = Math . PI ; else rodrigues . theta = Math . acos ( diagSum ) ; // compute the value of x,y,z up to a sign ambiguity rodrigues . unitAxisRotation . x = Math . sqrt ( ( R . get ( 0 , 0 ) + 1 ) / 2 ) ; rodrigues . unitAxisRotation . y = Math . sqrt ( ( R . get ( 1 , 1 ) + 1 ) / 2 ) ; rodrigues . unitAxisRotation . z = Math . sqrt ( ( R . get ( 2 , 2 ) + 1 ) / 2 ) ; double x = rodrigues . unitAxisRotation . x ; double y = rodrigues . unitAxisRotation . y ; double z = rodrigues . unitAxisRotation . z ; if ( Math . abs ( R . get ( 1 , 0 ) - 2 * x * y ) > GrlConstants . EPS ) { x *= - 1 ; } if ( Math . abs ( R . get ( 2 , 0 ) - 2 * x * z ) > GrlConstants . EPS ) { z *= - 1 ; } if ( Math . abs ( R . get ( 2 , 1 ) - 2 * z * y ) > GrlConstants . EPS ) { y *= - 1 ; x *= - 1 ; } rodrigues . unitAxisRotation . x = x ; rodrigues . unitAxisRotation . y = y ; rodrigues . unitAxisRotation . z = z ; } return rodrigues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a rotation matrix about the x - axis . [CODESPLIT] public static DMatrixRMaj rotX ( double ang , DMatrixRMaj R ) { if ( R == null ) R = new DMatrixRMaj ( 3 , 3 ) ; setRotX ( ang , R ) ; return R ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the values in the specified matrix to a rotation matrix about the x - axis . [CODESPLIT] public static void setRotX ( double ang , DMatrixRMaj R ) { double c = Math . cos ( ang ) ; double s = Math . sin ( ang ) ; R . set ( 0 , 0 , 1 ) ; R . set ( 1 , 1 , c ) ; R . set ( 1 , 2 , - s ) ; R . set ( 2 , 1 , s ) ; R . set ( 2 , 2 , c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a rotation matrix about the y - axis . [CODESPLIT] public static DMatrixRMaj rotY ( double ang , DMatrixRMaj R ) { R = checkDeclare3x3 ( R ) ; setRotY ( ang , R ) ; return R ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a rotation matrix about the z - axis . [CODESPLIT] public static DMatrixRMaj rotZ ( double ang , DMatrixRMaj R ) { R = checkDeclare3x3 ( R ) ; setRotZ ( ang , R ) ; return R ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the values in the specified matrix to a rotation matrix about the z - axis . [CODESPLIT] public static void setRotZ ( double ang , DMatrixRMaj r ) { double c = Math . cos ( ang ) ; double s = Math . sin ( ang ) ; r . set ( 0 , 0 , c ) ; r . set ( 0 , 1 , - s ) ; r . set ( 1 , 0 , s ) ; r . set ( 1 , 1 , c ) ; r . set ( 2 , 2 , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an Euler coordinate into a rotation matrix . Different type of Euler coordinates are accepted . [CODESPLIT] public static DMatrixRMaj eulerToMatrix ( EulerType type , double rotA , double rotB , double rotC , DMatrixRMaj R ) { R = checkDeclare3x3 ( R ) ; DMatrixRMaj R_a = rotationAboutAxis ( type . getAxisA ( ) , rotA , null ) ; DMatrixRMaj R_b = rotationAboutAxis ( type . getAxisB ( ) , rotB , null ) ; DMatrixRMaj R_c = rotationAboutAxis ( type . getAxisC ( ) , rotC , null ) ; DMatrixRMaj A = new DMatrixRMaj ( 3 , 3 ) ; CommonOps_DDRM . mult ( R_b , R_a , A ) ; CommonOps_DDRM . mult ( R_c , A , R ) ; return R ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a rotation matrix about the specified axis . [CODESPLIT] private static DMatrixRMaj rotationAboutAxis ( int axis , double angle , DMatrixRMaj R ) { switch ( axis ) { case 0 : return ConvertRotation3D_F64 . rotX ( angle , R ) ; case 1 : return ConvertRotation3D_F64 . rotY ( angle , R ) ; case 2 : return ConvertRotation3D_F64 . rotZ ( angle , R ) ; default : throw new IllegalArgumentException ( \"Unknown which\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds a rotation matrix which is the optimal approximation to an arbitrary 3 by 3 matrix . Optimality is specified by the equation below : <br > <br > min ||R - Q||<sup > 2< / sup > <sub > F< / sub > <br > R<br > where R is the rotation matrix and Q is the matrix being approximated . < / p > <p / > <p > The technique used is based on SVD and is described in Appendix C of A Flexible New Technique for Camera Calibration Technical Report updated 2002 . < / p > <p / > <p > Both origin and R can be the same instance . < / p > [CODESPLIT] public static DMatrixRMaj approximateRotationMatrix ( DMatrixRMaj orig , DMatrixRMaj R ) { R = checkDeclare3x3 ( R ) ; SingularValueDecomposition < DMatrixRMaj > svd = DecompositionFactory_DDRM . svd ( orig . numRows , orig . numCols , true , true , false ) ; if ( ! svd . decompose ( orig ) ) throw new RuntimeException ( \"SVD Failed\" ) ; CommonOps_DDRM . mult ( svd . getU ( null , false ) , svd . getV ( null , true ) , R ) ; // svd does not guarantee that U anv V have positive determinants. double det = CommonOps_DDRM . det ( R ) ; if ( det < 0 ) CommonOps_DDRM . scale ( - 1 , R ) ; return R ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Converts a unit quaternion into a rotation matrix . < / p > [CODESPLIT] public static DMatrixRMaj quaternionToMatrix ( Quaternion_F64 quat , DMatrixRMaj R ) { return quaternionToMatrix ( quat . w , quat . x , quat . y , quat . z , R ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the slope to the unit vector specified by the provided angle . [CODESPLIT] public void setAngle ( double angle ) { slope . set ( Math . cos ( angle ) , Math . sin ( angle ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a point along the line . See parametric equation in class description . [CODESPLIT] public Point2D_F64 getPointOnLine ( double t ) { return new Point2D_F64 ( slope . x * t + p . x , slope . y * t + p . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the { @link Se3_F64 } object into homogenous notation . <br > [CODESPLIT] public static DMatrixRMaj homogenous ( Se3_F64 transform , DMatrixRMaj H ) { if ( H == null ) { H = new DMatrixRMaj ( 4 , 4 ) ; } else { H . reshape ( 4 , 4 ) ; } CommonOps_DDRM . insert ( transform . R , H , 0 , 0 ) ; H . data [ 3 ] = transform . T . x ; H . data [ 7 ] = transform . T . y ; H . data [ 11 ] = transform . T . z ; H . data [ 12 ] = 0 ; H . data [ 13 ] = 0 ; H . data [ 14 ] = 0 ; H . data [ 15 ] = 1 ; return H ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the twist coordinate into homogenous format . <br > H = [ hat ( w ) v ; 0 0 ] [CODESPLIT] public static DMatrixRMaj homogenous ( TwistCoordinate_F64 twist , DMatrixRMaj H ) { if ( H == null ) { H = new DMatrixRMaj ( 4 , 4 ) ; } else { H . reshape ( 4 , 4 ) ; H . data [ 12 ] = 0 ; H . data [ 13 ] = 0 ; H . data [ 14 ] = 0 ; H . data [ 15 ] = 0 ; } H . data [ 0 ] = 0 ; H . data [ 1 ] = - twist . w . z ; H . data [ 2 ] = twist . w . y ; H . data [ 3 ] = twist . v . x ; H . data [ 4 ] = twist . w . z ; H . data [ 5 ] = 0 ; H . data [ 6 ] = - twist . w . x ; H . data [ 7 ] = twist . v . y ; H . data [ 8 ] = - twist . w . y ; H . data [ 9 ] = twist . w . x ; H . data [ 10 ] = 0 ; H . data [ 11 ] = twist . v . z ; return H ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the exponential map for a twist : <br > exp ( hat ( xi ) * theta ) = [ SO ( I - SO ) * ( w cross v ) + w * w<sup > T< / sup > v&Theta ; 0 1 ] <br > SO = exp ( hat ( w ) * theta ) < / p > [CODESPLIT] public static Se3_F64 exponential ( TwistCoordinate_F64 twist , double theta , Se3_F64 motion ) { if ( motion == null ) { motion = new Se3_F64 ( ) ; } double w_norm = twist . w . norm ( ) ; if ( w_norm == 0.0 ) { CommonOps_DDRM . setIdentity ( motion . R ) ; motion . T . x = twist . v . x * theta ; motion . T . y = twist . v . y * theta ; motion . T . z = twist . v . z * theta ; return motion ; } DMatrixRMaj R = motion . getR ( ) ; // First handle the SO region.  This Rodrigues equation double wx = twist . w . x / w_norm , wy = twist . w . y / w_norm , wz = twist . w . z / w_norm ; ConvertRotation3D_F64 . rodriguesToMatrix ( wx , wy , wz , theta * w_norm , R ) ; theta *= w_norm ; // Now compute the translational component // (I - SO)*(w cross v) + w*w'*v*theta double vx = twist . v . x , vy = twist . v . y , vz = twist . v . z ; double wv_x = wy * vz - wz * vy ; double wv_y = wz * vx - wx * vz ; double wv_z = wx * vy - wy * vx ; double left_x = ( 1 - R . data [ 0 ] ) * wv_x - R . data [ 1 ] * wv_y - R . data [ 2 ] * wv_z ; double left_y = - R . data [ 3 ] * wv_x + ( 1 - R . data [ 4 ] ) * wv_y - R . data [ 5 ] * wv_z ; double left_z = - R . data [ 6 ] * wv_x - R . data [ 7 ] * wv_y + ( 1 - R . data [ 8 ] ) * wv_z ; double right_x = ( wx * wx * vx + wx * wy * vy + wx * wz * vz ) * theta ; double right_y = ( wy * wx * vx + wy * wy * vy + wy * wz * vz ) * theta ; double right_z = ( wz * wx * vx + wz * wy * vy + wz * wz * vz ) * theta ; motion . T . x = ( double ) left_x + right_x ; motion . T . y = ( double ) left_y + right_y ; motion . T . z = ( double ) left_z + right_z ; motion . T . divide ( w_norm ) ; return motion ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a rigid body motion into a twist coordinate . The value of theta used to generate the motion is assumed to be one . [CODESPLIT] public static TwistCoordinate_F64 twist ( Se3_F64 motion , TwistCoordinate_F64 twist ) { if ( twist == null ) twist = new TwistCoordinate_F64 ( ) ; if ( MatrixFeatures_DDRM . isIdentity ( motion . R , GrlConstants . TEST_F64 ) ) { twist . w . set ( 0 , 0 , 0 ) ; twist . v . set ( motion . T ) ; } else { Rodrigues_F64 rod = new Rodrigues_F64 ( ) ; ConvertRotation3D_F64 . matrixToRodrigues ( motion . R , rod ) ; twist . w . set ( rod . unitAxisRotation ) ; double theta = rod . theta ; // A = (I-SO)*hat(w) + w*w'*theta DMatrixRMaj A = CommonOps_DDRM . identity ( 3 ) ; CommonOps_DDRM . subtract ( A , motion . R , A ) ; DMatrixRMaj w_hat = GeometryMath_F64 . crossMatrix ( twist . w , null ) ; DMatrixRMaj tmp = A . copy ( ) ; CommonOps_DDRM . mult ( tmp , w_hat , A ) ; Vector3D_F64 w = twist . w ; A . data [ 0 ] += w . x * w . x * theta ; A . data [ 1 ] += w . x * w . y * theta ; A . data [ 2 ] += w . x * w . z * theta ; A . data [ 3 ] += w . y * w . x * theta ; A . data [ 4 ] += w . y * w . y * theta ; A . data [ 5 ] += w . y * w . z * theta ; A . data [ 6 ] += w . z * w . x * theta ; A . data [ 7 ] += w . z * w . y * theta ; A . data [ 8 ] += w . z * w . z * theta ; DMatrixRMaj y = new DMatrixRMaj ( 3 , 1 ) ; y . data [ 0 ] = motion . T . x ; y . data [ 1 ] = motion . T . y ; y . data [ 2 ] = motion . T . z ; DMatrixRMaj x = new DMatrixRMaj ( 3 , 1 ) ; CommonOps_DDRM . solve ( A , y , x ) ; twist . w . scale ( rod . theta ) ; twist . v . x = ( double ) x . data [ 0 ] ; twist . v . y = ( double ) x . data [ 1 ] ; twist . v . z = ( double ) x . data [ 2 ] ; twist . v . scale ( rod . theta ) ; } return twist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify the two transforms which values are to be interpolated between [CODESPLIT] public void setTransforms ( Se3_F64 initial , Se3_F64 end ) { this . initial . set ( initial ) ; translation . x = end . T . x - initial . T . x ; translation . y = end . T . y - initial . T . y ; translation . z = end . T . z - initial . T . z ; CommonOps_DDRM . multTransA ( initial . getR ( ) , end . getR ( ) , R ) ; ConvertRotation3D_F64 . matrixToRodrigues ( R , rotation ) ; rotMagnitude = rotation . theta ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interpolates a value between the first and second transform . A value close to 0 will be more similar to the initial and 1 more similar to the end . [CODESPLIT] public void interpolate ( double where , Se3_F64 output ) { rotation . setTheta ( where * rotMagnitude ) ; ConvertRotation3D_F64 . rodriguesToMatrix ( rotation , R ) ; output . T . x = initial . T . x + where * translation . x ; output . T . y = initial . T . y + where * translation . y ; output . T . z = initial . T . z + where * translation . z ; CommonOps_DDRM . mult ( initial . R , R , output . R ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes sure x0 y0 is the lower extent and x1 y1 is the upper extent [CODESPLIT] public void enforceExtents ( ) { if ( p1 . x < p0 . x ) { double tmp = p1 . x ; p1 . x = p0 . x ; p0 . x = tmp ; } if ( p1 . y < p0 . y ) { double tmp = p1 . y ; p1 . y = p0 . y ; p0 . y = tmp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a 2D polygon into a 3D polygon . The 2D points will lie on the x - y plane ( e . g . ( x y 0 )) and are converted to 3D using polyToWorld . [CODESPLIT] public static void polygon2Dto3D ( Polygon2D_F64 polygon2D , Se3_F64 polyToWorld , FastQueue < Point3D_F64 > output ) { output . resize ( polygon2D . size ( ) ) ; for ( int i = 0 ; i < polygon2D . size ( ) ; i ++ ) { Point2D_F64 p2 = polygon2D . get ( i ) ; Point3D_F64 p3 = output . get ( i ) ; p3 . set ( p2 . x , p2 . y , 0 ) ; SePointOps_F64 . transform ( polyToWorld , p3 , p3 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the weighted best fit line to the set of points using the polar line equation . The solution is optimal in the Euclidean sense see [ 1 ] for more details . < / p > [CODESPLIT] public static LinePolar2D_F64 polar ( List < Point2D_F64 > points , double weights [ ] , LinePolar2D_F64 ret ) { final int N = points . size ( ) ; double totalWeight = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalWeight += weights [ i ] ; } if ( totalWeight == 0 ) return null ; if ( ret == null ) ret = new LinePolar2D_F64 ( ) ; double meanX = 0 ; double meanY = 0 ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double w = weights [ i ] ; meanX += w * p . x ; meanY += w * p . y ; } meanX /= totalWeight ; meanY /= totalWeight ; double top = 0 ; double bottom = 0 ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double w = weights [ i ] ; double dx = meanX - p . x ; double dy = meanY - p . y ; top += w * dx * dy ; bottom += w * ( dy * dy - dx * dx ) ; } top /= totalWeight ; bottom /= totalWeight ; ret . angle = Math . atan2 ( - 2.0 * top , bottom ) / 2.0 ; ret . distance = ( double ) ( meanX * Math . cos ( ret . angle ) + meanY * Math . sin ( ret . angle ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SVD based method for fitting a plane to a set of points . The plane s equation is returned as a point on the plane and the normal vector . [CODESPLIT] public boolean svd ( List < Point3D_F64 > points , Point3D_F64 outputCenter , Vector3D_F64 outputNormal ) { final int N = points . size ( ) ; // find the centroid outputCenter . set ( 0 , 0 , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { Point3D_F64 p = points . get ( i ) ; outputCenter . x += p . x ; outputCenter . y += p . y ; outputCenter . z += p . z ; } outputCenter . x /= N ; outputCenter . y /= N ; outputCenter . z /= N ; return solvePoint ( points , outputCenter , outputNormal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SVD based method for fitting a plane to a set of points and a known point on the plane . The plane s equation is returned as a point on the plane and the normal vector . [CODESPLIT] public boolean solvePoint ( List < Point3D_F64 > points , Point3D_F64 pointOnPlane , Vector3D_F64 outputNormal ) { final int N = points . size ( ) ; // construct the matrix A . reshape ( N , 3 ) ; int index = 0 ; for ( int i = 0 ; i < N ; i ++ ) { Point3D_F64 p = points . get ( i ) ; A . data [ index ++ ] = p . x - pointOnPlane . x ; A . data [ index ++ ] = p . y - pointOnPlane . y ; A . data [ index ++ ] = p . z - pointOnPlane . z ; } // decompose and find the singular value if ( ! solverNull . process ( A , 1 , nullspace ) ) return false ; // the normal is the singular vector outputNormal . x = ( double ) nullspace . unsafe_get ( 0 , 0 ) ; outputNormal . y = ( double ) nullspace . unsafe_get ( 1 , 0 ) ; outputNormal . z = ( double ) nullspace . unsafe_get ( 2 , 0 ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resturns the length of the specified side that is composed of point index and index + 1 [CODESPLIT] public double getSideLength ( int index ) { Point2D_F64 a = vertexes . get ( index ) ; Point2D_F64 b = vertexes . get ( ( index + 1 ) % vertexes . size ) ; return ( double ) a . distance ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the point is inside the polygon . Points along the border are ambiguously considered inside or outside . [CODESPLIT] public boolean isInside ( Point2D_F64 p ) { if ( isConvex ( ) ) { return Intersection2D_F64 . containConvex ( this , p ) ; } else { return Intersection2D_F64 . containConcave ( this , p ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the line / edge defined by vertex index and index + 1 . [CODESPLIT] public LineSegment2D_F64 getLine ( int index , LineSegment2D_F64 storage ) { if ( storage == null ) storage = new LineSegment2D_F64 ( ) ; int j = ( index + 1 ) % vertexes . size ; storage . a . set ( get ( index ) ) ; storage . b . set ( get ( j ) ) ; return storage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the polygon into a list . [CODESPLIT] public List < Point2D_F64 > convert ( @ Nullable List < Point2D_F64 > storage , boolean copy ) { if ( storage == null ) storage = new ArrayList <> ( ) ; else storage . clear ( ) ; if ( copy ) { for ( int i = 0 ; i < vertexes . size ; i ++ ) { storage . add ( vertexes . get ( i ) . copy ( ) ) ; } } else { storage . addAll ( vertexes . toList ( ) ) ; } return storage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the polygon to be the same as the list . A true copy is created and no references to points in the list are saved . [CODESPLIT] public void set ( List < Point2D_F64 > list ) { vertexes . resize ( list . size ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { vertexes . data [ i ] . set ( list . get ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts symmetric 3x3 matrix back into a conic . [CODESPLIT] public static DMatrixRMaj convert ( ConicGeneral_F64 src , DMatrixRMaj dst ) { if ( dst == null ) dst = new DMatrixRMaj ( 3 , 3 ) ; else dst . reshape ( 3 , 3 ) ; double B = src . B / 2.0 ; double D = src . D / 2.0 ; double E = src . E / 2.0 ; dst . data [ 0 ] = src . A ; dst . data [ 1 ] = B ; dst . data [ 2 ] = D ; dst . data [ 3 ] = B ; dst . data [ 4 ] = src . C ; dst . data [ 5 ] = E ; dst . data [ 6 ] = D ; dst . data [ 7 ] = E ; dst . data [ 8 ] = src . F ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts symmetric 3x3 matrix back into a conic . Only the upper right portion of src is read . [CODESPLIT] public static ConicGeneral_F64 convert ( DMatrix3x3 src , ConicGeneral_F64 dst ) { if ( dst == null ) dst = new ConicGeneral_F64 ( ) ; dst . A = src . a11 ; dst . B = 2 * src . a12 ; dst . D = 2 * src . a13 ; dst . C = src . a22 ; dst . E = 2 * src . a23 ; dst . F = src . a33 ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the conic into a symmetric 3x3 matrix [CODESPLIT] public static DMatrix3x3 convert ( ConicGeneral_F64 src , DMatrix3x3 dst ) { if ( dst == null ) dst = new DMatrix3x3 ( ) ; double B = src . B / 2.0 ; double D = src . D / 2.0 ; double E = src . E / 2.0 ; dst . a11 = src . A ; dst . a12 = B ; dst . a13 = D ; dst . a21 = B ; dst . a22 = src . C ; dst . a23 = E ; dst . a31 = D ; dst . a32 = E ; dst . a33 = src . F ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts symmetric 3x3 matrix back into a conic . Only the upper right portion of src is read . [CODESPLIT] public static ConicGeneral_F64 convert ( DMatrixRMaj src , ConicGeneral_F64 dst ) { if ( dst == null ) dst = new ConicGeneral_F64 ( ) ; dst . A = src . data [ 0 ] ; dst . B = 2 * src . data [ 1 ] ; dst . D = 2 * src . data [ 2 ] ; dst . C = src . data [ 4 ] ; dst . E = 2 * src . data [ 5 ] ; dst . F = src . data [ 8 ] ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the conic into a parabola . If the conic isn t a parabola then it is converted into one by adjusting the value of B . [CODESPLIT] public static ParabolaGeneral_F64 convert ( ConicGeneral_F64 src , ParabolaGeneral_F64 dst ) { if ( dst == null ) dst = new ParabolaGeneral_F64 ( ) ; // NOTE haven't put much through if this is the correct way to handle negative values of A or C dst . A = Math . signum ( src . A ) * Math . sqrt ( Math . abs ( src . A ) ) ; dst . C = Math . signum ( src . C ) * Math . sqrt ( Math . abs ( src . C ) ) ; dst . D = src . D ; dst . E = src . E ; dst . F = src . F ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the parabola into a conic . [CODESPLIT] public static ConicGeneral_F64 convert ( ParabolaGeneral_F64 src , ConicGeneral_F64 dst ) { if ( dst == null ) dst = new ConicGeneral_F64 ( ) ; dst . A = src . A * src . A ; dst . B = src . A * src . C * 2.0 ; dst . C = src . C * src . C ; dst . D = src . D ; dst . E = src . E ; dst . F = src . F ; return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static ParabolaParametric_F64 convert ( ParabolaGeneral_F64 src , ParabolaParametric_F64 dst ) { if ( dst == null ) dst = new ParabolaParametric_F64 ( ) ; double A = src . A ; double C = src . C ; double D = src . D ; double E = src . E ; double F = src . F ; double bottom = C * D - A * E ; if ( bottom == 0 ) { throw new RuntimeException ( \"Not a parabola\" ) ; } else { dst . A = - C / bottom ; dst . B = E / bottom ; dst . C = - C * F / bottom ; dst . D = A / bottom ; dst . E = - D / bottom ; dst . F = A * F / bottom ; } return dst ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a skew symmetric cross product matrix from the provided tuple . [CODESPLIT] public static DMatrixRMaj crossMatrix ( double x0 , double x1 , double x2 , DMatrixRMaj ret ) { if ( ret == null ) { ret = new DMatrixRMaj ( 3 , 3 ) ; } else { ret . zero ( ) ; } ret . set ( 0 , 1 , - x2 ) ; ret . set ( 0 , 2 , x1 ) ; ret . set ( 1 , 0 , x2 ) ; ret . set ( 1 , 2 , - x0 ) ; ret . set ( 2 , 0 , - x1 ) ; ret . set ( 2 , 1 , x0 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a skew symmetric cross product matrix from the provided tuple . [CODESPLIT] public static DMatrixRMaj crossMatrix ( GeoTuple3D_F64 v , DMatrixRMaj ret ) { if ( ret == null ) { ret = new DMatrixRMaj ( 3 , 3 ) ; } else { ret . zero ( ) ; } double x = v . getX ( ) ; double y = v . getY ( ) ; double z = v . getZ ( ) ; ret . set ( 0 , 1 , - z ) ; ret . set ( 0 , 2 , y ) ; ret . set ( 1 , 0 , z ) ; ret . set ( 1 , 2 , - x ) ; ret . set ( 2 , 0 , - y ) ; ret . set ( 2 , 1 , x ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the cross product : <br > <br > c = a x b < / p > [CODESPLIT] public static void cross ( double a_x , double a_y , double a_z , double b_x , double b_y , double b_z , GeoTuple3D_F64 c ) { c . x = a_y * b_z - a_z * b_y ; c . y = a_z * b_x - a_x * b_z ; c . z = a_x * b_y - a_y * b_x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the cross product : <br > <br > c = a x b<br > where a is in homogeneous coordinates . < / p > [CODESPLIT] public static void cross ( GeoTuple2D_F64 a , GeoTuple3D_F64 b , GeoTuple3D_F64 c ) { c . x = a . y * b . z - b . y ; c . y = b . x - a . x * b . z ; c . z = a . x * b . y - a . y * b . x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Adds two points together . <br > <br > c = a + b < / p > <p / > <p > Point c can be the same instance as a or b . < / p > [CODESPLIT] public static void add ( GeoTuple3D_F64 a , GeoTuple3D_F64 b , GeoTuple3D_F64 c ) { c . x = a . x + b . x ; c . y = a . y + b . y ; c . z = a . z + b . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Adds two points together while scaling them . <br > <br > pt<sub > 2< / sub > = a<sub > 0< / sub > pt<sub > 0< / sub > + a<sub > 1< / sub > pt<sub > 1< / sub > < / p > <p / > <p > Point c can be the same instance as a or b . < / p > [CODESPLIT] public static void add ( double a0 , GeoTuple3D_F64 pt0 , double a1 , GeoTuple3D_F64 pt1 , GeoTuple3D_F64 pt2 ) { pt2 . x = a0 * pt0 . x + a1 * pt1 . x ; pt2 . y = a0 * pt0 . y + a1 * pt1 . y ; pt2 . z = a0 * pt0 . z + a1 * pt1 . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > ret = p0 + M * p1< / p > [CODESPLIT] public static < T extends GeoTuple3D_F64 > T addMult ( T p0 , DMatrixRMaj M , T p1 , T result ) { if ( M . numRows != 3 || M . numCols != 3 ) throw new IllegalArgumentException ( \"Input matrix must be 3 by 3, not \" + M . numRows + \" \" + M . numCols ) ; if ( result == null ) { result = ( T ) p0 . createNewInstance ( ) ; } double x = p1 . x ; double y = p1 . y ; double z = p1 . z ; result . x = p0 . x + ( double ) ( M . data [ 0 ] * x + M . data [ 1 ] * y + M . data [ 2 ] * z ) ; result . y = p0 . y + ( double ) ( M . data [ 3 ] * x + M . data [ 4 ] * y + M . data [ 5 ] * z ) ; result . z = p0 . z + ( double ) ( M . data [ 6 ] * x + M . data [ 7 ] * y + M . data [ 8 ] * z ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Substracts two points from each other . <br > <br > c = a - b < / p > <p / > <p > Point c can be the same instance as a or b . < / p > [CODESPLIT] public static void sub ( GeoTuple3D_F64 a , GeoTuple3D_F64 b , GeoTuple3D_F64 c ) { c . x = a . x - b . x ; c . y = a . y - b . y ; c . z = a . z - b . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rotates a 2D point by the specified angle . [CODESPLIT] public static void rotate ( double theta , GeoTuple2D_F64 pt , GeoTuple2D_F64 solution ) { double c = Math . cos ( theta ) ; double s = Math . sin ( theta ) ; double x = pt . x ; double y = pt . y ; solution . x = c * x - s * y ; solution . y = s * x + c * y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rotates a 2D point by the specified angle . [CODESPLIT] public static void rotate ( double c , double s , GeoTuple2D_F64 pt , GeoTuple2D_F64 solution ) { double x = pt . x ; double y = pt . y ; solution . x = c * x - s * y ; solution . y = s * x + c * y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mod = M * pt <p > pt and mod can be the same reference . < / p > [CODESPLIT] public static < T extends GeoTuple3D_F64 > T mult ( DMatrixRMaj M , T pt , T result ) { if ( M . numRows != 3 || M . numCols != 3 ) throw new IllegalArgumentException ( \"Input matrix must be 3 by 3, not \" + M . numRows + \" \" + M . numCols ) ; if ( result == null ) { result = ( T ) pt . createNewInstance ( ) ; } double x = pt . x ; double y = pt . y ; double z = pt . z ; result . x = ( double ) ( M . data [ 0 ] * x + M . data [ 1 ] * y + M . data [ 2 ] * z ) ; result . y = ( double ) ( M . data [ 3 ] * x + M . data [ 4 ] * y + M . data [ 5 ] * z ) ; result . z = ( double ) ( M . data [ 6 ] * x + M . data [ 7 ] * y + M . data [ 8 ] * z ) ; return ( T ) result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes mod = M * pt where both pt and mod are in homogeneous coordinates with z assumed to be equal to 1 and M is a 3x3 matrix . < / p > <p > pt and mod can be the same point . < / p > [CODESPLIT] public static < T extends GeoTuple2D_F64 > T mult ( DMatrixRMaj M , T pt , T mod ) { if ( M . numRows != 3 || M . numCols != 3 ) throw new IllegalArgumentException ( \"Input matrix must be 3 by 3, not \" + M . numRows + \" \" + M . numCols ) ; if ( mod == null ) { throw new IllegalArgumentException ( \"Must provide an instance in mod\" ) ; } double x = pt . x ; double y = pt . y ; double modz = ( double ) ( M . unsafe_get ( 2 , 0 ) * x + M . unsafe_get ( 2 , 1 ) * y + M . unsafe_get ( 2 , 2 ) ) ; mod . x = ( double ) ( ( M . unsafe_get ( 0 , 0 ) * x + M . unsafe_get ( 0 , 1 ) * y + M . unsafe_get ( 0 , 2 ) ) / modz ) ; mod . y = ( double ) ( ( M . unsafe_get ( 1 , 0 ) * x + M . unsafe_get ( 1 , 1 ) * y + M . unsafe_get ( 1 , 2 ) ) / modz ) ; return mod ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "x = P * X [CODESPLIT] public static void mult ( DMatrixRMaj P , GeoTuple4D_F64 X , GeoTuple3D_F64 mod ) { if ( P . numRows != 3 || P . numCols != 4 ) throw new IllegalArgumentException ( \"Input matrix must be 3 by 4 not \" + P . numRows + \" \" + P . numCols ) ; mod . x = P . data [ 0 ] * X . x + P . data [ 1 ] * X . y + P . data [ 2 ] * X . z + P . data [ 3 ] * X . w ; mod . y = P . data [ 4 ] * X . x + P . data [ 5 ] * X . y + P . data [ 6 ] * X . z + P . data [ 7 ] * X . w ; mod . z = P . data [ 8 ] * X . x + P . data [ 9 ] * X . y + P . data [ 10 ] * X . z + P . data [ 11 ] * X . w ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the following : <br > result = cross ( A ) <sup > T< / sup > * M<br > where M and result are 3x3 matrices cross ( A ) is the cross product matrix of A . < / p > [CODESPLIT] public static DMatrixRMaj multCrossATransA ( GeoTuple2D_F64 A , DMatrixRMaj M , DMatrixRMaj result ) { if ( M . numRows != 3 || M . numCols != 3 ) throw new IllegalArgumentException ( \"Input matrix must be 3 by 3, not \" + M . numRows + \" \" + M . numCols ) ; if ( result == null ) { result = new DMatrixRMaj ( 3 , 3 ) ; } double x = A . x ; double y = A . y ; double a11 = M . data [ 0 ] ; double a12 = M . data [ 1 ] ; double a13 = M . data [ 2 ] ; double a21 = M . data [ 3 ] ; double a22 = M . data [ 4 ] ; double a23 = M . data [ 5 ] ; double a31 = M . data [ 6 ] ; double a32 = M . data [ 7 ] ; double a33 = M . data [ 8 ] ; result . data [ 0 ] = a21 - a31 * y ; result . data [ 1 ] = a22 - a32 * y ; result . data [ 2 ] = a23 - a33 * y ; result . data [ 3 ] = - a11 + a31 * x ; result . data [ 4 ] = - a12 + a32 * x ; result . data [ 5 ] = - a13 + a33 * x ; result . data [ 6 ] = a11 * y - a21 * x ; result . data [ 7 ] = a12 * y - a22 * x ; result . data [ 8 ] = a13 * y - a23 * x ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mod = M<sup > T< / sup > * pt . Both pt and mod can be the same instance . [CODESPLIT] public static < T extends GeoTuple3D_F64 > T multTran ( DMatrixRMaj M , T pt , T mod ) { if ( M . numRows != 3 || M . numCols != 3 ) throw new IllegalArgumentException ( \"Rotation matrices are 3 by 3.\" ) ; if ( mod == null ) { mod = ( T ) pt . createNewInstance ( ) ; } double x = pt . x ; double y = pt . y ; double z = pt . z ; mod . x = ( double ) ( M . unsafe_get ( 0 , 0 ) * x + M . unsafe_get ( 1 , 0 ) * y + M . unsafe_get ( 2 , 0 ) * z ) ; mod . y = ( double ) ( M . unsafe_get ( 0 , 1 ) * x + M . unsafe_get ( 1 , 1 ) * y + M . unsafe_get ( 2 , 1 ) * z ) ; mod . z = ( double ) ( M . unsafe_get ( 0 , 2 ) * x + M . unsafe_get ( 1 , 2 ) * y + M . unsafe_get ( 2 , 2 ) * z ) ; return ( T ) mod ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the inner matrix product : <br > ret = x<sup > T< / sup > A<sup > T< / sup > y < / p > [CODESPLIT] public static double innerProdTranM ( GeoTuple3D_F64 a , DMatrixRMaj M , GeoTuple3D_F64 b ) { if ( M . numRows != 3 || M . numCols != 3 ) throw new IllegalArgumentException ( \"M must be 3 by 3.\" ) ; DMatrixRMaj m1 = new DMatrixRMaj ( 3 , 1 , true , a . x , a . y , a . z ) ; DMatrixRMaj m2 = new DMatrixRMaj ( 3 , 1 , true , b . x , b . y , b . z ) ; return ( double ) ( VectorVectorMult_DDRM . innerProdTranA ( m1 , M , m2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the outer product of two vectors : <br > O = a * b<sup > T< / sup > [CODESPLIT] public static DMatrixRMaj outerProd ( GeoTuple3D_F64 a , GeoTuple3D_F64 b , DMatrixRMaj ret ) { if ( ret == null ) ret = new DMatrixRMaj ( 3 , 3 ) ; ret . data [ 0 ] = a . x * b . x ; ret . data [ 1 ] = a . x * b . y ; ret . data [ 2 ] = a . x * b . z ; ret . data [ 3 ] = a . y * b . x ; ret . data [ 4 ] = a . y * b . y ; ret . data [ 5 ] = a . y * b . z ; ret . data [ 6 ] = a . z * b . x ; ret . data [ 7 ] = a . z * b . y ; ret . data [ 8 ] = a . z * b . z ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the outer product of two vectors onto a matrix : <br > ret = A + scalar * a * b<sup > T< / sup > [CODESPLIT] public static DMatrixRMaj addOuterProd ( DMatrixRMaj A , double scalar , GeoTuple3D_F64 b , GeoTuple3D_F64 c , DMatrixRMaj ret ) { if ( ret == null ) ret = new DMatrixRMaj ( 3 , 3 ) ; ret . data [ 0 ] = A . data [ 0 ] + scalar * b . x * c . x ; ret . data [ 1 ] = A . data [ 1 ] + scalar * b . x * c . y ; ret . data [ 2 ] = A . data [ 2 ] + scalar * b . x * c . z ; ret . data [ 3 ] = A . data [ 3 ] + scalar * b . y * c . x ; ret . data [ 4 ] = A . data [ 4 ] + scalar * b . y * c . y ; ret . data [ 5 ] = A . data [ 5 ] + scalar * b . y * c . z ; ret . data [ 6 ] = A . data [ 6 ] + scalar * b . z * c . x ; ret . data [ 7 ] = A . data [ 7 ] + scalar * b . z * c . y ; ret . data [ 8 ] = A . data [ 8 ] + scalar * b . z * c . z ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the inner matrix product : ret = a * M * b<br > where ret is a scalar number . a and b are automatically converted into homogeneous coordinates . < / p > [CODESPLIT] public static double innerProd ( GeoTuple2D_F64 a , DMatrixRMaj M , GeoTuple2D_F64 b ) { if ( M . numRows != 3 || M . numCols != 3 ) throw new IllegalArgumentException ( \"M must be 3 by 3.\" ) ; DMatrixRMaj m1 = new DMatrixRMaj ( 3 , 1 , true , a . x , a . y , 1 ) ; DMatrixRMaj m2 = new DMatrixRMaj ( 3 , 1 , true , b . x , b . y , 1 ) ; return ( double ) ( VectorVectorMult_DDRM . innerProdA ( m1 , M , m2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Multiplies each element in the tuple by v . <br > p<sub > i< / sub > = p<sub > i< / sub > * v < / p > [CODESPLIT] public static void scale ( GeoTuple3D_F64 p , double v ) { p . x *= v ; p . y *= v ; p . z *= v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divides each element by v [CODESPLIT] public static void divide ( GeoTuple3D_F64 p , double v ) { p . x /= v ; p . y /= v ; p . z /= v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Changes the sign of the vector : <br > <br > T = - T < / p > [CODESPLIT] public static void changeSign ( GeoTuple3D_F64 t ) { t . x = - t . x ; t . y = - t . y ; t . z = - t . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a GeoTuple3D_F64 into DMatrixRMaj [CODESPLIT] public static DMatrixRMaj toMatrix ( GeoTuple3D_F64 in , DMatrixRMaj out ) { if ( out == null ) out = new DMatrixRMaj ( 3 , 1 ) ; else if ( out . getNumElements ( ) != 3 ) throw new IllegalArgumentException ( \"Vector with 3 elements expected\" ) ; out . data [ 0 ] = in . x ; out . data [ 1 ] = in . y ; out . data [ 2 ] = in . z ; return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a DMatrixRMaj into GeoTuple3D_F64 [CODESPLIT] public static void toTuple3D ( DMatrixRMaj in , GeoTuple3D_F64 out ) { out . x = ( double ) in . get ( 0 ) ; out . y = ( double ) in . get ( 1 ) ; out . z = ( double ) in . get ( 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assign the Rodrigues coordinates using a 3 element vector . Theta is the vector s magnitude and the axis of rotation is the unit vector . [CODESPLIT] public void setParamVector ( double x , double y , double z ) { double ax = Math . abs ( x ) ; double ay = Math . abs ( y ) ; double az = Math . abs ( z ) ; double max = Math . max ( ax , ay ) ; max = Math . max ( max , az ) ; if ( max == 0 ) { theta = 0 ; unitAxisRotation . set ( 1 , 0 , 0 ) ; } else { x /= max ; y /= max ; z /= max ; theta = Math . sqrt ( x * x + y * y + z * z ) ; unitAxisRotation . x = x / theta ; unitAxisRotation . y = y / theta ; unitAxisRotation . z = z / theta ; theta *= max ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an angle which is ( - pi to pi ) into a half circle angle ( - pi / 2 to pi / 2 ) . [CODESPLIT] public static double toHalfCircle ( double angle ) { if ( angle < 0 ) angle += Math . PI ; if ( angle > Math . PI / 2.0 ) angle -= Math . PI ; return angle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an angle which is equivalent to the one provided but between ( inclusive ) - &pi ; and &pi ; . [CODESPLIT] public static double bound ( double ang ) { ang %= GrlConstants . PI2 ; if ( ang > PI ) { return ang - GrlConstants . PI2 ; } else if ( ang < - PI ) { return ang + GrlConstants . PI2 ; } return ang ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an angle which is equivalent to the one provided but between ( inclusive ) - &pi ; and &pi ; . [CODESPLIT] public static float bound ( float ang ) { ang %= GrlConstants . F_PI2 ; if ( ang > GrlConstants . F_PI ) { return ang - GrlConstants . F_PI2 ; } else if ( ang < - GrlConstants . F_PI ) { return ang + GrlConstants . F_PI2 ; } return ang ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bounds the angle between - &pi ; / 2 and &pi ; / 2 [CODESPLIT] public static double boundHalf ( double angle ) { angle = bound ( angle ) ; if ( angle > GrlConstants . PId2 ) { angle -= Math . PI ; } else if ( angle < - GrlConstants . PId2 ) { angle += Math . PI ; } return angle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bounds the angle between - &pi ; / 2 and &pi ; / 2 [CODESPLIT] public static float boundHalf ( float angle ) { angle = bound ( angle ) ; if ( angle > GrlConstants . F_PId2 ) { angle -= GrlConstants . F_PI ; } else if ( angle < - GrlConstants . F_PId2 ) { angle += GrlConstants . F_PI ; } return angle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Angular distance in radians to go from angA to angB in counter clock - wise direction . The resulting angle will be from 0 to 2&pi ; . [CODESPLIT] public static double distanceCCW ( double angA , double angB ) { if ( angB >= angA ) return angB - angA ; else return GrlConstants . PI2 - ( angA - angB ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Angular distance in radians to go from angA to angB in counter clock - wise direction . The resulting angle will be from 0 to 2&pi ; . [CODESPLIT] public static float distanceCCW ( float angA , float angB ) { if ( angB >= angA ) return angB - angA ; else return GrlConstants . F_PI2 - ( angA - angB ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Angular distance in radians to go from angA to angB in clock - wise direction . The resulting angle will be from 0 to 2&pi ; . [CODESPLIT] public static double distanceCW ( double angA , double angB ) { if ( angA >= angB ) return angA - angB ; else return GrlConstants . PI2 - ( angB - angA ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Angular distance in radians to go from angA to angB in clock - wise direction . The resulting angle will be from 0 to 2&pi ; . [CODESPLIT] public static float distanceCW ( float angA , float angB ) { if ( angA >= angB ) return angA - angB ; else return GrlConstants . F_PI2 - ( angB - angA ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the difference between two angles and bounds the result between - pi and pi : <br > result = angA - angB<br > and takes in account boundary conditions . < / p > [CODESPLIT] public static double minus ( double angA , double angB ) { double diff = angA - angB ; if ( diff > Math . PI ) { return GrlConstants . PI2 - diff ; } else if ( diff < - Math . PI ) return - GrlConstants . PI2 - diff ; return diff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the difference between two angles and bounds the result between - pi and pi : <br > result = angA - angB<br > and takes in account boundary conditions . < / p > [CODESPLIT] public static float minus ( float angA , float angB ) { float diff = angA - angB ; if ( diff > GrlConstants . F_PI ) { return GrlConstants . F_PI2 - diff ; } else if ( diff < - GrlConstants . F_PI ) return - GrlConstants . F_PI2 - diff ; return diff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Angular distance between two half circle angles . [CODESPLIT] public static double distHalf ( double angA , double angB ) { double a = Math . abs ( angA - angB ) ; if ( a <= Math . PI / 2 ) return a ; else return Math . PI - a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures a reflective bound so that the numbers from 0 to 1 where 0 is inclusive and 1 is inclusive . <pre > Examples : 1 . 5 = 0 . 5 - 0 . 25 = 0 . 25 - 0 . 75 = 0 . 75 0 = 0 1 = 1 0 . 999 = 0 . 999 2 = 0 - 1 = 1 < / pre > [CODESPLIT] public static double reflectZeroToOne ( double value ) { if ( value < 0 ) value = - value ; value = value % 2.0 ; if ( value > 1.0 ) return 2.0 - value ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the intersection of a line and a plane . Returns true if they intersect at a unique point or false if there is no intersection or an infinite number of intersections . [CODESPLIT] public static boolean intersect ( PlaneNormal3D_F64 plane , LineParametric3D_F64 line , Point3D_F64 intersection ) { double dx = plane . p . x - line . p . x ; double dy = plane . p . y - line . p . y ; double dz = plane . p . z - line . p . z ; double top = dx * plane . n . x + dy * plane . n . y + dz * plane . n . z ; double bottom = line . slope . dot ( plane . n ) ; if ( bottom == 0 ) return false ; double d = top / bottom ; intersection . x = line . p . x + d * line . slope . x ; intersection . y = line . p . y + d * line . slope . y ; intersection . z = line . p . z + d * line . slope . z ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the intersection of a line and a plane . Returns true if they intersect at a unique point or false if there is no intersection or an infinite number of intersections . [CODESPLIT] public static boolean intersect ( PlaneGeneral3D_F64 plane , LineParametric3D_F64 line , Point3D_F64 intersection ) { double top = plane . D - plane . A * line . p . x - plane . B * line . p . y - plane . C * line . p . z ; double bottom = plane . A * line . slope . x + plane . B * line . slope . y + plane . C * line . slope . z ; if ( bottom == 0 ) return false ; double d = top / bottom ; intersection . x = line . p . x + d * line . slope . x ; intersection . y = line . p . y + d * line . slope . y ; intersection . z = line . p . z + d * line . slope . z ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the line which is the intersection between the two planes . For a valid solution to be returned the planes must not be parallel to each other . If the planes are parallel then the slope of the returned line will have a value of zero for each element . [CODESPLIT] public static boolean intersect ( PlaneGeneral3D_F64 a , PlaneGeneral3D_F64 b , LineParametric3D_F64 line ) { // Line's slope is the cross product of the two normal vectors GeometryMath_F64 . cross ( a . A , a . B , a . C , b . A , b . B , b . C , line . slope ) ; if ( line . slope . normSq ( ) == 0 ) return false ; // Closest point on plane 'a' to origin (0,0,0) double n2 = a . A * a . A + a . B * a . B + a . C * a . C ; double closestX = a . A * a . D / n2 ; double closestY = a . B * a . D / n2 ; double closestZ = a . C * a . D / n2 ; // Cross product between normal of 'a' and the line's slope.  This points towards the intersection double slopeX = a . B * line . slope . z - a . C * line . slope . y ; double slopeY = a . C * line . slope . x - a . A * line . slope . z ; double slopeZ = a . A * line . slope . y - a . B * line . slope . x ; // Now find the intersection of the plane and a line containing point 'closest' and pointing towards the // the intersection. double top = b . D - b . A * closestX - b . B * closestY - b . C * closestZ ; double bottom = b . A * slopeX + b . B * slopeY + b . C * slopeZ ; double d = top / bottom ; line . p . x = closestX + d * slopeX ; line . p . y = closestY + d * slopeY ; line . p . z = closestZ + d * slopeZ ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the intersection between a 3D triangle and a line - segment . Code ported from [ 1 ] . < / p > [CODESPLIT] public static int intersect ( Triangle3D_F64 T , LineSegment3D_F64 R , Point3D_F64 output ) { return intersect ( T , R , output , new Vector3D_F64 ( ) , new Vector3D_F64 ( ) , new Vector3D_F64 ( ) , new Vector3D_F64 ( ) , new Vector3D_F64 ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the intersection between a 3D triangle and a line - segment . Code ported from [ 1 ] . Internal working variables are provided in this interface to reduce memory creation / destruction . < / p > [CODESPLIT] public static int intersect ( Triangle3D_F64 T , LineSegment3D_F64 R , Point3D_F64 output , Vector3D_F64 u , Vector3D_F64 v , Vector3D_F64 n , Vector3D_F64 dir , Vector3D_F64 w0 ) { double r , a , b ; // params to calc ray-plane intersect // get triangle edge vectors and plane normal u . minus ( T . v1 , T . v0 ) ; // NOTE: these could be precomputed v . minus ( T . v2 , T . v0 ) ; n . cross ( u , v ) ; if ( n . normSq ( ) == 0 ) // triangle is degenerate return - 1 ; // do not deal with this case dir . minus ( R . b , R . a ) ; // ray direction vector w0 . minus ( R . a , T . v0 ) ; a = - n . dot ( w0 ) ; b = n . dot ( dir ) ; if ( Math . abs ( b ) < GrlConstants . EPS ) { // ray is  parallel to triangle plane if ( a == 0 ) // ray lies in triangle plane return 2 ; else return 0 ; // ray disjoint from plane } // get intersect point of ray with triangle plane r = a / b ; if ( r < 0.0 ) // ray goes away from triangle return 0 ; // => no intersect else if ( r > 1.0 ) // is past the end of the line segment return 0 ; // intersect point of ray and plane output . x = R . a . x + r * dir . x ; output . y = R . a . y + r * dir . y ; output . z = R . a . z + r * dir . z ; // is I inside T? if ( containedPlane ( T . v0 , output , u , v , w0 ) ) { return 1 ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the intersection between a 3D triangle and a line . Code ported from [ 1 ] . Internal working variables are provided in this interface to reduce memory creation / destruction . < / p > [CODESPLIT] public static int intersect ( Triangle3D_F64 T , LineParametric3D_F64 R , Point3D_F64 output ) { return intersect ( T , R , output , new Vector3D_F64 ( ) , new Vector3D_F64 ( ) , new Vector3D_F64 ( ) , new Vector3D_F64 ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects if a 2D convex polygon that has been moved into a 3D world is intersected by the 3D line . <pre > Transformation : 1 ) Each 2D point is converted into 3D : X = ( x y 0 ) 2 ) X = R * X + T where ( R T ) are a rigid body transform from poly to world frames < / pre > [CODESPLIT] public static int intersectConvex ( FastQueue < Point3D_F64 > polygon , LineParametric3D_F64 line , Point3D_F64 output , Vector3D_F64 n , Vector3D_F64 u , Vector3D_F64 v , Vector3D_F64 w0 ) { if ( polygon . size < 3 ) throw new IllegalArgumentException ( \"There must be 3 or more points\" ) ; double r , a , b ; // params to calc ray-plane intersect Point3D_F64 v0 = polygon . get ( 0 ) ; Point3D_F64 v1 = polygon . get ( 1 ) ; Point3D_F64 v2 = polygon . get ( 2 ) ; // get triangle edge vectors and plane normal u . minus ( v1 , v0 ) ; // NOTE: these could be precomputed v . minus ( v2 , v0 ) ; n . cross ( u , v ) ; if ( n . normSq ( ) == 0 ) // triangle is degenerate return - 1 ; // do not deal with this case Vector3D_F64 dir = line . slope ; w0 . minus ( line . p , v0 ) ; a = - n . dot ( w0 ) ; b = n . dot ( dir ) ; if ( Math . abs ( b ) < GrlConstants . EPS ) { // ray is  parallel to triangle plane if ( a == 0 ) // ray lies in triangle plane return 2 ; else return 0 ; // ray disjoint from plane } // get intersect point of ray with triangle plane r = a / b ; // intersect point of ray and plane output . x = line . p . x + r * dir . x ; output . y = line . p . y + r * dir . y ; output . z = line . p . z + r * dir . z ; // See if it's inside any of the triangles for ( int i = 2 ; i < polygon . size ; i ++ ) { // is I inside T? if ( containedPlane ( v0 , output , u , v , w0 ) ) { if ( r >= 0 ) return 1 ; else return 3 ; } if ( i < polygon . size - 1 ) { u . minus ( polygon . get ( i ) , v0 ) ; v . minus ( polygon . get ( i + 1 ) , v0 ) ; } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the point on the same plane as T is contained inside of T . [CODESPLIT] private static boolean containedPlane ( Point3D_F64 T_v0 , Point3D_F64 output , Vector3D_F64 u , Vector3D_F64 v , Vector3D_F64 w0 ) { double uu , uv , vv , wu , wv , D ; uu = u . dot ( u ) ; uv = u . dot ( v ) ; vv = v . dot ( v ) ; w0 . minus ( output , T_v0 ) ; wu = w0 . dot ( u ) ; wv = w0 . dot ( v ) ; D = uv * uv - uu * vv ; // get and test parametric coords double s , t ; s = ( uv * wv - vv * wu ) / D ; if ( s < 0.0 || s > 1.0 ) // I is outside T return false ; t = ( uv * wu - uu * wv ) / D ; return ! ( t < 0.0 ) && ! ( ( s + t ) > 1.0 ) ; // I is outside T }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the point is contained inside the box . The point is considered to be inside the box if the following test passes for each dimension . box . x &le ; point . x { @code < } box . x + box . lengthX [CODESPLIT] public static boolean contained ( BoxLength3D_F64 box , Point3D_F64 point ) { return ( box . p . x <= point . x && point . x < box . p . x + box . lengthX && box . p . y <= point . y && point . y < box . p . y + box . lengthY && box . p . z <= point . z && point . z < box . p . z + box . lengthZ ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns true if the point is contained inside the box with an exclusive upper extent . The point is considered to be inside the box if the following test passes : <br > box . p0 . x &le ; point . x { @code < } box . p1 . x<br > box . p0 . y &le ; point . y { @code < } box . p1 . y<br > box . p0 . z &le ; point . z { @code < } box . p1 . z<br > < / p > [CODESPLIT] public static boolean contained ( Box3D_F64 box , Point3D_F64 point ) { return ( box . p0 . x <= point . x && point . x < box . p1 . x && box . p0 . y <= point . y && point . y < box . p1 . y && box . p0 . z <= point . z && point . z < box . p1 . z ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the intersection of a line and sphere . There can be 0 1 or 2 intersections . If there is 1 intersection the same point is returned twice . [CODESPLIT] public static boolean intersect ( LineParametric3D_F64 line , Sphere3D_F64 sphere , Point3D_F64 a , Point3D_F64 b ) { // this equation was found by solving for l: // ||(P + V*l) - X0|| == r double r2 = sphere . radius * sphere . radius ; double PP = GeometryMath_F64 . dot ( line . p , line . p ) ; double PV = GeometryMath_F64 . dot ( line . p , line . slope ) ; double PX = GeometryMath_F64 . dot ( line . p , sphere . center ) ; double VV = GeometryMath_F64 . dot ( line . slope , line . slope ) ; double VX = GeometryMath_F64 . dot ( line . slope , sphere . center ) ; double XX = GeometryMath_F64 . dot ( sphere . center , sphere . center ) ; // Coefficients in the quadratic equation double A = VV ; double B = 2.0 * ( PV - VX ) ; double C = PP + XX - 2.0 * PX - r2 ; // solve for the quadratic equation double inner = B * B - 4.0 * A * C ; if ( inner < 0 ) return false ; double sqrt = Math . sqrt ( inner ) ; double t0 = ( - B + sqrt ) / ( 2.0 * A ) ; double t1 = ( - B - sqrt ) / ( 2.0 * A ) ; line . setPointOnLine ( t0 , a ) ; line . setPointOnLine ( t1 , b ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform linear interpolation [CODESPLIT] public static void interpolate ( Se2_F64 a , Se2_F64 b , double where , Se2_F64 output ) { double w0 = 1.0 - where ; output . T . x = a . T . x * w0 + b . T . x * where ; output . T . y = a . T . y * w0 + b . T . y * where ; // interpolating rotation is more difficult // This only works well if the difference between the two angles is small double yaw0 = a . getYaw ( ) ; double yaw1 = b . getYaw ( ) ; double cw = UtilAngle . distanceCW ( yaw0 , yaw1 ) ; double ccw = UtilAngle . distanceCCW ( yaw0 , yaw1 ) ; double yaw ; if ( cw > ccw ) { yaw = yaw0 + ccw * where ; } else { yaw = yaw0 - cw * where ; } output . setYaw ( yaw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The unit eigenvector corresponding to the maximum eigenvalue of Q is the rotation parameterized as a quaternion . [CODESPLIT] private void extractQuaternionFromQ ( SimpleMatrix q ) { SimpleEVD < SimpleMatrix > evd = q . eig ( ) ; int indexMax = evd . getIndexMax ( ) ; SimpleMatrix v_max = evd . getEigenVector ( indexMax ) ; quat . w = ( double ) v_max . get ( 0 ) ; quat . x = ( double ) v_max . get ( 1 ) ; quat . y = ( double ) v_max . get ( 2 ) ; quat . z = ( double ) v_max . get ( 3 ) ; quat . normalize ( ) ; ConvertRotation3D_F64 . quaternionToMatrix ( quat , motion . getR ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the convex hull . The output will be in counter - clockwise order . [CODESPLIT] public void process ( Point2D_F64 [ ] input , int length , Polygon2D_F64 hull ) { // ahdnle special cases if ( length == 2 ) { hull . vertexes . resize ( length ) ; for ( int i = 0 ; i < length ; i ++ ) { hull . get ( i ) . set ( input [ i ] ) ; } return ; } sorter . sort ( input , length ) ; work . reset ( ) ; // construct the lower hull for ( int i = 0 ; i < length ; i ++ ) { Point2D_F64 p = input [ i ] ; //Contains at least 2 points and the last two points and 'p' do not make a counter-clockwise turn while ( work . size ( ) >= 2 && subtractThenCross ( p , work . getTail ( 0 ) , work . getTail ( 1 ) ) >= 0 ) { // remove the last points from the hull work . removeTail ( ) ; } // append p to the end work . add ( p ) ; } work . removeTail ( ) ; int minSize = work . size + 2 ; // construct upper hull for ( int i = length - 1 ; i >= 0 ; i -- ) // Finding top layer from hull { //Contains at least 2 points and the last two points and 'p' do not make a counter-clockwise turn Point2D_F64 p = input [ i ] ; while ( work . size ( ) >= minSize && subtractThenCross ( p , work . getTail ( 0 ) , work . getTail ( 1 ) ) >= 0 ) { work . removeTail ( ) ; } // append p to the end work . add ( p ) ; } work . removeTail ( ) ; // create a copy for the output // the work buffer contains references to the input points, but to be safe the output should have its // own instances hull . vertexes . resize ( work . size ) ; for ( int i = 0 ; i < work . size ( ) ; i ++ ) { hull . vertexes . data [ i ] . set ( work . get ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the following operation : output = z - component [ ( a - b ) cross ( a - c ) ] [CODESPLIT] private static double subtractThenCross ( Point2D_F64 a , Point2D_F64 b , Point2D_F64 c ) { double x0 = b . x - a . x ; double y0 = b . y - a . y ; double x1 = c . x - a . x ; double y1 = c . y - a . y ; return x0 * y1 - y0 * x1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the covariance matrix . Q = [ a11 a12 ; a12 a22 ] [CODESPLIT] public boolean setCovariance ( double a11 , double a12 , double a22 ) { Q . data [ 0 ] = a11 ; Q . data [ 1 ] = a12 ; Q . data [ 2 ] = a12 ; Q . data [ 3 ] = a22 ; if ( ! eigen . decompose ( Q ) ) { System . err . println ( \"Eigenvalue decomposition failed!\" ) ; return false ; } Complex_F64 v0 = eigen . getEigenvalue ( 0 ) ; Complex_F64 v1 = eigen . getEigenvalue ( 1 ) ; DMatrixRMaj a0 , a1 ; if ( v0 . getMagnitude2 ( ) > v1 . getMagnitude2 ( ) ) { a0 = eigen . getEigenVector ( 0 ) ; a1 = eigen . getEigenVector ( 1 ) ; lengthX = ( double ) v0 . getMagnitude ( ) ; lengthY = ( double ) v1 . getMagnitude ( ) ; } else { a0 = eigen . getEigenVector ( 1 ) ; a1 = eigen . getEigenVector ( 0 ) ; lengthX = ( double ) v1 . getMagnitude ( ) ; lengthY = ( double ) v0 . getMagnitude ( ) ; } if ( a0 == null || a1 == null ) { System . err . println ( \"Complex eigenvalues: \" + v0 + \"  \" + v1 ) ; return false ; } lengthX = Math . sqrt ( lengthX ) ; lengthY = Math . sqrt ( lengthY ) ; x . set ( ( double ) a0 . get ( 0 ) , ( double ) a0 . get ( 1 ) ) ; y . set ( ( double ) a1 . get ( 0 ) , ( double ) a1 . get ( 1 ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the provided transform so that it does not transform any points . [CODESPLIT] public static void setToNoMotion ( Se3_F64 se ) { CommonOps_DDRM . setIdentity ( se . getR ( ) ) ; se . getT ( ) . set ( 0 , 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts { [CODESPLIT] public static Affine2D_F64 toAffine ( Se2_F64 se , Affine2D_F64 affine ) { if ( affine == null ) affine = new Affine2D_F64 ( ) ; affine . a11 = se . c ; affine . a12 = - se . s ; affine . a21 = se . s ; affine . a22 = se . c ; affine . tx = se . T . x ; affine . ty = se . T . y ; return affine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts it into a 4 by 4 homogeneous matrix . [CODESPLIT] public static DMatrixRMaj toHomogeneous ( Se3_F64 se , DMatrixRMaj ret ) { if ( ret == null ) ret = new DMatrixRMaj ( 4 , 4 ) ; else { ret . set ( 3 , 0 , 0 ) ; ret . set ( 3 , 1 , 0 ) ; ret . set ( 3 , 2 , 0 ) ; } CommonOps_DDRM . insert ( se . getR ( ) , ret , 0 , 0 ) ; Vector3D_F64 T = se . getT ( ) ; ret . set ( 0 , 3 , T . x ) ; ret . set ( 1 , 3 , T . y ) ; ret . set ( 2 , 3 , T . z ) ; ret . set ( 3 , 3 , 1 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a homogeneous representation into { @link Se3_F64 } . [CODESPLIT] public static Se3_F64 toSe3 ( DMatrixRMaj H , Se3_F64 ret ) { if ( H . numCols != 4 || H . numRows != 4 ) throw new IllegalArgumentException ( \"The homogeneous matrix must be 4 by 4 by definition.\" ) ; if ( ret == null ) ret = new Se3_F64 ( ) ; ret . setTranslation ( ( double ) H . get ( 0 , 3 ) , ( double ) H . get ( 1 , 3 ) , ( double ) H . get ( 2 , 3 ) ) ; CommonOps_DDRM . extract ( H , 0 , 3 , 0 , 3 , ret . getR ( ) , 0 , 0 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts it into a 3 by 3 homogeneous matrix . [CODESPLIT] public static DMatrixRMaj toHomogeneous ( Se2_F64 se , DMatrixRMaj ret ) { if ( ret == null ) ret = new DMatrixRMaj ( 3 , 3 ) ; else { ret . set ( 2 , 0 , 0 ) ; ret . set ( 2 , 1 , 0 ) ; } final double c = se . getCosineYaw ( ) ; final double s = se . getSineYaw ( ) ; ret . set ( 0 , 0 , c ) ; ret . set ( 0 , 1 , - s ) ; ret . set ( 1 , 0 , s ) ; ret . set ( 1 , 1 , c ) ; ret . set ( 0 , 2 , se . getX ( ) ) ; ret . set ( 1 , 2 , se . getY ( ) ) ; ret . set ( 2 , 2 , 1 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a homogeneous representation into { @link Se2_F64 } . [CODESPLIT] public static Se2_F64 toSe2 ( DMatrixRMaj H , Se2_F64 ret ) { if ( H . numCols != 3 || H . numRows != 3 ) throw new IllegalArgumentException ( \"The homogeneous matrix must be 3 by 3 by definition.\" ) ; if ( ret == null ) ret = new Se2_F64 ( ) ; ret . setTranslation ( ( double ) H . get ( 0 , 2 ) , ( double ) H . get ( 1 , 2 ) ) ; double c = ( double ) H . get ( 0 , 0 ) ; double s = ( double ) H . get ( 1 , 0 ) ; ret . setYaw ( Math . atan2 ( s , c ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of an { @link Se3_F64 } using Euler XYZ coordinates for the rotation and a translation vector . [CODESPLIT] public static Se3_F64 eulerXyz ( double dx , double dy , double dz , double rotX , double rotY , double rotZ , Se3_F64 se ) { return eulerXyz ( dx , dy , dz , EulerType . XYZ , rotX , rotY , rotZ , se ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create SE3 using axis - angle for rotation and XYZ tanslation [CODESPLIT] public static Se3_F64 axisXyz ( double dx , double dy , double dz , double rotX , double rotY , double rotZ , Se3_F64 se ) { if ( se == null ) se = new Se3_F64 ( ) ; double theta = Math . sqrt ( rotX * rotX + rotY + rotY + rotZ * rotZ ) ; if ( theta == 0 ) { CommonOps_DDRM . setIdentity ( se . R ) ; } else { ConvertRotation3D_F64 . rodriguesToMatrix ( rotX / theta , rotY / theta , rotZ / theta , theta , se . getR ( ) ) ; } Vector3D_F64 T = se . getT ( ) ; T . x = dx ; T . y = dy ; T . z = dz ; return se ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Can be used to see if two transforms are identical to within tolerance [CODESPLIT] public static boolean isIdentical ( Se3_F64 a , Se3_F64 b , double tolT , double tolR ) { if ( Math . abs ( a . T . x - b . T . x ) > tolT ) return false ; if ( Math . abs ( a . T . y - b . T . y ) > tolT ) return false ; if ( Math . abs ( a . T . z - b . T . z ) > tolT ) return false ; DMatrixRMaj D = new DMatrixRMaj ( 3 , 3 ) ; CommonOps_DDRM . multTransA ( a . R , b . R , D ) ; Rodrigues_F64 rod = new Rodrigues_F64 ( ) ; ConvertRotation3D_F64 . matrixToRodrigues ( D , rod ) ; return rod . theta <= tolR ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the best fit projection of a onto SE ( 3 ) . This is useful when a was estimated using a linear algorithm . [CODESPLIT] public static boolean bestFit ( Se3_F64 a ) { SingularValueDecomposition_F64 < DMatrixRMaj > svd = DecompositionFactory_DDRM . svd ( true , true , true ) ; if ( ! svd . decompose ( a . R ) ) throw new RuntimeException ( \"SVD Failed\" ) ; CommonOps_DDRM . multTransB ( svd . getU ( null , false ) , svd . getV ( null , false ) , a . R ) ; // determinant should be +1 double det = CommonOps_DDRM . det ( a . R ) ; if ( det < 0 ) { CommonOps_DDRM . scale ( - 1 , a . R ) ; } // compute the determinant of the singular matrix double b = 1.0 ; double s [ ] = svd . getSingularValues ( ) ; for ( int i = 0 ; i < svd . numberOfSingularValues ( ) ; i ++ ) { b *= s [ i ] ; } b = Math . signum ( det ) / Math . pow ( b , 1.0 / 3.0 ) ; GeometryMath_F64 . scale ( a . T , b ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the distance the closest point on a line segment is from the specified point . The closest point is bounded to be along the line segment . < / p > [CODESPLIT] public static double distance ( LineSegment2D_I32 line , Point2D_I32 p ) { int a = line . b . x - line . a . x ; int b = line . b . y - line . a . y ; double t = a * ( p . x - line . a . x ) + b * ( p . y - line . a . y ) ; t /= ( a * a + b * b ) ; // if the point of intersection is past the end points return the distance // from the closest end point if ( t < 0 ) { return UtilPoint2D_I32 . distance ( line . a . x , line . a . y , p . x , p . y ) ; } else if ( t > 1.0 ) return UtilPoint2D_I32 . distance ( line . b . x , line . b . y , p . x , p . y ) ; // return the distance of the closest point on the line return UtilPoint2D_F64 . distance ( line . a . x + t * a , line . a . y + t * b , p . x , p . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the distance of a point to the closest point on a line . < / p > [CODESPLIT] public static double distance ( LineParametric2D_I32 line , Point2D_I32 p ) { int a = line . slopeX ; int b = line . slopeY ; double t = a * ( p . x - line . p . x ) + b * ( p . y - line . p . y ) ; t /= ( a * a + b * b ) ; // return the distance of the closest point on the line return UtilPoint2D_F64 . distance ( line . p . x + t * a , line . p . y + t * b , p . x , p . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts latitude and longitude coordinates into a unit vector [CODESPLIT] public static < T extends GeoTuple3D_F64 < T > > T latlonToUnitVector ( double lat , double lon , T vector ) { if ( vector == null ) vector = ( T ) new Vector3D_F64 ( ) ; vector . x = Math . cos ( lat ) * Math . cos ( lon ) ; vector . y = Math . cos ( lat ) * Math . sin ( lon ) ; vector . z = - Math . sin ( lat ) ; return vector ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes ( x - x_c ) ** 2 + ( y - y_c ) ** 2 - r . If ( x y ) lies on the circle then it should be 0 . [CODESPLIT] public static double evaluate ( double x , double y , Circle2D_F64 circle ) { x -= circle . center . x ; y -= circle . center . y ; return x * x + y * y - circle . radius * circle . radius ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given three points find the circle that intersects all three . If false is returned that means the points all lie along a line and there is no circle . [CODESPLIT] public static boolean circle ( Point2D_F64 x0 , Point2D_F64 x1 , Point2D_F64 x2 , Circle2D_F64 circle ) { // points that lie on line a and b double xa = ( x0 . x + x1 . x ) / 2.0 ; double ya = ( x0 . y + x1 . y ) / 2.0 ; double xb = ( x1 . x + x2 . x ) / 2.0 ; double yb = ( x1 . y + x2 . y ) / 2.0 ; // slopes of lines a and b double m2 = x0 . x - x1 . x ; double m1 = x1 . y - x0 . y ; double n2 = x2 . x - x1 . x ; double n1 = x1 . y - x2 . y ; // find the intersection of the lines double bottom = m2 * n1 - n2 * m1 ; if ( bottom == 0 ) return false ; double alpha = ( - m2 * ( xb - xa ) + m1 * ( yb - ya ) ) / bottom ; circle . center . x = xb + n1 * alpha ; circle . center . y = yb + n2 * alpha ; circle . radius = circle . center . distance ( x0 ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Radius squares of the circle that passes through these three points . [CODESPLIT] public static double circleRadiusSq ( Point2D_F64 x0 , Point2D_F64 x1 , Point2D_F64 x2 ) { // points that lie on line a and b double xa = ( x0 . x + x1 . x ) / 2.0 ; double ya = ( x0 . y + x1 . y ) / 2.0 ; double xb = ( x1 . x + x2 . x ) / 2.0 ; double yb = ( x1 . y + x2 . y ) / 2.0 ; // slopes of lines a and b double m2 = x0 . x - x1 . x ; double m1 = x1 . y - x0 . y ; double n2 = x2 . x - x1 . x ; double n1 = x1 . y - x2 . y ; // find the intersection of the lines double bottom = m2 * n1 - n2 * m1 ; if ( bottom == 0 ) return Double . NaN ; double alpha = ( - m2 * ( xb - xa ) + m1 * ( yb - ya ) ) / bottom ; double dx = xb + n1 * alpha - x0 . x ; double dy = yb + n2 * alpha - x0 . y ; return dx * dx + dy * dy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the point which minimizes the distance between the two lines in 3D . If the two lines are parallel the result is undefined . [CODESPLIT] public static Point3D_F64 closestPoint ( LineParametric3D_F64 l0 , LineParametric3D_F64 l1 , Point3D_F64 ret ) { if ( ret == null ) { ret = new Point3D_F64 ( ) ; } ret . x = l0 . p . x - l1 . p . x ; ret . y = l0 . p . y - l1 . p . y ; ret . z = l0 . p . z - l1 . p . z ; // this solution is from: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/ double dv01v1 = MiscOps . dot ( ret , l1 . slope ) ; double dv1v0 = MiscOps . dot ( l1 . slope , l0 . slope ) ; double dv1v1 = MiscOps . dot ( l1 . slope , l1 . slope ) ; double t0 = dv01v1 * dv1v0 - MiscOps . dot ( ret , l0 . slope ) * dv1v1 ; double bottom = MiscOps . dot ( l0 . slope , l0 . slope ) * dv1v1 - dv1v0 * dv1v0 ; if ( bottom == 0 ) return null ; t0 /= bottom ; // ( d1343 + mua d4321 ) / d4343 double t1 = ( dv01v1 + t0 * dv1v0 ) / dv1v1 ; ret . x = ( double ) 0.5 * ( ( l0 . p . x + t0 * l0 . slope . x ) + ( l1 . p . x + t1 * l1 . slope . x ) ) ; ret . y = ( double ) 0.5 * ( ( l0 . p . y + t0 * l0 . slope . y ) + ( l1 . p . y + t1 * l1 . slope . y ) ) ; ret . z = ( double ) 0.5 * ( ( l0 . p . z + t0 * l0 . slope . z ) + ( l1 . p . z + t1 * l1 . slope . z ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the closest point on line lo to l1 and on l1 to l0 . The solution is returned in param as a value of t for each line . < / p > <p > point on l0 = l0 . a + param [ 0 ] * l0 . slope<br > point on l1 = l1 . a + param [ 1 ] * l1 . slope < / p > @param l0 first line . Not modified . @param l1 second line . Not modified . @param param param [ 0 ] for line0 location and param [ 1 ] for line1 location . [CODESPLIT] public static boolean closestPoints ( LineParametric3D_F64 l0 , LineParametric3D_F64 l1 , double param [ ] ) { double dX = l0 . p . x - l1 . p . x ; double dY = l0 . p . y - l1 . p . y ; double dZ = l0 . p . z - l1 . p . z ; // this solution is from: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/ double dv01v1 = MiscOps . dot ( dX , dY , dZ , l1 . slope ) ; double dv1v0 = MiscOps . dot ( l1 . slope , l0 . slope ) ; double dv1v1 = MiscOps . dot ( l1 . slope , l1 . slope ) ; double t0 = dv01v1 * dv1v0 - MiscOps . dot ( dX , dY , dZ , l0 . slope ) * dv1v1 ; double bottom = MiscOps . dot ( l0 . slope , l0 . slope ) * dv1v1 - dv1v0 * dv1v0 ; if ( bottom == 0 ) return false ; t0 /= bottom ; // ( d1343 + mua d4321 ) / d4343 double t1 = ( dv01v1 + t0 * dv1v0 ) / dv1v1 ; param [ 0 ] = t0 ; param [ 1 ] = t1 ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the closest point on a line to the specified point . [CODESPLIT] public static Point3D_F64 closestPoint ( LineParametric3D_F64 line , Point3D_F64 pt , Point3D_F64 ret ) { if ( ret == null ) { ret = new Point3D_F64 ( ) ; } double dx = pt . x - line . p . x ; double dy = pt . y - line . p . y ; double dz = pt . z - line . p . z ; double n2 = line . slope . normSq ( ) ; double d = ( line . slope . x * dx + line . slope . y * dy + line . slope . z * dz ) ; ret . x = line . p . x + d * line . slope . x / n2 ; ret . y = line . p . y + d * line . slope . y / n2 ; ret . z = line . p . z + d * line . slope . z / n2 ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the closest point on a line to the specified point as a function of distance along the line . The 3D coordinate of the point at d the returned value is P = ( x y z ) + ( slope . x slope . y slope . z ) * d . [CODESPLIT] public static double closestPoint ( LineParametric3D_F64 line , Point3D_F64 pt ) { double dx = pt . x - line . p . x ; double dy = pt . y - line . p . y ; double dz = pt . z - line . p . z ; return ( line . slope . x * dx + line . slope . y * dy + line . slope . z * dz ) / line . slope . normSq ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the closest point on the plane to the specified point . [CODESPLIT] public static Point3D_F64 closestPoint ( PlaneNormal3D_F64 plane , Point3D_F64 point , Point3D_F64 found ) { if ( found == null ) found = new Point3D_F64 ( ) ; double A = plane . n . x ; double B = plane . n . y ; double C = plane . n . z ; double D = plane . n . x * plane . p . x + plane . n . y * plane . p . y + plane . n . z * plane . p . z ; double top = A * point . x + B * point . y + C * point . z - D ; double n2 = A * A + B * B + C * C ; found . x = point . x - A * top / n2 ; found . y = point . y - B * top / n2 ; found . z = point . z - C * top / n2 ; return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the closest point on the plane to the specified point . [CODESPLIT] public static Point3D_F64 closestPoint ( PlaneGeneral3D_F64 plane , Point3D_F64 point , Point3D_F64 found ) { if ( found == null ) found = new Point3D_F64 ( ) ; double top = plane . A * point . x + plane . B * point . y + plane . C * point . z - plane . D ; double n2 = plane . A * plane . A + plane . B * plane . B + plane . C * plane . C ; found . x = point . x - plane . A * top / n2 ; found . y = point . y - plane . B * top / n2 ; found . z = point . z - plane . C * top / n2 ; return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the closest point on the plane to the origin . [CODESPLIT] public static Point3D_F64 closestPointOrigin ( PlaneGeneral3D_F64 plane , Point3D_F64 found ) { if ( found == null ) found = new Point3D_F64 ( ) ; double n2 = plane . A * plane . A + plane . B * plane . B + plane . C * plane . C ; found . x = plane . A * plane . D / n2 ; found . y = plane . B * plane . D / n2 ; found . z = plane . C * plane . D / n2 ; return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the closest point on a line segment to the specified point . [CODESPLIT] public static Point3D_F64 closestPoint ( LineSegment3D_F64 line , Point3D_F64 pt , Point3D_F64 ret ) { if ( ret == null ) { ret = new Point3D_F64 ( ) ; } double dx = pt . x - line . a . x ; double dy = pt . y - line . a . y ; double dz = pt . z - line . a . z ; double slope_x = line . b . x - line . a . x ; double slope_y = line . b . y - line . a . y ; double slope_z = line . b . z - line . a . z ; double n = ( double ) Math . sqrt ( slope_x * slope_x + slope_y * slope_y + slope_z * slope_z ) ; double d = ( slope_x * dx + slope_y * dy + slope_z * dz ) / n ; // if it is past the end points just return one of the end points if ( d <= 0 ) { ret . set ( line . a ) ; } else if ( d >= n ) { ret . set ( line . b ) ; } else { ret . x = line . a . x + d * slope_x / n ; ret . y = line . a . y + d * slope_y / n ; ret . z = line . a . z + d * slope_z / n ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the point which minimizes its distance from the two line segments . [CODESPLIT] public static Point3D_F64 closestPoint ( LineSegment3D_F64 l0 , LineSegment3D_F64 l1 , Point3D_F64 ret ) { if ( ret == null ) { ret = new Point3D_F64 ( ) ; } ret . x = l0 . a . x - l1 . a . x ; ret . y = l0 . a . y - l1 . a . y ; ret . z = l0 . a . z - l1 . a . z ; double slope0_x = l0 . b . x - l0 . a . x ; double slope0_y = l0 . b . y - l0 . a . y ; double slope0_z = l0 . b . z - l0 . a . z ; double slope1_x = l1 . b . x - l1 . a . x ; double slope1_y = l1 . b . y - l1 . a . y ; double slope1_z = l1 . b . z - l1 . a . z ; // normalize the slopes for easier math double n0 = ( double ) Math . sqrt ( slope0_x * slope0_x + slope0_y * slope0_y + slope0_z * slope0_z ) ; double n1 = ( double ) Math . sqrt ( slope1_x * slope1_x + slope1_y * slope1_y + slope1_z * slope1_z ) ; slope0_x /= n0 ; slope0_y /= n0 ; slope0_z /= n0 ; slope1_x /= n1 ; slope1_y /= n1 ; slope1_z /= n1 ; // this solution is from: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/ double dv01v1 = ret . x * slope1_x + ret . y * slope1_y + ret . z * slope1_z ; double dv01v0 = ret . x * slope0_x + ret . y * slope0_y + ret . z * slope0_z ; double dv1v0 = slope1_x * slope0_x + slope1_y * slope0_y + slope1_z * slope0_z ; double t0 = dv01v1 * dv1v0 - dv01v0 ; double bottom = 1 - dv1v0 * dv1v0 ; if ( bottom == 0 ) return null ; t0 /= bottom ; // restrict it to be on the line if ( t0 < 0 ) return closestPoint ( l1 , l0 . a , ret ) ; if ( t0 > 1 ) return closestPoint ( l1 , l0 . b , ret ) ; // ( d1343 + mua d4321 ) / d4343 double t1 = ( dv01v1 + t0 * dv1v0 ) ; if ( t1 < 0 ) return closestPoint ( l0 , l1 . a , ret ) ; if ( t1 > 1 ) return closestPoint ( l0 , l1 . b , ret ) ; ret . x = ( double ) 0.5 * ( ( l0 . a . x + t0 * slope0_x ) + ( l1 . a . x + t1 * slope1_x ) ) ; ret . y = ( double ) 0.5 * ( ( l0 . a . y + t0 * slope0_y ) + ( l1 . a . y + t1 * slope1_y ) ) ; ret . z = ( double ) 0.5 * ( ( l0 . a . z + t0 * slope0_z ) + ( l1 . a . z + t1 * slope1_z ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closest point from a 3D triangle to a point . [CODESPLIT] public static Point3D_F64 closestPoint ( Point3D_F64 vertexA , Point3D_F64 vertexB , Point3D_F64 vertexC , Point3D_F64 point , Point3D_F64 ret ) { if ( ret == null ) { ret = new Point3D_F64 ( ) ; } DistancePointTriangle3D_F64 alg = new DistancePointTriangle3D_F64 ( ) ; alg . setTriangle ( vertexA , vertexB , vertexC ) ; alg . closestPoint ( point , ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the closest point along the line to the plane as a function of t : <br > [ x y z ] = [ x_0 y_0 z_0 ] + t· [ slopeX slopeY slopZ ] < / p > [CODESPLIT] public static double closestPointT ( LineParametric3D_F64 line , PlaneNormal3D_F64 plane ) { double dx = plane . p . x - line . p . x ; double dy = plane . p . y - line . p . y ; double dz = plane . p . z - line . p . z ; double top = dx * plane . n . x + dy * plane . n . y + dz * plane . n . z ; double bottom = line . slope . dot ( plane . n ) ; if ( bottom == 0 ) return Double . NaN ; return top / bottom ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a 2D homography transform to the point and stores the results in another variable . b = H * a where a is the input / orig point b is the output / result point and H is a homography from a to b . [CODESPLIT] public static Point2D_F64 transform ( Homography2D_F64 H , Point2D_F64 orig , Point2D_F64 result ) { if ( result == null ) { result = new Point2D_F64 ( ) ; } // copy the values so that no errors happen if orig and result are the same instance double x = orig . x ; double y = orig . y ; double z = H . a31 * x + H . a32 * y + H . a33 ; result . x = ( H . a11 * x + H . a12 * y + H . a13 ) / z ; result . y = ( H . a21 * x + H . a22 * y + H . a23 ) / z ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a 2D special euclidean transform to the point and stores the results in another variable . [CODESPLIT] public static Point2D_F64 transform ( Se2_F64 se , Point2D_F64 orig , Point2D_F64 result ) { if ( result == null ) { result = new Point2D_F64 ( ) ; } final double c = se . getCosineYaw ( ) ; final double s = se . getSineYaw ( ) ; // copy the values so that no errors happen if orig and result are the same instance double x = orig . x ; double y = orig . y ; result . x = se . getX ( ) + x * c - y * s ; result . y = se . getY ( ) + x * s + y * c ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a 2D special euclidean transform to an array of points . [CODESPLIT] public static void transform ( Se2_F64 se , Point2D_F64 points [ ] , int length ) { double tranX = se . getX ( ) ; double tranY = se . getY ( ) ; final double c = se . getCosineYaw ( ) ; final double s = se . getSineYaw ( ) ; for ( int i = 0 ; i < length ; i ++ ) { Point2D_F64 pt = points [ i ] ; double x = pt . x ; double y = pt . y ; pt . x = tranX + x * c - y * s ; pt . y = tranY + x * s + y * c ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a 3D special euclidean transform to a list of points . [CODESPLIT] public static void transform ( Se3_F64 se , Point3D_F64 [ ] points , int start , int length ) { for ( int i = 0 ; i < length ; i ++ ) { Point3D_F64 p = points [ i + start ] ; transform ( se , p , p ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a 3D special euclidean transform to a list of points . [CODESPLIT] public static void transform ( Se3_F64 se , List < Point3D_F64 > points ) { for ( Point3D_F64 p : points ) { transform ( se , p , p ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > . Applies the transform specified by SpecialEuclidean to a point . <br > <br > p = R * p + T < / p > <p > Both origPt and tranPt can be the same instance . < / p > [CODESPLIT] public static Point3D_F64 transform ( Se3_F64 se , Point3D_F64 origPt , Point3D_F64 tranPt ) { if ( tranPt == null ) tranPt = new Point3D_F64 ( ) ; DMatrixRMaj R = se . getR ( ) ; Vector3D_F64 T = se . getT ( ) ; GeometryMath_F64 . mult ( R , origPt , tranPt ) ; GeometryMath_F64 . add ( tranPt , T , tranPt ) ; return tranPt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > . Applies the transform specified by SpecialEuclidean to a homogenous point . <br > <br > p = [ R t ] * p < / p > <p > Both origPt and tranPt can be the same instance . < / p > [CODESPLIT] public static Point3D_F64 transform ( Se3_F64 se , Point4D_F64 origPt , Point3D_F64 tranPt ) { if ( tranPt == null ) tranPt = new Point3D_F64 ( ) ; DMatrixRMaj R = se . getR ( ) ; Vector3D_F64 T = se . getT ( ) ; double P11 = R . data [ 0 ] , P12 = R . data [ 1 ] , P13 = R . data [ 2 ] , P14 = T . x ; double P21 = R . data [ 3 ] , P22 = R . data [ 4 ] , P23 = R . data [ 5 ] , P24 = T . y ; double P31 = R . data [ 6 ] , P32 = R . data [ 7 ] , P33 = R . data [ 8 ] , P34 = T . z ; tranPt . x = P11 * origPt . x + P12 * origPt . y + P13 * origPt . z + P14 * origPt . w ; tranPt . y = P21 * origPt . x + P22 * origPt . y + P23 * origPt . z + P24 * origPt . w ; tranPt . z = P31 * origPt . x + P32 * origPt . y + P33 * origPt . z + P34 * origPt . w ; return tranPt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > . Applies the transform in the reverse direction<br > <br > p = R<sup > T< / sup > * ( p - T ) < / p > <p > Both origPt and tranPt can be the same instance . < / p > [CODESPLIT] public static Point3D_F64 transformReverse ( Se3_F64 se , Point3D_F64 origPt , Point3D_F64 tranPt ) { if ( tranPt == null ) tranPt = new Point3D_F64 ( ) ; DMatrixRMaj R = se . getR ( ) ; Vector3D_F64 T = se . getT ( ) ; GeometryMath_F64 . sub ( origPt , T , tranPt ) ; GeometryMath_F64 . multTran ( R , tranPt , tranPt ) ; return tranPt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the polygon into a list . [CODESPLIT] public List < Point2D_F64 > convert ( @ Nullable List < Point2D_F64 > storage , boolean copy ) { if ( storage == null ) storage = new ArrayList <> ( ) ; else storage . clear ( ) ; if ( copy ) { for ( int i = 0 ; i < 4 ; i ++ ) { storage . add ( get ( i ) . copy ( ) ) ; } } else { for ( int i = 0 ; i < 4 ; i ++ ) { storage . add ( get ( i ) ) ; } } return storage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the polygon to be the same as the list . A true copy is created and no references to points in the list are saved . [CODESPLIT] public void set ( List < Point2D_F64 > list ) { if ( list . size ( ) != 4 ) throw new IllegalArgumentException ( \"List must have size of 4\" ) ; a . set ( list . get ( 0 ) ) ; b . set ( list . get ( 1 ) ) ; c . set ( list . get ( 2 ) ) ; d . set ( list . get ( 3 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the two quadrilaterals are equal to each other to within tolerance . Equality is defined by seeing if the distance between two equivalent vertexes is within tolerance . [CODESPLIT] public boolean isEquals ( Quadrilateral_F64 quad , double tol ) { tol *= tol ; if ( a . distance2 ( quad . a ) > tol ) return false ; if ( b . distance2 ( quad . b ) > tol ) return false ; if ( c . distance2 ( quad . c ) > tol ) return false ; return d . distance2 ( quad . d ) <= tol ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the acute angle between the slope of two lines . Lines do not need to ever intersect . Found using the dot product . [CODESPLIT] public static double acuteAngle ( LineGeneral2D_F64 a , LineGeneral2D_F64 b ) { double la = Math . sqrt ( a . A * a . A + a . B * a . B ) ; double lb = Math . sqrt ( b . A * b . A + b . B * b . B ) ; // numerical round off error can cause it to be barely greater than 1, which is outside the allowed // domain of acos() double value = ( a . A * b . A + a . B * b . B ) / ( la * lb ) ; if ( value < - 1.0 ) value = - 1.0 ; else if ( value > 1.0 ) value = 1.0 ; return Math . acos ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the acute angle between the slope of two lines and assumes that the lines have been normalized such that A * A + B * B = 1 . This avoids the need to compute the square root twice . Lines do not need to ever intersect . Found using the dot product . [CODESPLIT] public static double acuteAngleN ( LineGeneral2D_F64 a , LineGeneral2D_F64 b ) { double value = a . A * b . A + a . B * b . B ; if ( value < - 1.0 ) value = - 1.0 ; else if ( value > 1.0 ) value = 1.0 ; return Math . acos ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line from polar form to parametric . [CODESPLIT] public static LineParametric2D_F64 convert ( LinePolar2D_F64 src , LineParametric2D_F64 ret ) { if ( ret == null ) ret = new LineParametric2D_F64 ( ) ; double c = ( double ) Math . cos ( src . angle ) ; double s = ( double ) Math . sin ( src . angle ) ; ret . p . set ( c * src . distance , s * src . distance ) ; ret . slope . set ( - s , c ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line from polar form to general . After conversion the line will be normalized e . g . A * A + B * B == 1 . [CODESPLIT] public static LineGeneral2D_F64 convert ( LinePolar2D_F64 src , LineGeneral2D_F64 ret ) { if ( ret == null ) ret = new LineGeneral2D_F64 ( ) ; double c = ( double ) Math . cos ( src . angle ) ; double s = ( double ) Math . sin ( src . angle ) ; ret . A = c ; ret . B = s ; ret . C = - src . distance ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line from general to polar . [CODESPLIT] public static LinePolar2D_F64 convert ( LineGeneral2D_F64 src , LinePolar2D_F64 ret ) { if ( ret == null ) ret = new LinePolar2D_F64 ( ) ; double r = Math . sqrt ( src . A * src . A + src . B * src . B ) ; double sign = src . C < 0 ? - 1 : 1 ; ret . angle = Math . atan2 ( - sign * src . B / r , - sign * src . A / r ) ; ret . distance = sign * src . C / r ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line segment into a parametric line . The start point will be src . a and the direction will be in the direction of src . b - src . a [CODESPLIT] public static LineParametric2D_F64 convert ( LineSegment2D_F64 src , LineParametric2D_F64 ret ) { if ( ret == null ) ret = new LineParametric2D_F64 ( ) ; ret . p . set ( src . a ) ; ret . slope . set ( src . slopeX ( ) , src . slopeY ( ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line segment into a general line . [CODESPLIT] public static LineGeneral2D_F64 convert ( LineSegment2D_F64 src , LineGeneral2D_F64 ret ) { return convert ( src . a , src . b , ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line segment into a general line . Line segment is defined by two points . [CODESPLIT] public static LineGeneral2D_F64 convert ( Point2D_F64 a , Point2D_F64 b , LineGeneral2D_F64 ret ) { if ( ret == null ) ret = new LineGeneral2D_F64 ( ) ; ret . A = a . y - b . y ; ret . B = b . x - a . x ; ret . C = - ( ret . A * a . x + ret . B * a . y ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line segment into a line in parametric format . It will point from a to b . Point a and b must be unique . [CODESPLIT] public static LineParametric2D_F64 convert ( Point2D_F64 a , Point2D_F64 b , LineParametric2D_F64 ret ) { if ( ret == null ) ret = new LineParametric2D_F64 ( ) ; ret . p . set ( a ) ; ret . slope . x = b . x - a . x ; ret . slope . y = b . y - a . y ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line from parametric to polar . [CODESPLIT] public static LinePolar2D_F64 convert ( LineParametric2D_F64 src , LinePolar2D_F64 ret ) { if ( ret == null ) ret = new LinePolar2D_F64 ( ) ; double top = src . slope . y * src . p . x - src . slope . x * src . p . y ; ret . distance = top / src . slope . norm ( ) ; ret . angle = Math . atan2 ( - src . slope . x , src . slope . y ) ; if ( ret . distance < 0 ) { ret . distance = - ret . distance ; ret . angle = UtilAngle . bound ( ret . angle + Math . PI ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line from parametric to general [CODESPLIT] public static LineGeneral2D_F64 convert ( LineParametric2D_F64 src , LineGeneral2D_F64 ret ) { if ( ret == null ) { ret = new LineGeneral2D_F64 ( ) ; } ret . A = - src . slope . y ; ret . B = src . slope . x ; ret . C = - ret . A * src . p . x - ret . B * src . p . y ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a line from general to parametric [CODESPLIT] public static LineParametric2D_F64 convert ( LineGeneral2D_F64 src , LineParametric2D_F64 ret ) { if ( ret == null ) { ret = new LineParametric2D_F64 ( ) ; } ret . slope . x = src . B ; ret . slope . y = - src . A ; // find a point on the line if ( Math . abs ( src . B ) > Math . abs ( src . A ) ) { ret . p . y = - src . C / src . B ; ret . p . x = 0 ; } else { ret . p . x = - src . C / src . A ; ret . p . y = 0 ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a plane in normal form into a general equation [CODESPLIT] public static PlaneGeneral3D_F64 convert ( PlaneNormal3D_F64 input , PlaneGeneral3D_F64 output ) { if ( output == null ) output = new PlaneGeneral3D_F64 ( ) ; Vector3D_F64 n = input . n ; Point3D_F64 p = input . p ; output . A = n . x ; output . B = n . y ; output . C = n . z ; output . D = n . x * p . x + n . y * p . y + n . z * p . z ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Converts a plane in general form into normal form . The point on the plane in normal form will be the closest point to the origin . < / p > [CODESPLIT] public static PlaneNormal3D_F64 convert ( PlaneGeneral3D_F64 input , PlaneNormal3D_F64 output ) { if ( output == null ) output = new PlaneNormal3D_F64 ( ) ; double top = - input . D ; double n2 = input . A * input . A + input . B * input . B + input . C * input . C ; output . p . x = - input . A * top / n2 ; output . p . y = - input . B * top / n2 ; output . p . z = - input . C * top / n2 ; output . n . set ( input . A , input . B , input . C ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a plane in tangent form into a plane in normal form [CODESPLIT] public static PlaneNormal3D_F64 convert ( PlaneTangent3D_F64 input , PlaneNormal3D_F64 output ) { if ( output == null ) output = new PlaneNormal3D_F64 ( ) ; // the value of input is a vector normal to the plane and a point on the plane. output . n . x = input . x ; output . n . y = input . y ; output . n . z = input . z ; output . p . set ( input ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines a plane using a 3D rigid body transform . + z is the 3rd column the rotation matrix . The plane s point is the translation . The plane reference frame is the x - y plane . [CODESPLIT] public static PlaneNormal3D_F64 convert ( Se3_F64 planeToWorld , PlaneNormal3D_F64 output ) { if ( output == null ) output = new PlaneNormal3D_F64 ( ) ; // the value of input is a vector normal to the plane and a point on the plane. output . n . x = planeToWorld . R . unsafe_get ( 0 , 2 ) ; output . n . y = planeToWorld . R . unsafe_get ( 1 , 2 ) ; output . n . z = planeToWorld . R . unsafe_get ( 2 , 2 ) ; output . p . set ( planeToWorld . T . x , planeToWorld . T . y , planeToWorld . T . z ) ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the plane into Hessian normal form . This is done by dividing each coefficient by the Euclidean norm of ( A B C ) . [CODESPLIT] public static void hessianNormalForm ( PlaneGeneral3D_F64 plane ) { double n = Math . sqrt ( plane . A * plane . A + plane . B * plane . B + plane . C * plane . C ) ; plane . A /= n ; plane . B /= n ; plane . C /= n ; plane . D /= n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the plane s definition to test to see if a point is one the plane [CODESPLIT] public static double evaluate ( PlaneGeneral3D_F64 plane , Point3D_F64 point ) { return plane . A * point . x + plane . B * point . y + plane . C * point . z - plane . D ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the plane s definition to test to see if a point is one the plane [CODESPLIT] public static double evaluate ( PlaneNormal3D_F64 plane , Point3D_F64 point ) { double dx = point . x - plane . p . x ; double dy = point . y - plane . p . y ; double dz = point . z - plane . p . z ; return plane . n . x * dx + plane . n . y * dy + plane . n . z * dz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There are an infinite number of possible 2D coordinate axises for a plane . This selects one which will be right handed using { @link UtilVector3D_F64#perpendicularCanonical ( Vector3D_F64 Vector3D_F64 ) } and a cross product . [CODESPLIT] public static void selectAxis2D ( Vector3D_F64 normal , Vector3D_F64 axisX , Vector3D_F64 axisY ) { UtilVector3D_F64 . perpendicularCanonical ( normal , axisX ) ; axisX . normalize ( ) ; axisY . cross ( normal , axisX ) ; axisY . normalize ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Projects the point onto the 2D coordinate system specified by the provided x - axis . If the chose of x - axis is arbitrary { @link UtilVector3D_F64#perpendicularCanonical ( Vector3D_F64 Vector3D_F64 ) } is recommended as a way to select [CODESPLIT] public static void point3Dto2D ( Point3D_F64 pointOnPlane , Vector3D_F64 axisX , Vector3D_F64 axisY , Point3D_F64 A , Point2D_F64 output ) { double x = A . x - pointOnPlane . x ; double y = A . y - pointOnPlane . y ; double z = A . z - pointOnPlane . z ; output . x = x * axisX . x + y * axisX . y + z * axisX . z ; output . y = x * axisY . x + y * axisY . y + z * axisY . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a point on the plane s 2D coordinate system convert it back into a 3D point . [CODESPLIT] public static void point2Dto3D ( Point3D_F64 origin , Vector3D_F64 axisX , Vector3D_F64 axisY , Point2D_F64 A , Point3D_F64 output ) { output . x = origin . x + axisX . x * A . x + axisY . y * A . y ; output . y = origin . y + axisX . y * A . x + axisY . y * A . y ; output . z = origin . z + axisX . z * A . x + axisY . y * A . y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a transform from the plane s reference frame into world s reference frame . The z - axis is set to the plane s normal and the x - axis and y - axis are arbitrarily choosen . Points which lie along the plane will lie along its x - y plane . [CODESPLIT] public static Se3_F64 planeToWorld ( PlaneGeneral3D_F64 plane , Se3_F64 planeToWorld ) { if ( planeToWorld == null ) planeToWorld = new Se3_F64 ( ) ; Vector3D_F64 axisZ = new Vector3D_F64 ( plane . A , plane . B , plane . C ) ; axisZ . normalize ( ) ; Vector3D_F64 axisX = new Vector3D_F64 ( ) ; Vector3D_F64 axisY = new Vector3D_F64 ( ) ; UtilPlane3D_F64 . selectAxis2D ( axisZ , axisX , axisY ) ; return planeToWorld ( plane , axisX , axisY , axisZ , planeToWorld ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the two GeoTuple have values which are nearly the same . False is always returned if the dimension is different . [CODESPLIT] public boolean isIdentical ( T t , double tol ) { if ( t . getDimension ( ) != getDimension ( ) ) return false ; int N = getDimension ( ) ; for ( int i = 0 ; i < N ; i ++ ) { double diff = Math . abs ( getIdx ( i ) - t . getIdx ( i ) ) ; if ( diff > tol ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generic copy routine . It is recommended that this be overridden with a faster implementation . [CODESPLIT] @ Override public T copy ( ) { T ret = createNewInstance ( ) ; int N = getDimension ( ) ; for ( int i = 0 ; i < N ; i ++ ) { ret . setIdx ( i , getIdx ( i ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the square of the Euclidean norm . [CODESPLIT] public double normSq ( ) { double total = 0 ; int N = getDimension ( ) ; for ( int i = 0 ; i < N ; i ++ ) { double a = getIdx ( i ) ; total += a * a ; } return total ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link LineSegment3D_F64 } into { @link LineParametric3D_F64 } . [CODESPLIT] public static LineParametric3D_F64 convert ( LineSegment3D_F64 line , LineParametric3D_F64 output ) { if ( output == null ) output = new LineParametric3D_F64 ( ) ; output . p . set ( line . a ) ; output . slope . x = line . b . x - line . a . x ; output . slope . y = line . b . y - line . a . y ; output . slope . z = line . b . z - line . a . z ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the value of T for a point on the parametric line [CODESPLIT] public static double computeT ( LineParametric3D_F64 line , Point3D_F64 pointOnLine ) { double dx = pointOnLine . x - line . p . x ; double dy = pointOnLine . y - line . p . y ; double dz = pointOnLine . z - line . p . z ; double adx = Math . abs ( dx ) ; double ady = Math . abs ( dy ) ; double adz = Math . abs ( dz ) ; double t ; if ( adx > ady ) { if ( adx > adz ) { t = dx / line . slope . x ; } else { t = dz / line . slope . z ; } } else if ( ady > adz ) { t = dy / line . slope . y ; } else { t = dz / line . slope . z ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if any of its parameters have an uncountable number [CODESPLIT] public boolean hasUncountable ( ) { return UtilEjml . isUncountable ( A ) || UtilEjml . isUncountable ( C ) || UtilEjml . isUncountable ( D ) || UtilEjml . isUncountable ( E ) || UtilEjml . isUncountable ( F ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if they are equivalent up to a scale factor [CODESPLIT] public boolean isEquivalent ( ParabolaGeneral_F64 parabola , double tol ) { double scale = relativeScale ( parabola ) ; if ( Math . abs ( A * scale - parabola . A ) > tol ) return false ; if ( Math . abs ( C * scale - parabola . C ) > tol ) return false ; if ( Math . abs ( D * scale - parabola . D ) > tol ) return false ; if ( Math . abs ( E * scale - parabola . E ) > tol ) return false ; if ( Math . abs ( F * scale - parabola . F ) > tol ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the unweighted best fit line to the set of points using the polar line equation . The solution is optimal in the Euclidean sense see [ 1 ] for more details . < / p > [CODESPLIT] public static LinePolar2D_F32 polar ( List < Point2D_I32 > points , int start , int length , LinePolar2D_F32 ret ) { if ( ret == null ) ret = new LinePolar2D_F32 ( ) ; int sumX = 0 ; int sumY = 0 ; final int N = length ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_I32 p = points . get ( start + i ) ; sumX += p . x ; sumY += p . y ; } float meanX = sumX / ( float ) N ; float meanY = sumY / ( float ) N ; float top = 0 ; float bottom = 0 ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_I32 p = points . get ( start + i ) ; float dx = meanX - p . x ; float dy = meanY - p . y ; top += dx * dy ; bottom += dy * dy - dx * dx ; } ret . angle = ( float ) Math . atan2 ( - 2.0f * top , bottom ) / 2.0f ; ret . distance = ( float ) ( meanX * Math . cos ( ret . angle ) + meanY * Math . sin ( ret . angle ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The box s area . area = lengthX * lengthY * lengthZ [CODESPLIT] public double area ( ) { return ( p1 . x - p0 . x ) * ( p1 . y - p0 . y ) * ( p1 . z - p0 . z ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes and return the center of the cube . [CODESPLIT] public Point3D_F64 center ( Point3D_F64 storage ) { if ( storage == null ) storage = new Point3D_F64 ( ) ; storage . x = ( p0 . x + p1 . x ) / 2.0 ; storage . y = ( p0 . y + p1 . y ) / 2.0 ; storage . z = ( p0 . z + p1 . z ) / 2.0 ; return storage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the acute angle between the two lines . Does not check for intersection [CODESPLIT] public static double acuteAngle ( LineSegment2D_I32 line0 , LineSegment2D_I32 line1 ) { int dx0 = line0 . b . x - line0 . a . x ; int dy0 = line0 . b . y - line0 . a . y ; int dx1 = line1 . b . x - line1 . a . x ; int dy1 = line1 . b . y - line1 . a . y ; double bottom = Math . sqrt ( dx0 * dx0 + dy0 * dy0 ) * Math . sqrt ( dx1 * dx1 + dy1 * dy1 ) ; return Math . acos ( ( dx0 * dx1 + dy0 * dy1 ) / bottom ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given two sets of corresponding points compute the { @link Se2_F64 } transform which minimizes the difference between the two sets of points . [CODESPLIT] public static Se2_F64 fitPoints2D ( List < Point2D_F64 > from , List < Point2D_F64 > to ) { MotionTransformPoint < Se2_F64 , Point2D_F64 > alg = fitPoints2D ( ) ; alg . process ( from , to ) ; return alg . getTransformSrcToDst ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given two sets of corresponding points compute the { @link Se3_F64 } transform which minimizes the difference between the two sets of points . [CODESPLIT] public static Se3_F64 fitPoints3D ( List < Point3D_F64 > from , List < Point3D_F64 > to ) { MotionTransformPoint < Se3_F64 , Point3D_F64 > alg = fitPoints3D ( ) ; alg . process ( from , to ) ; return alg . getTransformSrcToDst ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the homogenous 3D point lies on the plane at infinity [CODESPLIT] public static boolean isInfiniteH ( Point4D_F64 p , double tol ) { double n = Math . sqrt ( p . x * p . x + p . y * p . y + p . z * p . z ) ; return Math . abs ( p . w ) <= n * tol ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normally distributed homogenous 3D point . w is fixed [CODESPLIT] public static List < Point4D_F64 > randomN ( Point3D_F64 center , double w , double stdev , int num , Random rand ) { List < Point4D_F64 > ret = new ArrayList <> ( ) ; for ( int i = 0 ; i < num ; i ++ ) { Point4D_F64 p = new Point4D_F64 ( ) ; p . x = center . x + rand . nextGaussian ( ) * stdev ; p . y = center . y + rand . nextGaussian ( ) * stdev ; p . z = center . z + rand . nextGaussian ( ) * stdev ; p . w = w ; ret . add ( p ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a point from homogenous coordinates into Euclidean [CODESPLIT] public static Point3D_F64 h_to_e ( Point4D_F64 p ) { Point3D_F64 out = new Point3D_F64 ( ) ; h_to_e ( p , out ) ; return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a 2D affine transform to the point and stores the results in another variable . [CODESPLIT] public static Vector2D_F64 transform ( Affine2D_F64 se , Vector2D_F64 orig , Vector2D_F64 result ) { if ( result == null ) { result = new Vector2D_F64 ( ) ; } // copy the values so that no errors happen if orig and result are the same instance double x = orig . x ; double y = orig . y ; result . x = se . a11 * x + se . a12 * y ; result . y = se . a21 * x + se . a22 * y ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a 2D affine transform to the point and stores the results in another variable . [CODESPLIT] public static Point2D_F64 transform ( Affine2D_F64 se , Point2D_F64 orig , Point2D_F64 result ) { if ( result == null ) { result = new Point2D_F64 ( ) ; } // copy the values so that no errors happen if orig and result are the same instance double x = orig . x ; double y = orig . y ; result . x = se . tx + se . a11 * x + se . a12 * y ; result . y = se . ty + se . a21 * x + se . a22 * y ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the acute angle between the two vectors . Computed using the dot product . [CODESPLIT] public static double acute ( Vector2D_F64 a , Vector2D_F64 b ) { double dot = a . dot ( b ) ; double value = dot / ( a . norm ( ) * b . norm ( ) ) ; if ( value > 1.0 ) value = 1.0 ; else if ( value < - 1.0 ) value = - 1.0 ; return Math . acos ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the vector equal to a - b . [CODESPLIT] public static Vector2D_F64 minus ( Point2D_F64 a , Point2D_F64 b , Vector2D_F64 output ) { if ( output == null ) output = new Vector2D_F64 ( ) ; output . x = a . x - b . x ; output . y = a . y - b . y ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests to see if the two vectors are identical up to a sign difference [CODESPLIT] public static boolean identicalSign ( double xa , double ya , double xb , double yb , double tol ) { double dx0 = xb - xa ; double dy0 = yb - ya ; double dx1 = xb + xa ; double dy1 = yb + ya ; double error0 = dx0 * dx0 + dy0 * dy0 ; double error1 = dx1 * dx1 + dy1 * dy1 ; if ( error0 < error1 ) { return error0 <= tol * tol ; } else { return error1 <= tol * tol ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets this rectangle to be equal to the passed in rectangle . [CODESPLIT] public void set ( RectangleLength2D_I32 r ) { this . x0 = r . x0 ; this . y0 = r . y0 ; this . width = r . width ; this . height = r . height ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In - place minus operation . this = a - b . [CODESPLIT] public void minus ( Point3D_F64 a , Point3D_F64 b ) { x = a . x - b . x ; y = a . y - b . y ; z = a . z - b . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dot product between this and a = this . x * a . x + this . y * a . y + this . z * a . z [CODESPLIT] public double dot ( Vector3D_F64 a ) { return x * a . x + y * a . y + z * a . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Convert from quadratic to rotated formats . Equations taken from [ 1 ] . < / p > [CODESPLIT] public static EllipseRotated_F64 convert ( EllipseQuadratic_F64 input , EllipseRotated_F64 output ) { if ( output == null ) output = new EllipseRotated_F64 ( ) ; double a11 = input . A ; double a12 = input . B ; double a22 = input . C ; double b1 = 2 * input . D ; double b2 = 2 * input . E ; double c = input . F ; output . center . x = ( a22 * b1 - a12 * b2 ) / ( 2 * ( a12 * a12 - a11 * a22 ) ) ; output . center . y = ( a11 * b2 - a12 * b1 ) / ( 2 * ( a12 * a12 - a11 * a22 ) ) ; double k1 = output . center . x ; double k2 = output . center . y ; double mu = 1.0 / ( a11 * k1 * k1 + 2 * a12 * k1 * k2 + a22 * k2 * k2 - c ) ; double m11 = mu * a11 ; double m12 = mu * a12 ; double m22 = mu * a22 ; double inner = Math . sqrt ( ( m11 - m22 ) * ( m11 - m22 ) + 4 * m12 * m12 ) ; double l1 = ( ( m11 + m22 ) + inner ) / 2.0 ; double l2 = ( ( m11 + m22 ) - inner ) / 2.0 ; output . b = 1 / ( double ) Math . sqrt ( l1 ) ; output . a = 1 / ( double ) Math . sqrt ( l2 ) ; // direction of minor axis double dx , dy ; if ( m11 >= m22 ) { dx = l1 - m22 ; dy = m12 ; } else { dx = m12 ; dy = l1 - m11 ; } // direction of major axis output . phi = Math . atan2 ( - dx , dy ) ; if ( output . phi < - GrlConstants . PId2 ) { output . phi += ( double ) Math . PI ; } else if ( output . phi > GrlConstants . PId2 ) { output . phi -= ( double ) Math . PI ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert from rotated to quadratic . [CODESPLIT] public static EllipseQuadratic_F64 convert ( EllipseRotated_F64 input , EllipseQuadratic_F64 output ) { if ( output == null ) output = new EllipseQuadratic_F64 ( ) ; double x0 = input . center . x ; double y0 = input . center . y ; double a = input . a ; double b = input . b ; double phi = input . phi ; double cphi = Math . cos ( phi ) ; double sphi = Math . sin ( phi ) ; double cphi2 = cphi * cphi ; double sphi2 = sphi * sphi ; double a2 = a * a ; double b2 = b * b ; double x02 = x0 * x0 ; double y02 = y0 * y0 ; // TODO simplfy using more trig identities output . A = cphi2 / a2 + sphi2 / b2 ; output . B = sphi * cphi / a2 - sphi * cphi / b2 ; output . C = sphi2 / a2 + cphi2 / b2 ; output . D = - x0 * cphi2 / a2 - y0 * sphi * cphi / a2 - x0 * sphi2 / b2 + y0 * sphi * cphi / b2 ; output . E = - x0 * sphi * cphi / a2 - y0 * sphi2 / a2 + x0 * sphi * cphi / b2 - y0 * cphi2 / b2 ; output . F = x02 * cphi2 / a2 + 2 * x0 * y0 * sphi * cphi / a2 + y02 * sphi2 / a2 + x02 * sphi2 / b2 - 2 * x0 * y0 * sphi * cphi / b2 + y02 * cphi2 / b2 - 1 ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the value of the quadratic ellipse function at point ( x y ) . Should equal 0 if the point is along the ellipse . [CODESPLIT] public static double evaluate ( double x , double y , EllipseQuadratic_F64 ellipse ) { return ellipse . A * x * x + 2 * ellipse . B * x * y + ellipse . C * y * y + 2 * ellipse . D * x + 2 * ellipse . E * y + ellipse . F ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the value of the quadratic ellipse function at point ( x y ) . Should equal 1 if the point is on the ellipse . [CODESPLIT] public static double evaluate ( double x , double y , EllipseRotated_F64 ellipse ) { double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; x -= ellipse . center . x ; y -= ellipse . center . y ; double left = ( x * cphi + y * sphi ) ; double right = ( - x * sphi + y * cphi ) ; double ll = left / ellipse . a ; double rr = right / ellipse . b ; return ll * ll + rr * rr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the point on the ellipse at location t where t is an angle in radians [CODESPLIT] public static Point2D_F64 computePoint ( double t , EllipseRotated_F64 ellipse , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double ct = Math . cos ( t ) ; double st = Math . sin ( t ) ; double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; // coordinate in ellipse frame double x = ellipse . a * ct ; double y = ellipse . b * st ; // put into global frame output . x = ellipse . center . x + x * cphi - y * sphi ; output . y = ellipse . center . y + x * sphi + y * cphi ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the value of t used to specify a point s location [CODESPLIT] public static double computeAngle ( Point2D_F64 p , EllipseRotated_F64 ellipse ) { // put point into ellipse's reference frame double ce = Math . cos ( ellipse . phi ) ; double se = Math . sin ( ellipse . phi ) ; // world into ellipse frame double xc = p . x - ellipse . center . x ; double yc = p . y - ellipse . center . y ; double x = ce * xc + se * yc ; double y = - se * xc + ce * yc ; return Math . atan2 ( y / ellipse . b , x / ellipse . a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the tangent to the ellipse at the specified location [CODESPLIT] public static Vector2D_F64 computeTangent ( double t , EllipseRotated_F64 ellipse , Vector2D_F64 output ) { if ( output == null ) output = new Vector2D_F64 ( ) ; double ct = Math . cos ( t ) ; double st = Math . sin ( t ) ; double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; // point in ellipse frame multiplied by b^2 and a^2 double x = ellipse . a * ct * ellipse . b * ellipse . b ; double y = ellipse . b * st * ellipse . a * ellipse . a ; // rotate vector normal into world frame double rx = x * cphi - y * sphi ; double ry = x * sphi + y * cphi ; // normalize and change into tangent double r = Math . sqrt ( rx * rx + ry * ry ) ; output . x = - ry / r ; output . y = rx / r ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds two points on the ellipse that in combination with point pt each define a line that is tangent to the ellipse . < / p > [CODESPLIT] public static boolean tangentLines ( Point2D_F64 pt , EllipseRotated_F64 ellipse , Point2D_F64 tangentA , Point2D_F64 tangentB ) { // Derivation: // Compute the tangent at only point along the ellipse by computing dy/dx //    x*b^2/(y*a^2) or - x*b^2/(y*a^2)  are the possible solutions for the tangent // The slope of the line and the gradient are the same, so this is true: //   y - y'     -x*b^2 //  -------  =  ------- //   x - x'      y*a^2 // //  (x,y) is point on ellipse, (x',y') is pt that lines pass through // //  that becomes //  y^2*a^2 + x^2*b^2 = x'*x*b^2 + y'*y*a^2 //  use the equation for the ellipse (centered and aligned at origin) //  a^2*b^2 =  x'*x*b^2 + y'*y*a^2 // // solve for y // plug into ellipse equation // solve for x, which is a quadratic equation // translate and rotate into ellipse reference frame double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; double tmpx = pt . x - ellipse . center . x ; double tmpy = pt . y - ellipse . center . y ; double xt = tmpx * cphi + tmpy * sphi ; double yt = - tmpx * sphi + tmpy * cphi ; // solve double a2 = ellipse . a * ellipse . a ; double b2 = ellipse . b * ellipse . b ; // quadratic equation for the two variants. // solving for x double aa0 = yt * yt / b2 + xt * xt / a2 ; double bb0 = - 2.0 * xt ; double cc0 = a2 * ( 1.0 - yt * yt / b2 ) ; double descriminant0 = bb0 * bb0 - 4.0 * aa0 * cc0 ; // solving for y double aa1 = xt * xt / a2 + yt * yt / b2 ; double bb1 = - 2.0 * yt ; double cc1 = b2 * ( 1.0 - xt * xt / a2 ) ; double descriminant1 = bb1 * bb1 - 4.0 * aa1 * cc1 ; double x0 , y0 , x1 , y1 ; if ( descriminant0 < 0 && descriminant1 < 0 ) { return false ; } else if ( descriminant0 > descriminant1 ) { if ( yt == 0 ) return false ; double right = Math . sqrt ( descriminant0 ) ; x0 = ( - bb0 + right ) / ( 2.0 * aa0 ) ; x1 = ( - bb0 - right ) / ( 2.0 * aa0 ) ; y0 = b2 / yt - xt * x0 * b2 / ( yt * a2 ) ; y1 = b2 / yt - xt * x1 * b2 / ( yt * a2 ) ; } else { if ( xt == 0 ) return false ; double right = Math . sqrt ( descriminant1 ) ; y0 = ( - bb1 + right ) / ( 2.0 * aa1 ) ; y1 = ( - bb1 - right ) / ( 2.0 * aa1 ) ; x0 = a2 / xt - yt * y0 * a2 / ( xt * b2 ) ; x1 = a2 / xt - yt * y1 * a2 / ( xt * b2 ) ; } // convert the lines back into world space tangentA . x = x0 * cphi - y0 * sphi + ellipse . center . x ; tangentA . y = x0 * sphi + y0 * cphi + ellipse . center . y ; tangentB . x = x1 * cphi - y1 * sphi + ellipse . center . x ; tangentB . y = x1 * sphi + y1 * cphi + ellipse . center . y ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds four lines which are tangent to both ellipses . Both ellipses must not intersect . Line 0 and line 3 will not intersect the line joining the center of the two ellipses while line 1 and 2 will . < / p > [CODESPLIT] public static boolean tangentLines ( EllipseRotated_F64 ellipseA , EllipseRotated_F64 ellipseB , Point2D_F64 tangentA0 , Point2D_F64 tangentA1 , Point2D_F64 tangentA2 , Point2D_F64 tangentA3 , Point2D_F64 tangentB0 , Point2D_F64 tangentB1 , Point2D_F64 tangentB2 , Point2D_F64 tangentB3 ) { TangentLinesTwoEllipses_F64 alg = new TangentLinesTwoEllipses_F64 ( GrlConstants . TEST_F64 , 10 ) ; return alg . process ( ellipseA , ellipseB , tangentA0 , tangentA1 , tangentA2 , tangentA3 , tangentB0 , tangentB1 , tangentB2 , tangentB3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Selects 4 pairs of points . Each point in the pair represents an end point in a line segment which is tangent to both ellipseA and ellipseB . Both ellipses are assumed to not intersect each other . If a fatal error occurs the function will return false . However it can return true and did not converge . To check for convergence call { @link #isConverged () } . < / p > [CODESPLIT] public boolean process ( EllipseRotated_F64 ellipseA , EllipseRotated_F64 ellipseB , Point2D_F64 tangentA0 , Point2D_F64 tangentA1 , Point2D_F64 tangentA2 , Point2D_F64 tangentA3 , Point2D_F64 tangentB0 , Point2D_F64 tangentB1 , Point2D_F64 tangentB2 , Point2D_F64 tangentB3 ) { converged = false ; // initialize by picking an arbitrary point on A and then finding the points on B in which // a line is tangent to B and passes through the point on A if ( ! initialize ( ellipseA , ellipseB , tangentA0 , tangentA1 , tangentA2 , tangentA3 , tangentB0 , tangentB1 , tangentB2 , tangentB3 ) ) return false ; // update the location of each point until it converges or the maximum number of iterations has been exceeded int iteration = 0 ; for ( ; iteration < maxIterations ; iteration ++ ) { boolean allGood = false ; sumDifference = 0 ; if ( ! selectTangent ( tangentA0 , tangentB0 , ellipseB , tangentB0 , false ) ) return false ; if ( ! selectTangent ( tangentA1 , tangentB1 , ellipseB , tangentB1 , true ) ) return false ; if ( ! selectTangent ( tangentA2 , tangentB2 , ellipseB , tangentB2 , true ) ) return false ; if ( ! selectTangent ( tangentA3 , tangentB3 , ellipseB , tangentB3 , false ) ) return false ; if ( Math . sqrt ( sumDifference ) / 4.0 <= convergenceTol ) { allGood = true ; } sumDifference = 0 ; if ( ! selectTangent ( tangentB0 , tangentA0 , ellipseA , tangentA0 , false ) ) return false ; if ( ! selectTangent ( tangentB1 , tangentA1 , ellipseA , tangentA1 , true ) ) return false ; if ( ! selectTangent ( tangentB2 , tangentA2 , ellipseA , tangentA2 , true ) ) return false ; if ( ! selectTangent ( tangentB3 , tangentA3 , ellipseA , tangentA3 , false ) ) return false ; if ( allGood && Math . sqrt ( sumDifference ) / 4.0 <= convergenceTol ) { break ; } } converged = iteration < maxIterations ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select the initial tangent points on the ellipses . This is done by : [CODESPLIT] boolean initialize ( EllipseRotated_F64 ellipseA , EllipseRotated_F64 ellipseB , Point2D_F64 tangentA0 , Point2D_F64 tangentA1 , Point2D_F64 tangentA2 , Point2D_F64 tangentA3 , Point2D_F64 tangentB0 , Point2D_F64 tangentB1 , Point2D_F64 tangentB2 , Point2D_F64 tangentB3 ) { centerLine . set ( ellipseA . center , ellipseB . center ) ; UtilLine2D_F64 . convert ( centerLine , lineGeneral ) ; Intersection2D_F64 . intersection ( lineGeneral , ellipseA , temp0 , temp1 , - 1 ) ; if ( temp0 . distance2 ( ellipseB . center ) < temp1 . distance2 ( ellipseB . center ) ) { tangentA0 . set ( temp0 ) ; } else { tangentA0 . set ( temp1 ) ; } // Two seed points for B.  This points will be on two different sides of center line if ( ! tangentLines ( tangentA0 , ellipseB , tangentB0 , tangentB1 ) ) return false ; // Find initial seed of 4 points on ellipse A.  Careful which pairs of points cross or // don't cross the center line if ( ! selectTangent ( tangentB0 , tangentA0 , ellipseA , tangentA0 , false ) ) return false ; if ( ! selectTangent ( tangentB0 , tangentA0 , ellipseA , tangentA1 , true ) ) return false ; if ( ! selectTangent ( tangentB1 , tangentA0 , ellipseA , tangentA2 , true ) ) return false ; if ( ! selectTangent ( tangentB1 , tangentA0 , ellipseA , tangentA3 , false ) ) return false ; // not all of the B's have been initialized.  That's ok.  It will just have a large error // the first iteration return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects a tangent point on the ellipse which is closest to the original source point of A . [CODESPLIT] boolean selectTangent ( Point2D_F64 a , Point2D_F64 previousTangent , EllipseRotated_F64 ellipse , Point2D_F64 tangent , boolean cross ) { if ( ! tangentLines ( a , ellipse , temp0 , temp1 ) ) return false ; tempLine . a = a ; tempLine . b = temp0 ; boolean crossed0 = Intersection2D_F64 . intersection ( centerLine , tempLine , junk ) != null ; tempLine . b = temp1 ; boolean crossed1 = Intersection2D_F64 . intersection ( centerLine , tempLine , junk ) != null ; if ( crossed0 == crossed1 ) throw new RuntimeException ( \"Well this didn't work\" ) ; if ( cross == crossed0 ) { sumDifference += previousTangent . distance2 ( temp0 ) ; tangent . set ( temp0 ) ; } else { sumDifference += previousTangent . distance2 ( temp1 ) ; tangent . set ( temp1 ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes sure x0 y0 is the lower extent and x1 y1 is the upper extent [CODESPLIT] public void enforceExtents ( ) { if ( x1 < x0 ) { int tmp = x1 ; x1 = x0 ; x0 = tmp ; } if ( y1 < y0 ) { int tmp = y1 ; y1 = y0 ; y0 = tmp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance squared from this to a . No floating point operations are used . < / p > [CODESPLIT] public int distance2 ( Point2D_I32 a ) { int dx = x - a . x ; int dy = y - a . y ; return dx * dx + dy * dy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the best fit matrix in SO ( 3 ) for the input matrix . [CODESPLIT] public static void bestFit ( DMatrixRMaj A ) { SingularValueDecomposition_F64 < DMatrixRMaj > svd = DecompositionFactory_DDRM . svd ( true , true , true ) ; if ( ! svd . decompose ( A ) ) throw new RuntimeException ( \"SVD Failed\" ) ; CommonOps_DDRM . multTransB ( svd . getU ( null , false ) , svd . getV ( null , false ) , A ) ; // determinant should be +1 double det = CommonOps_DDRM . det ( A ) ; if ( det < 0 ) CommonOps_DDRM . scale ( - 1 , A ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to retrieve the corners of the box . [CODESPLIT] public Point3D_F64 getCorner ( int index , Point3D_F64 corner ) { if ( corner == null ) corner = new Point3D_F64 ( ) ; corner . set ( p ) ; if ( ( index & 0x01 ) != 0 ) { corner . x += lengthX ; } if ( ( index & 0x02 ) != 0 ) { corner . y += lengthY ; } if ( ( index & 0x04 ) != 0 ) { corner . z += lengthZ ; } return corner ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distance of the closest point between two lines . Parallel lines are correctly handled . [CODESPLIT] public static double distance ( LineParametric3D_F64 l0 , LineParametric3D_F64 l1 ) { double x = l0 . p . x - l1 . p . x ; double y = l0 . p . y - l1 . p . y ; double z = l0 . p . z - l1 . p . z ; // this solution is from: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/ double dv01v1 = MiscOps . dot ( x , y , z , l1 . slope ) ; double dv1v0 = MiscOps . dot ( l1 . slope , l0 . slope ) ; double dv1v1 = MiscOps . dot ( l1 . slope , l1 . slope ) ; double bottom = MiscOps . dot ( l0 . slope , l0 . slope ) * dv1v1 - dv1v0 * dv1v0 ; double t0 ; if ( bottom == 0 ) { // handle parallel lines t0 = 0 ; } else { t0 = ( dv01v1 * dv1v0 - MiscOps . dot ( x , y , z , l0 . slope ) * dv1v1 ) / bottom ; } // ( d1343 + mua d4321 ) / d4343 double t1 = ( dv01v1 + t0 * dv1v0 ) / dv1v1 ; double dx = ( l0 . p . x + t0 * l0 . slope . x ) - ( l1 . p . x + t1 * l1 . slope . x ) ; double dy = ( l0 . p . y + t0 * l0 . slope . y ) - ( l1 . p . y + t1 * l1 . slope . y ) ; double dz = ( l0 . p . z + t0 * l0 . slope . z ) - ( l1 . p . z + t1 * l1 . slope . z ) ; // round off error can make distanceSq go negative when it is very close to zero double distanceSq = dx * dx + dy * dy + dz * dz ; if ( distanceSq < 0 ) return 0 ; else return Math . sqrt ( distanceSq ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distance from the point to the closest point on the line . [CODESPLIT] public static double distance ( LineParametric3D_F64 l , Point3D_F64 p ) { double x = l . p . x - p . x ; double y = l . p . y - p . y ; double z = l . p . z - p . z ; double cc = x * x + y * y + z * z ; // could avoid a square root here by computing b*b directly // however that is most likely more prone to numerical overflow since the numerator will need to be squared // before division can reduce its \"power\" double b = MiscOps . dot ( x , y , z , l . slope ) / l . slope . norm ( ) ; double distanceSq = cc - b * b ; // round off error can make distanceSq go negative when it is very close to zero if ( distanceSq < 0 ) { return 0 ; } else { return Math . sqrt ( distanceSq ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distance from the point to the closest point on the line segment . [CODESPLIT] public static double distance ( LineSegment3D_F64 l , Point3D_F64 p ) { double dx = p . x - l . a . x ; double dy = p . y - l . a . y ; double dz = p . z - l . a . z ; double cc = dx * dx + dy * dy + dz * dz ; double slope_x = l . b . x - l . a . x ; double slope_y = l . b . y - l . a . y ; double slope_z = l . b . z - l . a . z ; double n = ( double ) Math . sqrt ( slope_x * slope_x + slope_y * slope_y + slope_z * slope_z ) ; double d = ( slope_x * dx + slope_y * dy + slope_z * dz ) / n ; // check end points if ( d <= 0 ) return p . distance ( l . a ) ; else if ( d >= n ) return p . distance ( l . b ) ; double distanceSq = cc - d * d ; // round off error can make distanceSq go negative when it is very close to zero if ( distanceSq < 0 ) { return 0 ; } else { return Math . sqrt ( distanceSq ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Distance between a plane and a point . A signed distance is returned where a positive value is returned if the point is on the same side of the plane as the normal and the opposite if it s on the other . [CODESPLIT] public static double distance ( PlaneGeneral3D_F64 plane , Point3D_F64 point ) { double top = plane . A * point . x + plane . B * point . y + plane . C * point . z - plane . D ; return top / Math . sqrt ( plane . A * plane . A + plane . B * plane . B + plane . C * plane . C ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the signed distance a point is from the sphere s surface . If the point is outside of the sphere it s distance will be positive . If it is inside it will be negative . <p > < / p > distance = ||sphere . center - point|| - r [CODESPLIT] public static double distance ( Sphere3D_F64 sphere , Point3D_F64 point ) { double r = point . distance ( sphere . center ) ; return r - sphere . radius ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the signed distance a point is from the cylinder s surface . If the point is outside of the cylinder it s distance will be positive . If it is inside it will be negative . [CODESPLIT] public static double distance ( Cylinder3D_F64 cylinder , Point3D_F64 point ) { double r = Distance3D_F64 . distance ( cylinder . line , point ) ; return r - cylinder . radius ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signed distance from a 3D point to 3D triangle . The sign indicates which side of the triangle the point is on . See { @link georegression . metric . alg . DistancePointTriangle3D_F64 } for the details . [CODESPLIT] public static double distance ( Triangle3D_F64 triangle , Point3D_F64 point ) { DistancePointTriangle3D_F64 alg = new DistancePointTriangle3D_F64 ( ) ; alg . setTriangle ( triangle . v0 , triangle . v1 , triangle . v2 ) ; Point3D_F64 cp = new Point3D_F64 ( ) ; alg . closestPoint ( point , cp ) ; double d = point . distance ( cp ) ; return alg . sign ( point ) * d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "where = p + t * slope . [CODESPLIT] public void setPointOnLine ( double t , Point3D_F64 where ) { where . x = p . x + t * slope . x ; where . y = p . y + t * slope . y ; where . z = p . z + t * slope . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a point along the line . See parametric equation in class description . [CODESPLIT] public Point3D_F64 getPointOnLine ( double t ) { return new Point3D_F64 ( slope . x * t + p . x , slope . y * t + p . y , slope . z * t + p . z ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance of the closest point on the line from a point . < / p > [CODESPLIT] public static double distance ( LineParametric2D_F64 line , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( line , p ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance of the closest point on the line from a point . < / p > [CODESPLIT] public static double distance ( LineParametric2D_F64 line , double x , double y ) { return Math . sqrt ( distanceSq ( line , x , y ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance squared of the closest point on the line from a point . < / p > [CODESPLIT] public static double distanceSq ( LineParametric2D_F64 line , Point2D_F64 p ) { double scale = Math . max ( Math . abs ( line . slope . x ) , Math . abs ( line . slope . y ) ) ; double t = ClosestPoint2D_F64 . closestPointT ( line , p , scale ) ; double a = ( line . slope . x / scale ) * t + line . p . x ; double b = ( line . slope . y / scale ) * t + line . p . y ; double dx = p . x - a ; double dy = p . y - b ; return dx * dx + dy * dy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance of the closest point on a line segment to the specified point . < / p > [CODESPLIT] public static double distance ( LineSegment2D_F64 line , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( line , p ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance of the closest point on a line segment to the specified point . < / p > [CODESPLIT] public static double distance ( LineSegment2D_F64 line , double x , double y ) { return Math . sqrt ( distanceSq ( line , x , y ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance squared of the closest point on a line segment to the specified point . < / p > [CODESPLIT] public static double distanceSq ( LineSegment2D_F64 line , Point2D_F64 p ) { double a = line . b . x - line . a . x ; double b = line . b . y - line . a . y ; double t = a * ( p . x - line . a . x ) + b * ( p . y - line . a . y ) ; t /= ( a * a + b * b ) ; // if the point of intersection is past the end points return the distance // from the closest end point if ( t < 0 ) { return UtilPoint2D_F64 . distanceSq ( line . a . x , line . a . y , p . x , p . y ) ; } else if ( t > 1.0 ) return UtilPoint2D_F64 . distanceSq ( line . b . x , line . b . y , p . x , p . y ) ; // return the distance of the closest point on the line return UtilPoint2D_F64 . distanceSq ( line . a . x + t * a , line . a . y + t * b , p . x , p . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the distance between the two line segments [CODESPLIT] public static double distance ( LineSegment2D_F64 segmentA , LineSegment2D_F64 segmentB ) { return Math . sqrt ( distanceSq ( segmentA , segmentB ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the distance squared between the two line segments [CODESPLIT] public static double distanceSq ( LineSegment2D_F64 segmentA , LineSegment2D_F64 segmentB ) { // intersection of the two lines relative to A double slopeAX = segmentA . slopeX ( ) ; double slopeAY = segmentA . slopeY ( ) ; double slopeBX = segmentB . slopeX ( ) ; double slopeBY = segmentB . slopeY ( ) ; double ta = slopeBX * ( segmentA . a . y - segmentB . a . y ) - slopeBY * ( segmentA . a . x - segmentB . a . x ) ; double bottom = slopeBY * slopeAX - slopeAY * slopeBX ; // see they intersect if ( bottom != 0 ) { // see if the intersection is inside of lineA ta /= bottom ; if ( ta >= 0 && ta <= 1.0 ) { // see if the intersection is inside of lineB double tb = slopeAX * ( segmentB . a . y - segmentA . a . y ) - slopeAY * ( segmentB . a . x - segmentA . a . x ) ; tb /= slopeAY * slopeBX - slopeBY * slopeAX ; if ( tb >= 0 && tb <= 1.0 ) return 0 ; } } double closest = Double . MAX_VALUE ; closest = Math . min ( closest , distanceSq ( segmentA , segmentB . a ) ) ; closest = Math . min ( closest , distanceSq ( segmentA , segmentB . b ) ) ; closest = Math . min ( closest , distanceSq ( segmentB , segmentA . a ) ) ; closest = Math . min ( closest , distanceSq ( segmentB , segmentA . b ) ) ; return closest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Euclidean distance of the closest point on the quadrilateral to the provided point . [CODESPLIT] public static double distance ( Quadrilateral_F64 quad , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( quad , p ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Euclidean distance squared of the closest point on the quadrilateral to the provided point . [CODESPLIT] public static double distanceSq ( Quadrilateral_F64 quad , Point2D_F64 p ) { LineSegment2D_F64 seg = LineSegment2D_F64 . wrap ( quad . a , quad . b ) ; double a = distanceSq ( seg , p ) ; seg . a = quad . b ; seg . b = quad . c ; a = Math . min ( a , distanceSq ( seg , p ) ) ; seg . a = quad . c ; seg . b = quad . d ; a = Math . min ( a , distanceSq ( seg , p ) ) ; seg . a = quad . d ; seg . b = quad . a ; return Math . min ( a , distanceSq ( seg , p ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Euclidean distance of the closest point on the Polygon to the provided point . [CODESPLIT] public static double distance ( Polygon2D_F64 poly , Point2D_F64 p ) { return Math . sqrt ( distanceSq ( poly , p , null ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Euclidean distance squared of the closest point on the Polygon to the provided point . [CODESPLIT] public static double distanceSq ( Polygon2D_F64 poly , Point2D_F64 p , LineSegment2D_F64 storage ) { if ( storage == null ) storage = LineSegment2D_F64 . wrap ( null , null ) ; double minimum = Double . MAX_VALUE ; for ( int i = 0 ; i < poly . size ( ) ; i ++ ) { int j = ( i + 1 ) % poly . size ( ) ; storage . a = poly . vertexes . data [ i ] ; storage . b = poly . vertexes . data [ j ] ; double d = distanceSq ( storage , p ) ; if ( d < minimum ) minimum = d ; } return minimum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the Euclidean distance of the closest point on the line to the specified point . < / p > [CODESPLIT] public static double distance ( LineGeneral2D_F64 line , Point2D_F64 p ) { return Math . abs ( line . A * p . x + line . B * p . y + line . C ) / Math . sqrt ( line . A * line . A + line . B * line . B ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the signed Euclidean distance of the closest point on the line to the specified point . The line is assumed be normalized . See { @link LineGeneral2D_F64 } for details on normalization . < / p > [CODESPLIT] public static double distanceNorm ( LineGeneral2D_F64 line , Point2D_F64 p ) { return Math . abs ( line . A * p . x + line . B * p . y + line . C ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the distance of the closest point on the line from the origin [CODESPLIT] public static double distanceOrigin ( LineParametric2D_F64 line ) { double top = line . slope . y * line . p . x - line . slope . x * line . p . y ; return Math . abs ( top ) / line . slope . norm ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Euclidean distance of closest point on ellipse to point p . [CODESPLIT] public static double distance ( EllipseRotated_F64 ellipse , Point2D_F64 p ) { return Math . sqrt ( distance2 ( ellipse , p ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Euclidean distance squared of closest point on ellipse to point p . [CODESPLIT] public static double distance2 ( EllipseRotated_F64 ellipse , Point2D_F64 p ) { // put point into ellipse's reference frame double cphi = Math . cos ( ellipse . phi ) ; double sphi = Math . sin ( ellipse . phi ) ; double xc = p . x - ellipse . center . x ; double yc = p . y - ellipse . center . y ; double r = Math . sqrt ( xc * xc + yc * yc ) ; double x = cphi * xc + sphi * yc ; double y = - sphi * xc + cphi * yc ; double ct = x / r ; double st = y / r ; x = ellipse . center . x + ellipse . a * ct * cphi - ellipse . b * st * sphi ; y = ellipse . center . y + ellipse . a * ct * sphi + ellipse . b * st * cphi ; return p . distance2 ( x , y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the next transform in the sequence . [CODESPLIT] public void addTransform ( boolean forward , T tran ) { path . add ( new Node < T > ( tran , forward ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the closest point on line to the specified point . < / p > [CODESPLIT] public static Point2D_F64 closestPoint ( LineGeneral2D_F64 line , Point2D_F64 p , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double AA = line . A * line . A ; double AB = line . A * line . B ; double BB = line . B * line . B ; output . y = AA * p . y - AB * p . x - line . B * line . C ; output . y /= AA + BB ; output . x = BB * p . x - AB * p . y - line . A * line . C ; output . x /= AA + BB ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Finds the closest point on line to the specified point . < / p > [CODESPLIT] public static Point2D_F64 closestPoint ( LineParametric2D_F64 line , Point2D_F64 p , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double t = closestPointT ( line , p ) ; output . x = line . p . x + line . slope . x * t ; output . y = line . p . y + line . slope . y * t ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the closest point along the line as a function of t : <br > [ x y ] = [ x_0 y_0 ] + t· [ slopeX slopeY ] < / p > [CODESPLIT] public static double closestPointT ( LineParametric2D_F64 line , Point2D_F64 p ) { double t = line . slope . x * ( p . x - line . p . x ) + line . slope . y * ( p . y - line . p . y ) ; t /= line . slope . x * line . slope . x + line . slope . y * line . slope . y ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Computes the closest point along the line as a function of t : <br > [ x y ] = [ x_0 y_0 ] + t· [ slopeX slopeY ] < / p > [CODESPLIT] public static double closestPointT ( LineParametric2D_F64 line , double x , double y , double scale ) { double sx = line . slope . x / scale ; double sy = line . slope . y / scale ; double t = sx * ( x - line . p . x ) + sy * ( y - line . p . y ) ; t /= sx * sx + sy * sy ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the closest point on the line segment to the provided point p . [CODESPLIT] public static Point2D_F64 closestPoint ( LineSegment2D_F64 line , Point2D_F64 p , Point2D_F64 output ) { if ( output == null ) output = new Point2D_F64 ( ) ; double slopeX = line . b . x - line . a . x ; double slopeY = line . b . y - line . a . y ; double t = slopeX * ( p . x - line . a . x ) + slopeY * ( p . y - line . a . y ) ; t /= slopeX * slopeX + slopeY * slopeY ; if ( t < 0 ) t = 0 ; else if ( t > 1 ) t = 1 ; output . x = line . a . x + slopeX * t ; output . y = line . a . y + slopeY * t ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the closest point on an ellipse to the provided point . If there are multiple solutions then one is arbitrarily chosen . [CODESPLIT] public static Point2D_F64 closestPoint ( EllipseRotated_F64 ellipse , Point2D_F64 p ) { ClosestPointEllipseAngle_F64 alg = new ClosestPointEllipseAngle_F64 ( GrlConstants . TEST_F64 , 30 ) ; alg . setEllipse ( ellipse ) ; alg . process ( p ) ; return alg . getClosest ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fits the polynomial curve to the data . [CODESPLIT] public boolean process ( double [ ] data , int offset , int length , PolynomialCurve_F64 output ) { int N = length / 2 ; int numCoefs = output . size ( ) ; A . reshape ( N , numCoefs ) ; b . reshape ( N , 1 ) ; x . reshape ( numCoefs , 1 ) ; int end = offset + length ; for ( int i = offset , idxA = 0 ; i < end ; i += 2 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double pow = 1.0 ; for ( int j = 0 ; j < numCoefs ; j ++ ) { A . data [ idxA ++ ] = pow ; pow *= x ; } b . data [ i / 2 ] = y ; } if ( ! solver . setA ( A ) ) return false ; solver . solve ( b , x ) ; for ( int i = 0 ; i < numCoefs ; i ++ ) { output . set ( i , x . data [ i ] ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fits the conic to the points . Strongly recommended that you transform the points such that they have zero mean and a standard deviation along x and y axis independently . [CODESPLIT] @ Override public boolean process ( List < Point2D_F64 > points , ConicGeneral_F64 output ) { final int N = points . size ( ) ; if ( N < 3 ) throw new IllegalArgumentException ( \"At least 3 points required\" ) ; CommonOps_DDF6 . fill ( ATA , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double x = p . x ; double y = p . y ; double xx = x * x ; double xxx = xx * x ; double yy = y * y ; double yyy = yy * y ; ATA . a11 += xx * xx ; ATA . a12 += xxx * y ; ATA . a13 += xx * yy ; ATA . a14 += xxx ; ATA . a15 += xx * y ; ATA . a16 += xx ; ATA . a22 += xx * yy ; ATA . a23 += x * yyy ; //\t\t\tATA.a24 += xx*y; ATA . a25 += x * yy ; ATA . a26 += x * y ; ATA . a33 += yyy * y ; //\t\t\tATA.a34 += x*yy; ATA . a35 += yyy ; ATA . a36 += yy ; //\t\t\tATA.a44 += xx; ATA . a45 += x * y ; ATA . a46 += x ; //\t\t\tATA.a55 += yy; ATA . a56 += y ; } ATA . a21 = ATA . a12 ; ATA . a24 = ATA . a15 ; ATA . a31 = ATA . a13 ; ATA . a32 = ATA . a23 ; ATA . a34 = ATA . a25 ; ATA . a41 = ATA . a14 ; ATA . a42 = ATA . a24 ; ATA . a43 = ATA . a34 ; ATA . a44 = ATA . a16 ; ATA . a51 = ATA . a15 ; ATA . a52 = ATA . a25 ; ATA . a53 = ATA . a35 ; ATA . a54 = ATA . a45 ; ATA . a55 = ATA . a36 ; ATA . a61 = ATA . a16 ; ATA . a62 = ATA . a26 ; ATA . a63 = ATA . a36 ; ATA . a64 = ATA . a56 ; ATA . a65 = ATA . a56 ; ATA . a66 = N ; ConvertDMatrixStruct . convert ( ATA , tmp ) ; if ( ! solver . process ( tmp , 1 , nullspace ) ) return false ; output . A = nullspace . data [ 0 ] ; output . B = nullspace . data [ 1 ] ; output . C = nullspace . data [ 2 ] ; output . D = nullspace . data [ 3 ] ; output . E = nullspace . data [ 4 ] ; output . F = nullspace . data [ 5 ] ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a random vector where each axis is selected from a uniform distribution . [CODESPLIT] public static Vector3D_F64 createRandom ( double min , double max , Random rand ) { double range = max - min ; Vector3D_F64 a = new Vector3D_F64 ( ) ; a . x = range * rand . nextDouble ( ) + min ; a . y = range * rand . nextDouble ( ) + min ; a . z = range * rand . nextDouble ( ) + min ; return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects a vector which will be perpendicular . [CODESPLIT] public static Vector3D_F64 perpendicularCanonical ( Vector3D_F64 A , Vector3D_F64 output ) { if ( output == null ) output = new Vector3D_F64 ( ) ; // normalize for scaling double scale = Math . abs ( A . x ) + Math . abs ( A . y ) + Math . abs ( A . z ) ; if ( scale == 0 ) { output . set ( 0 , 0 , 0 ) ; } else { double x = A . x / scale ; double y = A . y / scale ; double z = A . z / scale ; // For numerical stability ensure that the largest variable is swapped if ( Math . abs ( x ) > Math . abs ( y ) ) { output . set ( z , 0 , - x ) ; } else { output . set ( 0 , z , - y ) ; } } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the two vectors are identical to within tolerance . Each axis is checked individually . [CODESPLIT] public static boolean isIdentical ( Vector3D_F64 a , Vector3D_F64 b , double tol ) { if ( Math . abs ( a . x - b . x ) > tol ) return false ; if ( Math . abs ( a . y - b . y ) > tol ) return false ; return Math . abs ( a . z - b . z ) <= tol ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rescales the vector such that its normal is equal to one . [CODESPLIT] public static void normalize ( Vector3D_F64 v ) { double a = v . norm ( ) ; v . x /= a ; v . y /= a ; v . z /= a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a matrix from the set of column vectors . Each vector is a column in the new matrix . [CODESPLIT] public static DMatrixRMaj createMatrix ( DMatrixRMaj R , Vector3D_F64 ... v ) { if ( R == null ) { R = new DMatrixRMaj ( 3 , v . length ) ; } for ( int i = 0 ; i < v . length ; i ++ ) { R . set ( 0 , i , v [ i ] . x ) ; R . set ( 1 , i , v [ i ] . y ) ; R . set ( 2 , i , v [ i ] . z ) ; } return R ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts matrices into vectors . All matrices must be vectors with 3 elements . [CODESPLIT] public static Vector3D_F64 convert ( DMatrixRMaj m ) { Vector3D_F64 v = new Vector3D_F64 ( ) ; v . x = ( double ) m . data [ 0 ] ; v . y = ( double ) m . data [ 1 ] ; v . z = ( double ) m . data [ 2 ] ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the acute angle between the two vectors . Computed using the dot product . [CODESPLIT] public static double acute ( GeoTuple3D_F64 a , GeoTuple3D_F64 b ) { double dot = a . x * b . x + a . y * b . y + a . z * b . z ; double value = dot / ( a . norm ( ) * b . norm ( ) ) ; if ( value > 1.0 ) value = 1.0 ; else if ( value < - 1.0 ) value = - 1.0 ; return Math . acos ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > In - place addition< / p > [CODESPLIT] public void plusIP ( GeoTuple3D_F64 a ) { x += a . x ; y += a . y ; z += a . z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Addition< / p > [CODESPLIT] public T plus ( GeoTuple3D_F64 a ) { T ret = createNewInstance ( ) ; ret . x = x + a . x ; ret . y = y + a . y ; ret . z = z + a . z ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scalar multiplication [CODESPLIT] public T times ( double scalar ) { T ret = createNewInstance ( ) ; ret . x = x * scalar ; ret . y = y * scalar ; ret . z = z * scalar ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the two rectangles intersect each other [CODESPLIT] public static boolean intersects ( Rectangle2D_I32 a , Rectangle2D_I32 b ) { return ( a . x0 < b . x1 && a . x1 > b . x0 && a . y0 < b . y1 && a . y1 > b . y0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the intersection between two rectangles . If the rectangles don t intersect then false is returned . [CODESPLIT] public static boolean intersection ( Rectangle2D_I32 a , Rectangle2D_I32 b , Rectangle2D_I32 result ) { if ( ! intersects ( a , b ) ) return false ; result . x0 = Math . max ( a . x0 , b . x0 ) ; result . x1 = Math . min ( a . x1 , b . x1 ) ; result . y0 = Math . max ( a . y0 , b . y0 ) ; result . y1 = Math . min ( a . y1 , b . y1 ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http : // www . ecse . rpi . edu / Homepages / wrf / Research / Short_Notes / pnpoly . html [CODESPLIT] public static boolean containConvex ( Polygon2D_I32 polygon , Point2D_I32 pt ) { final int N = polygon . size ( ) ; boolean c = false ; for ( int i = 0 , j = N - 1 ; i < N ; j = i ++ ) { Point2D_I32 a = polygon . vertexes . data [ i ] ; Point2D_I32 b = polygon . vertexes . data [ j ] ; if ( ( ( a . y > pt . y ) != ( b . y > pt . y ) ) && ( pt . x < ( b . x - a . x ) * ( pt . y - a . y ) / ( b . y - a . y ) + a . x ) ) c = ! c ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the point is contained inside the concave polygon . [CODESPLIT] public static boolean containConcave ( Polygon2D_I32 polygon , Point2D_I32 pt ) { final int N = polygon . size ( ) ; int left = 0 ; int right = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { Point2D_I32 a = polygon . vertexes . data [ i ] ; Point2D_I32 b = polygon . vertexes . data [ i + 1 ] ; if ( ( pt . y >= a . y && pt . y < b . y ) || ( pt . y >= b . y && pt . y < a . y ) ) { // location of line segment along x-axis at y = pt.y double x = b . y == a . y ? pt . x : ( pt . y - a . y ) * ( b . x - a . x ) / ( double ) ( b . y - a . y ) + a . x ; if ( x <= pt . x ) left ++ ; else if ( x > pt . x ) right ++ ; } } Point2D_I32 a = polygon . vertexes . data [ N - 1 ] ; Point2D_I32 b = polygon . vertexes . data [ 0 ] ; if ( ( pt . y >= a . y && pt . y < b . y ) || ( pt . y >= b . y && pt . y < a . y ) ) { // location of line segment along x-axis at y = pt.y double x = b . y == a . y ? pt . x : ( pt . y - pt . y ) * ( b . x - a . x ) / ( double ) ( b . y - a . y ) + a . x ; if ( x <= pt . x ) left ++ ; else if ( x > pt . x ) right ++ ; } return ( left % 2 == 1 && right % 2 == 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "True if the point is contained inside the rectangle [CODESPLIT] public static boolean contains ( RectangleLength2D_I32 a , int x , int y ) { if ( a . getX ( ) <= x && a . getX ( ) + a . getWidth ( ) > x ) { return a . getY ( ) <= y && a . getY ( ) + a . getHeight ( ) > y ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "True if the point is contained inside the rectangle [CODESPLIT] public static boolean contains ( Rectangle2D_I32 a , int x , int y ) { return ( x >= a . x0 && y >= a . y0 && x < a . x1 && y < a . y1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Addition< / p > [CODESPLIT] public T plus ( GeoTuple2D_F64 a ) { T ret = createNewInstance ( ) ; ret . x = x + a . x ; ret . y = y + a . y ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Euclidean distance from the point [CODESPLIT] public double distance ( double x , double y ) { double dx = x - this . x ; double dy = y - this . y ; return Math . sqrt ( dx * dx + dy * dy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the ellipse which point distance is going to be found from [CODESPLIT] public void setEllipse ( EllipseRotated_F64 ellipse ) { this . ellipse = ellipse ; ce = Math . cos ( ellipse . phi ) ; se = Math . sin ( ellipse . phi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the closest point on the ellipse to the specified point . To get the solution call { @link #getClosest () } [CODESPLIT] public void process ( Point2D_F64 point ) { // put point into ellipse's coordinate system double xc = point . x - ellipse . center . x ; double yc = point . y - ellipse . center . y ; // double x = ce * xc + se * yc ; double y = - se * xc + ce * yc ; // initial guess for the angle theta = Math . atan2 ( ellipse . a * y , ellipse . b * x ) ; double a2_m_b2 = ellipse . a * ellipse . a - ellipse . b * ellipse . b ; // use Newton's Method to find the solution int i = 0 ; for ( ; i < maxIterations ; i ++ ) { double c = Math . cos ( theta ) ; double s = Math . sin ( theta ) ; double f = a2_m_b2 * c * s - x * ellipse . a * s + y * ellipse . b * c ; if ( Math . abs ( f ) < tol ) break ; double d = a2_m_b2 * ( c * c - s * s ) - x * ellipse . a * c - y * ellipse . b * s ; theta = theta - f / d ; } // compute solution in ellipse coordinate frame x = ellipse . a * ( double ) Math . cos ( theta ) ; y = ellipse . b * ( double ) Math . sin ( theta ) ; // put back into original coordinate system closest . x = ce * x - se * y + ellipse . center . x ; closest . y = se * x + ce * y + ellipse . center . y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the quaternion into a unit quaternion . [CODESPLIT] public void normalize ( ) { double n = Math . sqrt ( w * w + x * x + y * y + z * z ) ; w /= n ; x /= n ; y /= n ; z /= n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fits the conic to the points . Strongly recommended that you transform the points such that they have zero mean and a standard deviation along x and y axis independently . [CODESPLIT] @ Override public boolean process ( List < Point2D_F64 > points , ConicGeneral_F64 output ) { final int N = points . size ( ) ; if ( N < 3 ) throw new IllegalArgumentException ( \"At least 3 points required\" ) ; A . reshape ( N , 6 ) ; for ( int i = 0 , index = 0 ; i < N ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double x = p . x ; double y = p . y ; A . data [ index ++ ] = x * x ; A . data [ index ++ ] = x * y ; A . data [ index ++ ] = y * y ; A . data [ index ++ ] = x ; A . data [ index ++ ] = y ; A . data [ index ++ ] = 1 ; } if ( ! solver . process ( A , 1 , nullspace ) ) return false ; output . A = nullspace . data [ 0 ] ; output . B = nullspace . data [ 1 ] ; output . C = nullspace . data [ 2 ] ; output . D = nullspace . data [ 3 ] ; output . E = nullspace . data [ 4 ] ; output . F = nullspace . data [ 5 ] ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the area of an arbitrary triangle from 3 - vertices . [CODESPLIT] public static double triangle ( Point2D_F64 a , Point2D_F64 b , Point2D_F64 c ) { double inner = a . x * ( b . y - c . y ) + b . x * ( c . y - a . y ) + c . x * ( a . y - b . y ) ; return Math . abs ( inner / 2.0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Area of a quadrilateral computed from two triangles . [CODESPLIT] public static double quadrilateral ( Quadrilateral_F64 quad ) { double bx = quad . b . x - quad . a . x ; double by = quad . b . y - quad . a . y ; double cx = quad . c . x - quad . a . x ; double cy = quad . c . y - quad . a . y ; double dx = quad . d . x - quad . a . x ; double dy = quad . d . y - quad . a . y ; if ( ( bx * cy - by * cx >= 0 ) == ( cx * dy - cy * dx >= 0 ) ) { return triangle ( quad . a , quad . b , quad . c ) + triangle ( quad . a , quad . c , quad . d ) ; } else { return triangle ( quad . a , quad . b , quad . d ) + triangle ( quad . b , quad . c , quad . d ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Area of a simple polygon . Meaning it can be concave or convex but can t have self intersections [CODESPLIT] public static double polygonSimple ( Polygon2D_F64 poly ) { double total = 0 ; Point2D_F64 v0 = poly . get ( 0 ) ; Point2D_F64 v1 = poly . get ( 1 ) ; for ( int i = 2 ; i < poly . size ( ) ; i ++ ) { Point2D_F64 v2 = poly . get ( i ) ; total += v1 . x * ( v2 . y - v0 . y ) ; v0 = v1 ; v1 = v2 ; } Point2D_F64 v2 = poly . get ( 0 ) ; total += v1 . x * ( v2 . y - v0 . y ) ; v0 = v1 ; v1 = v2 ; v2 = poly . get ( 1 ) ; total += v1 . x * ( v2 . y - v0 . y ) ; return Math . abs ( total / 2.0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point which has the mean location of all the points in the list . This is also known as the centroid . [CODESPLIT] public static Point2D_F64 mean ( List < Point2D_F64 > list , Point2D_F64 mean ) { if ( mean == null ) mean = new Point2D_F64 ( ) ; double x = 0 ; double y = 0 ; for ( Point2D_F64 p : list ) { x += p . getX ( ) ; y += p . getY ( ) ; } x /= list . size ( ) ; y /= list . size ( ) ; mean . set ( x , y ) ; return mean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point which has the mean location of all the points in the array . This is also known as the centroid . [CODESPLIT] public static Point2D_F64 mean ( Point2D_F64 [ ] list , int offset , int length , Point2D_F64 mean ) { if ( mean == null ) mean = new Point2D_F64 ( ) ; double x = 0 ; double y = 0 ; for ( int i = 0 ; i < length ; i ++ ) { Point2D_F64 p = list [ offset + i ] ; x += p . getX ( ) ; y += p . getY ( ) ; } x /= length ; y /= length ; mean . set ( x , y ) ; return mean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the mean / average of two points . [CODESPLIT] public static Point2D_F64 mean ( Point2D_F64 a , Point2D_F64 b , Point2D_F64 mean ) { if ( mean == null ) mean = new Point2D_F64 ( ) ; mean . x = ( a . x + b . x ) / 2.0 ; mean . y = ( a . y + b . y ) / 2.0 ; return mean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the minimal volume { @link georegression . struct . shapes . RectangleLength2D_F64 } which contains all the points . [CODESPLIT] public static RectangleLength2D_F64 bounding ( List < Point2D_F64 > points , RectangleLength2D_F64 bounding ) { if ( bounding == null ) bounding = new RectangleLength2D_F64 ( ) ; double minX = Double . MAX_VALUE , maxX = - Double . MAX_VALUE ; double minY = Double . MAX_VALUE , maxY = - Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; if ( p . x < minX ) minX = p . x ; if ( p . x > maxX ) maxX = p . x ; if ( p . y < minY ) minY = p . y ; if ( p . y > maxY ) maxY = p . y ; } bounding . x0 = minX ; bounding . y0 = minY ; bounding . width = maxX - minX ; bounding . height = maxY - minY ; // make sure rounding doesn't cause a point to be out of bounds bounding . width += Math . max ( 0 , ( maxX - ( bounding . x0 + bounding . width ) ) * 10.0 ) ; bounding . height += Math . max ( 0 , ( maxY - ( bounding . y0 + bounding . height ) ) * 10.0 ) ; return bounding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the minimal volume { @link georegression . struct . shapes . RectangleLength2D_F64 } which contains all the points . [CODESPLIT] public static Rectangle2D_F64 bounding ( List < Point2D_F64 > points , Rectangle2D_F64 bounding ) { if ( bounding == null ) bounding = new Rectangle2D_F64 ( ) ; double minX = Double . MAX_VALUE , maxX = - Double . MAX_VALUE ; double minY = Double . MAX_VALUE , maxY = - Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; if ( p . x < minX ) minX = p . x ; if ( p . x > maxX ) maxX = p . x ; if ( p . y < minY ) minY = p . y ; if ( p . y > maxY ) maxY = p . y ; } bounding . set ( minX , minY , maxX , maxY ) ; return bounding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the points into counter - clockwise order around their center . [CODESPLIT] public static List < Point2D_F64 > orderCCW ( List < Point2D_F64 > points ) { Point2D_F64 center = mean ( points , null ) ; double angles [ ] = new double [ points . size ( ) ] ; for ( int i = 0 ; i < angles . length ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double dx = p . x - center . x ; double dy = p . y - center . y ; angles [ i ] = Math . atan2 ( dy , dx ) ; } int order [ ] = new int [ points . size ( ) ] ; QuickSort_F64 sorter = new QuickSort_F64 ( ) ; sorter . sort ( angles , 0 , points . size ( ) , order ) ; List < Point2D_F64 > out = new ArrayList < Point2D_F64 > ( points . size ( ) ) ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { out . add ( points . get ( order [ i ] ) ) ; } return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the mean and covariance matrix from the set of points . This describes a normal distribution [CODESPLIT] public static void computeNormal ( List < Point2D_F64 > points , Point2D_F64 mean , DMatrix covariance ) { if ( covariance . getNumCols ( ) != 2 || covariance . getNumRows ( ) != 2 ) { if ( covariance instanceof ReshapeMatrix ) { ( ( ReshapeMatrix ) covariance ) . reshape ( 2 , 2 ) ; } else { throw new IllegalArgumentException ( \"Must be a 2x2 matrix\" ) ; } } mean ( points , mean ) ; double xx = 0 , xy = 0 , yy = 0 ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_F64 p = points . get ( i ) ; double dx = p . x - mean . x ; double dy = p . y - mean . y ; xx += dx * dx ; xy += dx * dy ; yy += dy * dy ; } xx /= points . size ( ) ; xy /= points . size ( ) ; yy /= points . size ( ) ; covariance . unsafe_set ( 0 , 0 , xx ) ; covariance . unsafe_set ( 0 , 1 , xy ) ; covariance . unsafe_set ( 1 , 0 , xy ) ; covariance . unsafe_set ( 1 , 1 , yy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Randomly generates points from the specified normal distribution [CODESPLIT] public static List < Point2D_F64 > randomNorm ( Point2D_F64 mean , DMatrix covariance , int count , Random rand , @ Nullable List < Point2D_F64 > output ) { if ( output == null ) output = new ArrayList <> ( ) ; // extract values of covariance double cxx = covariance . get ( 0 , 0 ) ; double cxy = covariance . get ( 0 , 1 ) ; double cyy = covariance . get ( 1 , 1 ) ; // perform cholesky decomposition double sxx = Math . sqrt ( cxx ) ; double sxy = cxy / cxx ; double syy = Math . sqrt ( cyy - sxy * sxy ) ; for ( int i = 0 ; i < count ; i ++ ) { Point2D_F64 p = new Point2D_F64 ( ) ; double x = rand . nextGaussian ( ) ; double y = rand . nextGaussian ( ) ; p . x = mean . x + sxx * x + sxy * y ; p . y = mean . y + sxy * x + syy * y ; output . add ( p ) ; } return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A * x + B * y + C = 0 [CODESPLIT] public void set ( double a , double b , double c ) { this . A = a ; this . B = b ; this . C = c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that A * A + B * B == 1 [CODESPLIT] public void normalize ( ) { double d = Math . sqrt ( A * A + B * B ) ; A /= d ; B /= d ; C /= d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In - place minus operation . this = a - b . [CODESPLIT] public void minus ( Point2D_F64 a , Point2D_F64 b ) { x = a . x - b . x ; y = a . y - b . y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the minimum area bounding rectangle which is aligned to the x and y axis around the list of points . Note ( x0 y0 ) is inclusive and ( x1 y1 ) is exclusive . [CODESPLIT] public static void bounding ( List < Point2D_I32 > points , Rectangle2D_I32 rectangle ) { rectangle . x0 = Integer . MAX_VALUE ; rectangle . y0 = Integer . MAX_VALUE ; rectangle . x1 = Integer . MIN_VALUE ; rectangle . y1 = Integer . MIN_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point2D_I32 p = points . get ( i ) ; if ( p . x < rectangle . x0 ) rectangle . x0 = p . x ; if ( p . x > rectangle . x1 ) rectangle . x1 = p . x ; if ( p . y < rectangle . y0 ) rectangle . y0 = p . y ; if ( p . y > rectangle . y1 ) rectangle . y1 = p . y ; } rectangle . x1 ++ ; rectangle . y1 ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the minimum area bounding rectangle which is aligned to the x and y axis around the polygon . Note ( x0 y0 ) is inclusive and ( x1 y1 ) is exclusive . [CODESPLIT] public static void bounding ( Polygon2D_I32 quad , Rectangle2D_I32 rectangle ) { UtilPolygons2D_I32 . bounding ( quad . vertexes . toList ( ) , rectangle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the polygon is ordered in a counter - clockwise order . This is done by summing up the interior angles . [CODESPLIT] public static boolean isCCW ( List < Point2D_I32 > polygon ) { final int N = polygon . size ( ) ; int sign = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int j = ( i + 1 ) % N ; int k = ( i + 2 ) % N ; if ( isPositiveZ ( polygon . get ( i ) , polygon . get ( j ) , polygon . get ( k ) ) ) { sign ++ ; } else { sign -- ; } } return sign < 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flips the order of points inside the polygon . The first index will remain the same will otherwise be reversed [CODESPLIT] public static void flip ( Polygon2D_I32 a ) { int N = a . size ( ) ; int H = N / 2 ; for ( int i = 1 ; i <= H ; i ++ ) { int j = N - i ; Point2D_I32 tmp = a . vertexes . data [ i ] ; a . vertexes . data [ i ] = a . vertexes . data [ j ] ; a . vertexes . data [ j ] = tmp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the polugon is convex or concave . [CODESPLIT] public static boolean isConvex ( Polygon2D_I32 poly ) { // if the cross product of all consecutive triples is positive or negative then it is convex final int N = poly . size ( ) ; int numPositive = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int j = ( i + 1 ) % N ; int k = ( i + 2 ) % N ; Point2D_I32 a = poly . vertexes . data [ i ] ; Point2D_I32 b = poly . vertexes . data [ j ] ; Point2D_I32 c = poly . vertexes . data [ k ] ; int dx0 = a . x - b . x ; int dy0 = a . y - b . y ; int dx1 = c . x - b . x ; int dy1 = c . y - b . y ; int z = dx0 * dy1 - dy0 * dx1 ; if ( z > 0 ) numPositive ++ ; // z can be zero if there are duplicate points. // not sure if it should throw an exception if its \"bad\" or not } return ( numPositive == 0 || numPositive == N ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the cross product would result in a strictly positive z ( e . g . z &gt ; 0 ) . If true then the order is clockwise . [CODESPLIT] public static boolean isPositiveZ ( Point2D_I32 a , Point2D_I32 b , Point2D_I32 c ) { int dx0 = a . x - b . x ; int dy0 = a . y - b . y ; int dx1 = c . x - b . x ; int dy1 = c . y - b . y ; int z = dx0 * dy1 - dy0 * dx1 ; return z > 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the vertexes of the two polygon s are the same up to the specified tolerance [CODESPLIT] public static boolean isIdentical ( Polygon2D_I32 a , Polygon2D_I32 b ) { if ( a . size ( ) != b . size ( ) ) return false ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( ! a . get ( i ) . equals ( b . get ( i ) ) ) return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the vertexes of the two polygon s are the same up to the specified tolerance and allows for a shift in their order [CODESPLIT] public static boolean isEquivalent ( Polygon2D_I32 a , Polygon2D_I32 b ) { if ( a . size ( ) != b . size ( ) ) return false ; // first find two vertexes which are the same Point2D_I32 a0 = a . get ( 0 ) ; int match = - 1 ; for ( int i = 0 ; i < b . size ( ) ; i ++ ) { if ( a0 . equals ( b . get ( i ) ) ) { match = i ; break ; } } if ( match < 0 ) return false ; // now go in a circle and see if they all line up for ( int i = 1 ; i < b . size ( ) ; i ++ ) { Point2D_I32 ai = a . get ( i ) ; Point2D_I32 bi = b . get ( ( match + i ) % b . size ( ) ) ; if ( ! ai . equals ( bi ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the point which has the mean location of all the points in the list . This is also known as the centroid . [CODESPLIT] public static Point2D_I32 mean ( List < Point2D_I32 > list , Point2D_I32 mean ) { if ( mean == null ) mean = new Point2D_I32 ( ) ; int sumX = 0 , sumY = 0 ; int N = list . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_I32 p = list . get ( i ) ; sumX += p . x ; sumY += p . y ; } mean . x = sumX / N ; mean . y = sumY / N ; return mean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > In - place addition< / p > [CODESPLIT] public void plusIP ( GeoTuple4D_F64 a ) { x += a . x ; y += a . y ; z += a . z ; w += a . w ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In - place scalar multiplication [CODESPLIT] public void timesIP ( double scalar ) { x *= scalar ; y *= scalar ; z *= scalar ; w *= scalar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute value of the component with the largest absolute value [CODESPLIT] public double maxAbs ( ) { double absX = Math . abs ( x ) ; double absY = Math . abs ( y ) ; double absZ = Math . abs ( z ) ; double absW = Math . abs ( w ) ; double found = Math . max ( absX , absY ) ; if ( found < absZ ) found = absZ ; if ( found < absW ) found = absW ; return found ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Fits points to the quadratic polynomial . It s recommended that you apply a linear transform to the points to ensure that they have zero mean and a standard deviation of 1 . Then reverse the transform on the result . A solution is found using the pseudo inverse and inverse by minor matrices . < / p > [CODESPLIT] public static boolean fitMM ( double [ ] data , int offset , int length , PolynomialQuadratic1D_F64 output , @ Nullable DMatrix3x3 work ) { if ( work == null ) work = new DMatrix3x3 ( ) ; final int N = length / 2 ; // Unrolled pseudo inverse // coef = inv(A^T*A)*A^T*y double sx0 = N , sx1 = 0 , sx2 = 0 ; double sx3 = 0 ; double sx4 = 0 ; double b0 = 0 , b1 = 0 , b2 = 0 ; int end = offset + length ; for ( int i = offset ; i < end ; i += 2 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double x2 = x * x ; sx1 += x ; sx2 += x2 ; sx3 += x2 * x ; sx4 += x2 * x2 ; b0 += y ; b1 += x * y ; b2 += x2 * y ; } DMatrix3x3 A = work ; A . set ( sx0 , sx1 , sx2 , sx1 , sx2 , sx3 , sx2 , sx3 , sx4 ) ; if ( ! CommonOps_DDF3 . invert ( A , A ) ) // TODO use a symmetric inverse. Should be slightly faster return false ; // output = inv(A)*B      Unrolled here for speed output . a = A . a11 * b0 + A . a12 * b1 + A . a13 * b2 ; output . b = A . a21 * b0 + A . a22 * b1 + A . a23 * b2 ; output . c = A . a31 * b0 + A . a32 * b1 + A . a33 * b2 ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Fits points to the quadratic polynomial using a QRP linear solver . < / p > [CODESPLIT] public static boolean fitQRP ( double [ ] data , int offset , int length , PolynomialQuadratic1D_F64 output ) { FitPolynomialSolverTall_F64 solver = new FitPolynomialSolverTall_F64 ( ) ; return solver . process ( data , offset , length , output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Fits points to the cubic polynomial . It s recommended that you apply a linear transform to the points to ensure that they have zero mean and a standard deviation of 1 . Then reverse the transform on the result . A solution is found using the pseudo inverse and inverse by minor matrices . < / p > [CODESPLIT] public static boolean fitMM ( double [ ] data , int offset , int length , PolynomialCubic1D_F64 output , @ Nullable DMatrix4x4 A ) { if ( A == null ) A = new DMatrix4x4 ( ) ; final int N = length / 2 ; if ( N < 4 ) throw new IllegalArgumentException ( \"Need at least 4 points and not \" + N ) ; // Unrolled pseudo inverse // coef = inv(A^T*A)*A^T*y double sx1 = 0 , sx2 = 0 , sx3 = 0 , sx4 = 0 , sx5 = 0 , sx6 = 0 ; double b0 = 0 , b1 = 0 , b2 = 0 , b3 = 0 ; int end = offset + length ; for ( int i = offset ; i < end ; i += 2 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double x2 = x * x ; double x3 = x2 * x ; double x4 = x2 * x2 ; sx1 += x ; sx2 += x2 ; sx3 += x3 ; sx4 += x4 ; sx5 += x4 * x ; sx6 += x4 * x2 ; b0 += y ; b1 += x * y ; b2 += x2 * y ; b3 += x3 * y ; } A . set ( N , sx1 , sx2 , sx3 , sx1 , sx2 , sx3 , sx4 , sx2 , sx3 , sx4 , sx5 , sx3 , sx4 , sx5 , sx6 ) ; if ( ! CommonOps_DDF4 . invert ( A , A ) ) // TODO use a symmetric inverse. Should be slightly faster return false ; // output = inv(A)*B      Unrolled here for speed output . a = A . a11 * b0 + A . a12 * b1 + A . a13 * b2 + A . a14 * b3 ; output . b = A . a21 * b0 + A . a22 * b1 + A . a23 * b2 + A . a24 * b3 ; output . c = A . a31 * b0 + A . a32 * b1 + A . a33 * b2 + A . a34 * b3 ; output . d = A . a41 * b0 + A . a42 * b1 + A . a43 * b2 + A . a44 * b3 ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Fits points to a 2D quadratic polynomial . There are two inputs and one output for each data point . It s recommended that you apply a linear transform to the points . < / p > [CODESPLIT] public static boolean fit ( double [ ] data , int offset , int length , PolynomialQuadratic2D_F64 output ) { final int N = length / 3 ; if ( N < 6 ) throw new IllegalArgumentException ( \"Need at least 6 points and not \" + N ) ; // Unrolled pseudo inverse // coef = inv(A^T*A)*A^T*y double sx1 = 0 , sy1 = 0 , sx1y1 = 0 , sx2 = 0 , sy2 = 0 , sx2y1 = 0 , sx1y2 = 0 , sx2y2 = 0 , sx3 = 0 , sy3 = 0 , sx3y1 = 0 , sx1y3 = 0 , sx4 = 0 , sy4 = 0 ; double b0 = 0 , b1 = 0 , b2 = 0 , b3 = 0 , b4 = 0 , b5 = 0 ; int end = offset + length ; for ( int i = offset ; i < end ; i += 3 ) { double x = data [ i ] ; double y = data [ i + 1 ] ; double z = data [ i + 2 ] ; double x2 = x * x ; double x3 = x2 * x ; double x4 = x2 * x2 ; double y2 = y * y ; double y3 = y2 * y ; double y4 = y2 * y2 ; sx1 += x ; sx2 += x2 ; sx3 += x3 ; sx4 += x4 ; sy1 += y ; sy2 += y2 ; sy3 += y3 ; sy4 += y4 ; sx1y1 += x * y ; sx2y1 += x2 * y ; sx1y2 += x * y2 ; sx2y2 += x2 * y2 ; sx3y1 += x3 * y ; sx1y3 += x * y3 ; b0 += z ; b1 += x * z ; b2 += y * z ; b3 += x * y * z ; b4 += x2 * z ; b5 += y2 * z ; } // using a fixed size matrix because the notation is much nicer DMatrix6x6 A = new DMatrix6x6 ( ) ; A . set ( N , sx1 , sy1 , sx1y1 , sx2 , sy2 , sx1 , sx2 , sx1y1 , sx2y1 , sx3 , sx1y2 , sy1 , sx1y1 , sy2 , sx1y2 , sx2y1 , sy3 , sx1y1 , sx2y1 , sx1y2 , sx2y2 , sx3y1 , sx1y3 , sx2 , sx3 , sx2y1 , sx3y1 , sx4 , sx2y2 , sy2 , sx1y2 , sy3 , sx1y3 , sx2y2 , sy4 ) ; DMatrixRMaj _A = new DMatrixRMaj ( 6 , 6 ) ; ConvertDMatrixStruct . convert ( A , _A ) ; // pseudo inverse is required to handle degenerate matrices, e.g. lines LinearSolverDense < DMatrixRMaj > solver = LinearSolverFactory_DDRM . pseudoInverse ( true ) ; if ( ! solver . setA ( _A ) ) return false ; solver . invert ( _A ) ; DMatrixRMaj B = new DMatrixRMaj ( 6 , 1 , true , b0 , b1 , b2 , b3 , b4 , b5 ) ; DMatrixRMaj Y = new DMatrixRMaj ( 6 , 1 ) ; CommonOps_DDRM . mult ( _A , B , Y ) ; // output = inv(A)*B      Unrolled here for speed output . a = Y . data [ 0 ] ; output . b = Y . data [ 1 ] ; output . c = Y . data [ 2 ] ; output . d = Y . data [ 3 ] ; output . e = Y . data [ 4 ] ; output . f = Y . data [ 5 ] ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Euclidean distance between the two specified points [CODESPLIT] public static double distance ( double x0 , double y0 , double z0 , double x1 , double y1 , double z1 ) { return norm ( x1 - x0 , y1 - y0 , z1 - z0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Euclidean distance squared between the two specified points [CODESPLIT] public static double distanceSq ( double x0 , double y0 , double z0 , double x1 , double y1 , double z1 ) { double dx = x1 - x0 ; double dy = y1 - y0 ; double dz = z1 - z0 ; return dx * dx + dy * dy + dz * dz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Randomly generates a set of points on the plane centered at the plane s origin using a uniform distribution . [CODESPLIT] public static List < Point3D_F64 > random ( PlaneNormal3D_F64 plane , double max , int num , Random rand ) { List < Point3D_F64 > ret = new ArrayList <> ( ) ; Vector3D_F64 axisX = new Vector3D_F64 ( ) ; Vector3D_F64 axisY = new Vector3D_F64 ( ) ; UtilPlane3D_F64 . selectAxis2D ( plane . n , axisX , axisY ) ; for ( int i = 0 ; i < num ; i ++ ) { double x = 2 * max * ( rand . nextDouble ( ) - 0.5 ) ; double y = 2 * max * ( rand . nextDouble ( ) - 0.5 ) ; Point3D_F64 p = new Point3D_F64 ( ) ; p . x = plane . p . x + axisX . x * x + axisY . x * y ; p . y = plane . p . y + axisX . y * x + axisY . y * y ; p . z = plane . p . z + axisX . z * x + axisY . z * y ; ret . add ( p ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a list of random points from a uniform distribution along each axis [CODESPLIT] public static List < Point3D_F64 > random ( Point3D_F64 mean , double minX , double maxX , double minY , double maxY , double minZ , double maxZ , int num , Random rand ) { List < Point3D_F64 > ret = new ArrayList <> ( ) ; for ( int i = 0 ; i < num ; i ++ ) { Point3D_F64 p = new Point3D_F64 ( ) ; p . x = mean . x + rand . nextDouble ( ) * ( maxX - minX ) + minX ; p . y = mean . y + rand . nextDouble ( ) * ( maxY - minY ) + minY ; p . z = mean . z + rand . nextDouble ( ) * ( maxZ - minZ ) + minZ ; ret . add ( p ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a list of random points from a normal distribution along each axis [CODESPLIT] public static List < Point3D_F64 > randomN ( Point3D_F64 mean , double stdX , double stdY , double stdZ , int num , Random rand ) { List < Point3D_F64 > ret = new ArrayList <> ( ) ; for ( int i = 0 ; i < num ; i ++ ) { Point3D_F64 p = new Point3D_F64 ( ) ; p . x = mean . x + rand . nextGaussian ( ) * stdX ; p . y = mean . y + rand . nextGaussian ( ) * stdY ; p . z = mean . z + rand . nextGaussian ( ) * stdZ ; ret . add ( p ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the mean of the list of points . [CODESPLIT] public static Point3D_F64 mean ( List < Point3D_F64 > points , Point3D_F64 mean ) { if ( mean == null ) mean = new Point3D_F64 ( ) ; double x = 0 , y = 0 , z = 0 ; for ( Point3D_F64 p : points ) { x += p . x ; y += p . y ; z += p . z ; } mean . x = x / points . size ( ) ; mean . y = y / points . size ( ) ; mean . z = z / points . size ( ) ; return mean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the mean of the list of points up to element num . [CODESPLIT] public static Point3D_F64 mean ( List < Point3D_F64 > points , int num , Point3D_F64 mean ) { if ( mean == null ) mean = new Point3D_F64 ( ) ; double x = 0 , y = 0 , z = 0 ; for ( int i = 0 ; i < num ; i ++ ) { Point3D_F64 p = points . get ( i ) ; x += p . x ; y += p . y ; z += p . z ; } mean . x = x / num ; mean . y = y / num ; mean . z = z / num ; return mean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the minimal volume { @link Box3D_F64 } which contains all the points . [CODESPLIT] public static void boundingBox ( List < Point3D_F64 > points , Box3D_F64 bounding ) { double minX = Double . MAX_VALUE , maxX = - Double . MAX_VALUE ; double minY = Double . MAX_VALUE , maxY = - Double . MAX_VALUE ; double minZ = Double . MAX_VALUE , maxZ = - Double . MAX_VALUE ; for ( int i = 0 ; i < points . size ( ) ; i ++ ) { Point3D_F64 p = points . get ( i ) ; if ( p . x < minX ) minX = p . x ; if ( p . x > maxX ) maxX = p . x ; if ( p . y < minY ) minY = p . y ; if ( p . y > maxY ) maxY = p . y ; if ( p . z < minZ ) minZ = p . z ; if ( p . z > maxZ ) maxZ = p . z ; } bounding . p0 . set ( minX , minY , minZ ) ; bounding . p1 . set ( maxX , maxY , maxZ ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discards any cached principal for the given collection of credentials . [CODESPLIT] public void invalidateAll ( Iterable < JwtContext > credentials ) { credentials . forEach ( context -> cache . invalidate ( context . getJwt ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discards any cached principal for the collection of credentials satisfying the given predicate . [CODESPLIT] public void invalidateAll ( Predicate < ? super JwtContext > predicate ) { cache . asMap ( ) . entrySet ( ) . stream ( ) . map ( entry -> entry . getValue ( ) . getKey ( ) ) . filter ( predicate :: test ) . map ( JwtContext :: getJwt ) . forEach ( cache :: invalidate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the given String collections into a set using case - insensitive matching . If there are multiple instances of the same string but with different capitalization only the first one found will be included . [CODESPLIT] @ SafeVarargs public static Set < String > combineToSet ( Collection < String > ... collections ) { Set < String > result = new HashSet < String > ( ) ; Set < String > lowercaseSet = new HashSet < String > ( ) ; for ( Collection < String > collection : collections ) { if ( collection != null ) { for ( String value : collection ) { if ( ! lowercaseSet . contains ( value . toLowerCase ( ) ) ) { lowercaseSet . add ( value . toLowerCase ( ) ) ; result . add ( value ) ; } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the set of features defined in the server . xml [CODESPLIT] public Set < String > getServerFeatures ( File serverDirectory ) { Set < String > result = getConfigDropinsFeatures ( null , serverDirectory , \"defaults\" ) ; result = getServerXmlFeatures ( result , new File ( serverDirectory , \"server.xml\" ) , null ) ; // add the overrides at the end since they should not be replaced by any previous content return getConfigDropinsFeatures ( result , serverDirectory , \"overrides\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets features from the configDropins s defaults or overrides directory [CODESPLIT] private Set < String > getConfigDropinsFeatures ( Set < String > origResult , File serverDirectory , String folderName ) { Set < String > result = origResult ; File configDropinsFolder ; try { configDropinsFolder = new File ( new File ( serverDirectory , \"configDropins\" ) , folderName ) . getCanonicalFile ( ) ; } catch ( IOException e ) { // skip this directory if its path cannot be queried warn ( \"The \" + serverDirectory + \"/configDropins/\" + folderName + \" directory cannot be accessed. Skipping its server features.\" ) ; debug ( e ) ; return result ; } File [ ] configDropinsXmls = configDropinsFolder . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File dir , String name ) { return name . endsWith ( \".xml\" ) ; } } ) ; if ( configDropinsXmls == null || configDropinsXmls . length == 0 ) { return result ; } // sort the files in alphabetical order so that overrides will happen in the proper order Comparator < File > comparator = new Comparator < File > ( ) { @ Override public int compare ( File left , File right ) { return left . getAbsolutePath ( ) . toLowerCase ( ) . compareTo ( right . getAbsolutePath ( ) . toLowerCase ( ) ) ; } } ; Collections . sort ( Arrays . asList ( configDropinsXmls ) , comparator ) ; for ( File xml : configDropinsXmls ) { Set < String > features = getServerXmlFeatures ( result , xml , null ) ; if ( features != null ) { result = features ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds features from the given server file into the origResult or a new set if origResult is null . [CODESPLIT] private Set < String > getServerXmlFeatures ( Set < String > origResult , File serverFile , List < File > parsedXmls ) { Set < String > result = origResult ; List < File > updatedParsedXmls = parsedXmls != null ? parsedXmls : new ArrayList < File > ( ) ; File canonicalServerFile ; try { canonicalServerFile = serverFile . getCanonicalFile ( ) ; } catch ( IOException e ) { // skip this server.xml if its path cannot be queried warn ( \"The server file \" + serverFile + \" cannot be accessed. Skipping its features.\" ) ; debug ( e ) ; return result ; } updatedParsedXmls . add ( canonicalServerFile ) ; if ( canonicalServerFile . exists ( ) ) { try { Document doc = new XmlDocument ( ) { public Document getDocument ( File file ) throws IOException , ParserConfigurationException , SAXException { createDocument ( file ) ; return doc ; } } . getDocument ( canonicalServerFile ) ; Element root = doc . getDocumentElement ( ) ; NodeList nodes = root . getChildNodes ( ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { if ( nodes . item ( i ) instanceof Element ) { Element child = ( Element ) nodes . item ( i ) ; if ( \"featureManager\" . equals ( child . getNodeName ( ) ) ) { if ( result == null ) { result = new HashSet < String > ( ) ; } result . addAll ( parseFeatureManagerNode ( child ) ) ; } else if ( \"include\" . equals ( child . getNodeName ( ) ) ) { result = parseIncludeNode ( result , canonicalServerFile , child , updatedParsedXmls ) ; } } } } catch ( IOException | ParserConfigurationException | SAXException e ) { // just skip this server.xml if it cannot be parsed warn ( \"The server file \" + serverFile + \" cannot be parsed. Skipping its features.\" ) ; debug ( e ) ; return result ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse features from an include node . [CODESPLIT] private Set < String > parseIncludeNode ( Set < String > origResult , File serverFile , Element node , List < File > updatedParsedXmls ) { Set < String > result = origResult ; String includeFileName = node . getAttribute ( \"location\" ) ; if ( includeFileName == null || includeFileName . trim ( ) . isEmpty ( ) ) { return result ; } File includeFile = null ; if ( isURL ( includeFileName ) ) { try { File tempFile = File . createTempFile ( \"serverFromURL\" , \".xml\" ) ; FileUtils . copyURLToFile ( new URL ( includeFileName ) , tempFile , COPY_FILE_TIMEOUT_MILLIS , COPY_FILE_TIMEOUT_MILLIS ) ; includeFile = tempFile ; } catch ( IOException e ) { // skip this xml if it cannot be accessed from URL warn ( \"The server file \" + serverFile + \" includes a URL \" + includeFileName + \" that cannot be accessed. Skipping the included features.\" ) ; debug ( e ) ; return result ; } } else { includeFile = new File ( includeFileName ) ; } try { if ( ! includeFile . isAbsolute ( ) ) { includeFile = new File ( serverFile . getParentFile ( ) . getAbsolutePath ( ) , includeFileName ) . getCanonicalFile ( ) ; } else { includeFile = includeFile . getCanonicalFile ( ) ; } } catch ( IOException e ) { // skip this xml if its path cannot be queried warn ( \"The server file \" + serverFile + \" includes a file \" + includeFileName + \" that cannot be accessed. Skipping the included features.\" ) ; debug ( e ) ; return result ; } if ( ! updatedParsedXmls . contains ( includeFile ) ) { String onConflict = node . getAttribute ( \"onConflict\" ) ; Set < String > features = getServerXmlFeatures ( null , includeFile , updatedParsedXmls ) ; result = handleOnConflict ( result , onConflict , features ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse feature elements from a featureManager node trimming whitespace and treating everything as lowercase . [CODESPLIT] private static Set < String > parseFeatureManagerNode ( Element node ) { Set < String > result = new HashSet < String > ( ) ; NodeList features = node . getElementsByTagName ( \"feature\" ) ; if ( features != null ) { for ( int j = 0 ; j < features . getLength ( ) ; j ++ ) { String content = features . item ( j ) . getTextContent ( ) ; if ( content != null ) { if ( content . contains ( \":\" ) ) { String [ ] split = content . split ( \":\" , 2 ) ; result . add ( split [ 1 ] . trim ( ) . toLowerCase ( ) ) ; } else { result . add ( content . trim ( ) . toLowerCase ( ) ) ; } } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the JSON files corresponding to the product properties from the lib / versions / * . properties files [CODESPLIT] private Set < File > downloadProductJsons ( ) throws PluginExecutionException { // download JSONs Set < File > downloadedJsons = new HashSet < File > ( ) ; for ( ProductProperties properties : propertiesList ) { File json = downloadJsons ( properties . getId ( ) , properties . getVersion ( ) ) ; if ( json != null ) { downloadedJsons . add ( json ) ; } } return downloadedJsons ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Download the JSON file for the given product . [CODESPLIT] private File downloadJsons ( String productId , String productVersion ) { String jsonGroupId = productId + \".features\" ; try { return downloadArtifact ( jsonGroupId , \"features\" , \"json\" , productVersion ) ; } catch ( PluginExecutionException e ) { debug ( \"Cannot find json for productId \" + productId + \", productVersion \" + productVersion , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this scenario is not supported for installing from Maven repository which is one of the following conditions : from parameter is specified ( don t need Maven repositories ) or esa files are specified in the configuration ( not supported with Maven for now ) [CODESPLIT] private boolean hasUnsupportedParameters ( String from , Set < String > pluginListedEsas ) { boolean hasFrom = from != null ; boolean hasPluginListedEsas = ! pluginListedEsas . isEmpty ( ) ; debug ( \"hasFrom: \" + hasFrom ) ; debug ( \"hasPluginListedEsas: \" + hasPluginListedEsas ) ; return hasFrom || hasPluginListedEsas ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the set of all Open Liberty features by scanning the product JSONs . [CODESPLIT] public static Set < String > getOpenLibertyFeatureSet ( Set < File > jsons ) throws PluginExecutionException { Set < String > libertyFeatures = new HashSet < String > ( ) ; for ( File file : jsons ) { Scanner s = null ; try { s = new Scanner ( file ) ; // scan Maven coordinates for artifactIds that belong to the Open Liberty groupId while ( s . findWithinHorizon ( OPEN_LIBERTY_GROUP_ID + \":([^:]*):\" , 0 ) != null ) { MatchResult match = s . match ( ) ; if ( match . groupCount ( ) >= 1 ) { libertyFeatures . add ( match . group ( 1 ) ) ; } } } catch ( FileNotFoundException e ) { throw new PluginExecutionException ( \"The JSON file is not found at \" + file . getAbsolutePath ( ) , e ) ; } finally { if ( s != null ) { s . close ( ) ; } } } return libertyFeatures ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if all features in featuresToInstall are Open Liberty features . [CODESPLIT] private boolean isOnlyOpenLibertyFeatures ( List < String > featuresToInstall ) throws PluginExecutionException { boolean result = containsIgnoreCase ( getOpenLibertyFeatureSet ( downloadedJsons ) , featuresToInstall ) ; debug ( \"Is installing only Open Liberty features? \" + result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the reference collection contains all of the strings in the target collection ignoring case . [CODESPLIT] public static boolean containsIgnoreCase ( Collection < String > reference , Collection < String > target ) { return toLowerCase ( reference ) . containsAll ( toLowerCase ( target ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve download and install features from a Maven repository . This method calls the resolver with the given JSONs and feature list downloads the ESAs corresponding to the resolved features then installs those features . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void installFeatures ( boolean isAcceptLicense , List < String > featuresToInstall ) throws PluginExecutionException { List < File > jsonRepos = new ArrayList < File > ( downloadedJsons ) ; debug ( \"JSON repos: \" + jsonRepos ) ; info ( \"Installing features: \" + featuresToInstall ) ; // override license acceptance if installing only Open Liberty features boolean acceptLicenseMapValue = isOnlyOpenLibertyFeatures ( featuresToInstall ) ? true : isAcceptLicense ; try { Map < String , Object > mapBasedInstallKernel = createMapBasedInstallKernelInstance ( installDirectory ) ; mapBasedInstallKernel . put ( \"install.local.esa\" , true ) ; mapBasedInstallKernel . put ( \"single.json.file\" , jsonRepos ) ; mapBasedInstallKernel . put ( \"features.to.resolve\" , featuresToInstall ) ; mapBasedInstallKernel . put ( \"license.accept\" , acceptLicenseMapValue ) ; if ( isDebugEnabled ( ) ) { mapBasedInstallKernel . put ( \"debug\" , Level . FINEST ) ; } Collection < ? > resolvedFeatures = ( Collection < ? > ) mapBasedInstallKernel . get ( \"action.result\" ) ; if ( resolvedFeatures == null ) { debug ( \"action.exception.stacktrace: \" + mapBasedInstallKernel . get ( \"action.exception.stacktrace\" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( \"action.error.message\" ) ; throw new PluginExecutionException ( exceptionMessage ) ; } else if ( resolvedFeatures . isEmpty ( ) ) { debug ( \"action.exception.stacktrace: \" + mapBasedInstallKernel . get ( \"action.exception.stacktrace\" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( \"action.error.message\" ) ; if ( exceptionMessage == null ) { debug ( \"resolvedFeatures was empty but the install kernel did not issue any messages\" ) ; info ( \"The features are already installed, so no action is needed.\" ) ; return ; } else if ( exceptionMessage . contains ( \"CWWKF1250I\" ) ) { info ( exceptionMessage ) ; info ( \"The features are already installed, so no action is needed.\" ) ; return ; } else { throw new PluginExecutionException ( exceptionMessage ) ; } } Collection < File > artifacts = downloadEsas ( resolvedFeatures ) ; StringBuilder installedFeaturesBuilder = new StringBuilder ( ) ; Collection < String > actionReturnResult = new ArrayList < String > ( ) ; for ( File esaFile : artifacts ) { mapBasedInstallKernel . put ( \"license.accept\" , acceptLicenseMapValue ) ; mapBasedInstallKernel . put ( \"action.install\" , esaFile ) ; if ( to != null ) { mapBasedInstallKernel . put ( \"to.extension\" , to ) ; debug ( \"Installing to extension: \" + to ) ; } Integer ac = ( Integer ) mapBasedInstallKernel . get ( \"action.result\" ) ; debug ( \"action.result: \" + ac ) ; debug ( \"action.error.message: \" + mapBasedInstallKernel . get ( \"action.error.message\" ) ) ; if ( mapBasedInstallKernel . get ( \"action.error.message\" ) != null ) { debug ( \"action.exception.stacktrace: \" + mapBasedInstallKernel . get ( \"action.exception.stacktrace\" ) ) ; String exceptionMessage = ( String ) mapBasedInstallKernel . get ( \"action.error.message\" ) ; debug ( exceptionMessage ) ; throw new PluginExecutionException ( exceptionMessage ) ; } else if ( mapBasedInstallKernel . get ( \"action.install.result\" ) != null ) { actionReturnResult . addAll ( ( Collection < String > ) mapBasedInstallKernel . get ( \"action.install.result\" ) ) ; } } for ( String installResult : actionReturnResult ) { installedFeaturesBuilder . append ( installResult ) . append ( \" \" ) ; } productInfoValidate ( ) ; info ( \"The following features have been installed: \" + installedFeaturesBuilder . toString ( ) ) ; } catch ( PrivilegedActionException e ) { throw new PluginExecutionException ( \"Could not load the jar \" + installJarFile . getAbsolutePath ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Download the override bundle from the repository with the given groupId and artifactId corresponding to the latest version in the range between the current Open Liberty version ( inclusive ) and the next version ( exclusive ) . Returns a string in the format filepath ; BundleName where BundleName is the bundle symbolic name from its manifest . [CODESPLIT] public String getOverrideBundleDescriptor ( String groupId , String artifactId ) throws PluginExecutionException { File overrideJar = downloadOverrideJar ( groupId , artifactId ) ; if ( overrideJar != null && overrideJar . exists ( ) ) { String symbolicName = extractSymbolicName ( overrideJar ) ; if ( symbolicName != null ) { return overrideJar . getAbsolutePath ( ) + \";\" + symbolicName ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the next product version number . [CODESPLIT] public static String getNextProductVersion ( String version ) throws PluginExecutionException { String result = null ; int versionSplittingIndex = version . lastIndexOf ( \".\" ) + 1 ; if ( versionSplittingIndex == 0 ) { throw new PluginExecutionException ( \"Product version \" + version + \" is not in the expected format. It must have period separated version segments.\" ) ; } String quarterVersion = version . substring ( versionSplittingIndex ) ; int nextQuarterSpecifier ; try { nextQuarterSpecifier = Integer . parseInt ( quarterVersion ) + 1 ; } catch ( NumberFormatException e ) { throw new PluginExecutionException ( \"Product version \" + version + \" is not in the expected format. Its last segment is expected to be an integer.\" , e ) ; } result = version . substring ( 0 , versionSplittingIndex ) + nextQuarterSpecifier ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the bundle symbolic name from the jar manifest . [CODESPLIT] public static String extractSymbolicName ( File jar ) throws PluginExecutionException { JarFile jarFile = null ; try { jarFile = new JarFile ( jar ) ; return jarFile . getManifest ( ) . getMainAttributes ( ) . getValue ( \"Bundle-SymbolicName\" ) ; } catch ( IOException e ) { throw new PluginExecutionException ( \"Could not load the jar \" + jar . getAbsolutePath ( ) , e ) ; } finally { if ( jarFile != null ) { try { jarFile . close ( ) ; } catch ( IOException e ) { // nothing to do here } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find latest install map jar from specified directory [CODESPLIT] public static File getMapBasedInstallKernelJar ( File dir ) { File [ ] installMapJars = dir . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File dir , String name ) { return name . startsWith ( INSTALL_MAP_PREFIX ) && name . endsWith ( INSTALL_MAP_SUFFIX ) ; } } ) ; File result = null ; if ( installMapJars != null ) { for ( File jar : installMapJars ) { if ( isReplacementJar ( result , jar ) ) { result = jar ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether file2 can replace file1 as the install map jar . [CODESPLIT] private static boolean isReplacementJar ( File file1 , File file2 ) { if ( file1 == null ) { return true ; } else if ( file2 == null ) { return false ; } else { String version1 = extractVersion ( file1 . getName ( ) ) ; String version2 = extractVersion ( file2 . getName ( ) ) ; return compare ( version1 , version2 ) < 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the extracted version from fileName [CODESPLIT] private static String extractVersion ( String fileName ) { int startIndex = INSTALL_MAP_PREFIX . length ( ) + 1 ; // skip the underscore after the prefix int endIndex = fileName . lastIndexOf ( INSTALL_MAP_SUFFIX ) ; if ( startIndex < endIndex ) { return fileName . substring ( startIndex , endIndex ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs pairwise comparison of version strings including nulls and non - integer components . [CODESPLIT] private static int compare ( String version1 , String version2 ) { if ( version1 == null && version2 == null ) { return 0 ; } else if ( version1 == null && version2 != null ) { return - 1 ; } else if ( version1 != null && version2 == null ) { return 1 ; } String [ ] components1 = version1 . split ( \"\\\\.\" ) ; String [ ] components2 = version2 . split ( \"\\\\.\" ) ; for ( int i = 0 ; i < components1 . length && i < components2 . length ; i ++ ) { int comparison ; try { comparison = new Integer ( components1 [ i ] ) . compareTo ( new Integer ( components2 [ i ] ) ) ; } catch ( NumberFormatException e ) { comparison = components1 [ i ] . compareTo ( components2 [ i ] ) ; } if ( comparison != 0 ) { return comparison ; } } return components1 . length - components2 . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs product validation by running bin / productInfo validate [CODESPLIT] private void productInfoValidate ( ) throws PluginExecutionException { String output = productInfo ( installDirectory , \"validate\" ) ; if ( output == null ) { throw new PluginExecutionException ( \"Could not perform product validation. The productInfo command returned with no output\" ) ; } else if ( output . contains ( \"[ERROR]\" ) ) { throw new PluginExecutionException ( output ) ; } else { info ( \"Product validation completed successfully.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the productInfo command and returns the output [CODESPLIT] public static String productInfo ( File installDirectory , String action ) throws PluginExecutionException { Process pr = null ; InputStream is = null ; Scanner s = null ; Worker worker = null ; try { String command ; if ( OSUtil . isWindows ( ) ) { command = installDirectory + \"\\\\bin\\\\productInfo.bat \" + action ; } else { command = installDirectory + \"/bin/productInfo \" + action ; } pr = Runtime . getRuntime ( ) . exec ( command ) ; worker = new Worker ( pr ) ; worker . start ( ) ; worker . join ( 300000 ) ; if ( worker . exit == null ) { throw new PluginExecutionException ( \"productInfo command timed out\" ) ; } int exitValue = pr . exitValue ( ) ; if ( exitValue != 0 ) { throw new PluginExecutionException ( \"productInfo exited with return code \" + exitValue ) ; } is = pr . getInputStream ( ) ; s = new Scanner ( is ) ; // use regex to match the beginning of the input s . useDelimiter ( \"\\\\A\" ) ; if ( s . hasNext ( ) ) { return s . next ( ) ; } return null ; } catch ( IOException ex ) { throw new PluginExecutionException ( \"productInfo error: \" + ex ) ; } catch ( InterruptedException ex ) { worker . interrupt ( ) ; Thread . currentThread ( ) . interrupt ( ) ; throw new PluginExecutionException ( \"productInfo error: \" + ex ) ; } finally { if ( s != null ) { s . close ( ) ; } if ( is != null ) { try { is . close ( ) ; } catch ( IOException e ) { } } if ( pr != null ) { pr . destroy ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the given artifact is a Spring Boot Uber JAR [CODESPLIT] public static boolean isSpringBootUberJar ( File artifact ) { if ( artifact == null || ! artifact . exists ( ) || ! artifact . isFile ( ) ) { return false ; } try ( JarFile jarFile = new JarFile ( artifact ) ) { Manifest manifest = jarFile . getManifest ( ) ; if ( manifest != null ) { Attributes attributes = manifest . getMainAttributes ( ) ; if ( attributes . getValue ( BOOT_VERSION_ATTRIBUTE ) != null && attributes . getValue ( BOOT_START_CLASS_ATTRIBUTE ) != null ) { return true ; } else { //Checking that there is a spring-boot-VERSION.RELEASE.jar in the BOOT-INF/lib directory //Handles the Gradle case where the spring plugin does not set the properties in the manifest Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; String entryName = entry . getName ( ) ; if ( ! entryName . startsWith ( \"org\" ) && ( entryName . matches ( BOOT_JAR_EXPRESSION ) || entryName . matches ( BOOT_WAR_EXPRESSION ) ) ) { return true ; } } } } } catch ( IOException e ) { } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts Map<String String > to Map<LibertyPropertyI String > . Validates each key property name . [CODESPLIT] public static Map < LibertyPropertyI , String > getArquillianProperties ( Map < String , String > arquillianProperties , Class < ? > cls ) throws ArquillianConfigurationException { Map < LibertyPropertyI , String > props = new HashMap < LibertyPropertyI , String > ( ) ; if ( arquillianProperties != null && ! arquillianProperties . isEmpty ( ) ) { for ( Entry < String , String > entry : arquillianProperties . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( key != null && value != null ) { LibertyPropertyI p = getArquillianProperty ( key , cls ) ; props . put ( p , value ) ; } } } return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that the given key exists in ArquillianProperties [CODESPLIT] private static LibertyPropertyI getArquillianProperty ( String key , Class < ? > cls ) throws ArquillianConfigurationException { try { if ( cls == LibertyManagedObject . LibertyManagedProperty . class ) { return LibertyManagedObject . LibertyManagedProperty . valueOf ( key ) ; } else if ( cls == LibertyRemoteObject . LibertyRemoteProperty . class ) { return LibertyRemoteObject . LibertyRemoteProperty . valueOf ( key ) ; } } catch ( IllegalArgumentException e ) { throw new ArquillianConfigurationException ( \"Property \\\"\" + key + \"\\\" in arquillianProperties does not exist. You probably have a typo.\" ) ; } throw new ArquillianConfigurationException ( \"This should never happen.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We assume any environment that is not headless will have a web browser to display the image in a web page . [CODESPLIT] @ Override public boolean isWorkingInThisEnvironment ( String forFile ) { return ! GraphicsEnvironment . isHeadless ( ) && GenericDiffReporter . isFileExtensionValid ( forFile , GenericDiffReporter . IMAGE_FILE_EXTENSIONS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a request for a text input to the window . <br > <b > Example : < / b > { @code String name = FancyMessageBox . askForTextInput ( What is your nickname? Nicknames ) ; } [CODESPLIT] public static String askForTextInput ( String message , String title ) { return fancyMessageBox . askForTextInput ( message , title ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the message to the window . <br > <b > Example : < / b > { @code FancyMessageBox . showMessage ( Girl programmers rule! Just the Facts ) ; } [CODESPLIT] public static void showMesage ( String message , String title , ImageIcon icon ) { fancyMessageBox . showMessage ( message , title , icon ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a file <div > <b > Example : < / b > { @code parser . parseRtfFile ( filename data ) } < / div > [CODESPLIT] public static String parseRtfFile ( String fileName , Object data ) { try { String text = FileUtils . readFromClassPath ( data . getClass ( ) , fileName ) ; return parse ( text , \"\\\\{\" , \"\\\\}\" , data ) ; } catch ( Exception e ) { throw ObjectUtils . throwAsError ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Paints a circle <div > <b > Example : < / b > { @code circle . paint ( g caller ) } < / div > [CODESPLIT] @ Override public void paint ( Graphics2D g , JPanel caller ) { Color color2 = PenColors . getTransparentVersion ( mainColor , percentTransparent ) ; g . setColor ( color2 ) ; g . fillOval ( x - radius , y - radius , radius * 2 , radius * 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a cool shape fast <div > <b > Example : < / b > { [CODESPLIT] public static void drawShape ( int sides , Color color , int length , int width ) { Tortoise . show ( ) ; Tortoise . setSpeed ( 7 ) ; Tortoise . getBackgroundWindow ( ) . getCanvas ( ) . setBackground ( PenColors . Yellows . Goldenrod ) ; new Text ( \"TKP Java - Make Some Shapes!\" ) . setTopLeft ( 225 , 50 ) . addTo ( Tortoise . getBackgroundWindow ( ) ) ; for ( int i = 0 ; i < sides ; i ++ ) { Tortoise . setPenColor ( color ) ; Tortoise . setPenWidth ( width ) ; Tortoise . move ( length ) ; Tortoise . turn ( 360 / sides ) ; } VirtualProctor . setClassName ( \"Grace Hopper's Class\" ) ; VirtualProctor . setName ( \"Jean Bartik\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws an entire Tortoise -- fast! <div > <b > Example : < / b > { [CODESPLIT] public static void drawTortoise ( ) { Tortoise . show ( ) ; Tortoise . setSpeed ( 9 ) ; Tortoise . getBackgroundWindow ( ) . setBackground ( PenColors . Greens . DarkSeaGreen ) ; new Text ( \"TKP Java - It's the Tortoise!\" ) . setTopLeft ( 200 , 75 ) . addTo ( Tortoise . getBackgroundWindow ( ) ) ; Tortoise . setPenColor ( PenColors . Greens . Green ) ; Tortoise . setPenWidth ( 3 ) ; makeTortoiseBody ( ) ; Tortoise . setPenColor ( PenColors . Browns . Brown ) ; Tortoise . turn ( - 65 ) ; Tortoise . makeTortoiseLeg ( ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 150 ) ; Tortoise . turn ( - 90 ) ; Tortoise . makeTortoiseLeg ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a tortoise can eat a slice of a pizza <div > <b > Example : < / b > { @code tortoise . eatPizza ( pizza ) } < / div > [CODESPLIT] public boolean eatPizza ( Pizza pizza ) { if ( ! pizza . takeSlice ( ) ) { return false ; } if ( this . topping == null ) { return true ; } if ( this . topping != Topping . Cheese ) { return pizza . hasTopping ( topping ) ; } return pizza . wasCooked ( ) && pizza . hasTopping ( topping ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the makeASquare recipe -- #11 . 1 [CODESPLIT] private static void makeASquare ( double length ) { //  If the current length is greater than 10 --#10.2 if ( length > 10 ) { //    Run the recipe moveToTheSquareStart with the current length  --#4.3 moveToTheSquareStart ( length ) ; // //    Do the following 4 times --#7.1  for ( int i = 0 ; i < 4 ; i ++ ) { //      Move the Tortoise the current length   Tortoise . move ( length ) ; //      MakeASquare with the current length divided by 1.7 (recipe below)--#11.3   makeASquare ( length / 1.7 ) ; //          If the current process count is less than 3 (HINT: use 'i') --#9 if ( i < 3 ) { //            Turn the tortoise 90 degrees to the right Tortoise . turn ( 90 ) ; // } //  End Repeat --#7.2   } //  MoveBackToCenter with the current length (recipe below)--#5.3  moveBackToCenter ( length ) ; //  Set the current length to the current length times two --#10.1 length = length * 2 ; } //  End of makeASquare recipe }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the moveToTheSquareStart recipe -- #4 . 1 [CODESPLIT] private static void moveToTheSquareStart ( double length ) { //    Set the pen up for the tortoise --#1.2 Tortoise . setPenUp ( ) ; //    Move the tortoise the current length divided by two --#1.3 Tortoise . move ( length / 2 ) ; //    Turn the tortoise 90 degrees to the left --#2.1 Tortoise . turn ( - 90 ) ; //    Move the tortoise the current length divided by two --#2.2 Tortoise . move ( length / 2 ) ; //    Turn the tortoise 180 degrees to the right --#3.1 Tortoise . turn ( 180 ) ; //    Set the pen down for the tortoise --#3.2 Tortoise . setPenDown ( ) ; //  End of moveToTheSquareStart recipe --#4.2  }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the moveBackToCenter recipe [CODESPLIT] private static void moveBackToCenter ( double length ) { Tortoise . setPenUp ( ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( length / 2 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( length / 2 ) ; Tortoise . turn ( 180 ) ; Tortoise . setPenDown ( ) ; // }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A convenience function to check if two objects are equal . [CODESPLIT] public static boolean isEqual ( Object s1 , Object s2 ) { return s1 == s2 || ( s1 != null ) && s1 . equals ( s2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses a RTF Viewer to display the results of a model ( or text ) <div > <b > Example : < / b > { @code viewer . displayRtfFile ( text ) } < / div > [CODESPLIT] public static void displayRtfFile ( String text ) { try { File file ; file = File . createTempFile ( \"currentStory\" , \".rtf\" ) ; FileWriter f = new FileWriter ( file ) ; f . write ( text ) ; f . close ( ) ; TestUtils . displayFile ( file . getPath ( ) ) ; } catch ( IOException e ) { throw ObjectUtils . throwAsError ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads an int from a String . [CODESPLIT] public static int load ( String i , int defaultValue , boolean stripNonNumeric ) { try { i = stripNonNumeric ? StringUtils . stripNonNumeric ( i , true , true ) : i ; defaultValue = Integer . parseInt ( i ) ; } catch ( Exception ignored ) { } return defaultValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "randomly chooses a number between the minimum and maximum <div > <b > Example : < / b > { @code int grade = NumberUtils . getRandomInt ( 1 100 ) ; } < / div > [CODESPLIT] public static int getRandomInt ( int minimum , int maximum ) { int diff = maximum - minimum ; if ( diff == 0 ) { return maximum ; } else { return RANDOM . nextInt ( diff ) + minimum ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ignore the following It s needed to run the deep dive [CODESPLIT] private Tortoise [ ] throwPizzaParty ( ) { Tortoise karai = new Tortoise ( ) ; Tortoise cecil = new Tortoise ( ) ; Tortoise michealangelo = new Tortoise ( ) ; Tortoise fred = new Tortoise ( ) ; return new Tortoise [ ] { karai , cecil , michealangelo , fred } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if a pizza has a particular kind of topping <div > <b > Example : < / b > { @code pizza . hasTopping ( topping ) } < / div > [CODESPLIT] public boolean hasTopping ( Topping topping ) { for ( Topping toppingToday : toppings ) { if ( toppingToday == topping ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "******************************************************************* [CODESPLIT] public boolean accept ( File pathname ) { String name = pathname . getName ( ) . toLowerCase ( ) ; boolean accept ; accept = ! ( name . equals ( \".\" ) || name . equals ( \"..\" ) ) && ! pathname . isDirectory ( ) ; return accept ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------- Recipe for CreateColorPalette -- #8 . 2 [CODESPLIT] private static void createColorPalette ( ) { Color color1 = PenColors . Reds . Red ; Color color2 = PenColors . Oranges . DarkOrange ; Color color3 = PenColors . Yellows . Gold ; Color color4 = PenColors . Yellows . Yellow ; ColorWheel . addColor ( color1 ) ; ColorWheel . addColor ( color2 ) ; ColorWheel . addColor ( color3 ) ; ColorWheel . addColor ( color4 ) ; ColorWheel . addColor ( color4 ) ; ColorWheel . addColor ( color3 ) ; ColorWheel . addColor ( color2 ) ; ColorWheel . addColor ( color1 ) ; //  ------------- End of createColorPalette recipe --#8.3 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------- Recipe for DrawOctogon -- #9 . 2 [CODESPLIT] private static void drawOctogon ( ) { //     Do the following 8 times --#5.1 for ( int i = 0 ; i < 8 ; i ++ ) { //     Change the pen color of the line the tortoise draws to the next color on the color wheel --#3 Tortoise . setPenColor ( ColorWheel . getNextColor ( ) ) ; //     Move the tortoise 50 pixels --#2 Tortoise . move ( 50 ) ; //     Turn the tortoise 1/8th of 360 degrees to the right --#4 Tortoise . turn ( 360.0 / 8 ) ; //    End Repeat --#5.2  } //    ------------- End of drawOctogon recipe --#10.3 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Captures an image of the result of your program and displays it to you [CODESPLIT] public static void verify ( ) { try { Approvals . verify ( TURTLE . getImage ( ) ) ; } catch ( Exception e ) { throw ObjectUtils . throwAsError ( e ) ; } finally { TortoiseUtils . resetTurtle ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the <a href = http : // en . wikipedia . org / wiki / Taxicab_geometry > Manhattan Distance< / a > between two positions . [CODESPLIT] public static int getDistance ( Point start , Point end ) { return Math . abs ( start . x - end . x ) + Math . abs ( start . y - end . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a copy of the puzzle where the blank swapped with the value in the target position [CODESPLIT] public Puzzle swapBlank ( int target ) { int [ ] copy = Arrays . copyOf ( cells , cells . length ) ; int x = copy [ target ] ; copy [ getBlankIndex ( ) ] = x ; copy [ target ] = 8 ; return new Puzzle ( copy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate the distance between the goal by summing the distance between each cell and its goal . [CODESPLIT] public int getDistanceToGoal ( ) { int distance = 0 ; for ( int i = 0 ; i < cells . length ; i ++ ) { distance += getDistance ( i , cells [ i ] ) ; } return distance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a sound that you can play through your speakers . Use a TKPSound ( there is a list ) <br > <b > Example : < / b > { [CODESPLIT] public synchronized void setSound ( TKPSound mySound ) { String sound = \"soundFiles/\" + mySound + \".wav\" ; URL resource = this . getClass ( ) . getResource ( sound ) ; if ( resource == null ) { resource = this . getClass ( ) . getClassLoader ( ) . getResource ( sound ) ; } if ( resource == null ) { throw new IllegalStateException ( \"Could not get TKPSound: \" + sound ) ; } this . soundUrl = resource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Plays a TKPSound through your speakers . You must first set the TKPSound <br > <b > Example : < / b > { [CODESPLIT] public synchronized void playSound ( ) { final URL sound = this . soundUrl ; new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { Clip clip = AudioSystem . getClip ( ) ; AudioInputStream inputStream = AudioSystem . getAudioInputStream ( sound ) ; clip . open ( inputStream ) ; clip . start ( ) ; } catch ( Exception e ) { System . out . println ( \"play sound error: \" + e . getMessage ( ) + \" for \" + sound ) ; } } } ) . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a formatted string to standard output using the specified format string and arguments and then flushes standard output . [CODESPLIT] public static void printf ( String format , Object ... args ) { out . printf ( LOCALE , format , args ) ; out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a formatted string to standard output using the locale and the specified format string and arguments ; then flushes standard output . [CODESPLIT] public static void printf ( Locale locale , String format , Object ... args ) { out . printf ( locale , format , args ) ; out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unit tests some of the methods in <tt > StdOut< / tt > . [CODESPLIT] public static void main ( String [ ] args ) { // write to stdout StdOut . println ( \"Test\" ) ; StdOut . println ( 17 ) ; StdOut . println ( true ) ; StdOut . printf ( \"%.6f\\n\" , 1.0 / 7.0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recipe for makeAFishyDecision with the numberOfFish [CODESPLIT] public static void makeAFishyDecision ( int numberOfFish ) { // Use a switch...case on the numberOfFish switch ( numberOfFish ) { // When the numberOfFish is -1 case - 1 : // Uncomment to create a string of this image String image = \"../TeachingKidsProgramming.Source.Java/src/main/resources/icons/thumb-up.png\" ; //  Create a new ImageIcon from your image ImageIcon icon = new ImageIcon ( image ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( \"Had a Fish\" , \"Not hungry anymore...\" , icon ) ; // End break ; // When the numberOfFish is 0   case 0 : // Uncomment to create a string of this image String image0 = \"../TeachingKidsProgramming.Source.Java/src/main/resources/icons/information.png\" ; //  Create a new ImageIcon from your image ImageIcon icon0 = new ImageIcon ( image0 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( \"No Fish\" , \"Still hungry\" , icon0 ) ; // End break ; // When the numberOfFish is 1     case 1 : // Uncomment to create a string of this image String image1 = \"../TeachingKidsProgramming.Source.Java/src/main/resources/icons/star.png\" ; // Create a new ImageIcon from your image ImageIcon icon1 = new ImageIcon ( image1 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( \"One Fish\" , \"This one has a little star\" , icon1 ) ; // End break ; // When the numberOfFish is 0     case 2 : // Uncomment to create a string of this image String image2 = \"../TeachingKidsProgramming.Source.Java/src/main/resources/icons/github.png\" ; //  Create a new ImageIcon from your image ImageIcon icon2 = new ImageIcon ( image2 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( \"Two Fish\" , \"Funny things are everywhere\" , icon2 ) ; // End break ; // Otherwise   default : // Uncomment to create a string of this image String image4 = \"../TeachingKidsProgramming.Source.Java/src/main/resources/icons/hint.png\" ; // Create a new ImageIcon from your image ImageIcon icon4 = new ImageIcon ( image4 ) ; // Show a message with the fancy message box this text, this title and this icon... FancyMessageBox . showMesage ( \"Vegetaraian meal\" , \"Fish are icky\" , icon4 ) ; // End break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a line segment between ( <em > x< / em > <sub > 0< / sub > <em > y< / em > <sub > 0< / sub > ) and ( <em > x< / em > <sub > 1< / sub > <em > y< / em > <sub > 1< / sub > ) . [CODESPLIT] public static void line ( double x0 , double y0 , double x1 , double y1 ) { offscreen . draw ( new Line2D . Double ( scaleX ( x0 ) , scaleY ( y0 ) , scaleX ( x1 ) , scaleY ( y1 ) ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws one pixel at ( <em > x< / em > <em > y< / em > ) . This method is private because pixels depend on the display . To achieve the same effect set the pen radius to 0 and call { @code point () } . [CODESPLIT] private static void pixel ( double x , double y ) { offscreen . fillRect ( ( int ) Math . round ( scaleX ( x ) ) , ( int ) Math . round ( scaleY ( y ) ) , 1 , 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a point centered at ( <em > x< / em > <em > y< / em > ) . The point is a filled circle whose radius is equal to the pen radius . To draw a single - pixel point first set the pen radius to 0 . [CODESPLIT] public static void point ( double x , double y ) { double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double r = currentPenRadius ; float scaledPenRadius = ( float ) ( r * DEFAULT_SIZE ) ; if ( scaledPenRadius <= 1 ) pixel ( x , y ) ; else offscreen . fill ( new Ellipse2D . Double ( xs - scaledPenRadius / 2 , ys - scaledPenRadius / 2 , scaledPenRadius , scaledPenRadius ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a circle of the specified radius centered at ( <em > x< / em > <em > y< / em > ) . [CODESPLIT] public static void circle ( double x , double y , double radius ) { if ( ! ( radius >= 0 ) ) throw new IllegalArgumentException ( \"radius must be nonnegative\" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * radius ) ; double hs = factorY ( 2 * radius ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Ellipse2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws an ellipse with the specified semimajor and semiminor axes centered at ( <em > x< / em > <em > y< / em > ) . [CODESPLIT] public static void ellipse ( double x , double y , double semiMajorAxis , double semiMinorAxis ) { if ( ! ( semiMajorAxis >= 0 ) ) throw new IllegalArgumentException ( \"ellipse semimajor axis must be nonnegative\" ) ; if ( ! ( semiMinorAxis >= 0 ) ) throw new IllegalArgumentException ( \"ellipse semiminor axis must be nonnegative\" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * semiMajorAxis ) ; double hs = factorY ( 2 * semiMinorAxis ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Ellipse2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a circular arc of the specified radius centered at ( <em > x< / em > <em > y< / em > ) from angle1 to angle2 ( in degrees ) . [CODESPLIT] public static void arc ( double x , double y , double radius , double angle1 , double angle2 ) { if ( radius < 0 ) throw new IllegalArgumentException ( \"arc radius must be nonnegative\" ) ; while ( angle2 < angle1 ) angle2 += 360 ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * radius ) ; double hs = factorY ( 2 * radius ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Arc2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs , angle1 , angle2 - angle1 , Arc2D . OPEN ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a square of side length 2r centered at ( <em > x< / em > <em > y< / em > ) . [CODESPLIT] public static void square ( double x , double y , double halfLength ) { if ( ! ( halfLength >= 0 ) ) throw new IllegalArgumentException ( \"half length must be nonnegative\" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * halfLength ) ; double hs = factorY ( 2 * halfLength ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Rectangle2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a rectangle of the specified size centered at ( <em > x< / em > <em > y< / em > ) . [CODESPLIT] public static void rectangle ( double x , double y , double halfWidth , double halfHeight ) { if ( ! ( halfWidth >= 0 ) ) throw new IllegalArgumentException ( \"half width must be nonnegative\" ) ; if ( ! ( halfHeight >= 0 ) ) throw new IllegalArgumentException ( \"half height must be nonnegative\" ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( 2 * halfWidth ) ; double hs = factorY ( 2 * halfHeight ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; else offscreen . draw ( new Rectangle2D . Double ( xs - ws / 2 , ys - hs / 2 , ws , hs ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a polygon with the vertices ( <em > x< / em > <sub > 0< / sub > <em > y< / em > <sub > 0< / sub > ) ( <em > x< / em > <sub > 1< / sub > <em > y< / em > <sub > 1< / sub > ) ... ( <em > x< / em > <sub > <em > n< / em > &minus ; 1< / sub > <em > y< / em > <sub > <em > n< / em > &minus ; 1< / sub > ) . [CODESPLIT] public static void polygon ( double [ ] x , double [ ] y ) { if ( x == null ) throw new NullPointerException ( ) ; if ( y == null ) throw new NullPointerException ( ) ; int n1 = x . length ; int n2 = y . length ; if ( n1 != n2 ) throw new IllegalArgumentException ( \"arrays must be of the same length\" ) ; int n = n1 ; GeneralPath path = new GeneralPath ( ) ; path . moveTo ( ( float ) scaleX ( x [ 0 ] ) , ( float ) scaleY ( y [ 0 ] ) ) ; for ( int i = 0 ; i < n ; i ++ ) path . lineTo ( ( float ) scaleX ( x [ i ] )  , ( float ) scaleY ( y [ i ] ) ) ; path . closePath ( ) ; offscreen . draw ( path ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws the specified image centered at ( <em > x< / em > <em > y< / em > ) . The supported image formats are JPEG PNG and GIF . As an optimization the picture is cached so there is no performance penalty for redrawing the same image multiple times ( e . g . in an animation ) . However if you change the picture file after drawing it subsequent calls will draw the original picture . [CODESPLIT] public static void picture ( double x , double y , String filename ) { Image image = getImageFromFile ( filename ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; int ws = image . getWidth ( null ) ; int hs = image . getHeight ( null ) ; if ( ws < 0 || hs < 0 ) throw new IllegalArgumentException ( \"image \" + filename + \" is corrupt\" ) ; offscreen . drawImage ( image , ( int ) Math . round ( xs - ws / 2.0 ) , ( int ) Math . round ( ys - hs / 2.0 ) , null ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws the specified image centered at ( <em > x< / em > <em > y< / em > ) rotated given number of degrees and rescaled to the specified bounding box . The supported image formats are JPEG PNG and GIF . [CODESPLIT] public static void picture ( double x , double y , String filename , double scaledWidth , double scaledHeight , double degrees ) { if ( scaledWidth < 0 ) throw new IllegalArgumentException ( \"width is negative: \" + scaledWidth ) ; if ( scaledHeight < 0 ) throw new IllegalArgumentException ( \"height is negative: \" + scaledHeight ) ; Image image = getImageFromFile ( filename ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; double ws = factorX ( scaledWidth ) ; double hs = factorY ( scaledHeight ) ; if ( ws < 0 || hs < 0 ) throw new IllegalArgumentException ( \"image \" + filename + \" is corrupt\" ) ; if ( ws <= 1 && hs <= 1 ) pixel ( x , y ) ; offscreen . rotate ( Math . toRadians ( - degrees ) , xs , ys ) ; offscreen . drawImage ( image , ( int ) Math . round ( xs - ws / 2.0 ) , ( int ) Math . round ( ys - hs / 2.0 ) , ( int ) Math . round ( ws ) , ( int ) Math . round ( hs ) , null ) ; offscreen . rotate ( Math . toRadians ( + degrees ) , xs , ys ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the given text string in the current font centered at ( <em > x< / em > <em > y< / em > ) . [CODESPLIT] public static void text ( double x , double y , String text ) { if ( text == null ) throw new NullPointerException ( ) ; offscreen . setFont ( font ) ; FontMetrics metrics = offscreen . getFontMetrics ( ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; int ws = metrics . stringWidth ( text ) ; int hs = metrics . getDescent ( ) ; offscreen . drawString ( text , ( float ) ( xs - ws / 2.0 ) , ( float ) ( ys + hs ) ) ; draw ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the given text string in the current font centered at ( <em > x< / em > <em > y< / em > ) and rotated by the specified number of degrees . [CODESPLIT] public static void text ( double x , double y , String text , double degrees ) { if ( text == null ) throw new NullPointerException ( ) ; double xs = scaleX ( x ) ; double ys = scaleY ( y ) ; offscreen . rotate ( Math . toRadians ( - degrees ) , xs , ys ) ; text ( x , y , text ) ; offscreen . rotate ( Math . toRadians ( + degrees ) , xs , ys ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves the drawing to using the specified filename . The supported image formats are JPEG and PNG ; the filename suffix must be <tt > . jpg< / tt > or <tt > . png< / tt > . [CODESPLIT] public static void save ( String filename ) { if ( filename == null ) throw new NullPointerException ( ) ; File file = new File ( filename ) ; String suffix = filename . substring ( filename . lastIndexOf ( ' ' ) + 1 ) ; if ( suffix . toLowerCase ( ) . equals ( \"png\" ) ) { try { ImageIO . write ( onscreenImage , suffix , file ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else if ( suffix . toLowerCase ( ) . equals ( \"jpg\" ) ) { WritableRaster raster = onscreenImage . getRaster ( ) ; WritableRaster newRaster ; newRaster = raster . createWritableChild ( 0 , 0 , width , height , 0 , 0 , new int [ ] { 0 , 1 , 2 } ) ; DirectColorModel cm = ( DirectColorModel ) onscreenImage . getColorModel ( ) ; DirectColorModel newCM = new DirectColorModel ( cm . getPixelSize ( ) , cm . getRedMask ( ) , cm . getGreenMask ( ) , cm . getBlueMask ( ) ) ; BufferedImage rgbBuffer = new BufferedImage ( newCM , newRaster , false , null ) ; try { ImageIO . write ( rgbBuffer , suffix , file ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } else { System . out . println ( \"Invalid image file type: \" + suffix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints to screen any variable information to be viewed . [CODESPLIT] public synchronized static void variable ( String name , Object value ) { if ( ! variable ) { return ; } System . out . println ( timeStamp ( ) + \"*=> \" + name + \" = '\" + ( value == null ? null : value . toString ( ) ) + \"'\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * setup code [CODESPLIT] private void setUpTortoise ( ) { Tortoise . show ( ) ; Tortoise . setSpeed ( 10 ) ; Tortoise . setPenColor ( PenColors . Greens . Green ) ; Tortoise . setPenWidth ( 4 ) ; // TODO: Generate a unique maze png and set as background for this maze instance //call tortoiseMaze.setupBackground }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up a particular set of Colors on the Color Wheel <div > <b > Example : < / b > { [CODESPLIT] public static void setupColorWheel ( ) { ColorWheel . addColor ( PenColors . Grays . Gray ) ; ColorWheel . addColor ( PenColors . Greens . Green ) ; ColorWheel . addColor ( PenColors . Pinks . Pink ) ; ColorWheel . addColor ( PenColors . Purples . Purple ) ; ColorWheel . addColor ( PenColors . Blues . Blue ) ; ColorWheel . addColor ( PenColors . Yellows . Yellow ) ; ColorWheel . addColor ( PenColors . Browns . Brown ) ; ColorWheel . addColor ( PenColors . Oranges . Orange ) ; ColorWheel . addColor ( PenColors . Reds . Red ) ; ColorWheel . addColor ( PenColors . Whites . White ) ; setupBackgroundAndLines ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws an <i > amazing< / > TKP inner P <div > <b > Example : < / b > { [CODESPLIT] public static void draw_inner_tkp_P ( ) { Tortoise . setX ( MakeALogo . XValue + 355 ) ; Tortoise . setY ( MakeALogo . YValue - 135 ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 10 ) ; TKPLogo . curve6 ( ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 50 ) ; Tortoise . hide ( ) ; Tortoise . turn ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws an <i > awesome< / > TKP outer P <div > <b > Example : < / b > { [CODESPLIT] public static void draw_outer_tkp_P ( ) { Tortoise . setAngle ( 180 ) ; Tortoise . setX ( MakeALogo . XValue + 320 ) ; Tortoise . setY ( MakeALogo . YValue ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 120 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 47 ) ; TKPLogo . curve5 ( ) ; Tortoise . move ( 12 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 50 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 43 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws an <i > outstanding< / > TKP right bracket <div > <b > Example : < / b > { [CODESPLIT] public static void drawRightBracket ( ) { Tortoise . setAngle ( - 90 ) ; Tortoise . setX ( MakeALogo . XValue + 250 ) ; Tortoise . setY ( MakeALogo . YValue - 20 ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 30 ) ; TKPLogo . curve3 ( ) ; Tortoise . move ( 40 ) ; TKPLogo . curve4 ( ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 10 ) ; TKPLogo . curve4 ( ) ; Tortoise . move ( 40 ) ; TKPLogo . curve3 ( ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 15 ) ; TKPLogo . curve1 ( ) ; Tortoise . move ( 35 ) ; TKPLogo . curve2 ( ) ; Tortoise . turn ( 180 ) ; TKPLogo . curve2 ( ) ; Tortoise . move ( 35 ) ; TKPLogo . curve1 ( ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 11 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws an <i > incredible< / > TKP T <div > <b > Example : < / b > { [CODESPLIT] public static void draw_tkp_T ( ) { Tortoise . setX ( MakeALogo . XValue ) ; Tortoise . setY ( MakeALogo . YValue ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 120 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( - 75 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 75 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 35 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 95 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 35 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 75 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( - 75 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( - 90 ) ; Tortoise . move ( 120 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 10 ) ; Tortoise . turn ( 80 ) ; Tortoise . move ( 15 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 50 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws an <i > impressive< / > TKP K <div > <b > Example : < / b > { [CODESPLIT] public static void draw_tkp_K ( ) { Tortoise . setAngle ( 180 ) ; Tortoise . setX ( MakeALogo . XValue + 150 ) ; Tortoise . setY ( MakeALogo . YValue + 15 ) ; Tortoise . turn ( 180 ) ; Tortoise . move ( 200 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 128 ) ; Tortoise . turn ( - 150 ) ; Tortoise . move ( 70 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 70 ) ; Tortoise . turn ( - 80 ) ; Tortoise . move ( 80 ) ; Tortoise . turn ( 140 ) ; Tortoise . move ( 40 ) ; Tortoise . turn ( 40 ) ; Tortoise . move ( 60 ) ; Tortoise . turn ( - 130 ) ; Tortoise . move ( 45 ) ; Tortoise . turn ( 90 ) ; Tortoise . move ( 30 ) ; Tortoise . turn ( 2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a turtle instance to a window NOTE : this method must be called BEFORE calling any other methods on turtle instances <p > <b > Example : < / b > { @code multiTurtleWindow . addTurtle ( myTurtle ) } < / p > [CODESPLIT] public void addTurtle ( Turtle turtle ) { if ( turtle == null ) { return ; } turtle . setFrame ( this . getFrame ( ) ) ; turtle . setPanel ( this ) ; this . turtles . add ( turtle ) ; clearPainters ( ) ; configurePainters ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------- Recipe for CreateColorPalette ( HINT : Use PenColors ) -- #8 [CODESPLIT] private static void createColorPalette ( ) { //     Add steel blue to the color wheel --#7 ColorWheel . addColor ( PenColors . Blues . SteelBlue ) ; //     Add dark orchid to the color wheel --#11 ColorWheel . addColor ( PenColors . Purples . DarkOrchid ) ; //     Add dark slate blue to the color wheel --#12 ColorWheel . addColor ( PenColors . Blues . DarkSlateBlue ) ; //     Add teal to the color wheel --#13 ColorWheel . addColor ( PenColors . Blues . Teal ) ; //     Add indigo to the color wheel --#14 ColorWheel . addColor ( PenColors . Purples . Indigo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------- Recipe for AdjustPen -- #9 [CODESPLIT] private static void adjustPen ( ) { //     Change the color of the line the tortoise draws to the next color on the color wheel --#6 Tortoise . setPenColor ( ColorWheel . getNextColor ( ) ) ; //     Increase the tortoises pen width by 1 --#15                                                Tortoise . setPenWidth ( Tortoise . getPenWidth ( ) + 1.0 ) ; //     If the tortoise's pen width is greater than 4, then --#17 if ( Tortoise . getPenWidth ( ) > 4 ) { //     Reset the pen width to 1 --#16 Tortoise . setPenWidth ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------- Recipe for DrawPentagon -- #10 [CODESPLIT] private static void drawPentagon ( ) { //    Do the following 200 times --#2 for ( int i = 0 ; i < 200 ; i ++ ) { //     AdjustPen (recipe below) --#9 adjustPen ( ) ; //     Move the tortoise the length of a side --#4 Tortoise . move ( i ) ; //     Turn the tortoise 1/5th of 360 degrees --#1 Tortoise . turn ( 360.0 / 5 ) ; //     Turn the tortoise 1 more degree --#5 Tortoise . turn ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the speed that a turtle instance moves <p > <b > Example : < / b > { @code myTurtle . setSpeed ( speed ) } < / p > [CODESPLIT] public void setSpeed ( int speed ) { if ( speed != TEST_SPEED ) { if ( speed < 1 || 10 < speed ) { throw new RuntimeException ( String . format ( \"I call shenanigans!!!\\nThe speed '%s' is not between the acceptable range of [1-10]\\nPerhaps you should read the documentation\" , speed ) ) ; } } this . speed = speed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the distance that a turtle instance moves in pixels <p > <b > Example : < / b > { @code myTurtle . move ( 100 ) } < / p > [CODESPLIT] public void move ( Number amount ) { double max = MAX_MOVE_AMOUNT ; Saver < Double > s = penDown ? new Mover ( new Point ( getX ( ) , getY ( ) ) ) : new EmptyMover ( ) ; animate ( amount . doubleValue ( ) , max , s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws a lightning bolt of a specified length <p > <b > Example : < / b > { @code myTurtle . drawLightning ( length ) } < / p > [CODESPLIT] public void drawLightning ( int length ) { this . setX ( 50 ) ; this . setY ( 350 ) ; this . setSpeed ( 10 ) ; for ( int i = 1 ; i < 5 ; i ++ ) { this . setPenWidth ( i * 4 ) ; this . turn ( 65 + i ) ; this . move ( length ) ; this . turn ( - 65 ) ; this . move ( length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Paints a diamond <div > <b > Example : < / b > { @code diamond . paint ( g caller ) } < / div > [CODESPLIT] @ Override public void paint ( Graphics2D g , JPanel caller ) { Color color2 = PenColors . getTransparentVersion ( mainColor , percentTransparent ) ; g . setColor ( color2 ) ; int width = 400 ; int height = 300 ; g . rotate ( 50 ) ; g . fillRect ( x , y , width , height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------- Recipe for WeaveOneLayer -- #9 [CODESPLIT] public static double weaveOneLayer ( double length , double zoom ) { //    Do the following 6 times --#5 for ( int i = 0 ; i < 6 ; i ++ ) { //     DrawTriangle (recipe below) --#4.2 drawTriangle ( length ) ; //     Turn the tortoise 1/6th of 360 degrees to the right --#7 Tortoise . turn ( 360.0 / 6 ) ; //     Increase the length of the line by the current zoom --#8.1 length += zoom ; //    End Repeat --#10.2 } return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------- Recipe for DrawTriangle -- #4 [CODESPLIT] public static void drawTriangle ( double length ) { //    Do the following 3 times --#3.1 for ( int i = 0 ; i < 3 ; i ++ ) { //     Move the tortoise the length of a line --#1.1 Tortoise . move ( length ) ; //     Turn the tortoise 1/3rd of 360 degrees --#2 Tortoise . turn ( 360.0 / 3 ) ; //    End Repeat --#3.2 } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random integer uniformly in [ a b ) . [CODESPLIT] public static int uniform ( int a , int b ) { if ( b <= a ) throw new IllegalArgumentException ( \"Invalid range\" ) ; if ( ( long ) b - a >= Integer . MAX_VALUE ) throw new IllegalArgumentException ( \"Invalid range\" ) ; return a + uniform ( b - a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random real number uniformly in [ a b ) . [CODESPLIT] public static double uniform ( double a , double b ) { if ( ! ( a < b ) ) throw new IllegalArgumentException ( \"Invalid range\" ) ; return a + uniform ( ) * ( b - a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random integer from a geometric distribution with success probability <em > p< / em > . [CODESPLIT] public static int geometric ( double p ) { if ( ! ( p >= 0.0 && p <= 1.0 ) ) throw new IllegalArgumentException ( \"Probability must be between 0.0 and 1.0\" ) ; // using algorithm given by Knuth return ( int ) Math . ceil ( Math . log ( uniform ( ) ) / Math . log ( 1.0 - p ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random integer from a Poisson distribution with mean &lambda ; . [CODESPLIT] public static int poisson ( double lambda ) { if ( ! ( lambda > 0.0 ) ) throw new IllegalArgumentException ( \"Parameter lambda must be positive\" ) ; if ( Double . isInfinite ( lambda ) ) throw new IllegalArgumentException ( \"Parameter lambda must not be infinite\" ) ; // using algorithm given by Knuth // see http://en.wikipedia.org/wiki/Poisson_distribution int k = 0 ; double p = 1.0 ; double L = Math . exp ( - lambda ) ; do { k ++ ; p *= uniform ( ) ; } while ( p >= L ) ; return k - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random integer from the specified discrete distribution . [CODESPLIT] public static int discrete ( double [ ] a ) { if ( a == null ) throw new NullPointerException ( \"argument array is null\" ) ; double EPSILON = 1E-14 ; double sum = 0.0 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( ! ( a [ i ] >= 0.0 ) ) throw new IllegalArgumentException ( \"array entry \" + i + \" must be nonnegative: \" + a [ i ] ) ; sum = sum + a [ i ] ; } if ( sum > 1.0 + EPSILON || sum < 1.0 - EPSILON ) throw new IllegalArgumentException ( \"sum of array entries does not approximately equal 1.0: \" + sum ) ; // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while ( true ) { double r = uniform ( ) ; sum = 0.0 ; for ( int i = 0 ; i < a . length ; i ++ ) { sum = sum + a [ i ] ; if ( sum > r ) return i ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unit test . [CODESPLIT] public static void main ( String [ ] args ) { int N = Integer . parseInt ( args [ 0 ] ) ; if ( args . length == 2 ) StdRandom . setSeed ( Long . parseLong ( args [ 1 ] ) ) ; double [ ] t = { .5 , .3 , .1 , .1 } ; StdOut . println ( \"seed = \" + StdRandom . getSeed ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { StdOut . printf ( \"%2d \" , uniform ( 100 ) ) ; StdOut . printf ( \"%8.5f \" , uniform ( 10.0 , 99.0 ) ) ; StdOut . printf ( \"%5b \" , bernoulli ( .5 ) ) ; StdOut . printf ( \"%7.5f \" , gaussian ( 9.0 , .2 ) ) ; StdOut . printf ( \"%2d \" , discrete ( t ) ) ; StdOut . println ( ) ; } String [ ] a = \"A B C D E F G\" . split ( \" \" ) ; for ( String s : a ) StdOut . print ( s + \" \" ) ; StdOut . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets http http according to path . It must exist as http . [CODESPLIT] public void setAsset ( String path ) { try { this . asset = new URL ( path ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( \"URL does not exist: \" + path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads http from the http [CODESPLIT] private byte [ ] loadAssetFromURL ( ) { try { URLConnection cnn = this . asset . openConnection ( ) ; cnn . connect ( ) ; int b = - 1 ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; while ( ( b = cnn . getInputStream ( ) . read ( ) ) != - 1 ) stream . write ( b ) ; stream . flush ( ) ; stream . close ( ) ; this . lastModified = cnn . getLastModified ( ) ; this . expireAt = cnn . getExpiration ( ) ; this . ETAG = cnn . getHeaderField ( HttpHeaders . ETAG ) ; return stream . toByteArray ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capitalizes the first character of the word given . It will convert i to I [CODESPLIT] public static final String capitalizeFirstChar ( String word ) { return Character . toUpperCase ( word . charAt ( 0 ) ) + word . substring ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Un capitalizes the first character of the word given . It will convert i to I [CODESPLIT] public static final String unCapitalizeFirstChar ( String word ) { return Character . toLowerCase ( word . charAt ( 0 ) ) + word . substring ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create as a { @link User } resource . [CODESPLIT] @ RobeService ( group = \"User\" , description = \"Create as a User resource.\" ) @ POST @ UnitOfWork public User create ( @ RobeAuth Credentials credentials , @ Valid User model ) { return userDao . create ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates a single { @link User } matches with the given id . <p > Status Code : Not Found 404 Not Matches 412 [CODESPLIT] @ RobeService ( group = \"User\" , description = \"Updates a single User matches with the given id.\" ) @ PUT @ UnitOfWork @ Path ( \"{id}\" ) public User update ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id , @ Valid User model ) { if ( ! id . equals ( model . getOid ( ) ) ) { throw new WebApplicationException ( Response . status ( 412 ) . build ( ) ) ; } User entity = userDao . findById ( id ) ; if ( entity == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } userDao . detach ( entity ) ; return userDao . update ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates a single { @link User } matches with the given id . <p > Status Code : Not Found 404 Not Matches 412 [CODESPLIT] @ RobeService ( group = \"User\" , description = \"Updates a single User matches with the given id.\" ) @ PATCH @ UnitOfWork @ Path ( \"{id}\" ) public User merge ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id , User model ) { if ( ! id . equals ( model . getOid ( ) ) ) throw new WebApplicationException ( Response . status ( 412 ) . build ( ) ) ; User dest = userDao . findById ( id ) ; if ( dest == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } Fields . mergeRight ( model , dest ) ; return userDao . update ( dest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns modified list of the entities regarding to the search model . { @inheritDoc } [CODESPLIT] public Criteria < T > queryAllStrict ( SearchModel search ) { Query < T > query = new Query <> ( new TransformerImpl < T > ( this . currentSession ( ) ) ) ; return query . createCriteria ( this . getEntityClass ( ) , search ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns modified list of the entities regarding to the search model . { @inheritDoc } [CODESPLIT] public Criteria < Map < String , Object > > queryAll ( SearchModel search ) { Transformer < Map < String , Object > > transformer = new TransformerImpl <> ( this . currentSession ( ) , Criteria . MAP_CLASS ) ; Query < Map < String , Object > > query = new Query <> ( transformer ) ; return query . createCriteria ( this . getEntityClass ( ) , search ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns modified list of the entities regarding to the search model . { @inheritDoc } [CODESPLIT] public < E > Criteria < E > queryAll ( SearchModel search , Class < E > transformClass ) { Query < E > query = new Query <> ( new TransformerImpl <> ( this . currentSession ( ) , transformClass ) ) ; return query . createCriteria ( this . getEntityClass ( ) , search ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns modified list of the entities regarding to the search model . { @inheritDoc } [CODESPLIT] public List < T > findAllStrict ( SearchModel search ) { Result < T > resultPair = queryAllStrict ( search ) . pairList ( ) ; search . setTotalCount ( resultPair . getTotalCount ( ) ) ; ResponseHeadersUtil . addTotalCount ( search ) ; return resultPair . getList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns modified list of the entities regarding to the search model . { @inheritDoc } [CODESPLIT] public List < Map < String , Object > > findAll ( SearchModel search ) { Result < Map < String , Object > > resultPair = queryAll ( search ) . pairList ( ) ; search . setTotalCount ( resultPair . getTotalCount ( ) ) ; ResponseHeadersUtil . addTotalCount ( search ) ; return resultPair . getList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns modified list of the entities regarding to the search model . { @inheritDoc } [CODESPLIT] public < E > List < E > findAll ( SearchModel search , Class < E > transformClass ) { Result < E > resultPair = queryAll ( search , transformClass ) . pairList ( ) ; search . setTotalCount ( resultPair . getTotalCount ( ) ) ; ResponseHeadersUtil . addTotalCount ( search ) ; return resultPair . getList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public T findById ( Class < ? extends RobeEntity > clazz , Serializable oid ) { return ( T ) currentSession ( ) . get ( clazz , Preconditions . checkNotNull ( oid ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helps to fix path [CODESPLIT] private String fixPath ( String path ) { if ( ! path . isEmpty ( ) ) { if ( ! path . endsWith ( \"/\" ) ) return path + ' ' ; else return path ; } else return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the environment . [CODESPLIT] @ Override public void run ( T configuration , Environment environment ) throws Exception { if ( configuration . getMail ( ) != null && configuration instanceof HasMailConfiguration && configuration instanceof Configuration ) { MailManager . setSender ( new MailSender ( configuration . getMail ( ) ) ) ; } else { LOGGER . warn ( \"Bundle included but no configuration (mail) found at yml.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link HTriggerInfo } resource . [CODESPLIT] @ RobeService ( group = \"QuartzJob\" , description = \"Create a HTriggerInfo resource.\" ) @ POST @ UnitOfWork public HTriggerInfo create ( @ RobeAuth Credentials credentials , @ Valid HTriggerInfo model ) { //Save to the DB HJobInfo job = jobDao . findById ( model . getJobOid ( ) ) ; if ( job == null ) { throw new WebApplicationException ( \"Job not found\" , Response . Status . NOT_FOUND ) ; } if ( ! job . getProvider ( ) . equals ( HibernateJobInfoProvider . class ) ) { throw new WebApplicationException ( \"Trigger is not provided by an editable source.\" , Response . Status . PRECONDITION_FAILED ) ; } HTriggerInfo record = triggerDao . create ( model ) ; return new TriggerInfoDTO ( record ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update a HTriggerInfo resource with the matches given id . <p > Status Code : Not Found 404 Not Matches 412 [CODESPLIT] @ RobeService ( group = \"QuartzJob\" , description = \"Update a HTriggerInfo resource with the matches given id.\" ) @ PUT @ UnitOfWork @ Path ( \"{id}\" ) public HTriggerInfo update ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id , @ Valid HTriggerInfo model ) { HJobInfo job = jobDao . findById ( model . getJobOid ( ) ) ; if ( job == null ) { throw new WebApplicationException ( \"Job not found\" , Response . Status . NOT_FOUND ) ; } if ( ! job . getProvider ( ) . equals ( HibernateJobInfoProvider . class ) ) { throw new WebApplicationException ( \"Trigger is not provided by an editable source.\" , Response . Status . PRECONDITION_FAILED ) ; } if ( ! id . equals ( model . getOid ( ) ) ) { throw new WebApplicationException ( \"URL trigger id is not same with the payload id\" , Response . Status . FORBIDDEN ) ; } HTriggerInfo entity = triggerDao . findById ( id ) ; if ( entity == null ) { throw new WebApplicationException ( \"Trigger not found\" , Response . Status . NOT_FOUND ) ; } triggerDao . detach ( entity ) ; model = triggerDao . update ( model ) ; return new TriggerInfoDTO ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all HTriggerInfo as a collection with the matches given job id . [CODESPLIT] @ RobeService ( group = \"HJobInfo\" , description = \"Returns all HTriggerInfo as a collection with the matches given job id.\" ) @ PUT @ Path ( \"{id}/resume\" ) @ UnitOfWork public boolean resume ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id ) { HTriggerInfo info = triggerDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobManager . getInstance ( ) . resumeTrigger ( TriggerKey . triggerKey ( info . getName ( ) , info . getGroup ( ) ) ) ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates Join Query for the given JoinCriteria [CODESPLIT] public static String joinToString ( CriteriaJoin criteriaJoin ) { StringBuilder builder = new StringBuilder ( \"LEFT OUTER JOIN \" ) . append ( criteriaJoin . getEntityClass ( ) . getName ( ) ) . append ( \" \" ) . append ( criteriaJoin . getAlias ( ) ) . append ( \" \" ) . append ( \" ON \" ) ; if ( criteriaJoin . getJoinRelations ( ) . size ( ) == 0 ) { throw new RuntimeException ( \"Not found any Join Relations in \" + criteriaJoin . getAlias ( ) + \" Join Criteria ! \" ) ; } StringJoiner joiner = new StringJoiner ( \" AND \" ) ; List < JoinRelation > relationList = criteriaJoin . getJoinRelations ( ) ; for ( JoinRelation joinRelation : relationList ) { StringBuilder relationBuilder = new StringBuilder ( \"\\n\" ) . append ( joinRelation . getRelationCriteria ( ) . getAlias ( ) ) . append ( \".\" ) . append ( joinRelation . getRelationField ( ) ) . append ( \"=\" ) . append ( joinRelation . getJoinedCriteria ( ) . getAlias ( ) ) . append ( \".\" ) . append ( joinRelation . getJoinedField ( ) ) ; joiner . add ( relationBuilder . toString ( ) ) ; } if ( joiner . length ( ) > 0 ) { builder . append ( joiner . toString ( ) ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combines the token and cookie sentence [CODESPLIT] public static String getTokenSentence ( BasicToken token ) throws Exception { if ( token == null ) return tokenKey + \"=\" + cookieSentence ; String sentence = tokenKey + \"=\" + token . getTokenString ( ) + cookieSentence ; //TODO: Learn how to calculate expire according to the browser time. //        sentence = sentence.replace(\"{expireDate}\", token.getExpirationDate().toGMTString()); return sentence ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the expiration date of token . Renews and puts at header of response . [CODESPLIT] @ Override public void filter ( ContainerRequestContext requestContext , ContainerResponseContext responseContext ) throws IOException { String authToken = extractAuthTokenFromCookieList ( requestContext . getHeaders ( ) . getFirst ( \"Cookie\" ) ) ; if ( authToken != null && authToken . length ( ) != 0 ) { try { BasicToken token = new BasicToken ( authToken ) ; if ( token . isExpired ( ) ) { LOGGER . debug ( \"ExpireDate : \" + token . getExpirationDate ( ) . toString ( ) ) ; LOGGER . debug ( \"Now: \" + DateTime . now ( ) . toDate ( ) . toString ( ) ) ; responseContext . getHeaders ( ) . putSingle ( \"Set-Cookie\" , getTokenSentence ( null ) ) ; responseContext . setStatusInfo ( Response . Status . UNAUTHORIZED ) ; responseContext . setEntity ( \"Token expired. Please login again.\" ) ; LOGGER . info ( \"Token expired. Please login again.\" ) ; } else { token . setExpiration ( token . getMaxAge ( ) ) ; if ( ! logoutPath . equals ( requestContext . getUriInfo ( ) . getPath ( ) ) ) { String cookie = getTokenSentence ( token ) ; responseContext . getHeaders ( ) . putSingle ( \"Set-Cookie\" , cookie ) ; } } } catch ( Exception e ) { LOGGER . error ( \"Token re-creation failed\" , e . getMessage ( ) ) ; responseContext . setStatusInfo ( Response . Status . UNAUTHORIZED ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the accesstoken from cookies [CODESPLIT] private String extractAuthTokenFromCookieList ( String cookieList ) { if ( cookieList == null || cookieList . length ( ) == 0 ) { return null ; } String [ ] cookies = cookieList . split ( \";\" ) ; for ( String cookie : cookies ) { if ( cookie . trim ( ) . startsWith ( tokenKey ) ) { return cookie . trim ( ) . substring ( tokenKey . length ( ) + 1 ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers any Guice - bound providers or root resources . [CODESPLIT] public static void registerGuiceBound ( Injector injector , final JerseyEnvironment environment ) { while ( injector != null ) { for ( Key < ? > key : injector . getBindings ( ) . keySet ( ) ) { Type type = key . getTypeLiteral ( ) . getType ( ) ; if ( type instanceof Class ) { Class < ? > c = ( Class ) type ; if ( isProviderClass ( c ) ) { logger . info ( \"Registering {} as a provider class\" , c . getName ( ) ) ; environment . register ( c ) ; } else if ( isRootResourceClass ( c ) ) { // Jersey rejects resources that it doesn't think are acceptable // Including abstract classes and interfaces, even if there is a valid Guice binding. if ( Resource . isAcceptable ( c ) ) { logger . info ( \"Registering {} as a root resource class\" , c . getName ( ) ) ; environment . register ( c ) ; } else { logger . warn ( \"Class {} was not registered as a resource. Bind a concrete implementation instead.\" , c . getName ( ) ) ; } } } } injector = injector . getParent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check username and password for authentication <p > Status Code : UNAUTHORIZED no have authentication . INTERNAL_SERVER_ERROR Blocked . [CODESPLIT] @ POST @ UnitOfWork ( flushMode = FlushMode . ALWAYS ) @ Path ( \"login\" ) @ Timed public Response login ( @ Context HttpServletRequest request , Map < String , String > credentials ) throws Exception { Optional < User > user = userDao . findByUsername ( credentials . get ( \"username\" ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . UNAUTHORIZED ) ; } else if ( user . get ( ) . getPassword ( ) . equals ( credentials . get ( \"password\" ) ) ) { if ( ! user . get ( ) . isActive ( ) ) return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( \"User blocked.\" ) . build ( ) ; Map < String , String > attributes = new HashMap <> ( ) ; attributes . put ( \"userAgent\" , request . getHeader ( \"User-Agent\" ) ) ; attributes . put ( \"remoteAddr\" , request . getRemoteAddr ( ) ) ; BasicToken token = new BasicToken ( user . get ( ) . getUserId ( ) , user . get ( ) . getEmail ( ) , DateTime . now ( ) , attributes ) ; token . setExpiration ( token . getMaxAge ( ) ) ; credentials . remove ( \"password\" ) ; credentials . put ( \"domain\" , TokenBasedAuthResponseFilter . getTokenSentence ( null ) ) ; user . get ( ) . setLastLoginTime ( DateTime . now ( ) . toDate ( ) ) ; user . get ( ) . setFailCount ( 0 ) ; logAction ( new ActionLog ( \"LOGIN\" , null , user . get ( ) . toString ( ) , true , request . getRemoteAddr ( ) ) ) ; return Response . ok ( ) . header ( \"Set-Cookie\" , TokenBasedAuthResponseFilter . getTokenSentence ( token ) ) . entity ( credentials ) . build ( ) ; } else { if ( ! user . get ( ) . isActive ( ) ) { logAction ( new ActionLog ( \"LOGIN\" , \"Blocked\" , user . get ( ) . toString ( ) , false , request . getRemoteAddr ( ) ) ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( \"User blocked.\" ) . build ( ) ; } int failCount = user . get ( ) . getFailCount ( ) + 1 ; user . get ( ) . setFailCount ( failCount ) ; boolean block = failCount >= Integer . valueOf ( ( String ) SystemParameterCache . get ( \"USER_BLOCK_FAIL_LIMIT\" , \"3\" ) ) ; if ( block ) user . get ( ) . setActive ( false ) ; userDao . update ( user . get ( ) ) ; logAction ( new ActionLog ( \"LOGIN\" , \"Wrong Password\" , user . get ( ) . toString ( ) , false , request . getRemoteAddr ( ) ) ) ; return Response . status ( Response . Status . UNAUTHORIZED ) . build ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log out [CODESPLIT] @ POST @ UnitOfWork @ Path ( \"logout\" ) @ Timed public Response logout ( @ RobeAuth Credentials credentials , @ Context HttpServletRequest request ) throws Exception { Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . UNAUTHORIZED ) ; } else { BasicToken . clearPermissionCache ( credentials . getUsername ( ) ) ; user . get ( ) . setLastLogoutTime ( DateTime . now ( ) . toDate ( ) ) ; logAction ( new ActionLog ( \"LOGOUT\" , null , user . get ( ) . toString ( ) , true , request . getRemoteAddr ( ) ) ) ; return Response . ok ( ) . header ( \"Set-Cookie\" , TokenBasedAuthResponseFilter . getTokenSentence ( null ) ) . build ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "User Information Returns <p > Status Code : UNAUTHORIZED no have authentication . [CODESPLIT] @ Path ( \"profile\" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public User getProfile ( @ RobeAuth Credentials credentials ) { Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . UNAUTHORIZED ) ; } else return user . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "User Change Password <p > Status Code : NOT_FOUND not found user . PRECONDITION_FAILED change passsword error . [CODESPLIT] @ POST @ UnitOfWork @ Path ( \"password\" ) @ Timed public Response changePassword ( @ Context HttpServletRequest request , @ RobeAuth Credentials credentials , Map < String , String > passwords ) { Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { throw new WebApplicationException ( Response . Status . NOT_FOUND ) ; } else if ( user . get ( ) . getPassword ( ) . equals ( passwords . get ( \"password\" ) ) ) { if ( passwords . get ( \"newPassword\" ) . equals ( passwords . get ( \"newPasswordRepeat\" ) ) ) { user . get ( ) . setPassword ( passwords . get ( \"newPassword\" ) ) ; return Response . status ( Response . Status . OK ) . entity ( \"Your password has been updated\" ) . build ( ) ; } else { return Response . status ( Response . Status . PRECONDITION_FAILED ) . entity ( \"Your new password does not match.\" ) . build ( ) ; } } else { return Response . status ( Response . Status . PRECONDITION_FAILED ) . entity ( \"Your password is incorrect.\" ) . build ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @link Optional } { @link io . robe . auth . Credentials } instance from provided tokenString [CODESPLIT] @ Override public Optional < BasicToken > authenticate ( String tokenString ) throws AuthenticationException { tokenString = tokenString . replaceAll ( \"\\\"\" , \"\" ) ; LOGGER . debug ( \"Authenticating from database:  \" + tokenString ) ; try { // Decode tokenString and get user BasicToken token = new BasicToken ( tokenString ) ; Optional < UserEntry > user = ( Optional < UserEntry > ) userStore . findByUsername ( token . getUsername ( ) ) ; if ( ! user . isPresent ( ) ) { LOGGER . warn ( \"User is not available: \" + tokenString ) ; return Optional . empty ( ) ; } // If user exists and active than check Service Permissions for authorization controls if ( user . get ( ) . isActive ( ) ) { if ( token . getPermissions ( ) == null ) { LOGGER . debug ( \"Loading Permissions from DB: \" + tokenString ) ; Set < String > permissions = new HashSet < String > ( ) ; Set < PermissionEntry > rolePermissions = new HashSet < PermissionEntry > ( ) ; //If user role is a group than add sub role permissions to group Optional < RoleEntry > role = ( Optional < RoleEntry > ) roleStore . findByRoleId ( user . get ( ) . getRoleId ( ) ) ; getAllRolePermissions ( role . get ( ) , rolePermissions ) ; for ( PermissionEntry permission : rolePermissions ) { if ( permission . getType ( ) . equals ( PermissionEntry . Type . SERVICE ) ) { Optional < ? extends ServiceEntry > service = serviceStore . findByCode ( permission . getRestrictedItemId ( ) ) ; if ( service . isPresent ( ) ) { permissions . add ( service . get ( ) . getPath ( ) + \":\" + service . get ( ) . getMethod ( ) ) ; } } } // Create credentials with user info and permission list token . setPermissions ( Collections . unmodifiableSet ( permissions ) ) ; } else { LOGGER . debug ( \"Loading Permissions from Cache: \" + tokenString ) ; } return Optional . ofNullable ( token ) ; } } catch ( Exception e ) { LOGGER . error ( tokenString , e ) ; } return Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill permission list with role and sub - role permissions recursively . [CODESPLIT] private void getAllRolePermissions ( RoleEntry parent , Set < PermissionEntry > rolePermissions ) { rolePermissions . addAll ( permissionStore . findByRoleId ( parent . getId ( ) ) ) ; Set < RoleGroupEntry > roleGroupEntries = ( Set < RoleGroupEntry > ) roleGroupStore . findByGroupId ( parent . getId ( ) ) ; for ( RoleGroupEntry entry : roleGroupEntries ) { Optional < RoleEntry > role = ( Optional < RoleEntry > ) roleStore . findByRoleId ( entry . getRoleId ( ) ) ; getAllRolePermissions ( role . get ( ) , rolePermissions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all HJobInfo as a collection [CODESPLIT] @ RobeService ( group = \"HJobInfo\" , description = \"Returns all HJobInfo as a collection.\" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public Collection < JobInfoDTO > getAll ( @ RobeAuth Credentials credentials , @ SearchParam SearchModel search ) { List < JobInfoDTO > dtoList = new LinkedList <> ( ) ; for ( HJobInfo info : jobDao . findAllStrict ( search ) ) { JobInfoDTO dto = new JobInfoDTO ( info ) ; try { if ( ! JobManager . getInstance ( ) . isScheduledJob ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . UNSCHEDULED ) ; } else { if ( JobManager . getInstance ( ) . isPausedJob ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . PAUSED ) ; } else { dto . setStatus ( JobInfoDTO . Status . ACTIVE ) ; } } } catch ( SchedulerException e ) { e . printStackTrace ( ) ; } dtoList . add ( dto ) ; } return dtoList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a HJobInfo resource with the matches given id . <p > Status Code : Not Found 404 [CODESPLIT] @ RobeService ( group = \"HJobInfo\" , description = \"Returns a HJobInfo resource with the matches given id.\" ) @ Path ( \"{id}\" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public HJobInfo get ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id ) { HJobInfo entity = jobDao . findById ( id ) ; if ( entity == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all HTriggerInfo as a collection with the matches given job id . [CODESPLIT] @ RobeService ( group = \"HJobInfo\" , description = \"Returns all HTriggerInfo as a collection with the matches given job id.\" ) @ GET @ Path ( \"{id}/triggers\" ) @ UnitOfWork public List < TriggerInfoDTO > getJobTriggers ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id ) { List < TriggerInfoDTO > dtos = new LinkedList <> ( ) ; for ( HTriggerInfo info : triggerDao . findByJobOid ( id ) ) { TriggerInfoDTO dto = new TriggerInfoDTO ( info ) ; try { if ( ! JobManager . getInstance ( ) . isScheduledTrigger ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . UNSCHEDULED ) ; } else { if ( JobManager . getInstance ( ) . isPausedTrigger ( dto . getName ( ) , dto . getGroup ( ) ) ) { dto . setStatus ( JobInfoDTO . Status . PAUSED ) ; } else { dto . setStatus ( JobInfoDTO . Status . ACTIVE ) ; } } } catch ( SchedulerException e ) { e . printStackTrace ( ) ; } dtos . add ( dto ) ; } return dtos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all HTriggerInfo as a collection with the matches given job id . [CODESPLIT] @ RobeService ( group = \"HJobInfo\" , description = \"Returns all HTriggerInfo as a collection with the matches given job id.\" ) @ PUT @ Path ( \"{id}/schedule\" ) @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public boolean schedule ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id ) { HJobInfo info = jobDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobInfo dto = new HibernateJobInfoProvider ( ) . getJob ( info . getJobClass ( ) ) ; JobDetail detail = HibernateJobInfoProvider . convert2JobDetail ( dto ) ; Set < Trigger > triggers = new HashSet <> ( dto . getTriggers ( ) . size ( ) ) ; for ( TriggerInfo triggerInfo : dto . getTriggers ( ) ) { if ( triggerInfo . getType ( ) . equals ( TriggerInfo . Type . CRON ) || triggerInfo . getType ( ) . equals ( TriggerInfo . Type . SIMPLE ) ) { triggers . add ( HibernateJobInfoProvider . convert2Trigger ( triggerInfo , dto ) ) ; } } JobManager . getInstance ( ) . scheduleJob ( detail , triggers , false ) ; return true ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all HTriggerInfo as a collection with the matches given job id . [CODESPLIT] @ RobeService ( group = \"HJobInfo\" , description = \"Returns all HTriggerInfo as a collection with the matches given job id.\" ) @ PUT @ Path ( \"{id}/pause\" ) @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public boolean pause ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id ) { HJobInfo info = jobDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobManager . getInstance ( ) . pauseJob ( info . getName ( ) , info . getGroup ( ) ) ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all HTriggerInfo as a collection with the matches given job id . [CODESPLIT] @ RobeService ( group = \"HJobInfo\" , description = \"Returns all HTriggerInfo as a collection with the matches given job id.\" ) @ PUT @ Path ( \"{id}/resume\" ) @ UnitOfWork public boolean resume ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id ) { HJobInfo info = jobDao . findById ( id ) ; if ( info == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } try { JobManager . getInstance ( ) . resumeJob ( info . getName ( ) , info . getGroup ( ) ) ; } catch ( SchedulerException e ) { e . printStackTrace ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the desired method call with a new instance of the { @link ResourceServlet } implementation . Transaction management is done here . [CODESPLIT] private final void dispatch ( Method call , UnitOfWork uow , HttpServletRequest req , HttpServletResponse resp ) { if ( uow == null ) { try { ResourceServlet servlet = GuiceBundle . getInjector ( ) . getInstance ( servletClass ) ; call . invoke ( servlet , req , resp ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else { SessionFactory sessionFactory = GuiceBundle . getInjector ( ) . getInstance ( SessionFactory . class ) ; Session session = sessionFactory . openSession ( ) ; try { configureSession ( session , uow ) ; ManagedSessionContext . bind ( session ) ; beginTransaction ( session , uow ) ; try { ResourceServlet servlet = ( singleton == null ) ? singleton : GuiceBundle . getInjector ( ) . getInstance ( servletClass ) ; call . invoke ( servlet , req , resp ) ; commitTransaction ( session , uow ) ; } catch ( Exception e ) { rollbackTransaction ( session , uow ) ; throw new RuntimeException ( e ) ; } } finally { session . close ( ) ; ManagedSessionContext . unbind ( sessionFactory ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a projection to this list of projections after wrapping it with an alias [CODESPLIT] public ProjectionList add ( Projection projection , String alias ) { return add ( Projections . alias ( projection , alias ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get menu for logged user [CODESPLIT] @ RobeService ( group = \"Menu\" , description = \"Get menu for logged user\" ) @ Path ( \"user\" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) @ CacheControl ( noCache = true ) public List < MenuItem > getUserHierarchicalMenu ( @ RobeAuth Credentials credentials ) { Optional < User > user = userDao . findByUsername ( credentials . getUsername ( ) ) ; Set < Permission > permissions = new HashSet < Permission > ( ) ; Role parent = roleDao . findById ( user . get ( ) . getRoleOid ( ) ) ; getAllRolePermissions ( parent , permissions ) ; Set < String > menuOids = new HashSet < String > ( ) ; List < MenuItem > items = convertMenuToMenuItem ( menuDao . findHierarchicalMenu ( ) ) ; items = readMenuHierarchical ( items ) ; for ( Permission permission : permissions ) { if ( permission . getType ( ) . equals ( Permission . Type . MENU ) ) { menuOids . add ( permission . getRestrictedItemOid ( ) ) ; } } List < MenuItem > permittedItems = new LinkedList < MenuItem > ( ) ; createMenuWithPermissions ( menuOids , items , permittedItems ) ; return permittedItems ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Menu } resource . [CODESPLIT] @ RobeService ( group = \"Menu\" , description = \"Create a Menu resource.\" ) @ POST @ UnitOfWork public Menu create ( @ RobeAuth Credentials credentials , @ Valid Menu model ) { return menuDao . create ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an identical JobDetail instance from the given parameters . [CODESPLIT] public static JobDetail convert2JobDetail ( JobInfo info ) { JobKey jobKey = JobKey . jobKey ( info . getName ( ) ) ; JobDetail jobDetail = newJob ( info . getJobClass ( ) ) . withIdentity ( jobKey ) . build ( ) ; return jobDetail ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an identical Trigger instance from the given annotation . [CODESPLIT] public static Trigger convert2Trigger ( TriggerInfo trig , JobInfo job ) { TriggerBuilder < Trigger > builder = newTrigger ( ) ; builder . withIdentity ( trig . getName ( ) , trig . getGroup ( ) ) ; builder . forJob ( job . getName ( ) , job . getGroup ( ) ) ; switch ( trig . getType ( ) ) { case CRON : setStartEndTime ( trig , builder ) ; if ( ! trig . getCron ( ) . isEmpty ( ) ) builder . withSchedule ( CronScheduleBuilder . cronSchedule ( trig . getCron ( ) ) ) ; break ; case SIMPLE : setStartEndTime ( trig , builder ) ; setCountIntervalValues ( trig , builder ) ; break ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helps to set count and intervals [CODESPLIT] private static void setCountIntervalValues ( TriggerInfo dto , TriggerBuilder < org . quartz . Trigger > builder ) { SimpleScheduleBuilder builderSc = SimpleScheduleBuilder . simpleSchedule ( ) ; if ( dto . getRepeatCount ( ) != 0 ) builderSc . withRepeatCount ( dto . getRepeatCount ( ) ) ; if ( dto . getRepeatInterval ( ) > 0 ) builderSc . withIntervalInMilliseconds ( dto . getRepeatInterval ( ) ) ; builder . withSchedule ( builderSc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helps to set start and end times [CODESPLIT] private static void setStartEndTime ( TriggerInfo dto , TriggerBuilder < org . quartz . Trigger > builder ) { if ( dto . getStartTime ( ) > - 1 ) builder . startAt ( new Date ( dto . getStartTime ( ) ) ) ; else builder . startNow ( ) ; if ( dto . getEndTime ( ) > - 1 ) builder . endAt ( new Date ( dto . getEndTime ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes the mail item into the queue and manages the mail sender thread . If thread is alive it will send the mail at the end of current thread queue . Else a new thread will be created and started . [CODESPLIT] public static boolean sendMail ( MailItem item ) { LOGGER . debug ( \"Mail : \" + item . toString ( ) ) ; boolean result = queue . add ( item ) ; LOGGER . info ( \"Adding mail to queue. Queue size: \" + queue . size ( ) ) ; // If thread is alive leave the job to it // Else create new thread and start. if ( ! consumerThread . isAlive ( ) ) { consumerThread = new Thread ( consumer ) ; consumerThread . start ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called to write the message body . [CODESPLIT] @ Override public void write ( OutputStream output ) throws IOException , WebApplicationException { //Write until available bytes are less than buffer. while ( bufferedInputStream . available ( ) > buffer . length ) { bufferedInputStream . read ( buffer ) ; output . write ( buffer ) ; } //Write one more time to finish and exit. buffer = new byte [ bufferedInputStream . available ( ) ] ; bufferedInputStream . read ( buffer ) ; output . write ( buffer ) ; bufferedInputStream . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the environment . Forwards the configuration to Quartz . Collect { @link JobInfoProvider } classes Initializes scheduler Collects all subtypes of { @link org . quartz . Job } annotated with { @link RobeJob } including { @link @RobeTrigger } s * Collects additional triggers from providers * Registers them all for future control . [CODESPLIT] @ Override public void run ( T configuration , Environment environment ) { QuartzConfiguration qConf = configuration . getQuartz ( ) ; try { initializeScheduler ( qConf . getProperties ( ) ) ; collectAndScheduleJobs ( qConf . getScanPackages ( ) ) ; environment . lifecycle ( ) . manage ( new ManagedQuartz ( getOnStartJobs ( ) , getOnStopJobs ( ) ) ) ; } catch ( SchedulerException e ) { LOGGER . error ( \"SchedulerException:\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize scheduler and start JobManager [CODESPLIT] private void initializeScheduler ( Properties properties ) throws SchedulerException { SchedulerFactory factory = new StdSchedulerFactory ( properties ) ; Scheduler scheduler = factory . getScheduler ( ) ; scheduler . start ( ) ; JobManager . initialize ( scheduler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an ordered list of the fields which belongs to the given class . [CODESPLIT] protected final Collection < FieldEntry > getFields ( Class clazz ) { LinkedList < FieldEntry > fieldList = getAllFields ( clazz ) ; Collections . sort ( fieldList , new Comparator < FieldEntry > ( ) { public int compare ( FieldEntry o1 , FieldEntry o2 ) { return o1 . compareTo ( o2 ) ; } } ) ; return fieldList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a map of the fields which belongs to the given class with field name as key . [CODESPLIT] protected final Map < String , Field > getFieldMap ( Class clazz ) { Map < String , Field > fieldList = new HashMap < String , Field > ( ) ; for ( FieldEntry entry : getAllFields ( clazz ) ) { Field field = entry . getValue ( ) ; fieldList . put ( field . getName ( ) , field ) ; } return fieldList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds Hibernate bundle for PROVIDER connection Asset bundle for io . robe . admin screens and Class scanners for <ul > <li > Entities< / li > <li > HealthChecks< / li > <li > Providers< / li > <li > InjectableProviders< / li > <li > Resources< / li > <li > Tasks< / li > <li > Managed objects< / li > < / ul > [CODESPLIT] @ Override public void initialize ( Bootstrap < T > bootstrap ) { T config = loadConfiguration ( bootstrap ) ; RobeHibernateBundle < T > hibernateBundle = RobeHibernateBundle . createInstance ( config . getHibernate ( ) . getScanPackages ( ) , config . getHibernate ( ) . getEntities ( ) ) ; List < Module > modules = new LinkedList <> ( ) ; modules . add ( new HibernateModule ( hibernateBundle ) ) ; bootstrap . addBundle ( new GuiceBundle < T > ( modules , bootstrap . getApplication ( ) . getConfigurationClass ( ) ) ) ; bootstrap . addBundle ( hibernateBundle ) ; bootstrap . addBundle ( new TokenAuthBundle < T > ( ) ) ; bootstrap . addCommand ( new InitializeCommand ( this , hibernateBundle ) ) ; bootstrap . addBundle ( new QuartzBundle < T > ( ) ) ; bootstrap . addBundle ( new MailBundle < T > ( ) ) ; bootstrap . addBundle ( new AdvancedAssetBundle < T > ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } In addition adds exception mapper . [CODESPLIT] @ UnitOfWork @ Override public void run ( T configuration , Environment environment ) throws Exception { TokenFactory . authenticator = new TokenAuthenticator ( GuiceBundle . getInjector ( ) . getInstance ( UserDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( ServiceDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( RoleDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( PermissionDao . class ) , GuiceBundle . getInjector ( ) . getInstance ( RoleGroupDao . class ) ) ; TokenFactory . tokenKey = configuration . getAuth ( ) . getTokenKey ( ) ; environment . jersey ( ) . register ( RobeExceptionMapper . class ) ; environment . jersey ( ) . register ( new ExceptionMapperBinder ( true ) ) ; environment . jersey ( ) . register ( new SearchFactoryProvider . Binder ( ) ) ; environment . jersey ( ) . register ( MultiPartFeature . class ) ; if ( configuration . getRecaptcha ( ) != null ) { new ReCaptchaValidation ( configuration . getRecaptcha ( ) ) ; } JobPersister jobPersister = new JobPersister ( QuartzBundle . JOBS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all services and menus collection with the matches given Role id . [CODESPLIT] @ RobeService ( group = \"Permission\" , description = \"Returns all services and menus collection with the matches given Role id.\" ) @ GET @ Path ( \"{id}/permissions\" ) @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public Map < String , Object > getRolePermissions ( @ RobeAuth Credentials credentials , @ PathParam ( \"id\" ) String id ) { List < Permission > permissions = new ArrayList <> ( ) ; List < Service > services = new ArrayList <> ( ) ; List < Menu > menus = new ArrayList <> ( ) ; Role role = roleDao . findById ( id ) ; getAllRolePermissions ( role , permissions ) ; for ( Permission permission : permissions ) { if ( permission . getType ( ) . equals ( PermissionEntry . Type . SERVICE ) ) { Service service = serviceDao . findById ( permission . getRestrictedItemOid ( ) ) ; if ( service != null ) { if ( services . indexOf ( service ) == - 1 ) { services . add ( service ) ; } } } else if ( permission . getType ( ) . equals ( PermissionEntry . Type . MENU ) ) { Menu menu = menuDao . findById ( permission . getRestrictedItemOid ( ) ) ; if ( menu != null ) { if ( menus . indexOf ( menu ) == - 1 ) { menus . add ( menu ) ; } } } } Map < String , Object > response = new HashMap <> ( ) ; response . put ( \"menu\" , menus ) ; response . put ( \"service\" , services ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Role } resource . [CODESPLIT] @ RobeService ( group = \"Role\" , description = \"Create a Role resource.\" ) @ POST @ UnitOfWork public Role create ( @ RobeAuth Credentials credentials , @ Valid Role model ) { return roleDao . create ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create { @link Service ) resource and matches with the given id . [CODESPLIT] @ RobeService ( group = \"Service\" , description = \"Create Service resource and return given Service path link at header Location=example/{id].\" ) @ POST @ UnitOfWork public Service create ( @ RobeAuth Credentials credentials , @ Valid Service model ) { return serviceDao . create ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "refreshing service with description <p > TODO exception handler [CODESPLIT] @ Path ( \"refresh\" ) @ GET @ UnitOfWork public Response refreshServices ( @ RobeAuth Credentials credentials ) { GuiceConfiguration configuration = GuiceBundle . getConfiguration ( ) ; Reflections reflections = new Reflections ( configuration . getScanPackages ( ) , this . getClass ( ) . getClassLoader ( ) ) ; Set < Class < ? > > services = reflections . getTypesAnnotatedWith ( Path . class ) ; int count = 0 ; for ( Class service : services ) { String parentPath = \"/\" + ( ( Path ) service . getAnnotation ( Path . class ) ) . value ( ) ; for ( Method method : service . getMethods ( ) ) { String httpMethod = ifServiceGetHttpMethod ( method ) ; if ( httpMethod == null ) { continue ; } String path = parentPath ; path = extractPath ( method , path ) ; io . robe . admin . hibernate . entity . Service entity = serviceDao . findByPathAndMethod ( path , ServiceEntry . Method . valueOf ( httpMethod ) ) ; RobeService robeService = ( RobeService ) method . getAnnotation ( RobeService . class ) ; if ( entity != null ) { if ( robeService != null ) { entity . setDescription ( robeService . description ( ) ) ; entity . setGroup ( robeService . group ( ) ) ; serviceDao . update ( entity ) ; } continue ; } entity = new io . robe . admin . hibernate . entity . Service ( ) ; entity . setPath ( path ) ; entity . setMethod ( io . robe . admin . hibernate . entity . Service . Method . valueOf ( httpMethod ) ) ; if ( robeService != null ) { entity . setDescription ( robeService . description ( ) ) ; entity . setGroup ( robeService . group ( ) ) ; } else { entity . setGroup ( \"UNGROUPED\" ) ; entity . setDescription ( \"\" ) ; } entity . setDescription ( entity . getDescription ( ) + \" (\" + entity . getMethod ( ) + \" \" + entity . getPath ( ) + \")\" ) ; serviceDao . create ( entity ) ; count ++ ; } } return Response . ok ( count ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses or wraps the exception and transforms it to a human readable json loaded response . [CODESPLIT] @ Override public Response toResponse ( Exception e ) { String id = System . nanoTime ( ) + \"\" ; LOGGER . error ( id , e ) ; if ( e instanceof RobeRuntimeException ) { return ( ( RobeRuntimeException ) e ) . getResponse ( id ) ; } else if ( e instanceof ConstraintViolationException ) { ConstraintViolationException exception = ( ConstraintViolationException ) e ; RobeMessage [ ] errors = new RobeMessage [ exception . getConstraintViolations ( ) . size ( ) ] ; int i = 0 ; for ( ConstraintViolation error : exception . getConstraintViolations ( ) ) { errors [ i ++ ] = new RobeMessage . Builder ( ) . message ( error . getMessage ( ) ) . status ( 422 ) . id ( id ) . build ( ) ; } return Response . status ( 422 ) . entity ( errors ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } else if ( e instanceof WebApplicationException ) { WebApplicationException we = ( WebApplicationException ) e ; RobeMessage error = new RobeMessage . Builder ( ) . id ( id ) . message ( we . getMessage ( ) ) . status ( we . getResponse ( ) . getStatus ( ) ) . build ( ) ; return Response . fromResponse ( we . getResponse ( ) ) . entity ( error ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } else { if ( e . getClass ( ) . getName ( ) . equals ( \"org.hibernate.exception.ConstraintViolationException\" ) ) { if ( e . getCause ( ) != null && e . getCause ( ) . getMessage ( ) != null ) { RobeMessage error = new RobeMessage . Builder ( ) . message ( e . getCause ( ) . getMessage ( ) . split ( \"for\" ) [ 0 ] ) . status ( Response . Status . CONFLICT . getStatusCode ( ) ) . id ( id ) . build ( ) ; return Response . status ( Response . Status . CONFLICT ) . entity ( error ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } } RobeMessage error = new RobeMessage . Builder ( ) . message ( e . getMessage ( ) ) . id ( id ) . build ( ) ; return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( error ) . type ( MediaType . APPLICATION_JSON ) . build ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure method for Token generation configurations and encryptor configure [CODESPLIT] public static void configure ( TokenBasedAuthConfiguration configuration ) { encryptor . setPoolSize ( configuration . getPoolSize ( ) ) ; // This would be a good value for a 4-core system if ( configuration . getServerPassword ( ) . equals ( \"auto\" ) ) { encryptor . setPassword ( UUID . randomUUID ( ) . toString ( ) ) ; } else { encryptor . setPassword ( configuration . getServerPassword ( ) ) ; } encryptor . setAlgorithm ( configuration . getAlgorithm ( ) ) ; encryptor . initialize ( ) ; BasicToken . defaultMaxAge = configuration . getMaxage ( ) ; //Create cache for permissions. cache = CacheBuilder . newBuilder ( ) . expireAfterAccess ( defaultMaxAge , TimeUnit . SECONDS ) . expireAfterWrite ( defaultMaxAge , TimeUnit . SECONDS ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates attribute has with userAgent remoteAddr keys . Combines them and hashes with SHA256 and sets the variable . [CODESPLIT] private void generateAttributesHash ( Map < String , String > attributes ) { StringBuilder attr = new StringBuilder ( ) ; attr . append ( attributes . get ( \"userAgent\" ) ) ; //        attr.append(attributes.get(\"remoteAddr\")); TODO: add remote ip address after you find how to get remote IP from HttpContext attributesHash = Hashing . sha256 ( ) . hashString ( attr . toString ( ) , StandardCharsets . UTF_8 ) . toString ( ) ; resetTokenString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a tokenString with a new expiration date and assigns it . [CODESPLIT] private String generateTokenString ( ) throws Exception { //Renew age //Stringify token data StringBuilder dataString = new StringBuilder ( ) ; dataString . append ( getUserId ( ) ) . append ( SEPARATOR ) . append ( getUsername ( ) ) . append ( SEPARATOR ) . append ( getExpirationDate ( ) . getTime ( ) ) . append ( SEPARATOR ) . append ( attributesHash ) ; // Encrypt token data string String newTokenString = encryptor . encrypt ( dataString . toString ( ) ) ; newTokenString = BaseEncoding . base16 ( ) . encode ( newTokenString . getBytes ( ) ) ; tokenString = newTokenString ; return newTokenString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a mail with the given item . [CODESPLIT] public void sendMessage ( MailItem item ) throws MessagingException { checkNotNull ( item . getReceivers ( ) ) ; checkNotNull ( item . getReceivers ( ) . get ( 0 ) ) ; checkNotNull ( item . getTitle ( ) ) ; checkNotNull ( item . getBody ( ) ) ; //If sender is empty send with the account sender. Message msg = new MimeMessage ( session ) ; if ( item . getSender ( ) == null || item . getSender ( ) . length ( ) == 0 ) { item . setSender ( configuration . getProperties ( ) . get ( configuration . getUsernameKey ( ) ) . toString ( ) ) ; } InternetAddress from = new InternetAddress ( item . getSender ( ) ) ; msg . setFrom ( from ) ; InternetAddress [ ] to = new InternetAddress [ item . getReceivers ( ) . size ( ) ] ; for ( int i = 0 ; i < item . getReceivers ( ) . size ( ) ; i ++ ) { to [ i ] = new InternetAddress ( item . getReceivers ( ) . get ( i ) ) ; } msg . setRecipients ( Message . RecipientType . TO , to ) ; msg . setSubject ( item . getTitle ( ) ) ; MimeBodyPart body = new MimeBodyPart ( ) ; body . setContent ( item . getBody ( ) , \"text/html; charset=UTF-8\" ) ; Multipart content = new MimeMultipart ( ) ; content . addBodyPart ( body ) ; if ( item . getAttachments ( ) != null && item . getAttachments ( ) . size ( ) > 0 ) { for ( DataSource attachment : item . getAttachments ( ) ) { BodyPart itemBodyPart = new MimeBodyPart ( ) ; itemBodyPart . setDataHandler ( new DataHandler ( attachment ) ) ; itemBodyPart . setFileName ( attachment . getName ( ) ) ; content . addBodyPart ( itemBodyPart ) ; } } msg . setContent ( content ) ; //update headers msg . saveChanges ( ) ; Transport . send ( msg ) ; // set header value for ( Map . Entry < String , String [ ] > entry : item . getHeaders ( ) . entrySet ( ) ) { String [ ] value = msg . getHeader ( entry . getKey ( ) ) ; if ( value != null ) { entry . setValue ( value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read more https : // github . com / dropwizard / dropwizard / issues / 932 [CODESPLIT] @ Override protected Hibernate5Module createHibernate5Module ( ) { Hibernate5Module module = new Hibernate5Module ( ) ; module . disable ( Hibernate5Module . Feature . USE_TRANSIENT_ANNOTATION ) ; return module ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verify that the supplied password matches the password for this user . Password should be stored as a hash . It is recommended you use the hashPassword ( password accountName ) method in this class . This method is typically used for reauthentication for the most sensitive functions such as transactions changing email address and changing other account information . [CODESPLIT] public boolean verifyPassword ( T user , String password ) { Optional < T > entry ; entry = ( Optional < T > ) userStore . findByUsername ( user . getUsername ( ) ) ; return entry . isPresent ( ) && entry . get ( ) . getPassword ( ) . equals ( Hashing . sha256 ( ) . hashString ( password , Charset . forName ( \"UTF-8\" ) ) . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate strong password that takes into account the user s information and old password . Implementations should verify that the new password does not include information such as the username fragments of the old password and other information that could be used to weaken the strength of the password . [CODESPLIT] public String generateStrongPassword ( T user , String oldPassword ) { String newPassword ; do { newPassword = generateStrongPassword ( ) ; // Continue until new password does not contain user info or same with old password } while ( newPassword . contains ( user . getUsername ( ) ) || oldPassword . equals ( Hashing . sha256 ( ) . hashString ( newPassword , Charset . forName ( \"UTF-8\" ) ) . toString ( ) ) ) ; return newPassword ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the password for the specified user . This requires the current password as well as the password to replace it with . The new password should be checked against old hashes to be sure the new password does not closely resemble or equal any recent passwords for that UserEntry . Password strength should also be verified . This new password must be repeated to ensure that the user has typed it in correctly . [CODESPLIT] public void changePassword ( T user , String currentPassword , String newPassword , String newPassword2 ) throws AuthenticationException { verifyPassword ( user , currentPassword ) ; if ( ! newPassword . equals ( newPassword2 ) ) { throw new AuthenticationException ( user . getUsername ( ) + \": New password and re-type password must be same\" ) ; } else if ( newPassword . equals ( currentPassword ) ) { throw new AuthenticationException ( user . getUsername ( ) + \": New password and old password must be different\" ) ; } verifyPasswordStrength ( currentPassword , newPassword , user ) ; Optional < ? extends UserEntry > optional = userStore . changePassword ( user . getUsername ( ) , newPassword ) ; if ( ! optional . isPresent ( ) ) { throw new AuthenticationException ( user . getUsername ( ) + \": Can't update UserEntry Password\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the UserEntry matching the provided accountName . If the accoundId is not found an Anonymous UserEntry or null may be returned . [CODESPLIT] public T getUser ( String accountName ) { Optional < T > optional = ( Optional < T > ) userStore . findByUsername ( accountName ) ; if ( optional . isPresent ( ) ) { return optional . get ( ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the hashed password using the accountName as the salt . The salt helps to prevent against rainbow table attacks where the attacker pre - calculates hashes for known strings . This method specifies the use of the user s account name as the salt value . The Encryptor . hash method can be used if a different salt is required . [CODESPLIT] public String hashPassword ( String password , String accountName ) { return Hashing . sha256 ( ) . hashString ( password , Charset . forName ( \"UTF-8\" ) ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the account name passes site - specific complexity requirements like minimum length . [CODESPLIT] public void verifyAccountNameStrength ( String accountName ) throws AuthenticationException { Matcher matcher = PATTERN . matcher ( accountName ) ; if ( ! matcher . matches ( ) ) { throw new AuthenticationException ( accountName + \" is not a valid email\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that the password meets site - specific complexity requirements like length or number of character sets . This method takes the old password so that the algorithm can analyze the new password to see if it is too similar to the old password . Note that this has to be invoked when the user has entered the old password as the list of old credentials stored by ESAPI is all hashed . Additionally the user object is taken in order to verify the password and account name differ . [CODESPLIT] public void verifyPasswordStrength ( String oldPassword , String newPassword , T user ) throws AuthenticationException { List < Rule > rules = getPasswordRules ( ) ; PasswordValidator validator = new PasswordValidator ( rules ) ; PasswordData passwordData = new PasswordData ( new Password ( newPassword ) ) ; RuleResult result = validator . validate ( passwordData ) ; if ( ! result . isValid ( ) ) { StringBuilder messages = new StringBuilder ( ) ; for ( String msg : validator . getMessages ( result ) ) { messages . append ( msg ) . append ( \"\\n\" ) ; } throw new AuthenticationException ( messages . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets http http according to path . It must exist as http . [CODESPLIT] public void setAsset ( String path ) { this . asset = new File ( path ) ; if ( ! this . asset . exists ( ) || ! this . asset . isFile ( ) ) throw new RuntimeException ( \"File does not exist: \" + path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates hash ( MD5 ) from http path and last modification date [CODESPLIT] public void generateMD5 ( ) { md5 = Hashing . md5 ( ) . hashString ( asset . getPath ( ) + asset . lastModified ( ) , StandardCharsets . UTF_8 ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads http from the http [CODESPLIT] private byte [ ] loadAssetFromFile ( ) { try { lastModified = asset . lastModified ( ) ; return Files . toByteArray ( asset ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes http to a cache ( byte array ) [CODESPLIT] private void loadAssetToCache ( ) { try { cache = com . google . common . io . Files . toByteArray ( asset ) ; lastModified = asset . lastModified ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO this method should be refactoring . [CODESPLIT] public static void fillCache ( ) { SessionFactory sessionFactory = RobeHibernateBundle . getInstance ( ) . getSessionFactory ( ) ; ManagedSessionContext . bind ( sessionFactory . openSession ( ) ) ; SystemParameterDao dao = new SystemParameterDao ( sessionFactory ) ; List < SystemParameter > parameters = dao . findAllStrict ( ) ; for ( SystemParameter parameter : parameters ) { cache . put ( parameter . getKey ( ) , parameter . getValue ( ) ) ; dao . detach ( parameter ) ; // TODO } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "implemented just to GET method . [CODESPLIT] @ Override public SearchModel provide ( ) { SearchModel searchModel = new SearchModel ( ) ; searchModel . setResponse ( response ) ; String method = getMethod ( ) ; if ( \"GET\" . equals ( method ) ) { MultivaluedMap < String , String > queryParameters = getUriInfo ( ) . getQueryParameters ( ) ; for ( Map . Entry < String , List < String > > param : queryParameters . entrySet ( ) ) { if ( param . getValue ( ) . get ( 0 ) == null ) continue ; if ( \"_q\" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setQ ( param . getValue ( ) . get ( 0 ) ) ; } else if ( \"_limit\" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setLimit ( Integer . parseInt ( param . getValue ( ) . get ( 0 ) ) ) ; } else if ( \"_offset\" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setOffset ( Integer . parseInt ( param . getValue ( ) . get ( 0 ) ) ) ; } else if ( \"_fields\" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setFields ( param . getValue ( ) . get ( 0 ) . split ( \",\" ) ) ; } else if ( \"_sort\" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setSort ( param . getValue ( ) . get ( 0 ) . split ( \",\" ) ) ; } else if ( \"_filter\" . equalsIgnoreCase ( param . getKey ( ) ) ) { searchModel . setFilterExpression ( param . getValue ( ) . get ( 0 ) ) ; } } } return searchModel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the environment . [CODESPLIT] @ Override public void run ( T configuration , Environment environment ) { try { if ( configuration . getGuice ( ) == null ) { LOGGER . error ( \"GuiceBundle can not work without and configuration!\" ) ; } GuiceBundle . configuration = configuration . getGuice ( ) ; createReflections ( configuration . getGuice ( ) . getScanPackages ( ) ) ; JerseyUtil . registerGuiceBound ( injector , environment . jersey ( ) ) ; JerseyUtil . registerGuiceFilter ( environment ) ; deModule . setEnvironmentData ( configuration , environment ) ; findAndRunScanners ( environment , injector ) ; } catch ( Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link org . reflections . Reflections } with the given packages ( configuration ) [CODESPLIT] private void createReflections ( String [ ] scanPackages ) { if ( scanPackages . length < 1 ) { LOGGER . warn ( \"No package defined in configuration (scanPackages)!\" ) ; return ; } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder ( ) ; FilterBuilder filterBuilder = new FilterBuilder ( ) ; for ( String packageName : scanPackages ) { configurationBuilder . addUrls ( ClasspathHelper . forPackage ( packageName ) ) ; filterBuilder . include ( FilterBuilder . prefix ( packageName ) ) ; } configurationBuilder . filterInputsBy ( filterBuilder ) . setScanners ( new SubTypesScanner ( ) , new TypeAnnotationsScanner ( ) ) ; this . reflections = new Reflections ( configurationBuilder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collects all classes extended { @link io . robe . guice . scanner . Scanner } and adds them to environment [CODESPLIT] private void findAndRunScanners ( Environment environment , Injector injector ) { Set < Class < ? extends Scanner > > scanners = reflections . getSubTypesOf ( Scanner . class ) ; for ( Class < ? extends Scanner > scanner : scanners ) { try { LOGGER . info ( scanner . getName ( ) + \": \" ) ; Scanner instance = scanner . newInstance ( ) ; instance . scanAndAdd ( environment , injector , reflections ) ; } catch ( Exception e ) { LOGGER . error ( \"Added scanner: \" + scanner , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Begins new transaction in a new session and performs operations provided in { @link TransactionWrapper } <br / > In case of an exception is thrown the { @link TransactionExceptionHandler } will be invoked . [CODESPLIT] public static void exec ( TransactionWrapper transactionWrapper , TransactionExceptionHandler exceptionHandler ) { exec ( transactionWrapper , exceptionHandler , FlushMode . AUTO ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Begins new transaction in a new session and performs operations provided in { @link TransactionWrapper } <br / > In case of an exception is thrown the { @link TransactionExceptionHandler } will be invoked . [CODESPLIT] public static void exec ( TransactionWrapper transactionWrapper , TransactionExceptionHandler exceptionHandler , FlushMode flushMode ) { checkNotNull ( transactionWrapper ) ; new Transaction ( transactionWrapper , exceptionHandler , flushMode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If present backup current the session in { [CODESPLIT] private void storePreviousSession ( ) { if ( ManagedSessionContext . hasBind ( SESSION_FACTORY ) ) { SESSIONS . get ( ) . add ( SESSION_FACTORY . getCurrentSession ( ) ) ; ManagedSessionContext . unbind ( SESSION_FACTORY ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a new session sets flush mode and bind this session to { [CODESPLIT] private void configureNewSession ( ) { session = SESSION_FACTORY . openSession ( ) ; session . setFlushMode ( flushMode ) ; ManagedSessionContext . bind ( session ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If transaction is present and active then commit . [CODESPLIT] private void success ( ) { org . hibernate . Transaction txn = session . getTransaction ( ) ; if ( txn != null && txn . getStatus ( ) . equals ( TransactionStatus . ACTIVE ) ) { txn . commit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If transaction is present and active then rollback . [CODESPLIT] private void error ( ) { org . hibernate . Transaction txn = session . getTransaction ( ) ; if ( txn != null && txn . getStatus ( ) . equals ( TransactionStatus . ACTIVE ) ) { txn . rollback ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes and unbinds the current session . <br / > If { [CODESPLIT] private void finish ( ) { try { if ( session != null ) { session . close ( ) ; } } finally { ManagedSessionContext . unbind ( SESSION_FACTORY ) ; if ( ! SESSIONS . get ( ) . isEmpty ( ) ) { ManagedSessionContext . bind ( SESSIONS . get ( ) . pop ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the progress . [CODESPLIT] private void start ( ) { try { before ( ) ; transactionWrapper . wrap ( ) ; success ( ) ; } catch ( Exception e ) { error ( ) ; if ( exceptionHandler != null ) { exceptionHandler . onException ( e ) ; } else { throw e ; } } finally { finish ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get hierarchical menu service for permission [CODESPLIT] @ RobeService ( group = \"Permission\" , description = \"Get hierarchical menu service for permission\" ) @ Path ( \"menus\" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public List < MenuItem > getHierarchicalMenu ( @ RobeAuth Credentials credentials ) { return readMenuHierarchical ( convertMenuToMenuItem ( menuDao . findHierarchicalMenu ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all { @link Permission } s as a collection . [CODESPLIT] @ RobeService ( group = \"Permission\" , description = \"Return all permissions as a collection.\" ) @ GET @ UnitOfWork ( readOnly = true , cacheMode = GET , flushMode = FlushMode . MANUAL ) public List < Permission > getAll ( @ RobeAuth Credentials credentials , @ SearchParam SearchModel search ) { return permissionDao . findAllStrict ( search ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Permission } resource . <p > Status Code : Not Found 404 Not Matches 412 [CODESPLIT] @ RobeService ( group = \"Permission\" , description = \"Creates a permission resource.\" ) @ POST @ UnitOfWork public Permission create ( @ RobeAuth Credentials credentials , @ Valid Permission model ) { return permissionDao . create ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "roleOid . permissionOid . code [CODESPLIT] public static < E > Holder < E > configureFieldByName ( Criteria < E > criteria , String name ) { if ( Validations . isEmptyOrNull ( name ) ) return null ; // parse x.y name as [x, y] String [ ] names = name . split ( \"\\\\.\" ) ; // uses to keep current name by names index. String currentName ; // init start index of names. int step = 0 ; // always will be current criteria CriteriaParent < E > currentCriteria = criteria ; FieldMeta currentFieldMeta ; // use aliasJoiner to use as alias. StringJoiner aliasJoiner = new StringJoiner ( \"$\" ) ; do { // get current name of field by index. like x.y.z => if step = 1 then currentName = y currentName = names [ step ] ; if ( Validations . isEmptyOrNull ( currentName ) ) { throw new RuntimeException ( currentName + \" defined name is wrong ! \" ) ; } currentFieldMeta = criteria . getMeta ( ) . getFieldMap ( ) . get ( currentName ) ; step ++ ; aliasJoiner . add ( currentCriteria . getAlias ( ) ) ; if ( step >= names . length ) { break ; } if ( currentFieldMeta . getReference ( ) == null ) { throw new RuntimeException ( \"\" + currentName + \" join field of \" + name + \"'s reference target information must defined ! \" ) ; } CriteriaJoin < E > criteriaJoin = currentCriteria . getJoin ( currentName ) ; if ( criteriaJoin == null ) { currentCriteria . createJoin ( currentName , currentFieldMeta . getReference ( ) . getTargetEntity ( ) , currentFieldMeta . getReference ( ) . getReferenceId ( ) ) ; } currentCriteria = criteriaJoin ; } while ( step >= names . length ) ; Holder < E > holder = new Holder <> ( ) ; holder . currentFieldName = currentName ; holder . currentCriteria = currentCriteria ; holder . currentFieldMeta = currentFieldMeta ; return holder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges all path patterns and and creates a single string value which will be equal with service methods path annotation value and HTTP method type . Generated string will be used for permission checks . [CODESPLIT] private boolean isAuthorized ( BasicToken token , List < UriTemplate > matchedTemplates , String method ) { StringBuilder path = new StringBuilder ( ) ; // Merge all path templates and generate a path. for ( UriTemplate template : matchedTemplates ) { path . insert ( 0 , template . getTemplate ( ) ) ; } path . append ( \":\" ) . append ( method ) ; //Look at user permissions to see if the service is permitted. return token . getPermissions ( ) . contains ( path . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the environment . [CODESPLIT] @ Override public void run ( T configuration , Environment environment ) throws Exception { this . configuration = configuration . getAuth ( ) ; environment . jersey ( ) . register ( new TokenFactoryProvider . Binder < Credentials > ( Credentials . class ) ) ; environment . jersey ( ) . register ( new TokenBasedAuthResponseFilter ( configuration . getAuth ( ) ) ) ; environment . jersey ( ) . register ( TokenFeature . class ) ; BasicToken . configure ( configuration . getAuth ( ) ) ; if ( configuration . getAuth ( ) . getAlgorithm ( ) != null ) { checkCryptography ( this . configuration ) ; } environment . jersey ( ) . register ( new SecurityHeadersFilter ( configuration . getAuth ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if cryptography restrictions apply . Restrictions apply if the value of { @link Cipher#getMaxAllowedKeyLength ( String ) } returns a value smaller than { @link Integer#MAX_VALUE } if there are any restrictions according to the JavaDoc of the method . This method is used with the transform <code > AES / CBC / PKCS5Padding < / code > as this is an often used algorithm that is <a href = https : // docs . oracle . com / javase / 8 / docs / technotes / guides / security / StandardNames . html#impl > an implementation requirement for Java SE< / a > . [CODESPLIT] public static void checkCryptography ( TokenBasedAuthConfiguration configuration ) { try { Field field = Class . forName ( \"javax.crypto.JceSecurity\" ) . getDeclaredField ( \"isRestricted\" ) ; field . setAccessible ( true ) ; field . set ( null , java . lang . Boolean . FALSE ) ; } catch ( ClassNotFoundException e ) { StringBuilder builder = new StringBuilder ( \"javax.crypto.JceSecurity class not found !\\n\" ) ; builder . append ( getUpgradJceErrorMessage ( ) ) ; throw new RuntimeException ( builder . toString ( ) , e ) ; } catch ( final IllegalAccessException | NoSuchFieldException e ) { try { if ( BasicToken . getEncryptor ( ) . isInitialized ( ) ) { BasicToken . getEncryptor ( ) . encrypt ( \"Sample Data\" ) ; } } catch ( EncryptionOperationNotPossibleException ex ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( configuration . getAlgorithm ( ) ) . append ( \" not exist on Java Cryptography Extension (JCE)\" ) . append ( getUpgradJceErrorMessage ( ) ) ; LOGGER . error ( builder . toString ( ) ) ; throw new RuntimeException ( builder . toString ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create { @link SystemParameter ) resource . [CODESPLIT] @ RobeService ( group = \"SystemParameter\" , description = \"Create SystemParameter resource and return given SystemParameter path link at header Location=example/{id].\" ) @ POST @ UnitOfWork public SystemParameter create ( @ RobeAuth Credentials credentials , @ Valid SystemParameter model ) { return systemParameterDao . create ( model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create or update { @link SystemParameter ) resource . [CODESPLIT] @ RobeService ( group = \"SystemParameter\" , description = \"Create or update SystemParameter resource.\" ) @ POST @ Path ( \"admin\" ) @ UnitOfWork public Map < String , String > bulkSaveOrUpdate ( Map < String , String > values ) { for ( Map . Entry < String , String > entry : values . entrySet ( ) ) { Optional < SystemParameter > optionalParameter = systemParameterDao . findByKey ( entry . getKey ( ) ) ; SystemParameter parameter ; if ( ! optionalParameter . isPresent ( ) ) { parameter = new SystemParameter ( ) ; parameter . setKey ( entry . getKey ( ) ) ; parameter . setValue ( entry . getValue ( ) ) ; } else { parameter = optionalParameter . get ( ) ; parameter . setValue ( entry . getValue ( ) ) ; } systemParameterDao . update ( parameter ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "First it checks is there any annotation class for parsing operations if it is parses with given format if there is a exception while parsing with given format catches and tries with default values If there is no given format tries with static values [CODESPLIT] @ Override public Date parse ( Object o , Field field ) { if ( ! isValid ( o ) ) { return null ; } JsonFormat formatAnn = field . getAnnotation ( JsonFormat . class ) ; if ( formatAnn == null ) { throw new RuntimeException ( \"JsonFormat with pattern needed for: \" + field . getName ( ) ) ; } try { return new SimpleDateFormat ( formatAnn . pattern ( ) , Locale . getDefault ( ) ) . parse ( o . toString ( ) ) ; } catch ( ParseException e ) { throw new RuntimeException ( \"JsonFormat with pattern is wrong for: \" + field . getName ( ) + \" pattern: \" + formatAnn . pattern ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets current response created with exception parameters . [CODESPLIT] public Response getResponse ( ) { return Response . status ( Response . Status . INTERNAL_SERVER_ERROR ) . entity ( builder . build ( ) ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generates = equals [CODESPLIT] public static Restriction eq ( String name , Object value ) { return new Restriction ( Operator . EQUALS , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "! = not equals operator [CODESPLIT] public static Restriction ne ( String name , Object value ) { return new Restriction ( Operator . NOT_EQUALS , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< less than operator [CODESPLIT] public static Restriction lt ( String name , Object Object ) { return new Restriction ( Operator . LESS_THAN , name , Object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< = less or equals than operator [CODESPLIT] public static Restriction le ( String name , Object value ) { return new Restriction ( Operator . LESS_OR_EQUALS_THAN , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "> greater than operator [CODESPLIT] public static Restriction gt ( String name , Object value ) { return new Restriction ( Operator . GREATER_THAN , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "> = greater or equals than operator [CODESPLIT] public static Restriction ge ( String name , Object value ) { return new Restriction ( Operator . GREATER_OR_EQUALS_THAN , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "~ = contains than operator [CODESPLIT] public static Restriction ilike ( String name , Object value ) { return new Restriction ( Operator . CONTAINS , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "| = in list operator [CODESPLIT] public static Restriction in ( String name , Object value ) { return new Restriction ( Operator . IN , name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the list of declared namespaces with a new namespace . [CODESPLIT] public NamespaceManager withNamespace ( String namespace , String href ) { if ( namespaces . containsKey ( namespace ) ) { throw new RepresentationException ( format ( \"Duplicate namespace '%s' found for representation factory\" , namespace ) ) ; } if ( ! href . contains ( \"{rel}\" ) ) { throw new RepresentationException ( format ( \"Namespace '%s' does not include {rel} URI template argument.\" , namespace ) ) ; } return new NamespaceManager ( namespaces . put ( namespace , href ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds or replaces the content of the representation . [CODESPLIT] public ResourceRepresentation < V > withContent ( ByteString content ) { return new ResourceRepresentation <> ( Option . of ( content ) , links , rels , namespaceManager , value , resources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define rel semantics for this representation . [CODESPLIT] public ResourceRepresentation < V > withRel ( Rel rel ) { if ( rels . containsKey ( rel . rel ( ) ) ) { throw new IllegalStateException ( String . format ( \"Rel %s is already declared.\" , rel . rel ( ) ) ) ; } final TreeMap < String , Rel > updatedRels = rels . put ( rel . rel ( ) , rel ) ; return new ResourceRepresentation <> ( content , links , updatedRels , namespaceManager , value , resources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a link to this resource . [CODESPLIT] public ResourceRepresentation < V > withLink ( String rel , URI uri ) { return withLink ( rel , uri . toASCIIString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a link to this resource . [CODESPLIT] public ResourceRepresentation < V > withLink ( String rel , String href , Map < String , String > properties ) { return withLink ( Links . create ( rel , href , properties ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a link to this resource . [CODESPLIT] public ResourceRepresentation < V > withLink ( String rel , String href , java . util . Map < String , String > properties ) { return withLink ( Links . create ( rel , href , HashMap . ofAll ( properties ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a link to this resource . [CODESPLIT] public ResourceRepresentation < V > withLink ( Link link ) { String rel = Links . getRel ( link ) ; Support . checkRelType ( rel ) ; validateSingletonRel ( rel ) ; final TreeMap < String , Rel > updatedRels = ! rels . containsKey ( rel ) ? rels . put ( rel , Rels . natural ( rel ) ) : rels ; final List < Link > updatedLinks = links . append ( link ) ; return new ResourceRepresentation <> ( content , updatedLinks , updatedRels , namespaceManager , value , resources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a link to this resource . [CODESPLIT] public ResourceRepresentation < V > withLinks ( List < Link > links ) { links . forEach ( link -> { String rel = Links . getRel ( link ) ; Support . checkRelType ( rel ) ; validateSingletonRel ( rel ) ; } ) ; final TreeMap < String , Rel > updatedRels = links . map ( Links :: getRel ) . foldLeft ( rels , ( accum , rel ) -> ! accum . containsKey ( rel ) ? accum . put ( rel , Rels . natural ( rel ) ) : accum ) ; final List < Link > updatedLinks = this . links . appendAll ( links ) ; return new ResourceRepresentation <> ( content , updatedLinks , updatedRels , namespaceManager , value , resources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the value of this resource with a new value optionally of a new type . [CODESPLIT] public < R > ResourceRepresentation < R > withValue ( R newValue ) { return new ResourceRepresentation <> ( Option . none ( ) , links , rels , namespaceManager , newValue , resources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new namespace . [CODESPLIT] public ResourceRepresentation < V > withNamespace ( String namespace , String href ) { if ( ! rels . containsKey ( \"curies\" ) ) { rels = rels . put ( \"curies\" , Rels . collection ( \"curies\" ) ) ; } final NamespaceManager updatedNamespaceManager = namespaceManager . withNamespace ( namespace , href ) ; return new ResourceRepresentation <> ( content , links , rels , updatedNamespaceManager , value , resources ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableSet } from the given { @code Iterable } . [CODESPLIT] public static < K , V > Map < K , V > copyOf ( Map < ? extends K , ? extends V > map ) { return new ImmutableMap < K , V > ( new LinkedHashMap < K , V > ( map ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the root cause of the given { @code Throwable } . If the given { @code Throwable } is not the result of a previous one it is considered as the root . [CODESPLIT] public static Throwable getRootCause ( Throwable t ) { Throwable cause = t . getCause ( ) ; return cause == null ? t : getRootCause ( cause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the chain of { @code Throwable } s that caused the given one . The given { @code Throwable } is the first element in the returned { @code List } the last one is the root cause . [CODESPLIT] public static List < Throwable > getCauseChain ( Throwable t ) { List < Throwable > chain = new ArrayList < Throwable > ( ) ; chain . add ( Parameters . checkNotNull ( t ) ) ; Throwable cause = t . getCause ( ) ; while ( cause != null ) { chain . add ( cause ) ; cause = cause . getCause ( ) ; } return Collections . unmodifiableList ( chain ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stack trace of the given { @code Throwable } as a { @code String } . [CODESPLIT] public static String getStackTrace ( Throwable t ) { StringWriter out = new StringWriter ( ) ; PrintWriter writer = new PrintWriter ( out ) ; t . printStackTrace ( writer ) ; writer . flush ( ) ; return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stack frames of the given { @code Throwable } . The stack frames are simply obtained from calling { @code toString } on each { @link StackTraceElement } of { @code t } . [CODESPLIT] public static List < String > getStackFrames ( Throwable t ) { StackTraceElement [ ] elements = t . getStackTrace ( ) ; List < String > frames = new ArrayList < String > ( elements . length ) ; for ( StackTraceElement element : elements ) { frames . add ( element . toString ( ) ) ; } return Collections . unmodifiableList ( frames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re - throws the given { @code Throwable } if it is already an instance of { @code RuntimeException } or { @link Error } and if not wraps it in a { @code RuntimeException } before throwing it . [CODESPLIT] public static RuntimeException propagate ( Throwable t ) { Parameters . checkNotNull ( t ) ; if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error ) t ; } throw new RuntimeException ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes the given { @code Serializable } object into an array of { @code byte } s . [CODESPLIT] public static byte [ ] encode ( Serializable object ) { Parameters . checkNotNull ( object ) ; ObjectOutputStream oos = null ; try { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; oos = new ObjectOutputStream ( out ) ; oos . writeObject ( object ) ; oos . flush ( ) ; return out . toByteArray ( ) ; } catch ( IOException ex ) { throw new EncodingException ( ex ) ; } finally { IO . close ( oos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserializes the given array of { @code byte } s into an object . [CODESPLIT] public static < T extends Serializable > T decode ( byte [ ] bytes , Class < T > t ) { Parameters . checkNotNull ( t ) ; Parameters . checkNotNull ( bytes ) ; ObjectInputStream ois = null ; ByteArrayInputStream in = new ByteArrayInputStream ( bytes ) ; try { ois = new ObjectInputStream ( in ) ; return Parameters . checkType ( ois . readObject ( ) , t ) ; } catch ( IOException ex ) { throw new DecodingException ( ex ) ; } catch ( ClassNotFoundException ex ) { throw new DecodingException ( ex ) ; } finally { IO . close ( ois ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the specified range in the given { @code String } can be encoded into UTF - 8 . [CODESPLIT] public static boolean canEncode ( String str , int off , int len ) { return canEncode ( str . substring ( off , off + len ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the specified range in the given byte array represents valid UTF - 8 encoded characters . [CODESPLIT] public static boolean canDecode ( byte [ ] input , int off , int len ) { try { decode ( input , off , len ) ; } catch ( IllegalArgumentException ex ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the UTF - 8 encoding of the given { @code String } . [CODESPLIT] public static byte [ ] encode ( String str ) { CharsetEncoder encoder = Charsets . UTF_8 . newEncoder ( ) ; try { ByteBuffer out = encoder . encode ( CharBuffer . wrap ( str ) ) ; byte [ ] bytes = new byte [ out . limit ( ) ] ; out . get ( bytes ) ; return bytes ; } catch ( CharacterCodingException ex ) { throw new IllegalArgumentException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the UTF - 8 encoding of the specified character sequence . [CODESPLIT] public static byte [ ] encode ( String str , int off , int len ) { return encode ( str . substring ( off , off + len ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given { @code int } value using little - endian byte ordering convention into the given array starting at the given offset . [CODESPLIT] public static void encode ( int n , byte [ ] out , int off ) { out [ off ] = ( byte ) n ; out [ off + 1 ] = ( byte ) ( n >>> 8 ) ; out [ off + 2 ] = ( byte ) ( n >>> 16 ) ; out [ off + 3 ] = ( byte ) ( n >>> 24 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given { @code long } value using little - endian byte ordering convention into the given array starting at the given offset . [CODESPLIT] public static void encode ( long n , byte [ ] out , int off ) { out [ off ] = ( byte ) n ; out [ off + 1 ] = ( byte ) ( n >>> 8 ) ; out [ off + 2 ] = ( byte ) ( n >>> 16 ) ; out [ off + 3 ] = ( byte ) ( n >>> 24 ) ; out [ off + 4 ] = ( byte ) ( n >>> 32 ) ; out [ off + 5 ] = ( byte ) ( n >>> 40 ) ; out [ off + 6 ] = ( byte ) ( n >>> 48 ) ; out [ off + 7 ] = ( byte ) ( n >>> 56 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the first 4 bytes starting at { @code off } of the given array into an { @code int } value using little - endian byte ordering convention . [CODESPLIT] public static int decodeInt ( byte [ ] in , int off ) { return ( in [ off ] & 0xFF ) | ( ( in [ off + 1 ] & 0xFF ) << 8 ) | ( ( in [ off + 2 ] & 0xFF ) << 16 ) | ( ( in [ off + 3 ] & 0xFF ) << 24 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the first 8 bytes starting at { @code off } of the given array into a { @code long } value using little - endian byte ordering convention . [CODESPLIT] public static long decodeLong ( byte [ ] in , int off ) { return ( long ) ( in [ off ] & 0xFF ) | ( ( long ) ( in [ off + 1 ] & 0xFF ) << 8 ) | ( ( long ) ( in [ off + 2 ] & 0xFF ) << 16 ) | ( ( long ) ( in [ off + 3 ] & 0xFF ) << 24 ) | ( ( long ) ( in [ off + 4 ] & 0xFF ) << 32 ) | ( ( long ) ( in [ off + 5 ] & 0xFF ) << 40 ) | ( ( long ) ( in [ off + 6 ] & 0xFF ) << 48 ) | ( ( long ) ( in [ off + 7 ] & 0xFF ) << 56 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of the given { @code InputStream } into the given { @code Writer } using the system s default charset . [CODESPLIT] public static void copy ( InputStream in , Writer out ) throws IOException { copy ( new InputStreamReader ( in , Charsets . DEFAULT ) , out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of the given { @code InputStream } into the given { @code Writer } using the specified charset . [CODESPLIT] public static void copy ( InputStream in , Writer out , Charset charset ) throws IOException { copy ( new InputStreamReader ( in , charset ) , out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of the given { @code Reader } into the given { @code OutputStream } using the system s default charset . [CODESPLIT] public static void copy ( Reader in , OutputStream out ) throws IOException { copy ( in , new OutputStreamWriter ( out , Charsets . DEFAULT ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of the given { @code Reader } into the given { @code OutputStream } using the specified charset . [CODESPLIT] public static void copy ( Reader in , OutputStream out , Charset charset ) throws IOException { copy ( in , new OutputStreamWriter ( out , charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given streams have the same content . [CODESPLIT] public static boolean equal ( Reader in1 , Reader in2 ) throws IOException { if ( in1 == in2 ) { return true ; } if ( in1 == null || in2 == null ) { return false ; } in1 = buffer ( in1 ) ; in2 = buffer ( in2 ) ; int c1 = in1 . read ( ) ; int c2 = in2 . read ( ) ; while ( c1 != - 1 && c2 != - 1 && c1 == c2 ) { c1 = in1 . read ( ) ; c2 = in2 . read ( ) ; } return in1 . read ( ) == - 1 && in2 . read ( ) == - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the whole content of the given { @code Reader } into a { @code String } . [CODESPLIT] public static String read ( Reader in ) throws IOException { Writer out = new StringWriter ( ) ; copy ( in , out ) ; return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the whole content of the given { @code InputStream } into a { @code String } using the system s default charset . [CODESPLIT] public static String read ( InputStream in ) throws IOException { return read ( new InputStreamReader ( in , Charsets . DEFAULT ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the whole content of the given { @code InputStream } into a { @code String } using the specified charset . [CODESPLIT] public static String read ( InputStream in , Charset charset ) throws IOException { return read ( new InputStreamReader ( in , charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all the lines from the given source { @code Reader } . Note that the returned { @code List } is immutable . [CODESPLIT] public static List < String > readLines ( Reader in ) throws IOException { BufferedReader reader = buffer ( in ) ; List < String > lines = new ArrayList < String > ( ) ; String line = reader . readLine ( ) ; while ( line != null ) { lines . add ( line ) ; line = reader . readLine ( ) ; } return Collections . unmodifiableList ( lines ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all the lines from the given source { @code InputStream } using the system s default charset . Note that the returned { @code List } is immutable . [CODESPLIT] public static List < String > readLines ( InputStream in ) throws IOException { return readLines ( in , Charsets . DEFAULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all the lines from the given source { @code InputStream } using the specified charset . Note that the returned { @code List } is immutable . [CODESPLIT] public static List < String > readLines ( InputStream in , Charset charset ) throws IOException { return readLines ( new InputStreamReader ( in , charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new immutable { @code KDF } instance implementing the PBKDF1 algorithm ( RFC 2898 ) . [CODESPLIT] public static KDF pbkdf1 ( Algorithm < Digest > digest , int iterationCount , int dkLen ) { return new PBKDF1 ( digest , iterationCount , dkLen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new immutable { @code KDF } instance implementing the PBKDF2 algorithm ( RFC 2898 ) . [CODESPLIT] public static KDF pbkdf2 ( Algorithm < MAC > mac , int iterationCount , int dkLen ) { return new PBKDF2 ( mac , iterationCount , dkLen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new immutable { @code KDF } instance implementing the HKDF algorithm ( RFC 5869 ) . [CODESPLIT] public static KDF hkdf ( Algorithm < MAC > mac , byte [ ] info , int dkLen ) { return new HKDF ( mac , info , dkLen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a new immutable { @code KDF } instance implementing the SCrypt algorithm ( RFC 7914 ) . [CODESPLIT] public static KDF scrypt ( int r , int n , int p , int dkLen ) { return new SCrypt ( r , n , p , dkLen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the contents of { @code src } to { @code dst } . If { @code dst } doesn t exist it will be created . If it already exists it can be either a directory or a regular file if { @code src } is also a regular file . Named after the Unix command of the same name . [CODESPLIT] public static void cp ( File src , File dst ) throws IOException { if ( ! src . exists ( ) ) { throw new FileNotFoundException ( src + \" doesn't exist\" ) ; } Parameters . checkCondition ( ( ! dst . exists ( ) || dst . isDirectory ( ) ) || ( src . isFile ( ) && dst . isFile ( ) ) ) ; if ( src . isDirectory ( ) ) { copyDirectory ( src , dst ) ; } else if ( src . isFile ( ) ) { copyFile ( src , dst ) ; } else { throw new IOException ( src + \" is neither a directory nor a regular file\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the contents of the given input { @code File } to the given { @code OutputStream } . Named after the Unix command of the same name . [CODESPLIT] public static void cp ( File src , OutputStream dst ) throws IOException { InputStream in = newInputStream ( src ) ; try { ByteStreams . copy ( in , dst ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the contents of the given { @code InputStream } to the given output { @code File } . Named after the Unix command of the same name . [CODESPLIT] public static void cp ( InputStream src , File dst ) throws IOException { OutputStream out = newOutputStream ( dst ) ; try { ByteStreams . copy ( src , out ) ; } finally { IO . close ( out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves a file from one path to another . Named after the Unix command of the same name . [CODESPLIT] public static void mv ( File src , File dst ) throws IOException { Parameters . checkNotNull ( dst ) ; if ( ! src . equals ( dst ) ) { cp ( src , dst ) ; try { rm ( src ) ; } catch ( IOException e ) { rm ( dst ) ; throw new IOException ( \"Can't move \" + src , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the given { @code File } s . Directories will be recursively deleted . Named after the Unix command of the same name . [CODESPLIT] public static void rm ( File ... files ) throws IOException { for ( File f : files ) { if ( f . exists ( ) ) { if ( f . isDirectory ( ) ) { rm ( f . listFiles ( ) ) ; } if ( ! f . delete ( ) ) { throw new IOException ( \"Can't delete \" + f ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates empty files at the specified paths or updates the last modification time of the files at the specified paths . Named after the Unix command of the same name . [CODESPLIT] public static void touch ( File ... files ) throws IOException { long now = System . currentTimeMillis ( ) ; for ( File f : files ) { if ( ! f . createNewFile ( ) && ! f . setLastModified ( now ) ) { throw new IOException ( \"Failed to touch \" + f ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the first ( up to { @code n } ) bytes of the given { @code File } . Named after the Unix command of the same name . [CODESPLIT] public static byte [ ] head ( File f , int n ) throws IOException { Parameters . checkCondition ( n >= 0 ) ; InputStream in = newInputStream ( f ) ; byte [ ] buf = new byte [ n ] ; try { return XArrays . copyOf ( buf , 0 , in . read ( buf ) ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the last ( up to { @code n } ) bytes of the given { @code File } . Named after the Unix command of the same name . [CODESPLIT] public static byte [ ] tail ( File f , int n ) throws IOException { Parameters . checkCondition ( n >= 0 ) ; RandomAccessFile file = new RandomAccessFile ( f , \"r\" ) ; file . seek ( file . length ( ) - n ) ; byte [ ] data = new byte [ n ] ; file . read ( data ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code File } s have the same content . Two regular files are considered equal if they contain the same bytes . Two directories are considered equal if they both contain the same items where an item is either a directory or a regular file ( items must have the same name and content in both directories ) . [CODESPLIT] public static boolean equal ( File f1 , File f2 ) throws IOException { if ( f1 == f2 ) { return true ; } if ( f1 == null || f2 == null || ! haveSameType ( f1 , f2 ) ) { return false ; } return f1 . equals ( f2 ) ? true : haveSameContent ( f1 , f2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the file name without its path or extension . This method is named after the basename Unix command . [CODESPLIT] public static String getBaseName ( File f ) { String fileName = f . getName ( ) ; int index = fileName . lastIndexOf ( ' ' ) ; return index == - 1 ? fileName : fileName . substring ( 0 , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @code OutputStream } to write to the given { @code File } . [CODESPLIT] public static BufferedOutputStream newOutputStream ( File f , WriteOption ... options ) throws IOException { Set < WriteOption > opts = ImmutableSet . of ( options ) ; checkWriteOptions ( opts ) ; checkFileExistence ( f , opts ) ; return new BufferedOutputStream ( newOutputStream ( f , opts ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the content of the given { @code File } . [CODESPLIT] public static byte [ ] read ( File f ) throws IOException { InputStream in = newInputStream ( f ) ; try { return ByteStreams . read ( in ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a { @code MediaType } from its { @code String } representation . [CODESPLIT] public static MediaType parse ( String input ) { Parameters . checkNotNull ( input ) ; Matcher m = MEDIA_TYPE_PATTERN . matcher ( input ) ; Parameters . checkCondition ( m . matches ( ) ) ; String type = m . group ( 1 ) ; String subtype = m . group ( 2 ) ; String params = m . group ( 3 ) ; ParametersParser parser = new ParametersParser ( ) ; return create ( type , subtype , parser . parse ( params ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code MediaType } with the given type and subtype . [CODESPLIT] public static MediaType create ( String type , String subtype ) { Map < String , String > params = Collections . emptyMap ( ) ; return create ( type , subtype , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of the charset parameter if it is specified or { @code null } otherwise . [CODESPLIT] public Charset charset ( ) { String charset = parameters . get ( CHARSET ) ; return charset == null ? null : Charset . forName ( charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code MediaType } instance similar to this one but with the specified parameter set to the given value . [CODESPLIT] public MediaType withParameter ( String attribute , String value ) { Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( attribute , value ) ; return withParameters ( params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code MediaType } instance having the same type and subtype as this one but whose parameters is the union of this instances parameters with the given ones ( the given parameters have precedence over this instance s parameters ) . [CODESPLIT] public MediaType withParameters ( Map < String , String > parameters ) { Map < String , String > params = new LinkedHashMap < String , String > ( ) ; params . putAll ( this . parameters ) ; params . putAll ( normalizeParameters ( parameters ) ) ; return new MediaType ( type , subtype , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code MediaType } instance similar to this one but without the specified parameter . [CODESPLIT] public MediaType withoutParameter ( String attribute ) { Parameters . checkNotNull ( attribute ) ; Map < String , String > params = new LinkedHashMap < String , String > ( ) ; params . putAll ( parameters ) ; params . remove ( attribute ) ; return new MediaType ( type , subtype , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code MediaType } instance with the same type and subtype as this instance but without any parameters . [CODESPLIT] public MediaType withoutParameters ( ) { Map < String , String > params = Collections . emptyMap ( ) ; return new MediaType ( type , subtype , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether this media type is within the specified media range . Namely it returns { @code true } if the type of { @code range } is the wildcard or is equal to the type of this instance and if the subtype of { @code range } is the wildcard or is equal to the subtype of this instance and if all the parameters present in { @code range } are also present in this instance . [CODESPLIT] public boolean is ( MediaType range ) { return ( range . type . equals ( WILDCARD ) || range . type . equals ( type ) ) && ( range . subtype . equals ( WILDCARD ) || range . subtype . equals ( subtype ) ) && parameters . entrySet ( ) . containsAll ( range . parameters . entrySet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the given { @code Iterable } s into a single one . Note that the returned { @code Iterable } is only a view that is any subsequent update on any of the input { @code Iterable } s will affect the returned view . The input { @code Iterable } s will not be polled until necessary . The returned view s { @code Iterator } supports { @link Iterator#remove () } when the corresponding input { @code Iterator } supports it . [CODESPLIT] public static < T > Iterable < T > concat ( Iterable < ? extends Iterable < ? extends T > > iterables ) { return new ConcatIterable < T > ( iterables ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a cyclic { @code Iterable } that cycles indefinitely over the given { @code Iterable } s elements . The returned { @code Iterable } s { @code Iterator } supports { @code Iterator#remove () } . [CODESPLIT] public static < T > Iterable < T > cycle ( Iterable < ? extends T > iterable ) { return new CyclicIterable < T > ( toList ( iterable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @code Iterable } that cycles indefinitely over the given elements . The returned { @code Iterable } s { @code Iterator } supports { @link Iterator#remove () } . [CODESPLIT] public static < T > Iterable < T > cycle ( T ... elements ) { return new CyclicIterable < T > ( new ArrayList < T > ( Arrays . asList ( elements ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Iterable } s contain equal elements in the same order . [CODESPLIT] public static boolean equal ( Iterable < ? > i1 , Iterable < ? > i2 ) { if ( i1 == i2 ) { return true ; } if ( i1 == null || i2 == null ) { return false ; } return Iterators . equal ( i1 . iterator ( ) , i2 . iterator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @code Iterable } view of the given { @code Iterable } that will only return its first { @code limit } items . The returned view s { @code Iterator } s support { @link Iterator#remove () } if the original { @code Iterator } does . [CODESPLIT] public static < T > Iterable < T > limit ( Iterable < ? extends T > iterable , int limit ) { return new LimitIterable < T > ( iterable , limit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @code Iterable } view of the given { @code Iterable } that skips its first { @code n } elements . The returned { @code Iterable } s { @code Iterator } supports { @link Iterator#remove () } if the original { @code Iterator } does . [CODESPLIT] public static < T > Iterable < T > skip ( Iterable < T > iterable , int n ) { return new SkipIterable < T > ( iterable , n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code List } containing all the given { @code Iterable } s elements . [CODESPLIT] public static < T > List < T > toList ( Iterable < ? extends T > iterable ) { List < T > list = new ArrayList < T > ( ) ; for ( T e : iterable ) { list . add ( e ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Set } containing all the given { @code Iterable } s elements . The returned { @code Set } has the same iteration order as the source { @code Iterable } . [CODESPLIT] public static < T > Set < T > toSet ( Iterable < ? extends T > iterable ) { Set < T > set = new LinkedHashSet < T > ( ) ; for ( T e : iterable ) { set . add ( e ) ; } return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Bag } containing all the given { @code Iterable } s elements . The returned { @code Bag } has the same iteration order as the source { @code Iterable } . [CODESPLIT] public static < T > Bag < T > toBag ( Iterable < ? extends T > iterable ) { return new ArrayBag < T > ( iterable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the padding bits and the message length to the input data . [CODESPLIT] private void addPadding ( ) { int len = BLOCK_LENGTH - bufferLen ; if ( len < 9 ) { len += BLOCK_LENGTH ; } byte [ ] buf = new byte [ len ] ; buf [ 0 ] = ( byte ) 0x80 ; for ( int i = 1 ; i < len - 8 ; i ++ ) { buf [ i ] = ( byte ) 0x00 ; } counter = ( counter + ( long ) bufferLen ) * 8L ; LittleEndian . encode ( counter , buf , len - 8 ) ; update ( buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableList } from the given { @code Collection } . [CODESPLIT] public static < E > List < E > copyOf ( Collection < ? extends E > c ) { return new ImmutableList < E > ( new ArrayList < E > ( c ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableList } from the given { @code Iterable } . [CODESPLIT] public static < E > List < E > copyOf ( Iterable < ? extends E > i ) { return new ImmutableList < E > ( Iterables . toList ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableList } from the given { @code Iterator } . [CODESPLIT] public static < E > List < E > copyOf ( Iterator < ? extends E > i ) { return new ImmutableList < E > ( Iterators . toList ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableList } containing the given elements . [CODESPLIT] public static < E > List < E > copyOf ( E [ ] values ) { return new ImmutableList < E > ( Arrays . asList ( values ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableList } containing the given elements . [CODESPLIT] public static < E > List < E > of ( E ... values ) { return new ImmutableList < E > ( Arrays . asList ( values ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first ( up to 10 ) lines of the given { @code File } using the specified charset . Named after the Unix command of the same name . [CODESPLIT] public static List < String > head ( File f , Charset charset ) throws IOException { return head ( f , 10 , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first ( up to { @code n } ) lines of the given { @code File } using the system s default charset . Named after the Unix command of the same name . [CODESPLIT] public static List < String > head ( File f , int n ) throws IOException { return head ( f , n , Charsets . DEFAULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first ( up to { @code n } ) lines of the given { @code File } using the specified charset . Named after the Unix command of the same name . [CODESPLIT] public static List < String > head ( File f , int n , Charset charset ) throws IOException { Parameters . checkCondition ( n >= 0 ) ; List < String > lines = new ArrayList < String > ( ) ; BufferedReader reader = newReader ( f , charset ) ; try { String line = reader . readLine ( ) ; while ( line != null && lines . size ( ) < n ) { lines . add ( line ) ; line = reader . readLine ( ) ; } } finally { IO . close ( reader ) ; } return Collections . unmodifiableList ( lines ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last ( up to 10 ) lines of the given { @code File } using the specified charset . Named after the Unix command of the same name . [CODESPLIT] public static List < String > tail ( File f , Charset charset ) throws IOException { return tail ( f , 10 , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last ( up to n ) lines of the given { @code File } using the specified charset . Named after the Unix command of the same name . [CODESPLIT] public static List < String > tail ( File f , int n , Charset charset ) throws IOException { Parameters . checkCondition ( n >= 0 ) ; if ( n == 0 ) { return Collections . emptyList ( ) ; } List < String > lines = new LinkedList < String > ( ) ; BufferedReader reader = newReader ( f , charset ) ; try { String line = reader . readLine ( ) ; while ( line != null ) { lines . add ( line ) ; if ( lines . size ( ) > n ) { lines . remove ( 0 ) ; } line = reader . readLine ( ) ; } } finally { IO . close ( reader ) ; } return Collections . unmodifiableList ( lines ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code BufferedReader } to read the given { @code File } using the specified charset . [CODESPLIT] public static BufferedReader newReader ( File f , Charset charset ) throws FileNotFoundException { InputStream in = new FileInputStream ( f ) ; return new BufferedReader ( new InputStreamReader ( in , charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code BufferedWriter } to write to the given { @code File } using the system s default charset . [CODESPLIT] public static BufferedWriter newWriter ( File f , WriteOption ... options ) throws IOException { return newWriter ( f , Charsets . DEFAULT , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code BufferedWriter } to write to the given { @code File } using the specified charset . [CODESPLIT] public static BufferedWriter newWriter ( File f , Charset charset , WriteOption ... options ) throws IOException { OutputStream out = XFiles . newOutputStream ( f , options ) ; return new BufferedWriter ( new OutputStreamWriter ( out , charset ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the whole content of the given { @code File } as a { @code String } using the specified charset . [CODESPLIT] public static String read ( File f , Charset charset ) throws IOException { BufferedReader in = newReader ( f , charset ) ; try { return CharStreams . read ( in ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all the lines from the given { @code File } using the system s default charset . Note that the returned { @code List } is immutable . [CODESPLIT] public static List < String > readLines ( File f ) throws IOException { return readLines ( f , Charsets . DEFAULT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code URN } by parsing the given { @code String } . This function invokes the { @link URN#URN ( java . lang . String ) } constructor ; any { @code URNSyntaxException } thrown by the constructor is caught and wrapped in a new { @code IllegalArgumentException } which is then thrown . This method is provided for use in situations where it is known that the given { @code String } is a legal { @code URN } . [CODESPLIT] public static URN create ( String urn ) { try { return new URN ( urn ) ; } catch ( URNSyntaxException ex ) { throw new IllegalArgumentException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and returns the resource having the given name using the { @linkplain Thread#getContextClassLoader () context class loader } . Note that if the context class loader is { @code null } the class loader that loaded this class will be used instead . [CODESPLIT] public static Resource find ( String name ) { Parameters . checkNotNull ( name ) ; ClassLoader loader = XObjects . firstNonNull ( Thread . currentThread ( ) . getContextClassLoader ( ) , Resource . class . getClassLoader ( ) ) ; URL url = loader . getResource ( name ) ; if ( url != null ) { return new Resource ( url ) ; } throw new NotFoundException ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and returns the resource having the given name ( relative to the specified class ) . [CODESPLIT] public static Resource find ( String name , Class < ? > contextClass ) { Parameters . checkNotNull ( name ) ; URL url = contextClass . getResource ( name ) ; if ( url != null ) { return new Resource ( url ) ; } throw new NotFoundException ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of this resource to the specified stream . [CODESPLIT] public void copyTo ( OutputStream out ) throws IOException { InputStream in = url . openStream ( ) ; try { ByteStreams . copy ( in , out ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of this resource to the specified stream . [CODESPLIT] public void copyTo ( Writer out , Charset charset ) throws IOException { InputStream in = url . openStream ( ) ; try { CharStreams . copy ( in , out , charset ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads and returns this resource s content as a { @code byte [] } . [CODESPLIT] public byte [ ] read ( ) throws IOException { InputStream in = url . openStream ( ) ; try { return ByteStreams . read ( in ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads and returns this resource s content as a { @code String } . [CODESPLIT] public String read ( Charset charset ) throws IOException { InputStream in = url . openStream ( ) ; try { return CharStreams . read ( in , charset ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads and returns all this resource s lines . Note that the returned { @code List } is immutable . [CODESPLIT] public List < String > readLines ( Charset charset ) throws IOException { InputStream in = url . openStream ( ) ; try { return CharStreams . readLines ( in , charset ) ; } finally { IO . close ( in ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Calendar } s represent the same instant . [CODESPLIT] public static boolean isSameInstant ( Calendar cal1 , Calendar cal2 ) { return isSameInstant ( cal1 . getTime ( ) , cal2 . getTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Date } s represent the same local time . [CODESPLIT] public static boolean isSameLocalTime ( Date date1 , Date date2 ) { return isSameLocalTime ( toCalendar ( date1 ) , toCalendar ( date2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Calendar } s represent the same local time . [CODESPLIT] public static boolean isSameLocalTime ( Calendar cal1 , Calendar cal2 ) { return cal1 . get ( MILLISECOND ) == cal2 . get ( MILLISECOND ) && cal1 . get ( SECOND ) == cal2 . get ( SECOND ) && cal1 . get ( MINUTE ) == cal2 . get ( MINUTE ) && cal1 . get ( HOUR_OF_DAY ) == cal2 . get ( HOUR_OF_DAY ) && cal1 . get ( DAY_OF_YEAR ) == cal2 . get ( DAY_OF_YEAR ) && cal1 . get ( YEAR ) == cal2 . get ( YEAR ) && cal1 . get ( ERA ) == cal2 . get ( ERA ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Date } s represent the same day . [CODESPLIT] public static boolean isSameDay ( Date date1 , Date date2 ) { return isSameDay ( toCalendar ( date1 ) , toCalendar ( date2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Calendar } s represent the same day . [CODESPLIT] public static boolean isSameDay ( Calendar cal1 , Calendar cal2 ) { return cal1 . get ( ERA ) == cal2 . get ( ERA ) && cal1 . get ( YEAR ) == cal2 . get ( YEAR ) && cal1 . get ( DAY_OF_YEAR ) == cal2 . get ( DAY_OF_YEAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Date } s represent the same week . [CODESPLIT] public static boolean isSameWeek ( Date date1 , Date date2 ) { return isSameWeek ( toCalendar ( date1 ) , toCalendar ( date2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Calendar } s represent the same week . [CODESPLIT] public static boolean isSameWeek ( Calendar cal1 , Calendar cal2 ) { return cal1 . get ( ERA ) == cal2 . get ( ERA ) && cal1 . get ( YEAR ) == cal2 . get ( YEAR ) && cal1 . get ( WEEK_OF_YEAR ) == cal2 . get ( WEEK_OF_YEAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Date } s represent the same month . [CODESPLIT] public static boolean isSameMonth ( Date date1 , Date date2 ) { return isSameMonth ( toCalendar ( date1 ) , toCalendar ( date2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Calendar } s represent the same month . [CODESPLIT] public static boolean isSameMonth ( Calendar cal1 , Calendar cal2 ) { return cal1 . get ( ERA ) == cal2 . get ( ERA ) && cal1 . get ( YEAR ) == cal2 . get ( YEAR ) && cal1 . get ( MONTH ) == cal2 . get ( MONTH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Date } s represent the same year . [CODESPLIT] public static boolean isSameYear ( Date date1 , Date date2 ) { return isSameYear ( toCalendar ( date1 ) , toCalendar ( date2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Calendar } s represent the same year . [CODESPLIT] public static boolean isSameYear ( Calendar cal1 , Calendar cal2 ) { return cal1 . get ( ERA ) == cal2 . get ( ERA ) && cal1 . get ( YEAR ) == cal2 . get ( YEAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a { @code String } representing a date into a { @code Date } instance . The given formats will be used sequentially until a successful parsing is obtained . A parsing is considered successful if it parses the whole input { @code String } . [CODESPLIT] public static Date parse ( String date , String ... formats ) { return parse ( date , Locale . getDefault ( ) , formats ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a { @code String } representing a date into a { @code Date } instance . The given formats will be used sequentially until a successful parsing is obtained . A parsing is considered successful if it parses the whole input { @code String } . [CODESPLIT] public static Date parse ( String date , Locale locale , String ... formats ) { Parameters . checkNotNull ( date ) ; Parameters . checkCondition ( formats . length > 0 ) ; for ( String format : formats ) { DateFormat df = new SimpleDateFormat ( format , locale ) ; df . setLenient ( true ) ; ParsePosition position = new ParsePosition ( 0 ) ; Date d = df . parse ( date , position ) ; if ( d != null && position . getIndex ( ) == date . length ( ) ) { return d ; } } throw new IllegalArgumentException ( \"Unparseable date: \" + date ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code String } representation of the given { @code Date } according to the specified format pattern . [CODESPLIT] public static String format ( Date date , String format ) { Parameters . checkNotNull ( date ) ; return new SimpleDateFormat ( format ) . format ( date ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @code Date } into a { @code Calendar } . [CODESPLIT] public static Calendar toCalendar ( Date date ) { Calendar calendar = getInstance ( ) ; calendar . setTime ( date ) ; return calendar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates all the given { @code Iterator } s into a single one . The source { @code Iterator } s aren t polled until necessary . The returned { @code Iterator } supports { @link Iterator#remove () } when the corresponding input { @code Iterator } supports it . [CODESPLIT] public static < E > Iterator < E > concat ( Iterator < ? extends E > ... iterators ) { return concat ( Arrays . asList ( iterators ) . iterator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates all the given { @code Iterator } s into a single one . The source { @code Iterator } s aren t polled until necessary . The returned { @code Iterator } supports { @link Iterator#remove () } when the corresponding input { @code Iterator } supports it . [CODESPLIT] public static < E > Iterator < E > concat ( Iterator < ? extends Iterator < ? extends E > > iterators ) { return new ConcatIterator < E > ( iterators ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @code Iterator } that cycles indefinitely over the content of the given source { @code Iterator } . The source { @code Iterator } is not polled until necessary . The returned { @code Iterator } supports { @link Iterator#remove () } . [CODESPLIT] public static < E > Iterator < E > cycle ( Iterator < ? extends E > iterator ) { return new LazyCyclicIterator < E > ( iterator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an { @code Iterator } that cycles indefinitely over the given elements . The returned { @code Iterator } supports { @link Iterator#remove () } . [CODESPLIT] public static < E > Iterator < E > cycle ( E ... elements ) { return new CyclicIterator < E > ( Arrays . asList ( elements ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code Iterator } s contain equal elements in the same order . Note that this method consumes entirely the input { @code Iterator } s . [CODESPLIT] public static boolean equal ( Iterator < ? > i1 , Iterator < ? > i2 ) { if ( i1 == i2 ) { return true ; } if ( i1 == null || i2 == null ) { return false ; } while ( i1 . hasNext ( ) && i2 . hasNext ( ) ) { if ( ! XObjects . equal ( i1 . next ( ) , i2 . next ( ) ) ) { return false ; } } return ! ( i1 . hasNext ( ) || i2 . hasNext ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an { @code Iterator } returning only the first { @code limit } elements of the given { @code Iterator } . The source { @code Iterator } is not polled until necessary . The returned { @code Iterator } supports { @link Iterator#remove () } if the source { @code Iterator } supports it . [CODESPLIT] public static < E > Iterator < E > limit ( Iterator < ? extends E > iterator , int limit ) { return new LimitIterator < E > ( iterator , limit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips { @code n } elements from the given { @code Iterator } . [CODESPLIT] public static int skip ( Iterator < ? > iterator , int n ) { Parameters . checkCondition ( n >= 0 ) ; int skipped = 0 ; while ( skipped < n && iterator . hasNext ( ) ) { iterator . next ( ) ; skipped ++ ; } return skipped ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Set } containing all the given { @code Iterator } s elements . The returned { @code Set } has the same iteration order as the given { @code Iterator } . This method consumes entirely the input { @code Iterator } . [CODESPLIT] public static < E > Set < E > toSet ( Iterator < ? extends E > iterator ) { Set < E > set = new LinkedHashSet < E > ( ) ; while ( iterator . hasNext ( ) ) { set . add ( iterator . next ( ) ) ; } return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Bag } containing all the given { @code Iterator } s elements . The returned { @code Bag } has the same iteration order as the given { @code Iterator } . This method consumes entirely the input { @code Iterator } . [CODESPLIT] public static < E > Bag < E > toBag ( Iterator < ? extends E > iterator ) { return new ArrayBag < E > ( iterator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code String } only contains space \\ n \\ r or \\ t characters . [CODESPLIT] public static boolean isBlank ( String str ) { for ( char c : str . toCharArray ( ) ) { if ( c != ' ' && c != ' ' && c != ' ' && c != ' ' ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Abbreviates the given { @code String } using the specified ellipsis so that the returned { @code String } s length is equal to { @code length } . [CODESPLIT] public static String abbreviate ( String str , int length , String ellipsis ) { Parameters . checkCondition ( length > ellipsis . length ( ) ) ; if ( str . length ( ) <= length ) { return str ; } return str . substring ( 0 , length - ellipsis . length ( ) ) + ellipsis ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the given { @code String } s . [CODESPLIT] public static String concat ( String ... strings ) { StringBuilder sb = new StringBuilder ( strings . length * 10 ) ; for ( String string : strings ) { sb . append ( string ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes and returns the Damerau - Levenshtein distance between the given { @code String } s . This distance is obtained by counting the minimum number of operations needed to transform one { @code String } into the other where an operation is defined as an insertion deletion or substitution of a single character or a transposition of two adjacent characters . [CODESPLIT] public static int distance ( String str1 , String str2 ) { char [ ] s1 = str1 . toCharArray ( ) ; char [ ] s2 = str2 . toCharArray ( ) ; int [ ] [ ] d = new int [ s1 . length + 1 ] [ s2 . length + 1 ] ; for ( int i = 0 ; i <= s1 . length ; i ++ ) { d [ i ] [ 0 ] = i ; } for ( int i = 0 ; i <= s2 . length ; i ++ ) { d [ 0 ] [ i ] = i ; } for ( int i = 1 ; i <= s1 . length ; i ++ ) { for ( int j = 1 ; j <= s2 . length ; j ++ ) { int c = s1 [ i - 1 ] == s2 [ j - 1 ] ? 0 : 1 ; d [ i ] [ j ] = min ( d [ i - 1 ] [ j ] + 1 , d [ i ] [ j - 1 ] + 1 , d [ i - 1 ] [ j - 1 ] + c ) ; if ( i > 1 && j > 1 && s1 [ i - 1 ] == s2 [ j - 2 ] && s1 [ i - 2 ] == s2 [ j - 1 ] ) { d [ i ] [ j ] = min ( d [ i ] [ j ] , d [ i - 2 ] [ j - 2 ] + c ) ; } } } return d [ s1 . length ] [ s2 . length ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random { @code String } using the given characters and the specified source of randomness . All characters have equal likelihood to appear in the resulting { @code String } assuming that the source of randomness is fair . [CODESPLIT] public static String random ( int length , Random rnd , char ... chars ) { Parameters . checkCondition ( length >= 0 ) ; Parameters . checkCondition ( chars . length > 0 ) ; StringBuilder sb = new StringBuilder ( length ) ; for ( int i = 0 ; i < length ; i ++ ) { sb . append ( chars [ rnd . nextInt ( chars . length ) ] ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code String } obtained by repeating { @code count } times the given { @code String } . [CODESPLIT] public static String repeat ( String str , int count ) { Parameters . checkCondition ( count >= 0 ) ; StringBuilder sb = new StringBuilder ( str . length ( ) * count ) ; for ( int i = 0 ; i < count ; i ++ ) { sb . append ( str ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Randomly permutes the characters from the given { @code String } using the specified source of randomness . All permutations occur with equal likelihood assuming that the source of randomness is fair . This implementation uses the optimized version of the Fisher - Yates shuffle algorithm ( Fisher Yates Durstenfeld Knuth ) and thus runs in linear time . [CODESPLIT] public static String shuffle ( String str , Random rnd ) { return new String ( XArrays . shuffle ( str . toCharArray ( ) , rnd ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the new { @code String } obtained by stripping the first and last { @code n } characters from the given one . [CODESPLIT] public static String strip ( String str , int n ) { return stripRight ( stripLeft ( str , n ) , n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the new { @code String } obtained by stripping the first { @code n } characters from the given one . [CODESPLIT] public static String stripLeft ( String str , int n ) { Parameters . checkCondition ( n >= 0 ) ; int start = Math . min ( str . length ( ) , n ) ; return str . substring ( start ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the new { @code String } obtained by stripping the last { @code n } characters from the given one . [CODESPLIT] public static String stripRight ( String str , int n ) { Parameters . checkCondition ( n >= 0 ) ; int end = Math . max ( 0 , str . length ( ) - n ) ; return str . substring ( 0 , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of the given { @code String } with leading whitespaces omitted . [CODESPLIT] public static String trimLeft ( String str ) { int start = 0 ; for ( char c : str . toCharArray ( ) ) { if ( c != ' ' ) { break ; } start ++ ; } return str . substring ( start ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of the given { @code String } with trailing whitespaces omitted . [CODESPLIT] public static String trimRight ( String str ) { int end = str . length ( ) ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) != ' ' ) { break ; } end -- ; } return str . substring ( 0 , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code String } of length at least { @code len } created by prepending as many copies of { @code padChar } as necessary to reach that length . [CODESPLIT] public static String padLeft ( String str , int len , char padChar ) { Parameters . checkCondition ( len >= 0 ) ; StringBuilder sb = new StringBuilder ( len ) ; while ( sb . length ( ) < len - str . length ( ) ) { sb . append ( padChar ) ; } sb . append ( str ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code String } of length at least { @code len } created by appending as many copies of { @code padChar } as necessary to reach that length . [CODESPLIT] public static String padRight ( String str , int len , char padChar ) { Parameters . checkNotNull ( str ) ; Parameters . checkCondition ( len >= 0 ) ; StringBuilder sb = new StringBuilder ( len ) ; sb . append ( str ) ; while ( sb . length ( ) < len ) { sb . append ( padChar ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Quotes the given { @code String } with double quotes . If the given { @code String } has multiple quotes only one of them is kept . [CODESPLIT] public static String quote ( String str ) { return new StringBuilder ( str . length ( ) + 2 ) . append ( \"\\\"\" ) . append ( unquote ( str ) ) . append ( \"\\\"\" ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unquotes the given { @code String } that is this method removes any leading or trailing double quotes . If the given { @code String } is not quoted returns it unmodified . [CODESPLIT] public static String unquote ( String str ) { String unquoted = str ; while ( unquoted . startsWith ( \"\\\"\" ) ) { unquoted = unquoted . substring ( 1 ) ; } while ( unquoted . endsWith ( \"\\\"\" ) ) { unquoted = unquoted . substring ( 0 , unquoted . length ( ) - 1 ) ; } return unquoted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Counts the occurrences of the substring { @code sub } in { @code str } . [CODESPLIT] public static int countOccurrences ( String str , String sub ) { Parameters . checkNotNull ( str ) ; int n = 0 ; if ( ! sub . isEmpty ( ) ) { int start = 0 ; while ( true ) { start = str . indexOf ( sub , start ) ; if ( start == - 1 ) { break ; } start += sub . length ( ) ; n ++ ; } } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code URL } by parsing the given { @code String } . This function invokes the { @link URL#URL ( java . lang . String ) } constructor ; any { @code MalformedURLException } thrown by the constructor is caught and wrapped in a new { @code IllegalArgumentException } which is then thrown . This method is provided for use in situations where it is known that the given { @code String } is a legal { @code URL } . [CODESPLIT] public static URL create ( String url ) { Parameters . checkNotNull ( url ) ; try { return new URL ( url ) ; } catch ( MalformedURLException ex ) { throw new IllegalArgumentException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Relativizes the specified full { @code URL } against the given base . Behaves as { @link java . net . URI#relativize ( java . net . URI ) } . [CODESPLIT] public static String relativize ( URL base , URL full ) { try { return base . toURI ( ) . relativize ( full . toURI ( ) ) . normalize ( ) . toString ( ) ; } catch ( URISyntaxException ex ) { throw new IllegalArgumentException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the specified path against the given base { @code URL } . Behaves as { @link java . net . URI#resolve ( java . lang . String ) } . [CODESPLIT] public static URL resolve ( URL base , String path ) { try { return base . toURI ( ) . resolve ( path ) . normalize ( ) . toURL ( ) ; } catch ( URISyntaxException ex ) { throw new IllegalArgumentException ( ex ) ; } catch ( MalformedURLException ex ) { throw new IllegalArgumentException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the qualified name of the given class ( package name followed by a dot followed by the class name ) . For array classes this method returns the component type class name followed by as many [] as the array s dimension . [CODESPLIT] public static String getQualifiedName ( Class < ? > c ) { if ( c . isArray ( ) ) { StringBuilder qname = new StringBuilder ( ) ; while ( c . isArray ( ) ) { c = c . getComponentType ( ) ; qname . append ( \"[]\" ) ; } qname . insert ( 0 , c . getName ( ) ) ; return qname . toString ( ) ; } return c . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns only the name of the given class that is without its package name and without its eventual outer class name . [CODESPLIT] public static String getShortName ( Class < ? > c ) { String qname = getQualifiedName ( c ) ; int start = qname . lastIndexOf ( ' ' ) ; if ( start == - 1 ) { start = qname . lastIndexOf ( ' ' ) ; } return qname . substring ( start + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name of the package of the given class or the empty { @code String } if the class is defined in the default package . [CODESPLIT] public static String getPackageName ( Class < ? > c ) { String name = c . getName ( ) ; int i = name . lastIndexOf ( ' ' ) ; return i != - 1 ? name . substring ( 0 , i ) : \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the super types of the given class that is all the classes in which any instance of the given class can be cast into . [CODESPLIT] public static Set < Class < ? > > getSuperTypes ( Class < ? > c ) { Set < Class < ? > > classes = new HashSet < Class < ? > > ( ) ; for ( Class < ? > clazz : c . getInterfaces ( ) ) { classes . add ( clazz ) ; classes . addAll ( getSuperTypes ( clazz ) ) ; } Class < ? > sup = c . getSuperclass ( ) ; if ( sup != null ) { classes . add ( sup ) ; classes . addAll ( getSuperTypes ( sup ) ) ; } return Collections . unmodifiableSet ( classes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code Set } of common super types of the given classes that is all the classes in which any instance of the given classes can be cast into . [CODESPLIT] public static Set < Class < ? > > getCommonSuperTypes ( Iterable < Class < ? > > classes ) { Iterator < Class < ? > > i = classes . iterator ( ) ; Parameters . checkCondition ( i . hasNext ( ) ) ; Set < Class < ? > > common = new HashSet < Class < ? > > ( getSuperTypes ( i . next ( ) ) ) ; while ( i . hasNext ( ) ) { common . retainAll ( getSuperTypes ( i . next ( ) ) ) ; } return Collections . unmodifiableSet ( common ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies that the given password matches the hashed one . [CODESPLIT] public static boolean verify ( String password , byte [ ] hash ) { byte [ ] h = Arrays . copyOf ( hash , HASH_LENGTH + SALT_LENGTH + 3 ) ; int n = 1 << ( h [ HASH_LENGTH + SALT_LENGTH ] & 0xFF ) ; int r = h [ HASH_LENGTH + SALT_LENGTH + 1 ] & 0xFF ; int p = h [ HASH_LENGTH + SALT_LENGTH + 2 ] & 0xFF ; if ( n > N || n < N_MIN || r > R || r < R_MIN || p > P || p < P_MIN ) { n = N ; r = R ; p = P ; } byte [ ] salt = new byte [ SALT_LENGTH ] ; System . arraycopy ( h , HASH_LENGTH , salt , 0 , SALT_LENGTH ) ; byte [ ] expected = hash ( password , salt , r , n , p ) ; int result = 0 ; for ( int i = 0 ; i < h . length ; i ++ ) { result |= h [ i ] ^ expected [ i ] ; } return result == 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the next line from the standard input using the given charset . [CODESPLIT] public static String readString ( Charset charset ) throws IOException { Reader in = new InputStreamReader ( System . in , charset ) ; BufferedReader reader = new BufferedReader ( in ) ; try { return reader . readLine ( ) ; } finally { reader . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the given byte to this buffer . [CODESPLIT] public ByteBuffer append ( byte b ) { int newCount = count + 1 ; ensureCapacity ( newCount ) ; buf [ count ] = b ; count = newCount ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the given data to this buffer . [CODESPLIT] public ByteBuffer append ( byte [ ] bytes , int off , int len ) { int newCount = count + len ; ensureCapacity ( newCount ) ; System . arraycopy ( bytes , off , buf , count , len ) ; count = newCount ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns { @code len } bytes from this buffer starting at { @code off } . [CODESPLIT] public byte [ ] toByteArray ( int off , int len ) { if ( off < 0 || len < 0 || off + len > count ) { throw new IndexOutOfBoundsException ( ) ; } byte [ ] data = new byte [ len ] ; System . arraycopy ( buf , off , data , 0 , len ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the given arrays into a single one . [CODESPLIT] public static long [ ] concat ( long [ ] ... arrays ) { int len = 0 ; for ( long [ ] array : arrays ) { len += array . length ; } long [ ] concat = new long [ len ] ; int i = 0 ; for ( long [ ] array : arrays ) { System . arraycopy ( array , 0 , concat , i , array . length ) ; i = array . length ; } return concat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the given arrays into a single one . [CODESPLIT] public static < T > T [ ] concat ( T [ ] ... arrays ) { Parameters . checkCondition ( arrays . length > 0 ) ; int len = 0 ; for ( T [ ] array : arrays ) { len += array . length ; } T [ ] concat = newArray ( arrays [ 0 ] . getClass ( ) . getComponentType ( ) , len ) ; int i = 0 ; for ( T [ ] array : arrays ) { System . arraycopy ( array , 0 , concat , i , array . length ) ; i = array . length ; } return concat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the specified range of elements from the given array into a new array . The returned array will be padded with { @code 0 } if necessary so that it has an exact length of { @code len } . [CODESPLIT] public static long [ ] copyOf ( long [ ] a , int off , int len ) { long [ ] copy = new long [ len ] ; if ( len > a . length - off ) { System . arraycopy ( a , off , copy , 0 , a . length - off ) ; } else { System . arraycopy ( a , off , copy , 0 , len ) ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the specified range of elements from the given array into a new array . The returned array will be padded with { @code null } if necessary so that it has an exact length of { @code len } . [CODESPLIT] public static < T > T [ ] copyOf ( T [ ] a , int off , int len ) { T [ ] copy = newArray ( a . getClass ( ) . getComponentType ( ) , len ) ; if ( len > a . length - off ) { System . arraycopy ( a , off , copy , 0 , a . length - off ) ; } else { System . arraycopy ( a , off , copy , 0 , len ) ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of the given array . The original array and the returned copy will have identical length and content . [CODESPLIT] public static < T > T [ ] copyOf ( T [ ] original ) { return Arrays . copyOf ( original , original . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array containing the same elements as the given one but in reverse order . [CODESPLIT] public static long [ ] reverse ( long ... a ) { int len = a . length ; long [ ] copy = new long [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { copy [ i ] = a [ len - i - 1 ] ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array containing the same elements as the given one but in reverse order . [CODESPLIT] public static < T > T [ ] reverse ( T [ ] a ) { int len = a . length ; T [ ] copy = newArray ( a . getClass ( ) . getComponentType ( ) , len ) ; for ( int i = 0 ; i < len ; i ++ ) { copy [ i ] = a [ len - i - 1 ] ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array containing the same elements as the given one but rotated by the given distance . The element at index { @code i } in the returned array corresponds to the element in the original array at index { @code ( i - distance ) } mod { @code a . length } for all values of { @code i } between { @code 0 } and { @code a . length - 1 } inclusive . Note that rotation by { @code 0 } or by a multiple of { @code a . length } is a no - op . [CODESPLIT] public static long [ ] rotate ( long [ ] a , int distance ) { int len = a . length ; long [ ] copy = new long [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { copy [ i ] = a [ index ( i - distance , len ) ] ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new array containing the same elements as the given one but rotated by the given distance . The element at index { @code i } in the returned array corresponds to the element in the original array at index { @code ( i - distance ) } mod { @code a . length } for all values of { @code i } between { @code 0 } and { @code a . length - 1 } inclusive . Note that rotation by { @code 0 } or by a multiple of { @code a . length } is a no - op . [CODESPLIT] public static < T > T [ ] rotate ( T [ ] a , int distance ) { int len = a . length ; T [ ] copy = newArray ( a . getClass ( ) . getComponentType ( ) , len ) ; for ( int i = 0 ; i < len ; i ++ ) { copy [ i ] = a [ index ( i - distance , len ) ] ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of the given array where its element have been randomly permuted using the specified source of randomness . All permutations occur with equal likelihood assuming that the source of randomness is fair . This method uses the optimized version of the Fisher - Yates shuffle algorithm ( Fisher Yates Durstenfeld Knuth ) and thus runs in linear time . [CODESPLIT] public static int [ ] shuffle ( int [ ] a , Random rnd ) { int [ ] copy = copyOf ( a ) ; for ( int i = copy . length ; i > 1 ; i -- ) { swap ( copy , i - 1 , rnd . nextInt ( i ) ) ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a sorted copy of the given array of objects into ascending order according to the natural ordering of its elements ( all elements in the array must implement the { @link Comparable } interface ) . [CODESPLIT] public static < T > T [ ] sort ( T [ ] a ) { T [ ] copy = copyOf ( a ) ; Arrays . sort ( copy ) ; return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a sorted copy of the given array of objects into ascending order according to the order induced by the given { @code Comparator } . [CODESPLIT] public static < T > T [ ] sort ( T [ ] a , Comparator < ? super T > c ) { T [ ] copy = Arrays . copyOf ( a , a . length ) ; Arrays . sort ( copy , c ) ; return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Long } s to an array of { @code long } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static long [ ] toPrimitive ( Long ... a ) { if ( a != null ) { long [ ] p = new long [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Integer } s to an array of { @code int } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static int [ ] toPrimitive ( Integer ... a ) { if ( a != null ) { int [ ] p = new int [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Short } s to an array of { @code short } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static short [ ] toPrimitive ( Short ... a ) { if ( a != null ) { short [ ] p = new short [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Character } s to an array of { @code char } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static char [ ] toPrimitive ( Character ... a ) { if ( a != null ) { char [ ] p = new char [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Byte } s to an array of { @code byte } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static byte [ ] toPrimitive ( Byte ... a ) { if ( a != null ) { byte [ ] p = new byte [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Boolean } s to an array of { @code boolean } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static boolean [ ] toPrimitive ( Boolean ... a ) { if ( a != null ) { boolean [ ] p = new boolean [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Float } s to an array of { @code float } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static float [ ] toPrimitive ( Float ... a ) { if ( a != null ) { float [ ] p = new float [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code Double } s to an array of { @code double } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static double [ ] toPrimitive ( Double ... a ) { if ( a != null ) { double [ ] p = new double [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { p [ i ] = a [ i ] ; } return p ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code long } s to an array of { @code Long } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Long [ ] toObject ( long ... a ) { if ( a != null ) { Long [ ] w = new Long [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code int } s to an array of { @code Integer } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Integer [ ] toObject ( int ... a ) { if ( a != null ) { Integer [ ] w = new Integer [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code short } s to an array of { @code Short } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Short [ ] toObject ( short ... a ) { if ( a != null ) { Short [ ] w = new Short [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code char } s to an array of { @code Character } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Character [ ] toObject ( char ... a ) { if ( a != null ) { Character [ ] w = new Character [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code byte } s to an array of { @code Byte } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Byte [ ] toObject ( byte ... a ) { if ( a != null ) { Byte [ ] w = new Byte [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code boolean } s to an array of { @code Boolean } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Boolean [ ] toObject ( boolean ... a ) { if ( a != null ) { Boolean [ ] w = new Boolean [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code float } s to an array of { @code Float } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Float [ ] toObject ( float ... a ) { if ( a != null ) { Float [ ] w = new Float [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of { @code double } s to an array of { @code Double } s . Returns { @code null } if the given array is { @code null } . Does not modify the input array . [CODESPLIT] public static Double [ ] toObject ( double ... a ) { if ( a != null ) { Double [ ] w = new Double [ a . length ] ; for ( int i = 0 ; i < a . length ; i ++ ) { w [ i ] = a [ i ] ; } return w ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes { @code len } ASCII encoded bytes from the given input buffer starting at { @code off } . [CODESPLIT] public static String decode ( byte [ ] input , int off , int len ) { CharsetDecoder decoder = Charsets . US_ASCII . newDecoder ( ) ; ByteBuffer buf = ByteBuffer . wrap ( input , off , len ) ; try { CharBuffer out = decoder . decode ( buf ) ; char [ ] chars = new char [ out . limit ( ) ] ; out . get ( chars ) ; return new String ( chars ) ; } catch ( CharacterCodingException ex ) { throw new IllegalArgumentException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code String } is an alphabetic sequence that is a sequence which only contains letters . [CODESPLIT] public static boolean isAlphabetic ( String str ) { for ( char c : str . toCharArray ( ) ) { if ( ! isLetter ( c ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns whether the given { @code String } is an alphanumeric sequence that is a sequence which only contains letters and digits . [CODESPLIT] public static boolean isAlphaNumeric ( String str ) { for ( char c : str . toCharArray ( ) ) { if ( ! isDigit ( c ) && ! isLetter ( c ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code String } in which all uppercase ASCII characters have been replaced by their lowercase equivalent ( all other characters are unchanged ) . [CODESPLIT] public static String toLowerCase ( String str ) { StringBuilder sb = new StringBuilder ( str . length ( ) ) ; for ( char c : str . toCharArray ( ) ) { sb . append ( toLowerCase ( c ) ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code BaseEncoding } that behaves as this one except that it adds the specified separator after every { @code n } characters when encoding data and ignores any occurence of the specified separator when decoding encoded data . [CODESPLIT] public BaseEncoding withSeparator ( String separator , int n ) { Parameters . checkCondition ( n > 0 ) ; for ( char c : separator . toCharArray ( ) ) { if ( isPaddingChar ( c ) || isInAlphabet ( c ) ) { throw new IllegalArgumentException ( \"Invalid separator character: '\" + c + \"'\" ) ; } } return new BaseEncoding ( alphabet , separator , n , omitPadding , ignoreUnknownChars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the given data bytes according to this { @code BaseEncoding } s configuration . [CODESPLIT] public String encode ( byte [ ] in , int off , int len ) { checkBounds ( in , off , len ) ; StringBuilder sb = new StringBuilder ( maxEncodedLength ( len ) ) ; int accu = 0 ; int count = 0 ; int b = alphabet . bitsPerChar ( ) ; for ( int i = off ; i < off + len ; i ++ ) { accu = ( accu << 8 ) | ( in [ i ] & 0xFF ) ; count += 8 ; while ( count >= b ) { count -= b ; sb . append ( alphabet . encode ( accu >>> count ) ) ; } } if ( count > 0 ) { accu = ( accu & ( 0xFF >>> ( 8 - count ) ) ) << ( b - count ) ; sb . append ( alphabet . encode ( accu ) ) ; if ( ! omitPadding ) { int c = alphabet . charsPerBlock ( ) ; int pad = c - ( sb . length ( ) % c ) ; for ( int i = 0 ; i < pad ; i ++ ) { sb . append ( PADDING_CHAR ) ; } } } insertSeparators ( sb ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the given encoded { @code String } according to this { @code BaseEncoding } s configuration . Decoding is not case - sensitive when possible ( namely for Base16 Base32 and Base32Hex schemes ) . [CODESPLIT] public byte [ ] decode ( String in ) { String encoded = n > 0 ? in . replace ( separator , \"\" ) : in ; ByteBuffer buf = new ByteBuffer ( maxDecodedLength ( encoded . length ( ) ) ) ; int accu = 0 ; int count = 0 ; int decoded = 0 ; for ( int i = 0 ; i < encoded . length ( ) ; i ++ ) { char c = encoded . charAt ( i ) ; if ( isPaddingChar ( c ) && ! omitPadding ) { break ; } int v = decode ( c ) ; if ( v != - 1 ) { decoded ++ ; accu = ( accu << alphabet . bitsPerChar ( ) ) | v ; count += alphabet . bitsPerChar ( ) ; while ( count >= 8 ) { count -= 8 ; buf . append ( ( byte ) ( accu >>> count ) ) ; } } } if ( ! omitPadding || ! alphabet . requiresPadding ( ) ) { decoded += getPaddingLength ( encoded ) ; int blockSize = alphabet . charsPerBlock ( ) ; Parameters . checkCondition ( decoded % blockSize == 0 ) ; } return buf . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the specified range from the given encoded { @code String } according to this { @code BaseEncoding } s configuration . Decoding is not case - sensitive when possible ( namely for Base16 Base32 and Base32Hex schemes ) . [CODESPLIT] public byte [ ] decode ( String in , int off , int len ) { return decode ( in . substring ( off , off + len ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code Fraction } representation of the given value . [CODESPLIT] public static Fraction valueOf ( Integer val ) { return new Fraction ( BigInteger . valueOf ( val ) , BigInteger . ONE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @code Fraction } from its { @code String } representation . [CODESPLIT] public static Fraction parse ( String str ) { String fraction = str . replaceAll ( \"\\\\s\" , \"\" ) ; int index = fraction . indexOf ( ' ' ) ; if ( index < 0 ) { return valueOf ( new BigInteger ( fraction ) ) ; } BigInteger n = new BigInteger ( fraction . substring ( 0 , index ) ) ; BigInteger d = new BigInteger ( fraction . substring ( index + 1 ) ) ; return new Fraction ( n , d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given value to this one and returns the result in reduced form . [CODESPLIT] public Fraction plus ( Fraction f ) { return new Fraction ( n . multiply ( f . d ) . add ( f . n . multiply ( d ) ) , d . multiply ( f . d ) ) . reduced ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtracts the given value from this one and returns the result in reduced form . [CODESPLIT] public Fraction minus ( Fraction f ) { return new Fraction ( n . multiply ( f . d ) . subtract ( f . n . multiply ( d ) ) , d . multiply ( f . d ) ) . reduced ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiplies this value by the given one and returns the result in reduced form . [CODESPLIT] public Fraction multipliedBy ( Fraction f ) { return new Fraction ( n . multiply ( f . n ) , d . multiply ( f . d ) ) . reduced ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divides this value by the given one and returns the result in reduced form . [CODESPLIT] public Fraction dividedBy ( Fraction f ) { if ( ZERO . equals ( f ) ) { throw new ArithmeticException ( \"Division by zero\" ) ; } return new Fraction ( n . multiply ( f . d ) , d . multiply ( f . n ) ) . reduced ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code Fraction } obtained by raising this to the given power in reduced form . [CODESPLIT] public Fraction power ( int exponent ) { return new Fraction ( n . pow ( exponent ) , d . pow ( exponent ) ) . reduced ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the opposite of this { @code Fraction } . The result is not reduced before being returned . [CODESPLIT] public Fraction negated ( ) { if ( d . signum ( ) < 0 ) { return new Fraction ( n , d . negate ( ) ) ; } return new Fraction ( n . negate ( ) , d ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the reduced form of this { @code Fraction } . Also note that the sign information will be held by the numerator . [CODESPLIT] public Fraction reduced ( ) { BigInteger gcd = n . gcd ( d ) ; if ( d . signum ( ) < 0 ) { BigInteger numerator = n . divide ( gcd ) . negate ( ) ; BigInteger denominator = d . divide ( gcd ) . negate ( ) ; return new Fraction ( numerator , denominator ) ; } return new Fraction ( n . divide ( gcd ) , d . divide ( gcd ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableSet } from the given { @code Collection } . [CODESPLIT] public static < E > Set < E > copyOf ( Collection < ? extends E > c ) { return new ImmutableSet < E > ( new LinkedHashSet < E > ( c ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableSet } from the given { @code Iterable } . [CODESPLIT] public static < E > Set < E > copyOf ( Iterable < ? extends E > i ) { return new ImmutableSet < E > ( Iterables . toSet ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableSet } from the given { @code Iterator } . [CODESPLIT] public static < E > Set < E > copyOf ( Iterator < ? extends E > i ) { return new ImmutableSet < E > ( Iterators . toSet ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableSet } containing the given elements . [CODESPLIT] public static < E > Set < E > copyOf ( E [ ] values ) { return new ImmutableSet < E > ( new LinkedHashSet < E > ( Arrays . asList ( values ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableSet } containing the given elements . [CODESPLIT] public static < E > Set < E > of ( E ... values ) { return new ImmutableSet < E > ( new LinkedHashSet < E > ( Arrays . asList ( values ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given duration s { @code String } representation into a { @code Duration } instance . The given { @code String } must be a list of value / unit pairs separated by + - \\ n \\ t \\ r { @code & } or characters or by the and { @code String } . Values must be integer ( either positive or negative ) values . Valid units are : milliseconds millisecond millis and ms for milliseconds seconds second sec secs and s for seconds minutes minute min mins and m for minutes hours hour and h for hours days day and d for days . Values must be separated from their unit by a whitespace character . Parsing is not case sensitive . [CODESPLIT] public static Duration parse ( String duration ) { String [ ] tokens = duration . toLowerCase ( ) . replace ( \"and\" , \"\" ) . replaceAll ( \"[,&\\\\+]\" , \" \" ) . replaceAll ( \"-\\\\s+\" , \"-\" ) . replace ( \"--\" , \"\" ) . replaceAll ( \"[\\n\\t\\r]\" , \" \" ) . trim ( ) . replaceAll ( \"\\\\s+\" , \" \" ) . split ( \"\\\\s\" ) ; Parameters . checkCondition ( tokens . length % 2 == 0 ) ; long ms = 0L ; for ( int i = 0 ; i < tokens . length ; i += 2 ) { long v = Long . parseLong ( tokens [ i ] ) ; TimeUnit u = parseTimeUnit ( tokens [ i + 1 ] ) ; ms = safeAdd ( ms , MILLISECONDS . convert ( v , u ) ) ; } return new Duration ( ms ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code Duration } representing the given amount in the given unit . [CODESPLIT] public static Duration of ( long amount , TimeUnit unit ) { long duration = MILLISECONDS . convert ( amount , unit ) ; if ( unit . convert ( duration , MILLISECONDS ) != amount ) { throw new ArithmeticException ( \"Too large duration: \" + amount + \" \" + unit ) ; } return new Duration ( duration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code Duration } instance by summing all the given { @code Duration } s values . [CODESPLIT] public static Duration of ( Duration ... durations ) { if ( durations . length == 0 ) { return new Duration ( 0L ) ; } long ms = durations [ 0 ] . milliseconds ; for ( int i = 1 ; i < durations . length ; i ++ ) { ms = safeAdd ( ms , durations [ i ] . milliseconds ) ; } return new Duration ( ms ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code Duration } instance representing the amount of time elapsed between the given dates . [CODESPLIT] public static Duration between ( Date start , Date end ) { return new Duration ( end . getTime ( ) - start . getTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the maximum of the given values . [CODESPLIT] public static long max ( long ... values ) { Parameters . checkCondition ( values . length > 0 ) ; long max = values [ 0 ] ; for ( int i = 1 ; i < values . length ; i ++ ) { max = Math . max ( max , values [ i ] ) ; } return max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the minimum of the given values . [CODESPLIT] public static long min ( long ... values ) { Parameters . checkCondition ( values . length > 0 ) ; long min = values [ 0 ] ; for ( int i = 1 ; i < values . length ; i ++ ) { min = Math . min ( min , values [ i ] ) ; } return min ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the arithmetic mean of the given values . This method is not subject to overflow . [CODESPLIT] public static double mean ( int ... values ) { Parameters . checkCondition ( values . length > 0 ) ; long sum = 0L ; for ( int value : values ) { sum += value ; } return ( double ) sum / values . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the arithmetic mean of the given values . This method is not subject to overflow . [CODESPLIT] public static double mean ( long ... values ) { Parameters . checkCondition ( values . length > 0 ) ; BigDecimal sum = BigDecimal . ZERO ; for ( long value : values ) { sum = sum . add ( BigDecimal . valueOf ( value ) ) ; } return sum . divide ( BigDecimal . valueOf ( values . length ) ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute value of the given value provided the result fits into a { @code long } . [CODESPLIT] public static long safeAbs ( long a ) { if ( a == Long . MIN_VALUE ) { throw new ArithmeticException ( \"Long overflow: abs(\" + a + \")\" ) ; } return Math . abs ( a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the absolute value of the given value provided the result fits into an { @code int } . [CODESPLIT] public static int safeAbs ( int a ) { if ( a == Integer . MIN_VALUE ) { throw new ArithmeticException ( \"Int overflow: abs(\" + a + \")\" ) ; } return Math . abs ( a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the difference of { @code a } and { @code b } provided the result fits into a { @code long } . [CODESPLIT] public static long safeSubtract ( long a , long b ) { long diff = a - b ; if ( a < 0L != diff < 0L && a < 0L != b < 0L ) { throw new ArithmeticException ( \"Long overflow: \" + a + \" - \" + b ) ; } return diff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the product of { @code a } and { @code b } provided the result fits into a { @code long } . [CODESPLIT] public static long safeMultiply ( long a , long b ) { if ( a == 0L || b == 0L ) { return 0L ; } long max = a < 0L == b < 0L ? Long . MAX_VALUE : Long . MIN_VALUE ; if ( ( b > 0L && b > max / a ) || ( b < 0L && b < max / a ) ) { throw new ArithmeticException ( \"Long overflow: \" + a + \" * \" + b ) ; } return a * b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the product of { @code a } and { @code b } provided the result fits into an { @code int } . [CODESPLIT] public static int safeMultiply ( int a , int b ) { if ( a == 0 || b == 0 ) { return 0 ; } long max = a < 0 == b < 0 ? Integer . MAX_VALUE : Integer . MIN_VALUE ; if ( ( b > 0 && b > max / a ) || ( b < 0 && b < max / a ) ) { throw new ArithmeticException ( \"Int overflow: \" + a + \" * \" + b ) ; } return a * b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the result of the integer division of the first number by the second provided the result fits into a { @code long } . [CODESPLIT] public static long safeDivide ( long a , long b ) { if ( a == Long . MIN_VALUE && b == - 1L ) { throw new ArithmeticException ( \"Long overflow: \" + a + \" / \" + b ) ; } return a / b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the result of the integer division of the first number by the second provided the result fits into an { @code int } . [CODESPLIT] public static int safeDivide ( int a , int b ) { if ( a == Integer . MIN_VALUE && b == - 1L ) { throw new ArithmeticException ( \"Int overflow: \" + a + \" / \" + b ) ; } return a / b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of the first argument raised to the power of the second provided the result fits into a { @code long } . This method implements the exponentiation by squaring method . Please refer to <a href = http : // en . wikipedia . org / wiki / Exponentiation_by_squaring > Wikipedia< / a > for further information . [CODESPLIT] public static long safePow ( long a , int b ) { Parameters . checkCondition ( b >= 0 ) ; if ( b == 0 ) { return 1L ; } long base = a ; int exponent = b ; long result = 1L ; try { while ( exponent > 1 ) { if ( ( exponent & 1 ) != 0 ) { result = safeMultiply ( result , base ) ; exponent -= 1 ; } base = safeMultiply ( base , base ) ; exponent >>= 1 ; } return safeMultiply ( result , base ) ; } catch ( ArithmeticException e ) { throw new ArithmeticException ( \"Long overflow: \" + a + \" ^ \" + b ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the greatest common divisor of the absolute value of the given two numbers . This method first computes the absolute values of the given numbers thus it doesn t accept { @code Long . MIN_VALUE } . Also note that if one of the given values is { @code 0 } this method will return the absolute value of the second argument . This method implements the binary GCD algorithm ( also known as Stein s algorithm ) . For further information on this algorithm please refer to <a href = http : // en . wikipedia . org / wiki / Binary_GCD_algorithm > Wikipedia< / a > . [CODESPLIT] public static long gcd ( long a , long b ) { if ( a < 0L || b < 0L ) { try { return gcd ( safeAbs ( a ) , safeAbs ( b ) ) ; } catch ( ArithmeticException e ) { throw new ArithmeticException ( \"Long overflow: gcd(\" + a + \", \" + b + \")\" ) ; } } if ( a == 0L ) { return b ; } if ( b == 0L ) { return a ; } int shift = 0 ; while ( ( ( a | b ) & 1L ) == 0 ) { a >>= 1 ; b >>= 1 ; shift ++ ; } while ( ( a & 1L ) == 0L ) { a >>= 1 ; } do { while ( ( b & 1L ) == 0L ) { b >>= 1 ; } if ( a > b ) { long tmp = b ; b = a ; a = tmp ; } b -= a ; } while ( b != 0L ) ; return a << shift ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the greatest common divisor of the absolute value of the given two numbers . This method first computes the absolute values of the given numbers thus it doesn t accept { @code Integer . MIN_VALUE } . Also note that if one of the given values is { @code 0 } this method will return the absolute value of the second argument . This method implements the binary GCD algorithm ( also known as Stein s algorithm ) . For further information on this algorithm please refer to <a href = http : // en . wikipedia . org / wiki / Binary_GCD_algorithm > Wikipedia< / a > . [CODESPLIT] public static int gcd ( int a , int b ) { try { if ( a < 0 || b < 0 ) { return gcd ( safeAbs ( a ) , safeAbs ( b ) ) ; } return ( int ) gcd ( ( long ) a , ( long ) b ) ; } catch ( ArithmeticException e ) { throw new ArithmeticException ( \"Int overflow: gcd(\" + a + \", \" + b + \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the least common multiple of the absolute value of the given two numbers . This method first computes the absolute values of the given numbers thus it doesn t accept { @code Long . MIN_VALUE } . Also note that if one of the given values is { @code 0 } this method will return the absolute value of the second argument . This method uses the formula { @code lcm ( a b ) = ( a / gcd ( a b )) * b } . Please refer to <a href = http : // en . wikipedia . org / wiki / Least_common_multiple > Wikipedia< / a > for further information . [CODESPLIT] public static long lcm ( long a , long b ) { try { if ( a < 0L || b < 0L ) { return lcm ( safeAbs ( a ) , safeAbs ( b ) ) ; } if ( a == 0L ) { return b ; } if ( b == 0L ) { return a ; } return safeMultiply ( a / gcd ( a , b ) , b ) ; } catch ( ArithmeticException e ) { throw new ArithmeticException ( \"Long overflow: lcm(\" + a + \", \" + b + \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Casts the given { @code long } value to { @code int } if possible . [CODESPLIT] public static int safeToInt ( long a ) { if ( a >= Integer . MIN_VALUE && a <= Integer . MAX_VALUE ) { return ( int ) a ; } throw new ArithmeticException ( a + \" can't be cast to int\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the given reference is not { @code null } and returns it in case of success . [CODESPLIT] public static < T > T checkNotNull ( T ref , String msg , Object ... args ) { if ( ref == null ) { throw new NullPointerException ( format ( msg , args ) ) ; } return ref ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the truth of the given condition checking parameters validity . [CODESPLIT] public static void checkCondition ( boolean condition , String msg , Object ... args ) { if ( ! condition ) { throw new IllegalArgumentException ( format ( msg , args ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the type of the given reference and in case of success casts and returns it . [CODESPLIT] public static < T > T checkType ( Object ref , Class < T > type ) { if ( type . isInstance ( ref ) ) { return type . cast ( ref ) ; } throw new ClassCastException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the type of the given reference and in case of success casts and returns it . [CODESPLIT] public static < T > T checkType ( Object ref , Class < T > type , String msg , Object ... args ) { if ( type . isInstance ( ref ) ) { return type . cast ( ref ) ; } throw new ClassCastException ( format ( msg , args ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a logical and on the given values that is this method returns { @code true } if and only if all the given { @code Boolean } values are { @code true } and { @code false } in all other cases . [CODESPLIT] public static Boolean and ( Boolean ... bools ) { Parameters . checkCondition ( bools . length > 0 ) ; for ( Boolean bool : bools ) { if ( ! bool ) { return FALSE ; } } return TRUE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an exclusive or on the given values that is this method returns { @code true } if and only if only one of the given { @code Boolean } values is { @code true } and { @code false } in all other cases . [CODESPLIT] public static Boolean xor ( Boolean ... bools ) { Parameters . checkCondition ( bools . length > 0 ) ; boolean xor = false ; for ( Boolean bool : bools ) { if ( bool ) { if ( xor ) { return FALSE ; } else { xor = true ; } } } return xor ? TRUE : FALSE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given { @code String } into a { @code Boolean } . This method returns { @code true } if the given { @code String } contains true yes 1 or on . [CODESPLIT] public static Boolean valueOf ( String bool ) { String s = bool . replaceAll ( \"\\\\s\" , \"\" ) ; boolean b = \"true\" . equalsIgnoreCase ( s ) || \"yes\" . equalsIgnoreCase ( s ) || \"on\" . equalsIgnoreCase ( s ) || \"1\" . equalsIgnoreCase ( s ) ; return b ? TRUE : FALSE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Splitter } that will use the specified separator to split { @code String } s . [CODESPLIT] public static Splitter on ( String separator ) { return on ( Pattern . compile ( Pattern . quote ( separator ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Splitter } that will use the specified pattern to split { @code String } s . [CODESPLIT] public static Splitter on ( Pattern pattern ) { return new Splitter ( - 1 , false , pattern , null , null , \"\" , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Splitter } that will behave as this one except that it will limit the number of times the splitting pattern is applied . If { @code limit } is strictly positive then the pattern will be applied at most { @code limit - 1 } times . If { @code limit } is non - positive then the splitting pattern will be applied as many times as possible . [CODESPLIT] public Splitter limit ( int limit ) { return new Splitter ( limit == 0 ? - 1 : limit , trim , pattern , prefix , suffix , forEmpty , ignoreEmptyStrings ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Splitter } that will behave as this one except that it will ignore the given prefix . [CODESPLIT] public Splitter ignorePrefix ( String prefix ) { Parameters . checkNotNull ( prefix ) ; return new Splitter ( limit , trim , pattern , prefix , suffix , forEmpty , ignoreEmptyStrings ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Splitter } that will behave as this one except that it will ignore the given suffix . [CODESPLIT] public Splitter ignoreSuffix ( String suffix ) { Parameters . checkNotNull ( suffix ) ; return new Splitter ( limit , trim , pattern , prefix , suffix , forEmpty , ignoreEmptyStrings ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Splitter } that will behave as this one except that it will ignore empty results . [CODESPLIT] public Splitter ignoreEmptyStrings ( ) { return new Splitter ( limit , trim , pattern , prefix , suffix , forEmpty , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Splitter } that will behave as this one except that it will replace empty results by the specified { @code String } . [CODESPLIT] public Splitter replaceEmptyStringWith ( String forEmpty ) { return new Splitter ( limit , trim , pattern , prefix , suffix , forEmpty , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits the given { @code String } into parts according to its configuration . [CODESPLIT] public List < String > split ( String s ) { String [ ] parts = pattern . split ( removePrefixAndSuffix ( s ) , limit ) ; List < String > results = new ArrayList < String > ( parts . length ) ; for ( String part : parts ) { String str = trim ? part . trim ( ) : part ; if ( ! str . isEmpty ( ) ) { results . add ( str ) ; } else if ( ! ignoreEmptyStrings ) { results . add ( forEmpty ) ; } } return Collections . unmodifiableList ( results ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Comparator } that will call each { @code Comparator } in the given array until one of them returns a non - zero result ( will return { @code 0 } if they all return { @code 0 } ) . [CODESPLIT] public static < T > Comparator < T > compose ( Comparator < ? super T > ... comparators ) { return compose ( Arrays . asList ( comparators ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Comparator } that will call each { @code Comparator } in the given { @code Iterable } until one of them returns a non - zero result ( will return { @code 0 } if they all return { @code 0 } ) . [CODESPLIT] public static < T > Comparator < T > compose ( Iterable < ? extends Comparator < ? super T > > comparators ) { return new CompositeComparator < T > ( comparators ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Comparator } that represents the reverse ordering of the given one . Namely the returned { @code Comparator } will return a negative value if the original returns a positive value and conversely will return a positive value if it returns a negative value . [CODESPLIT] public static < T > Comparator < T > reverse ( final Comparator < T > comparator ) { Parameters . checkNotNull ( comparator ) ; return new Comparator < T > ( ) { @ Override public int compare ( T o1 , T o2 ) { return - comparator . compare ( o1 , o2 ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @code Comparator } that compares { @code Comparable } objects in natural order . The returned comparator doesn t accept { @code null } values . [CODESPLIT] public static < T extends Comparable < ? super T > > Comparator < T > naturalOrder ( ) { return new Comparator < T > ( ) { @ Override public int compare ( T o1 , T o2 ) { return o1 . compareTo ( Parameters . checkNotNull ( o2 ) ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Comparator } that considers { @code null } values as less than all other values and compares non - { @code null } values with the given { @code Comparator } . [CODESPLIT] public static < T > Comparator < T > withNullsFirst ( final Comparator < T > comparator ) { Parameters . checkNotNull ( comparator ) ; return new Comparator < T > ( ) { @ Override public int compare ( T o1 , T o2 ) { return o1 == o2 ? 0 : o1 == null ? - 1 : o2 == null ? 1 : comparator . compare ( o1 , o2 ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Joiner } that will behave as this one except that it will trim inputs before joining them . [CODESPLIT] public Joiner trimInputs ( ) { return new Joiner ( separator , prefix , suffix , true , ignoreNull , ignoreEmpty , forNull , forEmpty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Joiner } that will behave as this one except that it will ignore { @code null } input values . [CODESPLIT] public Joiner ignoreNulls ( ) { return new Joiner ( separator , prefix , suffix , trim , true , ignoreEmpty , forNull , forEmpty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Joiner } that will behave as this one except that it will ignore empty input { @code String } s . [CODESPLIT] public Joiner ignoreEmptyStrings ( ) { return new Joiner ( separator , prefix , suffix , trim , ignoreNull , true , forNull , forEmpty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Joiner } that will behave as this one except that it will replace { @code null } input values with the specified { @code String } . [CODESPLIT] public Joiner replaceNullWith ( String forNull ) { return new Joiner ( separator , prefix , suffix , trim , false , ignoreEmpty , forNull , forEmpty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Joiner } that will behave as this one except that it will replace empty input { @code String } s with the specified value . [CODESPLIT] public Joiner replaceEmptyStringWith ( String forEmpty ) { return new Joiner ( separator , prefix , suffix , trim , ignoreNull , false , forNull , forEmpty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new { @code Joiner } that will behave as this one except that it will use the specified prefix when joining { @code String } s . [CODESPLIT] public Joiner withPrefix ( String prefix ) { return new Joiner ( separator , prefix , suffix , trim , ignoreNull , ignoreEmpty , forNull , forEmpty ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins the given { @code String } s according to its configuration . [CODESPLIT] public String join ( Iterable < ? > parts ) { boolean first = true ; StringBuilder sb = new StringBuilder ( prefix ) ; for ( Object part : parts ) { String s = format ( part ) ; if ( s != null ) { if ( first ) { first = false ; } else { sb . append ( separator ) ; } sb . append ( s ) ; } } return sb . append ( suffix ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a { @link Digest } instance corresponding to the given algorithm . [CODESPLIT] static Digest newDigest ( Algorithm < Digest > algorithm ) { Parameters . checkNotNull ( algorithm ) ; Digest digest ; if ( algorithm == Algorithm . MD2 ) { digest = Digests . md2 ( ) ; } else if ( algorithm == Algorithm . MD4 ) { digest = Digests . md4 ( ) ; } else if ( algorithm == Algorithm . MD5 ) { digest = Digests . md5 ( ) ; } else if ( algorithm == Algorithm . SHA1 ) { digest = Digests . sha1 ( ) ; } else if ( algorithm == Algorithm . SHA256 ) { digest = Digests . sha256 ( ) ; } else if ( algorithm == Algorithm . SHA512 ) { digest = Digests . sha512 ( ) ; } else if ( algorithm == Algorithm . KECCAK224 ) { digest = Digests . keccak224 ( ) ; } else if ( algorithm == Algorithm . KECCAK256 ) { digest = Digests . keccak256 ( ) ; } else if ( algorithm == Algorithm . KECCAK384 ) { digest = Digests . keccak384 ( ) ; } else if ( algorithm == Algorithm . KECCAK512 ) { digest = Digests . keccak512 ( ) ; } else { throw new IllegalArgumentException ( \"Unknown algorithm\" ) ; } return digest ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns a { @link MAC } instance corresponding to the given algorithm initialized with the provided secret key . [CODESPLIT] static MAC newMAC ( Algorithm < MAC > algorithm , byte [ ] key ) { Parameters . checkNotNull ( algorithm ) ; MAC mac ; if ( algorithm == Algorithm . HMAC_MD2 ) { mac = HMAC . md2 ( key ) ; } else if ( algorithm == Algorithm . HMAC_MD4 ) { mac = HMAC . md4 ( key ) ; } else if ( algorithm == Algorithm . HMAC_MD5 ) { mac = HMAC . md5 ( key ) ; } else if ( algorithm == Algorithm . HMAC_SHA1 ) { mac = HMAC . sha1 ( key ) ; } else if ( algorithm == Algorithm . HMAC_SHA256 ) { mac = HMAC . sha256 ( key ) ; } else if ( algorithm == Algorithm . HMAC_SHA512 ) { mac = HMAC . sha512 ( key ) ; } else if ( algorithm == Algorithm . HMAC_KECCAK224 ) { mac = HMAC . keccak224 ( key ) ; } else if ( algorithm == Algorithm . HMAC_KECCAK256 ) { mac = HMAC . keccak256 ( key ) ; } else if ( algorithm == Algorithm . HMAC_KECCAK384 ) { mac = HMAC . keccak384 ( key ) ; } else if ( algorithm == Algorithm . HMAC_KECCAK512 ) { mac = HMAC . keccak512 ( key ) ; } else { throw new IllegalArgumentException ( \"Unknown algorithm\" ) ; } return mac ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableBag } from the given { @code Collection } . [CODESPLIT] public static < E > Bag < E > copyOf ( Collection < ? extends E > c ) { return new ImmutableBag < E > ( new ArrayBag < E > ( c ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableBag } from the given { @code Iterable } . [CODESPLIT] public static < E > Bag < E > copyOf ( Iterable < ? extends E > i ) { return new ImmutableBag < E > ( new ArrayBag < E > ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableBag } from the given { @code Iterator } . [CODESPLIT] public static < E > Bag < E > copyOf ( Iterator < ? extends E > i ) { return new ImmutableBag < E > ( new ArrayBag < E > ( i ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableBag } containing the given elements . [CODESPLIT] public static < E > Bag < E > copyOf ( E [ ] values ) { return new ImmutableBag < E > ( new ArrayBag < E > ( values ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code ImmutableBag } containing the given elements . [CODESPLIT] public static < E > Bag < E > of ( E ... values ) { return new ImmutableBag < E > ( new ArrayBag < E > ( values ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] private String getRelationHref ( Link link , Object [ ] args , Annotation [ ] [ ] parameterAnnotations ) { HalLink halLink = halResource . getLink ( link . relation ( ) ) ; if ( halLink == null ) { throw new UnsupportedOperationException ( link . relation ( ) ) ; } if ( halLink . getDeprecation ( ) != null ) { log . warn ( \"Link '\" + link + \"' has been deprecated: \" + halLink . getDeprecation ( ) ) ; } String href ; if ( halLink . isTemplated ( ) ) { try { UriTemplate uriTemplate = UriTemplate . fromTemplate ( halLink . getHref ( ) ) ; for ( int i = 0 ; i < args . length ; i ++ ) { for ( Annotation annotation : parameterAnnotations [ i ] ) { if ( annotation . annotationType ( ) == UriVariable . class ) { UriVariable uriVariable = ( UriVariable ) annotation ; assignTemplateValue ( uriTemplate , uriVariable . name ( ) , args [ i ] ) ; } } } for ( int i = 0 ; i < link . uriValues ( ) . length ; i ++ ) { UriValue uriValue = link . uriValues ( ) [ i ] ; assignTemplateValue ( uriTemplate , uriValue . name ( ) , uriValue . value ( ) ) ; } href = uriTemplate . expand ( ) ; } catch ( MalformedUriTemplateException | VariableExpansionException e ) { throw new RuntimeException ( e ) ; } } else { href = halLink . getHref ( ) ; } return href ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] public AmazonServiceException handle ( HttpResponse response ) throws Exception { JSONObject jsonBody = getBodyAsJson ( response ) ; Class < ? extends AmazonServiceException > exceptionClass = exceptionClasses . get ( response . getStatusCode ( ) ) ; AmazonServiceException result ; // Support other attribute names for the message? // TODO: Inspect exception type (caching details) and apply other values from the body String message = jsonBody . has ( \"message\" ) ? jsonBody . getString ( \"message\" ) : jsonBody . getString ( \"Message\" ) ; if ( exceptionClass != null ) { result = exceptionClass . getConstructor ( String . class ) . newInstance ( message ) ; } else { result = AmazonServiceException . class . getConstructor ( String . class ) . newInstance ( message ) ; } result . setServiceName ( response . getRequest ( ) . getServiceName ( ) ) ; result . setStatusCode ( response . getStatusCode ( ) ) ; if ( response . getStatusCode ( ) < 500 ) { result . setErrorType ( ErrorType . Client ) ; } else { result . setErrorType ( ErrorType . Service ) ; } for ( Entry < String , String > headerEntry : response . getHeaders ( ) . entrySet ( ) ) { if ( headerEntry . getKey ( ) . equalsIgnoreCase ( \"X-Amzn-RequestId\" ) ) { result . setRequestId ( headerEntry . getValue ( ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] private JSONObject getBodyAsJson ( HttpResponse response ) { try ( InputStream stream = response . getContent ( ) ) { BufferedReader reader = new BufferedReader ( new InputStreamReader ( stream ) ) ; StringBuilder sb = new StringBuilder ( ) ; while ( true ) { String line = reader . readLine ( ) ; if ( line == null ) { break ; } sb . append ( line ) ; } return new JSONObject ( sb . length ( ) == 0 ? \"{}\" : sb . toString ( ) ) ; } catch ( IOException e ) { throw new AmazonClientException ( \"Unable to read error response: \" + e . getMessage ( ) , e ) ; } catch ( JSONException e ) { throw new AmazonClientException ( \"Unable to parse error response: \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public Map < String , HalResource > unmarshall ( JsonUnmarshallerContext context ) throws Exception { Map < String , HalResource > embedded = new LinkedHashMap <> ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { // Ignore the field name and move to the next token.  The item's key will be the embedded resource's selfHref. token = context . nextToken ( ) ; if ( token == JsonToken . START_ARRAY ) { List < HalResource > halResources = new HalJsonArrayUnmarshaller <> ( HalJsonResourceUnmarshaller . getInstance ( ) ) . unmarshall ( context ) ; for ( HalResource halResource : halResources ) { embedded . put ( halResource . _getSelfHref ( ) , halResource ) ; } } else { HalResource halResource = HalJsonResourceUnmarshaller . getInstance ( ) . unmarshall ( context ) ; embedded . put ( halResource . _getSelfHref ( ) , halResource ) ; } } token = context . nextToken ( ) ; } return embedded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] private HalClient getHalClient ( ) { if ( halClient == null ) { this . halClient = new HalClient ( clientConfiguration == null ? new ClientConfiguration ( ) : clientConfiguration , endpoint , serviceName , awsCredentialsProvider == null ? new DefaultAWSCredentialsProviderChain ( ) : awsCredentialsProvider , resourceCache == null ? ImmediatelyExpiringCache . getInstance ( ) : resourceCache , errorResponseHandler ) ; if ( regionId != null ) { halClient . setSignerRegionOverride ( regionId ) ; } } return halClient ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public List < Object > unmarshall ( JsonUnmarshallerContext context ) throws Exception { List < Object > list = new ArrayList <> ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != JsonToken . END_ARRAY ) { if ( token . isScalarValue ( ) ) { list . add ( JsonUnmarshallerUtil . getObjectForToken ( token , context ) ) ; } else if ( token == JsonToken . START_OBJECT ) { context . nextToken ( ) ; list . add ( HalJsonMapUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else if ( token == JsonToken . START_ARRAY ) { context . nextToken ( ) ; list . add ( HalJsonListUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } token = context . nextToken ( ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public Map < String , Object > unmarshall ( JsonUnmarshallerContext context ) throws Exception { Map < String , Object > map = new HashMap <> ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { String property = context . readText ( ) ; token = context . nextToken ( ) ; if ( token == JsonToken . START_OBJECT ) { context . nextToken ( ) ; map . put ( property , HalJsonMapUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else if ( token == JsonToken . START_ARRAY ) { context . nextToken ( ) ; map . put ( property , HalJsonListUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else { map . put ( property , JsonUnmarshallerUtil . getObjectForToken ( token , context ) ) ; } } token = context . nextToken ( ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] public < T > T getResource ( Class < T > resourceClass , String resourcePath ) { return getResource ( null , resourceClass , resourcePath , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] < T > T getResource ( HalResource sourceResource , Class < T > resourceClass , String resourcePath , boolean lazy ) { if ( resourceCache . containsKey ( resourcePath ) ) { return resourceClass . cast ( resourceCache . get ( resourcePath ) ) ; } HalResource halResource ; if ( sourceResource != null && sourceResource . getEmbedded ( ) . containsKey ( resourcePath ) ) { halResource = sourceResource . getEmbedded ( ) . get ( resourcePath ) ; } else if ( lazy ) { halResource = null ; } else { halResource = getHalResource ( resourcePath ) ; } return createAndCacheResource ( resourceClass , resourcePath , halResource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] private < T > T invoke ( HttpMethodName httpMethodName , String resourcePath , Object representation , HttpResponseHandler < AmazonWebServiceResponse < T > > responseHandler ) throws AmazonClientException { ExecutionContext executionContext = createExecutionContext ( ) ; AWSRequestMetrics awsRequestMetrics = executionContext . getAwsRequestMetrics ( ) ; awsRequestMetrics . startEvent ( AWSRequestMetrics . Field . RequestMarshallTime . name ( ) ) ; Request request = buildRequest ( httpMethodName , resourcePath , representation ) ; awsRequestMetrics . endEvent ( AWSRequestMetrics . Field . RequestMarshallTime . name ( ) ) ; awsRequestMetrics . startEvent ( AWSRequestMetrics . Field . CredentialsRequestTime . name ( ) ) ; AWSCredentials credentials = awsCredentialsProvider . getCredentials ( ) ; awsRequestMetrics . endEvent ( AWSRequestMetrics . Field . CredentialsRequestTime . name ( ) ) ; executionContext . setCredentials ( credentials ) ; awsRequestMetrics . startEvent ( AWSRequestMetrics . Field . ClientExecuteTime . name ( ) ) ; Response < T > response = client . execute ( request , responseHandler , errorResponseHandler , executionContext ) ; awsRequestMetrics . endEvent ( AWSRequestMetrics . Field . ClientExecuteTime . name ( ) ) ; awsRequestMetrics . log ( ) ; return response . getAwsResponse ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : test w / map of Integer ... [CODESPLIT] @ Override public Object get ( Object key ) { Object value = backingMap . get ( key ) ; // When a value is accessed, it's intended type can either be a // class or some other type (like a ParameterizedType). // // If the target type is a class and the value is of that type, // we return it.  If the value is not of that type, we convert // it and store the converted value (trusting it was converted // properly) back to the backing store. // // If the target type is not a class, it may be ParameterizedType // like List<T> or Map<K, V>.  We check if the value is already // a converting type and if so, we return it.  If the value is // not, we convert it and if it's now a converting type, we store // the new value in the backing store. if ( type instanceof Class ) { if ( ! ( ( Class ) type ) . isInstance ( value ) ) { value = convert ( type , value ) ; //noinspection unchecked backingMap . put ( key , value ) ; } } else { if ( ! ( value instanceof ConvertingMap ) && ! ( value instanceof ConvertingList ) ) { value = convert ( type , value ) ; if ( value instanceof ConvertingMap || value instanceof ConvertingList ) { //noinspection unchecked backingMap . put ( key , value ) ; } } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] static Object getObjectForToken ( JsonToken token , JsonUnmarshallerContext context ) throws IOException { switch ( token ) { case VALUE_STRING : return context . getJsonParser ( ) . getText ( ) ; case VALUE_NUMBER_FLOAT : case VALUE_NUMBER_INT : return context . getJsonParser ( ) . getNumberValue ( ) ; case VALUE_FALSE : return Boolean . FALSE ; case VALUE_TRUE : return Boolean . TRUE ; case VALUE_NULL : return null ; default : throw new RuntimeException ( \"We expected a VALUE token but got: \" + token ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public Map < String , HalLink > unmarshall ( JsonUnmarshallerContext context ) throws Exception { Map < String , HalLink > links = new LinkedHashMap <> ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { if ( context . testExpression ( \"curie\" ) ) { context . nextToken ( ) ; HalJsonCurieUnmarshaller . getInstance ( ) . unmarshall ( context ) ; } else { String relation = context . readText ( ) ; token = context . nextToken ( ) ; if ( token == JsonToken . START_ARRAY ) { List < HalLink > halLinks = new HalJsonArrayUnmarshaller <> ( HalJsonLinkUnmarshaller . getInstance ( ) ) . unmarshall ( context ) ; int i = 0 ; for ( HalLink halLink : halLinks ) { links . put ( relation + \"_\" + i ++ , halLink ) ; } } else { links . put ( relation , HalJsonLinkUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } } } token = context . nextToken ( ) ; } return links ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public List < T > unmarshall ( JsonUnmarshallerContext context ) throws Exception { List < T > list = new ArrayList <> ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != END_ARRAY ) { if ( token == JsonToken . START_OBJECT ) { list . add ( itemUnmarshaller . unmarshall ( context ) ) ; } token = context . nextToken ( ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override protected void registerAdditionalMetadataExpressions ( JsonUnmarshallerContext unmarshallerContext ) { Map < String , String > headers = unmarshallerContext . getHttpResponse ( ) . getHeaders ( ) ; if ( headers . containsKey ( \"Location\" ) ) { location = headers . get ( \"Location\" ) ; } else if ( headers . containsKey ( \"location\" ) ) { location = headers . get ( \"location\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public HalResource unmarshall ( JsonUnmarshallerContext context ) throws Exception { HalResource halResource = new HalResource ( ) ; JsonToken token = context . getCurrentToken ( ) ; if ( token == null ) { token = context . nextToken ( ) ; } while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { if ( context . testExpression ( \"_links\" ) ) { context . nextToken ( ) ; halResource . setLinks ( HalJsonLinksUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else if ( context . testExpression ( \"_embedded\" ) ) { context . nextToken ( ) ; halResource . setEmbedded ( HalJsonEmbeddedUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else { String property = context . readText ( ) ; token = context . nextToken ( ) ; if ( token == JsonToken . START_OBJECT ) { context . nextToken ( ) ; halResource . addProperty ( property , HalJsonMapUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else if ( token == JsonToken . START_ARRAY ) { context . nextToken ( ) ; halResource . addProperty ( property , HalJsonListUnmarshaller . getInstance ( ) . unmarshall ( context ) ) ; } else { halResource . addProperty ( property , JsonUnmarshallerUtil . getObjectForToken ( token , context ) ) ; } } } token = context . nextToken ( ) ; } return halResource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public Object get ( int index ) { Object value = backingList . get ( index ) ; // When a value is accessed, it's intended type can either be a // class or some other type (like a ParameterizedType). // // If the target type is a class and the value is of that type, // we return it.  If the value is not of that type, we convert // it and store the converted value (trusting it was converted // properly) back to the backing store. // // If the target type is not a class, it may be ParameterizedType // like List<T> or Map<K, V>.  We check if the value is already // a converting type and if so, we return it.  If the value is // not, we convert it and if it's now a converting type, we store // the new value in the backing store. if ( type instanceof Class ) { if ( ! ( ( Class ) type ) . isInstance ( value ) ) { value = convert ( type , value ) ; //noinspection unchecked backingList . set ( index , value ) ; } } else { if ( ! ( value instanceof ConvertingMap ) && ! ( value instanceof ConvertingList ) ) { value = convert ( type , value ) ; if ( value instanceof ConvertingMap || value instanceof ConvertingList ) { //noinspection unchecked backingList . set ( index , value ) ; } } } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] static Type getCollectionType ( Type type , int index , Class defaultClass ) { if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; return parameterizedType . getActualTypeArguments ( ) [ index ] ; } else { return defaultClass ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] private static Object convertFromNull ( Type type ) { if ( ! ( type instanceof Class ) ) { return null ; } Class < ? > clazz = ( Class ) type ; if ( ! clazz . isPrimitive ( ) ) { return null ; } if ( int . class . isAssignableFrom ( clazz ) ) { return 0 ; } else if ( long . class . isAssignableFrom ( clazz ) ) { return 0L ; } else if ( short . class . isAssignableFrom ( clazz ) ) { return 0 ; } else if ( double . class . isAssignableFrom ( clazz ) ) { return 0.0 ; } else if ( float . class . isAssignableFrom ( clazz ) ) { return 0.0F ; } else if ( boolean . class . isAssignableFrom ( clazz ) ) { return Boolean . FALSE ; } else if ( char . class . isAssignableFrom ( clazz ) ) { return 0 ; } else if ( byte . class . isAssignableFrom ( clazz ) ) { return 0 ; } else { throw new RuntimeException ( \"Unexpected primitive type: \" + clazz . getSimpleName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public HalLink unmarshall ( JsonUnmarshallerContext context ) throws Exception { HalLink halLink = new HalLink ( ) ; JsonToken token = context . getCurrentToken ( ) ; while ( token != null && token != JsonToken . END_OBJECT ) { if ( token == JsonToken . FIELD_NAME ) { if ( context . testExpression ( \"href\" ) ) { context . nextToken ( ) ; halLink . setHref ( context . readText ( ) ) ; } else if ( context . testExpression ( \"name\" ) ) { context . nextToken ( ) ; halLink . setName ( context . readText ( ) ) ; } else if ( context . testExpression ( \"title\" ) ) { context . nextToken ( ) ; halLink . setTitle ( context . readText ( ) ) ; } else if ( context . testExpression ( \"templated\" ) ) { context . nextToken ( ) ; halLink . setTemplated ( Boolean . valueOf ( context . readText ( ) ) ) ; } else if ( context . testExpression ( \"deprecation\" ) ) { context . nextToken ( ) ; halLink . setDeprecation ( context . readText ( ) ) ; } else { // Ignore this.  Likely one of hreflang, profile, type context . nextToken ( ) ; } } token = context . nextToken ( ) ; } return halLink ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------- [CODESPLIT] @ Override public HalLink unmarshall ( JsonUnmarshallerContext context ) throws Exception { HalLink halLink = new HalLink ( ) ; JsonToken token = context . getCurrentToken ( ) ; // Ignore curies for now. while ( token != null && token != JsonToken . END_OBJECT ) { token = context . nextToken ( ) ; } return halLink ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch a LocationforecastLTS from the MET API based on longitude latitude and altitude . [CODESPLIT] public MeteoData < LocationForecast > fetchContent ( double longitude , double latitude , int altitude ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( PARAM_LATITUDE , latitude ) . addParameter ( PARAM_LONGITUDE , longitude ) . addParameter ( PARAM_ALTITUDE , altitude ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch a Sunrise from the MET API based on a given longitude latitude and date . [CODESPLIT] public MeteoData < Sunrise > fetchContent ( double longitude , double latitude , LocalDate date ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( PARAM_LATITUDE , latitude ) . addParameter ( PARAM_LONGITUDE , longitude ) . addParameter ( PARAM_DATE , zonedDateTimeToYyyyMMdd ( date ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch a Sunrise from the MET API based on a given longitude latitude and date range . [CODESPLIT] public MeteoData < Sunrise > fetchContent ( double longitude , double latitude , LocalDate from , LocalDate to ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( PARAM_LATITUDE , latitude ) . addParameter ( PARAM_LONGITUDE , longitude ) . addParameter ( PARAM_FROM , zonedDateTimeToYyyyMMdd ( from ) ) . addParameter ( PARAM_TO , zonedDateTimeToYyyyMMdd ( to ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all point forecasts from now and to the given hours ahead . [CODESPLIT] public List < MeteoExtrasForecast > findHourlyPointForecastsFromNow ( int hoursAhead ) { List < MeteoExtrasForecast > pointExtrasForecasts = new ArrayList <> ( ) ; ZonedDateTime now = getNow ( ) ; for ( int i = 0 ; i < hoursAhead ; i ++ ) { ZonedDateTime ahead = now . plusHours ( i ) ; Optional < PointForecast > pointForecast = getIndexer ( ) . getPointForecast ( ahead ) ; pointForecast . ifPresent ( pof -> { Optional < PeriodForecast > periodForecast = getIndexer ( ) . getTightestFitPeriodForecast ( pof . getFrom ( ) ) ; periodForecast . ifPresent ( pef -> pointExtrasForecasts . add ( new MeteoExtrasForecast ( pof , pef ) ) ) ; } ) ; } return pointExtrasForecasts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the most accurate forecast for the given date . [CODESPLIT] public Optional < MeteoExtrasForecast > findNearestForecast ( ZonedDateTime dateTime ) { ZonedDateTime dt = toZeroMSN ( dateTime . withZoneSameInstant ( METZONE ) ) ; PointForecast chosenForecast = null ; for ( Forecast forecast : getLocationForecast ( ) . getForecasts ( ) ) { if ( forecast instanceof PointForecast ) { PointForecast pointForecast = ( PointForecast ) forecast ; if ( isDateMatch ( dt , cloneZonedDateTime ( pointForecast . getFrom ( ) ) ) ) { chosenForecast = pointForecast ; break ; } else if ( chosenForecast == null ) { chosenForecast = pointForecast ; } else if ( isNearerDate ( pointForecast . getFrom ( ) , dt , chosenForecast . getFrom ( ) ) ) { chosenForecast = pointForecast ; } } } if ( chosenForecast == null ) { return Optional . empty ( ) ; } return Optional . of ( new MeteoExtrasForecast ( chosenForecast , getIndexer ( ) . getWidestFitPeriodForecast ( chosenForecast . getFrom ( ) ) . orElse ( null ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"maxTemperature\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMaxTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMaxTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link LocationType . Symbol } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"symbol\" , scope = LocationType . class ) public JAXBElement < LocationType . Symbol > createLocationTypeSymbol ( LocationType . Symbol value ) { return new JAXBElement < LocationType . Symbol > ( _LocationTypeSymbol_QNAME , LocationType . Symbol . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"highestTemperature\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeHighestTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeHighestTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"windGust\" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeWindGust ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeWindGust_QNAME , Windspeed . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"currentDirection\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeCurrentDirection ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeCurrentDirection_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link LocationType . StateOfTheSea } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"stateOfTheSea\" , scope = LocationType . class ) public JAXBElement < LocationType . StateOfTheSea > createLocationTypeStateOfTheSea ( LocationType . StateOfTheSea value ) { return new JAXBElement < LocationType . StateOfTheSea > ( _LocationTypeStateOfTheSea_QNAME , LocationType . StateOfTheSea . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"meanabsoluteerror\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeMeanabsoluteerror ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeMeanabsoluteerror_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Precipitation } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"maximumPrecipitation\" , scope = LocationType . class ) public JAXBElement < Precipitation > createLocationTypeMaximumPrecipitation ( Precipitation value ) { return new JAXBElement < Precipitation > ( _LocationTypeMaximumPrecipitation_QNAME , Precipitation . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Tidalwater } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"tidalwater\" , scope = LocationType . class ) public JAXBElement < Tidalwater > createLocationTypeTidalwater ( Tidalwater value ) { return new JAXBElement < Tidalwater > ( _LocationTypeTidalwater_QNAME , Tidalwater . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"waveHeight\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWaveHeight ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWaveHeight_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Precipitation } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"precipitation\" , scope = LocationType . class ) public JAXBElement < Precipitation > createLocationTypePrecipitation ( Precipitation value ) { return new JAXBElement < Precipitation > ( _LocationTypePrecipitation_QNAME , Precipitation . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Score } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"score\" , scope = LocationType . class ) public JAXBElement < Score > createLocationTypeScore ( Score value ) { return new JAXBElement < Score > ( _LocationTypeScore_QNAME , Score . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"areaMaxWindSpeed\" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeAreaMaxWindSpeed ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeAreaMaxWindSpeed_QNAME , Windspeed . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link LocationType . SnowDepth } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"snowDepth\" , scope = LocationType . class ) public JAXBElement < LocationType . SnowDepth > createLocationTypeSnowDepth ( LocationType . SnowDepth value ) { return new JAXBElement < LocationType . SnowDepth > ( _LocationTypeSnowDepth_QNAME , LocationType . SnowDepth . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"lowClouds\" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeLowClouds ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeLowClouds_QNAME , Cloudiness . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"minTemperature\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMinTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMinTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"bias\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeBias ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeBias_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"temperature\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link LocationType . Weather } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"weather\" , scope = LocationType . class ) public JAXBElement < LocationType . Weather > createLocationTypeWeather ( LocationType . Weather value ) { return new JAXBElement < LocationType . Weather > ( _LocationTypeWeather_QNAME , LocationType . Weather . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"humidity\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeHumidity ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeHumidity_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"numberofobservations\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeNumberofobservations ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeNumberofobservations_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link LocationType . WindDirection } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"windDirection\" , scope = LocationType . class ) public JAXBElement < LocationType . WindDirection > createLocationTypeWindDirection ( LocationType . WindDirection value ) { return new JAXBElement < LocationType . WindDirection > ( _LocationTypeWindDirection_QNAME , LocationType . WindDirection . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"maxTemperatureDay\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMaxTemperatureDay ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMaxTemperatureDay_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"windSpeed\" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeWindSpeed ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeWindSpeed_QNAME , Windspeed . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"wavePeriod\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWavePeriod ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWavePeriod_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"minTemperatureNight\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMinTemperatureNight ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMinTemperatureNight_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Uv } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"uv\" , scope = LocationType . class ) public JAXBElement < Uv > createLocationTypeUv ( Uv value ) { return new JAXBElement < Uv > ( _LocationTypeUv_QNAME , Uv . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"highClouds\" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeHighClouds ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeHighClouds_QNAME , Cloudiness . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"maxTemperatureNight\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMaxTemperatureNight ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMaxTemperatureNight_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"windProbability\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWindProbability ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWindProbability_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"maxWaveHeight\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeMaxWaveHeight ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeMaxWaveHeight_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"surfaceTemperature\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeSurfaceTemperature ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeSurfaceTemperature_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Pressure } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"pressure\" , scope = LocationType . class ) public JAXBElement < Pressure > createLocationTypePressure ( Pressure value ) { return new JAXBElement < Pressure > ( _LocationTypePressure_QNAME , Pressure . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"cloudiness\" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeCloudiness ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeCloudiness_QNAME , Cloudiness . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"waveDirection\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeWaveDirection ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeWaveDirection_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"symbolProbability\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeSymbolProbability ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeSymbolProbability_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link UnitValue } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"temperatureProbability\" , scope = LocationType . class ) public JAXBElement < UnitValue > createLocationTypeTemperatureProbability ( UnitValue value ) { return new JAXBElement < UnitValue > ( _LocationTypeTemperatureProbability_QNAME , UnitValue . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Groundcover } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"groundCover\" , scope = LocationType . class ) public JAXBElement < Groundcover > createLocationTypeGroundCover ( Groundcover value ) { return new JAXBElement < Groundcover > ( _LocationTypeGroundCover_QNAME , Groundcover . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"minTemperatureDay\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeMinTemperatureDay ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeMinTemperatureDay_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Windspeed } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"maxWindSpeed\" , scope = LocationType . class ) public JAXBElement < Windspeed > createLocationTypeMaxWindSpeed ( Windspeed value ) { return new JAXBElement < Windspeed > ( _LocationTypeMaxWindSpeed_QNAME , Windspeed . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link LocationType . ForestFire } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"forest-fire\" , scope = LocationType . class ) public JAXBElement < LocationType . ForestFire > createLocationTypeForestFire ( LocationType . ForestFire value ) { return new JAXBElement < LocationType . ForestFire > ( _LocationTypeForestFire_QNAME , LocationType . ForestFire . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"mediumClouds\" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeMediumClouds ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeMediumClouds_QNAME , Cloudiness . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"dewpointTemperature\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeDewpointTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeDewpointTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Temperature } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"lowestTemperature\" , scope = LocationType . class ) public JAXBElement < Temperature > createLocationTypeLowestTemperature ( Temperature value ) { return new JAXBElement < Temperature > ( _LocationTypeLowestTemperature_QNAME , Temperature . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Cloudiness } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"fog\" , scope = LocationType . class ) public JAXBElement < Cloudiness > createLocationTypeFog ( Cloudiness value ) { return new JAXBElement < Cloudiness > ( _LocationTypeFog_QNAME , Cloudiness . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch a textforecast for a named forecast [CODESPLIT] public MeteoData < Weather > fetchContent ( ForecastQuery query ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( \"forecast\" , query . getName ( ) ) . addParameter ( \"language\" , query . getLanguage ( ) . getValue ( ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a longterm forecast but only with a small subset of the weather data fields . Typically for use in simple weather reports where you only show the predicted weather icon and temperature and not all the weather details . [CODESPLIT] public MeteoExtrasLongTermForecast createSimpleLongTermForecast ( ) throws MeteoException { List < MeteoExtrasForecastDay > forecastDays = new ArrayList <> ( ) ; ZonedDateTime dt = getNow ( ) ; for ( int i = 0 ; i <= 6 ; i ++ ) { ZonedDateTime dti = dt . plusDays ( i ) ; if ( getIndexer ( ) . hasForecastsForDay ( dti ) ) { MeteoExtrasForecastDay mefd = createSimpleForcastForDay ( dti ) ; if ( mefd != null && mefd . getForecasts ( ) . size ( ) > 0 ) { forecastDays . add ( mefd ) ; } } } return new MeteoExtrasLongTermForecast ( forecastDays ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a longterm forecast . [CODESPLIT] public MeteoExtrasLongTermForecast createLongTermForecast ( ) { List < MeteoExtrasForecastDay > forecastDays = new ArrayList <> ( ) ; ZonedDateTime dt = toZeroHMSN ( getLocationForecast ( ) . getCreated ( ) . plusDays ( 1 ) ) ; for ( int i = 0 ; i < series . getSeries ( ) . size ( ) ; i ++ ) { createLongTermForecastDay ( dt . plusDays ( i ) , series . getSeries ( ) . get ( i ) ) . ifPresent ( forecastDays :: add ) ; } return new MeteoExtrasLongTermForecast ( forecastDays ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an untitled Location from coordinate string . [CODESPLIT] public static Location fromCoordinates ( String coordinates ) { if ( coordinates == null ) { throw new IllegalArgumentException ( \"Cannot create Location from null input.\" ) ; } Matcher m = P . matcher ( coordinates ) ; if ( ! m . matches ( ) ) { throw new IllegalArgumentException ( coordinates + \" must be on the pattern (longitude,latitude,altitude) : \" + P . pattern ( ) ) ; } try { Double longitude = Double . valueOf ( m . group ( 1 ) ) ; Double latitude = Double . valueOf ( m . group ( 2 ) ) ; Integer altitude = 0 ; if ( m . group ( 3 ) != null ) { altitude = Integer . valueOf ( m . group ( 3 ) . substring ( 1 ) ) ; } return new Location ( longitude , latitude , altitude , \"\" ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( coordinates + \" must be on the pattern (longitude,latitude,altitude) : \" + P . pattern ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch a list of all available textforecasts . [CODESPLIT] public MeteoData < Available > fetchContent ( ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( \"available\" , null ) . skipQuestionMarkInUrl ( ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Probability } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"probability\" , scope = LocationType . class ) public JAXBElement < Probability > createLocationTypeProbability ( Probability value ) { return new JAXBElement < Probability > ( _LocationTypeProbability_QNAME , Probability . class , LocationType . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"productdescription\" ) public JAXBElement < String > createProductdescription ( String value ) { return new JAXBElement < String > ( _Productdescription_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"header\" ) public JAXBElement < String > createHeader ( String value ) { return new JAXBElement < String > ( _Header_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create name for a wind symbol . [CODESPLIT] public static Optional < String > createWindSymbolName ( PointForecast pointForecast ) { if ( pointForecast == null || pointForecast . getWindDirection ( ) == null || pointForecast . getWindSpeed ( ) == null ) { return Optional . empty ( ) ; } return Optional . of ( pointForecast . getWindDirection ( ) . getName ( ) . toLowerCase ( ) + idFormat . format ( pointForecast . getWindSpeed ( ) . getBeaufort ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find matching Beaufort level for a given point forecast . [CODESPLIT] public static Optional < BeaufortLevel > findBeaufortLevel ( PointForecast pointForecast ) { if ( pointForecast == null || pointForecast . getWindSpeed ( ) == null ) { return Optional . empty ( ) ; } return Optional . ofNullable ( findUnitById ( pointForecast . getWindSpeed ( ) . getBeaufort ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrap the construction of URL s to avoid throwing of checked MalformedURLException . Instead MeteoException is thrown . [CODESPLIT] public static URI createUri ( String uri ) throws MeteoException { if ( uri == null ) { throw new MeteoException ( \"URI is null\" ) ; } try { return new URI ( uri ) ; } catch ( URISyntaxException e ) { throw new MeteoException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the sun is shining for a given time . [CODESPLIT] public boolean isSun ( ZonedDateTime currentDate ) { if ( getSun ( ) . getNeverRise ( ) ) { return false ; } else if ( getSun ( ) . getNeverSet ( ) ) { return true ; } return timeWithinPeriod ( currentDate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the PointForecast that matches the given time . [CODESPLIT] Optional < PointForecast > getPointForecast ( ZonedDateTime dateTime ) { for ( Forecast forecast : forecasts ) { if ( forecast instanceof PointForecast ) { PointForecast pointForecast = ( PointForecast ) forecast ; if ( createHourIndexKey ( dateTime ) . equals ( createHourIndexKey ( cloneZonedDateTime ( pointForecast . getFrom ( ) ) ) ) ) { return Optional . of ( pointForecast ) ; } } } return Optional . empty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Find the period forecast that is the widest fit for a point forecast . [CODESPLIT] Optional < PeriodForecast > getWidestFitPeriodForecast ( ZonedDateTime from ) { if ( from == null ) { return Optional . empty ( ) ; } return getWidestFitScoreForecast ( from ) . map ( ScoreForecast :: getPeriodForecast ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the period forecast that has the best fitted forecast for a given period . [CODESPLIT] Optional < PeriodForecast > getBestFitPeriodForecast ( ZonedDateTime from , ZonedDateTime to ) { if ( from == null || to == null ) { return Optional . empty ( ) ; } // Making sure that we remove minutes, seconds and milliseconds from the request timestamps ZonedDateTime requestFrom = toZeroMSN ( from ) ; ZonedDateTime requestTo = toZeroMSN ( to ) ; //  Get list of period forecasts for the requested day. Return empty if date isn't present List < PeriodForecast > forecastsList = dayIndex . get ( new DayIndexKey ( requestFrom ) ) ; if ( forecastsList == null ) { return Optional . empty ( ) ; } PeriodForecast chosenForecast = null ; long score = 0 ; long tmpScore = 0 ; for ( PeriodForecast forecast : forecastsList ) { ZonedDateTime actualFrom = cloneZonedDateTime ( forecast . getFrom ( ) ) ; ZonedDateTime actualTo = cloneZonedDateTime ( forecast . getTo ( ) ) ; if ( requestFrom . equals ( actualFrom ) && requestTo . equals ( actualTo ) ) { return Optional . of ( forecast ) ; } else if ( ( requestFrom . isBefore ( actualFrom ) && requestTo . isBefore ( actualFrom ) ) || ( requestFrom . isAfter ( actualTo ) && requestTo . isAfter ( actualTo ) ) || actualTo . isEqual ( actualFrom ) ) { continue ; // this period is outside the requested period or this is a point forecast. } else if ( requestFrom . isBefore ( actualFrom ) && requestTo . isBefore ( actualTo ) ) { tmpScore = hoursBetween ( requestTo , actualFrom ) ; } else if ( ( actualFrom . isBefore ( requestFrom ) || actualFrom . isEqual ( requestFrom ) ) && actualTo . isBefore ( requestTo ) ) { tmpScore = hoursBetween ( actualTo , requestFrom ) ; } else if ( actualFrom . isAfter ( requestFrom ) && ( actualTo . isBefore ( requestTo ) || actualTo . isEqual ( requestTo ) ) ) { tmpScore = hoursBetween ( actualTo , actualFrom ) ; } else if ( actualFrom . isBefore ( requestFrom ) && actualTo . isAfter ( requestTo ) ) { tmpScore = hoursBetween ( requestTo , requestFrom ) ; } else { DateTimeFormatter formatter = DateTimeFormatter . ofPattern ( \"yyyy-MM-dd:HH:mm\" ) ; log . warn ( \"Unhandled forecast Requested period:\" + requestFrom . format ( formatter ) + \"--\" + requestTo . format ( formatter ) + \", Actual period: \" + actualFrom . format ( formatter ) + \"--\" + actualTo . format ( formatter ) ) ; } tmpScore = Math . abs ( tmpScore ) ; if ( ( score == 0 && tmpScore > 0 ) || tmpScore > score ) { score = tmpScore ; chosenForecast = forecast ; } } return Optional . ofNullable ( chosenForecast ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch textforecasts and warnings for a geographical point or area in Norwegian . [CODESPLIT] public MeteoData < TextLocationWeather > fetchContent ( double longitude , double latitude ) throws MeteoException { return fetchContent ( longitude , latitude , TextLocationLanguage . NB ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch textforecasts and warnings for a geographical point or area . [CODESPLIT] public MeteoData < TextLocationWeather > fetchContent ( double longitude , double latitude , TextLocationLanguage language ) throws MeteoException { MeteoResponse response = getMeteoClient ( ) . fetchContent ( createServiceUriBuilder ( ) . addParameter ( \"latitude\" , latitude ) . addParameter ( \"longitude\" , longitude ) . addParameter ( \"language\" , language . getValue ( ) ) . build ( ) ) ; return new MeteoData <> ( parser . parse ( response . getData ( ) ) , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the file extensions to use with the specified decoder . <p > If the specified Decoder doesn t have any file extensions explicitly associated with it then a single empty string is returned . [CODESPLIT] private static String [ ] getFileExtensions ( final Decoder decoder ) { final Class < ? extends Decoder > decoderClass = decoder . getClass ( ) ; final FileExtensions fileExtensionsAnnotation = decoderClass . getAnnotation ( FileExtensions . class ) ; return ( fileExtensionsAnnotation == null ) ? new String [ ] { \"\" } : fileExtensionsAnnotation . value ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a ( partial ) ServicePath into a file name to access . The file names are in the format cfg_group_subgroup_appid_ConfigurationClass [ . ext ] . [CODESPLIT] private String nameToFile ( final Class configClass , final Name servicePath , final String fileNameDelimiter , final String extension ) { StringBuilder builder = new StringBuilder ( \"cfg\" ) ; for ( final String component : servicePath ) { builder . append ( fileNameDelimiter ) . append ( component ) ; } builder . append ( fileNameDelimiter ) . append ( configClass . getSimpleName ( ) ) ; if ( ! extension . isEmpty ( ) ) { builder . append ( ' ' ) . append ( extension ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks connection retrieves appropriate changelog and performs database update . [CODESPLIT] private void updateDB ( ) throws SQLException , LiquibaseException { System . out . println ( \"About to perform DB update.\" ) ; try ( BasicDataSource dataSource = new BasicDataSource ( ) ) { dataSource . setUrl ( fullConnectionString ) ; dataSource . setUsername ( username ) ; dataSource . setPassword ( password ) ; try ( java . sql . Connection c = dataSource . getConnection ( ) ) { Database database = DatabaseFactory . getInstance ( ) . findCorrectDatabaseImplementation ( new JdbcConnection ( c ) ) ; // Check that the Database does indeed exist before we try to run the liquibase update. Liquibase liquibase = null ; ClassLoaderResourceAccessor accessor = new ClassLoaderResourceAccessor ( ) ; try { if ( accessor . getResourcesAsStream ( \"changelog-master.xml\" ) != null ) { liquibase = new Liquibase ( \"changelog-master.xml\" , new ClassLoaderResourceAccessor ( ) , database ) ; } else if ( accessor . getResourcesAsStream ( \"changelog.xml\" ) != null ) { liquibase = new Liquibase ( \"changelog.xml\" , new ClassLoaderResourceAccessor ( ) , database ) ; } else { String errorMessage = \"No liquibase changelog-master.xml or changelog.xml could be located\" ; Logger . getLogger ( Application . class . getName ( ) ) . log ( Level . SEVERE , errorMessage , this ) ; throw new RuntimeException ( errorMessage ) ; } } catch ( final IOException ioe ) { Logger . getLogger ( Application . class . getName ( ) ) . log ( Level . SEVERE , ioe . getMessage ( ) , ioe ) ; } liquibase . getLog ( ) . setLogLevel ( logLevel ) ; liquibase . update ( new Contexts ( ) ) ; System . out . println ( \"DB update finished.\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the specified script . The source of the script is supplied as a UTF - 8 encoded { @code InputStream } . The default { @code ScriptContext } for the { @code ScriptEngine } is used . [CODESPLIT] private static Object evaluateScript ( final ScriptEngine scriptEngine , final InputStream stream ) throws IOException , ScriptException { try ( final InputStreamReader reader = new InputStreamReader ( stream , StandardCharsets . UTF_8 ) ) { return scriptEngine . eval ( reader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a method on a script object compiled during a previous script execution which is retained in the state of the ScriptEngine . [CODESPLIT] private static String invokeStringMethod ( final ScriptEngine jsEngine , final Object thiz , final String name , final Object ... args ) throws NoSuchMethodException , ScriptException { return ( String ) ( ( Invocable ) jsEngine ) . invokeMethod ( thiz , name , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the referenced object potentially performing a remote DataStore lookup and deserialisation . If the object is already present or has been previously acquired it is immediately returned . [CODESPLIT] public synchronized T acquire ( final DataSource source ) throws DataSourceException { if ( object == null ) { if ( getReference ( ) == null ) { throw new IllegalStateException ( \"No reference or object present\" ) ; } else { object = source . getObject ( getReference ( ) , objectClass ) ; } } return object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ReferencedObject that uses a remote reference to data present in an ObjectSource . [CODESPLIT] public static < T > ReferencedObject < T > getReferencedObject ( final Class < T > clazz , final String ref ) { return new ReferencedObject <> ( clazz , ref , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ReferencedObject that directly wraps an object without a reference . [CODESPLIT] public static < T > ReferencedObject < T > getWrappedObject ( final Class < T > clazz , final T obj ) { return new ReferencedObject <> ( clazz , null , obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override protected InputStream getConfigurationStream ( final Class configClass , final Name relativePath ) throws ConfigurationException { try { return remoteCall ( relativePath . toString ( ) , configClass . getSimpleName ( ) ) . getBody ( ) . in ( ) ; } catch ( final HttpConfigurationException e ) { throw new ConfigurationException ( \"No configuration at path: \" + relativePath , e ) ; } catch ( final IOException | InterruptedException e ) { throw new ConfigurationException ( \"Failed to retrieve configuration\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform exponential backoff / retry of acquiring a data file from an HTTP source . [CODESPLIT] private Response remoteCall ( final String path , final String configName ) throws ConfigurationException , InterruptedException { int i = 0 ; while ( true ) { try { return remote . getRemoteConfiguration ( path , configName ) ; } catch ( final HttpConfigurationException nfe ) { // don't retry if we have an explicit failure from the HTTP server throw nfe ; } catch ( final ConfigurationException e ) { LOG . debug ( \"HTTP client call failed, retrying\" ) ; if ( i == retries ) { throw e ; } else { Thread . sleep ( ( long ) Math . pow ( 2 , i ) * 1000L ) ; } i ++ ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquire a configuration class from the provider . The requested class will be a simple Java object that when returned and can be interacted with using getters and other standard mechanisms . Configuration classes may themselves contain other configuration objects which will be recursively acquired if marked @Configuration . Any fields marked @Encrypted will be decrypted any fields marked and any validation annotations will be processed . [CODESPLIT] @ Override public final < T > T getConfiguration ( final Class < T > configClass ) throws ConfigurationException { Objects . requireNonNull ( configClass ) ; incrementRequests ( ) ; T config = getCompleteConfig ( configClass ) ; Set < ConstraintViolation < T > > violations = getValidator ( ) . validate ( config ) ; if ( violations . isEmpty ( ) ) { return config ; } else { incrementErrors ( ) ; LOG . error ( \"Configuration constraint violations found for {}: {}\" , configClass . getSimpleName ( ) , violations ) ; throw new ConfigurationException ( \"Configuration validation failed for \" + configClass . getSimpleName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the recursive entry point for acquiring a complete configuration class to return . Attempt to acquire a deserialised object representing the configuration class requested and analyse it for declared fields marked @Configuration . If any are found the method recursively calls itself until all configuration is satisfied . [CODESPLIT] private < T > T getCompleteConfig ( final Class < T > configClass ) throws ConfigurationException { T config = getConfig ( configClass ) ; for ( final Field f : configClass . getDeclaredFields ( ) ) { if ( f . isAnnotationPresent ( Configuration . class ) ) { try { Method setter = getMethod ( f . getName ( ) , configClass , PropertyDescriptor :: getWriteMethod ) ; if ( setter != null ) { setter . invoke ( config , getCompleteConfig ( f . getType ( ) ) ) ; } } catch ( final ConfigurationException e ) { LOG . debug ( \"Didn't find any overriding configuration\" , e ) ; } catch ( final InvocationTargetException | IllegalAccessException e ) { incrementErrors ( ) ; throw new ConfigurationException ( \"Failed to get complete configuration for \" + configClass . getSimpleName ( ) , e ) ; } } else if ( f . getType ( ) . equals ( String . class ) && f . isAnnotationPresent ( Encrypted . class ) ) { try { Method getter = getMethod ( f . getName ( ) , config . getClass ( ) , PropertyDescriptor :: getReadMethod ) ; Method setter = getMethod ( f . getName ( ) , config . getClass ( ) , PropertyDescriptor :: getWriteMethod ) ; if ( getter != null && setter != null ) { final String configValue = ( String ) getter . invoke ( config ) ; final String encryptedValue = isSubstitutorEnabled ? tokenSubstitutor ( configValue ) : configValue ; setter . invoke ( config , getCipher ( ) . decrypt ( encryptedValue ) ) ; } } catch ( final CipherException | InvocationTargetException | IllegalAccessException e ) { throw new ConfigurationException ( \"Failed to decrypt class fields\" , e ) ; } } else if ( isSubstitutorEnabled && f . getType ( ) . equals ( String . class ) ) { try { String propertyName = f . getName ( ) ; Method getter = getMethod ( propertyName , config . getClass ( ) , PropertyDescriptor :: getReadMethod ) ; Method setter = getMethod ( propertyName , config . getClass ( ) , PropertyDescriptor :: getWriteMethod ) ; if ( getter != null && setter != null ) { // Property value may contain tokens that require substitution. String propertyValueByToken = tokenSubstitutor ( ( String ) getter . invoke ( config ) ) ; setter . invoke ( config , propertyValueByToken ) ; } } catch ( final InvocationTargetException | IllegalAccessException e ) { throw new ConfigurationException ( \"Failed to get complete configuration for \" + configClass . getSimpleName ( ) , e ) ; } } } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquire decode and decrypt a configuration object from a data stream . [CODESPLIT] private < T > T getConfig ( final Class < T > configClass ) throws ConfigurationException { Iterator < Name > it = getServicePath ( ) . descendingPathIterator ( ) ; while ( it . hasNext ( ) ) { try ( InputStream in = getConfigurationStream ( configClass , it . next ( ) ) ) { return decoder . deserialise ( in , configClass ) ; } catch ( final ConfigurationException e ) { LOG . trace ( \"No configuration at this path level\" , e ) ; } catch ( final CodecException | IOException e ) { incrementErrors ( ) ; throw new ConfigurationException ( \"Failed to get configuration for \" + configClass . getSimpleName ( ) , e ) ; } } incrementErrors ( ) ; throw new ConfigurationException ( \"No configuration found for \" + configClass . getSimpleName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the string substitution functionality should be enabled . [CODESPLIT] private static boolean getIsSubstitutorEnabled ( final BootstrapConfiguration bootstrapConfig ) { final String ENABLE_SUBSTITUTOR_CONFIG_KEY = \"CAF_CONFIG_ENABLE_SUBSTITUTOR\" ; final boolean ENABLE_SUBSTITUTOR_CONFIG_DEFAULT = true ; // Return the default if the setting is not configured if ( ! bootstrapConfig . isConfigurationPresent ( ENABLE_SUBSTITUTOR_CONFIG_KEY ) ) { return ENABLE_SUBSTITUTOR_CONFIG_DEFAULT ; } // Return the configured setting. // The ConfigurationException should never happen since isConfigurationPresent() has already been called. try { return bootstrapConfig . getConfigurationBoolean ( ENABLE_SUBSTITUTOR_CONFIG_KEY ) ; } catch ( final ConfigurationException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Excludes all com . sun . jersey classes . [CODESPLIT] @ Override public < T > Iterator < Class < T > > createClassIterator ( final Class < T > service , final String serviceName , final ClassLoader loader , final boolean ignoreOnClassNotFound ) { final Iterator < Class < T > > delegateClassIterator = delegate . createClassIterator ( service , serviceName , loader , ignoreOnClassNotFound ) ; Stream < Class < T > > stream = StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( delegateClassIterator , Spliterator . ORDERED ) , false ) ; return stream . filter ( t -> ! t . getPackage ( ) . getName ( ) . startsWith ( \"com.sun.jersey\" ) ) . collect ( Collectors . toList ( ) ) . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Decoder that should be used to interpret the configuration files . [CODESPLIT] @ Override public Decoder getDecoder ( final BootstrapConfiguration bootstrap , final Decoder defaultDecoder ) { final String DECODER_CONFIG_KEY = \"CAF_CONFIG_DECODER\" ; final String decoder ; try { // Return the specified default Decoder if none has been configured if ( ! bootstrap . isConfigurationPresent ( DECODER_CONFIG_KEY ) ) { return defaultDecoder ; } // Lookup the Decoder to use decoder = bootstrap . getConfiguration ( DECODER_CONFIG_KEY ) ; } catch ( final ConfigurationException ex ) { // Throw a RuntimeException since this shouldn't happen // (since isConfigurationPresent() has already been called) throw new RuntimeException ( ex ) ; } try { // Retrieve the Decoder using the ModuleProvider return ModuleProvider . getInstance ( ) . getModule ( Decoder . class , decoder ) ; } catch ( final NullPointerException ex ) { throw new RuntimeException ( \"Unable to get Decoder using \" + DECODER_CONFIG_KEY + \" value: \" + decoder , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the first advertised service implementation for the specified interface . The implementations are advertised via the Java ServiceLoader mechanism . [CODESPLIT] public static < T > T getService ( final Class < T > intf ) throws ModuleLoaderException { return getService ( intf , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the first advertised service implementation for the specified interface . The implementations are advertised via the Java ServiceLoader mechanism . [CODESPLIT] public static < T > T getService ( final Class < T > intf , final Class < ? extends T > defaultImpl ) throws ModuleLoaderException { final T implementation = getServiceOrElse ( intf , null ) ; if ( implementation != null ) { return implementation ; } if ( defaultImpl == null ) { throw new ModuleLoaderException ( \"Missing implementation: \" + intf ) ; } try { return defaultImpl . getConstructor ( ) . newInstance ( ) ; } catch ( final InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e ) { throw new ModuleLoaderException ( \"Cannot instantiate class\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the first advertised service implementation for the specified interface . The implementations are advertised via the Java ServiceLoader mechanism . [CODESPLIT] public static < T > T getServiceOrElse ( final Class < T > intf , final T defaultObj ) { Objects . requireNonNull ( intf ) ; final T ret ; List < T > implementations = getServices ( intf ) ; if ( implementations . isEmpty ( ) ) { return defaultObj ; } else { ret = implementations . get ( 0 ) ; } if ( implementations . size ( ) > 1 ) { LOG . warn ( \"There is more than one implementation of {} available on the classpath, taking the first available\" , intf ) ; } LOG . info ( \"Detected component implementation {}\" , ret . getClass ( ) . getSimpleName ( ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all advertised service implementations of the specified interface . [CODESPLIT] public static < T > List < T > getServices ( final Class < T > intf ) { Objects . requireNonNull ( intf ) ; List < T > ret = new LinkedList <> ( ) ; for ( final T t : ServiceLoader . load ( intf ) ) { ret . add ( t ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a module by its simple name that implements a particular type T [CODESPLIT] public < T > T getModule ( final Class < T > interfaceImplemented , final String moduleType ) throws NullPointerException { //check for this type in the map Map < String , Object > computedValue = loadedModules . computeIfAbsent ( interfaceImplemented , ModuleProvider :: loadModules ) ; Object moduleInstance = computedValue . get ( moduleType ) ; Objects . requireNonNull ( moduleInstance , \"Unable to find implementation of \" + interfaceImplemented . getName ( ) + \" with moduleType \" + moduleType ) ; return ( T ) moduleInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the referenced data as a stream potentially performing a remote lookup . [CODESPLIT] public synchronized InputStream acquire ( final DataSource source ) throws DataSourceException { InputStream ret ; if ( data == null ) { if ( getReference ( ) == null ) { throw new IllegalStateException ( \"No data or reference present\" ) ; } else { ret = source . getStream ( getReference ( ) ) ; } } else { ret = new ByteArrayInputStream ( data ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the size of the data . [CODESPLIT] public synchronized long size ( final DataSource source ) throws DataSourceException { if ( data == null ) { if ( getReference ( ) == null ) { throw new IllegalStateException ( \"No data or reference present\" ) ; } else { return source . getDataSize ( getReference ( ) ) ; } } else { return data . length ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a ReferencedData instance that wraps data but also has a reference . [CODESPLIT] public static ReferencedData getWrappedData ( final String ref , final byte [ ] data ) { return new ReferencedData ( Objects . requireNonNull ( ref ) , data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the components of the Name at the specified numeric index [CODESPLIT] public String getIndex ( final int index ) { if ( index < 0 || index >= components . size ( ) ) { throw new IllegalArgumentException ( \"Index out of bounds\" ) ; } return components . get ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a Name that consists of a subsection of the current Name . [CODESPLIT] public Name getPrefix ( final int upperIndex ) { if ( upperIndex < 0 || upperIndex > components . size ( ) ) { throw new IllegalArgumentException ( \"Index out of bounds\" ) ; } return new Name ( components . subList ( 0 , upperIndex ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is an arc colored and hence on a color chain? [CODESPLIT] boolean colored ( ) { return type == Compiler . PLAIN || type == Compiler . AHEAD || type == Compiler . BEHIND ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exec - match regular expression [CODESPLIT] boolean exec ( HsrePattern re , CharSequence data , EnumSet < ExecFlags > execFlags ) throws RegexException { /* sanity checks */ /* setup */ if ( 0 != ( re . guts . info & Flags . REG_UIMPOSSIBLE ) ) { throw new RegexException ( \"Regex marked impossible\" ) ; } eflags = 0 ; for ( ExecFlags ef : execFlags ) { switch ( ef ) { case NOTBOL : eflags |= Flags . REG_NOTBOL ; break ; case NOTEOL : eflags |= Flags . REG_NOTEOL ; break ; case LOOKING_AT : eflags |= Flags . REG_LOOKING_AT ; break ; default : throw new RuntimeException ( \"impossible exec flag\" ) ; } } this . re = re ; this . g = re . guts ; this . data = data ; this . dataLength = this . data . length ( ) ; if ( this . match != null ) { this . match . clear ( ) ; } else { this . match = Lists . newArrayList ( ) ; } match . add ( null ) ; // make room for 1. if ( 0 != ( g . info & Flags . REG_UBACKREF ) ) { while ( match . size ( ) < g . nsub + 1 ) { match . add ( null ) ; } } if ( mem != null && mem . length >= g . ntree ) { Arrays . fill ( mem , 0 ) ; } else { mem = new int [ g . ntree ] ; } /* do it */ assert g . tree != null ; if ( 0 != ( g . info & Flags . REG_UBACKREF ) ) { return cfind ( g . tree . machine ) ; } else { return find ( g . tree . machine ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find - find a match for the main NFA ( no - complications case ) <p > First it runs the search machine in non - greedy mode ( shortest ) . The search machine is the NFA with . * added to the front and the back more or less . See makesearch . In many cases running the search machine shortest is considerably faster than running the actual regular expression in greedy ( longest ) . So even though this may seem like it would take extra time doing an extra scan the alternative is much slower . The search machine tells you if the expression can be found anywhere and if so where is the furthest possible end . < / p > <p > If the search machine succeeds the does an iteration to find the exact bounds ; the loop uses longest or shortest as appropriate to the flags . In C there was an option to _only_ run the search machine and return a simple boolean with no bounds . We have no API for that via an ExecFlag . < / p > <p > If the top - level API call is lookingAt we never want to scan down the data looking for matches . But shortest can still be much faster than longest . So the code runs the original machine first . If non - greedy expressions were very common I suppose that it would be faster to omit this step in that case . Thereafter the loop has a check to bail if these is no match at the beginning of the data which is the constraint of lookingAt . < / p > [CODESPLIT] boolean find ( Cnfa cnfa ) { int begin ; int end = - 1 ; int cold ; int open ; /* open and close of range of possible starts */ int close ; boolean hitend ; boolean shorter = 0 != ( g . tree . flags & Subre . SHORTER ) ; boolean lookingAt = 0 != ( eflags & Flags . REG_LOOKING_AT ) ; int [ ] coldp = new int [ 1 ] ; Dfa d = new Dfa ( this , cnfa ) ; if ( lookingAt ) { /*\n             * shortest is faster than longest. So, we want to check with it.\n             * However, since we aren't making a 'search re' with an extra .* on\n             * the front, we don't add an extra requirement to make progress on the\n             * very first arc. If the expression has something like a* at the front,\n             * it can 'no-progress' consuming the a characters.\n             * All of this casts doubts on the 'requireInitialProgress' feature -- at all.\n             * These initial calls to shortest should be all the opportunity we need\n             * to do 'lookingAt'.\n             */ close = d . shortest ( 0 , 0 , data . length ( ) , coldp , null ) ; cold = 0 ; } else { /* First, a shot with the search RE. */ Dfa s = new Dfa ( this , g . search ) ; close = s . shortest ( 0 , 0 , data . length ( ) , coldp , null ) ; cold = coldp [ 0 ] ; } if ( close == - 1 ) { /* not found */ return false ; } /* find starting point and match */ open = cold ; cold = - 1 ; for ( begin = open ; begin <= close ; begin ++ ) { /*\n             * if LOOKING_AT, we can't validly have a 'begin' after 'open'.\n             * I'm not sure this test can even ever go off, since the 'shortest' test\n             * up above should accomplish the same thing.\n             */ if ( begin > 0 && lookingAt ) { return false ; } boolean [ ] hitendp = new boolean [ 1 ] ; if ( shorter ) { end = d . shortest ( begin , begin , data . length ( ) , null , hitendp ) ; } else { end = d . longest ( begin , data . length ( ) , hitendp ) ; } hitend = hitendp [ 0 ] ; if ( hitend && cold == - 1 ) { cold = begin ; } if ( end != - 1 ) { /* success */ break ; /* NOTE BREAK OUT */ } } if ( end == - 1 ) { return false ; } /* and pin down details */ match . set ( 0 , new RegMatch ( begin , end ) ) ; // no need to do the work. return re . nsub <= 0 || dissect ( g . tree , begin , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cfind - find a match for the main NFA ( with complications ) [CODESPLIT] private boolean cfind ( Cnfa cnfa ) { int [ ] cold = new int [ 1 ] ; Dfa s = new Dfa ( this , g . search ) ; Dfa d = new Dfa ( this , cnfa ) ; return cfindloop ( d , s , cold ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cfindloop - the heart of cfind [CODESPLIT] private boolean cfindloop ( Dfa d , Dfa s , int [ ] coldp ) { int begin ; int end ; int cold ; int open ; /* open and close of range of possible starts */ int close ; int estart ; int estop ; boolean shorter = 0 != ( g . tree . flags & Subre . SHORTER ) ; boolean hitend [ ] = new boolean [ 1 ] ; boolean lookingAt = 0 != ( eflags & Flags . REG_LOOKING_AT ) ; assert d != null && s != null ; close = 0 ; do { int [ ] cold0 = new int [ 1 ] ; /*\n             * Call search NFA to see if this is possible at all.\n             */ if ( lookingAt ) { // in the looking at case, we use the un-search-ified RE. close = d . shortest ( close , close , data . length ( ) , cold0 , null ) ; cold = 0 ; } else { close = s . shortest ( close , close , data . length ( ) , cold0 , null ) ; cold = cold0 [ 0 ] ; } if ( close == - 1 ) { break ; /* NOTE BREAK */ } assert cold != - 1 ; open = cold ; cold = - 1 ; for ( begin = open ; begin <= close ; begin ++ ) { if ( begin > 0 && lookingAt ) { // Is this possible given the looking-at constraint in the call to shortest above? return false ; } estart = begin ; estop = data . length ( ) ; for ( ; ; ) { if ( shorter ) { end = d . shortest ( begin , estart , estop , null , hitend ) ; } else { end = d . longest ( begin , estop , hitend ) ; } if ( hitend [ 0 ] && cold == - 1 ) { cold = begin ; } if ( end == - 1 ) { break ; /* NOTE BREAK OUT */ } for ( int x = 0 ; x < match . size ( ) ; x ++ ) { match . set ( x , null ) ; } int maxsubno = getMaxSubno ( g . tree , 0 ) ; mem = new int [ maxsubno + 1 ] ; boolean matched = cdissect ( g . tree , begin , end ) ; if ( matched ) { // indicate the full match bounds. match . set ( 0 , new RegMatch ( begin , end ) ) ; coldp [ 0 ] = cold ; return true ; } if ( shorter ? end == estop : end == begin ) { /* no point in trying again */ coldp [ 0 ] = cold ; return false ; } /* go around and try again */ if ( shorter ) { estart = end + 1 ; } else { estop = end - 1 ; } } } } while ( close < data . length ( ) ) ; coldp [ 0 ] = cold ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "subset - set any subexpression relevant to a successful subre [CODESPLIT] private void subset ( RuntimeSubexpression sub , int begin , int end ) { int n = sub . number ; assert n > 0 ; while ( match . size ( ) < ( n + 1 ) ) { match . add ( null ) ; } match . set ( n , new RegMatch ( begin , end ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dissect - determine subexpression matches ( uncomplicated case ) [CODESPLIT] private boolean dissect ( RuntimeSubexpression t , int begin , int end ) { switch ( t . op ) { case ' ' : /* terminal node */ assert t . left == null && t . right == null ; return true ; /* no action, parent did the work */ case ' ' : /* alternation */ assert t . left != null ; return altdissect ( t , begin , end ) ; case ' ' : /* back ref -- shouldn't be calling us! */ throw new RuntimeException ( \"impossible backref\" ) ; case ' ' : /* concatenation */ assert t . left != null && t . right != null ; return condissect ( t , begin , end ) ; case ' ' : /* capturing */ assert t . left != null && t . right == null ; assert t . number > 0 ; subset ( t , begin , end ) ; return dissect ( t . left , begin , end ) ; default : throw new RuntimeException ( \"Impossible op\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "condissect - determine concatenation subexpression matches ( uncomplicated ) [CODESPLIT] private boolean condissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; Dfa d2 ; int mid ; assert t . op == ' ' ; assert t . left != null && t . left . machine . states . length > 0 ; assert t . right != null && t . right . machine . states . length > 0 ; boolean shorter = ( t . left . flags & Subre . SHORTER ) != 0 ; int stop = shorter ? end : begin ; d = new Dfa ( this , t . left . machine ) ; d2 = new Dfa ( this , t . right . machine ) ; /* pick a tentative midpoint */ if ( shorter ) { mid = d . shortest ( begin , begin , end , null , null ) ; } else { mid = d . longest ( begin , end , null ) ; } if ( mid == - 1 ) { throw new RuntimeException ( \"Impossible mid.\" ) ; } /* iterate until satisfaction or failure */ while ( d2 . longest ( mid , end , null ) != end ) { /* that midpoint didn't work, find a new one */ if ( mid == stop ) { /* all possibilities exhausted! */ throw new RuntimeException ( \"no midpoint\" ) ; } if ( shorter ) { mid = d . shortest ( begin , mid + 1 , end , null , null ) ; } else { mid = d . longest ( begin , mid - 1 , null ) ; } if ( mid == - 1 ) { throw new RuntimeException ( \"Failed midpoint\" ) ; } } /* satisfaction */ boolean dissectMatch = dissect ( t . left , begin , mid ) ; if ( ! dissectMatch ) { return false ; } return dissect ( t . right , mid , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "altdissect - determine alternative subexpression matches ( uncomplicated ) [CODESPLIT] private boolean altdissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; assert t != null ; assert t . op == ' ' ; for ( ; t != null ; t = t . right ) { assert t . left != null && t . left . machine . states . length > 0 ; d = new Dfa ( this , t . left . machine ) ; if ( d . longest ( begin , end , null ) == end ) { return dissect ( t . left , begin , end ) ; } } throw new RuntimeException ( \"none matched\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cdissect - determine subexpression matches ( with complications ) The retry memory stores the offset of the trial midpoint from begin plus 1 so that 0 uniquely means clean slate . [CODESPLIT] private boolean cdissect ( RuntimeSubexpression t , int begin , int end ) { assert t != null ; switch ( t . op ) { case ' ' : /* terminal node */ assert t . left == null && t . right == null ; return true ; /* no action, parent did the work */ case ' ' : /* alternation */ assert t . left != null ; return caltdissect ( t , begin , end ) ; case ' ' : /* back ref -- shouldn't be calling us! */ assert t . left == null && t . right == null ; return cbrdissect ( t , begin , end ) ; case ' ' : /* concatenation */ assert t . left != null && t . right != null ; return ccondissect ( t , begin , end ) ; case ' ' : /* capturing */ assert t . left != null && t . right == null ; assert t . number > 0 ; boolean cdmatch = cdissect ( t . left , begin , end ) ; if ( cdmatch ) { subset ( t , begin , end ) ; } return cdmatch ; default : throw new RuntimeException ( \"Impossible op\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "crevdissect - determine backref shortest - first subexpression matches The retry memory stores the offset of the trial midpoint from begin plus 1 so that 0 uniquely means clean slate . [CODESPLIT] private boolean crevdissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; Dfa d2 ; int mid ; assert t . op == ' ' ; assert t . left != null && t . left . machine . states . length > 0 ; assert t . right != null && t . right . machine . states . length > 0 ; assert 0 != ( t . left . flags & Subre . SHORTER ) ; /* concatenation -- need to split the substring between parts */ d = new Dfa ( this , t . left . machine ) ; d2 = new Dfa ( this , t . right . machine ) ; /* pick a tentative midpoint */ if ( mem [ t . retry ] == 0 ) { mid = d . shortest ( begin , begin , end , null , null ) ; if ( mid == - 1 ) { return false ; } mem [ t . retry ] = ( mid - begin ) + 1 ; } else { mid = begin + ( mem [ t . retry ] - 1 ) ; } /* iterate until satisfaction or failure */ for ( ; ; ) { /* try this midpoint on for size */ boolean cdmatch = cdissect ( t . left , begin , mid ) ; if ( cdmatch && d2 . longest ( mid , end , null ) == end && ( cdissect ( t . right , mid , end ) ) ) { break ; /* NOTE BREAK OUT */ } /* that midpoint didn't work, find a new one */ if ( mid == end ) { /* all possibilities exhausted */ return false ; } mid = d . shortest ( begin , mid + 1 , end , null , null ) ; if ( mid == - 1 ) { /* failed to find a new one */ return false ; } mem [ t . retry ] = ( mid - begin ) + 1 ; zapmem ( t . left ) ; zapmem ( t . right ) ; } /* satisfaction */ return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cbrdissect - determine backref subexpression matches [CODESPLIT] private boolean cbrdissect ( RuntimeSubexpression t , int begin , int end ) { int i ; int n = t . number ; int len ; int paren ; int p ; int stop ; int min = t . min ; int max = t . max ; assert t . op == ' ' ; assert n >= 0 ; //TODO: could this get be out of range? if ( match . get ( n ) == null ) { return false ; } paren = match . get ( n ) . start ; len = match . get ( n ) . end - match . get ( n ) . start ; /* no room to maneuver -- retries are pointless */ if ( 0 != mem [ t . retry ] ) { return false ; } mem [ t . retry ] = 1 ; /* special-case zero-length string */ if ( len == 0 ) { return begin == end ; } /* and too-short string */ assert end >= begin ; if ( ( end - begin ) < len ) { return false ; } stop = end - len ; /* count occurrences */ i = 0 ; for ( p = begin ; p <= stop && ( i < max || max == Compiler . INFINITY ) ; p += len ) { // paren is index of if ( g . compare . compare ( data , paren , p , len ) != 0 ) { break ; } i ++ ; } /* and sort it out */ if ( p != end ) { /* didn't consume all of it */ return false ; } return min <= i && ( i <= max || max == Compiler . INFINITY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * - caltdissect - determine alternative subexpression matches ( w . complications ) ^ static int caltdissect ( struct vars * struct Subre int int ) ; [CODESPLIT] private boolean caltdissect ( RuntimeSubexpression t , int begin , int end ) { Dfa d ; if ( t == null ) { return false ; } assert t . op == ' ' ; if ( mem [ t . retry ] == TRIED ) { return caltdissect ( t . right , begin , end ) ; } if ( mem [ t . retry ] == UNTRIED ) { d = new Dfa ( this , t . left . machine ) ; if ( d . longest ( begin , end , null ) != end ) { mem [ t . retry ] = TRIED ; return caltdissect ( t . right , begin , end ) ; } mem [ t . retry ] = TRYING ; } boolean cdmatch = cdissect ( t . left , begin , end ) ; if ( cdmatch ) { return true ; } mem [ t . retry ] = TRIED ; return caltdissect ( t . right , begin , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "makesearch - turn an NFA into a search NFA ( implicit prepend of . * ? ) NFA must have been optimize () d already . [CODESPLIT] private void makesearch ( Nfa nfa ) { Arc a ; Arc b ; State pre = nfa . pre ; State s ; State s2 ; State slist ; /* no loops are needed if it's anchored */ for ( a = pre . outs ; a != null ; a = a . outchain ) { assert a . type == PLAIN ; if ( a . co != nfa . bos [ 0 ] && a . co != nfa . bos [ 1 ] ) { break ; } } if ( a != null ) { /* add implicit .* in front */ cm . rainbow ( nfa , PLAIN , Constants . COLORLESS , pre , pre ) ; /* and ^* and \\A* too -- not always necessary, but harmless */ nfa . newarc ( PLAIN , nfa . bos [ 0 ] , pre , pre ) ; nfa . newarc ( PLAIN , nfa . bos [ 1 ] , pre , pre ) ; } /*\n     * Now here's the subtle part.  Because many REs have no lookback\n     * constraints, often knowing when you were in the pre state tells\n     * you little; it's the next state(s) that are informative.  But\n     * some of them may have other inarcs, i.e. it may be possible to\n     * make actual progress and then return to one of them.  We must\n     * de-optimize such cases, splitting each such state into progress\n     * and no-progress states.\n     */ /* first, make a list of the states */ slist = null ; for ( a = pre . outs ; a != null ; a = a . outchain ) { s = a . to ; for ( b = s . ins ; b != null ; b = b . inchain ) { if ( b . from != pre ) { break ; } } if ( b != null ) { /* must be split */ if ( s . tmp == null ) { /* if not already in the list */ /* (fixes bugs 505048, 230589, */ /* 840258, 504785) */ s . tmp = slist ; slist = s ; } } } /* do the splits */ for ( s = slist ; s != null ; s = s2 ) { s2 = nfa . newstate ( ) ; copyouts ( nfa , s , s2 ) ; for ( a = s . ins ; a != null ; a = b ) { b = a . inchain ; if ( a . from != pre ) { cparc ( nfa , a , a . from , s2 ) ; nfa . freearc ( a ) ; } } s2 = s . tmp ; s . tmp = null ; /* clean up while we're at it */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cloneouts - copy out arcs of a state to another state pair modifying type [CODESPLIT] private void cloneouts ( Nfa nfa , State old , State from , State to , int type ) { Arc a ; assert old != from ; for ( a = old . outs ; a != null ; a = a . outchain ) { nfa . newarc ( type , a . co , from , to ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "optst - optimize a subRE subtree [CODESPLIT] private void optst ( Subre t ) { if ( t == null ) { return ; } /* recurse through children */ if ( t . left != null ) { optst ( t . left ) ; } if ( t . right != null ) { optst ( t . right ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "numst - number tree nodes ( assigning retry indexes ) [CODESPLIT] private int numst ( Subre t , int start ) { int i ; assert t != null ; i = start ; t . retry = ( short ) i ++ ; if ( t . left != null ) { i = numst ( t . left , i ) ; } if ( t . right != null ) { i = numst ( t . right , i ) ; } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "markst - mark tree nodes as INUSE [CODESPLIT] private void markst ( Subre t ) { assert t != null ; t . flags |= Subre . INUSE ; if ( t . left != null ) { markst ( t . left ) ; } if ( t . right != null ) { markst ( t . right ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * optimize results from top node [CODESPLIT] private long nfatree ( Subre t ) throws RegexException { assert t != null && t . begin != null ; if ( t . left != null ) { nfatree ( t . left ) ; } if ( t . right != null ) { nfatree ( t . right ) ; } return nfanode ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "nfanode - do one NFA for nfatree [CODESPLIT] private long nfanode ( Subre t ) throws RegexException { long ret ; assert t . begin != null ; if ( LOG . isDebugEnabled ( ) && IS_DEBUG ) { LOG . debug ( String . format ( \"========= TREE NODE %s ==========\" , t . shortId ( ) ) ) ; } Nfa newNfa = new Nfa ( nfa ) ; newNfa . dupnfa ( t . begin , t . end , newNfa . init , newNfa . finalState ) ; newNfa . specialcolors ( ) ; ret = newNfa . optimize ( ) ; t . cnfa = newNfa . compact ( ) ; // freenfa ... depend on our friend the GC. return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse - parse an RE This is actually just the top level which parses a bunch of branches tied together with | . They appear in the tree as the left children of a chain of | subres . [CODESPLIT] private Subre parse ( int stopper , int type , State initState , State finalState ) throws RegexException { State left ; /* scaffolding for branch */ State right ; Subre branches ; /* top level */ Subre branch ; /* current branch */ Subre t ; /* temporary */ int firstbranch ; /* is this the first branch? */ assert stopper == ' ' || stopper == EOS ; branches = new Subre ( ' ' , Subre . LONGER , initState , finalState ) ; branch = branches ; firstbranch = 1 ; do { /* a branch */ if ( 0 == firstbranch ) { /* need a place to hang it */ branch . right = new Subre ( ' ' , Subre . LONGER , initState , finalState ) ; branch = branch . right ; } firstbranch = 0 ; left = nfa . newstate ( ) ; right = nfa . newstate ( ) ; nfa . emptyarc ( initState , left ) ; nfa . emptyarc ( right , finalState ) ; branch . left = parsebranch ( stopper , type , left , right , false ) ; branch . flags |= up ( branch . flags | branch . left . flags ) ; if ( ( branch . flags & ~ branches . flags ) != 0 ) /* new flags */ { for ( t = branches ; t != branch ; t = t . right ) { t . flags |= branch . flags ; } } } while ( eat ( ' ' ) ) ; assert see ( stopper ) || see ( EOS ) ; if ( ! see ( stopper ) ) { assert stopper == ' ' && see ( EOS ) ; //ERR(REG_EPAREN); throw new RegexException ( \"Unbalanced parentheses.\" ) ; } /* optimize out simple cases */ if ( branch == branches ) { /* only one branch */ assert branch . right == null ; t = branch . left ; branch . left = null ; branches = t ; } else if ( ! messy ( branches . flags ) ) { /* no interesting innards */ branches . left = null ; branches . right = null ; branches . op = ' ' ; } return branches ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parsebranch - parse one branch of an RE This mostly manages concatenation working closely with parseqatom () . Concatenated things are bundled up as much as possible with separate nodes introduced only when necessary due to substructure . [CODESPLIT] private Subre parsebranch ( int stopper , int type , State left , State right , boolean partial ) throws RegexException { State lp ; /* left end of current construct */ boolean seencontent = false ; /* is there anything in this branch yet? */ Subre t ; lp = left ; t = new Subre ( ' ' , 0 , left , right ) ; /* op '=' is tentative */ while ( ! see ( ' ' ) && ! see ( stopper ) && ! see ( EOS ) ) { if ( seencontent ) { /* implicit concat operator */ lp = nfa . newstate ( ) ; moveins ( nfa , right , lp ) ; } seencontent = true ; /* NB, recursion in parseqatom() may swallow rest of branch */ parseqatom ( stopper , type , lp , right , t ) ; } if ( ! seencontent ) { /* empty branch */ if ( ! partial ) { note ( Flags . REG_UUNSPEC ) ; } nfa . emptyarc ( left , right ) ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CHECKSTYLE : OFF [CODESPLIT] private void parseqatom ( int stopper , int type , State lp , State rp , Subre top ) throws RegexException { State s ; /* temporaries for new states */ State s2 ; int m ; int n ; Subre atom ; /* atom's subtree */ Subre t ; boolean cap ; /* capturing parens? */ int pos ; /* positive lookahead? */ int subno ; /* capturing-parens or backref number */ int atomtype ; int qprefer ; /* quantifier short/long preference */ int f ; AtomSetter atomp ; /* initial bookkeeping */ atom = null ; assert lp . nouts == 0 ; /* must string new code */ assert rp . nins == 0 ; /*  between lp and rp */ subno = 0 ; /* just to shut lint up */ /* an atom or constraint... */ atomtype = nexttype ; switch ( atomtype ) { /* first, constraints, which end by returning */ case ' ' : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; if ( 0 != ( cflags & Flags . REG_NLANCH ) ) { nfa . newarc ( BEHIND , nlcolor , lp , rp ) ; } lex . next ( ) ; return ; case ' ' : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; if ( 0 != ( cflags & Flags . REG_NLANCH ) ) { nfa . newarc ( AHEAD , nlcolor , lp , rp ) ; } lex . next ( ) ; return ; case SBEGIN : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; /* BOL */ nfa . newarc ( ' ' , ( short ) 0 , lp , rp ) ; /* or BOS */ lex . next ( ) ; return ; case SEND : nfa . newarc ( ' ' , ( short ) 1 , lp , rp ) ; /* EOL */ nfa . newarc ( ' ' , ( short ) 0 , lp , rp ) ; /* or EOS */ lex . next ( ) ; return ; case ' ' : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; nonword ( BEHIND , lp , s ) ; word ( AHEAD , s , rp ) ; return ; case ' ' : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; word ( BEHIND , lp , s ) ; nonword ( AHEAD , s , rp ) ; return ; case WBDRY : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; nonword ( BEHIND , lp , s ) ; word ( AHEAD , s , rp ) ; s = nfa . newstate ( ) ; word ( BEHIND , lp , s ) ; nonword ( AHEAD , s , rp ) ; return ; case NWBDRY : wordchrs ( ) ; /* does next() */ s = nfa . newstate ( ) ; word ( BEHIND , lp , s ) ; word ( AHEAD , s , rp ) ; s = nfa . newstate ( ) ; nonword ( BEHIND , lp , s ) ; nonword ( AHEAD , s , rp ) ; return ; case LACON : /* lookahead constraint */ pos = nextvalue ; lex . next ( ) ; s = nfa . newstate ( ) ; s2 = nfa . newstate ( ) ; parse ( ' ' , LACON , s , s2 ) ; // parse for side-effect. assert see ( ' ' ) ; lex . next ( ) ; n = newlacon ( s , s2 , pos ) ; nfa . newarc ( LACON , ( short ) n , lp , rp ) ; return ; /* then errors, to get them out of the way */ case ' ' : case ' ' : case ' ' : case ' ' : throw new RegexException ( \"Pattern syntax error (*+?} misplaced).\" ) ; /* then plain characters, and minor variants on that theme */ case ' ' : /* unbalanced paren */ if ( ( cflags & Flags . REG_ADVANCED ) != Flags . REG_EXTENDED ) { throw new RegexException ( \"Unbalanced parenthesis.\" ) ; } /* legal in EREs due to specification botch */ note ( Flags . REG_UPBOTCH ) ; /* fallthrough into case PLAIN */ case PLAIN : // look out for surrogates as ordinary chars. if ( nextvalue < Character . MAX_VALUE && Character . isHighSurrogate ( ( char ) nextvalue ) ) { char high = ( char ) nextvalue ; lex . next ( ) ; char low = ( char ) nextvalue ; int codepoint = Character . toCodePoint ( high , low ) ; onechr ( codepoint , lp , rp ) ; } else { onechr ( nextvalue , lp , rp ) ; } cm . okcolors ( nfa ) ; lex . next ( ) ; break ; case ' ' : if ( nextvalue == 1 ) { bracket ( lp , rp ) ; } else { cbracket ( lp , rp ) ; } assert see ( ' ' ) ; lex . next ( ) ; break ; case ' ' : cm . rainbow ( nfa , PLAIN , ( 0 != ( cflags & Flags . REG_NLSTOP ) ) ? nlcolor : Constants . COLORLESS , lp , rp ) ; lex . next ( ) ; break ; /* and finally the ugly stuff */ case ' ' : /* value flags as capturing or non */ if ( type == LACON ) { cap = false ; } else { cap = nextvalue != 0 ; } if ( cap ) { subno = subs . size ( ) + 1 ; // first subno is 1. /*\n                 * This recurses via a call to parse just below.\n                 * So, the size() just above has to reflect this new sub,\n                 * even though we won't create the object until a little further\n                 * down.\n                 */ subs . add ( null ) ; } else { atomtype = PLAIN ; /* something that's not '(' */ } lex . next ( ) ; /* need new endpoints because tree will contain pointers */ s = nfa . newstate ( ) ; s2 = nfa . newstate ( ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( s2 , rp ) ; atom = parse ( ' ' , PLAIN , s , s2 ) ; assert see ( ' ' ) ; lex . next ( ) ; if ( cap ) { // we can't assert anything about the size of 'subs', recursion may have added to it. // but we can check that nothing has used our slot. assert subs . get ( subno - 1 ) == null ; subs . set ( subno - 1 , atom ) ; t = new Subre ( ' ' , atom . flags | Subre . CAP , lp , rp ) ; t . subno = subno ; t . left = atom ; atom = t ; } /* postpone everything else pending possible {0} */ break ; case BACKREF : /* the Feature From The Black Lagoon */ if ( type == LACON ) { throw new RegexException ( \"REG_ESUBREG\" ) ; } if ( nextvalue > subs . size ( ) ) { throw new RegexException ( String . format ( \"Backreference to %d out of range of defined subexpressions (%d)\" , nextvalue , subs . size ( ) ) ) ; } if ( subs . get ( nextvalue - 1 ) == null ) { // \\1 is first backref, living in slot 0. throw new RegexException ( String . format ( \"Backreference to %d refers to non-capturing group.\" , nextvalue ) ) ; } assert nextvalue > 0 ; atom = new Subre ( ' ' , Subre . BACKR , lp , rp ) ; subno = nextvalue ; atom . subno = subno ; nfa . emptyarc ( lp , rp ) ; /* temporarily, so there's something */ lex . next ( ) ; break ; default : throw new RuntimeException ( \"Impossible type in lex\" ) ; } /* ...and an atom may be followed by a quantifier */ switch ( nexttype ) { case ' ' : m = 0 ; n = INFINITY ; qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; lex . next ( ) ; break ; case ' ' : m = 1 ; n = INFINITY ; qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; lex . next ( ) ; break ; case ' ' : m = 0 ; n = 1 ; qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; lex . next ( ) ; break ; case ' ' : lex . next ( ) ; m = scannum ( ) ; if ( eat ( ' ' ) ) { if ( see ( DIGIT ) ) { n = scannum ( ) ; } else { n = INFINITY ; } if ( m > n ) { throw new RegexException ( \"First quantity is larger than second quantity in {m,n} quantifier.\" ) ; } /* {m,n} exercises preference, even if it's {m,m} */ qprefer = ( nextvalue != 0 ) ? Subre . LONGER : Subre . SHORTER ; } else { n = m ; /* {m} passes operand's preference through */ qprefer = 0 ; } if ( ! see ( ' ' ) ) { /* catches errors too */ throw new RegexException ( \"Invalid syntax for {m,n} quantifier.\" ) ; } lex . next ( ) ; break ; default : /* no quantifier */ m = 1 ; n = 1 ; qprefer = 0 ; break ; } /* annoying special case:  {0} or {0,0} cancels everything */ if ( m == 0 && n == 0 ) { if ( atomtype == ' ' ) { assert subno == subs . size ( ) - 1 ; subs . remove ( subs . size ( ) - 1 ) ; } delsub ( nfa , lp , rp ) ; nfa . emptyarc ( lp , rp ) ; return ; } /* if not a messy case, avoid hard part */ assert ! messy ( top . flags ) ; f = top . flags | qprefer | ( ( atom != null ) ? atom . flags : 0 ) ; if ( atomtype != ' ' && atomtype != BACKREF && ! messy ( up ( f ) ) ) { if ( ! ( m == 1 && n == 1 ) ) { repeat ( lp , rp , m , n ) ; } top . flags = f ; return ; } /*\n     * hard part:  something messy\n     * That is, capturing parens, back reference, short/long clash, or\n     * an atom with substructure containing one of those.\n     */ /* now we'll need a subre for the contents even if they're boring */ if ( atom == null ) { atom = new Subre ( ' ' , 0 , lp , rp ) ; } /*\n     * prepare a general-purpose state skeleton\n     *\n     *    --. [s] ---prefix--. [begin] ---atom--. [end] ----rest--. [rp]\n     *   /                                            /\n     * [lp] ---. [s2] ----bypass---------------------\n     *\n     * where bypass is an empty, and prefix is some repetitions of atom\n     */ s = nfa . newstate ( ) ; /* first, new endpoints for the atom */ s2 = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . moveins ( rp , s2 ) ; atom . begin = s ; atom . end = s2 ; s = nfa . newstate ( ) ; /* and spots for prefix and bypass */ s2 = nfa . newstate ( ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( lp , s2 ) ; /* break remaining subRE into x{...} and what follows */ t = new Subre ( ' ' , Subre . combine ( qprefer , atom . flags ) , lp , rp ) ; t . left = atom ; final Subre target = t ; atomp = new AtomSetter ( ) { @ Override public void set ( Subre s ) { target . left = s ; } } ; /* here we should recurse... but we must postpone that to the end */ /* split top into prefix and remaining */ assert top . op == ' ' && top . left == null && top . right == null ; top . left = new Subre ( ' ' , top . flags , top . begin , lp ) ; top . op = ' ' ; top . right = t ; /* if it's a backref, now is the time to replicate the subNFA */ if ( atomtype == BACKREF ) { assert atom . begin . nouts == 1 ; /* just the EMPTY */ delsub ( nfa , atom . begin , atom . end ) ; assert subs . get ( subno - 1 ) != null ; /* and here's why the recursion got postponed:  it must */ /* wait until the skeleton is filled in, because it may */ /* hit a backref that wants to copy the filled-in skeleton */ nfa . dupnfa ( subs . get ( subno - 1 ) . begin , subs . get ( subno - 1 ) . end , atom . begin , atom . end ) ; } /* it's quantifier time; first, turn x{0,...} into x{1,...}|empty */ if ( m == 0 ) { nfa . emptyarc ( s2 , atom . end ) ; /* the bypass */ assert Subre . pref ( qprefer ) != 0 ; f = Subre . combine ( qprefer , atom . flags ) ; t = new Subre ( ' ' , f , lp , atom . end ) ; t . left = atom ; t . right = new Subre ( ' ' , Subre . pref ( f ) , s2 , atom . end ) ; t . right . left = new Subre ( ' ' , 0 , s2 , atom . end ) ; atomp . set ( t ) ; final Subre target2 = t ; atomp = new AtomSetter ( ) { @ Override public void set ( Subre s ) { target2 . left = s ; } } ; m = 1 ; } /* deal with the rest of the quantifier */ if ( atomtype == BACKREF ) { /* special case:  backrefs have internal quantifiers */ nfa . emptyarc ( s , atom . begin ) ; /* empty prefix */ /* just stuff everything into atom */ repeat ( atom . begin , atom . end , m , n ) ; atom . min = ( short ) m ; atom . max = ( short ) n ; atom . flags |= Subre . combine ( qprefer , atom . flags ) ; } else if ( m == 1 && n == 1 ) { /* no/vacuous quantifier:  done */ nfa . emptyarc ( s , atom . begin ) ; /* empty prefix */ } else { /* turn x{m,n} into x{m-1,n-1}x, with capturing */ /*  parens in only second x */ nfa . dupnfa ( atom . begin , atom . end , s , atom . begin ) ; assert m >= 1 && m != INFINITY && n >= 1 ; repeat ( s , atom . begin , m - 1 , ( n == INFINITY ) ? n : n - 1 ) ; f = Subre . combine ( qprefer , atom . flags ) ; t = new Subre ( ' ' , f , s , atom . end ) ; /* prefix and atom */ t . left = new Subre ( ' ' , Subre . pref ( f ) , s , atom . begin ) ; t . right = atom ; atomp . set ( t ) ; } /* and finally, look after that postponed recursion */ t = top . right ; if ( ! ( see ( ' ' ) || see ( stopper ) || see ( EOS ) ) ) { t . right = parsebranch ( stopper , type , atom . end , rp , true ) ; } else { nfa . emptyarc ( atom . end , rp ) ; t . right = new Subre ( ' ' , 0 , atom . end , rp ) ; } assert see ( ' ' ) || see ( stopper ) || see ( EOS ) ; t . flags |= Subre . combine ( t . flags , t . right . flags ) ; top . flags |= Subre . combine ( top . flags , t . flags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CHECKSTYLE : ON [CODESPLIT] private void delsub ( Nfa nfa , State lp , State rp ) { rp . tmp = rp ; deltraverse ( nfa , lp , lp ) ; assert lp . nouts == 0 && rp . nins == 0 ; /* did the job */ assert lp . no != State . FREESTATE && rp . no != State . FREESTATE ; /* no more */ lp . tmp = null ; rp . tmp = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deltraverse - the recursive heart of delsub This routine s basic job is to destroy all out - arcs of the state . [CODESPLIT] private void deltraverse ( Nfa nfa , State leftend , State s ) { Arc a ; State to ; if ( s . nouts == 0 ) { return ; /* nothing to do */ } if ( s . tmp != null ) { return ; /* already in progress */ } s . tmp = s ; /* mark as in progress */ while ( ( a = s . outs ) != null ) { to = a . to ; deltraverse ( nfa , leftend , to ) ; assert to . nouts == 0 || to . tmp != null ; nfa . freearc ( a ) ; if ( to . nins == 0 && to . tmp == null ) { assert to . nouts == 0 ; nfa . freestate ( to ) ; } } assert s . no != State . FREESTATE ; /* we're still here */ assert s == leftend || s . nins != 0 ; /* and still reachable */ assert s . nouts == 0 ; /* but have no outarcs */ s . tmp = null ; /* we're done here */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "nonword - generate arcs for non - word - character ahead or behind [CODESPLIT] private void nonword ( int dir , State lp , State rp ) { int anchor = ( dir == AHEAD ) ? ' ' : ' ' ; assert dir == AHEAD || dir == BEHIND ; nfa . newarc ( anchor , ( short ) 1 , lp , rp ) ; nfa . newarc ( anchor , ( short ) 0 , lp , rp ) ; cm . colorcomplement ( nfa , dir , wordchrs , lp , rp ) ; /* (no need for special attention to \\n) */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "word - generate arcs for word character ahead or behind [CODESPLIT] private void word ( int dir , State lp , State rp ) { assert dir == AHEAD || dir == BEHIND ; cloneouts ( nfa , wordchrs , lp , rp , dir ) ; /* (no need for special attention to \\n) */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "scannum - scan a number [CODESPLIT] private int scannum ( ) throws RegexException { int n = 0 ; while ( see ( DIGIT ) && n < DUPMAX ) { n = n * 10 + nextvalue ; lex . next ( ) ; } if ( see ( DIGIT ) || n > DUPMAX ) { throw new RegexException ( \"Unvalid reference number.\" ) ; } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "repeat - replicate subNFA for quantifiers The duplication sequences used here are chosen carefully so that any pointers starting out pointing into the subexpression end up pointing into the last occurrence . ( Note that it may not be strung between the same left and right end states however! ) This used to be important for the subRE tree although the important bits are now handled by the in - line code in parse () and when this is called it doesn t matter any more . [CODESPLIT] private void repeat ( State lp , State rp , int m , int n ) throws RegexException { final int rm = reduce ( m ) ; final int rn = reduce ( n ) ; State s ; State s2 ; switch ( pair ( rm , rn ) ) { // pair(0, 0) case 0 : /* empty string */ // never get here; other code optimizes this out. delsub ( nfa , lp , rp ) ; nfa . emptyarc ( lp , rp ) ; break ; //case PAIR(0, 1):      /* do as x| */ case 1 : nfa . emptyarc ( lp , rp ) ; break ; //case PAIR(0, SOME):       /* do as x{1,n}| */ case SOME : repeat ( lp , rp , 1 , n ) ; nfa . emptyarc ( lp , rp ) ; break ; //case PAIR(0, INF):        /* loop x around */ case INF : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . moveins ( rp , s ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( s , rp ) ; break ; //case PAIR(1, 1):      /* no action required */ case 4 * 1 + 1 : break ; //case PAIR(1, SOME):       /* do as x{0,n-1}x = (x{1,n-1}|)x */ case 4 * 1 + SOME : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . dupnfa ( s , rp , lp , s ) ; repeat ( lp , s , 1 , n - 1 ) ; nfa . emptyarc ( lp , s ) ; break ; //case PAIR(1, INF):        /* add loopback arc */ case 4 * 1 + INF : s = nfa . newstate ( ) ; s2 = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . moveins ( rp , s2 ) ; nfa . emptyarc ( lp , s ) ; nfa . emptyarc ( s2 , rp ) ; nfa . emptyarc ( s2 , s ) ; break ; //case PAIR(SOME, SOME):        /* do as x{m-1,n-1}x */ case 4 * SOME + SOME : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . dupnfa ( s , rp , lp , s ) ; repeat ( lp , s , m - 1 , n - 1 ) ; break ; //case PAIR(SOME, INF):     /* do as x{m-1,}x */ case 4 * SOME + INF : s = nfa . newstate ( ) ; nfa . moveouts ( lp , s ) ; nfa . dupnfa ( s , rp , lp , s ) ; repeat ( lp , s , m - 1 , n ) ; break ; default : throw new RuntimeException ( \"Impossible quantification\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "wordchrs - set up word - chr list for word - boundary stuff if needed The list is kept as a bunch of arcs between two dummy states ; it s disposed of by the unreachable - states sweep in NFA optimization . Does NEXT () . Must not be called from any unusual lexical context . This should be reconciled with the \\ w etc . handling in lex . c and should be cleaned up to reduce dependencies on input scanning . [CODESPLIT] private void wordchrs ( ) throws RegexException { State left ; State right ; if ( wordchrs != null ) { lex . next ( ) ; /* for consistency */ return ; } left = nfa . newstate ( ) ; right = nfa . newstate ( ) ; /* fine point:  implemented with [::], and lexer will set REG_ULOCALE */ lex . lexword ( ) ; lex . next ( ) ; assert savepattern != null && see ( ' ' ) ; bracket ( left , right ) ; assert savepattern != null && see ( ' ' ) ; lex . next ( ) ; wordchrs = left ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "bracket - handle non - complemented bracket expression Also called from cbracket for complemented bracket expressions . [CODESPLIT] private void bracket ( State lp , State rp ) throws RegexException { assert see ( ' ' ) ; lex . next ( ) ; while ( ! see ( ' ' ) && ! see ( EOS ) ) { brackpart ( lp , rp ) ; } assert see ( ' ' ) ; cm . okcolors ( nfa ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "brackpart - handle one item ( or range ) within a bracket expression [CODESPLIT] private void brackpart ( State lp , State rp ) throws RegexException { UnicodeSet set ; /*\n         * OK, well; if the user uses \\U the item that comes next can be a full codepoint.\n         * If the user does not, it might be part of a surrogate.\n         */ int c ; // start and end chars of a range int startc ; int endc = 0 ; int ele ; /* parse something, get rid of special cases, take shortcuts */ switch ( nexttype ) { case RANGE : /* a-b-c or other botch */ throw new RegexException ( \"Invalid syntax in range expression.\" ) ; case PLAIN : c = nextvalue ; lex . next ( ) ; if ( c <= Character . MAX_VALUE && Character . isHighSurrogate ( ( char ) c ) ) { // some idiot could write a high surrogate and then immediate \\\\Uxxxxx, woof. char low = ( char ) nextvalue ; lex . next ( ) ; startc = Character . toCodePoint ( ( char ) c , low ) ; } else { startc = c ; } /* shortcut for ordinary char (not range, not MCCE leader) */ if ( ! see ( RANGE ) ) { onechr ( startc , lp , rp ) ; return ; } break ; // COLLEL and ECLASS are of dubious utility and don't try to get surrogates right. case COLLEL : String charName = scanplain ( ) ; if ( charName . length ( ) == 0 ) { throw new RegexException ( \"Missing character name for collation.\" ) ; } ele = Locale . element ( charName ) ; if ( ele == - 1 ) { throw new RegexException ( \"Invalid character name \" + charName ) ; } else { startc = ( char ) ele ; } break ; case ECLASS : charName = scanplain ( ) ; if ( charName . length ( ) == 0 ) { throw new RegexException ( \"Unterminated or invalid equivalence class.\" ) ; } ele = Locale . element ( charName ) ; if ( ele == - 1 ) { throw new RegexException ( \"Invalid character name \" + charName ) ; } else { startc = ( char ) ele ; } set = Locale . eclass ( ( char ) startc , 0 != ( cflags & Flags . REG_ICASE ) ) ; dovec ( set , lp , rp ) ; return ; case CCLASS : String className = scanplain ( ) ; if ( className . length ( ) == 0 ) { throw new RegexException ( \"Missing class name for char class.\" ) ; } set = Locale . cclass ( className , 0 != ( cflags & Flags . REG_ICASE ) ) ; dovec ( set , lp , rp ) ; return ; default : throw new RegexException ( \"Impossible lexical state.\" ) ; } if ( see ( RANGE ) ) { lex . next ( ) ; switch ( nexttype ) { case PLAIN : case RANGE : c = nextvalue ; lex . next ( ) ; if ( c <= Character . MAX_VALUE && Character . isHighSurrogate ( ( char ) c ) ) { char low = ( char ) nextvalue ; lex . next ( ) ; endc = Character . toCodePoint ( ( char ) c , low ) ; } else { endc = c ; } break ; case COLLEL : String charName = scanplain ( ) ; if ( charName . length ( ) == 0 ) { throw new RegexException ( \"Missing character name in collation.\" ) ; } // look up named character. ele = Locale . element ( charName ) ; if ( ele == - 1 ) { throw new RegexException ( \"Invalid character name \" + charName ) ; } break ; default : throw new RegexException ( \"Invalid syntax in range.\" ) ; } } else { endc = startc ; } set = new UnicodeSet ( startc , endc ) ; if ( 0 != ( cflags & Flags . REG_ICASE ) ) { set . closeOver ( UnicodeSet . ADD_CASE_MAPPINGS ) ; } dovec ( set , lp , rp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "scanplain - scan PLAIN contents of [ . etc . Certain bits of trickery in lex . c know that this code does not try to look past the final bracket of the [ . etc . [CODESPLIT] private String scanplain ( ) throws RegexException { int startp = now ; int endp ; assert see ( COLLEL ) || see ( ECLASS ) || see ( CCLASS ) ; lex . next ( ) ; endp = now ; while ( see ( PLAIN ) ) { endp = now ; lex . next ( ) ; } String ret = new String ( pattern , startp , endp - startp ) ; assert see ( END ) ; lex . next ( ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cbracket - handle complemented bracket expression We do it by calling bracket () with dummy endpoints and then complementing the result . The alternative would be to invoke rainbow () and then delete arcs as the b . e . is seen ... but that gets messy . [CODESPLIT] private void cbracket ( State lp , State rp ) throws RegexException { State left = nfa . newstate ( ) ; State right = nfa . newstate ( ) ; bracket ( left , right ) ; if ( 0 != ( cflags & Flags . REG_NLSTOP ) ) { nfa . newarc ( PLAIN , nlcolor , left , right ) ; } assert lp . nouts == 0 ; /* all outarcs will be ours */ /* easy part of complementing */ cm . colorcomplement ( nfa , PLAIN , left , lp , rp ) ; // No MCCE in Java. nfa . dropstate ( left ) ; assert right . nins == 0 ; nfa . freestate ( right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "newlacon - allocate a lookahead - constraint subRE [CODESPLIT] private int newlacon ( State begin , State end , int pos ) { if ( lacons . size ( ) == 0 ) { // skip 0 lacons . add ( null ) ; } Subre sub = new Subre ( ( char ) 0 , 0 , begin , end ) ; sub . subno = pos ; lacons . add ( sub ) ; return lacons . size ( ) - 1 ; // it's the index into the array, -1. }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "onechr - fill in arcs for a plain character and possible case complements This is mostly a shortcut for efficient handling of the common case . [CODESPLIT] private void onechr ( int c , State lp , State rp ) throws RegexException { if ( 0 == ( cflags & Flags . REG_ICASE ) ) { nfa . newarc ( PLAIN , cm . subcolor ( c ) , lp , rp ) ; return ; } /* rats, need general case anyway... */ dovec ( Locale . allcases ( c ) , lp , rp ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dovec - fill in arcs for each element of a cvec all kinds of MCCE complexity removed . [CODESPLIT] private void dovec ( UnicodeSet set , State lp , State rp ) throws RegexException { int rangeCount = set . getRangeCount ( ) ; for ( int rx = 0 ; rx < rangeCount ; rx ++ ) { int rangeStart = set . getRangeStart ( rx ) ; int rangeEnd = set . getRangeEnd ( rx ) ; /*\n             * Note: ICU operates in UTF-32 here, and the ColorMap is happy to play along.\n             */ if ( LOG . isDebugEnabled ( ) && IS_DEBUG ) { LOG . debug ( String . format ( \"%s %d %4x %4x\" , set , rx , rangeStart , rangeEnd ) ) ; } //TODO: this arc is probably redundant. if ( rangeStart == rangeEnd ) { nfa . newarc ( PLAIN , cm . subcolor ( rangeStart ) , lp , rp ) ; } cm . subrange ( rangeStart , rangeEnd , lp , rp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile a pattern . [CODESPLIT] public static RePattern compile ( String pattern , EnumSet < PatternFlags > flags ) throws RegexException { return Compiler . compile ( pattern , flags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile a pattern . [CODESPLIT] public static RePattern compile ( String pattern , PatternFlags ... flags ) throws RegexException { EnumSet < PatternFlags > flagSet = EnumSet . noneOf ( PatternFlags . class ) ; Collections . addAll ( flagSet , flags ) ; return Compiler . compile ( pattern , flagSet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * back chain [CODESPLIT] Arc findarc ( int type , short co ) { for ( Arc a = outs ; a != null ; a = a . outchain ) { if ( a . type == type && a . co == co ) { return a ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the color for a character . [CODESPLIT] private short getcolor ( int c ) { try { return map . get ( c ) ; } catch ( NullPointerException npe ) { throw new RegexRuntimeException ( String . format ( \"Failed to map codepoint U+%08X.\" , c ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pseudocolor - allocate a false color to be managed by other means . [CODESPLIT] short pseudocolor ( ) { short co = newcolor ( ) ; ColorDesc cd = colorDescs . get ( co ) ; cd . setNChars ( 1 ) ; cd . markPseudo ( ) ; return co ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "subcolor - allocate a new subcolor ( if necessary ) to this char Internal API that can do a range of characters ; called from { @link #subrange } . [CODESPLIT] private short subcolor ( int c , int rangeCount ) throws RegexException { short co ; /* current color of c */ short sco ; /* new subcolor */ co = getcolor ( c ) ; sco = newsub ( co ) ; assert sco != Constants . COLORLESS ; if ( co == sco ) /* already in an open subcolor */ { return co ; /* rest is redundant */ } ColorDesc cd = colorDescs . get ( co ) ; cd . incrementNChars ( - rangeCount ) ; ColorDesc scd = colorDescs . get ( sco ) ; scd . incrementNChars ( rangeCount ) ; map . put ( Range . closedOpen ( c , c + rangeCount ) , sco ) ; return sco ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "newsub - allocate a new subcolor ( if necessary ) for a color [CODESPLIT] private short newsub ( short co ) throws RegexException { short sco ; // new subcolor. ColorDesc cd = colorDescs . get ( co ) ; sco = colorDescs . get ( co ) . sub ; if ( sco == Constants . NOSUB ) { /* color has no open subcolor */ if ( cd . getNChars ( ) == 1 ) { /* optimization */ return co ; } sco = newcolor ( ) ; /* must create subcolor */ if ( sco == Constants . COLORLESS ) { throw new RegexException ( \"Invalid color allocation\" ) ; } ColorDesc subcd = colorDescs . get ( sco ) ; cd . sub = sco ; subcd . sub = sco ; /* open subcolor points to self */ } return sco ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "subrange - allocate new subcolors to this range of chars fill in arcs . The range will overlap existing ranges ; even in the simplest case it will overlap the initial WHITE range . For each existing range that it overlaps allocate a new color mark the range as mapping to that color and add an arc between the states for that color . [CODESPLIT] void subrange ( int from , int to , State lp , State rp ) throws RegexException { /* Avoid one call to map.get() for each character in the range.\n         * This map will usually contain one item, but in complex cases more.\n         * For example, if we had [a-f][g-h] and then someone asked for [f-g], there\n         * would be two. Each of these new ranges will get a new color via subcolor.\n         */ Map < Range < Integer > , Short > curColors = map . subRangeMap ( Range . closed ( from , to ) ) . asMapOfRanges ( ) ; /*\n         * To avoid concurrent mod problems, we need to copy the ranges we are working from.\n         */ List < Range < Integer > > ranges = Lists . newArrayList ( curColors . keySet ( ) ) ; for ( Range < Integer > rangeToProcess : ranges ) { // bound management here irritating. int start = rangeToProcess . lowerEndpoint ( ) ; if ( rangeToProcess . lowerBoundType ( ) == BoundType . OPEN ) { start ++ ; } int end = rangeToProcess . upperEndpoint ( ) ; if ( rangeToProcess . upperBoundType ( ) == BoundType . CLOSED ) { end ++ ; } // allocate a new subcolor and account it owning the entire range. short color = subcolor ( start , end - start ) ; compiler . getNfa ( ) . newarc ( Compiler . PLAIN , color , lp , rp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "okcolors - promote subcolors to full colors [CODESPLIT] void okcolors ( Nfa nfa ) { ColorDesc cd ; ColorDesc scd ; Arc a ; short sco ; for ( short co = 0 ; co < colorDescs . size ( ) ; co ++ ) { cd = colorDescs . get ( co ) ; if ( cd == null ) { continue ; // not in use at all, so can't have a subcolor. } sco = cd . sub ; if ( sco == Constants . NOSUB ) { /* has no subcolor, no further action */ } else if ( sco == co ) { /* is subcolor, let parent deal with it */ } else if ( cd . getNChars ( ) == 0 ) { /* parent empty, its arcs change color to subcolor */ cd . sub = Constants . NOSUB ; scd = colorDescs . get ( sco ) ; assert scd . getNChars ( ) > 0 ; assert scd . sub == sco ; scd . sub = Constants . NOSUB ; while ( ( a = cd . arcs ) != null ) { assert a . co == co ; cd . arcs = a . colorchain ; a . setColor ( sco ) ; a . colorchain = scd . arcs ; scd . arcs = a ; } freecolor ( co ) ; } else { /* parent's arcs must gain parallel subcolor arcs */ cd . sub = Constants . NOSUB ; scd = colorDescs . get ( sco ) ; assert scd . getNChars ( ) > 0 ; assert scd . sub == sco ; scd . sub = Constants . NOSUB ; for ( a = cd . arcs ; a != null ; a = a . colorchain ) { assert a . co == co ; nfa . newarc ( a . type , sco , a . from , a . to ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "colorchain - add this arc to the color chain of its color [CODESPLIT] void colorchain ( Arc a ) { ColorDesc cd = colorDescs . get ( a . co ) ; a . colorchain = cd . arcs ; cd . arcs = a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "uncolorchain - delete this arc from the color chain of its color [CODESPLIT] void uncolorchain ( Arc a ) { ColorDesc cd = colorDescs . get ( a . co ) ; Arc aa ; aa = cd . arcs ; if ( aa == a ) { /* easy case */ cd . arcs = a . colorchain ; } else { for ( ; aa != null && aa . colorchain != a ; aa = aa . colorchain ) { // } assert aa != null ; aa . colorchain = a . colorchain ; } a . colorchain = null ; /* paranoia */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rainbow - add arcs of all full colors ( but one ) between specified states [CODESPLIT] void rainbow ( Nfa nfa , int type , short but , State from , State to ) { ColorDesc cd ; short co ; for ( co = 0 ; co < colorDescs . size ( ) ; co ++ ) { cd = colorDescs . get ( co ) ; if ( cd != null && cd . sub != co && co != but && ! cd . pseudo ( ) ) { nfa . newarc ( type , co , from , to ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "colorcomplement - add arcs of complementary colors The calling sequence ought to be reconciled with cloneouts () . [CODESPLIT] void colorcomplement ( Nfa nfa , int type , State of , State from , State to ) { ColorDesc cd ; short co ; assert of != from ; for ( co = 0 ; co < colorDescs . size ( ) ; co ++ ) { cd = colorDescs . get ( co ) ; if ( cd != null && ! cd . pseudo ( ) ) { if ( of . findarc ( Compiler . PLAIN , co ) == null ) { nfa . newarc ( type , co , from , to ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumpcolors - debugging output [CODESPLIT] void dumpcolors ( ) { /*\n         * we want to organize this by colors.\n         */ for ( int co = 0 ; co < colorDescs . size ( ) ; co ++ ) { ColorDesc cd = colorDescs . get ( co ) ; if ( cd != null ) { dumpcolor ( co , cd ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Not speedy . This is for debugging . [CODESPLIT] private void dumpcolor ( int co , ColorDesc cd ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; pw . format ( \"Color %d - %d chars %s\\n\" , co , cd . getNChars ( ) , cd . pseudo ( ) ? \" (pseudo)\" : \"\" ) ; for ( Map . Entry < Range < Integer > , Short > me : map . asMapOfRanges ( ) . entrySet ( ) ) { if ( me . getValue ( ) == co ) { pw . format ( \" %s %s\\n\" , me . getKey ( ) , UCharacter . getExtendedName ( me . getKey ( ) . lowerEndpoint ( ) ) ) ; } } pw . flush ( ) ; String r = sw . toString ( ) ; System . out . println ( r ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lexstart - set up lexical stuff scan leading options [CODESPLIT] void lexstart ( ) throws RegexException { prefixes ( ) ; /* may turn on new type bits etc. */ if ( 0 != ( v . cflags & Flags . REG_QUOTE ) ) { assert 0 == ( v . cflags & ( Flags . REG_ADVANCED | Flags . REG_EXPANDED | Flags . REG_NEWLINE ) ) ; intocon ( L_Q ) ; } else if ( 0 != ( v . cflags & Flags . REG_EXTENDED ) ) { assert 0 == ( v . cflags & Flags . REG_QUOTE ) ; intocon ( L_ERE ) ; } else { assert 0 == ( v . cflags & ( Flags . REG_QUOTE | Flags . REG_ADVF ) ) ; intocon ( L_BRE ) ; } v . nexttype = Compiler . EMPTY ; /* remember we were at the start */ next ( ) ; /* set up the first token */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prefixes - implement various special prefixes [CODESPLIT] void prefixes ( ) throws RegexException { /* literal string doesn't get any of this stuff */ if ( 0 != ( v . cflags & Flags . REG_QUOTE ) ) { return ; } /* initial \"***\" gets special things */ if ( have ( 4 ) && next3 ( ' ' , ' ' , ' ' ) ) { switch ( charAtNowPlus ( 3 ) ) { case ' ' : /* \"***?\" error, msg shows version */ throw new RegexException ( \"REG_BADPAT\" ) ; case ' ' : /* \"***=\" shifts to literal string */ v . note ( Flags . REG_UNONPOSIX ) ; v . cflags |= Flags . REG_QUOTE ; v . cflags &= ~ ( Flags . REG_ADVANCED | Flags . REG_EXPANDED | Flags . REG_NEWLINE ) ; v . now += 4 ; return ; /* and there can be no more prefixes */ case ' ' : /* \"***:\" shifts to AREs */ v . note ( Flags . REG_UNONPOSIX ) ; v . cflags |= Flags . REG_ADVANCED ; v . now += 4 ; break ; default : /* otherwise *** is just an error */ throw new RegexException ( \"REG_BADRPT\" ) ; } } /* BREs and EREs don't get embedded options */ if ( ( v . cflags & Flags . REG_ADVANCED ) != Flags . REG_ADVANCED ) { return ; } /* embedded options (AREs only) */ if ( have ( 3 ) && next2 ( ' ' , ' ' ) && iscalpha ( charAtNowPlus ( 2 ) ) ) { v . note ( Flags . REG_UNONPOSIX ) ; v . now += 2 ; for ( ; ! ateos ( ) && iscalpha ( charAtNow ( ) ) ; v . now ++ ) { switch ( charAtNow ( ) ) { case ' ' : /* BREs (but why???) */ v . cflags &= ~ ( Flags . REG_ADVANCED | Flags . REG_QUOTE ) ; break ; case ' ' : /* case sensitive */ v . cflags &= ~ Flags . REG_ICASE ; break ; case ' ' : /* plain EREs */ v . cflags |= Flags . REG_EXTENDED ; v . cflags &= ~ ( Flags . REG_ADVF | Flags . REG_QUOTE ) ; break ; case ' ' : /* case insensitive */ v . cflags |= Flags . REG_ICASE ; break ; case ' ' : /* Perloid synonym for n */ case ' ' : /* \\n affects ^ $ . [^ */ v . cflags |= Flags . REG_NEWLINE ; break ; case ' ' : /* ~Perl, \\n affects . [^ */ v . cflags |= Flags . REG_NLSTOP ; v . cflags &= ~ Flags . REG_NLANCH ; break ; case ' ' : /* literal string */ v . cflags |= Flags . REG_QUOTE ; v . cflags &= ~ Flags . REG_ADVANCED ; break ; case ' ' : /* single line, \\n ordinary */ v . cflags &= ~ Flags . REG_NEWLINE ; break ; case ' ' : /* tight syntax */ v . cflags &= ~ Flags . REG_EXPANDED ; break ; case ' ' : /* weird, \\n affects ^ $ only */ v . cflags &= ~ Flags . REG_NLSTOP ; v . cflags |= Flags . REG_NLANCH ; break ; case ' ' : /* expanded syntax */ v . cflags |= Flags . REG_EXPANDED ; break ; default : throw new RegexException ( \"REG_BADOPT\" ) ; } } if ( ! next1 ( ' ' ) ) { throw new RegexException ( \"REG_BADOPT\" ) ; } v . now ++ ; if ( 0 != ( v . cflags & Flags . REG_QUOTE ) ) { v . cflags &= ~ ( Flags . REG_EXPANDED | Flags . REG_NEWLINE ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lexnest - call a subroutine interpolating string at the lexical level Note this is not a very general facility . There are a number of implicit assumptions about what sorts of strings can be subroutines . [CODESPLIT] void lexnest ( char [ ] interpolated ) { assert v . savepattern == null ; /* only one level of nesting */ v . savepattern = v . pattern ; v . savenow = v . now ; v . savestop = v . stop ; v . savenow = v . now ; v . pattern = interpolated ; v . now = 0 ; v . stop = v . pattern . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "next - get next token [CODESPLIT] boolean next ( ) throws RegexException { char c ; /* remember flavor of last token */ v . lasttype = v . nexttype ; /* REG_BOSONLY */ if ( v . nexttype == Compiler . EMPTY && ( 0 != ( v . cflags & Flags . REG_BOSONLY ) ) ) { /* at start of a REG_BOSONLY RE */ return retv ( Compiler . SBEGIN , ( char ) 0 ) ; /* same as \\A */ } /* if we're nested and we've hit end, return to outer level */ if ( v . savepattern != null && ateos ( ) ) { v . now = v . savenow ; v . stop = v . savestop ; v . savenow = - 1 ; v . savestop = - 1 ; v . pattern = v . savepattern ; v . savepattern = null ; // mark that it's not saved. } /* skip white space etc. if appropriate (not in literal or []) */ if ( 0 != ( v . cflags & Flags . REG_EXPANDED ) ) { switch ( v . lexcon ) { case L_ERE : case L_BRE : case L_EBND : case L_BBND : skip ( ) ; break ; } } /* handle EOS, depending on context */ if ( ateos ( ) ) { switch ( v . lexcon ) { case L_ERE : case L_BRE : case L_Q : return ret ( Compiler . EOS ) ; case L_EBND : case L_BBND : throw new RegexException ( \"Unbalanced braces.\" ) ; case L_BRACK : case L_CEL : case L_ECL : case L_CCL : throw new RegexException ( \"Unbalanced brackets.\" ) ; } assert false ; } /* okay, time to actually get a character */ c = charAtNowAdvance ( ) ; /* deal with the easy contexts, punt EREs to code below */ switch ( v . lexcon ) { case L_BRE : /* punt BREs to separate function */ return brenext ( c ) ; case L_ERE : /* see below */ break ; case L_Q : /* literal strings are easy */ return retv ( Compiler . PLAIN , c ) ; case L_BBND : /* bounds are fairly simple */ case L_EBND : switch ( c ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : return retv ( Compiler . DIGIT , digitval ( c ) ) ; case ' ' : return ret ( ' ' ) ; case ' ' : /* ERE bound ends with } */ if ( incon ( L_EBND ) ) { intocon ( L_ERE ) ; if ( 0 != ( v . cflags & Flags . REG_ADVF ) && next1 ( ' ' ) ) { v . now ++ ; note ( Flags . REG_UNONPOSIX ) ; return retv ( ' ' , 0 ) ; } return retv ( ' ' , 1 ) ; } else { throw new RegexException ( \"Errors.REG_BADBR\" ) ; } case ' ' : /* BRE bound ends with \\} */ if ( incon ( L_BBND ) && next1 ( ' ' ) ) { v . now ++ ; intocon ( L_BRE ) ; return ret ( ' ' ) ; } else { throw new RegexException ( \"Errors.REG_BADBR\" ) ; } default : throw new RegexException ( \"Errors.REG_BADBR\" ) ; } case L_BRACK : /* brackets are not too hard */ switch ( c ) { case ' ' : if ( lasttype ( ' ' ) ) { return retv ( Compiler . PLAIN , c ) ; } else { intocon ( 0 != ( v . cflags & Flags . REG_EXTENDED ) ? L_ERE : L_BRE ) ; return ret ( ' ' ) ; } case ' ' : note ( Flags . REG_UBBS ) ; if ( 0 == ( v . cflags & Flags . REG_ADVF ) ) { return retv ( Compiler . PLAIN , c ) ; } note ( Flags . REG_UNONPOSIX ) ; if ( ateos ( ) ) { throw new RegexException ( \"REG_EESCAPE\" ) ; } lexescape ( ) ; switch ( v . nexttype ) { /* not all escapes okay here */ case Compiler . PLAIN : return true ; case Compiler . CCLASS : switch ( v . nextvalue ) { case ' ' : lexnest ( brbackd ) ; break ; case ' ' : lexnest ( brbacks ) ; break ; case ' ' : lexnest ( brbackw ) ; break ; default : throw new RegexException ( \"Errors.REG_EESCAPE\" ) ; } /* lexnest done, back up and try again */ v . nexttype = v . lasttype ; return next ( ) ; } /* not one of the acceptable escapes */ throw new RegexException ( \"Errors.REG_EESCAPE\" ) ; case ' ' : if ( lasttype ( ' ' ) || next1 ( ' ' ) ) { return retv ( Compiler . PLAIN , c ) ; } else { return retv ( Compiler . RANGE , c ) ; } case ' ' : if ( ateos ( ) ) { throw new RegexException ( \"Errors.REG_EBRACK\" ) ; } switch ( charAtNowAdvance ( ) ) { case ' ' : intocon ( L_CEL ) ; /* might or might not be locale-specific */ return ret ( Compiler . COLLEL ) ; case ' ' : intocon ( L_ECL ) ; note ( Flags . REG_ULOCALE ) ; return ret ( Compiler . ECLASS ) ; case ' ' : intocon ( L_CCL ) ; note ( Flags . REG_ULOCALE ) ; return ret ( Compiler . CCLASS ) ; default : /* oops */ v . now -- ; return retv ( Compiler . PLAIN , c ) ; } default : return retv ( Compiler . PLAIN , c ) ; } case L_CEL : /* collating elements are easy */ if ( c == ' ' && next1 ( ' ' ) ) { v . now ++ ; intocon ( L_BRACK ) ; return retv ( Compiler . END , ' ' ) ; } else { return retv ( Compiler . PLAIN , c ) ; } case L_ECL : /* ditto equivalence classes */ if ( c == ' ' && next1 ( ' ' ) ) { v . now ++ ; intocon ( L_BRACK ) ; return retv ( Compiler . END , ' ' ) ; } else { return retv ( Compiler . PLAIN , c ) ; } case L_CCL : /* ditto character classes */ if ( c == ' ' && next1 ( ' ' ) ) { v . now ++ ; intocon ( L_BRACK ) ; return retv ( Compiler . END , ' ' ) ; } else { return retv ( Compiler . PLAIN , c ) ; } default : assert false ; break ; } /* that got rid of everything except EREs and AREs */ assert incon ( L_ERE ) ; /* deal with EREs and AREs, except for backslashes */ switch ( c ) { case ' ' : return ret ( ' ' ) ; case ' ' : if ( 0 != ( v . cflags & Flags . REG_ADVF ) && next1 ( ' ' ) ) { v . now ++ ; note ( Flags . REG_UNONPOSIX ) ; return retv ( ' ' , 0 ) ; } return retv ( ' ' , 1 ) ; case ' ' : if ( 0 != ( v . cflags & Flags . REG_ADVF ) && next1 ( ' ' ) ) { v . now ++ ; note ( Flags . REG_UNONPOSIX ) ; return retv ( ' ' , 0 ) ; } return retv ( ' ' , 1 ) ; case ' ' : if ( 0 != ( v . cflags & Flags . REG_ADVF ) && next1 ( ' ' ) ) { v . now ++ ; note ( Flags . REG_UNONPOSIX ) ; return retv ( ' ' , 0 ) ; } return retv ( ' ' , 1 ) ; case ' ' : /* bounds start or plain character */ if ( 0 != ( v . cflags & Flags . REG_EXPANDED ) ) { skip ( ) ; } if ( ateos ( ) || ! iscdigit ( charAtNow ( ) ) ) { note ( Flags . REG_UBRACES ) ; note ( Flags . REG_UUNSPEC ) ; return retv ( Compiler . PLAIN , c ) ; } else { note ( Flags . REG_UBOUNDS ) ; intocon ( L_EBND ) ; return ret ( ' ' ) ; } case ' ' : /* parenthesis, or advanced extension */ if ( 0 != ( v . cflags & Flags . REG_ADVF ) && next1 ( ' ' ) ) { note ( Flags . REG_UNONPOSIX ) ; v . now ++ ; char flagChar = charAtNowAdvance ( ) ; switch ( flagChar ) { case ' ' : /* non-capturing paren */ return retv ( ' ' , 0 ) ; case ' ' : /* comment */ while ( ! ateos ( ) && charAtNow ( ) != ' ' ) { v . now ++ ; } if ( ! ateos ( ) ) { v . now ++ ; } assert v . nexttype == v . lasttype ; return next ( ) ; case ' ' : /* positive lookahead */ note ( Flags . REG_ULOOKAHEAD ) ; return retv ( Compiler . LACON , 1 ) ; case ' ' : /* negative lookahead */ note ( Flags . REG_ULOOKAHEAD ) ; return retv ( Compiler . LACON , 0 ) ; default : throw new RegexException ( String . format ( \"Invalid flag after '(?': %c\" , flagChar ) ) ; } } if ( 0 != ( v . cflags & Flags . REG_NOSUB ) || 0 != ( v . cflags & Flags . REG_NOCAPT ) ) { return retv ( ' ' , 0 ) ; /* all parens non-capturing */ } else { return retv ( ' ' , 1 ) ; } case ' ' : if ( lasttype ( ' ' ) ) { note ( Flags . REG_UUNSPEC ) ; } return retv ( ' ' , c ) ; case ' ' : /* easy except for [[:<:]] and [[:>:]] */ if ( have ( 6 ) && charAtNow ( ) == ' ' && charAtNowPlus ( 1 ) == ' ' && ( charAtNowPlus ( 2 ) == ' ' || charAtNowPlus ( 2 ) == ' ' ) && charAtNowPlus ( 3 ) == ' ' && charAtNowPlus ( 4 ) == ' ' && charAtNowPlus ( 5 ) == ' ' ) { c = charAtNowPlus ( 2 ) ; v . now += 6 ; note ( Flags . REG_UNONPOSIX ) ; return ret ( ( c == ' ' ) ? ' ' : ' ' ) ; } intocon ( L_BRACK ) ; if ( next1 ( ' ' ) ) { v . now ++ ; return retv ( ' ' , 0 ) ; } return retv ( ' ' , 1 ) ; case ' ' : return ret ( ' ' ) ; case ' ' : return ret ( ' ' ) ; case ' ' : return ret ( ' ' ) ; case ' ' : /* mostly punt backslashes to code below */ if ( ateos ( ) ) { throw new RegexException ( \"REG_EESCAPE\" ) ; } break ; default : /* ordinary character */ return retv ( Compiler . PLAIN , c ) ; } /* ERE/ARE backslash handling; backslash already eaten */ assert ! ateos ( ) ; if ( 0 == ( v . cflags & Flags . REG_ADVF ) ) { /* only AREs have non-trivial escapes */ if ( iscalnum ( charAtNow ( ) ) ) { note ( Flags . REG_UBSALNUM ) ; note ( Flags . REG_UUNSPEC ) ; } return retv ( Compiler . PLAIN , charAtNowAdvance ( ) ) ; } lexescape ( ) ; if ( v . nexttype == Compiler . CCLASS ) { /* fudge at lexical level */ switch ( v . nextvalue ) { case ' ' : lexnest ( backd ) ; break ; case ' ' : lexnest ( backD ) ; break ; case ' ' : lexnest ( backs ) ; break ; case ' ' : lexnest ( backS ) ; break ; case ' ' : lexnest ( backw ) ; break ; case ' ' : lexnest ( backW ) ; break ; default : throw new RuntimeException ( \"Invalid escape \" + Character . toString ( ( char ) v . nextvalue ) ) ; } /* lexnest done, back up and try again */ v . nexttype = v . lasttype ; return next ( ) ; } /* otherwise, lexescape has already done the work */ return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "brenext - get next BRE token This is much like EREs except for all the stupid backslashes and the [CODESPLIT] boolean brenext ( char pc ) throws RegexException { char c = pc ; switch ( c ) { case ' ' : if ( lasttype ( Compiler . EMPTY ) || lasttype ( ' ' ) || lasttype ( ' ' ) ) { return retv ( Compiler . PLAIN , c ) ; } return ret ( ' ' ) ; case ' ' : //CHECKSTYLE:OFF if ( have ( 6 ) && charAtNow ( ) == ' ' && charAtNowPlus ( 1 ) == ' ' && ( charAtNowPlus ( 2 ) == ' ' || charAtNowPlus ( 2 ) == ' ' ) && charAtNowPlus ( 3 ) == ' ' && charAtNowPlus ( 4 ) == ' ' && charAtNowPlus ( 5 ) == ' ' ) { c = charAtNowPlus ( 2 ) ; v . now += 6 ; note ( Flags . REG_UNONPOSIX ) ; return ret ( ( c == ' ' ) ? ' ' : ' ' ) ; //CHECKSTYLE:ON } intocon ( L_BRACK ) ; if ( next1 ( ' ' ) ) { v . now ++ ; return retv ( ' ' , 0 ) ; } return retv ( ' ' , 1 ) ; case ' ' : return ret ( ' ' ) ; case ' ' : if ( lasttype ( Compiler . EMPTY ) ) { return ret ( ' ' ) ; } if ( lasttype ( ' ' ) ) { note ( Flags . REG_UUNSPEC ) ; return ret ( ' ' ) ; } return retv ( Compiler . PLAIN , c ) ; case ' ' : if ( 0 != ( v . cflags & Flags . REG_EXPANDED ) ) { skip ( ) ; } if ( ateos ( ) ) { return ret ( ' ' ) ; } if ( next2 ( ' ' , ' ' ) ) { note ( Flags . REG_UUNSPEC ) ; return ret ( ' ' ) ; } return retv ( Compiler . PLAIN , c ) ; case ' ' : break ; /* see below */ default : return retv ( Compiler . PLAIN , c ) ; } assert c == ' ' ; if ( ateos ( ) ) { throw new RegexException ( \"REG_EESCAPE\" ) ; } c = charAtNowAdvance ( ) ; switch ( c ) { case ' ' : intocon ( L_BBND ) ; note ( Flags . REG_UBOUNDS ) ; return ret ( ' ' ) ; case ' ' : return retv ( ' ' , 1 ) ; case ' ' : return retv ( ' ' , c ) ; case ' ' : note ( Flags . REG_UNONPOSIX ) ; return ret ( ' ' ) ; case ' ' : note ( Flags . REG_UNONPOSIX ) ; return ret ( ' ' ) ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : note ( Flags . REG_UBACKREF ) ; return retv ( Compiler . BACKREF , digitval ( c ) ) ; default : if ( iscalnum ( c ) ) { note ( Flags . REG_UBSALNUM ) ; note ( Flags . REG_UUNSPEC ) ; } return retv ( Compiler . PLAIN , c ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CHECKSTYLE : OFF [CODESPLIT] boolean lexescape ( ) throws RegexException { int c ; int save ; assert 0 != ( v . cflags & Flags . REG_ADVF ) ; assert ! ateos ( ) ; c = charAtNowAdvance ( ) ; if ( ! iscalnum ( ( char ) c ) ) { return retv ( Compiler . PLAIN , c ) ; } note ( Flags . REG_UNONPOSIX ) ; switch ( c ) { case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : return retv ( Compiler . SBEGIN , 0 ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : if ( ateos ( ) ) { throw new RegexException ( \"Incomplete \\\\c escape.\" ) ; } return retv ( Compiler . PLAIN , ( char ) ( charAtNowAdvance ( ) & 037 ) ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . CCLASS , ' ' ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . CCLASS , ' ' ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : return ret ( ' ' ) ; case ' ' : return ret ( ' ' ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . CCLASS , ' ' ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . CCLASS , ' ' ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : c = lexdigits ( 16 , 4 , 4 ) ; return retv ( Compiler . PLAIN , c ) ; case ' ' : c = lexdigits ( 16 , 8 , 8 ) ; // This escape is for UTF-32 characters. There are, ahem, certain requirements. if ( c > Character . MAX_CODE_POINT ) { throw new RegexException ( \"Invalid UTF-32 escape.\" ) ; } return retv ( Compiler . PLAIN , c ) ; case ' ' : return retv ( Compiler . PLAIN , ' ' ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . CCLASS , ' ' ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . CCLASS , ' ' ) ; case ' ' : c = lexdigits ( 16 , 1 , 255 ) ; /* REs >255 long outside spec */ return retv ( Compiler . PLAIN , c ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . WBDRY , 0 ) ; case ' ' : note ( Flags . REG_ULOCALE ) ; return retv ( Compiler . NWBDRY , 0 ) ; case ' ' : return retv ( Compiler . SEND , 0 ) ; case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : save = v . now ; v . now -- ; /* put first digit back */ c = lexdigits ( 10 , 1 , 255 ) ; /* REs >255 long outside spec */ /* ugly heuristic (first test is \"exactly 1 digit?\") */ if ( v . now - save == 0 || c <= v . getSubs ( ) . size ( ) ) { note ( Flags . REG_UBACKREF ) ; return retv ( Compiler . BACKREF , ( char ) c ) ; } /* oops, doesn't look like it's a backref after all... */ v . now = save ; /* and fall through into octal number */ case ' ' : v . now -- ; /* put first digit back */ c = lexdigits ( 8 , 1 , 3 ) ; return retv ( Compiler . PLAIN , c ) ; default : throw new RegexException ( \"Invalid escape\" ) ; // unknown escape. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * chr value ; errors signalled via ERR [CODESPLIT] private int lexdigits ( int base , int minlen , int maxlen ) throws RegexException { int n ; /* unsigned to avoid overflow misbehavior */ int len ; int c ; int d ; final char ub = ( char ) base ; n = 0 ; for ( len = 0 ; len < maxlen && ! ateos ( ) ; len ++ ) { c = charAtNowAdvance ( ) ; switch ( c ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : d = digitval ( ( char ) c ) ; break ; case ' ' : case ' ' : d = 10 ; break ; case ' ' : case ' ' : d = 11 ; break ; case ' ' : case ' ' : d = 12 ; break ; case ' ' : case ' ' : d = 13 ; break ; case ' ' : case ' ' : d = 14 ; break ; case ' ' : case ' ' : d = 15 ; break ; default : v . now -- ; /* oops, not a digit at all */ d = - 1 ; break ; } if ( d >= base ) { /* not a plausible digit */ v . now -- ; d = - 1 ; } if ( d < 0 ) { break ; /* NOTE BREAK OUT */ } n = n * ub + d ; } if ( len < minlen ) { throw new RegexException ( \"Not enough digits.\" ) ; } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the color for a full codepoint . [CODESPLIT] short getcolor ( int codepoint ) { try { return fullMap . get ( codepoint ) ; } catch ( NullPointerException npe ) { throw new RuntimeException ( String . format ( \" CP %08x no mapping\" , codepoint ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called at the start of a match . arguably we could just construct a new DFA each time . [CODESPLIT] StateSet initialize ( int start ) { // Discard state sets; reuse would be faster if we kept them, // but then we'd need the real cache. stateSets . clear ( ) ; StateSet stateSet = new StateSet ( nstates , ncolors ) ; stateSet . states . set ( cnfa . pre ) ; stateSet . noprogress = true ; // Insert into hash table based on that one state. stateSets . put ( stateSet . states , stateSet ) ; stateSet . setLastSeen ( start ) ; return stateSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "miss -- the state set was not found in the stateSets . [CODESPLIT] StateSet miss ( StateSet css , short co , int cp ) { if ( css . outs [ co ] != null ) { return css . outs [ co ] ; } /* first, what set of states would we end up in? */ BitSet work = new BitSet ( nstates ) ; boolean ispost = false ; boolean noprogress = true ; boolean gotstate = false ; for ( int i = 0 ; i < nstates ; i ++ ) { if ( css . states . get ( i ) ) { long ca ; int ax ; short caco ; int catarget ; for ( ax = cnfa . states [ i ] + 1 , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ; caco != Constants . COLORLESS ; ax ++ , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ) { if ( caco == co ) { work . set ( catarget ) ; gotstate = true ; if ( catarget == cnfa . post ) { ispost = true ; } // get target state, index arcs, get color, compare to 0. if ( 0 == Cnfa . carcColor ( cnfa . arcs [ cnfa . states [ catarget ] ] ) ) { noprogress = false ; } } } } } boolean dolacons = gotstate && cnfa . hasLacons ; boolean sawlacons = false ; while ( dolacons ) { /* transitive closure */ dolacons = false ; for ( int i = 0 ; i < nstates ; i ++ ) { if ( work . get ( i ) ) { long ca ; int ax ; short caco ; int catarget ; for ( ax = cnfa . states [ i ] + 1 , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ; caco != Constants . COLORLESS ; ax ++ , ca = cnfa . arcs [ ax ] , caco = Cnfa . carcColor ( ca ) , catarget = Cnfa . carcTarget ( ca ) ) { if ( caco <= ncolors ) { continue ; /* NOTE CONTINUE */ } sawlacons = true ; if ( work . get ( catarget ) ) { continue ; /* NOTE CONTINUE */ } if ( ! lacon ( cp , caco ) ) { continue ; /* NOTE CONTINUE */ } work . set ( catarget ) ; dolacons = true ; if ( catarget == cnfa . post ) { ispost = true ; } if ( 0 == Cnfa . carcColor ( cnfa . arcs [ cnfa . states [ catarget ] ] ) ) { noprogress = false ; } } } } } if ( ! gotstate ) { return null ; } StateSet stateSet = stateSets . get ( work ) ; if ( stateSet == null ) { stateSet = new StateSet ( work , ncolors ) ; stateSet . ins = new Arcp ( null , Constants . WHITE ) ; stateSet . poststate = ispost ; stateSet . noprogress |= noprogress ; /* lastseen to be dealt with by caller */ stateSets . put ( work , stateSet ) ; } if ( ! sawlacons ) { css . outs [ co ] = stateSet ; css . inchain [ co ] = stateSet . ins ; stateSet . ins = new Arcp ( css , co ) ; } return stateSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "longest - longest - preferred matching engine [CODESPLIT] int longest ( int start , int stop , boolean [ ] hitstop ) { int cp ; int realstop = ( stop == runtime . dataLength ) ? stop : stop + 1 ; short co ; StateSet css ; int post ; /* initialize */ css = initialize ( start ) ; cp = start ; if ( hitstop != null ) { hitstop [ 0 ] = false ; } /* startup */ if ( cp == 0 ) { co = cnfa . bos [ 0 != ( runtime . eflags & Flags . REG_NOTBOL ) ? 0 : 1 ] ; } else { char theChar = runtime . data . charAt ( cp - 1 ) ; if ( Character . isLowSurrogate ( theChar ) ) { // collect the other end of the surrogate. theChar = runtime . data . charAt ( cp - 2 ) ; char high = theChar ; int codepoint = Character . toCodePoint ( high , theChar ) ; co = cm . getcolor ( codepoint ) ; // and get a color for the pair. } else { co = cm . getcolor ( theChar ) ; } } css = miss ( css , co , cp ) ; if ( css == null ) { return - 1 ; } css . setLastSeen ( cp ) ; StateSet ss ; /* main loop */ while ( cp < realstop ) { char theChar = runtime . data . charAt ( cp ) ; int increment = 1 ; if ( Character . isHighSurrogate ( theChar ) ) { int codepoint = Character . toCodePoint ( theChar , runtime . data . charAt ( cp + 1 ) ) ; co = cm . getcolor ( codepoint ) ; increment = 2 ; } else { co = cm . getcolor ( theChar ) ; } ss = css . outs [ co ] ; if ( ss == null ) { ss = miss ( css , co , cp + increment ) ; if ( ss == null ) { break ; /* NOTE BREAK OUT */ } } cp = cp + increment ; ss . setLastSeen ( cp ) ; css = ss ; } /* shutdown */ if ( cp == runtime . dataLength && stop == runtime . dataLength ) { if ( hitstop != null ) { hitstop [ 0 ] = true ; } co = cnfa . eos [ 0 != ( runtime . eflags & Flags . REG_NOTEOL ) ? 0 : 1 ] ; ss = miss ( css , co , cp ) ; /* special case:  match ended at eol? */ if ( ss != null && ss . poststate ) { return cp ; } else if ( ss != null ) { ss . setLastSeen ( cp ) ; /* to be tidy */ } } /* find last match, if any */ post = - 1 ; for ( StateSet thisSS : stateSets . values ( ) ) { //.object2ObjectEntrySet()) { if ( thisSS . poststate && post != thisSS . getLastSeen ( ) && ( post == - 1 || post < thisSS . getLastSeen ( ) ) ) { post = thisSS . getLastSeen ( ) ; } } if ( post != - 1 ) { /* found one */ /* Post points after the codepoint after the last one in the match (!) */ /* So, if that is an SMP codepoint, we need to back up 2 to get to the beginning of it,\n             * and thus be just after the last character of the match. */ char postChar = runtime . data . charAt ( post - 1 ) ; if ( Character . isLowSurrogate ( postChar ) ) { return post - 2 ; } else { return post - 1 ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "lastcold - determine last point at which no progress had been made [CODESPLIT] int lastcold ( ) { int nopr = 0 ; for ( StateSet ss : stateSets . values ( ) ) { if ( ss . noprogress && nopr < ss . getLastSeen ( ) ) { nopr = ss . getLastSeen ( ) ; } } return nopr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eclass - Because we have no MCCE support this just processing single characters . [CODESPLIT] static UnicodeSet eclass ( char c , boolean cases ) { /* otherwise, none */ if ( cases ) { return allcases ( c ) ; } else { UnicodeSet set = new UnicodeSet ( ) ; set . add ( c ) ; return set ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "allcases - supply cvec for all case counterparts of a chr ( including itself ) This is a shortcut preferably an efficient one for simple characters ; messy cases are done via range () . [CODESPLIT] static UnicodeSet allcases ( int c ) { UnicodeSet set = new UnicodeSet ( ) ; set . add ( c ) ; set . closeOver ( UnicodeSet . ADD_CASE_MAPPINGS ) ; return set ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a UnicodeSet for a character class name . It appears that the names that TCL accepts are also acceptable to ICU . [CODESPLIT] public static UnicodeSet cclass ( String cclassName , boolean casefold ) throws RegexException { try { if ( casefold ) { return KNOWN_SETS_CI . get ( cclassName ) ; } else { return KNOWN_SETS_CS . get ( cclassName ) ; } } catch ( ExecutionException e ) { Throwables . propagateIfInstanceOf ( e . getCause ( ) , RegexException . class ) ; throw new RegexRuntimeException ( e . getCause ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "carcsort - sort compacted - NFA arcs by color Really dumb algorithm but if the list is long enough for that to matter you re in real trouble anyway . [CODESPLIT] void carcsort ( int first , int last ) { int p ; int q ; long tmp ; if ( last - first <= 1 ) { return ; } for ( p = first ; p <= last ; p ++ ) { for ( q = p ; q <= last ; q ++ ) { short pco = Cnfa . carcColor ( arcs [ p ] ) ; short qco = Cnfa . carcColor ( arcs [ q ] ) ; int pto = Cnfa . carcTarget ( arcs [ p ] ) ; int qto = Cnfa . carcTarget ( arcs [ q ] ) ; if ( pco > qco || ( pco == qco && pto > qto ) ) { assert p != q ; tmp = arcs [ p ] ; arcs [ p ] = arcs [ q ] ; arcs [ q ] = tmp ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumpst - dump a subRE tree [CODESPLIT] String dumpst ( boolean nfapresent ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( \"%s. `%c'\" , shortId ( ) , op ) ) ; if ( 0 != ( flags & LONGER ) ) { sb . append ( \" longest\" ) ; } if ( 0 != ( flags & SHORTER ) ) { sb . append ( \" shortest\" ) ; } if ( 0 != ( flags & MIXED ) ) { sb . append ( \" hasmixed\" ) ; } if ( 0 != ( flags & CAP ) ) { sb . append ( \" hascapture\" ) ; } if ( 0 != ( flags & BACKR ) ) { sb . append ( \" hasbackref\" ) ; } if ( 0 == ( flags & INUSE ) ) { sb . append ( \" UNUSED\" ) ; } if ( subno != 0 ) { sb . append ( String . format ( \" (#%d)\" , subno ) ) ; } if ( min != 1 || max != 1 ) { sb . append ( String . format ( \" {%d,\" , min ) ) ; if ( max != Compiler . INFINITY ) { sb . append ( String . format ( \"%d\" , max ) ) ; } sb . append ( \"}\" ) ; } if ( nfapresent ) { sb . append ( String . format ( \" %d-%d\" , begin . no , end . no ) ) ; } if ( left != null ) { sb . append ( String . format ( \" L:%s\" , left . toString ( ) ) ) ; } if ( right != null ) { sb . append ( String . format ( \" R:%s\" , right . toString ( ) ) ) ; } sb . append ( \"\\n\" ) ; if ( left != null ) { left . dumpst ( nfapresent ) ; } if ( right != null ) { right . dumpst ( nfapresent ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Called by all the resetting functions . Allows find to work as specified . [CODESPLIT] private void resetState ( ) { // if there are any matches sitting in the runtime, eliminate. if ( runtime != null && runtime . match != null ) { runtime . match . clear ( ) ; } nextFindOffset = regionStart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for new states . [CODESPLIT] State newstate ( int flag ) { State newState = new State ( ) ; newState . no = nstates ++ ; // a unique number. if ( states == null ) { states = newState ; } if ( slast != null ) { assert slast . next == null ; slast . next = newState ; } newState . prev = slast ; slast = newState ; newState . flag = flag ; return newState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "moveouts - move all out arcs of a state to another state [CODESPLIT] void moveouts ( State old , State newState ) { Arc a ; assert old != newState ; while ( ( a = old . outs ) != null ) { cparc ( a , newState , a . to ) ; freearc ( a ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "moveins - move all in arcs of a state to another state You might think this could be done better by just updating the existing arcs and you would be right if it weren t for the desire for duplicate suppression which makes it easier to just make new ones to exploit the suppression built into newarc . [CODESPLIT] void moveins ( State old , State newState ) { Arc a ; assert old != newState ; while ( ( a = old . ins ) != null ) { cparc ( a , a . from , newState ) ; freearc ( a ) ; } assert old . nins == 0 ; assert old . ins == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copyins - copy all in arcs of a state to another state [CODESPLIT] void copyins ( State old , State newState ) { Arc a ; assert old != newState ; for ( a = old . ins ; a != null ; a = a . inchain ) { cparc ( a , a . from , newState ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copyouts - copy all out arcs of a state to another state [CODESPLIT] void copyouts ( State old , State newState ) { Arc a ; assert old != newState ; for ( a = old . outs ; a != null ; a = a . outchain ) { cparc ( a , newState , a . to ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get rid of a state releasing all its arcs . I m not sure that all this is needed as opposed to depending on the GC . [CODESPLIT] void dropstate ( State s ) { Arc a ; while ( ( a = s . ins ) != null ) { freearc ( a ) ; } while ( ( a = s . outs ) != null ) { freearc ( a ) ; } freestate ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unwire a state from the NFA . [CODESPLIT] void freestate ( State s ) { assert s != null ; assert s . nins == 0 ; assert s . nouts == 0 ; if ( s . next != null ) { s . next . prev = s . prev ; } else { assert s == slast ; slast = s . prev ; } if ( s . prev != null ) { s . prev . next = s . next ; } else { assert s == states ; states = s . next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cparc - allocate a new arc within an NFA copying details from old one [CODESPLIT] void cparc ( Arc oa , State from , State to ) { newarc ( oa . type , oa . co , from , to ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dupnfa - duplicate sub - NFA Another recursive traversal this time using tmp to point to duplicates as well as mark already - seen states . ( You knew there was a reason why it s a state pointer didn t you? : - )) [CODESPLIT] void dupnfa ( State start , State stop , State from , State to ) { if ( start == stop ) { newarc ( Compiler . EMPTY , ( short ) 0 , from , to ) ; return ; } stop . tmp = to ; duptraverse ( start , from ) ; /* done, except for clearing out the tmp pointers */ stop . tmp = null ; cleartraverse ( start ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "duptraverse - recursive heart of dupnfa [CODESPLIT] void duptraverse ( State s , State stmp ) { Arc a ; if ( s . tmp != null ) { return ; /* already done */ } s . tmp = ( stmp == null ) ? newstate ( ) : stmp ; if ( s . tmp == null ) { return ; } for ( a = s . outs ; a != null ; a = a . outchain ) { duptraverse ( a . to , null ) ; assert a . to . tmp != null ; cparc ( a , s . tmp , a . to . tmp ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * - cleartraverse - recursive cleanup for algorithms that leave tmp ptrs set [CODESPLIT] void cleartraverse ( State s ) { Arc a ; if ( s . tmp == null ) { return ; } s . tmp = null ; for ( a = s . outs ; a != null ; a = a . outchain ) { cleartraverse ( a . to ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "specialcolors - fill in special colors for an NFA [CODESPLIT] void specialcolors ( ) { /* false colors for BOS, BOL, EOS, EOL */ if ( parent == null ) { bos [ 0 ] = cm . pseudocolor ( ) ; bos [ 1 ] = cm . pseudocolor ( ) ; eos [ 0 ] = cm . pseudocolor ( ) ; eos [ 1 ] = cm . pseudocolor ( ) ; } else { assert parent . bos [ 0 ] != Constants . COLORLESS ; bos [ 0 ] = parent . bos [ 0 ] ; assert parent . bos [ 1 ] != Constants . COLORLESS ; bos [ 1 ] = parent . bos [ 1 ] ; assert parent . eos [ 0 ] != Constants . COLORLESS ; eos [ 0 ] = parent . eos [ 0 ] ; assert parent . eos [ 1 ] != Constants . COLORLESS ; eos [ 1 ] = parent . eos [ 1 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumpnfa - dump an NFA in human - readable form [CODESPLIT] void dumpnfa ( ) { if ( ! LOG . isDebugEnabled ( ) || ! IS_DEBUG ) { return ; } LOG . debug ( \"dump nfa\" ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( \"pre %d, post %d init %d final %d\" , pre . no , post . no , init . no , finalState . no ) ) ; if ( bos [ 0 ] != Constants . COLORLESS ) { sb . append ( String . format ( \", bos [%d]\" , bos [ 0 ] ) ) ; } if ( bos [ 1 ] != Constants . COLORLESS ) { sb . append ( String . format ( \", bol [%d]\" , bos [ 1 ] ) ) ; } if ( eos [ 0 ] != Constants . COLORLESS ) { sb . append ( String . format ( \", eos [%d]\" , eos [ 0 ] ) ) ; } if ( eos [ 1 ] != Constants . COLORLESS ) { sb . append ( String . format ( \", eol [%d]\" , eos [ 1 ] ) ) ; } LOG . debug ( sb . toString ( ) ) ; for ( State s = states ; s != null ; s = s . next ) { dumpstate ( s ) ; } if ( parent == null ) { cm . dumpcolors ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumpstate - dump an NFA state in human - readable form [CODESPLIT] void dumpstate ( State s ) { Arc a ; if ( ! LOG . isDebugEnabled ( ) || ! IS_DEBUG ) { return ; } StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( \"State %d%s%c\" , s . no , ( s . tmp != null ) ? \"T\" : \"\" , ( s . flag != 0 ) ? ( char ) s . flag : ' ' ) ) ; if ( s . prev != null && s . prev . next != s ) { sb . append ( String . format ( \"\\tstate chain bad\" ) ) ; } if ( s . nouts == 0 ) { sb . append ( \"\\tno out arcs\" ) ; } else { dumparcs ( s , sb ) ; } LOG . debug ( sb . toString ( ) ) ; for ( a = s . ins ; a != null ; a = a . inchain ) { if ( a . to != s ) { LOG . debug ( String . format ( \"\\tlink from %d to %d on %d's in-chain\" , a . from . no , a . to . no , s . no ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumparcs - dump out - arcs in human - readable form [CODESPLIT] void dumparcs ( State s , StringBuilder sb ) { int pos ; assert s . nouts > 0 ; /* printing arcs in reverse order is usually clearer */ pos = dumprarcs ( s . outs , s , 1 , sb ) ; if ( pos != 1 ) { //sb.append(\"\\n\"); } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumprarcs - dump remaining outarcs recursively in reverse order [CODESPLIT] int dumprarcs ( Arc a , State s , int pos , StringBuilder sb ) { if ( a . outchain != null ) { pos = dumprarcs ( a . outchain , s , pos , sb ) ; } dumparc ( a , s , sb ) ; if ( pos == 5 ) { sb . append ( \"\\n\" ) ; pos = 1 ; } else { pos ++ ; } return pos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "dumparc - dump one outarc in readable form including prefixing tab [CODESPLIT] void dumparc ( Arc a , State s , StringBuilder sb ) { sb . append ( \"\\t\" ) ; switch ( a . type ) { case Compiler . PLAIN : sb . append ( String . format ( \"[%d]\" , a . co ) ) ; break ; case Compiler . AHEAD : sb . append ( String . format ( \">%d>\" , a . co ) ) ; break ; case Compiler . BEHIND : sb . append ( String . format ( \"<%d<\" , a . co ) ) ; break ; case Compiler . LACON : sb . append ( String . format ( \":%d:\" , a . co ) ) ; break ; case ' ' : case ' ' : sb . append ( String . format ( \"%c%d\" , ( char ) a . type , a . co ) ) ; break ; case Compiler . EMPTY : break ; default : sb . append ( String . format ( \"0x%x/0%d\" , a . type , a . co ) ) ; break ; } if ( a . from != s ) { sb . append ( String . format ( \"?%d?\" , a . from . no ) ) ; } sb . append ( \"->\" ) ; if ( a . to == null ) { sb . append ( \"null\" ) ; Arc aa ; for ( aa = a . to . ins ; aa != null ; aa = aa . inchain ) { if ( aa == a ) { break ; /* NOTE BREAK OUT */ } } if ( aa == null ) { LOG . debug ( \"?!?\" ) ; /* missing from in-chain */ } } else { sb . append ( String . format ( \"%d\" , a . to . no ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "optimize - optimize an NFA [CODESPLIT] long optimize ( ) throws RegexException { LOG . debug ( \"initial cleanup\" ) ; cleanup ( ) ; /* may simplify situation */ dumpnfa ( ) ; LOG . debug ( \"empties\" ) ; fixempties ( ) ; /* get rid of EMPTY arcs */ LOG . debug ( \"constraints\" ) ; pullback ( ) ; /* pull back constraints backward */ pushfwd ( ) ; /* push fwd constraints forward */ LOG . debug ( \"final cleanup\" ) ; cleanup ( ) ; /* final tidying */ return analyze ( ) ; /* and analysis */ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "analyze - ascertain potentially - useful facts about an optimized NFA [CODESPLIT] long analyze ( ) { Arc a ; Arc aa ; if ( pre . outs == null ) { return Flags . REG_UIMPOSSIBLE ; } for ( a = pre . outs ; a != null ; a = a . outchain ) { for ( aa = a . to . outs ; aa != null ; aa = aa . outchain ) { if ( aa . to == post ) { return Flags . REG_UEMPTYMATCH ; } } } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pullback - pull back constraints backward to ( with luck ) eliminate them [CODESPLIT] void pullback ( ) throws RegexException { State s ; State nexts ; Arc a ; Arc nexta ; boolean progress ; /* find and pull until there are no more */ do { progress = false ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; for ( a = s . outs ; a != null ; a = nexta ) { nexta = a . outchain ; if ( a . type == ' ' || a . type == Compiler . BEHIND ) { if ( pull ( a ) ) { progress = true ; } } assert nexta == null || s . no != State . FREESTATE ; } } if ( progress ) { dumpnfa ( ) ; } } while ( progress ) ; for ( a = pre . outs ; a != null ; a = nexta ) { nexta = a . outchain ; if ( a . type == ' ' ) { assert a . co == 0 || a . co == 1 ; newarc ( Compiler . PLAIN , bos [ a . co ] , a . from , a . to ) ; freearc ( a ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- pull - pull a back constraint backward past its source state A significant property of this function is that it deletes at most one state -- the constraint s from state -- and only if the constraint was that state s last outarc . [CODESPLIT] boolean pull ( Arc con ) throws RegexException { State from = con . from ; State to = con . to ; Arc a ; Arc nexta ; State s ; if ( from == to ) { /* circular constraint is pointless */ freearc ( con ) ; return true ; } if ( 0 != from . flag ) { /* can't pull back beyond start */ return false ; } if ( from . nins == 0 ) { /* unreachable */ freearc ( con ) ; return true ; } /* first, clone from state if necessary to avoid other outarcs */ if ( from . nouts > 1 ) { s = newstate ( ) ; assert to != from ; /* con is not an inarc */ copyins ( from , s ) ; /* duplicate inarcs */ cparc ( con , s , to ) ; /* move constraint arc */ freearc ( con ) ; from = s ; con = from . outs ; } assert from . nouts == 1 ; /* propagate the constraint into the from state's inarcs */ for ( a = from . ins ; a != null ; a = nexta ) { nexta = a . inchain ; switch ( combine ( con , a ) ) { case INCOMPATIBLE : /* destroy the arc */ freearc ( a ) ; break ; case SATISFIED : /* no action needed */ break ; case COMPATIBLE : /* swap the two arcs, more or less */ s = newstate ( ) ; cparc ( a , s , to ) ; /* anticipate move */ cparc ( con , a . from , s ) ; freearc ( a ) ; break ; default : throw new RegexException ( \"REG_ASSERT\" ) ; } } /* remaining inarcs, if any, incorporate the constraint */ moveins ( from , to ) ; dropstate ( from ) ; /* will free the constraint */ return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pushfwd - push forward constraints forward to ( with luck ) eliminate them [CODESPLIT] void pushfwd ( ) throws RegexException { State s ; State nexts ; Arc a ; Arc nexta ; boolean progress ; /* find and push until there are no more */ do { progress = false ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; for ( a = s . ins ; a != null ; a = nexta ) { nexta = a . inchain ; if ( a . type == ' ' || a . type == Compiler . AHEAD ) { if ( push ( a ) ) { progress = true ; } } assert nexta == null || s . no != State . FREESTATE ; } } if ( progress ) { dumpnfa ( ) ; } } while ( progress ) ; for ( a = post . ins ; a != null ; a = nexta ) { nexta = a . inchain ; if ( a . type == ' ' ) { assert a . co == 0 || a . co == 1 ; newarc ( Compiler . PLAIN , eos [ a . co ] , a . from , a . to ) ; freearc ( a ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "push - push a forward constraint forward past its destination state A significant property of this function is that it deletes at most one state -- the constraint s to state -- and only if the constraint was that state s last inarc . [CODESPLIT] boolean push ( Arc con ) throws RegexException { State from = con . from ; State to = con . to ; Arc a ; Arc nexta ; State s ; if ( to == from ) { /* circular constraint is pointless */ freearc ( con ) ; return true ; } if ( 0 != to . flag ) { /* can't push forward beyond end */ return false ; } if ( to . nouts == 0 ) { /* dead end */ freearc ( con ) ; return true ; } /* first, clone to state if necessary to avoid other inarcs */ if ( to . nins > 1 ) { s = newstate ( ) ; copyouts ( to , s ) ; /* duplicate outarcs */ cparc ( con , from , s ) ; /* move constraint */ freearc ( con ) ; to = s ; con = to . ins ; } assert to . nins == 1 ; /* propagate the constraint into the to state's outarcs */ for ( a = to . outs ; a != null ; a = nexta ) { nexta = a . outchain ; switch ( combine ( con , a ) ) { case INCOMPATIBLE : /* destroy the arc */ freearc ( a ) ; break ; case SATISFIED : /* no action needed */ break ; case COMPATIBLE : /* swap the two arcs, more or less */ s = newstate ( ) ; cparc ( con , s , a . to ) ; /* anticipate move */ cparc ( a , from , s ) ; freearc ( a ) ; break ; default : throw new RegexException ( \"REG_ASSERT\" ) ; } } /* remaining outarcs, if any, incorporate the constraint */ moveouts ( to , from ) ; dropstate ( to ) ; /* will free the constraint */ return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "combine - constraint lands on an arc what happens? [CODESPLIT] int combine ( Arc con , Arc a ) throws RegexException { //# define  CA(ct,at)   (((ct)<<CHAR_BIT) | (at)) //CA(con->type, a->type)) { switch ( ( con . type << 8 ) | a . type ) { case ' ' << 8 | Compiler . PLAIN : /* newlines are handled separately */ case ' ' << 8 | Compiler . PLAIN : return INCOMPATIBLE ; case Compiler . AHEAD << 8 | Compiler . PLAIN : /* color constraints meet colors */ case Compiler . BEHIND << 8 | Compiler . PLAIN : if ( con . co == a . co ) { return SATISFIED ; } return INCOMPATIBLE ; case ' ' << 8 | ' ' : /* collision, similar constraints */ case ' ' << 8 | ' ' : case Compiler . AHEAD << 8 | Compiler . AHEAD : case Compiler . BEHIND << 8 | Compiler . BEHIND : if ( con . co == a . co ) { /* true duplication */ return SATISFIED ; } return INCOMPATIBLE ; case ' ' << 8 | Compiler . BEHIND : /* collision, dissimilar constraints */ case Compiler . BEHIND << 8 | ' ' : case ' ' << 8 | Compiler . AHEAD : case Compiler . AHEAD << 8 | ' ' : return INCOMPATIBLE ; case ' ' << 8 | Compiler . AHEAD : case Compiler . BEHIND << 8 | ' ' : case Compiler . BEHIND << 8 | Compiler . AHEAD : case ' ' << 8 | ' ' : case ' ' << 8 | Compiler . BEHIND : case Compiler . AHEAD << 8 | ' ' : case Compiler . AHEAD << 8 | Compiler . BEHIND : case ' ' << 8 | Compiler . LACON : case Compiler . BEHIND << 8 | Compiler . LACON : case ' ' << 8 | Compiler . LACON : case Compiler . AHEAD << 8 | Compiler . LACON : return COMPATIBLE ; default : throw new RuntimeException ( \"Impossible arc\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cleanup - clean up NFA after optimizations [CODESPLIT] void cleanup ( ) { State s ; State nexts ; int n ; /* clear out unreachable or dead-end states */ /* use pre to mark reachable, then post to mark can-reach-post */ markreachable ( pre , null , pre ) ; markcanreach ( post , pre , post ) ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; if ( s . tmp != post && 0 == s . flag ) { dropstate ( s ) ; } } assert post . nins == 0 || post . tmp == post ; cleartraverse ( pre ) ; assert post . nins == 0 || post . tmp == null ; /* the nins==0 (final unreachable) case will be caught later */ /* renumber surviving states */ n = 0 ; for ( s = states ; s != null ; s = s . next ) { s . no = n ++ ; } nstates = n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "markreachable - recursive marking of reachable states [CODESPLIT] void markreachable ( State s , State okay , State mark ) { Arc a ; if ( s . tmp != okay ) { return ; } s . tmp = mark ; for ( a = s . outs ; a != null ; a = a . outchain ) { markreachable ( a . to , okay , mark ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "markcanreach - recursive marking of states which can reach here [CODESPLIT] void markcanreach ( State s , State okay , State mark ) { Arc a ; if ( s . tmp != okay ) { return ; } s . tmp = mark ; for ( a = s . ins ; a != null ; a = a . inchain ) { markcanreach ( a . from , okay , mark ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fixempties - get rid of EMPTY arcs [CODESPLIT] void fixempties ( ) { State s ; State nexts ; Arc a ; Arc nexta ; boolean progress ; /* find and eliminate empties until there are no more */ do { progress = false ; for ( s = states ; s != null ; s = nexts ) { nexts = s . next ; for ( a = s . outs ; a != null ; a = nexta ) { nexta = a . outchain ; if ( a . type == Compiler . EMPTY && unempty ( a ) ) { progress = true ; } assert nexta == null || s . no != State . FREESTATE ; } } if ( progress ) { dumpnfa ( ) ; } } while ( progress ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unempty - optimize out an EMPTY arc if possible Actually as it stands this function always succeeds but the return value is kept with an eye on possible future changes . [CODESPLIT] boolean unempty ( Arc a ) { State from = a . from ; State to = a . to ; boolean usefrom ; /* work on from, as opposed to to? */ assert a . type == Compiler . EMPTY ; assert from != pre && to != post ; if ( from == to ) { /* vacuous loop */ freearc ( a ) ; return true ; } /* decide which end to work on */ usefrom = true ; /* default:  attack from */ if ( from . nouts > to . nins ) { usefrom = false ; } else if ( from . nouts == to . nins ) { /* decide on secondary issue:  move/copy fewest arcs */ if ( from . nins > to . nouts ) { usefrom = false ; } } freearc ( a ) ; if ( usefrom ) { if ( from . nouts == 0 ) { /* was the state's only outarc */ moveins ( from , to ) ; freestate ( from ) ; } else { copyins ( from , to ) ; } } else { if ( to . nins == 0 ) { /* was the state's only inarc */ moveouts ( to , from ) ; freestate ( to ) ; } else { copyouts ( to , from ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the given rule parameters file . [CODESPLIT] private Map < String , String > getRuleParameters ( ) throws CliExecutionException { Map < String , String > ruleParameters ; if ( ruleParametersFile == null ) { ruleParameters = Collections . emptyMap ( ) ; } else { Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStream ( ruleParametersFile ) ) ; } catch ( IOException e ) { throw new CliExecutionException ( \"Cannot read rule parameters file '\" + ruleParametersFile . getPath ( ) + \"'.\" ) ; } ruleParameters = new TreeMap <> ( ) ; for ( String name : properties . stringPropertyNames ( ) ) { ruleParameters . put ( name , properties . getProperty ( name ) ) ; } } return ruleParameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all configured rule interpreter plugins . [CODESPLIT] private Map < String , Collection < RuleInterpreterPlugin > > getRuleInterpreterPlugins ( ) throws CliExecutionException { try { return pluginRepository . getRuleInterpreterPluginRepository ( ) . getRuleInterpreterPlugins ( Collections . < String , Object > emptyMap ( ) ) ; } catch ( PluginRepositoryException e ) { throw new CliExecutionException ( \"Cannot get report plugins.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all configured report plugins . [CODESPLIT] private Map < String , ReportPlugin > getReportPlugins ( ReportContext reportContext ) throws CliExecutionException { ReportPluginRepository reportPluginRepository ; try { reportPluginRepository = pluginRepository . getReportPluginRepository ( ) ; return reportPluginRepository . getReportPlugins ( reportContext , pluginProperties ) ; } catch ( PluginRepositoryException e ) { throw new CliExecutionException ( \"Cannot get report plugins.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the selection of rules . [CODESPLIT] protected RuleSelection getRuleSelection ( RuleSet ruleSet ) { return RuleSelection . select ( ruleSet , groupIds , constraintIds , conceptIds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main method . [CODESPLIT] public static void main ( String [ ] args ) { try { DefaultTaskFactoryImpl taskFactory = new DefaultTaskFactoryImpl ( ) ; new Main ( taskFactory ) . run ( args ) ; } catch ( CliExecutionException e ) { String message = getErrorMessage ( e ) ; LOGGER . error ( message ) ; System . exit ( e . getExitCode ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run tasks according to the given arguments . [CODESPLIT] public void run ( String [ ] args ) throws CliExecutionException { Options options = gatherOptions ( taskFactory ) ; CommandLine commandLine = getCommandLine ( args , options ) ; interpretCommandLine ( commandLine , options , taskFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract an error message from the given exception and its causes . [CODESPLIT] private static String getErrorMessage ( CliExecutionException e ) { StringBuffer messageBuilder = new StringBuffer ( ) ; Throwable current = e ; do { messageBuilder . append ( \"-> \" ) ; messageBuilder . append ( current . getMessage ( ) ) ; current = current . getCause ( ) ; } while ( current != null ) ; return messageBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gather all options which are supported by the task ( i . e . including standard and specific options ) . [CODESPLIT] private Options gatherOptions ( TaskFactory taskFactory ) { final Options options = new Options ( ) ; gatherTasksOptions ( taskFactory , options ) ; gatherStandardOptions ( options ) ; return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gathers the standard options shared by all tasks . [CODESPLIT] @ SuppressWarnings ( \"static-access\" ) private void gatherStandardOptions ( final Options options ) { options . addOption ( OptionBuilder . withArgName ( \"p\" ) . withDescription ( \"Path to property file; default is jqassistant.properties in the class path\" ) . withLongOpt ( \"properties\" ) . hasArg ( ) . create ( \"p\" ) ) ; options . addOption ( new Option ( \"help\" , \"print this message\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gathers the task specific options for all tasks . [CODESPLIT] private void gatherTasksOptions ( TaskFactory taskFactory , Options options ) { for ( Task task : taskFactory . getTasks ( ) ) { for ( Option option : task . getOptions ( ) ) { options . addOption ( option ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string containing the names of all supported tasks . [CODESPLIT] private String gatherTaskNames ( TaskFactory taskFactory ) { final StringBuilder builder = new StringBuilder ( ) ; for ( String taskName : taskFactory . getTaskNames ( ) ) { builder . append ( \"'\" ) . append ( taskName ) . append ( \"' \" ) ; } return builder . toString ( ) . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the command line and execute the requested task . [CODESPLIT] private void interpretCommandLine ( CommandLine commandLine , Options options , TaskFactory taskFactory ) throws CliExecutionException { if ( commandLine . hasOption ( OPTION_HELP ) ) { printUsage ( options , null ) ; System . exit ( 1 ) ; } List < String > taskNames = commandLine . getArgList ( ) ; if ( taskNames . isEmpty ( ) ) { printUsage ( options , \"A task must be specified, i.e. one  of \" + gatherTaskNames ( taskFactory ) ) ; System . exit ( 1 ) ; } List < Task > tasks = new ArrayList <> ( ) ; for ( String taskName : taskNames ) { Task task = taskFactory . fromName ( taskName ) ; if ( task == null ) { printUsage ( options , \"Unknown task \" + taskName ) ; } tasks . add ( task ) ; } Map < String , Object > properties = readProperties ( commandLine ) ; PluginRepository pluginRepository = getPluginRepository ( ) ; try { executeTasks ( tasks , options , commandLine , pluginRepository , properties ) ; } catch ( PluginRepositoryException e ) { throw new CliExecutionException ( \"Unexpected plugin repository problem while executing tasks.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the command line [CODESPLIT] private CommandLine getCommandLine ( String [ ] args , Options options ) { final CommandLineParser parser = new BasicParser ( ) ; CommandLine commandLine = null ; try { commandLine = parser . parse ( options , args ) ; } catch ( ParseException e ) { printUsage ( options , e . getMessage ( ) ) ; System . exit ( 1 ) ; } return commandLine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a task . [CODESPLIT] private void executeTask ( Task task , Options option , CommandLine commandLine , PluginRepository pluginRepository , Map < String , Object > properties ) throws CliExecutionException { try { task . withStandardOptions ( commandLine ) ; task . withOptions ( commandLine ) ; } catch ( CliConfigurationException e ) { printUsage ( option , e . getMessage ( ) ) ; System . exit ( 1 ) ; } task . initialize ( pluginRepository , properties ) ; task . run ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the plugin properties file if specified on the command line or if it exists on the class path . [CODESPLIT] private Map < String , Object > readProperties ( CommandLine commandLine ) throws CliConfigurationException { final Properties properties = new Properties ( ) ; InputStream propertiesStream ; if ( commandLine . hasOption ( \"p\" ) ) { File propertyFile = new File ( commandLine . getOptionValue ( \"p\" ) ) ; if ( ! propertyFile . exists ( ) ) { throw new CliConfigurationException ( \"Property file given by command line does not exist: \" + propertyFile . getAbsolutePath ( ) ) ; } try { propertiesStream = new FileInputStream ( propertyFile ) ; } catch ( FileNotFoundException e ) { throw new CliConfigurationException ( \"Cannot open property file.\" , e ) ; } } else { propertiesStream = Main . class . getResourceAsStream ( \"/jqassistant.properties\" ) ; } Map < String , Object > result = new HashMap <> ( ) ; if ( propertiesStream != null ) { try { properties . load ( propertiesStream ) ; } catch ( IOException e ) { throw new CliConfigurationException ( \"Cannot load properties from file.\" , e ) ; } for ( String name : properties . stringPropertyNames ( ) ) { result . put ( name , properties . getProperty ( name ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print usage information . [CODESPLIT] private void printUsage ( final Options options , final String errorMessage ) { if ( errorMessage != null ) { System . out . println ( \"Error: \" + errorMessage ) ; } final HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( Main . class . getCanonicalName ( ) + \" <task> [options]\" , options ) ; System . out . println ( \"Tasks are: \" + gatherTaskNames ( taskFactory ) ) ; System . out . println ( \"Example: \" + Main . class . getCanonicalName ( ) + \" scan -f java:classpath::target/classes java:classpath::target/test-classes\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the JQASSISTANT_HOME directory . [CODESPLIT] private File getHomeDirectory ( ) { String dirName = System . getenv ( ENV_JQASSISTANT_HOME ) ; if ( dirName != null ) { File dir = new File ( dirName ) ; if ( dir . exists ( ) ) { LOGGER . debug ( \"Using JQASSISTANT_HOME '\" + dir . getAbsolutePath ( ) + \"'.\" ) ; return dir ; } else { LOGGER . warn ( \"JQASSISTANT_HOME '\" + dir . getAbsolutePath ( ) + \"' points to a non-existing directory.\" ) ; return null ; } } LOGGER . warn ( \"JQASSISTANT_HOME is not set.\" ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the class loader to be used for detecting and loading plugins . [CODESPLIT] private ClassLoader createPluginClassLoader ( ) throws CliExecutionException { ClassLoader parentClassLoader = Task . class . getClassLoader ( ) ; File homeDirectory = getHomeDirectory ( ) ; if ( homeDirectory != null ) { File pluginDirectory = new File ( homeDirectory , DIRECTORY_PLUGINS ) ; if ( pluginDirectory . exists ( ) ) { final List < URL > urls = new ArrayList <> ( ) ; final Path pluginDirectoryPath = pluginDirectory . toPath ( ) ; SimpleFileVisitor < Path > visitor = new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { if ( file . toFile ( ) . getName ( ) . endsWith ( \".jar\" ) ) { urls . add ( file . toFile ( ) . toURI ( ) . toURL ( ) ) ; } return FileVisitResult . CONTINUE ; } } ; try { Files . walkFileTree ( pluginDirectoryPath , visitor ) ; } catch ( IOException e ) { throw new CliExecutionException ( \"Cannot read plugin directory.\" , e ) ; } LOGGER . debug ( \"Using plugin URLs: \" + urls ) ; return new com . buschmais . jqassistant . commandline . PluginClassLoader ( urls , parentClassLoader ) ; } } return parentClassLoader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given list of option values into a map of resources and their associated ( optional ) scopes . [CODESPLIT] private Map < String , String > parseResources ( List < String > optionValues ) { Map < String , String > resources = new HashMap <> ( ) ; for ( String file : optionValues ) { String [ ] parts = file . split ( \"::\" ) ; String fileName ; String scopeName = null ; if ( parts . length == 2 ) { scopeName = parts [ 0 ] ; fileName = parts [ 1 ] ; } else { fileName = parts [ 0 ] ; } resources . put ( fileName , scopeName ) ; } return resources ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a geometry to GeoJSON . Note that any data stored in getUserData () of the geometries that is not on the top level GeometryCollection is lost in the process . [CODESPLIT] public String write ( Geometry geometry ) { try { JSONStringer b = new JSONStringer ( ) ; if ( geometry . getClass ( ) . equals ( GeometryCollection . class ) ) { writeFeatureCollection ( b , ( GeometryCollection ) geometry ) ; } else { writeFeature ( b , geometry ) ; } return b . toString ( ) ; } catch ( JSONException e ) { throw new GeoJsonException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * The shell of a polygon in GeoJSON is defined in counterclockwise order in JTS it is the other way round [CODESPLIT] private static Polygon createReversed ( Polygon geometry ) { Polygon r = ( Polygon ) geometry . clone ( ) ; r . normalize ( ) ; return ( Polygon ) r . reverse ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify which countries are guaranteed to contain the given bounding box fully . The given bounding box may wrap around the 180th longitude i . e minLongitude = 170 and maxLongitude = - 170 . [CODESPLIT] public Set < String > getContainingIds ( double minLongitude , double minLatitude , double maxLongitude , double maxLatitude ) { Set < String > ids = new HashSet <> ( ) ; forCellsIn ( minLongitude , minLatitude , maxLongitude , maxLatitude , cell -> { if ( ids . isEmpty ( ) ) { ids . addAll ( cell . getContainingIds ( ) ) ; } else { ids . retainAll ( cell . getContainingIds ( ) ) ; } } ) ; return ids ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identify which countries intersect with the given bounding box . The given bounding box may wrap around the 180th longitude i . e minLongitude = 170 and maxLongitude = - 170 . [CODESPLIT] public Set < String > getIntersectingIds ( double minLongitude , double minLatitude , double maxLongitude , double maxLatitude ) { Set < String > ids = new HashSet <> ( ) ; forCellsIn ( minLongitude , minLatitude , maxLongitude , maxLatitude , cell -> { ids . addAll ( cell . getAllIds ( ) ) ; } ) ; return ids ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "http : // geomalgorithms . com / a03 - _inclusion . html [CODESPLIT] private static boolean isPointInPolygon ( Point p , Point [ ] v ) { int wn = 0 ; for ( int j = 0 , i = v . length - 1 ; j < v . length ; i = j ++ ) { if ( v [ i ] . y <= p . y ) { if ( v [ j ] . y > p . y ) { if ( isLeft ( v [ i ] , v [ j ] , p ) > 0 ) ++ wn ; } } else { if ( v [ j ] . y <= p . y ) { if ( isLeft ( v [ i ] , v [ j ] , p ) < 0 ) -- wn ; } } } return wn != 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there s no match returns the result with { [CODESPLIT] public RouteResult < T > route ( HttpMethod method , String uri ) { MethodlessRouter < T > router = routers . get ( method ) ; if ( router == null ) { router = anyMethodRouter ; } QueryStringDecoder decoder = new QueryStringDecoder ( uri ) ; String [ ] tokens = decodePathTokens ( uri ) ; RouteResult < T > ret = router . route ( uri , decoder . path ( ) , tokens ) ; if ( ret != null ) { return new RouteResult < T > ( uri , decoder . path ( ) , ret . pathParams ( ) , decoder . parameters ( ) , ret . target ( ) ) ; } if ( router != anyMethodRouter ) { ret = anyMethodRouter . route ( uri , decoder . path ( ) , tokens ) ; if ( ret != null ) { return new RouteResult < T > ( uri , decoder . path ( ) , ret . pathParams ( ) , decoder . parameters ( ) , ret . target ( ) ) ; } } if ( notFound != null ) { return new RouteResult < T > ( uri , decoder . path ( ) , Collections . < String , String > emptyMap ( ) , decoder . parameters ( ) , notFound ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a target and params this method tries to do the reverse routing and returns the URI . [CODESPLIT] public String uri ( HttpMethod method , T target , Object ... params ) { MethodlessRouter < T > router = ( method == null ) ? anyMethodRouter : routers . get ( method ) ; // Fallback to anyMethodRouter if no router is found for the method if ( router == null ) { router = anyMethodRouter ; } String ret = router . uri ( target , params ) ; if ( ret != null ) { return ret ; } // Fallback to anyMethodRouter if the router was not anyMethodRouter and no path is found return ( router != anyMethodRouter ) ? anyMethodRouter . uri ( target , params ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------------------------- [CODESPLIT] public Router < T > CONNECT_FIRST ( String path , T target ) { return addRouteFirst ( HttpMethod . CONNECT , path , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------------------------- [CODESPLIT] public Router < T > CONNECT_LAST ( String path , T target ) { return addRouteLast ( HttpMethod . CONNECT , path , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method does nothing if the path pattern has already been added . A path pattern can only point to one target . [CODESPLIT] public OrderlessRouter < T > addRoute ( String pathPattern , T target ) { PathPattern p = new PathPattern ( pathPattern ) ; if ( routes . containsKey ( p ) ) { return this ; } routes . put ( p , target ) ; addReverseRoute ( target , p ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the route specified by the path pattern . [CODESPLIT] public void removePathPattern ( String pathPattern ) { PathPattern p = new PathPattern ( pathPattern ) ; T target = routes . remove ( p ) ; if ( target == null ) { return ; } Set < PathPattern > paths = reverseRoutes . remove ( target ) ; paths . remove ( p ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all routes leading to the target . [CODESPLIT] public void removeTarget ( T target ) { Set < PathPattern > patterns = reverseRoutes . remove ( ObjectUtil . checkNotNull ( target , \"target\" ) ) ; if ( patterns == null ) { return ; } // A pattern can only point to one target. // A target can have multiple patterns. // Remove all patterns leading to this target. for ( PathPattern pattern : patterns ) { routes . remove ( pattern ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of routes in this router . [CODESPLIT] public int size ( ) { return first . routes ( ) . size ( ) + other . routes ( ) . size ( ) + last . routes ( ) . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds route to the first section . [CODESPLIT] public MethodlessRouter < T > addRouteFirst ( String pathPattern , T target ) { first . addRoute ( pathPattern , target ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds route to the other section . [CODESPLIT] public MethodlessRouter < T > addRoute ( String pathPattern , T target ) { other . addRoute ( pathPattern , target ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds route to the last section . [CODESPLIT] public MethodlessRouter < T > addRouteLast ( String pathPattern , T target ) { last . addRoute ( pathPattern , target ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the route specified by the path pattern . [CODESPLIT] public void removePathPattern ( String pathPattern ) { first . removePathPattern ( pathPattern ) ; other . removePathPattern ( pathPattern ) ; last . removePathPattern ( pathPattern ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all routes leading to the target . [CODESPLIT] public void removeTarget ( T target ) { first . removeTarget ( target ) ; other . removeTarget ( target ) ; last . removeTarget ( target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if there s any matching route . [CODESPLIT] public boolean anyMatched ( String [ ] requestPathTokens ) { return first . anyMatched ( requestPathTokens ) || other . anyMatched ( requestPathTokens ) || last . anyMatched ( requestPathTokens ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------- [CODESPLIT] @ Override public void channelRead0 ( ChannelHandlerContext ctx , Object msg ) { // This handler is the last inbound handler. // This means msg has not been handled by any previous handler. ctx . close ( ) ; if ( msg != LastHttpContent . EMPTY_LAST_CONTENT ) { onUnknownMessage ( msg ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There are two different Criterion for if a property is null or checking equality . This is a convience method to return the one based on if value is null or not . [CODESPLIT] private Criterion smartEqual ( String property , Object value ) { if ( value == null ) { return Restrictions . isNull ( property ) ; } else { return Restrictions . eq ( property , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the file name String for an owner and book name . [CODESPLIT] protected String getStoreFileName ( String owner , String name ) { final StringBuilder fileNameBuff = new StringBuilder ( ) ; fileNameBuff . append ( owner != null ? \"_\" + owner : \"null\" ) ; fileNameBuff . append ( \"_\" ) ; fileNameBuff . append ( name != null ? \"_\" + name : \"null\" ) ; fileNameBuff . append ( \".bms.xml\" ) ; return fileNameBuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the { @link File } object to use for storing retrieving and deleting the bookmark set . [CODESPLIT] protected File getStoreFile ( String owner , String name ) { final String fileStoreName = this . getStoreFileName ( owner , name ) ; final File basePath = this . getStoreDirectory ( ) ; final File storeFile = new File ( basePath , fileStoreName ) ; return storeFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a BookmarkSet for the request using the injected { @link OwnerResolver } and { @link NameResolver } . <br > <br > If <code > create< / code > is false and no BookmarkSet exists for the name and owner null is returned . <br > <br > If <code > create< / code > is true and no BookmarkSet exists for the name and owner a new BookmarkSet is created . [CODESPLIT] public BookmarkSet getBookmarkSet ( PortletRequest request , boolean create ) { final String owner = this . ownerResolver . getOwner ( request ) ; final String name = this . nameResolver . getBookmarkSetName ( request ) ; BookmarkSet bookmarkSet = this . bookmarkStore . getBookmarkSet ( owner , name ) ; if ( bookmarkSet == null && create ) { bookmarkSet = this . bookmarkStore . createBookmarkSet ( owner , name ) ; if ( bookmarkSet == null ) { throw new IllegalStateException ( \"Required BookmarkSet is null even after createBookmarkSet was called.\" ) ; } } return bookmarkSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an immutable sorted view of the values of the children Map . The sorting is done using the current childComparator . Warning this is has a time cost of 2n log ( n ) on every call . [CODESPLIT] public List < Entry > getSortedChildren ( ) { if ( this . children == null ) { return null ; } else { final Collection < Entry > childCollection = this . children . values ( ) ; final List < Entry > childList = new ArrayList < Entry > ( childCollection ) ; Collections . sort ( childList , this . childComparator ) ; return Collections . unmodifiableList ( childList ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Folders are always greater than non - Folders if they are both Folders or both not Folders they are equal . [CODESPLIT] protected int compareFolders ( final Entry e1 , final Entry e2 ) { final boolean f1 = e1 instanceof Folder ; final boolean f2 = e2 instanceof Folder ; if ( f1 && ! f2 ) { return - 1 ; } else if ( ! f1 && f2 ) { return 1 ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compairs the entries by name note created and modified properties in that order . [CODESPLIT] protected int compareEntries ( final Entry e1 , final Entry e2 ) { return new CompareToBuilder ( ) . append ( e1 . getName ( ) , e2 . getName ( ) ) . append ( e1 . getNote ( ) , e2 . getNote ( ) ) . append ( e1 . getCreated ( ) , e2 . getCreated ( ) ) . append ( e1 . getModified ( ) , e2 . getModified ( ) ) . toComparison ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If both classes are not Bookmarks they are equal . If they are both bookmarks they are compared by url then newWindow properties . [CODESPLIT] protected int compareBookmarks ( final Entry e1 , final Entry e2 ) { if ( e1 instanceof Bookmark && e2 instanceof Bookmark ) { final Bookmark b1 = ( Bookmark ) e1 ; final Bookmark b2 = ( Bookmark ) e2 ; return new CompareToBuilder ( ) . append ( b1 . getUrl ( ) , b2 . getUrl ( ) ) . append ( b1 . isNewWindow ( ) , b2 . isNewWindow ( ) ) . toComparison ( ) ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets Preferences for the request using the injected { @link OwnerResolver } and { @link NameResolver } . <br > <br > If <code > create< / code > is false and no Preferences exists for the name and owner null is returned . <br > <br > If <code > create< / code > is true and no Preferences exists for the name and owner a new Preferences is created . [CODESPLIT] public Preferences getPreferences ( PortletRequest request , boolean create ) { final String owner = this . ownerResolver . getOwner ( request ) ; final String name = this . nameResolver . getBookmarkSetName ( request ) ; Preferences preferences = this . preferencesStore . getPreferences ( owner , name ) ; if ( preferences == null && create ) { preferences = this . preferencesStore . createPreferences ( owner , name ) ; if ( preferences == null ) { throw new IllegalStateException ( \"Required Preferences is null even after createPreferences was called.\" ) ; } } return preferences ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an immutable sorted view of the values of the children Map . The sorting is done using the current childComparator . Warning this is has a time cost of 2n log ( n ) on every call . [CODESPLIT] public List < Entry > getSortedChildren ( ) { List < Entry > children = new ArrayList < Entry > ( ) ; log . debug ( \"children: \" + children . size ( ) ) ; HttpClient client = new HttpClient ( ) ; GetMethod get = null ; try { log . debug ( \"getting url \" + url ) ; get = new GetMethod ( url ) ; int rc = client . executeMethod ( get ) ; if ( rc != HttpStatus . SC_OK ) { log . error ( \"HttpStatus:\" + rc ) ; } DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = domBuilderFactory . newDocumentBuilder ( ) ; InputStream in = get . getResponseBodyAsStream ( ) ; builder = domBuilderFactory . newDocumentBuilder ( ) ; Document doc = builder . parse ( in ) ; get . releaseConnection ( ) ; Element e = ( Element ) doc . getElementsByTagName ( \"rdf:RDF\" ) . item ( 0 ) ; log . debug ( \"got root \" + e ) ; NodeList n = e . getElementsByTagName ( \"item\" ) ; log . debug ( \"found items \" + n . getLength ( ) ) ; for ( int i = 0 ; i < n . getLength ( ) ; i ++ ) { Bookmark bookmark = new Bookmark ( ) ; Element l = ( Element ) n . item ( i ) ; bookmark . setName ( ( ( Element ) l . getElementsByTagName ( \"title\" ) . item ( 0 ) ) . getTextContent ( ) ) ; bookmark . setUrl ( ( ( Element ) l . getElementsByTagName ( \"link\" ) . item ( 0 ) ) . getTextContent ( ) ) ; if ( l . getElementsByTagName ( \"description\" ) . getLength ( ) > 0 ) { bookmark . setNote ( ( ( Element ) l . getElementsByTagName ( \"description\" ) . item ( 0 ) ) . getTextContent ( ) ) ; } children . add ( bookmark ) ; log . debug ( \"added bookmark \" + bookmark . getName ( ) + \" \" + bookmark . getUrl ( ) ) ; } } catch ( HttpException e ) { log . error ( \"Error parsing delicious\" , e ) ; } catch ( IOException e ) { log . error ( \"Error parsing delicious\" , e ) ; } catch ( ParserConfigurationException e ) { log . error ( \"Error parsing delicious\" , e ) ; } catch ( SAXException e ) { log . error ( \"Error parsing delicious\" , e ) ; } finally { if ( get != null ) get . releaseConnection ( ) ; } log . debug ( \"children: \" + children . size ( ) ) ; return children ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the optional short description <p > The short description is the first line of { @link #getDescription () } < / p > [CODESPLIT] public String getShortDescription ( ) { if ( this . description == null ) { return null ; } final String [ ] lines = this . description . split ( \"\\\\R\" , 2 ) ; if ( lines . length > 0 ) { return lines [ 0 ] ; } else { return \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the last - modified time of the servlet class file associated with this JspServletWrapper . [CODESPLIT] public void setServletClassLastModifiedTime ( long lastModified ) { if ( this . servletClassLastModifiedTime < lastModified ) { synchronized ( this ) { if ( this . servletClassLastModifiedTime < lastModified ) { this . servletClassLastModifiedTime = lastModified ; reload = true ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile ( if needed ) and load a tag file [CODESPLIT] public Class loadTagFile ( ) throws JasperException { try { ctxt . compile ( ) ; if ( reload ) { tagHandlerClass = ctxt . load ( ) ; } } catch ( ClassNotFoundException ex ) { } catch ( FileNotFoundException ex ) { log . log ( Level . SEVERE , Localizer . getMessage ( \"jsp.error.compiling\" ) ) ; throw new JasperException ( ex ) ; } return tagHandlerClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile and load a prototype for the Tag file . This is needed when compiling tag files with circular dependencies . A prototpe ( skeleton ) with no dependencies on other other tag files is generated and compiled . [CODESPLIT] public Class loadTagFilePrototype ( ) throws JasperException { ctxt . setPrototypeMode ( true ) ; try { return loadTagFile ( ) ; } finally { ctxt . setPrototypeMode ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a list of files that the current page has source dependency on . [CODESPLIT] public java . util . List < String > getDependants ( ) { try { Object target ; if ( isTagFile ) { if ( reload ) { tagHandlerClass = ctxt . load ( ) ; } target = tagHandlerClass . newInstance ( ) ; } else { target = getServlet ( ) ; } if ( target != null && target instanceof JspSourceDependent ) { return ( ( JspSourceDependent ) target ) . getDependants ( ) ; } } catch ( Throwable ex ) { } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Handles the case where a requested JSP file no longer exists . [CODESPLIT] private void jspFileNotFound ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { FileNotFoundException fnfe = new FileNotFoundException ( jspUri ) ; ctxt . incrementRemoved ( ) ; String includeRequestUri = ( String ) request . getAttribute ( \"javax.servlet.include.request_uri\" ) ; if ( includeRequestUri != null ) { // This file was included. Throw an exception as // a response.sendError() will be ignored by the // servlet engine. throw new ServletException ( fnfe ) ; } else { try { response . sendError ( HttpServletResponse . SC_NOT_FOUND , fnfe . getMessage ( ) ) ; } catch ( IllegalStateException ise ) { log . log ( Level . SEVERE , Localizer . getMessage ( \"jsp.error.file.not.found\" , fnfe . getMessage ( ) ) , fnfe ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a JSP document by responding to SAX events . [CODESPLIT] public static Node . Nodes parse ( ParserController pc , String path , JarFile jarFile , Node parent , boolean isTagFile , boolean directivesOnly , String pageEnc , String jspConfigPageEnc , boolean isEncodingSpecifiedInProlog ) throws JasperException { JspDocumentParser jspDocParser = new JspDocumentParser ( pc , path , isTagFile , directivesOnly ) ; Node . Nodes pageNodes = null ; try { // Create dummy root and initialize it with given page encodings Node . Root dummyRoot = new Node . Root ( null , parent , true ) ; dummyRoot . setPageEncoding ( pageEnc ) ; dummyRoot . setJspConfigPageEncoding ( jspConfigPageEnc ) ; dummyRoot . setIsEncodingSpecifiedInProlog ( isEncodingSpecifiedInProlog ) ; jspDocParser . current = dummyRoot ; if ( parent == null ) { jspDocParser . addInclude ( dummyRoot , jspDocParser . pageInfo . getIncludePrelude ( ) ) ; } else { jspDocParser . isTop = false ; } // Parse the input SAXParser saxParser = getSAXParser ( false , jspDocParser ) ; InputStream inStream = null ; try { inStream = JspUtil . getInputStream ( path , jarFile , jspDocParser . ctxt , jspDocParser . err ) ; saxParser . parse ( new InputSource ( inStream ) , jspDocParser ) ; } catch ( EnableDTDValidationException e ) { saxParser = getSAXParser ( true , jspDocParser ) ; jspDocParser . isValidating = true ; if ( inStream != null ) { try { inStream . close ( ) ; } catch ( Exception any ) { } } inStream = JspUtil . getInputStream ( path , jarFile , jspDocParser . ctxt , jspDocParser . err ) ; saxParser . parse ( new InputSource ( inStream ) , jspDocParser ) ; } finally { if ( inStream != null ) { try { inStream . close ( ) ; } catch ( Exception any ) { } } } if ( parent == null ) { jspDocParser . addInclude ( dummyRoot , jspDocParser . pageInfo . getIncludeCoda ( ) ) ; jspDocParser . pageInfo . setRootPath ( path ) ; } // Create Node.Nodes from dummy root pageNodes = new Node . Nodes ( dummyRoot ) ; } catch ( IOException ioe ) { jspDocParser . err . jspError ( \"jsp.error.data.file.read\" , path , ioe ) ; } catch ( SAXParseException e ) { jspDocParser . err . jspError ( new Mark ( jspDocParser . ctxt , path , e . getLineNumber ( ) , e . getColumnNumber ( ) ) , e . getMessage ( ) ) ; } catch ( Exception e ) { jspDocParser . err . jspError ( e ) ; } return pageNodes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Processes the given list of included files . [CODESPLIT] private void addInclude ( Node parent , List files ) throws SAXException { if ( files != null ) { Iterator iter = files . iterator ( ) ; while ( iter . hasNext ( ) ) { String file = ( String ) iter . next ( ) ; AttributesImpl attrs = new AttributesImpl ( ) ; attrs . addAttribute ( \"\" , \"file\" , \"file\" , \"CDATA\" , file ) ; // Create a dummy Include directive node Node includeDir = new Node . IncludeDirective ( attrs , null , // XXX parent ) ; processIncludeDirective ( file , includeDir ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Receives notification of the start of an element . [CODESPLIT] public void startElement ( String uri , String localName , String qName , Attributes attrs ) throws SAXException { AttributesImpl taglibAttrs = null ; AttributesImpl nonTaglibAttrs = null ; AttributesImpl nonTaglibXmlnsAttrs = null ; processChars ( ) ; checkPrefixes ( uri , qName , attrs ) ; if ( directivesOnly && ! ( JSP_URI . equals ( uri ) && ( localName . startsWith ( DIRECTIVE_ACTION ) || localName . startsWith ( ROOT_ACTION ) ) ) ) { return ; } // jsp:text must not have any subelements if ( JSP_URI . equals ( uri ) && TEXT_ACTION . equals ( current . getLocalName ( ) ) ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.text.has_subelement\" ) , locator ) ; } startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ; if ( attrs != null ) { /*\n             * Notice that due to a bug in the underlying SAX parser, the\n             * attributes must be enumerated in descending order. \n             */ boolean isTaglib = false ; for ( int i = attrs . getLength ( ) - 1 ; i >= 0 ; i -- ) { isTaglib = false ; String attrQName = attrs . getQName ( i ) ; if ( ! attrQName . startsWith ( \"xmlns\" ) ) { if ( nonTaglibAttrs == null ) { nonTaglibAttrs = new AttributesImpl ( ) ; } nonTaglibAttrs . addAttribute ( attrs . getURI ( i ) , attrs . getLocalName ( i ) , attrs . getQName ( i ) , attrs . getType ( i ) , attrs . getValue ( i ) ) ; } else { if ( attrQName . startsWith ( \"xmlns:jsp\" ) ) { isTaglib = true ; } else { String attrUri = attrs . getValue ( i ) ; // TaglibInfo for this uri already established in // startPrefixMapping isTaglib = pageInfo . hasTaglib ( attrUri ) ; } if ( isTaglib ) { if ( taglibAttrs == null ) { taglibAttrs = new AttributesImpl ( ) ; } taglibAttrs . addAttribute ( attrs . getURI ( i ) , attrs . getLocalName ( i ) , attrs . getQName ( i ) , attrs . getType ( i ) , attrs . getValue ( i ) ) ; } else { if ( nonTaglibXmlnsAttrs == null ) { nonTaglibXmlnsAttrs = new AttributesImpl ( ) ; } nonTaglibXmlnsAttrs . addAttribute ( attrs . getURI ( i ) , attrs . getLocalName ( i ) , attrs . getQName ( i ) , attrs . getType ( i ) , attrs . getValue ( i ) ) ; } } } } Node node = null ; if ( tagDependentPending && JSP_URI . equals ( uri ) && localName . equals ( BODY_ACTION ) ) { tagDependentPending = false ; tagDependentNesting ++ ; current = parseStandardAction ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; return ; } if ( tagDependentPending && JSP_URI . equals ( uri ) && localName . equals ( ATTRIBUTE_ACTION ) ) { current = parseStandardAction ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; return ; } if ( tagDependentPending ) { tagDependentPending = false ; tagDependentNesting ++ ; } if ( tagDependentNesting > 0 ) { node = new Node . UninterpretedTag ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; } else if ( JSP_URI . equals ( uri ) ) { node = parseStandardAction ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; } else { node = parseCustomAction ( qName , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; if ( node == null ) { node = new Node . UninterpretedTag ( qName , localName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , startMark , current ) ; } else { // custom action String bodyType = getBodyType ( ( Node . CustomTag ) node ) ; if ( scriptlessBodyNode == null && bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_SCRIPTLESS ) ) { scriptlessBodyNode = node ; } else if ( TagInfo . BODY_CONTENT_TAG_DEPENDENT . equalsIgnoreCase ( bodyType ) ) { tagDependentPending = true ; } } } current = node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Receives notification of character data inside an element . [CODESPLIT] public void characters ( char [ ] buf , int offset , int len ) { if ( charBuffer == null ) { charBuffer = new StringBuilder ( ) ; } charBuffer . append ( buf , offset , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Receives notification of the end of an element . [CODESPLIT] public void endElement ( String uri , String localName , String qName ) throws SAXException { processChars ( ) ; if ( directivesOnly && ! ( JSP_URI . equals ( uri ) && localName . startsWith ( DIRECTIVE_ACTION ) ) ) { return ; } if ( current instanceof Node . NamedAttribute ) { boolean isTrim = ( ( Node . NamedAttribute ) current ) . isTrim ( ) ; Node . Nodes subElems = ( ( Node . NamedAttribute ) current ) . getBody ( ) ; for ( int i = 0 ; subElems != null && i < subElems . size ( ) ; i ++ ) { Node subElem = subElems . getNode ( i ) ; if ( ! ( subElem instanceof Node . TemplateText ) ) { continue ; } // Ignore any whitespace (including spaces, carriage returns, // line feeds, and tabs, that appear at the beginning and at // the end of the body of the <jsp:attribute> action, if the // action's 'trim' attribute is set to TRUE (default). // In addition, any textual nodes in the <jsp:attribute> that // have only white space are dropped from the document, with // the exception of leading and trailing white-space-only // textual nodes in a <jsp:attribute> whose 'trim' attribute // is set to FALSE, which must be kept verbatim. if ( i == 0 ) { if ( isTrim ) { ( ( Node . TemplateText ) subElem ) . ltrim ( ) ; } } else if ( i == subElems . size ( ) - 1 ) { if ( isTrim ) { ( ( Node . TemplateText ) subElem ) . rtrim ( ) ; } } else { if ( ( ( Node . TemplateText ) subElem ) . isAllSpace ( ) ) { subElems . remove ( subElem ) ; } } } } else if ( current instanceof Node . ScriptingElement ) { checkScriptingBody ( ( Node . ScriptingElement ) current ) ; } if ( isTagDependent ( current ) ) { tagDependentNesting -- ; } if ( scriptlessBodyNode != null && current . equals ( scriptlessBodyNode ) ) { scriptlessBodyNode = null ; } if ( current . getParent ( ) != null ) { current = current . getParent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * See org . xml . sax . ext . LexicalHandler . [CODESPLIT] public void comment ( char [ ] buf , int offset , int len ) throws SAXException { processChars ( ) ; // Flush char buffer and remove white spaces // ignore comments in the DTD if ( ! inDTD ) { startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ; new Node . Comment ( new String ( buf , offset , len ) , startMark , current ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * See org . xml . sax . ext . LexicalHandler . [CODESPLIT] public void startCDATA ( ) throws SAXException { processChars ( ) ; // Flush char buffer and remove white spaces startMark = new Mark ( ctxt , path , locator . getLineNumber ( ) , locator . getColumnNumber ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * See org . xml . sax . ext . LexicalHandler . [CODESPLIT] public void startDTD ( String name , String publicId , String systemId ) throws SAXException { if ( ! isValidating ) { fatalError ( ENABLE_DTD_VALIDATION_EXCEPTION ) ; } inDTD = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Receives notification of the start of a Namespace mapping . [CODESPLIT] public void startPrefixMapping ( String prefix , String uri ) throws SAXException { if ( directivesOnly && ! ( JSP_URI . equals ( uri ) ) ) { return ; } try { addTaglibInfo ( prefix , uri ) ; } catch ( JasperException je ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.could.not.add.taglibraries\" ) , locator , je ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Receives notification of the end of a Namespace mapping . [CODESPLIT] public void endPrefixMapping ( String prefix ) throws SAXException { if ( directivesOnly ) { String uri = pageInfo . getURI ( prefix ) ; if ( ! JSP_URI . equals ( uri ) ) { return ; } } pageInfo . popPrefixMapping ( prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private utility methods [CODESPLIT] private Node parseStandardAction ( String qName , String localName , Attributes nonTaglibAttrs , Attributes nonTaglibXmlnsAttrs , Attributes taglibAttrs , Mark start , Node parent ) throws SAXException { Node node = null ; if ( localName . equals ( ROOT_ACTION ) ) { if ( ! ( current instanceof Node . Root ) ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.nested_jsproot\" ) , locator ) ; } node = new Node . JspRoot ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; if ( isTop ) { pageInfo . setHasJspRoot ( true ) ; } } else if ( localName . equals ( PAGE_DIRECTIVE_ACTION ) ) { if ( isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.action.istagfile\" , localName ) , locator ) ; } node = new Node . PageDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; String imports = nonTaglibAttrs . getValue ( \"import\" ) ; // There can only be one 'import' attribute per page directive if ( imports != null ) { ( ( Node . PageDirective ) node ) . addImport ( imports ) ; } } else if ( localName . equals ( INCLUDE_DIRECTIVE_ACTION ) ) { node = new Node . IncludeDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; processIncludeDirective ( nonTaglibAttrs . getValue ( \"file\" ) , node ) ; } else if ( localName . equals ( DECLARATION_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.no.scriptlets\" , localName ) , locator ) ; } node = new Node . Declaration ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( SCRIPTLET_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.no.scriptlets\" , localName ) , locator ) ; } node = new Node . Scriptlet ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( EXPRESSION_ACTION ) ) { if ( scriptlessBodyNode != null ) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.no.scriptlets\" , localName ) , locator ) ; } node = new Node . Expression ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( USE_BEAN_ACTION ) ) { node = new Node . UseBean ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( SET_PROPERTY_ACTION ) ) { node = new Node . SetProperty ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( GET_PROPERTY_ACTION ) ) { node = new Node . GetProperty ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( INCLUDE_ACTION ) ) { node = new Node . IncludeAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( FORWARD_ACTION ) ) { node = new Node . ForwardAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PARAM_ACTION ) ) { node = new Node . ParamAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PARAMS_ACTION ) ) { node = new Node . ParamsAction ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( PLUGIN_ACTION ) ) { node = new Node . PlugIn ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( TEXT_ACTION ) ) { node = new Node . JspText ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( BODY_ACTION ) ) { node = new Node . JspBody ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( ATTRIBUTE_ACTION ) ) { node = new Node . NamedAttribute ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( OUTPUT_ACTION ) ) { node = new Node . JspOutput ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( TAG_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.action.isnottagfile\" , localName ) , locator ) ; } node = new Node . TagDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; String imports = nonTaglibAttrs . getValue ( \"import\" ) ; // There can only be one 'import' attribute per tag directive if ( imports != null ) { ( ( Node . TagDirective ) node ) . addImport ( imports ) ; } } else if ( localName . equals ( ATTRIBUTE_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.action.isnottagfile\" , localName ) , locator ) ; } node = new Node . AttributeDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( VARIABLE_DIRECTIVE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.action.isnottagfile\" , localName ) , locator ) ; } node = new Node . VariableDirective ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( INVOKE_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.action.isnottagfile\" , localName ) , locator ) ; } node = new Node . InvokeAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( DOBODY_ACTION ) ) { if ( ! isTagFile ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.action.isnottagfile\" , localName ) , locator ) ; } node = new Node . DoBodyAction ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( ELEMENT_ACTION ) ) { node = new Node . JspElement ( qName , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else if ( localName . equals ( FALLBACK_ACTION ) ) { node = new Node . FallBackAction ( qName , nonTaglibXmlnsAttrs , taglibAttrs , start , current ) ; } else { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.xml.badStandardAction\" , localName ) , locator ) ; } return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks if the XML element with the given tag name is a custom action and returns the corresponding Node object . [CODESPLIT] private Node parseCustomAction ( String qName , String localName , String uri , Attributes nonTaglibAttrs , Attributes nonTaglibXmlnsAttrs , Attributes taglibAttrs , Mark start , Node parent ) throws SAXException { if ( uri . startsWith ( TagConstants . URN_JSPTLD ) ) { uri = uri . substring ( TagConstants . URN_JSPTLD . length ( ) ) ; } // Check if this is a user-defined (custom) tag TagLibraryInfo tagLibInfo = pageInfo . getTaglib ( uri ) ; if ( tagLibInfo == null ) { return null ; } TagInfo tagInfo = tagLibInfo . getTag ( localName ) ; TagFileInfo tagFileInfo = tagLibInfo . getTagFile ( localName ) ; if ( tagInfo == null && tagFileInfo == null ) { throw new SAXException ( Localizer . getMessage ( \"jsp.error.xml.bad_tag\" , localName , uri ) ) ; } Class tagHandlerClass = null ; if ( tagInfo != null ) { String handlerClassName = tagInfo . getTagClassName ( ) ; try { tagHandlerClass = ctxt . getClassLoader ( ) . loadClass ( handlerClassName ) ; } catch ( Exception e ) { throw new SAXException ( Localizer . getMessage ( \"jsp.error.loadclass.taghandler\" , handlerClassName , qName ) , e ) ; } } String prefix = \"\" ; int colon = qName . indexOf ( ' ' ) ; if ( colon != - 1 ) { prefix = qName . substring ( 0 , colon ) ; } Node . CustomTag ret = null ; if ( tagInfo != null ) { ret = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , qName , prefix , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , parent , tagInfo , tagHandlerClass ) ; } else { ret = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , qName , prefix , localName , uri , nonTaglibAttrs , nonTaglibXmlnsAttrs , taglibAttrs , start , parent , tagFileInfo ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Adds the tag library associated with the given uri namespace to the translation unit that this parser is associated with . [CODESPLIT] private void addTaglibInfo ( String prefix , String uri ) throws JasperException { if ( uri . startsWith ( URN_JSPTAGDIR ) ) { // uri (of the form \"urn:jsptagdir:path\") references tag file dir String tagdir = uri . substring ( URN_JSPTAGDIR . length ( ) ) ; TagLibraryInfo taglibInfo = new ImplicitTagLibraryInfo ( ctxt , parserController , prefix , tagdir , err ) ; if ( pageInfo . getTaglib ( uri ) == null ) { pageInfo . addTaglib ( uri , taglibInfo ) ; } pageInfo . pushPrefixMapping ( prefix , uri ) ; } else { // uri references TLD file boolean isPlainUri = false ; if ( uri . startsWith ( TagConstants . URN_JSPTLD ) ) { uri = uri . substring ( TagConstants . URN_JSPTLD . length ( ) ) ; } else { isPlainUri = true ; } // START GlassFish 750 ConcurrentHashMap < String , TagLibraryInfoImpl > taglibs = ctxt . getTaglibs ( ) ; TagLibraryInfoImpl taglibInfo = taglibs . get ( uri ) ; if ( taglibInfo == null ) { synchronized ( taglibs ) { taglibInfo = taglibs . get ( uri ) ; if ( taglibInfo == null ) { // END GlassFish 750             String [ ] location = ctxt . getTldLocation ( uri ) ; if ( location != null || ! isPlainUri ) { /*\n                             * If the uri value is a plain uri, a translation\n                             * error must not be generated if the uri is not\n                             * found in the taglib map.\n                             * Instead, any actions in the namespace defined\n                             * by the uri value must be treated as\n                             * uninterpreted.\n                             */ taglibInfo = new TagLibraryInfoImpl ( ctxt , parserController , prefix , uri , location , err ) ; // START GlassFish 750 ctxt . addTaglib ( uri , taglibInfo ) ; pageInfo . addTaglib ( uri , taglibInfo ) ; // END GlassFish 750 } // START GlassFish 750 } } } // END GlassFish 750 if ( taglibInfo != null ) { if ( pageInfo . getTaglib ( uri ) == null ) { pageInfo . addTaglib ( uri , new TagLibraryInfoImpl ( prefix , uri , taglibInfo , pageInfo ) ) ; } pageInfo . pushPrefixMapping ( prefix , uri ) ; } else { pageInfo . pushPrefixMapping ( prefix , null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Ensures that the given body only contains nodes that are instances of TemplateText . [CODESPLIT] private void checkScriptingBody ( Node . ScriptingElement scriptingElem ) throws SAXException { Node . Nodes body = scriptingElem . getBody ( ) ; if ( body != null ) { int size = body . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Node n = body . getNode ( i ) ; if ( ! ( n instanceof Node . TemplateText ) ) { String elemType = SCRIPTLET_ACTION ; if ( scriptingElem instanceof Node . Declaration ) elemType = DECLARATION_ACTION ; if ( scriptingElem instanceof Node . Expression ) elemType = EXPRESSION_ACTION ; String msg = Localizer . getMessage ( \"jsp.error.parse.xml.scripting.invalid.body\" , elemType ) ; throw new SAXException ( msg ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses the given file included via an include directive . [CODESPLIT] private void processIncludeDirective ( String fname , Node parent ) throws SAXException { if ( fname == null ) { return ; } try { parserController . parse ( fname , parent , null ) ; } catch ( FileNotFoundException fnfe ) { throw new SAXParseException ( Localizer . getMessage ( \"jsp.error.file.not.found\" , fname ) , locator , fnfe ) ; } catch ( Exception e ) { throw new SAXException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks an element s given URI qname and attributes to see if any of them hijack the jsp prefix that is bind it to a namespace other than http : // java . sun . com / JSP / Page . [CODESPLIT] private void checkPrefixes ( String uri , String qName , Attributes attrs ) { checkPrefix ( uri , qName ) ; int len = attrs . getLength ( ) ; for ( int i = 0 ; i < len ; i ++ ) { checkPrefix ( attrs . getURI ( i ) , attrs . getQName ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks the given URI and qname to see if they hijack the jsp prefix which would be the case if qName contained the jsp prefix and uri was different from http : // java . sun . com / JSP / Page . [CODESPLIT] private void checkPrefix ( String uri , String qName ) { int index = qName . indexOf ( ' ' ) ; if ( index != - 1 ) { String prefix = qName . substring ( 0 , index ) ; pageInfo . addPrefix ( prefix ) ; if ( \"jsp\" . equals ( prefix ) && ! JSP_URI . equals ( uri ) ) { pageInfo . setIsJspPrefixHijacked ( true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets SAXParser . [CODESPLIT] private static SAXParser getSAXParser ( boolean validating , JspDocumentParser jspDocParser ) throws Exception { SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; // Preserve xmlns attributes factory . setFeature ( \"http://xml.org/sax/features/namespace-prefixes\" , true ) ; factory . setFeature ( \"http://xml.org/sax/features/validation\" , validating ) ; // Configure the parser SAXParser saxParser = factory . newSAXParser ( ) ; XMLReader xmlReader = saxParser . getXMLReader ( ) ; xmlReader . setProperty ( LEXICAL_HANDLER_PROPERTY , jspDocParser ) ; xmlReader . setErrorHandler ( jspDocParser ) ; return saxParser ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the class with the specified name searching using the following algorithm until it finds and returns the class . If the class cannot be found returns <code > ClassNotFoundException< / code > . <ul > <li > Call <code > findLoadedClass ( String ) < / code > to check if the class has already been loaded . If it has the same <code > Class< / code > object is returned . < / li > <li > If the <code > delegate< / code > property is set to <code > true< / code > call the <code > loadClass () < / code > method of the parent class loader if any . < / li > <li > Call <code > findClass () < / code > to find this class in our locally defined repositories . < / li > <li > Call the <code > loadClass () < / code > method of our parent class loader if any . < / li > < / ul > If the class was found using the above steps and the <code > resolve< / code > flag is <code > true< / code > this method will then call <code > resolveClass ( Class ) < / code > on the resulting Class object . [CODESPLIT] public synchronized Class loadClass ( final String name , boolean resolve ) throws ClassNotFoundException { Class clazz = null ; // (0) Check our previously loaded class cache clazz = findLoadedClass ( name ) ; if ( clazz != null ) { if ( resolve ) resolveClass ( clazz ) ; return ( clazz ) ; } // (.5) Permission to access this class when using a SecurityManager if ( securityManager != null ) { int dot = name . lastIndexOf ( ' ' ) ; if ( dot >= 0 ) { try { // Do not call the security manager since by default, we grant that package. if ( ! \"org.apache.jasper.runtime\" . equalsIgnoreCase ( name . substring ( 0 , dot ) ) ) { securityManager . checkPackageAccess ( name . substring ( 0 , dot ) ) ; } } catch ( SecurityException se ) { String error = \"Security Violation, attempt to use \" + \"Restricted Class: \" + name ; se . printStackTrace ( ) ; throw new ClassNotFoundException ( error ) ; } } } if ( ! name . startsWith ( Constants . JSP_PACKAGE_NAME ) ) { // Class is not in org.apache.jsp, therefore, have our // parent load it clazz = parent . loadClass ( name ) ; if ( resolve ) resolveClass ( clazz ) ; return clazz ; } return findClass ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "START OF IASRI 4709374 [CODESPLIT] public Class findClass ( String className ) throws ClassNotFoundException { // If the class file is in memory, use it byte [ ] cdata = this . bytecodes . get ( className ) ; String path = className . replace ( ' ' , ' ' ) + \".class\" ; if ( cdata == null ) { // If the bytecode preprocessor is not enabled, use super.findClass // as usual. /* XXX\n            if (!PreprocessorUtil.isPreprocessorEnabled()) { \n                return super.findClass(className);\n            }\n*/ // read class data from file cdata = loadClassDataFromFile ( path ) ; if ( cdata == null ) { throw new ClassNotFoundException ( className ) ; } } // Preprocess the loaded byte code /* XXX\n        if (PreprocessorUtil.isPreprocessorEnabled()) {\n            cdata = PreprocessorUtil.processClass(path, cdata);\n        }\n*/ Class clazz = null ; if ( securityManager != null ) { ProtectionDomain pd = new ProtectionDomain ( codeSource , permissionCollection ) ; clazz = defineClass ( className , cdata , 0 , cdata . length , pd ) ; } else { clazz = defineClass ( className , cdata , 0 , cdata . length ) ; } return clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Load JSP class data from file . [CODESPLIT] private byte [ ] loadClassDataFromFile ( final String fileName ) { byte [ ] classBytes = null ; try { InputStream in = null ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { in = AccessController . doPrivileged ( new PrivilegedAction < InputStream > ( ) { public InputStream run ( ) { return getResourceAsStream ( fileName ) ; } } ) ; } else { in = getResourceAsStream ( fileName ) ; } if ( in == null ) { return null ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte buf [ ] = new byte [ 1024 ] ; for ( int i = 0 ; ( i = in . read ( buf ) ) != - 1 ; ) { baos . write ( buf , 0 , i ) ; } in . close ( ) ; baos . close ( ) ; classBytes = baos . toByteArray ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; return null ; } return classBytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call and wrap { @link Exception } s into a { @link RuntimeException } [CODESPLIT] public static < T > T wrapException ( final Callable < T > callable ) { try { return callable . call ( ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Call and wrap { @link Exception } s into an exception provided by the function . <p > If the function returns { @code null } a { @link RuntimeException } will be created instead . < / p > [CODESPLIT] public static < T > T wrapException ( final Callable < T > callable , final Function < Exception , RuntimeException > func ) { try { return callable . call ( ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { RuntimeException t = func . apply ( e ) ; if ( t == null ) { t = new RuntimeException ( e ) ; } else { // fixing the stack trace to be a bit more precise t . setStackTrace ( Thread . currentThread ( ) . getStackTrace ( ) ) ; } throw t ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the basic authentication header [CODESPLIT] public static String [ ] parseAuthorization ( final HttpServletRequest request ) { final String auth = request . getHeader ( \"Authorization\" ) ; logger . debug ( \"Auth header: {}\" , auth ) ; if ( auth == null || auth . isEmpty ( ) ) { return null ; } final String [ ] toks = auth . split ( \"\\\\s\" ) ; if ( toks . length < 2 ) { return null ; } if ( ! \"Basic\" . equalsIgnoreCase ( toks [ 0 ] ) ) { return null ; } final byte [ ] authData = Base64 . getDecoder ( ) . decode ( toks [ 1 ] ) ; final String authStr = StandardCharsets . ISO_8859_1 . decode ( ByteBuffer . wrap ( authData ) ) . toString ( ) ; logger . debug ( \"Auth String: {}\" , authStr ) ; final String [ ] authToks = authStr . split ( \":\" , 2 ) ; logger . debug ( \"Auth tokens: {}\" , new Object [ ] { authToks } ) ; if ( authToks . length != 2 ) { return null ; } return authToks ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generated Servlet and Tag Handler implementations call this method to retrieve an instance of the ProtectedFunctionMapper . This is necessary since generated code does not have access to create instances of classes in this package . [CODESPLIT] public static ProtectedFunctionMapper getInstance ( ) { ProtectedFunctionMapper funcMapper ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { funcMapper = AccessController . doPrivileged ( new PrivilegedAction < ProtectedFunctionMapper > ( ) { public ProtectedFunctionMapper run ( ) { return new ProtectedFunctionMapper ( ) ; } } ) ; } else { funcMapper = new ProtectedFunctionMapper ( ) ; } funcMapper . fnmap = new java . util . HashMap < String , Method > ( ) ; return funcMapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stores a mapping from the given EL function prefix and name to the given Java method . [CODESPLIT] public void mapFunction ( String fnQName , final Class < ? > c , final String methodName , final Class < ? > [ ] args ) { java . lang . reflect . Method method ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { try { method = AccessController . doPrivileged ( new PrivilegedExceptionAction < Method > ( ) { public Method run ( ) throws Exception { return c . getDeclaredMethod ( methodName , args ) ; } } ) ; } catch ( PrivilegedActionException ex ) { throw new RuntimeException ( \"Invalid function mapping - no such method: \" + ex . getException ( ) . getMessage ( ) ) ; } } else { try { method = c . getDeclaredMethod ( methodName , args ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( \"Invalid function mapping - no such method: \" + e . getMessage ( ) ) ; } } this . fnmap . put ( fnQName , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance for this class and stores the Method for the given EL function prefix and name . This method is used for the case when there is only one function in the EL expression . [CODESPLIT] public static ProtectedFunctionMapper getMapForFunction ( String fnQName , final Class < ? > c , final String methodName , final Class < ? > [ ] args ) { java . lang . reflect . Method method ; ProtectedFunctionMapper funcMapper ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { funcMapper = AccessController . doPrivileged ( new PrivilegedAction < ProtectedFunctionMapper > ( ) { public ProtectedFunctionMapper run ( ) { return new ProtectedFunctionMapper ( ) ; } } ) ; try { method = AccessController . doPrivileged ( new PrivilegedExceptionAction < Method > ( ) { public Method run ( ) throws Exception { return c . getDeclaredMethod ( methodName , args ) ; } } ) ; } catch ( PrivilegedActionException ex ) { throw new RuntimeException ( \"Invalid function mapping - no such method: \" + ex . getException ( ) . getMessage ( ) ) ; } } else { funcMapper = new ProtectedFunctionMapper ( ) ; try { method = c . getDeclaredMethod ( methodName , args ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( \"Invalid function mapping - no such method: \" + e . getMessage ( ) ) ; } } funcMapper . theMethod = method ; return funcMapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the specified local name and prefix into a Java . lang . Method . Returns null if the prefix and local name are not found . [CODESPLIT] public Method resolveFunction ( String prefix , String localName ) { if ( this . fnmap != null ) { return this . fnmap . get ( prefix + \":\" + localName ) ; } return theMethod ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the contents of the XMLString structure with the specified values . [CODESPLIT] public void setValues ( char [ ] ch , int offset , int length ) { this . ch = ch ; this . offset = offset ; this . length = length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the contents of the XMLString structure with copies of the given string structure . <p > <strong > Note : < / strong > This does not copy the character array ; only the reference to the array is copied . [CODESPLIT] public void setValues ( XMLString s ) { setValues ( s . ch , s . offset , s . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "interface extensions [CODESPLIT] @ Override public List < MenuEntry > getViews ( final HttpServletRequest request , final Object object ) { if ( ! ( object instanceof ChannelId ) ) { return null ; } final ChannelId channel = ( ChannelId ) object ; final List < MenuEntry > result = new LinkedList <> ( ) ; final Map < String , Object > model = new HashMap <> ( 1 ) ; model . put ( \"channelId\" , channel . getId ( ) ) ; result . add ( new MenuEntry ( \"Help\" , 100_000 , \"Description\" , 1_000 , LinkTarget . createFromController ( DescriptionController . class , \"channelDescription\" ) . expand ( model ) , Modifier . DEFAULT , \"comment\" ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the specified variable within the given context . Returns null if the variable is not found . [CODESPLIT] public Object resolveVariable ( String pName ) throws javax . servlet . jsp . el . ELException { ELContext elContext = pageContext . getELContext ( ) ; ELResolver elResolver = elContext . getELResolver ( ) ; try { return elResolver . getValue ( elContext , null , pName ) ; } catch ( javax . el . ELException ex ) { throw new javax . servlet . jsp . el . ELException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a JSP page or tag file . This is invoked by the compiler . [CODESPLIT] public Node . Nodes parse ( String inFileName ) throws FileNotFoundException , JasperException , IOException { // If we're parsing a packaged tag file or a resource included by it // (using an include directive), ctxt.getTagFileJar() returns the  // JAR file from which to read the tag file or included resource, // respectively. isTagFile = ctxt . isTagFile ( ) ; directiveOnly = false ; return doParse ( inFileName , null , ctxt . getTagFileJarUrl ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes an include directive with the given path . [CODESPLIT] public Node . Nodes parse ( String inFileName , Node parent , URL jarFileUrl ) throws FileNotFoundException , JasperException , IOException { // For files that are statically included, isTagfile and directiveOnly // remain unchanged. return doParse ( inFileName , parent , jarFileUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts tag file directive information from the tag file with the given name . [CODESPLIT] public Node . Nodes parseTagFileDirectives ( String inFileName ) throws FileNotFoundException , JasperException , IOException { boolean isTagFileSave = isTagFile ; boolean directiveOnlySave = directiveOnly ; isTagFile = true ; directiveOnly = true ; Node . Nodes page = doParse ( inFileName , null , ( URL ) ctxt . getTagFileJarUrls ( ) . get ( inFileName ) ) ; directiveOnly = directiveOnlySave ; isTagFile = isTagFileSave ; return page ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the JSP page or tag file with the given path name . [CODESPLIT] private Node . Nodes doParse ( String inFileName , Node parent , URL jarFileUrl ) throws FileNotFoundException , JasperException , IOException { Node . Nodes parsedPage = null ; isEncodingSpecifiedInProlog = false ; isDefaultPageEncoding = false ; hasBom = false ; JarFile jarFile = getJarFile ( jarFileUrl ) ; String absFileName = resolveFileName ( inFileName ) ; String jspConfigPageEnc = getJspConfigPageEncoding ( absFileName ) ; // Figure out what type of JSP document and encoding type we are // dealing with determineSyntaxAndEncoding ( absFileName , jarFile , jspConfigPageEnc ) ; if ( parent != null ) { // Included resource, add to dependent list compiler . getPageInfo ( ) . addDependant ( absFileName ) ; } comparePageEncodings ( jspConfigPageEnc ) ; // Dispatch to the appropriate parser if ( isXml ) { // JSP document (XML syntax) // InputStream for jspx page is created and properly closed in // JspDocumentParser. parsedPage = JspDocumentParser . parse ( this , absFileName , jarFile , parent , isTagFile , directiveOnly , sourceEnc , jspConfigPageEnc , isEncodingSpecifiedInProlog ) ; } else { // Standard syntax InputStreamReader inStreamReader = null ; try { inStreamReader = JspUtil . getReader ( absFileName , sourceEnc , jarFile , ctxt , err ) ; JspReader jspReader = new JspReader ( ctxt , absFileName , sourceEnc , inStreamReader , err ) ; parsedPage = Parser . parse ( this , absFileName , jspReader , parent , isTagFile , directiveOnly , jarFileUrl , sourceEnc , jspConfigPageEnc , isDefaultPageEncoding , hasBom ) ; } finally { if ( inStreamReader != null ) { try { inStreamReader . close ( ) ; } catch ( Exception any ) { } } } } if ( jarFile != null ) { try { jarFile . close ( ) ; } catch ( Throwable t ) { } } baseDirStack . pop ( ) ; return parsedPage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Ensures that the page encoding specified in the JSP config element ( with matching URL pattern ) if present matches the page encoding specified in the XML prolog of a JSP document ( XML syntax ) and the page encoding derived from the BOM . [CODESPLIT] private void comparePageEncodings ( String jspConfigPageEnc ) throws JasperException { if ( jspConfigPageEnc == null ) { return ; } if ( isXml && isEncodingSpecifiedInProlog ) { /*\n             * Make sure the encoding specified in the XML prolog matches\n             * that in the JSP config element, treating \"UTF-16\", \"UTF-16BE\",\n             * and \"UTF-16LE\" as identical.\n             */ if ( ! jspConfigPageEnc . equalsIgnoreCase ( sourceEnc ) && ( ! jspConfigPageEnc . toLowerCase ( ) . startsWith ( \"utf-16\" ) || ! sourceEnc . toLowerCase ( ) . startsWith ( \"utf-16\" ) ) ) { err . jspError ( \"jsp.error.prolog_config_encoding_mismatch\" , sourceEnc , jspConfigPageEnc ) ; } } if ( hasBom ) { /*\n             * Make sure the encoding specified in the BOM matches\n             * that in the JSP config element, treating \"UTF-16\", \"UTF-16BE\",\n             * and \"UTF-16LE\" as identical.\n             */ if ( ! jspConfigPageEnc . equalsIgnoreCase ( sourceEnc ) && ( ! jspConfigPageEnc . toLowerCase ( ) . startsWith ( \"utf-16\" ) || ! sourceEnc . toLowerCase ( ) . startsWith ( \"utf-16\" ) ) ) { err . jspError ( \"jsp.error.bom_config_encoding_mismatch\" , sourceEnc , jspConfigPageEnc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks to see if the given URI is matched by a URL pattern specified in a jsp - property - group in web . xml and if so returns the value of the <page - encoding > element . [CODESPLIT] private String getJspConfigPageEncoding ( String absFileName ) throws JasperException { JspConfig jspConfig = ctxt . getOptions ( ) . getJspConfig ( ) ; JspProperty jspProperty = jspConfig . findJspProperty ( absFileName ) ; return jspProperty . getPageEncoding ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines the syntax ( standard or XML ) and page encoding properties for the given file and stores them in the isXml and sourceEnc instance variables respectively . [CODESPLIT] private void determineSyntaxAndEncoding ( String absFileName , JarFile jarFile , String jspConfigPageEnc ) throws JasperException , IOException { isXml = false ; /*\n\t * 'true' if the syntax (XML or standard) of the file is given\n\t * from external information: either via a JSP configuration element,\n\t * the \".jspx\" suffix, or the enclosing file (for included resources)\n\t */ boolean isExternal = false ; /*\n\t * Indicates whether we need to revert from temporary usage of\n\t * \"ISO-8859-1\" back to \"UTF-8\"\n\t */ boolean revert = false ; JspConfig jspConfig = ctxt . getOptions ( ) . getJspConfig ( ) ; JspProperty jspProperty = jspConfig . findJspProperty ( absFileName ) ; if ( jspProperty . isXml ( ) != null ) { // If <is-xml> is specified in a <jsp-property-group>, it is used. isXml = JspUtil . booleanValue ( jspProperty . isXml ( ) ) ; isExternal = true ; } else if ( absFileName . endsWith ( \".jspx\" ) || absFileName . endsWith ( \".tagx\" ) ) { isXml = true ; isExternal = true ; } if ( isExternal && ! isXml ) { // JSP (standard) syntax. Use encoding specified in jsp-config // if provided. sourceEnc = jspConfigPageEnc ; if ( sourceEnc != null ) { return ; } // We don't know the encoding sourceEnc = \"ISO-8859-1\" ; } else { // XML syntax or unknown, (auto)detect encoding ... Object [ ] ret = XMLEncodingDetector . getEncoding ( absFileName , jarFile , ctxt , err ) ; sourceEnc = ( String ) ret [ 0 ] ; if ( ( ( Boolean ) ret [ 1 ] ) . booleanValue ( ) ) { isEncodingSpecifiedInProlog = true ; } if ( ret [ 2 ] != null && ( ( Boolean ) ret [ 2 ] ) . booleanValue ( ) ) { hasBom = true ; } if ( ! isXml && sourceEnc . equalsIgnoreCase ( \"utf-8\" ) && ! hasBom ) { /*\n\t\t * We don't know if we're dealing with XML or standard syntax.\n\t\t * Therefore, we need to check to see if the page contains\n\t\t * a <jsp:root> element.\n\t\t *\n                 * We need to be careful, because the page may be encoded in\n                 * ISO-8859-1 (or something entirely different: UTF-8 was \n                 * chosen as the default, for lack of better alternative),\n                 * and may contain byte sequences that will cause a UTF-8\n                 * converter to throw exceptions. \n\t\t *\n\t\t * It is safe to use a source encoding of ISO-8859-1 in this\n\t\t * case, as there are no invalid byte sequences in ISO-8859-1,\n\t\t * and the byte/character sequences we're looking for (i.e.,\n\t\t * <jsp:root>) are identical in either encoding (both UTF-8\n\t\t * and ISO-8859-1 are extensions of ASCII).\n\t\t */ sourceEnc = \"ISO-8859-1\" ; revert = true ; } } if ( isXml ) { // (This implies 'isExternal' is TRUE.) // We know we're dealing with a JSP document (via JSP config or // \".jspx\" suffix), so we're done. return ; } /*\n\t * At this point, 'isExternal' or 'isXml' is FALSE.\n\t * Search for jsp:root action, in order to determine if we're dealing \n\t * with XML or standard syntax (unless we already know what we're \n\t * dealing with, i.e., when 'isExternal' is TRUE and 'isXml' is FALSE).\n\t * No check for XML prolog, since nothing prevents a page from\n\t * outputting XML and still using JSP syntax (in this case, the \n\t * XML prolog is treated as template text).\n\t */ JspReader jspReader = null ; try { jspReader = new JspReader ( ctxt , absFileName , sourceEnc , jarFile , err ) ; } catch ( FileNotFoundException ex ) { throw new JasperException ( ex ) ; } jspReader . setSingleFile ( true ) ; Mark startMark = jspReader . mark ( ) ; if ( ! isExternal ) { jspReader . reset ( startMark ) ; if ( hasJspRoot ( jspReader ) ) { isXml = true ; if ( revert ) sourceEnc = \"UTF-8\" ; return ; } else { isXml = false ; } } /*\n\t * At this point, we know we're dealing with JSP syntax.\n\t * If an XML prolog is provided, it's treated as template text.\n\t * Determine the page encoding from the page directive, unless it's\n\t * specified via JSP config.\n\t */ if ( ! hasBom ) { sourceEnc = jspConfigPageEnc ; } if ( sourceEnc == null ) { sourceEnc = getPageEncodingForJspSyntax ( jspReader , startMark ) ; if ( sourceEnc == null ) { // Default to \"ISO-8859-1\" per JSP spec sourceEnc = \"ISO-8859-1\" ; isDefaultPageEncoding = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Determines page source encoding for page or tag file in JSP syntax by reading ( in this order ) the value of the pageEncoding page directive attribute or the charset value of the contentType page directive attribute . [CODESPLIT] private String getPageEncodingForJspSyntax ( JspReader jspReader , Mark startMark ) throws JasperException { String encoding = null ; String saveEncoding = null ; jspReader . reset ( startMark ) ; /*\n\t * Determine page encoding from directive of the form <%@ page %>,\n\t * <%@ tag %>, <jsp:directive.page > or <jsp:directive.tag >.\n\t */ while ( true ) { if ( jspReader . skipUntil ( \"<\" ) == null ) { break ; } // If this is a comment, skip until its end if ( jspReader . matches ( \"%--\" ) ) { if ( jspReader . skipUntil ( \"--%>\" ) == null ) { // error will be caught in Parser break ; } continue ; } boolean isDirective = jspReader . matches ( \"%@\" ) ; if ( isDirective ) { jspReader . skipSpaces ( ) ; } else { isDirective = jspReader . matches ( \"jsp:directive.\" ) ; } if ( ! isDirective ) { continue ; } // compare for \"tag \", so we don't match \"taglib\" if ( jspReader . matches ( \"tag \" ) || jspReader . matches ( \"page\" ) ) { jspReader . skipSpaces ( ) ; Attributes attrs = Parser . parseAttributes ( this , jspReader ) ; encoding = getPageEncodingFromDirective ( attrs , \"pageEncoding\" ) ; if ( encoding != null ) { break ; } encoding = getPageEncodingFromDirective ( attrs , \"contentType\" ) ; if ( encoding != null ) { saveEncoding = encoding ; } } } if ( encoding == null ) { encoding = saveEncoding ; } return encoding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Scans the given attributes for the attribute with the given name which is either pageEncoding or contentType and returns the specified page encoding . [CODESPLIT] private String getPageEncodingFromDirective ( Attributes attrs , String attrName ) { String value = attrs . getValue ( attrName ) ; if ( attrName . equals ( \"pageEncoding\" ) ) { return value ; } // attrName = contentType String contentType = value ; String encoding = null ; if ( contentType != null ) { int loc = contentType . indexOf ( CHARSET ) ; if ( loc != - 1 ) { encoding = contentType . substring ( loc + CHARSET . length ( ) ) ; } } return encoding ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Resolve the name of the file and update baseDirStack () to keep track of the current base directory for each included file . The root file is always an absolute path so no need to put an initial value in the baseDirStack . [CODESPLIT] private String resolveFileName ( String inFileName ) { String fileName = inFileName . replace ( ' ' , ' ' ) ; boolean isAbsolute = fileName . startsWith ( \"/\" ) ; fileName = isAbsolute ? fileName : baseDirStack . peek ( ) + fileName ; String baseDir = fileName . substring ( 0 , fileName . lastIndexOf ( \"/\" ) + 1 ) ; baseDirStack . push ( baseDir ) ; return fileName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Checks to see if the given page contains as its first element a <root > element whose prefix is bound to the JSP namespace as in : [CODESPLIT] private boolean hasJspRoot ( JspReader reader ) throws JasperException { // <prefix>:root must be the first element Mark start = null ; while ( ( start = reader . skipUntil ( \"<\" ) ) != null ) { int c = reader . nextChar ( ) ; if ( c != ' ' && c != ' ' ) break ; } if ( start == null ) { return false ; } Mark stop = reader . skipUntil ( \":root\" ) ; if ( stop == null ) { return false ; } // call substring to get rid of leading '<' String prefix = reader . getText ( start , stop ) . substring ( 1 ) ; start = stop ; stop = reader . skipUntil ( \">\" ) ; if ( stop == null ) { return false ; } // Determine namespace associated with <root> element's prefix String root = reader . getText ( start , stop ) ; String xmlnsDecl = \"xmlns:\" + prefix ; int index = root . indexOf ( xmlnsDecl ) ; if ( index == - 1 ) { return false ; } index += xmlnsDecl . length ( ) ; while ( index < root . length ( ) && Character . isWhitespace ( root . charAt ( index ) ) ) { index ++ ; } if ( index < root . length ( ) && root . charAt ( index ) == ' ' ) { index ++ ; while ( index < root . length ( ) && Character . isWhitespace ( root . charAt ( index ) ) ) { index ++ ; } if ( index < root . length ( ) && root . charAt ( index ++ ) == ' ' && root . regionMatches ( index , JSP_URI , 0 , JSP_URI . length ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a Compiler object . [CODESPLIT] public Compiler createCompiler ( boolean jspcMode ) throws JasperException { if ( jspCompiler != null ) { return jspCompiler ; } jspCompiler = new Compiler ( this , jsw , jspcMode ) ; return jspCompiler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a resource as a stream relative to the meanings of this context s implementation . [CODESPLIT] public java . io . InputStream getResourceAsStream ( String res ) throws JasperException { return context . getResourceAsStream ( canonicalURI ( res ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the location of the TLD associated with the given taglib uri . [CODESPLIT] public String [ ] getTldLocation ( String uri ) throws JasperException { String [ ] location = getOptions ( ) . getTldScanner ( ) . getLocation ( uri ) ; return location ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================== Removal ==================== [CODESPLIT] public void incrementRemoved ( ) { if ( removed > 1 ) { jspCompiler . removeGeneratedFiles ( ) ; if ( rctxt != null ) rctxt . removeWrapper ( jspUri ) ; } removed ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================== Compile and reload ==================== [CODESPLIT] public void compile ( ) throws JasperException , FileNotFoundException { createCompiler ( false ) ; if ( jspCompiler . isOutDated ( ) ) { try { jspCompiler . compile ( true ) ; jsw . setReload ( true ) ; jsw . setCompilationException ( null ) ; } catch ( JasperException ex ) { // Cache compilation exception jsw . setCompilationException ( ex ) ; throw ex ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; JasperException je = new JasperException ( Localizer . getMessage ( \"jsp.error.unable.compile\" ) , ex ) ; // Cache compilation exception jsw . setCompilationException ( je ) ; throw je ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================== Manipulating the class ==================== [CODESPLIT] public Class load ( ) throws JasperException , ClassNotFoundException { try { String name = getFullClassName ( ) ; if ( options . getUsePrecompiled ( ) ) { servletClass = getClassLoader ( ) . loadClass ( name ) ; } else { servletClass = getJspLoader ( ) . loadClass ( name ) ; } } catch ( ClassNotFoundException cex ) { // Do not wrapper this in JasperException if use-precompiled is set, // because this is really a 404. if ( options . getUsePrecompiled ( ) ) { throw cex ; } throw new JasperException ( Localizer . getMessage ( \"jsp.error.unable.load\" ) , cex ) ; } catch ( Exception ex ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.unable.compile\" ) , ex ) ; } removed = 0 ; return servletClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a single character . This method will block until a character is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( ) throws IOException { int b0 = fInputStream . read ( ) ; if ( b0 > 0x80 ) { throw new IOException ( Localizer . getMessage ( \"jsp.error.xml.invalidASCII\" , Integer . toString ( b0 ) ) ) ; } return b0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read characters into a portion of an array . This method will block until some input is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( char ch [ ] , int offset , int length ) throws IOException { if ( length > fBuffer . length ) { length = fBuffer . length ; } int count = fInputStream . read ( fBuffer , 0 , length ) ; for ( int i = 0 ; i < count ; i ++ ) { int b0 = fBuffer [ i ] ; if ( b0 < 0 ) { throw new IOException ( Localizer . getMessage ( \"jsp.error.xml.invalidASCII\" , Integer . toString ( b0 ) ) ) ; } ch [ offset + i ] = ( char ) b0 ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the last modification timestamp of all channels [CODESPLIT] private Optional < Instant > calcLastMod ( ) { Instant globalLastMod = null ; for ( final ChannelInformation ci : this . channelService . list ( ) ) { final Optional < Instant > lastMod = ofNullable ( ci . getState ( ) . getModificationTimestamp ( ) ) ; if ( globalLastMod == null || lastMod . get ( ) . isAfter ( globalLastMod ) ) { globalLastMod = lastMod . get ( ) ; } } return Optional . ofNullable ( globalLastMod ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We assume that the bootclassloader never uses the context classloader to find classes in itself . [CODESPLIT] ArrayList basicFindClassLoaders ( ) { Class [ ] stack = contextFinder . getClassContext ( ) ; ArrayList result = new ArrayList ( 1 ) ; ClassLoader previousLoader = null ; for ( int i = 1 ; i < stack . length ; i ++ ) { ClassLoader tmp = stack [ i ] . getClassLoader ( ) ; if ( checkClass ( stack [ i ] ) && tmp != null && tmp != this ) { if ( checkClassLoader ( tmp ) ) { if ( previousLoader != tmp ) { result . add ( tmp ) ; previousLoader = tmp ; } } // stop at the framework classloader or the first bundle classloader if ( Activator . getBundle ( stack [ i ] ) != null ) break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "not be used as a delegate otherwise we endup in endless recursion . [CODESPLIT] private boolean checkClassLoader ( ClassLoader classloader ) { if ( classloader == null || classloader == getParent ( ) ) return false ; for ( ClassLoader parent = classloader . getParent ( ) ; parent != null ; parent = parent . getParent ( ) ) if ( parent == this ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "False is returned when a cycle is being detected [CODESPLIT] private boolean startLoading ( String name ) { Set classesAndResources = ( Set ) cycleDetector . get ( ) ; if ( classesAndResources != null && classesAndResources . contains ( name ) ) return false ; if ( classesAndResources == null ) { classesAndResources = new HashSet ( 3 ) ; cycleDetector . set ( classesAndResources ) ; } classesAndResources . add ( name ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the Stream Header into a buffer . This is a helper function for the constructors . [CODESPLIT] private static byte [ ] readStreamHeader ( InputStream in ) throws IOException { byte [ ] streamHeader = new byte [ DecoderUtil . STREAM_HEADER_SIZE ] ; new DataInputStream ( in ) . readFully ( streamHeader ) ; return streamHeader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decompresses into an array of bytes . <p > If <code > len< / code > is zero no bytes are read and <code > 0< / code > is returned . Otherwise this will try to decompress <code > len< / code > bytes of uncompressed data . Less than <code > len< / code > bytes may be read only in the following situations : <ul > <li > The end of the compressed data was reached successfully . < / li > <li > An error is detected after at least one but less <code > len< / code > bytes have already been successfully decompressed . The next call with non - zero <code > len< / code > will immediately throw the pending exception . < / li > <li > An exception is thrown . < / li > < / ul > [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; if ( endReached ) return - 1 ; int size = 0 ; try { while ( len > 0 ) { if ( blockDecoder == null ) { try { blockDecoder = new BlockInputStream ( in , check , verifyCheck , memoryLimit , - 1 , - 1 , arrayCache ) ; } catch ( IndexIndicatorException e ) { indexHash . validate ( in ) ; validateStreamFooter ( ) ; endReached = true ; return size > 0 ? size : - 1 ; } } int ret = blockDecoder . read ( buf , off , len ) ; if ( ret > 0 ) { size += ret ; off += ret ; len -= ret ; } else if ( ret == - 1 ) { indexHash . add ( blockDecoder . getUnpaddedSize ( ) , blockDecoder . getUncompressedSize ( ) ) ; blockDecoder = null ; } } } catch ( IOException e ) { exception = e ; if ( size == 0 ) throw e ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of uncompressed bytes that can be read without blocking . The value is returned with an assumption that the compressed input data will be valid . If the compressed data is corrupt <code > CorruptedInputException< / code > may get thrown before the number of bytes claimed to be available have been read from this input stream . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; return blockDecoder == null ? 0 : blockDecoder . available ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the stream and optionally calls <code > in . close () < / code > . If the stream was already closed this does nothing . If <code > close ( false ) < / code > has been called a further call of <code > close ( true ) < / code > does nothing ( it doesn t call <code > in . close () < / code > ) . <p > If you don t want to close the underlying <code > InputStream< / code > there is usually no need to worry about closing this stream either ; it s fine to do nothing and let the garbage collector handle it . However if you are using { @link ArrayCache } <code > close ( false ) < / code > can be useful to put the allocated arrays back to the cache without closing the underlying <code > InputStream< / code > . <p > Note that if you successfully reach the end of the stream ( <code > read< / code > returns <code > - 1< / code > ) the arrays are automatically put back to the cache by that <code > read< / code > call . In this situation <code > close ( false ) < / code > is redundant ( but harmless ) . [CODESPLIT] public void close ( boolean closeInput ) throws IOException { if ( in != null ) { if ( blockDecoder != null ) { blockDecoder . close ( ) ; blockDecoder = null ; } try { if ( closeInput ) in . close ( ) ; } finally { in = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Paginate from a full data set [CODESPLIT] public static < T > PaginationResult < T > paginate ( final Integer startPage , final int pageSize , final List < T > fullDataSet ) { return paginate ( startPage , pageSize , ( start , length ) -> { final int len = fullDataSet . size ( ) ; if ( start > len ) { return Collections . emptyList ( ) ; } return fullDataSet . subList ( start , Math . min ( start + length , len ) ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls { [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { return randomAccessFile . read ( buf , off , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string to a MetaKey if possible [CODESPLIT] public static MetaKey fromString ( final String string ) { final int idx = string . indexOf ( ' ' ) ; if ( idx < 1 ) { // -1: none at all, 0: empty namespace return null ; } if ( idx + 1 >= string . length ( ) ) { // empty key segment return null ; } return new MetaKey ( string . substring ( 0 , idx ) , string . substring ( idx + 1 ) , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill extra requirements the RPM file itself may have [CODESPLIT] private void fillRequirements ( ) throws IOException { this . requirements . add ( new Dependency ( \"rpmlib(CompressedFileNames)\" , \"3.0.4-1\" , RpmDependencyFlags . LESS , RpmDependencyFlags . EQUAL , RpmDependencyFlags . RPMLIB ) ) ; if ( ! this . options . getFileDigestAlgorithm ( ) . equals ( DigestAlgorithm . MD5 ) ) { this . requirements . add ( new Dependency ( \"rpmlib(FileDigests)\" , \"4.6.0-1\" , RpmDependencyFlags . LESS , RpmDependencyFlags . EQUAL , RpmDependencyFlags . RPMLIB ) ) ; } this . requirements . add ( new Dependency ( \"rpmlib(PayloadFilesHavePrefix)\" , \"4.0-1\" , RpmDependencyFlags . LESS , RpmDependencyFlags . EQUAL , RpmDependencyFlags . RPMLIB ) ) ; this . options . getPayloadCoding ( ) . createProvider ( ) . fillRequirements ( this . requirements :: add ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actually build the RPM file <p > <strong > Note : < / strong > this method may only be called once per instance < / p > [CODESPLIT] public void build ( ) throws IOException { if ( this . hasBuilt ) { throw new IllegalStateException ( \"RPM file has already been built. Can only be built once.\" ) ; } this . hasBuilt = true ; fillProvides ( ) ; fillRequirements ( ) ; fillHeader ( ) ; final LeadBuilder leadBuilder = new LeadBuilder ( this . name , this . version ) ; leadBuilder . fillFlagsFromHeader ( this . header , createLeadArchitectureMapper ( ) , createLeadOperatingSystemMapper ( ) ) ; if ( this . headerCustomizer != null ) { this . headerCustomizer . accept ( this . header ) ; } try ( final RpmWriter writer = new RpmWriter ( this . targetFile , leadBuilder , this . header , this . options . getHeaderCharset ( ) , this . options . getOpenOptions ( ) ) ) { writer . addAllSignatureProcessors ( this . signatureProcessors ) ; writer . setPayload ( this . recorder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of TagLibraryInfo objects representing the entire set of tag libraries ( including this TagLibraryInfo ) imported by taglib directives in the translation unit that references this TagLibraryInfo . [CODESPLIT] public TagLibraryInfo [ ] getTagLibraryInfos ( ) { TagLibraryInfo [ ] taglibs = null ; Collection c = pageInfo . getTaglibs ( ) ; if ( c != null ) { Object [ ] objs = c . toArray ( ) ; if ( objs != null && objs . length > 0 ) { taglibs = new TagLibraryInfo [ objs . length ] ; for ( int i = 0 ; i < objs . length ; i ++ ) { taglibs [ i ] = ( TagLibraryInfo ) objs [ i ] ; } } } return taglibs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the given tag name maps to a tag file path and if so parses the corresponding tag file . [CODESPLIT] public TagFileInfo getTagFile ( String shortName ) { TagFileInfo tagFile = super . getTagFile ( shortName ) ; if ( tagFile == null ) { String path = tagFileMap . get ( shortName ) ; if ( path == null ) { return null ; } TagInfo tagInfo = null ; try { tagInfo = TagFileProcessor . parseTagFileDirectives ( pc , shortName , path , this ) ; } catch ( JasperException je ) { throw new RuntimeException ( je . toString ( ) ) ; } tagFile = new TagFileInfo ( shortName , path , tagInfo ) ; vec . add ( tagFile ) ; this . tagFiles = vec . toArray ( new TagFileInfo [ vec . size ( ) ] ) ; } return tagFile ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the JSP version and tlib - version from the implicit . tld at the given path . [CODESPLIT] private void parseImplicitTld ( JspCompilationContext ctxt , String path ) throws JasperException { InputStream is = null ; TreeNode tld = null ; try { URL uri = ctxt . getResource ( path ) ; if ( uri == null ) { // no implicit.tld return ; } is = uri . openStream ( ) ; /* SJSAS 6384538\n            tld = new ParserUtils().parseXMLDocument(IMPLICIT_TLD, is);\n            */ // START SJSAS 6384538 tld = new ParserUtils ( ) . parseXMLDocument ( IMPLICIT_TLD , is , ctxt . getOptions ( ) . isValidationEnabled ( ) ) ; // END SJSAS 6384538 } catch ( Exception ex ) { throw new JasperException ( ex ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Throwable t ) { } } } this . jspversion = tld . findAttribute ( \"version\" ) ; Iterator list = tld . findChildren ( ) ; while ( list . hasNext ( ) ) { TreeNode element = ( TreeNode ) list . next ( ) ; String tname = element . getName ( ) ; if ( \"tlibversion\" . equals ( tname ) || \"tlib-version\" . equals ( tname ) ) { this . tlibversion = element . getBody ( ) ; } else if ( \"jspversion\" . equals ( tname ) || \"jsp-version\" . equals ( tname ) ) { this . jspversion = element . getBody ( ) ; } else if ( ! \"shortname\" . equals ( tname ) && ! \"short-name\" . equals ( tname ) ) { err . jspError ( \"jsp.error.implicitTld.additionalElements\" , path , tname ) ; } } // JSP version in implicit.tld must be 2.0 or greater Double jspVersionDouble = Double . valueOf ( this . jspversion ) ; if ( Double . compare ( jspVersionDouble , Constants . JSP_VERSION_2_0 ) < 0 ) { err . jspError ( \"jsp.error.implicitTld.jspVersion\" , path , this . jspversion ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the digest of a closed file [CODESPLIT] public String getChecksum ( final String fileName , final String algorithm ) { if ( ! this . digests . contains ( algorithm ) ) { return null ; } final String result = this . checksums . get ( fileName + \":\" + algorithm ) ; if ( result == null ) { throw new IllegalStateException ( String . format ( \"Stream '%s' not closed.\" , fileName ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the size of a closed file [CODESPLIT] public long getSize ( final String fileName ) { final Long result = this . sizes . get ( fileName ) ; if ( result == null ) { throw new IllegalStateException ( String . format ( \"Stream '%s' not closed or was not added\" , fileName ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the name of the channel [CODESPLIT] private static void validateChannelName ( final String name , final ValidationContext ctx ) { if ( name == null || name . isEmpty ( ) ) { return ; } final Matcher m = ChannelService . NAME_PATTERN . matcher ( name ) ; if ( ! m . matches ( ) ) { ctx . error ( \"names\" , String . format ( \"The channel name '%s' must match the pattern '%s'\" , name , ChannelService . NAME_PATTERN . pattern ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Seeks <code > n< / code > bytes forward in this stream . <p > This will not seek past the end of the file . If the current position is already at or past the end of the file this doesn t seek at all and returns <code > 0< / code > . Otherwise if skipping <code > n< / code > bytes would cause the position to exceed the stream size this will do equivalent of <code > seek ( length () ) < / code > and the return value will be adjusted accordingly . <p > If <code > n< / code > is negative the position isn t changed and the return value is <code > 0< / code > . It doesn t seek backward because it would conflict with the specification of { @link java . io . InputStream#skip ( long ) InputStream . skip } . [CODESPLIT] public long skip ( long n ) throws IOException { if ( n <= 0 ) return 0 ; long size = length ( ) ; long pos = position ( ) ; if ( pos >= size ) return 0 ; if ( size - pos < n ) n = size - pos ; seek ( pos + n ) ; return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets how much memory the encoder will need with the given filter chain . This function simply calls <code > getEncoderMemoryUsage () < / code > for every filter in the array and returns the sum of the returned values . [CODESPLIT] public static int getEncoderMemoryUsage ( FilterOptions [ ] options ) { int m = 0 ; for ( int i = 0 ; i < options . length ; ++ i ) m += options [ i ] . getEncoderMemoryUsage ( ) ; return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets how much memory the decoder will need with the given filter chain . This function simply calls <code > getDecoderMemoryUsage () < / code > for every filter in the array and returns the sum of the returned values . [CODESPLIT] public static int getDecoderMemoryUsage ( FilterOptions [ ] options ) { int m = 0 ; for ( int i = 0 ; i < options . length ; ++ i ) m += options [ i ] . getDecoderMemoryUsage ( ) ; return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decompresses into an array of bytes . <p > If <code > len< / code > is zero no bytes are read and <code > 0< / code > is returned . Otherwise this will try to decompress <code > len< / code > bytes of uncompressed data . Less than <code > len< / code > bytes may be read only in the following situations : <ul > <li > The end of the compressed data was reached successfully . < / li > <li > An error is detected after at least one but less than <code > len< / code > bytes have already been successfully decompressed . The next call with non - zero <code > len< / code > will immediately throw the pending exception . < / li > <li > An exception is thrown . < / li > < / ul > [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; int size = 0 ; try { if ( seekNeeded ) seek ( ) ; if ( endReached ) return - 1 ; while ( len > 0 ) { if ( blockDecoder == null ) { seek ( ) ; if ( endReached ) break ; } int ret = blockDecoder . read ( buf , off , len ) ; if ( ret > 0 ) { curPos += ret ; size += ret ; off += ret ; len -= ret ; } else if ( ret == - 1 ) { blockDecoder = null ; } } } catch ( IOException e ) { // We know that the file isn't simply truncated because we could // parse the Indexes in the constructor. So convert EOFException // to CorruptedInputException. if ( e instanceof EOFException ) e = new CorruptedInputException ( ) ; exception = e ; if ( size == 0 ) throw e ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of uncompressed bytes that can be read without blocking . The value is returned with an assumption that the compressed input data will be valid . If the compressed data is corrupt <code > CorruptedInputException< / code > may get thrown before the number of bytes claimed to be available have been read from this input stream . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; if ( endReached || seekNeeded || blockDecoder == null ) return 0 ; return blockDecoder . available ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Seeks to the specified absolute uncompressed position in the stream . This only stores the new position so this function itself is always very fast . The actual seek is done when <code > read< / code > is called to read at least one byte . <p > Seeking past the end of the stream is possible . In that case <code > read< / code > will return <code > - 1< / code > to indicate the end of the stream . [CODESPLIT] public void seek ( long pos ) throws IOException { if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( pos < 0 ) throw new XZIOException ( \"Negative seek position: \" + pos ) ; seekPos = pos ; seekNeeded = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Seeks to the beginning of the given XZ Block . [CODESPLIT] public void seekToBlock ( int blockNumber ) throws IOException { if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( blockNumber < 0 || blockNumber >= blockCount ) throw new XZIOException ( \"Invalid XZ Block number: \" + blockNumber ) ; // This is a bit silly implementation. Here we locate the uncompressed // offset of the specified Block, then when doing the actual seek in // seek(), we need to find the Block number based on seekPos. seekPos = getBlockPos ( blockNumber ) ; seekNeeded = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the actual seeking . This is also called when <code > read< / code > needs a new Block to decode . [CODESPLIT] private void seek ( ) throws IOException { // If seek(long) wasn't called, we simply need to get the next Block // from the same Stream. If there are no more Blocks in this Stream, // then we behave as if seek(long) had been called. if ( ! seekNeeded ) { if ( curBlockInfo . hasNext ( ) ) { curBlockInfo . setNext ( ) ; initBlockDecoder ( ) ; return ; } seekPos = curPos ; } seekNeeded = false ; // Check if we are seeking to or past the end of the file. if ( seekPos >= uncompressedSize ) { curPos = seekPos ; if ( blockDecoder != null ) { blockDecoder . close ( ) ; blockDecoder = null ; } endReached = true ; return ; } endReached = false ; // Locate the Block that contains the uncompressed target position. locateBlockByPos ( curBlockInfo , seekPos ) ; // Seek in the underlying stream and create a new Block decoder // only if really needed. We can skip it if the current position // is already in the correct Block and the target position hasn't // been decompressed yet. // // NOTE: If curPos points to the beginning of this Block, it's // because it was left there after decompressing an earlier Block. // In that case, decoding of the current Block hasn't been started // yet. (Decoding of a Block won't be started until at least one // byte will also be read from it.) if ( ! ( curPos > curBlockInfo . uncompressedOffset && curPos <= seekPos ) ) { // Seek to the beginning of the Block. in . seek ( curBlockInfo . compressedOffset ) ; // Since it is possible that this Block is from a different // Stream than the previous Block, initialize a new Check. check = Check . getInstance ( curBlockInfo . getCheckType ( ) ) ; // Create a new Block decoder. initBlockDecoder ( ) ; curPos = curBlockInfo . uncompressedOffset ; } // If the target wasn't at a Block boundary, decompress and throw // away data to reach the target position. if ( seekPos > curPos ) { // NOTE: The \"if\" below is there just in case. In this situation, // blockDecoder.skip will always skip the requested amount // or throw an exception. long skipAmount = seekPos - curPos ; if ( blockDecoder . skip ( skipAmount ) != skipAmount ) throw new CorruptedInputException ( ) ; curPos = seekPos ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates the Block that contains the given uncompressed position . [CODESPLIT] private void locateBlockByPos ( BlockInfo info , long pos ) { if ( pos < 0 || pos >= uncompressedSize ) throw new IndexOutOfBoundsException ( \"Invalid uncompressed position: \" + pos ) ; // Locate the Stream that contains the target position. IndexDecoder index ; for ( int i = 0 ; ; ++ i ) { index = streams . get ( i ) ; if ( index . hasUncompressedOffset ( pos ) ) break ; } // Locate the Block from the Stream that contains the target position. index . locateBlock ( info , pos ) ; assert ( info . compressedOffset & 3 ) == 0 ; assert info . uncompressedSize > 0 ; assert pos >= info . uncompressedOffset ; assert pos < info . uncompressedOffset + info . uncompressedSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates the given Block and stores information about it to <code > info< / code > . [CODESPLIT] private void locateBlockByNumber ( BlockInfo info , int blockNumber ) { // Validate. if ( blockNumber < 0 || blockNumber >= blockCount ) throw new IndexOutOfBoundsException ( \"Invalid XZ Block number: \" + blockNumber ) ; // Skip the search if info already points to the correct Block. if ( info . blockNumber == blockNumber ) return ; // Search the Stream that contains the given Block and then // search the Block from that Stream. for ( int i = 0 ; ; ++ i ) { IndexDecoder index = streams . get ( i ) ; if ( index . hasRecord ( blockNumber ) ) { index . setBlockInfo ( info , blockNumber ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes a new BlockInputStream . This is a helper function for <code > seek () < / code > . [CODESPLIT] private void initBlockDecoder ( ) throws IOException { try { // Set it to null first so that GC can collect it if memory // runs tight when initializing a new BlockInputStream. if ( blockDecoder != null ) { blockDecoder . close ( ) ; blockDecoder = null ; } blockDecoder = new BlockInputStream ( in , check , verifyCheck , memoryLimit , curBlockInfo . unpaddedSize , curBlockInfo . uncompressedSize , arrayCache ) ; } catch ( MemoryLimitException e ) { // BlockInputStream doesn't know how much memory we had // already needed so we need to recreate the exception. assert memoryLimit >= 0 ; throw new MemoryLimitException ( e . getMemoryNeeded ( ) + indexMemoryUsage , memoryLimit + indexMemoryUsage ) ; } catch ( IndexIndicatorException e ) { // It cannot be Index so the file must be corrupt. throw new CorruptedInputException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate codes for Collections The pseudo code is : [CODESPLIT] private void doCollection ( TagPluginContext ctxt ) { ctxt . generateImport ( \"java.util.*\" ) ; generateIterators ( ctxt ) ; String itemsV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"Object \" + itemsV + \"= \" ) ; ctxt . generateAttribute ( \"items\" ) ; ctxt . generateJavaSource ( \";\" ) ; String indexV = null , beginV = null , endV = null , stepV = null ; if ( hasBegin ) { beginV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"int \" + beginV + \" = \" ) ; ctxt . generateAttribute ( \"begin\" ) ; ctxt . generateJavaSource ( \";\" ) ; } if ( hasEnd ) { indexV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"int \" + indexV + \" = 0;\" ) ; endV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"int \" + endV + \" = \" ) ; ctxt . generateAttribute ( \"end\" ) ; ctxt . generateJavaSource ( \";\" ) ; } if ( hasStep ) { stepV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"int \" + stepV + \" = \" ) ; ctxt . generateAttribute ( \"step\" ) ; ctxt . generateJavaSource ( \";\" ) ; } String iterV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"Iterator \" + iterV + \" = null;\" ) ; // Object[] ctxt . generateJavaSource ( \"if (\" + itemsV + \" instanceof Object[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((Object[])\" + itemsV + \");\" ) ; // boolean[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof boolean[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((boolean[])\" + itemsV + \");\" ) ; // byte[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof byte[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((byte[])\" + itemsV + \");\" ) ; // char[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof char[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((char[])\" + itemsV + \");\" ) ; // short[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof short[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((short[])\" + itemsV + \");\" ) ; // int[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof int[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((int[])\" + itemsV + \");\" ) ; // long[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof long[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((long[])\" + itemsV + \");\" ) ; // float[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof float[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((float[])\" + itemsV + \");\" ) ; // double[] ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof double[])\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((double[])\" + itemsV + \");\" ) ; // Collection ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof Collection)\" ) ; ctxt . generateJavaSource ( iterV + \"=((Collection)\" + itemsV + \").iterator();\" ) ; // Iterator ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof Iterator)\" ) ; ctxt . generateJavaSource ( iterV + \"=(Iterator)\" + itemsV + \";\" ) ; // Enumeration ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof Enumeration)\" ) ; ctxt . generateJavaSource ( iterV + \"=toIterator((Enumeration)\" + itemsV + \");\" ) ; // Map ctxt . generateJavaSource ( \"else if (\" + itemsV + \" instanceof Map)\" ) ; ctxt . generateJavaSource ( iterV + \"=((Map)\" + itemsV + \").entrySet().iterator();\" ) ; if ( hasBegin ) { String tV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"for (int \" + tV + \"=\" + beginV + \";\" + tV + \">0 && \" + iterV + \".hasNext(); \" + tV + \"--)\" ) ; ctxt . generateJavaSource ( iterV + \".next();\" ) ; } ctxt . generateJavaSource ( \"while (\" + iterV + \".hasNext()){\" ) ; if ( hasVar ) { ctxt . generateJavaSource ( \"_jspx_page_context.setAttribute(\" ) ; ctxt . generateAttribute ( \"var\" ) ; ctxt . generateJavaSource ( \", \" + iterV + \".next());\" ) ; } ctxt . generateBody ( ) ; if ( hasStep ) { String tV = ctxt . getTemporaryVariableName ( ) ; ctxt . generateJavaSource ( \"for (int \" + tV + \"=\" + stepV + \"-1;\" + tV + \">0 && \" + iterV + \".hasNext(); \" + tV + \"--)\" ) ; ctxt . generateJavaSource ( iterV + \".next();\" ) ; } if ( hasEnd ) { if ( hasStep ) { ctxt . generateJavaSource ( indexV + \"+=\" + stepV + \";\" ) ; } else { ctxt . generateJavaSource ( indexV + \"++;\" ) ; } if ( hasBegin ) { ctxt . generateJavaSource ( \"if(\" + beginV + \"+\" + indexV + \">\" + endV + \")\" ) ; } else { ctxt . generateJavaSource ( \"if(\" + indexV + \">\" + endV + \")\" ) ; } ctxt . generateJavaSource ( \"break;\" ) ; } ctxt . generateJavaSource ( \"}\" ) ; // while }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate iterators for data types supported in items [CODESPLIT] private void generateIterators ( TagPluginContext ctxt ) { // Object[] ctxt . generateDeclaration ( \"ObjectArrayIterator\" , \"private Iterator toIterator(final Object[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return a[index++];}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // boolean[] ctxt . generateDeclaration ( \"booleanArrayIterator\" , \"private Iterator toIterator(final boolean[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Boolean(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // byte[] ctxt . generateDeclaration ( \"byteArrayIterator\" , \"private Iterator toIterator(final byte[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Byte(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // char[] ctxt . generateDeclaration ( \"charArrayIterator\" , \"private Iterator toIterator(final char[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Character(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // short[] ctxt . generateDeclaration ( \"shortArrayIterator\" , \"private Iterator toIterator(final short[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Short(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // int[] ctxt . generateDeclaration ( \"intArrayIterator\" , \"private Iterator toIterator(final int[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Integer(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // long[] ctxt . generateDeclaration ( \"longArrayIterator\" , \"private Iterator toIterator(final long[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Long(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // float[] ctxt . generateDeclaration ( \"floatArrayIterator\" , \"private Iterator toIterator(final float[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Float(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // double[] ctxt . generateDeclaration ( \"doubleArrayIterator\" , \"private Iterator toIterator(final double[] a){\\n\" + \"  return (new Iterator() {\\n\" + \"    int index=0;\\n\" + \"    public boolean hasNext() {\\n\" + \"      return index < a.length;}\\n\" + \"    public Object next() {\\n\" + \"      return new Double(a[index++]);}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; // Enumeration ctxt . generateDeclaration ( \"enumIterator\" , \"private Iterator toIterator(final Enumeration e){\\n\" + \"  return (new Iterator() {\\n\" + \"    public boolean hasNext() {\\n\" + \"      return e.hasMoreElements();}\\n\" + \"    public Object next() {\\n\" + \"      return e.nextElement();}\\n\" + \"    public void remove() {}\\n\" + \"  });\\n\" + \"}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a list of all relevant maven artifacts [CODESPLIT] protected static List < MavenVersionedArtifact > getMavenArtifacts ( final String channelId , final Supplier < Collection < ArtifactInformation > > artifactsSupplier , final String groupId , final String artifactId , final boolean snapshot , final Predicate < ComparableVersion > versionFilter ) { final List < MavenVersionedArtifact > arts = new ArrayList <> ( ) ; for ( final ArtifactInformation ai : artifactsSupplier . get ( ) ) { if ( ! isZip ( ai ) ) { // if is is anot a zip, then this is not for the unzip plugin continue ; } // fetch meta data final String mvnGroupId = ai . getMetaData ( ) . get ( MK_GROUP_ID ) ; final String mvnArtifactId = ai . getMetaData ( ) . get ( MK_ARTIFACT_ID ) ; final String classifier = ai . getMetaData ( ) . get ( MK_CLASSIFIER ) ; final String mvnVersion = ai . getMetaData ( ) . get ( MK_VERSION ) ; final String mvnSnapshotVersion = ai . getMetaData ( ) . get ( MK_SNAPSHOT_VERSION ) ; if ( mvnGroupId == null || mvnArtifactId == null || mvnVersion == null ) { // no GAV information continue ; } if ( classifier != null && ! classifier . isEmpty ( ) ) { // no classifiers right now continue ; } if ( ! mvnGroupId . equals ( groupId ) || ! mvnArtifactId . equals ( artifactId ) ) { // wrong group or artifact id continue ; } if ( ! snapshot && ( mvnSnapshotVersion != null || mvnVersion . endsWith ( \"-SNAPSHOT\" ) ) ) { // we are not looking for snapshots continue ; } final ComparableVersion v = parseVersion ( mvnVersion ) ; final ComparableVersion sv = parseVersion ( mvnSnapshotVersion ) ; if ( v == null ) { // unable to parse v continue ; } if ( versionFilter == null ) { // no filter, add it arts . add ( new MavenVersionedArtifact ( sv != null ? sv : v , channelId , ai ) ) ; } else if ( versionFilter . test ( v ) ) { // filter matched, add it arts . add ( new MavenVersionedArtifact ( sv != null ? sv : v , channelId , ai ) ) ; } else if ( sv != null && versionFilter . test ( sv ) ) { // we have a snapshot version and it matched, add it arts . add ( new MavenVersionedArtifact ( sv , channelId , ai ) ) ; } } return arts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if an artifact is a ZIP file <p > An artifact is a ZIP file if at least one of th following tests is true : <ul > <li > Its lower case name ends with <code > . zip< / code > < / li > <li > The meta data field <code > mvn : extension< / code > is set to <code > zip< / code > <li > The meta data field <code > mime : type< / code > is set to <code > application / zip< / code > < / ul > < / p > [CODESPLIT] protected static boolean isZip ( final ArtifactInformation artifact ) { if ( artifact . getName ( ) . toLowerCase ( ) . endsWith ( \".zip\" ) ) { return true ; } final String mdExtension = artifact . getMetaData ( ) . get ( MK_MVN_EXTENSION ) ; if ( mdExtension != null && mdExtension . equalsIgnoreCase ( \"zip\" ) ) { return true ; } final String mdMime = artifact . getMetaData ( ) . get ( MK_MIME_TYPE ) ; if ( mdMime != null && mdMime . equalsIgnoreCase ( \"application/zip\" ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the opts array from backward indexes to forward indexes . Then it will be simple to get the next symbol from the array in later calls to <code > getNextSymbol () < / code > . [CODESPLIT] private int convertOpts ( ) { optEnd = optCur ; int optPrev = opts [ optCur ] . optPrev ; do { Optimum opt = opts [ optCur ] ; if ( opt . prev1IsLiteral ) { opts [ optPrev ] . optPrev = optCur ; opts [ optPrev ] . backPrev = - 1 ; optCur = optPrev -- ; if ( opt . hasPrev2 ) { opts [ optPrev ] . optPrev = optPrev + 1 ; opts [ optPrev ] . backPrev = opt . backPrev2 ; optCur = optPrev ; optPrev = opt . optPrev2 ; } } int temp = opts [ optPrev ] . optPrev ; opts [ optPrev ] . optPrev = optCur ; optCur = optPrev ; optPrev = temp ; } while ( optCur > 0 ) ; optCur = opts [ 0 ] . optPrev ; back = opts [ optCur ] . backPrev ; return optCur ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the state and reps for the current byte in the opts array . [CODESPLIT] private void updateOptStateAndReps ( ) { int optPrev = opts [ optCur ] . optPrev ; assert optPrev < optCur ; if ( opts [ optCur ] . prev1IsLiteral ) { -- optPrev ; if ( opts [ optCur ] . hasPrev2 ) { opts [ optCur ] . state . set ( opts [ opts [ optCur ] . optPrev2 ] . state ) ; if ( opts [ optCur ] . backPrev2 < REPS ) opts [ optCur ] . state . updateLongRep ( ) ; else opts [ optCur ] . state . updateMatch ( ) ; } else { opts [ optCur ] . state . set ( opts [ optPrev ] . state ) ; } opts [ optCur ] . state . updateLiteral ( ) ; } else { opts [ optCur ] . state . set ( opts [ optPrev ] . state ) ; } if ( optPrev == optCur - 1 ) { // Must be either a short rep or a literal. assert opts [ optCur ] . backPrev == 0 || opts [ optCur ] . backPrev == - 1 ; if ( opts [ optCur ] . backPrev == 0 ) opts [ optCur ] . state . updateShortRep ( ) ; else opts [ optCur ] . state . updateLiteral ( ) ; System . arraycopy ( opts [ optPrev ] . reps , 0 , opts [ optCur ] . reps , 0 , REPS ) ; } else { int back ; if ( opts [ optCur ] . prev1IsLiteral && opts [ optCur ] . hasPrev2 ) { optPrev = opts [ optCur ] . optPrev2 ; back = opts [ optCur ] . backPrev2 ; opts [ optCur ] . state . updateLongRep ( ) ; } else { back = opts [ optCur ] . backPrev ; if ( back < REPS ) opts [ optCur ] . state . updateLongRep ( ) ; else opts [ optCur ] . state . updateMatch ( ) ; } if ( back < REPS ) { opts [ optCur ] . reps [ 0 ] = opts [ optPrev ] . reps [ back ] ; int rep ; for ( rep = 1 ; rep <= back ; ++ rep ) opts [ optCur ] . reps [ rep ] = opts [ optPrev ] . reps [ rep - 1 ] ; for ( ; rep < REPS ; ++ rep ) opts [ optCur ] . reps [ rep ] = opts [ optPrev ] . reps [ rep ] ; } else { opts [ optCur ] . reps [ 0 ] = back - REPS ; System . arraycopy ( opts [ optPrev ] . reps , 0 , opts [ optCur ] . reps , 1 , REPS - 1 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates prices of a literal a short rep and literal + rep0 . [CODESPLIT] private void calc1BytePrices ( int pos , int posState , int avail , int anyRepPrice ) { // This will be set to true if using a literal or a short rep. boolean nextIsByte = false ; int curByte = lz . getByte ( 0 ) ; int matchByte = lz . getByte ( opts [ optCur ] . reps [ 0 ] + 1 ) ; // Try a literal. int literalPrice = opts [ optCur ] . price + literalEncoder . getPrice ( curByte , matchByte , lz . getByte ( 1 ) , pos , opts [ optCur ] . state ) ; if ( literalPrice < opts [ optCur + 1 ] . price ) { opts [ optCur + 1 ] . set1 ( literalPrice , optCur , - 1 ) ; nextIsByte = true ; } // Try a short rep. if ( matchByte == curByte && ( opts [ optCur + 1 ] . optPrev == optCur || opts [ optCur + 1 ] . backPrev != 0 ) ) { int shortRepPrice = getShortRepPrice ( anyRepPrice , opts [ optCur ] . state , posState ) ; if ( shortRepPrice <= opts [ optCur + 1 ] . price ) { opts [ optCur + 1 ] . set1 ( shortRepPrice , optCur , 0 ) ; nextIsByte = true ; } } // If neither a literal nor a short rep was the cheapest choice, // try literal + long rep0. if ( ! nextIsByte && matchByte != curByte && avail > MATCH_LEN_MIN ) { int lenLimit = Math . min ( niceLen , avail - 1 ) ; int len = lz . getMatchLen ( 1 , opts [ optCur ] . reps [ 0 ] , lenLimit ) ; if ( len >= MATCH_LEN_MIN ) { nextState . set ( opts [ optCur ] . state ) ; nextState . updateLiteral ( ) ; int nextPosState = ( pos + 1 ) & posMask ; int price = literalPrice + getLongRepAndLenPrice ( 0 , len , nextState , nextPosState ) ; int i = optCur + 1 + len ; while ( optEnd < i ) opts [ ++ optEnd ] . reset ( ) ; if ( price < opts [ i ] . price ) opts [ i ] . set2 ( price , optCur , 0 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates prices of long rep and long rep + literal + rep0 . [CODESPLIT] private int calcLongRepPrices ( int pos , int posState , int avail , int anyRepPrice ) { int startLen = MATCH_LEN_MIN ; int lenLimit = Math . min ( avail , niceLen ) ; for ( int rep = 0 ; rep < REPS ; ++ rep ) { int len = lz . getMatchLen ( opts [ optCur ] . reps [ rep ] , lenLimit ) ; if ( len < MATCH_LEN_MIN ) continue ; while ( optEnd < optCur + len ) opts [ ++ optEnd ] . reset ( ) ; int longRepPrice = getLongRepPrice ( anyRepPrice , rep , opts [ optCur ] . state , posState ) ; for ( int i = len ; i >= MATCH_LEN_MIN ; -- i ) { int price = longRepPrice + repLenEncoder . getPrice ( i , posState ) ; if ( price < opts [ optCur + i ] . price ) opts [ optCur + i ] . set1 ( price , optCur , rep ) ; } if ( rep == 0 ) startLen = len + 1 ; int len2Limit = Math . min ( niceLen , avail - len - 1 ) ; int len2 = lz . getMatchLen ( len + 1 , opts [ optCur ] . reps [ rep ] , len2Limit ) ; if ( len2 >= MATCH_LEN_MIN ) { // Rep int price = longRepPrice + repLenEncoder . getPrice ( len , posState ) ; nextState . set ( opts [ optCur ] . state ) ; nextState . updateLongRep ( ) ; // Literal int curByte = lz . getByte ( len , 0 ) ; int matchByte = lz . getByte ( 0 ) ; // lz.getByte(len, len) int prevByte = lz . getByte ( len , 1 ) ; price += literalEncoder . getPrice ( curByte , matchByte , prevByte , pos + len , nextState ) ; nextState . updateLiteral ( ) ; // Rep0 int nextPosState = ( pos + len + 1 ) & posMask ; price += getLongRepAndLenPrice ( 0 , len2 , nextState , nextPosState ) ; int i = optCur + len + 1 + len2 ; while ( optEnd < i ) opts [ ++ optEnd ] . reset ( ) ; if ( price < opts [ i ] . price ) opts [ i ] . set3 ( price , optCur , rep , len , 0 ) ; } } return startLen ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates prices of a normal match and normal match + literal + rep0 . [CODESPLIT] private void calcNormalMatchPrices ( int pos , int posState , int avail , int anyMatchPrice , int startLen ) { // If the longest match is so long that it would not fit into // the opts array, shorten the matches. if ( matches . len [ matches . count - 1 ] > avail ) { matches . count = 0 ; while ( matches . len [ matches . count ] < avail ) ++ matches . count ; matches . len [ matches . count ++ ] = avail ; } if ( matches . len [ matches . count - 1 ] < startLen ) return ; while ( optEnd < optCur + matches . len [ matches . count - 1 ] ) opts [ ++ optEnd ] . reset ( ) ; int normalMatchPrice = getNormalMatchPrice ( anyMatchPrice , opts [ optCur ] . state ) ; int match = 0 ; while ( startLen > matches . len [ match ] ) ++ match ; for ( int len = startLen ; ; ++ len ) { int dist = matches . dist [ match ] ; // Calculate the price of a match of len bytes from the nearest // possible distance. int matchAndLenPrice = getMatchAndLenPrice ( normalMatchPrice , dist , len , posState ) ; if ( matchAndLenPrice < opts [ optCur + len ] . price ) opts [ optCur + len ] . set1 ( matchAndLenPrice , optCur , dist + REPS ) ; if ( len != matches . len [ match ] ) continue ; // Try match + literal + rep0. First get the length of the rep0. int len2Limit = Math . min ( niceLen , avail - len - 1 ) ; int len2 = lz . getMatchLen ( len + 1 , dist , len2Limit ) ; if ( len2 >= MATCH_LEN_MIN ) { nextState . set ( opts [ optCur ] . state ) ; nextState . updateMatch ( ) ; // Literal int curByte = lz . getByte ( len , 0 ) ; int matchByte = lz . getByte ( 0 ) ; // lz.getByte(len, len) int prevByte = lz . getByte ( len , 1 ) ; int price = matchAndLenPrice + literalEncoder . getPrice ( curByte , matchByte , prevByte , pos + len , nextState ) ; nextState . updateLiteral ( ) ; // Rep0 int nextPosState = ( pos + len + 1 ) & posMask ; price += getLongRepAndLenPrice ( 0 , len2 , nextState , nextPosState ) ; int i = optCur + len + 1 + len2 ; while ( optEnd < i ) opts [ ++ optEnd ] . reset ( ) ; if ( price < opts [ i ] . price ) opts [ i ] . set3 ( price , optCur , dist + REPS , len , 0 ) ; } if ( ++ match == matches . count ) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decompresses into an array of bytes . <p > If <code > len< / code > is zero no bytes are read and <code > 0< / code > is returned . Otherwise this will block until <code > len< / code > bytes have been decompressed the end of the LZMA2 stream is reached or an exception is thrown . [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; if ( endReached ) return - 1 ; try { int size = 0 ; while ( len > 0 ) { if ( uncompressedSize == 0 ) { decodeChunkHeader ( ) ; if ( endReached ) return size == 0 ? - 1 : size ; } int copySizeMax = Math . min ( uncompressedSize , len ) ; if ( ! isLZMAChunk ) { lz . copyUncompressed ( in , copySizeMax ) ; } else { lz . setLimit ( copySizeMax ) ; lzma . decode ( ) ; } int copiedSize = lz . flush ( buf , off ) ; off += copiedSize ; len -= copiedSize ; size += copiedSize ; uncompressedSize -= copiedSize ; if ( uncompressedSize == 0 ) if ( ! rc . isFinished ( ) || lz . hasPending ( ) ) throw new CorruptedInputException ( ) ; } return size ; } catch ( IOException e ) { exception = e ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of uncompressed bytes that can be read without blocking . The value is returned with an assumption that the compressed input data will be valid . If the compressed data is corrupt <code > CorruptedInputException< / code > may get thrown before the number of bytes claimed to be available have been read from this input stream . <p > In LZMA2InputStream the return value will be non - zero when the decompressor is in the middle of an LZMA2 chunk . The return value will then be the number of uncompressed bytes remaining from that chunk . The return value can also be non - zero in the middle of an uncompressed chunk but then the return value depends also on the <code > available () < / code > method of the underlying InputStream . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; return isLZMAChunk ? uncompressedSize : Math . min ( uncompressedSize , in . available ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void start ( final BundleContext bundleContext ) throws Exception { Activator . INSTANCE = this ; this . aspects = new ChannelAspectProcessor ( bundleContext ) ; this . recipes = new RecipeProcessor ( bundleContext ) ; this . generatorProcessor = new GeneratorProcessor ( bundleContext ) ; this . generatorProcessor . open ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void stop ( final BundleContext bundleContext ) throws Exception { this . aspects . close ( ) ; this . recipes . dispose ( ) ; this . generatorProcessor . close ( ) ; Activator . INSTANCE = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a single character . This method will block until a character is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( ) throws IOException { // decode character int c = fSurrogate ; if ( fSurrogate == - 1 ) { // NOTE: We use the index into the buffer if there are remaining //       bytes from the last block read. -Ac int index = 0 ; // get first byte int b0 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b0 == - 1 ) { return - 1 ; } // UTF-8:   [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if ( b0 < 0x80 ) { c = ( char ) b0 ; } // UTF-8:   [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] else if ( ( b0 & 0xE0 ) == 0xC0 ) { int b1 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b1 == - 1 ) { expectedByte ( 2 , 2 ) ; } if ( ( b1 & 0xC0 ) != 0x80 ) { invalidByte ( 2 , 2 , b1 ) ; } c = ( ( b0 << 6 ) & 0x07C0 ) | ( b1 & 0x003F ) ; } // UTF-8:   [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] else if ( ( b0 & 0xF0 ) == 0xE0 ) { int b1 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b1 == - 1 ) { expectedByte ( 2 , 3 ) ; } if ( ( b1 & 0xC0 ) != 0x80 ) { invalidByte ( 2 , 3 , b1 ) ; } int b2 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b2 == - 1 ) { expectedByte ( 3 , 3 ) ; } if ( ( b2 & 0xC0 ) != 0x80 ) { invalidByte ( 3 , 3 , b2 ) ; } c = ( ( b0 << 12 ) & 0xF000 ) | ( ( b1 << 6 ) & 0x0FC0 ) | ( b2 & 0x003F ) ; } // UTF-8:   [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) //          [1101 11yy] [yyxx xxxx] (low surrogate) //          * uuuuu = wwww + 1 else if ( ( b0 & 0xF8 ) == 0xF0 ) { int b1 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b1 == - 1 ) { expectedByte ( 2 , 4 ) ; } if ( ( b1 & 0xC0 ) != 0x80 ) { invalidByte ( 2 , 3 , b1 ) ; } int b2 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b2 == - 1 ) { expectedByte ( 3 , 4 ) ; } if ( ( b2 & 0xC0 ) != 0x80 ) { invalidByte ( 3 , 3 , b2 ) ; } int b3 = index == fOffset ? fInputStream . read ( ) : fBuffer [ index ++ ] & 0x00FF ; if ( b3 == - 1 ) { expectedByte ( 4 , 4 ) ; } if ( ( b3 & 0xC0 ) != 0x80 ) { invalidByte ( 4 , 4 , b3 ) ; } int uuuuu = ( ( b0 << 2 ) & 0x001C ) | ( ( b1 >> 4 ) & 0x0003 ) ; if ( uuuuu > 0x10 ) { invalidSurrogate ( uuuuu ) ; } int wwww = uuuuu - 1 ; int hs = 0xD800 | ( ( wwww << 6 ) & 0x03C0 ) | ( ( b1 << 2 ) & 0x003C ) | ( ( b2 >> 4 ) & 0x0003 ) ; int ls = 0xDC00 | ( ( b2 << 6 ) & 0x03C0 ) | ( b3 & 0x003F ) ; c = hs ; fSurrogate = ls ; } // error else { invalidByte ( 1 , 1 , b0 ) ; } } // use surrogate else { fSurrogate = - 1 ; } // return character return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read characters into a portion of an array . This method will block until some input is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( char ch [ ] , int offset , int length ) throws IOException { // handle surrogate int out = offset ; if ( fSurrogate != - 1 ) { ch [ offset + 1 ] = ( char ) fSurrogate ; fSurrogate = - 1 ; length -- ; out ++ ; } // read bytes int count = 0 ; if ( fOffset == 0 ) { // adjust length to read if ( length > fBuffer . length ) { length = fBuffer . length ; } // perform read operation count = fInputStream . read ( fBuffer , 0 , length ) ; if ( count == - 1 ) { return - 1 ; } count += out - offset ; } // skip read; last character was in error // NOTE: Having an offset value other than zero means that there was //       an error in the last character read. In this case, we have //       skipped the read so we don't consume any bytes past the  //       error. By signalling the error on the next block read we //       allow the method to return the most valid characters that //       it can on the previous block read. -Ac else { count = fOffset ; fOffset = 0 ; } // convert bytes to characters final int total = count ; for ( int in = 0 ; in < total ; in ++ ) { int b0 = fBuffer [ in ] & 0x00FF ; // UTF-8:   [0xxx xxxx] // Unicode: [0000 0000] [0xxx xxxx] if ( b0 < 0x80 ) { ch [ out ++ ] = ( char ) b0 ; continue ; } // UTF-8:   [110y yyyy] [10xx xxxx] // Unicode: [0000 0yyy] [yyxx xxxx] if ( ( b0 & 0xE0 ) == 0xC0 ) { int b1 = - 1 ; if ( ++ in < total ) { b1 = fBuffer [ in ] & 0x00FF ; } else { b1 = fInputStream . read ( ) ; if ( b1 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } expectedByte ( 2 , 2 ) ; } count ++ ; } if ( ( b1 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } invalidByte ( 2 , 2 , b1 ) ; } int c = ( ( b0 << 6 ) & 0x07C0 ) | ( b1 & 0x003F ) ; ch [ out ++ ] = ( char ) c ; count -= 1 ; continue ; } // UTF-8:   [1110 zzzz] [10yy yyyy] [10xx xxxx] // Unicode: [zzzz yyyy] [yyxx xxxx] if ( ( b0 & 0xF0 ) == 0xE0 ) { int b1 = - 1 ; if ( ++ in < total ) { b1 = fBuffer [ in ] & 0x00FF ; } else { b1 = fInputStream . read ( ) ; if ( b1 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } expectedByte ( 2 , 3 ) ; } count ++ ; } if ( ( b1 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } invalidByte ( 2 , 3 , b1 ) ; } int b2 = - 1 ; if ( ++ in < total ) { b2 = fBuffer [ in ] & 0x00FF ; } else { b2 = fInputStream . read ( ) ; if ( b2 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } expectedByte ( 3 , 3 ) ; } count ++ ; } if ( ( b2 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fOffset = 3 ; return out - offset ; } invalidByte ( 3 , 3 , b2 ) ; } int c = ( ( b0 << 12 ) & 0xF000 ) | ( ( b1 << 6 ) & 0x0FC0 ) | ( b2 & 0x003F ) ; ch [ out ++ ] = ( char ) c ; count -= 2 ; continue ; } // UTF-8:   [1111 0uuu] [10uu zzzz] [10yy yyyy] [10xx xxxx]* // Unicode: [1101 10ww] [wwzz zzyy] (high surrogate) //          [1101 11yy] [yyxx xxxx] (low surrogate) //          * uuuuu = wwww + 1 if ( ( b0 & 0xF8 ) == 0xF0 ) { int b1 = - 1 ; if ( ++ in < total ) { b1 = fBuffer [ in ] & 0x00FF ; } else { b1 = fInputStream . read ( ) ; if ( b1 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } expectedByte ( 2 , 4 ) ; } count ++ ; } if ( ( b1 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } invalidByte ( 2 , 4 , b1 ) ; } int b2 = - 1 ; if ( ++ in < total ) { b2 = fBuffer [ in ] & 0x00FF ; } else { b2 = fInputStream . read ( ) ; if ( b2 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fOffset = 2 ; return out - offset ; } expectedByte ( 3 , 4 ) ; } count ++ ; } if ( ( b2 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fOffset = 3 ; return out - offset ; } invalidByte ( 3 , 4 , b2 ) ; } int b3 = - 1 ; if ( ++ in < total ) { b3 = fBuffer [ in ] & 0x00FF ; } else { b3 = fInputStream . read ( ) ; if ( b3 == - 1 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fOffset = 3 ; return out - offset ; } expectedByte ( 4 , 4 ) ; } count ++ ; } if ( ( b3 & 0xC0 ) != 0x80 ) { if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fBuffer [ 1 ] = ( byte ) b1 ; fBuffer [ 2 ] = ( byte ) b2 ; fBuffer [ 3 ] = ( byte ) b3 ; fOffset = 4 ; return out - offset ; } invalidByte ( 4 , 4 , b2 ) ; } // decode bytes into surrogate characters int uuuuu = ( ( b0 << 2 ) & 0x001C ) | ( ( b1 >> 4 ) & 0x0003 ) ; if ( uuuuu > 0x10 ) { invalidSurrogate ( uuuuu ) ; } int wwww = uuuuu - 1 ; int zzzz = b1 & 0x000F ; int yyyyyy = b2 & 0x003F ; int xxxxxx = b3 & 0x003F ; int hs = 0xD800 | ( ( wwww << 6 ) & 0x03C0 ) | ( zzzz << 2 ) | ( yyyyyy >> 4 ) ; int ls = 0xDC00 | ( ( yyyyyy << 6 ) & 0x03C0 ) | xxxxxx ; // set characters ch [ out ++ ] = ( char ) hs ; ch [ out ++ ] = ( char ) ls ; count -= 2 ; continue ; } // error if ( out > offset ) { fBuffer [ 0 ] = ( byte ) b0 ; fOffset = 1 ; return out - offset ; } invalidByte ( 1 , 1 , b0 ) ; } // return number of characters converted return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws an exception for expected byte . [CODESPLIT] private void expectedByte ( int position , int count ) throws UTFDataFormatException { throw new UTFDataFormatException ( Localizer . getMessage ( \"jsp.error.xml.expectedByte\" , Integer . toString ( position ) , Integer . toString ( count ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throws an exception for invalid byte . [CODESPLIT] private void invalidByte ( int position , int count , int c ) throws UTFDataFormatException { throw new UTFDataFormatException ( Localizer . getMessage ( \"jsp.error.xml.invalidByte\" , Integer . toString ( position ) , Integer . toString ( count ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the location of the TLD associated with the given taglib uri . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public String [ ] getLocation ( String uri ) throws JasperException { if ( mappings == null ) { // Recovering the map done in onStart. mappings = ( HashMap < String , String [ ] > ) ctxt . getAttribute ( Constants . JSP_TLD_URI_TO_LOCATION_MAP ) ; } if ( mappings != null && mappings . get ( uri ) != null ) { // if the uri is in, return that, and dont bother to do full scan return mappings . get ( uri ) ; } if ( ! doneScanning ) { scanListeners = false ; scanTlds ( ) ; doneScanning = true ; } if ( mappings == null ) { // Should never happend return null ; } return mappings . get ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan the all the tlds accessible in the web app . For performance reasons this is done in two stages . At servlet initialization time we only scan the jar files for listeners . The container passes a list of system jar files that are known to contain tlds with listeners . The rest of the jar files will be scanned when a JSP page with a tld referenced is compiled . [CODESPLIT] private void scanTlds ( ) throws JasperException { mappings = new HashMap < String , String [ ] > ( ) ; // Make a local copy of the system jar cache  jarTldCacheLocal . putAll ( jarTldCache ) ; try { processWebDotXml ( ) ; scanJars ( ) ; processTldsInFileSystem ( \"/WEB-INF/\" ) ; } catch ( JasperException ex ) { throw ex ; } catch ( Exception ex ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.internal.tldinit\" ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Populates taglib map described in web . xml . [CODESPLIT] private void processWebDotXml ( ) throws Exception { // Skip if we are only looking for listeners if ( scanListeners ) { return ; } JspConfigDescriptor jspConfig = ctxt . getJspConfigDescriptor ( ) ; if ( jspConfig == null ) { return ; } for ( TaglibDescriptor taglib : jspConfig . getTaglibs ( ) ) { if ( taglib == null ) { continue ; } String tagUri = taglib . getTaglibURI ( ) ; String tagLoc = taglib . getTaglibLocation ( ) ; if ( tagUri == null || tagLoc == null ) { continue ; } // Ignore system tlds in web.xml, for backward compatibility if ( systemUris . contains ( tagUri ) || ( ! useMyFaces && systemUrisJsf . contains ( tagUri ) ) ) { continue ; } // Save this location if appropriate if ( uriType ( tagLoc ) == NOROOT_REL_URI ) tagLoc = \"/WEB-INF/\" + tagLoc ; String tagLoc2 = null ; if ( tagLoc . endsWith ( JAR_FILE_SUFFIX ) ) { tagLoc = ctxt . getResource ( tagLoc ) . toString ( ) ; tagLoc2 = \"META-INF/taglib.tld\" ; } if ( log . isLoggable ( Level . FINE ) ) { log . fine ( \"Add tld map from web.xml: \" + tagUri + \"=>\" + tagLoc + \",\" + tagLoc2 ) ; } mappings . put ( tagUri , new String [ ] { tagLoc , tagLoc2 } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans the given JarURLConnection for TLD files located in META - INF ( or a subdirectory of it ) . If the scanning in is done as part of the ServletContextInitializer the listeners in the tlds in this jar file are added to the servlet context and for any TLD that has a <uri > element an implicit map entry is added to the taglib map . [CODESPLIT] private void scanJar ( JarURLConnection conn , List < String > tldNames , boolean isLocal ) throws JasperException { String resourcePath = conn . getJarFileURL ( ) . toString ( ) ; TldInfo [ ] tldInfos = jarTldCacheLocal . get ( resourcePath ) ; // Optimize for most common cases: jars known to NOT have tlds if ( tldInfos != null && tldInfos . length == 0 ) { try { conn . getJarFile ( ) . close ( ) ; } catch ( IOException ex ) { //ignored } return ; } // scan the tld if the jar has not been cached. if ( tldInfos == null ) { JarFile jarFile = null ; ArrayList < TldInfo > tldInfoA = new ArrayList < TldInfo > ( ) ; try { jarFile = conn . getJarFile ( ) ; if ( tldNames != null ) { for ( String tldName : tldNames ) { JarEntry entry = jarFile . getJarEntry ( tldName ) ; InputStream stream = jarFile . getInputStream ( entry ) ; tldInfoA . add ( scanTld ( resourcePath , tldName , stream ) ) ; } } else { Enumeration < JarEntry > entries = jarFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; String name = entry . getName ( ) ; if ( ! name . startsWith ( \"META-INF/\" ) ) continue ; if ( ! name . endsWith ( \".tld\" ) ) continue ; InputStream stream = jarFile . getInputStream ( entry ) ; tldInfoA . add ( scanTld ( resourcePath , name , stream ) ) ; } } } catch ( IOException ex ) { if ( resourcePath . startsWith ( FILE_PROTOCOL ) && ! ( ( new File ( resourcePath ) ) . exists ( ) ) ) { if ( log . isLoggable ( Level . WARNING ) ) { log . log ( Level . WARNING , Localizer . getMessage ( \"jsp.warn.nojar\" , resourcePath ) , ex ) ; } } else { throw new JasperException ( Localizer . getMessage ( \"jsp.error.jar.io\" , resourcePath ) , ex ) ; } } finally { if ( jarFile != null ) { try { jarFile . close ( ) ; } catch ( Throwable t ) { // ignore } } } // Update the jar TLD cache tldInfos = tldInfoA . toArray ( new TldInfo [ tldInfoA . size ( ) ] ) ; jarTldCacheLocal . put ( resourcePath , tldInfos ) ; if ( ! isLocal ) { // Also update the global cache; jarTldCache . put ( resourcePath , tldInfos ) ; } } // Iterate over tldinfos to add listeners or to map tldlocations for ( TldInfo tldInfo : tldInfos ) { if ( scanListeners ) { addListener ( tldInfo , isLocal ) ; } mapTldLocation ( resourcePath , tldInfo , isLocal ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Searches the filesystem under / WEB - INF for any TLD files and scans them for <uri > and <listener > elements . [CODESPLIT] private void processTldsInFileSystem ( String startPath ) throws JasperException { Set dirList = ctxt . getResourcePaths ( startPath ) ; if ( dirList != null ) { Iterator it = dirList . iterator ( ) ; while ( it . hasNext ( ) ) { String path = ( String ) it . next ( ) ; if ( path . endsWith ( \"/\" ) ) { processTldsInFileSystem ( path ) ; } if ( ! path . endsWith ( \".tld\" ) ) { continue ; } if ( path . startsWith ( \"/WEB-INF/tags/\" ) && ! path . endsWith ( \"implicit.tld\" ) ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.tldinit.tldInWebInfTags\" , path ) ) ; } InputStream stream = ctxt . getResourceAsStream ( path ) ; TldInfo tldInfo = scanTld ( path , null , stream ) ; // Add listeners or to map tldlocations for this TLD if ( scanListeners ) { addListener ( tldInfo , true ) ; } mapTldLocation ( path , tldInfo , true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan the given TLD for uri and listeners elements . [CODESPLIT] private TldInfo scanTld ( String resourcePath , String entryName , InputStream stream ) throws JasperException { try { // Parse the tag library descriptor at the specified resource path TreeNode tld = new ParserUtils ( ) . parseXMLDocument ( resourcePath , stream , isValidationEnabled ) ; String uri = null ; TreeNode uriNode = tld . findChild ( \"uri\" ) ; if ( uriNode != null ) { uri = uriNode . getBody ( ) ; } ArrayList < String > listeners = new ArrayList < String > ( ) ; Iterator < TreeNode > listenerNodes = tld . findChildren ( \"listener\" ) ; while ( listenerNodes . hasNext ( ) ) { TreeNode listener = listenerNodes . next ( ) ; TreeNode listenerClass = listener . findChild ( \"listener-class\" ) ; if ( listenerClass != null ) { String listenerClassName = listenerClass . getBody ( ) ; if ( listenerClassName != null ) { listeners . add ( listenerClassName ) ; } } } return new TldInfo ( uri , entryName , listeners . toArray ( new String [ listeners . size ( ) ] ) ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( Throwable t ) { // do nothing } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Scans all JARs accessible to the webapp s classloader and its parent classloaders for TLDs . [CODESPLIT] private void scanJars ( ) throws Exception { ClassLoader webappLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; ClassLoader loader = webappLoader ; Map < URI , List < String > > tldMap ; if ( scanListeners ) { tldMap = getTldListenerMap ( ) ; } else { tldMap = getTldMap ( ) ; } Boolean isStandalone = ( Boolean ) ctxt . getAttribute ( IS_STANDALONE_ATTRIBUTE_NAME ) ; while ( loader != null ) { if ( loader instanceof URLClassLoader ) { boolean isLocal = ( loader == webappLoader ) ; URL [ ] urls = ( ( URLClassLoader ) loader ) . getURLs ( ) ; List < String > extraJars = new ArrayList < String > ( ) ; for ( int i = 0 ; i < urls . length ; i ++ ) { URLConnection conn = urls [ i ] . openConnection ( ) ; JarURLConnection jconn = null ; if ( conn instanceof JarURLConnection ) { jconn = ( JarURLConnection ) conn ; } else { String urlStr = urls [ i ] . toString ( ) ; if ( urlStr . startsWith ( FILE_PROTOCOL ) && urlStr . endsWith ( JAR_FILE_SUFFIX ) ) { URL jarURL = new URL ( \"jar:\" + urlStr + \"!/\" ) ; jconn = ( JarURLConnection ) jarURL . openConnection ( ) ; } } if ( jconn != null ) { jconn . setUseCaches ( false ) ; if ( isLocal ) { // For local jars, collect the jar files in the // Manifest Class-Path, to be scanned later. addManifestClassPath ( null , extraJars , jconn ) ; } scanJar ( jconn , null , isLocal ) ; } } // Scan the jars collected from manifest class-path.  Expand // the list to include jar files from their manifest classpath. if ( extraJars . size ( ) > 0 ) { List < String > newJars ; do { newJars = new ArrayList < String > ( ) ; for ( String jar : extraJars ) { URL jarURL = new URL ( \"jar:\" + jar + \"!/\" ) ; JarURLConnection jconn = ( JarURLConnection ) jarURL . openConnection ( ) ; jconn . setUseCaches ( false ) ; if ( addManifestClassPath ( extraJars , newJars , jconn ) ) { scanJar ( jconn , null , true ) ; } } extraJars . addAll ( newJars ) ; } while ( newJars . size ( ) != 0 ) ; } } if ( tldMap != null && isStandalone != null ) { if ( isStandalone . booleanValue ( ) ) { break ; } else { if ( EAR_LIB_CLASSLOADER . equals ( loader . getClass ( ) . getName ( ) ) ) { // Do not walk up classloader delegation chain beyond // EarLibClassLoader break ; } } } loader = loader . getParent ( ) ; } if ( tldMap != null ) { for ( URI uri : tldMap . keySet ( ) ) { URL jarURL = new URL ( \"jar:\" + uri . toString ( ) + \"!/\" ) ; scanJar ( ( JarURLConnection ) jarURL . openConnection ( ) , tldMap . get ( uri ) , false ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add the jars in the manifest Class - Path to the list jars [CODESPLIT] private boolean addManifestClassPath ( List < String > scannedJars , List < String > newJars , JarURLConnection jconn ) { Manifest manifest ; try { manifest = jconn . getManifest ( ) ; } catch ( IOException ex ) { // Maybe non existing jar, ignored return false ; } String file = jconn . getJarFileURL ( ) . toString ( ) ; if ( ! file . contains ( \"WEB-INF\" ) ) { // Only jar in WEB-INF is considered here return true ; } if ( manifest == null ) return true ; java . util . jar . Attributes attrs = manifest . getMainAttributes ( ) ; String cp = ( String ) attrs . getValue ( \"Class-Path\" ) ; if ( cp == null ) return true ; String [ ] paths = cp . split ( \" \" ) ; int lastIndex = file . lastIndexOf ( ' ' ) ; if ( lastIndex < 0 ) { lastIndex = file . lastIndexOf ( ' ' ) ; } String baseDir = \"\" ; if ( lastIndex > 0 ) { baseDir = file . substring ( 0 , lastIndex + 1 ) ; } for ( String path : paths ) { String p ; if ( path . startsWith ( \"/\" ) || path . startsWith ( \"\\\\\" ) ) { p = \"file:\" + path ; } else { p = baseDir + path ; } if ( ( scannedJars == null || ! scannedJars . contains ( p ) ) && ! newJars . contains ( p ) ) { newJars . add ( p ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new JspServletWrapper . [CODESPLIT] public void addWrapper ( String jspUri , JspServletWrapper jsw ) { jsps . remove ( jspUri ) ; jsps . put ( jspUri , jsw ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the parent class loader . [CODESPLIT] public ClassLoader getParentClassLoader ( ) { ClassLoader parentClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( parentClassLoader == null ) { parentClassLoader = this . getClass ( ) . getClassLoader ( ) ; } return parentClassLoader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the bytecode for the class in a map . The current time is noted . [CODESPLIT] public void setBytecode ( String name , byte [ ] bytecode ) { if ( bytecode == null ) { bytecodes . remove ( name ) ; bytecodeBirthTimes . remove ( name ) ; return ; } bytecodes . put ( name , bytecode ) ; bytecodeBirthTimes . put ( name , Long . valueOf ( System . currentTimeMillis ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the time the bytecode for a class was created [CODESPLIT] public long getBytecodeBirthTime ( String name ) { Long time = bytecodeBirthTimes . get ( name ) ; return ( time != null ? time . longValue ( ) : 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the bytecode for a class to disk . [CODESPLIT] public void saveBytecode ( String className , String classFileName ) { byte [ ] bytecode = getBytecode ( className ) ; if ( bytecode != null ) { try { FileOutputStream fos = new FileOutputStream ( classFileName ) ; fos . write ( bytecode ) ; fos . close ( ) ; } catch ( IOException ex ) { context . log ( \"Error in saving bytecode for \" + className + \" to \" + classFileName , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method used by background thread to check the JSP dependencies registered with this class for JSP s . [CODESPLIT] private void checkCompile ( ) { for ( JspServletWrapper jsw : jsps . values ( ) ) { if ( jsw . isTagFile ( ) ) { // Skip tag files in background compiliations, since modified // tag files will be recompiled anyway when their client JSP // pages are compiled.  This also avoids problems when the // tag files and their clients are not modified simultaneously. continue ; } JspCompilationContext ctxt = jsw . getJspEngineContext ( ) ; // JspServletWrapper also synchronizes on this when // it detects it has to do a reload synchronized ( jsw ) { try { ctxt . compile ( ) ; } catch ( FileNotFoundException ex ) { ctxt . incrementRemoved ( ) ; } catch ( Throwable t ) { jsw . getServletContext ( ) . log ( Localizer . getMessage ( \"jsp.error.background.compile\" ) , t ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method used to initialize classpath for compiles . [CODESPLIT] private void initClassPath ( ) { /* Classpath can be specified in one of two ways, depending on\n           whether the compilation is embedded or invoked from Jspc.\n           1. Calculated by the web container, and passed to Jasper in the\n              context attribute.\n           2. Jspc directly invoke JspCompilationContext.setClassPath, in\n              case the classPath initialzed here is ignored.\n        */ StringBuilder cpath = new StringBuilder ( ) ; String sep = System . getProperty ( \"path.separator\" ) ; cpath . append ( options . getScratchDir ( ) + sep ) ; String cp = ( String ) context . getAttribute ( Constants . SERVLET_CLASSPATH ) ; if ( cp == null || cp . equals ( \"\" ) ) { cp = options . getClassPath ( ) ; } if ( cp != null ) { classpath = cpath . toString ( ) + cp ; } // START GlassFish Issue 845 if ( classpath != null ) { try { classpath = URLDecoder . decode ( classpath , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { if ( log . isLoggable ( Level . FINE ) ) log . log ( Level . FINE , \"Exception decoding classpath : \" + classpath , e ) ; } } // END GlassFish Issue 845 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method used to initialize SecurityManager data . [CODESPLIT] private void initSecurity ( ) { // Setup the PermissionCollection for this web app context // based on the permissions configured for the root of the // web app context directory, then add a file read permission // for that directory. Policy policy = Policy . getPolicy ( ) ; if ( policy != null ) { try { // Get the permissions for the web app context String docBase = context . getRealPath ( \"/\" ) ; if ( docBase == null ) { docBase = options . getScratchDir ( ) . toString ( ) ; } String codeBase = docBase ; if ( ! codeBase . endsWith ( File . separator ) ) { codeBase = codeBase + File . separator ; } File contextDir = new File ( codeBase ) ; URL url = contextDir . getCanonicalFile ( ) . toURL ( ) ; codeSource = new CodeSource ( url , ( Certificate [ ] ) null ) ; permissionCollection = policy . getPermissions ( codeSource ) ; // Create a file read permission for web app context directory if ( ! docBase . endsWith ( File . separator ) ) { permissionCollection . add ( new FilePermission ( docBase , \"read\" ) ) ; docBase = docBase + File . separator ; } else { permissionCollection . add ( new FilePermission ( docBase . substring ( 0 , docBase . length ( ) - 1 ) , \"read\" ) ) ; } docBase = docBase + \"-\" ; permissionCollection . add ( new FilePermission ( docBase , \"read\" ) ) ; // Create a file read permission for web app tempdir (work) // directory String workDir = options . getScratchDir ( ) . toString ( ) ; if ( ! workDir . endsWith ( File . separator ) ) { permissionCollection . add ( new FilePermission ( workDir , \"read\" ) ) ; workDir = workDir + File . separator ; } workDir = workDir + \"-\" ; permissionCollection . add ( new FilePermission ( workDir , \"read\" ) ) ; // Allow the JSP to access org.apache.jasper.runtime.HttpJspBase permissionCollection . add ( new RuntimePermission ( \"accessClassInPackage.org.apache.jasper.runtime\" ) ) ; ClassLoader parentClassLoader = getParentClassLoader ( ) ; if ( parentClassLoader instanceof URLClassLoader ) { URL [ ] urls = ( ( URLClassLoader ) parentClassLoader ) . getURLs ( ) ; String jarUrl = null ; String jndiUrl = null ; for ( int i = 0 ; i < urls . length ; i ++ ) { if ( jndiUrl == null && urls [ i ] . toString ( ) . startsWith ( \"jndi:\" ) ) { jndiUrl = urls [ i ] . toString ( ) + \"-\" ; } if ( jarUrl == null && urls [ i ] . toString ( ) . startsWith ( \"jar:jndi:\" ) ) { jarUrl = urls [ i ] . toString ( ) ; jarUrl = jarUrl . substring ( 0 , jarUrl . length ( ) - 2 ) ; jarUrl = jarUrl . substring ( 0 , jarUrl . lastIndexOf ( ' ' ) ) + \"/-\" ; } } if ( jarUrl != null ) { permissionCollection . add ( new FilePermission ( jarUrl , \"read\" ) ) ; permissionCollection . add ( new FilePermission ( jarUrl . substring ( 4 ) , \"read\" ) ) ; } if ( jndiUrl != null ) permissionCollection . add ( new FilePermission ( jndiUrl , \"read\" ) ) ; } } catch ( Exception e ) { context . log ( \"Security Init for context failed\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the background thread that will periodically check for changes to compile time included files in a JSP . [CODESPLIT] protected void threadStart ( ) { // Has the background thread already been started? if ( thread != null ) { return ; } // Start the background thread threadDone = false ; thread = new Thread ( this , threadName ) ; thread . setDaemon ( true ) ; thread . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop the background thread that is periodically checking for changes to compile time included files in a JSP . [CODESPLIT] protected void threadStop ( ) { if ( thread == null ) { return ; } threadDone = true ; thread . interrupt ( ) ; try { thread . join ( ) ; } catch ( InterruptedException e ) { ; } thread = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The background thread that checks for changes to files included by a JSP and flags that a recompile is required . [CODESPLIT] public void run ( ) { // Loop until the termination semaphore is set while ( ! threadDone ) { // Wait for our check interval threadSleep ( ) ; // Check for included files which are newer than the // JSP which uses them. try { checkCompile ( ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; log . log ( Level . SEVERE , Localizer . getMessage ( \"jsp.error.recompile\" ) , t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find by the locator <p > This method does not acquire the read lock this has to be done by the caller < / p > [CODESPLIT] protected Optional < ChannelInstance > find ( final By by ) { switch ( by . getType ( ) ) { case ID : return findById ( ( String ) by . getQualifier ( ) ) ; case NAME : return findByName ( ( String ) by . getQualifier ( ) ) ; case COMPOSITE : { final By [ ] bys = ( By [ ] ) by . getQualifier ( ) ; for ( final By oneBy : bys ) { final Optional < ChannelInstance > result = find ( oneBy ) ; if ( result . isPresent ( ) ) { return result ; } } return Optional . empty ( ) ; } default : throw new IllegalArgumentException ( String . format ( \"Unknown locator type: %s\" , by . getType ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a channel by name [CODESPLIT] private Optional < ChannelInstance > findByName ( final String name ) { if ( name == null ) { return empty ( ) ; } final String id = this . manager . accessCall ( KEY_STORAGE , ChannelServiceAccess . class , channels -> { return channels . mapToId ( name ) ; } ) ; return findById ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a channel [CODESPLIT] private ChannelInstance findChannel ( final By by ) { final Optional < ChannelInstance > channel ; try ( Locked l = lock ( this . readLock ) ) { channel = find ( by ) ; } if ( ! channel . isPresent ( ) ) { throw new ChannelNotFoundException ( by . toString ( ) ) ; } return channel . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update the channel to deploy group cache map [CODESPLIT] private void updateDeployGroupCache ( final ChannelServiceAccess model ) { // this will simply rebuild the complete map // clear first this . deployKeysMap . clear ( ) ; // fill afterwards for ( final Map . Entry < String , Set < String > > entry : model . getDeployGroupMap ( ) . entrySet ( ) ) { final String channelId = entry . getKey ( ) ; final List < DeployGroup > groups = entry . getValue ( ) . stream ( ) . map ( groupId -> model . getDeployGroup ( groupId ) ) . collect ( Collectors . toList ( ) ) ; this . deployKeysMap . putAll ( channelId , groups ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "methods of DeployAuthService [CODESPLIT] @ Override public List < DeployGroup > listGroups ( final int position , final int count ) { return this . manager . accessCall ( KEY_STORAGE , ChannelServiceAccess . class , model -> { return split ( model . getDeployGroups ( ) , position , count ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "statistics [CODESPLIT] @ Override public ChannelStatistics getStatistics ( ) { final ChannelStatistics cs = new ChannelStatistics ( ) ; try ( Locked l = lock ( this . readLock ) ) { final Collection < ChannelInformation > cis = list ( ) ; cs . setTotalNumberOfArtifacts ( cis . stream ( ) . mapToLong ( ci -> ci . getState ( ) . getNumberOfArtifacts ( ) ) . sum ( ) ) ; cs . setTotalNumberOfBytes ( cis . stream ( ) . mapToLong ( ci -> ci . getState ( ) . getNumberOfBytes ( ) ) . sum ( ) ) ; } return cs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the remaining content of one stream to the other [CODESPLIT] public static long copy ( final InputStream in , final OutputStream out ) throws IOException { Objects . requireNonNull ( in ) ; Objects . requireNonNull ( out ) ; final byte [ ] buffer = new byte [ COPY_BUFFER_SIZE ] ; long result = 0 ; int rc ; while ( ( rc = in . read ( buffer ) ) >= 0 ) { result += rc ; out . write ( buffer , 0 , rc ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the remaining content of one reader to the { @link Appendable } ( or { @link Writer } [CODESPLIT] public static long copy ( final Readable readable , final Appendable appendable ) throws IOException { final CharBuffer buffer = CharBuffer . allocate ( COPY_BUFFER_SIZE ) ; long total = 0 ; while ( readable . read ( buffer ) >= 0 ) { buffer . flip ( ) ; appendable . append ( buffer ) ; total += buffer . remaining ( ) ; buffer . clear ( ) ; } return total ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main entry for Parser [CODESPLIT] public static Node . Nodes parse ( ParserController pc , String path , JspReader reader , Node parent , boolean isTagFile , boolean directivesOnly , URL jarFileUrl , String pageEnc , String jspConfigPageEnc , boolean isDefaultPageEncoding , boolean hasBom ) throws JasperException { Parser parser = new Parser ( pc , reader , isTagFile , directivesOnly , jarFileUrl , hasBom ) ; Node . Root root = new Node . Root ( reader . mark ( ) , parent , false ) ; root . setPageEncoding ( pageEnc ) ; root . setJspConfigPageEncoding ( jspConfigPageEnc ) ; root . setIsDefaultPageEncoding ( isDefaultPageEncoding ) ; root . setHasBom ( hasBom ) ; if ( hasBom ) { // Consume (remove) BOM, so it won't appear in page output char bomChar = ( char ) reader . nextChar ( ) ; if ( bomChar != 0xFEFF ) { parser . err . jspError ( reader . mark ( ) , \"jsp.error.invalidBom\" , Integer . toHexString ( bomChar ) . toUpperCase ( ) ) ; } } if ( directivesOnly ) { parser . parseTagFileDirectives ( root ) ; return new Node . Nodes ( root ) ; } // For the Top level page, add inlcude-prelude and include-coda PageInfo pageInfo = pc . getCompiler ( ) . getPageInfo ( ) ; if ( parent == null ) { parser . addInclude ( root , pageInfo . getIncludePrelude ( ) ) ; } while ( reader . hasMoreInput ( ) ) { parser . parseElements ( root ) ; } if ( parent == null ) { parser . addInclude ( root , pageInfo . getIncludeCoda ( ) ) ; parser . pageInfo . setRootPath ( path ) ; } Node . Nodes page = new Node . Nodes ( root ) ; return page ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attributes :: = ( S Attribute ) * S? [CODESPLIT] Attributes parseAttributes ( ) throws JasperException { AttributesImpl attrs = new AttributesImpl ( ) ; reader . skipSpaces ( ) ; while ( parseAttribute ( attrs ) ) reader . skipSpaces ( ) ; return attrs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse Attributes for a reader provided for external use [CODESPLIT] public static Attributes parseAttributes ( ParserController pc , JspReader reader ) throws JasperException { Parser tmpParser = new Parser ( pc , reader , false , false , null , false ) ; return tmpParser . parseAttributes ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attribute :: = Name S? Eq S? ( <% = RTAttributeValueDouble | AttributeValueDouble | <% = RTAttributeValueSingle | AttributeValueSingle } Note : JSP and XML spec does not allow while spaces around Eq . It is added to be backward compatible with Tomcat and with other xml parsers . [CODESPLIT] private boolean parseAttribute ( AttributesImpl attrs ) throws JasperException { // Get the qualified name String qName = parseName ( ) ; if ( qName == null ) return false ; // Determine prefix and local name components String localName = qName ; String uri = \"\" ; int index = qName . indexOf ( ' ' ) ; if ( index != - 1 ) { String prefix = qName . substring ( 0 , index ) ; uri = pageInfo . getURI ( prefix ) ; if ( uri == null ) { err . jspError ( reader . mark ( ) , \"jsp.error.attribute.invalidPrefix\" , prefix ) ; } localName = qName . substring ( index + 1 ) ; } reader . skipSpaces ( ) ; if ( ! reader . matches ( \"=\" ) ) err . jspError ( reader . mark ( ) , \"jsp.error.attribute.noequal\" ) ; reader . skipSpaces ( ) ; char quote = ( char ) reader . nextChar ( ) ; if ( quote != ' ' && quote != ' ' ) err . jspError ( reader . mark ( ) , \"jsp.error.attribute.noquote\" ) ; String watchString = \"\" ; if ( reader . matches ( \"<%=\" ) ) watchString = \"%>\" ; watchString = watchString + quote ; String attrValue = parseAttributeValue ( watchString ) ; attrs . addAttribute ( uri , localName , qName , \"CDATA\" , attrValue ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Name :: = ( Letter | _ | : ) ( Letter | Digit | . | _ | - | : ) * [CODESPLIT] private String parseName ( ) throws JasperException { char ch = ( char ) reader . peekChar ( ) ; if ( Character . isLetter ( ch ) || ch == ' ' || ch == ' ' ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( ch ) ; reader . nextChar ( ) ; ch = ( char ) reader . peekChar ( ) ; while ( Character . isLetter ( ch ) || Character . isDigit ( ch ) || ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ) { buf . append ( ch ) ; reader . nextChar ( ) ; ch = ( char ) reader . peekChar ( ) ; } return buf . toString ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "AttributeValueDouble :: = ( QuotedChar - ) * ( | <TRANSLATION_ERROR > ) RTAttributeValueDouble :: = (( QuotedChar - ) * - (( QuotedChar - ) % > ) ( % > | TRANSLATION_ERROR ) [CODESPLIT] private String parseAttributeValue ( String watch ) throws JasperException { Mark start = reader . mark ( ) ; Mark stop = reader . skipUntilIgnoreEsc ( watch ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.attribute.unterminated\" , watch ) ; } String ret = parseQuoted ( reader . getText ( start , stop ) ) ; if ( watch . length ( ) == 1 ) // quote return ret ; // putback delimiter '<%=' and '%>', since they are needed if the // attribute does not allow RTexpression. return \"<%=\" + ret + \"%>\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "may be send to EL processor . [CODESPLIT] private String parseQuoted ( String tx ) { StringBuilder buf = new StringBuilder ( ) ; int size = tx . length ( ) ; int i = 0 ; while ( i < size ) { char ch = tx . charAt ( i ) ; if ( ch == ' ' ) { if ( i + 5 < size && tx . charAt ( i + 1 ) == ' ' && tx . charAt ( i + 2 ) == ' ' && tx . charAt ( i + 3 ) == ' ' && tx . charAt ( i + 4 ) == ' ' && tx . charAt ( i + 5 ) == ' ' ) { buf . append ( ' ' ) ; i += 6 ; } else if ( i + 5 < size && tx . charAt ( i + 1 ) == ' ' && tx . charAt ( i + 2 ) == ' ' && tx . charAt ( i + 3 ) == ' ' && tx . charAt ( i + 4 ) == ' ' && tx . charAt ( i + 5 ) == ' ' ) { buf . append ( ' ' ) ; i += 6 ; } else { buf . append ( ch ) ; ++ i ; } } else if ( ch == ' ' && i + 1 < size ) { ch = tx . charAt ( i + 1 ) ; if ( ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ) { buf . append ( ch ) ; i += 2 ; } else { buf . append ( ' ' ) ; ++ i ; } } else { buf . append ( ch ) ; ++ i ; } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Invokes parserController to parse the included page [CODESPLIT] private void processIncludeDirective ( String file , Node parent ) throws JasperException { if ( file == null ) { return ; } try { parserController . parse ( file , parent , jarFileUrl ) ; } catch ( FileNotFoundException ex ) { err . jspError ( start , \"jsp.error.file.not.found\" , file ) ; } catch ( Exception ex ) { err . jspError ( start , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a page directive with the following syntax : PageDirective :: = ( S Attribute ) * [CODESPLIT] private void parsePageDirective ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; Node . PageDirective n = new Node . PageDirective ( attrs , start , parent ) ; /*\n\t * A page directive may contain multiple 'import' attributes, each of\n\t * which consists of a comma-separated list of package names.\n\t * Store each list with the node, where it is parsed.\n\t */ for ( int i = 0 ; i < attrs . getLength ( ) ; i ++ ) { if ( \"import\" . equals ( attrs . getQName ( i ) ) ) { n . addImport ( attrs . getValue ( i ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses an include directive with the following syntax : IncludeDirective :: = ( S Attribute ) * [CODESPLIT] private void parseIncludeDirective ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; // Included file expanded here Node includeNode = new Node . IncludeDirective ( attrs , start , parent ) ; processIncludeDirective ( attrs . getValue ( \"file\" ) , includeNode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a list of files . This is used for implementing include - prelude and include - coda of jsp - config element in web . xml [CODESPLIT] private void addInclude ( Node parent , List files ) throws JasperException { if ( files != null ) { Iterator iter = files . iterator ( ) ; while ( iter . hasNext ( ) ) { String file = ( String ) iter . next ( ) ; AttributesImpl attrs = new AttributesImpl ( ) ; attrs . addAttribute ( \"\" , \"file\" , \"file\" , \"CDATA\" , file ) ; // Create a dummy Include directive node Node includeNode = new Node . IncludeDirective ( attrs , reader . mark ( ) , parent ) ; processIncludeDirective ( file , includeNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a taglib directive with the following syntax : Directive :: = ( S Attribute ) * [CODESPLIT] private void parseTaglibDirective ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; String uri = attrs . getValue ( \"uri\" ) ; String prefix = attrs . getValue ( \"prefix\" ) ; if ( prefix != null ) { Mark prevMark = pageInfo . getNonCustomTagPrefix ( prefix ) ; if ( prevMark != null ) { err . jspError ( reader . mark ( ) , \"jsp.error.prefix.use_before_dcl\" , prefix , prevMark . getFile ( ) , \"\" + prevMark . getLineNumber ( ) ) ; } if ( uri != null ) { String uriPrev = pageInfo . getURI ( prefix ) ; if ( uriPrev != null && ! uriPrev . equals ( uri ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.prefix.refined\" , prefix , uri , uriPrev ) ; } /* GlassFish 750\n\t\tif (pageInfo.getTaglib(uri) == null) {\n\t\t    String[] location = ctxt.getTldLocation(uri);\n                    TagLibraryInfoImpl taglib = null;\n                    try {\n\t\t        taglib = new TagLibraryInfoImpl(ctxt,\n                                                        parserController,\n                                                        prefix,\n                                                        uri,\n                                                        location,\n                                                        err);\n                    } catch (JasperException je) {\n                        err.throwException(reader.mark(), je);\n                    }\n\t\t    pageInfo.addTaglib(uri, taglib);\n\t\t}\n                */ // START GlassFish 750 ConcurrentHashMap < String , TagLibraryInfoImpl > taglibs = ctxt . getTaglibs ( ) ; TagLibraryInfoImpl taglib = taglibs . get ( uri ) ; if ( taglib == null ) { synchronized ( taglibs ) { taglib = taglibs . get ( uri ) ; if ( taglib == null ) { String [ ] location = ctxt . getTldLocation ( uri ) ; try { taglib = new TagLibraryInfoImpl ( ctxt , parserController , prefix , uri , location , err ) ; } catch ( JasperException je ) { err . throwException ( reader . mark ( ) , je ) ; } ctxt . addTaglib ( uri , taglib ) ; pageInfo . addTaglib ( uri , taglib ) ; } } } if ( pageInfo . getTaglib ( uri ) == null ) { pageInfo . addTaglib ( uri , new TagLibraryInfoImpl ( prefix , uri , taglib , pageInfo ) ) ; } // END GlassFish 750   pageInfo . addPrefixMapping ( prefix , uri ) ; } else { String tagdir = attrs . getValue ( \"tagdir\" ) ; if ( tagdir != null ) { String urnTagdir = URN_JSPTAGDIR + tagdir ; if ( pageInfo . getTaglib ( urnTagdir ) == null ) { pageInfo . addTaglib ( urnTagdir , new ImplicitTagLibraryInfo ( ctxt , parserController , prefix , tagdir , err ) ) ; } pageInfo . addPrefixMapping ( prefix , urnTagdir ) ; } } } new Node . TaglibDirective ( attrs , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a directive with the following syntax : Directive :: = S? ( page PageDirective | include IncludeDirective | taglib TagLibDirective ) S? % > [CODESPLIT] private void parseDirective ( Node parent ) throws JasperException { reader . skipSpaces ( ) ; String directive = null ; if ( reader . matches ( \"page\" ) ) { directive = \"&lt;%@ page\" ; if ( isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.istagfile\" , directive ) ; } parsePageDirective ( parent ) ; } else if ( reader . matches ( \"include\" ) ) { directive = \"&lt;%@ include\" ; parseIncludeDirective ( parent ) ; } else if ( reader . matches ( \"taglib\" ) ) { if ( directivesOnly ) { // No need to get the tagLibInfo objects.  This alos suppresses // parsing of any tag files used in this tag file. return ; } directive = \"&lt;%@ taglib\" ; parseTaglibDirective ( parent ) ; } else if ( reader . matches ( \"tag\" ) ) { directive = \"&lt;%@ tag\" ; if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.isnottagfile\" , directive ) ; } parseTagDirective ( parent ) ; } else if ( reader . matches ( \"attribute\" ) ) { directive = \"&lt;%@ attribute\" ; if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.isnottagfile\" , directive ) ; } parseAttributeDirective ( parent ) ; } else if ( reader . matches ( \"variable\" ) ) { directive = \"&lt;%@ variable\" ; if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.isnottagfile\" , directive ) ; } parseVariableDirective ( parent ) ; } else { err . jspError ( reader . mark ( ) , \"jsp.error.invalid.directive\" , reader . parseToken ( false ) ) ; } reader . skipSpaces ( ) ; if ( ! reader . matches ( \"%>\" ) ) { err . jspError ( start , \"jsp.error.unterminated\" , directive ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a directive with the following syntax : [CODESPLIT] private void parseXMLDirective ( Node parent ) throws JasperException { reader . skipSpaces ( ) ; String eTag = null ; if ( reader . matches ( \"page\" ) ) { eTag = \"jsp:directive.page\" ; if ( isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.istagfile\" , \"&lt;\" + eTag ) ; } parsePageDirective ( parent ) ; } else if ( reader . matches ( \"include\" ) ) { eTag = \"jsp:directive.include\" ; parseIncludeDirective ( parent ) ; } else if ( reader . matches ( \"tag\" ) ) { eTag = \"jsp:directive.tag\" ; if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.isnottagfile\" , \"&lt;\" + eTag ) ; } parseTagDirective ( parent ) ; } else if ( reader . matches ( \"attribute\" ) ) { eTag = \"jsp:directive.attribute\" ; if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.isnottagfile\" , \"&lt;\" + eTag ) ; } parseAttributeDirective ( parent ) ; } else if ( reader . matches ( \"variable\" ) ) { eTag = \"jsp:directive.variable\" ; if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.directive.isnottagfile\" , \"&lt;\" + eTag ) ; } parseVariableDirective ( parent ) ; } else { err . jspError ( reader . mark ( ) , \"jsp.error.invalid.directive\" , reader . parseToken ( false ) ) ; } reader . skipSpaces ( ) ; if ( reader . matches ( \">\" ) ) { reader . skipSpaces ( ) ; if ( ! reader . matchesETag ( eTag ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;\" + eTag ) ; } } else if ( ! reader . matches ( \"/>\" ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;\" + eTag ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a tag directive with the following syntax : PageDirective :: = ( S Attribute ) * [CODESPLIT] private void parseTagDirective ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; Node . TagDirective n = new Node . TagDirective ( attrs , start , parent ) ; /*\n         * A page directive may contain multiple 'import' attributes, each of\n         * which consists of a comma-separated list of package names.\n         * Store each list with the node, where it is parsed.\n         */ for ( int i = 0 ; i < attrs . getLength ( ) ; i ++ ) { if ( \"import\" . equals ( attrs . getQName ( i ) ) ) { n . addImport ( attrs . getValue ( i ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a attribute directive with the following syntax : AttributeDirective :: = ( S Attribute ) * [CODESPLIT] private void parseAttributeDirective ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; new Node . AttributeDirective ( attrs , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses a variable directive with the following syntax : PageDirective :: = ( S Attribute ) * [CODESPLIT] private void parseVariableDirective ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; new Node . VariableDirective ( attrs , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * JSPCommentBody :: = ( Char * - ( Char * -- % > )) -- % > [CODESPLIT] private void parseComment ( Node parent ) throws JasperException { start = reader . mark ( ) ; Mark stop = reader . skipUntil ( \"--%>\" ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;%--\" ) ; } new Node . Comment ( reader . getText ( start , stop ) , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * DeclarationBody :: = ( Char * - ( char * % > )) % > [CODESPLIT] private void parseDeclaration ( Node parent ) throws JasperException { start = reader . mark ( ) ; Mark stop = reader . skipUntil ( \"%>\" ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;%!\" ) ; } new Node . Declaration ( parseScriptText ( reader . getText ( start , stop ) ) , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * XMLDeclarationBody :: = ( S? / > ) | ( S? > ( Char * - ( char * < )) CDSect? ) * ETag | <TRANSLATION_ERROR > CDSect :: = CDStart CData CDEnd CDStart :: = <! [ CDATA [ CData :: = ( Char * - ( Char * ]] > Char * )) CDEnd :: = ]] > [CODESPLIT] private void parseXMLDeclaration ( Node parent ) throws JasperException { reader . skipSpaces ( ) ; if ( ! reader . matches ( \"/>\" ) ) { if ( ! reader . matches ( \">\" ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;jsp:declaration&gt;\" ) ; } Mark stop ; String text ; while ( true ) { start = reader . mark ( ) ; stop = reader . skipUntil ( \"<\" ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;jsp:declaration&gt;\" ) ; } text = parseScriptText ( reader . getText ( start , stop ) ) ; new Node . Declaration ( text , start , parent ) ; if ( reader . matches ( \"![CDATA[\" ) ) { start = reader . mark ( ) ; stop = reader . skipUntil ( \"]]>\" ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"CDATA\" ) ; } text = parseScriptText ( reader . getText ( start , stop ) ) ; new Node . Declaration ( text , start , parent ) ; } else { break ; } } if ( ! reader . matchesETagWithoutLessThan ( \"jsp:declaration\" ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;jsp:declaration&gt;\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ExpressionBody :: = ( Char * - ( char * % > )) % > [CODESPLIT] private void parseExpression ( Node parent ) throws JasperException { start = reader . mark ( ) ; Mark stop = reader . skipUntil ( \"%>\" ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;%=\" ) ; } new Node . Expression ( parseScriptText ( reader . getText ( start , stop ) ) , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ELExpressionBody ( following $ { or # { to first unquoted } ) // XXX add formal production and confirm implementation against it // once it s decided [CODESPLIT] private void parseELExpression ( Node parent , String typeEL ) throws JasperException { start = reader . mark ( ) ; boolean singleQuoted = false , doubleQuoted = false ; int curl = 0 ; int currentChar ; do { // XXX could move this logic to JspReader currentChar = reader . nextChar ( ) ; if ( currentChar == ' ' && ( singleQuoted || doubleQuoted ) ) { // skip character following '\\' within quotes reader . nextChar ( ) ; currentChar = reader . nextChar ( ) ; } if ( currentChar == - 1 ) err . jspError ( start , \"jsp.error.unterminated\" , typeEL ) ; if ( currentChar == ' ' ) doubleQuoted = ! doubleQuoted ; else if ( currentChar == ' ' ) singleQuoted = ! singleQuoted ; else if ( currentChar == ' ' ) curl ++ ; else if ( currentChar == ' ' ) curl -- ; } while ( currentChar != ' ' || curl >= 0 || singleQuoted || doubleQuoted ) ; String text = typeEL + reader . getText ( start , reader . mark ( ) ) ; new Node . ELExpression ( text , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ScriptletBody :: = ( Char * - ( char * % > )) % > [CODESPLIT] private void parseScriptlet ( Node parent ) throws JasperException { start = reader . mark ( ) ; Mark stop = reader . skipUntil ( \"%>\" ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;%\" ) ; } new Node . Scriptlet ( parseScriptText ( reader . getText ( start , stop ) ) , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Param :: = <jsp : param S Attributes S? EmptyBody S? [CODESPLIT] private void parseParam ( Node parent ) throws JasperException { if ( ! reader . matches ( \"<jsp:param\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.paramexpected\" ) ; } Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; Node paramActionNode = new Node . ParamAction ( attrs , start , parent ) ; parseEmptyBody ( paramActionNode , \"jsp:param\" ) ; reader . skipSpaces ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * For Include : StdActionContent :: = Attributes ParamBody [CODESPLIT] private void parseInclude ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; Node includeNode = new Node . IncludeAction ( attrs , start , parent ) ; parseOptionalBody ( includeNode , \"jsp:include\" , JAVAX_BODY_CONTENT_PARAM ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * For Forward : StdActionContent :: = Attributes ParamBody [CODESPLIT] private void parseForward ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; Node forwardNode = new Node . ForwardAction ( attrs , start , parent ) ; parseOptionalBody ( forwardNode , \"jsp:forward\" , JAVAX_BODY_CONTENT_PARAM ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * For GetProperty : StdActionContent :: = Attributes EmptyBody [CODESPLIT] private void parseGetProperty ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; Node getPropertyNode = new Node . GetProperty ( attrs , start , parent ) ; parseOptionalBody ( getPropertyNode , \"jsp:getProperty\" , TagInfo . BODY_CONTENT_EMPTY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * For SetProperty : StdActionContent :: = Attributes EmptyBody [CODESPLIT] private void parseSetProperty ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; Node setPropertyNode = new Node . SetProperty ( attrs , start , parent ) ; parseOptionalBody ( setPropertyNode , \"jsp:setProperty\" , TagInfo . BODY_CONTENT_EMPTY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * EmptyBody :: = / > | ( > ETag ) | ( > S? <jsp : attribute NamedAttributes ETag ) [CODESPLIT] private void parseEmptyBody ( Node parent , String tag ) throws JasperException { if ( reader . matches ( \"/>\" ) ) { // Done } else if ( reader . matches ( \">\" ) ) { if ( reader . matchesETag ( tag ) ) { // Done } else if ( reader . matchesOptionalSpacesFollowedBy ( \"<jsp:attribute\" ) ) { // Parse the one or more named attribute nodes parseNamedAttributes ( parent ) ; if ( ! reader . matchesETag ( tag ) ) { // Body not allowed err . jspError ( reader . mark ( ) , \"jsp.error.jspbody.emptybody.only\" , \"&lt;\" + tag ) ; } } else { err . jspError ( reader . mark ( ) , \"jsp.error.jspbody.emptybody.only\" , \"&lt;\" + tag ) ; } } else { err . jspError ( reader . mark ( ) , \"jsp.error.unterminated\" , \"&lt;\" + tag ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * For UseBean : StdActionContent :: = Attributes OptionalBody [CODESPLIT] private void parseUseBean ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; Node useBeanNode = new Node . UseBean ( attrs , start , parent ) ; parseOptionalBody ( useBeanNode , \"jsp:useBean\" , TagInfo . BODY_CONTENT_JSP ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses OptionalBody but also reused to parse bodies for plugin and param since the syntax is identical ( the only thing that differs substantially is how to process the body and thus we accept the body type as a parameter ) . [CODESPLIT] private void parseOptionalBody ( Node parent , String tag , String bodyType ) throws JasperException { if ( reader . matches ( \"/>\" ) ) { // EmptyBody return ; } if ( ! reader . matches ( \">\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.unterminated\" , \"&lt;\" + tag ) ; } if ( reader . matchesETag ( tag ) ) { // EmptyBody return ; } if ( ! parseJspAttributeAndBody ( parent , tag , bodyType ) ) { // Must be ( '>' # Body ETag ) parseBody ( parent , tag , bodyType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to parse JspAttributeAndBody production . Returns true if it matched or false if not . Assumes EmptyBody is okay as well . [CODESPLIT] private boolean parseJspAttributeAndBody ( Node parent , String tag , String bodyType ) throws JasperException { boolean result = false ; if ( reader . matchesOptionalSpacesFollowedBy ( \"<jsp:attribute\" ) ) { // May be an EmptyBody, depending on whether // There's a \"<jsp:body\" before the ETag // First, parse <jsp:attribute> elements: parseNamedAttributes ( parent ) ; result = true ; } if ( reader . matchesOptionalSpacesFollowedBy ( \"<jsp:body\" ) ) { // ActionBody parseJspBody ( parent , bodyType ) ; reader . skipSpaces ( ) ; if ( ! reader . matchesETag ( tag ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.unterminated\" , \"&lt;\" + tag ) ; } result = true ; } else if ( result && ! reader . matchesETag ( tag ) ) { // If we have <jsp:attribute> but something other than // <jsp:body> or the end tag, translation error. err . jspError ( reader . mark ( ) , \"jsp.error.jspbody.required\" , \"&lt;\" + tag ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Params :: = > S? ( ( <jsp : body > ( ( S? Param + S? < / jsp : body > ) | <TRANSLATION_ERROR > ) ) | Param + ) < / jsp : params > [CODESPLIT] private void parseJspParams ( Node parent ) throws JasperException { Node jspParamsNode = new Node . ParamsAction ( start , parent ) ; parseOptionalBody ( jspParamsNode , \"jsp:params\" , JAVAX_BODY_CONTENT_PARAM ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Fallback :: = / > | ( > S? <jsp : body > ( ( S? ( Char * - ( Char * < / jsp : body > ) ) < / jsp : body > S? ) | <TRANSLATION_ERROR > ) < / jsp : fallback > ) | ( > ( Char * - ( Char * < / jsp : fallback > ) ) < / jsp : fallback > ) [CODESPLIT] private void parseFallBack ( Node parent ) throws JasperException { Node fallBackNode = new Node . FallBackAction ( start , parent ) ; parseOptionalBody ( fallBackNode , \"jsp:fallback\" , JAVAX_BODY_CONTENT_TEMPLATE_TEXT ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * For Plugin : StdActionContent :: = Attributes PluginBody [CODESPLIT] private void parsePlugin ( Node parent ) throws JasperException { Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; Node pluginNode = new Node . PlugIn ( attrs , start , parent ) ; parseOptionalBody ( pluginNode , \"jsp:plugin\" , JAVAX_BODY_CONTENT_PLUGIN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * PluginTags :: = ( <jsp : params Params S? ) ? ( <jsp : fallback Fallback? S? ) ? [CODESPLIT] private void parsePluginTags ( Node parent ) throws JasperException { reader . skipSpaces ( ) ; if ( reader . matches ( \"<jsp:params\" ) ) { parseJspParams ( parent ) ; reader . skipSpaces ( ) ; } if ( reader . matches ( \"<jsp:fallback\" ) ) { parseFallBack ( parent ) ; reader . skipSpaces ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * StandardAction :: = include StdActionContent | forward StdActionContent | invoke StdActionContent | doBody StdActionContent | getProperty StdActionContent | setProperty StdActionContent | useBean StdActionContent | plugin StdActionContent | element StdActionContent [CODESPLIT] private void parseStandardAction ( Node parent ) throws JasperException { Mark start = reader . mark ( ) ; if ( reader . matches ( INCLUDE_ACTION ) ) { parseInclude ( parent ) ; } else if ( reader . matches ( FORWARD_ACTION ) ) { parseForward ( parent ) ; } else if ( reader . matches ( INVOKE_ACTION ) ) { if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.action.isnottagfile\" , \"&lt;jsp:invoke\" ) ; } parseInvoke ( parent ) ; } else if ( reader . matches ( DOBODY_ACTION ) ) { if ( ! isTagFile ) { err . jspError ( reader . mark ( ) , \"jsp.error.action.isnottagfile\" , \"&lt;jsp:doBody\" ) ; } parseDoBody ( parent ) ; } else if ( reader . matches ( GET_PROPERTY_ACTION ) ) { parseGetProperty ( parent ) ; } else if ( reader . matches ( SET_PROPERTY_ACTION ) ) { parseSetProperty ( parent ) ; } else if ( reader . matches ( USE_BEAN_ACTION ) ) { parseUseBean ( parent ) ; } else if ( reader . matches ( PLUGIN_ACTION ) ) { parsePlugin ( parent ) ; } else if ( reader . matches ( ELEMENT_ACTION ) ) { parseElement ( parent ) ; } else if ( reader . matches ( ATTRIBUTE_ACTION ) ) { err . jspError ( start , \"jsp.error.namedAttribute.invalidUse\" ) ; } else if ( reader . matches ( BODY_ACTION ) ) { err . jspError ( start , \"jsp.error.jspbody.invalidUse\" ) ; } else if ( reader . matches ( FALLBACK_ACTION ) ) { err . jspError ( start , \"jsp.error.fallback.invalidUse\" ) ; } else if ( reader . matches ( PARAMS_ACTION ) ) { err . jspError ( start , \"jsp.error.params.invalidUse\" ) ; } else if ( reader . matches ( PARAM_ACTION ) ) { err . jspError ( start , \"jsp.error.param.invalidUse\" ) ; } else if ( reader . matches ( OUTPUT_ACTION ) ) { err . jspError ( start , \"jsp.error.jspoutput.invalidUse\" ) ; } else { err . jspError ( start , \"jsp.error.badStandardAction\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * # < CustomAction CustomActionBody [CODESPLIT] private boolean parseCustomTag ( Node parent ) throws JasperException { if ( reader . peekChar ( ) != ' ' ) { return false ; } // Parse 'CustomAction' production (tag prefix and custom action name) reader . nextChar ( ) ; // skip '<' String tagName = reader . parseToken ( false ) ; int i = tagName . indexOf ( ' ' ) ; if ( i == - 1 ) { reader . reset ( start ) ; return false ; } String prefix = tagName . substring ( 0 , i ) ; String shortTagName = tagName . substring ( i + 1 ) ; // Check if this is a user-defined tag. String uri = pageInfo . getURI ( prefix ) ; if ( uri == null ) { // If error-on-undeclared-namespace is set to true in // jsp-property-group, then it is an error if ( pageInfo . errorOnUndeclaredNamespace ( ) ) { err . jspError ( start , \"jsp.error.undeclared.namespace\" , prefix ) ; } reader . reset ( start ) ; // Remember the prefix for later error checking pageInfo . putNonCustomTagPrefix ( prefix , reader . mark ( ) ) ; return false ; } TagLibraryInfo tagLibInfo = pageInfo . getTaglib ( uri ) ; TagInfo tagInfo = tagLibInfo . getTag ( shortTagName ) ; TagFileInfo tagFileInfo = tagLibInfo . getTagFile ( shortTagName ) ; if ( tagInfo == null && tagFileInfo == null ) { err . jspError ( start , \"jsp.error.bad_tag\" , shortTagName , prefix ) ; } Class tagHandlerClass = null ; if ( tagInfo != null ) { // Must be a classic tag, load it here. // tag files will be loaded later, in TagFileProcessor String handlerClassName = tagInfo . getTagClassName ( ) ; try { tagHandlerClass = ctxt . getClassLoader ( ) . loadClass ( handlerClassName ) ; } catch ( Exception e ) { err . jspError ( start , \"jsp.error.loadclass.taghandler\" , handlerClassName , tagName ) ; } } // Parse 'CustomActionBody' production: // At this point we are committed - if anything fails, we produce // a translation error. // Parse 'Attributes' production: Attributes attrs = parseAttributes ( ) ; reader . skipSpaces ( ) ; // Parse 'CustomActionEnd' production: if ( reader . matches ( \"/>\" ) ) { if ( tagInfo != null ) { new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , tagName , prefix , shortTagName , uri , attrs , start , parent , tagInfo , tagHandlerClass ) ; } else { new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , tagName , prefix , shortTagName , uri , attrs , start , parent , tagFileInfo ) ; } return true ; } // Now we parse one of 'CustomActionTagDependent',  // 'CustomActionJSPContent', or 'CustomActionScriptlessContent'. // depending on body-content in TLD. // Looking for a body, it still can be empty; but if there is a // a tag body, its syntax would be dependent on the type of // body content declared in the TLD. String bc ; if ( tagInfo != null ) { bc = tagInfo . getBodyContent ( ) ; } else { bc = tagFileInfo . getTagInfo ( ) . getBodyContent ( ) ; } Node tagNode = null ; if ( tagInfo != null ) { tagNode = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , tagName , prefix , shortTagName , uri , attrs , start , parent , tagInfo , tagHandlerClass ) ; } else { tagNode = new Node . CustomTag ( tagLibInfo . getRequiredVersion ( ) , tagName , prefix , shortTagName , uri , attrs , start , parent , tagFileInfo ) ; } parseOptionalBody ( tagNode , tagName , bc ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parse for a template text string until < or $ { is encountered recognizing escape sequences \\ % \\ $ and \\ # . [CODESPLIT] private void parseTemplateText ( Node parent ) throws JasperException { if ( ! reader . hasMoreInput ( ) ) return ; CharArrayWriter ttext = new CharArrayWriter ( ) ; // Output the first character int ch = reader . nextChar ( ) ; if ( ch == ' ' ) { reader . pushChar ( ) ; } else { ttext . write ( ch ) ; } while ( reader . hasMoreInput ( ) ) { ch = reader . nextChar ( ) ; if ( ch == ' ' ) { reader . pushChar ( ) ; break ; } else if ( ch == ' ' || ch == ' ' ) { if ( ! reader . hasMoreInput ( ) ) { ttext . write ( ch ) ; break ; } if ( reader . nextChar ( ) == ' ' ) { reader . pushChar ( ) ; reader . pushChar ( ) ; break ; } ttext . write ( ch ) ; reader . pushChar ( ) ; continue ; } else if ( ch == ' ' ) { if ( ! reader . hasMoreInput ( ) ) { ttext . write ( ' ' ) ; break ; } char next = ( char ) reader . peekChar ( ) ; // Looking for \\% or \\$ // Note that this behavior can be altered by the attributes // el-ignored and deferred-syntax-allowed-as-literal and // similar attributes in a page directive.  However, since // the page direcitve may appear later in the same page, the // '\\' will be regenerated in Generator.java. if ( next == ' ' || next == ' ' || next == ' ' ) { ch = reader . nextChar ( ) ; } } ttext . write ( ch ) ; } new Node . TemplateText ( ttext . toString ( ) , start , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * XMLTemplateText :: = ( S? / > ) | ( S? > ( ( Char * - ( Char * ( < | $ { ) ) ) ( $ { ELExpressionBody ) ? CDSect? ) * ETag ) | <TRANSLATION_ERROR > [CODESPLIT] private void parseXMLTemplateText ( Node parent ) throws JasperException { reader . skipSpaces ( ) ; if ( ! reader . matches ( \"/>\" ) ) { if ( ! reader . matches ( \">\" ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;jsp:text&gt;\" ) ; } CharArrayWriter ttext = new CharArrayWriter ( ) ; while ( reader . hasMoreInput ( ) ) { int ch = reader . nextChar ( ) ; if ( ch == ' ' ) { // Check for <![CDATA[ if ( ! reader . matches ( \"![CDATA[\" ) ) { break ; } start = reader . mark ( ) ; Mark stop = reader . skipUntil ( \"]]>\" ) ; if ( stop == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"CDATA\" ) ; } String text = reader . getText ( start , stop ) ; ttext . write ( text , 0 , text . length ( ) ) ; } else if ( ch == ' ' ) { if ( ! reader . hasMoreInput ( ) ) { ttext . write ( ' ' ) ; break ; } ch = reader . nextChar ( ) ; if ( ch != ' ' && ch != ' ' ) { ttext . write ( ' ' ) ; } ttext . write ( ch ) ; } else if ( ch == ' ' || ch == ' ' ) { if ( ! reader . hasMoreInput ( ) ) { ttext . write ( ch ) ; break ; } if ( reader . nextChar ( ) != ' ' ) { ttext . write ( ch ) ; reader . pushChar ( ) ; continue ; } // Create a template text node new Node . TemplateText ( ttext . toString ( ) , start , parent ) ; // Mark and parse the EL expression and create its node: start = reader . mark ( ) ; parseELExpression ( parent , ( ch == ' ' ) ? \"${\" : \"#{\" ) ; start = reader . mark ( ) ; ttext = new CharArrayWriter ( ) ; } else { ttext . write ( ch ) ; } } new Node . TemplateText ( ttext . toString ( ) , start , parent ) ; if ( ! reader . hasMoreInput ( ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;jsp:text&gt;\" ) ; } else if ( ! reader . matchesETagWithoutLessThan ( \"jsp:text\" ) ) { err . jspError ( start , \"jsp.error.jsptext.badcontent\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * AllBody :: = ( <% -- JSPCommentBody ) | ( <% [CODESPLIT] private void parseElements ( Node parent ) throws JasperException { if ( scriptlessCount > 0 ) { // vc: ScriptlessBody // We must follow the ScriptlessBody production if one of // our parents is ScriptlessBody. parseElementsScriptless ( parent ) ; return ; } start = reader . mark ( ) ; if ( reader . matches ( \"<%--\" ) ) { parseComment ( parent ) ; } else if ( reader . matches ( \"<%@\" ) ) { parseDirective ( parent ) ; } else if ( reader . matches ( \"<jsp:directive.\" ) ) { parseXMLDirective ( parent ) ; } else if ( reader . matches ( \"<%!\" ) ) { parseDeclaration ( parent ) ; } else if ( reader . matches ( \"<jsp:declaration\" ) ) { parseXMLDeclaration ( parent ) ; } else if ( reader . matches ( \"<%=\" ) ) { parseExpression ( parent ) ; } else if ( reader . matches ( \"<jsp:expression\" ) ) { parseXMLExpression ( parent ) ; } else if ( reader . matches ( \"<%\" ) ) { parseScriptlet ( parent ) ; } else if ( reader . matches ( \"<jsp:scriptlet\" ) ) { parseXMLScriptlet ( parent ) ; } else if ( reader . matches ( \"<jsp:text\" ) ) { parseXMLTemplateText ( parent ) ; } else if ( reader . matches ( \"${\" ) ) { parseELExpression ( parent , \"${\" ) ; } else if ( reader . matches ( \"#{\" ) ) { parseELExpression ( parent , \"#{\" ) ; } else if ( reader . matches ( \"<jsp:\" ) ) { parseStandardAction ( parent ) ; } else if ( ! parseCustomTag ( parent ) ) { checkUnbalancedEndTag ( ) ; parseTemplateText ( parent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ScriptlessBody :: = ( <% -- JSPCommentBody ) | ( <% [CODESPLIT] private void parseElementsScriptless ( Node parent ) throws JasperException { // Keep track of how many scriptless nodes we've encountered // so we know whether our child nodes are forced scriptless scriptlessCount ++ ; start = reader . mark ( ) ; if ( reader . matches ( \"<%--\" ) ) { parseComment ( parent ) ; } else if ( reader . matches ( \"<%@\" ) ) { parseDirective ( parent ) ; } else if ( reader . matches ( \"<jsp:directive.\" ) ) { parseXMLDirective ( parent ) ; } else if ( reader . matches ( \"<%!\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.no.scriptlets\" ) ; } else if ( reader . matches ( \"<jsp:declaration\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.no.scriptlets\" ) ; } else if ( reader . matches ( \"<%=\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.no.scriptlets\" ) ; } else if ( reader . matches ( \"<jsp:expression\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.no.scriptlets\" ) ; } else if ( reader . matches ( \"<%\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.no.scriptlets\" ) ; } else if ( reader . matches ( \"<jsp:scriptlet\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.no.scriptlets\" ) ; } else if ( reader . matches ( \"<jsp:text\" ) ) { parseXMLTemplateText ( parent ) ; } else if ( reader . matches ( \"${\" ) ) { parseELExpression ( parent , \"${\" ) ; } else if ( reader . matches ( \"#{\" ) ) { parseELExpression ( parent , \"#{\" ) ; } else if ( reader . matches ( \"<jsp:\" ) ) { parseStandardAction ( parent ) ; } else if ( ! parseCustomTag ( parent ) ) { checkUnbalancedEndTag ( ) ; parseTemplateText ( parent ) ; } scriptlessCount -- ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * TemplateTextBody :: = ( <% -- JSPCommentBody ) | ( <% [CODESPLIT] private void parseElementsTemplateText ( Node parent ) throws JasperException { start = reader . mark ( ) ; if ( reader . matches ( \"<%--\" ) ) { parseComment ( parent ) ; } else if ( reader . matches ( \"<%@\" ) ) { parseDirective ( parent ) ; } else if ( reader . matches ( \"<jsp:directive.\" ) ) { parseXMLDirective ( parent ) ; } else if ( reader . matches ( \"<%!\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Declarations\" ) ; } else if ( reader . matches ( \"<jsp:declaration\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Declarations\" ) ; } else if ( reader . matches ( \"<%=\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Expressions\" ) ; } else if ( reader . matches ( \"<jsp:expression\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Expressions\" ) ; } else if ( reader . matches ( \"<%\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Scriptlets\" ) ; } else if ( reader . matches ( \"<jsp:scriptlet\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Scriptlets\" ) ; } else if ( reader . matches ( \"<jsp:text\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"&lt;jsp:text\" ) ; } else if ( reader . matches ( \"${\" ) || reader . matches ( \"#{\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Expression language\" ) ; } else if ( reader . matches ( \"<jsp:\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Standard actions\" ) ; } else if ( parseCustomTag ( parent ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.not.in.template\" , \"Custom actions\" ) ; } else { checkUnbalancedEndTag ( ) ; parseTemplateText ( parent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Flag as error if an unbalanced end tag appears by itself . [CODESPLIT] private void checkUnbalancedEndTag ( ) throws JasperException { if ( ! reader . matches ( \"</\" ) ) { return ; } // Check for unbalanced standard actions if ( reader . matches ( \"jsp:\" ) ) { err . jspError ( start , \"jsp.error.unbalanced.endtag\" , \"jsp:\" ) ; } // Check for unbalanced custom actions String tagName = reader . parseToken ( false ) ; int i = tagName . indexOf ( ' ' ) ; if ( i == - 1 || pageInfo . getURI ( tagName . substring ( 0 , i ) ) == null ) { reader . reset ( start ) ; return ; } err . jspError ( start , \"jsp.error.unbalanced.endtag\" , tagName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TagDependentBody : = [CODESPLIT] private void parseTagDependentBody ( Node parent , String tag ) throws JasperException { Mark bodyStart = reader . mark ( ) ; Mark bodyEnd = reader . skipUntilETag ( tag ) ; if ( bodyEnd == null ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;\" + tag ) ; } new Node . TemplateText ( reader . getText ( bodyStart , bodyEnd ) , bodyStart , parent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses jsp : body action . [CODESPLIT] private void parseJspBody ( Node parent , String bodyType ) throws JasperException { Mark start = reader . mark ( ) ; Node bodyNode = new Node . JspBody ( start , parent ) ; reader . skipSpaces ( ) ; if ( ! reader . matches ( \"/>\" ) ) { if ( ! reader . matches ( \">\" ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;jsp:body\" ) ; } parseBody ( bodyNode , \"jsp:body\" , bodyType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parse the body as JSP content . [CODESPLIT] private void parseBody ( Node parent , String tag , String bodyType ) throws JasperException { if ( bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_TAG_DEPENDENT ) ) { parseTagDependentBody ( parent , tag ) ; } else if ( bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_EMPTY ) ) { if ( ! reader . matchesETag ( tag ) ) { err . jspError ( start , \"jasper.error.emptybodycontent.nonempty\" , tag ) ; } } else if ( bodyType == JAVAX_BODY_CONTENT_PLUGIN ) { // (note the == since we won't recognize JAVAX_*  // from outside this module). parsePluginTags ( parent ) ; if ( ! reader . matchesETag ( tag ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.unterminated\" , \"&lt;\" + tag ) ; } } else if ( bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_JSP ) || bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_SCRIPTLESS ) || ( bodyType == JAVAX_BODY_CONTENT_PARAM ) || ( bodyType == JAVAX_BODY_CONTENT_TEMPLATE_TEXT ) ) { while ( reader . hasMoreInput ( ) ) { if ( reader . matchesETag ( tag ) ) { return ; } // Check for nested jsp:body or jsp:attribute if ( tag . equals ( \"jsp:body\" ) || tag . equals ( \"jsp:attribute\" ) ) { if ( reader . matches ( \"<jsp:attribute\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.nested.jspattribute\" ) ; } else if ( reader . matches ( \"<jsp:body\" ) ) { err . jspError ( reader . mark ( ) , \"jsp.error.nested.jspbody\" ) ; } } if ( bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_JSP ) ) { parseElements ( parent ) ; } else if ( bodyType . equalsIgnoreCase ( TagInfo . BODY_CONTENT_SCRIPTLESS ) ) { parseElementsScriptless ( parent ) ; } else if ( bodyType == JAVAX_BODY_CONTENT_PARAM ) { // (note the == since we won't recognize JAVAX_*  // from outside this module). reader . skipSpaces ( ) ; parseParam ( parent ) ; } else if ( bodyType == JAVAX_BODY_CONTENT_TEMPLATE_TEXT ) { parseElementsTemplateText ( parent ) ; } } err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;\" + tag ) ; } else { err . jspError ( start , \"jsp.error.tld.badbodycontent\" , bodyType , tag ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses named attributes . [CODESPLIT] private void parseNamedAttributes ( Node parent ) throws JasperException { do { Mark start = reader . mark ( ) ; Attributes attrs = parseAttributes ( ) ; if ( attrs == null || attrs . getValue ( \"name\" ) == null ) { err . jspError ( start , \"jsp.error.jspAttribute.missing.name\" ) ; } Node . NamedAttribute namedAttributeNode = new Node . NamedAttribute ( attrs , start , parent ) ; reader . skipSpaces ( ) ; if ( ! reader . matches ( \"/>\" ) ) { if ( ! reader . matches ( \">\" ) ) { err . jspError ( start , \"jsp.error.unterminated\" , \"&lt;jsp:attribute\" ) ; } if ( namedAttributeNode . isTrim ( ) ) { reader . skipSpaces ( ) ; } parseBody ( namedAttributeNode , \"jsp:attribute\" , getAttributeBodyType ( parent , attrs . getValue ( \"name\" ) ) ) ; if ( namedAttributeNode . isTrim ( ) ) { Node . Nodes subElems = namedAttributeNode . getBody ( ) ; if ( subElems != null ) { Node lastNode = subElems . getNode ( subElems . size ( ) - 1 ) ; if ( lastNode instanceof Node . TemplateText ) { ( ( Node . TemplateText ) lastNode ) . rtrim ( ) ; } } } } reader . skipSpaces ( ) ; } while ( reader . matches ( \"<jsp:attribute\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the body type of <jsp : attribute > from the enclosing node [CODESPLIT] private String getAttributeBodyType ( Node n , String name ) { if ( n instanceof Node . CustomTag ) { TagInfo tagInfo = ( ( Node . CustomTag ) n ) . getTagInfo ( ) ; TagAttributeInfo [ ] tldAttrs = tagInfo . getAttributes ( ) ; for ( int i = 0 ; i < tldAttrs . length ; i ++ ) { if ( name . equals ( tldAttrs [ i ] . getName ( ) ) ) { if ( tldAttrs [ i ] . isFragment ( ) ) { return TagInfo . BODY_CONTENT_SCRIPTLESS ; } if ( tldAttrs [ i ] . canBeRequestTime ( ) ) { return TagInfo . BODY_CONTENT_JSP ; } } } if ( tagInfo . hasDynamicAttributes ( ) ) { return TagInfo . BODY_CONTENT_JSP ; } } else if ( n instanceof Node . IncludeAction ) { if ( \"page\" . equals ( name ) ) { return TagInfo . BODY_CONTENT_JSP ; } } else if ( n instanceof Node . ForwardAction ) { if ( \"page\" . equals ( name ) ) { return TagInfo . BODY_CONTENT_JSP ; } } else if ( n instanceof Node . SetProperty ) { if ( \"value\" . equals ( name ) ) { return TagInfo . BODY_CONTENT_JSP ; } } else if ( n instanceof Node . UseBean ) { if ( \"beanName\" . equals ( name ) ) { return TagInfo . BODY_CONTENT_JSP ; } } else if ( n instanceof Node . PlugIn ) { if ( \"width\" . equals ( name ) || \"height\" . equals ( name ) ) { return TagInfo . BODY_CONTENT_JSP ; } } else if ( n instanceof Node . ParamAction ) { if ( \"value\" . equals ( name ) ) { return TagInfo . BODY_CONTENT_JSP ; } } else if ( n instanceof Node . JspElement ) { return TagInfo . BODY_CONTENT_JSP ; } return JAVAX_BODY_CONTENT_TEMPLATE_TEXT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the attribute that is non request time expression either from the attribute of the node or from a jsp : attrbute [CODESPLIT] public String getTextAttribute ( String name ) { String attr = getAttributeValue ( name ) ; if ( attr != null ) { return attr ; } NamedAttribute namedAttribute = getNamedAttributeNode ( name ) ; if ( namedAttribute == null ) { return null ; } return namedAttribute . getText ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches all subnodes of this node for jsp : attribute standard actions with the given name and returns the NamedAttribute node of the matching named attribute nor null if no such node is found . <p > This should always be called and only be called for nodes that accept dynamic runtime attribute expressions . [CODESPLIT] public NamedAttribute getNamedAttributeNode ( String name ) { NamedAttribute result = null ; // Look for the attribute in NamedAttribute children Nodes nodes = getNamedAttributeNodes ( ) ; int numChildNodes = nodes . size ( ) ; for ( int i = 0 ; i < numChildNodes ; i ++ ) { NamedAttribute na = ( NamedAttribute ) nodes . getNode ( i ) ; boolean found = false ; int index = name . indexOf ( ' ' ) ; if ( index != - 1 ) { // qualified name found = na . getName ( ) . equals ( name ) ; } else { found = na . getLocalName ( ) . equals ( name ) ; } if ( found ) { result = na ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches all subnodes of this node for jsp : attribute standard actions and returns that set of nodes as a Node . Nodes object . [CODESPLIT] public Node . Nodes getNamedAttributeNodes ( ) { if ( namedAttributeNodes != null ) { return namedAttributeNodes ; } Node . Nodes result = new Node . Nodes ( ) ; // Look for the attribute in NamedAttribute children Nodes nodes = getBody ( ) ; if ( nodes != null ) { int numChildNodes = nodes . size ( ) ; for ( int i = 0 ; i < numChildNodes ; i ++ ) { Node n = nodes . getNode ( i ) ; if ( n instanceof NamedAttribute ) { result . add ( n ) ; } else if ( ! ( n instanceof Comment ) ) { // Nothing can come before jsp:attribute, and only // jsp:body can come after it. break ; } } } namedAttributeNodes = result ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Adds this Node to the body of the given parent . [CODESPLIT] private void addToParent ( Node parent ) { if ( parent != null ) { this . parent = parent ; Nodes parentBody = parent . getBody ( ) ; if ( parentBody == null ) { parentBody = new Nodes ( ) ; parent . setBody ( parentBody ) ; } parentBody . add ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a list of matching factories <p > The returned list is a copy of the current state . The list may be modified by the caller but will not be updated by this tracker when the state changes . < / p > [CODESPLIT] public List < ProcessorFactoryInformation > getFactoriesFor ( final Class < ? > [ ] contextClasses ) { requireNonNull ( contextClasses ) ; final List < ProcessorFactoryInformation > result = new ArrayList <> ( ) ; this . tracker . consumeAll ( stream -> stream . filter ( service -> isMatch ( service , contextClasses ) ) . forEach ( result :: add ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an attribute to this node replacing any existing attribute with the same name . [CODESPLIT] public void addAttribute ( String name , String value ) { if ( attributes == null ) attributes = new HashMap < String , String > ( ) ; attributes . put ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new child node to this node . [CODESPLIT] public void addChild ( TreeNode node ) { if ( children == null ) children = new ArrayList < TreeNode > ( ) ; children . add ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value of the specified node attribute if it exists or <code > null< / code > otherwise . [CODESPLIT] public String findAttribute ( String name ) { if ( attributes == null ) return ( null ) ; else return ( attributes . get ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an Iterator of the attribute names of this node . If there are no attributes an empty Iterator is returned . [CODESPLIT] public Iterator < String > findAttributes ( ) { Set < String > attrs ; if ( attributes == null ) attrs = Collections . emptySet ( ) ; else attrs = attributes . keySet ( ) ; return attrs . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the first child node of this node with the specified name if there is one ; otherwise return <code > null< / code > . [CODESPLIT] public TreeNode findChild ( String name ) { if ( children == null ) return ( null ) ; for ( TreeNode item : children ) { if ( name . equals ( item . getName ( ) ) ) return ( item ) ; } return ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an Iterator of all children of this node . If there are no children an empty Iterator is returned . [CODESPLIT] public Iterator < TreeNode > findChildren ( ) { List < TreeNode > nodes ; if ( children == null ) nodes = Collections . emptyList ( ) ; else nodes = children ; return nodes . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an Iterator over all children of this node that have the specified name . If there are no such children an empty Iterator is returned . [CODESPLIT] public Iterator < TreeNode > findChildren ( String name ) { List < TreeNode > results ; if ( children == null ) results = Collections . emptyList ( ) ; else { results = new ArrayList < TreeNode > ( ) ; for ( TreeNode item : children ) { if ( name . equals ( item . getName ( ) ) ) results . add ( item ) ; } } return results . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance without classifier and extension [CODESPLIT] public MavenCoordinates toBase ( ) { if ( this . classifier == null && this . extension == null ) { return this ; } return new MavenCoordinates ( this . groupId , this . artifactId , this . version ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the given variable name is used as an alias and if so returns the variable name for which it is used as an alias . [CODESPLIT] private String findAlias ( String varName ) { if ( aliases == null ) return varName ; String alias = aliases . get ( varName ) ; if ( alias == null ) { return varName ; } return alias ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start capturing thread s output . [CODESPLIT] public static void setThread ( ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; data . set ( baos ) ; streams . set ( new PrintStream ( baos ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop capturing thread s output and return captured data as a String . [CODESPLIT] public static String unsetThread ( ) { ByteArrayOutputStream baos = ( ByteArrayOutputStream ) data . get ( ) ; if ( baos == null ) { return null ; } streams . set ( null ) ; data . set ( null ) ; return baos . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find PrintStream to which the output must be written to . [CODESPLIT] protected PrintStream findStream ( ) { PrintStream ps = ( PrintStream ) streams . get ( ) ; if ( ps == null ) { ps = wrapped ; } return ps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write field only when the value is set [CODESPLIT] protected static void writeOptional ( final StringWriter writer , final String fieldName , final String value ) { if ( value != null ) { write ( writer , fieldName , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a field [CODESPLIT] protected static void write ( final StringWriter writer , final String fieldName , final String value ) { writer . write ( fieldName + \": \" + value + \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new element and add it as the last child [CODESPLIT] public static Element addElement ( final Element parent , final String name ) { final Element ele = parent . getOwnerDocument ( ) . createElement ( name ) ; parent . appendChild ( ele ) ; return ele ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new element and add it as the first child [CODESPLIT] public static Element addElementFirst ( final Element parent , final String name ) { final Element ele = parent . getOwnerDocument ( ) . createElement ( name ) ; parent . insertBefore ( ele , null ) ; return ele ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the text value of the first element with the matching name <p > Assuming you have an XML file : [CODESPLIT] public static String getText ( final Element ele , final String name ) { for ( final Node child : iter ( ele . getChildNodes ( ) ) ) { if ( ! ( child instanceof Element ) ) { continue ; } final Element childEle = ( Element ) child ; if ( ! childEle . getNodeName ( ) . equals ( name ) ) { continue ; } return childEle . getTextContent ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a single character . [CODESPLIT] public void write ( int c ) throws IOException { if ( writer != null ) { writer . write ( c ) ; } else { ensureOpen ( ) ; if ( nextChar >= bufferSize ) { reAllocBuff ( 1 ) ; } cb [ nextChar ++ ] = ( char ) c ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a portion of an array of characters . [CODESPLIT] public void write ( char [ ] cbuf , int off , int len ) throws IOException { if ( writer != null ) { writer . write ( cbuf , off , len ) ; } else { ensureOpen ( ) ; if ( ( off < 0 ) || ( off > cbuf . length ) || ( len < 0 ) || ( ( off + len ) > cbuf . length ) || ( ( off + len ) < 0 ) ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return ; } if ( len >= bufferSize - nextChar ) reAllocBuff ( len ) ; System . arraycopy ( cbuf , off , cb , nextChar , len ) ; nextChar += len ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a portion of a String . [CODESPLIT] public void write ( String s , int off , int len ) throws IOException { if ( writer != null ) { writer . write ( s , off , len ) ; } else { ensureOpen ( ) ; if ( len >= bufferSize - nextChar ) reAllocBuff ( len ) ; s . getChars ( off , off + len , cb , nextChar ) ; nextChar += len ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the stream flushing it first . Once a stream has been closed further write () or flush () invocations will cause an IOException to be thrown . Closing a previously - closed stream however has no effect . [CODESPLIT] public void close ( ) throws IOException { if ( writer != null ) { writer . close ( ) ; } else { cb = null ; closed = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the contents of this BodyJspWriter into a Writer . Subclasses are likely to do interesting things with the implementation so some things are extra efficient . [CODESPLIT] public void writeOut ( Writer out ) throws IOException { if ( writer == null ) { out . write ( cb , 0 , nextChar ) ; // Flush not called as the writer passed could be a BodyContent and // it doesn't allow to flush. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the writer to which all output is written . [CODESPLIT] void setWriter ( Writer writer ) { this . writer = writer ; if ( writer != null ) { // According to the spec, the JspWriter returned by  // JspContext.pushBody(java.io.Writer writer) must behave as // though it were unbuffered. This means that its getBufferSize() // must always return 0. The implementation of // JspWriter.getBufferSize() returns the value of JspWriter's // 'bufferSize' field, which is inherited by this class.  // Therefore, we simply save the current 'bufferSize' (so we can  // later restore it should this BodyContentImpl ever be reused by // a call to PageContext.pushBody()) before setting it to 0. if ( bufferSize != 0 ) { bufferSizeSave = bufferSize ; bufferSize = 0 ; } } else { bufferSize = bufferSizeSave ; clearBody ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reallocates buffer since the spec requires it to be unbounded . [CODESPLIT] private void reAllocBuff ( int len ) { if ( bufferSize + len <= cb . length ) { bufferSize = cb . length ; return ; } if ( len < cb . length ) { len = cb . length ; } bufferSize = cb . length + len ; char [ ] tmp = new char [ bufferSize ] ; System . arraycopy ( cb , 0 , tmp , 0 , cb . length ) ; cb = tmp ; tmp = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the functions mappers for all EL expressions in the JSP page . [CODESPLIT] public static void map ( Compiler compiler , Node . Nodes page ) throws JasperException { ELFunctionMapper map = new ELFunctionMapper ( ) ; map . ds = new StringBuilder ( ) ; map . ss = new StringBuilder ( ) ; page . visit ( map . new ELFunctionVisitor ( ) ) ; // Append the declarations to the root node String ds = map . ds . toString ( ) ; if ( ds . length ( ) > 0 ) { Node root = page . getRoot ( ) ; new Node . Declaration ( map . ss . toString ( ) , null , root ) ; new Node . Declaration ( \"static {\\n\" + ds + \"}\\n\" , null , root ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traverse up from the provided parent and find the first which uses the same key [CODESPLIT] private static State getSameParent ( final State parent , final MetaKey key ) { State current = parent ; while ( current != null ) { if ( current . key . equals ( key ) ) { return current ; } current = current . parent ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a new model with the storage manager [CODESPLIT] public StorageRegistration registerModel ( final long lockPriority , final MetaKey key , final StorageModelProvider < ? , ? > storageProvider ) throws ModelInitializationException { this . modelLock . writeLock ( ) . lock ( ) ; try { testClosed ( ) ; if ( this . modelKeyMap . containsKey ( key ) ) { throw new IllegalArgumentException ( String . format ( \"A provider for '%s' is already registered\" , key ) ) ; } try { storageProvider . start ( this . context ) ; } catch ( final Exception e ) { throw new ModelInitializationException ( \"Failed to start model provider: \" + key , e ) ; } final long id = this . counter ++ ; final Entry entry = new Entry ( id , lockPriority , key , storageProvider ) ; this . modelIdMap . put ( id , entry ) ; this . modelKeyMap . put ( key , entry ) ; return new StorageRegistration ( ) { @ Override public void unregister ( ) { unregisterModel ( id ) ; } } ; } finally { this . modelLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stream directly from the storage [CODESPLIT] public boolean stream ( final MetaKey key , final IOConsumer < InputStream > consumer ) throws IOException { return streamFrom ( this . dataPath , key , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Monitor the job only produces an HTML fragment of the current job state [CODESPLIT] @ RequestMapping ( \"/{id}/monitor\" ) public ModelAndView monitor ( @ PathVariable ( \"id\" ) final String id ) { final JobHandle job = this . manager . getJob ( id ) ; if ( job != null ) { logger . debug ( \"Job: {} - {}\" , job . getId ( ) , job . getState ( ) ) ; } else { logger . debug ( \"No job: {}\" , id ) ; } final Map < String , Object > model = new HashMap <> ( 1 ) ; model . put ( \"job\" , job ) ; return new ModelAndView ( \"monitor\" , model ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clean up the path so that is looks like . / usr / local / file [CODESPLIT] private String cleanupPath ( String fileName ) { if ( fileName == null ) { return null ; } fileName = fileName . replace ( \"\\\\\" , \"/\" ) ; // just in case we get windows paths fileName = fileName . replace ( \"/+\" , \"/\" ) ; if ( fileName . startsWith ( \"./\" ) ) { return fileName ; } if ( fileName . startsWith ( \"/\" ) ) { return \".\" + fileName ; } return \"./\" + fileName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate the request is authenticated against the deploy keys <p > If the request could not be authenticated a basic authentication request is sent back and the { @link HttpServletResponse } will be committed . < / p > [CODESPLIT] protected boolean authenticate ( final By by , final HttpServletRequest request , final HttpServletResponse response ) throws IOException { if ( isAuthenticated ( by , request ) ) { return true ; } BasicAuthentication . request ( response , \"channel\" , \"Please authenticate\" ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simply test if the request is authenticated against the channels deploy keys [CODESPLIT] protected boolean isAuthenticated ( final By by , final HttpServletRequest request ) { final String [ ] authToks = parseAuthorization ( request ) ; if ( authToks == null ) { return false ; } // we don't enforce the \"deploy\" user name anymore final String deployKey = authToks [ 1 ] ; logger . debug ( \"Deploy key: '{}'\" , deployKey ) ; final ChannelService service = getService ( request ) ; if ( service == null ) { logger . info ( \"Called 'isAuthenticated' without service\" ) ; return false ; } return service . getChannelDeployKeyStrings ( by ) . orElse ( Collections . emptySet ( ) ) . contains ( deployKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a single character . This method will block until a character is available an I / O error occurs or the end of the stream is reached . [CODESPLIT] public int read ( ) throws IOException { int b0 = fInputStream . read ( ) & 0xff ; if ( b0 == 0xff ) return - 1 ; int b1 = fInputStream . read ( ) & 0xff ; if ( b1 == 0xff ) return - 1 ; if ( fEncoding >= 4 ) { int b2 = fInputStream . read ( ) & 0xff ; if ( b2 == 0xff ) return - 1 ; int b3 = fInputStream . read ( ) & 0xff ; if ( b3 == 0xff ) return - 1 ; if ( log . isLoggable ( Level . FINE ) ) log . fine ( \"b0 is \" + ( b0 & 0xff ) + \" b1 \" + ( b1 & 0xff ) + \" b2 \" + ( b2 & 0xff ) + \" b3 \" + ( b3 & 0xff ) ) ; if ( fEncoding == UCS4BE ) return ( b0 << 24 ) + ( b1 << 16 ) + ( b2 << 8 ) + b3 ; else return ( b3 << 24 ) + ( b2 << 16 ) + ( b1 << 8 ) + b0 ; } else { // UCS-2 if ( fEncoding == UCS2BE ) return ( b0 << 8 ) + b1 ; else return ( b1 << 8 ) + b0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete the document but don t close the underlying writer [CODESPLIT] public void finish ( ) throws IOException { if ( ! this . finished ) { this . finished = true ; writeEnd ( ) ; } try { this . out . close ( ) ; } catch ( final XMLStreamException e ) { throw new IOException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an appropriate Gson parser to processing ChannelData instances [CODESPLIT] public static Gson makeGson ( final boolean pretty ) { final GsonBuilder gb = new GsonBuilder ( ) ; if ( pretty ) { gb . setPrettyPrinting ( ) ; } gb . registerTypeAdapter ( Node . class , new NodeAdapter ( ) ) ; gb . registerTypeAdapter ( byte [ ] . class , new ByteArrayAdapter ( ) ) ; return gb . create ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an integer [ 0 63 ] matching the highest two bits of an integer . This is like bit scan reverse ( BSR ) on x86 except that this also cares about the second highest bit . [CODESPLIT] public static int getDistSlot ( int dist ) { if ( dist <= DIST_MODEL_START && dist >= 0 ) return dist ; int n = dist ; int i = 31 ; if ( ( n & 0xFFFF0000 ) == 0 ) { n <<= 16 ; i = 15 ; } if ( ( n & 0xFF000000 ) == 0 ) { n <<= 8 ; i -= 8 ; } if ( ( n & 0xF0000000 ) == 0 ) { n <<= 4 ; i -= 4 ; } if ( ( n & 0xC0000000 ) == 0 ) { n <<= 2 ; i -= 2 ; } if ( ( n & 0x80000000 ) == 0 ) -- i ; return ( i << 1 ) + ( ( dist >>> ( i - 1 ) ) & 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compresses for LZMA2 . [CODESPLIT] public boolean encodeForLZMA2 ( ) { // LZMA2 uses RangeEncoderToBuffer so IOExceptions aren't possible. try { if ( ! lz . isStarted ( ) && ! encodeInit ( ) ) return false ; while ( uncompressedSize <= LZMA2_UNCOMPRESSED_LIMIT && rc . getPendingSize ( ) <= LZMA2_COMPRESSED_LIMIT ) if ( ! encodeSymbol ( ) ) return false ; } catch ( IOException e ) { throw new Error ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a string from meta data <p > If the provided metadata set is <code > null< / code > then the result will also be <code > null< / code > . < / p > [CODESPLIT] public static String getString ( final Map < MetaKey , String > metadata , final String ns , final String key ) { return getString ( metadata , ns , key , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a string from meta data <p > If the provided metadata set is <code > null< / code > then the result will also be <code > null< / code > . < / p > [CODESPLIT] public static String getString ( final Map < MetaKey , String > metadata , final String ns , final String key , final String defaultValue ) { if ( metadata == null ) { return defaultValue ; } final String result = metadata . get ( new MetaKey ( ns , key ) ) ; if ( result == null ) { return defaultValue ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an unmodifiable map of provided and extracted meta data [CODESPLIT] public static Map < MetaKey , String > union ( final Map < MetaKey , String > providedMetaData , final Map < MetaKey , String > extractedMetaData ) { final int size1 = providedMetaData != null ? providedMetaData . size ( ) : 0 ; final int size2 = extractedMetaData != null ? extractedMetaData . size ( ) : 0 ; if ( size1 + size2 == 0 ) { return Collections . emptyMap ( ) ; } final Map < MetaKey , String > result = new HashMap <> ( size1 + size2 ) ; if ( extractedMetaData != null ) { result . putAll ( extractedMetaData ) ; } // provided will override if ( providedMetaData != null ) { result . putAll ( providedMetaData ) ; } return Collections . unmodifiableMap ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write out the announce file <br > Writing a file like this seems a little bit strange from a Java perspective . However there seems to be no other way to create a file with a provided set of initial file attributes other than { @link Files#newByteChannel ( java . nio . file . Path Set FileAttribute ... ) } . All other methods don t access file attributes . [CODESPLIT] protected void writeAnnounceFile ( final String adminToken ) { final Path path = ANNOUNCE_FILE . toPath ( ) ; /*\n         * Try to delete the file first. We don't care about the result\n         * since the next operation will try to create a new file anyway.\n         *\n         * However by deleting it first, we try to ensure that the initial\n         * file permissions are set. If the file exists these would not be\n         * changed.\n         */ ANNOUNCE_FILE . delete ( ) ; // posix final FileAttribute < ? > [ ] attrs ; if ( ANNOUNCE_FILE_POSIX ) { final Set < PosixFilePermission > perms = EnumSet . of ( PosixFilePermission . OWNER_READ , PosixFilePermission . OWNER_WRITE ) ; attrs = new FileAttribute < ? > [ ] { PosixFilePermissions . asFileAttribute ( perms ) } ; } else { attrs = new FileAttribute < ? > [ 0 ] ; } final Set < ? extends OpenOption > options = EnumSet . of ( StandardOpenOption . CREATE , StandardOpenOption . WRITE , StandardOpenOption . TRUNCATE_EXISTING ) ; try ( SeekableByteChannel sbc = Files . newByteChannel ( path , options , attrs ) ) { final StringWriter sw = new StringWriter ( ) ; final PrintWriter writer = new PrintWriter ( sw ) ; writer . format ( \"user=%s%n\" , NAME ) ; writer . format ( \"password=%s%n\" , adminToken ) ; writer . close ( ) ; final ByteBuffer data = ByteBuffer . wrap ( sw . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ; while ( data . hasRemaining ( ) ) { sbc . write ( data ) ; } } catch ( final UnsupportedOperationException e ) { System . err . format ( \"WARNING: Failed to write out announce file with secured posix permissions. If you are on a non-posix platform (e.g. Windows), you might need to set the system property '%s' to 'true'%n\" , PROP_NOT_POSIX ) ; } catch ( final IOException e ) { System . err . println ( \"WARNING: Unable to write announce file: \" + ExceptionHelper . getMessage ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of the javax . servlet . error . exception request attribute value if present otherwise the value of the javax . servlet . jsp . jspException request attribute value . [CODESPLIT] public static Throwable getThrowable ( ServletRequest request ) { Throwable error = ( Throwable ) request . getAttribute ( SERVLET_EXCEPTION ) ; if ( error == null ) { error = ( Throwable ) request . getAttribute ( JSP_EXCEPTION ) ; if ( error != null ) { /*\n\t\t * The only place that sets JSP_EXCEPTION is\n\t\t * PageContextImpl.handlePageException(). It really should set\n\t\t * SERVLET_EXCEPTION, but that would interfere with the \n\t\t * ErrorReportValve. Therefore, if JSP_EXCEPTION is set, we\n\t\t * need to set SERVLET_EXCEPTION.\n\t\t */ request . setAttribute ( SERVLET_EXCEPTION , error ) ; } } return error ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "__begin introspecthelperMethod [CODESPLIT] public static void introspecthelper ( Object bean , String prop , String value , ServletRequest request , String param , boolean ignoreMethodNF ) throws JasperException { if ( Constants . IS_SECURITY_ENABLED ) { try { PrivilegedIntrospectHelper dp = new PrivilegedIntrospectHelper ( bean , prop , value , request , param , ignoreMethodNF ) ; AccessController . doPrivileged ( dp ) ; } catch ( PrivilegedActionException pe ) { Exception e = pe . getException ( ) ; throw ( JasperException ) e ; } } else { internalIntrospecthelper ( bean , prop , value , request , param , ignoreMethodNF ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a typed array . This is a special case where params are passed through the request and the property is indexed . [CODESPLIT] public static void createTypedArray ( String propertyName , Object bean , Method method , String [ ] values , Class t , Class propertyEditorClass ) throws JasperException { try { if ( propertyEditorClass != null ) { Object [ ] tmpval = new Integer [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) { tmpval [ i ] = getValueFromBeanInfoPropertyEditor ( t , propertyName , values [ i ] , propertyEditorClass ) ; } method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Integer . class ) ) { Integer [ ] tmpval = new Integer [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Integer . valueOf ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Byte . class ) ) { Byte [ ] tmpval = new Byte [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Byte . valueOf ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Boolean . class ) ) { Boolean [ ] tmpval = new Boolean [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Boolean . valueOf ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Short . class ) ) { Short [ ] tmpval = new Short [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Short . valueOf ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Long . class ) ) { Long [ ] tmpval = new Long [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Long . valueOf ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Double . class ) ) { Double [ ] tmpval = new Double [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Double . valueOf ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Float . class ) ) { Float [ ] tmpval = new Float [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Float . valueOf ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( Character . class ) ) { Character [ ] tmpval = new Character [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Character . valueOf ( values [ i ] . charAt ( 0 ) ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( int . class ) ) { int [ ] tmpval = new int [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Integer . parseInt ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( byte . class ) ) { byte [ ] tmpval = new byte [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Byte . parseByte ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( boolean . class ) ) { boolean [ ] tmpval = new boolean [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = ( Boolean . valueOf ( values [ i ] ) ) . booleanValue ( ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( short . class ) ) { short [ ] tmpval = new short [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Short . parseShort ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( long . class ) ) { long [ ] tmpval = new long [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Long . parseLong ( values [ i ] ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( double . class ) ) { double [ ] tmpval = new double [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Double . valueOf ( values [ i ] ) . doubleValue ( ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( float . class ) ) { float [ ] tmpval = new float [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = Float . valueOf ( values [ i ] ) . floatValue ( ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else if ( t . equals ( char . class ) ) { char [ ] tmpval = new char [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) tmpval [ i ] = values [ i ] . charAt ( 0 ) ; method . invoke ( bean , new Object [ ] { tmpval } ) ; } else { Object [ ] tmpval = new Integer [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) { tmpval [ i ] = getValueFromPropertyEditorManager ( t , propertyName , values [ i ] ) ; } method . invoke ( bean , new Object [ ] { tmpval } ) ; } } catch ( Exception ex ) { throw new JasperException ( \"error in invoking method\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "__begin lookupReadMethodMethod [CODESPLIT] public static Object handleGetProperty ( Object o , String prop ) throws JasperException { if ( o == null ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.beans.nullbean\" ) ) ; } Object value = null ; try { Method method = getReadMethod ( o . getClass ( ) , prop ) ; value = method . invoke ( o , ( Object [ ] ) null ) ; } catch ( Exception ex ) { throw new JasperException ( ex ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use proprietaryEvaluate public static void handleSetPropertyExpression ( Object bean String prop String expression PageContext pageContext VariableResolver variableResolver FunctionMapper functionMapper ) throws JasperException { try { Method method = getWriteMethod ( bean . getClass () prop ) ; method . invoke ( bean new Object [] { pageContext . getExpressionEvaluator () . evaluate ( expression method . getParameterTypes () [ 0 ] variableResolver functionMapper null ) } ) ; } catch ( Exception ex ) { throw new JasperException ( ex ) ; } } [CODESPLIT] public static void handleSetPropertyExpression ( Object bean , String prop , String expression , PageContext pageContext , ProtectedFunctionMapper functionMapper ) throws JasperException { try { Method method = getWriteMethod ( bean . getClass ( ) , prop ) ; method . invoke ( bean , new Object [ ] { PageContextImpl . evaluateExpression ( expression , method . getParameterTypes ( ) [ 0 ] , pageContext , functionMapper ) } ) ; } catch ( Exception ex ) { throw new JasperException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a possibly relative resource path into a context - relative resource path that starts with a / . [CODESPLIT] public static String getContextRelativePath ( ServletRequest request , String relativePath ) { if ( relativePath . startsWith ( \"/\" ) ) return ( relativePath ) ; if ( ! ( request instanceof HttpServletRequest ) ) return ( relativePath ) ; HttpServletRequest hrequest = ( HttpServletRequest ) request ; String uri = ( String ) request . getAttribute ( \"javax.servlet.include.servlet_path\" ) ; if ( uri != null ) { String pathInfo = ( String ) request . getAttribute ( \"javax.servlet.include.path_info\" ) ; if ( pathInfo == null ) { if ( uri . lastIndexOf ( ' ' ) >= 0 ) { uri = uri . substring ( 0 , uri . lastIndexOf ( ' ' ) ) ; } } } else { // STARTJR: fix improper handling of jsp:include uri = hrequest . getServletPath ( ) ; String pathInfo = hrequest . getPathInfo ( ) ; if ( pathInfo != null ) { uri = uri + pathInfo ; } if ( uri . lastIndexOf ( ' ' ) >= 0 ) { uri = uri . substring ( 0 , uri . lastIndexOf ( ' ' ) ) ; } // ENDJR } return uri + ' ' + relativePath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a RequestDispatcher . include () operation with optional flushing of the response beforehand . [CODESPLIT] public static void include ( ServletRequest request , ServletResponse response , String relativePath , JspWriter out , boolean flush ) throws IOException , ServletException { if ( flush && ! ( out instanceof BodyContent ) ) out . flush ( ) ; // FIXME - It is tempting to use request.getRequestDispatcher() to // resolve a relative path directly, but Catalina currently does not // take into account whether the caller is inside a RequestDispatcher // include or not.  Whether Catalina *should* take that into account // is a spec issue currently under review.  In the mean time, // replicate Jasper's previous behavior String resourcePath = getContextRelativePath ( request , relativePath ) ; RequestDispatcher rd = request . getRequestDispatcher ( resourcePath ) ; rd . include ( request , new ServletResponseWrapperInclude ( response , out ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given tag handler to this tag handler pool unless this tag handler pool has already reached its capacity in which case the tag handler s release () method is called . [CODESPLIT] public void reuse ( Tag handler ) { PerThreadData ptd = perThread . get ( ) ; if ( ptd . current < ( ptd . handlers . length - 1 ) ) { ptd . handlers [ ++ ptd . current ] = handler ; } else { handler . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the release () method of all tag handlers in this tag handler pool . [CODESPLIT] public void release ( ) { Enumeration < PerThreadData > enumeration = perThreadDataVector . elements ( ) ; while ( enumeration . hasMoreElements ( ) ) { PerThreadData ptd = enumeration . nextElement ( ) ; if ( ptd . handlers != null ) { for ( int i = ptd . current ; i >= 0 ; i -- ) { if ( ptd . handlers [ i ] != null ) { ptd . handlers [ i ] . release ( ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the uploaded artifact is actually a checksum file [CODESPLIT] private String isCheckSum ( final Coordinates c ) { final String cext = c . getExtension ( ) ; if ( cext == null ) { return null ; } for ( final String ext : this . options . getChecksumExtensions ( ) ) { if ( cext . endsWith ( \".\" + ext ) ) { return ext ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "private final static Logger logger = LoggerFactory . getLogger ( VirtualizerImpl . class ) ; [CODESPLIT] @ Override public void virtualize ( final Context context ) { try { processVirtualize ( context ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finishes the stream without closing the underlying OutputStream . [CODESPLIT] public void finish ( ) throws IOException { if ( ! finished ) { if ( exception != null ) throw exception ; try { if ( expectedUncompressedSize != - 1 && expectedUncompressedSize != currentUncompressedSize ) throw new XZIOException ( \"Expected uncompressed size (\" + expectedUncompressedSize + \") doesn't equal \" + \"the number of bytes written to the stream (\" + currentUncompressedSize + \")\" ) ; lz . setFinishing ( ) ; lzma . encodeForLZMA1 ( ) ; if ( useEndMarker ) lzma . encodeLZMA1EndMarker ( ) ; rc . finish ( ) ; } catch ( IOException e ) { exception = e ; throw e ; } finished = true ; lzma . putArraysToCache ( arrayCache ) ; lzma = null ; lz = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the exception associated with this page context if any . [CODESPLIT] public Exception getException ( ) { Throwable t = JspRuntimeLibrary . getThrowable ( request ) ; // Only wrap if needed if ( ( t != null ) && ( ! ( t instanceof Exception ) ) ) { t = new JspException ( t ) ; } return ( Exception ) t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates an EL expression [CODESPLIT] public static Object evaluateExpression ( final String expression , final Class expectedType , final PageContext pageContext , final ProtectedFunctionMapper functionMap ) throws ELException { Object retValue ; if ( SecurityUtil . isPackageProtectionEnabled ( ) ) { try { retValue = AccessController . doPrivileged ( new PrivilegedExceptionAction < Object > ( ) { public Object run ( ) throws Exception { ELContextImpl elContext = ( ELContextImpl ) pageContext . getELContext ( ) ; elContext . setFunctionMapper ( functionMap ) ; ExpressionFactory expFactory = getExpressionFactory ( pageContext ) ; ValueExpression expr = expFactory . createValueExpression ( elContext , expression , expectedType ) ; return expr . getValue ( elContext ) ; } } ) ; } catch ( PrivilegedActionException ex ) { Exception realEx = ex . getException ( ) ; if ( realEx instanceof ELException ) { throw ( ELException ) realEx ; } else { throw new ELException ( realEx ) ; } } } else { ELContextImpl elContext = ( ELContextImpl ) pageContext . getELContext ( ) ; elContext . setFunctionMapper ( functionMap ) ; ExpressionFactory expFactory = getExpressionFactory ( pageContext ) ; ValueExpression expr = expFactory . createValueExpression ( elContext , expression , expectedType ) ; retValue = expr . getValue ( elContext ) ; } return retValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the prefix by guessing the port from the OSGi settings [CODESPLIT] protected String makePrefixFromOsgiProperties ( ) { final String port = System . getProperty ( \"org.osgi.service.http.port\" ) ; if ( port == null ) { return null ; } final StringBuilder sb = new StringBuilder ( ) ; sb . append ( \"http://\" ) . append ( discoverHostname ( ) ) ; if ( ! \"80\" . equals ( port ) ) { sb . append ( ' ' ) . append ( port ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if this file is an XML file [CODESPLIT] public static boolean isXml ( final Path path ) throws IOException { final XmlToolsFactory xml = Activator . getXmlToolsFactory ( ) ; final XMLInputFactory xin = xml . newXMLInputFactory ( ) ; try ( InputStream stream = new BufferedInputStream ( Files . newInputStream ( path ) ) ) { try { final XMLStreamReader reader = xin . createXMLStreamReader ( stream ) ; reader . next ( ) ; return true ; } catch ( final XMLStreamException e ) { return false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the tag file and collects information on the directives included in it . The method is used to obtain the info on the tag file when the handler that it represents is referenced . The tag file is not compiled here . [CODESPLIT] public static TagInfo parseTagFileDirectives ( ParserController pc , String name , String path , TagLibraryInfo tagLibInfo ) throws JasperException { ErrorDispatcher err = pc . getCompiler ( ) . getErrorDispatcher ( ) ; Node . Nodes page = null ; try { page = pc . parseTagFileDirectives ( path ) ; } catch ( FileNotFoundException e ) { err . jspError ( \"jsp.error.file.not.found\" , path ) ; } catch ( IOException e ) { err . jspError ( \"jsp.error.file.not.found\" , path ) ; } TagFileDirectiveVisitor tagFileVisitor = new TagFileDirectiveVisitor ( pc . getCompiler ( ) , tagLibInfo , name , path ) ; page . visit ( tagFileVisitor ) ; tagFileVisitor . postCheck ( ) ; return tagFileVisitor . getTagInfo ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles and loads a tagfile . [CODESPLIT] private Class loadTagFile ( Compiler compiler , String tagFilePath , TagInfo tagInfo , PageInfo parentPageInfo ) throws JasperException { JspCompilationContext ctxt = compiler . getCompilationContext ( ) ; JspRuntimeContext rctxt = ctxt . getRuntimeContext ( ) ; synchronized ( rctxt ) { JspServletWrapper wrapper = ( JspServletWrapper ) rctxt . getWrapper ( tagFilePath ) ; if ( wrapper == null ) { wrapper = new JspServletWrapper ( ctxt . getServletContext ( ) , ctxt . getOptions ( ) , tagFilePath , tagInfo , ctxt . getRuntimeContext ( ) , ( URL ) ctxt . getTagFileJarUrls ( ) . get ( tagFilePath ) ) ; rctxt . addWrapper ( tagFilePath , wrapper ) ; // Use same classloader and classpath for compiling tag files wrapper . getJspEngineContext ( ) . setClassLoader ( ( URLClassLoader ) ctxt . getClassLoader ( ) ) ; wrapper . getJspEngineContext ( ) . setClassPath ( ctxt . getClassPath ( ) ) ; } else { // Make sure that JspCompilationContext gets the latest TagInfo // for the tag file.  TagInfo instance was created the last // time the tag file was scanned for directives, and the tag // file may have been modified since then. wrapper . getJspEngineContext ( ) . setTagInfo ( tagInfo ) ; } Class tagClazz ; int tripCount = wrapper . incTripCount ( ) ; try { if ( tripCount > 0 ) { // When tripCount is greater than zero, a circular // dependency exists.  The circularily dependant tag // file is compiled in prototype mode, to avoid infinite // recursion. JspServletWrapper tempWrapper = new JspServletWrapper ( ctxt . getServletContext ( ) , ctxt . getOptions ( ) , tagFilePath , tagInfo , ctxt . getRuntimeContext ( ) , ( URL ) ctxt . getTagFileJarUrls ( ) . get ( tagFilePath ) ) ; tagClazz = tempWrapper . loadTagFilePrototype ( ) ; tempVector . add ( tempWrapper . getJspEngineContext ( ) . getCompiler ( ) ) ; } else { tagClazz = wrapper . loadTagFile ( ) ; } } finally { wrapper . decTripCount ( ) ; } // Add the dependants for this tag file to its parent's // dependant list.  The only reliable dependency information // can only be obtained from the tag instance. try { Object tagIns = tagClazz . newInstance ( ) ; if ( tagIns instanceof JspSourceDependent ) { for ( String dependant : ( ( JspSourceDependent ) tagIns ) . getDependants ( ) ) { parentPageInfo . addDependant ( dependant ) ; } } } catch ( Exception e ) { // ignore errors } return tagClazz ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements a phase of the translation that compiles ( if necessary ) the tag files used in a JSP files . The directives in the tag files are assumed to have been proccessed and encapsulated as TagFileInfo in the CustomTag nodes . [CODESPLIT] public void loadTagFiles ( Compiler compiler , Node . Nodes page ) throws JasperException { tempVector = new ArrayList < Compiler > ( ) ; page . visit ( new TagFileLoaderVisitor ( compiler ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removed the java and class files for the tag prototype generated from the current compilation . [CODESPLIT] public void removeProtoTypeFiles ( String classFileName ) { Iterator < Compiler > iter = tempVector . iterator ( ) ; while ( iter . hasNext ( ) ) { Compiler c = iter . next ( ) ; if ( classFileName == null ) { c . removeGeneratedClassFiles ( ) ; } else if ( classFileName . equals ( c . getCompilationContext ( ) . getClassFileName ( ) ) ) { c . removeGeneratedClassFiles ( ) ; tempVector . remove ( c ) ; return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "END GlassFish 750 [CODESPLIT] public static void main ( String arg [ ] ) { if ( arg . length == 0 ) { System . out . println ( Localizer . getMessage ( \"jspc.usage\" ) ) ; } else { JspC jspc = new JspC ( ) ; try { jspc . setArgs ( arg ) ; if ( jspc . helpNeeded ) { System . out . println ( Localizer . getMessage ( \"jspc.usage\" ) ) ; } else { jspc . execute ( ) ; } } catch ( JasperException je ) { System . err . println ( je ) ; //System.err.println(je.getMessage()); if ( jspc . getDieLevel ( ) != NO_DIE_LEVEL ) { System . exit ( jspc . getDieLevel ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Base dir for the webapp . Used to generate class names and resolve includes [CODESPLIT] public void setUriroot ( String s ) { uriRoot = s ; if ( s != null ) { try { uriRoot = new File ( s ) . getCanonicalPath ( ) ; } catch ( Exception ex ) { uriRoot = s ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses comma - separated list of JSP files to be processed . [CODESPLIT] public void setJspFiles ( String jspFiles ) { StringTokenizer tok = new StringTokenizer ( jspFiles , \" ,\" ) ; while ( tok . hasMoreTokens ( ) ) { pages . add ( tok . nextToken ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the list of JSP compilation errors caught during the most recent invocation of this instance s <code > execute< / code > method when failOnError has been set to FALSE . [CODESPLIT] public List < JasperException > getJSPCompilationErrors ( ) { ArrayList < JasperException > ret = null ; Collection < JasperException > c = jspErrors . values ( ) ; if ( c != null ) { ret = new ArrayList < JasperException > ( ) ; Iterator < JasperException > it = c . iterator ( ) ; while ( it . hasNext ( ) ) { ret . add ( it . next ( ) ) ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include the generated web . xml inside the webapp s web . xml . [CODESPLIT] protected void mergeIntoWebXml ( ) throws IOException { File webappBase = new File ( uriRoot ) ; File webXml = new File ( webappBase , \"WEB-INF/web.xml\" ) ; File webXml2 = new File ( webappBase , \"WEB-INF/web2.xml\" ) ; String insertStartMarker = Localizer . getMessage ( \"jspc.webinc.insertStart\" ) ; String insertEndMarker = Localizer . getMessage ( \"jspc.webinc.insertEnd\" ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( webXml ) , \"UTF-8\" ) ) ; BufferedReader fragmentReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( webxmlFile ) , \"UTF-8\" ) ) ; PrintWriter writer = new PrintWriter ( new OutputStreamWriter ( new FileOutputStream ( webXml2 ) , \"UTF-8\" ) ) ; // Insert the <servlet> and <servlet-mapping> declarations int pos = - 1 ; String line = null ; while ( true ) { line = reader . readLine ( ) ; if ( line == null ) { break ; } // Skip anything previously generated by JSPC if ( line . indexOf ( insertStartMarker ) >= 0 ) { while ( true ) { line = reader . readLine ( ) ; if ( line == null ) { return ; } if ( line . indexOf ( insertEndMarker ) >= 0 ) { line = reader . readLine ( ) ; if ( line == null ) { return ; } break ; } } } for ( int i = 0 ; i < insertBefore . length ; i ++ ) { pos = line . indexOf ( insertBefore [ i ] ) ; if ( pos >= 0 ) break ; } if ( pos >= 0 ) { writer . println ( line . substring ( 0 , pos ) ) ; break ; } else { writer . println ( line ) ; } } writer . println ( insertStartMarker ) ; while ( true ) { String line2 = fragmentReader . readLine ( ) ; if ( line2 == null ) { writer . println ( ) ; break ; } writer . println ( line2 ) ; } writer . println ( insertEndMarker ) ; writer . println ( ) ; for ( int i = 0 ; i < pos ; i ++ ) { writer . print ( \" \" ) ; } if ( line != null ) { writer . println ( line . substring ( pos ) ) ; } while ( true ) { line = reader . readLine ( ) ; if ( line == null ) { break ; } writer . println ( line ) ; } writer . close ( ) ; reader . close ( ) ; fragmentReader . close ( ) ; FileInputStream fis = new FileInputStream ( webXml2 ) ; FileOutputStream fos = new FileOutputStream ( webXml ) ; byte buf [ ] = new byte [ 512 ] ; try { while ( true ) { int n = fis . read ( buf ) ; if ( n < 0 ) { break ; } fos . write ( buf , 0 , n ) ; } } finally { if ( fis != null ) { fis . close ( ) ; } if ( fos != null ) { fos . close ( ) ; } } webXml2 . delete ( ) ; ( new File ( webxmlFile ) ) . delete ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locate all jsp files in the webapp . Used if no explicit jsps are specified . [CODESPLIT] public void scanFiles ( File base ) throws JasperException { Stack < String > dirs = new Stack < String > ( ) ; dirs . push ( base . toString ( ) ) ; if ( extensions == null ) { extensions = new ArrayList < String > ( ) ; extensions . add ( \"jsp\" ) ; extensions . add ( \"jspx\" ) ; } while ( ! dirs . isEmpty ( ) ) { String s = dirs . pop ( ) ; File f = new File ( s ) ; if ( f . exists ( ) && f . isDirectory ( ) ) { String [ ] files = f . list ( ) ; String ext ; for ( int i = 0 ; ( files != null ) && i < files . length ; i ++ ) { File f2 = new File ( s , files [ i ] ) ; if ( f2 . isDirectory ( ) ) { dirs . push ( f2 . getPath ( ) ) ; } else { String path = f2 . getPath ( ) ; String uri = path . substring ( uriRoot . length ( ) ) ; ext = files [ i ] . substring ( files [ i ] . lastIndexOf ( ' ' ) + 1 ) ; if ( extensions . contains ( ext ) || jspConfig . isJspPage ( uri ) ) { pages . add ( path ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "==================== Private utility methods ==================== [CODESPLIT] private String nextArg ( ) { if ( ( argPos >= args . length ) || ( fullstop = SWITCH_FULL_STOP . equals ( args [ argPos ] ) ) ) { return null ; } else { return args [ argPos ++ ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the classloader as / if needed for the given compilation context . [CODESPLIT] private void initClassLoader ( JspCompilationContext clctxt ) throws IOException { classPath = getClassPath ( ) ; ClassLoader jspcLoader = getClass ( ) . getClassLoader ( ) ; // Turn the classPath into URLs ArrayList < URL > urls = new ArrayList < URL > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( classPath , File . pathSeparator ) ; while ( tokenizer . hasMoreTokens ( ) ) { String path = tokenizer . nextToken ( ) ; try { File libFile = new File ( path ) ; urls . add ( libFile . toURL ( ) ) ; } catch ( IOException ioe ) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException ( ioe . toString ( ) ) ; } } File webappBase = new File ( uriRoot ) ; if ( webappBase . exists ( ) ) { File classes = new File ( webappBase , \"/WEB-INF/classes\" ) ; try { if ( classes . exists ( ) ) { classPath = classPath + File . pathSeparator + classes . getCanonicalPath ( ) ; urls . add ( classes . getCanonicalFile ( ) . toURL ( ) ) ; } } catch ( IOException ioe ) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException ( ioe . toString ( ) ) ; } File lib = new File ( webappBase , \"/WEB-INF/lib\" ) ; if ( lib . exists ( ) && lib . isDirectory ( ) ) { String [ ] libs = lib . list ( ) ; for ( int i = 0 ; i < libs . length ; i ++ ) { if ( libs [ i ] . length ( ) < 5 ) continue ; String ext = libs [ i ] . substring ( libs [ i ] . length ( ) - 4 ) ; if ( ! \".jar\" . equalsIgnoreCase ( ext ) ) { if ( \".tld\" . equalsIgnoreCase ( ext ) ) { log . warning ( \"TLD files should not be placed in /WEB-INF/lib\" ) ; } continue ; } try { File libFile = new File ( lib , libs [ i ] ) ; classPath = classPath + File . pathSeparator + libFile . getCanonicalPath ( ) ; urls . add ( libFile . getCanonicalFile ( ) . toURL ( ) ) ; } catch ( IOException ioe ) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException ( ioe . toString ( ) ) ; } } } } // What is this ?? urls . add ( new File ( clctxt . getRealPath ( \"/\" ) ) . getCanonicalFile ( ) . toURL ( ) ) ; URL urlsA [ ] = new URL [ urls . size ( ) ] ; urls . toArray ( urlsA ) ; /* SJSAS 6327357\n        loader = new URLClassLoader(urlsA, this.getClass().getClassLoader());\n         */ // START SJSAS 6327357 ClassLoader sysClassLoader = initSystemClassLoader ( ) ; if ( sysClassLoader != null ) { loader = new URLClassLoader ( urlsA , sysClassLoader ) ; } else { loader = new URLClassLoader ( urlsA , this . getClass ( ) . getClassLoader ( ) ) ; } // END SJSAS 6327357 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the WEB - INF dir by looking up in the directory tree . This is used if no explicit docbase is set but only files . XXX Maybe we should require the docbase . [CODESPLIT] private void locateUriRoot ( File f ) { String tUriBase = uriBase ; if ( tUriBase == null ) { tUriBase = \"/\" ; } try { if ( f . exists ( ) ) { f = new File ( f . getCanonicalPath ( ) ) ; while ( f != null ) { File g = new File ( f , \"WEB-INF\" ) ; if ( g . exists ( ) && g . isDirectory ( ) ) { uriRoot = f . getCanonicalPath ( ) ; uriBase = tUriBase ; if ( log . isLoggable ( Level . INFO ) ) { log . info ( Localizer . getMessage ( \"jspc.implicit.uriRoot\" , uriRoot ) ) ; } break ; } if ( f . exists ( ) && f . isDirectory ( ) ) { tUriBase = \"/\" + f . getName ( ) + \"/\" + tUriBase ; } String fParent = f . getParent ( ) ; if ( fParent == null ) { break ; } else { f = new File ( fParent ) ; } // If there is no acceptible candidate, uriRoot will // remain null to indicate to the CompilerContext to // use the current working/user dir. } if ( uriRoot != null ) { File froot = new File ( uriRoot ) ; uriRoot = froot . getCanonicalPath ( ) ; } } } catch ( IOException ioe ) { // since this is an optional default and a null value // for uriRoot has a non-error meaning, we can just // pass straight through } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "START SJSAS 6327357 [CODESPLIT] private ClassLoader initSystemClassLoader ( ) throws IOException { String sysClassPath = getSystemClassPath ( ) ; if ( sysClassPath == null ) { return null ; } ArrayList < URL > urls = new ArrayList < URL > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( sysClassPath , File . pathSeparator ) ; while ( tokenizer . hasMoreTokens ( ) ) { urls . add ( new File ( tokenizer . nextToken ( ) ) . toURL ( ) ) ; } if ( urls . size ( ) == 0 ) { return null ; } URL urlsArray [ ] = new URL [ urls . size ( ) ] ; urls . toArray ( urlsArray ) ; return new URLClassLoader ( urlsArray , this . getClass ( ) . getClassLoader ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Purges all compilation errors related to JSP fragments . [CODESPLIT] private void purgeJspFragmentErrors ( ) { Iterator < String > it = dependents . iterator ( ) ; if ( it != null ) { while ( it . hasNext ( ) ) { jspErrors . remove ( it . next ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves to the next byte checks that there is enough available space and possibly normalizes the hash tables and the hash chain . [CODESPLIT] private int movePos ( ) { int avail = movePos ( 4 , 4 ) ; if ( avail != 0 ) { if ( ++ lzPos == Integer . MAX_VALUE ) { int normalizationOffset = Integer . MAX_VALUE - cyclicSize ; hash . normalize ( normalizationOffset ) ; normalize ( chain , cyclicSize , normalizationOffset ) ; lzPos -= normalizationOffset ; } if ( ++ cyclicPos == cyclicSize ) cyclicPos = 0 ; } return avail ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------- [CODESPLIT] public Expression parseExpression ( String expression , Class expectedType , FunctionMapper fMapper ) throws ELException { ExpressionFactory fac = ExpressionFactory . newInstance ( ) ; javax . el . ValueExpression expr ; ELContextImpl elContext = new ELContextImpl ( null ) ; javax . el . FunctionMapper fm = new FunctionMapperWrapper ( fMapper ) ; elContext . setFunctionMapper ( fm ) ; try { expr = fac . createValueExpression ( elContext , expression , expectedType ) ; } catch ( javax . el . ELException ex ) { throw new ELException ( ex ) ; } return new ExpressionImpl ( expr , pageContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the delta distance in bytes . The new distance must be in the range [ DISTANCE_MIN DISTANCE_MAX ] . [CODESPLIT] public void setDistance ( int distance ) throws UnsupportedOptionsException { if ( distance < DISTANCE_MIN || distance > DISTANCE_MAX ) throw new UnsupportedOptionsException ( \"Delta distance must be in the range [\" + DISTANCE_MIN + \", \" + DISTANCE_MAX + \"]: \" + distance ) ; this . distance = distance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "search the stream for a match to a string [CODESPLIT] boolean matches ( String string ) throws JasperException { Mark mark = mark ( ) ; int ch = 0 ; int i = 0 ; do { ch = nextChar ( ) ; if ( ( ( char ) ch ) != string . charAt ( i ++ ) ) { reset ( mark ) ; return false ; } } while ( i < string . length ( ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks ahead to see if there are optional spaces followed by the given String . If so true is returned and those spaces and characters are skipped . If not false is returned and the position is restored to where we were before . [CODESPLIT] boolean matchesOptionalSpacesFollowedBy ( String s ) throws JasperException { Mark mark = mark ( ) ; skipSpaces ( ) ; boolean result = matches ( s ) ; if ( ! result ) { reset ( mark ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skip until the given string is matched in the stream . When returned the context is positioned past the end of the match . [CODESPLIT] Mark skipUntil ( String limit ) throws JasperException { Mark ret = null ; int limlen = limit . length ( ) ; int ch ; skip : for ( ret = mark ( ) , ch = nextChar ( ) ; ch != - 1 ; ret = mark ( ) , ch = nextChar ( ) ) { if ( ch == limit . charAt ( 0 ) ) { Mark restart = mark ( ) ; for ( int i = 1 ; i < limlen ; i ++ ) { if ( peekChar ( ) == limit . charAt ( i ) ) nextChar ( ) ; else { reset ( restart ) ; continue skip ; } } return ret ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skip until the given string is matched in the stream but ignoring chars initially escaped by a \\ . When returned the context is positioned past the end of the match . [CODESPLIT] Mark skipUntilIgnoreEsc ( String limit ) throws JasperException { Mark ret = null ; int limlen = limit . length ( ) ; int ch ; int prev = ' ' ; // Doesn't matter skip : for ( ret = mark ( ) , ch = nextChar ( ) ; ch != - 1 ; ret = mark ( ) , prev = ch , ch = nextChar ( ) ) { if ( ch == ' ' && prev == ' ' ) { ch = 0 ; // Double \\ is not an escape char anymore } else if ( ch == limit . charAt ( 0 ) && prev != ' ' ) { for ( int i = 1 ; i < limlen ; i ++ ) { if ( peekChar ( ) == limit . charAt ( i ) ) nextChar ( ) ; else continue skip ; } return ret ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skip until the given end tag is matched in the stream . When returned the context is positioned past the end of the tag . [CODESPLIT] Mark skipUntilETag ( String tag ) throws JasperException { Mark ret = skipUntil ( \"</\" + tag ) ; if ( ret != null ) { skipSpaces ( ) ; if ( nextChar ( ) != ' ' ) ret = null ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a space delimited token . If quoted the token will consume all characters up to a matching quote otherwise it consumes up to the first delimiter character . [CODESPLIT] String parseToken ( boolean quoted ) throws JasperException { StringBuilder stringBuffer = new StringBuilder ( ) ; skipSpaces ( ) ; stringBuffer . setLength ( 0 ) ; if ( ! hasMoreInput ( ) ) { return \"\" ; } int ch = peekChar ( ) ; if ( quoted ) { if ( ch == ' ' || ch == ' ' ) { char endQuote = ch == ' ' ? ' ' : ' ' ; // Consume the open quote:  ch = nextChar ( ) ; for ( ch = nextChar ( ) ; ch != - 1 && ch != endQuote ; ch = nextChar ( ) ) { if ( ch == ' ' ) ch = nextChar ( ) ; stringBuffer . append ( ( char ) ch ) ; } // Check end of quote, skip closing quote: if ( ch == - 1 ) { err . jspError ( mark ( ) , \"jsp.error.quotes.unterminated\" ) ; } } else { err . jspError ( mark ( ) , \"jsp.error.attr.quoted\" ) ; } } else { if ( ! isDelimiter ( ) ) { // Read value until delimiter is found: do { ch = nextChar ( ) ; // Take care of the quoting here. if ( ch == ' ' ) { if ( peekChar ( ) == ' ' || peekChar ( ) == ' ' || peekChar ( ) == ' ' || peekChar ( ) == ' ' ) ch = nextChar ( ) ; } stringBuffer . append ( ( char ) ch ) ; } while ( ! isDelimiter ( ) ) ; } } return stringBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse utils - Is current character a token delimiter ? Delimiters are currently defined to be = &gt ; &lt ; and or any any space character as defined by <code > isSpace< / code > . [CODESPLIT] private boolean isDelimiter ( ) throws JasperException { if ( ! isSpace ( ) ) { int ch = peekChar ( ) ; // Look for a single-char work delimiter: if ( ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' || ch == ' ' ) { return true ; } // Look for an end-of-comment or end-of-tag:\t\t if ( ch == ' ' ) { Mark mark = mark ( ) ; if ( ( ( ch = nextChar ( ) ) == ' ' ) || ( ( ch == ' ' ) && ( nextChar ( ) == ' ' ) ) ) { reset ( mark ) ; return true ; } else { reset ( mark ) ; return false ; } } return false ; } else { return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a new source file . This method is used to implement file inclusion . Each included file gets a unique identifier ( which is the index in the array of source files ) . [CODESPLIT] private int registerSourceFile ( String file ) { if ( sourceFiles . contains ( file ) ) return - 1 ; sourceFiles . add ( file ) ; this . size ++ ; return sourceFiles . size ( ) - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregister the source file . This method is used to implement file inclusion . Each included file gets a uniq identifier ( which is the index in the array of source files ) . [CODESPLIT] private int unregisterSourceFile ( String file ) { if ( ! sourceFiles . contains ( file ) ) return - 1 ; sourceFiles . remove ( file ) ; this . size -- ; return sourceFiles . size ( ) - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push a file ( and its associated Stream ) on the file stack . THe current position in the current file is remembered . [CODESPLIT] private void pushFile ( String file , String encoding , InputStreamReader reader ) throws JasperException , FileNotFoundException { // Register the file String longName = file ; int fileid = registerSourceFile ( longName ) ; if ( fileid == - 1 ) { err . jspError ( \"jsp.error.file.already.registered\" , file ) ; } currFileId = fileid ; try { CharArrayWriter caw = new CharArrayWriter ( ) ; char buf [ ] = new char [ 1024 ] ; for ( int i = 0 ; ( i = reader . read ( buf ) ) != - 1 ; ) caw . write ( buf , 0 , i ) ; caw . close ( ) ; if ( current == null ) { current = new Mark ( this , caw . toCharArray ( ) , fileid , getFile ( fileid ) , master , encoding ) ; } else { current . pushStream ( caw . toCharArray ( ) , fileid , getFile ( fileid ) , longName , encoding ) ; } } catch ( Throwable ex ) { log . log ( Level . SEVERE , \"Exception parsing file \" , ex ) ; // Pop state being constructed: popFile ( ) ; err . jspError ( \"jsp.error.file.cannot.read\" , file ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( Exception any ) { } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pop a file from the file stack . The field current is retored to the value to point to the previous files if any and is set to null otherwise . [CODESPLIT] private boolean popFile ( ) throws JasperException { // Is stack created ? (will happen if the Jsp file we're looking at is // missing. if ( current == null || currFileId < 0 ) { return false ; } // Restore parser state: String fName = getFile ( currFileId ) ; currFileId = unregisterSourceFile ( fName ) ; if ( currFileId < - 1 ) { err . jspError ( \"jsp.error.file.not.registered\" , fName ) ; } Mark previous = current . popStream ( ) ; if ( previous != null ) { master = current . baseDir ; current = previous ; return true ; } // Note that although the current file is undefined here, \"current\" // is not set to null just for convience, for it maybe used to // set the current (undefined) position. return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an unclassified version of ourself [CODESPLIT] public Coordinates makeUnclassified ( ) { if ( this . classifier == null ) { return this ; } return new Coordinates ( this . groupId , this . artifactId , this . version , this . qualifiedVersion , null , this . extension ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add custom binders assigned to the method <p > Custom binders assigned to the method will be added to the binding manager instance . < / p > [CODESPLIT] protected static void addMethodBinders ( final BindingManager manager , final Method method ) { final ControllerBinder [ ] binders = method . getAnnotationsByType ( ControllerBinder . class ) ; if ( binders == null ) { return ; } for ( final ControllerBinder binder : binders ) { try { final Binder binderImpl = binder . value ( ) . newInstance ( ) ; if ( binderImpl instanceof ControllerBinderParametersAware ) { ( ( ControllerBinderParametersAware ) binderImpl ) . setParameters ( binder . parameters ( ) ) ; } manager . addBinder ( binderImpl ) ; } catch ( InstantiationException | IllegalAccessException e ) { manager . addBinder ( new ErrorBinder ( e ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the given stratum as a String : a StratumSection followed by at least one FileSection and at least one LineSection . [CODESPLIT] public String getString ( ) { // check state and initialize buffer if ( fileNameList . size ( ) == 0 || lineData . size ( ) == 0 ) return null ; StringBuilder out = new StringBuilder ( ) ; // print StratumSection out . append ( \"*S \" + stratumName + \"\\n\" ) ; // print FileSection out . append ( \"*F\\n\" ) ; int bound = fileNameList . size ( ) ; for ( int i = 0 ; i < bound ; i ++ ) { if ( filePathList . get ( i ) != null ) { out . append ( \"+ \" + i + \" \" + fileNameList . get ( i ) + \"\\n\" ) ; // Source paths must be relative, not absolute, so we // remove the leading \"/\", if one exists. String filePath = filePathList . get ( i ) ; if ( filePath . startsWith ( \"/\" ) ) { filePath = filePath . substring ( 1 ) ; } out . append ( filePath + \"\\n\" ) ; } else { out . append ( i + \" \" + fileNameList . get ( i ) + \"\\n\" ) ; } } // print LineSection out . append ( \"*L\\n\" ) ; bound = lineData . size ( ) ; for ( int i = 0 ; i < bound ; i ++ ) { LineInfo li = lineData . get ( i ) ; out . append ( li . getString ( ) ) ; } return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke CompilationResult#getProblems safely so that it works with 3 . 1 . 1 and more recent versions of the eclipse java compiler . See https : // jsp . dev . java . net / issues / show_bug . cgi?id = 13 [CODESPLIT] private static final IProblem [ ] safeGetProblems ( CompilationResult result ) { if ( ! USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM ) { try { return result . getProblems ( ) ; } catch ( NoSuchMethodError re ) { USE_INTROSPECTION_TO_INVOKE_GET_PROBLEM = true ; } } try { if ( GET_PROBLEM_METH == null ) { GET_PROBLEM_METH = result . getClass ( ) . getDeclaredMethod ( \"getProblems\" , new Class [ ] { } ) ; } //an array of a particular type can be casted into an array of a super type. return ( IProblem [ ] ) GET_PROBLEM_METH . invoke ( result , null ) ; } catch ( Throwable e ) { if ( e instanceof RuntimeException ) { throw ( RuntimeException ) e ; } else { throw new RuntimeException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the compression options to the given preset . <p > The presets 0 - 3 are fast presets with medium compression . The presets 4 - 6 are fairly slow presets with high compression . The default preset ( <code > PRESET_DEFAULT< / code > ) is 6 . <p > The presets 7 - 9 are like the preset 6 but use bigger dictionaries and have higher compressor and decompressor memory requirements . Unless the uncompressed size of the file exceeds 8&nbsp ; MiB 16&nbsp ; MiB or 32&nbsp ; MiB it is waste of memory to use the presets 7 8 or 9 respectively . [CODESPLIT] public void setPreset ( int preset ) throws UnsupportedOptionsException { if ( preset < 0 || preset > 9 ) throw new UnsupportedOptionsException ( \"Unsupported preset: \" + preset ) ; lc = LC_DEFAULT ; lp = LP_DEFAULT ; pb = PB_DEFAULT ; dictSize = presetToDictSize [ preset ] ; if ( preset <= 3 ) { mode = MODE_FAST ; mf = MF_HC4 ; niceLen = preset <= 1 ? 128 : NICE_LEN_MAX ; depthLimit = presetToDepthLimit [ preset ] ; } else { mode = MODE_NORMAL ; mf = MF_BT4 ; niceLen = ( preset == 4 ) ? 16 : ( preset == 5 ) ? 32 : 64 ; depthLimit = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the dictionary size in bytes . <p > The dictionary ( or history buffer ) holds the most recently seen uncompressed data . Bigger dictionary usually means better compression . However using a dictioanary bigger than the size of the uncompressed data is waste of memory . <p > Any value in the range [ DICT_SIZE_MIN DICT_SIZE_MAX ] is valid but sizes of 2^n and 2^n&nbsp ; + &nbsp ; 2^ ( n - 1 ) bytes are somewhat recommended . [CODESPLIT] public void setDictSize ( int dictSize ) throws UnsupportedOptionsException { if ( dictSize < DICT_SIZE_MIN ) throw new UnsupportedOptionsException ( \"LZMA2 dictionary size must be at least 4 KiB: \" + dictSize + \" B\" ) ; if ( dictSize > DICT_SIZE_MAX ) throw new UnsupportedOptionsException ( \"LZMA2 dictionary size must not exceed \" + ( DICT_SIZE_MAX >> 20 ) + \" MiB: \" + dictSize + \" B\" ) ; this . dictSize = dictSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the number of literal context bits and literal position bits . <p > The sum of <code > lc< / code > and <code > lp< / code > is limited to 4 . Trying to exceed it will throw an exception . This function lets you change both at the same time . [CODESPLIT] public void setLcLp ( int lc , int lp ) throws UnsupportedOptionsException { if ( lc < 0 || lp < 0 || lc > LC_LP_MAX || lp > LC_LP_MAX || lc + lp > LC_LP_MAX ) throw new UnsupportedOptionsException ( \"lc + lp must not exceed \" + LC_LP_MAX + \": \" + lc + \" + \" + lp ) ; this . lc = lc ; this . lp = lp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the number of position bits . <p > This affects what kind of alignment in the uncompressed data is assumed in general . The default ( 2 ) means four - byte alignment ( 2^<code > pb< / code > = 2^2 = 4 ) which is often a good choice when there s no better guess . <p > When the alignment is known setting the number of position bits accordingly may reduce the file size a little . For example with text files having one - byte alignment ( US - ASCII ISO - 8859 - * UTF - 8 ) using <code > setPb ( 0 ) < / code > can improve compression slightly . For UTF - 16 text <code > setPb ( 1 ) < / code > is a good choice . If the alignment is an odd number like 3 bytes <code > setPb ( 0 ) < / code > might be the best choice . <p > Even though the assumed alignment can be adjusted with <code > setPb< / code > and <code > setLp< / code > LZMA2 still slightly favors 16 - byte alignment . It might be worth taking into account when designing file formats that are likely to be often compressed with LZMA2 . [CODESPLIT] public void setPb ( int pb ) throws UnsupportedOptionsException { if ( pb < 0 || pb > PB_MAX ) throw new UnsupportedOptionsException ( \"pb must not exceed \" + PB_MAX + \": \" + pb ) ; this . pb = pb ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the compression mode . <p > This specifies the method to analyze the data produced by a match finder . The default is <code > MODE_FAST< / code > for presets 0 - 3 and <code > MODE_NORMAL< / code > for presets 4 - 9 . <p > Usually <code > MODE_FAST< / code > is used with Hash Chain match finders and <code > MODE_NORMAL< / code > with Binary Tree match finders . This is also what the presets do . <p > The special mode <code > MODE_UNCOMPRESSED< / code > doesn t try to compress the data at all ( and doesn t use a match finder ) and will simply wrap it in uncompressed LZMA2 chunks . [CODESPLIT] public void setMode ( int mode ) throws UnsupportedOptionsException { if ( mode < MODE_UNCOMPRESSED || mode > MODE_NORMAL ) throw new UnsupportedOptionsException ( \"Unsupported compression mode: \" + mode ) ; this . mode = mode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the nice length of matches . Once a match of at least <code > niceLen< / code > bytes is found the algorithm stops looking for better matches . Higher values tend to give better compression at the expense of speed . The default depends on the preset . [CODESPLIT] public void setNiceLen ( int niceLen ) throws UnsupportedOptionsException { if ( niceLen < NICE_LEN_MIN ) throw new UnsupportedOptionsException ( \"Minimum nice length of matches is \" + NICE_LEN_MIN + \" bytes: \" + niceLen ) ; if ( niceLen > NICE_LEN_MAX ) throw new UnsupportedOptionsException ( \"Maximum nice length of matches is \" + NICE_LEN_MAX + \": \" + niceLen ) ; this . niceLen = niceLen ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the match finder type . <p > Match finder has a major effect on compression speed memory usage and compression ratio . Usually Hash Chain match finders are faster than Binary Tree match finders . The default depends on the preset : 0 - 3 use <code > MF_HC4< / code > and 4 - 9 use <code > MF_BT4< / code > . [CODESPLIT] public void setMatchFinder ( int mf ) throws UnsupportedOptionsException { if ( mf != MF_HC4 && mf != MF_BT4 ) throw new UnsupportedOptionsException ( \"Unsupported match finder: \" + mf ) ; this . mf = mf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets how much memory the LZMA2 decoder will need to decompress the data that was encoded with these options and stored in a . xz file . <p > The returned value may bigger than the value returned by a direct call to { [CODESPLIT] public int getDecoderMemoryUsage ( ) { // Round the dictionary size up to the next 2^n or 2^n + 2^(n-1). int d = dictSize - 1 ; d |= d >>> 2 ; d |= d >>> 3 ; d |= d >>> 4 ; d |= d >>> 8 ; d |= d >>> 16 ; return LZMA2InputStream . getMemoryUsage ( d + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Mark where , Exception e ) throws JasperException { dispatch ( where , e . getMessage ( ) , null , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( String errCode , String ... args ) throws JasperException { dispatch ( null , errCode , args , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Mark where , String errCode , String ... args ) throws JasperException { dispatch ( where , errCode , args , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Node n , String errCode , String ... args ) throws JasperException { dispatch ( n . getStart ( ) , errCode , args , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( String errCode , String arg , Exception e ) throws JasperException { dispatch ( null , errCode , new Object [ ] { arg } , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] public void jspError ( Node n , String errCode , String arg , Exception e ) throws JasperException { dispatch ( n . getStart ( ) , errCode , new Object [ ] { arg } , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and throws a new exception from the given JasperException by prepending the given location information ( containing file name line number and column number ) to the message of the given exception and copying the stacktrace of the given exception to the new exception . [CODESPLIT] public void throwException ( Mark where , JasperException je ) throws JasperException { if ( where == null ) { throw je ; } // Get file location String file = null ; if ( jspcMode ) { // Get the full URL of the resource that caused the error try { file = where . getURL ( ) . toString ( ) ; } catch ( MalformedURLException me ) { // Fallback to using context-relative path file = where . getFile ( ) ; } } else { // Get the context-relative resource path, so as to not // disclose any local filesystem details file = where . getFile ( ) ; } JasperException newEx = new JasperException ( file + \"(\" + where . getLineNumber ( ) + \",\" + where . getColumnNumber ( ) + \")\" + \" \" + je . getMessage ( ) , je . getCause ( ) ) ; newEx . setStackTrace ( je . getStackTrace ( ) ) ; throw newEx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given compilation error report and exception to the configured error handler . [CODESPLIT] public void javacError ( String errorReport , Exception e ) throws JasperException { errHandler . javacError ( errorReport , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Dispatches the given JSP parse error to the configured error handler . [CODESPLIT] private void dispatch ( Mark where , String errCode , Object [ ] args , Exception e ) throws JasperException { String file = null ; String errMsg = null ; int line = - 1 ; int column = - 1 ; boolean hasLocation = false ; // Localize if ( errCode != null ) { errMsg = Localizer . getMessage ( errCode , args ) ; } else if ( e != null ) { // give a hint about what's wrong errMsg = e . getMessage ( ) ; } // Get error location if ( where != null ) { if ( jspcMode ) { // Get the full URL of the resource that caused the error try { file = where . getURL ( ) . toString ( ) ; } catch ( MalformedURLException me ) { // Fallback to using context-relative path file = where . getFile ( ) ; } } else { // Get the context-relative resource path, so as to not // disclose any local filesystem details file = where . getFile ( ) ; } line = where . getLineNumber ( ) ; column = where . getColumnNumber ( ) ; hasLocation = true ; } // Get nested exception Exception nestedEx = e ; if ( ( e instanceof SAXException ) && ( ( ( SAXException ) e ) . getException ( ) != null ) ) { nestedEx = ( ( SAXException ) e ) . getException ( ) ; } if ( hasLocation ) { errHandler . jspError ( file , line , column , errMsg , nestedEx ) ; } else { errHandler . jspError ( errMsg , nestedEx ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses the given Java compilation error message which may contain one or more compilation errors into an array of JavacErrorDetail instances . [CODESPLIT] public static JavacErrorDetail [ ] parseJavacMessage ( Node . Nodes pageNodes , String errMsg , String fname ) throws IOException , JasperException { ArrayList < JavacErrorDetail > errors = new ArrayList < JavacErrorDetail > ( ) ; StringBuilder errMsgBuf = null ; int lineNum = - 1 ; JavacErrorDetail javacError = null ; BufferedReader reader = new BufferedReader ( new StringReader ( errMsg ) ) ; /*\n         * Parse compilation errors. Each compilation error consists of a file\n         * path and error line number, followed by a number of lines describing\n         * the error.\n         */ String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { /*\n\t     * Error line number is delimited by set of colons.\n\t     * Ignore colon following drive letter on Windows (fromIndex = 2).\n\t     * XXX Handle deprecation warnings that don't have line info\n\t     */ int beginColon = line . indexOf ( ' ' , 2 ) ; int endColon = line . indexOf ( ' ' , beginColon + 1 ) ; if ( ( beginColon >= 0 ) && ( endColon >= 0 ) ) { if ( javacError != null ) { // add previous error to error vector errors . add ( javacError ) ; } String lineNumStr = line . substring ( beginColon + 1 , endColon ) ; try { lineNum = Integer . parseInt ( lineNumStr ) ; } catch ( NumberFormatException e ) { // XXX } errMsgBuf = new StringBuilder ( ) ; javacError = createJavacError ( fname , pageNodes , errMsgBuf , lineNum ) ; } // Ignore messages preceding first error if ( errMsgBuf != null ) { errMsgBuf . append ( line ) ; errMsgBuf . append ( \"\\n\" ) ; } } // Add last error to error vector if ( javacError != null ) { errors . add ( javacError ) ; } reader . close ( ) ; return errors . toArray ( new JavacErrorDetail [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filter the provided aspect lists by a predicate on the ID [CODESPLIT] public static List < AspectInformation > filterIds ( final List < AspectInformation > list , final Predicate < String > predicate ) { if ( list == null ) { return null ; } return list . stream ( ) . filter ( ( i ) - > predicate . test ( i . getFactoryId ( ) ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all aspect ids which are currently missing but required by this aspect [CODESPLIT] public String [ ] getMissingIds ( final List < AspectInformation > assignedAspects ) { final Set < AspectInformation > required = new HashSet <> ( ) ; addRequired ( required , this , assignedAspects ) ; return required . stream ( ) . map ( AspectInformation :: getFactoryId ) . toArray ( size -> new String [ size ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the path prefix URL for . xsd resources [CODESPLIT] public static void setSchemaResourcePrefix ( String prefix ) { if ( prefix != null && prefix . startsWith ( \"file:\" ) ) { schemaResourcePrefix = uencode ( prefix ) ; isSchemaResourcePrefixFileUrl = true ; } else { schemaResourcePrefix = prefix ; isSchemaResourcePrefixFileUrl = false ; } for ( int i = 0 ; i < CACHED_SCHEMA_RESOURCE_PATHS . length ; i ++ ) { String path = DEFAULT_SCHEMA_RESOURCE_PATHS [ i ] ; int index = path . lastIndexOf ( ' ' ) ; if ( index != - 1 ) { CACHED_SCHEMA_RESOURCE_PATHS [ i ] = schemaResourcePrefix + path . substring ( index + 1 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the path prefix URL for . dtd resources [CODESPLIT] public static void setDtdResourcePrefix ( String prefix ) { if ( prefix != null && prefix . startsWith ( \"file:\" ) ) { dtdResourcePrefix = uencode ( prefix ) ; isDtdResourcePrefixFileUrl = true ; } else { dtdResourcePrefix = prefix ; isDtdResourcePrefixFileUrl = false ; } for ( int i = 0 ; i < CACHED_DTD_RESOURCE_PATHS . length ; i ++ ) { String path = DEFAULT_DTD_RESOURCE_PATHS [ i ] ; int index = path . lastIndexOf ( ' ' ) ; if ( index != - 1 ) { CACHED_DTD_RESOURCE_PATHS [ i ] = dtdResourcePrefix + path . substring ( index + 1 ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "END PWC 6386258 [CODESPLIT] private static String uencode ( String prefix ) { if ( prefix != null && prefix . startsWith ( \"file:\" ) ) { StringTokenizer tokens = new StringTokenizer ( prefix , \"/\\\\:\" , true ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; while ( tokens . hasMoreElements ( ) ) { String token = tokens . nextToken ( ) ; if ( \"/\" . equals ( token ) || \"\\\\\" . equals ( token ) || \":\" . equals ( token ) ) { stringBuilder . append ( token ) ; } else { try { stringBuilder . append ( URLEncoder . encode ( token , \"UTF-8\" ) ) ; } catch ( java . io . UnsupportedEncodingException ex ) { } } } return stringBuilder . toString ( ) ; } else { return prefix ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the specified XML document and return a <code > TreeNode< / code > that corresponds to the root node of the document tree . [CODESPLIT] public TreeNode parseXMLDocument ( String uri , InputSource is ) throws JasperException { return parseXMLDocument ( uri , is , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the specified XML document and return a <code > TreeNode< / code > that corresponds to the root node of the document tree . [CODESPLIT] public TreeNode parseXMLDocument ( String uri , InputSource is , boolean validate ) throws JasperException { Document document = null ; // Perform an XML parse of this document, via JAXP // START 6412405 ClassLoader currentLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Thread . currentThread ( ) . setContextClassLoader ( getClass ( ) . getClassLoader ( ) ) ; // END 6412405 try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; /* See CR 6399139\n            factory.setFeature(\n                \"http://apache.org/xml/features/validation/dynamic\",\n                true);\n            */ DocumentBuilder builder = factory . newDocumentBuilder ( ) ; builder . setEntityResolver ( entityResolver ) ; builder . setErrorHandler ( errorHandler ) ; document = builder . parse ( is ) ; document . setDocumentURI ( uri ) ; if ( validate ) { Schema schema = getSchema ( document ) ; if ( schema != null ) { // Validate TLD against specified schema schema . newValidator ( ) . validate ( new DOMSource ( document ) ) ; } /* See CR 6399139\n                else {\n                    log.warning(Localizer.getMessage(\n                        \"jsp.warning.dtdValidationNotSupported\"));\n                }\n                */ } } catch ( ParserConfigurationException ex ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.parse.xml\" , uri ) , ex ) ; } catch ( SAXParseException ex ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.parse.xml.line\" , uri , Integer . toString ( ex . getLineNumber ( ) ) , Integer . toString ( ex . getColumnNumber ( ) ) ) , ex ) ; } catch ( SAXException sx ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.parse.xml\" , uri ) , sx ) ; } catch ( IOException io ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.parse.xml\" , uri ) , io ) ; // START 6412405 } finally { Thread . currentThread ( ) . setContextClassLoader ( currentLoader ) ; } // END 6412405 // Convert the resulting document to a graph of TreeNodes return ( convert ( null , document . getDocumentElement ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and return a TreeNode that corresponds to the specified Node including processing all of the attributes and children nodes . [CODESPLIT] protected TreeNode convert ( TreeNode parent , Node node ) { // Construct a new TreeNode for this node TreeNode treeNode = new TreeNode ( node . getNodeName ( ) , parent ) ; // Convert all attributes of this node NamedNodeMap attributes = node . getAttributes ( ) ; if ( attributes != null ) { int n = attributes . getLength ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node attribute = attributes . item ( i ) ; treeNode . addAttribute ( attribute . getNodeName ( ) , attribute . getNodeValue ( ) ) ; } } // Create and attach all children of this node NodeList children = node . getChildNodes ( ) ; if ( children != null ) { int n = children . getLength ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node child = children . item ( i ) ; if ( child instanceof Comment ) continue ; if ( child instanceof Text ) { String body = ( ( Text ) child ) . getData ( ) ; if ( body != null ) { body = body . trim ( ) ; if ( body . length ( ) > 0 ) treeNode . setBody ( body ) ; } } else { TreeNode treeChild = convert ( treeNode , child ) ; } } } // Return the completed TreeNode graph return ( treeNode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets the compiled schema referenced by the given XML document . [CODESPLIT] private static Schema getSchema ( Document document ) throws SAXException , JasperException { Schema schema = null ; Element root = document . getDocumentElement ( ) ; NamedNodeMap map = root . getAttributes ( ) ; for ( int i = 0 ; map != null && i < map . getLength ( ) ; i ++ ) { if ( SCHEMA_LOCATION_ATTR . equals ( map . item ( i ) . getLocalName ( ) ) ) { String schemaLocation = map . item ( i ) . getNodeValue ( ) ; if ( Constants . SCHEMA_LOCATION_JSP_20 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . TAGLIB_SCHEMA_PUBLIC_ID_20 ) ; break ; } else if ( Constants . SCHEMA_LOCATION_JSP_21 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . TAGLIB_SCHEMA_PUBLIC_ID_21 ) ; break ; } else if ( Constants . SCHEMA_LOCATION_WEBAPP_24 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . WEBAPP_SCHEMA_PUBLIC_ID_24 ) ; break ; } else if ( Constants . SCHEMA_LOCATION_WEBAPP_25 . equals ( schemaLocation ) ) { schema = getSchema ( Constants . WEBAPP_SCHEMA_PUBLIC_ID_25 ) ; break ; } else { throw new JasperException ( Localizer . getMessage ( \"jsp.error.parse.unknownTldSchemaLocation\" , document . getDocumentURI ( ) , map . item ( i ) . getNodeValue ( ) ) ) ; } } } return schema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets the compiled schema for the given schema public id . [CODESPLIT] private static Schema getSchema ( String schemaPublicId ) throws SAXException { Schema schema = schemaCache . get ( schemaPublicId ) ; if ( schema == null ) { synchronized ( schemaCache ) { schema = schemaCache . get ( schemaPublicId ) ; if ( schema == null ) { SchemaFactory schemaFactory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; schemaFactory . setResourceResolver ( new MyLSResourceResolver ( ) ) ; schemaFactory . setErrorHandler ( new MyErrorHandler ( ) ) ; String path = schemaPublicId ; if ( schemaResourcePrefix != null ) { int index = schemaPublicId . lastIndexOf ( ' ' ) ; if ( index != - 1 ) { path = schemaPublicId . substring ( index + 1 ) ; } path = schemaResourcePrefix + path ; } InputStream input = null ; if ( isSchemaResourcePrefixFileUrl ) { try { File f = new File ( new URI ( path ) ) ; if ( f . exists ( ) ) { input = new FileInputStream ( f ) ; } } catch ( Exception e ) { throw new SAXException ( e ) ; } } else { input = ParserUtils . class . getResourceAsStream ( path ) ; } if ( input == null ) { throw new SAXException ( Localizer . getMessage ( \"jsp.error.internal.filenotfound\" , schemaPublicId ) ) ; } schema = schemaFactory . newSchema ( new StreamSource ( input ) ) ; schemaCache . put ( schemaPublicId , schema ) ; } } } return schema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new BindingManager with default binders <p > This call creates a new BindingManager instance and add the following binders : < / p > <ul > <li > { @link MapBinder } < / li > <li > { @link BindingManagerBinder } < / li > < / ul > [CODESPLIT] public static final BindingManager create ( final Map < String , Object > data ) { final BindingManager result = new BindingManager ( ) ; result . addBinder ( new MapBinder ( data ) ) ; result . addBinder ( new BindingManagerBinder ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge all errors of this binding into this result [CODESPLIT] private static void mergeErrors ( final BindingResult bindingResult , final BindingResult result ) { if ( bindingResult == null ) { return ; } result . addErrors ( bindingResult . getLocalErrors ( ) ) ; for ( final Map . Entry < String , BindingResult > child : bindingResult . getChildren ( ) . entrySet ( ) ) { mergeErrors ( child . getValue ( ) , result . getChildOrAdd ( child . getKey ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new binder <p > If the binder has to be initialized then all methods annotated with { @link Initializer } will be called . < / p > [CODESPLIT] public void addBinder ( final Binder binder , final boolean initializeBinder ) { if ( initializeBinder ) { initializeBinder ( binder ) ; } this . binders . add ( binder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the binder with our current state [CODESPLIT] private void initializeBinder ( final Binder binder ) { for ( final Method m : binder . getClass ( ) . getMethods ( ) ) { if ( ! m . isAnnotationPresent ( Binder . Initializer . class ) ) { continue ; } final Call call = bind ( m , binder ) ; try { call . invoke ( ) ; } catch ( final Exception e ) { throw new RuntimeException ( String . format ( \"Failed to initialze binder: %s # %s\" , binder , m ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This actively scans for available aspects and returns their information objects [CODESPLIT] public static Map < String , ChannelAspectInformation > scanAspectInformations ( final BundleContext context ) { Collection < ServiceReference < ChannelAspectFactory >> refs ; try { refs = context . getServiceReferences ( ChannelAspectFactory . class , null ) ; } catch ( final InvalidSyntaxException e ) { // this should never happen since we don't specific a filter return Collections . emptyMap ( ) ; } if ( refs == null ) { return Collections . emptyMap ( ) ; } final Map < String , ChannelAspectInformation > result = new HashMap <> ( refs . size ( ) ) ; for ( final ServiceReference < ChannelAspectFactory > ref : refs ) { final ChannelAspectInformation info = makeInformation ( ref ) ; result . put ( info . getFactoryId ( ) , info ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates an appropriate SMAP representing the current compilation context . ( JSR - 045 . ) [CODESPLIT] public void generateSmap ( Node . Nodes pageNodes ) throws IOException { classInfos = new ArrayList < ClassInfo > ( ) ; String className = ctxt . getFullClassName ( ) ; // Instantiate a SmapStratum for the main JSP page. SmapStratum s = new SmapStratum ( \"JSP\" ) ; classInfos . add ( new ClassInfo ( className , s ) ) ; // Map out Node.Nodes and putting LineInfo into SmapStratum evaluateNodes ( pageNodes , s , ctxt . getOptions ( ) . getMappedFile ( ) ) ; String classFileName = ctxt . getClassFileName ( ) ; for ( ClassInfo entry : classInfos ) { // Get SmapStratum s = entry . getSmapStratum ( ) ; s . optimizeLineSection ( ) ; // Set up our SMAP generator SmapGenerator g = new SmapGenerator ( ) ; g . setOutputFileName ( unqualify ( ctxt . getServletJavaFileName ( ) ) ) ; g . addStratum ( s , true ) ; String name = entry . getClassName ( ) ; // class name // Compute the class name and output file name for inner classes if ( ! className . equals ( name ) ) { classFileName = ctxt . getOutputDir ( ) + name . substring ( name . lastIndexOf ( ' ' ) + 1 ) + \".class\" ; } entry . setClassFileName ( classFileName ) ; entry . setSmap ( g . getString ( ) ) ; if ( ctxt . getOptions ( ) . isSmapDumped ( ) ) { File outSmap = new File ( classFileName + \".smap\" ) ; PrintWriter so = new PrintWriter ( new OutputStreamWriter ( new FileOutputStream ( outSmap ) , SMAP_ENCODING ) ) ; so . print ( g . getString ( ) ) ; so . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an unqualified version of the given file path . [CODESPLIT] private static String unqualify ( String path ) { path = path . replace ( ' ' , ' ' ) ; return path . substring ( path . lastIndexOf ( ' ' ) + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke tag plugin for the given custom tag if a plugin exists for the custom tag s tag handler . [CODESPLIT] private void invokePlugin ( Node . CustomTag n ) { TagPlugin tagPlugin = tagPlugins . get ( n . getTagHandlerClass ( ) . getName ( ) ) ; if ( tagPlugin == null ) { return ; } TagPluginContext tagPluginContext = new TagPluginContextImpl ( n , pageInfo ) ; n . setTagPluginContext ( tagPluginContext ) ; tagPlugin . doTag ( tagPluginContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets { [CODESPLIT] private static < T > T getArray ( CacheMap < T > cache , int size ) { // putArray doesn't add small arrays to the cache and so it's // pointless to look for small arrays here. if ( size < CACHEABLE_SIZE_MIN ) return null ; // Try to find a stack that holds arrays of T[size]. CyclicStack < Reference < T > > stack ; synchronized ( cache ) { stack = cache . get ( size ) ; } if ( stack == null ) return null ; // Try to find a non-cleared Reference from the stack. T array ; do { Reference < T > r = stack . pop ( ) ; if ( r == null ) return null ; array = r . get ( ) ; } while ( array == null ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts the { [CODESPLIT] private static < T > void putArray ( CacheMap < T > cache , T array , int size ) { // Small arrays aren't cached. if ( size < CACHEABLE_SIZE_MIN ) return ; CyclicStack < Reference < T > > stack ; synchronized ( cache ) { // Get a stack that holds arrays of T[size]. If no such stack // exists, allocate a new one. If the cache already had STACKS_MAX // number of stacks, the least recently used stack is removed by // cache.put (it calls removeEldestEntry). stack = cache . get ( size ) ; if ( stack == null ) { stack = new CyclicStack < Reference < T > > ( ) ; cache . put ( size , stack ) ; } } stack . push ( new SoftReference < T > ( array ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocates a new byte array hopefully reusing an existing array from the cache . [CODESPLIT] public byte [ ] getByteArray ( int size , boolean fillWithZeros ) { byte [ ] array = getArray ( byteArrayCache , size ) ; if ( array == null ) array = new byte [ size ] ; else if ( fillWithZeros ) Arrays . fill ( array , ( byte ) 0x00 ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is like getByteArray but for int arrays . [CODESPLIT] public int [ ] getIntArray ( int size , boolean fillWithZeros ) { int [ ] array = getArray ( intArrayCache , size ) ; if ( array == null ) array = new int [ size ] ; else if ( fillWithZeros ) Arrays . fill ( array , 0 ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare an import with dependencies <p > This method does resolve even transient dependencies and also adds the sources if requested < / p > [CODESPLIT] public static AetherResult prepareDependencies ( final Path tmpDir , final ImportConfiguration cfg ) throws RepositoryException { Objects . requireNonNull ( tmpDir ) ; Objects . requireNonNull ( cfg ) ; final RepositoryContext ctx = new RepositoryContext ( tmpDir , cfg . getRepositoryUrl ( ) , cfg . isAllOptional ( ) ) ; // add all coordinates final CollectRequest cr = new CollectRequest ( ) ; cr . setRepositories ( ctx . getRepositories ( ) ) ; for ( final MavenCoordinates coords : cfg . getCoordinates ( ) ) { final Dependency dep = new Dependency ( new DefaultArtifact ( coords . toString ( ) ) , COMPILE ) ; cr . addDependency ( dep ) ; } final DependencyFilter filter = DependencyFilterUtils . classpathFilter ( COMPILE ) ; final DependencyRequest deps = new DependencyRequest ( cr , filter ) ; // resolve final DependencyResult dr = ctx . getSystem ( ) . resolveDependencies ( ctx . getSession ( ) , deps ) ; final List < ArtifactResult > arts = dr . getArtifactResults ( ) ; if ( ! cfg . isIncludeSources ( ) ) { // we are already done here return asResult ( arts , cfg , of ( dr ) ) ; } // resolve sources final List < ArtifactRequest > requests = extendRequests ( arts . stream ( ) . map ( ArtifactResult :: getRequest ) , ctx , cfg ) ; return asResult ( resolve ( ctx , requests ) , cfg , of ( dr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare a plain import process <p > Prepare a simple import request with a specific list of coordinates < / p > [CODESPLIT] public static AetherResult preparePlain ( final Path tmpDir , final ImportConfiguration cfg ) throws ArtifactResolutionException { Objects . requireNonNull ( tmpDir ) ; Objects . requireNonNull ( cfg ) ; final RepositoryContext ctx = new RepositoryContext ( tmpDir , cfg . getRepositoryUrl ( ) , cfg . isAllOptional ( ) ) ; // extend final List < ArtifactRequest > requests = extendRequests ( cfg . getCoordinates ( ) . stream ( ) . map ( c -> { final DefaultArtifact artifact = new DefaultArtifact ( c . toString ( ) ) ; return makeRequest ( ctx . getRepositories ( ) , artifact ) ; } ) , ctx , cfg ) ; // process return asResult ( resolve ( ctx , requests ) , cfg , empty ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the actual import request <p > This method takes the import configuration as is and simply tries to import it . Not manipulating the list of coordinates any more < / p > [CODESPLIT] public static Collection < ArtifactResult > processImport ( final Path tmpDir , final ImportConfiguration cfg ) throws ArtifactResolutionException { Objects . requireNonNull ( tmpDir ) ; Objects . requireNonNull ( cfg ) ; final RepositoryContext ctx = new RepositoryContext ( tmpDir , cfg . getRepositoryUrl ( ) ) ; final Collection < ArtifactRequest > requests = new LinkedList <> ( ) ; for ( final MavenCoordinates coords : cfg . getCoordinates ( ) ) { // main artifact final DefaultArtifact main = new DefaultArtifact ( coords . toString ( ) ) ; requests . add ( makeRequest ( ctx . getRepositories ( ) , main ) ) ; } // process return ctx . getSystem ( ) . resolveArtifacts ( ctx . getSession ( ) , requests ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert aether result list to AetherResult object [CODESPLIT] public static AetherResult asResult ( final Collection < ArtifactResult > results , final ImportConfiguration cfg , final Optional < DependencyResult > dependencyResult ) { final AetherResult result = new AetherResult ( ) ; // create set of requested coordinates final Set < String > requested = new HashSet <> ( cfg . getCoordinates ( ) . size ( ) ) ; for ( final MavenCoordinates mc : cfg . getCoordinates ( ) ) { requested . add ( mc . toString ( ) ) ; } // generate dependency map final Map < String , Boolean > optionalDeps = new HashMap <> ( ) ; fillOptionalDependenciesMap ( dependencyResult , optionalDeps ) ; // convert artifacts for ( final ArtifactResult ar : results ) { final AetherResult . Entry entry = new AetherResult . Entry ( ) ; final MavenCoordinates coordinates = MavenCoordinates . fromResult ( ar ) ; final String key = coordinates . toBase ( ) . toString ( ) ; entry . setCoordinates ( coordinates ) ; entry . setResolved ( ar . isResolved ( ) ) ; entry . setRequested ( requested . contains ( key ) ) ; entry . setOptional ( optionalDeps . getOrDefault ( key , Boolean . FALSE ) ) ; // convert error if ( ar . getExceptions ( ) != null && ! ar . getExceptions ( ) . isEmpty ( ) ) { final StringBuilder sb = new StringBuilder ( ar . getExceptions ( ) . get ( 0 ) . getMessage ( ) ) ; if ( ar . getExceptions ( ) . size ( ) > 1 ) { sb . append ( \" ...\" ) ; } entry . setError ( sb . toString ( ) ) ; } // add to list result . getArtifacts ( ) . add ( entry ) ; } // sort by coordinates Collections . sort ( result . getArtifacts ( ) , Comparator . comparing ( AetherResult . Entry :: getCoordinates ) ) ; // set repo url result . setRepositoryUrl ( cfg . getRepositoryUrl ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the following is a workaround until these problems are resolved . [CODESPLIT] private InputStream getResourceAsStream ( String uri ) throws JasperException { try { // see if file exists on the filesystem first String real = ctxt . getRealPath ( uri ) ; if ( real == null ) { return ctxt . getResourceAsStream ( uri ) ; } else { return new FileInputStream ( real ) ; } } catch ( FileNotFoundException ex ) { // if file not found on filesystem, get the resource through // the context return ctxt . getResourceAsStream ( uri ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of TagLibraryInfo objects representing the entire set of tag libraries ( including this TagLibraryInfo ) imported by taglib directives in the translation unit that references this TagLibraryInfo . [CODESPLIT] public TagLibraryInfo [ ] getTagLibraryInfos ( ) { TagLibraryInfo [ ] taglibs = null ; Collection < TagLibraryInfo > c = pageInfo . getTaglibs ( ) ; if ( c != null && c . size ( ) > 0 ) { taglibs = c . toArray ( new TagLibraryInfo [ 0 ] ) ; } return taglibs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] private void parseTLD ( JspCompilationContext ctxt , String uri , InputStream in , URL jarFileUrl ) throws JasperException { List < TagInfo > tagVector = new ArrayList < TagInfo > ( ) ; List < TagFileInfo > tagFileVector = new ArrayList < TagFileInfo > ( ) ; HashMap < String , FunctionInfo > functionTable = new HashMap < String , FunctionInfo > ( ) ; // Create an iterator over the child elements of our <taglib> element ParserUtils pu = new ParserUtils ( ) ; TreeNode tld = pu . parseXMLDocument ( uri , in ) ; // Check to see if the <taglib> root element contains a 'version' // attribute, which was added in JSP 2.0 to replace the <jsp-version> // subelement this . jspversion = tld . findAttribute ( \"version\" ) ; // Process each child element of our <taglib> element Iterator list = tld . findChildren ( ) ; while ( list . hasNext ( ) ) { TreeNode element = ( TreeNode ) list . next ( ) ; String tname = element . getName ( ) ; if ( \"tlibversion\" . equals ( tname ) // JSP 1.1 || \"tlib-version\" . equals ( tname ) ) { // JSP 1.2 this . tlibversion = element . getBody ( ) ; } else if ( \"jspversion\" . equals ( tname ) || \"jsp-version\" . equals ( tname ) ) { this . jspversion = element . getBody ( ) ; } else if ( \"shortname\" . equals ( tname ) || \"short-name\" . equals ( tname ) ) this . shortname = element . getBody ( ) ; else if ( \"uri\" . equals ( tname ) ) this . urn = element . getBody ( ) ; else if ( \"info\" . equals ( tname ) || \"description\" . equals ( tname ) ) this . info = element . getBody ( ) ; else if ( \"validator\" . equals ( tname ) ) this . tagLibraryValidator = createValidator ( element ) ; else if ( \"tag\" . equals ( tname ) ) tagVector . add ( createTagInfo ( element , jspversion ) ) ; else if ( \"tag-file\" . equals ( tname ) ) { TagFileInfo tagFileInfo = createTagFileInfo ( element , uri , jarFileUrl ) ; tagFileVector . add ( tagFileInfo ) ; } else if ( \"function\" . equals ( tname ) ) { // JSP2.0 FunctionInfo funcInfo = createFunctionInfo ( element ) ; String funcName = funcInfo . getName ( ) ; if ( functionTable . containsKey ( funcName ) ) { err . jspError ( \"jsp.error.tld.fn.duplicate.name\" , funcName , uri ) ; } functionTable . put ( funcName , funcInfo ) ; } else if ( \"display-name\" . equals ( tname ) || // Ignored elements \"small-icon\" . equals ( tname ) || \"large-icon\" . equals ( tname ) || \"listener\" . equals ( tname ) ) { ; } else if ( \"taglib-extension\" . equals ( tname ) ) { // Recognized but ignored } else { err . jspError ( \"jsp.error.unknown.element.in.taglib\" , tname ) ; } } if ( tlibversion == null ) { err . jspError ( \"jsp.error.tld.mandatory.element.missing\" , \"tlib-version\" ) ; } if ( jspversion == null ) { err . jspError ( \"jsp.error.tld.mandatory.element.missing\" , \"jsp-version\" ) ; } this . tags = tagVector . toArray ( new TagInfo [ 0 ] ) ; this . tagFiles = tagFileVector . toArray ( new TagFileInfo [ 0 ] ) ; this . functions = new FunctionInfo [ functionTable . size ( ) ] ; int i = 0 ; for ( FunctionInfo funcInfo : functionTable . values ( ) ) { this . functions [ i ++ ] = funcInfo ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * @param uri The uri of the TLD @param ctxt The compilation context [CODESPLIT] private String [ ] generateTLDLocation ( String uri , JspCompilationContext ctxt ) throws JasperException { int uriType = TldScanner . uriType ( uri ) ; if ( uriType == TldScanner . ABS_URI ) { err . jspError ( \"jsp.error.taglibDirective.absUriCannotBeResolved\" , uri ) ; } else if ( uriType == TldScanner . NOROOT_REL_URI ) { uri = ctxt . resolveRelativeUri ( uri ) ; } String [ ] location = new String [ 2 ] ; location [ 0 ] = uri ; if ( location [ 0 ] . endsWith ( \"jar\" ) ) { URL url = null ; try { url = ctxt . getResource ( location [ 0 ] ) ; } catch ( Exception ex ) { err . jspError ( \"jsp.error.tld.unable_to_get_jar\" , location [ 0 ] , ex . toString ( ) ) ; } if ( url == null ) { err . jspError ( \"jsp.error.tld.missing_jar\" , location [ 0 ] ) ; } location [ 0 ] = url . toString ( ) ; location [ 1 ] = \"META-INF/taglib.tld\" ; } return location ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parses the tag file directives of the given TagFile and turns them into a TagInfo . [CODESPLIT] private TagFileInfo createTagFileInfo ( TreeNode elem , String uri , URL jarFileUrl ) throws JasperException { String name = null ; String path = null ; String description = null ; String displayName = null ; String icon = null ; boolean checkConflict = false ; Iterator list = elem . findChildren ( ) ; while ( list . hasNext ( ) ) { TreeNode child = ( TreeNode ) list . next ( ) ; String tname = child . getName ( ) ; if ( \"name\" . equals ( tname ) ) { name = child . getBody ( ) ; } else if ( \"path\" . equals ( tname ) ) { path = child . getBody ( ) ; } else if ( \"description\" . equals ( tname ) ) { checkConflict = true ; description = child . getBody ( ) ; } else if ( \"display-name\" . equals ( tname ) ) { checkConflict = true ; displayName = child . getBody ( ) ; } else if ( \"icon\" . equals ( tname ) ) { checkConflict = true ; icon = child . getBody ( ) ; } else if ( \"example\" . equals ( tname ) ) { // Ignore <example> element: Bugzilla 33538 } else if ( \"tag-extension\" . equals ( tname ) ) { // Ignore <tag-extension> element: Bugzilla 33538 } else { err . jspError ( \"jsp.error.unknown.element.in.tagfile\" , tname ) ; } } if ( path . startsWith ( \"/META-INF/tags\" ) ) { // Tag file packaged in JAR // STARTJR: fix possible NPE if ( jarFileUrl != null ) { ctxt . getTagFileJarUrls ( ) . put ( path , jarFileUrl ) ; } // ENDJR: fix possible NPE } else if ( ! path . startsWith ( \"/WEB-INF/tags\" ) ) { err . jspError ( \"jsp.error.tagfile.illegalPath\" , path ) ; } JasperTagInfo tagInfo = ( JasperTagInfo ) TagFileProcessor . parseTagFileDirectives ( parserController , name , path , this ) ; if ( checkConflict ) { String tstring = tagInfo . getInfoString ( ) ; if ( tstring != null && ! \"\" . equals ( tstring ) ) { description = tstring ; } tstring = tagInfo . getDisplayName ( ) ; if ( tstring != null && ! \"\" . equals ( tstring ) ) { displayName = tstring ; } tstring = tagInfo . getSmallIcon ( ) ; if ( tstring != null && ! \"\" . equals ( tstring ) ) { icon = tstring ; } tagInfo = new JasperTagInfo ( tagInfo . getTagName ( ) , tagInfo . getTagClassName ( ) , tagInfo . getBodyContent ( ) , description , tagInfo . getTagLibrary ( ) , tagInfo . getTagExtraInfo ( ) , tagInfo . getAttributes ( ) , displayName , icon , tagInfo . getLargeIcon ( ) , tagInfo . getTagVariableInfos ( ) , tagInfo . getDynamicAttributesMapName ( ) ) ; } return new TagFileInfo ( name , path , tagInfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translation - time validation of the XML document associated with the JSP page . This is a convenience method on the associated TagLibraryValidator class . [CODESPLIT] public ValidationMessage [ ] validate ( PageData thePage ) { TagLibraryValidator tlv = getTagLibraryValidator ( ) ; if ( tlv == null ) return null ; String uri = getURI ( ) ; if ( uri . startsWith ( \"/\" ) ) { uri = URN_JSPTLD + uri ; } ValidationMessage [ ] messages = tlv . validate ( getPrefixString ( ) , uri , thePage ) ; tlv . release ( ) ; return messages ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets this mark s state to a new stream . It will store the current stream in it s includeStack . [CODESPLIT] public void pushStream ( char [ ] inStream , int inFileid , String name , String inBaseDir , String inEncoding ) { // store current state in stack includeStack . push ( new IncludeState ( cursor , line , col , fileid , fileName , baseDir , encoding , stream ) ) ; // set new variables cursor = 0 ; line = 1 ; col = 1 ; fileid = inFileid ; fileName = name ; baseDir = inBaseDir ; encoding = inEncoding ; stream = inStream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Restores this mark s state to a previously stored stream . [CODESPLIT] public Mark popStream ( ) { // make sure we have something to pop if ( includeStack . size ( ) <= 0 ) { return null ; } // get previous state in stack IncludeState state = includeStack . pop ( ) ; // set new variables cursor = state . cursor ; line = state . line ; col = state . col ; fileid = state . fileid ; fileName = state . fileName ; baseDir = state . baseDir ; stream = state . stream ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Autodetects the encoding of the XML document supplied by the given input stream . [CODESPLIT] public static Object [ ] getEncoding ( String fname , JarFile jarFile , JspCompilationContext ctxt , ErrorDispatcher err ) throws IOException , JasperException { InputStream inStream = JspUtil . getInputStream ( fname , jarFile , ctxt , err ) ; XMLEncodingDetector detector = new XMLEncodingDetector ( ) ; Object [ ] ret = detector . getEncoding ( inStream , err ) ; inStream . close ( ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "org . apache . xerces . impl . XMLEntityManager . startEntity () [CODESPLIT] private void createInitialReader ( ) throws IOException , JasperException { // wrap this stream in RewindableInputStream stream = new RewindableInputStream ( stream ) ; // perform auto-detect of encoding if necessary if ( encoding == null ) { // read first four bytes and determine encoding final byte [ ] b4 = new byte [ 4 ] ; int count = 0 ; for ( ; count < 4 ; count ++ ) { b4 [ count ] = ( byte ) stream . read ( ) ; } if ( count == 4 ) { Object [ ] encodingDesc = getEncodingName ( b4 , count ) ; encoding = ( String ) ( encodingDesc [ 0 ] ) ; isBigEndian = ( Boolean ) ( encodingDesc [ 1 ] ) ; hasBom = ( Boolean ) ( encodingDesc [ 2 ] ) ; stream . reset ( ) ; // Special case UTF-8 files with BOM created by Microsoft // tools. It's more efficient to consume the BOM than make // the reader perform extra checks. -Ac if ( count > 2 && encoding . equals ( \"UTF-8\" ) ) { int b0 = b4 [ 0 ] & 0xFF ; int b1 = b4 [ 1 ] & 0xFF ; int b2 = b4 [ 2 ] & 0xFF ; if ( b0 == 0xEF && b1 == 0xBB && b2 == 0xBF ) { // ignore first three bytes... stream . skip ( 3 ) ; } } reader = createReader ( stream , encoding , isBigEndian ) ; } else { reader = createReader ( stream , encoding , isBigEndian ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the IANA encoding name that is auto - detected from the bytes specified with the endian - ness of that encoding where appropriate . [CODESPLIT] private Object [ ] getEncodingName ( byte [ ] b4 , int count ) { if ( count < 2 ) { return new Object [ ] { \"UTF-8\" , null , null } ; } // UTF-16, with BOM int b0 = b4 [ 0 ] & 0xFF ; int b1 = b4 [ 1 ] & 0xFF ; if ( b0 == 0xFE && b1 == 0xFF ) { // UTF-16, big-endian, with a BOM return new Object [ ] { \"UTF-16BE\" , Boolean . TRUE , Boolean . TRUE } ; } /* SJSAS 6307968\n        if (b0 == 0xFF && b1 == 0xFE) {\n        */ // BEGIN SJSAS 6307968 if ( count == 2 && b0 == 0xFF && b1 == 0xFE ) { // END SJSAS 6307968 // UTF-16, little-endian, with a BOM return new Object [ ] { \"UTF-16LE\" , Boolean . FALSE , Boolean . TRUE } ; } // default to UTF-8 if we don't have enough bytes to make a // good determination of the encoding if ( count < 3 ) { return new Object [ ] { \"UTF-8\" , null , null } ; } // UTF-8 with a BOM int b2 = b4 [ 2 ] & 0xFF ; if ( b0 == 0xEF && b1 == 0xBB && b2 == 0xBF ) { return new Object [ ] { \"UTF-8\" , null , Boolean . TRUE } ; } // default to UTF-8 if we don't have enough bytes to make a // good determination of the encoding if ( count < 4 ) { return new Object [ ] { \"UTF-8\" , null , null } ; } // other encodings int b3 = b4 [ 3 ] & 0xFF ; if ( b0 == 0x00 && b1 == 0x00 && b2 == 0x00 && b3 == 0x3C ) { // UCS-4, big endian (1234) return new Object [ ] { \"ISO-10646-UCS-4\" , Boolean . TRUE , null } ; } if ( b0 == 0x3C && b1 == 0x00 && b2 == 0x00 && b3 == 0x00 ) { // UCS-4, little endian (4321) return new Object [ ] { \"ISO-10646-UCS-4\" , Boolean . FALSE , null } ; } if ( b0 == 0x00 && b1 == 0x00 && b2 == 0x3C && b3 == 0x00 ) { // UCS-4, unusual octet order (2143) // REVISIT: What should this be? return new Object [ ] { \"ISO-10646-UCS-4\" , null , null } ; } if ( b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x00 ) { // UCS-4, unusual octect order (3412) // REVISIT: What should this be? return new Object [ ] { \"ISO-10646-UCS-4\" , null , null } ; } if ( b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x3F ) { // UTF-16, big-endian, no BOM // (or could turn out to be UCS-2... // REVISIT: What should this be? return new Object [ ] { \"UTF-16BE\" , Boolean . TRUE , null } ; } if ( b0 == 0x3C && b1 == 0x00 && b2 == 0x3F && b3 == 0x00 ) { // UTF-16, little-endian, no BOM // (or could turn out to be UCS-2... return new Object [ ] { \"UTF-16LE\" , Boolean . FALSE , null } ; } if ( b0 == 0x4C && b1 == 0x6F && b2 == 0xA7 && b3 == 0x94 ) { // EBCDIC // a la xerces1, return CP037 instead of EBCDIC here return new Object [ ] { \"CP037\" , null , null } ; } if ( b0 == 0x00 && b1 == 0x00 && b2 == 0xFE && b3 == 0xFF ) { // UTF-32, big-endian, with a BOM return new Object [ ] { \"UTF-32BE\" , Boolean . TRUE , Boolean . TRUE } ; } if ( b0 == 0xFF && b1 == 0xFE && b2 == 0x00 && b3 == 0x00 ) { // UTF-32, little-endian, with a BOM return new Object [ ] { \"UTF-32LE\" , Boolean . FALSE , Boolean . TRUE } ; } // BEGIN SJSAS 6307968 if ( b0 == 0xFF && b1 == 0xFE ) { // UTF-16, little-endian, with a BOM return new Object [ ] { \"UTF-16LE\" , Boolean . FALSE , Boolean . TRUE } ; } // END SJSAS 6307968 // default encoding return new Object [ ] { \"UTF-8\" , null , null } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "org . apache . xerces . impl . XMLDocumentScannerImpl . dispatch [CODESPLIT] private void scanXMLDecl ( ) throws IOException , JasperException { if ( skipString ( \"<?xml\" ) ) { fMarkupDepth ++ ; // NOTE: special case where document starts with a PI //       whose name starts with \"xml\" (e.g. \"xmlfoo\") if ( XMLChar . isName ( peekChar ( ) ) ) { fStringBuffer . clear ( ) ; fStringBuffer . append ( \"xml\" ) ; while ( XMLChar . isName ( peekChar ( ) ) ) { fStringBuffer . append ( ( char ) scanChar ( ) ) ; } String target = fSymbolTable . addSymbol ( fStringBuffer . ch , fStringBuffer . offset , fStringBuffer . length ) ; scanPIData ( target , fString ) ; } // standard XML declaration else { scanXMLDeclOrTextDecl ( false ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans an XML or text declaration . <p > <pre > [ 23 ] XMLDecl :: = &lt ; ?xml VersionInfo EncodingDecl? SDDecl? S? ? > [ 24 ] VersionInfo :: = S version Eq ( VersionNum | VersionNum ) [ 80 ] EncodingDecl :: = S encoding Eq ( EncName | EncName ) [ 81 ] EncName :: = [ A - Za - z ] ( [ A - Za - z0 - 9 . _ ] | - ) * [ 32 ] SDDecl :: = S standalone Eq (( ( yes | no ) ) | ( ( yes | no ) )) [CODESPLIT] private void scanXMLDeclOrTextDecl ( boolean scanningTextDecl ) throws IOException , JasperException { // scan decl scanXMLDeclOrTextDecl ( scanningTextDecl , fStrings ) ; fMarkupDepth -- ; // pseudo-attribute values String encodingPseudoAttr = fStrings [ 1 ] ; // set encoding on reader if ( encodingPseudoAttr != null ) { isEncodingSetInProlog = true ; encoding = encodingPseudoAttr ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans surrogates and append them to the specified buffer . <p > <strong > Note : < / strong > This assumes the current char has already been identified as a high surrogate . [CODESPLIT] private boolean scanSurrogates ( XMLStringBuffer buf ) throws IOException , JasperException { int high = scanChar ( ) ; int low = peekChar ( ) ; if ( ! XMLChar . isLowSurrogate ( low ) ) { err . jspError ( \"jsp.error.xml.invalidCharInContent\" , Integer . toString ( high , 16 ) ) ; return false ; } scanChar ( ) ; // convert surrogates to supplemental character int c = XMLChar . supplemental ( ( char ) high , ( char ) low ) ; // supplemental character must be a valid XML character if ( ! XMLChar . isValid ( c ) ) { err . jspError ( \"jsp.error.xml.invalidCharInContent\" , Integer . toString ( c , 16 ) ) ; return false ; } // fill in the buffer buf . append ( ( char ) high ) ; buf . append ( ( char ) low ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience function used in all XML scanners . [CODESPLIT] private void reportFatalError ( String msgId , String arg ) throws JasperException { err . jspError ( msgId , arg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a set of default repository links <p > This method calls { @link #fillRepoLinks ( ChannelInformation List String int String int LinkTarget ) } by using the baseName also as prefix and using a default { @code priorityOffset } of 10_000 < / p > [CODESPLIT] public static void fillRepoLinks ( final ChannelInformation channel , final List < MenuEntry > links , final String baseName , final int basePriority , final LinkTarget linkTemplate ) { fillRepoLinks ( channel , links , baseName , basePriority , baseName , 10_000 , linkTemplate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a set of default repository links [CODESPLIT] public static void fillRepoLinks ( final ChannelInformation channel , final List < MenuEntry > links , final String baseName , final int basePriority , final String prefix , final int priorityOffset , final LinkTarget linkTemplate ) { Objects . requireNonNull ( linkTemplate , \"'linkTemplate' must not be null\" ) ; fillRepoLinks ( channel , links , baseName , basePriority , prefix , priorityOffset , idOrName -> makeDefaultRepoLink ( linkTemplate , idOrName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a set of default repository links [CODESPLIT] public static void fillRepoLinks ( final ChannelInformation channel , final List < MenuEntry > links , final String baseName , final int basePriority , final String prefix , final int priorityOffset , final Function < String , LinkTarget > targetFunction ) { Objects . requireNonNull ( channel , \"'channel' must not be null\" ) ; Objects . requireNonNull ( links , \"'links' must not be null\" ) ; Objects . requireNonNull ( baseName , \"'baseName' must not be null\" ) ; Objects . requireNonNull ( prefix , \"'prefix' must not be null\" ) ; Objects . requireNonNull ( targetFunction , \"'targetFunction' must not be null\" ) ; links . add ( new MenuEntry ( baseName , basePriority , prefix + \" (by ID)\" , priorityOffset , targetFunction . apply ( channel . getId ( ) ) , Modifier . LINK , null ) ) ; int i = 1 ; for ( final String name : channel . getNames ( ) ) { final LinkTarget target = targetFunction . apply ( name ) ; if ( target != null ) { links . add ( new MenuEntry ( baseName , basePriority , String . format ( \"%s (name: %s)\" , prefix , name ) , priorityOffset + i , target , Modifier . LINK , null ) ) ; } i ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the real path for the specified context - relative virtual path . [CODESPLIT] public String getRealPath ( String path ) { if ( ! myResourceBaseURL . getProtocol ( ) . equals ( \"file\" ) ) return ( null ) ; if ( ! path . startsWith ( \"/\" ) ) return ( null ) ; try { return ( getResource ( path ) . getFile ( ) . replace ( ' ' , File . separatorChar ) ) ; } catch ( Throwable t ) { return ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a URL object of a resource that is mapped to the specified context - relative path . [CODESPLIT] public URL getResource ( String path ) throws MalformedURLException { if ( ! path . startsWith ( \"/\" ) ) throw new MalformedURLException ( \"Path '\" + path + \"' does not start with '/'\" ) ; URL url = new URL ( myResourceBaseURL , path . substring ( 1 ) ) ; InputStream is = null ; try { is = url . openStream ( ) ; } catch ( Throwable t ) { url = null ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Throwable t2 ) { // Ignore } } } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an InputStream allowing access to the resource at the specified context - relative path . [CODESPLIT] public InputStream getResourceAsStream ( String path ) { try { return ( getResource ( path ) . openStream ( ) ) ; } catch ( Throwable t ) { return ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the set of resource paths for the directory at the specified context path . [CODESPLIT] public Set < String > getResourcePaths ( String path ) { Set < String > thePaths = new HashSet < String > ( ) ; if ( ! path . endsWith ( \"/\" ) ) path += \"/\" ; String basePath = getRealPath ( path ) ; if ( basePath == null ) return ( thePaths ) ; File theBaseDir = new File ( basePath ) ; if ( ! theBaseDir . exists ( ) || ! theBaseDir . isDirectory ( ) ) return ( thePaths ) ; String theFiles [ ] = theBaseDir . list ( ) ; for ( int i = 0 ; i < theFiles . length ; i ++ ) { File testFile = new File ( basePath + File . separator + theFiles [ i ] ) ; if ( testFile . isFile ( ) ) thePaths . add ( path + theFiles [ i ] ) ; else if ( testFile . isDirectory ( ) ) thePaths . add ( path + theFiles [ i ] + \"/\" ) ; } return ( thePaths ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log the specified message and exception . [CODESPLIT] public void log ( String message , Throwable exception ) { myLogWriter . println ( message ) ; exception . printStackTrace ( myLogWriter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Adds the servlet with the given name description class name init parameters and loadOnStartup to this servlet context . [CODESPLIT] public void addServlet ( String servletName , String description , String className , Map < String , String > initParameters , int loadOnStartup ) { // Do nothing return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the filter with the given name description and class name to this servlet context . [CODESPLIT] public void addFilter ( String filterName , String description , String className , Map < String , String > initParameters ) { // Do nothing return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the filter chain with a single filter . This is equivalent to passing a single - member FilterOptions array to <code > updateFilters ( FilterOptions [] ) < / code > . [CODESPLIT] public void updateFilters ( FilterOptions filterOptions ) throws XZIOException { FilterOptions [ ] opts = new FilterOptions [ 1 ] ; opts [ 0 ] = filterOptions ; updateFilters ( opts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the filter chain with 1 - 4 filters . <p > Currently this cannot be used to update e . g . LZMA2 options in the middle of a XZ Block . Use <code > endBlock () < / code > to finish the current XZ Block before calling this function . The new filter chain will then be used for the next XZ Block . [CODESPLIT] public void updateFilters ( FilterOptions [ ] filterOptions ) throws XZIOException { if ( blockEncoder != null ) throw new UnsupportedOptionsException ( \"Changing filter options \" + \"in the middle of a XZ Block not implemented\" ) ; if ( filterOptions . length < 1 || filterOptions . length > 4 ) throw new UnsupportedOptionsException ( \"XZ filter chain must be 1-4 filters\" ) ; filtersSupportFlushing = true ; FilterEncoder [ ] newFilters = new FilterEncoder [ filterOptions . length ] ; for ( int i = 0 ; i < filterOptions . length ; ++ i ) { newFilters [ i ] = filterOptions [ i ] . getFilterEncoder ( ) ; filtersSupportFlushing &= newFilters [ i ] . supportsFlushing ( ) ; } RawCoder . validate ( newFilters ) ; filters = newFilters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an array of bytes to be compressed . The compressors tend to do internal buffering and thus the written data won t be readable from the compressed output immediately . Use <code > flush () < / code > to force everything written so far to be written to the underlaying output stream but be aware that flushing reduces compression ratio . [CODESPLIT] public void write ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( exception != null ) throw exception ; if ( finished ) throw new XZIOException ( \"Stream finished or closed\" ) ; try { if ( blockEncoder == null ) blockEncoder = new BlockOutputStream ( out , filters , check , arrayCache ) ; blockEncoder . write ( buf , off , len ) ; } catch ( IOException e ) { exception = e ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finishes the current XZ Block ( but not the whole XZ Stream ) . This doesn t flush the stream so it s possible that not all data will be decompressible from the output stream when this function returns . Call also <code > flush () < / code > if flushing is wanted in addition to finishing the current XZ Block . <p > If there is no unfinished Block open this function will do nothing . ( No empty XZ Block will be created . ) <p > This function can be useful for example to create random - accessible . xz files . <p > Starting a new XZ Block means that the encoder state is reset . Doing this very often will increase the size of the compressed file a lot ( more than plain <code > flush () < / code > would do ) . [CODESPLIT] public void endBlock ( ) throws IOException { if ( exception != null ) throw exception ; if ( finished ) throw new XZIOException ( \"Stream finished or closed\" ) ; // NOTE: Once there is threading with multiple Blocks, it's possible // that this function will be more like a barrier that returns // before the last Block has been finished. if ( blockEncoder != null ) { try { blockEncoder . finish ( ) ; index . add ( blockEncoder . getUnpaddedSize ( ) , blockEncoder . getUncompressedSize ( ) ) ; blockEncoder = null ; } catch ( IOException e ) { exception = e ; throw e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flushes the encoder and calls <code > out . flush () < / code > . All buffered pending data will then be decompressible from the output stream . <p > Calling this function very often may increase the compressed file size a lot . The filter chain options may affect the size increase too . For example with LZMA2 the HC4 match finder has smaller penalty with flushing than BT4 . <p > Some filters don t support flushing . If the filter chain has such a filter <code > flush () < / code > will call <code > endBlock () < / code > before flushing . [CODESPLIT] public void flush ( ) throws IOException { if ( exception != null ) throw exception ; if ( finished ) throw new XZIOException ( \"Stream finished or closed\" ) ; try { if ( blockEncoder != null ) { if ( filtersSupportFlushing ) { // This will eventually call out.flush() so // no need to do it here again. blockEncoder . flush ( ) ; } else { endBlock ( ) ; out . flush ( ) ; } } else { out . flush ( ) ; } } catch ( IOException e ) { exception = e ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finishes compression without closing the underlying stream . No more data can be written to this stream after finishing ( calling <code > write< / code > with an empty buffer is OK ) . <p > Repeated calls to <code > finish () < / code > do nothing unless an exception was thrown by this stream earlier . In that case the same exception is thrown again . <p > After finishing the stream may be closed normally with <code > close () < / code > . If the stream will be closed anyway there usually is no need to call <code > finish () < / code > separately . [CODESPLIT] public void finish ( ) throws IOException { if ( ! finished ) { // This checks for pending exceptions so we don't need to // worry about it here. endBlock ( ) ; try { index . encode ( out ) ; encodeStreamFooter ( ) ; } catch ( IOException e ) { exception = e ; throw e ; } // Set it to true only if everything goes fine. Setting it earlier // would cause repeated calls to finish() do nothing instead of // throwing an exception to indicate an earlier error. finished = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finishes compression and closes the underlying stream . The underlying stream <code > out< / code > is closed even if finishing fails . If both finishing and closing fail the exception thrown by <code > finish () < / code > is thrown and the exception from the failed <code > out . close () < / code > is lost . [CODESPLIT] public void close ( ) throws IOException { if ( out != null ) { // If finish() throws an exception, it stores the exception to // the variable \"exception\". So we can ignore the possible // exception here. try { finish ( ) ; } catch ( IOException e ) { } try { out . close ( ) ; } catch ( IOException e ) { // Remember the exception but only if there is no previous // pending exception. if ( exception == null ) exception = e ; } out = null ; } if ( exception != null ) throw exception ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the size of the LZ window buffer that needs to be allocated . [CODESPLIT] private static int getBufSize ( int dictSize , int extraSizeBefore , int extraSizeAfter , int matchLenMax ) { int keepSizeBefore = extraSizeBefore + dictSize ; int keepSizeAfter = extraSizeAfter + matchLenMax ; int reserveSize = Math . min ( dictSize / 2 + ( 256 << 10 ) , 512 << 20 ) ; return keepSizeBefore + keepSizeAfter + reserveSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets approximate memory usage of the LZEncoder base structure and the match finder as kibibytes . [CODESPLIT] public static int getMemoryUsage ( int dictSize , int extraSizeBefore , int extraSizeAfter , int matchLenMax , int mf ) { // Buffer size + a little extra int m = getBufSize ( dictSize , extraSizeBefore , extraSizeAfter , matchLenMax ) / 1024 + 10 ; switch ( mf ) { case MF_HC4 : m += HC4 . getMemoryUsage ( dictSize ) ; break ; case MF_BT4 : m += BT4 . getMemoryUsage ( dictSize ) ; break ; default : throw new IllegalArgumentException ( ) ; } return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new LZEncoder . <p > @param dictSize dictionary size [CODESPLIT] public static LZEncoder getInstance ( int dictSize , int extraSizeBefore , int extraSizeAfter , int niceLen , int matchLenMax , int mf , int depthLimit , ArrayCache arrayCache ) { switch ( mf ) { case MF_HC4 : return new HC4 ( dictSize , extraSizeBefore , extraSizeAfter , niceLen , matchLenMax , depthLimit , arrayCache ) ; case MF_BT4 : return new BT4 ( dictSize , extraSizeBefore , extraSizeAfter , niceLen , matchLenMax , depthLimit , arrayCache ) ; } throw new IllegalArgumentException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a preset dictionary . If a preset dictionary is wanted this function must be called immediately after creating the LZEncoder before any data has been encoded . [CODESPLIT] public void setPresetDict ( int dictSize , byte [ ] presetDict ) { assert ! isStarted ( ) ; assert writePos == 0 ; if ( presetDict != null ) { // If the preset dictionary buffer is bigger than the dictionary // size, copy only the tail of the preset dictionary. int copySize = Math . min ( presetDict . length , dictSize ) ; int offset = presetDict . length - copySize ; System . arraycopy ( presetDict , offset , buf , 0 , copySize ) ; writePos += copySize ; skip ( copySize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves data from the end of the buffer to the beginning discarding old data and making space for new input . [CODESPLIT] private void moveWindow ( ) { // Align the move to a multiple of 16 bytes. LZMA2 needs this // because it uses the lowest bits from readPos to get the // alignment of the uncompressed data. int moveOffset = ( readPos + 1 - keepSizeBefore ) & ~ 15 ; int moveSize = writePos - moveOffset ; System . arraycopy ( buf , moveOffset , buf , 0 , moveSize ) ; readPos -= moveOffset ; readLimit -= moveOffset ; writePos -= moveOffset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies new data into the LZEncoder s buffer . [CODESPLIT] public int fillWindow ( byte [ ] in , int off , int len ) { assert ! finishing ; // Move the sliding window if needed. if ( readPos >= bufSize - keepSizeAfter ) moveWindow ( ) ; // Try to fill the dictionary buffer. If it becomes full, // some of the input bytes may be left unused. if ( len > bufSize - writePos ) len = bufSize - writePos ; System . arraycopy ( in , off , buf , writePos , len ) ; writePos += len ; // Set the new readLimit but only if there's enough data to allow // encoding of at least one more byte. if ( writePos >= keepSizeAfter ) readLimit = writePos - keepSizeAfter ; processPendingBytes ( ) ; // Tell the caller how much input we actually copied into // the dictionary. return len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process pending bytes remaining from preset dictionary initialization or encoder flush operation . [CODESPLIT] private void processPendingBytes ( ) { // After flushing or setting a preset dictionary there will be // pending data that hasn't been ran through the match finder yet. // Run it through the match finder now if there is enough new data // available (readPos < readLimit) that the encoder may encode at // least one more input byte. This way we don't waste any time // looping in the match finder (and marking the same bytes as // pending again) if the application provides very little new data // per write call. if ( pendingSize > 0 && readPos < readLimit ) { readPos -= pendingSize ; int oldPendingSize = pendingSize ; pendingSize = 0 ; skip ( oldPendingSize ) ; assert pendingSize < oldPendingSize ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the length of a match at the given distance . [CODESPLIT] public int getMatchLen ( int dist , int lenLimit ) { int backPos = readPos - dist - 1 ; int len = 0 ; while ( len < lenLimit && buf [ readPos + len ] == buf [ backPos + len ] ) ++ len ; return len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the length of a match at the given distance and forward offset . [CODESPLIT] public int getMatchLen ( int forward , int dist , int lenLimit ) { int curPos = readPos + forward ; int backPos = curPos - dist - 1 ; int len = 0 ; while ( len < lenLimit && buf [ curPos + len ] == buf [ backPos + len ] ) ++ len ; return len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies that the matches returned by the match finder are valid . This is meant to be used in an assert statement . This is totally useless for actual encoding since match finder s results should naturally always be valid if it isn t broken . [CODESPLIT] public boolean verifyMatches ( Matches matches ) { int lenLimit = Math . min ( getAvail ( ) , matchLenMax ) ; for ( int i = 0 ; i < matches . count ; ++ i ) if ( getMatchLen ( matches . dist [ i ] , lenLimit ) != matches . len [ i ] ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves to the next byte checks if there is enough input available and returns the amount of input available . [CODESPLIT] int movePos ( int requiredForFlushing , int requiredForFinishing ) { assert requiredForFlushing >= requiredForFinishing ; ++ readPos ; int avail = writePos - readPos ; if ( avail < requiredForFlushing ) { if ( avail < requiredForFinishing || ! finishing ) { ++ pendingSize ; avail = 0 ; } } return avail ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Package - level access [CODESPLIT] void recycle ( ) { flushed = false ; closed = false ; out = null ; byteOut = null ; releaseCharBuffer ( ) ; response = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flush the output buffer to the underlying character stream without flushing the stream itself . This method is non - private only so that it may be invoked by PrintStream . [CODESPLIT] protected final void flushBuffer ( ) throws IOException { if ( bufferSize == 0 ) return ; flushed = true ; ensureOpen ( ) ; if ( buf . pos == buf . offset ) return ; initOut ( ) ; out . write ( buf . buf , buf . offset , buf . pos - buf . offset ) ; buf . pos = buf . offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discard the output buffer . [CODESPLIT] public final void clear ( ) throws IOException { if ( ( bufferSize == 0 ) && ( out != null ) ) // clear() is illegal after any unbuffered output (JSP.5.5) throw new IllegalStateException ( getLocalizeMessage ( \"jsp.error.ise_on_clear\" ) ) ; if ( flushed ) throw new IOException ( getLocalizeMessage ( \"jsp.error.attempt_to_clear_flushed_buffer\" ) ) ; ensureOpen ( ) ; if ( buf != null ) buf . pos = buf . offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flush the stream . [CODESPLIT] public void flush ( ) throws IOException { flushBuffer ( ) ; if ( out != null ) { out . flush ( ) ; } // START 6426898 else { // Set the default character encoding if there isn't any present, // see CR 6699416 response . setCharacterEncoding ( response . getCharacterEncoding ( ) ) ; // Cause response headers to be sent response . flushBuffer ( ) ; } // END 6426898 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the stream . [CODESPLIT] public void close ( ) throws IOException { if ( response == null || closed ) // multiple calls to close is OK return ; flush ( ) ; if ( out != null ) out . close ( ) ; out = null ; byteOut = null ; closed = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to write a String pre - encoded with the page encoding . [CODESPLIT] public void write ( boolean bytesOK , byte buf [ ] , String str ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 && bytesOK ) { initByteOut ( ) ; if ( implementsByteWriter ) { write ( buf , 0 , buf . length ) ; return ; } } write ( str ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a single character . [CODESPLIT] public void write ( int c ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 ) { initOut ( ) ; out . write ( c ) ; } else { if ( getRemaining ( ) == 0 ) if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; buf . buf [ buf . pos ++ ] = ( char ) c ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a portion of an array of characters . [CODESPLIT] public void write ( char cbuf [ ] , int off , int len ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 ) { initOut ( ) ; out . write ( cbuf , off , len ) ; return ; } if ( ( off < 0 ) || ( off > cbuf . length ) || ( len < 0 ) || ( ( off + len ) > cbuf . length ) || ( ( off + len ) < 0 ) ) { throw new IndexOutOfBoundsException ( ) ; } else if ( len == 0 ) { return ; } if ( len >= bufferSize ) { /* If the request length exceeds the size of the output buffer,\n               flush the buffer and then write the data directly.  In this\n               way buffered streams will cascade harmlessly. */ if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; initOut ( ) ; out . write ( cbuf , off , len ) ; return ; } int b = off , t = off + len ; while ( b < t ) { int d = min ( getRemaining ( ) , t - b ) ; System . arraycopy ( cbuf , b , buf . buf , buf . pos , d ) ; b += d ; buf . pos += d ; if ( getRemaining ( ) == 0 ) if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a portion of a String . [CODESPLIT] public void write ( String s , int off , int len ) throws IOException { ensureOpen ( ) ; if ( bufferSize == 0 ) { initOut ( ) ; out . write ( s , off , len ) ; return ; } int b = off , t = off + len ; while ( b < t ) { int d = min ( getRemaining ( ) , t - b ) ; s . getChars ( b , b + d , buf . buf , buf . pos ) ; b += d ; buf . pos += d ; if ( getRemaining ( ) == 0 ) if ( autoFlush ) flushBuffer ( ) ; else bufferOverflow ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "END PWC 6512276 [CODESPLIT] private void allocateCharBuffer ( ) { if ( bufferSize == 0 ) return ; if ( bufferSize > MAX_BUFFER_SIZE ) { buf = new CharBuffer ( new char [ bufferSize ] , 0 , bufferSize ) ; } else { buf = getCharBufferThreadLocalPool ( ) . allocate ( bufferSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lock and return { @link AutoCloseable } instance for unlocking Use with a <tt > try - with - resources< / tt > construct : [CODESPLIT] public static Locked lock ( final Lock lock ) { lock . lock ( ) ; return new Locked ( ) { @ Override public void close ( ) { lock . unlock ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Processes the given JSP parse error . [CODESPLIT] public void jspError ( String fname , int line , int column , String errMsg , Exception ex ) throws JasperException { throw new JasperException ( fname + \"(\" + line + \",\" + column + \")\" + \" \" + errMsg , ex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Processes the given javac compilation errors . [CODESPLIT] public void javacError ( JavacErrorDetail [ ] details ) throws JasperException { if ( details == null ) { return ; } Object [ ] args = null ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < details . length ; i ++ ) { if ( details [ i ] . getJspBeginLineNumber ( ) >= 0 ) { args = new Object [ ] { Integer . valueOf ( details [ i ] . getJspBeginLineNumber ( ) ) , details [ i ] . getJspFileName ( ) } ; buf . append ( Localizer . getMessage ( \"jsp.error.single.line.number\" , args ) ) ; buf . append ( \"\\n\" ) ; } buf . append ( Localizer . getMessage ( \"jsp.error.corresponding.servlet\" ) ) ; buf . append ( details [ i ] . getErrorMessage ( ) ) ; buf . append ( \"\\n\\n\" ) ; } if ( buf . length ( ) == 0 ) { throw new JasperException ( Localizer . getMessage ( \"jsp.error.nojdk\" ) ) ; } throw new JasperException ( Localizer . getMessage ( \"jsp.error.unable.compile\" ) + \"\\n\\n\" + buf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the given javac error report and exception . [CODESPLIT] public void javacError ( String errorReport , Exception exception ) throws JasperException { throw new JasperException ( Localizer . getMessage ( \"jsp.error.unable.compile\" ) , exception ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts all allocated arrays back to the underlying ArrayCache that haven t already been put there with a call to { [CODESPLIT] public void reset ( ) { if ( byteArrays != null ) { // Put the arrays to the cache in reverse order: the array that // was allocated first is returned last. synchronized ( byteArrays ) { for ( int i = byteArrays . size ( ) - 1 ; i >= 0 ; -- i ) arrayCache . putArray ( byteArrays . get ( i ) ) ; byteArrays . clear ( ) ; } synchronized ( intArrays ) { for ( int i = intArrays . size ( ) - 1 ; i >= 0 ; -- i ) arrayCache . putArray ( intArrays . get ( i ) ) ; intArrays . clear ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode ) { String errMsg = errCode ; try { errMsg = bundle . getString ( errCode ) ; } catch ( MissingResourceException e ) { } return errMsg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode , String arg ) { return getMessage ( errCode , new Object [ ] { arg } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode , String arg1 , String arg2 ) { return getMessage ( errCode , new Object [ ] { arg1 , arg2 } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the localized error message corresponding to the given error code . [CODESPLIT] public static String getMessage ( String errCode , Object [ ] args ) { String errMsg = errCode ; try { errMsg = bundle . getString ( errCode ) ; if ( args != null ) { MessageFormat formatter = new MessageFormat ( errMsg ) ; errMsg = formatter . format ( args ) ; } } catch ( MissingResourceException e ) { } return errMsg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a key from the aggregator fields [CODESPLIT] public List < String > makeKey ( final Map < MetaKey , String > metaData , final boolean requireAll ) { final List < String > result = new ArrayList <> ( this . fields . size ( ) ) ; for ( final MetaKey field : this . fields ) { final String value = metaData . get ( field ) ; if ( requireAll && value == null ) { return null ; } result . add ( value ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile the jsp file into equivalent servlet in java source [CODESPLIT] private void generateJava ( ) throws Exception { long t1 , t2 , t3 , t4 ; t1 = t2 = t3 = t4 = 0 ; if ( log . isLoggable ( Level . FINE ) ) { t1 = System . currentTimeMillis ( ) ; } // Setup page info area pageInfo = new PageInfo ( new BeanRepository ( ctxt . getClassLoader ( ) , errDispatcher ) , ctxt . getJspFile ( ) ) ; JspConfig jspConfig = options . getJspConfig ( ) ; JspProperty jspProperty = jspConfig . findJspProperty ( ctxt . getJspFile ( ) ) ; /*\n         * If the current uri is matched by a pattern specified in\n         * a jsp-property-group in web.xml, initialize pageInfo with\n         * those properties.\n         */ pageInfo . setELIgnored ( JspUtil . booleanValue ( jspProperty . isELIgnored ( ) ) ) ; pageInfo . setScriptingInvalid ( JspUtil . booleanValue ( jspProperty . isScriptingInvalid ( ) ) ) ; pageInfo . setTrimDirectiveWhitespaces ( JspUtil . booleanValue ( jspProperty . getTrimSpaces ( ) ) ) ; pageInfo . setDeferredSyntaxAllowedAsLiteral ( JspUtil . booleanValue ( jspProperty . getPoundAllowed ( ) ) ) ; pageInfo . setErrorOnUndeclaredNamespace ( JspUtil . booleanValue ( jspProperty . errorOnUndeclaredNamespace ( ) ) ) ; if ( jspProperty . getIncludePrelude ( ) != null ) { pageInfo . setIncludePrelude ( jspProperty . getIncludePrelude ( ) ) ; } if ( jspProperty . getIncludeCoda ( ) != null ) { pageInfo . setIncludeCoda ( jspProperty . getIncludeCoda ( ) ) ; } if ( options . isDefaultBufferNone ( ) && pageInfo . getBufferValue ( ) == null ) { // Set to unbuffered if not specified explicitly pageInfo . setBuffer ( 0 ) ; } String javaFileName = ctxt . getServletJavaFileName ( ) ; ServletWriter writer = null ; try { // Setup the ServletWriter Writer javaWriter = javaCompiler . getJavaWriter ( javaFileName , ctxt . getOptions ( ) . getJavaEncoding ( ) ) ; writer = new ServletWriter ( new PrintWriter ( javaWriter ) ) ; ctxt . setWriter ( writer ) ; // Reset the temporary variable counter for the generator. JspUtil . resetTemporaryVariableName ( ) ; // Parse the file ParserController parserCtl = new ParserController ( ctxt , this ) ; pageNodes = parserCtl . parse ( ctxt . getJspFile ( ) ) ; if ( ctxt . isPrototypeMode ( ) ) { // generate prototype .java file for the tag file Generator . generate ( writer , this , pageNodes ) ; writer . close ( ) ; writer = null ; return ; } // Validate and process attributes Validator . validate ( this , pageNodes ) ; if ( log . isLoggable ( Level . FINE ) ) { t2 = System . currentTimeMillis ( ) ; } // Collect page info Collector . collect ( this , pageNodes ) ; // Compile (if necessary) and load the tag files referenced in // this compilation unit. tfp = new TagFileProcessor ( ) ; tfp . loadTagFiles ( this , pageNodes ) ; if ( log . isLoggable ( Level . FINE ) ) { t3 = System . currentTimeMillis ( ) ; } // Determine which custom tag needs to declare which scripting vars ScriptingVariabler . set ( pageNodes , errDispatcher ) ; // Optimizations by Tag Plugins TagPluginManager tagPluginManager = options . getTagPluginManager ( ) ; tagPluginManager . apply ( pageNodes , errDispatcher , pageInfo ) ; // Optimization: concatenate contiguous template texts. TextOptimizer . concatenate ( this , pageNodes ) ; // Generate static function mapper codes. ELFunctionMapper . map ( this , pageNodes ) ; // generate servlet .java file Generator . generate ( writer , this , pageNodes ) ; writer . close ( ) ; writer = null ; // The writer is only used during the compile, dereference // it in the JspCompilationContext when done to allow it // to be GC'd and save memory. ctxt . setWriter ( null ) ; if ( log . isLoggable ( Level . FINE ) ) { t4 = System . currentTimeMillis ( ) ; log . fine ( \"Generated \" + javaFileName + \" total=\" + ( t4 - t1 ) + \" generate=\" + ( t4 - t3 ) + \" validate=\" + ( t2 - t1 ) ) ; } } catch ( Exception e ) { if ( writer != null ) { try { writer . close ( ) ; writer = null ; } catch ( Exception e1 ) { // do nothing } } // Remove the generated .java file javaCompiler . doJavaFile ( false ) ; throw e ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( Exception e2 ) { // do nothing } } } // JSR45 Support if ( ! options . isSmapSuppressed ( ) ) { smapUtil . generateSmap ( pageNodes ) ; } // If any proto type .java and .class files was generated, // the prototype .java may have been replaced by the current // compilation (if the tag file is self referencing), but the // .class file need to be removed, to make sure that javac would // generate .class again from the new .java file just generated. tfp . removeProtoTypeFiles ( ctxt . getClassFileName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile the servlet from . java file to . class file [CODESPLIT] private void generateClass ( ) throws FileNotFoundException , JasperException , Exception { long t1 = 0 ; if ( log . isLoggable ( Level . FINE ) ) { t1 = System . currentTimeMillis ( ) ; } String javaFileName = ctxt . getServletJavaFileName ( ) ; setJavaCompilerOptions ( ) ; // Start java compilation JavacErrorDetail [ ] javacErrors = javaCompiler . compile ( ctxt . getFullClassName ( ) , pageNodes ) ; if ( javacErrors != null ) { // If there are errors, always generate java files to disk. javaCompiler . doJavaFile ( true ) ; log . severe ( \"Error compiling file: \" + javaFileName ) ; errDispatcher . javacError ( javacErrors ) ; } if ( log . isLoggable ( Level . FINE ) ) { long t2 = System . currentTimeMillis ( ) ; log . fine ( \"Compiled \" + javaFileName + \" \" + ( t2 - t1 ) + \"ms\" ) ; } // Save or delete the generated Java files, depending on the // value of \"keepgenerated\" attribute javaCompiler . doJavaFile ( ctxt . keepGenerated ( ) ) ; // JSR45 Support if ( ! ctxt . isPrototypeMode ( ) && ! options . isSmapSuppressed ( ) ) { smapUtil . installSmap ( ) ; } // START CR 6373479 if ( jsw != null && jsw . getServletClassLastModifiedTime ( ) <= 0 ) { jsw . setServletClassLastModifiedTime ( javaCompiler . getClassLastModified ( ) ) ; } // END CR 6373479 if ( options . getSaveBytecode ( ) ) { javaCompiler . saveClassFile ( ctxt . getFullClassName ( ) , ctxt . getClassFileName ( ) ) ; } // On some systems, due to file caching, the time stamp for the updated // JSP file may actually be greater than that of the newly created byte // codes in the cache.  In such cases, adjust the cache time stamp to // JSP page time, to avoid unnecessary recompilations. ctxt . getRuntimeContext ( ) . adjustBytecodeTime ( ctxt . getFullClassName ( ) , jspModTime ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compile the jsp file from the current engine context . As an side - effect tag files that are referenced by this page are also compiled . [CODESPLIT] public void compile ( boolean compileClass ) throws FileNotFoundException , JasperException , Exception { try { // Create the output directory for the generated files // Always try and create the directory tree, in case the generated // directories were deleted after the server was started. ctxt . makeOutputDir ( ctxt . getOutputDir ( ) ) ; // If errDispatcher is nulled from a previous compilation of the // same page, instantiate one here. if ( errDispatcher == null ) { errDispatcher = new ErrorDispatcher ( jspcMode ) ; } generateJava ( ) ; if ( compileClass ) { generateClass ( ) ; } else { // If called from jspc to only compile to .java files, // make sure that .java files are written to disk. javaCompiler . doJavaFile ( ctxt . keepGenerated ( ) ) ; } } finally { if ( tfp != null ) { tfp . removeProtoTypeFiles ( null ) ; } javaCompiler . release ( ) ; // Make sure these object which are only used during the // generation and compilation of the JSP page get // dereferenced so that they can be GC'd and reduce the // memory footprint. tfp = null ; errDispatcher = null ; if ( ! jspcMode ) { pageInfo = null ; } pageNodes = null ; if ( ctxt . getWriter ( ) != null ) { ctxt . getWriter ( ) . close ( ) ; ctxt . setWriter ( null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a compilation is necessary by checking the time stamp of the JSP page with that of the corresponding . class or . java file . If the page has dependencies the check is also extended to its dependeants and so on . This method can by overidden by a subclasses of Compiler . [CODESPLIT] public boolean isOutDated ( boolean checkClass ) { String jsp = ctxt . getJspFile ( ) ; if ( jsw != null && ( ctxt . getOptions ( ) . getModificationTestInterval ( ) > 0 ) ) { if ( jsw . getLastModificationTest ( ) + ( ctxt . getOptions ( ) . getModificationTestInterval ( ) * 1000 ) > System . currentTimeMillis ( ) ) { return false ; } else { jsw . setLastModificationTest ( System . currentTimeMillis ( ) ) ; } } long jspRealLastModified = 0 ; // START PWC 6468930 File targetFile ; if ( checkClass ) { targetFile = new File ( ctxt . getClassFileName ( ) ) ; } else { targetFile = new File ( ctxt . getServletJavaFileName ( ) ) ; } // Get the target file's last modified time. File.lastModified() // returns 0 if the file does not exist. long targetLastModified = targetFile . lastModified ( ) ; // Check cached class file if ( checkClass ) { JspRuntimeContext rtctxt = ctxt . getRuntimeContext ( ) ; String className = ctxt . getFullClassName ( ) ; long cachedTime = rtctxt . getBytecodeBirthTime ( className ) ; if ( cachedTime > targetLastModified ) { targetLastModified = cachedTime ; } else { // Remove from cache, since the bytecodes from the file is more // current, so that JasperLoader won't load the cached version rtctxt . setBytecode ( className , null ) ; } } if ( targetLastModified == 0L ) return true ; // Check if the jsp exists in the filesystem (instead of a jar // or a remote location). If yes, then do a File.lastModified() // to determine its last modified time. This is more performant  // (fewer stat calls) than the ctxt.getResource() followed by  // openConnection(). However, it only works for file system jsps. // If the file has indeed changed, then need to call URL.OpenConnection()  // so that the cache loads the latest jsp file if ( jsw != null ) { File jspFile = jsw . getJspFile ( ) ; if ( jspFile != null ) { jspRealLastModified = jspFile . lastModified ( ) ; } } if ( jspRealLastModified == 0 || targetLastModified < jspRealLastModified ) { // END PWC 6468930 try { URL jspUrl = ctxt . getResource ( jsp ) ; if ( jspUrl == null ) { ctxt . incrementRemoved ( ) ; return false ; } URLConnection uc = jspUrl . openConnection ( ) ; if ( uc instanceof JarURLConnection ) { jspRealLastModified = ( ( JarURLConnection ) uc ) . getJarEntry ( ) . getTime ( ) ; } else { jspRealLastModified = uc . getLastModified ( ) ; } uc . getInputStream ( ) . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return true ; } // START PWC 6468930 } // END PWC 6468930 /* PWC 6468930\n        long targetLastModified = 0;\n        File targetFile;\n        \n        if( checkClass ) {\n            targetFile = new File(ctxt.getClassFileName());\n        } else {\n            targetFile = new File(ctxt.getServletJavaFileName());\n        }\n        \n        if (!targetFile.exists()) {\n            return true;\n        }\n\n        targetLastModified = targetFile.lastModified();\n        */ if ( checkClass && jsw != null ) { jsw . setServletClassLastModifiedTime ( targetLastModified ) ; } if ( targetLastModified < jspRealLastModified ) { // Remember JSP mod time jspModTime = jspRealLastModified ; if ( log . isLoggable ( Level . FINE ) ) { log . fine ( \"Compiler: outdated: \" + targetFile + \" \" + targetLastModified ) ; } return true ; } // determine if source dependent files (e.g. includes using include // directives) have been changed. if ( jsw == null ) { return false ; } List < String > depends = jsw . getDependants ( ) ; if ( depends == null ) { return false ; } for ( String include : depends ) { try { URL includeUrl = ctxt . getResource ( include ) ; if ( includeUrl == null ) { return true ; } URLConnection includeUconn = includeUrl . openConnection ( ) ; long includeLastModified = 0 ; if ( includeUconn instanceof JarURLConnection ) { includeLastModified = ( ( JarURLConnection ) includeUconn ) . getJarEntry ( ) . getTime ( ) ; } else { includeLastModified = includeUconn . getLastModified ( ) ; } includeUconn . getInputStream ( ) . close ( ) ; if ( includeLastModified > targetLastModified ) { // START GlassFish 750 if ( include . endsWith ( \".tld\" ) ) { ctxt . clearTaglibs ( ) ; ctxt . clearTagFileJarUrls ( ) ; } // END GlassFish 750 return true ; } } catch ( Exception e ) { e . printStackTrace ( ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove generated files [CODESPLIT] public void removeGeneratedFiles ( ) { try { String classFileName = ctxt . getClassFileName ( ) ; if ( classFileName != null ) { File classFile = new File ( classFileName ) ; if ( log . isLoggable ( Level . FINE ) ) log . fine ( \"Deleting \" + classFile ) ; classFile . delete ( ) ; } } catch ( Exception e ) { // Remove as much as possible, ignore possible exceptions } try { String javaFileName = ctxt . getServletJavaFileName ( ) ; if ( javaFileName != null ) { File javaFile = new File ( javaFileName ) ; if ( log . isLoggable ( Level . FINE ) ) log . fine ( \"Deleting \" + javaFile ) ; javaFile . delete ( ) ; } } catch ( Exception e ) { // Remove as much as possible, ignore possible exceptions } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an instance of JavaCompiler . If Running with JDK 6 use a Jsr199JavaCompiler that supports JSR199 else if eclipse s JDT compiler is available use that . The default is to use javac from ant . [CODESPLIT] private void initJavaCompiler ( ) throws JasperException { boolean disablejsr199 = Boolean . TRUE . toString ( ) . equals ( System . getProperty ( \"org.apache.jasper.compiler.disablejsr199\" ) ) ; Double version = Double . valueOf ( System . getProperty ( \"java.specification.version\" ) ) ; if ( ! disablejsr199 && ( version >= 1.6 || getClassFor ( \"javax.tools.Tool\" ) != null ) ) { // JDK 6 or bundled with jsr199 compiler javaCompiler = new Jsr199JavaCompiler ( ) ; } else { Class c = getClassFor ( \"org.eclipse.jdt.internal.compiler.Compiler\" ) ; if ( c != null ) { c = getClassFor ( \"org.apache.jasper.compiler.JDTJavaCompiler\" ) ; if ( c != null ) { try { javaCompiler = ( JavaCompiler ) c . newInstance ( ) ; } catch ( Exception ex ) { } } } } if ( javaCompiler == null ) { Class c = getClassFor ( \"org.apache.tools.ant.taskdefs.Javac\" ) ; if ( c != null ) { c = getClassFor ( \"org.apache.jasper.compiler.AntJavaCompiler\" ) ; if ( c != null ) { try { javaCompiler = ( JavaCompiler ) c . newInstance ( ) ; } catch ( Exception ex ) { } } } } if ( javaCompiler == null ) { errDispatcher . jspError ( \"jsp.error.nojavac\" ) ; } javaCompiler . init ( ctxt , errDispatcher , jspcMode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the path refers to a jar file in WEB - INF and is a system jar . [CODESPLIT] private boolean systemJarInWebinf ( String path ) { if ( path . indexOf ( \"/WEB-INF/\" ) < 0 ) { return false ; } Boolean useMyFaces = ( Boolean ) ctxt . getServletContext ( ) . getAttribute ( \"com.sun.faces.useMyFaces\" ) ; if ( useMyFaces == null || ! useMyFaces ) { for ( String jar : systemJsfJars ) { if ( path . indexOf ( jar ) > 0 ) { return true ; } } } for ( String jar : systemJars ) { if ( path . indexOf ( jar ) > 0 ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode into an array of bytes . <p > This calls <code > in . read ( buf off len ) < / code > and defilters the returned data . [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; int size ; try { size = in . read ( buf , off , len ) ; } catch ( IOException e ) { exception = e ; throw e ; } if ( size == - 1 ) return - 1 ; delta . decode ( buf , off , size ) ; return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls <code > in . available () < / code > . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; return in . available ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Single quote and escape a character [CODESPLIT] static String quote ( char c ) { StringBuilder b = new StringBuilder ( ) ; b . append ( ' ' ) ; if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else if ( c == ' ' ) b . append ( ' ' ) . append ( ' ' ) ; else b . append ( c ) ; b . append ( ' ' ) ; return b . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates declarations . This includes info of the page directive and scriptlet declarations . [CODESPLIT] private void generateDeclarations ( Node . Nodes page ) throws JasperException { class DeclarationVisitor extends Node . Visitor { private boolean getServletInfoGenerated = false ; /*\n             * Generates getServletInfo() method that returns the value of the\n             * page directive's 'info' attribute, if present.\n             *\n             * The Validator has already ensured that if the translation unit\n             * contains more than one page directive with an 'info' attribute,\n             * their values match.\n             */ public void visit ( Node . PageDirective n ) throws JasperException { if ( getServletInfoGenerated ) { return ; } String info = n . getAttributeValue ( \"info\" ) ; if ( info == null ) return ; getServletInfoGenerated = true ; out . printil ( \"public String getServletInfo() {\" ) ; out . pushIndent ( ) ; out . printin ( \"return \" ) ; out . print ( quote ( info ) ) ; out . println ( \";\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; } public void visit ( Node . Declaration n ) throws JasperException { n . setBeginJavaLine ( out . getJavaLine ( ) ) ; out . printMultiLn ( n . getText ( ) ) ; out . println ( ) ; n . setEndJavaLine ( out . getJavaLine ( ) ) ; } // Custom Tags may contain declarations from tag plugins. public void visit ( Node . CustomTag n ) throws JasperException { if ( n . useTagPlugin ( ) ) { if ( n . getAtSTag ( ) != null ) { n . getAtSTag ( ) . visit ( this ) ; } visitBody ( n ) ; if ( n . getAtETag ( ) != null ) { n . getAtETag ( ) . visit ( this ) ; } } else { visitBody ( n ) ; } } } out . println ( ) ; page . visit ( new DeclarationVisitor ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles list of tag handler pool names . [CODESPLIT] private void compileTagHandlerPoolList ( Node . Nodes page ) throws JasperException { class TagHandlerPoolVisitor extends Node . Visitor { private Set < String > names = new HashSet < String > ( ) ; /*\n             * Constructor\n             *\n             * @param v Set of tag handler pool names to populate\n             */ TagHandlerPoolVisitor ( Set < String > v ) { names = v ; } /*\n             * Gets the name of the tag handler pool for the given custom tag\n             * and adds it to the list of tag handler pool names unless it is\n             * already contained in it.\n             */ public void visit ( Node . CustomTag n ) throws JasperException { if ( ! n . implementsSimpleTag ( ) ) { String name = createTagHandlerPoolName ( n . getPrefix ( ) , n . getLocalName ( ) , n . getAttributes ( ) , n . hasEmptyBody ( ) ) ; n . setTagHandlerPoolName ( name ) ; if ( ! names . contains ( name ) ) { names . add ( name ) ; } } visitBody ( n ) ; } /*\n             * Creates the name of the tag handler pool whose tag handlers may\n             * be (re)used to service this action.\n             *\n             * @return The name of the tag handler pool\n             */ private String createTagHandlerPoolName ( String prefix , String shortName , Attributes attrs , boolean hasEmptyBody ) { String poolName = null ; poolName = \"_jspx_tagPool_\" + prefix + \"_\" + shortName ; if ( attrs != null ) { String [ ] attrNames = new String [ attrs . getLength ( ) ] ; for ( int i = 0 ; i < attrNames . length ; i ++ ) { attrNames [ i ] = attrs . getQName ( i ) ; } Arrays . sort ( attrNames , Collections . reverseOrder ( ) ) ; for ( int i = 0 ; i < attrNames . length ; i ++ ) { poolName = poolName + \"_\" + attrNames [ i ] ; } } if ( hasEmptyBody ) { poolName = poolName + \"_nobody\" ; } return JspUtil . makeXmlJavaIdentifier ( poolName ) ; } } page . visit ( new TagHandlerPoolVisitor ( tagHandlerPoolNames ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the _jspInit () method for instantiating the tag handler pools . For tag file _jspInit has to be invoked manually and the ServletConfig object explicitly passed . [CODESPLIT] private void generateTagHandlerInit ( ) { if ( ! isPoolingEnabled || tagHandlerPoolNames . isEmpty ( ) ) { return ; } if ( ctxt . isTagFile ( ) ) { out . printil ( \"private void _jspInit(ServletConfig config) {\" ) ; } else { out . printil ( \"public void _jspInit() {\" ) ; } out . pushIndent ( ) ; for ( String tagHandlerPoolName : tagHandlerPoolNames ) { out . printin ( tagHandlerPoolName ) ; out . print ( \" = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(\" ) ; if ( ctxt . isTagFile ( ) ) { out . print ( \"config\" ) ; } else { out . print ( \"getServletConfig()\" ) ; } out . println ( \");\" ) ; } out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the _jspDestroy () method which is responsible for calling the release () method on every tag handler in any of the tag handler pools . [CODESPLIT] private void generateTagHandlerDestroy ( ) { if ( ! isPoolingEnabled || tagHandlerPoolNames . isEmpty ( ) ) { return ; } out . printil ( \"public void _jspDestroy() {\" ) ; out . pushIndent ( ) ; for ( String tagHandlerPoolName : tagHandlerPoolNames ) { out . printin ( tagHandlerPoolName ) ; out . println ( \".release();\" ) ; } out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate preamble package name ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreamblePackage ( String packageName ) throws JasperException { if ( ! \"\" . equals ( packageName ) && packageName != null ) { out . printil ( \"package \" + packageName + \";\" ) ; out . println ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate preamble imports ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleImports ( ) throws JasperException { Iterator < String > iter = pageInfo . getImports ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { out . printin ( \"import \" ) ; out . print ( iter . next ( ) ) ; out . println ( \";\" ) ; } out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generation of static initializers in preamble . For example dependant list el function map prefix map . ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleStaticInitializers ( ) throws JasperException { out . printil ( \"private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();\" ) ; out . println ( ) ; // Static data for getDependants() out . printil ( \"private static java.util.List<String> _jspx_dependants;\" ) ; out . println ( ) ; List < String > dependants = pageInfo . getDependants ( ) ; Iterator < String > iter = dependants . iterator ( ) ; if ( ! dependants . isEmpty ( ) ) { out . printil ( \"static {\" ) ; out . pushIndent ( ) ; out . printin ( \"_jspx_dependants = new java.util.ArrayList<String>(\" ) ; out . print ( \"\" + dependants . size ( ) ) ; out . println ( \");\" ) ; while ( iter . hasNext ( ) ) { out . printin ( \"_jspx_dependants.add(\\\"\" ) ; out . print ( iter . next ( ) ) ; out . println ( \"\\\");\" ) ; } out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; } // Codes to support genStringAsByteArray option // Generate a static variable for the initial response encoding if ( genBytes ) { // first get the respons encoding String contentType = pageInfo . getContentType ( ) ; String encoding = \"ISO-8859-1\" ; int i = contentType . indexOf ( \"charset=\" ) ; if ( i > 0 ) encoding = contentType . substring ( i + 8 ) ; // Make sure the encoding is supported // Assume that this can be determined at compile time try { \"testing\" . getBytes ( encoding ) ; out . printin ( \"private static final String _jspx_encoding = \" ) ; out . print ( quote ( encoding ) ) ; out . println ( \";\" ) ; out . printil ( \"private boolean _jspx_gen_bytes = true;\" ) ; out . printil ( \"private boolean _jspx_encoding_tested;\" ) ; } catch ( java . io . UnsupportedEncodingException ex ) { genBytes = false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declare tag handler pools ( tags of the same type and with the same attribute set share the same tag handler pool ) ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleClassVariableDeclarations ( String className ) throws JasperException { if ( isPoolingEnabled ) { if ( ! tagHandlerPoolNames . isEmpty ( ) ) { for ( String tagHandlerPoolName : tagHandlerPoolNames ) { out . printil ( \"private org.apache.jasper.runtime.TagHandlerPool \" + tagHandlerPoolName + \";\" ) ; } out . println ( ) ; } } out . printil ( \"private org.glassfish.jsp.api.ResourceInjector \" + \"_jspx_resourceInjector;\" ) ; out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declare general - purpose methods ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void genPreambleMethods ( ) throws JasperException { // Method used to get compile time file dependencies out . printil ( \"public java.util.List<String> getDependants() {\" ) ; out . pushIndent ( ) ; out . printil ( \"return _jspx_dependants;\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; // Method to get bytes from String if ( genBytes ) { out . printil ( \"private static byte[] _jspx_getBytes(String s) {\" ) ; out . pushIndent ( ) ; out . printil ( \"try {\" ) ; out . pushIndent ( ) ; out . printil ( \"return s.getBytes(_jspx_encoding);\" ) ; out . popIndent ( ) ; out . printil ( \"} catch (java.io.UnsupportedEncodingException ex) {\" ) ; out . printil ( \"}\" ) ; out . printil ( \"return null;\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; // Generate code to see if the response encoding has been set // differently from the encoding declared in the page directive. // Note that we only need to do the test once.  The assumption // is that the encoding cannot be changed once some data has been // written. out . printil ( \"private boolean _jspx_same_encoding(String encoding) {\" ) ; out . pushIndent ( ) ; out . printil ( \"if (! _jspx_encoding_tested) {\" ) ; out . pushIndent ( ) ; out . printil ( \"_jspx_gen_bytes = _jspx_encoding.equals(encoding);\" ) ; out . printil ( \"_jspx_encoding_tested = true;\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . printil ( \"return _jspx_gen_bytes;\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; } generateTagHandlerInit ( ) ; generateTagHandlerDestroy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the beginning of the static portion of the servlet . [CODESPLIT] private void generatePreamble ( Node . Nodes page ) throws JasperException { String servletPackageName = ctxt . getServletPackageName ( ) ; String servletClassName = ctxt . getServletClassName ( ) ; String serviceMethodName = Constants . SERVICE_METHOD_NAME ; // First the package name: genPreamblePackage ( servletPackageName ) ; // Generate imports genPreambleImports ( ) ; // Generate class declaration out . printin ( \"public final class \" ) ; out . print ( servletClassName ) ; out . print ( \" extends \" ) ; out . println ( pageInfo . getExtends ( ) ) ; out . printin ( \"    implements org.apache.jasper.runtime.JspSourceDependent\" ) ; if ( ! pageInfo . isThreadSafe ( ) ) { out . println ( \",\" ) ; out . printin ( \"                 SingleThreadModel\" ) ; } out . println ( \" {\" ) ; out . pushIndent ( ) ; // Class body begins here generateDeclarations ( page ) ; // Static initializations here genPreambleStaticInitializers ( ) ; // Class variable declarations genPreambleClassVariableDeclarations ( servletClassName ) ; // Constructor //\tgenerateConstructor(className); // Methods here genPreambleMethods ( ) ; // Now the service method out . printin ( \"public void \" ) ; out . print ( serviceMethodName ) ; out . println ( \"(HttpServletRequest request, HttpServletResponse response)\" ) ; out . println ( \"        throws java.io.IOException, ServletException {\" ) ; out . pushIndent ( ) ; out . println ( ) ; // Local variable declarations out . printil ( \"PageContext pageContext = null;\" ) ; if ( pageInfo . isSession ( ) ) out . printil ( \"HttpSession session = null;\" ) ; if ( pageInfo . isErrorPage ( ) ) { out . printil ( \"Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);\" ) ; out . printil ( \"if (exception != null) {\" ) ; out . pushIndent ( ) ; out . printil ( \"response.setStatus((Integer)request.getAttribute(\\\"javax.servlet.error.status_code\\\"));\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; } out . printil ( \"ServletContext application = null;\" ) ; out . printil ( \"ServletConfig config = null;\" ) ; out . printil ( \"JspWriter out = null;\" ) ; out . printil ( \"Object page = this;\" ) ; out . printil ( \"JspWriter _jspx_out = null;\" ) ; out . printil ( \"PageContext _jspx_page_context = null;\" ) ; out . println ( ) ; out . printil ( \"try {\" ) ; out . pushIndent ( ) ; out . printin ( \"response.setContentType(\" ) ; out . print ( quote ( pageInfo . getContentType ( ) ) ) ; out . println ( \");\" ) ; if ( ctxt . getOptions ( ) . isXpoweredBy ( ) ) { out . printil ( \"response.setHeader(\\\"X-Powered-By\\\", \\\"\" + Constants . JSP_NAME + \"\\\");\" ) ; } out . printil ( \"pageContext = _jspxFactory.getPageContext(this, request, response,\" ) ; out . printin ( \"\\t\\t\\t\" ) ; out . print ( quote ( pageInfo . getErrorPage ( ) ) ) ; out . print ( \", \" + pageInfo . isSession ( ) ) ; out . print ( \", \" + pageInfo . getBuffer ( ) ) ; out . print ( \", \" + pageInfo . isAutoFlush ( ) ) ; out . println ( \");\" ) ; out . printil ( \"_jspx_page_context = pageContext;\" ) ; out . printil ( \"application = pageContext.getServletContext();\" ) ; out . printil ( \"config = pageContext.getServletConfig();\" ) ; if ( pageInfo . isSession ( ) ) out . printil ( \"session = pageContext.getSession();\" ) ; out . printil ( \"out = pageContext.getOut();\" ) ; out . printil ( \"_jspx_out = out;\" ) ; out . printil ( \"_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute(\\\"com.sun.appserv.jsp.resource.injector\\\");\" ) ; out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates an XML Prolog which includes an XML declaration and an XML doctype declaration . [CODESPLIT] private void generateXmlProlog ( Node . Nodes page ) { /*\n         * An XML declaration is generated under the following conditions:\n         *\n         * - 'omit-xml-declaration' attribute of <jsp:output> action is set to\n         *   \"no\" or \"false\"\n         * - JSP document without a <jsp:root>\n         */ String omitXmlDecl = pageInfo . getOmitXmlDecl ( ) ; if ( ( omitXmlDecl != null && ! JspUtil . booleanValue ( omitXmlDecl ) ) || ( omitXmlDecl == null && page . getRoot ( ) . isXmlSyntax ( ) && ! pageInfo . hasJspRoot ( ) && ! ctxt . isTagFile ( ) ) ) { String cType = pageInfo . getContentType ( ) ; String charSet = cType . substring ( cType . indexOf ( \"charset=\" ) + 8 ) ; out . printil ( \"out.write(\\\"<?xml version=\\\\\\\"1.0\\\\\\\" encoding=\\\\\\\"\" + charSet + \"\\\\\\\"?>\\\\n\\\");\" ) ; } /*\n         * Output a DOCTYPE declaration if the doctype-root-element appears.\n         * If doctype-public appears:\n         *     <!DOCTYPE name PUBLIC \"doctypePublic\" \"doctypeSystem\">\n         * else\n         *     <!DOCTYPE name SYSTEM \"doctypeSystem\" >\n         */ String doctypeName = pageInfo . getDoctypeName ( ) ; if ( doctypeName != null ) { String doctypePublic = pageInfo . getDoctypePublic ( ) ; String doctypeSystem = pageInfo . getDoctypeSystem ( ) ; out . printin ( \"out.write(\\\"<!DOCTYPE \" ) ; out . print ( doctypeName ) ; if ( doctypePublic == null ) { out . print ( \" SYSTEM \\\\\\\"\" ) ; } else { out . print ( \" PUBLIC \\\\\\\"\" ) ; out . print ( doctypePublic ) ; out . print ( \"\\\\\\\" \\\\\\\"\" ) ; } out . print ( doctypeSystem ) ; out . println ( \"\\\\\\\">\\\\n\\\");\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Generates the constructor . ( shared by servlet and tag handler preamble generation ) [CODESPLIT] private void generateConstructor ( String className ) { out . printil ( \"public \" + className + \"() {\" ) ; out . printil ( \"}\" ) ; out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Common part of postamble shared by both servlets and tag files . [CODESPLIT] private void genCommonPostamble ( ) { // Append any methods that were generated in the buffer. for ( int i = 0 ; i < methodsBuffered . size ( ) ; i ++ ) { GenBuffer methodBuffer = methodsBuffered . get ( i ) ; methodBuffer . adjustJavaLines ( out . getJavaLine ( ) - 1 ) ; out . printMultiLn ( methodBuffer . toString ( ) ) ; } // Append the helper class if ( fragmentHelperClass . isUsed ( ) ) { fragmentHelperClass . generatePostamble ( ) ; fragmentHelperClass . adjustJavaLines ( out . getJavaLine ( ) - 1 ) ; out . printMultiLn ( fragmentHelperClass . toString ( ) ) ; } // Append char array declarations if ( arrayBuffer != null ) { out . printMultiLn ( arrayBuffer . toString ( ) ) ; } // Close the class definition out . popIndent ( ) ; out . printil ( \"}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the ending part of the static portion of the servlet . [CODESPLIT] private void generatePostamble ( Node . Nodes page ) { out . popIndent ( ) ; out . printil ( \"} catch (Throwable t) {\" ) ; out . pushIndent ( ) ; out . printil ( \"if (!(t instanceof SkipPageException)){\" ) ; out . pushIndent ( ) ; out . printil ( \"out = _jspx_out;\" ) ; out . printil ( \"if (out != null && out.getBufferSize() != 0)\" ) ; out . pushIndent ( ) ; out . printil ( \"out.clearBuffer();\" ) ; out . popIndent ( ) ; out . printil ( \"if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);\" ) ; out . printil ( \"else throw new ServletException(t);\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . popIndent ( ) ; out . printil ( \"} finally {\" ) ; out . pushIndent ( ) ; out . printil ( \"_jspxFactory.releasePageContext(_jspx_page_context);\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; // Close the service method out . popIndent ( ) ; out . printil ( \"}\" ) ; // Generated methods, helper classes, etc. genCommonPostamble ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main entry for Generator . [CODESPLIT] public static void generate ( ServletWriter out , Compiler compiler , Node . Nodes page ) throws JasperException { Generator gen = new Generator ( out , compiler ) ; if ( gen . isPoolingEnabled ) { gen . compileTagHandlerPoolList ( page ) ; } if ( gen . ctxt . isTagFile ( ) ) { JasperTagInfo tagInfo = ( JasperTagInfo ) gen . ctxt . getTagInfo ( ) ; gen . generateTagHandlerPreamble ( tagInfo , page ) ; if ( gen . ctxt . isPrototypeMode ( ) ) { return ; } gen . generateXmlProlog ( page ) ; gen . fragmentHelperClass . generatePreamble ( ) ; page . visit ( gen . new GenerateVisitor ( gen . ctxt . isTagFile ( ) , out , gen . methodsBuffered , gen . fragmentHelperClass ) ) ; gen . generateTagHandlerPostamble ( tagInfo ) ; } else { gen . generatePreamble ( page ) ; gen . generateXmlProlog ( page ) ; gen . fragmentHelperClass . generatePreamble ( ) ; page . visit ( gen . new GenerateVisitor ( gen . ctxt . isTagFile ( ) , out , gen . methodsBuffered , gen . fragmentHelperClass ) ) ; gen . generatePostamble ( page ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Generates tag handler preamble . [CODESPLIT] private void generateTagHandlerPreamble ( JasperTagInfo tagInfo , Node . Nodes tag ) throws JasperException { // Generate package declaration String className = tagInfo . getTagClassName ( ) ; int lastIndex = className . lastIndexOf ( ' ' ) ; if ( lastIndex != - 1 ) { String pkgName = className . substring ( 0 , lastIndex ) ; genPreamblePackage ( pkgName ) ; className = className . substring ( lastIndex + 1 ) ; } // Generate imports genPreambleImports ( ) ; // Generate class declaration out . printin ( \"public final class \" ) ; out . println ( className ) ; out . printil ( \"    extends javax.servlet.jsp.tagext.SimpleTagSupport\" ) ; out . printin ( \"    implements org.apache.jasper.runtime.JspSourceDependent\" ) ; if ( tagInfo . hasDynamicAttributes ( ) ) { out . println ( \",\" ) ; out . printin ( \"               javax.servlet.jsp.tagext.DynamicAttributes\" ) ; } out . println ( \" {\" ) ; out . println ( ) ; out . pushIndent ( ) ; /*\n         * Class body begins here\n         */ generateDeclarations ( tag ) ; // Static initializations here genPreambleStaticInitializers ( ) ; out . printil ( \"private JspContext jspContext;\" ) ; // Declare writer used for storing result of fragment/body invocation // if 'varReader' or 'var' attribute is specified out . printil ( \"private java.io.Writer _jspx_sout;\" ) ; // Class variable declarations genPreambleClassVariableDeclarations ( tagInfo . getTagName ( ) ) ; generateSetJspContext ( tagInfo ) ; // Tag-handler specific declarations generateTagHandlerAttributes ( tagInfo ) ; if ( tagInfo . hasDynamicAttributes ( ) ) generateSetDynamicAttribute ( ) ; // Methods here genPreambleMethods ( ) ; // Now the doTag() method out . printil ( \"public void doTag() throws JspException, java.io.IOException {\" ) ; if ( ctxt . isPrototypeMode ( ) ) { out . printil ( \"}\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; return ; } out . pushIndent ( ) ; /*\n         * According to the spec, 'pageContext' must not be made available as\n         * an implicit object in tag files.\n         * Declare _jspx_page_context, so we can share the code generator with\n         * JSPs. \n         */ out . printil ( \"PageContext _jspx_page_context = (PageContext)jspContext;\" ) ; // Declare implicit objects.   out . printil ( \"HttpServletRequest request = \" + \"(HttpServletRequest) _jspx_page_context.getRequest();\" ) ; out . printil ( \"HttpServletResponse response = \" + \"(HttpServletResponse) _jspx_page_context.getResponse();\" ) ; out . printil ( \"HttpSession session = _jspx_page_context.getSession();\" ) ; out . printil ( \"ServletContext application = _jspx_page_context.getServletContext();\" ) ; out . printil ( \"ServletConfig config = _jspx_page_context.getServletConfig();\" ) ; out . printil ( \"JspWriter out = jspContext.getOut();\" ) ; if ( isPoolingEnabled && ! tagHandlerPoolNames . isEmpty ( ) ) { out . printil ( \"_jspInit(config);\" ) ; } generatePageScopedVariables ( tagInfo ) ; out . println ( ) ; out . printil ( \"try {\" ) ; out . pushIndent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates declarations for tag handler attributes and defines the getter and setter methods for each . [CODESPLIT] private void generateTagHandlerAttributes ( TagInfo tagInfo ) throws JasperException { if ( tagInfo . hasDynamicAttributes ( ) ) { out . printil ( \"private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();\" ) ; } // Declare attributes TagAttributeInfo [ ] attrInfos = tagInfo . getAttributes ( ) ; for ( int i = 0 ; i < attrInfos . length ; i ++ ) { out . printin ( \"private \" ) ; if ( attrInfos [ i ] . isFragment ( ) ) { out . print ( \"javax.servlet.jsp.tagext.JspFragment \" ) ; } else { out . print ( JspUtil . toJavaSourceType ( attrInfos [ i ] . getTypeName ( ) ) ) ; out . print ( \" \" ) ; } out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( \";\" ) ; } out . println ( ) ; // Define attribute getter and setter methods for ( int i = 0 ; i < attrInfos . length ; i ++ ) { // getter method out . printin ( \"public \" ) ; if ( attrInfos [ i ] . isFragment ( ) ) { out . print ( \"javax.servlet.jsp.tagext.JspFragment \" ) ; } else { out . print ( JspUtil . toJavaSourceType ( attrInfos [ i ] . getTypeName ( ) ) ) ; out . print ( \" \" ) ; } out . print ( toGetterMethod ( attrInfos [ i ] . getName ( ) ) ) ; out . println ( \" {\" ) ; out . pushIndent ( ) ; out . printin ( \"return this.\" ) ; out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( \";\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; // setter method out . printin ( \"public void \" ) ; out . print ( toSetterMethodName ( attrInfos [ i ] . getName ( ) ) ) ; if ( attrInfos [ i ] . isFragment ( ) ) { out . print ( \"(javax.servlet.jsp.tagext.JspFragment \" ) ; } else { out . print ( \"(\" ) ; out . print ( JspUtil . toJavaSourceType ( attrInfos [ i ] . getTypeName ( ) ) ) ; out . print ( \" \" ) ; } out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( \") {\" ) ; out . pushIndent ( ) ; out . printin ( \"this.\" ) ; out . print ( attrInfos [ i ] . getName ( ) ) ; out . print ( \" = \" ) ; out . print ( attrInfos [ i ] . getName ( ) ) ; out . println ( \";\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Generate setter for JspContext so we can create a wrapper and store both the original and the wrapper . We need the wrapper to mask the page context from the tag file and simulate a fresh page context . We need the original to do things like sync AT_BEGIN and AT_END scripting variables . [CODESPLIT] private void generateSetJspContext ( TagInfo tagInfo ) { boolean nestedSeen = false ; boolean atBeginSeen = false ; boolean atEndSeen = false ; // Determine if there are any aliases boolean aliasSeen = false ; TagVariableInfo [ ] tagVars = tagInfo . getTagVariableInfos ( ) ; for ( int i = 0 ; i < tagVars . length ; i ++ ) { if ( tagVars [ i ] . getNameFromAttribute ( ) != null && tagVars [ i ] . getNameGiven ( ) != null ) { aliasSeen = true ; break ; } } if ( aliasSeen ) { out . printil ( \"public void setJspContext(JspContext ctx, java.util.Map aliasMap) {\" ) ; } else { out . printil ( \"public void setJspContext(JspContext ctx) {\" ) ; } out . pushIndent ( ) ; out . printil ( \"super.setJspContext(ctx);\" ) ; out . printil ( \"java.util.ArrayList<String> _jspx_nested = null;\" ) ; out . printil ( \"java.util.ArrayList<String> _jspx_at_begin = null;\" ) ; out . printil ( \"java.util.ArrayList<String> _jspx_at_end = null;\" ) ; for ( int i = 0 ; i < tagVars . length ; i ++ ) { switch ( tagVars [ i ] . getScope ( ) ) { case VariableInfo . NESTED : if ( ! nestedSeen ) { out . printil ( \"_jspx_nested = new java.util.ArrayList<String>();\" ) ; nestedSeen = true ; } out . printin ( \"_jspx_nested.add(\" ) ; break ; case VariableInfo . AT_BEGIN : if ( ! atBeginSeen ) { out . printil ( \"_jspx_at_begin = new java.util.ArrayList<String>();\" ) ; atBeginSeen = true ; } out . printin ( \"_jspx_at_begin.add(\" ) ; break ; case VariableInfo . AT_END : if ( ! atEndSeen ) { out . printil ( \"_jspx_at_end = new java.util.ArrayList<String>();\" ) ; atEndSeen = true ; } out . printin ( \"_jspx_at_end.add(\" ) ; break ; } // switch out . print ( quote ( tagVars [ i ] . getNameGiven ( ) ) ) ; out . println ( \");\" ) ; } if ( aliasSeen ) { out . printil ( \"this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, aliasMap);\" ) ; } else { out . printil ( \"this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null);\" ) ; } out . popIndent ( ) ; out . printil ( \"}\" ) ; out . println ( ) ; out . printil ( \"public JspContext getJspContext() {\" ) ; out . pushIndent ( ) ; out . printil ( \"return this.jspContext;\" ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Generates implementation of javax . servlet . jsp . tagext . DynamicAttributes . setDynamicAttribute () method which saves each dynamic attribute that is passed in so that a scoped variable can later be created for it . [CODESPLIT] public void generateSetDynamicAttribute ( ) { out . printil ( \"public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {\" ) ; out . pushIndent ( ) ; /* \n         * According to the spec, only dynamic attributes with no uri are to\n         * be present in the Map; all other dynamic attributes are ignored.\n         */ out . printil ( \"if (uri == null)\" ) ; out . pushIndent ( ) ; out . printil ( \"_jspx_dynamic_attrs.put(localName, value);\" ) ; out . popIndent ( ) ; out . popIndent ( ) ; out . printil ( \"}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates a page - scoped variable for each declared tag attribute . Also if the tag accepts dynamic attributes a page - scoped variable is made available for each dynamic attribute that was passed in . [CODESPLIT] private void generatePageScopedVariables ( JasperTagInfo tagInfo ) { // \"normal\" attributes TagAttributeInfo [ ] attrInfos = tagInfo . getAttributes ( ) ; for ( int i = 0 ; i < attrInfos . length ; i ++ ) { String attrName = attrInfos [ i ] . getName ( ) ; out . printil ( \"if( \" + toGetterMethod ( attrName ) + \" != null ) {\" ) ; out . pushIndent ( ) ; out . printin ( \"_jspx_page_context.setAttribute(\" ) ; out . print ( quote ( attrName ) ) ; out . print ( \", \" ) ; out . print ( toGetterMethod ( attrName ) ) ; out . println ( \");\" ) ; if ( attrInfos [ i ] . isDeferredValue ( ) ) { // If the attribute is a deferred value, also set it to an EL // variable of the same name. out . printin ( \"org.apache.jasper.runtime.PageContextImpl.setValueVariable(\" ) ; out . print ( \"_jspx_page_context, \" ) ; out . print ( quote ( attrName ) ) ; out . print ( \", \" ) ; out . print ( toGetterMethod ( attrName ) ) ; out . println ( \");\" ) ; } if ( attrInfos [ i ] . isDeferredMethod ( ) ) { // If the attribute is a deferred method, set a wrapped // ValueExpression to an EL variable of the same name. out . printin ( \"org.apache.jasper.runtime.PageContextImpl.setMethodVariable(\" ) ; out . print ( \"_jspx_page_context, \" ) ; out . print ( quote ( attrName ) ) ; out . print ( \", \" ) ; out . print ( toGetterMethod ( attrName ) ) ; out . println ( \");\" ) ; } out . popIndent ( ) ; out . println ( \"}\" ) ; } // Expose the Map containing dynamic attributes as a page-scoped var if ( tagInfo . hasDynamicAttributes ( ) ) { out . printin ( \"_jspx_page_context.setAttribute(\\\"\" ) ; out . print ( tagInfo . getDynamicAttributesMapName ( ) ) ; out . print ( \"\\\", _jspx_dynamic_attrs);\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Generates the getter method for the given attribute name . [CODESPLIT] private String toGetterMethod ( String attrName ) { char [ ] attrChars = attrName . toCharArray ( ) ; attrChars [ 0 ] = Character . toUpperCase ( attrChars [ 0 ] ) ; return \"get\" + new String ( attrChars ) + \"()\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Generates the setter method name for the given attribute name . [CODESPLIT] private String toSetterMethodName ( String attrName ) { char [ ] attrChars = attrName . toCharArray ( ) ; attrChars [ 0 ] = Character . toUpperCase ( attrChars [ 0 ] ) ; return \"set\" + new String ( attrChars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read in a map of properties [CODESPLIT] private Map < MetaKey , String > readProperties ( final InputStream stream ) throws IOException { try { // wrap the input stream since we don't want the XML parser to close the stream while parsing final Document doc = this . xmlToolsFactory . newDocumentBuilder ( ) . parse ( new FilterInputStream ( stream ) { @ Override public void close ( ) { // do nothing } } ) ; final Element root = doc . getDocumentElement ( ) ; if ( ! \"properties\" . equals ( root . getNodeName ( ) ) ) { throw new IllegalStateException ( String . format ( \"Root element must be of type '%s'\" , \"properties\" ) ) ; } final Map < MetaKey , String > result = new HashMap <> ( ) ; for ( final Element ele : XmlHelper . iterElement ( root , \"property\" ) ) { final String namespace = ele . getAttribute ( \"namespace\" ) ; final String key = ele . getAttribute ( \"key\" ) ; final String value = ele . getTextContent ( ) ; if ( namespace . isEmpty ( ) || key . isEmpty ( ) ) { continue ; } result . put ( new MetaKey ( namespace , key ) , value ) ; } return result ; } catch ( final Exception e ) { throw new IOException ( \"Failed to read properties\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Export the content of a channel [CODESPLIT] private void exportChannel ( final By by , final OutputStream stream ) throws IOException { final ZipOutputStream zos = new ZipOutputStream ( stream ) ; initExportFile ( zos ) ; this . channelService . accessRun ( by , ReadableChannel . class , channel -> { putDataEntry ( zos , \"names\" , makeNames ( channel . getId ( ) ) ) ; putDataEntry ( zos , \"description\" , channel . getId ( ) . getDescription ( ) ) ; putDirEntry ( zos , \"artifacts\" ) ; putProperties ( zos , \"properties.xml\" , channel . getContext ( ) . getProvidedMetaData ( ) ) ; putAspects ( zos , channel . getContext ( ) . getAspectStates ( ) . keySet ( ) ) ; // the first run receives all artifacts and filters for the root elements putArtifacts ( zos , \"artifacts/\" , channel , channel . getArtifacts ( ) , true ) ; } ) ; this . channelService . accessRun ( by , TriggeredChannel . class , channel -> { putTriggers ( zos , channel ) ; } ) ; zos . finish ( ) ; // don't close stream, since there might be other channels following }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make an array of header entries with given charset <p > <strong > Note : < / strong > Further updates on this instance will not update the returned array . This is actually a copy of the current state . < / p > [CODESPLIT] public HeaderEntry [ ] makeEntries ( Charset charset ) { if ( charset == null ) { throw new IllegalArgumentException ( \"'charset' cannot be null\" ) ; } Header . charset = charset ; return this . entries . entrySet ( ) . stream ( ) . map ( Header :: makeEntry ) . toArray ( num -> new HeaderEntry [ num ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate XML view against the TagLibraryValidator classes of all imported tag libraries . [CODESPLIT] private static void validateXmlView ( PageData xmlView , Compiler compiler ) throws JasperException { StringBuilder errMsg = null ; ErrorDispatcher errDisp = compiler . getErrorDispatcher ( ) ; for ( Iterator < TagLibraryInfo > iter = compiler . getPageInfo ( ) . getTaglibs ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { TagLibraryInfo o = iter . next ( ) ; if ( ! ( o instanceof TagLibraryInfoImpl ) ) continue ; TagLibraryInfoImpl tli = ( TagLibraryInfoImpl ) o ; ValidationMessage [ ] errors = tli . validate ( xmlView ) ; if ( ( errors != null ) && ( errors . length != 0 ) ) { if ( errMsg == null ) { errMsg = new StringBuilder ( ) ; } errMsg . append ( \"<h3>\" ) ; errMsg . append ( Localizer . getMessage ( \"jsp.error.tlv.invalid.page\" , tli . getShortName ( ) ) ) ; errMsg . append ( \"</h3>\" ) ; for ( int i = 0 ; i < errors . length ; i ++ ) { if ( errors [ i ] != null ) { errMsg . append ( \"<p>\" ) ; errMsg . append ( errors [ i ] . getId ( ) ) ; errMsg . append ( \": \" ) ; errMsg . append ( errors [ i ] . getMessage ( ) ) ; errMsg . append ( \"</p>\" ) ; } } } } if ( errMsg != null ) { errDisp . jspError ( errMsg . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the next available tag handler from this tag handler pool instantiating one if this tag handler pool is empty . [CODESPLIT] public < T extends JspTag > JspTag get ( Class < T > handlerClass ) throws JspException { synchronized ( this ) { if ( current >= 0 ) { return handlers [ current -- ] ; } } // Out of sync block - there is no need for other threads to // wait for us to construct a tag for this thread. JspTag tagHandler = null ; try { if ( resourceInjector != null ) { tagHandler = resourceInjector . createTagHandlerInstance ( handlerClass ) ; } else { tagHandler = handlerClass . newInstance ( ) ; } } catch ( Exception e ) { throw new JspException ( e . getMessage ( ) , e ) ; } return tagHandler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given tag handler to this tag handler pool unless this tag handler pool has already reached its capacity in which case the tag handler s release () method is called . [CODESPLIT] public void reuse ( JspTag handler ) { synchronized ( this ) { if ( current < ( handlers . length - 1 ) ) { handlers [ ++ current ] = handler ; return ; } } // There is no need for other threads to wait for us to release if ( handler instanceof Tag ) { ( ( Tag ) handler ) . release ( ) ; } if ( resourceInjector != null ) { resourceInjector . preDestroy ( handler ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls the release () method of all available tag handlers in this tag handler pool . [CODESPLIT] public synchronized void release ( ) { for ( int i = current ; i >= 0 ; i -- ) { if ( handlers [ i ] instanceof Tag ) { ( ( Tag ) handlers [ i ] ) . release ( ) ; } if ( resourceInjector != null ) { resourceInjector . preDestroy ( handlers [ i ] ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an EL expression [CODESPLIT] public static ELNode . Nodes parse ( String expression ) { ELParser parser = new ELParser ( expression ) ; while ( parser . hasNextChar ( ) ) { String text = parser . skipUntilEL ( ) ; if ( text . length ( ) > 0 ) { parser . expr . add ( new ELNode . Text ( text ) ) ; } ELNode . Nodes elexpr = parser . parseEL ( ) ; if ( ! elexpr . isEmpty ( ) ) { parser . expr . add ( new ELNode . Root ( elexpr , parser . isDollarExpr ) ) ; } } return parser . expr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an EL expression string $ { ... } or # { ... } [CODESPLIT] private ELNode . Nodes parseEL ( ) { StringBuilder buf = new StringBuilder ( ) ; ELexpr = new ELNode . Nodes ( ) ; while ( hasNext ( ) ) { nextToken ( ) ; if ( curToken instanceof Char ) { if ( curToken . toChar ( ) == ' ' ) { break ; } buf . append ( curToken . toChar ( ) ) ; } else { // Output whatever is in buffer if ( buf . length ( ) > 0 ) { ELexpr . add ( new ELNode . ELText ( buf . toString ( ) ) ) ; } if ( ! parseFunction ( ) ) { ELexpr . add ( new ELNode . ELText ( curToken . toString ( ) ) ) ; } } } if ( buf . length ( ) > 0 ) { ELexpr . add ( new ELNode . ELText ( buf . toString ( ) ) ) ; } return ELexpr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skip until an EL expression ( $ { or # { ) is reached allowing escape sequences \\\\ \\ $ and \\ # . [CODESPLIT] private String skipUntilEL ( ) { char prev = 0 ; StringBuilder buf = new StringBuilder ( ) ; while ( hasNextChar ( ) ) { char ch = nextChar ( ) ; if ( prev == ' ' ) { prev = 0 ; if ( ch == ' ' ) { buf . append ( ' ' ) ; if ( ! escapeBS ) prev = ' ' ; } else if ( ch == ' ' || ch == ' ' ) { buf . append ( ch ) ; } // else error! } else if ( prev == ' ' || prev == ' ' ) { if ( ch == ' ' ) { this . isDollarExpr = ( prev == ' ' ) ; prev = 0 ; break ; } buf . append ( prev ) ; if ( ch == ' ' || ch == ' ' || ch == ' ' ) { prev = ch ; } else { buf . append ( ch ) ; } } else if ( ch == ' ' || ch == ' ' || ch == ' ' ) { prev = ch ; } else { buf . append ( ch ) ; } } if ( prev != 0 ) { buf . append ( prev ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Parse a string in single or double quotes allowing for escape sequences \\\\ and ( \\ or \\ ) [CODESPLIT] private Token parseQuotedChars ( char quote ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( quote ) ; while ( hasNextChar ( ) ) { char ch = nextChar ( ) ; if ( ch == ' ' ) { ch = nextChar ( ) ; if ( ch == ' ' || ch == quote ) { buf . append ( ch ) ; } // else error! } else if ( ch == quote ) { buf . append ( ch ) ; break ; } else { buf . append ( ch ) ; } } return new QuotedString ( buf . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select the property group that has more restrictive url - pattern . In case of tie select the first . [CODESPLIT] private JspPropertyGroup selectProperty ( JspPropertyGroup prev , JspPropertyGroup curr ) { if ( prev == null ) { return curr ; } if ( prev . getExtension ( ) == null ) { // exact match return prev ; } if ( curr . getExtension ( ) == null ) { // exact match return curr ; } String prevPath = prev . getPath ( ) ; String currPath = curr . getPath ( ) ; if ( prevPath == null && currPath == null ) { // Both specifies a *.ext, keep the first one return prev ; } if ( prevPath == null && currPath != null ) { return curr ; } if ( prevPath != null && currPath == null ) { return prev ; } if ( prevPath . length ( ) >= currPath . length ( ) ) { return prev ; } return curr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a property that best matches the supplied resource . [CODESPLIT] public JspProperty findJspProperty ( String uri ) throws JasperException { init ( ) ; // JSP Configuration settings do not apply to tag files\t     if ( jspProperties == null || uri . endsWith ( \".tag\" ) || uri . endsWith ( \".tagx\" ) ) { return defaultJspProperty ; } String uriPath = null ; int index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriPath = uri . substring ( 0 , index + 1 ) ; } String uriExtension = null ; index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriExtension = uri . substring ( index + 1 ) ; } ArrayList < String > includePreludes = new ArrayList < String > ( ) ; ArrayList < String > includeCodas = new ArrayList < String > ( ) ; JspPropertyGroup isXmlMatch = null ; JspPropertyGroup elIgnoredMatch = null ; JspPropertyGroup scriptingInvalidMatch = null ; JspPropertyGroup trimSpacesMatch = null ; JspPropertyGroup poundAllowedMatch = null ; JspPropertyGroup pageEncodingMatch = null ; JspPropertyGroup defaultContentTypeMatch = null ; JspPropertyGroup bufferMatch = null ; JspPropertyGroup errorOnUndeclaredNamespaceMatch = null ; for ( JspPropertyGroup jpg : jspProperties ) { JspProperty jp = jpg . getJspProperty ( ) ; // (arrays will be the same length) String extension = jpg . getExtension ( ) ; String path = jpg . getPath ( ) ; if ( extension == null ) { // exact match pattern: /a/foo.jsp if ( ! uri . equals ( path ) ) { // not matched; continue ; } } else { // Matching patterns *.ext or /p/* if ( path != null && uriPath != null && ! uriPath . startsWith ( path ) ) { // not matched continue ; } if ( ! extension . equals ( \"*\" ) && ! extension . equals ( uriExtension ) ) { // not matched continue ; } } // We have a match // Add include-preludes and include-codas if ( jp . getIncludePrelude ( ) != null ) { includePreludes . addAll ( jp . getIncludePrelude ( ) ) ; } if ( jp . getIncludeCoda ( ) != null ) { includeCodas . addAll ( jp . getIncludeCoda ( ) ) ; } // If there is a previous match for the same property, remember // the one that is more restrictive. if ( jp . isXml ( ) != null ) { isXmlMatch = selectProperty ( isXmlMatch , jpg ) ; } if ( jp . isELIgnored ( ) != null ) { elIgnoredMatch = selectProperty ( elIgnoredMatch , jpg ) ; } if ( jp . isScriptingInvalid ( ) != null ) { scriptingInvalidMatch = selectProperty ( scriptingInvalidMatch , jpg ) ; } if ( jp . getPageEncoding ( ) != null ) { pageEncodingMatch = selectProperty ( pageEncodingMatch , jpg ) ; } if ( jp . getTrimSpaces ( ) != null ) { trimSpacesMatch = selectProperty ( trimSpacesMatch , jpg ) ; } if ( jp . getPoundAllowed ( ) != null ) { poundAllowedMatch = selectProperty ( poundAllowedMatch , jpg ) ; } if ( jp . getDefaultContentType ( ) != null ) { defaultContentTypeMatch = selectProperty ( defaultContentTypeMatch , jpg ) ; } if ( jp . getBuffer ( ) != null ) { bufferMatch = selectProperty ( bufferMatch , jpg ) ; } if ( jp . errorOnUndeclaredNamespace ( ) != null ) { errorOnUndeclaredNamespaceMatch = selectProperty ( errorOnUndeclaredNamespaceMatch , jpg ) ; } } String isXml = defaultIsXml ; String isELIgnored = defaultIsELIgnored ; String isScriptingInvalid = defaultIsScriptingInvalid ; String trimSpaces = defaultTrimSpaces ; String poundAllowed = defaultPoundAllowed ; String pageEncoding = null ; String defaultContentType = null ; String buffer = null ; String errorOnUndeclaredNamespace = defaultErrorOnUndeclaredNamespace ; if ( isXmlMatch != null ) { isXml = isXmlMatch . getJspProperty ( ) . isXml ( ) ; } if ( elIgnoredMatch != null ) { isELIgnored = elIgnoredMatch . getJspProperty ( ) . isELIgnored ( ) ; } if ( scriptingInvalidMatch != null ) { isScriptingInvalid = scriptingInvalidMatch . getJspProperty ( ) . isScriptingInvalid ( ) ; } if ( trimSpacesMatch != null ) { trimSpaces = trimSpacesMatch . getJspProperty ( ) . getTrimSpaces ( ) ; } if ( poundAllowedMatch != null ) { poundAllowed = poundAllowedMatch . getJspProperty ( ) . getPoundAllowed ( ) ; } if ( pageEncodingMatch != null ) { pageEncoding = pageEncodingMatch . getJspProperty ( ) . getPageEncoding ( ) ; } if ( defaultContentTypeMatch != null ) { defaultContentType = defaultContentTypeMatch . getJspProperty ( ) . getDefaultContentType ( ) ; } if ( bufferMatch != null ) { buffer = bufferMatch . getJspProperty ( ) . getBuffer ( ) ; } if ( errorOnUndeclaredNamespaceMatch != null ) { errorOnUndeclaredNamespace = errorOnUndeclaredNamespaceMatch . getJspProperty ( ) . errorOnUndeclaredNamespace ( ) ; } return new JspProperty ( isXml , isELIgnored , isScriptingInvalid , trimSpaces , poundAllowed , pageEncoding , includePreludes , includeCodas , defaultContentType , buffer , errorOnUndeclaredNamespace ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To find out if an uri matches an url pattern in jsp config . If so then the uri is a JSP page . This is used primarily for jspc . [CODESPLIT] public boolean isJspPage ( String uri ) throws JasperException { init ( ) ; if ( jspProperties == null ) { return false ; } String uriPath = null ; int index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriPath = uri . substring ( 0 , index + 1 ) ; } String uriExtension = null ; index = uri . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { uriExtension = uri . substring ( index + 1 ) ; } for ( JspPropertyGroup jpg : jspProperties ) { JspProperty jp = jpg . getJspProperty ( ) ; String extension = jpg . getExtension ( ) ; String path = jpg . getPath ( ) ; if ( extension == null ) { if ( uri . equals ( path ) ) { // There is an exact match return true ; } } else { if ( ( path == null || path . equals ( uriPath ) ) && ( extension . equals ( \"*\" ) || extension . equals ( uriExtension ) ) ) { // Matches *, *.ext, /p/*, or /p/*.ext return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a standard comment for echo outputed chunk . [CODESPLIT] public void printComment ( Mark start , Mark stop , char [ ] chars ) { if ( start != null && stop != null ) { println ( \"// from=\" + start ) ; println ( \"//   to=\" + stop ) ; } if ( chars != null ) for ( int i = 0 ; i < chars . length ; ) { printin ( ) ; print ( \"// \" ) ; while ( chars [ i ] != ' ' && i < chars . length ) writer . print ( chars [ i ++ ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the current indention followed by the given string [CODESPLIT] public void printin ( String s ) { writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . print ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the current indention and then the string and a \\ n . [CODESPLIT] public void printil ( String s ) { javaLine ++ ; writer . print ( SPACES . substring ( 0 , indent ) ) ; writer . println ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the given string . [CODESPLIT] public void printMultiLn ( String s ) { int index = 0 ; // look for hidden newlines inside strings while ( ( index = s . indexOf ( ' ' , index ) ) > - 1 ) { javaLine ++ ; index ++ ; } writer . print ( s ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the token is a runtime expression . In standard JSP syntax a runtime expression starts with <% and ends with % > . When the JSP document is in XML syntax a runtime expression starts with % = and ends with % . [CODESPLIT] public static boolean isExpression ( String token , boolean isXml ) { String openExpr ; String closeExpr ; if ( isXml ) { openExpr = OPEN_EXPR_XML ; closeExpr = CLOSE_EXPR_XML ; } else { openExpr = OPEN_EXPR ; closeExpr = CLOSE_EXPR ; } if ( token . startsWith ( openExpr ) && token . endsWith ( closeExpr ) ) { return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a potential expression and converts it into XML form [CODESPLIT] public static String getExprInXml ( String expression ) { String returnString ; int length = expression . length ( ) ; if ( expression . startsWith ( OPEN_EXPR ) && expression . endsWith ( CLOSE_EXPR ) ) { returnString = expression . substring ( 1 , length - 1 ) ; } else { returnString = expression ; } return escapeXml ( returnString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the given scope is valid . [CODESPLIT] public static void checkScope ( String scope , Node n , ErrorDispatcher err ) throws JasperException { if ( scope != null && ! scope . equals ( \"page\" ) && ! scope . equals ( \"request\" ) && ! scope . equals ( \"session\" ) && ! scope . equals ( \"application\" ) ) { err . jspError ( n , \"jsp.error.invalid.scope\" , scope ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if all mandatory attributes are present and if all attributes present have valid names . Checks attributes specified as XML - style attributes as well as attributes specified using the jsp : attribute standard action . [CODESPLIT] public static void checkAttributes ( String typeOfTag , Node n , ValidAttribute [ ] validAttributes , ErrorDispatcher err ) throws JasperException { Attributes attrs = n . getAttributes ( ) ; Mark start = n . getStart ( ) ; boolean valid = true ; // AttributesImpl.removeAttribute is broken, so we do this... int tempLength = ( attrs == null ) ? 0 : attrs . getLength ( ) ; ArrayList < String > temp = new ArrayList < String > ( tempLength ) ; for ( int i = 0 ; i < tempLength ; i ++ ) { String qName = attrs . getQName ( i ) ; if ( ( ! qName . equals ( \"xmlns\" ) ) && ( ! qName . startsWith ( \"xmlns:\" ) ) ) temp . add ( qName ) ; } // Add names of attributes specified using jsp:attribute Node . Nodes tagBody = n . getBody ( ) ; if ( tagBody != null ) { int numSubElements = tagBody . size ( ) ; for ( int i = 0 ; i < numSubElements ; i ++ ) { Node node = tagBody . getNode ( i ) ; if ( node instanceof Node . NamedAttribute ) { String attrName = node . getAttributeValue ( \"name\" ) ; temp . add ( attrName ) ; // Check if this value appear in the attribute of the node if ( n . getAttributeValue ( attrName ) != null ) { err . jspError ( n , \"jsp.error.duplicate.name.jspattribute\" , attrName ) ; } } else { // Nothing can come before jsp:attribute, and only // jsp:body can come after it. break ; } } } /*\n\t * First check to see if all the mandatory attributes are present.\n\t * If so only then proceed to see if the other attributes are valid\n\t * for the particular tag.\n\t */ String missingAttribute = null ; for ( int i = 0 ; i < validAttributes . length ; i ++ ) { int attrPos ; if ( validAttributes [ i ] . mandatory ) { attrPos = temp . indexOf ( validAttributes [ i ] . name ) ; if ( attrPos != - 1 ) { temp . remove ( attrPos ) ; valid = true ; } else { valid = false ; missingAttribute = validAttributes [ i ] . name ; break ; } } } // If mandatory attribute is missing then the exception is thrown if ( ! valid ) err . jspError ( start , \"jsp.error.mandatory.attribute\" , typeOfTag , missingAttribute ) ; // Check to see if there are any more attributes for the specified tag. int attrLeftLength = temp . size ( ) ; if ( attrLeftLength == 0 ) return ; // Now check to see if the rest of the attributes are valid too. String attribute = null ; for ( int j = 0 ; j < attrLeftLength ; j ++ ) { valid = false ; attribute = temp . get ( j ) ; for ( int i = 0 ; i < validAttributes . length ; i ++ ) { if ( attribute . equals ( validAttributes [ i ] . name ) ) { valid = true ; break ; } } if ( ! valid ) err . jspError ( start , \"jsp.error.invalid.attribute\" , typeOfTag , attribute ) ; } // XXX *could* move EL-syntax validation here... (sb) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape the 5 entities defined by XML . [CODESPLIT] public static String escapeXml ( String s ) { if ( s == null ) return null ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' ) { sb . append ( \"&lt;\" ) ; } else if ( c == ' ' ) { sb . append ( \"&gt;\" ) ; } else if ( c == ' ' ) { sb . append ( \"&apos;\" ) ; } else if ( c == ' ' ) { sb . append ( \"&amp;\" ) ; } else if ( c == ' ' ) { sb . append ( \"&quot;\" ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a String value to boolean . Besides the standard conversions done by Boolean . valueOf ( s ) . booleanValue () the value yes ( ignore case ) is also converted to true . If s is null then false is returned . [CODESPLIT] public static boolean booleanValue ( String s ) { boolean b = false ; if ( s != null ) { if ( s . equalsIgnoreCase ( \"yes\" ) ) { b = true ; } else { b = Boolean . valueOf ( s ) . booleanValue ( ) ; } } return b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the <tt > Class< / tt > object associated with the class or interface with the given string name . [CODESPLIT] public static Class < ? > toClass ( String type , ClassLoader loader ) throws ClassNotFoundException { Class < ? > c = null ; int i0 = type . indexOf ( ' ' ) ; int dims = 0 ; if ( i0 > 0 ) { // This is an array.  Count the dimensions for ( int i = 0 ; i < type . length ( ) ; i ++ ) { if ( type . charAt ( i ) == ' ' ) dims ++ ; } type = type . substring ( 0 , i0 ) ; } if ( \"boolean\" . equals ( type ) ) c = boolean . class ; else if ( \"char\" . equals ( type ) ) c = char . class ; else if ( \"byte\" . equals ( type ) ) c = byte . class ; else if ( \"short\" . equals ( type ) ) c = short . class ; else if ( \"int\" . equals ( type ) ) c = int . class ; else if ( \"long\" . equals ( type ) ) c = long . class ; else if ( \"float\" . equals ( type ) ) c = float . class ; else if ( \"double\" . equals ( type ) ) c = double . class ; else if ( type . indexOf ( ' ' ) < 0 ) c = loader . loadClass ( type ) ; if ( dims == 0 ) return c ; if ( dims == 1 ) return java . lang . reflect . Array . newInstance ( c , 1 ) . getClass ( ) ; // Array of more than i dimension return java . lang . reflect . Array . newInstance ( c , new int [ dims ] ) . getClass ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces a String representing a call to the EL interpreter . [CODESPLIT] public static String interpreterCall ( boolean isTagFile , String expression , Class expectedType , String fnmapvar , String expectedDeferredType , String expectedReturnType , String [ ] expectedParamTypes ) { /*\n         * Determine which context object to use.\n         */ String jspCtxt = null ; if ( isTagFile ) jspCtxt = \"this.getJspContext()\" ; else jspCtxt = \"_jspx_page_context\" ; if ( expectedType == javax . el . ValueExpression . class ) { if ( expectedDeferredType == null ) { expectedDeferredType = \"java.lang.Object\" ; } return \"org.apache.jasper.runtime.PageContextImpl.getValueExpression\" + \"(\" + Generator . quote ( expression ) + \", \" + \"(PageContext)\" + jspCtxt + \", \" + expectedDeferredType + \".class, \" + fnmapvar + \")\" ; } if ( expectedType == javax . el . MethodExpression . class ) { if ( expectedReturnType == null ) { expectedReturnType = \"Void\" ; } StringBuilder params = new StringBuilder ( ) ; if ( expectedParamTypes != null ) { for ( int i = 0 ; i < expectedParamTypes . length ; i ++ ) { if ( i > 0 ) { params . append ( \", \" ) ; } params . append ( expectedParamTypes [ i ] + \".class\" ) ; } } return \"org.apache.jasper.runtime.PageContextImpl.getMethodExpression\" + \"(\" + Generator . quote ( expression ) + \", \" + \"(PageContext)\" + jspCtxt + \", \" + fnmapvar + \", \" + expectedReturnType + \".class, \" + \"new Class[] {\" + params . toString ( ) + \"})\" ; } /*\n         * Determine whether to use the expected type's textual name\n\t * or, if it's a primitive, the name of its correspondent boxed\n\t * type.\n         */ String targetType = expectedType . getName ( ) ; String primitiveConverterMethod = null ; if ( expectedType . isPrimitive ( ) ) { if ( expectedType . equals ( Boolean . TYPE ) ) { targetType = Boolean . class . getName ( ) ; primitiveConverterMethod = \"booleanValue\" ; } else if ( expectedType . equals ( Byte . TYPE ) ) { targetType = Byte . class . getName ( ) ; primitiveConverterMethod = \"byteValue\" ; } else if ( expectedType . equals ( Character . TYPE ) ) { targetType = Character . class . getName ( ) ; primitiveConverterMethod = \"charValue\" ; } else if ( expectedType . equals ( Short . TYPE ) ) { targetType = Short . class . getName ( ) ; primitiveConverterMethod = \"shortValue\" ; } else if ( expectedType . equals ( Integer . TYPE ) ) { targetType = Integer . class . getName ( ) ; primitiveConverterMethod = \"intValue\" ; } else if ( expectedType . equals ( Long . TYPE ) ) { targetType = Long . class . getName ( ) ; primitiveConverterMethod = \"longValue\" ; } else if ( expectedType . equals ( Float . TYPE ) ) { targetType = Float . class . getName ( ) ; primitiveConverterMethod = \"floatValue\" ; } else if ( expectedType . equals ( Double . TYPE ) ) { targetType = Double . class . getName ( ) ; primitiveConverterMethod = \"doubleValue\" ; } } targetType = toJavaSourceType ( targetType ) ; StringBuilder call = new StringBuilder ( \"(\" + targetType + \") \" + \"org.apache.jasper.runtime.PageContextImpl.evaluateExpression\" + \"(\" + Generator . quote ( expression ) + \", \" + targetType + \".class, \" + \"(PageContext)\" + jspCtxt + \", \" + fnmapvar + \")\" ) ; /*\n         * Add the primitive converter method if we need to.\n         */ if ( primitiveConverterMethod != null ) { call . insert ( 0 , \"(\" ) ; call . append ( \").\" + primitiveConverterMethod + \"()\" ) ; } return call . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates the syntax of all EL expressions within the given string . [CODESPLIT] public static void validateExpressions ( Mark where , String expressions , FunctionMapper functionMapper , ErrorDispatcher err ) throws JasperException { try { ELContextImpl elContext = new ELContextImpl ( null ) ; elContext . setFunctionMapper ( functionMapper ) ; getExpressionFactory ( ) . createValueExpression ( elContext , expressions , Object . class ) ; } catch ( ELException e ) { err . jspError ( where , \"jsp.error.invalid.expression\" , expressions , e . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the fully - qualified class name of the tag handler corresponding to the given tag file path . [CODESPLIT] public static String getTagHandlerClassName ( String path , ErrorDispatcher err ) throws JasperException { String className = null ; int begin = 0 ; int index ; index = path . lastIndexOf ( \".tag\" ) ; if ( index == - 1 ) { err . jspError ( \"jsp.error.tagfile.badSuffix\" , path ) ; } //It's tempting to remove the \".tag\" suffix here, but we can't. //If we remove it, the fully-qualified class name of this tag //could conflict with the package name of other tags. //For instance, the tag file //    /WEB-INF/tags/foo.tag //would have fully-qualified class name //    org.apache.jsp.tag.web.foo //which would conflict with the package name of the tag file //    /WEB-INF/tags/foo/bar.tag index = path . indexOf ( WEB_INF_TAGS ) ; if ( index != - 1 ) { className = \"org.apache.jsp.tag.web.\" ; begin = index + WEB_INF_TAGS . length ( ) ; } else { index = path . indexOf ( META_INF_TAGS ) ; if ( index != - 1 ) { className = \"org.apache.jsp.tag.meta.\" ; begin = index + META_INF_TAGS . length ( ) ; } else { err . jspError ( \"jsp.error.tagfile.illegalPath\" , path ) ; } } className += makeJavaPackage ( path . substring ( begin ) ) ; return className ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the given path to a Java package or fully - qualified class name [CODESPLIT] public static final String makeJavaPackage ( String path ) { String classNameComponents [ ] = split ( path , \"/\" ) ; StringBuilder legalClassNames = new StringBuilder ( ) ; for ( int i = 0 ; i < classNameComponents . length ; i ++ ) { legalClassNames . append ( makeJavaIdentifier ( classNameComponents [ i ] ) ) ; if ( i < classNameComponents . length - 1 ) { legalClassNames . append ( ' ' ) ; } } return legalClassNames . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a string into it s components . [CODESPLIT] private static final String [ ] split ( String path , String pat ) { ArrayList < String > comps = new ArrayList < String > ( ) ; int pos = path . indexOf ( pat ) ; int start = 0 ; while ( pos >= 0 ) { if ( pos > start ) { String comp = path . substring ( start , pos ) ; comps . add ( comp ) ; } start = pos + pat . length ( ) ; pos = path . indexOf ( pat , start ) ; } if ( start < path . length ( ) ) { comps . add ( path . substring ( start ) ) ; } String [ ] result = new String [ comps . size ( ) ] ; for ( int i = 0 ; i < comps . size ( ) ; i ++ ) { result [ i ] = comps . get ( i ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the given identifier to a legal Java identifier [CODESPLIT] public static final String makeJavaIdentifier ( String identifier ) { StringBuilder modifiedIdentifier = new StringBuilder ( identifier . length ( ) ) ; if ( ! Character . isJavaIdentifierStart ( identifier . charAt ( 0 ) ) ) { modifiedIdentifier . append ( ' ' ) ; } for ( int i = 0 ; i < identifier . length ( ) ; i ++ ) { char ch = identifier . charAt ( i ) ; if ( Character . isJavaIdentifierPart ( ch ) && ch != ' ' ) { modifiedIdentifier . append ( ch ) ; } else if ( ch == ' ' ) { modifiedIdentifier . append ( ' ' ) ; } else { modifiedIdentifier . append ( mangleChar ( ch ) ) ; } } if ( isJavaKeyword ( modifiedIdentifier . toString ( ) ) ) { modifiedIdentifier . append ( ' ' ) ; } return modifiedIdentifier . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Mangle the specified character to create a legal Java class name . [CODESPLIT] public static final String mangleChar ( char ch ) { char [ ] result = new char [ 5 ] ; result [ 0 ] = ' ' ; result [ 1 ] = Character . forDigit ( ( ch >> 12 ) & 0xf , 16 ) ; result [ 2 ] = Character . forDigit ( ( ch >> 8 ) & 0xf , 16 ) ; result [ 3 ] = Character . forDigit ( ( ch >> 4 ) & 0xf , 16 ) ; result [ 4 ] = Character . forDigit ( ch & 0xf , 16 ) ; return new String ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test whether the argument is a Java keyword [CODESPLIT] public static boolean isJavaKeyword ( String key ) { int i = 0 ; int j = javaKeywords . length ; while ( i < j ) { int k = ( i + j ) / 2 ; int result = javaKeywords [ k ] . compareTo ( key ) ; if ( result == 0 ) { return true ; } if ( result < 0 ) { i = k + 1 ; } else { j = k ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the given Xml name to a legal Java identifier . This is slightly more efficient than makeJavaIdentifier in that we only need to worry about . - and : in the string . We also assume that the resultant string is further concatenated with some prefix string so that we don t have to worry about it being a Java key word . [CODESPLIT] public static final String makeXmlJavaIdentifier ( String name ) { if ( name . indexOf ( ' ' ) >= 0 ) name = replace ( name , ' ' , \"$1\" ) ; if ( name . indexOf ( ' ' ) >= 0 ) name = replace ( name , ' ' , \"$2\" ) ; if ( name . indexOf ( ' ' ) >= 0 ) name = replace ( name , ' ' , \"$3\" ) ; return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the canonical name from a Class instance . Note that a simple replacment of $ with . of a binary name would not work as $ is a legal Java Identifier character . [CODESPLIT] public static String getCanonicalName ( Class c ) { String binaryName = c . getName ( ) ; c = c . getDeclaringClass ( ) ; if ( c == null ) { return binaryName ; } StringBuilder buf = new StringBuilder ( binaryName ) ; do { buf . setCharAt ( c . getName ( ) . length ( ) , ' ' ) ; c = c . getDeclaringClass ( ) ; } while ( c != null ) ; return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a list of jar files their manifest attribute Class - path are scanned and jars specified there are added to the list . This is carried out recursively . Note : This is needed to work around the JDK bug 6725230 . [CODESPLIT] public static List < String > expandClassPath ( List < String > files ) { for ( int i = 0 ; i < files . size ( ) ; i ++ ) { String file = files . get ( i ) ; if ( ! file . endsWith ( \".jar\" ) ) { continue ; } Manifest manifest = manifestMap . get ( file ) ; JarFile jarfile = null ; if ( manifest == null ) { try { jarfile = new JarFile ( file , false ) ; manifest = jarfile . getManifest ( ) ; if ( manifest == null ) { // mark jar file as known to contain no manifest manifestMap . put ( file , nullManifest ) ; continue ; } else if ( ! file . contains ( \"/WEB-INF\" ) ) { // Don't cache any jars bundled with the app. manifestMap . put ( file , manifest ) ; } } catch ( IOException ex ) { // Ignored continue ; } finally { try { if ( jarfile != null ) jarfile . close ( ) ; } catch ( IOException ex ) { // Ignored } } } else if ( manifest == nullManifest ) { continue ; } java . util . jar . Attributes attrs = manifest . getMainAttributes ( ) ; String cp = ( String ) attrs . getValue ( \"Class-Path\" ) ; if ( cp == null ) { continue ; } String [ ] paths = cp . split ( \" \" ) ; int lastIndex = file . lastIndexOf ( File . separatorChar ) ; String baseDir = \"\" ; if ( lastIndex > 0 ) { baseDir = file . substring ( 0 , lastIndex + 1 ) ; } for ( String path : paths ) { String p ; if ( path . startsWith ( File . separator ) ) { p = path ; } else { p = baseDir + path ; } if ( ! files . contains ( p ) ) { files . add ( p ) ; } } } return files ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a random token <p > This method uses the internal instance of of a { @link SecureRandom } generator to create a new token . < / p > [CODESPLIT] public static String createToken ( final int length ) { final byte [ ] data = new byte [ length ] ; random . nextBytes ( data ) ; return Strings . hex ( data ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add property entry only of value is not null [CODESPLIT] private static void addProperty ( final Map < String , String > props , final String key , final String value ) { if ( value == null ) { return ; } props . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a list of units inside a { @code units } element [CODESPLIT] public static void writeXml ( final XMLStreamWriter xsw , final List < InstallableUnit > ius ) throws XMLStreamException { xsw . writeStartElement ( \"units\" ) ; xsw . writeAttribute ( \"size\" , Integer . toString ( ius . size ( ) ) ) ; for ( final InstallableUnit iu : ius ) { iu . writeXmlForUnit ( xsw ) ; } xsw . writeEndElement ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the unit as XML fragment [CODESPLIT] public void writeXmlForUnit ( final XMLStreamWriter xsw ) throws XMLStreamException { xsw . writeStartElement ( \"unit\" ) ; xsw . writeAttribute ( \"id\" , this . id ) ; xsw . writeAttribute ( \"version\" , \"\" + this . version ) ; xsw . writeAttribute ( \"singleton\" , Boolean . toString ( this . singleton ) ) ; { xsw . writeEmptyElement ( \"update\" ) ; xsw . writeAttribute ( \"id\" , this . id ) ; xsw . writeAttribute ( \"range\" , \"[0.0.0,\" + this . version + \")\" ) ; xsw . writeAttribute ( \"severity\" , \"0\" ) ; } { xsw . writeStartElement ( \"properties\" ) ; xsw . writeAttribute ( \"size\" , Integer . toString ( this . properties . size ( ) ) ) ; for ( final Map . Entry < String , String > entry : this . properties . entrySet ( ) ) { xsw . writeStartElement ( \"property\" ) ; xsw . writeAttribute ( \"name\" , entry . getKey ( ) ) ; if ( entry . getValue ( ) != null ) { xsw . writeAttribute ( \"value\" , entry . getValue ( ) ) ; } xsw . writeEndElement ( ) ; } xsw . writeEndElement ( ) ; // properties } { xsw . writeStartElement ( \"provides\" ) ; xsw . writeAttribute ( \"size\" , Integer . toString ( this . provides . size ( ) ) ) ; for ( final Entry < String > entry : this . provides ) { xsw . writeStartElement ( \"provided\" ) ; xsw . writeAttribute ( \"namespace\" , entry . getNamespace ( ) ) ; xsw . writeAttribute ( \"name\" , entry . getKey ( ) ) ; xsw . writeAttribute ( \"version\" , entry . getValue ( ) ) ; xsw . writeEndElement ( ) ; } xsw . writeEndElement ( ) ; // provides } { xsw . writeStartElement ( \"requires\" ) ; xsw . writeAttribute ( \"size\" , Integer . toString ( this . requires . size ( ) ) ) ; for ( final Entry < Requirement > entry : this . requires ) { xsw . writeStartElement ( \"required\" ) ; xsw . writeAttribute ( \"namespace\" , entry . getNamespace ( ) ) ; xsw . writeAttribute ( \"name\" , entry . getKey ( ) ) ; xsw . writeAttribute ( \"range\" , makeString ( entry . getValue ( ) . getRange ( ) ) ) ; if ( entry . getValue ( ) . isOptional ( ) ) { xsw . writeAttribute ( \"optional\" , \"true\" ) ; } if ( entry . getValue ( ) . getGreedy ( ) != null ) { xsw . writeAttribute ( \"greedy\" , \"\" + entry . getValue ( ) . getGreedy ( ) ) ; } final String filterString = entry . getValue ( ) . getFilter ( ) ; if ( filterString != null && ! filterString . isEmpty ( ) ) { xsw . writeStartElement ( \"filter\" ) ; xsw . writeCharacters ( entry . getValue ( ) . getFilter ( ) ) ; xsw . writeEndElement ( ) ; // filter } xsw . writeEndElement ( ) ; // required } xsw . writeEndElement ( ) ; // requires } { if ( this . filter != null && ! this . filter . isEmpty ( ) ) { xsw . writeStartElement ( \"filter\" ) ; xsw . writeCharacters ( this . filter ) ; xsw . writeEndElement ( ) ; // filter } } if ( ! this . artifacts . isEmpty ( ) ) { xsw . writeStartElement ( \"artifacts\" ) ; xsw . writeAttribute ( \"size\" , Integer . toString ( this . artifacts . size ( ) ) ) ; for ( final Artifact artifact : this . artifacts ) { xsw . writeEmptyElement ( \"artifact\" ) ; xsw . writeAttribute ( \"classifier\" , artifact . getClassifer ( ) ) ; xsw . writeAttribute ( \"id\" , artifact . getId ( ) ) ; xsw . writeAttribute ( \"version\" , \"\" + artifact . getVersion ( ) ) ; } xsw . writeEndElement ( ) ; // artifacts } { if ( this . touchpoints . isEmpty ( ) ) { xsw . writeEmptyElement ( \"touchpoint\" ) ; xsw . writeAttribute ( \"id\" , \"null\" ) ; xsw . writeAttribute ( \"version\" , \"0.0.0\" ) ; } else { for ( final Touchpoint tp : this . touchpoints ) { xsw . writeEmptyElement ( \"touchpoint\" ) ; xsw . writeAttribute ( \"id\" , tp . getId ( ) ) ; xsw . writeAttribute ( \"version\" , tp . getVersion ( ) ) ; if ( ! tp . getInstructions ( ) . isEmpty ( ) ) { xsw . writeStartElement ( \"touchpointData\" ) ; xsw . writeAttribute ( \"size\" , \"1\" ) ; xsw . writeStartElement ( \"instructions\" ) ; xsw . writeAttribute ( \"size\" , Integer . toString ( tp . getInstructions ( ) . size ( ) ) ) ; for ( final Map . Entry < String , String > entry : tp . getInstructions ( ) . entrySet ( ) ) { xsw . writeStartElement ( \"instruction\" ) ; xsw . writeAttribute ( \"key\" , entry . getKey ( ) ) ; xsw . writeCharacters ( entry . getValue ( ) ) ; xsw . writeEndElement ( ) ; // instruction } xsw . writeEndElement ( ) ; // instructions xsw . writeEndElement ( ) ; // touchpointData } } } } { xsw . writeStartElement ( \"licenses\" ) ; xsw . writeAttribute ( \"size\" , Integer . toString ( this . licenses . size ( ) ) ) ; for ( final License licenseEntry : this . licenses ) { xsw . writeStartElement ( \"license\" ) ; if ( licenseEntry . getUri ( ) != null ) { xsw . writeAttribute ( \"url\" , licenseEntry . getUri ( ) ) ; xsw . writeAttribute ( \"uri\" , licenseEntry . getUri ( ) ) ; } if ( licenseEntry . getText ( ) != null ) { xsw . writeCData ( licenseEntry . getText ( ) ) ; } xsw . writeEndElement ( ) ; // license } xsw . writeEndElement ( ) ; // licenses } if ( this . copyright != null || this . copyrightUrl != null ) { xsw . writeStartElement ( \"copyright\" ) ; if ( this . copyrightUrl != null ) { xsw . writeAttribute ( \"url\" , this . copyrightUrl ) ; xsw . writeAttribute ( \"uri\" , this . copyrightUrl ) ; } if ( this . copyright != null ) { xsw . writeCData ( this . copyright ) ; } xsw . writeEndElement ( ) ; } xsw . writeEndElement ( ) ; // unit }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a job instance for updating it . <p > The fetched job will automatically be cloned and persisted . < / p > [CODESPLIT] public JobInstanceEntity getJobForUpdate ( final String id ) { JobInstanceEntity job = this . cloneMap . get ( id ) ; if ( job != null ) { // this already is the cloned job return job ; } // fetch the job job = this . jobs . get ( id ) ; if ( job == null ) { return null ; } // make the clone final JobInstanceEntity clonedJob = new JobInstanceEntity ( job ) ; this . cloneMap . put ( id , clonedJob ) ; return clonedJob ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a modifier value to a bootstrap type modifier [CODESPLIT] public static String modifier ( final String prefix , final Modifier modifier ) { if ( modifier == null ) { return \"\" ; } String value = null ; switch ( modifier ) { case DEFAULT : value = \"default\" ; break ; case PRIMARY : value = \"primary\" ; break ; case SUCCESS : value = \"success\" ; break ; case INFO : value = \"info\" ; break ; case WARNING : value = \"warning\" ; break ; case DANGER : value = \"danger\" ; break ; case LINK : value = \"link\" ; break ; } if ( value != null && prefix != null ) { return prefix + value ; } else { return value != null ? value : \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all meta data values which match namespace and key [CODESPLIT] public static SortedSet < String > metadata ( final Map < MetaKey , String > metadata , String namespace , String key ) { final SortedSet < String > result = new TreeSet <> ( ) ; if ( namespace . isEmpty ( ) ) { namespace = null ; } if ( key . isEmpty ( ) ) { key = null ; } for ( final Map . Entry < MetaKey , String > entry : metadata . entrySet ( ) ) { if ( namespace != null && ! namespace . equals ( entry . getKey ( ) . getNamespace ( ) ) ) { continue ; } if ( key != null && ! key . equals ( entry . getKey ( ) . getKey ( ) ) ) { continue ; } result . add ( entry . getValue ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Initializes this JspServlet . [CODESPLIT] public void init ( ServletConfig config ) throws ServletException { super . init ( config ) ; this . config = config ; this . context = config . getServletContext ( ) ; // Initialize the JSP Runtime Context options = new EmbeddedServletOptions ( config , context ) ; rctxt = new JspRuntimeContext ( context , options ) ; // START SJSWS 6232180 // Determine which HTTP methods to service (\"*\" means all) httpMethodsString = config . getInitParameter ( \"httpMethods\" ) ; if ( httpMethodsString != null && ! httpMethodsString . equals ( \"*\" ) ) { httpMethodsSet = new HashSet < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( httpMethodsString , \", \\t\\n\\r\\f\" ) ; while ( tokenizer . hasMoreTokens ( ) ) { httpMethodsSet . add ( tokenizer . nextToken ( ) ) ; } } // END SJSWS 6232180 // START GlassFish 750 taglibs = new ConcurrentHashMap < String , TagLibraryInfo > ( ) ; context . setAttribute ( Constants . JSP_TAGLIBRARY_CACHE , taglibs ) ; tagFileJarUrls = new ConcurrentHashMap < String , URL > ( ) ; context . setAttribute ( Constants . JSP_TAGFILE_JAR_URLS_CACHE , tagFileJarUrls ) ; // END GlassFish 750 if ( log . isLoggable ( Level . FINEST ) ) { log . finest ( Localizer . getMessage ( \"jsp.message.scratch.dir.is\" , options . getScratchDir ( ) . toString ( ) ) ) ; log . finest ( Localizer . getMessage ( \"jsp.message.dont.modify.servlets\" ) ) ; } this . jspProbeEmitter = ( JspProbeEmitter ) config . getServletContext ( ) . getAttribute ( \"org.glassfish.jsp.monitor.probeEmitter\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Look for a <em > precompilation request< / em > as described in Section 8 . 4 . 2 of the JSP 1 . 2 Specification . <strong > WARNING< / strong > - we cannot use <code > request . getParameter () < / code > for this because that will trigger parsing all of the request parameters and not give a servlet the opportunity to call <code > request . setCharacterEncoding () < / code > first . < / p > [CODESPLIT] boolean preCompile ( HttpServletRequest request ) throws ServletException { String queryString = request . getQueryString ( ) ; if ( queryString == null ) { return ( false ) ; } int start = queryString . indexOf ( Constants . PRECOMPILE ) ; if ( start < 0 ) { return ( false ) ; } queryString = queryString . substring ( start + Constants . PRECOMPILE . length ( ) ) ; if ( queryString . length ( ) == 0 ) { return ( true ) ; // ?jsp_precompile } if ( queryString . startsWith ( \"&\" ) ) { return ( true ) ; // ?jsp_precompile&foo=bar... } if ( ! queryString . startsWith ( \"=\" ) ) { return ( false ) ; // part of some other name or value } int limit = queryString . length ( ) ; int ampersand = queryString . indexOf ( \"&\" ) ; if ( ampersand > 0 ) { limit = ampersand ; } String value = queryString . substring ( 1 , limit ) ; if ( value . equals ( \"true\" ) ) { return ( true ) ; // ?jsp_precompile=true } else if ( value . equals ( \"false\" ) ) { // Spec says if jsp_precompile=false, the request should not // be delivered to the JSP page; the easiest way to implement // this is to set the flag to true, and precompile the page anyway. // This still conforms to the spec, since it says the // precompilation request can be ignored. return ( true ) ; // ?jsp_precompile=false } else { throw new ServletException ( \"Cannot have request parameter \" + Constants . PRECOMPILE + \" set to \" + value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- Private Methods [CODESPLIT] private void serviceJspFile ( HttpServletRequest request , HttpServletResponse response , String jspUri , Throwable exception , boolean precompile ) throws ServletException , IOException { JspServletWrapper wrapper = ( JspServletWrapper ) rctxt . getWrapper ( jspUri ) ; if ( wrapper == null ) { synchronized ( this ) { wrapper = ( JspServletWrapper ) rctxt . getWrapper ( jspUri ) ; if ( wrapper == null ) { // Check if the requested JSP page exists, to avoid // creating unnecessary directories and files. if ( null == context . getResource ( jspUri ) && ! options . getUsePrecompiled ( ) ) { String includeRequestUri = ( String ) request . getAttribute ( \"javax.servlet.include.request_uri\" ) ; if ( includeRequestUri != null ) { // Missing JSP resource has been the target of a // RequestDispatcher.include(). // Throw an exception (rather than returning a  // 404 response error code), because any call to // response.sendError() must be ignored by the // servlet engine when issued from within an // included resource (as per the Servlet spec). throw new FileNotFoundException ( JspUtil . escapeXml ( jspUri ) ) ; } response . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; log . severe ( Localizer . getMessage ( \"jsp.error.file.not.found\" , context . getRealPath ( jspUri ) ) ) ; return ; } boolean isErrorPage = exception != null ; wrapper = new JspServletWrapper ( config , options , jspUri , isErrorPage , rctxt ) ; rctxt . addWrapper ( jspUri , wrapper ) ; } } } wrapper . service ( request , response , precompile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "STARTS S1AS [CODESPLIT] private void incrementErrorCount ( String jspUri ) { countErrors . incrementAndGet ( ) ; // Fire the jspErrorEvent probe event if ( jspProbeEmitter != null ) { jspProbeEmitter . jspErrorEvent ( jspUri ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean up timed out user registrations [CODESPLIT] @ Override public void run ( ) throws Exception { this . storageManager . modifyRun ( MODEL_KEY , UserWriteModel . class , users -> { final Date timeout = new Date ( System . currentTimeMillis ( ) - getTimeout ( ) ) ; final Collection < UserEntity > updates = new LinkedList <> ( ) ; final Collection < String > removals = new LinkedList <> ( ) ; for ( final UserEntity user : users . asCollection ( ) ) { if ( user . getEmailTokenDate ( ) == null || user . getEmailTokenDate ( ) . after ( timeout ) ) { continue ; } // process timeout if ( user . isEmailVerified ( ) ) { user . setEmailToken ( null ) ; user . setEmailTokenDate ( null ) ; user . setEmailTokenSalt ( null ) ; updates . add ( user ) ; } else { // delete removals . add ( user . getId ( ) ) ; } } updates . forEach ( users :: putUser ) ; removals . forEach ( users :: removeUser ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the { @code p2 . repo : fragment - keys } field contains a matching key [CODESPLIT] private static boolean hasKey ( final ArtifactInformation art , final String key ) { if ( key == null ) { return false ; } final String keysString = art . getMetaData ( ) . get ( P2RepoConstants . KEY_FRAGMENT_KEYS ) ; if ( keysString == null ) { return false ; } final String [ ] keys = keysString . split ( P2RepoConstants . ENTRY_DELIMITER ) ; for ( final String actualKey : keys ) { if ( key . equals ( actualKey ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the last segment of a path the filename [CODESPLIT] public static String getBasename ( final String name ) { if ( name == null ) { return null ; } final String [ ] toks = name . split ( \"/\" ) ; if ( toks . length < 1 ) { return name ; } return toks [ toks . length - 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decompresses into an array of bytes . <p > If <code > len< / code > is zero no bytes are read and <code > 0< / code > is returned . Otherwise this will try to decompress <code > len< / code > bytes of uncompressed data . Less than <code > len< / code > bytes may be read only in the following situations : <ul > <li > The end of the compressed data was reached successfully . < / li > <li > An error is detected after at least one but less <code > len< / code > bytes have already been successfully decompressed . The next call with non - zero <code > len< / code > will immediately throw the pending exception . < / li > <li > An exception is thrown . < / li > < / ul > [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { if ( off < 0 || len < 0 || off + len < 0 || off + len > buf . length ) throw new IndexOutOfBoundsException ( ) ; if ( len == 0 ) return 0 ; if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; if ( endReached ) return - 1 ; int size = 0 ; try { while ( len > 0 ) { if ( xzIn == null ) { prepareNextStream ( ) ; if ( endReached ) return size == 0 ? - 1 : size ; } int ret = xzIn . read ( buf , off , len ) ; if ( ret > 0 ) { size += ret ; off += ret ; len -= ret ; } else if ( ret == - 1 ) { xzIn = null ; } } } catch ( IOException e ) { exception = e ; if ( size == 0 ) throw e ; } return size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of uncompressed bytes that can be read without blocking . The value is returned with an assumption that the compressed input data will be valid . If the compressed data is corrupt <code > CorruptedInputException< / code > may get thrown before the number of bytes claimed to be available have been read from this input stream . [CODESPLIT] public int available ( ) throws IOException { if ( in == null ) throw new XZIOException ( \"Stream closed\" ) ; if ( exception != null ) throw exception ; return xzIn == null ? 0 : xzIn . available ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the stream and optionally calls <code > in . close () < / code > . If the stream was already closed this does nothing . If <code > close ( false ) < / code > has been called a further call of <code > close ( true ) < / code > does nothing ( it doesn t call <code > in . close () < / code > ) . <p > If you don t want to close the underlying <code > InputStream< / code > there is usually no need to worry about closing this stream either ; it s fine to do nothing and let the garbage collector handle it . However if you are using { @link ArrayCache } <code > close ( false ) < / code > can be useful to put the allocated arrays back to the cache without closing the underlying <code > InputStream< / code > . <p > Note that if you successfully reach the end of the stream ( <code > read< / code > returns <code > - 1< / code > ) the arrays are automatically put back to the cache by that <code > read< / code > call . In this situation <code > close ( false ) < / code > is redundant ( but harmless ) . [CODESPLIT] public void close ( boolean closeInput ) throws IOException { if ( in != null ) { if ( xzIn != null ) { xzIn . close ( false ) ; xzIn = null ; } try { if ( closeInput ) in . close ( ) ; } finally { in = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a way for the sub class to get a { @link java . nio . ByteBuffer } representation of a certain Rollup object . [CODESPLIT] @ Override protected ByteBuffer toByteBuffer ( Object value ) { if ( ! ( value instanceof BluefloodGaugeRollup ) ) { throw new IllegalArgumentException ( \"toByteBuffer(): expecting BluefloodGaugeRollup class but got \" + value . getClass ( ) . getSimpleName ( ) ) ; } BluefloodGaugeRollup gaugeRollup = ( BluefloodGaugeRollup ) value ; return serDes . serialize ( gaugeRollup ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Consider 5 files getting merged in the buildstore . Assuming the flush rate to be 1 file / min we need all the files together in order to construct 5 min rollup How are we going to decide that a particular range has been totally filled up and ready to be rolled? One behaviour which we will start seeing in the buildstore is higher ranges starting to build up . This means the current range has almost filled up . But there is still a possibility for backed up data getting merged . So we provide RANGE_BUFFER . Basically for every call to getEligibleData it is going to return ( n - RANGE_BUFFER ) ranges to get rolled up and keep ( RANGE_BUFFER ) in buildstore Also note that returning the range will eventually remove them from buildstore after all rollups are completed in RollupGenerator for that range . [CODESPLIT] public static Map < Range , ConcurrentHashMap < Locator , Points > > getEligibleData ( ) { if ( locatorToTimestampToPoint . size ( ) <= RANGE_BUFFER ) { log . debug ( \"Range buffer still not exceeded. Returning null data to rollup generator\" ) ; return null ; } else { Object [ ] sortedKeySet = locatorToTimestampToPoint . keySet ( ) . toArray ( ) ; Range cuttingPoint = ( Range ) sortedKeySet [ sortedKeySet . length - RANGE_BUFFER - 1 ] ; log . info ( \"Found completed ranges up to the threshold range of {}\" , cuttingPoint ) ; completedRangesReturned . mark ( ) ; return locatorToTimestampToPoint . headMap ( cuttingPoint , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Similar to { @link #get ( Locator String ) } except this does not throw any { @link CacheException } . Instead it may return null if the cache does not contain the requested locator for the specified key . [CODESPLIT] public String safeGet ( Locator locator , String key ) { String cacheValue = null ; try { cacheValue = get ( locator , key ) ; } catch ( CacheException ex ) { log . trace ( String . format ( \"no cache value found for locator=%s, key=%s\" , locator . toString ( ) , key ) ) ; } return cacheValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if updated . [CODESPLIT] public boolean put ( Locator locator , String key , String value ) throws CacheException { if ( value == null ) return false ; Timer . Context cachePutTimerContext = MetadataCache . cachePutTimer . time ( ) ; boolean dbWrite = false ; try { CacheKey cacheKey = new CacheKey ( locator , key ) ; String oldValue = cache . getIfPresent ( cacheKey ) ; // don't care if oldValue == EMPTY. // always put new value in the cache. it keeps reads from happening. cache . put ( cacheKey , value ) ; if ( oldValue == null || ! oldValue . equals ( value ) ) { dbWrite = true ; } if ( dbWrite ) { updatedMetricMeter . mark ( ) ; if ( ! batchedWrites ) { databasePut ( locator , key , value ) ; } else { databaseLazyWrite ( locator , key ) ; } } return dbWrite ; } finally { cachePutTimerContext . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "implements the CacheLoader interface . [CODESPLIT] private String databaseLoad ( Locator locator , String key ) throws CacheException { try { CacheKey cacheKey = new CacheKey ( locator , key ) ; Map < String , String > metadata = io . getAllValues ( locator ) ; if ( metadata == null || metadata . isEmpty ( ) ) { cache . put ( cacheKey , NULL ) ; return NULL ; } int metadataRowSize = 0 ; // prepopulate all other metadata other than the key we called the method with for ( Map . Entry < String , String > meta : metadata . entrySet ( ) ) { metadataRowSize += meta . getKey ( ) . getBytes ( ) . length + locator . toString ( ) . getBytes ( ) . length ; if ( meta . getValue ( ) != null ) metadataRowSize += meta . getValue ( ) . getBytes ( ) . length ; if ( meta . getKey ( ) . equals ( key ) ) continue ; CacheKey metaKey = new CacheKey ( locator , meta . getKey ( ) ) ; cache . put ( metaKey , meta . getValue ( ) ) ; } totalMetadataSize . update ( metadataRowSize ) ; String value = metadata . get ( key ) ; if ( value == null ) { cache . put ( cacheKey , NULL ) ; value = NULL ; } return value ; } catch ( IOException ex ) { throw new CacheException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "type comparisions we use to determine how to serialize a number . [CODESPLIT] public static Collection < IMetric > buildMetricsCollection ( AggregatedPayload payload ) { Collection < IMetric > metrics = new ArrayList < IMetric > ( ) ; metrics . addAll ( PreaggregateConversions . convertCounters ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getFlushIntervalMillis ( ) , payload . getCounters ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertGauges ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getGauges ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertSets ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getSets ( ) ) ) ; metrics . addAll ( PreaggregateConversions . convertTimers ( payload . getTenantId ( ) , payload . getTimestamp ( ) , payload . getTimers ( ) ) ) ; return metrics ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "resolve a number to a Long or double . [CODESPLIT] public static Number resolveNumber ( Number n ) { if ( n instanceof LazilyParsedNumber ) { try { return n . longValue ( ) ; } catch ( NumberFormatException ex ) { return n . doubleValue ( ) ; } } else { // already resolved. return n ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "History : this used to support multiple types . [CODESPLIT] public ByteBuffer serialize ( String str ) { try { byte [ ] buf = new byte [ computeBufLength ( str ) ] ; CodedOutputStream out = CodedOutputStream . newInstance ( buf ) ; writeToOutputStream ( str , out ) ; return ByteBuffer . wrap ( buf ) ; } catch ( IOException e ) { throw new RuntimeException ( \"Error serializing string metadata\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "writes object to CodedOutputStream . [CODESPLIT] private static void writeToOutputStream ( Object obj , CodedOutputStream out ) throws IOException { out . writeRawByte ( STRING ) ; out . writeStringNoTag ( ( String ) obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a locator with key = shard long value calculated using Util . getShard () [CODESPLIT] @ Override public void insertLocator ( Locator locator ) throws IOException { Timer . Context timer = Instrumentation . getWriteTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; try { MutationBatch mutationBatch = AstyanaxIO . getKeyspace ( ) . prepareMutationBatch ( ) ; AstyanaxWriter . getInstance ( ) . insertLocator ( locator , mutationBatch ) ; mutationBatch . execute ( ) ; } catch ( Exception e ) { throw new IOException ( e ) ; } finally { timer . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the locators for a shard i . e . those that should be rolled up for a given shard . Should means : 1 ) A locator is capable of rollup . 2 ) A locator has had new data in the past LOCATOR_TTL seconds . [CODESPLIT] @ Override public Collection < Locator > getLocators ( long shard ) throws IOException { Timer . Context ctx = Instrumentation . getReadTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; try { RowQuery < Long , Locator > query = AstyanaxIO . getKeyspace ( ) . prepareQuery ( CassandraModel . CF_METRICS_LOCATOR ) . getKey ( shard ) ; if ( LOG . isTraceEnabled ( ) ) LOG . trace ( \"ALocatorIO.getLocators() executing: select * from \\\"\" + CassandraModel . KEYSPACE + \"\\\".\" + CassandraModel . CF_METRICS_LOCATOR_NAME + \" where key=\" + Long . toString ( shard ) ) ; return query . execute ( ) . getResult ( ) . getColumnNames ( ) ; } catch ( NotFoundException e ) { Instrumentation . markNotFound ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; return Collections . emptySet ( ) ; } catch ( ConnectionException ex ) { Instrumentation . markReadError ( ex ) ; LOG . error ( \"Connection exception during getLocators(\" + Long . toString ( shard ) + \")\" , ex ) ; throw new IOException ( \"Error reading locators\" , ex ) ; } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the TTL for a particular locator rollupType and granularity . [CODESPLIT] protected int getTtl ( Locator locator , RollupType rollupType , Granularity granularity ) { return ( int ) TTL_PROVIDER . getTTL ( locator . getTenantId ( ) , granularity , rollupType ) . get ( ) . toSeconds ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the map of timestamp - > { @link Rollup } to { @link Points } object [CODESPLIT] protected < T extends Object > Points < T > convertToPoints ( final Map < Long , T > timestampToRollupMap ) { Points points = new Points ( ) ; for ( Map . Entry < Long , T > value : timestampToRollupMap . entrySet ( ) ) { points . add ( createPoint ( value . getKey ( ) , value . getValue ( ) ) ) ; } return points ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create all prepared statements use in this class for metrics_locator [CODESPLIT] private void createPreparedStatements ( ) { // create a generic select statement for retrieving from metrics_locator Select . Where select = QueryBuilder . select ( ) . all ( ) . from ( CassandraModel . CF_METRICS_LOCATOR_NAME ) . where ( eq ( KEY , bindMarker ( ) ) ) ; getValue = DatastaxIO . getSession ( ) . prepare ( select ) ; // create a generic insert statement for inserting into metrics_locator Insert insert = QueryBuilder . insertInto ( CassandraModel . CF_METRICS_LOCATOR_NAME ) . using ( ttl ( TenantTtlProvider . LOCATOR_TTL ) ) . value ( KEY , bindMarker ( ) ) . value ( COLUMN1 , bindMarker ( ) ) . value ( VALUE , bindMarker ( ) ) ; putValue = DatastaxIO . getSession ( ) . prepare ( insert ) . setConsistencyLevel ( ConsistencyLevel . LOCAL_ONE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a locator with key = shard long value calculated using Util . getShard () [CODESPLIT] @ Override public void insertLocator ( Locator locator ) throws IOException { Session session = DatastaxIO . getSession ( ) ; Timer . Context timer = Instrumentation . getWriteTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; try { // bound values and execute BoundStatement bs = getBoundStatementForLocator ( locator ) ; session . execute ( bs ) ; } finally { timer . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package protect so other classes in this package can call it [CODESPLIT] BoundStatement getBoundStatementForLocator ( Locator locator ) { // get shard this locator would belong to long shard = ( long ) Util . getShard ( locator . toString ( ) ) ; return putValue . bind ( shard , locator . toString ( ) , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the locators for a shard i . e . those that should be rolled up for a given shard . Should means : 1 ) A locator is capable of rollup . 2 ) A locator has had new data in the past LOCATOR_TTL seconds . [CODESPLIT] @ Override public Collection < Locator > getLocators ( long shard ) throws IOException { Timer . Context ctx = Instrumentation . getReadTimerContext ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; Session session = DatastaxIO . getSession ( ) ; Collection < Locator > locators = new ArrayList < Locator > ( ) ; try { // bind value BoundStatement bs = getValue . bind ( shard ) ; List < Row > results = session . execute ( bs ) . all ( ) ; for ( Row row : results ) { if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"Read metrics_locators with shard \" + shard + \": \" + row . getString ( KEY ) + row . getString ( COLUMN1 ) ) ; } locators . add ( Locator . createLocatorFromDbKey ( row . getString ( COLUMN1 ) ) ) ; } // return results if ( locators . size ( ) == 0 ) { Instrumentation . markNotFound ( CassandraModel . CF_METRICS_LOCATOR_NAME ) ; return Collections . emptySet ( ) ; } else { return locators ; } } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to log delayed metrics if tracking delayed metrics is turned on for this Blueflood service . [CODESPLIT] public void trackDelayedMetricsTenant ( String tenantid , final List < Metric > delayedMetrics ) { if ( isTrackingDelayedMetrics ) { String logMessage = String . format ( \"[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s\" , tenantid ) ; log . info ( logMessage ) ; // log individual delayed metrics locator and collectionTime double delayedMinutes ; long nowMillis = System . currentTimeMillis ( ) ; for ( Metric metric : delayedMetrics ) { delayedMinutes = ( double ) ( nowMillis - metric . getCollectionTime ( ) ) / 1000 / 60 ; logMessage = String . format ( \"[TRACKER][DELAYED METRIC] %s has collectionTime %s which is delayed by %.2f minutes\" , metric . getLocator ( ) . toString ( ) , dateFormatter . format ( new Date ( metric . getCollectionTime ( ) ) ) , delayedMinutes ) ; log . info ( logMessage ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method logs the delayed aggregated metrics for a particular tenant if tracking delayed metric is turned on for this Blueflood service . Aggregated metrics have one single timestamp for the group of metrics that are sent in one request . [CODESPLIT] public void trackDelayedAggregatedMetricsTenant ( String tenantId , long collectionTimeMs , long delayTimeMs , List < String > delayedMetricNames ) { if ( isTrackingDelayedMetrics ) { String logMessage = String . format ( \"[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s\" , tenantId ) ; log . info ( logMessage ) ; // log individual delayed metrics locator and collectionTime double delayMin = delayTimeMs / 1000 / 60 ; logMessage = String . format ( \"[TRACKER][DELAYED METRIC] %s have collectionTime %s which is delayed by %.2f minutes\" , StringUtils . join ( delayedMetricNames , \",\" ) , dateFormatter . format ( new Date ( collectionTimeMs ) ) , delayMin ) ; log . info ( logMessage ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "read out a type - specified number . [CODESPLIT] protected Number getUnversionedDoubleOrLong ( CodedInputStream in ) throws IOException { byte type = in . readRawByte ( ) ; if ( type == Constants . B_DOUBLE ) return in . readDouble ( ) ; else return in . readRawVarint64 ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "put out a number prefaced only by a type . [CODESPLIT] protected void putUnversionedDoubleOrLong ( Number number , CodedOutputStream out ) throws IOException { if ( number instanceof Double ) { out . writeRawByte ( Constants . B_DOUBLE ) ; out . writeDoubleNoTag ( number . doubleValue ( ) ) ; } else { out . writeRawByte ( Constants . B_I64 ) ; out . writeRawVarint64 ( number . longValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the existing configuration values into a Map including those specified in defaultProps . [CODESPLIT] public Map < Object , Object > getAllProperties ( ) { Map < Object , Object > map = new HashMap < Object , Object > ( ) ; for ( Object key : defaultProps . keySet ( ) ) { map . put ( key , defaultProps . getProperty ( key . toString ( ) ) ) ; } for ( Object key : props . keySet ( ) ) { map . put ( key , props . getProperty ( key . toString ( ) ) ) ; } return Collections . unmodifiableMap ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "idempotent other than when the month changes between two calls [CODESPLIT] private void createContainer ( ) { String containerName = CONTAINER_DATE_FORMAT . format ( new Date ( ) ) ; blobStore . createContainerInLocation ( null , containerName ) ; lastContainerCreated = containerName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a way for the sub class to get a { @link java . nio . ByteBuffer } representation of a certain Rollup object . [CODESPLIT] @ Override protected ByteBuffer toByteBuffer ( Object value ) { if ( ! ( value instanceof BluefloodCounterRollup ) ) { throw new IllegalArgumentException ( \"toByteBuffer(): expecting BluefloodCounterRollup class but got \" + value . getClass ( ) . getSimpleName ( ) ) ; } BluefloodCounterRollup counterRollup = ( BluefloodCounterRollup ) value ; return serDes . serialize ( counterRollup ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { [CODESPLIT] @ Override protected BoundStatement getBoundStatementForMetric ( IMetric metric , Granularity granularity ) { Object metricValue = metric . getMetricValue ( ) ; if ( ! ( metricValue instanceof BluefloodCounterRollup ) ) { throw new InvalidDataException ( String . format ( \"getBoundStatementForMetric(locator=%s, granularity=%s): metric value %s is not type BluefloodCounterRollup\" , metric . getLocator ( ) , granularity , metric . getMetricValue ( ) . getClass ( ) . getSimpleName ( ) ) ) ; } PreparedStatement statement = metricsCFPreparedStatements . preaggrGranToInsertStatement . get ( granularity ) ; return statement . bind ( metric . getLocator ( ) . toString ( ) , metric . getCollectionTime ( ) , serDes . serialize ( ( BluefloodCounterRollup ) metricValue ) , metric . getTtlInSeconds ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void update ( long millis , int shard ) { // there are two update paths. for managed shards, we must guard the // scheduled and running collections. but for unmanaged shards, we just // let the update happen uncontested. final Timer . Context dirtyTimerCtx = markSlotDirtyTimer . time ( ) ; try { if ( log . isTraceEnabled ( ) ) { log . trace ( \"Updating {} to {}\" , shard , millis ) ; } boolean isManaged = shardStateManager . contains ( shard ) ; for ( Granularity g : Granularity . rollupGranularities ( ) ) { ShardStateManager . SlotStateManager slotStateManager = shardStateManager . getSlotStateManager ( shard , g ) ; int slot = g . slot ( millis ) ; if ( isManaged ) { synchronized ( scheduledSlots ) { //put SlotKey key = SlotKey . of ( g , slot , shard ) ; if ( scheduledSlots . remove ( key ) && log . isDebugEnabled ( ) ) { // don't worry about orderedScheduledSlots log . debug ( \"descheduled {}.\" , key ) ; } } } slotStateManager . createOrUpdateForSlotAndMillisecond ( slot , millis ) ; } } finally { dirtyTimerCtx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only one thread should be calling in this puppy . [CODESPLIT] void scheduleEligibleSlots ( long maxAgeMillis , long rollupDelayForMetricsWithShortDelay , long rollupWaitForMetricsWithLongDelay ) { long now = scheduleTime ; ArrayList < Integer > shardKeys = new ArrayList < Integer > ( shardStateManager . getManagedShards ( ) ) ; Collections . shuffle ( shardKeys ) ; for ( int shard : shardKeys ) { for ( Granularity g : Granularity . rollupGranularities ( ) ) { // sync on map since we do not want anything added to or taken from it while we iterate. synchronized ( scheduledSlots ) { // read synchronized ( runningSlots ) { // read List < Integer > slotsToWorkOn = shardStateManager . getSlotStateManager ( shard , g ) . getSlotsEligibleForRollup ( now , maxAgeMillis , rollupDelayForMetricsWithShortDelay , rollupWaitForMetricsWithLongDelay ) ; if ( slotsToWorkOn . size ( ) == 0 ) { continue ; } if ( ! canWorkOnShard ( shard ) ) { continue ; } for ( Integer slot : slotsToWorkOn ) { SlotKey slotKey = SlotKey . of ( g , slot , shard ) ; if ( areChildKeysOrSelfKeyScheduledOrRunning ( slotKey ) ) { continue ; } SlotKey key = SlotKey . of ( g , slot , shard ) ; scheduledSlots . add ( key ) ; orderedScheduledSlots . add ( key ) ; recentlyScheduledShards . put ( shard , scheduleTime ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next scheduled key . It has a few side effects : 1 ) it resets update tracking for that slot 2 ) it adds the key to the set of running rollups . [CODESPLIT] @ VisibleForTesting SlotKey getNextScheduled ( ) { synchronized ( scheduledSlots ) { if ( scheduledSlots . size ( ) == 0 ) return null ; synchronized ( runningSlots ) { SlotKey key = orderedScheduledSlots . remove ( 0 ) ; int slot = key . getSlot ( ) ; Granularity gran = key . getGranularity ( ) ; int shard = key . getShard ( ) ; // notice how we change the state, but the timestamp remained // the same. this is important.  When the state is evaluated // (i.e., in Reader.getShardState()) we need to realize that // when timestamps are the same (this will happen), that a // remove always wins during the coalesce. scheduledSlots . remove ( key ) ; if ( canWorkOnShard ( shard ) ) { UpdateStamp stamp = shardStateManager . getSlotStateManager ( shard , gran ) . getAndSetState ( slot , UpdateStamp . State . Running ) ; runningSlots . put ( key , stamp . getTimestamp ( ) ) ; return key ; } else { shardOwnershipChanged . mark ( ) ; return null ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take the given slot out of the running group and put it back into the scheduled group . If { @code rescheduleImmediately } is true the slot will be the next slot returned by a call to { @link #getNextScheduled () } . If { @code rescheduleImmediately } is false then the given slot will go to the end of the line as when it was first scheduled by { @link #scheduleEligibleSlots ( long long long ) } . [CODESPLIT] void pushBackToScheduled ( SlotKey key , boolean rescheduleImmediately ) { synchronized ( scheduledSlots ) { synchronized ( runningSlots ) { int slot = key . getSlot ( ) ; Granularity gran = key . getGranularity ( ) ; int shard = key . getShard ( ) ; // no need to set dirty/clean here. shardStateManager . getSlotStateManager ( shard , gran ) . getAndSetState ( slot , UpdateStamp . State . Active ) ; scheduledSlots . add ( key ) ; log . debug ( \"pushBackToScheduled -> added to scheduledSlots: \" + key + \" size:\" + scheduledSlots . size ( ) ) ; if ( rescheduleImmediately ) { orderedScheduledSlots . add ( 0 , key ) ; } else { orderedScheduledSlots . add ( key ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the given slot from the running group after it has been successfully re - rolled . [CODESPLIT] void clearFromRunning ( SlotKey slotKey ) { synchronized ( runningSlots ) { runningSlots . remove ( slotKey ) ; UpdateStamp stamp = shardStateManager . getUpdateStamp ( slotKey ) ; shardStateManager . setAllCoarserSlotsDirtyForSlot ( slotKey ) ; //When state gets set to \"X\", before it got persisted, it might get scheduled for rollup //again, if we get delayed metrics. To prevent this we temporarily set last rollup time with current //time. This value wont get persisted. long currentTimeInMillis = clock . now ( ) . getMillis ( ) ; stamp . setLastRollupTimestamp ( currentTimeInMillis ) ; log . debug ( \"SlotKey {} is marked in memory with last rollup time as {}\" , slotKey , currentTimeInMillis ) ; // Update the stamp to Rolled state if and only if the current state // is running. If the current state is active, it means we received // a delayed put which toggled the status to Active. if ( stamp . getState ( ) == UpdateStamp . State . Running ) { stamp . setState ( UpdateStamp . State . Rolled ) ; // Note: Rollup state will be updated to the last ACTIVE // timestamp which caused rollup process to kick in. stamp . setDirty ( true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method inserts a collection of { @link com . rackspacecloud . blueflood . types . IMetric } objects to the appropriate Cassandra column family . Effectively this method is only called to write the raw metrics received during Ingest requests . Another method insertRollups is used by the Rollup processes to write rolled up metrics . [CODESPLIT] @ Override public void insertMetrics ( Collection < IMetric > metrics ) throws IOException { Timer . Context ctx = Instrumentation . getWriteTimerContext ( CassandraModel . CF_METRICS_FULL_NAME ) ; try { if ( isBatchIngestEnabled ) { insertMetricsInBatch ( metrics ) ; } else { insertMetricsIndividually ( metrics ) ; } } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches { @link com . rackspacecloud . blueflood . outputs . formats . MetricData } objects for the specified list of { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } from the specified column family [CODESPLIT] @ Override public Map < Locator , MetricData > getDatapointsForRange ( List < Locator > locators , Range range , Granularity gran ) { Map < Locator , MetricData > metrics = new HashMap < Locator , MetricData > ( ) ; String columnFamily = CassandraModel . getBasicColumnFamilyName ( gran ) ; metrics . putAll ( super . getDatapointsForRange ( locators , range , columnFamily , gran ) ) ; return metrics ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the appropriate IO object which interacts with the Cassandra database . [CODESPLIT] @ Override public DAbstractMetricIO getIO ( String rollupType , Granularity granularity ) { if ( granularity == Granularity . FULL ) return simpleNumberIO ; else return basicIO ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a collection of metrics in a batch using an unlogged { @link BatchStatement } [CODESPLIT] private void insertMetricsInBatch ( Collection < IMetric > metrics ) throws IOException { BatchStatement batch = new BatchStatement ( BatchStatement . Type . UNLOGGED ) ; for ( IMetric metric : metrics ) { BoundStatement bound = simpleNumberIO . getBoundStatementForMetric ( metric ) ; batch . add ( bound ) ; Instrumentation . markFullResMetricWritten ( ) ; Locator locator = metric . getLocator ( ) ; if ( ! LocatorCache . getInstance ( ) . isLocatorCurrentInBatchLayer ( locator ) ) { LocatorCache . getInstance ( ) . setLocatorCurrentInBatchLayer ( locator ) ; batch . add ( locatorIO . getBoundStatementForLocator ( locator ) ) ; } // if we are recording delayed metrics, we may need to do an // extra insert if ( isRecordingDelayedMetrics ) { BoundStatement bs = getBoundStatementForMetricIfDelayed ( metric ) ; if ( bs != null ) { batch . add ( bs ) ; } } } LOG . trace ( String . format ( \"insert batch statement size=%d\" , batch . size ( ) ) ) ; try { DatastaxIO . getSession ( ) . execute ( batch ) ; } catch ( Exception ex ) { Instrumentation . markWriteError ( ) ; LOG . error ( String . format ( \"error writing batch of %d metrics\" , batch . size ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listens on the event . [CODESPLIT] public Emitter on ( String event , Listener fn ) { ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . get ( event ) ; if ( callbacks == null ) { callbacks = new ConcurrentLinkedQueue < Listener > ( ) ; ConcurrentLinkedQueue < Listener > _callbacks = this . callbacks . putIfAbsent ( event , callbacks ) ; if ( _callbacks != null ) { callbacks = _callbacks ; } } callbacks . add ( fn ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a one time listener for the event . [CODESPLIT] public Emitter once ( final String event , final Listener < T > fn ) { Listener on = new Listener < T > ( ) { @ Override public void call ( T ... args ) { Emitter . this . off ( event , this ) ; fn . call ( args ) ; } } ; this . onceCallbacks . put ( fn , on ) ; this . on ( event , on ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all listeners of the specified event . [CODESPLIT] public Emitter off ( String event ) { ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . remove ( event ) ; if ( callbacks != null ) { for ( Listener fn : callbacks ) { this . onceCallbacks . remove ( fn ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes each of listeners with the given args . [CODESPLIT] public Future emit ( String event , T ... args ) { ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . get ( event ) ; if ( callbacks != null ) { callbacks = new ConcurrentLinkedQueue < Listener > ( callbacks ) ; for ( Listener fn : callbacks ) { fn . call ( args ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of listeners for the specified event . [CODESPLIT] public List < Listener > listeners ( String event ) { ConcurrentLinkedQueue < Listener > callbacks = this . callbacks . get ( event ) ; return callbacks != null ? new ArrayList < Listener > ( callbacks ) : new ArrayList < Listener > ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the remote file name . [CODESPLIT] public String getRemoteName ( ) { Date time = new Date ( timestamp ) ; String formattedTime = new SimpleDateFormat ( \"yyyyMMdd_\" ) . format ( time ) ; return formattedTime + System . currentTimeMillis ( ) + \"_\" + Configuration . getInstance ( ) . getStringProperty ( CloudfilesConfig . CLOUDFILES_HOST_UNIQUE_IDENTIFIER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize a Rollup Event and append it to the file . [CODESPLIT] public void append ( RollupEvent rollup ) throws IOException { ensureOpen ( ) ; outputStream . write ( serializer . toBytes ( rollup ) ) ; outputStream . write ( ' ' ) ; outputStream . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the timestamp from a filename . [CODESPLIT] private static long parseTimestamp ( String fileName ) throws NumberFormatException { String numberPart = fileName . substring ( 0 , fileName . length ( ) - 5 ) ; return Long . parseLong ( numberPart ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the Ingest server [CODESPLIT] public void startServer ( ) throws InterruptedException { RouteMatcher router = new RouteMatcher ( ) ; router . get ( \"/v1.0\" , new DefaultHandler ( ) ) ; router . post ( \"/v1.0/multitenant/experimental/metrics\" , new HttpMultitenantMetricsIngestionHandler ( processor , timeout , ENABLE_PER_TENANT_METRICS ) ) ; router . post ( \"/v1.0/:tenantId/experimental/metrics\" , new HttpMetricsIngestionHandler ( processor , timeout , ENABLE_PER_TENANT_METRICS ) ) ; router . post ( \"/v1.0/:tenantId/experimental/metrics/statsd\" , new HttpAggregatedIngestionHandler ( processor , timeout , ENABLE_PER_TENANT_METRICS ) ) ; router . get ( \"/v2.0\" , new DefaultHandler ( ) ) ; router . post ( \"/v2.0/:tenantId/ingest/multi\" , new HttpMultitenantMetricsIngestionHandler ( processor , timeout , ENABLE_PER_TENANT_METRICS ) ) ; router . post ( \"/v2.0/:tenantId/ingest\" , new HttpMetricsIngestionHandler ( processor , timeout , ENABLE_PER_TENANT_METRICS ) ) ; router . post ( \"/v2.0/:tenantId/ingest/aggregated\" , new HttpAggregatedIngestionHandler ( processor , timeout , ENABLE_PER_TENANT_METRICS ) ) ; router . post ( \"/v2.0/:tenantId/ingest/aggregated/multi\" , new HttpAggregatedMultiIngestionHandler ( processor , timeout , ENABLE_PER_TENANT_METRICS ) ) ; router . post ( \"/v2.0/:tenantId/events\" , getHttpEventsIngestionHandler ( ) ) ; final RouteMatcher finalRouter = router ; log . info ( \"Starting metrics listener HTTP server on port {}\" , httpIngestPort ) ; ServerBootstrap server = new ServerBootstrap ( ) ; server . group ( acceptorGroup , workerGroup ) . channel ( NioServerSocketChannel . class ) . childHandler ( new ChannelInitializer < SocketChannel > ( ) { @ Override public void initChannel ( SocketChannel channel ) throws Exception { setupPipeline ( channel , finalRouter ) ; } } ) ; Channel channel = server . bind ( new InetSocketAddress ( httpIngestHost , httpIngestPort ) ) . sync ( ) . channel ( ) ; allOpenChannels . add ( channel ) ; //register the tracker MBean for JMX/jolokia log . info ( \"Registering tracker service\" ) ; Tracker . getInstance ( ) . register ( ) ; log . info ( \"Token search improvements enabled: \" + EXP_TOKEN_SEARCH_IMPROVEMENTS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "determine which DataType to use for serialization . [CODESPLIT] public static Rollup . Type getRollupComputer ( RollupType srcType , Granularity srcGran ) { switch ( srcType ) { case COUNTER : return Rollup . CounterFromCounter ; case TIMER : return Rollup . TimerFromTimer ; case GAUGE : return Rollup . GaugeFromGauge ; case BF_BASIC : return srcGran == Granularity . FULL ? Rollup . BasicFromRaw : Rollup . BasicFromBasic ; case SET : return Rollup . SetFromSet ; default : break ; } throw new IllegalArgumentException ( String . format ( \"Cannot compute rollups for %s from %s\" , srcType . name ( ) , srcGran . shortName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance of this class based on what configuration says our driver should be . [CODESPLIT] public static synchronized IOContainer fromConfig ( ) { if ( FROM_CONFIG_INSTANCE == null ) { String driver = configuration . getStringProperty ( CoreConfig . CASSANDRA_DRIVER ) ; LOG . info ( String . format ( \"Using driver %s\" , driver ) ) ; boolean isRecordingDelayedMetrics = configuration . getBooleanProperty ( CoreConfig . RECORD_DELAYED_METRICS ) ; LOG . info ( String . format ( \"Recording delayed metrics: %s\" , isRecordingDelayedMetrics ) ) ; boolean isDtxIngestBatchEnabled = configuration . getBooleanProperty ( CoreConfig . ENABLE_DTX_INGEST_BATCH ) ; LOG . info ( String . format ( \"Datastax Ingest batch enabled: %s\" , isDtxIngestBatchEnabled ) ) ; FROM_CONFIG_INSTANCE = new IOContainer ( DriverType . getDriverType ( driver ) , isRecordingDelayedMetrics , isDtxIngestBatchEnabled ) ; } return FROM_CONFIG_INSTANCE ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to build the ttl mapping . Only insert to the mapping if the value is a valid date . [CODESPLIT] private boolean put ( ImmutableTable . Builder < Granularity , RollupType , TimeValue > ttlMapBuilder , Configuration config , Granularity gran , RollupType rollupType , TtlConfig configKey ) { int value ; try { value = config . getIntegerProperty ( configKey ) ; if ( value < 0 ) return false ; } catch ( NumberFormatException ex ) { log . trace ( String . format ( \"No valid TTL config set for granularity: %s, rollup type: %s\" , gran . name ( ) , rollupType . name ( ) ) , ex ) ; return false ; } ttlMapBuilder . put ( gran , rollupType , new TimeValue ( value , TimeUnit . DAYS ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge simple numbers with this rollup . [CODESPLIT] protected void computeFromSimpleMetrics ( Points < SimpleNumber > input ) throws IOException { if ( input == null ) { throw new IOException ( \"Null input to create rollup from\" ) ; } if ( input . isEmpty ( ) ) { return ; } Map < Long , Points . Point < SimpleNumber > > points = input . getPoints ( ) ; for ( Map . Entry < Long , Points . Point < SimpleNumber > > item : points . entrySet ( ) ) { this . count += 1 ; SimpleNumber numericMetric = item . getValue ( ) . getData ( ) ; average . handleFullResMetric ( numericMetric . getValue ( ) ) ; variance . handleFullResMetric ( numericMetric . getValue ( ) ) ; minValue . handleFullResMetric ( numericMetric . getValue ( ) ) ; maxValue . handleFullResMetric ( numericMetric . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge rollups into this rollup . [CODESPLIT] protected void computeFromRollupsHelper ( Points < ? extends IBaseRollup > input ) throws IOException { if ( input == null ) { throw new IOException ( \"Null input to create rollup from\" ) ; } if ( input . isEmpty ( ) ) { return ; } // See this and get mind blown: // http://stackoverflow.com/questions/18907262/bounded-wildcard-related-compiler-error Map < Long , ? extends Points . Point < ? extends IBaseRollup > > points = input . getPoints ( ) ; for ( Map . Entry < Long , ? extends Points . Point < ? extends IBaseRollup > > item : points . entrySet ( ) ) { IBaseRollup rollup = item . getValue ( ) . getData ( ) ; if ( ! ( rollup instanceof BaseRollup ) ) { throw new IOException ( \"Cannot create BaseRollup from type \" + rollup . getClass ( ) . getName ( ) ) ; } IBaseRollup baseRollup = ( IBaseRollup ) rollup ; this . count += baseRollup . getCount ( ) ; average . handleRollupMetric ( baseRollup ) ; variance . handleRollupMetric ( baseRollup ) ; minValue . handleRollupMetric ( baseRollup ) ; maxValue . handleRollupMetric ( baseRollup ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a particular rollupType determine what is the proper class to do read / write with and return that [CODESPLIT] public static AbstractMetricsRW getMetricsRWForRollupType ( RollupType rollupType ) { if ( rollupType == null || rollupType == RollupType . BF_BASIC ) { return IOContainer . fromConfig ( ) . getBasicMetricsRW ( ) ; } else { return IOContainer . fromConfig ( ) . getPreAggregatedMetricsRW ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package protect so other classes in this package can call it [CODESPLIT] BoundStatement getBoundStatementForLocator ( Granularity granularity , int slot , Locator locator ) { int shard = Util . getShard ( locator . toString ( ) ) ; return putValue . bind ( SlotKey . of ( granularity , slot , shard ) . toString ( ) , locator . toString ( ) , \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compute the maximum width for each field across a collection of formatters . [CODESPLIT] public static int [ ] computeMaximums ( String [ ] headers , OutputFormatter ... outputs ) { int [ ] max = new int [ headers . length ] ; for ( int i = 0 ; i < headers . length ; i ++ ) max [ i ] = headers [ i ] . length ( ) ; for ( OutputFormatter output : outputs ) { max [ 0 ] = Math . max ( output . host . length ( ) , max [ 0 ] ) ; for ( int i = 1 ; i < headers . length ; i ++ ) max [ i ] = Math . max ( output . results [ i - 1 ] . length ( ) , max [ i ] ) ; } return max ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "formats a header row after maximums have been established . [CODESPLIT] public static String formatHeader ( int [ ] maximums , String [ ] headers ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < headers . length ; i ++ ) sb = sb . append ( formatIn ( headers [ i ] , maximums [ i ] , false ) ) . append ( GAP ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "formats results and sets formattedStrings . [CODESPLIT] public static String [ ] format ( int [ ] maximums , OutputFormatter ... outputs ) { String [ ] formattedStrings = new String [ outputs . length ] ; int pos = 0 ; for ( OutputFormatter output : outputs ) { StringBuilder sb = new StringBuilder ( ) ; sb = sb . append ( formatIn ( output . host , maximums [ 0 ] , false ) ) ; for ( int i = 0 ; i < output . results . length ; i ++ ) sb = sb . append ( GAP ) . append ( formatIn ( output . results [ i ] , maximums [ i + 1 ] , true ) ) ; formattedStrings [ pos ++ ] = sb . toString ( ) ; } return formattedStrings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the different ZooKeeper metrics . [CODESPLIT] private void registerMetrics ( final ObjectName nameObj , MetricRegistry reg ) { reg . register ( MetricRegistry . name ( ZKShardLockManager . class , \"Lock Disinterested Time Millis\" ) , new JmxAttributeGauge ( nameObj , \"LockDisinterestedTimeMillis\" ) ) ; reg . register ( MetricRegistry . name ( ZKShardLockManager . class , \"Min Lock Hold Time Millis\" ) , new JmxAttributeGauge ( nameObj , \"MinLockHoldTimeMillis\" ) ) ; reg . register ( MetricRegistry . name ( ZKShardLockManager . class , \"Seconds Since Last Scavenge\" ) , new JmxAttributeGauge ( nameObj , \"SecondsSinceLastScavenge\" ) ) ; reg . register ( MetricRegistry . name ( ZKShardLockManager . class , \"Zk Connection Status\" ) , new JmxAttributeGauge ( nameObj , \"ZkConnectionStatus\" ) { @ Override public Object getValue ( ) { Object val = super . getValue ( ) ; if ( val . equals ( \"connected\" ) ) { return 1 ; } return 0 ; } } ) ; reg . register ( MetricRegistry . name ( ZKShardLockManager . class , \"Held Shards\" ) , new Gauge < Integer > ( ) { @ Override public Integer getValue ( ) { return getHeldShards ( ) . size ( ) ; } } ) ; reg . register ( MetricRegistry . name ( ZKShardLockManager . class , \"Unheld Shards\" ) , new Gauge < Integer > ( ) { @ Override public Integer getValue ( ) { return getUnheldShards ( ) . size ( ) ; } } ) ; reg . register ( MetricRegistry . name ( ZKShardLockManager . class , \"Error Shards\" ) , new Gauge < Integer > ( ) { @ Override public Integer getValue ( ) { return getErrorShards ( ) . size ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits until the zookeeper connection is available . [CODESPLIT] @ VisibleForTesting boolean waitForZKConnections ( long waitTimeSeconds ) { for ( int i = 0 ; i < waitTimeSeconds ; i ++ ) { if ( connected ) { return connected ; } log . debug ( \"Waiting for connect\" ) ; try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException ex ) { } } return connected ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only called from { @link #init ( TimeValue ) } . [CODESPLIT] @ VisibleForTesting void prefetchLocks ( ) { if ( ! connected ) { log . warn ( \"Cannot connect to Zookeeper; will not perform initial lock acquisition\" ) ; for ( Lock lock : locks . values ( ) ) { lock . connectionLost ( ) ; } } else { log . info ( \"Pre-fetching zookeeper locks for shards\" ) ; boolean isManagingAllShards = locks . size ( ) >= Constants . NUMBER_OF_SHARDS ; int maxLocksToPrefetch = moreThanHalf ( ) ; if ( isManagingAllShards ) { maxLocksToPrefetch = Constants . NUMBER_OF_SHARDS ; } List < Integer > shards = new ArrayList < Integer > ( locks . keySet ( ) ) ; Collections . shuffle ( shards ) ; int locksObtained = 0 ; for ( int shard : shards ) { try { log . debug ( \"Initial lock attempt for shard={}\" , shard ) ; final Lock lock = locks . get ( shard ) ; lock . acquire ( ) . get ( ) ; if ( lock . isHeld ( ) && ++ locksObtained >= maxLocksToPrefetch ) { break ; } } catch ( InterruptedException ex ) { log . warn ( \"Thread exception while acquiring initial locks: \" + ex . getMessage ( ) , ex ) ; } catch ( ExecutionException ex ) { log . error ( \"Problem acquiring lock \" + shard + \" \" + ex . getCause ( ) . getMessage ( ) , ex . getCause ( ) ) ; } } log . info ( \"Finished pre-fetching zookeeper locks\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unsafe method for testing . [CODESPLIT] @ VisibleForTesting void waitForQuiesceUnsafe ( ) { while ( lockTaskCount . get ( ) > 0 ) { log . trace ( \"Waiting for quiesce\" ) ; try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ignore ) { } } // this time out needs to be longer than ZK_LOCK_TIMEOUT for valid tests. try { Thread . sleep ( 2000 ) ; } catch ( InterruptedException ignore ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given the encoded slot key returns the java object of it . For the valid slot keys this function is inverse of { @link #toString () } . @return decoded { @link SlotKey } <code > null< / code > if it s an invalid slotkey . [CODESPLIT] public static SlotKey parse ( String string ) { String [ ] tokens = string . split ( \",\" ) ; if ( tokens . length != 3 ) { return null ; } Granularity granularity = Granularity . fromString ( tokens [ 0 ] ) ; if ( granularity == null ) { return null ; } try { int slot = Integer . parseInt ( tokens [ 1 ] ) ; int shard = Integer . parseInt ( tokens [ 2 ] ) ; return of ( granularity , slot , shard ) ; } catch ( IllegalArgumentException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method creates a collection of slot keys that are within the same timespan of the current slot key but of a finer granularity . For example a slot key of granularity { @link Granularity#MIN_20 MIN_20 } will have four child keys each of granularity { @link Granularity#MIN_5 MIN_5 } . <p > [CODESPLIT] public Collection < SlotKey > getChildrenKeys ( ) { if ( granularity == Granularity . FULL ) { return ImmutableList . of ( ) ; } List < SlotKey > result = new ArrayList < SlotKey > ( ) ; Granularity finer ; try { finer = granularity . finer ( ) ; } catch ( GranularityException e ) { throw new AssertionError ( \"Should not occur.\" ) ; } int factor = finer . numSlots ( ) / granularity . numSlots ( ) ; for ( int i = 0 ; i < factor ; i ++ ) { int childSlot = slot * factor + i ; SlotKey child = SlotKey . of ( finer , childSlot , shard ) ; result . add ( child ) ; result . addAll ( child . getChildrenKeys ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as the method { @link #getChildrenKeys () } except this method returns only the children corresponding to the destination granularity . [CODESPLIT] public Collection < SlotKey > getChildrenKeys ( Granularity destGranularity ) { if ( ! getGranularity ( ) . isCoarser ( destGranularity ) ) { throw new IllegalArgumentException ( String . format ( \"Current granularity [%s] must be coarser than the destination granularity [%s]\" , getGranularity ( ) , destGranularity ) ) ; } List < SlotKey > result = new ArrayList < SlotKey > ( ) ; for ( SlotKey slotKey : this . getChildrenKeys ( ) ) { if ( slotKey . getGranularity ( ) . equals ( destGranularity ) ) { result . add ( slotKey ) ; } } return Collections . unmodifiableList ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method would extrapolate a given slotkey to a corresponding parent slotkey of a given ( higher ) granularity . [CODESPLIT] public SlotKey extrapolate ( Granularity destGranularity ) { if ( destGranularity . equals ( this . getGranularity ( ) ) ) { return this ; } if ( ! destGranularity . isCoarser ( getGranularity ( ) ) ) { throw new IllegalArgumentException ( \"Destination granularity must be coarser than the current granularity\" ) ; } int factor = getGranularity ( ) . numSlots ( ) / destGranularity . numSlots ( ) ; int parentSlot = getSlot ( ) / factor ; return SlotKey . of ( destGranularity , parentSlot , getShard ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the threadpool name . Used to generate metric names and thread names . [CODESPLIT] public ThreadPoolBuilder withName ( String name ) { // ensure we've got a spot to put the thread id. if ( ! name . contains ( \"%d\" ) ) { name = name + \"-%d\" ; } nameMap . putIfAbsent ( name , new AtomicInteger ( 0 ) ) ; int id = nameMap . get ( name ) . incrementAndGet ( ) ; this . poolName = String . format ( name , id ) ; if ( id > 1 ) { this . threadNameFormat = name . replace ( \"%d\" , id + \"-%d\" ) ; } else { this . threadNameFormat = name ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "our own stuff . [CODESPLIT] @ Override public void handle ( ChannelHandlerContext ctx , FullHttpRequest request ) { Tracker . getInstance ( ) . track ( request ) ; requestCount . inc ( ) ; final Timer . Context timerContext = handlerTimer . time ( ) ; long ingestTime = clock . now ( ) . getMillis ( ) ; // this is all JSON. String body = null ; try { String submitterTenantId = request . headers ( ) . get ( HttpMetricsIngestionServer . TENANT_ID_HEADER ) ; body = request . content ( ) . toString ( Constants . DEFAULT_CHARSET ) ; List < AggregatedPayload > bundleList = createBundleList ( body ) ; if ( bundleList . size ( ) > 0 ) { // has aggregated metric bundle in body // convert and add metric bundle to MetricsCollection if valid MetricsCollection collection = new MetricsCollection ( ) ; List < ErrorResponse . ErrorData > errors = new ArrayList < ErrorResponse . ErrorData > ( ) ; // for each metric bundle int delayedMetricsCount = 0 ; int metricsCount = 0 ; for ( AggregatedPayload bundle : bundleList ) { // validate, convert, and add to collection List < ErrorResponse . ErrorData > bundleValidationErrors = bundle . getValidationErrors ( ) ; if ( bundleValidationErrors . isEmpty ( ) ) { // no validation error, add to collection collection . add ( PreaggregateConversions . buildMetricsCollection ( bundle ) ) ; } else { // failed validation, add to error errors . addAll ( bundleValidationErrors ) ; } if ( bundle . hasDelayedMetrics ( ingestTime ) ) { Tracker . getInstance ( ) . trackDelayedAggregatedMetricsTenant ( bundle . getTenantId ( ) , bundle . getTimestamp ( ) , bundle . getDelayTime ( ingestTime ) , bundle . getAllMetricNames ( ) ) ; bundle . markDelayMetricsReceived ( ingestTime ) ; delayedMetricsCount += bundle . getAllMetricNames ( ) . size ( ) ; } else { metricsCount += bundle . getAllMetricNames ( ) . size ( ) ; } } // if has validation errors and no valid metrics if ( ! errors . isEmpty ( ) && collection . size ( ) == 0 ) { // return BAD_REQUEST and error DefaultHandler . sendErrorResponse ( ctx , request , errors , HttpResponseStatus . BAD_REQUEST ) ; return ; } // process valid metrics in collection ListenableFuture < List < Boolean > > futures = processor . apply ( collection ) ; List < Boolean > persisteds = futures . get ( timeout . getValue ( ) , timeout . getUnit ( ) ) ; for ( Boolean persisted : persisteds ) { if ( ! persisted ) { DefaultHandler . sendErrorResponse ( ctx , request , \"Internal error persisting data\" , HttpResponseStatus . INTERNAL_SERVER_ERROR ) ; return ; } } recordPerTenantMetrics ( submitterTenantId , metricsCount , delayedMetricsCount ) ; // return OK or MULTI_STATUS response depending if there were validation errors if ( errors . isEmpty ( ) ) { // no validation error, response OK DefaultHandler . sendResponse ( ctx , request , null , HttpResponseStatus . OK ) ; return ; } else { // has some validation errors, response MULTI_STATUS DefaultHandler . sendErrorResponse ( ctx , request , errors , HttpResponseStatus . MULTI_STATUS ) ; return ; } } else { // no aggregated metric bundles in body, response OK DefaultHandler . sendResponse ( ctx , request , \"No valid metrics\" , HttpResponseStatus . BAD_REQUEST ) ; return ; } } catch ( JsonParseException ex ) { log . debug ( String . format ( \"BAD JSON: %s\" , body ) ) ; DefaultHandler . sendErrorResponse ( ctx , request , ex . getMessage ( ) , HttpResponseStatus . BAD_REQUEST ) ; } catch ( InvalidDataException ex ) { log . debug ( String . format ( \"Invalid request body: %s\" , body ) ) ; DefaultHandler . sendErrorResponse ( ctx , request , ex . getMessage ( ) , HttpResponseStatus . BAD_REQUEST ) ; } catch ( TimeoutException ex ) { DefaultHandler . sendErrorResponse ( ctx , request , \"Timed out persisting metrics\" , HttpResponseStatus . ACCEPTED ) ; } catch ( Exception ex ) { log . debug ( String . format ( \"Exception processing: %s\" , body ) ) ; log . error ( \"Other exception while trying to parse content\" , ex ) ; DefaultHandler . sendErrorResponse ( ctx , request , \"Internal error saving data\" , HttpResponseStatus . INTERNAL_SERVER_ERROR ) ; } finally { timerContext . stop ( ) ; requestCount . dec ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given metricIndex and docCount classifies the data with respect to baseLevel and stores it accordingly . [CODESPLIT] public void add ( String metricIndex , long docCount ) { final String [ ] tokens = metricIndex . split ( METRIC_TOKEN_SEPARATOR_REGEX ) ; /**\n         *\n         * For the ES response shown in class description, for a baseLevel of 2,\n         * the data is classified as follows\n         *\n         * metricNamesWithNextLevelSet    -> {foo.bar.baz}   (Metric Names which are at base + 1 level and also have a subsequent level.)\n         *\n         * For count map, data is in the form {metricIndex, (actualDocCount, childrenTotalDocCount)}\n         *\n         * metricNameBaseLevelMap   -> {foo.bar.baz -> (2, 1)}     (all indexes which are of same length as baseLevel)\n         *\n         */ switch ( tokens . length - baseLevel ) { case 1 : if ( baseLevel > 0 ) { metricNamesWithNextLevelSet . add ( metricIndex . substring ( 0 , metricIndex . lastIndexOf ( \".\" ) ) ) ; } else { metricNamesWithNextLevelSet . add ( metricIndex . substring ( 0 , metricIndex . indexOf ( \".\" ) ) ) ; } //For foo.bar.baz, baseLevel=3 we update children doc count of foo.bar.baz addChildrenDocCount ( metricNameBaseLevelMap , metricIndex . substring ( 0 , metricIndex . lastIndexOf ( \".\" ) ) , docCount ) ; break ; case 0 : setActualDocCount ( metricNameBaseLevelMap , metricIndex , docCount ) ; break ; default : break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares actualDocCount and total docCount of its immediate children of an index to determine if the metric index is a complete metric name or not . [CODESPLIT] private Set < String > getCompleteMetricNames ( Map < String , MetricIndexDocCount > metricIndexMap ) { Set < String > completeMetricNames = new HashSet < String > ( ) ; for ( Map . Entry < String , MetricIndexDocCount > entry : metricIndexMap . entrySet ( ) ) { MetricIndexDocCount metricIndexDocCount = entry . getValue ( ) ; if ( metricIndexDocCount != null ) { //if total doc count is greater than its children docs, its a complete metric name if ( metricIndexDocCount . actualDocCount > 0 && metricIndexDocCount . actualDocCount > metricIndexDocCount . childrenTotalDocCount ) { completeMetricNames . add ( entry . getKey ( ) ) ; } } } return Collections . unmodifiableSet ( completeMetricNames ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Side effect : mark dirty slots as clean [CODESPLIT] protected Map < Granularity , Map < Integer , UpdateStamp > > getDirtySlotsToPersist ( int shard ) { Map < Granularity , Map < Integer , UpdateStamp > > slotTimes = new HashMap < Granularity , Map < Integer , UpdateStamp > > ( ) ; int numUpdates = 0 ; for ( Granularity gran : Granularity . rollupGranularities ( ) ) { Map < Integer , UpdateStamp > dirty = getSlotStateManager ( shard , gran ) . getDirtySlotStampsAndMarkClean ( ) ; slotTimes . put ( gran , dirty ) ; if ( dirty . size ( ) > 0 ) { numUpdates += dirty . size ( ) ; } } if ( numUpdates > 0 ) { // for updates that come by way of scribe, you'll typically see 5 as the number of updates (one for // each granularity).  On rollup slaves the situation is a bit different. You'll see only the slot // of the granularity just written to marked dirty (so 1). log . debug ( \"Found {} dirty slots for shard {}\" , new Object [ ] { numUpdates , shard } ) ; return slotTimes ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method return list of tokens with their parents for a current Discovery object . [CODESPLIT] public static List < Token > getTokens ( Locator locator ) { if ( StringUtils . isEmpty ( locator . getMetricName ( ) ) || StringUtils . isEmpty ( locator . getTenantId ( ) ) ) return new ArrayList <> ( ) ; String [ ] tokens = locator . getMetricName ( ) . split ( Locator . METRIC_TOKEN_SEPARATOR_REGEX ) ; return IntStream . range ( 0 , tokens . length ) . mapToObj ( index -> new Token ( locator , tokens , index ) ) . collect ( toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously insert a rolled up metric to the appropriate column family for a particular granularity [CODESPLIT] public ResultSetFuture putAsync ( Locator locator , long collectionTime , Rollup rollup , Granularity granularity , int ttl ) { Session session = DatastaxIO . getSession ( ) ; // we use batch statement here in case sub classes // override the addRollupToBatch() and provide // multiple statements BatchStatement batch = new BatchStatement ( ) ; addRollupToBatch ( batch , locator , rollup , collectionTime , granularity , ttl ) ; Collection < Statement > statements = batch . getStatements ( ) ; if ( statements . size ( ) == 1 ) { Statement oneStatement = statements . iterator ( ) . next ( ) ; return session . executeAsync ( oneStatement ) ; } else { LOG . debug ( String . format ( \"Using BatchStatement for %d statements\" , statements . size ( ) ) ) ; return session . executeAsync ( batch ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch rollup objects for a { @link com . rackspacecloud . blueflood . types . Locator } from the specified column family and range . [CODESPLIT] protected < T extends Object > Table < Locator , Long , T > getRollupsForLocator ( final Locator locator , String columnFamily , Range range ) { return getValuesForLocators ( new ArrayList < Locator > ( ) { { add ( locator ) ; } } , columnFamily , range ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch values for a list of { @link com . rackspacecloud . blueflood . types . Locator } from the specified column family and range . [CODESPLIT] protected < T extends Object > Table < Locator , Long , T > getValuesForLocators ( final List < Locator > locators , String columnFamily , Range range ) { Table < Locator , Long , T > locatorTimestampRollup = HashBasedTable . create ( ) ; Map < Locator , List < ResultSetFuture > > resultSetFuturesMap = selectForLocatorListAndRange ( columnFamily , locators , range ) ; for ( Map . Entry < Locator , List < ResultSetFuture > > entry : resultSetFuturesMap . entrySet ( ) ) { Locator locator = entry . getKey ( ) ; List < ResultSetFuture > futures = entry . getValue ( ) ; Table < Locator , Long , T > result = toLocatorTimestampValue ( futures , locator , columnFamily , range ) ; locatorTimestampRollup . putAll ( result ) ; } return locatorTimestampRollup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { @link com . datastax . driver . core . PreparedStatement } statement to the { @link com . datastax . driver . core . BatchStatement } to insert this Rollup object to metrics_preaggregated_ { granularity } column family [CODESPLIT] protected void addRollupToBatch ( BatchStatement batch , Locator locator , Rollup rollup , long collectionTime , Granularity granularity , int ttl ) { Statement statement = createStatement ( locator , collectionTime , rollup , granularity , ttl ) ; batch . add ( statement ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously execute select statements against the specified column family for a specific list of { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } [CODESPLIT] protected Map < Locator , List < ResultSetFuture > > selectForLocatorListAndRange ( String columnFamilyName , List < Locator > locators , Range range ) { Map < Locator , List < ResultSetFuture > > locatorFuturesMap = new HashMap < Locator , List < ResultSetFuture > > ( ) ; for ( Locator locator : locators ) { List < ResultSetFuture > existing = locatorFuturesMap . get ( locator ) ; if ( existing == null ) { existing = new ArrayList < ResultSetFuture > ( ) ; locatorFuturesMap . put ( locator , existing ) ; } existing . addAll ( selectForLocatorAndRange ( columnFamilyName , locator , range ) ) ; } return locatorFuturesMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a select statement against the specified column family for a specific { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } [CODESPLIT] protected List < ResultSetFuture > selectForLocatorAndRange ( String columnFamily , Locator locator , Range range ) { List < ResultSetFuture > resultsFutures = new ArrayList < ResultSetFuture > ( ) ; PreparedStatement statement = metricsCFPreparedStatements . cfNameToSelectStatement . get ( columnFamily ) ; resultsFutures . add ( session . executeAsync ( statement . bind ( locator . toString ( ) , range . getStart ( ) , range . getStop ( ) ) ) ) ; return resultsFutures ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Give a { [CODESPLIT] public < T extends Object > Table < Locator , Long , T > toLocatorTimestampValue ( List < ResultSetFuture > futures , Locator locator , String columnFamily , Range range ) { Table < Locator , Long , T > locatorTimestampRollup = HashBasedTable . create ( ) ; for ( ResultSetFuture future : futures ) { try { List < Row > rows = future . getUninterruptibly ( ) . all ( ) ; // we only want to count the number of points we // get when we're querying the metrics_full if ( StringUtils . isNotEmpty ( columnFamily ) && columnFamily . equals ( CassandraModel . CF_METRICS_FULL_NAME ) ) { Instrumentation . getRawPointsIn5MinHistogram ( ) . update ( rows . size ( ) ) ; } for ( Row row : rows ) { String key = row . getString ( DMetricsCFPreparedStatements . KEY ) ; Locator loc = Locator . createLocatorFromDbKey ( key ) ; Long hash = row . getLong ( DMetricsCFPreparedStatements . COLUMN1 ) ; locatorTimestampRollup . put ( loc , hash , ( T ) fromByteBuffer ( row . getBytes ( DMetricsCFPreparedStatements . VALUE ) ) ) ; } } catch ( Exception ex ) { Instrumentation . markReadError ( ) ; LOG . error ( String . format ( \"error reading metric for locator %s, column family '%s', range %s\" , locator , columnFamily , range . toString ( ) ) , ex ) ; } } return locatorTimestampRollup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We need to derive ranges ( actual times ) from slots ( which are fixed integers that wrap ) when we discover a late slot . These ranges can be derived from a reference point ( which is usually something like now ) . [CODESPLIT] public Range deriveRange ( int slot , long referenceMillis ) { // referenceMillis refers to the current time in reference to the range we want to generate from the supplied  // slot. This implies that the range we wish to return is before slot(reference).  allow for slot wrapping. referenceMillis = snapMillis ( referenceMillis ) ; int refSlot = slot ( referenceMillis ) ; int slotDiff = slot > refSlot ? ( numSlots ( ) - slot + refSlot ) : ( refSlot - slot ) ; long rangeStart = referenceMillis - slotDiff * milliseconds ( ) ; return new Range ( rangeStart , rangeStart + milliseconds ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return granularity that maps most closely to requested number of points using the algorithm specified in the { @code GET_BY_POINTS_SELECTION_ALGORITHM } config value . See { @link #granularityFromPointsInInterval ( String long long int String long ) } . [CODESPLIT] public static Granularity granularityFromPointsInInterval ( String tenantid , long from , long to , int points ) { return granularityFromPointsInInterval ( tenantid , from , to , points , GET_BY_POINTS_SELECTION_ALGORITHM , GET_BY_POINTS_ASSUME_INTERVAL , DEFAULT_TTL_COMPARISON_SOURCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @code ttlComparisonClock } defaults to { @link #DEFAULT_TTL_COMPARISON_SOURCE } . [CODESPLIT] public static Granularity granularityFromPointsInInterval ( String tenantid , long from , long to , int points , String algorithm , long assumedIntervalMillis ) { return granularityFromPointsInInterval ( tenantid , from , to , points , algorithm , assumedIntervalMillis , DEFAULT_TTL_COMPARISON_SOURCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return granularity that maps most closely to requested number of points based on provided selection algorithm [CODESPLIT] public static Granularity granularityFromPointsInInterval ( String tenantid , long from , long to , int points , String algorithm , long assumedIntervalMillis , Clock ttlComparisonClock ) { if ( from >= to ) { throw new RuntimeException ( \"Invalid interval specified for fromPointsInInterval\" ) ; } double requestedDuration = to - from ; if ( algorithm . startsWith ( \"GEOMETRIC\" ) ) return granularityFromPointsGeometric ( tenantid , from , to , requestedDuration , points , assumedIntervalMillis , ttlComparisonClock ) ; else if ( algorithm . startsWith ( \"LINEAR\" ) ) return granularityFromPointsLinear ( requestedDuration , points , assumedIntervalMillis ) ; else if ( algorithm . startsWith ( \"LESSTHANEQUAL\" ) ) return granularityFromPointsLessThanEqual ( requestedDuration , points , assumedIntervalMillis ) ; return granularityFromPointsGeometric ( tenantid , from , to , requestedDuration , points , assumedIntervalMillis , ttlComparisonClock ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the granularity in the interval that will yield a number of data points that are closest to the requested points but < = requested points . [CODESPLIT] private static Granularity granularityFromPointsLessThanEqual ( double requestedDuration , int points , long assumedIntervalMillis ) { Granularity gran = granularityFromPointsLinear ( requestedDuration , points , assumedIntervalMillis ) ; if ( requestedDuration / gran . milliseconds ( ) > points ) { try { gran = gran . coarser ( ) ; } catch ( GranularityException e ) { /* do nothing, already at 1440m */ } } return gran ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the granularity in the interval that will yield a number of data points that are close to $points in terms of linear distance . [CODESPLIT] private static Granularity granularityFromPointsLinear ( double requestedDuration , int points , long assumedIntervalMillis ) { int closest = Integer . MAX_VALUE ; int diff = 0 ; Granularity gran = null ; for ( Granularity g : Granularity . granularities ( ) ) { if ( g == Granularity . FULL ) diff = ( int ) Math . abs ( points - ( requestedDuration / assumedIntervalMillis ) ) ; else diff = ( int ) Math . abs ( points - ( requestedDuration / g . milliseconds ( ) ) ) ; if ( diff < closest ) { closest = diff ; gran = g ; } else { break ; } } return gran ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set the server time in millis . [CODESPLIT] public synchronized void setServerTime ( long millis ) { log . info ( \"Manually setting server time to {}  {}\" , millis , new java . util . Date ( millis ) ) ; context . setCurrentTimeMillis ( millis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a shard to be managed ( via JMX ) [CODESPLIT] public void addShard ( Integer shard ) { if ( ! shardStateManager . getManagedShards ( ) . contains ( shard ) ) context . addShard ( shard ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a shard from being managed ( via JMX ) [CODESPLIT] public void removeShard ( Integer shard ) { if ( shardStateManager . getManagedShards ( ) . contains ( shard ) ) context . removeShard ( shard ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For all of these { @link Locator } s get a unique list of { @link Token } s which are not in token cache [CODESPLIT] static Set < Token > getUniqueTokens ( final List < Locator > locators ) { return Token . getUniqueTokens ( locators . stream ( ) ) . filter ( token -> ! TokenCache . getInstance ( ) . isTokenCurrent ( token ) ) . collect ( toSet ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all { @link Locator } s corresponding to the metrics which are not current . [CODESPLIT] static List < Locator > getLocators ( final List < List < IMetric > > input ) { //converting list of lists of metrics to flat list of locators that are not current. return input . stream ( ) . flatMap ( List :: stream ) . map ( IMetric :: getLocator ) . filter ( locator -> ! LocatorCache . getInstance ( ) . isLocatorCurrentInTokenDiscoveryLayer ( locator ) ) . collect ( toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given batch of metrics insert unique tokens using { @link TokenDiscoveryIO } . [CODESPLIT] public ListenableFuture < Boolean > processTokens ( final List < List < IMetric > > input ) { return getThreadPool ( ) . submit ( ( ) -> { boolean success = true ; List < Locator > locators = getLocators ( input ) ; List < Token > tokens = new ArrayList <> ( ) ; tokens . addAll ( getUniqueTokens ( locators ) ) ; if ( tokens . size ( ) > 0 ) { for ( TokenDiscoveryIO io : tokenDiscoveryIOs ) { try { io . insertDiscovery ( tokens ) ; } catch ( Exception ex ) { getLogger ( ) . error ( ex . getMessage ( ) , ex ) ; writeErrorMeters . get ( io . getClass ( ) ) . mark ( ) ; success = false ; } } } if ( success && tokens . size ( ) > 0 ) { tokens . stream ( ) . filter ( token -> ! token . isLeaf ( ) ) //do not cache leaf nodes . forEach ( token -> { //updating token cache TokenCache . getInstance ( ) . setTokenCurrent ( token ) ; } ) ; locators . stream ( ) . forEach ( locator -> { //updating locator cache LocatorCache . getInstance ( ) . setLocatorCurrentInTokenDiscoveryLayer ( locator ) ; } ) ; } return success ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a { [CODESPLIT] public static void instrument ( final ThreadPoolExecutor executor , String threadPoolName ) { MetricRegistry registry = Metrics . getRegistry ( ) ; registry . register ( name ( threadPoolName , \"queue-size\" ) , new Gauge < Integer > ( ) { @ Override public Integer getValue ( ) { return executor . getQueue ( ) . size ( ) ; } } ) ; registry . register ( name ( threadPoolName , \"queue-max\" ) , new Gauge < Integer > ( ) { @ Override public Integer getValue ( ) { return executor . getQueue ( ) . size ( ) + executor . getQueue ( ) . remainingCapacity ( ) ; } } ) ; registry . register ( name ( threadPoolName , \"threadpool-active\" ) , new Gauge < Integer > ( ) { @ Override public Integer getValue ( ) { return executor . getActiveCount ( ) ; } } ) ; registry . register ( name ( threadPoolName , \"threadpool-max\" ) , new Gauge < Integer > ( ) { @ Override public Integer getValue ( ) { return executor . getMaximumPoolSize ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the set of unique Cassandra hosts from configuration file . If a single host appears multiple times in the configuration only one will be listed . [CODESPLIT] public Set < String > getUniqueHosts ( ) { Set < String > uniqueHosts = new HashSet < String > ( ) ; Collections . addAll ( uniqueHosts , config . getStringProperty ( CoreConfig . CASSANDRA_HOSTS ) . split ( \",\" ) ) ; return uniqueHosts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a set of unique Cassandra hosts with Binary Transport protocol enabled from configuration file . This may or may not be different than { @link #getUniqueHosts () } [CODESPLIT] protected Set < String > getUniqueBinaryTransportHosts ( ) { Set < String > uniqueHosts = new HashSet < String > ( ) ; Collections . addAll ( uniqueHosts , config . getStringProperty ( CoreConfig . CASSANDRA_BINXPORT_HOSTS ) . split ( \",\" ) ) ; return uniqueHosts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a set of unique Cassandra hosts with Binary Transport protocol enabled from configuration file as a set of { @link java . net . InetSocketAddress } objects . [CODESPLIT] public Set < InetSocketAddress > getUniqueBinaryTransportHostsAsInetSocketAddresses ( ) { Set < String > hosts = getUniqueBinaryTransportHosts ( ) ; Set < InetSocketAddress > inetAddresses = new HashSet < InetSocketAddress > ( ) ; for ( String host : hosts ) { String [ ] parts = host . split ( \":\" ) ; InetSocketAddress inetSocketAddress ; if ( parts . length == 1 ) { inetSocketAddress = new InetSocketAddress ( parts [ 0 ] , config . getIntegerProperty ( CoreConfig . CASSANDRA_BINXPORT_PORT ) ) ; } else { inetSocketAddress = new InetSocketAddress ( parts [ 0 ] , Integer . parseInt ( parts [ 1 ] ) ) ; } inetAddresses . add ( inetSocketAddress ) ; } return inetAddresses ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the number of max connections per Cassandra hosts [CODESPLIT] public int getMaxConnPerHost ( int numHosts ) { int maxConns = config . getIntegerProperty ( CoreConfig . MAX_CASSANDRA_CONNECTIONS ) ; return maxConns / numHosts + ( maxConns % numHosts == 0 ? 0 : 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize without sum attribute . This is used by { @link GaugeSerDes } [CODESPLIT] protected void serializeRollupV1 ( BaseRollup baseRollup , CodedOutputStream protobufOut ) throws IOException { protobufOut . writeRawByte ( Constants . VERSION_1_ROLLUP ) ; serializeBaseRollupHelper ( baseRollup , protobufOut ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds ES query to grab tokens corresponding to the given query glob . For a given query foo . bar . * we would like to grab all the tokens with parent as foo . bar [CODESPLIT] private String getTokenQueryDslString ( String tenantId , String query ) { String [ ] queryTokens = query . split ( Locator . METRIC_TOKEN_SEPARATOR_REGEX ) ; String lastToken = queryTokens [ queryTokens . length - 1 ] ; /**\n         * Builds parent part of the query for the given input query glob tokens.\n         * For a given query foo.bar.*, parent part is foo.bar\n         *\n         * For example:\n         *\n         *  For query = foo.bar.*\n         *          { \"term\": {  \"parent\": \"foo.bar\" }}\n         *\n         *  For query = foo.*.*\n         *          { \"regexp\": {  \"parent\": \"foo.[^.]+\" }}\n         *\n         *  For query = foo.b*.*\n         *          { \"regexp\": {  \"parent\": \"foo.b[^.]*\" }}\n         */ String parentString = getParentString ( queryTokens ) ; String tenantIdTermQueryString = getTermQueryString ( ESFieldLabel . tenantId . name ( ) , tenantId ) ; List < String > mustNodes = new ArrayList <> ( ) ; mustNodes . add ( tenantIdTermQueryString ) ; mustNodes . add ( parentString ) ; // For example: if query=foo.bar.*, we can just get every token for the parent=foo.bar // but if query=foo.bar.b*, we want to add the token part of the query for \"b*\" if ( ! lastToken . equals ( \"*\" ) ) { String tokenQString ; GlobPattern pattern = new GlobPattern ( lastToken ) ; if ( pattern . hasWildcard ( ) ) { String compiledString = pattern . compiled ( ) . toString ( ) ; tokenQString = getRegexpQueryString ( ESFieldLabel . token . name ( ) , compiledString ) ; } else { tokenQString = getTermQueryString ( ESFieldLabel . token . name ( ) , lastToken ) ; } mustNodes . add ( tokenQString ) ; } String mustQueryString = getMustQueryString ( mustNodes ) ; String boolQueryString = getBoolQueryString ( mustQueryString ) ; // replace one '\\' char with two '\\\\' boolQueryString = boolQueryString . replaceAll ( \"\\\\\\\\\" , \"\\\\\\\\\\\\\\\\\" ) ; return boolQueryString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given glob gives regex for { @code Locator . METRIC_TOKEN_SEPARATOR } separated tokens [CODESPLIT] protected String getRegexToHandleTokens ( GlobPattern globPattern ) { String [ ] queryRegexParts = globPattern . compiled ( ) . toString ( ) . split ( \"\\\\\\\\.\" ) ; return Arrays . stream ( queryRegexParts ) . map ( this :: convertRegexToCaptureUptoNextToken ) . collect ( joining ( Locator . METRIC_TOKEN_SEPARATOR_REGEX ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If index () fails for whatever reason it always throws IOException because indexing failed for Elasticsearch . [CODESPLIT] public void index ( final String urlFormat , final String bulkString ) throws IOException { String tempUrl = String . format ( urlFormat , getNextBaseUrl ( ) ) ; HttpEntity entity = new NStringEntity ( bulkString , ContentType . APPLICATION_JSON ) ; int statusCode = 0 ; /*\n        Here I am using Queue to keep a round-robin selection of next base url. If current base URL fails for\n        whatever reason (with response == null), then in catch block, I am enqueueing the next base URL so that\n        in next iteration call picks up the new URL. If URL works, queue will be empty and loop will break out.\n        */ Queue < String > callQ = new LinkedList <> ( ) ; callQ . add ( tempUrl ) ; int callCount = 0 ; while ( ! callQ . isEmpty ( ) && callCount < MAX_CALL_COUNT ) { callCount ++ ; String url = callQ . remove ( ) ; logger . debug ( \"Using url [{}]\" , url ) ; HttpPost httpPost = new HttpPost ( url ) ; httpPost . setHeaders ( getHeaders ( ) ) ; httpPost . setEntity ( entity ) ; CloseableHttpResponse response = null ; try { logger . debug ( \"ElasticsearchRestHelper.index Thread name in use: [{}]\" , Thread . currentThread ( ) . getName ( ) ) ; response = closeableHttpClient . execute ( httpPost ) ; statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; String str = EntityUtils . toString ( response . getEntity ( ) ) ; EntityUtils . consume ( response . getEntity ( ) ) ; if ( statusCode != HttpStatus . SC_OK && statusCode != HttpStatus . SC_CREATED ) { logger . error ( \"index method failed with status code: {} and error: {}\" , statusCode , str ) ; } } catch ( Exception e ) { if ( response == null ) { logger . error ( \"index method failed with message: {}\" , e . getMessage ( ) ) ; url = String . format ( urlFormat , getNextBaseUrl ( ) ) ; callQ . add ( url ) ; } else { logger . error ( \"index method failed with status code: {} and exception message: {}\" , statusCode , e . getMessage ( ) ) ; } } finally { if ( response != null ) { response . close ( ) ; } } } if ( statusCode != HttpStatus . SC_OK && statusCode != HttpStatus . SC_CREATED ) throw new IOException ( \"Elasticsearch indexing failed with status code: [\" + statusCode + \"]\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "iterate over all column families that store metrics . [CODESPLIT] public static Iterable < MetricColumnFamily > getMetricColumnFamilies ( ) { return new Iterable < MetricColumnFamily > ( ) { @ Override public Iterator < MetricColumnFamily > iterator ( ) { return new Iterator < MetricColumnFamily > ( ) { private int pos = 0 ; @ Override public boolean hasNext ( ) { return pos < METRIC_COLUMN_FAMILES . length ; } @ Override public MetricColumnFamily next ( ) { return METRIC_COLUMN_FAMILES [ pos ++ ] ; } @ Override public void remove ( ) { throw new NoSuchMethodError ( \"Not implemented\" ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "should be populated . [CODESPLIT] private static Map < String , Object > parseOptions ( String [ ] args ) { final GnuParser parser = new GnuParser ( ) ; final Map < String , Object > options = new HashMap < String , Object > ( ) ; try { final long now = System . currentTimeMillis ( ) ; CommandLine line = parser . parse ( cliOptions , args ) ; options . put ( SRC , line . getOptionValue ( SRC ) ) ; options . put ( DST , line . getOptionValue ( DST ) ) ; // default range is one year ago until now. options . put ( FROM , line . hasOption ( FROM ) ? parseDateTime ( line . getOptionValue ( FROM ) ) : now - ( 365L * 24L * 60L * 60L * 1000L ) ) ; options . put ( TO , line . hasOption ( TO ) ? parseDateTime ( line . getOptionValue ( TO ) ) : now ) ; options . put ( LIMIT , line . hasOption ( LIMIT ) ? Integer . parseInt ( line . getOptionValue ( LIMIT ) ) : Integer . MAX_VALUE ) ; options . put ( SKIP , line . hasOption ( SKIP ) ? Integer . parseInt ( line . getOptionValue ( SKIP ) ) : 0 ) ; options . put ( BATCH_SIZE , line . hasOption ( BATCH_SIZE ) ? Integer . parseInt ( line . getOptionValue ( BATCH_SIZE ) ) : 100 ) ; // create a mapping of all cf names -> cf. // then determine which column family to process. Map < String , ColumnFamily < Locator , Long > > nameToCf = new HashMap < String , ColumnFamily < Locator , Long > > ( ) { { for ( CassandraModel . MetricColumnFamily cf : CassandraModel . getMetricColumnFamilies ( ) ) { put ( cf . getName ( ) , cf ) ; } } } ; if ( nameToCf . get ( line . getOptionValue ( COLUMN_FAMILY ) ) == null ) { throw new ParseException ( \"Invalid column family\" ) ; } CassandraModel . MetricColumnFamily columnFamily = ( CassandraModel . MetricColumnFamily ) nameToCf . get ( line . getOptionValue ( COLUMN_FAMILY ) ) ; options . put ( COLUMN_FAMILY , columnFamily ) ; options . put ( TTL , line . hasOption ( TTL ) ? Integer . parseInt ( line . getOptionValue ( TTL ) ) : ( int ) ( 5 * columnFamily . getDefaultTTL ( ) . toSeconds ( ) ) ) ; options . put ( READ_THREADS , line . hasOption ( READ_THREADS ) ? Integer . parseInt ( line . getOptionValue ( READ_THREADS ) ) : 1 ) ; options . put ( WRITE_THREADS , line . hasOption ( WRITE_THREADS ) ? Integer . parseInt ( line . getOptionValue ( WRITE_THREADS ) ) : 1 ) ; options . put ( VERIFY , line . hasOption ( VERIFY ) ) ; options . put ( DISCOVER , line . hasOption ( DISCOVER ) ? NodeDiscoveryType . RING_DESCRIBE : NodeDiscoveryType . NONE ) ; options . put ( RATE , line . hasOption ( RATE ) ? Integer . parseInt ( line . getOptionValue ( RATE ) ) : 500 ) ; } catch ( ParseException ex ) { HelpFormatter helpFormatter = new HelpFormatter ( ) ; helpFormatter . printHelp ( \"bf-migrate\" , cliOptions ) ; System . exit ( - 1 ) ; } return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a way for the sub class to get a { @link java . nio . ByteBuffer } representation of a certain Rollup object . [CODESPLIT] @ Override protected ByteBuffer toByteBuffer ( Object value ) { if ( ! ( value instanceof BluefloodTimerRollup ) ) { throw new IllegalArgumentException ( \"toByteBuffer(): expecting BluefloodTimerRollup class but got \" + value . getClass ( ) . getSimpleName ( ) ) ; } BluefloodTimerRollup TimerRollup = ( BluefloodTimerRollup ) value ; return serDes . serialize ( TimerRollup ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a collection of metrics to the metrics_preaggregated_full column family [CODESPLIT] @ Override public void insertMetrics ( Collection < IMetric > metrics ) throws IOException { insertMetrics ( metrics , Granularity . FULL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a collection of metrics to the correct column family based on the specified granularity [CODESPLIT] @ Override public void insertMetrics ( Collection < IMetric > metrics , Granularity granularity ) throws IOException { try { AstyanaxWriter . getInstance ( ) . insertMetrics ( metrics , CassandraModel . getPreaggregatedColumnFamily ( granularity ) , isRecordingDelayedMetrics , clock ) ; } catch ( ConnectionException ex ) { throw new IOException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches { @link com . rackspacecloud . blueflood . outputs . formats . MetricData } objects for the specified { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } from the specified column family [CODESPLIT] @ Override public MetricData getDatapointsForRange ( final Locator locator , Range range , Granularity gran ) { return AstyanaxReader . getInstance ( ) . getDatapointsForRange ( locator , range , gran ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches { @link com . rackspacecloud . blueflood . outputs . formats . MetricData } objects for the specified list of { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } from the specified column family [CODESPLIT] @ Override public Map < Locator , MetricData > getDatapointsForRange ( List < Locator > locators , Range range , Granularity gran ) { return AstyanaxReader . getInstance ( ) . getDatapointsForRange ( locators , range , gran ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches a { @link com . rackspacecloud . blueflood . types . Points } object for a particular locator and rollupType from the specified column family and range [CODESPLIT] @ Override public < T extends Rollup > Points < T > getDataToRollup ( final Locator locator , RollupType rollupType , Range range , String columnFamilyName ) throws IOException { ColumnFamily cf = CassandraModel . getColumnFamily ( columnFamilyName ) ; // a quick n dirty hack, this code will go away someday Granularity granularity = CassandraModel . getGranularity ( cf ) ; Class < ? extends Rollup > rollupClass = RollupType . classOf ( rollupType , granularity ) ; return AstyanaxReader . getInstance ( ) . getDataToRoll ( rollupClass , locator , range , cf ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a raw metric ( not its rolled up value ) to the proper column family [CODESPLIT] public ResultSetFuture insertRawAsync ( IMetric metric ) { BoundStatement bound = getBoundStatementForMetric ( metric ) ; return session . executeAsync ( bound ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a { @link BoundStatement } for a particular metric . The statement could be part of a BatchStatement or it could be executed as is . [CODESPLIT] public BoundStatement getBoundStatementForMetric ( IMetric metric ) { return metricsCFPreparedStatements . insertToMetricsBasicFullStatement . bind ( metric . getLocator ( ) . toString ( ) , metric . getCollectionTime ( ) , serDes . serialize ( metric . getMetricValue ( ) ) , metric . getTtlInSeconds ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This methods gets locators to rollup a slot . [CODESPLIT] protected Set < Locator > getLocators ( RollupExecutionContext executionContext , boolean isReroll , Granularity delayedMetricsRerollGranularity , Granularity delayedMetricsStorageGranularity ) { Set < Locator > locators = new HashSet < Locator > ( ) ; //if delayed metric tracking is enabled, if its re-roll, if slot granularity is no coarser than // DELAYED_METRICS_REROLL_GRANULARITY, get delayed locators if ( RECORD_DELAYED_METRICS && isReroll && ! getGranularity ( ) . isCoarser ( delayedMetricsRerollGranularity ) ) { if ( getGranularity ( ) . isCoarser ( delayedMetricsStorageGranularity ) ) { // For example, if we are re-rolling a 60m slot, and we store delayed metrics at 20m, we need to // grab delayed metrics for 3 * 20m slots corresponding to the 60m slot. for ( SlotKey slotKey : parentSlotKey . getChildrenKeys ( delayedMetricsStorageGranularity ) ) { locators . addAll ( getDelayedLocators ( executionContext , slotKey ) ) ; } } else { locators = getDelayedLocators ( executionContext , parentSlotKey . extrapolate ( delayedMetricsStorageGranularity ) ) ; } } else { locators = getLocators ( executionContext ) ; } return locators ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns a list of { @link MetricName } s matching the given glob query . [CODESPLIT] public List < MetricName > getMetricNames ( final String tenant , final String query ) throws Exception { Timer . Context esMetricNamesQueryTimerCtx = esMetricNamesQueryTimer . time ( ) ; String response ; try { String regexString = regexToGrabCurrentAndNextLevel ( query ) ; // replace one '\\' char with two '\\\\' regexString = regexString . replaceAll ( \"\\\\\\\\\" , \"\\\\\\\\\\\\\\\\\" ) ; response = getMetricNamesFromES ( tenant , regexString ) ; } finally { esMetricNamesQueryTimerCtx . stop ( ) ; } // For example, if query = foo.bar.*, base level is 3 which is equal to the number of tokens in the query. int baseLevel = getTotalTokens ( query ) ; MetricIndexData metricIndexData = getMetricIndexData ( response , baseLevel ) ; List < MetricName > metricNames = new ArrayList <> ( ) ; //Metric Names matching query which have next level metricNames . addAll ( metricIndexData . getMetricNamesWithNextLevel ( ) . stream ( ) . map ( x -> new MetricName ( x , false ) ) . collect ( toSet ( ) ) ) ; //complete metric names matching query metricNames . addAll ( metricIndexData . getCompleteMetricNamesAtBaseLevel ( ) . stream ( ) . map ( x -> new MetricName ( x , true ) ) . collect ( toSet ( ) ) ) ; return metricNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs terms aggregation by metric_name which returns doc_count by metric_name index that matches the given regex . [CODESPLIT] private String getMetricNamesFromES ( final String tenant , final String regexMetricName ) throws IOException { String metricNamesFromElasticsearchQueryString = String . format ( queryToFetchMetricNamesFromElasticsearchFormat , tenant , regexMetricName , regexMetricName ) ; return elasticsearchRestHelper . fetchDocuments ( ELASTICSEARCH_INDEX_NAME_READ , ELASTICSEARCH_DOCUMENT_TYPE , tenant , metricNamesFromElasticsearchQueryString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns regex which could grab metric names from current level to the next level for a given query . [CODESPLIT] protected String regexToGrabCurrentAndNextLevel ( final String query ) { if ( StringUtils . isEmpty ( query ) ) { throw new IllegalArgumentException ( \"Query(glob) string cannot be null/empty\" ) ; } String queryRegex = getRegex ( query ) ; int totalQueryTokens = getTotalTokens ( query ) ; if ( totalQueryTokens == 1 ) { // get metric names which matches the given query and have a next level, // Ex: For metric foo.bar.baz.qux, if query=*, we should get foo.bar. We are not // grabbing 0 level as it will give back bar, baz, qux because of the way data is structured. String baseRegex = convertRegexToCaptureUptoNextToken ( queryRegex ) ; return baseRegex + METRIC_TOKEN_SEPARATOR_REGEX + REGEX_TO_GRAB_SINGLE_TOKEN ; } else { String [ ] queryRegexParts = queryRegex . split ( \"\\\\\\\\.\" ) ; String queryRegexUptoPrevLevel = StringUtils . join ( queryRegexParts , METRIC_TOKEN_SEPARATOR_REGEX , 0 , totalQueryTokens - 1 ) ; String baseRegex = convertRegexToCaptureUptoNextToken ( queryRegexUptoPrevLevel ) ; String queryRegexLastLevel = queryRegexParts [ totalQueryTokens - 1 ] ; String lastTokenRegex = convertRegexToCaptureUptoNextToken ( queryRegexLastLevel ) ; // Ex: For metric foo.bar.baz.qux.xxx, if query=foo.bar.b*, get foo.bar.baz, foo.bar.baz.qux // In this case baseRegex = \"foo.bar\", lastTokenRegex = \"b[^.]*\"' and the final // regex is foo\\.bar\\.b[^.]*(\\.[^.]*){0,1} return baseRegex + METRIC_TOKEN_SEPARATOR_REGEX + lastTokenRegex + \"(\" + METRIC_TOKEN_SEPARATOR_REGEX + REGEX_TO_GRAB_SINGLE_TOKEN + \")\" + \"{0,1}\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start background storage management and uploading tasks . [CODESPLIT] public synchronized void start ( ) { if ( uploaderThread != null ) { throw new RuntimeException ( \"StorageManager is already started\" ) ; } fileUploader = new DoneFileUploader ( ) ; uploaderThread = new Thread ( fileUploader , \"StorageManager uploader\" ) ; uploaderThread . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop background storage management . [CODESPLIT] public synchronized void stop ( ) throws IOException { if ( uploaderThread == null ) { throw new RuntimeException ( \"Not running\" ) ; } uploaderThread . interrupt ( ) ; uploaderThread = null ; fileUploader . shutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge simple numbers with this rollup . [CODESPLIT] protected void computeFromSimpleMetrics ( Points < SimpleNumber > input ) throws IOException { super . computeFromSimpleMetrics ( input ) ; if ( input . isEmpty ( ) ) { return ; } Map < Long , Points . Point < SimpleNumber > > points = input . getPoints ( ) ; for ( Map . Entry < Long , Points . Point < SimpleNumber > > item : points . entrySet ( ) ) { SimpleNumber numericMetric = item . getValue ( ) . getData ( ) ; sum += numericMetric . getValue ( ) . doubleValue ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "merge rollups into this rollup . [CODESPLIT] protected void computeFromRollups ( Points < BasicRollup > input ) throws IOException { computeFromRollupsHelper ( input ) ; if ( input . isEmpty ( ) ) { return ; } // See this and get mind blown: // http://stackoverflow.com/questions/18907262/bounded-wildcard-related-compiler-error Map < Long , ? extends Points . Point < ? extends BasicRollup > > points = input . getPoints ( ) ; for ( Map . Entry < Long , ? extends Points . Point < ? extends BasicRollup > > item : points . entrySet ( ) ) { BasicRollup rollup = item . getValue ( ) . getData ( ) ; if ( ! ( rollup instanceof BasicRollup ) ) { throw new IOException ( \"Cannot create BasicRollup from type \" + rollup . getClass ( ) . getName ( ) ) ; } BasicRollup basicRollup = ( BasicRollup ) rollup ; sum += basicRollup . getSum ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if Locator is recently inserted in the batch layer [CODESPLIT] public synchronized boolean isLocatorCurrentInBatchLayer ( Locator loc ) { LocatorCacheEntry entry = insertedLocators . getIfPresent ( loc . toString ( ) ) ; return entry != null && entry . isBatchCurrent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if Locator is recently inserted in the discovery layer [CODESPLIT] public synchronized boolean isLocatorCurrentInDiscoveryLayer ( Locator loc ) { LocatorCacheEntry entry = insertedLocators . getIfPresent ( loc . toString ( ) ) ; return entry != null && entry . isDiscoveryCurrent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if Locator is recently inserted in the token discovery layer [CODESPLIT] public synchronized boolean isLocatorCurrentInTokenDiscoveryLayer ( Locator loc ) { LocatorCacheEntry entry = insertedLocators . getIfPresent ( loc . toString ( ) ) ; return entry != null && entry . isTokenDiscoveryCurrent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the delayed locator is recently inserted for a given slot [CODESPLIT] public synchronized boolean isDelayedLocatorForASlotCurrent ( int slot , Locator locator ) { return insertedDelayedLocators . getIfPresent ( getLocatorSlotKey ( slot , locator ) ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marks the delayed locator as recently inserted for a given slot [CODESPLIT] public synchronized void setDelayedLocatorForASlotCurrent ( int slot , Locator locator ) { insertedDelayedLocators . put ( getLocatorSlotKey ( slot , locator ) , Boolean . TRUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a way for the sub class to get a { @link java . nio . ByteBuffer } representation of a certain Rollup object . [CODESPLIT] @ Override protected ByteBuffer toByteBuffer ( Object value ) { if ( ! ( value instanceof BluefloodSetRollup ) ) { throw new IllegalArgumentException ( \"toByteBuffer(): expecting BluefloodSetRollup class but got \" + value . getClass ( ) . getSimpleName ( ) ) ; } BluefloodSetRollup setRollup = ( BluefloodSetRollup ) value ; return serDes . serialize ( setRollup ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "given a start and stop time return an iterator over ranges in * this * granularity that should be rolled up into single points in the next coarser granularity . [CODESPLIT] public static Iterable < Range > getRangesToRollup ( Granularity g , final long startMillis , final long stopMillis ) throws GranularityException { final long snappedStartMillis = g . coarser ( ) . snapMillis ( startMillis ) ; final long snappedStopMillis = g . coarser ( ) . snapMillis ( stopMillis + g . coarser ( ) . milliseconds ( ) ) ; return new IntervalRangeIterator ( g , snappedStartMillis , snappedStopMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a mapping of ranges in the coarser granularity to the sub - ranges in finer granularity [CODESPLIT] public static Map < Range , Iterable < Range > > mapFinerRanges ( Granularity g , Range range ) throws GranularityException { if ( range . getStart ( ) >= range . getStop ( ) ) throw new IllegalArgumentException ( \"start cannot be greater than end. Start: \" + range . getStart ( ) + \" Stop:\" + range . getStop ( ) ) ; final long snappedStartMillis = g . snapMillis ( range . getStart ( ) ) ; final long snappedStopMillis = g . snapMillis ( range . getStop ( ) + g . milliseconds ( ) ) ; HashMap < Range , Iterable < Range > > rangeMap = new HashMap < Range , Iterable < Range > > ( ) ; long tempStartMillis = snappedStartMillis ; int numberOfMillis = g . milliseconds ( ) ; while ( tempStartMillis <= ( snappedStopMillis - numberOfMillis ) ) { Range slotRange = new Range ( tempStartMillis , tempStartMillis + numberOfMillis ) ; rangeMap . put ( slotRange , new IntervalRangeIterator ( g . finer ( ) , slotRange . start , slotRange . stop ) ) ; tempStartMillis = tempStartMillis + numberOfMillis ; } return rangeMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the Ranges for an interval at this granularity [CODESPLIT] public static Iterable < Range > rangesForInterval ( Granularity g , final long from , final long to ) { if ( g == Granularity . FULL ) { return Arrays . asList ( new Range ( from , to ) ) ; } final long snappedStartMillis = g . snapMillis ( from ) ; final long snappedStopMillis = g . snapMillis ( to + g . milliseconds ( ) ) ; return new IntervalRangeIterator ( g , snappedStartMillis , snappedStopMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "single column updates ) . [CODESPLIT] public void insertFull ( Collection < ? extends IMetric > metrics , boolean isRecordingDelayedMetrics , Clock clock ) throws ConnectionException { Timer . Context ctx = Instrumentation . getWriteTimerContext ( CassandraModel . CF_METRICS_FULL_NAME ) ; try { MutationBatch mutationBatch = keyspace . prepareMutationBatch ( ) ; for ( IMetric metric : metrics ) { final Locator locator = metric . getLocator ( ) ; // key = shard // col = locator (acct + entity + check + dimension.metric) // value = <nothing> if ( ! LocatorCache . getInstance ( ) . isLocatorCurrentInBatchLayer ( locator ) ) { if ( mutationBatch != null ) insertLocator ( locator , mutationBatch ) ; LocatorCache . getInstance ( ) . setLocatorCurrentInBatchLayer ( locator ) ; } if ( isRecordingDelayedMetrics ) { //retaining the same conditional logic that was used to insertLocator(locator, batch) above. if ( mutationBatch != null ) { insertLocatorIfDelayed ( metric , mutationBatch , clock ) ; } } insertMetric ( metric , mutationBatch ) ; Instrumentation . markFullResMetricWritten ( ) ; } // insert it try { mutationBatch . execute ( ) ; } catch ( ConnectionException e ) { Instrumentation . markWriteError ( e ) ; log . error ( \"Connection exception during insertFull\" , e ) ; throw e ; } } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method inserts the locator into the metric_delayed_locator column family if the metric is delayed . [CODESPLIT] private void insertLocatorIfDelayed ( IMetric metric , MutationBatch mutationBatch , Clock clock ) { Locator locator = metric . getLocator ( ) ; long delay = clock . now ( ) . getMillis ( ) - metric . getCollectionTime ( ) ; if ( delay > MAX_AGE_ALLOWED ) { //track locator for configured granularity level. to re-roll only the delayed locator's for that slot int slot = DELAYED_METRICS_STORAGE_GRANULARITY . slot ( metric . getCollectionTime ( ) ) ; if ( ! LocatorCache . getInstance ( ) . isDelayedLocatorForASlotCurrent ( slot , locator ) ) { insertDelayedLocator ( DELAYED_METRICS_STORAGE_GRANULARITY , slot , locator , mutationBatch ) ; LocatorCache . getInstance ( ) . setDelayedLocatorForASlotCurrent ( slot , locator ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "numeric only! [CODESPLIT] public final void insertLocator ( Locator locator , MutationBatch mutationBatch ) { mutationBatch . withRow ( CassandraModel . CF_METRICS_LOCATOR , ( long ) Util . getShard ( locator . toString ( ) ) ) . putEmptyColumn ( locator , TenantTtlProvider . LOCATOR_TTL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "numeric only! [CODESPLIT] public final void insertDelayedLocator ( Granularity g , int slot , Locator locator , MutationBatch mutationBatch ) { int shard = Util . getShard ( locator . toString ( ) ) ; mutationBatch . withRow ( CassandraModel . CF_METRICS_DELAYED_LOCATOR , SlotKey . of ( g , slot , shard ) ) . putEmptyColumn ( locator , TenantTtlProvider . DELAYED_LOCATOR_TTL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generic IMetric insertion . All other metric insertion methods could use this one . [CODESPLIT] public void insertMetrics ( Collection < IMetric > metrics , ColumnFamily cf , boolean isRecordingDelayedMetrics , Clock clock ) throws ConnectionException { Timer . Context ctx = Instrumentation . getWriteTimerContext ( cf . getName ( ) ) ; Multimap < Locator , IMetric > map = asMultimap ( metrics ) ; MutationBatch batch = keyspace . prepareMutationBatch ( ) ; try { for ( Locator locator : map . keySet ( ) ) { ColumnListMutation < Long > mutation = batch . withRow ( cf , locator ) ; for ( IMetric metric : map . get ( locator ) ) { mutation . putColumn ( metric . getCollectionTime ( ) , metric . getMetricValue ( ) , ( AbstractSerializer ) ( Serializers . serializerFor ( metric . getMetricValue ( ) . getClass ( ) ) ) , metric . getTtlInSeconds ( ) ) ; if ( cf . getName ( ) . equals ( CassandraModel . CF_METRICS_PREAGGREGATED_FULL_NAME ) ) { Instrumentation . markFullResPreaggregatedMetricWritten ( ) ; } if ( isRecordingDelayedMetrics ) { //retaining the same conditional logic that was used to perform insertLocator(locator, batch). insertLocatorIfDelayed ( metric , batch , clock ) ; } } if ( ! LocatorCache . getInstance ( ) . isLocatorCurrentInBatchLayer ( locator ) ) { insertLocator ( locator , batch ) ; LocatorCache . getInstance ( ) . setLocatorCurrentInBatchLayer ( locator ) ; } } try { batch . execute ( ) ; } catch ( ConnectionException e ) { Instrumentation . markWriteError ( e ) ; log . error ( \"Connection exception persisting data\" , e ) ; throw e ; } } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method inserts a collection of { @link com . rackspacecloud . blueflood . service . SingleRollupWriteContext } objects to the appropriate Cassandra column family . [CODESPLIT] @ Override public void insertRollups ( List < SingleRollupWriteContext > writeContexts ) { if ( writeContexts . size ( ) == 0 ) { return ; } Timer . Context ctx = Instrumentation . getWriteTimerContext ( writeContexts . get ( 0 ) . getDestinationCF ( ) . getName ( ) ) ; try { BatchStatement batch = new BatchStatement ( BatchStatement . Type . UNLOGGED ) ; for ( SingleRollupWriteContext writeContext : writeContexts ) { Rollup rollup = writeContext . getRollup ( ) ; Locator locator = writeContext . getLocator ( ) ; Granularity granularity = writeContext . getGranularity ( ) ; int ttl = getTtl ( locator , rollup . getRollupType ( ) , granularity ) ; // lookup the right writer RollupType rollupType = writeContext . getRollup ( ) . getRollupType ( ) ; DAbstractMetricIO io = getIO ( rollupType . name ( ) . toLowerCase ( ) , granularity ) ; Statement statement = io . createStatement ( locator , writeContext . getTimestamp ( ) , rollup , writeContext . getGranularity ( ) , ttl ) ; batch . add ( statement ) ; } Session session = DatastaxIO . getSession ( ) ; session . execute ( batch ) ; } catch ( Exception ex ) { Instrumentation . markWriteError ( ) ; LOG . error ( String . format ( \"error writing locator batch of size %s, granularity %s\" , writeContexts . size ( ) , writeContexts . get ( 0 ) . getGranularity ( ) ) , ex ) ; } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches { @link com . rackspacecloud . blueflood . outputs . formats . MetricData } objects for the specified { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } from the specified column family [CODESPLIT] @ Override public MetricData getDatapointsForRange ( final Locator locator , Range range , Granularity granularity ) { Map < Locator , MetricData > result = getDatapointsForRange ( new ArrayList < Locator > ( ) { { add ( locator ) ; } } , range , granularity ) ; return result . get ( locator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches { @link com . rackspacecloud . blueflood . outputs . formats . MetricData } objects for the specified { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } from the specified column family [CODESPLIT] public Map < Locator , MetricData > getDatapointsForRange ( List < Locator > locators , Range range , String columnFamily , Granularity granularity ) { Timer . Context ctx = Instrumentation . getReadTimerContext ( columnFamily ) ; try { MetadataCache metadataCache = MetadataCache . getInstance ( ) ; // in this loop, we will fire all the executeAsync() of // various select statements, the collect all of the // ResultSetFutures Map < Locator , List < ResultSetFuture > > locatorToFuturesMap = new HashMap < Locator , List < ResultSetFuture > > ( ) ; Map < Locator , DAbstractMetricIO > locatorIOMap = new HashMap < Locator , DAbstractMetricIO > ( ) ; for ( Locator locator : locators ) { try { String rType = metadataCache . get ( locator , MetricMetadata . ROLLUP_TYPE . name ( ) . toLowerCase ( ) ) ; DAbstractMetricIO io = getIO ( rType , granularity ) ; // put everything in a map of locator -> io so // we can use em up later locatorIOMap . put ( locator , io ) ; // do the query List < ResultSetFuture > selectFutures = io . selectForLocatorAndRange ( columnFamily , locator , range ) ; // add all ResultSetFutures for a particular locator together List < ResultSetFuture > existing = locatorToFuturesMap . get ( locator ) ; if ( existing == null ) { existing = new ArrayList < ResultSetFuture > ( ) ; locatorToFuturesMap . put ( locator , existing ) ; } existing . addAll ( selectFutures ) ; } catch ( CacheException ex ) { Instrumentation . markReadError ( ) ; LOG . error ( String . format ( \"Error looking up locator %s in cache\" , locator ) , ex ) ; } } return resultSetsToMetricData ( locatorToFuturesMap , locatorIOMap , columnFamily , range ) ; } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches a { @link com . rackspacecloud . blueflood . types . Points } object for a particular locator and rollupType from the specified column family and range [CODESPLIT] @ Override public Points getDataToRollup ( final Locator locator , RollupType rollupType , Range range , String columnFamilyName ) throws IOException { Timer . Context ctx = Instrumentation . getReadTimerContext ( columnFamilyName ) ; try { // read the rollup object from the proper IO class DAbstractMetricIO io = getIO ( rollupType . name ( ) . toLowerCase ( ) , CassandraModel . getGranularity ( columnFamilyName ) ) ; Table < Locator , Long , Object > locatorTimestampRollup = io . getRollupsForLocator ( locator , columnFamilyName , range ) ; Points points = new Points ( ) ; for ( Table . Cell < Locator , Long , Object > cell : locatorTimestampRollup . cellSet ( ) ) { points . add ( createPoint ( cell . getColumnKey ( ) , cell . getValue ( ) ) ) ; } return points ; } catch ( Exception e ) { Instrumentation . markReadError ( ) ; LOG . error ( String . format ( \"Unable to read locator=%s rolluptype=%s columnFamilyName=%s for rollup\" , locator , rollupType . name ( ) , columnFamilyName ) , e ) ; throw new IOException ( e ) ; } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a list of { @link com . datastax . driver . core . ResultSetFuture } for each { @link com . rackspacecloud . blueflood . types . Locator } to { @link com . rackspacecloud . blueflood . outputs . formats . MetricData } object . [CODESPLIT] protected Map < Locator , MetricData > resultSetsToMetricData ( Map < Locator , List < ResultSetFuture > > resultSets , Map < Locator , DAbstractMetricIO > locatorIO , String columnFamily , Range range ) { MetadataCache metadataCache = MetadataCache . getInstance ( ) ; // iterate through all ResultSetFuture Map < Locator , MetricData > locatorMetricDataMap = new HashMap < Locator , MetricData > ( ) ; for ( Map . Entry < Locator , List < ResultSetFuture > > entry : resultSets . entrySet ( ) ) { Locator locator = entry . getKey ( ) ; List < ResultSetFuture > futures = entry . getValue ( ) ; DAbstractMetricIO io = locatorIO . get ( locator ) ; // get ResultSets to a Table of locator, timestamp, rollup Table < Locator , Long , Object > locatorTimestampRollup = io . toLocatorTimestampValue ( futures , locator , columnFamily , range ) ; Map < Long , Object > tsRollupMap = locatorTimestampRollup . row ( locator ) ; // convert to Points and MetricData Points points = convertToPoints ( tsRollupMap ) ; // create MetricData MetricData metricData = new MetricData ( points , metadataCache . getUnitString ( locator ) ) ; locatorMetricDataMap . put ( locator , metricData ) ; } return locatorMetricDataMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a map of timestamps - > Rollups / SimpleNumbers return RollupType or null if not a Rollup . [CODESPLIT] private RollupType getRollupType ( Map < Long , Object > tsRollupMap ) { if ( tsRollupMap . isEmpty ( ) ) return null ; else { Object value = tsRollupMap . values ( ) . iterator ( ) . next ( ) ; return value instanceof Rollup ? ( ( Rollup ) value ) . getRollupType ( ) : null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if the metric is considered delayed or not [CODESPLIT] protected boolean isDelayed ( IMetric metric ) { long delay = clock . now ( ) . getMillis ( ) - metric . getCollectionTime ( ) ; return delay > MAX_AGE_ALLOWED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method inserts the locator into the metric_delayed_locator column family if the metric is delayed . [CODESPLIT] protected void insertLocatorIfDelayed ( IMetric metric ) throws IOException { Locator locator = metric . getLocator ( ) ; if ( isDelayed ( metric ) ) { int slot = getDelayedSlot ( metric ) ; if ( ! LocatorCache . getInstance ( ) . isDelayedLocatorForASlotCurrent ( slot , locator ) ) { delayedLocatorIO . insertLocator ( DELAYED_METRICS_STORAGE_GRANULARITY , slot , locator ) ; LocatorCache . getInstance ( ) . setDelayedLocatorForASlotCurrent ( slot , locator ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a BoundStatement if a metric needs to be inserted to the metrics_delayed_locator Column Family . Returns null otherwise . [CODESPLIT] protected BoundStatement getBoundStatementForMetricIfDelayed ( IMetric metric ) { Locator locator = metric . getLocator ( ) ; if ( isDelayed ( metric ) ) { int slot = getDelayedSlot ( metric ) ; if ( ! LocatorCache . getInstance ( ) . isDelayedLocatorForASlotCurrent ( slot , locator ) ) { LocatorCache . getInstance ( ) . setDelayedLocatorForASlotCurrent ( slot , locator ) ; return delayedLocatorIO . getBoundStatementForLocator ( DELAYED_METRICS_STORAGE_GRANULARITY , slot , locator ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method queries elasticsearch for a given glob query and returns list of { @link MetricName } s . [CODESPLIT] private List < MetricName > searchESByIndexes ( String tenantId , String query , String [ ] indexes ) { if ( StringUtils . isEmpty ( query ) ) return new ArrayList <> ( ) ; Timer . Context timerCtx = esMetricNamesQueryTimer . time ( ) ; try { String response = elasticsearchRestHelper . fetchTokenDocuments ( indexes , tenantId , query ) ; List < MetricName > metricNames = getMetricNames ( response ) ; Set < MetricName > uniqueMetricNames = new HashSet <> ( metricNames ) ; return new ArrayList <> ( uniqueMetricNames ) ; } catch ( IOException e ) { log . error ( \"IOException: Elasticsearch token query failed for tenantId {}. {}\" , tenantId , e . getMessage ( ) ) ; throw new RuntimeException ( String . format ( \"searchESByIndexes failed with message: %s\" , e . getMessage ( ) ) , e ) ; } catch ( Exception e ) { log . error ( \"Exception: Elasticsearch token query failed for tenantId {}. {}\" , tenantId , e . getMessage ( ) ) ; throw new RuntimeException ( String . format ( \"searchESByIndexes failed with message: %s\" , e . getMessage ( ) ) , e ) ; } finally { timerCtx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method that returns all metadata for a given locator as a map . [CODESPLIT] public Map < String , String > getMetadataValues ( Locator locator ) { Timer . Context ctx = Instrumentation . getReadTimerContext ( CassandraModel . CF_METRICS_METADATA_NAME ) ; try { final ColumnList < String > results = keyspace . prepareQuery ( CassandraModel . CF_METRICS_METADATA ) . getKey ( locator ) . execute ( ) . getResult ( ) ; return new HashMap < String , String > ( ) { { for ( Column < String > result : results ) { put ( result . getName ( ) , result . getValue ( StringMetadataSerializer . get ( ) ) ) ; } } } ; } catch ( NotFoundException ex ) { Instrumentation . markNotFound ( CassandraModel . CF_METRICS_METADATA_NAME ) ; return null ; } catch ( ConnectionException e ) { log . error ( \"Error reading metadata value\" , e ) ; Instrumentation . markReadError ( e ) ; throw new RuntimeException ( e ) ; } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo : A better interface may be to pass the serializer in instead of the class type . [CODESPLIT] public < T extends Rollup > Points < T > getDataToRoll ( Class < T > type , final Locator locator , Range range , ColumnFamily < Locator , Long > cf ) throws IOException { AbstractSerializer serializer = Serializers . serializerFor ( type ) ; // special cases. :( the problem here is that the normal full res serializer returns Number instances instead of // SimpleNumber instances. // todo: this logic will only become more complicated. It needs to be in its own method and the serializer needs // to be known before we ever get to this method (see above comment). if ( cf == CassandraModel . CF_METRICS_FULL ) { serializer = Serializers . simpleNumberSerializer ; } else if ( cf == CassandraModel . CF_METRICS_PREAGGREGATED_FULL ) { // consider a method for this.  getSerializer(CF, TYPE); if ( type . equals ( BluefloodTimerRollup . class ) ) { serializer = Serializers . timerRollupInstance ; } else if ( type . equals ( BluefloodSetRollup . class ) ) { serializer = Serializers . setRollupInstance ; } else if ( type . equals ( BluefloodGaugeRollup . class ) ) { serializer = Serializers . gaugeRollupInstance ; } else if ( type . equals ( BluefloodCounterRollup . class ) ) { serializer = Serializers . counterRollupInstance ; } else { serializer = Serializers . simpleNumberSerializer ; } } ColumnList < Long > cols = getColumnsFromDB ( locator , cf , range ) ; Points < T > points = new Points < T > ( ) ; try { for ( Column < Long > col : cols ) { points . add ( new Points . Point < T > ( col . getName ( ) , ( T ) col . getValue ( serializer ) ) ) ; } // we only want to count the number of points we // get when we're querying the metrics_full // we don't do for aggregated or other granularities if ( cf == CassandraModel . CF_METRICS_FULL ) { Instrumentation . getRawPointsIn5MinHistogram ( ) . update ( points . getPoints ( ) . size ( ) ) ; } } catch ( RuntimeException ex ) { log . error ( \"Problem deserializing data for \" + locator + \" (\" + range + \") from \" + cf . getName ( ) , ex ) ; throw new IOException ( ex ) ; } return points ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get data points for a particular { @link Locator } { @link Range } and { @link Granularity } . [CODESPLIT] public MetricData getDatapointsForRange ( Locator locator , Range range , Granularity gran ) { RollupType rollupType = RollupType . BF_BASIC ; String rollupTypeStr = metaCache . safeGet ( locator , rollupTypeCacheKey ) ; if ( rollupTypeStr != null ) { rollupType = RollupType . fromString ( rollupTypeStr ) ; } return getNumericMetricDataForRange ( locator , range , gran , rollupType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get data points for multiple { @link Locator } for the specified { @link Range } and { @link Granularity } . [CODESPLIT] public Map < Locator , MetricData > getDatapointsForRange ( List < Locator > locators , Range range , Granularity gran ) { ListMultimap < ColumnFamily , Locator > locatorsByCF = ArrayListMultimap . create ( ) ; Map < Locator , MetricData > results = new HashMap < Locator , MetricData > ( ) ; for ( Locator locator : locators ) { try { RollupType rollupType = RollupType . fromString ( metaCache . get ( locator , MetricMetadata . ROLLUP_TYPE . name ( ) . toLowerCase ( ) ) ) ; ColumnFamily cf = CassandraModel . getColumnFamily ( rollupType , gran ) ; List < Locator > locs = locatorsByCF . get ( cf ) ; locs . add ( locator ) ; } catch ( Exception e ) { // pass for now. need metric to figure this stuff out. log . error ( String . format ( \"error getting datapoints for locator %s, range %s, granularity %s\" , locator , range . toString ( ) , gran . toString ( ) ) , e ) ; } } for ( ColumnFamily CF : locatorsByCF . keySet ( ) ) { List < Locator > locs = locatorsByCF . get ( CF ) ; results . putAll ( getNumericDataForRangeLocatorList ( range , gran , CF , locs ) ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches a { @link com . rackspacecloud . blueflood . types . Points } object for a particular locator and rollupType from the specified column family and range [CODESPLIT] @ Override public Points < BasicRollup > getDataToRollup ( final Locator locator , RollupType rollupType , Range range , String columnFamilyName ) throws IOException { return AstyanaxReader . getInstance ( ) . getDataToRoll ( BasicRollup . class , locator , range , CassandraModel . getColumnFamily ( columnFamilyName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return a serializer for a specific type [CODESPLIT] public static < T > AbstractSerializer < T > serializerFor ( Class < T > type ) { if ( type == null ) throw new RuntimeException ( \"serializable type cannot be null\" , new SerializationException ( \"serializable type cannot be null\" ) ) ; else if ( type . equals ( String . class ) ) throw new RuntimeException ( \"We don't serialize strings anymore\" , new SerializationException ( \"We don't serialize strings anymore\" ) ) ; if ( type . equals ( BasicRollup . class ) ) return ( AbstractSerializer < T > ) basicRollupInstance ; else if ( type . equals ( BluefloodTimerRollup . class ) ) return ( AbstractSerializer < T > ) timerRollupInstance ; else if ( type . equals ( BluefloodCounterRollup . class ) ) return ( AbstractSerializer < T > ) counterRollupInstance ; else if ( type . equals ( BluefloodGaugeRollup . class ) ) return ( AbstractSerializer < T > ) gaugeRollupInstance ; else if ( type . equals ( BluefloodSetRollup . class ) ) return ( AbstractSerializer < T > ) setRollupInstance ; else if ( type . equals ( SimpleNumber . class ) ) return ( AbstractSerializer < T > ) fullInstance ; else if ( type . equals ( Integer . class ) ) return ( AbstractSerializer < T > ) fullInstance ; else if ( type . equals ( Long . class ) ) return ( AbstractSerializer < T > ) fullInstance ; else if ( type . equals ( Double . class ) ) return ( AbstractSerializer < T > ) fullInstance ; else if ( type . equals ( Float . class ) ) return ( AbstractSerializer < T > ) fullInstance ; else if ( type . equals ( byte [ ] . class ) ) return ( AbstractSerializer < T > ) fullInstance ; else if ( type . equals ( Object . class ) ) return ( AbstractSerializer < T > ) fullInstance ; else return ( AbstractSerializer < T > ) fullInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the Content - Type header to see if clients specify the right media type [CODESPLIT] public boolean isContentTypeValid ( HttpHeaders headers ) { String contentType = headers . get ( HttpHeaders . Names . CONTENT_TYPE ) ; // if we get no Content-Type or we get application/json, then it's valid // any other, it's invalid return ( Strings . isNullOrEmpty ( contentType ) || contentType . toLowerCase ( ) . contains ( MEDIA_TYPE_APPLICATION_JSON ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the Accept header to see if clients accept the correct media type [CODESPLIT] public boolean isAcceptValid ( HttpHeaders headers ) { String accept = headers . get ( HttpHeaders . Names . ACCEPT ) ; // if we get no Accept (which means */*), or */*, // or application/json, then it's valid return ( Strings . isNullOrEmpty ( accept ) || accept . contains ( ACCEPT_ALL ) || accept . toLowerCase ( ) . contains ( MEDIA_TYPE_APPLICATION_JSON ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "REST call to index into ES [CODESPLIT] public void insertDiscovery ( List < IMetric > batch ) throws IOException { batchHistogram . update ( batch . size ( ) ) ; if ( batch . size ( ) == 0 ) { log . debug ( \"ElasticIO: batch size for insertDiscovery is zero, so skip calling Elasticsearch ingest.\" ) ; return ; } Timer . Context ctx = writeTimer . time ( ) ; try { for ( Object obj : batch ) { if ( ! ( obj instanceof IMetric ) ) { classCastExceptionMeter . mark ( ) ; continue ; } } elasticsearchRestHelper . indexMetrics ( batch ) ; } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is invoked by the validator automatically [CODESPLIT] @ AssertTrue ( message = \"At least one of the aggregated metrics(gauges, counters, timers, sets) are expected\" ) private boolean isValid ( ) { boolean isGaugePresent = gauges != null && gauges . length > 0 ; boolean isCounterPresent = counters != null && counters . length > 0 ; boolean isTimerPresent = timers != null && timers . length > 0 ; boolean isSetPresent = sets != null && sets . length > 0 ; return ( isGaugePresent || isCounterPresent || isTimerPresent || isSetPresent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marks / instruments our internal metrics that we have received short or delayed metrics [CODESPLIT] public void markDelayMetricsReceived ( long ingestTime ) { long delay = getDelayTime ( ingestTime ) ; if ( delay > MAX_AGE_ALLOWED ) { if ( delay <= SHORT_DELAY ) { Instrumentation . markMetricsWithShortDelayReceived ( ) ; } else { Instrumentation . markMetricsWithLongDelayReceived ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets run by the thread . [CODESPLIT] private void doCheck ( ) { if ( ! running ) return ; if ( fileManager == null ) return ; if ( unexpectedErrors > MAX_UNEXPECTED_ERRORS ) { log . info ( \"Terminating because of errors\" ) ; terminate ( false ) ; return ; } Timer . Context waitTimerContext = waitingTimer . time ( ) ; // Possible infinite thread sleep? This will make sure we fire downloading only when are the files are consumed/merged while ( downloadDir . listFiles ( ) . length != 0 ) { log . debug ( \"Waiting for files in download directory to clear up. Sleeping for 1 min. If you see this persistently, it means the downloaded files are not getting merged properly/timely\" ) ; try { Thread . sleep ( 60000 ) ; } catch ( Exception ex ) { } } waitTimerContext . stop ( ) ; if ( downloadLock . tryLock ( ) ) { try { if ( fileManager . hasNewFiles ( ) ) { fileManager . downloadNewFiles ( downloadDir ) ; } } catch ( Throwable unexpected ) { unexpectedErrors += 1 ; log . error ( \"UNEXPECTED; WILL TRY TO RECOVER\" ) ; log . error ( unexpected . getMessage ( ) , unexpected ) ; // sleep for a minute? if ( Thread . interrupted ( ) ) { try { thread . sleep ( 60000 ) ; } catch ( Exception ex ) { log . error ( ex . getMessage ( ) , ex ) ; } } } finally { downloadLock . unlock ( ) ; } } else { log . debug ( \"Download in progress\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a collection of rolled up metrics to the metrics_preaggregated_ { granularity } column family . Only our tests should call this method . Services should call either insertMetrics ( Collection metrics ) or insertRollups () [CODESPLIT] @ VisibleForTesting @ Override public void insertMetrics ( Collection < IMetric > metrics , Granularity granularity ) throws IOException { Timer . Context ctx = Instrumentation . getWriteTimerContext ( CassandraModel . getPreaggregatedColumnFamilyName ( granularity ) ) ; try { Multimap < Locator , IMetric > map = asMultimap ( metrics ) ; if ( isBatchIngestEnabled ) { insertMetricsInBatch ( map , granularity ) ; } else { insertMetricsIndividually ( map , granularity ) ; } } finally { ctx . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches { @link com . rackspacecloud . blueflood . outputs . formats . MetricData } objects for the specified list of { @link com . rackspacecloud . blueflood . types . Locator } and { @link com . rackspacecloud . blueflood . types . Range } from the specified column family [CODESPLIT] @ Override public Map < Locator , MetricData > getDatapointsForRange ( List < Locator > locators , Range range , Granularity granularity ) /*throws IOException*/ { String columnFamily = CassandraModel . getPreaggregatedColumnFamilyName ( granularity ) ; return getDatapointsForRange ( locators , range , columnFamily , granularity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the appropriate IO object which interacts with the Cassandra database . [CODESPLIT] @ Override public DAbstractMetricIO getIO ( String rollupType , Granularity granularity ) { // find out the rollupType for this locator RollupType rType = RollupType . fromString ( rollupType ) ; // get the right PreaggregatedIO class that can process // this rollupType DAbstractMetricIO io = rollupTypeToIO . get ( rType ) ; if ( io == null ) { throw new InvalidDataException ( String . format ( \"getIO: unsupported rollupType=%s\" , rollupType ) ) ; } return io ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return an available port assigned at random by the OS . [CODESPLIT] public int get ( ) throws IllegalStateException { ServerSocket socket = null ; try { socket = this . severSocketFactory . createServerSocket ( 0 ) ; socket . setReuseAddress ( false ) ; return socket . getLocalPort ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( \"Could not determine random port to assign.\" , e ) ; } finally { if ( socket != null ) { try { socket . close ( ) ; } catch ( IOException e ) { LOGGER . debug ( \"Couldn't close socket that was temporarily opened to determine random port.\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Extractor instance appropriate based on the given configuration . [CODESPLIT] public Extractor getNewInstance ( ) { Extractor extractor = new BasicExtractor ( config ) ; if ( config . shouldCachedDownload ( ) ) { extractor = new CachedExtractor ( extractor , config ) ; } return extractor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides if the operating system matches . [CODESPLIT] private static boolean getOSMatches ( final String osNamePrefix , final String osVersionPrefix ) { return isOSMatch ( OS_NAME , OS_VERSION , osNamePrefix , osVersionPrefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets a System property defaulting to { @code null } if the property cannot be read . < / p > <p > If a { @code SecurityException } is caught the return value is { @code null } and a message is written to { @code System . err } . < / p > [CODESPLIT] private static String getSystemProperty ( final String property ) { try { return System . getProperty ( property ) ; } catch ( final SecurityException ex ) { // we are not allowed to look at this property System . err . println ( \"Caught a SecurityException reading the system property '\" + property + \"'; the SystemUtils property value will default to null.\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Decides if the Java version matches . < / p > <p > This method is package private instead of private to support unit test invocation . < / p > [CODESPLIT] static boolean isJavaVersionMatch ( final String version , final String versionPrefix ) { if ( version == null ) { return false ; } return version . startsWith ( versionPrefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides if the operating system matches . <p > This method is package private instead of private to support unit test invocation . < / p > [CODESPLIT] static boolean isOSMatch ( final String osName , final String osVersion , final String osNamePrefix , final String osVersionPrefix ) { if ( osName == null || osVersion == null ) { return false ; } return isOSNameMatch ( osName , osNamePrefix ) && isOSVersionMatch ( osVersion , osVersionPrefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decides if the operating system version matches . <p > This method is package private instead of private to support unit test invocation . < / p > [CODESPLIT] static boolean isOSVersionMatch ( final String osVersion , final String osVersionPrefix ) { if ( osVersion == null || osVersion . trim ( ) . isEmpty ( ) ) { return false ; } // Compare parts of the version string instead of using String.startsWith(String) because otherwise // osVersionPrefix 10.1 would also match osVersion 10.10 String [ ] versionPrefixParts = osVersionPrefix . split ( \"\\\\.\" ) ; String [ ] versionParts = osVersion . split ( \"\\\\.\" ) ; for ( int i = 0 ; i < Math . min ( versionPrefixParts . length , versionParts . length ) ; i ++ ) { if ( ! versionPrefixParts [ i ] . equals ( versionParts [ i ] ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the RabbitMQ node port as defined by the { [CODESPLIT] public int getRabbitMqPort ( ) { String portValue = this . envVars . get ( RabbitMqEnvVar . NODE_PORT . getEnvVarName ( ) ) ; if ( portValue == null ) { return RabbitMqEnvVar . DEFAULT_NODE_PORT ; } else { return Integer . parseInt ( portValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the RabbitMQ server process and blocks the current thread until the initialization is completed . [CODESPLIT] public void start ( ) throws ErlangVersionException , DownloadException , ExtractionException , StartupException { if ( rabbitMqProcess != null ) { throw new IllegalStateException ( \"Start shouldn't be called more than once unless stop() has been called before.\" ) ; } check ( ) ; download ( ) ; extract ( ) ; run ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submits the command to stop RabbitMQ and blocks the current thread until the shutdown is completed . [CODESPLIT] public void stop ( ) throws ShutDownException { if ( rabbitMqProcess == null ) { throw new IllegalStateException ( \"Stop shouldn't be called unless 'start()' was successful.\" ) ; } new ShutdownHelper ( config , rabbitMqProcess ) . run ( ) ; rabbitMqProcess = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Start the stopwatch . < / p > [CODESPLIT] public void start ( ) { if ( this . runningState == State . STOPPED ) { throw new IllegalStateException ( \"Stopwatch must be reset before being restarted. \" ) ; } if ( this . runningState != State . UNSTARTED ) { throw new IllegalStateException ( \"Stopwatch already started. \" ) ; } this . startTime = System . nanoTime ( ) ; this . startTimeMillis = System . currentTimeMillis ( ) ; this . runningState = State . RUNNING ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Stop the stopwatch . < / p > [CODESPLIT] public void stop ( ) { if ( this . runningState != State . RUNNING && this . runningState != State . SUSPENDED ) { throw new IllegalStateException ( \"Stopwatch is not running. \" ) ; } if ( this . runningState == State . RUNNING ) { this . stopTime = System . nanoTime ( ) ; } this . runningState = State . STOPPED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Split the time . < / p > [CODESPLIT] public void split ( ) { if ( this . runningState != State . RUNNING ) { throw new IllegalStateException ( \"Stopwatch is not running. \" ) ; } this . stopTime = System . nanoTime ( ) ; this . splitState = SplitState . SPLIT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Suspend the stopwatch for later resumption . < / p > [CODESPLIT] public void suspend ( ) { if ( this . runningState != State . RUNNING ) { throw new IllegalStateException ( \"Stopwatch must be running to suspend. \" ) ; } this . stopTime = System . nanoTime ( ) ; this . runningState = State . SUSPENDED ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Resume the stopwatch after a suspend . < / p > [CODESPLIT] public void resume ( ) { if ( this . runningState != State . SUSPENDED ) { throw new IllegalStateException ( \"Stopwatch must be suspended to resume. \" ) ; } this . startTime += System . nanoTime ( ) - this . stopTime ; this . runningState = State . RUNNING ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Get the time on the stopwatch in nanoseconds . < / p > [CODESPLIT] public long getNanoTime ( ) { if ( this . runningState == State . STOPPED || this . runningState == State . SUSPENDED ) { return this . stopTime - this . startTime ; } else if ( this . runningState == State . UNSTARTED ) { return 0 ; } else if ( this . runningState == State . RUNNING ) { return System . nanoTime ( ) - this . startTime ; } throw new RuntimeException ( \"Illegal running state has occurred.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins the elements of the provided collection into a single String containing the provided list of elements . <p > No delimiter is added before or after the list . <p > Empty collections return an empty String . [CODESPLIT] public static < T > String join ( Collection < T > collection , CharSequence joinedBy ) { if ( collection . isEmpty ( ) ) { return \"\" ; } StringBuilder stringBuilder = new StringBuilder ( 256 ) ; for ( T t : collection ) { stringBuilder . append ( t . toString ( ) ) . append ( joinedBy ) ; } return stringBuilder . substring ( 0 , stringBuilder . length ( ) - joinedBy . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the current system s Erlang version to compare it to the minimum required version . <p > The system s Erlang version is always retrieved but the comparison might be skipped if the RabbitMQ version doesn t specify a minimum required version . [CODESPLIT] public void check ( ) throws ErlangVersionException { String erlangVersion ; try { erlangVersion = erlangShell . getErlangVersion ( ) ; LOGGER . debug ( \"Erlang version installed in this system: {}\" , erlangVersion ) ; } catch ( ErlangShellException e ) { throw new ErlangVersionException ( \"Could not determine Erlang version. Ensure Erlang is correctly installed.\" , e ) ; } if ( minErlangVersion == null ) { LOGGER . debug ( \"RabbitMQ version to execute doesn't specify a minimum Erlang version. Will skip this check.\" ) ; return ; } else { LOGGER . debug ( \"RabbitMQ version to execute requires Erlang version {} or above.\" , minErlangVersion ) ; } int [ ] expected ; int [ ] actual ; try { expected = parse ( minErlangVersion ) ; actual = parse ( erlangVersion ) ; } catch ( RuntimeException e ) { LOGGER . warn ( \"Error parsing Erlang version: \" + minErlangVersion + \" or \" + erlangVersion + \". Ignoring check...\" ) ; return ; } for ( int i = 0 ; i < actual . length ; i ++ ) { if ( actual [ i ] > expected [ i ] ) { break ; } if ( actual [ i ] < expected [ i ] ) { throw new ErlangVersionException ( String . format ( \"Minimum required Erlang version not found. Expected '%s' or higher. Actual is: '%s'\" , minErlangVersion , erlangVersion ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method exposes a way to invoke { @value EXECUTABLE } command with any arguments . This is useful when the class methods don t expose the desired functionality . <p > For example : <pre > <code > RabbitMqPlugins command = new RabbitMqPlugins ( config ) ; command . execute ( list - v management ) ; < / code > < / pre > [CODESPLIT] public Future < ProcessResult > execute ( String ... arguments ) throws RabbitMqCommandException { return new RabbitMqCommand ( config , EXECUTABLE , arguments ) . call ( ) . getFuture ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as { [CODESPLIT] public Map < Plugin . State , Set < Plugin > > groupedList ( ) throws RabbitMqCommandException { Collection < Plugin > plugins = list ( ) . values ( ) ; return groupPluginsByState ( plugins ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the { @code rabbitmq - plugins list } command [CODESPLIT] public Map < String , Plugin > list ( ) { String [ ] args = { LIST_COMMAND } ; String executionErrorMessage = String . format ( \"Error executing: %s %s\" , EXECUTABLE , LIST_COMMAND ) ; String unexpectedExitCodeMessage = \"Listing of plugins failed with exit code: \" ; ProcessResult processResult = getProcessResult ( args , executionErrorMessage , unexpectedExitCodeMessage ) ; List < Plugin > plugins = parseListOutput ( processResult ) ; Map < String , Plugin > result = mapPluginsByName ( plugins ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the command { @code rabbitmq - plugins enable { plugin }} and blocks until the call finishes . [CODESPLIT] public void enable ( String plugin ) throws RabbitMqCommandException { String [ ] args = { \"enable\" , plugin } ; String executionErrorMessage = \"Error while enabling plugin '\" + plugin + \"'\" ; String unexpectedExitCodeMessage = \"Enabling of plugin '\" + plugin + \"' failed with exit code: \" ; getProcessResult ( args , executionErrorMessage , unexpectedExitCodeMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disables the given plugin by executing { @code rabbitmq - plugins disable { plugin }} and blocks until the call is finished . [CODESPLIT] public void disable ( String plugin ) throws RabbitMqCommandException { String [ ] args = { \"disable\" , plugin } ; String executionErrorMessage = \"Error while disabling plugin '\" + plugin + \"'\" ; String unexpectedExitCodeMessage = \"Disabling of plugin '\" + plugin + \"' failed with exit code: \" ; getProcessResult ( args , executionErrorMessage , unexpectedExitCodeMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies bytes from the URL <code > source< / code > to a file <code > destination< / code > . The directories up to <code > destination< / code > will be created if they don t already exist . <code > destination< / code > will be overwritten if it already exists . [CODESPLIT] public static void copyURLToFile ( URL source , File destination , int connectionTimeout , int readTimeout ) throws IOException { copyUrlToFile ( source , destination , connectionTimeout , readTimeout , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies bytes from the URL <code > source< / code > to a file <code > destination< / code > . The directories up to <code > destination< / code > will be created if they don t already exist . <code > destination< / code > will be overwritten if it already exists . [CODESPLIT] public static void copyUrlToFile ( URL source , File destination , int connectionTimeout , int readTimeout , Proxy proxy ) throws IOException { URLConnection connection ; if ( proxy == null ) { connection = source . openConnection ( ) ; } else { connection = source . openConnection ( proxy ) ; } connection . setConnectTimeout ( connectionTimeout ) ; connection . setReadTimeout ( readTimeout ) ; InputStream input = connection . getInputStream ( ) ; copyInputStreamToFile ( input , destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies bytes from an { @link InputStream } <code > source< / code > to a file <code > destination< / code > . The directories up to <code > destination< / code > will be created if they don t already exist . <code > destination< / code > will be overwritten if it already exists . [CODESPLIT] public static void copyInputStreamToFile ( InputStream source , File destination ) throws IOException { try { FileOutputStream output = openOutputStream ( destination ) ; try { copy ( source , output ) ; output . close ( ) ; // don't swallow close Exception if copy completes normally } finally { closeQuietly ( output ) ; } } finally { closeQuietly ( source ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the RabbitMQ Server and blocks the current thread until the server is confirmed to have started . <p > This is useful to ensure no other interactions happen with the RabbitMQ Server until it s safe to do so [CODESPLIT] @ Override public Future < ProcessResult > call ( ) throws StartupException { PatternFinderOutputStream initializationWatcher = new PatternFinderOutputStream ( BROKER_STARTUP_COMPLETED ) ; // Inform the initializationWatcher if the process ends before the expected output is produced. PublishingProcessListener rabbitMqProcessListener = new PublishingProcessListener ( ) ; rabbitMqProcessListener . addSubscriber ( initializationWatcher ) ; Future < ProcessResult > resultFuture = startProcess ( initializationWatcher , rabbitMqProcessListener ) ; waitForConfirmation ( initializationWatcher ) ; return resultFuture ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param outputLine as generated by the command line { @code rabbitmq - plugins groupedList } [CODESPLIT] public static Plugin fromString ( String outputLine ) { Matcher matcher = LIST_OUTPUT_PATTERN . matcher ( outputLine ) ; if ( ! matcher . matches ( ) ) { return null ; } String state = matcher . group ( 1 ) ; String pluginName = matcher . group ( 2 ) ; String version = matcher . group ( 3 ) ; return new Plugin ( pluginName , State . fromString ( state ) , version ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default parameters for media constraints . Might have to tweak in future . [CODESPLIT] public static PnSignalingParams defaultInstance ( ) { MediaConstraints pcConstraints = PnSignalingParams . defaultPcConstraints ( ) ; MediaConstraints videoConstraints = PnSignalingParams . defaultVideoConstraints ( ) ; MediaConstraints audioConstraints = PnSignalingParams . defaultAudioConstraints ( ) ; List < PeerConnection . IceServer > iceServers = PnSignalingParams . defaultIceServers ( ) ; return new PnSignalingParams ( iceServers , pcConstraints , videoConstraints , audioConstraints ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append default servers to the end of given list and set as iceServers instance variable [CODESPLIT] public void addIceServers ( List < PeerConnection . IceServer > iceServers ) { if ( this . iceServers != null ) { iceServers . addAll ( this . iceServers ) ; } this . iceServers = iceServers ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiate iceServers if they are not already and add Ice Server to beginning of list . [CODESPLIT] public void addIceServers ( PeerConnection . IceServer iceServers ) { if ( this . iceServers == null ) { this . iceServers = new ArrayList < PeerConnection . IceServer > ( ) ; } this . iceServers . add ( 0 , iceServers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Add a max user threshold . Connect with another user by their ID . [CODESPLIT] boolean connect ( String userId ) { if ( ! peers . containsKey ( userId ) ) { // Prevents duplicate dials. if ( peers . size ( ) < MAX_CONNECTIONS ) { PnPeer peer = addPeer ( userId ) ; peer . pc . addStream ( this . localMediaStream ) ; try { actionMap . get ( CreateOfferAction . TRIGGER ) . execute ( userId , new JSONObject ( ) ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; return false ; } return true ; } } this . mRtcListener . onDebug ( new PnRTCMessage ( \"CONNECT FAILED. Duplicate dial or max peer \" + \"connections exceeded. Max: \" + MAX_CONNECTIONS + \" Current: \" + this . peers . size ( ) ) ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close connection ( hangup ) no a certain peer . [CODESPLIT] public void closeConnection ( String id ) { JSONObject packet = new JSONObject ( ) ; try { if ( ! this . peers . containsKey ( id ) ) return ; PnPeer peer = this . peers . get ( id ) ; peer . hangup ( ) ; packet . put ( PnRTCMessage . JSON_HANGUP , true ) ; transmitMessage ( id , packet ) ; mRtcListener . onPeerConnectionClosed ( peer ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close connections ( hangup ) on all open connections . [CODESPLIT] public void closeAllConnections ( ) { Iterator < String > peerIds = this . peers . keySet ( ) . iterator ( ) ; while ( peerIds . hasNext ( ) ) { closeConnection ( peerIds . next ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send SDP Offers / Answers nd ICE candidates to peers . [CODESPLIT] void transmitMessage ( String toID , JSONObject packet ) { if ( this . id == null ) { // Not logged in. Put an error in the debug cb. mRtcListener . onDebug ( new PnRTCMessage ( \"Cannot transmit before calling Client.connect\" ) ) ; } try { JSONObject message = new JSONObject ( ) ; message . put ( PnRTCMessage . JSON_PACKET , packet ) ; message . put ( PnRTCMessage . JSON_ID , \"\" ) ; //Todo: session id, unused in js SDK? message . put ( PnRTCMessage . JSON_NUMBER , this . id ) ; this . mPubNub . publish ( toID , message , new Callback ( ) { // Todo: reconsider callback. @ Override public void successCallback ( String channel , Object message , String timetoken ) { mRtcListener . onDebug ( new PnRTCMessage ( ( JSONObject ) message ) ) ; } @ Override public void errorCallback ( String channel , PubnubError error ) { mRtcListener . onDebug ( new PnRTCMessage ( error . errorObject ) ) ; } } ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static method to generate the proper JSON for a user message . Use this when you don t have a { [CODESPLIT] public static JSONObject generateUserMessage ( String userId , JSONObject message ) { JSONObject json = new JSONObject ( ) ; try { JSONObject packet = new JSONObject ( ) ; packet . put ( PnRTCMessage . JSON_USERMSG , message ) ; json . put ( PnRTCMessage . JSON_PACKET , packet ) ; json . put ( PnRTCMessage . JSON_ID , \"\" ) ; //Todo: session id, unused in js SDK? json . put ( PnRTCMessage . JSON_NUMBER , userId ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return json ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a custom JSONObject user message to a single peer . [CODESPLIT] public void transmit ( String userId , JSONObject message ) { JSONObject usrMsgJson = new JSONObject ( ) ; try { usrMsgJson . put ( PnRTCMessage . JSON_USERMSG , message ) ; this . pcClient . transmitMessage ( userId , usrMsgJson ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a custom JSONObject user message to all peers . [CODESPLIT] public void transmitAll ( JSONObject message ) { List < PnPeer > peerList = this . pcClient . getPeers ( ) ; for ( PnPeer p : peerList ) { transmit ( p . getId ( ) , message ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the weitereAdresse property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < WeitereAdresse > getWeitereAdresse ( ) { if ( weitereAdresse == null ) { weitereAdresse = new ArrayList < WeitereAdresse > ( ) ; } return this . weitereAdresse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the userDefinedSimplefield property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < UserDefinedSimplefield > getUserDefinedSimplefield ( ) { if ( userDefinedSimplefield == null ) { userDefinedSimplefield = new ArrayList < UserDefinedSimplefield > ( ) ; } return this . userDefinedSimplefield ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the userDefinedAnyfield property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < UserDefinedAnyfield > getUserDefinedAnyfield ( ) { if ( userDefinedAnyfield == null ) { userDefinedAnyfield = new ArrayList < UserDefinedAnyfield > ( ) ; } return this . userDefinedAnyfield ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the apiSuchfelder property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setApiSuchfelder ( JAXBElement < ApiSuchfelderTyp > value ) { this . apiSuchfelder = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the multimediaAnhang property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < MultimediaAnhangTyp > getMultimediaAnhang ( ) { if ( multimediaAnhang == null ) { multimediaAnhang = new ArrayList < MultimediaAnhangTyp > ( ) ; } return this . multimediaAnhang ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the statusVBM property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public StatusTyp getStatusVBM ( ) { if ( statusVBM == null ) { return StatusTyp . AKTIV ; } else { return statusVBM ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the statusIS24 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public StatusTyp getStatusIS24 ( ) { if ( statusIS24 == null ) { return StatusTyp . AKTIV ; } else { return statusIS24 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the statusHP property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public StatusTyp getStatusHP ( ) { if ( statusHP == null ) { return StatusTyp . AKTIV ; } else { return statusHP ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the importmodus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public AktionsTyp getImportmodus ( ) { if ( importmodus == null ) { return AktionsTyp . IMPORTIEREN ; } else { return importmodus ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the adressdruck property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public Boolean getAdressdruck ( ) { if ( adressdruck == null ) { return false ; } else { return adressdruck ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the waehrung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public WaehrungTyp getWaehrung ( ) { if ( waehrung == null ) { return WaehrungTyp . EUR ; } else { return waehrung ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( TrovitWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a Trovit object with some example data // this object corresponds to the <trovit> element in XML Trovit trovit = FACTORY . createTrovit ( ) ; // append some example ads to the transfer trovit . getAd ( ) . add ( createAd ( ) ) ; trovit . getAd ( ) . add ( createAd ( ) ) ; trovit . getAd ( ) . add ( createAd ( ) ) ; // convert the Trovit object into a XML document TrovitDocument doc = null ; try { doc = TrovitDocument . newDocument ( trovit ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link AdType } with some example data . [CODESPLIT] @ SuppressWarnings ( \"CatchMayIgnoreException\" ) protected static AdType createAd ( ) { // create an example real estate AdType ad = FACTORY . createAdType ( ) ; ad . setAddress ( \"object address\" ) ; ad . setAgency ( \"name of the agency\" ) ; ad . setBathrooms ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 5 ) ) ) ; ad . setByOwner ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setCity ( \"name of the city\" ) ; ad . setCityArea ( \"name of the district\" ) ; ad . setCondition ( \"some notes about the condition\" ) ; ad . setContactEmail ( \"test@mywebsite.org\" ) ; ad . setContactName ( \"John Smith\" ) ; ad . setContactTelephone ( \"0049301234567\" ) ; ad . setContent ( \"some more descriptions\" ) ; ad . setCountry ( \"DE\" ) ; ad . setDate ( Calendar . getInstance ( ) ) ; ad . setEcoScore ( \"A\" ) ; ad . setExpirationDate ( Calendar . getInstance ( ) ) ; ad . setFloorNumber ( \"number of floors\" ) ; ad . setForeclosure ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setForeclosureType ( ForeclosureTypeValue . values ( ) [ RandomUtils . nextInt ( 0 , ForeclosureTypeValue . values ( ) . length ) ] ) ; ad . setId ( RandomStringUtils . random ( 5 ) ) ; ad . setIsFurnished ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setIsNew ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setIsRentToOwn ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setLatitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 180 ) - 90 ) ) ; ad . setLongitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 360 ) - 180 ) ) ; ad . setMlsDatabase ( \"notes about mls database\" ) ; ad . setNeighborhood ( \"notes about the neighborhood\" ) ; ad . setOrientation ( OrientationValue . values ( ) [ RandomUtils . nextInt ( 0 , OrientationValue . values ( ) . length ) ] ) ; ad . setParking ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setPostcode ( \"postcode\" ) ; ad . setPropertyType ( \"notes about the property type\" ) ; ad . setRegion ( \"notes about the region\" ) ; ad . setRooms ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1 , 10 ) ) ) ; ad . setTitle ( \"title of the object\" ) ; ad . setType ( TypeValue . values ( ) [ RandomUtils . nextInt ( 0 , TypeValue . values ( ) . length ) ] ) ; ad . setYear ( BigInteger . valueOf ( RandomUtils . nextInt ( 1700 , 2017 ) ) ) ; ad . setFloorArea ( FACTORY . createFloorAreaType ( ) ) ; ad . getFloorArea ( ) . setUnit ( AreaUnitValue . values ( ) [ RandomUtils . nextInt ( 0 , AreaUnitValue . values ( ) . length ) ] ) ; ad . getFloorArea ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextInt ( 10 , 10000 ) ) ) ; ad . setPictures ( FACTORY . createAdTypePictures ( ) ) ; ad . getPictures ( ) . getPicture ( ) . add ( createPicture ( 0 ) ) ; ad . getPictures ( ) . getPicture ( ) . add ( createPicture ( 1 ) ) ; ad . getPictures ( ) . getPicture ( ) . add ( createPicture ( 2 ) ) ; ad . setPlotArea ( FACTORY . createPlotAreaType ( ) ) ; ad . getPlotArea ( ) . setUnit ( AreaUnitValue . values ( ) [ RandomUtils . nextInt ( 0 , AreaUnitValue . values ( ) . length ) ] ) ; ad . getPlotArea ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextInt ( 10 , 10000 ) ) ) ; ad . setPrice ( FACTORY . createPriceType ( ) ) ; ad . getPrice ( ) . setPeriod ( PricePeriodValue . values ( ) [ RandomUtils . nextInt ( 0 , PricePeriodValue . values ( ) . length ) ] ) ; ad . getPrice ( ) . setValue ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100 , 2000 ) ) . setScale ( 2 , RoundingMode . HALF_EVEN ) ) ; try { ad . setUrl ( new URI ( \"http://mywebsite.org/\" ) ) ; ad . setMobileUrl ( new URI ( \"http://mobile.mywebsite.org/\" ) ) ; ad . setVirtualTour ( new URI ( \"http://tour.mywebsite.org/\" ) ) ; } catch ( URISyntaxException ex ) { } return ad ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link PictureType } with some example data . [CODESPLIT] protected static PictureType createPicture ( int pos ) { try { PictureType pic = FACTORY . createPictureType ( ) ; pic . setPictureTitle ( \"some descriptive title\" ) ; pic . setPictureUrl ( new URI ( \"http://mywebsite.org/image\" + pos + \".jpg\" ) ) ; pic . setFeatured ( pos == 0 ) ; return pic ; } catch ( URISyntaxException ex ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( KyeroWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a Root object with some example data // this object corresponds to the <root> element in XML Root root = FACTORY . createRoot ( ) ; root . setKyero ( createKyero ( ) ) ; root . setAgent ( createAgent ( ) ) ; root . getProperty ( ) . add ( createProperty ( ) ) ; root . getProperty ( ) . add ( createProperty ( ) ) ; root . getProperty ( ) . add ( createProperty ( ) ) ; // convert the Root object into a XML document KyeroDocument doc = null ; try { doc = KyeroDocument . newDocument ( root ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; // downgrade XML document to an earlier version // and write it to the console doc . downgrade ( KyeroVersion . V2_1 ) ; writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Agent } object with some example data . [CODESPLIT] protected static Agent createAgent ( ) { Agent agent = FACTORY . createRootAgent ( ) ; agent . setAddr1 ( \"first address line\" ) ; agent . setAddr2 ( \"second address line\" ) ; agent . setCountry ( \"Germany\" ) ; agent . setEmail ( \"test@test.org\" ) ; agent . setFax ( \"030/123456\" ) ; agent . setId ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 10000 ) ) ) ; agent . setMob ( \"030/123457\" ) ; agent . setName ( \"name of the company\" ) ; agent . setPostcode ( \"12345\" ) ; agent . setRegion ( \"Berlin\" ) ; agent . setTel ( \"030/123458\" ) ; agent . setTown ( \"Berlin\" ) ; return agent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link KyeroType } object with some example data . [CODESPLIT] protected static KyeroType createKyero ( ) { KyeroType kyero = FACTORY . createKyeroType ( ) ; kyero . setFeedGenerated ( Calendar . getInstance ( ) ) ; kyero . setFeedVersion ( KyeroUtils . VERSION . toXmlVersion ( ) ) ; return kyero ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link PropertyType } object with some example data . [CODESPLIT] @ SuppressWarnings ( \"CatchMayIgnoreException\" ) protected static PropertyType createProperty ( ) { final String id = RandomStringUtils . random ( 5 ) ; int imageCount = 0 ; // create an example real estate PropertyType obj = FACTORY . createPropertyType ( ) ; obj . setBaths ( BigInteger . valueOf ( RandomUtils . nextLong ( 0 , 5 ) ) ) ; obj . setBeds ( BigInteger . valueOf ( RandomUtils . nextLong ( 0 , 5 ) ) ) ; obj . setCountry ( \"Germany\" ) ; obj . setCurrency ( CurrencyType . EUR ) ; obj . setDate ( Calendar . getInstance ( ) ) ; obj . setId ( id ) ; obj . setLeasehold ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setLocationDetail ( \"some details about the location\" ) ; obj . setNewBuild ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setNotes ( \"some notes about the property\" ) ; obj . setPartOwnership ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setPool ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setPrice ( RandomUtils . nextLong ( 10000 , 9999999 ) ) ; obj . setPriceFreq ( PriceFreqType . SALE ) ; obj . setProvince ( \"Berlin\" ) ; obj . setRef ( RandomStringUtils . random ( 5 ) ) ; obj . setTown ( \"Berlin\" ) ; obj . setType ( \"house\" ) ; obj . setDesc ( FACTORY . createLangType ( ) ) ; obj . getDesc ( ) . setCa ( \"Catalan property description\" ) ; obj . getDesc ( ) . setDa ( \"Danish property description\" ) ; obj . getDesc ( ) . setDe ( \"German property description\" ) ; obj . getDesc ( ) . setEn ( \"English property description\" ) ; obj . getDesc ( ) . setEs ( \"Spanish property description\" ) ; obj . getDesc ( ) . setFi ( \"Finnish property description\" ) ; obj . getDesc ( ) . setFr ( \"French property description\" ) ; obj . getDesc ( ) . setIt ( \"Italian property description\" ) ; obj . getDesc ( ) . setNl ( \"Dutch property description\" ) ; obj . getDesc ( ) . setNo ( \"Norwegian property description\" ) ; obj . getDesc ( ) . setPt ( \"Portuguese property description\" ) ; obj . getDesc ( ) . setRu ( \"Russian property description\" ) ; obj . getDesc ( ) . setSv ( \"Swedish property description\" ) ; obj . setEnergyRating ( FACTORY . createEnergyRatingType ( ) ) ; obj . getEnergyRating ( ) . setConsumption ( EnergyRatingMarkType . C ) ; obj . getEnergyRating ( ) . setEmissions ( EnergyRatingMarkType . E ) ; obj . setFeatures ( FACTORY . createFeaturesType ( ) ) ; obj . getFeatures ( ) . getFeature ( ) . add ( \"name of a feature\" ) ; obj . getFeatures ( ) . getFeature ( ) . add ( \"name of another feature\" ) ; obj . setImages ( FACTORY . createImagesType ( ) ) ; obj . getImages ( ) . getImage ( ) . add ( createPropertyImage ( id , ++ imageCount ) ) ; obj . getImages ( ) . getImage ( ) . add ( createPropertyImage ( id , ++ imageCount ) ) ; obj . getImages ( ) . getImage ( ) . add ( createPropertyImage ( id , ++ imageCount ) ) ; obj . setLocation ( FACTORY . createGpsLocationType ( ) ) ; obj . getLocation ( ) . setLatitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . getLocation ( ) . setLongitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . setSurfaceArea ( FACTORY . createSurfaceType ( ) ) ; obj . getSurfaceArea ( ) . setBuilt ( BigInteger . valueOf ( RandomUtils . nextLong ( 50 , 250 ) ) ) ; obj . getSurfaceArea ( ) . setPlot ( BigInteger . valueOf ( RandomUtils . nextLong ( 100 , 1500 ) ) ) ; obj . setUrl ( FACTORY . createUrlType ( ) ) ; try { obj . getUrl ( ) . setCa ( new URI ( \"http://catalan.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setDa ( new URI ( \"http://danish.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setDe ( new URI ( \"http://german.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setEn ( new URI ( \"http://english.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setEs ( new URI ( \"http://spanish.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setFi ( new URI ( \"http://finnish.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setFr ( new URI ( \"http://french.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setIt ( new URI ( \"http://italian.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setNl ( new URI ( \"http://dutch.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setNo ( new URI ( \"http://norwegian.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setPt ( new URI ( \"http://portuguese.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setRu ( new URI ( \"http://russian.website.com/property/\" + id + \".htm\" ) ) ; obj . getUrl ( ) . setSv ( new URI ( \"http://swedish.website.com/property/\" + id + \".htm\" ) ) ; } catch ( URISyntaxException ex ) { } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Image } object with some example data . [CODESPLIT] @ SuppressWarnings ( \"CatchMayIgnoreException\" ) protected static Image createPropertyImage ( String id , int pos ) { // create an example image Image img = FACTORY . createImagesTypeImage ( ) ; img . setId ( pos ) ; try { img . setUrl ( new URI ( \"http://website.com/property/\" + id + \"/image_\" + pos + \".jpg\" ) ) ; } catch ( URISyntaxException ex ) { } return img ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"openimmo_anid\" ) public JAXBElement < String > createOpenimmoAnid ( String value ) { return new JAXBElement < String > ( _OpenimmoAnid_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"lizenzkennung\" ) public JAXBElement < String > createLizenzkennung ( String value ) { return new JAXBElement < String > ( _Lizenzkennung_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"bundesland\" ) public JAXBElement < String > createBundesland ( String value ) { return new JAXBElement < String > ( _Bundesland_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gemeindecode\" ) public JAXBElement < String > createGemeindecode ( String value ) { return new JAXBElement < String > ( _Gemeindecode_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"flur\" ) public JAXBElement < String > createFlur ( String value ) { return new JAXBElement < String > ( _Flur_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigInteger } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_etagen\" ) @ XmlJavaTypeAdapter ( Adapter5 . class ) public JAXBElement < BigInteger > createAnzahlEtagen ( BigInteger value ) { return new JAXBElement < BigInteger > ( _AnzahlEtagen_QNAME , BigInteger . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"regionaler_zusatz\" ) public JAXBElement < String > createRegionalerZusatz ( String value ) { return new JAXBElement < String > ( _RegionalerZusatz_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"karten_makro\" ) public JAXBElement < Boolean > createKartenMakro ( Boolean value ) { return new JAXBElement < Boolean > ( _KartenMakro_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"karten_mikro\" ) public JAXBElement < Boolean > createKartenMikro ( Boolean value ) { return new JAXBElement < Boolean > ( _KartenMikro_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"virtuelletour\" ) public JAXBElement < Boolean > createVirtuelletour ( Boolean value ) { return new JAXBElement < Boolean > ( _Virtuelletour_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"luftbildern\" ) public JAXBElement < Boolean > createLuftbildern ( Boolean value ) { return new JAXBElement < Boolean > ( _Luftbildern_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"referenz_id\" ) public JAXBElement < String > createReferenzId ( String value ) { return new JAXBElement < String > ( _ReferenzId_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"titel\" ) public JAXBElement < String > createTitel ( String value ) { return new JAXBElement < String > ( _Titel_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"position\" ) public JAXBElement < String > createPosition ( String value ) { return new JAXBElement < String > ( _Position_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"zusatzfeld\" ) public JAXBElement < String > createZusatzfeld ( String value ) { return new JAXBElement < String > ( _Zusatzfeld_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"postf_ort\" ) public JAXBElement < String > createPostfOrt ( String value ) { return new JAXBElement < String > ( _PostfOrt_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"email_direkt\" ) public JAXBElement < String > createEmailDirekt ( String value ) { return new JAXBElement < String > ( _EmailDirekt_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"email_feedback\" ) public JAXBElement < String > createEmailFeedback ( String value ) { return new JAXBElement < String > ( _EmailFeedback_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"tel_handy\" ) public JAXBElement < String > createTelHandy ( String value ) { return new JAXBElement < String > ( _TelHandy_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"tel_fax\" ) public JAXBElement < String > createTelFax ( String value ) { return new JAXBElement < String > ( _TelFax_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"url\" ) public JAXBElement < String > createUrl ( String value ) { return new JAXBElement < String > ( _Url_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"immobilientreuhaenderid\" ) public JAXBElement < String > createImmobilientreuhaenderid ( String value ) { return new JAXBElement < String > ( _Immobilientreuhaenderid_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"pauschalmiete\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createPauschalmiete ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Pauschalmiete_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"flaechevon\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createFlaechevon ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Flaechevon_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"flaechebis\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createFlaechebis ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Flaechebis_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gesamtmietebrutto\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createGesamtmietebrutto ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Gesamtmietebrutto_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gesamtbelastungbrutto\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createGesamtbelastungbrutto ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Gesamtbelastungbrutto_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kaufpreisbrutto\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createKaufpreisbrutto ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Kaufpreisbrutto_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"monatlichekostenbrutto\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createMonatlichekostenbrutto ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Monatlichekostenbrutto_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"provisionbrutto\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createProvisionbrutto ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Provisionbrutto_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"richtpreisprom2\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createRichtpreisprom2 ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Richtpreisprom2_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"nettokaltmiete\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createNettokaltmiete ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Nettokaltmiete_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kaltmiete\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createKaltmiete ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Kaltmiete_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"nebenkosten\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createNebenkosten ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Nebenkosten_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"warmmiete\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createWarmmiete ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Warmmiete_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"heizkosten_enthalten\" ) public JAXBElement < Boolean > createHeizkostenEnthalten ( Boolean value ) { return new JAXBElement < Boolean > ( _HeizkostenEnthalten_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"pacht\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createPacht ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Pacht_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"erbpacht\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createErbpacht ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Erbpacht_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"hausgeld\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createHausgeld ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Hausgeld_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"abstand\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAbstand ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Abstand_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"preis_zeitraum_von\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createPreisZeitraumVon ( Calendar value ) { return new JAXBElement < Calendar > ( _PreisZeitraumVon_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"richtpreis\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createRichtpreis ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Richtpreis_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Stellplatz } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"stp_freiplatz\" ) public JAXBElement < Stellplatz > createStpFreiplatz ( Stellplatz value ) { return new JAXBElement < Stellplatz > ( _StpFreiplatz_QNAME , Stellplatz . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Stellplatz } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"stp_tiefgarage\" ) public JAXBElement < Stellplatz > createStpTiefgarage ( Stellplatz value ) { return new JAXBElement < Stellplatz > ( _StpTiefgarage_QNAME , Stellplatz . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Stellplatz } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"stp_garage\" ) public JAXBElement < Stellplatz > createStpGarage ( Stellplatz value ) { return new JAXBElement < Stellplatz > ( _StpGarage_QNAME , Stellplatz . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Stellplatz } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"stp_carport\" ) public JAXBElement < Stellplatz > createStpCarport ( Stellplatz value ) { return new JAXBElement < Stellplatz > ( _StpCarport_QNAME , Stellplatz . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Stellplatz } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"stp_duplex\" ) public JAXBElement < Stellplatz > createStpDuplex ( Stellplatz value ) { return new JAXBElement < Stellplatz > ( _StpDuplex_QNAME , Stellplatz . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"provisionspflichtig\" ) public JAXBElement < Boolean > createProvisionspflichtig ( Boolean value ) { return new JAXBElement < Boolean > ( _Provisionspflichtig_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"courtage_hinweis\" ) public JAXBElement < String > createCourtageHinweis ( String value ) { return new JAXBElement < String > ( _CourtageHinweis_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"mwst_satz\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createMwstSatz ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _MwstSatz_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"mwst_gesamt\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createMwstGesamt ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _MwstGesamt_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"nettorendite_ist\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createNettorenditeIst ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _NettorenditeIst_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"nettorendite_soll\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createNettorenditeSoll ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _NettorenditeSoll_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"erschliessungskosten\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createErschliessungskosten ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Erschliessungskosten_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kaution_text\" ) public JAXBElement < String > createKautionText ( String value ) { return new JAXBElement < String > ( _KautionText_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"lagerflaeche\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createLagerflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Lagerflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"verkaufsflaeche\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createVerkaufsflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Verkaufsflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gastroflaeche\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createGastroflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Gastroflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"grz\" ) public JAXBElement < String > createGrz ( String value ) { return new JAXBElement < String > ( _Grz_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_badezimmer\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlBadezimmer ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlBadezimmer_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_sep_wc\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlSepWc ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlSepWc_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_balkone\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlBalkone ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlBalkone_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_terrassen\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlTerrassen ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlTerrassen_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_logia\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlLogia ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlLogia_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kellerflaeche\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createKellerflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Kellerflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"fensterfront_qm\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createFensterfrontQm ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _FensterfrontQm_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"grundstuecksfront\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createGrundstuecksfront ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Grundstuecksfront_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"dachbodenflaeche\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createDachbodenflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Dachbodenflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigInteger } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_stellplaetze\" ) @ XmlJavaTypeAdapter ( Adapter6 . class ) public JAXBElement < BigInteger > createAnzahlStellplaetze ( BigInteger value ) { return new JAXBElement < BigInteger > ( _AnzahlStellplaetze_QNAME , BigInteger . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"plaetze_gastraum\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createPlaetzeGastraum ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _PlaetzeGastraum_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_betten\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlBetten ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlBetten_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_tagungsraeume\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlTagungsraeume ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlTagungsraeume_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"vermietbare_flaeche\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createVermietbareFlaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _VermietbareFlaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anzahl_wohneinheiten\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAnzahlWohneinheiten ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlWohneinheiten_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kubatur\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createKubatur ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Kubatur_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"ausnuetzungsziffer\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createAusnuetzungsziffer ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Ausnuetzungsziffer_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"beginn_angebotsphase\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createBeginnAngebotsphase ( Calendar value ) { return new JAXBElement < Calendar > ( _BeginnAngebotsphase_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"besichtigungstermin\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createBesichtigungstermin ( Calendar value ) { return new JAXBElement < Calendar > ( _Besichtigungstermin_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"besichtigungstermin_2\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createBesichtigungstermin2 ( Calendar value ) { return new JAXBElement < Calendar > ( _Besichtigungstermin2_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"beginn_bietzeit\" ) @ XmlJavaTypeAdapter ( Adapter3 . class ) public JAXBElement < Calendar > createBeginnBietzeit ( Calendar value ) { return new JAXBElement < Calendar > ( _BeginnBietzeit_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"ende_bietzeit\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createEndeBietzeit ( Calendar value ) { return new JAXBElement < Calendar > ( _EndeBietzeit_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"hoechstgebot_zeigen\" ) public JAXBElement < Boolean > createHoechstgebotZeigen ( Boolean value ) { return new JAXBElement < Boolean > ( _HoechstgebotZeigen_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"mindestpreis\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createMindestpreis ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Mindestpreis_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"zwangsversteigerung\" ) public JAXBElement < Boolean > createZwangsversteigerung ( Boolean value ) { return new JAXBElement < Boolean > ( _Zwangsversteigerung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"aktenzeichen\" ) public JAXBElement < String > createAktenzeichen ( String value ) { return new JAXBElement < String > ( _Aktenzeichen_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"zvtermin\" ) @ XmlJavaTypeAdapter ( Adapter3 . class ) public JAXBElement < Calendar > createZvtermin ( Calendar value ) { return new JAXBElement < Calendar > ( _Zvtermin_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"zusatztermin\" ) @ XmlJavaTypeAdapter ( Adapter3 . class ) public JAXBElement < Calendar > createZusatztermin ( Calendar value ) { return new JAXBElement < Calendar > ( _Zusatztermin_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"amtsgericht\" ) public JAXBElement < String > createAmtsgericht ( String value ) { return new JAXBElement < String > ( _Amtsgericht_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"verkehrswert\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createVerkehrswert ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Verkehrswert_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link AusstattKategorie } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"ausstatt_kategorie\" ) public JAXBElement < AusstattKategorie > createAusstattKategorie ( AusstattKategorie value ) { return new JAXBElement < AusstattKategorie > ( _AusstattKategorie_QNAME , AusstattKategorie . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"raeume_veraenderbar\" ) public JAXBElement < Boolean > createRaeumeVeraenderbar ( Boolean value ) { return new JAXBElement < Boolean > ( _RaeumeVeraenderbar_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kamin\" ) public JAXBElement < Boolean > createKamin ( Boolean value ) { return new JAXBElement < Boolean > ( _Kamin_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"klimatisiert\" ) public JAXBElement < Boolean > createKlimatisiert ( Boolean value ) { return new JAXBElement < Boolean > ( _Klimatisiert_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gartennutzung\" ) public JAXBElement < Boolean > createGartennutzung ( Boolean value ) { return new JAXBElement < Boolean > ( _Gartennutzung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"rollstuhlgerecht\" ) public JAXBElement < Boolean > createRollstuhlgerecht ( Boolean value ) { return new JAXBElement < Boolean > ( _Rollstuhlgerecht_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"dvbt\" ) public JAXBElement < Boolean > createDvbt ( Boolean value ) { return new JAXBElement < Boolean > ( _Dvbt_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"sauna\" ) public JAXBElement < Boolean > createSauna ( Boolean value ) { return new JAXBElement < Boolean > ( _Sauna_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"swimmingpool\" ) public JAXBElement < Boolean > createSwimmingpool ( Boolean value ) { return new JAXBElement < Boolean > ( _Swimmingpool_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"wasch_trockenraum\" ) public JAXBElement < Boolean > createWaschTrockenraum ( Boolean value ) { return new JAXBElement < Boolean > ( _WaschTrockenraum_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"wintergarten\" ) public JAXBElement < Boolean > createWintergarten ( Boolean value ) { return new JAXBElement < Boolean > ( _Wintergarten_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"dv_verkabelung\" ) public JAXBElement < Boolean > createDvVerkabelung ( Boolean value ) { return new JAXBElement < Boolean > ( _DvVerkabelung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"rampe\" ) public JAXBElement < Boolean > createRampe ( Boolean value ) { return new JAXBElement < Boolean > ( _Rampe_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"hebebuehne\" ) public JAXBElement < Boolean > createHebebuehne ( Boolean value ) { return new JAXBElement < Boolean > ( _Hebebuehne_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gastterrasse\" ) public JAXBElement < Boolean > createGastterrasse ( Boolean value ) { return new JAXBElement < Boolean > ( _Gastterrasse_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"stromanschlusswert\" ) public JAXBElement < String > createStromanschlusswert ( String value ) { return new JAXBElement < String > ( _Stromanschlusswert_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kantine_cafeteria\" ) public JAXBElement < Boolean > createKantineCafeteria ( Boolean value ) { return new JAXBElement < Boolean > ( _KantineCafeteria_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"teekueche\" ) public JAXBElement < Boolean > createTeekueche ( Boolean value ) { return new JAXBElement < Boolean > ( _Teekueche_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"hallenhoehe\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createHallenhoehe ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Hallenhoehe_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"brauereibindung\" ) public JAXBElement < Boolean > createBrauereibindung ( Boolean value ) { return new JAXBElement < Boolean > ( _Brauereibindung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"sporteinrichtungen\" ) public JAXBElement < Boolean > createSporteinrichtungen ( Boolean value ) { return new JAXBElement < Boolean > ( _Sporteinrichtungen_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"telefon_ferienimmobilie\" ) public JAXBElement < Boolean > createTelefonFerienimmobilie ( Boolean value ) { return new JAXBElement < Boolean > ( _TelefonFerienimmobilie_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"umts_empfang\" ) public JAXBElement < Boolean > createUmtsEmpfang ( Boolean value ) { return new JAXBElement < Boolean > ( _UmtsEmpfang_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"abstellraum\" ) public JAXBElement < Boolean > createAbstellraum ( Boolean value ) { return new JAXBElement < Boolean > ( _Abstellraum_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"fahrradraum\" ) public JAXBElement < Boolean > createFahrradraum ( Boolean value ) { return new JAXBElement < Boolean > ( _Fahrradraum_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"rolladen\" ) public JAXBElement < Boolean > createRolladen ( Boolean value ) { return new JAXBElement < Boolean > ( _Rolladen_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"bibliothek\" ) public JAXBElement < Boolean > createBibliothek ( Boolean value ) { return new JAXBElement < Boolean > ( _Bibliothek_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"dachboden\" ) public JAXBElement < Boolean > createDachboden ( Boolean value ) { return new JAXBElement < Boolean > ( _Dachboden_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gaestewc\" ) public JAXBElement < Boolean > createGaestewc ( Boolean value ) { return new JAXBElement < Boolean > ( _Gaestewc_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"kabelkanaele\" ) public JAXBElement < Boolean > createKabelkanaele ( Boolean value ) { return new JAXBElement < Boolean > ( _Kabelkanaele_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"seniorengerecht\" ) public JAXBElement < Boolean > createSeniorengerecht ( Boolean value ) { return new JAXBElement < Boolean > ( _Seniorengerecht_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"letztemodernisierung\" ) public JAXBElement < String > createLetztemodernisierung ( String value ) { return new JAXBElement < String > ( _Letztemodernisierung_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"bauzone\" ) public JAXBElement < String > createBauzone ( String value ) { return new JAXBElement < String > ( _Bauzone_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"dreizeiler\" ) public JAXBElement < String > createDreizeiler ( String value ) { return new JAXBElement < String > ( _Dreizeiler_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"lage\" ) public JAXBElement < String > createLage ( String value ) { return new JAXBElement < String > ( _Lage_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"pfad\" ) public JAXBElement < String > createPfad ( String value ) { return new JAXBElement < String > ( _Pfad_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"objektadresse_freigeben\" ) public JAXBElement < Boolean > createObjektadresseFreigeben ( Boolean value ) { return new JAXBElement < Boolean > ( _ObjektadresseFreigeben_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"anbieternr\" ) public JAXBElement < String > createAnbieternr ( String value ) { return new JAXBElement < String > ( _Anbieternr_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"objektnr_intern\" ) public JAXBElement < String > createObjektnrIntern ( String value ) { return new JAXBElement < String > ( _ObjektnrIntern_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigInteger } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"max_personen\" ) @ XmlJavaTypeAdapter ( Adapter6 . class ) public JAXBElement < BigInteger > createMaxPersonen ( BigInteger value ) { return new JAXBElement < BigInteger > ( _MaxPersonen_QNAME , BigInteger . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"nichtraucher\" ) public JAXBElement < Boolean > createNichtraucher ( Boolean value ) { return new JAXBElement < Boolean > ( _Nichtraucher_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"openimmo_obid\" ) public JAXBElement < String > createOpenimmoObid ( String value ) { return new JAXBElement < String > ( _OpenimmoObid_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"weitergabe_negativ\" ) public JAXBElement < String > createWeitergabeNegativ ( String value ) { return new JAXBElement < String > ( _WeitergabeNegativ_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"weitergabe_positiv\" ) public JAXBElement < String > createWeitergabePositiv ( String value ) { return new JAXBElement < String > ( _WeitergabePositiv_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"gruppen_kennung\" ) public JAXBElement < String > createGruppenKennung ( String value ) { return new JAXBElement < String > ( _GruppenKennung_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"sprache\" ) public JAXBElement < String > createSprache ( String value ) { return new JAXBElement < String > ( _Sprache_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"objektart_zusatz\" ) public JAXBElement < String > createObjektartZusatz ( String value ) { return new JAXBElement < String > ( _ObjektartZusatz_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"impressum\" ) public JAXBElement < String > createImpressum ( String value ) { return new JAXBElement < String > ( _Impressum_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"\" , name = \"version\" ) public JAXBElement < String > createVersion ( String value ) { return new JAXBElement < String > ( _Version_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the bodenbelag property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public BodenbelagTyp getBodenbelag ( ) { if ( bodenbelag == null ) { return BodenbelagTyp . KEINE_ANGABE ; } else { return bodenbelag ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the region property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setRegion ( java . lang . String value ) { this . region = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the area property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setArea ( java . lang . String value ) { this . area = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the address property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setAddress ( java . lang . String value ) { this . address = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the description property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setDescription ( java . lang . String value ) { this . description = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the rentCollectionPeriod property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setRentCollectionPeriod ( OverseasRentalAdType . RentPeriod value ) { this . rentCollectionPeriod = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the furnished property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setFurnished ( OverseasRentalAdType . Furnished value ) { this . furnished = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the phone1 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPhone1 ( java . lang . String value ) { this . phone1 = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the phone2 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPhone2 ( java . lang . String value ) { this . phone2 = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the contactName property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setContactName ( java . lang . String value ) { this . contactName = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the phoneInfo property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPhoneInfo ( java . lang . String value ) { this . phoneInfo = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the mainEmail property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMainEmail ( java . lang . String value ) { this . mainEmail = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the ccEmail property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setCcEmail ( java . lang . String value ) { this . ccEmail = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the externalId property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setExternalId ( java . lang . String value ) { this . externalId = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the agentId property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setAgentId ( java . lang . String value ) { this . agentId = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( Is24CsvWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create some CSV records List < Is24CsvRecord > records = new ArrayList <> ( ) ; records . add ( createHausKaufRecord ( ) ) ; records . add ( createHausKaufRecord ( ) ) ; records . add ( createWohnungMieteRecord ( ) ) ; records . add ( createWohnungMieteRecord ( ) ) ; // write CSV records into a java.io.File try { write ( records , File . createTempFile ( \"output-\" , \".csv\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write CSV records into a java.io.OutputStream write ( records , new NullOutputStream ( ) ) ; // write CSV records into a java.io.Writer write ( records , new NullWriter ( ) ) ; // write CSV records into a string and send it to the console writeToConsole ( records ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link HausKauf } with some example data . [CODESPLIT] protected static Is24CsvRecord createHausKaufRecord ( ) { // create an example real estate HausKauf obj = new HausKauf ( ) ; init ( obj ) ; obj . setAnzahlBadezimmer ( RandomUtils . nextInt ( 1 , 5 ) ) ; obj . setAnzahlGarageStellplatz ( RandomUtils . nextInt ( 1 , 5 ) ) ; obj . setAnzahlSchlafzimmer ( RandomUtils . nextInt ( 1 , 5 ) ) ; obj . setAusstattung ( Ausstattung . GEHOBEN ) ; obj . setBarrierefrei ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBaujahr ( RandomUtils . nextInt ( 1900 , 1990 ) ) ; obj . setBauphase ( Bauphase . FERTIG_GESTELLT ) ; obj . setBefeuerungsart ( Befeuerungsart . KOHLE ) ; obj . setDenkmalschutz ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEinliegerwohnung ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEnergieausweisInklWarmwasser ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEnergieausweisKennwert ( RandomUtils . nextDouble ( 50 , 500 ) ) ; obj . setEnergieausweisTyp ( EnergieausweisTyp . ENERGIEVERBRAUCHSKENNWERT ) ; obj . setFerienhaus ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGaesteWc ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGrundstuecksflaeche ( RandomUtils . nextDouble ( 200 , 2000 ) ) ; obj . setHeizungsart ( Heizungsart . ZENTRALHEIZUNG ) ; obj . setKaufpreis ( RandomUtils . nextDouble ( 100000 , 1000000 ) ) ; obj . setKeller ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setMieteinnahmenProMonat ( RandomUtils . nextDouble ( 5000 , 50000 ) ) ; obj . setNutzflaeche ( RandomUtils . nextDouble ( 200 , 1000 ) ) ; obj . setObjektkategorie ( ObjektkategorieHaus . MEHRFAMILIENHAUS ) ; obj . setObjektzustand ( Objektzustand . GEPFLEGT ) ; obj . setSanierungsjahr ( RandomUtils . nextInt ( 1990 , 2010 ) ) ; obj . setStellplatz ( Stellplatz . CARPORT ) ; obj . setStellplatzpreis ( RandomUtils . nextDouble ( 1000 , 5000 ) ) ; obj . setVerfuegbarAb ( \"notes about availability\" ) ; obj . setVermietet ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setWohnflaeche ( RandomUtils . nextDouble ( 100 , 500 ) ) ; obj . setZimmer ( RandomUtils . nextInt ( 1 , 10 ) ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link WohnungMiete } with some example data . [CODESPLIT] protected static Is24CsvRecord createWohnungMieteRecord ( ) { // create an example real estate WohnungMiete obj = new WohnungMiete ( ) ; init ( obj ) ; obj . setAnzahlBadezimmer ( RandomUtils . nextInt ( 1 , 5 ) ) ; obj . setAnzahlGarageStellplatz ( RandomUtils . nextInt ( 1 , 5 ) ) ; obj . setAnzahlSchlafzimmer ( RandomUtils . nextInt ( 1 , 5 ) ) ; obj . setAufzug ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setAusstattung ( Ausstattung . GEHOBEN ) ; obj . setBalkonTerrasse ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBarrierefrei ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBaujahr ( RandomUtils . nextInt ( 1900 , 1990 ) ) ; obj . setBefeuerungsart ( Befeuerungsart . OEL ) ; obj . setEinbaukueche ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEnergieausweisInklWarmwasser ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEnergieausweisKennwert ( RandomUtils . nextDouble ( 50 , 500 ) ) ; obj . setEnergieausweisTyp ( EnergieausweisTyp . ENERGIEVERBRAUCHSKENNWERT ) ; obj . setEtage ( RandomUtils . nextInt ( 0 , 10 ) ) ; obj . setEtagenzahl ( RandomUtils . nextInt ( 0 , 10 ) ) ; obj . setFoerderung ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGaesteWc ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGartennutzung ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setHaustiere ( Auswahl . NACH_VEREINBARUNG ) ; obj . setHeizkosten ( RandomUtils . nextDouble ( 100 , 500 ) ) ; obj . setHeizungsart ( Heizungsart . OFENHEIZUNG ) ; obj . setKaltmiete ( RandomUtils . nextDouble ( 500 , 3000 ) ) ; obj . setKaution ( \"notes about deposit\" ) ; obj . setKeller ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setNebenkosten ( RandomUtils . nextDouble ( 100 , 500 ) ) ; obj . setNebenkostenInklHeizkosten ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setNutzflaeche ( RandomUtils . nextDouble ( 50 , 500 ) ) ; obj . setObjektkategorie ( ObjektkategorieWohnung . PENTHOUSE ) ; obj . setObjektzustand ( Objektzustand . MODERNISIERT ) ; obj . setSanierungsjahr ( RandomUtils . nextInt ( 1990 , 2010 ) ) ; obj . setSeniorengerecht ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setStellplatz ( Stellplatz . TIEFGARAGE ) ; obj . setStellplatzmiete ( RandomUtils . nextDouble ( 50 , 500 ) ) ; obj . setVerfuegbarAb ( \"notes about availability\" ) ; obj . setWarmmiete ( RandomUtils . nextDouble ( 500 , 2000 ) ) ; obj . setWohnflaeche ( RandomUtils . nextDouble ( 50 , 250 ) ) ; obj . setZimmer ( RandomUtils . nextInt ( 1 , 10 ) ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Init common values of an { @link Is24CsvRecord } . [CODESPLIT] protected static void init ( Is24CsvRecord obj ) { obj . setAdressdruck ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setAktiv ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setAnbieterObjektId ( RandomStringUtils . random ( 5 ) ) ; obj . setBeschreibungAusstattung ( \"description about features\" ) ; obj . setBeschreibungLage ( \"description about location\" ) ; obj . setBeschreibungObjekt ( \"description about object\" ) ; obj . setBeschreibungSonstiges ( \"further descriptions\" ) ; obj . setGruppierungId ( RandomUtils . nextInt ( 0 , 1000 ) ) ; obj . setImportmodus ( Importmodus . IMPORTIEREN ) ; obj . setInternationaleRegion ( \"name of international region\" ) ; obj . setKontaktAnrede ( \"Mr\" ) ; obj . setKontaktEmail ( \"tester@test.org\" ) ; obj . setKontaktHausNr ( \"123\" ) ; obj . setKontaktLand ( \"DEU\" ) ; obj . setKontaktMobiltelefon ( \"030/123456\" ) ; obj . setKontaktNachname ( \"Mustermann\" ) ; obj . setKontaktOrt ( \"Berlin\" ) ; obj . setKontaktPlz ( \"12345\" ) ; obj . setKontaktStrasse ( \"example street\" ) ; obj . setKontaktTelefax ( \"030/123457\" ) ; obj . setKontaktTelefon ( \"030/123458\" ) ; obj . setKontaktVorname ( \"Max\" ) ; obj . setKontaktWebseite ( \"http://www.test.org/\" ) ; obj . setObjektHausNr ( \"124\" ) ; obj . setObjektLand ( \"DEU\" ) ; obj . setObjektOrt ( \"Berlin\" ) ; obj . setObjektPlz ( \"12345\" ) ; obj . setObjektStrasse ( \"example street\" ) ; obj . setProvision ( \"commission\" ) ; obj . setProvisionpflichtig ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setProvisionshinweis ( \"notes about commission\" ) ; obj . setScoutKundenId ( RandomStringUtils . random ( 5 ) ) ; obj . setScoutObjektId ( RandomStringUtils . random ( 5 ) ) ; obj . setUeberschrift ( \"a nice title for the object\" ) ; obj . setWaehrung ( Currency . getInstance ( \"EUR\" ) ) ; obj . setDatei1 ( new Datei ( \"test1.jpg\" , DateiTyp . BILD , DateiSuffix . JPG , \"a nice image\" ) ) ; obj . setDatei2 ( new Datei ( \"test2.png\" , DateiTyp . BILD , DateiSuffix . PNG , \"another nice image\" ) ) ; obj . setDatei3 ( new Datei ( \"test3.pdf\" , DateiTyp . GRUNDRISS_PDF , DateiSuffix . PDF , \"a document with groundplan\" ) ) ; obj . setDatei4 ( new Datei ( \"http://www.test.org/\" , DateiTyp . LINK , null , \"agency website\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write some { @link Is24CsvRecord } objects into an { @link OutputStream } . [CODESPLIT] protected static void write ( List < Is24CsvRecord > records , OutputStream output ) { LOGGER . info ( \"writing document\" ) ; try { Is24CsvPrinter printer = Is24CsvPrinter . create ( output ) ; printer . printRecords ( records ) ; LOGGER . info ( \"> written to a java.io.OutputStream\" ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't write document into an OutputStream!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write some { @link Is24CsvRecord } objects into a { @link String } and print the results to the console . [CODESPLIT] protected static void writeToConsole ( List < Is24CsvRecord > records ) { LOGGER . info ( \"writing document\" ) ; StringBuilder csv = new StringBuilder ( ) ; try ( Is24CsvPrinter printer = Is24CsvPrinter . create ( csv ) ) { printer . printRecords ( records ) ; LOGGER . info ( StringUtils . repeat ( \"-\" , 50 ) + System . lineSeparator ( ) + csv . toString ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't write document into a string!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the epart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setEpart ( Energiepass . Epart value ) { this . epart = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the jahrgang property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setJahrgang ( Energiepass . Jahrgang value ) { this . jahrgang = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the gebaeudeart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGebaeudeart ( Energiepass . Gebaeudeart value ) { this . gebaeudeart = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the bueroTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setBueroTyp ( BueroPraxen . BueroTyp value ) { this . bueroTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if a string contains a parsable number . [CODESPLIT] public static boolean isNumeric ( String value , Locale locale ) { if ( value == null ) return false ; int start = 0 ; final DecimalFormatSymbols symbols = ( locale != null ) ? DecimalFormatSymbols . getInstance ( locale ) : DecimalFormatSymbols . getInstance ( ) ; if ( value . startsWith ( \"+\" ) || value . startsWith ( \"-\" ) ) start ++ ; boolean fraction = false ; for ( int i = start ; i < value . length ( ) ; i ++ ) { final char c = value . charAt ( i ) ; if ( c == symbols . getDecimalSeparator ( ) && ! fraction ) { fraction = true ; continue ; } if ( c == symbols . getGroupingSeparator ( ) && ! fraction ) { continue ; } if ( ! Character . isDigit ( c ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string value into a number . [CODESPLIT] public static Number parseNumber ( String value , Locale ... locales ) throws NumberFormatException { return parseNumber ( value , false , locales ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string value into a number . [CODESPLIT] public static Number parseNumber ( String value , boolean integerOnly , Locale ... locales ) throws NumberFormatException { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; // ignore leading plus sign if ( value . startsWith ( \"+\" ) ) value = StringUtils . trimToNull ( value . substring ( 1 ) ) ; // remove any spaces value = StringUtils . replace ( value , StringUtils . SPACE , StringUtils . EMPTY ) ; if ( ArrayUtils . isEmpty ( locales ) ) locales = new Locale [ ] { Locale . getDefault ( ) } ; for ( Locale locale : locales ) { // check, if the value is completely numeric for the locale if ( ! isNumeric ( value , locale ) ) continue ; NumberFormat format = NumberFormat . getNumberInstance ( locale ) ; try { format . setMinimumFractionDigits ( 0 ) ; format . setParseIntegerOnly ( integerOnly ) ; format . setGroupingUsed ( value . indexOf ( DecimalFormatSymbols . getInstance ( locale ) . getGroupingSeparator ( ) ) > - 1 ) ; return format . parse ( value ) ; } catch ( ParseException ex ) { } } throw new NumberFormatException ( \"The provided value '\" + value + \"' is not numeric!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a number into a string value . [CODESPLIT] public static String printNumber ( Number value , int integerDigits , int fractionDigits ) { return printNumber ( value , integerDigits , fractionDigits , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a number into a string value . [CODESPLIT] public static String printNumber ( Number value , int integerDigits , int fractionDigits , Locale locale ) { if ( value == null ) return null ; NumberFormat format = NumberFormat . getNumberInstance ( ( locale != null ) ? locale : Locale . ENGLISH ) ; format . setMaximumIntegerDigits ( integerDigits ) ; format . setMaximumFractionDigits ( fractionDigits ) ; format . setMinimumFractionDigits ( 0 ) ; format . setGroupingUsed ( false ) ; return format . format ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the gebiete property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGebiete ( LageGebiet . Gebiete value ) { this . gebiete = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link FilemakerResultDocument } from a { @link FMPXMLRESULT } object . [CODESPLIT] public static FilemakerResultDocument newDocument ( FMPXMLRESULT xmlResult ) throws ParserConfigurationException , JAXBException { Document document = XmlUtils . newDocument ( ) ; FilemakerUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( xmlResult , document ) ; return new FilemakerResultDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Is24XmlDocument } from a { @link Document } . [CODESPLIT] public static Is24XmlDocument createDocument ( Document doc ) { if ( Is24XmlDocument . isReadable ( doc ) ) return new Is24XmlDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Marshaller } to write JAXB objects into XML . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static Marshaller createMarshaller ( String encoding , boolean formatted ) throws JAXBException { Marshaller m = getContext ( ) . createMarshaller ( ) ; m . setProperty ( Marshaller . JAXB_ENCODING , encoding ) ; m . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , formatted ) ; m . setEventHandler ( new XmlValidationHandler ( ) ) ; return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Unmarshaller } to read JAXB objects from XML . [CODESPLIT] public static Unmarshaller createUnmarshaller ( ) throws JAXBException { Unmarshaller m = getContext ( ) . createUnmarshaller ( ) ; m . setEventHandler ( new XmlValidationHandler ( ) ) ; return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @link JAXBContext } for this format . [CODESPLIT] public synchronized static JAXBContext getContext ( ) throws JAXBException { if ( JAXB == null ) initContext ( Thread . currentThread ( ) . getContextClassLoader ( ) ) ; return JAXB ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the location property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setLocation ( Anhang . Location value ) { this . location = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the gruppe property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGruppe ( Anhang . Gruppe value ) { this . gruppe = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the type property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setType ( Floor . FloorType value ) { this . type = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the agent property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T01:43:04+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setAgent ( Root . Agent value ) { this . agent = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the property property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T01:43:04+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < PropertyType > getProperty ( ) { if ( property == null ) { property = new ArrayList < PropertyType > ( ) ; } return this . property ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link File } into a { @link DaftIeDocument } and print some of its content to console . [CODESPLIT] protected static void read ( File xmlFile ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process file: \" + xmlFile . getAbsolutePath ( ) ) ; if ( ! xmlFile . isFile ( ) ) { LOGGER . warn ( \"> provided file is invalid\" ) ; return ; } DaftIeDocument doc = DaftIeUtils . createDocument ( xmlFile ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into an { @link DaftIeDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; DaftIeDocument doc = DaftIeUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of a { @link DaftIeDocument } to console . [CODESPLIT] protected static void printToConsole ( DaftIeDocument doc ) throws JAXBException { LOGGER . info ( \"> process document in version \" + doc . getDocumentVersion ( ) ) ; Daft daft = doc . toObject ( ) ; // process overseas rental if ( daft . getOverseasRental ( ) != null ) { for ( OverseasRentalAdType ad : daft . getOverseasRental ( ) . getOverseasRentalAd ( ) ) { // get object nr String objectNr = StringUtils . trimToNull ( ad . getExternalId ( ) ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object description String objectInfo = StringUtils . trimToNull ( ad . getDescription ( ) ) ; if ( objectInfo == null ) objectInfo = \"???\" ; // print object information to console LOGGER . info ( \"> found object \" + \"'\" + objectNr + \"' for rent: \" + objectInfo ) ; } } // process overseas sales if ( daft . getOverseasSales ( ) != null ) { for ( OverseasSaleAdType ad : daft . getOverseasSales ( ) . getOverseasSaleAd ( ) ) { // get object nr String objectNr = StringUtils . trimToNull ( ad . getExternalId ( ) ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object description String objectInfo = StringUtils . trimToNull ( ad . getDescription ( ) ) ; if ( objectInfo == null ) objectInfo = \"???\" ; // print object information to console LOGGER . info ( \"> found object \" + \"'\" + objectNr + \"' for sale: \" + objectInfo ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the stand property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setStand ( Verkaufstatus . Stand value ) { this . stand = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the userDefinedExtend property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < UserDefinedExtend > getUserDefinedExtend ( ) { if ( userDefinedExtend == null ) { userDefinedExtend = new ArrayList < UserDefinedExtend > ( ) ; } return this . userDefinedExtend ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a { @link Document } is readable as a { @link OpenImmoTransferDocument } . [CODESPLIT] public static boolean isReadable ( Document doc ) { Element root = XmlUtils . getRootElement ( doc ) ; return \"openimmo\" . equals ( root . getLocalName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link OpenImmoTransferDocument } from a { @link Openimmo } object . [CODESPLIT] public static OpenImmoTransferDocument newDocument ( Openimmo openimmo ) throws ParserConfigurationException , JAXBException { if ( openimmo . getUebertragung ( ) == null ) openimmo . setUebertragung ( OpenImmoUtils . getFactory ( ) . createUebertragung ( ) ) ; if ( StringUtils . isBlank ( openimmo . getUebertragung ( ) . getVersion ( ) ) ) openimmo . getUebertragung ( ) . setVersion ( OpenImmoUtils . VERSION . toReadableVersion ( ) ) ; Document document = XmlUtils . newDocument ( ) ; OpenImmoUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( openimmo , document ) ; return new OpenImmoTransferDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Openimmo } object from the contained { @link Document } . [CODESPLIT] @ Override public Openimmo toObject ( ) throws JAXBException { this . upgradeToLatestVersion ( ) ; return ( Openimmo ) OpenImmoUtils . createUnmarshaller ( ) . unmarshal ( this . getDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the zeiteinheit property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setZeiteinheit ( PreisZeiteinheit . Zeiteinheit value ) { this . zeiteinheit = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the zimmer property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Zimmer > getZimmer ( ) { if ( zimmer == null ) { zimmer = new ArrayList < Zimmer > ( ) ; } return this . zimmer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the haus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Haus > getHaus ( ) { if ( haus == null ) { haus = new ArrayList < Haus > ( ) ; } return this . haus ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the bueroPraxen property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < BueroPraxen > getBueroPraxen ( ) { if ( bueroPraxen == null ) { bueroPraxen = new ArrayList < BueroPraxen > ( ) ; } return this . bueroPraxen ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the gastgewerbe property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Gastgewerbe > getGastgewerbe ( ) { if ( gastgewerbe == null ) { gastgewerbe = new ArrayList < Gastgewerbe > ( ) ; } return this . gastgewerbe ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the landUndForstwirtschaft property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < LandUndForstwirtschaft > getLandUndForstwirtschaft ( ) { if ( landUndForstwirtschaft == null ) { landUndForstwirtschaft = new ArrayList < LandUndForstwirtschaft > ( ) ; } return this . landUndForstwirtschaft ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the sonstige property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Sonstige > getSonstige ( ) { if ( sonstige == null ) { sonstige = new ArrayList < Sonstige > ( ) ; } return this . sonstige ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the zinshausRenditeobjekt property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < ZinshausRenditeobjekt > getZinshausRenditeobjekt ( ) { if ( zinshausRenditeobjekt == null ) { zinshausRenditeobjekt = new ArrayList < ZinshausRenditeobjekt > ( ) ; } return this . zinshausRenditeobjekt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the terrain property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < TerrainType > getTerrain ( ) { if ( terrain == null ) { terrain = new ArrayList < TerrainType > ( ) ; } return this . terrain ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the periode property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPeriode ( MieteinnahmenIst . Periode value ) { this . periode = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; jahrgang&gt ; elements in &lt ; energiepass&gt ; to OpenImmo 1 . 2 . 7 . <p > The value bei_besichtigung of &lt ; jahrgang&gt ; elements in &lt ; energiepass&gt ; is not available in OpenImmo 1 . 2 . 7 . [CODESPLIT] protected void downgradeEnergiepassJahrgangElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass/io:jahrgang\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; String value = StringUtils . trimToNull ( node . getTextContent ( ) ) ; if ( value == null || value . equalsIgnoreCase ( \"bei_besichtigung\" ) ) { Element parentNode = ( Element ) node . getParentNode ( ) ; parentNode . removeChild ( node ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link CasaItDocument } from a { @link Container } object . [CODESPLIT] public static CasaItDocument newDocument ( Container container ) throws ParserConfigurationException , JAXBException { Document document = XmlUtils . newDocument ( ) ; CasaItUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( container , document ) ; return new CasaItDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the umfang property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setUmfang ( Uebertragung . Umfang value ) { this . umfang = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link DaftIeDocument } from a { @link Daft } object . [CODESPLIT] public static DaftIeDocument newDocument ( Daft daft ) throws ParserConfigurationException , JAXBException { if ( StringUtils . isBlank ( daft . getVersion ( ) ) ) daft . setVersion ( DaftIeUtils . VERSION . toReadableVersion ( ) ) ; Document document = XmlUtils . newDocument ( ) ; DaftIeUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( daft , document ) ; return new DaftIeDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Daft } object from the contained { @link Document } . [CODESPLIT] @ Override public Daft toObject ( ) throws JAXBException { this . upgradeToLatestVersion ( ) ; return ( Daft ) DaftIeUtils . createUnmarshaller ( ) . unmarshal ( this . getDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the wohnungtyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setWohnungtyp ( Wohnung . Wohnungtyp value ) { this . wohnungtyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an ISO - 2 country code from a country name . [CODESPLIT] public static String getCountryISO2 ( String country ) { country = StringUtils . trimToNull ( country ) ; if ( country == null ) return null ; if ( country . length ( ) == 2 ) return country ; String [ ] iso2Codes = Locale . getISOCountries ( ) ; if ( country . length ( ) == 3 ) { String iso2Code = LocaleUtils . getCountryISO2FromISO3 ( country ) ; if ( iso2Code != null ) return iso2Code ; } for ( String iso2Code : iso2Codes ) { Locale countryLocale = new Locale ( iso2Code , iso2Code ) ; for ( Locale translationLocale : LocaleUtils . availableLocaleList ( ) ) { String name = StringUtils . trimToNull ( countryLocale . getDisplayCountry ( translationLocale ) ) ; if ( name != null && name . equalsIgnoreCase ( country ) ) return iso2Code ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ISO - 2 country code from an ISO - 3 country code . [CODESPLIT] public static String getCountryISO2FromISO3 ( String iso3Code ) { iso3Code = StringUtils . trimToNull ( iso3Code ) ; if ( iso3Code == null ) return null ; if ( iso3Code . length ( ) == 3 ) { for ( String iso2Code : Locale . getISOCountries ( ) ) { Locale countryLocale = new Locale ( iso2Code , iso2Code ) ; String countryISO3 = StringUtils . trimToNull ( countryLocale . getISO3Country ( ) ) ; if ( countryISO3 != null && countryISO3 . equalsIgnoreCase ( iso3Code ) ) { return iso2Code ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an ISO - 3 country code from a country name . [CODESPLIT] public static String getCountryISO3 ( String country ) { country = StringUtils . trimToNull ( country ) ; if ( country == null ) return null ; if ( country . length ( ) == 3 ) return country ; String [ ] iso2Codes = Locale . getISOCountries ( ) ; if ( country . length ( ) == 2 ) { String iso3code = LocaleUtils . getCountryISO3FromISO2 ( country ) ; if ( iso3code != null ) return iso3code ; } for ( String iso2Code : iso2Codes ) { Locale countryLocale = new Locale ( iso2Code , iso2Code ) ; String iso3Code = StringUtils . trimToNull ( countryLocale . getISO3Country ( ) ) ; if ( iso3Code == null ) continue ; for ( Locale translationLocale : LocaleUtils . availableLocaleList ( ) ) { String name = StringUtils . trimToNull ( countryLocale . getDisplayCountry ( translationLocale ) ) ; if ( name != null && name . equalsIgnoreCase ( country ) ) return iso3Code ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an ISO - 3 country code from an ISO - 2 country code . [CODESPLIT] public static String getCountryISO3FromISO2 ( String iso2Code ) { iso2Code = StringUtils . trimToNull ( iso2Code ) ; if ( iso2Code == null ) return null ; if ( iso2Code . length ( ) == 2 ) { Locale countryLocale = new Locale ( iso2Code , iso2Code ) ; String iso3Code = StringUtils . trimToNull ( countryLocale . getISO3Country ( ) ) ; if ( iso3Code != null ) return iso3Code ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a country name in another language . [CODESPLIT] public static String getCountryName ( String country , Locale language ) { country = StringUtils . trimToNull ( country ) ; if ( country == null ) return null ; String iso2Code = LocaleUtils . getCountryISO2 ( country ) ; if ( iso2Code != null ) { String name = StringUtils . trimToNull ( new Locale ( iso2Code , iso2Code ) . getDisplayCountry ( language ) ) ; if ( name != null ) return name ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translate a country name into another language . [CODESPLIT] public static String translateCountryName ( String country , Locale language ) { country = StringUtils . trimToNull ( country ) ; if ( country == null ) return null ; for ( String iso2Code : Locale . getISOCountries ( ) ) { Locale countryLocale = new Locale ( iso2Code , iso2Code ) ; for ( Locale translationLocale : LocaleUtils . availableLocaleList ( ) ) { String name = StringUtils . trimToNull ( countryLocale . getDisplayCountry ( translationLocale ) ) ; if ( name != null && name . equalsIgnoreCase ( country ) ) { name = StringUtils . trimToNull ( countryLocale . getDisplayCountry ( language ) ) ; if ( name != null ) return name ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the anbieter property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Anbieter > getAnbieter ( ) { if ( anbieter == null ) { anbieter = new ArrayList < Anbieter > ( ) ; } return this . anbieter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the periode property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPeriode ( MieteinnahmenSoll . Periode value ) { this . periode = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the category property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setCategory ( BusinessElement . BusinessElementCategory value ) { this . category = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the pdf property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < URI > getPdf ( ) { if ( pdf == null ) { pdf = new ArrayList < URI > ( ) ; } return this . pdf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the aktionart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setAktionart ( Aktion . AktionArt value ) { this . aktionart = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( IdxReadingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // read example file, if no files were specified as command line arguments if ( args . length < 1 ) { try { read ( IdxReadingExample . class . getResourceAsStream ( PACKAGE + \"/idx.csv\" ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't read example file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 2 ) ; } } // read files, that were specified as command line arguments else { for ( String arg : args ) { try { read ( new File ( arg ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't read file '\" + arg + \"'!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link File } into an { @link IdxParser } and print some of its content to console . [CODESPLIT] protected static void read ( File csvFile ) throws IOException { LOGGER . info ( \"process file: \" + csvFile . getAbsolutePath ( ) ) ; if ( ! csvFile . isFile ( ) ) { LOGGER . warn ( \"> The provided file is invalid!\" ) ; return ; } try ( IdxParser parser = IdxParser . create ( csvFile ) ) { if ( parser == null ) LOGGER . warn ( \"> Can't create parser!\" ) ; else printToConsole ( parser ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an { @link InputStream } into an { @link IdxParser } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream csvInputStream ) throws IOException { LOGGER . info ( \"process example file\" ) ; try ( IdxParser parser = IdxParser . create ( csvInputStream ) ) { if ( parser == null ) LOGGER . warn ( \"> Can't create parser!\" ) ; else printToConsole ( parser ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of an { @link IdxParser } to console . [CODESPLIT] protected static void printToConsole ( IdxParser parser ) { // process records while ( parser . hasNext ( ) ) { IdxRecord record = parser . next ( ) ; // get object nr String objectNr = record . getRefObject ( ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object title String objectTitle = record . getObjectTitle ( ) ; if ( objectTitle == null ) objectTitle = \"???\" ; // print object information to console System . out . println ( \"> found object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the realestateitems property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:02+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setRealestateitems ( Container . Realestateitems value ) { this . realestateitems = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the pacht property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPacht ( JAXBElement < VermarktungGrundstueckWohnenMieteTyp . Pacht > value ) { this . pacht = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objektkategorie2 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public HalleProduktionKategorieTyp getObjektkategorie2 ( ) { if ( objektkategorie2 == null ) { return HalleProduktionKategorieTyp . KEINE_ANGABE ; } else { return objektkategorie2 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( ImmoXmlWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create an Immoxml object with some example data // this object corresponds to the <immoxml> root element in XML Immoxml immoxml = FACTORY . createImmoxml ( ) ; immoxml . setUebertragung ( createUebertragung ( ) ) ; immoxml . getAnbieter ( ) . add ( createAnbieter ( ) ) ; // convert the Immoxml object into a XML document ImmoXmlDocument doc = null ; try { doc = ImmoXmlDocument . newDocument ( immoxml ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Uebertragung } with some example data . [CODESPLIT] protected static Uebertragung createUebertragung ( ) { // create an example transfer Uebertragung uebertragung = FACTORY . createUebertragung ( ) ; uebertragung . setArt ( Uebertragung . Art . OFFLINE ) ; uebertragung . setSendersoftware ( \"OpenEstate-IO\" ) ; uebertragung . setTechnEmail ( \"test@test.org\" ) ; uebertragung . setUmfang ( Uebertragung . Umfang . VOLL ) ; return uebertragung ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 7 to 1 . 2 . 6 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_6 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . removeMultipleEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove odd <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeObjektTextElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <objekt_text> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeSummemietenettoElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <summemietenetto> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBefeuerungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <befeuerung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeAnhangElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <anhang> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeAktionElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <aktion> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade an OpenImmo document from version 1 . 2 . 6 to 1 . 2 . 7 . [CODESPLIT] @ Override public void upgradeFromPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_7 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . upgradeSummemietenettoElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <summemietenetto> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; befeuerung&gt ; elements to OpenImmo 1 . 2 . 6 . <p > The attributes KOHLE HOLZ FLUESSIGGAS of &lt ; befeuerung&gt ; elements are not available in OpenImmo 1 . 2 . 6 . [CODESPLIT] protected void downgradeBefeuerungElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:befeuerung[@KOHLE or @HOLZ or @FLUESSIGGAS]\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; node . removeAttribute ( \"KOHLE\" ) ; node . removeAttribute ( \"HOLZ\" ) ; node . removeAttribute ( \"FLUESSIGGAS\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; energiepass&gt ; elements to OpenImmo 1 . 2 . 6 . <p > The child elements &lt ; stromwert&gt ; &lt ; waermewert&gt ; &lt ; wertklasse&gt ; &lt ; baujahr&gt ; &lt ; ausstelldatum&gt ; &lt ; jahrgang&gt ; &lt ; gebaeudeart&gt ; are copied into separate &lt ; user_defined_simplefield&gt ; elements as it was <a href = http : // www . openimmo . de / go . php / p / 44 / cm_enev2014 . htm > suggested by OpenImmo e . V . < / a > . <p > The child elements &lt ; primaerenergietraeger&gt ; &lt ; epasstext&gt ; are not available in OpenImmo 1 . 2 . 6 . [CODESPLIT] protected void downgradeEnergiepassElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; boolean stromwertPassed = false ; boolean waermewertPassed = false ; boolean wertklassePassed = false ; boolean baujahrPassed = false ; boolean ausstelldatumPassed = false ; boolean jahrgangPassed = false ; boolean gebaeudeartPassed = false ; List childNodes ; // <primaerenergietraeger> elements are not supported in version 1.2.6 childNodes = XmlUtils . newXPath ( \"io:primaerenergietraeger\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; node . removeChild ( childNode ) ; } // <epasstext> elements are not supported in version 1.2.6 childNodes = XmlUtils . newXPath ( \"io:epasstext\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <stromwert> elements childNodes = XmlUtils . newXPath ( \"io:stromwert\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! stromwertPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_stromwert\" , value ) ) ; stromwertPassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <waermewert> elements childNodes = XmlUtils . newXPath ( \"io:waermewert\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! waermewertPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_waermewert\" , value ) ) ; waermewertPassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <wertklasse> elements childNodes = XmlUtils . newXPath ( \"io:wertklasse\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! wertklassePassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_wertklasse\" , value ) ) ; wertklassePassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <baujahr> elements childNodes = XmlUtils . newXPath ( \"io:baujahr\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! baujahrPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_baujahr\" , value ) ) ; baujahrPassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <ausstelldatum> elements childNodes = XmlUtils . newXPath ( \"io:ausstelldatum\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! ausstelldatumPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_ausstelldatum\" , value ) ) ; ausstelldatumPassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <jahrgang> elements childNodes = XmlUtils . newXPath ( \"io:jahrgang\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! jahrgangPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( \"2008\" . equalsIgnoreCase ( value ) || \"2014\" . equalsIgnoreCase ( value ) || \"ohne\" . equalsIgnoreCase ( value ) ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_jahrgang\" , value ) ) ; jahrgangPassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <gebaeudeart> elements childNodes = XmlUtils . newXPath ( \"io:gebaeudeart\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! gebaeudeartPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( \"wohn\" . equalsIgnoreCase ( value ) || \"nichtwohn\" . equalsIgnoreCase ( value ) || \"ohne\" . equalsIgnoreCase ( value ) ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_gebaeudeart\" , value ) ) ; gebaeudeartPassed = true ; } } node . removeChild ( childNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only use one &lt ; energiepass&gt ; element for each &lt ; immobilie&gt ; . <p > OpenImmo 1 . 2 . 6 does not allow more then one &lt ; energiepass&gt ; element for each &lt ; immobilie&gt ; ( maxOccurs = 1 ) . Odd &lt ; energiepass&gt ; elements are removed by this function . [CODESPLIT] protected void removeMultipleEnergiepassElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element parentNode = ( Element ) item ; List childNodes = XmlUtils . newXPath ( \"io:energiepass\" , doc ) . selectNodes ( parentNode ) ; if ( childNodes . size ( ) < 2 ) continue ; for ( int j = 1 ; j < childNodes . size ( ) ; j ++ ) { parentNode . removeChild ( ( Node ) childNodes . get ( j ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( FilemakerWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a mapping from the example document, if no files were specified as command line arguments FilemakerResultMapping mapping = null ; if ( args . length < 1 ) { try { mapping = new FilemakerResultDocument ( buildExampleDocument ( ) ) . toMapping ( ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create mapping!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } } // read file, that was specified as command line argument else { try { mapping = new FilemakerResultDocument ( XmlUtils . newDocument ( new File ( args [ 0 ] ) ) ) . toMapping ( ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create mapping from file '\" + args [ 0 ] + \"'!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } } if ( mapping == null ) { LOGGER . error ( \"No mapping was created!\" ) ; System . exit ( 1 ) ; } // loop through available rows and access their values through the field name for ( int i = 0 ; i < mapping . getRowCount ( ) ; i ++ ) { FilemakerResultMapping . Row row = mapping . getRow ( i ) ; LOGGER . info ( StringUtils . repeat ( \"-\" , 50 ) ) ; LOGGER . info ( \"record at row \" + i ) ; LOGGER . info ( \"> recordId = \" + row . getRecordId ( ) ) ; LOGGER . info ( \"> modId = \" + row . getModId ( ) ) ; // access record values through their field name for ( String field : row . getFieldNames ( ) ) { LOGGER . info ( \"> \" + field + \" = \" + row . getValue ( field ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the content property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Object > getContent ( ) { if ( content == null ) { content = new ArrayList < Object > ( ) ; } return this . content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the names of specified fields . [CODESPLIT] public String [ ] getFieldNames ( ) { List < String > names = new ArrayList <> ( ) ; for ( MetaDataType . FIELD field : this . fields ) { names . add ( field . getNAME ( ) ) ; } return names . toArray ( new String [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the blick property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setBlick ( Ausblick . Blick value ) { this . blick = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the pauschalmiete property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPauschalmiete ( WazTyp . Pauschalmiete value ) { this . pauschalmiete = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the monatsmiete property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMonatsmiete ( WazTyp . Monatsmiete value ) { this . monatsmiete = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the parkplatz property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public StellplatzKategorieTyp getParkplatz ( ) { if ( parkplatz == null ) { return StellplatzKategorieTyp . KEINE_ANGABE ; } else { return parkplatz ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Container . Realestateitems . Realestate . Images . Advertismentimage } [CODESPLIT] public Container . Realestateitems . Realestate . Images . Advertismentimage createContainerRealestateitemsRealestateImagesAdvertismentimage ( ) { return new Container . Realestateitems . Realestate . Images . Advertismentimage ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the lastenaufzug property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setLastenaufzug ( JAXBElement < HebeanlageTyp > value ) { this . lastenaufzug = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objektkategorie2 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public EinzelhandelKategorienTyp getObjektkategorie2 ( ) { if ( objektkategorie2 == null ) { return EinzelhandelKategorienTyp . KEINE_ANGABE ; } else { return objektkategorie2 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the zustandArt property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setZustandArt ( Zustand . ZustandArt value ) { this . zustandArt = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into an { @link ImmobiliareItDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; ImmobiliareItDocument doc = ImmobiliareItUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of an { @link ImmobiliareItDocument } to console . [CODESPLIT] protected static void printToConsole ( ImmobiliareItDocument doc ) throws JAXBException { LOGGER . info ( \"> process document in version \" + doc . getDocumentVersion ( ) ) ; Feed feed = doc . toObject ( ) ; // process properties if ( feed . getProperties ( ) != null ) { for ( Property object : feed . getProperties ( ) . getProperty ( ) ) { // get object nr String objectNr = StringUtils . trimToNull ( object . getUniqueId ( ) ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object description String objectInfo = ( object . getFeatures ( ) != null && ! object . getFeatures ( ) . getDescription ( ) . isEmpty ( ) ) ? StringUtils . trimToNull ( object . getFeatures ( ) . getDescription ( ) . get ( 0 ) . getValue ( ) ) : null ; if ( objectInfo == null ) objectInfo = \"???\" ; // print object information to console LOGGER . info ( \"> found object \" + \"'\" + objectNr + \"': \" + objectInfo ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the feld property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Bewertung . Feld > getFeld ( ) { if ( feld == null ) { feld = new ArrayList < Bewertung . Feld > ( ) ; } return this . feld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receive notification of a validation warning or error . [CODESPLIT] @ Override public boolean handleEvent ( ValidationEvent event ) { if ( event == null ) throw new IllegalArgumentException ( \"No validation event was provided!\" ) ; int line = - 1 ; int col = - 1 ; if ( event . getLocator ( ) != null ) { line = event . getLocator ( ) . getLineNumber ( ) ; col = event . getLocator ( ) . getColumnNumber ( ) ; } if ( ValidationEvent . FATAL_ERROR == event . getSeverity ( ) ) { LOGGER . warn ( \"fatal validation error\" ) ; if ( line > - 1 && col > - 1 ) LOGGER . warn ( \"> at line \" + line + \" / column \" + col ) ; LOGGER . warn ( \"> \" + event . getMessage ( ) ) ; return false ; } if ( ValidationEvent . WARNING == event . getSeverity ( ) ) { LOGGER . warn ( \"validation warning\" ) ; if ( line > - 1 && col > - 1 ) LOGGER . warn ( \"> at line \" + line + \" / column \" + col ) ; LOGGER . warn ( \"> \" + event . getMessage ( ) ) ; } else { LOGGER . warn ( \"validation error\" ) ; if ( line > - 1 && col > - 1 ) LOGGER . warn ( \"> at line \" + line + \" / column \" + col ) ; LOGGER . warn ( \"> \" + event . getMessage ( ) ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write content of the record in a human readable form . [CODESPLIT] public void dump ( Writer writer , String lineSeparator ) throws IOException { for ( int i = 0 ; i < this . getRecordLenth ( ) ; i ++ ) { StringBuilder txt = new StringBuilder ( ) ; try ( StringReader reader = new StringReader ( StringUtils . trimToEmpty ( this . get ( i ) ) ) ) { for ( String line : IOUtils . readLines ( reader ) ) { if ( txt . length ( ) > 0 ) txt . append ( lineSeparator ) ; txt . append ( line ) ; } } writer . write ( i + \":\" + txt . toString ( ) ) ; writer . write ( System . lineSeparator ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of the record at a certain index position . [CODESPLIT] protected final String get ( int pos , String defaultValue ) { String value = StringUtils . trimToNull ( this . values . get ( pos ) ) ; return ( value != null ) ? value : defaultValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads data from { @link CsvParser } into the record . [CODESPLIT] protected void parse ( CSVRecord record ) { this . values . clear ( ) ; for ( int i = 0 ; i < record . size ( ) ; i ++ ) { this . values . put ( i , this . parse ( record . get ( i ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of values for this record as they are written into CSV . [CODESPLIT] protected Iterable < String > print ( ) { final int length = this . getRecordLenth ( ) ; List < String > row = new ArrayList <> ( ) ; for ( int i = 0 ; i < length ; i ++ ) { row . add ( this . get ( i ) ) ; } return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of this record at a certain index position . [CODESPLIT] protected final void set ( int pos , String value ) { value = StringUtils . trimToNull ( value ) ; if ( value != null ) this . values . put ( pos , value ) ; else if ( this . values . containsKey ( pos ) ) this . values . remove ( pos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the ctype property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setCtype ( Check . Ctype value ) { this . ctype = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into a { @link TrovitDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; TrovitDocument doc = TrovitUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of a { @link TrovitDocument } to console . [CODESPLIT] protected static void printToConsole ( TrovitDocument doc ) throws JAXBException { Trovit trovit = doc . toObject ( ) ; // process ads for ( AdType ad : trovit . getAd ( ) ) { // get object nr String objectNr = StringUtils . trimToNull ( ad . getId ( ) ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object title String objectTitle = StringUtils . trimToNull ( ad . getTitle ( ) ) ; if ( objectTitle == null ) objectTitle = \"???\" ; // print object information to console LOGGER . info ( \"> found object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the haustyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setHaustyp ( Haus . Haustyp value ) { this . haustyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into a { @link KyeroDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; KyeroDocument doc = KyeroUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of a { @link KyeroDocument } to console . [CODESPLIT] protected static void printToConsole ( KyeroDocument doc ) throws JAXBException { Root root = doc . toObject ( ) ; // process properties in the document for ( PropertyType obj : root . getProperty ( ) ) { // get object nr String objectNr = ( obj . getId ( ) != null ) ? obj . getId ( ) : \"???\" ; // get object description String objectInfo = null ; if ( obj . getDesc ( ) != null ) { objectInfo = StringUtils . trimToNull ( obj . getDesc ( ) . getEn ( ) ) ; if ( objectInfo == null ) objectInfo = StringUtils . trimToNull ( obj . getDesc ( ) . getDe ( ) ) ; if ( objectInfo == null ) objectInfo = StringUtils . trimToNull ( obj . getDesc ( ) . getEs ( ) ) ; } // print object information to console LOGGER . info ( \"> found object '\" + objectNr + \"' \" + \"with title '\" + objectInfo + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the energiepass property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Energiepass > getEnergiepass ( ) { if ( energiepass == null ) { energiepass = new ArrayList < Energiepass > ( ) ; } return this . energiepass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the keller property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setKeller ( Unterkellert . Keller value ) { this . keller = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the grundstTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGrundstTyp ( Grundstueck . GrundstTyp value ) { this . grundstTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the geschlAttr property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGeschlAttr ( Geschlecht . GeschlAttr value ) { this . geschlAttr = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the hallenTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setHallenTyp ( HallenLagerProd . HallenTyp value ) { this . hallenTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the type property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setType ( Box . BoxType value ) { this . type = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the wiederholungstermin property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public Boolean getWiederholungstermin ( ) { if ( wiederholungstermin == null ) { return false ; } else { return wiederholungstermin ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the teilungsversteigerung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public Boolean getTeilungsversteigerung ( ) { if ( teilungsversteigerung == null ) { return false ; } else { return teilungsversteigerung ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the kauf property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setKauf ( JAXBElement < VermarktungGrundstueckWohnenKaufTyp . Kauf > value ) { this . kauf = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 3 to 1 . 2 . 2 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_2 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . removeEmailFeedbackElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <email_feedback> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removePreiseChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <preise> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeFlaechenChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <flaechen> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeAusstattungChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <ausstattung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeZustandAngabenChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <zustand_angaben> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeUserDefinedExtendElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <user_defined_extend> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeParkenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <parken> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBadElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <bad> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeKuecheElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <kueche> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBodenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <boden> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBefeuerungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <befeuerung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeAusrichtBalkonTerrasseElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <ausricht_balkon_terrasse> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeDachformElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <dachform> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeWohnungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <wohnung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeHausElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <haus> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeSonstigeElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <sonstige> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeZinshausRenditeobjektElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <zinshaus_renditeobjekt> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade an OpenImmo document from version 1 . 2 . 2 to 1 . 2 . 3 . [CODESPLIT] @ Override public void upgradeFromPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_3 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . upgradeSonstigeElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <sonstige> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeZinshausRenditeobjektElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <zinshaus_renditeobjekt> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; ausricht_balkon_terrasse&gt ; elements to OpenImmo 1 . 2 . 2 . <p > The attributes NORDOST NORDWEST SUEDOST SUEDWEST for &lt ; ausricht_balkon_terrasse&gt ; elements are not available in version 1 . 2 . 2 . <p > Any occurences of these values are replaced by the single components - e . g . NORDOST is removed and NORD + OST is set . [CODESPLIT] protected void downgradeAusrichtBalkonTerrasseElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:ausricht_balkon_terrasse[@NORDOST or @NORDWEST or @SUEDOST or @SUEDWEST]\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; if ( node . hasAttribute ( \"NORDOST\" ) ) { String value = StringUtils . trimToEmpty ( node . getAttribute ( \"NORDOST\" ) ) . toLowerCase ( ) ; if ( value . equals ( \"1\" ) || value . equals ( \"true\" ) ) { node . setAttribute ( \"NORD\" , \"true\" ) ; node . setAttribute ( \"OST\" , \"true\" ) ; } node . removeAttribute ( \"NORDOST\" ) ; } if ( node . hasAttribute ( \"NORDWEST\" ) ) { String value = StringUtils . trimToEmpty ( node . getAttribute ( \"NORDWEST\" ) ) . toLowerCase ( ) ; if ( value . equals ( \"1\" ) || value . equals ( \"true\" ) ) { node . setAttribute ( \"NORD\" , \"true\" ) ; node . setAttribute ( \"WEST\" , \"true\" ) ; } node . removeAttribute ( \"NORDWEST\" ) ; } if ( node . hasAttribute ( \"SUEDOST\" ) ) { String value = StringUtils . trimToEmpty ( node . getAttribute ( \"SUEDOST\" ) ) . toLowerCase ( ) ; if ( value . equals ( \"1\" ) || value . equals ( \"true\" ) ) { node . setAttribute ( \"SUED\" , \"true\" ) ; node . setAttribute ( \"OST\" , \"true\" ) ; } node . removeAttribute ( \"SUEDOST\" ) ; } if ( node . hasAttribute ( \"SUEDWEST\" ) ) { String value = StringUtils . trimToEmpty ( node . getAttribute ( \"SUEDWEST\" ) ) . toLowerCase ( ) ; if ( value . equals ( \"1\" ) || value . equals ( \"true\" ) ) { node . setAttribute ( \"SUED\" , \"true\" ) ; node . setAttribute ( \"WEST\" , \"true\" ) ; } node . removeAttribute ( \"SUEDWEST\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove unsupported children from all &lt ; flaechen&gt ; elements . <p > OpenImmo 1 . 2 . 2 does not support the following children for &lt ; flaechen&gt ; elements : &lt ; anzahl_balkone&gt ; &lt ; anzahl_terrassen&gt ; <p > These elements are removed by this function . If &lt ; anzahl_balkon_terrassen&gt ; is not already specified the sum values of &lt ; anzahl_balkone&gt ; and &lt ; anzahl_terrassen&gt ; are written into &lt ; anzahl_balkon_terrassen&gt ; . [CODESPLIT] protected void downgradeFlaechenChildElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:flaechen\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element parentNode = ( Element ) item ; boolean passedAnzahlBalkone = false ; boolean passedAnzahlTerrassen = false ; double sum = 0 ; List childNodes = XmlUtils . newXPath ( \"io:anzahl_balkone\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Node node = ( Node ) childItem ; if ( ! passedAnzahlBalkone ) { passedAnzahlBalkone = true ; String value = StringUtils . trimToNull ( node . getTextContent ( ) ) ; try { sum += ( value != null ) ? Double . parseDouble ( value ) : 0 ; } catch ( NumberFormatException ex ) { LOGGER . warn ( \"Can't parse <anzahl_balkone>\" + value + \"</anzahl_balkone> into a numeric value!\" ) ; LOGGER . warn ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } parentNode . removeChild ( node ) ; } childNodes = XmlUtils . newXPath ( \"io:anzahl_terrassen\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Node node = ( Node ) childItem ; if ( ! passedAnzahlTerrassen ) { passedAnzahlTerrassen = true ; String value = StringUtils . trimToNull ( node . getTextContent ( ) ) ; try { sum += ( value != null ) ? Double . parseDouble ( value ) : 0 ; } catch ( NumberFormatException ex ) { LOGGER . warn ( \"Can't parse <anzahl_terrassen>\" + value + \"</anzahl_terrassen> into a numeric value!\" ) ; LOGGER . warn ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } parentNode . removeChild ( node ) ; } if ( sum > 0 ) { Element node = ( Element ) XmlUtils . newXPath ( \"io:anzahl_balkon_terrassen\" , doc ) . selectSingleNode ( parentNode ) ; if ( node == null ) { node = doc . createElementNS ( StringUtils . EMPTY , \"anzahl_balkon_terrassen\" ) ; node . setTextContent ( String . valueOf ( sum ) ) ; parentNode . appendChild ( node ) ; } else if ( StringUtils . isBlank ( node . getTextContent ( ) ) ) { node . setTextContent ( String . valueOf ( sum ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace &lt ; parken&gt ; elements with &lt ; sonstige&gt ; elements . <p > OpenImmo 1 . 2 . 2 does not support &lt ; parken&gt ; elements . Any occurence is converted into &lt ; sonstige&gt ; elements . [CODESPLIT] protected void downgradeParkenElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:objektkategorie/io:objektart/io:parken\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; parentNode . removeChild ( node ) ; Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"sonstige\" ) ; newNode . setAttribute ( \"sonstige_typ\" , \"PARKFLACHE\" ) ; parentNode . appendChild ( newNode ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; zinshaus_renditeobjekt&gt ; elements to OpenImmo 1 . 2 . 3 . <p > The options PFLEGEHEIM SANATORIUM SENIORENHEIM BETREUTES - WOHNEN for the haustyp attribute of &lt ; haus&gt ; elements are placed in the &lt ; zinshaus_renditeobjekt&gt ; element in version 1 . 2 . 3 . [CODESPLIT] protected void upgradeZinshausRenditeobjektElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:objektkategorie/io:objektart/io:haus[@haustyp]\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parent = ( Element ) node . getParentNode ( ) ; String value = StringUtils . trimToNull ( node . getAttribute ( \"haustyp\" ) ) ; if ( \"PFLEGEHEIM\" . equalsIgnoreCase ( value ) ) { parent . removeChild ( node ) ; Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"zinshaus_renditeobjekt\" ) ; newNode . setAttribute ( \"zins_typ\" , \"PFLEGEHEIM\" ) ; parent . appendChild ( newNode ) ; } else if ( \"SANATORIUM\" . equalsIgnoreCase ( value ) ) { parent . removeChild ( node ) ; Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"zinshaus_renditeobjekt\" ) ; newNode . setAttribute ( \"zins_typ\" , \"SANATORIUM\" ) ; parent . appendChild ( newNode ) ; } else if ( \"SENIORENHEIM\" . equalsIgnoreCase ( value ) ) { parent . removeChild ( node ) ; Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"zinshaus_renditeobjekt\" ) ; newNode . setAttribute ( \"zins_typ\" , \"SENIORENHEIM\" ) ; parent . appendChild ( newNode ) ; } else if ( \"BETREUTES-WOHNEN\" . equalsIgnoreCase ( value ) ) { parent . removeChild ( node ) ; Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"zinshaus_renditeobjekt\" ) ; newNode . setAttribute ( \"zins_typ\" , \"BETREUTES-WOHNEN\" ) ; parent . appendChild ( newNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VirtuelleImmobilieBaseTyp } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"VirtuelleImmobilie\" ) public JAXBElement < VirtuelleImmobilieBaseTyp > createVirtuelleImmobilie ( VirtuelleImmobilieBaseTyp value ) { return new JAXBElement < VirtuelleImmobilieBaseTyp > ( _VirtuelleImmobilie_QNAME , VirtuelleImmobilieBaseTyp . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link ImmobilieBaseTyp } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Immobilie\" ) public JAXBElement < ImmobilieBaseTyp > createImmobilie ( ImmobilieBaseTyp value ) { return new JAXBElement < ImmobilieBaseTyp > ( _Immobilie_QNAME , ImmobilieBaseTyp . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link WohnungKauf }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"WohnungKauf\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public WohnungKauf createWohnungKauf ( WohnungKauf . Type value ) { return new WohnungKauf ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link WohnungMiete }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"WohnungMiete\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public WohnungMiete createWohnungMiete ( WohnungMiete . Type value ) { return new WohnungMiete ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link HausKauf }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"HausKauf\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public HausKauf createHausKauf ( HausKauf . Type value ) { return new HausKauf ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link HausMiete }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"HausMiete\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public HausMiete createHausMiete ( HausMiete . Type value ) { return new HausMiete ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link WAZ }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"WAZ\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public WAZ createWAZ ( WAZ . Type value ) { return new WAZ ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Grundstueck } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Grundstueck\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public JAXBElement < Grundstueck > createGrundstueck ( Grundstueck value ) { return new JAXBElement < Grundstueck > ( _Grundstueck_QNAME , Grundstueck . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link GrundstueckWohnenKauf }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"GrundstueckWohnenKauf\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public GrundstueckWohnenKauf createGrundstueckWohnenKauf ( GrundstueckWohnenKauf . Type value ) { return new GrundstueckWohnenKauf ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link GrundstueckWohnenMiete }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"GrundstueckWohnenMiete\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public GrundstueckWohnenMiete createGrundstueckWohnenMiete ( GrundstueckWohnenMiete . Type value ) { return new GrundstueckWohnenMiete ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link GrundstueckGewerbe }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"GrundstueckGewerbe\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public GrundstueckGewerbe createGrundstueckGewerbe ( GrundstueckGewerbe . Type value ) { return new GrundstueckGewerbe ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link TypenHaus } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"TypenHaus\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"VirtuelleImmobilie\" ) public JAXBElement < TypenHaus > createTypenHaus ( TypenHaus value ) { return new JAXBElement < TypenHaus > ( _TypenHaus_QNAME , TypenHaus . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link BueroPraxis }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"BueroPraxis\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public BueroPraxis createBueroPraxis ( BueroPraxis . Type value ) { return new BueroPraxis ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Einzelhandel }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Einzelhandel\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public Einzelhandel createEinzelhandel ( Einzelhandel . Type value ) { return new Einzelhandel ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Gastronomie }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Gastronomie\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public Gastronomie createGastronomie ( Gastronomie . Type value ) { return new Gastronomie ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link HalleProduktion }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"HalleProduktion\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public HalleProduktion createHalleProduktion ( HalleProduktion . Type value ) { return new HalleProduktion ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link SonstigeGewerbe }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"SonstigeGewerbe\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public SonstigeGewerbe createSonstigeGewerbe ( SonstigeGewerbe . Type value ) { return new SonstigeGewerbe ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Anlageobjekt }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Anlageobjekt\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public Anlageobjekt createAnlageobjekt ( Anlageobjekt . Type value ) { return new Anlageobjekt ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link GarageMiete }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"GarageMiete\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public GarageMiete createGarageMiete ( GarageMiete . Type value ) { return new GarageMiete ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link GarageKauf }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"GarageKauf\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public GarageKauf createGarageKauf ( GarageKauf . Type value ) { return new GarageKauf ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Zwangsversteigerung }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Zwangsversteigerung\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public Zwangsversteigerung createZwangsversteigerung ( Zwangsversteigerung . Type value ) { return new Zwangsversteigerung ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link WGZimmer }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"WGZimmer\" , substitutionHeadNamespace = \"http://www.immobilienscout24.de/immobilientransfer\" , substitutionHeadName = \"Immobilie\" ) public WGZimmer createWGZimmer ( WGZimmer . Type value ) { return new WGZimmer ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link ApiSuchfelderTyp } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"ApiSuchfelder\" , scope = ImmobilieBaseTyp . class ) public JAXBElement < ApiSuchfelderTyp > createImmobilieBaseTypApiSuchfelder ( ApiSuchfelderTyp value ) { return new JAXBElement < ApiSuchfelderTyp > ( _ImmobilieBaseTypApiSuchfelder_QNAME , ApiSuchfelderTyp . class , ImmobilieBaseTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link HebeanlageTyp } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Lastenaufzug\" , scope = EinzelhandelTyp . class ) public JAXBElement < HebeanlageTyp > createEinzelhandelTypLastenaufzug ( HebeanlageTyp value ) { return new JAXBElement < HebeanlageTyp > ( _EinzelhandelTypLastenaufzug_QNAME , HebeanlageTyp . class , EinzelhandelTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link ApiSuchfelderTyp } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"ApiSuchfelder\" , scope = VirtuelleImmobilieBaseTyp . class ) public JAXBElement < ApiSuchfelderTyp > createVirtuelleImmobilieBaseTypApiSuchfelder ( ApiSuchfelderTyp value ) { return new JAXBElement < ApiSuchfelderTyp > ( _ImmobilieBaseTypApiSuchfelder_QNAME , ApiSuchfelderTyp . class , VirtuelleImmobilieBaseTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Ackerland\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungAckerland ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungAckerland_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Bauerwartungsland\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungBauerwartungsland ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungBauerwartungsland_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Bootsstaende\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungBootsstaende ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungBootsstaende_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Buero\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungBuero ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungBuero_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Camping\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungCamping ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungCamping_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Doppelhaus\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungDoppelhaus ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungDoppelhaus_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Einfamilienhaus\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungEinfamilienhaus ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungEinfamilienhaus_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Einzelhandel-gross\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungEinzelhandelGross ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungEinzelhandelGross_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Einzelhandel-klein\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungEinzelhandelKlein ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungEinzelhandelKlein_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Garagen\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungGaragen ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungGaragen_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Garten\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungGarten ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungGarten_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Gastronomie\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungGastronomie ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungGastronomie_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Gewerbe\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungGewerbe ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungGewerbe_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Hotel\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungHotel ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungHotel_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Industrie\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungIndustrie ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungIndustrie_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"keineBebauung\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungKeineBebauung ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungKeineBebauung_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Kleingewerbe\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungKleingewerbe ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungKleingewerbe_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Lager\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungLager ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungLager_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Mehrfamilienhaus\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungMehrfamilienhaus ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungMehrfamilienhaus_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Obstpflanzung\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungObstpflanzung ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungObstpflanzung_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Parkhaus\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungParkhaus ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungParkhaus_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Produktion\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungProduktion ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungProduktion_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Reihenhaus\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungReihenhaus ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungReihenhaus_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Stellplaetze\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungStellplaetze ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungStellplaetze_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Villa\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungVilla ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungVilla_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Wald\" , scope = GrundstueckEmpfohleneNutzung . class ) public JAXBElement < Object > createGrundstueckEmpfohleneNutzungWald ( Object value ) { return new JAXBElement < Object > ( _GrundstueckEmpfohleneNutzungWald_QNAME , Object . class , GrundstueckEmpfohleneNutzung . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"KeineAngabe\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypKeineAngabe ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypKeineAngabe_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Erdwaerme\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypErdwaerme ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypErdwaerme_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Solarheizung\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypSolarheizung ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypSolarheizung_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Pelletheizung\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypPelletheizung ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypPelletheizung_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Gas\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypGas ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypGas_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Oel\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypOel ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypOel_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Fernwaerme\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypFernwaerme ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypFernwaerme_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Strom\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypStrom ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypStrom_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Kohle\" , scope = BefeuerungsArtTyp . class ) public JAXBElement < Object > createBefeuerungsArtTypKohle ( Object value ) { return new JAXBElement < Object > ( _BefeuerungsArtTypKohle_QNAME , Object . class , BefeuerungsArtTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Kauf\" , scope = VermarktungGewerbeTyp2 . class ) public JAXBElement < Object > createVermarktungGewerbeTyp2Kauf ( Object value ) { return new JAXBElement < Object > ( _VermarktungGewerbeTyp2Kauf_QNAME , Object . class , VermarktungGewerbeTyp2 . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGewerbeTyp . Miete } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Miete\" , scope = VermarktungGewerbeTyp . class ) public JAXBElement < VermarktungGewerbeTyp . Miete > createVermarktungGewerbeTypMiete ( VermarktungGewerbeTyp . Miete value ) { return new JAXBElement < VermarktungGewerbeTyp . Miete > ( _VermarktungGewerbeTypMiete_QNAME , VermarktungGewerbeTyp . Miete . class , VermarktungGewerbeTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGewerbeTyp . Kauf } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Kauf\" , scope = VermarktungGewerbeTyp . class ) public JAXBElement < VermarktungGewerbeTyp . Kauf > createVermarktungGewerbeTypKauf ( VermarktungGewerbeTyp . Kauf value ) { return new JAXBElement < VermarktungGewerbeTyp . Kauf > ( _VermarktungGewerbeTyp2Kauf_QNAME , VermarktungGewerbeTyp . Kauf . class , VermarktungGewerbeTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckWohnenMieteTyp . Pacht } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Pacht\" , scope = VermarktungGrundstueckWohnenMieteTyp . class ) public JAXBElement < VermarktungGrundstueckWohnenMieteTyp . Pacht > createVermarktungGrundstueckWohnenMieteTypPacht ( VermarktungGrundstueckWohnenMieteTyp . Pacht value ) { return new JAXBElement < VermarktungGrundstueckWohnenMieteTyp . Pacht > ( _VermarktungGrundstueckWohnenMieteTypPacht_QNAME , VermarktungGrundstueckWohnenMieteTyp . Pacht . class , VermarktungGrundstueckWohnenMieteTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckWohnenMieteTyp . Miete } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Miete\" , scope = VermarktungGrundstueckWohnenMieteTyp . class ) public JAXBElement < VermarktungGrundstueckWohnenMieteTyp . Miete > createVermarktungGrundstueckWohnenMieteTypMiete ( VermarktungGrundstueckWohnenMieteTyp . Miete value ) { return new JAXBElement < VermarktungGrundstueckWohnenMieteTyp . Miete > ( _VermarktungGewerbeTypMiete_QNAME , VermarktungGrundstueckWohnenMieteTyp . Miete . class , VermarktungGrundstueckWohnenMieteTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckWohnenKaufTyp . Kauf } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Kauf\" , scope = VermarktungGrundstueckWohnenKaufTyp . class ) public JAXBElement < VermarktungGrundstueckWohnenKaufTyp . Kauf > createVermarktungGrundstueckWohnenKaufTypKauf ( VermarktungGrundstueckWohnenKaufTyp . Kauf value ) { return new JAXBElement < VermarktungGrundstueckWohnenKaufTyp . Kauf > ( _VermarktungGewerbeTyp2Kauf_QNAME , VermarktungGrundstueckWohnenKaufTyp . Kauf . class , VermarktungGrundstueckWohnenKaufTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckWohnenKaufTyp . Erbpacht } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Erbpacht\" , scope = VermarktungGrundstueckWohnenKaufTyp . class ) public JAXBElement < VermarktungGrundstueckWohnenKaufTyp . Erbpacht > createVermarktungGrundstueckWohnenKaufTypErbpacht ( VermarktungGrundstueckWohnenKaufTyp . Erbpacht value ) { return new JAXBElement < VermarktungGrundstueckWohnenKaufTyp . Erbpacht > ( _VermarktungGrundstueckWohnenKaufTypErbpacht_QNAME , VermarktungGrundstueckWohnenKaufTyp . Erbpacht . class , VermarktungGrundstueckWohnenKaufTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckTypAlt . Kauf } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Kauf\" , scope = VermarktungGrundstueckTypAlt . class ) public JAXBElement < VermarktungGrundstueckTypAlt . Kauf > createVermarktungGrundstueckTypAltKauf ( VermarktungGrundstueckTypAlt . Kauf value ) { return new JAXBElement < VermarktungGrundstueckTypAlt . Kauf > ( _VermarktungGewerbeTyp2Kauf_QNAME , VermarktungGrundstueckTypAlt . Kauf . class , VermarktungGrundstueckTypAlt . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckTypAlt . Pacht } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Pacht\" , scope = VermarktungGrundstueckTypAlt . class ) public JAXBElement < VermarktungGrundstueckTypAlt . Pacht > createVermarktungGrundstueckTypAltPacht ( VermarktungGrundstueckTypAlt . Pacht value ) { return new JAXBElement < VermarktungGrundstueckTypAlt . Pacht > ( _VermarktungGrundstueckWohnenMieteTypPacht_QNAME , VermarktungGrundstueckTypAlt . Pacht . class , VermarktungGrundstueckTypAlt . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckTypAlt . Erbpacht } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Erbpacht\" , scope = VermarktungGrundstueckTypAlt . class ) public JAXBElement < VermarktungGrundstueckTypAlt . Erbpacht > createVermarktungGrundstueckTypAltErbpacht ( VermarktungGrundstueckTypAlt . Erbpacht value ) { return new JAXBElement < VermarktungGrundstueckTypAlt . Erbpacht > ( _VermarktungGrundstueckWohnenKaufTypErbpacht_QNAME , VermarktungGrundstueckTypAlt . Erbpacht . class , VermarktungGrundstueckTypAlt . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckGewerbeTyp . Kauf } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Kauf\" , scope = VermarktungGrundstueckGewerbeTyp . class ) public JAXBElement < VermarktungGrundstueckGewerbeTyp . Kauf > createVermarktungGrundstueckGewerbeTypKauf ( VermarktungGrundstueckGewerbeTyp . Kauf value ) { return new JAXBElement < VermarktungGrundstueckGewerbeTyp . Kauf > ( _VermarktungGewerbeTyp2Kauf_QNAME , VermarktungGrundstueckGewerbeTyp . Kauf . class , VermarktungGrundstueckGewerbeTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckGewerbeTyp . Pacht } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Pacht\" , scope = VermarktungGrundstueckGewerbeTyp . class ) public JAXBElement < VermarktungGrundstueckGewerbeTyp . Pacht > createVermarktungGrundstueckGewerbeTypPacht ( VermarktungGrundstueckGewerbeTyp . Pacht value ) { return new JAXBElement < VermarktungGrundstueckGewerbeTyp . Pacht > ( _VermarktungGrundstueckWohnenMieteTypPacht_QNAME , VermarktungGrundstueckGewerbeTyp . Pacht . class , VermarktungGrundstueckGewerbeTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckGewerbeTyp . Erbpacht } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Erbpacht\" , scope = VermarktungGrundstueckGewerbeTyp . class ) public JAXBElement < VermarktungGrundstueckGewerbeTyp . Erbpacht > createVermarktungGrundstueckGewerbeTypErbpacht ( VermarktungGrundstueckGewerbeTyp . Erbpacht value ) { return new JAXBElement < VermarktungGrundstueckGewerbeTyp . Erbpacht > ( _VermarktungGrundstueckWohnenKaufTypErbpacht_QNAME , VermarktungGrundstueckGewerbeTyp . Erbpacht . class , VermarktungGrundstueckGewerbeTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link VermarktungGrundstueckGewerbeTyp . Miete } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"Miete\" , scope = VermarktungGrundstueckGewerbeTyp . class ) public JAXBElement < VermarktungGrundstueckGewerbeTyp . Miete > createVermarktungGrundstueckGewerbeTypMiete ( VermarktungGrundstueckGewerbeTyp . Miete value ) { return new JAXBElement < VermarktungGrundstueckGewerbeTyp . Miete > ( _VermarktungGewerbeTypMiete_QNAME , VermarktungGrundstueckGewerbeTyp . Miete . class , VermarktungGrundstueckGewerbeTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"ApiSuchfeld1\" , scope = ApiSuchfelderTyp . class ) public JAXBElement < String > createApiSuchfelderTypApiSuchfeld1 ( String value ) { return new JAXBElement < String > ( _ApiSuchfelderTypApiSuchfeld1_QNAME , String . class , ApiSuchfelderTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"ApiSuchfeld2\" , scope = ApiSuchfelderTyp . class ) public JAXBElement < String > createApiSuchfelderTypApiSuchfeld2 ( String value ) { return new JAXBElement < String > ( _ApiSuchfelderTypApiSuchfeld2_QNAME , String . class , ApiSuchfelderTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immobilienscout24.de/immobilientransfer\" , name = \"ApiSuchfeld3\" , scope = ApiSuchfelderTyp . class ) public JAXBElement < String > createApiSuchfelderTypApiSuchfeld3 ( String value ) { return new JAXBElement < String > ( _ApiSuchfelderTypApiSuchfeld3_QNAME , String . class , ApiSuchfelderTyp . class , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"immoxml_anid\" ) public JAXBElement < String > createImmoxmlAnid ( String value ) { return new JAXBElement < String > ( _ImmoxmlAnid_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"strasse\" ) public JAXBElement < String > createStrasse ( String value ) { return new JAXBElement < String > ( _Strasse_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"hausnummer\" ) public JAXBElement < String > createHausnummer ( String value ) { return new JAXBElement < String > ( _Hausnummer_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"plz\" ) public JAXBElement < String > createPlz ( String value ) { return new JAXBElement < String > ( _Plz_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"ort\" ) public JAXBElement < String > createOrt ( String value ) { return new JAXBElement < String > ( _Ort_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"flurstueck\" ) public JAXBElement < String > createFlurstueck ( String value ) { return new JAXBElement < String > ( _Flurstueck_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"gemarkung\" ) public JAXBElement < String > createGemarkung ( String value ) { return new JAXBElement < String > ( _Gemarkung_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigInteger } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"etage\" ) @ XmlJavaTypeAdapter ( Adapter5 . class ) public JAXBElement < BigInteger > createEtage ( BigInteger value ) { return new JAXBElement < BigInteger > ( _Etage_QNAME , BigInteger . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"wohnungsnr\" ) public JAXBElement < String > createWohnungsnr ( String value ) { return new JAXBElement < String > ( _Wohnungsnr_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"vorname\" ) public JAXBElement < String > createVorname ( String value ) { return new JAXBElement < String > ( _Vorname_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anrede\" ) public JAXBElement < String > createAnrede ( String value ) { return new JAXBElement < String > ( _Anrede_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anrede_brief\" ) public JAXBElement < String > createAnredeBrief ( String value ) { return new JAXBElement < String > ( _AnredeBrief_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"firma\" ) public JAXBElement < String > createFirma ( String value ) { return new JAXBElement < String > ( _Firma_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Object } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"zusatzfeld\" ) public JAXBElement < Object > createZusatzfeld ( Object value ) { return new JAXBElement < Object > ( _Zusatzfeld_QNAME , Object . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"postfach\" ) public JAXBElement < String > createPostfach ( String value ) { return new JAXBElement < String > ( _Postfach_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"postf_plz\" ) public JAXBElement < String > createPostfPlz ( String value ) { return new JAXBElement < String > ( _PostfPlz_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"email_zentrale\" ) public JAXBElement < String > createEmailZentrale ( String value ) { return new JAXBElement < String > ( _EmailZentrale_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"email_privat\" ) public JAXBElement < String > createEmailPrivat ( String value ) { return new JAXBElement < String > ( _EmailPrivat_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"tel_zentrale\" ) public JAXBElement < String > createTelZentrale ( String value ) { return new JAXBElement < String > ( _TelZentrale_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"tel_durchw\" ) public JAXBElement < String > createTelDurchw ( String value ) { return new JAXBElement < String > ( _TelDurchw_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"tel_privat\" ) public JAXBElement < String > createTelPrivat ( String value ) { return new JAXBElement < String > ( _TelPrivat_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"adressfreigabe\" ) public JAXBElement < Boolean > createAdressfreigabe ( Boolean value ) { return new JAXBElement < Boolean > ( _Adressfreigabe_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"personennummer\" ) public JAXBElement < String > createPersonennummer ( String value ) { return new JAXBElement < String > ( _Personennummer_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"freitextfeld\" ) public JAXBElement < String > createFreitextfeld ( String value ) { return new JAXBElement < String > ( _Freitextfeld_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"kaufpreis\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createKaufpreis ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Kaufpreis_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"heizkosten\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createHeizkosten ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Heizkosten_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"zzg_mehrwertsteuer\" ) public JAXBElement < Boolean > createZzgMehrwertsteuer ( Boolean value ) { return new JAXBElement < Boolean > ( _ZzgMehrwertsteuer_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"mietzuschlaege\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createMietzuschlaege ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Mietzuschlaege_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"preis_zeitraum_bis\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createPreisZeitraumBis ( Calendar value ) { return new JAXBElement < Calendar > ( _PreisZeitraumBis_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"mietpreis_pro_qm\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createMietpreisProQm ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _MietpreisProQm_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"kaufpreis_pro_qm\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createKaufpreisProQm ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _KaufpreisProQm_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Stellplatz } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"stp_parkhaus\" ) public JAXBElement < Stellplatz > createStpParkhaus ( Stellplatz value ) { return new JAXBElement < Stellplatz > ( _StpParkhaus_QNAME , Stellplatz . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"freitext_preis\" ) public JAXBElement < String > createFreitextPreis ( String value ) { return new JAXBElement < String > ( _FreitextPreis_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"x_fache\" ) public JAXBElement < String > createXFache ( String value ) { return new JAXBElement < String > ( _XFache_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"nettorendite\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createNettorendite ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Nettorendite_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"mieteinnahmen_ist\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createMieteinnahmenIst ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _MieteinnahmenIst_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"mieteinnahmen_soll\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createMieteinnahmenSoll ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _MieteinnahmenSoll_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"kaution\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createKaution ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Kaution_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"geschaeftsguthaben\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createGeschaeftsguthaben ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Geschaeftsguthaben_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"wohnflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createWohnflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Wohnflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"nutzflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createNutzflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Nutzflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"gesamtflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createGesamtflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Gesamtflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"ladenflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createLadenflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Ladenflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"freiflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createFreiflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Freiflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"bueroflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createBueroflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Bueroflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"bueroteilflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createBueroteilflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Bueroteilflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"fensterfront\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createFensterfront ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Fensterfront_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"sonstflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createSonstflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Sonstflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"verwaltungsflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createVerwaltungsflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Verwaltungsflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"gfz\" ) public JAXBElement < String > createGfz ( String value ) { return new JAXBElement < String > ( _Gfz_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"bmz\" ) public JAXBElement < String > createBmz ( String value ) { return new JAXBElement < String > ( _Bmz_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"bgf\" ) public JAXBElement < String > createBgf ( String value ) { return new JAXBElement < String > ( _Bgf_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"grundstuecksflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createGrundstuecksflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Grundstuecksflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anzahl_zimmer\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createAnzahlZimmer ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlZimmer_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anzahl_schlafzimmer\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createAnzahlSchlafzimmer ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlSchlafzimmer_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"balkon_terrasse_flaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createBalkonTerrasseFlaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _BalkonTerrasseFlaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anzahl_wohn_schlafzimmer\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createAnzahlWohnSchlafzimmer ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlWohnSchlafzimmer_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"gartenflaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createGartenflaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Gartenflaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anzahl_balkon_terrassen\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createAnzahlBalkonTerrassen ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlBalkonTerrassen_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"teilbar_ab\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createTeilbarAb ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _TeilbarAb_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"beheizbare_flaeche\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createBeheizbareFlaeche ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _BeheizbareFlaeche_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anzahl_stellplaetze\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createAnzahlStellplaetze ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlStellplaetze_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anzahl_gewerbeeinheiten\" ) @ XmlJavaTypeAdapter ( Adapter7 . class ) public JAXBElement < BigDecimal > createAnzahlGewerbeeinheiten ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _AnzahlGewerbeeinheiten_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"einliegerwohnung\" ) public JAXBElement < Boolean > createEinliegerwohnung ( Boolean value ) { return new JAXBElement < Boolean > ( _Einliegerwohnung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"wg_geeignet\" ) public JAXBElement < Boolean > createWgGeeignet ( Boolean value ) { return new JAXBElement < Boolean > ( _WgGeeignet_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"kabel_sat_tv\" ) public JAXBElement < Boolean > createKabelSatTv ( Boolean value ) { return new JAXBElement < Boolean > ( _KabelSatTv_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"barrierefrei\" ) public JAXBElement < Boolean > createBarrierefrei ( Boolean value ) { return new JAXBElement < Boolean > ( _Barrierefrei_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"kran\" ) public JAXBElement < Boolean > createKran ( Boolean value ) { return new JAXBElement < Boolean > ( _Kran_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"stromanschlusswert\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createStromanschlusswert ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Stromanschlusswert_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"wellnessbereich\" ) public JAXBElement < Boolean > createWellnessbereich ( Boolean value ) { return new JAXBElement < Boolean > ( _Wellnessbereich_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"baujahr\" ) public JAXBElement < String > createBaujahr ( String value ) { return new JAXBElement < String > ( _Baujahr_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"altlasten\" ) public JAXBElement < String > createAltlasten ( String value ) { return new JAXBElement < String > ( _Altlasten_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"zulieferung\" ) public JAXBElement < Boolean > createZulieferung ( Boolean value ) { return new JAXBElement < Boolean > ( _Zulieferung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"objekttitel\" ) public JAXBElement < String > createObjekttitel ( String value ) { return new JAXBElement < String > ( _Objekttitel_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"ausstatt_beschr\" ) public JAXBElement < String > createAusstattBeschr ( String value ) { return new JAXBElement < String > ( _AusstattBeschr_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"objektbeschreibung\" ) public JAXBElement < String > createObjektbeschreibung ( String value ) { return new JAXBElement < String > ( _Objektbeschreibung_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"sonstige_angaben\" ) public JAXBElement < String > createSonstigeAngaben ( String value ) { return new JAXBElement < String > ( _SonstigeAngaben_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anhangtitel\" ) public JAXBElement < String > createAnhangtitel ( String value ) { return new JAXBElement < String > ( _Anhangtitel_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"format\" ) public JAXBElement < String > createFormat ( String value ) { return new JAXBElement < String > ( _Format_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link byte [] } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"anhanginhalt\" ) public JAXBElement < byte [ ] > createAnhanginhalt ( byte [ ] value ) { return new JAXBElement < byte [ ] > ( _Anhanginhalt_QNAME , byte [ ] . class , null , ( ( byte [ ] ) value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"verfuegbar_ab\" ) public JAXBElement < String > createVerfuegbarAb ( String value ) { return new JAXBElement < String > ( _VerfuegbarAb_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"abdatum\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createAbdatum ( Calendar value ) { return new JAXBElement < Calendar > ( _Abdatum_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"bisdatum\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createBisdatum ( Calendar value ) { return new JAXBElement < Calendar > ( _Bisdatum_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"versteigerungstermin\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createVersteigerungstermin ( Calendar value ) { return new JAXBElement < Calendar > ( _Versteigerungstermin_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"wbs_sozialwohnung\" ) public JAXBElement < Boolean > createWbsSozialwohnung ( Boolean value ) { return new JAXBElement < Boolean > ( _WbsSozialwohnung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"vermietet\" ) public JAXBElement < Boolean > createVermietet ( Boolean value ) { return new JAXBElement < Boolean > ( _Vermietet_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"objektnr_extern\" ) public JAXBElement < String > createObjektnrExtern ( String value ) { return new JAXBElement < String > ( _ObjektnrExtern_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"gruppennummer\" ) public JAXBElement < String > createGruppennummer ( String value ) { return new JAXBElement < String > ( _Gruppennummer_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"zugang\" ) public JAXBElement < String > createZugang ( String value ) { return new JAXBElement < String > ( _Zugang_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"aktiv_von\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createAktivVon ( Calendar value ) { return new JAXBElement < Calendar > ( _AktivVon_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"aktiv_bis\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createAktivBis ( Calendar value ) { return new JAXBElement < Calendar > ( _AktivBis_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link BigDecimal } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"laufzeit\" ) @ XmlJavaTypeAdapter ( Adapter2 . class ) public JAXBElement < BigDecimal > createLaufzeit ( BigDecimal value ) { return new JAXBElement < BigDecimal > ( _Laufzeit_QNAME , BigDecimal . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"haustiere\" ) public JAXBElement < Boolean > createHaustiere ( Boolean value ) { return new JAXBElement < Boolean > ( _Haustiere_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"denkmalgeschuetzt\" ) public JAXBElement < Boolean > createDenkmalgeschuetzt ( Boolean value ) { return new JAXBElement < Boolean > ( _Denkmalgeschuetzt_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Calendar } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"stand_vom\" ) @ XmlJavaTypeAdapter ( Adapter4 . class ) public JAXBElement < Calendar > createStandVom ( Calendar value ) { return new JAXBElement < Calendar > ( _StandVom_QNAME , Calendar . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"kennung_ursprung\" ) public JAXBElement < String > createKennungUrsprung ( String value ) { return new JAXBElement < String > ( _KennungUrsprung_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"immoxml_obid\" ) public JAXBElement < String > createImmoxmlObid ( String value ) { return new JAXBElement < String > ( _ImmoxmlObid_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"weitergabe_generell\" ) public JAXBElement < Boolean > createWeitergabeGenerell ( Boolean value ) { return new JAXBElement < Boolean > ( _WeitergabeGenerell_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"als_ferien\" ) public JAXBElement < Boolean > createAlsFerien ( Boolean value ) { return new JAXBElement < Boolean > ( _AlsFerien_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"gewerbliche_nutzung\" ) public JAXBElement < Boolean > createGewerblicheNutzung ( Boolean value ) { return new JAXBElement < Boolean > ( _GewerblicheNutzung_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link String } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"branchen\" ) public JAXBElement < String > createBranchen ( String value ) { return new JAXBElement < String > ( _Branchen_QNAME , String . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link JAXBElement } { @code < } { @link Boolean } { @code > }} [CODESPLIT] @ XmlElementDecl ( namespace = \"http://www.immoxml.de\" , name = \"hochhaus\" ) public JAXBElement < Boolean > createHochhaus ( Boolean value ) { return new JAXBElement < Boolean > ( _Hochhaus_QNAME , Boolean . class , null , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( OpenImmoWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create an Openimmo object with some example data // this object corresponds to the <openimmo> root element in XML Openimmo openimmo = FACTORY . createOpenimmo ( ) ; openimmo . setUebertragung ( createUebertragung ( ) ) ; openimmo . getAnbieter ( ) . add ( createAnbieter ( ) ) ; // convert the Openimmo object into a XML document OpenImmoTransferDocument doc = null ; try { doc = OpenImmoTransferDocument . newDocument ( openimmo ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; // downgrade XML document to an earlier version // and write it to the console doc . downgrade ( OpenImmoVersion . V1_2_3 ) ; writeToConsole ( doc ) ; // downgrade XML document to the first version // and write it to the console doc . downgrade ( OpenImmoVersion . V1_1 ) ; writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Anbieter } with some example data . [CODESPLIT] protected static Anbieter createAnbieter ( ) { // create an example agency Anbieter anbieter = FACTORY . createAnbieter ( ) ; anbieter . setAnbieternr ( \"123456\" ) ; anbieter . setFirma ( \"Agency Name\" ) ; anbieter . setOpenimmoAnid ( \"123456\" ) ; // add some real estates to the agency anbieter . getImmobilie ( ) . add ( createImmobilie ( ) ) ; anbieter . getImmobilie ( ) . add ( createImmobilie ( ) ) ; return anbieter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Immobilie } with some example data . [CODESPLIT] protected static Immobilie createImmobilie ( ) { // create an example real estate Immobilie immobilie = FACTORY . createImmobilie ( ) ; // add some administrative information immobilie . setVerwaltungTechn ( FACTORY . createVerwaltungTechn ( ) ) ; immobilie . getVerwaltungTechn ( ) . setAktion ( FACTORY . createAktion ( ) ) ; immobilie . getVerwaltungTechn ( ) . getAktion ( ) . setAktionart ( Aktion . AktionArt . CHANGE ) ; immobilie . getVerwaltungTechn ( ) . setObjektnrIntern ( RandomStringUtils . randomNumeric ( 10 ) ) ; // set categorization immobilie . setObjektkategorie ( FACTORY . createObjektkategorie ( ) ) ; immobilie . getObjektkategorie ( ) . setNutzungsart ( FACTORY . createNutzungsart ( ) ) ; immobilie . getObjektkategorie ( ) . getNutzungsart ( ) . setANLAGE ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; immobilie . getObjektkategorie ( ) . getNutzungsart ( ) . setGEWERBE ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; immobilie . getObjektkategorie ( ) . getNutzungsart ( ) . setWAZ ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; immobilie . getObjektkategorie ( ) . getNutzungsart ( ) . setWOHNEN ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; immobilie . getObjektkategorie ( ) . setVermarktungsart ( FACTORY . createVermarktungsart ( ) ) ; immobilie . getObjektkategorie ( ) . getVermarktungsart ( ) . setKAUF ( true ) ; immobilie . getObjektkategorie ( ) . setObjektart ( FACTORY . createObjektart ( ) ) ; Haus singleFamilyHouse = FACTORY . createHaus ( ) ; singleFamilyHouse . setHaustyp ( Haus . Haustyp . EINFAMILIENHAUS ) ; immobilie . getObjektkategorie ( ) . getObjektart ( ) . getHaus ( ) . add ( singleFamilyHouse ) ; // add some information about the location immobilie . setGeo ( FACTORY . createGeo ( ) ) ; immobilie . getGeo ( ) . setPlz ( RandomStringUtils . randomNumeric ( 5 ) ) ; immobilie . getGeo ( ) . setOrt ( \"Berlin\" ) ; immobilie . getGeo ( ) . setLand ( FACTORY . createLand ( ) ) ; immobilie . getGeo ( ) . getLand ( ) . setIsoLand ( Locale . GERMANY . getISO3Country ( ) ) ; // add some information about prices immobilie . setPreise ( FACTORY . createPreise ( ) ) ; immobilie . getPreise ( ) . setHeizkosten ( new BigDecimal ( \"456.0\" ) ) ; immobilie . getPreise ( ) . setKaufpreis ( FACTORY . createKaufpreis ( ) ) ; immobilie . getPreise ( ) . getKaufpreis ( ) . setAufAnfrage ( false ) ; immobilie . getPreise ( ) . getKaufpreis ( ) . setValue ( new BigDecimal ( \"123456.79\" ) ) ; // add some information about features immobilie . setAusstattung ( FACTORY . createAusstattung ( ) ) ; immobilie . getAusstattung ( ) . setGaestewc ( true ) ; immobilie . getAusstattung ( ) . setGartennutzung ( true ) ; immobilie . getAusstattung ( ) . setHeizungsart ( FACTORY . createHeizungsart ( ) ) ; immobilie . getAusstattung ( ) . getHeizungsart ( ) . setZENTRAL ( true ) ; immobilie . getAusstattung ( ) . getHeizungsart ( ) . setFUSSBODEN ( true ) ; // add some descriptions immobilie . setFreitexte ( FACTORY . createFreitexte ( ) ) ; immobilie . getFreitexte ( ) . setObjekttitel ( \"A title for the property.\" ) ; immobilie . getFreitexte ( ) . setObjektbeschreibung ( \"Some longer descriptive text about the property.\" ) ; // set the contact person immobilie . setKontaktperson ( FACTORY . createKontaktperson ( ) ) ; immobilie . getKontaktperson ( ) . setName ( \"Max Mustermann\" ) ; immobilie . getKontaktperson ( ) . setEmailFeedback ( \"max@mustermann.org\" ) ; immobilie . getKontaktperson ( ) . setTelDurchw ( \"030/123456789\" ) ; immobilie . getKontaktperson ( ) . setPlz ( RandomStringUtils . randomNumeric ( 5 ) ) ; immobilie . getKontaktperson ( ) . setOrt ( \"Berlin\" ) ; immobilie . getKontaktperson ( ) . setLand ( FACTORY . createLand ( ) ) ; immobilie . getKontaktperson ( ) . getLand ( ) . setIsoLand ( Locale . GERMANY . getISO3Country ( ) ) ; return immobilie ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Uebertragung } with some example data . [CODESPLIT] protected static Uebertragung createUebertragung ( ) { // create an example transfer Uebertragung uebertragung = FACTORY . createUebertragung ( ) ; uebertragung . setArt ( Uebertragung . Art . OFFLINE ) ; uebertragung . setModus ( Uebertragung . Modus . NEW ) ; uebertragung . setSendersoftware ( \"OpenEstate-IO\" ) ; uebertragung . setSenderversion ( \"1.4\" ) ; uebertragung . setTechnEmail ( \"test@test.org\" ) ; uebertragung . setTimestamp ( Calendar . getInstance ( ) ) ; uebertragung . setUmfang ( Uebertragung . Umfang . VOLL ) ; return uebertragung ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( FilemakerWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a FMPXMLRESULT object with some example data // this object corresponds to the <FMPXMLRESULT> root element in XML FMPXMLRESULT result = FACTORY . createFMPXMLRESULT ( ) ; result . setERRORCODE ( \"0\" ) ; result . setPRODUCT ( createProduct ( ) ) ; result . setDATABASE ( createDatabase ( ) ) ; result . setMETADATA ( createMetaData ( ) ) ; result . setRESULTSET ( createResultSet ( ) ) ; // convert the Openimmo object into a XML document FilemakerResultDocument doc = null ; try { doc = FilemakerResultDocument . newDocument ( result ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link DatabaseType } with some example data . [CODESPLIT] protected static DatabaseType createDatabase ( ) { DatabaseType database = FACTORY . createDatabaseType ( ) ; database . setNAME ( \"example database\" ) ; database . setLAYOUT ( \"fmmedia2universal\" ) ; database . setDATEFORMAT ( \"D.m.yyyy\" ) ; database . setTIMEFORMAT ( \"k:mm:ss\" ) ; database . setRECORDS ( BigInteger . ZERO ) ; return database ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link MetaDataType } with some example data . [CODESPLIT] protected static MetaDataType createMetaData ( ) { MetaDataType metadata = FACTORY . createMetaDataType ( ) ; MetaDataType . FIELD field ; field = FACTORY . createMetaDataTypeFIELD ( ) ; field . setNAME ( \"number of rooms\" ) ; field . setEMPTYOK ( true ) ; field . setMAXREPEAT ( BigInteger . ONE ) ; field . setTYPE ( FieldType . NUMBER ) ; metadata . getFIELD ( ) . add ( field ) ; field = FACTORY . createMetaDataTypeFIELD ( ) ; field . setNAME ( \"price\" ) ; field . setEMPTYOK ( false ) ; field . setMAXREPEAT ( BigInteger . ONE ) ; field . setTYPE ( FieldType . NUMBER ) ; metadata . getFIELD ( ) . add ( field ) ; field = FACTORY . createMetaDataTypeFIELD ( ) ; field . setNAME ( \"description\" ) ; field . setEMPTYOK ( true ) ; field . setMAXREPEAT ( BigInteger . ONE ) ; field . setTYPE ( FieldType . TEXT ) ; metadata . getFIELD ( ) . add ( field ) ; return metadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link ProductType } with some example data . [CODESPLIT] protected static ProductType createProduct ( ) { ProductType product = FACTORY . createProductType ( ) ; product . setNAME ( \"OpenEstate-IO\" ) ; product . setVERSION ( \"1.4\" ) ; product . setBUILD ( \"123\" ) ; return product ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link ResultSetType } with some example data . [CODESPLIT] protected static ResultSetType createResultSet ( ) { ResultSetType result = FACTORY . createResultSetType ( ) ; result . getROW ( ) . add ( createResultSetRow ( 1 , 3 , 100 , \"a first example\" ) ) ; result . getROW ( ) . add ( createResultSetRow ( 2 , null , 200 , \"a second example\" ) ) ; result . getROW ( ) . add ( createResultSetRow ( 3 , 5 , 300 , null ) ) ; result . setFOUND ( BigInteger . valueOf ( result . getROW ( ) . size ( ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link org . openestate . io . filemaker . xml . result . ResultSetType . ROW } with some example data . [CODESPLIT] @ SuppressWarnings ( \"ConstantConditions\" ) protected static ResultSetType . ROW createResultSetRow ( long id , Number numberOfRooms , Number price , String description ) { ResultSetType . ROW . COL col ; ResultSetType . ROW row = FACTORY . createResultSetTypeROW ( ) ; row . setRECORDID ( BigInteger . valueOf ( id ) ) ; row . setMODID ( BigInteger . valueOf ( id ) ) ; col = FACTORY . createResultSetTypeROWCOL ( ) ; if ( numberOfRooms != null ) col . getDATA ( ) . add ( StringUtils . EMPTY ) ; else col . getDATA ( ) . add ( String . valueOf ( numberOfRooms ) ) ; row . getCOL ( ) . add ( col ) ; col = FACTORY . createResultSetTypeROWCOL ( ) ; if ( price != null ) col . getDATA ( ) . add ( \"0\" ) ; else col . getDATA ( ) . add ( String . valueOf ( price ) ) ; row . getCOL ( ) . add ( col ) ; col = FACTORY . createResultSetTypeROWCOL ( ) ; col . getDATA ( ) . add ( StringUtils . trimToEmpty ( description ) ) ; row . getCOL ( ) . add ( col ) ; return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link FilemakerResultDocument } into a { @link String } and print the results to the console . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void writeToConsole ( FilemakerResultDocument doc ) { LOGGER . info ( \"writing document\" ) ; try { String xml = doc . toXmlString ( PRETTY_PRINT ) ; LOGGER . info ( StringUtils . repeat ( \"-\" , 50 ) + System . lineSeparator ( ) + xml ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't write document into a string!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link CasaItDocument } from a { @link Document } . [CODESPLIT] public static CasaItDocument createDocument ( Document doc ) { if ( CasaItDocument . isReadable ( doc ) ) return new CasaItDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an { @link InputStream } into an { @link Is24XmlDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; Is24XmlDocument doc = Is24XmlUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of an { @link Is24XmlDocument } to console . [CODESPLIT] protected static void printToConsole ( Is24XmlDocument doc ) throws JAXBException { ImmobilienTransferTyp transfer = doc . toObject ( ) ; // process agency in the document if ( transfer . getAnbieter ( ) != null ) { // process objects for ( JAXBElement < ? extends ImmobilieBaseTyp > i : transfer . getAnbieter ( ) . getImmobilie ( ) ) { ImmobilieBaseTyp obj = i . getValue ( ) ; // get object nr String objectNr = ( ! StringUtils . isBlank ( obj . getAnbieterObjektID ( ) ) ) ? obj . getAnbieterObjektID ( ) . trim ( ) : \"???\" ; // get object title String objectTitle = ( ! StringUtils . isBlank ( obj . getUeberschrift ( ) ) ) ? obj . getUeberschrift ( ) . trim ( ) : \"???\" ; // print object information to console LOGGER . info ( \"> found object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } // process virtual objects for ( JAXBElement < ? extends VirtuelleImmobilieBaseTyp > i : transfer . getAnbieter ( ) . getVirtuelleImmobilie ( ) ) { VirtuelleImmobilieBaseTyp obj = i . getValue ( ) ; // get object nr String objectNr = ( ! StringUtils . isBlank ( obj . getAnbieterObjektID ( ) ) ) ? obj . getAnbieterObjektID ( ) . trim ( ) : \"???\" ; // get object title String objectTitle = ( ! StringUtils . isBlank ( obj . getUeberschrift ( ) ) ) ? obj . getUeberschrift ( ) . trim ( ) : \"???\" ; // print object information to console LOGGER . info ( \"> found virtual object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the bevorzugt property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Interessent . Bevorzugt > getBevorzugt ( ) { if ( bevorzugt == null ) { bevorzugt = new ArrayList < Interessent . Bevorzugt > ( ) ; } return this . bevorzugt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the wunsch property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Interessent . Wunsch > getWunsch ( ) { if ( wunsch == null ) { wunsch = new ArrayList < Interessent . Wunsch > ( ) ; } return this . wunsch ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the art property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setArt ( Uebertragung . Art value ) { this . art = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the modus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setModus ( Uebertragung . Modus value ) { this . modus = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the emailSonstige property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < EmailSonstige > getEmailSonstige ( ) { if ( emailSonstige == null ) { emailSonstige = new ArrayList < EmailSonstige > ( ) ; } return this . emailSonstige ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the telSonstige property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < TelSonstige > getTelSonstige ( ) { if ( telSonstige == null ) { telSonstige = new ArrayList < TelSonstige > ( ) ; } return this . telSonstige ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the handelTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setHandelTyp ( Einzelhandel . HandelTyp value ) { this . handelTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the erschlAttr property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setErschlAttr ( Erschliessung . ErschlAttr value ) { this . erschlAttr = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 6 to 1 . 2 . 5 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_5 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . removePreiseChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <preise> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeKaufpreisElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <kaufpreis> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeZwangsversteigerungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <zwangsversteigerung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeFlaechenChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <flaechen> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeBauzoneElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <bauzone> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBodenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <boden> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeEnergietypElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <energietyp> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeAusblickElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <ausblick> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBueroPraxenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <buero_praxen> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; ausblick&gt ; elements to OpenImmo 1 . 2 . 5 . <p > The option MEER for the blick attribute of &lt ; ausblick&gt ; elements is not available in version 1 . 2 . 5 . <p > Any occurence of the MEER value is replaced by the SEE value . [CODESPLIT] protected void downgradeAusblickElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:infrastruktur/io:ausblick[@blick]\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; String value = StringUtils . trimToNull ( node . getAttribute ( \"blick\" ) ) ; if ( \"MEER\" . equalsIgnoreCase ( value ) ) node . setAttribute ( \"blick\" , \"SEE\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( WisItWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a WIS object with some example data // this object corresponds to the <WIS> element in XML WIS wis = FACTORY . createWIS ( ) ; wis . setBENUTZER ( FACTORY . createWISBENUTZER ( ) ) ; wis . setOBJEKTE ( FACTORY . createWISOBJEKTE ( ) ) ; // append some example ads to the transfer wis . getOBJEKTE ( ) . getOBJEKT ( ) . add ( createOBJEKT ( ) ) ; wis . getOBJEKTE ( ) . getOBJEKT ( ) . add ( createOBJEKT ( ) ) ; wis . getOBJEKTE ( ) . getOBJEKT ( ) . add ( createOBJEKT ( ) ) ; wis . getOBJEKTE ( ) . setANZAHL ( BigInteger . valueOf ( wis . getOBJEKTE ( ) . getOBJEKT ( ) . size ( ) ) ) ; // convert the WIS object into a XML document WisItDocument doc = null ; try { doc = WisItDocument . newDocument ( wis ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link ObjectType } with some example data . [CODESPLIT] protected static ObjectType createOBJEKT ( ) { // create an example real estate ObjectType obj = FACTORY . createObjectType ( ) ; obj . setABSTELLPLATZ ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setAUFANFRAGE ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setAUFZUG ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBALKON ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBAUJAHR ( String . valueOf ( RandomUtils . nextInt ( 1900 , 2015 ) ) ) ; obj . setDACHBODEN ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setFLAECHEART ( AreaType . NETTO ) ; obj . setFOERDERBAR ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setFRAKTION ( \"some notes about the fraction\" ) ; obj . setGARAGE ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGRUENFLAECHE ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGUELTIGBIS ( Calendar . getInstance ( ) ) ; obj . setHEIZUNG ( HeatingType . ZENTRAL ) ; obj . setID ( RandomStringUtils . random ( 5 ) ) ; obj . setIMMOBILIENART ( PropertyType . EINFAMILIENHAUS ) ; obj . setINFODE ( \"some description in german language\" ) ; obj . setINFOIT ( \"some description in italian language\" ) ; obj . setKELLER ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setKLIMAHAUS ( EnergyStandard . A ) ; obj . setKONVENTIONIERT ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setKUBATUR ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100 , 1000 ) ) ) ; obj . setLOESCHEN ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setLOGGIA ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setMIETEKAUF ( MarketingType . MIETE ) ; obj . setNUTZFLAECHE ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100 , 1000 ) ) ) ; obj . setORT ( \"Bozen\" ) ; obj . setPREIS ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 300 , 3000 ) ) ) ; obj . setSTOCKWERK ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; obj . setSTOCKWERKE ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 10 ) ) ) ; obj . setTERRASSE ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setUEBERGABEZEITPUNKT ( \"some notes about the time of handover\" ) ; obj . setZIMMER ( BigInteger . valueOf ( RandomUtils . nextInt ( 1 , 5 ) ) ) ; obj . setZUSTAND ( ConditionType . GEBRAUCHT ) ; obj . setBILD1 ( obj . getID ( ) + \"_1.jpg\" ) ; obj . setBILD2 ( obj . getID ( ) + \"_2.jpg\" ) ; obj . setBILD3 ( obj . getID ( ) + \"_3.jpg\" ) ; obj . setBILD4 ( obj . getID ( ) + \"_4.jpg\" ) ; obj . setBILD5 ( obj . getID ( ) + \"_5.jpg\" ) ; obj . setBILD6 ( obj . getID ( ) + \"_6.jpg\" ) ; obj . setBILD7 ( obj . getID ( ) + \"_7.jpg\" ) ; obj . setBILD8 ( obj . getID ( ) + \"_8.jpg\" ) ; obj . setBILD9 ( obj . getID ( ) + \"_9.jpg\" ) ; obj . setBILD10 ( obj . getID ( ) + \"_10.jpg\" ) ; obj . setDOWNLOAD1 ( obj . getID ( ) + \"_1.pdf\" ) ; obj . setDOWNLOAD2 ( obj . getID ( ) + \"_2.pdf\" ) ; obj . setDOWNLOAD3 ( obj . getID ( ) + \"_3.pdf\" ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link WisItDocument } into an { @link OutputStream } . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void write ( WisItDocument doc , OutputStream output ) { LOGGER . info ( \"writing document\" ) ; try { doc . toXml ( output , PRETTY_PRINT ) ; LOGGER . info ( \"> written to a java.io.OutputStream\" ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't write document into an OutputStream!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the apiSuchfeld1 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setApiSuchfeld1 ( JAXBElement < String > value ) { this . apiSuchfeld1 = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the apiSuchfeld2 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setApiSuchfeld2 ( JAXBElement < String > value ) { this . apiSuchfeld2 = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the apiSuchfeld3 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setApiSuchfeld3 ( JAXBElement < String > value ) { this . apiSuchfeld3 = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the row property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:42:33+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < ResultSetType . ROW > getROW ( ) { if ( row == null ) { row = new ArrayList < ResultSetType . ROW > ( ) ; } return this . row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the distanzZuSport property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setDistanzZuSport ( DistanzenSport . DistanzZuSport value ) { this . distanzZuSport = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link DaftIeDocument } from a { @link Document } . [CODESPLIT] public static DaftIeDocument createDocument ( Document doc ) { if ( DaftIeDocument . isReadable ( doc ) ) return new DaftIeDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the anhang property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Anhang > getAnhang ( ) { if ( anhang == null ) { anhang = new ArrayList < Anhang > ( ) ; } return this . anhang ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objektKategorie2 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public GaragenKategorieTyp getObjektKategorie2 ( ) { if ( objektKategorie2 == null ) { return GaragenKategorieTyp . KEINE_ANGABE ; } else { return objektKategorie2 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objektzustand property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public ObjektZustandTyp getObjektzustand ( ) { if ( objektzustand == null ) { return ObjektZustandTyp . KEINE_ANGABE ; } else { return objektzustand ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the hausKategorie property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public HausKategorienTyp getHausKategorie ( ) { if ( hausKategorie == null ) { return HausKategorienTyp . KEINE_ANGABE ; } else { return hausKategorie ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the ausstattungsqualitaet property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public AusstattungsqualitaetsTyp getAusstattungsqualitaet ( ) { if ( ausstattungsqualitaet == null ) { return AusstattungsqualitaetsTyp . KEINE_ANGABE ; } else { return ausstattungsqualitaet ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( OpenImmoReadingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // read example files, if no files were specified as command line arguments if ( args . length < 1 ) { try { read ( OpenImmoReadingExample . class . getResourceAsStream ( PACKAGE + \"/openimmo.xml\" ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't read example transfer file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 2 ) ; } try { read ( OpenImmoReadingExample . class . getResourceAsStream ( PACKAGE + \"/openimmo-feedback.xml\" ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't read example feedback file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 2 ) ; } } // read files, that were specified as command line arguments else { for ( String arg : args ) { try { read ( new File ( arg ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't read file '\" + arg + \"'!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 2 ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link File } into an { @link OpenImmoTransferDocument } or { @link OpenImmoFeedbackDocument } and print some of their content to console . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void read ( File xmlFile ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process file: \" + xmlFile . getAbsolutePath ( ) ) ; if ( ! xmlFile . isFile ( ) ) { LOGGER . warn ( \"> provided file is invalid\" ) ; return ; } OpenImmoDocument doc = OpenImmoUtils . createDocument ( xmlFile ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else if ( doc . isFeedback ( ) ) { printToConsole ( ( OpenImmoFeedbackDocument ) doc ) ; } else if ( doc . isTransfer ( ) ) { printToConsole ( ( OpenImmoTransferDocument ) doc ) ; } else { LOGGER . warn ( \"> unsupported type of document: \" + doc . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into an { @link OpenImmoTransferDocument } or { @link OpenImmoFeedbackDocument } and print some of their content to console . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; OpenImmoDocument doc = OpenImmoUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else if ( doc . isFeedback ( ) ) { printToConsole ( ( OpenImmoFeedbackDocument ) doc ) ; } else if ( doc . isTransfer ( ) ) { printToConsole ( ( OpenImmoTransferDocument ) doc ) ; } else { LOGGER . warn ( \"> unsupported type of document: \" + doc . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of an { @link OpenImmoFeedbackDocument } to console . [CODESPLIT] protected static void printToConsole ( OpenImmoFeedbackDocument doc ) throws JAXBException { LOGGER . info ( \"> process feedback document in version \" + doc . getDocumentVersion ( ) ) ; OpenimmoFeedback feedback = doc . toObject ( ) ; for ( Objekt objekt : feedback . getObjekt ( ) ) { // get object nr String objectNr = ( ! StringUtils . isBlank ( objekt . getOobjId ( ) ) ) ? objekt . getOobjId ( ) . trim ( ) : \"???\" ; // get object title String objectTitle = ( ! StringUtils . isBlank ( objekt . getBezeichnung ( ) ) ) ? objekt . getBezeichnung ( ) . trim ( ) : \"???\" ; LOGGER . info ( \">> feedback for object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of an { @link OpenImmoTransferDocument } to console . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void printToConsole ( OpenImmoTransferDocument doc ) throws JAXBException { LOGGER . info ( \"> process transfer document in version \" + doc . getDocumentVersion ( ) ) ; Openimmo openimmo = doc . toObject ( ) ; // process agencies in the document for ( Anbieter anbieter : openimmo . getAnbieter ( ) ) { LOGGER . info ( \">> found agency '\" + anbieter . getAnbieternr ( ) + \"'\" ) ; // process real estates of the agency for ( Immobilie immobilie : anbieter . getImmobilie ( ) ) { // get object nr String objectNr = ( immobilie . getVerwaltungTechn ( ) != null ) ? immobilie . getVerwaltungTechn ( ) . getObjektnrIntern ( ) : \"???\" ; // get object title String objectTitle = ( immobilie . getFreitexte ( ) != null ) ? immobilie . getFreitexte ( ) . getObjekttitel ( ) : \"???\" ; // print object information to console LOGGER . info ( \">>> found object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the vermarktungsart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < String > getVermarktungsart ( ) { if ( vermarktungsart == null ) { vermarktungsart = new ArrayList < String > ( ) ; } return this . vermarktungsart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the interessent property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Interessent > getInteressent ( ) { if ( interessent == null ) { interessent = new ArrayList < Interessent > ( ) ; } return this . interessent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the wert property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setWert ( ProvisionTeilen . Wert value ) { this . wert = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ImmoXmlDocument } from a { @link Immoxml } object . [CODESPLIT] public static ImmoXmlDocument newDocument ( Immoxml immoxml ) throws ParserConfigurationException , JAXBException { if ( immoxml . getUebertragung ( ) == null ) immoxml . setUebertragung ( ImmoXmlUtils . getFactory ( ) . createUebertragung ( ) ) ; if ( StringUtils . isBlank ( immoxml . getUebertragung ( ) . getVersion ( ) ) ) immoxml . getUebertragung ( ) . setVersion ( ImmoXmlUtils . VERSION . toReadableVersion ( ) ) ; Document document = XmlUtils . newDocument ( ) ; ImmoXmlUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( immoxml , document ) ; return new ImmoXmlDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Immoxml } object from the contained { @link Document } . [CODESPLIT] @ Override public Immoxml toObject ( ) throws JAXBException { this . upgradeToLatestVersion ( ) ; return ( Immoxml ) ImmoXmlUtils . createUnmarshaller ( ) . unmarshal ( this . getDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the ackerland property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setAckerland ( JAXBElement < Object > value ) { this . ackerland = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the bauerwartungsland property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setBauerwartungsland ( JAXBElement < Object > value ) { this . bauerwartungsland = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the bootsstaende property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setBootsstaende ( JAXBElement < Object > value ) { this . bootsstaende = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the buero property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setBuero ( JAXBElement < Object > value ) { this . buero = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the camping property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setCamping ( JAXBElement < Object > value ) { this . camping = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the doppelhaus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setDoppelhaus ( JAXBElement < Object > value ) { this . doppelhaus = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the einfamilienhaus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setEinfamilienhaus ( JAXBElement < Object > value ) { this . einfamilienhaus = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the einzelhandelGross property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setEinzelhandelGross ( JAXBElement < Object > value ) { this . einzelhandelGross = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the einzelhandelKlein property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setEinzelhandelKlein ( JAXBElement < Object > value ) { this . einzelhandelKlein = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the garagen property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGaragen ( JAXBElement < Object > value ) { this . garagen = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the garten property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGarten ( JAXBElement < Object > value ) { this . garten = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the gastronomie property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGastronomie ( JAXBElement < Object > value ) { this . gastronomie = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the gewerbe property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGewerbe ( JAXBElement < Object > value ) { this . gewerbe = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the hotel property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setHotel ( JAXBElement < Object > value ) { this . hotel = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the industrie property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setIndustrie ( JAXBElement < Object > value ) { this . industrie = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the keineBebauung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setKeineBebauung ( JAXBElement < Object > value ) { this . keineBebauung = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the kleingewerbe property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setKleingewerbe ( JAXBElement < Object > value ) { this . kleingewerbe = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the lager property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setLager ( JAXBElement < Object > value ) { this . lager = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the mehrfamilienhaus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMehrfamilienhaus ( JAXBElement < Object > value ) { this . mehrfamilienhaus = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the obstpflanzung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setObstpflanzung ( JAXBElement < Object > value ) { this . obstpflanzung = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the parkhaus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setParkhaus ( JAXBElement < Object > value ) { this . parkhaus = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the produktion property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setProduktion ( JAXBElement < Object > value ) { this . produktion = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the reihenhaus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setReihenhaus ( JAXBElement < Object > value ) { this . reihenhaus = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the stellplaetze property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setStellplaetze ( JAXBElement < Object > value ) { this . stellplaetze = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the villa property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setVilla ( JAXBElement < Object > value ) { this . villa = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the wald property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setWald ( JAXBElement < Object > value ) { this . wald = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrades the contained { @link Document } to an earlier version . [CODESPLIT] public void downgrade ( VersionType targetVersion ) { if ( targetVersion == null ) throw new NullPointerException ( \"No target version was provided!\" ) ; XmlVersion currentVersion = this . getDocumentVersion ( ) ; if ( currentVersion == null ) { currentVersion = this . getLatestVersion ( ) ; LOGGER . warn ( \"Can't determine document version! Assuming latest version \" + currentVersion . toReadableVersion ( ) + \".\" ) ; } if ( currentVersion == targetVersion ) return ; if ( currentVersion . isOlderThen ( targetVersion ) ) { LOGGER . warn ( \"The provided target version (\" + targetVersion . toReadableVersion ( ) + \") \" + \"is newer then the document version (\" + currentVersion . toReadableVersion ( ) + \").\" ) ; return ; } XmlVersion v = currentVersion ; while ( true ) { v . getConverter ( ) . downgradeToPreviousVersion ( this ) ; v = v . getPreviousVersion ( ) ; if ( v == targetVersion ) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrades the contained { @link Document } to a newer version . [CODESPLIT] public void upgrade ( XmlVersion targetVersion ) { if ( targetVersion == null ) throw new NullPointerException ( \"No target version was provided!\" ) ; XmlVersion currentVersion = this . getDocumentVersion ( ) ; if ( currentVersion == null ) { currentVersion = this . getLatestVersion ( ) ; LOGGER . warn ( \"Can't determine document version! Assuming latest version \" + currentVersion . toReadableVersion ( ) + \".\" ) ; } if ( currentVersion == targetVersion ) return ; if ( currentVersion . isNewerThen ( targetVersion ) ) { LOGGER . warn ( \"The provided target version (\" + targetVersion . toReadableVersion ( ) + \") \" + \"is older then the document version (\" + currentVersion . toReadableVersion ( ) + \").\" ) ; return ; } XmlVersion v = currentVersion ; while ( true ) { v = v . getNextVersion ( ) ; v . getConverter ( ) . upgradeFromPreviousVersion ( this ) ; if ( v == targetVersion ) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the anbieter property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setAnbieter ( ImmobilienTransferTyp . Anbieter value ) { this . anbieter = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the wohnung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Wohnung > getWohnung ( ) { if ( wohnung == null ) { wohnung = new ArrayList < Wohnung > ( ) ; } return this . wohnung ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the grundstueck property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Grundstueck > getGrundstueck ( ) { if ( grundstueck == null ) { grundstueck = new ArrayList < Grundstueck > ( ) ; } return this . grundstueck ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the einzelhandel property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Einzelhandel > getEinzelhandel ( ) { if ( einzelhandel == null ) { einzelhandel = new ArrayList < Einzelhandel > ( ) ; } return this . einzelhandel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the hallenLagerProd property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < HallenLagerProd > getHallenLagerProd ( ) { if ( hallenLagerProd == null ) { hallenLagerProd = new ArrayList < HallenLagerProd > ( ) ; } return this . hallenLagerProd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the parken property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Parken > getParken ( ) { if ( parken == null ) { parken = new ArrayList < Parken > ( ) ; } return this . parken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the freizeitimmobilieGewerblich property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < FreizeitimmobilieGewerblich > getFreizeitimmobilieGewerblich ( ) { if ( freizeitimmobilieGewerblich == null ) { freizeitimmobilieGewerblich = new ArrayList < FreizeitimmobilieGewerblich > ( ) ; } return this . freizeitimmobilieGewerblich ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objektartZusatz property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < String > getObjektartZusatz ( ) { if ( objektartZusatz == null ) { objektartZusatz = new ArrayList < String > ( ) ; } return this . objektartZusatz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the stellplatzart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Stellplatzart > getStellplatzart ( ) { if ( stellplatzart == null ) { stellplatzart = new ArrayList < Stellplatzart > ( ) ; } return this . stellplatzart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the maxDauer property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMaxDauer ( MaxMietdauer . MaxDauer value ) { this . maxDauer = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link FilemakerDocument } from a { @link Document } . [CODESPLIT] public static FilemakerDocument createDocument ( Document doc ) { if ( FilemakerResultDocument . isReadable ( doc ) ) return new FilemakerResultDocument ( doc ) ; else if ( FilemakerLayoutDocument . isReadable ( doc ) ) return new FilemakerLayoutDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( IdxWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create some CSV records List < IdxRecord > records = new ArrayList <> ( ) ; records . add ( createRecord ( ) ) ; records . add ( createRecord ( ) ) ; records . add ( createRecord ( ) ) ; records . add ( createRecord ( ) ) ; // write CSV records into a java.io.File try { write ( records , File . createTempFile ( \"output-\" , \".csv\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write CSV records into a java.io.OutputStream write ( records , new NullOutputStream ( ) ) ; // write CSV records into a java.io.Writer write ( records , new NullWriter ( ) ) ; // write CSV records into a string and send it to the console writeToConsole ( records ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link IdxRecord } with some example data . [CODESPLIT] protected static IdxRecord createRecord ( ) { // create an example real estate IdxRecord obj = new IdxRecord ( ) ; obj . setAdvertisementId ( RandomStringUtils . random ( 5 ) ) ; obj . setAgencyCity ( \"Berlin\" ) ; obj . setAgencyCountry ( Locale . GERMANY . getCountry ( ) ) ; obj . setAgencyEmail ( \"tester@test.org\" ) ; obj . setAgencyFax ( \"030/123456\" ) ; obj . setAgencyId ( RandomStringUtils . random ( 5 ) ) ; obj . setAgencyName ( \"agency name\" ) ; obj . setAgencyName2 ( \"additional agency name\" ) ; obj . setAgencyPhone ( \"030/123457\" ) ; obj . setAgencyReference ( RandomStringUtils . random ( 5 ) ) ; obj . setAgencyStreet ( \"example street 123\" ) ; obj . setAgencyZip ( \"12345\" ) ; obj . setAnimalAllowed ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setAvailableFrom ( Calendar . getInstance ( ) ) ; obj . setBalcony ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBillingCompany ( \"agency name\" ) ; obj . setBillingCountry ( \"Germany\" ) ; obj . setBillingFirstName ( \"Max\" ) ; obj . setBillingLanguage ( Language . GERMAN ) ; obj . setBillingMobile ( \"030/132456\" ) ; obj . setBillingName ( \"Mustermann\" ) ; obj . setBillingPhone ( \"030/123457\" ) ; obj . setBillingPhone2 ( \"030/123458\" ) ; obj . setBillingPlaceName ( \"Berlin\" ) ; obj . setBillingPostBox ( \"additional address notes\" ) ; obj . setBillingSalutation ( Salutation . MALE ) ; obj . setBillingStreet ( \"example street 123\" ) ; obj . setBillingZip ( \"12345\" ) ; obj . setBuildingLandConnected ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setCableTv ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setCarryingCapacityCrane ( RandomUtils . nextDouble ( 500 , 5000 ) ) ; obj . setCarryingCapacityElevator ( RandomUtils . nextDouble ( 500 , 5000 ) ) ; obj . setCeilingHeight ( RandomUtils . nextDouble ( 2 , 10 ) ) ; obj . setChildFriendly ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setCornerHouse ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setCurrency ( Currency . getInstance ( \"EUR\" ) ) ; obj . setDistanceKindergarten ( RandomUtils . nextInt ( 50 , 5000 ) ) ; obj . setDistanceMotorway ( RandomUtils . nextInt ( 50 , 5000 ) ) ; obj . setDistancePublicTransport ( RandomUtils . nextInt ( 50 , 5000 ) ) ; obj . setDistanceSchool1 ( RandomUtils . nextInt ( 50 , 5000 ) ) ; obj . setDistanceSchool2 ( RandomUtils . nextInt ( 50 , 5000 ) ) ; obj . setDistanceShop ( RandomUtils . nextInt ( 50 , 5000 ) ) ; obj . setElevator ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setFireplace ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setFlatSharingCommunity ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setFloor ( RandomUtils . nextInt ( 0 , 10 ) ) ; obj . setGarage ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGardenhouse ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGasSupply ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGrossPremium ( GrossPremium . FROM_4_UNTIL_5 ) ; obj . setHallHeight ( RandomUtils . nextDouble ( 3 , 15 ) ) ; obj . setIsdn ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setLastModified ( Calendar . getInstance ( ) ) ; obj . setLiftingPlatform ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setMaximalFloorLoading ( RandomUtils . nextDouble ( 50 , 5000 ) ) ; obj . setMiddleHouse ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setMinEnergyCertified ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setMinEnergyGeneral ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setNewBuilding ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setNumberOfApartments ( RandomUtils . nextDouble ( 1 , 10 ) ) ; obj . setNumberOfFloors ( RandomUtils . nextInt ( 1 , 10 ) ) ; obj . setNumberOfRooms ( RandomUtils . nextDouble ( 1 , 10 ) ) ; obj . setObjectCity ( \"Berlin\" ) ; obj . setObjectCountry ( Locale . GERMANY . getCountry ( ) ) ; obj . setObjectDescription ( \"some description\" + System . lineSeparator ( ) + \" about the object\" ) ; obj . setObjectSituation ( \"some description about the location\" ) ; obj . setObjectState ( \"BE\" ) ; obj . setObjectStreet ( \"example street 124\" ) ; obj . setObjectTitle ( \"title of object\" ) ; obj . setObjectType ( ObjectType . HOUSE_VILLA ) ; obj . setObjectZip ( \"12345\" ) ; obj . setOfferType ( OfferType . SALE ) ; obj . setOldBuilding ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setOwnObjectUrl ( \"http://test.org/object/123\" ) ; obj . setParking ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setPowerSupply ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setPriceUnit ( PriceUnit . MONTHLY ) ; obj . setRailwayTerminal ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setRaisedGroundFloor ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setRamp ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setRefHouse ( RandomStringUtils . random ( 5 ) ) ; obj . setRefObject ( RandomStringUtils . random ( 5 ) ) ; obj . setRefProperty ( RandomStringUtils . random ( 5 ) ) ; obj . setRentExtra ( RandomUtils . nextLong ( 100 , 1000 ) ) ; obj . setRentNet ( RandomUtils . nextLong ( 100 , 1000 ) ) ; obj . setRestrooms ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setSellingPrice ( RandomUtils . nextLong ( 100 , 1000 ) ) ; obj . setSenderId ( \"OpenEstate.org\" ) ; obj . setSewageSupply ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setSparefield1 ( \"spare field 1\" ) ; obj . setSparefield2 ( \"spare field 2\" ) ; obj . setSparefield3 ( \"spare field 3\" ) ; obj . setSparefield4 ( \"spare field 4\" ) ; obj . setSurfaceLiving ( RandomUtils . nextLong ( 50 , 300 ) ) ; obj . setSurfaceProperty ( RandomUtils . nextLong ( 100 , 1000 ) ) ; obj . setSurfaceUsable ( RandomUtils . nextLong ( 100 , 1000 ) ) ; obj . setSwimmingpool ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setUnderBuildingLaws ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setUnderRoof ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setUrl ( \"http://test.org/object/123\" ) ; obj . setView ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setVisitName ( \"Max Mustermann\" ) ; obj . setVisitPhone ( \"030/123456\" ) ; obj . setVisitRemark ( \"notes about the contact person\" ) ; obj . setVolume ( RandomUtils . nextLong ( 50 , 500 ) ) ; obj . setWaterSupply ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setWheelcharAccessible ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setYearBuilt ( RandomUtils . nextInt ( 1900 , 1995 ) ) ; obj . setYearRenovated ( RandomUtils . nextInt ( 1995 , 2010 ) ) ; obj . setDocument ( new Media ( \"document.pdf\" , \"a document about the object\" ) ) ; obj . setMovie ( new Media ( \"document.mp4\" , \"a document about the object\" ) ) ; obj . setPicture1 ( new Media ( \"image1.jpg\" , \"title for image 1\" , \"description for image 1\" ) ) ; obj . setPicture2 ( new Media ( \"image2.jpg\" , \"title for image 2\" , \"description for image 2\" ) ) ; obj . setPicture3 ( new Media ( \"image3.jpg\" , \"title for image 3\" , \"description for image 3\" ) ) ; obj . setPicture4 ( new Media ( \"image4.jpg\" , \"title for image 4\" , \"description for image 4\" ) ) ; obj . setPicture5 ( new Media ( \"image5.jpg\" , \"title for image 5\" , \"description for image 5\" ) ) ; obj . setPicture6 ( new Media ( \"image6.jpg\" , \"title for image 6\" , \"description for image 6\" ) ) ; obj . setPicture7 ( new Media ( \"image7.jpg\" , \"title for image 7\" , \"description for image 7\" ) ) ; obj . setPicture8 ( new Media ( \"image8.jpg\" , \"title for image 8\" , \"description for image 8\" ) ) ; obj . setPicture9 ( new Media ( \"image9.jpg\" , \"title for image 9\" , \"description for image 9\" ) ) ; obj . setPicture10 ( new Media ( \"image10.jpg\" , \"title for image 10\" , \"description for image 10\" ) ) ; obj . setPicture11 ( new Media ( \"image11.jpg\" , \"title for image 11\" , \"description for image 11\" ) ) ; obj . setPicture12 ( new Media ( \"image12.jpg\" , \"title for image 12\" , \"description for image 12\" ) ) ; obj . setPicture13 ( new Media ( \"image13.jpg\" , \"title for image 13\" , \"description for image 13\" ) ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write some { @link IdxRecord } objects into a { @link File } . [CODESPLIT] protected static void write ( List < IdxRecord > records , File file ) { LOGGER . info ( \"writing document\" ) ; try ( IdxPrinter printer = IdxPrinter . create ( file ) ) { printer . printRecords ( records ) ; LOGGER . info ( \"> written to: \" + file . getAbsolutePath ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't write document into a file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the erschlAttr property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setErschlAttr ( ErschliessungUmfang . ErschlAttr value ) { this . erschlAttr = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the feature property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < String > getFeature ( ) { if ( feature == null ) { feature = new ArrayList < String > ( ) ; } return this . feature ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link CsvParser } from a { @link File } with CSV data . [CODESPLIT] @ SuppressFBWarnings ( value = \"OBL_UNSATISFIED_OBLIGATION\" , justification = \"The stream is closed later together with the parser.\" ) public final Parser parse ( File csvFile ) throws IOException { return this . parse ( new FileInputStream ( csvFile ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link CsvPrinter } that writes CSV data into a { @link File } . [CODESPLIT] @ SuppressFBWarnings ( value = \"OBL_UNSATISFIED_OBLIGATION\" , justification = \"The stream is closed later together with the printer.\" ) public final Printer print ( File csvFile ) throws IOException { return print ( new FileOutputStream ( csvFile ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print a { @link CsvRecord } followed by a record separator ( line break ) . [CODESPLIT] public void printRecord ( Record record ) throws IOException { for ( String value : record . print ( ) ) { this . print ( value ) ; } this . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print multiple { @link CsvRecord } objects . [CODESPLIT] public void printRecords ( Iterable < Record > records ) throws IOException { for ( Record record : records ) { this . printRecord ( record ) ; } this . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to replace line breaks in a string with a custom value before printing . <p > This method may be used by inheriting classes if the particular format does not support line breaks . [CODESPLIT] protected static String replaceLineBreaks ( String value , String lineBreak ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; if ( lineBreak == null ) lineBreak = \"<br/>\" ; Matcher m = LINES . matcher ( value ) ; StringBuilder out = new StringBuilder ( ) ; while ( m . find ( ) ) { out . append ( StringUtils . trimToEmpty ( m . group ( ) ) ) ; if ( ! m . hitEnd ( ) ) out . append ( lineBreak ) ; } return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ImmobiliareItDocument } from a { @link Document } . [CODESPLIT] public static ImmobiliareItDocument createDocument ( Document doc ) { if ( ImmobiliareItDocument . isReadable ( doc ) ) return new ImmobiliareItDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link TrovitDocument } from a { @link Document } . [CODESPLIT] public static TrovitDocument createDocument ( Document doc ) { if ( TrovitDocument . isReadable ( doc ) ) return new TrovitDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link AreaUnitValue } value from XML . [CODESPLIT] public static AreaUnitValue parseAreaUnitValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; final AreaUnitValue unit = AreaUnitValue . fromXmlValue ( value ) ; if ( unit != null ) return unit ; throw new IllegalArgumentException ( \"Can't parse foreclosure type value '\" + value + \"'!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link Boolean } value from XML . [CODESPLIT] public static Boolean parseBooleanValue ( String value ) { value = StringUtils . lowerCase ( StringUtils . trimToEmpty ( value ) , Locale . ENGLISH ) ; switch ( value ) { case \"true\" : case \"yes\" : case \"si\" : case \"1\" : return Boolean . TRUE ; case \"false\" : case \"no\" : case \"0\" : return Boolean . FALSE ; default : throw new IllegalArgumentException ( \"Can't parse boolean value '\" + value + \"'!\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link Calendar } value from XML . [CODESPLIT] public static Calendar parseDateValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; final String [ ] patterns = new String [ ] { \"dd/MM/yyyy\" , \"dd/MM/yyyy hh:mm:ss\" , \"dd-MM-yyyy\" , \"dd-MM-yyyy hh:mm:ss\" , \"yyyy/MM/dd\" , \"yyyy/MM/dd hh:mm:ss\" , \"yyyy-MM-dd\" , \"yyyy-MM-dd hh:mm:ss\" } ; try { Date date = DateUtils . parseDateStrictly ( value , Locale . ENGLISH , patterns ) ; Calendar cal = Calendar . getInstance ( Locale . getDefault ( ) ) ; cal . setTime ( date ) ; return cal ; } catch ( ParseException ex ) { throw new IllegalArgumentException ( \"Can't parse date value '\" + value + \"'!\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link ForeclosureTypeValue } value from XML . [CODESPLIT] public static ForeclosureTypeValue parseForeclosureTypeValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; final ForeclosureTypeValue foreclosure = ForeclosureTypeValue . fromXmlValue ( value ) ; if ( foreclosure != null ) return foreclosure ; throw new IllegalArgumentException ( \"Can't parse foreclosure type value '\" + value + \"'!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link OrientationValue } value from XML . [CODESPLIT] public static OrientationValue parseOrientationValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; final OrientationValue orientation = OrientationValue . fromXmlValue ( value ) ; if ( orientation != null ) return orientation ; throw new IllegalArgumentException ( \"Can't parse orientation value '\" + value + \"'!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link Currency } value from XML . [CODESPLIT] public static Currency parsePriceCurrencyValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; try { return Currency . getInstance ( value . toUpperCase ( ) ) ; } catch ( IllegalArgumentException ex ) { throw new IllegalArgumentException ( \"Can't parse price currency value '\" + value + \"'!\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link PricePeriodValue } value from XML . [CODESPLIT] public static PricePeriodValue parsePricePeriodValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; final PricePeriodValue period = PricePeriodValue . fromXmlValue ( value ) ; if ( period != null ) return period ; throw new IllegalArgumentException ( \"Can't parse price period value '\" + value + \"'!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link BigDecimal } value from XML for a price . [CODESPLIT] public static BigDecimal parsePriceValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; try { return DatatypeConverter . parseDecimal ( value ) ; } catch ( NumberFormatException ex ) { throw new IllegalArgumentException ( \"Can't parse price value '\" + value + \"'!\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link BigDecimal } value from XML for a number of rooms . [CODESPLIT] public static BigDecimal parseRoomsValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; final Matcher m = ROOMS_INTERVAL . matcher ( value ) ; if ( m . find ( ) ) { final int from = Integer . parseInt ( m . group ( 1 ) ) ; final int to = Integer . parseInt ( m . group ( 2 ) ) ; if ( ( to - from ) != - 1 ) { throw new IllegalArgumentException ( \"Can't parse rooms value '\" + value + \"' because of an invalid interval!\" ) ; } return DatatypeConverter . parseDecimal ( to + \".5\" ) ; } try { return DatatypeConverter . parseDecimal ( value ) ; } catch ( NumberFormatException ex ) { throw new IllegalArgumentException ( \"Can't parse rooms value '\" + value + \"'!\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link TypeValue } value from XML . [CODESPLIT] public static TypeValue parseTypeValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) return null ; final TypeValue type = TypeValue . fromXmlValue ( value ) ; if ( type != null ) return type ; throw new IllegalArgumentException ( \"Can't parse type value '\" + value + \"'!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link Boolean } value into XML output . [CODESPLIT] public static String printBooleanValue ( Boolean value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty boolean value!\" ) ; return DatatypeConverter . printBoolean ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link String } value for a description into XML output . <p > The description must contain at least 30 characters . [CODESPLIT] public static String printContentValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty content value!\" ) ; if ( value . length ( ) < 30 ) throw new IllegalArgumentException ( \"Can't print content value '\" + value + \"' because it is shorter than 30 characters!\" ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link String } value for a country code into XML output . <p > The country has to be represendet by a ISO - Code wirh two or three characters . [CODESPLIT] public static String printCountryValue ( String value ) { value = StringUtils . trimToNull ( value ) ; if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty country value!\" ) ; if ( value . length ( ) != 2 && value . length ( ) != 3 ) throw new IllegalArgumentException ( \"Can't print country value '\" + value + \"' because it is neither an ISO-2-Code nor an ISO-3-Code!\" ) ; return StringUtils . upperCase ( value , Locale . ENGLISH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link Calendar } value into XML output . [CODESPLIT] public static String printDateValue ( Calendar value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty date value!\" ) ; return new SimpleDateFormat ( \"dd-MM-yyyy hh:mm:ss\" , Locale . ENGLISH ) . format ( value . getTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link BigDecimal } value into XML output with a valid latitude range . [CODESPLIT] public static String printLatitudeValue ( BigDecimal value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty latitude value!\" ) ; if ( value . compareTo ( new BigDecimal ( \"-90\" ) ) < 0 ) throw new IllegalArgumentException ( \"Can't print latitude value '\" + value + \"' because it is below -90!\" ) ; if ( value . compareTo ( new BigDecimal ( \"90\" ) ) > 0 ) throw new IllegalArgumentException ( \"Can't print latitude value '\" + value + \"' because it is above 90!\" ) ; value = value . setScale ( 10 , BigDecimal . ROUND_HALF_UP ) ; return DatatypeConverter . printDecimal ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link BigInteger } value into XML output for a plot area . [CODESPLIT] public static String printPlotAreaValue ( BigInteger value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty plot area value!\" ) ; if ( value . compareTo ( BigInteger . ONE ) < 0 ) throw new IllegalArgumentException ( \"Can't print floor plot value '\" + value + \"' because it is below 1!\" ) ; if ( value . compareTo ( BigInteger . valueOf ( 1000000000L ) ) > 0 ) throw new IllegalArgumentException ( \"Can't print floor plot value '\" + value + \"' because it is above 1000000000!\" ) ; return DatatypeConverter . printInteger ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link BigDecimal } value into XML output for a price . [CODESPLIT] public static String printPriceValue ( BigDecimal value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty price value!\" ) ; if ( value . compareTo ( BigDecimal . ZERO ) < 0 ) throw new IllegalArgumentException ( \"Can't print price value '\" + value + \"' because it is below 0!\" ) ; if ( value . compareTo ( new BigDecimal ( \"1000000000\" ) ) > 0 ) throw new IllegalArgumentException ( \"Can't print price value '\" + value + \"' because it is above 1000000000!\" ) ; value = value . setScale ( 2 , BigDecimal . ROUND_HALF_UP ) ; return DatatypeConverter . printDecimal ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link BigDecimal } value into XML output for a room number . [CODESPLIT] public static String printRoomsValue ( BigDecimal value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty rooms value!\" ) ; if ( value . compareTo ( BigDecimal . ZERO ) < 0 ) throw new IllegalArgumentException ( \"Can't print rooms value '\" + value + \"' because it is below 0!\" ) ; if ( value . compareTo ( new BigDecimal ( \"20\" ) ) > 0 ) throw new IllegalArgumentException ( \"Can't print rooms value '\" + value + \"' because it is above 20!\" ) ; value = value . setScale ( 1 , BigDecimal . ROUND_HALF_UP ) ; //return DatatypeConverter.printDecimal( value ); final BigInteger integerPart = value . toBigInteger ( ) ; final BigInteger decimalPart = value . subtract ( new BigDecimal ( integerPart , 1 ) ) . multiply ( BigDecimal . TEN ) . toBigInteger ( ) ; if ( decimalPart . compareTo ( BigInteger . ZERO ) != 0 ) return integerPart . toString ( ) + \".5\" ; return DatatypeConverter . printInteger ( integerPart ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write an { @link URI } value into XML output . [CODESPLIT] public static String printUriValue ( URI value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty URI value!\" ) ; if ( \"http\" . equalsIgnoreCase ( value . getScheme ( ) ) ) return value . toString ( ) ; if ( \"https\" . equalsIgnoreCase ( value . getScheme ( ) ) ) return value . toString ( ) ; throw new IllegalArgumentException ( \"Can't print URI '\" + value + \"' because of an unsupported scheme!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link BigInteger } value into XML output for a year number . [CODESPLIT] public static String printYearValue ( BigInteger value ) { if ( value == null ) throw new IllegalArgumentException ( \"Can't print empty year value!\" ) ; if ( value . compareTo ( BigInteger . valueOf ( 1700L ) ) < 0 ) throw new IllegalArgumentException ( \"Can't print year value '\" + value + \"' because it is below 1700!\" ) ; if ( value . compareTo ( BigInteger . valueOf ( 9999L ) ) > 0 ) throw new IllegalArgumentException ( \"Can't print year value '\" + value + \"' because it is above 9999!\" ) ; return DatatypeConverter . printInteger ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the zimmertyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setZimmertyp ( Zimmer . Zimmertyp value ) { this . zimmertyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively remove any comments and unnecessary white spaces from a { @link Node } and its children . [CODESPLIT] public static void clean ( Node node ) { NodeList childNodes = node . getChildNodes ( ) ; for ( int n = childNodes . getLength ( ) - 1 ; n >= 0 ; n -- ) { Node child = childNodes . item ( n ) ; short nodeType = child . getNodeType ( ) ; if ( nodeType == Node . ELEMENT_NODE ) { XmlUtils . clean ( child ) ; } else if ( nodeType == Node . COMMENT_NODE ) { node . removeChild ( child ) ; } else if ( nodeType == Node . TEXT_NODE ) { String value = StringUtils . trimToNull ( child . getNodeValue ( ) ) ; if ( value == null ) node . removeChild ( child ) ; else child . setNodeValue ( value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the number of nodes that are matching against an XPath expression . [CODESPLIT] public static int countNodes ( String xpathExpression , Document doc ) throws JaxenException { return XmlUtils . countNodes ( xpathExpression , doc , doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Count the number of nodes that are matching against an XPath expression . [CODESPLIT] public static int countNodes ( String xpathExpression , Document doc , Object context ) throws JaxenException { return XmlUtils . newXPath ( xpathExpression , doc ) . selectNodes ( context ) . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the root { @link Element } of a { @link Document } . [CODESPLIT] public static Element getRootElement ( Document doc ) { if ( doc == null ) return null ; NodeList children = doc . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node node = children . item ( i ) ; if ( node instanceof Element ) return ( Element ) node ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an empty { @link Document } . [CODESPLIT] public static Document newDocument ( boolean namespaceAware ) throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( namespaceAware ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . newDocument ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from a XML string . [CODESPLIT] public static Document newDocument ( String xmlString ) throws SAXException , IOException , ParserConfigurationException { return XmlUtils . newDocument ( xmlString , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from a XML string . [CODESPLIT] public static Document newDocument ( String xmlString , boolean namespaceAware ) throws SAXException , IOException , ParserConfigurationException { return XmlUtils . newDocument ( new InputSource ( new StringReader ( xmlString ) ) , namespaceAware ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from an { @link InputSource } . [CODESPLIT] public static Document newDocument ( InputSource xmlSource ) throws SAXException , IOException , ParserConfigurationException { return XmlUtils . newDocument ( xmlSource , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from an { @link InputSource } . [CODESPLIT] public static Document newDocument ( InputSource xmlSource , boolean namespaceAware ) throws SAXException , IOException , ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( namespaceAware ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( xmlSource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from an { @link InputStream } . [CODESPLIT] public static Document newDocument ( InputStream xmlStream ) throws SAXException , IOException , ParserConfigurationException { return XmlUtils . newDocument ( xmlStream , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from an { @link InputStream } . [CODESPLIT] public static Document newDocument ( InputStream xmlStream , boolean namespaceAware ) throws SAXException , IOException , ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( namespaceAware ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( xmlStream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from a { @link File } . [CODESPLIT] public static Document newDocument ( File xmlFile ) throws SAXException , IOException , ParserConfigurationException { return XmlUtils . newDocument ( xmlFile , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Document } from a { @link File } . [CODESPLIT] public static Document newDocument ( File xmlFile , boolean namespaceAware ) throws SAXException , IOException , ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( namespaceAware ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( xmlFile ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link XPath } expression . [CODESPLIT] public static XPath newXPath ( String expression ) throws JaxenException { return XmlUtils . newXPath ( expression , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link XPath } expression . [CODESPLIT] public static XPath newXPath ( String expression , Document doc ) throws JaxenException { return XmlUtils . newXPath ( expression , doc , \"io\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link XPath } expression . [CODESPLIT] public static XPath newXPath ( String expression , Document doc , String namespacePrefix ) throws JaxenException { DOMXPath xpath = new DOMXPath ( expression ) ; //LOGGER.debug( \"new xpath: \" + xpath.debug() ); if ( doc != null && namespacePrefix != null ) { Element root = XmlUtils . getRootElement ( doc ) ; String uri = StringUtils . trimToEmpty ( root . getNamespaceURI ( ) ) ; xpath . addNamespace ( namespacePrefix , uri ) ; } return xpath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print nodes of a { @link Document } recursively to the local logger . [CODESPLIT] public static void printNodes ( Document doc ) { NodeList children = doc . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node node = children . item ( i ) ; if ( node instanceof Element ) printNode ( ( Element ) node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the namespace of any { @link Element } in a { @link Document } . [CODESPLIT] public static void replaceNamespace ( Document doc , String newNamespaceURI ) { NodeList children = doc . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { XmlUtils . replaceNamespace ( doc , children . item ( i ) , newNamespaceURI ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the namespace of a { @link Node } and its children . [CODESPLIT] public static void replaceNamespace ( Document doc , Node node , String newNamespaceURI ) { if ( node instanceof Attr ) { doc . renameNode ( node , newNamespaceURI , node . getLocalName ( ) ) ; } else if ( node instanceof Element ) { doc . renameNode ( node , newNamespaceURI , node . getLocalName ( ) ) ; NodeList children = node . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { XmlUtils . replaceNamespace ( doc , children . item ( i ) , newNamespaceURI ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all text values of a { @link Document } with CDATA values . [CODESPLIT] public static void replaceTextWithCData ( Document doc ) { NodeList children = doc . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { XmlUtils . replaceTextWithCData ( doc , children . item ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace all text values of a { @link Node } with CDATA values . [CODESPLIT] public static void replaceTextWithCData ( Document doc , Node node ) { if ( node instanceof Text ) { Text text = ( Text ) node ; CDATASection cdata = doc . createCDATASection ( text . getTextContent ( ) ) ; Element parent = ( Element ) text . getParentNode ( ) ; parent . replaceChild ( cdata , text ) ; } else if ( node instanceof Element ) { //LOGGER.debug( \"ELEMENT \" + element.getTagName() ); NodeList children = node . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { //LOGGER.debug( \"> \" + children.item( i ).getClass().getName() ); XmlUtils . replaceTextWithCData ( doc , children . item ( i ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link Document } to a { @link File } . [CODESPLIT] public static void write ( Document doc , File file ) throws TransformerException , IOException { XmlUtils . write ( doc , file , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link Document } to a { @link File } . [CODESPLIT] public static void write ( Document doc , File file , boolean prettyPrint ) throws TransformerException , IOException { try ( OutputStream output = new FileOutputStream ( file ) ) { XmlUtils . write ( doc , output , prettyPrint ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link Document } to an { @link OutputStream } . [CODESPLIT] public static void write ( Document doc , OutputStream output ) throws TransformerException { XmlUtils . write ( doc , output , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link Document } to a { @link Writer } . [CODESPLIT] public static void write ( Document doc , Writer output ) throws TransformerException { XmlUtils . write ( doc , output , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link Document } to a { @link Writer } . [CODESPLIT] public static void write ( Document doc , Writer output , boolean prettyPrint ) throws TransformerException { XmlUtils . clean ( doc ) ; Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , \"no\" ) ; transformer . setOutputProperty ( OutputKeys . METHOD , \"xml\" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , \"UTF-8\" ) ; transformer . setOutputProperty ( OutputKeys . STANDALONE , \"yes\" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , ( prettyPrint ) ? \"yes\" : \"no\" ) ; if ( prettyPrint ) { transformer . setOutputProperty ( \"{http://xml.apache.org/xslt}indent-amount\" , \"2\" ) ; } transformer . transform ( new DOMSource ( doc ) , new StreamResult ( output ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate XML for the contained { @link Document } . [CODESPLIT] public void toXml ( File xmlFile , boolean prettyPrint ) throws TransformerException , IOException { if ( this . isTextWrittenAsCDATA ( ) ) { XmlUtils . replaceTextWithCData ( this . getDocument ( ) ) ; } prepareDocumentBeforeWritingToXml ( this . getDocument ( ) ) ; XmlUtils . write ( this . getDocument ( ) , xmlFile , prettyPrint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate XML for the contained { @link Document } . [CODESPLIT] public void toXml ( OutputStream output , boolean prettyPrint ) throws TransformerException , IOException { if ( this . isTextWrittenAsCDATA ( ) ) { XmlUtils . replaceTextWithCData ( this . getDocument ( ) ) ; } prepareDocumentBeforeWritingToXml ( this . getDocument ( ) ) ; XmlUtils . write ( this . getDocument ( ) , output , prettyPrint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns XML for the contained { @link Document } . [CODESPLIT] public final String toXmlString ( boolean prettyPrint ) throws TransformerException , IOException { try ( StringWriter w = new StringWriter ( ) ) { this . toXml ( w , prettyPrint ) ; return w . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link WisItDocument } from a { @link Document } . [CODESPLIT] public static WisItDocument createDocument ( Document doc ) { if ( WisItDocument . isReadable ( doc ) ) return new WisItDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 5 to 1 . 2 . 4 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_4 ) ; // downgrade a feedback document if ( doc instanceof OpenImmoFeedbackDocument ) { try { this . removeFeedbackObjektChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <objekt> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } // downgrade a transfer document else if ( doc instanceof OpenImmoTransferDocument ) { try { this . removeKontaktpersonChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <kontaktperson> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeMwstGesamtElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <mwst_gesamt> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeVerkehrswertElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <verkehrswert> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeAnzahlLogiaElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <anzahl_logia> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeErschliessungUmfangElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <erschliessung_umfang> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeVerwaltungTechnChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <verwaltung_techn> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeZustandElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <zustand> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBebaubarNachElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <bebaubar_nach> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeErschliessungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <erschliessung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeWohnungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <wohnung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeHausElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <haus> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade an OpenImmo document from version 1 . 2 . 4 to 1 . 2 . 5 . [CODESPLIT] @ Override @ SuppressWarnings ( \"Duplicates\" ) public void upgradeFromPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_5 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . upgradeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; energiepass&gt ; elements to OpenImmo 1 . 2 . 4 . <p > The child elements &lt ; hwbwert&gt ; &lt ; hwbklasse&gt ; &lt ; fgeewert&gt ; &lt ; fgeeklasse&gt ; are copied into separate &lt ; user_defined_simplefield&gt ; elements as it was suggested by OpenImmo e . V .. [CODESPLIT] protected void downgradeEnergiepassElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; boolean hwbwertPassed = false ; boolean hwbklassePassed = false ; boolean fgeewertPassed = false ; boolean fgeeklassePassed = false ; List childNodes ; // create a <user_defined_simplefield> for <hwbwert> elements childNodes = XmlUtils . newXPath ( \"io:hwbwert\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! hwbwertPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_hwbwert\" , value ) ) ; hwbwertPassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <hwbklasse> elements childNodes = XmlUtils . newXPath ( \"io:hwbklasse\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! hwbklassePassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_hwbklasse\" , value ) ) ; hwbklassePassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <fgeewert> elements childNodes = XmlUtils . newXPath ( \"io:fgeewert\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! fgeewertPassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_fgeewert\" , value ) ) ; fgeewertPassed = true ; } } node . removeChild ( childNode ) ; } // create a <user_defined_simplefield> for <baujahr> elements childNodes = XmlUtils . newXPath ( \"io:fgeeklasse\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! fgeeklassePassed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { parentNode . appendChild ( OpenImmoUtils . createUserDefinedSimplefield ( doc , \"epass_fgeeklasse\" , value ) ) ; fgeeklassePassed = true ; } } node . removeChild ( childNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; energiepass&gt ; elements to OpenImmo 1 . 2 . 5 . <p > The &lt ; user_defined_simplefield&gt ; elements for Austria that were suggested by OpenImmo e . V . are explicitly supported in OpenImmo 1 . 2 . 5 as child elements of &lt ; energiepass&gt ; . Any matching &lt ; user_defined_simplefield&gt ; elements are moved into the &lt ; energiepass&gt ; element . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected void upgradeEnergiepassElements ( Document doc ) throws JaxenException { Map < String , String > fields = new HashMap <> ( ) ; fields . put ( \"hwbwert\" , \"user_defined_simplefield[@feldname='epass_hwbwert']\" ) ; fields . put ( \"hwbklasse\" , \"user_defined_simplefield[@feldname='epass_hwbklasse']\" ) ; fields . put ( \"fgeewert\" , \"user_defined_simplefield[@feldname='epass_fgeewert']\" ) ; fields . put ( \"fgeeklasse\" , \"user_defined_simplefield[@feldname='epass_fgeeklasse']\" ) ; List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element energiepassNode = ( Element ) XmlUtils . newXPath ( \"io:energiepass\" , doc ) . selectSingleNode ( node ) ; if ( energiepassNode == null ) { energiepassNode = doc . createElementNS ( StringUtils . EMPTY , \"energiepass\" ) ; } for ( Map . Entry < String , String > entry : fields . entrySet ( ) ) { boolean fieldProcessed = false ; List childNodes = XmlUtils . newXPath ( entry . getValue ( ) , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( ! fieldProcessed ) { String value = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( value != null ) { Element newElement = doc . createElementNS ( StringUtils . EMPTY , entry . getKey ( ) ) ; newElement . setTextContent ( value ) ; energiepassNode . appendChild ( newElement ) ; fieldProcessed = true ; } } node . removeChild ( childNode ) ; } } if ( energiepassNode . getParentNode ( ) == null && energiepassNode . hasChildNodes ( ) ) { node . appendChild ( energiepassNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the keineAngabe property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setKeineAngabe ( JAXBElement < Object > value ) { this . keineAngabe = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the erdwaerme property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setErdwaerme ( JAXBElement < Object > value ) { this . erdwaerme = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the solarheizung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setSolarheizung ( JAXBElement < Object > value ) { this . solarheizung = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the pelletheizung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPelletheizung ( JAXBElement < Object > value ) { this . pelletheizung = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the gas property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGas ( JAXBElement < Object > value ) { this . gas = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the oel property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setOel ( JAXBElement < Object > value ) { this . oel = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the fernwaerme property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setFernwaerme ( JAXBElement < Object > value ) { this . fernwaerme = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the strom property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setStrom ( JAXBElement < Object > value ) { this . strom = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the kohle property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setKohle ( JAXBElement < Object > value ) { this . kohle = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( ImmobiliareItWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a Feed object with some example data // this object corresponds to the <feed> root element in XML Feed feed = FACTORY . createFeed ( ) ; // append some example objects to the Feed object feed . setProperties ( FACTORY . createFeedProperties ( ) ) ; feed . getProperties ( ) . getProperty ( ) . add ( createProperty ( ) ) ; feed . getProperties ( ) . getProperty ( ) . add ( createProperty ( ) ) ; // convert the Feed object into a XML document ImmobiliareItDocument doc = null ; try { doc = ImmobiliareItDocument . newDocument ( feed ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Property } with some example data . [CODESPLIT] protected static Property createProperty ( ) { // create an example real estate for rent Property obj = FACTORY . createFeedPropertiesProperty ( ) ; obj . setBuildingStatus ( Status . ABITABILE ) ; obj . setCategory ( Category . COMMERCIALE ) ; obj . setDateExpiration ( Calendar . getInstance ( ) ) ; obj . setDateUpdated ( Calendar . getInstance ( ) ) ; obj . setOperation ( Operation . WRITE ) ; obj . setUniqueId ( RandomStringUtils . random ( 5 ) ) ; obj . setAgent ( FACTORY . createFeedPropertiesPropertyAgent ( ) ) ; obj . getAgent ( ) . setEmail ( \"agency@test.org\" ) ; obj . getAgent ( ) . setOfficeName ( \"agency name\" ) ; obj . setBlueprints ( FACTORY . createFeedPropertiesPropertyBlueprints ( ) ) ; obj . getBlueprints ( ) . getBlueprint ( ) . add ( createPictureExtended ( ) ) ; obj . getBlueprints ( ) . getBlueprint ( ) . add ( createPictureExtended ( ) ) ; obj . getBlueprints ( ) . getBlueprint ( ) . add ( createPictureExtended ( ) ) ; obj . setBuilding ( FACTORY . createBuilding ( ) ) ; obj . getBuilding ( ) . setCategory ( Category . COMMERCIALE ) ; obj . getBuilding ( ) . setClazz ( Clazz . SIGNORILE ) ; obj . getBuilding ( ) . setDetail ( PropertyTypeBusiness . ALBERGO ) ; obj . getBuilding ( ) . setStatus ( Status . DISCRETO ) ; obj . getBuilding ( ) . setType ( PropertyType . APPARTAMENTO ) ; obj . setExtraFeatures ( FACTORY . createFeedPropertiesPropertyExtraFeatures ( ) ) ; obj . getExtraFeatures ( ) . setAirConditioning ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getExtraFeatures ( ) . setBalcony ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getExtraFeatures ( ) . setBathrooms ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 5 ) ) ) ; obj . getExtraFeatures ( ) . setBeamHeight ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 10 ) ) ) ; obj . getExtraFeatures ( ) . setBedrooms ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 5 ) ) ) ; obj . getExtraFeatures ( ) . setBuildYear ( RandomUtils . nextInt ( 1900 , 2000 ) ) ; obj . getExtraFeatures ( ) . setDocDescription ( \"some descriptions\" ) ; obj . getExtraFeatures ( ) . setDocSpecification ( \"some specifications\" ) ; obj . getExtraFeatures ( ) . setElevator ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getExtraFeatures ( ) . setFloorplannerUrl ( \"http://floorplanner-url.it/\" ) ; obj . getExtraFeatures ( ) . setFreeConditions ( \"free conditions\" ) ; obj . getExtraFeatures ( ) . setFurniture ( Furniture . PARZIALMENTE_ARREDATO ) ; obj . getExtraFeatures ( ) . setGarden ( Garden . NESSUNO ) ; obj . getExtraFeatures ( ) . setHeating ( Heat . AUTONOMO ) ; obj . getExtraFeatures ( ) . setKitchen ( Kitchen . SEMI_ABITABILE ) ; obj . getExtraFeatures ( ) . setNet ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getExtraFeatures ( ) . setNumFloors ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 5 ) ) ) ; obj . getExtraFeatures ( ) . setOverheadCrane ( YesNoReady . READY ) ; obj . getExtraFeatures ( ) . setReception ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getExtraFeatures ( ) . setRentContract ( Rental . LIBERO ) ; obj . getExtraFeatures ( ) . setSecurityAlarm ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getExtraFeatures ( ) . setTerrace ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getExtraFeatures ( ) . setVirtualTour ( \"virtual tour\" ) ; obj . getExtraFeatures ( ) . setAdditionalCosts ( FACTORY . createAdditionalCostsType ( ) ) ; obj . getExtraFeatures ( ) . getAdditionalCosts ( ) . setCurrency ( Currency . getInstance ( \"EUR\" ) ) ; obj . getExtraFeatures ( ) . getAdditionalCosts ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextLong ( 0 , 5000 ) ) ) ; obj . getExtraFeatures ( ) . setExternalArea ( FACTORY . createLandSizeType ( ) ) ; obj . getExtraFeatures ( ) . getExternalArea ( ) . setUnit ( LandSizeUnit . M2 ) ; obj . getExtraFeatures ( ) . getExternalArea ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextLong ( 50 , 5000 ) ) ) ; obj . getExtraFeatures ( ) . setFloor ( FACTORY . createFloor ( ) ) ; obj . getExtraFeatures ( ) . getFloor ( ) . setType ( Floor . FloorType . INTERMEDIO ) ; obj . getExtraFeatures ( ) . getFloor ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextLong ( 0 , 10 ) ) ) ; obj . getExtraFeatures ( ) . setGarage ( FACTORY . createBox ( ) ) ; obj . getExtraFeatures ( ) . getGarage ( ) . setType ( Box . BoxType . POSTO_AUTO ) ; obj . getExtraFeatures ( ) . getGarage ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextLong ( 0 , 10 ) ) ) ; obj . getExtraFeatures ( ) . setOfficeSize ( FACTORY . createSizeType ( ) ) ; obj . getExtraFeatures ( ) . getOfficeSize ( ) . setUnit ( SizeUnit . M2 ) ; obj . getExtraFeatures ( ) . getOfficeSize ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextLong ( 5 , 50 ) ) ) ; obj . setFeatures ( FACTORY . createFeedPropertiesPropertyFeatures ( ) ) ; obj . getFeatures ( ) . setEnergyClass ( ClassEnergy . D ) ; obj . getFeatures ( ) . setRooms ( RandomUtils . nextInt ( 1 , 5 ) ) ; obj . getFeatures ( ) . setEnergyPerformance ( FACTORY . createClassEnergyPerformance ( ) ) ; obj . getFeatures ( ) . getEnergyPerformance ( ) . setCertified ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getFeatures ( ) . getEnergyPerformance ( ) . setUnit ( EnergyUnit . KWH_M2ANNO ) ; obj . getFeatures ( ) . getEnergyPerformance ( ) . setValue ( \"energy performance\" ) ; obj . getFeatures ( ) . setPrice ( FACTORY . createPriceType ( ) ) ; obj . getFeatures ( ) . getPrice ( ) . setCurrency ( Currency . getInstance ( \"EUR\" ) ) ; obj . getFeatures ( ) . getPrice ( ) . setReserved ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getFeatures ( ) . getPrice ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextLong ( 500 , 5000000 ) ) ) ; obj . getFeatures ( ) . setSize ( FACTORY . createSizeType ( ) ) ; obj . getFeatures ( ) . getSize ( ) . setUnit ( SizeUnit . M2 ) ; obj . getFeatures ( ) . getSize ( ) . setValue ( BigInteger . valueOf ( RandomUtils . nextLong ( 50 , 5000 ) ) ) ; obj . setLocation ( FACTORY . createLocationStructure ( ) ) ; obj . getLocation ( ) . setAdministrativeArea ( \"administrative area\" ) ; obj . getLocation ( ) . setCountryCode ( \"DE\" ) ; obj . getLocation ( ) . setCity ( FACTORY . createLocationStructureCity ( ) ) ; obj . getLocation ( ) . getCity ( ) . setCode ( BigInteger . ZERO ) ; obj . getLocation ( ) . getCity ( ) . setValue ( \"Berlin\" ) ; obj . getLocation ( ) . setLocality ( FACTORY . createLocationStructureLocality ( ) ) ; obj . getLocation ( ) . getLocality ( ) . setLatitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . getLocation ( ) . getLocality ( ) . setLongitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . getLocation ( ) . getLocality ( ) . setPostalCode ( \"13125\" ) ; obj . getLocation ( ) . getLocality ( ) . setNeighbourhood ( FACTORY . createLocationStructureLocalityNeighbourhood ( ) ) ; obj . getLocation ( ) . getLocality ( ) . getNeighbourhood ( ) . setId ( BigInteger . ZERO ) ; obj . getLocation ( ) . getLocality ( ) . getNeighbourhood ( ) . setType ( LocationNeighbourhoodType . DISTRICT ) ; obj . getLocation ( ) . getLocality ( ) . getNeighbourhood ( ) . setValue ( \"about the neighbourhood\" ) ; obj . getLocation ( ) . getLocality ( ) . setThoroughfare ( FACTORY . createLocationStructureLocalityThoroughfare ( ) ) ; obj . getLocation ( ) . getLocality ( ) . getThoroughfare ( ) . setDisplay ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getLocation ( ) . getLocality ( ) . getThoroughfare ( ) . setValue ( \"about thoroughfare\" ) ; obj . getLocation ( ) . setSubAdministrativeArea ( FACTORY . createLocationStructureSubAdministrativeArea ( ) ) ; obj . getLocation ( ) . getSubAdministrativeArea ( ) . setCode ( RandomStringUtils . random ( 5 ) ) ; obj . getLocation ( ) . getSubAdministrativeArea ( ) . setValue ( \"Berlin\" ) ; obj . setPictures ( FACTORY . createFeedPropertiesPropertyPictures ( ) ) ; obj . getPictures ( ) . getPictureUrlAndPicture ( ) . add ( createPicture ( ) ) ; obj . getPictures ( ) . getPictureUrlAndPicture ( ) . add ( createPicture ( ) ) ; obj . getPictures ( ) . getPictureUrlAndPicture ( ) . add ( createPicture ( ) ) ; obj . setPropertyType ( FACTORY . createProptype ( ) ) ; obj . getPropertyType ( ) . setBusinessType ( FACTORY . createBusinessElement ( ) ) ; obj . getPropertyType ( ) . getBusinessType ( ) . setCategory ( BusinessElement . BusinessElementCategory . IMMOBILE ) ; obj . getPropertyType ( ) . getBusinessType ( ) . setValue ( PropertyTypeBusiness . ALTRO ) ; obj . getPropertyType ( ) . setTerrains ( FACTORY . createTerrains ( ) ) ; obj . getPropertyType ( ) . getTerrains ( ) . getTerrain ( ) . add ( TerrainType . SEMINATIVO ) ; obj . getPropertyType ( ) . setType ( PropertyTypeSimple . CASA_INDIPENDENTE ) ; obj . setTransactionType ( FACTORY . createTransactionType ( ) ) ; obj . getTransactionType ( ) . setAuction ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getTransactionType ( ) . setOwnership ( OwnershipType . PARZIALE ) ; obj . getTransactionType ( ) . setValue ( \"notes about transaction\" ) ; obj . setVideos ( FACTORY . createFeedPropertiesPropertyVideos ( ) ) ; obj . getVideos ( ) . getVideo ( ) . add ( createVideo ( ) ) ; obj . getVideos ( ) . getVideo ( ) . add ( createVideo ( ) ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link PictureProject } with some example data . [CODESPLIT] protected static PictureProject createPicture ( ) { PictureProject pic = FACTORY . createPictureProject ( ) ; pic . setPosition ( BigInteger . valueOf ( RandomUtils . nextLong ( 0 , 100 ) ) ) ; pic . setValue ( \"image-\" + RandomUtils . nextInt ( 0 , 999 ) + \".jpg\" ) ; return pic ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link PictureExtended } with some example data . [CODESPLIT] protected static PictureExtended createPictureExtended ( ) { PictureExtended pic = FACTORY . createPictureExtended ( ) ; pic . setPosition ( BigInteger . valueOf ( RandomUtils . nextLong ( 0 , 100 ) ) ) ; pic . setValue ( \"image-\" + RandomUtils . nextInt ( 0 , 999 ) + \".jpg\" ) ; pic . setUrl ( \"http://mywebsite.org/\" + pic . getValue ( ) ) ; return pic ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link VideoProject } with some example data . [CODESPLIT] protected static VideoProject createVideo ( ) { VideoProject video = FACTORY . createVideoProject ( ) ; video . setType ( VideoType . LOCAL ) ; video . setValue ( \"video-\" + RandomUtils . nextInt ( 0 , 999 ) + \".mp4\" ) ; return video ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a random string with ASCII letters and digits . [CODESPLIT] public static String random ( int length ) { return new RandomStringGenerator . Builder ( ) . filteredBy ( NUMBERS , LETTERS ) . build ( ) . generate ( length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a random string with ASCII letters . [CODESPLIT] public static String randomLetters ( int length ) { return new RandomStringGenerator . Builder ( ) . filteredBy ( LETTERS ) . build ( ) . generate ( length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a random string with ASCII digits . [CODESPLIT] public static String randomNumeric ( int length ) { return new RandomStringGenerator . Builder ( ) . filteredBy ( NUMBERS ) . build ( ) . generate ( length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the wohnungKategorie property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public WohnungKategorienTyp getWohnungKategorie ( ) { if ( wohnungKategorie == null ) { return WohnungKategorienTyp . KEINE_ANGABE ; } else { return wohnungKategorie ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the benutzer property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:55:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setBENUTZER ( WIS . BENUTZER value ) { this . benutzer = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the objekte property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:55:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setOBJEKTE ( WIS . OBJEKTE value ) { this . objekte = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the feed property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Feedindex . Feed > getFeed ( ) { if ( feed == null ) { feed = new ArrayList < Feedindex . Feed > ( ) ; } return this . feed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the moeb property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMoeb ( Moebliert . Moeb value ) { this . moeb = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the serviceleistungen property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Serviceleistungen > getServiceleistungen ( ) { if ( serviceleistungen == null ) { serviceleistungen = new ArrayList < Serviceleistungen > ( ) ; } return this . serviceleistungen ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Is24XmlDocument } from a { @link ImmobilienTransferTyp } object . [CODESPLIT] public static Is24XmlDocument newDocument ( ImmobilienTransferTyp transfer ) throws ParserConfigurationException , JAXBException { return newDocument ( Is24XmlUtils . getFactory ( ) . createIS24ImmobilienTransfer ( transfer ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Is24XmlDocument } from a { @link ImmobilienTransferTyp } object . [CODESPLIT] public static Is24XmlDocument newDocument ( IS24ImmobilienTransfer transfer ) throws ParserConfigurationException , JAXBException { Document document = XmlUtils . newDocument ( ) ; Is24XmlUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( transfer , document ) ; return new Is24XmlDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ImmobilienTransferTyp } object from the contained { @link Document } . [CODESPLIT] @ Override public ImmobilienTransferTyp toObject ( ) throws JAXBException { return ( ( IS24ImmobilienTransfer ) Is24XmlUtils . createUnmarshaller ( ) . unmarshal ( this . getDocument ( ) ) ) . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the subAdministrativeArea property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setSubAdministrativeArea ( LocationStructure . SubAdministrativeArea value ) { this . subAdministrativeArea = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the city property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setCity ( LocationStructure . City value ) { this . city = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the locality property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setLocality ( LocationStructure . Locality value ) { this . locality = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 1 to 1 . 2 . 0 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_0 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . removeObjektartZusatzElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <objektart_zusatz> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeHausElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <haus> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } try { this . downgradeXmlNamespace ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade the XML namespace!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade an OpenImmo document from version 1 . 2 . 0 to 1 . 2 . 1 . [CODESPLIT] @ Override @ SuppressWarnings ( \"Duplicates\" ) public void upgradeFromPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_1 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . upgradeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } try { this . upgradeXmlNamespace ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade the XML namespace!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; energiepass&gt ; elements to OpenImmo 1 . 2 . 0 . <p > The &lt ; mitwarmwasser&gt ; child element of the &lt ; energiepass&gt ; element is not available in version 1 . 2 . 0 . <p > The &lt ; energieverbrauchkennwert&gt ; &lt ; endenergiebedarf&gt ; child elements of the &lt ; energiepass&gt ; element are moved into &lt ; energiebedarf&gt ; and &lt ; skala&gt ; in version 1 . 2 . 0 . [CODESPLIT] protected void downgradeEnergiepassElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element parentNode = ( Element ) item ; boolean skalaProcessed = false ; String artValue = XmlUtils . newXPath ( \"io:art/text()\" , doc ) . stringValueOf ( parentNode ) ; List childNodes = XmlUtils . newXPath ( \"io:mitwarmwasser\" , doc ) . selectNodes ( parentNode ) ; for ( Object child : childNodes ) { Node childNode = ( Node ) child ; childNode . getParentNode ( ) . removeChild ( childNode ) ; } childNodes = XmlUtils . newXPath ( \"io:energieverbrauchkennwert\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; String childValue = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( ! skalaProcessed && \"VERBRAUCH\" . equalsIgnoreCase ( artValue ) && childValue != null ) { skalaProcessed = true ; Element skalaNode = doc . createElementNS ( OpenImmoUtils . OLD_NAMESPACE , \"skala\" ) ; skalaNode . setAttribute ( \"type\" , \"ZAHL\" ) ; skalaNode . setTextContent ( childValue ) ; parentNode . appendChild ( skalaNode ) ; } childNode . getParentNode ( ) . removeChild ( childNode ) ; } childNodes = XmlUtils . newXPath ( \"io:endenergiebedarf\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; String childValue = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; if ( ! skalaProcessed && \"BEDARF\" . equalsIgnoreCase ( artValue ) && childValue != null ) { skalaProcessed = true ; Element skalaNode = doc . createElementNS ( OpenImmoUtils . OLD_NAMESPACE , \"skala\" ) ; skalaNode . setAttribute ( \"type\" , \"ZAHL\" ) ; skalaNode . setTextContent ( childValue ) ; parentNode . appendChild ( skalaNode ) ; Element newNode = doc . createElementNS ( OpenImmoUtils . OLD_NAMESPACE , \"energiebedarf\" ) ; newNode . setTextContent ( childValue ) ; parentNode . appendChild ( newNode ) ; } childNode . getParentNode ( ) . removeChild ( childNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; energiepass&gt ; elements to OpenImmo 1 . 2 . 1 . <p > Make sure that a valid value for &lt ; art&gt ; is used . <p > Remove unsupported &lt ; heizwert&gt ; element . <p > Replace &lt ; energiebedarf&gt ; &lt ; skala&gt ; with &lt ; energieverbrauchkennwert&gt ; or &lt ; endenergiebedarf&gt ; according to the provided &lt ; art&gt ; . [CODESPLIT] protected void upgradeEnergiepassElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element parentNode = ( Element ) item ; String energiebedarfValue = null ; String skalaValue = null ; Element artNode = ( Element ) XmlUtils . newXPath ( \"io:art\" , doc ) . selectSingleNode ( parentNode ) ; String artValue = ( artNode != null ) ? StringUtils . trimToNull ( artNode . getTextContent ( ) ) : null ; List childNodes = XmlUtils . newXPath ( \"io:heizwert\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; childNode . getParentNode ( ) . removeChild ( childNode ) ; } childNodes = XmlUtils . newXPath ( \"io:energiebedarf\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Node childNode = ( Node ) childItem ; if ( energiebedarfValue == null ) energiebedarfValue = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; childNode . getParentNode ( ) . removeChild ( childNode ) ; } childNodes = XmlUtils . newXPath ( \"io:skala\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Element childNode = ( Element ) childItem ; if ( skalaValue == null && \"ZAHL\" . equalsIgnoreCase ( childNode . getAttribute ( \"type\" ) ) ) skalaValue = StringUtils . trimToNull ( childNode . getTextContent ( ) ) ; childNode . getParentNode ( ) . removeChild ( childNode ) ; } if ( artNode != null && \"VERBRAUCH\" . equalsIgnoreCase ( artValue ) ) { artNode . setTextContent ( \"VERBRAUCH\" ) ; String value = skalaValue ; if ( value != null ) { Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"energieverbrauchkennwert\" ) ; newNode . setTextContent ( value ) ; parentNode . appendChild ( newNode ) ; } } else if ( artNode != null && \"BEDARF\" . equalsIgnoreCase ( artValue ) ) { artNode . setTextContent ( \"BEDARF\" ) ; String value = ( energiebedarfValue != null ) ? energiebedarfValue : skalaValue ; if ( value != null ) { Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"endenergiebedarf\" ) ; newNode . setTextContent ( value ) ; parentNode . appendChild ( newNode ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the miete property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMiete ( VermarktungGewerbeTyp2 . Miete value ) { this . miete = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the kauf property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setKauf ( JAXBElement < Object > value ) { this . kauf = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the landTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setLandTyp ( LandUndForstwirtschaft . LandTyp value ) { this . landTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the field property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:42:33+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < MetaDataType . FIELD > getFIELD ( ) { if ( field == null ) { field = new ArrayList < MetaDataType . FIELD > ( ) ; } return this . field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( Is24XmlWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a ImmobilienTransferTyp object with some example data // this object corresponds to the <IS24ImmobilienTransfer> root element in XML ImmobilienTransferTyp transfer = FACTORY . createImmobilienTransferTyp ( ) ; transfer . setEmailBeiFehler ( \"test@test.org\" ) ; transfer . setErstellerSoftware ( \"OpenEstate-IO\" ) ; transfer . setErstellerSoftwareVersion ( \"1.4\" ) ; transfer . setAnbieter ( createAnbieter ( ) ) ; // convert the ImmobilienTransferTyp object into a XML document Is24XmlDocument doc = null ; try { doc = Is24XmlDocument . newDocument ( transfer ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Anbieter } with some example data . [CODESPLIT] protected static Anbieter createAnbieter ( ) { // create an example agency Anbieter anbieter = FACTORY . createImmobilienTransferTypAnbieter ( ) ; anbieter . setScoutKundenID ( \"123456\" ) ; // add some real estates to the agency anbieter . getImmobilie ( ) . add ( createImmobilieHausKauf ( ) ) ; anbieter . getImmobilie ( ) . add ( createImmobilieHausKauf ( ) ) ; anbieter . getImmobilie ( ) . add ( createImmobilieHausMiete ( ) ) ; anbieter . getImmobilie ( ) . add ( createImmobilieHausMiete ( ) ) ; return anbieter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link HausKauf } with some example data . [CODESPLIT] protected static HausKauf createImmobilieHausKauf ( ) { // create an example real estate HausKauf . Type obj = FACTORY . createHausKaufType ( ) ; initImmobilie ( obj ) ; obj . setAlsFerienwohnungGeeignet ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setAnzahlBadezimmer ( RandomUtils . nextLong ( 1 , 5 ) ) ; obj . setAnzahlGaragenStellplaetze ( RandomUtils . nextLong ( 0 , 3 ) ) ; obj . setAnzahlSchlafzimmer ( RandomUtils . nextLong ( 1 , 5 ) ) ; obj . setAusstattungsqualitaet ( AusstattungsqualitaetsTyp . LUXUS ) ; obj . setBarrierefrei ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBaujahr ( RandomUtils . nextLong ( 1900 , 2010 ) ) ; obj . setBauphase ( BauphaseTyp . HAUS_FERTIG_GESTELLT ) ; obj . setDenkmalschutzobjekt ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEtagenzahl ( RandomUtils . nextLong ( 1 , 10 ) ) ; obj . setFreiAb ( \"notes about availability\" ) ; obj . setGaesteWC ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGrundstuecksFlaeche ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100 , 1500 ) ) ) ; obj . setHausKategorie ( HausKategorienTyp . MEHRFAMILIENHAUS ) ; obj . setHeizungsart ( HeizungsartTyp . ETAGENHEIZUNG ) ; obj . setJahrLetzteModernisierung ( RandomUtils . nextLong ( 1980 , 2000 ) ) ; obj . setKeller ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setMitEinliegerwohnung ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setNutzflaeche ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100 , 1000 ) ) ) ; obj . setObjektzustand ( ObjektZustandTyp . NEUWERTIG ) ; obj . setParkplatz ( StellplatzKategorieTyp . TIEFGARAGE ) ; obj . setRollstuhlgerecht ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setVermietet ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setWohnflaeche ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 50 , 500 ) ) ) ; obj . setZimmer ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1 , 10 ) ) ) ; obj . setBefeuerungsArt ( FACTORY . createBefeuerungsArtTyp ( ) ) ; obj . getBefeuerungsArt ( ) . setOel ( FACTORY . createBefeuerungsArtTypOel ( Boolean . TRUE ) ) ; obj . getBefeuerungsArt ( ) . setGas ( FACTORY . createBefeuerungsArtTypGas ( Boolean . TRUE ) ) ; obj . setEnergieausweis ( FACTORY . createEnergieausweisTyp ( ) ) ; obj . getEnergieausweis ( ) . setEnergieausweistyp ( EnergieausweistypTyp . ENERGIEVERBRAUCHSKENNWERT ) ; obj . getEnergieausweis ( ) . setEnergieverbrauchskennwert ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 50 , 500 ) ) ) ; obj . getEnergieausweis ( ) . setWarmwasserEnthalten ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setKaufpreise ( FACTORY . createVermarktungWohnKaufTyp ( ) ) ; obj . getKaufpreise ( ) . setKaufpreis ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100000 , 9999999 ) ) ) ; obj . getKaufpreise ( ) . setMieteinnahmenProMonat ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 5000 , 50000 ) ) ) ; obj . getKaufpreise ( ) . setStellplatzKaufpreis ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1000 , 10000 ) ) ) ; obj . getKaufpreise ( ) . setWohngeld ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 500 , 5000 ) ) ) ; return FACTORY . createHausKauf ( obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link HausMiete } with some example data . [CODESPLIT] protected static HausMiete createImmobilieHausMiete ( ) { // create an example real estate HausMiete . Type obj = FACTORY . createHausMieteType ( ) ; initImmobilie ( obj ) ; obj . setAnzahlBadezimmer ( RandomUtils . nextLong ( 1 , 5 ) ) ; obj . setAnzahlGaragenStellplaetze ( RandomUtils . nextLong ( 0 , 3 ) ) ; obj . setAnzahlSchlafzimmer ( RandomUtils . nextLong ( 1 , 5 ) ) ; obj . setAusstattungsqualitaet ( AusstattungsqualitaetsTyp . GEHOBEN ) ; obj . setBarrierefrei ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setBaujahr ( RandomUtils . nextLong ( 1900 , 2010 ) ) ; obj . setBetreutesWohnen ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEinbaukueche ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setEtagenzahl ( RandomUtils . nextLong ( 1 , 10 ) ) ; obj . setFreiAb ( \"notes about availability\" ) ; obj . setGaesteWC ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setGrundstuecksFlaeche ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100 , 1500 ) ) ) ; obj . setHausKategorie ( HausKategorienTyp . EINFAMILIENHAUS ) ; obj . setHaustiere ( GenehmigungTyp . NACH_VEREINBARUNG ) ; obj . setHeizungsart ( HeizungsartTyp . ZENTRALHEIZUNG ) ; obj . setJahrLetzteModernisierung ( RandomUtils . nextLong ( 1980 , 2000 ) ) ; obj . setKeller ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setNutzflaeche ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 150 , 500 ) ) ) ; obj . setObjektzustand ( ObjektZustandTyp . GEPFLEGT ) ; obj . setParkplatz ( StellplatzKategorieTyp . CARPORT ) ; obj . setRollstuhlgerecht ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setWohnflaeche ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 50 , 300 ) ) ) ; obj . setZimmer ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1 , 5 ) ) ) ; obj . setBefeuerungsArt ( FACTORY . createBefeuerungsArtTyp ( ) ) ; obj . getBefeuerungsArt ( ) . setErdwaerme ( FACTORY . createBefeuerungsArtTypErdwaerme ( Boolean . TRUE ) ) ; obj . getBefeuerungsArt ( ) . setPelletheizung ( FACTORY . createBefeuerungsArtTypPelletheizung ( Boolean . TRUE ) ) ; obj . setEnergieausweis ( FACTORY . createEnergieausweisTyp ( ) ) ; obj . getEnergieausweis ( ) . setEnergieausweistyp ( EnergieausweistypTyp . ENERGIEVERBRAUCHSKENNWERT ) ; obj . getEnergieausweis ( ) . setEnergieverbrauchskennwert ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 50 , 500 ) ) ) ; obj . getEnergieausweis ( ) . setWarmwasserEnthalten ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setMietpreise ( FACTORY . createVermarktungWohnMieteTyp ( ) ) ; obj . getMietpreise ( ) . setHeizkosten ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 100 , 500 ) ) ) ; obj . getMietpreise ( ) . setHeizkostenInWarmmieteEnthalten ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getMietpreise ( ) . setKaltmiete ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 150 , 1500 ) ) ) ; obj . getMietpreise ( ) . setKaution ( \"notes about deposit\" ) ; obj . getMietpreise ( ) . setNebenkosten ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 50 , 500 ) ) ) ; obj . getMietpreise ( ) . setStellplatzMiete ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 50 , 500 ) ) ) ; obj . getMietpreise ( ) . setWarmmiete ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 250 , 2500 ) ) ) ; return FACTORY . createHausMiete ( obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Feed . Projects . Project . Lots . Lot } [CODESPLIT] public Feed . Projects . Project . Lots . Lot createFeedProjectsProjectLotsLot ( ) { return new Feed . Projects . Project . Lots . Lot ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Feed . Projects . Project . Agent . SalesOffice } [CODESPLIT] public Feed . Projects . Project . Agent . SalesOffice createFeedProjectsProjectAgentSalesOffice ( ) { return new Feed . Projects . Project . Agent . SalesOffice ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Feed . Projects . Project . Lots . Lot . Pictures } [CODESPLIT] public Feed . Projects . Project . Lots . Lot . Pictures createFeedProjectsProjectLotsLotPictures ( ) { return new Feed . Projects . Project . Lots . Lot . Pictures ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Feed . Projects . Project . Agent . SalesOffice . City } [CODESPLIT] public Feed . Projects . Project . Agent . SalesOffice . City createFeedProjectsProjectAgentSalesOfficeCity ( ) { return new Feed . Projects . Project . Agent . SalesOffice . City ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of { @link Feed . Projects . Project . Agent . SalesOffice . Locality } [CODESPLIT] public Feed . Projects . Project . Agent . SalesOffice . Locality createFeedProjectsProjectAgentSalesOfficeLocality ( ) { return new Feed . Projects . Project . Agent . SalesOffice . Locality ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 0 to 1 . 1 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_1 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . downgradeUebertragungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <uebertragung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeUserDefinedExtendElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <user_defined_extend> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeAnbieterChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <anbieter> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeBieterverfahrenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <bieterverfahren> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeBewertungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <bewertung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeGeoChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <geo> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeHeizkostenEnthaltenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <heizkosten_enthalten> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeAusstattungChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <ausstattung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeMieteinnahmenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <mieteinnahmen_ist> and <mieteinnahmen_soll> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBefeuerungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <befeuerung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeHausElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <haus> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade an OpenImmo document from version 1 . 1 to 1 . 2 . 0 . [CODESPLIT] @ Override public void upgradeFromPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_0 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . upgradeMieteinnahmenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <mieteinnahmen_ist> and <mieteinnahmen_soll> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; mieteinnahmen_ist&gt ; &lt ; mieteinnahmen_soll&gt ; elements to OpenImmo 1 . 1 . <p > The periode attribute of the &lt ; mieteinnahmen_ist&gt ; and &lt ; mieteinnahmen_soll&gt ; elements is not available in version 1 . 1 . <p > Any occurences of these values is removed . <p > The numeric value within the &lt ; mieteinnahmen_ist&gt ; and &lt ; mieteinnahmen_soll&gt ; elements is converted according to the value of the periode attribute . [CODESPLIT] protected void downgradeMieteinnahmenElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:preise/io:mieteinnahmen_ist[@periode] |\" + \"/io:openimmo/io:anbieter/io:immobilie/io:preise/io:mieteinnahmen_soll[@periode]\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; String value = StringUtils . trimToNull ( node . getTextContent ( ) ) ; Double numericValue = null ; try { numericValue = ( value != null ) ? DatatypeConverter . parseDouble ( value ) : null ; } catch ( Exception ex ) { String tagName = node . getTagName ( ) ; LOGGER . warn ( \"Can't parse <\" + tagName + \">\" + value + \"</\" + tagName + \"> as number!\" ) ; LOGGER . warn ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } if ( numericValue != null && numericValue > 0 ) { String periode = StringUtils . trimToNull ( node . getAttribute ( \"periode\" ) ) ; if ( \"MONAT\" . equalsIgnoreCase ( periode ) ) { node . setTextContent ( DatatypeConverter . printDouble ( numericValue * 12 ) ) ; } else if ( \"WOCHE\" . equalsIgnoreCase ( periode ) ) { node . setTextContent ( DatatypeConverter . printDouble ( numericValue * 52 ) ) ; } else if ( \"TAG\" . equalsIgnoreCase ( periode ) ) { node . setTextContent ( DatatypeConverter . printDouble ( numericValue * 365 ) ) ; } } node . removeAttribute ( \"periode\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove unsupported children from all &lt ; ausstattung&gt ; elements . <p > OpenImmo 1 . 1 does not support the following children for &lt ; ausstattung&gt ; elements : &lt ; dvbt&gt ; &lt ; breitband_zugang&gt ; &lt ; umts_empfang&gt ; &lt ; abstellraum&gt ; &lt ; fahrradraum&gt ; &lt ; rolladen&gt ; <p > These elements are removed by this function . [CODESPLIT] protected void removeAusstattungChildElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:dvbt | \" + \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:breitband_zugang | \" + \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:umts_empfang | \" + \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:abstellraum | \" + \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:fahrradraum | \" + \"/io:openimmo/io:anbieter/io:immobilie/io:ausstattung/io:rolladen\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; parentNode . removeChild ( node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; mieteinnahmen_ist&gt ; &lt ; mieteinnahmen_soll&gt ; elements to OpenImmo 1 . 2 . 0 . <p > The periode attribute with the value JAHR is added to any &lt ; mieteinnahmen_ist&gt ; and &lt ; mieteinnahmen_soll&gt ; elements . [CODESPLIT] protected void upgradeMieteinnahmenElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:preise/io:mieteinnahmen_ist |\" + \"/io:openimmo/io:anbieter/io:immobilie/io:preise/io:mieteinnahmen_soll\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; node . setAttribute ( \"periode\" , \"JAHR\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the ad property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:55:25+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < AdType > getAd ( ) { if ( ad == null ) { ad = new ArrayList < AdType > ( ) ; } return this . ad ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the gastgewTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setGastgewTyp ( Gastgewerbe . GastgewTyp value ) { this . gastgewTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the platzart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPlatzart ( StpSonstige . Platzart value ) { this . platzart = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objektkategorie2 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public BueroPraxisKategorienTyp getObjektkategorie2 ( ) { if ( objektkategorie2 == null ) { return BueroPraxisKategorienTyp . KEINE_ANGABE ; } else { return objektkategorie2 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the datenVerkabelung property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public DatenVerkabelungsTyp getDatenVerkabelung ( ) { if ( datenVerkabelung == null ) { return DatenVerkabelungsTyp . KEINE_ANGABE ; } else { return datenVerkabelung ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the klimaanlage property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public JaNeinVereinbarungTyp getKlimaanlage ( ) { if ( klimaanlage == null ) { return JaNeinVereinbarungTyp . KEINE_ANGABE ; } else { return klimaanlage ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the image property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T01:43:04+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < ImagesType . Image > getImage ( ) { if ( image == null ) { image = new ArrayList < ImagesType . Image > ( ) ; } return this . image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( CasaItWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a Container object with some example data // this object corresponds to the <container> root element in XML Container container = FACTORY . createContainer ( ) ; container . setRealestateitems ( FACTORY . createContainerRealestateitems ( ) ) ; // append some example objects to the Container object container . getRealestateitems ( ) . getRealestate ( ) . add ( createRealestate ( ) ) ; container . getRealestateitems ( ) . getRealestate ( ) . add ( createRealestate ( ) ) ; container . getRealestateitems ( ) . getRealestate ( ) . add ( createRealestate ( ) ) ; // convert the Container object into a XML document CasaItDocument doc = null ; try { doc = CasaItDocument . newDocument ( container ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Realestate } with some example data . [CODESPLIT] protected static Realestate createRealestate ( ) { // create an example real estate Realestate obj = FACTORY . createContainerRealestateitemsRealestate ( ) ; obj . setAction ( BigInteger . ONE ) ; obj . setAgencycode ( 0 ) ; obj . setBathrooms ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 5 ) ) ) ; obj . setCondition ( BigInteger . ONE ) ; obj . setContracttype ( BigInteger . ONE ) ; obj . setFloor ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 5 ) ) ) ; obj . setHasbalcony ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setHasterrace ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setHeatingtype ( BigInteger . ONE ) ; obj . setHousetypology ( BigInteger . ONE ) ; obj . setOccupationstate ( BigInteger . ONE ) ; obj . setRealestatetype ( BigInteger . ONE ) ; obj . setReference ( RandomStringUtils . random ( 5 ) ) ; obj . setReferenceID ( RandomUtils . nextInt ( 1 , 1000 ) ) ; obj . setRooms ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 10 ) ) ) ; obj . setSize ( BigInteger . valueOf ( RandomUtils . nextLong ( 50 , 5000 ) ) ) ; obj . setAddress ( FACTORY . createContainerRealestateitemsRealestateAddress ( ) ) ; obj . getAddress ( ) . setCity ( \"Berlin\" ) ; obj . getAddress ( ) . setNumber ( \"123\" ) ; obj . getAddress ( ) . setStreet ( \"example street\" ) ; obj . getAddress ( ) . setZip ( \"12345\" ) ; obj . getAddress ( ) . setZone ( \"Berlin\" ) ; obj . setBox ( FACTORY . createContainerRealestateitemsRealestateBox ( ) ) ; obj . getBox ( ) . setSize ( BigInteger . valueOf ( RandomUtils . nextLong ( 50 , 1000 ) ) ) ; obj . getBox ( ) . setType ( BigInteger . ONE ) ; obj . setBuilding ( FACTORY . createContainerRealestateitemsRealestateBuilding ( ) ) ; obj . getBuilding ( ) . setAge ( BigInteger . valueOf ( RandomUtils . nextLong ( 5 , 50 ) ) ) ; obj . getBuilding ( ) . setExpenses ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1000 , 1000000 ) ) ) ; obj . getBuilding ( ) . setHaslift ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getBuilding ( ) . setTotalfloors ( BigInteger . valueOf ( RandomUtils . nextLong ( 1 , 5 ) ) ) ; obj . getBuilding ( ) . setUnits ( BigInteger . ONE ) ; obj . setConfiguration ( FACTORY . createContainerRealestateitemsRealestateConfiguration ( ) ) ; obj . getConfiguration ( ) . setIsaddressvisibleonsite ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getConfiguration ( ) . setIsmapvisible ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . getConfiguration ( ) . setIsrealestatevisibleonmap ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; obj . setDescription ( FACTORY . createContainerRealestateitemsRealestateDescription ( ) ) ; obj . getDescription ( ) . setValue ( \"a nice little description for the object\" ) ; obj . setGarden ( FACTORY . createContainerRealestateitemsRealestateGarden ( ) ) ; obj . getGarden ( ) . setSize ( BigInteger . valueOf ( RandomUtils . nextLong ( 10 , 100 ) ) ) ; obj . getGarden ( ) . setType ( BigInteger . ONE ) ; obj . setGooglemapcoordinate ( FACTORY . createContainerRealestateitemsRealestateGooglemapcoordinate ( ) ) ; obj . getGooglemapcoordinate ( ) . setLatitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . getGooglemapcoordinate ( ) . setLatitudemapcenter ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . getGooglemapcoordinate ( ) . setLongitude ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . getGooglemapcoordinate ( ) . setLongitudemapcenter ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 0 , 90 ) ) ) ; obj . getGooglemapcoordinate ( ) . setMapzoom ( 10 ) ; obj . setImages ( FACTORY . createContainerRealestateitemsRealestateImages ( ) ) ; obj . getImages ( ) . getAdvertismentimage ( ) . add ( createAdvertismentimage ( ) ) ; obj . getImages ( ) . getAdvertismentimage ( ) . add ( createAdvertismentimage ( ) ) ; obj . getImages ( ) . getAdvertismentimage ( ) . add ( createAdvertismentimage ( ) ) ; obj . setPrice ( FACTORY . createContainerRealestateitemsRealestatePrice ( ) ) ; obj . getPrice ( ) . setMax ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1000 , 1000000 ) ) ) ; obj . getPrice ( ) . setMin ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1000 , 1000000 ) ) ) ; obj . getPrice ( ) . setValue ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 1000 , 1000000 ) ) ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link Advertismentimage } with some example data . [CODESPLIT] protected static Advertismentimage createAdvertismentimage ( ) { Advertismentimage img = FACTORY . createContainerRealestateitemsRealestateImagesAdvertismentimage ( ) ; img . setImagetype ( \"image/jpeg\" ) ; img . setPath ( \"image-\" + RandomStringUtils . randomNumeric ( 3 ) + \".jpg\" ) ; return img ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the priceType property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPriceType ( OverseasSaleAdType . PriceType value ) { this . priceType = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the newDevelopmentAvailability property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setNewDevelopmentAvailability ( java . lang . String value ) { this . newDevelopmentAvailability = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the directions property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setDirections ( java . lang . String value ) { this . directions = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the co2Rating property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setCo2Rating ( java . lang . String value ) { this . co2Rating = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the energyRating property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setEnergyRating ( java . lang . String value ) { this . energyRating = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the viewingDetails property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setViewingDetails ( java . lang . String value ) { this . viewingDetails = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the propertyStatus property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPropertyStatus ( OverseasSaleAdType . PropertyStatus value ) { this . propertyStatus = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objektkategorie2 property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public TypenHausKategorienTyp getObjektkategorie2 ( ) { if ( objektkategorie2 == null ) { return TypenHausKategorienTyp . KEINE_ANGABE ; } else { return objektkategorie2 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the pictures property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:55:25+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setPictures ( AdType . Pictures value ) { this . pictures = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link FilemakerLayoutDocument } from a { @link FMPXMLLAYOUT } object . [CODESPLIT] public static FilemakerLayoutDocument newDocument ( FMPXMLLAYOUT xmlLayout ) throws ParserConfigurationException , JAXBException { Document document = XmlUtils . newDocument ( ) ; FilemakerUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( xmlLayout , document ) ; return new FilemakerLayoutDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read an { @link InputStream } into a { @link CasaItDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; CasaItDocument doc = CasaItUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of a { @link CasaItDocument } to console . [CODESPLIT] protected static void printToConsole ( CasaItDocument doc ) throws JAXBException { Container container = doc . toObject ( ) ; // process real estates if ( container . getRealestateitems ( ) != null ) { for ( Container . Realestateitems . Realestate obj : container . getRealestateitems ( ) . getRealestate ( ) ) { // get object nr String objectNr = StringUtils . trimToNull ( obj . getReference ( ) ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object title String objectTitle = ( obj . getDescription ( ) != null ) ? StringUtils . trimToNull ( obj . getDescription ( ) . getValue ( ) ) : null ; if ( objectTitle == null ) objectTitle = \"???\" ; // print object information to console LOGGER . info ( \"> found object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the type property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setType ( BoxProject . BoxProjectType value ) { this . type = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the bebaubarAttr property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setBebaubarAttr ( BebaubarNach . BebaubarAttr value ) { this . bebaubarAttr = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 4 to 1 . 2 . 3 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_3 ) ; // downgrade a feedback document if ( doc instanceof OpenImmoFeedbackDocument ) { try { this . removeFeedbackVersionElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <version> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeFeedbackInteressentChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <interessent> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } // downgrade a transfer document else if ( doc instanceof OpenImmoTransferDocument ) { try { this . removePreiseChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <preise> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeWintergartenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported <wintergarten> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeEnergietypElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <energietyp> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBebaubarNachElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <bebaubar_nach> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeAnhangElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <anhang> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeWohnungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <wohnung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeGrundstueckElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <grundstueck> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeLandUndForstwirtschaftElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <land_und_forstwirtschaft> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeParkenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <parken> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade an OpenImmo document from version 1 . 2 . 3 to 1 . 2 . 4 . [CODESPLIT] @ Override public void upgradeFromPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_4 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . upgradeAnzahlBalkonTerrassenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <anzahl_balkon_terrassen> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeAnhangElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <anhang> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeSonstigeElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <sonstige> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; anhang&gt ; elements to OpenImmo 1 . 2 . 3 . <p > The options QRCODE FILM FILMLINK for the gruppe attribute of &lt ; anhang&gt ; elements are not available in version 1 . 2 . 3 . <p > The option REMOTE for the location attribute of &lt ; anhang&gt ; elements is not available in version 1 . 2 . 3 . <p > The the child element &lt ; check&gt ; of &lt ; anhang&gt ; elements is not available in version 1 . 2 . 3 . [CODESPLIT] protected void downgradeAnhangElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:anhang | \" + \"/io:openimmo/io:anbieter/io:immobilie/io:anhaenge/io:anhang\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; String value = StringUtils . trimToNull ( node . getAttribute ( \"gruppe\" ) ) ; if ( \"QRCODE\" . equalsIgnoreCase ( value ) ) node . removeAttribute ( \"gruppe\" ) ; else if ( \"FILM\" . equalsIgnoreCase ( value ) ) node . removeAttribute ( \"gruppe\" ) ; else if ( \"FILMLINK\" . equalsIgnoreCase ( value ) ) node . removeAttribute ( \"gruppe\" ) ; value = StringUtils . trimToNull ( node . getAttribute ( \"location\" ) ) ; if ( \"REMOTE\" . equalsIgnoreCase ( value ) ) node . setAttribute ( \"location\" , \"EXTERN\" ) ; List childNodes = XmlUtils . newXPath ( \"io:check\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { node . removeChild ( ( Node ) childItem ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove unsupported children from all &lt ; interessent&gt ; elements in feedback XML . <p > OpenImmo 1 . 2 . 3 does not support more then one &lt ; bevorzugt&gt ; &lt ; wunsch&gt ; elements in feedback XML . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected void removeFeedbackInteressentChildElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo_feedback/io:objekt/io:interessent\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element parentNode = ( Element ) item ; boolean bevorzugtPassed = false ; boolean wunschPassed = false ; List childNodes = XmlUtils . newXPath ( \"io:bevorzugt\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Element node = ( Element ) childItem ; if ( ! bevorzugtPassed ) bevorzugtPassed = true ; else parentNode . removeChild ( node ) ; } childNodes = XmlUtils . newXPath ( \"io:wunsch\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Element node = ( Element ) childItem ; if ( ! wunschPassed ) wunschPassed = true ; else parentNode . removeChild ( node ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; anhang&gt ; elements to OpenImmo 1 . 2 . 4 . <p > The option REMOTE for the location attribute of &lt ; anhang&gt ; elements is introduced with OpenImmo 1 . 2 . 4 . <p > If the &lt ; pfad&gt ; element of an &lt ; anhang&gt ; element contains an URL ( beginning with http : // / https : // / ftp : // / ftps : // ) the value of the location attribute is changed to REMOTE . [CODESPLIT] protected void upgradeAnhangElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:anhang/io:daten/io:pfad | \" + \"/io:openimmo/io:anbieter/io:immobilie/io:anhaenge/io:anhang/io:daten/io:pfad\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) . getParentNode ( ) ; String value = StringUtils . trimToEmpty ( node . getTextContent ( ) ) . toLowerCase ( ) ; if ( value . startsWith ( \"http://\" ) ) parentNode . setAttribute ( \"location\" , \"REMOTE\" ) ; else if ( value . startsWith ( \"https://\" ) ) parentNode . setAttribute ( \"location\" , \"REMOTE\" ) ; else if ( value . startsWith ( \"ftp://\" ) ) parentNode . setAttribute ( \"location\" , \"REMOTE\" ) ; else if ( value . startsWith ( \"ftps://\" ) ) parentNode . setAttribute ( \"location\" , \"REMOTE\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; anzahl_balkon_terrassen&gt ; elements to OpenImmo 1 . 2 . 4 . <p > The &lt ; anzahl_balkon_terrassen&gt ; is not supported anymore in version 1 . 2 . 4 . The element is replaced by &lt ; anzahl_balkone&gt ; and &lt ; anzahl_terrassen&gt ; . <p > Any &lt ; anzahl_balkon_terrassen&gt ; element is removed . Its content is copied into &lt ; anzahl_balkone&gt ; if this element is not already present . [CODESPLIT] protected void upgradeAnzahlBalkonTerrassenElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:flaechen/io:anzahl_balkon_terrassen\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; String value = StringUtils . trimToNull ( node . getTextContent ( ) ) ; if ( value != null ) { Element newNode = ( Element ) XmlUtils . newXPath ( \"io:anzahl_balkone\" , doc ) . selectSingleNode ( parentNode ) ; if ( newNode == null ) { newNode = doc . createElementNS ( StringUtils . EMPTY , \"anzahl_balkone\" ) ; newNode . setTextContent ( value ) ; parentNode . appendChild ( newNode ) ; } else if ( StringUtils . isBlank ( newNode . getTextContent ( ) ) ) { newNode . setTextContent ( value ) ; } } parentNode . removeChild ( node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; sonstige&gt ; elements to OpenImmo 1 . 2 . 4 . <p > The options GARAGEN PARKFLACHE for the sonstige_typ attribute of &lt ; sonstige&gt ; elements were removed with OpenImmo 1 . 2 . 4 . <p > For any occurence of these values the corresponding &lt ; sonstige&gt ; element is replaced with a &lt ; parken&gt ; element . [CODESPLIT] protected void upgradeSonstigeElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:objektkategorie/io:objektart/io:sonstige[@sonstige_typ]\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; String value = StringUtils . trimToNull ( node . getAttribute ( \"sonstige_typ\" ) ) ; if ( \"GARAGEN\" . equalsIgnoreCase ( value ) || \"PARKFLACHE\" . equalsIgnoreCase ( value ) ) { Element parentNode = ( Element ) node . getParentNode ( ) ; parentNode . removeChild ( node ) ; Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"parken\" ) ; newNode . setAttribute ( \"parken_typ\" , \"STELLPLATZ\" ) ; parentNode . appendChild ( newNode ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the parkenTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setParkenTyp ( Parken . ParkenTyp value ) { this . parkenTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the location property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setLocation ( Foto . Location value ) { this . location = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link OpenImmoFeedbackDocument } from a { @link OpenimmoFeedback } object . [CODESPLIT] public static OpenImmoFeedbackDocument newDocument ( OpenimmoFeedback feedback ) throws ParserConfigurationException , JAXBException { if ( StringUtils . isBlank ( feedback . getVersion ( ) ) ) feedback . setVersion ( OpenImmoUtils . VERSION . toReadableVersion ( ) ) ; Document document = XmlUtils . newDocument ( ) ; OpenImmoUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( feedback , document ) ; return new OpenImmoFeedbackDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link OpenimmoFeedback } object from the contained { @link Document } . [CODESPLIT] @ Override public OpenimmoFeedback toObject ( ) throws JAXBException { this . upgradeToLatestVersion ( ) ; return ( OpenimmoFeedback ) OpenImmoUtils . createUnmarshaller ( ) . unmarshal ( this . getDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link KyeroDocument } from a { @link Root } object . [CODESPLIT] public static KyeroDocument newDocument ( Root root ) throws ParserConfigurationException , JAXBException { if ( root . getKyero ( ) == null ) root . setKyero ( KyeroUtils . getFactory ( ) . createKyeroType ( ) ) ; if ( StringUtils . isBlank ( root . getKyero ( ) . getFeedVersion ( ) ) ) root . getKyero ( ) . setFeedVersion ( KyeroUtils . VERSION . toXmlVersion ( ) ) ; Document document = XmlUtils . newDocument ( ) ; KyeroUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( root , document ) ; return new KyeroDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Root } object from the contained { @link Document } . [CODESPLIT] @ Override public Root toObject ( ) throws JAXBException { this . upgradeToLatestVersion ( ) ; return ( Root ) KyeroUtils . createUnmarshaller ( ) . unmarshal ( this . getDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the alterAttr property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setAlterAttr ( Alter . AlterAttr value ) { this . alterAttr = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link KyeroDocument } from a { @link Document } . [CODESPLIT] public static KyeroDocument createDocument ( Document doc ) { if ( KyeroDocument . isReadable ( doc ) ) return new KyeroDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the freizeitTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setFreizeitTyp ( FreizeitimmobilieGewerblich . FreizeitTyp value ) { this . freizeitTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the telefonart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setTelefonart ( TelSonstige . Telefonart value ) { this . telefonart = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into an { @link ImmoXmlDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; ImmoXmlDocument doc = ImmoXmlUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of an { @link ImmoXmlDocument } to console . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void printToConsole ( ImmoXmlDocument doc ) throws JAXBException { LOGGER . info ( \"> process document in version \" + doc . getDocumentVersion ( ) ) ; Immoxml immoxml = doc . toObject ( ) ; // process agencies in the document for ( Anbieter anbieter : immoxml . getAnbieter ( ) ) { LOGGER . info ( \">> found agency '\" + anbieter . getAnbieternr ( ) + \"'\" ) ; // process real estates of the agency for ( Immobilie immobilie : anbieter . getImmobilie ( ) ) { // get object nr String objectNr = ( immobilie . getVerwaltungTechn ( ) != null ) ? immobilie . getVerwaltungTechn ( ) . getObjektnrIntern ( ) : \"???\" ; // get object title String objectTitle = ( immobilie . getFreitexte ( ) != null ) ? immobilie . getFreitexte ( ) . getObjekttitel ( ) : \"???\" ; // print object information to console LOGGER . info ( \">>> found object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the emailart property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setEmailart ( EmailSonstige . Emailart value ) { this . emailart = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a record according to the object category that is provided in a { @link CSVRecord } . [CODESPLIT] public static Is24CsvRecord createRecord ( CSVRecord record ) { Immobilienart art = Is24CsvRecord . getImmobilienart ( record ) ; if ( Immobilienart . ANLAGE . equals ( art ) ) return Anlageobjekt . newRecord ( record ) ; else if ( Immobilienart . GEWERBE_BUERO_PRAXEN . equals ( art ) ) return GewerbeBueroPraxis . newRecord ( record ) ; else if ( Immobilienart . GEWERBE_EINZELHANDEL . equals ( art ) ) return GewerbeEinzelhandel . newRecord ( record ) ; else if ( Immobilienart . GEWERBE_GASTRONOMIE_HOTEL . equals ( art ) ) return GewerbeGastronomieHotel . newRecord ( record ) ; else if ( Immobilienart . GEWERBE_HALLE_PRODUKTION . equals ( art ) ) return GewerbeHalleProduktion . newRecord ( record ) ; else if ( Immobilienart . GEWERBE_SONSTIGES . equals ( art ) ) return GewerbeSonstiges . newRecord ( record ) ; else if ( Immobilienart . HAUS_KAUF . equals ( art ) ) return HausKauf . newRecord ( record ) ; else if ( Immobilienart . HAUS_MIETE . equals ( art ) ) return HausMiete . newRecord ( record ) ; else if ( Immobilienart . STELLPLATZ_KAUF . equals ( art ) ) return StellplatzKauf . newRecord ( record ) ; else if ( Immobilienart . STELLPLATZ_MIETE . equals ( art ) ) return StellplatzMiete . newRecord ( record ) ; else if ( Immobilienart . WOHNEN_AUF_ZEIT . equals ( art ) ) return WohnenAufZeit . newRecord ( record ) ; else if ( Immobilienart . WOHNUNG_KAUF . equals ( art ) ) return WohnungKauf . newRecord ( record ) ; else if ( Immobilienart . WOHNUNG_MIETE . equals ( art ) ) return WohnungMiete . newRecord ( record ) ; // Immobilienart für Grundstücke wird abhängig zur Objektkategorie erzeugt else if ( Immobilienart . GRUNDSTUECKE . equals ( art ) ) { ObjektkategorieGrundstueck cat = Grundstueck . getObjektkategorie ( record ) ; if ( ObjektkategorieGrundstueck . WOHNEN . equals ( cat ) ) return GrundstueckWohnen . newRecord ( record ) ; else return GrundstueckGewerbe . newRecord ( record ) ; } LOGGER . warn ( \"Unsupported 'Immobilienart' value: \" + record . get ( Is24CsvRecord . FIELD_IMMOBILIENART ) ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the overseasSales property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setOverseasSales ( Daft . OverseasSales value ) { this . overseasSales = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the overseasRental property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setOverseasRental ( Daft . OverseasRental value ) { this . overseasRental = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link OpenImmoDocument } from an { @link InputStream } . [CODESPLIT] public static OpenImmoDocument createDocument ( InputStream input ) throws SAXException , IOException , ParserConfigurationException { return createDocument ( XmlUtils . newDocument ( input , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link OpenImmoDocument } from a { @link File } . [CODESPLIT] public static OpenImmoDocument createDocument ( File xmlFile ) throws SAXException , IOException , ParserConfigurationException { return createDocument ( XmlUtils . newDocument ( xmlFile , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link OpenImmoDocument } from a { @link String } . [CODESPLIT] public static OpenImmoDocument createDocument ( String xmlString ) throws SAXException , IOException , ParserConfigurationException { return createDocument ( XmlUtils . newDocument ( xmlString , true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link OpenImmoDocument } from a { @link Document } . [CODESPLIT] public static OpenImmoDocument createDocument ( Document doc ) { if ( OpenImmoTransferDocument . isReadable ( doc ) ) return new OpenImmoTransferDocument ( doc ) ; else if ( OpenImmoFeedbackDocument . isReadable ( doc ) ) return new OpenImmoFeedbackDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to create a &lt ; user_defined_simplefield&gt ; element with a feldname attribute and a string value . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static Element createUserDefinedSimplefield ( Document doc , String name , String value ) { Element root = XmlUtils . getRootElement ( doc ) ; Element node = doc . createElementNS ( root . getNamespaceURI ( ) , \"user_defined_simplefield\" ) ; node . setAttribute ( \"feldname\" , name ) ; node . setTextContent ( value ) ; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the fehler property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Fehlerliste . Fehler > getFehler ( ) { if ( fehler == null ) { fehler = new ArrayList < Fehlerliste . Fehler > ( ) ; } return this . fehler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the erbpacht property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setErbpacht ( JAXBElement < VermarktungGrundstueckGewerbeTyp . Erbpacht > value ) { this . erbpacht = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the miete property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:52:47+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMiete ( JAXBElement < VermarktungGrundstueckGewerbeTyp . Miete > value ) { this . miete = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link File } into a { @link FilemakerResultDocument } or { @link FilemakerLayoutDocument } and print some of their content to console . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void read ( File xmlFile ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process file: \" + xmlFile . getAbsolutePath ( ) ) ; if ( ! xmlFile . isFile ( ) ) { LOGGER . warn ( \"> provided file is invalid\" ) ; return ; } FilemakerDocument doc = FilemakerUtils . createDocument ( xmlFile ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else if ( doc . isResult ( ) ) { printToConsole ( ( FilemakerResultDocument ) doc ) ; } else if ( doc . isLayout ( ) ) { printToConsole ( ( FilemakerLayoutDocument ) doc ) ; } else { LOGGER . warn ( \"> unsupported type of document: \" + doc . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into a { @link FilemakerResultDocument } or { @link FilemakerLayoutDocument } and print some of their content to console . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; FilemakerDocument doc = FilemakerUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else if ( doc . isResult ( ) ) { printToConsole ( ( FilemakerResultDocument ) doc ) ; } else if ( doc . isLayout ( ) ) { printToConsole ( ( FilemakerLayoutDocument ) doc ) ; } else { LOGGER . warn ( \"> unsupported type of document: \" + doc . getClass ( ) . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of a { @link FilemakerLayoutDocument } to console . [CODESPLIT] protected static void printToConsole ( FilemakerLayoutDocument doc ) throws JAXBException { LOGGER . info ( \"> process layout document\" ) ; FMPXMLLAYOUT layout = doc . toObject ( ) ; LOGGER . info ( \"> error code      : \" + layout . getERRORCODE ( ) ) ; if ( layout . getPRODUCT ( ) != null ) { LOGGER . info ( \"> product name    : \" + layout . getPRODUCT ( ) . getNAME ( ) ) ; LOGGER . info ( \"> product version : \" + layout . getPRODUCT ( ) . getVERSION ( ) ) ; LOGGER . info ( \"> product build   : \" + layout . getPRODUCT ( ) . getBUILD ( ) ) ; } if ( layout . getLAYOUT ( ) != null ) { LOGGER . info ( \"> database name   : \" + layout . getLAYOUT ( ) . getDATABASE ( ) ) ; LOGGER . info ( \"> database layout : \" + layout . getLAYOUT ( ) . getNAME ( ) ) ; for ( LayoutType . FIELD field : layout . getLAYOUT ( ) . getFIELD ( ) ) { LOGGER . info ( \"> database field  : \" + field . getNAME ( ) + \" / \" + field . getSTYLE ( ) . getTYPE ( ) + \" / \" + field . getSTYLE ( ) . getVALUELIST ( ) ) ; } } if ( layout . getVALUELISTS ( ) != null ) { for ( ValueListsType . VALUELIST valueList : layout . getVALUELISTS ( ) . getVALUELIST ( ) ) { LOGGER . info ( \"> database values : \" + valueList . getNAME ( ) ) ; for ( String value : valueList . getVALUE ( ) ) { LOGGER . info ( \">> \" + value ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of a { @link FilemakerResultDocument } to console . [CODESPLIT] protected static void printToConsole ( FilemakerResultDocument doc ) throws JAXBException { LOGGER . info ( \"> process result document\" ) ; FMPXMLRESULT result = doc . toObject ( ) ; LOGGER . info ( \"> error code       : \" + result . getERRORCODE ( ) ) ; if ( result . getPRODUCT ( ) != null ) { LOGGER . info ( \"> product name     : \" + result . getPRODUCT ( ) . getNAME ( ) ) ; LOGGER . info ( \"> product version  : \" + result . getPRODUCT ( ) . getVERSION ( ) ) ; LOGGER . info ( \"> product build    : \" + result . getPRODUCT ( ) . getBUILD ( ) ) ; } if ( result . getDATABASE ( ) != null ) { LOGGER . info ( \"> database name    : \" + result . getDATABASE ( ) . getNAME ( ) ) ; LOGGER . info ( \"> database layout  : \" + result . getDATABASE ( ) . getLAYOUT ( ) ) ; LOGGER . info ( \"> database date    : \" + result . getDATABASE ( ) . getDATEFORMAT ( ) ) ; LOGGER . info ( \"> database time    : \" + result . getDATABASE ( ) . getTIMEFORMAT ( ) ) ; LOGGER . info ( \"> database records : \" + result . getDATABASE ( ) . getRECORDS ( ) ) ; } if ( result . getMETADATA ( ) != null ) { for ( MetaDataType . FIELD field : result . getMETADATA ( ) . getFIELD ( ) ) { LOGGER . info ( \"> database field   : \" + field . getNAME ( ) ) ; LOGGER . info ( \">> type : \" + field . getTYPE ( ) ) ; LOGGER . info ( \">> max repeat : \" + field . getMAXREPEAT ( ) ) ; } } if ( result . getRESULTSET ( ) != null ) { LOGGER . info ( \"> result set found  : \" + result . getRESULTSET ( ) . getFOUND ( ) ) ; for ( ResultSetType . ROW row : result . getRESULTSET ( ) . getROW ( ) ) { LOGGER . info ( \"> result set row    : \" + row . getRECORDID ( ) + \" / \" + row . getMODID ( ) ) ; for ( ResultSetType . ROW . COL col : row . getCOL ( ) ) { for ( String data : col . getDATA ( ) ) { LOGGER . info ( \">> \" + data ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the stpSonstige property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < StpSonstige > getStpSonstige ( ) { if ( stpSonstige == null ) { stpSonstige = new ArrayList < StpSonstige > ( ) ; } return this . stpSonstige ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the valuelist property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:42:33+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < ValueListsType . VALUELIST > getVALUELIST ( ) { if ( valuelist == null ) { valuelist = new ArrayList < ValueListsType . VALUELIST > ( ) ; } return this . valuelist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the minDauer property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMinDauer ( MinMietdauer . MinDauer value ) { this . minDauer = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the zinsTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setZinsTyp ( ZinshausRenditeobjekt . ZinsTyp value ) { this . zinsTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the photo property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:41:42+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < URI > getPhoto ( ) { if ( photo == null ) { photo = new ArrayList < URI > ( ) ; } return this . photo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a { @link InputStream } into a { @link WisItDocument } and print some of its content to console . [CODESPLIT] protected static void read ( InputStream xmlInputStream ) throws SAXException , IOException , ParserConfigurationException , JAXBException { LOGGER . info ( \"process example file\" ) ; WisItDocument doc = WisItUtils . createDocument ( xmlInputStream ) ; if ( doc == null ) { LOGGER . warn ( \"> provided XML is not supported\" ) ; } else { printToConsole ( doc ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of a { @link WisItDocument } to console . [CODESPLIT] protected static void printToConsole ( WisItDocument doc ) throws JAXBException { WIS wis = doc . toObject ( ) ; // process objects if ( wis . getOBJEKTE ( ) != null ) { for ( ObjectType obj : wis . getOBJEKTE ( ) . getOBJEKT ( ) ) { // get object nr String objectNr = StringUtils . trimToNull ( obj . getID ( ) ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object description String objectInfo = StringUtils . trimToNull ( obj . getINFODE ( ) ) ; if ( objectInfo == null ) objectInfo = obj . getINFOIT ( ) ; if ( objectInfo == null ) objectInfo = \"???\" ; // print object information to console LOGGER . info ( \"> found object '\" + objectNr + \"' \" + \"with title '\" + objectInfo + \"'\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the metadata property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setMetadata ( Feed . Metadata value ) { this . metadata = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the projects property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setProjects ( Feed . Projects value ) { this . projects = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the properties property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:48:12+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setProperties ( Feed . Properties value ) { this . properties = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the example application . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) public static void main ( String [ ] args ) { // init logging PropertyConfigurator . configure ( DaftIeWritingExample . class . getResource ( PACKAGE + \"/log4j.properties\" ) ) ; // create a Daft object with some example data // this object corresponds to the <daft> root element in XML Daft daft = FACTORY . createDaft ( ) ; // append some example objects for rent to the Daft object daft . setOverseasRental ( FACTORY . createDaftOverseasRental ( ) ) ; daft . getOverseasRental ( ) . getOverseasRentalAd ( ) . add ( createAdForRent ( ) ) ; daft . getOverseasRental ( ) . getOverseasRentalAd ( ) . add ( createAdForRent ( ) ) ; // append some example objects for sale to the Daft object daft . setOverseasSales ( FACTORY . createDaftOverseasSales ( ) ) ; daft . getOverseasSales ( ) . getOverseasSaleAd ( ) . add ( createAdForSale ( ) ) ; daft . getOverseasSales ( ) . getOverseasSaleAd ( ) . add ( createAdForSale ( ) ) ; daft . getOverseasSales ( ) . getOverseasSaleAd ( ) . add ( createAdForSale ( ) ) ; // convert the Daft object into a XML document DaftIeDocument doc = null ; try { doc = DaftIeDocument . newDocument ( daft ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't create XML document!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.File try { write ( doc , File . createTempFile ( \"output-\" , \".xml\" ) ) ; } catch ( IOException ex ) { LOGGER . error ( \"Can't create temporary file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } // write XML document into a java.io.OutputStream write ( doc , new NullOutputStream ( ) ) ; // write XML document into a java.io.Writer write ( doc , new NullWriter ( ) ) ; // write XML document into a string and send it to the console writeToConsole ( doc ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link OverseasRentalAdType } with some example data . [CODESPLIT] @ SuppressWarnings ( \"CatchMayIgnoreException\" ) protected static OverseasRentalAdType createAdForRent ( ) { // create an example real estate for rent OverseasRentalAdType ad = FACTORY . createOverseasRentalAdType ( ) ; ad . setAddress ( \"Beispielstraße 123\") ;  ad . setAgentId ( \"123\" ) ; ad . setArea ( \"Berlin\" ) ; ad . setAvailableFrom ( Calendar . getInstance ( ) ) ; ad . setBathroomNumber ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setBedroomNumber ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setCableTelevision ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setCcEmail ( \"test@openestate.org\" ) ; ad . setCommercialType ( CommercialType . LAND ) ; ad . setContactName ( \"Max Mustermann\" ) ; ad . setCountry ( \"DE\" ) ; ad . setDescription ( \"A description about the property.\" ) ; ad . setDishwasher ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setDoubleBeds ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setDryer ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setExternalId ( String . valueOf ( RandomUtils . nextInt ( 1 , 1000 ) ) ) ; ad . setFurnished ( OverseasRentalAdType . Furnished . FURNISHED ) ; ad . setHouseType ( HouseType . TOWNHOUSE ) ; ad . setLease ( BigInteger . valueOf ( RandomUtils . nextInt ( 100 , 1000 ) ) ) ; ad . setMainEmail ( \"test@openstate.org\" ) ; ad . setMicrowave ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setNumberPeople ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setPhone1 ( \"030/123456\" ) ; ad . setPhone2 ( \"030/123457\" ) ; ad . setPhoneInfo ( \"Some information about contacts via phone.\" ) ; ad . setPropertyType ( PropertyType . HOUSE ) ; ad . setRegion ( \"Berlin\" ) ; ad . setRent ( BigInteger . valueOf ( RandomUtils . nextInt ( 100 , 1000 ) ) ) ; ad . setRentCollectionPeriod ( OverseasRentalAdType . RentPeriod . MONTHLY ) ; ad . setSingleBeds ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setTwinBeds ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setWashingMachine ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; // add some features ad . setFeatures ( FACTORY . createFeaturesType ( ) ) ; ad . getFeatures ( ) . getFeature ( ) . add ( \"another feature\" ) ; ad . getFeatures ( ) . getFeature ( ) . add ( \"some more feature\" ) ; // add some photos ad . setPhotos ( FACTORY . createPhotosType ( ) ) ; try { ad . getPhotos ( ) . getPhoto ( ) . add ( new URI ( \"http://www.mywebsite.org/image1.jpg\" ) ) ; ad . getPhotos ( ) . getPhoto ( ) . add ( new URI ( \"http://www.mywebsite.org/image2.jpg\" ) ) ; ad . getPhotos ( ) . getPhoto ( ) . add ( new URI ( \"http://www.mywebsite.org/image3.jpg\" ) ) ; } catch ( URISyntaxException ex ) { } return ad ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an { @link OverseasRentalAdType } with some example data . [CODESPLIT] @ SuppressWarnings ( \"CatchMayIgnoreException\" ) protected static OverseasSaleAdType createAdForSale ( ) { // create an example real estate for sale OverseasSaleAdType ad = FACTORY . createOverseasSaleAdType ( ) ; ad . setAcres ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 10 , 1000 ) ) ) ; ad . setAddress ( \"Beispielstraße 123\") ;  ad . setAgentId ( \"123\" ) ; ad . setArea ( \"Berlin\" ) ; ad . setBathroomNumber ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setBedroomNumber ( BigInteger . valueOf ( RandomUtils . nextInt ( 0 , 5 ) ) ) ; ad . setCcEmail ( \"test@openestate.org\" ) ; ad . setCo2Rating ( \"some notes about CO2 rating\" ) ; ad . setCommercialType ( CommercialType . SHOP ) ; ad . setContactName ( \"Max Mustermann\" ) ; ad . setCountry ( \"DE\" ) ; ad . setDescription ( \"A description about the property.\" ) ; ad . setDirections ( \"some notes about directions\" ) ; ad . setEnergyRating ( \"some notes about energy rating\" ) ; ad . setExternalId ( String . valueOf ( RandomUtils . nextInt ( 1 , 1000 ) ) ) ; ad . setHouseType ( HouseType . DETACHED ) ; ad . setIsNewDevelopment ( RandomUtils . nextInt ( 0 , 2 ) == 1 ) ; ad . setMainEmail ( \"test@openstate.org\" ) ; ad . setNewDevelopmentAvailability ( \"some notes about development\" ) ; ad . setPhone1 ( \"030/123456\" ) ; ad . setPhone2 ( \"030/123457\" ) ; ad . setPhoneInfo ( \"Some information about contacts via phone.\" ) ; ad . setPrice ( BigInteger . valueOf ( RandomUtils . nextInt ( 100 , 1000000 ) ) ) ; ad . setPriceType ( OverseasSaleAdType . PriceType . REGION ) ; ad . setPropertyStatus ( OverseasSaleAdType . PropertyStatus . FOR_SALE ) ; ad . setPropertyType ( PropertyType . HOUSE ) ; ad . setRegion ( \"Berlin\" ) ; ad . setSquareMetres ( BigDecimal . valueOf ( RandomUtils . nextDouble ( 10 , 1000 ) ) ) ; ad . setUnitsAvailable ( BigInteger . valueOf ( RandomUtils . nextInt ( 1 , 50 ) ) ) ; ad . setViewingDetails ( \"some notes about viewing details\" ) ; // add some features ad . setFeatures ( FACTORY . createFeaturesType ( ) ) ; ad . getFeatures ( ) . getFeature ( ) . add ( \"another feature\" ) ; ad . getFeatures ( ) . getFeature ( ) . add ( \"some more feature\" ) ; // add some pdf documents ad . setPdfs ( FACTORY . createPdfsType ( ) ) ; try { ad . getPdfs ( ) . getPdf ( ) . add ( new URI ( \"http://www.mywebsite.org/document1.pdf\" ) ) ; ad . getPdfs ( ) . getPdf ( ) . add ( new URI ( \"http://www.mywebsite.org/document2.pdf\" ) ) ; } catch ( URISyntaxException ex ) { } // add some photos ad . setPhotos ( FACTORY . createPhotosType ( ) ) ; try { ad . getPhotos ( ) . getPhoto ( ) . add ( new URI ( \"http://www.mywebsite.org/image1.jpg\" ) ) ; ad . getPhotos ( ) . getPhoto ( ) . add ( new URI ( \"http://www.mywebsite.org/image2.jpg\" ) ) ; ad . getPhotos ( ) . getPhoto ( ) . add ( new URI ( \"http://www.mywebsite.org/image3.jpg\" ) ) ; } catch ( URISyntaxException ex ) { } return ad ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a { @link DaftIeDocument } into a { @link File } . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected static void write ( DaftIeDocument doc , File file ) { LOGGER . info ( \"writing document with version \" + doc . getDocumentVersion ( ) ) ; try { doc . toXml ( file , PRETTY_PRINT ) ; LOGGER . info ( \"> written to: \" + file . getAbsolutePath ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't write document into a file!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link TrovitDocument } from a { @link Trovit } object . [CODESPLIT] public static TrovitDocument newDocument ( Trovit trovit ) throws ParserConfigurationException , JAXBException { Document document = XmlUtils . newDocument ( ) ; TrovitUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( trovit , document ) ; return new TrovitDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade a Kyero document from version 3 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( KyeroDocument doc ) { doc . setDocumentVersion ( KyeroVersion . V2_1 ) ; try { this . downgradeNewBuildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <new_build> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeTypeElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <type> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeUrlElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <url> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeLocationElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <location> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeEnergyRatingElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <energy_rating> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeNotesElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <notes> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeUnsupportedLanguageElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported translation elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade a Kyero document to version 3 . [CODESPLIT] @ Override public void upgradeFromPreviousVersion ( KyeroDocument doc ) { doc . setDocumentVersion ( KyeroVersion . V3 ) ; try { this . removeCustomElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <custom> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeNewBuildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <new_build> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeTypeElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <type> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeCurrencyElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <currency> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . upgradeUrlElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't upgrade <url> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; new_build&gt ; elements to Kyero 2 . 1 . <p > The &lt ; new_build&gt ; elements are not available in version 2 . 1 . Instead the value new_build is used in the &lt ; price_freq&gt ; element . <p > Any &lt ; new_build&gt ; elements are removed . If its value is set to 1 then &lt ; price_freq&gt ; sale&lt ; / price_freq&gt ; is converted to &lt ; price_freq&gt ; new_build&lt ; / price_freq&gt ; [CODESPLIT] protected void downgradeNewBuildElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:root/io:property/io:new_build\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; String value = StringUtils . trimToNull ( node . getTextContent ( ) ) ; if ( \"1\" . equals ( value ) ) { Element priceFreqNode = ( Element ) XmlUtils . newXPath ( \"io:price_freq\" , doc ) . selectSingleNode ( parentNode ) ; if ( priceFreqNode == null ) { priceFreqNode = doc . createElementNS ( KyeroUtils . NAMESPACE , \"price_freq\" ) ; priceFreqNode . setTextContent ( \"new_build\" ) ; parentNode . appendChild ( priceFreqNode ) ; } else if ( \"sale\" . equalsIgnoreCase ( priceFreqNode . getTextContent ( ) ) ) { priceFreqNode . setTextContent ( \"new_build\" ) ; } } parentNode . removeChild ( node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; type&gt ; elements to Kyero 2 . 1 . <p > The &lt ; type&gt ; elements require a &lt ; en&gt ; child element in version 2 . 1 . <p > An &lt ; en&gt ; child element is created for any &lt ; type&gt ; element . [CODESPLIT] protected void downgradeTypeElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:root/io:property/io:type\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; String value = StringUtils . trimToNull ( node . getTextContent ( ) ) ; node . setTextContent ( null ) ; Element childNode = doc . createElementNS ( KyeroUtils . NAMESPACE , \"en\" ) ; childNode . setTextContent ( value ) ; node . appendChild ( childNode ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; url&gt ; elements to Kyero 2 . 1 . <p > The &lt ; url&gt ; elements only support a simple text value in version 2 . 1 . Version 3 allows different URL s for different languages . <p > Any children of &lt ; url&gt ; elements are removed . The english URL or the first found URL is copied as simple value into the &lt ; url&gt ; element . [CODESPLIT] @ SuppressWarnings ( \"Duplicates\" ) protected void downgradeUrlElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:root/io:property/io:url\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; String enUrlValue = null ; String fallbackUrlValue = null ; List childNodes = XmlUtils . newXPath ( \"*\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Element langNode = ( Element ) childItem ; if ( \"en\" . equalsIgnoreCase ( langNode . getLocalName ( ) ) ) enUrlValue = StringUtils . trimToNull ( langNode . getTextContent ( ) ) ; else if ( fallbackUrlValue == null ) fallbackUrlValue = StringUtils . trimToNull ( langNode . getTextContent ( ) ) ; node . removeChild ( langNode ) ; } node . setTextContent ( ( enUrlValue != null ) ? enUrlValue : fallbackUrlValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove elements with translations in unsupported languages . <p > Kyero 2 . 1 does only support translation in &lt ; title&gt ; ( for images ) &lt ; desc&gt ; ( for properties ) elements for en es de nl fr . [CODESPLIT] protected void removeUnsupportedLanguageElements ( Document doc ) throws JaxenException { String [ ] unsupportedLanguages = new String [ ] { \"ar\" , \"bg\" , \"ca\" , \"cs\" , \"da\" , \"el\" , \"et\" , \"fa\" , \"fi\" , \"he\" , \"hi\" , \"hu\" , \"id\" , \"it\" , \"ja\" , \"ko\" , \"lt\" , \"lv\" , \"no\" , \"pl\" , \"pt\" , \"ro\" , \"ru\" , \"sk\" , \"sl\" , \"sv\" , \"th\" , \"tr\" , \"uk\" , \"vi\" , \"zh\" , } ; List nodes = XmlUtils . newXPath ( \"/io:root/io:property/io:desc | \" + \"/io:root/io:property/io:images/io:image/io:title\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; List childNodes = XmlUtils . newXPath ( \"*\" , doc ) . selectNodes ( node ) ; for ( Object childItem : childNodes ) { Element langNode = ( Element ) childItem ; String lang = langNode . getLocalName ( ) . toLowerCase ( ) ; if ( ArrayUtils . contains ( unsupportedLanguages , lang ) ) { node . removeChild ( langNode ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; new_build&gt ; elements for Kyero 3 . <p > The &lt ; new_build&gt ; elements are not available in version 2 . 1 . Instead the value new_build is used in the &lt ; price_freq&gt ; element . <p > Any occurrences of &lt ; price_freq&gt ; new_build&lt ; / price_freq&gt ; is replaced by &lt ; price_freq&gt ; sale&lt ; / price_freq&gt ; and &lt ; new_build&gt ; 1&lt ; / new_build&gt ; is added to the property . [CODESPLIT] protected void upgradeNewBuildElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:root/io:property/io:price_freq\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; if ( ! \"new_build\" . equalsIgnoreCase ( node . getTextContent ( ) ) ) continue ; node . setTextContent ( \"sale\" ) ; Element newBuildNode = doc . createElementNS ( KyeroUtils . NAMESPACE , \"new_build\" ) ; newBuildNode . setTextContent ( \"1\" ) ; parentNode . appendChild ( newBuildNode ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link WisItDocument } from a { @link WIS } object . [CODESPLIT] public static WisItDocument newDocument ( WIS wis ) throws ParserConfigurationException , JAXBException { if ( wis . getOBJEKTE ( ) == null ) wis . setOBJEKTE ( WisItUtils . getFactory ( ) . createWISOBJEKTE ( ) ) ; wis . getOBJEKTE ( ) . setANZAHL ( BigInteger . valueOf ( wis . getOBJEKTE ( ) . getOBJEKT ( ) . size ( ) ) ) ; Document document = XmlUtils . newDocument ( ) ; WisItUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( wis , document ) ; return new WisItDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print some content of an { @link Is24CsvParser } to console . [CODESPLIT] protected static void printToConsole ( Is24CsvParser parser ) { // process records while ( parser . hasNext ( ) ) { Is24CsvRecord record = parser . next ( ) ; // get object nr String objectNr = record . getAnbieterObjektId ( ) ; if ( objectNr == null ) objectNr = \"???\" ; // get object title String objectTitle = record . getUeberschrift ( ) ; if ( objectTitle == null ) objectTitle = \"???\" ; // print object information to console LOGGER . info ( \"> found object '\" + objectNr + \"' \" + \"with title '\" + objectTitle + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ImmobiliareItDocument } from a { @link Feed } object . [CODESPLIT] public static ImmobiliareItDocument newDocument ( Feed feed ) throws ParserConfigurationException , JAXBException { if ( feed . getVersion ( ) == null ) feed . setVersion ( Version . V2_5 ) ; Document document = XmlUtils . newDocument ( ) ; ImmobiliareItUtils . createMarshaller ( \"UTF-8\" , true ) . marshal ( feed , document ) ; return new ImmobiliareItDocument ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link Feed } object from the contained { @link Document } . [CODESPLIT] @ Override public Feed toObject ( ) throws JAXBException { this . upgradeToLatestVersion ( ) ; return ( Feed ) ImmobiliareItUtils . createUnmarshaller ( ) . unmarshal ( this . getDocument ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade an OpenImmo document from version 1 . 2 . 2 to 1 . 2 . 1 . [CODESPLIT] @ Override public void downgradeToPreviousVersion ( OpenImmoDocument doc ) { doc . setDocumentVersion ( OpenImmoVersion . V1_2_1 ) ; if ( doc instanceof OpenImmoTransferDocument ) { try { this . downgradeUebertragungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <uebertragung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeVersteigerungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <versteigerung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeProvisionspflichtigElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove <provisionspflichtig> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . removeAusstattungChildElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't remove unsupported children of <ausstattung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeObjektartElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <objektart> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeEnergiepassElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <energiepass> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBodenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <boden> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBefeuerungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <befeuerung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeWohnungElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <wohnung> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeHausElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <haus> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeGrundstueckElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <grundstueck> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeBueroPraxenElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <buero_praxen> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeEinzelhandelElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <einzelhandel> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeGastgewerbeElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <gastgewerbe> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeHallenLagerProdElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <hallen_lager_prod> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeLandUndForstwirtschaftElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <land_und_forstwirtschaft> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } try { this . downgradeFreizeitimmobilieGewerblichElements ( doc . getDocument ( ) ) ; } catch ( Exception ex ) { LOGGER . error ( \"Can't downgrade <freizeitimmobilie_gewerblich> elements!\" ) ; LOGGER . error ( \"> \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Downgrade &lt ; objektart&gt ; elements to OpenImmo 1 . 2 . 1 . <p > The &lt ; objektart&gt ; element does only allow the same type of child element in version 1 . 2 . 1 . <p > Any child type that differs from the first child type is removed . [CODESPLIT] protected void downgradeObjektartElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:objektkategorie/io:objektart\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element parentNode = ( Element ) item ; String type = null ; List childNodes = XmlUtils . newXPath ( \"*\" , doc ) . selectNodes ( parentNode ) ; for ( Object childItem : childNodes ) { Element node = ( Element ) childItem ; if ( type == null ) { //LOGGER.debug( \"PRIMARY TYPE: \" + node.getLocalName() ); type = node . getLocalName ( ) ; } else if ( ! type . equalsIgnoreCase ( node . getLocalName ( ) ) ) { //LOGGER.debug( \"REMOVE SECONDARY TYPE: \" + node.getLocalName() ); parentNode . removeChild ( node ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrade &lt ; energiepass&gt ; elements to OpenImmo 1 . 2 . 2 . <p > The &lt ; art&gt ; child element of the &lt ; energiepass&gt ; element is renamed to &lt ; epart&gt ; in version 1 . 2 . 2 . [CODESPLIT] protected void upgradeEnergiepassElements ( Document doc ) throws JaxenException { List nodes = XmlUtils . newXPath ( \"/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass/io:art\" , doc ) . selectNodes ( doc ) ; for ( Object item : nodes ) { Element node = ( Element ) item ; Element parentNode = ( Element ) node . getParentNode ( ) ; Element newNode = doc . createElementNS ( StringUtils . EMPTY , \"epart\" ) ; newNode . setTextContent ( node . getTextContent ( ) ) ; parentNode . replaceChild ( newNode , node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the immobilie property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Immobilie > getImmobilie ( ) { if ( immobilie == null ) { immobilie = new ArrayList < Immobilie > ( ) ; } return this . immobilie ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ImmoXmlDocument } from a { @link Document } . [CODESPLIT] public static ImmoXmlDocument createDocument ( Document doc ) { if ( ImmoXmlDocument . isReadable ( doc ) ) return new ImmoXmlDocument ( doc ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the objekt property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Objekt > getObjekt ( ) { if ( objekt == null ) { objekt = new ArrayList < Objekt > ( ) ; } return this . objekt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the fehlerliste property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Fehlerliste > getFehlerliste ( ) { if ( fehlerliste == null ) { fehlerliste = new ArrayList < Fehlerliste > ( ) ; } return this . fehlerliste ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the status property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Status > getStatus ( ) { if ( status == null ) { status = new ArrayList < Status > ( ) ; } return this . status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the sonstigeTyp property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:50:55+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setSonstigeTyp ( Sonstige . SonstigeTyp value ) { this . sonstigeTyp = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the distanzZu property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public void setDistanzZu ( Distanzen . DistanzZu value ) { this . distanzZu = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the distanzen property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < Distanzen > getDistanzen ( ) { if ( distanzen == null ) { distanzen = new ArrayList < Distanzen > ( ) ; } return this . distanzen ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the distanzenSport property . [CODESPLIT] @ Generated ( value = \"com.sun.tools.xjc.Driver\" , date = \"2018-10-12T02:54:50+02:00\" , comments = \"JAXB RI v2.2.11\" ) public List < DistanzenSport > getDistanzenSport ( ) { if ( distanzenSport == null ) { distanzenSport = new ArrayList < DistanzenSport > ( ) ; } return this . distanzenSport ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------ [CODESPLIT] public Response setnx ( Object key , Object val ) { return req ( Cmd . setnx , bytes ( key ) , bytes ( val ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "指定配置生成一个单连接的客户端 [CODESPLIT] public static final SSDB simple ( String host , int port , int timeout ) { return new SimpleClient ( host , port , timeout ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "指定配置生成一个使用连接池的客户端 [CODESPLIT] public static final SSDB pool ( String host , int port , int timeout , Object config ) { return pool ( host , port , timeout , config , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "指定配置生成一个使用连接池的客户端 [CODESPLIT] public static final SSDB pool ( String host , int port , int timeout , Object config , byte [ ] auth ) { return new SimpleClient ( _pool ( host , port , timeout , config , auth ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "按指定配置生成master / slave且使用连接池的客户端 [CODESPLIT] public static final SSDB replication ( String masterHost , int masterPort , String slaveHost , int slavePort , int timeout , Object config ) { return replication ( masterHost , masterPort , slaveHost , slavePort , timeout , config , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "按指定配置生成master / slave且使用连接池的客户端 [CODESPLIT] public static final SSDB replication ( String masterHost , int masterPort , String slaveHost , int slavePort , int timeout , Object config , byte [ ] masterAuth , byte [ ] slaveAuth ) { PoolSSDBStream master = _pool ( masterHost , masterPort , timeout , config , masterAuth ) ; PoolSSDBStream slave = _pool ( slaveHost , slavePort , timeout , config , slaveAuth ) ; return new SimpleClient ( new ReplicationSSDMStream ( master , slave ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "按ssdb的通信协议写入一个Block <p > < / p > <b > 如果本方法抛异常 应立即关闭输出流< / b > [CODESPLIT] public static void writeBlock ( OutputStream out , byte [ ] data ) throws IOException { if ( data == null ) data = EMPTY_ARG ; out . write ( Integer . toString ( data . length ) . getBytes ( ) ) ; out . write ( ' ' ) ; out . write ( data ) ; out . write ( ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "向输出流发送一个命令及其参数 <p > < / p > <b > 如果本方法抛异常 应立即关闭输出流< / b > [CODESPLIT] public static void sendCmd ( OutputStream out , Cmd cmd , byte [ ] ... vals ) throws IOException { SSDBs . writeBlock ( out , cmd . bytes ( ) ) ; for ( byte [ ] bs : vals ) { SSDBs . writeBlock ( out , bs ) ; } out . write ( ' ' ) ; out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从输入流读取一个响应 <p > < / p > <b > 如果本方法抛异常 应立即关闭输入流< / b > [CODESPLIT] public static Response readResp ( InputStream in ) throws IOException { Response resp = respFactory . make ( ) ; byte [ ] data = SSDBs . readBlock ( in ) ; if ( data == null ) throw new SSDBException ( \"protocol error. unexpect \\\\n\" ) ; resp . stat = new String ( data ) ; while ( true ) { data = SSDBs . readBlock ( in ) ; if ( data == null ) break ; resp . datas . add ( data ) ; } return resp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断class是否实现了接口类 [CODESPLIT] public static boolean isContainsInterface ( Class < ? > clazz , Class < ? > interfaceClass ) { Class < ? > [ ] interfaces = clazz . getInterfaces ( ) ; for ( int i = 0 ; i < interfaces . length ; i ++ ) { Class < ? > class1 = interfaces [ i ] ; if ( class1 == interfaceClass ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取该class所表示的父类的泛型数组 <br > 例如如下定义中： [CODESPLIT] public static Type [ ] getGenericTypes ( Class < ? > clazz ) { Type mySuperClass = clazz . getGenericSuperclass ( ) ; System . out . println ( mySuperClass ) ; System . out . println ( mySuperClass . getClass ( ) ) ; Type [ ] types = ( ( ParameterizedType ) mySuperClass ) . getActualTypeArguments ( ) ; for ( int i = 0 ; i < types . length ; i ++ ) { Type type = types [ i ] ; System . out . println ( type ) ; } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取Class类的所有字段名 <br > 2013 - 10 - 21 下午5 : 19 : 48 [CODESPLIT] public static String [ ] getClassFields ( Class < ? > clazz ) { Field [ ] fields = clazz . getDeclaredFields ( ) ; int length = fields . length ; String [ ] fieldNames = new String [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { Field field = fields [ i ] ; fieldNames [ i ] = field . getName ( ) ; } return fieldNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取Class类的所有非静态字段名 <br > 2013 - 10 - 21 下午5 : 19 : 48 [CODESPLIT] public static Collection < String > getUnstaticClassFieldNameCollection ( Class < ? > clazz ) { if ( clazz == null ) { throw new NullPointerException ( \"传入的clazz为空对象！\");   } Field [ ] fields = clazz . getDeclaredFields ( ) ; int length = fields . length ; Collection < String > fieldNames = new ArrayList < String > ( ) ; for ( int i = 0 ; i < length ; i ++ ) { Field field = fields [ i ] ; if ( ! Modifier . isStatic ( field . getModifiers ( ) ) ) { fieldNames . add ( field . getName ( ) ) ; } } return fieldNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取Class类的所有字段名 <br > 2013 - 10 - 21 下午5 : 19 : 48 [CODESPLIT] public static String [ ] getClassSimpleFields ( Class < ? > clazz ) { Field [ ] fields = clazz . getDeclaredFields ( ) ; int length = fields . length ; Collection < Field > fieldCollection = new ArrayList < Field > ( ) ; for ( int i = 0 ; i < length ; i ++ ) { Field field = fields [ i ] ; if ( isSimpleType ( field ) ) { fieldCollection . add ( field ) ; } } String [ ] fieldNames = new String [ fieldCollection . size ( ) ] ; int i = 0 ; for ( Iterator iterator = fieldCollection . iterator ( ) ; iterator . hasNext ( ) ; ) { Field field = ( Field ) iterator . next ( ) ; fieldNames [ i ] = field . getName ( ) ; i ++ ; } return fieldNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据get方法获取字段名 [CODESPLIT] public static String getFieldNameByGetMethod ( Method method ) { Assert . notNull ( method ) ; String methodName = method . getName ( ) ; EntityHelper . print ( methodName ) ; if ( methodName . startsWith ( \"get\" ) ) { String name = methodName . substring ( 3 , 4 ) . toLowerCase ( ) + methodName . substring ( 4 ) ; return name ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取Class类的单例，如果其他类不是使用的该方法，那么必定造成对象引用不一致！因此一定要检查每个对象的构造方式是否一致都是使用本方法来构造 <br > 2013 - 10 - 21 上午11 : 22 : 55 [CODESPLIT] public static final < T > T getSingleton ( Class < T > clazz , Object ... args ) throws Exception { T instance = null ; synchronized ( LOCK ) { instance = ( T ) singletonMap . get ( clazz ) ; if ( instance == null ) { Constructor < ? > constructor = null ; try { constructor = getConstructor ( clazz , args ) ; } catch ( SecurityException e1 ) { } catch ( NoSuchMethodException e1 ) { } if ( constructor != null ) { try { instance = ( T ) constructor . newInstance ( args ) ; } catch ( IllegalArgumentException e ) { } catch ( InstantiationException e ) { } catch ( IllegalAccessException e ) { } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } if ( instance == null ) { Constructor < ? > [ ] constructors = clazz . getConstructors ( ) ; for ( int i = 0 ; i < constructors . length ; i ++ ) { Constructor < ? > constructorVar = constructors [ i ] ; try { instance = ( T ) constructorVar . newInstance ( args ) ; } catch ( IllegalArgumentException e ) { } catch ( InstantiationException e ) { } catch ( IllegalAccessException e ) { } catch ( InvocationTargetException e ) { } } } if ( instance == null ) { throw new NoSuchMethodException ( \"无法初始化对象: \" + clazz + \";  检 传入的参数 否 合\");   } } singletonMap . put ( clazz , instance ) ; } return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据传入的给予构造参数的传入值获取构造方法 <br > 2013 - 10 - 21 上午11 : 03 : 13 [CODESPLIT] public static Constructor < ? > getConstructor ( Class < ? > clazz , Object ... args ) throws SecurityException , NoSuchMethodException { Constructor < ? > constructor = null ; int length = args . length ; Class < ? > [ ] classes = new Class < ? > [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { Object object = args [ i ] ; classes [ i ] = object . getClass ( ) ; } constructor = clazz . getConstructor ( classes ) ; return constructor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据Class类、方法名和传入的参数，获取对应的方法对象 <br > 2013 - 10 - 21 下午4 : 49 : 19 [CODESPLIT] public static Method getMethod ( Class < ? extends Object > clazz , String methodName , Object ... args ) throws SecurityException , NoSuchMethodException { Method method = null ; int length = args . length ; Class < ? > [ ] classes = new Class < ? > [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { Object object = args [ i ] ; classes [ i ] = object . getClass ( ) ; } try { method = clazz . getDeclaredMethod ( methodName , classes ) ; } catch ( Exception e ) { } if ( method == null && args . length > 0 ) { Method [ ] methods = clazz . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method methodVar = methods [ i ] ; Class < ? > [ ] types = methodVar . getParameterTypes ( ) ; boolean isThisMethod = false ; if ( types . length == args . length ) { isThisMethod = true ; for ( int j = 0 ; j < types . length && isThisMethod ; j ++ ) { Class < ? > type = types [ j ] ; Object parameter = args [ j ] ; if ( ! typeEquals ( type , parameter ) ) { isThisMethod = false ; } } } if ( isThisMethod ) { method = methodVar ; break ; } } } return method ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据字段获取Class类的get方法 <br > 2013 - 10 - 21 下午12 : 05 : 53 [CODESPLIT] public static Method getMethodOfBeanByField ( Class < ? > clazz , Field field ) { Method method = prefixMethodOfBeanByField ( \"get\" , clazz , field ) ; if ( method == null && ( field . getType ( ) . equals ( Boolean . class ) || field . getType ( ) . equals ( boolean . class ) ) ) { method = prefixMethodOfBeanByField ( \"is\" , clazz , field ) ; } return method ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据字段获取Class类的set方法 <br > 2013 - 10 - 21 下午12 : 05 : 53 [CODESPLIT] public static Method setMethodOfBeanByField ( Class < ? > clazz , Field field ) { return prefixMethodOfBeanByField ( \"set\" , clazz , field , field . getType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据字段获取Class类的set方法 <br > 2013 - 10 - 21 下午12 : 05 : 53 [CODESPLIT] public static Method prefixMethodOfBeanByField ( String prefix , Class < ? > clazz , Field field , Class < ? > ... argTypes ) { Method method = null ; String fieldName = field . getName ( ) ; StringBuilder builder = new StringBuilder ( prefix ) ; builder . append ( fieldName . substring ( 0 , 1 ) . toUpperCase ( ) ) ; builder . append ( fieldName . substring ( 1 , fieldName . length ( ) ) ) ; String methodName = builder . toString ( ) ; try { method = clazz . getDeclaredMethod ( methodName , argTypes ) ; } catch ( SecurityException e ) { } catch ( NoSuchMethodException e ) { } return method ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取类的所有超类 <br > 2013 - 9 - 15 下午8 : 16 : 21 [CODESPLIT] public static Collection < Class > getAllSuperClassesOfClass ( Class clazz ) { Collection < Class > classes = new LinkedHashSet < Class > ( ) ; classes . add ( clazz ) ; Class superClass = clazz . getSuperclass ( ) ; while ( superClass != null ) { classes . add ( superClass ) ; superClass = superClass . getSuperclass ( ) ; } return classes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "简单的ToString方法，只会查找简单类型的数据 <br > 2013 - 8 - 14 下午3 : 42 : 01 [CODESPLIT] public static String simpleReflectToString ( Object object ) { if ( object == null ) { return null ; } Class clazz = object . getClass ( ) ; Class superClazz = clazz . getSuperclass ( ) ; StringBuilder builder = new StringBuilder ( clazz . getName ( ) ) ; builder . append ( \"@\" ) ; builder . append ( Integer . toHexString ( object . hashCode ( ) ) ) ; builder . append ( \"[\" ) ; Method [ ] methods = clazz . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method method = methods [ i ] ; if ( ! isSimpleType ( method . getReturnType ( ) ) ) { continue ; } String methodName = method . getName ( ) ; if ( methodName . startsWith ( \"get\" ) && ! Modifier . isStatic ( method . getModifiers ( ) ) && Modifier . isPublic ( method . getModifiers ( ) ) ) { try { Object value = method . invoke ( object ) ; String propertyName = methodName . substring ( 3 , 4 ) . toLowerCase ( ) + methodName . substring ( 4 ) ; builder . append ( propertyName ) ; builder . append ( \"=\" ) ; if ( value == null ) { builder . append ( \"<null>\" ) ; } else { if ( value . getClass ( ) . isArray ( ) ) { int arraysuperLength = Array . getLength ( value ) ; builder . append ( \"{\" ) ; for ( int j = 0 ; j < arraysuperLength ; j ++ ) { Object object2 = Array . get ( value , j ) ; builder . append ( object2 . toString ( ) ) ; if ( j < arraysuperLength - 1 ) { builder . append ( \", \" ) ; } } builder . append ( \"}\" ) ; } else { builder . append ( value . toString ( ) ) ; } } builder . append ( \", \" ) ; } catch ( IllegalArgumentException e ) { } catch ( IllegalAccessException e ) { } catch ( InvocationTargetException e ) { } } } if ( builder . toString ( ) . contains ( \", \" ) ) { builder . replace ( builder . length ( ) - 2 , builder . length ( ) , \"\" ) ; } builder . append ( \"]\" ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "比较两个数组 [CODESPLIT] public static boolean arrayEquals ( Object one , Object anotherOne ) { if ( one == null || anotherOne == null ) { return false ; } else if ( ! one . getClass ( ) . equals ( anotherOne . getClass ( ) ) || ! one . getClass ( ) . isArray ( ) ) { return false ; } else if ( Array . getLength ( one ) != Array . getLength ( anotherOne ) ) { return false ; } return arrayHashCode ( one ) == arrayHashCode ( anotherOne ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据类名获取首字母消息的名称 <br > 2014年2月25日 下午3 : 25 : 46 [CODESPLIT] public static String getClassToBeanName ( Class < ? > clazz ) { String simpleName = clazz . getSimpleName ( ) ; String firstWord = simpleName . substring ( 0 , 1 ) . toLowerCase ( ) ; String otherWords = simpleName . substring ( 1 ) ; return firstWord + otherWords ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Delegates to { @link #detectCodepage ( java . io . InputStream int ) } with a buffered input stream of size 10 ( 8 needed as maximum ) . < / p > [CODESPLIT] public Charset detectCodepage ( URL url ) throws IOException { Charset result ; BufferedInputStream in = new BufferedInputStream ( url . openStream ( ) ) ; result = this . detectCodepage ( in , Integer . MAX_VALUE ) ; in . close ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "读取属性文件 [CODESPLIT] public static Map < String , String > readProperties ( File propertiesFile ) { if ( ! propertiesFile . exists ( ) ) { return null ; } InputStream inputStream = null ; try { inputStream = new FileInputStream ( propertiesFile ) ; return readProperties ( inputStream ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( inputStream != null ) { try { inputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the { @link javax . xml . stream . XMLStreamReader } for the given StAX Source . [CODESPLIT] public static XMLStreamReader getXMLStreamReader ( Source source ) { if ( source instanceof StAXSource ) { return ( ( StAXSource ) source ) . getXMLStreamReader ( ) ; } else if ( source instanceof StaxSource ) { return ( ( StaxSource ) source ) . getXMLStreamReader ( ) ; } else { throw new IllegalArgumentException ( \"Source '\" + source + \"' is neither StaxSource nor StAXSource\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the { @link javax . xml . stream . XMLEventReader } for the given StAX Source . [CODESPLIT] public static XMLEventReader getXMLEventReader ( Source source ) { if ( source instanceof StAXSource ) { return ( ( StAXSource ) source ) . getXMLEventReader ( ) ; } else if ( source instanceof StaxSource ) { return ( ( StaxSource ) source ) . getXMLEventReader ( ) ; } else { throw new IllegalArgumentException ( \"Source '\" + source + \"' is neither StaxSource nor StAXSource\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the { @link javax . xml . stream . XMLStreamWriter } for the given StAX Result . [CODESPLIT] public static XMLStreamWriter getXMLStreamWriter ( Result result ) { if ( result instanceof StAXResult ) { return ( ( StAXResult ) result ) . getXMLStreamWriter ( ) ; } else if ( result instanceof StaxResult ) { return ( ( StaxResult ) result ) . getXMLStreamWriter ( ) ; } else { throw new IllegalArgumentException ( \"Result '\" + result + \"' is neither StaxResult nor StAXResult\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the { @link javax . xml . stream . XMLEventWriter } for the given StAX Result . [CODESPLIT] public static XMLEventWriter getXMLEventWriter ( Result result ) { if ( result instanceof StAXResult ) { return ( ( StAXResult ) result ) . getXMLEventWriter ( ) ; } else if ( result instanceof StaxResult ) { return ( ( StaxResult ) result ) . getXMLEventWriter ( ) ; } else { throw new IllegalArgumentException ( \"Result '\" + result + \"' is neither StaxResult nor StAXResult\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成密钥对 [CODESPLIT] private static void generateKeyPair ( ) throws Exception { //        /** RSA算法要求有一个可信任的随机数源 */ //        SecureRandom secureRandom = new SecureRandom(); /** 为RSA算法创建一个KeyPairGenerator对象 */ KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( ALGORITHM ) ; /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ //        keyPairGenerator.initialize(KEYSIZE, secureRandom); keyPairGenerator . initialize ( KEYSIZE ) ; /** 生成密匙对 */ KeyPair keyPair = keyPairGenerator . generateKeyPair ( ) ; /** 得到公钥 */ Key publicKey = keyPair . getPublic ( ) ; /** 得到私钥 */ Key privateKey = keyPair . getPrivate ( ) ; ObjectOutputStream oos1 = null ; ObjectOutputStream oos2 = null ; try { /** 用对象流将生成的密钥写入文件 */ oos1 = new ObjectOutputStream ( new FileOutputStream ( PUBLIC_KEY_FILE ) ) ; oos2 = new ObjectOutputStream ( new FileOutputStream ( PRIVATE_KEY_FILE ) ) ; oos1 . writeObject ( publicKey ) ; oos2 . writeObject ( privateKey ) ; } catch ( Exception e ) { throw e ; } finally { /** 清空缓存，关闭文件输出流 */ oos1 . close ( ) ; oos2 . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加密方法 [CODESPLIT] private static String encrypt ( String source ) throws Exception { generateKeyPair ( ) ; Key publicKey ; ObjectInputStream ois = null ; try { /** 将文件中的公钥对象读出 */ ois = new ObjectInputStream ( new FileInputStream ( PUBLIC_KEY_FILE ) ) ; publicKey = ( Key ) ois . readObject ( ) ; } catch ( Exception e ) { throw e ; } finally { ois . close ( ) ; } /** 得到Cipher对象来实现对源数据的RSA加密 */ Cipher cipher = Cipher . getInstance ( ALGORITHM ) ; cipher . init ( Cipher . ENCRYPT_MODE , publicKey ) ; byte [ ] b = source . getBytes ( ) ; /** 执行加密操作 */ byte [ ] b1 = cipher . doFinal ( b ) ; BASE64Encoder encoder = new BASE64Encoder ( ) ; return encoder . encode ( b1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解密算法 [CODESPLIT] private static String decrypt ( String cryptograph ) throws Exception { Key privateKey ; ObjectInputStream ois = null ; try { /** 将文件中的私钥对象读出 */ ois = new ObjectInputStream ( new FileInputStream ( PRIVATE_KEY_FILE ) ) ; privateKey = ( Key ) ois . readObject ( ) ; } catch ( Exception e ) { throw e ; } finally { ois . close ( ) ; } /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */ Cipher cipher = Cipher . getInstance ( ALGORITHM ) ; cipher . init ( Cipher . DECRYPT_MODE , privateKey ) ; BASE64Decoder decoder = new BASE64Decoder ( ) ; byte [ ] b1 = decoder . decodeBuffer ( cryptograph ) ; /** 执行解密操作 */ byte [ ] b = cipher . doFinal ( b1 ) ; return new String ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成密钥对 [CODESPLIT] public KeyPair generatorKeyPair ( String algorithm , int keySize ) throws NoSuchAlgorithmException { /** 为RSA算法创建一个KeyPairGenerator对象 */ KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm ) ; /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ //        keyPairGenerator.initialize(KEYSIZE, secureRandom); keyPairGenerator . initialize ( keySize ) ; /** 生成密匙对 */ KeyPair keyPair = keyPairGenerator . generateKeyPair ( ) ; return keyPair ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解密算法 [CODESPLIT] public String decrypt ( String cryptograph , KeyPair keyPair ) throws Exception { return decrypt ( cryptograph , keyPair . getPrivate ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the given exception is compatible with the exceptions declared in a throws clause . [CODESPLIT] public static boolean isCompatibleWithThrowsClause ( Throwable ex , Class < ? > [ ] declaredExceptions ) { if ( ! isCheckedException ( ex ) ) { return true ; } if ( declaredExceptions != null ) { int i = 0 ; while ( i < declaredExceptions . length ) { if ( declaredExceptions [ i ] . isAssignableFrom ( ex . getClass ( ) ) ) { return true ; } i ++ ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将对象序列化到文件 [CODESPLIT] public static File writeObjectToFile ( File folder , Serializable serializable ) throws IOException { Assert . notNull ( folder , \"文件夹不能为空\");   if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } Assert . isTrue ( folder . isDirectory ( ) , folder + \"不是文件夹\");   File file = new File ( folder , System . currentTimeMillis ( ) + nextIndex ( ) + \"\" ) ; ObjectOutputStream outputStream = new ObjectOutputStream ( new FileOutputStream ( file ) ) ; outputStream . writeObject ( serializable ) ; outputStream . flush ( ) ; outputStream . close ( ) ; return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回固定长度的 [CODESPLIT] private static String nextIndex ( ) { String rs = \"\" ; synchronized ( SerializeHelper . class ) { rs += ++ index < 0 ? - index : index ; int least = 3 - rs . length ( ) ; for ( int i = 0 ; i < least ; i ++ ) { rs = \"0\" + rs ; } return rs ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public synchronized Charset detectCodepage ( InputStream in , int length ) throws IOException { this . Reset ( ) ; int len ; int read = 0 ; boolean done = false ; boolean isAscii = true ; Charset ret = null ; do { len = in . read ( buf , 0 , Math . min ( buf . length , length - read ) ) ; if ( len > 0 ) { read += len ; } if ( ! done ) done = det . DoIt ( buf , len , false ) ; } while ( len > 0 && ! done ) ; det . DataEnd ( ) ; if ( this . codpage == null ) { if ( this . m_guessing ) { ret = guess ( ) ; } else { ret = UnknownCharset . getInstance ( ) ; } } else { ret = this . codpage ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the bindings for this namespace context . The supplied map must consist of string key value pairs . [CODESPLIT] public void setBindings ( Map < String , String > bindings ) { for ( Map . Entry < String , String > entry : bindings . entrySet ( ) ) { bindNamespaceUri ( entry . getKey ( ) , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the given prefix to the given namespace . [CODESPLIT] public void bindNamespaceUri ( String prefix , String namespaceUri ) { Assert . notNull ( prefix , \"No prefix given\" ) ; Assert . notNull ( namespaceUri , \"No namespaceUri given\" ) ; if ( XMLConstants . DEFAULT_NS_PREFIX . equals ( prefix ) ) { defaultNamespaceUri = namespaceUri ; } else { prefixToNamespaceUri . put ( prefix , namespaceUri ) ; getPrefixesInternal ( namespaceUri ) . add ( prefix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the given prefix from this context . [CODESPLIT] public void removeBinding ( String prefix ) { if ( XMLConstants . DEFAULT_NS_PREFIX . equals ( prefix ) ) { defaultNamespaceUri = \"\" ; } else { String namespaceUri = prefixToNamespaceUri . remove ( prefix ) ; List < String > prefixes = getPrefixesInternal ( namespaceUri ) ; prefixes . remove ( prefix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用工具获取文件的编码方式 [CODESPLIT] public static synchronized String getEncodeByUtil ( File file ) { CodepageDetectorProxy detector = CodepageDetectorProxy . getInstance ( ) ; detector . add ( new ParsingDetector ( false ) ) ; detector . add ( JChardetFacade . getInstance ( ) ) ; // 用到antlr.jar、chardet.jar // ASCIIDetector用于ASCII编码测定 detector . add ( ASCIIDetector . getInstance ( ) ) ; // UnicodeDetector用于Unicode家族编码的测定 //        detector.add(UnicodeDetector.getInstance()); Charset charset = null ; try { charset = detector . detectCodepage ( file . toURI ( ) . toURL ( ) ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } if ( charset != null ) return charset . name ( ) ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取加载的所有类 [CODESPLIT] public static Class [ ] getAllClasses ( ) { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Class < ? > cla = classLoader . getClass ( ) ; while ( cla != ClassLoader . class ) cla = cla . getSuperclass ( ) ; Field field = null ; try { field = cla . getDeclaredField ( \"classes\" ) ; field . setAccessible ( true ) ; Vector < Class > v = null ; try { v = ( Vector < Class > ) field . get ( classLoader ) ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { System . out . println ( v . get ( i ) ) ; } return v . toArray ( new Class [ ] { } ) ; } catch ( NoSuchFieldException e ) { e . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检查类是否直接或间接实现接口 [CODESPLIT] public static boolean isImplementsInterface ( Class clazz , Class enterface ) { Assert . notNull ( clazz ) ; Assert . notNull ( enterface ) ; Class [ ] interfaces = clazz . getInterfaces ( ) ; Class superclass = clazz . getSuperclass ( ) ; if ( superclass != null ) { boolean implementsInterface = isImplementsInterface ( superclass , enterface ) ; if ( implementsInterface ) { return true ; } } boolean flag = false ; for ( Class anInterface : interfaces ) { if ( enterface == anInterface ) { return true ; } else { flag = isImplementsInterface ( anInterface , enterface ) ; if ( flag ) { return flag ; } } } return flag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given String into a single { @code MimeType } . [CODESPLIT] public static MimeType parseMimeType ( String mimeType ) { if ( ! StringUtils . hasLength ( mimeType ) ) { throw new InvalidMimeTypeException ( mimeType , \"'mimeType' must not be empty\" ) ; } String [ ] parts = StringUtils . tokenizeToStringArray ( mimeType , \";\" ) ; String fullType = parts [ 0 ] . trim ( ) ; // java.net.HttpURLConnection returns a *; q=.2 Accept header if ( MimeType . WILDCARD_TYPE . equals ( fullType ) ) { fullType = \"*/*\" ; } int subIndex = fullType . indexOf ( ' ' ) ; if ( subIndex == - 1 ) { throw new InvalidMimeTypeException ( mimeType , \"does not contain '/'\" ) ; } if ( subIndex == fullType . length ( ) - 1 ) { throw new InvalidMimeTypeException ( mimeType , \"does not contain subtype after '/'\" ) ; } String type = fullType . substring ( 0 , subIndex ) ; String subtype = fullType . substring ( subIndex + 1 , fullType . length ( ) ) ; if ( MimeType . WILDCARD_TYPE . equals ( type ) && ! MimeType . WILDCARD_TYPE . equals ( subtype ) ) { throw new InvalidMimeTypeException ( mimeType , \"wildcard type is legal only in '*/*' (all mime types)\" ) ; } Map < String , String > parameters = null ; if ( parts . length > 1 ) { parameters = new LinkedHashMap < String , String > ( parts . length - 1 ) ; for ( int i = 1 ; i < parts . length ; i ++ ) { String parameter = parts [ i ] ; int eqIndex = parameter . indexOf ( ' ' ) ; if ( eqIndex != - 1 ) { String attribute = parameter . substring ( 0 , eqIndex ) ; String value = parameter . substring ( eqIndex + 1 , parameter . length ( ) ) ; parameters . put ( attribute , value ) ; } } } try { return new MimeType ( type , subtype , parameters ) ; } catch ( UnsupportedCharsetException ex ) { throw new InvalidMimeTypeException ( mimeType , \"unsupported charset '\" + ex . getCharsetName ( ) + \"'\" ) ; } catch ( IllegalArgumentException ex ) { throw new InvalidMimeTypeException ( mimeType , ex . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given comma - separated string into a list of { @code MimeType } objects . [CODESPLIT] public static List < MimeType > parseMimeTypes ( String mimeTypes ) { if ( ! StringUtils . hasLength ( mimeTypes ) ) { return Collections . emptyList ( ) ; } String [ ] tokens = mimeTypes . split ( \",\\\\s*\" ) ; List < MimeType > result = new ArrayList < MimeType > ( tokens . length ) ; for ( String token : tokens ) { result . add ( parseMimeType ( token ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts the given list of { @code MimeType } objects by specificity . <p > Given two mime types : <ol > <li > if either mime type has a { @linkplain MimeType#isWildcardType () wildcard type } then the mime type without the wildcard is ordered before the other . < / li > <li > if the two mime types have different { @linkplain MimeType#getType () types } then they are considered equal and remain their current order . < / li > <li > if either mime type has a { @linkplain MimeType#isWildcardSubtype () wildcard subtype } then the mime type without the wildcard is sorted before the other . < / li > <li > if the two mime types have different { @linkplain MimeType#getSubtype () subtypes } then they are considered equal and remain their current order . < / li > <li > if the two mime types have a different amount of { @linkplain MimeType#getParameter ( String ) parameters } then the mime type with the most parameters is ordered before the other . < / li > < / ol > <p > For example : <blockquote > audio / basic &lt ; audio / * &lt ; * &#047 ; * < / blockquote > <blockquote > audio / basic ; level = 1 &lt ; audio / basic< / blockquote > <blockquote > audio / basic == text / html< / blockquote > <blockquote > audio / basic == audio / wave< / blockquote > [CODESPLIT] public static void sortBySpecificity ( List < MimeType > mimeTypes ) { Assert . notNull ( mimeTypes , \"'mimeTypes' must not be null\" ) ; if ( mimeTypes . size ( ) > 1 ) { Collections . sort ( mimeTypes , SPECIFICITY_COMPARATOR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Charset detectCodepage ( final InputStream in , final int length ) throws IOException { EncodingLexer lexer ; EncodingParser parser ; Charset charset = null ; String csName = null ; InputStream limitedInputStream = new LimitedInputStream ( in , length ) ; if ( this . m_verbose ) { System . out . println ( \"  parsing for html-charset/xml-encoding attribute with codepage: US-ASCII\" ) ; } try { lexer = new EncodingLexer ( new InputStreamReader ( limitedInputStream , \"US-ASCII\" ) ) ; parser = new EncodingParser ( lexer ) ; csName = parser . htmlDocument ( ) ; if ( csName != null ) { // TODO: prepare document with illegal value, then test: Decide to catch // exception and return // UnsupportedCharset. try { charset = Charset . forName ( csName ) ; } catch ( UnsupportedCharsetException uce ) { charset = UnsupportedCharset . forName ( csName ) ; } } else { charset = UnknownCharset . getInstance ( ) ; } } catch ( ANTLRException ae ) { if ( this . m_verbose ) { System . out . println ( \"  ANTLR parser exception: \" + ae . getMessage ( ) ) ; } } catch ( Exception deepdown ) { if ( this . m_verbose ) { System . out . println ( \"  Decoding Exception: \" + deepdown . getMessage ( ) + \" (unsupported java charset).\" ) ; } if ( charset == null ) { if ( csName != null ) { charset = UnsupportedCharset . forName ( csName ) ; } else { charset = UnknownCharset . getInstance ( ) ; } } } return charset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect the validation mode for the XML document in the supplied { @link java . io . InputStream } . Note that the supplied { @link java . io . InputStream } is closed by this method before returning . [CODESPLIT] public int detectValidationMode ( InputStream inputStream ) throws IOException { // Peek into the file to look for DOCTYPE. BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; try { boolean isDtdValidated = false ; String content ; while ( ( content = reader . readLine ( ) ) != null ) { content = consumeCommentTokens ( content ) ; if ( this . inComment || ! StringUtils . hasText ( content ) ) { continue ; } if ( hasDoctype ( content ) ) { isDtdValidated = true ; break ; } if ( hasOpeningTag ( content ) ) { // End of meaningful data... break ; } } return ( isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD ) ; } catch ( CharConversionException ex ) { // Choked on some character encoding... // Leave the decision up to the caller. return VALIDATION_AUTO ; } finally { reader . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does the supplied content contain an XML opening tag . If the parse state is currently in an XML comment then this method always returns false . It is expected that all comment tokens will have consumed for the supplied content before passing the remainder to this method . [CODESPLIT] private boolean hasOpeningTag ( String content ) { if ( this . inComment ) { return false ; } int openTagIndex = content . indexOf ( ' ' ) ; return ( openTagIndex > - 1 && content . length ( ) > openTagIndex && Character . isLetter ( content . charAt ( openTagIndex + 1 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes all the leading comment data in the given String and returns the remaining content which may be empty since the supplied content might be all comment data . For our purposes it is only important to strip leading comment content on a line since the first piece of non comment content will be either the DOCTYPE declaration or the root element of the document . [CODESPLIT] private String consumeCommentTokens ( String line ) { if ( line . indexOf ( START_COMMENT ) == - 1 && line . indexOf ( END_COMMENT ) == - 1 ) { return line ; } while ( ( line = consume ( line ) ) != null ) { if ( ! this . inComment && ! line . trim ( ) . startsWith ( START_COMMENT ) ) { return line ; } } return line ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consume the next comment token update the inComment flag and return the remaining content . [CODESPLIT] private String consume ( String line ) { int index = ( this . inComment ? endComment ( line ) : startComment ( line ) ) ; return ( index == - 1 ? null : line . substring ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to consume the supplied token against the supplied content and update the in comment parse state to the supplied value . Returns the index into the content which is after the token or - 1 if the token is not found . [CODESPLIT] private int commentToken ( String line , String token , boolean inCommentIfPresent ) { int index = line . indexOf ( token ) ; if ( index > - 1 ) { this . inComment = inCommentIfPresent ; } return ( index == - 1 ? index : index + token . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "计算日期之间相差多少天 [CODESPLIT] public static int diffOfDay ( Date date1 , Date date2 ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( date1 . getTime ( ) ) ; int i = calendar . get ( Calendar . DAY_OF_YEAR ) ; Calendar calendar2 = Calendar . getInstance ( ) ; calendar2 . setTimeInMillis ( date2 . getTime ( ) ) ; int i2 = calendar2 . get ( Calendar . DAY_OF_YEAR ) ; return i2 - i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取现在时间 [CODESPLIT] public static Date getNowDate ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; ParsePosition pos = new ParsePosition ( 8 ) ; Date currentTime_2 = FORMATTER_LONG . parse ( dateString , pos ) ; return currentTime_2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取现在时间 [CODESPLIT] public static Date getNowDateShort ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_SHORT . format ( currentTime ) ; ParsePosition pos = new ParsePosition ( 8 ) ; Date currentTime_2 = FORMATTER_SHORT . parse ( dateString , pos ) ; return currentTime_2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取现在时间 [CODESPLIT] public static String getStringDate ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; return dateString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取现在时间 [CODESPLIT] public static String getStringDateShort ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_SHORT . format ( currentTime ) ; return dateString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取时间 小时 : 分 ; 秒 HH : mm : ss [CODESPLIT] public static String getTimeShort ( ) { SimpleDateFormat formatter = new SimpleDateFormat ( \"HH:mm:ss\" ) ; Date currentTime = new Date ( ) ; String dateString = formatter . format ( currentTime ) ; return dateString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将长时间格式字符串转换为时间 yyyy - MM - dd HH : mm : ss [CODESPLIT] public static Date strToDateLong ( String strDate ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = FORMATTER_LONG . parse ( strDate , pos ) ; return strtodate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "字符串转换为时间 [CODESPLIT] public static Date strToDate ( String strDate , String dateFormat ) { return strToDate ( strDate , new SimpleDateFormat ( dateFormat ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "字符串转换为时间 [CODESPLIT] public static Date strToDate ( String strDate , DateFormat dateFormat ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = dateFormat . parse ( strDate , pos ) ; return strtodate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将长时间格式时间转换为字符串 yyyy - MM - dd HH : mm : ss [CODESPLIT] public static String dateToStrLong ( Date dateDate ) { String dateString = FORMATTER_LONG . format ( dateDate ) ; return dateString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将短时间格式时间转换为字符串 yyyy - MM - dd [CODESPLIT] public static String dateToStr ( Date dateDate ) { String dateString = FORMATTER_SHORT . format ( dateDate ) ; return dateString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将短时间格式字符串转换为时间 yyyy - MM - dd [CODESPLIT] public static Date strToDate ( String strDate ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = FORMATTER_SHORT . parse ( strDate , pos ) ; return strtodate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "提取一个月中的最后一天 [CODESPLIT] public static Date getLastDate ( long day ) { Date date = new Date ( ) ; long date_3_hm = date . getTime ( ) - 3600000 * 34 * day ; Date date_3_hm_date = new Date ( date_3_hm ) ; return date_3_hm_date ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到现在时间 [CODESPLIT] public static String getStringToday ( ) { Date currentTime = new Date ( ) ; SimpleDateFormat formatter = new SimpleDateFormat ( \"yyyyMMdd HHmmss\" ) ; String dateString = formatter . format ( currentTime ) ; return dateString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到现在小时 [CODESPLIT] public static String getHour ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; String hour ; hour = dateString . substring ( 11 , 13 ) ; return hour ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到现在分钟 [CODESPLIT] public static String getTime ( ) { Date currentTime = new Date ( ) ; String dateString = FORMATTER_LONG . format ( currentTime ) ; String min ; min = dateString . substring ( 14 , 16 ) ; return min ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据用户传入的时间表示格式，返回当前时间的格式 如果是yyyyMMdd，注意字母y不能大写。 [CODESPLIT] public static String getUserDate ( String sformat ) { Date currentTime = new Date ( ) ; SimpleDateFormat formatter = new SimpleDateFormat ( sformat ) ; String dateString = formatter . format ( currentTime ) ; return dateString ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "二个小时时间间的差值 必须保证二个时间都是 HH : MM 的格式，返回字符型的分钟 [CODESPLIT] public static String getTwoHour ( String st1 , String st2 ) { String [ ] kk = null ; String [ ] jj = null ; kk = st1 . split ( \":\" ) ; jj = st2 . split ( \":\" ) ; if ( Integer . parseInt ( kk [ 0 ] ) < Integer . parseInt ( jj [ 0 ] ) ) return \"0\" ; else { double y = Double . parseDouble ( kk [ 0 ] ) + Double . parseDouble ( kk [ 1 ] ) / 60 ; double u = Double . parseDouble ( jj [ 0 ] ) + Double . parseDouble ( jj [ 1 ] ) / 60 ; if ( ( y - u ) > 0 ) return y - u + \"\" ; else return \"0\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到二个日期间的间隔天数 [CODESPLIT] public static String getTwoDay ( String sj1 , String sj2 ) { SimpleDateFormat myFormatter = new SimpleDateFormat ( \"yyyy-MM-dd\" ) ; long day = 0 ; try { Date date = myFormatter . parse ( sj1 ) ; Date mydate = myFormatter . parse ( sj2 ) ; day = ( date . getTime ( ) - mydate . getTime ( ) ) / ( 24 * 60 * 60 * 1000 ) ; } catch ( Exception e ) { return \"\" ; } return day + \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "时间前推或后推分钟 其中JJ表示分钟 . [CODESPLIT] public static String getPreTime ( String sj1 , String jj ) { SimpleDateFormat format = new SimpleDateFormat ( \"yyyy-MM-dd HH:mm:ss\" ) ; String mydate1 = \"\" ; try { Date date1 = format . parse ( sj1 ) ; long Time = ( date1 . getTime ( ) / 1000 ) + Integer . parseInt ( jj ) * 60 ; date1 . setTime ( Time * 1000 ) ; mydate1 = format . format ( date1 ) ; } catch ( Exception e ) { } return mydate1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到一个时间延后或前移几天的时间 nowdate为时间 delay为前移或后延的天数 [CODESPLIT] public static Date getNextDay ( Date nowDate , int delay ) { long myTime = ( nowDate . getTime ( ) / 1000 ) + delay * 24 * 60 * 60 ; Date date = new Date ( ) ; date . setTime ( myTime * 1000 ) ; return date ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到一个时间延后或前移几天的时间 nowdate为时间 delay为前移或后延的天数 [CODESPLIT] public static String getNextDay ( String nowDate , int delay ) { try { SimpleDateFormat format = new SimpleDateFormat ( \"yyyy-MM-dd\" ) ; String mdate = \"\" ; Date d = strToDate ( nowDate ) ; long myTime = ( d . getTime ( ) / 1000 ) + delay * 24 * 60 * 60 ; d . setTime ( myTime * 1000 ) ; mdate = format . format ( d ) ; return mdate ; } catch ( Exception e ) { return \"\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断是否润年 [CODESPLIT] public static boolean isLeapYear ( String ddate ) { /**\n         * 详细设计： 1.被400整除是闰年，否则： 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年\n         * 3.能被4整除同时能被100整除则不是闰年\n         */ Date d = strToDate ( ddate ) ; GregorianCalendar gc = ( GregorianCalendar ) Calendar . getInstance ( ) ; gc . setTime ( d ) ; int year = gc . get ( Calendar . YEAR ) ; if ( ( year % 400 ) == 0 ) return true ; else if ( ( year % 4 ) == 0 ) { if ( ( year % 100 ) == 0 ) return false ; else return true ; } else return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回美国时间格式 26 Apr 2006 [CODESPLIT] public static String getEDate ( String str ) { ParsePosition pos = new ParsePosition ( 0 ) ; Date strtodate = FORMATTER_SHORT . parse ( str , pos ) ; String j = strtodate . toString ( ) ; String [ ] k = j . split ( \" \" ) ; return k [ 2 ] + k [ 1 ] . toUpperCase ( ) + k [ 5 ] . substring ( 2 , 4 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取一个月的最后一天 [CODESPLIT] public static String getEndDateOfMonth ( String dat ) { // yyyy-MM-dd String str = dat . substring ( 0 , 8 ) ; String month = dat . substring ( 5 , 7 ) ; int mon = Integer . parseInt ( month ) ; if ( mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12 ) { str += \"31\" ; } else if ( mon == 4 || mon == 6 || mon == 9 || mon == 11 ) { str += \"30\" ; } else { if ( isLeapYear ( dat ) ) { str += \"29\" ; } else { str += \"28\" ; } } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断二个时间是否在同一个周 [CODESPLIT] public static boolean isSameWeekDates ( Date date1 , Date date2 ) { Calendar cal1 = Calendar . getInstance ( ) ; Calendar cal2 = Calendar . getInstance ( ) ; cal1 . setTime ( date1 ) ; cal2 . setTime ( date2 ) ; int subYear = cal1 . get ( Calendar . YEAR ) - cal2 . get ( Calendar . YEAR ) ; if ( 0 == subYear ) { if ( cal1 . get ( Calendar . WEEK_OF_YEAR ) == cal2 . get ( Calendar . WEEK_OF_YEAR ) ) return true ; } else if ( 1 == subYear && 11 == cal2 . get ( Calendar . MONTH ) ) { // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周 if ( cal1 . get ( Calendar . WEEK_OF_YEAR ) == cal2 . get ( Calendar . WEEK_OF_YEAR ) ) return true ; } else if ( - 1 == subYear && 11 == cal1 . get ( Calendar . MONTH ) ) { if ( cal1 . get ( Calendar . WEEK_OF_YEAR ) == cal2 . get ( Calendar . WEEK_OF_YEAR ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "产生周序列 即得到当前时间所在的年度是第几周 [CODESPLIT] public static String getSeqWeek ( ) { Calendar c = Calendar . getInstance ( Locale . CHINA ) ; String week = Integer . toString ( c . get ( Calendar . WEEK_OF_YEAR ) ) ; if ( week . length ( ) == 1 ) week = \"0\" + week ; String year = Integer . toString ( c . get ( Calendar . YEAR ) ) ; return year + week ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获得一个日期所在的周的星期几的日期，如要找出2002年2月3日所在周的星期一是几号 [CODESPLIT] public static String getWeek ( String sdate , String num ) { // 再转换为时间 Date dd = DateHelper . strToDate ( sdate ) ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( dd ) ; if ( num . equals ( \"1\" ) ) // 返回星期一所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . MONDAY ) ; else if ( num . equals ( \"2\" ) ) // 返回星期二所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . TUESDAY ) ; else if ( num . equals ( \"3\" ) ) // 返回星期三所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . WEDNESDAY ) ; else if ( num . equals ( \"4\" ) ) // 返回星期四所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . THURSDAY ) ; else if ( num . equals ( \"5\" ) ) // 返回星期五所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . FRIDAY ) ; else if ( num . equals ( \"6\" ) ) // 返回星期六所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . SATURDAY ) ; else if ( num . equals ( \"0\" ) ) // 返回星期日所在的日期 c . set ( Calendar . DAY_OF_WEEK , Calendar . SUNDAY ) ; return new SimpleDateFormat ( \"yyyy-MM-dd\" ) . format ( c . getTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据一个日期，返回是星期几的字符串 [CODESPLIT] public static String getWeek ( String sdate ) { // 再转换为时间 Date date = DateHelper . strToDate ( sdate ) ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( date ) ; // int hour=c.get(Calendar.DAY_OF_WEEK); // hour中存的就是星期几了，其范围 1~7 // 1=星期日 7=星期六，其他类推 return new SimpleDateFormat ( \"EEEE\" ) . format ( c . getTime ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "两个时间之间的天数 [CODESPLIT] public static long getDays ( String date1 , String date2 ) { if ( date1 == null || date1 . equals ( \"\" ) ) return 0 ; if ( date2 == null || date2 . equals ( \"\" ) ) return 0 ; // 转换为标准时间 SimpleDateFormat myFormatter = new SimpleDateFormat ( \"yyyy-MM-dd\" ) ; Date date = null ; Date mydate = null ; try { date = myFormatter . parse ( date1 ) ; mydate = myFormatter . parse ( date2 ) ; } catch ( Exception e ) { } long day = ( date . getTime ( ) - mydate . getTime ( ) ) / ( 24 * 60 * 60 * 1000 ) ; return day ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "形成如下的日历 ， 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间 此函数返回该日历第一行星期日所在的日期 [CODESPLIT] public static String getNowMonth ( String sdate ) { // 取该时间所在月的一号 sdate = sdate . substring ( 0 , 8 ) + \"01\" ; // 得到这个月的1号是星期几 Date date = DateHelper . strToDate ( sdate ) ; Calendar c = Calendar . getInstance ( ) ; c . setTime ( date ) ; int u = c . get ( Calendar . DAY_OF_WEEK ) ; String newday = DateHelper . getNextDay ( sdate , 1 - u ) ; return newday ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回一个随机数 [CODESPLIT] public static String getRandom ( int i ) { Random jjj = new Random ( ) ; // int suiJiShu = jjj.nextInt(9); if ( i == 0 ) return \"\" ; String jj = \"\" ; for ( int k = 0 ; k < i ; k ++ ) { jj = jj + jjj . nextInt ( 9 ) ; } return jj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取时间的日期（转换为0时） [CODESPLIT] public static Date getDay ( Date date ) { //        long time = date.getTime() / 1000; //        System.out.println(time); //        System.out.println(CalendarHelper.DAY); //        long day = 24 * 60 * 60; //        System.out.println(time % (day * 1000)); //        System.out.println((time % day) / CalendarHelper.HOUR); //        time = time - (time % day); //        Date date1 = new Date(time * 1000); String dateStr = FORMATTER_SHORT . format ( date ) ; Date date1 = strToDate ( dateStr , FORMATTER_SHORT ) ; return date1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize log4j from the given file location with no config file refreshing . Assumes an XML file in case of a . xml file extension and a properties file otherwise . [CODESPLIT] public static void initLogging ( String location ) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils . resolvePlaceholders ( location ) ; URL url = ResourceUtils . getURL ( resolvedLocation ) ; if ( resolvedLocation . toLowerCase ( ) . endsWith ( XML_FILE_EXTENSION ) ) { DOMConfigurator . configure ( url ) ; } else { PropertyConfigurator . configure ( url ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize log4j from the given location with the given refresh interval for the config file . Assumes an XML file in case of a . xml file extension and a properties file otherwise . <p > Log4j s watchdog thread will asynchronously check whether the timestamp of the config file has changed using the given interval between checks . A refresh interval of 1000 milliseconds ( one second ) which allows to do on - demand log level changes with immediate effect is not unfeasible . <p > <b > WARNING : < / b > Log4j s watchdog thread does not terminate until VM shutdown ; in particular it does not terminate on LogManager shutdown . Therefore it is recommended to <i > not< / i > use config file refreshing in a production J2EE environment ; the watchdog thread would not stop on application shutdown there . [CODESPLIT] public static void initLogging ( String location , long refreshInterval ) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils . resolvePlaceholders ( location ) ; File file = ResourceUtils . getFile ( resolvedLocation ) ; if ( ! file . exists ( ) ) { throw new FileNotFoundException ( \"Log4j config file [\" + resolvedLocation + \"] not found\" ) ; } if ( resolvedLocation . toLowerCase ( ) . endsWith ( XML_FILE_EXTENSION ) ) { DOMConfigurator . configureAndWatch ( file . getAbsolutePath ( ) , refreshInterval ) ; } else { PropertyConfigurator . configureAndWatch ( file . getAbsolutePath ( ) , refreshInterval ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the given prefix to the given namespaces . [CODESPLIT] @ Override public final void startPrefixMapping ( String prefix , String uri ) { namespaceContext . bindNamespaceUri ( prefix , uri ) ; namespaceContextChanged = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a namespace URI and DOM or SAX qualified name to a { @code QName } . The qualified name can have the form { @code prefix : localname } or { @code localName } . [CODESPLIT] protected QName toQName ( String namespaceUri , String qualifiedName ) { int idx = qualifiedName . indexOf ( ' ' ) ; if ( idx == - 1 ) { return new QName ( namespaceUri , qualifiedName ) ; } else { String prefix = qualifiedName . substring ( 0 , idx ) ; String localPart = qualifiedName . substring ( idx + 1 ) ; return new QName ( namespaceUri , localPart , prefix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add given iterator to this composite . [CODESPLIT] public void add ( Iterator < E > iterator ) { Assert . state ( ! inUse , \"You can no longer add iterator to a composite iterator that's already in use\" ) ; if ( iterators . contains ( iterator ) ) { throw new IllegalArgumentException ( \"You cannot add the same iterator twice\" ) ; } iterators . add ( iterator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "发送邮件 [CODESPLIT] @ Override public void sendEmail ( EmailVo emailVo ) throws MessagingException { Assert . notNull ( emailVo . getTo ( ) , \"接收人不能为空\");   MimeMessage msg = javaMailSenderFactory . createMimeMessage ( ) ; MimeMessageHelper msgHelper = null ; if ( ( emailVo . getInlineImageVos ( ) != null && emailVo . getInlineImageVos ( ) . size ( ) > 0 ) || ( emailVo . getAttachmentVos ( ) != null && emailVo . getAttachmentVos ( ) . size ( ) > 0 ) ) { msgHelper = new MimeMessageHelper ( msg , true , \"utf-8\" ) ; } else { msgHelper = new MimeMessageHelper ( msg , \"utf-8\" ) ; } if ( emailVo . getFrom ( ) == null || \"\" . equals ( emailVo . getFrom ( ) . trim ( ) ) ) { emailVo . setFrom ( javaMailSenderFactory . getSystemEmail ( ) ) ; } if ( ( emailVo . getCc ( ) == null || \"\" . equals ( emailVo . getCc ( ) . length == 0 ) ) && javaMailSenderFactory . getDefaultCc ( ) != null && ! javaMailSenderFactory . getDefaultCc ( ) . equals ( \"\" ) ) { emailVo . setCc ( javaMailSenderFactory . getDefaultCc ( ) . split ( \",\" ) ) ; } if ( ( emailVo . getBcc ( ) == null || \"\" . equals ( emailVo . getBcc ( ) . length == 0 ) ) && javaMailSenderFactory . getDefaultBcc ( ) != null && ! javaMailSenderFactory . getDefaultBcc ( ) . equals ( \"\" ) ) { emailVo . setBcc ( javaMailSenderFactory . getDefaultBcc ( ) . split ( \",\" ) ) ; } if ( emailVo . getMessageDate ( ) == null ) { emailVo . setMessageDate ( new Date ( ) ) ; } if ( emailVo . getCc ( ) != null ) { msgHelper . setCc ( emailVo . getCc ( ) ) ; // 抄送 } if ( emailVo . getBcc ( ) != null ) { msgHelper . setBcc ( emailVo . getBcc ( ) ) ; // 密送 } if ( emailVo . getSubject ( ) != null ) { msgHelper . setSubject ( emailVo . getSubject ( ) ) ; } handlerAttachments ( emailVo , msgHelper ) ; String from = null ; if ( emailVo . getFrom ( ) != null && ! \"\" . equals ( emailVo . getFrom ( ) ) ) { from = emailVo . getFrom ( ) ; } else { if ( javaMailSenderFactory . getEmailAccount ( ) . getFrom ( ) != null && ! \"\" . equals ( javaMailSenderFactory . getEmailAccount ( ) . getFrom ( ) ) ) { from = javaMailSenderFactory . getEmailAccount ( ) . getFrom ( ) ; } else { from = javaMailSenderFactory . getEmailAccount ( ) . getUsername ( ) ; } } try { if ( javaMailSenderFactory . getEmailAccount ( ) . getNickName ( ) != null ) { msgHelper . setFrom ( from , javaMailSenderFactory . getEmailAccount ( ) . getNickName ( ) ) ; } else { msgHelper . setFrom ( from ) ; } } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; msgHelper . setFrom ( from ) ; } msgHelper . setTo ( emailVo . getTo ( ) ) ; // 接收人 Collection < Inline > inlines = handlerInlineImages ( emailVo , msgHelper ) ; if ( emailVo . getHtml ( ) != null ) { msgHelper . setText ( emailVo . getHtml ( ) , emailVo . isHtml ( ) ) ; if ( inlines != null ) { // 添加inline for ( Inline inline : inlines ) { msgHelper . addInline ( inline . getContentId ( ) , inline . getFile ( ) ) ; } } } javaMailSenderFactory . send ( msg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理内嵌对象 [CODESPLIT] private Collection < Inline > handlerInlineImages ( EmailVo emailVo , MimeMessageHelper msgHelper ) throws MessagingException { Collection < Inline > inlines = null ; if ( emailVo . getInlineImageVos ( ) != null && emailVo . getInlineImageVos ( ) . size ( ) > 0 ) { inlines = new HashSet < Inline > ( ) ; String html = emailVo . getHtml ( ) ; if ( html == null || html . trim ( ) . equals ( \"\" ) ) { // 如果内容空或者不是 html则直接跳过 return inlines ; } //  ------------------------------------------- 查找带数字的标记 ${数字} ------------------------------------------- Matcher matcherIndexTag = PATTERN_FIND_TAG_AND_INDEX . matcher ( html ) ; int contentIdIndex = 0 ; while ( matcherIndexTag . find ( ) ) { String htmlTag = matcherIndexTag . group ( ) ; // 查找到<img src=\"${1}\" /> 的内容 Matcher matcherDollar = PATTERN_DOLLAR_VARIABLE_INDEX . matcher ( htmlTag ) ; if ( matcherDollar . find ( ) ) { String dollarFind = matcherDollar . group ( ) ; // 查找到${1}内容 String indexStr = dollarFind . replace ( \"$\" , \"\" ) . replace ( \"{\" , \"\" ) . replace ( \"}\" , \"\" ) . trim ( ) ; // 移除外面的$符号和大括号 int index = Integer . parseInt ( indexStr ) ; try { InlineImageVo inlineImageVo = emailVo . getInlineImageVos ( ) . get ( index ) ; File file = inlineImageVo . getFile ( ) ; String contentId = \"file\" + contentIdIndex ++ ; // 生成contentId //                        msgHelper.addInline(contentId, file);// 将附件内容传送给MimeMessageHelper Inline inline = new Inline ( ) ; inline . setFile ( file ) ; inline . setContentId ( contentId ) ; inlines . add ( inline ) ; htmlTag = matcherDollar . replaceAll ( \"cid:\" + contentId ) ; //                        System.out.println(\"indexStr ====== \" + indexStr); //                        System.out.println(\"htmlTag ====== \" + htmlTag); html = matcherIndexTag . replaceFirst ( htmlTag ) ; matcherIndexTag = PATTERN_FIND_TAG_AND_INDEX . matcher ( html ) ; //                        System.out.println(\"html ====== \" + html); } catch ( Exception e ) { e . printStackTrace ( ) ; } } } //  ------------------------------------------- 查找带字母变量的标记 ${variable} ------------------------------------------- Matcher matcherTag = PATTERN_FIND_TAG . matcher ( html ) ; while ( matcherTag . find ( ) ) { String htmlTag = matcherTag . group ( ) ; // 查找到<img src=\"${1}\" /> 的内容 Matcher matcherDollar = PATTERN_DOLLAR_VARIABLE_SELF_DEFINE . matcher ( htmlTag ) ; if ( matcherDollar . find ( ) ) { String dollarFind = matcherDollar . group ( ) ; // 查找到${1}内容 String dollarVariable = dollarFind . replace ( \"$\" , \"\" ) . replace ( \"{\" , \"\" ) . replace ( \"}\" , \"\" ) . trim ( ) ; // 移除外面的$符号和大括号 try { InlineImageVo inlineImageVo = null ; for ( InlineImageVo imageVo : emailVo . getInlineImageVos ( ) ) { if ( imageVo . getContentId ( ) != null && imageVo . getContentId ( ) . equals ( dollarVariable ) ) { inlineImageVo = imageVo ; } } if ( inlineImageVo == null ) { continue ; } File file = inlineImageVo . getFile ( ) ; //                        String contentId = \"file\" + contentIdIndex++; // 生成contentId //                        msgHelper.addInline(contentId, file);// 将附件内容传送给MimeMessageHelper Inline inline = new Inline ( ) ; inline . setFile ( file ) ; inline . setContentId ( inlineImageVo . getContentId ( ) ) ; inlines . add ( inline ) ; htmlTag = matcherDollar . replaceAll ( \"cid:\" + inlineImageVo . getContentId ( ) ) ; //                        System.out.println(\"htmlTag ====== \" + htmlTag); html = matcherTag . replaceFirst ( htmlTag ) ; matcherTag = PATTERN_FIND_TAG . matcher ( html ) ; //                        System.out.println(\"html ====== \" + html); } catch ( Exception e ) { e . printStackTrace ( ) ; } } } emailVo . setHtml ( html ) ; if ( inlines != null && inlines . size ( ) > 0 ) { emailVo . setHtml ( true ) ; } } return inlines ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理附件 [CODESPLIT] private void handlerAttachments ( EmailVo emailVo , MimeMessageHelper msgHelper ) throws MessagingException { if ( emailVo . getAttachmentVos ( ) != null ) { // 检查附件 for ( AttachmentVo attachmentVo : emailVo . getAttachmentVos ( ) ) { File attachment = attachmentVo . getAttachment ( ) ; if ( attachment == null ) { InputStream inputStream = attachmentVo . getAttachmentInputStream ( ) ; if ( attachmentVo . getAttachmentName ( ) == null ) { attachmentVo . setAttachmentName ( new Date ( ) . toString ( ) ) ; } InputStreamSource inputStreamSource = new InputStreamResource ( inputStream ) ; msgHelper . addAttachment ( attachmentVo . getAttachmentName ( ) , inputStreamSource ) ; } else { if ( attachmentVo . getAttachmentName ( ) == null ) { attachmentVo . setAttachmentName ( attachment . getName ( ) ) ; } try { msgHelper . addAttachment ( MimeUtility . encodeWord ( attachmentVo . getAttachmentName ( ) ) , attachment ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置继承类 [CODESPLIT] public CodeBuilder superClass ( Class < ? > clazz ) { if ( clazz . isInterface ( ) ) { System . out . println ( clazz + \"为接口对象！取消设为继承类。\");   return this ; } String simpleName = clazz . getSimpleName ( ) ; Package pkg = clazz . getPackage ( ) ; imports . add ( pkg . getName ( ) + \".\" + simpleName ) ; // 导入包 this . superClass = simpleName ; // 设置继承的类名 return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "增加接口 [CODESPLIT] public CodeBuilder addInterface ( Class < ? > interfaceClass ) { if ( ! interfaceClass . isInterface ( ) ) { System . out . println ( interfaceClass + \"不是接口类型！取消设为实现。\");   return this ; } String simpleName = interfaceClass . getSimpleName ( ) ; Package pkg = interfaceClass . getPackage ( ) ; imports . add ( pkg . getName ( ) + \".\" + simpleName ) ; // 导入包 this . interfaces . add ( simpleName ) ; // 添加实现的接口 return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "过滤包含规则 [CODESPLIT] private void filterInclude ( ) { if ( include == null || files == null ) { return ; } Set < File > toIncludes = new HashSet < File > ( ) ; for ( File file : files ) { Matcher matcher = include . matcher ( file . getPath ( ) ) ; if ( matcher . find ( ) ) { toIncludes . add ( file ) ; } } this . files = toIncludes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "过滤排除规则 [CODESPLIT] private void filterExclude ( ) { if ( exclude == null || files == null ) { return ; } Set < File > toExcludes = new HashSet < File > ( ) ; for ( File file : files ) { Matcher matcher = exclude . matcher ( file . getPath ( ) ) ; if ( matcher . find ( ) ) { toExcludes . add ( file ) ; } } files . removeAll ( toExcludes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "开始重写文件 [CODESPLIT] public void build ( ) { filterInclude ( ) ; filterExclude ( ) ; for ( final File file : files ) { ThreadPool . invoke ( new Thread ( ) { @ Override public void run ( ) { new CodeProcessor ( file , CodeBuilder . this ) ; } } ) ; // 在线程池内运行 } ThreadPool . shutDown ( ) ; // 开启停止线程 }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "或者被<code > orAnnotationClass< / code > 注解的条件，与andAnnotation方法冲突 [CODESPLIT] public CodeCondition orAnnotation ( Class < ? > orAnnotationClass ) { if ( ! orAnnotationClass . isAnnotation ( ) ) { System . out . println ( \"Class: \" + orAnnotationClass + \" 不是注解类！\");   return this ; } orAnnotatedClasses = CollectionHelper . checkOrInitHashSet ( orAnnotatedClasses ) ; orAnnotatedClasses . add ( orAnnotationClass ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "并且被<code > andAnnotationClass< / code > 注解的条件 [CODESPLIT] public CodeCondition andAnnotation ( Class < ? > andAnnotationClass ) { if ( ! andAnnotationClass . isAnnotation ( ) ) { System . out . println ( \"Class: \" + andAnnotationClass + \" 不是注解类！\");   return this ; } andAnnotatedClasses = CollectionHelper . checkOrInitHashSet ( andAnnotatedClasses ) ; andAnnotatedClasses . add ( andAnnotationClass ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "条件且 [CODESPLIT] public CodeCondition and ( CodeCondition anotherCodeCondition ) { if ( anotherCodeCondition == null ) { System . out . println ( \"CodeCondition为空！\");   return this ; } andCodeConditions = CollectionHelper . checkOrInitHashSet ( andCodeConditions ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "条件或 [CODESPLIT] public CodeCondition or ( CodeCondition anotherCodeCondition ) { if ( anotherCodeCondition == null ) { System . out . println ( \"CodeCondition为空！\");   return this ; } orCodeConditions = CollectionHelper . checkOrInitHashSet ( orCodeConditions ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "填充0 <br > 2013 - 10 - 31 下午2 : 46 : 15 [CODESPLIT] public static String fillZero ( long number , int length ) { StringBuilder builder = new StringBuilder ( ) ; int least = length - numberLength ( number ) ; char [ ] zeros = new char [ least ] ; for ( int i = 0 ; i < least ; i ++ ) { zeros [ i ] = ' ' ; } builder . append ( new String ( zeros ) ) ; builder . append ( number ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Function to return a string from the set : A - Za - z0 - 9 . / [CODESPLIT] static private final String to64 ( long v , int size ) { StringBuffer result = new StringBuffer ( ) ; while ( -- size >= 0 ) { result . append ( itoa64 . charAt ( ( int ) ( v & 0x3f ) ) ) ; v >>>= 6 ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LINUX / BSD MD5Crypt function [CODESPLIT] static public final String crypt ( String password ) { StringBuffer salt = new StringBuffer ( ) ; java . util . Random rnd = new java . util . Random ( ) ; // build a random 8 chars salt while ( salt . length ( ) < 8 ) { int index = ( int ) ( rnd . nextFloat ( ) * SALTCHARS . length ( ) ) ; salt . append ( SALTCHARS . substring ( index , index + 1 ) ) ; } // crypt return crypt ( password , salt . toString ( ) , \"$1$\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Linux / BSD MD5Crypt function [CODESPLIT] static public final String crypt ( String password , String salt , String magic ) { byte finalState [ ] ; long l ; /**\n         * Two MD5 hashes are used\n         */ MessageDigest ctx , ctx1 ; try { ctx = MessageDigest . getInstance ( \"md5\" ) ; ctx1 = MessageDigest . getInstance ( \"md5\" ) ; } catch ( NoSuchAlgorithmException ex ) { System . err . println ( ex ) ; return null ; } /* Refine the Salt first */ /* If it starts with the magic string, then skip that */ if ( salt . startsWith ( magic ) ) { salt = salt . substring ( magic . length ( ) ) ; } /* It stops at the first '$', max 8 chars */ if ( salt . indexOf ( ' ' ) != - 1 ) { salt = salt . substring ( 0 , salt . indexOf ( ' ' ) ) ; } if ( salt . length ( ) > 8 ) { salt = salt . substring ( 0 , 8 ) ; } /**\n         * Transformation set #1: The password first, since that is what is most\n         * unknown Magic string Raw salt\n         */ ctx . update ( password . getBytes ( ) ) ; ctx . update ( magic . getBytes ( ) ) ; ctx . update ( salt . getBytes ( ) ) ; /* Then just as many characters of the MD5(pw,salt,pw) */ ctx1 . update ( password . getBytes ( ) ) ; ctx1 . update ( salt . getBytes ( ) ) ; ctx1 . update ( password . getBytes ( ) ) ; finalState = ctx1 . digest ( ) ; // ctx1.Final(); for ( int pl = password . length ( ) ; pl > 0 ; pl -= 16 ) { ctx . update ( finalState , 0 , pl > 16 ? 16 : pl ) ; } /**\n         * the original code claimed that finalState was being cleared to keep\n         * dangerous bits out of memory, but doing this is also required in\n         * order to get the right output.\n         */ clearbits ( finalState ) ; /* Then something really weird... */ for ( int i = password . length ( ) ; i != 0 ; i >>>= 1 ) { if ( ( i & 1 ) != 0 ) { ctx . update ( finalState , 0 , 1 ) ; } else { ctx . update ( password . getBytes ( ) , 0 , 1 ) ; } } finalState = ctx . digest ( ) ; /**\n         * and now, just to make sure things don't run too fast On a 60 Mhz\n         * Pentium this takes 34 msec, so you would need 30 seconds to build a\n         * 1000 entry dictionary... (The above timings from the C version)\n         */ for ( int i = 0 ; i < 1000 ; i ++ ) { try { ctx1 = MessageDigest . getInstance ( \"md5\" ) ; } catch ( NoSuchAlgorithmException e0 ) { return null ; } if ( ( i & 1 ) != 0 ) { ctx1 . update ( password . getBytes ( ) ) ; } else { ctx1 . update ( finalState , 0 , 16 ) ; } if ( ( i % 3 ) != 0 ) { ctx1 . update ( salt . getBytes ( ) ) ; } if ( ( i % 7 ) != 0 ) { ctx1 . update ( password . getBytes ( ) ) ; } if ( ( i & 1 ) != 0 ) { ctx1 . update ( finalState , 0 , 16 ) ; } else { ctx1 . update ( password . getBytes ( ) ) ; } finalState = ctx1 . digest ( ) ; // Final(); } /* Now make the output string */ StringBuffer result = new StringBuffer ( ) ; result . append ( magic ) ; result . append ( salt ) ; result . append ( \"$\" ) ; /**\n         * Build a 22 byte output string from the set: A-Za-z0-9./\n         */ l = ( bytes2u ( finalState [ 0 ] ) << 16 ) | ( bytes2u ( finalState [ 6 ] ) << 8 ) | bytes2u ( finalState [ 12 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 1 ] ) << 16 ) | ( bytes2u ( finalState [ 7 ] ) << 8 ) | bytes2u ( finalState [ 13 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 2 ] ) << 16 ) | ( bytes2u ( finalState [ 8 ] ) << 8 ) | bytes2u ( finalState [ 14 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 3 ] ) << 16 ) | ( bytes2u ( finalState [ 9 ] ) << 8 ) | bytes2u ( finalState [ 15 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = ( bytes2u ( finalState [ 4 ] ) << 16 ) | ( bytes2u ( finalState [ 10 ] ) << 8 ) | bytes2u ( finalState [ 5 ] ) ; result . append ( to64 ( l , 4 ) ) ; l = bytes2u ( finalState [ 11 ] ) ; result . append ( to64 ( l , 2 ) ) ; /* Don't leave anything around in vm they could use. */ clearbits ( finalState ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从所有的 classpath 下面搜索指定的 Class [CODESPLIT] public static Collection < Class < ? > > getClasses ( ClassFileFilter filter ) { Set < URLClassLoader > loaders = new LinkedHashSet < URLClassLoader > ( 8 ) ; loaders . addAll ( getClassLoaders ( Thread . currentThread ( ) . getContextClassLoader ( ) ) ) ; loaders . addAll ( getClassLoaders ( ClassLookupHelper . class . getClassLoader ( ) ) ) ; Set < Class < ? > > klasses = new LinkedHashSet < Class < ? > > ( ) ; for ( URLClassLoader cl : loaders ) { for ( URL url : cl . getURLs ( ) ) { String file = url . getFile ( ) ; if ( file . endsWith ( \".jar\" ) || file . endsWith ( \".zip\" ) ) { lookupClassesInJar ( null , url , true , cl , filter , klasses ) ; } else { lookupClassesInFileSystem ( null , new File ( file ) , true , cl , filter , klasses ) ; } } } return klasses ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据 baseClassLoader 找到所有的祖先 URLClassLoader ( 包括自己 ) [CODESPLIT] private static Collection < URLClassLoader > getClassLoaders ( ClassLoader baseClassLoader ) { Collection < URLClassLoader > loaders = new ArrayList < URLClassLoader > ( 8 ) ; ClassLoader loader = baseClassLoader ; while ( loader != null ) { if ( \"sun.misc.Launcher$ExtClassLoader\" . equals ( loader . getClass ( ) . getName ( ) ) ) { break ; } if ( loader instanceof URLClassLoader ) { loaders . add ( ( URLClassLoader ) loader ) ; } loader = loader . getParent ( ) ; } return loaders ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从指定 package 中获取所有的 Class [CODESPLIT] public static Set < Class < ? > > getClasses ( Package pkg , boolean recursive , ClassFileFilter filter ) { return getClasses ( pkg . getName ( ) , recursive , filter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从指定 package 中获取所有的 Class [CODESPLIT] public static Set < Class < ? > > getClasses ( String packageName , boolean recursive , ClassFileFilter filter ) { if ( packageName == null || packageName . length ( ) == 0 ) { throw new IllegalArgumentException ( \"packageName is empty.\" ) ; } ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String packageDirName = packageName . replace ( ' ' , ' ' ) ; Collection < URL > urls ; try { Enumeration < URL > dirs = loader . getResources ( packageDirName ) ; urls = Collections . list ( dirs ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } Set < Class < ? > > klasses = new LinkedHashSet < Class < ? > > ( ) ; for ( URL url : urls ) { String protocol = url . getProtocol ( ) ; if ( \"file\" . equals ( protocol ) ) { lookupClassesInFileSystem ( packageName , new File ( url . getFile ( ) ) , recursive , loader , filter , klasses ) ; } else if ( \"jar\" . equals ( protocol ) ) { lookupClassesInJar ( packageName , url , recursive , loader , filter , klasses ) ; } } return klasses ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "以文件的形式来获取包下的所有 Class [CODESPLIT] private static void lookupClassesInFileSystem ( String packageName , File packagePath , final boolean recursive , ClassLoader loader , ClassFileFilter filter , Set < Class < ? > > klasses ) { if ( ! packagePath . exists ( ) || ! packagePath . isDirectory ( ) ) { return ; } File [ ] dirfiles = packagePath . listFiles ( new FileFilter ( ) { public boolean accept ( File file ) { return ( recursive && file . isDirectory ( ) ) || ( file . getName ( ) . endsWith ( \".class\" ) ) ; } } ) ; String packageNamePrefix = \"\" ; if ( packageName != null && packageName . length ( ) > 0 ) { packageNamePrefix = packageName + ' ' ; } for ( File file : dirfiles ) { if ( file . isDirectory ( ) ) { lookupClassesInFileSystem ( packageNamePrefix + file . getName ( ) , file , recursive , loader , filter , klasses ) ; } else { // 去掉后面的 .class 只留下类名 String klassName = packageNamePrefix + file . getName ( ) . substring ( 0 , file . getName ( ) . length ( ) - 6 ) ; try { if ( filter == null || filter . accept ( klassName , file , loader ) ) { Class < ? > klass = loader . loadClass ( klassName ) ; klasses . add ( klass ) ; } } catch ( Throwable e ) { } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "以在 Jar 包中获取指定包下的所有 Class [CODESPLIT] private static void lookupClassesInJar ( String packageName , URL jarUrl , boolean recursive , ClassLoader loader , ClassFileFilter filter , Set < Class < ? > > klasses ) { String packageDirName = \"\" ; if ( packageName != null && packageName . length ( ) > 0 ) { packageDirName = packageName . replace ( ' ' , ' ' ) + ' ' ; } JarFile jar = null ; try { if ( \"jar\" . equals ( jarUrl . getProtocol ( ) ) ) { jar = ( ( JarURLConnection ) jarUrl . openConnection ( ) ) . getJarFile ( ) ; } else { jar = new JarFile ( jarUrl . getFile ( ) ) ; } Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { // 获取jar里的一个实体 可以是目录和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries . nextElement ( ) ; if ( entry . isDirectory ( ) ) { continue ; } String name = entry . getName ( ) ; if ( name . charAt ( 0 ) == ' ' ) { name = name . substring ( 1 ) ; } if ( name . startsWith ( packageDirName ) && name . endsWith ( \".class\" ) ) { if ( name . lastIndexOf ( ' ' ) > packageDirName . length ( ) ) { // 在子包内 if ( ! recursive ) continue ; } // 去掉后面的 .class 只留下类名 String klassName = name . substring ( 0 , name . length ( ) - 6 ) ; klassName = klassName . replace ( ' ' , ' ' ) ; try { if ( filter == null || filter . accept ( klassName , jar , entry , loader ) ) { Class < ? > klass = loader . loadClass ( klassName ) ; klasses . add ( klass ) ; } } catch ( Throwable e ) { } } } } catch ( IOException e ) { } finally { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an input stream that contains what will written in this Application to { @link System#err } . <p > <b > Caution< / b > If you do not consume the bytes to read from the result you may block the whole application . Do only use this for debugging purposes or end to end test code! <p > Attempting to read from the result in the same thread that called here is not recommended as it may deadlock the thread . Also the thread reading from the stream result should not write anything to { @link System#err } . <p > Prefer using { @link #findMatchInSystemErr ( String ) } to avoid deadlocks . <p > [CODESPLIT] public static InputStream captureSystemErrForDebuggingPurposesOnly ( final boolean teeToOriginalSysErr ) throws IOException { PipedOutputStream pipeOut = new PipedOutputStream ( ) ; PipedInputStream pipeIn = new PipedInputStream ( pipeOut ) ; OutputStream out = pipeOut ; if ( teeToOriginalSysErr ) { out = new MultiplexingOutputStream ( System . err , pipeOut ) ; } PrintStream streamOut = new PrintStream ( out ) ; System . setErr ( streamOut ) ; return pipeIn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an input stream that contains what will written in this Application to { @link System#out } . <p > <b > Caution< / b > If you do not consume the bytes to read from the result you may block the whole application . Do only use this for debugging purposes or end to end test code! <p > Attempting to read from the result in the same thread that called here is not recommended as it may deadlock the thread . Also the thread reading from the stream result should not write anything to { @link System#out } . <p > Prefer using { @link #findMatchInSystemOut ( String ) } to avoid deadlocks . <p > [CODESPLIT] public static InputStream captureSystemOutForDebuggingPurposesOnly ( final boolean teeToOriginalSysOut ) throws IOException { PipedOutputStream pipeOut = new PipedOutputStream ( ) ; PipedInputStream pipeIn = new PipedInputStream ( pipeOut ) ; OutputStream out = pipeOut ; if ( teeToOriginalSysOut ) { out = new MultiplexingOutputStream ( System . out , pipeOut ) ; } PrintStream streamOut = new PrintStream ( out ) ; System . setOut ( streamOut ) ; return pipeIn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance to a runnable running in a separate Thread that tries to match the expected output in { @link System#out } . <p > Ensure that you found the expected String in the input stream given by calling { @link info . monitorenter . util . ExceptionUtil . InputStreamTracer#isMatched () } . But take into account that it is time - critical ( concurrency ) if your result was found . <p > Prefer this instead of { @link #captureSystemOutForDebuggingPurposesOnly ( boolean ) } as this will avoid blocking your application . <p > [CODESPLIT] public static InputStreamTracer findMatchInSystemOut ( final String expectMatch ) throws IOException { InputStream systemout = captureSystemOutForDebuggingPurposesOnly ( true ) ; InputStreamTracer result = new InputStreamTracer ( systemout , expectMatch , Charset . defaultCharset ( ) ) ; Thread traceThread = new Thread ( result ) ; traceThread . setDaemon ( true ) ; traceThread . start ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance to a runnable running in a separate Thread that tries to match the expected output in { @link System#err } . <p > Ensure that you found the expected String in the input stream given by calling { @link info . monitorenter . util . ExceptionUtil . InputStreamTracer#isMatched () } . But take into account that it is time - critical ( concurrency ) if your result was found . <p > Prefer this instead of { @link #captureSystemErrForDebuggingPurposesOnly ( boolean ) } as this will avoid blocking your application . <p > [CODESPLIT] public static InputStreamTracer findMatchInSystemErr ( final String expectMatch ) throws IOException { InputStream systemout = captureSystemErrForDebuggingPurposesOnly ( true ) ; InputStreamTracer result = new InputStreamTracer ( systemout , expectMatch , Charset . defaultCharset ( ) ) ; Thread traceThread = new Thread ( result ) ; traceThread . setDaemon ( true ) ; traceThread . start ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints out the current Thread stack to the given stream . <p > [CODESPLIT] public static void dumpThreadStack ( PrintStream outprint ) { StackTraceElement [ ] stackTrace = Thread . currentThread ( ) . getStackTrace ( ) ; String stackTraceString = StringUtil . arrayToString ( stackTrace , \"\\n\" ) ; outprint . println ( stackTraceString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the singleton instance of this class . <p > This method is useless for now as all methods are static . It may be used in future if VM - global configuration will be put to the state of the instance . <p > [CODESPLIT] public static ExceptionUtil instance ( ) { if ( ExceptionUtil . instance == null ) { ExceptionUtil . instance = new ExceptionUtil ( ) ; } return ExceptionUtil . instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the specified Option to the list of accepted options [CODESPLIT] public final Option addOption ( Option opt ) { if ( opt . shortForm ( ) != null ) this . options . put ( \"-\" + opt . shortForm ( ) , opt ) ; this . options . put ( \"--\" + opt . longForm ( ) , opt ) ; return opt ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for adding a string option . [CODESPLIT] public final Option addStringOption ( char shortForm , String longForm ) { return addOption ( new Option . StringOption ( shortForm , longForm ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for adding an integer option . [CODESPLIT] public final Option addIntegerOption ( char shortForm , String longForm ) { return addOption ( new Option . IntegerOption ( shortForm , longForm ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for adding a long integer option . [CODESPLIT] public final Option addLongOption ( char shortForm , String longForm ) { return addOption ( new Option . LongOption ( shortForm , longForm ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for adding a double option . [CODESPLIT] public final Option addDoubleOption ( char shortForm , String longForm ) { return addOption ( new Option . DoubleOption ( shortForm , longForm ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method for adding a boolean option . [CODESPLIT] public final Option addBooleanOption ( char shortForm , String longForm ) { return addOption ( new Option . BooleanOption ( shortForm , longForm ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the options and non - option arguments from the given list of command - line arguments . The specified locale is used for parsing options whose values might be locale - specific . [CODESPLIT] public final void parse ( String [ ] argv , Locale locale ) throws IllegalOptionValueException , UnknownOptionException { // It would be best if this method only threw OptionException, but for // backwards compatibility with old user code we throw the two // exceptions above instead. Vector otherArgs = new Vector ( ) ; int position = 0 ; this . values = new Hashtable ( 10 ) ; while ( position < argv . length ) { String curArg = argv [ position ] ; if ( curArg . startsWith ( \"-\" ) ) { if ( curArg . equals ( \"--\" ) ) { // end of options position += 1 ; break ; } String valueArg = null ; if ( curArg . startsWith ( \"--\" ) ) { // handle --arg=value int equalsPos = curArg . indexOf ( \"=\" ) ; if ( equalsPos != - 1 ) { valueArg = curArg . substring ( equalsPos + 1 ) ; curArg = curArg . substring ( 0 , equalsPos ) ; } } else if ( curArg . length ( ) > 2 ) { // handle -abcd for ( int i = 1 ; i < curArg . length ( ) ; i ++ ) { Option opt = ( Option ) this . options . get ( \"-\" + curArg . charAt ( i ) ) ; if ( opt == null ) throw new UnknownSuboptionException ( curArg , curArg . charAt ( i ) ) ; if ( opt . wantsValue ( ) ) throw new NotFlagException ( curArg , curArg . charAt ( i ) ) ; addValue ( opt , opt . getValue ( null , locale ) ) ; } position ++ ; continue ; } Option opt = ( Option ) this . options . get ( curArg ) ; if ( opt == null ) { throw new UnknownOptionException ( curArg ) ; } Object value = null ; if ( opt . wantsValue ( ) ) { if ( valueArg == null ) { position += 1 ; if ( position < argv . length ) { valueArg = argv [ position ] ; } } value = opt . getValue ( valueArg , locale ) ; } else { value = opt . getValue ( null , locale ) ; } addValue ( opt , value ) ; position += 1 ; } else { otherArgs . addElement ( curArg ) ; position += 1 ; } } for ( ; position < argv . length ; ++ position ) { otherArgs . addElement ( argv [ position ] ) ; } this . remainingArgs = new String [ otherArgs . size ( ) ] ; otherArgs . copyInto ( remainingArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A default delegation to { @link #detectCodepage ( java . net . URL ) } that opens the document specified by the given URL with the detected codepage . <p > [CODESPLIT] public final Reader open ( final URL url ) throws IOException { Reader ret = null ; Charset cs = this . detectCodepage ( url ) ; if ( cs != null ) { ret = new InputStreamReader ( new BufferedInputStream ( url . openStream ( ) ) , cs ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "打印出调用堆栈 <br > 2013 - 8 - 28 下午3 : 52 : 17 [CODESPLIT] public static void printStackTrace ( ) { Throwable throwable = new Throwable ( ) ; StackTraceElement [ ] stackTraceElements = throwable . getStackTrace ( ) ; StackTraceElement [ ] stackTraceElementsTarget = new StackTraceElement [ stackTraceElements . length - 1 ] ; // for (int i = 1, j = 0; i < stackTraceElements.length; i++) { // StackTraceElement stackTraceElement = stackTraceElements[i]; // System.out.println(stackTraceElement.getClassName()); // System.out.println(stackTraceElement.getFileName()); // System.out.println(stackTraceElement.getMethodName()); // System.out.println(stackTraceElement.getLineNumber()); // System.out.println(\"    at \" + stackTraceElement.getClassName() + \".\" // + stackTraceElement.getMethodName() + \"(\" + // stackTraceElement.getFileName() + \":\" + // stackTraceElement.getLineNumber() + \")\"); // } System . arraycopy ( stackTraceElements , 1 , stackTraceElementsTarget , 0 , stackTraceElementsTarget . length ) ; System . out . println ( \" ----------------------- StackTrace Info ----------------------- \" ) ; System . out . print ( buildStackTrace ( stackTraceElementsTarget ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "组织堆栈信息，将堆栈数组拼接成字符串 <br > 2013 - 8 - 28 下午3 : 50 : 50 [CODESPLIT] public static String buildStackTrace ( StackTraceElement [ ] stackTraceElements ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < stackTraceElements . length ; i ++ ) { StackTraceElement stackTraceElement = stackTraceElements [ i ] ; builder . append ( \"    at \" ) ; builder . append ( stackTraceElement . getClassName ( ) ) ; builder . append ( \".\" ) ; builder . append ( stackTraceElement . getMethodName ( ) ) ; builder . append ( \"(\" ) ; builder . append ( stackTraceElement . getFileName ( ) ) ; builder . append ( \":\" ) ; builder . append ( stackTraceElement . getLineNumber ( ) ) ; builder . append ( \")\" ) ; builder . append ( StringHelper . line ( ) ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回不包括本类调用堆栈的当前堆栈 <br > 2013 - 7 - 26 下午6 : 09 : 09 [CODESPLIT] public static StackTraceElement [ ] getStackTrace ( ) { Throwable throwable = new Throwable ( ) ; StackTraceElement [ ] stackTraceElements = throwable . getStackTrace ( ) ; StackTraceElement [ ] stackTraceElementsTarget = new StackTraceElement [ stackTraceElements . length ] ; System . arraycopy ( stackTraceElements , 0 , stackTraceElementsTarget , 0 , stackTraceElementsTarget . length ) ; return stackTraceElementsTarget ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取间接调用的类名<p > < / p > 比如A方法调用B方法，B方法再调用whoInvoke () 方法，这样B方法内就能返回A方法在那个类下 [CODESPLIT] public static Class whoInvoke ( ) { Throwable throwable = new Throwable ( ) ; StackTraceElement [ ] stackTraceElements = throwable . getStackTrace ( ) ; StackTraceElement stackTraceElement = stackTraceElements [ 2 ] ; try { return Class . forName ( stackTraceElement . getClassName ( ) ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------- debug ---------------------------- [CODESPLIT] public static void debug ( Object object , Object message ) { Class clazz = object . getClass ( ) ; debug ( clazz , message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "读取field的注解值（包括get、set方法） [CODESPLIT] public static < T extends Annotation > T readAnnotationValueOnField ( Field field , Class < T > annotationClass ) { if ( field . isAnnotationPresent ( annotationClass ) ) { T t = field . getAnnotation ( annotationClass ) ; return t ; } else { Method method = EntityHelper . findGetMethod ( field ) ; if ( method . isAnnotationPresent ( annotationClass ) ) { T t = method . getAnnotation ( annotationClass ) ; return t ; } return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "在类内搜索所有的字段的annotationClass注解值 [CODESPLIT] public static < T extends Annotation > Collection < T > readAnnotationsInClass ( Class < ? > clazz , Class < T > annotationClass ) { Collection < T > collection = null ; Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( Field field : fields ) { T t = readAnnotationValueOnField ( field , annotationClass ) ; if ( t == null ) { continue ; } if ( collection == null ) { collection = new ArrayList < T > ( ) ; } collection . add ( t ) ; } return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "在类内搜索使用annotationClass注解的字段（包括在get、set方法上注解） [CODESPLIT] public static < T extends Annotation > Collection < Field > getFieldsWithAnnotationInClass ( Class < ? > inClazz , Class < T > annotationClass ) { Collection < Field > fieldCollection = null ; Field [ ] fields = inClazz . getDeclaredFields ( ) ; for ( Field field : fields ) { if ( Modifier . isStatic ( field . getModifiers ( ) ) || Modifier . isFinal ( field . getModifiers ( ) ) ) { continue ; } T t = readAnnotationValueOnField ( field , annotationClass ) ; if ( t == null ) { continue ; } if ( fieldCollection == null ) { fieldCollection = new ArrayList < Field > ( ) ; } fieldCollection . add ( field ) ; } return fieldCollection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从第一个字符开始比较两个字符串的大小（按照单个字符的ascii码比较），例如： abc 大于 aac 、 1234 小于 2234 、 1234 大于 123 、 223 大于 1234 [CODESPLIT] public static boolean compareNumberString ( String firstString , String secondString ) { Assert . notNull ( firstString , \"第一个字符串为空！\");   Assert . notNull ( secondString , \"第二个字符串为空！\");   char [ ] chars1 = firstString . toCharArray ( ) ; char [ ] chars2 = secondString . toCharArray ( ) ; int length1 = chars1 . length ; int length2 = chars2 . length ; int maxLength = length1 > length2 ? length1 : length2 ; for ( int i = 0 ; i < maxLength ; i ++ ) { int value1 = - 1 ; int value2 = - 1 ; if ( i < length1 ) { value1 = chars1 [ i ] ; } if ( i < length2 ) { value2 = chars2 [ i ] ; } if ( value1 < value2 ) { return true ; } else { return false ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "计算数组的hashCode <br > 2013 - 10 - 25 上午11 : 06 : 57 [CODESPLIT] public static int hashCodeOfStringArray ( String [ ] stringArray ) { if ( stringArray == null ) { return 0 ; } int hashCode = 17 ; for ( int i = 0 ; i < stringArray . length ; i ++ ) { String value = stringArray [ i ] ; hashCode = hashCode * 31 + ( value == null ? 0 : value . hashCode ( ) ) ; } return hashCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "换行符 <br > 2013 - 8 - 14 下午1 : 20 : 06 [CODESPLIT] public static String line ( ) { String lineSeparator = java . security . AccessController . doPrivileged ( new sun . security . action . GetPropertyAction ( \"line.separator\" ) ) ; //\t\tString lineSeparator = System.getProperty(\"line.separator\"); return lineSeparator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<br > 2013 - 8 - 28 下午5 : 26 : 24 [CODESPLIT] public static String convertEncode ( String str ) { if ( nullOrEmpty ( str ) ) { return null ; } try { return new String ( str . getBytes ( ) , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "StringReader转换为字符串 <br > 2013 - 9 - 2 下午9 : 03 : 29 [CODESPLIT] public String stringReaderToString ( StringReader reader ) { StringBuilder builder = new StringBuilder ( ) ; char [ ] buffer = new char [ 128 ] ; int length = - 1 ; try { while ( ( length = reader . read ( buffer ) ) != - 1 ) { if ( buffer . length != length ) { System . arraycopy ( buffer , 0 , buffer , 0 , length ) ; } builder . append ( buffer ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { reader . close ( ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "High - level method for instantiation of a new instance of the class specified by the given fully qualified class name with singleton retrieval support . Delegates to { @link #newInstance ( Class ) } . [CODESPLIT] public Object newInstance ( String fullyQualifiedClassName ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { Object ret = this . newInstance ( Class . forName ( fullyQualifiedClassName ) ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dynamic instantiation of the given type with singleton retrieval support as described in this class description . [CODESPLIT] public Object newInstance ( Class c ) throws InstantiationException , IllegalAccessException { Object ret = null ; Method [ ] methods = c . getDeclaredMethods ( ) ; Method m ; int modifiers ; // searching for static methods: for ( int i = 0 ; i < methods . length ; i ++ ) { m = methods [ i ] ; modifiers = m . getModifiers ( ) ; if ( ( modifiers & Modifier . STATIC ) != 0 ) { // searching for public access: if ( ( modifiers & Modifier . PUBLIC ) != 0 ) { // searching for no parameters: if ( m . getParameterTypes ( ) . length == 0 ) { // searching for return type: if ( m . getReturnType ( ) == c ) { // searching for substring \"instance\" in method name: if ( m . getName ( ) . toLowerCase ( ) . indexOf ( \"instance\" ) != - 1 ) { try { // Finally we found a singleton method: // we are static and don't need an instance. ret = m . invoke ( null , dummyParameters ) ; } catch ( IllegalArgumentException e ) { // This will not happen: // we ensured that no arguments are needed. e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { // This will not happen (only in applet context perhaps or with some // SecurityManager): // we ensured public access. e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; } } } } } } } // check, if we found a singleton: if ( ret == null ) { // try to invoke the default constructor: Constructor [ ] constructors = c . getConstructors ( ) ; Constructor con = null ; // search for a parameterless constructor: for ( int i = 0 ; i < constructors . length ; i ++ ) { con = constructors [ i ] ; if ( con . getParameterTypes ( ) . length == 0 ) { // see, if public: modifiers = con . getModifiers ( ) ; try { if ( ( modifiers & Modifier . PUBLIC ) == 0 ) { // try to set accessible: con . setAccessible ( true ) ; } // invokes the default constructor ret = c . newInstance ( ) ; } catch ( SecurityException se ) { // damn } } } } if ( ret == null ) { System . err . println ( \"Unable to instantiate: \" + c . getName ( ) + \": no singleton method, no public default constructor.\" ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Singleton retrieval method . <p > Be sure to configure the instance returned at a single location in your code to avoid unpredictable application - wide side effects . <p > [CODESPLIT] public static CodepageDetectorProxy getInstance ( ) { if ( CodepageDetectorProxy . instance == null ) { CodepageDetectorProxy . instance = new CodepageDetectorProxy ( ) ; } return CodepageDetectorProxy . instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Detects the codepage by iteratively delegating the call to all internal { @link info . monitorenter . cpdetector . io . ICodepageDetector } instances added by { @link #add ( info . monitorenter . cpdetector . io . ICodepageDetector ) } . < / p > <p > The given InputStream has to support mark such that the call { @link java . io . InputStream#mark ( int ) } with argument length does not throw an exception . This is needed as the stream has to be resetted to the beginning for each internal delegate that tries to detect . < / p > <p > If this is impossible ( large documents ) prefer using { @link #detectCodepage ( java . net . URL ) } . < / p > [CODESPLIT] public Charset detectCodepage ( final InputStream in , final int length ) throws IOException , IllegalArgumentException { if ( ! in . markSupported ( ) ) { throw new IllegalArgumentException ( \"The given input stream (\" + in . getClass ( ) . getName ( ) + \") has to support for marking.\" ) ; } Charset ret = null ; int markLimit = length ; Iterator < ICodepageDetector > detectorIt = this . detectors . iterator ( ) ; while ( detectorIt . hasNext ( ) ) { in . mark ( markLimit ) ; ret = detectorIt . next ( ) . detectCodepage ( in , length ) ; // if more bytes have been read than marked (length) this will throw an // exception: try { in . reset ( ) ; } catch ( IOException ioex ) { IllegalStateException ise = new IllegalStateException ( \"More than the given length had to be read and the given stream could not be reset. Undetermined state for this detection.\" ) ; ise . initCause ( ioex ) ; throw ise ; } if ( ret != null ) { if ( ret != UnknownCharset . getInstance ( ) ) { if ( ret instanceof UnsupportedCharset ) { // TODO: Debug logging: found illegal charset tag or encoding // declaration. } else { break ; } } } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取 目标对象 [CODESPLIT] public static Object getTarget ( Object proxy ) throws Exception { if ( ! AopUtils . isAopProxy ( proxy ) ) { return proxy ; //不是代理对象 } if ( AopUtils . isJdkDynamicProxy ( proxy ) ) { return getJdkDynamicProxyTargetObject ( proxy ) ; } else { //cglib return getCglibProxyTargetObject ( proxy ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回两个日期的毫秒之差 [CODESPLIT] public static long compareDate ( Date nearDate , Date farDate ) { long nearMilli = nearDate . getTime ( ) ; long farMilli = farDate . getTime ( ) ; long result = nearMilli - farMilli ; if ( result < 0 ) { result = - result ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "计算指定日期到现在的时间计算 [CODESPLIT] public static String caculatorDateToString ( Date date ) { long milliSecond = compareDate ( date ) ; List dateCaculators = DateCalculator . getDateCalculators ( ) ; for ( Iterator iterator = dateCaculators . iterator ( ) ; iterator . hasNext ( ) ; ) { DateCalculator dateCalculator = ( DateCalculator ) iterator . next ( ) ; if ( milliSecond >= dateCalculator . getMinMilliSecond ( ) && milliSecond <= dateCalculator . getMaxMilliSecond ( ) ) { String displayStr = dateCalculator . getDisplayStr ( ) ; long numberOfUnit = 0 ; if ( dateCalculator . getMinMilliSecond ( ) == 0 ) { // 分母为零，则直接为0 numberOfUnit = 0 ; } else { numberOfUnit = milliSecond / dateCalculator . getMinMilliSecond ( ) ; } // 替代所有{0} Pattern p = Pattern . compile ( \"(\\\\{.+?\\\\})\" ) ; Matcher m = p . matcher ( displayStr ) ; displayStr = m . replaceAll ( numberOfUnit + \"\" ) ; // displayStr = displayStr.replace(\"\\\\{0\\\\}\", numberOfUnit + // \"\"); return displayStr ; } } return milliSecond + \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a new value instance overwriting the old value which is returned . <p > [CODESPLIT] public K setValue ( final K value ) { final K ret = this . m_value ; this . m_value = value ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成文件 [CODESPLIT] public File generate ( ) { QRCode qrCode = new QRCode ( ) ; File file = qrCode . encode ( profile ) ; return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "增加扫描的包 [CODESPLIT] public PackageScanner addPackage ( String pkg ) { Package aPackage = Package . getPackage ( pkg ) ; addPackage ( aPackage ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "开始扫描 [CODESPLIT] public Collection < Class < ? > > scan ( ) { Assert . notEmpty ( packages , \"待扫描的包为空！\");   Collection < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; ClassLookupHelper . ClassFileFilter classFileFilter = new ClassLookupHelper . ClassFileFilter ( ) { @ Override public boolean accept ( String klassName , File file , ClassLoader loader ) { return true ; } @ Override public boolean accept ( String klassName , JarFile jar , JarEntry entry , ClassLoader loader ) { return true ; } } ; for ( Package pkg : packages ) { Set < Class < ? > > scanClasses = ClassLookupHelper . getClasses ( pkg , recursive , classFileFilter ) ; for ( Class < ? > scanClass : scanClasses ) { if ( isAnnotationPassed ( scanClass ) && isStartWithPassed ( scanClass ) && isInterfacePassed ( scanClass ) ) { classes . add ( scanClass ) ; } } } return classes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean accept ( File pathname ) { boolean ret = false ; // search for extension without dot.  StringTokenizer tokenizer = new StringTokenizer ( pathname . getAbsolutePath ( ) , \".\" ) ; String extension = \"no.txt\" ; // a dot, because verify will not allow these tokens: won't accept, if no extension in pathname. while ( tokenizer . hasMoreElements ( ) ) { extension = tokenizer . nextToken ( ) ; } for ( int i = this . m_extensions . length - 1 ; i >= 0 ; i -- ) { if ( this . m_extensions [ i ] . equals ( extension ) ) { ret = true ; break ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成QRCode二维码 [CODESPLIT] public File encode ( Profile profile ) { try { File isFile = new File ( profile . getPath ( ) ) ; if ( ! isFile . exists ( ) ) { isFile . mkdirs ( ) ; } SimpleDateFormat sdf = new SimpleDateFormat ( \"yyyyMMddHHmmss\" ) ; String fileName = UUID . randomUUID ( ) + \".\" + profile . getFormat ( ) ; //            String url = zxing.getPath() + fileName; File file = new File ( profile . getPath ( ) , fileName ) ; //            writeToFile(bitMatrix, profile.getFormat(), file, profile.isLogoFlag(), profile.getLogoPath()); BufferedImage bufferedImage = encodeToBufferedImage ( profile ) ; ImageIO . write ( bufferedImage , profile . getFormat ( ) , file ) ; return file ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成二维码内容 [CODESPLIT] public BufferedImage toBufferedImageContents ( BitMatrix bitMatrix ) { int width = bitMatrix . getWidth ( ) ; int height = bitMatrix . getHeight ( ) ; BufferedImage image = new BufferedImage ( width , height , BufferedImage . TYPE_INT_RGB ) ; for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { image . setRGB ( x , y , bitMatrix . get ( x , y ) == true ? BLACK : WHITE ) ; } } return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解析二维码 [CODESPLIT] public String decode ( String path ) throws IOException , NotFoundException { if ( path == null || path . equals ( \"\" ) ) { System . out . println ( \"文件路径不能为空!\");   } File file = new File ( path ) ; BufferedImage image = ImageIO . read ( file ) ; /*判断是否是图片*/ if ( image != null ) { return decode ( image ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be invoked before the main execution logic of concrete subclasses . <p > This implementation applies the concurrency throttle . [CODESPLIT] protected void beforeAccess ( ) { if ( this . concurrencyLimit == NO_CONCURRENCY ) { throw new IllegalStateException ( \"Currently no invocations allowed - concurrency limit set to NO_CONCURRENCY\" ) ; } if ( this . concurrencyLimit > 0 ) { boolean debug = logger . isDebugEnabled ( ) ; synchronized ( this . monitor ) { boolean interrupted = false ; while ( this . concurrencyCount >= this . concurrencyLimit ) { if ( interrupted ) { throw new IllegalStateException ( \"Thread was interrupted while waiting for invocation access, \" + \"but concurrency limit still does not allow for entering\" ) ; } if ( debug ) { logger . debug ( \"Concurrency count \" + this . concurrencyCount + \" has reached limit \" + this . concurrencyLimit + \" - blocking\" ) ; } try { this . monitor . wait ( ) ; } catch ( InterruptedException ex ) { // Re-interrupt current thread, to allow other threads to react. Thread . currentThread ( ) . interrupt ( ) ; interrupted = true ; } } if ( debug ) { logger . debug ( \"Entering throttle at concurrency count \" + this . concurrencyCount ) ; } this . concurrencyCount ++ ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To be invoked after the main execution logic of concrete subclasses . [CODESPLIT] protected void afterAccess ( ) { if ( this . concurrencyLimit >= 0 ) { synchronized ( this . monitor ) { this . concurrencyCount -- ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Returning from throttle at concurrency count \" + this . concurrencyCount ) ; } this . monitor . notify ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--------------------------------------------------------------------- [CODESPLIT] private void readObject ( ObjectInputStream ois ) throws IOException , ClassNotFoundException { // Rely on default serialization, just initialize state after deserialization. ois . defaultReadObject ( ) ; // Initialize transient fields. this . logger = LogFactory . getLog ( getClass ( ) ) ; this . monitor = new Object ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "带回调函数的代理线程，本方法将创建新线程在线程池内运行<br > <b > 注意：回调函数一定要是带三个参数的方法：<br > 第一个参数来接收代理函数执行方法的返回值，<br > 第二个参数用来接收代理函数执行过程中抛出的异常，<br > 第三个参数用来回调调用时传给代理线程的参数列表< / b > <br > <br > <br > 回调方法的获取方法<br > <pre > Class . getDeclaredMethod ( &quot ; callBack&quot ; Object . class Throwable . class Object [] . class ) ; < / pre > 2013 - 9 - 16 下午9 : 30 : 29 [CODESPLIT] public static void invoke ( Object callBackInstance , Method callBackMethod , Object instance , Method method , Object ... parameters ) { if ( method != null ) { ProxyThread proxyThread = new ProxyThread ( callBackInstance , callBackMethod , instance , method , parameters ) ; pool . execute ( proxyThread ) ; } else { EntityHelper . print ( \"空对象\");   StackTraceHelper . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "代理线程，本方法将创建新线程在线程池内运行 <br > 2013 - 9 - 16 下午9 : 38 : 12 [CODESPLIT] public static void invoke ( Object instance , Method method , Object ... parameters ) { invoke ( null , null , instance , method , parameters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取json字符串 [CODESPLIT] public static String getJsonString ( Object object ) { ObjectMapper objectMapper = new ObjectMapper ( ) ; String json = null ; try { json = objectMapper . writeValueAsString ( object ) ; } catch ( JsonProcessingException e ) { e . printStackTrace ( ) ; } return json ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取格式化的json数组 [CODESPLIT] public static String getPrettyJsonString ( Object object ) { ObjectMapper objectMapper = new ObjectMapper ( ) ; String json = null ; try { json = objectMapper . writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( object ) ; } catch ( JsonProcessingException e ) { e . printStackTrace ( ) ; } return json ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "增加指定字段的数量 [CODESPLIT] public CalendarBuilder next ( int field , int plus ) { calculateCalendar . set ( field , calculateCalendar . get ( field ) + plus ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete the supplied { @link java . io . File } - for directories recursively delete any nested directories or files as well . [CODESPLIT] public static boolean deleteRecursively ( File root ) { if ( root != null && root . exists ( ) ) { if ( root . isDirectory ( ) ) { File [ ] children = root . listFiles ( ) ; if ( children != null ) { for ( File child : children ) { deleteRecursively ( child ) ; } } } return root . delete ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively copy the contents of the { @code src } file / directory to the { @code dest } file / directory . [CODESPLIT] public static void copyRecursively ( File src , File dest ) throws IOException { Assert . isTrue ( src != null && ( src . isDirectory ( ) || src . isFile ( ) ) , \"Source File must denote a directory or file\" ) ; Assert . notNull ( dest , \"Destination File must not be null\" ) ; doCopyRecursively ( src , dest ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actually copy the contents of the { @code src } file / directory to the { @code dest } file / directory . [CODESPLIT] private static void doCopyRecursively ( File src , File dest ) throws IOException { if ( src . isDirectory ( ) ) { dest . mkdir ( ) ; File [ ] entries = src . listFiles ( ) ; if ( entries == null ) { throw new IOException ( \"Could not list files in directory: \" + src ) ; } for ( File entry : entries ) { doCopyRecursively ( entry , new File ( dest , entry . getName ( ) ) ) ; } } else if ( src . isFile ( ) ) { try { dest . createNewFile ( ) ; } catch ( IOException ex ) { IOException ioex = new IOException ( \"Failed to create file: \" + dest ) ; ioex . initCause ( ex ) ; throw ioex ; } FileCopyUtils . copy ( src , dest ) ; } else { // Special File handle: neither a file not a directory. // Simply skip it when contained in nested directory... } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<br > 2013 - 10 - 28 上午11 : 11 : 24 [CODESPLIT] private Collection < String > checkAndPutToCollection ( Collection < String > collection , String [ ] names ) { if ( collection == null ) { collection = new HashSet < String > ( ) ; } Collections . addAll ( collection , names ) ; return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理IgnoreProperties注解 <br > 2013 - 10 - 30 下午6 : 15 : 41 [CODESPLIT] private void processIgnorePropertiesAnnotation ( IgnoreProperties properties , Map < Class < ? > , Collection < String > > pojoAndNamesMap ) { IgnoreProperty [ ] values = properties . value ( ) ; AllowProperty [ ] allowProperties = properties . allow ( ) ; if ( allowProperties != null ) { for ( AllowProperty allowProperty : allowProperties ) { processAllowPropertyAnnotation ( allowProperty , pojoAndNamesMap ) ; } } if ( values != null ) { for ( IgnoreProperty property : values ) { processIgnorePropertyAnnotation ( property , pojoAndNamesMap ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理IgnoreProperty注解 <br > 2013 - 10 - 30 下午6 : 16 : 08 [CODESPLIT] private void processIgnorePropertyAnnotation ( IgnoreProperty property , Map < Class < ? > , Collection < String > > pojoAndNamesMap ) { String [ ] names = property . name ( ) ; Class < ? > pojoClass = property . pojo ( ) ; // Class<?> proxyAnnotationInterface = createMixInAnnotation(names);// // 根据注解创建代理接口 Collection < String > nameCollection = pojoAndNamesMap . get ( pojoClass ) ; nameCollection = checkAndPutToCollection ( nameCollection , names ) ; pojoAndNamesMap . put ( pojoClass , nameCollection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "处理AllowProperty注解 <br > 2013 - 10 - 30 下午6 : 16 : 08 [CODESPLIT] private void processAllowPropertyAnnotation ( AllowProperty property , Map < Class < ? > , Collection < String > > pojoAndNamesMap ) { String [ ] allowNames = property . name ( ) ; Class < ? > pojoClass = property . pojo ( ) ; Collection < String > ignoreProperties = EntityHelper . getUnstaticClassFieldNameCollection ( pojoClass ) ; Collection < String > allowNameCollection = new ArrayList < String > ( ) ; Collections . addAll ( allowNameCollection , allowNames ) ; Collection < String > nameCollection = pojoAndNamesMap . get ( pojoClass ) ; if ( nameCollection != null ) { nameCollection . removeAll ( allowNameCollection ) ; } else { ignoreProperties . removeAll ( allowNameCollection ) ; nameCollection = ignoreProperties ; } pojoAndNamesMap . put ( pojoClass , nameCollection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据方法获取过滤映射表 <br > 2013 - 10 - 25 下午2 : 47 : 34 [CODESPLIT] public Map < Class < ? > , Class < ? > > getProxyMixInAnnotation ( Method method ) { //        if (isResponseBodyAnnotation && !method.isAnnotationPresent(ResponseBody.class)) { //            return null; //        } Map < Class < ? > , Class < ? > > map = proxyMethodMap . get ( method ) ; // 从缓存中查找是否存在 if ( map != null && map . entrySet ( ) . size ( ) > 0 ) { // 如果已经读取该方法的注解信息，则从缓存中读取 return map ; } else { map = new HashMap < Class < ? > , Class < ? > > ( ) ; } Class < ? > clazzOfMethodIn = method . getDeclaringClass ( ) ; // 方法所在的class Map < Class < ? > , Collection < String > > pojoAndNamesMap = new HashMap < Class < ? > , Collection < String > > ( ) ; IgnoreProperties classIgnoreProperties = clazzOfMethodIn . getAnnotation ( IgnoreProperties . class ) ; IgnoreProperty classIgnoreProperty = clazzOfMethodIn . getAnnotation ( IgnoreProperty . class ) ; AllowProperty classAllowProperty = clazzOfMethodIn . getAnnotation ( AllowProperty . class ) ; IgnoreProperties ignoreProperties = method . getAnnotation ( IgnoreProperties . class ) ; IgnoreProperty ignoreProperty = method . getAnnotation ( IgnoreProperty . class ) ; AllowProperty allowProperty = method . getAnnotation ( AllowProperty . class ) ; if ( allowProperty != null ) { // 方法上的AllowProperty注解 processAllowPropertyAnnotation ( allowProperty , pojoAndNamesMap ) ; } if ( classAllowProperty != null ) { processAllowPropertyAnnotation ( classAllowProperty , pojoAndNamesMap ) ; } if ( classIgnoreProperties != null ) { // 类上的IgnoreProperties注解 processIgnorePropertiesAnnotation ( classIgnoreProperties , pojoAndNamesMap ) ; } if ( classIgnoreProperty != null ) { // 类上的IgnoreProperty注解 processIgnorePropertyAnnotation ( classIgnoreProperty , pojoAndNamesMap ) ; } if ( ignoreProperties != null ) { // 方法上的IgnoreProperties注解 processIgnorePropertiesAnnotation ( ignoreProperties , pojoAndNamesMap ) ; } if ( ignoreProperty != null ) { // 方法上的IgnoreProperties注解 processIgnorePropertyAnnotation ( ignoreProperty , pojoAndNamesMap ) ; } Set < Entry < Class < ? > , Collection < String > > > entries = pojoAndNamesMap . entrySet ( ) ; for ( Iterator < Entry < Class < ? > , Collection < String > > > iterator = entries . iterator ( ) ; iterator . hasNext ( ) ; ) { Entry < Class < ? > , Collection < String > > entry = ( Entry < Class < ? > , Collection < String > > ) iterator . next ( ) ; Collection < String > nameCollection = entry . getValue ( ) ; nameCollection = putGlobalIgnoreProperties ( nameCollection ) ; // 将全局过滤字段放入集合内 String [ ] names = nameCollection . toArray ( new String [ ] { } ) ; // EntityHelper.print(entry.getKey()); // for (int i = 0; i < names.length; i++) { // String name = names[i]; // EntityHelper.print(name); // } Class < ? > clazz = createMixInAnnotation ( names ) ; map . put ( entry . getKey ( ) , clazz ) ; } proxyMethodMap . put ( method , map ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建jackson的代理注解接口类 <br > 2013 - 10 - 25 上午11 : 59 : 50 [CODESPLIT] private Class < ? > createMixInAnnotation ( String [ ] names ) { Class < ? > clazz = null ; clazz = proxyMixInAnnotationMap . get ( StringHelper . hashCodeOfStringArray ( names ) ) ; if ( clazz != null ) { return clazz ; } ClassPool pool = ClassPool . getDefault ( ) ; // 创建代理接口 CtClass cc = pool . makeInterface ( \"ProxyMixInAnnotation\" + System . currentTimeMillis ( ) + proxyIndex ++ ) ; ClassFile ccFile = cc . getClassFile ( ) ; ConstPool constpool = ccFile . getConstPool ( ) ; // create the annotation AnnotationsAttribute attr = new AnnotationsAttribute ( constpool , AnnotationsAttribute . visibleTag ) ; // 创建JsonIgnoreProperties注解 Annotation jsonIgnorePropertiesAnnotation = new Annotation ( JsonIgnoreProperties . class . getName ( ) , constpool ) ; BooleanMemberValue ignoreUnknownMemberValue = new BooleanMemberValue ( false , constpool ) ; ArrayMemberValue arrayMemberValue = new ArrayMemberValue ( constpool ) ; // value的数组成员 Collection < MemberValue > memberValues = new HashSet < MemberValue > ( ) ; for ( int i = 0 ; i < names . length ; i ++ ) { String name = names [ i ] ; StringMemberValue memberValue = new StringMemberValue ( constpool ) ; // 将name值设入注解内 memberValue . setValue ( name ) ; memberValues . add ( memberValue ) ; } arrayMemberValue . setValue ( memberValues . toArray ( new MemberValue [ ] { } ) ) ; jsonIgnorePropertiesAnnotation . addMemberValue ( \"value\" , arrayMemberValue ) ; jsonIgnorePropertiesAnnotation . addMemberValue ( \"ignoreUnknown\" , ignoreUnknownMemberValue ) ; attr . addAnnotation ( jsonIgnorePropertiesAnnotation ) ; ccFile . addAttribute ( attr ) ; // generate the class try { clazz = cc . toClass ( ) ; proxyMixInAnnotationMap . put ( StringHelper . hashCodeOfStringArray ( names ) , clazz ) ; // JsonIgnoreProperties ignoreProperties = (JsonIgnoreProperties) // clazz // .getAnnotation(JsonIgnoreProperties.class); // EntityHelper.print(ignoreProperties); // // EntityHelper.print(clazz); // try { // Object instance = clazz.newInstance(); // EntityHelper.print(instance); // // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } } catch ( CannotCompileException e ) { e . printStackTrace ( ) ; } // right // mthd.getMethodInfo().addAttribute(attr); return clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<br > 2013 - 10 - 25 下午12 : 29 : 58 [CODESPLIT] private JsonEncoding getJsonEncoding ( String characterEncoding ) { for ( JsonEncoding encoding : JsonEncoding . values ( ) ) { if ( characterEncoding . equals ( encoding . getJavaName ( ) ) ) { return encoding ; } } return JsonEncoding . UTF8 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the given method is originally declared by { [CODESPLIT] public static boolean isObjectMethod ( Method method ) { try { Object . class . getDeclaredMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; return true ; } catch ( SecurityException ex ) { return false ; } catch ( NoSuchMethodException ex ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the target object on which to call the target method . Only necessary when the target method is not static ; else a target class is sufficient . [CODESPLIT] public void setTargetObject ( Object targetObject ) { this . targetObject = targetObject ; if ( targetObject != null ) { this . targetClass = targetObject . getClass ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare the specified method . The method can be invoked any number of times afterwards . [CODESPLIT] public void prepare ( ) throws ClassNotFoundException , NoSuchMethodException { if ( this . staticMethod != null ) { int lastDotIndex = this . staticMethod . lastIndexOf ( ' ' ) ; if ( lastDotIndex == - 1 || lastDotIndex == this . staticMethod . length ( ) ) { throw new IllegalArgumentException ( \"staticMethod must be a fully qualified class plus method name: \" + \"e.g. 'example.MyExampleClass.myExampleMethod'\" ) ; } String className = this . staticMethod . substring ( 0 , lastDotIndex ) ; String methodName = this . staticMethod . substring ( lastDotIndex + 1 ) ; this . targetClass = resolveClassName ( className ) ; this . targetMethod = methodName ; } Class < ? > targetClass = getTargetClass ( ) ; String targetMethod = getTargetMethod ( ) ; if ( targetClass == null ) { throw new IllegalArgumentException ( \"Either 'targetClass' or 'targetObject' is required\" ) ; } if ( targetMethod == null ) { throw new IllegalArgumentException ( \"Property 'targetMethod' is required\" ) ; } Object [ ] arguments = getArguments ( ) ; Class < ? > [ ] argTypes = new Class < ? > [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; ++ i ) { argTypes [ i ] = ( arguments [ i ] != null ? arguments [ i ] . getClass ( ) : Object . class ) ; } // Try to get the exact method first. try { this . methodObject = targetClass . getMethod ( targetMethod , argTypes ) ; } catch ( NoSuchMethodException ex ) { // Just rethrow exception if we can't get any match. this . methodObject = findMatchingMethod ( ) ; if ( this . methodObject == null ) { throw ex ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve the given class name into a Class . <p > The default implementations uses { @code ClassUtils . forName } using the thread context class loader . [CODESPLIT] protected Class < ? > resolveClassName ( String className ) throws ClassNotFoundException { return ClassUtils . forName ( className , ClassUtils . getDefaultClassLoader ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find a matching method with the specified name for the specified arguments . [CODESPLIT] protected Method findMatchingMethod ( ) { String targetMethod = getTargetMethod ( ) ; Object [ ] arguments = getArguments ( ) ; int argCount = arguments . length ; Method [ ] candidates = ReflectionUtils . getAllDeclaredMethods ( getTargetClass ( ) ) ; int minTypeDiffWeight = Integer . MAX_VALUE ; Method matchingMethod = null ; for ( Method candidate : candidates ) { if ( candidate . getName ( ) . equals ( targetMethod ) ) { Class < ? > [ ] paramTypes = candidate . getParameterTypes ( ) ; if ( paramTypes . length == argCount ) { int typeDiffWeight = getTypeDifferenceWeight ( paramTypes , arguments ) ; if ( typeDiffWeight < minTypeDiffWeight ) { minTypeDiffWeight = typeDiffWeight ; matchingMethod = candidate ; } } } } return matchingMethod ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke the specified method . <p > The invoker needs to have been prepared before . [CODESPLIT] public Object invoke ( ) throws InvocationTargetException , IllegalAccessException { // In the static case, target will simply be {@code null}. Object targetObject = getTargetObject ( ) ; Method preparedMethod = getPreparedMethod ( ) ; if ( targetObject == null && ! Modifier . isStatic ( preparedMethod . getModifiers ( ) ) ) { throw new IllegalArgumentException ( \"Target method must not be non-static without a target\" ) ; } ReflectionUtils . makeAccessible ( preparedMethod ) ; return preparedMethod . invoke ( targetObject , getArguments ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Algorithm that judges the match between the declared parameter types of a candidate method and a specific list of arguments that this method is supposed to be invoked with . <p > Determines a weight that represents the class hierarchy difference between types and arguments . A direct match i . e . type Integer - arg of class Integer does not increase the result - all direct matches means weight 0 . A match between type Object and arg of class Integer would increase the weight by 2 due to the superclass 2 steps up in the hierarchy ( i . e . Object ) being the last one that still matches the required type Object . Type Number and class Integer would increase the weight by 1 accordingly due to the superclass 1 step up the hierarchy ( i . e . Number ) still matching the required type Number . Therefore with an arg of type Integer a constructor ( Integer ) would be preferred to a constructor ( Number ) which would in turn be preferred to a constructor ( Object ) . All argument weights get accumulated . <p > Note : This is the algorithm used by MethodInvoker itself and also the algorithm used for constructor and factory method selection in Spring s bean container ( in case of lenient constructor resolution which is the default for regular bean definitions ) . [CODESPLIT] public static int getTypeDifferenceWeight ( Class < ? > [ ] paramTypes , Object [ ] args ) { int result = 0 ; for ( int i = 0 ; i < paramTypes . length ; i ++ ) { if ( ! ClassUtils . isAssignableValue ( paramTypes [ i ] , args [ i ] ) ) { return Integer . MAX_VALUE ; } if ( args [ i ] != null ) { Class < ? > paramType = paramTypes [ i ] ; Class < ? > superClass = args [ i ] . getClass ( ) . getSuperclass ( ) ; while ( superClass != null ) { if ( paramType . equals ( superClass ) ) { result = result + 2 ; superClass = null ; } else if ( ClassUtils . isAssignable ( paramType , superClass ) ) { result = result + 2 ; superClass = superClass . getSuperclass ( ) ; } else { superClass = null ; } } if ( paramType . isInterface ( ) ) { result = result + 1 ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the integer to an unsigned number . [CODESPLIT] private static String toUnsignedString ( int i , int shift ) { char [ ] buf = new char [ 32 ] ; int charPos = 32 ; int radix = 1 << shift ; int mask = radix - 1 ; do { buf [ -- charPos ] = digits [ i & mask ] ; i >>>= shift ; } while ( i != 0 ) ; return new String ( buf , charPos , ( 32 - charPos ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到上传文件的文件头 [CODESPLIT] private static String bytesToHexString ( byte [ ] src ) { StringBuilder stringBuilder = new StringBuilder ( ) ; if ( null == src || src . length <= 0 ) { return null ; } for ( int i = 0 ; i < src . length ; i ++ ) { int v = src [ i ] & 0xFF ; String hv = Integer . toHexString ( v ) ; if ( hv . length ( ) < 2 ) { stringBuilder . append ( 0 ) ; } stringBuilder . append ( hv ) ; } return stringBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取文件类型 [CODESPLIT] public static String getFileType ( File file ) { String res = null ; try { @ SuppressWarnings ( \"resource\" ) FileInputStream fis = new FileInputStream ( file ) ; byte [ ] b = new byte [ 10 ] ; fis . read ( b , 0 , b . length ) ; String fileCode = bytesToHexString ( b ) ; Iterator < String > keyIter = FILE_TYPE_MAP . keySet ( ) . iterator ( ) ; while ( keyIter . hasNext ( ) ) { String key = keyIter . next ( ) ; if ( key . toLowerCase ( ) . startsWith ( fileCode . toLowerCase ( ) ) || fileCode . toLowerCase ( ) . startsWith ( key . toLowerCase ( ) ) ) { res = FILE_TYPE_MAP . get ( key ) ; break ; } } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the given object to a byte array . [CODESPLIT] public static byte [ ] serialize ( Object object ) { if ( object == null ) { return null ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { ObjectOutputStream oos = new ObjectOutputStream ( baos ) ; oos . writeObject ( object ) ; oos . flush ( ) ; } catch ( IOException ex ) { throw new IllegalArgumentException ( \"Failed to serialize object of type: \" + object . getClass ( ) , ex ) ; } return baos . toByteArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize the byte array into an object . [CODESPLIT] public static Object deserialize ( byte [ ] bytes ) { if ( bytes == null ) { return null ; } try { ObjectInputStream ois = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; return ois . readObject ( ) ; } catch ( IOException ex ) { throw new IllegalArgumentException ( \"Failed to deserialize object\" , ex ) ; } catch ( ClassNotFoundException ex ) { throw new IllegalStateException ( \"Failed to deserialize object type\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "打印对象同时加入注释 [CODESPLIT] public void printC ( Object object ) { StackTraceElement [ ] stackTraceElements = StackTraceHelper . getStackTrace ( ) ; StackTraceElement stackTraceElement = stackTraceElements [ 2 ] ; // 调用本类的对象类型堆栈 StringBuilder builder = new StringBuilder ( ) ; builder . append ( \" ------------------------------------------------------------ \" ) ; builder . append ( StringHelper . line ( ) ) ; builder . append ( StackTraceHelper . buildStackTrace ( new StackTraceElement [ ] { stackTraceElement } ) ) ; builder . append ( \"    \" ) ; if ( object == null ) { builder . append ( \"<null>\" ) ; } else { builder . append ( object . getClass ( ) . getSimpleName ( ) ) ; builder . append ( \" =============== \" ) ; String content = buildObjectToString ( object ) ; builder . append ( buildContent ( content ) ) ; } builder . append ( StringHelper . line ( ) ) ; builder . append ( \" ------------------------------------------------------------ \" ) ; System . out . println ( builder . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用反射机制自动ToString <br > 2013 - 8 - 28 下午3 : 16 : 40 [CODESPLIT] public String reflectToString ( Object object ) { if ( object == null ) { return null ; } Class clazz = object . getClass ( ) ; StringBuilder builder = new StringBuilder ( clazz . getName ( ) ) ; builder . append ( \"@\" ) ; builder . append ( Integer . toHexString ( object . hashCode ( ) ) ) ; builder . append ( \"[\" ) ; Set < Method > methods = new LinkedHashSet < Method > ( ) ; Collection < Class > classes = EntityHelper . getAllSuperClassesOfClass ( clazz ) ; for ( Iterator iterator = classes . iterator ( ) ; iterator . hasNext ( ) ; ) { Class claxx = ( Class ) iterator . next ( ) ; Method [ ] clazzMethods = claxx . getDeclaredMethods ( ) ; for ( int i = 0 ; i < clazzMethods . length ; i ++ ) { Method method = clazzMethods [ i ] ; methods . add ( method ) ; } } // for (int i = 0; i < methods.length; i++) { // Method method = methods[i]; for ( Iterator iterator = methods . iterator ( ) ; iterator . hasNext ( ) ; ) { Method method = ( Method ) iterator . next ( ) ; String methodName = method . getName ( ) ; if ( methodName . startsWith ( \"get\" ) && ! Modifier . isStatic ( method . getModifiers ( ) ) && Modifier . isPublic ( method . getModifiers ( ) ) ) { try { Object value = method . invoke ( object ) ; String propertyName = methodName . substring ( 3 , 4 ) . toLowerCase ( ) + methodName . substring ( 4 ) ; if ( propertyName . equals ( \"class\" ) || ignoreProperties . contains ( propertyName ) ) { // 忽略getClass方法 continue ; } builder . append ( propertyName ) ; builder . append ( \"=\" ) ; if ( value == null ) { builder . append ( \"<null>\" ) ; } else { if ( value . getClass ( ) . isArray ( ) ) { int arraySuperLength = Array . getLength ( value ) ; builder . append ( \"{\" ) ; for ( int j = 0 ; j < arraySuperLength ; j ++ ) { Object object2 = Array . get ( value , j ) ; builder . append ( object2 . toString ( ) ) ; if ( j < arraySuperLength - 1 ) { builder . append ( \", \" ) ; } } builder . append ( \"}\" ) ; } else { builder . append ( value . toString ( ) ) ; } } builder . append ( \", \" ) ; } catch ( IllegalArgumentException e ) { } catch ( IllegalAccessException e ) { } catch ( InvocationTargetException e ) { } } } if ( builder . toString ( ) . contains ( \", \" ) ) { builder . replace ( builder . length ( ) - 2 , builder . length ( ) , \"\" ) ; } builder . append ( \"]\" ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) It is assumed that the inputstream is at the start of the file or String ( in order to read the BOM ) . [CODESPLIT] public Charset detectCodepage ( InputStream in , int length ) throws IOException { byte [ ] bom = new byte [ 4 ] ; // Get the byte-order mark, if there is one in . read ( bom , 0 , 4 ) ; // Unicode formats => read BOM byte b = ( byte ) 0xEF ; if ( bom [ 0 ] == ( byte ) 0x00 && bom [ 1 ] == ( byte ) 0x00 && bom [ 2 ] == ( byte ) 0xFE && bom [ 2 ] == ( byte ) 0xFF ) // utf-32BE return Charset . forName ( \"UTF-32BE\" ) ; if ( bom [ 0 ] == ( byte ) 0xFF && bom [ 1 ] == ( byte ) 0xFE && bom [ 2 ] == ( byte ) 0x00 && bom [ 2 ] == ( byte ) 0x00 ) // utf-32BE return Charset . forName ( \"UTF-32LE\" ) ; if ( bom [ 0 ] == ( byte ) 0xEF && bom [ 1 ] == ( byte ) 0xBB && bom [ 2 ] == ( byte ) 0xBF ) // utf-8 return Charset . forName ( \"UTF-8\" ) ; if ( bom [ 0 ] == ( byte ) 0xff && bom [ 1 ] == ( byte ) 0xfe ) // ucs-2le, ucs-4le, and ucs-16le return Charset . forName ( \"UTF-16LE\" ) ; if ( bom [ 0 ] == ( byte ) 0xfe && bom [ 1 ] == ( byte ) 0xff ) // utf-16 and ucs-2 return Charset . forName ( \"UTF-16BE\" ) ; if ( bom [ 0 ] == ( byte ) 0 && bom [ 1 ] == ( byte ) 0 && bom [ 2 ] == ( byte ) 0xfe && bom [ 3 ] == ( byte ) 0xff ) // ucs-4 return Charset . forName ( \"UCS-4\" ) ; return UnknownCharset . getInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断String对象是否包含字符（如果全部为空格也返回false） [CODESPLIT] public static boolean hasText ( String ... string ) { if ( string == null ) { return false ; } boolean flag = true ; for ( String s : string ) { flag = flag && ( s != null && ! \"\" . equals ( s . trim ( ) ) ) ; if ( ! flag ) { return false ; } } return flag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sn = MD5 ( urlencode ( basicString + sk )) <p > 其中 basicString 的算法如下： <p > ( 1 ) get 请求 <p > url 中 http : // 域名 { uri } <p > basicString = uri <p > ( 2 ) post 请求 <p > url 中 http : // 域名 { uri } POST 参数按照key进行从小大到字母排序 <p > 然后拼装成：k1 = v1&amp ; k2 = v2&amp ; k3 = v3&amp ; ... &amp ; kn = vn的格式 = &gt ; { params } <p > basicString = uri + ? + params [CODESPLIT] public String calculateAKSN ( String ak , String sk , String url , List < NameValuePair > nameValuePairs , String method ) { String params = \"\" ; if ( method . equals ( \"POST\" ) ) { Collections . sort ( nameValuePairs , new Comparator < NameValuePair > ( ) { @ Override public int compare ( NameValuePair o1 , NameValuePair o2 ) { StringComparator comparator = new StringComparator ( ) ; return comparator . compare ( o1 . getName ( ) , o2 . getName ( ) ) ; } } ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; for ( Iterator < NameValuePair > iterator = nameValuePairs . iterator ( ) ; iterator . hasNext ( ) ; ) { NameValuePair nameValuePair = iterator . next ( ) ; String name = nameValuePair . getName ( ) ; String value = nameValuePair . getValue ( ) ; stringBuilder . append ( name ) ; stringBuilder . append ( \"=\" ) ; stringBuilder . append ( value ) ; if ( iterator . hasNext ( ) ) { stringBuilder . append ( \"&\" ) ; } } params = stringBuilder . toString ( ) ; } String basicString = url + \"? \" + params ; String sn = null ; try { sn = MD5Helper . encrypt ( URLEncoder . encode ( basicString + sk , \"UTF-8\" ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return sn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all child elements of the given DOM element that match any of the given element names . Only looks at the direct child level of the given element ; do not go into further depth ( in contrast to the DOM API s { @code getElementsByTagName } method ) . [CODESPLIT] public static List < Element > getChildElementsByTagName ( Element ele , String [ ] childEleNames ) { Assert . notNull ( ele , \"Element must not be null\" ) ; Assert . notNull ( childEleNames , \"Element names collection must not be null\" ) ; List < String > childEleNameList = Arrays . asList ( childEleNames ) ; NodeList nl = ele . getChildNodes ( ) ; List < Element > childEles = new ArrayList < Element > ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameMatch ( node , childEleNameList ) ) { childEles . add ( ( Element ) node ) ; } } return childEles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all child elements of the given DOM element that match the given element name . Only look at the direct child level of the given element ; do not go into further depth ( in contrast to the DOM API s { @code getElementsByTagName } method ) . [CODESPLIT] public static List < Element > getChildElementsByTagName ( Element ele , String childEleName ) { return getChildElementsByTagName ( ele , new String [ ] { childEleName } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method that returns the first child element identified by its name . [CODESPLIT] public static Element getChildElementByTagName ( Element ele , String childEleName ) { Assert . notNull ( ele , \"Element must not be null\" ) ; Assert . notNull ( childEleName , \"Element name must not be null\" ) ; NodeList nl = ele . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element && nodeNameMatch ( node , childEleName ) ) { return ( Element ) node ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method that returns the first child element value identified by its name . [CODESPLIT] public static String getChildElementValueByTagName ( Element ele , String childEleName ) { Element child = getChildElementByTagName ( ele , childEleName ) ; return ( child != null ? getTextValue ( child ) : null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all child elements of the given DOM element [CODESPLIT] public static List < Element > getChildElements ( Element ele ) { Assert . notNull ( ele , \"Element must not be null\" ) ; NodeList nl = ele . getChildNodes ( ) ; List < Element > childEles = new ArrayList < Element > ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node node = nl . item ( i ) ; if ( node instanceof Element ) { childEles . add ( ( Element ) node ) ; } } return childEles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the text value from the given DOM element ignoring XML comments . <p > Appends all CharacterData nodes and EntityReference nodes into a single String value excluding Comment nodes . Only exposes actual user - specified text no default values of any kind . [CODESPLIT] public static String getTextValue ( Element valueEle ) { Assert . notNull ( valueEle , \"Element must not be null\" ) ; StringBuilder sb = new StringBuilder ( ) ; NodeList nl = valueEle . getChildNodes ( ) ; for ( int i = 0 ; i < nl . getLength ( ) ; i ++ ) { Node item = nl . item ( i ) ; if ( ( item instanceof CharacterData && ! ( item instanceof Comment ) ) || item instanceof EntityReference ) { sb . append ( item . getNodeValue ( ) ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Namespace - aware equals comparison . Returns { [CODESPLIT] public static boolean nodeNameEquals ( Node node , String desiredName ) { Assert . notNull ( node , \"Node must not be null\" ) ; Assert . notNull ( desiredName , \"Desired name must not be null\" ) ; return nodeNameMatch ( node , desiredName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches the given node s name and local name against the given desired name . [CODESPLIT] private static boolean nodeNameMatch ( Node node , String desiredName ) { return ( desiredName . equals ( node . getNodeName ( ) ) || desiredName . equals ( node . getLocalName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches the given node s name and local name against the given desired names . [CODESPLIT] private static boolean nodeNameMatch ( Node node , Collection < ? > desiredNames ) { return ( desiredNames . contains ( node . getNodeName ( ) ) || desiredNames . contains ( node . getLocalName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@throws java . io . IOException [CODESPLIT] private final void renderHeaderCell ( String columnName , int firstOrLast ) throws IOException { m_out . write ( this . HeadCellStartTag ( ( firstOrLast == FIRST_CELL_IN_ROW ) ) ) ; m_out . write ( columnName ) ; m_out . write ( this . HeadCellStopTag ( ( firstOrLast == LAST_CELL_IN_ROW ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public final void render ( TableModel model ) throws IOException { this . m_out . write ( this . TableStartTag ( ) ) ; int rows = model . getRowCount ( ) ; // write header m_out . write ( this . HeadRowStartTag ( ) ) ; this . renderHeader ( model ) ; m_out . write ( this . HeadRowStopTag ( ) ) ; for ( int i = 0 ; i < rows ; i ++ ) { this . renderRow ( model , i ) ; } this . m_out . write ( this . TableStopTag ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "移除主机字符，例如传入admin@xiongyingqi . com，那么该方法将截取@之前的字符返回admin [CODESPLIT] public static String removeDomain ( String str ) { if ( str != null && ! \"\" . equals ( str ) ) { int index = str . indexOf ( \"@\" ) ; if ( index >= 0 ) { str = str . substring ( 0 , index ) ; } } return str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the given amount of spaces to the String . <p > [CODESPLIT] public static final String appendSpaces ( final String s , final int count ) { StringBuffer tmp = new StringBuffer ( s ) ; for ( int i = 0 ; i < count ; i ++ ) { tmp . append ( \" \" ) ; } return tmp . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given Object is no Array it s toString - method is invoked . Primitive type - Arrays and Object - Arrays are introspected using java . lang . reflect . Array . Convention for creation fo String - representation : <p > [CODESPLIT] public static final String arrayToString ( final Object isArr ) { String result = StringUtil . arrayToString ( isArr , \",\" ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given Object is no Array it s toString - method is invoked . Primitive type - Arrays and Object - Arrays are introspected using java . lang . reflect . Array . Convention for creation for String - representation : <br > [CODESPLIT] public static final String arrayToString ( final Object isArr , final String separator ) { String result ; if ( isArr == null ) { result = \"null\" ; } else { Object element ; StringBuffer tmp = new StringBuffer ( ) ; try { int length = Array . getLength ( isArr ) ; tmp . append ( \"[\" ) ; for ( int i = 0 ; i < length ; i ++ ) { element = Array . get ( isArr , i ) ; if ( element == null ) { tmp . append ( \"null\" ) ; } else { tmp . append ( element . toString ( ) ) ; } if ( i < length - 1 ) { tmp . append ( separator ) ; } } tmp . append ( \"]\" ) ; result = tmp . toString ( ) ; } catch ( ArrayIndexOutOfBoundsException bound ) { // programming mistake or bad Array.getLength(obj). tmp . append ( \"]\" ) ; result = tmp . toString ( ) ; } catch ( IllegalArgumentException noarr ) { result = isArr . toString ( ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the singleton instance of this class . <p > [CODESPLIT] public static StringUtil instance ( ) { if ( StringUtil . instance == null ) { StringUtil . instance = new StringUtil ( ) ; } return StringUtil . instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the argument is null or consists of whitespaces only . <p > [CODESPLIT] public static boolean isEmpty ( final String test ) { boolean result ; if ( test == null ) { result = true ; } else { result = test . trim ( ) . length ( ) == 0 ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Little String output - helper that modifies the given LinkedList by getting it s Objects and replace them by their toString () - representation . <p > [CODESPLIT] public static final void listOfArraysToString ( final List < Object > objects ) { if ( objects == null ) { return ; } int stop = objects . size ( ) ; for ( int i = 0 ; i < stop ; i ++ ) { objects . add ( i , StringUtil . arrayToString ( objects . remove ( i ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the maximum length of a { @link Object#toString () } result in characters within the given List . <p > [CODESPLIT] public static final int longestStringRepresentation ( final List < Object > objects ) { int result ; if ( objects == null ) { result = 0 ; } else { int maxsize = 0 ; int tint = 0 ; String tmp ; int stop = objects . size ( ) ; for ( int i = 0 ; i < stop ; i ++ ) { tmp = StringUtil . arrayToString ( objects . get ( i ) ) ; tint = tmp . length ( ) ; if ( tint > maxsize ) { maxsize = tint ; } } // maximum size known. result = maxsize ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the necessary amount of spaces to the string until it has the givn length . No Exception is thrown if the length of the String is shorter than the given length but nothing will happen and a message will be printed to the System . out . [CODESPLIT] public static final String setSize ( final String s , final int length ) { String result = s ; int oldlen = s . length ( ) ; if ( oldlen > length ) { System . err . println ( \"greenpeace.util.setSize(String s,int length): length (\" + length + \") is smaller than s.length(\" + oldlen + \") : \" + s ) ; } else { int tofill = length - oldlen ; result = StringUtil . appendSpaces ( s , tofill ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Modifies the given LinkedList by getting it s Objects and replace them by their toString () - representation concatenated with the necessary amount of white spaces that every String in the List will have the same amount of characters . <p > [CODESPLIT] public static final void toLongestString ( final List < Object > objects ) { if ( objects == null ) { return ; } int maxsize = 0 ; int tint = 0 ; String tmp ; int stop = objects . size ( ) ; for ( int i = 0 ; i < stop ; i ++ ) { StringUtil . arrayToString ( objects . get ( i ) ) ; tmp = ( String ) objects . get ( i ) ; tint = tmp . length ( ) ; if ( tint > maxsize ) { maxsize = tint ; } objects . add ( i , tmp ) ; } // maximum size known. for ( int i = 0 ; i < stop ; i ++ ) { objects . add ( i , StringUtil . setSize ( ( String ) objects . remove ( i ) , maxsize ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "增加参数，默认使用urlEncoding [CODESPLIT] public HttpBuilder param ( String name , String value ) { return param ( name , value , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "增加参数 [CODESPLIT] public HttpBuilder param ( String name , String value , boolean urlEncoding ) { String encodedValue = null ; if ( urlEncoding && value != null ) { try { encodedValue = URLEncoder . encode ( value , charset . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { Logger . error ( e ) ; } } if ( encodedValue == null ) { encodedValue = value ; } NameValuePair nameValuePair = new BasicNameValuePair ( name , encodedValue ) ; this . nameValuePairs . add ( nameValuePair ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据输入的Unicode字符，获取它的GB2312编码或者ascii编码， [CODESPLIT] public static short getGB2312Id ( char ch ) { try { byte [ ] buffer = Character . toString ( ch ) . getBytes ( \"GB2312\" ) ; if ( buffer . length != 2 ) { // 正常情况下buffer应该是两个字节，否则说明ch不属于GB2312编码，故返回'?'，此时说明不认识该字符 return - 1 ; } int b0 = ( int ) ( buffer [ 0 ] & 0x0FF ) - 161 ; // 编码从A1开始，因此减去0xA1=161 int b1 = ( int ) ( buffer [ 1 ] & 0x0FF ) - 161 ; // 第一个字符和最后一个字符没有汉字，因此每个区只收16*6-2=94个汉字 return ( short ) ( b0 * 94 + b1 ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取包下所有被Controller注解的类所表示的路径 <br > 2013 - 10 - 17 下午1 : 02 : 45 [CODESPLIT] public static Collection < String > getAnnotationMappedPaths ( Package pkg ) { if ( pkg == null ) { return null ; } Collection < String > rs = new LinkedHashSet < String > ( ) ; Set < Class < ? > > classes = PackageUtil . getclass ( pkg ) ; for ( Iterator iterator = classes . iterator ( ) ; iterator . hasNext ( ) ; ) { Class < ? > clazz = ( Class < ? > ) iterator . next ( ) ; if ( clazz . isAnnotationPresent ( Controller . class ) ) { String [ ] clazzPaths = null ; if ( clazz . isAnnotationPresent ( RequestMapping . class ) ) { RequestMapping typeMapping = clazz . getAnnotation ( RequestMapping . class ) ; clazzPaths = typeMapping . value ( ) ; } String [ ] methodPaths = null ; Collection < String > methodPathCollection = new ArrayList < String > ( ) ; Method [ ] methods = clazz . getDeclaredMethods ( ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { Method method = methods [ i ] ; if ( method . isAnnotationPresent ( RequestMapping . class ) ) { RequestMapping typeMapping = method . getAnnotation ( RequestMapping . class ) ; String [ ] methodPathsVar = typeMapping . value ( ) ; Collections . addAll ( methodPathCollection , methodPathsVar ) ; } } if ( methodPathCollection . size ( ) > 0 ) { methodPaths = methodPathCollection . toArray ( new String [ ] { } ) ; } if ( clazzPaths != null && clazzPaths . length > 0 && methodPaths != null && methodPaths . length > 0 ) { for ( int i = 0 ; i < clazzPaths . length ; i ++ ) { String typePath = clazzPaths [ i ] ; typePath = checkForPath ( typePath ) ; for ( int j = 0 ; j < methodPaths . length ; j ++ ) { String methodPath = methodPaths [ j ] ; methodPath = checkForPath ( methodPath ) ; String mappedPath = typePath + methodPath ; rs . add ( mappedPath ) ; } } } else if ( ( clazzPaths != null && clazzPaths . length > 0 ) && ( methodPaths == null || methodPaths . length == 0 ) ) { for ( int i = 0 ; i < clazzPaths . length ; i ++ ) { String typePath = clazzPaths [ i ] ; typePath = checkForPath ( typePath ) ; rs . add ( typePath ) ; } } else if ( ( methodPaths != null && methodPaths . length > 0 ) && ( clazzPaths == null || clazzPaths . length == 0 ) ) { EntityHelper . print ( methodPaths ) ; for ( int i = 0 ; i < clazzPaths . length ; i ++ ) { String typePath = clazzPaths [ i ] ; typePath = checkForPath ( typePath ) ; rs . add ( typePath ) ; } } } } return rs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start to monitor given handle object for becoming weakly reachable . When the handle isn t used anymore the given listener will be called . [CODESPLIT] public static void monitor ( Object handle , ReleaseListener listener ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"Monitoring handle [\" + handle + \"] with release listener [\" + listener + \"]\" ) ; } // Make weak reference to this handle, so we can say when // handle is not used any more by polling on handleQueue. WeakReference < Object > weakRef = new WeakReference < Object > ( handle , handleQueue ) ; // Add monitored entry to internal map of all monitored entries. addEntry ( weakRef , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add entry to internal map of tracked entries . Internal monitoring thread is started if not already running . [CODESPLIT] private static void addEntry ( Reference < ? > ref , ReleaseListener entry ) { synchronized ( WeakReferenceMonitor . class ) { // Add entry, the key is given reference. trackedEntries . put ( ref , entry ) ; // Start monitoring thread lazily. if ( monitoringThread == null ) { monitoringThread = new Thread ( new MonitoringProcess ( ) , WeakReferenceMonitor . class . getName ( ) ) ; monitoringThread . setDaemon ( true ) ; monitoringThread . start ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether to keep the monitoring thread alive i . e . whether there are still entries being tracked . [CODESPLIT] private static boolean keepMonitoringThreadAlive ( ) { synchronized ( WeakReferenceMonitor . class ) { if ( ! trackedEntries . isEmpty ( ) ) { return true ; } else { logger . debug ( \"No entries left to track - stopping reference monitor thread\" ) ; monitoringThread = null ; return false ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public static final long DB = 1024 * NB ; [CODESPLIT] public static boolean checkFileSizeLessThen ( File file , long size ) { try { fileNotFullAndExists ( file ) ; } catch ( Exception e ) { return false ; } return file . length ( ) <= size ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取文件类型 <br > 2013 - 9 - 2 下午9 : 08 : 51 [CODESPLIT] public static String getMimeType ( File data ) { if ( ! data . exists ( ) ) { return null ; } ContentHandler contenthandler = new BodyContentHandler ( ) ; Metadata metadata = new Metadata ( ) ; metadata . set ( Metadata . RESOURCE_NAME_KEY , data . getName ( ) ) ; Parser parser = new AutoDetectParser ( ) ; try { parser . parse ( new FileInputStream ( data ) , contenthandler , metadata , null ) ; } catch ( FileNotFoundException e ) { LOGGER . error ( e ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } catch ( SAXException e ) { LOGGER . error ( e ) ; } catch ( TikaException e ) { LOGGER . error ( e ) ; } // System.out.println(\"Mime: \" + metadata.get(Metadata.CONTENT_TYPE)); // System.out.println(\"Mime str: \" + metadata.toString()); return metadata . get ( Metadata . CONTENT_TYPE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据后缀名从文件夹获取文件 <br > 2013 - 9 - 6 下午3 : 15 : 56 [CODESPLIT] public static File [ ] listFilesBySuffix ( File folder , final String suffix ) { File [ ] files = folder . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( File paramFile , String paramString ) { String newSuffix = suffix ; if ( ! newSuffix . startsWith ( \".\" ) ) { newSuffix = \".\" + newSuffix ; } if ( paramString . endsWith ( newSuffix ) ) { return true ; } return false ; } } ) ; return files ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从url地址读取文件信息并写入到临时文件 <br > 2013 - 9 - 2 下午2 : 57 : 15 [CODESPLIT] public static File readURL ( String urlStr ) throws IOException { URL url = new URL ( urlStr ) ; // System.out.println(\" ----------------- url ----------------- \"); // System.out.println(urlStr); // System.out.println(url.getPath()); // System.out.println(url.getHost()); // System.out.println(\" ---------------------------------- \"); InputStream inputStream = null ; if ( url . getHost ( ) . trim ( ) . equals ( \"\" ) ) { // inputStream = new FileInputStream(url.getFile()); File file = new File ( url . getFile ( ) ) ; return file ; } else { inputStream = url . openStream ( ) ; } return readInputStream ( inputStream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从流读取文件内容 <br > 2013 - 9 - 2 下午2 : 52 : 39 [CODESPLIT] public static File readInputStream ( InputStream inputStream ) { String filePath = System . getProperty ( \"java.io.tmpdir\" , \"tmp/\" ) ; filePath += System . currentTimeMillis ( ) + StringUtil . randomString ( 8 ) + \".tmp\" ; return readInputStream ( inputStream , filePath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将文件转换为URL地址 <br > 2013 - 9 - 2 下午10 : 07 : 14 [CODESPLIT] public static URL toURL ( File file ) { if ( file == null || ! file . exists ( ) ) { return null ; } URI uri = file . toURI ( ) ; URL url = null ; try { url = uri . toURL ( ) ; } catch ( MalformedURLException e ) { LOGGER . error ( e ) ; } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将流读入到文件内 <br > 2013 - 9 - 2 下午10 : 04 : 17 [CODESPLIT] public static File readInputStream ( InputStream inputStream , File file ) { try { validateFile ( file ) ; } catch ( Exception e2 ) { e2 . printStackTrace ( ) ; } try { FileOutputStream outputStream = new FileOutputStream ( file ) ; int length = - 1 ; try { int bufferSize = 128 ; byte [ ] buffer = new byte [ bufferSize ] ; while ( ( length = inputStream . read ( buffer ) ) != - 1 ) { if ( length != bufferSize ) { System . arraycopy ( buffer , 0 , buffer , 0 , length ) ; } outputStream . write ( buffer ) ; } } catch ( IOException e ) { LOGGER . error ( e ) ; } finally { // try { // inputStream.close(); // } catch (IOException e1) { // e1.printStackTrace(); // } try { inputStream . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } try { outputStream . flush ( ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } try { outputStream . close ( ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } } } catch ( FileNotFoundException e1 ) { e1 . printStackTrace ( ) ; return null ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "读取指定文件的文件内容（以String的形式） <br > 2013 - 8 - 30 下午5 : 26 : 55 [CODESPLIT] public static String readFileToString ( File file ) { byte [ ] bts = null ; try { bts = readFileToBytes ( file ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } String content = null ; try { content = new String ( bts , getEncode ( file ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将源文件剪切到目标文件 [CODESPLIT] public static boolean cutFile ( File originFile , File targetFile ) { Assert . notNull ( originFile ) ; Assert . notNull ( targetFile ) ; copyFile ( originFile , targetFile ) ; if ( originFile . length ( ) == targetFile . length ( ) ) { return originFile . delete ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "读取inputStream并返回字节数组 <br > 2013 - 9 - 3 下午12 : 10 : 06 [CODESPLIT] public static byte [ ] readInputStreamToBytes ( InputStream inputStream ) throws Exception { byte [ ] data = null ; try { int bufferSize = 128 ; byte [ ] buffer = new byte [ bufferSize ] ; int offset = 0 ; ByteBuffer byteBuffer = ByteBuffer . allocate ( 1024 ) ; int length = - 1 ; while ( ( length = inputStream . read ( buffer ) ) != - 1 ) { // if(length != bufferSize){ // System.arraycopy(buffer, 0, data, offset, length); // } //                    System.arraycopy(buffer, 0, data, offset, length);// 从缓冲区拷贝数组 if ( offset + length > byteBuffer . limit ( ) ) { byteBuffer = growByteBuffer ( byteBuffer , ( int ) ( byteBuffer . limit ( ) * 1.5 ) ) ; } byteBuffer . put ( buffer , 0 , length ) ; offset += length ; } byteBuffer . flip ( ) ; //            byteBuffer.limit(offset); data = new byte [ offset ] ; byteBuffer . get ( data , 0 , offset ) ; //            data = byteBuffer.array(); } catch ( IOException e ) { LOGGER . error ( e ) ; } finally { try { inputStream . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "读取文件内容并返回字节数组 <br > 2013 - 9 - 3 下午12 : 10 : 06 [CODESPLIT] public static byte [ ] readFileToBytes ( File iconFile ) throws Exception { try { validateFile ( iconFile ) ; } catch ( Exception e2 ) { e2 . printStackTrace ( ) ; } long fileSize = iconFile . length ( ) ; if ( fileSize > Integer . MAX_VALUE ) { throw new Exception ( \"读取的文件过大！\");   } byte [ ] data = new byte [ ( int ) fileSize ] ; // 由于文件已经确定，因此大小也可以确定 try { int length = - 1 ; FileInputStream inputStream = new FileInputStream ( iconFile ) ; try { int bufferSize = 128 ; byte [ ] buffer = new byte [ bufferSize ] ; int offset = 0 ; while ( ( length = inputStream . read ( buffer ) ) != - 1 ) { // if(length != bufferSize){ // System.arraycopy(buffer, 0, data, offset, length); // } System . arraycopy ( buffer , 0 , data , offset , length ) ; // 从缓冲区拷贝数组 offset += length ; } } catch ( IOException e ) { LOGGER . error ( e ) ; } finally { try { inputStream . close ( ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; } } } catch ( FileNotFoundException e1 ) { e1 . printStackTrace ( ) ; return null ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将字节组写入文件 <br > 2013 - 9 - 3 下午2 : 39 : 21 [CODESPLIT] public static File writeBytesToFile ( byte [ ] data , File file ) { try { validateFile ( file ) ; } catch ( Exception e1 ) { e1 . printStackTrace ( ) ; } FileOutputStream outputStream = null ; try { outputStream = new FileOutputStream ( file ) ; outputStream . write ( data ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; LOGGER . error ( e ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; LOGGER . error ( e ) ; } finally { if ( outputStream != null ) { try { outputStream . flush ( ) ; outputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; LOGGER . error ( e ) ; } } } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将字符串写入文件 <br > 2013 - 9 - 6 下午12 : 09 : 45 [CODESPLIT] public static File writeStringToFile ( File file , String string ) { try { byte [ ] bts = string . getBytes ( getEncode ( file ) ) ; file = writeBytesToFile ( bts , file ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; ; LOGGER . error ( e ) ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将对象写入文件 <br > 2013 - 9 - 6 下午1 : 08 : 58 [CODESPLIT] public static void serializeObjectToFile ( File targetFile , Serializable serializable ) { FileOutputStream fileOutputStream = null ; ObjectOutputStream objectOutputStream = null ; try { fileOutputStream = new FileOutputStream ( targetFile ) ; try { objectOutputStream = new ObjectOutputStream ( fileOutputStream ) ; objectOutputStream . writeObject ( serializable ) ; } catch ( IOException e ) { LOGGER . error ( e ) ; } } catch ( FileNotFoundException e ) { LOGGER . error ( e ) ; } finally { closeOutStream ( objectOutputStream ) ; closeOutStream ( fileOutputStream ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve $ { ... } placeholders in the given text replacing them with corresponding system property values . Unresolvable placeholders with no default value are ignored and passed through unchanged if the flag is set to true . [CODESPLIT] public static String resolvePlaceholders ( String text , boolean ignoreUnresolvablePlaceholders ) { PropertyPlaceholderHelper helper = ( ignoreUnresolvablePlaceholders ? nonStrictHelper : strictHelper ) ; return helper . replacePlaceholders ( text , new SystemPropertyPlaceholderResolver ( text ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------- 包定义和导入包 ---------------------------------------- [CODESPLIT] private String findPackage ( ) { Matcher matcher = PATTERN_FIND_PACKAGE . matcher ( content ) ; if ( matcher . find ( ) ) { return matcher . group ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检查导入包 [CODESPLIT] private void checkImport ( ) { Set < String > classImports = new HashSet < String > ( ) ; classImports . addAll ( builder . getImports ( ) ) ; classImports . removeAll ( findImports ( content ) ) ; // 移除已经导入的包 Set < String > classImportsToRemove = new HashSet < String > ( ) ; // 如果要导入的包与类所在的package一致，则忽略导入 final String packageStr = findPackage ( ) ; // 类所定义的包路径 if ( packageStr != null ) { //如果定义了包路径，则在包路径后面新增导入 String packageName = findPackageName ( packageStr ) ; for ( String impt : classImports ) { int point = impt . lastIndexOf ( \".\" ) ; String pkgNameOfImport = impt . substring ( 0 , point ) ; //截取import的类所属包 if ( pkgNameOfImport . equals ( packageName ) ) { // 如果包已经导入，则取消导入 classImportsToRemove . add ( impt ) ; } } classImports . removeAll ( classImportsToRemove ) ; //如果定义了包路径，则在包路径后面新增导入 StringBuilder builder = new StringBuilder ( packageStr ) ; builder . append ( StringHelper . line ( ) ) ; for ( String toImport : classImports ) { builder . append ( StringHelper . line ( ) ) ; builder . append ( \"import \" ) ; builder . append ( toImport ) ; builder . append ( \";\" ) ; } content = StringHelper . replaceFirst ( content , packageStr , builder . toString ( ) ) ; } else { // 如果没有定义包，则在头部导入包 StringBuilder builder = new StringBuilder ( ) ; for ( String toImport : classImports ) { builder . append ( StringHelper . line ( ) ) ; builder . append ( \"import \" ) ; builder . append ( toImport ) ; builder . append ( \";\" ) ; } content = builder . append ( content ) . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检查class定义段 [CODESPLIT] private void checkClass ( ) { Matcher findClassMatcher = PATTERN_FIND_CLASS_SEGMENT . matcher ( content ) ; if ( findClassMatcher . find ( ) ) { final String classDefine = findClassMatcher . group ( ) ; // 查找类定义 String classDefineReplace = checkSuperClass ( classDefine ) ; classDefineReplace = checkInterfaces ( classDefineReplace ) ; content = StringHelper . replaceFirst ( content , classDefine , classDefineReplace ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查找已有的接口定义 [CODESPLIT] private Set < String > findInterfaces ( String interfaceDefineString ) { String interfaceStrings = StringHelper . replaceFirst ( interfaceDefineString , \"implements\" , \"\" ) ; String [ ] interfaces = interfaceStrings . split ( \",\" ) ; Set < String > stringSet = new HashSet < String > ( ) ; for ( String interfaceString : interfaces ) { stringSet . add ( interfaceString . trim ( ) ) ; } return stringSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检查implements关键字 [CODESPLIT] private String checkInterfaces ( String classSegment ) { if ( builder . getInterfaces ( ) == null || builder . getInterfaces ( ) . size ( ) == 0 ) { return classSegment ; } Matcher matcher = PATTERN_FIND_INTERCES . matcher ( classSegment ) ; if ( matcher . find ( ) ) { final String interfaceDefineString = matcher . group ( ) ; Set < String > interfaceSet = findInterfaces ( interfaceDefineString ) ; StringBuilder interfaceDefineStringReplace = new StringBuilder ( interfaceDefineString ) ; for ( String interfaceName : builder . getInterfaces ( ) ) { if ( interfaceSet . contains ( interfaceName ) ) { // 如果已经存在接口的定义，则跳过该定义 continue ; } interfaceDefineStringReplace . append ( \", \" ) ; interfaceDefineStringReplace . append ( interfaceName ) ; } classSegment = StringHelper . replaceFirst ( classSegment , interfaceDefineString , interfaceDefineStringReplace . toString ( ) ) ; } else { final String interfaceDefineString = \"{\" ; StringBuilder interfaceDefineStringReplace = new StringBuilder ( \"implements \" ) ; boolean isFirstInterface = true ; for ( String interfaceName : builder . getInterfaces ( ) ) { if ( ! isFirstInterface ) { interfaceDefineStringReplace . append ( \", \" ) ; } if ( isFirstInterface ) { isFirstInterface = false ; } interfaceDefineStringReplace . append ( interfaceName ) ; } interfaceDefineStringReplace . append ( interfaceDefineString ) ; classSegment = StringHelper . replaceFirst ( classSegment , interfaceDefineString , interfaceDefineStringReplace . toString ( ) ) ; } return classSegment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "检查extends关键字 [CODESPLIT] private String checkSuperClass ( String classSegment ) { if ( builder . isRemoveSuperClass ( ) || builder . getSuperClass ( ) != null ) { Matcher matcher = PATTERN_FIND_SUPER_CLASS . matcher ( classSegment ) ; String superClassString = \"\" ; if ( builder . getSuperClass ( ) != null ) { superClassString = \"extends \" + builder . getSuperClass ( ) + \" \" ; } if ( matcher . find ( ) ) { String replacement = matcher . group ( ) ; classSegment = StringHelper . replaceFirst ( classSegment , replacement , superClassString ) ; } else { Matcher classNameMatcher = PATTERN_FIND_CLASS_NAME . matcher ( classSegment ) ; if ( classNameMatcher . find ( ) ) { String className = classNameMatcher . group ( ) ; String justClassName = findClassName ( className ) ; if ( justClassName != null && justClassName . equals ( builder . getSuperClass ( ) ) ) { return classSegment ; } classSegment = StringHelper . replaceFirst ( classSegment , className , className + superClassString ) ; } } } return classSegment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------- 代码段 ---------------------------------------- [CODESPLIT] private void checkCodeFragment ( ) { Matcher matcher = PATTERN_FIND_CLASS_SEGMENT . matcher ( content ) ; if ( matcher . find ( ) ) { final String classDefine = matcher . group ( ) ; StringBuilder builder = new StringBuilder ( classDefine ) ; for ( String codeFragment : this . builder . getCodeFragments ( ) ) { builder . append ( StringHelper . line ( ) ) ; builder . append ( codeFragment ) ; } content = StringHelper . replaceFirst ( content , classDefine , builder . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------- 移除注解 -------------------------- [CODESPLIT] private void checkAnnotations ( ) { if ( ! builder . isRemoveAnnotations ( ) ) { return ; } Matcher matcher = PATTERN_FIND_ANNOTAION . matcher ( content ) ; while ( matcher . find ( ) ) { final String annotation = matcher . group ( ) ; //            StringBuilder builder = new StringBuilder(annotation); //            for (String codeFragment : this.builder.getCodeFragments()) { //                builder.append(StringHelper.line()); //                builder.append(codeFragment); //            } content = StringHelper . replaceFirst ( content , annotation , \"\" ) ; EntityHelper . print ( content ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the Path to the My Documents folder or <code > null< / code > [CODESPLIT] public static String getMyDocumentsFromWinRegistry ( ) { try { Process process = Runtime . getRuntime ( ) . exec ( PERSONAL_FOLDER_CMD ) ; StreamReader streamreader = new StreamReader ( process . getInputStream ( ) ) ; streamreader . start ( ) ; process . waitFor ( ) ; streamreader . join ( ) ; String result = streamreader . getResult ( ) ; int p = result . indexOf ( REGSTR_TOKEN ) ; if ( p == - 1 ) return null ; return result . substring ( p + REGSTR_TOKEN . length ( ) ) . trim ( ) ; } catch ( Exception e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test the phone number from which the city is using Taobao API [CODESPLIT] public static String calcMobileCity ( String mobileNumber ) throws MalformedURLException { ObjectMapper objectMapper = new ObjectMapper ( ) ; String jsonString = null ; String urlString = \"http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=\" + mobileNumber ; StringBuffer sb = new StringBuffer ( ) ; BufferedReader buffer ; URL url = new URL ( urlString ) ; try { InputStream in = url . openStream ( ) ; //solve the garbage problem buffer = new BufferedReader ( new InputStreamReader ( in , \"gb2312\" ) ) ; String line = null ; while ( ( line = buffer . readLine ( ) ) != null ) { sb . append ( line ) ; } in . close ( ) ; buffer . close ( ) ; // System.out.println(sb.toString()); jsonString = sb . toString ( ) ; EntityHelper . print ( jsonString ) ; //replace \\ jsonString = jsonString . replaceAll ( \"^[__]\\\\w{14}+[_ = ]+\" , \"[\" ) ; // System.out.println(jsonString+\"]\"); String jsonString2 = jsonString + \"]\" ; //json object into the STRING //            array = JSONArray.fromObject(jsonString2); //Get JSONArray of JSONObject object , easy to read array of key-value pairs in //            jsonObject = array.getJSONObject(0); } catch ( Exception e ) { e . printStackTrace ( ) ; } //        return jsonObject.getString(\"province\"); return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static void main ( String [ ] args ) throws Exception { TimerHelper . getTime ( ) ; Random random = new Random ( ) ; for ( int i = 0 ; i < 100 ; i ++ ) { long number = 13000000000L + random . nextInt ( 1000000000 ) ; String testMobileNumber = \"\" + number ; //            System.out.println(getMobileAddress(testMobileNumber)); ThreadPool . invoke ( null , PhoneNumberAddress . class . getMethod ( \"getMobileAddress\" , String . class ) , testMobileNumber ) ; } ThreadPool . shutDown ( ) ; System . out . println ( TimerHelper . getTime ( ) ) ; //        System.out.println(calcMobilesCities(mobileList).toString()); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "按照日期进行排序 <br > 2013 - 6 - 25 下午9 : 46 : 45 [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public List sortByDateTime ( Collection < ? extends T > collection , final Field field , final boolean asc ) { if ( collection == null ) { return null ; } List list = new ArrayList ( ) ; list . addAll ( collection ) ; Collections . sort ( list , new Comparator < T > ( ) { @ Override public int compare ( T o1 , T o2 ) { Object object = invokeMethod ( o1 , field ) ; Object object2 = invokeMethod ( o2 , field ) ; if ( object == null || object2 == null ) { return 0 ; } int value = 0 ; if ( object instanceof Date ) { Date v1 = ( Date ) object ; Date v2 = ( Date ) object2 ; if ( v1 . getTime ( ) < v2 . getTime ( ) ) { value = - 1 ; } else if ( v1 . getTime ( ) > v2 . getTime ( ) ) { value = 1 ; } if ( ! asc ) { value = - value ; } } return value ; } } ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enable indenting for the supplied { @link javax . xml . transform . Transformer } . <p > If the underlying XSLT engine is Xalan then the special output key { @code indent - amount } will be also be set to a value of { @link #DEFAULT_INDENT_AMOUNT } characters . [CODESPLIT] public static void enableIndenting ( Transformer transformer , int indentAmount ) { Assert . notNull ( transformer , \"Transformer must not be null\" ) ; Assert . isTrue ( indentAmount > - 1 , \"The indent amount cannot be less than zero : got \" + indentAmount ) ; transformer . setOutputProperty ( OutputKeys . INDENT , \"yes\" ) ; try { // Xalan-specific, but this is the most common XSLT engine in any case transformer . setOutputProperty ( \"{http://xml.apache.org/xslt}indent-amount\" , String . valueOf ( indentAmount ) ) ; } catch ( IllegalArgumentException ignored ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disable indenting for the supplied { @link javax . xml . transform . Transformer } . [CODESPLIT] public static void disableIndenting ( Transformer transformer ) { Assert . notNull ( transformer , \"Transformer must not be null\" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , \"no\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取与上个计时点以毫秒为单位的时差 ，如果是第一个计时点，则开始即时并返回0<br > 此方法是以线程和调用类来区别计时的，即：不同的类或不同的线程都会导致计时器的从0开始计时<br > 2013 - 7 - 26 下午6 : 21 : 40 [CODESPLIT] public static long getTime ( ) { // StackTraceHelper.printStackTrace(); StackTraceElement [ ] stackTraceElements = StackTraceHelper . getStackTrace ( ) ; StackTraceElement stackTraceElement = stackTraceElements [ 2 ] ; // 调用本类的对象类型堆栈 String clazz = stackTraceElement . getClassName ( ) ; // 调用本类的对象类型 Thread thread = Thread . currentThread ( ) ; TimerHolder holder = new TimerHolder ( ) ; holder . setObject ( clazz ) ; holder . setThread ( thread ) ; // String methodName = stackTraceElement.getMethodName(); // int lineNumber = stackTraceElement.getLineNumber(); // long hashCode = 17; // hashCode = 37 * hashCode + clazz.hashCode(); // hashCode = 37 * hashCode + methodName.hashCode(); // hashCode = 37 * hashCode + lineNumber; // System.out.println(\"stackTraceElement.getClassName() ========= \" + // stackTraceElement.getClassName()); Long startTime = holderObjects . get ( holder ) ; // System.out.println(stackTraceElement); if ( startTime == null ) { startTime = System . currentTimeMillis ( ) ; } long time = System . currentTimeMillis ( ) - startTime ; startTime = System . currentTimeMillis ( ) ; holderObjects . put ( holder , startTime ) ; return time ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a { @code QName } to a qualified name as used by DOM and SAX . The returned string has a format of { @code prefix : localName } if the prefix is set or just { @code localName } if not . [CODESPLIT] protected String toQualifiedName ( QName qName ) { String prefix = qName . getPrefix ( ) ; if ( ! StringUtils . hasLength ( prefix ) ) { return qName . getLocalPart ( ) ; } else { return prefix + \":\" + qName . getLocalPart ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the prefix mapping for the given prefix . [CODESPLIT] protected void startPrefixMapping ( String prefix , String namespace ) throws SAXException { if ( getContentHandler ( ) != null ) { if ( prefix == null ) { prefix = \"\" ; } if ( ! StringUtils . hasLength ( namespace ) ) { return ; } if ( ! namespace . equals ( namespaces . get ( prefix ) ) ) { getContentHandler ( ) . startPrefixMapping ( prefix , namespace ) ; namespaces . put ( prefix , namespace ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ends the prefix mapping for the given prefix . [CODESPLIT] protected void endPrefixMapping ( String prefix ) throws SAXException { if ( getContentHandler ( ) != null ) { if ( namespaces . containsKey ( prefix ) ) { getContentHandler ( ) . endPrefixMapping ( prefix ) ; namespaces . remove ( prefix ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given callback to this registry . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void addCallback ( ListenableFutureCallback < ? super T > callback ) { Assert . notNull ( callback , \"'callback' must not be null\" ) ; synchronized ( mutex ) { switch ( state ) { case NEW : callbacks . add ( callback ) ; break ; case SUCCESS : callback . onSuccess ( ( T ) result ) ; break ; case FAILURE : callback . onFailure ( ( Throwable ) result ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a { @link ListenableFutureCallback#onSuccess ( Object ) } call on all added callbacks with the given result [CODESPLIT] public void success ( T result ) { synchronized ( mutex ) { state = State . SUCCESS ; this . result = result ; while ( ! callbacks . isEmpty ( ) ) { callbacks . poll ( ) . onSuccess ( result ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers a { @link ListenableFutureCallback#onFailure ( Throwable ) } call on all added callbacks with the given { @code Throwable } . [CODESPLIT] public void failure ( Throwable t ) { synchronized ( mutex ) { state = State . FAILURE ; this . result = t ; while ( ! callbacks . isEmpty ( ) ) { callbacks . poll ( ) . onFailure ( t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MD5 加密， 结果默认为小写 <br > 2013 - 11 - 4 下午6 : 33 : 06 [CODESPLIT] public static String encrypt ( String message , String encode ) { return encrypt ( message , encode , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "MD5 加密 <br > 2013 - 11 - 4 下午6 : 33 : 06 [CODESPLIT] public static String encrypt ( String message , String encode , boolean toUpperCase ) { MessageDigest messageDigest = null ; try { messageDigest = MessageDigest . getInstance ( \"MD5\" ) ; messageDigest . reset ( ) ; messageDigest . update ( message . getBytes ( encode ) ) ; } catch ( NoSuchAlgorithmException e ) { e . printStackTrace ( ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } byte [ ] byteArray = messageDigest . digest ( ) ; StringBuffer md5StrBuff = new StringBuffer ( ) ; for ( int i = 0 ; i < byteArray . length ; i ++ ) { if ( Integer . toHexString ( 0xFF & byteArray [ i ] ) . length ( ) == 1 ) { md5StrBuff . append ( \"0\" ) . append ( Integer . toHexString ( 0xFF & byteArray [ i ] ) ) ; } else { String hex = Integer . toHexString ( 0xFF & byteArray [ i ] ) ; if ( toUpperCase ) { hex = hex . toUpperCase ( ) ; } md5StrBuff . append ( hex ) ; } } return md5StrBuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts all path information of the String representation of the given URL . <p > [CODESPLIT] public static Map . Entry < String , String > cutDirectoryInformation ( final java . net . URL path ) { Map . Entry < String , String > ret = null ; String pre ; String suf ; String parse ; final StringBuffer tmp = new StringBuffer ( ) ; parse = path . toExternalForm ( ) ; if ( parse . endsWith ( \"/\" ) ) { pre = parse ; suf = \"\" ; } else { final StringTokenizer tokenizer = new StringTokenizer ( path . getFile ( ) , \"/\" ) ; tmp . append ( path . getProtocol ( ) ) ; tmp . append ( \":\" ) ; tmp . append ( path . getHost ( ) ) ; pre = \"\" ; while ( tokenizer . hasMoreElements ( ) ) { tmp . append ( pre ) ; pre = tokenizer . nextToken ( ) ; tmp . append ( \"/\" ) ; } suf = pre ; pre = tmp . toString ( ) ; } ret = new Entry < String , String > ( pre , suf ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts the path information of the String that is interpreted as a filename into the directory part and the file part . The current operating system s path separator is used to cut all path information from the String . <p > [CODESPLIT] public static Map . Entry < String , String > cutDirectoryInformation ( final String path ) { final StringBuffer dir = new StringBuffer ( ) ; String file = \"\" ; final String fileseparator = System . getProperty ( \"file.separator\" ) ; final StringTokenizer tokenizer = new StringTokenizer ( path , fileseparator ) ; final int size = tokenizer . countTokens ( ) ; switch ( size ) { case 0 : dir . append ( new File ( \".\" ) . getAbsolutePath ( ) ) ; break ; case 1 : final File test = new File ( tokenizer . nextToken ( ) ) ; if ( new File ( path ) . isDirectory ( ) ) { dir . append ( test . getAbsolutePath ( ) ) ; } else { dir . append ( new File ( \".\" ) . getAbsolutePath ( ) ) ; file = path ; } break ; default : String token ; while ( tokenizer . hasMoreElements ( ) ) { // reuse String file separator: bad style... token = tokenizer . nextToken ( ) ; if ( tokenizer . hasMoreTokens ( ) ) { dir . append ( token ) ; dir . append ( fileseparator ) ; } else { if ( new File ( path ) . isFile ( ) ) { file = token ; } else { dir . append ( token ) ; } } } } return new Entry < String , String > ( dir . toString ( ) , file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cuts a String into the part before the last dot and after the last dot . If only one dot is contained on the first position it will completely be used as prefix part . <p > [CODESPLIT] public static Map . Entry < String , String > cutExtension ( final String filename ) { String prefix ; String suffix = null ; final StringTokenizer tokenizer = new StringTokenizer ( filename , \".\" ) ; int tokenCount = tokenizer . countTokens ( ) ; if ( tokenCount > 1 ) { final StringBuffer prefCollect = new StringBuffer ( ) ; while ( tokenCount > 1 ) { tokenCount -- ; prefCollect . append ( tokenizer . nextToken ( ) ) ; if ( tokenCount > 1 ) { prefCollect . append ( \".\" ) ; } } prefix = prefCollect . toString ( ) ; suffix = tokenizer . nextToken ( ) ; } else { prefix = filename ; suffix = \"\" ; } return new Entry < String , String > ( prefix , suffix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a filename based on the given name . If a file with the given name does not exist <tt > name< / tt > will be returned . <p > [CODESPLIT] public static String getDefaultFileName ( final String name ) { String result ; File f = new File ( name ) ; if ( ! f . exists ( ) ) { result = f . getAbsolutePath ( ) ; } else { final Map . Entry < String , String > cut = FileUtil . cutExtension ( name ) ; final String prefix = cut . getKey ( ) ; final String suffix = cut . getValue ( ) ; int num = 0 ; while ( f . exists ( ) ) { f = new File ( prefix + ' ' + num + ' ' + suffix ) ; num ++ ; } result = f . getAbsolutePath ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the singleton instance of this class . <p > [CODESPLIT] public static FileUtil getInstance ( ) { if ( FileUtil . instance == null ) { FileUtil . instance = new FileUtil ( ) ; } return FileUtil . instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests wether the given input stream only contains ASCII characters if interpreted by reading bytes ( 16 bit ) . <p > This does not mean that the underlying content is really an ASCII text file . It just might be viewed with an editor showing only valid ASCII characters . <p > [CODESPLIT] public static boolean isAllASCII ( final InputStream in ) throws IOException { boolean ret = true ; int read = - 1 ; do { read = in . read ( ) ; if ( read > 0x7F ) { ret = false ; break ; } } while ( read != - 1 ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests wether the content of the given file is identical at character level when it is opened with both different Charsets . <p > This is most often the case if the given file only contains ASCII codes but may also occur when both codepages cover common ranges and the document only contains values m_out of those ranges ( like the EUC - CN charset contains all mappings from BIG5 ) . <p > [CODESPLIT] public static boolean isEqual ( final File document , final Charset a , final Charset b ) throws IOException { boolean ret = true ; FileInputStream aIn = null ; FileInputStream bIn = null ; InputStreamReader aReader = null ; InputStreamReader bReader = null ; try { aIn = new FileInputStream ( document ) ; bIn = new FileInputStream ( document ) ; aReader = new InputStreamReader ( aIn , a ) ; bReader = new InputStreamReader ( bIn , b ) ; int readA = - 1 ; int readB = - 1 ; do { readA = aReader . read ( ) ; readB = bReader . read ( ) ; if ( readA != readB ) { // also the case, if one is at the end earlier... ret = false ; break ; } } while ( ( readA != - 1 ) && ( readB != - 1 ) ) ; return ret ; } finally { if ( aReader != null ) { aReader . close ( ) ; } if ( bReader != null ) { bReader . close ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the content of the given File into an array . <p > This method currently does not check for maximum length and might cause a java . lang . OutOfMemoryError . It is only intended for performance - measurements of data - based algorithms that want to exclude I / O - usage . <p > [CODESPLIT] public static byte [ ] readRAM ( final File f ) throws IOException { final int total = ( int ) f . length ( ) ; final byte [ ] ret = new byte [ total ] ; final InputStream in = new FileInputStream ( f ) ; try { int offset = 0 ; int read = 0 ; do { read = in . read ( ret , offset , total - read ) ; if ( read > 0 ) { offset += read ; } } while ( ( read != - 1 ) && ( offset != total ) ) ; return ret ; } finally { in . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the duplicate line breaks in the given file . <p > [CODESPLIT] public static void removeDuplicateLineBreaks ( final File f ) { final String sep = StringUtil . getNewLine ( ) ; if ( ! f . exists ( ) ) { System . err . println ( \"FileUtil.removeDuplicateLineBreak(File f): \" + f . getAbsolutePath ( ) + \" does not exist!\" ) ; } else { if ( f . isDirectory ( ) ) { System . err . println ( \"FileUtil.removeDuplicateLineBreak(File f): \" + f . getAbsolutePath ( ) + \" is a directory!\" ) ; } else { // real file FileInputStream inStream = null ; BufferedInputStream in = null ; FileWriter out = null ; try { inStream = new FileInputStream ( f ) ; in = new BufferedInputStream ( inStream , 1024 ) ; StringBuffer result = new StringBuffer ( ) ; int tmpread ; while ( ( tmpread = in . read ( ) ) != - 1 ) { result . append ( ( char ) tmpread ) ; } String tmpstring ; final StringTokenizer toke = new StringTokenizer ( result . toString ( ) , sep , true ) ; result = new StringBuffer ( ) ; int breaks = 0 ; while ( toke . hasMoreTokens ( ) ) { tmpstring = toke . nextToken ( ) . trim ( ) ; if ( tmpstring . equals ( \"\" ) && ( breaks > 0 ) ) { breaks ++ ; // if(breaks<=2)result.append(sep); continue ; } if ( tmpstring . equals ( \"\" ) ) { tmpstring = sep ; breaks ++ ; } else { breaks = 0 ; } result . append ( tmpstring ) ; } // delete original file and write it new from tmpfile. f . delete ( ) ; f . createNewFile ( ) ; out = new FileWriter ( f ) ; out . write ( result . toString ( ) ) ; } catch ( final FileNotFoundException e ) { // does never happen. } catch ( final IOException g ) { g . printStackTrace ( System . err ) ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } if ( out != null ) { try { out . flush ( ) ; out . close ( ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the formatted file size to Bytes KB MB or GB depending on the given value . <p > [CODESPLIT] public String formatFilesize ( final long filesize , final Locale locale ) { String result ; final long filesizeNormal = Math . abs ( filesize ) ; if ( Math . abs ( filesize ) < 1024 ) { result = MessageFormat . format ( this . m_bundle . getString ( \"GUI_FILEUTIL_FILESIZE_BYTES_1\" ) , new Object [ ] { new Long ( filesizeNormal ) } ) ; } else if ( filesizeNormal < 1048576 ) { // 1048576 = 1024.0 * 1024.0 result = MessageFormat . format ( this . m_bundle . getString ( \"GUI_FILEUTIL_FILESIZE_KBYTES_1\" ) , new Object [ ] { new Double ( filesizeNormal / 1024.0 ) } ) ; } else if ( filesizeNormal < 1073741824 ) { // 1024.0^3 = 1073741824 result = MessageFormat . format ( this . m_bundle . getString ( \"GUI_FILEUTIL_FILESIZE_MBYTES_1\" ) , new Object [ ] { new Double ( filesize / 1048576.0 ) } ) ; } else { result = MessageFormat . format ( this . m_bundle . getString ( \"GUI_FILEUTIL_FILESIZE_GBYTES_1\" ) , new Object [ ] { new Double ( filesizeNormal / 1073741824.0 ) } ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end encode3to4 [CODESPLIT] private static byte [ ] encode3to4 ( byte [ ] source , int srcOffset , int numSigBytes , byte [ ] destination , int destOffset ) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an // int. int inBuff = ( numSigBytes > 0 ? ( ( source [ srcOffset ] << 24 ) >>> 8 ) : 0 ) | ( numSigBytes > 1 ? ( ( source [ srcOffset + 1 ] << 24 ) >>> 16 ) : 0 ) | ( numSigBytes > 2 ? ( ( source [ srcOffset + 2 ] << 24 ) >>> 24 ) : 0 ) ; switch ( numSigBytes ) { case 3 : destination [ destOffset ] = ALPHABET [ ( inBuff >>> 18 ) ] ; destination [ destOffset + 1 ] = ALPHABET [ ( inBuff >>> 12 ) & 0x3f ] ; destination [ destOffset + 2 ] = ALPHABET [ ( inBuff >>> 6 ) & 0x3f ] ; destination [ destOffset + 3 ] = ALPHABET [ ( inBuff ) & 0x3f ] ; return destination ; case 2 : destination [ destOffset ] = ALPHABET [ ( inBuff >>> 18 ) ] ; destination [ destOffset + 1 ] = ALPHABET [ ( inBuff >>> 12 ) & 0x3f ] ; destination [ destOffset + 2 ] = ALPHABET [ ( inBuff >>> 6 ) & 0x3f ] ; destination [ destOffset + 3 ] = EQUALS_SIGN ; return destination ; case 1 : destination [ destOffset ] = ALPHABET [ ( inBuff >>> 18 ) ] ; destination [ destOffset + 1 ] = ALPHABET [ ( inBuff >>> 12 ) & 0x3f ] ; destination [ destOffset + 2 ] = EQUALS_SIGN ; destination [ destOffset + 3 ] = EQUALS_SIGN ; return destination ; default : return destination ; } // end switch }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "随机生成指定长度字节数的密钥 <br > 2014 - 2 - 11 下午9 : 10 : 17 [CODESPLIT] public byte [ ] generateKey ( int length ) { if ( length <= 0 ) { throw new IllegalArgumentException ( \"长度为：\" + lengt    \"， 指定 密 长度错误！\");   } byte [ ] bts = new byte [ length ] ; Random random = new Random ( ) ; for ( int i = 0 ; i < length ; i ++ ) { bts [ i ] = ( byte ) random . nextInt ( 255 ) ; } return bts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定的时间刷新周期获取时间字节 <br > 2014 - 2 - 11 下午9 : 13 : 21 [CODESPLIT] public byte [ ] getTimeBytes ( int seconds ) { if ( seconds <= 0 ) { throw new IllegalArgumentException ( \"秒数为：\" + secon s  + \"， 指定的密钥更新周期错误！\");   } long currentTimeMillis = System . currentTimeMillis ( ) ; // System.out.println(currentTimeMillis); // 对秒数取整，比如seconds=30，那么21点00分18秒与21点00分29秒是相同的结果 currentTimeMillis /= seconds * SECOND ; // long currentTimeMillisRs = currentTimeMillis * seconds * // SECOND;//还原时间位数 // System.out.println(currentTimeMillisRs); // Date date = new Date(currentTimeMillisRs); // String dateStr = DateHelper.FORMATTER_LONG.format(date); // System.out.println(dateStr); return ByteHelper . longToBytes ( currentTimeMillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对字节进行迭代运算，这样结果就不具备规律性 <br > 2014 - 2 - 11 下午9 : 14 : 18 [CODESPLIT] public byte [ ] generateCode ( byte [ ] key , int refreshTime ) { byte [ ] bs = getTimeBytes ( refreshTime ) ; int length = bs . length ; for ( int i = 0 ; i < length ; i ++ ) { byte b = bs [ i ] ; for ( int j = 0 ; j < length ; j ++ ) { bs [ i ] = ( byte ) ( bs [ j ] | b ) ; bs [ i ] = ( byte ) ( bs [ j ] ^ b ) ; } } int keyLength = key . length ; byte [ ] rs = new byte [ keyLength ] ; System . arraycopy ( key , 0 , rs , 0 , keyLength ) ; for ( int i = 0 ; i < keyLength ; i ++ ) { byte k = rs [ i ] ; for ( int j = 0 ; j < length ; j ++ ) { rs [ i ] = ( byte ) ( bs [ j ] ^ k ) ; rs [ i ] = ( byte ) ( bs [ j ] | k ) ; } } // String string = Base64.encodeBytes(rs); // System.out.println(string); return rs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取最接近digit位数字的二进制表示的数（一定大于digit位的数字）的大小 例如，如果digit为6，那么表示999999最接近的二进制数字为1048576 ( 2的20次方 ) ，结果返回20 <br > 2014 - 1 - 21 下午5 : 27 : 53 [CODESPLIT] public static int minApproach ( int digit ) { int max = ( int ) ( Math . pow ( 10 , digit ) - 1 ) ; //\tSystem.out.println(max); int i = 0 ; while ( max > 0 ) { max >>= 1 ; i ++ ; } //\tint k = 1 << i; //\tSystem.out.println(k); //\tSystem.out.println(i); return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a Tree from the entries . [CODESPLIT] private ITreeNode parseTree ( ) { ITreeNode root = new TreeNodeUniqueChildren ( ) ; ITreeNode newnode , oldnode ; Enumeration entries = this . jar . entries ( ) ; String entry ; while ( entries . hasMoreElements ( ) ) { newnode = root ; oldnode = root ; entry = ( ( JarEntry ) entries . nextElement ( ) ) . getName ( ) ; System . out . println ( \"Entry: \" + entry ) ; StringTokenizer tokenizer = new StringTokenizer ( entry , \"/\" ) ; while ( tokenizer . hasMoreElements ( ) ) { String path = tokenizer . nextToken ( ) ; newnode = new TreeNodeUniqueChildren ( path ) ; oldnode . addChildNode ( newnode ) ; oldnode = newnode ; } } return root ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Little helper that transforms ( back ) the nodes of the tree that was parsed from the entries during initialization to canonical strings for entries . [CODESPLIT] private String getSearchPath ( ITreeNode node ) { List l = new LinkedList ( ) ; node . getUserObjectPathFromRoot ( l ) ; Iterator it = l . iterator ( ) ; StringBuffer ret = new StringBuffer ( ) ; int i = 0 ; String token ; while ( it . hasNext ( ) ) { // avoid the \"root\" token. token = it . next ( ) . toString ( ) ; if ( i != 0 ) { ret . append ( token ) ; if ( it . hasNext ( ) ) { ret . append ( ' ' ) ; } } i ++ ; } return ret . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public String [ ] list ( ) { String [ ] ret = new String [ this . childs . size ( ) ] ; Iterator it = this . childs . iterator ( ) ; for ( int i = 0 ; it . hasNext ( ) ; i ++ ) { ret [ i ] = it . next ( ) . toString ( ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public File [ ] listFiles ( ) { File [ ] ret = new File [ this . childs . size ( ) ] ; Iterator it = this . childs . iterator ( ) ; for ( int i = 0 ; it . hasNext ( ) ; i ++ ) { ret [ i ] = ( File ) it . next ( ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public File [ ] listFiles ( FileFilter filter ) { List ret = new LinkedList ( ) ; Iterator it = this . childs . iterator ( ) ; File next ; while ( it . hasNext ( ) ) { next = ( File ) it . next ( ) ; if ( filter . accept ( next ) ) { ret . add ( next ) ; } } return ( File [ ] ) ret . toArray ( new File [ ret . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据当前MixIn集合生成objectMapper<p > <p > <b > 注意：该方法在返回mapper对象之后调用clear方法，如果再次调用builderMapper () 肯定会保存< / b > [CODESPLIT] public static ObjectMapper builderMapper ( ) { ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder . mapper == null && isContainsMixIn ( ) ) { holder . mapper = new ObjectMapper ( ) ; for ( Map . Entry < Class < ? > , Class < ? > > mixIn : holder . mixIns ) { holder . mapper . addMixInAnnotations ( mixIn . getKey ( ) , mixIn . getValue ( ) ) ; } } clear ( ) ; // 如果不调用clear可能导致线程内的数据是脏的！ return holder . mapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据当前MixIn集合生成objectMapper [CODESPLIT] public static org . codehaus . jackson . map . ObjectMapper builderCodehausMapper ( ) { ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder . codehausMapper == null && isContainsMixIn ( ) ) { holder . codehausMapper = new org . codehaus . jackson . map . ObjectMapper ( ) ; for ( Map . Entry < Class < ? > , Class < ? > > mixIn : holder . mixIns ) { holder . codehausMapper . getDeserializationConfig ( ) . addMixInAnnotations ( mixIn . getKey ( ) , mixIn . getValue ( ) ) ; holder . codehausMapper . getSerializationConfig ( ) . addMixInAnnotations ( mixIn . getKey ( ) , mixIn . getValue ( ) ) ; } } clear ( ) ; // 如果不调用clear可能导致线程内的数据是脏的！ return holder . codehausMapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置MixIn集合到线程内，如果线程内已经存在数据，则会先清除 [CODESPLIT] public static void setMixIns ( Set < Map . Entry < Class < ? > , Class < ? > > > resetMixIns ) { ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder == null ) { holder = new ThreadJacksonMixInHolder ( ) ; holderThreadLocal . set ( holder ) ; } holder . mixIns = resetMixIns ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "不同于setMixIns，addMixIns为增加MixIn集合到线程内，即不会清除已经保存的数据 <br > 2014年4月4日 下午12 : 08 : 15 [CODESPLIT] public static void addMixIns ( Set < Map . Entry < Class < ? > , Class < ? > > > toAddMixIns ) { ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; if ( holder == null ) { holder = new ThreadJacksonMixInHolder ( ) ; holderThreadLocal . set ( holder ) ; } if ( holder . mixIns == null ) { holder . mixIns = new HashSet < Map . Entry < Class < ? > , Class < ? > > > ( ) ; } holder . mixIns . addAll ( toAddMixIns ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取线程内的MixIn集合<p > < / p > <b > 注意：为了防止线程执行完毕之后仍然存在有数据，请务必适时调用clear () 方法< / b > [CODESPLIT] public static Set < Map . Entry < Class < ? > , Class < ? > > > getMixIns ( ) { ThreadJacksonMixInHolder holder = holderThreadLocal . get ( ) ; return holder . mixIns ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断当前线程是否存在MixIn集合 [CODESPLIT] public static boolean isContainsMixIn ( ) { if ( holderThreadLocal . get ( ) == null ) { return false ; } if ( holderThreadLocal . get ( ) . mixIns != null && holderThreadLocal . get ( ) . mixIns . size ( ) > 0 ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and return a list of { [CODESPLIT] private List < Namespace > createNamespaces ( SimpleNamespaceContext namespaceContext ) { if ( namespaceContext == null ) { return null ; } List < Namespace > namespaces = new ArrayList < Namespace > ( ) ; String defaultNamespaceUri = namespaceContext . getNamespaceURI ( XMLConstants . DEFAULT_NS_PREFIX ) ; if ( StringUtils . hasLength ( defaultNamespaceUri ) ) { namespaces . add ( this . eventFactory . createNamespace ( defaultNamespaceUri ) ) ; } for ( Iterator < String > iterator = namespaceContext . getBoundPrefixes ( ) ; iterator . hasNext ( ) ; ) { String prefix = iterator . next ( ) ; String namespaceUri = namespaceContext . getNamespaceURI ( prefix ) ; namespaces . add ( this . eventFactory . createNamespace ( prefix , namespaceUri ) ) ; } return namespaces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定的过滤表创建jackson对象 <br > 2013 - 10 - 25 下午2 : 46 : 43 [CODESPLIT] private ObjectMapper createObjectMapper ( Map < Class < ? > , Class < ? > > map ) { ObjectMapper mapper = new ObjectMapper ( ) ; Set < Entry < Class < ? > , Class < ? > > > entries = map . entrySet ( ) ; for ( Iterator < Entry < Class < ? > , Class < ? > > > iterator = entries . iterator ( ) ; iterator . hasNext ( ) ; ) { Entry < Class < ? > , Class < ? > > entry = iterator . next ( ) ; mapper . getSerializationConfig ( ) . addMixInAnnotations ( entry . getKey ( ) , entry . getValue ( ) ) ; //            mapper.addMixInAnnotations(entry.getKey(), entry.getValue()); } return mapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将摘要信息转换为相应的编码 [CODESPLIT] private static String encode ( String code , String message ) { return encode ( code , message . getBytes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加密方法 <pre > // 1 . 1 首先要创建一个密匙 // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom () ; // 为我们选择的DES算法生成一个KeyGenerator对象 KeyGenerator kg = KeyGenerator . getInstance ( DES ) ; kg . init ( sr ) ; // 生成密匙 SecretKey key = kg . generateKey () ; // 获取密匙数据 byte rawKeyData [] = key . getEncoded () ; // byte rawKeyData [] = sucretsa . getBytes () ; System . out . println ( 密匙长度 === + rawKeyData . length ) ; System . out . println ( 密匙Base64 === + Base64 . encodeBytes ( rawKeyData )) ; [CODESPLIT] public static byte [ ] desEncrypt ( byte rawKeyData [ ] , byte [ ] data ) throws InvalidKeyException , NoSuchAlgorithmException , IllegalBlockSizeException , BadPaddingException , NoSuchPaddingException , InvalidKeySpecException { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom ( ) ; // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec ( rawKeyData ) ; // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory . getInstance ( \"DES\" ) ; SecretKey key = keyFactory . generateSecret ( dks ) ; // Cipher对象实际完成加密操作 Cipher cipher = Cipher . getInstance ( \"DES\" ) ; // 用密匙初始化Cipher对象 cipher . init ( Cipher . ENCRYPT_MODE , key , sr ) ; // 现在，获取数据并加密 //        byte data[] = str.getBytes(); // 正式执行加密操作 byte [ ] encryptedData = cipher . doFinal ( data ) ; //        System.out.println(\"加密后===>\" + encryptedData); return encryptedData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "解密方法 [CODESPLIT] public static byte [ ] desDecrypt ( byte rawKeyData [ ] , byte [ ] encryptedData ) throws IllegalBlockSizeException , BadPaddingException , InvalidKeyException , NoSuchAlgorithmException , NoSuchPaddingException , InvalidKeySpecException { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom ( ) ; // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec ( rawKeyData ) ; // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory . getInstance ( \"DES\" ) ; SecretKey key = keyFactory . generateSecret ( dks ) ; // Cipher对象实际完成解密操作 Cipher cipher = Cipher . getInstance ( \"DES\" ) ; // 用密匙初始化Cipher对象 cipher . init ( Cipher . DECRYPT_MODE , key , sr ) ; // 正式执行解密操作 byte decryptedData [ ] = cipher . doFinal ( encryptedData ) ; //        System.out.println(\"解密后===>\" + new String(decryptedData)); return decryptedData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Adds the given argument to the acceptance filter . The filter will only return true for a Class a in the following condition : [CODESPLIT] public synchronized boolean addSuperClass ( Class c ) { boolean ret = false ; if ( ( c . getModifiers ( ) & Modifier . FINAL ) != 0 ) { } else { ret = this . superclasses . add ( c ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to detect ( from the file path and the Classloaders urls ) and load the corresponding class and delegates to { @link #accept ( Class ) } . [CODESPLIT] public boolean accept ( File pathname ) { boolean ret = false ; if ( pathname . isDirectory ( ) ) { ret = true ; } else { String ext = FileUtil . cutExtension ( pathname . getName ( ) ) . getValue ( ) . toString ( ) ; if ( ext . equals ( \"jar\" ) ) { // is a \"directory\": ret = true ; } else if ( ext . equals ( \"class\" ) ) { Class cl = this . forFile ( pathname ) ; if ( cl != null ) { ret = this . accept ( cl ) ; } } else { ret = false ; } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for creating a { @link GelfTransport } provider within the plugin manager . [CODESPLIT] @ PluginFactory @ SuppressWarnings ( \"unused\" ) public static GelfAppender createGelfAppender ( @ PluginElement ( \"Filter\" ) Filter filter , @ PluginElement ( \"Layout\" ) Layout < ? extends Serializable > layout , @ PluginElement ( value = \"AdditionalFields\" ) final KeyValuePair [ ] additionalFields , @ PluginAttribute ( value = \"name\" ) String name , @ PluginAttribute ( value = \"ignoreExceptions\" , defaultBoolean = true ) Boolean ignoreExceptions , @ PluginAttribute ( value = \"server\" , defaultString = \"localhost\" ) String server , @ PluginAttribute ( value = \"port\" , defaultInt = 12201 ) Integer port , @ PluginAttribute ( value = \"protocol\" , defaultString = \"UDP\" ) String protocol , @ PluginAttribute ( value = \"hostName\" ) String hostName , @ PluginAttribute ( value = \"queueSize\" , defaultInt = 512 ) Integer queueSize , @ PluginAttribute ( value = \"connectTimeout\" , defaultInt = 1000 ) Integer connectTimeout , @ PluginAttribute ( value = \"reconnectDelay\" , defaultInt = 500 ) Integer reconnectDelay , @ PluginAttribute ( value = \"sendBufferSize\" , defaultInt = - 1 ) Integer sendBufferSize , @ PluginAttribute ( value = \"tcpNoDelay\" , defaultBoolean = false ) Boolean tcpNoDelay , @ PluginAttribute ( value = \"tcpKeepAlive\" , defaultBoolean = false ) Boolean tcpKeepAlive , @ PluginAttribute ( value = \"includeSource\" , defaultBoolean = true ) Boolean includeSource , @ PluginAttribute ( value = \"includeThreadContext\" , defaultBoolean = true ) Boolean includeThreadContext , @ PluginAttribute ( value = \"includeStackTrace\" , defaultBoolean = true ) Boolean includeStackTrace , @ PluginAttribute ( value = \"includeExceptionCause\" , defaultBoolean = false ) Boolean includeExceptionCause , @ PluginAttribute ( value = \"tlsEnabled\" , defaultBoolean = false ) Boolean tlsEnabled , @ PluginAttribute ( value = \"tlsEnableCertificateVerification\" , defaultBoolean = true ) Boolean tlsEnableCertificateVerification , @ PluginAttribute ( value = \"tlsTrustCertChainFilename\" ) String tlsTrustCertChainFilename ) { if ( name == null ) { LOGGER . error ( \"No name provided for ConsoleAppender\" ) ; return null ; } if ( ! \"UDP\" . equalsIgnoreCase ( protocol ) && ! \"TCP\" . equalsIgnoreCase ( protocol ) ) { LOG . warn ( \"Invalid protocol {}, falling back to UDP\" , protocol ) ; protocol = \"UDP\" ; } if ( hostName == null || hostName . trim ( ) . isEmpty ( ) ) { try { final String canonicalHostName = InetAddress . getLocalHost ( ) . getCanonicalHostName ( ) ; if ( isFQDN ( canonicalHostName ) ) { hostName = canonicalHostName ; } else { hostName = InetAddress . getLocalHost ( ) . getHostName ( ) ; } } catch ( UnknownHostException e ) { LOG . warn ( \"Couldn't detect local host name, falling back to \\\"localhost\\\"\" ) ; hostName = \"localhost\" ; } } final InetSocketAddress serverAddress = new InetSocketAddress ( server , port ) ; final GelfTransports gelfProtocol = GelfTransports . valueOf ( protocol . toUpperCase ( ) ) ; final GelfConfiguration gelfConfiguration = new GelfConfiguration ( serverAddress ) . transport ( gelfProtocol ) . queueSize ( queueSize ) . connectTimeout ( connectTimeout ) . reconnectDelay ( reconnectDelay ) . sendBufferSize ( sendBufferSize ) . tcpNoDelay ( tcpNoDelay ) . tcpKeepAlive ( tcpKeepAlive ) ; if ( tlsEnabled ) { if ( gelfProtocol . equals ( GelfTransports . TCP ) ) { gelfConfiguration . enableTls ( ) ; if ( ! tlsEnableCertificateVerification ) { LOG . warn ( \"TLS certificate validation is disabled. This is unsecure!\" ) ; gelfConfiguration . disableTlsCertVerification ( ) ; } if ( tlsEnableCertificateVerification && tlsTrustCertChainFilename != null ) { gelfConfiguration . tlsTrustCertChainFile ( new File ( tlsTrustCertChainFilename ) ) ; } } else { LOG . warn ( \"Enabling of TLS is invalid for UDP Transport\" ) ; } } return new GelfAppender ( name , layout , filter , ignoreExceptions , gelfConfiguration , hostName , includeSource , includeThreadContext , includeStackTrace , additionalFields , includeExceptionCause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO cache values [CODESPLIT] private boolean isRtl ( CharSequence text ) { if ( textDir == null ) { textDir = getTextDirectionHeuristic ( ) ; } return textDir . isRtl ( text , 0 , text . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates text color for specified item based on its position and state . [CODESPLIT] private int getTextColor ( int item ) { int scrollX = getScrollX ( ) ; // set color of text int color = textColor . getDefaultColor ( ) ; int itemWithPadding = ( int ) ( itemWidth + dividerSize ) ; if ( scrollX > itemWithPadding * item - itemWithPadding / 2 && scrollX < itemWithPadding * ( item + 1 ) - itemWithPadding / 2 ) { int position = scrollX - itemWithPadding / 2 ; color = getColor ( position , item ) ; } else if ( item == pressedItem ) { color = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed } , color ) ; } return color ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets values to choose from [CODESPLIT] public void setValues ( CharSequence [ ] values ) { if ( this . values != values ) { this . values = values ; if ( this . values != null ) { layouts = new BoringLayout [ this . values . length ] ; for ( int i = 0 ; i < layouts . length ; i ++ ) { layouts [ i ] = new BoringLayout ( this . values [ i ] , textPaint , itemWidth , Layout . Alignment . ALIGN_CENTER , 1f , 1f , boringMetrics , false , ellipsize , itemWidth ) ; } } else { layouts = new BoringLayout [ 0 ] ; } // start marque only if has already been measured if ( getWidth ( ) > 0 ) { startMarqueeIfNeeded ( ) ; } requestLayout ( ) ; invalidate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates color for specific position on time picker [CODESPLIT] private int getColor ( int scrollX , int position ) { int itemWithPadding = ( int ) ( itemWidth + dividerSize ) ; float proportion = Math . abs ( ( ( 1f * scrollX % itemWithPadding ) / 2 ) / ( itemWithPadding / 2f ) ) ; if ( proportion > .5 ) { proportion = ( proportion - .5f ) ; } else { proportion = .5f - proportion ; } proportion *= 2 ; int defaultColor ; int selectedColor ; if ( pressedItem == position ) { defaultColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed } , textColor . getDefaultColor ( ) ) ; selectedColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed , android . R . attr . state_selected } , defaultColor ) ; } else { defaultColor = textColor . getDefaultColor ( ) ; selectedColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_selected } , defaultColor ) ; } return ( Integer ) new ArgbEvaluator ( ) . evaluate ( proportion , selectedColor , defaultColor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets text size for items [CODESPLIT] private void setTextSize ( float size ) { if ( size != textPaint . getTextSize ( ) ) { textPaint . setTextSize ( size ) ; requestLayout ( ) ; invalidate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates x scroll position that is still in range of view scroller [CODESPLIT] private int getInBoundsX ( int x ) { if ( x < 0 ) { x = 0 ; } else if ( x > ( ( itemWidth + ( int ) dividerSize ) * ( values . length - 1 ) ) ) { x = ( ( itemWidth + ( int ) dividerSize ) * ( values . length - 1 ) ) ; } return x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleans up the path of an incoming request . Repeating / s are reduced to one / . Trailing / s are removed . A <code > null< / code > or empty path is converted to / . [CODESPLIT] private static String cleanPath ( String path ) { path = path == null ? \"/\" : path ; if ( ! path . startsWith ( \"/\" ) ) { path = \"/\" + path ; } path = path . replaceAll ( \"/+\" , \"/\" ) ; if ( path . length ( ) > 1 && path . endsWith ( \"/\" ) ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Starts jrobotremoteserver with an example library and returns . The application will shutdown when all of the web server s threads exit . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { RemoteServer . configureLogging ( ) ; RemoteServer server = new RemoteServer ( ) ; server . addLibrary ( MyRemoteLibrary . class , 8270 ) ; server . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The introduction is stored in a text file resource because it is easier to edit than String constants . [CODESPLIT] private String getIntro ( ) { try { InputStream introStream = MyRemoteLibrary . class . getResourceAsStream ( \"__intro__.txt\" ) ; StringWriter writer = new StringWriter ( ) ; IOUtils . copy ( introStream , writer , Charset . defaultCharset ( ) ) ; return writer . toString ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array containing the names of the keywords that the library implements . [CODESPLIT] public String [ ] get_keyword_names ( ) { try { String [ ] names = servlet . getLibrary ( ) . getKeywordNames ( ) ; if ( names == null || names . length == 0 ) throw new RuntimeException ( \"No keywords found in the test library\" ) ; String [ ] newNames = Arrays . copyOf ( names , names . length + 1 ) ; newNames [ names . length ] = \"stop_remote_server\" ; return newNames ; } catch ( Throwable e ) { log . warn ( \"\" , e ) ; throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the given keyword and return the results . [CODESPLIT] public Map < String , Object > run_keyword ( String keyword , Object [ ] args , Map < String , Object > kwargs ) { Map < String , Object > result = new HashMap < String , Object > ( ) ; StdStreamRedirecter redirector = new StdStreamRedirecter ( ) ; redirector . redirectStdStreams ( ) ; try { result . put ( \"status\" , \"PASS\" ) ; Object retObj = \"\" ; if ( keyword . equalsIgnoreCase ( \"stop_remote_server\" ) ) { retObj = stopRemoteServer ( ) ; } else { try { retObj = servlet . getLibrary ( ) . runKeyword ( keyword , args , kwargs ) ; } catch ( Exception e ) { if ( illegalArgumentIn ( e ) ) { for ( int i = 0 ; i < args . length ; i ++ ) args [ i ] = arraysToLists ( args [ i ] ) ; retObj = servlet . getLibrary ( ) . runKeyword ( keyword , args , kwargs ) ; } else { throw ( e ) ; } } } if ( retObj != null && ! retObj . equals ( \"\" ) ) { result . put ( \"return\" , retObj ) ; } } catch ( Throwable e ) { result . put ( \"status\" , \"FAIL\" ) ; Throwable thrown = e . getCause ( ) == null ? e : e . getCause ( ) ; result . put ( \"error\" , getError ( thrown ) ) ; result . put ( \"traceback\" , ExceptionUtils . getStackTrace ( thrown ) ) ; boolean continuable = isFlagSet ( \"ROBOT_CONTINUE_ON_FAILURE\" , thrown ) ; if ( continuable ) { result . put ( \"continuable\" , true ) ; } boolean fatal = isFlagSet ( \"ROBOT_EXIT_ON_FAILURE\" , thrown ) ; if ( fatal ) { result . put ( \"fatal\" , true ) ; } } finally { String stdOut = StringUtils . defaultString ( redirector . getStdOutAsString ( ) ) ; String stdErr = StringUtils . defaultString ( redirector . getStdErrAsString ( ) ) ; if ( ! stdOut . isEmpty ( ) || ! stdErr . isEmpty ( ) ) { StringBuilder output = new StringBuilder ( stdOut ) ; if ( ! stdOut . isEmpty ( ) && ! stdErr . isEmpty ( ) ) { if ( ! stdOut . endsWith ( \"\\n\" ) ) { output . append ( \"\\n\" ) ; } boolean addLevel = true ; for ( String prefix : logLevelPrefixes ) { if ( stdErr . startsWith ( prefix ) ) { addLevel = false ; break ; } } if ( addLevel ) { output . append ( \"*INFO*\" ) ; } } result . put ( \"output\" , output . append ( stdErr ) . toString ( ) ) ; } redirector . resetStdStreams ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the given keyword and return the results . [CODESPLIT] public Map < String , Object > run_keyword ( String keyword , Object [ ] args ) { return run_keyword ( keyword , args , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array of argument specifications for the given keyword . [CODESPLIT] public String [ ] get_keyword_arguments ( String keyword ) { if ( keyword . equalsIgnoreCase ( \"stop_remote_server\" ) ) { return new String [ 0 ] ; } try { String [ ] args = servlet . getLibrary ( ) . getKeywordArguments ( keyword ) ; return args == null ? new String [ 0 ] : args ; } catch ( Throwable e ) { log . warn ( \"\" , e ) ; throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get documentation for given keyword . [CODESPLIT] public String get_keyword_documentation ( String keyword ) { if ( keyword . equalsIgnoreCase ( \"stop_remote_server\" ) ) { return \"Stops the remote server.\\n\\nThe server may be configured so that users cannot stop it.\" ; } try { String doc = servlet . getLibrary ( ) . getKeywordDocumentation ( keyword ) ; return doc == null ? \"\" : doc ; } catch ( Throwable e ) { log . warn ( \"\" , e ) ; throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main method for command line usage . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { configureLogging ( ) ; CommandLineHelper helper = new CommandLineHelper ( args ) ; if ( helper . getHelpRequested ( ) ) { System . out . print ( helper . getUsage ( ) ) ; System . exit ( 0 ) ; } RemoteServer remoteServer = new RemoteServer ( ) ; String error = helper . getError ( ) ; if ( error == null ) { try { for ( String path : helper . getLibraryMap ( ) . keySet ( ) ) remoteServer . putLibrary ( path , helper . getLibraryMap ( ) . get ( path ) ) ; } catch ( IllegalPathException e ) { error = e . getMessage ( ) ; } } if ( error != null ) { System . out . println ( \"Error: \" + error ) ; System . out . println ( ) ; System . out . println ( helper . getUsage ( ) ) ; System . exit ( 1 ) ; } remoteServer . setPort ( helper . getPort ( ) ) ; remoteServer . setAllowStop ( helper . getAllowStop ( ) ) ; remoteServer . setHost ( helper . getHost ( ) ) ; remoteServer . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the given test library to the specified path . Paths must : <ul > <li > start with a / < / li > <li > contain only alphanumeric characters or any of these : / - . _ ~< / li > <li > not end in a / < / li > <li > not contain a repeating sequence of / s< / li > < / ul > [CODESPLIT] public RemoteLibrary putLibrary ( String path , Object library ) { RemoteLibrary oldLibrary = servlet . putLibrary ( path , library ) ; String name = servlet . getLibraryMap ( ) . get ( path ) . getName ( ) ; log . info ( String . format ( \"Mapped path %s to library %s.\" , path , name ) ) ; return oldLibrary ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This has been deprecated . Please use { @link #putLibrary } and { @link #setPort } instead . [CODESPLIT] @ Deprecated public void addLibrary ( String className , int port ) { Class < ? > clazz ; try { clazz = Class . forName ( className ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } addLibrary ( clazz , port ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This has been deprecated . Please use { @link #putLibrary } and { @link #setPort } instead . [CODESPLIT] @ Deprecated public void addLibrary ( Class < ? > clazz , int port ) { if ( ! server . isStopped ( ) ) // old behavior throw new IllegalStateException ( \"Cannot add a library once the server is started\" ) ; if ( connector . getPort ( ) != 0 && connector . getPort ( ) != port ) { throw new RuntimeException ( \"Serving on multiple ports is no longer supported. Please use putLibrary with different paths instead.\" ) ; } if ( servlet . getLibraryMap ( ) . keySet ( ) . contains ( \"/\" ) ) { throw new RuntimeException ( \"A library has already been mapped to /.\" ) ; } Object library ; try { library = clazz . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } setPort ( port ) ; putLibrary ( \"/\" , library ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A non - blocking method for stopping the remote server that allows requests to complete within the given timeout before shutting down the server . New connections will not be accepted after calling this . [CODESPLIT] public void stop ( int timeoutMS ) throws Exception { log . info ( \"Robot Framework remote server stopping\" ) ; if ( timeoutMS > 0 ) { server . setGracefulShutdown ( timeoutMS ) ; Thread stopper = new Thread ( ) { @ Override public void run ( ) { try { server . stop ( ) ; } catch ( Throwable e ) { log . error ( String . format ( \"Failed to stop the server: %s\" , e . getMessage ( ) ) , e ) ; } } } ; stopper . start ( ) ; } else { server . stop ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the remote server . Add test libraries first before calling this . [CODESPLIT] public void start ( ) throws Exception { log . info ( \"Robot Framework remote server starting\" ) ; server . start ( ) ; log . info ( String . format ( \"Robot Framework remote server started on port %d.\" , getLocalPort ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures logging systems used by <tt > RemoteServer< / tt > and its dependencies . Specifically <ul > <li > Configure Log4J to log to the console< / li > <li > Set Log4J s log level to INFO< / li > <li > Redirect the Jetty s logging to Log4J< / li > <li > Set Jakarta Commons Logging to log to Log4J< / li > < / ul > This is convenient if you do not want to configure the logging yourself . This will only affect future instances of { [CODESPLIT] public static void configureLogging ( ) { Logger root = Logger . getRootLogger ( ) ; root . removeAllAppenders ( ) ; BasicConfigurator . configure ( ) ; root . setLevel ( Level . INFO ) ; org . eclipse . jetty . util . log . Log . setLog ( new Jetty2Log4J ( ) ) ; LogFactory . releaseAll ( ) ; LogFactory . getFactory ( ) . setAttribute ( \"org.apache.commons.logging.Log\" , \"org.apache.commons.logging.impl.Log4JLogger\" ) ; log = LogFactory . getLog ( RemoteServer . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the prefixes from all keys in this handler mapping assuming a String was used as the key and period was used as a separator . Example : AccountsReceivable . Billing . getInvoice - > getInvoice [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void removePrefixes ( ) { Map < String , Object > newHandlerMap = new HashMap < String , Object > ( ) ; for ( Entry < String , Object > entry : ( Set < Entry < String , Object > > ) this . handlerMap . entrySet ( ) ) { String newKey = ( String ) entry . getKey ( ) ; if ( entry . getKey ( ) instanceof String ) { String key = ( String ) entry . getKey ( ) ; if ( key . contains ( \".\" ) ) { newKey = key . substring ( key . lastIndexOf ( \".\" ) + 1 ) ; } } newHandlerMap . put ( newKey , entry . getValue ( ) ) ; } this . handlerMap = newHandlerMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate Json by given path to file with properties with only included domain keys . [CODESPLIT] public String convertPropertiesFromFileToJson ( String pathToFile , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { return convertPropertiesFromFileToJson ( new File ( pathToFile ) , includeDomainKeys ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate Json by given file with properties with only included domain keys . [CODESPLIT] public String convertPropertiesFromFileToJson ( File file , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { try { InputStream targetStream = new FileInputStream ( file ) ; return convertToJson ( targetStream , includeDomainKeys ) ; } catch ( FileNotFoundException e ) { throw new ReadInputException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate Json by given InputStream and given filter . [CODESPLIT] public String convertToJson ( InputStream inputStream , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { return convertToJson ( inputStreamToProperties ( inputStream ) , includeDomainKeys ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate Json by given Java Properties [CODESPLIT] public String convertToJson ( Properties properties ) throws ParsePropertiesException { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { if ( ! ( entry . getKey ( ) instanceof String ) ) { throw new ParsePropertiesException ( format ( PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE , entry . getKey ( ) . getClass ( ) , entry . getKey ( ) == null ? \"null\" : entry . getKey ( ) ) ) ; } } return convertFromValuesAsObjectMap ( propertiesToMap ( properties ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate Json by given Map&lt ; String String&gt ; [CODESPLIT] public String convertToJson ( Map < String , String > properties ) throws ParsePropertiesException { return convertFromValuesAsObjectMap ( stringValueMapToObjectValueMap ( properties ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate Json by given Map&lt ; String Object&gt ; [CODESPLIT] public String convertFromValuesAsObjectMap ( Map < String , Object > properties ) throws ParsePropertiesException { ObjectJsonType coreObjectJsonType = new ObjectJsonType ( ) ; for ( String propertiesKey : getAllKeysFromProperties ( properties ) ) { addFieldsToJsonObject ( properties , coreObjectJsonType , propertiesKey ) ; } return prettifyOfJson ( coreObjectJsonType . toStringJson ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate Json by given Map&lt ; String String&gt ; and given filter [CODESPLIT] public String convertFromValuesAsObjectMap ( Map < String , Object > properties , String ... includeDomainKeys ) throws ParsePropertiesException { Map < String , Object > filteredProperties = new HashMap <> ( ) ; for ( String key : properties . keySet ( ) ) { for ( String requiredKey : includeDomainKeys ) { checkKey ( properties , filteredProperties , key , requiredKey ) ; } } return convertFromValuesAsObjectMap ( filteredProperties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generate Json by given Java Properties and given filter [CODESPLIT] public String convertToJson ( Properties properties , String ... includeDomainKeys ) throws ParsePropertiesException { return convertFromValuesAsObjectMap ( propertiesToMap ( properties ) , includeDomainKeys ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets background color for this button . <p / > Xml attribute : { @code app : floatingActionButtonColor } <p / > NOTE : this method sets the <code > mColorStateList< / code > field to <code > null< / code > [CODESPLIT] public void setColor ( int color ) { boolean changed = mColor != color || mColorStateList != null ; mColor = color ; mColorStateList = null ; if ( changed ) { updateBackground ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets color state list as background for this button . <p / > Xml attribute : { @code app : floatingActionButtonColor } [CODESPLIT] public void setColorStateList ( ColorStateList colorStateList ) { boolean changed = mColorStateList != colorStateList ; mColorStateList = colorStateList ; if ( changed ) { updateBackground ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inflate and initialize background drawable for this view with arguments inflated from xml or specified using { [CODESPLIT] public void initBackground ( ) { final int backgroundId ; if ( mSize == SIZE_MINI ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { backgroundId = R . drawable . com_shamanland_fab_circle_mini ; } else { backgroundId = R . drawable . com_shamanland_fab_mini ; } } else { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { backgroundId = R . drawable . com_shamanland_fab_circle_normal ; } else { backgroundId = R . drawable . com_shamanland_fab_normal ; } } updateBackground ( getResources ( ) . getDrawable ( backgroundId ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates required radius of shadow . [CODESPLIT] protected static int getShadowRadius ( Drawable shadow , Drawable circle ) { int radius = 0 ; if ( shadow != null && circle != null ) { Rect rect = new Rect ( ) ; radius = ( circle . getIntrinsicWidth ( ) + ( shadow . getPadding ( rect ) ? rect . left + rect . right : 0 ) ) / 2 ; } return Math . max ( 1 , radius ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builder to create an instance of the client . [CODESPLIT] public static Builder < OcspMultiClient > builder ( ) { return new Builder <> ( new BuildHandler < OcspMultiClient > ( ) { @ Override public OcspMultiClient build ( Properties properties ) { return new OcspMultiClient ( properties ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builder to create an instance of OcspFetcher using Apache HttpClient for connectivity . [CODESPLIT] public static Builder < OcspFetcher > builder ( ) { return new Builder <> ( new BuildHandler < OcspFetcher > ( ) { @ Override public OcspFetcher build ( Properties properties ) { return new ApacheOcspFetcher ( properties ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method for finding issuer by provided issuers in properties given an issued certificate . [CODESPLIT] protected X509Certificate findIntermediate ( X509Certificate certificate ) throws OcspException { for ( X509Certificate issuer : properties . get ( INTERMEDIATES ) ) if ( issuer . getSubjectX500Principal ( ) . equals ( certificate . getIssuerX500Principal ( ) ) ) return issuer ; throw new OcspException ( \"Unable to find issuer '%s'.\" , certificate . getIssuerX500Principal ( ) . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builder to create an instance of the client . [CODESPLIT] public static Builder < OcspClient > builder ( ) { return new Builder <> ( new BuildHandler < OcspClient > ( ) { @ Override public OcspClient build ( Properties properties ) { return new OcspClient ( properties ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the maven plugin . [CODESPLIT] @ Override public void execute ( ) throws MojoExecutionException { // First, if filtering is enabled, perform that using the Maven magic if ( applyFiltering ) { performMavenPropertyFiltering ( new File ( inputDirectory ) , filteredOutputDirectory , getInputEncoding ( ) ) ; inputDirectory = filteredOutputDirectory . getAbsolutePath ( ) ; } getLog ( ) . info ( \"Pre-processing markdown files from input directory: \" + inputDirectory ) ; preprocessMarkdownFiles ( new File ( inputDirectory ) ) ; if ( ! markdownDTOs . isEmpty ( ) ) { getLog ( ) . info ( \"Process Pegdown extension options\" ) ; int options = getPegdownExtensions ( pegdownExtensions ) ; final Map < String , Attributes > attributesMap = processAttributes ( attributes ) ; getLog ( ) . info ( \"Parse Markdown to HTML\" ) ; processMarkdown ( markdownDTOs , options , attributesMap ) ; } // FIXME: This will possibly overwrite any filtering updates made in the maven property filtering step above if ( StringUtils . isNotEmpty ( copyDirectories ) ) { getLog ( ) . info ( \"Copy files from directories\" ) ; for ( String dir : copyDirectories . split ( \",\" ) ) { for ( Entry < String , String > copyAction : getFoldersToCopy ( inputDirectory , outputDirectory , dir ) . entrySet ( ) ) { copyFiles ( copyAction . getKey ( ) , copyAction . getValue ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse attributes of the form NodeName : attributeName = attribute value : attributeName = attribute value ... [CODESPLIT] private Map < String , Attributes > processAttributes ( String [ ] attributeList ) { HashMap < String , Attributes > nodeAttributeMap = new HashMap <> ( ) ; for ( String attribute : attributeList ) { String [ ] nodeAttributes = attribute . split ( \"\\\\|\" ) ; Attributes attributes = new Attributes ( ) ; for ( int i = 1 ; i < nodeAttributes . length ; i ++ ) { String [ ] attributeNameValue = nodeAttributes [ i ] . split ( \"=\" , 2 ) ; if ( attributeNameValue . length > 1 ) { String value = attributeNameValue [ 1 ] ; if ( ! value . isEmpty ( ) ) { if ( value . charAt ( 0 ) == ' ' && value . charAt ( value . length ( ) - 1 ) == ' ' ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } else if ( value . charAt ( 0 ) == ' ' && value . charAt ( value . length ( ) - 1 ) == ' ' ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } } attributes . addValue ( attributeNameValue [ 0 ] , value ) ; } else { attributes . addValue ( attributeNameValue [ 0 ] , attributeNameValue [ 0 ] ) ; } } nodeAttributeMap . put ( nodeAttributes [ 0 ] , attributes ) ; } return nodeAttributeMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read Markdown files from directory . [CODESPLIT] @ SuppressWarnings ( \"UnusedReturnValue\" ) private boolean preprocessMarkdownFiles ( File inputDirectory ) throws MojoExecutionException { getLog ( ) . debug ( \"Read files from: \" + inputDirectory ) ; try { if ( ! inputDirectory . exists ( ) ) { getLog ( ) . info ( \"There is no input folder for the project. Skipping.\" ) ; return false ; } int baseDepth = StringUtils . countMatches ( inputDirectory . getAbsolutePath ( ) , File . separator ) ; // Reading just the markdown dir and sub dirs if recursive option set List < File > markdownFiles = getFilesAsArray ( FileUtils . iterateFiles ( inputDirectory , getInputFileExtensions ( ) , recursiveInput ) ) ; for ( File file : markdownFiles ) { getLog ( ) . debug ( \"File getName() \" + file . getName ( ) ) ; getLog ( ) . debug ( \"File getAbsolutePath() \" + file . getAbsolutePath ( ) ) ; getLog ( ) . debug ( \"File getPath() \" + file . getPath ( ) ) ; MarkdownDTO dto = new MarkdownDTO ( ) ; dto . markdownFile = file ; dto . folderDepth = StringUtils . countMatches ( file . getAbsolutePath ( ) , File . separator ) - ( baseDepth + 1 ) ; if ( alwaysUseDefaultTitle ) { dto . title = defaultTitle ; } else { List < String > raw = FileUtils . readLines ( file , getInputEncoding ( ) ) ; dto . title = getTitle ( raw ) ; } if ( applyFiltering ) { for ( String line : FileUtils . readLines ( file , getInputEncoding ( ) ) ) { if ( isVariableLine ( line ) ) { String key = line . replaceAll ( \"(^\\\\{)|(=.*)\" , \"\" ) ; String value = line . replaceAll ( \"(^\\\\{(.*?)=)|(}$)\" , \"\" ) ; getLog ( ) . debug ( \"Substitute: '\" + key + \"' -> '\" + value + \"'\" ) ; dto . substitutes . put ( key , value ) ; } } } String inputFileExtension = FilenameUtils . getExtension ( file . getName ( ) ) ; dto . htmlFile = new File ( recursiveInput ? outputDirectory + File . separator + file . getParentFile ( ) . getPath ( ) . substring ( inputDirectory . getPath ( ) . length ( ) ) + File . separator + file . getName ( ) . replaceAll ( \".\" + inputFileExtension , \".html\" ) : outputDirectory + File . separator + file . getName ( ) . replaceAll ( \".\" + inputFileExtension , \".html\" ) ) ; getLog ( ) . debug ( \"File htmlFile() \" + dto . htmlFile ) ; markdownDTOs . add ( dto ) ; } } catch ( IOException e ) { throw new MojoExecutionException ( \"Unable to load file \" + e . getMessage ( ) , e ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace variables with given pattern . [CODESPLIT] private String substituteVariables ( String template , String patternString , Map < String , String > variables ) { Pattern pattern = Pattern . compile ( patternString ) ; Matcher matcher = pattern . matcher ( template ) ; StringBuffer buffer = new StringBuffer ( ) ; while ( matcher . find ( ) ) { if ( variables . containsKey ( matcher . group ( 1 ) ) ) { String replacement = variables . get ( matcher . group ( 1 ) ) ; // quote to work properly with $ and {,} signs matcher . appendReplacement ( buffer , replacement != null ? Matcher . quoteReplacement ( replacement ) : \"null\" ) ; } } matcher . appendTail ( buffer ) ; return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Going through list of DTOs and parsing the markdown into HTML . Add header and footer to the big String . [CODESPLIT] private void processMarkdown ( List < MarkdownDTO > markdownDTOs , int options , final Map < String , Attributes > attributesMap ) throws MojoExecutionException { getLog ( ) . debug ( \"Process Markdown\" ) ; getLog ( ) . debug ( \"inputEncoding: '\" + getInputEncoding ( ) + \"', outputEncoding: '\" + getOutputEncoding ( ) + \"'\" ) ; //getLog().debug(\"parsingTimeout: \" + getParsingTimeoutInMillis() + \" ms\"); getLog ( ) . debug ( \"applyFiltering: \" + applyFiltering ) ; MutableDataHolder flexmarkOptions = PegdownOptionsAdapter . flexmarkOptions ( options ) . toMutable ( ) ; ArrayList < Extension > extensions = new ArrayList < Extension > ( ) ; for ( Extension extension : flexmarkOptions . get ( Parser . EXTENSIONS ) ) { extensions . add ( extension ) ; } if ( transformRelativeMarkdownLinks ) { flexmarkOptions . set ( PageGeneratorExtension . INPUT_FILE_EXTENSIONS , inputFileExtensions ) ; extensions . add ( PageGeneratorExtension . create ( ) ) ; } if ( ! attributesMap . isEmpty ( ) ) { flexmarkOptions . set ( AttributesExtension . ATTRIBUTE_MAP , attributesMap ) ; extensions . add ( AttributesExtension . create ( ) ) ; } flexmarkOptions . set ( Parser . EXTENSIONS , extensions ) ; Parser parser = Parser . builder ( flexmarkOptions ) . build ( ) ; HtmlRenderer renderer = HtmlRenderer . builder ( flexmarkOptions ) . build ( ) ; for ( MarkdownDTO dto : markdownDTOs ) { getLog ( ) . debug ( \"dto: \" + dto ) ; try { String headerHtml = \"\" ; String footerHtml = \"\" ; try { if ( StringUtils . isNotEmpty ( headerHtmlFile ) ) { headerHtml = FileUtils . readFileToString ( new File ( headerHtmlFile ) , getInputEncoding ( ) ) ; headerHtml = addTitleToHtmlFile ( headerHtml , dto . title ) ; headerHtml = replaceVariables ( headerHtml , dto . substitutes ) ; headerHtml = updateRelativePaths ( headerHtml , dto . folderDepth ) ; } if ( StringUtils . isNotEmpty ( footerHtmlFile ) ) { footerHtml = FileUtils . readFileToString ( new File ( footerHtmlFile ) , getInputEncoding ( ) ) ; footerHtml = replaceVariables ( footerHtml , dto . substitutes ) ; footerHtml = updateRelativePaths ( footerHtml , dto . folderDepth ) ; } } catch ( FileNotFoundException e ) { if ( failIfFilesAreMissing ) { throw e ; } else { getLog ( ) . warn ( \"header and/or footer file is missing.\" ) ; headerHtml = \"\" ; footerHtml = \"\" ; } } catch ( Exception e ) { throw new MojoExecutionException ( \"Error while processing header/footer: \" + e . getMessage ( ) , e ) ; } String markdown = FileUtils . readFileToString ( dto . markdownFile , getInputEncoding ( ) ) ; markdown = replaceVariables ( markdown , dto . substitutes ) ; // getLog().debug(markdown); String markdownAsHtml ; Node document = parser . parse ( markdown ) ; markdownAsHtml = renderer . render ( document ) ; String data = headerHtml + markdownAsHtml + footerHtml ; FileUtils . writeStringToFile ( dto . htmlFile , data , getOutputEncoding ( ) ) ; } catch ( MojoExecutionException e ) { throw e ; } catch ( IOException e ) { getLog ( ) . error ( \"Error : \" + e . getMessage ( ) , e ) ; throw new MojoExecutionException ( \"Unable to write file \" + e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the first h1 for the title . [CODESPLIT] private String getTitle ( List < String > raw ) { if ( raw == null ) { return defaultTitle ; } String previousLine = \"\" ; for ( String line : raw ) { line = line . trim ( ) ; if ( line . startsWith ( \"#\" ) ) { line = line . replace ( \"#\" , \"\" ) ; return line ; } //Checking for Setext style headers. //Line is considered a match if it passes: //Starts with either = or - //It has the same number of characters as the previous line //It only contains - or = and nothing else. // //If there is a match we consider the previous line to be the title. if ( ( line . startsWith ( \"=\" ) && StringUtils . countMatches ( line , \"=\" ) == previousLine . length ( ) && line . matches ( \"^=+$\" ) ) || ( line . startsWith ( \"-\" ) && StringUtils . countMatches ( line , \"-\" ) == previousLine . length ( ) && line . matches ( \"^-+$\" ) ) ) { return previousLine ; } previousLine = line ; } return defaultTitle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the title to the html file . [CODESPLIT] private String addTitleToHtmlFile ( String html , String title ) { if ( html == null ) { return html ; } if ( title != null ) { getLog ( ) . debug ( \"Setting the title in the HTML file to: \" + title ) ; return html . replaceFirst ( \"titleToken\" , title ) ; } else { getLog ( ) . debug ( \"Title was null, setting the title in the HTML file to an empty string\" ) ; return html . replaceFirst ( \"titleToken\" , \"\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace variables in the html file . [CODESPLIT] private String replaceVariables ( String initialContent , Map < String , String > variables ) { String newContent = initialContent ; // Only apply substitution if filtering is enabled and there is actually something to // substitute, otherwise just return the original content. if ( applyFiltering && newContent != null ) { newContent = newContent . replaceAll ( \"\\\\{\\\\w*=.*}\" , \"\" ) ; if ( variables != null ) { newContent = substituteVariables ( newContent , \"\\\\$\\\\{(.+?)\\\\}\" , variables ) ; } } return newContent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update relative include paths corresponding to the markdown file s location in the folder structure . [CODESPLIT] private String updateRelativePaths ( String html , int folderDepth ) { if ( html == null ) { return html ; } getLog ( ) . debug ( \"Updating relative paths in html includes (css, js).\" ) ; return html . replaceAll ( \"##SITE_BASE##\" , getSiteBasePrefix ( folderDepth ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy files from one dir to another based on file extensions . [CODESPLIT] private void copyFiles ( String fromDir , String toDir ) throws MojoExecutionException { getLog ( ) . debug ( \"fromDir=\" + fromDir + \"; toDir=\" + toDir ) ; try { File fromDirFile = new File ( fromDir ) ; if ( fromDirFile . exists ( ) ) { Iterator < File > files = FileUtils . iterateFiles ( new File ( fromDir ) , null , false ) ; while ( files . hasNext ( ) ) { File file = files . next ( ) ; if ( file . exists ( ) ) { FileUtils . copyFileToDirectory ( file , new File ( toDir ) ) ; } else { getLog ( ) . error ( \"File '\" + file . getAbsolutePath ( ) + \"' does not exist. Skipping copy\" ) ; } } } } catch ( IOException e ) { throw new MojoExecutionException ( \"Unable to copy file \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This solves https : // issues . apache . org / jira / browse / MRESOURCES - 99 . <br / > BUT : <br / > This should be done different than defining those properties a second time cause they have already being defined in Maven Model Builder ( package org . apache . maven . model . interpolation ) via BuildTimestampValueSource . But those can t be found in the context which can be got from the maven core . <br / > A solution could be to put those values into the context by Maven core so they are accessible everywhere . ( I m not sure if this is a good idea ) . Better ideas are always welcome . <p > The problem at the moment is that maven core handles usage of properties and replacements in the model but does not the resource filtering which needed some of the properties . [CODESPLIT] private Properties addSeveralSpecialProperties ( ) { String timeStamp = new MavenBuildTimestamp ( new Date ( ) , timestampFormat ) . formattedTimestamp ( ) ; Properties additionalProperties = new Properties ( ) ; additionalProperties . put ( \"mdpagegenerator.timestamp\" , timeStamp ) ; if ( project . getBasedir ( ) != null ) { additionalProperties . put ( \"project.baseUri\" , project . getBasedir ( ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; } return additionalProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When retrieving more statements LRS will return full path .. the client will have part in the URI already so cut that off [CODESPLIT] protected String checkPath ( String path ) { if ( path . toLowerCase ( ) . contains ( \"statements\" ) && path . toLowerCase ( ) . contains ( \"more\" ) ) { int pathLength = this . _host . getPath ( ) . length ( ) ; return path . substring ( pathLength , path . length ( ) ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this will wrap the view which is added to the slider into another layout so we can then overlap the small and large view [CODESPLIT] private View wrapSliderContent ( View child , int index ) { //TODO !! if ( index == 1 && child . getId ( ) != - 1 ) { mLargeView = ( ViewGroup ) child ; mContainer = new ScrimInsetsRelativeLayout ( getContext ( ) ) ; mContainer . setGravity ( Gravity . START ) ; mContainer . setLayoutParams ( child . getLayoutParams ( ) ) ; mContainer . addView ( mLargeView , ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . MATCH_PARENT ) ; mSmallView = new LinearLayout ( getContext ( ) ) ; mContainer . addView ( mSmallView , ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . MATCH_PARENT ) ; mLargeView . setAlpha ( 0 ) ; mLargeView . setVisibility ( View . GONE ) ; //correct fitsSystemWindows handling mContainer . setFitsSystemWindows ( true ) ; mSmallView . setFitsSystemWindows ( true ) ; return mContainer ; } return child ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "animate to the large view [CODESPLIT] public void fadeUp ( int duration ) { //animate up mContainer . clearAnimation ( ) ; ResizeWidthAnimation anim = new ResizeWidthAnimation ( mContainer , mMaxWidth , new ApplyTransformationListener ( ) { @ Override public void applyTransformation ( int width ) { overlapViews ( width ) ; } } ) ; anim . setDuration ( duration ) ; mContainer . startAnimation ( anim ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "animate to the small view [CODESPLIT] public void fadeDown ( int duration ) { //fade down mContainer . clearAnimation ( ) ; ResizeWidthAnimation anim = new ResizeWidthAnimation ( mContainer , mMinWidth , new ApplyTransformationListener ( ) { @ Override public void applyTransformation ( int width ) { overlapViews ( width ) ; } } ) ; anim . setDuration ( duration ) ; mContainer . startAnimation ( anim ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "calculate the percentage to how many percent the slide is already visible [CODESPLIT] private float calculatePercentage ( int width ) { int absolute = mMaxWidth - mMinWidth ; int current = width - mMinWidth ; float percentage = 100.0f * current / absolute ; //we can assume that we are crossfaded if the percentage is > 90 mIsCrossfaded = percentage > 90 ; return percentage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "overlap the views and provide the crossfade effect [CODESPLIT] private void overlapViews ( int width ) { if ( width == mWidth ) { return ; } //remember this width so it is't processed twice mWidth = width ; float percentage = calculatePercentage ( width ) ; float alpha = percentage / 100 ; mSmallView . setAlpha ( 1 ) ; mSmallView . setClickable ( false ) ; mLargeView . bringToFront ( ) ; mLargeView . setAlpha ( alpha ) ; mLargeView . setClickable ( true ) ; mLargeView . setVisibility ( alpha > 0.01f ? View . VISIBLE : View . GONE ) ; //notify the crossfadeListener if ( mCrossfadeListener != null ) { mCrossfadeListener . onCrossfade ( mContainer , calculatePercentage ( width ) , width ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The intent to launch the Activity . [CODESPLIT] protected < T extends Activity > Intent getLaunchIntent ( String targetPackage , Class < T > activityClass , BundleCreator bundleCreator ) { Intent intent = new Intent ( Intent . ACTION_MAIN ) ; intent . setClassName ( targetPackage , activityClass . getName ( ) ) ; intent . putExtras ( bundleCreator . createBundle ( ) ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; return intent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launch the activity if needed . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void launchActivity ( ) { if ( activity != null && ActivityRunMode . SPECIFICATION . equals ( activityRunMode ) ) return ; String targetPackage = instrumentation . getTargetContext ( ) . getPackageName ( ) ; Intent intent = getLaunchIntent ( targetPackage , activityClass , bundleCreator ) ; activity = instrumentation . startActivitySync ( intent ) ; instrumentation . waitForIdleSync ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getTodos Retrieves all todos a user can read . [CODESPLIT] public TodoListResponse getTodos ( String type , String status , UUID factSheetId , UUID userId , UUID workspaceId , Boolean getArchived , Integer size , Integer page ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = \"/todos\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"type\" , type ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"status\" , status ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"factSheetId\" , factSheetId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"userId\" , userId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"workspaceId\" , workspaceId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"getArchived\" , getArchived ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"size\" , size ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"page\" , page ) ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { \"application/json\" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { \"token\" } ; GenericType < TodoListResponse > localVarReturnType = new GenericType < TodoListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"GET\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getFactSheets Retrieves all Fact Sheets [CODESPLIT] public FactSheetListResponse getFactSheets ( String type , String relationTypes , Integer pageSize , String cursor , Boolean permissions ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = \"/factSheets\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"type\" , type ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"relationTypes\" , relationTypes ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"pageSize\" , pageSize ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"cursor\" , cursor ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"permissions\" , permissions ) ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { \"application/json\" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { \"token\" } ; GenericType < FactSheetListResponse > localVarReturnType = new GenericType < FactSheetListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"GET\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the connect timeout ( in milliseconds ) . A value of 0 means no timeout otherwise values must be between 1 and { [CODESPLIT] public ApiClient setConnectTimeout ( int connectionTimeout ) { this . connectionTimeout = connectionTimeout ; httpClient . property ( ClientProperties . CONNECT_TIMEOUT , connectionTimeout ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the date format used to parse / format date parameters . [CODESPLIT] public ApiClient setDateFormat ( DateFormat dateFormat ) { this . dateFormat = dateFormat ; // also set the date format for model (de)serialization with Date properties this . json . setDateFormat ( ( DateFormat ) dateFormat . clone ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize the given Java object into string entity according the given Content - Type ( only JSON is supported for now ) . [CODESPLIT] public Entity < ? > serialize ( Object obj , Map < String , Object > formParams , String contentType ) throws ApiException { Entity < ? > entity = null ; if ( contentType . startsWith ( \"multipart/form-data\" ) ) { MultiPart multiPart = new MultiPart ( ) ; for ( Entry < String , Object > param : formParams . entrySet ( ) ) { if ( param . getValue ( ) instanceof File ) { File file = ( File ) param . getValue ( ) ; FormDataContentDisposition contentDisp = FormDataContentDisposition . name ( param . getKey ( ) ) . fileName ( file . getName ( ) ) . size ( file . length ( ) ) . build ( ) ; multiPart . bodyPart ( new FormDataBodyPart ( contentDisp , file , MediaType . APPLICATION_OCTET_STREAM_TYPE ) ) ; } else { FormDataContentDisposition contentDisp = FormDataContentDisposition . name ( param . getKey ( ) ) . build ( ) ; multiPart . bodyPart ( new FormDataBodyPart ( contentDisp , parameterToString ( param . getValue ( ) ) ) ) ; } } entity = Entity . entity ( multiPart , MediaType . MULTIPART_FORM_DATA_TYPE ) ; } else if ( contentType . startsWith ( \"application/x-www-form-urlencoded\" ) ) { Form form = new Form ( ) ; for ( Entry < String , Object > param : formParams . entrySet ( ) ) { form . param ( param . getKey ( ) , parameterToString ( param . getValue ( ) ) ) ; } entity = Entity . entity ( form , MediaType . APPLICATION_FORM_URLENCODED_TYPE ) ; } else { // We let jersey handle the serialization entity = Entity . entity ( obj , contentType ) ; } return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserialize response body to Java object according to the Content - Type . [CODESPLIT] public < T > T deserialize ( Response response , GenericType < T > returnType ) throws ApiException { // Handle file downloading. if ( returnType . equals ( File . class ) ) { @ SuppressWarnings ( \"unchecked\" ) T file = ( T ) downloadFileFromResponse ( response ) ; return file ; } String contentType = null ; List < Object > contentTypes = response . getHeaders ( ) . get ( \"Content-Type\" ) ; if ( contentTypes != null && ! contentTypes . isEmpty ( ) ) contentType = String . valueOf ( contentTypes . get ( 0 ) ) ; if ( contentType == null ) throw new ApiException ( 500 , \"missing Content-Type in response\" ) ; return response . readEntity ( returnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Download file from the given response . [CODESPLIT] public File downloadFileFromResponse ( Response response ) throws ApiException { try { File file = prepareDownloadFile ( response ) ; Files . copy ( response . readEntity ( InputStream . class ) , file . toPath ( ) ) ; return file ; } catch ( IOException e ) { throw new ApiException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke API by sending HTTP request with the given options . [CODESPLIT] public < T > T invokeAPI ( String path , String method , List < Pair > queryParams , Object body , Map < String , String > headerParams , Map < String , Object > formParams , String accept , String contentType , String [ ] authNames , GenericType < T > returnType ) throws ApiException { updateParamsForAuth ( new String [ ] { \"token\" , \"apiKey\" } /*authNames*/ , queryParams , headerParams ) ; // Not using `.target(this.basePath).path(path)` below, // to support (constant) query string in `path`, e.g. \"/posts?draft=1\" WebTarget target = httpClient . target ( this . basePath + path ) ; if ( queryParams != null ) { for ( Pair queryParam : queryParams ) { if ( queryParam . getValue ( ) != null ) { target = target . queryParam ( queryParam . getName ( ) , queryParam . getValue ( ) ) ; } } } Invocation . Builder invocationBuilder = target . request ( ) . accept ( accept ) ; for ( String key : headerParams . keySet ( ) ) { String value = headerParams . get ( key ) ; if ( value != null ) { invocationBuilder = invocationBuilder . header ( key , value ) ; } } for ( String key : defaultHeaderMap . keySet ( ) ) { if ( ! headerParams . containsKey ( key ) ) { String value = defaultHeaderMap . get ( key ) ; if ( value != null ) { invocationBuilder = invocationBuilder . header ( key , value ) ; } } } Entity < ? > entity = serialize ( body , formParams , contentType ) ; Response response = null ; if ( \"GET\" . equals ( method ) ) { response = invocationBuilder . get ( ) ; } else if ( \"POST\" . equals ( method ) ) { response = invocationBuilder . post ( entity ) ; } else if ( \"PUT\" . equals ( method ) ) { response = invocationBuilder . put ( entity ) ; } else if ( \"DELETE\" . equals ( method ) ) { response = invocationBuilder . delete ( ) ; } else { throw new ApiException ( 500 , \"unknown method type \" + method ) ; } statusCode = response . getStatusInfo ( ) . getStatusCode ( ) ; responseHeaders = buildResponseHeaders ( response ) ; if ( response . getStatus ( ) == Status . NO_CONTENT . getStatusCode ( ) ) { return null ; } else if ( response . getStatusInfo ( ) . getFamily ( ) . equals ( Status . Family . SUCCESSFUL ) ) { if ( returnType == null ) return null ; else return deserialize ( response , returnType ) ; } else { String message = \"error\" ; String respBody = null ; if ( response . hasEntity ( ) ) { try { respBody = String . valueOf ( response . readEntity ( String . class ) ) ; message = respBody ; } catch ( RuntimeException e ) { // e.printStackTrace(); } } throw new ApiException ( response . getStatus ( ) , message , buildResponseHeaders ( response ) , respBody ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the Client used to make HTTP requests . [CODESPLIT] private Client buildHttpClient ( boolean debugging ) { final ClientConfig clientConfig = new ClientConfig ( ) ; clientConfig . register ( MultiPartFeature . class ) ; clientConfig . register ( json ) ; clientConfig . register ( JacksonFeature . class ) ; if ( debugging ) { clientConfig . register ( LoggingFilter . class ) ; } return ClientBuilder . newClient ( clientConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "createAccessControlEntity Creates an access control entity [CODESPLIT] public AccessControlEntityResponse createAccessControlEntity ( AccessControlEntity body ) throws ApiException { Object localVarPostBody = body ; // create path and map variables String localVarPath = \"/models/accessControlEntities\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { \"application/json\" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { \"token\" } ; GenericType < AccessControlEntityResponse > localVarReturnType = new GenericType < AccessControlEntityResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"POST\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "updateDataModel Updates the data model for a workspace [CODESPLIT] public DataModelUpdateResponse updateDataModel ( DataModel body , Boolean force , String workspaceId ) throws ApiException { Object localVarPostBody = body ; // verify the required parameter 'body' is set if ( body == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'body' when calling updateDataModel\" ) ; } // create path and map variables String localVarPath = \"/models/dataModel\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"force\" , force ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"workspaceId\" , workspaceId ) ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { \"application/json\" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { \"token\" } ; GenericType < DataModelUpdateResponse > localVarReturnType = new GenericType < DataModelUpdateResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"PUT\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "createFullExport Creates a full export of the workspace data or an export of the changelog depending on given type [CODESPLIT] public JobResponse createFullExport ( String exportType , String startDate , String endDate ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = \"/exports/fullExport\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"exportType\" , exportType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"startDate\" , startDate ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"endDate\" , endDate ) ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { \"application/json\" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { } ; GenericType < JobResponse > localVarReturnType = new GenericType < JobResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"POST\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getExports Lists all exports of the given type in the workspace of the authorized user [CODESPLIT] public ExportListResponse getExports ( String exportType , UUID userId , Integer pageSize , String cursor , String sorting , String sortDirection ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = \"/exports\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"exportType\" , exportType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"userId\" , userId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"pageSize\" , pageSize ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"cursor\" , cursor ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"sorting\" , sorting ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"sortDirection\" , sortDirection ) ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { } ; GenericType < ExportListResponse > localVarReturnType = new GenericType < ExportListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"GET\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get state [CODESPLIT] @ ApiModelProperty ( example = \"null\" , required = true , value = \"\" ) public Map < String , Object > getState ( ) { return state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies all urls needed to get an access token based on given host name and common url naming convention . [CODESPLIT] public ApiClientBuilder withTokenProviderHost ( String host ) { withOAuth2TokenUrl ( URI . create ( String . format ( \"https://%s/services/mtm/v1/oauth2/token\" , host ) ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets your client Id and client Secret . [CODESPLIT] public ApiClientBuilder withClientCredentials ( String clientId , String clientSecret ) { this . clientId = clientId ; this . clientSecret = clientSecret ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "processGraphQLMultipart Processes GraphQL requests supporting multipart documents [CODESPLIT] public GraphQLResult processGraphQLMultipart ( String graphQLRequest , File file ) throws ApiException { Object localVarPostBody = null ; // verify the required parameter 'graphQLRequest' is set if ( graphQLRequest == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'graphQLRequest' when calling processGraphQLMultipart\" ) ; } // verify the required parameter 'file' is set if ( file == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'file' when calling processGraphQLMultipart\" ) ; } // create path and map variables String localVarPath = \"/graphql/upload\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; if ( graphQLRequest != null ) localVarFormParams . put ( \"graphQLRequest\" , graphQLRequest ) ; if ( file != null ) localVarFormParams . put ( \"file\" , file ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { \"multipart/form-data\" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { \"token\" } ; GenericType < GraphQLResult > localVarReturnType = new GenericType < GraphQLResult > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"POST\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get params [CODESPLIT] @ ApiModelProperty ( example = \"null\" , required = true , value = \"\" ) public Map < String , String > getParams ( ) { return params ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getBookmarks Retrieves all stored bookmarks a user can read . [CODESPLIT] public BookmarkListResponse getBookmarks ( String bookmarkType , String groupKey , String sharingType ) throws ApiException { Object localVarPostBody = null ; // verify the required parameter 'bookmarkType' is set if ( bookmarkType == null ) { throw new ApiException ( 400 , \"Missing the required parameter 'bookmarkType' when calling getBookmarks\" ) ; } // create path and map variables String localVarPath = \"/bookmarks\" . replaceAll ( \"\\\\{format\\\\}\" , \"json\" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"bookmarkType\" , bookmarkType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"groupKey\" , groupKey ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( \"\" , \"sharingType\" , sharingType ) ) ; final String [ ] localVarAccepts = { \"application/json\" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { \"application/json\" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { \"token\" } ; GenericType < BookmarkListResponse > localVarReturnType = new GenericType < BookmarkListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , \"GET\" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps Jena bindings defined by a variable name and a { @link org . apache . jena . graph . Node } to MarkLogic { @link com . marklogic . client . semantics . SPARQLQueryDefinition } bindings . [CODESPLIT] public static SPARQLQueryDefinition bindObject ( SPARQLQueryDefinition qdef , String variableName , Node objectNode ) { SPARQLBindings bindings = qdef . getBindings ( ) ; if ( objectNode . isURI ( ) ) { bindings . bind ( variableName , objectNode . getURI ( ) ) ; } else if ( objectNode . isLiteral ( ) ) { if ( ! \"\" . equals ( objectNode . getLiteralLanguage ( ) ) ) { String languageTag = objectNode . getLiteralLanguage ( ) ; bindings . bind ( variableName , objectNode . getLiteralLexicalForm ( ) , Locale . forLanguageTag ( languageTag ) ) ; } else if ( objectNode . getLiteralDatatype ( ) != null ) { try { String xsdType = objectNode . getLiteralDatatypeURI ( ) ; String fragment = new URI ( xsdType ) . getFragment ( ) ; bindings . bind ( variableName , objectNode . getLiteralLexicalForm ( ) , RDFTypes . valueOf ( fragment . toUpperCase ( ) ) ) ; } catch ( URISyntaxException e ) { throw new MarkLogicJenaException ( \"Unrecognized binding type.  Use XSD only.\" , e ) ; } } else { // is this a hole, no type string? bindings . bind ( variableName , objectNode . getLiteralLexicalForm ( ) , RDFTypes . STRING ) ; } } qdef . setBindings ( bindings ) ; return qdef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] @ Override protected void addToDftGraph ( Node s , Node p , Node o ) { checkIsOpen ( ) ; Node s1 = skolemize ( s ) ; Node p1 = skolemize ( p ) ; Node o1 = skolemize ( o ) ; client . sinkQuad ( null , s1 , p1 , o1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges triples into a graph on the MarkLogic server . mergeGraph () is NOT part of Jena s DatasetGraph interface . [CODESPLIT] public void mergeGraph ( Node graphName , Graph graph ) { checkIsOpen ( ) ; sync ( ) ; client . mergeGraph ( graphName . getURI ( ) , graph ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds permissions to a graph . [CODESPLIT] public void addPermissions ( Node graphName , GraphPermissions permissions ) { checkIsOpen ( ) ; client . mergeGraphPermissions ( graphName . getURI ( ) , permissions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the permissions on a graph . [CODESPLIT] public void writePermissions ( Node graphName , GraphPermissions permissions ) { checkIsOpen ( ) ; client . writeGraphPermissions ( graphName . getURI ( ) , permissions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fluent setter for rulesets . [CODESPLIT] public MarkLogicDatasetGraph withRulesets ( SPARQLRuleset ... rulesets ) { if ( this . rulesets == null ) { this . rulesets = rulesets ; } else { Collection < SPARQLRuleset > collection = new ArrayList < SPARQLRuleset > ( ) ; collection . addAll ( Arrays . asList ( this . rulesets ) ) ; collection . addAll ( Arrays . asList ( rulesets ) ) ; this . rulesets = collection . toArray ( new SPARQLRuleset [ ] { } ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the connection and free resources [CODESPLIT] public void close ( ) { if ( writeBuffer != null ) { writeBuffer . cancel ( ) ; } if ( timer != null ) { timer . cancel ( ) ; } client = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "synchronization needed because of setting of page length [CODESPLIT] public synchronized InputStreamHandle executeSelect ( SPARQLQueryDefinition qdef , InputStreamHandle handle , Long offset , Long limit ) { if ( limit == null ) { this . sparqlQueryManager . clearPageLength ( ) ; } else { this . sparqlQueryManager . setPageLength ( limit ) ; } if ( offset != null ) { return this . sparqlQueryManager . executeSelect ( qdef , handle , offset , currentTransaction ) ; } else { return this . sparqlQueryManager . executeSelect ( qdef , handle , currentTransaction ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If timer is turned on ( periodicFlush = true in constructor ) this method puts a quad into the cache which is periodically sent to MarkLogic otherwise it sends the quad directly [CODESPLIT] public void sinkQuad ( Node g , Node s , Node p , Node o ) { if ( writeBuffer != null ) { writeBuffer . add ( g , s , p , o ) ; } else { Graph graph = GraphFactory . createDefaultGraph ( ) ; graph . add ( Triple . create ( s , p , o ) ) ; mergeGraph ( g . getURI ( ) , graph ) ; return ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a MarkLogicDatasetGraph from an existing { @link com . marklogic . client . DatabaseClient } . [CODESPLIT] public static MarkLogicDatasetGraph createDatasetGraph ( DatabaseClient client ) { JenaDatabaseClient jenaClient = new JenaDatabaseClient ( client ) ; MarkLogicDatasetGraph datasetGraph = new MarkLogicDatasetGraph ( jenaClient ) ; MarkLogicQueryEngine . unregister ( ) ; MarkLogicQueryEngine . register ( ) ; MarkLogicUpdateEngine . unregister ( ) ; MarkLogicUpdateEngine . register ( ) ; return datasetGraph ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates MarkLogicDatasetGraph from access parameters to a REST MarkLogic server . [CODESPLIT] static public MarkLogicDatasetGraph createDatasetGraph ( String host , int port , String user , String password , Authentication type ) { DatabaseClient client = DatabaseClientFactory . newClient ( host , port , user , password , type ) ; return MarkLogicDatasetGraphFactory . createDatasetGraph ( client ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String execute ( @ Nonnull String command , String ... arguments ) throws IOException , GMException , GMServiceException { PooledGMConnection connection = pool . borrowObject ( ) ; try { return connection . execute ( command , arguments ) ; } finally { pool . returnObject ( connection ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override @ Nonnull public PooledGMConnection borrowObject ( ) throws GMServiceException { try { return super . borrowObject ( ) ; } catch ( GMServiceException e ) { throw e ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new GMServiceException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } <p > This implementation delegates to super class but ensures that there is no other checked exception except { @link GMServiceException } will be thrown . [CODESPLIT] @ Override public void returnObject ( @ Nonnull PooledGMConnection connection ) throws GMServiceException { try { super . returnObject ( connection ) ; } catch ( GMServiceException e ) { throw e ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new GMServiceException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override protected int run ( @ Nonnull LinkedList < String > pArgs ) throws Exception { int rc ; try { String result = executor . execute ( pArgs ) ; if ( outputConsumer != null && result != null ) outputConsumer . consumeOutput ( stringToStream ( result ) ) ; rc = 0 ; } catch ( GMException e ) { if ( errorConsumer != null ) errorConsumer . consumeError ( stringToStream ( e . getMessage ( ) ) ) ; else throw e ; rc = 1 ; } finished ( rc ) ; return rc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the path to GraphicsMagick executable . [CODESPLIT] public void setGMPath ( @ Nonnull String gmPath ) { if ( gmPath == null ) throw new NullPointerException ( \"gmPath\" ) ; factory = builder . buildFactory ( gmPath ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String execute ( @ Nonnull String command , String ... arguments ) throws GMException , GMServiceException , IOException { final GMConnection connection = getConnection ( ) ; try { return connection . execute ( command , arguments ) ; } finally { connection . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String execute ( List < String > command ) throws GMException , GMServiceException , IOException { final GMConnection connection = getConnection ( ) ; try { return connection . execute ( command ) ; } finally { connection . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override @ Nonnull public GMConnection getConnection ( ) throws GMServiceException { try { return new BasicGMConnection ( factory . getProcess ( ) ) ; } catch ( IOException e ) { throw new GMServiceException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Limits the number of threads used by the GraphicsMagick process during execution . Note that no validation is made so ensure that the value is a non - positive integer presumably less than the maximum CPU cores on the host . [CODESPLIT] public GMOperation limitThreads ( final int threadsPerProcess ) { final List < String > args = getCmdArgs ( ) ; args . add ( \"-limit\" ) ; args . add ( \"threads\" ) ; args . add ( Integer . toString ( threadsPerProcess ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resize source to desired target dimensions using default resizing filter algorithm . [CODESPLIT] public GMOperation resize ( final int width , final int height , final Collection < GeometryAnnotation > annotations ) { final List < String > args = getCmdArgs ( ) ; args . add ( \"-resize\" ) ; args . add ( resample ( width , height , annotations ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rotates the image with empty triangles back - filled using default background color . [CODESPLIT] public GMOperation rotate ( final double degrees , final RotationAnnotation annotation ) { if ( annotation == null ) { throw new IllegalArgumentException ( \"Rotation annotation must be defined\" ) ; } final List < String > args = getCmdArgs ( ) ; args . add ( \"-rotate\" ) ; args . add ( String . format ( Locale . ENGLISH , \"%.1f%s\" , degrees , annotation . asAnnotation ( ) ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines the gravity for geometry - based operations . See documentation for more details as this option works in conjunction with various options in different ways . [CODESPLIT] public GMOperation gravity ( final Gravity value ) { if ( value == null ) { throw new IllegalArgumentException ( \"Gravity value must be defined\" ) ; } gravity ( value . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strips out ICC profiles . [CODESPLIT] public GMOperation stripProfiles ( ) { final List < String > args = getCmdArgs ( ) ; args . add ( \"+profile\" ) ; args . add ( \"*\" ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Defines font for text overlay . [CODESPLIT] public GMOperation font ( final String style , final int size , final String color ) { if ( isBlank ( style ) ) { throw new IllegalArgumentException ( \"Text font style must be defined\" ) ; } if ( isBlank ( color ) ) { throw new IllegalArgumentException ( \"Text font color must be defined\" ) ; } font ( style ) ; pointsize ( size ) ; fill ( color ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Draws text overlay on image with the upper - right corner defined by the { @code offsetX } and { @code offsetY } parameters . Note that { @link#gravity ( Gravity ) } will affect how the offset values are interpreted . [CODESPLIT] public GMOperation drawText ( final String text , final int offsetX , final int offsetY ) { if ( isBlank ( text ) ) { throw new IllegalArgumentException ( \"Text string must be defined\" ) ; } draw ( String . format ( Locale . ENGLISH , \"text %d %d '%s'\" , offsetX , offsetY , text ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the source image to convert . [CODESPLIT] public GMOperation source ( final File file , @ CheckForNull final Integer width , @ CheckForNull final Integer height ) throws IOException { if ( file != null && ! file . exists ( ) ) { throw new IOException ( \"Source file '\" + file + \"' does not exist\" ) ; } if ( ( width != null ) && ( height != null ) && ( width > 0 ) && ( height > 0 ) ) { size ( width , height ) ; } return addImage ( file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add image to operation . [CODESPLIT] public GMOperation addImage ( final File file ) { if ( file == null ) { throw new IllegalArgumentException ( \"file must be defined\" ) ; } getCmdArgs ( ) . add ( file . getPath ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add option - quality to the GraphicsMagick commandline ( see the documentation of GraphicsMagick for details ) . [CODESPLIT] public GMOperation quality ( double quality ) { final List < String > args = getCmdArgs ( ) ; args . add ( \"-quality\" ) ; args . add ( Double . toString ( quality ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Time histogram . [CODESPLIT] public @ NotNull Histogram timeSeconds ( @ NotNull String name ) { return histograms . computeIfAbsent ( \"vertx_\" + name + \"_time_seconds\" , key -> register ( Histogram . build ( key , \"Processing time in seconds\" ) . labelNames ( \"local_address\" ) . create ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HTTP requests gauge . [CODESPLIT] public @ NotNull Gauge httpRequests ( @ NotNull String name ) { return gauges . computeIfAbsent ( \"vertx_\" + name + \"_requests\" , key -> register ( Gauge . build ( key , \"HTTP requests number\" ) . labelNames ( \"local_address\" , \"method\" , \"path\" , \"state\" ) . create ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bytes counter . [CODESPLIT] public @ NotNull Counter bytes ( @ NotNull String name ) { return counters . computeIfAbsent ( \"vertx_\" + name + \"_bytes\" , key -> register ( Counter . build ( key , \"Read/written bytes\" ) . labelNames ( \"local_address\" , \"type\" ) . create ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a set of arguments and populate the target with the appropriate values . [CODESPLIT] public static List < String > parse ( Object target , String [ ] args ) { List < String > arguments = new ArrayList < String > ( ) ; arguments . addAll ( Arrays . asList ( args ) ) ; Class < ? > clazz ; if ( target instanceof Class ) { clazz = ( Class ) target ; } else { clazz = target . getClass ( ) ; try { BeanInfo info = Introspector . getBeanInfo ( clazz ) ; for ( PropertyDescriptor pd : info . getPropertyDescriptors ( ) ) { processProperty ( target , pd , arguments ) ; } } catch ( IntrospectionException e ) { // If its not a JavaBean we ignore it } } // Check fields of 'target' class and its superclasses for ( Class < ? > currentClazz = clazz ; currentClazz != null ; currentClazz = currentClazz . getSuperclass ( ) ) { for ( Field field : currentClazz . getDeclaredFields ( ) ) { processField ( target , field , arguments ) ; } } for ( String argument : arguments ) { if ( argument . startsWith ( \"-\" ) ) { throw new IllegalArgumentException ( \"Invalid argument: \" + argument ) ; } } return arguments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate usage information based on the target annotations . [CODESPLIT] public static void usage ( PrintStream errStream , Object target ) { Class < ? > clazz ; if ( target instanceof Class ) { clazz = ( Class ) target ; } else { clazz = target . getClass ( ) ; } errStream . println ( \"Usage: \" + clazz . getName ( ) ) ; for ( Class < ? > currentClazz = clazz ; currentClazz != null ; currentClazz = currentClazz . getSuperclass ( ) ) { for ( Field field : currentClazz . getDeclaredFields ( ) ) { fieldUsage ( errStream , target , field ) ; } } try { BeanInfo info = Introspector . getBeanInfo ( clazz ) ; for ( PropertyDescriptor pd : info . getPropertyDescriptors ( ) ) { propertyUsage ( errStream , target , pd ) ; } } catch ( IntrospectionException e ) { // If its not a JavaBean we ignore it } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts and returns the time unit from a string . If the string doesn t include a unit it returns null . [CODESPLIT] public static TimeUnit extractTimeUnitFromString ( String timeString ) { timeString = timeString . toLowerCase ( ) ; if ( timeString . contains ( \"minute\" ) ) { return TimeUnit . MINUTES ; } else if ( timeString . contains ( \"microsecond\" ) ) { return TimeUnit . MICROSECONDS ; } else if ( timeString . contains ( \"millisecond\" ) ) { return TimeUnit . MILLISECONDS ; } else if ( timeString . contains ( \"second\" ) ) { return TimeUnit . SECONDS ; } else if ( timeString . contains ( \"hour\" ) ) { return TimeUnit . HOURS ; } else if ( timeString . toLowerCase ( ) . contains ( \"day\" ) ) { return TimeUnit . DAYS ; } else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse properties instead of String arguments . Any additional arguments need to be passed some other way . This is often used in a second pass when the property filename is passed on the command line . Because of required properties you must be careful to set them all in the property file . [CODESPLIT] public static void parse ( Object target , Properties arguments ) { Class clazz ; if ( target instanceof Class ) { clazz = ( Class ) target ; } else { clazz = target . getClass ( ) ; } for ( Field field : clazz . getDeclaredFields ( ) ) { processField ( target , field , arguments ) ; } try { BeanInfo info = Introspector . getBeanInfo ( clazz ) ; for ( PropertyDescriptor pd : info . getPropertyDescriptors ( ) ) { processProperty ( target , pd , arguments ) ; } } catch ( IntrospectionException e ) { // If its not a JavaBean we ignore it } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "src : http : // stackoverflow . com / questions / 1399126 / java - util - zip - recreating - directory - structure [CODESPLIT] public static void zipDir ( File directory , File zipfile ) throws IOException { URI base = directory . toURI ( ) ; Deque < File > queue = new LinkedList < File > ( ) ; queue . push ( directory ) ; OutputStream out = new FileOutputStream ( zipfile ) ; Closeable res = out ; try { ZipOutputStream zout = new ZipOutputStream ( out ) ; res = zout ; while ( ! queue . isEmpty ( ) ) { directory = queue . pop ( ) ; for ( File kid : directory . listFiles ( ) ) { String name = base . relativize ( kid . toURI ( ) ) . getPath ( ) ; if ( kid . isDirectory ( ) ) { queue . push ( kid ) ; name = name . endsWith ( \"/\" ) ? name : name + \"/\" ; zout . putNextEntry ( new ZipEntry ( name ) ) ; } else { zout . putNextEntry ( new ZipEntry ( name ) ) ; copy ( kid , zout ) ; zout . closeEntry ( ) ; } } } } finally { res . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a presentation file at a given url [CODESPLIT] static public void execute ( URL url ) throws SlideExecutionException { checkNotNull ( url ) ; ScreenRegion screenRegion = new DesktopScreenRegion ( ) ; Context context = new Context ( screenRegion ) ; execute ( url , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a presentation file at an URL using a specific { [CODESPLIT] static public void execute ( URL url , Context context ) throws SlideExecutionException { checkNotNull ( url ) ; checkNotNull ( context ) ; logger . debug ( \"execute slides with context {}\" , context ) ; SlidesReader reader = new PPTXSlidesReader ( ) ; List < Slide > slides ; try { slides = reader . read ( url ) ; } catch ( IOException e ) { throw new SlideExecutionException ( e ) ; } SlidesExecutor executor = new AutomationExecutor ( context ) ; executor . execute ( slides ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a presentation file [CODESPLIT] static public void execute ( File file ) throws SlideExecutionException { checkNotNull ( file ) ; try { execute ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new SlideExecutionException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interpret a presentation file as a list of executable actions [CODESPLIT] public static List < Action > interpret ( File file ) throws IOException { checkNotNull ( file ) ; Interpreter interpreter = new DefaultInterpreter ( ) ; SlidesReader reader = new PPTXSlidesReader ( ) ; List < Slide > slides ; slides = reader . read ( file ) ; List < Action > actions = Lists . newArrayList ( ) ; for ( Slide slide : slides ) { Action action = interpreter . interpret ( slide ) ; actions . add ( action ) ; logger . info ( \"Action interpreted: {}\" , action ) ; } return actions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "detector . stop () ; [CODESPLIT] synchronized void setCurrentSlideIndex ( int i ) { this . index = i ; Slide slide = slides . get ( i ) ; viewer . setSlide ( slide ) ; viewer . setVisible ( true ) ; pending = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute and wait for execution to finish [CODESPLIT] public void execute ( Context context ) throws ActionExecutionException { int count = 0 ; for ( Action action : getChildren ( ) ) { if ( ! isBackground ( action ) ) { count += 1 ; } } doneSignal = new CountDownLatch ( count ) ; List < Worker > workers = Lists . newArrayList ( ) ; for ( Action action : getChildren ( ) ) { final Context workerContxt = new Context ( context ) ; if ( ! isBackground ( action ) ) { Worker worker = new Worker ( action , workerContxt ) ; workers . add ( worker ) ; new Thread ( worker ) . start ( ) ; } else { Worker worker = new BackgroundWorker ( action , workerContxt ) ; new Thread ( worker ) . start ( ) ; } } try { doneSignal . await ( ) ; } catch ( InterruptedException e ) { } stop ( ) ; // if any of the worker did not succeed,  // rethrow the associated ActionExecutionException for ( Worker worker : workers ) { if ( ! worker . success ) { throw worker . exception ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Argument : [CODESPLIT] public boolean step2 ( ) { Target target = new ImageTarget ( new File ( \"image2.png\" ) ) ; target . setMinScore ( DEFAULT_MINSCORE ) ; ScreenRegion loc = screenRegion . find ( target ) ; if ( loc != null ) { mouse . rightClick ( loc . getCenter ( ) ) ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Argument : [CODESPLIT] public boolean step6 ( ) { Target target = new ImageTarget ( new File ( \"image6.png\" ) ) ; target . setMinScore ( DEFAULT_MINSCORE ) ; ScreenRegion loc = screenRegion . find ( target ) ; return loc == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Argument : something to type [CODESPLIT] public boolean step7 ( ) { Target target = new ImageTarget ( new File ( \"image7.png\" ) ) ; target . setMinScore ( DEFAULT_MINSCORE ) ; ScreenRegion loc = screenRegion . find ( target ) ; if ( loc != null ) { mouse . click ( loc . getCenter ( ) ) ; keyboard . type ( \"something to type\" ) ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "end constructor [CODESPLIT] private static boolean supportsDnD ( ) { // Static Boolean\r if ( supportsDnD == null ) { boolean support = false ; try { Class arbitraryDndClass = Class . forName ( \"java.awt.dnd.DnDConstants\" ) ; support = true ; } // end try\r catch ( Exception e ) { support = false ; } // end catch\r supportsDnD = new Boolean ( support ) ; } // end if: first time through\r return supportsDnD . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "END 2007 - 09 - 12 Nathan Blomquist -- Linux ( KDE / Gnome ) support added . [CODESPLIT] private void makeDropTarget ( final java . io . PrintStream out , final java . awt . Component c , boolean recursive ) { // Make drop target\r final java . awt . dnd . DropTarget dt = new java . awt . dnd . DropTarget ( ) ; try { dt . addDropTargetListener ( dropListener ) ; } // end try\r catch ( java . util . TooManyListenersException e ) { e . printStackTrace ( ) ; log ( out , \"FileDrop: Drop will not work due to previous error. Do you have another listener attached?\" ) ; } // end catch\r // Listen for hierarchy changes and remove the drop target when the parent gets cleared out.\r c . addHierarchyListener ( new java . awt . event . HierarchyListener ( ) { public void hierarchyChanged ( java . awt . event . HierarchyEvent evt ) { log ( out , \"FileDrop: Hierarchy changed.\" ) ; java . awt . Component parent = c . getParent ( ) ; if ( parent == null ) { c . setDropTarget ( null ) ; log ( out , \"FileDrop: Drop target cleared from component.\" ) ; } // end if: null parent\r else { new java . awt . dnd . DropTarget ( c , dropListener ) ; log ( out , \"FileDrop: Drop target added to component.\" ) ; } // end else: parent not null\r } // end hierarchyChanged\r } ) ; // end hierarchy listener\r if ( c . getParent ( ) != null ) new java . awt . dnd . DropTarget ( c , dropListener ) ; if ( recursive && ( c instanceof java . awt . Container ) ) { // Get the container\r java . awt . Container cont = ( java . awt . Container ) c ; // Get it's components\r java . awt . Component [ ] comps = cont . getComponents ( ) ; // Set it's components as listeners also\r for ( int i = 0 ; i < comps . length ; i ++ ) makeDropTarget ( out , comps [ i ] , recursive ) ; } // end if: recursively set components as listener\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the dragged data is a file list . [CODESPLIT] private boolean isDragOk ( final java . io . PrintStream out , final java . awt . dnd . DropTargetDragEvent evt ) { boolean ok = false ; // Get data flavors being dragged\r java . awt . datatransfer . DataFlavor [ ] flavors = evt . getCurrentDataFlavors ( ) ; // See if any of the flavors are a file list\r int i = 0 ; while ( ! ok && i < flavors . length ) { // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.\r // Is the flavor a file list?\r final DataFlavor curFlavor = flavors [ i ] ; if ( curFlavor . equals ( java . awt . datatransfer . DataFlavor . javaFileListFlavor ) || curFlavor . isRepresentationClassReader ( ) ) { ok = true ; } // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.\r i ++ ; } // end while: through flavors\r // If logging is enabled, show data flavors\r if ( out != null ) { if ( flavors . length == 0 ) log ( out , \"FileDrop: no data flavors.\" ) ; for ( i = 0 ; i < flavors . length ; i ++ ) log ( out , flavors [ i ] . toString ( ) ) ; } // end if: logging enabled\r return ok ; } // end isDragOk\r /** Outputs <tt>message</tt> to <tt>out</tt> if it's not null. */ private static void log ( java . io . PrintStream out , String message ) { // Log message if requested\r if ( out != null ) out . println ( message ) ; } // end log\r /**\r\n     * Removes the drag-and-drop hooks from the component and optionally\r\n     * from the all children. You should call this if you add and remove\r\n     * components after you've set up the drag-and-drop.\r\n     * This will recursively unregister all components contained within\r\n     * <var>c</var> if <var>c</var> is a {@link java.awt.Container}.\r\n     *\r\n     * @param c The component to unregister as a drop target\r\n     * @since 1.0\r\n     */ public static boolean remove  ( java . awt . Component c ) { return remove ( null , c , true ) ; } // end remove\r /**\r\n     * Removes the drag-and-drop hooks from the component and optionally\r\n     * from the all children. You should call this if you add and remove\r\n     * components after you've set up the drag-and-drop.\r\n     *\r\n     * @param out Optional {@link java.io.PrintStream} for logging drag and drop messages\r\n     * @param c The component to unregister\r\n     * @param recursive Recursively unregister components within a container\r\n     * @since 1.0\r\n     */ public static boolean remove  ( java . io . PrintStream out , java . awt . Component c , boolean recursive ) { // Make sure we support dnd.\r if ( supportsDnD ( ) ) { log ( out , \"FileDrop: Removing drag-and-drop hooks.\" ) ; c . setDropTarget ( null ) ; if ( recursive && ( c instanceof java . awt . Container ) ) { java . awt . Component [ ] comps = ( ( java . awt . Container ) c ) . getComponents ( ) ; for ( int i = 0 ; i < comps . length ; i ++ ) remove ( out , comps [ i ] , recursive ) ; return true ; } // end if: recursive\r else return false ; } // end if: supports DnD\r else return false ; } // end remove\r /* ********  I N N E R   I N T E R F A C E   L I S T E N E R  ******** */ /**\r\n     * Implement this inner interface to listen for when files are dropped. For example\r\n     * your class declaration may begin like this:\r\n     * <code><pre>\r\n     *      public class MyClass implements FileDrop.Listener\r\n     *      ...\r\n     *      public void filesDropped( java.io.File[] files )\r\n     *      {\r\n     *          ...\r\n     *      }   // end filesDropped\r\n     *      ...\r\n     * </pre></code>\r\n     *\r\n     * @since 1.1\r\n     */ public static interface Listener { /**\r\n         * This method is called when files have been successfully dropped.\r\n         *\r\n         * @param files An array of <tt>File</tt>s that were dropped.\r\n         * @since 1.0\r\n         */ public abstract void filesDropped ( java . io . File [ ] files ) ; } // end inner-interface Listener\r /* ********  I N N E R   C L A S S  ******** */ /**\r\n     * This is the event that is passed to the\r\n     * {@link FileDropListener#filesDropped filesDropped(...)} method in\r\n     * your {@link FileDropListener} when files are dropped onto\r\n     * a registered drop target.\r\n     *\r\n     * <p>I'm releasing this code into the Public Domain. Enjoy.</p>\r\n     * \r\n     * @author  Robert Harder\r\n     * @author  rob@iharder.net\r\n     * @version 1.2\r\n     */ public static class Event extends java . util . EventObject { private java . io . File [ ] files ; /**\r\n         * Constructs an {@link Event} with the array\r\n         * of files that were dropped and the\r\n         * {@link FileDrop} that initiated the event.\r\n         *\r\n         * @param files The array of files that were dropped\r\n         * @source The event source\r\n         * @since 1.1\r\n         */ public Event ( java . io . File [ ] files , Object source ) { super ( source ) ; this . files = files ; } // end constructor\r /**\r\n         * Returns an array of files that were dropped on a\r\n         * registered drop target.\r\n         *\r\n         * @return array of files that were dropped\r\n         * @since 1.1\r\n         */ public java . io . File [ ] getFiles ( ) { return files ; } // end getFiles\r } // end inner class Event\r /* ********  I N N E R   C L A S S  ******** */ /**\r\n     * At last an easy way to encapsulate your custom objects for dragging and dropping\r\n     * in your Java programs!\r\n     * When you need to create a {@link java.awt.datatransfer.Transferable} object,\r\n     * use this class to wrap your object.\r\n     * For example:\r\n     * <pre><code>\r\n     *      ...\r\n     *      MyCoolClass myObj = new MyCoolClass();\r\n     *      Transferable xfer = new TransferableObject( myObj );\r\n     *      ...\r\n     * </code></pre>\r\n     * Or if you need to know when the data was actually dropped, like when you're\r\n     * moving data out of a list, say, you can use the {@link TransferableObject.Fetcher}\r\n     * inner class to return your object Just in Time.\r\n     * For example:\r\n     * <pre><code>\r\n     *      ...\r\n     *      final MyCoolClass myObj = new MyCoolClass();\r\n     *\r\n     *      TransferableObject.Fetcher fetcher = new TransferableObject.Fetcher()\r\n     *      {   public Object getObject(){ return myObj; }\r\n     *      }; // end fetcher\r\n     *\r\n     *      Transferable xfer = new TransferableObject( fetcher );\r\n     *      ...\r\n     * </code></pre>\r\n     *\r\n     * The {@link java.awt.datatransfer.DataFlavor} associated with \r\n     * {@link TransferableObject} has the representation class\r\n     * <tt>net.iharder.dnd.TransferableObject.class</tt> and MIME type\r\n     * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.\r\n     * This data flavor is accessible via the static\r\n     * {@link #DATA_FLAVOR} property.\r\n     *\r\n     *\r\n     * <p>I'm releasing this code into the Public Domain. Enjoy.</p>\r\n     * \r\n     * @author  Robert Harder\r\n     * @author  rob@iharder.net\r\n     * @version 1.2\r\n     */ public static class TransferableObject implements java . awt . datatransfer . Transferable { /**\r\n         * The MIME type for {@link #DATA_FLAVOR} is \r\n         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.\r\n         *\r\n         * @since 1.1\r\n         */ public final static String MIME_TYPE = \"application/x-net.iharder.dnd.TransferableObject\" ; /**\r\n         * The default {@link java.awt.datatransfer.DataFlavor} for\r\n         * {@link TransferableObject} has the representation class\r\n         * <tt>net.iharder.dnd.TransferableObject.class</tt>\r\n         * and the MIME type \r\n         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.\r\n         *\r\n         * @since 1.1\r\n         */ public final static java . awt . datatransfer . DataFlavor DATA_FLAVOR = new java . awt . datatransfer . DataFlavor ( FileDrop . TransferableObject . class , MIME_TYPE ) ; private Fetcher fetcher ; private Object data ; private java . awt . datatransfer . DataFlavor customFlavor ; /**\r\n         * Creates a new {@link TransferableObject} that wraps <var>data</var>.\r\n         * Along with the {@link #DATA_FLAVOR} associated with this class,\r\n         * this creates a custom data flavor with a representation class \r\n         * determined from <code>data.getClass()</code> and the MIME type\r\n         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.\r\n         *\r\n         * @param data The data to transfer\r\n         * @since 1.1\r\n         */ public TransferableObject ( Object data ) { this . data = data ; this . customFlavor = new java . awt . datatransfer . DataFlavor ( data . getClass ( ) , MIME_TYPE ) ; } // end constructor\r /**\r\n         * Creates a new {@link TransferableObject} that will return the\r\n         * object that is returned by <var>fetcher</var>.\r\n         * No custom data flavor is set other than the default\r\n         * {@link #DATA_FLAVOR}.\r\n         *\r\n         * @see Fetcher\r\n         * @param fetcher The {@link Fetcher} that will return the data object\r\n         * @since 1.1\r\n         */ public TransferableObject ( Fetcher fetcher ) { this . fetcher = fetcher ; } // end constructor\r /**\r\n         * Creates a new {@link TransferableObject} that will return the\r\n         * object that is returned by <var>fetcher</var>.\r\n         * Along with the {@link #DATA_FLAVOR} associated with this class,\r\n         * this creates a custom data flavor with a representation class <var>dataClass</var>\r\n         * and the MIME type\r\n         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.\r\n         *\r\n         * @see Fetcher\r\n         * @param dataClass The {@link java.lang.Class} to use in the custom data flavor\r\n         * @param fetcher The {@link Fetcher} that will return the data object\r\n         * @since 1.1\r\n         */ public TransferableObject ( Class dataClass , Fetcher fetcher ) { this . fetcher = fetcher ; this . customFlavor = new java . awt . datatransfer . DataFlavor ( dataClass , MIME_TYPE ) ; } // end constructor\r /**\r\n         * Returns the custom {@link java.awt.datatransfer.DataFlavor} associated\r\n         * with the encapsulated object or <tt>null</tt> if the {@link Fetcher}\r\n         * constructor was used without passing a {@link java.lang.Class}.\r\n         *\r\n         * @return The custom data flavor for the encapsulated object\r\n         * @since 1.1\r\n         */ public java . awt . datatransfer . DataFlavor getCustomDataFlavor ( ) { return customFlavor ; } // end getCustomDataFlavor\r /* ********  T R A N S F E R A B L E   M E T H O D S  ******** */ /**\r\n         * Returns a two- or three-element array containing first\r\n         * the custom data flavor, if one was created in the constructors,\r\n         * second the default {@link #DATA_FLAVOR} associated with\r\n         * {@link TransferableObject}, and third the\r\n         * {@link java.awt.datatransfer.DataFlavor.stringFlavor}.\r\n         *\r\n         * @return An array of supported data flavors\r\n         * @since 1.1\r\n         */ public java . awt . datatransfer . DataFlavor [ ] getTransferDataFlavors ( ) { if ( customFlavor != null ) return new java . awt . datatransfer . DataFlavor [ ] { customFlavor , DATA_FLAVOR , java . awt . datatransfer . DataFlavor . stringFlavor } ; // end flavors array\r else return new java . awt . datatransfer . DataFlavor [ ] { DATA_FLAVOR , java . awt . datatransfer . DataFlavor . stringFlavor } ; // end flavors array\r } // end getTransferDataFlavors\r /**\r\n         * Returns the data encapsulated in this {@link TransferableObject}.\r\n         * If the {@link Fetcher} constructor was used, then this is when\r\n         * the {@link Fetcher#getObject getObject()} method will be called.\r\n         * If the requested data flavor is not supported, then the\r\n         * {@link Fetcher#getObject getObject()} method will not be called.\r\n         *\r\n         * @param flavor The data flavor for the data to return\r\n         * @return The dropped data\r\n         * @since 1.1\r\n         */ public Object getTransferData ( java . awt . datatransfer . DataFlavor flavor ) throws java . awt . datatransfer . UnsupportedFlavorException , java . io . IOException { // Native object\r if ( flavor . equals ( DATA_FLAVOR ) ) return fetcher == null ? data : fetcher . getObject ( ) ; // String\r if ( flavor . equals ( java . awt . datatransfer . DataFlavor . stringFlavor ) ) return fetcher == null ? data . toString ( ) : fetcher . getObject ( ) . toString ( ) ; // We can't do anything else\r throw new java . awt . datatransfer . UnsupportedFlavorException ( flavor ) ; } // end getTransferData\r /**\r\n         * Returns <tt>true</tt> if <var>flavor</var> is one of the supported\r\n         * flavors. Flavors are supported using the <code>equals(...)</code> method.\r\n         *\r\n         * @param flavor The data flavor to check\r\n         * @return Whether or not the flavor is supported\r\n         * @since 1.1\r\n         */ public boolean isDataFlavorSupported ( java . awt . datatransfer . DataFlavor flavor ) { // Native object\r if ( flavor . equals ( DATA_FLAVOR ) ) return true ; // String\r if ( flavor . equals ( java . awt . datatransfer . DataFlavor . stringFlavor ) ) return true ; // We can't do anything else\r return false ; } // end isDataFlavorSupported\r /* ********  I N N E R   I N T E R F A C E   F E T C H E R  ******** */ /**\r\n         * Instead of passing your data directly to the {@link TransferableObject}\r\n         * constructor, you may want to know exactly when your data was received\r\n         * in case you need to remove it from its source (or do anyting else to it).\r\n         * When the {@link #getTransferData getTransferData(...)} method is called\r\n         * on the {@link TransferableObject}, the {@link Fetcher}'s\r\n         * {@link #getObject getObject()} method will be called.\r\n         *\r\n         * @author Robert Harder\r\n         * @copyright 2001\r\n         * @version 1.1\r\n         * @since 1.1\r\n         */ public static interface Fetcher { /**\r\n             * Return the object being encapsulated in the\r\n             * {@link TransferableObject}.\r\n             *\r\n             * @return The dropped object\r\n             * @since 1.1\r\n             */ public abstract Object getObject ( ) ; } // end inner interface Fetcher\r } // end class TransferableObject\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute and wait for execution to finish [CODESPLIT] public void execute ( Context context ) throws ActionExecutionException { Action action = checkNotNull ( getChild ( ) ) ; // start a timer that will set the timesup flag to true Timer timer = new Timer ( ) ; TimerTask task = new TimerTask ( ) { @ Override public void run ( ) { timesupFlag = true ; } } ; if ( timeout < Long . MAX_VALUE ) { timer . schedule ( task , timeout ) ; } ActionExecutionException exception = null ; timesupFlag = false ; stopFlag = false ; while ( ! timesupFlag && ! stopFlag ) { try { action . execute ( context ) ; return ; } catch ( ActionExecutionException e ) { exception = e ; } synchronized ( this ) { try { this . wait ( interval ) ; } catch ( InterruptedException e ) { } } } if ( timesupFlag ) { // execution does not succeed before timeout // rethrow the exception if ( exception != null ) throw exception ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sort a list of rectangles by their sizes in ascending order [CODESPLIT] static public List < Rectangle > sortBySize ( List < Rectangle > list ) { List < Rectangle > result = Lists . newArrayList ( ) ; Collections . sort ( list , new Comparator < Rectangle > ( ) { @ Override public int compare ( Rectangle r1 , Rectangle r2 ) { return ( r1 . height * r1 . width ) - ( r2 . height * r2 . width ) ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] private Action interpretAsBookmark ( Slide slide ) { SlideElement keywordElement = slide . select ( ) . isKeyword ( KeywordDictionary . BOOKMARK ) . first ( ) ; if ( keywordElement == null ) return null ; String text = keywordElement . getText ( ) ; if ( text . isEmpty ( ) ) { logger . error ( \"No name is specified for the bookmark keyword\" ) ; return null ; } slide . remove ( keywordElement ) ; BookmarkAction action = new BookmarkAction ( ) ; action . setName ( text ) ; return action ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an object where each field represents an { @link Widget } that can be found and interacted with automatically [CODESPLIT] public static < T > T create ( Class < T > classToProxy ) { if ( ! classToProxy . isAnnotationPresent ( WidgetSlide . class ) ) // path to pptx file is not specified throw new RuntimeException ( \"@Source annotation is missing in \" + classToProxy + \". Need this to know where\" + \"to read slides\" ) ; WidgetSlide source = classToProxy . getAnnotation ( WidgetSlide . class ) ; source . value ( ) ; //\t\tif (source.url().isEmpty() > 0){ SlidesReader reader = new PPTXSlidesReader ( ) ; List < Slide > slides ; //\t\tFile file = new File(source.value()); try { if ( ! source . value ( ) . isEmpty ( ) ) { slides = reader . read ( new File ( source . value ( ) ) ) ; } else if ( ! source . url ( ) . isEmpty ( ) ) { slides = reader . read ( new URL ( source . url ( ) ) ) ; } else { throw new RuntimeException ( \"@Source is not specified correctly\" ) ; } } catch ( IOException e ) { // error in reading the slides from the given source  throw new RuntimeException ( e ) ; } DefaultSlideDriver driver ; if ( slides . size ( ) == 0 ) { // there is no slide found driver = new DefaultSlideDriver ( ) ; } else { driver = new DefaultSlideDriver ( slides . get ( 0 ) ) ; } T page = instantiatePage ( driver , classToProxy ) ; initElements ( driver , page ) ; return page ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render the given template string as a string based on the parameter values associated with this context [CODESPLIT] public String render ( String templateText ) { checkNotNull ( templateText ) ; ST st = new ST ( templateText ) ; for ( Map . Entry < String , Object > e : parameters . entrySet ( ) ) { st . add ( e . getKey ( ) , e . getValue ( ) ) ; } return st . render ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the file of the slide rel for a slide number [CODESPLIT] File getSlideXMLRel ( int slideNumber ) { String filename = String . format ( \"slide%d.xml.rels\" , slideNumber ) ; return new File ( getRelationshipsDirectory ( ) , filename ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the mouse action is within the screen region range . [CODESPLIT] protected boolean inRange ( NativeMouseEvent e ) { Rectangle r = screenRegion . getBounds ( ) ; r . x += screenOffsetX ; r . y += screenOffsetY ; int x = e . getX ( ) ; int y = e . getY ( ) ; return r . contains ( x , y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "namely if they have the same x range they would intersect [CODESPLIT] public Selector overlapVerticallyWith ( final SlideElement element , final float minOverlapRatio ) { checkNotNull ( element ) ; final Rectangle r1 = element . getBounds ( ) ; r1 . x = 0 ; r1 . width = 1 ; elements = Collections2 . filter ( elements , new Predicate < SlideElement > ( ) { @ Override public boolean apply ( SlideElement e ) { if ( e == element ) { return false ; } if ( r1 . height == 0 ) { return false ; } Rectangle r2 = e . getBounds ( ) ; r2 . x = 0 ; r2 . width = 1 ; Rectangle intersection = r1 . intersection ( r2 ) ; float yOverlapRatio = 1f * intersection . height / r1 . height ; return yOverlapRatio > minOverlapRatio ; } } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void init ( ) { this . registerBeanDefinitionParser ( \"inbound-channel-adapter\" , new SnsInboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( \"outbound-channel-adapter\" , new SnsOutboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( \"outbound-gateway\" , new SnsOutboundGatewayParser ( ) ) ; this . registerBeanDefinitionParser ( \"publish-subscribe-channel\" , new SnsPublishSubscribeChannelParser ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void init ( ) { this . registerBeanDefinitionParser ( \"inbound-channel-adapter\" , new SqsInboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( \"outbound-channel-adapter\" , new SqsOutboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( \"outbound-gateway\" , new SqsOutboundGatewayParser ( ) ) ; this . registerBeanDefinitionParser ( \"channel\" , new SqsChannelParser ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new { @link BeanDefinitionBuilder } for the class { @link SqsExecutor } . Initialize the wrapped { @link SqsExecutor } with common properties . [CODESPLIT] public static BeanDefinitionBuilder getSqsExecutorBuilder ( final Element element , final ParserContext parserContext ) { Assert . notNull ( element , \"The provided element must not be null.\" ) ; Assert . notNull ( parserContext , \"The provided parserContext must not be null.\" ) ; final BeanDefinitionBuilder sqsExecutorBuilder = BeanDefinitionBuilder . genericBeanDefinition ( SqsExecutor . class ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , \"queue-name\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"queue\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"aws-credentials-provider\" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , \"receive-message-wait-timeout\" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , \"region-id\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"prefetch-count\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"message-delay\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"maximum-message-size\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"message-retention-period\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"visibility-timeout\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"aws-client-configuration\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , \"message-marshaller\" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , \"queue-url\" ) ; return sqsExecutorBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new { @link BeanDefinitionBuilder } for the class { @link SnsExecutor } . Initialize the wrapped { @link SnsExecutor } with common properties . [CODESPLIT] public static BeanDefinitionBuilder getSnsExecutorBuilder ( final Element element , final ParserContext parserContext ) { Assert . notNull ( element , \"The provided element must not be null.\" ) ; Assert . notNull ( parserContext , \"The provided parserContext must not be null.\" ) ; final BeanDefinitionBuilder snsExecutorBuilder = BeanDefinitionBuilder . genericBeanDefinition ( SnsExecutor . class ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( snsExecutorBuilder , element , \"topic-name\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , \"sns-test-proxy\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , \"aws-credentials-provider\" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( snsExecutorBuilder , element , \"region-id\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , \"aws-client-configuration\" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , \"message-marshaller\" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( snsExecutorBuilder , element , \"topic-arn\" ) ; return snsExecutorBuilder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies and sets the parameters . E . g . initializes the to be used [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . isTrue ( this . queueName != null || this . queueUrl != null , \"Either queueName or queueUrl must not be empty.\" ) ; Assert . isTrue ( queue != null || awsCredentialsProvider != null , \"Either queue or awsCredentialsProvider needs to be provided\" ) ; if ( messageMarshaller == null ) { messageMarshaller = new JsonMessageMarshaller ( ) ; } if ( queue == null ) { if ( sqsClient == null ) { if ( awsClientConfiguration == null ) { sqsClient = new AmazonSQSClient ( awsCredentialsProvider ) ; } else { sqsClient = new AmazonSQSClient ( awsCredentialsProvider , awsClientConfiguration ) ; } } if ( regionId != null ) { sqsClient . setEndpoint ( String . format ( \"sqs.%s.amazonaws.com\" , regionId ) ) ; } if ( queueName != null ) { createQueueIfNotExists ( ) ; } addPermissions ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the outbound Sqs Operation . [CODESPLIT] public Object executeOutboundOperation ( final Message < ? > message ) { try { String serializedMessage = messageMarshaller . serialize ( message ) ; if ( queue == null ) { SendMessageRequest request = new SendMessageRequest ( queueUrl , serializedMessage ) ; SendMessageResult result = sqsClient . sendMessage ( request ) ; log . debug ( \"Message sent, Id:\" + result . getMessageId ( ) ) ; } else { queue . add ( serializedMessage ) ; } } catch ( MessageMarshallerException e ) { log . error ( e . getMessage ( ) , e ) ; throw new MessagingException ( e . getMessage ( ) , e . getCause ( ) ) ; } return message . getPayload ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a retrieving ( polling ) Sqs operation . [CODESPLIT] public Message < ? > poll ( long timeout ) { Message < ? > message = null ; String payloadJSON = null ; com . amazonaws . services . sqs . model . Message qMessage = null ; int timeoutSeconds = ( timeout > 0 ? ( ( int ) ( timeout / 1000 ) ) : receiveMessageWaitTimeout ) ; destroyWaitTime = timeoutSeconds ; try { if ( queue == null ) { if ( prefetchQueue . isEmpty ( ) ) { ReceiveMessageRequest request = new ReceiveMessageRequest ( queueUrl ) . withWaitTimeSeconds ( timeoutSeconds ) . withMaxNumberOfMessages ( prefetchCount ) . withAttributeNames ( \"All\" ) ; ReceiveMessageResult result = sqsClient . receiveMessage ( request ) ; for ( com . amazonaws . services . sqs . model . Message sqsMessage : result . getMessages ( ) ) { prefetchQueue . offer ( sqsMessage ) ; } qMessage = prefetchQueue . poll ( ) ; } else { qMessage = prefetchQueue . remove ( ) ; } if ( qMessage != null ) { payloadJSON = qMessage . getBody ( ) ; // MD5 verification try { byte [ ] computedHash = Md5Utils . computeMD5Hash ( payloadJSON . getBytes ( \"UTF-8\" ) ) ; String hexDigest = new String ( Hex . encodeHex ( computedHash ) ) ; if ( ! hexDigest . equals ( qMessage . getMD5OfBody ( ) ) ) { payloadJSON = null ; // ignore this message log . warn ( \"Dropped message due to MD5 checksum failure\" ) ; } } catch ( Exception e ) { log . warn ( \"Failed to verify MD5 checksum: \" + e . getMessage ( ) , e ) ; } } } else { try { payloadJSON = queue . poll ( timeoutSeconds , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { log . warn ( e . getMessage ( ) , e ) ; } } if ( payloadJSON != null ) { JSONObject qMessageJSON = new JSONObject ( payloadJSON ) ; if ( qMessageJSON . has ( SNS_MESSAGE_KEY ) ) { // posted from SNS payloadJSON = qMessageJSON . getString ( SNS_MESSAGE_KEY ) ; // XXX: other SNS attributes? } Message < ? > packet = null ; try { packet = messageMarshaller . deserialize ( payloadJSON ) ; } catch ( MessageMarshallerException marshallingException ) { throw new MessagingException ( marshallingException . getMessage ( ) , marshallingException . getCause ( ) ) ; } MessageBuilder < ? > builder = MessageBuilder . fromMessage ( packet ) ; if ( qMessage != null ) { builder . setHeader ( SqsHeaders . MSG_RECEIPT_HANDLE , qMessage . getReceiptHandle ( ) ) ; builder . setHeader ( SqsHeaders . AWS_MESSAGE_ID , qMessage . getMessageId ( ) ) ; for ( Map . Entry < String , String > e : qMessage . getAttributes ( ) . entrySet ( ) ) { if ( e . getKey ( ) . equals ( \"ApproximateReceiveCount\" ) ) { builder . setHeader ( SqsHeaders . RECEIVE_COUNT , Integer . valueOf ( e . getValue ( ) ) ) ; } else if ( e . getKey ( ) . equals ( \"SentTimestamp\" ) ) { builder . setHeader ( SqsHeaders . SENT_AT , new Date ( Long . valueOf ( e . getValue ( ) ) ) ) ; } else if ( e . getKey ( ) . equals ( \"ApproximateFirstReceiveTimestamp\" ) ) { builder . setHeader ( SqsHeaders . FIRST_RECEIVED_AT , new Date ( Long . valueOf ( e . getValue ( ) ) ) ) ; } else if ( e . getKey ( ) . equals ( \"SenderId\" ) ) { builder . setHeader ( SqsHeaders . SENDER_AWS_ID , e . getValue ( ) ) ; } else { builder . setHeader ( e . getKey ( ) , e . getValue ( ) ) ; } } } else { builder . setHeader ( SqsHeaders . MSG_RECEIPT_HANDLE , \"\" ) ; // to satisfy test conditions } message = builder . build ( ) ; } } catch ( JSONException e ) { log . warn ( e . getMessage ( ) , e ) ; } finally { destroyWaitTime = 0 ; } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies and sets the parameters . E . g . initializes the to be used [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . isTrue ( this . topicName != null || this . topicArn != null , \"Either topicName or topicArn must not be empty.\" ) ; Assert . isTrue ( snsTestProxy != null || awsCredentialsProvider != null , \"Either snsTestProxy or awsCredentialsProvider needs to be provided\" ) ; if ( messageMarshaller == null ) { messageMarshaller = new JsonMessageMarshaller ( ) ; } if ( snsTestProxy == null ) { if ( awsClientConfiguration == null ) { client = new AmazonSNSClient ( awsCredentialsProvider ) ; } else { client = new AmazonSNSClient ( awsCredentialsProvider , awsClientConfiguration ) ; } if ( regionId != null ) { client . setEndpoint ( String . format ( \"sns.%s.amazonaws.com\" , regionId ) ) ; } if ( topicArn == null ) { createTopicIfNotExists ( ) ; } processSubscriptions ( ) ; addPermissions ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the outbound Sns Operation . [CODESPLIT] public Object executeOutboundOperation ( final Message < ? > message ) { try { String serializedMessage = messageMarshaller . serialize ( message ) ; if ( snsTestProxy == null ) { PublishRequest request = new PublishRequest ( ) ; PublishResult result = client . publish ( request . withTopicArn ( topicArn ) . withMessage ( serializedMessage ) ) ; log . debug ( \"Published message to topic: \" + result . getMessageId ( ) ) ; } else { snsTestProxy . dispatchMessage ( serializedMessage ) ; } } catch ( MessageMarshallerException e ) { log . error ( e . getMessage ( ) , e ) ; throw new MessagingException ( e . getMessage ( ) , e . getCause ( ) ) ; } return message . getPayload ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "e . g . / drivers / h2 / h2 - 1 . 3 . 162 . jar [CODESPLIT] static public String getManifestVersionNumber ( File file ) throws IOException { JarFile jar = new JarFile ( file ) ; Manifest manifest = jar . getManifest ( ) ; String versionNumber = null ; java . util . jar . Attributes attributes = manifest . getMainAttributes ( ) ; if ( attributes != null ) { Iterator it = attributes . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Attributes . Name key = ( Attributes . Name ) it . next ( ) ; String keyword = key . toString ( ) ; if ( keyword . equals ( \"Implementation-Version\" ) || keyword . equals ( \"Bundle-Version\" ) ) { versionNumber = ( String ) attributes . get ( key ) ; break ; } } } jar . close ( ) ; if ( versionNumber == null || versionNumber . equals ( \"\" ) ) { return null ; } return versionNumber ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds ( extracts if necessary ) a named executable for the runtime operating system and architecture . The executable should be a regular Java resource at the path / jne / [ os ] / [ arch ] / [ exe ] . The name of the file will be automatically adjusted for the target platform . For example on Windows to find the cat application this method will actually search for cat . exe . [CODESPLIT] synchronized static public File findExecutable ( String name , String targetName ) throws IOException { return findExecutable ( name , targetName , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds ( or extracts ) a named executable for the runtime operating system and architecture . The executable should be a regular Java resource at the path / jne / [ os ] / [ arch ] / [ exe ] . [CODESPLIT] synchronized static public File findExecutable ( String name , Options options ) throws IOException { return findExecutable ( name , null , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds ( or extracts ) a named executable for the runtime operating system and architecture . The executable should be a regular Java resource at the path / jne / [ os ] / [ arch ] / [ exe ] . [CODESPLIT] synchronized static public File findExecutable ( String name , String targetName , Options options ) throws IOException { if ( options == null ) { options = DEFAULT_OPTIONS ; } String fileName = options . createExecutableName ( name , options . getOperatingSystem ( ) ) ; String targetFileName = null ; if ( targetName != null ) { targetFileName = options . createExecutableName ( targetName , options . getOperatingSystem ( ) ) ; } // always search for specific arch first File file = find ( fileName , targetFileName , options , options . getOperatingSystem ( ) , options . getHardwareArchitecture ( ) ) ; // for x64 fallback to x86 if an exe was not found if ( file == null && options . isX32ExecutableFallback ( ) && options . getHardwareArchitecture ( ) == HardwareArchitecture . X64 ) { file = find ( fileName , targetFileName , options , options . getOperatingSystem ( ) , HardwareArchitecture . X32 ) ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as findExecutable but throws an exception if the executable was not found . [CODESPLIT] synchronized static public File requireExecutable ( String name , Options options ) throws IOException { return requireExecutable ( name , null , options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as findExecutable but throws an exception if the executable was not found . [CODESPLIT] synchronized static public File requireExecutable ( String name , String targetName , Options options ) throws IOException { File file = findExecutable ( name , targetName , options ) ; if ( file == null ) { throw new ResourceNotFoundException ( \"Resource executable \" + name + \" not found\" ) ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Loads a dynamic library . Attempts to find ( extracts if necessary ) a named library for the runtime operating system and architecture . If the library was found as a resource and / or extracted it will then be loaded via System . load () . If the library was not found as a resource this method will simply fallback to System . loadLibrary () . Thus this method should be safe as a drop - in replacement for calls to System . loadLibrary () . < / p > <p > If including the library as a Java resource the resource path will be / jne / [ os ] / [ arch ] / [ lib ] . The name of the file will be automatically adjusted for the target platform . For example on Windows to find the cat library this method will search for cat . dll . On Linux to find the cat library this method will search for libcat . so . On Mac to find the cat library this method will search for libcat . dylib . < / p > [CODESPLIT] synchronized static public void loadLibrary ( String name , Options options , Integer majorVersion ) { // search for specific library File f = null ; try { f = findLibrary ( name , options , majorVersion ) ; } catch ( Exception e ) { log . debug ( \"exception while finding library: \" + e . getMessage ( ) ) ; throw new UnsatisfiedLinkError ( \"Unable to cleanly find (or extract) library [\" + name + \"] as resource\" ) ; } // temporarily prepend library path to load library if found if ( f != null ) { // since loading of dependencies of a library cannot dynamically happen // and the user would be required to provide a valid LD_LIBRARY_PATH when // launching the java process -- we don't need to do use loadLibrary // and can just tell it to load a specific library file log . debug ( \"System.load(\" + f . getAbsolutePath ( ) + \")\" ) ; System . load ( f . getAbsolutePath ( ) ) ; } else { log . debug ( \"falling back to System.loadLibrary(\" + name + \")\" ) ; // fallback to java method System . loadLibrary ( name ) ; } log . debug ( \"library [\" + name + \"] loaded!\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds ( or extracts ) a named file . Will first attempt to locate the file for the runtime operating system and architecture then fallback to just the runtime operating system and finally fallback to the resource prefix . For example a file named resource . txt running on a JVM on x64 linux would search the following 3 resource paths : [CODESPLIT] synchronized static public File findFile ( String name , Options options ) throws IOException { if ( options == null ) { options = DEFAULT_OPTIONS ; } // 1. try with os & arch File file = JNE . find ( name , name , options , options . getOperatingSystem ( ) , options . getHardwareArchitecture ( ) ) ; // 2. try with os & any arch if ( file == null ) { file = JNE . find ( name , name , options , options . getOperatingSystem ( ) , HardwareArchitecture . ANY ) ; } // 3. try with os & any arch if ( file == null ) { file = JNE . find ( name , name , options , OperatingSystem . ANY , HardwareArchitecture . ANY ) ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as findFile but throws an exception if the file was not found . [CODESPLIT] synchronized static public File requireFile ( String name , Options options ) throws IOException { File file = findFile ( name , options ) ; if ( file == null ) { throw new ResourceNotFoundException ( \"Resource file \" + name + \" not found\" ) ; } return file ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Underlying method used by findExecutable and loadLibrary to find and extract executables as needed . Although public it s NOT recommended to use this method unless you know what you re doing . [CODESPLIT] synchronized static public File find ( String fileName , String targetFileName , Options options , OperatingSystem os , HardwareArchitecture arch ) throws IOException { if ( options == null ) { options = DEFAULT_OPTIONS ; } if ( os == null || os == OperatingSystem . UNKNOWN ) { throw new ExtractException ( \"Unable to detect operating system (e.g. Windows)\" ) ; } if ( arch == null || arch == HardwareArchitecture . UNKNOWN ) { throw new ExtractException ( \"Unable to detect hardware architecture (e.g. x86)\" ) ; } if ( targetFileName == null ) { targetFileName = fileName ; } log . debug ( \"finding fileName [\" + fileName + \"] targetFileName [\" + targetFileName + \"] os [\" + os + \"] arch [\" + arch + \"]...\" ) ; //String resourcePath = options.getResourcePrefix() + \"/\" + os.name().toLowerCase() + \"/\" + arch.name().toLowerCase() + \"/\" + name; String resourcePath = options . createResourcePath ( os , arch , fileName ) ; log . debug ( \"finding resource [\" + resourcePath + \"]\" ) ; URL url = JNE . class . getResource ( resourcePath ) ; if ( url == null ) { log . debug ( \"resource [\" + resourcePath + \"] not found\" ) ; return null ; } // support for \"file\" and \"jar\" log . debug ( \"resource found @ \" + url ) ; if ( url . getProtocol ( ) . equals ( \"jar\" ) ) { log . debug ( \"resource in jar; extracting file if necessary...\" ) ; // in the case of where the app specifies an extract directory and // does not request deleteOnExit we need a way to detect if the  // executables changed from the previous app run -- we do this with // a very basic \"hash\" for an extracted resource. We basically combine // the path of the jar and manifest version of when the exe was extracted String versionHash = getJarVersionHashForResource ( url ) ; log . debug ( \"version hash [\" + versionHash + \"]\" ) ; // where should we extract the executable? File d = options . getExtractDir ( ) ; if ( d == null ) { d = getOrCreateTempDirectory ( options . isCleanupExtracted ( ) ) ; } else { // does the extract dir exist? if ( ! d . exists ( ) ) { d . mkdirs ( ) ; } if ( ! d . isDirectory ( ) ) { throw new ExtractException ( \"Extract dir [\" + d + \"] is not a directory\" ) ; } } log . debug ( \"using dir [\" + d + \"]\" ) ; // create both target exe and hash files File exeFile = new File ( d , targetFileName ) ; File exeHashFile = new File ( exeFile . getAbsolutePath ( ) + \".hash\" ) ; // if file already exists verify its hash if ( exeFile . exists ( ) ) { log . debug ( \"file already exists; verifying if hash matches\" ) ; // verify the version hash still matches if ( ! exeHashFile . exists ( ) ) { // hash file missing -- we will force a new extract to be safe exeFile . delete ( ) ; } else { // hash file exists, verify it matches what we expect String existingHash = readFileToString ( exeHashFile ) ; if ( existingHash == null || ! existingHash . equals ( versionHash ) ) { log . debug ( \"hash mismatch; deleting files; will freshly extract file\" ) ; // hash mismatch -- will force an overwrite of both files exeFile . delete ( ) ; exeHashFile . delete ( ) ; } else { log . debug ( \"hash matches; will use existing file\" ) ; // hash match (exeFile and exeHashFile are both perrrrfect) //System.out.println(\"exe already extracted AND hash matched -- reusing same exe\"); return exeFile ; } } } // does exe already exist? (previously extracted) if ( ! exeFile . exists ( ) ) { try { log . debug ( \"extracting [\" + url + \"] to [\" + exeFile + \"]...\" ) ; extractTo ( url , exeFile ) ; // set file to \"executable\" log . debug ( \"setting to executable\" ) ; exeFile . setExecutable ( true ) ; // create corrosponding hash file log . debug ( \"writing hash file\" ) ; writeStringToFile ( exeHashFile , versionHash ) ; // schedule files for deletion? if ( options . isCleanupExtracted ( ) ) { log . debug ( \"scheduling file and hash for delete on exit\" ) ; exeFile . deleteOnExit ( ) ; exeHashFile . deleteOnExit ( ) ; } } catch ( IOException e ) { log . debug ( \"failed to extract file\" ) ; throw new ExtractException ( \"Unable to cleanly extract executable from jar\" , e ) ; } } log . debug ( \"returning [\" + exeFile + \"]\" ) ; return exeFile ; } else if ( url . getProtocol ( ) . equals ( \"file\" ) ) { log . debug ( \"resource in file\" ) ; try { File exeFile = new File ( url . toURI ( ) ) ; if ( ! exeFile . canExecute ( ) ) { log . debug ( \"setting file to executable\" ) ; if ( ! exeFile . setExecutable ( true ) ) { log . debug ( \"unable to cleanly set file to executable\" ) ; throw new ExtractException ( \"Executable was found but it cannot be set to execute [\" + exeFile . getAbsolutePath ( ) + \"]\" ) ; } } log . debug ( \"returning [\" + exeFile + \"]\" ) ; return exeFile ; } catch ( URISyntaxException e ) { log . debug ( \"uri syntax error\" ) ; throw new ExtractException ( \"Unable to create executable file from uri\" , e ) ; } } else { throw new ExtractException ( \"Unsupported executable resource protocol [\" + url . getProtocol ( ) + \"]\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to create a temporary directory that did not exist previously . [CODESPLIT] static private File getOrCreateTempDirectory ( boolean deleteOnExit ) throws ExtractException { // return the single instance if already created if ( ( TEMP_DIRECTORY != null ) && TEMP_DIRECTORY . exists ( ) ) { return TEMP_DIRECTORY ; } // use jvm supplied temp directory in case multiple jvms compete //        try { //            Path tempDirectory = Files.createTempDirectory(\"jne.\"); //            File tempDirectoryAsFile = tempDirectory.toFile(); //            if (deleteOnExit) { //                tempDirectoryAsFile.deleteOnExit(); //            } //            return tempDirectoryAsFile; //        } catch (IOException e) { //            throw new ExtractException(\"Unable to create temporary dir\", e); //        } // use totally unique name to avoid race conditions try { Path baseDir = Paths . get ( System . getProperty ( \"java.io.tmpdir\" ) ) ; Path tempDirectory = baseDir . resolve ( \"jne.\" + UUID . randomUUID ( ) . toString ( ) ) ; Files . createDirectories ( tempDirectory ) ; File tempDirectoryAsFile = tempDirectory . toFile ( ) ; if ( deleteOnExit ) { tempDirectoryAsFile . deleteOnExit ( ) ; } // save temp directory so its only exactracted once TEMP_DIRECTORY = tempDirectoryAsFile ; return TEMP_DIRECTORY ; } catch ( IOException e ) { throw new ExtractException ( \"Unable to create temporary dir\" , e ) ; } //        File baseDir = new File(System.getProperty(\"java.io.tmpdir\")); //        String baseName = System.currentTimeMillis() + \"-\"; // //        for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) { //            File d = new File(baseDir, baseName + counter); //            if (d.mkdirs()) { //                // schedule this directory to be deleted on exit //                if (deleteOnExit) { //                    d.deleteOnExit(); //                } //                tempDirectory = d; //                return d; //            } //        } // //        throw new ExtractException(\"Failed to create temporary directory within \" + TEMP_DIR_ATTEMPTS + \" attempts (tried \" + baseName + \"0 to \" + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')'); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log for a particular level using the <code > ARRAY_MARKER< / code > . [CODESPLIT] @ Override /* package private */ void log ( final LogLevel level , final String event , final String message , final String [ ] dataKeys , final Object [ ] dataValues , final Throwable throwable ) { if ( shouldLog ( level ) ) { final String [ ] augmentedDataKeys = Arrays . copyOf ( dataKeys , dataKeys . length + 2 ) ; final Object [ ] augmentedDataValues = Arrays . copyOf ( dataValues , dataValues . length + 2 ) ; augmentedDataKeys [ augmentedDataKeys . length - 2 ] = \"_skipped\" ; augmentedDataKeys [ augmentedDataKeys . length - 1 ] = \"_lastLogTime\" ; augmentedDataValues [ augmentedDataValues . length - 2 ] = _skipped . getAndSet ( 0 ) ; augmentedDataValues [ augmentedDataValues . length - 1 ] = _lastLogTime . getAndSet ( _clock . instant ( ) ) ; super . log ( level , event , message , augmentedDataKeys , augmentedDataValues , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log for a particular level using the <code > LISTS_MARKER< / code > . [CODESPLIT] @ Override /* package private */ void log ( final LogLevel level , final String event , final List < String > dataKeys , final List < Object > dataValues , final List < String > contextKeys , final List < Object > contextValues , final Throwable throwable ) { if ( shouldLog ( level ) ) { dataKeys . add ( \"_skipped\" ) ; dataKeys . add ( \"_lastLogTime\" ) ; dataValues . add ( _skipped . getAndSet ( 0 ) ) ; dataValues . add ( _lastLogTime . getAndSet ( _clock . instant ( ) ) ) ; super . log ( level , event , dataKeys , dataValues , contextKeys , contextValues , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct an immutable map from one key - value pair . Although this is more convenient than the static factory methods this method does not capture the instance being logged . [CODESPLIT] public static LogValueMap of ( final String k1 , final Object v1 ) { return builder ( ) . put ( k1 , v1 ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CHECKSTYLE . OFF : ParameterNumber - Provided for compatibility wth ImmutableMap . of [CODESPLIT] public static LogValueMap of ( final String k1 , final Object v1 , final String k2 , final Object v2 , final String k3 , final Object v3 , final String k4 , final Object v4 , final String k5 , final Object v5 ) { return builder ( ) . put ( k1 , v1 ) . put ( k2 , v2 ) . put ( k3 , v3 ) . put ( k4 , v4 ) . put ( k5 , v5 ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new log event at the trace level . The provided <code > Consumer< / code > populates a <code > DeferredLogBuilder< / code > to define the log event . The consumer may not be invoked if it is not necessary . Therefore it is important not to include side - effects in the provided <code > Consumer< / code > . [CODESPLIT] public void trace ( final Consumer < DeferredLogBuilder > consumer ) { if ( _slf4jLogger . isTraceEnabled ( ) ) { final LogBuilder logBuilder = new DefaultLogBuilder ( this , LogLevel . TRACE ) ; consumer . accept ( logBuilder ) ; logBuilder . log ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the trace level . Default values are used for all other parameters . [CODESPLIT] public void trace ( @ Nullable final String message ) { log ( LogLevel . TRACE , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with a <code > Throwable< / code > at the trace level . Default values are used for all other parameters . [CODESPLIT] public void trace ( @ Nullable final String message , @ Nullable final Throwable throwable ) { log ( LogLevel . TRACE , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event at the trace level . Default values are used for all other parameters . [CODESPLIT] public void trace ( @ Nullable final String event , @ Nullable final String message ) { log ( LogLevel . TRACE , event , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the trace level . [CODESPLIT] public void trace ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Map < String , Object > data , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isTraceEnabled ( ) ) { LogLevel . TRACE . log ( getSlf4jLogger ( ) , event , createKeysFromCollection ( data == null ? Collections . emptyList ( ) : data . keySet ( ) , MESSAGE_DATA_KEY ) , createValuesFromCollection ( data == null ? Collections . emptyList ( ) : data . values ( ) , message ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the trace level . [CODESPLIT] public void trace ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String [ ] dataKeys , @ Nullable final Object ... dataValues ) { final Throwable throwable = extractThrowable ( dataKeys , dataValues ) ; log ( LogLevel . TRACE , event , message , dataKeys , chompArray ( dataValues , throwable == null ? 0 : 1 ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs and a <code > Throwable< / code > at the trace level . This method is provided only for efficiency over the var - args method above as it avoids an array creation during invocation . [CODESPLIT] public void trace ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String dataKey1 , @ Nullable final Object dataValue1 , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isTraceEnabled ( ) ) { LogLevel . TRACE . log ( getSlf4jLogger ( ) , event , createKeysFromArgs ( MESSAGE_DATA_KEY , dataKey1 ) , createValuesFromArgs ( message , dataValue1 ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new log event at the debug level . The provided <code > Consumer< / code > populates a <code > DeferredLogBuilder< / code > to define the log event . The consumer may not be invoked if it is not necessary . Therefore it is important not to include side - effects in the provided <code > Consumer< / code > . [CODESPLIT] public void debug ( final Consumer < DeferredLogBuilder > consumer ) { if ( _slf4jLogger . isDebugEnabled ( ) ) { final LogBuilder logBuilder = new DefaultLogBuilder ( this , LogLevel . DEBUG ) ; consumer . accept ( logBuilder ) ; logBuilder . log ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the debug level . Default values are used for all other parameters . [CODESPLIT] public void debug ( @ Nullable final String message ) { log ( LogLevel . DEBUG , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with a <code > Throwable< / code > at the debug level . Default values are used for all other parameters . [CODESPLIT] public void debug ( @ Nullable final String message , @ Nullable final Throwable throwable ) { log ( LogLevel . DEBUG , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event at the debug level . Default values are used for all other parameters . [CODESPLIT] public void debug ( @ Nullable final String event , @ Nullable final String message ) { log ( LogLevel . DEBUG , event , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the debug level . [CODESPLIT] public void debug ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Map < String , Object > data , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isDebugEnabled ( ) ) { LogLevel . DEBUG . log ( getSlf4jLogger ( ) , event , createKeysFromCollection ( data == null ? Collections . emptyList ( ) : data . keySet ( ) , MESSAGE_DATA_KEY ) , createValuesFromCollection ( data == null ? Collections . emptyList ( ) : data . values ( ) , message ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the debug level . [CODESPLIT] public void debug ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String [ ] dataKeys , @ Nullable final Object ... dataValues ) { final Throwable throwable = extractThrowable ( dataKeys , dataValues ) ; log ( LogLevel . DEBUG , event , message , dataKeys , chompArray ( dataValues , throwable == null ? 0 : 1 ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs and a <code > Throwable< / code > at the debug level . This method is provided only for efficiency over the var - args method above as it avoids an array creation during invocation . [CODESPLIT] public void debug ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String dataKey1 , @ Nullable final Object dataValue1 , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isDebugEnabled ( ) ) { LogLevel . DEBUG . log ( getSlf4jLogger ( ) , event , createKeysFromArgs ( MESSAGE_DATA_KEY , dataKey1 ) , createValuesFromArgs ( message , dataValue1 ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new log event at the info level . The provided <code > Consumer< / code > populates a <code > DeferredLogBuilder< / code > to define the log event . The consumer may not be invoked if it is not necessary . Therefore it is important not to include side - effects in the provided <code > Consumer< / code > . [CODESPLIT] public void info ( final Consumer < DeferredLogBuilder > consumer ) { if ( _slf4jLogger . isInfoEnabled ( ) ) { final LogBuilder logBuilder = new DefaultLogBuilder ( this , LogLevel . INFO ) ; consumer . accept ( logBuilder ) ; logBuilder . log ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the info level . Default values are used for all other parameters . [CODESPLIT] public void info ( @ Nullable final String message ) { log ( LogLevel . INFO , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event at the info level . Default values are used for all other parameters . [CODESPLIT] public void info ( @ Nullable final String event , @ Nullable final String message ) { log ( LogLevel . INFO , event , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with a <code > Throwable< / code > at the info level . Default values are used for all other parameters . [CODESPLIT] public void info ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Throwable throwable ) { log ( LogLevel . INFO , event , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the info level . [CODESPLIT] public void info ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Map < String , Object > data , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isInfoEnabled ( ) ) { LogLevel . INFO . log ( getSlf4jLogger ( ) , event , createKeysFromCollection ( data == null ? Collections . emptyList ( ) : data . keySet ( ) , MESSAGE_DATA_KEY ) , createValuesFromCollection ( data == null ? Collections . emptyList ( ) : data . values ( ) , message ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the info level . [CODESPLIT] public void info ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String [ ] dataKeys , @ Nullable final Object ... dataValues ) { final Throwable throwable = extractThrowable ( dataKeys , dataValues ) ; log ( LogLevel . INFO , event , message , dataKeys , chompArray ( dataValues , throwable == null ? 0 : 1 ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the info level . This method is provided only for efficiency over the var - args method above as it avoids an array creation during invocation . [CODESPLIT] public void info ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String dataKey1 , @ Nullable final String dataKey2 , @ Nullable final Object dataValue1 , @ Nullable final Object dataValue2 ) { info ( event , message , dataKey1 , dataKey2 , dataValue1 , dataValue2 , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs and a <code > Throwable< / code > at the info level . This method is provided only for efficiency over the var - args method above as it avoids an array creation during invocation . [CODESPLIT] public void info ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String dataKey1 , @ Nullable final String dataKey2 , @ Nullable final Object dataValue1 , @ Nullable final Object dataValue2 , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isInfoEnabled ( ) ) { LogLevel . INFO . log ( getSlf4jLogger ( ) , event , createKeysFromArgs ( MESSAGE_DATA_KEY , dataKey1 , dataKey2 ) , createValuesFromArgs ( message , dataValue1 , dataValue2 ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new log event at the warn level . The provided <code > Consumer< / code > populates a <code > DeferredLogBuilder< / code > to define the log event . The consumer may not be invoked if it is not necessary . Therefore it is important not to include side - effects in the provided <code > Consumer< / code > . [CODESPLIT] public void warn ( final Consumer < DeferredLogBuilder > consumer ) { if ( _slf4jLogger . isWarnEnabled ( ) ) { final LogBuilder logBuilder = new DefaultLogBuilder ( this , LogLevel . WARN ) ; consumer . accept ( logBuilder ) ; logBuilder . log ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the warn level . Default values are used for all other parameters . [CODESPLIT] public void warn ( @ Nullable final String message ) { log ( LogLevel . WARN , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event at the warn level . Default values are used for all other parameters . [CODESPLIT] public void warn ( @ Nullable final String event , @ Nullable final String message ) { log ( LogLevel . WARN , event , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with a <code > Throwable< / code > at the warn level . Default values are used for all other parameters . [CODESPLIT] public void warn ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Throwable throwable ) { log ( LogLevel . WARN , event , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the warn level . [CODESPLIT] public void warn ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Map < String , Object > data ) { warn ( event , message , data , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the warn level . [CODESPLIT] public void warn ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Map < String , Object > data , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isWarnEnabled ( ) ) { LogLevel . WARN . log ( getSlf4jLogger ( ) , event , createKeysFromCollection ( data == null ? Collections . emptyList ( ) : data . keySet ( ) , MESSAGE_DATA_KEY ) , createValuesFromCollection ( data == null ? Collections . emptyList ( ) : data . values ( ) , message ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the warn level . [CODESPLIT] public void warn ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String [ ] dataKeys , @ Nullable final Object ... dataValues ) { final Throwable throwable = extractThrowable ( dataKeys , dataValues ) ; log ( LogLevel . WARN , event , message , dataKeys , chompArray ( dataValues , throwable == null ? 0 : 1 ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs and a <code > Throwable< / code > at the warn level . This method is provided only for efficiency over the var - args method above as it avoids an array creation during invocation . [CODESPLIT] public void warn ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String dataKey1 , @ Nullable final String dataKey2 , @ Nullable final Object dataValue1 , @ Nullable final Object dataValue2 , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isWarnEnabled ( ) ) { LogLevel . WARN . log ( getSlf4jLogger ( ) , event , createKeysFromArgs ( MESSAGE_DATA_KEY , dataKey1 , dataKey2 ) , createValuesFromArgs ( message , dataValue1 , dataValue2 ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new log event at the error level . The provided <code > Consumer< / code > populates a <code > DeferredLogBuilder< / code > to define the log event . The consumer may not be invoked if it is not necessary . Therefore it is important not to include side - effects in the provided <code > Consumer< / code > . [CODESPLIT] public void error ( final Consumer < DeferredLogBuilder > consumer ) { if ( _slf4jLogger . isErrorEnabled ( ) ) { final LogBuilder logBuilder = new DefaultLogBuilder ( this , LogLevel . ERROR ) ; consumer . accept ( logBuilder ) ; logBuilder . log ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the error level . Default values are used for all other parameters . [CODESPLIT] public void error ( @ Nullable final String message ) { log ( LogLevel . ERROR , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message with a <code > Throwable< / code > at the error level . Default values are used for all other parameters . [CODESPLIT] public void error ( @ Nullable final String message , @ Nullable final Throwable throwable ) { log ( LogLevel . ERROR , DEFAULT_EVENT , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event at the error level . Default values are used for all other parameters . [CODESPLIT] public void error ( @ Nullable final String event , @ Nullable final String message ) { log ( LogLevel . ERROR , event , message , EMPTY_STRING_ARRAY , EMPTY_OBJECT_ARRAY , DEFAULT_THROWABLE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the error level . [CODESPLIT] public void error ( @ Nullable final String event , @ Nullable final String message , @ Nullable final Map < String , Object > data , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isErrorEnabled ( ) ) { LogLevel . ERROR . log ( getSlf4jLogger ( ) , event , createKeysFromCollection ( data == null ? Collections . emptyList ( ) : data . keySet ( ) , MESSAGE_DATA_KEY ) , createValuesFromCollection ( data == null ? Collections . emptyList ( ) : data . values ( ) , message ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs at the error level . [CODESPLIT] public void error ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String [ ] dataKeys , @ Nullable final Object ... dataValues ) { final Throwable throwable = extractThrowable ( dataKeys , dataValues ) ; log ( LogLevel . ERROR , event , message , dataKeys , chompArray ( dataValues , throwable == null ? 0 : 1 ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message for a canonical event with supporting key - value pairs and a <code > Throwable< / code > at the error level . This method is provided only for efficiency over the var - args method above as it avoids an array creation during invocation . [CODESPLIT] public void error ( @ Nullable final String event , @ Nullable final String message , @ Nullable final String dataKey1 , @ Nullable final Object dataValue1 , @ Nullable final Throwable throwable ) { if ( getSlf4jLogger ( ) . isErrorEnabled ( ) ) { LogLevel . ERROR . log ( getSlf4jLogger ( ) , event , createKeysFromArgs ( MESSAGE_DATA_KEY , dataKey1 ) , createValuesFromArgs ( message , dataValue1 ) , throwable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] void log ( final LogLevel level , @ Nullable final String event , @ Nullable final String message , @ Nullable final String [ ] dataKeys , @ Nullable final Object [ ] dataValues , @ Nullable final Throwable throwable ) { level . log ( getSlf4jLogger ( ) , event , createKeysFromArray ( dataKeys , MESSAGE_DATA_KEY ) , createValuesFromArray ( dataValues , message ) , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] void log ( final LogLevel level , @ Nullable final String event , final List < String > dataKeys , final List < Object > dataValues , final List < String > contextKeys , final List < Object > contextValues , @ Nullable final Throwable throwable ) { level . log ( getSlf4jLogger ( ) , event , dataKeys , dataValues , contextKeys , contextValues , throwable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static @ Nullable String [ ] createKeysFromCollection ( @ Nullable final Collection < String > collection , @ Nullable final String ... keys ) { if ( isNullOrEmpty ( keys ) ) { return collection == null ? null : collection . toArray ( new String [ collection . size ( ) ] ) ; } if ( isNullOrEmpty ( collection ) ) { return keys ; } final String [ ] combined = new String [ collection . size ( ) + keys . length ] ; for ( int i = 0 ; i < keys . length ; ++ i ) { combined [ i ] = keys [ i ] ; } int i = 0 ; for ( final String item : collection ) { combined [ keys . length + i ++ ] = item ; } return combined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static @ Nullable Object [ ] createValuesFromCollection ( @ Nullable final Collection < Object > collection , @ Nullable final Object ... values ) { if ( isNullOrEmpty ( values ) ) { return collection == null ? null : collection . toArray ( new Object [ collection . size ( ) ] ) ; } if ( isNullOrEmpty ( collection ) ) { return values ; } final Object [ ] combined = new Object [ collection . size ( ) + values . length ] ; for ( int i = 0 ; i < values . length ; ++ i ) { combined [ i ] = values [ i ] ; } int i = 0 ; for ( final Object item : collection ) { combined [ values . length + i ++ ] = item ; } return combined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static @ Nullable String [ ] createKeysFromArray ( @ Nullable final String [ ] array , @ Nullable final String ... keys ) { if ( isNullOrEmpty ( keys ) ) { return array ; } if ( isNullOrEmpty ( array ) ) { return keys ; } final String [ ] combined = Arrays . copyOf ( keys , array . length + keys . length ) ; for ( int i = 0 ; i < array . length ; ++ i ) { combined [ keys . length + i ] = array [ i ] ; } return combined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static @ Nullable Object [ ] createValuesFromArray ( @ Nullable final Object [ ] array , @ Nullable final Object ... values ) { if ( isNullOrEmpty ( values ) ) { return array ; } if ( isNullOrEmpty ( array ) ) { return values ; } final Object [ ] combined = Arrays . copyOf ( values , array . length + values . length ) ; for ( int i = 0 ; i < array . length ; ++ i ) { combined [ values . length + i ] = array [ i ] ; } return combined ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static @ Nullable Throwable extractThrowable ( @ Nullable final String [ ] keys , @ Nullable final Object [ ] values ) { final int keyLength = keys == null ? 0 : keys . length ; if ( values != null && values . length == keyLength + 1 ) { final int throwableIndex = values . length - 1 ; if ( values [ throwableIndex ] instanceof Throwable ) { return ( Throwable ) values [ throwableIndex ] ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static @ Nullable Object [ ] chompArray ( @ Nullable final Object [ ] in , final int count ) { if ( count == 0 || in == null ) { return in ; } return Arrays . copyOf ( in , in . length - count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize an event . [CODESPLIT] public String serialize ( final ILoggingEvent event , final String eventName , @ Nullable final Map < String , ? extends Object > map ) throws Exception { final StringWriter jsonWriter = new StringWriter ( ) ; final JsonGenerator jsonGenerator = _jsonFactory . createGenerator ( jsonWriter ) ; // Start wrapper StenoSerializationHelper . startStenoWrapper ( event , eventName , jsonGenerator , _objectMapper ) ; // Write event data jsonGenerator . writeObjectFieldStart ( \"data\" ) ; if ( map != null ) { for ( final Map . Entry < String , ? extends Object > entry : map . entrySet ( ) ) { if ( StenoSerializationHelper . isSimpleType ( entry . getValue ( ) ) ) { jsonGenerator . writeObjectField ( entry . getKey ( ) , entry . getValue ( ) ) ; } else { jsonGenerator . writeFieldName ( entry . getKey ( ) ) ; _objectMapper . writeValue ( jsonGenerator , entry . getValue ( ) ) ; } } } jsonGenerator . writeEndObject ( ) ; // End 'data' field // Output throwable StenoSerializationHelper . writeThrowable ( event . getThrowableProxy ( ) , jsonGenerator , _objectMapper ) ; // End wrapper StenoSerializationHelper . endStenoWrapper ( event , eventName , jsonGenerator , _objectMapper , _encoder ) ; return jsonWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize an event . [CODESPLIT] public String serialize ( final ILoggingEvent event , final String eventName ) throws Exception { final StringWriter jsonWriter = new StringWriter ( ) ; final JsonGenerator jsonGenerator = _jsonFactory . createGenerator ( jsonWriter ) ; // Start wrapper StenoSerializationHelper . startStenoWrapper ( event , eventName , jsonGenerator , _objectMapper ) ; // Write event data jsonGenerator . writeObjectFieldStart ( \"data\" ) ; jsonGenerator . writeObjectField ( \"message\" , event . getFormattedMessage ( ) ) ; jsonGenerator . writeEndObject ( ) ; // End 'data' field // Output throwable StenoSerializationHelper . writeThrowable ( event . getThrowableProxy ( ) , jsonGenerator , _objectMapper ) ; // End wrapper StenoSerializationHelper . endStenoWrapper ( event , eventName , jsonGenerator , _objectMapper , _encoder ) ; return jsonWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Before outputting the message inject additional context . [CODESPLIT] @ Before ( \"call(* com.arpnetworking.steno.LogBuilder.log())\" ) public void addToContextLineAndMethod ( final JoinPoint joinPoint ) { final SourceLocation sourceLocation = joinPoint . getSourceLocation ( ) ; final LogBuilder targetLogBuilder = ( LogBuilder ) joinPoint . getTarget ( ) ; targetLogBuilder . addContext ( \"line\" , String . valueOf ( sourceLocation . getLine ( ) ) ) ; targetLogBuilder . addContext ( \"file\" , sourceLocation . getFileName ( ) ) ; targetLogBuilder . addContext ( \"class\" , sourceLocation . getWithinType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start writing the Steno JSON wrapper . [CODESPLIT] public static void startStenoWrapper ( final ILoggingEvent event , final String eventName , final JsonGenerator jsonGenerator , final ObjectMapper objectMapper ) throws IOException { final StenoSerializationHelper . StenoLevel level = StenoSerializationHelper . StenoLevel . findByLogbackLevel ( event . getLevel ( ) ) ; jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeObjectField ( \"time\" , ISO_DATE_TIME_FORMATTER . format ( Instant . ofEpochMilli ( event . getTimeStamp ( ) ) ) ) ; jsonGenerator . writeObjectField ( \"name\" , eventName ) ; jsonGenerator . writeObjectField ( \"level\" , level . name ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete writing the Steno JSON wrapper . [CODESPLIT] public static void endStenoWrapper ( final ILoggingEvent event , final String eventName , final JsonGenerator jsonGenerator , final ObjectMapper objectMapper , final StenoEncoder encoder ) throws IOException { endStenoWrapper ( event , eventName , Collections . emptyList ( ) , Collections . emptyList ( ) , jsonGenerator , objectMapper , encoder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Complete writing the Steno JSON wrapper . [CODESPLIT] public static void endStenoWrapper ( final ILoggingEvent event , final String eventName , @ Nullable final List < String > contextKeys , @ Nullable final List < Object > contextValues , final JsonGenerator jsonGenerator , final ObjectMapper objectMapper , final StenoEncoder encoder ) throws IOException { jsonGenerator . writeFieldName ( \"context\" ) ; objectMapper . writeValue ( jsonGenerator , StenoSerializationHelper . createContext ( encoder , event , objectMapper , contextKeys , contextValues ) ) ; jsonGenerator . writeObjectField ( \"id\" , StenoSerializationHelper . createId ( ) ) ; jsonGenerator . writeObjectField ( \"version\" , \"0\" ) ; jsonGenerator . writeEndObject ( ) ; // End log message jsonGenerator . writeRaw ( ' ' ) ; jsonGenerator . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write specified key - value pairs into the current block . [CODESPLIT] public static void writeKeyValuePairs ( @ Nullable final List < String > keys , @ Nullable final List < Object > values , final JsonGenerator jsonGenerator , final ObjectMapper objectMapper , final StenoEncoder encoder ) throws IOException { if ( keys != null ) { final int contextValuesLength = values == null ? 0 : values . size ( ) ; for ( int i = 0 ; i < keys . size ( ) ; ++ i ) { final String key = keys . get ( i ) ; if ( i >= contextValuesLength ) { jsonGenerator . writeObjectField ( key , null ) ; } else { final Object value = values . get ( i ) ; if ( isSimpleType ( value ) ) { jsonGenerator . writeObjectField ( key , value ) ; } else { jsonGenerator . writeFieldName ( key ) ; objectMapper . writeValue ( jsonGenerator , value ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write a <code > Throwable< / code > via <code > IThrowableProxy< / code > as JSON . [CODESPLIT] public static void writeThrowable ( final IThrowableProxy throwableProxy , final JsonGenerator jsonGenerator , final ObjectMapper objectMapper ) throws IOException { if ( throwableProxy != null ) { jsonGenerator . writeObjectFieldStart ( \"exception\" ) ; serializeThrowable ( throwableProxy , jsonGenerator , objectMapper ) ; jsonGenerator . writeEndObject ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function assumes the field object has already been started for this throwable this only fills in the fields in the exception or equivalent object and does not create the field in the containing object . [CODESPLIT] public static void serializeThrowable ( final IThrowableProxy throwableProxy , final JsonGenerator jsonGenerator , final ObjectMapper objectMapper ) throws IOException { jsonGenerator . writeStringField ( \"type\" , throwableProxy . getClassName ( ) ) ; jsonGenerator . writeStringField ( \"message\" , throwableProxy . getMessage ( ) ) ; jsonGenerator . writeArrayFieldStart ( \"backtrace\" ) ; for ( final StackTraceElementProxy ste : throwableProxy . getStackTraceElementProxyArray ( ) ) { jsonGenerator . writeString ( ste . toString ( ) ) ; } jsonGenerator . writeEndArray ( ) ; jsonGenerator . writeObjectFieldStart ( \"data\" ) ; if ( throwableProxy instanceof ThrowableProxy ) { final JsonNode jsonNode = objectMapper . valueToTree ( ( ( ThrowableProxy ) throwableProxy ) . getThrowable ( ) ) ; for ( final Iterator < Map . Entry < String , JsonNode > > iterator = jsonNode . fields ( ) ; iterator . hasNext ( ) ; ) { final Map . Entry < String , JsonNode > field = iterator . next ( ) ; jsonGenerator . writeFieldName ( field . getKey ( ) ) ; objectMapper . writeValue ( jsonGenerator , field . getValue ( ) ) ; } } // Although Throwable has a final getSuppressed which cannot return a null array, the // proxy in Logback provides no such guarantees. if ( throwableProxy . getSuppressed ( ) != null && throwableProxy . getSuppressed ( ) . length > 0 ) { jsonGenerator . writeArrayFieldStart ( \"suppressed\" ) ; for ( final IThrowableProxy suppressed : throwableProxy . getSuppressed ( ) ) { jsonGenerator . writeStartObject ( ) ; serializeThrowable ( suppressed , jsonGenerator , objectMapper ) ; jsonGenerator . writeEndObject ( ) ; } jsonGenerator . writeEndArray ( ) ; } if ( throwableProxy . getCause ( ) != null ) { jsonGenerator . writeObjectFieldStart ( \"cause\" ) ; serializeThrowable ( throwableProxy . getCause ( ) , jsonGenerator , objectMapper ) ; jsonGenerator . writeEndObject ( ) ; } jsonGenerator . writeEndObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a context based on the <code > StenoEncoder< / code > configuration . [CODESPLIT] public static Map < String , Object > createContext ( final StenoEncoder encoder , final ILoggingEvent event , final ObjectMapper objectMapper , @ Nullable final List < String > contextKeys , @ Nullable final List < Object > contextValues ) { final Map < String , Object > context = new LinkedHashMap <> ( ) ; if ( encoder . isInjectContextHost ( ) ) { context . put ( \"host\" , StenoSerializationHelper . HOST_CONVERTER . convert ( event ) ) ; } if ( encoder . isInjectContextProcess ( ) ) { context . put ( \"processId\" , StenoSerializationHelper . PROCESS_CONVERTER . convert ( event ) ) ; } if ( encoder . isInjectContextThread ( ) ) { context . put ( \"threadId\" , StenoSerializationHelper . THREAD_CONVERTER . convert ( event ) ) ; } if ( encoder . isInjectContextLogger ( ) ) { if ( encoder . isCompressLoggerName ( ) ) { context . put ( \"logger\" , StenoSerializationHelper . CONDENSED_LOGGER_CONVERTER . convert ( event ) ) ; } else { context . put ( \"logger\" , StenoSerializationHelper . LOGGER_CONVERTER . convert ( event ) ) ; } } if ( encoder . isInjectContextFile ( ) ) { context . put ( \"file\" , StenoSerializationHelper . FILE_CONVERTER . convert ( event ) ) ; } if ( encoder . isInjectContextClass ( ) ) { context . put ( \"class\" , StenoSerializationHelper . CLASS_CONVERTER . convert ( event ) ) ; } if ( encoder . isInjectContextMethod ( ) ) { context . put ( \"method\" , StenoSerializationHelper . METHOD_CONVERTER . convert ( event ) ) ; } if ( encoder . isInjectContextLine ( ) ) { context . put ( \"line\" , StenoSerializationHelper . LINE_CONVERTER . convert ( event ) ) ; } final Iterator < String > injectContextMdcIterator = encoder . iteratorForInjectContextMdc ( ) ; while ( injectContextMdcIterator . hasNext ( ) ) { final String key = injectContextMdcIterator . next ( ) ; final String value = event . getMDCPropertyMap ( ) . get ( key ) ; context . put ( key , value ) ; } if ( contextKeys != null ) { final int contextValuesLength = contextValues == null ? 0 : contextValues . size ( ) ; for ( int i = 0 ; i < contextKeys . size ( ) ; ++ i ) { final String key = contextKeys . get ( i ) ; final Object value = i < contextValuesLength ? contextValues . get ( i ) : null ; context . put ( key , value ) ; } } return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if an object represents a primitive Json type . These include instances of <code > Number< / code > <code > String< / code > and <code > Boolean< / code > . [CODESPLIT] public static boolean isSimpleType ( @ Nullable final Object obj ) { if ( obj == null ) { return true ; } final Class < ? > objClass = obj . getClass ( ) ; if ( String . class . isAssignableFrom ( objClass ) ) { return true ; } if ( Number . class . isAssignableFrom ( objClass ) ) { return true ; } if ( Boolean . class . isAssignableFrom ( objClass ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a Steno <code > Logger< / code > for a context class . [CODESPLIT] public static Logger getLogger ( final Class < ? > clazz ) { return new Logger ( org . slf4j . LoggerFactory . getLogger ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a rate limited Steno <code > Logger< / code > for a context class . [CODESPLIT] public static Logger getRateLimitLogger ( final Class < ? > clazz , final Duration duration ) { return new RateLimitLogger ( org . slf4j . LoggerFactory . getLogger ( clazz ) , duration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a Steno <code > Logger< / code > for a context name . [CODESPLIT] public static Logger getLogger ( final String name ) { return new Logger ( org . slf4j . LoggerFactory . getLogger ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a rate limited Steno <code > Logger< / code > for a context name . [CODESPLIT] public static Logger getRateLimitLogger ( final String name , final Duration duration ) { return new RateLimitLogger ( org . slf4j . LoggerFactory . getLogger ( name ) , duration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a rate limited Steno <code > Logger< / code > for an already instantiated <code > org . slf4j . Logger< / code > instance . [CODESPLIT] public static Logger getRateLimitLogger ( final org . slf4j . Logger logger , final Duration duration ) { return new RateLimitLogger ( logger , duration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables / Disables redaction support when serializing complex objects . Redacted fields / properties marked with the @LogRedact annotation will be output as a string with the value { @code <REDACTED > } . [CODESPLIT] public void setRedactEnabled ( final boolean redactEnabled ) { final SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider ( ) ; if ( redactEnabled ) { simpleFilterProvider . addFilter ( RedactionFilter . REDACTION_FILTER_ID , new RedactionFilter ( ! _redactNull ) ) ; } else { simpleFilterProvider . addFilter ( RedactionFilter . REDACTION_FILTER_ID , SimpleBeanPropertyFilter . serializeAllExcept ( Collections . < String > emptySet ( ) ) ) ; } _objectMapper . setFilterProvider ( simpleFilterProvider ) ; _redactEnabled = redactEnabled ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables / Disables output of null for redacted fields when serializing complex objects . [CODESPLIT] public void setRedactNull ( final boolean redactNull ) { if ( _redactEnabled ) { final SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider ( ) ; simpleFilterProvider . addFilter ( RedactionFilter . REDACTION_FILTER_ID , new RedactionFilter ( ! redactNull ) ) ; _objectMapper . setFilterProvider ( simpleFilterProvider ) ; } _redactNull = redactNull ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a context based on the <code > KeyValueEncoder< / code > configuration . [CODESPLIT] public static Map < String , Object > createContext ( final KeyValueEncoder encoder , final ILoggingEvent event , @ Nullable final List < String > contextKeys , @ Nullable final List < Object > contextValues ) { final Map < String , Object > context = new LinkedHashMap <> ( ) ; context . put ( \"host\" , KeyValueSerializationHelper . HOST_CONVERTER . convert ( event ) ) ; context . put ( \"processId\" , KeyValueSerializationHelper . PROCESS_CONVERTER . convert ( event ) ) ; context . put ( \"threadId\" , KeyValueSerializationHelper . THREAD_CONVERTER . convert ( event ) ) ; if ( contextKeys != null ) { final int contextValuesLength = contextValues == null ? 0 : contextValues . size ( ) ; for ( int i = 0 ; i < contextKeys . size ( ) ; ++ i ) { final String key = contextKeys . get ( i ) ; final Object value = i < contextValuesLength ? contextValues . get ( i ) : null ; context . put ( key , value ) ; } } return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public byte [ ] encode ( final ILoggingEvent event ) { final Marker marker = event . getMarker ( ) ; final String name = event . getMessage ( ) ; final Object [ ] argumentArray = event . getArgumentArray ( ) ; String output ; try { output = encodeAsString ( event , marker , name , argumentArray ) ; } catch ( final EncodingException ee ) { output = encodeAsString ( event , ee ) ; } return encodeString ( output ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the <code > marker< / code > represents an array event . [CODESPLIT] protected boolean isArrayStenoEvent ( @ Nullable final Marker marker ) { return marker != null && marker . contains ( StenoMarker . ARRAY_MARKER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the <code > marker< / code > represents a JSON array event . [CODESPLIT] protected boolean isArrayJsonStenoEvent ( @ Nullable final Marker marker ) { return marker != null && marker . contains ( StenoMarker . ARRAY_JSON_MARKER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the <code > marker< / code > represents a map event . [CODESPLIT] protected boolean isMapStenoEvent ( @ Nullable final Marker marker ) { return marker != null && marker . contains ( StenoMarker . MAP_MARKER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the <code > marker< / code > represents a JSON map event . [CODESPLIT] protected boolean isMapJsonStenoEvent ( @ Nullable final Marker marker ) { return marker != null && marker . contains ( StenoMarker . MAP_JSON_MARKER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the <code > marker< / code > represents an object event . [CODESPLIT] protected boolean isObjectStenoEvent ( @ Nullable final Marker marker ) { return marker != null && marker . contains ( StenoMarker . OBJECT_MARKER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the <code > marker< / code > represents a JSON object event . [CODESPLIT] protected boolean isObjectJsonStenoEvent ( @ Nullable final Marker marker ) { return marker != null && marker . contains ( StenoMarker . OBJECT_JSON_MARKER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the <code > marker< / code > represents a lists event . [CODESPLIT] protected boolean isListsStenoEvent ( @ Nullable final Marker marker ) { return marker != null && marker . contains ( StenoMarker . LISTS_MARKER ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a Steno log compatible representation . [CODESPLIT] @ LogValue public Object toLogValue ( ) { return LogValueMapFactory . < String , Object > builder ( ) . put ( \"logBuilder\" , _logBuilder ) . put ( \"duration\" , _duration ) . put ( \"lastLogTime\" , _lastLogTime ) . put ( \"skipped\" , _skipped ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize an event . [CODESPLIT] public String serialize ( final ILoggingEvent event , final String eventName , @ Nullable final Object data ) throws Exception { final String jsonData = _objectMapper . writeValueAsString ( data ) ; return _objectAsJsonStrategy . serialize ( event , eventName , jsonData ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a format <code > String< / code > compatible with <code > MessageFormatter< / code > . [CODESPLIT] protected String buildFormatString ( @ Nullable final String name , @ Nullable final String [ ] keys ) { final String effectiveName = name == null ? _logEventName : name ; final StringWriter stringWriter = new StringWriter ( ) ; stringWriter . append ( \"name=\\\"\" ) . append ( effectiveName ) . append ( \"\\\"\" ) ; if ( keys != null && keys . length > 0 ) { for ( final String key : keys ) { stringWriter . append ( \", \" ) . append ( key ) . append ( \"=\\\"{}\\\"\" ) ; } } return stringWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escape all <code > String< / code > instances . [CODESPLIT] protected Object [ ] escapeStringValues ( final Object [ ] values ) { final Object [ ] escapedValues = new Object [ values . length ] ; for ( int i = 0 ; i < values . length ; i ++ ) { Object value = values [ i ] ; // Instance of check implies value is not null if ( value instanceof String ) { value = ( ( String ) value ) . replaceAll ( \"\\\"\" , \"\\\\\\\\\\\"\" ) ; } escapedValues [ i ] = value ; } return escapedValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] String createMessage ( final ILoggingEvent event , @ Nullable final String eventName , @ Nullable final String [ ] keys , @ Nullable final Object [ ] values ) { final String formatString = buildFormatString ( eventName , keys ) ; final LoggingEventWrapper eventWrapper = new LoggingEventWrapper ( event , formatString , values ) ; return layout . doLayout ( eventWrapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] Map < String , Object > createSafeContext ( final ILoggingEvent event ) { return createSafeContext ( event , Collections . emptyList ( ) , Collections . emptyList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] Map < String , Object > createSafeContext ( final ILoggingEvent event , @ Nullable final List < String > contextKeys , @ Nullable final List < Object > contextValues ) { return KeyValueSerializationHelper . createContext ( this , event , contextKeys , contextValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the the message formatted with arguments . Implemented as suggested in : [CODESPLIT] public String getFormattedMessage ( ) { if ( _formattedMessage != null ) { return _formattedMessage ; } if ( _argumentArray != null ) { _formattedMessage = MessageFormatter . arrayFormat ( _message , _argumentArray ) . getMessage ( ) ; } else { _formattedMessage = _message ; } return _formattedMessage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override @ Deprecated public void serializeAsField ( final Object pojo , final JsonGenerator jgen , final SerializerProvider prov , final BeanPropertyWriter writer ) throws Exception { if ( writer . getAnnotation ( LogRedact . class ) == null ) { super . serializeAsField ( pojo , jgen , prov , writer ) ; } else { // since 2.3 if ( _allowNull && writer . get ( pojo ) == null ) { super . serializeAsField ( pojo , jgen , prov , writer ) ; } else { jgen . writeStringField ( writer . getSerializedName ( ) . getValue ( ) , REDACTION_STRING ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize an event . [CODESPLIT] public String serialize ( final ILoggingEvent event , final String eventName , final String jsonData ) throws Exception { final StringWriter jsonWriter = new StringWriter ( ) ; final JsonGenerator jsonGenerator = _jsonFactory . createGenerator ( jsonWriter ) ; // Start wrapper StenoSerializationHelper . startStenoWrapper ( event , eventName , jsonGenerator , _objectMapper ) ; // Write event data jsonGenerator . writeFieldName ( \"data\" ) ; if ( jsonData == null ) { jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeEndObject ( ) ; } else { jsonGenerator . writeRawValue ( jsonData ) ; } // TODO(vkoskela): Support writing null objects as-is via configuration [ISSUE-4] // e.g. \"data\":null -- although this is not supported by the current Steno specification // Output throwable StenoSerializationHelper . writeThrowable ( event . getThrowableProxy ( ) , jsonGenerator , _objectMapper ) ; // End wrapper StenoSerializationHelper . endStenoWrapper ( event , eventName , jsonGenerator , _objectMapper , _encoder ) ; return jsonWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the relevant caller data adjusted for Steno logger wrapping . [CODESPLIT] protected StackTraceElement getCallerData ( final ILoggingEvent loggingEvent ) { final StackTraceElement [ ] callerData = loggingEvent . getCallerData ( ) ; if ( callerData != null ) { for ( int i = 0 ; i < callerData . length ; ++ i ) { final String callerClassName = callerData [ i ] . getClassName ( ) ; if ( ! callerClassName . startsWith ( STENO_CLASS_NAME_PREFIX ) ) { return callerData [ i ] ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize an event . [CODESPLIT] public String serialize ( final ILoggingEvent event , final String eventName , @ Nullable final List < String > dataKeys , @ Nullable final List < Object > dataValues , @ Nullable final List < String > contextKeys , @ Nullable final List < Object > contextValues ) throws Exception { final StringWriter jsonWriter = new StringWriter ( ) ; final JsonGenerator jsonGenerator = _jsonFactory . createGenerator ( jsonWriter ) ; // Start wrapper StenoSerializationHelper . startStenoWrapper ( event , eventName , jsonGenerator , _objectMapper ) ; // Write event data jsonGenerator . writeObjectFieldStart ( \"data\" ) ; StenoSerializationHelper . writeKeyValuePairs ( dataKeys , dataValues , jsonGenerator , _objectMapper , _encoder ) ; jsonGenerator . writeEndObject ( ) ; // End 'data' field // Output throwable StenoSerializationHelper . writeThrowable ( event . getThrowableProxy ( ) , jsonGenerator , _objectMapper ) ; // End wrapper StenoSerializationHelper . endStenoWrapper ( event , eventName , contextKeys , contextValues , jsonGenerator , _objectMapper , _encoder ) ; return jsonWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize an event . [CODESPLIT] public String serialize ( final ILoggingEvent event , final String eventName , @ Nullable final String [ ] keys , @ Nullable final Object [ ] values ) throws Exception { final StringWriter jsonWriter = new StringWriter ( ) ; final JsonGenerator jsonGenerator = _jsonFactory . createGenerator ( jsonWriter ) ; // Start wrapper StenoSerializationHelper . startStenoWrapper ( event , eventName , jsonGenerator , _objectMapper ) ; // Write event data jsonGenerator . writeObjectFieldStart ( \"data\" ) ; final int argsLength = values == null ? 0 : values . length ; if ( keys != null ) { for ( int i = 0 ; i < keys . length ; i ++ ) { if ( i >= argsLength ) { jsonGenerator . writeObjectField ( keys [ i ] , null ) ; } else if ( StenoSerializationHelper . isSimpleType ( values [ i ] ) ) { jsonGenerator . writeObjectField ( keys [ i ] , values [ i ] ) ; } else { jsonGenerator . writeFieldName ( keys [ i ] ) ; _objectMapper . writeValue ( jsonGenerator , values [ i ] ) ; } } } jsonGenerator . writeEndObject ( ) ; // End 'data' field // Output throwable StenoSerializationHelper . writeThrowable ( event . getThrowableProxy ( ) , jsonGenerator , _objectMapper ) ; // End wrapper StenoSerializationHelper . endStenoWrapper ( event , eventName , jsonGenerator , _objectMapper , _encoder ) ; return jsonWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a serialization safe context based on the <code > StenoEncoder< / code > configuration . [CODESPLIT] public static Map < String , Object > createSafeContext ( final StenoEncoder encoder , final ILoggingEvent event , final ObjectMapper objectMapper ) { return createSafeContext ( encoder , event , objectMapper , Collections . emptyList ( ) , Collections . emptyList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a serialization safe context based on the <code > StenoEncoder< / code > configuration . [CODESPLIT] public static Map < String , Object > createSafeContext ( final StenoEncoder encoder , final ILoggingEvent event , final ObjectMapper objectMapper , @ Nullable final List < String > contextKeys , @ Nullable final List < Object > contextValues ) { return StenoSerializationHelper . createContext ( encoder , event , objectMapper , contextKeys , contextValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safely serialize a value . [CODESPLIT] public static void safeEncodeValue ( final StringBuilder encoder , @ Nullable final Object value ) { if ( value == null ) { encoder . append ( \"null\" ) ; } else if ( value instanceof Map ) { safeEncodeMap ( encoder , ( Map < ? , ? > ) value ) ; } else if ( value instanceof List ) { safeEncodeList ( encoder , ( List < ? > ) value ) ; } else if ( value . getClass ( ) . isArray ( ) ) { safeEncodeArray ( encoder , value ) ; } else if ( value instanceof LogValueMapFactory . LogValueMap ) { safeEncodeLogValueMap ( encoder , ( LogValueMapFactory . LogValueMap ) value ) ; } else if ( value instanceof Throwable ) { safeEncodeThrowable ( encoder , ( Throwable ) value ) ; } else if ( StenoSerializationHelper . isSimpleType ( value ) ) { if ( value instanceof Boolean ) { encoder . append ( BooleanNode . valueOf ( ( Boolean ) value ) . toString ( ) ) ; } else if ( value instanceof Double ) { encoder . append ( DoubleNode . valueOf ( ( Double ) value ) . toString ( ) ) ; } else if ( value instanceof Float ) { encoder . append ( FloatNode . valueOf ( ( Float ) value ) . toString ( ) ) ; } else if ( value instanceof Long ) { encoder . append ( LongNode . valueOf ( ( Long ) value ) . toString ( ) ) ; } else if ( value instanceof Integer ) { encoder . append ( IntNode . valueOf ( ( Integer ) value ) . toString ( ) ) ; } else { encoder . append ( new TextNode ( value . toString ( ) ) . toString ( ) ) ; } } else { safeEncodeValue ( encoder , LogReferenceOnly . of ( value ) . toLogValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static void safeEncodeThrowable ( final StringBuilder encoder , final Throwable throwable ) { encoder . append ( \"{\\\"type\\\":\\\"\" ) . append ( throwable . getClass ( ) . getName ( ) ) . append ( \"\\\",\\\"message\\\":\" ) ; safeEncodeValue ( encoder , throwable . getMessage ( ) ) ; encoder . append ( \",\\\"backtrace\\\":[\" ) ; for ( final StackTraceElement ste : throwable . getStackTrace ( ) ) { safeEncodeValue ( encoder , ste . toString ( ) ) ; encoder . append ( \",\" ) ; } if ( throwable . getStackTrace ( ) . length == 0 ) { encoder . append ( \"]\" ) ; } else { encoder . setCharAt ( encoder . length ( ) - 1 , ' ' ) ; } encoder . append ( \",\\\"data\\\":{\" ) ; if ( throwable . getSuppressed ( ) . length > 0 ) { encoder . append ( \"\\\"suppressed\\\":[\" ) ; for ( final Throwable suppressed : throwable . getSuppressed ( ) ) { safeEncodeThrowable ( encoder , suppressed ) ; encoder . append ( \",\" ) ; } encoder . setCharAt ( encoder . length ( ) - 1 , ' ' ) ; encoder . append ( \",\" ) ; } if ( throwable . getCause ( ) != null ) { encoder . append ( \"\\\"cause\\\":\" ) ; safeEncodeThrowable ( encoder , throwable . getCause ( ) ) ; encoder . append ( \",\" ) ; } if ( encoder . charAt ( encoder . length ( ) - 1 ) == ' ' ) { encoder . setCharAt ( encoder . length ( ) - 1 , ' ' ) ; } else { encoder . append ( \"}\" ) ; } encoder . append ( \"}\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static void safeEncodeMap ( final StringBuilder encoder , final Map < ? , ? > valueAsMap ) { encoder . append ( \"{\" ) ; for ( Map . Entry < ? , ? > entry : valueAsMap . entrySet ( ) ) { encoder . append ( \"\\\"\" ) . append ( entry . getKey ( ) . toString ( ) ) . append ( \"\\\":\" ) ; safeEncodeValue ( encoder , entry . getValue ( ) ) ; encoder . append ( \",\" ) ; } if ( valueAsMap . isEmpty ( ) ) { encoder . append ( \"}\" ) ; } else { encoder . setCharAt ( encoder . length ( ) - 1 , ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static void safeEncodeList ( final StringBuilder encoder , final List < ? > valueAsList ) { encoder . append ( \"[\" ) ; for ( Object listValue : valueAsList ) { safeEncodeValue ( encoder , listValue ) ; encoder . append ( \",\" ) ; } if ( valueAsList . isEmpty ( ) ) { encoder . append ( \"]\" ) ; } else { encoder . setCharAt ( encoder . length ( ) - 1 , ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static void safeEncodeArray ( final StringBuilder encoder , final Object value ) { encoder . append ( \"[\" ) ; for ( int i = 0 ; i < Array . getLength ( value ) ; ++ i ) { safeEncodeValue ( encoder , Array . get ( value , i ) ) ; encoder . append ( \",\" ) ; } if ( Array . getLength ( value ) == 0 ) { encoder . append ( \"]\" ) ; } else { encoder . setCharAt ( encoder . length ( ) - 1 , ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package private [CODESPLIT] static void safeEncodeLogValueMap ( final StringBuilder encoder , final LogValueMapFactory . LogValueMap logValueMap ) { final Map < String , Object > safeLogValueMap = new LinkedHashMap <> ( ) ; final Optional < Object > target = logValueMap . getTarget ( ) ; safeLogValueMap . put ( \"_id\" , target . isPresent ( ) ? Integer . toHexString ( System . identityHashCode ( target . get ( ) ) ) : null ) ; safeLogValueMap . put ( \"_class\" , target . isPresent ( ) ? target . get ( ) . getClass ( ) . getName ( ) : null ) ; safeEncodeValue ( encoder , safeLogValueMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If values size hit { @link #MAX } then query will be split ( size % MAX + [ 1 ] ) [CODESPLIT] @ Override public int delete ( List < ? > values , boolean shouldNotify ) throws StormException { final CachedTable table = super . getCachedTable ( values ) ; FieldHolder primaryKey ; try { primaryKey = getPrimaryKey ( table ) ; } catch ( NoPrimaryKeyFoundException e ) { throw new StormException ( e ) ; } final List < Selection > selections = new ArrayList <> ( ) ; final int size = values . size ( ) ; int x = size / MAX ; final int steps = x == 0 ? 1 : size % MAX != 0 ? x + 1 : x ; if ( steps > 1 ) { for ( int i = 0 , end = MAX , start = 0 ; i < steps ; i ++ , start = end , end += Math . min ( size - ( MAX * i ) , MAX ) ) { selections . add ( getSelection ( primaryKey , values . subList ( start , end ) ) ) ; } } else { selections . add ( getSelection ( primaryKey , values ) ) ; } int result = 0 ; beginTransaction ( ) ; try { for ( Selection selection : selections ) { result += deleteInner ( table . getTableName ( ) , selection ) ; } setTransactionSuccessful ( ) ; } finally { endTransaction ( ) ; } if ( shouldNotify && result > 0 ) { manager . notifyChange ( table . getNotificationUri ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialise the warehouse path . <p > This method can be overridden to provide additional initialisations . < / p > [CODESPLIT] protected void init ( ) throws Throwable { metastoreLocation = temporaryFolder . newFolder ( \"metastore\" ) ; conf . setVar ( ConfVars . METASTOREWAREHOUSE , metastoreLocation . getAbsolutePath ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new database with the specified name . [CODESPLIT] public void createDatabase ( String databaseName ) throws TException { HiveMetaStoreClient client = new HiveMetaStoreClient ( conf ( ) ) ; String databaseFolder = new File ( temporaryFolder . getRoot ( ) , databaseName ) . toURI ( ) . toString ( ) ; try { client . createDatabase ( new Database ( databaseName , null , databaseFolder , null ) ) ; } finally { client . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "we should clear it [CODESPLIT] protected void checkMappings ( int arrayPosition ) { final int index = positions . indexOfValue ( arrayPosition ) ; if ( index >= 0 ) { positions . removeAt ( index ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens new SQLite connection and closes previous if it was not closed [CODESPLIT] public void open ( @ Nullable SQLiteOpenCallbacks callbacks ) throws SQLiteException { if ( isOpen ( ) ) { close ( ) ; } initDB ( Storm . getApplicationContext ( ) , mInfo . name , mInfo . version , new ArrayList <> ( mCached . values ( ) ) , mInfo . pragma , callbacks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Counts number of rows in specified query . If { @link ru . noties . storm . query . Selection } is null then counts all rows in Class table . [CODESPLIT] public int count ( Class < ? > clazz , @ Nullable Selection selection ) { final String tableName = getTableName ( clazz ) ; final boolean hasSelection = selection != null ; final Cursor cursor = mDataBase . query ( tableName , new String [ ] { \"count(1)\" } , hasSelection ? selection . getSelection ( ) : null , hasSelection ? selection . getSelectionArgs ( ) : null , null , null , null , \"1\" ) ; if ( cursor == null ) { return 0 ; } final int result ; if ( cursor . moveToFirst ( ) ) { result = cursor . getInt ( 0 ) ; } else { result = 0 ; } cursor . close ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The main entry point for the Storm library . Should be called only once - Application s onCreate () is a good start This method won t open any SQLite database connections . See { @link DatabaseManager#open () } [CODESPLIT] public void init ( Context applicationContext , boolean isDebug ) { if ( mIsInitCalled ) { throw new AssertionError ( \"init() has already been called\" ) ; } mApplicationContext = applicationContext ; mFieldValueGetterFactory = new FieldValueGetterFactory ( ) ; mFieldValueSetterFactory = new FieldValueSetterFactory ( ) ; mCursorValueProviderFactory = new CursorValueProviderFactory ( ) ; mContentValuesSetterFactory = new ContentValuesSetterFactory ( ) ; mIsDebug = isDebug ; mIsInitCalled = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers { [CODESPLIT] public < T , IC extends InstanceCreator < T > > void registerInstanceCreator ( @ NonNull Class < T > clazz , @ NonNull IC ics ) { mInstanceCreators . register ( clazz , ics ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers Type serializer ( aka not supported SQLite types ) { @link ru . noties . storm . sd . AbsSerializer } As a matter of fact { @link ru . noties . storm . sd . AbsSerializer } has only one method that indicates what SQLite type ( { @link ru . noties . storm . FieldType } ) this type will represent . Methods <code > serialize< / code > and <code > deserialize< / code > are not in the inheritance tree . This is done due to the autoboxing issue . [CODESPLIT] public < T > void registerTypeSerializer ( Class < T > who , AbsSerializer < T > serializer ) { //noinspection unchecked mSerializers . put ( who , ( AbsSerializer < Object > ) serializer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the save attr . [CODESPLIT] public static String parseSaveAttr ( final Cell cell , final Map < String , String > saveCommentsMap ) { if ( cell != null ) { String key = cell . getSheet ( ) . getSheetName ( ) + \"!\" + CellUtility . getCellIndexNumberKey ( cell . getColumnIndex ( ) , cell . getRowIndex ( ) ) ; String saveAttr = null ; if ( saveCommentsMap != null ) { saveAttr = ParserUtility . getStringBetweenBracket ( saveCommentsMap . get ( key ) ) ; } if ( ( saveAttr == null ) && ( cell . getCellTypeEnum ( ) == CellType . STRING ) ) { saveAttr = SaveAttrsUtility . parseSaveAttrString ( cell . getStringCellValue ( ) ) ; } if ( ( saveAttr != null ) && ( ! saveAttr . isEmpty ( ) ) ) { return TieConstants . CELL_ADDR_PRE_FIX + cell . getColumnIndex ( ) + \"=\" + saveAttr + \",\" ; } } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save data to object in context . [CODESPLIT] public static void saveDataToObjectInContext ( final Map < String , Object > context , final String saveAttr , final String strValue , final ExpressionEngine engine ) { int index = saveAttr . lastIndexOf ( ' ' ) ; if ( index > 0 ) { String strObject = saveAttr . substring ( 0 , index ) ; String strMethod = saveAttr . substring ( index + 1 ) ; strObject = TieConstants . METHOD_PREFIX + strObject + TieConstants . METHOD_END ; Object object = CommandUtility . evaluate ( strObject , context , engine ) ; CellControlsUtility . setObjectProperty ( object , strMethod , strValue , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reload the data from context to websheet row . [CODESPLIT] public static void refreshSheetRowFromContext ( final Map < String , Object > context , final String fullSaveAttr , final Row row , final ExpressionEngine engine ) { if ( ! fullSaveAttr . startsWith ( TieConstants . CELL_ADDR_PRE_FIX ) ) { return ; } int ipos = fullSaveAttr . indexOf ( ' ' ) ; if ( ipos > 0 ) { String columnIndex = fullSaveAttr . substring ( 1 , ipos ) ; String saveAttr = fullSaveAttr . substring ( ipos + 1 ) ; Cell cell = row . getCell ( Integer . parseInt ( columnIndex ) ) ; if ( cell . getCellTypeEnum ( ) != CellType . FORMULA ) { CommandUtility . evaluateNormalCells ( cell , TieConstants . METHOD_PREFIX + saveAttr + TieConstants . METHOD_END , context , engine ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the save attr string . [CODESPLIT] public static String parseSaveAttrString ( final String strValue ) { if ( strValue != null ) { int first = strValue . indexOf ( TieConstants . METHOD_PREFIX ) ; int last = strValue . lastIndexOf ( TieConstants . METHOD_PREFIX ) ; int end = strValue . lastIndexOf ( TieConstants . METHOD_END ) ; if ( ( first >= 0 ) && ( first == last ) && ( end > 1 ) ) { return strValue . substring ( first + 2 , end ) ; } } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the save attr list from row . [CODESPLIT] public static String getSaveAttrListFromRow ( final Row row ) { if ( row != null ) { Cell cell = row . getCell ( TieConstants . HIDDEN_SAVE_OBJECTS_COLUMN ) ; if ( cell != null ) { String str = cell . getStringCellValue ( ) ; if ( ( str != null ) && ( ! str . isEmpty ( ) ) ) { return str ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the save attr from list . [CODESPLIT] public static String getSaveAttrFromList ( final int columnIndex , final String saveAttrs ) { if ( ( saveAttrs != null ) && ( ! saveAttrs . isEmpty ( ) ) ) { String str = TieConstants . CELL_ADDR_PRE_FIX + columnIndex + \"=\" ; int istart = saveAttrs . indexOf ( str ) ; if ( istart >= 0 ) { int iend = saveAttrs . indexOf ( ' ' , istart ) ; if ( iend > istart ) { return saveAttrs . substring ( istart + str . length ( ) , iend ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the columnIndex from saveAttr . saveAttr format as : $columnIndex = xxxxxxx [CODESPLIT] public static String getColumnIndexFromSaveAttr ( final String saveAttr ) { if ( ( saveAttr != null ) && ( ! saveAttr . isEmpty ( ) ) ) { int iend = saveAttr . indexOf ( ' ' ) ; if ( iend > 0 ) { int istart = saveAttr . indexOf ( ' ' ) ; if ( iend > istart ) { return saveAttr . substring ( istart + 1 , iend ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is checks for save attr . [CODESPLIT] public static boolean isHasSaveAttr ( final Cell cell ) { Cell saveAttrCell = cell . getRow ( ) . getCell ( TieConstants . HIDDEN_SAVE_OBJECTS_COLUMN ) ; if ( saveAttrCell != null ) { return isHasSaveAttr ( cell , saveAttrCell . getStringCellValue ( ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is checks for save attr . [CODESPLIT] public static boolean isHasSaveAttr ( final Cell cell , final String saveAttrs ) { if ( cell != null ) { int columnIndex = cell . getColumnIndex ( ) ; String str = TieConstants . CELL_ADDR_PRE_FIX + columnIndex + \"=\" ; if ( ( saveAttrs != null ) && ( saveAttrs . indexOf ( str ) >= 0 ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the save objects in hidden column . [CODESPLIT] public static void setSaveObjectsInHiddenColumn ( final Row row , final String saveAttr ) { Cell cell = row . getCell ( TieConstants . HIDDEN_SAVE_OBJECTS_COLUMN , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; cell . setCellValue ( saveAttr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the save attrs for sheet . [CODESPLIT] public static void setSaveAttrsForSheet ( final Sheet sheet , final int minRowNum , final int maxRowNum , final Map < String , String > saveCommentsMap ) { for ( Row row : sheet ) { int rowIndex = row . getRowNum ( ) ; if ( ( rowIndex >= minRowNum ) && ( rowIndex <= maxRowNum ) ) { setSaveAttrsForRow ( row , saveCommentsMap ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the save attrs for row . [CODESPLIT] public static void setSaveAttrsForRow ( final Row row , final Map < String , String > saveCommentsMap ) { StringBuilder saveAttr = new StringBuilder ( ) ; for ( Cell cell : row ) { String sAttr = parseSaveAttr ( cell , saveCommentsMap ) ; if ( ! sAttr . isEmpty ( ) ) { saveAttr . append ( sAttr ) ; } } if ( saveAttr . length ( ) > 0 ) { SaveAttrsUtility . setSaveObjectsInHiddenColumn ( row , saveAttr . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare context and attrs for cell . [CODESPLIT] public static String prepareContextAndAttrsForCell ( Cell poiCell , String fullName , CellHelper cellHelper ) { if ( fullName == null ) { return null ; } String saveAttrList = SaveAttrsUtility . getSaveAttrListFromRow ( poiCell . getRow ( ) ) ; if ( saveAttrList != null ) { String saveAttr = SaveAttrsUtility . getSaveAttrFromList ( poiCell . getColumnIndex ( ) , saveAttrList ) ; if ( saveAttr != null ) { cellHelper . restoreDataContext ( fullName ) ; return saveAttr ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) @ Override public List getSerListFromCtObjChart ( final Object ctObjChart ) { if ( ctObjChart instanceof CTPieChart ) { return ( ( CTPieChart ) ctObjChart ) . getSerList ( ) ; } return this . getEmptySerlist ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTShapeProperties getShapePropertiesFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTPieSer ) { return ( ( CTPieSer ) ctObjSer ) . getSpPr ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTNumDataSource getCTNumDataSourceFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTPieSer ) { return ( ( CTPieSer ) ctObjSer ) . getVal ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final List < CTDPt > getDPtListFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTPieSer ) { List < CTDPt > dptList = ( ( CTPieSer ) ctObjSer ) . getDPtList ( ) ; if ( dptList == null ) { // return empty list instead of null for pie.\r // this will ensure pie create valueColorList in serial object.\r dptList = new ArrayList <> ( ) ; } return dptList ; } return this . getEmptyDptlist ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert string to int ( length ) . [CODESPLIT] protected final int calcLength ( final String lengthStr ) { try { return Integer . parseInt ( lengthStr ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"canot calcLength :\" + ex . getLocalizedMessage ( ) , ex ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final Object getAsObject ( final FacesContext context , final UIComponent component , final String value ) { Double doubleValue = 0.0 ; String symbol = \"\" ; String strValue = value ; try { symbol = ( String ) component . getAttributes ( ) . get ( TieConstants . CELL_DATA_SYMBOL ) ; if ( ( symbol != null ) && ( symbol . equals ( TieConstants . CELL_FORMAT_PERCENTAGE_SYMBOL ) && strValue != null ) ) { strValue = strValue . trim ( ) ; if ( strValue . endsWith ( TieConstants . CELL_FORMAT_PERCENTAGE_SYMBOL ) ) { doubleValue = Double . valueOf ( strValue . substring ( 0 , strValue . length ( ) - 1 ) ) / TieConstants . CELL_FORMAT_PERCENTAGE_VALUE ; strValue = doubleValue . toString ( ) ; } } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"error in getAsObject of TieSheetNumberConverter : \" + ex . getLocalizedMessage ( ) , ex ) ; } return strValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fmt number . [CODESPLIT] private String fmtNumber ( final double d ) { if ( Double . compare ( d % 1 , 0 ) == 0 ) { return String . format ( \"%d\" , ( int ) d ) ; } else { return String . format ( \"%.2f\" , d ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final String getAsString ( final FacesContext context , final UIComponent component , final Object value ) { String strValue = null ; String symbol = \"\" ; try { strValue = ( String ) value ; symbol = ( String ) component . getAttributes ( ) . get ( TieConstants . CELL_DATA_SYMBOL ) ; if ( ( symbol != null ) && ( symbol . equals ( TieConstants . CELL_FORMAT_PERCENTAGE_SYMBOL ) ) && ( value != null ) && ! ( ( String ) value ) . isEmpty ( ) ) { Double doubleValue = Double . valueOf ( ( String ) value ) * TieConstants . CELL_FORMAT_PERCENTAGE_VALUE ; strValue = fmtNumber ( doubleValue ) + TieConstants . CELL_FORMAT_PERCENTAGE_SYMBOL ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"error in getAsString of TieSheetNumberConverter : \" + ex . getLocalizedMessage ( ) , ex ) ; } return strValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save the cell before serialize . [CODESPLIT] private void writeObject ( final java . io . ObjectOutputStream out ) throws IOException { saveList = new ArrayList <> ( ) ; for ( Map . Entry < Cell , String > entry : this . getMap ( ) . entrySet ( ) ) { saveList . add ( new SerialKey ( new SerialCellAddress ( entry . getKey ( ) ) , entry . getValue ( ) ) ) ; } out . defaultWriteObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recover the cell reference to the sheet . [CODESPLIT] public void recover ( final Sheet sheet ) { if ( ! this . getMap ( ) . isEmpty ( ) ) { map . clear ( ) ; } for ( SerialKey entry : this . saveList ) { SerialCellAddress skey = entry . getKey ( ) ; map . put ( sheet . getRow ( skey . getRow ( ) ) . getCell ( skey . getColumn ( ) ) , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put shift attrs . [CODESPLIT] public final void putShiftAttrs ( final String fullName , final ConfigRangeAttrs attrs , final RowsMapping unitRowsMapping ) { attrs . setUnitRowsMapping ( unitRowsMapping ) ; this . shiftMap . put ( fullName , attrs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up workbook . Also create evaluation wrapper . [CODESPLIT] public void setWb ( final Workbook pWb ) { this . getSerialWb ( ) . setWb ( pWb ) ; this . wbWrapper = XSSFEvaluationWorkbook . create ( ( XSSFWorkbook ) pWb ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return evaluation wrapper if needed . [CODESPLIT] public XSSFEvaluationWorkbook getWbWrapper ( ) { if ( ( this . wbWrapper == null ) && ( this . getWb ( ) != null ) ) { this . wbWrapper = XSSFEvaluationWorkbook . create ( ( XSSFWorkbook ) this . getWb ( ) ) ; } return wbWrapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get formulaevaluator . [CODESPLIT] public FormulaEvaluator getFormulaEvaluator ( ) { if ( ( this . formulaEvaluator == null ) && ( this . getWb ( ) != null ) ) { this . formulaEvaluator = this . getWb ( ) . getCreationHelper ( ) . createFormulaEvaluator ( ) ; } return formulaEvaluator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recalculate max coulumn count across sheets in the workbook . [CODESPLIT] public void reCalcMaxColCounts ( ) { if ( ( this . getSheetConfigMap ( ) == null ) || ( this . getSheetConfigMap ( ) . isEmpty ( ) ) ) { this . maxColCounts = 0 ; return ; } int maxColumns = 0 ; for ( SheetConfiguration sheetConfig : this . getSheetConfigMap ( ) . values ( ) ) { int counts = sheetConfig . getHeaderCellRange ( ) . getRightCol ( ) - sheetConfig . getHeaderCellRange ( ) . getLeftCol ( ) + 1 ; if ( maxColumns < counts ) { maxColumns = counts ; } } this . maxColCounts = maxColumns ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load web sheet from inputStream file with data object . [CODESPLIT] public int loadWebSheet ( final InputStream inputStream , final Map < String , Object > pDataContext ) { return this . getHelper ( ) . getWebSheetLoader ( ) . loadWorkbook ( inputStream , pDataContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load web sheet from giving workbook with data object . [CODESPLIT] public int loadWebSheet ( final Workbook pWb , final Map < String , Object > pDataContext ) { return this . getHelper ( ) . getWebSheetLoader ( ) . loadWorkbook ( pWb , pDataContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggered when user switch the tab . This will load different tab ( sheet ) as the current sheet . [CODESPLIT] public void onTabChange ( final TabChangeEvent event ) { String tabName = event . getTab ( ) . getTitle ( ) ; loadWorkSheetByTabName ( tabName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load worksheet by tab name . [CODESPLIT] public int loadWorkSheetByTabName ( final String tabName ) { try { int sheetId = this . getHelper ( ) . getWebSheetLoader ( ) . findTabIndexWithName ( tabName ) ; if ( ( getSheetConfigMap ( ) != null ) && ( sheetId < getSheetConfigMap ( ) . size ( ) ) ) { this . getHelper ( ) . getWebSheetLoader ( ) . loadWorkSheet ( tabName ) ; setActiveTabIndex ( sheetId ) ; } return 1 ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"loadWorkSheetByTabName failed. error = \" + ex . getMessage ( ) , ex ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "download current workbook . [CODESPLIT] public void doExport ( ) { try { String fileName = this . getExportFileName ( ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; this . getWb ( ) . write ( out ) ; InputStream stream = new BufferedInputStream ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; exportFile = new DefaultStreamedContent ( stream , \"application/force-download\" , fileName ) ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"Error in export file : \" + e . getLocalizedMessage ( ) , e ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the current workbooks . [CODESPLIT] public void doSave ( ) { this . setSubmitMde ( false ) ; if ( ! this . getHelper ( ) . getValidationHandler ( ) . preValidation ( ) ) { LOG . fine ( \"Validation failded before saving\" ) ; return ; } processSave ( ) ; this . getHelper ( ) . getWebSheetLoader ( ) . setUnsavedStatus ( RequestContext . getCurrentInstance ( ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submit the current workbooks . [CODESPLIT] public void doSubmit ( ) { this . setSubmitMde ( true ) ; // validation may behavior differently depend on the submit mode.\r // e.g. when submit mode = false, empty fields or value not changed cells\r // don't need to pass the validation rule. This allow partial save the form. \r // when submit mode = true, all cells need to pass the validation.\r if ( ! this . getHelper ( ) . getValidationHandler ( ) . preValidation ( ) ) { LOG . fine ( \"Validation failed before saving\" ) ; return ; } processSubmit ( ) ; this . getHelper ( ) . getWebSheetLoader ( ) . setUnsavedStatus ( RequestContext . getCurrentInstance ( ) , false ) ; this . setSubmitMde ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "populate component . [CODESPLIT] public void populateComponent ( final ComponentSystemEvent event ) { UIComponent component = event . getComponent ( ) ; int [ ] rowcol = CellUtility . getRowColFromComponentAttributes ( component ) ; int row = rowcol [ 0 ] ; int col = rowcol [ 1 ] ; FacesCell fcell = CellUtility . getFacesCellFromBodyRow ( row , col , this . getBodyRows ( ) , this . getCurrent ( ) . getCurrentTopRow ( ) , this . getCurrent ( ) . getCurrentLeftColumn ( ) ) ; CellControlsUtility . populateAttributes ( component , fcell , this . getCellDefaultControl ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current sheet config . [CODESPLIT] public SheetConfiguration getCurrentSheetConfig ( ) { String currentTabName = this . getCurrent ( ) . getCurrentTabName ( ) ; if ( currentTabName == null ) { return null ; } return this . getSheetConfigMap ( ) . get ( currentTabName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load the bean from saving . [CODESPLIT] private void readObject ( final java . io . ObjectInputStream in ) throws IOException { try { in . defaultReadObject ( ) ; recover ( ) ; } catch ( EncryptedDocumentException | ClassNotFoundException e ) { LOG . log ( Level . SEVERE , \" error in readObject of serialWorkbook : \" + e . getLocalizedMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final Object getAsObject ( final FacesContext context , final UIComponent component , final String value ) { if ( value == null ) { return null ; } String pattern = ( String ) component . getAttributes ( ) . get ( \"pattern\" ) ; SimpleDateFormat formatter = new SimpleDateFormat ( pattern , getLocale ( context , component ) ) ; try { return formatter . parse ( value ) ; } catch ( Exception e ) { throw new ConverterException ( \"ConverterException = \" + e . getLocalizedMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final String getAsString ( final FacesContext context , final UIComponent component , final Object value ) { if ( value == null ) { return \"\" ; } if ( value instanceof String ) { return ( String ) value ; } if ( context == null || component == null ) { throw new NullPointerException ( ) ; } try { String pattern = ( String ) component . getAttributes ( ) . get ( TieConstants . WIDGET_ATTR_PATTERN ) ; SimpleDateFormat dateFormat = new SimpleDateFormat ( pattern , getLocale ( context , component ) ) ; return dateFormat . format ( value ) ; } catch ( Exception e ) { throw new ConverterException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the locale . [CODESPLIT] private Locale getLocale ( final FacesContext context , final UIComponent component ) { String localeStr = ( String ) component . getAttributes ( ) . get ( TieConstants . COMPONENT_ATTR_LOCALE ) ; if ( localeStr == null ) { return context . getViewRoot ( ) . getLocale ( ) ; } return Locale . forLanguageTag ( localeStr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return picture to web front end . [CODESPLIT] public StreamedContent getPicture ( ) { FacesContext context = FacesContext . getCurrentInstance ( ) ; if ( context . getCurrentPhaseId ( ) == PhaseId . RENDER_RESPONSE ) { // So, we're rendering the HTML. Return a stub StreamedContent so\r // that it will generate right URL.\r LOG . fine ( \" return empty picture\" ) ; return new DefaultStreamedContent ( ) ; } else { // So, browser is requesting the image. Return a real\r // StreamedContent with the image bytes.\r String pictureId = context . getExternalContext ( ) . getRequestParameterMap ( ) . get ( \"pictureViewId\" ) ; PictureData picData = ( PictureData ) FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getSessionMap ( ) . get ( pictureId ) ; FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getSessionMap ( ) . remove ( pictureId ) ; LOG . fine ( \" return real picture and remove session\" ) ; return new DefaultStreamedContent ( new ByteArrayInputStream ( picData . getData ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the cell helper . [CODESPLIT] public final CellHelper getCellHelper ( ) { if ( ( this . cellHelper == null ) && ( this . parent != null ) ) { this . cellHelper = new CellHelper ( parent ) ; } return cellHelper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the pic helper . [CODESPLIT] public final PicturesHelper getPicHelper ( ) { if ( ( this . picHelper == null ) && ( this . parent != null ) ) { this . picHelper = new PicturesHelper ( parent ) ; } return picHelper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the validation handler . [CODESPLIT] public final ValidationHandler getValidationHandler ( ) { if ( ( this . validationHandler == null ) && ( this . parent != null ) ) { this . validationHandler = new ValidationHandler ( parent ) ; } return validationHandler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the chart helper . [CODESPLIT] public final ChartHelper getChartHelper ( ) { if ( ( this . chartHelper == null ) && ( this . parent != null ) ) { this . chartHelper = new ChartHelper ( parent ) ; } return chartHelper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert shared formulas . [CODESPLIT] public static Ptg [ ] convertSharedFormulas ( final Ptg [ ] ptgs , final ShiftFormulaRef shiftFormulaRef ) { List < Ptg > newPtgList = new ArrayList <> ( ) ; Object ptg ; for ( int k = 0 ; k < ptgs . length ; ++ k ) { ptg = ptgs [ k ] ; newPtgList . addAll ( Arrays . asList ( convertPtg ( ptgs , k , shiftFormulaRef , ptg ) ) ) ; } return newPtgList . toArray ( new Ptg [ newPtgList . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "3d ( reference to other sheet ) is not supported . only 2d ( within the sheet ) is supported . [CODESPLIT] public static int getFirstSupportedRowNumFromPtg ( final Object ptg ) { int rCode = - 1 ; if ( ptg instanceof RefPtgBase ) { if ( ! ( ptg instanceof Ref3DPxg ) && ! ( ptg instanceof Ref3DPtg ) ) { rCode = ( ( RefPtgBase ) ptg ) . getRow ( ) ; } } else if ( ptg instanceof AreaPtgBase && ! ( ptg instanceof Area3DPxg ) && ! ( ptg instanceof Area3DPtg ) ) { rCode = ( ( AreaPtgBase ) ptg ) . getFirstRow ( ) ; } return rCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert ptg . [CODESPLIT] private static Ptg [ ] convertPtg ( final Ptg [ ] ptgs , final int position , final ShiftFormulaRef shiftFormulaRef , final Object ptg ) { byte originalOperandClass = - 1 ; if ( ! ( ( Ptg ) ptg ) . isBaseToken ( ) ) { originalOperandClass = ( ( Ptg ) ptg ) . getPtgClass ( ) ; } int currentRow ; currentRow = getFirstSupportedRowNumFromPtg ( ptg ) ; if ( ( currentRow >= 0 ) && shiftFormulaRef . getWatchList ( ) . contains ( currentRow ) ) { return convertPtgForWatchList ( ptgs , position , shiftFormulaRef , ptg , originalOperandClass , currentRow ) ; } // no need change ptg\r if ( ( ptg instanceof AttrPtg ) && ( shiftFormulaRef . getFormulaChanged ( ) > 1 ) ) { AttrPtg newPtg = ( AttrPtg ) ptg ; if ( newPtg . isSum ( ) ) { FuncVarPtg fptg = FuncVarPtg . create ( \"sum\" , shiftFormulaRef . getFormulaChanged ( ) ) ; return singlePtg ( fptg , fptg . getPtgClass ( ) , shiftFormulaRef . getFormulaChanged ( ) ) ; } } return singlePtg ( ptg , originalOperandClass , shiftFormulaRef . getFormulaChanged ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert ptg for watch list . [CODESPLIT] private static Ptg [ ] convertPtgForWatchList ( final Ptg [ ] ptgs , final int position , final ShiftFormulaRef shiftFormulaRef , final Object ptg , final byte originalOperandClass , final int currentRow ) { List < SerialRow > rowlist = getRowsList ( currentRow , shiftFormulaRef . getCurrentRowsMappingList ( ) ) ; if ( ( rowlist == null ) || ( rowlist . isEmpty ( ) ) ) { // no need change ptg\r return singlePtg ( ptg , originalOperandClass , - 1 ) ; } shiftFormulaRef . setFormulaChanged ( 1 ) ; // one to one or has no round brackets\r if ( ( rowlist . size ( ) == 1 ) || ( ( position + 1 ) >= ptgs . length ) || ! ( ptgs [ position + 1 ] instanceof ParenthesisPtg ) ) { // change ptg one to one\r // return changed ptg\r return singlePtg ( fixupRefRelativeRowOneToOne ( ptg , rowlist . get ( 0 ) . getRow ( ) ) , originalOperandClass , - 1 ) ; } shiftFormulaRef . setFormulaChanged ( rowlist . size ( ) ) ; return fixupRefRelativeRowOneToMany ( ptg , originalOperandClass , rowlist , ptgs , position ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Single ptg . [CODESPLIT] private static Ptg [ ] singlePtg ( final Object ptg , final byte originalOperandClass , final int formulaChanged ) { Ptg [ ] newPtg = new Ptg [ 1 ] ; if ( originalOperandClass != ( - 1 ) ) { ( ( Ptg ) ptg ) . setClass ( originalOperandClass ) ; } Object ptgAfter = ptg ; if ( ptg instanceof FuncVarPtg ) { FuncVarPtg fptg = ( FuncVarPtg ) ptg ; if ( ( formulaChanged > 0 ) && ( fptg . getNumberOfOperands ( ) != formulaChanged ) ) { ptgAfter = FuncVarPtg . create ( ( ( FuncVarPtg ) ptg ) . getName ( ) , formulaChanged ) ; } } newPtg [ 0 ] = ( Ptg ) ptgAfter ; return newPtg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the rows list . [CODESPLIT] private static List < SerialRow > getRowsList ( final int currentRow , final List < RowsMapping > currentRowsMappingList ) { List < SerialRow > all = null ; int size = currentRowsMappingList . size ( ) ; for ( RowsMapping rowsmapping : currentRowsMappingList ) { List < SerialRow > current = rowsmapping . get ( currentRow ) ; if ( current != null ) { if ( size == 1 ) { return current ; } all = assembleRowsListFromRowsMapping ( all , current ) ; } } return all ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assemble rowslist from rowsmapping . [CODESPLIT] private static List < SerialRow > assembleRowsListFromRowsMapping ( final List < SerialRow > all , final List < SerialRow > current ) { List < SerialRow > list ; if ( all == null ) { list = new ArrayList <> ( ) ; list . addAll ( current ) ; } else { list = all ; for ( SerialRow row : current ) { if ( ! all . contains ( row ) ) { list . add ( row ) ; } } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fixup ref relative row one to one . [CODESPLIT] protected static Object fixupRefRelativeRowOneToOne ( final Object ptg , final Row newRow ) { if ( ptg instanceof RefPtgBase ) { if ( ptg instanceof Ref3DPxg ) { Ref3DPxg ref3dPxg = ( Ref3DPxg ) ptg ; Ref3DPxg new3dpxg = new Ref3DPxg ( ref3dPxg . getExternalWorkbookNumber ( ) , new SheetIdentifier ( null , new NameIdentifier ( ref3dPxg . getSheetName ( ) , false ) ) , new CellReference ( newRow . getRowNum ( ) , ref3dPxg . getColumn ( ) ) ) ; new3dpxg . setClass ( ref3dPxg . getPtgClass ( ) ) ; new3dpxg . setColRelative ( ref3dPxg . isColRelative ( ) ) ; new3dpxg . setRowRelative ( ref3dPxg . isRowRelative ( ) ) ; new3dpxg . setLastSheetName ( ref3dPxg . getLastSheetName ( ) ) ; return new3dpxg ; } else { RefPtgBase refPtgBase = ( RefPtgBase ) ptg ; return new RefPtg ( newRow . getRowNum ( ) , refPtgBase . getColumn ( ) , refPtgBase . isRowRelative ( ) , refPtgBase . isColRelative ( ) ) ; } } else { if ( ptg instanceof Area3DPxg ) { Area3DPxg area3dPxg = ( Area3DPxg ) ptg ; Area3DPxg new3dpxg = new Area3DPxg ( area3dPxg . getExternalWorkbookNumber ( ) , new SheetIdentifier ( null , new NameIdentifier ( area3dPxg . getSheetName ( ) , false ) ) , area3dPxg . format2DRefAsString ( ) ) ; new3dpxg . setClass ( area3dPxg . getPtgClass ( ) ) ; new3dpxg . setFirstColRelative ( area3dPxg . isFirstColRelative ( ) ) ; new3dpxg . setLastColRelative ( area3dPxg . isLastColRelative ( ) ) ; int shiftRow = newRow . getRowNum ( ) - area3dPxg . getFirstRow ( ) ; new3dpxg . setFirstRow ( area3dPxg . getFirstRow ( ) + shiftRow ) ; new3dpxg . setLastRow ( area3dPxg . getLastRow ( ) + shiftRow ) ; new3dpxg . setFirstRowRelative ( area3dPxg . isFirstRowRelative ( ) ) ; new3dpxg . setLastRowRelative ( area3dPxg . isLastRowRelative ( ) ) ; new3dpxg . setLastSheetName ( area3dPxg . getLastSheetName ( ) ) ; return new3dpxg ; } else { AreaPtgBase areaPtgBase = ( AreaPtgBase ) ptg ; int shiftRow = newRow . getRowNum ( ) - areaPtgBase . getFirstRow ( ) ; return new AreaPtg ( areaPtgBase . getFirstRow ( ) + shiftRow , areaPtgBase . getLastRow ( ) + shiftRow , areaPtgBase . getFirstColumn ( ) , areaPtgBase . getLastColumn ( ) , areaPtgBase . isFirstRowRelative ( ) , areaPtgBase . isLastRowRelative ( ) , areaPtgBase . isFirstColRelative ( ) , areaPtgBase . isLastColRelative ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change formula ptg by replace one ref with multiple ref . We require user follow the rule to define dynamic formula . e . g . If cell reference in formula maybe become multiple cells then should use round brackets around it . [CODESPLIT] protected static Ptg [ ] fixupRefRelativeRowOneToMany ( final Object ptg , final byte originalOperandClass , final List < SerialRow > rowList , final Ptg [ ] ptgs , final int position ) { int size = rowList . size ( ) ; Ptg [ ] newPtg = null ; // if followedby valueoperator, then change to multiple ptg plus Add\r // e.g. (A1) --> (A1+A2)\r if ( isFollowedByValueOperator ( ptgs , position ) ) { if ( ptg instanceof RefPtgBase ) { newPtg = new Ptg [ size + 1 ] ; buildDynamicRowForRefPtgBase ( ptg , originalOperandClass , rowList , newPtg , false ) ; newPtg [ rowList . size ( ) ] = AddPtg . instance ; } } else { // otherwise change to mutiple ptg plus parenth\r // e.g. SUM((A1)) --> SUM((A1),(A2))\r // SUM((A1:B1)) --> SUM((A1:B1),(A2:B2))\r newPtg = new Ptg [ ( size * 2 ) - 1 ] ; if ( ptg instanceof RefPtgBase ) { buildDynamicRowForRefPtgBase ( ptg , originalOperandClass , rowList , newPtg , true ) ; } else { buildDynamicRowForAreaPtgBase ( ptg , originalOperandClass , rowList , newPtg ) ; } } return newPtg ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the dynamic row for ref ptg base . [CODESPLIT] private static void buildDynamicRowForRefPtgBase ( final Object ptg , final byte originalOperandClass , final List < SerialRow > rowList , final Ptg [ ] newPtg , final boolean includeParenthesis ) { RefPtgBase refPtg = ( RefPtgBase ) ptg ; int unitSize = 1 ; if ( includeParenthesis ) { unitSize = 2 ; } for ( int i = 0 ; i < rowList . size ( ) ; i ++ ) { Row row = rowList . get ( i ) . getRow ( ) ; if ( refPtg instanceof Ref3DPxg ) { Ref3DPxg ref3dPxg = ( Ref3DPxg ) refPtg ; Ref3DPxg new3dpxg = new Ref3DPxg ( ref3dPxg . getExternalWorkbookNumber ( ) , new SheetIdentifier ( null , new NameIdentifier ( ref3dPxg . getSheetName ( ) , false ) ) , new CellReference ( row . getRowNum ( ) , ref3dPxg . getColumn ( ) ) ) ; new3dpxg . setClass ( originalOperandClass ) ; new3dpxg . setColRelative ( ref3dPxg . isColRelative ( ) ) ; new3dpxg . setRowRelative ( ref3dPxg . isRowRelative ( ) ) ; new3dpxg . setLastSheetName ( ref3dPxg . getLastSheetName ( ) ) ; newPtg [ i * unitSize ] = new3dpxg ; } else { RefPtgBase refPtgBase = refPtg ; newPtg [ i * unitSize ] = new RefPtg ( row . getRowNum ( ) , refPtgBase . getColumn ( ) , refPtgBase . isRowRelative ( ) , refPtgBase . isColRelative ( ) ) ; } if ( ( unitSize == 2 ) && ( i < ( rowList . size ( ) - 1 ) ) ) { newPtg [ i * unitSize + 1 ] = ParenthesisPtg . instance ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the dynamic row for area ptg base . [CODESPLIT] private static void buildDynamicRowForAreaPtgBase ( final Object ptg , final byte originalOperandClass , final List < SerialRow > rowList , final Ptg [ ] newPtg ) { AreaPtgBase areaPtg = ( AreaPtgBase ) ptg ; int originFirstRow = areaPtg . getFirstRow ( ) ; int originLastRow = areaPtg . getLastRow ( ) ; int unitSize = 2 ; for ( int i = 0 ; i < rowList . size ( ) ; i ++ ) { Row row = rowList . get ( i ) . getRow ( ) ; int shiftRow = row . getRowNum ( ) - originFirstRow ; if ( ptg instanceof Area3DPxg ) { Area3DPxg area3dPxg = ( Area3DPxg ) ptg ; Area3DPxg new3dpxg = new Area3DPxg ( area3dPxg . getExternalWorkbookNumber ( ) , new SheetIdentifier ( null , new NameIdentifier ( area3dPxg . getSheetName ( ) , false ) ) , area3dPxg . format2DRefAsString ( ) ) ; new3dpxg . setClass ( originalOperandClass ) ; new3dpxg . setFirstColRelative ( area3dPxg . isFirstColRelative ( ) ) ; new3dpxg . setLastColRelative ( area3dPxg . isLastColRelative ( ) ) ; new3dpxg . setFirstRow ( originFirstRow + shiftRow ) ; new3dpxg . setLastRow ( originLastRow + shiftRow ) ; new3dpxg . setFirstRowRelative ( area3dPxg . isFirstRowRelative ( ) ) ; new3dpxg . setLastRowRelative ( area3dPxg . isLastRowRelative ( ) ) ; new3dpxg . setLastSheetName ( area3dPxg . getLastSheetName ( ) ) ; newPtg [ i * unitSize ] = new3dpxg ; } else { AreaPtgBase areaPtgBase = ( AreaPtgBase ) ptg ; newPtg [ i * unitSize ] = new AreaPtg ( originFirstRow + shiftRow , originLastRow + shiftRow , areaPtgBase . getFirstColumn ( ) , areaPtgBase . getLastColumn ( ) , areaPtgBase . isFirstRowRelative ( ) , areaPtgBase . isLastRowRelative ( ) , areaPtgBase . isFirstColRelative ( ) , areaPtgBase . isLastColRelative ( ) ) ; } if ( i < ( rowList . size ( ) - 1 ) ) { newPtg [ i * unitSize + 1 ] = ParenthesisPtg . instance ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check is current ptg followed by valueOperationPtg . valueOperationPtg include : Add SubStract Multiply Divide etc . [CODESPLIT] private static boolean isFollowedByValueOperator ( final Ptg [ ] ptgs , final int position ) { for ( int i = position ; i < ptgs . length ; i ++ ) { Object ptg = ptgs [ position ] ; if ( ptg instanceof OperationPtg ) { return ptg instanceof ValueOperatorPtg ; } else if ( ptg instanceof AttrPtg ) { return false ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "retrieve background color for plot area . [CODESPLIT] public static XColor getBgColor ( final CTPlotArea ctPlot , final ThemesTable themeTable ) { CTSolidColorFillProperties colorFill = null ; try { colorFill = ctPlot . getSpPr ( ) . getSolidFill ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No entry in bgcolor for solidFill\" , ex ) ; } XColor xcolor = findAutomaticFillColor ( themeTable , colorFill ) ; if ( xcolor != null ) { return xcolor ; } else { return new XColor ( new XSSFColor ( Color . WHITE ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get line color of line chart from CTLineSer . [CODESPLIT] public static XColor geColorFromSpPr ( final int index , final CTShapeProperties ctSpPr , final ThemesTable themeTable , final boolean isLineColor ) { CTSolidColorFillProperties colorFill = null ; try { if ( isLineColor ) { colorFill = ctSpPr . getLn ( ) . getSolidFill ( ) ; } else { colorFill = ctSpPr . getSolidFill ( ) ; } } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No entry for solidFill\" , ex ) ; } XColor xcolor = findAutomaticFillColor ( themeTable , colorFill ) ; if ( xcolor != null ) { return xcolor ; } else { return getXColorWithAutomaticFill ( index , themeTable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find automatic fill color . [CODESPLIT] private static XColor findAutomaticFillColor ( final ThemesTable themeTable , final CTSolidColorFillProperties colorFill ) { // if there's no solidFill, then use automaticFill color\r if ( colorFill == null ) { return null ; } CTSchemeColor ctsColor = colorFill . getSchemeClr ( ) ; if ( ctsColor != null ) { return getXColorFromSchemeClr ( ctsColor , themeTable ) ; } else { CTSRgbColor ctrColor = colorFill . getSrgbClr ( ) ; if ( ctrColor != null ) { return getXColorFromRgbClr ( ctrColor ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "assemble xssfcolor with tint / lumoff / lummod / alpha to xcolor . [CODESPLIT] private static XColor assembleXcolor ( final XSSFColor bcolor , final double preTint , final int lumOff , final int lumMod , final int alphaInt ) { if ( bcolor == null ) { return null ; } double tint = preTint ; if ( Double . compare ( tint , 0 ) == 0 ) { // no preTint\r if ( lumOff > 0 ) { tint = lumOff / MILLION_NUMBERS ; } else { if ( lumMod > 0 ) { tint = - 1 * ( lumMod / MILLION_NUMBERS ) ; } } } bcolor . setTint ( tint ) ; double alpha = 0 ; if ( alphaInt > 0 ) { alpha = alphaInt / MILLION_NUMBERS ; } return new XColor ( bcolor , alpha ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "retrieve xcolor from scheme color . [CODESPLIT] private static XColor getXColorFromSchemeClr ( final CTSchemeColor ctsColor , final ThemesTable themeTable ) { if ( ctsColor . getVal ( ) != null ) { return getXColorWithSchema ( ctsColor . getVal ( ) . toString ( ) , 0 , ctsColor , themeTable ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get xcolor with color schema name . Normally the names are accent1 to 7 . Sometimes also have lumOff / lumMod / alphaInt setting . [CODESPLIT] private static XColor getXColorWithSchema ( final String colorSchema , final double preTint , final CTSchemeColor ctsColor , final ThemesTable themeTable ) { int colorIndex = getThemeIndexFromName ( colorSchema ) ; if ( colorIndex < 0 ) { return null ; } XSSFColor bcolor = themeTable . getThemeColor ( colorIndex ) ; if ( bcolor == null ) { return null ; } int lumOff = 0 ; int lumMod = 0 ; int alphaInt = 0 ; if ( ctsColor != null ) { try { lumOff = ctsColor . getLumOffArray ( 0 ) . getVal ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No lumOff entry\" , ex ) ; } try { lumMod = ctsColor . getLumModArray ( 0 ) . getVal ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No lumMod entry\" , ex ) ; } try { alphaInt = ctsColor . getAlphaArray ( 0 ) . getVal ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No alpha entry\" , ex ) ; } } return assembleXcolor ( bcolor , preTint , lumOff , lumMod , alphaInt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get xcolor from ctsRgbColor . [CODESPLIT] private static XColor getXColorFromRgbClr ( final CTSRgbColor ctrColor ) { XSSFColor bcolor = null ; try { byte [ ] rgb = ctrColor . getVal ( ) ; bcolor = new XSSFColor ( rgb ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"Cannot get rgb color error = \" + ex . getLocalizedMessage ( ) , ex ) ; return null ; } int lumOff = 0 ; int lumMod = 0 ; int alphaStr = 0 ; try { lumOff = ctrColor . getLumOffArray ( 0 ) . getVal ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No lumOff entry\" , ex ) ; } try { lumMod = ctrColor . getLumModArray ( 0 ) . getVal ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No lumMod entry\" , ex ) ; } try { alphaStr = ctrColor . getAlphaArray ( 0 ) . getVal ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"No alpha entry\" , ex ) ; } return assembleXcolor ( bcolor , 0 , lumOff , lumMod , alphaStr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get xcolor for automatic fill setting . This is the default setting in Excel for chart colors . Normally the colors will be accent1 to 7 . [CODESPLIT] private static XColor getXColorWithAutomaticFill ( final int index , final ThemesTable themeTable ) { int reminder = ( index + 1 ) % AUTOCOLORSIZE ; if ( reminder == 0 ) { reminder = AUTOCOLORSIZE ; } String schema = AUTOCOLORNAME + reminder ; double tint = getAutomaticTint ( index ) ; return getXColorWithSchema ( schema , tint , null , themeTable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get automatic tint number for specified index line . The default automatic color only have 6 colors . If there are more than 6 lines then use tint for next round e . g . color7 = color1 + tint ( 0 . 25 ) [CODESPLIT] private static double getAutomaticTint ( final int index ) { final double [ ] idxArray = { 0 , 0.25 , 0.5 , - 0.25 , - 0.5 , 0.1 , 0.3 , - 0.1 , - 0.3 } ; int i = index / AUTOCOLORSIZE ; if ( i >= idxArray . length ) { return 0 ; } else { return idxArray [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "convert xssf color to color . [CODESPLIT] public static Color xssfClrToClr ( final XSSFColor xssfColor ) { short [ ] rgb = getTripletFromXSSFColor ( xssfColor ) ; return new Color ( rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return index number for giving index name . e . g . tx1 return 1 . [CODESPLIT] private static int getThemeIndexFromName ( final String idxName ) { final String [ ] idxArray = { \"bg1\" , \"tx1\" , \"bg2\" , \"tx2\" , \"accent1\" , \"accent2\" , \"accent3\" , \"accent4\" , \"accent5\" , \"accent6\" , \"hlink\" , \"folHlink\" } ; try { for ( int i = 0 ; i < idxArray . length ; i ++ ) { if ( idxArray [ i ] . equalsIgnoreCase ( idxName ) ) { return i ; } } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"error in getThemeIndexFromName :\" + ex . getLocalizedMessage ( ) , ex ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert xssfcolor to triple let numbers . [CODESPLIT] public static short [ ] getTripletFromXSSFColor ( final XSSFColor xssfColor ) { short [ ] rgbfix = { RGB8BITS , RGB8BITS , RGB8BITS } ; if ( xssfColor != null ) { byte [ ] rgb = xssfColor . getRGBWithTint ( ) ; if ( rgb == null ) { rgb = xssfColor . getRGB ( ) ; } // Bytes are signed, so values of 128+ are negative!\r // 0: red, 1: green, 2: blue\r rgbfix [ 0 ] = ( short ) ( ( rgb [ 0 ] < 0 ) ? ( rgb [ 0 ] + RGB8BITS ) : rgb [ 0 ] ) ; rgbfix [ 1 ] = ( short ) ( ( rgb [ 1 ] < 0 ) ? ( rgb [ 1 ] + RGB8BITS ) : rgb [ 1 ] ) ; rgbfix [ 2 ] = ( short ) ( ( rgb [ 2 ] < 0 ) ? ( rgb [ 2 ] + RGB8BITS ) : rgb [ 2 ] ) ; } return rgbfix ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the bg color from cell . [CODESPLIT] static String getBgColorFromCell ( final Workbook wb , final Cell poiCell , final CellStyle cellStyle ) { String style = \"\" ; if ( poiCell instanceof HSSFCell ) { int bkColorIndex = cellStyle . getFillForegroundColor ( ) ; HSSFColor color = HSSFColor . getIndexHash ( ) . get ( bkColorIndex ) ; if ( color != null ) { // correct color for customPalette\r HSSFPalette palette = ( ( HSSFWorkbook ) wb ) . getCustomPalette ( ) ; HSSFColor color2 = palette . getColor ( bkColorIndex ) ; if ( ! color . getHexString ( ) . equalsIgnoreCase ( color2 . getHexString ( ) ) ) { color = color2 ; } style = \"background-color:rgb(\" + FacesUtility . strJoin ( color . getTriplet ( ) , \",\" ) + \");\" ; } } else if ( poiCell instanceof XSSFCell ) { XSSFColor color = ( ( XSSFCell ) poiCell ) . getCellStyle ( ) . getFillForegroundColorColor ( ) ; if ( color != null ) { style = \"background-color:rgb(\" + FacesUtility . strJoin ( getTripletFromXSSFColor ( color ) , \",\" ) + \");\" ; } } return style ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find component according it s class . [CODESPLIT] private static String findComponentNameFromClass ( final UIComponent component ) { String cname = component . getClass ( ) . getSimpleName ( ) ; if ( supportComponents . contains ( cname ) ) { return cname ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "populate attributes . [CODESPLIT] public static void populateAttributes ( final UIComponent component , final FacesCell fcell , final Map < String , Map < String , String > > defaultControlMap ) { List < CellFormAttributes > inputAttrs = fcell . getInputAttrs ( ) ; String cname = findComponentNameFromClass ( component ) ; if ( cname == null ) { return ; } Map < String , String > defaultMap = defaultControlMap . get ( cname ) ; if ( defaultMap == null ) { defaultMap = new HashMap <> ( ) ; defaultControlMap . put ( cname , defaultMap ) ; } for ( Map . Entry < String , String > entry : defaultMap . entrySet ( ) ) { setObjectProperty ( component , entry . getKey ( ) , entry . getValue ( ) , true ) ; } for ( CellFormAttributes attr : inputAttrs ) { String propertyName = attr . getType ( ) ; String propertyValue = attr . getValue ( ) ; if ( ! defaultMap . containsKey ( propertyName ) ) { String defaultValue = getObjectPropertyValue ( component , propertyName , true ) ; defaultMap . put ( propertyName , defaultValue ) ; } setObjectProperty ( component , propertyName , propertyValue , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "match parameter of method . [CODESPLIT] private static AttributesType matchParaMeterOfMethod ( final Object obj , final String methodName ) { for ( AttributesType attr : AttributesType . values ( ) ) { try { obj . getClass ( ) . getMethod ( methodName , new Class [ ] { attr . clazz } ) ; return attr ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \" error in matchParaMeterOfMethod = \" + ex . getLocalizedMessage ( ) , ex ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set object property . [CODESPLIT] public static void setObjectProperty ( final Object obj , final String propertyName , final String propertyValue , final boolean ignoreNonExisting ) { try { String methodName = \"set\" + Character . toUpperCase ( propertyName . charAt ( 0 ) ) + propertyName . substring ( 1 ) ; AttributesType parameterType = matchParaMeterOfMethod ( obj , methodName ) ; if ( parameterType != null ) { Method method = obj . getClass ( ) . getMethod ( methodName , new Class [ ] { parameterType . clazz } ) ; method . invoke ( obj , convertToObject ( parameterType , propertyValue ) ) ; } } catch ( Exception e ) { String msg = \"failed to set property '\" + propertyName + \"' to value '\" + propertyValue + \"' for object \" + obj ; if ( ignoreNonExisting ) { LOG . log ( Level . FINE , msg , e ) ; } else { LOG . warning ( msg ) ; throw new IllegalArgumentException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get object property value . [CODESPLIT] public static String getObjectPropertyValue ( final Object obj , final String propertyName , final boolean ignoreNonExisting ) { try { Method method = obj . getClass ( ) . getMethod ( \"get\" + Character . toUpperCase ( propertyName . charAt ( 0 ) ) + propertyName . substring ( 1 ) ) ; return ( String ) method . invoke ( obj ) ; } catch ( Exception e ) { String msg = \"failed to get property '\" + propertyName + \"' for object \" + obj ; if ( ignoreNonExisting ) { LOG . log ( Level . FINE , msg , e ) ; } else { LOG . warning ( msg ) ; throw new IllegalArgumentException ( e ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup control attributes . [CODESPLIT] public static void setupControlAttributes ( final int originRowIndex , final FacesCell fcell , final Cell poiCell , final SheetConfiguration sheetConfig , final CellAttributesMap cellAttributesMap ) { int rowIndex = originRowIndex ; if ( rowIndex < 0 ) { rowIndex = poiCell . getRowIndex ( ) ; } String skey = poiCell . getSheet ( ) . getSheetName ( ) + \"!\" + CellUtility . getCellIndexNumberKey ( poiCell . getColumnIndex ( ) , rowIndex ) ; Map < String , String > commentMap = cellAttributesMap . getTemplateCommentMap ( ) . get ( \"$$\" ) ; if ( commentMap != null ) { String comment = commentMap . get ( skey ) ; if ( comment != null ) { CommandUtility . createCellComment ( poiCell , comment , sheetConfig . getFinalCommentMap ( ) ) ; } } String widgetType = cellAttributesMap . getCellInputType ( ) . get ( skey ) ; if ( widgetType != null ) { fcell . setControl ( widgetType . toLowerCase ( ) ) ; fcell . setInputAttrs ( cellAttributesMap . getCellInputAttributes ( ) . get ( skey ) ) ; fcell . setSelectItemAttrs ( cellAttributesMap . getCellSelectItemsAttributes ( ) . get ( skey ) ) ; fcell . setDatePattern ( cellAttributesMap . getCellDatePattern ( ) . get ( skey ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find cell validate attributes . [CODESPLIT] public static List < CellFormAttributes > findCellValidateAttributes ( final Map < String , List < CellFormAttributes > > validateMaps , final int originRowIndex , final Cell cell ) { String key = cell . getSheet ( ) . getSheetName ( ) + \"!\" + CellUtility . getCellIndexNumberKey ( cell . getColumnIndex ( ) , originRowIndex ) ; return validateMaps . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup faces cell picture charts . [CODESPLIT] public final void setupFacesCellPictureCharts ( final Sheet sheet1 , final FacesCell fcell , final Cell cell , final String fId ) { if ( parent . getPicturesMap ( ) != null ) { setupFacesCellPicture ( sheet1 , fcell , cell , fId ) ; } if ( parent . getCharsData ( ) . getChartsMap ( ) != null ) { setupFacesCellCharts ( sheet1 , fcell , cell , fId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup faces cell charts . [CODESPLIT] private void setupFacesCellCharts ( final Sheet sheet1 , final FacesCell fcell , final Cell cell , final String fId ) { try { String chartId = parent . getCharsData ( ) . getChartPositionMap ( ) . get ( fId ) ; if ( chartId != null ) { BufferedImage img = parent . getCharsData ( ) . getChartsMap ( ) . get ( chartId ) ; if ( img != null ) { fcell . setContainChart ( true ) ; fcell . setChartId ( chartId ) ; fcell . setChartStyle ( PicturesUtility . generateChartStyle ( sheet1 , fcell , cell , chartId , parent . getCharsData ( ) . getChartAnchorsMap ( ) ) ) ; } } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"setupFacesCell Charts error = \" + ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup faces cell picture . [CODESPLIT] private void setupFacesCellPicture ( final Sheet sheet1 , final FacesCell fcell , final Cell cell , final String fId ) { try { Picture pic = parent . getPicturesMap ( ) . get ( fId ) ; if ( pic != null ) { fcell . setContainPic ( true ) ; fcell . setPictureId ( fId ) ; fcell . setPictureStyle ( PicturesUtility . generatePictureStyle ( sheet1 , fcell , cell , pic ) ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"setupFacesCell Picture error = \" + ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initial chart map for specified workbook . [CODESPLIT] private void initChartsMap ( final Workbook wb ) { try { if ( wb instanceof XSSFWorkbook ) { initXSSFChartsMap ( ( XSSFWorkbook ) wb , parent . getCharsData ( ) ) ; } } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"getChartsMap Error Exception = \" + e . getLocalizedMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return cell Value for paredCell . ParsedCell contain sheetName / row / col which normally is parsed from String like : Sheet1!B2 . [CODESPLIT] public final String getParsedCellValue ( final ParsedCell pCell ) { String result = \"\" ; try { Cell poiCell = parent . getWb ( ) . getSheet ( pCell . getSheetName ( ) ) . getRow ( pCell . getRow ( ) ) . getCell ( pCell . getCol ( ) ) ; result = CellUtility . getCellValueWithoutFormat ( poiCell ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"error getParsedCellValue :\" + ex . getLocalizedMessage ( ) , ex ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create default category dataset for JfreeChart with giving chartData . [CODESPLIT] private DefaultPieDataset createPieDataset ( final ChartData chartData ) { DefaultPieDataset dataset = new DefaultPieDataset ( ) ; List < ParsedCell > categoryList = chartData . getCategoryList ( ) ; for ( ChartSeries chartSeries : chartData . getSeriesList ( ) ) { List < ParsedCell > valueList = chartSeries . getValueList ( ) ; for ( int i = 0 ; i < categoryList . size ( ) ; i ++ ) { try { String sCategory = getParsedCellValue ( categoryList . get ( i ) ) ; String sValue = getParsedCellValue ( valueList . get ( i ) ) ; dataset . setValue ( sCategory , Double . parseDouble ( sValue ) ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"error in creatPieDataset : \" + ex . getLocalizedMessage ( ) , ex ) ; } } } return dataset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return pie chart title from chartData . [CODESPLIT] private String getPieTitle ( final ChartData chartData ) { for ( ChartSeries chartSeries : chartData . getSeriesList ( ) ) { if ( chartSeries != null ) { return getParsedCellValue ( chartSeries . getSeriesLabel ( ) ) ; } } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set color of series . [CODESPLIT] public final void setSeriesStyle ( final JFreeChart chart , final int seriesIndex , final String style ) { if ( chart != null && style != null ) { BasicStroke stroke = ChartUtility . toStroke ( style ) ; Plot plot = chart . getPlot ( ) ; if ( plot instanceof CategoryPlot ) { CategoryPlot categoryPlot = chart . getCategoryPlot ( ) ; CategoryItemRenderer cir = categoryPlot . getRenderer ( ) ; try { cir . setSeriesStroke ( seriesIndex , stroke ) ; // series line\r // style\r } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"Error setting style '\" + style + \"' for series '\" + Integer . toString ( seriesIndex ) + \"' of chart '\" + chart . toString ( ) + \"': \" + e . getLocalizedMessage ( ) , e ) ; } } else if ( plot instanceof XYPlot ) { XYPlot xyPlot = chart . getXYPlot ( ) ; XYItemRenderer xyir = xyPlot . getRenderer ( ) ; try { xyir . setSeriesStroke ( seriesIndex , stroke ) ; // series line\r // style\r } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"Error setting style '\" + style + \"' for series '\" + Integer . toString ( seriesIndex ) + \"' of chart '\" + chart . toString ( ) + \"': \" + e . getLocalizedMessage ( ) , e ) ; } } else { LOG . log ( Level . FINE , \"setSeriesColor() unsupported plot: {}\" , plot . toString ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create jfree bar chart . [CODESPLIT] public JFreeChart createAreaChart ( final ChartData chartData ) { PlotOrientation orientation = PlotOrientation . VERTICAL ; // create the chart...\r final JFreeChart chart = ChartFactory . createAreaChart ( chartData . getTitle ( ) , // chart title\r chartData . getCatAx ( ) . getTitle ( ) , // x axis label\r chartData . getValAx ( ) . getTitle ( ) , // y axis label\r createDataset ( chartData ) , // data\r orientation , true , // include legend\r false , // tooltips\r false // urls\r ) ; setupStyle ( chart , chartData ) ; return chart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create jfree bar chart . [CODESPLIT] public JFreeChart createBarChart ( final ChartData chartData , final boolean vertical ) { PlotOrientation orientation = PlotOrientation . VERTICAL ; if ( ! vertical ) { orientation = PlotOrientation . HORIZONTAL ; } // create the chart...\r final JFreeChart chart = ChartFactory . createBarChart ( chartData . getTitle ( ) , // chart title\r chartData . getCatAx ( ) . getTitle ( ) , // x axis label\r chartData . getValAx ( ) . getTitle ( ) , // y axis label\r createDataset ( chartData ) , // data\r orientation , true , // include legend\r false , // tooltips\r false // urls\r ) ; setupBarStyle ( chart , chartData ) ; return chart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create jfree bar chart . [CODESPLIT] public JFreeChart createPieChart ( final ChartData chartData ) { // create the chart...\r final JFreeChart chart = ChartFactory . createPieChart ( getPieTitle ( chartData ) , // chart title\r createPieDataset ( chartData ) , // data\r true , // include legend\r false , // tooltips\r false // urls\r ) ; setupPieStyle ( chart , chartData ) ; return chart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create pie 3d chart . [CODESPLIT] public JFreeChart createPie3DChart ( final ChartData chartData ) { // create the chart...\r final JFreeChart chart = ChartFactory . createPieChart3D ( getPieTitle ( chartData ) , // chart title\r createPieDataset ( chartData ) , // data\r true , // include legend\r false , // tooltips\r false // urls\r ) ; setupPieStyle ( chart , chartData ) ; return chart ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "finalize the style for jfreechart . The default setting is different from jfreechart and Excel . We try to minimize the difference . [CODESPLIT] private void setupStyle ( final JFreeChart chart , final ChartData chartData ) { CategoryPlot plot = ( CategoryPlot ) chart . getPlot ( ) ; List < ChartSeries > seriesList = chartData . getSeriesList ( ) ; BasicStroke bLine = new BasicStroke ( 2.0f ) ; for ( int i = 0 ; i < seriesList . size ( ) ; i ++ ) { Color cColor = ColorUtility . xssfClrToClr ( seriesList . get ( i ) . getSeriesColor ( ) . getXssfColor ( ) ) ; plot . getRenderer ( ) . setSeriesPaint ( i , cColor ) ; plot . getRenderer ( ) . setSeriesStroke ( i , bLine ) ; } plot . setBackgroundPaint ( ColorUtility . xssfClrToClr ( chartData . getBgColor ( ) . getXssfColor ( ) ) ) ; // below are modifications for default setting in excel chart\r // to-do: need read setting from xml in future\r plot . setOutlineVisible ( false ) ; plot . setRangeGridlinesVisible ( true ) ; plot . setRangeGridlinePaint ( Color . BLACK ) ; plot . setRangeGridlineStroke ( new BasicStroke ( TieConstants . DEFAULT_BASIC_STROKE ) ) ; plot . setRangeAxisLocation ( AxisLocation . BOTTOM_OR_LEFT ) ; chart . setBackgroundPaint ( Color . WHITE ) ; LegendTitle legend = chart . getLegend ( ) ; legend . setPosition ( RectangleEdge . RIGHT ) ; legend . setFrame ( BlockBorder . NONE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "finalize the style for jfreechart . The default setting is different from jfreechart and Excel . We try to minimize the difference . [CODESPLIT] private void setupPieStyle ( final JFreeChart chart , final ChartData chartData ) { PiePlot plot = ( PiePlot ) chart . getPlot ( ) ; List < ChartSeries > seriesList = chartData . getSeriesList ( ) ; List < ParsedCell > categoryList = chartData . getCategoryList ( ) ; BasicStroke bLine = new BasicStroke ( 2.0f ) ; for ( int i = 0 ; i < seriesList . size ( ) ; i ++ ) { ChartSeries chartSeries = seriesList . get ( i ) ; List < XColor > valueColorList = chartSeries . getValueColorList ( ) ; for ( int index = 0 ; index < categoryList . size ( ) ; index ++ ) { try { String sCategory = getParsedCellValue ( categoryList . get ( index ) ) ; Color cColor = ColorUtility . xssfClrToClr ( valueColorList . get ( index ) . getXssfColor ( ) ) ; plot . setSectionPaint ( sCategory , cColor ) ; plot . setSectionOutlineStroke ( sCategory , bLine ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"SetupPieStyle error = \" + ex . getLocalizedMessage ( ) , ex ) ; } } } plot . setBackgroundPaint ( ColorUtility . xssfClrToClr ( chartData . getBgColor ( ) . getXssfColor ( ) ) ) ; // below are modifications for default setting in excel chart\r // to-do: need read setting from xml in future\r plot . setOutlineVisible ( false ) ; plot . setLegendItemShape ( new Rectangle ( TieConstants . DEFAULT_LEGENT_ITEM_SHAPE_WIDTH , TieConstants . DEFAULT_LEGENT_ITEM_SHAPE_HEIGHT ) ) ; chart . setBackgroundPaint ( Color . WHITE ) ; LegendTitle legend = chart . getLegend ( ) ; legend . setPosition ( RectangleEdge . RIGHT ) ; legend . setFrame ( BlockBorder . NONE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "finalize the style for barchart . This will call setupStyle common first . [CODESPLIT] private void setupBarStyle ( final JFreeChart chart , final ChartData chartData ) { setupStyle ( chart , chartData ) ; CategoryPlot plot = ( CategoryPlot ) chart . getPlot ( ) ; BarRenderer renderer = ( BarRenderer ) plot . getRenderer ( ) ; renderer . setBarPainter ( new StandardBarPainter ( ) ) ; renderer . setItemMargin ( TieConstants . DEFAULT_BAR_STYLE_ITEM_MARGIN ) ; plot . setForegroundAlpha ( TieConstants . DEFAULT_BARSTYLE_FOREGROUND_ALPHA ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create default category dataset for JfreeChart with giving chartData . [CODESPLIT] private DefaultCategoryDataset createDataset ( final ChartData chartData ) { DefaultCategoryDataset dataset = new DefaultCategoryDataset ( ) ; List < ParsedCell > categoryList = chartData . getCategoryList ( ) ; for ( ChartSeries chartSeries : chartData . getSeriesList ( ) ) { String seriesLabel = getParsedCellValue ( chartSeries . getSeriesLabel ( ) ) ; List < ParsedCell > valueList = chartSeries . getValueList ( ) ; for ( int i = 0 ; i < categoryList . size ( ) ; i ++ ) { try { String sCategory = getParsedCellValue ( categoryList . get ( i ) ) ; String sValue = getParsedCellValue ( valueList . get ( i ) ) ; dataset . addValue ( Double . parseDouble ( sValue ) , seriesLabel , sCategory ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"error in creatDataset : \" + ex . getLocalizedMessage ( ) , ex ) ; } } } return dataset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initial chart map for XSSF format file . XSSF file is actually the only format in POI support chart object . [CODESPLIT] private void initXSSFChartsMap ( final XSSFWorkbook wb , final ChartsData chartsData ) { initAnchorsMap ( wb , chartsData ) ; Map < String , ClientAnchor > anchorMap = chartsData . getChartAnchorsMap ( ) ; Map < String , BufferedImage > chartMap = chartsData . getChartsMap ( ) ; Map < String , ChartData > chartDataMap = chartsData . getChartDataMap ( ) ; chartMap . clear ( ) ; chartDataMap . clear ( ) ; for ( int i = 0 ; i < wb . getNumberOfSheets ( ) ; i ++ ) { XSSFSheet sheet = wb . getSheetAt ( i ) ; XSSFDrawing drawing = sheet . createDrawingPatriarch ( ) ; List < XSSFChart > charts = drawing . getCharts ( ) ; if ( ( charts != null ) && ( ! charts . isEmpty ( ) ) ) { for ( XSSFChart chart : charts ) { generateSingleXSSFChart ( chart , getChartIdFromParent ( chart , sheet . getSheetName ( ) ) , sheet , anchorMap , chartMap , chartDataMap ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the chart id from parent . [CODESPLIT] private String getChartIdFromParent ( final XSSFChart chart , final String sheetName ) { if ( chart . getParent ( ) != null ) { for ( RelationPart rp : chart . getParent ( ) . getRelationParts ( ) ) { if ( rp . getDocumentPart ( ) == chart ) { return sheetName + \"!\" + rp . getRelationship ( ) . getId ( ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "initial anchors map for specified workbook . Excel put the chart position information in draw . xml instead of chart . xml . anchors map contains the information getting from draw . xml . [CODESPLIT] private void initAnchorsMap ( final Workbook wb , final ChartsData chartsData ) { try { if ( wb instanceof XSSFWorkbook ) { ChartUtility . initXSSFAnchorsMap ( ( XSSFWorkbook ) wb , chartsData ) ; } } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"Web Form getAnchorsMap Error Exception = \" + e . getLocalizedMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate single XSSF chart . [CODESPLIT] private void generateSingleXSSFChart ( final XSSFChart chart , final String chartId , final XSSFSheet sheet , final Map < String , ClientAnchor > anchorMap , final Map < String , BufferedImage > chartMap , final Map < String , ChartData > chartDataMap ) { ClientAnchor anchor ; try { anchor = anchorMap . get ( chartId ) ; if ( anchor != null ) { ChartData chartData = ChartUtility . initChartDataFromXSSFChart ( chartId , chart , ( XSSFWorkbook ) parent . getWb ( ) ) ; chartDataMap . put ( chartId , chartData ) ; JFreeChart jchart = createChart ( chartData ) ; if ( jchart != null ) { AnchorSize anchorSize = PicturesUtility . getAnchorSize ( sheet , null , null , anchor ) ; BufferedImage img = jchart . createBufferedImage ( anchorSize . getWidth ( ) , anchorSize . getHeight ( ) ) ; chartMap . put ( chartId , img ) ; } } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"generate chart for \" + chartId + \" error = \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform to collection object . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static Collection transformToCollectionObject ( final ExpressionEngine engine , final String collectionName , final Map < String , Object > context ) { Object collectionObject = engine . evaluate ( collectionName , context ) ; if ( ! ( collectionObject instanceof Collection ) ) { throw new EvaluationException ( collectionName + \" expression is not a collection\" ) ; } return ( Collection ) collectionObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the full name from row . [CODESPLIT] public static String getFullNameFromRow ( final Row row ) { if ( row != null ) { Cell cell = row . getCell ( TieConstants . HIDDEN_FULL_NAME_COLUMN ) ; if ( cell != null ) { return cell . getStringCellValue ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Re build upper level formula . [CODESPLIT] public static void reBuildUpperLevelFormula ( final ConfigBuildRef configBuildRef , final String actionFullName ) { Map < Cell , String > cachedMap = configBuildRef . getCachedCells ( ) ; Map < String , List < RowsMapping > > rowsMap = new HashMap <> ( ) ; for ( Map . Entry < Cell , String > entry : cachedMap . entrySet ( ) ) { Cell cell = entry . getKey ( ) ; String originFormula = entry . getValue ( ) ; if ( originFormula != null ) { setupUpperLevelFormula ( cell , originFormula , actionFullName , rowsMap , configBuildRef ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup upper level formula . [CODESPLIT] private static void setupUpperLevelFormula ( final Cell cell , final String originFormula , final String actionFullName , final Map < String , List < RowsMapping > > rowsMap , final ConfigBuildRef configBuildRef ) { String fullName = getFullNameFromRow ( cell . getRow ( ) ) ; // check wither it's upper level\r if ( actionFullName . startsWith ( fullName + \":\" ) ) { // get rows mapping for upper level row\r List < RowsMapping > currentRowsMappingList = rowsMap . get ( fullName ) ; if ( currentRowsMappingList == null ) { currentRowsMappingList = gatherRowsMappingByFullName ( configBuildRef , fullName ) ; rowsMap . put ( fullName , currentRowsMappingList ) ; } ShiftFormulaRef shiftFormulaRef = new ShiftFormulaRef ( configBuildRef . getWatchList ( ) , currentRowsMappingList ) ; shiftFormulaRef . setFormulaChanged ( 0 ) ; buildCellFormulaForShiftedRows ( configBuildRef . getSheet ( ) , configBuildRef . getWbWrapper ( ) , shiftFormulaRef , cell , originFormula ) ; if ( shiftFormulaRef . getFormulaChanged ( ) > 0 ) { configBuildRef . getCachedCells ( ) . put ( cell , originFormula ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the cell formula for shifted rows . [CODESPLIT] public static void buildCellFormulaForShiftedRows ( final Sheet sheet , final XSSFEvaluationWorkbook wbWrapper , final ShiftFormulaRef shiftFormulaRef , final Cell cell , final String originFormula ) { // only shift when there's watchlist exist.\r if ( ( shiftFormulaRef . getWatchList ( ) != null ) && ( ! shiftFormulaRef . getWatchList ( ) . isEmpty ( ) ) ) { Ptg [ ] ptgs = FormulaParser . parse ( originFormula , wbWrapper , FormulaType . CELL , sheet . getWorkbook ( ) . getSheetIndex ( sheet ) ) ; Ptg [ ] convertedFormulaPtg = ShiftFormulaUtility . convertSharedFormulas ( ptgs , shiftFormulaRef ) ; if ( shiftFormulaRef . getFormulaChanged ( ) > 0 ) { // only change formula when indicator is true\r cell . setCellFormula ( FormulaRenderer . toFormulaString ( wbWrapper , convertedFormulaPtg ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gather rows mapping by full name . [CODESPLIT] public static List < RowsMapping > gatherRowsMappingByFullName ( final ConfigBuildRef configBuildRef , final String fullName ) { List < RowsMapping > list = new ArrayList <> ( ) ; Map < String , ConfigRangeAttrs > shiftMap = configBuildRef . getShiftMap ( ) ; for ( Map . Entry < String , ConfigRangeAttrs > entry : shiftMap . entrySet ( ) ) { String fname = entry . getKey ( ) ; if ( fname . startsWith ( fullName + \":\" ) || fname . equals ( fullName ) ) { ConfigRangeAttrs attrs = entry . getValue ( ) ; list . add ( attrs . getUnitRowsMapping ( ) ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increase index number in shift map . [CODESPLIT] public static void changeIndexNumberInShiftMap ( final Map < String , ConfigRangeAttrs > shiftMap , final Map < String , String > changeMap ) { for ( Map . Entry < String , String > entry : changeMap . entrySet ( ) ) { String key = entry . getKey ( ) ; String newKey = entry . getValue ( ) ; ConfigRangeAttrs attrs = shiftMap . get ( key ) ; if ( attrs != null ) { shiftMap . remove ( key ) ; shiftMap . put ( newKey , attrs ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increase upper level final length . [CODESPLIT] public static void changeUpperLevelFinalLength ( final Map < String , ConfigRangeAttrs > shiftMap , final String addedFullName , final int increasedLength ) { String [ ] parts = addedFullName . split ( \":\" ) ; StringBuilder fname = new StringBuilder ( ) ; for ( int i = 0 ; i < ( parts . length - 1 ) ; i ++ ) { if ( i == 0 ) { fname . append ( parts [ i ] ) ; } else { fname . append ( \":\" ) . append ( parts [ i ] ) ; } String sname = fname . toString ( ) ; shiftMap . get ( sname ) . setFinalLength ( shiftMap . get ( sname ) . getFinalLength ( ) + increasedLength ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change index number in hidden column . [CODESPLIT] public static void changeIndexNumberInHiddenColumn ( final ConfigBuildRef configBuildRef , final int startRowIndex , final String fullName , final Map < String , String > changeMap , final int steps ) { String searchName = fullName . substring ( 0 , fullName . lastIndexOf ( ' ' ) + 1 ) ; Sheet sheet = configBuildRef . getSheet ( ) ; for ( int i = startRowIndex ; i <= sheet . getLastRowNum ( ) ; i ++ ) { Row row = sheet . getRow ( i ) ; String fname = getFullNameFromRow ( row ) ; if ( ( fname != null ) && ( fname . indexOf ( searchName ) >= 0 ) ) { int sindex = fname . indexOf ( searchName ) ; String snum = fname . substring ( sindex + searchName . length ( ) ) ; int sufindex = snum . indexOf ( ' ' ) ; String suffix = \"\" ; if ( sufindex > 0 ) { snum = snum . substring ( 0 , sufindex ) ; suffix = \":\" ; } int increaseNum = Integer . parseInt ( snum ) + steps ; String realFullName = fname . substring ( sindex ) ; String changeName = fname . replace ( searchName + snum + suffix , searchName + increaseNum + suffix ) ; if ( changeMap . get ( realFullName ) == null ) { changeMap . put ( realFullName , changeName . substring ( sindex ) ) ; } setFullNameInHiddenColumn ( row , changeName ) ; } else { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the full name in hidden column . [CODESPLIT] public static void setFullNameInHiddenColumn ( final Row row , final String fullName ) { Cell cell = row . getCell ( TieConstants . HIDDEN_FULL_NAME_COLUMN , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; cell . setCellValue ( fullName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the original row num in hidden column . [CODESPLIT] public static int getOriginalRowNumInHiddenColumn ( final Row row ) { if ( row != null ) { Cell cell = row . getCell ( TieConstants . HIDDEN_ORIGIN_ROW_NUMBER_COLUMN , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; String rowNum = cell . getStringCellValue ( ) ; try { if ( ( rowNum != null ) && ( ! rowNum . isEmpty ( ) ) && ( WebSheetUtility . isNumeric ( rowNum ) ) ) { return Integer . parseInt ( rowNum ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"getOriginalRowNumInHiddenColumn rowNum = \" + rowNum + \" error = \" + ex . getLocalizedMessage ( ) , ex ) ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the original row num in hidden column . [CODESPLIT] public static void setOriginalRowNumInHiddenColumn ( final Row row , final int rowNum ) { Cell cell = row . getCell ( TieConstants . HIDDEN_ORIGIN_ROW_NUMBER_COLUMN , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; cell . setCellValue ( Integer . toString ( rowNum ) ) ; cell . setCellType ( CellType . STRING ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find parent rows mapping from shift map . [CODESPLIT] public static List < RowsMapping > findParentRowsMappingFromShiftMap ( final String [ ] parts , final Map < String , ConfigRangeAttrs > shiftMap ) { StringBuilder fullName = new StringBuilder ( ) ; List < RowsMapping > rowsMappingList = new ArrayList <> ( ) ; /**\r\n\t\t * skip first one and last one. first one is line no. last one is it's\r\n\t\t * self.\r\n\t\t */ for ( int i = 1 ; i < parts . length - 1 ; i ++ ) { String part = parts [ i ] ; if ( fullName . length ( ) == 0 ) { fullName . append ( part ) ; } else { fullName . append ( \":\" + part ) ; } if ( fullName . length ( ) > 0 ) { ConfigRangeAttrs rangeAttrs = shiftMap . get ( fullName . toString ( ) ) ; if ( rangeAttrs != null ) { rowsMappingList . add ( rangeAttrs . getUnitRowsMapping ( ) ) ; } } } return rowsMappingList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find child rows mapping from shift map . [CODESPLIT] public static List < RowsMapping > findChildRowsMappingFromShiftMap ( final String fullName , final NavigableMap < String , ConfigRangeAttrs > shiftMap ) { List < RowsMapping > rowsMappingList = new ArrayList <> ( ) ; NavigableMap < String , ConfigRangeAttrs > tailmap = shiftMap . tailMap ( fullName , false ) ; for ( Map . Entry < String , ConfigRangeAttrs > entry : tailmap . entrySet ( ) ) { String key = entry . getKey ( ) ; // check it's children\r if ( key . startsWith ( fullName ) ) { rowsMappingList . add ( entry . getValue ( ) . getUnitRowsMapping ( ) ) ; } else { break ; } } return rowsMappingList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find item in collection . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static Object findItemInCollection ( final Collection collection , final int index ) { if ( index >= 0 ) { if ( collection instanceof List ) { List list = ( List ) collection ; return list . get ( index ) ; } int i = 0 ; for ( Object object : collection ) { if ( i == index ) { return object ; } i ++ ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the current range . [CODESPLIT] public static ConfigRange buildCurrentRange ( final ConfigRange sourceConfigRange , final Sheet sheet , final int insertPosition ) { ConfigRange current = new ConfigRange ( sourceConfigRange ) ; int shiftNum = insertPosition - sourceConfigRange . getFirstRowAddr ( ) . getRow ( ) ; current . shiftRowRef ( sheet , shiftNum ) ; return current ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Whether the row is static . This only check rowIndex against original template . [CODESPLIT] public static boolean isStaticRow ( final ConfigRange sourceConfigRange , final int rowIndex ) { if ( sourceConfigRange . getCommandList ( ) != null ) { for ( int i = 0 ; i < sourceConfigRange . getCommandList ( ) . size ( ) ; i ++ ) { Command command = sourceConfigRange . getCommandList ( ) . get ( i ) ; if ( ( rowIndex >= command . getConfigRange ( ) . getFirstRowAddr ( ) . getRow ( ) ) && ( rowIndex < ( command . getConfigRange ( ) . getLastRowPlusAddr ( ) . getRow ( ) ) ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Whether the row is static . This check row after shifted . [CODESPLIT] public static boolean isStaticRowRef ( final ConfigRange sourceConfigRange , final Row row ) { if ( sourceConfigRange . getCommandList ( ) != null ) { for ( int i = 0 ; i < sourceConfigRange . getCommandList ( ) . size ( ) ; i ++ ) { Command command = sourceConfigRange . getCommandList ( ) . get ( i ) ; int rowIndex = row . getRowNum ( ) ; if ( ( rowIndex >= command . getTopRow ( ) ) && ( rowIndex < ( command . getTopRow ( ) + command . getFinalLength ( ) ) ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove last each command index from full name . e . g . for F . departments : E . department . 1 : E . employee . 2 will return F . departments : E . department . 1 : E . employee [CODESPLIT] public static String getFullDataCollectNameFromFullName ( final String fullName ) { if ( fullName == null ) { return \"\" ; } int lastEachCommandPos = fullName . lastIndexOf ( TieConstants . EACH_COMMAND_FULL_NAME_PREFIX ) ; if ( lastEachCommandPos < 0 ) { return \"\" ; } int lastEachCommandIndexPos = fullName . indexOf ( ' ' , lastEachCommandPos + TieConstants . EACH_COMMAND_FULL_NAME_PREFIX . length ( ) ) ; if ( lastEachCommandIndexPos < 0 ) { return fullName ; } return fullName . substring ( 0 , lastEachCommandIndexPos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "100 > = 80 [CODESPLIT] public static String replaceExpressionWithCellValue ( final String attrValue , final int rowIndex , final Sheet sheet ) { int ibegin = 0 ; int ifind ; int inameEnd ; String tempStr ; String findStr ; String replaceStr ; String returnStr = attrValue ; while ( ( ifind = attrValue . indexOf ( TieConstants . CELL_ADDR_PRE_FIX , ibegin ) ) > 0 ) { inameEnd = ParserUtility . findFirstNonCellNamePosition ( attrValue , ifind ) ; if ( inameEnd > 0 ) { findStr = attrValue . substring ( ifind , inameEnd ) ; } else { findStr = attrValue . substring ( ifind ) ; } if ( findStr . indexOf ( TieConstants . CELL_ADDR_PRE_FIX , 1 ) < 0 ) { // only $A\r tempStr = findStr + TieConstants . CELL_ADDR_PRE_FIX + ( rowIndex + 1 ) ; } else { tempStr = findStr ; } replaceStr = CellUtility . getCellValueWithoutFormat ( WebSheetUtility . getCellByReference ( tempStr , sheet ) ) ; if ( replaceStr == null ) { replaceStr = \"\" ; } returnStr = attrValue . replace ( findStr , replaceStr ) ; ibegin = ifind + 1 ; } return returnStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index merged region . [CODESPLIT] public static Map < String , CellRangeAddress > indexMergedRegion ( final Sheet sheet1 ) { int numRegions = sheet1 . getNumMergedRegions ( ) ; Map < String , CellRangeAddress > cellRangeMap = new HashMap <> ( ) ; for ( int i = 0 ; i < numRegions ; i ++ ) { CellRangeAddress caddress = sheet1 . getMergedRegion ( i ) ; if ( caddress != null ) { cellRangeMap . put ( CellUtility . getCellIndexNumberKey ( caddress . getFirstColumn ( ) , caddress . getFirstRow ( ) ) , caddress ) ; } } return cellRangeMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skipped region cells . [CODESPLIT] public static List < String > skippedRegionCells ( final Sheet sheet1 ) { int numRegions = sheet1 . getNumMergedRegions ( ) ; List < String > skipCellList = new ArrayList <> ( ) ; for ( int i = 0 ; i < numRegions ; i ++ ) { CellRangeAddress caddress = sheet1 . getMergedRegion ( i ) ; if ( caddress != null ) { addSkipCellToListInTheRegion ( skipCellList , caddress ) ; } } return skipCellList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add skipped cell into the list of a region . [CODESPLIT] private static void addSkipCellToListInTheRegion ( final List < String > skipCellList , final CellRangeAddress caddress ) { for ( int col = caddress . getFirstColumn ( ) ; col <= caddress . getLastColumn ( ) ; col ++ ) { for ( int row = caddress . getFirstRow ( ) ; row <= caddress . getLastRow ( ) ; row ++ ) { if ( ( col == caddress . getFirstColumn ( ) ) && ( row == caddress . getFirstRow ( ) ) ) { continue ; } skipCellList . add ( CellUtility . getCellIndexNumberKey ( col , row ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build Sheet Comment From command alias . [CODESPLIT] public static void buildSheetCommentFromAlias ( Sheet sheet , List < TieCommandAlias > tieCommandAliasList ) { if ( ( tieCommandAliasList == null ) || ( tieCommandAliasList . isEmpty ( ) ) ) { return ; } for ( Row row : sheet ) { for ( Cell cell : row ) { buildCellCommentFromalias ( tieCommandAliasList , cell ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the cell comment fromalias . [CODESPLIT] private static void buildCellCommentFromalias ( List < TieCommandAlias > tieCommandAliasList , Cell cell ) { String value = CellUtility . getCellValueWithoutFormat ( cell ) ; if ( ( value != null ) && ( ! value . isEmpty ( ) ) ) { for ( TieCommandAlias alias : tieCommandAliasList ) { Matcher matcher = alias . getPattern ( ) . matcher ( value ) ; if ( matcher . find ( ) ) { CellUtility . createOrInsertComment ( cell , alias . getCommand ( ) ) ; if ( alias . isRemove ( ) ) { CellUtility . setCellValue ( cell , ParserUtility . removeCharsFromString ( value , matcher . start ( ) , matcher . end ( ) ) ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the configuration . [CODESPLIT] public final Map < String , SheetConfiguration > buildConfiguration ( ) { Map < String , SheetConfiguration > sheetConfigMap = new LinkedHashMap <> ( ) ; // in buildsheet, it's possible to add sheets in workbook.\r // so cache the sheetname first here.\r List < String > sheetNames = new ArrayList <> ( ) ; String sname ; for ( int i = 0 ; i < parent . getWb ( ) . getNumberOfSheets ( ) ; i ++ ) { sname = parent . getWb ( ) . getSheetName ( i ) ; if ( ! sname . startsWith ( org . tiefaces . common . TieConstants . COPY_SHEET_PREFIX ) ) { sheetNames . add ( sname ) ; } } for ( String sheetName : sheetNames ) { Sheet sheet = parent . getWb ( ) . getSheet ( sheetName ) ; ConfigurationUtility . buildSheetCommentFromAlias ( sheet , parent . getTieCommandAliasList ( ) ) ; buildSheet ( sheet , sheetConfigMap , parent . getCellAttributesMap ( ) ) ; } return sheetConfigMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the sheet configuration . [CODESPLIT] private SheetConfiguration getSheetConfiguration ( final Sheet sheet , final String formName , final int sheetRightCol ) { SheetConfiguration sheetConfig = new SheetConfiguration ( ) ; sheetConfig . setFormName ( formName ) ; sheetConfig . setSheetName ( sheet . getSheetName ( ) ) ; int leftCol = sheet . getLeftCol ( ) ; int lastRow = sheet . getLastRowNum ( ) ; int firstRow = sheet . getFirstRowNum ( ) ; int rightCol = 0 ; int maxRow = 0 ; for ( Row row : sheet ) { if ( row . getRowNum ( ) > TieConstants . TIE_WEB_SHEET_MAX_ROWS ) { break ; } maxRow = row . getRowNum ( ) ; int firstCellNum = row . getFirstCellNum ( ) ; if ( firstCellNum >= 0 && firstCellNum < leftCol ) { leftCol = firstCellNum ; } if ( ( row . getLastCellNum ( ) - 1 ) > rightCol ) { int verifiedcol = verifyLastCell ( row , rightCol , sheetRightCol ) ; if ( verifiedcol > rightCol ) { rightCol = verifiedcol ; } } } if ( maxRow < lastRow ) { lastRow = maxRow ; } // header range row set to 0 while column set to first column to\r // max\r // column (FF) e.g. $A$0 : $FF$0\r String tempStr = TieConstants . CELL_ADDR_PRE_FIX + WebSheetUtility . getExcelColumnName ( leftCol ) + TieConstants . CELL_ADDR_PRE_FIX + \"0 : \" + TieConstants . CELL_ADDR_PRE_FIX + WebSheetUtility . getExcelColumnName ( rightCol ) + TieConstants . CELL_ADDR_PRE_FIX + \"0\" ; sheetConfig . setFormHeaderRange ( tempStr ) ; sheetConfig . setHeaderCellRange ( new CellRange ( tempStr ) ) ; // body range row set to first row to last row while column set\r // to\r // first column to max column (FF) e.g. $A$1 : $FF$1000\r tempStr = TieConstants . CELL_ADDR_PRE_FIX + WebSheetUtility . getExcelColumnName ( leftCol ) + TieConstants . CELL_ADDR_PRE_FIX + ( firstRow + 1 ) + \" : \" + TieConstants . CELL_ADDR_PRE_FIX + WebSheetUtility . getExcelColumnName ( rightCol ) + TieConstants . CELL_ADDR_PRE_FIX + ( lastRow + 1 ) ; sheetConfig . setFormBodyRange ( tempStr ) ; sheetConfig . setBodyCellRange ( new CellRange ( tempStr ) ) ; sheetConfig . setFormBodyType ( org . tiefaces . common . TieConstants . FORM_TYPE_FREE ) ; sheetConfig . setCellFormAttributes ( new HashMap < String , List < CellFormAttributes > > ( ) ) ; // check it's a hidden sheet\r int sheetIndex = parent . getWb ( ) . getSheetIndex ( sheet ) ; if ( parent . getWb ( ) . isSheetHidden ( sheetIndex ) || parent . getWb ( ) . isSheetVeryHidden ( sheetIndex ) ) { sheetConfig . setHidden ( true ) ; } return sheetConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the form command from sheet config . [CODESPLIT] private FormCommand buildFormCommandFromSheetConfig ( final SheetConfiguration sheetConfig , final Sheet sheet ) { int firstRow = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int leftCol = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int rightCol = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; int lastRow = sheetConfig . getBodyCellRange ( ) . getBottomRow ( ) ; Cell firstCell = sheet . getRow ( firstRow ) . getCell ( leftCol , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; FormCommand fcommand = new FormCommand ( ) ; fcommand . setCommandTypeName ( TieConstants . COMMAND_FORM ) ; if ( sheetConfig . isHidden ( ) ) { fcommand . setHidden ( TieConstants . TRUE_STRING ) ; } else { fcommand . setHidden ( TieConstants . FALSE_STRING ) ; } fcommand . setName ( sheetConfig . getFormName ( ) ) ; fcommand . getConfigRange ( ) . setFirstRowRef ( firstCell , true ) ; fcommand . getConfigRange ( ) . setLastRowPlusRef ( sheet , rightCol , lastRow , true ) ; fcommand . setHeaderLength ( \"0\" ) ; fcommand . setFooterLength ( \"0\" ) ; fcommand . setLength ( Integer . toString ( lastRow - firstRow + 1 ) ) ; return fcommand ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check last column . if it s blank then treat it as null cell . [CODESPLIT] private int verifyLastCell ( final Row row , final int stoppoint , final int sheetRightCol ) { int lastCol = sheetRightCol ; int col ; for ( col = lastCol ; col >= stoppoint ; col -- ) { Cell cell = row . getCell ( col ) ; if ( ( cell != null ) && ( cell . getCellTypeEnum ( ) != CellType . BLANK ) ) { break ; } } return col ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build a sheet for configuration map . [CODESPLIT] public final void buildSheet ( final Sheet sheet , final Map < String , SheetConfiguration > sheetConfigMap , final CellAttributesMap cellAttributesMap ) { if ( ( sheet . getLastRowNum ( ) <= 0 ) && ( sheet . getRow ( 0 ) == null ) ) { // this is a empty sheet. skip it.\r return ; } checkAndRepairLastRow ( sheet ) ; int sheetRightCol = WebSheetUtility . getSheetRightCol ( sheet ) ; List < ConfigCommand > commandList = buildCommandListFromSheetComment ( ( XSSFSheet ) sheet , sheetRightCol , cellAttributesMap ) ; boolean hasEachCommand = hasEachCommandInTheList ( commandList ) ; List < String > formList = new ArrayList <> ( ) ; buildSheetConfigMapFromFormCommand ( sheet , sheetConfigMap , commandList , formList , sheetRightCol ) ; // match parent command\r matchParentCommand ( commandList ) ; // setup save attrs in hidden column in the sheet.\r // loop command list again to assemble other command list into sheet\r // configuration\r matchSheetConfigForm ( sheetConfigMap , commandList , formList ) ; initTemplateForCommand ( sheet , sheetConfigMap , formList , hasEachCommand ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check and repair the sheet s lastrow . If the row is blank then remove it . [CODESPLIT] private final void checkAndRepairLastRow ( final Sheet sheet ) { // repair last row if it's inserted in the configuration generation\r Row lastrow = sheet . getRow ( sheet . getLastRowNum ( ) ) ; // if it's lastrow and all the cells are blank. then remove the lastrow.\r if ( lastrow != null ) { for ( Cell cell : lastrow ) { if ( ( cell . getCellTypeEnum ( ) != CellType . _NONE ) && ( cell . getCellTypeEnum ( ) != CellType . BLANK ) ) { return ; } } sheet . removeRow ( lastrow ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize template for command to use . e . g . set origin row number and copy template if there s each command . create missing row as row require sequenced . [CODESPLIT] private void initTemplateForCommand ( final Sheet sheet , final Map < String , SheetConfiguration > sheetConfigMap , final List < String > formList , final boolean hasEachCommand ) { for ( String formname : formList ) { SheetConfiguration sheetConfig = sheetConfigMap . get ( formname ) ; CellRange range = sheetConfig . getBodyCellRange ( ) ; for ( int index = range . getTopRow ( ) ; index <= range . getBottomRow ( ) ; index ++ ) { Row row = sheet . getRow ( index ) ; if ( row == null ) { row = sheet . createRow ( index ) ; } if ( hasEachCommand ) { ConfigurationUtility . setOriginalRowNumInHiddenColumn ( row , index ) ; } } } if ( hasEachCommand ) { copyTemplateForTieCommands ( sheet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build command list from comments . after transfer the comment to command remove it from comments . [CODESPLIT] private List < ConfigCommand > buildCommandListFromSheetComment ( final XSSFSheet sheet , final int sheetRightCol , final CellAttributesMap cellAttributesMap ) { List < ConfigCommand > commandList = new ArrayList <> ( ) ; // if skip then return empty list.\r if ( parent . isSkipConfiguration ( ) ) { return commandList ; } Map < CellAddress , ? extends Comment > comments = null ; try { // due to a poi bug. null exception throwed if no comments in the\r // sheet.\r comments = sheet . getCellComments ( ) ; } catch ( Exception ex ) { LOG . log ( Level . FINE , \"Null exception throwed when no comment exists: \" + ex . getLocalizedMessage ( ) , ex ) ; } if ( comments == null ) { return commandList ; } // not sure the map is sorted. So use tree map to sort it.\r SortedSet < CellAddress > keys = new TreeSet <> ( comments . keySet ( ) ) ; // go through each comments\r // if found tie command then transfer it to list also remove from\r // comments.\r for ( CellAddress key : keys ) { Cell cell = sheet . getRow ( key . getRow ( ) ) . getCell ( key . getColumn ( ) , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; buildCommandList ( sheet , sheetRightCol , cell , commandList , cellAttributesMap ) ; } return commandList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build top level configuration map from command list . User can either put tie : form command in the comments ( which will transfer to sheetConfig ) Or just ignore it then use whole sheet as one form . [CODESPLIT] private void buildSheetConfigMapFromFormCommand ( final Sheet sheet , final Map < String , SheetConfiguration > sheetConfigMap , final List < ConfigCommand > commandList , final List < String > formList , final int sheetRightCol ) { boolean foundForm = false ; int minRowNum = sheet . getLastRowNum ( ) ; int maxRowNum = sheet . getFirstRowNum ( ) ; for ( Command command : commandList ) { // check whether is form command\r if ( command . getCommandTypeName ( ) . equalsIgnoreCase ( TieConstants . COMMAND_FORM ) ) { foundForm = true ; FormCommand fcommand = ( FormCommand ) command ; sheetConfigMap . put ( fcommand . getName ( ) , getSheetConfigurationFromConfigCommand ( sheet , fcommand , sheetRightCol ) ) ; formList . add ( fcommand . getName ( ) ) ; if ( fcommand . getTopRow ( ) < minRowNum ) { minRowNum = fcommand . getTopRow ( ) ; } if ( fcommand . getLastRow ( ) > maxRowNum ) { maxRowNum = fcommand . getLastRow ( ) ; } } } // if no form found, then use the whole sheet as form\r if ( ! foundForm ) { WebSheetUtility . clearHiddenColumns ( sheet ) ; String formName = sheet . getSheetName ( ) ; SheetConfiguration sheetConfig = getSheetConfiguration ( sheet , formName , sheetRightCol ) ; FormCommand fcommand = buildFormCommandFromSheetConfig ( sheetConfig , sheet ) ; commandList . add ( fcommand ) ; sheetConfig . setFormCommand ( fcommand ) ; sheetConfigMap . put ( formName , sheetConfig ) ; formList . add ( formName ) ; minRowNum = sheet . getFirstRowNum ( ) ; maxRowNum = sheet . getLastRowNum ( ) ; } // if skip config then return.\r if ( parent . isSkipConfiguration ( ) ) { return ; } SaveAttrsUtility . setSaveAttrsForSheet ( sheet , minRowNum , maxRowNum , parent . getCellAttributesMap ( ) . getTemplateCommentMap ( ) . get ( TieConstants . SAVE_COMMENT_KEY_IN_MAP ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set up parent attribute for each command ( exclude form command ) . The top level commands have no parent . [CODESPLIT] private void matchParentCommand ( final List < ConfigCommand > commandList ) { if ( commandList == null ) { return ; } for ( int i = 0 ; i < commandList . size ( ) ; i ++ ) { ConfigCommand child = commandList . get ( i ) ; if ( ! child . getCommandTypeName ( ) . equalsIgnoreCase ( TieConstants . COMMAND_FORM ) ) { setParentForChildCommand ( commandList , i , child ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the parent for child command . [CODESPLIT] private void setParentForChildCommand ( final List < ConfigCommand > commandList , final int i , final ConfigCommand child ) { int matchIndex = - 1 ; ConfigRange matchRange = null ; for ( int j = 0 ; j < commandList . size ( ) ; j ++ ) { if ( j != i ) { Command commandParent = commandList . get ( j ) ; if ( ! commandParent . getCommandTypeName ( ) . equalsIgnoreCase ( TieConstants . COMMAND_FORM ) && WebSheetUtility . insideRange ( child . getConfigRange ( ) , commandParent . getConfigRange ( ) ) && ( ( matchRange == null ) || ( WebSheetUtility . insideRange ( commandParent . getConfigRange ( ) , matchRange ) ) ) ) { matchRange = commandParent . getConfigRange ( ) ; matchIndex = j ; } } } if ( matchIndex >= 0 ) { commandList . get ( matchIndex ) . getConfigRange ( ) . addCommand ( child ) ; child . setParentFound ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check whether contain each command in the list . [CODESPLIT] private boolean hasEachCommandInTheList ( final List < ConfigCommand > commandList ) { if ( commandList != null ) { for ( ConfigCommand command : commandList ) { if ( command . getCommandTypeName ( ) . equalsIgnoreCase ( TieConstants . COMMAND_EACH ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble top level command to sheetConfiguration ( form ) . top level commands are those haven t matched from matchParentCommand function . [CODESPLIT] private void matchSheetConfigForm ( final Map < String , SheetConfiguration > sheetConfigMap , final List < ConfigCommand > commandList , final List < String > formList ) { for ( ConfigCommand command : commandList ) { // check weather it's form command\r if ( ! command . getCommandTypeName ( ) . equalsIgnoreCase ( TieConstants . COMMAND_FORM ) && ( ! command . isParentFound ( ) ) ) { matchCommandToSheetConfigForm ( sheetConfigMap , formList , command ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match command to sheet config form . [CODESPLIT] private void matchCommandToSheetConfigForm ( final Map < String , SheetConfiguration > sheetConfigMap , final List < String > formList , final ConfigCommand command ) { for ( String formname : formList ) { SheetConfiguration sheetConfig = sheetConfigMap . get ( formname ) ; if ( WebSheetUtility . insideRange ( command . getConfigRange ( ) , sheetConfig . getFormCommand ( ) . getConfigRange ( ) ) ) { sheetConfig . getFormCommand ( ) . getConfigRange ( ) . addCommand ( command ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the each command area to seperated sheet . As it will be used for iteration . [CODESPLIT] private void copyTemplateForTieCommands ( final Sheet sheet ) { // if skip configuration. then return.\r if ( parent . isSkipConfiguration ( ) ) { return ; } Workbook wb = sheet . getWorkbook ( ) ; String copyName = TieConstants . COPY_SHEET_PREFIX + sheet . getSheetName ( ) ; if ( wb . getSheet ( copyName ) == null ) { Sheet newSheet = wb . cloneSheet ( wb . getSheetIndex ( sheet ) ) ; int sheetIndex = wb . getSheetIndex ( newSheet ) ; wb . setSheetName ( sheetIndex , copyName ) ; wb . setSheetHidden ( sheetIndex , Workbook . SHEET_STATE_VERY_HIDDEN ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build command list from comment . [CODESPLIT] private List < ConfigCommand > buildCommandList ( final Sheet sheet , final int sheetRightCol , final Cell cell , final List < ConfigCommand > cList , final CellAttributesMap cellAttributesMap ) { Comment comment = cell . getCellComment ( ) ; String text = comment . getString ( ) . getString ( ) ; String [ ] commentLines = text . split ( \"\\\\n\" ) ; StringBuilder newComment = new StringBuilder ( ) ; boolean changed = false ; for ( String commentLine : commentLines ) { String line = commentLine . trim ( ) ; if ( ParserUtility . isCommandString ( line ) ) { processCommandLine ( sheet , cell , line , cList , sheetRightCol ) ; changed = true ; } else if ( ParserUtility . isEmptyMethodString ( line ) || ParserUtility . isMethodString ( line ) ) { processMethodLine ( cell , line , cellAttributesMap ) ; changed = true ; } else { if ( newComment . length ( ) > 0 ) { newComment . append ( \"\\\\n\" + commentLine ) ; } else { newComment . append ( commentLine ) ; } } } if ( ! changed ) { moveCommentToMap ( cell , text , cellAttributesMap . getTemplateCommentMap ( ) , true ) ; } else { // reset comment string if changed\r if ( newComment . length ( ) > 0 ) { moveCommentToMap ( cell , newComment . toString ( ) , cellAttributesMap . getTemplateCommentMap ( ) , true ) ; CreationHelper factory = sheet . getWorkbook ( ) . getCreationHelper ( ) ; RichTextString str = factory . createRichTextString ( newComment . toString ( ) ) ; comment . setString ( str ) ; } else { // remove cell comment if new comment become empty.\r cell . removeCellComment ( ) ; } } return cList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process method line . [CODESPLIT] private void processMethodLine ( final Cell cell , final String line , final CellAttributesMap cellAttributesMap ) { if ( ParserUtility . isWidgetMethodString ( line ) ) { ParserUtility . parseWidgetAttributes ( cell , line , cellAttributesMap ) ; } else if ( ParserUtility . isValidateMethodString ( line ) ) { ParserUtility . parseValidateAttributes ( cell , line , cellAttributesMap ) ; } else { moveCommentToMap ( cell , line , cellAttributesMap . getTemplateCommentMap ( ) , false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process command line . [CODESPLIT] private void processCommandLine ( final Sheet sheet , final Cell cell , final String line , final List < ConfigCommand > cList , final int sheetRightCol ) { int nameEndIndex = line . indexOf ( TieConstants . ATTR_PREFIX , TieConstants . COMMAND_PREFIX . length ( ) ) ; if ( nameEndIndex < 0 ) { String errMsg = \"Failed to parse command line [\" + line + \"]. Expected '\" + TieConstants . ATTR_PREFIX + \"' symbol.\" ; LOG . severe ( errMsg ) ; throw new IllegalStateException ( errMsg ) ; } String commandName = line . substring ( TieConstants . COMMAND_PREFIX . length ( ) , nameEndIndex ) . trim ( ) ; Map < String , String > attrMap = buildAttrMap ( line , nameEndIndex ) ; ConfigCommand configCommand = createConfigCommand ( sheet , cell , sheetRightCol , commandName , attrMap ) ; if ( configCommand != null ) { cList . add ( configCommand ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "change the comment . [CODESPLIT] private void moveCommentToMap ( final Cell cell , final String newComment , final Map < String , Map < String , String > > sheetCommentMap , final boolean normalComment ) { String cellKey = cell . getSheet ( ) . getSheetName ( ) + \"!$\" + cell . getColumnIndex ( ) + \"$\" + cell . getRowIndex ( ) ; ParserUtility . parseCommentToMap ( cellKey , newComment , sheetCommentMap , normalComment ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create configuration command . [CODESPLIT] private ConfigCommand createConfigCommand ( final Sheet sheet , final Cell firstCell , final int sheetRightCol , final String commandName , final Map < String , String > attrMap ) { @ SuppressWarnings ( \"rawtypes\" ) Class clas = commandMap . get ( commandName ) ; if ( clas == null ) { LOG . log ( Level . WARNING , \"Cannot find command class for {} \" , commandName ) ; return null ; } try { ConfigCommand command = ( ConfigCommand ) clas . newInstance ( ) ; command . setCommandTypeName ( commandName ) ; for ( Map . Entry < String , String > attr : attrMap . entrySet ( ) ) { WebSheetUtility . setObjectProperty ( command , attr . getKey ( ) , attr . getValue ( ) , true ) ; } command . getConfigRange ( ) . setFirstRowRef ( firstCell , true ) ; command . getConfigRange ( ) . setLastRowPlusRef ( sheet , sheetRightCol , command . getLastRow ( ) , true ) ; return command ; } catch ( Exception e ) { LOG . log ( Level . WARNING , \"Failed to initialize command class \" + clas . getName ( ) + \" for command\" + commandName , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the attributes map . [CODESPLIT] private Map < String , String > buildAttrMap ( final String commandLine , final int nameEndIndex ) { int paramsEndIndex = commandLine . lastIndexOf ( TieConstants . ATTR_SUFFIX ) ; if ( paramsEndIndex < 0 ) { String errMsg = \"Failed to parse command line [\" + commandLine + \"]. Expected '\" + TieConstants . ATTR_SUFFIX + \"' symbol.\" ; throw new IllegalArgumentException ( errMsg ) ; } String attrString = commandLine . substring ( nameEndIndex + 1 , paramsEndIndex ) . trim ( ) ; return ParserUtility . parseCommandAttributes ( attrString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create sheet configuration from form command . [CODESPLIT] private SheetConfiguration getSheetConfigurationFromConfigCommand ( final Sheet sheet , final FormCommand fcommand , final int sheetRightCol ) { SheetConfiguration sheetConfig = new SheetConfiguration ( ) ; sheetConfig . setFormName ( fcommand . getName ( ) ) ; sheetConfig . setSheetName ( sheet . getSheetName ( ) ) ; int leftCol = fcommand . getLeftCol ( ) ; int lastRow = fcommand . getLastRow ( ) ; int rightCol = 0 ; int maxRow = 0 ; for ( Row row : sheet ) { if ( row . getRowNum ( ) > TieConstants . TIE_WEB_SHEET_MAX_ROWS ) { break ; } maxRow = row . getRowNum ( ) ; if ( ( row . getLastCellNum ( ) - 1 ) > rightCol ) { int verifiedcol = verifyLastCell ( row , rightCol , sheetRightCol ) ; if ( verifiedcol > rightCol ) { rightCol = verifiedcol ; } } } if ( maxRow < lastRow ) { lastRow = maxRow ; } // header range row set to 0 while column set to first column to\r // max\r // column (FF) e.g. $A$0 : $FF$0\r setHeaderOfSheetConfiguration ( fcommand , sheetConfig , leftCol , rightCol ) ; // body range row set to first row to last row while column set\r // to\r // first column to max column (FF) e.g. $A$1 : $FF$1000\r setBodyOfSheetConfiguration ( fcommand , sheetConfig , leftCol , lastRow , rightCol ) ; // footer range row set to 0 while column set to first column to\r // max\r // column (FF) e.g. $A$0 : $FF$0\r setFooterOfSheetConfiguration ( fcommand , sheetConfig , leftCol , rightCol ) ; String hidden = fcommand . getHidden ( ) ; if ( ( hidden != null ) && ( Boolean . parseBoolean ( hidden ) ) ) { sheetConfig . setHidden ( true ) ; } String fixedWidthStyle = fcommand . getFixedWidthStyle ( ) ; if ( ( fixedWidthStyle != null ) && ( Boolean . parseBoolean ( fixedWidthStyle ) ) ) { sheetConfig . setFixedWidthStyle ( true ) ; } sheetConfig . setFormCommand ( fcommand ) ; return sheetConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the footer of sheet configuration . [CODESPLIT] private void setFooterOfSheetConfiguration ( final FormCommand fcommand , final SheetConfiguration sheetConfig , final int leftCol , final int rightCol ) { String tempStr ; if ( fcommand . calcFooterLength ( ) == 0 ) { tempStr = CellUtility . getCellIndexLetterKey ( leftCol , 0 ) + \" : \" + CellUtility . getCellIndexLetterKey ( rightCol , 0 ) ; } else { tempStr = CellUtility . getCellIndexLetterKey ( leftCol , fcommand . getTopRow ( ) + fcommand . calcHeaderLength ( ) + fcommand . calcBodyLength ( ) ) + \" : \" + CellUtility . getCellIndexLetterKey ( rightCol , fcommand . getTopRow ( ) + fcommand . calcHeaderLength ( ) ) ; } sheetConfig . setFormFooterRange ( tempStr ) ; sheetConfig . setFooterCellRange ( new CellRange ( tempStr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the body of sheet configuration . [CODESPLIT] private void setBodyOfSheetConfiguration ( final FormCommand fcommand , final SheetConfiguration sheetConfig , final int leftCol , final int lastRow , final int rightCol ) { String tempStr ; tempStr = CellUtility . getCellIndexLetterKey ( leftCol , fcommand . getTopRow ( ) + fcommand . calcHeaderLength ( ) + 1 ) + \" : \" + CellUtility . getCellIndexLetterKey ( rightCol , lastRow + 1 ) ; sheetConfig . setFormBodyRange ( tempStr ) ; sheetConfig . setBodyCellRange ( new CellRange ( tempStr ) ) ; sheetConfig . setFormBodyType ( TieConstants . FORM_TYPE_FREE ) ; sheetConfig . setCellFormAttributes ( new HashMap < String , List < CellFormAttributes > > ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the header of sheet configuration . [CODESPLIT] private void setHeaderOfSheetConfiguration ( final FormCommand fcommand , final SheetConfiguration sheetConfig , final int leftCol , final int rightCol ) { String tempStr ; if ( fcommand . calcHeaderLength ( ) == 0 ) { tempStr = CellUtility . getCellIndexLetterKey ( leftCol , 0 ) + \" : \" + CellUtility . getCellIndexLetterKey ( rightCol , 0 ) ; } else { tempStr = CellUtility . getCellIndexLetterKey ( leftCol , fcommand . getTopRow ( ) + 1 ) + \" : \" + CellUtility . getCellIndexLetterKey ( rightCol , fcommand . getTopRow ( ) + fcommand . calcHeaderLength ( ) ) ; } sheetConfig . setFormHeaderRange ( tempStr ) ; sheetConfig . setHeaderCellRange ( new CellRange ( tempStr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the row . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" } ) public static int addRow ( final ConfigBuildRef configBuildRef , final int rowIndex , final Map < String , Object > dataContext ) { // replace the lastCollection.\r // since here's add one row.\r // Then we should insert one empty object in the list.\r // The collection must be a list to support add/delete function.\r // and the object must support empty constructor.\r String fullName = ConfigurationUtility . getFullNameFromRow ( configBuildRef . getSheet ( ) . getRow ( rowIndex ) ) ; String [ ] parts = fullName . split ( \":\" ) ; configBuildRef . getCellHelper ( ) . restoreDataContext ( fullName ) ; CollectionObject collect = configBuildRef . getCellHelper ( ) . getLastCollect ( fullName ) ; Collection lastCollection = collect . getLastCollection ( ) ; int lastCollectionIndex = collect . getLastCollectionIndex ( ) ; EachCommand eachCommand = collect . getEachCommand ( ) ; if ( lastCollectionIndex < 0 ) { // no each command in the loop.\r throw new AddRowException ( \"No each command found.\" ) ; } String unitFullName = CommandUtility . insertEmptyObjectInContext ( fullName , lastCollection , eachCommand , lastCollectionIndex , dataContext ) ; RowsMapping unitRowsMapping = new RowsMapping ( ) ; ConfigRangeAttrs savedRangeAttrs = configBuildRef . getShiftMap ( ) . get ( fullName ) ; int insertPosition = savedRangeAttrs . getFirstRowRef ( ) . getRowIndex ( ) + savedRangeAttrs . getFinalLength ( ) ; configBuildRef . setInsertPosition ( insertPosition ) ; CommandUtility . insertEachTemplate ( eachCommand . getConfigRange ( ) , configBuildRef , lastCollectionIndex + 1 , insertPosition , unitRowsMapping ) ; ConfigRange currentRange = ConfigurationUtility . buildCurrentRange ( eachCommand . getConfigRange ( ) , configBuildRef . getSheet ( ) , insertPosition ) ; List < RowsMapping > currentRowsMappingList = ConfigurationUtility . findParentRowsMappingFromShiftMap ( parts , configBuildRef . getShiftMap ( ) ) ; currentRowsMappingList . add ( unitRowsMapping ) ; currentRange . getAttrs ( ) . setAllowAdd ( true ) ; configBuildRef . setBodyAllowAdd ( true ) ; // reverse order of changeMap.\r Map < String , String > changeMap = new TreeMap <> ( Collections . reverseOrder ( ) ) ; ConfigurationUtility . changeIndexNumberInHiddenColumn ( configBuildRef , currentRange . getAttrs ( ) . getLastRowPlusRef ( ) . getRowIndex ( ) , fullName , changeMap , 1 ) ; ConfigurationUtility . changeIndexNumberInShiftMap ( configBuildRef . getShiftMap ( ) , changeMap ) ; configBuildRef . putShiftAttrs ( unitFullName , currentRange . getAttrs ( ) , unitRowsMapping ) ; int length = currentRange . buildAt ( unitFullName , configBuildRef , insertPosition , dataContext , currentRowsMappingList ) ; currentRange . getAttrs ( ) . setFinalLength ( length ) ; ConfigurationUtility . reBuildUpperLevelFormula ( configBuildRef , fullName ) ; ConfigurationUtility . changeUpperLevelFinalLength ( configBuildRef . getShiftMap ( ) , fullName , length ) ; currentRowsMappingList . remove ( unitRowsMapping ) ; dataContext . remove ( eachCommand . getVar ( ) ) ; return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete row . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" } ) public static int deleteRow ( final ConfigBuildRef configBuildRef , final int rowIndex , final Map < String , Object > dataContext , final SheetConfiguration sheetConfig , final List < FacesRow > bodyRows ) { String fullName = ConfigurationUtility . getFullNameFromRow ( configBuildRef . getSheet ( ) . getRow ( rowIndex ) ) ; configBuildRef . getCellHelper ( ) . restoreDataContext ( fullName ) ; CollectionObject collect = configBuildRef . getCellHelper ( ) . getLastCollect ( fullName ) ; Collection lastCollection = collect . getLastCollection ( ) ; int lastCollectionIndex = collect . getLastCollectionIndex ( ) ; EachCommand eachCommand = collect . getEachCommand ( ) ; if ( lastCollectionIndex < 0 ) { // no each command in the loop.\r throw new DeleteRowException ( \"No each command found.\" ) ; } if ( lastCollection . size ( ) <= 1 ) { // this is the last record and no parent left.\r throw new DeleteRowException ( \"Cannot delete the last record in the group.\" ) ; } CommandUtility . deleteObjectInContext ( lastCollection , eachCommand , lastCollectionIndex , dataContext ) ; // find range from shiftmap.\r ConfigRangeAttrs currentRangeAttrs = configBuildRef . getShiftMap ( ) . get ( fullName ) ; if ( currentRangeAttrs == null ) { throw new DeleteRowException ( \"Cannot find delete range.\" ) ; } // The lastRowRef is wrong in rangeAttrs. So use length to recalc it.\r int startRow = currentRangeAttrs . getFirstRowIndex ( ) ; int length = currentRangeAttrs . getFinalLength ( ) ; int endRow = startRow + length - 1 ; List < String > removeFullNameList = findRemoveFullNameList ( configBuildRef . getSheet ( ) , startRow , endRow ) ; // remove range from shiftmap.\r removeRangesFromShiftMap ( configBuildRef . getShiftMap ( ) , removeFullNameList ) ; // 1. remove ranged rows from sheet\r String var = eachCommand . getVar ( ) ; CommandUtility . removeRowsInSheet ( configBuildRef . getSheet ( ) , startRow , endRow , configBuildRef . getCachedCells ( ) ) ; // 2. reset FacesRow row index.\r CommandUtility . removeRowsInBody ( sheetConfig , bodyRows , startRow , endRow ) ; // 3. decrease index number in hidden column\r Map < String , String > changeMap = new TreeMap <> ( ) ; ConfigurationUtility . changeIndexNumberInHiddenColumn ( configBuildRef , startRow , fullName , changeMap , - 1 ) ; // 4. decrease index number in shift map\r ConfigurationUtility . changeIndexNumberInShiftMap ( configBuildRef . getShiftMap ( ) , changeMap ) ; // 5. rebuild upper level formula\r ConfigurationUtility . reBuildUpperLevelFormula ( configBuildRef , fullName ) ; // 6. decrease upper level final length\r ConfigurationUtility . changeUpperLevelFinalLength ( configBuildRef . getShiftMap ( ) , fullName , - length ) ; dataContext . remove ( var ) ; return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the ranges from shift map . [CODESPLIT] private static void removeRangesFromShiftMap ( final NavigableMap < String , ConfigRangeAttrs > shiftMap , final List < String > removeFullNameList ) { for ( String fname : removeFullNameList ) { shiftMap . remove ( fname ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find remove full name list . [CODESPLIT] private static List < String > findRemoveFullNameList ( final Sheet sheet , final int startRow , final int endRow ) { List < String > list = new ArrayList <> ( ) ; for ( int rowIndex = startRow ; rowIndex <= endRow ; rowIndex ++ ) { String fullName = ConfigurationUtility . getFullNameFromRow ( sheet . getRow ( rowIndex ) ) ; if ( ! list . contains ( fullName ) ) { list . add ( fullName ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the each command from parts name . [CODESPLIT] public static EachCommand getEachCommandFromPartsName ( final Map < String , Command > commandIndexMap , final String [ ] varparts ) { if ( varparts . length == TieConstants . DEFAULT_COMMAND_PART_LENGTH ) { return ( EachCommand ) commandIndexMap . get ( TieConstants . EACH_COMMAND_FULL_NAME_PREFIX + varparts [ 1 ] ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert empty object in context . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) private static String insertEmptyObjectInContext ( final String fullName , final Collection lastCollection , final EachCommand eachCommand , final int lastCollectionIndex , final Map < String , Object > dataContext ) { if ( ! ( lastCollection instanceof List ) ) { throw new EvaluationException ( \"Collection must be list in order to insert/delete.\" ) ; } List collectionList = ( List ) lastCollection ; // the object must support empty constructor.\r Object currentObj = collectionList . get ( lastCollectionIndex ) ; Object insertObj ; try { insertObj = currentObj . getClass ( ) . newInstance ( ) ; collectionList . add ( lastCollectionIndex + 1 , insertObj ) ; dataContext . put ( eachCommand . getVar ( ) , insertObj ) ; return fullName . substring ( 0 , fullName . lastIndexOf ( ' ' ) + 1 ) + ( lastCollectionIndex + 1 ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new EvaluationException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete object in context . [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" } ) private static void deleteObjectInContext ( final Collection lastCollection , final EachCommand eachCommand , final int lastCollectionIndex , final Map < String , Object > dataContext ) { if ( ! ( lastCollection instanceof List ) ) { throw new EvaluationException ( eachCommand . getVar ( ) + TieConstants . EACH_COMMAND_INVALID_MSG ) ; } List collectionList = ( List ) lastCollection ; // the object must support empty constructor.\r collectionList . remove ( lastCollectionIndex ) ; dataContext . remove ( eachCommand . getVar ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare collection data in context . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static int prepareCollectionDataInContext ( final String [ ] varparts , final Collection collection , final Map < String , Object > dataContext ) { if ( varparts . length == TieConstants . DEFAULT_COMMAND_PART_LENGTH ) { int collectionIndex = Integer . parseInt ( varparts [ 2 ] ) ; Object obj = ConfigurationUtility . findItemInCollection ( collection , collectionIndex ) ; if ( obj != null ) { dataContext . put ( varparts [ 1 ] , obj ) ; return collectionIndex ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Index command range . [CODESPLIT] public static void indexCommandRange ( final ConfigRange sourceConfigRange , final Map < String , Command > indexMap ) { if ( sourceConfigRange . getCommandList ( ) != null ) { for ( int i = 0 ; i < sourceConfigRange . getCommandList ( ) . size ( ) ; i ++ ) { Command command = sourceConfigRange . getCommandList ( ) . get ( i ) ; indexMap . put ( command . getCommandName ( ) , command ) ; command . getConfigRange ( ) . indexCommandRange ( indexMap ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is row allow add . [CODESPLIT] public static boolean isRowAllowAdd ( final Row row , final SheetConfiguration sheetConfig ) { String fullName = ConfigurationUtility . getFullNameFromRow ( row ) ; if ( fullName != null ) { ConfigRangeAttrs attrs = sheetConfig . getShiftMap ( ) . get ( fullName ) ; if ( ( attrs != null ) && ( attrs . isAllowAdd ( ) ) && ( row . getRowNum ( ) == attrs . getFirstRowRef ( ) . getRowIndex ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert each template . [CODESPLIT] public static void insertEachTemplate ( final ConfigRange sourceConfigRange , final ConfigBuildRef configBuildRef , final int index , final int insertPosition , final RowsMapping unitRowsMapping ) { int srcStartRow = sourceConfigRange . getFirstRowAddr ( ) . getRow ( ) ; int srcEndRow = sourceConfigRange . getLastRowPlusAddr ( ) . getRow ( ) - 1 ; Sheet sheet = configBuildRef . getSheet ( ) ; Workbook wb = sheet . getWorkbook ( ) ; // excel sheet name has limit 31 chars\r String copyName = TieConstants . COPY_SHEET_PREFIX + sheet . getSheetName ( ) ; if ( copyName . length ( ) > TieConstants . EXCEL_SHEET_NAME_LIMIT ) { copyName = copyName . substring ( 0 , TieConstants . EXCEL_SHEET_NAME_LIMIT ) ; } Sheet srcSheet = wb . getSheet ( copyName ) ; if ( index > 0 ) { CellUtility . copyRows ( srcSheet , sheet , srcStartRow , srcEndRow , insertPosition , false , true ) ; } for ( int rowIndex = srcStartRow ; rowIndex <= srcEndRow ; rowIndex ++ ) { if ( configBuildRef . getWatchList ( ) . contains ( rowIndex ) && ( ConfigurationUtility . isStaticRow ( sourceConfigRange , rowIndex ) ) ) { unitRowsMapping . addRow ( rowIndex , sheet . getRow ( insertPosition + rowIndex - srcStartRow ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) public static void evaluate ( final Map < String , Object > context , final Cell cell , final ExpressionEngine engine ) { if ( ( cell != null ) && ( cell . getCellTypeEnum ( ) == CellType . STRING ) ) { String strValue = cell . getStringCellValue ( ) ; if ( isUserFormula ( strValue ) ) { evaluateUserFormula ( cell , strValue ) ; } else { evaluateNormalCells ( cell , strValue , context , engine ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate normal cells . [CODESPLIT] public static void evaluateNormalCells ( final Cell cell , final String strValue , final Map < String , Object > context , final ExpressionEngine engine ) { if ( strValue . contains ( TieConstants . METHOD_PREFIX ) ) { Object evaluationResult = evaluate ( strValue , context , engine ) ; if ( evaluationResult == null ) { evaluationResult = \"\" ; } CellUtility . setCellValue ( cell , evaluationResult . toString ( ) ) ; createTieCell ( cell , context , engine ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate user formula . [CODESPLIT] private static void evaluateUserFormula ( final Cell cell , final String strValue ) { String formulaStr = strValue . substring ( 2 , strValue . length ( ) - 1 ) ; if ( ( formulaStr != null ) && ( ! formulaStr . isEmpty ( ) ) ) { cell . setCellFormula ( formulaStr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is user formula . [CODESPLIT] private static boolean isUserFormula ( final String str ) { return str . startsWith ( TieConstants . USER_FORMULA_PREFIX ) && str . endsWith ( TieConstants . USER_FORMULA_SUFFIX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate . [CODESPLIT] public static Object evaluate ( final String strValue , final Map < String , Object > context , final ExpressionEngine engine ) { StringBuffer sb = new StringBuffer ( ) ; int beginExpressionLength = TieConstants . METHOD_PREFIX . length ( ) ; int endExpressionLength = TieConstants . METHOD_END . length ( ) ; Matcher exprMatcher = TieConstants . EXPRESSION_NOTATION_PATTERN . matcher ( strValue ) ; String matchedString ; String expression ; Object lastMatchEvalResult = null ; int matchCount = 0 ; int endOffset = 0 ; while ( exprMatcher . find ( ) ) { endOffset = exprMatcher . end ( ) ; matchCount ++ ; matchedString = exprMatcher . group ( ) ; expression = matchedString . substring ( beginExpressionLength , matchedString . length ( ) - endExpressionLength ) ; lastMatchEvalResult = engine . evaluate ( expression , context ) ; exprMatcher . appendReplacement ( sb , Matcher . quoteReplacement ( lastMatchEvalResult != null ? lastMatchEvalResult . toString ( ) : \"\" ) ) ; } String lastStringResult = lastMatchEvalResult != null ? lastMatchEvalResult . toString ( ) : \"\" ; boolean isAppendTail = matchCount == 1 && endOffset < strValue . length ( ) ; Object evaluationResult = null ; if ( matchCount > 1 || isAppendTail ) { exprMatcher . appendTail ( sb ) ; evaluationResult = sb . toString ( ) ; } else if ( matchCount == 1 ) { if ( sb . length ( ) > lastStringResult . length ( ) ) { evaluationResult = sb . toString ( ) ; } else { evaluationResult = lastMatchEvalResult ; } } else if ( matchCount == 0 ) { evaluationResult = strValue ; } return evaluationResult ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the cell comment . [CODESPLIT] public static void createCellComment ( final Cell cell , final String newComment , final Map < Cell , String > finalCommentMap ) { // due to poi's bug. the comment must be set in sorted order ( row first\r // then column),\r // otherwise poi will mess up.\r // workaround solution is to save all comments into a map,\r // and output them together when download workbook.\r if ( newComment != null ) { finalCommentMap . put ( cell , newComment ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "evaluate boolean express . [CODESPLIT] public static boolean evalBoolExpression ( final ExpressionEngine expEngine , final String pscript ) { Object result = null ; String script = \"( \" + pscript + \" )\" ; script = script . toUpperCase ( ) . replace ( \"AND\" , \"&&\" ) ; script = script . toUpperCase ( ) . replace ( \"OR\" , \"||\" ) ; try { result = expEngine . evaluate ( script ) ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"WebForm WebFormHelper evalBoolExpression script = \" + script + \"; error = \" + e . getLocalizedMessage ( ) , e ) ; } if ( result != null ) { return ( ( Boolean ) result ) . booleanValue ( ) ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the rows . [CODESPLIT] public static void removeRowsInSheet ( final Sheet sheet , final int rowIndexStart , final int rowIndexEnd , final Map < Cell , String > cachedMap ) { for ( int irow = rowIndexStart ; irow <= rowIndexEnd ; irow ++ ) { removeCachedCellForRow ( sheet , irow , cachedMap ) ; } int irows = rowIndexEnd - rowIndexStart + 1 ; if ( ( irows < 1 ) || ( rowIndexStart < 0 ) ) { return ; } int lastRowNum = sheet . getLastRowNum ( ) ; if ( rowIndexEnd < lastRowNum ) { sheet . shiftRows ( rowIndexEnd + 1 , lastRowNum , - irows ) ; } if ( rowIndexEnd == lastRowNum ) { // reverse order to delete rows.\r for ( int i = rowIndexEnd ; i >= rowIndexStart ; i -- ) { removeSingleRowInSheet ( sheet , rowIndexStart ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the single row in sheet . [CODESPLIT] private static void removeSingleRowInSheet ( final Sheet sheet , final int rowIndexStart ) { Row removingRow = sheet . getRow ( rowIndexStart ) ; if ( removingRow != null ) { sheet . removeRow ( removingRow ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the cached cell for row . [CODESPLIT] private static void removeCachedCellForRow ( final Sheet sheet , final int rowIndexStart , final Map < Cell , String > cachedMap ) { Row removingRow = sheet . getRow ( rowIndexStart ) ; if ( removingRow != null ) { // remove cached cell.\r for ( Cell cell : removingRow ) { cachedMap . remove ( cell ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the rows in body . [CODESPLIT] public static void removeRowsInBody ( final SheetConfiguration sheetConfig , final List < FacesRow > bodyRows , final int rowIndexStart , final int rowIndexEnd ) { int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; if ( ( rowIndexEnd < rowIndexStart ) || ( rowIndexStart < top ) ) { return ; } int irows = rowIndexEnd - rowIndexStart + 1 ; for ( int rowIndex = rowIndexEnd ; rowIndex >= rowIndexStart ; rowIndex -- ) { bodyRows . remove ( rowIndex - top ) ; } for ( int irow = rowIndexStart - top ; irow < bodyRows . size ( ) ; irow ++ ) { FacesRow facesrow = bodyRows . get ( irow ) ; facesrow . setRowIndex ( facesrow . getRowIndex ( ) - irows ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put picture image to session map and return the key to web . [CODESPLIT] private String loadPicture ( final int rowIndex , final int colIndex ) { FacesCell facesCell = parent . getCellHelper ( ) . getFacesCellWithRowColFromCurrentPage ( rowIndex , colIndex ) ; if ( facesCell != null && facesCell . isContainPic ( ) ) { FacesContext context = FacesContext . getCurrentInstance ( ) ; String pictureId = facesCell . getPictureId ( ) ; String pictureViewId = Integer . toHexString ( System . identityHashCode ( parent . getWb ( ) ) ) + pictureId ; Map < String , Object > sessionMap = context . getExternalContext ( ) . getSessionMap ( ) ; if ( sessionMap . get ( pictureViewId ) == null ) { sessionMap . put ( pictureViewId , parent . getPicturesMap ( ) . get ( pictureId ) . getPictureData ( ) ) ; } return pictureViewId ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put chart image to session map and return the key to web . [CODESPLIT] private String loadChart ( final int rowIndex , final int colIndex ) { FacesCell facesCell = parent . getCellHelper ( ) . getFacesCellWithRowColFromCurrentPage ( rowIndex , colIndex ) ; if ( facesCell != null && facesCell . isContainChart ( ) ) { FacesContext context = FacesContext . getCurrentInstance ( ) ; String chartId = facesCell . getChartId ( ) ; String chartViewId = Integer . toHexString ( System . identityHashCode ( parent . getWb ( ) ) ) + chartId ; if ( context != null ) { Map < String , Object > sessionMap = context . getExternalContext ( ) . getSessionMap ( ) ; if ( sessionMap . get ( chartViewId ) == null ) { sessionMap . put ( chartViewId , parent . getCharsData ( ) . getChartsMap ( ) . get ( chartId ) ) ; } } return chartViewId ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final Object get ( final Object key ) { Object result = \"\" ; try { CellMapKey mkey = new CellMapKey ( ( String ) key ) ; if ( ! mkey . isParseSuccess ( ) ) { return result ; } Cell poiCell = parent . getCellHelper ( ) . getPoiCellWithRowColFromCurrentPage ( mkey . getRowIndex ( ) , mkey . getColIndex ( ) ) ; if ( poiCell == null ) { return result ; } if ( mkey . isCharted ( ) ) { result = loadChart ( mkey . getRowIndex ( ) , mkey . getColIndex ( ) ) ; } else if ( mkey . isPictured ( ) ) { result = loadPicture ( mkey . getRowIndex ( ) , mkey . getColIndex ( ) ) ; } else if ( mkey . isFormatted ( ) ) { result = CellUtility . getCellValueWithFormat ( poiCell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) ; } else { result = CellUtility . getCellValueWithoutFormat ( poiCell ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"Web Form CellMap get value error=\" + ex . getLocalizedMessage ( ) , ex ) ; } // return blank if null\r return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final Object put ( final Object key , final Object value ) { try { CellMapKey mkey = new CellMapKey ( ( String ) key ) ; if ( ! mkey . isParseSuccess ( ) ) { return null ; } Cell poiCell = parent . getCellHelper ( ) . getPoiCellWithRowColFromCurrentPage ( mkey . getRowIndex ( ) , mkey . getColIndex ( ) ) ; if ( poiCell == null ) { return null ; } String oldValue = CellUtility . getCellValueWithoutFormat ( poiCell ) ; FacesCell facesCell = parent . getCellHelper ( ) . getFacesCellWithRowColFromCurrentPage ( mkey . getRowIndex ( ) , mkey . getColIndex ( ) ) ; String newValue = assembleNewValue ( value , facesCell ) ; if ( newValue != null && ! newValue . equals ( oldValue ) ) { CellUtility . setCellValue ( poiCell , newValue ) ; if ( facesCell . isHasSaveAttr ( ) ) { parent . getCellHelper ( ) . saveDataInContext ( poiCell , newValue ) ; } // patch to avoid not updated downloaded file\r CellUtility . copyCell ( poiCell . getSheet ( ) , poiCell . getRow ( ) , poiCell . getRow ( ) , poiCell . getColumnIndex ( ) , false ) ; parent . getCellHelper ( ) . reCalc ( ) ; } return value ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"Save cell data error : \" + ex . getLocalizedMessage ( ) , ex ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble new value . [CODESPLIT] private String assembleNewValue ( final Object value , final FacesCell facesCell ) { String newValue ; if ( value instanceof java . util . Date ) { String datePattern = facesCell . getDatePattern ( ) ; if ( datePattern == null || datePattern . isEmpty ( ) ) { datePattern = parent . getDefaultDatePattern ( ) ; } Format formatter = new SimpleDateFormat ( datePattern ) ; newValue = formatter . format ( value ) ; } else { newValue = ( String ) value ; } if ( \"textarea\" . equalsIgnoreCase ( facesCell . getInputType ( ) ) && ( newValue != null ) ) { // remove \"\\r\" because excel issue\r newValue = newValue . replace ( \"\\r\\n\" , \"\\n\" ) ; } return newValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return cell value with format . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) public static String getCellValueWithFormat ( final Cell poiCell , final FormulaEvaluator formulaEvaluator , final DataFormatter dataFormatter ) { if ( poiCell == null ) { return null ; } String result ; try { CellType cellType = poiCell . getCellTypeEnum ( ) ; if ( cellType == CellType . FORMULA ) { cellType = formulaEvaluator . evaluate ( poiCell ) . getCellTypeEnum ( ) ; } if ( cellType == CellType . ERROR ) { result = \"\" ; } else { result = dataFormatter . formatCellValue ( poiCell , formulaEvaluator ) ; } } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"Web Form WebFormHelper getCellValue Error row = \" + poiCell . getRowIndex ( ) + \" column = \" + poiCell . getColumnIndex ( ) + \" error = \" + e . getLocalizedMessage ( ) + \"; Change return result to blank\" , e ) ; result = \"\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get input cell value . none input return blank [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) public static String getCellValueWithoutFormat ( final Cell poiCell ) { if ( poiCell == null ) { return null ; } if ( poiCell . getCellTypeEnum ( ) == CellType . FORMULA ) { return getCellStringValueWithType ( poiCell , poiCell . getCachedFormulaResultTypeEnum ( ) ) ; } else { return getCellStringValueWithType ( poiCell , poiCell . getCellTypeEnum ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get cell value as string but with giving type . [CODESPLIT] private static String getCellStringValueWithType ( final Cell poiCell , final CellType cellType ) { switch ( cellType ) { case BOOLEAN : return getCellStringValueWithBooleanType ( poiCell ) ; case NUMERIC : return getCellStringValueWithNumberType ( poiCell ) ; case STRING : return poiCell . getStringCellValue ( ) ; default : return \"\" ; } // switch\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the cell string value with number type . [CODESPLIT] private static String getCellStringValueWithNumberType ( final Cell poiCell ) { String result ; if ( DateUtil . isCellDateFormatted ( poiCell ) ) { result = poiCell . getDateCellValue ( ) . toString ( ) ; } else { result = BigDecimal . valueOf ( poiCell . getNumericCellValue ( ) ) . toPlainString ( ) ; // remove .0 from end for int\r if ( result . endsWith ( \".0\" ) ) { result = result . substring ( 0 , result . length ( ) - 2 ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set cell value with giving String value . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) public static Cell setCellValue ( final Cell c , final String value ) { try { if ( value . length ( ) == 0 ) { c . setCellType ( CellType . BLANK ) ; } else if ( WebSheetUtility . isNumeric ( value ) ) { setCellValueNumber ( c , value ) ; } else if ( WebSheetUtility . isDate ( value ) ) { setCellValueDate ( c , value ) ; } else if ( c . getCellTypeEnum ( ) == CellType . BOOLEAN ) { setCellValueBoolean ( c , value ) ; } else { setCellValueString ( c , value ) ; } } catch ( Exception e ) { LOG . log ( Level . SEVERE , \" error in setCellValue of CellUtility = \" + e . getLocalizedMessage ( ) , e ) ; setCellValueString ( c , value ) ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the cell value string . [CODESPLIT] private static void setCellValueString ( final Cell c , final String value ) { c . setCellType ( CellType . STRING ) ; c . setCellValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the cell value boolean . [CODESPLIT] private static void setCellValueBoolean ( final Cell c , final String value ) { if ( \"Y\" . equalsIgnoreCase ( value ) || \"Yes\" . equalsIgnoreCase ( value ) || \"True\" . equalsIgnoreCase ( value ) ) { c . setCellValue ( true ) ; } else { c . setCellValue ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the cell value date . [CODESPLIT] private static void setCellValueDate ( final Cell c , final String value ) { String date = WebSheetUtility . parseDate ( value ) ; setCellValueString ( c , date ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the cell value number . [CODESPLIT] private static void setCellValueNumber ( final Cell c , final String value ) { double val = Double . parseDouble ( value . replace ( Character . toString ( ' ' ) , \"\" ) ) ; c . setCellType ( CellType . NUMERIC ) ; c . setCellValue ( val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy rows . [CODESPLIT] public static void copyRows ( final Sheet srcSheet , final Sheet destSheet , final int srcRowStart , final int srcRowEnd , final int destRow , final boolean checkLock , final boolean setHiddenColumn ) { int length = srcRowEnd - srcRowStart + 1 ; if ( length <= 0 ) { return ; } destSheet . shiftRows ( destRow , destSheet . getLastRowNum ( ) , length , true , false ) ; for ( int i = 0 ; i < length ; i ++ ) { copySingleRow ( srcSheet , destSheet , srcRowStart + i , destRow + i , checkLock , setHiddenColumn ) ; } // If there are are any merged regions in the source row, copy to new\r // row\r for ( int i = 0 ; i < srcSheet . getNumMergedRegions ( ) ; i ++ ) { CellRangeAddress cellRangeAddress = srcSheet . getMergedRegion ( i ) ; if ( ( cellRangeAddress . getFirstRow ( ) >= srcRowStart ) && ( cellRangeAddress . getLastRow ( ) <= srcRowEnd ) ) { int targetRowFrom = cellRangeAddress . getFirstRow ( ) - srcRowStart + destRow ; int targetRowTo = cellRangeAddress . getLastRow ( ) - srcRowStart + destRow ; CellRangeAddress newCellRangeAddress = new CellRangeAddress ( targetRowFrom , targetRowTo , cellRangeAddress . getFirstColumn ( ) , cellRangeAddress . getLastColumn ( ) ) ; destSheet . addMergedRegion ( newCellRangeAddress ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy single row . [CODESPLIT] private static void copySingleRow ( final Sheet srcSheet , final Sheet destSheet , final int sourceRowNum , final int destinationRowNum , final boolean checkLock , final boolean setHiddenColumn ) { // Get the source / new row\r Row newRow = destSheet . getRow ( destinationRowNum ) ; Row sourceRow = srcSheet . getRow ( sourceRowNum ) ; if ( newRow == null ) { newRow = destSheet . createRow ( destinationRowNum ) ; } newRow . setHeight ( sourceRow . getHeight ( ) ) ; // Loop through source columns to add to new row\r for ( int i = 0 ; i < sourceRow . getLastCellNum ( ) ; i ++ ) { // Grab a copy of the old/new cell\r copyCell ( destSheet , sourceRow , newRow , i , checkLock ) ; } if ( setHiddenColumn ) { ConfigurationUtility . setOriginalRowNumInHiddenColumn ( newRow , sourceRow . getRowNum ( ) ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy cell . [CODESPLIT] public static Cell copyCell ( final Sheet destSheet , final Row sourceRow , final Row newRow , final int cellIndex , final boolean checkLock ) { // If the old cell is null jump to next cell\r Cell sourceCell = sourceRow . getCell ( cellIndex ) ; if ( sourceCell == null ) { return null ; } // If source cell is dest cell refresh it\r boolean refreshCell = false ; if ( sourceRow . equals ( newRow ) && ( sourceCell . getColumnIndex ( ) == cellIndex ) ) { sourceRow . removeCell ( sourceCell ) ; refreshCell = true ; } Cell newCell = newRow . createCell ( cellIndex ) ; try { if ( ! refreshCell && ( sourceCell . getCellComment ( ) != null ) ) { // If there is a cell comment, copy\r cloneComment ( sourceCell , newCell ) ; } copyCellSetStyle ( destSheet , sourceCell , newCell ) ; copyCellSetValue ( sourceCell , newCell , checkLock ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"copy cell set error = \" + ex . getLocalizedMessage ( ) , ex ) ; } return newCell ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set cell value . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) private static void copyCellSetValue ( final Cell sourceCell , final Cell newCell , final boolean checkLock ) { CellStyle newCellStyle = newCell . getCellStyle ( ) ; String name = sourceCell . getCellTypeEnum ( ) . toString ( ) ; CellValueType e = Enum . valueOf ( CellValueType . class , name ) ; e . setCellValue ( newCell , sourceCell , checkLock , newCellStyle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set up cell style . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) private static void copyCellSetStyle ( final Sheet destSheet , final Cell sourceCell , final Cell newCell ) { CellStyle newCellStyle = getCellStyleFromSourceCell ( destSheet , sourceCell ) ; newCell . setCellStyle ( newCellStyle ) ; // If there is a cell hyperlink, copy\r if ( sourceCell . getHyperlink ( ) != null ) { newCell . setHyperlink ( sourceCell . getHyperlink ( ) ) ; } // Set the cell data type\r newCell . setCellType ( sourceCell . getCellTypeEnum ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clone existing comments into new cell comment . [CODESPLIT] public static void cloneComment ( final Cell sourceCell , final Cell newCell ) { XSSFSheet sheet = ( XSSFSheet ) newCell . getSheet ( ) ; CreationHelper factory = sheet . getWorkbook ( ) . getCreationHelper ( ) ; Drawing drawing = sheet . createDrawingPatriarch ( ) ; XSSFComment sourceComment = ( XSSFComment ) sourceCell . getCellComment ( ) ; // Below code are from POI busy manual.\r // When the comment box is visible, have it show in a 1x3 space\r ClientAnchor anchor = createCommentAnchor ( newCell , factory ) ; // Create the comment and set the text+author\r Comment comment = drawing . createCellComment ( anchor ) ; RichTextString str = factory . createRichTextString ( sourceComment . getString ( ) . toString ( ) ) ; comment . setString ( str ) ; comment . setAuthor ( sourceComment . getAuthor ( ) ) ; // Assign the comment to the cell\r newCell . setCellComment ( comment ) ; comment . setColumn ( newCell . getColumnIndex ( ) ) ; comment . setRow ( newCell . getRowIndex ( ) ) ; // As POI doesn't has well support for comments,\r // So we have to use low level api to match the comments.\r matchCommentSettings ( newCell , sourceCell ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the comment anchor . [CODESPLIT] private static ClientAnchor createCommentAnchor ( final Cell newCell , CreationHelper factory ) { ClientAnchor anchor = factory . createClientAnchor ( ) ; anchor . setCol1 ( newCell . getColumnIndex ( ) ) ; anchor . setCol2 ( newCell . getColumnIndex ( ) + 1 ) ; anchor . setRow1 ( newCell . getRowIndex ( ) ) ; anchor . setRow2 ( newCell . getRowIndex ( ) + 3 ) ; return anchor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the or insert comment . [CODESPLIT] public static void createOrInsertComment ( final Cell cell , final String commentStr ) { XSSFSheet sheet = ( XSSFSheet ) cell . getSheet ( ) ; CreationHelper factory = sheet . getWorkbook ( ) . getCreationHelper ( ) ; Drawing drawing = sheet . createDrawingPatriarch ( ) ; Comment comment = cell . getCellComment ( ) ; String originStr = \"\" ; if ( comment == null ) { // Below code are from POI busy manual.\r // When the comment box is visible, have it show in a 1x3 space\r ClientAnchor anchor = createCommentAnchor ( cell , factory ) ; // Create the comment and set the text+author\r comment = drawing . createCellComment ( anchor ) ; } else { originStr = comment . getString ( ) . getString ( ) + \"\\n\" ; } originStr += commentStr ; RichTextString str = factory . createRichTextString ( originStr ) ; comment . setString ( str ) ; comment . setAuthor ( \"\" ) ; // Assign the comment to the cell\r cell . setCellComment ( comment ) ; comment . setColumn ( cell . getColumnIndex ( ) ) ; comment . setRow ( cell . getRowIndex ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use low level API to match the comments setting . [CODESPLIT] private static void matchCommentSettings ( final Cell newCell , final Cell sourceCell ) { try { XSSFVMLDrawing sourceVml = getVmlDrawingFromCell ( sourceCell ) ; XSSFVMLDrawing targetVml = getVmlDrawingFromCell ( newCell ) ; CTShape sourceCtShape = getCtShapeFromVml ( sourceCell , sourceVml ) ; CTShape targetCtShape = getCtShapeFromVml ( newCell , targetVml ) ; targetCtShape . setType ( sourceCtShape . getType ( ) ) ; CTClientData sourceClientData = sourceCtShape . getClientDataArray ( 0 ) ; CTClientData targetClientData = targetCtShape . getClientDataArray ( 0 ) ; String [ ] anchorArray = sourceClientData . getAnchorList ( ) . get ( 0 ) . split ( \",\" ) ; int shiftRows = newCell . getRowIndex ( ) - sourceCell . getRowIndex ( ) ; /*\r\n\t\t\t * AchorArray mappings: 0->col1 1->dx1 2->row1 3->dy1 4->col2 5->dx2 6-> row2\r\n\t\t\t * 7->dy2\r\n\t\t\t */ anchorArray [ 2 ] = Integer . toString ( Integer . parseInt ( anchorArray [ 2 ] . trim ( ) ) + shiftRows ) ; anchorArray [ 6 ] = Integer . toString ( Integer . parseInt ( anchorArray [ 6 ] . trim ( ) ) + shiftRows ) ; targetClientData . getAnchorList ( ) . set ( 0 , FacesUtility . strJoin ( anchorArray , \",\" ) ) ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"matchCommentSettings error = \" + e . getLocalizedMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find vmldrawing part according to cell . [CODESPLIT] private static XSSFVMLDrawing getVmlDrawingFromCell ( final Cell cell ) { XSSFSheet sourceSheet = ( XSSFSheet ) cell . getSheet ( ) ; for ( POIXMLDocumentPart sourcePart : sourceSheet . getRelations ( ) ) { if ( ( sourcePart != null ) && ( sourcePart instanceof XSSFVMLDrawing ) ) { return ( XSSFVMLDrawing ) sourcePart ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find CtShape from vml object . This class use reflection to invoke the protected method in POI . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) private static CTShape getCtShapeFromVml ( final Cell sourceCell , XSSFVMLDrawing sourceVml ) throws ReflectiveOperationException { Method findshape ; // int parameter\r Class [ ] paramInt = new Class [ 2 ] ; paramInt [ 0 ] = Integer . TYPE ; paramInt [ 1 ] = Integer . TYPE ; findshape = sourceVml . getClass ( ) . getDeclaredMethod ( \"findCommentShape\" , paramInt ) ; findshape . setAccessible ( true ) ; return ( CTShape ) findshape . invoke ( sourceVml , sourceCell . getRowIndex ( ) , sourceCell . getColumnIndex ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "create cell style from source cell . [CODESPLIT] private static CellStyle getCellStyleFromSourceCell ( final Sheet destSheet , final Cell sourceCell ) { Workbook wb = destSheet . getWorkbook ( ) ; // Copy style from old cell and apply to new cell\r CellStyle newCellStyle = wb . createCellStyle ( ) ; newCellStyle . cloneStyleFrom ( sourceCell . getCellStyle ( ) ) ; return newCellStyle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return cell index number key . e . g . $0$0 for A1 cell . [CODESPLIT] public static String getCellIndexNumberKey ( final Cell cell ) { if ( cell != null ) { return TieConstants . CELL_ADDR_PRE_FIX + cell . getColumnIndex ( ) + TieConstants . CELL_ADDR_PRE_FIX + cell . getRowIndex ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return cell index number key . e . g . $0$0 for A1 cell . [CODESPLIT] public static String getCellIndexNumberKey ( final int columnIndex , final int rowIndex ) { return TieConstants . CELL_ADDR_PRE_FIX + columnIndex + TieConstants . CELL_ADDR_PRE_FIX + rowIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return cell index key with column letter and row index . e . g . $A$0 for A1 cell . [CODESPLIT] public static String getCellIndexLetterKey ( final String columnLetter , final int rowIndex ) { return TieConstants . CELL_ADDR_PRE_FIX + columnLetter + TieConstants . CELL_ADDR_PRE_FIX + rowIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return cell index key with column and row index . e . g . $A$0 for A1 cell . [CODESPLIT] public static String getCellIndexLetterKey ( final int columnIndex , final int rowIndex ) { return TieConstants . CELL_ADDR_PRE_FIX + WebSheetUtility . getExcelColumnName ( columnIndex ) + TieConstants . CELL_ADDR_PRE_FIX + rowIndex ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set up facesCell s attribute from poiCell and others . [CODESPLIT] public static void convertCell ( final SheetConfiguration sheetConfig , final FacesCell fcell , final Cell poiCell , final Map < String , CellRangeAddress > cellRangeMap , final int originRowIndex , final CellAttributesMap cellAttributesMap , final String saveAttrs ) { CellRangeAddress caddress ; String key = getCellIndexNumberKey ( poiCell ) ; caddress = cellRangeMap . get ( key ) ; if ( caddress != null ) { // has col or row span\r fcell . setColspan ( caddress . getLastColumn ( ) - caddress . getFirstColumn ( ) + 1 ) ; fcell . setRowspan ( caddress . getLastRow ( ) - caddress . getFirstRow ( ) + 1 ) ; } CellControlsUtility . setupControlAttributes ( originRowIndex , fcell , poiCell , sheetConfig , cellAttributesMap ) ; fcell . setHasSaveAttr ( SaveAttrsUtility . isHasSaveAttr ( poiCell , saveAttrs ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the row col from component attributes . [CODESPLIT] public static int [ ] getRowColFromComponentAttributes ( final UIComponent target ) { int rowIndex = ( Integer ) target . getAttributes ( ) . get ( \"data-row\" ) ; int colIndex = ( Integer ) target . getAttributes ( ) . get ( \"data-column\" ) ; int [ ] list = new int [ 2 ] ; list [ 0 ] = rowIndex ; list [ 1 ] = colIndex ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the inits the rows from config . [CODESPLIT] public static int getInitRowsFromConfig ( final SheetConfiguration sheetConfig ) { int initRows = 1 ; if ( \"Repeat\" . equalsIgnoreCase ( sheetConfig . getFormBodyType ( ) ) ) { initRows = sheetConfig . getBodyInitialRows ( ) ; if ( initRows < 1 ) { initRows = 1 ; } } return initRows ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the faces row from body row . [CODESPLIT] public static FacesRow getFacesRowFromBodyRow ( final int row , final List < FacesRow > bodyRows , final int topRow ) { FacesRow frow = null ; try { frow = bodyRows . get ( row - topRow ) ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"getFacesRowFromBodyRow Error row = \" + row + \"top row = \" + topRow + \" ; error = \" + e . getLocalizedMessage ( ) , e ) ; } return frow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the faces cell from body row . [CODESPLIT] public static FacesCell getFacesCellFromBodyRow ( final int row , final int col , final List < FacesRow > bodyRows , final int topRow , final int leftCol ) { FacesCell cell = null ; try { cell = bodyRows . get ( row - topRow ) . getCells ( ) . get ( col - leftCol ) ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"getFacesCellFromBodyRow Error row = \" + row + \" col = \" + col + \"top row = \" + topRow + \" leftCol = \" + leftCol + \" ; error = \" + e . getLocalizedMessage ( ) , e ) ; } return cell ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the poi cell with row col from current page . [CODESPLIT] public static Cell getPoiCellWithRowColFromCurrentPage ( final int rowIndex , final int colIndex , final Workbook wb ) { if ( wb != null ) { return getPoiCellFromSheet ( rowIndex , colIndex , wb . getSheetAt ( wb . getActiveSheetIndex ( ) ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the poi cell from sheet . [CODESPLIT] public static Cell getPoiCellFromSheet ( final int rowIndex , final int colIndex , final Sheet sheet1 ) { if ( ( sheet1 != null ) && ( sheet1 . getRow ( rowIndex ) != null ) ) { return sheet1 . getRow ( rowIndex ) . getCell ( colIndex ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the skey from poi cell . [CODESPLIT] public static String getSkeyFromPoiCell ( final Cell poiCell ) { return poiCell . getSheet ( ) . getSheetName ( ) + \"!\" + CellUtility . getCellIndexNumberKey ( poiCell . getColumnIndex ( ) , poiCell . getRowIndex ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the or add tie cell in map . [CODESPLIT] public static TieCell getOrAddTieCellInMap ( final Cell poiCell , HashMap < String , TieCell > tieCells ) { String skey = CellUtility . getSkeyFromPoiCell ( poiCell ) ; TieCell tieCell = tieCells . get ( skey ) ; if ( tieCell == null ) { tieCell = new TieCell ( ) ; tieCell . setSkey ( skey ) ; tieCells . put ( skey , tieCell ) ; } return tieCell ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) @ Override public List getSerListFromCtObjChart ( final Object ctObjChart ) { if ( ctObjChart instanceof CTBarChart ) { return ( ( CTBarChart ) ctObjChart ) . getSerList ( ) ; } return emptySerlist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) @ Override public final CTAxDataSource getCtAxDataSourceFromSerList ( final List serList ) { if ( ( serList != null ) && ( ! serList . isEmpty ( ) ) && ( serList . get ( 0 ) instanceof CTBarSer ) ) { return ( ( CTBarSer ) serList . get ( 0 ) ) . getCat ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTShapeProperties getShapePropertiesFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTBarSer ) { return ( ( CTBarSer ) ctObjSer ) . getSpPr ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTNumDataSource getCTNumDataSourceFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTBarSer ) { return ( ( CTBarSer ) ctObjSer ) . getVal ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current data context name . [CODESPLIT] public final String getCurrentDataContextName ( ) { if ( currentDataContextName == null ) { StringBuilder sb = new StringBuilder ( ) ; List < String > list = this . getCurrentDataContextNameList ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( i > 0 ) { sb . append ( \":\" + list . get ( i ) ) ; } else { sb . append ( list . get ( i ) ) ; } } this . setCurrentDataContextName ( sb . toString ( ) ) ; } return currentDataContextName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate the expression . [CODESPLIT] public final Object evaluate ( final String expression , final Map < String , Object > context ) { JexlContext jexlContext = new MapContext ( context ) ; try { JexlEngine jexl = JEXL_LOCAL . get ( ) ; Map < String , Expression > expMap = JEXL_MAP_LOCAL . get ( ) ; Expression jexlExpression = expMap . get ( expression ) ; if ( jexlExpression == null ) { jexlExpression = jexl . createExpression ( expression ) ; expMap . put ( expression , jexlExpression ) ; } return jexlExpression . evaluate ( jexlContext ) ; } catch ( Exception e ) { throw new EvaluationException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "evaluate from giving context . [CODESPLIT] public final Object evaluate ( final Map < String , Object > context ) { JexlContext jexlContext = new MapContext ( context ) ; try { return jExpression . evaluate ( jexlContext ) ; } catch ( Exception e ) { throw new EvaluationException ( \"An error occurred when evaluating expression \" + jExpression . getExpression ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save the row before serialize . [CODESPLIT] private void writeObject ( final java . io . ObjectOutputStream out ) throws IOException { this . rowIndex = this . getRow ( ) . getRowNum ( ) ; out . defaultWriteObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the row . [CODESPLIT] public final void addRow ( final Integer sourceRowNum , final Row targetRow ) { List < SerialRow > mapRowList = rowsMap . get ( sourceRowNum ) ; if ( mapRowList == null ) { mapRowList = new ArrayList <> ( ) ; } SerialRow serialTarget = new SerialRow ( targetRow , - 1 ) ; if ( ! mapRowList . contains ( serialTarget ) ) { mapRowList . add ( serialTarget ) ; rowsMap . put ( sourceRowNum , mapRowList ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the row . [CODESPLIT] public final void removeRow ( final Integer sourceRowNum , final Row targetRow ) { List < SerialRow > mapRowList = rowsMap . get ( sourceRowNum ) ; if ( mapRowList != null ) { mapRowList . remove ( new SerialRow ( targetRow , - 1 ) ) ; rowsMap . put ( sourceRowNum , mapRowList ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merge map . [CODESPLIT] public final void mergeMap ( final RowsMapping addMap ) { Map < Integer , List < SerialRow > > map = addMap . getRowsMap ( ) ; for ( Map . Entry < Integer , List < SerialRow > > entry : map . entrySet ( ) ) { List < SerialRow > entryRowList = entry . getValue ( ) ; if ( ( entryRowList != null ) && ( ! entryRowList . isEmpty ( ) ) ) { for ( SerialRow row : entryRowList ) { this . addRow ( entry . getKey ( ) , row . getRow ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recover rows mapping by using it s address . [CODESPLIT] public final void recover ( final Sheet sheet ) { for ( Map . Entry < Integer , List < SerialRow > > entry : this . getRowsMap ( ) . entrySet ( ) ) { List < SerialRow > listRow = entry . getValue ( ) ; for ( SerialRow serialRow : listRow ) { serialRow . recover ( sheet ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return chart type from CTChart object . [CODESPLIT] public static ChartType getChartType ( final CTChart ctChart ) { CTPlotArea plotArea = ctChart . getPlotArea ( ) ; for ( ChartType chartType : ChartType . values ( ) ) { if ( chartType . isThisType ( plotArea ) ) { return chartType ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert style string to stroke object . [CODESPLIT] public static BasicStroke toStroke ( final String style ) { BasicStroke result = null ; if ( style != null ) { float lineWidth = STROKE_DEFAULT_LINE_WIDTH ; float [ ] dash = { STROKE_DEFAULT_DASH_WIDTH } ; float [ ] dot = { lineWidth } ; if ( style . equalsIgnoreCase ( STYLE_LINE ) ) { result = new BasicStroke ( lineWidth ) ; } else if ( style . equalsIgnoreCase ( STYLE_DASH ) ) { result = new BasicStroke ( lineWidth , BasicStroke . CAP_BUTT , BasicStroke . JOIN_MITER , STROKE_MITER_LIMIT_STYLE_DASH , dash , STROKE_DEFAULT_DASHPHASE ) ; } else if ( style . equalsIgnoreCase ( STYLE_DOT ) ) { result = new BasicStroke ( lineWidth , BasicStroke . CAP_BUTT , BasicStroke . JOIN_MITER , STROKE_MITER_LIMIT_STYLE_DOT , dot , STROKE_DEFAULT_DASHPHASE ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init chart data . [CODESPLIT] public static ChartData initChartDataFromXSSFChart ( final String chartId , final XSSFChart chart , final XSSFWorkbook wb ) { ThemesTable themeTable = wb . getStylesSource ( ) . getTheme ( ) ; ChartData chartData = new ChartData ( ) ; XSSFRichTextString chartTitle = chart . getTitle ( ) ; if ( chartTitle != null ) { chartData . setTitle ( chartTitle . toString ( ) ) ; } CTChart ctChart = chart . getCTChart ( ) ; ChartType chartType = ChartUtility . getChartType ( ctChart ) ; if ( chartType == null ) { throw new IllegalChartException ( \"Unknown chart type\" ) ; } chartData . setBgColor ( ColorUtility . getBgColor ( ctChart . getPlotArea ( ) , themeTable ) ) ; chartData . setId ( chartId ) ; chartData . setType ( chartType ) ; List < CTCatAx > ctCatAxList = ctChart . getPlotArea ( ) . getCatAxList ( ) ; if ( ( ctCatAxList != null ) && ( ! ctCatAxList . isEmpty ( ) ) ) { chartData . setCatAx ( new ChartAxis ( ctCatAxList . get ( 0 ) ) ) ; } List < CTValAx > ctValAxList = ctChart . getPlotArea ( ) . getValAxList ( ) ; if ( ( ctValAxList != null ) && ( ! ctValAxList . isEmpty ( ) ) ) { chartData . setValAx ( new ChartAxis ( ctValAxList . get ( 0 ) ) ) ; } ChartObject ctObj = chartType . createChartObject ( ) ; if ( ctObj == null ) { throw new IllegalChartException ( \"Cannot create chart object.\" ) ; } setUpChartData ( chartData , ctChart , themeTable , ctObj ) ; return chartData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build chartData for line chart . chartData include categoryList and seriesList which used for generate jfreechart . [CODESPLIT] public static void setUpChartData ( final ChartData chartData , final CTChart ctChart , final ThemesTable themeTable , final ChartObject ctObj ) { Object chartObj = null ; @ SuppressWarnings ( \"rawtypes\" ) List plotCharts = ctObj . getChartListFromCtChart ( ctChart ) ; // chart object\r if ( plotCharts != null && ( ! plotCharts . isEmpty ( ) ) ) { chartObj = plotCharts . get ( 0 ) ; } if ( chartObj != null ) { @ SuppressWarnings ( \"rawtypes\" ) List bsers = ctObj . getSerListFromCtObjChart ( chartObj ) ; if ( ! AppUtils . emptyList ( bsers ) ) { chartData . buildCategoryList ( ctObj . getCtAxDataSourceFromSerList ( bsers ) ) ; chartData . buildSeriesList ( bsers , themeTable , ctObj ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "retrieve anchor information from draw . xml for all the charts in the workbook . then save them to anchors map . [CODESPLIT] public static void initXSSFAnchorsMap ( final XSSFWorkbook wb , final ChartsData charsData ) { Map < String , ClientAnchor > anchortMap = charsData . getChartAnchorsMap ( ) ; Map < String , String > positionMap = charsData . getChartPositionMap ( ) ; anchortMap . clear ( ) ; positionMap . clear ( ) ; for ( int i = 0 ; i < wb . getNumberOfSheets ( ) ; i ++ ) { initXSSFAnchorsMapForSheet ( anchortMap , positionMap , wb . getSheetAt ( i ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inits the XSSF anchors map for sheet . [CODESPLIT] private static void initXSSFAnchorsMapForSheet ( final Map < String , ClientAnchor > anchortMap , final Map < String , String > positionMap , final XSSFSheet sheet ) { XSSFDrawing drawing = sheet . createDrawingPatriarch ( ) ; CTDrawing ctDrawing = drawing . getCTDrawing ( ) ; if ( ctDrawing . sizeOfTwoCellAnchorArray ( ) <= 0 ) { return ; } List < CTTwoCellAnchor > alist = ctDrawing . getTwoCellAnchorList ( ) ; for ( int j = 0 ; j < alist . size ( ) ; j ++ ) { CTTwoCellAnchor ctanchor = alist . get ( j ) ; String singleChartId = getAnchorAssociateChartId ( ctanchor ) ; if ( singleChartId != null ) { String chartId = sheet . getSheetName ( ) + \"!\" + singleChartId ; int dx1 = ( int ) ctanchor . getFrom ( ) . getColOff ( ) ; int dy1 = ( int ) ctanchor . getFrom ( ) . getRowOff ( ) ; int dx2 = ( int ) ctanchor . getTo ( ) . getColOff ( ) ; int dy2 = ( int ) ctanchor . getTo ( ) . getRowOff ( ) ; int col1 = ctanchor . getFrom ( ) . getCol ( ) ; int row1 = ctanchor . getFrom ( ) . getRow ( ) ; int col2 = ctanchor . getTo ( ) . getCol ( ) ; int row2 = ctanchor . getTo ( ) . getRow ( ) ; anchortMap . put ( chartId , new XSSFClientAnchor ( dx1 , dy1 , dx2 , dy2 , col1 , row1 , col2 , row2 ) ) ; positionMap . put ( WebSheetUtility . getFullCellRefName ( sheet . getSheetName ( ) , row1 , col1 ) , chartId ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the anchor associate chart id . [CODESPLIT] private static String getAnchorAssociateChartId ( final CTTwoCellAnchor ctanchor ) { if ( ctanchor . getGraphicFrame ( ) == null ) { return null ; } Node parentNode = ctanchor . getGraphicFrame ( ) . getGraphic ( ) . getGraphicData ( ) . getDomNode ( ) ; NodeList childNodes = parentNode . getChildNodes ( ) ; for ( int i = 0 ; i < childNodes . getLength ( ) ; i ++ ) { Node childNode = childNodes . item ( i ) ; if ( ( childNode != null ) && ( \"c:chart\" . equalsIgnoreCase ( childNode . getNodeName ( ) ) ) && ( childNode . hasAttributes ( ) ) ) { String rId = getChartIdFromChildNodeAttributes ( childNode . getAttributes ( ) ) ; if ( rId != null ) { return rId ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the chart id from child node attributes . [CODESPLIT] private static String getChartIdFromChildNodeAttributes ( final NamedNodeMap attrs ) { for ( int j = 0 ; j < attrs . getLength ( ) ; j ++ ) { Attr attribute = ( Attr ) attrs . item ( j ) ; if ( \"r:id\" . equalsIgnoreCase ( attribute . getName ( ) ) ) { return attribute . getValue ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save the workbook before serialize . [CODESPLIT] private void writeObject ( final java . io . ObjectOutputStream out ) throws IOException { out . defaultWriteObject ( ) ; if ( wb != null ) { wb . write ( out ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recover the cell reference to the sheet . [CODESPLIT] public void recover ( ) { Map < String , SheetConfiguration > map = this . getSheetConfigMap ( ) ; for ( Entry < String , SheetConfiguration > entry : map . entrySet ( ) ) { entry . getValue ( ) . recover ( this . getWb ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) @ Override public final int buildAt ( String fullName , final ConfigBuildRef configBuildRef , final int atRow , final Map < String , Object > context , final List < RowsMapping > currentRowsMappingList ) { fullName = fullName + \":\" + this . getCommandName ( ) ; Collection itemsCollection = ConfigurationUtility . transformToCollectionObject ( configBuildRef . getEngine ( ) , this . getItems ( ) , context ) ; String objClassName = this . getClassName ( ) ; if ( objClassName == null ) { objClassName = configBuildRef . getCollectionObjNameMap ( ) . get ( this . getVar ( ) ) ; } if ( configBuildRef . isAddMode ( ) && itemsCollection . isEmpty ( ) ) { // do something here to insert one empty object\r try { itemsCollection . add ( Class . forName ( objClassName ) . newInstance ( ) ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"canot insert empty object in itemCollections error = \" + ex . getLocalizedMessage ( ) , ex ) ; return 0 ; } } int insertPosition = buildEachObjects ( fullName , configBuildRef , atRow , context , currentRowsMappingList , itemsCollection , objClassName ) ; return insertPosition - atRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the each objects . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) private int buildEachObjects ( String fullName , final ConfigBuildRef configBuildRef , final int atRow , final Map < String , Object > context , final List < RowsMapping > currentRowsMappingList , final Collection itemsCollection , final String objClassName ) { int index = 0 ; int insertPosition = atRow ; String thisObjClassName = objClassName ; // loop through each object in the collection\r for ( Object obj : itemsCollection ) { // gather and cache object class name which used for add row\r if ( thisObjClassName == null ) { thisObjClassName = obj . getClass ( ) . getName ( ) ; configBuildRef . getCollectionObjNameMap ( ) . put ( this . var , thisObjClassName ) ; } RowsMapping unitRowsMapping = new RowsMapping ( ) ; context . put ( var , obj ) ; CommandUtility . insertEachTemplate ( this . getConfigRange ( ) , configBuildRef , index , insertPosition , unitRowsMapping ) ; ConfigRange currentRange = ConfigurationUtility . buildCurrentRange ( this . getConfigRange ( ) , configBuildRef . getSheet ( ) , insertPosition ) ; currentRowsMappingList . add ( unitRowsMapping ) ; String unitFullName = fullName + \".\" + index ; currentRange . getAttrs ( ) . setAllowAdd ( false ) ; if ( ( this . allowAdd != null ) && ( \"true\" . equalsIgnoreCase ( this . allowAdd . trim ( ) ) ) ) { currentRange . getAttrs ( ) . setAllowAdd ( true ) ; configBuildRef . setBodyAllowAdd ( true ) ; } configBuildRef . putShiftAttrs ( unitFullName , currentRange . getAttrs ( ) , new RowsMapping ( unitRowsMapping ) ) ; int length = currentRange . buildAt ( unitFullName , configBuildRef , insertPosition , context , currentRowsMappingList ) ; currentRange . getAttrs ( ) . setFinalLength ( length ) ; insertPosition += length ; currentRowsMappingList . remove ( unitRowsMapping ) ; index ++ ; context . remove ( var ) ; } return insertPosition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save data in context . [CODESPLIT] public final void saveDataInContext ( final Cell poiCell , final String strValue ) { String saveAttr = SaveAttrsUtility . prepareContextAndAttrsForCell ( poiCell , ConfigurationUtility . getFullNameFromRow ( poiCell . getRow ( ) ) , this ) ; if ( saveAttr != null ) { SaveAttrsUtility . saveDataToObjectInContext ( parent . getSerialDataContext ( ) . getDataContext ( ) , saveAttr , strValue , parent . getExpEngine ( ) ) ; parent . getHelper ( ) . getWebSheetLoader ( ) . setUnsavedStatus ( RequestContext . getCurrentInstance ( ) , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recalc whole workbook . [CODESPLIT] public final void reCalc ( ) { parent . getFormulaEvaluator ( ) . clearAllCachedResultValues ( ) ; try { parent . getFormulaEvaluator ( ) . evaluateAll ( ) ; } catch ( Exception ex ) { // skip the formula exception when recalc but log it\r LOG . log ( Level . SEVERE , \" recalc formula error : \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the poi cell with row col from current page . [CODESPLIT] public final Cell getPoiCellWithRowColFromCurrentPage ( final int rowIndex , final int colIndex ) { return CellUtility . getPoiCellWithRowColFromCurrentPage ( rowIndex , colIndex , parent . getWb ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the poi cell with row col from tab . [CODESPLIT] public final Cell getPoiCellWithRowColFromTab ( final int rowIndex , final int colIndex , final String tabName ) { if ( parent . getWb ( ) != null ) { return CellUtility . getPoiCellFromSheet ( rowIndex , colIndex , parent . getWb ( ) . getSheet ( parent . getSheetConfigMap ( ) . get ( tabName ) . getSheetName ( ) ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the faces cell with row col from current page . [CODESPLIT] public final FacesCell getFacesCellWithRowColFromCurrentPage ( final int rowIndex , final int colIndex ) { if ( parent . getBodyRows ( ) != null ) { int top = parent . getCurrent ( ) . getCurrentTopRow ( ) ; int left = parent . getCurrent ( ) . getCurrentLeftColumn ( ) ; return parent . getBodyRows ( ) . get ( rowIndex - top ) . getCells ( ) . get ( colIndex - left ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restore data context . [CODESPLIT] public final void restoreDataContext ( final String fullName ) { String [ ] parts = fullName . split ( \":\" ) ; if ( ! isNeedRestore ( fullName , parts ) ) { return ; } boolean stopSkip = false ; List < String > list = parent . getCurrent ( ) . getCurrentDataContextNameList ( ) ; int listSize = list . size ( ) ; // prepare collection data in context.\r // must loop through the full name which may have multiple\r // layer.\r // i.e. E.department.1:E.employee.0\r // need prepare department.1 and employee.0\r for ( int i = 0 ; i < parts . length ; i ++ ) { String part = parts [ i ] ; boolean skip = false ; if ( ( ! stopSkip ) && ( i < listSize ) ) { String listPart = list . get ( i ) ; if ( part . equalsIgnoreCase ( listPart ) ) { skip = true ; } } if ( ! skip ) { stopSkip = true ; startRestoreDataContext ( part ) ; } } if ( stopSkip ) { parent . getCurrent ( ) . setCurrentDataContextName ( fullName ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get last collect object from full name . [CODESPLIT] public final CollectionObject getLastCollect ( final String fullName ) { String [ ] parts = fullName . split ( \":\" ) ; String part = parts [ parts . length - 1 ] ; return startRestoreDataContext ( part ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is need restore . [CODESPLIT] private boolean isNeedRestore ( final String fullName , final String [ ] parts ) { if ( fullName == null ) { return false ; } if ( ( parent . getCurrent ( ) . getCurrentDataContextName ( ) != null ) && ( parent . getCurrent ( ) . getCurrentDataContextName ( ) . toLowerCase ( ) . startsWith ( fullName . toLowerCase ( ) ) ) ) { return false ; } return ( ( parts != null ) && ( parts . length > 1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start restore data context . [CODESPLIT] private CollectionObject startRestoreDataContext ( final String part ) { if ( part . startsWith ( TieConstants . EACH_COMMAND_FULL_NAME_PREFIX ) ) { String [ ] varparts = part . split ( \"\\\\.\" ) ; CollectionObject collect = new CollectionObject ( ) ; collect . setEachCommand ( CommandUtility . getEachCommandFromPartsName ( parent . getCurrentSheetConfig ( ) . getCommandIndexMap ( ) , varparts ) ) ; collect . setLastCollection ( ConfigurationUtility . transformToCollectionObject ( parent . getExpEngine ( ) , collect . getEachCommand ( ) . getItems ( ) , parent . getSerialDataContext ( ) . getDataContext ( ) ) ) ; collect . setLastCollectionIndex ( CommandUtility . prepareCollectionDataInContext ( varparts , collect . getLastCollection ( ) , parent . getSerialDataContext ( ) . getDataContext ( ) ) ) ; return collect ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shift row ref . [CODESPLIT] public final void shiftRowRef ( final Sheet sheet , final int shiftnum ) { try { this . setFirstRowRef ( sheet . getRow ( attrs . getFirstRowAddr ( ) . getRow ( ) + shiftnum ) . getCell ( attrs . getFirstRowAddr ( ) . getColumn ( ) , MissingCellPolicy . CREATE_NULL_AS_BLANK ) , false ) ; this . setLastRowPlusRef ( sheet , attrs . getLastRowPlusAddr ( ) . getColumn ( ) , attrs . getLastRowPlusAddr ( ) . getRow ( ) + shiftnum - 1 , false ) ; if ( commandList != null ) { for ( ConfigCommand command : commandList ) { command . shiftRowRef ( sheet , shiftnum ) ; } } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"shiftRowRef error =\" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set first cell also set static relative address firstCellAddress . [CODESPLIT] public final void setFirstRowRef ( final Cell pFirstRowRef , final boolean alsoCreateAddr ) { this . attrs . setFirstRowRef ( pFirstRowRef ) ; if ( alsoCreateAddr ) { this . setFirstRowAddr ( new SerialCellAddress ( pFirstRowRef ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set last cell also set static relative address lastCellAddress . [CODESPLIT] public final void setLastRowPlusRef ( final Sheet sheet , final int rightCol , final int lastRow , final boolean alsoSetAddr ) { if ( ( lastRow >= 0 ) && ( sheet != null ) && ( rightCol >= 0 ) ) { Row row = sheet . getRow ( lastRow + 1 ) ; if ( row == null ) { row = sheet . createRow ( lastRow + 1 ) ; } Cell cell = row . getCell ( rightCol ) ; if ( cell == null ) { cell = row . getCell ( rightCol , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; this . attrs . setLastCellCreated ( true ) ; } else { this . attrs . setLastCellCreated ( false ) ; } this . attrs . setLastRowPlusRef ( cell ) ; if ( alsoSetAddr ) { this . setLastRowPlusAddr ( new SerialCellAddress ( cell ) ) ; } } else { this . attrs . setLastRowPlusRef ( null ) ; if ( alsoSetAddr ) { this . attrs . setLastRowPlusAddr ( null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build the config range at specified point ( start row ) . context include the data objects for evaluation . build sequence is inside - out . e . g . first build all the command area the range included . each command will hold the final length after data populated . then buildCells build all cells in the range except those commands . and update the formulas . [CODESPLIT] public final int buildAt ( final String fullName , final ConfigBuildRef configBuildRef , final int atRow , final Map < String , Object > context , final List < RowsMapping > currentRowsMappingList ) { if ( commandList != null ) { for ( int i = 0 ; i < commandList . size ( ) ; i ++ ) { Command command = commandList . get ( i ) ; command . setFinalLength ( 0 ) ; int populatedLength = command . buildAt ( fullName , configBuildRef , command . getConfigRange ( ) . getFirstRowRef ( ) . getRowIndex ( ) , context , currentRowsMappingList ) ; command . setFinalLength ( populatedLength ) ; } } buildCells ( fullName , configBuildRef , atRow , context , currentRowsMappingList ) ; return this . getLastRowPlusRef ( ) . getRowIndex ( ) - this . getFirstRowRef ( ) . getRowIndex ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build all the static cells in the range ( exclude command areas ) . [CODESPLIT] private void buildCells ( final String fullName , final ConfigBuildRef configBuildRef , final int atRow , final Map < String , Object > context , final List < RowsMapping > rowsMappingList ) { if ( ( context == null ) || context . isEmpty ( ) ) { // no need to evaluate as there's no data object.\r return ; } // keep rowsMappingList as current as no change\r // allRowsMappingList = child + current\r List < RowsMapping > allRowsMappingList = ConfigurationUtility . findChildRowsMappingFromShiftMap ( fullName , configBuildRef . getShiftMap ( ) ) ; allRowsMappingList . addAll ( rowsMappingList ) ; int lastRowPlus = this . getLastRowPlusRef ( ) . getRowIndex ( ) ; ShiftFormulaRef shiftFormulaRef = new ShiftFormulaRef ( configBuildRef . getWatchList ( ) , allRowsMappingList ) ; for ( int i = atRow ; i < lastRowPlus ; i ++ ) { buildCellsForRow ( configBuildRef . getSheet ( ) . getRow ( i ) , fullName , context , configBuildRef , shiftFormulaRef ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the cells for row . [CODESPLIT] private void buildCellsForRow ( final Row row , final String fullName , final Map < String , Object > context , final ConfigBuildRef configBuildRef , ShiftFormulaRef shiftFormulaRef ) { if ( ( row == null ) || ! ConfigurationUtility . isStaticRowRef ( this , row ) ) { return ; } for ( Cell cell : row ) { buildSingleCell ( cell , context , configBuildRef , shiftFormulaRef ) ; } ConfigurationUtility . setFullNameInHiddenColumn ( row , fullName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the single cell . [CODESPLIT] private void buildSingleCell ( final Cell cell , final Map < String , Object > context , final ConfigBuildRef configBuildRef , final ShiftFormulaRef shiftFormulaRef ) { try { CommandUtility . evaluate ( context , cell , configBuildRef . getEngine ( ) ) ; if ( cell . getCellTypeEnum ( ) == CellType . FORMULA ) { // rebuild formula if necessary for dynamic row\r String originFormula = cell . getCellFormula ( ) ; shiftFormulaRef . setFormulaChanged ( 0 ) ; ConfigurationUtility . buildCellFormulaForShiftedRows ( configBuildRef . getSheet ( ) , configBuildRef . getWbWrapper ( ) , shiftFormulaRef , cell , cell . getCellFormula ( ) ) ; if ( shiftFormulaRef . getFormulaChanged ( ) > 0 ) { configBuildRef . getCachedCells ( ) . put ( cell , originFormula ) ; } } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"build cell ( row = \" + cell . getRowIndex ( ) + \" column = \" + cell . getColumnIndex ( ) + \" error = \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recover by using it s address . [CODESPLIT] public final void recover ( final Sheet sheet ) { this . getAttrs ( ) . recover ( sheet ) ; if ( this . commandList != null ) { for ( ConfigCommand command : this . commandList ) { command . recover ( sheet ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save the workbook before serialize . [CODESPLIT] private void writeObject ( final java . io . ObjectOutputStream out ) throws IOException { Gson objGson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; this . mapToJson = objGson . toJson ( this . dataContext ) ; out . defaultWriteObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load the workbook from saving . [CODESPLIT] private void readObject ( final java . io . ObjectInputStream in ) throws IOException { try { in . defaultReadObject ( ) ; Gson objGson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; Type listType = new TypeToken < Map < String , Object > > ( ) { } . getType ( ) ; this . dataContext = objGson . fromJson ( mapToJson , listType ) ; } catch ( EncryptedDocumentException | ClassNotFoundException e ) { LOG . log ( Level . SEVERE , \" error in readObject of serialWorkbook : \" + e . getLocalizedMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build categotry list . [CODESPLIT] public final void buildCategoryList ( final CTAxDataSource ctAxDs ) { List < ParsedCell > cells = new ArrayList <> ( ) ; try { String fullRangeName = ctAxDs . getStrRef ( ) . getF ( ) ; String sheetName = WebSheetUtility . getSheetNameFromFullCellRefName ( fullRangeName ) ; CellRangeAddress region = CellRangeAddress . valueOf ( WebSheetUtility . removeSheetNameFromFullCellRefName ( fullRangeName ) ) ; for ( int row = region . getFirstRow ( ) ; row <= region . getLastRow ( ) ; row ++ ) { for ( int col = region . getFirstColumn ( ) ; col <= region . getLastColumn ( ) ; col ++ ) { cells . add ( new ParsedCell ( sheetName , row , col ) ) ; } } } catch ( Exception ex ) { LOG . log ( Level . FINE , \"failed in buildCategoryList\" , ex ) ; } this . setCategoryList ( cells ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "build series list . [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public final void buildSeriesList ( final List bsers , final ThemesTable themeTable , final ChartObject ctObj ) { List < ChartSeries > lseriesList = new ArrayList <> ( ) ; try { for ( int index = 0 ; index < bsers . size ( ) ; index ++ ) { Object ctObjSer = bsers . get ( index ) ; ChartSeries ctSer = buildChartSeriesInList ( themeTable , ctObj , ctObjSer , index ) ; lseriesList . add ( ctSer ) ; } } catch ( Exception ex ) { LOG . log ( Level . FINE , \"failed in buildSerialList\" , ex ) ; } this . setSeriesList ( lseriesList ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the chart series in list . [CODESPLIT] private ChartSeries buildChartSeriesInList ( final ThemesTable themeTable , final ChartObject ctObj , final Object ctObjSer , final int index ) { ChartSeries ctSer = new ChartSeries ( ) ; ctSer . setSeriesLabel ( new ParsedCell ( ctObj . getSeriesLabelFromCTSer ( ctObjSer ) ) ) ; ctSer . setSeriesColor ( ColorUtility . geColorFromSpPr ( index , ctObj . getShapePropertiesFromCTSer ( ctObjSer ) , themeTable , ctObj . isLineColor ( ) ) ) ; List < ParsedCell > cells = new ArrayList <> ( ) ; String fullRangeName = ( ctObj . getCTNumDataSourceFromCTSer ( ctObjSer ) ) . getNumRef ( ) . getF ( ) ; String sheetName = WebSheetUtility . getSheetNameFromFullCellRefName ( fullRangeName ) ; CellRangeAddress region = CellRangeAddress . valueOf ( WebSheetUtility . removeSheetNameFromFullCellRefName ( fullRangeName ) ) ; for ( int row = region . getFirstRow ( ) ; row <= region . getLastRow ( ) ; row ++ ) { for ( int col = region . getFirstColumn ( ) ; col <= region . getLastColumn ( ) ; col ++ ) { cells . add ( new ParsedCell ( sheetName , row , col ) ) ; } } ctSer . setValueList ( cells ) ; ctSer . setValueColorList ( getColorListFromDPTWithValueList ( ctObj . getDPtListFromCTSer ( ctObjSer ) , cells , themeTable , ctObj ) ) ; return ctSer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get color list from dpt . [CODESPLIT] private List < XColor > getColorListFromDPTWithValueList ( final List < CTDPt > dptList , final List < ParsedCell > cells , final ThemesTable themeTable , final ChartObject ctObj ) { List < XColor > colors = new ArrayList <> ( ) ; if ( ( dptList != null ) && ( cells != null ) ) { for ( int index = 0 ; index < cells . size ( ) ; index ++ ) { CTDPt dpt = getDPtFromListWithIndex ( dptList , index ) ; CTShapeProperties ctSpPr = null ; if ( dpt != null ) { ctSpPr = dpt . getSpPr ( ) ; } colors . add ( ColorUtility . geColorFromSpPr ( index , ctSpPr , themeTable , ctObj . isLineColor ( ) ) ) ; } } return colors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get dpt from list . [CODESPLIT] private CTDPt getDPtFromListWithIndex ( final List < CTDPt > dptList , final int index ) { if ( dptList != null ) { for ( CTDPt dpt : dptList ) { if ( dpt . getIdx ( ) . getVal ( ) == index ) { return dpt ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the command index map . [CODESPLIT] public final void setCommandIndexMap ( final Map < String , Command > pcommandIndexMap ) { if ( pcommandIndexMap instanceof HashMap ) { this . commandIndexMap = ( HashMap < String , Command > ) pcommandIndexMap ; } else { this . commandIndexMap = new HashMap <> ( ) ; this . commandIndexMap . putAll ( pcommandIndexMap ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recover the cell reference to the sheet . [CODESPLIT] public void recover ( final Workbook wb ) { Sheet sheet = wb . getSheet ( this . sheetName ) ; this . getSerialCachedCells ( ) . recover ( sheet ) ; this . getSerialFinalCommentMap ( ) . recover ( sheet ) ; this . getFormCommand ( ) . recover ( sheet ) ; if ( this . getShiftMap ( ) != null ) { for ( Map . Entry < String , ConfigRangeAttrs > entry : this . getShiftMap ( ) . entrySet ( ) ) { entry . getValue ( ) . recover ( sheet ) ; } } if ( this . getCommandIndexMap ( ) != null ) { for ( Map . Entry < String , Command > entry : this . getCommandIndexMap ( ) . entrySet ( ) ) { entry . getValue ( ) . recover ( sheet ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the pictrues map . [CODESPLIT] public static void getPictruesMap ( final Workbook wb , final Map < String , Picture > picMap ) { if ( wb instanceof XSSFWorkbook ) { getXSSFPictruesMap ( ( XSSFWorkbook ) wb , picMap ) ; } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the XSSF pictrues map . [CODESPLIT] private static void getXSSFPictruesMap ( final XSSFWorkbook wb , final Map < String , Picture > picMap ) { picMap . clear ( ) ; List < XSSFPictureData > pictures = wb . getAllPictures ( ) ; if ( pictures . isEmpty ( ) ) { return ; } for ( int i = 0 ; i < wb . getNumberOfSheets ( ) ; i ++ ) { XSSFSheet sheet = wb . getSheetAt ( i ) ; for ( POIXMLDocumentPart dr : sheet . getRelations ( ) ) { try { indexPictureInMap ( picMap , sheet , dr ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"Load Picture error = \" + ex . getLocalizedMessage ( ) , ex ) ; } } } return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save pciture in map with index . [CODESPLIT] private static void indexPictureInMap ( final Map < String , Picture > picMap , final XSSFSheet sheet , final POIXMLDocumentPart dr ) { if ( dr instanceof XSSFDrawing ) { XSSFDrawing drawing = ( XSSFDrawing ) dr ; List < XSSFShape > shapes = drawing . getShapes ( ) ; for ( XSSFShape shape : shapes ) { if ( shape instanceof XSSFPicture ) { XSSFPicture pic = ( XSSFPicture ) shape ; XSSFClientAnchor anchor = pic . getPreferredSize ( ) ; CTMarker ctMarker = anchor . getFrom ( ) ; String picIndex = WebSheetUtility . getFullCellRefName ( sheet . getSheetName ( ) , ctMarker . getRow ( ) , ctMarker . getCol ( ) ) ; picMap . put ( picIndex , pic ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate picture style . [CODESPLIT] public static String generatePictureStyle ( final Sheet sheet1 , final FacesCell fcell , final Cell cell , final Picture pic ) { ClientAnchor anchor = pic . getClientAnchor ( ) ; if ( anchor != null ) { AnchorSize anchorSize = getAnchorSize ( sheet1 , fcell , cell , anchor ) ; if ( anchorSize != null ) { return \"MARGIN-LEFT:\" + String . format ( \"%.2f\" , anchorSize . getPercentLeft ( ) ) + \"%;MARGIN-TOP:\" + String . format ( \"%.2f\" , anchorSize . getPercentTop ( ) ) + \"%;width:\" + String . format ( \"%.2f\" , anchorSize . getPercentWidth ( ) ) + \"%;\" ; } } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate chart style . [CODESPLIT] public static String generateChartStyle ( final Sheet sheet1 , final FacesCell fcell , final Cell cell , final String chartId , final Map < String , ClientAnchor > anchorsMap ) { ClientAnchor anchor = anchorsMap . get ( chartId ) ; if ( anchor != null ) { AnchorSize anchorSize = getAnchorSize ( sheet1 , fcell , cell , anchor ) ; if ( anchorSize != null ) { return \"MARGIN-LEFT:\" + String . format ( \"%.2f\" , anchorSize . getPercentLeft ( ) ) + \"%;MARGIN-TOP:\" + String . format ( \"%.2f\" , anchorSize . getPercentTop ( ) ) + \"%;width:\" + String . format ( \"%.2f\" , anchorSize . getPercentWidth ( ) ) + \"%;height:135%;\" ; } } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the anchor size . [CODESPLIT] public static AnchorSize getAnchorSize ( final Sheet sheet1 , final FacesCell fcell , final Cell cell , final ClientAnchor anchor ) { if ( ! ( sheet1 instanceof XSSFSheet ) ) { return null ; } double picWidth = 0.0 ; double picHeight = 0.0 ; int left = anchor . getDx1 ( ) / org . apache . poi . util . Units . EMU_PER_PIXEL ; int top = ( int ) ( ( double ) anchor . getDy1 ( ) / org . apache . poi . util . Units . EMU_PER_PIXEL / WebSheetUtility . PICTURE_HEIGHT_ADJUST ) ; int right = anchor . getDx2 ( ) / org . apache . poi . util . Units . EMU_PER_PIXEL ; int bottom = ( int ) ( ( double ) anchor . getDy2 ( ) / org . apache . poi . util . Units . EMU_PER_PIXEL / WebSheetUtility . PICTURE_HEIGHT_ADJUST ) ; double cellWidth = 0.0 ; double cellHeight = 0.0 ; if ( ( cell != null ) && ( fcell != null ) ) { for ( int col = cell . getColumnIndex ( ) ; col < cell . getColumnIndex ( ) + fcell . getColspan ( ) ; col ++ ) { cellWidth += sheet1 . getColumnWidthInPixels ( col ) ; } double lastCellWidth = sheet1 . getColumnWidthInPixels ( cell . getColumnIndex ( ) + fcell . getColspan ( ) - 1 ) ; for ( int rowIndex = cell . getRowIndex ( ) ; rowIndex < cell . getRowIndex ( ) + fcell . getRowspan ( ) ; rowIndex ++ ) { cellHeight += WebSheetUtility . pointsToPixels ( sheet1 . getRow ( rowIndex ) . getHeightInPoints ( ) ) ; } double lastCellHeight = WebSheetUtility . pointsToPixels ( sheet1 . getRow ( cell . getRowIndex ( ) + fcell . getRowspan ( ) - 1 ) . getHeightInPoints ( ) ) ; picWidth = cellWidth - lastCellWidth + right - left ; picHeight = cellHeight - lastCellHeight + bottom - top ; } else { for ( short col = anchor . getCol1 ( ) ; col < anchor . getCol2 ( ) ; col ++ ) { picWidth += sheet1 . getColumnWidthInPixels ( col ) ; } for ( int rowindex = anchor . getRow1 ( ) ; rowindex < anchor . getRow2 ( ) ; rowindex ++ ) { Row row = sheet1 . getRow ( rowindex ) ; if ( row != null ) { picHeight += WebSheetUtility . pointsToPixels ( row . getHeightInPoints ( ) ) ; } } } return new AnchorSize ( left , top , ( int ) picWidth , ( int ) picHeight , cellWidth , cellHeight ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put . [CODESPLIT] public final void put ( final Cell cell , final CellType formula ) { Map < Cell , FormulaMapping > map = cachedMap ; // if cellType not null then only specified Type will be put into Cache\r // e.g. only formula cell will be cached then pass in\r // Cell.CELL_TYPE_FORMULA\r if ( ( cell != null ) && ( ( formula == null ) || ( cell . getCellTypeEnum ( ) == formula ) ) ) { String value = CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) ; FormulaMapping f = map . get ( cell ) ; if ( f == null ) { f = new FormulaMapping ( ) ; } f . setValue ( value ) ; map . put ( cell , f ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put . [CODESPLIT] public final void put ( final Cell cell , final String originFormula ) { Map < Cell , FormulaMapping > map = cachedMap ; // if cellType not null then only specified Type will be put into Cache\r // e.g. only formula cell will be cached then pass in\r // Cell.CELL_TYPE_FORMULA\r if ( ( cell != null ) && ( originFormula != null ) ) { FormulaMapping f = map . get ( cell ) ; if ( f == null ) { f = new FormulaMapping ( ) ; } f . setOriginFormula ( originFormula ) ; String value = CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) ; f . setValue ( value ) ; map . put ( cell , f ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is value changed . [CODESPLIT] public final boolean isValueChanged ( final Cell cell ) { String newValue = CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) ; return isValueChanged ( cell , newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is value changed . [CODESPLIT] public final boolean isValueChanged ( final Cell cell , final String pnewValue ) { Map < Cell , FormulaMapping > map = cachedMap ; String oldValue = map . get ( cell ) . getValue ( ) ; String newValue = pnewValue ; if ( oldValue == null ) { oldValue = \"\" ; } if ( newValue == null ) { newValue = \"\" ; } return ( ! oldValue . equals ( newValue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the pattern . [CODESPLIT] public Pattern getPattern ( ) { if ( ( this . pattern == null ) && ( alias != null ) ) { this . pattern = Pattern . compile ( \"\\\\s*\" + ParserUtility . wildcardToRegex ( alias ) ) ; } return pattern ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final void encodeBegin ( final FacesContext context ) throws IOException { webSheetBean = ( TieWebSheetBean ) this . getAttributes ( ) . get ( TieConstants . ATTRS_WEBSHEETBEAN ) ; if ( ( webSheetBean != null ) && ( webSheetBean . getWebFormClientId ( ) == null ) ) { LOG . fine ( \"WebSheet component parameter setup\" ) ; webSheetBean . setClientId ( this . getClientId ( ) ) ; webSheetBean . setWebFormClientId ( this . getClientId ( ) + \":\" + TieConstants . COMPONENT_ID ) ; String maxrows = ( String ) this . getAttributes ( ) . get ( \"maxRowsPerPage\" ) ; if ( ( maxrows != null ) && ( ! maxrows . isEmpty ( ) ) ) { webSheetBean . setMaxRowsPerPage ( Integer . valueOf ( maxrows ) ) ; } Boolean hideSingleSheetTabTitle = ( Boolean ) this . getAttributes ( ) . get ( \"hideSingleSheetTabTitle\" ) ; if ( hideSingleSheetTabTitle != null ) { webSheetBean . setHideSingleSheetTabTitle ( hideSingleSheetTabTitle ) ; } } super . encodeBegin ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return real chart picture when browser requesting the image . [CODESPLIT] public StreamedContent getChart ( ) throws IOException { FacesContext context = FacesContext . getCurrentInstance ( ) ; if ( context . getCurrentPhaseId ( ) == PhaseId . RENDER_RESPONSE ) { // So, we're rendering the HTML. Return a stub StreamedContent so\r // that it will generate right URL.\r LOG . fine ( \" return empty chart picture\" ) ; return new DefaultStreamedContent ( ) ; } else { // So, browser is requesting the image. Return a real\r // StreamedContent with the image bytes.\r String chartId = context . getExternalContext ( ) . getRequestParameterMap ( ) . get ( \"chartViewId\" ) ; BufferedImage bufferedImg = ( BufferedImage ) FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getSessionMap ( ) . get ( chartId ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; ImageIO . write ( bufferedImg , \"png\" , os ) ; FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getSessionMap ( ) . remove ( chartId ) ; return new DefaultStreamedContent ( new ByteArrayInputStream ( os . toByteArray ( ) ) , \"image/png\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "save the cell before serialize . [CODESPLIT] private void writeObject ( final java . io . ObjectOutputStream out ) throws IOException { this . cellAddr = new SerialCellAddress ( this . cell ) ; out . defaultWriteObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recover cell by using it s address . [CODESPLIT] public final void recover ( final Sheet sheet ) { if ( this . cellAddr != null ) { this . setCell ( sheet . getRow ( this . cellAddr . getRow ( ) ) . getCell ( this . cellAddr . getColumn ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the row style . [CODESPLIT] public static String getRowStyle ( final Workbook wb , final Cell poiCell , final String inputType , final float rowHeight , final int rowspan ) { CellStyle cellStyle = poiCell . getCellStyle ( ) ; if ( ( cellStyle != null ) && ( rowspan == 1 ) ) { short fontIdx = cellStyle . getFontIndex ( ) ; Font font = wb . getFontAt ( fontIdx ) ; float maxHeight = rowHeight ; if ( ! inputType . isEmpty ( ) ) { maxHeight = Math . min ( font . getFontHeightInPoints ( ) + 8f , rowHeight ) ; } return \"height:\" + WebSheetUtility . pointsToPixels ( maxHeight ) + \"px;\" ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the cell font style . [CODESPLIT] public static String getCellFontStyle ( final Workbook wb , final Cell poiCell ) { CellStyle cellStyle = poiCell . getCellStyle ( ) ; StringBuilder webStyle = new StringBuilder ( ) ; if ( cellStyle != null ) { short fontIdx = cellStyle . getFontIndex ( ) ; Font font = wb . getFontAt ( fontIdx ) ; if ( font . getItalic ( ) ) { webStyle . append ( \"font-style: italic;\" ) ; } if ( font . getBold ( ) ) { webStyle . append ( \"font-weight: bold;\" ) ; } webStyle . append ( \"font-size: \" + font . getFontHeightInPoints ( ) + \"pt;\" ) ; String decoration = getCellFontDecoration ( font ) ; if ( decoration . length ( ) > 0 ) { webStyle . append ( \"text-decoration:\" + decoration + \";\" ) ; } webStyle . append ( getCellFontColor ( font ) ) ; } return webStyle . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get cell font color . [CODESPLIT] private static String getCellFontColor ( final Font font ) { short [ ] rgbfix = { TieConstants . RGB_MAX , TieConstants . RGB_MAX , TieConstants . RGB_MAX } ; if ( font instanceof XSSFFont ) { XSSFColor color = ( ( XSSFFont ) font ) . getXSSFColor ( ) ; if ( color != null ) { rgbfix = ColorUtility . getTripletFromXSSFColor ( color ) ; } } if ( rgbfix [ 0 ] != TieConstants . RGB_MAX ) { return \"color:rgb(\" + FacesUtility . strJoin ( rgbfix , \",\" ) + \");\" ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get font decoration . [CODESPLIT] private static String getCellFontDecoration ( final Font font ) { StringBuilder decoration = new StringBuilder ( ) ; if ( font . getUnderline ( ) != 0 ) { decoration . append ( \" underline\" ) ; } if ( font . getStrikeout ( ) ) { decoration . append ( \" line-through\" ) ; } return decoration . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the cell style . [CODESPLIT] public static String getCellStyle ( final Workbook wb , final Cell poiCell , final String inputType ) { CellStyle cellStyle = poiCell . getCellStyle ( ) ; StringBuilder webStyle = new StringBuilder ( ) ; if ( cellStyle != null ) { if ( ! inputType . isEmpty ( ) ) { webStyle . append ( getAlignmentFromCell ( poiCell , cellStyle ) ) ; webStyle . append ( getVerticalAlignmentFromCell ( cellStyle ) ) ; } webStyle . append ( ColorUtility . getBgColorFromCell ( wb , poiCell , cellStyle ) ) ; } return webStyle . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the column style . [CODESPLIT] public static String getColumnStyle ( final Workbook wb , final FacesCell fcell , final Cell poiCell , final float rowHeight ) { String inputType = fcell . getInputType ( ) ; CellStyle cellStyle = poiCell . getCellStyle ( ) ; StringBuilder webStyle = new StringBuilder ( ) ; if ( cellStyle != null ) { if ( fcell . isContainPic ( ) || fcell . isContainChart ( ) ) { webStyle . append ( \"vertical-align: top;\" ) ; } else { webStyle . append ( getAlignmentFromCell ( poiCell , cellStyle ) ) ; webStyle . append ( getVerticalAlignmentFromCell ( cellStyle ) ) ; } webStyle . append ( ColorUtility . getBgColorFromCell ( wb , poiCell , cellStyle ) ) ; webStyle . append ( getRowStyle ( wb , poiCell , inputType , rowHeight , fcell . getRowspan ( ) ) ) ; } else { webStyle . append ( getAlignmentFromCellType ( poiCell ) ) ; } return webStyle . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the alignment from cell . [CODESPLIT] private static String getAlignmentFromCell ( final Cell poiCell , final CellStyle cellStyle ) { String style = \"\" ; switch ( cellStyle . getAlignmentEnum ( ) ) { case LEFT : style = TieConstants . TEXT_ALIGN_LEFT ; break ; case RIGHT : style = TieConstants . TEXT_ALIGN_RIGHT ; break ; case CENTER : style = TieConstants . TEXT_ALIGN_CENTER ; break ; case GENERAL : style = getAlignmentFromCellType ( poiCell ) ; break ; default : break ; } return style ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the vertical alignment from cell . [CODESPLIT] private static String getVerticalAlignmentFromCell ( final CellStyle cellStyle ) { String style = \"\" ; switch ( cellStyle . getVerticalAlignmentEnum ( ) ) { case TOP : style = TieConstants . VERTICAL_ALIGN_TOP ; break ; case CENTER : style = TieConstants . VERTICAL_ALIGN_CENTER ; break ; case BOTTOM : style = TieConstants . VERTICAL_ALIGN_BOTTOM ; break ; default : break ; } return style ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "e . g . lineNumberColumnWidth and addRowColumnWidth [CODESPLIT] public static int calcTotalWidth ( final Sheet sheet1 , final int firstCol , final int lastCol , final int additionalWidth ) { int totalWidth = additionalWidth ; for ( int i = firstCol ; i <= lastCol ; i ++ ) { totalWidth += sheet1 . getColumnWidth ( i ) ; } return totalWidth ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calc total height . [CODESPLIT] public static int calcTotalHeight ( final Sheet sheet1 , final int firstRow , final int lastRow , final int additionalHeight ) { int totalHeight = additionalHeight ; for ( int i = firstRow ; i <= lastRow ; i ++ ) { totalHeight += sheet1 . getRow ( i ) . getHeight ( ) ; } return totalHeight ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup cell style . [CODESPLIT] public static void setupCellStyle ( final Workbook wb , final FacesCell fcell , final Cell poiCell , final float rowHeight ) { CellStyle cellStyle = poiCell . getCellStyle ( ) ; if ( ( cellStyle != null ) && ( ! cellStyle . getLocked ( ) ) ) { // not locked\r if ( fcell . getInputType ( ) . isEmpty ( ) ) { fcell . setInputType ( CellStyleUtility . getInputTypeFromCellType ( poiCell ) ) ; } if ( fcell . getControl ( ) . isEmpty ( ) && ( ! fcell . getInputType ( ) . isEmpty ( ) ) ) { fcell . setControl ( \"text\" ) ; } setInputStyleBaseOnInputType ( fcell , poiCell ) ; } String webStyle = getCellStyle ( wb , poiCell , fcell . getInputType ( ) ) + getCellFontStyle ( wb , poiCell ) + getRowStyle ( wb , poiCell , fcell . getInputType ( ) , rowHeight , fcell . getRowspan ( ) ) ; fcell . setStyle ( webStyle ) ; fcell . setColumnStyle ( getColumnStyle ( wb , fcell , poiCell , rowHeight ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set up Input Style parameter for input number component which need those parameters to make it work . e . g . symbol symbol position decimal places . [CODESPLIT] static void setInputStyleBaseOnInputType ( final FacesCell fcell , final Cell poiCell ) { if ( ( fcell == null ) || fcell . getInputType ( ) . isEmpty ( ) ) { return ; } switch ( fcell . getInputType ( ) ) { case TieConstants . CELL_INPUT_TYPE_PERCENTAGE : fcell . setSymbol ( \"%\" ) ; fcell . setSymbolPosition ( \"p\" ) ; fcell . setDecimalPlaces ( CellStyleUtility . getDecimalPlacesFromFormat ( poiCell ) ) ; break ; case TieConstants . CELL_INPUT_TYPE_INTEGER : fcell . setDecimalPlaces ( ( short ) 0 ) ; break ; case TieConstants . CELL_INPUT_TYPE_DOUBLE : fcell . setDecimalPlaces ( CellStyleUtility . getDecimalPlacesFromFormat ( poiCell ) ) ; fcell . setSymbol ( CellStyleUtility . getSymbolFromFormat ( poiCell ) ) ; fcell . setSymbolPosition ( CellStyleUtility . getSymbolPositionFromFormat ( poiCell ) ) ; break ; default : break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the input type from cell type . [CODESPLIT] @ SuppressWarnings ( \"deprecation\" ) private static String getInputTypeFromCellType ( final Cell cell ) { String inputType = TieConstants . CELL_INPUT_TYPE_TEXT ; if ( cell . getCellTypeEnum ( ) == CellType . NUMERIC ) { inputType = TieConstants . CELL_INPUT_TYPE_DOUBLE ; } CellStyle style = cell . getCellStyle ( ) ; if ( style != null ) { int formatIndex = style . getDataFormat ( ) ; String formatString = style . getDataFormatString ( ) ; if ( DateUtil . isADateFormat ( formatIndex , formatString ) ) { inputType = TieConstants . CELL_INPUT_TYPE_DATE ; } else { if ( isAPercentageCell ( formatString ) ) { inputType = TieConstants . CELL_INPUT_TYPE_PERCENTAGE ; } } } return inputType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get decimal places from format string e . g . 0 . 00 will return 2 [CODESPLIT] private static short getDecimalPlacesFromFormat ( final Cell cell ) { CellStyle style = cell . getCellStyle ( ) ; if ( style == null ) { return 0 ; } String formatString = style . getDataFormatString ( ) ; if ( formatString == null ) { return 0 ; } int ipos = formatString . indexOf ( ' ' ) ; if ( ipos < 0 ) { return 0 ; } short counter = 0 ; for ( int i = ipos + 1 ; i < formatString . length ( ) ; i ++ ) { if ( formatString . charAt ( i ) == ' ' ) { counter ++ ; } else { break ; } } return counter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get symbol from format string e . g . [ $CAD ] # ##0 . 00 will return CAD . While $# ##0 . 00 will return $ [CODESPLIT] private static String getSymbolFromFormat ( final Cell cell ) { CellStyle style = cell . getCellStyle ( ) ; if ( style == null ) { return null ; } String formatString = style . getDataFormatString ( ) ; if ( formatString == null ) { return null ; } if ( formatString . indexOf ( TieConstants . CELL_ADDR_PRE_FIX ) < 0 ) { return null ; } int ipos = formatString . indexOf ( \"[$\" ) ; if ( ipos < 0 ) { // only $ found, then return default dollar symbol\r return \"$\" ; } // return specified dollar symbol\r return formatString . substring ( ipos + 2 , formatString . indexOf ( ' ' , ipos ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get symbol position from format string e . g . [ $CAD ] # ##0 . 00 will return p . While # ##0 . 00 $ will return s [CODESPLIT] private static String getSymbolPositionFromFormat ( final Cell cell ) { CellStyle style = cell . getCellStyle ( ) ; if ( style == null ) { return \"p\" ; } String formatString = style . getDataFormatString ( ) ; if ( formatString == null ) { return \"p\" ; } int symbolpos = formatString . indexOf ( ' ' ) ; int numberpos = formatString . indexOf ( ' ' ) ; if ( numberpos < 0 ) { numberpos = formatString . indexOf ( ' ' ) ; } if ( symbolpos < numberpos ) { return \"p\" ; } else { return \"s\" ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return faces context resource path . [CODESPLIT] public static Set < String > getResourcePaths ( final FacesContext context , final String path ) { return context . getExternalContext ( ) . getResourcePaths ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get resource file as stream . [CODESPLIT] public static InputStream getResourceAsStream ( final FacesContext context , final String path ) { return context . getExternalContext ( ) . getResourceAsStream ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "evaluate expression . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T evaluateExpressionGet ( final FacesContext context , final String expression ) { if ( expression == null ) { return null ; } return ( T ) context . getApplication ( ) . evaluateExpressionGet ( context , expression , Object . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove prefix path of the full path . [CODESPLIT] public static String removePrefixPath ( final String prefix , final String resource ) { String normalizedResource = resource ; if ( normalizedResource . startsWith ( prefix ) ) { normalizedResource = normalizedResource . substring ( prefix . length ( ) - 1 ) ; } return normalizedResource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "evaluate input type . [CODESPLIT] public static boolean evalInputType ( final String input , final String type ) { Scanner scanner = new Scanner ( input ) ; boolean ireturn = false ; if ( \"Integer\" . equalsIgnoreCase ( type ) ) { ireturn = scanner . hasNextInt ( ) ; } else if ( \"Double\" . equalsIgnoreCase ( type ) ) { ireturn = scanner . hasNextDouble ( ) ; } else if ( \"Boolean\" . equalsIgnoreCase ( type ) ) { ireturn = scanner . hasNextBoolean ( ) ; } else if ( \"Byte\" . equalsIgnoreCase ( type ) ) { ireturn = scanner . hasNextByte ( ) ; } else if ( type . toLowerCase ( ) . startsWith ( \"text\" ) ) { ireturn = true ; } scanner . close ( ) ; return ireturn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find bean in context . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T findBean ( final String beanName ) { FacesContext context = FacesContext . getCurrentInstance ( ) ; return ( T ) context . getApplication ( ) . evaluateExpressionGet ( context , TieConstants . EL_START + beanName + TieConstants . EL_END , Object . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "evaluate expression . [CODESPLIT] public static < T > T evaluateExpression ( final String expression , final Class < ? extends T > expected ) { return evaluateExpression ( FacesContext . getCurrentInstance ( ) , expression , expected ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "evaluate expression . [CODESPLIT] public static < T > T evaluateExpression ( final FacesContext context , final String expression , final Class < ? extends T > expected ) { return context . getApplication ( ) . evaluateExpressionGet ( context , expression , expected ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "join string . [CODESPLIT] public static String strJoin ( final short [ ] aArr , final String sSep ) { StringBuilder sbStr = new StringBuilder ( ) ; for ( int i = 0 , il = aArr . length ; i < il ; i ++ ) { if ( i > 0 ) { sbStr . append ( sSep ) ; } sbStr . append ( aArr [ i ] ) ; } return sbStr . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "round number according to decimal places . [CODESPLIT] public static double round ( final double value , final int places ) { if ( places < 0 ) { throw new IllegalArgumentException ( ) ; } BigDecimal bd = BigDecimal . valueOf ( value ) ; bd = bd . setScale ( places , RoundingMode . HALF_UP ) ; return bd . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get tab type . [CODESPLIT] public String getTabType ( ) { int sheetId = webFormTabView . getActiveIndex ( ) ; if ( ( sheetId >= 0 ) && ( tabs != null ) ) { if ( sheetId >= tabs . size ( ) ) { sheetId = 0 ; } tabType = tabs . get ( sheetId ) . type . toLowerCase ( ) ; } else { tabType = TieConstants . TAB_TYPE_NONE ; } return tabType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get tab style . [CODESPLIT] public String getTabStyle ( ) { String tabStyle = TieConstants . TAB_STYLE_VISIBLE ; int sheetId = webFormTabView . getActiveIndex ( ) ; if ( ( sheetId >= 0 ) && ( sheetId < tabs . size ( ) ) ) { tabStyle = TieConstants . TAB_STYLE_INVISIBLE ; } return tabStyle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the default date pattern . [CODESPLIT] public String getDefaultDatePattern ( ) { if ( defaultDatePattern == null ) { DateFormat formatter = DateFormat . getDateInstance ( DateFormat . SHORT , Locale . getDefault ( ) ) ; defaultDatePattern = ( ( SimpleDateFormat ) formatter ) . toLocalizedPattern ( ) ; } return defaultDatePattern ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the decimal separator by default locale . [CODESPLIT] public String getDecimalSeparatorByDefaultLocale ( ) { final DecimalFormat nf = ( DecimalFormat ) DecimalFormat . getInstance ( getDefaultLocale ( ) ) ; return \"\" + nf . getDecimalFormatSymbols ( ) . getDecimalSeparator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the thousand separator by default locale . [CODESPLIT] public String getThousandSeparatorByDefaultLocale ( ) { final DecimalFormat nf = ( DecimalFormat ) DecimalFormat . getInstance ( getDefaultLocale ( ) ) ; return \"\" + nf . getDecimalFormatSymbols ( ) . getGroupingSeparator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the tie command alias list . [CODESPLIT] public void setTieCommandAliasList ( String aliasListJson ) { Gson gson = new Gson ( ) ; Type aliasListType = new TypeToken < ArrayList < TieCommandAlias > > ( ) { } . getType ( ) ; this . tieCommandAliasList = gson . fromJson ( aliasListJson , aliasListType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Watch list serve for formula changes . Basically all the rows appeared in the formula in the current sheet will be watched . Note if the cell reference is from other sheet or workbooks it will be ignored . [CODESPLIT] private List < Integer > buildFormWatchList ( final XSSFEvaluationWorkbook wbWrapper , final Sheet sheet ) { List < Integer > watchList = new ArrayList <> ( ) ; ConfigRange cRange = this . getConfigRange ( ) ; List < ConfigCommand > commandList = cRange . getCommandList ( ) ; if ( commandList . isEmpty ( ) ) { // if no command then no dynamic changes. then no need formula\r // shifts.\r return watchList ; } int lastStaticRow = commandList . get ( 0 ) . getTopRow ( ) - 1 ; if ( lastStaticRow < 0 ) { lastStaticRow = this . getTopRow ( ) ; } int sheetIndex = sheet . getWorkbook ( ) . getSheetIndex ( sheet ) ; for ( int i = this . getTopRow ( ) ; i <= this . getLastRow ( ) ; i ++ ) { Row row = sheet . getRow ( i ) ; for ( Cell cell : row ) { if ( cell . getCellTypeEnum ( ) == CellType . FORMULA ) { buildWatchListForCell ( wbWrapper , sheetIndex , cell , watchList , lastStaticRow ) ; } } } return watchList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the watch list for cell . [CODESPLIT] private void buildWatchListForCell ( final XSSFEvaluationWorkbook wbWrapper , final int sheetIndex , final Cell cell , final List < Integer > watchList , final int lastStaticRow ) { String formula = cell . getCellFormula ( ) ; Ptg [ ] ptgs = FormulaParser . parse ( formula , wbWrapper , FormulaType . CELL , sheetIndex ) ; for ( int k = 0 ; k < ptgs . length ; k ++ ) { Object ptg = ptgs [ k ] ; // For area formula, only first row is watched.\r // Reason is the lastRow must shift same rows with\r // firstRow.\r // Otherwise it's difficult to calculate.\r // In case some situation cannot fit, then should make\r // change to the formula.\r int areaInt = ShiftFormulaUtility . getFirstSupportedRowNumFromPtg ( ptg ) ; if ( areaInt >= 0 ) { addToWatchList ( areaInt , lastStaticRow , watchList ) ; } } // when insert row, the formula may changed. so here is the\r // workaround.\r // change formula to user formula to preserve the row\r // changes.\r cell . setCellType ( CellType . STRING ) ; cell . setCellValue ( TieConstants . USER_FORMULA_PREFIX + formula + TieConstants . USER_FORMULA_SUFFIX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only rows in dynamic area will be added to watch list . [CODESPLIT] private void addToWatchList ( final int addRow , final int lastStaticRow , final List < Integer > watchList ) { if ( ( addRow > lastStaticRow ) && ! ( watchList . contains ( addRow ) ) ) { watchList . add ( addRow ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override /**\r\n\t * build the command area at the row.\r\n\t */ public final int buildAt ( String fullName , final ConfigBuildRef configBuildRef , final int atRow , final Map < String , Object > context , List < RowsMapping > currentRowsMappingList ) { configBuildRef . setWatchList ( buildFormWatchList ( configBuildRef . getWbWrapper ( ) , configBuildRef . getSheet ( ) ) ) ; fullName = this . getCommandName ( ) ; RowsMapping unitRowsMapping = new RowsMapping ( ) ; for ( Integer index : configBuildRef . getWatchList ( ) ) { if ( ConfigurationUtility . isStaticRow ( this . getConfigRange ( ) , index ) ) { unitRowsMapping . addRow ( index , configBuildRef . getSheet ( ) . getRow ( index ) ) ; } } currentRowsMappingList = new ArrayList <> ( ) ; currentRowsMappingList . add ( unitRowsMapping ) ; this . getConfigRange ( ) . getAttrs ( ) . setAllowAdd ( false ) ; configBuildRef . putShiftAttrs ( fullName , this . getConfigRange ( ) . getAttrs ( ) , new RowsMapping ( unitRowsMapping ) ) ; configBuildRef . setOriginConfigRange ( new ConfigRange ( this . getConfigRange ( ) ) ) ; configBuildRef . getOriginConfigRange ( ) . indexCommandRange ( configBuildRef . getCommandIndexMap ( ) ) ; int length = this . getConfigRange ( ) . buildAt ( fullName , configBuildRef , atRow , context , currentRowsMappingList ) ; this . getConfigRange ( ) . getAttrs ( ) . setFinalLength ( length ) ; this . setFinalLength ( length ) ; configBuildRef . getSheet ( ) . setColumnHidden ( TieConstants . HIDDEN_FULL_NAME_COLUMN , true ) ; configBuildRef . getSheet ( ) . setColumnHidden ( TieConstants . HIDDEN_SAVE_OBJECTS_COLUMN , true ) ; configBuildRef . getSheet ( ) . setColumnHidden ( TieConstants . HIDDEN_ORIGIN_ROW_NUMBER_COLUMN , true ) ; return length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) @ Override public final List getSerListFromCtObjChart ( final Object ctObjChart ) { if ( ctObjChart instanceof CTLineChart ) { return ( ( CTLineChart ) ctObjChart ) . getSerList ( ) ; } return emptyLinelist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTShapeProperties getShapePropertiesFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTLineSer ) { return ( ( CTLineSer ) ctObjSer ) . getSpPr ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTNumDataSource getCTNumDataSourceFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTLineSer ) { return ( ( CTLineSer ) ctObjSer ) . getVal ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check it s a command comment . [CODESPLIT] public static boolean isCommandString ( final String str ) { if ( str == null ) { return false ; } return str . startsWith ( TieConstants . COMMAND_PREFIX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method string is start as $ follow by method name then with { and } . i . e . $init { department . name } [CODESPLIT] public static boolean isMethodString ( final String str ) { if ( str == null ) { return false ; } return str . matches ( TieConstants . METHOD_REGEX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "empty method string is start as $ follow with { and } . i . e . $ { department . name } [CODESPLIT] public static boolean isEmptyMethodString ( final String str ) { if ( str == null ) { return false ; } return str . startsWith ( TieConstants . METHOD_PREFIX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "widget method start with $widget . e . g . $widget . calendar { .... [CODESPLIT] public static boolean isWidgetMethodString ( final String str ) { if ( str == null ) { return false ; } return str . startsWith ( TieConstants . METHOD_WIDGET_PREFIX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "validate method start with $validate { rule = ... error = ... } . [CODESPLIT] public static boolean isValidateMethodString ( final String str ) { if ( str == null ) { return false ; } return str . startsWith ( TieConstants . METHOD_VALIDATE_PREFIX ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the widget attributes . [CODESPLIT] public static void parseWidgetAttributes ( final Cell cell , final String newComment , final CellAttributesMap cellAttributesMap ) { if ( ( newComment == null ) || ( newComment . isEmpty ( ) ) ) { return ; } int widgetStart = newComment . indexOf ( TieConstants . METHOD_WIDGET_PREFIX ) ; int elStart = newComment . indexOf ( TieConstants . EL_START_BRACKET ) ; if ( ( widgetStart < 0 ) || ( widgetStart >= elStart ) ) { return ; } String type = newComment . substring ( widgetStart + TieConstants . METHOD_WIDGET_PREFIX . length ( ) , elStart ) ; String values = getStringBetweenBracket ( newComment ) ; if ( values == null ) { return ; } // map's key is sheetName!$columnIndex$rowIndex\r String key = getAttributeKeyInMapByCell ( cell ) ; // one cell only has one control widget\r cellAttributesMap . getCellInputType ( ) . put ( key , type ) ; List < CellFormAttributes > inputs = cellAttributesMap . getCellInputAttributes ( ) . get ( key ) ; if ( inputs == null ) { inputs = new ArrayList <> ( ) ; cellAttributesMap . getCellInputAttributes ( ) . put ( key , inputs ) ; } parseInputAttributes ( inputs , values ) ; parseSpecialAttributes ( key , type , inputs , cellAttributesMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get attribute key in map by cell . [CODESPLIT] public static String getAttributeKeyInMapByCell ( final Cell cell ) { if ( cell == null ) { return null ; } // map's key is sheetName!$columnIndex$rowIndex\r return cell . getSheet ( ) . getSheetName ( ) + \"!\" + CellUtility . getCellIndexNumberKey ( cell ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the validate attributes . [CODESPLIT] public static void parseValidateAttributes ( final Cell cell , final String newComment , final CellAttributesMap cellAttributesMap ) { if ( ( newComment == null ) || ( newComment . isEmpty ( ) ) ) { return ; } if ( ! newComment . startsWith ( TieConstants . METHOD_VALIDATE_PREFIX ) ) { return ; } String values = getStringBetweenBracket ( newComment ) ; if ( values == null ) { return ; } // map's key is sheetName!$columnIndex$rowIndex\r String key = getAttributeKeyInMapByCell ( cell ) ; List < CellFormAttributes > attrs = cellAttributesMap . getCellValidateAttributes ( ) . get ( key ) ; if ( attrs == null ) { attrs = new ArrayList <> ( ) ; cellAttributesMap . getCellValidateAttributes ( ) . put ( key , attrs ) ; } parseValidateAttributes ( attrs , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the string between two bracket . . e . g . $save { employee . name } return employee . name . [CODESPLIT] public static String getStringBetweenBracket ( final String newComment ) { if ( newComment == null ) { return null ; } int elStart = newComment . indexOf ( TieConstants . EL_START_BRACKET ) ; int elEnd = findPairBracketPosition ( newComment , elStart ) ; if ( elStart >= elEnd ) { return null ; } return newComment . substring ( elStart + 1 , elEnd ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find pair bracket position . [CODESPLIT] private static int findPairBracketPosition ( final String str , final int startPos ) { int bracketNum = 0 ; for ( int i = startPos ; i < str . length ( ) ; i ++ ) { char current = str . charAt ( i ) ; if ( current == TieConstants . EL_START_BRACKET ) { bracketNum ++ ; } else if ( current == TieConstants . EL_END ) { bracketNum -- ; if ( bracketNum <= 0 ) { return i ; } } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the attributes from string . [CODESPLIT] public static Map < String , String > parseCommandAttributes ( final String attrString ) { Map < String , String > attrMap = new LinkedHashMap <> ( ) ; Matcher attrMatcher = TieConstants . ATTR_REGEX_PATTERN . matcher ( attrString ) ; while ( attrMatcher . find ( ) ) { String attrData = attrMatcher . group ( ) ; int attrNameEndIndex = attrData . indexOf ( ' ' ) ; String attrName = attrData . substring ( 0 , attrNameEndIndex ) . trim ( ) ; String attrValuePart = attrData . substring ( attrNameEndIndex + 1 ) . trim ( ) ; String attrValue = attrValuePart . substring ( 1 , attrValuePart . length ( ) - 1 ) ; attrMap . put ( attrName , attrValue ) ; } return attrMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse input attributes . [CODESPLIT] public static void parseInputAttributes ( final List < CellFormAttributes > clist , final String controlAttrs ) { // only one type control allowed for one cell.\r clist . clear ( ) ; if ( controlAttrs != null ) { String [ ] cattrs = controlAttrs . split ( TieConstants . SPLIT_SPACE_SEPERATE_ATTRS_REGX , - 1 ) ; for ( String cattr : cattrs ) { String [ ] details = splitByEualSign ( cattr ) ; if ( details . length > 1 ) { CellFormAttributes attr = new CellFormAttributes ( ) ; attr . setType ( details [ 0 ] . trim ( ) ) ; attr . setValue ( details [ 1 ] . replaceAll ( \"\\\"\" , \"\" ) ) ; clist . add ( attr ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse validate attributes . [CODESPLIT] public static void parseValidateAttributes ( final List < CellFormAttributes > clist , final String controlAttrs ) { // one cell could have multiple validation rules.\r if ( controlAttrs == null ) { return ; } String [ ] cattrs = controlAttrs . split ( TieConstants . SPLIT_SPACE_SEPERATE_ATTRS_REGX , - 1 ) ; CellFormAttributes attr = new CellFormAttributes ( ) ; for ( String cattr : cattrs ) { extractValidationAttributes ( attr , cattr ) ; } if ( ( attr . getValue ( ) != null ) && ( ! attr . getValue ( ) . isEmpty ( ) ) ) { clist . add ( attr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extractValidationAttributes . [CODESPLIT] private static void extractValidationAttributes ( final CellFormAttributes attr , final String cattr ) { String [ ] details = splitByEualSign ( cattr ) ; if ( details . length > 1 ) { if ( details [ 0 ] . equalsIgnoreCase ( TieConstants . VALIDATION_RULE_TAG ) ) { attr . setValue ( details [ 1 ] . replaceAll ( \"\\\"\" , \"\" ) ) ; } else if ( details [ 0 ] . equalsIgnoreCase ( TieConstants . VALIDATION_ERROR_MSG_TAG ) ) { attr . setMessage ( details [ 1 ] . replaceAll ( \"\\\"\" , \"\" ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "split string by = sign . [CODESPLIT] private static String [ ] splitByEualSign ( final String attrData ) { int attrNameEndIndex = attrData . indexOf ( ' ' ) ; if ( attrNameEndIndex < 0 ) { return new String [ 0 ] ; } String attrName = attrData . substring ( 0 , attrNameEndIndex ) . trim ( ) ; String attrValue = attrData . substring ( attrNameEndIndex + 1 ) . trim ( ) ; String [ ] rlist = new String [ 2 ] ; rlist [ 0 ] = attrName ; rlist [ 1 ] = attrValue ; return rlist ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "parse select item attributes . [CODESPLIT] public static void parseSpecialAttributes ( final String key , final String type , final List < CellFormAttributes > inputs , final CellAttributesMap cellAttributesMap ) { SpecialAttributes sAttr = new SpecialAttributes ( ) ; for ( CellFormAttributes attr : inputs ) { gatherSpecialAttributes ( type , sAttr , attr ) ; } if ( sAttr . selectLabels != null ) { processSelectItemAttributes ( key , cellAttributesMap , sAttr ) ; } if ( type . equalsIgnoreCase ( TieConstants . WIDGET_CALENDAR ) ) { processCalendarAttributes ( key , cellAttributesMap , sAttr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process calendar attributes . [CODESPLIT] private static void processCalendarAttributes ( final String key , final CellAttributesMap cellAttributesMap , final SpecialAttributes sAttr ) { cellAttributesMap . getCellDatePattern ( ) . put ( key , sAttr . defaultDatePattern ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process select item attributes . [CODESPLIT] private static void processSelectItemAttributes ( final String key , final CellAttributesMap cellAttributesMap , final SpecialAttributes sAttr ) { if ( ( sAttr . selectValues == null ) || ( sAttr . selectValues . length != sAttr . selectLabels . length ) ) { sAttr . selectValues = sAttr . selectLabels ; } Map < String , String > smap = cellAttributesMap . getCellSelectItemsAttributes ( ) . get ( key ) ; if ( smap == null ) { smap = new LinkedHashMap <> ( ) ; } smap . clear ( ) ; if ( sAttr . defaultSelectLabel != null ) { smap . put ( sAttr . defaultSelectLabel , sAttr . defaultSelectValue ) ; } for ( int i = 0 ; i < sAttr . selectLabels . length ; i ++ ) { smap . put ( sAttr . selectLabels [ i ] , sAttr . selectValues [ i ] ) ; } cellAttributesMap . getCellSelectItemsAttributes ( ) . put ( key , smap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gather special attributes . [CODESPLIT] private static void gatherSpecialAttributes ( final String type , final SpecialAttributes sAttr , final CellFormAttributes attr ) { String attrKey = attr . getType ( ) ; if ( attrKey . equalsIgnoreCase ( TieConstants . SELECT_ITEM_LABELS ) ) { sAttr . selectLabels = attr . getValue ( ) . split ( \";\" ) ; } if ( attrKey . equalsIgnoreCase ( TieConstants . SELECT_ITEM_VALUES ) ) { sAttr . selectValues = attr . getValue ( ) . split ( \";\" ) ; } if ( attrKey . equalsIgnoreCase ( TieConstants . DEFAULT_SELECT_ITEM_LABEL ) ) { sAttr . defaultSelectLabel = attr . getValue ( ) ; } if ( attrKey . equalsIgnoreCase ( TieConstants . DEFAULT_SELECT_ITEM_VALUE ) ) { sAttr . defaultSelectValue = attr . getValue ( ) ; } if ( type . equalsIgnoreCase ( TieConstants . WIDGET_CALENDAR ) && attrKey . equalsIgnoreCase ( TieConstants . WIDGET_ATTR_PATTERN ) ) { sAttr . defaultDatePattern = attr . getValue ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse Comment To Map [CODESPLIT] public static void parseCommentToMap ( final String cellKey , final String newComment , final Map < String , Map < String , String > > sheetCommentMap , final boolean normalComment ) { if ( ( newComment != null ) && ( ! newComment . trim ( ) . isEmpty ( ) ) ) { // normal comment key is $$\r String commentKey = TieConstants . NORMAL_COMMENT_KEY_IN_MAP ; if ( ! normalComment ) { // not normal comment. e.g. ${... or $init{... or\r // key = $ or key = $init\r commentKey = newComment . substring ( 0 , newComment . indexOf ( TieConstants . EL_START_BRACKET ) ) ; } Map < String , String > map = sheetCommentMap . get ( commentKey ) ; if ( map == null ) { map = new HashMap <> ( ) ; } // inner map's key is sheetName!$columnIndex$rowIndex\r map . put ( cellKey , newComment ) ; sheetCommentMap . put ( commentKey , map ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find first non letterordigit position from string . [CODESPLIT] public static int findFirstNonCellNamePosition ( String input , int startPosition ) { char c ; for ( int i = startPosition ; i < input . length ( ) ; i ++ ) { c = input . charAt ( i ) ; if ( c != ' ' && ! Character . isLetterOrDigit ( c ) ) { return i ; } } return - 1 ; // not found\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the chars from string . [CODESPLIT] public static String removeCharsFromString ( String inputStr , int start , int end ) { StringBuilder sb = new StringBuilder ( inputStr ) ; sb . delete ( start , end ) ; //    \t if ((start > 0) && (inputStr.charAt(start - 1) ==' ')) {\r //    \t\t // if end with a space, then remove it as well.\r //    \t\t sb.deleteCharAt(start - 1);\r //    \t }\r return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the excel column name . [CODESPLIT] public static String getExcelColumnName ( final int pnumber ) { StringBuilder converted = new StringBuilder ( ) ; // Repeatedly divide the number by 26 and convert the\r // remainder into the appropriate letter.\r int number = pnumber ; while ( number >= 0 ) { int remainder = number % TieConstants . EXCEL_LETTER_NUMBERS ; converted . insert ( 0 , ( char ) ( remainder + ' ' ) ) ; number = ( number / TieConstants . EXCEL_LETTER_NUMBERS ) - 1 ; } return converted . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return full name for cell with sheet name and $ format e . g . Sheet1$A$1 [CODESPLIT] public static String getFullCellRefName ( final Sheet sheet1 , final Cell cell ) { if ( ( sheet1 != null ) && ( cell != null ) ) { return sheet1 . getSheetName ( ) + \"!$\" + getExcelColumnName ( cell . getColumnIndex ( ) ) + \"$\" + ( cell . getRowIndex ( ) + 1 ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return full name for cell with sheet name and $ format e . g . Sheet1$A$1 [CODESPLIT] public static String getFullCellRefName ( final String sheetName , final int rowIndex , final int colIndex ) { if ( sheetName != null ) { return sheetName + \"!$\" + getExcelColumnName ( colIndex ) + \"$\" + ( rowIndex + 1 ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return sheet name from cell full name e . g . return Sheet1 from Sheet1$A$1 [CODESPLIT] public static String getSheetNameFromFullCellRefName ( final String fullName ) { if ( ( fullName != null ) && ( fullName . contains ( \"!\" ) ) ) { return fullName . substring ( 0 , fullName . indexOf ( ' ' ) ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove sheet name from cell full name e . g . return $A$1 from Sheet1$A$1 [CODESPLIT] public static String removeSheetNameFromFullCellRefName ( final String fullName ) { if ( ( fullName != null ) && ( fullName . contains ( \"!\" ) ) ) { return fullName . substring ( fullName . indexOf ( ' ' ) + 1 ) ; } return fullName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert col to int . [CODESPLIT] public static int convertColToInt ( final String col ) { String name = col . toUpperCase ( ) ; int number = 0 ; int pow = 1 ; for ( int i = name . length ( ) - 1 ; i >= 0 ; i -- ) { number += ( name . charAt ( i ) - ' ' + 1 ) * pow ; pow *= TieConstants . EXCEL_LETTER_NUMBERS ; } return number - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the cell by reference . [CODESPLIT] public static Cell getCellByReference ( final String cellRef , final Sheet sheet ) { Cell c = null ; try { CellReference ref = new CellReference ( cellRef ) ; Row r = sheet . getRow ( ref . getRow ( ) ) ; if ( r != null ) { c = r . getCell ( ref . getCol ( ) , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; } } catch ( Exception ex ) { // use log.debug because mostly it's expected\r LOG . log ( Level . SEVERE , \"WebForm WebFormHelper getCellByReference cellRef = \" + cellRef + \"; error = \" + ex . getLocalizedMessage ( ) , ex ) ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "pixel units to excel width units ( units of 1 / 256th of a character width ) . [CODESPLIT] public static short pixel2WidthUnits ( final int pxs ) { short widthUnits = ( short ) ( EXCEL_COLUMN_WIDTH_FACTOR * ( pxs / UNIT_OFFSET_LENGTH ) ) ; widthUnits += UNIT_OFFSET_MAP [ pxs % UNIT_OFFSET_LENGTH ] ; return widthUnits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "excel width units ( units of 1 / 256th of a character width ) to pixel units . [CODESPLIT] public static int widthUnits2Pixel ( final int widthUnits ) { int pixels = ( widthUnits / EXCEL_COLUMN_WIDTH_FACTOR ) * UNIT_OFFSET_LENGTH ; int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR ; pixels += Math . round ( offsetWidthUnits / ( ( float ) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH ) ) ; return pixels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Height units 2 pixel . [CODESPLIT] public static int heightUnits2Pixel ( final short heightUnits ) { int pixels = heightUnits / EXCEL_ROW_HEIGHT_FACTOR ; int offsetHeightUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR ; pixels += Math . round ( ( float ) offsetHeightUnits / ( ( float ) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH / 2 ) ) ; pixels += ( Math . floor ( pixels / PIXEL_HEIGHT_ASPC_ADJUST ) + 1 ) * 4 ; return pixels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is date . [CODESPLIT] public static boolean isDate ( final String s ) { Pattern pattern = Pattern . compile ( DATE_REGEX_4_DIGIT_YEAR ) ; String [ ] terms = s . split ( \" \" ) ; Matcher matcher ; for ( String term : terms ) { matcher = pattern . matcher ( term ) ; if ( matcher . matches ( ) ) { return true ; } } pattern = Pattern . compile ( DATE_REGEX_2_DIGIT_YEAR ) ; terms = s . split ( \" \" ) ; for ( String term : terms ) { matcher = pattern . matcher ( term ) ; if ( matcher . matches ( ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the date . [CODESPLIT] public static String parseDate ( final String entry ) { Pattern pattern = Pattern . compile ( DATE_REGEX_4_DIGIT_YEAR ) ; String [ ] terms = entry . split ( \" \" ) ; Matcher matcher ; for ( String term : terms ) { matcher = pattern . matcher ( term ) ; if ( matcher . matches ( ) ) { return matcher . group ( ) ; } } pattern = Pattern . compile ( DATE_REGEX_2_DIGIT_YEAR ) ; terms = entry . split ( \" \" ) ; for ( String term : terms ) { matcher = pattern . matcher ( term ) ; if ( matcher . matches ( ) ) { return matcher . group ( ) ; } } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is numeric . [CODESPLIT] public static boolean isNumeric ( final String str ) { String s = str ; if ( s . startsWith ( \"-\" ) ) { s = s . substring ( 1 ) ; } char c ; int i ; int sLen = s . length ( ) ; ShouldContinueParameter sPara = new ShouldContinueParameter ( false , false , 0 ) ; for ( i = 0 ; i < sLen ; i ++ ) { c = s . charAt ( i ) ; if ( c < ' ' || c > ' ' ) { if ( ! shouldContinue ( c , sPara ) ) { return false ; } } else { if ( sPara . isCommaHit ( ) ) { sPara . setSinceLastComma ( sPara . getSinceLastComma ( ) + 1 ) ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should continue . [CODESPLIT] private static boolean shouldContinue ( final char c , final ShouldContinueParameter para ) { if ( c == ' ' && ! para . isDecimalHit ( ) ) { para . setDecimalHit ( true ) ; if ( para . isCommaHit ( ) && para . getSinceLastComma ( ) != 3 ) { return false ; } return true ; } else if ( c == ' ' && ! para . isDecimalHit ( ) ) { if ( para . isCommaHit ( ) ) { if ( para . getSinceLastComma ( ) != 3 ) { return false ; } para . setSinceLastComma ( 0 ) ; } para . setCommaHit ( true ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the object property . [CODESPLIT] public static void setObjectProperty ( final Object obj , final String propertyName , final String propertyValue , final boolean ignoreNonExisting ) { try { Method method = obj . getClass ( ) . getMethod ( \"set\" + Character . toUpperCase ( propertyName . charAt ( 0 ) ) + propertyName . substring ( 1 ) , new Class [ ] { String . class } ) ; method . invoke ( obj , propertyValue ) ; } catch ( Exception e ) { String msg = \"failed to set property '\" + propertyName + \"' to value '\" + propertyValue + \"' for object \" + obj ; if ( ignoreNonExisting ) { LOG . info ( msg ) ; } else { LOG . warning ( msg ) ; throw new IllegalArgumentException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cell compare to . [CODESPLIT] public static int cellCompareTo ( final Cell thisCell , final Cell otherCell ) { int r = thisCell . getRowIndex ( ) - otherCell . getRowIndex ( ) ; if ( r != 0 ) { return r ; } r = thisCell . getColumnIndex ( ) - otherCell . getColumnIndex ( ) ; if ( r != 0 ) { return r ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inside range . [CODESPLIT] public static boolean insideRange ( final ConfigRange child , final ConfigRange parent ) { return ( ( cellCompareTo ( child . getFirstRowRef ( ) , parent . getFirstRowRef ( ) ) >= 0 ) && ( cellCompareTo ( child . getLastRowPlusRef ( ) , parent . getLastRowPlusRef ( ) ) <= 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the last column of the sheet . [CODESPLIT] public static int getSheetRightCol ( final Sheet sheet ) { try { if ( sheet instanceof XSSFSheet ) { XSSFSheet xsheet = ( XSSFSheet ) sheet ; int rightCol = getSheetRightColFromDimension ( xsheet ) ; if ( rightCol > TieConstants . MAX_COLUMNS_IN_SHEET ) { clearHiddenColumns ( sheet ) ; rightCol = getSheetRightColFromDimension ( xsheet ) ; } return rightCol ; } } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"error in getSheetRightCol : \" + e . getLocalizedMessage ( ) , e ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear hidden columns . [CODESPLIT] public static void clearHiddenColumns ( final Sheet sheet ) { for ( Row row : sheet ) { if ( row . getLastCellNum ( ) > TieConstants . MAX_COLUMNS_IN_SHEET ) { deleteHiddenColumnsInRow ( row ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete hidden columns in row . [CODESPLIT] private static void deleteHiddenColumnsInRow ( final Row row ) { deleteCellFromRow ( row , TieConstants . HIDDEN_SAVE_OBJECTS_COLUMN ) ; deleteCellFromRow ( row , TieConstants . HIDDEN_ORIGIN_ROW_NUMBER_COLUMN ) ; deleteCellFromRow ( row , TieConstants . HIDDEN_FULL_NAME_COLUMN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete cell from row . [CODESPLIT] private static void deleteCellFromRow ( final Row row , final int cellNum ) { Cell cell = row . getCell ( cellNum ) ; if ( cell != null ) { row . removeCell ( cell ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return the last column of the sheet . [CODESPLIT] private static int getSheetRightColFromDimension ( final XSSFSheet xsheet ) { CTSheetDimension dimension = xsheet . getCTWorksheet ( ) . getDimension ( ) ; String sheetDimensions = dimension . getRef ( ) ; if ( sheetDimensions . indexOf ( ' ' ) < 0 ) { return - 1 ; } else { return CellRangeAddress . valueOf ( sheetDimensions ) . getLastColumn ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final String getSeriesLabelFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTAreaSer ) { return ( ( CTAreaSer ) ctObjSer ) . getTx ( ) . getStrRef ( ) . getF ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTShapeProperties getShapePropertiesFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTAreaSer ) { return ( ( CTAreaSer ) ctObjSer ) . getSpPr ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public final CTNumDataSource getCTNumDataSourceFromCTSer ( final Object ctObjSer ) { if ( ctObjSer instanceof CTAreaSer ) { return ( ( CTAreaSer ) ctObjSer ) . getVal ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "process event . [CODESPLIT] @ Override public final void processEvent ( final SystemEvent event ) { LOGGER . log ( Level . INFO , \"Running on TieFaces {0}\" , AppUtils . getBuildVersion ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh after status changed . [CODESPLIT] private void refreshAfterStatusChanged ( final boolean oldStatus , final boolean newStatus , final int formRow , final int formCol , final FacesCell cell , final boolean updateGui ) { if ( ! newStatus ) { cell . setErrormsg ( \"\" ) ; } cell . setInvalid ( newStatus ) ; if ( updateGui && ( oldStatus != newStatus ) && ( parent . getWebFormClientId ( ) != null ) ) { RequestContext . getCurrentInstance ( ) . update ( parent . getWebFormClientId ( ) + \":\" + ( formRow ) + \":group\" + ( formCol ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate with row col in current page . [CODESPLIT] public boolean validateWithRowColInCurrentPage ( final int row , final int col , boolean updateGui ) { //until now passEmptyCheck has one to one relation to submitMode\r //e.g. when passEmptyCheck = false, then submitMode = true.\r boolean submitMode = parent . getSubmitMode ( ) ; boolean passEmptyCheck = ! submitMode ; int topRow = parent . getCurrent ( ) . getCurrentTopRow ( ) ; int leftCol = parent . getCurrent ( ) . getCurrentLeftColumn ( ) ; boolean pass = true ; FacesRow fRow = CellUtility . getFacesRowFromBodyRow ( row , parent . getBodyRows ( ) , topRow ) ; if ( fRow == null ) { return pass ; } FacesCell cell = CellUtility . getFacesCellFromBodyRow ( row , col , parent . getBodyRows ( ) , topRow , leftCol ) ; if ( cell == null ) { return pass ; } Cell poiCell = parent . getCellHelper ( ) . getPoiCellWithRowColFromCurrentPage ( row , col ) ; boolean oldStatus = cell . isInvalid ( ) ; String value = CellUtility . getCellValueWithoutFormat ( poiCell ) ; if ( value == null ) { value = \"\" ; } else { value = value . trim ( ) ; } if ( passEmptyCheck && value . isEmpty ( ) ) { refreshAfterStatusChanged ( oldStatus , false , row - topRow , col - leftCol , cell , updateGui ) ; return pass ; } if ( ( ( parent . isOnlyValidateInSubmitMode ( ) && submitMode ) || ! parent . isOnlyValidateInSubmitMode ( ) ) && ! validateByTieWebSheetValidationBean ( poiCell , topRow , leftCol , cell , value , updateGui ) ) { return false ; } SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( parent . getCurrent ( ) . getCurrentTabName ( ) ) ; List < CellFormAttributes > cellAttributes = CellControlsUtility . findCellValidateAttributes ( parent . getCellAttributesMap ( ) . getCellValidateAttributes ( ) , fRow . getOriginRowIndex ( ) , poiCell ) ; if ( parent . isAdvancedContext ( ) && parent . getConfigAdvancedContext ( ) . getErrorSuffix ( ) != null && ! checkErrorMessageFromObjectInContext ( row - topRow , col - leftCol , cell , poiCell , value , sheetConfig , updateGui ) ) { return false ; } if ( cellAttributes != null ) { pass = validateAllRulesForSingleCell ( row - topRow , col - leftCol , cell , poiCell , value , sheetConfig , cellAttributes , updateGui ) ; } if ( pass ) { refreshAfterStatusChanged ( oldStatus , false , row - topRow , col - leftCol , cell , updateGui ) ; } return pass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate by tie web sheet validation bean . [CODESPLIT] private boolean validateByTieWebSheetValidationBean ( final Cell poiCell , final int topRow , final int leftCol , final FacesCell cell , final String value , boolean updateGui ) { if ( parent . getTieWebSheetValidationBean ( ) != null ) { String errormsg = null ; String fullName = ConfigurationUtility . getFullNameFromRow ( poiCell . getRow ( ) ) ; String saveAttr = SaveAttrsUtility . prepareContextAndAttrsForCell ( poiCell , fullName , parent . getCellHelper ( ) ) ; if ( saveAttr != null ) { int row = poiCell . getRowIndex ( ) ; int col = poiCell . getColumnIndex ( ) ; errormsg = parent . getTieWebSheetValidationBean ( ) . validate ( parent . getSerialDataContext ( ) . getDataContext ( ) , saveAttr , ConfigurationUtility . getFullNameFromRow ( poiCell . getRow ( ) ) , poiCell . getSheet ( ) . getSheetName ( ) , row , col , value ) ; if ( ( errormsg != null ) && ( ! errormsg . isEmpty ( ) ) ) { cell . setErrormsg ( errormsg ) ; refreshAfterStatusChanged ( false , true , row - topRow , col - leftCol , cell , updateGui ) ; return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check error message from object in context . [CODESPLIT] private boolean checkErrorMessageFromObjectInContext ( final int formRow , final int formCol , final FacesCell cell , final Cell poiCell , final String value , final SheetConfiguration sheetConfig , boolean updateGui ) { @ SuppressWarnings ( \"unchecked\" ) HashMap < String , TieCell > tieCells = ( HashMap < String , TieCell > ) parent . getSerialDataContext ( ) . getDataContext ( ) . get ( \"tiecells\" ) ; if ( tieCells != null ) { TieCell tieCell = tieCells . get ( CellUtility . getSkeyFromPoiCell ( poiCell ) ) ; if ( tieCell != null && tieCell . getContextObject ( ) != null ) { String errorMethod = tieCell . getMethodStr ( ) + parent . getConfigAdvancedContext ( ) . getErrorSuffix ( ) ; String errorMessage = CellControlsUtility . getObjectPropertyValue ( tieCell . getContextObject ( ) , errorMethod , true ) ; if ( errorMessage != null && ! errorMessage . isEmpty ( ) ) { cell . setErrormsg ( errorMessage ) ; LOG . log ( Level . INFO , \"Validation failed for sheet {0} row {1} column {2} : {3}\" , new Object [ ] { poiCell . getSheet ( ) . getSheetName ( ) , poiCell . getRowIndex ( ) , poiCell . getColumnIndex ( ) , errorMessage } ) ; refreshAfterStatusChanged ( false , true , formRow , formCol , cell , updateGui ) ; return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate all rules for single cell . [CODESPLIT] private boolean validateAllRulesForSingleCell ( final int formRow , final int formCol , final FacesCell cell , final Cell poiCell , final String value , final SheetConfiguration sheetConfig , final List < CellFormAttributes > cellAttributes , boolean updateGui ) { Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetConfig . getSheetName ( ) ) ; for ( CellFormAttributes attr : cellAttributes ) { boolean pass = doValidation ( value , attr , poiCell . getRowIndex ( ) , poiCell . getColumnIndex ( ) , sheet1 ) ; if ( ! pass ) { String errmsg = attr . getMessage ( ) ; if ( errmsg == null ) { errmsg = TieConstants . DEFALT_MSG_INVALID_INPUT ; } cell . setErrormsg ( errmsg ) ; LOG . log ( Level . INFO , \"Validation failed for sheet {0} row {1} column {2} : {3}\" , new Object [ ] { poiCell . getSheet ( ) . getSheetName ( ) , poiCell . getRowIndex ( ) , poiCell . getColumnIndex ( ) , errmsg } ) ; refreshAfterStatusChanged ( false , true , formRow , formCol , cell , updateGui ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do validation . [CODESPLIT] private boolean doValidation ( final Object value , final CellFormAttributes attr , final int rowIndex , final int colIndex , final Sheet sheet ) { boolean pass ; String attrValue = attr . getValue ( ) ; attrValue = attrValue . replace ( \"$value\" , value . toString ( ) + \"\" ) . replace ( \"$rowIndex\" , rowIndex + \"\" ) . replace ( \"$colIndex\" , colIndex + \"\" ) . replace ( \"$sheetName\" , sheet . getSheetName ( ) ) ; attrValue = ConfigurationUtility . replaceExpressionWithCellValue ( attrValue , rowIndex , sheet ) ; if ( attrValue . contains ( TieConstants . EL_START ) ) { Object returnObj = FacesUtility . evaluateExpression ( attrValue , Object . class ) ; attrValue = returnObj . toString ( ) ; pass = Boolean . parseBoolean ( attrValue ) ; } else { pass = parent . getCellHelper ( ) . evalBoolExpression ( attrValue ) ; } return pass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate cell . [CODESPLIT] public final boolean validateCell ( final UIComponent target ) { int [ ] rowcol = CellUtility . getRowColFromComponentAttributes ( target ) ; int row = rowcol [ 0 ] ; int col = rowcol [ 1 ] ; return validateWithRowColInCurrentPage ( row , col , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate current page . [CODESPLIT] public final boolean validateCurrentPage ( ) { boolean allpass = true ; int top = parent . getCurrent ( ) . getCurrentTopRow ( ) ; for ( int irow = 0 ; irow < parent . getBodyRows ( ) . size ( ) ; irow ++ ) { if ( ! validateRowInCurrentPage ( irow + top , false ) ) { allpass = false ; } } return allpass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate row in current page . [CODESPLIT] public final boolean validateRowInCurrentPage ( final int irow , final boolean updateGui ) { SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( parent . getCurrent ( ) . getCurrentTabName ( ) ) ; return this . validateRow ( irow , sheetConfig , updateGui ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate row . [CODESPLIT] private boolean validateRow ( final int irow , final SheetConfiguration sheetConfig , boolean updateGui ) { boolean pass = true ; if ( sheetConfig == null ) { return pass ; } int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; List < FacesCell > cellRow = parent . getBodyRows ( ) . get ( irow - top ) . getCells ( ) ; for ( int index = 0 ; index < cellRow . size ( ) ; index ++ ) { FacesCell fcell = cellRow . get ( index ) ; if ( ( fcell != null ) && ( ! validateWithRowColInCurrentPage ( irow , fcell . getColumnIndex ( ) , updateGui ) ) ) { pass = false ; } } return pass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggered when value in cells changed . e . g . user edit cell . [CODESPLIT] public void valueChangeEvent ( final AjaxBehaviorEvent event ) { try { FacesContext facesContext = FacesContext . getCurrentInstance ( ) ; String tblName = parent . getWebFormClientId ( ) ; UIComponent target = event . getComponent ( ) ; boolean pass = validateCell ( target ) ; if ( pass ) { // to improve performance, re-validate current row only\r // page validation take times. will happen when change tab(page)\r // or\r // reload page.\r int [ ] rowcol = CellUtility . getRowColFromComponentAttributes ( target ) ; validateRowInCurrentPage ( rowcol [ 0 ] , true ) ; refreshCachedCellsInCurrentPage ( facesContext , tblName ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"Validation error:\" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh cached cells in current page . [CODESPLIT] private void refreshCachedCellsInCurrentPage ( final FacesContext facesContext , final String tblName ) { // refresh current page calculation fields\r UIComponent s = facesContext . getViewRoot ( ) . findComponent ( tblName ) ; if ( s == null ) { return ; } DataTable webDataTable = ( DataTable ) s ; int first = webDataTable . getFirst ( ) ; int rowsToRender = webDataTable . getRowsToRender ( ) ; int rowCounts = webDataTable . getRowCount ( ) ; int top = parent . getCurrent ( ) . getCurrentTopRow ( ) ; int left = parent . getCurrent ( ) . getCurrentLeftColumn ( ) ; for ( int i = first ; i <= ( first + rowsToRender ) ; i ++ ) { if ( i < rowCounts ) { refreshCachedCellsInRow ( tblName , top , left , i ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh cached cells in row . [CODESPLIT] private void refreshCachedCellsInRow ( final String tblName , final int top , final int left , final int i ) { FacesRow dataRow = parent . getBodyRows ( ) . get ( i ) ; int isize = dataRow . getCells ( ) . size ( ) ; for ( int index = 0 ; index < isize ; index ++ ) { FacesCell fcell = dataRow . getCells ( ) . get ( index ) ; Cell poiCell = parent . getCellHelper ( ) . getPoiCellWithRowColFromCurrentPage ( i + top , index + left ) ; if ( poiCell != null ) { parent . getHelper ( ) . getWebSheetLoader ( ) . refreshCachedCell ( tblName , i , index , poiCell , fcell ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set submit mode flag with javascript for holding in client side . [CODESPLIT] public void setSubmitModeInView ( final Boolean fullflag ) { if ( FacesContext . getCurrentInstance ( ) != null ) { Map < String , Object > viewMap = FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . getViewMap ( ) ; if ( viewMap != null ) { Boolean flag = ( Boolean ) viewMap . get ( TieConstants . SUBMITMODE ) ; if ( ( flag == null ) || ( ! flag . equals ( fullflag ) ) ) { viewMap . put ( TieConstants . SUBMITMODE , fullflag ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "triggered validation process before actions like save or submit . [CODESPLIT] public boolean preValidation ( ) { String currentTabName = parent . getCurrent ( ) . getCurrentTabName ( ) ; String tabName = null ; String firstInvalidTabName = null ; boolean reload = false ; for ( Map . Entry < String , SheetConfiguration > entry : parent . getSheetConfigMap ( ) . entrySet ( ) ) { tabName = entry . getKey ( ) ; // if not reload and tabname==current then skip reloading.\r if ( reload || ( ! tabName . equals ( currentTabName ) ) ) { parent . getWebSheetLoader ( ) . prepareWorkShee ( tabName ) ; reload = true ; } if ( ! parent . getValidationHandler ( ) . validateCurrentPage ( ) && ( firstInvalidTabName == null ) ) { firstInvalidTabName = tabName ; } } if ( firstInvalidTabName != null ) { if ( ! tabName . equals ( firstInvalidTabName ) ) { parent . getHelper ( ) . getWebSheetLoader ( ) . loadWorkSheet ( firstInvalidTabName ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "clear all the related maps . [CODESPLIT] public final void clear ( ) { if ( this . templateCommentMap != null ) { this . templateCommentMap . clear ( ) ; } if ( this . cellDatePattern != null ) { this . cellDatePattern . clear ( ) ; } if ( this . cellInputAttributes != null ) { this . cellInputAttributes . clear ( ) ; } if ( this . cellInputType != null ) { this . cellInputType . clear ( ) ; } if ( this . cellSelectItemsAttributes != null ) { this . cellSelectItemsAttributes . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load header rows . [CODESPLIT] private void loadHeaderRows ( final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { int top = sheetConfig . getHeaderCellRange ( ) . getTopRow ( ) ; int bottom = sheetConfig . getHeaderCellRange ( ) . getBottomRow ( ) ; int left = sheetConfig . getHeaderCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getHeaderCellRange ( ) . getRightCol ( ) ; String sheetName = sheetConfig . getSheetName ( ) ; Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetName ) ; int totalWidth = CellStyleUtility . calcTotalWidth ( sheet1 , left , right , WebSheetUtility . pixel2WidthUnits ( parent . getLineNumberColumnWidth ( ) + parent . getAddRowColumnWidth ( ) ) ) ; RangeBuildRef rangeBuildRef = new RangeBuildRef ( left , right , totalWidth , sheet1 ) ; if ( sheetConfig . isFixedWidthStyle ( ) ) { parent . setTableWidthStyle ( \"table-layout: fixed; width:\" + WebSheetUtility . widthUnits2Pixel ( totalWidth ) + \"px;\" ) ; } parent . setLineNumberColumnWidthStyle ( getWidthStyle ( WebSheetUtility . pixel2WidthUnits ( parent . getLineNumberColumnWidth ( ) ) , totalWidth ) ) ; parent . setAddRowColumnWidthStyle ( \"width:\" + parent . getAddRowColumnWidth ( ) + \"px;\" ) ; parent . getHeaderRows ( ) . clear ( ) ; if ( top < 0 ) { // this is blank configuration. set column letter as header\r parent . getHeaderRows ( ) . add ( loadHeaderRowWithoutConfigurationTab ( rangeBuildRef , true ) ) ; // set showlinenumber to true as default\r parent . setShowLineNumber ( true ) ; } else { parent . getHeaderRows ( ) . add ( loadHeaderRowWithoutConfigurationTab ( rangeBuildRef , false ) ) ; for ( int i = top ; i <= bottom ; i ++ ) { parent . getHeaderRows ( ) . add ( loadHeaderRowWithConfigurationTab ( sheetConfig , rangeBuildRef , i , cellRangeMap , skippedRegionCells ) ) ; } // set showlinenumber to false as default\r parent . setShowLineNumber ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load header row without configuration tab . [CODESPLIT] private List < HeaderCell > loadHeaderRowWithoutConfigurationTab ( final RangeBuildRef rangeBuildRef , final boolean rendered ) { int firstCol = rangeBuildRef . getLeft ( ) ; int lastCol = rangeBuildRef . getRight ( ) ; double totalWidth = ( double ) rangeBuildRef . getTotalWidth ( ) ; Sheet sheet1 = rangeBuildRef . getSheet ( ) ; List < HeaderCell > headercells = new ArrayList <> ( ) ; for ( int i = firstCol ; i <= lastCol ; i ++ ) { if ( ! sheet1 . isColumnHidden ( i ) ) { String style = getHeaderColumnStyle ( parent . getWb ( ) , null , sheet1 . getColumnWidth ( i ) , totalWidth ) ; headercells . add ( new HeaderCell ( \"1\" , \"1\" , style , style , WebSheetUtility . getExcelColumnName ( i ) , rendered , true ) ) ; } } fillToMaxColumns ( headercells ) ; return headercells ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fill to max columns . [CODESPLIT] private void fillToMaxColumns ( final List < HeaderCell > headercells ) { if ( headercells . size ( ) < parent . getMaxColCounts ( ) ) { int fills = parent . getMaxColCounts ( ) - headercells . size ( ) ; for ( int s = 0 ; s < fills ; s ++ ) { headercells . add ( new HeaderCell ( \"1\" , \"1\" , \"\" , \"\" , \"\" , false , false ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the header column style . [CODESPLIT] private String getHeaderColumnStyle ( final Workbook wb , final Cell cell , final double colWidth , final double totalWidth ) { String columnstyle = \"\" ; if ( cell != null ) { columnstyle += CellStyleUtility . getCellStyle ( wb , cell , \"\" ) + CellStyleUtility . getCellFontStyle ( wb , cell ) ; // +\r } columnstyle = columnstyle + getWidthStyle ( colWidth , totalWidth ) ; return columnstyle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the width style . [CODESPLIT] private String getWidthStyle ( final double colWidth , final double totalWidth ) { double percentage = FacesUtility . round ( TieConstants . CELL_FORMAT_PERCENTAGE_VALUE * colWidth / totalWidth , 2 ) ; return \"width:\" + percentage + TieConstants . CELL_FORMAT_PERCENTAGE_SYMBOL + \";\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load header row with configuration tab . [CODESPLIT] private List < HeaderCell > loadHeaderRowWithConfigurationTab ( final SheetConfiguration sheetConfig , final RangeBuildRef rangeBuildRef , final int currentRow , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { Sheet sheet1 = rangeBuildRef . getSheet ( ) ; int left = rangeBuildRef . getLeft ( ) ; int right = rangeBuildRef . getRight ( ) ; double totalWidth = ( double ) rangeBuildRef . getTotalWidth ( ) ; Row row = sheet1 . getRow ( currentRow ) ; List < HeaderCell > headercells = new ArrayList <> ( ) ; for ( int cindex = left ; cindex <= right ; cindex ++ ) { String cellindex = CellUtility . getCellIndexNumberKey ( cindex , currentRow ) ; if ( ! skippedRegionCells . contains ( cellindex ) && ! sheet1 . isColumnHidden ( cindex ) ) { Cell cell = null ; if ( row != null ) { cell = row . getCell ( cindex , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; } int originRowIndex = ConfigurationUtility . getOriginalRowNumInHiddenColumn ( row ) ; if ( cell != null ) { FacesCell fcell = new FacesCell ( ) ; CellUtility . convertCell ( sheetConfig , fcell , cell , cellRangeMap , originRowIndex , parent . getCellAttributesMap ( ) , null ) ; parent . getPicHelper ( ) . setupFacesCellPictureCharts ( sheet1 , fcell , cell , WebSheetUtility . getFullCellRefName ( sheet1 , cell ) ) ; CellStyleUtility . setupCellStyle ( parent . getWb ( ) , fcell , cell , row . getHeightInPoints ( ) ) ; fcell . setColumnStyle ( fcell . getColumnStyle ( ) + getColumnWidthStyle ( sheet1 , cellRangeMap , cellindex , cindex , totalWidth ) ) ; fcell . setColumnIndex ( cindex ) ; headercells . add ( new HeaderCell ( Integer . toString ( fcell . getRowspan ( ) ) , Integer . toString ( fcell . getColspan ( ) ) , fcell . getStyle ( ) , fcell . getColumnStyle ( ) , CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) , true , true ) ) ; } } } fillToMaxColumns ( headercells ) ; return headercells ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the column width style . [CODESPLIT] private String getColumnWidthStyle ( final Sheet sheet1 , final Map < String , CellRangeAddress > cellRangeMap , final String cellindex , final int cindex , final double totalWidth ) { CellRangeAddress caddress = cellRangeMap . get ( cellindex ) ; double colWidth ; // check whether the cell has rowspan or colspan\r if ( caddress != null ) { colWidth = CellStyleUtility . calcTotalWidth ( sheet1 , caddress . getFirstColumn ( ) , caddress . getLastColumn ( ) , 0 ) ; } else { colWidth = sheet1 . getColumnWidth ( cindex ) ; } return getWidthStyle ( colWidth , totalWidth ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear workbook . [CODESPLIT] private void clearWorkbook ( ) { parent . setFormulaEvaluator ( null ) ; parent . setDataFormatter ( null ) ; parent . setSheetConfigMap ( null ) ; parent . setTabs ( null ) ; parent . getSerialDataContext ( ) . setDataContext ( null ) ; parent . setPicturesMap ( null ) ; parent . setHeaderRows ( null ) ; parent . setBodyRows ( null ) ; parent . setWb ( null ) ; parent . getHeaderRows ( ) . clear ( ) ; parent . getBodyRows ( ) . clear ( ) ; parent . getCharsData ( ) . getChartsMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartDataMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartAnchorsMap ( ) . clear ( ) ; parent . getCharsData ( ) . getChartPositionMap ( ) . clear ( ) ; parent . getCellAttributesMap ( ) . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load workbook . [CODESPLIT] public final int loadWorkbook ( final InputStream fis , final Map < String , Object > dataContext ) { try { Workbook wb = WorkbookFactory . create ( fis ) ; int ireturn = loadWorkbook ( wb , dataContext ) ; fis . close ( ) ; return ireturn ; } catch ( Exception e ) { LOG . log ( Level . SEVERE , \"Web Form loadWorkbook Error Exception = \" + e . getLocalizedMessage ( ) , e ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load workbook . [CODESPLIT] public final int loadWorkbook ( final Workbook wb , final Map < String , Object > dataContext ) { try { clearWorkbook ( ) ; // only support xssf workbook now since 2016 July\r if ( ! ( wb instanceof XSSFWorkbook ) ) { LOG . fine ( \"Error: WebSheet only support xlsx template.\" ) ; return - 1 ; } LOG . fine ( \"Begin load work book...\" ) ; parent . setWb ( wb ) ; parent . getSerialDataContext ( ) . setDataContext ( dataContext ) ; parent . setSheetConfigMap ( new ConfigurationHandler ( parent ) . buildConfiguration ( ) ) ; parent . reCalcMaxColCounts ( ) ; parent . getChartHelper ( ) . loadChartsMap ( ) ; parent . getPicHelper ( ) . loadPicturesMap ( ) ; initSheet ( ) ; initTabs ( ) ; if ( ! parent . getTabs ( ) . isEmpty ( ) ) { loadWorkSheet ( parent . getTabs ( ) . get ( 0 ) . getTitle ( ) ) ; } } catch ( Exception e ) { LOG . log ( Level . FINE , \"Web Form loadWorkbook Error Exception = \" + e . getLocalizedMessage ( ) , e ) ; return - 1 ; } return 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inits the tabs . [CODESPLIT] private void initTabs ( ) { parent . setTabs ( new ArrayList < TabModel > ( ) ) ; if ( parent . getSheetConfigMap ( ) != null ) { for ( String key : parent . getSheetConfigMap ( ) . keySet ( ) ) { parent . getTabs ( ) . add ( new TabModel ( \"form_\" + key , key , \"form\" ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "load data process . unfinished . [CODESPLIT] private void loadData ( ) { if ( parent . getSerialDataContext ( ) . getDataContext ( ) == null ) { // no data objects available.\r return ; } if ( parent . isAdvancedContext ( ) ) { parent . getSerialDataContext ( ) . getDataContext ( ) . put ( \"tiecells\" , new HashMap < String , TieCell > ( ) ) ; } for ( SheetConfiguration sheetConfig : parent . getSheetConfigMap ( ) . values ( ) ) { List < RowsMapping > currentRowsMappingList = null ; ConfigBuildRef configBuildRef = new ConfigBuildRef ( parent . getWbWrapper ( ) , parent . getWb ( ) . getSheet ( sheetConfig . getSheetName ( ) ) , parent . getExpEngine ( ) , parent . getCellHelper ( ) , sheetConfig . getCachedCells ( ) , parent . getCellAttributesMap ( ) , sheetConfig . getFinalCommentMap ( ) ) ; int length = sheetConfig . getFormCommand ( ) . buildAt ( null , configBuildRef , sheetConfig . getFormCommand ( ) . getTopRow ( ) , parent . getSerialDataContext ( ) . getDataContext ( ) , currentRowsMappingList ) ; sheetConfig . setShiftMap ( configBuildRef . getShiftMap ( ) ) ; sheetConfig . setCollectionObjNameMap ( configBuildRef . getCollectionObjNameMap ( ) ) ; sheetConfig . setCommandIndexMap ( configBuildRef . getCommandIndexMap ( ) ) ; sheetConfig . setWatchList ( configBuildRef . getWatchList ( ) ) ; sheetConfig . setBodyAllowAddRows ( configBuildRef . isBodyAllowAdd ( ) ) ; sheetConfig . getBodyCellRange ( ) . setBottomRow ( sheetConfig . getFormCommand ( ) . getTopRow ( ) + length - 1 ) ; sheetConfig . setBodyPopulated ( true ) ; } parent . getCellHelper ( ) . reCalc ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh data . [CODESPLIT] public void refreshData ( ) { if ( parent . getSerialDataContext ( ) . getDataContext ( ) == null ) { // no data objects available.\r return ; } for ( SheetConfiguration sheetConfig : parent . getSheetConfigMap ( ) . values ( ) ) { for ( int irow = sheetConfig . getFormCommand ( ) . getTopRow ( ) ; irow < sheetConfig . getFormCommand ( ) . getLastRow ( ) ; irow ++ ) { refreshDataForRow ( parent . getWb ( ) . getSheet ( sheetConfig . getSheetName ( ) ) . getRow ( irow ) ) ; } } parent . getCellHelper ( ) . reCalc ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh data for row . [CODESPLIT] private void refreshDataForRow ( Row row ) { if ( row == null ) { return ; } String saveAttrList = SaveAttrsUtility . getSaveAttrListFromRow ( row ) ; if ( saveAttrList != null ) { String [ ] saveAttrs = saveAttrList . split ( \",\" ) ; for ( String fullSaveAttr : saveAttrs ) { refreshDataForCell ( row , fullSaveAttr ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "refresh data for single cell . [CODESPLIT] private void refreshDataForCell ( Row row , String fullSaveAttr ) { if ( fullSaveAttr != null ) { try { String fullName = ConfigurationUtility . getFullNameFromRow ( row ) ; if ( fullName != null ) { parent . getCellHelper ( ) . restoreDataContext ( fullName ) ; SaveAttrsUtility . refreshSheetRowFromContext ( parent . getSerialDataContext ( ) . getDataContext ( ) , fullSaveAttr , row , parent . getExpEngine ( ) ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"refreshDataForCell with fullAaveAttr =\" + fullSaveAttr + \" error = \" + ex . getMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find tab index with name . [CODESPLIT] public final int findTabIndexWithName ( final String tabname ) { for ( int i = 0 ; i < parent . getTabs ( ) . size ( ) ; i ++ ) { if ( parent . getTabs ( ) . get ( i ) . getTitle ( ) . equalsIgnoreCase ( tabname ) ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load work sheet . [CODESPLIT] public final void loadWorkSheet ( final String tabName ) { prepareWorkShee ( tabName ) ; parent . getValidationHandler ( ) . validateCurrentPage ( ) ; createDynamicColumns ( tabName ) ; // reset datatable current page to 1\r setDataTablePage ( 0 ) ; parent . getCurrent ( ) . setCurrentDataContextName ( null ) ; saveObjs ( ) ; if ( ( RequestContext . getCurrentInstance ( ) != null ) && ( parent . getClientId ( ) != null ) ) { RequestContext . getCurrentInstance ( ) . update ( parent . getClientId ( ) + \":websheettab\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "prepare worksheet for loading . this only load at backend without refresh gui . [CODESPLIT] public final void prepareWorkShee ( final String tabName ) { int tabIndex = findTabIndexWithName ( tabName ) ; if ( parent . getWebFormTabView ( ) != null ) { parent . getWebFormTabView ( ) . setActiveIndex ( tabIndex ) ; } parent . getCurrent ( ) . setCurrentTabName ( tabName ) ; String sheetName = parent . getSheetConfigMap ( ) . get ( tabName ) . getSheetName ( ) ; Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetName ) ; parent . getWb ( ) . setActiveSheet ( parent . getWb ( ) . getSheetIndex ( sheet1 ) ) ; SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( tabName ) ; parent . setMaxRowsPerPage ( parent . getSheetConfigMap ( ) . get ( tabName ) . getMaxRowPerPage ( ) ) ; parent . setBodyAllowAddRows ( parent . getSheetConfigMap ( ) . get ( tabName ) . isBodyAllowAddRows ( ) ) ; // populate repeat rows before setup cell range map\r Map < String , CellRangeAddress > cellRangeMap = ConfigurationUtility . indexMergedRegion ( sheet1 ) ; List < String > skippedRegionCells = ConfigurationUtility . skippedRegionCells ( sheet1 ) ; loadHeaderRows ( sheetConfig , cellRangeMap , skippedRegionCells ) ; loadBodyRows ( sheetConfig , cellRangeMap , skippedRegionCells ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the data table page . [CODESPLIT] private void setDataTablePage ( final int first ) { if ( parent . getWebFormClientId ( ) != null ) { final DataTable d = ( DataTable ) FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . findComponent ( parent . getWebFormClientId ( ) ) ; if ( d != null ) { d . setFirst ( first ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save objs . [CODESPLIT] private void saveObjs ( ) { try { if ( FacesContext . getCurrentInstance ( ) != null ) { Map < String , Object > viewMap = FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . getViewMap ( ) ; viewMap . put ( \"currentTabName\" , parent . getCurrent ( ) . getCurrentTabName ( ) ) ; viewMap . put ( TieConstants . SUBMITMODE , parent . getSubmitMode ( ) ) ; } } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"saveobjs in viewMap error = \" + ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup row info . [CODESPLIT] private void setupRowInfo ( final FacesRow facesRow , final Sheet sheet1 , final Row row , final int rowIndex , final boolean allowAdd ) { facesRow . setAllowAdd ( allowAdd ) ; if ( row != null ) { facesRow . setRendered ( ! row . getZeroHeight ( ) ) ; facesRow . setRowheight ( row . getHeight ( ) ) ; int rowNum = ConfigurationUtility . getOriginalRowNumInHiddenColumn ( row ) ; facesRow . setOriginRowIndex ( rowNum ) ; } else { facesRow . setRendered ( true ) ; facesRow . setRowheight ( sheet1 . getDefaultRowHeight ( ) ) ; facesRow . setOriginRowIndex ( rowIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load body rows . [CODESPLIT] private void loadBodyRows ( final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int bottom = CellUtility . getBodyBottomFromConfig ( sheetConfig ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; String sheetName = sheetConfig . getSheetName ( ) ; Sheet sheet1 = parent . getWb ( ) . getSheet ( sheetName ) ; parent . getBodyRows ( ) . clear ( ) ; clearCache ( ) ; for ( int i = top ; i <= bottom ; i ++ ) { parent . getBodyRows ( ) . add ( assembleFacesBodyRow ( i , sheet1 , left , right , sheetConfig , cellRangeMap , skippedRegionCells ) ) ; } sheetConfig . setBodyPopulated ( true ) ; parent . getCurrent ( ) . setCurrentTopRow ( top ) ; parent . getCurrent ( ) . setCurrentLeftColumn ( left ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assemble faces body row . [CODESPLIT] private FacesRow assembleFacesBodyRow ( final int rowIndex , final Sheet sheet1 , final int left , final int right , final SheetConfiguration sheetConfig , final Map < String , CellRangeAddress > cellRangeMap , final List < String > skippedRegionCells ) { FacesRow facesRow = new FacesRow ( rowIndex ) ; Row row = sheet1 . getRow ( rowIndex ) ; setupRowInfo ( facesRow , sheet1 , row , rowIndex , CommandUtility . isRowAllowAdd ( row , sheetConfig ) ) ; String saveAttrList = SaveAttrsUtility . getSaveAttrListFromRow ( row ) ; List < FacesCell > bodycells = new ArrayList <> ( ) ; for ( int cindex = left ; cindex <= right ; cindex ++ ) { String cellindex = CellUtility . getCellIndexNumberKey ( cindex , rowIndex ) ; if ( ! skippedRegionCells . contains ( cellindex ) && ! sheet1 . isColumnHidden ( cindex ) ) { Cell cell = null ; if ( row != null ) { cell = row . getCell ( cindex , MissingCellPolicy . CREATE_NULL_AS_BLANK ) ; } if ( cell != null ) { FacesCell fcell = new FacesCell ( ) ; CellUtility . convertCell ( sheetConfig , fcell , cell , cellRangeMap , facesRow . getOriginRowIndex ( ) , parent . getCellAttributesMap ( ) , saveAttrList ) ; parent . getPicHelper ( ) . setupFacesCellPictureCharts ( sheet1 , fcell , cell , WebSheetUtility . getFullCellRefName ( sheet1 , cell ) ) ; CellStyleUtility . setupCellStyle ( parent . getWb ( ) , fcell , cell , row . getHeightInPoints ( ) ) ; fcell . setColumnIndex ( cindex ) ; bodycells . add ( fcell ) ; addCache ( cell ) ; } else { bodycells . add ( null ) ; } } else { bodycells . add ( null ) ; } } facesRow . setCells ( bodycells ) ; return facesRow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh cached cell . [CODESPLIT] public final void refreshCachedCell ( final String tblName , final int i , final int index , final Cell cell , final FacesCell fcell ) { if ( ( cell != null ) && ( cell . getCellTypeEnum ( ) == CellType . FORMULA ) && ( tblName != null ) ) { try { processRefreshCell ( tblName , i , index , cell , fcell ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"refresh Cached Cell error : \" + ex . getLocalizedMessage ( ) , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process refresh cell . [CODESPLIT] private void processRefreshCell ( final String tblName , final int i , final int index , final Cell cell , final FacesCell fcell ) { String newValue = CellUtility . getCellValueWithFormat ( cell , parent . getFormulaEvaluator ( ) , parent . getDataFormatter ( ) ) ; if ( parent . getCachedCells ( ) . isValueChanged ( cell , newValue ) ) { if ( fcell . isHasSaveAttr ( ) ) { parent . getCellHelper ( ) . saveDataInContext ( cell , newValue ) ; } RequestContext . getCurrentInstance ( ) . update ( tblName + \":\" + i + \":cocalc\" + index ) ; parent . getCachedCells ( ) . put ( cell , CellType . FORMULA ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the dynamic columns . [CODESPLIT] private void createDynamicColumns ( final String tabName ) { SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( tabName ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; parent . getColumns ( ) . clear ( ) ; for ( int i = left ; i <= right ; i ++ ) { parent . getColumns ( ) . add ( \"column\" + ( i - left ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the repeat row . [CODESPLIT] public final void addRepeatRow ( final int rowIndex ) { try { SheetConfiguration sheetConfig = parent . getSheetConfigMap ( ) . get ( parent . getCurrent ( ) . getCurrentTabName ( ) ) ; Sheet sheet = parent . getWb ( ) . getSheet ( sheetConfig . getSheetName ( ) ) ; ConfigBuildRef configBuildRef = new ConfigBuildRef ( parent . getWbWrapper ( ) , sheet , parent . getExpEngine ( ) , parent . getCellHelper ( ) , sheetConfig . getCachedCells ( ) , parent . getCellAttributesMap ( ) , sheetConfig . getFinalCommentMap ( ) ) ; // set add mode\r configBuildRef . setAddMode ( true ) ; configBuildRef . setCollectionObjNameMap ( sheetConfig . getCollectionObjNameMap ( ) ) ; configBuildRef . setCommandIndexMap ( sheetConfig . getCommandIndexMap ( ) ) ; configBuildRef . setShiftMap ( sheetConfig . getShiftMap ( ) ) ; configBuildRef . setWatchList ( sheetConfig . getWatchList ( ) ) ; int length = CommandUtility . addRow ( configBuildRef , rowIndex , parent . getSerialDataContext ( ) . getDataContext ( ) ) ; refreshBodyRowsInRange ( configBuildRef . getInsertPosition ( ) , length , sheet , sheetConfig ) ; parent . getCellHelper ( ) . reCalc ( ) ; } catch ( AddRowException e ) { FacesContext . getCurrentInstance ( ) . addMessage ( null , new FacesMessage ( FacesMessage . SEVERITY_ERROR , \"Add Row Error\" , e . getMessage ( ) ) ) ; LOG . log ( Level . SEVERE , \"Add row error = \" + e . getLocalizedMessage ( ) , e ) ; } catch ( Exception ex ) { LOG . log ( Level . SEVERE , \"Add row error = \" + ex . getLocalizedMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh body rows in range . [CODESPLIT] private void refreshBodyRowsInRange ( final int insertPosition , final int length , final Sheet sheet , final SheetConfiguration sheetConfig ) { Map < String , CellRangeAddress > cellRangeMap = ConfigurationUtility . indexMergedRegion ( sheet ) ; List < String > skippedRegionCells = ConfigurationUtility . skippedRegionCells ( sheet ) ; int top = sheetConfig . getBodyCellRange ( ) . getTopRow ( ) ; int left = sheetConfig . getBodyCellRange ( ) . getLeftCol ( ) ; int right = sheetConfig . getBodyCellRange ( ) . getRightCol ( ) ; for ( int irow = insertPosition ; irow < ( insertPosition + length ) ; irow ++ ) { parent . getBodyRows ( ) . add ( irow - top , assembleFacesBodyRow ( irow , sheet , left , right , sheetConfig , cellRangeMap , skippedRegionCells ) ) ; } for ( int irow = insertPosition + length - top ; irow < parent . getBodyRows ( ) . size ( ) ; irow ++ ) { FacesRow facesrow = parent . getBodyRows ( ) . get ( irow ) ; facesrow . setRowIndex ( facesrow . getRowIndex ( ) + length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the unsaved status . [CODESPLIT] public void setUnsavedStatus ( final RequestContext requestContext , final Boolean statusFlag ) { // in client js should have setUnsavedState method\r if ( requestContext != null ) { LOG . log ( Level . FINE , \"run setUnsavedState( {} )\" , statusFlag . toString ( ) ) ; requestContext . execute ( \"setUnsavedState(\" + statusFlag . toString ( ) + \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if is unsaved status . [CODESPLIT] public final Boolean isUnsavedStatus ( ) { Map < String , Object > viewMap = FacesContext . getCurrentInstance ( ) . getViewRoot ( ) . getViewMap ( ) ; Boolean flag = ( Boolean ) viewMap . get ( TieConstants . UNSAVEDSTATE ) ; if ( flag == null ) { return false ; } return flag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "recover by using it s address . [CODESPLIT] public final void recover ( final Sheet sheet ) { this . getSerialFirstRowRef ( ) . recover ( sheet ) ; this . getSerialLastRowPlusRef ( ) . recover ( sheet ) ; if ( this . getUnitRowsMapping ( ) != null ) { this . getUnitRowsMapping ( ) . recover ( sheet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Converts a CEF formatted String into a { [CODESPLIT] public CommonEvent parse ( String cefString , final boolean validate ) { return this . parse ( cefString , validate , Locale . ENGLISH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a CEF formatted String into a { [CODESPLIT] public CommonEvent parse ( String cefString , final boolean validate , Locale locale ) { int cefHeaderSize = 7 ; CommonEvent cefEvent = new CefRev23 ( locale ) ; // Note how split number of splits is cefHeaderSize + 1. This is because the final split // should be the body of the CEF message // Compiled pattern is equivalent to \"(?<!\\\\\\\\)\" + Pattern.quote(\"|\") final String [ ] extractedMessage = cefString . split ( \"(?<!\\\\\\\\)\" + Pattern . quote ( \"|\" ) , cefHeaderSize + 1 ) ; // CEF header misses values if ( extractedMessage . length < cefHeaderSize ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"CEF message failed validation\" ) ; } return null ; } final HashMap < String , Object > headers = new HashMap < String , Object > ( ) ; headers . put ( \"version\" , Integer . valueOf ( extractedMessage [ 0 ] . substring ( extractedMessage [ 0 ] . length ( ) - 1 ) ) ) ; headers . put ( \"deviceVendor\" , extractedMessage [ 1 ] ) ; headers . put ( \"deviceProduct\" , extractedMessage [ 2 ] ) ; headers . put ( \"deviceVersion\" , extractedMessage [ 3 ] ) ; headers . put ( \"deviceEventClassId\" , extractedMessage [ 4 ] ) ; headers . put ( \"name\" , extractedMessage [ 5 ] ) ; headers . put ( \"severity\" , extractedMessage [ 6 ] ) ; final HashMap < String , String > extensions = new HashMap < String , String > ( ) ; final String ext = extractedMessage [ 7 ] ; // Compiled pattern is equivalent to String extensionRegex = \"(?<!\\\\\\\\)\" + Pattern.quote(\"=\"); final Matcher matcher = extensionPattern . matcher ( ext ) ; final Matcher valueMatcher = extensionPattern . matcher ( ext ) ; int index = 0 ; while ( matcher . find ( ) ) { String key = ext . substring ( index , matcher . end ( ) - 1 ) . replace ( \" \" , \"\" ) ; // Capture the start of the value (first char after delimiter match); int valueStart = matcher . end ( ) ; // Handle all but last extension if ( valueMatcher . find ( valueStart ) ) { // FInd the next match to determine the maximum length of the value int nextMatch = valueMatcher . start ( ) ; // Find the last space prior to next match (i.e. last char before next key) int lastSpace = ext . lastIndexOf ( \" \" , nextMatch ) ; // Copy the value between the value start (i.e. this match) // and the lastSpace (i.e. last char prior to next key) String value = ext . substring ( valueStart , lastSpace ) ; // Put to map. extensions . put ( key , value ) ; // Update index to the last character before the next key index = lastSpace + 1 ; // Treat the last KV (if match is true) } else if ( valueMatcher . find ( valueStart - 1 ) ) { // We are handling the final character, value end if newline at the // end of string int valueEnd = ext . length ( ) ; String value = ext . substring ( valueStart , valueEnd ) ; extensions . put ( key , value ) ; // Update the index to the end of the string so no matches are possible index = valueEnd ; } } try { cefEvent . setHeader ( headers ) ; cefEvent . setExtension ( extensions ) ; } catch ( CEFHandlingException e ) { logger . error ( e . toString ( ) ) ; return null ; } if ( validate ) { if ( validator == null ) { // Since the validator wasn't initiated previously, create a new one; this . validator = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ; ; } Set < ConstraintViolation < CommonEvent > > validationResult = validator . validate ( cefEvent ) ; if ( validationResult . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( \"CEF message failed validation\" ) ; } return null ; } else { return cefEvent ; } } else { return cefEvent ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "By convention { [CODESPLIT] @ Override public Scope supply ( Dependency < ? super Scope > dep , Injector injector ) throws UnresolvableDependency { String disk = dep . instance . name . toString ( ) ; File dir = new File ( disk . substring ( 5 ) ) ; return new DiskScope ( injector . resolve ( Config . class ) , dir , DependencyScope :: instanceName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this resource provide the instance wanted by the given { [CODESPLIT] public boolean isNameCompatibleWith ( Dependency < ? super T > dependency ) { return instance . name . isCompatibleWith ( dependency . instance . name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes those bindings that are ambiguous but also do not clash because of different { [CODESPLIT] public static Binding < ? > [ ] disambiguate ( Binding < ? > [ ] bindings ) { if ( bindings . length <= 1 ) { return bindings ; } List < Binding < ? > > uniques = new ArrayList <> ( bindings . length ) ; Arrays . sort ( bindings ) ; uniques . add ( bindings [ 0 ] ) ; int lastUniqueIndex = 0 ; Set < Type < ? > > required = new HashSet <> ( ) ; List < Binding < ? > > dropped = new ArrayList <> ( ) ; for ( int i = 1 ; i < bindings . length ; i ++ ) { Binding < ? > b_d = bindings [ lastUniqueIndex ] ; Binding < ? > b_i = bindings [ i ] ; final boolean equalResource = b_d . resource . equalTo ( b_i . resource ) ; DeclarationType t_d = b_d . source . declarationType ; DeclarationType t_i = b_i . source . declarationType ; if ( equalResource && t_d . clashesWith ( t_i ) ) { throw new InconsistentBinding ( \"Duplicate binds:\\n\" + b_d + \"\\n\" + b_i ) ; } if ( t_i == DeclarationType . REQUIRED ) { required . add ( b_i . resource . type ( ) ) ; } else if ( equalResource && t_d . droppedWith ( t_i ) ) { if ( i - 1 == lastUniqueIndex ) { dropped . add ( uniques . remove ( uniques . size ( ) - 1 ) ) ; } dropped . add ( b_i ) ; } else if ( ! equalResource || ! t_i . replacedBy ( t_d ) ) { uniques . add ( b_i ) ; lastUniqueIndex = i ; } } return withoutProvidedThatAreNotRequiredIn ( uniques , required , dropped ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "as long as there is a clear contract : namely that failure is always indicated by a EventEception [CODESPLIT] @ Override public < E , T > T compute ( Event < E , T > event ) throws Throwable { return unwrapGet ( event , submit ( event , ( ) -> doProcess ( event ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the given event type so that it is handled by the { @link EventProcessor } system . [CODESPLIT] protected < T > void handle ( Class < T > event ) { if ( ! event . isInterface ( ) ) throw new IllegalArgumentException ( \"Event type has to be an interface but was: \" + event ) ; initbind ( event ) . to ( ( Initialiser < T > ) ( listener , injector ) -> injector . resolve ( EventProcessor . class ) . register ( event , listener ) ) ; bind ( event ) . toSupplier ( ( dep , injector ) -> injector . resolve ( EventProcessor . class ) . getProxy ( event ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add ( accumulate ) a binding described by the 4 - tuple given . [CODESPLIT] public < T > void add ( Binding < T > complete ) { if ( ! complete . isComplete ( ) ) { throw new InconsistentBinding ( \"Incomplete binding added: \" + complete ) ; } // NB. #64 here we can inform post binding that about the new binding bindings . add ( complete ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the given { @link Macro } and derives the { @link #with ( Class Macro ) } type from its declaration . This is a utility method that can be used as long as the { @link Macro } implementation is not generic . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > Macros with ( Macro < T > macro ) { Class < ? > type = Type . supertype ( Macro . class , Type . raw ( macro . getClass ( ) ) ) . parameter ( 0 ) . rawType ; return with ( ( Class < ? super T > ) type , macro ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the given { @link Macro } for the given exact ( no super - types! ) type of values . [CODESPLIT] public < T > Macros with ( Class < T > type , Macro < ? extends T > macro ) { int index = index ( type ) ; if ( index >= 0 ) { Macro < ? > [ ] tmp = macros . clone ( ) ; tmp [ index ] = macro ; return new Macros ( types , tmp ) ; } return new Macros ( arrayPrepand ( type , types ) , arrayPrepand ( macro , macros ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A generic version of { @link Macro#expand ( Object Binding Bindings ) } that uses the matching predefined { @link Macro } for the actual type of the value and expands it . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T , V > void expandInto ( Bindings bindings , Binding < T > binding , V value ) { macroForValueOf ( ( Class < ? super V > ) value . getClass ( ) ) . expand ( value , binding , bindings ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Example - <i > typeOf< / i > [CODESPLIT] public Type < T > parametizedAsUpperBounds ( ) { if ( ! isParameterized ( ) ) return isRawType ( ) ? parametized ( wildcards ( rawType . getTypeParameters ( ) ) ) : this ; if ( areAllTypeParametersAreUpperBounds ( ) ) return this ; return new Type <> ( upperBound , rawType , arrayMap ( params , Type :: asUpperBound ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Arrays [CODESPLIT] public static < A > A [ ] arrayFilter ( A [ ] arr , Predicate < A > accept ) { if ( arr == null || arr . length == 0 ) return arr ; A [ ] accepted = newArray ( arr , arr . length ) ; int j = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) if ( accept . test ( arr [ i ] ) ) accepted [ j ++ ] = arr [ i ] ; return j == arr . length ? arr : copyOf ( accepted , j ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a special form of flatmap where the mapping does not return zero to n Bs but always returns a B . If { [CODESPLIT] public static < A , B > B [ ] arrayFlatmap ( A [ ] as , Class < B > to , Function < A , B > flatmapOp ) { B [ ] bs = newArray ( to , as . length ) ; int j = 0 ; for ( int i = 0 ; i < as . length ; i ++ ) { B b = flatmapOp . apply ( as [ i ] ) ; if ( b != null ) bs [ j ++ ] = b ; } return j == as . length ? bs : copyOf ( bs , j ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Annotations [CODESPLIT] public static Method annotationPropertyByType ( Class < ? > type , Class < ? extends Annotation > annotation ) { return arrayFindFirst ( annotation . getDeclaredMethods ( ) , m -> m . getReturnType ( ) == type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return A { @link Class } counts as virtual when it is known that its not a type handled by an { @link Injector } context either because it cannot be constructed at all or it does not make sense to let the { @link Injector } take care of it . This includes value types enums collection types ( including arrays ) or any type than cannot be instantiated by its nature ( abstract types ) . [CODESPLIT] public static boolean isClassVirtual ( Class < ? > cls ) { return cls == null || cls . isInterface ( ) || cls . isEnum ( ) || cls . isAnnotation ( ) || cls . isAnonymousClass ( ) || cls . isPrimitive ( ) || cls . isArray ( ) || Modifier . isAbstract ( cls . getModifiers ( ) ) || cls == String . class || Number . class . isAssignableFrom ( cls ) || cls == Boolean . class || cls == Void . class || cls == Class . class || Collection . class . isAssignableFrom ( cls ) || Map . class . isAssignableFrom ( cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return A { @link Class } is monomodal if it there is just a single possible initial state . All newly created instances can just have this similar initial state but due to internal state they could ( not necessarily must ) develop ( behave ) different later on . [CODESPLIT] public static boolean isClassMonomodal ( Class < ? > cls ) { if ( cls . isInterface ( ) ) return false ; if ( cls == Object . class ) return true ; for ( Field f : cls . getDeclaredFields ( ) ) if ( ! Modifier . isStatic ( f . getModifiers ( ) ) ) return false ; for ( Constructor < ? > c : cls . getDeclaredConstructors ( ) ) // maybe arguments are passed to super-type so we check it too if ( c . getParameterTypes ( ) . length > 0 ) return isClassMonomodal ( cls . getSuperclass ( ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Members [CODESPLIT] public static < T extends Member > T moreVisible ( T a , T b ) { int am = a . getModifiers ( ) ; int bm = b . getModifiers ( ) ; if ( isPublic ( am ) ) return a ; if ( isPublic ( bm ) ) return b ; if ( isProtected ( am ) ) return a ; if ( isProtected ( bm ) ) return b ; if ( isPrivate ( bm ) ) return a ; if ( isPrivate ( am ) ) return b ; return a ; // same }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the constructor with most visible visibility and longest argument list . Self - referencing constructors are ignored . [CODESPLIT] public static < T > Constructor < T > commonConstructor ( Class < T > type ) throws NoMethodForDependency { Constructor < ? > [ ] cs = type . getDeclaredConstructors ( ) ; if ( cs . length == 0 ) throw new NoMethodForDependency ( raw ( type ) ) ; Constructor < ? > mostParamsConstructor = null ; for ( Constructor < ? > c : cs ) { if ( ! arrayContains ( c . getParameterTypes ( ) , type , ( a , b ) -> a == b ) // avoid self referencing constructors (synthetic) as they cause endless loop && ( mostParamsConstructor == null // || ( moreVisible ( c , mostParamsConstructor ) == c && ( moreVisible ( mostParamsConstructor , c ) == c || c . getParameterCount ( ) > mostParamsConstructor . getParameterCount ( ) ) ) ) ) { mostParamsConstructor = c ; } } if ( mostParamsConstructor == null ) throw new NoMethodForDependency ( raw ( type ) ) ; @ SuppressWarnings ( \"unchecked\" ) Constructor < T > c = ( Constructor < T > ) mostParamsConstructor ; return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Sequences [CODESPLIT] public static boolean seqRegionEquals ( CharSequence s1 , CharSequence s2 , int length ) { if ( s1 . length ( ) < length || s2 . length ( ) < length ) return false ; if ( s1 == s2 ) return true ; for ( int i = length - 1 ; i > 0 ; i -- ) if ( s1 . charAt ( i ) != s2 . charAt ( i ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Exception Handling [CODESPLIT] public static < T > T orElse ( T defaultValue , Provider < T > src ) { try { return src . provide ( ) ; } catch ( UnresolvableDependency e ) { return defaultValue ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > foo . bar . baz - > foo . bar foo . bar . - > foo . < / pre > [CODESPLIT] private static String parent ( String root ) { return root . substring ( 0 , root . lastIndexOf ( ' ' , root . length ( ) - 2 ) + ( root . endsWith ( \".\" ) ? 1 : 0 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO maybe extract a Plugins Extension [CODESPLIT] public static < T > Dependency < T > dependency ( Class < T > type ) { return dependency ( raw ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method for transferring input stream to output . [CODESPLIT] protected static void writeInputStreamToOutput ( final Context context , final InputStream source , final OutputStream output ) throws IOException { BuffersPool pool = BeansManager . get ( context ) . getContainer ( ) . getBean ( BuffersPool . class ) ; IoUtils . transfer ( source , output , pool ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write next line as a long . [CODESPLIT] protected static void writeLong ( final Writer writer , final long value ) throws IOException { writer . write ( new StringBuilder ( ) . append ( value ) . append ( ' ' ) . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write next line to the output . [CODESPLIT] protected final void writeString ( final Writer writer , final String line ) throws IOException { if ( line != null ) { writer . write ( line + ' ' ) ; } else { writer . write ( ' ' ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make workarounds for POST requests via { [CODESPLIT] protected void doSendWorkarounds ( final URLConnection connection ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . GINGERBREAD && connection instanceof HttpURLConnection ) { try { Field resHeaderField = connection . getClass ( ) . getDeclaredField ( \"resHeader\" ) ; resHeaderField . setAccessible ( true ) ; resHeaderField . set ( connection , null ) ; } catch ( Exception e ) { Log . w ( \"Workaround\" , \"Failed to make a wrokaround for Android 2.2\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes { @code count } bytes from the byte array { @code buffer } starting at { @code offset } to this stream . If there is room in the buffer to hold the bytes they are copied in . If not the buffered bytes plus the bytes in { @code buffer } are written to the target stream the target is flushed and the buffer is cleared . [CODESPLIT] @ Override public synchronized void write ( final byte [ ] buffer , final int offset , final int length ) throws IOException { checkNotClosed ( ) ; if ( buffer == null ) { throw new NullPointerException ( \"buffer == null\" ) ; } final byte [ ] internalBuffer = buf ; if ( length >= internalBuffer . length ) { flushInternal ( ) ; out . write ( buffer , offset , length ) ; return ; } if ( ( offset | length ) < 0 || offset > buffer . length || buffer . length - offset < length ) { throw new ArrayIndexOutOfBoundsException ( \"length=\" + buffer . length + \"; regionStart=\" + offset + \"; regionLength=\" + length ) ; } // flush the internal buffer first if we have not enough space left if ( length > ( internalBuffer . length - count ) ) { flushInternal ( ) ; } System . arraycopy ( buffer , offset , internalBuffer , count , length ) ; count += length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes one byte to this stream . Only the low order byte of the integer { @code oneByte } is written . If there is room in the buffer the byte is copied into the buffer and the count incremented . Otherwise the buffer plus { @code oneByte } are written to the target stream the target is flushed and the buffer is reset . [CODESPLIT] @ Override public synchronized void write ( final int oneByte ) throws IOException { checkNotClosed ( ) ; if ( count == buf . length ) { out . write ( buf , 0 , count ) ; count = 0 ; } buf [ count ++ ] = ( byte ) oneByte ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set network stats tag . Converts string tag to integer one . [CODESPLIT] protected void setConvertedTrafficStatsTag ( final String tag ) { result . statsTag = Utils . getTrafficStatsTag ( tag ) ; if ( config . isDebugRest ( ) ) { Log . d ( TAG , \"TrafficStats tag <\" + tag + \">=\" + Integer . toHexString ( result . statsTag ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup binary content with the local file . [CODESPLIT] protected void addBinaryContent ( final String name , final Uri data , final String contentType ) { String contentName = RequestDescription . BINARY_NAME_DEFAULT ; if ( ContentResolver . SCHEME_FILE . equals ( data . getScheme ( ) ) ) { try { contentName = new File ( new URI ( data . toString ( ) ) ) . getName ( ) ; } catch ( final URISyntaxException e ) { Log . e ( TAG , \"Bad file URI: \" + data , e ) ; } } addBinaryContent ( name , contentName , data , contentType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup binary content with the local file . [CODESPLIT] protected void addBinaryContent ( final String name , final String contentName , final Uri data , final String contentType ) { final ContentUriBinaryData bdata = new ContentUriBinaryData ( ) ; bdata . setName ( name ) ; bdata . setContentUri ( data , contentName ) ; bdata . setContentType ( contentType ) ; result . addBinaryData ( bdata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup binary content with the bitmap . [CODESPLIT] protected void addBitmap ( final String name , final Bitmap bitmap , final String fileName ) { final BitmapBinaryData bdata = new BitmapBinaryData ( ) ; bdata . setName ( name ) ; bdata . setContentName ( fileName ) ; bdata . setBitmap ( bitmap ) ; result . addBinaryData ( bdata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup binary content with the file descriptor . [CODESPLIT] protected void addFileDescriptor ( final String name , final AssetFileDescriptor fd , final String contentType , final String fileName ) { final AssetFdBinaryData bdata = new AssetFdBinaryData ( ) ; bdata . setFileDescriptor ( fileName , fd ) ; bdata . setName ( name ) ; bdata . setContentType ( contentType ) ; result . addBinaryData ( bdata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove parameter with the specified name from request description . [CODESPLIT] protected Parameter removeParameter ( final String name ) { if ( name == null ) { throw new IllegalArgumentException ( \"Parameter name cannot be null\" ) ; } final Iterator < Parameter > iter = result . simpleParameters . getChildren ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { final Parameter p = iter . next ( ) ; if ( name . equals ( p . name ) ) { iter . remove ( ) ; return p ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add header to request description . [CODESPLIT] protected BaseRequestBuilder < MT > addHeader ( final String name , final String value ) { result . addHeader ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear the builder . [CODESPLIT] public void clear ( ) { final RequestDescription result = this . result ; result . simpleParameters . children . clear ( ) ; result . clearBinaryData ( ) ; result . contentType = null ; result . clearHeaders ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Play the track . [CODESPLIT] protected void callPlay ( final Uri uri , final int volume , final Bundle params ) { playing = true ; paused = false ; context . startService ( createPlayIntent ( ) . setData ( uri ) . putExtra ( StreamingPlaybackService . EXTRA_VOLUME , volume ) . putExtra ( StreamingPlaybackService . EXTRA_TRACK_INFO , params ) ) ; bind ( ) ; onPlayingChanged ( ) ; preparing = true ; onPreparingChanged ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop playback . [CODESPLIT] protected void callStop ( ) { playing = false ; paused = false ; context . startService ( createStopIntent ( ) ) ; onPlayingChanged ( ) ; preparing = false ; onPreparingChanged ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind to the streaming service . [CODESPLIT] protected final void bind ( ) { if ( bindRequested ) { return ; } final boolean result = context . bindService ( createBindIntent ( ) , serviceConnection , 0 ) ; if ( DEBUG ) { Log . v ( TAG , \"Bind to streaming service: \" + result ) ; } bindRequested = result ; onBind ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbind from the streaming service . [CODESPLIT] protected final void unbind ( ) { if ( streamingPlayback != null ) { dropListener ( ) ; } try { context . unbindService ( serviceConnection ) ; } catch ( final RuntimeException e ) { if ( DEBUG ) { Log . w ( TAG , \"Cannot unbind radio\" , e ) ; } } bindRequested = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drop streaming service listener . [CODESPLIT] protected final void dropListener ( ) { if ( DEBUG ) { Log . v ( TAG , \"Drop listener\" ) ; } if ( streamingPlayback != null ) { try { streamingPlayback . removeListener ( ) ; } catch ( final RemoteException e ) { Log . e ( TAG , \"Cannot remove listener\" , e ) ; } bindRequested = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store image to the disk cache . If max allowed size is set image may be rescaled on disk . [CODESPLIT] public void storeToDisk ( ) throws IOException { if ( manager . isPresentOnDisk ( url ) ) { return ; } if ( ! hasAllowedSize ( ) ) { IoUtils . consumeStream ( getRemoteInputStream ( ) , manager . getBuffersPool ( ) ) ; return ; } ImageResult result = decodeStream ( getRemoteInputStream ( ) , true ) ; if ( result . getType ( ) == ImageSourceType . NETWORK && result . getBitmap ( ) != null ) { // image was scaled writeBitmapToDisk ( result . getBitmap ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Plan an image on loading . [CODESPLIT] public ImageRequestsBuilder add ( final String url ) { requests . add ( new ImageRequest ( manager , url , defaultAllowedSize ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Plan an image on loading . [CODESPLIT] public ImageRequestsBuilder add ( final String url , final float relativeSize ) { requests . add ( new ImageRequest ( manager , url , relativeSize ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Composes URI builder using { [CODESPLIT] protected Uri . Builder buildUri ( ) { final Uri . Builder builder = Uri . parse ( requestDescription . getUrl ( ) ) . buildUpon ( ) ; for ( final Parameter p : requestDescription . getSimpleParameters ( ) . getChildren ( ) ) { if ( p instanceof ParameterValue ) { builder . appendQueryParameter ( p . getName ( ) , ( ( ParameterValue ) p ) . getValue ( ) ) ; } } return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all the bytes from input stream and convert them to a string . Input stream is closed after this method invocation . [CODESPLIT] public static String streamToString ( final InputStream stream , final String charset , final BuffersPool buffersPool ) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; transfer ( stream , output , buffersPool ) ; return new String ( output . toByteArray ( ) , charset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read all the bytes from input stream and convert them to a string using UTF - 8 charset . Input stream is closed after this method invocation . [CODESPLIT] public static String streamToString ( final InputStream stream , final BuffersPool buffersPool ) throws IOException { return streamToString ( stream , UTF_8_NAME , buffersPool ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transfers all the bytes from input to output stream . If read / write operations are successful output stream will be flushed . Input stream is always closed after this method invocation . [CODESPLIT] public static void transfer ( final InputStream input , final OutputStream output , final BuffersPool buffersPool ) throws IOException { final InputStream in = buffersPool == null ? new BufferedInputStream ( input , BUFFER_SIZE_8K ) : new PoolableBufferedInputStream ( input , BUFFER_SIZE_8K , buffersPool ) ; final byte [ ] buffer = buffersPool == null ? new byte [ BUFFER_SIZE_8K ] : buffersPool . get ( BUFFER_SIZE_8K ) ; try { int cnt ; while ( ( cnt = in . read ( buffer ) ) != EOF ) { output . write ( buffer , 0 , cnt ) ; } output . flush ( ) ; } finally { closeQuietly ( in ) ; if ( buffersPool != null ) { buffersPool . release ( buffer ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consume the stream and close it . This implementation calls { @link InputStream#read ( byte [] ) } method and ignores any read bytes . [CODESPLIT] public static void consumeStream ( final InputStream input , final BuffersPool buffersPool ) throws IOException { // do not use skip, just use a buffer and read it all final byte [ ] buffer = buffersPool == null ? new byte [ BUFFER_SIZE_8K ] : buffersPool . get ( BUFFER_SIZE_8K ) ; try { //noinspection StatementWithEmptyBody while ( input . read ( buffer ) != EOF ) ; } finally { closeQuietly ( input ) ; if ( buffersPool != null ) { buffersPool . release ( buffer ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets stream of uncompressed bytes for the { @link URLConnection } wrapping its input stream according to what is defined in its content encoding . Supported encodings : { @link #ENCODING_GZIP } { @link #ENCODING_DEFLATE } . [CODESPLIT] public static InputStream getUncompressedInputStream ( final URLConnection connection ) throws IOException { final InputStream source = connection . getInputStream ( ) ; final String encoding = connection . getContentEncoding ( ) ; return getUncompressedInputStream ( encoding , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the supplied stream into either { @link GZIPInputStream } or { @link InflaterInputStream } depending on { @code encoding } parameter value . [CODESPLIT] public static InputStream getUncompressedInputStream ( final String encoding , final InputStream source ) throws IOException { if ( ENCODING_GZIP . equalsIgnoreCase ( encoding ) ) { return new GZIPInputStream ( source ) ; } if ( ENCODING_DEFLATE . equalsIgnoreCase ( encoding ) ) { final Inflater inflater = new Inflater ( /*no header*/ true ) ; return new InflaterInputStream ( source , inflater ) ; } return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Throw { [CODESPLIT] protected void checkBeanExists ( final String name ) { if ( name == null ) { throw new NullPointerException ( \"Bean name cannot be null\" ) ; } if ( ! beansManager . getContainer ( ) . containsBean ( name ) ) { throw new IllegalArgumentException ( \"Bean \" + name + \" does not exist\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the data to the given OutputStream . [CODESPLIT] @ Override protected void sendData ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendData(OutputStream)\" ) ; } out . write ( getContent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the number of bytes that are available before this stream will block . This method returns the number of bytes available in the buffer plus those available in the source stream . [CODESPLIT] @ Override public synchronized int available ( ) throws IOException { final InputStream localIn = in ; // 'in' could be invalidated by close()\r if ( buf == null || localIn == null ) { throw new IOException ( \"Stream is closed\" ) ; } return count - pos + localIn . available ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes this stream . The source stream is closed and any resources associated with it are released . [CODESPLIT] @ Override public void close ( ) throws IOException { final byte [ ] localBuf = buf ; buf = null ; final InputStream localIn = in ; in = null ; pool . release ( localBuf ) ; if ( localIn != null ) { localIn . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a single byte from this stream and returns it as an integer in the range from 0 to 255 . Returns - 1 if the end of the source string has been reached . If the internal buffer does not contain any available bytes then it is filled from the source stream and the first byte is returned . [CODESPLIT] @ Override public synchronized int read ( ) throws IOException { // Use local refs since buf and in may be invalidated by an\r // unsynchronized close()\r byte [ ] localBuf = buf ; final InputStream localIn = in ; if ( localBuf == null || localIn == null ) { throw new IOException ( \"Stream is closed\" ) ; } /* Are there buffered bytes available? */ if ( pos >= count && fillbuf ( localIn , localBuf ) == - 1 ) { return - 1 ; /* no, fill buffer */ } // localBuf may have been invalidated by fillbuf\r if ( localBuf != buf ) { localBuf = buf ; if ( localBuf == null ) { throw new IOException ( \"Stream is closed\" ) ; } } /* Did filling the buffer fail with -1 (EOF)? */ final int mask = 0xFF ; if ( count - pos > 0 ) { return localBuf [ pos ++ ] & mask ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads at most { @code length } bytes from this stream and stores them in byte array { @code buffer } starting at offset { @code offset } . Returns the number of bytes actually read or - 1 if no bytes were read and the end of the stream was encountered . If all the buffered bytes have been used a mark has not been set and the requested number of bytes is larger than the receiver s buffer size this implementation bypasses the buffer and simply places the results directly into { @code buffer } . [CODESPLIT] @ Override public synchronized int read ( final byte [ ] buffer , final int start , final int length ) throws IOException { int offset = start ; // Use local ref since buf may be invalidated by an unsynchronized\r // close()\r byte [ ] localBuf = buf ; if ( localBuf == null ) { throw new IOException ( \"Stream is closed\" ) ; } // avoid int overflow\r // BEGIN android-changed\r // Exception priorities (in case of multiple errors) differ from\r // RI, but are spec-compliant.\r // made implicit null check explicit, used (offset | length) < 0\r // instead of (offset < 0) || (length < 0) to safe one operation\r if ( buffer == null ) { throw new NullPointerException ( \"Buffer is null\" ) ; } if ( ( offset | length ) < 0 || offset > buffer . length - length ) { throw new IndexOutOfBoundsException ( \"Bad offsets\" ) ; } // END android-changed\r if ( length == 0 ) { return 0 ; } final InputStream localIn = in ; if ( localIn == null ) { throw new IOException ( \"Stream is closed\" ) ; } int required ; if ( pos < count ) { /* There are bytes available in the buffer. */ final int copylength = count - pos >= length ? length : count - pos ; System . arraycopy ( localBuf , pos , buffer , offset , copylength ) ; pos += copylength ; if ( copylength == length || localIn . available ( ) == 0 ) { return copylength ; } offset += copylength ; required = length - copylength ; } else { required = length ; } while ( true ) { int read ; /*\r\n       * If we're not marked and the required size is greater than the\r\n       * buffer, simply read the bytes directly bypassing the buffer.\r\n       */ if ( markpos == - 1 && required >= localBuf . length ) { read = localIn . read ( buffer , offset , required ) ; if ( read == - 1 ) { return required == length ? - 1 : length - required ; } } else { if ( fillbuf ( localIn , localBuf ) == - 1 ) { return required == length ? - 1 : length - required ; } // localBuf may have been invalidated by fillbuf\r if ( localBuf != buf ) { localBuf = buf ; if ( localBuf == null ) { throw new IOException ( \"Stream is closed\" ) ; } } read = count - pos >= required ? required : count - pos ; System . arraycopy ( localBuf , pos , buffer , offset , read ) ; pos += read ; } required -= read ; if ( required == 0 ) { return length ; } if ( localIn . available ( ) == 0 ) { return length - required ; } offset += read ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets this stream to the last marked location . [CODESPLIT] @ Override public synchronized void reset ( ) throws IOException { // BEGIN android-changed\r /*\r\n     * These exceptions get thrown in some \"normalish\" circumstances,\r\n     * so it is preferable to avoid loading up the whole big set of\r\n     * messages just for these cases.\r\n     */ if ( buf == null ) { throw new IOException ( \"Stream is closed\" ) ; } if ( - 1 == markpos ) { throw new IOException ( \"Mark has been invalidated.\" ) ; } // END android-changed\r pos = markpos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips { @code amount } number of bytes in this stream . Subsequent { @code read () } s will not return these bytes unless { @code reset () } is used . [CODESPLIT] @ Override public synchronized long skip ( final long amount ) throws IOException { // Use local refs since buf and in may be invalidated by an\r // unsynchronized close()\r final byte [ ] localBuf = buf ; final InputStream localIn = in ; if ( localBuf == null ) { throw new IOException ( \"Stream is closed\" ) ; } if ( amount < 1 ) { return 0 ; } if ( localIn == null ) { throw new IOException ( \"Stream is closed\" ) ; } if ( count - pos >= amount ) { pos += amount ; return amount ; } long read = count - pos ; pos = count ; if ( markpos != - 1 && amount <= marklimit ) { if ( fillbuf ( localIn , localBuf ) == - 1 ) { return read ; } if ( count - pos >= amount - read ) { pos += amount - read ; return amount ; } // Couldn't get all the bytes, skip what we read\r read += ( count - pos ) ; pos = count ; return read ; } return read + localIn . skip ( amount - read ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the start to the specified output stream . [CODESPLIT] protected void sendStart ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendStart(OutputStream out)\" ) ; } out . write ( EXTRA_BYTES ) ; out . write ( getPartBoundary ( ) ) ; out . write ( CRLF_BYTES ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the content disposition header to the specified output stream . [CODESPLIT] protected void sendDispositionHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendDispositionHeader(OutputStream out)\" ) ; } out . write ( CONTENT_DISPOSITION_BYTES ) ; out . write ( QUOTE_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( getName ( ) ) ) ; out . write ( QUOTE_BYTES ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the content type header to the specified output stream . [CODESPLIT] protected void sendContentTypeHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendContentTypeHeader(OutputStream out)\" ) ; } final String contentType = getContentType ( ) ; if ( contentType != null ) { out . write ( CRLF_BYTES ) ; out . write ( CONTENT_TYPE_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( contentType ) ) ; final String charSet = getCharSet ( ) ; if ( charSet != null ) { out . write ( CHARSET_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( charSet ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the content transfer encoding header to the specified output stream . [CODESPLIT] protected void sendTransferEncodingHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendTransferEncodingHeader(OutputStream out)\" ) ; } final String transferEncoding = getTransferEncoding ( ) ; if ( transferEncoding != null ) { out . write ( CRLF_BYTES ) ; out . write ( CONTENT_TRANSFER_ENCODING_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( transferEncoding ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the end of the header to the output stream . [CODESPLIT] protected void sendEndOfHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendEndOfHeader(OutputStream out)\" ) ; } out . write ( CRLF_BYTES ) ; out . write ( CRLF_BYTES ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the end data to the output stream . [CODESPLIT] protected void sendEnd ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendEnd(OutputStream out)\" ) ; } out . write ( CRLF_BYTES ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write all the data to the output stream . If you override this method make sure to override #length () as well [CODESPLIT] public void send ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter send(OutputStream out)\" ) ; } sendStart ( out ) ; sendDispositionHeader ( out ) ; sendContentTypeHeader ( out ) ; sendTransferEncodingHeader ( out ) ; sendEndOfHeader ( out ) ; sendData ( out ) ; sendEnd ( out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the full length of all the data . If you override this method make sure to override #send ( OutputStream ) as well [CODESPLIT] public long length ( ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter length()\" ) ; } if ( lengthOfData ( ) < 0 ) { return - 1 ; } final ByteArrayOutputStream overhead = new ByteArrayOutputStream ( ) ; sendStart ( overhead ) ; sendDispositionHeader ( overhead ) ; sendContentTypeHeader ( overhead ) ; sendTransferEncodingHeader ( overhead ) ; sendEndOfHeader ( overhead ) ; sendEnd ( overhead ) ; return overhead . size ( ) + lengthOfData ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write all parts and the last boundary to the specified output stream . [CODESPLIT] public static void sendParts ( final OutputStream out , final Part [ ] parts , final byte [ ] partBoundary ) throws IOException { if ( parts == null ) { throw new IllegalArgumentException ( \"Parts may not be null\" ) ; } if ( partBoundary == null || partBoundary . length == 0 ) { throw new IllegalArgumentException ( \"partBoundary may not be empty\" ) ; } for ( int i = 0 ; i < parts . length ; i ++ ) { // set the part boundary before the part is sent parts [ i ] . setPartBoundary ( partBoundary ) ; parts [ i ] . send ( out ) ; } out . write ( EXTRA_BYTES ) ; out . write ( partBoundary ) ; out . write ( EXTRA_BYTES ) ; out . write ( CRLF_BYTES ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the length of the multipart message including the given parts . [CODESPLIT] public static long getLengthOfParts ( final Part [ ] parts , final byte [ ] partBoundary ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"getLengthOfParts(Parts[])\" ) ; } if ( parts == null ) { throw new IllegalArgumentException ( \"Parts may not be null\" ) ; } long total = 0 ; for ( int i = 0 ; i < parts . length ; i ++ ) { // set the part boundary before we calculate the part's length parts [ i ] . setPartBoundary ( partBoundary ) ; final long l = parts [ i ] . length ( ) ; if ( l < 0 ) { return - 1 ; } total += l ; } total += EXTRA_BYTES . length ; total += partBoundary . length ; total += EXTRA_BYTES . length ; total += CRLF_BYTES . length ; return total ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if it is it returns the url parameter [CODESPLIT] private String isRedirect ( String uri ) throws URISyntaxException , MalformedURLException { // Decode the path.        \r URI url = new URI ( uri ) ; if ( REDIRECT_PATH . equals ( url . getPath ( ) ) ) { String query = url . getRawQuery ( ) ; Map < String , String > params = getQueryMap ( query ) ; String urlParam = params . get ( URL_PARAMETER ) ; if ( urlParam == null ) return null ; try { return URLDecoder . decode ( urlParam , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { Logger . getLogger ( WebsockifyProxyHandler . class . getName ( ) ) . severe ( e . getMessage ( ) ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When file timestamp is the same as what the browser is sending up send a 304 Not Modified [CODESPLIT] private void sendNotModified ( ChannelHandlerContext ctx ) { HttpResponse response = new DefaultHttpResponse ( HTTP_1_1 , HttpResponseStatus . NOT_MODIFIED ) ; setDateHeader ( response ) ; // Close the connection as soon as the error message is sent.\r ctx . getChannel ( ) . write ( response ) . addListener ( ChannelFutureListener . CLOSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the Date header for the HTTP response [CODESPLIT] private void setDateHeader ( HttpResponse response ) { SimpleDateFormat dateFormatter = new SimpleDateFormat ( HTTP_DATE_FORMAT , Locale . US ) ; dateFormatter . setTimeZone ( TimeZone . getTimeZone ( HTTP_DATE_GMT_TIMEZONE ) ) ; Calendar time = new GregorianCalendar ( ) ; response . setHeader ( HttpHeaders . Names . DATE , dateFormatter . format ( time . getTime ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the Date and Cache headers for the HTTP Response [CODESPLIT] private void setDateAndCacheHeaders ( HttpResponse response , File fileToCache ) { SimpleDateFormat dateFormatter = new SimpleDateFormat ( HTTP_DATE_FORMAT , Locale . US ) ; dateFormatter . setTimeZone ( TimeZone . getTimeZone ( HTTP_DATE_GMT_TIMEZONE ) ) ; // Date header\r Calendar time = new GregorianCalendar ( ) ; response . setHeader ( HttpHeaders . Names . DATE , dateFormatter . format ( time . getTime ( ) ) ) ; // Add cache headers\r time . add ( Calendar . SECOND , HTTP_CACHE_SECONDS ) ; response . setHeader ( HttpHeaders . Names . EXPIRES , dateFormatter . format ( time . getTime ( ) ) ) ; response . setHeader ( HttpHeaders . Names . CACHE_CONTROL , \"private, max-age=\" + HTTP_CACHE_SECONDS ) ; response . setHeader ( HttpHeaders . Names . LAST_MODIFIED , dateFormatter . format ( new Date ( fileToCache . lastModified ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the content type header for the HTTP Response [CODESPLIT] private void setContentTypeHeader ( HttpResponse response , File file ) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap ( ) ; response . setHeader ( HttpHeaders . Names . CONTENT_TYPE , mimeTypesMap . getContentType ( file . getPath ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the specified channel after all queued write requests are flushed . [CODESPLIT] static void closeOnFlush ( Channel ch ) { if ( ch . isConnected ( ) ) { ch . write ( ChannelBuffers . EMPTY_BUFFER ) . addListener ( ChannelFutureListener . CLOSE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the disposition header to the output stream . [CODESPLIT] @ Override protected void sendDispositionHeader ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( \"FilePart\" , \"enter sendDispositionHeader(OutputStream out)\" ) ; } super . sendDispositionHeader ( out ) ; final String filename = this . source . getFileName ( ) ; if ( filename != null ) { out . write ( FILE_NAME_BYTES ) ; out . write ( QUOTE_BYTES ) ; out . write ( EncodingUtils . getAsciiBytes ( filename ) ) ; out . write ( QUOTE_BYTES ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the data in source to the specified stream . [CODESPLIT] @ Override protected void sendData ( final OutputStream out ) throws IOException { if ( DEBUG ) { Log . v ( TAG , \"enter sendData(OutputStream out)\" ) ; } if ( lengthOfData ( ) == 0 ) { // this file contains no data, so there is nothing to send. // we don't want to create a zero length buffer as this will // cause an infinite loop when reading. if ( DEBUG ) { Log . d ( TAG , \"No data to send.\" ) ; } return ; } final int size = 4096 ; final byte [ ] tmp = new byte [ size ] ; final InputStream instream = source . createInputStream ( ) ; try { int len ; while ( ( len = instream . read ( tmp ) ) >= 0 ) { out . write ( tmp , 0 , len ) ; } } finally { // we're done with the stream, close it instream . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup cache . This operation causes disk reads . [CODESPLIT] protected void install ( final int version ) throws IOException { if ( buffersPool == null ) { throw new IllegalStateException ( \"Buffers pool is not resolved\" ) ; } diskCache = DiskLruCache . open ( ensureWorkingDirectory ( ) , version , ENTRIES_COUNT , getMaxSize ( ) ) ; onCacheInstalled ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method is synchronized in order to avoid concurrent calls to mkdir [CODESPLIT] private synchronized File ensureWorkingDirectory ( ) throws IOException { File directory = getWorkingDirectory ( ) ; if ( ! directory . exists ( ) ) { if ( ! directory . mkdirs ( ) ) { throw new IOException ( \"Working directory \" + directory + \" cannot be created\" ) ; } } else { if ( ! directory . isDirectory ( ) ) { if ( ! directory . delete ( ) ) { throw new IOException ( directory + \" is not a directory and cannot be deleted\" ) ; } if ( ! directory . mkdirs ( ) ) { throw new IOException ( \"Working directory \" + directory + \" cannot be recreated\" ) ; } } } return directory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read cache for the specified cache entry . [CODESPLIT] protected CacheResponse get ( final CacheEntry requestInfo ) { if ( ! checkDiskCache ( ) ) { return null ; } final CacheEntry entry = newCacheEntry ( ) ; final DiskLruCache . Snapshot snapshot = readCacheInfo ( requestInfo , entry ) ; if ( snapshot == null ) { return null ; } if ( ! entry . matches ( requestInfo ) || ! entry . canBeUsed ( ) ) { snapshot . close ( ) ; return null ; } hitCount . incrementAndGet ( ) ; final InputStream body = newBodyInputStream ( snapshot ) ; return entry . newCacheResponse ( body ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an input stream that reads the body of a snapshot closing the snapshot when the stream is closed . [CODESPLIT] private InputStream newBodyInputStream ( final DiskLruCache . Snapshot snapshot ) { return new FilterInputStream ( snapshot . getInputStream ( ENTRY_BODY ) ) { @ Override public void close ( ) throws IOException { snapshot . close ( ) ; super . close ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare for new width and hight . [CODESPLIT] protected void reset ( final int width , final int height ) { Bitmap bitmap = this . bitmap ; // recycle old buffer if ( bitmap != null ) { bitmap . recycle ( ) ; } bitmap = Bitmap . createBitmap ( width , height , Bitmap . Config . ARGB_8888 ) ; // high quality this . bitmap = bitmap ; this . bitmapCanvas = new Canvas ( bitmap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the singleton instance for this class [CODESPLIT] public static WebsockifySslContext getInstance ( String keystore , String password , String keyPassword ) { WebsockifySslContext context = SingletonHolder . INSTANCE_MAP . get ( keystore ) ; if ( context == null ) { context = new WebsockifySslContext ( keystore , password , keyPassword ) ; SingletonHolder . INSTANCE_MAP . put ( keystore , context ) ; } return context ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates that a keystore with the given parameters exists and can be used for an SSL context . [CODESPLIT] public static void validateKeystore ( String keystore , String password , String keyPassword ) throws KeyManagementException , UnrecoverableKeyException , IOException , NoSuchAlgorithmException , CertificateException , KeyStoreException { getSSLContext ( keystore , password , keyPassword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method replaces the scale type of an image view without call to layout requests . [CODESPLIT] public ScaleType replaceScaleType ( final ScaleType type ) { blockLayoutRequests = true ; final ScaleType result = getScaleType ( ) ; setScaleType ( type ) ; blockLayoutRequests = false ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a scale type and store a previous one that will be restores after the next call to { [CODESPLIT] public void setTemporaryScaleType ( final ScaleType scaleType ) { final ScaleType old = replaceScaleType ( scaleType ) ; if ( storedScaleType == null ) { storedScaleType = old ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Please call it from the main thread ( with looper ) . [CODESPLIT] public void startListening ( final Context context ) { if ( DEBUG ) { Log . d ( TAG , \"Start location listening...\" ) ; } try { locationManager = ( LocationManager ) context . getSystemService ( Context . LOCATION_SERVICE ) ; if ( locationManager == null ) { return ; } } catch ( final Exception e ) { return ; } myHandler = myLooper != null ? new MyHandler ( myLooper ) : new MyHandler ( ) ; if ( listener != null ) { listener . onLocationStart ( ) ; } final Location last = getLastKnown ( locationManager ) ; if ( last != null ) { newLocation ( last ) ; } final Criteria c = new Criteria ( ) ; c . setAltitudeRequired ( false ) ; c . setSpeedRequired ( false ) ; c . setBearingRequired ( false ) ; c . setCostAllowed ( false ) ; c . setPowerRequirement ( Criteria . POWER_LOW ) ; c . setAccuracy ( Criteria . ACCURACY_COARSE ) ; final String coarseProvider = locationManager . getBestProvider ( c , false ) ; c . setPowerRequirement ( Criteria . NO_REQUIREMENT ) ; c . setAccuracy ( Criteria . ACCURACY_FINE ) ; final String fineProvider = locationManager . getBestProvider ( c , false ) ; if ( DEBUG ) { Log . d ( TAG , \"Providers \" + coarseProvider + \"/\" + fineProvider ) ; } final long minTime = 60000 ; final int minDistance = 50 ; if ( coarseProvider != null ) { if ( DEBUG ) { Log . d ( TAG , \"Register for \" + coarseProvider ) ; } locationManager . requestLocationUpdates ( coarseProvider , minTime , minDistance , coarseListener ) ; myHandler . sendEmptyMessageDelayed ( MSG_STOP_COARSE_PROVIDER , MAX_COARSE_PROVIDER_LISTEN_TIME ) ; } if ( fineProvider != null ) { if ( DEBUG ) { Log . d ( TAG , \"Register for \" + fineProvider ) ; } locationManager . requestLocationUpdates ( fineProvider , minTime , minDistance , fineListener ) ; myHandler . sendEmptyMessageDelayed ( MSG_STOP_FINE_PROVIDER , MAX_FINE_PROVIDER_LISTEN_TIME ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop updates . [CODESPLIT] public void stopListening ( ) { if ( locationManager == null ) { return ; } if ( DEBUG ) { Log . d ( TAG , \"Stop location listening...\" ) ; } if ( listener != null ) { listener . onLocationStop ( ) ; } myHandler . removeMessages ( MSG_STOP_FINE_PROVIDER ) ; locationManager . removeUpdates ( coarseListener ) ; locationManager . removeUpdates ( fineListener ) ; locationManager = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a pending intent that can be used for starting request processing . Note that after this method is executed executor of the request builder is always null . [CODESPLIT] public PendingIntent getPendingIntent ( final RequestBuilder < ? > requestBuilder , final int flags ) { return PendingIntent . getService ( context , 0 , getIntent ( requestBuilder ) , flags ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform disconnect actions . [CODESPLIT] protected void disconnect ( final URLConnection connection ) { final URLConnection http = UrlConnectionWrapper . unwrap ( connection ) ; if ( http instanceof HttpURLConnection ) { ( ( HttpURLConnection ) http ) . disconnect ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the service connection . [CODESPLIT] public void bind ( ) { if ( serviceObject != null ) { return ; } final Context context = contextRef . get ( ) ; if ( context == null ) { return ; } // TODO make it configurable\r final Intent intent = new Intent ( context , GoroService . class ) ; intent . setAction ( getInterfaceClass ( ) . getName ( ) ) ; if ( DEBUG_CALLS ) { Log . v ( TAG , \"Attempt to bind to service \" + this + \"/\" + context , new RuntimeException ( ) ) ; } // start manually, so that it will be stopped manually\r context . startService ( intent ) ; final boolean bindResult = context . bindService ( intent , this , 0 ) ; if ( DEBUG ) { Log . v ( TAG , \"Binded to service: \" + bindResult + \", \" + context + \", interface: \" + getInterfaceClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroy the service connection . [CODESPLIT] public void unbind ( ) { if ( serviceObject == null ) { return ; } serviceObject = null ; final Context context = contextRef . get ( ) ; if ( DEBUG ) { Log . v ( TAG , \"Unbind \" + context + \" from \" + getInterfaceClass ( ) ) ; } if ( context == null ) { return ; } try { context . unbindService ( this ) ; } catch ( final Exception e ) { if ( DEBUG ) { Log . e ( TAG , \"Cannot unbind from application service\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method should be called when wrapped view gets changes related to this consumer . [CODESPLIT] public void notifyAboutViewChanges ( ) { final T view = this . view ; if ( view != null && view instanceof ImagesLoadListenerProvider ) { this . listener = ( ( ImagesLoadListenerProvider ) view ) . getImagesLoadListener ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The client won t send any message so connect directly on channel open [CODESPLIT] @ Override public void channelOpen ( final ChannelHandlerContext ctx , final ChannelStateEvent e ) throws Exception { try { // make the proxy connection\r ensureTargetConnection ( e . getChannel ( ) , false , null ) ; } catch ( Exception ex ) { // target connection failed, so close the client connection\r e . getChannel ( ) . close ( ) ; ex . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Data loading has been successful we are going to accept data . Here we can implement some accumulation logic . [CODESPLIT] protected ResponseData < MT > onAcceptData ( final ResponseData < MT > previousData , final ResponseData < MT > responseData ) { return responseData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "request to completely reset the loader [CODESPLIT] @ Override protected void onReset ( ) { if ( DEBUG ) { Log . v ( TAG , \"onReset \" + this ) ; } super . onReset ( ) ; onStopLoading ( ) ; if ( receivedResponse != null ) { onReleaseData ( receivedResponse ) ; receivedResponse = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For testing only . [CODESPLIT] void waitForLoader ( final long time ) { try { done . await ( time , TimeUnit . MILLISECONDS ) ; } catch ( final InterruptedException e ) { Log . e ( TAG , \"waitForLoader() ininterrupted\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main thread [CODESPLIT] public boolean addTarget ( final ImageConsumer imageHolder ) { if ( future . isCancelled ( ) ) { return false ; } // we should start a new task imageHolder . onStart ( this , request . url ) ; synchronized ( targets ) { if ( result != null ) { imagesManager . setResultImage ( imageHolder , result , false ) ; imageHolder . onFinish ( request . url , result ) ; } else if ( error != null ) { imageHolder . onError ( request . url , error ) ; } else { imageHolder . currentLoader = this ; targets . add ( imageHolder ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main thread [CODESPLIT] public void removeTarget ( final ImageConsumer consumer ) { if ( imagesManager . debug ) { Log . d ( TAG , \"Cancel request: \" + request . getKey ( ) + \"\\nLoader: \" + this ) ; } consumer . onCancel ( request . url ) ; synchronized ( targets ) { targets . remove ( consumer ) ; if ( targets . isEmpty ( ) ) { if ( ! future . cancel ( true ) ) { if ( imagesManager . debug ) { Log . d ( TAG , \"Can't cancel task so let's try to remove loader manually\" ) ; } imagesManager . currentLoads . remove ( request . getKey ( ) , this ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "worker thread [CODESPLIT] private void safeImageSet ( final ImageResult result ) { if ( imagesManager . debug ) { Log . v ( ImagesManager . TAG , \"Post setting drawable for \" + request . getKey ( ) ) ; } synchronized ( targets ) { if ( this . result != null ) { throw new IllegalStateException ( \"Result is already set\" ) ; } memCacheImage ( result ) ; this . result = result ; } post ( new Runnable ( ) { @ Override public void run ( ) { if ( imagesManager . debug ) { Log . v ( TAG , \"Set drawable for \" + request . getKey ( ) ) ; } final ArrayList < ImageConsumer > targets = ImageLoader . this . targets ; final int count = targets . size ( ) ; if ( count > 0 ) { //noinspection ForLoopReplaceableByForEach for ( int i = 0 ; i < count ; i ++ ) { final ImageConsumer imageHolder = targets . get ( i ) ; if ( imagesManager . debug ) { Log . d ( TAG , \"Try to set \" + imageHolder + \" - \" + request . getKey ( ) ) ; } setToConsumer ( imageHolder , result ) ; } } else if ( imagesManager . debug ) { Log . w ( TAG , \"set drawable: have no targets in list\" ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main thread [CODESPLIT] private void setToConsumer ( final ImageConsumer consumer , final ImageResult result ) { if ( consumer . currentLoader == this ) { imagesManager . setResultImage ( consumer , result , true ) ; } else { if ( imagesManager . debug ) { Log . d ( TAG , \"Skip set for \" + consumer ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set text view value or set its visibility to { [CODESPLIT] public static void setTextOrHide ( final TextView view , final CharSequence text ) { setTextOrHide ( view , text , View . GONE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set text view value or change its visibility in case of empty value . [CODESPLIT] public static void setTextOrHide ( final TextView view , final CharSequence text , final int hvisibility ) { if ( TextUtils . isEmpty ( text ) ) { view . setVisibility ( hvisibility ) ; } else { view . setText ( text ) ; view . setVisibility ( View . VISIBLE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hide soft keyboard . [CODESPLIT] public static void hideSoftInput ( final View textView ) { try { final InputMethodManager imm = ( InputMethodManager ) textView . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . hideSoftInputFromWindow ( textView . getWindowToken ( ) , 0 ) ; } catch ( final Exception e ) { Log . w ( TAG , \"Ignore exception\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show soft keyboard . [CODESPLIT] public static void showSoftInput ( final View textView ) { try { final InputMethodManager imm = ( InputMethodManager ) textView . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . showSoftInput ( textView , InputMethodManager . SHOW_FORCED ) ; } catch ( final Exception e ) { Log . w ( TAG , \"Ignore exception\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Toggles keyboard visibility . [CODESPLIT] public static void toggleSoftInput ( final View textView ) { try { final InputMethodManager imm = ( InputMethodManager ) textView . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . toggleSoftInputFromWindow ( textView . getWindowToken ( ) , 0 , 0 ) ; } catch ( final Exception e ) { Log . w ( TAG , \"Ignore exception\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts device independent points to actual pixels . [CODESPLIT] public static int pixelsWidth ( final DisplayMetrics displayMetrics , final int dip ) { final float scale = displayMetrics . density ; final float alpha = 0.5f ; return ( int ) ( dip * scale + alpha ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find view by ID . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T extends View > T find ( final View view , final int id ) { final View result = view . findViewById ( id ) ; return ( T ) result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find view by ID . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T extends View > T find ( final Activity activity , final int id ) { final View result = activity . findViewById ( id ) ; return ( T ) result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "cancel the timer if exception is caught - prevents useless stack traces [CODESPLIT] @ Override public void exceptionCaught ( ChannelHandlerContext ctx , ExceptionEvent e ) throws Exception { cancelDirectConnectionTimer ( ) ; Logger . getLogger ( PortUnificationHandler . class . getName ( ) ) . severe ( \"Exception on connection to \" + ctx . getChannel ( ) . getRemoteAddress ( ) + \": \" + e . getCause ( ) . getMessage ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an opaque token representing the current position in the stream . Call { [CODESPLIT] public long savePosition ( int readLimit ) { long offsetLimit = offset + readLimit ; if ( limit < offsetLimit ) { setLimit ( offsetLimit ) ; } return offset ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes sure that the underlying stream can backtrack the full range from { [CODESPLIT] private void setLimit ( long limit ) { try { if ( reset < offset && offset <= this . limit ) { in . reset ( ) ; in . mark ( ( int ) ( limit - reset ) ) ; skip ( reset , offset ) ; } else { reset = offset ; in . mark ( ( int ) ( limit - offset ) ) ; } this . limit = limit ; } catch ( IOException e ) { throw new IllegalStateException ( \"Unable to mark: \" + e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the stream to the position recorded by { [CODESPLIT] public void reset ( long token ) throws IOException { if ( offset > limit || token < reset ) { throw new IOException ( \"Cannot reset\" ) ; } in . reset ( ) ; skip ( reset , token ) ; offset = token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips { [CODESPLIT] private void skip ( long current , long target ) throws IOException { while ( current < target ) { long skipped = in . skip ( target - current ) ; current += skipped ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear the cached entities . [CODESPLIT] public boolean clearCache ( final String url ) { memCache . remove ( url ) ; try { return imagesResponseCache . deleteGetEntry ( url ) ; } catch ( final IOException e ) { Log . w ( TAG , \"Cannot clear disk cache for \" + url , e ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the requested image to the specified view . Called from the GUI thread . [CODESPLIT] public void populateImage ( final View view , final String url ) { final Object tag = view . getTag ( ) ; ImageConsumer consumer = null ; if ( tag == null ) { consumer = createImageConsumer ( view ) ; view . setTag ( consumer ) ; } else { if ( ! ( tag instanceof ImageConsumer ) ) { throw new IllegalStateException ( \"View already has a tag \" + tag + \". Cannot store consumer\" ) ; } consumer = ( ImageConsumer ) tag ; } populateImage ( consumer , url ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancel image loading for a view . [CODESPLIT] public void cancelImageLoading ( final View view ) { checkThread ( ) ; final Object tag = view . getTag ( ) ; if ( tag != null && tag instanceof ImageConsumer ) { cancelImageLoading ( ( ImageConsumer ) tag ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an image holder instance for the defined view . [CODESPLIT] protected ImageConsumer createImageConsumer ( final View view ) { if ( this . consumerFactory == null ) { throw new IllegalStateException ( \"Image consumers factory bean not found in container. Take a look at DefaultBeansManager.edit().images() method in assist package.\" ) ; } return consumerFactory . createConsumer ( view ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It must be executed in the main thread . [CODESPLIT] protected final void setResultImage ( final ImageConsumer consumer , final ImageResult result , final boolean animate ) { decorateResult ( consumer , result ) ; consumer . setImage ( createDrawable ( result . getBitmap ( ) ) , animate ) ; consumer . reset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set preloader . [CODESPLIT] private void setLoadingImage ( final ImageConsumer consumer ) { if ( ! consumer . skipLoadingImage ( ) ) { Drawable d = getLoadingDrawable ( consumer ) ; if ( ! consumer . hasUndefinedSize ( ) || ( d . getIntrinsicWidth ( ) != 0 && d . getIntrinsicHeight ( ) != 0 ) ) { consumer . setLoadingImage ( d ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executed in the main thread . [CODESPLIT] private void startImageLoaderTask ( final ImageConsumer consumer , final ImageRequest request ) { final String key = request . getKey ( ) ; if ( debug ) { Log . d ( TAG , \"Key \" + key ) ; } ImageLoader loader = currentLoads . get ( key ) ; if ( loader != null ) { final boolean added = loader . addTarget ( consumer ) ; if ( ! added ) { loader = null ; } } if ( loader == null ) { if ( debug ) { Log . d ( TAG , \"Start a new task\" ) ; } loader = new ImageLoader ( request , this ) ; if ( ! loader . addTarget ( consumer ) ) { throw new IllegalStateException ( \"Cannot add target to the new loader\" ) ; } currentLoads . put ( key , loader ) ; if ( debug ) { Log . d ( TAG , \"Current loaders count: \" + currentLoads . size ( ) ) ; } final Executor executor = getImageTaskExecutor ( ) ; executor . execute ( loader . future ) ; } else if ( debug ) { Log . d ( TAG , \"Joined to the existing task \" + key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add image to memory cache . [CODESPLIT] protected void memCacheImage ( final String url , final Bitmap bitmap ) { if ( debug ) { Log . d ( TAG , \"Memcache for \" + url ) ; } memCache . putElement ( url , bitmap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the raw type provided by the token an presence of { [CODESPLIT] protected Type getModelType ( final EntityTypeToken modelType ) { final Class < ? > modelClass = modelType . getRawClass ( ) ; // check for wrappers final Model modelAnnotation = modelClass . getAnnotation ( Model . class ) ; if ( modelAnnotation == null ) { return modelType . getType ( ) ; } final Class < ? > wrapper = modelAnnotation . wrapper ( ) ; return wrapper != null && wrapper != Model . class ? wrapper : modelType . getType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recycle the buffer . [CODESPLIT] public void release ( final byte [ ] buffer ) { if ( buffer == null ) { return ; } final int capacity = buffer . length ; if ( capacity == 0 ) { return ; } synchronized ( lock ) { List < Object > bList = buffers . get ( capacity ) ; if ( bList == null ) { bList = new LinkedList < Object > ( ) ; buffers . put ( capacity , bList ) ; } bList . add ( buffer ) ; usedBuffersCount -- ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A good place to set custom request headers . [CODESPLIT] protected void onURLConnectionPrepared ( final Context context , final URLConnection urlConnection ) { if ( contentType != null ) { urlConnection . addRequestProperty ( \"Content-Type\" , contentType ) ; } if ( contentLanguage != null ) { urlConnection . addRequestProperty ( \"Accept-Language\" , contentLanguage ) ; } urlConnection . addRequestProperty ( \"Accept-Encoding\" , IoUtils . ENCODING_GZIP ) ; urlConnection . addRequestProperty ( \"User-Agent\" , buildUserAgent ( context ) ) ; if ( headers != null ) { for ( String name : headers . keySet ( ) ) { urlConnection . addRequestProperty ( name , headers . getString ( name ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build { [CODESPLIT] public URLConnection makeConnection ( final Context context ) throws IOException { ConverterFactory factory = CONVERTER_FACTORIES . get ( operationType ) ; if ( factory == null ) { throw new IllegalArgumentException ( \"Don't know how to convert operation type \" + operationType ) ; } final BaseRequestDescriptionConverter converter = factory . createConverter ( this , context ) ; // create instance\r final URLConnection connection = converter . prepareConnectionInstance ( ) ; // setup headers\r onURLConnectionPrepared ( context , connection ) ; // make a connection\r converter . connect ( connection ) ; // send data, if required\r converter . sendRequest ( connection ) ; return connection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add string parameter . [CODESPLIT] public SimpleRequestBuilder < MT > addParam ( final String name , final String value ) { addSimpleParameter ( name , value ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "XXX on 2 . 3 we get NP exception in case of HTTPs connection and cache [CODESPLIT] private void connectWithWorkaround ( ) throws IOException { if ( Build . VERSION . SDK_INT > Build . VERSION_CODES . GINGERBREAD_MR1 ) { super . connect ( ) ; return ; } URLConnection coreConnection = UrlConnectionWrapper . unwrap ( getCore ( ) ) ; if ( coreConnection instanceof HttpsURLConnection ) { // CHECKSTYLE:OFF try { super . connect ( ) ; } catch ( NullPointerException e ) { // ignore this NP } // CHECKSTYLE:ON } else { super . connect ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate 32 bytes length MD5 digest . [CODESPLIT] public static String getMd5 ( final String text ) { try { final MessageDigest md = MessageDigest . getInstance ( \"MD5\" ) ; final byte [ ] utf8Bytes = text . getBytes ( UTF_8_NAME ) ; md . update ( utf8Bytes , 0 , utf8Bytes . length ) ; final byte [ ] md5hash = md . digest ( ) ; final int radix = 16 ; final int length = 32 ; final StringBuilder result = new StringBuilder ( length ) . append ( new BigInteger ( 1 , md5hash ) . toString ( radix ) ) ; final int zeroBeginLen = length - result . length ( ) ; if ( zeroBeginLen > 0 ) { final char [ ] zeroBegin = new char [ zeroBeginLen ] ; Arrays . fill ( zeroBegin , Character . forDigit ( 0 , radix ) ) ; result . insert ( 0 , zeroBegin ) ; } return result . toString ( ) ; } catch ( final NoSuchAlgorithmException | UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether activity contains a sharing intent previously set with { [CODESPLIT] public boolean checkSharingIntent ( final Activity activity ) { final Intent activityIntent = activity . getIntent ( ) ; if ( activityIntent . hasExtra ( SharingHelper . EXTRA_SHARING ) ) { processSharingIntent ( activityIntent . < Intent > getParcelableExtra ( SharingHelper . EXTRA_SHARING ) ) ; activityIntent . removeExtra ( SharingHelper . EXTRA_SHARING ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * From MultipartEntity [CODESPLIT] private static byte [ ] generateMultipartBoundary ( ) { final Random rand = new Random ( ) ; final int c11 = 11 , c30 = 30 ; final byte [ ] bytes = new byte [ rand . nextInt ( c11 ) + c30 ] ; // a random size from 30 to 40 final byte [ ] chars = getMultipartChars ( ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] = chars [ rand . nextInt ( chars . length ) ] ; } return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the given constant [CODESPLIT] public static String stringFor ( int n ) { switch ( n ) { case CUBLAS_GEMM_DEFAULT : return \"CUBLAS_GEMM_DEFAULT\" ; case CUBLAS_GEMM_ALGO0 : return \"CUBLAS_GEMM_ALGO0\" ; case CUBLAS_GEMM_ALGO1 : return \"CUBLAS_GEMM_ALGO1\" ; case CUBLAS_GEMM_ALGO2 : return \"CUBLAS_GEMM_ALGO2\" ; case CUBLAS_GEMM_ALGO3 : return \"CUBLAS_GEMM_ALGO3\" ; case CUBLAS_GEMM_ALGO4 : return \"CUBLAS_GEMM_ALGO4\" ; case CUBLAS_GEMM_ALGO5 : return \"CUBLAS_GEMM_ALGO5\" ; case CUBLAS_GEMM_ALGO6 : return \"CUBLAS_GEMM_ALGO6\" ; case CUBLAS_GEMM_ALGO7 : return \"CUBLAS_GEMM_ALGO7\" ; case CUBLAS_GEMM_ALGO8 : return \"CUBLAS_GEMM_ALGO8\" ; case CUBLAS_GEMM_ALGO9 : return \"CUBLAS_GEMM_ALGO9\" ; case CUBLAS_GEMM_ALGO10 : return \"CUBLAS_GEMM_ALGO10\" ; case CUBLAS_GEMM_ALGO11 : return \"CUBLAS_GEMM_ALGO11\" ; case CUBLAS_GEMM_ALGO12 : return \"CUBLAS_GEMM_ALGO12\" ; case CUBLAS_GEMM_ALGO13 : return \"CUBLAS_GEMM_ALGO13\" ; case CUBLAS_GEMM_ALGO14 : return \"CUBLAS_GEMM_ALGO14\" ; case CUBLAS_GEMM_ALGO15 : return \"CUBLAS_GEMM_ALGO15\" ; case CUBLAS_GEMM_ALGO16 : return \"CUBLAS_GEMM_ALGO16\" ; case CUBLAS_GEMM_ALGO17 : return \"CUBLAS_GEMM_ALGO17\" ; case CUBLAS_GEMM_ALGO18 : return \"CUBLAS_GEMM_ALGO18\" ; case CUBLAS_GEMM_ALGO19 : return \"CUBLAS_GEMM_ALGO19\" ; case CUBLAS_GEMM_ALGO20 : return \"CUBLAS_GEMM_ALGO20\" ; case CUBLAS_GEMM_ALGO21 : return \"CUBLAS_GEMM_ALGO21\" ; case CUBLAS_GEMM_ALGO22 : return \"CUBLAS_GEMM_ALGO22\" ; case CUBLAS_GEMM_ALGO23 : return \"CUBLAS_GEMM_ALGO23\" ; case CUBLAS_GEMM_DEFAULT_TENSOR_OP : return \"CUBLAS_GEMM_DEFAULT_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO0_TENSOR_OP : return \"CUBLAS_GEMM_ALGO0_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO1_TENSOR_OP : return \"CUBLAS_GEMM_ALGO1_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO2_TENSOR_OP : return \"CUBLAS_GEMM_ALGO2_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO3_TENSOR_OP : return \"CUBLAS_GEMM_ALGO3_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO4_TENSOR_OP : return \"CUBLAS_GEMM_ALGO4_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO5_TENSOR_OP : return \"CUBLAS_GEMM_ALGO5_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO6_TENSOR_OP : return \"CUBLAS_GEMM_ALGO6_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO7_TENSOR_OP : return \"CUBLAS_GEMM_ALGO7_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO8_TENSOR_OP : return \"CUBLAS_GEMM_ALGO8_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO9_TENSOR_OP : return \"CUBLAS_GEMM_ALGO9_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO10_TENSOR_OP : return \"CUBLAS_GEMM_ALGO10_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO11_TENSOR_OP : return \"CUBLAS_GEMM_ALGO11_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO12_TENSOR_OP : return \"CUBLAS_GEMM_ALGO12_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO13_TENSOR_OP : return \"CUBLAS_GEMM_ALGO13_TENSOR_OP\" ; case CUBLAS_GEMM_ALGO14_TENSOR_OP : return \"CUBLAS_GEMM_ALGO14_TENSOR_OP\" ; } return \"INVALID cublasGemmAlgo: \" + n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the String identifying the given cublasStatus [CODESPLIT] public static String stringFor ( int n ) { switch ( n ) { case CUBLAS_STATUS_SUCCESS : return \"CUBLAS_STATUS_SUCCESS\" ; case CUBLAS_STATUS_NOT_INITIALIZED : return \"CUBLAS_STATUS_NOT_INITIALIZED\" ; case CUBLAS_STATUS_ALLOC_FAILED : return \"CUBLAS_STATUS_ALLOC_FAILED\" ; case CUBLAS_STATUS_INVALID_VALUE : return \"CUBLAS_STATUS_INVALID_VALUE\" ; case CUBLAS_STATUS_ARCH_MISMATCH : return \"CUBLAS_STATUS_ARCH_MISMATCH\" ; case CUBLAS_STATUS_MAPPING_ERROR : return \"CUBLAS_STATUS_MAPPING_ERROR\" ; case CUBLAS_STATUS_EXECUTION_FAILED : return \"CUBLAS_STATUS_EXECUTION_FAILED\" ; case CUBLAS_STATUS_INTERNAL_ERROR : return \"CUBLAS_STATUS_INTERNAL_ERROR\" ; case CUBLAS_STATUS_NOT_SUPPORTED : return \"CUBLAS_STATUS_NOT_SUPPORTED\" ; case JCUBLAS_STATUS_INTERNAL_ERROR : return \"JCUBLAS_STATUS_INTERNAL_ERROR\" ; } return \"INVALID cublasStatus: \" + n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the given result is different to cublasStatus . CUBLAS_STATUS_SUCCESS and exceptions have been enabled this method will throw a CudaException with an error message that corresponds to the given result code . Otherwise the given result is simply returned . [CODESPLIT] private static int checkResult ( int result ) { if ( exceptionsEnabled && result != cublasStatus . CUBLAS_STATUS_SUCCESS ) { throw new CudaException ( cublasStatus . stringFor ( result ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus_t cublasSetVector ( int n int elemSize const void * x int incx void * y int incy ) [CODESPLIT] public static int cublasSetVector ( int n , int elemSize , Pointer x , int incx , Pointer devicePtr , int incy ) { return checkResult ( cublasSetVectorNative ( n , elemSize , x , incx , devicePtr , incy ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus_t cublasGetVector ( int n int elemSize const void * x int incx void * y int incy ) [CODESPLIT] public static int cublasGetVector ( int n , int elemSize , Pointer x , int incx , Pointer y , int incy ) { return checkResult ( cublasGetVectorNative ( n , elemSize , x , incx , y , incy ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus_t cublasSetMatrix ( int rows int cols int elemSize const void * A int lda void * B int ldb ) [CODESPLIT] public static int cublasSetMatrix ( int rows , int cols , int elemSize , Pointer A , int lda , Pointer B , int ldb ) { return checkResult ( cublasSetMatrixNative ( rows , cols , elemSize , A , lda , B , ldb ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus_t cublasGetMatrix ( int rows int cols int elemSize const void * A int lda void * B int ldb ) [CODESPLIT] public static int cublasGetMatrix ( int rows , int cols , int elemSize , Pointer A , int lda , Pointer B , int ldb ) { return checkResult ( cublasGetMatrixNative ( rows , cols , elemSize , A , lda , B , ldb ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus cublasSetVectorAsync ( int n int elemSize const void * x int incx void * y int incy cudaStream_t stream ) ; [CODESPLIT] public static int cublasSetVectorAsync ( int n , int elemSize , Pointer hostPtr , int incx , Pointer devicePtr , int incy , cudaStream_t stream ) { return checkResult ( cublasSetVectorAsyncNative ( n , elemSize , hostPtr , incx , devicePtr , incy , stream ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus cublasGetVectorAsync ( int n int elemSize const void * x int incx void * y int incy cudaStream_t stream ) [CODESPLIT] public static int cublasGetVectorAsync ( int n , int elemSize , Pointer devicePtr , int incx , Pointer hostPtr , int incy , cudaStream_t stream ) { return checkResult ( cublasGetVectorAsyncNative ( n , elemSize , devicePtr , incx , hostPtr , incy , stream ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus_t cublasSetMatrixAsync ( int rows int cols int elemSize const void * A int lda void * B int ldb cudaStream_t stream ) [CODESPLIT] public static int cublasSetMatrixAsync ( int rows , int cols , int elemSize , Pointer A , int lda , Pointer B , int ldb , cudaStream_t stream ) { return checkResult ( cublasSetMatrixAsyncNative ( rows , cols , elemSize , A , lda , B , ldb , stream ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasStatus_t cublasGetMatrixAsync ( int rows int cols int elemSize const void * A int lda void * B int ldb cudaStream_t stream ) [CODESPLIT] public static int cublasGetMatrixAsync ( int rows , int cols , int elemSize , Pointer A , int lda , Pointer B , int ldb , cudaStream_t stream ) { return checkResult ( cublasGetMatrixAsyncNative ( rows , cols , elemSize , A , lda , B , ldb , stream ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasSnrm2 ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasSnrm2Native ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDnrm2 ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasDnrm2Native ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasScnrm2 ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasScnrm2Native ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDznrm2 ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasDznrm2Native ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDotEx ( cublasHandle handle , int n , Pointer x , int xType , int incx , Pointer y , int yType , int incy , Pointer result , int resultType , int executionType ) { return checkResult ( cublasDotExNative ( handle , n , x , xType , incx , y , yType , incy , result , resultType , executionType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDdot ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer result ) /** host or device pointer */ { return checkResult ( cublasDdotNative ( handle , n , x , incx , y , incy , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasCdotu ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer result ) /** host or device pointer */ { return checkResult ( cublasCdotuNative ( handle , n , x , incx , y , incy , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasCdotc ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer result ) /** host or device pointer */ { return checkResult ( cublasCdotcNative ( handle , n , x , incx , y , incy , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasZdotu ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer result ) /** host or device pointer */ { return checkResult ( cublasZdotuNative ( handle , n , x , incx , y , incy , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasZdotc ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer result ) /** host or device pointer */ { return checkResult ( cublasZdotcNative ( handle , n , x , incx , y , incy , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasScalEx ( cublasHandle handle , int n , Pointer alpha , /** host or device pointer */ int alphaType , Pointer x , int xType , int incx , int executionType ) { return checkResult ( cublasScalExNative ( handle , n , alpha , alphaType , x , xType , incx , executionType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasIdamax ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasIdamaxNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasIcamax ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasIcamaxNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasIzamax ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasIzamaxNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasIsamin ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasIsaminNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasIdamin ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasIdaminNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasIcamin ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasIcaminNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasIzamin ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasIzaminNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasSasum ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasSasumNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDasum ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasDasumNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasScasum ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasScasumNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDzasum ( cublasHandle handle , int n , Pointer x , int incx , Pointer result ) /** host or device pointer */ { return checkResult ( cublasDzasumNative ( handle , n , x , incx , result ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasSrot ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasSrotNative ( handle , n , x , incx , y , incy , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDrot ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasDrotNative ( handle , n , x , incx , y , incy , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasCrot ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasCrotNative ( handle , n , x , incx , y , incy , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasCsrot ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasCsrotNative ( handle , n , x , incx , y , incy , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasZrot ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasZrotNative ( handle , n , x , incx , y , incy , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasZdrot ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasZdrotNative ( handle , n , x , incx , y , incy , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasSrotg ( cublasHandle handle , Pointer a , /** host or device pointer */ Pointer b , /** host or device pointer */ Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasSrotgNative ( handle , a , b , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDrotg ( cublasHandle handle , Pointer a , /** host or device pointer */ Pointer b , /** host or device pointer */ Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasDrotgNative ( handle , a , b , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasCrotg ( cublasHandle handle , Pointer a , /** host or device pointer */ Pointer b , /** host or device pointer */ Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasCrotgNative ( handle , a , b , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasZrotg ( cublasHandle handle , Pointer a , /** host or device pointer */ Pointer b , /** host or device pointer */ Pointer c , /** host or device pointer */ Pointer s ) /** host or device pointer */ { return checkResult ( cublasZrotgNative ( handle , a , b , c , s ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasSrotm ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer param ) /** host or device pointer */ { return checkResult ( cublasSrotmNative ( handle , n , x , incx , y , incy , param ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDrotm ( cublasHandle handle , int n , Pointer x , int incx , Pointer y , int incy , Pointer param ) /** host or device pointer */ { return checkResult ( cublasDrotmNative ( handle , n , x , incx , y , incy , param ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasSrotmg ( cublasHandle handle , Pointer d1 , /** host or device pointer */ Pointer d2 , /** host or device pointer */ Pointer x1 , /** host or device pointer */ Pointer y1 , /** host or device pointer */ Pointer param ) /** host or device pointer */ { return checkResult ( cublasSrotmgNative ( handle , d1 , d2 , x1 , y1 , param ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasDrotmg ( cublasHandle handle , Pointer d1 , /** host or device pointer */ Pointer d2 , /** host or device pointer */ Pointer x1 , /** host or device pointer */ Pointer y1 , /** host or device pointer */ Pointer param ) /** host or device pointer */ { return checkResult ( cublasDrotmgNative ( handle , d1 , d2 , x1 , y1 , param ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "host or device pointer [CODESPLIT] public static int cublasSgemv ( cublasHandle handle , int trans , int m , int n , Pointer alpha , /** host or device pointer */ Pointer A , int lda , Pointer x , int incx , Pointer beta , /** host or device pointer */ Pointer y , int incy ) { return checkResult ( cublasSgemvNative ( handle , trans , m , n , alpha , A , lda , x , incx , beta , y , incy ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the current CUBLAS status by calling cublasGetErrorNative and store the result as the lastResult . If the obtained result code is not cublasStatus . CUBLAS_STATUS_SUCCESS and exceptions have been enabled an CudaException will be thrown . [CODESPLIT] private static void checkResultBLAS ( ) { if ( exceptionsEnabled ) { lastResult = cublasGetErrorNative ( ) ; if ( lastResult != cublasStatus . CUBLAS_STATUS_SUCCESS ) { throw new CudaException ( cublasStatus . stringFor ( lastResult ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for CUBLAS function . <br / > <br / > cublasStatus cublasAlloc ( int n int elemSize void ** devicePtr ) <br / > <br / > creates an object in GPU memory space capable of holding an array of n elements where each element requires elemSize bytes of storage . If the function call is successful a pointer to the object in GPU memory space is placed in devicePtr . Note that this is a device pointer that cannot be dereferenced in host code . <br / > <br / > Return Values<br / > ------------- <br / > CUBLAS_STATUS_NOT_INITIALIZED if CUBLAS library has not been initialized<br / > CUBLAS_STATUS_INVALID_VALUE if n < = 0 or elemSize < = 0<br / > CUBLAS_STATUS_ALLOC_FAILED if the object could not be allocated due to lack of resources . <br / > CUBLAS_STATUS_SUCCESS if storage was successfully allocated<br / > [CODESPLIT] public static int cublasAlloc ( int n , int elemSize , Pointer ptr ) { return checkResult ( cublasAllocNative ( n , elemSize , ptr ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a float array containing the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasSetVector ( int n , cuComplex x [ ] , int offsetx , int incx , Pointer y , int incy ) { ByteBuffer byteBufferx = ByteBuffer . allocateDirect ( x . length * 4 * 2 ) ; byteBufferx . order ( ByteOrder . nativeOrder ( ) ) ; FloatBuffer floatBufferx = byteBufferx . asFloatBuffer ( ) ; int indexx = offsetx ; for ( int i = 0 ; i < n ; i ++ , indexx += incx ) { floatBufferx . put ( indexx * 2 + 0 , x [ indexx ] . x ) ; floatBufferx . put ( indexx * 2 + 1 , x [ indexx ] . y ) ; } return checkResult ( cublasSetVectorNative ( n , 8 , Pointer . to ( floatBufferx ) . withByteOffset ( offsetx * 4 * 2 ) , incx , y , incy ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a float array that may store the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasGetVector ( int n , Pointer x , int incx , cuComplex y [ ] , int offsety , int incy ) { ByteBuffer byteBuffery = ByteBuffer . allocateDirect ( y . length * 4 * 2 ) ; byteBuffery . order ( ByteOrder . nativeOrder ( ) ) ; FloatBuffer floatBuffery = byteBuffery . asFloatBuffer ( ) ; int status = cublasGetVectorNative ( n , 8 , x , incx , Pointer . to ( floatBuffery ) . withByteOffset ( offsety * 4 * 2 ) , incy ) ; if ( status == cublasStatus . CUBLAS_STATUS_SUCCESS ) { floatBuffery . rewind ( ) ; int indexy = offsety ; for ( int i = 0 ; i < n ; i ++ , indexy += incy ) { y [ indexy ] . x = floatBuffery . get ( indexy * 2 + 0 ) ; y [ indexy ] . y = floatBuffery . get ( indexy * 2 + 1 ) ; } } return checkResult ( status ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a float array containing the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasSetMatrix ( int rows , int cols , cuComplex A [ ] , int offsetA , int lda , Pointer B , int ldb ) { ByteBuffer byteBufferA = ByteBuffer . allocateDirect ( A . length * 4 * 2 ) ; byteBufferA . order ( ByteOrder . nativeOrder ( ) ) ; FloatBuffer floatBufferA = byteBufferA . asFloatBuffer ( ) ; for ( int i = 0 ; i < A . length ; i ++ ) { floatBufferA . put ( A [ i ] . x ) ; floatBufferA . put ( A [ i ] . y ) ; } return checkResult ( cublasSetMatrixNative ( rows , cols , 8 , Pointer . to ( floatBufferA ) . withByteOffset ( offsetA * 4 * 2 ) , lda , B , ldb ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a float array that may store the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasGetMatrix ( int rows , int cols , Pointer A , int lda , cuComplex B [ ] , int offsetB , int ldb ) { ByteBuffer byteBufferB = ByteBuffer . allocateDirect ( B . length * 4 * 2 ) ; byteBufferB . order ( ByteOrder . nativeOrder ( ) ) ; FloatBuffer floatBufferB = byteBufferB . asFloatBuffer ( ) ; int status = cublasGetMatrixNative ( rows , cols , 8 , A , lda , Pointer . to ( floatBufferB ) . withByteOffset ( offsetB * 4 * 2 ) , ldb ) ; if ( status == cublasStatus . CUBLAS_STATUS_SUCCESS ) { floatBufferB . rewind ( ) ; for ( int c = 0 ; c < cols ; c ++ ) { for ( int r = 0 ; r < rows ; r ++ ) { int index = c * ldb + r + offsetB ; B [ index ] . x = floatBufferB . get ( index * 2 + 0 ) ; B [ index ] . y = floatBufferB . get ( index * 2 + 1 ) ; } } } return checkResult ( status ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuDoubleComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a double array containing the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasSetVector ( int n , cuDoubleComplex x [ ] , int offsetx , int incx , Pointer y , int incy ) { ByteBuffer byteBufferx = ByteBuffer . allocateDirect ( x . length * 8 * 2 ) ; byteBufferx . order ( ByteOrder . nativeOrder ( ) ) ; DoubleBuffer doubleBufferx = byteBufferx . asDoubleBuffer ( ) ; int indexx = offsetx ; for ( int i = 0 ; i < n ; i ++ , indexx += incx ) { doubleBufferx . put ( indexx * 2 + 0 , x [ indexx ] . x ) ; doubleBufferx . put ( indexx * 2 + 1 , x [ indexx ] . y ) ; } return checkResult ( cublasSetVectorNative ( n , 16 , Pointer . to ( doubleBufferx ) . withByteOffset ( offsetx * 8 * 2 ) , incx , y , incy ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuDoubleComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a double array that may store the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasGetVector ( int n , Pointer x , int incx , cuDoubleComplex y [ ] , int offsety , int incy ) { ByteBuffer byteBuffery = ByteBuffer . allocateDirect ( y . length * 8 * 2 ) ; byteBuffery . order ( ByteOrder . nativeOrder ( ) ) ; DoubleBuffer doubleBuffery = byteBuffery . asDoubleBuffer ( ) ; int status = cublasGetVectorNative ( n , 16 , x , incx , Pointer . to ( doubleBuffery ) . withByteOffset ( offsety * 8 * 2 ) , incy ) ; if ( status == cublasStatus . CUBLAS_STATUS_SUCCESS ) { doubleBuffery . rewind ( ) ; int indexy = offsety ; for ( int i = 0 ; i < n ; i ++ , indexy += incy ) { y [ indexy ] . x = doubleBuffery . get ( indexy * 2 + 0 ) ; y [ indexy ] . y = doubleBuffery . get ( indexy * 2 + 1 ) ; } } return checkResult ( status ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuDoubleComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a double array containing the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasSetMatrix ( int rows , int cols , cuDoubleComplex A [ ] , int offsetA , int lda , Pointer B , int ldb ) { ByteBuffer byteBufferA = ByteBuffer . allocateDirect ( A . length * 8 * 2 ) ; byteBufferA . order ( ByteOrder . nativeOrder ( ) ) ; DoubleBuffer doubleBufferA = byteBufferA . asDoubleBuffer ( ) ; for ( int i = 0 ; i < A . length ; i ++ ) { doubleBufferA . put ( A [ i ] . x ) ; doubleBufferA . put ( A [ i ] . y ) ; } return checkResult ( cublasSetMatrixNative ( rows , cols , 16 , Pointer . to ( doubleBufferA ) . withByteOffset ( offsetA * 8 * 2 ) , lda , B , ldb ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extended wrapper for arrays of cuDoubleComplex values . Note that this method only exists for convenience and compatibility with native C code . It is much more efficient to provide a Pointer to a double array that may store the complex numbers where each pair of consecutive numbers in the array describes the real - and imaginary part of one complex number . [CODESPLIT] public static int cublasGetMatrix ( int rows , int cols , Pointer A , int lda , cuDoubleComplex B [ ] , int offsetB , int ldb ) { ByteBuffer byteBufferB = ByteBuffer . allocateDirect ( B . length * 8 * 2 ) ; byteBufferB . order ( ByteOrder . nativeOrder ( ) ) ; DoubleBuffer doubleBufferB = byteBufferB . asDoubleBuffer ( ) ; int status = cublasGetMatrixNative ( rows , cols , 16 , A , lda , Pointer . to ( doubleBufferB ) . withByteOffset ( offsetB * 8 * 2 ) , ldb ) ; if ( status == cublasStatus . CUBLAS_STATUS_SUCCESS ) { doubleBufferB . rewind ( ) ; for ( int c = 0 ; c < cols ; c ++ ) { for ( int r = 0 ; r < rows ; r ++ ) { int index = c * ldb + r + offsetB ; B [ index ] . x = doubleBufferB . get ( index * 2 + 0 ) ; B [ index ] . y = doubleBufferB . get ( index * 2 + 1 ) ; } } } return checkResult ( status ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for CUBLAS function . <pre > void cublasSrotm ( int n float * x int incx float * y int incy const float * sparam ) [CODESPLIT] public static void cublasSrotm ( int n , Pointer x , int incx , Pointer y , int incy , float sparam [ ] ) { cublasSrotmNative ( n , x , incx , y , incy , sparam ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for CUBLAS function . <pre > void cublasSrotmg ( float * psd1 float * psd2 float * psx1 const float * psy1 float * sparam ) [CODESPLIT] public static void cublasSrotmg ( float sd1 [ ] , float sd2 [ ] , float sx1 [ ] , float sy1 , float sparam [ ] ) { cublasSrotmgNative ( sd1 , sd2 , sx1 , sy1 , sparam ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for CUBLAS function . <pre > void cublasDrotm ( int n double * x int incx double * y int incy const double * sparam ) [CODESPLIT] public static void cublasDrotm ( int n , Pointer x , int incx , Pointer y , int incy , double sparam [ ] ) { cublasDrotmNative ( n , x , incx , y , incy , sparam ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wrapper for CUBLAS function . <pre > void cublasDrotmg ( double * psd1 double * psd2 double * psx1 const double * psy1 double * sparam ) [CODESPLIT] public static void cublasDrotmg ( double sd1 [ ] , double sd2 [ ] , double sx1 [ ] , double sy1 , double sparam [ ] ) { cublasDrotmgNative ( sd1 , sd2 , sx1 , sy1 , sparam ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int cublasIsamax ( int n const float * x int incx ) [CODESPLIT] public static int cublasIsamax ( int n , Pointer x , int incx ) { int result = cublasIsamaxNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int cublasIsamin ( int n const float * x int incx ) [CODESPLIT] public static int cublasIsamin ( int n , Pointer x , int incx ) { int result = cublasIsaminNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > float cublasSasum ( int n const float * x int incx ) [CODESPLIT] public static float cublasSasum ( int n , Pointer x , int incx ) { float result = cublasSasumNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSaxpy ( int n float alpha const float * x int incx float * y int incy ) [CODESPLIT] public static void cublasSaxpy ( int n , float alpha , Pointer x , int incx , Pointer y , int incy ) { cublasSaxpyNative ( n , alpha , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasScopy ( int n const float * x int incx float * y int incy ) [CODESPLIT] public static void cublasScopy ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasScopyNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > float cublasSdot ( int n const float * x int incx const float * y int incy ) [CODESPLIT] public static float cublasSdot ( int n , Pointer x , int incx , Pointer y , int incy ) { float result = cublasSdotNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > float cublasSnrm2 ( int n const float * x int incx ) [CODESPLIT] public static float cublasSnrm2 ( int n , Pointer x , int incx ) { float result = cublasSnrm2Native ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSrot ( int n float * x int incx float * y int incy float sc float ss ) [CODESPLIT] public static void cublasSrot ( int n , Pointer x , int incx , Pointer y , int incy , float sc , float ss ) { cublasSrotNative ( n , x , incx , y , incy , sc , ss ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSrotg ( float * host_sa float * host_sb float * host_sc float * host_ss ) [CODESPLIT] public static void cublasSrotg ( Pointer host_sa , Pointer host_sb , Pointer host_sc , Pointer host_ss ) { cublasSrotgNative ( host_sa , host_sb , host_sc , host_ss ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void sscal ( int n float alpha float * x int incx ) [CODESPLIT] public static void cublasSscal ( int n , float alpha , Pointer x , int incx ) { cublasSscalNative ( n , alpha , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSswap ( int n float * x int incx float * y int incy ) [CODESPLIT] public static void cublasSswap ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasSswapNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCaxpy ( int n cuComplex alpha const cuComplex * x int incx cuComplex * y int incy ) [CODESPLIT] public static void cublasCaxpy ( int n , cuComplex alpha , Pointer x , int incx , Pointer y , int incy ) { cublasCaxpyNative ( n , alpha , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCcopy ( int n const cuComplex * x int incx cuComplex * y int incy ) [CODESPLIT] public static void cublasCcopy ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasCcopyNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZcopy ( int n const cuDoubleComplex * x int incx cuDoubleComplex * y int incy ) [CODESPLIT] public static void cublasZcopy ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasZcopyNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCscal ( int n cuComplex alpha cuComplex * x int incx ) [CODESPLIT] public static void cublasCscal ( int n , cuComplex alpha , Pointer x , int incx ) { cublasCscalNative ( n , alpha , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCrotg ( cuComplex * host_ca cuComplex cb float * host_sc cuComplex * host_cs ) [CODESPLIT] public static void cublasCrotg ( Pointer host_ca , cuComplex cb , Pointer host_sc , Pointer host_cs ) { cublasCrotgNative ( host_ca , cb , host_sc , host_cs ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCrot ( int n cuComplex * x int incx cuComplex * y int incy float sc cuComplex cs ) [CODESPLIT] public static void cublasCrot ( int n , Pointer x , int incx , Pointer y , int incy , float c , cuComplex s ) { cublasCrotNative ( n , x , incx , y , incy , c , s ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void csrot ( int n cuComplex * x int incx cuCumplex * y int incy float c float s ) [CODESPLIT] public static void cublasCsrot ( int n , Pointer x , int incx , Pointer y , int incy , float c , float s ) { cublasCsrotNative ( n , x , incx , y , incy , c , s ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCsscal ( int n float alpha cuComplex * x int incx ) [CODESPLIT] public static void cublasCsscal ( int n , float alpha , Pointer x , int incx ) { cublasCsscalNative ( n , alpha , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCswap ( int n const cuComplex * x int incx cuComplex * y int incy ) [CODESPLIT] public static void cublasCswap ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasCswapNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZswap ( int n const cuDoubleComplex * x int incx cuDoubleComplex * y int incy ) [CODESPLIT] public static void cublasZswap ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasZswapNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cuComplex cdotu ( int n const cuComplex * x int incx const cuComplex * y int incy ) [CODESPLIT] public static cuComplex cublasCdotu ( int n , Pointer x , int incx , Pointer y , int incy ) { cuComplex result = cublasCdotuNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cuComplex cublasCdotc ( int n const cuComplex * x int incx const cuComplex * y int incy ) [CODESPLIT] public static cuComplex cublasCdotc ( int n , Pointer x , int incx , Pointer y , int incy ) { cuComplex result = cublasCdotcNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int cublasIcamax ( int n const float * x int incx ) [CODESPLIT] public static int cublasIcamax ( int n , Pointer x , int incx ) { int result = cublasIcamaxNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int cublasIcamin ( int n const float * x int incx ) [CODESPLIT] public static int cublasIcamin ( int n , Pointer x , int incx ) { int result = cublasIcaminNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > float cublasScasum ( int n const cuDouble * x int incx ) [CODESPLIT] public static float cublasScasum ( int n , Pointer x , int incx ) { float result = cublasScasumNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > float cublasScnrm2 ( int n const cuComplex * x int incx ) [CODESPLIT] public static float cublasScnrm2 ( int n , Pointer x , int incx ) { float result = cublasScnrm2Native ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZaxpy ( int n cuDoubleComplex alpha const cuDoubleComplex * x int incx cuDoubleComplex * y int incy ) [CODESPLIT] public static void cublasZaxpy ( int n , cuDoubleComplex alpha , Pointer x , int incx , Pointer y , int incy ) { cublasZaxpyNative ( n , alpha , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cuDoubleComplex zdotu ( int n const cuDoubleComplex * x int incx const cuDoubleComplex * y int incy ) [CODESPLIT] public static cuDoubleComplex cublasZdotu ( int n , Pointer x , int incx , Pointer y , int incy ) { cuDoubleComplex result = cublasZdotuNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cuDoubleComplex cublasZdotc ( int n const cuDoubleComplex * x int incx const cuDoubleComplex * y int incy ) [CODESPLIT] public static cuDoubleComplex cublasZdotc ( int n , Pointer x , int incx , Pointer y , int incy ) { cuDoubleComplex result = cublasZdotcNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZscal ( int n cuComplex alpha cuComplex * x int incx ) [CODESPLIT] public static void cublasZscal ( int n , cuDoubleComplex alpha , Pointer x , int incx ) { cublasZscalNative ( n , alpha , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZdscal ( int n double alpha cuDoubleComplex * x int incx ) [CODESPLIT] public static void cublasZdscal ( int n , double alpha , Pointer x , int incx ) { cublasZdscalNative ( n , alpha , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > double cublasDznrm2 ( int n const cuDoubleComplex * x int incx ) [CODESPLIT] public static double cublasDznrm2 ( int n , Pointer x , int incx ) { double result = cublasDznrm2Native ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZrotg ( cuDoubleComplex * host_ca cuDoubleComplex cb double * host_sc double * host_cs ) [CODESPLIT] public static void cublasZrotg ( Pointer host_ca , cuDoubleComplex cb , Pointer host_sc , Pointer host_cs ) { cublasZrotgNative ( host_ca , cb , host_sc , host_cs ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasZrot ( int n cuDoubleComplex * x int incx cuDoubleComplex * y int incy double sc cuDoubleComplex cs ) [CODESPLIT] public static void cublasZrot ( int n , Pointer x , int incx , Pointer y , int incy , double sc , cuDoubleComplex cs ) { cublasZrotNative ( n , x , incx , y , incy , sc , cs ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void zdrot ( int n cuDoubleComplex * x int incx cuCumplex * y int incy double c double s ) [CODESPLIT] public static void cublasZdrot ( int n , Pointer x , int incx , Pointer y , int incy , double c , double s ) { cublasZdrotNative ( n , x , incx , y , incy , c , s ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int cublasIzamax ( int n const double * x int incx ) [CODESPLIT] public static int cublasIzamax ( int n , Pointer x , int incx ) { int result = cublasIzamaxNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int cublasIzamin ( int n const cuDoubleComplex * x int incx ) [CODESPLIT] public static int cublasIzamin ( int n , Pointer x , int incx ) { int result = cublasIzaminNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > double cublasDzasum ( int n const cuDoubleComplex * x int incx ) [CODESPLIT] public static double cublasDzasum ( int n , Pointer x , int incx ) { double result = cublasDzasumNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSgbmv ( char trans int m int n int kl int ku float alpha const float * A int lda const float * x int incx float beta float * y int incy ) [CODESPLIT] public static void cublasSgbmv ( char trans , int m , int n , int kl , int ku , float alpha , Pointer A , int lda , Pointer x , int incx , float beta , Pointer y , int incy ) { cublasSgbmvNative ( trans , m , n , kl , ku , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasSgemv ( char trans int m int n float alpha const float * A int lda const float * x int incx float beta float * y int incy ) [CODESPLIT] public static void cublasSgemv ( char trans , int m , int n , float alpha , Pointer A , int lda , Pointer x , int incx , float beta , Pointer y , int incy ) { cublasSgemvNative ( trans , m , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasSger ( int m int n float alpha const float * x int incx const float * y int incy float * A int lda ) [CODESPLIT] public static void cublasSger ( int m , int n , float alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasSgerNative ( m , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSsbmv ( char uplo int n int k float alpha const float * A int lda const float * x int incx float beta float * y int incy ) [CODESPLIT] public static void cublasSsbmv ( char uplo , int n , int k , float alpha , Pointer A , int lda , Pointer x , int incx , float beta , Pointer y , int incy ) { cublasSsbmvNative ( uplo , n , k , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSspmv ( char uplo int n float alpha const float * AP const float * x int incx float beta float * y int incy ) [CODESPLIT] public static void cublasSspmv ( char uplo , int n , float alpha , Pointer AP , Pointer x , int incx , float beta , Pointer y , int incy ) { cublasSspmvNative ( uplo , n , alpha , AP , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSspr ( char uplo int n float alpha const float * x int incx float * AP ) [CODESPLIT] public static void cublasSspr ( char uplo , int n , float alpha , Pointer x , int incx , Pointer AP ) { cublasSsprNative ( uplo , n , alpha , x , incx , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSspr2 ( char uplo int n float alpha const float * x int incx const float * y int incy float * AP ) [CODESPLIT] public static void cublasSspr2 ( char uplo , int n , float alpha , Pointer x , int incx , Pointer y , int incy , Pointer AP ) { cublasSspr2Native ( uplo , n , alpha , x , incx , y , incy , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSsymv ( char uplo int n float alpha const float * A int lda const float * x int incx float beta float * y int incy ) [CODESPLIT] public static void cublasSsymv ( char uplo , int n , float alpha , Pointer A , int lda , Pointer x , int incx , float beta , Pointer y , int incy ) { cublasSsymvNative ( uplo , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSsyr ( char uplo int n float alpha const float * x int incx float * A int lda ) [CODESPLIT] public static void cublasSsyr ( char uplo , int n , float alpha , Pointer x , int incx , Pointer A , int lda ) { cublasSsyrNative ( uplo , n , alpha , x , incx , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSsyr2 ( char uplo int n float alpha const float * x int incx const float * y int incy float * A int lda ) [CODESPLIT] public static void cublasSsyr2 ( char uplo , int n , float alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasSsyr2Native ( uplo , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStbmv ( char uplo char trans char diag int n int k const float * A int lda float * x int incx ) [CODESPLIT] public static void cublasStbmv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasStbmvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStbsv ( char uplo char trans char diag int n int k const float * A int lda float * X int incx ) [CODESPLIT] public static void cublasStbsv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasStbsvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStpmv ( char uplo char trans char diag int n const float * AP float * x int incx ) ; [CODESPLIT] public static void cublasStpmv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasStpmvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStpsv ( char uplo char trans char diag int n const float * AP float * X int incx ) [CODESPLIT] public static void cublasStpsv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasStpsvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStrmv ( char uplo char trans char diag int n const float * A int lda float * x int incx ) ; [CODESPLIT] public static void cublasStrmv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasStrmvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStrsv ( char uplo char trans char diag int n const float * A int lda float * x int incx ) [CODESPLIT] public static void cublasStrsv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasStrsvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtrmv ( char uplo char trans char diag int n const cuDoubleComplex * A int lda cuDoubleComplex * x int incx ) ; [CODESPLIT] public static void cublasZtrmv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasZtrmvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZgbmv ( char trans int m int n int kl int ku cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * x int incx cuDoubleComplex beta cuDoubleComplex * y int incy ) ; [CODESPLIT] public static void cublasZgbmv ( char trans , int m , int n , int kl , int ku , cuDoubleComplex alpha , Pointer A , int lda , Pointer x , int incx , cuDoubleComplex beta , Pointer y , int incy ) { cublasZgbmvNative ( trans , m , n , kl , ku , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtbmv ( char uplo char trans char diag int n int k const cuDoubleComplex * A int lda cuDoubleComplex * x int incx ) [CODESPLIT] public static void cublasZtbmv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasZtbmvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtbsv ( char uplo char trans char diag int n int k const cuDoubleComplex * A int lda cuDoubleComplex * X int incx ) [CODESPLIT] public static void cublasZtbsv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasZtbsvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZhemv ( char uplo int n cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * x int incx cuDoubleComplex beta cuDoubleComplex * y int incy ) [CODESPLIT] public static void cublasZhemv ( char uplo , int n , cuDoubleComplex alpha , Pointer A , int lda , Pointer x , int incx , cuDoubleComplex beta , Pointer y , int incy ) { cublasZhemvNative ( uplo , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZhpmv ( char uplo int n cuDoubleComplex alpha const cuDoubleComplex * AP const cuDoubleComplex * x int incx cuDoubleComplex beta cuDoubleComplex * y int incy ) [CODESPLIT] public static void cublasZhpmv ( char uplo , int n , cuDoubleComplex alpha , Pointer AP , Pointer x , int incx , cuDoubleComplex beta , Pointer y , int incy ) { cublasZhpmvNative ( uplo , n , alpha , AP , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasZgemv ( char trans int m int n cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * x int incx cuDoubleComplex beta cuDoubleComplex * y int incy ) [CODESPLIT] public static void cublasZgemv ( char trans , int m , int n , cuDoubleComplex alpha , Pointer A , int lda , Pointer x , int incx , cuDoubleComplex beta , Pointer y , int incy ) { cublasZgemvNative ( trans , m , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtpmv ( char uplo char trans char diag int n const cuDoubleComplex * AP cuDoubleComplex * x int incx ) ; [CODESPLIT] public static void cublasZtpmv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasZtpmvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtpsv ( char uplo char trans char diag int n const cuDoubleComplex * AP cuDoubleComplex * X int incx ) [CODESPLIT] public static void cublasZtpsv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasZtpsvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasCgemv ( char trans int m int n cuComplex alpha const cuComplex * A int lda const cuComplex * x int incx cuComplex beta cuComplex * y int incy ) [CODESPLIT] public static void cublasCgemv ( char trans , int m , int n , cuComplex alpha , Pointer A , int lda , Pointer x , int incx , cuComplex beta , Pointer y , int incy ) { cublasCgemvNative ( trans , m , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCgbmv ( char trans int m int n int kl int ku cuComplex alpha const cuComplex * A int lda const cuComplex * x int incx cuComplex beta cuComplex * y int incy ) ; [CODESPLIT] public static void cublasCgbmv ( char trans , int m , int n , int kl , int ku , cuComplex alpha , Pointer A , int lda , Pointer x , int incx , cuComplex beta , Pointer y , int incy ) { cublasCgbmvNative ( trans , m , n , kl , ku , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasChemv ( char uplo int n cuComplex alpha const cuComplex * A int lda const cuComplex * x int incx cuComplex beta cuComplex * y int incy ) [CODESPLIT] public static void cublasChemv ( char uplo , int n , cuComplex alpha , Pointer A , int lda , Pointer x , int incx , cuComplex beta , Pointer y , int incy ) { cublasChemvNative ( uplo , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasChbmv ( char uplo int n int k cuComplex alpha const cuComplex * A int lda const cuComplex * x int incx cuComplex beta cuComplex * y int incy ) [CODESPLIT] public static void cublasChbmv ( char uplo , int n , int k , cuComplex alpha , Pointer A , int lda , Pointer x , int incx , cuComplex beta , Pointer y , int incy ) { cublasChbmvNative ( uplo , n , k , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > [CODESPLIT] public static void cublasCtrmv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasCtrmvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCtbmv ( char uplo char trans char diag int n int k const cuComplex * A int lda cuComplex * x int incx ) [CODESPLIT] public static void cublasCtbmv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasCtbmvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCtpmv ( char uplo char trans char diag int n const cuComplex * AP cuComplex * x int incx ) ; [CODESPLIT] public static void cublasCtpmv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasCtpmvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCtrsv ( char uplo char trans char diag int n const cuComplex * A int lda cuComplex * x int incx ) [CODESPLIT] public static void cublasCtrsv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasCtrsvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCtbsv ( char uplo char trans char diag int n int k const cuComplex * A int lda cuComplex * X int incx ) [CODESPLIT] public static void cublasCtbsv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasCtbsvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCtpsv ( char uplo char trans char diag int n const cuComplex * AP cuComplex * X int incx ) [CODESPLIT] public static void cublasCtpsv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasCtpsvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasCgeru ( int m int n cuComplex alpha const cuComplex * x int incx const cuComplex * y int incy cuComplex * A int lda ) [CODESPLIT] public static void cublasCgeru ( int m , int n , cuComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasCgeruNative ( m , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasCgerc ( int m int n cuComplex alpha const cuComplex * x int incx const cuComplex * y int incy cuComplex * A int lda ) [CODESPLIT] public static void cublasCgerc ( int m , int n , cuComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasCgercNative ( m , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCher ( char uplo int n float alpha const cuComplex * x int incx cuComplex * A int lda ) [CODESPLIT] public static void cublasCher ( char uplo , int n , float alpha , Pointer x , int incx , Pointer A , int lda ) { cublasCherNative ( uplo , n , alpha , x , incx , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasChpr ( char uplo int n float alpha const cuComplex * x int incx cuComplex * AP ) [CODESPLIT] public static void cublasChpr ( char uplo , int n , float alpha , Pointer x , int incx , Pointer AP ) { cublasChprNative ( uplo , n , alpha , x , incx , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasChpr2 ( char uplo int n cuComplex alpha const cuComplex * x int incx const cuComplex * y int incy cuComplex * AP ) [CODESPLIT] public static void cublasChpr2 ( char uplo , int n , cuComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer AP ) { cublasChpr2Native ( uplo , n , alpha , x , incx , y , incy , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCher2 ( char uplo int n cuComplex alpha const cuComplex * x int incx const cuComplex * y int incy cuComplex * A int lda ) [CODESPLIT] public static void cublasCher2 ( char uplo , int n , cuComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasCher2Native ( uplo , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSgemm ( char transa char transb int m int n int k float alpha const float * A int lda const float * B int ldb float beta float * C int ldc ) [CODESPLIT] public static void cublasSgemm ( char transa , char transb , int m , int n , int k , float alpha , Pointer A , int lda , Pointer B , int ldb , float beta , Pointer C , int ldc ) { cublasSgemmNative ( transa , transb , m , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSsymm ( char side char uplo int m int n float alpha const float * A int lda const float * B int ldb float beta float * C int ldc ) ; [CODESPLIT] public static void cublasSsymm ( char side , char uplo , int m , int n , float alpha , Pointer A , int lda , Pointer B , int ldb , float beta , Pointer C , int ldc ) { cublasSsymmNative ( side , uplo , m , n , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSsyrk ( char uplo char trans int n int k float alpha const float * A int lda float beta float * C int ldc ) [CODESPLIT] public static void cublasSsyrk ( char uplo , char trans , int n , int k , float alpha , Pointer A , int lda , float beta , Pointer C , int ldc ) { cublasSsyrkNative ( uplo , trans , n , k , alpha , A , lda , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasSsyr2k ( char uplo char trans int n int k float alpha const float * A int lda const float * B int ldb float beta float * C int ldc ) [CODESPLIT] public static void cublasSsyr2k ( char uplo , char trans , int n , int k , float alpha , Pointer A , int lda , Pointer B , int ldb , float beta , Pointer C , int ldc ) { cublasSsyr2kNative ( uplo , trans , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStrmm ( char side char uplo char transa char diag int m int n float alpha const float * A int lda const float * B int ldb ) [CODESPLIT] public static void cublasStrmm ( char side , char uplo , char transa , char diag , int m , int n , float alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasStrmmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasStrsm ( char side char uplo char transa char diag int m int n float alpha const float * A int lda float * B int ldb ) [CODESPLIT] public static void cublasStrsm ( char side , char uplo , char transa , char diag , int m , int n , float alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasStrsmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCgemm ( char transa char transb int m int n int k cuComplex alpha const cuComplex * A int lda const cuComplex * B int ldb cuComplex beta cuComplex * C int ldc ) [CODESPLIT] public static void cublasCgemm ( char transa , char transb , int m , int n , int k , cuComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuComplex beta , Pointer C , int ldc ) { cublasCgemmNative ( transa , transb , m , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCsymm ( char side char uplo int m int n cuComplex alpha const cuComplex * A int lda const cuComplex * B int ldb cuComplex beta cuComplex * C int ldc ) ; [CODESPLIT] public static void cublasCsymm ( char side , char uplo , int m , int n , cuComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuComplex beta , Pointer C , int ldc ) { cublasCsymmNative ( side , uplo , m , n , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasChemm ( char side char uplo int m int n cuComplex alpha const cuComplex * A int lda const cuComplex * B int ldb cuComplex beta cuComplex * C int ldc ) ; [CODESPLIT] public static void cublasChemm ( char side , char uplo , int m , int n , cuComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuComplex beta , Pointer C , int ldc ) { cublasChemmNative ( side , uplo , m , n , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCsyrk ( char uplo char trans int n int k cuComplex alpha const cuComplex * A int lda cuComplex beta cuComplex * C int ldc ) [CODESPLIT] public static void cublasCsyrk ( char uplo , char trans , int n , int k , cuComplex alpha , Pointer A , int lda , cuComplex beta , Pointer C , int ldc ) { cublasCsyrkNative ( uplo , trans , n , k , alpha , A , lda , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCherk ( char uplo char trans int n int k float alpha const cuComplex * A int lda float beta cuComplex * C int ldc ) [CODESPLIT] public static void cublasCherk ( char uplo , char trans , int n , int k , float alpha , Pointer A , int lda , float beta , Pointer C , int ldc ) { cublasCherkNative ( uplo , trans , n , k , alpha , A , lda , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCsyr2k ( char uplo char trans int n int k cuComplex alpha const cuComplex * A int lda const cuComplex * B int ldb cuComplex beta cuComplex * C int ldc ) [CODESPLIT] public static void cublasCsyr2k ( char uplo , char trans , int n , int k , cuComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuComplex beta , Pointer C , int ldc ) { cublasCsyr2kNative ( uplo , trans , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCher2k ( char uplo char trans int n int k cuComplex alpha const cuComplex * A int lda const cuComplex * B int ldb float beta cuComplex * C int ldc ) [CODESPLIT] public static void cublasCher2k ( char uplo , char trans , int n , int k , cuComplex alpha , Pointer A , int lda , Pointer B , int ldb , float beta , Pointer C , int ldc ) { cublasCher2kNative ( uplo , trans , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCtrmm ( char side char uplo char transa char diag int m int n cuComplex alpha const cuComplex * A int lda const cuComplex * B int ldb ) [CODESPLIT] public static void cublasCtrmm ( char side , char uplo , char transa , char diag , int m , int n , cuComplex alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasCtrmmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasCtrsm ( char side char uplo char transa char diag int m int n cuComplex alpha const cuComplex * A int lda cuComplex * B int ldb ) [CODESPLIT] public static void cublasCtrsm ( char side , char uplo , char transa , char diag , int m , int n , cuComplex alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasCtrsmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > double cublasDasum ( int n const double * x int incx ) [CODESPLIT] public static double cublasDasum ( int n , Pointer x , int incx ) { double result = cublasDasumNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDaxpy ( int n double alpha const double * x int incx double * y int incy ) [CODESPLIT] public static void cublasDaxpy ( int n , double alpha , Pointer x , int incx , Pointer y , int incy ) { cublasDaxpyNative ( n , alpha , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDcopy ( int n const double * x int incx double * y int incy ) [CODESPLIT] public static void cublasDcopy ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasDcopyNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > double cublasDdot ( int n const double * x int incx const double * y int incy ) [CODESPLIT] public static double cublasDdot ( int n , Pointer x , int incx , Pointer y , int incy ) { double result = cublasDdotNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > double dnrm2 ( int n const double * x int incx ) [CODESPLIT] public static double cublasDnrm2 ( int n , Pointer x , int incx ) { double result = cublasDnrm2Native ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDrot ( int n double * x int incx double * y int incy double sc double ss ) [CODESPLIT] public static void cublasDrot ( int n , Pointer x , int incx , Pointer y , int incy , double sc , double ss ) { cublasDrotNative ( n , x , incx , y , incy , sc , ss ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDrotg ( double * host_sa double * host_sb double * host_sc double * host_ss ) [CODESPLIT] public static void cublasDrotg ( Pointer host_sa , Pointer host_sb , Pointer host_sc , Pointer host_ss ) { cublasDrotgNative ( host_sa , host_sb , host_sc , host_ss ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDscal ( int n double alpha double * x int incx ) [CODESPLIT] public static void cublasDscal ( int n , double alpha , Pointer x , int incx ) { cublasDscalNative ( n , alpha , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDswap ( int n double * x int incx double * y int incy ) [CODESPLIT] public static void cublasDswap ( int n , Pointer x , int incx , Pointer y , int incy ) { cublasDswapNative ( n , x , incx , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int idamax ( int n const double * x int incx ) [CODESPLIT] public static int cublasIdamax ( int n , Pointer x , int incx ) { int result = cublasIdamaxNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > int idamin ( int n const double * x int incx ) [CODESPLIT] public static int cublasIdamin ( int n , Pointer x , int incx ) { int result = cublasIdaminNative ( n , x , incx ) ; checkResultBLAS ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasDgemv ( char trans int m int n double alpha const double * A int lda const double * x int incx double beta double * y int incy ) [CODESPLIT] public static void cublasDgemv ( char trans , int m , int n , double alpha , Pointer A , int lda , Pointer x , int incx , double beta , Pointer y , int incy ) { cublasDgemvNative ( trans , m , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasDger ( int m int n double alpha const double * x int incx const double * y int incy double * A int lda ) [CODESPLIT] public static void cublasDger ( int m , int n , double alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasDgerNative ( m , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDsyr ( char uplo int n double alpha const double * x int incx double * A int lda ) [CODESPLIT] public static void cublasDsyr ( char uplo , int n , double alpha , Pointer x , int incx , Pointer A , int lda ) { cublasDsyrNative ( uplo , n , alpha , x , incx , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDsyr2 ( char uplo int n double alpha const double * x int incx const double * y int incy double * A int lda ) [CODESPLIT] public static void cublasDsyr2 ( char uplo , int n , double alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasDsyr2Native ( uplo , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDspr ( char uplo int n double alpha const double * x int incx double * AP ) [CODESPLIT] public static void cublasDspr ( char uplo , int n , double alpha , Pointer x , int incx , Pointer AP ) { cublasDsprNative ( uplo , n , alpha , x , incx , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDspr2 ( char uplo int n double alpha const double * x int incx const double * y int incy double * AP ) [CODESPLIT] public static void cublasDspr2 ( char uplo , int n , double alpha , Pointer x , int incx , Pointer y , int incy , Pointer AP ) { cublasDspr2Native ( uplo , n , alpha , x , incx , y , incy , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtrsv ( char uplo char trans char diag int n const double * A int lda double * x int incx ) [CODESPLIT] public static void cublasDtrsv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasDtrsvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtrmv ( char uplo char trans char diag int n const double * A int lda double * x int incx ) ; [CODESPLIT] public static void cublasDtrmv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasDtrmvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtbmv ( char uplo char trans char diag int n int k const double * A int lda double * x int incx ) [CODESPLIT] public static void cublasDtbmv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasDtbmvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtpmv ( char uplo char trans char diag int n const double * AP double * x int incx ) ; [CODESPLIT] public static void cublasDtpmv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasDtpmvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtpsv ( char uplo char trans char diag int n const double * AP double * X int incx ) [CODESPLIT] public static void cublasDtpsv ( char uplo , char trans , char diag , int n , Pointer AP , Pointer x , int incx ) { cublasDtpsvNative ( uplo , trans , diag , n , AP , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtbsv ( char uplo char trans char diag int n int k const double * A int lda double * X int incx ) [CODESPLIT] public static void cublasDtbsv ( char uplo , char trans , char diag , int n , int k , Pointer A , int lda , Pointer x , int incx ) { cublasDtbsvNative ( uplo , trans , diag , n , k , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDsymv ( char uplo int n double alpha const double * A int lda const double * x int incx double beta double * y int incy ) [CODESPLIT] public static void cublasDsymv ( char uplo , int n , double alpha , Pointer A , int lda , Pointer x , int incx , double beta , Pointer y , int incy ) { cublasDsymvNative ( uplo , n , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDsbmv ( char uplo int n int k double alpha const double * A int lda const double * x int incx double beta double * y int incy ) [CODESPLIT] public static void cublasDsbmv ( char uplo , int n , int k , double alpha , Pointer A , int lda , Pointer x , int incx , double beta , Pointer y , int incy ) { cublasDsbmvNative ( uplo , n , k , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDspmv ( char uplo int n double alpha const double * AP const double * x int incx double beta double * y int incy ) [CODESPLIT] public static void cublasDspmv ( char uplo , int n , double alpha , Pointer AP , Pointer x , int incx , double beta , Pointer y , int incy ) { cublasDspmvNative ( uplo , n , alpha , AP , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtrsm ( char side char uplo char transa char diag int m int n double alpha const double * A int lda double * B int ldb ) [CODESPLIT] public static void cublasDtrsm ( char side , char uplo , char transa , char diag , int m , int n , double alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasDtrsmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtrsm ( char side char uplo char transa char diag int m int n cuDoubleComplex alpha const cuDoubleComplex * A int lda cuDoubleComplex * B int ldb ) [CODESPLIT] public static void cublasZtrsm ( char side , char uplo , char transa , char diag , int m , int n , cuDoubleComplex alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasZtrsmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDtrmm ( char side char uplo char transa char diag int m int n double alpha const double * A int lda const double * B int ldb ) [CODESPLIT] public static void cublasDtrmm ( char side , char uplo , char transa , char diag , int m , int n , double alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasDtrmmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDsymm ( char side char uplo int m int n double alpha const double * A int lda const double * B int ldb double beta double * C int ldc ) ; [CODESPLIT] public static void cublasDsymm ( char side , char uplo , int m , int n , double alpha , Pointer A , int lda , Pointer B , int ldb , double beta , Pointer C , int ldc ) { cublasDsymmNative ( side , uplo , m , n , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZsymm ( char side char uplo int m int n cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * B int ldb cuDoubleComplex beta cuDoubleComplex * C int ldc ) ; [CODESPLIT] public static void cublasZsymm ( char side , char uplo , int m , int n , cuDoubleComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuDoubleComplex beta , Pointer C , int ldc ) { cublasZsymmNative ( side , uplo , m , n , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDsyrk ( char uplo char trans int n int k double alpha const double * A int lda double beta double * C int ldc ) [CODESPLIT] public static void cublasDsyrk ( char uplo , char trans , int n , int k , double alpha , Pointer A , int lda , double beta , Pointer C , int ldc ) { cublasDsyrkNative ( uplo , trans , n , k , alpha , A , lda , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZsyrk ( char uplo char trans int n int k cuDoubleComplex alpha const cuDoubleComplex * A int lda cuDoubleComplex beta cuDoubleComplex * C int ldc ) [CODESPLIT] public static void cublasZsyrk ( char uplo , char trans , int n , int k , cuDoubleComplex alpha , Pointer A , int lda , cuDoubleComplex beta , Pointer C , int ldc ) { cublasZsyrkNative ( uplo , trans , n , k , alpha , A , lda , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZsyr2k ( char uplo char trans int n int k cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * B int ldb cuDoubleComplex beta cuDoubleComplex * C int ldc ) [CODESPLIT] public static void cublasZsyr2k ( char uplo , char trans , int n , int k , cuDoubleComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuDoubleComplex beta , Pointer C , int ldc ) { cublasZsyr2kNative ( uplo , trans , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZher2k ( char uplo char trans int n int k cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * B int ldb double beta cuDoubleComplex * C int ldc ) [CODESPLIT] public static void cublasZher2k ( char uplo , char trans , int n , int k , cuDoubleComplex alpha , Pointer A , int lda , Pointer B , int ldb , double beta , Pointer C , int ldc ) { cublasZher2kNative ( uplo , trans , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZher ( char uplo int n double alpha const cuDoubleComplex * x int incx cuDoubleComplex * A int lda ) [CODESPLIT] public static void cublasZher ( char uplo , int n , double alpha , Pointer x , int incx , Pointer A , int lda ) { cublasZherNative ( uplo , n , alpha , x , incx , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZhpr ( char uplo int n double alpha const cuDoubleComplex * x int incx cuDoubleComplex * AP ) [CODESPLIT] public static void cublasZhpr ( char uplo , int n , double alpha , Pointer x , int incx , Pointer AP ) { cublasZhprNative ( uplo , n , alpha , x , incx , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZhpr2 ( char uplo int n cuDoubleComplex alpha const cuDoubleComplex * x int incx const cuDoubleComplex * y int incy cuDoubleComplex * AP ) [CODESPLIT] public static void cublasZhpr2 ( char uplo , int n , cuDoubleComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer AP ) { cublasZhpr2Native ( uplo , n , alpha , x , incx , y , incy , AP ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZher2 ( char uplo int n cuDoubleComplex alpha const cuDoubleComplex * x int incx const cuDoubleComplex * y int incy cuDoubleComplex * A int lda ) [CODESPLIT] public static void cublasZher2 ( char uplo , int n , cuDoubleComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasZher2Native ( uplo , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasDsyr2k ( char uplo char trans int n int k double alpha const double * A int lda const double * B int ldb double beta double * C int ldc ) [CODESPLIT] public static void cublasDsyr2k ( char uplo , char trans , int n , int k , double alpha , Pointer A , int lda , Pointer B , int ldb , double beta , Pointer C , int ldc ) { cublasDsyr2kNative ( uplo , trans , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZgemm ( char transa char transb int m int n int k cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * B int ldb cuDoubleComplex beta cuDoubleComplex * C int ldc ) [CODESPLIT] public static void cublasZgemm ( char transa , char transb , int m , int n , int k , cuDoubleComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuDoubleComplex beta , Pointer C , int ldc ) { cublasZgemmNative ( transa , transb , m , n , k , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtrmm ( char side char uplo char transa char diag int m int n cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * B int ldb ) [CODESPLIT] public static void cublasZtrmm ( char side , char uplo , char transa , char diag , int m , int n , cuDoubleComplex alpha , Pointer A , int lda , Pointer B , int ldb ) { cublasZtrmmNative ( side , uplo , transa , diag , m , n , alpha , A , lda , B , ldb ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasZgeru ( int m int n cuDoubleComplex alpha const cuDoubleComplex * x int incx const cuDoubleComplex * y int incy cuDoubleComplex * A int lda ) [CODESPLIT] public static void cublasZgeru ( int m , int n , cuDoubleComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasZgeruNative ( m , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > cublasZgerc ( int m int n cuDoubleComplex alpha const cuDoubleComplex * x int incx const cuDoubleComplex * y int incy cuDoubleComplex * A int lda ) [CODESPLIT] public static void cublasZgerc ( int m , int n , cuDoubleComplex alpha , Pointer x , int incx , Pointer y , int incy , Pointer A , int lda ) { cublasZgercNative ( m , n , alpha , x , incx , y , incy , A , lda ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZherk ( char uplo char trans int n int k double alpha const cuDoubleComplex * A int lda double beta cuDoubleComplex * C int ldc ) [CODESPLIT] public static void cublasZherk ( char uplo , char trans , int n , int k , double alpha , Pointer A , int lda , double beta , Pointer C , int ldc ) { cublasZherkNative ( uplo , trans , n , k , alpha , A , lda , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZhemm ( char side char uplo int m int n cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * B int ldb cuDoubleComplex beta cuDoubleComplex * C int ldc ) ; [CODESPLIT] public static void cublasZhemm ( char side , char uplo , int m , int n , cuDoubleComplex alpha , Pointer A , int lda , Pointer B , int ldb , cuDoubleComplex beta , Pointer C , int ldc ) { cublasZhemmNative ( side , uplo , m , n , alpha , A , lda , B , ldb , beta , C , ldc ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZtrsv ( char uplo char trans char diag int n const cuDoubleComplex * A int lda cuDoubleComplex * x int incx ) [CODESPLIT] public static void cublasZtrsv ( char uplo , char trans , char diag , int n , Pointer A , int lda , Pointer x , int incx ) { cublasZtrsvNative ( uplo , trans , diag , n , A , lda , x , incx ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > void cublasZhbmv ( char uplo int n int k cuDoubleComplex alpha const cuDoubleComplex * A int lda const cuDoubleComplex * x int incx cuDoubleComplex beta cuDoubleComplex * y int incy ) [CODESPLIT] public static void cublasZhbmv ( char uplo , int n , int k , cuDoubleComplex alpha , Pointer A , int lda , Pointer x , int incx , cuDoubleComplex beta , Pointer y , int incy ) { cublasZhbmvNative ( uplo , n , k , alpha , A , lda , x , incx , beta , y , incy ) ; checkResultBLAS ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tiek pieņemts ka izsaucošā funkcija nodrošina ka vārds tiešām beidzas ar šo galotni . [CODESPLIT] public String stem ( String word ) throws WrongEndingException { if ( ! word . endsWith ( ending ) ) throw new WrongEndingException ( \"Gļuks - vārds (\" + w rd + \"  nebeidzas ar norādīto galotni (\" + e d ng + \" \" ;   return word . substring ( 0 , word . length ( ) - ending . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returned Lexemes shouldn t be modified to avoid changing recognition of other words! Not cloned due to performance and memory usage concerns . [CODESPLIT] public ArrayList < Lexeme > getEndingLexemes ( String celms ) { return paradigm . getLexemesByStem ( ) . get ( stemID - 1 ) . get ( celms ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add one occurrence of one lexeme . [CODESPLIT] public void addLexeme ( int lexemeId ) { int count = 1 ; if ( lexemeFrequency . get ( lexemeId ) != null ) count = lexemeFrequency . get ( lexemeId ) + 1 ; lexemeFrequency . put ( lexemeId , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add one occurrence of one ending . [CODESPLIT] public void addEnding ( int endingId ) { int count = 1 ; if ( endingFrequency . get ( endingId ) != null ) count = endingFrequency . get ( endingId ) + 1 ; endingFrequency . put ( endingId , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert frequency data in XML format . [CODESPLIT] public void toXML ( Writer stream ) throws IOException { stream . write ( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" ) ; stream . write ( \"<Statistika>\\n\" ) ; stream . write ( \"<Galotņu_biežums\\n\");   for ( Entry < Integer , Integer > tuple : endingFrequency . entrySet ( ) ) { stream . write ( \" Galotne_\" + tuple . getKey ( ) . toString ( ) + \"=\\\"\" + tuple . getValue ( ) . toString ( ) + \"\\\"\" ) ; } stream . write ( \"/>\\n\" ) ; stream . write ( \"<Leksēmu_biežums\\n\");   for ( Entry < Integer , Integer > tuple : lexemeFrequency . entrySet ( ) ) { stream . write ( \" Leksēma_\"+ t uple. g etKey( ) . t oString( ) + \" =\\\"\"+ t uple. g etValue( ) . t oString( ) + \" \\\"\") ;  } stream . write ( \"/>\\n\" ) ; stream . write ( \"</Statistika>\\n\" ) ; stream . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cumulative frequency estimate for given wordform . [CODESPLIT] public double getEstimate ( AttributeValues wordform ) { double estimate = 0.1 ; String endingIdStr = wordform . getValue ( AttributeNames . i_EndingID ) ; int endingId = ( endingIdStr == null ) ? - 1 : Integer . parseInt ( endingIdStr ) ; if ( endingFrequency . get ( endingId ) != null ) estimate += endingFrequency . get ( endingId ) ; String lexemeIdStr = wordform . getValue ( AttributeNames . i_LexemeID ) ; int lexemeId = ( lexemeIdStr == null ) ? - 1 : Integer . parseInt ( lexemeIdStr ) ; if ( lexemeFrequency . get ( lexemeId ) != null ) estimate += lexemeFrequency . get ( lexemeId ) * lexemeWeight ; return estimate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if given char is a whitespace char ( space tab newline ) . [CODESPLIT] public static boolean isSpace ( char c ) { return Character . isWhitespace ( c ) || Character . isISOControl ( c ) || c == ' ' || c == ' ' || c == ' ' || c == ' ' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Tokenizes the string ( sentence? ) and runs morphoanalysis on each word . [CODESPLIT] public static LinkedList < Word > tokenize ( Analyzer morphoAnalyzer , String chunk ) { LinkedList < Word > tokens = new LinkedList < Word > ( ) ; if ( chunk == null ) return tokens ; Trie automats = morphoAnalyzer . automats ; //bug fix - pievienota beigās whitespace\r String str = chunk + \" \" ; //workaround dubultapostrofu izvirtībai\r str = str . replaceAll ( \"''\" , \"\\u200B''\" ) ; // FIXME mēs te mazliet izčakarējam accumulatedWhitespace on Offsetus\r //workaround teikuma beigu saīsinājumiem utt\r str = str . replaceAll ( \"([\\\\p{L}\\\\d])\\\\.(\\\\p{Z})*$\" , \"$1\\u200B.$2\" ) ; // FIXME mēs te mazliet izčakarējam accumulatedWhitespace un offsetus\r //        str = str.replaceAll(\"([\\\\d])\\\\.(\\\\p{Z})*$\", \"$1\\u200B.$2\"); // FIXME mēs te mazliet izčakarējam accumulatedWhitespace un offsetus\r // te tiek ciklā doti visi tekstā esošie vārdi uz morfoanalīzi.\r int progress = 0 ; boolean inApostrophes = false ; Status statuss = Status . IN_SPACE ; StringBuilder accumulatedWhitespace = new StringBuilder ( ) ; int lastGoodEnd = 0 ; boolean canEndInNextStep = false ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { switch ( statuss ) { case IN_SPACE : if ( ! Splitting . isSpace ( str . charAt ( i ) ) ) { if ( str . charAt ( i ) == ' ' ) inApostrophes = true ; automats . reset ( ) ; //atjauno automāta stāvokli\r automats . findNextBranch ( str . charAt ( i ) ) ; //atrod pirmo derīgo zaru\r if ( automats . status ( ) > 0 ) { //pārbauda vai automātā atrada meklēto simbolu\r //ja atrada\r statuss = Status . IN_WORD ; progress = i ; //pārbauda vai ar to var arī virkne beigties\r canEndInNextStep = ( automats . status ( ) == 2 ) ; } else { //ja neatrada, pievieno vienu simbolu un mēģina vēl\r tokens . add ( formToken ( morphoAnalyzer , str , i , i + 1 , accumulatedWhitespace ) ) ; } } else { accumulatedWhitespace . append ( str . charAt ( i ) ) ; } break ; case IN_WORD : //pārbauda vai ir atrastas potenciālās beigas\r if ( canEndInNextStep == true && ( Splitting . isSeparator ( str . charAt ( i ) ) || ! Character . isLetter ( ( i > 0 ? str . charAt ( i - 1 ) : 0 ) ) ) ) { lastGoodEnd = i ; if ( str . charAt ( i ) == ' ' && inApostrophes ) { tokens . add ( formToken ( morphoAnalyzer , str , progress , i , accumulatedWhitespace ) ) ; accumulatedWhitespace = new StringBuilder ( ) ; tokens . add ( formToken ( morphoAnalyzer , str , i , i + 1 , accumulatedWhitespace ) ) ; inApostrophes = false ; statuss = Status . IN_SPACE ; break ; } } canEndInNextStep = false ; //mēģina atrast nākamo simbolu automātā\r if ( automats . findNext ( str . charAt ( i ) ) > 0 ) { //ja atrada \r //pārbauda vai ar to var arī virkne beigties\r if ( automats . status ( ) == 2 ) canEndInNextStep = true ; } else { //ja neatrada, pārbauda vai automāta darbības laikā tika atrasta potenciālā beigu pozīcija\r if ( lastGoodEnd > progress ) { tokens . add ( formToken ( morphoAnalyzer , str , progress , lastGoodEnd , accumulatedWhitespace ) ) ; i = lastGoodEnd - 1 ; statuss = Status . IN_SPACE ; accumulatedWhitespace = new StringBuilder ( ) ; } else { i = progress ; //mēgina atrast nākamo derīgo zaru\r automats . nextBranch ( ) ; automats . findNextBranch ( str . charAt ( i ) ) ; if ( automats . status ( ) > 0 ) { //pārbauda vai atrada meklēto simbolu\r //pārbauda vai ar to var arī virkne beigties\r if ( automats . status ( ) == 2 ) canEndInNextStep = true ; } else { //ja neatrada, pievieno simbolu rezultātam un pēc tam dosies meklēt jauno sākumu\r //vispār šis ir fishy. FIXME\r tokens . add ( formToken ( morphoAnalyzer , str , i , i + 1 , accumulatedWhitespace ) ) ; statuss = Status . IN_SPACE ; accumulatedWhitespace = new StringBuilder ( ) ; } } } break ; } } // for i..\r if ( statuss == Status . IN_WORD ) { tokens . add ( formToken ( morphoAnalyzer , str , progress , str . length ( ) , accumulatedWhitespace ) ) ; } return tokens ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Tokenizes some text ( usually a sentence ) [CODESPLIT] public static LinkedList < Word > tokenize ( Analyzer morphoAnalyzer , String chunk , boolean bruteSplit ) { if ( bruteSplit ) { LinkedList < Word > tokens = new LinkedList < Word > ( ) ; if ( chunk == null ) return tokens ; String [ ] parts_of_string = chunk . trim ( ) . split ( \" \" ) ; for ( String part : parts_of_string ) { if ( part . length ( ) > 0 ) tokens . add ( ( morphoAnalyzer == null ) ? new Word ( part ) : morphoAnalyzer . analyze ( part ) ) ; } return tokens ; } else { return tokenize ( morphoAnalyzer , chunk ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Tokenizes a paragraph and splits it into sentences . [CODESPLIT] public static LinkedList < LinkedList < Word > > tokenizeSentences ( Analyzer morphoAnalyzer , String paragraph , int lengthCap ) { LinkedList < LinkedList < Word >> result = new LinkedList < LinkedList < Word > > ( ) ; List < Word > tokens = Splitting . tokenize ( morphoAnalyzer , paragraph ) ; LinkedList < Word > sentence = new LinkedList < Word > ( ) ; for ( Word word : tokens ) { // Teikumu beigas iekšā tiešajā runā - pievelkam pēdiņu klāt\r if ( sentence . size ( ) == 0 ) { if ( ( word . isRecognized ( ) && word . getBestWordform ( ) . getTag ( ) . equalsIgnoreCase ( \"zq\" ) ) || word . getToken ( ) . equals ( \")\" ) ) { // Pārbaudam vai iepriekšējā teikuma beigās ir punkts\r if ( ! result . isEmpty ( ) && ! result . getLast ( ) . isEmpty ( ) ) { String prevtoken = result . getLast ( ) . getLast ( ) . getToken ( ) ; if ( prevtoken . equals ( \".\" ) || prevtoken . equals ( \"!\" ) || prevtoken . equals ( \"?\" ) || prevtoken . equals ( \"\\\"\" ) ) { result . getLast ( ) . add ( word ) ; continue ; } } } } sentence . add ( word ) ; if ( Splitting . isChunkCloser ( word ) || // does this token look like end of sentence\r ( sentence . size ( ) >= lengthCap - 5 && ( word . hasAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Punctuation ) || word . getToken ( ) . startsWith ( \"<\" ) ) ) || sentence . size ( ) > lengthCap ) { // hard limit\t\t\r result . add ( sentence ) ; sentence = new LinkedList < Word > ( ) ; } } if ( ! sentence . isEmpty ( ) ) result . add ( sentence ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public String getDemo () { return this . getValue ( LocījumuDemo ) ; TODO : apskatīt kur lieto un vai vajag } // [CODESPLIT] public void shortDescription ( PrintWriter stream ) { stream . printf ( \"%s :\\t%s : %s  #%d\\n\" , token , getTag ( ) , getValue ( AttributeNames . i_Lemma ) , lexeme . getID ( ) ) ; //FIXME - nečeko, vai leksēma nav null\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For debugging purposes only . [CODESPLIT] public void longDescription ( PrintStream out ) { out . println ( this . token + \":\" ) ; for ( String s : this . attributes . keySet ( ) ) { out . println ( s + \"\\t\" + attributes . get ( s ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if attribute - value structure has attribute matching given attributeValue and if so then set corresponding position in the tag . [CODESPLIT] private static void verifyAndSetKamolsAttribute ( AttributeValues avs , StringBuilder tag , int index , char tagValue , String attribute , String attributeValue ) { if ( avs . isMatchingStrong ( attribute , attributeValue ) ) tag . setCharAt ( index , tagValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert internal attribute - value structure to SemTi - Kamols tag . [CODESPLIT] public static String toKamolsMarkup ( AttributeValues avs ) { StringBuilder res = toKamolsMarkup ( avs , defaulti ) ; if ( res . length ( ) < 1 ) return res . toString ( ) ; // if (res.charAt(0) == 'v' && res.charAt(1) == '_') res.setCharAt(1, 'm'); PP 2012.12.07 - nezinu kāpēc tas te ir, bet tas čakarē tagošanu (jo tagsvm.... neatbilst nevienam varēt vai būt verbam) // if (res.charAt(0) == 'p' && res.charAt(6) == '_') res.setCharAt(6, 'n');  // if (res.charAt(0) == 'v' && res.charAt(3) != 'p' && res.charAt(10) == '_')\tres.setCharAt(10, 'n'); return res . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert internal attribute - value structure to SemTi - Kamols tag . Usage of default tags given as parameter . No additional defaults used . [CODESPLIT] private static StringBuilder toKamolsMarkup ( AttributeValues avs , boolean defaults ) { StringBuilder tag = new StringBuilder ( ) ; String pos = avs . getValue ( AttributeNames . i_PartOfSpeech ) ; if ( pos == null ) return tag ; if ( pos . equalsIgnoreCase ( AttributeNames . v_Noun ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"ncmsnn\" ) ; else tag . append ( \"n_____\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_NounType , AttributeNames . v_CommonNoun ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_NounType , AttributeNames . v_ProperNoun ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Kopdzimte ) ; //? nav TagSet //Tagset toties ir \"Nepiemīt\" dzimte verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_NumberSpecial , AttributeNames . v_SingulareTantum ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_NumberSpecial , AttributeNames . v_PlurareTantum ) ; //Tagset toties ir \"Nepiemīt\" skaitlis verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Declension , AttributeNames . v_InflexibleGenitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nelokaams ) ; // ? nav TagSet //Tagset toties ir \"Nepiemīt\" locījums verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , \"1\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , \"2\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , \"3\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , \"4\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , \"5\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , \"6\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , AttributeNames . v_Reflexive ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Declension , AttributeNames . v_NA ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Verb ) && ! avs . isMatchingStrong ( AttributeNames . i_Izteiksme , AttributeNames . v_Participle ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"vmni0t1000n\" ) ; //else tag.append(\"vm_________\"); else tag . append ( \"v__________\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_MainVerb ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_PaliigDv ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Modaals ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Faazes ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_IzpausmesVeida ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Buut ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_TiktTapt ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Nebuut ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_No ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_Yes ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Iisteniibas ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Atstaastiijuma ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Veeleejuma ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Vajadziibas ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Paveeles ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Nenoteiksme ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Participle ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Tagadne ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Naakotne ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Pagaatne ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Transitivity , AttributeNames . v_Transitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Transitivity , AttributeNames . v_Intransitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Transitivity , AttributeNames . v_NA ) ; //? Nav tagset verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Konjugaacija , \"1\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Konjugaacija , \"2\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Konjugaacija , \"3\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Konjugaacija , AttributeNames . v_Nekaartns ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Konjugaacija , AttributeNames . v_NA ) ; //? Nav tagset verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Person , \"1\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Person , \"2\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Person , \"3\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Person , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 8 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetKamolsAttribute ( avs , tag , 8 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetKamolsAttribute ( avs , tag , 8 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 9 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Active ) ; verifyAndSetKamolsAttribute ( avs , tag , 9 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Passive ) ; verifyAndSetKamolsAttribute ( avs , tag , 9 , ' ' , AttributeNames . i_Voice , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 10 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_Yes ) ; verifyAndSetKamolsAttribute ( avs , tag , 10 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_No ) ; //verifyAndSetKamolsAttribute(avs,tag,10,'n',AttributeNames.i_Noliegums,null); } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Verb ) && avs . isMatchingStrong ( AttributeNames . i_Izteiksme , AttributeNames . v_Participle ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"vmnpdmsnapn\" ) ; else tag . append ( \"v__p_______\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_MainVerb ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_PaliigDv ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Modaals ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Faazes ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_IzpausmesVeida ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Buut ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_TiktTapt ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Nebuut ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_No ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_Yes ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Iisteniibas ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Atstaastiijuma ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Veeleejuma ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Vajadziibas ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Paveeles ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Nenoteiksme ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Participle ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Lokaamiiba , AttributeNames . v_Lokaams ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Lokaamiiba , AttributeNames . v_DaljeejiLokaams ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Lokaamiiba , AttributeNames . v_Nelokaams ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Gender , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetKamolsAttribute ( avs , tag , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 8 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Active ) ; verifyAndSetKamolsAttribute ( avs , tag , 8 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Passive ) ; verifyAndSetKamolsAttribute ( avs , tag , 8 , ' ' , AttributeNames . i_Voice , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Tagadne ) ; verifyAndSetKamolsAttribute ( avs , tag , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Pagaatne ) ; verifyAndSetKamolsAttribute ( avs , tag , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Naakotne ) ; verifyAndSetKamolsAttribute ( avs , tag , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 10 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Indefinite ) ; verifyAndSetKamolsAttribute ( avs , tag , 10 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Definite ) ; verifyAndSetKamolsAttribute ( avs , tag , 10 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_NA ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Adjective ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"afmsnnp\" ) ; else tag . append ( \"a______\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_AdjectiveType , AttributeNames . v_QualificativeAdjective ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_AdjectiveType , AttributeNames . v_RelativeAdjective ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Indefinite ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Definite ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Positive ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Comparative ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Superlative ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Pronoun ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"pp1msnn\" ) ; else tag . append ( \"p______\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Personu ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Atgriezeniskie ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Piederiibas ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Noraadaamie ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Nenoteiktie ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Jautaajamie ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_AttieksmesVv ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Noteiktie ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Person , \"1\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Person , \"2\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Person , \"3\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Person , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nelokaams ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_No ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_Yes ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Adverb ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"rp_\" ) ; else tag . append ( \"r__\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Relative ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Positive ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Comparative ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Superlative ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Meera ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Veida ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Vietas ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Laika ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Ceelonja ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Preposition ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"sppgn\" ) ; else tag . append ( \"s____\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Novietojums , AttributeNames . v_Pirms ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Novietojums , AttributeNames . v_Peec ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_Genitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_Dative ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_Accusative ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_VietasApstNoziime , AttributeNames . v_Yes ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_VietasApstNoziime , AttributeNames . v_No ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Conjunction ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"ccs\" ) ; else tag . append ( \"c__\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_SaikljaTips , AttributeNames . v_Sakaartojuma ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_SaikljaTips , AttributeNames . v_Pakaartojuma ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Divkaarshs ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Atkaartots ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Numeral ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"mcs_snv\" ) ; else tag . append ( \"m______\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_SkaitljaTips , AttributeNames . v_PamataSv ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_SkaitljaTips , AttributeNames . v_Kaartas ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_SkaitljaTips , AttributeNames . v_Daljskaitlis ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; verifyAndSetKamolsAttribute ( avs , tag , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Savienojums ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetKamolsAttribute ( avs , tag , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetKamolsAttribute ( avs , tag , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetKamolsAttribute ( avs , tag , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_NA ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Ones ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Teens ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Tens ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Hundreds ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Thousands ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Millions ) ; verifyAndSetKamolsAttribute ( avs , tag , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Billions ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Interjection ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"is\" ) ; else tag . append ( \"i_\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Particle ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"qs\" ) ; else tag . append ( \"q_\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Punctuation ) ) { tag . setLength ( 0 ) ; if ( defaults ) tag . append ( \"zc\" ) ; else tag . append ( \"z_\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Komats ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Peedinja ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Punkts ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Iekava ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Domuziime ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Kols ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Cita ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Abbreviation ) ) { tag . setLength ( 0 ) ; tag . append ( \"y\" ) ; } else if ( pos . equalsIgnoreCase ( AttributeNames . v_Residual ) ) { tag . setLength ( 0 ) ; tag . append ( \"xx\" ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Foreign ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Typo ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Number ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Ordinal ) ; verifyAndSetKamolsAttribute ( avs , tag , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_URI ) ; } return tag ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if tag has given value in specified position and if so then set corresponding attribute - value pair in the given attribute - value structure . [CODESPLIT] private static void verifyAndSetAVSAttribute ( String tag , FeatureStructure avs , int index , char tagValue , String attribute , String attributeValue ) { //TODO - šī metode 'silently fails' uz jauniem variantiem/simboliem //marķējumā. Normāli atrisinās tikai šīs klases pāreja uz xml //konfigfaila apstrādi if ( index >= tag . length ( ) ) return ; if ( tag . charAt ( index ) == tagValue ) avs . addAttribute ( attribute , attributeValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove formating from Kamols - style tag . [CODESPLIT] public static String removeKamolsMarkupFormating ( String tag ) { String result = \"\" ; if ( ! tag . contains ( \",\" ) ) return \"x\" ; int depth = 0 ; int commas = 0 ; for ( char c : tag . toCharArray ( ) ) { if ( c == ' ' ) depth ++ ; if ( c == ' ' ) depth -- ; if ( depth == 1 && c == ' ' ) commas ++ ; if ( commas == 2 ) result = result + c ; } result = result . replaceAll ( \"_[A-Z0-9]*\" , \"_\" ) ; result = result . replaceAll ( \"(\\\\[|\\\\]|\\\\,| )\" , \"\" ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert SemTi - Kamols markup tag to internal attribute - value structure . [CODESPLIT] public static AttributeValues fromKamolsMarkup ( String tag ) { AttributeValues attributes = new AttributeValues ( ) ; if ( tag == null || tag . equals ( \"\" ) ) return attributes ; switch ( tag . charAt ( 0 ) ) { case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Noun ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_NounType , AttributeNames . v_CommonNoun ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_NounType , AttributeNames . v_ProperNoun ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Kopdzimte ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_NumberSpecial , AttributeNames . v_SingulareTantum ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_NumberSpecial , AttributeNames . v_PlurareTantum ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , \"1\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , \"2\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , \"3\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , \"4\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , \"5\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , \"6\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , AttributeNames . v_Reflexive ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Declension , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Declension , AttributeNames . v_InflexibleGenitive ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Verb ) ; if ( tag . length ( ) < 4 || tag . charAt ( 3 ) != ' ' ) { // nav divdabis verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_MainVerb ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_PaliigDv ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Modaals ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Faazes ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_IzpausmesVeida ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Buut ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_TiktTapt ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Nebuut ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_No ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_Yes ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Iisteniibas ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Atstaastiijuma ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Veeleejuma ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Vajadziibas ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Paveeles ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Nenoteiksme ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Participle ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Tagadne ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Naakotne ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Pagaatne ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Transitivity , AttributeNames . v_Transitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Transitivity , AttributeNames . v_Intransitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Transitivity , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Konjugaacija , \"1\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Konjugaacija , \"2\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Konjugaacija , \"3\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Konjugaacija , AttributeNames . v_Nekaartns ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Konjugaacija , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Person , \"1\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Person , \"2\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Person , \"3\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Person , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 8 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 8 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 8 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 9 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Active ) ; verifyAndSetAVSAttribute ( tag , attributes , 9 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Passive ) ; verifyAndSetAVSAttribute ( tag , attributes , 9 , ' ' , AttributeNames . i_Voice , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 10 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_No ) ; verifyAndSetAVSAttribute ( tag , attributes , 10 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_Yes ) ; } else { // ir divdabis verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_MainVerb ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_PaliigDv ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Modaals ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Faazes ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_IzpausmesVeida ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Buut ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_TiktTapt ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VerbType , AttributeNames . v_Nebuut ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_No ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Reflexive , AttributeNames . v_Yes ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Iisteniibas ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Atstaastiijuma ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Veeleejuma ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Vajadziibas ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Paveeles ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Nenoteiksme ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Izteiksme , AttributeNames . v_Participle ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Lokaamiiba , AttributeNames . v_Lokaams ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Lokaamiiba , AttributeNames . v_DaljeejiLokaams ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Lokaamiiba , AttributeNames . v_Nelokaams ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Gender , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Case , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 8 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Active ) ; verifyAndSetAVSAttribute ( tag , attributes , 8 , ' ' , AttributeNames . i_Voice , AttributeNames . v_Passive ) ; verifyAndSetAVSAttribute ( tag , attributes , 8 , ' ' , AttributeNames . i_Voice , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Tagadne ) ; verifyAndSetAVSAttribute ( tag , attributes , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Naakotne ) ; verifyAndSetAVSAttribute ( tag , attributes , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_Pagaatne ) ; verifyAndSetAVSAttribute ( tag , attributes , 9 , ' ' , AttributeNames . i_Laiks , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 10 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Indefinite ) ; verifyAndSetAVSAttribute ( tag , attributes , 10 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Definite ) ; verifyAndSetAVSAttribute ( tag , attributes , 10 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_NA ) ; } break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Adjective ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_AdjectiveType , AttributeNames . v_QualificativeAdjective ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_AdjectiveType , AttributeNames . v_RelativeAdjective ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Indefinite ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Definiteness , AttributeNames . v_Definite ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Positive ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Comparative ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Superlative ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Pronoun ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Personu ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Atgriezeniskie ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Piederiibas ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Noraadaamie ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Nenoteiktie ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Jautaajamie ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_AttieksmesVv ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_VvTips , AttributeNames . v_Noteiktie ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Person , \"1\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Person , \"2\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Person , \"3\" ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Person , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nelokaams ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_No ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Noliegums , AttributeNames . v_Yes ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Anafora , AttributeNames . v_Adjektiivu ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Anafora , AttributeNames . v_Substantiivu ) ; verifyAndSetAVSAttribute ( tag , attributes , 7 , ' ' , AttributeNames . i_Anafora , AttributeNames . v_NA ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Adverb ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Positive ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Comparative ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Superlative ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_Relative ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Degree , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Meera ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Veida ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Vietas ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Laika ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_ApstTips , AttributeNames . v_Ceelonja ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Preposition ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Novietojums , AttributeNames . v_Pirms ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Novietojums , AttributeNames . v_Peec ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Number , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_Genitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_Dative ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_Accusative ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Rekcija , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_VietasApstNoziime , AttributeNames . v_Yes ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_VietasApstNoziime , AttributeNames . v_No ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Conjunction ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_SaikljaTips , AttributeNames . v_Sakaartojuma ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_SaikljaTips , AttributeNames . v_Pakaartojuma ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Divkaarshs ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Atkaartots ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Numeral ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_SkaitljaTips , AttributeNames . v_PamataSv ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_SkaitljaTips , AttributeNames . v_Kaartas ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_SkaitljaTips , AttributeNames . v_Daljskaitlis ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; verifyAndSetAVSAttribute ( tag , attributes , 2 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Savienojums ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Masculine ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_Feminine ) ; verifyAndSetAVSAttribute ( tag , attributes , 3 , ' ' , AttributeNames . i_Gender , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Singular ) ; verifyAndSetAVSAttribute ( tag , attributes , 4 , ' ' , AttributeNames . i_Number , AttributeNames . v_Plural ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Nominative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Genitive ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Dative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Accusative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Vocative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_Locative ) ; verifyAndSetAVSAttribute ( tag , attributes , 5 , ' ' , AttributeNames . i_Case , AttributeNames . v_NA ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Ones ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Teens ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Tens ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Hundreds ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Thousands ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Millions ) ; verifyAndSetAVSAttribute ( tag , attributes , 6 , ' ' , AttributeNames . i_Order , AttributeNames . v_Billions ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Interjection ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Particle ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Vienkaarshs ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_Uzbuuve , AttributeNames . v_Salikts ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Residual ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Foreign ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Typo ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Number ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_Ordinal ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_ResidualType , AttributeNames . v_URI ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Abbreviation ) ; break ; case ' ' : attributes . addAttribute ( AttributeNames . i_PartOfSpeech , AttributeNames . v_Punctuation ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Komats ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Peedinja ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Punkts ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Iekava ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Domuziime ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Kols ) ; verifyAndSetAVSAttribute ( tag , attributes , 1 , ' ' , AttributeNames . i_PieturziimesTips , AttributeNames . v_Cita ) ; break ; } return attributes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts Kamols - style markup to Prolog list . [CODESPLIT] public static String charsToPrologList ( String chars ) { StringBuilder sb = new StringBuilder ( chars . length ( ) * 2 + 1 ) ; charsToPrologList ( chars , sb ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts Kamols - style markup to Prolog list . [CODESPLIT] public static void charsToPrologList ( String chars , StringBuilder sb ) { sb . append ( ' ' ) ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { if ( i > 0 ) sb . append ( ' ' ) ; //FIXME - ne īstā vieta kristīnes marķējuma loģikai //FIXME - aizvākt visas anaforas prom. /Lauma if ( ( chars . startsWith ( \"p\" ) && i == 7 ) // elements, kurš ir kā saraksts no viena elem jādod || ( chars . startsWith ( \"s\" ) && i == 4 ) || ( chars . startsWith ( \"m\" ) && i == 6 ) ) sb . append ( \"[\" + chars . charAt ( i ) + \"]\" ) ; else sb . append ( chars . charAt ( i ) ) ; } if ( ( chars . startsWith ( \"p\" ) && chars . length ( ) < 8 ) ) // tagi tagad saīsināti, compatibility ar veco čunkeri sb . append ( \",[0]\" ) ; sb . append ( ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts Word object to Prolog format necessary for chunker ( A - table record ) . [CODESPLIT] public static String wordToChunkerFormat ( Word word , boolean toolgenerated ) { if ( ! word . isRecognized ( ) ) return ( \"[]\" ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( ' ' ) ; if ( word . getCorrectWordform ( ) != null ) { wordformToChunkerFormat ( word . getToken ( ) , toolgenerated , sb , word . getCorrectWordform ( ) ) ; } else for ( Wordform vf : word . wordforms ) { if ( sb . length ( ) > 1 ) sb . append ( ' ' ) ; wordformToChunkerFormat ( word . getToken ( ) , toolgenerated , sb , vf ) ; } sb . append ( ' ' ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform retrieval of metrics from AppDynamics using specified parameters . [CODESPLIT] public List < MetricData > get ( ) throws RequestException , UnauthorizedException { HttpResponse < String > response ; try { response = Unirest . get ( this . appdURL + \"/controller/rest/applications/\" + appName + \"/metric-data\" ) . header ( \"accept\" , \"application/json\" ) . basicAuth ( this . appdUsername , this . appdPassword ) . queryString ( getQueryString ( ) ) . queryString ( \"output\" , \"json\" ) . asString ( ) ; } catch ( UnirestException e ) { throw new RequestException ( \"Something was wrong with sending request.\" , e ) ; } if ( response == null ) { throw new RequestException ( \"Response is empty.\" ) ; } switch ( response . getStatus ( ) ) { case 200 : { return process ( new JsonNode ( response . getBody ( ) ) ) ; } case 401 : { throw new UnauthorizedException ( \"Authentication failed\" ) ; } default : { throw new RequestException ( \"Unhandled response code \" + response . getStatus ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate querystring for the request . [CODESPLIT] protected Map < String , Object > getQueryString ( ) { Map < String , Object > qs = new HashMap <> ( ) ; if ( timeParams != null ) { qs . put ( \"time-range-type\" , timeParams . type ) ; if ( timeParams . duration > 0 ) { qs . put ( \"duration-in-mins\" , timeParams . duration ) ; } if ( timeParams . startTime > 0 ) { qs . put ( \"start-time\" , timeParams . startTime ) ; } if ( timeParams . endTime > 0 ) { qs . put ( \"end-time\" , timeParams . endTime ) ; } } qs . put ( \"rollup\" , false ) ; if ( metricPath != null ) { qs . put ( \"metric-path\" , metricPath ) ; } return qs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the JSON response from the request . [CODESPLIT] protected List < MetricData > process ( JsonNode node ) { JSONArray dataArray = node . getArray ( ) ; List < MetricData > list = new LinkedList <> ( ) ; for ( int i = 0 ; i < dataArray . length ( ) ; i ++ ) { JSONObject data = dataArray . getJSONObject ( i ) ; MetricData metricData = new MetricData ( data . getString ( \"frequency\" ) , data . getLong ( \"metricId\" ) , data . getString ( \"metricName\" ) , data . getString ( \"metricPath\" ) ) ; list . add ( metricData ) ; JSONArray valueArray = data . getJSONArray ( \"metricValues\" ) ; for ( int j = 0 ; j < valueArray . length ( ) ; j ++ ) { JSONObject value = valueArray . getJSONObject ( j ) ; metricData . metricValues . add ( new MetricValue ( value . getLong ( \"count\" ) , value . getLong ( \"value\" ) , value . getLong ( \"max\" ) , value . getLong ( \"min\" ) , value . getLong ( \"sum\" ) , value . getLong ( \"startTimeInMillis\" ) ) ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse JSON String as configurations that the task should query from AppDynamics . [CODESPLIT] public static List < AppInfo > parseInfo ( String jsonString ) throws IOException { ObjectMapper mapper = new ObjectMapper ( ) ; return mapper . readValue ( jsonString , new TypeReference < List < AppInfo > > ( ) { } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process { @link MetricTimeSeries } and { @link MetricValue } filtering out data point earlier or equal to timestamp that was marked as already sent . [CODESPLIT] public List < SignalFxProtocolBuffers . DataPoint > process ( MetricTimeSeries mts , List < MetricValue > metricValues ) { Long lastTimestamp = mtsToLastTimestamp . get ( mts ) ; Long latestTimestamp = lastTimestamp ; List < SignalFxProtocolBuffers . DataPoint > dataPoints = new LinkedList <> ( ) ; SignalFxProtocolBuffers . DataPoint . Builder dataPointBuilder = SignalFxProtocolBuffers . DataPoint . newBuilder ( ) . setMetric ( mts . metricName ) ; if ( mts . dimensions != null ) { for ( Map . Entry < String , String > entry : mts . dimensions . entrySet ( ) ) { dataPointBuilder . addDimensions ( SignalFxProtocolBuffers . Dimension . newBuilder ( ) . setKey ( entry . getKey ( ) ) . setValue ( entry . getValue ( ) ) ) ; } } for ( MetricValue metricValue : metricValues ) { if ( lastTimestamp == null || metricValue . startTimeInMillis > lastTimestamp ) { SignalFxProtocolBuffers . DataPoint dataPoint = dataPointBuilder . setTimestamp ( metricValue . startTimeInMillis ) . setValue ( SignalFxProtocolBuffers . Datum . newBuilder ( ) . setIntValue ( metricValue . value ) ) . build ( ) ; dataPoints . add ( dataPoint ) ; latestTimestamp = lastTimestamp == null ? metricValue . startTimeInMillis : Math . max ( metricValue . startTimeInMillis , latestTimestamp ) ; } } if ( lastTimestamp == null || latestTimestamp > lastTimestamp ) { mtsToLastTimestamp . put ( mts , latestTimestamp ) ; } return dataPoints ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve configurations by looking up in property param first then environment variable . [CODESPLIT] public static ConnectionConfig getConnectionConfig ( ) { boolean isValid = true ; String appdUsername = getPropertyOrEnv ( \"com.signalfx.appd.username\" , \"APPD_USERNAME\" ) ; if ( StringUtils . isEmpty ( appdUsername ) ) { log . error ( \"AppDynamics username not specified.\" ) ; isValid = false ; } String appdPassword = getPropertyOrEnv ( \"com.signalfx.appd.password\" , \"APPD_PASSWORD\" ) ; if ( StringUtils . isEmpty ( appdPassword ) ) { log . error ( \"AppDynamics password not specified.\" ) ; isValid = false ; } String appdURL = getPropertyOrEnv ( \"com.signalfx.appd.host\" , \"APPD_HOST\" ) ; if ( StringUtils . isEmpty ( appdURL ) ) { log . error ( \"AppDynamics host not specified.\" ) ; isValid = false ; } String fxToken = getPropertyOrEnv ( \"com.signalfx.api.token\" , \"SIGNALFX_TOKEN\" ) ; if ( StringUtils . isEmpty ( fxToken ) ) { log . error ( \"SignalFx token not specified.\" ) ; isValid = false ; } if ( isValid ) { return new ConnectionConfig ( appdUsername , appdPassword , appdURL , fxToken ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform reading and reporting of AppDynamics metrics to SignalFx [CODESPLIT] public void perform ( List < AppInfo > apps , MetricDataRequest . TimeParams timeParams ) { List < SignalFxProtocolBuffers . DataPoint > dataPoints = new LinkedList <> ( ) ; for ( AppInfo app : apps ) { dataRequest . setAppName ( app . name ) ; for ( MetricInfo metricInfo : app . metrics ) { dataRequest . setTimeParams ( timeParams ) ; dataRequest . setMetricPath ( metricInfo . metricPathQuery ) ; List < MetricData > metricDataList ; try { metricDataList = dataRequest . get ( ) ; } catch ( RequestException e ) { // too bad log . error ( \"Metric query failure for \\\"{}\\\"\" , metricInfo . metricPathQuery ) ; counterAppDRequestFailure . inc ( ) ; continue ; } catch ( UnauthorizedException e ) { log . error ( \"AppDynamics authentication failed\" ) ; return ; } if ( metricDataList != null && metricDataList . size ( ) > 0 ) { for ( MetricData metricData : metricDataList ) { MetricTimeSeries mts = metricInfo . getMetricTimeSeries ( metricData . metricPath ) ; List < SignalFxProtocolBuffers . DataPoint > mtsDataPoints = processor . process ( mts , metricData . metricValues ) ; dataPoints . addAll ( mtsDataPoints ) ; if ( ! mtsDataPoints . isEmpty ( ) ) { counterMtsReported . inc ( ) ; } else { counterMtsEmpty . inc ( ) ; } } } else { // no metrics found, something is wrong with selection log . warn ( \"No metric found for query \\\"{}\\\"\" , metricInfo . metricPathQuery ) ; } } } if ( ! dataPoints . isEmpty ( ) ) { try { reporter . report ( dataPoints ) ; counterDataPointsReported . inc ( dataPoints . size ( ) ) ; } catch ( Reporter . ReportException e ) { log . error ( \"There were errors reporting metric\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link MetricTimeSeries } for a given metric path . It will use the given metric path as dimensions mapping and add extra dimensions as specified in the MetricInfo . [CODESPLIT] public MetricTimeSeries getMetricTimeSeries ( String actualMetricPath ) { Map < String , String > actualDimensions = new HashMap <> ( ) ; actualDimensions . putAll ( dimensions ) ; String [ ] path = actualMetricPath . split ( \"\\\\|\" ) ; for ( int i = 0 ; i < dimensionsPath . length ; i ++ ) { if ( \"-\" . equals ( dimensionsPath [ i ] ) ) { continue ; } actualDimensions . put ( dimensionsPath [ i ] , path [ i ] ) ; } return new MetricTimeSeries ( path [ path . length - 1 ] , actualDimensions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a reader builder for com . helger . genericode . v04 . CodeListDocument . [CODESPLIT] @ Nonnull public static GenericodeReader < com . helger . genericode . v04 . CodeListDocument > gc04CodeList ( ) { return new GenericodeReader <> ( EGenericodeDocumentType . GC04_CODE_LIST , com . helger . genericode . v04 . CodeListDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a reader builder for com . helger . genericode . v04 . CodeListSetDocument . [CODESPLIT] @ Nonnull public static GenericodeReader < com . helger . genericode . v04 . CodeListSetDocument > gc04CodeListSet ( ) { return new GenericodeReader <> ( EGenericodeDocumentType . GC04_CODE_LIST_SET , com . helger . genericode . v04 . CodeListSetDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a reader builder for com . helger . genericode . v04 . ColumnSetDocument . [CODESPLIT] @ Nonnull public static GenericodeReader < com . helger . genericode . v04 . ColumnSetDocument > gc04ColumnSet ( ) { return new GenericodeReader <> ( EGenericodeDocumentType . GC04_COLUMN_SET , com . helger . genericode . v04 . ColumnSetDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a reader builder for com . helger . genericode . v10 . CodeListDocument . [CODESPLIT] @ Nonnull public static GenericodeReader < com . helger . genericode . v10 . CodeListDocument > gc10CodeList ( ) { return new GenericodeReader <> ( EGenericodeDocumentType . GC10_CODE_LIST , com . helger . genericode . v10 . CodeListDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a reader builder for com . helger . genericode . v10 . CodeListSetDocument . [CODESPLIT] @ Nonnull public static GenericodeReader < com . helger . genericode . v10 . CodeListSetDocument > gc10CodeListSet ( ) { return new GenericodeReader <> ( EGenericodeDocumentType . GC10_CODE_LIST_SET , com . helger . genericode . v10 . CodeListSetDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a reader builder for com . helger . genericode . v10 . ColumnSetDocument . [CODESPLIT] @ Nonnull public static GenericodeReader < com . helger . genericode . v10 . ColumnSetDocument > gc10ColumnSet ( ) { return new GenericodeReader <> ( EGenericodeDocumentType . GC10_COLUMN_SET , com . helger . genericode . v10 . ColumnSetDocument . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the ID of the passed column element . [CODESPLIT] @ Nonnull public static String getColumnElementID ( @ Nonnull final Object aColumnElement ) { if ( aColumnElement instanceof ColumnRef ) return ( ( ColumnRef ) aColumnElement ) . getId ( ) ; if ( aColumnElement instanceof Column ) return ( ( Column ) aColumnElement ) . getId ( ) ; if ( aColumnElement instanceof Key ) { final List < KeyColumnRef > aKeyColumnRefs = ( ( Key ) aColumnElement ) . getColumnRef ( ) ; final KeyColumnRef aKeyColumnRef = CollectionHelper . getFirstElement ( aKeyColumnRefs ) ; if ( aKeyColumnRef == null ) throw new IllegalArgumentException ( \"Key contains not KeyColumnRef!!\" ) ; final Object aRef = aKeyColumnRef . getRef ( ) ; if ( aRef instanceof Column ) return ( ( Column ) aRef ) . getId ( ) ; throw new IllegalArgumentException ( \"Unsupported referenced object: \" + aRef + \" - \" + ClassHelper . getSafeClassName ( aRef ) ) ; } throw new IllegalArgumentException ( \"Illegal column element: \" + aColumnElement + \" - \" + ClassHelper . getSafeClassName ( aColumnElement ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of a column identified by an ID within a specified row . This method only handles simple values . [CODESPLIT] @ Nullable public static String getRowValue ( @ Nonnull final Row aRow , @ Nonnull final String sColumnID ) { for ( final Value aValue : aRow . getValue ( ) ) { final String sID = getColumnElementID ( aValue . getColumnRef ( ) ) ; if ( sID . equals ( sColumnID ) ) { final SimpleValue aSimpleValue = aValue . getSimpleValue ( ) ; return aSimpleValue != null ? aSimpleValue . getValue ( ) : null ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all contained columns [CODESPLIT] @ Nonnull @ ReturnsMutableCopy public static ICommonsList < Column > getAllColumns ( @ Nonnull final ColumnSet aColumnSet ) { final ICommonsList < Column > ret = new CommonsArrayList <> ( ) ; getAllColumns ( aColumnSet , ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all contained columns [CODESPLIT] public static void getAllColumns ( @ Nonnull final ColumnSet aColumnSet , @ Nonnull final Collection < Column > aTarget ) { CollectionHelper . findAll ( aColumnSet . getColumnChoice ( ) , o -> o instanceof Column , o -> aTarget . add ( ( Column ) o ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the IDs of all contained columns [CODESPLIT] @ Nonnull @ ReturnsMutableCopy public static ICommonsList < String > getAllColumnIDs ( @ Nonnull final ColumnSet aColumnSet ) { final ICommonsList < String > ret = new CommonsArrayList <> ( ) ; getAllColumnIDs ( aColumnSet , ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the IDs of all contained columns [CODESPLIT] public static void getAllColumnIDs ( @ Nonnull final ColumnSet aColumnSet , @ Nonnull final Collection < String > aTarget ) { CollectionHelper . findAll ( aColumnSet . getColumnChoice ( ) , o -> o instanceof Column , o -> aTarget . add ( ( ( Column ) o ) . getId ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the column with the specified ID . [CODESPLIT] @ Nullable public static Column getColumnOfID ( @ Nonnull final ColumnSet aColumnSet , @ Nullable final String sID ) { if ( sID != null ) for ( final Column aColumn : getAllColumns ( aColumnSet ) ) if ( aColumn . getId ( ) . equals ( sID ) ) return aColumn ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all contained keys [CODESPLIT] @ Nonnull @ ReturnsMutableCopy public static ICommonsList < Key > getAllKeys ( @ Nonnull final ColumnSet aColumnSet ) { final ICommonsList < Key > ret = new CommonsArrayList <> ( ) ; getAllKeys ( aColumnSet , ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all contained keys [CODESPLIT] public static void getAllKeys ( @ Nonnull final ColumnSet aColumnSet , @ Nonnull final Collection < Key > aTarget ) { CollectionHelper . findAll ( aColumnSet . getKeyChoice ( ) , o -> o instanceof Key , o -> aTarget . add ( ( Key ) o ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the IDs of all contained keys [CODESPLIT] public static void getAllKeyIDs ( @ Nonnull final ColumnSet aColumnSet , @ Nonnull final Collection < String > aTarget ) { CollectionHelper . findAll ( aColumnSet . getKeyChoice ( ) , o -> o instanceof Key , o -> aTarget . add ( ( ( Key ) o ) . getId ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the key with the specified ID . [CODESPLIT] @ Nullable public static Key getKeyOfID ( @ Nonnull final ColumnSet aColumnSet , @ Nullable final String sID ) { if ( sID != null ) for ( final Key aKey : getAllKeys ( aColumnSet ) ) if ( aKey . getId ( ) . equals ( sID ) ) return aKey ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the passed column ID is a key column in the specified column set [CODESPLIT] public static boolean isKeyColumn ( @ Nonnull final ColumnSet aColumnSet , @ Nullable final String sColumnID ) { if ( sColumnID != null ) for ( final Key aKey : getAllKeys ( aColumnSet ) ) for ( final KeyColumnRef aColumnRef : aKey . getColumnRef ( ) ) if ( aColumnRef . getRef ( ) instanceof Column ) if ( ( ( Column ) aColumnRef . getRef ( ) ) . getId ( ) . equals ( sColumnID ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link ShortName } object [CODESPLIT] @ Nonnull public static ShortName createShortName ( @ Nullable final String sValue ) { final ShortName aShortName = s_aFactory . createShortName ( ) ; aShortName . setValue ( sValue ) ; return aShortName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link LongName } object [CODESPLIT] @ Nonnull public static LongName createLongName ( @ Nullable final String sValue ) { final LongName aLongName = s_aFactory . createLongName ( ) ; aLongName . setValue ( sValue ) ; return aLongName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link SimpleValue } object [CODESPLIT] @ Nonnull public static SimpleValue createSimpleValue ( @ Nullable final String sValue ) { final SimpleValue aSimpleValue = s_aFactory . createSimpleValue ( ) ; aSimpleValue . setValue ( sValue ) ; return aSimpleValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link KeyColumnRef } object [CODESPLIT] @ Nonnull public static KeyColumnRef createKeyColumnRef ( @ Nullable final Column aColumn ) { final KeyColumnRef aColumnRef = s_aFactory . createKeyColumnRef ( ) ; // Important: reference the object itself and not just the ID!!! aColumnRef . setRef ( aColumn ) ; return aColumnRef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new column to be added to a column set [CODESPLIT] @ Nonnull public static Column createColumn ( @ Nonnull @ Nonempty final String sColumnID , @ Nonnull final UseType eUseType , @ Nonnull @ Nonempty final String sShortName , @ Nullable final String sLongName , @ Nonnull @ Nonempty final String sDataType ) { ValueEnforcer . notEmpty ( sColumnID , \"ColumnID\" ) ; ValueEnforcer . notNull ( eUseType , \"useType\" ) ; ValueEnforcer . notEmpty ( sShortName , \"ShortName\" ) ; ValueEnforcer . notEmpty ( sDataType , \"DataType\" ) ; final Column aColumn = s_aFactory . createColumn ( ) ; aColumn . setId ( sColumnID ) ; aColumn . setUse ( eUseType ) ; aColumn . setShortName ( createShortName ( sShortName ) ) ; if ( StringHelper . hasText ( sLongName ) ) aColumn . getLongName ( ) . add ( createLongName ( sLongName ) ) ; final Data aData = s_aFactory . createData ( ) ; aData . setType ( sDataType ) ; aColumn . setData ( aData ) ; return aColumn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new key to be added to a column set [CODESPLIT] @ Nonnull public static Key createKey ( @ Nonnull @ Nonempty final String sColumnID , @ Nonnull @ Nonempty final String sShortName , @ Nullable final String sLongName , @ Nonnull final Column aColumn ) { ValueEnforcer . notEmpty ( sColumnID , \"ColumnID\" ) ; ValueEnforcer . notEmpty ( sShortName , \"ShortName\" ) ; ValueEnforcer . notNull ( aColumn , \"Column\" ) ; final Key aKey = s_aFactory . createKey ( ) ; aKey . setId ( sColumnID ) ; aKey . setShortName ( createShortName ( sShortName ) ) ; if ( StringHelper . hasText ( sLongName ) ) aKey . getLongName ( ) . add ( createLongName ( sLongName ) ) ; aKey . getColumnRef ( ) . add ( createKeyColumnRef ( aColumn ) ) ; return aKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the number of lines to skip before the header row starts [CODESPLIT] @ Nonnull public ExcelReadOptions < USE_TYPE > setLinesToSkip ( @ Nonnegative final int nLinesToSkip ) { ValueEnforcer . isGE0 ( nLinesToSkip , \"LinesToSkip\" ) ; m_nLinesToSkip = nLinesToSkip ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a single column definition . [CODESPLIT] @ Nonnull public ExcelReadOptions < USE_TYPE > addColumn ( @ Nonnegative final int nIndex , @ Nonnull @ Nonempty final String sColumnID , @ Nonnull final USE_TYPE eUseType , @ Nonnull @ Nonempty final String sDataType , final boolean bKeyColumn ) { ValueEnforcer . isGE0 ( nIndex , \"Index\" ) ; final Integer aIndex = Integer . valueOf ( nIndex ) ; if ( m_aColumns . containsKey ( aIndex ) ) throw new IllegalArgumentException ( \"The column at index \" + nIndex + \" is already mapped!\" ) ; m_aColumns . put ( aIndex , new ExcelReadColumn <> ( nIndex , sColumnID , eUseType , sDataType , bKeyColumn ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a writer builder for com . helger . genericode . v04 . CodeListDocument . [CODESPLIT] @ Nonnull public static GenericodeWriter < com . helger . genericode . v04 . CodeListDocument > gc04CodeList ( ) { return new GenericodeWriter <> ( EGenericodeDocumentType . GC04_CODE_LIST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a writer builder for com . helger . genericode . v04 . CodeListSetDocument . [CODESPLIT] @ Nonnull public static GenericodeWriter < com . helger . genericode . v04 . CodeListSetDocument > gc04CodeListSet ( ) { return new GenericodeWriter <> ( EGenericodeDocumentType . GC04_CODE_LIST_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a writer builder for com . helger . genericode . v04 . ColumnSetDocument . [CODESPLIT] @ Nonnull public static GenericodeWriter < com . helger . genericode . v04 . ColumnSetDocument > gc04ColumnSet ( ) { return new GenericodeWriter <> ( EGenericodeDocumentType . GC04_COLUMN_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a writer builder for com . helger . genericode . v10 . CodeListDocument . [CODESPLIT] @ Nonnull public static GenericodeWriter < com . helger . genericode . v10 . CodeListDocument > gc10CodeList ( ) { return new GenericodeWriter <> ( EGenericodeDocumentType . GC10_CODE_LIST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a writer builder for com . helger . genericode . v10 . CodeListSetDocument . [CODESPLIT] @ Nonnull public static GenericodeWriter < com . helger . genericode . v10 . CodeListSetDocument > gc10CodeListSet ( ) { return new GenericodeWriter <> ( EGenericodeDocumentType . GC10_CODE_LIST_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a writer builder for com . helger . genericode . v10 . ColumnSetDocument . [CODESPLIT] @ Nonnull public static GenericodeWriter < com . helger . genericode . v10 . ColumnSetDocument > gc10ColumnSet ( ) { return new GenericodeWriter <> ( EGenericodeDocumentType . GC10_COLUMN_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a validator builder for com . helger . genericode . v04 . CodeListDocument . [CODESPLIT] @ Nonnull public static GenericodeValidator < com . helger . genericode . v04 . CodeListDocument > gc04CodeList ( ) { return new GenericodeValidator <> ( EGenericodeDocumentType . GC04_CODE_LIST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a validator builder for com . helger . genericode . v04 . CodeListSetDocument . [CODESPLIT] @ Nonnull public static GenericodeValidator < com . helger . genericode . v04 . CodeListSetDocument > gc04CodeListSet ( ) { return new GenericodeValidator <> ( EGenericodeDocumentType . GC04_CODE_LIST_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a validator builder for com . helger . genericode . v04 . ColumnSetDocument . [CODESPLIT] @ Nonnull public static GenericodeValidator < com . helger . genericode . v04 . ColumnSetDocument > gc04ColumnSet ( ) { return new GenericodeValidator <> ( EGenericodeDocumentType . GC04_COLUMN_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a validator builder for com . helger . genericode . v10 . CodeListDocument . [CODESPLIT] @ Nonnull public static GenericodeValidator < com . helger . genericode . v10 . CodeListDocument > gc10CodeList ( ) { return new GenericodeValidator <> ( EGenericodeDocumentType . GC10_CODE_LIST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a validator builder for com . helger . genericode . v10 . CodeListSetDocument . [CODESPLIT] @ Nonnull public static GenericodeValidator < com . helger . genericode . v10 . CodeListSetDocument > gc10CodeListSet ( ) { return new GenericodeValidator <> ( EGenericodeDocumentType . GC10_CODE_LIST_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a validator builder for com . helger . genericode . v10 . ColumnSetDocument . [CODESPLIT] @ Nonnull public static GenericodeValidator < com . helger . genericode . v10 . ColumnSetDocument > gc10ColumnSet ( ) { return new GenericodeValidator <> ( EGenericodeDocumentType . GC10_COLUMN_SET ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@param pair of exchange / coin [CODESPLIT] public double getLastValue ( Pair pair ) throws NumberFormatException , IOException , NoMarketDataException { double lastValue = Double . parseDouble ( getTicker ( pair ) ) ; return lastValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send Logs to Server [CODESPLIT] protected static void sendLogsToServer ( boolean setSentTime ) { long timeSent = new Date ( ) . getTime ( ) ; String appFeedBackSummary = Utility . convertFileToString ( \"AppFeedBackSummary.json\" ) ; if ( \"\" . equals ( appFeedBackSummary ) || \"{}\" . equals ( appFeedBackSummary ) ) { return ; } else { try { JSONObject appFeedBacksummaryJSON = new JSONObject ( appFeedBackSummary ) ; JSONArray savedArray = ( JSONArray ) appFeedBacksummaryJSON . get ( \"saved\" ) ; HashMap < String , String > timeSentMap = new HashMap <> ( ) ; //Add timeSent to all the json file's which are not set with timeSent for ( int i = 0 ; i < savedArray . length ( ) ; i ++ ) { String instanceName = ( String ) savedArray . get ( i ) ; String screenFeedBackJsonFile = Utility . getJSONfileName ( instanceName ) ; String actualTimeSent = Utility . addAndFetchSentTimeFromScreenFeedBackJson ( screenFeedBackJsonFile , timeSent , setSentTime ) ; if ( actualTimeSent != null ) { timeSentMap . put ( instanceName , actualTimeSent ) ; } } //Iterate each feedback element which is not yet sent for ( int i = 0 ; i < savedArray . length ( ) ; i ++ ) { String instanceName = ( String ) savedArray . get ( i ) ; String screenFeedBackJsonFile = Utility . getJSONfileName ( instanceName ) ; String actualTimeSent = timeSentMap . get ( instanceName ) ; String zipFile = Utility . storageDirectory + instanceName + \"_\" + actualTimeSent + \".zip\" ; List < String > fileList = new ArrayList <> ( ) ; fileList . add ( Utility . getImageFileName ( instanceName ) ) ; fileList . add ( screenFeedBackJsonFile ) ; Utility . createZipArchive ( fileList , zipFile ) ; LogPersister . sendInAppFeedBackFile ( zipFile , new FeedBackUploadResponseListener ( instanceName , zipFile , actualTimeSent ) ) ; } } catch ( JSONException je ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * [CODESPLIT] protected static void unsetContext ( ) { instances . clear ( ) ; context = null ; capture = null ; analyticsCapture = null ; logFileMaxSize = null ; level = null ; uncaughtExceptionHandler = null ; fileLoggerInstance = null ; LogManager . getLogManager ( ) . getLogger ( \"\" ) . removeHandler ( julHandler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Context object must be set in order to use the Logger API . This is called automatically by BMSClient . [CODESPLIT] static public void setContext ( final Context context ) { // once setContext is called, we can set up the uncaught exception handler since // it will force logging to the file if ( null == LogPersister . context ) { // set a custom JUL Handler so we can capture third-party and internal java.util.logging.Logger API calls LogManager . getLogManager ( ) . getLogger ( \"\" ) . addHandler ( julHandler ) ; java . util . logging . Logger . getLogger ( \"\" ) . setLevel ( Level . ALL ) ; LogPersister . context = context ; // now that we have a context, let's set the fileLoggerInstance properly unless it was already set by tests if ( fileLoggerInstance == null || fileLoggerInstance instanceof FileLogger ) { FileLogger . setContext ( context ) ; fileLoggerInstance = FileLogger . getInstance ( ) ; } SharedPreferences prefs = LogPersister . context . getSharedPreferences ( SHARED_PREF_KEY , Context . MODE_PRIVATE ) ; // level if ( null != level ) { // someone called setLevel method before setContext setLevelSync ( level ) ; // seems redundant, but we do this to save to SharedPrefs now that we have Context } else { // set it to the SharedPrefs value, or DEFAULT if no value in SharedPrefs yet setLevelSync ( Logger . LEVEL . fromString ( prefs . getString ( SHARED_PREF_KEY_level , getLevelDefault ( ) . toString ( ) ) ) ) ; } // logFileMaxSize if ( null != logFileMaxSize ) { // someone called setMaxStoreSize method before setContext setMaxLogStoreSize ( logFileMaxSize ) ; // seems redundant, but we do this to save to SharedPrefs now that we have Context } else { // set it to the SharedPrefs value, or DEFAULT if no value in SharedPrefs yet setMaxLogStoreSize ( prefs . getInt ( SHARED_PREF_KEY_logFileMaxSize , DEFAULT_logFileMaxSize ) ) ; } // capture if ( null != capture ) { // someone called setCapture method before setContext setCaptureSync ( capture ) ; // seems redundant, but we do this to save to SharedPrefs now that we have Context } else { // set it to the SharedPrefs value, or DEFAULT if no value in SharedPrefs yet setCaptureSync ( prefs . getBoolean ( SHARED_PREF_KEY_logPersistence , DEFAULT_capture ) ) ; } uncaughtExceptionHandler = new UncaughtExceptionHandler ( ) ; Thread . setDefaultUncaughtExceptionHandler ( uncaughtExceptionHandler ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the level and above at which log messages should be saved / printed . For example passing LEVEL . INFO will log INFO WARN ERROR and FATAL . A null parameter value is ignored and has no effect . [CODESPLIT] static public void setLogLevel ( final Logger . LEVEL desiredLevel ) { ThreadPoolWorkQueue . execute ( new Runnable ( ) { @ Override public void run ( ) { setLevelSync ( desiredLevel ) ; // we do this mostly to enable unit tests to logger.wait(100) instead of // Thread.sleep(100) -- it's faster, more stable, and more deterministic that way synchronized ( WAIT_LOCK ) { WAIT_LOCK . notifyAll ( ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current Logger . LEVEL . [CODESPLIT] static public Logger . LEVEL getLogLevel ( ) { final Future < Logger . LEVEL > task = ThreadPoolWorkQueue . submit ( new Callable < Logger . LEVEL > ( ) { @ Override public Logger . LEVEL call ( ) { return getLevelSync ( ) ; } } ) ; try { return task . get ( ) ; } catch ( Exception e ) { return getLevelSync ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Global setting : turn persisting of log data passed to this class s log methods on or off . [CODESPLIT] static public void storeLogs ( final boolean shouldStoreLogs ) { ThreadPoolWorkQueue . execute ( new Runnable ( ) { @ Override public void run ( ) { setCaptureSync ( shouldStoreLogs ) ; // we do this mostly to enable unit tests to logger.wait(100) instead of // Thread.sleep(100) -- it's faster, more stable, and more deterministic that way synchronized ( WAIT_LOCK ) { WAIT_LOCK . notifyAll ( ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current value of the capture flag indicating that the Logger is recording log calls persistently . [CODESPLIT] static public boolean getCapture ( ) { final Future < Boolean > task = ThreadPoolWorkQueue . submit ( new Callable < Boolean > ( ) { @ Override public Boolean call ( ) { return getCaptureSync ( ) ; } } ) ; try { return task . get ( ) ; } catch ( Exception e ) { return getCaptureSync ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@exclude Global setting : turn persisting of analytics data passed to this class s analytics methods on or off . [CODESPLIT] static public void setAnalyticsCapture ( final boolean capture ) { ThreadPoolWorkQueue . execute ( new Runnable ( ) { @ Override public void run ( ) { setAnalyticsCaptureSync ( capture ) ; // we do this mostly to enable unit tests to logger.wait(100) instead of // Thread.sleep(100) -- it's faster, more stable, and more deterministic that way synchronized ( WAIT_LOCK ) { WAIT_LOCK . notifyAll ( ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@exclude Get the current value of the analyticsCapture flag indicating that the Logger is recording analytics calls persistently . [CODESPLIT] static public boolean getAnalyticsCapture ( ) { final Future < Boolean > task = ThreadPoolWorkQueue . submit ( new Callable < Boolean > ( ) { @ Override public Boolean call ( ) { return getAnalyticsCaptureSync ( ) ; } } ) ; try { return task . get ( ) ; } catch ( Exception e ) { return getAnalyticsCaptureSync ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the maximum size of the local log file . Once the maximum file size is reached no more data will be appended . Consider that this file is sent to a server . [CODESPLIT] static public void setMaxLogStoreSize ( final int bytes ) { // TODO: also check if bytes is bigger than remaining disk space? if ( bytes >= 10000 ) { logFileMaxSize = bytes ; } if ( null != context ) { SharedPreferences prefs = context . getSharedPreferences ( SHARED_PREF_KEY , Context . MODE_PRIVATE ) ; prefs . edit ( ) . putInt ( SHARED_PREF_KEY_logFileMaxSize , logFileMaxSize ) . commit ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See { @link #send () } [CODESPLIT] static public void send ( ResponseListener listener ) { if ( sendingLogs ) { return ; } else { sendingLogs = true ; sendFiles ( LogPersister . FILENAME , listener ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@exclude Send the accumulated log data when the persistent log buffer exists and is not empty . The data accumulates in the log buffer from the use of { @link LogPersister } with capture ( see { @link LogPersister#setAnalyticsCapture ( boolean ) } ) turned on . [CODESPLIT] static public void sendAnalytics ( ResponseListener listener ) { if ( sendingAnalyticsLogs ) { return ; } else { sendingAnalyticsLogs = true ; sendFiles ( LogPersister . ANALYTICS_FILENAME , listener ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ask the Logger if an uncaught exception which often appears to the user as a crashed app is present in the persistent capture buffer . This method should not be called after calling { @link com . ibm . mobilefirstplatform . clientsdk . android . core . api . BMSClient#initialize ( Context String String String ) } . If it is called too early an error message is issued and false is returned . [CODESPLIT] static public boolean isUnCaughtExceptionDetected ( ) { if ( context == null ) { if ( ! context_null_msg_already_printed ) { Log . w ( LOG_TAG_NAME , CONTEXT_NULL_MSG ) ; context_null_msg_already_printed = true ; } return false ; } return context . getSharedPreferences ( SHARED_PREF_KEY , Context . MODE_PRIVATE ) . getBoolean ( SHARED_PREF_KEY_CRASH_DETECTED , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@exclude [CODESPLIT] public static void doLog ( final Logger . LEVEL calledLevel , String message , final long timestamp , final Throwable t , JSONObject additionalMetadata , final String loggerName , final boolean isInternalLogger , final Object loggerObject ) { // we do this outside of the thread, otherwise we can't find the caller to attach the call stack metadata JSONObject metadata = appendStackMetadata ( additionalMetadata ) ; ThreadPoolWorkQueue . execute ( new DoLogRunnable ( calledLevel , message , timestamp , metadata , t , loggerName , isInternalLogger , loggerObject ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "if we have callstack metadata prepend it to the message [CODESPLIT] protected static String prependMetadata ( String message , JSONObject metadata ) { try { if ( null != metadata ) { String clazz = \"\" ; String method = \"\" ; String file = \"\" ; String line = \"\" ; if ( metadata . has ( \"$class\" ) ) { clazz = metadata . getString ( \"$class\" ) ; clazz = clazz . substring ( clazz . lastIndexOf ( ' ' ) + 1 , clazz . length ( ) ) ; } if ( metadata . has ( \"$method\" ) ) { method = metadata . getString ( \"$method\" ) ; } if ( metadata . has ( \"$file\" ) ) { file = metadata . getString ( \"$file\" ) ; } if ( metadata . has ( \"$line\" ) ) { line = metadata . getString ( \"$line\" ) ; } if ( ! ( clazz + method + file + line ) . equals ( \"\" ) ) { // we got something... message = clazz + \".\" + method + \" in \" + file + \":\" + line + \" :: \" + message ; } } } catch ( Exception e ) { // ignore... it's best effort anyway } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get stack trace caused by Logger exceptions [CODESPLIT] protected static JSONObject appendStackMetadata ( JSONObject additionalMetadata ) { JSONObject jsonMetadata ; if ( additionalMetadata != null ) { jsonMetadata = additionalMetadata ; } else { jsonMetadata = new JSONObject ( ) ; } try { // try/catch Exception wraps all because I don't know yet if I can trust getStackTrace... needs more testing // below is slightly more performant than: Thread.currentThread().getStackTrace(); StackTraceElement [ ] stackTraceElements = new Exception ( ) . getStackTrace ( ) ; int index = 0 ; // find the start of the Logger call stack: while ( ! stackTraceElements [ index ] . getClassName ( ) . equals ( LogPersister . class . getName ( ) ) ) { index ++ ; } // then find the caller: while ( stackTraceElements [ index ] . getClassName ( ) . equals ( LogPersister . class . getName ( ) ) || stackTraceElements [ index ] . getClassName ( ) . startsWith ( JULHandler . class . getName ( ) ) || stackTraceElements [ index ] . getClassName ( ) . startsWith ( java . util . logging . Logger . class . getName ( ) ) || stackTraceElements [ index ] . getClassName ( ) . startsWith ( BMSAnalytics . class . getName ( ) ) ) { index ++ ; } jsonMetadata . put ( \"$class\" , stackTraceElements [ index ] . getClassName ( ) ) ; jsonMetadata . put ( \"$file\" , stackTraceElements [ index ] . getFileName ( ) ) ; jsonMetadata . put ( \"$method\" , stackTraceElements [ index ] . getMethodName ( ) ) ; jsonMetadata . put ( \"$line\" , stackTraceElements [ index ] . getLineNumber ( ) ) ; jsonMetadata . put ( \"$src\" , \"java\" ) ; } catch ( Exception e ) { Log . e ( LOG_TAG_NAME , \"Could not generate jsonMetadata object.\" , e ) ; } return jsonMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Will create JSONObject with the passed parameters and other relevant information . See class - level documentation . [CODESPLIT] private static JSONObject createJSONObject ( final Logger . LEVEL level , final String pkg , final String message , long timestamp , final JSONObject jsonMetadata , final Throwable t ) { JSONObject jsonObject = new JSONObject ( ) ; try { jsonObject . put ( \"timestamp\" , timestamp ) ; jsonObject . put ( \"level\" , level . toString ( ) ) ; jsonObject . put ( \"pkg\" , pkg ) ; jsonObject . put ( \"msg\" , message ) ; jsonObject . put ( \"threadid\" , Thread . currentThread ( ) . getId ( ) ) ; if ( null != jsonMetadata ) { jsonObject . put ( \"metadata\" , jsonMetadata ) ; } if ( null != t ) { jsonObject . put ( \"metadata\" , appendFullStackTrace ( jsonMetadata , t ) ) ; } } catch ( JSONException e ) { Log . e ( LOG_TAG_NAME , \"Error adding JSONObject key/value pairs\" , e ) ; } return jsonObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "append the full stacktrace to a $stacktrace key JSONArray in the passed jsonMetadata object and return it . [CODESPLIT] private static JSONObject appendFullStackTrace ( JSONObject jsonMetadata , Throwable t ) { JSONArray stackArray = new JSONArray ( ) ; Throwable throwable = t ; StackTraceElement [ ] stackTraceElements ; boolean first = true ; // walk up the throwable's call stack: while ( throwable != null ) { stackArray . put ( ( first ? \"Exception \" : \"Caused by: \" ) + throwable . getClass ( ) . getName ( ) + ( throwable . getMessage ( ) != null ? \": \" + throwable . getMessage ( ) : \"\" ) ) ; stackTraceElements = throwable . getStackTrace ( ) ; for ( int i = 0 ; i < stackTraceElements . length ; i ++ ) { stackArray . put ( stackTraceElements [ i ] . toString ( ) ) ; } throwable = throwable . getCause ( ) ; first = false ; } try { if ( null == jsonMetadata ) { jsonMetadata = new JSONObject ( ) ; } jsonMetadata . put ( \"$stacktrace\" , stackArray ) ; jsonMetadata . put ( \"$exceptionMessage\" , t . getLocalizedMessage ( ) ) ; jsonMetadata . put ( \"$exceptionClass\" , t . getClass ( ) . getName ( ) ) ; } catch ( JSONException e ) { // ignore.  getting the stacktrace is best effort } return jsonMetadata ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We only persist ( append ) to the log file if the passed jsonObject parameter has data the Logger capture flag is set to true and the log file size is less than FILE_SIZE_LOG_THRESHOLD . [CODESPLIT] private synchronized static void captureToFile ( final JSONObject jsonObject , Logger . LEVEL calledLevel ) { boolean cap = getCaptureSync ( ) ; boolean analyticsCap = getAnalyticsCaptureSync ( ) ; if ( context == null ) { if ( ! context_null_msg_already_printed ) { Log . w ( LOG_TAG_NAME , CONTEXT_NULL_MSG ) ; context_null_msg_already_printed = true ; } return ; } if ( jsonObject . length ( ) == 0 ) { return ; } try { // Determine whether is needs to go to analytics or logger if ( analyticsCap && calledLevel . equals ( Logger . LEVEL . ANALYTICS ) ) { fileLoggerInstance . log ( jsonObject , ANALYTICS_FILENAME ) ; } else if ( cap ) { fileLoggerInstance . log ( jsonObject , FILENAME ) ; } } catch ( Exception e ) { Log . e ( LOG_TAG_NAME , \"An error occurred capturing data to file.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize BMSAnalytics API . This must be called before any other BMSAnalytics . * methods [CODESPLIT] static public void init ( Application app , String applicationName , String clientApiKey , boolean hasUserContext , boolean collectLocation , Analytics . DeviceEvent ... contexts ) { Context context = app . getApplicationContext ( ) ; if ( collectLocation ) { locationService = MFPAnalyticsLocationListener . getInstance ( context ) ; } //Initialize LogPersister LogPersister . setLogLevel ( Logger . getLogLevel ( ) ) ; LogPersister . setContext ( context ) ; //Instrument Logger with LogPersisterDelegate LogPersisterDelegate logPersisterDelegate = new LogPersisterDelegate ( ) ; Logger . setLogPersister ( logPersisterDelegate ) ; MFPInAppFeedBackListner . setContext ( context ) ; Analytics . setAnalyticsDelegate ( new BMSAnalyticsDelegate ( ) ) ; BMSAnalytics . clientApiKey = clientApiKey ; if ( contexts != null ) { for ( Analytics . DeviceEvent event : contexts ) { switch ( event ) { case LIFECYCLE : MFPActivityLifeCycleCallbackListener . init ( app ) ; break ; case NETWORK : isRecordingNetworkEvents = true ; break ; case ALL : MFPActivityLifeCycleCallbackListener . init ( app ) ; isRecordingNetworkEvents = true ; break ; case NONE : break ; } } } //if (!hasUserContext) { //    Use device ID as default user ID: //} if ( collectLocation ) { BMSAnalytics . collectLocation = collectLocation ; locationService . init ( ) ; } DEFAULT_USER_ID = getDeviceID ( context ) ; if ( ! collectLocation ) { setUserIdentity ( DEFAULT_USER_ID , true ) ; } BMSAnalytics . hasUserContext = hasUserContext ; appName = applicationName ; //Intercept requests to add device metadata header BaseRequest . registerInterceptor ( new MetadataHeaderInterceptor ( context . getApplicationContext ( ) ) ) ; BaseRequest . registerInterceptor ( new NetworkLoggingInterceptor ( ) ) ; enable ( ) ; MFPInAppFeedBackListner . sendAppFeedback ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize MFPAnalytics API . This must be called before any other MFPAnalytics . * methods [CODESPLIT] @ Deprecated static public void init ( Application app , String applicationName , String clientApiKey , Analytics . DeviceEvent ... contexts ) { init ( app , applicationName , clientApiKey , false , false , contexts ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log location event [CODESPLIT] public static void logLocation ( ) { if ( ! BMSAnalytics . collectLocation ) { logger . error ( \"You must enable collectLocation before location can be logged\" ) ; return ; } if ( ! locationService . getInitLocationRequests ( ) ) { logger . error ( \"locationService  Initialization has failed\" ) ; return ; } // Create metadata object to log JSONObject metadata = new JSONObject ( ) ; String hashedUserID = UUID . nameUUIDFromBytes ( DEFAULT_USER_ID . getBytes ( ) ) . toString ( ) ; try { metadata . put ( CATEGORY , LOG_LOCATION_KEY ) ; metadata . put ( LATITUDE_KEY , locationService . getLatitude ( ) ) ; metadata . put ( LONGITUDE_KEY , locationService . getLongitude ( ) ) ; metadata . put ( TIMESTAMP_KEY , ( new Date ( ) ) . getTime ( ) ) ; metadata . put ( APP_SESSION_ID_KEY , MFPAnalyticsActivityLifecycleListener . getAppSessionID ( ) ) ; metadata . put ( USER_ID_KEY , hashedUserID ) ; } catch ( JSONException e ) { logger . debug ( \"JSONException encountered logging change in user context: \" + e . getMessage ( ) ) ; } log ( metadata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify current application user . This value will be hashed to ensure privacy . If your application does not have user context then nothing will happen . [CODESPLIT] private static void setUserIdentity ( final String user , boolean isInitialCtx ) { if ( ! isInitialCtx && ! BMSAnalytics . hasUserContext ) { // log it to file: logger . error ( \"Cannot set user identity with anonymous user collection enabled.\" ) ; return ; } // Create metadata object to log JSONObject metadata = new JSONObject ( ) ; DEFAULT_USER_ID = user ; String hashedUserID = UUID . nameUUIDFromBytes ( user . getBytes ( ) ) . toString ( ) ; try { if ( isInitialCtx ) { metadata . put ( CATEGORY , INITIAL_CTX_CATEGORY ) ; } else { metadata . put ( CATEGORY , USER_SWITCH_CATEGORY ) ; } if ( BMSAnalytics . collectLocation ) { if ( locationService . getInitLocationRequests ( ) ) { metadata . put ( LONGITUDE_KEY , locationService . getLongitude ( ) ) ; metadata . put ( LATITUDE_KEY , locationService . getLatitude ( ) ) ; } } metadata . put ( TIMESTAMP_KEY , ( new Date ( ) ) . getTime ( ) ) ; metadata . put ( APP_SESSION_ID_KEY , MFPAnalyticsActivityLifecycleListener . getAppSessionID ( ) ) ; metadata . put ( USER_ID_KEY , hashedUserID ) ; } catch ( JSONException e ) { logger . debug ( \"JSONException encountered logging change in user context: \" + e . getMessage ( ) ) ; } MFPInAppFeedBackListner . setUserIdentity ( user ) ; log ( metadata ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callers should pass a JSONObject in the format described in the class - level documentation . It will be placed as - is using JSONObject . toString () with no additional contextual information automatically appended . We use java . util . logging simply to take advantage of its built - in thread - safety and log rollover . [CODESPLIT] public synchronized void log ( final JSONObject logData , String fileName ) throws SecurityException , IOException { if ( null != singleton ) { filePath = context . getFilesDir ( ) + System . getProperty ( \"file.separator\" ) + fileName ; FileHandler handler = null ; handler = new FileHandler ( filePath , LogPersister . getMaxLogStoreSize ( ) , LogPersister . MAX_NUM_LOG_FILES , true ) ; handler . setFormatter ( formatter ) ; singleton . addHandler ( handler ) ; singleton . log ( Level . FINEST , logData . toString ( ) + \",\" ) ; singleton . getHandlers ( ) [ 0 ] . close ( ) ; singleton . removeHandler ( handler ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public for testing only [CODESPLIT] private byte [ ] getByteArrayFromFile ( final String file ) throws UnsupportedEncodingException { String ret = \"\" ; File fl = new File ( context . getFilesDir ( ) , file ) ; if ( fl . exists ( ) ) { try { FileInputStream fin = new FileInputStream ( fl ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ( int ) fl . length ( ) ) ; copyStream ( fin , baos ) ; return baos . toByteArray ( ) ; } catch ( IOException e ) { Log . e ( LogPersister . LOG_TAG_NAME , \"problem reading file \" + fl . toString ( ) , e ) ; } } return ret . getBytes ( \"UTF-8\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starting the location updates [CODESPLIT] protected void startLocationUpdates ( ) { if ( ActivityCompat . checkSelfPermission ( Context , Manifest . permission . ACCESS_FINE_LOCATION ) != PackageManager . PERMISSION_GRANTED && ActivityCompat . checkSelfPermission ( Context , Manifest . permission . ACCESS_COARSE_LOCATION ) != PackageManager . PERMISSION_GRANTED ) { // TODO: Consider calling //    ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding //   public void onRequestPermissionsResult(int requestCode, String[] permissions, //                                          int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return ; } LocationServices . FusedLocationApi . requestLocationUpdates ( mGoogleApiClient , mLocationRequest , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates and logs the size of first numEntries in the region . [CODESPLIT] public void sizeRegion ( Region < ? , ? > region , int numEntries ) { if ( region == null ) { throw new IllegalArgumentException ( \"Region is null.\" ) ; } if ( region instanceof PartitionedRegion ) { sizePartitionedRegion ( region , numEntries ) ; } else { sizeReplicatedOrLocalRegion ( region , numEntries ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sizes numEntries of a partitioned region or all the entries if numEntries is 0 . [CODESPLIT] private void sizePartitionedRegion ( Region < ? , ? > region , int numEntries ) { Region < ? , ? > primaryDataSet = PartitionRegionHelper . getLocalData ( region ) ; int regionSize = primaryDataSet . size ( ) ; if ( numEntries == 0 ) { numEntries = primaryDataSet . size ( ) ; } else if ( numEntries > regionSize ) { numEntries = regionSize ; } int count = 0 ; for ( Iterator < ? > i = primaryDataSet . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { if ( count == numEntries ) { break ; } EntrySnapshot entry = ( EntrySnapshot ) i . next ( ) ; RegionEntry re = entry . getRegionEntry ( ) ; dumpSizes ( entry , re ) ; } dumpTotalAndAverageSizes ( numEntries ) ; clearTotals ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sizes numEntries of a replicated or local region or all the entries if numEntries is 0 . [CODESPLIT] private void sizeReplicatedOrLocalRegion ( Region < ? , ? > region , int numEntries ) { Set < ? > entries = region . entrySet ( ) ; int regionSize = entries . size ( ) ; if ( numEntries == 0 ) { numEntries = entries . size ( ) ; } else if ( numEntries > regionSize ) { numEntries = regionSize ; } int count = 0 ; for ( Iterator < ? > i = entries . iterator ( ) ; i . hasNext ( ) ; ) { if ( count == numEntries ) { break ; } LocalRegion . NonTXEntry entry = ( LocalRegion . NonTXEntry ) i . next ( ) ; RegionEntry re = entry . getRegionEntry ( ) ; dumpSizes ( entry , re ) ; } dumpTotalAndAverageSizes ( numEntries ) ; clearTotals ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public String getLocators ( ) { StringBuilder locatorList = new StringBuilder ( ) ; Map < String , ? > credentials = getCredentials ( ) ; if ( credentials == null ) return null ; List < String > locators = ( List < String > ) credentials . get ( \"locators\" ) ; for ( String locator : locators ) { if ( locatorList . length ( ) != 0 ) locatorList . append ( \",\" ) ; locatorList . append ( locator ) ; } return locatorList . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public List < URI > getLocatorUrlList ( ) { List < URI > locatorList = new ArrayList < URI > ( ) ; Map < String , ? > credentials = getCredentials ( ) ; List < String > locators = null ; if ( credentials != null ) locators = ( List < String > ) credentials . get ( \"locators\" ) ; try { if ( locators == null || locators . isEmpty ( ) ) { //get for LOCATORS env String locatorsConfig = Config . getProperty ( GeodeConfigConstants . LOCATORS_PROP , \"\" ) ; if ( locatorsConfig . length ( ) == 0 ) return null ; String [ ] parsedLocators = locatorsConfig . split ( \",\" ) ; if ( parsedLocators == null || parsedLocators . length == 0 ) return null ; locators = Arrays . asList ( parsedLocators ) ; } for ( String locator : locators ) { Matcher m = regExpPattern . matcher ( locator ) ; if ( ! m . matches ( ) ) { throw new IllegalStateException ( \"Unexpected locator format. expected host[port], but got:\" + locator ) ; } locatorList . add ( new URI ( \"locator://\" + m . group ( 1 ) + \":\" + m . group ( 2 ) ) ) ; } return locatorList ; } catch ( URISyntaxException e ) { throw new ConfigException ( \"One of the provided locators has an incorrect syntax:\" + locatorList ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public SecuredToken getSecuredToken ( String username , String token ) { Map < String , ? > credentials = getCredentials ( ) ; if ( credentials == null ) return null ; List < Map < String , String > > users = ( List ) credentials . get ( \"users\" ) ; if ( users == null ) return null ; Map < String , String > map = null ; if ( username == null || username . trim ( ) . length ( ) == 0 ) { map = users . iterator ( ) . next ( ) ; } else { map = users . stream ( ) . filter ( m -> username . equals ( m . get ( \"username\" ) ) ) . findFirst ( ) . orElse ( null ) ; } if ( map == null ) return null ; String password = map . get ( \"password\" ) ; if ( password == null ) password = \"\" ; return new UserSecuredCredentials ( map . get ( \"username\" ) , password . toCharArray ( ) , token ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public void constructPoolLocator ( ClientCacheFactory factory ) { List < URI > list = this . getLocatorUrlList ( ) ; if ( list != null && ! list . isEmpty ( ) ) { for ( URI uri : list ) { factory . addPoolLocator ( uri . getHost ( ) , uri . getPort ( ) ) ; } } else { factory . addPoolLocator ( this . host , this . port ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) private List < Map < String , ? > > getGemFireService ( Map services ) { List < Map < String , ? > > l = ( List ) services . get ( \"p-cloudcache\" ) ; return l ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a snapshot entry . If the last entry has been read a null value will be returned . [CODESPLIT] public SnapshotRecord readSnapshotRecord ( ) throws IOException , ClassNotFoundException { byte [ ] key = DataSerializer . readByteArray ( dis ) ; if ( key == null ) { return null ; } byte [ ] value = DataSerializer . readByteArray ( dis ) ; return new SnapshotRecord ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ Override public void visitResourceInst ( ResourceInst resourceInst ) { String name = resourceInst . getName ( ) ; ResourceType resourceType = resourceInst . getType ( ) ; boolean skip = resourceType == null || resourceType . getName ( ) == null || ( this . typeName != null && ! resourceType . getName ( ) . toUpperCase ( ) . contains ( this . typeName ) ) ; if ( skip ) { System . out . println ( \"skipping resourceType:\" + resourceType + \" name:\" + name ) ; return ; } ArrayList < String > values = new ArrayList < String > ( ) ; ArrayList < String > headers = new ArrayList < String > ( ) ; headers . add ( \"name\" ) ; values . add ( name ) ; StatValue [ ] statValues = resourceInst . getStatValues ( ) ; if ( statValues == null ) return ; for ( StatValue statValue : statValues ) { String statName = statValue . getDescriptor ( ) . getName ( ) ; if ( this . statNames != null && this . statNames . length > 0 ) { if ( Arrays . binarySearch ( statNames , statName ) < 0 ) continue ; //skip } StatValue dataStoreEntryCount = resourceInst . getStatValue ( statName ) ; StatDescriptor statDescriptor = resourceInst . getType ( ) . getStat ( statName ) ; headers . add ( statName + \"        \" + statDescriptor . getDescription ( ) ) ; values . add ( String . valueOf ( dataStoreEntryCount . getSnapshotsMaximum ( ) ) ) ; } writeCsv ( resourceInst , headers , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] void writeCsv ( ResourceInst resourceInst , List < String > headers , List < String > values ) { File file = null ; if ( this . statsFile == null ) file = csvFile ; else file = Paths . get ( this . outputDirectory . toFile ( ) . getAbsolutePath ( ) , this . statsFile . getName ( ) + \".\" + resourceInst . getType ( ) . getName ( ) + \".csv\" ) . toFile ( ) ; CsvWriter csvWriter = new CsvWriter ( file ) ; try { csvWriter . writeHeader ( headers ) ; csvWriter . appendRow ( values ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "elapsed millis from base [CODESPLIT] void dump ( PrintWriter stream ) { stream . print ( \"[size=\" + count ) ; for ( int i = 0 ; i < count ; i ++ ) { if ( i != 0 ) { stream . print ( \", \" ) ; stream . print ( timeStamps [ i ] - timeStamps [ i - 1 ] ) ; } else { stream . print ( \" \" + timeStamps [ i ] ) ; } } stream . println ( \"]\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array of time stamp values the first of which has the specified index . Each returned time stamp is the number of millis since midnight Jan 1 1970 UTC . [CODESPLIT] double [ ] getTimeValuesSinceIdx ( int idx ) { int resultSize = this . count - idx ; double [ ] result = new double [ resultSize ] ; for ( int i = 0 ; i < resultSize ; i ++ ) { result [ i ] = getMilliTimeStamp ( idx + i ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public UserProfileDetails toUserDetails ( Collection < String > authorities ) { if ( this . userName == null || this . userName . length ( ) == 0 ) throw new IllegalArgumentException ( \"userName is required\" ) ; if ( password == null || password . length == 0 ) throw new IllegalArgumentException ( \"Password is required\" ) ; if ( authorities == null || authorities . isEmpty ( ) ) throw new IllegalArgumentException ( \"authorities is required\" ) ; Collection < GrantedAuthority > grantAuthorities = authorities . stream ( ) . map ( a -> new SimpleGrantedAuthority ( a ) ) . collect ( Collectors . toSet ( ) ) ; UserProfileDetails user = new UserProfileDetails ( this . userName , String . valueOf ( password ) , grantAuthorities ) ; user . setEmail ( email ) ; user . setFirstName ( firstName ) ; user . setLastName ( lastName ) ; return user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accepts a file or directory contain the statistics files [CODESPLIT] public Chart convert ( File file ) { if ( file == null ) return null ; try { if ( file . isDirectory ( ) ) { //Process for all files Set < File > statsFiles = IO . listFileRecursive ( file , \"*.gfs\" ) ; if ( statsFiles == null || statsFiles . isEmpty ( ) ) return null ; for ( File statFile : statsFiles ) { GfStatsReader reader = new GfStatsReader ( statFile . getAbsolutePath ( ) ) ; reader . accept ( visitor ) ; } } else { GfStatsReader reader = new GfStatsReader ( file . getAbsolutePath ( ) ) ; reader . accept ( visitor ) ; } return visitor . getChart ( ) ; } catch ( IOException e ) { throw new RuntimeException ( \"File:\" + file + \" ERROR:\" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Calculates each stat given the result of calling getSnapshots [CODESPLIT] protected void calcStats ( double [ ] values ) { if ( statsValid ) { return ; } size = values . length ; if ( size == 0 ) { min = 0.0 ; max = 0.0 ; avg = 0.0 ; stddev = 0.0 ; mostRecent = 0.0 ; } else { min = values [ 0 ] ; max = values [ 0 ] ; mostRecent = values [ values . length - 1 ] ; double total = values [ 0 ] ; for ( int i = 1 ; i < size ; i ++ ) { total += values [ i ] ; if ( values [ i ] < min ) { min = values [ i ] ; } else if ( values [ i ] > max ) { max = values [ i ] ; } } avg = total / size ; stddev = 0.0 ; if ( size > 1 ) { for ( int i = 0 ; i < size ; i ++ ) { double dv = values [ i ] - avg ; stddev += ( dv * dv ) ; } stddev /= ( size - 1 ) ; stddev = Math . sqrt ( stddev ) ; } } statsValid = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* [CODESPLIT] public static boolean isReplicatedRegion ( DistributedRegionMXBean distributedRegionMXBean ) { if ( distributedRegionMXBean == null ) return true ; String type = distributedRegionMXBean . getRegionType ( ) ; return type != null && type . toUpperCase ( Locale . US ) . contains ( \"REPLICATE\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] public static DistributedRegionMXBean getRegionMBean ( String regionName , JMX jmx ) { ObjectName on = getRegionObjectName ( regionName , jmx ) ; if ( on == null ) return null ; DistributedRegionMXBean region = jmx . newBean ( DistributedRegionMXBean . class , on ) ; return region ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dynamically create a GemFire pool with just the server [CODESPLIT] public static synchronized Pool getPoolForServer ( String serverName , JMX jmx ) throws InstanceNotFoundException { Pool pool = PoolManager . find ( serverName ) ; if ( pool != null ) return pool ; PoolFactory poolFactory = PoolManager . createFactory ( ) ; //LogWriter logWriter = getClientCache(jmx).getLogger(); try { //get host name //ex: object GemFire:type=Member,member=server_1 ObjectName objectName = new ObjectName ( new StringBuilder ( \"GemFire:type=Member,member=\" ) . append ( serverName ) . toString ( ) ) ; String host = jmx . getAttribute ( objectName , \"Host\" ) ; if ( host == null || host . length ( ) == 0 ) throw new IllegalArgumentException ( \"host not found for serverName:\" + serverName + \" not found\" ) ; host = lookupNetworkHost ( host ) ; String findJmxPort = new StringBuilder ( \"GemFire:service=CacheServer,port=*,type=Member,member=\" ) . append ( serverName ) . toString ( ) ; //search ObjectNames Set < ObjectName > objectNames = jmx . searchObjectNames ( findJmxPort ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) throw new IllegalArgumentException ( \"Unable to to find port with server name:\" + serverName ) ; ObjectName portObjectName = objectNames . iterator ( ) . next ( ) ; Integer port = jmx . getAttribute ( portObjectName , \"Port\" ) ; if ( port == null ) throw new IllegalArgumentException ( \"Unable to obtain port for objectName:\" + portObjectName + \" for server:\" + serverName ) ; System . out . println ( \"Found cache server host\" + host + \" port:\" + port ) ; poolFactory = poolFactory . addServer ( host , port . intValue ( ) ) ; return poolFactory . create ( serverName ) ; } catch ( InstanceNotFoundException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( \"Unable to create pool for servername:\" + serverName + \" error:\" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This methods create a pool for connecting to a locator [CODESPLIT] public static synchronized Pool getPoolForLocator ( JMX jmx ) { String locatorsPoolName = jmx . getHost ( ) + \"[\" + jmx . getPort ( ) + \"]\" ; Pool pool = PoolManager . find ( locatorsPoolName ) ; if ( pool != null ) return pool ; PoolFactory poolFactory = PoolManager . createFactory ( ) ; try { int port = getLocatorPort ( jmx ) ; poolFactory = poolFactory . addLocator ( jmx . getHost ( ) , port ) ; return poolFactory . create ( locatorsPoolName ) ; } catch ( Exception e ) { throw new RuntimeException ( \"Unable to create pool for locator:\" + jmx . getHost ( ) + \" error:\" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get region based on a given name ( create the region if it exists on the server but not on the client ) . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < K , V > Region < K , V > getRegion ( String regionName , JMX jmx ) { Region < K , V > region = getClientCache ( jmx ) . getRegion ( regionName ) ; if ( region == null ) { //check if region exist on server if ( isExistingRegionOnServer ( regionName , jmx ) ) { // create it locally region = ( Region < K , V > ) clientCache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) . create ( regionName ) ; } } return region ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > List all regions that match a wildcard expression ( ex : R * ) . Note that special internal regions that begin with the name __ will be skipped . < / pre > [CODESPLIT] public static Collection < Region < ? , ? > > listRootRegions ( String regionPattern , JMX jmx ) { //Use JMX to query for distributed regions //Ex: name GemFire:service=Region,name=/exampleRegion,type=Distributed String regionJmxPattern = String . format ( \"GemFire:service=Region,name=/%s,type=Distributed\" , regionPattern ) ; //this.getLogger().info(\"Searching for JMX region patterns: \"+regionJmxPattern); Set < ObjectName > regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { //search with quotes regionJmxPattern = String . format ( \"GemFire:service=Region,name=\\\"/%s\\\",type=Distributed\" , regionPattern ) ; regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; } if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { //this.getLogger().warn(\"No regions found\"); return null ; } //sort the list regionObjNameSet = new TreeSet < ObjectName > ( regionObjNameSet ) ; ArrayList < Region < ? , ? > > regionSet = new ArrayList < Region < ? , ? > > ( regionObjNameSet . size ( ) ) ; String regionName = null ; try { for ( ObjectName regionObjectName : regionObjNameSet ) { regionName = jmx . getAttribute ( regionObjectName , \"Name\" ) ; if ( regionName . startsWith ( \"__\" ) ) { continue ; //skip special regions } regionSet . add ( getRegion ( regionName , jmx ) ) ; } return regionSet ; } catch ( InstanceNotFoundException e ) { throw new RuntimeException ( \"Cannot list regions:\" + regionPattern + \" ERROR:\" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the client cache based on the JMX connection ( if no cache instance ) [CODESPLIT] public static synchronized ClientCache getClientCache ( JMX jmx ) { try { if ( clientCache == null || clientCache . isClosed ( ) ) { try { clientCache = ClientCacheFactory . getAnyInstance ( ) ; } catch ( CacheClosedException e ) { clientCache = null ; } if ( clientCache != null ) return clientCache ; // Get Locator port // locator bean GemFire:service=Locator,type=Member,member=locator String locatorNamePattern = \"GemFire:type=Member,member=*\" ; QueryExp queryExp = Query . eq ( Query . attr ( \"Manager\" ) , Query . value ( true ) ) ; Set < ObjectName > objectNames = jmx . searchObjectNames ( locatorNamePattern , queryExp ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) { throw new RuntimeException ( \"Data export error: no manager locators found through JMX connection\" ) ; } ObjectName locatorJmxMgrObjName = objectNames . iterator ( ) . next ( ) ; String locatorMemberName = jmx . getAttribute ( locatorJmxMgrObjName , \"Member\" ) ; ObjectName locatorServiceObjName = new ObjectName ( String . format ( \"GemFire:service=Locator,type=Member,member=%s\" , locatorMemberName ) ) ; // get port int port = jmx . getAttribute ( locatorServiceObjName , \"Port\" ) ; String host = jmx . getAttribute ( locatorJmxMgrObjName , \"Host\" ) ; host = lookupNetworkHost ( host ) ; clientCache = new ClientCacheFactory ( ) . addPoolLocator ( host , port ) . setPoolSubscriptionEnabled ( false ) . setPdxReadSerialized ( Boolean . valueOf ( System . getProperty ( \"PdxReadSerialized\" , \"false\" ) ) . booleanValue ( ) ) . create ( ) ; } return clientCache ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( \"JMX connection error \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if a given region exists [CODESPLIT] private static boolean isExistingRegionOnServer ( String regionName , JMX jmx ) { String regionJmxPattern = String . format ( \"GemFire:service=Region,name=/%s,type=Distributed\" , regionName ) ; //System.out.println(\"searching for:\"+regionJmxPattern); Set < ObjectName > regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { //search with quotes regionJmxPattern = String . format ( \"GemFire:service=Region,name=\\\"/%s\\\",type=Distributed\" , regionName ) ; //System.out.println(\"searching for:\"+regionJmxPattern); regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; } return regionObjNameSet != null && ! regionObjNameSet . isEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private static ObjectName getRegionObjectName ( String regionName , JMX jmx ) { String regionJmxPattern = String . format ( \"GemFire:service=Region,name=/%s,type=Distributed\" , regionName ) ; //System.out.println(\"searching for:\"+regionJmxPattern); Set < ObjectName > regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { //search with quotes //GemFire:service=Region,name=\"/ui-test-region\",type=Distributed regionJmxPattern = String . format ( \"GemFire:service=Region,name=\\\"/%s\\\",type=Distributed\" , regionName ) ; //System.out.println(\"searching for:\"+regionJmxPattern); regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; } if ( regionObjNameSet == null ) return null ; return regionObjNameSet . iterator ( ) . next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a GemFire JMX client [CODESPLIT] public static MemberMXBean getMember ( String name , JMX jmx ) { try { String pattern = \"GemFire:type=Member,member=\" + name ; Set < ObjectName > objectNames = jmx . searchObjectNames ( pattern ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) return null ; ObjectName serverName = new ObjectName ( pattern ) ; return jmx . newBean ( MemberMXBean . class , serverName ) ; } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( \"Unable to get member \" + name + \" ERROR:\" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] static DistributedSystemMXBean getDistributedSystemMXBean ( JMX jmx ) throws Exception { DistributedSystemMXBean system = jmx . newBean ( DistributedSystemMXBean . class , new ObjectName ( \"GemFire:service=System,type=Distributed\" ) ) ; return system ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] public static Collection < GatewayReceiverMXBean > listGatewayReceivers ( JMX jmx ) throws Exception { DistributedSystemMXBean system = jmx . newBean ( DistributedSystemMXBean . class , new ObjectName ( \"GemFire:service=System,type=Distributed\" ) ) ; ObjectName [ ] objectNames = system . listGatewayReceiverObjectNames ( ) ; if ( objectNames == null ) return null ; GatewayReceiverMXBean gatewayReceiver = null ; ArrayList < GatewayReceiverMXBean > list = new ArrayList < GatewayReceiverMXBean > ( objectNames . length ) ; for ( ObjectName objectName : objectNames ) { gatewayReceiver = jmx . newBean ( GatewayReceiverMXBean . class , objectName ) ; list . add ( gatewayReceiver ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines the unique set of the host names for the distributed system [CODESPLIT] public static Collection < String > listHosts ( JMX jmx ) { Set < ObjectName > objectNames = jmx . searchObjectNames ( \"GemFire:type=Member,member=*\" ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) { return null ; } HashSet < String > hostLists = new HashSet < String > ( objectNames . size ( ) ) ; MemberMXBean memberMXBean = null ; for ( ObjectName objectName : objectNames ) { memberMXBean = jmx . newBean ( MemberMXBean . class , objectName ) ; hostLists . add ( memberMXBean . getHost ( ) ) ; } return hostLists ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supports resolving host network lookup issues [CODESPLIT] static synchronized String lookupNetworkHost ( String host ) { try { if ( _bundle == null ) { URL url = GemFireJmxClient . class . getResource ( hostPropFileName ) ; String filePath = null ; if ( url == null ) filePath = hostPropFileName ; else filePath = url . toString ( ) ; System . out . println ( new StringBuilder ( \"Loading IP addresses from \" ) . append ( filePath ) . toString ( ) ) ; _bundle = ResourceBundle . getBundle ( \"host\" ) ; } System . out . println ( new StringBuilder ( \"Looking for host name \\\"\" ) . append ( host ) . append ( \"\\\" IP address in \" ) . append ( hostPropFileName ) . toString ( ) ) ; String newHost = _bundle . getString ( host ) ; System . out . println ( new StringBuilder ( host ) . append ( \"=\" ) . append ( newHost ) . toString ( ) ) ; return newHost ; } catch ( RuntimeException e ) { System . out . println ( \"Using host:\" + host ) ; return host ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] public User getUSer ( String email ) { try { ExampleFunctionService userService = appContext . getBean ( ExampleFunctionService . class ) ; return userService . findUserByEmail ( email ) ; } finally { appContext . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the data should be sent [CODESPLIT] public static boolean isErrorAndSendException ( ResultSender < Object > resultSender , Object data ) { if ( data instanceof Throwable ) { Throwable e = ( Throwable ) data ; resultSender . sendException ( e ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a function with the given execution settings [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > Collection < T > exeWithResults ( Execution < ? , ? , ? > execution , Function < ? > function ) throws Exception { ResultCollector < ? , ? > resultCollector ; try { resultCollector = execution . execute ( function ) ; } catch ( FunctionException e ) { if ( e . getCause ( ) instanceof NullPointerException ) throw new RuntimeException ( \"Unable to execute function:\" + function . getId ( ) + \" assert hostnames(s) for locators and cache server can be resovled. \" + \" If you do not have access to the host file, create host.properties and add to the CLASSPATH. \" + \" Example: locahost=127.1.0.0 \" + \" also assert that all cache servers have been initialized. Check if the server's cache.xml has all required <initializer>..</initializer> configurations\" , e ) ; else throw e ; } Object resultsObject = resultCollector . getResult ( ) ; //Return a result in collection (for a single response)\r Collection < Object > collectionResults = ( Collection < Object > ) resultsObject ; //if empty return null\r if ( collectionResults . isEmpty ( ) ) return null ; Collection < Object > list = new ArrayList < Object > ( collectionResults . size ( ) ) ; flatten ( collectionResults , list ) ; if ( list . isEmpty ( ) ) return null ; return ( Collection < T > ) list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used to flatten results from multiple servers [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > void flatten ( Collection < Object > input , Collection < Object > flattenOutput ) throws Exception { if ( input == null || input . isEmpty ( ) || flattenOutput == null ) return ; for ( Object inputObj : input ) { if ( inputObj instanceof Exception ) throw ( Exception ) inputObj ; if ( inputObj == null ) continue ; if ( inputObj instanceof Collection ) flatten ( ( Collection < Object > ) inputObj , flattenOutput ) ; else flattenOutput . add ( inputObj ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public static < T > Collection < T > collectResults ( ResultCollector < ? , ? > resultCollector ) throws Exception { if ( resultCollector == null ) return null ; Collection < Object > results = ( Collection ) resultCollector . getResult ( ) ; if ( results == null || results . isEmpty ( ) ) return null ; ArrayList < Object > output = new ArrayList <> ( 10 ) ; flatten ( results , output ) ; if ( output . isEmpty ( ) ) return null ; output . trimToSize ( ) ; return ( Collection ) output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Select results for OQL [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < ReturnType > Collection < ReturnType > query ( Query queryObj , RegionFunctionContext rfc , Object ... params ) throws FunctionDomainException , TypeMismatchException , NameResolutionException , QueryInvocationTargetException { SelectResults < ReturnType > selectResults ; // Execute Query locally. Returns results set. if ( rfc == null || JvmRegionFunctionContext . class . isAssignableFrom ( rfc . getClass ( ) ) ) { if ( params == null || params . length == 0 ) { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( ) ; } else { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( params ) ; } if ( selectResults == null || selectResults . isEmpty ( ) ) return null ; ArrayList < ReturnType > results = new ArrayList < ReturnType > ( selectResults . size ( ) ) ; results . addAll ( selectResults . asList ( ) ) ; return results ; } else { if ( params == null || params . length == 0 ) { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( rfc ) ; } else { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( rfc , params ) ; } if ( selectResults == null || selectResults . isEmpty ( ) ) return null ; return selectResults ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for put events registration [CODESPLIT] public static < K , V > CacheListenerBridge < K , V > forAfterPut ( Consumer < EntryEvent < K , V > > consumer ) { return new CacheListenerBridge < K , V > ( consumer , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method for delete events registration [CODESPLIT] public static < K , V > CacheListenerBridge < K , V > forAfterDelete ( Consumer < EntryEvent < K , V > > consumer ) { return new CacheListenerBridge < K , V > ( null , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] private void updateRemoveConsumer ( EntryEvent < K , V > event ) { if ( this . removeConsumers == null || this . removeConsumers . isEmpty ( ) ) return ; for ( Consumer < EntryEvent < K , V > > removeConsumer : this . removeConsumers ) { removeConsumer . accept ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] private void updatePutConsumer ( EntryEvent < K , V > event ) { if ( this . putConsumers == null || this . putConsumers . isEmpty ( ) ) return ; for ( Consumer < EntryEvent < K , V > > putConsumer : putConsumers ) { putConsumer . accept ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a new records [CODESPLIT] @ PostMapping ( path = \"{region}/{type}/{key}\" , produces = \"application/json\" ) public String putEntry ( @ PathVariable String region , @ PathVariable String type , @ PathVariable String key , @ RequestBody String value ) throws Exception { if ( region == null || region . length ( ) == 0 || key == null || value == null ) return null ; if ( type == null || type . length ( ) == 0 ) throw new IllegalArgumentException ( \"type is required. URL pattern {region}/{type}/{key}\" ) ; try { Region < String , Object > gemRegion = geode . getRegion ( region ) ; System . out . println ( \"Putting key $key in region $region\" ) ; Class < ? > clz = Class . forName ( type ) ; Object obj = gson . fromJson ( value , clz ) ; Object response = gemRegion . put ( key , obj ) ; if ( response == null ) return null ; return gson . toJson ( response ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete a region entry by a key [CODESPLIT] @ DeleteMapping ( path = \"{regionName}/{key}\" , produces = \"application/json\" ) public String delete ( @ PathVariable String regionName , @ PathVariable String key ) { Region < String , PdxInstance > region = this . geode . getRegion ( regionName ) ; PdxInstance pdx = region . remove ( key ) ; if ( pdx == null ) return null ; return JSONFormatter . toJSON ( pdx ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a value by a given key [CODESPLIT] @ GetMapping ( path = \"{region}/{key}\" , produces = \"application/json\" ) String getValueByKey ( @ PathVariable String region , @ PathVariable String key ) { try { if ( region == null || region . length ( ) == 0 || key == null ) return null ; Region < String , Object > gemRegion = geode . getRegion ( region ) ; Object value = gemRegion . get ( key ) ; if ( value == null ) return null ; return gson . toJson ( value ) ; } catch ( ServerOperationException serverError ) { Throwable cause = serverError . getRootCause ( ) ; if ( cause instanceof RegionDestroyedException ) { throw new DataServiceSystemException ( \"Region \\\"\" + region + \"\\\" not found\" ) ; } throw new DataServiceSystemException ( serverError . getMessage ( ) , serverError ) ; } catch ( RuntimeException e ) { e . printStackTrace ( ) ; throw new DataServiceSystemException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handling exceptions in general for REST responses [CODESPLIT] @ ExceptionHandler ( Exception . class ) private DataError handleException ( HttpServletRequest request , HttpServletResponse response , Exception e ) { return faultAgent . handleException ( request , response , e ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ Override public void close ( ) { if ( cqQuery != null ) { try { cqQuery . close ( ) ; } catch ( Exception e ) { Debugger . println ( e . getMessage ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "On region filter facts determine how to parse the inputs typically for CICS to grid calls [CODESPLIT] public OnRegionFilterKeyFacts [ ] getOnRegionFilterKeyFacts ( ) { if ( onRegionFilterKeyFacts == null ) return null ; return Arrays . copyOf ( onRegionFilterKeyFacts , onRegionFilterKeyFacts . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function will use the JsonExportFunction function to export json data and read the results to be returned to callers [CODESPLIT] @ Override public void execute ( FunctionContext < Object > functionContext ) { ResultSender < Object > sender = functionContext . getResultSender ( ) ; Cache cache = CacheFactory . getAnyInstance ( ) ; Logger logWriter = LogManager . getLogger ( getClass ( ) ) ; try { //export data\r String [ ] args = ( String [ ] ) functionContext . getArguments ( ) ; if ( args == null || args . length != 2 ) throw new FunctionException ( \"Required array args: [region,extension]\" ) ; String extensionArg = args [ 0 ] ; if ( extensionArg == null || extensionArg . length ( ) == 0 ) { throw new IllegalArgumentException ( \"File extension required\" ) ; } ExportFileType extension = ExportFileType . valueOf ( extensionArg ) ; String regionName = args [ 1 ] ; //TODO: accept multiple regions\r Region < Object , Object > region = cache . getRegion ( regionName ) ; if ( region == null ) { sender . lastResult ( null ) ; return ; } //TODO: get file from functions\r File file = new File ( new StringBuilder ( directoryPath ) . append ( \"/\" ) . append ( regionName ) . append ( \".\" ) . append ( extensionArg ) . toString ( ) ) ; //get server name\r String serverName = cache . getDistributedSystem ( ) . getDistributedMember ( ) . getName ( ) ; switch ( extension ) { case gfd : new GfdExportFunction ( ) . exportRegion ( region ) ; break ; default : throw new IllegalArgumentException ( \"Unsupported extension file type:\" + extension ) ; } Serializable content = readContent ( file , extension , logWriter ) ; Serializable [ ] arrayResults = { serverName , content , file . getAbsolutePath ( ) } ; sender . lastResult ( arrayResults ) ; } catch ( Exception e ) { String stackTrace = Debugger . stackTrace ( e ) ; logWriter . error ( stackTrace ) ; throw new FunctionException ( stackTrace ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private Serializable readContent ( File file , ExportFileType exportFileType , Logger logWriter ) throws IOException { String filePath = file . getAbsolutePath ( ) ; logWriter . info ( \"reading \" + filePath ) ; switch ( exportFileType ) { case gfd : return IO . readBinaryFile ( file ) ; case json : return IO . readFile ( file . getAbsolutePath ( ) , StandardCharsets . UTF_8 ) ; default : throw new RuntimeException ( \"Unknown extension file type:\" + exportFileType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public UserProfileDetails findUserProfileDetailsByUserName ( String userName ) throws UsernameNotFoundException { UserDetails user = this . loadUserByUsername ( userName ) ; return ( UserProfileDetails ) user ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------- [CODESPLIT] public int compareTo ( Object aOther ) { FunctionAttribute other = ( FunctionAttribute ) aOther ; // compare names return other . getName ( ) . compareTo ( this . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public static int size ( Region < ? , ? > region ) { Set < ? > set = region . keySetOnServer ( ) ; if ( set == null || set . isEmpty ( ) ) return 0 ; return set . size ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ Override public < ReturnType > Collection < ReturnType > query ( String query , Object ... params ) { return Querier . query ( query , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List the unique set of host name [CODESPLIT] public static Set < String > listHosts ( JMX jmx ) { Set < ObjectName > memberObjects = jmx . searchObjectNames ( \"GemFire:type=Member,member=*\" ) ; if ( memberObjects == null || memberObjects . isEmpty ( ) ) { return null ; } HashSet < String > hostList = new HashSet < String > ( memberObjects . size ( ) ) ; MemberMXBean bean = null ; for ( ObjectName objectName : memberObjects ) { bean = jmx . newBean ( MemberMXBean . class , objectName ) ; try { hostList . add ( bean . getHost ( ) ) ; } catch ( UndeclaredThrowableException e ) { //will not be added } } return hostList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] public static boolean checkMemberStatus ( String serverName , JMX jmx ) { try { ObjectName objectName = new ObjectName ( \"GemFire:type=Member,member=\" + serverName ) ; String status = ( String ) jmx . invoke ( objectName , \"status\" , null , null ) ; boolean isOnline = status != null && status . contains ( \"online\" ) ; Debugger . println ( \"member:\" + serverName + \" isOnline:\" + isOnline ) ; return isOnline ; } catch ( MalformedObjectNameException e ) { throw new CommunicationException ( e . getMessage ( ) + \" server=\" + serverName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the search on Region [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) @ Override public void execute ( FunctionContext functionContext ) { Cache cache = CacheFactory . getAnyInstance ( ) ; try { //Function must be executed on REgion if ( ! ( functionContext instanceof RegionFunctionContext ) ) { throw new FunctionException ( \"Execute on a region\" ) ; } Object args = functionContext . getArguments ( ) ; if ( args == null ) throw new FunctionException ( \"arguments is required\" ) ; TextPageCriteria criteria = null ; if ( args instanceof PdxInstance ) { PdxInstance pdxInstance = ( PdxInstance ) args ; try { criteria = ( TextPageCriteria ) ( pdxInstance . getObject ( ) ) ; } catch ( PdxSerializationException e ) { throw new FunctionException ( e . getMessage ( ) + \" JSON:\" + JSONFormatter . toJSON ( pdxInstance ) ) ; } } else { criteria = ( TextPageCriteria ) args ; } Region < String , Collection < Object > > pagingRegion = cache . getRegion ( criteria . getPageRegionName ( ) ) ; Region < ? , ? > region = cache . getRegion ( criteria . getRegionName ( ) ) ; GeodePagination pagination = new GeodePagination ( ) ; TextPolicySearchStrategy geodeSearch = new TextPolicySearchStrategy ( cache ) ; //Collection<String> keys =  (Collection<String>)checkCachedKeysByCriteria(criteria,searchRequest,pagination,pagingRegion); geodeSearch . saveSearchResultsWithPageKeys ( criteria , criteria . getQuery ( ) , null , ( Region < String , Collection < Object > > ) pagingRegion ) ; //build results Collection < Object > collection = pagination . readResultsByPageValues ( criteria . getId ( ) , criteria . getSortField ( ) , criteria . isSortDescending ( ) , criteria . getBeginIndex ( ) , ( Region < Object , Object > ) region , ( Region ) pagingRegion ) ; if ( collection == null ) { functionContext . getResultSender ( ) . lastResult ( null ) ; return ; } PagingCollection < Object > pageCollection = new PagingCollection < Object > ( collection , criteria ) ; functionContext . getResultSender ( ) . lastResult ( pageCollection ) ; } catch ( RuntimeException e ) { Logger logger = LogManager . getLogger ( LuceneSearchFunction . class ) ; logger . error ( Debugger . stackTrace ( e ) ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] @ Override public boolean accept ( Entry < Object , Object > entry ) { return keys != null && keys . contains ( entry . getKey ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Current supports get cache server name Determine the logic name of app [CODESPLIT] public static String getAppName ( ResourceInst [ ] resources ) { if ( resources == null || resources . length == 0 ) return null ; ResourceType rt = null ; for ( ResourceInst resourceInst : resources ) { if ( resourceInst == null ) continue ; rt = resourceInst . getType ( ) ; if ( rt == null ) continue ; if ( ! \"CacheServerStats\" . equals ( rt . getName ( ) ) ) continue ; return resourceInst . getName ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize security properties [CODESPLIT] protected static void constructSecurity ( Properties props ) throws IOException { props . setProperty ( \"security-client-auth-init\" , GeodeConfigAuthInitialize . class . getName ( ) + \".create\" ) ; //write to file File sslFile = saveEnvFile ( GeodeConfigConstants . SSL_KEYSTORE_CLASSPATH_FILE_PROP ) ; System . out . println ( \"sslFile:\" + sslFile ) ; File sslTrustStoreFile = saveEnvFile ( GeodeConfigConstants . SSL_TRUSTSTORE_CLASSPATH_FILE_PROP ) ; String sslTrustStoreFilePath = \"\" ; if ( sslTrustStoreFile != null ) sslTrustStoreFilePath = sslTrustStoreFile . getAbsolutePath ( ) ; props . setProperty ( \"ssl-keystore\" , ( sslFile != null ) ? sslFile . getAbsolutePath ( ) : \"\" ) ; props . setProperty ( \"ssl-keystore-password\" , Config . getPropertyEnv ( \"ssl-keystore-password\" , \"\" ) ) ; props . setProperty ( \"ssl-truststore\" , sslTrustStoreFilePath ) ; props . setProperty ( \"ssl-protocols\" , Config . getPropertyEnv ( \"ssl-protocols\" , \"\" ) ) ; props . setProperty ( \"ssl-truststore-password\" , Config . getPropertyEnv ( \"ssl-truststore-password\" , \"\" ) ) ; props . setProperty ( \"ssl-keystore-type\" , Config . getPropertyEnv ( \"ssl-keystore-type\" , \"\" ) ) ; props . setProperty ( \"ssl-ciphers\" , Config . getPropertyEnv ( \"ssl-ciphers\" , \"\" ) ) ; props . setProperty ( \"ssl-require-authentication\" , Config . getPropertyEnv ( \"ssl-require-authentication\" , \"\" ) ) ; props . setProperty ( \"ssl-enabled-components\" , Config . getPropertyEnv ( \"ssl-enabled-components\" , \"\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] static PdxSerializer createPdxSerializer ( String pdxSerializerClassNm , String ... classPatterns ) { Object [ ] initArgs = { classPatterns } ; return ClassPath . newInstance ( pdxSerializerClassNm , initArgs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public < K , V > Map < K , V > readSearchResultsByPage ( TextPageCriteria criteria , int pageNumber ) { GeodeLuceneSearch search = new GeodeLuceneSearch ( this . clientCache ) ; Region < String , Collection < ? > > pageRegion = this . getRegion ( criteria . getPageRegionName ( ) ) ; Region < K , V > region = this . getRegion ( criteria . getRegionName ( ) ) ; return search . readResultsByPage ( criteria , pageNumber , region , pageRegion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public Collection < String > clearSearchResultsByPage ( TextPageCriteria criteria ) { GeodeLuceneSearch search = new GeodeLuceneSearch ( this . clientCache ) ; return search . clearSearchResultsByPage ( criteria , this . getRegion ( criteria . getPageRegionName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) private < K , V > Region < K , V > createRegion ( String regionName ) { if ( regionName . startsWith ( \"/\" ) ) regionName = regionName . substring ( 1 ) ; //remove prefix CacheListenerBridge < K , V > listener = ( CacheListenerBridge ) this . listenerMap . get ( regionName ) ; if ( listener != null ) { ClientRegionFactory < K , V > listenerRegionFactory = null ; if ( this . cachingProxy ) listenerRegionFactory = this . clientCache . createClientRegionFactory ( ClientRegionShortcut . CACHING_PROXY ) ; else listenerRegionFactory = this . clientCache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) ; listenerRegionFactory . addCacheListener ( ( CacheListener ) listener ) ; Region < K , V > region = listenerRegionFactory . create ( regionName ) ; region . registerInterestRegex ( \".*\" ) ; return region ; } if ( this . cachingProxy ) return ( Region < K , V > ) this . cachingRegionfactory . create ( regionName ) ; else return ( Region < K , V > ) this . proxyRegionfactory . create ( regionName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is an example to get or create a region [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < K , V > Region < K , V > getRegion ( String regionName ) { if ( regionName == null || regionName . length ( ) == 0 ) return null ; Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) return ( Region < K , V > ) region ; region = ( Region < K , V > ) this . createRegion ( regionName ) ; //Client side data policy is typically NORMAL or EMPTY if ( cachingProxy ) { //NORMAL data policy are typically used for CACHING_PROXY //You should interest so updates for the server will be pushed to the clients region . registerInterestRegex ( \".*\" ) ; } return region ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a proxy region [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < K , V > Region < K , V > getRegion ( ClientCache clientCache , String regionName ) { if ( regionName == null || regionName . length ( ) == 0 ) return null ; Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) return ( Region < K , V > ) region ; region = ( Region < K , V > ) clientCache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) . create ( regionName ) ; return region ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public < T > BlockingQueue < T > registerCq ( String cqName , String oql ) { try { QueryService queryService = this . clientCache . getQueryService ( ) ; // Create CqAttribute using CqAttributeFactory CqAttributesFactory cqf = new CqAttributesFactory ( ) ; // Create a listener and add it to the CQ attributes callback defined below CqQueueListener < T > cqListener = new CqQueueListener < T > ( ) ; cqf . addCqListener ( cqListener ) ; CqAttributes cqa = cqf . create ( ) ; // Name of the CQ and its query // Create the CqQuery CqQuery cqQuery = queryService . newCq ( cqName , oql , cqa ) ; cqListener . setCqQuery ( cqQuery ) ; // Execute CQ, getting the optional initial result set // Without the initial result set, the call is priceTracker.execute(); cqQuery . execute ( ) ; return cqListener ; } catch ( CqException | CqClosedException | RegionNotFoundException | QueryInvalidException | CqExistsException e ) { throw new nyla . solutions . core . exception . SystemException ( \"ERROR:\" + e . getMessage ( ) + \" cqName:\" + cqName + \" oql:\" + oql , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the observer as a listener for put / create events [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public < K , V > void registerAfterPut ( String regionName , Consumer < EntryEvent < K , V > > consumer ) { CacheListenerBridge < K , V > listener = ( CacheListenerBridge ) this . listenerMap . get ( regionName ) ; if ( listener == null ) { Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) throw new IllegalStateException ( \"Cannot register a listener when the region already created. Try registering the listener first. Then use GeodeClient.getRegion for regionName:\" + regionName ) ; listener = CacheListenerBridge . forAfterPut ( consumer ) ; } else { listener . addAfterPutListener ( consumer ) ; } this . listenerMap . put ( regionName , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the observer as a listener for remove / invalidate events [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public < K , V > void registerAfterDelete ( String regionName , Consumer < EntryEvent < K , V > > consumer ) { CacheListenerBridge < K , V > listener = ( CacheListenerBridge ) this . listenerMap . get ( regionName ) ; if ( listener == null ) { Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) throw new IllegalStateException ( \"Cannot register a listener when the region already created. Try registering the listener first. Then use GeodeClient.getRegion for regionName:\" + regionName ) ; listener = CacheListenerBridge . forAfterDelete ( consumer ) ; } else { listener . addAfterDeleteListener ( consumer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the RegionSyncReport the given [CODESPLIT] public void constructComparison ( Map < ? , BigInteger > sourceChecksumMap , Map < ? , BigInteger > targetMap ) { if ( sourceChecksumMap == null ) { if ( targetMap != null && ! targetMap . isEmpty ( ) ) { this . keysRemovedFromSource . addAll ( targetMap . keySet ( ) ) ; } return ; } if ( targetMap == null ) { this . keysMissingOnTarget . addAll ( sourceChecksumMap . keySet ( ) ) ; return ; } BigInteger targetBi = null ; BigInteger sourceBi = null ; for ( Map . Entry < ? , BigInteger > entrySource : sourceChecksumMap . entrySet ( ) ) { targetBi = targetMap . get ( entrySource . getKey ( ) ) ; sourceBi = sourceChecksumMap . get ( entrySource . getKey ( ) ) ; if ( targetBi == null ) { keysMissingOnTarget . add ( entrySource . getKey ( ) ) ; } else if ( ! targetBi . equals ( sourceBi ) ) { keysDifferentOnTarget . add ( entrySource . getKey ( ) ) ; } } //determine keysRemovedFromSource Set < ? > sourceKeySet = sourceChecksumMap . keySet ( ) ; for ( Map . Entry < ? , ? > targetEntry : targetMap . entrySet ( ) ) { if ( ! sourceKeySet . contains ( targetEntry . getKey ( ) ) ) { keysRemovedFromSource . add ( targetEntry . getKey ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Export region data in JSON format [CODESPLIT] public void execute ( FunctionContext < Object > fc ) { ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean didExport = false ; if ( fc instanceof RegionFunctionContext ) { didExport = exportOnRegion ( ( RegionFunctionContext ) fc ) ; } else { didExport = exportAllRegions ( fc ) ; } rs . lastResult ( didExport ) ; } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; LogManager . getLogger ( getClass ( ) ) . error ( sw . toString ( ) ) ; rs . sendException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private boolean exportAllRegions ( FunctionContext < Object > fc ) { String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) { throw new FunctionException ( \"Argument not provided\" ) ; } //Get region name from arguments\r String regionName = args [ 0 ] ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return exportRegion ( region ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] private boolean exportOnRegion ( RegionFunctionContext rfc ) { //get argument \r //check if region is partitioned\r Region < Object , Object > region = rfc . getDataSet ( ) ; return exportRegion ( region ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] private boolean exportRegion ( Region < Object , Object > region ) { if ( PartitionRegionHelper . isPartitionedRegion ( region ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } //get first\r ObjectMapper mapper = new ObjectMapper ( ) ; mapper . getSerializerProvider ( ) . setNullKeySerializer ( new DefaultNullKeySerializer ( ) ) ; mapper . getSerializerProvider ( ) . setDefaultKeySerializer ( new DefaultKeySerializer ( ) ) ; Set < Object > keySet = region . keySet ( ) ; if ( keySet == null || keySet . isEmpty ( ) ) { return false ; } String regionName = region . getName ( ) ; Collection < SerializationRegionWrapper > collection = new ArrayList < SerializationRegionWrapper > ( keySet . size ( ) ) ; SerializationRegionWrapper serializationWrapper = null ; try { String keyClassName = null ; Object value = null ; String valueClassName = null ; for ( Object key : keySet ) { keyClassName = key . getClass ( ) . getName ( ) ; value = region . get ( key ) ; valueClassName = value . getClass ( ) . getName ( ) ; serializationWrapper = new SerializationRegionWrapper ( key , keyClassName , value , valueClassName ) ; collection . add ( serializationWrapper ) ; } File resultFile = new File ( new StringBuilder ( this . directoryPath ) . append ( fileSeparator ) . append ( regionName ) . append ( suffix ) . toString ( ) ) ; //write data\r mapper . writeValue ( resultFile , collection ) ; return true ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new FunctionException ( \"Error exporting ERROR:\" + e . getMessage ( ) + \" serializationWrapper:\" + serializationWrapper , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] protected String getSecurityPassword ( ) { String password = Config . getProperty ( PASSWORD , Config . getProperty ( \"SECURITY_PASSWORD\" , \"\" ) ) ; return password ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] protected String getSecurityUserName ( ) { String username = Config . getProperty ( USER_NAME , Config . getProperty ( \"SECURITY_USERNAME\" , \"\" ) ) ; return username ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return true if the current ts must be inserted instead of being mapped to the tsAtInsertPoint [CODESPLIT] private static boolean mustInsert ( int nextIdx , long [ ] valueTimeStamps , long tsAtInsertPoint ) { return ( nextIdx < valueTimeStamps . length ) && ( valueTimeStamps [ nextIdx ] <= tsAtInsertPoint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if the timeStamp at curIdx is the one that ts is the closest to . We know that timeStamps [ curIdx - 1 ] if it exists was not the closest . [CODESPLIT] private static boolean isClosest ( long ts , long [ ] timeStamps , int curIdx ) { if ( curIdx >= ( timeStamps . length - 1 ) ) { // curIdx is the last one so it must be the closest return true ; } if ( ts == timeStamps [ curIdx ] ) { return true ; } return closer ( ts , timeStamps [ curIdx ] , timeStamps [ curIdx + 1 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the approximate amount of memory used to implement this object . [CODESPLIT] protected int getMemoryUsed ( ) { int result = 0 ; if ( values != null ) { for ( SimpleValue value : values ) { result += value . getMemoryUsed ( ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns true if sample was added . [CODESPLIT] protected boolean addValueSample ( int statOffset , long statDeltaBits ) { if ( this . values != null && this . values [ statOffset ] != null ) { this . values [ statOffset ] . prepareNextBits ( statDeltaBits ) ; return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Frees up any resources no longer needed after the archive file is closed . Returns true if this guy is no longer needed . [CODESPLIT] protected boolean close ( ) { if ( isLoaded ( ) ) { for ( SimpleValue value : values ) { if ( value != null ) { value . shrink ( ) ; } } return false ; } else { return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets the value of the stat in the current instance given the stat name . [CODESPLIT] public StatValue getStatValue ( String name ) { StatValue result = null ; StatDescriptor desc = getType ( ) . getStat ( name ) ; if ( desc != null ) { result = values [ desc . getOffset ( ) ] ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see if the archive has changed since the StatArchiverReader instance was created or last updated . If the archive has additional samples then those are read the resource instances maintained by the reader are updated . <p > Once closed a reader can no longer be updated . [CODESPLIT] public boolean update ( boolean doReset ) throws IOException { if ( this . closed ) { return false ; } if ( ! this . updateOK ) { throw new RuntimeException ( \"Update of this type of file is not supported\" ) ; } if ( doReset ) { this . dataIn . reset ( ) ; } int updateTokenCount = 0 ; while ( this . readToken ( ) ) { updateTokenCount ++ ; } return updateTokenCount != 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the archive . [CODESPLIT] public void close ( ) throws IOException { if ( ! this . closed ) { this . closed = true ; this . is . close ( ) ; this . dataIn . close ( ) ; this . is = null ; this . dataIn = null ; int typeCount = 0 ; if ( this . resourceTypeTable != null ) { // fix for bug 32320 for ( int i = 0 ; i < this . resourceTypeTable . length ; i ++ ) { if ( this . resourceTypeTable [ i ] != null ) { if ( this . resourceTypeTable [ i ] . close ( ) ) { this . resourceTypeTable [ i ] = null ; } else { typeCount ++ ; } } } ResourceType [ ] newTypeTable = new ResourceType [ typeCount ] ; typeCount = 0 ; for ( ResourceType aResourceTypeTable : this . resourceTypeTable ) { if ( aResourceTypeTable != null ) { newTypeTable [ typeCount ] = aResourceTypeTable ; typeCount ++ ; } } this . resourceTypeTable = newTypeTable ; } if ( this . resourceInstTable != null ) { // fix for bug 32320 int instCount = 0 ; for ( int i = 0 ; i < this . resourceInstTable . length ; i ++ ) { if ( this . resourceInstTable [ i ] != null ) { if ( this . resourceInstTable [ i ] . close ( ) ) { this . resourceInstTable [ i ] = null ; } else { instCount ++ ; } } } ResourceInst [ ] newInstTable = new ResourceInst [ instCount ] ; instCount = 0 ; for ( ResourceInst aResourceInstTable : this . resourceInstTable ) { if ( aResourceInstTable != null ) { newInstTable [ instCount ] = aResourceInstTable ; instCount ++ ; } } this . resourceInstTable = newInstTable ; this . resourceInstSize = instCount ; } // optimize memory usage of timeSeries now that no more samples this . timeSeries . shrink ( ) ; // filters are no longer needed since file will not be read from this . filters = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and converts all statistics files in a given directory to CSV [CODESPLIT] public static void toCvsFiles ( File directory ) throws IOException { Set < File > statsFiles = IO . listFileRecursive ( directory , \"*.gfs\" ) ; if ( statsFiles == null || statsFiles . isEmpty ( ) ) return ; for ( File archiveFile : statsFiles ) { GfStatsReader reader = new GfStatsReader ( archiveFile . getAbsolutePath ( ) ) ; reader . dumpCsvFiles ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main method to extract GF Stats to file [CODESPLIT] public static void main ( String [ ] args ) { File archiveFile , csvFile ; if ( args . length < 1 ) { System . err . println ( \"Usage: java \" + GfStatsReader . class . getName ( ) + \" archiveFile [csvFile [statName ]*]\" ) ; return ; } try { archiveFile = Paths . get ( args [ 0 ] ) . toFile ( ) ; if ( archiveFile . isDirectory ( ) ) { toCvsFiles ( archiveFile ) ; return ; } if ( args . length < 2 ) { GfStatsReader reader = new GfStatsReader ( archiveFile . getAbsolutePath ( ) ) ; reader . dumpCsvFiles ( ) ; return ; } String typeName = args [ 1 ] ; csvFile = Paths . get ( args [ 2 ] ) . toFile ( ) ; GenericCsvStatsVisitor visitor = null ; if ( args . length > 3 ) { String [ ] stateNames = Arrays . copyOfRange ( args , 2 , args . length - 1 ) ; visitor = new GenericCsvStatsVisitor ( csvFile , typeName , stateNames ) ; } else visitor = new GenericCsvStatsVisitor ( csvFile , typeName ) ; System . out . println ( \"accepting\" ) ; GfStatsReader reader = new GfStatsReader ( archiveFile . getAbsolutePath ( ) ) ; reader . accept ( visitor ) ; } catch ( IOException e ) { // TODO Auto-generated catch block e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close and recreate the JMX connect [CODESPLIT] public synchronized static JMX reconnect ( ) { try { ClientCache cache = null ; cache = ClientCacheFactory . getAnyInstance ( ) ; if ( cache != null && ! cache . isClosed ( ) ) { cache . close ( ) ; } } catch ( Exception e ) { System . out . println ( \"Cache was closed\" ) ; } if ( jmx != null ) { jmx . dispose ( ) ; jmx = null ; } return getJmx ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connect / Reconnect to a locator host / port [CODESPLIT] public static synchronized JMX reconnectJMX ( String locatorHost , int locatorPort ) { try { ClientCache cache = null ; cache = ClientCacheFactory . getAnyInstance ( ) ; if ( cache != null && ! cache . isClosed ( ) ) { cache . close ( ) ; } } catch ( Exception e ) { System . out . println ( \"Cache was closed\" ) ; } if ( jmx != null ) { jmx . dispose ( ) ; jmx = null ; } SingletonGemFireJmx . setLocatorJmxHost ( locatorHost ) ; SingletonGemFireJmx . setLocatorPort ( locatorPort ) ; return getJmx ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] public synchronized static JMX getJmx ( ) { if ( jmx == null ) jmx = JMX . connect ( locatorJmxHost , locatorJmxPort ) ; return jmx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops all cache servers followed by locators on a given server [CODESPLIT] public static int stopMembersOnHost ( String hostName ) { JMX jmx = SingletonGemFireJmx . getJmx ( ) ; String objectNamePattern = \"GemFire:type=Member,member=*\" ; QueryExp queryExp = null ; ValueExp [ ] values = null ; //Also get the IP try { InetAddress [ ] addresses = InetAddress . getAllByName ( hostName ) ; InetAddress address = null ; if ( addresses != null ) { values = new ValueExp [ addresses . length ] ; for ( int i = 0 ; i < addresses . length ; i ++ ) { address = addresses [ i ] ; values [ i ] = Query . value ( address . getHostAddress ( ) ) ; } } } catch ( UnknownHostException e ) { Debugger . println ( e . getMessage ( ) ) ; } if ( values != null ) { queryExp = Query . or ( Query . eq ( Query . attr ( \"Host\" ) , Query . value ( hostName ) ) , Query . in ( Query . attr ( \"Host\" ) , values ) ) ; } else { queryExp = Query . eq ( Query . attr ( \"Host\" ) , Query . value ( hostName ) ) ; } /*\n\t\t * QueryExp query = Query.and(Query.eq(Query.attr(\"Enabled\"), Query.value(true)),\n               Query.eq(Query.attr(\"Owner\"), Query.value(\"Duke\")));\n\t\t */ Set < ObjectName > memberObjectNames = jmx . searchObjectNames ( objectNamePattern , queryExp ) ; if ( memberObjectNames == null || memberObjectNames . isEmpty ( ) ) return 0 ; int memberCount = memberObjectNames . size ( ) ; MemberMXBean member = null ; Collection < String > locators = new ArrayList < String > ( ) ; for ( ObjectName objectName : memberObjectNames ) { member = GemFireJmxClient . getMember ( objectName . getKeyProperty ( \"member\" ) , SingletonGemFireJmx . getJmx ( ) ) ; if ( member . isLocator ( ) ) { locators . add ( member . getName ( ) ) ; } else { shutDownMember ( member . getName ( ) ) ; } } for ( String locatorName : locators ) { shutDownMember ( locatorName ) ; } return memberCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shut down a given member by its name [CODESPLIT] public static void shutDownMember ( String name ) { try { ObjectName serverName = new ObjectName ( \"GemFire:type=Member,member=\" + name ) ; JMX jmx = SingletonGemFireJmx . getJmx ( ) ; MemberMXBean bean = jmx . newBean ( MemberMXBean . class , serverName ) ; bean . shutDownMember ( ) ; //wait for member to shutdown System . out . println ( \"Waiting for member:\" + name + \"  to shutdown\" ) ; while ( GemFireJmxClient . checkMemberStatus ( name , SingletonGemFireJmx . getJmx ( ) ) ) { Thread . sleep ( shutDownDelay ) ; } } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( \"Unable to shutdown member \" + name + \" ERROR:\" + e . getMessage ( ) , e ) ; } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] public static void stopLocator ( JMX jmx , String locatorName ) { try { ObjectName objectName = new ObjectName ( \"GemFire:type=Member,member=\" + locatorName ) ; //DistributedSystemMXBean distributedSystemMXBean =  MemberMXBean bean = jmx . newBean ( MemberMXBean . class , objectName ) ; bean . shutDownMember ( ) ; } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( \"Cannot stop member:\" + locatorName + \" ERROR:\" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does not stop locators [CODESPLIT] public static String [ ] shutDown ( JMX jmx ) { try { DistributedSystemMXBean bean = toDistributeSystem ( jmx ) ; return bean . shutDownAllMembers ( ) ; } catch ( Exception e ) { throw new RuntimeException ( \" ERROR:\" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private static DistributedSystemMXBean toDistributeSystem ( JMX jmx ) throws MalformedObjectNameException { ObjectName objectName = new ObjectName ( \"GemFire:service=System,type=Distributed\" ) ; //DistributedSystemMXBean distributedSystemMXBean =  DistributedSystemMXBean bean = jmx . newBean ( DistributedSystemMXBean . class , objectName ) ; return bean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shut down each member in a given RedundancyZone [CODESPLIT] public static void shutDownRedundancyZone ( String redundancyZone ) { if ( redundancyZone == null || redundancyZone . length ( ) == 0 ) throw new IllegalArgumentException ( \"redundancyZone required\" ) ; String objectNamePattern = \"GemFire:type=Member,member=*\" ; QueryExp exp = Query . eq ( Query . attr ( \"RedundancyZone\" ) , Query . value ( redundancyZone ) ) ; Collection < ObjectName > memberObjectNames = SingletonGemFireJmx . getJmx ( ) . searchObjectNames ( objectNamePattern , exp ) ; for ( ObjectName objectName : memberObjectNames ) { GemFireMgmt . shutDownMember ( objectName . getKeyProperty ( \"member\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store the pagination search result details [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public < K , V > List < String > storePaginationMap ( String id , int pageSize , Region < String , Collection < K > > pageKeysRegion , List < Map . Entry < K , V > > results ) { if ( results == null || results . isEmpty ( ) ) return null ; //add to pages List < Collection < K > > pagesCollection = toKeyPages ( ( List ) results , pageSize ) ; int pageIndex = 1 ; String key = null ; ArrayList < String > keys = new ArrayList < String > ( pageSize ) ; for ( Collection < K > page : pagesCollection ) { //store in region key = toPageKey ( id , pageIndex ++ ) ; pageKeysRegion . put ( key , page ) ; keys . add ( key ) ; } keys . trimToSize ( ) ; return keys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* [CODESPLIT] public static String toPageKey ( String id , int pageNumber ) { return new StringBuilder ( ) . append ( id ) . append ( \"-\" ) . append ( pageNumber ) . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public List < String > storePagination ( String sanId , int pageSize , Map < String , Collection < ? > > pageKeysRegion , Collection < String > keys ) { if ( keys == null || keys . isEmpty ( ) ) return null ; //add to pages List < Collection < String > > pagesCollection = Organizer . toPages ( keys , pageSize ) ; String key = null ; int pageIndex = 1 ; ArrayList < String > pageKeys = new ArrayList < String > ( 10 ) ; for ( Collection < String > page : pagesCollection ) { //store in region key = new StringBuilder ( ) . append ( sanId ) . append ( \"-\" ) . append ( pageIndex ++ ) . toString ( ) ; pageKeysRegion . put ( key , page ) ; pageKeys . add ( key ) ; } pageKeys . trimToSize ( ) ; return pageKeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read Results from region by keys in pageRegion [CODESPLIT] public < K , V > Map < K , V > readResultsByPage ( TextPageCriteria criteria , int pageNumber , Region < K , V > region , Region < String , Collection < ? > > pageRegion ) { if ( pageRegion == null ) return null ; Collection < ? > regionKeys = pageRegion . get ( criteria . toPageKey ( pageNumber ) ) ; if ( regionKeys == null || regionKeys . isEmpty ( ) ) return null ; return region . getAll ( regionKeys ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public void execute ( FunctionContext < Object > fc ) { ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean results = false ; if ( fc instanceof RegionFunctionContext ) { results = importOnRegion ( ( RegionFunctionContext ) fc ) ; } else { String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) throw new IllegalArgumentException ( \"Arguments with region name required\" ) ; String regionName = args [ 0 ] ; this . importRegion ( regionName ) ; } rs . lastResult ( results ) ; } catch ( Exception e ) { String stackTrace = Debugger . stackTrace ( e ) ; LogManager . getLogger ( getClass ( ) ) . error ( stackTrace ) ; rs . sendException ( e ) ; throw new FunctionException ( stackTrace ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private boolean importRegion ( String regionName ) throws Exception { if ( regionName == null || regionName . length ( ) == 0 ) return false ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return importRegion ( region ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] protected boolean importOnRegion ( RegionFunctionContext rfc ) throws Exception { // get argument\r // check if region is partitioned\r Region < Object , Object > region = rfc . getDataSet ( ) ; return importRegion ( region ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Import exported data from a given [CODESPLIT] private boolean importRegion ( Region < Object , Object > region ) throws Exception { File file = DataOpsSecretary . determineFile ( ExportFileType . gfd , region . getName ( ) ) ; if ( ! file . exists ( ) ) return false ; region . getSnapshotService ( ) . load ( file , SnapshotFormat . GEMFIRE ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the remote locators and locator and assert that they match [CODESPLIT] public static boolean checkRemoteLocatorsAndLocatorsMatch ( String remoteLocators , String locators ) { if ( remoteLocators == null || remoteLocators . length ( ) == 0 ) return false ; if ( remoteLocators . equalsIgnoreCase ( locators ) ) return true ; String [ ] remoteLocatorsArray = remoteLocators . split ( \",\" ) ; if ( locators == null || locators . length ( ) == 0 ) return false ; String [ ] locatorsArray = locators . split ( \",\" ) ; String remoteLocatorHost , locatorHost ; int remoteLocatorPort , locatorPort ; for ( String remoteLocator : remoteLocatorsArray ) { if ( remoteLocator == null || remoteLocator . length ( ) == 0 ) continue ; //parse host for ( String locator : locatorsArray ) { if ( locator == null || locator . length ( ) == 0 ) continue ; try { remoteLocatorHost = parseLocatorHost ( remoteLocator ) ; locatorHost = parseLocatorHost ( locator ) ; remoteLocatorPort = parseLocatorPort ( remoteLocator ) ; locatorPort = parseLocatorPort ( locator ) ; if ( Networking . hostEquals ( remoteLocatorHost , locatorHost ) && remoteLocatorPort == locatorPort ) { return true ; } else { //check if ip address match } } catch ( NumberFormatException e ) { //port parse exception return false ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( \"remoteLocator:\" + remoteLocator + \" locator:\" + locator + \" ERROR:\" + e . getMessage ( ) , e ) ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private static String parseLocatorHost ( String locator ) { int i = locator . indexOf ( \"[\" ) ; if ( i > 0 ) return locator . substring ( 0 , i ) . trim ( ) ; else return locator . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private static int parseLocatorPort ( String locator ) { int start = locator . indexOf ( \"[\" ) ; String text = null ; if ( start > 0 ) { String results = locator . substring ( start + 1 ) ; int end = results . indexOf ( \"]\" ) ; if ( end > 0 ) { text = results . substring ( 0 , end ) . trim ( ) ; return Integer . parseInt ( text ) ; } } throw new IllegalArgumentException ( \"Expected format host[port] but provided with:\" + locator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ Override public void run ( ) { if ( ! outDirectory . exists ( ) ) { throw new IllegalArgumentException ( outDirectory + \" does not exist\" ) ; } // read try ( SnapshotRecordReader reader = new SnapshotRecordReader ( inFile ) ) { SnapshotRecord record = null ; // create writer int batchCount = 1 ; File out = createFile ( batchCount ++ ) ; SnapshotRecordWriter writer = null ; try { writer = new SnapshotRecordWriter ( out , regionName ) ; int cnt = 0 ; while ( ( record = reader . readSnapshotRecord ( ) ) != null ) { writer . writeSnapshotEntry ( record ) ; cnt ++ ; if ( cnt >= batchSize ) { out = createFile ( batchCount ++ ) ; writer . close ( ) ; writer = new SnapshotRecordWriter ( out , regionName ) ; } } } finally { if ( writer != null ) writer . close ( ) ; } } catch ( ClassNotFoundException | IOException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private Class < ? > forClassName ( String className ) throws ClassNotFoundException { if ( className == null || className . length ( ) == 0 ) throw new FunctionException ( \"class name string is empty: \" ) ; return Class . forName ( className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Returns the amount of memory used to implement this series . [CODESPLIT] protected int getMemoryUsed ( ) { int result = 4 + 8 + 8 + 8 + 4 + 4 + 4 ; if ( intervals != null ) { result += 4 * intervals . length ; for ( int i = 0 ; i <= intervalIdx ; i ++ ) { result += intervals [ i ] . getMemoryUsed ( ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Gets the first resultSize values of this series skipping over the first samplesToSkip ones . The first value in a series is at index 0 . The maximum result size can be obtained by calling getSize () . [CODESPLIT] public double [ ] getValuesEx ( int typeCode , int samplesToSkip , int resultSize ) { double [ ] result = new double [ resultSize ] ; int firstInterval = 0 ; int idx = 0 ; while ( samplesToSkip > 0 && firstInterval <= intervalIdx && intervals [ firstInterval ] . getSampleCount ( ) <= samplesToSkip ) { samplesToSkip -= intervals [ firstInterval ] . getSampleCount ( ) ; firstInterval ++ ; } for ( int i = firstInterval ; i <= intervalIdx ; i ++ ) { idx += intervals [ i ] . fill ( result , idx , typeCode , samplesToSkip ) ; samplesToSkip = 0 ; } if ( currentCount != 0 ) { idx += BitInterval . create ( currentStartBits , currentInterval , currentCount ) . fill ( result , idx , typeCode , samplesToSkip ) ; } // assert if ( idx != resultSize ) { throw new RuntimeException ( \"GetValuesEx didn't fill the last \" + ( resultSize - idx ) + \" entries of its result\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Free up any unused memory [CODESPLIT] void shrink ( ) { if ( intervals != null ) { int currentSize = intervalIdx + 1 ; if ( currentSize < intervals . length ) { BitInterval [ ] tmp = new BitInterval [ currentSize ] ; System . arraycopy ( intervals , 0 , tmp , 0 , currentSize ) ; intervals = tmp ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Export region data in JSON format [CODESPLIT] public void execute ( FunctionContext < Object > fc ) { ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean didExport = false ; if ( fc instanceof RegionFunctionContext ) { didExport = exportOnRegion ( ( RegionFunctionContext ) fc ) ; } else { //get region name from argument\r String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) throw new IllegalArgumentException ( \"Region name argument required\" ) ; String regionName = args [ 0 ] ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; if ( region != null ) didExport = exportRegion ( region ) ; else didExport = false ; } rs . lastResult ( didExport ) ; } catch ( Exception e ) { String stackTrace = Debugger . stackTrace ( e ) ; FunctionException functionException = new FunctionException ( stackTrace ) ; LogManager . getLogger ( getClass ( ) ) . error ( stackTrace ) ; rs . sendException ( functionException ) ; throw functionException ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] protected boolean exportRegion ( Region < Object , Object > region ) { if ( region == null ) return false ; if ( PartitionRegionHelper . isPartitionedRegion ( region ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } Logger logger = LogManager . getLogger ( getClass ( ) ) ; logger . info ( \"Exporting region\" + region . getName ( ) ) ; //get name\r String regionName = region . getName ( ) ; File resultFile = DataOpsSecretary . determineFile ( ExportFileType . gfd , regionName ) ; //delete previous\r logger . info ( \"deleting file:\" + resultFile . getAbsolutePath ( ) ) ; boolean wasDeleted = resultFile . delete ( ) ; logger . info ( \"delete:\" + wasDeleted ) ; try { //write data\r RegionSnapshotService < ? , ? > regionSnapshotService = region . getSnapshotService ( ) ; SnapshotOptionsImpl < ? , ? > options = ( SnapshotOptionsImpl < ? , ? > ) regionSnapshotService . createOptions ( ) ; //setting parallelMode=true will cause only the local region data to export\r options . setParallelMode ( true ) ; regionSnapshotService . save ( resultFile , SnapshotFormat . GEMFIRE ) ; return true ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new FunctionException ( \"Error exporting ERROR:\" + e . getMessage ( ) + \" \" + Debugger . stackTrace ( e ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Export region data in JSON format [CODESPLIT] public void execute ( FunctionContext < String [ ] > fc ) { ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean didExport = false ; if ( fc instanceof RegionFunctionContext ) { String [ ] args = fc . getArguments ( ) ; didExport = this . exportRegion ( ( ( RegionFunctionContext ) fc ) . getDataSet ( ) , Organizer . at ( 0 , args ) ) ; } else { didExport = exportRegionByArg ( fc ) ; } rs . lastResult ( didExport ) ; } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; LogManager . getLogger ( getClass ( ) ) . error ( sw . toString ( ) ) ; rs . sendException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private boolean exportRegionByArg ( FunctionContext < String [ ] > fc ) { String [ ] args = fc . getArguments ( ) ; if ( args == null || args . length == 0 ) { throw new FunctionException ( \"Argument not provided\" ) ; } //Get region name from arguments\r String regionName = Organizer . at ( 0 , args ) ; if ( regionName == null || regionName . length ( ) == 0 ) throw new FunctionException ( \"regionName is required at argumeng index 0\" ) ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return exportRegion ( region , Organizer . at ( 1 , args ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public Collection < String > saveSearchResultsWithPageKeys ( TextPageCriteria criteria , Region < String , Collection < ? > > pageKeysRegion ) { if ( criteria == null ) return null ; if ( criteria . getQuery ( ) == null || criteria . getQuery ( ) . length ( ) == 0 ) return null ; if ( criteria . getIndexName ( ) == null || criteria . getIndexName ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( \"Default criteria's indexName is required\" ) ; if ( criteria . getId ( ) == null || criteria . getId ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( \"Default criteria's id is required\" ) ; if ( criteria . getDefaultField ( ) == null || criteria . getDefaultField ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( \"Default criteria's defaultField is required\" ) ; try { LuceneQuery < Object , Object > luceneQuery = luceneService . createLuceneQueryFactory ( ) . create ( criteria . getIndexName ( ) , criteria . getRegionName ( ) , criteria . getQuery ( ) , criteria . getDefaultField ( ) ) ; List < LuceneResultStruct < Object , Object > > list = luceneQuery . findResults ( ) ; luceneQuery . findPages ( ) ; if ( list == null || list . isEmpty ( ) ) return null ; String sortField = criteria . getSortField ( ) ; BeanComparator beanComparator = null ; Collection < Map . Entry < Object , Object > > results = null ; if ( sortField != null && sortField . trim ( ) . length ( ) > 0 ) { beanComparator = new BeanComparator ( sortField , criteria . isSortDescending ( ) ) ; Collection < Map . Entry < Object , Object > > set = new TreeSet < Map . Entry < Object , Object > > ( beanComparator ) ; list . parallelStream ( ) . forEach ( e -> set . add ( new MapEntry < Object , Object > ( e . getKey ( ) , e . getValue ( ) ) ) ) ; results = set ; } else { results = list . stream ( ) . map ( e -> new MapEntry <> ( e . getKey ( ) , e . getValue ( ) ) ) . collect ( Collectors . toList ( ) ) ; } //add to pages List < Collection < Object > > pagesCollection = Organizer . toKeyPages ( results , criteria . getEndIndex ( ) - criteria . getBeginIndex ( ) ) ; int pageIndex = 0 ; String key = null ; ArrayList < String > keys = new ArrayList < String > ( 10 ) ; for ( Collection < Object > page : pagesCollection ) { //store in region key = new StringBuilder ( ) . append ( criteria . getId ( ) ) . append ( \"-\" ) . append ( pageIndex ++ ) . toString ( ) ; pageKeysRegion . put ( key , page ) ; keys . add ( key ) ; } keys . trimToSize ( ) ; return keys ; } catch ( LuceneQueryException e ) { throw new SystemException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public Collection < String > clearSearchResultsByPage ( TextPageCriteria criteria , Region < String , Collection < ? > > pageRegion ) { Collection < String > pageKeys = Querier . query ( \"select * from /\" + criteria . getPageRegionName ( ) + \".keySet() k where k like '\" + criteria . getId ( ) + \"%'\" ) ; pageRegion . removeAll ( pageKeys ) ; return pageKeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < T > Collection < T > search ( String indexName , String regionName , String queryString , String defaultField ) throws Exception { Region < ? , ? > region = GeodeClient . connect ( ) . getRegion ( regionName ) ; String [ ] args = { indexName , regionName , queryString , defaultField } ; return GemFireIO . exeWithResults ( FunctionService . onRegion ( region ) . setArguments ( args ) . setArguments ( args ) , new SimpleLuceneSearchFunction ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public void execute ( FunctionContext < Object > fc ) { ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean results = false ; if ( fc instanceof RegionFunctionContext ) { results = importOnRegion ( ( RegionFunctionContext ) fc ) ; } else { results = importAllRegions ( fc ) ; } rs . lastResult ( results ) ; } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; LogManager . getLogger ( getClass ( ) ) . error ( sw . toString ( ) ) ; rs . sendException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------------------------- [CODESPLIT] private boolean importAllRegions ( FunctionContext < Object > fc ) throws Exception { String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) { throw new FunctionException ( \"Argument not provided\" ) ; } // Get region name from arguments\r String regionName = args [ 0 ] ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return importRegion ( region ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] private boolean importRegion ( Region < Object , Object > region ) throws Exception { JsonNode node , keyNode , valueNode , keyClassName , valueClassName ; Object key , value ; if ( PartitionRegionHelper . isPartitionedRegion ( region ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } // get first\r ObjectMapper mapper = new ObjectMapper ( ) ; // Configure to be very forgiving\r // mapper.configure(Feature.FAIL_ON_INVALID_SUBTYPE, false);\r //\t\tmapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);\r //\t\tmapper.configure(Feature.FAIL_ON_NULL_FOR_PRIMITIVES, false);\r //\t\tmapper.configure(Feature.FAIL_ON_NUMBERS_FOR_ENUMS, false);\r //\r //\t\tKeyDeserializers keyDeserializers = new KeyDeserializers()\r //\t\t{\r //\r //\t\t\t@Override\r //\t\t\tpublic KeyDeserializer findKeyDeserializer(JavaType javatype,\r //\t\t\t\t\tDeserializationConfig deserializationconfig,\r //\t\t\t\t\tBeanDescription beandescription, BeanProperty beanproperty)\r //\t\t\t\t\tthrows JsonMappingException\r //\t\t\t{\r //\t\t\t\treturn new DefaultKeyDeserializer();\r //\t\t\t}\r //\t\t};\r //\r //\t\tmapper.setDeserializerProvider(mapper.getDeserializerProvider()\r //\t\t\t\t.withAdditionalKeyDeserializers(keyDeserializers));\r // read JSON file\r String filePath = new StringBuilder ( this . directoryPath ) . append ( fileSeparator ) . append ( region . getName ( ) ) . append ( suffix ) . toString ( ) ; File file = new File ( filePath ) ; if ( ! file . exists ( ) ) { LogManager . getLogger ( getClass ( ) ) . info ( file . getAbsolutePath ( ) + \" does not exists\" ) ; return false ; } try ( Reader reader = Files . newBufferedReader ( file . toPath ( ) , StandardCharsets . UTF_8 ) ) { // TokenBuffer buffer = new TokenBuffer\r JsonNode tree = mapper . readTree ( reader ) ; Iterator < JsonNode > children = tree . elements ( ) ; if ( children == null || ! children . hasNext ( ) ) { return false ; } while ( children . hasNext ( ) ) { node = children . next ( ) ; keyNode = node . get ( \"key\" ) ; valueNode = node . get ( \"value\" ) ; keyClassName = node . get ( \"keyClassName\" ) ; valueClassName = node . get ( \"valueClassName\" ) ; key = mapper . readValue ( keyNode . traverse ( ) , forClassName ( keyClassName ) ) ; value = mapper . readValue ( valueNode . traverse ( ) , forClassName ( valueClassName ) ) ; region . put ( key , value ) ; } return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<pre > This method will start a single locator and cache server . [CODESPLIT] public void startCluster ( ) throws Exception { IO . mkdir ( Paths . get ( runtimeDir + \"/locator\" ) . toFile ( ) ) ; IO . mkdir ( Paths . get ( runtimeDir + \"/server\" ) . toFile ( ) ) ; Shell shell = new Shell ( ) ; ProcessInfo pi = shell . execute ( location + \"/gfsh\" , \"-e\" , \"start locator  --dir=runtime/locator --bind-address=localhost --J=-D=gemfire.jmx-manager-hostname-for-clients=localhost --J=-D=gemfire.jmx-manager-bind-address=localhost --J=-D=gemfire.http-service-bind-address=localhost --http-service-port=0  --name=locator  --port=10334\" ) ; System . out . println ( pi . exitValue ) ; System . out . println ( pi . output ) ; System . out . println ( pi . error ) ; pi = shell . execute ( location + \"/gfsh\" , \"-e\" , \"start server --name=server --dir=\" + runtimeDir + \"/server --bind-address=localhost  --server-bind-address=localhost --locators=localhost[10334]\" ) ; System . out . println ( pi . exitValue ) ; System . out . println ( \"OUTPUT:\" + pi . output ) ; System . out . println ( \"ERROR:\" + pi . error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public void shutdown ( ) { try ( JMX jmx = JMX . connect ( \"localhost\" , 1099 ) ) { String [ ] members = GemFireMgmt . shutDown ( jmx ) ; Debugger . println ( \"members:\" + Debugger . toString ( members ) ) ; GemFireMgmt . stopLocator ( jmx , \"locator\" ) ; } try { IO . delete ( Paths . get ( runtimeDir + \"/server\" ) . toFile ( ) ) ; } catch ( IOException e ) { Debugger . printWarn ( e ) ; } try { IO . delete ( Paths . get ( runtimeDir + \"/locator\" ) . toFile ( ) ) ; } catch ( IOException e ) { Debugger . printWarn ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait for a given member to startup [CODESPLIT] public void waitForMemberStart ( String member , JMX jmx ) { boolean isRunning = false ; boolean printedStartMember = false ; int count = 0 ; while ( ! isRunning ) { try { isRunning = GemFireInspector . checkMemberStatus ( member , jmx ) ; } catch ( Exception e ) { Debugger . printWarn ( e ) ; } if ( ! printedStartMember ) { Debugger . println ( \"Waiting for member:\" + member + \".  Starting member to continue. \" + \" You can perform a gfsh status command to confirm whether the member is running\" ) ; printedStartMember = true ; } try { delay ( ) ; } catch ( Exception e ) { } if ( count > retryCount ) { throw new RuntimeException ( \"member:\" + member + \" did not start after \" + retryCount + \" checks with a delay of \" + sleepDelay + \" milliseconds\" ) ; } count ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait for a given member to startup [CODESPLIT] public void waitForMemberStop ( String member , JMX jmx ) throws InterruptedException { boolean isRunning = true ; boolean printedStartMember = false ; int count = 0 ; while ( isRunning && count < retryCount ) { isRunning = GemFireInspector . checkMemberStatus ( member , jmx ) ; if ( ! printedStartMember ) { Debugger . println ( \"Waiting for member:\" + member + \" to stop.\" ) ; printedStartMember = true ; } delay ( ) ; count ++ ; } if ( isRunning ) { throw new RuntimeException ( \"member:\" + member + \" failed to stop after \" + retryCount + \" checks with a delay of \" + sleepDelay + \" milliseconds\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public < K , V > Collection < String > saveSearchResultsWithPageKeys ( TextPageCriteria criteria , LuceneQueryProvider queryProvider , Predicate < LuceneResultStruct < K , V > > filter , Region < String , Collection < K > > pageKeysRegion ) { return saveSearchResultsWithPageKeys ( criteria , queryProvider . toString ( ) , filter , pageKeysRegion ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------ [CODESPLIT] public < K , V > Collection < String > saveSearchResultsWithPageKeys ( TextPageCriteria criteria , String query , Predicate < LuceneResultStruct < K , V > > filter , Region < String , Collection < K > > pageKeysRegion ) { if ( criteria == null ) return null ; if ( criteria . getId ( ) == null || criteria . getId ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( \"Default criteria's id is required\" ) ; try { //clearing asynchronously GeodePagination pagination = new GeodePagination ( ) ; pagination . clearSearchResultsByPage ( criteria , pageKeysRegion ) ; List < Map . Entry < K , V > > results = executeQuery ( criteria , query , filter ) ; List < String > keys = pagination . storePaginationMap ( criteria . getId ( ) , criteria . getEndIndex ( ) - criteria . getBeginIndex ( ) , pageKeysRegion , results ) ; return keys ; } catch ( LuceneQueryException e ) { throw new FunctionException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function gets HashMap key = Serializable value = BigInteger [CODESPLIT] @ Override public void execute ( FunctionContext < Object > functionContext ) { try { String [ ] args = ( String [ ] ) functionContext . getArguments ( ) ; if ( args == null || args . length == 0 ) throw new IllegalArgumentException ( \"region argument required\" ) ; String regionName = args [ 0 ] ; if ( regionName == null || regionName . length ( ) == 0 ) throw new IllegalArgumentException ( \"region name argument required\" ) ; Region < Serializable , Object > region = CacheFactory . getAnyInstance ( ) . getRegion ( regionName ) ; if ( region == null ) throw new IllegalArgumentException ( \"region:\" + regionName + \" not found\" ) ; functionContext . getResultSender ( ) . lastResult ( buildCheckSumMap ( region ) ) ; } catch ( Exception e ) { String stack = Debugger . stackTrace ( e ) ; LogManager . getLogger ( getClass ( ) ) . error ( stack ) ; throw new FunctionException ( stack ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build check sum map [CODESPLIT] HashMap < Serializable , BigInteger > buildCheckSumMap ( Region < Serializable , Object > region ) { if ( region . getAttributes ( ) . getDataPolicy ( ) . withPartitioning ( ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } Set < Serializable > keySet = region . keySet ( ) ; if ( keySet == null || keySet . isEmpty ( ) ) return null ; HashMap < Serializable , BigInteger > regionCheckSumMap = new HashMap < Serializable , BigInteger > ( keySet . size ( ) ) ; Object object = null ; Object tmp = null ; for ( Map . Entry < Serializable , Object > entry : region . entrySet ( ) ) { object = entry . getValue ( ) ; if ( PdxInstance . class . isAssignableFrom ( object . getClass ( ) ) ) { tmp = ( ( PdxInstance ) object ) . getObject ( ) ; if ( Serializable . class . isAssignableFrom ( tmp . getClass ( ) ) ) { object = tmp ; } //else use PdxInstance.hashCode } if ( ! ( PdxInstance . class . isAssignableFrom ( object . getClass ( ) ) ) ) { regionCheckSumMap . put ( entry . getKey ( ) , MD . checksum ( object ) ) ; } else { regionCheckSumMap . put ( entry . getKey ( ) , BigInteger . valueOf ( object . hashCode ( ) ) ) ; } } return regionCheckSumMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a GemFire query with no limit [CODESPLIT] @ PostMapping ( path = \"/\" , produces = \"application/json\" ) public String query ( @ RequestBody String query ) throws Exception { return queryLimit ( query , - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a GemFire query [CODESPLIT] @ PostMapping ( path = \"{limit}\" , produces = \"application/json\" ) public String queryLimit ( @ RequestBody String query , @ PathVariable int limit ) throws Exception { if ( query == null || query . length ( ) == 0 ) return null ; try { query = this . appendLimit ( query , limit ) ; Logger logger = LogManager . getLogger ( getClass ( ) ) ; logger . info ( \"QueryService: START query \" + query ) ; Collection < Object > results = querierService . query ( query ) ; logger . info ( \"QueryService: END query \" + query ) ; if ( results == null ) return null ; return gson . toJson ( results , Collection . class ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Frees up any resources no longer needed after the archive file is closed . Returns true if this guy is no longer needed . [CODESPLIT] protected boolean close ( ) { if ( isLoaded ( ) ) { for ( int i = 0 ; i < stats . length ; i ++ ) { if ( stats [ i ] != null ) { if ( ! stats [ i ] . isLoaded ( ) ) { stats [ i ] = null ; } } } return false ; } else { return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forces the value to be wrapped with if it isEqualTo for a string field . [CODESPLIT] private Object valueOf ( String columnName , Object value ) { java . lang . reflect . Field field ; try { field = tableObject . getDeclaredField ( columnName ) ; } catch ( NoSuchFieldException e ) { throw new RuntimeException ( String . format ( \"%s isEqualTo not a field found in %s\" , columnName , tableObject ) ) ; } return field . getType ( ) == String . class ? String . format ( \"\\'%s\\'\" , value ) : value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a TypeMirror is mapped to Sqlite Integer Type [CODESPLIT] boolean isTypeOf ( TypeMirror typeMirror ) { if ( integerKinds . contains ( typeMirror . getKind ( ) ) ) { return true ; } if ( integerObjects . contains ( typeMirror . toString ( ) ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes an object and serializes it to a byte array . Don t enforce that it extends serializable to allow for lists and maps to be passed in . [CODESPLIT] public static < T > byte [ ] serialize ( T object ) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; ObjectOutputStream objectOutputStream = new ObjectOutputStream ( byteArrayOutputStream ) ; objectOutputStream . writeObject ( object ) ; return byteArrayOutputStream . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "De - serialize a byte array back to it s original object . [CODESPLIT] public static < K > K deserialize ( byte [ ] bytes ) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream ( bytes ) ; ObjectInputStream objectInputStream = new ObjectInputStream ( byteArrayInputStream ) ; @ SuppressWarnings ( \"unchecked\" ) final K k = ( K ) objectInputStream . readObject ( ) ; return k ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a class type and constructs it . If the class does not have an empty constructor this will find the parametrized constructor and use nulls and default values to construct the class . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T createInstance ( Class < T > clazz ) { if ( clazz . isInterface ( ) ) { if ( clazz == List . class ) { return ( T ) new ArrayList ( ) ; } else if ( clazz == Map . class ) { return ( T ) new HashMap ( ) ; } throw new UnsupportedOperationException ( \"Interface types can not be instantiated.\" ) ; } ObjectInstantiator instantiator = OBJENESIS . getInstantiatorOf ( clazz ) ; return ( T ) instantiator . newInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the element has the [CODESPLIT] private void checkForTableId ( TableObject tableObject , Element element ) { // Check if user wants to use an id other than _id Id idAnnotation = element . getAnnotation ( Id . class ) ; if ( idAnnotation != null ) { if ( element . asType ( ) . getKind ( ) != TypeKind . LONG && ! ( \"java.lang.Long\" . equals ( element . asType ( ) . toString ( ) ) ) ) { logger . e ( \"@Id must be on a long\" ) ; } // Id attribute set and continue String columnName = Strings . isBlank ( idAnnotation . name ( ) ) // ? element . getSimpleName ( ) . toString ( ) // : idAnnotation . name ( ) ; final TableColumn idColumn = new TableColumn ( columnName , element . getSimpleName ( ) . toString ( ) , element . asType ( ) . toString ( ) , SqliteType . INTEGER ) ; tableObject . setIdColumn ( idColumn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the element has a [CODESPLIT] private void checkForFields ( TableObject tableObject , Element columnElement ) { Column columnAnnotation = columnElement . getAnnotation ( Column . class ) ; if ( columnAnnotation == null ) return ; // Convert the element from a field to a type final Element typeElement = typeUtils . asElement ( columnElement . asType ( ) ) ; final String type = typeElement == null ? columnElement . asType ( ) . toString ( ) : elementUtils . getBinaryName ( ( TypeElement ) typeElement ) . toString ( ) ; TableColumn tableColumn = new TableColumn ( columnElement , type , columnAnnotation . name ( ) ) ; if ( tableColumn . isBlob ( ) && ! tableColumn . isByteArray ( ) ) { String columnType = columnElement . asType ( ) . toString ( ) ; logger . d ( \"Column Element Type: \" + columnType ) ; if ( ! checkForSuperType ( columnElement , Serializable . class ) && ! columnType . equals ( \"java.lang.Byte[]\" ) && ! columnType . startsWith ( \"java.util.Map\" ) && ! columnType . startsWith ( \"java.util.List\" ) ) { logger . e ( String . format ( \"%s in %s is not Serializable and will not be able to be converted to a byte array\" , columnElement . toString ( ) , tableObject . getTableName ( ) ) ) ; } } else if ( tableColumn . isOneToMany ( ) ) { // List<T> should only have one generic type. Get that type and make sure // it has @Table annotation TypeMirror typeMirror = ( ( DeclaredType ) columnElement . asType ( ) ) . getTypeArguments ( ) . get ( 0 ) ; if ( typeUtils . asElement ( typeMirror ) . getAnnotation ( Table . class ) == null ) { logger . e ( \"One to many relationship in class %s where %s is not annotated with @Table\" , tableObject . getTableName ( ) , tableColumn . getColumnName ( ) ) ; } oneToManyCache . put ( typeMirror . toString ( ) , tableObject ) ; TypeElement childColumnElement = elementUtils . getTypeElement ( typeMirror . toString ( ) ) ; tableColumn . setType ( getClassName ( childColumnElement , getPackageName ( childColumnElement ) ) ) ; } else if ( tableColumn . getSqlType ( ) == SqliteType . UNKNOWN ) { @ SuppressWarnings ( \"ConstantConditions\" ) Table annotation = typeElement . getAnnotation ( Table . class ) ; if ( annotation == null ) { logger . e ( String . format ( \"%s in %s needs to be marked as a blob or should be \" + \"annotated with @Table\" , columnElement . toString ( ) , tableObject . getTableName ( ) ) ) ; } tableColumn . setOneToOne ( true ) ; } tableObject . addColumn ( tableColumn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for a supertype returns true if element has a supertype [CODESPLIT] private boolean checkForSuperType ( Element element , Class type ) { List < ? extends TypeMirror > superTypes = typeUtils . directSupertypes ( element . asType ( ) ) ; for ( TypeMirror superType : superTypes ) { if ( superType . toString ( ) . equals ( type . getName ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get table schema [CODESPLIT] private String getSchema ( ) { StringBuilder sb = new StringBuilder ( ) ; Iterator < TableColumn > iterator = columns . iterator ( ) ; while ( iterator . hasNext ( ) ) { TableColumn column = iterator . next ( ) ; if ( column . isOneToMany ( ) ) { if ( ! iterator . hasNext ( ) ) { // remove the extra \", \" after one to many int length = sb . length ( ) ; sb . replace ( length - 2 , length , \"\" ) ; } continue ; } sb . append ( column ) ; if ( iterator . hasNext ( ) ) { sb . append ( \", \" ) ; } } // writes out id_missing for logging, the actual idMissing check happens // by the annotation processor. String idCol = idColumn == null ? \"id_missing\" : idColumn . getColumnName ( ) ; return String . format ( CREATE_TABLE_DEFAULT , getTableName ( ) , idCol , sb . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the java functions required for the internal class [CODESPLIT] void brewJava ( Writer writer ) throws IOException { logger . d ( \"brewJava\" ) ; JavaWriter javaWriter = new JavaWriter ( writer ) ; javaWriter . setCompressingTypes ( false ) ; javaWriter . emitSingleLineComment ( \"Generated code from Shillelagh. Do not modify!\" ) // . emitPackage ( classPackage ) // /* Knows nothing of android types, must use strings. */ // . emitImports ( \"android.content.ContentValues\" , \"android.database.Cursor\" , // \"android.database.DatabaseUtils\" , \"android.database.sqlite.SQLiteDatabase\" ) // . emitImports ( ShillelaghUtil . class , ByteArrayInputStream . class , ByteArrayOutputStream . class , IOException . class , ObjectInputStream . class , ObjectOutputStream . class , LinkedList . class , Date . class , List . class ) // . beginType ( className , \"class\" , EnumSet . of ( PUBLIC , FINAL ) ) ; if ( this . isChildTable ) { emitParentInsert ( javaWriter ) ; emitSelectAll ( javaWriter ) ; } emitInsert ( javaWriter ) ; emitOneToOneInsert ( javaWriter ) ; emitGetId ( javaWriter ) ; emitCreateTable ( javaWriter ) ; emitDropTable ( javaWriter ) ; emitUpdate ( javaWriter ) ; emitUpdateColumnId ( javaWriter ) ; emitDeleteWithId ( javaWriter ) ; emitDeleteWithObject ( javaWriter ) ; emitMapCursorToObject ( javaWriter ) ; emitSingleMap ( javaWriter ) ; emitSelectById ( javaWriter ) ; javaWriter . endType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a way to get an id for foreign keys [CODESPLIT] private void emitGetId ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitGetId\" ) ; javaWriter . beginMethod ( \"long\" , GET_ID_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , \"value\" ) . emitStatement ( \"return value.%s\" , idColumn . getMemberName ( ) ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the function for creating the table [CODESPLIT] private void emitCreateTable ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitCreateTable\" ) ; javaWriter . beginMethod ( \"void\" , $$ CREATE_TABLE_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"db.execSQL(\\\"%s\\\")\" , getSchema ( ) ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the function dropping the table [CODESPLIT] private void emitDropTable ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitDropTable\" ) ; javaWriter . beginMethod ( \"void\" , $$ DROP_TABLE_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"db.execSQL(\\\"DROP TABLE IF EXISTS %s\\\")\" , getTableName ( ) ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the function for inserting a new value into the database [CODESPLIT] private void emitInsert ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitInsert\" ) ; String tableName = getTableName ( ) ; javaWriter . beginMethod ( \"void\" , $$ INSERT_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , \"element\" , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"ContentValues values = new ContentValues()\" ) ; List < TableColumn > childColumns = Lists . newLinkedList ( ) ; for ( TableColumn column : columns ) { String columnName = column . getColumnName ( ) ; String memberName = column . getMemberName ( ) ; if ( column . isBlob ( ) && ! column . isByteArray ( ) ) { javaWriter . emitStatement ( \"values.put(\\\"%s\\\", %s(element.%s))\" , columnName , SERIALIZE_FUNCTION , memberName ) ; } else if ( column . isOneToOne ( ) ) { javaWriter . emitStatement ( \"%s%s.%s(element.%s, db)\" , column . getType ( ) , $$ SUFFIX , INSERT_ONE_TO_ONE , column . getColumnName ( ) ) . emitStatement ( \"values.put(\\\"%s\\\", %s%s.%s(element.%s))\" , columnName , column . getType ( ) , $$ SUFFIX , GET_ID_FUNCTION , memberName ) ; } else if ( column . isDate ( ) ) { javaWriter . emitStatement ( \"values.put(\\\"%s\\\", element.%s.getTime())\" , columnName , memberName ) ; } else if ( column . isOneToMany ( ) ) { childColumns . add ( column ) ; } else if ( ! column . isOneToManyChild ( ) ) { javaWriter . emitStatement ( \"values.put(\\\"%s\\\", element.%s)\" , columnName , memberName ) ; } } javaWriter . emitStatement ( \"db.insert(\\\"%s\\\", null, values)\" , tableName ) ; if ( ! childColumns . isEmpty ( ) ) { javaWriter . emitStatement ( \"long id = DatabaseUtils.longForQuery(db, \" + \"\\\"SELECT ROWID FROM %s ORDER BY ROWID DESC LIMIT 1\\\", null)\" , tableName ) ; } for ( TableColumn childColumn : childColumns ) { javaWriter . emitStatement ( \"%s%s.%s(id, element.%s, db)\" , childColumn . getType ( ) , $$ SUFFIX , PARENT_INSERT_FUNCTION , childColumn . getMemberName ( ) ) ; } javaWriter . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the function for updating an object [CODESPLIT] private void emitUpdate ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitUpdate\" ) ; javaWriter . beginMethod ( \"void\" , $$ UPDATE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , \"element\" , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"ContentValues values = new ContentValues()\" ) ; for ( TableColumn column : columns ) { String columnName = column . getColumnName ( ) ; String memberName = column . getMemberName ( ) ; if ( column . getSqlType ( ) == SqliteType . BLOB && ! column . isByteArray ( ) ) { javaWriter . emitStatement ( \"values.put(\\\"%s\\\", %s(element.%s))\" , columnName , SERIALIZE_FUNCTION , memberName ) ; } else if ( column . isOneToOne ( ) ) { javaWriter . emitStatement ( \"values.put(\\\"%s\\\", %s%s.%s(element.%s))\" , columnName , column . getType ( ) , $$ SUFFIX , GET_ID_FUNCTION , memberName ) ; } else if ( column . isDate ( ) ) { javaWriter . emitStatement ( \"values.put(\\\"%s\\\", element.%s.getTime())\" , columnName , memberName ) ; } else if ( column . isOneToMany ( ) ) { javaWriter . beginControlFlow ( \"for (%s child : element.%s)\" , column . getType ( ) . replace ( \"$\" , \".\" ) , column . getColumnName ( ) ) . emitStatement ( \"%s%s.%s(child, db)\" , column . getType ( ) , $$ SUFFIX , $$ UPDATE_OBJECT_FUNCTION ) . endControlFlow ( ) ; } else if ( column . isOneToManyChild ( ) ) { // TODO: actually no way of actually updating this value directly add a wrapper? } else { javaWriter . emitStatement ( \"values.put(\\\"%s\\\", element.%s)\" , columnName , memberName ) ; } } javaWriter . emitStatement ( \"db.update(\\\"%s\\\", values, \\\"%s = \\\" + element.%s, null)\" , getTableName ( ) , idColumn . getColumnName ( ) , idColumn . getMemberName ( ) ) ; javaWriter . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the id of the object to the last insert [CODESPLIT] private void emitUpdateColumnId ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitUpdateColumnId\" ) ; // Updates the column id for the last inserted row javaWriter . beginMethod ( \"void\" , $$ UPDATE_ID_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , \"element\" , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"long id = DatabaseUtils.longForQuery(db, \\\"%s\\\", null)\" , String . format ( GET_ID_OF_LAST_INSERTED_ROW_SQL , getTableName ( ) ) ) . emitStatement ( \"element.%s = id\" , idColumn . getMemberName ( ) ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the function for deleting an object by id [CODESPLIT] private void emitDeleteWithId ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitDeleteWithId\" ) ; javaWriter . beginMethod ( \"void\" , $$ DELETE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , \"Long\" , \"id\" , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"db.delete(\\\"%s\\\", \\\"%s = \\\" + id, null)\" , getTableName ( ) , idColumn . getColumnName ( ) ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the function for deleting an object from the table [CODESPLIT] private void emitDeleteWithObject ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitDeleteWithObject\" ) ; javaWriter . beginMethod ( \"void\" , $$ DELETE_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , getTargetClass ( ) , \"element\" , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"%s(element.%s, db)\" , $$ DELETE_OBJECT_FUNCTION , idColumn . getMemberName ( ) ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the function for mapping a cursor to the object after executing a sql statement [CODESPLIT] private void emitMapCursorToObject ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitMapCursorToObject\" ) ; final String targetClass = getTargetClass ( ) ; javaWriter . beginMethod ( \"List<\" + targetClass + \">\" , $$ MAP_OBJECT_FUNCTION , EnumSet . of ( PUBLIC , STATIC ) , \"Cursor\" , \"cursor\" , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"List<%s> tableObjects = new LinkedList<%s>()\" , targetClass , targetClass ) . beginControlFlow ( \"if (cursor.moveToFirst())\" ) . beginControlFlow ( \"while (!cursor.isAfterLast())\" ) . emitStatement ( \"%s tableObject = %s(cursor, db)\" , targetClass , $$ MAP_SINGLE_FUNCTION ) . emitStatement ( \"tableObjects.add(tableObject)\" ) . emitStatement ( \"cursor.moveToNext()\" ) . endControlFlow ( ) . endControlFlow ( ) . emitStatement ( \"return tableObjects\" ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates function for getting an object by value [CODESPLIT] private void emitSelectById ( JavaWriter javaWriter ) throws IOException { logger . d ( \"emitSelectById\" ) ; javaWriter . beginMethod ( getTargetClass ( ) , $$ GET_OBJECT_BY_ID , EnumSet . of ( PUBLIC , STATIC ) , \"long\" , \"id\" , \"SQLiteDatabase\" , \"db\" ) . emitStatement ( \"Cursor cursor = db.rawQuery(\\\"SELECT * FROM %s WHERE %s  = id\\\", null)\" , getTableName ( ) , idColumn . getColumnName ( ) ) . emitStatement ( \"%s value = %s(cursor, db).get(0)\" , getTargetClass ( ) , $$ MAP_OBJECT_FUNCTION ) . emitStatement ( \"cursor.close()\" ) . emitStatement ( \"return value\" ) . endMethod ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a query and returns the results wrapped in an observable [CODESPLIT] public final Observable < T > toObservable ( ) { if ( ! HAS_RX_JAVA ) { throw new RuntimeException ( \"RxJava not available! Add RxJava to your build to use this feature\" ) ; } return shillelagh . getObservable ( tableObject , new CursorLoader ( ) { @ Override public Cursor getCursor ( ) { return shillelagh . rawQuery ( query . toString ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check to ensure that the column name provided is valid [CODESPLIT] final void checkColumnName ( String columnName ) { try { tableObject . getDeclaredField ( columnName ) ; } catch ( NoSuchFieldException e ) { throw new RuntimeException ( String . format ( \"%s isEqualTo not a field found in %s\" , columnName , tableObject ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a string there if not returns the default string [CODESPLIT] static String valueOrDefault ( String string , String defaultString ) { return isBlank ( string ) ? defaultString : string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capitalizes the first letter of the string passed in [CODESPLIT] static String capitalize ( String string ) { if ( isBlank ( string ) ) { return \"\" ; } char first = string . charAt ( 0 ) ; if ( Character . isUpperCase ( first ) ) { return string ; } else { return Character . toUpperCase ( first ) + string . substring ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a TypeMirror is mapped to Sqlite Type [CODESPLIT] boolean isTypeOf ( TypeMirror typeMirror ) { if ( realKinds . contains ( typeMirror . getKind ( ) ) ) { return true ; } if ( realObjects . contains ( typeMirror . toString ( ) ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Order the results in descending order [CODESPLIT] public Builder < T > descending ( ) { this . query . append ( \" DESC\" ) ; return new Builder < T > ( shillelagh , tableObject , query ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read temperature from the sensors . [CODESPLIT] public float readTemperature ( ) throws IOException { byte [ ] encoded = Files . readAllBytes ( new File ( deviceFile , \"w1_slave\" ) . toPath ( ) ) ; String tmp = new String ( encoded ) ; int tmpIndex = tmp . indexOf ( \"t=\" ) ; if ( tmpIndex < 0 ) { throw new IOException ( \"Could not read temperature!\" ) ; } return Integer . parseInt ( tmp . substring ( tmpIndex + 2 ) . trim ( ) ) / 1000f ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a type to the corresponding Cursor get function . For mapping objects between the database and java . If a type is not found getBlob is returned [CODESPLIT] public static String get ( String type ) { final String returnValue = SUPPORTED_CURSOR_METHODS . get ( type ) ; return returnValue != null ? returnValue : SUPPORTED_CURSOR_METHODS . get ( BLOB ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out debug logs will only print if { [CODESPLIT] void d ( String message , Object ... args ) { if ( DEBUG ) { messenger . printMessage ( NOTE , formatString ( message , args ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out notes [CODESPLIT] void n ( String message , Object ... args ) { messenger . printMessage ( NOTE , formatString ( message , args ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print out errors this will stop the build from succeeding [CODESPLIT] void e ( String message , Object ... args ) { messenger . printMessage ( ERROR , formatString ( message , args ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all icon fonts from bundle . [CODESPLIT] public static List < IconFont > getIconFonts ( ) { List < IconFont > list = new ArrayList <> ( ) ; list . add ( GoogleMaterialDesignIcons . getIconFont ( ) ) ; list . add ( Elusive . getIconFont ( ) ) ; list . add ( Entypo . getIconFont ( ) ) ; list . add ( FontAwesome . getIconFont ( ) ) ; list . add ( Iconic . getIconFont ( ) ) ; list . add ( Typicons . getIconFont ( ) ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all icons from bundle . [CODESPLIT] public static List < IconCode > getIcons ( ) { List < IconCode > list = new ArrayList <> ( ) ; for ( IconCode icon : GoogleMaterialDesignIcons . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Elusive . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Entypo . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : FontAwesome . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Iconic . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Typicons . values ( ) ) { list . add ( icon ) ; } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the next data point in the approximation of the solution . [CODESPLIT] @ Override public DataPoint nextPoint ( final float h ) { m_fY += h * m_aEquation . at ( m_fX , m_fY ) ; m_fX += h ; return new DataPoint ( m_fX , m_fY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add new data point : Augment the divided difference table by appending a new entry at the bottom of each column . [CODESPLIT] public void addDataPoint ( final DataPoint dataPoint ) { if ( m_nDataPoints >= m_aData . length ) return ; m_aData [ m_nDataPoints ] = dataPoint ; m_aDivDiff [ m_nDataPoints ] [ 0 ] = dataPoint . getY ( ) ; ++ m_nDataPoints ; for ( int order = 1 ; order < m_nDataPoints ; ++ order ) { final int bottom = m_nDataPoints - order - 1 ; final float numerator = m_aDivDiff [ bottom + 1 ] [ order - 1 ] - m_aDivDiff [ bottom ] [ order - 1 ] ; final float denominator = m_aData [ bottom + order ] . getX ( ) - m_aData [ bottom ] . getX ( ) ; m_aDivDiff [ bottom ] [ order ] = numerator / denominator ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value of the polynomial interpolation function at x . ( Implementation of Evaluatable . ) [CODESPLIT] public float at ( final float x ) { if ( m_nDataPoints < 2 ) return Float . NaN ; float y = m_aDivDiff [ 0 ] [ 0 ] ; float xFactor = 1 ; // Compute the value of the function. for ( int order = 1 ; order < m_nDataPoints ; ++ order ) { xFactor = xFactor * ( x - m_aData [ order - 1 ] . getX ( ) ) ; y = y + xFactor * m_aDivDiff [ 0 ] [ order ] ; } return y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the Sld Editor layout and attach handlers to the actions . [CODESPLIT] public VLayout createSldEditorLayout ( ) { final VLayout vLayout = new VLayout ( ) ; toolStrip = new ToolStrip ( ) ; toolStrip . setWidth100 ( ) ; codeMirrorPanel = new CodeMirrorPanel ( ) ; WidgetCanvas canvas = new WidgetCanvas ( codeMirrorPanel ) ; canvas . setWidth100 ( ) ; canvas . setHeight100 ( ) ; vLayout . addMember ( toolStrip ) ; vLayout . addMember ( canvas ) ; ToolStripButton saveButton = new ToolStripButton ( ) ; saveButton . setIcon ( \"[ISOMORPHIC]/\" + \"icons/silk/disk.png\" ) ; saveButton . setTitle ( msg . saveButtonTitle ( ) ) ; saveButton . setTooltip ( msg . saveButtonTooltip ( ) ) ; saveButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onSaveButton ( ) ; } } ) ; ToolStripButton cancelButton = new ToolStripButton ( ) ; cancelButton . setIcon ( \"[ISOMORPHIC]/\" + \"icons/silk/cancel.png\" ) ; cancelButton . setTitle ( msg . cancelButtonTitle ( ) ) ; cancelButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onCancelButton ( ) ; } } ) ; ToolStripButton validateButton = new ToolStripButton ( ) ; validateButton . setIcon ( \"[ISOMORPHIC]/\" + \"icons/silk/tick.png\" ) ; validateButton . setTitle ( msg . validateButtonTitle ( ) ) ; validateButton . setTooltip ( msg . validateButtonTooltip ( ) ) ; validateButton . addClickHandler ( new ClickHandler ( ) { @ Override public void onClick ( ClickEvent clickEvent ) { presenter . onValidateButton ( ) ; } } ) ; ToolStripButton formatBtn = new ToolStripButton ( ) ; formatBtn . setIcon ( \"[ISOMORPHIC]/\" + \"icons/silk/text_align_left.png\" ) ; formatBtn . setTitle ( msg . formatButtonTitle ( ) ) ; formatBtn . setTooltip ( msg . formatButtonTooltip ( ) ) ; formatBtn . addClickHandler ( new ClickHandler ( ) { public void onClick ( ClickEvent event ) { presenter . onFormatButton ( ) ; } } ) ; selectTemplate = new SelectItem ( ) ; selectTemplate . setTitle ( msg . templateSelectTitle ( ) ) ; selectTemplate . setTooltip ( msg . templateSelectTooltip ( ) ) ; selectTemplate . setWidth ( 200 ) ; selectTemplate . addChangeHandler ( new ChangeHandler ( ) { @ Override public void onChange ( ChangeEvent changeEvent ) { presenter . onTemplateSelect ( ( String ) changeEvent . getValue ( ) ) ; } } ) ; toolStrip . addFormItem ( selectTemplate ) ; toolStrip . addButton ( saveButton ) ; toolStrip . addButton ( validateButton ) ; toolStrip . addButton ( formatBtn ) ; /*\n\t\t * toolStrip.addSeparator(); toolStrip.addButton(saveButton);\n\t\t */ toolStrip . addFill ( ) ; toolStrip . addButton ( cancelButton ) ; return vLayout ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create background content decoration for the widget tab . [CODESPLIT] private HTMLFlow getBackgroundDecoration ( ) { // Show some background content in the tab. HTMLFlow htmlFlow = new HTMLFlow ( ) ; htmlFlow . setWidth100 ( ) ; htmlFlow . setHeight100 ( ) ; String contents = \"<div style='margin-left: 5px; font-size: 100pt; font-weight: bold; color:#DDFFDD'>GEOMAJAS</div>\" + \"<div style='margin-left: 10px; margin-top:-70px; font-size: 50pt; color:#CCCCCC'>SLD-Editor</div>\" + \"<div style='margin-left: 10px; margin-top:-15px; font-size: 28pt; color:#DDDDDD'>EXPERT-mode</div>\" ; htmlFlow . setContents ( contents ) ; return htmlFlow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute and return x^power . [CODESPLIT] public static double raise ( final double px , final int pexponent ) { double x = px ; int exponent = pexponent ; if ( exponent < 0 ) return 1 / raise ( x , - exponent ) ; double power = 1 ; // Loop to compute x^exponent. while ( exponent > 0 ) { // Is the rightmost exponent bit a 1? if ( ( exponent & 1 ) == 1 ) power *= x ; // Square x and shift the exponent 1 bit to the right. x *= x ; exponent >>= 1 ; } return power ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the values of this matrix . [CODESPLIT] public float [ ] copyValues1D ( ) { final float v [ ] = new float [ m_nRows ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { v [ r ] = m_aValues [ r ] [ 0 ] ; } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this column vector from an array of values . [CODESPLIT] protected void set ( final float values [ ] ) { this . m_nRows = values . length ; this . m_nCols = 1 ; this . m_aValues = new float [ m_nRows ] [ 1 ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { this . m_aValues [ r ] [ 0 ] = values [ r ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the Euclidean norm . [CODESPLIT] public float norm ( ) { double t = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final float v = m_aValues [ r ] [ 0 ] ; t += v * v ; } return ( float ) Math . sqrt ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the vector values . [CODESPLIT] public void print ( ) { for ( int r = 0 ; r < m_nRows ; ++ r ) { System . out . print ( \"  \" + m_aValues [ r ] [ 0 ] ) ; } System . out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute x^exponent to a given scale . Uses the same algorithm as class numbercruncher . mathutils . IntPower . [CODESPLIT] public static BigDecimal intPower ( @ Nonnull final BigDecimal px , final long pexponent , final int scale ) { BigDecimal x = px ; long exponent = pexponent ; // If the exponent is negative, compute 1/(x^-exponent). if ( exponent < 0 ) { return BigDecimal . ONE . divide ( intPower ( x , - exponent , scale ) , scale , RoundingMode . HALF_EVEN ) ; } BigDecimal power = BigDecimal . ONE ; // Loop to compute value^exponent. while ( exponent > 0 ) { // Is the rightmost bit a 1? if ( ( exponent & 1 ) == 1 ) { power = power . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; } // Square x and shift exponent 1 bit to the right. x = x . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; exponent >>= 1 ; Thread . yield ( ) ; } return power ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the integral root of x to a given scale x &ge ; 0 . Use Newton s algorithm . [CODESPLIT] public static BigDecimal intRoot ( @ Nonnull final BigDecimal px , final long index , final int scale ) { BigDecimal x = px ; // Check that x >= 0. if ( x . signum ( ) < 0 ) { throw new IllegalArgumentException ( \"x < 0: \" + x ) ; } final int sp1 = scale + 1 ; final BigDecimal n = x ; final BigDecimal i = BigDecimal . valueOf ( index ) ; final BigDecimal im1 = BigDecimal . valueOf ( index - 1 ) ; final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; BigDecimal xPrev ; // The initial approximation is x/index. x = x . divide ( i , scale , RoundingMode . HALF_EVEN ) ; // Loop until the approximations converge // (two successive approximations are equal after rounding). do { // x^(index-1) final BigDecimal xToIm1 = intPower ( x , index - 1 , sp1 ) ; // x^index final BigDecimal xToI = x . multiply ( xToIm1 ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // n + (index-1)*(x^index) final BigDecimal numerator = n . add ( im1 . multiply ( xToI ) ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // (index*(x^(index-1)) final BigDecimal denominator = i . multiply ( xToIm1 ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // x = (n + (index-1)*(x^index)) / (index*(x^(index-1))) xPrev = x ; x = numerator . divide ( denominator , sp1 , RoundingMode . DOWN ) ; Thread . yield ( ) ; } while ( x . subtract ( xPrev ) . abs ( ) . compareTo ( tolerance ) > 0 ) ; return x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute e^x to a given scale . Break x into its whole and fraction parts and compute ( e^ ( 1 + fraction / whole )) ^whole using Taylor s formula . [CODESPLIT] public static BigDecimal exp ( final BigDecimal x , final int scale ) { // e^0 = 1 if ( x . signum ( ) == 0 ) { return BigDecimal . ONE ; } // If x is negative, return 1/(e^-x). if ( x . signum ( ) == - 1 ) { return BigDecimal . ONE . divide ( exp ( x . negate ( ) , scale ) , scale , RoundingMode . HALF_EVEN ) ; } // Compute the whole part of x. BigDecimal xWhole = x . setScale ( 0 , RoundingMode . DOWN ) ; // If there isn't a whole part, compute and return e^x. if ( xWhole . signum ( ) == 0 ) return _expTaylor ( x , scale ) ; // Compute the fraction part of x. final BigDecimal xFraction = x . subtract ( xWhole ) ; // z = 1 + fraction/whole final BigDecimal z = BigDecimal . ONE . add ( xFraction . divide ( xWhole , scale , RoundingMode . HALF_EVEN ) ) ; // t = e^z final BigDecimal t = _expTaylor ( z , scale ) ; final BigDecimal maxLong = BigDecimal . valueOf ( Long . MAX_VALUE ) ; BigDecimal result = BigDecimal . ONE ; // Compute and return t^whole using intPower(). // If whole > Long.MAX_VALUE, then first compute products // of e^Long.MAX_VALUE. while ( xWhole . compareTo ( maxLong ) >= 0 ) { result = result . multiply ( intPower ( t , Long . MAX_VALUE , scale ) ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; xWhole = xWhole . subtract ( maxLong ) ; Thread . yield ( ) ; } return result . multiply ( intPower ( t , xWhole . longValue ( ) , scale ) ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute e^x to a given scale by the Taylor series . [CODESPLIT] private static BigDecimal _expTaylor ( final BigDecimal x , final int scale ) { BigDecimal factorial = BigDecimal . ONE ; BigDecimal xPower = x ; BigDecimal sumPrev ; // 1 + x BigDecimal sum = x . add ( BigDecimal . ONE ) ; // Loop until the sums converge // (two successive sums are equal after rounding). int i = 2 ; do { // x^i xPower = xPower . multiply ( x ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; // i! factorial = factorial . multiply ( BigDecimal . valueOf ( i ) ) ; // x^i/i! final BigDecimal term = xPower . divide ( factorial , scale , RoundingMode . HALF_EVEN ) ; // sum = sum + x^i/i! sumPrev = sum ; sum = sum . add ( term ) ; ++ i ; Thread . yield ( ) ; } while ( sum . compareTo ( sumPrev ) != 0 ) ; return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the natural logarithm of x to a given scale x &gt ; 0 . [CODESPLIT] public static BigDecimal ln ( @ Nonnull final BigDecimal x , final int scale ) { // Check that x > 0. if ( x . signum ( ) <= 0 ) { throw new IllegalArgumentException ( \"x <= 0: \" + x ) ; } // The number of digits to the left of the decimal point. final int magnitude = x . toString ( ) . length ( ) - x . scale ( ) - 1 ; if ( magnitude < 3 ) { return _lnNewton ( x , scale ) ; } // Compute magnitude*ln(x^(1/magnitude)). // x^(1/magnitude) final BigDecimal root = intRoot ( x , magnitude , scale ) ; // ln(x^(1/magnitude)) final BigDecimal lnRoot = _lnNewton ( root , scale ) ; // magnitude*ln(x^(1/magnitude)) return BigDecimal . valueOf ( magnitude ) . multiply ( lnRoot ) . setScale ( scale , RoundingMode . HALF_EVEN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the natural logarithm of x to a given scale x > 0 . Use Newton s algorithm . [CODESPLIT] private static BigDecimal _lnNewton ( @ Nonnull final BigDecimal px , final int scale ) { BigDecimal x = px ; final int sp1 = scale + 1 ; final BigDecimal n = x ; BigDecimal term ; // Convergence tolerance = 5*(10^-(scale+1)) final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; // Loop until the approximations converge // (two successive approximations are within the tolerance). do { // e^x final BigDecimal eToX = exp ( x , sp1 ) ; // (e^x - n)/e^x term = eToX . subtract ( n ) . divide ( eToX , sp1 , RoundingMode . DOWN ) ; // x - (e^x - n)/e^x x = x . subtract ( term ) ; Thread . yield ( ) ; } while ( term . compareTo ( tolerance ) > 0 ) ; return x . setScale ( scale , RoundingMode . HALF_EVEN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the arctangent of x to a given scale |x| &lt ; 1 [CODESPLIT] public static BigDecimal arctan ( @ Nonnull final BigDecimal x , final int scale ) { // Check that |x| < 1. if ( x . abs ( ) . compareTo ( BigDecimal . ONE ) >= 0 ) { throw new IllegalArgumentException ( \"|x| >= 1: \" + x ) ; } // If x is negative, return -arctan(-x). if ( x . signum ( ) == - 1 ) { return arctan ( x . negate ( ) , scale ) . negate ( ) ; } return _arctanTaylor ( x , scale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the arctangent of x to a given scale by the Taylor series |x| < 1 [CODESPLIT] private static BigDecimal _arctanTaylor ( final BigDecimal x , final int scale ) { final int sp1 = scale + 1 ; int i = 3 ; boolean addFlag = false ; BigDecimal power = x ; BigDecimal sum = x ; BigDecimal term ; // Convergence tolerance = 5*(10^-(scale+1)) final BigDecimal tolerance = BigDecimal . valueOf ( 5 ) . movePointLeft ( sp1 ) ; // Loop until the approximations converge // (two successive approximations are within the tolerance). do { // x^i power = power . multiply ( x ) . multiply ( x ) . setScale ( sp1 , RoundingMode . HALF_EVEN ) ; // (x^i)/i term = power . divide ( BigDecimal . valueOf ( i ) , sp1 , RoundingMode . HALF_EVEN ) ; // sum = sum +- (x^i)/i sum = addFlag ? sum . add ( term ) : sum . subtract ( term ) ; i += 2 ; addFlag = ! addFlag ; Thread . yield ( ) ; } while ( term . compareTo ( tolerance ) > 0 ) ; return sum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the square root of x to a given scale x &ge ; 0 . Use Newton s algorithm . [CODESPLIT] public static BigDecimal sqrt ( @ Nonnull final BigDecimal x , final int scale ) { // Check that x >= 0. if ( x . signum ( ) < 0 ) { throw new IllegalArgumentException ( \"x < 0: \" + x ) ; } // n = x*(10^(2*scale)) final BigInteger n = x . movePointRight ( scale << 1 ) . toBigInteger ( ) ; // The first approximation is the upper half of n. final int bits = ( n . bitLength ( ) + 1 ) >> 1 ; BigInteger ix = n . shiftRight ( bits ) ; BigInteger ixPrev ; // Loop until the approximations converge // (two successive approximations are equal after rounding). do { ixPrev = ix ; // x = (x + n/x)/2 ix = ix . add ( n . divide ( ix ) ) . shiftRight ( 1 ) ; Thread . yield ( ) ; } while ( ix . compareTo ( ixPrev ) != 0 ) ; return new BigDecimal ( ix , scale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the string containing the digits of pi . [CODESPLIT] protected void printPi ( final String piString ) { System . out . print ( \"\\npi = \" + piString . substring ( 0 , 2 ) ) ; int index = 2 ; int line = 0 ; int group = 0 ; final int length = piString . length ( ) ; // Loop for each group of 5 digits while ( index + 5 < length ) { System . out . print ( piString . substring ( index , index + 5 ) + \" \" ) ; index += 5 ; // End of line after 10 groups. if ( ++ group == 10 ) { System . out . println ( ) ; // Print a blank line after 10 lines. if ( ++ line == 10 ) { System . out . println ( ) ; line = 0 ; } System . out . print ( \"       \" ) ; group = 0 ; } } // Print the last partial line. if ( index < length ) { System . out . println ( piString . substring ( index ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a timestamp string that contains the elapsed time period . [CODESPLIT] protected String timestamp ( final long time ) { // Current time followed by elapsed time as (hh:mm:ss). final LocalDateTime aLDT = PDTFactory . getCurrentLocalDateTime ( ) ; final LocalDateTime aOld = PDTFactory . createLocalDateTime ( time ) ; return aLDT . toLocalTime ( ) . toString ( ) + \" (\" + Duration . between ( aOld , aLDT ) . toString ( ) + \")\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the minimum and maximum random values . [CODESPLIT] public void setLimits ( final float rMin , final float rMax ) { this . m_fMin = rMin ; this . m_fMax = rMax ; this . m_fWidth = ( rMax - rMin ) / m_n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine a random value s interval and count it . [CODESPLIT] public void put ( final float r ) { // Ignore the value if it's out of range. if ( ( r < m_fMin ) || ( r > m_fMax ) ) return ; // Determine its interval and count it. final int i = ( int ) ( ( r - m_fMin ) / m_fWidth ) ; ++ m_aCounters [ i ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the counter values as a horizontal bar chart . Scale the chart so that the longest bar is MAX_BAR_SIZE . [CODESPLIT] public void print ( ) { // Get the longest bar's length. int maxCount = 0 ; for ( int i = 0 ; i < m_n ; ++ i ) { maxCount = Math . max ( maxCount , m_aCounters [ i ] ) ; } // Compute the scaling factor. final float factor = ( ( float ) MAX_BAR_SIZE ) / maxCount ; // Loop to print each bar. for ( int i = 0 ; i < m_n ; ++ i ) { final int b = m_aCounters [ i ] ; // Interval number. m_aAlignRight . print ( i , 2 ) ; m_aAlignRight . print ( b , 7 ) ; System . out . print ( \": \" ) ; // Bar. final int length = Math . round ( factor * b ) ; for ( int j = 0 ; j < length ; ++ j ) System . out . print ( \"*\" ) ; System . out . println ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add another complex number to this one . [CODESPLIT] public Complex add ( final Complex z ) { return new Complex ( m_fReal + z . real ( ) , m_fImaginary + z . imaginary ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtract another complex number from this one . [CODESPLIT] public Complex subtract ( final Complex z ) { return new Complex ( m_fReal - z . real ( ) , m_fImaginary - z . imaginary ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply this complex number by another one . [CODESPLIT] public Complex multiply ( final Complex z ) { return new Complex ( m_fReal * z . real ( ) - m_fImaginary * z . imaginary ( ) , m_fReal * z . imaginary ( ) + m_fImaginary * z . real ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Divide this complex number by another one . [CODESPLIT] public Complex divide ( final Complex z ) { final float denom = z . real ( ) * z . real ( ) + z . imaginary ( ) * z . imaginary ( ) ; final float qr = ( m_fReal * z . real ( ) + m_fImaginary * z . imaginary ( ) ) / denom ; final float qi = ( m_fImaginary * z . real ( ) - m_fReal * z . imaginary ( ) ) / denom ; return new Complex ( qr , qi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the values of this matrix . [CODESPLIT] @ Nonnull @ ReturnsMutableCopy public float [ ] copyValues1D ( ) { final float v [ ] = new float [ m_nCols ] ; for ( int c = 0 ; c < m_nCols ; ++ c ) v [ ] = m_aValues [ 0 ] [ ] ; return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this row vector from a matrix . Only the first row is used . [CODESPLIT] private void _set ( final Matrix m ) { m_nRows = 1 ; m_nCols = m . m_nCols ; m_aValues = m . m_aValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the Euclidean norm . [CODESPLIT] public float norm ( ) { double t = 0 ; for ( int c = 0 ; c < m_nCols ; ++ c ) { final float v = m_aValues [ 0 ] [ c ] ; t += v * v ; } return ( float ) Math . sqrt ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the vector values . [CODESPLIT] public void print ( ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { System . out . print ( \"  \" + m_aValues [ 0 ] [ c ] ) ; } System . out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value of element [ r c ] in the matrix . [CODESPLIT] public float at ( final int r , final int c ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) || ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } return m_aValues [ r ] [ c ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a row of this matrix . [CODESPLIT] public RowVector getRow ( final int r ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } final RowVector rv = new RowVector ( m_nCols ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { rv . m_aValues [ 0 ] [ c ] = m_aValues [ r ] [ c ] ; } return rv ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a column of this matrix . [CODESPLIT] public ColumnVector getColumn ( final int c ) throws MatrixException { if ( ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } final ColumnVector cv = new ColumnVector ( m_nRows ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { cv . m_aValues [ r ] [ 0 ] = m_aValues [ r ] [ c ] ; } return cv ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the values of this matrix . [CODESPLIT] public float [ ] [ ] copyValues2D ( ) { final float v [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { v [ r ] [ c ] = m_aValues [ r ] [ c ] ; } } return v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value of element [ r c ] . [CODESPLIT] public void set ( final int r , final int c , final float value ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) || ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } m_aValues [ r ] [ c ] = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this matrix from a 2 - d array of values . If the rows do not have the same length then the matrix column count is the length of the shortest row . [CODESPLIT] protected void set ( final float values [ ] [ ] ) { m_nRows = values . length ; m_nCols = values [ 0 ] . length ; m_aValues = values ; for ( int r = 1 ; r < m_nRows ; ++ r ) { m_nCols = Math . min ( m_nCols , values [ r ] . length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a row of this matrix from a row vector . [CODESPLIT] public void setRow ( final RowVector rv , final int r ) throws MatrixException { if ( ( r < 0 ) || ( r >= m_nRows ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( m_nCols != rv . m_nCols ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int c = 0 ; c < m_nCols ; ++ c ) { m_aValues [ r ] [ c ] = rv . m_aValues [ 0 ] [ c ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a column of this matrix from a column vector . [CODESPLIT] public void setColumn ( final ColumnVector cv , final int c ) throws MatrixException { if ( ( c < 0 ) || ( c >= m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_INDEX ) ; } if ( m_nRows != cv . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } for ( int r = 0 ; r < m_nRows ; ++ r ) { m_aValues [ r ] [ c ] = cv . m_aValues [ r ] [ 0 ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the transpose of this matrix . [CODESPLIT] public Matrix transpose ( ) { final float tv [ ] [ ] = new float [ m_nCols ] [ m_nRows ] ; // transposed values // Set the values of the transpose. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { tv [ c ] [ r ] = m_aValues [ r ] [ c ] ; } } return new Matrix ( tv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add another matrix to this matrix . [CODESPLIT] public Matrix add ( final Matrix m ) throws MatrixException { // Validate m's size. if ( ( m_nRows != m . m_nRows ) && ( m_nCols != m . m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float sv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // sum values // Compute values of the sum. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { sv [ r ] [ c ] = m_aValues [ r ] [ c ] + m . m_aValues [ r ] [ c ] ; } } return new Matrix ( sv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subtract another matrix from this matrix . [CODESPLIT] public Matrix subtract ( final Matrix m ) throws MatrixException { // Validate m's size. if ( ( m_nRows != m . m_nRows ) && ( m_nCols != m . m_nCols ) ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float dv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // difference values // Compute values of the difference. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { dv [ r ] [ c ] = m_aValues [ r ] [ c ] - m . m_aValues [ r ] [ c ] ; } } return new Matrix ( dv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply this matrix by a constant . [CODESPLIT] public Matrix multiply ( final float k ) { final float pv [ ] [ ] = new float [ m_nRows ] [ m_nCols ] ; // product values // Compute values of the product. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { pv [ r ] [ c ] = k * m_aValues [ r ] [ c ] ; } } return new Matrix ( pv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply this matrix by another matrix . [CODESPLIT] public Matrix multiply ( final Matrix m ) throws MatrixException { // Validate m's dimensions. if ( m_nCols != m . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] [ ] = new float [ m_nRows ] [ m . m_nCols ] ; // product values // Compute values of the product. for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m . m_nCols ; ++ c ) { float dot = 0 ; for ( int k = 0 ; k < m_nCols ; ++ k ) { dot += m_aValues [ r ] [ k ] * m . m_aValues [ k ] [ c ] ; } pv [ r ] [ c ] = dot ; } } return new Matrix ( pv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply this matrix by a column vector : this * cv [CODESPLIT] public ColumnVector multiply ( final ColumnVector cv ) throws MatrixException { // Validate cv's size. if ( m_nRows != cv . m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] = new float [ m_nRows ] ; // product values // Compute the values of the product. for ( int r = 0 ; r < m_nRows ; ++ r ) { float dot = 0 ; for ( int c = 0 ; c < m_nCols ; ++ c ) { dot += m_aValues [ r ] [ c ] * cv . m_aValues [ c ] [ 0 ] ; } pv [ r ] = dot ; } return new ColumnVector ( pv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply a row vector by this matrix : rv * this [CODESPLIT] public RowVector multiply ( final RowVector rv ) throws MatrixException { // Validate rv's size. if ( m_nCols != rv . m_nCols ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } final float pv [ ] = new float [ m_nRows ] ; // product values // Compute the values of the product. for ( int c = 0 ; c < m_nCols ; ++ c ) { float dot = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { dot += rv . m_aValues [ 0 ] [ r ] * m_aValues [ r ] [ c ] ; } pv [ c ] = dot ; } return new RowVector ( pv ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the matrix values . [CODESPLIT] public void print ( final int width , @ Nonnull final PrintStream aPS ) { final SystemOutAlignRight ar = new SystemOutAlignRight ( aPS ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { ar . print ( \"Row \" , 0 ) ; ar . print ( r + 1 , 2 ) ; ar . print ( \":\" , 0 ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { ar . print ( m_aValues [ r ] [ c ] , width ) ; } ar . println ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next position of x [ n + 1 ] . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fFn = m_fFnp1 ; m_fFpn = m_aFunction . derivativeAt ( m_fXn ) ; // Compute the value of x[n+1]. m_fPrevXnp1 = m_fXnp1 ; m_fXnp1 = m_fXn - m_fFn / m_fFpn ; m_fFnp1 = m_aFunction . at ( m_fXnp1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the position of x [ n + 1 ] . [CODESPLIT] @ Override protected void checkPosition ( ) throws AbstractRootFinder . PositionUnchangedException { if ( EqualsHelper . equals ( m_fXnp1 , m_fPrevXnp1 ) ) { throw new AbstractRootFinder . PositionUnchangedException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attach an ImageResource to the button . [CODESPLIT] public void setResource ( ImageResource imageResource ) { Image img = new Image ( imageResource ) ; DOM . insertChild ( getElement ( ) , img . getElement ( ) , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new data point : Update the sums . [CODESPLIT] public void addDataPoint ( final DataPoint dataPoint ) { m_dSumX += dataPoint . getX ( ) ; m_dSumY += dataPoint . getY ( ) ; m_dSumXX += dataPoint . getX ( ) * dataPoint . getX ( ) ; m_dSumXY += dataPoint . getX ( ) * dataPoint . getY ( ) ; ++ m_nDataPoints ; m_bCoefsValid = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the coefficients . [CODESPLIT] private void _validateCoefficients ( ) { if ( m_bCoefsValid ) return ; if ( m_nDataPoints >= 2 ) { final float xBar = ( float ) m_dSumX / m_nDataPoints ; final float yBar = ( float ) m_dSumY / m_nDataPoints ; m_fA1 = ( float ) ( ( m_nDataPoints * m_dSumXY - m_dSumX * m_dSumY ) / ( m_nDataPoints * m_dSumXX - m_dSumX * m_dSumX ) ) ; m_fA0 = yBar - m_fA1 * xBar ; } else { m_fA0 = m_fA1 = Float . NaN ; } m_bCoefsValid = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next position of xn . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXn = m_fXn ; m_fXn = m_fGn ; m_fGn = m_aFunction . at ( m_fXn ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does not clear templateNames . [CODESPLIT] public void clear ( ) { rawSld = new RawSld ( ) ; dirty = false ; valid = false ; template = null ; sldDescriptor = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert StyledLayerDescriptorInfo to raw xml . [CODESPLIT] public RawSld toXml ( StyledLayerDescriptorInfo sldi ) throws SldException { try { if ( sldi . getVersion ( ) == null ) { sldi . setVersion ( \"1.0.0\" ) ; } return parseSldI ( sldi ) ; } catch ( JiBXException e ) { throw new SldException ( \"Validation error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert raw xml to StyledLayerDescriptorInfo . [CODESPLIT] public StyledLayerDescriptorInfo toSldI ( RawSld sld ) throws SldException { try { return parseXml ( sld . getName ( ) , sld . getXml ( ) ) ; } catch ( JiBXException e ) { throw new SldException ( \"Validation error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test by marshalling . [CODESPLIT] public void validate ( StyledLayerDescriptorInfo sld ) throws SldException { try { parseSldI ( sld ) ; } catch ( JiBXException e ) { throw new SldException ( \"Validation error\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test by unmarshalling . [CODESPLIT] public boolean validate ( RawSld sld ) throws SldException { try { parseXml ( \"\" , sld . getXml ( ) ) ; return true ; } catch ( JiBXException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "--------------------------------------------------------------- [CODESPLIT] private StyledLayerDescriptorInfo parseXml ( String name , String raw ) throws JiBXException { IBindingFactory bfact = BindingDirectory . getFactory ( StyledLayerDescriptorInfo . class ) ; IUnmarshallingContext uctx = bfact . createUnmarshallingContext ( ) ; Object object = uctx . unmarshalDocument ( new StringReader ( raw ) ) ; StyledLayerDescriptorInfo sld = ( StyledLayerDescriptorInfo ) object ; if ( sld . getName ( ) == null ) { sld . setName ( name ) ; } if ( sld . getTitle ( ) == null ) { sld . setTitle ( getTitle ( sld , name ) ) ; } if ( sld . getVersion ( ) == null ) { sld . setVersion ( \"1.0.0\" ) ; } return sld ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the next data point in the approximation of the solution . [CODESPLIT] @ Override public DataPoint nextPoint ( final float h ) { final float predictor = m_fY + Math . abs ( h ) * m_aEquation . at ( m_fX ) ; final float avgSlope = ( m_aEquation . at ( m_fX , m_fY ) + m_aEquation . at ( m_fX + h , predictor ) ) / 2 ; m_fY += h * avgSlope ; // corrector m_fX += h ; return new DataPoint ( m_fX , m_fY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Integrate the function from a to b using the trapezoidal algorithm and return an approximation to the area . ( Integrator implementation . ) [CODESPLIT] public float integrate ( final float a , final float b , final int intervals ) { if ( b <= a ) return 0 ; final float h = ( b - a ) / intervals ; // interval width float totalArea = 0 ; // Compute the area using the current number of intervals. for ( int i = 0 ; i < intervals ; ++ i ) { final float x1 = a + i * h ; totalArea += _areaOf ( x1 , h ) ; } return totalArea ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the area of the ith trapezoidal region . [CODESPLIT] private float _areaOf ( final float x1 , final float h ) { final float x2 = x1 + h ; // right bound of the region final float y1 = m_aIntegrand . at ( x1 ) ; // value at left bound final float y2 = m_aIntegrand . at ( x2 ) ; // value at right bound final float area = h * ( y1 + y2 ) / 2 ; // area of the region return area ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this square matrix from another matrix . Note that this matrix will reference the values of the argument matrix . If the values are not square only the upper left square is used . [CODESPLIT] private void _set ( final Matrix m ) { this . m_nRows = this . m_nCols = Math . min ( m . m_nRows , m . m_nCols ) ; this . m_aValues = m . m_aValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this square matrix from a 2 - d array of values . If the values are not square only the upper left square is used . [CODESPLIT] @ Override protected void set ( final float values [ ] [ ] ) { super . set ( values ) ; m_nRows = m_nCols = Math . min ( m_nRows , m_nCols ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires a { @link SldCloseEvent } that will save the current SLD and close it . If not successful the current SLD remains open . [CODESPLIT] public static void fireSave ( HasHandlers source ) { SldCloseEvent eventInstance = new SldCloseEvent ( true ) ; source . fireEvent ( eventInstance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires a { @link SldCloseEvent } that will close the current SLD regardless of changes . [CODESPLIT] public static void fire ( HasHandlers source ) { SldCloseEvent eventInstance = new SldCloseEvent ( false ) ; source . fireEvent ( eventInstance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the inverse of this matrix . [CODESPLIT] public InvertibleMatrix inverse ( ) throws MatrixException { final InvertibleMatrix inverse = new InvertibleMatrix ( m_nRows ) ; final IdentityMatrix identity = new IdentityMatrix ( m_nRows ) ; // Compute each column of the inverse matrix // using columns of the identity matrix. for ( int c = 0 ; c < m_nCols ; ++ c ) { final ColumnVector col = solve ( identity . getColumn ( c ) , true ) ; inverse . setColumn ( col , c ) ; } return inverse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the determinant . [CODESPLIT] public float determinant ( ) throws MatrixException { decompose ( ) ; // Each row exchange during forward elimination flips the sign // of the determinant, so check for an odd number of exchanges. float determinant = ( ( m_nExchangeCount & 1 ) == 0 ) ? 1 : - 1 ; // Form the product of the diagonal elements of matrix U. for ( int i = 0 ; i < m_nRows ; ++ i ) { final int pi = m_aPermutation [ i ] ; // permuted index determinant *= m_aLU . at ( pi , i ) ; } return determinant ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the Euclidean norm of this matrix . [CODESPLIT] public float norm ( ) { float sum = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { for ( int c = 0 ; c < m_nCols ; ++ c ) { final float v = m_aValues [ r ] [ c ] ; sum += v * v ; } } return ( float ) Math . sqrt ( sum ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the value of element [ r c ] in the matrix . [CODESPLIT] @ Override public void set ( final int r , final int c , final float value ) throws MatrixException { super . set ( r , c , value ) ; reset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a row of this matrix from a row vector . [CODESPLIT] @ Override public void setRow ( final RowVector rv , final int r ) throws MatrixException { super . setRow ( rv , r ) ; reset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a column of this matrix from a column vector . [CODESPLIT] @ Override public void setColumn ( final ColumnVector cv , final int c ) throws MatrixException { super . setColumn ( cv , c ) ; reset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Solve Ax = b for x using the Gaussian elimination algorithm . [CODESPLIT] public ColumnVector solve ( final ColumnVector b , final boolean improve ) throws MatrixException { // Validate b's size. if ( b . m_nRows != m_nRows ) { throw new MatrixException ( MatrixException . INVALID_DIMENSIONS ) ; } decompose ( ) ; // Solve Ly = b for y by forward substitution. // Solve Ux = y for x by back substitution. final ColumnVector y = _forwardSubstitution ( b ) ; final ColumnVector x = _backSubstitution ( y ) ; // Improve and return x. if ( improve ) _improve ( b , x ) ; return x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the decomposed matrix LU . [CODESPLIT] public void printDecomposed ( final int width , @ Nonnull final PrintStream aPS ) throws MatrixException { decompose ( ) ; final SystemOutAlignRight ar = new SystemOutAlignRight ( aPS ) ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final int pr = m_aPermutation [ r ] ; // permuted row index ar . print ( \"Row \" , 0 ) ; ar . print ( r + 1 , 2 ) ; ar . print ( \":\" , 0 ) ; for ( int c = 0 ; c < m_nCols ; ++ c ) { ar . print ( m_aLU . m_aValues [ pr ] [ c ] , width ) ; } ar . println ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the upper triangular matrix U and lower triangular matrix L such that A = L * U . Store L and U together in matrix LU . Compute the permutation vector permutation of the row indices . [CODESPLIT] protected void decompose ( ) throws MatrixException { // Return if the decomposition is valid. if ( m_aLU != null ) return ; // Create a new LU matrix and permutation vector. // LU is initially just a copy of the values of this system. m_aLU = new SquareMatrix ( this . copyValues2D ( ) ) ; m_aPermutation = new int [ m_nRows ] ; final float scales [ ] = new float [ m_nRows ] ; // Loop to initialize the permutation vector and scales. for ( int r = 0 ; r < m_nRows ; ++ r ) { m_aPermutation [ r ] = r ; // initially no row exchanges // Find the largest row element. float largestRowElmt = 0 ; for ( int c = 0 ; c < m_nRows ; ++ c ) { final float elmt = Math . abs ( m_aLU . at ( r , c ) ) ; if ( largestRowElmt < elmt ) largestRowElmt = elmt ; } // Set the scaling factor for row equilibration. if ( largestRowElmt != 0 ) { scales [ r ] = 1 / largestRowElmt ; } else { throw new MatrixException ( MatrixException . ZERO_ROW ) ; } } // Do forward elimination with scaled partial row pivoting. _forwardElimination ( scales ) ; // Check bottom right element of the permuted matrix. if ( m_aLU . at ( m_aPermutation [ m_nRows - 1 ] , m_nRows - 1 ) == 0 ) { throw new MatrixException ( MatrixException . SINGULAR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do forward elimination with scaled partial row pivoting . [CODESPLIT] private void _forwardElimination ( final float scales [ ] ) throws MatrixException { // Loop once per pivot row 0..nRows-1. for ( int rPivot = 0 ; rPivot < m_nRows - 1 ; ++ rPivot ) { float largestScaledElmt = 0 ; int rLargest = 0 ; // Starting from the pivot row rPivot, look down // column rPivot to find the largest scaled element. for ( int r = rPivot ; r < m_nRows ; ++ r ) { // Use the permuted row index. final int pr = m_aPermutation [ r ] ; final float absElmt = Math . abs ( m_aLU . at ( pr , rPivot ) ) ; final float scaledElmt = absElmt * scales [ pr ] ; if ( largestScaledElmt < scaledElmt ) { // The largest scaled element and // its row index. largestScaledElmt = scaledElmt ; rLargest = r ; } } // Is the matrix singular? if ( largestScaledElmt == 0 ) { throw new MatrixException ( MatrixException . SINGULAR ) ; } // Exchange rows if necessary to choose the best // pivot element by making its row the pivot row. if ( rLargest != rPivot ) { final int temp = m_aPermutation [ rPivot ] ; m_aPermutation [ rPivot ] = m_aPermutation [ rLargest ] ; m_aPermutation [ rLargest ] = temp ; ++ m_nExchangeCount ; } // Use the permuted pivot row index. final int prPivot = m_aPermutation [ rPivot ] ; final float pivotElmt = m_aLU . at ( prPivot , rPivot ) ; // Do the elimination below the pivot row. for ( int r = rPivot + 1 ; r < m_nRows ; ++ r ) { // Use the permuted row index. final int pr = m_aPermutation [ r ] ; final float multiple = m_aLU . at ( pr , rPivot ) / pivotElmt ; // Set the multiple into matrix L. m_aLU . set ( pr , rPivot , multiple ) ; // Eliminate an unknown from matrix U. if ( multiple != 0 ) { for ( int c = rPivot + 1 ; c < m_nCols ; ++ c ) { float elmt = m_aLU . at ( pr , c ) ; // Subtract the multiple of the pivot row. elmt -= multiple * m_aLU . at ( prPivot , c ) ; m_aLU . set ( pr , c , elmt ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Solve Ly = b for y by forward substitution . [CODESPLIT] private ColumnVector _forwardSubstitution ( final ColumnVector b ) throws MatrixException { final ColumnVector y = new ColumnVector ( m_nRows ) ; // Do forward substitution. for ( int r = 0 ; r < m_nRows ; ++ r ) { final int pr = m_aPermutation [ r ] ; // permuted row index float dot = 0 ; for ( int c = 0 ; c < r ; ++ c ) { dot += m_aLU . at ( pr , c ) * y . at ( c ) ; } y . set ( r , b . at ( pr ) - dot ) ; } return y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Solve Ux = y for x by back substitution . [CODESPLIT] private ColumnVector _backSubstitution ( final ColumnVector y ) throws MatrixException { final ColumnVector x = new ColumnVector ( m_nRows ) ; // Do back substitution. for ( int r = m_nRows - 1 ; r >= 0 ; -- r ) { final int pr = m_aPermutation [ r ] ; // permuted row index float dot = 0 ; for ( int c = r + 1 ; c < m_nRows ; ++ c ) { dot += m_aLU . at ( pr , c ) * x . at ( c ) ; } x . set ( r , ( y . at ( r ) - dot ) / m_aLU . at ( pr , r ) ) ; } return x ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iteratively improve the solution x to machine accuracy . [CODESPLIT] private void _improve ( final ColumnVector b , final ColumnVector x ) throws MatrixException { // Find the largest x element. float largestX = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final float absX = Math . abs ( x . m_aValues [ r ] [ 0 ] ) ; if ( largestX < absX ) largestX = absX ; } // Is x already as good as possible? if ( largestX == 0 ) return ; final ColumnVector residuals = new ColumnVector ( m_nRows ) ; // Iterate to improve x. for ( int iter = 0 ; iter < MAX_ITER ; ++ iter ) { // Compute residuals = b - Ax. // Must use double precision! for ( int r = 0 ; r < m_nRows ; ++ r ) { double dot = 0 ; for ( int c = 0 ; c < m_nRows ; ++ c ) { final double elmt = at ( r , c ) ; dot += elmt * x . at ( c ) ; // dbl.prec. * } final double value = b . at ( r ) - dot ; // dbl.prec. - residuals . set ( r , ( float ) value ) ; } // Solve Az = residuals for z. final ColumnVector z = solve ( residuals , false ) ; // Set x = x + z. // Find largest the largest difference. float largestDiff = 0 ; for ( int r = 0 ; r < m_nRows ; ++ r ) { final float oldX = x . at ( r ) ; x . set ( r , oldX + z . at ( r ) ) ; final float diff = Math . abs ( x . at ( r ) - oldX ) ; if ( largestDiff < diff ) largestDiff = diff ; } // Is any further improvement possible? if ( largestDiff < largestX * TOLERANCE ) return ; } // Failed to converge because A is nearly singular. throw new MatrixException ( MatrixException . NO_CONVERGENCE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a square matrix into an identity matrix . [CODESPLIT] public static void convert ( final SquareMatrix sm ) { for ( int r = 0 ; r < sm . m_nRows ; ++ r ) { for ( int c = 0 ; c < sm . m_nCols ; ++ c ) { sm . m_aValues [ r ] [ c ] = ( r == c ) ? 1 : 0 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next randomn value using the von Neumann algorithm . Requires sequences of uniformly - distributed random values in [ 0 1 ) . [CODESPLIT] public float nextVonNeumann ( ) { int n ; int k = 0 ; float u1 ; // Loop to try sequences of uniformly-distributed // random values. for ( ; ; ) { n = 1 ; u1 = GENERATOR . nextFloat ( ) ; float u = u1 ; float uPrev = Float . NaN ; // Loop to generate a sequence of ramdom values // as long as they are decreasing. for ( ; ; ) { uPrev = u ; u = GENERATOR . nextFloat ( ) ; // No longer decreasing? if ( u > uPrev ) { // n is even. if ( ( n & 1 ) == 0 ) { return u1 + k ; // return a random value } // n is odd. ++ k ; break ; // try another sequence } ++ n ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the next data point in the approximation of the solution . [CODESPLIT] @ Override public DataPoint nextPoint ( final float h ) { final float k1 = m_aEquation . at ( m_fX , m_fY ) ; final float k2 = m_aEquation . at ( m_fX + h / 2 , m_fY + k1 * h / 2 ) ; final float k3 = m_aEquation . at ( m_fX + h / 2 , m_fY + k2 * h / 2 ) ; final float k4 = m_aEquation . at ( m_fX + h , m_fY + k3 * h ) ; m_fY += ( k1 + 2 * ( k2 + k3 ) + k4 ) * h / 6 ; m_fX += h ; return new DataPoint ( m_fX , m_fY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do the regula falsi iteration procedure . [CODESPLIT] @ Override protected void doIterationProcedure ( final int n ) { if ( n == 1 ) return ; // already initialized if ( m_fFalse < 0 ) { m_fXNeg = m_fXFalse ; // the root is in the xPos side m_fNeg = m_fFalse ; } else { m_fXPos = m_fXFalse ; // the root is in the xNeg side m_fPos = m_fFalse ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next position of x - false . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXFalse = m_fXFalse ; m_fXFalse = m_fXPos - m_fPos * ( m_fXNeg - m_fXPos ) / ( m_fNeg - m_fPos ) ; m_fFalse = m_aFunction . at ( m_fXFalse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the position of x - false . [CODESPLIT] @ Override protected void checkPosition ( ) throws AbstractRootFinder . PositionUnchangedException { if ( EqualsHelper . equals ( m_fXFalse , m_fPrevXFalse ) ) { throw new AbstractRootFinder . PositionUnchangedException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next position of xFalse . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXFalse = m_fXFalse ; m_fPrevFFalse = m_fFalse ; m_fXFalse = m_fXPos - m_fPos * ( m_fXNeg - m_fXPos ) / ( m_fNeg - m_fPos ) ; m_fFalse = m_aFunction . at ( m_fXFalse ) ; m_bDecreasePos = m_bDecreaseNeg = false ; // If there was no sign change in f(xFalse), // or if this is the first iteration step, // then decrease the slope of the secant. if ( Float . isNaN ( m_fPrevFFalse ) || ( m_fPrevFFalse * m_fFalse > 0 ) ) { if ( m_fFalse < 0 ) m_bDecreasePos = true ; else m_bDecreaseNeg = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the interval . [CODESPLIT] public void checkInterval ( final float x1 , final float x2 ) throws InvalidIntervalException { final float y1 = m_aFunction . at ( x1 ) ; final float y2 = m_aFunction . at ( x2 ) ; // The interval is invalid if y1 and y2 have the same signs. if ( y1 * y2 > 0 ) throw new InvalidIntervalException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the value of an addend to the running sum . [CODESPLIT] public void add ( final float addend ) { // Correct the addend value and add it to the running sum. m_fCorrectedAddend = addend + m_fCorrection ; final float tempSum = m_fSum + m_fCorrectedAddend ; // Compute the next correction and set the running sum. // The parentheses are necessary to compute the high-order // bits of the addend. m_fCorrection = m_fCorrectedAddend - ( tempSum - m_fSum ) ; m_fSum = tempSum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Multiply two integer values a and b modulo m . [CODESPLIT] public static int multiply ( final int pa , final int pb , final int m ) { int a = pa ; int b = pb ; int product = 0 ; // Loop to compute product = (a*b)%m. while ( a > 0 ) { // Does the rightmost bit of a == 1? if ( ( a & 1 ) == 1 ) { product += b ; product %= m ; } // Double b modulo m, and // shift a 1 bit to the right. b <<= 1 ; b %= m ; a >>= 1 ; } return product ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Raise a to the b power modulo m . [CODESPLIT] public static int raise ( final int pbase , final int pexponent , final int m ) { int base = pbase ; int exponent = pexponent ; int power = 1 ; // Loop to compute power = (base^exponent)%m. while ( exponent > 0 ) { // Does the rightmost bit of the exponent == 1? if ( ( exponent & 1 ) == 1 ) { power = multiply ( power , base , m ) ; } // Square the base modulo m and // shift the exponent 1 bit to the right. base = multiply ( base , base , m ) ; exponent >>= 1 ; } return power ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do the secant iteration procedure . [CODESPLIT] @ Override protected void doIterationProcedure ( final int n ) { if ( n == 1 ) return ; // already initialized // Use the latest two points. m_fXnm1 = m_fXn ; // x[n-1] = x[n] m_fXn = m_fXnp1 ; // x[n] = x[n+1] m_fFnm1 = m_fFn ; // f(x[n-1]) = f(x[n]) m_fFn = m_fFnp1 ; // f(x[n]) = f(x[n+1]) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next position of x [ n + 1 ] . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXnp1 = m_fXnp1 ; m_fXnp1 = m_fXn - m_fFn * ( m_fXnm1 - m_fXn ) / ( m_fFnm1 - m_fFn ) ; m_fFnp1 = m_aFunction . at ( m_fXnp1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance of the SldManager . [CODESPLIT] public SldManager getSldManager ( ) { if ( sldManager == null ) { sldManager = new SldManagerImpl ( getEventBus ( ) , getSldEditorServiceFactory ( ) . createSldGwtServiceAsync ( ) ) ; } return sldManager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a long value into a character array of 0 and 1 that represents the value in base 2 . [CODESPLIT] private static char [ ] _toCharBitArray ( final long pvalue , final int size ) { long value = pvalue ; final char bits [ ] = new char [ size ] ; // Convert each bit from right to left. for ( int i = size - 1 ; i >= 0 ; -- i ) { bits [ i ] = ( value & 1 ) == 0 ? ' ' : ' ' ; value >>>= 1 ; } return bits ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decompose a floating - point value into its parts . [CODESPLIT] private void _decompose ( final char [ ] bits , final int bias , final int reserved , final int signIndex , final int signSize , final int exponentIndex , final int exponentSize , final int fractionIndex , final int fractionSize ) { this . m_nBias = bias ; // Extract the individual parts as strings of '0' and '1'. m_sSignBit = new String ( bits , signIndex , signSize ) ; m_sExponentBits = new String ( bits , exponentIndex , exponentSize ) ; m_sFractionBits = new String ( bits , fractionIndex , fractionSize ) ; try { m_nBiased = Integer . parseInt ( m_sExponentBits , 2 ) ; m_nFraction = Long . parseLong ( m_sFractionBits , 2 ) ; } catch ( final NumberFormatException ex ) { } m_bIsZero = ( m_nBiased == 0 ) && ( m_nFraction == 0 ) ; m_bIsDenormalized = ( m_nBiased == 0 ) && ( m_nFraction != 0 ) ; m_bIsReserved = ( m_nBiased == reserved ) ; m_sImpliedBit = m_bIsDenormalized || m_bIsZero || m_bIsReserved ? \"0\" : \"1\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the decomposed parts of the value . [CODESPLIT] public void print ( @ Nonnull final PrintStream aPW ) { aPW . println ( \"------------------------------\" ) ; // Print the value. if ( isDouble ( ) ) aPW . println ( \"double value = \" + doubleValue ( ) ) ; else aPW . println ( \"float value = \" + floatValue ( ) ) ; // Print the sign. aPW . print ( \"sign=\" + signBit ( ) ) ; // Print the bit representation of the exponent and its // biased and unbiased values. Indicate whether the value // is denormalized, or whether the exponent is reserved. aPW . print ( \", exponent=\" + exponentBits ( ) + \" (biased=\" + biasedExponent ( ) ) ; if ( isZero ( ) ) aPW . println ( \", zero)\" ) ; else if ( isExponentReserved ( ) ) aPW . println ( \", reserved)\" ) ; else if ( isDenormalized ( ) ) aPW . println ( \", denormalized, use \" + unbiasedExponent ( ) + \")\" ) ; else aPW . println ( \", normalized, unbiased=\" + unbiasedExponent ( ) + \")\" ) ; // Print the significand. aPW . println ( \"significand=\" + significandBits ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the value of the float biased exponent value . [CODESPLIT] public static void validateFloatBiasedExponent ( final int biased ) throws IEEE754Exception { if ( ( biased < 0 ) || ( biased > IEEE754Constants . FLOAT_EXPONENT_RESERVED ) ) { throw new IEEE754Exception ( \"The biased exponent value should be \" + \"0 through \" + IEEE754Constants . FLOAT_EXPONENT_RESERVED + \".\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the value of the float unbiased exponent value . [CODESPLIT] public static void validateFloatUnbiasedExponent ( final int unbiased ) throws IEEE754Exception { if ( ( unbiased < - IEEE754Constants . FLOAT_EXPONENT_BIAS + 1 ) || ( unbiased > IEEE754Constants . FLOAT_EXPONENT_BIAS ) ) { throw new IEEE754Exception ( \"The unbiased exponent value should be \" + - ( IEEE754Constants . FLOAT_EXPONENT_BIAS - 1 ) + \" through \" + IEEE754Constants . FLOAT_EXPONENT_BIAS + \".\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the value of the double biased exponent value . [CODESPLIT] public static void validateDoubleBiasedExponent ( final int biased ) throws IEEE754Exception { if ( ( biased < 0 ) || ( biased > IEEE754Constants . DOUBLE_EXPONENT_RESERVED ) ) { throw new IEEE754Exception ( \"The biased exponent value should be \" + \"0 through \" + IEEE754Constants . DOUBLE_EXPONENT_RESERVED + \".\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validate the value of the double unbiased exponent value . [CODESPLIT] public static void validateDoubleUnbiasedExponent ( final int unbiased ) throws IEEE754Exception { if ( ( unbiased < - IEEE754Constants . DOUBLE_EXPONENT_BIAS + 1 ) || ( unbiased > IEEE754Constants . DOUBLE_EXPONENT_BIAS ) ) { throw new IEEE754Exception ( \"The unbiased exponent value should be \" + - ( IEEE754Constants . DOUBLE_EXPONENT_BIAS - 1 ) + \" through \" + IEEE754Constants . DOUBLE_EXPONENT_BIAS + \".\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SldEditorServiceFactory constructor . [CODESPLIT] public SldGwtServiceAsync createSldGwtServiceAsync ( ) { this . service = GWT . create ( SldGwtService . class ) ; ServiceDefTarget endpoint = ( ServiceDefTarget ) service ; endpoint . setServiceEntryPoint ( GWT . getHostPageBaseURL ( ) + \"d/sldTemplates\" ) ; return service ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next random value using the Central Limit Theorem which states that the averages of sets of uniformly - distributed random values are normally distributed . [CODESPLIT] public float nextCentral ( ) { // Average 12 uniformly-distributed random values. float sum = 0.0f ; for ( int j = 0 ; j < 12 ; ++ j ) sum += GENERATOR . nextFloat ( ) ; // Subtract 6 to center about 0. return m_fStddev * ( sum - 6 ) + m_fMean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next randomn value using the polar algorithm . Requires two uniformly - distributed random values in [ - 1 + 1 ) . Actually computes two random values and saves the second one for the next invokation . [CODESPLIT] public float nextPolar ( ) { // If there's a saved value, return it. if ( m_bHaveNextPolar ) { m_bHaveNextPolar = false ; return m_fNextPolar ; } // point coordinates and their radius float u1 , u2 , r ; do { // u1 and u2 will be uniformly-distributed // random values in [-1, +1). u1 = 2 * GENERATOR . nextFloat ( ) - 1 ; u2 = 2 * GENERATOR . nextFloat ( ) - 1 ; // Want radius r inside the unit circle. r = u1 * u1 + u2 * u2 ; } while ( r >= 1 ) ; // Factor incorporates the standard deviation. final float factor = ( float ) ( m_fStddev * Math . sqrt ( - 2 * Math . log ( r ) / r ) ) ; // v1 and v2 are normally-distributed random values. final float v1 = factor * u1 + m_fMean ; final float v2 = factor * u2 + m_fMean ; // Save v1 for next time. m_fNextPolar = v1 ; m_bHaveNextPolar = true ; return v2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next random value using the ratio algorithm . Requires two uniformly - distributed random values in [ 0 1 ) . [CODESPLIT] public float nextRatio ( ) { float u , v , x , xx ; do { // u and v are two uniformly-distributed random values // in [0, 1), and u != 0. while ( ( u = GENERATOR . nextFloat ( ) ) == 0 ) { // try again if 0 } v = GENERATOR . nextFloat ( ) ; // y coord of point (u, y) final float y = C1 * ( v - 0.5f ) ; // ratio of point's coords x = y / u ; xx = x * x ; } while ( ( xx > 5f - C2 * u ) && // quick acceptance ( ( xx >= C3 / u + 1.4f ) || // quick rejection ( xx > ( float ) ( - 4 * Math . log ( u ) ) ) ) // final test ) ; return m_fStddev * x + m_fMean ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the Sieve of Eratosthenes . [CODESPLIT] public static boolean [ ] primeSieve ( final int n ) { final int halfN = ( n + 1 ) >> 1 ; final boolean sieve [ ] = new boolean [ n + 1 ] ; // Initialize every integer from 2 onwards to prime. for ( int i = 2 ; i <= n ; ++ i ) sieve [ i ] = true ; int prime = 2 ; // first prime number // Loop to create the sieve. while ( prime < halfN ) { // Mark as composites multiples of the prime. for ( int composite = prime << 1 ; composite <= n ; composite += prime ) sieve [ composite ] = false ; // Skip over composites to the next prime. while ( ( ++ prime < halfN ) && ( ! sieve [ prime ] ) ) { } } return sieve ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the prime factors of an integer value . [CODESPLIT] public static int [ ] factorsOf ( final int pn ) { int n = pn ; final boolean isPrime [ ] = primeSieve ( n ) ; // primes <= n final ICommonsList < Integer > v = new CommonsArrayList <> ( ) ; // Loop to try prime divisors. for ( int factor = 2 ; n > 1 ; ++ factor ) { if ( isPrime [ factor ] && ( n % factor == 0 ) ) { // Prime divisor found. v . add ( Integer . valueOf ( factor ) ) ; // Factor out multiples of the divisor. do { n /= factor ; } while ( n % factor == 0 ) ; } } // Create an array of the distinct prime factors. final int factors [ ] = new int [ v . size ( ) ] ; for ( int i = 0 ; i < v . size ( ) ; ++ i ) { factors [ i ] = v . get ( i ) . intValue ( ) ; } return factors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Do the bisection iteration procedure . [CODESPLIT] @ Override protected void doIterationProcedure ( final int n ) { if ( n == 1 ) return ; // already initialized if ( m_fMid < 0 ) { m_fXNeg = m_fXMid ; // the root is in the xPos half m_fNeg = m_fMid ; } else { m_fXPos = m_fXMid ; // the root is in the xNeg half m_fPos = m_fMid ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute the next position of xMid . [CODESPLIT] @ Override protected void computeNextPosition ( ) { m_fPrevXMid = m_fXMid ; m_fXMid = ( m_fXNeg + m_fXPos ) / 2 ; m_fMid = m_aFunction . at ( m_fXMid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the position of xMid . [CODESPLIT] @ Override protected void checkPosition ( ) throws AbstractRootFinder . PositionUnchangedException { if ( EqualsHelper . equals ( m_fXMid , m_fPrevXMid ) ) { throw new AbstractRootFinder . PositionUnchangedException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the JavaFX application instance to be provided by the CDI BeanManager . [CODESPLIT] public static void setJavaFxApplication ( final CdiApplication javaFxApplication ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; Platform . runLater ( ( ) -> { JAVA_FX_APPLICATION . set ( javaFxApplication ) ; latch . countDown ( ) ; } ) ; if ( ! Platform . isFxApplicationThread ( ) ) { try { latch . await ( ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Settings from a custom calabash . xml [CODESPLIT] public void setConfiguration ( File configFile ) { if ( configFile == null ) nextConfig = null ; else try { XProcConfiguration config = new XProcConfiguration ( \"he\" , false ) ; nextConfig = config . getProcessor ( ) . newDocumentBuilder ( ) . build ( new SAXSource ( new InputSource ( new FileReader ( configFile ) ) ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( \"Config file does not exist\" , e ) ; } catch ( SaxonApiException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Settings to be always applied [CODESPLIT] public void setDefaultConfiguration ( Reader defaultConfig ) { XProcConfiguration config = new XProcConfiguration ( \"he\" , false ) ; try { nextDefaultConfig = config . getProcessor ( ) . newDocumentBuilder ( ) . build ( new SAXSource ( new InputSource ( defaultConfig ) ) ) ; } catch ( SaxonApiException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a { [CODESPLIT] private StringConverter < ? > getStringConverter ( final Class < ? > valueClass ) { Class < ? extends StringConverter < ? > > aClass = StringConverterRetriever . retrieveConverterFor ( valueClass ) ; if ( aClass == null ) { throw new IllegalArgumentException ( String . format ( \"Can't find StringConverter for class '%s'.\" , valueClass . getName ( ) ) ) ; } try { return aClass . newInstance ( ) ; } catch ( final InstantiationException | IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a CDI - aware FXMLLoader . If an annotation of type @FXMLLoaderParams can be found use it s parameters to configure the FXMLLoader instance that shall be used to perform the loading of the FXML file . [CODESPLIT] @ Produces @ FXMLLoaderParams FXMLLoader createCdiFXMLLoader ( final InjectionPoint injectionPoint ) { final CdiFXMLLoader fxmlLoader = new CdiFXMLLoader ( ) ; final Annotated annotated = injectionPoint . getAnnotated ( ) ; final Class < ? > declaringClass = injectionPoint . getMember ( ) . getDeclaringClass ( ) ; if ( annotated . isAnnotationPresent ( FXMLLoaderParams . class ) ) { final FXMLLoaderParams annotation = annotated . getAnnotation ( FXMLLoaderParams . class ) ; initializeFXMLLoader ( fxmlLoader , declaringClass , annotation . location ( ) , annotation . resources ( ) , annotation . charset ( ) ) ; } return fxmlLoader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the given FXMLLoader instance using the provided parameters . [CODESPLIT] static void initializeFXMLLoader ( final FXMLLoader fxmlLoader , final Class < ? > targetClass , final String location , final String resources , final String charset ) { checkAndSetLocation ( fxmlLoader , targetClass , location ) ; if ( charset != null && ! charset . equals ( CHARSET_UNSPECIFIED ) ) { fxmlLoader . setCharset ( Charset . forName ( charset ) ) ; } if ( resources != null && ! resources . equals ( RESOURCES_UNSPECIFIED ) ) { fxmlLoader . setResources ( ResourceBundle . getBundle ( resources ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the location that has been specified ( if any ) and uses the default class loader to create an URL that points to a FXML file on the classpath . [CODESPLIT] private static void checkAndSetLocation ( FXMLLoader fxmlLoader , Class < ? > targetClass , String location ) { if ( location != null && ! location . equals ( LOCATION_UNSPECIFIED ) ) { final URL locationUrl = targetClass . getResource ( location ) ; if ( locationUrl == null ) { throw new IllegalArgumentException ( String . format ( \"Couldn't find FXML file: \\\"%s\\\".\" , location ) ) ; } fxmlLoader . setLocation ( locationUrl ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO Refactor HATEOAS link building . Time for ResourceAssembler or moving this stuff up the service . Although moving it up will create a circular dep . [CODESPLIT] @ RequestMapping ( value = \"\" , method = { RequestMethod . GET , RequestMethod . HEAD } ) public Resources < EventDefinitionResource > getEventDefinitions ( ) throws EventDefinitionNotFoundException , ProviderNotFoundException , AttributeDefinitionNotFoundException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( ) ; } final Resources < EventDefinitionResource > resources = getEventDefinitions ( eventDefinitionService . getEventDefinitions ( ) ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( resources ) ; } return resources ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Your business application s API key . This key identifies your application for purposes of quota management . [CODESPLIT] public ReverseGeocodeRequestBuilder key ( String client , String signature ) { parameters . put ( \"client\" , client ) ; parameters . put ( \"signature\" , signature ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The location latitude and longitude . [CODESPLIT] public ReverseGeocodeRequestBuilder latlng ( Double lat , Double lng ) { parameters . put ( \"latlng\" , lat + \",\" + lng ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One or more address types separated by a pipe ( | ) . [CODESPLIT] public ReverseGeocodeRequestBuilder resultType ( Type [ ] types ) { if ( types == null || types . length == 0 ) return this ; StringBuffer resultType = new StringBuffer ( ) ; for ( int i = 0 ; i < types . length - 1 ; i ++ ) resultType . append ( types [ i ] + \"|\" ) ; resultType . append ( types [ types . length - 1 ] ) ; parameters . put ( \"result_type\" , resultType . toString ( ) ) ; return this ; } /**\n\t * One or more location types, separated by a pipe (|). \n\t * \n\t * Specifying a type will restrict the results to this type. If multiple \n\t * types are specified, the API will return all addresses that match any \n\t * of the types. \n\t * \n\t * Note: This parameter is available only for requests that include an API \n\t * key or a client ID. \n\t * \n\t * The following values are supported:\n\t * \n\t *   \"ROOFTOP\" restricts the results to addresses for which we have \n\t *   location information accurate down to street address precision.\n\t *   \n\t *   \"RANGE_INTERPOLATED\" restricts the results to those that reflect \n\t *   an approximation (usually on a road) interpolated between two precise\n\t *   points (such as intersections). An interpolated range generally \n\t *   indicates that rooftop geocodes are unavailable for a street address.\n\t *   \n\t *   \"GEOMETRIC_CENTER\" restricts the results to geometric centers of a \n\t *   location such as a polyline (for example, a street) or polygon (region).\n\t *   \n\t *   \"APPROXIMATE\" restricts the results to those that are characterized \n\t *   as approximate.\n\t *   \n\t * @param types\n\t * @return ReverseGeocodeRequestBuilder\n\t */ public ReverseGeocodeRequestBuilder locationType ( LocationType [ ] types ) { if ( types == null || types . length == 0 ) return this ; StringBuffer resultType = new StringBuffer ( ) ; for ( int i = 0 ; i < types . length - 1 ; i ++ ) resultType . append ( types [ i ] + \"|\" ) ; resultType . append ( types [ types . length - 1 ] ) ; parameters . put ( \"location_type\" , resultType . toString ( ) ) ; return this ; } /**\n\t * Build the request object.\n\t * \n\t * @return AddressRequest\n\t */ public ReverseGeocodeRequest build ( ) { return new ReverseGeocodeRequest ( parameters ) ; } } ", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safely get the information from our convention [CODESPLIT] public static InetSocketAddress getHostPortPair ( Service svc ) { try { return new InetSocketAddress ( svc . getMetadata ( ) . get ( \"service.host\" ) , Integer . parseInt ( svc . getMetadata ( ) . get ( \"service.port\" ) ) ) ; } catch ( Exception e ) { logger . error ( \"Exception extracting metadata from service instance {}\" , svc , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an attribute definition that applies to a particular attribute filter . [CODESPLIT] protected AttributeDefinition getApplicableAttributeDefinition ( final UUID attributeDefinitionUuid , final List < AttributeDefinition > attributeDefinitions ) { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( attributeDefinitionUuid , attributeDefinitions ) ; } AttributeDefinition attributeDefinition = null ; for ( AttributeDefinition anAttributeDefinition : attributeDefinitions ) { if ( anAttributeDefinition . getUUID ( ) . equals ( attributeDefinitionUuid ) ) { attributeDefinition = anAttributeDefinition ; break ; } } if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( attributeDefinition ) ; } return attributeDefinition ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluate single attribute filter [CODESPLIT] protected boolean evaluate ( final UUID attributeDefinitionUuid , final AttributeFilterExpression attributeFilter , final Map < UUID , String > eventAttributes , final List < AttributeDefinition > attributeDefinitions ) throws ParseException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( attributeDefinitionUuid , attributeFilter , eventAttributes , attributeDefinitions ) ; } // Find a matching attribute final String attributeValue = eventAttributes . get ( attributeDefinitionUuid ) ; if ( attributeValue == null ) { // No attribute value to match attribute filter. if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"An attributeValue was not specified for this attribute definition.\" ) ; LOG . exit ( false ) ; } return false ; } // Find the Attribute definition that matches our filter. final AttributeDefinition attributeDefinition = getApplicableAttributeDefinition ( attributeDefinitionUuid , attributeDefinitions ) ; if ( attributeDefinition == null ) { // Really shouldn't have any filters defined for attributes that don't exist. if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( \"The attributeDefinition did not exist.\" ) ; LOG . exit ( false ) ; } return false ; } final Unit unit = attributeDefinition . getUnits ( ) ; try { boolean result = unit . evaluate ( attributeFilter . getOperator ( ) , attributeValue , attributeFilter . getOperand ( ) ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( result ) ; } return result ; } catch ( ParseException e ) { if ( LOG . isTraceEnabled ( ) ) { LOG . throwing ( e ) ; } throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO I d like to push a lot of this down into NickNack - core . [CODESPLIT] protected Action processVariables ( Action origAction , Event cause ) { final ActionResource newAction = new ActionResource ( ) ; final Map < UUID , String > newParameters = new HashMap <> ( ) ; newAction . setAppliesToActionDefinition ( origAction . getAppliesToActionDefinition ( ) ) ; for ( UUID key : origAction . getAttributes ( ) . keySet ( ) ) { newParameters . put ( key , processVariables ( origAction . getAttributes ( ) . get ( key ) , cause ) ) ; } newAction . setParameters ( newParameters ) ; return newAction ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helpers [CODESPLIT] private boolean isPertinent ( Event e ) { return ( e . getPayload ( ) instanceof ServicePayload ) && ( ( ServicePayload ) e . getPayload ( ) ) . getService ( ) . getTags ( ) . contains ( discovery . getType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo : switch to iterator . [CODESPLIT] private void pollAndProcessEvents ( ) { MethodOptions options = new MethodOptions ( 100 , null ) ; List < Event > events = null ; int count = 0 ; do { if ( shouldStopPolling ) break ; count += 1 ; try { // get events from server, filter the ones we are interested in. events = Lists . newArrayList ( discovery . getClient ( ) . getEventsClient ( ) . list ( options ) ) ; String lastEventId = processEvents ( events ) ; options = options . withMarker ( lastEventId ) ; } catch ( Exception ex ) { // todo: just log it. events = null ; } } while ( events != null && events . size ( ) > 0 ) ; // if it only happened once, assume there are not many events happening. if ( count == 1 ) { // todo: trace message. // todo: this should become configurable. try { Thread . sleep ( 1000 ) ; } catch ( Exception ex ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "1 .. 55 chars . anything goes . [CODESPLIT] public static String sanitizeTag ( String s ) { // if > 55 chars, assume max entropy is at the end (like a class name). if ( s . length ( ) > MAX_TAG_LENGTH ) { s = s . substring ( s . length ( ) - MAX_TAG_LENGTH ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO Refactor HATEOAS link building . Time for ResourceAssembler or moving this stuff up the service . Although moving it up will create a circular dep . [CODESPLIT] @ RequestMapping ( value = \"\" , method = { RequestMethod . GET , RequestMethod . HEAD } ) public Resources < StatesResource > getAllStates ( ) throws StateDefinitionNotFoundException , ProviderNotFoundException , AttributeDefinitionNotFoundException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( ) ; } final Resources < StatesResource > resources = getAllStates ( statesService . getAllStates ( ) , null ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( resources ) ; } return resources ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Your business application s API key . This key identifies your application for purposes of quota management . [CODESPLIT] public GeocodeRequestBuilder key ( String client , String signature ) { parameters . put ( \"client\" , client ) ; parameters . put ( \"signature\" , signature ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The address that you want to geocode . [CODESPLIT] public GeocodeRequestBuilder address ( String address ) { parameters . put ( \"address\" , address != null ? address . replace ( ' ' , ' ' ) : address ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In a geocoding response the Google Geocoding API can return address results restricted to a specific area . [CODESPLIT] public GeocodeRequestBuilder componenets ( Map < String , String > components ) { StringBuffer filters = new StringBuffer ( ) ; for ( Iterator < Map . Entry < String , String > > iterator = components . entrySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Map . Entry < String , String > entry = iterator . next ( ) ; filters . append ( entry . getKey ( ) + \":\" + entry . getValue ( ) != null ? entry . getValue ( ) . replace ( ' ' , ' ' ) : entry . getValue ( ) ) ; if ( iterator . hasNext ( ) ) filters . append ( \"|\" ) ; } parameters . put ( \"components\" , filters . toString ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ServiceInstance<T > instances required by the Curator interfaces . [CODESPLIT] public static ServiceInstance < BarCuratorService > convert ( BarCuratorService bar ) throws Exception { ServiceInstanceBuilder < BarCuratorService > builder = ServiceInstance . builder ( ) ; // these values are for the most part nonsensical. return builder . payload ( bar ) . uriSpec ( new UriSpec ( \"http://\" ) ) . sslPort ( 2400 ) . serviceType ( ServiceType . STATIC ) . port ( 2300 ) . address ( \"127.0.0.1\" ) . id ( String . format ( \"bar-%s-%d-%s\" , bar . a , bar . b , bar . c ) ) . name ( bar . name ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ServiceInstance<T > instances required by the Curator interfaces . [CODESPLIT] public static ServiceInstance < BarCuratorService > convert ( Service svc ) throws Exception { BarCuratorService bar = new BarCuratorService ( svc . getMetadata ( ) . get ( \"name\" ) , svc . getMetadata ( ) . get ( \"a\" ) , Integer . parseInt ( svc . getMetadata ( ) . get ( \"b\" ) ) , Float . parseFloat ( svc . getMetadata ( ) . get ( \"c\" ) ) ) ; return convert ( bar ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return all distinct names registered by this discovery type . [CODESPLIT] public Collection < String > queryForNames ( ) throws Exception { Set < String > names = new HashSet < String > ( ) ; // todo: it would be better to do: // services = client.getServicesClient().list(options, typeTag); // but there are some validation problems (the tag is allowed to be written, but not queried on). Iterator < Service > services = client . getServicesClient ( ) . list ( new MethodOptions ( 100 , null ) ) ; while ( services . hasNext ( ) ) { Service service = services . next ( ) ; // this conditional can be removed when the above operation works. if ( ! service . getTags ( ) . contains ( typeTag ) ) { continue ; } String name = service . getMetadata ( ) . get ( ServiceTracker . NAME ) ; if ( ! names . contains ( name ) ) { names . add ( name ) ; } } return names ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return all instances registered to this particular name for this discovery type [CODESPLIT] public Collection < ServiceInstance < T > > queryForInstances ( String name ) throws Exception { List < ServiceInstance < T >> serviceInstances = new ArrayList < ServiceInstance < T > > ( ) ; Iterator < Service > services = client . getServicesClient ( ) . list ( new MethodOptions ( 100 , null ) ) ; while ( services . hasNext ( ) ) { Service service = services . next ( ) ; if ( service . getTags ( ) . contains ( typeTag ) && service . getMetadata ( ) . get ( ServiceTracker . NAME ) . equals ( name ) ) { // does the job of the serializer in the curator code (theirs is just a json marshaller anyway). serviceInstances . add ( convert ( service ) ) ; } } return serviceInstances ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO Refactor HATEOAS link building . Time for ResourceAssembler or moving this stuff up the service . Although moving it up will create a circular dep . [CODESPLIT] @ RequestMapping ( value = \"\" , method = { RequestMethod . GET , RequestMethod . HEAD } ) public Resources < StateDefinitionResource > getStateDefinitions ( ) throws StateDefinitionNotFoundException , ProviderNotFoundException , AttributeDefinitionNotFoundException { if ( LOG . isTraceEnabled ( ) ) { LOG . entry ( ) ; } final Resources < StateDefinitionResource > resources = getStateDefinitions ( stateDefinitionService . getStateDefinitions ( ) ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . exit ( resources ) ; } return resources ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "taken from spark ( https : // github . com / perwendel / spark ) [CODESPLIT] public static Map < String , String > getParams ( List < String > request , List < String > matched ) { Map < String , String > params = new HashMap <> ( ) ; for ( int i = 0 ; ( i < request . size ( ) ) && ( i < matched . size ( ) ) ; i ++ ) { String matchedPart = matched . get ( i ) ; if ( SparkUtils . isParam ( matchedPart ) ) { params . put ( matchedPart . toLowerCase ( ) , request . get ( i ) ) ; } } return Collections . unmodifiableMap ( params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "taken from spark ( https : // github . com / perwendel / spark ) [CODESPLIT] public static List < String > getSplat ( List < String > request , List < String > matched ) { int nbrOfRequestParts = request . size ( ) ; int nbrOfMatchedParts = matched . size ( ) ; boolean sameLength = ( nbrOfRequestParts == nbrOfMatchedParts ) ; List < String > splat = new ArrayList <> ( ) ; for ( int i = 0 ; ( i < nbrOfRequestParts ) && ( i < nbrOfMatchedParts ) ; i ++ ) { String matchedPart = matched . get ( i ) ; if ( SparkUtils . isSplat ( matchedPart ) ) { StringBuilder splatParam = new StringBuilder ( request . get ( i ) ) ; if ( ! sameLength && ( i == ( nbrOfMatchedParts - 1 ) ) ) { for ( int j = i + 1 ; j < nbrOfRequestParts ; j ++ ) { splatParam . append ( \"/\" ) ; splatParam . append ( request . get ( j ) ) ; } } splat . add ( splatParam . toString ( ) ) ; } } return Collections . unmodifiableList ( splat ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Fluid Item... if ( this . getFluidItem ( ) != null ) { returnVal . put ( JSONMapping . FLUID_ITEM , this . getFluidItem ( ) . toJsonObject ( ) ) ; } //Flow Step Rule... if ( this . getFlowStepRule ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STEP_RULE , this . getFlowStepRule ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Key... if ( this . getKey ( ) != null ) { returnVal . put ( JSONMapping . KEY , this . getKey ( ) ) ; } //Value... if ( this . getValue ( ) != null ) { returnVal . put ( JSONMapping . VALUE , this . getValue ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Form Container / Electronic Forms . [CODESPLIT] public List < Collaboration > createCollaboration ( List < Collaboration > collaborationsParam ) { CollaborationListing collaborationListing = new CollaborationListing ( ) ; collaborationListing . setListing ( collaborationsParam ) ; if ( this . serviceTicket != null ) { collaborationListing . setServiceTicket ( this . serviceTicket ) ; } return new CollaborationListing ( this . putJson ( collaborationListing , WS . Path . Collaboration . Version1 . collaborationCreate ( ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all Collaboration items TO where logged in user . [CODESPLIT] public List < Collaboration > getAllToByLoggedIn ( ) { CollaborationListing collaborationListing = new CollaborationListing ( ) ; if ( this . serviceTicket != null ) { collaborationListing . setServiceTicket ( this . serviceTicket ) ; } return new CollaborationListing ( this . postJson ( collaborationListing , WS . Path . Collaboration . Version1 . getAllToByLoggedIn ( ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all Collaboration items TO where { @code Form } is { @code formParam } . [CODESPLIT] public List < Collaboration > getAllToByForm ( Form formParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } return new CollaborationListing ( this . postJson ( formParam , WS . Path . Collaboration . Version1 . getAllToByForm ( ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Form Container... if ( this . getFormContainer ( ) != null ) { returnVal . put ( JSONMapping . FORM_CONTAINER , this . getFormContainer ( ) . toJsonObject ( ) ) ; } //Parent Form Container... if ( this . getParentFormContainer ( ) != null ) { returnVal . put ( JSONMapping . PARENT_FORM_CONTAINER , this . getParentFormContainer ( ) . toJsonObject ( ) ) ; } //Parent Form Field... if ( this . getParentFormField ( ) != null ) { returnVal . put ( JSONMapping . PARENT_FORM_FIELD , this . getParentFormField ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Can Create... if ( this . isCanCreateAndModify ( ) != null ) { returnVal . put ( JSONMapping . CAN_CREATE_AND_MODIFY , this . isCanCreateAndModify ( ) . booleanValue ( ) ) ; } //Can View... if ( this . isCanView ( ) != null ) { returnVal . put ( JSONMapping . CAN_VIEW , this . isCanView ( ) . booleanValue ( ) ) ; } //Form Definition... if ( this . getFormFieldToFormDefinition ( ) != null ) { returnVal . put ( JSONMapping . FORM_FIELD_TO_FORM_DEFINITION , this . getFormFieldToFormDefinition ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = new JSONObject ( ) ; //Template Name... if ( this . getTemplateName ( ) != null ) { returnVal . put ( JSONMapping . TEMPLATE_NAME , this . getTemplateName ( ) ) ; } //Template Description... if ( this . getTemplateDescription ( ) != null ) { returnVal . put ( JSONMapping . TEMPLATE_DESCRIPTION , this . getTemplateDescription ( ) ) ; } //Template Comment... if ( this . getTemplateComment ( ) != null ) { returnVal . put ( JSONMapping . TEMPLATE_COMMENT , this . getTemplateComment ( ) ) ; } //Forms and Fields... if ( this . getFormsAndFields ( ) != null && ! this . getFormsAndFields ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( Form form : this . getFormsAndFields ( ) ) { jsonArray . put ( form . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . FORMS_AND_FIELDS , jsonArray ) ; } //User Queries... if ( this . getUserQueries ( ) != null && ! this . getUserQueries ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( UserQuery userQuery : this . getUserQueries ( ) ) { jsonArray . put ( userQuery . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . USER_QUERIES , jsonArray ) ; } //Flows... if ( this . getFlows ( ) != null && ! this . getFlows ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( Flow flow : this . getFlows ( ) ) { jsonArray . put ( flow . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . FLOWS , jsonArray ) ; } //Third Party Libraries... if ( this . getThirdPartyLibraries ( ) != null && ! this . getThirdPartyLibraries ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( ThirdPartyLibrary thirdPartyLibrary : this . getThirdPartyLibraries ( ) ) { jsonArray . put ( thirdPartyLibrary . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . THIRD_PARTY_LIBRARIES , jsonArray ) ; } //User Fields... if ( this . getUserFields ( ) != null && ! this . getUserFields ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( Field field : this . getUserFields ( ) ) { jsonArray . put ( field . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . USER_FIELDS , jsonArray ) ; } //Route Fields... if ( this . getRouteFields ( ) != null && ! this . getRouteFields ( ) . isEmpty ( ) ) { JSONArray fieldsArr = new JSONArray ( ) ; for ( Field toAdd : this . getRouteFields ( ) ) { fieldsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ROUTE_FIELDS , fieldsArr ) ; } //Global Fields... if ( this . getGlobalFields ( ) != null && ! this . getGlobalFields ( ) . isEmpty ( ) ) { JSONArray fieldsArr = new JSONArray ( ) ; for ( Field toAdd : this . getGlobalFields ( ) ) { fieldsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . GLOBAL_FIELDS , fieldsArr ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Name... if ( this . getName ( ) != null ) { returnVal . put ( JSONMapping . NAME , this . getName ( ) ) ; } //Description... if ( this . getDescription ( ) != null ) { returnVal . put ( JSONMapping . DESCRIPTION , this . getDescription ( ) ) ; } //Flow Steps... if ( this . getFlowSteps ( ) != null && ! this . getFlowSteps ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( FlowStep rule : this . getFlowSteps ( ) ) { jsonArray . put ( rule . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . FLOW_STEPS , jsonArray ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( JSONMapping . DATE_LAST_UPDATED , this . getDateAsLongFromJson ( this . getDateLastUpdated ( ) ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct the correct Meta - Data from parameters . [CODESPLIT] protected String getMetaDataForDecimalAs ( String metaDataPrefixParam , double minParam , double maxParam , double stepFactorParam , String prefixParam ) { StringBuffer returnBuffer = new StringBuffer ( ) ; if ( metaDataPrefixParam != null && ! metaDataPrefixParam . isEmpty ( ) ) { returnBuffer . append ( metaDataPrefixParam ) ; } //Min... returnBuffer . append ( FieldMetaData . Decimal . UNDERSCORE ) ; returnBuffer . append ( FieldMetaData . Decimal . MIN ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_OPEN ) ; returnBuffer . append ( minParam ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_CLOSE ) ; returnBuffer . append ( FieldMetaData . Decimal . UNDERSCORE ) ; //Max... returnBuffer . append ( FieldMetaData . Decimal . MAX ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_OPEN ) ; returnBuffer . append ( maxParam ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_CLOSE ) ; returnBuffer . append ( FieldMetaData . Decimal . UNDERSCORE ) ; //Step Factor... returnBuffer . append ( FieldMetaData . Decimal . STEP_FACTOR ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_OPEN ) ; returnBuffer . append ( stepFactorParam ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_CLOSE ) ; returnBuffer . append ( FieldMetaData . Decimal . UNDERSCORE ) ; //Prefix String prefix = ( prefixParam == null ) ? \"\" : prefixParam ; returnBuffer . append ( FieldMetaData . Decimal . PREFIX ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_OPEN ) ; returnBuffer . append ( prefix ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_CLOSE ) ; return returnBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code User } with the Email Fields and Roles inside the { @code userParam } . [CODESPLIT] public User createUser ( User userParam ) { if ( userParam != null && this . serviceTicket != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } return new User ( this . putJson ( userParam , WS . Path . User . Version1 . userCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing { @code User } with the Email Fields and Roles inside the { @code userParam } . [CODESPLIT] public User updateUser ( User userParam ) { if ( userParam != null && this . serviceTicket != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } return new User ( this . postJson ( userParam , WS . Path . User . Version1 . userUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Activate an existing { @code User } that is currently Deactivated . [CODESPLIT] public User activateUser ( User userParam ) { if ( userParam != null && this . serviceTicket != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } return new User ( this . postJson ( userParam , WS . Path . User . Version1 . userActivate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deactivate an existing { @code User } that is currently Active . [CODESPLIT] public User deActivateUser ( User userParam ) { if ( userParam != null && this . serviceTicket != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } return new User ( this . postJson ( userParam , WS . Path . User . Version1 . userDeActivate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Increment the invalid login count for { @code userParam } . [CODESPLIT] public User incrementInvalidLoginForUser ( User userParam ) { if ( userParam != null && this . serviceTicket != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } return new User ( this . postJson ( userParam , WS . Path . User . Version1 . incrementInvalidLogin ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Change the password for the currently logged in user . [CODESPLIT] public User changePasswordForLoggedInUser ( String existingPasswordParam , String newPasswordParam , String confirmNewPasswordParam ) { User toChangePasswordFor = new User ( ) ; if ( this . serviceTicket != null ) { toChangePasswordFor . setServiceTicket ( this . serviceTicket ) ; } String existingPassword = existingPasswordParam == null ? UtilGlobal . EMPTY : existingPasswordParam ; String newPassword = newPasswordParam == null ? UtilGlobal . EMPTY : newPasswordParam ; String confirmNewPassword = confirmNewPasswordParam == null ? UtilGlobal . EMPTY : confirmNewPasswordParam ; JSONObject passwordClear = new JSONObject ( ) ; passwordClear . put ( \"existing\" , existingPassword ) ; passwordClear . put ( \"new\" , newPassword ) ; passwordClear . put ( \"confirm_new\" , confirmNewPassword ) ; toChangePasswordFor . setPasswordClear ( passwordClear . toString ( ) ) ; return new User ( this . postJson ( toChangePasswordFor , WS . Path . User . Version1 . changePassword ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the { @code User } provided . Id must be set on the { @code User } . [CODESPLIT] public User deleteUser ( User userToDeleteParam , boolean forcefullyDeleteParam ) { if ( userToDeleteParam != null && this . serviceTicket != null ) { userToDeleteParam . setServiceTicket ( this . serviceTicket ) ; } return new User ( this . postJson ( userToDeleteParam , WS . Path . User . Version1 . userDelete ( forcefullyDeleteParam ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves user information for the logged in { @code User } . [CODESPLIT] public User getLoggedInUserInformation ( ) { User userToGetInfoFor = new User ( ) ; if ( this . serviceTicket != null ) { userToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new User ( this . postJson ( userToGetInfoFor , WS . Path . User . Version1 . userInformation ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves user information for the provided { @code usernameParam } . [CODESPLIT] public User getUserWhereUsername ( String usernameParam ) { User userToGetInfoFor = new User ( ) ; userToGetInfoFor . setUsername ( usernameParam ) ; if ( this . serviceTicket != null ) { userToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new User ( this . postJson ( userToGetInfoFor , WS . Path . User . Version1 . getByUsername ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves user information for the provided { @code emailAddressParam } . [CODESPLIT] public User getUserWhereEmail ( String emailAddressParam ) { User userToGetInfoFor = new User ( ) ; if ( emailAddressParam != null ) { List < String > emailAdd = new ArrayList ( ) ; emailAdd . add ( emailAddressParam ) ; userToGetInfoFor . setEmailAddresses ( emailAdd ) ; } if ( this . serviceTicket != null ) { userToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new User ( this . postJson ( userToGetInfoFor , WS . Path . User . Version1 . getByEmail ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves user information for the provided { @code userIdParam } . [CODESPLIT] public User getUserById ( Long userIdParam ) { User userToGetInfoFor = new User ( ) ; userToGetInfoFor . setId ( userIdParam ) ; if ( this . serviceTicket != null ) { userToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new User ( this . postJson ( userToGetInfoFor , WS . Path . User . Version1 . getById ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all user information . [CODESPLIT] public UserListing getAllUsers ( ) { UserListing userToGetInfoFor = new UserListing ( ) ; if ( this . serviceTicket != null ) { userToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new UserListing ( this . postJson ( userToGetInfoFor , WS . Path . User . Version1 . getAllUsers ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Users by { @code jobViewParam } . [CODESPLIT] public UserListing getAllUsersByJobView ( JobView jobViewParam ) { if ( this . serviceTicket != null && jobViewParam != null ) { jobViewParam . setServiceTicket ( this . serviceTicket ) ; } try { return new UserListing ( this . postJson ( jobViewParam , WS . Path . User . Version1 . getAllUsersByJobView ( ) ) ) ; } catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Users by { @code roleParam } . [CODESPLIT] public UserListing getAllUsersByRole ( Role roleParam ) { if ( this . serviceTicket != null && roleParam != null ) { roleParam . setServiceTicket ( this . serviceTicket ) ; } try { return new UserListing ( this . postJson ( roleParam , WS . Path . User . Version1 . getAllUsersByRole ( ) ) ) ; } catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Users by { @code roleParam } . [CODESPLIT] public UserListing getAllUsersWhereLoggedInSince ( Date loggedInSinceParam ) { User userToPost = new User ( ) ; userToPost . setLoggedInDateTime ( loggedInSinceParam ) ; if ( this . serviceTicket != null ) { userToPost . setServiceTicket ( this . serviceTicket ) ; } try { return new UserListing ( this . postJson ( userToPost , WS . Path . User . Version1 . getAllUsersWhereLoggedInSince ( ) ) ) ; } catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all user field values information by the { @code userParam } . [CODESPLIT] public UserFieldListing getAllUserFieldValuesByUser ( User userParam ) { if ( userParam == null ) { return null ; } if ( this . serviceTicket != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } try { return new UserFieldListing ( this . postJson ( userParam , WS . Path . User . Version1 . getUserFieldValuesByUser ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the gravatar bytes by email . [CODESPLIT] public byte [ ] getGravatarForEmail ( String emailAddressParam , int sizeParam ) { try { JSONObject gravatarJSONObj = this . getJson ( WS . Path . User . Version1 . getGravatarByEmail ( emailAddressParam , sizeParam ) ) ; String base64Text = gravatarJSONObj . optString ( JSON_TAG_DATA , \"\" ) ; if ( base64Text == null || base64Text . isEmpty ( ) ) { return null ; } return UtilGlobal . decodeBase64 ( base64Text ) ; } //JSON Parsing... catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , jsonExcept , FluidClientException . ErrorCode . JSON_PARSING ) ; } //Encoding not supported... catch ( UnsupportedEncodingException unsEncExcept ) { throw new FluidClientException ( unsEncExcept . getMessage ( ) , unsEncExcept , FluidClientException . ErrorCode . IO_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the gravatar bytes for Fluid user . [CODESPLIT] public byte [ ] getGravatarForUser ( User userParam , int sizeParam ) { if ( userParam == null ) { return null ; } try { JSONObject gravatarJSONObj = this . postJson ( userParam , WS . Path . User . Version1 . getGravatarByUser ( sizeParam ) ) ; String base64Text = gravatarJSONObj . optString ( JSON_TAG_DATA , \"\" ) ; if ( base64Text == null || base64Text . isEmpty ( ) ) { return null ; } return UtilGlobal . decodeBase64 ( base64Text ) ; } //JSON problem... catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , jsonExcept , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether { @code this } { @code User } has access to role { @code roleParam } . [CODESPLIT] @ XmlTransient public boolean doesUserHaveAccessToRole ( Role roleParam ) { if ( roleParam == null ) { return false ; } return this . doesUserHaveAccessToRole ( roleParam . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether { @code this } { @code User } has access to role with name { @code roleParam } . [CODESPLIT] @ XmlTransient public boolean doesUserHaveAccessToRole ( String roleNameParam ) { if ( roleNameParam == null || roleNameParam . trim ( ) . isEmpty ( ) ) { return false ; } if ( this . getRoles ( ) == null || this . getRoles ( ) . isEmpty ( ) ) { return false ; } String roleNameParamLower = roleNameParam . trim ( ) . toLowerCase ( ) ; for ( Role roleAtIndex : this . getRoles ( ) ) { if ( roleAtIndex . getName ( ) == null || roleAtIndex . getName ( ) . trim ( ) . isEmpty ( ) ) { continue ; } String iterRoleNameLower = roleAtIndex . getName ( ) . trim ( ) . toLowerCase ( ) ; if ( roleNameParamLower . equals ( iterRoleNameLower ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Active... returnVal . put ( JSONMapping . ACTIVE , this . isActive ( ) ) ; //Invalid Login Count... returnVal . put ( JSONMapping . INVALID_LOGIN_COUNT , this . getInvalidLoginCount ( ) ) ; //Username... if ( this . getUsername ( ) != null ) { returnVal . put ( JSONMapping . USERNAME , this . getUsername ( ) ) ; } //Password Sha 256... if ( this . getPasswordSha256 ( ) != null ) { returnVal . put ( JSONMapping . PASSWORD_SHA_256 , this . getPasswordSha256 ( ) ) ; } //Password Clear... if ( this . getPasswordClear ( ) != null ) { returnVal . put ( JSONMapping . PASSWORD_CLEAR , this . getPasswordClear ( ) ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( User . JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( User . JSONMapping . DATE_LAST_UPDATED , this . getDateAsLongFromJson ( this . getDateLastUpdated ( ) ) ) ; } //Password Changed At... if ( this . getPasswordChangedAt ( ) != null ) { returnVal . put ( JSONMapping . PASSWORD_CHANGED_AT , this . getDateAsLongFromJson ( this . getPasswordChangedAt ( ) ) ) ; } //Logged In Date Time... if ( this . getLoggedInDateTime ( ) != null ) { returnVal . put ( JSONMapping . LOGGED_IN_DATE_TIME , this . getDateAsLongFromJson ( this . getLoggedInDateTime ( ) ) ) ; } //SALT... if ( this . getSalt ( ) != null ) { returnVal . put ( JSONMapping . SALT , this . getSalt ( ) ) ; } //Timezone... if ( this . getTimezone ( ) != null ) { returnVal . put ( JSONMapping . TIMEZONE , this . getTimezone ( ) . doubleValue ( ) ) ; } //Date Format... if ( this . getDateFormat ( ) != null ) { returnVal . put ( JSONMapping . DATE_FORMAT , this . getDateFormat ( ) ) ; } //Time Format... if ( this . getTimeFormat ( ) != null ) { returnVal . put ( JSONMapping . TIME_FORMAT , this . getTimeFormat ( ) ) ; } //Locale... if ( this . getLocale ( ) != null ) { returnVal . put ( JSONMapping . LOCALE , this . getLocale ( ) ) ; } //Email Notification... returnVal . put ( JSONMapping . EMAIL_USER_NOTIFICATION , this . isEmailUserNotification ( ) ) ; //Roles... if ( this . getRoles ( ) != null && ! this . getRoles ( ) . isEmpty ( ) ) { JSONArray rolesArr = new JSONArray ( ) ; for ( Role toAdd : this . getRoles ( ) ) { rolesArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ROLES , rolesArr ) ; } //Email Addresses... if ( this . getEmailAddresses ( ) != null && ! this . getEmailAddresses ( ) . isEmpty ( ) ) { JSONArray emailArr = new JSONArray ( ) ; for ( String toAdd : this . getEmailAddresses ( ) ) { emailArr . put ( toAdd ) ; } returnVal . put ( JSONMapping . EMAIL_ADDRESSES , emailArr ) ; } //User Fields... if ( this . getUserFields ( ) != null && ! this . getUserFields ( ) . isEmpty ( ) ) { JSONArray userFieldsArr = new JSONArray ( ) ; for ( Field toAdd : this . getUserFields ( ) ) { userFieldsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . USER_FIELDS , userFieldsArr ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Field getField ( String fieldNameParam ) { if ( fieldNameParam == null || fieldNameParam . trim ( ) . isEmpty ( ) ) { return null ; } if ( this . userFields == null || this . userFields . isEmpty ( ) ) { return null ; } String fieldNameParamLower = fieldNameParam . trim ( ) . toLowerCase ( ) ; for ( Field field : this . userFields ) { String fieldName = field . getFieldName ( ) ; if ( fieldName == null || fieldName . trim ( ) . isEmpty ( ) ) { continue ; } String fieldNameLower = fieldName . trim ( ) . toLowerCase ( ) ; if ( fieldNameParamLower . equals ( fieldNameLower ) ) { return field ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code MultiChoice } . [CODESPLIT] @ XmlTransient public MultiChoice getFieldValueAsMultiChoice ( String fieldNameParam ) { Field fieldReturn = this . getField ( fieldNameParam ) ; return ( fieldReturn == null ) ? null : fieldReturn . getFieldValueAsMultiChoice ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Job View... if ( this . getJobView ( ) != null ) { returnVal . put ( JSONMapping . JOB_VIEW , this . getJobView ( ) . toJsonObject ( ) ) ; } //Role... if ( this . getRole ( ) != null ) { returnVal . put ( JSONMapping . ROLE , this . getRole ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code String } . [CODESPLIT] @ XmlTransient public String getFieldValueAsString ( ) { Object returnObj = this . getFieldValue ( ) ; return ( returnObj == null ) ? null : returnObj . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code Double } . [CODESPLIT] @ XmlTransient public Double getFieldValueAsDouble ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } if ( obj instanceof Double ) { return ( Double ) obj ; } if ( obj instanceof Number ) { return ( ( Number ) obj ) . doubleValue ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code Long } . [CODESPLIT] @ XmlTransient public Long getFieldValueAsLong ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } if ( obj instanceof Long ) { return ( Long ) obj ; } if ( obj instanceof Number ) { return ( ( Number ) obj ) . longValue ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code Integer } . [CODESPLIT] @ XmlTransient public Integer getFieldValueAsInteger ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } if ( obj instanceof Integer ) { return ( Integer ) obj ; } if ( obj instanceof Number ) { return ( ( Number ) obj ) . intValue ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code Number } . [CODESPLIT] @ XmlTransient public Number getFieldValueAsNumber ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } if ( obj instanceof Number ) { return ( Number ) obj ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code Boolean } . [CODESPLIT] @ XmlTransient public Boolean getFieldValueAsBoolean ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } if ( obj instanceof Boolean ) { return ( Boolean ) obj ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code Date } . [CODESPLIT] @ XmlTransient public Date getFieldValueAsDate ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } //Real Date... if ( obj instanceof Date ) { return ( Date ) obj ; } //Long... else if ( obj instanceof Long ) { Long longValue = ( Long ) obj ; if ( longValue . longValue ( ) > 0 ) { return new Date ( longValue . longValue ( ) ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code MultiChoice } . [CODESPLIT] @ XmlTransient public MultiChoice getFieldValueAsMultiChoice ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } if ( obj instanceof MultiChoice ) { return ( MultiChoice ) obj ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of { @code this } { @code Field } as a { @code TableField } . [CODESPLIT] @ XmlTransient public TableField getFieldValueAsTableField ( ) { Object obj = this . getFieldValue ( ) ; if ( obj == null ) { return null ; } if ( obj instanceof TableField ) { return ( TableField ) obj ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of { @code this } { @code Field } . [CODESPLIT] public void setFieldValue ( Object fieldValueParam ) { this . fieldValue = fieldValueParam ; if ( this . getFieldType ( ) == null && fieldValueParam != null ) { //Date... if ( fieldValueParam instanceof Date ) { this . setTypeAsEnum ( Type . DateTime ) ; } //Number... else if ( fieldValueParam instanceof Number ) { this . setTypeAsEnum ( Type . Decimal ) ; } //MultiChoice... else if ( fieldValueParam instanceof MultiChoice ) { this . setTypeAsEnum ( Type . MultipleChoice ) ; } //Table Field... else if ( fieldValueParam instanceof TableField ) { this . setTypeAsEnum ( Type . Table ) ; } //Text... else if ( fieldValueParam instanceof String ) { this . setTypeAsEnum ( Type . Text ) ; } //Boolean... else if ( fieldValueParam instanceof Boolean ) { this . setTypeAsEnum ( Type . TrueFalse ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the Type of { @code this } { @code Field } as { @code enum } . [CODESPLIT] @ XmlTransient public void setTypeAsEnum ( Type typeParam ) { if ( typeParam == null ) { this . fieldType = null ; return ; } this . fieldType = typeParam . name ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the Type of { @code this } { @code Field } as { @code enum } . [CODESPLIT] @ XmlTransient public Type getTypeAsEnum ( ) { if ( this . getFieldType ( ) == null || this . getFieldType ( ) . trim ( ) . isEmpty ( ) ) { return null ; } return Type . valueOf ( this . getFieldType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Field Name... if ( this . getFieldName ( ) != null ) { returnVal . put ( JSONMapping . FIELD_NAME , this . getFieldName ( ) ) ; } //Field Description... if ( this . getFieldDescription ( ) != null ) { returnVal . put ( JSONMapping . FIELD_DESCRIPTION , this . getFieldDescription ( ) ) ; } //Field Value... if ( this . getFieldValue ( ) != null ) { //Text... if ( this . getFieldValue ( ) instanceof String ) { returnVal . put ( JSONMapping . FIELD_VALUE , this . getFieldValue ( ) ) ; } //Decimal... else if ( this . getFieldValue ( ) instanceof Number ) { returnVal . put ( JSONMapping . FIELD_VALUE , ( ( Number ) this . getFieldValue ( ) ) . doubleValue ( ) ) ; } //True False... else if ( this . getFieldValue ( ) instanceof Boolean ) { returnVal . put ( JSONMapping . FIELD_VALUE , ( Boolean ) this . getFieldValue ( ) ) ; } //Date Time... else if ( this . getFieldValue ( ) instanceof Date ) { returnVal . put ( JSONMapping . FIELD_VALUE , this . getDateAsLongFromJson ( ( Date ) this . getFieldValue ( ) ) ) ; } //Multi Choice... else if ( this . getFieldValue ( ) instanceof MultiChoice ) { returnVal . put ( JSONMapping . FIELD_VALUE , ( ( MultiChoice ) this . getFieldValue ( ) ) . toJsonObject ( ) ) ; } //Table Field... else if ( this . getFieldValue ( ) instanceof TableField ) { returnVal . put ( JSONMapping . FIELD_VALUE , ( ( TableField ) this . getFieldValue ( ) ) . toJsonObject ( ) ) ; } else { returnVal . put ( JSONMapping . FIELD_VALUE , this . getFieldValue ( ) ) ; } } //Type... if ( this . getFieldType ( ) != null ) { returnVal . put ( JSONMapping . FIELD_TYPE , this . getFieldType ( ) ) ; } //Type Meta Data... if ( this . getTypeMetaData ( ) != null ) { returnVal . put ( JSONMapping . TYPE_META_DATA , this . getTypeMetaData ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the mapping object required by Elastic Search when making use of enhanced data - types . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonMappingForElasticSearch ( ) throws JSONException { String fieldNameUpperCamel = this . getFieldNameAsUpperCamel ( ) ; if ( fieldNameUpperCamel == null ) { return null ; } String elasticType = this . getElasticSearchFieldType ( ) ; if ( elasticType == null ) { return null ; } JSONObject returnVal = new JSONObject ( ) ; returnVal . put ( JSONMapping . Elastic . MAPPING_ONLY_TYPE , elasticType ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } for storage in ElasticSearch . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonForElasticSearch ( ) throws JSONException { if ( ! this . doesFieldQualifyForElasticSearchInsert ( ) ) { return null ; } JSONObject returnVal = new JSONObject ( ) ; String fieldIdAsString = this . getFieldNameAsUpperCamel ( ) ; Object fieldValue = this . getFieldValue ( ) ; //Table Field... if ( fieldValue instanceof TableField ) { TableField tableField = ( TableField ) this . getFieldValue ( ) ; if ( tableField . getTableRecords ( ) != null && ! tableField . getTableRecords ( ) . isEmpty ( ) ) { JSONArray array = new JSONArray ( ) ; for ( Form record : tableField . getTableRecords ( ) ) { if ( record . getId ( ) == null ) { continue ; } array . put ( record . getId ( ) ) ; } returnVal . put ( fieldIdAsString , array ) ; } } //Multiple Choice... else if ( fieldValue instanceof MultiChoice ) { MultiChoice multiChoice = ( MultiChoice ) this . getFieldValue ( ) ; if ( multiChoice . getSelectedMultiChoices ( ) != null && ! multiChoice . getSelectedMultiChoices ( ) . isEmpty ( ) ) { JSONArray array = new JSONArray ( ) ; for ( String selectedChoice : multiChoice . getSelectedMultiChoices ( ) ) { Long selectedChoiceAsLong = null ; try { if ( ! selectedChoice . isEmpty ( ) && Character . isDigit ( selectedChoice . charAt ( 0 ) ) ) { selectedChoiceAsLong = Long . parseLong ( selectedChoice ) ; } } catch ( NumberFormatException nfe ) { selectedChoiceAsLong = null ; } //When not long, store as is... if ( selectedChoiceAsLong == null ) { array . put ( selectedChoice ) ; } else { array . put ( selectedChoiceAsLong . longValue ( ) ) ; } } returnVal . put ( fieldIdAsString , array ) ; } } //Other valid types... else if ( ( fieldValue instanceof Number || fieldValue instanceof Boolean ) || fieldValue instanceof String ) { if ( ( fieldValue instanceof String ) && LATITUDE_AND_LONGITUDE . equals ( this . getTypeMetaData ( ) ) ) { String formFieldValueStr = fieldValue . toString ( ) ; UtilGlobal utilGlobal = new UtilGlobal ( ) ; String latitude = utilGlobal . getLatitudeFromFluidText ( formFieldValueStr ) ; String longitude = utilGlobal . getLongitudeFromFluidText ( formFieldValueStr ) ; fieldValue = ( latitude . concat ( UtilGlobal . COMMA ) . concat ( longitude ) ) ; } returnVal . put ( fieldIdAsString , fieldValue ) ; } //Date... else if ( fieldValue instanceof Date ) { returnVal . put ( fieldIdAsString , ( ( Date ) fieldValue ) . getTime ( ) ) ; } //Problem else { throw new FluidElasticSearchException ( \"Field Value of field-type '\" + fieldValue . getClass ( ) . getSimpleName ( ) + \"' and Value '\" + fieldValue + \"' is not supported.\" ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the object based on the ElasticSearch JSON structure . [CODESPLIT] @ XmlTransient public Field populateFromElasticSearchJson ( JSONObject jsonObjectParam ) throws JSONException { if ( this . getFieldNameAsUpperCamel ( ) == null ) { return null ; } String fieldIdAsString = this . getFieldNameAsUpperCamel ( ) ; if ( jsonObjectParam . isNull ( fieldIdAsString ) ) { return null ; } Field . Type type ; if ( ( type = this . getTypeAsEnum ( ) ) == null ) { return null ; } Object formFieldValue = jsonObjectParam . get ( fieldIdAsString ) ; Field fieldToAdd = null ; switch ( type ) { case DateTime : if ( formFieldValue instanceof Long ) { fieldToAdd = new Field ( this . getId ( ) , this . getFieldName ( ) , new Date ( ( ( Long ) formFieldValue ) . longValue ( ) ) , type ) ; } break ; case Decimal : if ( formFieldValue instanceof Number ) { fieldToAdd = new Field ( this . getId ( ) , this . getFieldName ( ) , ( ( Number ) formFieldValue ) . doubleValue ( ) , type ) ; } break ; case MultipleChoice : if ( formFieldValue instanceof JSONArray ) { JSONArray casted = ( JSONArray ) formFieldValue ; List < String > selectedChoices = new ArrayList ( ) ; for ( int index = 0 ; index < casted . length ( ) ; index ++ ) { selectedChoices . add ( casted . get ( index ) . toString ( ) ) ; } if ( selectedChoices . isEmpty ( ) ) { return null ; } MultiChoice multiChoiceToSet = new MultiChoice ( selectedChoices ) ; fieldToAdd = new Field ( this . getId ( ) , this . getFieldName ( ) , multiChoiceToSet , type ) ; } break ; case Table : List < Form > tableRecords = new ArrayList ( ) ; //When array already... if ( formFieldValue instanceof JSONArray ) { JSONArray casted = ( JSONArray ) formFieldValue ; for ( int index = 0 ; index < casted . length ( ) ; index ++ ) { Object obAtIndex = casted . get ( index ) ; if ( obAtIndex instanceof Number ) { tableRecords . add ( new Form ( ( ( Number ) obAtIndex ) . longValue ( ) ) ) ; } } } //When there is only a single number stored... else if ( formFieldValue instanceof Number ) { tableRecords . add ( new Form ( ( ( Number ) formFieldValue ) . longValue ( ) ) ) ; } if ( tableRecords . isEmpty ( ) ) { return null ; } fieldToAdd = new Field ( this . getId ( ) , this . getFieldName ( ) , new TableField ( tableRecords ) , type ) ; break ; case Text : case ParagraphText : if ( formFieldValue instanceof String ) { //Latitude and Longitude storage... if ( LATITUDE_AND_LONGITUDE . equals ( this . getTypeMetaData ( ) ) ) { String formFieldValueStr = formFieldValue . toString ( ) ; UtilGlobal utilGlobal = new UtilGlobal ( ) ; double latitude = utilGlobal . getLatitudeFromElasticSearchText ( formFieldValueStr ) ; double longitude = utilGlobal . getLongitudeFromElasticSearchText ( formFieldValueStr ) ; String newFieldVal = ( latitude + UtilGlobal . PIPE + longitude + UtilGlobal . PIPE ) ; fieldToAdd = new Field ( this . getId ( ) , this . getFieldName ( ) , newFieldVal , type ) ; } else { //Other... fieldToAdd = new Field ( this . getId ( ) , this . getFieldName ( ) , formFieldValue . toString ( ) , type ) ; } } break ; case TrueFalse : if ( formFieldValue instanceof Boolean ) { fieldToAdd = new Field ( this . getId ( ) , this . getFieldName ( ) , formFieldValue , type ) ; } break ; } return fieldToAdd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Not allowed to call this method . [CODESPLIT] @ Override @ XmlTransient public void populateFromElasticSearchJson ( JSONObject jsonObjectParam , List < Field > formFieldsParam ) throws JSONException { throw new FluidElasticSearchException ( \"Method not implemented. Make use of 'populateFromElasticSearchJson(JSONObject jsonObjectParam)' method.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the ElasticSearch equivalent data field - type from the Fluid datatype . [CODESPLIT] @ XmlTransient public String getElasticSearchFieldType ( ) { Type fieldType = this . getTypeAsEnum ( ) ; if ( fieldType == null ) { return null ; } //Get the fieldType by Fluid field fieldType... switch ( fieldType ) { case ParagraphText : return ElasticSearchType . TEXT ; case Text : String metaData = this . getTypeMetaData ( ) ; if ( metaData == null || metaData . isEmpty ( ) ) { return ElasticSearchType . TEXT ; } if ( LATITUDE_AND_LONGITUDE . equals ( metaData ) ) { return ElasticSearchType . GEO_POINT ; } return ElasticSearchType . TEXT ; case TrueFalse : return ElasticSearchType . BOOLEAN ; case DateTime : return ElasticSearchType . DATE ; case Decimal : return ElasticSearchType . DOUBLE ; case MultipleChoice : return ElasticSearchType . KEYWORD ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the provided { @code fieldParam } qualifies for insert into Elastic Search . [CODESPLIT] private boolean doesFieldQualifyForElasticSearchInsert ( ) { //Test Value... Field . Type fieldType ; if ( ( ( this . getFieldValue ( ) ) == null ) || ( ( fieldType = this . getTypeAsEnum ( ) ) == null ) ) { return false ; } //Test the Name... if ( this . getFieldName ( ) == null || this . getFieldName ( ) . trim ( ) . isEmpty ( ) ) { return false ; } //Confirm the fieldType is supported... switch ( fieldType ) { case DateTime : case Decimal : case MultipleChoice : case Table : case Text : case ParagraphText : case TrueFalse : case TextEncrypted : return true ; default : return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Client ID... if ( this . getClientId ( ) != null ) { returnVal . put ( JSONMapping . CLIENT_ID , this . getClientId ( ) ) ; } //Client Secret... if ( this . getClientSecret ( ) != null ) { returnVal . put ( JSONMapping . CLIENT_SECRET , this . getClientSecret ( ) ) ; } //Code... if ( this . getCode ( ) != null ) { returnVal . put ( JSONMapping . CODE , this . getCode ( ) ) ; } //Grant Type... if ( this . getGrantType ( ) != null ) { returnVal . put ( JSONMapping . GRANT_TYPE , this . getGrantType ( ) ) ; } //Redirect URI... if ( this . getRedirectUri ( ) != null ) { returnVal . put ( JSONMapping . REDIRECT_URI , this . getRedirectUri ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the property value of the step with property name { @code nameParam } . [CODESPLIT] public void setStepProperty ( String nameParam , String valueParam ) { if ( this . getStepProperties ( ) == null ) { this . setStepProperties ( new ArrayList ( ) ) ; } if ( nameParam == null || nameParam . trim ( ) . isEmpty ( ) ) { return ; } if ( valueParam . trim ( ) . isEmpty ( ) ) { return ; } String paramLower = nameParam . toLowerCase ( ) ; for ( StepProperty existingProp : this . getStepProperties ( ) ) { if ( existingProp . getName ( ) . toLowerCase ( ) . equals ( paramLower ) ) { existingProp . setValue ( valueParam ) ; return ; } } this . getStepProperties ( ) . add ( new StepProperty ( nameParam , valueParam ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the step property with name { @code nameParam } [CODESPLIT] public String getStepProperty ( String nameParam ) { if ( this . getStepProperties ( ) == null || this . getStepProperties ( ) . isEmpty ( ) ) { return null ; } if ( nameParam == null || nameParam . trim ( ) . isEmpty ( ) ) { return null ; } String paramLower = nameParam . toLowerCase ( ) ; for ( StepProperty stepProperty : this . getStepProperties ( ) ) { if ( stepProperty . getName ( ) . toLowerCase ( ) . equals ( paramLower ) ) { return stepProperty . getValue ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Name... if ( this . getName ( ) != null ) { returnVal . put ( JSONMapping . NAME , this . getName ( ) ) ; } //Description... if ( this . getDescription ( ) != null ) { returnVal . put ( JSONMapping . DESCRIPTION , this . getDescription ( ) ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( JSONMapping . DATE_LAST_UPDATED , this . getDateAsLongFromJson ( this . getDateLastUpdated ( ) ) ) ; } //Flow... if ( this . getFlow ( ) != null ) { returnVal . put ( JSONMapping . FLOW , this . getFlow ( ) . toJsonObject ( ) ) ; } //Flow Step Type... if ( this . getFlowStepType ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STEP_TYPE , this . getFlowStepType ( ) ) ; } //Flow Step Parent Id... if ( this . getFlowStepParentId ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STEP_PARENT_ID , this . getFlowStepParentId ( ) ) ; } //Entry Rules... if ( this . getEntryRules ( ) != null && ! this . getEntryRules ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( FlowStepRule rule : this . getEntryRules ( ) ) { jsonArray . put ( rule . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ENTRY_RULES , jsonArray ) ; } //Exit Rules... if ( this . getExitRules ( ) != null && ! this . getExitRules ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( FlowStepRule rule : this . getExitRules ( ) ) { jsonArray . put ( rule . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . EXIT_RULES , jsonArray ) ; } //View Rules... if ( this . getViewRules ( ) != null && ! this . getViewRules ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( FlowStepRule rule : this . getViewRules ( ) ) { jsonArray . put ( rule . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . VIEW_RULES , jsonArray ) ; } //Step Properties... if ( this . getStepProperties ( ) != null && ! this . getStepProperties ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( StepProperty stepProperty : this . getStepProperties ( ) ) { jsonArray . put ( stepProperty . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . STEP_PROPERTIES , jsonArray ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Username... if ( this . getUsername ( ) != null ) { returnVal . put ( JSONMapping . USERNAME , this . getUsername ( ) ) ; } //Lifetime... if ( this . getLifetime ( ) != null ) { returnVal . put ( JSONMapping . LIFETIME , this . getLifetime ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Flow Step . [CODESPLIT] public FlowStep createFlowStep ( FlowStep flowStepParam ) { if ( flowStepParam != null && this . serviceTicket != null ) { flowStepParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . putJson ( flowStepParam , WS . Path . FlowStep . Version1 . flowStepCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing Flow Step . [CODESPLIT] public FlowStep updateFlowStep ( FlowStep flowStepParam ) { if ( flowStepParam != null && this . serviceTicket != null ) { flowStepParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . postJson ( flowStepParam , WS . Path . FlowStep . Version1 . flowStepUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves an existing Flow Step via Primary key . [CODESPLIT] public FlowStep getFlowStepById ( Long flowStepIdParam , String flowStepTypeParam ) { FlowStep flowStep = new FlowStep ( flowStepIdParam ) ; flowStep . setFlowStepType ( flowStepTypeParam ) ; if ( this . serviceTicket != null ) { flowStep . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . postJson ( flowStep , WS . Path . FlowStep . Version1 . getById ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves an existing Flow Step via Step . [CODESPLIT] public FlowStep getFlowStepByStep ( FlowStep flowStepParam ) { if ( this . serviceTicket != null && flowStepParam != null ) { flowStepParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . postJson ( flowStepParam , WS . Path . FlowStep . Version1 . getByStep ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Assignment { @link com . fluidbpm . program . api . vo . flow . JobView } s via Flow Step Name key . [CODESPLIT] public JobViewListing getJobViewsByStepName ( String flowStepNameParam , Flow flowParam ) { FlowStep step = new FlowStep ( ) ; step . setName ( flowStepNameParam ) ; step . setFlow ( flowParam ) ; return this . getJobViewsByStep ( step ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Assignment { @link com . fluidbpm . program . api . vo . flow . JobView } s via Flow Step Name key . [CODESPLIT] public JobView getStandardJobViewBy ( String flowNameParam , String flowStepNameParam , String flowViewNameParam ) { if ( flowNameParam == null || flowNameParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Flow name not provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( flowStepNameParam == null || flowStepNameParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Step name not provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( flowViewNameParam == null || flowViewNameParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"View name not provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } JobViewListing jobViewListing = this . getJobViewsByStepName ( flowStepNameParam , new Flow ( flowNameParam ) ) ; JobView returnVal = null ; if ( jobViewListing . getListingCount ( ) . intValue ( ) > 1 ) { for ( JobView jobView : jobViewListing . getListing ( ) ) { if ( ViewType . STANDARD . equals ( jobView . getViewType ( ) ) && jobView . getViewName ( ) . equalsIgnoreCase ( flowViewNameParam ) ) { returnVal = jobView ; break ; } } } if ( returnVal == null ) { throw new FluidClientException ( \"No View found for Flow '\" + flowNameParam + \"', Step '\" + flowStepNameParam + \"' and View '\" + flowViewNameParam + \"'.\" , FluidClientException . ErrorCode . NO_RESULT ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Assignment { @link com . fluidbpm . program . api . vo . flow . JobView } s via Flow Step Primary key . [CODESPLIT] public JobViewListing getJobViewsByStep ( FlowStep flowStepParam ) { if ( this . serviceTicket != null && flowStepParam != null ) { flowStepParam . setServiceTicket ( this . serviceTicket ) ; } return new JobViewListing ( this . postJson ( flowStepParam , WS . Path . FlowStep . Version1 . getAllViewsByStep ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Assignment { @link com . fluidbpm . program . api . vo . flow . JobView } s via logged in { @code User } . [CODESPLIT] public JobViewListing getJobViewsByLoggedInUser ( ) { FlowStep flowStep = new FlowStep ( ) ; if ( this . serviceTicket != null ) { flowStep . setServiceTicket ( this . serviceTicket ) ; } return new JobViewListing ( this . postJson ( flowStep , WS . Path . FlowStep . Version1 . getAllViewsByLoggedInUser ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Assignment { @link com . fluidbpm . program . api . vo . flow . JobView } s for { @code User } . [CODESPLIT] public JobViewListing getJobViewsByUser ( User userParam ) { if ( this . serviceTicket != null && userParam != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } return new JobViewListing ( this . postJson ( userParam , WS . Path . FlowStep . Version1 . getAllViewsByUser ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Assignment { @link com . fluidbpm . program . api . vo . flow . JobView } s for { @code Flow } . [CODESPLIT] public JobViewListing getJobViewsByFlow ( Flow flowParam ) { if ( this . serviceTicket != null && flowParam != null ) { flowParam . setServiceTicket ( this . serviceTicket ) ; } return new JobViewListing ( this . postJson ( flowParam , WS . Path . FlowStep . Version1 . getAllViewsByFlow ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Steps via Flow . [CODESPLIT] public FlowStepListing getStepsByFlow ( Flow flowParam ) { if ( this . serviceTicket != null && flowParam != null ) { flowParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepListing ( this . postJson ( flowParam , WS . Path . FlowStep . Version1 . getAllStepsByFlow ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an existing Flow Step . [CODESPLIT] public FlowStep deleteFlowStep ( FlowStep flowStepParam ) { if ( flowStepParam != null && this . serviceTicket != null ) { flowStepParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . postJson ( flowStepParam , WS . Path . FlowStep . Version1 . flowStepDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forcefully delete an existing Flow Step . [CODESPLIT] public FlowStep forceDeleteFlowStep ( FlowStep flowStepParam ) { if ( flowStepParam != null && this . serviceTicket != null ) { flowStepParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . postJson ( flowStepParam , WS . Path . FlowStep . Version1 . flowStepDelete ( true ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search against the Elasticsearch instance with the { @code qbParam } . [CODESPLIT] public final List < ElasticTypeAndId > searchAndConvertHitsToIdsOnly ( QueryBuilder qbParam , String indexParam , int offsetParam , int limitParam , Long ... formTypesParam ) { SearchHits searchHits = this . searchWithHits ( qbParam , indexParam , true , offsetParam , limitParam , formTypesParam ) ; List < ElasticTypeAndId > returnVal = null ; long totalHits ; if ( searchHits != null && ( totalHits = searchHits . getTotalHits ( ) ) > 0 ) { returnVal = new ArrayList ( ) ; if ( ( searchHits . getHits ( ) . length != totalHits ) && ( searchHits . getHits ( ) . length != limitParam ) ) { throw new FluidElasticSearchException ( \"The Hits and fetch count has mismatch. Total hits is '\" + totalHits + \"' while hits is '\" + searchHits . getHits ( ) . length + \"'.\" ) ; } long iterationMax = totalHits ; if ( limitParam > 0 && totalHits > limitParam ) { iterationMax = limitParam ; } //Iterate... for ( int index = 0 ; index < iterationMax ; index ++ ) { SearchHit searchHit = searchHits . getAt ( index ) ; String idAsString ; if ( ( idAsString = searchHit . getId ( ) ) == null ) { continue ; } returnVal . add ( new ElasticTypeAndId ( this . toLongSafe ( idAsString ) , searchHit . getType ( ) ) ) ; } } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search against the Elasticsearch instance with the { @code qbParam } . [CODESPLIT] public final SearchHits searchWithHits ( QueryBuilder qbParam , String indexParam , boolean withNoFieldsParam , int offsetParam , int limitParam , Long ... formTypesParam ) { if ( this . client == null ) { throw new ElasticsearchException ( \"Elasticsearch client is not set.\" ) ; } SearchRequestBuilder searchRequestBuilder = this . client . prepareSearch ( //Indexes... indexParam ) . setSearchType ( SearchType . DFS_QUERY_THEN_FETCH ) . setQuery ( qbParam ) . setFrom ( 0 ) . setExplain ( false ) ; //No Fields... if ( withNoFieldsParam ) { searchRequestBuilder = searchRequestBuilder . storedFields ( NO_FIELDS_MAPPER ) ; } //The requested number of results... if ( limitParam > 0 ) { searchRequestBuilder = searchRequestBuilder . setSize ( limitParam ) ; } if ( offsetParam > - 1 ) { searchRequestBuilder = searchRequestBuilder . setFrom ( offsetParam ) ; } if ( formTypesParam == null ) { formTypesParam = new Long [ ] { } ; } //If Types is set... if ( formTypesParam != null && formTypesParam . length > 0 ) { String [ ] formTypesAsString = new String [ formTypesParam . length ] ; for ( int index = 0 ; index < formTypesParam . length ; index ++ ) { Long formTypeId = formTypesParam [ index ] ; if ( formTypeId == null ) { continue ; } formTypesAsString [ index ] = formTypeId . toString ( ) ; } searchRequestBuilder = searchRequestBuilder . setTypes ( formTypesAsString ) ; } //Perform the actual search... SearchResponse searchResponse = searchRequestBuilder . execute ( ) . actionGet ( ) ; if ( searchResponse == null ) { return null ; } return searchResponse . getHits ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search against the Elasticsearch instance with the { @code qbParam } . [CODESPLIT] public final boolean searchContainHits ( QueryBuilder qbParam , String indexParam , boolean withNoFieldsParam , int offsetParam , int limitParam , Long ... formTypesParam ) { SearchHits searchHits = this . searchWithHits ( qbParam , indexParam , withNoFieldsParam , offsetParam , limitParam , formTypesParam ) ; return ( searchHits != null && searchHits . getTotalHits ( ) > 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { @code Form } s via the provided { @code formIdsParam } . [CODESPLIT] public final List < Form > getFormsByIds ( String indexParam , List < Long > formIdsParam , boolean includeFieldDataParam , int offsetParam , int limitParam ) { if ( formIdsParam == null || formIdsParam . isEmpty ( ) ) { return null ; } if ( indexParam == null || indexParam . trim ( ) . isEmpty ( ) ) { throw new FluidElasticSearchException ( \"Index is mandatory for lookup.\" ) ; } //Query using the descendantId directly... StringBuffer byIdQuery = new StringBuffer ( ) ; for ( Long formId : formIdsParam ) { byIdQuery . append ( ABaseFluidJSONObject . JSONMapping . ID ) ; byIdQuery . append ( \":\\\"\" ) ; byIdQuery . append ( formId ) ; byIdQuery . append ( \"\\\" \" ) ; } String queryByIdsToString = byIdQuery . toString ( ) ; queryByIdsToString = queryByIdsToString . substring ( 0 , queryByIdsToString . length ( ) - 1 ) ; List < Form > returnVal = null ; if ( includeFieldDataParam ) { returnVal = this . searchAndConvertHitsToFormWithAllFields ( QueryBuilders . queryStringQuery ( queryByIdsToString ) , indexParam , offsetParam , limitParam , new Long [ ] { } ) ; } else { returnVal = this . searchAndConvertHitsToFormWithNoFields ( QueryBuilders . queryStringQuery ( queryByIdsToString ) , indexParam , offsetParam , limitParam , new Long [ ] { } ) ; } if ( returnVal == null || returnVal . isEmpty ( ) ) { return null ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search against the Elasticsearch instance with the { @code qbParam } . [CODESPLIT] public final List < Form > searchAndConvertHitsToFormWithAllFields ( QueryBuilder qbParam , String indexParam , int offsetParam , int limitParam , Long ... formTypesParam ) { SearchHits searchHits = this . searchWithHits ( qbParam , indexParam , false , offsetParam , limitParam , formTypesParam ) ; List < Form > returnVal = null ; long totalHits ; if ( searchHits != null && ( totalHits = searchHits . getTotalHits ( ) ) > 0 ) { returnVal = new ArrayList ( ) ; if ( ( searchHits . getHits ( ) . length != totalHits ) && ( searchHits . getHits ( ) . length != limitParam ) ) { throw new FluidElasticSearchException ( \"The Hits and fetch count has mismatch. Total hits is '\" + totalHits + \"' while hits is '\" + searchHits . getHits ( ) . length + \"'.\" ) ; } long iterationMax = totalHits ; if ( limitParam > 0 && totalHits > limitParam ) { iterationMax = limitParam ; } //Iterate... for ( int index = 0 ; index < iterationMax ; index ++ ) { SearchHit searchHit = searchHits . getAt ( index ) ; String source ; if ( ( source = searchHit . getSourceAsString ( ) ) == null ) { continue ; } this . printInfoOnSourceFromES ( searchHit ) ; Form formFromSource = new Form ( ) ; JSONObject jsonObject = new JSONObject ( source ) ; List < Field > fieldsForForm = null ; //Is Form Type available... if ( jsonObject . has ( Form . JSONMapping . FORM_TYPE_ID ) ) { if ( this . fieldUtil == null ) { throw new FluidElasticSearchException ( \"Field Util is not set. Use a different constructor.\" ) ; } fieldsForForm = formFromSource . convertTo ( this . fieldUtil . getFormFieldMappingForFormDefinition ( jsonObject . getLong ( Form . JSONMapping . FORM_TYPE_ID ) ) ) ; } formFromSource . populateFromElasticSearchJson ( jsonObject , fieldsForForm ) ; returnVal . add ( formFromSource ) ; } } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a search against the Elasticsearch instance with the { @code qbParam } . [CODESPLIT] public final List < Form > searchAndConvertHitsToFormWithNoFields ( QueryBuilder qbParam , String indexParam , int offsetParam , int limitParam , Long ... formTypesParam ) { SearchHits searchHits = this . searchWithHits ( qbParam , indexParam , false , offsetParam , limitParam , formTypesParam ) ; List < Form > returnVal = null ; long totalHits ; if ( searchHits != null && ( totalHits = searchHits . getTotalHits ( ) ) > 0 ) { returnVal = new ArrayList ( ) ; if ( ( searchHits . getHits ( ) . length != totalHits ) && ( searchHits . getHits ( ) . length != limitParam ) ) { throw new FluidElasticSearchException ( \"The Hits and fetch count has mismatch. Total hits is '\" + totalHits + \"' while hits is '\" + searchHits . getHits ( ) . length + \"'.\" ) ; } long iterationMax = totalHits ; if ( limitParam > 0 && totalHits > limitParam ) { iterationMax = limitParam ; } //Iterate... for ( int index = 0 ; index < iterationMax ; index ++ ) { SearchHit searchHit = searchHits . getAt ( index ) ; String source ; if ( ( source = searchHit . getSourceAsString ( ) ) == null ) { continue ; } this . printInfoOnSourceFromES ( searchHit ) ; Form formFromSource = new Form ( ) ; formFromSource . populateFromElasticSearchJson ( new JSONObject ( source ) , null ) ; returnVal . add ( formFromSource ) ; } } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate all the Table Field values from the Table index . [CODESPLIT] protected final List < Form > populateTableFields ( boolean addAllTableRecordsForReturnParam , boolean includeFieldDataParam , List < Field > formFieldsParam ) { if ( formFieldsParam == null || formFieldsParam . isEmpty ( ) ) { return null ; } List < Form > allTableRecordsFromAllFields = addAllTableRecordsForReturnParam ? new ArrayList ( ) : null ; //Populate each of the Table Fields... for ( Field descendantField : formFieldsParam ) { //Skip if not Table Field... if ( ! ( descendantField . getFieldValue ( ) instanceof TableField ) ) { continue ; } TableField tableField = ( TableField ) descendantField . getFieldValue ( ) ; List < Form > tableRecordWithIdOnly = tableField . getTableRecords ( ) ; if ( tableRecordWithIdOnly == null || tableRecordWithIdOnly . isEmpty ( ) ) { continue ; } //Populate the ids for lookup... List < Long > formIdsOnly = new ArrayList ( ) ; for ( Form tableRecord : tableRecordWithIdOnly ) { formIdsOnly . add ( tableRecord . getId ( ) ) ; } List < Form > populatedTableRecords = this . getFormsByIds ( Index . TABLE_RECORD , formIdsOnly , includeFieldDataParam , DEFAULT_OFFSET , MAX_NUMBER_OF_TABLE_RECORDS ) ; if ( addAllTableRecordsForReturnParam && populatedTableRecords != null ) { allTableRecordsFromAllFields . addAll ( populatedTableRecords ) ; } tableField . setTableRecords ( populatedTableRecords ) ; descendantField . setFieldValue ( tableField ) ; } return allTableRecordsFromAllFields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Confirms whether index with the name { @code indexToCheckParam } exists . [CODESPLIT] public boolean doesIndexExist ( String indexToCheckParam ) { if ( indexToCheckParam == null || indexToCheckParam . trim ( ) . isEmpty ( ) ) { return false ; } if ( this . client == null ) { throw new FluidElasticSearchException ( \"ElasticSearch client is not initialized.\" ) ; } return this . client . admin ( ) . cluster ( ) . prepareState ( ) . execute ( ) . actionGet ( ) . getState ( ) . getMetaData ( ) . hasIndex ( indexToCheckParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the SQL and ElasticSearch Connection . [CODESPLIT] @ Override public void closeConnection ( ) { CloseConnectionRunnable closeConnectionRunnable = new CloseConnectionRunnable ( this ) ; Thread closeConnThread = new Thread ( closeConnectionRunnable , \"Close ABaseES Connection\" ) ; closeConnThread . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks to see whether { @code this } { @code Attachment } name contains the value { @code containingTextParam } . [CODESPLIT] @ XmlTransient public boolean doesNameContain ( String containingTextParam ) { if ( this . getName ( ) == null || this . getName ( ) . trim ( ) . isEmpty ( ) ) { return false ; } if ( containingTextParam == null || containingTextParam . trim ( ) . isEmpty ( ) ) { return false ; } String paramLower = containingTextParam . toLowerCase ( ) ; String nameLower = this . getName ( ) . toLowerCase ( ) ; return nameLower . contains ( paramLower ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Attachment Data... if ( this . getAttachmentDataBase64 ( ) != null ) { returnVal . put ( JSONMapping . ATTACHMENT_DATA_BASE64 , this . getAttachmentDataBase64 ( ) ) ; } //Content Type... if ( this . getContentType ( ) != null ) { returnVal . put ( JSONMapping . CONTENT_TYPE , this . getContentType ( ) ) ; } //Form Id... if ( this . getFormId ( ) != null ) { returnVal . put ( JSONMapping . FORM_ID , this . getFormId ( ) ) ; } //Name... if ( this . getName ( ) != null ) { returnVal . put ( JSONMapping . NAME , this . getName ( ) ) ; } //Path... if ( this . getPath ( ) != null ) { returnVal . put ( JSONMapping . PATH , this . getPath ( ) ) ; } //Version... if ( this . getVersion ( ) != null ) { returnVal . put ( JSONMapping . VERSION , this . getVersion ( ) ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateCreated ( ) . getTime ( ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( JSONMapping . DATE_LAST_UPDATED , this . getDateLastUpdated ( ) . getTime ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the Table Records ( Forms ) for the { @code formToGetTableFormsForParam } . [CODESPLIT] public List < Form > getTableForms ( Form formToGetTableFormsForParam , boolean includeFieldDataParam ) { if ( formToGetTableFormsForParam != null && this . serviceTicket != null ) { formToGetTableFormsForParam . setServiceTicket ( this . serviceTicket ) ; } try { FormListing formListing = new FormListing ( this . postJson ( formToGetTableFormsForParam , WS . Path . SQLUtil . Version1 . getTableForms ( includeFieldDataParam ) ) ) ; return formListing . getListing ( ) ; } // catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Descendants for the { @code formToGetTableFormsForParam } . [CODESPLIT] public List < Form > getDescendants ( Form formToGetDescendantsForParam , boolean includeFieldDataParam , boolean includeTableFieldsParam , boolean inclTableFieldFormInfoParam ) { if ( formToGetDescendantsForParam != null && this . serviceTicket != null ) { formToGetDescendantsForParam . setServiceTicket ( this . serviceTicket ) ; } try { FormListing formListing = new FormListing ( this . postJson ( formToGetDescendantsForParam , WS . Path . SQLUtil . Version1 . getDescendants ( includeFieldDataParam , includeTableFieldsParam , inclTableFieldFormInfoParam ) ) ) ; return formListing . getListing ( ) ; } // catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Ancestor for the { @code formToGetAncestorForParam } . [CODESPLIT] public Form getAncestor ( Form formToGetAncestorForParam , boolean includeFieldDataParam , boolean includeTableFieldsParam ) { if ( formToGetAncestorForParam != null && this . serviceTicket != null ) { formToGetAncestorForParam . setServiceTicket ( this . serviceTicket ) ; } try { return new Form ( this . postJson ( formToGetAncestorForParam , WS . Path . SQLUtil . Version1 . getAncestor ( includeFieldDataParam , includeTableFieldsParam ) ) ) ; } //JSON Issue... catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Fields for the { @code formToGetFieldsForParam } . [CODESPLIT] public List < Field > getFormFields ( Form formToGetFieldsForParam , boolean includeTableFieldsParam ) { if ( formToGetFieldsForParam != null && this . serviceTicket != null ) { formToGetFieldsForParam . setServiceTicket ( this . serviceTicket ) ; } try { FormFieldListing formFieldListing = new FormFieldListing ( this . postJson ( formToGetFieldsForParam , WS . Path . SQLUtil . Version1 . getFormFields ( includeTableFieldsParam ) ) ) ; return formFieldListing . getListing ( ) ; } // catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method for creating camel - case - upper from { @code inputParam } [CODESPLIT] public String toCamelUpperCase ( String inputParam ) { if ( inputParam == null ) { return null ; } if ( inputParam . isEmpty ( ) ) { return EMPTY ; } char [ ] original = inputParam . toCharArray ( ) ; StringBuilder titleCase = new StringBuilder ( Character . toString ( Character . toLowerCase ( original [ 0 ] ) ) ) ; boolean nextTitleCase = false ; for ( int index = 1 ; index < original . length ; index ++ ) { char c = original [ index ] ; if ( Character . isSpaceChar ( c ) ) { nextTitleCase = true ; continue ; } //Just add... else if ( nextTitleCase ) { c = Character . toTitleCase ( c ) ; nextTitleCase = false ; } titleCase . append ( c ) ; } return titleCase . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract and returns Latitude from { @code textToCheckParam } applicable to Fluid . [CODESPLIT] public String getLatitudeFromFluidText ( String textToCheckParam ) { if ( textToCheckParam == null || textToCheckParam . isEmpty ( ) ) { return EMPTY ; } String [ ] latitudeAndLongitude = textToCheckParam . split ( REG_EX_PIPE ) ; if ( latitudeAndLongitude == null || latitudeAndLongitude . length < 2 ) { latitudeAndLongitude = textToCheckParam . split ( REG_EX_COMMA ) ; } if ( latitudeAndLongitude == null || latitudeAndLongitude . length == 0 ) { return ZERO ; } if ( latitudeAndLongitude . length > 1 ) { return toGoeSafe ( latitudeAndLongitude [ 0 ] ) ; } return ZERO ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract and returns Latitude from { @code textToCheckParam } applicable to ElasticSearch . [CODESPLIT] public double getLatitudeFromElasticSearchText ( String textToCheckParam ) { if ( textToCheckParam == null || textToCheckParam . isEmpty ( ) ) { return 0.0 ; } String [ ] latitudeAndLongitude = textToCheckParam . split ( REG_EX_COMMA ) ; if ( latitudeAndLongitude == null || latitudeAndLongitude . length < 2 ) { latitudeAndLongitude = textToCheckParam . split ( REG_EX_PIPE ) ; } if ( latitudeAndLongitude == null || latitudeAndLongitude . length == 0 ) { return 0.0 ; } if ( latitudeAndLongitude . length > 1 ) { return toDoubleSafe ( latitudeAndLongitude [ 0 ] ) ; } return 0.0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract and returns Longitude from { @code textToCheckParam } applicable to ElasticSearch . [CODESPLIT] public double getLongitudeFromElasticSearchText ( String textToCheckParam ) { if ( textToCheckParam == null || textToCheckParam . trim ( ) . isEmpty ( ) ) { return 0.0 ; } String [ ] latitudeAndLongitude = textToCheckParam . split ( REG_EX_COMMA ) ; if ( latitudeAndLongitude == null || latitudeAndLongitude . length < 2 ) { latitudeAndLongitude = textToCheckParam . split ( REG_EX_PIPE ) ; } if ( latitudeAndLongitude == null || latitudeAndLongitude . length == 0 ) { return 0.0 ; } if ( latitudeAndLongitude . length > 1 ) { return this . toDoubleSafe ( latitudeAndLongitude [ 1 ] ) ; } return 0.0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the { @code toParseParam } to a double . [CODESPLIT] public final double toDoubleSafe ( String toParseParam ) { if ( toParseParam == null || toParseParam . trim ( ) . isEmpty ( ) ) { return 0D ; } try { return Double . parseDouble ( toParseParam ) ; } catch ( NumberFormatException e ) { return 0D ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the { @code toParseParam } to a double . [CODESPLIT] public final String toGoeSafe ( String toParseParam ) { if ( toParseParam == null || toParseParam . trim ( ) . isEmpty ( ) ) { return ZERO ; } try { for ( char charToCheck : toParseParam . toCharArray ( ) ) { if ( ! Character . isDigit ( charToCheck ) && ' ' != charToCheck ) { return ZERO ; } } if ( toParseParam . length ( ) > 12 ) { return toParseParam . substring ( 0 , 12 ) ; } return toParseParam ; } catch ( NumberFormatException e ) { return ZERO ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes the { @code base64StringParam } as { @code byte [] } . [CODESPLIT] public static byte [ ] decodeBase64 ( String base64StringParam ) { if ( base64StringParam == null ) { return null ; } if ( base64StringParam . isEmpty ( ) ) { return new byte [ ] { } ; } return Base64 . getDecoder ( ) . decode ( base64StringParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the { @code bytesParam } as { @code java . lang . String } . [CODESPLIT] public static String encodeBase16 ( byte [ ] bytesParam ) { if ( bytesParam == null ) { return null ; } if ( bytesParam . length == 0 ) { return UtilGlobal . EMPTY ; } return DatatypeConverter . printHexBinary ( bytesParam ) . toUpperCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the { @code stringParam } as { @code byte [] } . [CODESPLIT] public static byte [ ] decodeBase16 ( String stringParam ) { if ( stringParam == null ) { return null ; } if ( stringParam . trim ( ) . isEmpty ( ) ) { return new byte [ ] { } ; } int len = stringParam . length ( ) ; byte [ ] data = new byte [ len / 2 ] ; for ( int i = 0 ; i < len ; i += 2 ) { data [ i / 2 ] = ( byte ) ( ( Character . digit ( stringParam . charAt ( i ) , 16 ) << 4 ) + Character . digit ( stringParam . charAt ( i + 1 ) , 16 ) ) ; } return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the { @code bytesParam } as { @code java . lang . String } . [CODESPLIT] public static String encodeBase64 ( byte [ ] bytesParam ) { if ( bytesParam == null ) { return null ; } if ( bytesParam . length == 0 ) { return UtilGlobal . EMPTY ; } return Base64 . getEncoder ( ) . encodeToString ( bytesParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the flat value on the { @code objectToSetFieldOnParam } JSON object . [CODESPLIT] public void setFlatFieldOnJSONObj ( String fieldNamePrefixParam , String fieldNameIdPrefixParam , Field fieldToExtractFromParam , JSONObject objectToSetFieldOnParam ) { if ( fieldToExtractFromParam == null ) { return ; } String fieldName = fieldToExtractFromParam . getFieldNameAsUpperCamel ( ) ; if ( fieldName == null || fieldName . trim ( ) . isEmpty ( ) ) { return ; } String completeFieldName = fieldNamePrefixParam . concat ( fieldName ) ; String completeFieldNameId = fieldNameIdPrefixParam . concat ( fieldName ) ; objectToSetFieldOnParam . put ( completeFieldNameId , fieldToExtractFromParam . getId ( ) ) ; Object fieldValue = fieldToExtractFromParam . getFieldValue ( ) ; if ( fieldValue == null ) { objectToSetFieldOnParam . put ( completeFieldName , JSONObject . NULL ) ; } //Table field... else if ( fieldValue instanceof TableField ) { return ; } //Multiple Choice... else if ( fieldValue instanceof MultiChoice ) { MultiChoice multiChoice = ( MultiChoice ) fieldValue ; //Nothing provided... if ( multiChoice . getSelectedMultiChoices ( ) == null || multiChoice . getSelectedMultiChoices ( ) . isEmpty ( ) ) { objectToSetFieldOnParam . put ( completeFieldName , JSONObject . NULL ) ; return ; } StringBuilder builder = new StringBuilder ( ) ; multiChoice . getSelectedMultiChoices ( ) . forEach ( selectedChoice -> { builder . append ( selectedChoice ) ; builder . append ( \", \" ) ; } ) ; String selectVal = builder . toString ( ) ; if ( selectVal != null && ! selectVal . trim ( ) . isEmpty ( ) ) { selectVal = selectVal . substring ( 0 , selectVal . length ( ) - 2 ) ; } objectToSetFieldOnParam . put ( completeFieldName , selectVal ) ; } //Other valid types... else if ( ( fieldValue instanceof Number || fieldValue instanceof Boolean ) || fieldValue instanceof String ) { if ( ( fieldValue instanceof String ) && Field . LATITUDE_AND_LONGITUDE . equals ( fieldToExtractFromParam . getTypeMetaData ( ) ) ) { String formFieldValueStr = fieldValue . toString ( ) ; String latitudeTxt = this . getLatitudeFromFluidText ( formFieldValueStr ) ; String longitudeTxt = this . getLongitudeFromFluidText ( formFieldValueStr ) ; fieldValue = ( latitudeTxt . concat ( UtilGlobal . COMMA ) . concat ( longitudeTxt ) ) ; } objectToSetFieldOnParam . put ( completeFieldName , fieldValue ) ; } //Date... else if ( fieldValue instanceof Date ) { objectToSetFieldOnParam . put ( completeFieldName , ( ( Date ) fieldValue ) . getTime ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether { @code this } message handler can process the message { @code messageParam } [CODESPLIT] public Object doesHandlerQualifyForProcessing ( String messageParam ) { JSONObject jsonObject = null ; try { jsonObject = new JSONObject ( messageParam ) ; } catch ( JSONException jsonExcept ) { throw new FluidClientException ( \"Unable to parse [\" + messageParam + \"]. \" + jsonExcept . getMessage ( ) , jsonExcept , FluidClientException . ErrorCode . JSON_PARSING ) ; } Error fluidError = new Error ( jsonObject ) ; if ( fluidError . getErrorCode ( ) > 0 ) { return fluidError ; } String echo = fluidError . getEcho ( ) ; //We can process the me if ( this . expectedEchoMessagesBeforeComplete . contains ( echo ) ) { return jsonObject ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the message . If there was an error the object will be Error If there was no error the object will be JSONObject [CODESPLIT] @ Override public void handleMessage ( Object objectToProcess ) { //There is an error... if ( objectToProcess instanceof Error ) { Error fluidError = ( ( Error ) objectToProcess ) ; this . errors . add ( fluidError ) ; //Do a message callback... if ( this . messageReceivedCallback != null ) { this . messageReceivedCallback . errorMessageReceived ( fluidError ) ; } //If complete future is provided... if ( this . completableFuture != null ) { this . completableFuture . completeExceptionally ( new FluidClientException ( fluidError . getErrorMessage ( ) , fluidError . getErrorCode ( ) ) ) ; } } //No Error... else { JSONObject jsonObject = ( JSONObject ) objectToProcess ; //Uncompress the compressed response... if ( this . compressedResponse ) { CompressedResponse compressedResponse = new CompressedResponse ( jsonObject ) ; byte [ ] compressedJsonList = UtilGlobal . decodeBase64 ( compressedResponse . getDataBase64 ( ) ) ; byte [ ] uncompressedJson = null ; try { uncompressedJson = this . uncompress ( compressedJsonList ) ; } catch ( IOException eParam ) { throw new FluidClientException ( \"I/O issue with uncompress. \" + eParam . getMessage ( ) , eParam , FluidClientException . ErrorCode . IO_ERROR ) ; } jsonObject = new JSONObject ( new String ( uncompressedJson ) ) ; } T messageForm = this . getNewInstanceBy ( jsonObject ) ; //Add to the list of return values... this . returnValue . add ( messageForm ) ; //Completable future is set, and all response messages received... if ( this . completableFuture != null ) { String echo = messageForm . getEcho ( ) ; if ( echo != null && ! echo . trim ( ) . isEmpty ( ) ) { this . expectedEchoMessagesBeforeComplete . remove ( echo ) ; } //All expected messages received... if ( this . expectedEchoMessagesBeforeComplete . isEmpty ( ) ) { this . completableFuture . complete ( this . returnValue ) ; } } //Do a message callback... if ( this . messageReceivedCallback != null ) { this . messageReceivedCallback . messageReceived ( messageForm ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event for when connection is closed . [CODESPLIT] @ Override public void connectionClosed ( ) { this . isConnectionClosed = true ; if ( this . completableFuture != null ) { //If there was no error... if ( this . getErrors ( ) . isEmpty ( ) ) { this . completableFuture . complete ( this . returnValue ) ; } //there was an error... else { Error firstFluidError = this . getErrors ( ) . get ( 0 ) ; this . completableFuture . completeExceptionally ( new FluidClientException ( firstFluidError . getErrorMessage ( ) , firstFluidError . getErrorCode ( ) ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the { @code expectedMessageEchoParam } echo to expect as a return value before the Web Socket operation may be regarded as complete . [CODESPLIT] public void addExpectedMessage ( String expectedMessageEchoParam ) { if ( expectedMessageEchoParam == null || expectedMessageEchoParam . trim ( ) . isEmpty ( ) ) { return ; } this . expectedEchoMessagesBeforeComplete . add ( expectedMessageEchoParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a list of echo messages of the current return values . [CODESPLIT] private List < String > getEchoMessagesFromReturnValue ( ) { List < String > returnListing = new ArrayList ( ) ; if ( this . returnValue == null ) { return returnListing ; } Iterator < T > iterForReturnVal = this . returnValue . iterator ( ) ; //Only add where the ECHO message is set... while ( iterForReturnVal . hasNext ( ) ) { T returnVal = iterForReturnVal . next ( ) ; if ( returnVal . getEcho ( ) == null ) { continue ; } returnListing . add ( returnVal . getEcho ( ) ) ; } return returnListing ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the local return value echo messages if all of them contain { @code echoMessageParam } . [CODESPLIT] public boolean doReturnValueEchoMessageContainAll ( List < String > echoMessageParam ) { if ( echoMessageParam == null || echoMessageParam . isEmpty ( ) ) { return false ; } List < String > allReturnValueEchoMessages = this . getEchoMessagesFromReturnValue ( ) ; for ( String toCheckFor : echoMessageParam ) { if ( ! allReturnValueEchoMessages . contains ( toCheckFor ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uncompress the raw { @code compressedBytesParam } . [CODESPLIT] protected byte [ ] uncompress ( byte [ ] compressedBytesParam ) throws IOException { byte [ ] buffer = new byte [ 1024 ] ; byte [ ] returnVal = null ; ZipInputStream zis = null ; if ( CHARSET == null ) { zis = new ZipInputStream ( new ByteArrayInputStream ( compressedBytesParam ) ) ; } else { zis = new ZipInputStream ( new ByteArrayInputStream ( compressedBytesParam ) , CHARSET ) ; } //get the zip file content ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; //get the zipped file list entry ZipEntry ze = zis . getNextEntry ( ) ; if ( ze == null ) { return returnVal ; } int len ; while ( ( len = zis . read ( buffer ) ) > 0 ) { bos . write ( buffer , 0 , len ) ; } zis . closeEntry ( ) ; zis . close ( ) ; bos . flush ( ) ; bos . close ( ) ; returnVal = bos . toByteArray ( ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Personal Inventory items for the logged in user . [CODESPLIT] public List < FluidItem > getPersonalInventoryItems ( ) { User loggedInUser = new User ( ) ; if ( this . serviceTicket != null ) { loggedInUser . setServiceTicket ( this . serviceTicket ) ; } try { return new FluidItemListing ( this . postJson ( loggedInUser , WS . Path . PersonalInventory . Version1 . getAllByLoggedInUser ( ) ) ) . getListing ( ) ; } //rethrow as a Fluid Client exception. catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the item { @code formToRemoveParam } from the personal inventory . [CODESPLIT] public Form removeFromPersonalInventory ( Form formToRemoveParam ) { if ( formToRemoveParam != null && this . serviceTicket != null ) { formToRemoveParam . setServiceTicket ( this . serviceTicket ) ; } try { return new Form ( this . postJson ( formToRemoveParam , WS . Path . PersonalInventory . Version1 . removeFromPersonalInventory ( ) ) ) ; } //rethrow as a Fluid Client exception. catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Encrypted Data Base 64... if ( this . getEncryptedDataBase64 ( ) != null ) { returnVal . put ( JSONMapping . ENCRYPTED_DATA_BASE_64 , this . getEncryptedDataBase64 ( ) ) ; } //Encrypted Data HMAC Base 64... if ( this . getEncryptedDataHmacBase64 ( ) != null ) { returnVal . put ( JSONMapping . ENCRYPTED_DATA_HMAC_BASE_64 , this . getEncryptedDataHmacBase64 ( ) ) ; } //IV Base 64... if ( this . getIvBase64 ( ) != null ) { returnVal . put ( JSONMapping . IV_BASE_64 , this . getIvBase64 ( ) ) ; } //Seed Base 64... if ( this . getSeedBase64 ( ) != null ) { returnVal . put ( JSONMapping . SEED_BASE_64 , this . getSeedBase64 ( ) ) ; } //Service Ticket Base 64... if ( this . getServiceTicket ( ) != null ) { returnVal . put ( ABaseFluidJSONObject . JSONMapping . SERVICE_TICKET , this . getServiceTicket ( ) ) ; } //Salt... if ( this . getSalt ( ) != null ) { returnVal . put ( JSONMapping . SALT , this . getSalt ( ) ) ; } //Principal Client... if ( this . getPrincipalClient ( ) != null ) { returnVal . put ( JSONMapping . PRINCIPAL_CLIENT , this . getPrincipalClient ( ) ) ; } //Role String... if ( this . getRoleString ( ) != null ) { returnVal . put ( JSONMapping . ROLE_STRING , this . getRoleString ( ) ) ; } //Timestamp... if ( this . getTimestamp ( ) != null ) { returnVal . put ( JSONMapping . TIMESTAMP , this . getTimestamp ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Form Container / Electronic Forms . [CODESPLIT] public Form createFormContainer ( Form formParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . putJson ( formParam , WS . Path . FormContainer . Version1 . formContainerCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Table Record . [CODESPLIT] public TableRecord createTableRecord ( TableRecord tableRecordParam ) { if ( tableRecordParam != null && this . serviceTicket != null ) { tableRecordParam . setServiceTicket ( this . serviceTicket ) ; } return new TableRecord ( this . putJson ( tableRecordParam , WS . Path . FormContainerTableRecord . Version1 . formContainerTableRecordCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update a Form Container / Electronic Form . The table record forms may also be updated with [CODESPLIT] public Form updateFormContainer ( Form formParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . postJson ( formParam , WS . Path . FormContainer . Version1 . formContainerUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the Custom Program with action alias { @code customWebActionParam } . This method may be used for Form and Table Records . [CODESPLIT] public Form executeCustomWebAction ( String customWebActionParam , Form formParam ) { return this . executeCustomWebAction ( customWebActionParam , false , null , formParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute the Custom Program with action alias { @code customWebActionParam } . This method may be used for Form and Table Records . [CODESPLIT] public Form executeCustomWebAction ( String customWebActionParam , boolean isTableRecordParam , Long formContainerTableRecordBelowsToParam , Form formParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } if ( customWebActionParam == null || customWebActionParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Custom Web Action is mandatory.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } try { return new Form ( this . postJson ( formParam , WS . Path . FormContainer . Version1 . executeCustomWebAction ( customWebActionParam , isTableRecordParam , formContainerTableRecordBelowsToParam ) ) ) ; } catch ( UnsupportedEncodingException unsEncExcept ) { throw new FluidClientException ( unsEncExcept . getMessage ( ) , unsEncExcept , FluidClientException . ErrorCode . IO_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the Form Container provided . Id must be set on the Form Container . [CODESPLIT] public Form deleteFormContainer ( Form formContainerParam ) { if ( formContainerParam != null && this . serviceTicket != null ) { formContainerParam . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . postJson ( formContainerParam , WS . Path . FormContainer . Version1 . formContainerDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves Electronic Form Workflow historic information . [CODESPLIT] public List < FormFlowHistoricData > getFormFlowHistoricData ( Form formParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } return new FormFlowHistoricDataListing ( this . postJson ( formParam , WS . Path . FlowItemHistory . Version1 . getByFormContainer ( ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves Electronic Form and Field historic information . [CODESPLIT] public List < FormHistoricData > getFormAndFieldHistoricData ( Form formParam , boolean includeCurrentParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } return new FormHistoricDataListing ( this . postJson ( formParam , WS . Path . FormHistory . Version1 . getByFormContainer ( includeCurrentParam ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves Electronic Form and Field historic information for the most recent modification . [CODESPLIT] public FormHistoricData getMostRecentFormAndFieldHistoricData ( Form formParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } return new FormHistoricData ( this . postJson ( formParam , WS . Path . FormHistory . Version1 . getByMostRecentByFormContainer ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Container by Primary key . [CODESPLIT] public Form getFormContainerById ( Long formContainerIdParam ) { Form form = new Form ( formContainerIdParam ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . postJson ( form , WS . Path . FormContainer . Version1 . getById ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lock the provided form container for logged in user . [CODESPLIT] public Form lockFormContainer ( Form formParam , JobView jobViewParam ) { return this . lockFormContainer ( formParam , jobViewParam , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lock the provided form container for logged in user . If { @code userToLockAsParam } is provided and valid that user will be used instead . [CODESPLIT] public Form lockFormContainer ( Form formParam , JobView jobViewParam , User userToLockAsParam ) { if ( this . serviceTicket != null && formParam != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } Long jobViewId = ( jobViewParam == null ) ? null : jobViewParam . getId ( ) ; Long lockAsUserId = ( userToLockAsParam == null ) ? null : userToLockAsParam . getId ( ) ; try { return new Form ( this . postJson ( formParam , WS . Path . FormContainer . Version1 . lockFormContainer ( jobViewId , lockAsUserId ) ) ) ; } //rethrow as a Fluid Client exception. catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unlock the provided form container from the logged in user . Item will not be removed from users Personal Inventory . [CODESPLIT] public Form unLockFormContainer ( Form formParam , boolean unlockAsyncParam ) { return this . unLockFormContainer ( formParam , null , unlockAsyncParam , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unlock the provided form container from the logged in user . The unlock will be performed asynchronous . Item will not be removed from users Personal Inventory . [CODESPLIT] public Form unLockFormContainer ( Form formParam , User userToUnLockAsParam ) { return this . unLockFormContainer ( formParam , userToUnLockAsParam , true , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unlock the provided form container from the logged in user . The unlock will be performed asynchronous . Item will not be removed from users Personal Inventory . [CODESPLIT] public Form unLockFormContainer ( Form formParam , User userToUnLockAsParam , boolean unlockAsyncParam ) { return this . unLockFormContainer ( formParam , userToUnLockAsParam , unlockAsyncParam , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unlock the provided form container from the logged in user . [CODESPLIT] public Form unLockFormContainer ( Form formParam , User userToUnLockAsParam , boolean unlockAsyncParam , boolean removeFromPersonalInventoryParam ) { if ( this . serviceTicket != null && formParam != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } Long unLockAsUserId = ( userToUnLockAsParam == null ) ? null : userToUnLockAsParam . getId ( ) ; try { return new Form ( this . postJson ( formParam , WS . Path . FormContainer . Version1 . unLockFormContainer ( unLockAsUserId , unlockAsyncParam , removeFromPersonalInventoryParam ) ) ) ; } //rethrow as a Fluid Client exception. catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Table field records as { @code List<Form > } . [CODESPLIT] public List < Form > getFormTableForms ( Long electronicFormIdParam , boolean includeFieldDataParam ) { List < Form > returnVal = new ArrayList ( ) ; if ( electronicFormIdParam == null ) { return returnVal ; } Map < Long , String > definitionAndTitle = this . formDefUtil . getFormDefinitionIdAndTitle ( ) ; PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; try { ISyntax syntax = SyntaxFactory . getInstance ( ) . getSyntaxFor ( this . getSQLTypeFromConnection ( ) , ISyntax . ProcedureMapping . Form . GetFormContainersTableFieldFormContainers ) ; preparedStatement = this . getConnection ( ) . prepareStatement ( syntax . getPreparedStatement ( ) ) ; preparedStatement . setLong ( 1 , electronicFormIdParam ) ; resultSet = preparedStatement . executeQuery ( ) ; //Iterate each of the form containers... while ( resultSet . next ( ) ) { returnVal . add ( this . mapFormContainerTo ( definitionAndTitle , resultSet ) ) ; } //When field data must also be included... if ( includeFieldDataParam ) { for ( Form form : returnVal ) { List < Field > formFields = this . fieldUtil . getFormFields ( form . getId ( ) , false , false ) ; form . setFormFields ( formFields ) ; } } } catch ( SQLException sqlError ) { throw new FluidSQLException ( sqlError ) ; } finally { this . closeStatement ( preparedStatement , resultSet ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the descendants for the { @code electronicFormIdsParam } Forms . [CODESPLIT] @ Override public List < Form > getFormDescendants ( List < Long > electronicFormIdsParam , boolean includeFieldDataParam , boolean includeTableFieldsParam , boolean includeTableFieldFormRecordInfoParam ) { if ( electronicFormIdsParam == null || electronicFormIdsParam . isEmpty ( ) ) { return null ; } List < Form > returnVal = new ArrayList ( ) ; for ( Long electronicFormId : electronicFormIdsParam ) { List < Form > forTheCycle = this . getFormDescendants ( electronicFormId , includeFieldDataParam , includeTableFieldsParam , includeTableFieldFormRecordInfoParam ) ; if ( forTheCycle == null ) { continue ; } returnVal . addAll ( forTheCycle ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the ancestor for the { @code electronicFormIdParam } Form . [CODESPLIT] public Form getFormAncestor ( Long electronicFormIdParam , boolean includeFieldDataParam , boolean includeTableFieldsParam ) { if ( electronicFormIdParam == null ) { return null ; } Form returnVal = null ; Map < Long , String > definitionAndTitle = this . formDefUtil . getFormDefinitionIdAndTitle ( ) ; PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; try { ISyntax syntax = SyntaxFactory . getInstance ( ) . getSyntaxFor ( this . getSQLTypeFromConnection ( ) , ISyntax . ProcedureMapping . Form . GetFormContainersParentFormContainer ) ; preparedStatement = this . getConnection ( ) . prepareStatement ( syntax . getPreparedStatement ( ) ) ; preparedStatement . setLong ( 1 , electronicFormIdParam ) ; resultSet = preparedStatement . executeQuery ( ) ; //Iterate each of the form containers... if ( resultSet . next ( ) ) { returnVal = this . mapFormContainerTo ( definitionAndTitle , resultSet ) ; } //When field data must also be included... if ( includeFieldDataParam && returnVal != null ) { returnVal . setFormFields ( this . fieldUtil . getFormFields ( returnVal . getId ( ) , includeTableFieldsParam , false ) ) ; } return returnVal ; } catch ( SQLException sqlError ) { throw new FluidSQLException ( sqlError ) ; } finally { this . closeStatement ( preparedStatement , resultSet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the Form to the provided Definition - Id and Title . [CODESPLIT] private Form mapFormContainerTo ( Map < Long , String > definitionAndTitleParam , ResultSet resultSetParam ) throws SQLException { Long formId = resultSetParam . getLong ( SQLColumnIndex . _01_FORM_ID ) ; String formType = definitionAndTitleParam . get ( resultSetParam . getLong ( SQLColumnIndex . _02_FORM_TYPE ) ) ; String title = resultSetParam . getString ( SQLColumnIndex . _03_TITLE ) ; Date created = resultSetParam . getDate ( SQLColumnIndex . _04_CREATED ) ; Date lastUpdated = resultSetParam . getDate ( SQLColumnIndex . _05_LAST_UPDATED ) ; Long currentUserId = resultSetParam . getLong ( SQLColumnIndex . _06_CURRENT_USER_ID ) ; if ( formType == null ) { throw new SQLException ( \"No mapping found for Form Type '\" + resultSetParam . getLong ( SQLColumnIndex . _02_FORM_TYPE ) + \"'.\" ) ; } Form toAdd = new Form ( formType ) ; toAdd . setId ( formId ) ; toAdd . setTitle ( title ) ; //Created... if ( created != null ) { toAdd . setDateCreated ( new Date ( created . getTime ( ) ) ) ; } //Last Updated... if ( lastUpdated != null ) { toAdd . setDateLastUpdated ( new Date ( lastUpdated . getTime ( ) ) ) ; } //Current User... if ( currentUserId != null && currentUserId . longValue ( ) > 0 ) { User currentUser = new User ( ) ; currentUser . setId ( currentUserId ) ; toAdd . setCurrentUser ( currentUser ) ; } return toAdd ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the Form states with the { @code resultSetParam } . [CODESPLIT] private void mapFormContainerStatesTo ( Form previousMappedForm , ResultSet resultSetParam ) throws SQLException { if ( previousMappedForm == null ) { return ; } //Form Container State... Long formContainerState = resultSetParam . getLong ( SQLColumnIndex . _07_FORM_CONTAINER_STATE ) ; long formContStateId = ( formContainerState == null ) ? 0 : formContainerState . longValue ( ) ; if ( formContStateId > 0 ) { if ( formContStateId == 1 ) { previousMappedForm . setState ( Form . State . OPEN ) ; } else if ( formContStateId == 2 ) { previousMappedForm . setState ( Form . State . LOCKED ) ; } } Long formContainerFlowState = resultSetParam . getLong ( SQLColumnIndex . _08_FORM_CONTAINER_FLOW_STATE ) ; long formContFlowStateId = ( formContainerFlowState == null ) ? 0 : formContainerFlowState . longValue ( ) ; if ( formContFlowStateId > 0 ) { if ( formContFlowStateId == 1 ) { previousMappedForm . setFlowState ( FluidItem . FlowState . NotInFlow . name ( ) ) ; } else if ( formContFlowStateId == 2 ) { previousMappedForm . setFlowState ( FluidItem . FlowState . WorkInProgress . name ( ) ) ; } else if ( formContFlowStateId == 3 ) { previousMappedForm . setFlowState ( FluidItem . FlowState . UserSend . name ( ) ) ; } else if ( formContFlowStateId == 4 ) { previousMappedForm . setFlowState ( FluidItem . FlowState . UserSendWorkInProgress . name ( ) ) ; } else if ( formContFlowStateId == 5 ) { previousMappedForm . setFlowState ( FluidItem . FlowState . Archive . name ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the comma separated list of roles as objects . [CODESPLIT] @ XmlTransient public static List < Role > convertToObjects ( String roleListingParam ) { if ( roleListingParam == null || roleListingParam . trim ( ) . isEmpty ( ) ) { return null ; } String [ ] listOfRoles = roleListingParam . split ( UtilGlobal . REG_EX_COMMA ) ; List < Role > returnVal = new ArrayList <> ( ) ; for ( String roleName : listOfRoles ) { Role roleToAdd = new Role ( ) ; roleToAdd . setName ( roleName . trim ( ) ) ; returnVal . add ( roleToAdd ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Name... if ( this . getName ( ) != null ) { returnVal . put ( JSONMapping . NAME , this . getName ( ) ) ; } //Description... if ( this . getDescription ( ) != null ) { returnVal . put ( JSONMapping . DESCRIPTION , this . getDescription ( ) ) ; } //Admin Permissions... if ( this . getAdminPermissions ( ) != null && ! this . getAdminPermissions ( ) . isEmpty ( ) ) { JSONArray adminPerArr = new JSONArray ( ) ; for ( String toAdd : this . getAdminPermissions ( ) ) { adminPerArr . put ( toAdd ) ; } returnVal . put ( JSONMapping . ADMIN_PERMISSIONS , adminPerArr ) ; } //Role to Form Definitions... if ( this . getRoleToFormDefinitions ( ) != null && ! this . getRoleToFormDefinitions ( ) . isEmpty ( ) ) { JSONArray roleToFormDefArr = new JSONArray ( ) ; for ( RoleToFormDefinition toAdd : this . getRoleToFormDefinitions ( ) ) { roleToFormDefArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ROLE_TO_FORM_DEFINITIONS , roleToFormDefArr ) ; } //Role To Form Field To Form Definition... if ( this . getRoleToFormFieldToFormDefinitions ( ) != null && ! this . getRoleToFormFieldToFormDefinitions ( ) . isEmpty ( ) ) { JSONArray roleToJobViewArr = new JSONArray ( ) ; for ( RoleToFormFieldToFormDefinition toAdd : this . getRoleToFormFieldToFormDefinitions ( ) ) { roleToJobViewArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ROLE_TO_FORM_FIELD_TO_FORM_DEFINITIONS , roleToJobViewArr ) ; } //Role to Job Views... if ( this . getRoleToJobViews ( ) != null && ! this . getRoleToJobViews ( ) . isEmpty ( ) ) { JSONArray roleToJobViewArr = new JSONArray ( ) ; for ( RoleToJobView toAdd : this . getRoleToJobViews ( ) ) { roleToJobViewArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ROLE_TO_JOB_VIEWS , roleToJobViewArr ) ; } //Role to User Queries... if ( this . getRoleToUserQueries ( ) != null && ! this . getRoleToUserQueries ( ) . isEmpty ( ) ) { JSONArray userQueriesArr = new JSONArray ( ) ; for ( RoleToUserQuery toAdd : this . getRoleToUserQueries ( ) ) { userQueriesArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ROLE_TO_USER_QUERIES , userQueriesArr ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Form Definition with the Fields inside the definition . [CODESPLIT] public Form createFormDefinition ( Form formDefinitionParam ) { if ( formDefinitionParam != null && this . serviceTicket != null ) { formDefinitionParam . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . putJson ( formDefinitionParam , WS . Path . FormDefinition . Version1 . formDefinitionCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing Form Definition with the Fields inside the definition . [CODESPLIT] public Form updateFormDefinition ( Form formDefinitionParam ) { if ( formDefinitionParam != null && this . serviceTicket != null ) { formDefinitionParam . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . postJson ( formDefinitionParam , WS . Path . FormDefinition . Version1 . formDefinitionUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Definition by Primary key . [CODESPLIT] public Form getFormDefinitionById ( Long formDefinitionIdParam ) { Form form = new Form ( formDefinitionIdParam ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . postJson ( form , WS . Path . FormDefinition . Version1 . getById ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Definition by Name . [CODESPLIT] public Form getFormDefinitionByName ( String formDefinitionNameParam ) { Form form = new Form ( formDefinitionNameParam ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . postJson ( form , WS . Path . FormDefinition . Version1 . getByName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Form Definitions by logged in user . [CODESPLIT] public List < Form > getAllByLoggedInUser ( boolean includeTableRecordTypesParam ) { Form form = new Form ( ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } if ( includeTableRecordTypesParam ) { return new FormListing ( this . postJson ( form , WS . Path . FormDefinition . Version1 . getAllByLoggedInUserIncludeTableTypes ( ) ) ) . getListing ( ) ; } else { return new FormListing ( this . postJson ( form , WS . Path . FormDefinition . Version1 . getAllByLoggedInUser ( ) ) ) . getListing ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Form Definitions where the logged in user can create a new instance of the { @code Form } . [CODESPLIT] public List < Form > getAllByLoggedInUserWhereCanCreateInstanceOf ( ) { Form form = new Form ( ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } return new FormListing ( this . postJson ( form , WS . Path . FormDefinition . Version1 . getAllByLoggedInAndCanCreateInstanceOf ( ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the Form Definition provided . Id must be set on the Form Definition . [CODESPLIT] public Form deleteFormDefinition ( Form formDefinitionParam ) { if ( formDefinitionParam != null && this . serviceTicket != null ) { formDefinitionParam . setServiceTicket ( this . serviceTicket ) ; } return new Form ( this . postJson ( formDefinitionParam , WS . Path . FormDefinition . Version1 . formDefinitionDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the { @code CachedFieldValue } value stored under the params . [CODESPLIT] public CachedFieldValue getCachedFieldValueFrom ( Long formDefIdParam , Long formContIdParam , Long formFieldIdParam ) { if ( ( formDefIdParam == null || formContIdParam == null ) || formFieldIdParam == null ) { return null ; } String storageKey = this . getStorageKeyFrom ( formDefIdParam , formContIdParam , formFieldIdParam ) ; Object objWithKey ; try { objWithKey = this . memcachedClient . get ( storageKey ) ; } //Changed for Java 1.6 compatibility... catch ( MemcachedException e ) { throw new FluidCacheException ( \"Unable to get Field value for '\" + storageKey + \"'.\" + \"Contact administrator. \" + e . getMessage ( ) , e ) ; } catch ( TimeoutException e ) { throw new FluidCacheException ( \"Unable to get Field value for '\" + storageKey + \"'.\" + \"Contact administrator. \" + e . getMessage ( ) , e ) ; } catch ( InterruptedException e ) { throw new FluidCacheException ( \"Unable to get Field value for '\" + storageKey + \"'.\" + \"Contact administrator. \" + e . getMessage ( ) , e ) ; } return this . getCacheFieldValueFromObject ( objWithKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the { @code objWithKeyParam } Object to { @code CachedFieldValue } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private CachedFieldValue getCacheFieldValueFromObject ( Object objWithKeyParam ) { if ( objWithKeyParam == null ) { return null ; } //Get Word... Method methodGetWord = CacheUtil . getMethod ( objWithKeyParam . getClass ( ) , CustomCode . IWord . METHOD_getWord ) ; //Get Value... Method methodGetValue = CacheUtil . getMethod ( objWithKeyParam . getClass ( ) , CustomCode . ADataType . METHOD_getValue ) ; //Word... Object getWordObj = CacheUtil . invoke ( methodGetWord , objWithKeyParam ) ; String getWordVal = null ; if ( getWordObj instanceof String ) { getWordVal = ( String ) getWordObj ; } //Value... Object getValueObj ; if ( FlowJobType . MULTIPLE_CHOICE . equals ( getWordVal ) ) { MultiChoice multiChoice = new MultiChoice ( ) ; //Available Choices... Method methodAvailableChoices = getMethod ( objWithKeyParam . getClass ( ) , CustomCode . MultipleChoice . METHOD_getAvailableChoices ) ; Object availChoicesObj = CacheUtil . invoke ( methodAvailableChoices , objWithKeyParam ) ; if ( availChoicesObj instanceof List ) { multiChoice . setAvailableMultiChoices ( ( List ) availChoicesObj ) ; } //Selected... Method methodSelectedChoices = getMethod ( objWithKeyParam . getClass ( ) , CustomCode . MultipleChoice . METHOD_getSelectedChoices ) ; Object selectedChoicesObj = invoke ( methodSelectedChoices , objWithKeyParam ) ; if ( selectedChoicesObj instanceof List ) { multiChoice . setSelectedMultiChoices ( ( List ) selectedChoicesObj ) ; } getValueObj = multiChoice ; } else { getValueObj = CacheUtil . invoke ( methodGetValue , objWithKeyParam ) ; } if ( getValueObj == null ) { return null ; } if ( getWordVal == null ) { throw new FluidCacheException ( \"Get Word value is 'null'. Not allowed.\" ) ; } CachedFieldValue returnVal = new CachedFieldValue ( ) ; returnVal . dataType = getWordVal ; returnVal . cachedFieldValue = getValueObj ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the java method from class { @code clazzParam } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static Method getMethod ( Class clazzParam , String nameParam ) { try { if ( clazzParam == null || nameParam == null ) { return null ; } Method returnVal = clazzParam . getDeclaredMethod ( nameParam ) ; returnVal . setAccessible ( true ) ; return returnVal ; } // catch ( NoSuchMethodException e ) { throw new FluidCacheException ( \"Unable to get method '\" + nameParam + \"'. \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the { @code methodParam } method on { @code objParam } . [CODESPLIT] private static Object invoke ( Method methodParam , Object objParam ) { try { return methodParam . invoke ( objParam ) ; } //Changed for Java 1.6 compatibility... catch ( InvocationTargetException e ) { throw new FluidCacheException ( \"Unable to invoke method '\" + methodParam . getName ( ) + \"'. \" + e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new FluidCacheException ( \"Unable to invoke method '\" + methodParam . getName ( ) + \"'. \" + e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new FluidCacheException ( \"Unable to invoke method '\" + methodParam . getName ( ) + \"'. \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the storage key the provided parameters . [CODESPLIT] private String getStorageKeyFrom ( Long formDefIdParam , Long formContIdParam , Long formFieldIdParam ) { StringBuilder stringBuff = new StringBuilder ( ) ; //Form Definition... if ( formDefIdParam == null ) { stringBuff . append ( NULL ) ; } else { stringBuff . append ( formDefIdParam . toString ( ) ) ; } stringBuff . append ( DASH ) ; //Form Container... if ( formContIdParam == null ) { stringBuff . append ( NULL ) ; } else { stringBuff . append ( formContIdParam . toString ( ) ) ; } stringBuff . append ( DASH ) ; //Form Field... if ( formFieldIdParam == null ) { stringBuff . append ( NULL ) ; } else { stringBuff . append ( formFieldIdParam . toString ( ) ) ; } return stringBuff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of MemcachedClient . [CODESPLIT] private MemcachedClient initXMemcachedClient ( ) { if ( this . memcachedClient != null && ! this . memcachedClient . isShutdown ( ) ) { return this . memcachedClient ; } try { this . memcachedClient = new XMemcachedClient ( this . cacheHost , this . cachePort ) ; return this . memcachedClient ; } //Unable to create client with connection. catch ( IOException e ) { throw new FluidCacheException ( \"Unable to create MemCache client. \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the Memcached client connection . [CODESPLIT] public void shutdown ( ) { if ( this . memcachedClient != null && ! this . memcachedClient . isShutdown ( ) ) { try { this . memcachedClient . shutdown ( ) ; } // catch ( IOException eParam ) { throw new FluidCacheException ( \"Unable to create shutdown MemCache client. \" + eParam . getMessage ( ) , eParam ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Order... if ( this . getOrder ( ) != null ) { returnVal . put ( JSONMapping . ORDER , this . getOrder ( ) ) ; } //Rule... if ( this . getRule ( ) != null ) { returnVal . put ( JSONMapping . RULE , this . getRule ( ) ) ; } //Current Typed Syntax... if ( this . getCurrentTypedSyntax ( ) != null ) { returnVal . put ( JSONMapping . CURRENT_TYPED_SYNTAX , this . getCurrentTypedSyntax ( ) ) ; } //Flow... if ( this . getFlow ( ) != null ) { returnVal . put ( JSONMapping . FLOW , this . getFlow ( ) . toJsonObject ( ) ) ; } //Flow Step... if ( this . getFlowStep ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STEP , this . getFlowStep ( ) . toJsonObject ( ) ) ; } //Next Valid Syntax Words... if ( this . getNextValidSyntaxWords ( ) != null && ! this . getNextValidSyntaxWords ( ) . isEmpty ( ) ) { JSONArray jsonArrayOfValidWords = new JSONArray ( ) ; for ( String validWord : this . getNextValidSyntaxWords ( ) ) { jsonArrayOfValidWords . put ( validWord ) ; } returnVal . put ( JSONMapping . NEXT_VALID_SYNTAX_WORDS , jsonArrayOfValidWords ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the Descendants ( Forms ) for the { @code formToGetTableFormsForParam } . [CODESPLIT] public List < FormListing > getDescendantsSynchronized ( Form ... formToGetDescendantsForParam ) { if ( formToGetDescendantsForParam == null || formToGetDescendantsForParam . length == 0 ) { return null ; } //Start a new request... String uniqueReqId = this . initNewRequest ( ) ; //Mass data fetch... int numberOfSentForms = 0 ; if ( this . massFetch ) { FormListing listingToSend = new FormListing ( ) ; List < Form > listOfValidForms = new ArrayList ( ) ; for ( Form formToSend : formToGetDescendantsForParam ) { if ( formToSend == null ) { throw new FluidClientException ( \"Cannot provide 'null' for Form.\" , FluidClientException . ErrorCode . ILLEGAL_STATE_ERROR ) ; } listOfValidForms . add ( new Form ( formToSend . getId ( ) ) ) ; } listingToSend . setEcho ( UUID . randomUUID ( ) . toString ( ) ) ; listingToSend . setListing ( listOfValidForms ) ; //Send the actual message... this . sendMessage ( listingToSend , uniqueReqId ) ; numberOfSentForms ++ ; } else { //Single... //Send all the messages... for ( Form formToSend : formToGetDescendantsForParam ) { this . setEchoIfNotSet ( formToSend ) ; //Send the actual message... this . sendMessage ( formToSend , uniqueReqId ) ; numberOfSentForms ++ ; } } try { List < FormListing > returnValue = this . getHandler ( uniqueReqId ) . getCF ( ) . get ( this . getTimeoutInMillis ( ) , TimeUnit . MILLISECONDS ) ; //Connection was closed.. this is a problem.... if ( this . getHandler ( uniqueReqId ) . isConnectionClosed ( ) ) { throw new FluidClientException ( \"SQLUtil-WebSocket-GetDescendants: \" + \"The connection was closed by the server prior to the response received.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } return returnValue ; } catch ( InterruptedException exceptParam ) { //Interrupted... throw new FluidClientException ( \"SQLUtil-WebSocket-Interrupted-GetDescendants: \" + exceptParam . getMessage ( ) , exceptParam , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } catch ( ExecutionException executeProblem ) { //Error on the web-socket... Throwable cause = executeProblem . getCause ( ) ; //Fluid client exception... if ( cause instanceof FluidClientException ) { throw ( FluidClientException ) cause ; } else { throw new FluidClientException ( \"SQLUtil-WebSocket-GetDescendants: \" + cause . getMessage ( ) , cause , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } } catch ( TimeoutException eParam ) { //Timeout... String errMessage = this . getExceptionMessageVerbose ( \"SQLUtil-WebSocket-GetDescendants\" , uniqueReqId , numberOfSentForms ) ; throw new FluidClientException ( errMessage , FluidClientException . ErrorCode . IO_ERROR ) ; } finally { this . removeHandler ( uniqueReqId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a property and returns the value as { @code java . lang . String } . [CODESPLIT] protected static String getStringPropertyFromProperties ( Properties propertiesParam , String propertyKeyParam ) { if ( propertiesParam == null || propertiesParam . isEmpty ( ) ) { return null ; } return propertiesParam . getProperty ( propertyKeyParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a property and returns the value as { @code int } . [CODESPLIT] protected static int getIntPropertyFromProperties ( Properties propertiesParam , String propertyKeyParam ) { String strProp = getStringPropertyFromProperties ( propertiesParam , propertyKeyParam ) ; if ( strProp == null || strProp . trim ( ) . isEmpty ( ) ) { return - 1 ; } try { return Integer . parseInt ( strProp ) ; } catch ( NumberFormatException nfe ) { return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns - 1 if there is a problem with conversion . [CODESPLIT] protected long toLongSafe ( String toParseParam ) { if ( toParseParam == null || toParseParam . trim ( ) . isEmpty ( ) ) { return - 1 ; } try { return Long . parseLong ( toParseParam . trim ( ) ) ; } catch ( NumberFormatException e ) { return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Flow... if ( this . getFlow ( ) != null ) { returnVal . put ( JSONMapping . FLOW , this . getFlow ( ) ) ; } //Form... if ( this . getForm ( ) != null ) { returnVal . put ( JSONMapping . FORM , this . getForm ( ) . toJsonObject ( ) ) ; } //User Fields... if ( this . getUserFields ( ) != null && ! this . getUserFields ( ) . isEmpty ( ) ) { JSONArray fieldsArr = new JSONArray ( ) ; for ( Field toAdd : this . getUserFields ( ) ) { fieldsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . USER_FIELDS , fieldsArr ) ; } //Route Fields... if ( this . getRouteFields ( ) != null && ! this . getRouteFields ( ) . isEmpty ( ) ) { JSONArray fieldsArr = new JSONArray ( ) ; for ( Field toAdd : this . getRouteFields ( ) ) { fieldsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ROUTE_FIELDS , fieldsArr ) ; } //Global Fields... if ( this . getGlobalFields ( ) != null && ! this . getGlobalFields ( ) . isEmpty ( ) ) { JSONArray fieldsArr = new JSONArray ( ) ; for ( Field toAdd : this . getGlobalFields ( ) ) { fieldsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . GLOBAL_FIELDS , fieldsArr ) ; } //Attachments... if ( this . getAttachments ( ) != null ) { JSONArray jsonArray = new JSONArray ( ) ; for ( Attachment toAdd : this . getAttachments ( ) ) { jsonArray . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ATTACHMENTS , jsonArray ) ; } //Flow State... if ( this . getFlowState ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STATE , this . getFlowState ( ) . toString ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize { @code this } object into a JSONObject . [CODESPLIT] @ XmlTransient public JSONObject convertToFlatJSONObject ( ) { JSONObject returnVal = new JSONObject ( ) ; //Id... returnVal . put ( FlatFormJSONMapping . FLUID_ITEM_ID , this . getId ( ) == null ? JSONObject . NULL : this . getId ( ) ) ; //Flow State... returnVal . put ( FlatFormJSONMapping . FLOW_STATE , ( this . getFlowState ( ) == null ) ? JSONObject . NULL : this . getFlowState ( ) . name ( ) ) ; //Populate the Form... JSONObject formJSONObjFlat = ( this . getForm ( ) == null ) ? null : this . getForm ( ) . convertToFlatJSONObject ( ) ; if ( formJSONObjFlat != null ) { formJSONObjFlat . keySet ( ) . forEach ( ( toAdd ) - > { returnVal . put ( toAdd , formJSONObjFlat . get ( toAdd ) )  ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Can Create... if ( this . isCanCreate ( ) != null ) { returnVal . put ( JSONMapping . CAN_CREATE , this . isCanCreate ( ) . booleanValue ( ) ) ; } //Form Definition... if ( this . getFormDefinition ( ) != null ) { returnVal . put ( JSONMapping . FORM_DEFINITION , this . getFormDefinition ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a comma seperated list of providers from { @code Identity } s . [CODESPLIT] public String getListOfProvidersFromIdentities ( ) { if ( this . getIdentities ( ) == null || this . getIdentities ( ) . isEmpty ( ) ) { return \"\" ; } StringBuilder returnVal = new StringBuilder ( ) ; for ( Identity identity : this . getIdentities ( ) ) { returnVal . append ( identity . getProvider ( ) ) ; returnVal . append ( \",\" ) ; } String toString = returnVal . toString ( ) ; return toString . substring ( 0 , toString . length ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //User Id... if ( this . getUserId ( ) != null ) { returnVal . put ( JSONMapping . USER_ID , this . getUserId ( ) ) ; } //Name... if ( this . getName ( ) != null ) { returnVal . put ( JSONMapping . NAME , this . getName ( ) ) ; } //Email... if ( this . getEmail ( ) != null ) { returnVal . put ( JSONMapping . EMAIL , this . getEmail ( ) ) ; } //Email Verified... returnVal . put ( JSONMapping . EMAIL_VERIFIED , this . isEmailVerified ( ) ) ; //Nickname... if ( this . getNickname ( ) != null ) { returnVal . put ( JSONMapping . NICKNAME , this . getNickname ( ) ) ; } //Picture... if ( this . getPicture ( ) != null ) { returnVal . put ( JSONMapping . PICTURE , this . getPicture ( ) ) ; } //Given Name... if ( this . getGivenName ( ) != null ) { returnVal . put ( JSONMapping . GIVEN_NAME , this . getGivenName ( ) ) ; } //Family Name... if ( this . getFamilyName ( ) != null ) { returnVal . put ( JSONMapping . FAMILY_NAME , this . getFamilyName ( ) ) ; } //Locale... if ( this . getLocale ( ) != null ) { returnVal . put ( JSONMapping . LOCALE , this . getLocale ( ) ) ; } //Identities... if ( this . getIdentities ( ) != null && ! this . getIdentities ( ) . isEmpty ( ) ) { JSONArray identitiesArr = new JSONArray ( ) ; for ( Identity toAdd : this . getIdentities ( ) ) { identitiesArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . IDENTITIES , identitiesArr ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes use of the Fluid Core to convert a document into a PDF file . [CODESPLIT] public File convertDocumentToPDF ( File inputDocumentParam ) { if ( inputDocumentParam == null || ! inputDocumentParam . exists ( ) ) { throw new UtilException ( \"Input document to convert not provided or does not exist.\" , UtilException . ErrorCode . COMMAND ) ; } if ( ! inputDocumentParam . isFile ( ) ) { throw new UtilException ( \"Input document '' is not a file.\" , UtilException . ErrorCode . COMMAND ) ; } File parentFolder = inputDocumentParam . getParentFile ( ) ; String inputFilenameWithoutExt = inputDocumentParam . getName ( ) ; int indexOfDot = - 1 ; if ( ( indexOfDot = inputFilenameWithoutExt . indexOf ( ' ' ) ) > - 1 ) { inputFilenameWithoutExt = inputFilenameWithoutExt . substring ( 0 , indexOfDot ) ; } File generatedPdfFileOut = new File ( parentFolder . getAbsolutePath ( ) . concat ( File . separator ) . concat ( inputFilenameWithoutExt ) . concat ( \".pdf\" ) ) ; String completeOutputPath = generatedPdfFileOut . getAbsolutePath ( ) ; try { CommandUtil . CommandResult commandResult = this . commandUtil . executeCommand ( CommandUtil . FLUID_CLI , COMMAND_CONVERT_DOC_TO_PDF , \"-i\" , inputDocumentParam . getAbsolutePath ( ) , \"-o\" , completeOutputPath ) ; //There is a problem... if ( commandResult . getExitCode ( ) != 0 ) { throw new UtilException ( \"Unable to convert '\" + inputDocumentParam . getName ( ) + \"' to PDF. \" + commandResult . toString ( ) , UtilException . ErrorCode . COMMAND ) ; } File returnVal = new File ( completeOutputPath ) ; if ( ! returnVal . exists ( ) ) { throw new UtilException ( \"Command executed, but no output file. Expected PDF at '\" + completeOutputPath + \"'.\" , UtilException . ErrorCode . GENERAL ) ; } return returnVal ; } // catch ( IOException eParam ) { throw new UtilException ( \"Problem executing command. \" + eParam . getMessage ( ) , eParam , UtilException . ErrorCode . GENERAL ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Ancestor for the { @code formToGetAncestorForParam } . [CODESPLIT] public Form getAncestor ( Form formToGetAncestorForParam , boolean includeFieldDataParam , boolean includeTableFieldsParam ) { if ( DISABLE_WS ) { this . mode = Mode . RESTfulActive ; } //ANCESTOR... try { //When mode is null or [WebSocketActive]... if ( this . getAncestorClient == null && Mode . RESTfulActive != this . mode ) { this . getAncestorClient = new SQLUtilWebSocketGetAncestorClient ( this . baseURL , null , this . loggedInUser . getServiceTicketAsHexUpper ( ) , this . timeoutMillis , includeFieldDataParam , includeTableFieldsParam , COMPRESS_RSP , COMPRESS_RSP_CHARSET ) ; this . mode = Mode . WebSocketActive ; } } catch ( FluidClientException clientExcept ) { if ( clientExcept . getErrorCode ( ) != FluidClientException . ErrorCode . WEB_SOCKET_DEPLOY_ERROR ) { throw clientExcept ; } this . mode = Mode . RESTfulActive ; } Form formToUse = ( formToGetAncestorForParam == null ) ? null : new Form ( formToGetAncestorForParam . getId ( ) ) ; return ( this . getAncestorClient == null ) ? this . sqlUtilClient . getAncestor ( formToUse , includeFieldDataParam , includeTableFieldsParam ) : this . getAncestorClient . getAncestorSynchronized ( formToUse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the Descendants ( Forms ) for the { @code formsToGetDescForParam } . [CODESPLIT] public List < FormListing > getDescendants ( boolean includeFieldDataParam , boolean includeTableFieldsParam , boolean includeTableFieldFormRecordInfoParam , boolean massFetchParam , Form ... formsToGetDescForParam ) { if ( DISABLE_WS ) { this . mode = Mode . RESTfulActive ; } //DESCENDANTS... try { //When mode is null or [WebSocketActive]... if ( this . getDescendantsClient == null && Mode . RESTfulActive != this . mode ) { this . getDescendantsClient = new SQLUtilWebSocketGetDescendantsClient ( this . baseURL , null , this . loggedInUser . getServiceTicketAsHexUpper ( ) , this . timeoutMillis , includeFieldDataParam , includeTableFieldsParam , includeTableFieldFormRecordInfoParam , massFetchParam , COMPRESS_RSP , COMPRESS_RSP_CHARSET ) ; this . mode = Mode . WebSocketActive ; } } catch ( FluidClientException clientExcept ) { if ( clientExcept . getErrorCode ( ) != FluidClientException . ErrorCode . WEB_SOCKET_DEPLOY_ERROR ) { throw clientExcept ; } this . mode = Mode . RESTfulActive ; } if ( formsToGetDescForParam == null || formsToGetDescForParam . length < 1 ) { return null ; } Form [ ] formsToFetchFor = new Form [ formsToGetDescForParam . length ] ; for ( int index = 0 ; index < formsToFetchFor . length ; index ++ ) { formsToFetchFor [ index ] = new Form ( formsToGetDescForParam [ index ] . getId ( ) ) ; } if ( this . getDescendantsClient != null ) { return this . getDescendantsClient . getDescendantsSynchronized ( formsToFetchFor ) ; } else { List < FormListing > returnVal = new ArrayList <> ( ) ; for ( Form formToFetchFor : formsToFetchFor ) { List < Form > listOfForms = this . sqlUtilClient . getDescendants ( formToFetchFor , includeFieldDataParam , includeTableFieldsParam , includeTableFieldFormRecordInfoParam ) ; FormListing toAdd = new FormListing ( ) ; toAdd . setListing ( listOfForms ) ; toAdd . setListingCount ( ( listOfForms == null ) ? 0 : listOfForms . size ( ) ) ; returnVal . add ( toAdd ) ; } return returnVal ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the Table ( Forms ) for the { @code formsToGetDescForParam } . [CODESPLIT] public List < FormListing > getTableForms ( boolean includeFieldDataParam , Form ... formsToGetTableFormsForParam ) { if ( DISABLE_WS ) { this . mode = Mode . RESTfulActive ; } //DESCENDANTS... try { //When mode is null or [WebSocketActive]... if ( this . getTableFormsClient == null && Mode . RESTfulActive != this . mode ) { this . getTableFormsClient = new SQLUtilWebSocketGetTableFormsClient ( this . baseURL , null , this . loggedInUser . getServiceTicketAsHexUpper ( ) , this . timeoutMillis , includeFieldDataParam , COMPRESS_RSP , COMPRESS_RSP_CHARSET ) ; this . mode = Mode . WebSocketActive ; } } catch ( FluidClientException clientExcept ) { if ( clientExcept . getErrorCode ( ) != FluidClientException . ErrorCode . WEB_SOCKET_DEPLOY_ERROR ) { throw clientExcept ; } this . mode = Mode . RESTfulActive ; } if ( formsToGetTableFormsForParam == null || formsToGetTableFormsForParam . length < 1 ) { return null ; } Form [ ] formsToFetchFor = new Form [ formsToGetTableFormsForParam . length ] ; for ( int index = 0 ; index < formsToFetchFor . length ; index ++ ) { formsToFetchFor [ index ] = new Form ( formsToGetTableFormsForParam [ index ] . getId ( ) ) ; } if ( this . getTableFormsClient != null ) { return this . getTableFormsClient . getTableFormsSynchronized ( formsToFetchFor ) ; } else { List < FormListing > returnVal = new ArrayList <> ( ) ; for ( Form formToFetchFor : formsToFetchFor ) { List < Form > listOfForms = this . sqlUtilClient . getTableForms ( formToFetchFor , includeFieldDataParam ) ; FormListing toAdd = new FormListing ( ) ; toAdd . setListing ( listOfForms ) ; toAdd . setListingCount ( ( listOfForms == null ) ? 0 : listOfForms . size ( ) ) ; returnVal . add ( toAdd ) ; } return returnVal ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the ( Fields ) for the { @code formsToGetDescForParam } . [CODESPLIT] public List < FormFieldListing > getFormFields ( boolean includeFieldDataParam , Form ... formsToGetFieldsForParam ) { if ( DISABLE_WS ) { this . mode = Mode . RESTfulActive ; } //FORM FIELDS... try { //When mode is null or [WebSocketActive]... if ( this . getFormFieldsClient == null && Mode . RESTfulActive != this . mode ) { this . getFormFieldsClient = new SQLUtilWebSocketGetFormFieldsClient ( this . baseURL , null , this . loggedInUser . getServiceTicketAsHexUpper ( ) , this . timeoutMillis , includeFieldDataParam , COMPRESS_RSP , COMPRESS_RSP_CHARSET ) ; this . mode = Mode . WebSocketActive ; } } catch ( FluidClientException clientExcept ) { if ( clientExcept . getErrorCode ( ) != FluidClientException . ErrorCode . WEB_SOCKET_DEPLOY_ERROR ) { throw clientExcept ; } this . mode = Mode . RESTfulActive ; } if ( formsToGetFieldsForParam == null || formsToGetFieldsForParam . length < 1 ) { return null ; } Form [ ] formsToFetchFor = new Form [ formsToGetFieldsForParam . length ] ; for ( int index = 0 ; index < formsToFetchFor . length ; index ++ ) { formsToFetchFor [ index ] = new Form ( formsToGetFieldsForParam [ index ] . getId ( ) ) ; } if ( this . getFormFieldsClient != null ) { return this . getFormFieldsClient . getFormFieldsSynchronized ( formsToFetchFor ) ; } else { List < FormFieldListing > returnVal = new ArrayList <> ( ) ; for ( Form formToFetchFor : formsToFetchFor ) { List < Field > listOfFields = this . sqlUtilClient . getFormFields ( formToFetchFor , includeFieldDataParam ) ; FormFieldListing toAdd = new FormFieldListing ( ) ; toAdd . setListing ( listOfFields ) ; toAdd . setListingCount ( ( listOfFields == null ) ? 0 : listOfFields . size ( ) ) ; returnVal . add ( toAdd ) ; } return returnVal ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the ( Fields ) for the { @code formsToGetDescForParam } . [CODESPLIT] public void massPopulateFormFields ( boolean includeFieldDataParam , Form ... formsToPopulateFormFieldsForParam ) { if ( DISABLE_WS ) { this . mode = Mode . RESTfulActive ; } //FORM FIELDS... try { //When mode is null or [WebSocketActive]... if ( this . getFormFieldsClient == null && Mode . RESTfulActive != this . mode ) { this . getFormFieldsClient = new SQLUtilWebSocketGetFormFieldsClient ( this . baseURL , null , this . loggedInUser . getServiceTicketAsHexUpper ( ) , this . timeoutMillis , includeFieldDataParam , COMPRESS_RSP , COMPRESS_RSP_CHARSET ) ; this . mode = Mode . WebSocketActive ; } } catch ( FluidClientException clientExcept ) { if ( clientExcept . getErrorCode ( ) != FluidClientException . ErrorCode . WEB_SOCKET_DEPLOY_ERROR ) { throw clientExcept ; } this . mode = Mode . RESTfulActive ; } //Nothing to do... if ( formsToPopulateFormFieldsForParam == null || formsToPopulateFormFieldsForParam . length < 1 ) { return ; } //Populate a known echo for all of the local form caches... Form [ ] formsToFetchForLocalCacheArr = new Form [ formsToPopulateFormFieldsForParam . length ] ; for ( int index = 0 ; index < formsToFetchForLocalCacheArr . length ; index ++ ) { formsToFetchForLocalCacheArr [ index ] = new Form ( formsToPopulateFormFieldsForParam [ index ] . getId ( ) ) ; formsToFetchForLocalCacheArr [ index ] . setEcho ( UUID . randomUUID ( ) . toString ( ) ) ; } List < FormFieldListing > listingReturnFieldValsPopulated = new ArrayList <> ( ) ; //Fetch all of the values in a single go... if ( this . getFormFieldsClient != null ) { listingReturnFieldValsPopulated = this . getFormFieldsClient . getFormFieldsSynchronized ( formsToFetchForLocalCacheArr ) ; } else { //Old Rest way of fetching all of the values... for ( Form formToFetchFor : formsToFetchForLocalCacheArr ) { List < Field > listOfFields = this . sqlUtilClient . getFormFields ( formToFetchFor , includeFieldDataParam ) ; FormFieldListing toAdd = new FormFieldListing ( ) ; toAdd . setListing ( listOfFields ) ; toAdd . setListingCount ( ( listOfFields == null ) ? 0 : listOfFields . size ( ) ) ; toAdd . setEcho ( formToFetchFor . getEcho ( ) ) ; listingReturnFieldValsPopulated . add ( toAdd ) ; } } //Populate each of the form from the param... for ( Form formToSetFieldsOn : formsToPopulateFormFieldsForParam ) { formToSetFieldsOn . setFormFields ( this . getFieldValuesForFormFromCache ( formToSetFieldsOn . getId ( ) , listingReturnFieldValsPopulated , formsToFetchForLocalCacheArr ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the field values from the cache . [CODESPLIT] private List < Field > getFieldValuesForFormFromCache ( Long formIdParam , List < FormFieldListing > listingReturnFieldValsPopulatedParam , Form [ ] formsToFetchForLocalCacheArrParam ) { if ( formIdParam == null || formIdParam . longValue ( ) < 1 ) { return null ; } if ( listingReturnFieldValsPopulatedParam == null || listingReturnFieldValsPopulatedParam . isEmpty ( ) ) { return null ; } if ( formsToFetchForLocalCacheArrParam == null || formsToFetchForLocalCacheArrParam . length == 0 ) { return null ; } for ( Form formIter : formsToFetchForLocalCacheArrParam ) { //Form is a match... if ( formIdParam . equals ( formIter . getId ( ) ) ) { String echoToUse = formIter . getEcho ( ) ; for ( FormFieldListing fieldListing : listingReturnFieldValsPopulatedParam ) { if ( echoToUse . equals ( fieldListing . getEcho ( ) ) ) { return fieldListing . getListing ( ) ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close any clients used during lifetime of { [CODESPLIT] public void closeAndClean ( ) { if ( this . sqlUtilClient != null ) { this . sqlUtilClient . closeAndClean ( ) ; } if ( this . getAncestorClient != null ) { this . getAncestorClient . closeAndClean ( ) ; } if ( this . getDescendantsClient != null ) { this . getDescendantsClient . closeAndClean ( ) ; } if ( this . getTableFormsClient != null ) { this . getTableFormsClient . closeAndClean ( ) ; } if ( this . getFormFieldsClient != null ) { this . getFormFieldsClient . closeAndClean ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Name... if ( this . getColumnName ( ) != null ) { returnVal . put ( JSONMapping . COLUMN_NAME , this . getColumnName ( ) ) ; } //Index... if ( this . getColumnIndex ( ) != null ) { returnVal . put ( JSONMapping . COLUMN_INDEX , this . getColumnIndex ( ) ) ; } //SQL Type... if ( this . getSqlType ( ) != null ) { returnVal . put ( JSONMapping . SQL_TYPE , this . getSqlType ( ) ) ; } //SQL Value... if ( this . getSqlValue ( ) != null ) { returnVal . put ( JSONMapping . SQL_VALUE , this . getSqlValue ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Base { @code toJsonObject } that creates a { @code JSONObject } with the Id and ServiceTicket set . < / p > [CODESPLIT] @ XmlTransient public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = new JSONObject ( ) ; //Id... if ( this . getId ( ) != null ) { returnVal . put ( JSONMapping . ID , this . getId ( ) ) ; } //Service Ticket... if ( this . getServiceTicket ( ) != null ) { returnVal . put ( JSONMapping . SERVICE_TICKET , this . getServiceTicket ( ) ) ; } //Echo... if ( this . getEcho ( ) != null ) { returnVal . put ( JSONMapping . ECHO , this . getEcho ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the { @code Long } timestamp into a { @code Date } object . [CODESPLIT] @ XmlTransient private Date getLongAsDateFromJson ( Long longValueParam ) { if ( longValueParam == null ) { return null ; } return new Date ( longValueParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the value of field { @code fieldNameParam } as a timestamp . [CODESPLIT] @ XmlTransient public Date getDateFieldValueFromFieldWithName ( String fieldNameParam ) { if ( ( fieldNameParam == null || fieldNameParam . trim ( ) . isEmpty ( ) ) || ( this . jsonObject == null || this . jsonObject . isNull ( fieldNameParam ) ) ) { return null ; } Object objectAtIndex = this . jsonObject . get ( fieldNameParam ) ; if ( objectAtIndex instanceof Number ) { return this . getLongAsDateFromJson ( ( ( Number ) objectAtIndex ) . longValue ( ) ) ; } else if ( objectAtIndex instanceof String ) { Date validDate = null ; for ( SimpleDateFormat format : SUPPORTED_FORMATS ) { try { validDate = format . parse ( ( String ) objectAtIndex ) ; if ( validDate != null ) { break ; } } catch ( ParseException parseExcept ) { validDate = null ; } } return validDate ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the { @code Date } object into a { @code Long } timestamp . [CODESPLIT] @ XmlTransient public Long getDateAsLongFromJson ( Date dateValueParam ) { if ( dateValueParam == null ) { return null ; } return dateValueParam . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Flow Step Entry rule . [CODESPLIT] public FlowStepRule createFlowStepEntryRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . putJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleEntryCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Flow Step Exit rule . [CODESPLIT] public FlowStepRule createFlowStepExitRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . putJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleExitCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Flow Step View rule . [CODESPLIT] public FlowStepRule createFlowStepViewRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . putJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleViewCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Flow Step Entry rule . [CODESPLIT] public FlowStepRule updateFlowStepEntryRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleUpdateEntry ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Flow Step Exit rule . [CODESPLIT] public FlowStepRule updateFlowStepExitRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleUpdateExit ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Flow Step View rule . [CODESPLIT] public FlowStepRule updateFlowStepViewRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleUpdateView ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the { @code viewRuleSyntaxParam } text within the Fluid workflow engine . [CODESPLIT] public FlowStepRule compileFlowStepViewRule ( String viewRuleSyntaxParam ) { FlowStepRule flowStepRule = new FlowStepRule ( ) ; flowStepRule . setRule ( viewRuleSyntaxParam ) ; if ( this . serviceTicket != null ) { flowStepRule . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRule , WS . Path . FlowStepRule . Version1 . compileViewSyntax ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the exit rules by step { @code flowStepParam } . Name or id can be provided . [CODESPLIT] public FlowStepRuleListing getExitRulesByStep ( FlowStep flowStepParam ) { if ( flowStepParam == null ) { return null ; } if ( this . serviceTicket != null ) { flowStepParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRuleListing ( this . postJson ( flowStepParam , WS . Path . FlowStepRule . Version1 . getExitRulesByStep ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles and Executes the { @code viewRuleSyntaxParam } text within the Fluid workflow engine . [CODESPLIT] public FlowItemExecuteResult compileFlowStepViewRuleAndExecute ( String viewRuleSyntaxParam , FluidItem fluidItemToExecuteOnParam ) { FlowStepRule flowStepRule = new FlowStepRule ( ) ; flowStepRule . setRule ( viewRuleSyntaxParam ) ; FlowItemExecutePacket toPost = new FlowItemExecutePacket ( ) ; if ( this . serviceTicket != null ) { toPost . setServiceTicket ( this . serviceTicket ) ; } toPost . setFlowStepRule ( flowStepRule ) ; toPost . setFluidItem ( fluidItemToExecuteOnParam ) ; return new FlowItemExecuteResult ( this . postJson ( toPost , WS . Path . FlowStepRule . Version1 . compileViewSyntaxAndExecute ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the { @code entryRuleSyntaxParam } text within the Fluid workflow engine . [CODESPLIT] public FlowStepRule compileFlowStepEntryRule ( String entryRuleSyntaxParam ) { FlowStepRule flowStepRule = new FlowStepRule ( ) ; flowStepRule . setRule ( entryRuleSyntaxParam ) ; if ( this . serviceTicket != null ) { flowStepRule . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRule , WS . Path . FlowStepRule . Version1 . compileEntrySyntax ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles and Executes the { @code entryRuleSyntaxParam } text within the Fluid workflow engine . [CODESPLIT] public FlowItemExecuteResult compileFlowStepEntryRuleAndExecute ( String entryRuleSyntaxParam , FluidItem fluidItemToExecuteOnParam ) { FlowStepRule flowStepRule = new FlowStepRule ( ) ; flowStepRule . setRule ( entryRuleSyntaxParam ) ; FlowItemExecutePacket toPost = new FlowItemExecutePacket ( ) ; if ( this . serviceTicket != null ) { toPost . setServiceTicket ( this . serviceTicket ) ; } toPost . setFlowStepRule ( flowStepRule ) ; toPost . setFluidItem ( fluidItemToExecuteOnParam ) ; return new FlowItemExecuteResult ( this . postJson ( toPost , WS . Path . FlowStepRule . Version1 . compileEntrySyntaxAndExecute ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves an entry rule order one up from the current location . [CODESPLIT] public FlowStepRule moveFlowStepEntryRuleUp ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleMoveEntryUp ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves an entry rule order one down from the current location . [CODESPLIT] public FlowStepRule moveFlowStepEntryRuleDown ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleMoveEntryDown ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes an Step Entry rule . [CODESPLIT] public FlowStepRule deleteFlowStepEntryRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStepRule ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleDeleteEntry ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes an Step Exit rule . [CODESPLIT] public FlowStep deleteFlowStepExitRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleDeleteExit ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes an Step View rule . [CODESPLIT] public FlowStep deleteFlowStepViewRule ( FlowStepRule flowStepRuleParam ) { if ( flowStepRuleParam != null && this . serviceTicket != null ) { flowStepRuleParam . setServiceTicket ( this . serviceTicket ) ; } return new FlowStep ( this . postJson ( flowStepRuleParam , WS . Path . FlowStepRule . Version1 . flowStepRuleDeleteView ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the next valid syntax rules for { @code inputRuleParam } . [CODESPLIT] public List < String > getNextValidSyntaxWordsEntryRule ( String inputRuleParam ) { if ( inputRuleParam == null ) { inputRuleParam = UtilGlobal . EMPTY ; } FlowStepRule flowStepRule = new FlowStepRule ( ) ; flowStepRule . setRule ( inputRuleParam ) ; if ( this . serviceTicket != null ) { flowStepRule . setServiceTicket ( this . serviceTicket ) ; } FlowStepRule returnedObj = new FlowStepRule ( this . postJson ( flowStepRule , WS . Path . FlowStepRule . Version1 . getNextValidEntrySyntax ( ) ) ) ; return returnedObj . getNextValidSyntaxWords ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the necessary login actions against Fluid . [CODESPLIT] public AppRequestToken login ( String usernameParam , String passwordParam ) { //Default login is for 9 hours. return this . login ( usernameParam , passwordParam , TimeUnit . HOURS . toSeconds ( 9 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the necessary login actions against Fluid . [CODESPLIT] public AppRequestToken login ( String usernameParam , String passwordParam , Long sessionLifespanSecondsParam ) { if ( this . isEmpty ( usernameParam ) || this . isEmpty ( passwordParam ) ) { throw new FluidClientException ( \"Username and Password required.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } AuthRequest authRequest = new AuthRequest ( ) ; authRequest . setUsername ( usernameParam ) ; authRequest . setLifetime ( sessionLifespanSecondsParam ) ; //Init the session... //Init the session to get the salt... AuthResponse authResponse ; try { authResponse = new AuthResponse ( this . postJson ( true , authRequest , WS . Path . User . Version1 . userInitSession ( ) ) ) ; } //JSON format problem... catch ( JSONException jsonException ) { throw new FluidClientException ( jsonException . getMessage ( ) , jsonException , FluidClientException . ErrorCode . JSON_PARSING ) ; } AuthEncryptedData authEncData = this . initializeSession ( passwordParam , authResponse ) ; //Issue the token... AppRequestToken appReqToken = this . issueAppRequestToken ( authResponse . getServiceTicketBase64 ( ) , usernameParam , authEncData ) ; appReqToken . setRoleString ( authEncData . getRoleListing ( ) ) ; appReqToken . setSalt ( authResponse . getSalt ( ) ) ; return appReqToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs HMAC and encryption to initialize the session . [CODESPLIT] private AuthEncryptedData initializeSession ( String passwordParam , AuthResponse authResponseParam ) { //IV... byte [ ] ivBytes = UtilGlobal . decodeBase64 ( authResponseParam . getIvBase64 ( ) ) ; //Seed... byte [ ] seedBytes = UtilGlobal . decodeBase64 ( authResponseParam . getSeedBase64 ( ) ) ; //Encrypted Data... byte [ ] encryptedData = UtilGlobal . decodeBase64 ( authResponseParam . getEncryptedDataBase64 ( ) ) ; //HMac from Response... byte [ ] hMacFromResponse = UtilGlobal . decodeBase64 ( authResponseParam . getEncryptedDataHmacBase64 ( ) ) ; //Local HMac... byte [ ] localGeneratedHMac = AES256Local . generateLocalHMAC ( encryptedData , passwordParam , authResponseParam . getSalt ( ) , seedBytes ) ; //Password mismatch... if ( ! Arrays . equals ( hMacFromResponse , localGeneratedHMac ) ) { throw new FluidClientException ( \"Login attempt failure.\" , FluidClientException . ErrorCode . LOGIN_FAILURE ) ; } //Decrypted Initialization Data... byte [ ] decryptedEncryptedData = AES256Local . decryptInitPacket ( encryptedData , passwordParam , authResponseParam . getSalt ( ) , ivBytes , seedBytes ) ; try { JSONObject jsonObj = new JSONObject ( new String ( decryptedEncryptedData ) ) ; return new AuthEncryptedData ( jsonObj ) ; } catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Issue a new { @code AppRequestToken } from provided params . [CODESPLIT] private AppRequestToken issueAppRequestToken ( String serviceTicketBase64Param , String usernameParam , AuthEncryptedData authEncryptDataParam ) { byte [ ] iv = AES256Local . generateRandom ( AES256Local . IV_SIZE_BYTES ) ; byte [ ] seed = AES256Local . generateRandom ( AES256Local . SEED_SIZE_BYTES ) ; byte [ ] sessionKey = UtilGlobal . decodeBase64 ( authEncryptDataParam . getSessionKeyBase64 ( ) ) ; byte [ ] dataToEncrypt = usernameParam . getBytes ( ) ; byte [ ] encryptedData = AES256Local . encrypt ( sessionKey , dataToEncrypt , iv ) ; byte [ ] encryptedDataHMac = AES256Local . generateLocalHMACForReqToken ( encryptedData , sessionKey , seed ) ; AppRequestToken requestToServer = new AppRequestToken ( ) ; requestToServer . setEncryptedDataBase64 ( UtilGlobal . encodeBase64 ( encryptedData ) ) ; requestToServer . setEncryptedDataHmacBase64 ( UtilGlobal . encodeBase64 ( encryptedDataHMac ) ) ; requestToServer . setIvBase64 ( UtilGlobal . encodeBase64 ( iv ) ) ; requestToServer . setSeedBase64 ( UtilGlobal . encodeBase64 ( seed ) ) ; requestToServer . setServiceTicket ( serviceTicketBase64Param ) ; try { return new AppRequestToken ( this . postJson ( requestToServer , WS . Path . User . Version1 . userIssueToken ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , jsonExcept , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Fluid Item... if ( this . getFluidItem ( ) != null ) { returnVal . put ( JSONMapping . FLUID_ITEM , this . getFluidItem ( ) . toJsonObject ( ) ) ; } //Flow Step Rule... if ( this . getFlowStepRule ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STEP_RULE , this . getFlowStepRule ( ) . toJsonObject ( ) ) ; } //Assignment Rule... if ( this . getAssignmentRuleValue ( ) != null ) { returnVal . put ( JSONMapping . ASSIGNMENT_RULE_VALUE , this . getAssignmentRuleValue ( ) ) ; } //Statement Result as String... if ( this . getStatementResultAsString ( ) != null ) { returnVal . put ( JSONMapping . STATEMENT_RESULT_AS_STRING , this . getStatementResultAsString ( ) ) ; } //Execute per Fluid Item Query... if ( this . getExecutePerFluidItemQuery ( ) != null ) { returnVal . put ( JSONMapping . EXECUTE_PER_FLUID_ITEM_QUERY , this . getExecutePerFluidItemQuery ( ) ) ; } //Fluid Item Query... if ( this . getFluidItemQuery ( ) != null ) { returnVal . put ( JSONMapping . FLUID_ITEM_QUERY , this . getFluidItemQuery ( ) ) ; } //Execution Result... if ( this . getExecutionResult ( ) != null ) { returnVal . put ( JSONMapping . EXECUTION_RESULT , this . getExecutionResult ( ) ) ; } //Progress to next phase... if ( this . getProgressToNextPhase ( ) != null ) { returnVal . put ( JSONMapping . PROGRESS_TO_NEXT_PHASE , this . getProgressToNextPhase ( ) ) ; } //Fluid Items... if ( this . getFluidItems ( ) != null && ! this . getFluidItems ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( FluidItem item : this . getFluidItems ( ) ) { jsonArray . put ( item . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . FLUID_ITEMS , jsonArray ) ; } //Execute Users... if ( this . getExecuteUsers ( ) != null && ! this . getExecuteUsers ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( User item : this . getExecuteUsers ( ) ) { jsonArray . put ( item . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . EXECUTE_USERS , jsonArray ) ; } //Mail Messages To Send... if ( this . getMailMessagesToSend ( ) != null && ! this . getMailMessagesToSend ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( MailMessage item : this . getMailMessagesToSend ( ) ) { jsonArray . put ( item . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . MAIL_MESSAGES_TO_SEND , jsonArray ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Available... if ( this . getAvailableMultiChoices ( ) != null ) { List < String > availChoices = this . getAvailableMultiChoices ( ) ; returnVal . put ( JSONMapping . AVAILABLE_MULTI_CHOICES , new JSONArray ( availChoices . toArray ( ) ) ) ; returnVal . put ( JSONMapping . AVAILABLE_CHOICES , new JSONArray ( availChoices . toArray ( ) ) ) ; returnVal . put ( JSONMapping . AVAILABLE_CHOICES_COMBINED , this . combineStringArrayWith ( availChoices , UtilGlobal . PIPE ) ) ; } //Selected... if ( this . getSelectedMultiChoices ( ) != null ) { List < String > selectChoices = this . getSelectedMultiChoices ( ) ; returnVal . put ( JSONMapping . SELECTED_MULTI_CHOICES , new JSONArray ( selectChoices . toArray ( ) ) ) ; returnVal . put ( JSONMapping . SELECTED_CHOICES , new JSONArray ( selectChoices . toArray ( ) ) ) ; returnVal . put ( JSONMapping . SELECTED_CHOICES_COMBINED , this . combineStringArrayWith ( selectChoices , UtilGlobal . PIPE ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine { @code listToCombineParam } into a single { @code String } . [CODESPLIT] @ XmlTransient public String combineStringArrayWith ( List < String > listToCombineParam , String separatorCharsParam ) { String returnValue = UtilGlobal . EMPTY ; int lengthOfSepChars = ( separatorCharsParam == null ) ? 0 : separatorCharsParam . length ( ) ; if ( listToCombineParam != null && ! listToCombineParam . isEmpty ( ) ) { StringBuffer concatBuffer = new StringBuffer ( ) ; for ( String toAdd : listToCombineParam ) { concatBuffer . append ( toAdd ) ; concatBuffer . append ( separatorCharsParam ) ; } String concatString = concatBuffer . toString ( ) ; returnValue = concatString . substring ( 0 , concatString . length ( ) - lengthOfSepChars ) ; } return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code UserQuery } . [CODESPLIT] public UserQuery createUserQuery ( UserQuery userQueryParam ) { if ( userQueryParam != null && this . serviceTicket != null ) { userQueryParam . setServiceTicket ( this . serviceTicket ) ; } return new UserQuery ( this . putJson ( userQueryParam , WS . Path . UserQuery . Version1 . userQueryCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing { @code UserQuery } . [CODESPLIT] public UserQuery updateUserQuery ( UserQuery userQueryParam ) { if ( userQueryParam != null && this . serviceTicket != null ) { userQueryParam . setServiceTicket ( this . serviceTicket ) ; } return new UserQuery ( this . postJson ( userQueryParam , WS . Path . UserQuery . Version1 . userQueryUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the { @code UserQuery } provided . Id must be set on the { @code UserQuery } . [CODESPLIT] public UserQuery deleteUserQuery ( UserQuery userQueryToDeleteParam ) { if ( userQueryToDeleteParam != null && this . serviceTicket != null ) { userQueryToDeleteParam . setServiceTicket ( this . serviceTicket ) ; } return new UserQuery ( this . postJson ( userQueryToDeleteParam , WS . Path . UserQuery . Version1 . userQueryDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves User Query information for the provided { @code userQueryIdParam } . [CODESPLIT] public UserQuery getUserQueryById ( Long userQueryIdParam ) { UserQuery userQueryToGetInfoFor = new UserQuery ( ) ; userQueryToGetInfoFor . setId ( userQueryIdParam ) ; if ( this . serviceTicket != null ) { userQueryToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new UserQuery ( this . postJson ( userQueryToGetInfoFor , WS . Path . UserQuery . Version1 . getById ( ) ) ) ; } catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all user query information . [CODESPLIT] public UserQueryListing getAllUserQueries ( ) { UserQuery userQueryToGetInfoFor = new UserQuery ( ) ; if ( this . serviceTicket != null ) { userQueryToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new UserQueryListing ( this . postJson ( userQueryToGetInfoFor , WS . Path . UserQuery . Version1 . getAllUserQueries ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the { @code UserQuery } { @code queryToExecuteParam } and returns the result information . [CODESPLIT] public FluidItemListing executeUserQuery ( UserQuery queryToExecuteParam , boolean populateAncestorIdParam , int queryLimitParam , int offsetParam ) { return this . executeUserQuery ( queryToExecuteParam , populateAncestorIdParam , queryLimitParam , offsetParam , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the { @code UserQuery } { @code queryToExecuteParam } and returns the result information . [CODESPLIT] public FluidItemListing executeUserQuery ( UserQuery queryToExecuteParam , boolean populateAncestorIdParam , int queryLimitParam , int offsetParam , boolean forceUseDatabaseParam ) { if ( this . serviceTicket != null && queryToExecuteParam != null ) { queryToExecuteParam . setServiceTicket ( this . serviceTicket ) ; } try { return new FluidItemListing ( this . postJson ( queryToExecuteParam , WS . Path . UserQuery . Version1 . executeUserQuery ( populateAncestorIdParam , forceUseDatabaseParam , queryLimitParam , offsetParam ) ) ) ; } catch ( JSONException jsonExcept ) { //JSON Issue... throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the Form Field mappings for Electronic Form { @code electronicFormIdParam } . [CODESPLIT] public List < FormFieldMapping > getFormFieldMappingForForm ( Long electronicFormIdParam ) { List < FormFieldMapping > returnVal = new ArrayList ( ) ; if ( electronicFormIdParam == null ) { return returnVal ; } PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; try { Long formDefinitionId = this . getFormDefinitionId ( electronicFormIdParam ) ; //Local Mapping... //When we have the key by definition, we can just return. if ( this . localDefinitionToFieldsMapping . containsKey ( formDefinitionId ) ) { return this . localDefinitionToFieldsMapping . get ( formDefinitionId ) ; } ISyntax syntax = SyntaxFactory . getInstance ( ) . getSyntaxFor ( this . getSQLTypeFromConnection ( ) , ISyntax . ProcedureMapping . Field . GetFormFieldsForFormContainer ) ; preparedStatement = this . getConnection ( ) . prepareStatement ( syntax . getPreparedStatement ( ) ) ; preparedStatement . setLong ( 1 , electronicFormIdParam ) ; resultSet = preparedStatement . executeQuery ( ) ; //Iterate each of the form containers... while ( resultSet . next ( ) ) { returnVal . add ( this . mapFormFieldMapping ( resultSet ) ) ; } //Cache the mapping... this . localDefinitionToFieldsMapping . put ( formDefinitionId , returnVal ) ; return returnVal ; } catch ( SQLException sqlError ) { throw new FluidSQLException ( sqlError ) ; } finally { this . closeStatement ( preparedStatement , resultSet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the Form Field mappings for Form Definition { @code electronicFormDefinitionIdParam } . [CODESPLIT] public List < FormFieldMapping > getFormFieldMappingForFormDefinition ( Long formDefinitionIdParam ) { List < FormFieldMapping > returnVal = new ArrayList ( ) ; if ( formDefinitionIdParam == null || formDefinitionIdParam . longValue ( ) < 1 ) { return returnVal ; } PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; try { //Local Mapping... //When we have the key by definition, we can just return. if ( this . localDefinitionToFieldsMapping . containsKey ( formDefinitionIdParam ) ) { return this . localDefinitionToFieldsMapping . get ( formDefinitionIdParam ) ; } ISyntax syntax = SyntaxFactory . getInstance ( ) . getSyntaxFor ( this . getSQLTypeFromConnection ( ) , ISyntax . ProcedureMapping . Field . GetFormFieldsForFormDefinition ) ; preparedStatement = this . getConnection ( ) . prepareStatement ( syntax . getPreparedStatement ( ) ) ; preparedStatement . setLong ( 1 , formDefinitionIdParam ) ; resultSet = preparedStatement . executeQuery ( ) ; //Iterate each of the form containers... while ( resultSet . next ( ) ) { returnVal . add ( this . mapFormFieldMapping ( resultSet ) ) ; } this . localDefinitionToFieldsMapping . put ( formDefinitionIdParam , returnVal ) ; return returnVal ; } // catch ( SQLException sqlError ) { throw new FluidSQLException ( sqlError ) ; } // finally { this . closeStatement ( preparedStatement , resultSet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Definition Id for the Electronic Form with id { @code electronicFormIdParam } . [CODESPLIT] public Long getFormDefinitionId ( Long electronicFormIdParam ) { if ( electronicFormIdParam == null ) { return null ; } PreparedStatement preparedStatement = null ; ResultSet resultSet ; try { ISyntax syntax = SyntaxFactory . getInstance ( ) . getSyntaxFor ( this . getSQLTypeFromConnection ( ) , ISyntax . ProcedureMapping . Field . GetFormDefinitionForFormContainer ) ; preparedStatement = this . getConnection ( ) . prepareStatement ( syntax . getPreparedStatement ( ) ) ; preparedStatement . setLong ( 1 , electronicFormIdParam ) ; resultSet = preparedStatement . executeQuery ( ) ; //Iterate each of the form containers... while ( resultSet . next ( ) ) { return resultSet . getLong ( 1 ) ; } return null ; } catch ( SQLException sqlError ) { throw new FluidSQLException ( sqlError ) ; } finally { this . closeStatement ( preparedStatement ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Fields { @code VALUES } for the Electronic Form with id { @code electronicFormIdParam } . [CODESPLIT] public List < Field > getFormFields ( Long electronicFormIdParam , boolean includeTableFieldsParam , boolean includeTableFieldFormRecordInfoParam ) { List < Field > returnVal = new ArrayList ( ) ; if ( electronicFormIdParam == null ) { return returnVal ; } List < FormFieldMapping > fieldMappings = this . getFormFieldMappingForForm ( electronicFormIdParam ) ; if ( fieldMappings == null || fieldMappings . isEmpty ( ) ) { return returnVal ; } //Get the values for each of the fields... for ( FormFieldMapping fieldMapping : fieldMappings ) { //Skip if ignore Table Fields... if ( ! includeTableFieldsParam && fieldMapping . dataType == UtilGlobal . FieldTypeId . _7_TABLE_FIELD ) { //Table Field... continue ; } Field fieldToAdd = this . getFormFieldValueFor ( fieldMapping , electronicFormIdParam , includeTableFieldFormRecordInfoParam ) ; if ( fieldToAdd == null ) { continue ; } //When table field... if ( includeTableFieldsParam && ( fieldToAdd . getFieldValue ( ) instanceof TableField ) ) { TableField tableField = ( TableField ) fieldToAdd . getFieldValue ( ) ; if ( tableField . getTableRecords ( ) != null && ! tableField . getTableRecords ( ) . isEmpty ( ) ) { for ( Form tableRecordForm : tableField . getTableRecords ( ) ) { tableRecordForm . setFormFields ( this . getFormFields ( tableRecordForm . getId ( ) , false , false ) ) ; } } } returnVal . add ( fieldToAdd ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Field value for Electronic Form { @code formContainerIdParam } . [CODESPLIT] public Field getFormFieldValueFor ( FormFieldMapping formFieldMappingParam , Long formContainerIdParam , boolean includeTableFieldFormRecordInfoParam ) { if ( formFieldMappingParam == null ) { return null ; } //First attempt to fetch from the cache... if ( this . getCacheUtil ( ) != null ) { CacheUtil . CachedFieldValue cachedFieldValue = this . getCacheUtil ( ) . getCachedFieldValueFrom ( formFieldMappingParam . formDefinitionId , formContainerIdParam , formFieldMappingParam . formFieldId ) ; if ( cachedFieldValue != null ) { Field field = cachedFieldValue . getCachedFieldValueAsField ( ) ; if ( field != null ) { field . setFieldName ( formFieldMappingParam . name ) ; return field ; } } } //Now use a database lookup... Field returnVal = null ; PreparedStatement preparedStatement = null , preparedStatementForTblInfo = null ; ResultSet resultSet = null , resultSetForTblInfo = null ; try { ISyntax syntax = SyntaxFactory . getInstance ( ) . getFieldValueSyntaxFor ( this . getSQLTypeFromConnection ( ) , formFieldMappingParam ) ; if ( syntax != null ) { preparedStatement = this . getConnection ( ) . prepareStatement ( syntax . getPreparedStatement ( ) ) ; preparedStatement . setLong ( 1 , formFieldMappingParam . formDefinitionId ) ; preparedStatement . setLong ( 2 , formFieldMappingParam . formFieldId ) ; preparedStatement . setLong ( 3 , formContainerIdParam ) ; resultSet = preparedStatement . executeQuery ( ) ; } switch ( formFieldMappingParam . dataType . intValue ( ) ) { //Text... case UtilGlobal . FieldTypeId . _1_TEXT : if ( resultSet . next ( ) ) { returnVal = new Field ( formFieldMappingParam . name , resultSet . getString ( 1 ) , Field . Type . Text ) ; } break ; //True False... case UtilGlobal . FieldTypeId . _2_TRUE_FALSE : if ( resultSet . next ( ) ) { returnVal = new Field ( formFieldMappingParam . name , resultSet . getBoolean ( 1 ) , Field . Type . TrueFalse ) ; } break ; //Paragraph Text... case UtilGlobal . FieldTypeId . _3_PARAGRAPH_TEXT : if ( resultSet . next ( ) ) { returnVal = new Field ( formFieldMappingParam . name , resultSet . getString ( 1 ) , Field . Type . ParagraphText ) ; } break ; //Multiple Choice... case UtilGlobal . FieldTypeId . _4_MULTI_CHOICE : MultiChoice multiChoice = new MultiChoice ( ) ; List < String > selectedValues = new ArrayList ( ) ; while ( resultSet . next ( ) ) { selectedValues . add ( resultSet . getString ( 1 ) ) ; } multiChoice . setSelectedMultiChoices ( selectedValues ) ; if ( ! selectedValues . isEmpty ( ) ) { returnVal = new Field ( formFieldMappingParam . name , multiChoice ) ; } break ; //Date Time... case UtilGlobal . FieldTypeId . _5_DATE_TIME : if ( resultSet . next ( ) ) { returnVal = new Field ( formFieldMappingParam . name , resultSet . getDate ( 1 ) , Field . Type . DateTime ) ; } break ; //Decimal... case UtilGlobal . FieldTypeId . _6_DECIMAL : if ( resultSet . next ( ) ) { returnVal = new Field ( formFieldMappingParam . name , resultSet . getDouble ( 1 ) , Field . Type . Decimal ) ; } break ; //Table Field... case UtilGlobal . FieldTypeId . _7_TABLE_FIELD : List < Long > formContainerIds = new ArrayList ( ) ; while ( resultSet . next ( ) ) { formContainerIds . add ( resultSet . getLong ( 1 ) ) ; } //Break if empty... if ( formContainerIds . isEmpty ( ) ) { break ; } TableField tableField = new TableField ( ) ; final List < Form > formRecords = new ArrayList ( ) ; //Populate all the ids for forms... formContainerIds . forEach ( formContId -> { formRecords . add ( new Form ( formContId ) ) ; } ) ; //Retrieve the info for the table record... if ( includeTableFieldFormRecordInfoParam ) { ISyntax syntaxForFormContInfo = SyntaxFactory . getInstance ( ) . getSyntaxFor ( this . getSQLTypeFromConnection ( ) , ISyntax . ProcedureMapping . Form . GetFormContainerInfo ) ; preparedStatementForTblInfo = this . getConnection ( ) . prepareStatement ( syntaxForFormContInfo . getPreparedStatement ( ) ) ; for ( Form formRecordToSetInfoOn : formRecords ) { preparedStatementForTblInfo . setLong ( 1 , formRecordToSetInfoOn . getId ( ) ) ; resultSetForTblInfo = preparedStatementForTblInfo . executeQuery ( ) ; if ( resultSetForTblInfo . next ( ) ) { Long formTypeId = resultSetForTblInfo . getLong ( SQLFormUtil . SQLColumnIndex . _02_FORM_TYPE ) ; formRecordToSetInfoOn . setFormTypeId ( formTypeId ) ; formRecordToSetInfoOn . setFormType ( this . sqlFormDefinitionUtil == null ? null : this . sqlFormDefinitionUtil . getFormDefinitionIdAndTitle ( ) . get ( formTypeId ) ) ; formRecordToSetInfoOn . setTitle ( resultSetForTblInfo . getString ( SQLFormUtil . SQLColumnIndex . _03_TITLE ) ) ; Date created = resultSetForTblInfo . getDate ( SQLFormUtil . SQLColumnIndex . _04_CREATED ) ; Date lastUpdated = resultSetForTblInfo . getDate ( SQLFormUtil . SQLColumnIndex . _05_LAST_UPDATED ) ; //Created... if ( created != null ) { formRecordToSetInfoOn . setDateCreated ( new Date ( created . getTime ( ) ) ) ; } //Last Updated... if ( lastUpdated != null ) { formRecordToSetInfoOn . setDateLastUpdated ( new Date ( lastUpdated . getTime ( ) ) ) ; } } } } tableField . setTableRecords ( formRecords ) ; returnVal = new Field ( formFieldMappingParam . name , tableField , Field . Type . Table ) ; //TODO __8__ encrypted field... break ; //Label... case UtilGlobal . FieldTypeId . _9_LABEL : returnVal = new Field ( formFieldMappingParam . name , formFieldMappingParam . description , Field . Type . Label ) ; break ; default : throw new SQLException ( \"Unable to map '\" + formContainerIdParam . intValue ( ) + \"', to Form Field value.\" ) ; } return returnVal ; } catch ( SQLException sqlError ) { throw new FluidSQLException ( sqlError ) ; } finally { this . closeStatement ( preparedStatement ) ; this . closeStatement ( preparedStatementForTblInfo ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps a { @code ResultSet } to a new instance of { @code FormFieldMapping } . [CODESPLIT] private FormFieldMapping mapFormFieldMapping ( ResultSet resultSetParam ) throws SQLException { return new FormFieldMapping ( resultSetParam . getLong ( 1 ) , resultSetParam . getLong ( 2 ) , resultSetParam . getLong ( 3 ) , resultSetParam . getString ( 4 ) , resultSetParam . getString ( 5 ) , resultSetParam . getString ( 6 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code Role } with the privileges inside the { @code roleParam } . [CODESPLIT] public Role createRole ( Role roleParam ) { if ( roleParam != null && this . serviceTicket != null ) { roleParam . setServiceTicket ( this . serviceTicket ) ; } return new Role ( this . putJson ( roleParam , WS . Path . Role . Version1 . roleCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing { @code Role } with the privileges inside the { @code roleParam } . [CODESPLIT] public Role updateRole ( Role roleParam ) { if ( roleParam != null && this . serviceTicket != null ) { roleParam . setServiceTicket ( this . serviceTicket ) ; } return new Role ( this . postJson ( roleParam , WS . Path . Role . Version1 . roleUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the { @code Role } provided . Id must be set on the { @code Role } . [CODESPLIT] public Role deleteRole ( Role roleToDeleteParam ) { if ( roleToDeleteParam != null && this . serviceTicket != null ) { roleToDeleteParam . setServiceTicket ( this . serviceTicket ) ; } return new Role ( this . postJson ( roleToDeleteParam , WS . Path . Role . Version1 . roleDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves role information for the provided { @code roleIdParam } . [CODESPLIT] public Role getRoleById ( Long roleIdParam ) { Role roleToGetInfoFor = new Role ( ) ; roleToGetInfoFor . setId ( roleIdParam ) ; if ( this . serviceTicket != null ) { roleToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new Role ( this . postJson ( roleToGetInfoFor , WS . Path . Role . Version1 . getById ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all role information . [CODESPLIT] public RoleListing getAllRoles ( ) { RoleListing roleToGetInfoFor = new RoleListing ( ) ; if ( this . serviceTicket != null ) { roleToGetInfoFor . setServiceTicket ( this . serviceTicket ) ; } try { return new RoleListing ( this . postJson ( roleToGetInfoFor , WS . Path . Role . Version1 . getAllRoles ( ) ) ) ; } // catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Attachment Path... if ( this . getAttachmentPath ( ) != null ) { returnVal . put ( JSONMapping . ATTACHMENT_PATH , this . getAttachmentPath ( ) ) ; } //Attachment Data Base64... if ( this . getAttachmentDataBase64 ( ) != null ) { returnVal . put ( JSONMapping . ATTACHMENT_DATA_BASE64 , this . getAttachmentDataBase64 ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the { @code commandParams } and returns the result . [CODESPLIT] public CommandResult executeCommand ( String ... commandParams ) throws IOException { if ( commandParams == null || commandParams . length == 0 ) { throw new IOException ( \"Unable to execute command. No commands provided.\" ) ; } List < String > returnedLines = new ArrayList ( ) ; Charset charset = Charset . forName ( ENCODING_UTF_8 ) ; try { Process process = null ; //One param... if ( commandParams . length == 1 ) { process = Runtime . getRuntime ( ) . exec ( commandParams [ 0 ] ) ; } //More params... else { process = Runtime . getRuntime ( ) . exec ( commandParams ) ; } BufferedReader reader = new BufferedReader ( new InputStreamReader ( process . getInputStream ( ) , charset ) ) ; String readLine = null ; while ( ( readLine = reader . readLine ( ) ) != null ) { returnedLines . add ( readLine ) ; } BufferedReader errorReader = new BufferedReader ( new InputStreamReader ( process . getErrorStream ( ) , charset ) ) ; while ( ( readLine = errorReader . readLine ( ) ) != null ) { returnedLines . add ( readLine ) ; } int exitValue = - 1000 ; try { exitValue = process . waitFor ( ) ; } catch ( InterruptedException e ) { String commandString = ( commandParams == null || commandParams . length == 0 ) ? \"<unknown>\" : commandParams [ 0 ] ; throw new IOException ( \"Unable to wait for command [\" + commandString + \"] to exit. \" + e . getMessage ( ) , e ) ; } String [ ] rtnArr = { } ; return new CommandResult ( exitValue , returnedLines . toArray ( rtnArr ) ) ; } catch ( IOException ioExeption ) { //IO Problem... String commandString = ( commandParams == null || commandParams . length == 0 ) ? \"<unknown>\" : commandParams [ 0 ] ; throw new IOException ( \"Unable to execute command/s [\" + commandString + \"]. \" + ioExeption . getMessage ( ) , ioExeption ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes the { @code objectCommandParam } and returns the result . [CODESPLIT] public CommandResult executeCommand ( String objectCommandParam ) throws Exception { if ( objectCommandParam == null ) { return new CommandResult ( 333 , new String [ ] { \"No Object Command provided. 'null' not allowed.\" } ) ; } return this . executeCommand ( new String [ ] { objectCommandParam } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Access Token... if ( this . getAccessToken ( ) != null ) { returnVal . put ( JSONMapping . ACCESS_TOKEN , this . getAccessToken ( ) ) ; } //Id Token... if ( this . getIdToken ( ) != null ) { returnVal . put ( JSONMapping . ID_TOKEN , this . getIdToken ( ) ) ; } //Token Type... if ( this . getTokenType ( ) != null ) { returnVal . put ( JSONMapping . TOKEN_TYPE , this . getTokenType ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Date... if ( this . getDate ( ) != null ) { returnVal . put ( JSONMapping . DATE , this . getDateAsLongFromJson ( this . getDate ( ) ) ) ; } //Date and Time Field Name... if ( this . getDateAndFieldName ( ) != null ) { returnVal . put ( JSONMapping . DATE_AND_FIELD_NAME , this . getDateAndFieldName ( ) ) ; } //Form Container Field Values JSON... if ( this . getFormContainerFieldValuesJSON ( ) != null ) { returnVal . put ( JSONMapping . FORM_CONTAINER_FIELD_VALUES_JSON , this . getFormContainerFieldValuesJSON ( ) ) ; } //Log Entry Type... if ( this . getLogEntryType ( ) != null ) { returnVal . put ( JSONMapping . LOG_ENTRY_TYPE , this . getLogEntryType ( ) ) ; } //Description... if ( this . getDescription ( ) != null ) { returnVal . put ( JSONMapping . DESCRIPTION , this . getDescription ( ) ) ; } //Historic Entry Type... if ( this . getHistoricEntryType ( ) != null ) { returnVal . put ( JSONMapping . HISTORIC_ENTRY_TYPE , this . getHistoricEntryType ( ) ) ; } //User... if ( this . getUser ( ) != null ) { returnVal . put ( JSONMapping . USER , this . getUser ( ) . toJsonObject ( ) ) ; } //Field... if ( this . getField ( ) != null ) { returnVal . put ( JSONMapping . FIELD , this . getField ( ) . toJsonObject ( ) ) ; } //Different from Previous... if ( this . getIsFieldDifferentFromPrevious ( ) != null ) { returnVal . put ( JSONMapping . IS_FIELD_DIFFERENT_FROM_PREVIOUS , this . getIsFieldDifferentFromPrevious ( ) ) ; } //Field type Signature... if ( this . getIsFieldTypeSignature ( ) != null ) { returnVal . put ( JSONMapping . IS_FIELD_TYPE_SIGNATURE , this . getIsFieldTypeSignature ( ) ) ; } //Escape Text... if ( this . getIsEscapeText ( ) != null ) { returnVal . put ( JSONMapping . IS_ESCAPE_TEXT , this . getIsEscapeText ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Can Create... if ( this . isCanCreate ( ) != null ) { returnVal . put ( JSONMapping . CAN_CREATE , this . isCanCreate ( ) . booleanValue ( ) ) ; } //Attachment can View... if ( this . isAttachmentsView ( ) != null ) { returnVal . put ( JSONMapping . ATTACHMENTS_VIEW , this . isAttachmentsView ( ) . booleanValue ( ) ) ; } //Attachment can Create or Modify... if ( this . isAttachmentsCreateUpdate ( ) != null ) { returnVal . put ( JSONMapping . ATTACHMENTS_CREATE_UPDATE , this . isAttachmentsCreateUpdate ( ) . booleanValue ( ) ) ; } //Form Definition... if ( this . getFormDefinition ( ) != null ) { returnVal . put ( JSONMapping . FORM_DEFINITION , this . getFormDefinition ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Object getFieldValueForField ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public String getFieldValueAsString ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public TableField getFieldValueAsTableField ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsTableField ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public MultiChoice getFieldValueAsMultiChoice ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsMultiChoice ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Date getFieldValueAsDate ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsDate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Boolean getFieldValueAsBoolean ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsBoolean ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Double getFieldValueAsDouble ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsDouble ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Integer getFieldValueAsInt ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsInteger ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Long getFieldValueAsLong ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsLong ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public Number getFieldValueAsNumber ( String fieldNameParam ) { Field fieldWithName = this . getField ( fieldNameParam ) ; return ( fieldWithName == null ) ? null : fieldWithName . getFieldValueAsNumber ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the value of the { @code fieldNameParam } requested . <p > If there is an existing value the value will be override with the value of { @code fieldValueParam } . [CODESPLIT] @ XmlTransient public void setFieldValue ( String fieldNameParam , Object fieldValueParam ) { if ( fieldNameParam == null || fieldNameParam . trim ( ) . length ( ) == 0 ) { return ; } if ( this . getFormFields ( ) == null || this . getFormFields ( ) . isEmpty ( ) ) { this . setFormFields ( new ArrayList ( ) ) ; } String fieldNameParamLower = fieldNameParam . toLowerCase ( ) ; for ( Iterator < Field > fieldIter = this . getFormFields ( ) . iterator ( ) ; fieldIter . hasNext ( ) ; ) { Field field = fieldIter . next ( ) ; if ( field . getFieldName ( ) == null || field . getFieldName ( ) . trim ( ) . length ( ) == 0 ) { continue ; } String fieldNameLower = field . getFieldName ( ) . toLowerCase ( ) ; if ( fieldNameParamLower . equals ( fieldNameLower ) ) { field . setFieldValue ( fieldValueParam ) ; return ; } } //When the Field is not added previously... this . getFormFields ( ) . add ( new Field ( fieldNameParam , fieldValueParam ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the value of the { @code fieldNameParam } requested . [CODESPLIT] @ XmlTransient public void setFieldValue ( String fieldNameParam , Object fieldValueParam , Field . Type typeParam ) { if ( fieldNameParam == null ) { return ; } if ( this . getFormFields ( ) == null || this . getFormFields ( ) . isEmpty ( ) ) { this . setFormFields ( new ArrayList ( ) ) ; } String paramLower = fieldNameParam . toLowerCase ( ) . trim ( ) ; boolean valueFound = false ; //Iterate the Form Fields... int fieldIndex = 0 ; for ( Iterator < Field > fieldIter = this . getFormFields ( ) . iterator ( ) ; fieldIter . hasNext ( ) ; fieldIndex ++ ) { Field field = fieldIter . next ( ) ; String toCheckNameLower = field . getFieldName ( ) ; if ( toCheckNameLower == null || toCheckNameLower . trim ( ) . isEmpty ( ) ) { continue ; } toCheckNameLower = toCheckNameLower . trim ( ) . toLowerCase ( ) ; if ( paramLower . equals ( toCheckNameLower ) ) { valueFound = true ; this . getFormFields ( ) . get ( fieldIndex ) . setFieldValue ( fieldValueParam ) ; this . getFormFields ( ) . get ( fieldIndex ) . setTypeAsEnum ( typeParam ) ; break ; } } //Add the value if it wasn't found by name... if ( ! valueFound ) { this . getFormFields ( ) . add ( new Field ( fieldNameParam , fieldValueParam , typeParam ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Determine whether the current { @code Form } Type / Definition is of type { @code formTypeParam } [CODESPLIT] @ XmlTransient public boolean isFormType ( String formTypeParam ) { if ( ( formTypeParam == null || formTypeParam . trim ( ) . isEmpty ( ) ) || ( this . getFormType ( ) == null || this . getFormType ( ) . trim ( ) . isEmpty ( ) ) ) { return false ; } return formTypeParam . toLowerCase ( ) . equals ( getFormType ( ) . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Form Type... if ( this . getFormType ( ) != null ) { returnVal . put ( JSONMapping . FORM_TYPE , this . getFormType ( ) ) ; } //Form Type Id... if ( this . getFormTypeId ( ) != null ) { returnVal . put ( JSONMapping . FORM_TYPE_ID , this . getFormTypeId ( ) ) ; } //Title... if ( this . getTitle ( ) != null ) { returnVal . put ( JSONMapping . TITLE , this . getTitle ( ) ) ; } //Form Description... if ( this . getFormDescription ( ) != null ) { returnVal . put ( JSONMapping . FORM_DESCRIPTION , this . getFormDescription ( ) ) ; } //Ancestor Label... if ( this . getAncestorLabel ( ) != null ) { returnVal . put ( JSONMapping . ANCESTOR_LABEL , this . getAncestorLabel ( ) ) ; } //Descendant Label... if ( this . getDescendantsLabel ( ) != null ) { returnVal . put ( JSONMapping . DESCENDANTS_LABEL , this . getDescendantsLabel ( ) ) ; } //Number Inputs... if ( this . getNumberInputs ( ) != null ) { returnVal . put ( JSONMapping . NUMBER_INPUTS , this . getNumberInputs ( ) ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( JSONMapping . DATE_LAST_UPDATED , this . getDateAsLongFromJson ( this . getDateLastUpdated ( ) ) ) ; } //Current User... if ( this . getCurrentUser ( ) != null ) { returnVal . put ( JSONMapping . CURRENT_USER , this . getCurrentUser ( ) . toJsonObject ( ) ) ; } //State... if ( this . getState ( ) != null ) { returnVal . put ( JSONMapping . STATE , this . getState ( ) ) ; } //Flow State... if ( this . getFlowState ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STATE , this . getFlowState ( ) ) ; } //Form Fields... if ( this . getFormFields ( ) != null && ! this . getFormFields ( ) . isEmpty ( ) ) { JSONArray formFieldsArr = new JSONArray ( ) ; for ( Field toAdd : this . getFormFields ( ) ) { formFieldsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . FORM_FIELDS , formFieldsArr ) ; } //Associated Flows... if ( this . getAssociatedFlows ( ) != null && ! this . getAssociatedFlows ( ) . isEmpty ( ) ) { JSONArray assoJobsArr = new JSONArray ( ) ; for ( Flow toAdd : this . getAssociatedFlows ( ) ) { assoJobsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ASSOCIATED_FLOWS , assoJobsArr ) ; } //Ancestor... Long ancestorIdLcl = this . getAncestorId ( ) ; if ( ancestorIdLcl != null ) { returnVal . put ( JSONMapping . ANCESTOR_ID , ancestorIdLcl ) ; } //Table Field Parent Id... if ( this . getTableFieldParentId ( ) != null ) { returnVal . put ( JSONMapping . TABLE_FIELD_PARENT_ID , this . getTableFieldParentId ( ) ) ; } //Descendant Ids... if ( this . getDescendantIds ( ) != null && ! this . getDescendantIds ( ) . isEmpty ( ) ) { JSONArray array = new JSONArray ( ) ; for ( Long formId : this . getDescendantIds ( ) ) { array . put ( formId ) ; } returnVal . put ( JSONMapping . DESCENDANT_IDS , array ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the mapping object required by Elastic Search when making use of enhanced data - types . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonMappingForElasticSearch ( ) throws JSONException { JSONObject returnVal = new JSONObject ( ) ; //Id... { JSONObject idJsonObj = new JSONObject ( ) ; idJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . LONG ) ; returnVal . put ( ABaseFluidJSONObject . JSONMapping . ID , idJsonObj ) ; } //Form Type... { JSONObject formTypeJsonObj = new JSONObject ( ) ; formTypeJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . KEYWORD ) ; returnVal . put ( JSONMapping . FORM_TYPE , formTypeJsonObj ) ; } //Form Type Id... { JSONObject formTypeIdJsonObj = new JSONObject ( ) ; formTypeIdJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . LONG ) ; returnVal . put ( JSONMapping . FORM_TYPE_ID , formTypeIdJsonObj ) ; } //Title... { JSONObject titleJsonObj = new JSONObject ( ) ; titleJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . TEXT ) ; returnVal . put ( JSONMapping . TITLE , titleJsonObj ) ; } //Form Description... { JSONObject formDescJsonObj = new JSONObject ( ) ; formDescJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . KEYWORD ) ; returnVal . put ( JSONMapping . FORM_DESCRIPTION , formDescJsonObj ) ; } //State... { JSONObject stateJsonObj = new JSONObject ( ) ; stateJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . KEYWORD ) ; returnVal . put ( JSONMapping . STATE , stateJsonObj ) ; } //Flow State... { JSONObject flowStateJsonObj = new JSONObject ( ) ; flowStateJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . KEYWORD ) ; returnVal . put ( JSONMapping . FLOW_STATE , flowStateJsonObj ) ; } //Current User... { JSONObject currentUserJsonObj = new JSONObject ( ) ; currentUserJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . OBJECT ) ; JSONObject properties = new JSONObject ( ) ; //Current User Id... JSONObject currentUserUserIdJsonObj = new JSONObject ( ) ; currentUserUserIdJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . LONG ) ; properties . put ( User . JSONMapping . Elastic . USER_ID , currentUserUserIdJsonObj ) ; //Current User Id... JSONObject currentUserUsernameJsonObj = new JSONObject ( ) ; currentUserUsernameJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . KEYWORD ) ; properties . put ( User . JSONMapping . USERNAME , currentUserUsernameJsonObj ) ; currentUserJsonObj . put ( ABaseFluidJSONObject . JSONMapping . Elastic . PROPERTIES , properties ) ; returnVal . put ( JSONMapping . CURRENT_USER , currentUserJsonObj ) ; } //Date Created... { JSONObject dateCreatedJsonObj = new JSONObject ( ) ; dateCreatedJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . DATE ) ; returnVal . put ( JSONMapping . DATE_CREATED , dateCreatedJsonObj ) ; } //Date Last Updated... { JSONObject dateLastUpdatedJsonObj = new JSONObject ( ) ; dateLastUpdatedJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . DATE ) ; returnVal . put ( JSONMapping . DATE_LAST_UPDATED , dateLastUpdatedJsonObj ) ; } //Get the listing of form fields... if ( this . getFormFields ( ) != null && ! this . getFormFields ( ) . isEmpty ( ) ) { for ( Field toAdd : this . getFormFields ( ) ) { JSONObject convertedField = toAdd . toJsonMappingForElasticSearch ( ) ; if ( convertedField == null ) { continue ; } String fieldNameAsCamel = toAdd . getFieldNameAsUpperCamel ( ) ; returnVal . put ( fieldNameAsCamel , convertedField ) ; } } //Ancestor Obj... { JSONObject ancestorJsonObj = new JSONObject ( ) ; ancestorJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . LONG ) ; returnVal . put ( JSONMapping . ANCESTOR_ID , ancestorJsonObj ) ; } //Table field parent id... { JSONObject tblFieldParentIdJsonObj = new JSONObject ( ) ; tblFieldParentIdJsonObj . put ( Field . JSONMapping . Elastic . MAPPING_ONLY_TYPE , Field . ElasticSearchType . LONG ) ; returnVal . put ( JSONMapping . TABLE_FIELD_PARENT_ID , tblFieldParentIdJsonObj ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } for storage in ElasticCache for { @code Form } . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonForElasticSearch ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Form Type... if ( this . getFormType ( ) != null ) { returnVal . put ( JSONMapping . FORM_TYPE , this . getFormType ( ) ) ; } //Form Type Id... if ( this . getFormTypeId ( ) != null ) { returnVal . put ( JSONMapping . FORM_TYPE_ID , this . getFormTypeId ( ) ) ; } //Title... if ( this . getTitle ( ) != null ) { returnVal . put ( JSONMapping . TITLE , this . getTitle ( ) ) ; } //Form Description... if ( this . getFormDescription ( ) != null ) { returnVal . put ( JSONMapping . FORM_DESCRIPTION , this . getFormDescription ( ) ) ; } //State... if ( this . getState ( ) != null ) { returnVal . put ( JSONMapping . STATE , this . getState ( ) ) ; } //Flow State... if ( this . getFlowState ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STATE , this . getFlowState ( ) ) ; } //Current User... JSONObject currentUserJsonObj = new JSONObject ( ) ; if ( this . getCurrentUser ( ) == null ) { currentUserJsonObj . put ( User . JSONMapping . Elastic . USER_ID , JSONObject . NULL ) ; currentUserJsonObj . put ( User . JSONMapping . USERNAME , JSONObject . NULL ) ; } else { //Id... if ( this . getCurrentUser ( ) . getId ( ) == null || this . getCurrentUser ( ) . getId ( ) . longValue ( ) < 1 ) { currentUserJsonObj . put ( User . JSONMapping . Elastic . USER_ID , JSONObject . NULL ) ; } else { currentUserJsonObj . put ( User . JSONMapping . Elastic . USER_ID , this . getCurrentUser ( ) . getId ( ) ) ; } //Username... if ( this . getCurrentUser ( ) . getUsername ( ) == null || this . getCurrentUser ( ) . getUsername ( ) . trim ( ) . isEmpty ( ) ) { currentUserJsonObj . put ( User . JSONMapping . USERNAME , JSONObject . NULL ) ; } else { currentUserJsonObj . put ( User . JSONMapping . USERNAME , this . getCurrentUser ( ) . getUsername ( ) ) ; } } returnVal . put ( JSONMapping . CURRENT_USER , currentUserJsonObj ) ; //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( JSONMapping . DATE_LAST_UPDATED , this . getDateAsLongFromJson ( this . getDateLastUpdated ( ) ) ) ; } //Form Fields... if ( this . getFormFields ( ) != null && ! this . getFormFields ( ) . isEmpty ( ) ) { for ( Field toAdd : this . getFormFields ( ) ) { JSONObject convertedFieldObj = toAdd . toJsonForElasticSearch ( ) ; if ( convertedFieldObj == null ) { continue ; } Iterator < String > iterKeys = convertedFieldObj . keys ( ) ; while ( iterKeys . hasNext ( ) ) { String key = iterKeys . next ( ) ; returnVal . put ( key , convertedFieldObj . get ( key ) ) ; } } } //Ancestor... Long ancestorIdLcl = this . getAncestorId ( ) ; if ( ancestorIdLcl != null ) { returnVal . put ( JSONMapping . ANCESTOR_ID , ancestorIdLcl ) ; } //Table Field Parent Id... if ( this . getTableFieldParentId ( ) != null ) { returnVal . put ( JSONMapping . TABLE_FIELD_PARENT_ID , this . getTableFieldParentId ( ) ) ; } //Descendant Ids... if ( this . getDescendantIds ( ) != null && ! this . getDescendantIds ( ) . isEmpty ( ) ) { JSONArray array = new JSONArray ( ) ; for ( Long formId : this . getDescendantIds ( ) ) { array . put ( formId ) ; } returnVal . put ( JSONMapping . DESCENDANT_IDS , array ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize { @code this } object into a JSONObject . [CODESPLIT] @ XmlTransient public JSONObject convertToFlatJSONObject ( ) { JSONObject returnVal = new JSONObject ( ) ; //Id... returnVal . put ( FlatFormJSONMapping . FORM_ID , this . getId ( ) == null ? JSONObject . NULL : this . getId ( ) ) ; //Title... returnVal . put ( FlatFormJSONMapping . FORM_TITLE , this . getTitle ( ) == null ? JSONObject . NULL : this . getTitle ( ) ) ; //Form Type... returnVal . put ( FlatFormJSONMapping . FORM_TYPE , this . getFormType ( ) == null ? JSONObject . NULL : this . getFormType ( ) ) ; //State... returnVal . put ( FlatFormJSONMapping . FORM_STATE , this . getState ( ) == null ? JSONObject . NULL : this . getState ( ) ) ; //Form Flow State... returnVal . put ( FlatFormJSONMapping . FORM_FLOW_STATE , this . getFlowState ( ) == null ? JSONObject . NULL : this . getFlowState ( ) ) ; //Date Created... returnVal . put ( FlatFormJSONMapping . FORM_DATE_CREATED , ( this . getDateCreated ( ) == null ) ? JSONObject . NULL : this . getDateCreated ( ) . getTime ( ) ) ; //Date Last Updated... returnVal . put ( FlatFormJSONMapping . FORM_DATE_LAST_UPDATED , ( this . getDateLastUpdated ( ) == null ) ? JSONObject . NULL : this . getDateLastUpdated ( ) . getTime ( ) ) ; //Form Fields... if ( this . getFormFields ( ) == null || this . getFormFields ( ) . isEmpty ( ) ) { return returnVal ; } //Set the form fields... UtilGlobal utilGlobal = new UtilGlobal ( ) ; this . getFormFields ( ) . forEach ( ( formFieldItem ) - > { utilGlobal . setFlatFieldOnJSONObj ( FlatFormJSONMapping . FORM_FIELD_PREFIX , FlatFormJSONMapping . FORM_FIELD_ID_PREFIX , formFieldItem , returnVal )  ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Mail Template... if ( this . getMailTemplate ( ) != null ) { returnVal . put ( JSONMapping . MAIL_TEMPLATE , this . getMailTemplate ( ) ) ; } //Mail SMTP Server... if ( this . getMailSMTPServer ( ) != null ) { returnVal . put ( JSONMapping . MAIL_SMTP_SERVER , this . getMailSMTPServer ( ) ) ; } //Recipients... if ( this . getRecipients ( ) != null && this . getRecipients ( ) . length > 0 ) { JSONArray jsonArray = new JSONArray ( ) ; for ( String item : this . getRecipients ( ) ) { jsonArray . put ( item ) ; } returnVal . put ( JSONMapping . RECIPIENTS , jsonArray ) ; } //Attachments... if ( this . getAttachments ( ) != null && ! this . getAttachments ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( MailMessageAttachment item : this . getAttachments ( ) ) { jsonArray . put ( item . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . ATTACHMENTS , jsonArray ) ; } //Name Values... if ( this . getNameValues ( ) != null && ! this . getNameValues ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; for ( MailMessageNameValue item : this . getNameValues ( ) ) { jsonArray . put ( item . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . NAME_VALUES , jsonArray ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = new JSONObject ( ) ; returnVal . put ( JSONMapping . CLIENT , this . getPrincipalClient ( ) ) ; returnVal . put ( JSONMapping . SESSION_KEY , this . getSessionKeyBase64 ( ) ) ; returnVal . put ( JSONMapping . TICKET_EXPIRES , this . getTicketExpires ( ) ) ; returnVal . put ( JSONMapping . AUTHORISED_USERNAME , this . getAuthorisedUsername ( ) ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends the { @code formToSendToFlowParam } to a { @code Flow } in Fluid . The return value is the { @code FluidItem } created as a result . [CODESPLIT] public FluidItem sendToFlowSynchronized ( Form formToSendToFlowParam , String destinationFlowParam ) { if ( formToSendToFlowParam == null ) { return null ; } if ( destinationFlowParam == null || destinationFlowParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"No destination Flow provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } FluidItem itemToSend = new FluidItem ( ) ; itemToSend . setFlow ( destinationFlowParam ) ; itemToSend . setForm ( formToSendToFlowParam ) ; //Send all the messages... itemToSend . setEcho ( UUID . randomUUID ( ) . toString ( ) ) ; //Start a new request... String uniqueReqId = this . initNewRequest ( ) ; //Send the actual message... this . sendMessage ( itemToSend , uniqueReqId ) ; try { List < FluidItem > returnValue = this . getHandler ( uniqueReqId ) . getCF ( ) . get ( this . getTimeoutInMillis ( ) , TimeUnit . MILLISECONDS ) ; //Connection was closed.. this is a problem.... if ( this . getHandler ( uniqueReqId ) . isConnectionClosed ( ) ) { throw new FluidClientException ( \"WebSocket-SendToFlow: \" + \"The connection was closed by the server prior to the response received.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } if ( returnValue == null || returnValue . isEmpty ( ) ) { return null ; } return returnValue . get ( 0 ) ; } //Interrupted... catch ( InterruptedException exceptParam ) { throw new FluidClientException ( \"WebSocket-Interrupted-SendToFlow: \" + exceptParam . getMessage ( ) , exceptParam , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } //Error on the web-socket... catch ( ExecutionException executeProblem ) { Throwable cause = executeProblem . getCause ( ) ; //Fluid client exception... if ( cause instanceof FluidClientException ) { throw ( FluidClientException ) cause ; } else { throw new FluidClientException ( \"WebSocket-SendToFlow: \" + cause . getMessage ( ) , cause , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } } //Timeout... catch ( TimeoutException eParam ) { throw new FluidClientException ( \"WebSocket-SendToFlow: Timeout while waiting for all return data. There were '\" + this . getHandler ( uniqueReqId ) . getReturnValue ( ) . size ( ) + \"' items after a Timeout of \" + ( TimeUnit . MILLISECONDS . toSeconds ( this . getTimeoutInMillis ( ) ) ) + \" seconds.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } finally { this . removeHandler ( uniqueReqId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the Service Ticket associated with the Fluid session as HEX . [CODESPLIT] public String getServiceTicketAsHexUpper ( ) { String serviceTicket = this . getServiceTicket ( ) ; if ( serviceTicket == null ) { return null ; } if ( serviceTicket . isEmpty ( ) ) { return serviceTicket ; } byte [ ] base64Bytes = Base64 . getDecoder ( ) . decode ( serviceTicket ) ; return this . bytesToHex ( base64Bytes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the byte [] to a HEX string as upper case . [CODESPLIT] private String bytesToHex ( byte [ ] bytesToConvert ) { if ( bytesToConvert == null ) { return null ; } if ( bytesToConvert . length == 0 ) { return UtilGlobal . EMPTY ; } char [ ] hexChars = new char [ bytesToConvert . length * 2 ] ; for ( int index = 0 ; index < bytesToConvert . length ; index ++ ) { int andWith127 = ( bytesToConvert [ index ] & 0xFF ) ; hexChars [ index * 2 ] = HEX_ARRAY [ andWith127 >>> 4 ] ; hexChars [ index * 2 + 1 ] = HEX_ARRAY [ andWith127 & 0x0F ] ; } return new String ( hexChars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //User Query... if ( this . getUserQuery ( ) != null ) { returnVal . put ( JSONMapping . USER_QUERY , this . getUserQuery ( ) . toJsonObject ( ) ) ; } //Role... if ( this . getRole ( ) != null ) { returnVal . put ( JSONMapping . ROLE , this . getRole ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Text Masked field . [CODESPLIT] public Field createFieldTextMasked ( Field formFieldParam , String maskValueParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( maskValueParam == null || maskValueParam . trim ( ) . isEmpty ( ) ) { maskValueParam = \"\" ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Text ) ; formFieldParam . setTypeMetaData ( FieldMetaData . Text . MASKED . concat ( maskValueParam ) ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Text Barcode field . [CODESPLIT] public Field createFieldTextBarcode ( Field formFieldParam , String barcodeTypeParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( barcodeTypeParam == null || barcodeTypeParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Barcode type cannot be empty.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Text ) ; formFieldParam . setTypeMetaData ( FieldMetaData . Text . BARCODE . concat ( barcodeTypeParam ) ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Multi Choice field . [CODESPLIT] public Field createFieldMultiChoicePlain ( Field formFieldParam , List < String > multiChoiceValuesParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( multiChoiceValuesParam == null ) { multiChoiceValuesParam = new ArrayList ( ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . MultipleChoice ) ; formFieldParam . setTypeMetaData ( FieldMetaData . MultiChoice . PLAIN ) ; formFieldParam . setFieldValue ( new MultiChoice ( multiChoiceValuesParam ) ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Decimal Spinner field . [CODESPLIT] public Field createFieldDecimalSpinner ( Field formFieldParam , double minParam , double maxParam , double stepFactorParam , String prefixParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; formFieldParam . setTypeMetaData ( this . getMetaDataForDecimalAs ( FieldMetaData . Decimal . SPINNER , minParam , maxParam , stepFactorParam , prefixParam ) ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Decimal Slider field . [CODESPLIT] public Field createFieldDecimalSlider ( Field formFieldParam , double minParam , double maxParam , double stepFactorParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; formFieldParam . setTypeMetaData ( this . getMetaDataForDecimalAs ( FieldMetaData . Decimal . SLIDER , minParam , maxParam , stepFactorParam , null ) ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Table Field . [CODESPLIT] public Field createFieldTable ( Field formFieldParam , Form formDefinitionParam , boolean sumDecimalsParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Table ) ; formFieldParam . setTypeMetaData ( this . getMetaDataForTableField ( formDefinitionParam , sumDecimalsParam ) ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Masked Text field . [CODESPLIT] public Field updateFieldTextMasked ( Field formFieldParam , String maskValueParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( maskValueParam == null || maskValueParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Masked value cannot be empty.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Text ) ; formFieldParam . setTypeMetaData ( FieldMetaData . Text . MASKED . concat ( maskValueParam ) ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Barcode Text field . [CODESPLIT] public Field updateFieldTextBarcode ( Field formFieldParam , String barcodeTypeParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( barcodeTypeParam == null || barcodeTypeParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Barcode type cannot be empty.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Text ) ; formFieldParam . setTypeMetaData ( FieldMetaData . Text . BARCODE . concat ( barcodeTypeParam ) ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Paragraph Text field . [CODESPLIT] public Field updateFieldParagraphTextPlain ( Field formFieldParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; formFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . PLAIN ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Multi Choice field . [CODESPLIT] public Field updateFieldMultiChoicePlain ( Field formFieldParam , List < String > multiChoiceValuesParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( multiChoiceValuesParam == null || multiChoiceValuesParam . isEmpty ( ) ) { throw new FluidClientException ( \"No Multi-choice values provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } List < String > beforeAvail = null , beforeSelected = null ; if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . MultipleChoice ) ; formFieldParam . setTypeMetaData ( FieldMetaData . MultiChoice . PLAIN ) ; if ( formFieldParam . getFieldValue ( ) instanceof MultiChoice ) { MultiChoice casted = ( MultiChoice ) formFieldParam . getFieldValue ( ) ; beforeAvail = casted . getAvailableMultiChoices ( ) ; beforeSelected = casted . getSelectedMultiChoices ( ) ; } formFieldParam . setFieldValue ( new MultiChoice ( multiChoiceValuesParam ) ) ; } Field returnVal = new Field ( this . postJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldUpdate ( ) ) ) ; if ( formFieldParam != null ) { formFieldParam . setFieldValue ( new MultiChoice ( beforeSelected , beforeAvail ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the Decimal Spinner field . [CODESPLIT] public Field updateFieldDecimalSpinner ( Field formFieldParam , double minParam , double maxParam , double stepFactorParam , String prefixParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; formFieldParam . setTypeMetaData ( this . getMetaDataForDecimalAs ( FieldMetaData . Decimal . SPINNER , minParam , maxParam , stepFactorParam , prefixParam ) ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the Decimal Slider field . [CODESPLIT] public Field updateFieldDecimalSlider ( Field formFieldParam , double minParam , double maxParam , double stepFactorParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; formFieldParam . setTypeMetaData ( this . getMetaDataForDecimalAs ( FieldMetaData . Decimal . SLIDER , minParam , maxParam , stepFactorParam , null ) ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates a Table Field . [CODESPLIT] public Field updateFieldTable ( Field formFieldParam , Form formDefinitionParam , boolean sumDecimalsParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Table ) ; formFieldParam . setTypeMetaData ( this . getMetaDataForTableField ( formDefinitionParam , sumDecimalsParam ) ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . FormField . Version1 . formFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve a Form Field via name . [CODESPLIT] public Field getFieldByName ( String fieldNameParam ) { Field field = new Field ( ) ; field . setFieldName ( fieldNameParam ) ; if ( this . serviceTicket != null ) { field . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( field , WS . Path . FormField . Version1 . getByName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the Form Fields via Form Definition name . [CODESPLIT] public FormFieldListing getFieldsByFormNameAndLoggedInUser ( String formNameParam , boolean editOnlyFieldsParam ) { Form form = new Form ( ) ; form . setFormType ( formNameParam ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } return new FormFieldListing ( this . postJson ( form , WS . Path . FormField . Version1 . getByFormDefinitionAndLoggedInUser ( editOnlyFieldsParam ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the Form Fields via Form Definition id . [CODESPLIT] public FormFieldListing getFieldsByFormTypeIdAndLoggedInUser ( Long formTypeIdParam , boolean editOnlyFieldsParam ) { Form form = new Form ( ) ; form . setFormTypeId ( formTypeIdParam ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } return new FormFieldListing ( this . postJson ( form , WS . Path . FormField . Version1 . getByFormDefinitionAndLoggedInUser ( editOnlyFieldsParam ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the provided field . [CODESPLIT] public Field deleteField ( Field fieldParam ) { if ( fieldParam != null && this . serviceTicket != null ) { fieldParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( fieldParam , WS . Path . FormField . Version1 . formFieldDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forcefully deletes the provided field . [CODESPLIT] public Field forceDeleteField ( Field fieldParam ) { if ( fieldParam != null && this . serviceTicket != null ) { fieldParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( fieldParam , WS . Path . FormField . Version1 . formFieldDelete ( true ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the Meta Data for a table field . [CODESPLIT] private String getMetaDataForTableField ( Form formDefinitionParam , boolean sumDecimalsParam ) { StringBuilder returnBuffer = new StringBuilder ( ) ; Long definitionId = ( formDefinitionParam == null ) ? - 1L : formDefinitionParam . getId ( ) ; //Min... returnBuffer . append ( definitionId ) ; returnBuffer . append ( FieldMetaData . TableField . UNDERSCORE ) ; returnBuffer . append ( FieldMetaData . TableField . SUM_DECIMALS ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_OPEN ) ; returnBuffer . append ( sumDecimalsParam ) ; returnBuffer . append ( FieldMetaData . Decimal . SQ_CLOSE ) ; return returnBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = new JSONObject ( ) ; returnVal . put ( JSONMapping . TICKET_EXPIRES , this . getTicketExpires ( ) ) ; returnVal . put ( JSONMapping . ROLE_LISTING , this . getRoleListing ( ) ) ; returnVal . put ( JSONMapping . SESSION_KEY , this . getSessionKeyBase64 ( ) ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new True False field . [CODESPLIT] public Field createFieldTrueFalse ( Field formFieldParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . TrueFalse ) ; formFieldParam . setTypeMetaData ( FieldMetaData . TrueFalse . TRUE_FALSE ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . UserField . Version1 . userFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Date and time field . [CODESPLIT] public Field createFieldDateTimeDateAndTime ( Field formFieldParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; formFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE_AND_TIME ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . UserField . Version1 . userFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Decimal field . [CODESPLIT] public Field createFieldDecimalPlain ( Field formFieldParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; formFieldParam . setTypeMetaData ( FieldMetaData . Decimal . PLAIN ) ; } return new Field ( this . putJson ( formFieldParam , WS . Path . UserField . Version1 . userFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing True False field . [CODESPLIT] public Field updateFieldTrueFalse ( Field formFieldParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . TrueFalse ) ; formFieldParam . setTypeMetaData ( FieldMetaData . TrueFalse . TRUE_FALSE ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . UserField . Version1 . userFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Multi Choice field . [CODESPLIT] public Field updateFieldMultiChoicePlain ( Field formFieldParam , List < String > multiChoiceValuesParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( multiChoiceValuesParam == null || multiChoiceValuesParam . isEmpty ( ) ) { throw new FluidClientException ( \"No Multi-choice values provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . MultipleChoice ) ; formFieldParam . setTypeMetaData ( FieldMetaData . MultiChoice . PLAIN ) ; formFieldParam . setFieldValue ( new MultiChoice ( multiChoiceValuesParam ) ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . UserField . Version1 . userFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Date field . [CODESPLIT] public Field updateFieldDateTimeDate ( Field formFieldParam ) { if ( formFieldParam != null && this . serviceTicket != null ) { formFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( formFieldParam != null ) { formFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; formFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE ) ; } return new Field ( this . postJson ( formFieldParam , WS . Path . UserField . Version1 . userFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing User field value . [CODESPLIT] public Field updateFieldValue ( Field userFieldValueParam ) { if ( userFieldValueParam != null && this . serviceTicket != null ) { userFieldValueParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( userFieldValueParam , WS . Path . UserField . Version1 . userFieldUpdateValue ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves field information by { @code fieldIdParam } . [CODESPLIT] public Field getFieldByName ( String fieldNameParam ) { Field field = new Field ( ) ; field . setFieldName ( fieldNameParam ) ; //Set for Payara server... field . setFieldValue ( new MultiChoice ( ) ) ; if ( this . serviceTicket != null ) { field . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( field , WS . Path . UserField . Version1 . getByName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes a field from Fluid . [CODESPLIT] public Field deleteField ( Field fieldParam ) { if ( fieldParam != null && this . serviceTicket != null ) { fieldParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( fieldParam , WS . Path . UserField . Version1 . userFieldDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forcefully Deletes a field from Fluid . [CODESPLIT] public Field forceDeleteField ( Field fieldParam ) { if ( fieldParam != null && this . serviceTicket != null ) { fieldParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( fieldParam , WS . Path . UserField . Version1 . userFieldDelete ( true ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates / Updates the index { @code indexParam } with mappings provided in { @code fluidFormMappingToUpdateParam } . [CODESPLIT] public void mergeMappingForIndex ( String indexParam , String parentTypeParam , Form fluidFormMappingToUpdateParam ) { if ( indexParam == null ) { throw new FluidElasticSearchException ( \"Index name '\" + indexParam + \"' is invalid.\" ) ; } //The Form mapping to update... if ( fluidFormMappingToUpdateParam == null ) { throw new FluidElasticSearchException ( \"Form for mapping not set.\" ) ; } //Form Type Id... if ( fluidFormMappingToUpdateParam . getFormTypeId ( ) == null || fluidFormMappingToUpdateParam . getFormTypeId ( ) . longValue ( ) < 1 ) { throw new FluidElasticSearchException ( \"Form 'FormType' not set for mapping.\" ) ; } String formTypeString = fluidFormMappingToUpdateParam . getFormTypeId ( ) . toString ( ) ; JSONObject newContentMappingBuilderFromParam = fluidFormMappingToUpdateParam . toJsonMappingForElasticSearch ( ) ; //Retrieve and update... GetIndexResponse getExistingIndex = this . getOrCreateIndex ( indexParam ) ; JSONObject existingPropsToUpdate = null ; for ( ObjectCursor mappingKey : getExistingIndex . getMappings ( ) . keys ( ) ) { //Found index... if ( ! mappingKey . value . toString ( ) . equals ( indexParam ) ) { continue ; } //Found a match... Object obj = getExistingIndex . getMappings ( ) . get ( mappingKey . value . toString ( ) ) ; if ( obj instanceof ImmutableOpenMap ) { ImmutableOpenMap casted = ( ImmutableOpenMap ) obj ; //Type... if ( casted . containsKey ( formTypeString ) && casted . get ( formTypeString ) instanceof MappingMetaData ) { MappingMetaData mappingMetaData = ( MappingMetaData ) casted . get ( formTypeString ) ; try { existingPropsToUpdate = new JSONObject ( mappingMetaData . source ( ) . string ( ) ) ; break ; } catch ( IOException eParam ) { throw new FluidElasticSearchException ( \"Unable to retrieve source from 'Mapping Meta-Data'. \" + eParam . getMessage ( ) , eParam ) ; } } } } //No mapping for the type create a new one... if ( existingPropsToUpdate == null ) { existingPropsToUpdate = new JSONObject ( ) ; existingPropsToUpdate . put ( ABaseFluidJSONObject . JSONMapping . Elastic . PROPERTIES , newContentMappingBuilderFromParam ) ; //Set the additional properties... this . setAdditionalProps ( existingPropsToUpdate , parentTypeParam ) ; PutMappingRequestBuilder putMappingRequestBuilder = this . client . admin ( ) . indices ( ) . preparePutMapping ( indexParam ) ; putMappingRequestBuilder = putMappingRequestBuilder . setType ( formTypeString ) ; putMappingRequestBuilder = putMappingRequestBuilder . setSource ( existingPropsToUpdate . toString ( ) , XContentType . JSON ) ; PutMappingResponse putMappingResponse = putMappingRequestBuilder . get ( ) ; if ( ! putMappingResponse . isAcknowledged ( ) ) { throw new FluidElasticSearchException ( \"Index Update for Creating '\" + indexParam + \"' and type '\" + formTypeString + \"' not acknowledged by ElasticSearch.\" ) ; } //Creation done. return ; } //Update the existing index... JSONObject existingPropertiesUpdated = existingPropsToUpdate . getJSONObject ( formTypeString ) . getJSONObject ( ABaseFluidJSONObject . JSONMapping . Elastic . PROPERTIES ) ; //Merge existing with new... for ( String existingKey : existingPropertiesUpdated . keySet ( ) ) { newContentMappingBuilderFromParam . put ( existingKey , existingPropertiesUpdated . get ( existingKey ) ) ; } //Check to see whether there are any new fields added... boolean noChanges = true ; for ( String possibleExistingKey : newContentMappingBuilderFromParam . keySet ( ) ) { if ( ! existingPropertiesUpdated . has ( possibleExistingKey ) ) { noChanges = false ; break ; } } if ( noChanges ) { return ; } //Update the properties to new values... existingPropsToUpdate . put ( ABaseFluidJSONObject . JSONMapping . Elastic . PROPERTIES , newContentMappingBuilderFromParam ) ; //Set the additional properties... this . setAdditionalProps ( existingPropsToUpdate , parentTypeParam ) ; //Push the change... PutMappingRequestBuilder putMappingRequestBuilder = this . client . admin ( ) . indices ( ) . preparePutMapping ( indexParam ) ; putMappingRequestBuilder = putMappingRequestBuilder . setType ( formTypeString ) ; putMappingRequestBuilder = putMappingRequestBuilder . setSource ( existingPropsToUpdate . toString ( ) , XContentType . JSON ) ; PutMappingResponse putMappingResponse = putMappingRequestBuilder . get ( ) ; if ( ! putMappingResponse . isAcknowledged ( ) ) { throw new FluidElasticSearchException ( \"Index Update for '\" + indexParam + \"' and type '\" + formTypeString + \"' not acknowledged by ElasticSearch.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the additional properties on the { @code existingPropsToUpdateParam } json object . [CODESPLIT] private void setAdditionalProps ( JSONObject existingPropsToUpdateParam , String parentTypeParam ) { if ( parentTypeParam == null || parentTypeParam . trim ( ) . length ( ) == 0 ) { return ; } JSONObject typeJson = new JSONObject ( ) ; typeJson . put ( Field . JSONMapping . FIELD_TYPE , parentTypeParam ) ; existingPropsToUpdateParam . put ( Form . JSONMapping . _PARENT , typeJson ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new index or fetches existing index . [CODESPLIT] public GetIndexResponse getOrCreateIndex ( String indexParam ) { if ( this . doesIndexExist ( indexParam ) ) { return this . client . admin ( ) . indices ( ) . prepareGetIndex ( ) . get ( ) ; } else { CreateIndexRequestBuilder createIndexRequestBuilder = this . client . admin ( ) . indices ( ) . prepareCreate ( indexParam ) ; CreateIndexResponse mappingCreateResponse = createIndexRequestBuilder . execute ( ) . actionGet ( ) ; if ( ! mappingCreateResponse . isAcknowledged ( ) ) { throw new FluidElasticSearchException ( \"Index Creation for '\" + indexParam + \"' not acknowledged by ElasticSearch.\" ) ; } return this . client . admin ( ) . indices ( ) . prepareGetIndex ( ) . get ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Rule... if ( this . getRule ( ) != null ) { returnVal . put ( JSONMapping . RULE , this . getRule ( ) ) ; } //View Name... if ( this . getViewName ( ) != null ) { returnVal . put ( JSONMapping . VIEW_NAME , this . getViewName ( ) ) ; } //View Group Name... if ( this . getViewGroupName ( ) != null ) { returnVal . put ( JSONMapping . VIEW_GROUP_NAME , this . getViewGroupName ( ) ) ; } //View Flow Name... if ( this . getViewGroupName ( ) != null ) { returnVal . put ( JSONMapping . VIEW_FLOW_NAME , this . getViewFlowName ( ) ) ; } //View Step Name... if ( this . getViewGroupName ( ) != null ) { returnVal . put ( JSONMapping . VIEW_STEP_NAME , this . getViewStepName ( ) ) ; } //View Priority... if ( this . getViewPriority ( ) != null ) { returnVal . put ( JSONMapping . VIEW_PRIORITY , this . getViewPriority ( ) ) ; } //View Type... if ( this . getViewType ( ) != null ) { returnVal . put ( JSONMapping . VIEW_TYPE , this . getViewType ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Datasource Name... if ( this . getDatasourceName ( ) != null ) { returnVal . put ( JSONMapping . DATASOURCE_NAME , this . getDatasourceName ( ) ) ; } //Query... if ( this . getQuery ( ) != null ) { returnVal . put ( JSONMapping . QUERY , this . getQuery ( ) ) ; } //Stored Procedure... if ( this . getStoredProcedure ( ) != null ) { returnVal . put ( JSONMapping . STORED_PROCEDURE , this . getStoredProcedure ( ) ) ; } //Inputs... if ( this . getSqlInputs ( ) != null ) { JSONArray jsonArray = new JSONArray ( ) ; for ( SQLColumn toAdd : this . getSqlInputs ( ) ) { jsonArray . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . SQL_INPUTS , jsonArray ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a SQL input parameter . If the sql inputs is { @code null } a new instance of { @code ArrayList } will be created prior to adding the parameter . [CODESPLIT] @ XmlTransient public void addSqlInput ( SQLColumn sqlInputToAddParam ) { if ( this . sqlInputs == null ) { this . sqlInputs = new ArrayList <> ( ) ; } if ( sqlInputToAddParam == null ) { return ; } this . sqlInputs . add ( sqlInputToAddParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Flow with an Introduction and Exit basic rule . [CODESPLIT] public Flow createFlow ( Flow flowParam ) { if ( flowParam != null && this . serviceTicket != null ) { flowParam . setServiceTicket ( this . serviceTicket ) ; } return new Flow ( this . putJson ( flowParam , WS . Path . Flow . Version1 . flowCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing Flow . [CODESPLIT] public Flow updateFlow ( Flow flowParam ) { if ( flowParam != null && this . serviceTicket != null ) { flowParam . setServiceTicket ( this . serviceTicket ) ; } return new Flow ( this . postJson ( flowParam , WS . Path . Flow . Version1 . flowUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a Flow by Primary Key . [CODESPLIT] public Flow getFlowById ( Long flowIdParam ) { Flow flow = new Flow ( flowIdParam ) ; if ( this . serviceTicket != null ) { flow . setServiceTicket ( this . serviceTicket ) ; } return new Flow ( this . postJson ( flow , WS . Path . Flow . Version1 . getById ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a Flow by unique Name . [CODESPLIT] public Flow getFlowByName ( String flowNameParam ) { Flow flow = new Flow ( ) ; flow . setName ( flowNameParam ) ; if ( this . serviceTicket != null ) { flow . setServiceTicket ( this . serviceTicket ) ; } return new Flow ( this . postJson ( flow , WS . Path . Flow . Version1 . getByName ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an existing Flow . [CODESPLIT] public Flow deleteFlow ( Flow flowParam ) { if ( flowParam != null && this . serviceTicket != null ) { flowParam . setServiceTicket ( this . serviceTicket ) ; } return new Flow ( this . postJson ( flowParam , WS . Path . Flow . Version1 . flowDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forcefully Delete an existing Flow . [CODESPLIT] public Flow forceDeleteFlow ( Flow flowParam ) { if ( flowParam != null && this . serviceTicket != null ) { flowParam . setServiceTicket ( this . serviceTicket ) ; } return new Flow ( this . postJson ( flowParam , WS . Path . Flow . Version1 . flowDelete ( true ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Global field value . [CODESPLIT] public Field updateFieldValue ( Field globalFieldValueParam ) { if ( globalFieldValueParam != null && this . serviceTicket != null ) { globalFieldValueParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( globalFieldValueParam , Version1 . globalFieldUpdateValue ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves field value by { @code fieldNameParam } . [CODESPLIT] public Field getFieldValueByName ( String fieldNameParam ) { Field field = new Field ( ) ; field . setFieldName ( fieldNameParam ) ; return this . getFieldValueBy ( field ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves field value by { @code fieldParam } . [CODESPLIT] private Field getFieldValueBy ( Field fieldParam ) { if ( fieldParam != null ) { //Set for Payara server... fieldParam . setFieldValue ( new MultiChoice ( ) ) ; if ( this . serviceTicket != null ) { fieldParam . setServiceTicket ( this . serviceTicket ) ; } } return new Field ( this . postJson ( fieldParam , Version1 . getValueBy ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve all the Global field values . [CODESPLIT] public List < Field > getAllGlobalFieldValues ( ) { Field field = new Field ( ) ; //Set for Payara server... field . setFieldValue ( new MultiChoice ( ) ) ; if ( this . serviceTicket != null ) { field . setServiceTicket ( this . serviceTicket ) ; } return new GlobalFieldListing ( this . postJson ( field , Version1 . getAllValues ( ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the ancestor for the { @code electronicFormIdParam } Form . [CODESPLIT] public Form getFormAncestor ( Long electronicFormIdParam , boolean includeFieldDataParam , boolean includeTableFieldsParam ) { if ( electronicFormIdParam == null ) { return null ; } //Query using the descendantId directly... StringBuffer ancestorQuery = new StringBuffer ( Form . JSONMapping . DESCENDANT_IDS ) ; ancestorQuery . append ( \":\\\"\" ) ; ancestorQuery . append ( electronicFormIdParam ) ; ancestorQuery . append ( \"\\\"\" ) ; //Search for the Ancestor... List < Form > ancestorForms = null ; if ( includeFieldDataParam ) { ancestorForms = this . searchAndConvertHitsToFormWithAllFields ( QueryBuilders . queryStringQuery ( ancestorQuery . toString ( ) ) , Index . DOCUMENT , DEFAULT_OFFSET , 1 , new Long [ ] { } ) ; } else { ancestorForms = this . searchAndConvertHitsToFormWithNoFields ( QueryBuilders . queryStringQuery ( ancestorQuery . toString ( ) ) , Index . DOCUMENT , DEFAULT_OFFSET , 1 , new Long [ ] { } ) ; } Form returnVal = null ; if ( ancestorForms != null && ! ancestorForms . isEmpty ( ) ) { returnVal = ancestorForms . get ( 0 ) ; } //No result... if ( returnVal == null ) { return null ; } //Whether table field data should be included... if ( ! includeTableFieldsParam ) { return returnVal ; } //Populate the Table Fields... this . populateTableFields ( false , includeFieldDataParam , returnVal . getFormFields ( ) ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the descendants for the { @code electronicFormIdParam } Form . [CODESPLIT] @ Override public List < Form > getFormDescendants ( Long electronicFormIdParam , boolean includeFieldDataParam , boolean includeTableFieldsParam , boolean includeTableFieldFormRecordInfoParam ) { if ( electronicFormIdParam == null ) { return null ; } List < Long > electronicFormIds = new ArrayList ( ) ; electronicFormIds . add ( electronicFormIdParam ) ; //Get Form Descendants... return this . getFormDescendants ( electronicFormIds , includeFieldDataParam , includeTableFieldsParam , includeTableFieldFormRecordInfoParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the descendants for the { @code electronicFormIdsParam } Forms . [CODESPLIT] public List < Form > getFormDescendants ( List < Long > electronicFormIdsParam , boolean includeFieldDataParam , boolean includeTableFieldsParam , boolean includeTableFieldFormRecordInfoParam ) { if ( electronicFormIdsParam == null || electronicFormIdsParam . isEmpty ( ) ) { return null ; } //String stringQuery = \"formType:(\\\"JIT Schedule\\\" \\\"SMT Training\\\") AND flowState:\\\"Not In Flow\\\"\"; //Query using the descendantId directly... StringBuffer descendantQuery = new StringBuffer ( Form . JSONMapping . ANCESTOR_ID ) ; descendantQuery . append ( \":(\" ) ; for ( Long electronicFormId : electronicFormIdsParam ) { descendantQuery . append ( \"\\\"\" ) ; descendantQuery . append ( electronicFormId ) ; descendantQuery . append ( \"\\\"\" ) ; descendantQuery . append ( \" \" ) ; } String fullQueryToExec = descendantQuery . toString ( ) ; fullQueryToExec = fullQueryToExec . substring ( 0 , fullQueryToExec . length ( ) - 1 ) ; fullQueryToExec = fullQueryToExec . concat ( \")\" ) ; //Search for the Descendants... List < Form > returnVal = null ; if ( includeFieldDataParam ) { returnVal = this . searchAndConvertHitsToFormWithAllFields ( QueryBuilders . queryStringQuery ( fullQueryToExec ) , Index . DOCUMENT , DEFAULT_OFFSET , MAX_NUMBER_OF_TABLE_RECORDS , new Long [ ] { } ) ; } else { returnVal = this . searchAndConvertHitsToFormWithNoFields ( QueryBuilders . queryStringQuery ( fullQueryToExec ) , Index . DOCUMENT , DEFAULT_OFFSET , MAX_NUMBER_OF_TABLE_RECORDS , new Long [ ] { } ) ; } //Whether table field data should be included... if ( ! includeTableFieldsParam ) { return returnVal ; } //No result... if ( returnVal == null ) { return returnVal ; } //Populate in order to have table field data... for ( Form descendantForm : returnVal ) { this . populateTableFields ( false , includeFieldDataParam , descendantForm . getFormFields ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Table field records as { @code List<Form > } . [CODESPLIT] public List < Form > getFormTableForms ( Long electronicFormIdParam , boolean includeFieldDataParam ) { if ( electronicFormIdParam == null ) { return null ; } //Query using the descendantId directly... StringBuffer primaryQuery = new StringBuffer ( ABaseFluidJSONObject . JSONMapping . ID ) ; primaryQuery . append ( \":\\\"\" ) ; primaryQuery . append ( electronicFormIdParam ) ; primaryQuery . append ( \"\\\"\" ) ; //Search for the primary... List < Form > formsWithId = null ; if ( includeFieldDataParam ) { formsWithId = this . searchAndConvertHitsToFormWithAllFields ( QueryBuilders . queryStringQuery ( primaryQuery . toString ( ) ) , Index . DOCUMENT , DEFAULT_OFFSET , 1 , new Long [ ] { } ) ; } else { formsWithId = this . searchAndConvertHitsToFormWithNoFields ( QueryBuilders . queryStringQuery ( primaryQuery . toString ( ) ) , Index . DOCUMENT , DEFAULT_OFFSET , 1 , new Long [ ] { } ) ; } Form returnVal = null ; if ( formsWithId != null && ! formsWithId . isEmpty ( ) ) { returnVal = formsWithId . get ( 0 ) ; } //No result... if ( returnVal == null ) { return null ; } //Populate the Table Fields... return this . populateTableFields ( true , includeFieldDataParam , returnVal . getFormFields ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Definition and Title mapping currently stored in Fluid . [CODESPLIT] public Map < Long , String > getFormDefinitionIdAndTitle ( ) { //When already cached, use the cached value... if ( ! LOCAL_MAPPING . isEmpty ( ) ) { Map < Long , String > returnVal = new HashMap <> ( LOCAL_MAPPING ) ; //The id's are outdated... if ( System . currentTimeMillis ( ) > timeToUpdateAgain ) { synchronized ( LOCAL_MAPPING ) { LOCAL_MAPPING . clear ( ) ; } } return returnVal ; } //Only allow one thread to set the local mapping... synchronized ( LOCAL_MAPPING ) { if ( ! LOCAL_MAPPING . isEmpty ( ) ) { return new HashMap <> ( LOCAL_MAPPING ) ; } PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; try { ISyntax syntax = SyntaxFactory . getInstance ( ) . getSyntaxFor ( this . getSQLTypeFromConnection ( ) , ISyntax . ProcedureMapping . FormDefinition . GetFormDefinitions ) ; preparedStatement = this . getConnection ( ) . prepareStatement ( syntax . getPreparedStatement ( ) ) ; resultSet = preparedStatement . executeQuery ( ) ; //Iterate each of the form containers... while ( resultSet . next ( ) ) { Long id = resultSet . getLong ( 1 ) ; String title = resultSet . getString ( 2 ) ; LOCAL_MAPPING . put ( id , title ) ; } //Update in 10 mins... timeToUpdateAgain = ( System . currentTimeMillis ( ) + TimeUnit . MINUTES . toMillis ( 10 ) ) ; } // catch ( SQLException sqlError ) { throw new FluidSQLException ( sqlError ) ; } // finally { this . closeStatement ( preparedStatement , resultSet ) ; } return new HashMap <> ( LOCAL_MAPPING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Salt... if ( this . getSalt ( ) != null ) { returnVal . put ( JSONMapping . SALT , this . getSalt ( ) ) ; } //Encrypted Data Base 64... if ( this . getEncryptedDataBase64 ( ) != null ) { returnVal . put ( JSONMapping . ENCRYPTED_DATA_BASE_64 , this . getEncryptedDataBase64 ( ) ) ; } //Encrypted Data HMAC Base 64... if ( this . getEncryptedDataHmacBase64 ( ) != null ) { returnVal . put ( JSONMapping . ENCRYPTED_DATA_HMAC_BASE_64 , this . getEncryptedDataHmacBase64 ( ) ) ; } //IV Base 64... if ( this . getIvBase64 ( ) != null ) { returnVal . put ( JSONMapping . IV_BASE_64 , this . getIvBase64 ( ) ) ; } //Seed Base 64... if ( this . getSeedBase64 ( ) != null ) { returnVal . put ( JSONMapping . SEED_BASE_64 , this . getSeedBase64 ( ) ) ; } //Service Ticket Base 64... if ( this . getServiceTicketBase64 ( ) != null ) { returnVal . put ( JSONMapping . SERVICE_TICKET_BASE_64 , this . getServiceTicketBase64 ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Data Base64... if ( this . getDataBase64 ( ) != null ) { returnVal . put ( JSONMapping . DATA_BASE_64 , this . getDataBase64 ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Sum Decimals... if ( this . getSumDecimals ( ) != null ) { returnVal . put ( JSONMapping . SUM_DECIMALS , this . getSumDecimals ( ) ) ; } //Table Field Records... if ( this . getTableRecords ( ) != null && ! this . getTableRecords ( ) . isEmpty ( ) ) { JSONArray assoFormsArr = new JSONArray ( ) ; for ( Form toAdd : this . getTableRecords ( ) ) { assoFormsArr . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . TABLE_RECORDS , assoFormsArr ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Listing... int listingCountFromListing = 0 ; if ( this . getListing ( ) != null && ! this . getListing ( ) . isEmpty ( ) ) { JSONArray jsonArray = new JSONArray ( ) ; listingCountFromListing = this . getListing ( ) . size ( ) ; for ( T toAdd : this . getListing ( ) ) { jsonArray . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . LISTING , jsonArray ) ; } //Listing count... if ( this . getListingCount ( ) == null ) { returnVal . put ( JSONMapping . LISTING_COUNT , new Integer ( listingCountFromListing ) ) ; } else { returnVal . put ( JSONMapping . LISTING_COUNT , this . getListingCount ( ) ) ; } //Listing index... if ( this . getListingIndex ( ) != null ) { returnVal . put ( JSONMapping . LISTING_INDEX , this . getListingIndex ( ) ) ; } //Listing page... if ( this . getListingIndex ( ) != null ) { returnVal . put ( JSONMapping . LISTING_PAGE , this . getListingPage ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the { @code getExpirationTime } to confirm whether the ticket has expired . [CODESPLIT] public boolean isExpired ( ) { if ( this . getExpirationTime ( ) == null ) { return true ; } Date expirationTime = new Date ( this . getExpirationTime ( ) ) ; return ( expirationTime . before ( new Date ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code UserNotification } for a user . The user will be notified through the Fluid User Dashboard or 3rd Party application . [CODESPLIT] public UserNotification createUserNotification ( UserNotification userNotificationParam ) { if ( userNotificationParam != null && this . serviceTicket != null ) { userNotificationParam . setServiceTicket ( this . serviceTicket ) ; } return new UserNotification ( this . putJson ( userNotificationParam , WS . Path . UserNotification . Version1 . userNotificationCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new { @code UserNotification } for a user . The user will be notified through the Fluid User Dashboard or 3rd Party application . [CODESPLIT] public UserNotification updateUserNotification ( UserNotification userNotificationParam ) { if ( userNotificationParam != null && this . serviceTicket != null ) { userNotificationParam . setServiceTicket ( this . serviceTicket ) ; } return new UserNotification ( this . postJson ( userNotificationParam , WS . Path . UserNotification . Version1 . userNotificationUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marks the { @code userNotificationParam } notification as read . [CODESPLIT] public UserNotification markUserNotificationAsRead ( UserNotification userNotificationParam , boolean asyncParam ) { if ( userNotificationParam != null && this . serviceTicket != null ) { userNotificationParam . setServiceTicket ( this . serviceTicket ) ; } return new UserNotification ( this . postJson ( userNotificationParam , WS . Path . UserNotification . Version1 . userNotificationMarkAsRead ( asyncParam ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the { @code UserNotification } provided . Id must be set on the { @code UserNotification } . [CODESPLIT] public UserNotification deleteUserNotification ( UserNotification userNotificationToDeleteParam ) { if ( userNotificationToDeleteParam != null && this . serviceTicket != null ) { userNotificationToDeleteParam . setServiceTicket ( this . serviceTicket ) ; } return new UserNotification ( this . postJson ( userNotificationToDeleteParam , WS . Path . UserNotification . Version1 . userNotificationDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the { @code UserNotification } provided . Id must be set on the { @code UserNotification } . [CODESPLIT] public UserNotification getUserNotificationById ( Long userNotificationPkParam ) { UserNotification userNoti = new UserNotification ( ) ; userNoti . setId ( userNotificationPkParam ) ; if ( this . serviceTicket != null ) { userNoti . setServiceTicket ( this . serviceTicket ) ; } try { return new UserNotification ( this . postJson ( userNoti , WS . Path . UserNotification . Version1 . getById ( ) ) ) ; } //Json format issues... catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all { @code READ } User Notification items for the logged in user . [CODESPLIT] public List < UserNotification > getAllReadByLoggedInUser ( int queryLimitParam , int offsetParam ) { User loggedInUser = new User ( ) ; if ( this . serviceTicket != null ) { loggedInUser . setServiceTicket ( this . serviceTicket ) ; } try { return new UserNotificationListing ( this . postJson ( loggedInUser , WS . Path . UserNotification . Version1 . getAllReadByUser ( queryLimitParam , offsetParam ) ) ) . getListing ( ) ; } catch ( JSONException jsonExcept ) { //rethrow as a Fluid Client exception. throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all User Notification items for user { @code userParam } between date { @code fromDateParam } and { @code toDateParam } . [CODESPLIT] public List < UserNotification > getAllByUserAndDateBetween ( User userParam , Date fromDateParam , Date toDateParam ) { return this . getAllByUserAndDateBetween ( userParam , - 1 , - 1 , fromDateParam , toDateParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all User Notification items for user { @code userParam } between date { @code fromDateParam } and { @code toDateParam } . [CODESPLIT] public List < UserNotification > getAllByUserAndDateBetween ( User userParam , int queryLimitParam , int offsetParam , Date fromDateParam , Date toDateParam ) { if ( this . serviceTicket != null && userParam != null ) { userParam . setServiceTicket ( this . serviceTicket ) ; } long fromDate = ( fromDateParam == null ) ? System . currentTimeMillis ( ) - TimeUnit . DAYS . toMillis ( 7 ) : fromDateParam . getTime ( ) ; long toDate = ( toDateParam == null ) ? System . currentTimeMillis ( ) : toDateParam . getTime ( ) ; try { return new UserNotificationListing ( this . postJson ( userParam , WS . Path . UserNotification . Version1 . getAllByUserAndDate ( queryLimitParam , offsetParam , fromDate , toDate ) ) ) . getListing ( ) ; } catch ( JSONException jsonExcept ) { //rethrow as a Fluid Client exception. throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a new initialization vector with a { @code seedParam } byte count . [CODESPLIT] public static byte [ ] generateRandom ( int seedParam ) { if ( AES256Local . secureRandom == null ) { AES256Local . secureRandom = new SecureRandom ( ) ; } return new IvParameterSpec ( AES256Local . secureRandom . generateSeed ( seedParam ) ) . getIV ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates an HMAC from { @code encryptedDataParam } . [CODESPLIT] public static byte [ ] hmacSha256 ( byte [ ] hMacKeyParam , byte [ ] encryptedDataParam ) { try { // hmac Mac hmac = Mac . getInstance ( HMAC_ALGO ) ; hmac . init ( new SecretKeySpec ( hMacKeyParam , HMAC_ALGO ) ) ; return hmac . doFinal ( encryptedDataParam ) ; } //Changed for Java 1.6 compatibility... catch ( NoSuchAlgorithmException except ) { throw new FluidClientException ( \"Unable to create HMAC from key. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( InvalidKeyException except ) { throw new FluidClientException ( \"Unable to create HMAC from key. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a derived HMAC from { @code encryptedDataParam } using other params . [CODESPLIT] public static byte [ ] generateLocalHMAC ( byte [ ] encryptedDataParam , String passwordParam , String saltParam , byte [ ] seedParam ) { byte [ ] poisonedSeed = poisonBytes ( seedParam ) ; byte [ ] passwordSha256 = sha256 ( passwordParam . concat ( saltParam ) . getBytes ( ) ) ; //Add the seed to the password and SHA-256... byte [ ] derivedKey = sha256 ( UtilGlobal . addAll ( passwordSha256 , poisonedSeed ) ) ; return hmacSha256 ( derivedKey , encryptedDataParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a derived HMAC from { @code encryptedDataParam } using { @code keyParam } . [CODESPLIT] public static byte [ ] generateLocalHMACForReqToken ( byte [ ] encryptedDataParam , byte [ ] keyParam , byte [ ] seedParam ) { byte [ ] poisonedSeed = poisonBytes ( seedParam ) ; //Add the seed to the password and SHA-256... byte [ ] derivedKey = sha256 ( UtilGlobal . addAll ( keyParam , poisonedSeed ) ) ; return hmacSha256 ( derivedKey , encryptedDataParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a derived version of { @code bytesToPoisonParam } . [CODESPLIT] private static byte [ ] poisonBytes ( byte [ ] bytesToPoisonParam ) { if ( bytesToPoisonParam == null ) { return null ; } byte [ ] returnVal = new byte [ bytesToPoisonParam . length ] ; for ( int index = 0 ; index < bytesToPoisonParam . length ; index ++ ) { byte poisoned = ( byte ) ( bytesToPoisonParam [ index ] ^ 222 ) ; returnVal [ index ] = poisoned ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decrypts the encrypted data . [CODESPLIT] public static byte [ ] decryptInitPacket ( byte [ ] encryptedDataParam , String passwordParam , String saltParam , byte [ ] ivParam , byte [ ] seedParam ) { //Stored like this in the database, so we have to get the password as stored in the database so that the // SHa256 and SALT combination will be valid... byte [ ] passwordSha256 = sha256 ( passwordParam . concat ( saltParam ) . getBytes ( ) ) ; //Add the seed to the password and SHA-256... byte [ ] derivedKey = sha256 ( UtilGlobal . addAll ( passwordSha256 , seedParam ) ) ; //Decrypt with the derived key. return decrypt ( derivedKey , encryptedDataParam , ivParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decrypt { @code dataToDecryptParam } using the { @code keyParam } key . [CODESPLIT] public static byte [ ] decrypt ( byte [ ] keyParam , byte [ ] dataToDecryptParam , byte [ ] ivParam ) { Key key = new SecretKeySpec ( keyParam , KEY_ALGO ) ; try { Cipher cipher = Cipher . getInstance ( ALGO_CBC ) ; cipher . init ( Cipher . DECRYPT_MODE , key , new IvParameterSpec ( ivParam ) ) ; return cipher . doFinal ( dataToDecryptParam ) ; } //Changed for Java 1.6 compatibility... catch ( InvalidKeyException except ) { throw new FluidClientException ( \"Key: Unable to decrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( InvalidAlgorithmParameterException except ) { throw new FluidClientException ( \"Algo: Unable to decrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( IllegalBlockSizeException except ) { throw new FluidClientException ( \"Block: Unable to decrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( NoSuchPaddingException except ) { throw new FluidClientException ( \"NoPadding: Unable to decrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( NoSuchAlgorithmException except ) { throw new FluidClientException ( \"NoAlgo: Unable to decrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( BadPaddingException except ) { throw new FluidClientException ( \"BadPadding: Unable to decrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encrypts the { @code dataToEncryptParam } data using key { @code keyParam } . [CODESPLIT] public static byte [ ] encrypt ( byte [ ] keyParam , byte [ ] dataToEncryptParam , byte [ ] ivParam ) { if ( dataToEncryptParam == null ) { throw new FluidClientException ( \"No data to encrypt provided. \" , FluidClientException . ErrorCode . AES_256 ) ; } Key key = new SecretKeySpec ( keyParam , KEY_ALGO ) ; try { Cipher cipher = Cipher . getInstance ( ALGO_CBC ) ; cipher . init ( Cipher . ENCRYPT_MODE , key , new IvParameterSpec ( ivParam ) ) ; return cipher . doFinal ( dataToEncryptParam ) ; } //Changed for Java 1.6 compatibility... catch ( InvalidKeyException except ) { throw new FluidClientException ( \"Key: Unable to encrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( InvalidAlgorithmParameterException except ) { throw new FluidClientException ( \"Algo: Unable to encrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( IllegalBlockSizeException except ) { throw new FluidClientException ( \"Block: Unable to encrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( NoSuchPaddingException except ) { throw new FluidClientException ( \"NoPadding: Unable to encrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( NoSuchAlgorithmException except ) { throw new FluidClientException ( \"NoAlgo: Unable to encrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } catch ( BadPaddingException except ) { throw new FluidClientException ( \"BadPadding: Unable to encrypt data. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . AES_256 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compute SHA256 digest from { @code dataParam } . [CODESPLIT] public static byte [ ] sha256 ( final byte [ ] dataParam ) { if ( dataParam == null || dataParam . length == 0 ) { return new byte [ ] { } ; } try { final MessageDigest digest = MessageDigest . getInstance ( \"SHA-256\" ) ; return digest . digest ( dataParam ) ; } // catch ( final NoSuchAlgorithmException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send the { @code baseFluidJSONObjectParam } via Web Socket . [CODESPLIT] public void sendMessage ( ABaseFluidJSONObject baseFluidJSONObjectParam , String requestIdParam ) { if ( baseFluidJSONObjectParam != null ) { baseFluidJSONObjectParam . setServiceTicket ( this . serviceTicket ) ; //Add the echo to the listing if [GenericListMessageHandler]. if ( this . getHandler ( requestIdParam ) instanceof AGenericListMessageHandler ) { AGenericListMessageHandler listHandler = ( AGenericListMessageHandler ) this . getHandler ( requestIdParam ) ; listHandler . addExpectedMessage ( baseFluidJSONObjectParam . getEcho ( ) ) ; } } this . webSocketClient . sendMessage ( baseFluidJSONObjectParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the HTTP Client is set this will close and clean any connections that needs to be closed . [CODESPLIT] @ Override public void closeAndClean ( ) { CloseConnectionRunnable closeConnectionRunnable = new CloseConnectionRunnable ( this ) ; Thread closeConnThread = new Thread ( closeConnectionRunnable , \"Close ABaseClientWebSocket Connection\" ) ; closeConnThread . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initiate a new request process . [CODESPLIT] public synchronized String initNewRequest ( ) { String returnVal = UUID . randomUUID ( ) . toString ( ) ; this . messageHandler . put ( returnVal , this . getNewHandlerInstance ( ) ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Web Service URL from { @code webServiceURLParam } . [CODESPLIT] private String getWebSocketBaseURIFrom ( String webServiceURLParam ) { if ( webServiceURLParam == null ) { return null ; } if ( webServiceURLParam . trim ( ) . length ( ) == 0 ) { return UtilGlobal . EMPTY ; } URI uri = URI . create ( webServiceURLParam ) ; StringBuilder returnBuffer = new StringBuilder ( ) ; String scheme = uri . getScheme ( ) ; if ( scheme == null ) { throw new FluidClientException ( \"Unable to get scheme from '\" + webServiceURLParam + \"' URL.\" , FluidClientException . ErrorCode . ILLEGAL_STATE_ERROR ) ; } scheme = scheme . trim ( ) . toLowerCase ( ) ; //https://localhost:8443/fluid-ws/ //Scheme... if ( Constant . HTTP . equals ( scheme ) ) { returnBuffer . append ( Constant . WS ) ; } else if ( Constant . HTTPS . equals ( scheme ) ) { returnBuffer . append ( Constant . WSS ) ; } else { returnBuffer . append ( uri . getScheme ( ) ) ; } // :// returnBuffer . append ( Constant . SCHEME_SEP ) ; returnBuffer . append ( uri . getHost ( ) ) ; // 80 / 443 if ( uri . getPort ( ) > 0 ) { returnBuffer . append ( Constant . COLON ) ; returnBuffer . append ( uri . getPort ( ) ) ; } // /fluid-ws/ returnBuffer . append ( uri . getPath ( ) ) ; return returnBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the { @code echo } value if not set . [CODESPLIT] protected void setEchoIfNotSet ( ABaseFluidVO baseToSetEchoOnIfNotSetParam ) { if ( baseToSetEchoOnIfNotSetParam == null ) { throw new FluidClientException ( \"Cannot provide 'null' for value object / pojo.\" , FluidClientException . ErrorCode . ILLEGAL_STATE_ERROR ) ; } else if ( baseToSetEchoOnIfNotSetParam . getEcho ( ) == null || baseToSetEchoOnIfNotSetParam . getEcho ( ) . trim ( ) . isEmpty ( ) ) { baseToSetEchoOnIfNotSetParam . setEcho ( UUID . randomUUID ( ) . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a verbose Exception message . [CODESPLIT] protected String getExceptionMessageVerbose ( String prefixParam , String uniqueReqIdParam , int numberOfSentItemsParam ) { StringBuilder formFieldsCombined = new StringBuilder ( ) ; int returnValSize = - 1 ; RespHandler respHandler = this . getHandler ( uniqueReqIdParam ) ; if ( respHandler instanceof AGenericListMessageHandler ) { List < ? extends ABaseFluidJSONObject > returnValue = ( ( AGenericListMessageHandler ) respHandler ) . getReturnValue ( ) ; if ( returnValue != null ) { returnValSize = returnValue . size ( ) ; returnValue . forEach ( listingItm -> { if ( listingItm instanceof ABaseListing ) { ABaseListing castedToListing = ( ABaseListing ) listingItm ; if ( castedToListing != null ) { castedToListing . getListing ( ) . forEach ( formItm -> { formFieldsCombined . append ( formItm . toString ( ) ) ; } ) ; } } else { formFieldsCombined . append ( listingItm . toString ( ) ) ; } } ) ; } } return ( prefixParam + \": \" + \"Timeout while waiting for all return data. There were '\" + returnValSize + \"' items after a Timeout of \" + ( TimeUnit . MILLISECONDS . toSeconds ( this . getTimeoutInMillis ( ) ) ) + \" seconds on req-ref-nr '\" + uniqueReqIdParam + \"'. Expected a total of '\" + numberOfSentItemsParam + \"' forms. Returned-Data '\" + formFieldsCombined . toString ( ) + \"'.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new administrator user for Fluid . This function only works if there are no pre - existing admin user . [CODESPLIT] public User createAdminUser ( String passwordParam ) { User adminUserCreate = new User ( ) ; adminUserCreate . setPasswordClear ( passwordParam ) ; return new User ( this . putJson ( adminUserCreate , WS . Path . User . Version1 . userCreateAdmin ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //User... if ( this . getUser ( ) != null ) { returnVal . put ( JSONMapping . USER , this . getUser ( ) . toJsonObject ( ) ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Read... if ( this . getDateRead ( ) != null ) { returnVal . put ( JSONMapping . DATE_READ , this . getDateAsLongFromJson ( this . getDateRead ( ) ) ) ; } //Expiring Link... if ( this . getExpiringLink ( ) != null ) { returnVal . put ( JSONMapping . EXPIRING_LINK , this . getExpiringLink ( ) ) ; } //Message... if ( this . getMessage ( ) != null ) { returnVal . put ( JSONMapping . MESSAGE , this . getMessage ( ) ) ; } //User Notification Type... returnVal . put ( JSONMapping . USER_NOTIFICATION_TYPE , this . getUserNotificationType ( ) ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Form Container... if ( this . getFormContainer ( ) != null ) { returnVal . put ( JSONMapping . FORM_CONTAINER , this . getFormContainer ( ) . toJsonObject ( ) ) ; } //Message... if ( this . getMessage ( ) != null ) { returnVal . put ( JSONMapping . MESSAGE , this . getMessage ( ) ) ; } //Date Read... if ( this . getDateRead ( ) != null ) { returnVal . put ( JSONMapping . DATE_READ , this . getDateAsLongFromJson ( this . getDateRead ( ) ) ) ; } //Date Sent... if ( this . getDateSent ( ) != null ) { returnVal . put ( JSONMapping . DATE_SENT , this . getDateAsLongFromJson ( this . getDateSent ( ) ) ) ; } //From User... if ( this . getFromUser ( ) != null ) { returnVal . put ( JSONMapping . FROM_USER , this . getFromUser ( ) . toJsonObject ( ) ) ; } //To User... if ( this . getToUser ( ) != null ) { returnVal . put ( JSONMapping . TO_USER , this . getToUser ( ) . toJsonObject ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a Access Token from Auth0 . [CODESPLIT] public AccessToken getAccessToken ( String clientIdParam , String clientSecretParam , String codeParam , String redirectUrlParam ) { if ( clientIdParam == null || clientIdParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Client Id must be provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( clientSecretParam == null || clientSecretParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Client Secret must be provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( codeParam == null || codeParam . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"Code must be provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } AccessTokenRequest tokenRequest = new AccessTokenRequest ( ) ; tokenRequest . setClientId ( clientIdParam ) ; tokenRequest . setClientSecret ( clientSecretParam ) ; tokenRequest . setGrantType ( AUTHORIZATION_CODE ) ; tokenRequest . setCode ( codeParam ) ; tokenRequest . setRedirectUri ( redirectUrlParam ) ; return new AccessToken ( this . postJson ( false , tokenRequest , WS . Path . Auth0 . Version1 . userToken ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets Auth0 Normalized User Profile info . [CODESPLIT] public NormalizedUserProfile getUserProfileInfo ( AccessToken accessTokenParam ) { if ( accessTokenParam == null || ( accessTokenParam . getAccessToken ( ) == null || accessTokenParam . getAccessToken ( ) . trim ( ) . isEmpty ( ) ) ) { throw new FluidClientException ( \"Code must be provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } try { String accessToken = accessTokenParam . getAccessToken ( ) ; List < HeaderNameValue > headerListing = new ArrayList < HeaderNameValue > ( ) ; headerListing . add ( new HeaderNameValue ( NormalizedUserProfile . HeaderMapping . AUTHORIZATION , \"Bearer \" + accessToken ) ) ; return new NormalizedUserProfile ( this . getJson ( true , WS . Path . Auth0 . Version1 . userInfo ( ) , headerListing ) ) ; } // catch ( UnsupportedEncodingException e ) { throw new FluidClientException ( \"Unable to Encode (Not Supported). \" + e . getMessage ( ) , FluidClientException . ErrorCode . ILLEGAL_STATE_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Fields { @code VALUES } for the Electronic Form with id { @code electronicFormIdParam } . [CODESPLIT] public Form getFormFields ( Long electronicFormIdParam , boolean includeTableFieldsParam ) { if ( electronicFormIdParam == null ) { return null ; } //Query using the descendantId directly... StringBuffer primaryQuery = new StringBuffer ( ABaseFluidJSONObject . JSONMapping . ID ) ; primaryQuery . append ( \":\\\"\" ) ; primaryQuery . append ( electronicFormIdParam ) ; primaryQuery . append ( \"\\\"\" ) ; //Search for the primary... List < Form > formsWithId = this . searchAndConvertHitsToFormWithAllFields ( QueryBuilders . queryStringQuery ( primaryQuery . toString ( ) ) , Index . DOCUMENT , DEFAULT_OFFSET , 1 , new Long [ ] { } ) ; Form returnVal = null ; if ( formsWithId != null && ! formsWithId . isEmpty ( ) ) { returnVal = formsWithId . get ( 0 ) ; } //No result... if ( returnVal == null ) { return null ; } //Skip Table fields... if ( ! includeTableFieldsParam ) { return returnVal ; } //Populate the Table Fields... this . populateTableFields ( false , true , returnVal . getFormFields ( ) ) ; return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override @ XmlTransient public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Filename... if ( this . getFilename ( ) != null ) { returnVal . put ( JSONMapping . FILENAME , this . getFilename ( ) ) ; } //Description... if ( this . getDescription ( ) != null ) { returnVal . put ( JSONMapping . DESCRIPTION , this . getDescription ( ) ) ; } //Sha-256 SUM... if ( this . getSha256sum ( ) != null ) { returnVal . put ( JSONMapping . SHA_256_SUM , this . getSha256sum ( ) ) ; } //Add Tools to Classpath... if ( this . isAddToolsToClassPath ( ) != null ) { returnVal . put ( JSONMapping . ADD_TOOLS_TO_CLASS_PATH , this . isAddToolsToClassPath ( ) ) ; } //Library Data in Base-64... if ( this . getLibraryDataBase64 ( ) != null ) { returnVal . put ( JSONMapping . LIBRARY_DATA_BASE64 , this . getLibraryDataBase64 ( ) ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( JSONMapping . DATE_LAST_UPDATED , this . getDateAsLongFromJson ( this . getDateLastUpdated ( ) ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP request with { @code postfixUrlParam } on { @code httpClientParam } . [CODESPLIT] private String executeHttp ( HttpClient httpClientParam , HttpUriRequest httpUriRequestParam , ResponseHandler responseHandlerParam , String postfixUrlParam ) { try { Object returnedObj = httpClientParam . execute ( httpUriRequestParam , responseHandlerParam ) ; //String text came back... if ( returnedObj instanceof String ) { return ( String ) returnedObj ; } else if ( returnedObj == null ) { //[null] - came back... throw new FluidClientException ( \"No results, [null] response.\" , FluidClientException . ErrorCode . NO_RESULT ) ; } throw new FluidClientException ( \"Expected 'String' got '\" + ( ( returnedObj == null ) ? null : returnedObj . getClass ( ) . getName ( ) ) + \"'.\" , FluidClientException . ErrorCode . ILLEGAL_STATE_ERROR ) ; } catch ( IOException except ) { //IO Problem... if ( except instanceof UnknownHostException ) { throw new FluidClientException ( \"Unable to reach host '\" + this . endpointUrl . concat ( postfixUrlParam ) + \"'. \" + except . getMessage ( ) , except , FluidClientException . ErrorCode . CONNECT_ERROR ) ; } if ( except instanceof ConnectException ) { throw new FluidClientException ( except . getMessage ( ) , except , FluidClientException . ErrorCode . CONNECT_ERROR ) ; } throw new FluidClientException ( except . getMessage ( ) , except , FluidClientException . ErrorCode . IO_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - GET request with { @code postfixUrlParam } . [CODESPLIT] public JSONObject getJson ( String postfixUrlParam , List < HeaderNameValue > headerNameValuesParam ) { return this . getJson ( false , postfixUrlParam , headerNameValuesParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - GET request with { @code postfixUrlParam } . [CODESPLIT] public JSONObject getJson ( boolean checkConnectionValidParam , String postfixUrlParam , List < HeaderNameValue > headerNameValuesParam ) { //Connection is not valid...throw error... if ( checkConnectionValidParam && ! this . isConnectionValid ( ) ) { throw new FluidClientException ( \"Unable to reach service at '\" + this . endpointUrl . concat ( postfixUrlParam ) + \"'.\" , FluidClientException . ErrorCode . CONNECT_ERROR ) ; } CloseableHttpClient httpclient = this . getClient ( ) ; try { HttpGet httpGet = new HttpGet ( this . endpointUrl . concat ( postfixUrlParam ) ) ; if ( headerNameValuesParam != null && ! headerNameValuesParam . isEmpty ( ) ) { for ( HeaderNameValue headerNameVal : headerNameValuesParam ) { if ( headerNameVal . getName ( ) == null || headerNameVal . getName ( ) . trim ( ) . isEmpty ( ) ) { continue ; } if ( headerNameVal . getValue ( ) == null ) { continue ; } httpGet . setHeader ( headerNameVal . getName ( ) , headerNameVal . getValue ( ) ) ; } } // Create a custom response handler ResponseHandler < String > responseHandler = this . getJsonResponseHandler ( this . endpointUrl . concat ( postfixUrlParam ) ) ; String responseBody = this . executeHttp ( httpclient , httpGet , responseHandler , postfixUrlParam ) ; if ( responseBody == null || responseBody . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"No response data from '\" + this . endpointUrl . concat ( postfixUrlParam ) + \"'.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } JSONObject jsonOjb = new JSONObject ( responseBody ) ; if ( jsonOjb . isNull ( Error . JSONMapping . ERROR_CODE ) ) { return jsonOjb ; } int errorCode = jsonOjb . getInt ( Error . JSONMapping . ERROR_CODE ) ; if ( errorCode > 0 ) { String errorMessage = ( jsonOjb . isNull ( Error . JSONMapping . ERROR_MESSAGE ) ? \"Not set\" : jsonOjb . getString ( Error . JSONMapping . ERROR_MESSAGE ) ) ; throw new FluidClientException ( errorMessage , errorCode ) ; } return jsonOjb ; } catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - POST request with { @code postfixUrlParam } . [CODESPLIT] protected JSONObject postJson ( ABaseFluidJSONObject baseDomainParam , String postfixUrlParam ) { //No need to check connection... return this . postJson ( false , baseDomainParam , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - POST request with { @code postfixUrlParam } . [CODESPLIT] protected JSONObject postJson ( List < HeaderNameValue > headerNameValuesParam , boolean checkConnectionValidParam , ABaseFluidJSONObject baseDomainParam , String postfixUrlParam ) { return this . executeJson ( HttpMethod . POST , headerNameValuesParam , checkConnectionValidParam , baseDomainParam , ContentType . APPLICATION_JSON , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - POST request with { @code postfixUrlParam } . [CODESPLIT] protected JSONObject postJson ( boolean checkConnectionValidParam , ABaseFluidJSONObject baseDomainParam , String postfixUrlParam ) { return this . executeJson ( HttpMethod . POST , null , checkConnectionValidParam , baseDomainParam , ContentType . APPLICATION_JSON , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - DELETE request with { @code postfixUrlParam } . [CODESPLIT] protected JSONObject deleteJson ( ABaseFluidJSONObject baseDomainParam , String postfixUrlParam ) { //No need to check connection... return this . deleteJson ( false , baseDomainParam , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - DELETE request with { @code postfixUrlParam } . [CODESPLIT] protected JSONObject deleteJson ( boolean checkConnectionValidParam , ABaseFluidJSONObject baseDomainParam , String postfixUrlParam ) { return this . executeJson ( HttpMethod . DELETE , null , checkConnectionValidParam , baseDomainParam , ContentType . APPLICATION_JSON , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - POST request with { @code postfixUrlParam } making use of form params as { @code formNameValuesParam } . [CODESPLIT] protected JSONObject postForm ( boolean checkConnectionValidParam , List < FormNameValue > formNameValuesParam , String postfixUrlParam ) { return this . executeForm ( HttpMethod . POST , null , checkConnectionValidParam , formNameValuesParam , ContentType . APPLICATION_FORM_URLENCODED , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - PUT request with { @code postfixUrlParam } . [CODESPLIT] protected JSONObject putJson ( boolean checkConnectionValidParam , ABaseFluidJSONObject baseDomainParam , String postfixUrlParam ) { return this . executeJson ( HttpMethod . PUT , null , checkConnectionValidParam , baseDomainParam , ContentType . APPLICATION_JSON , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP - PUT request with { @code postfixUrlParam } . [CODESPLIT] protected JSONObject putJson ( ABaseFluidJSONObject baseDomainParam , String postfixUrlParam ) { //Create without connection check... return this . putJson ( false , baseDomainParam , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submit a JSON based HTTP request body with JSON as a response . [CODESPLIT] protected JSONObject executeJson ( HttpMethod httpMethodParam , List < HeaderNameValue > headerNameValuesParam , boolean checkConnectionValidParam , ABaseFluidJSONObject baseDomainParam , ContentType contentTypeParam , String postfixUrlParam ) { //Validate that something is set. if ( baseDomainParam == null ) { throw new FluidClientException ( \"No JSON body to post.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } String bodyJsonString = baseDomainParam . toJsonObject ( ) . toString ( ) ; return this . executeString ( httpMethodParam , headerNameValuesParam , checkConnectionValidParam , bodyJsonString , contentTypeParam , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submit a HTML Form based HTTP request body with JSON as a response . [CODESPLIT] protected JSONObject executeForm ( HttpMethod httpMethodParam , List < HeaderNameValue > headerNameValuesParam , boolean checkConnectionValidParam , List < FormNameValue > formNameValuesParam , ContentType contentTypeParam , String postfixUrlParam ) { //Validate Form Field and values... if ( formNameValuesParam == null || formNameValuesParam . isEmpty ( ) ) { throw new FluidClientException ( \"No 'Name and Value' body to post.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } StringBuilder strBuilder = new StringBuilder ( ) ; for ( FormNameValue nameValue : formNameValuesParam ) { if ( nameValue . getName ( ) == null || nameValue . getName ( ) . trim ( ) . isEmpty ( ) ) { continue ; } if ( nameValue . getValue ( ) == null ) { continue ; } strBuilder . append ( nameValue . getName ( ) ) ; strBuilder . append ( EQUALS ) ; strBuilder . append ( nameValue . getValue ( ) ) ; strBuilder . append ( AMP ) ; } String bodyJsonString = strBuilder . toString ( ) ; bodyJsonString = bodyJsonString . substring ( 0 , bodyJsonString . length ( ) - 1 ) ; return this . executeString ( httpMethodParam , headerNameValuesParam , checkConnectionValidParam , bodyJsonString , contentTypeParam , postfixUrlParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submit the { @code stringParam } as HTTP request body with JSON as a response . [CODESPLIT] protected JSONObject executeString ( HttpMethod httpMethodParam , List < HeaderNameValue > headerNameValuesParam , boolean checkConnectionValidParam , String stringParam , ContentType contentTypeParam , String postfixUrlParam ) { String responseBody = this . executeTxtReceiveTxt ( httpMethodParam , headerNameValuesParam , checkConnectionValidParam , stringParam , contentTypeParam , postfixUrlParam ) ; if ( responseBody == null || responseBody . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"No response data from '\" + this . endpointUrl . concat ( postfixUrlParam ) + \"'.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } try { JSONObject jsonOjb = new JSONObject ( responseBody ) ; if ( jsonOjb . isNull ( Error . JSONMapping . ERROR_CODE ) ) { return jsonOjb ; } int errorCode = jsonOjb . getInt ( Error . JSONMapping . ERROR_CODE ) ; if ( errorCode > 0 ) { String errorMessage = ( jsonOjb . isNull ( Error . JSONMapping . ERROR_MESSAGE ) ? \"Not set\" : jsonOjb . getString ( Error . JSONMapping . ERROR_MESSAGE ) ) ; throw new FluidClientException ( errorMessage , errorCode ) ; } return jsonOjb ; } catch ( JSONException jsonExcept ) { //Invalid JSON Body... if ( responseBody != null && ! responseBody . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( jsonExcept . getMessage ( ) + \"\\n Response Body is: \\n\\n\" + responseBody , jsonExcept , FluidClientException . ErrorCode . JSON_PARSING ) ; } throw new FluidClientException ( jsonExcept . getMessage ( ) , jsonExcept , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submit the { @code stringParam } as HTTP request body with JSON as a response . [CODESPLIT] protected String executeTxtReceiveTxt ( HttpMethod httpMethodParam , List < HeaderNameValue > headerNameValuesParam , boolean checkConnectionValidParam , String stringParam , ContentType contentTypeParam , String postfixUrlParam ) { if ( stringParam == null || stringParam . isEmpty ( ) ) { throw new FluidClientException ( \"No JSON body to post.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } //Check connection... if ( checkConnectionValidParam && ! this . isConnectionValid ( ) ) { throw new FluidClientException ( \"Unable to reach service at '\" + this . endpointUrl . concat ( postfixUrlParam ) + \"'.\" , FluidClientException . ErrorCode . CONNECT_ERROR ) ; } CloseableHttpClient httpclient = this . getClient ( ) ; String responseBody = null ; try { HttpUriRequest uriRequest = null ; //POST... if ( httpMethodParam == HttpMethod . POST ) { //When its html Form Data... if ( contentTypeParam == ContentType . APPLICATION_FORM_URLENCODED ) { RequestBuilder builder = RequestBuilder . post ( ) . setUri ( this . endpointUrl . concat ( postfixUrlParam ) ) ; builder = this . addParamsToBuildFromString ( builder , stringParam ) ; uriRequest = builder . build ( ) ; } else { //JSON or any other... uriRequest = new HttpPost ( this . endpointUrl . concat ( postfixUrlParam ) ) ; } uriRequest . setHeader ( CONTENT_TYPE_HEADER , contentTypeParam . toString ( ) ) ; } else if ( httpMethodParam == HttpMethod . PUT ) { //PUT... if ( contentTypeParam == ContentType . APPLICATION_FORM_URLENCODED ) { RequestBuilder builder = RequestBuilder . put ( ) . setUri ( this . endpointUrl . concat ( postfixUrlParam ) ) ; builder = this . addParamsToBuildFromString ( builder , stringParam ) ; uriRequest = builder . build ( ) ; } else { uriRequest = new HttpPut ( this . endpointUrl . concat ( postfixUrlParam ) ) ; uriRequest . setHeader ( CONTENT_TYPE_HEADER , contentTypeParam . toString ( ) ) ; } } else if ( httpMethodParam == HttpMethod . DELETE ) { //DELETE... uriRequest = new HttpDelete ( this . endpointUrl . concat ( postfixUrlParam ) ) ; uriRequest . setHeader ( CONTENT_TYPE_HEADER , contentTypeParam . toString ( ) ) ; } //Check that the URI request is set. if ( uriRequest == null ) { throw new FluidClientException ( \"URI Request is not set for HTTP Method '\" + httpMethodParam + \"'.\" , FluidClientException . ErrorCode . ILLEGAL_STATE_ERROR ) ; } //Set additional headers... if ( headerNameValuesParam != null && ! headerNameValuesParam . isEmpty ( ) ) { for ( HeaderNameValue headerNameVal : headerNameValuesParam ) { if ( headerNameVal . getName ( ) == null || headerNameVal . getName ( ) . trim ( ) . isEmpty ( ) ) { continue ; } if ( headerNameVal . getValue ( ) == null ) { continue ; } uriRequest . setHeader ( headerNameVal . getName ( ) , headerNameVal . getValue ( ) ) ; } } //When HttpEntity Enclosing Request Base... if ( uriRequest instanceof HttpEntityEnclosingRequestBase ) { HttpEntity httpEntity = new StringEntity ( stringParam , contentTypeParam ) ; ( ( HttpEntityEnclosingRequestBase ) uriRequest ) . setEntity ( httpEntity ) ; } // Create a custom response handler ResponseHandler < String > responseHandler = this . getJsonResponseHandler ( this . endpointUrl . concat ( postfixUrlParam ) ) ; responseBody = this . executeHttp ( httpclient , uriRequest , responseHandler , postfixUrlParam ) ; if ( responseBody == null || responseBody . trim ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"No response data from '\" + this . endpointUrl . concat ( postfixUrlParam ) + \"'.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } return responseBody ; } catch ( FluidClientException fluidClientExcept ) { //Fluid Client Exception... throw fluidClientExcept ; } catch ( Exception otherExcept ) { //Other Exceptions... throw new FluidClientException ( otherExcept . getMessage ( ) , otherExcept , FluidClientException . ErrorCode . ILLEGAL_STATE_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add params to the { @code builderParam } and returns { @code builderParam } . [CODESPLIT] private RequestBuilder addParamsToBuildFromString ( RequestBuilder builderParam , String formDataToAddParam ) { String [ ] nameValuePairs = formDataToAddParam . split ( REGEX_AMP ) ; if ( nameValuePairs . length > 0 ) { for ( String nameValuePair : nameValuePairs ) { String [ ] nameValuePairArr = nameValuePair . split ( REGEX_EQUALS ) ; if ( nameValuePairArr . length > 1 ) { String name = nameValuePairArr [ 0 ] ; String value = nameValuePairArr [ 1 ] ; builderParam = builderParam . addParameter ( name , value ) ; } } } return builderParam ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a text based response handler used mainly for JSON . [CODESPLIT] private ResponseHandler < String > getJsonResponseHandler ( final String urlCalledParam ) { // Create a custom response handler ResponseHandler < String > responseHandler = new ResponseHandler < String > ( ) { /**\n\t\t\t * Process the {@code responseParam} and return text if valid.\n\t\t\t *\n\t\t\t * @param responseParam The HTTP response from the server.\n\t\t\t * @return Text response.\n\t\t\t * @throws IOException If there are any communication or I/O problems.\n\t\t\t */ public String handleResponse ( final HttpResponse responseParam ) throws IOException { int status = responseParam . getStatusLine ( ) . getStatusCode ( ) ; if ( status == 404 ) { throw new FluidClientException ( \"Endpoint for Service not found. URL [\" + urlCalledParam + \"].\" , FluidClientException . ErrorCode . CONNECT_ERROR ) ; } else if ( status >= 200 && status < 300 ) { HttpEntity entity = responseParam . getEntity ( ) ; String responseJsonString = ( entity == null ) ? null : EntityUtils . toString ( entity ) ; return responseJsonString ; } else if ( status == 400 ) { //Bad Request... Server Side Error meant for client... HttpEntity entity = responseParam . getEntity ( ) ; String responseJsonString = ( entity == null ) ? null : EntityUtils . toString ( entity ) ; return responseJsonString ; } else { HttpEntity entity = responseParam . getEntity ( ) ; String responseString = ( entity != null ) ? EntityUtils . toString ( entity ) : null ; throw new FluidClientException ( \"Unexpected response status: \" + status + \". \" + responseParam . getStatusLine ( ) . getReasonPhrase ( ) + \". \\nResponse Text [\" + responseString + \"]\" , FluidClientException . ErrorCode . IO_ERROR ) ; } } } ; return responseHandler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates a string into { @code application / x - www - form - urlencoded } format using a specific encoding scheme . This method uses the supplied encoding scheme to obtain the bytes for unsafe characters . [CODESPLIT] public static String encodeParam ( String textParam ) { if ( textParam == null ) { return null ; } try { return URLEncoder . encode ( textParam , ENCODING_UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a HTTP Get against the connection test Web Service to confirm whether the connection is valid . [CODESPLIT] public boolean isConnectionValid ( ) { //Init the session to get the salt... try { this . getJson ( false , WS . Path . Test . Version1 . testConnection ( ) ) ; } catch ( FluidClientException flowJobExcept ) { //Connect problem... if ( flowJobExcept . getErrorCode ( ) == FluidClientException . ErrorCode . CONNECT_ERROR ) { return false ; } throw flowJobExcept ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspects the { @code baseDomainParam } to confirm whether the base domain is of type { @code Error } . [CODESPLIT] protected boolean isError ( ABaseFluidJSONObject baseDomainParam ) { if ( baseDomainParam == null ) { return false ; } //Must be subclass of error and error code greater than 0... if ( baseDomainParam instanceof Error && ( ( Error ) baseDomainParam ) . getErrorCode ( ) > 0 ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Http client . [CODESPLIT] private CloseableHttpClient getClient ( ) { if ( this . closeableHttpClient != null ) { return this . closeableHttpClient ; } //Only accept self signed certificate if in Junit test case. String pathToFluidTrustStore = this . getPathToFluidSpecificTrustStore ( ) ; //Test mode... if ( IS_IN_JUNIT_TEST_MODE || pathToFluidTrustStore != null ) { SSLContextBuilder builder = new SSLContextBuilder ( ) ; try { //builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); if ( pathToFluidTrustStore == null ) { builder . loadTrustMaterial ( new SSLTrustAll ( ) ) ; } else { String password = this . getFluidSpecificTrustStorePassword ( ) ; if ( password == null ) { password = UtilGlobal . EMPTY ; } if ( IS_IN_JUNIT_TEST_MODE ) { builder . loadTrustMaterial ( new File ( pathToFluidTrustStore ) , password . toCharArray ( ) , new SSLTrustAll ( ) ) ; } else { builder . loadTrustMaterial ( new File ( pathToFluidTrustStore ) , password . toCharArray ( ) ) ; } } SSLContext sslContext = builder . build ( ) ; this . closeableHttpClient = HttpClients . custom ( ) . setSSLSocketFactory ( new SSLConnectionSocketFactory ( sslContext ) ) . build ( ) ; } catch ( NoSuchAlgorithmException e ) { //Changed for Java 1.6 compatibility... throw new FluidClientException ( \"NoSuchAlgorithm: Unable to load self signed trust material. \" + e . getMessage ( ) , e , FluidClientException . ErrorCode . CRYPTOGRAPHY ) ; } catch ( KeyManagementException e ) { throw new FluidClientException ( \"KeyManagement: Unable to load self signed trust material. \" + e . getMessage ( ) , e , FluidClientException . ErrorCode . CRYPTOGRAPHY ) ; } catch ( KeyStoreException e ) { throw new FluidClientException ( \"KeyStore: Unable to load self signed trust material. \" + e . getMessage ( ) , e , FluidClientException . ErrorCode . CRYPTOGRAPHY ) ; } catch ( CertificateException e ) { throw new FluidClientException ( \"Certificate: Unable to load self signed trust material. \" + e . getMessage ( ) , e , FluidClientException . ErrorCode . CRYPTOGRAPHY ) ; } catch ( IOException ioError ) { throw new FluidClientException ( \"IOError: Unable to load self signed trust material. \" + ioError . getMessage ( ) , ioError , FluidClientException . ErrorCode . CRYPTOGRAPHY ) ; } } else { //Default HTTP Client... this . closeableHttpClient = HttpClients . createDefault ( ) ; } return this . closeableHttpClient ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the system property for the Fluid specific trust store . [CODESPLIT] private String getPathToFluidSpecificTrustStore ( ) { String fluidSystemTrustStore = System . getProperty ( SYSTEM_PROP_FLUID_TRUST_STORE ) ; if ( fluidSystemTrustStore == null || fluidSystemTrustStore . trim ( ) . isEmpty ( ) ) { return null ; } File certFile = new File ( fluidSystemTrustStore ) ; if ( certFile . exists ( ) && certFile . isFile ( ) ) { return fluidSystemTrustStore ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the SQL and ElasticSearch Connection but not in a separate { [CODESPLIT] protected void closeConnectionNonThreaded ( ) { if ( this . closeableHttpClient != null ) { try { this . closeableHttpClient . close ( ) ; } catch ( IOException e ) { throw new FluidClientException ( \"Unable to close Http Client connection. \" + e . getMessage ( ) , e , FluidClientException . ErrorCode . IO_ERROR ) ; } } this . closeableHttpClient = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close the SQL Connection . [CODESPLIT] public void closeConnection ( ) { if ( this . connection == null ) { return ; } try { if ( this . connection . isClosed ( ) ) { return ; } this . connection . close ( ) ; } catch ( SQLException sqlExcept ) { throw new FluidSQLException ( sqlExcept ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves SQLType from the local { @code Connection } . [CODESPLIT] public SQLServerType getSQLTypeFromConnection ( ) { try { if ( this . databaseMetaData == null ) { this . databaseMetaData = this . getConnection ( ) . getMetaData ( ) ; } return SQLServerType . getSQLTypeFromProductName ( this . databaseMetaData . getDatabaseProductName ( ) ) ; } catch ( SQLException sqlExcept ) { //Unable to retrieve the product name. throw new FluidSQLException ( sqlExcept ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the { @code preparedStatementParam } and { @code resultSetParam } . [CODESPLIT] protected void closeStatement ( PreparedStatement preparedStatementParam , ResultSet resultSetParam ) { if ( resultSetParam == null ) { this . closeStatement ( preparedStatementParam ) ; return ; } try { resultSetParam . close ( ) ; this . closeStatement ( preparedStatementParam ) ; } catch ( SQLException sqlExcept ) { throw new FluidSQLException ( sqlExcept ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the { @code preparedStatementParam } . [CODESPLIT] protected void closeStatement ( PreparedStatement preparedStatementParam ) { if ( preparedStatementParam == null ) { return ; } try { preparedStatementParam . close ( ) ; } catch ( SQLException sqlExcept ) { throw new FluidSQLException ( sqlExcept ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the Form Container by Primary key . [CODESPLIT] public FluidItem getFluidItemByFormId ( Long formIdParam ) { Form form = new Form ( formIdParam ) ; if ( this . serviceTicket != null ) { form . setServiceTicket ( this . serviceTicket ) ; } return new FluidItem ( this . postJson ( form , WS . Path . FlowItem . Version1 . getByForm ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Fluid Item that will be sent to the { @code flowJobItemParam } Flow . [CODESPLIT] public FluidItem createFlowItem ( FluidItem flowJobItemParam , String flowNameParam ) { if ( flowJobItemParam != null && this . serviceTicket != null ) { flowJobItemParam . setServiceTicket ( this . serviceTicket ) ; } //Flow Job Item Step etc... if ( flowJobItemParam != null ) { flowJobItemParam . setFlow ( flowNameParam ) ; } try { return new FluidItem ( this . putJson ( flowJobItemParam , WS . Path . FlowItem . Version1 . flowItemCreate ( ) ) ) ; } // catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves items for the provided JobView . [CODESPLIT] public FluidItemListing getFluidItemsForView ( JobView jobViewParam , int queryLimitParam , int offsetParam , String sortFieldParam , String sortOrderParam ) { if ( this . serviceTicket != null && jobViewParam != null ) { jobViewParam . setServiceTicket ( this . serviceTicket ) ; } try { return new FluidItemListing ( this . postJson ( jobViewParam , WS . Path . FlowItem . Version1 . getByJobView ( queryLimitParam , offsetParam , sortFieldParam , sortOrderParam ) ) ) ; } //rethrow as a Fluid Client exception. catch ( JSONException jsonExcept ) { throw new FluidClientException ( jsonExcept . getMessage ( ) , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a workflow item currently in an { @code Assignment } step to [CODESPLIT] public FluidItem sendFlowItemOn ( FluidItem flowJobItemParam , boolean allowCollaboratorToSendOnParam ) { if ( flowJobItemParam != null && this . serviceTicket != null ) { flowJobItemParam . setServiceTicket ( this . serviceTicket ) ; } try { return new FluidItem ( this . postJson ( flowJobItemParam , WS . Path . FlowItem . Version1 . sendFlowItemOn ( allowCollaboratorToSendOnParam ) ) ) ; } catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a form item to be part of a workflow . [CODESPLIT] public FluidItem sendFormToFlow ( Form formToSendToFlowParam , String flowParam ) { FluidItem itemToSend = new FluidItem ( ) ; itemToSend . setForm ( formToSendToFlowParam ) ; itemToSend . setFlow ( flowParam ) ; if ( this . serviceTicket != null ) { itemToSend . setServiceTicket ( this . serviceTicket ) ; } try { return new FluidItem ( this . postJson ( itemToSend , WS . Path . FlowItem . Version1 . sendFlowItemToFlow ( ) ) ) ; } catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback hook for Connection close events . [CODESPLIT] @ OnClose public void onClose ( Session userSessionParam , CloseReason reasonParam ) { this . userSession = null ; if ( this . messageHandlers != null ) { this . messageHandlers . values ( ) . forEach ( handle -> { handle . connectionClosed ( ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback hook for Message Events . This method will be invoked when a client sends a message . [CODESPLIT] @ OnMessage public void onMessage ( String messageParam ) { boolean handlerFoundForMsg = false ; for ( IMessageResponseHandler handler : new ArrayList <> ( this . messageHandlers . values ( ) ) ) { Object qualifyObj = handler . doesHandlerQualifyForProcessing ( messageParam ) ; if ( qualifyObj instanceof Error ) { handler . handleMessage ( qualifyObj ) ; } else if ( qualifyObj instanceof JSONObject ) { handler . handleMessage ( qualifyObj ) ; handlerFoundForMsg = true ; break ; } } if ( ! handlerFoundForMsg ) { throw new FluidClientException ( \"No handler found for message;\\n\" + messageParam , FluidClientException . ErrorCode . IO_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a message . [CODESPLIT] public void sendMessage ( ABaseFluidJSONObject aBaseFluidJSONObjectParam ) { if ( aBaseFluidJSONObjectParam == null ) { throw new FluidClientException ( \"No JSON Object to send.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } else { this . sendMessage ( aBaseFluidJSONObjectParam . toJsonObject ( ) . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a message as text . [CODESPLIT] public void sendMessage ( String messageToSendParam ) { if ( this . userSession == null ) { throw new FluidClientException ( \"User Session is not set. Check if connection is open.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } RemoteEndpoint . Async asyncRemote = null ; if ( ( asyncRemote = this . userSession . getAsyncRemote ( ) ) == null ) { throw new FluidClientException ( \"Remote Session is not set. Check if connection is open.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } asyncRemote . sendText ( messageToSendParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the Web Socket User session . [CODESPLIT] public void closeSession ( ) { if ( this . userSession == null ) { return ; } try { this . userSession . close ( ) ; } catch ( IOException e ) { throw new FluidClientException ( \"Unable to close session. \" + e . getMessage ( ) , e , FluidClientException . ErrorCode . IO_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Base { @code toJsonObject } that creates a { @code JSONObject } with the Id and ServiceTicket set . < / p > [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; returnVal . put ( JSONMapping . ERROR_CODE , this . getErrorCode ( ) ) ; returnVal . put ( JSONMapping . ERROR_CODE_OTHER , this . getErrorCode ( ) ) ; //Error Message... if ( this . getErrorMessage ( ) != null ) { returnVal . put ( JSONMapping . ERROR_MESSAGE , this . getErrorMessage ( ) ) ; returnVal . put ( JSONMapping . ERROR_MESSAGE_OTHER , this . getErrorMessage ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the Ancestors ( Forms ) for the { @code formToGetAncestorsForForParam } . [CODESPLIT] public List < FormFieldListing > getFormFieldsSynchronized ( Form ... formsToGetFieldListingForForParam ) { if ( formsToGetFieldListingForForParam == null ) { return null ; } if ( formsToGetFieldListingForForParam . length == 0 ) { return null ; } //Start a new request... String uniqueReqId = this . initNewRequest ( ) ; //Send all the messages... int numberOfSentForms = 0 ; for ( Form formToSend : formsToGetFieldListingForForParam ) { this . setEchoIfNotSet ( formToSend ) ; //Send the actual message... this . sendMessage ( formToSend , uniqueReqId ) ; numberOfSentForms ++ ; } try { List < FormFieldListing > returnValue = this . getHandler ( uniqueReqId ) . getCF ( ) . get ( this . getTimeoutInMillis ( ) , TimeUnit . MILLISECONDS ) ; //Connection was closed.. this is a problem.... if ( this . getHandler ( uniqueReqId ) . isConnectionClosed ( ) ) { throw new FluidClientException ( \"SQLUtil-WebSocket-GetFormFields: \" + \"The connection was closed by the server prior to the response received.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } return returnValue ; } catch ( InterruptedException exceptParam ) { //Interrupted... throw new FluidClientException ( \"SQLUtil-WebSocket-Interrupted-GetFormFields: \" + exceptParam . getMessage ( ) , exceptParam , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } catch ( ExecutionException executeProblem ) { //Error on the web-socket... Throwable cause = executeProblem . getCause ( ) ; //Fluid client exception... if ( cause instanceof FluidClientException ) { throw ( FluidClientException ) cause ; } else { throw new FluidClientException ( \"SQLUtil-WebSocket-GetFormFields: \" + cause . getMessage ( ) , cause , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } } catch ( TimeoutException eParam ) { //Timeout... String errMessage = this . getExceptionMessageVerbose ( \"SQLUtil-WebSocket-GetFormFields\" , uniqueReqId , numberOfSentForms ) ; throw new FluidClientException ( errMessage , FluidClientException . ErrorCode . IO_ERROR ) ; } finally { this . removeHandler ( uniqueReqId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Rule Executed... if ( this . getRuleExecuted ( ) != null ) { returnVal . put ( JSONMapping . RULE_EXECUTED , this . getRuleExecuted ( ) ) ; } //Rule Executed Result... if ( this . getRuleExecutedResult ( ) != null ) { returnVal . put ( JSONMapping . RULE_EXECUTED_RESULT , this . getRuleExecutedResult ( ) ) ; } //Rule Order... if ( this . getFlowRuleOrder ( ) != null ) { returnVal . put ( JSONMapping . FLOW_RULE_ORDER , this . getFlowRuleOrder ( ) ) ; } //Log Entry Type... if ( this . getLogEntryType ( ) != null ) { returnVal . put ( JSONMapping . LOG_ENTRY_TYPE , this . getLogEntryType ( ) ) ; } //User... if ( this . getUser ( ) != null ) { returnVal . put ( JSONMapping . USER , this . getUser ( ) . toJsonObject ( ) ) ; } //Flow Step... if ( this . getFlowStep ( ) != null ) { returnVal . put ( JSONMapping . FLOW_STEP , this . getFlowStep ( ) . toJsonObject ( ) ) ; } //Form... if ( this . getForm ( ) != null ) { returnVal . put ( JSONMapping . FORM , this . getForm ( ) . toJsonObject ( ) ) ; } //Job View... if ( this . getJobView ( ) != null ) { returnVal . put ( JSONMapping . JOB_VIEW , this . getJobView ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a native SQL query on the remote Fluid instance . [CODESPLIT] public List < SQLResultSet > executeNativeSQLSynchronized ( NativeSQLQuery nativeSQLQueryParam ) { if ( nativeSQLQueryParam == null ) { return null ; } if ( nativeSQLQueryParam . getDatasourceName ( ) == null || nativeSQLQueryParam . getDatasourceName ( ) . isEmpty ( ) ) { throw new FluidClientException ( \"No data-source name provided. Not allowed.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } //No query to execute... if ( ( nativeSQLQueryParam . getQuery ( ) == null || nativeSQLQueryParam . getQuery ( ) . isEmpty ( ) ) && ( nativeSQLQueryParam . getStoredProcedure ( ) == null || nativeSQLQueryParam . getStoredProcedure ( ) . isEmpty ( ) ) ) { return null ; } //Validate the echo... this . setEchoIfNotSet ( nativeSQLQueryParam ) ; //Start a new request... String uniqueReqId = this . initNewRequest ( ) ; //Send the actual message... this . sendMessage ( nativeSQLQueryParam , uniqueReqId ) ; try { List < SQLResultSet > returnValue = this . getHandler ( uniqueReqId ) . getCF ( ) . get ( this . getTimeoutInMillis ( ) , TimeUnit . MILLISECONDS ) ; //Connection was closed.. this is a problem.... if ( this . getHandler ( uniqueReqId ) . isConnectionClosed ( ) ) { throw new FluidClientException ( \"SQLUtil-WebSocket-ExecuteNativeSQL: \" + \"The connection was closed by the server prior to the response received.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } return returnValue ; } //Interrupted... catch ( InterruptedException exceptParam ) { throw new FluidClientException ( \"SQLUtil-WebSocket-ExecuteNativeSQL: \" + exceptParam . getMessage ( ) , exceptParam , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } //Error on the web-socket... catch ( ExecutionException executeProblem ) { Throwable cause = executeProblem . getCause ( ) ; //Fluid client exception... if ( cause instanceof FluidClientException ) { throw ( FluidClientException ) cause ; } else { throw new FluidClientException ( \"SQLUtil-WebSocket-ExecuteNativeSQL: \" + cause . getMessage ( ) , cause , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } } //Timeout... catch ( TimeoutException eParam ) { throw new FluidClientException ( \"SQLUtil-WebSocket-ExecuteNativeSQL: Timeout while waiting for all return data. There were '\" + this . getHandler ( uniqueReqId ) . getReturnValue ( ) . size ( ) + \"' items after a Timeout of \" + ( TimeUnit . MILLISECONDS . toSeconds ( this . getTimeoutInMillis ( ) ) ) + \" seconds.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } finally { this . removeHandler ( uniqueReqId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the single instance of the { @code SyntaxFactory } . [CODESPLIT] public static SyntaxFactory getInstance ( ) { if ( SyntaxFactory . syntaxFactory == null ) { SyntaxFactory . syntaxFactory = new SyntaxFactory ( ) ; } return SyntaxFactory . syntaxFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code ISyntax } from the { @code sqlTypeParam } and { @code aliasParam } . [CODESPLIT] public ISyntax getSyntaxFor ( ABaseSQLUtil . SQLServerType sqlTypeParam , String aliasParam ) { if ( ISyntax . ProcedureMapping . isStoredProcedureMapping ( aliasParam ) ) { return new StoredProcedureSyntax ( aliasParam , ISyntax . ProcedureMapping . getParamCountForAlias ( aliasParam ) ) ; } throw new FluidSQLException ( new SQLException ( \"Unable to find Syntax for alias '\" + aliasParam + \"' and SQL Type '\" + sqlTypeParam + \"'.\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code ISyntax } from the { @code sqlTypeParam } and { @code formFieldMappingParam } . [CODESPLIT] public ISyntax getFieldValueSyntaxFor ( ABaseSQLUtil . SQLServerType sqlTypeParam , SQLFormFieldUtil . FormFieldMapping formFieldMappingParam ) { Long dataType = formFieldMappingParam . dataType ; if ( dataType == null ) { return null ; } switch ( dataType . intValue ( ) ) { case UtilGlobal . FieldTypeId . _1_TEXT : return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldValue_1_Text ) ; case UtilGlobal . FieldTypeId . _2_TRUE_FALSE : return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldValue_2_TrueFalse ) ; case UtilGlobal . FieldTypeId . _3_PARAGRAPH_TEXT : return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldValue_3_ParagraphText ) ; case UtilGlobal . FieldTypeId . _4_MULTI_CHOICE : if ( this . isPlain ( formFieldMappingParam . metaData ) ) { return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldValue_4_MultiChoice ) ; } else if ( this . isSelectMany ( formFieldMappingParam . metaData ) ) { return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldMultipleValue_4_MultiChoice ) ; } else { throw new FluidSQLException ( new SQLException ( \"Data Type '\" + dataType + \"' does not support '\" + formFieldMappingParam . metaData + \"'.\" ) ) ; } case UtilGlobal . FieldTypeId . _5_DATE_TIME : return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldValue_5_DateTime ) ; case UtilGlobal . FieldTypeId . _6_DECIMAL : return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldValue_6_Decimal ) ; case UtilGlobal . FieldTypeId . _7_TABLE_FIELD : return this . getSyntaxFor ( sqlTypeParam , ISyntax . ProcedureMapping . Field . GetFormFieldValue_7_TableField ) ; case UtilGlobal . FieldTypeId . _8_TEXT_ENCRYPTED : case UtilGlobal . FieldTypeId . _9_LABEL : return null ; default : throw new FluidSQLException ( new SQLException ( \"Data Type '\" + dataType + \"' is not supported.\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether { @code textToCheckParam } is Plain . [CODESPLIT] private boolean isPlain ( String textToCheckParam ) { if ( textToCheckParam == null || textToCheckParam . trim ( ) . isEmpty ( ) ) { return false ; } String toCheckLower = textToCheckParam . toLowerCase ( ) ; return toCheckLower . startsWith ( PLAIN . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether { @code textToCheckParam } is Select Many . [CODESPLIT] private boolean isSelectMany ( String textToCheckParam ) { if ( textToCheckParam == null || textToCheckParam . trim ( ) . isEmpty ( ) ) { return false ; } String toCheckLower = textToCheckParam . toLowerCase ( ) ; return toCheckLower . startsWith ( SELECT_MANY . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //SQL Columns... if ( this . getSqlColumns ( ) != null ) { JSONArray jsonArray = new JSONArray ( ) ; for ( SQLColumn toAdd : this . getSqlColumns ( ) ) { jsonArray . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . SQL_COLUMNS , jsonArray ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Name... if ( this . getName ( ) != null ) { returnVal . put ( JSONMapping . NAME , this . getName ( ) ) ; } //Value... if ( this . getValue ( ) != null ) { returnVal . put ( JSONMapping . VALUE , this . getValue ( ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Request a new license based on the license request input . [CODESPLIT] public String requestLicense ( LicenseRequest licenseRequestParam ) { if ( licenseRequestParam != null && this . serviceTicket != null ) { licenseRequestParam . setServiceTicket ( this . serviceTicket ) ; } return this . executeTxtReceiveTxt ( HttpMethod . POST , null , false , ( licenseRequestParam == null ) ? null : licenseRequestParam . toJsonObject ( ) . toString ( ) , ContentType . APPLICATION_JSON , Version1 . licenseRequest ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a generated license for the server . [CODESPLIT] public LicenseRequest applyLicense ( String licenseToApplyParam ) { LicenseRequest liceReq = new LicenseRequest ( ) ; liceReq . setLicenseCipherText ( licenseToApplyParam ) ; if ( this . serviceTicket != null ) { liceReq . setServiceTicket ( this . serviceTicket ) ; } return new LicenseRequest ( this . postJson ( liceReq , Version1 . licenseApply ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Name... if ( this . getName ( ) != null ) { returnVal . put ( JSONMapping . NAME , this . getName ( ) ) ; } //Description... if ( this . getDescription ( ) != null ) { returnVal . put ( JSONMapping . DESCRIPTION , this . getDescription ( ) ) ; } //Inputs... if ( this . getInputs ( ) != null ) { JSONArray jsonArray = new JSONArray ( ) ; for ( Field toAdd : this . getInputs ( ) ) { jsonArray . put ( toAdd . toJsonObject ( ) ) ; } returnVal . put ( JSONMapping . INPUTS , jsonArray ) ; } //Rules... if ( this . getRules ( ) != null ) { JSONArray jsonArray = new JSONArray ( ) ; for ( String toAdd : this . getRules ( ) ) { jsonArray . put ( toAdd ) ; } returnVal . put ( JSONMapping . RULES , jsonArray ) ; } //Date Created... if ( this . getDateCreated ( ) != null ) { returnVal . put ( JSONMapping . DATE_CREATED , this . getDateAsLongFromJson ( this . getDateCreated ( ) ) ) ; } //Date Last Updated... if ( this . getDateLastUpdated ( ) != null ) { returnVal . put ( JSONMapping . DATE_LAST_UPDATED , this . getDateAsLongFromJson ( this . getDateLastUpdated ( ) ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Plain Text field . [CODESPLIT] public Field createFieldTextPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . Text ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . Text . PLAIN ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new True False field . [CODESPLIT] public Field createFieldTrueFalse ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . TrueFalse ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . TrueFalse . TRUE_FALSE ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Paragraph Text field . [CODESPLIT] public Field createFieldParagraphTextPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . PLAIN ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Paragraph HTML field . [CODESPLIT] public Field createFieldParagraphTextHTML ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . HTML ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Multi Choice field . [CODESPLIT] public Field createFieldMultiChoicePlain ( Field routeFieldParam , List < String > multiChoiceValuesParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( multiChoiceValuesParam == null ) { multiChoiceValuesParam = new ArrayList ( ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . MultipleChoice ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . MultiChoice . PLAIN ) ; routeFieldParam . setFieldValue ( new MultiChoice ( multiChoiceValuesParam ) ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Multi Choice select Many field . [CODESPLIT] public Field createFieldMultiChoiceSelectMany ( Field routeFieldParam , List < String > multiChoiceValuesParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( multiChoiceValuesParam == null || multiChoiceValuesParam . isEmpty ( ) ) { throw new FluidClientException ( \"No Multi-choice values provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . MultipleChoice ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . MultiChoice . SELECT_MANY ) ; routeFieldParam . setFieldValue ( new MultiChoice ( multiChoiceValuesParam ) ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Date only field . [CODESPLIT] public Field createFieldDateTimeDate ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Date and time field . [CODESPLIT] public Field createFieldDateTimeDateAndTime ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE_AND_TIME ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Decimal field . [CODESPLIT] public Field createFieldDecimalPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . Decimal . PLAIN ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Text field . [CODESPLIT] public Field updateFieldTextPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . Text ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . Text . PLAIN ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing True False field . [CODESPLIT] public Field updateFieldTrueFalse ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . TrueFalse ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . TrueFalse . TRUE_FALSE ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Paragraph Text field . [CODESPLIT] public Field updateFieldParagraphTextPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . PLAIN ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Paragraph HTML field . [CODESPLIT] public Field updateFieldParagraphTextHTML ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . HTML ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Multi Choice field . [CODESPLIT] public Field updateFieldMultiChoicePlain ( Field routeFieldParam , List < String > multiChoiceValuesParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( multiChoiceValuesParam == null || multiChoiceValuesParam . isEmpty ( ) ) { throw new FluidClientException ( \"No Multi-choice values provided.\" , FluidClientException . ErrorCode . FIELD_VALIDATE ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . MultipleChoice ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . MultiChoice . PLAIN ) ; routeFieldParam . setFieldValue ( new MultiChoice ( multiChoiceValuesParam ) ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Date field . [CODESPLIT] public Field updateFieldDateTimeDate ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Date and Time field . [CODESPLIT] public Field updateFieldDateTimeDateAndTime ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE_AND_TIME ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Decimal field . [CODESPLIT] public Field updateFieldDecimalPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . Decimal . PLAIN ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update an existing Route field value . [CODESPLIT] public Field updateFieldValue ( Field routeFieldValueParam ) { if ( routeFieldValueParam != null && this . serviceTicket != null ) { routeFieldValueParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( routeFieldValueParam , Version1 . routeFieldUpdateValue ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an new Route field value . [CODESPLIT] public Field createFieldValue ( Field routeFieldValueToCreateParam , FluidItem fluidItemParam ) { if ( routeFieldValueToCreateParam != null && this . serviceTicket != null ) { routeFieldValueToCreateParam . setServiceTicket ( this . serviceTicket ) ; } Long fluidItmId = ( fluidItemParam == null ) ? null : fluidItemParam . getId ( ) ; return new Field ( this . putJson ( routeFieldValueToCreateParam , Version1 . routeFieldCreateValue ( fluidItmId ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves field information by { @code fieldIdParam } . [CODESPLIT] public Field getFieldById ( Long fieldIdParam ) { Field field = new Field ( fieldIdParam ) ; //Set for Payara server... field . setFieldValue ( new MultiChoice ( ) ) ; if ( this . serviceTicket != null ) { field . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( field , Version1 . getById ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the Route field values for { @code fluidItemParam } . [CODESPLIT] public List < Field > getRouteFieldValuesBy ( FluidItem fluidItemParam ) { if ( this . serviceTicket != null && fluidItemParam != null ) { fluidItemParam . setServiceTicket ( this . serviceTicket ) ; } return new RouteFieldListing ( this . postJson ( fluidItemParam , Version1 . getValuesBy ( ) ) ) . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes a field from Fluid . [CODESPLIT] public Field deleteField ( Field fieldParam ) { if ( fieldParam != null && this . serviceTicket != null ) { fieldParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( fieldParam , Version1 . routeFieldDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forcefully Deletes a field from Fluid . [CODESPLIT] public Field forceDeleteField ( Field fieldParam ) { if ( fieldParam != null && this . serviceTicket != null ) { fieldParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( fieldParam , Version1 . routeFieldDelete ( true ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert the { @code SQLFormFieldUtil . FormFieldMapping } to { @code Field } . [CODESPLIT] @ XmlTransient public List < Field > convertTo ( List < SQLFormFieldUtil . FormFieldMapping > formFieldMappingsParam ) { if ( formFieldMappingsParam == null ) { return null ; } List < Field > returnVal = new ArrayList ( ) ; for ( SQLFormFieldUtil . FormFieldMapping mappingToConvert : formFieldMappingsParam ) { returnVal . add ( this . convertTo ( mappingToConvert ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to convert from a { @code SQLFormFieldUtil . FormFieldMapping } to a { @code Field } . [CODESPLIT] @ XmlTransient public Field convertTo ( SQLFormFieldUtil . FormFieldMapping formFieldMappingParam ) { switch ( formFieldMappingParam . dataType . intValue ( ) ) { //Text... case UtilGlobal . FieldTypeId . _1_TEXT : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , null , Field . Type . Text ) ; //True False... case UtilGlobal . FieldTypeId . _2_TRUE_FALSE : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , null , Field . Type . TrueFalse ) ; //Paragraph Text... case UtilGlobal . FieldTypeId . _3_PARAGRAPH_TEXT : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , null , Field . Type . ParagraphText ) ; //Multiple Choice... case UtilGlobal . FieldTypeId . _4_MULTI_CHOICE : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , null , Field . Type . MultipleChoice ) ; //Date Time... case UtilGlobal . FieldTypeId . _5_DATE_TIME : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , null , Field . Type . DateTime ) ; //Decimal... case UtilGlobal . FieldTypeId . _6_DECIMAL : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , null , Field . Type . Decimal ) ; //Table Field... case UtilGlobal . FieldTypeId . _7_TABLE_FIELD : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , null , Field . Type . Table ) ; //TODO __8__ encrypted field... //Label... case UtilGlobal . FieldTypeId . _9_LABEL : return new Field ( formFieldMappingParam . formFieldId , formFieldMappingParam . name , formFieldMappingParam . description , Field . Type . Label ) ; default : throw new IllegalStateException ( \"Unable to map '\" + formFieldMappingParam . dataType . intValue ( ) + \"', to Form Field value.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a Configuration by Key . [CODESPLIT] public Configuration getConfigurationByKey ( String configurationKeyParam ) { Configuration configuration = new Configuration ( ) ; configuration . setKey ( configurationKeyParam ) ; if ( this . serviceTicket != null ) { configuration . setServiceTicket ( this . serviceTicket ) ; } return new Configuration ( this . postJson ( configuration , WS . Path . Configuration . Version1 . getByKey ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all Configurations . [CODESPLIT] public ConfigurationListing getAllConfigurations ( ) { Configuration configuration = new Configuration ( ) ; if ( this . serviceTicket != null ) { configuration . setServiceTicket ( this . serviceTicket ) ; } return new ConfigurationListing ( this . postJson ( configuration , WS . Path . Configuration . Version1 . getAllConfigurations ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Conversion to { @code JSONObject } from Java Object . [CODESPLIT] @ Override public JSONObject toJsonObject ( ) throws JSONException { JSONObject returnVal = super . toJsonObject ( ) ; //Machine Name... if ( this . getMachineName ( ) != null ) { returnVal . put ( JSONMapping . MACHINE_NAME , this . getMachineName ( ) ) ; } //Cipher Text... if ( this . getLicenseCipherText ( ) != null ) { returnVal . put ( JSONMapping . LICENSE_CIPHER_TEXT , this . getLicenseCipherText ( ) ) ; } //License Type... if ( this . getLicenseType ( ) != null ) { returnVal . put ( JSONMapping . LICENSE_TYPE , this . getLicenseType ( ) ) ; } //User Count... if ( this . getUserCount ( ) != null ) { returnVal . put ( JSONMapping . USER_COUNT , this . getUserCount ( ) ) ; } //Date Valid From... if ( this . getDateValidFrom ( ) != null ) { returnVal . put ( JSONMapping . DATE_VALID_FROM , this . getDateAsLongFromJson ( this . getDateValidFrom ( ) ) ) ; } //Date Valid To... if ( this . getDateValidTo ( ) != null ) { returnVal . put ( JSONMapping . DATE_VALID_TO , this . getDateAsLongFromJson ( this . getDateValidTo ( ) ) ) ; } return returnVal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new ( Form ) for the { @code formToCreateParam } . [CODESPLIT] public Form createFormContainerSynchronized ( Form formToCreateParam ) { if ( formToCreateParam == null ) { return null ; } //Send all the messages... if ( formToCreateParam . getEcho ( ) == null || formToCreateParam . getEcho ( ) . trim ( ) . isEmpty ( ) ) { formToCreateParam . setEcho ( UUID . randomUUID ( ) . toString ( ) ) ; } //Start a new request... String uniqueReqId = this . initNewRequest ( ) ; //Send the actual message... this . sendMessage ( formToCreateParam , uniqueReqId ) ; try { List < Form > returnValue = this . getHandler ( uniqueReqId ) . getCF ( ) . get ( this . getTimeoutInMillis ( ) , TimeUnit . MILLISECONDS ) ; //Connection was closed.. this is a problem.... if ( this . getHandler ( uniqueReqId ) . isConnectionClosed ( ) ) { throw new FluidClientException ( \"WebSocket-CreateFormContainer: \" + \"The connection was closed by the server prior to the response received.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } if ( returnValue == null || returnValue . isEmpty ( ) ) { return null ; } return returnValue . get ( 0 ) ; } //Interrupted... catch ( InterruptedException exceptParam ) { throw new FluidClientException ( \"WebSocket-Interrupted-CreateFormContainer: \" + exceptParam . getMessage ( ) , exceptParam , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } //Error on the web-socket... catch ( ExecutionException executeProblem ) { Throwable cause = executeProblem . getCause ( ) ; //Fluid client exception... if ( cause instanceof FluidClientException ) { throw ( FluidClientException ) cause ; } else { throw new FluidClientException ( \"WebSocket-CreateFormContainer: \" + cause . getMessage ( ) , cause , FluidClientException . ErrorCode . STATEMENT_EXECUTION_ERROR ) ; } } //Timeout... catch ( TimeoutException eParam ) { throw new FluidClientException ( \"WebSocket-CreateFormContainer: Timeout while waiting for all return data. There were '\" + this . getHandler ( uniqueReqId ) . getReturnValue ( ) . size ( ) + \"' items after a Timeout of \" + ( TimeUnit . MILLISECONDS . toSeconds ( this . getTimeoutInMillis ( ) ) ) + \" seconds.\" , FluidClientException . ErrorCode . IO_ERROR ) ; } finally { this . removeHandler ( uniqueReqId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a comma seperated list of providers from { @code Identity } s . [CODESPLIT] public String getListOfProvidersFromIdentities ( ) { if ( this . getIdentities ( ) == null || this . getIdentities ( ) . isEmpty ( ) ) { return \"\" ; } StringBuilder returnVal = new StringBuilder ( ) ; for ( Client client : this . getIdentities ( ) ) { returnVal . append ( client . getProvider ( ) ) ; returnVal . append ( \",\" ) ; } String toString = returnVal . toString ( ) ; return toString . substring ( 0 , toString . length ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uploads a new Attachment . If there is an existing attachment with the same name a new version will be uploaded . [CODESPLIT] public Attachment createAttachment ( Attachment attachmentParam ) { if ( attachmentParam != null && this . serviceTicket != null ) { attachmentParam . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . putJson ( attachmentParam , WS . Path . Attachment . Version1 . attachmentCreate ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a Attachment by Primary Key . [CODESPLIT] public Attachment getAttachmentById ( Long attachmentIdParam , boolean includeAttachmentDataParam ) { Attachment attachment = new Attachment ( attachmentIdParam ) ; if ( this . serviceTicket != null ) { attachment . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . postJson ( attachment , WS . Path . Attachment . Version1 . getById ( includeAttachmentDataParam ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves all the Attachments associated with Form { @code formParam } . [CODESPLIT] public List < Attachment > getAttachmentsByForm ( Form formParam , boolean includeAttachmentDataParam ) { if ( formParam != null && this . serviceTicket != null ) { formParam . setServiceTicket ( this . serviceTicket ) ; } AttachmentListing returnedListing = new AttachmentListing ( postJson ( formParam , WS . Path . Attachment . Version1 . getAllByFormContainer ( includeAttachmentDataParam , false ) ) ) ; return ( returnedListing == null ) ? null : returnedListing . getListing ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an existing Attachment . [CODESPLIT] public Attachment deleteAttachment ( Attachment attachmentParam ) { if ( attachmentParam != null && this . serviceTicket != null ) { attachmentParam . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . postJson ( attachmentParam , WS . Path . Attachment . Version1 . attachmentDelete ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forcefully Delete an existing Attachment . [CODESPLIT] public Attachment forceDeleteAttachment ( Attachment attachmentParam ) { if ( attachmentParam != null && this . serviceTicket != null ) { attachmentParam . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . postJson ( attachmentParam , WS . Path . Attachment . Version1 . attachmentDelete ( true ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two different objects of this type . [CODESPLIT] public static boolean hasDifferentValue ( XsdStringRestrictions o1 , XsdStringRestrictions o2 ) { if ( o1 == null && o2 == null ) { return false ; } String o1Value = null ; String o2Value ; if ( o1 != null ) { o1Value = o1 . getValue ( ) ; } if ( o2 != null ) { o2Value = o2 . getValue ( ) ; return o2Value . equals ( o1Value ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to match the received { [CODESPLIT] public void replaceUnsolvedAttributes ( NamedConcreteElement element ) { if ( element . getElement ( ) instanceof XsdAttributeGroup ) { attributeGroups . stream ( ) . filter ( attributeGroup -> attributeGroup instanceof UnsolvedReference && ( ( UnsolvedReference ) attributeGroup ) . getRef ( ) . equals ( element . getName ( ) ) ) . findFirst ( ) . ifPresent ( referenceBase -> { attributeGroups . remove ( referenceBase ) ; attributeGroups . add ( element ) ; attributes . addAll ( element . getElement ( ) . getElements ( ) ) ; element . getElement ( ) . setParent ( getOwner ( ) ) ; } ) ; } if ( element . getElement ( ) instanceof XsdAttribute ) { attributes . stream ( ) . filter ( attribute -> attribute instanceof UnsolvedReference && ( ( UnsolvedReference ) attribute ) . getRef ( ) . equals ( element . getName ( ) ) ) . findFirst ( ) . ifPresent ( referenceBase -> { attributes . remove ( referenceBase ) ; attributes . add ( element ) ; element . getElement ( ) . setParent ( getOwner ( ) ) ; } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces possible { [CODESPLIT] @ Override public void replaceUnsolvedElements ( NamedConcreteElement elementWrapper ) { if ( elementWrapper . getElement ( ) instanceof XsdElement ) { super . replaceUnsolvedElements ( elementWrapper ) ; } if ( elementWrapper . getElement ( ) instanceof XsdGroup ) { elements . add ( elementWrapper ) ; this . elements . removeIf ( element -> element instanceof UnsolvedReference && ( ( UnsolvedReference ) element ) . getRef ( ) . equals ( elementWrapper . getName ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the XSD file represented by the received InputStream . [CODESPLIT] private void parseJarFile ( InputStream inputStream ) { //https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ try { Node schemaNode = getSchemaNode ( inputStream ) ; if ( isXsdSchema ( schemaNode ) ) { XsdSchema . parse ( this , schemaNode ) ; } else { throw new ParsingException ( \"The top level element of a XSD file should be the xsd:schema node.\" ) ; } } catch ( SAXException | IOException | ParserConfigurationException e ) { Logger . getAnonymousLogger ( ) . log ( Level . SEVERE , \"Exception while parsing.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new class loader replacing the current one having another path added to the classpath . The new path is the path to the jar received in this class constructor . [CODESPLIT] private void setClassLoader ( String jarPath ) { if ( ! jarPath . endsWith ( \".jar\" ) ) { throw new ParsingException ( \"The jarPath received doesn't represent a jar file.\" ) ; } ClassLoader originalCl = Thread . currentThread ( ) . getContextClassLoader ( ) ; URL url = originalCl . getResource ( jarPath ) ; if ( url == null ) { try { url = new URL ( \"file:/\" + jarPath ) ; } catch ( MalformedURLException e ) { throw new ParsingException ( \"Invalid jar name.\" ) ; } } // Create class loader using given codebase // Use prevCl as parent to maintain current visibility ClassLoader urlCl = URLClassLoader . newInstance ( new URL [ ] { url } , originalCl ) ; Thread . currentThread ( ) . setContextClassLoader ( urlCl ) ; classLoader = urlCl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to parse { [CODESPLIT] static ReferenceBase xsdAnnotationChildrenParse ( Node node , XsdAnnotationChildren annotationChildren ) { annotationChildren . content = xsdRawContentParse ( node ) ; return ReferenceBase . createFromXsd ( annotationChildren ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if a given { [CODESPLIT] boolean isXsdSchema ( Node node ) { String schemaNodeName = node . getNodeName ( ) ; return schemaNodeName . equals ( XsdSchema . XSD_TAG ) || schemaNodeName . equals ( XsdSchema . XS_TAG ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method resolves all the remaining { [CODESPLIT] void resolveRefs ( ) { Map < String , List < NamedConcreteElement > > concreteElementsMap = parseElements . stream ( ) . filter ( concreteElement -> concreteElement instanceof NamedConcreteElement ) . map ( concreteElement -> ( NamedConcreteElement ) concreteElement ) . collect ( groupingBy ( NamedConcreteElement :: getName ) ) ; unsolvedElements . forEach ( unsolvedElement -> replaceUnsolvedReference ( concreteElementsMap , unsolvedElement ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces a single { [CODESPLIT] private void replaceUnsolvedReference ( Map < String , List < NamedConcreteElement > > concreteElementsMap , UnsolvedReference unsolvedReference ) { List < NamedConcreteElement > concreteElements = concreteElementsMap . get ( unsolvedReference . getRef ( ) ) ; if ( concreteElements != null ) { Map < String , String > oldElementAttributes = unsolvedReference . getElement ( ) . getAttributesMap ( ) ; for ( NamedConcreteElement concreteElement : concreteElements ) { NamedConcreteElement substitutionElementWrapper ; if ( ! unsolvedReference . isTypeRef ( ) ) { XsdNamedElements substitutionElement = concreteElement . getElement ( ) . clone ( oldElementAttributes ) ; substitutionElementWrapper = ( NamedConcreteElement ) ReferenceBase . createFromXsd ( substitutionElement ) ; } else { substitutionElementWrapper = concreteElement ; } unsolvedReference . getParent ( ) . replaceUnsolvedElements ( substitutionElementWrapper ) ; } } else { storeUnsolvedItem ( unsolvedReference ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves an occurrence of an element which couldn t be resolved in the { [CODESPLIT] private void storeUnsolvedItem ( UnsolvedReference unsolvedReference ) { if ( parserUnsolvedElementsMap . isEmpty ( ) ) { parserUnsolvedElementsMap . add ( new UnsolvedReferenceItem ( unsolvedReference ) ) ; } else { Optional < UnsolvedReferenceItem > innerEntry = parserUnsolvedElementsMap . stream ( ) . filter ( unsolvedReferenceObj -> unsolvedReferenceObj . getUnsolvedReference ( ) . getRef ( ) . equals ( unsolvedReference . getRef ( ) ) ) . findFirst ( ) ; if ( innerEntry . isPresent ( ) ) { innerEntry . ifPresent ( entry -> entry . getParents ( ) . add ( unsolvedReference . getParent ( ) ) ) ; } else { parserUnsolvedElementsMap . add ( new UnsolvedReferenceItem ( unsolvedReference ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new file to the parsing queue . This new file appears by having xsd : import or xsd : include tags in the original file to parse . [CODESPLIT] public void addFileToParse ( String schemaLocation ) { if ( ! schemaLocations . contains ( schemaLocation ) && schemaLocation . endsWith ( \".xsd\" ) ) { schemaLocations . add ( schemaLocation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts if the current object has the name attribute when not being a direct child of the XsdSchema element which is not allowed throwing an exception in that case . [CODESPLIT] private void rule2 ( ) { if ( ! ( parent instanceof XsdSchema ) && name != null ) { throw new ParsingException ( XSD_TAG + \" element: The \" + NAME_TAG + \" should only be used when the parent of the \" + XSD_TAG + \" is the \" + XsdSchema . XSD_TAG + \" element.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts if the current has no value for its name attribute while being a direct child of the top level XsdSchema element which is required . Throws an exception if no name is present . [CODESPLIT] private void rule3 ( ) { if ( parent instanceof XsdSchema && name == null ) { throw new ParsingException ( XSD_TAG + \" element: The \" + NAME_TAG + \" should is required the parent of the \" + XSD_TAG + \" is the \" + XsdSchema . XSD_TAG + \" element.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two different objects of this type . [CODESPLIT] public static boolean hasDifferentValue ( XsdDoubleRestrictions o1 , XsdDoubleRestrictions o2 ) { if ( o1 == null && o2 == null ) { return false ; } double o1Value = Double . MAX_VALUE ; double o2Value ; if ( o1 != null ) { o1Value = o1 . getValue ( ) ; } if ( o2 != null ) { o2Value = o2 . getValue ( ) ; return o2Value == o1Value ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method obtains all the restrictions for the current { [CODESPLIT] public List < XsdRestriction > getAllRestrictions ( ) { Map < String , XsdRestriction > restrictions = new HashMap <> ( ) ; Map < String , String > xsdBuiltinTypes = XsdParserCore . getXsdTypesToJava ( ) ; if ( restriction != null ) { restrictions . put ( xsdBuiltinTypes . get ( restriction . getBase ( ) ) , restriction ) ; } if ( union != null ) { union . getUnionElements ( ) . forEach ( unionMember -> { XsdRestriction unionMemberRestriction = unionMember . getRestriction ( ) ; if ( unionMemberRestriction != null ) { XsdRestriction existingRestriction = restrictions . getOrDefault ( xsdBuiltinTypes . get ( unionMemberRestriction . getBase ( ) ) , null ) ; if ( existingRestriction != null ) { if ( existsRestrictionOverlap ( existingRestriction , unionMemberRestriction ) ) { throw new InvalidParameterException ( \"The xsd file is invalid because has contradictory restrictions.\" ) ; } updateExistingRestriction ( existingRestriction , unionMemberRestriction ) ; } else { restrictions . put ( xsdBuiltinTypes . get ( unionMemberRestriction . getBase ( ) ) , unionMemberRestriction ) ; } } } ) ; } return new ArrayList <> ( restrictions . values ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins two distinct { [CODESPLIT] private void updateExistingRestriction ( XsdRestriction existing , XsdRestriction newRestriction ) { XsdPattern pattern = newRestriction . getPattern ( ) ; XsdMaxExclusive maxExclusive = newRestriction . getMaxExclusive ( ) ; XsdMaxInclusive maxInclusive = newRestriction . getMaxInclusive ( ) ; XsdMaxLength maxLength = newRestriction . getMaxLength ( ) ; XsdMinExclusive minExclusive = newRestriction . getMinExclusive ( ) ; XsdMinInclusive minInclusive = newRestriction . getMinInclusive ( ) ; XsdMinLength minLength = newRestriction . getMinLength ( ) ; XsdLength length = newRestriction . getLength ( ) ; XsdFractionDigits fractionDigits = newRestriction . getFractionDigits ( ) ; XsdTotalDigits totalDigits = newRestriction . getTotalDigits ( ) ; XsdWhiteSpace whiteSpace = newRestriction . getWhiteSpace ( ) ; if ( pattern != null ) { existing . setPattern ( pattern ) ; } if ( maxExclusive != null ) { existing . setMaxExclusive ( maxExclusive ) ; } if ( maxInclusive != null ) { existing . setMaxInclusive ( maxInclusive ) ; } if ( maxLength != null ) { existing . setMaxLength ( maxLength ) ; } if ( minExclusive != null ) { existing . setMinExclusive ( minExclusive ) ; } if ( minInclusive != null ) { existing . setMinInclusive ( minInclusive ) ; } if ( minLength != null ) { existing . setMinLength ( minLength ) ; } if ( length != null ) { existing . setLength ( length ) ; } if ( fractionDigits != null ) { existing . setFractionDigits ( fractionDigits ) ; } if ( totalDigits != null ) { existing . setTotalDigits ( totalDigits ) ; } if ( whiteSpace != null ) { existing . setWhiteSpace ( whiteSpace ) ; } updateExistingRestrictionEnumerations ( existing , newRestriction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the existing { [CODESPLIT] private void updateExistingRestrictionEnumerations ( XsdRestriction existing , XsdRestriction newRestriction ) { List < XsdEnumeration > existingEnumeration = existing . getEnumeration ( ) ; List < XsdEnumeration > newRestrictionEnumeration = newRestriction . getEnumeration ( ) ; if ( existingEnumeration == null ) { existing . setEnumeration ( newRestrictionEnumeration ) ; } else { if ( newRestrictionEnumeration != null ) { for ( XsdEnumeration enumerationElem : newRestrictionEnumeration ) { if ( existingEnumeration . stream ( ) . noneMatch ( existingEnumerationElem -> existingEnumerationElem . getValue ( ) . equals ( enumerationElem . getValue ( ) ) ) ) { existingEnumeration . add ( enumerationElem ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks for any restriction overlap between two different { [CODESPLIT] private boolean existsRestrictionOverlap ( XsdRestriction existing , XsdRestriction newRestriction ) { return hasDifferentValue ( existing . getPattern ( ) , newRestriction . getPattern ( ) ) || hasDifferentValue ( existing . getWhiteSpace ( ) , newRestriction . getWhiteSpace ( ) ) || hasDifferentValue ( existing . getTotalDigits ( ) , newRestriction . getTotalDigits ( ) ) || hasDifferentValue ( existing . getFractionDigits ( ) , newRestriction . getFractionDigits ( ) ) || hasDifferentValue ( existing . getMaxExclusive ( ) , newRestriction . getMaxExclusive ( ) ) || hasDifferentValue ( existing . getMaxInclusive ( ) , newRestriction . getMaxInclusive ( ) ) || hasDifferentValue ( existing . getMaxLength ( ) , newRestriction . getMaxLength ( ) ) || hasDifferentValue ( existing . getMinExclusive ( ) , newRestriction . getMinExclusive ( ) ) || hasDifferentValue ( existing . getMinInclusive ( ) , newRestriction . getMinInclusive ( ) ) || hasDifferentValue ( existing . getMinLength ( ) , newRestriction . getMinLength ( ) ) || hasDifferentValue ( existing . getLength ( ) , newRestriction . getLength ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts if the current object has a ref attribute at the same time as either a simpleType as children a form attribute or a type attribute . Throws an exception in that case . [CODESPLIT] private void rule3 ( ) { if ( attributesMap . containsKey ( REF_TAG ) && ( simpleType != null || form != null || type != null ) ) { throw new ParsingException ( XSD_TAG + \" element: If \" + REF_TAG + \" attribute is present, simpleType element, form attribute and type attribute cannot be present at the same time.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Receives a { [CODESPLIT] @ Override public void replaceUnsolvedElements ( NamedConcreteElement elementWrapper ) { super . replaceUnsolvedElements ( elementWrapper ) ; XsdAbstractElement element = elementWrapper . getElement ( ) ; if ( element instanceof XsdSimpleType && simpleType != null && type . equals ( elementWrapper . getName ( ) ) ) { this . simpleType = elementWrapper ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a XSD file and all its containing XSD elements . This code iterates on the nodes and parses the supported ones . The supported types are all the XSD types that have their tag present in the { [CODESPLIT] private void parseFile ( String filePath ) { //https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ try { if ( ! new File ( filePath ) . exists ( ) ) { throw new FileNotFoundException ( ) ; } Node schemaNode = getSchemaNode ( filePath ) ; if ( isXsdSchema ( schemaNode ) ) { XsdSchema . parse ( this , schemaNode ) ; } else { throw new ParsingException ( \"The top level element of a XSD file should be the xsd:schema node.\" ) ; } } catch ( SAXException | IOException | ParserConfigurationException e ) { Logger . getAnonymousLogger ( ) . log ( Level . SEVERE , \"Exception while parsing.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This function uses DOM to obtain a list of nodes from a XSD file . [CODESPLIT] private Node getSchemaNode ( String filePath ) throws IOException , SAXException , ParserConfigurationException { Document doc = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( filePath ) ; doc . getDocumentElement ( ) . normalize ( ) ; return doc . getFirstChild ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts if the current object has a form attribute while being a direct child of the top level XsdSchema element which isn t allowed throwing an exception in that case . [CODESPLIT] private void rule7 ( ) { if ( parent instanceof XsdSchema && attributesMap . containsKey ( FORM_TAG ) ) { throw new ParsingException ( XSD_TAG + \" element: The \" + FORM_TAG + \" attribute can only be present when the parent of the \" + xsdElementIsXsdSchema ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asserts if the current object has a ref attribute while being a direct child of the top level XsdSchema element which isn t allowed throwing an exception in that case . [CODESPLIT] private void rule3 ( ) { if ( parent instanceof XsdSchema && attributesMap . containsKey ( REF_TAG ) ) { throw new ParsingException ( XSD_TAG + \" element: The \" + REF_TAG + \" attribute cannot be present when the parent of the \" + xsdElementIsXsdSchema ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method aims to replace the previously created { [CODESPLIT] @ Override public void replaceUnsolvedElements ( NamedConcreteElement element ) { super . replaceUnsolvedElements ( element ) ; XsdNamedElements elem = element . getElement ( ) ; boolean isComplexOrSimpleType = elem instanceof XsdComplexType || elem instanceof XsdSimpleType ; if ( this . type instanceof UnsolvedReference && isComplexOrSimpleType && ( ( UnsolvedReference ) this . type ) . getRef ( ) . equals ( element . getName ( ) ) ) { this . type = element ; elem . setParent ( this ) ; } if ( this . substitutionGroup instanceof UnsolvedReference && elem instanceof XsdElement && ( ( UnsolvedReference ) this . substitutionGroup ) . getRef ( ) . equals ( element . getName ( ) ) ) { XsdElement xsdElement = ( XsdElement ) elem ; this . type = xsdElement . type ; this . simpleType = xsdElement . simpleType ; this . complexType = xsdElement . complexType ; this . substitutionGroup = element ; elem . setParent ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The base code for parsing any { [CODESPLIT] static ReferenceBase xsdParseSkeleton ( Node node , XsdAbstractElement element ) { XsdParserCore parser = element . getParser ( ) ; Node child = node . getFirstChild ( ) ; while ( child != null ) { if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) { String nodeName = child . getNodeName ( ) ; BiFunction < XsdParserCore , Node , ReferenceBase > parserFunction = XsdParserCore . getParseMappers ( ) . get ( nodeName ) ; if ( parserFunction != null ) { XsdAbstractElement childElement = parserFunction . apply ( parser , child ) . getElement ( ) ; childElement . accept ( element . getVisitor ( ) ) ; childElement . validateSchemaRules ( ) ; } } child = child . getNextSibling ( ) ; } ReferenceBase wrappedElement = ReferenceBase . createFromXsd ( element ) ; parser . addParsedElement ( wrappedElement ) ; return wrappedElement ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { [CODESPLIT] protected static Map < String , String > convertNodeMap ( NamedNodeMap nodeMap ) { HashMap < String , String > attributesMapped = new HashMap <> ( ) ; for ( int i = 0 ; i < nodeMap . getLength ( ) ; i ++ ) { Node node = nodeMap . item ( i ) ; attributesMapped . put ( node . getNodeName ( ) , node . getNodeValue ( ) ) ; } return attributesMapped ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method iterates on the current element children and replaces any { [CODESPLIT] public void replaceUnsolvedElements ( NamedConcreteElement element ) { List < ReferenceBase > elements = this . getElements ( ) ; if ( elements != null ) { elements . stream ( ) . filter ( referenceBase -> referenceBase instanceof UnsolvedReference ) . map ( referenceBase -> ( UnsolvedReference ) referenceBase ) . filter ( unsolvedReference -> unsolvedReference . getRef ( ) . equals ( element . getName ( ) ) ) . findFirst ( ) . ifPresent ( oldElement -> elements . set ( elements . indexOf ( oldElement ) , element ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In special cases such as { [CODESPLIT] static String xsdRawContentParse ( Node node ) { Node child = node . getFirstChild ( ) ; StringBuilder stringBuilder = new StringBuilder ( ) ; while ( child != null ) { if ( child . getNodeType ( ) == Node . TEXT_NODE ) { stringBuilder . append ( child . getTextContent ( ) ) ; } child = child . getNextSibling ( ) ; } return stringBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two different objects of this type . [CODESPLIT] public static boolean hasDifferentValue ( XsdIntegerRestrictions o1 , XsdIntegerRestrictions o2 ) { if ( o1 == null && o2 == null ) { return false ; } int o1Value = Integer . MAX_VALUE ; int o2Value ; if ( o1 != null ) { o1Value = o1 . getValue ( ) ; } if ( o2 != null ) { o2Value = o2 . getValue ( ) ; return o2Value == o1Value ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies if a given value is present in a given { [CODESPLIT] public static < T extends XsdEnum > T belongsToEnum ( final XsdEnum < T > instance , final String value ) { if ( value == null ) { return null ; } Optional < T > enumValue = Arrays . stream ( instance . getValues ( ) ) . filter ( enumField -> enumField . getValue ( ) . equals ( value ) ) . findFirst ( ) ; if ( enumValue . isPresent ( ) ) { return enumValue . get ( ) ; } else { StringBuilder possibleValues = new StringBuilder ( ) ; instance . getSupportedValues ( ) . forEach ( supportedValue -> possibleValues . append ( supportedValue ) . append ( \", \" ) ) ; String values = possibleValues . toString ( ) ; values = values . substring ( 0 , values . length ( ) - 2 ) ; throw new ParsingException ( \"The attribute \" + instance . getVariableName ( ) + \" doesn't support the value \\\"\" + value + \"\\\".\\n\" + \"The possible values for the \" + instance . getVariableName ( ) + \" attribute are:\\n\" + values ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the maxOccurs attribute is unbounded or an { [CODESPLIT] static String maxOccursValidation ( String elementName , String value ) { if ( value . equals ( \"unbounded\" ) ) { return value ; } validateNonNegativeInteger ( elementName , MAX_OCCURS_TAG , value ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates if a given String is a non negative { [CODESPLIT] static Integer validateNonNegativeInteger ( String elementName , String attributeName , String value ) { try { int intValue = Integer . parseInt ( value ) ; if ( intValue < 0 ) { throw new ParsingException ( \"The \" + elementName + \" \" + attributeName + \" attribute should be a non negative integer. (greater or equal than 0)\" ) ; } return intValue ; } catch ( NumberFormatException e ) { throw new ParsingException ( \"The \" + elementName + \" \" + attributeName + \"  attribute should be a non negative integer.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates if a given String is a non negative { [CODESPLIT] public static Integer validateRequiredNonNegativeInteger ( String elementName , String attributeName , String value ) { if ( value == null ) throw new ParsingException ( attributeMissingMessage ( elementName , attributeName ) ) ; return validateNonNegativeInteger ( elementName , attributeName , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates if a given String is a positive { [CODESPLIT] public static Integer validateRequiredPositiveInteger ( String elementName , String attributeName , String value ) { if ( value == null ) throw new ParsingException ( attributeMissingMessage ( elementName , attributeName ) ) ; return validatePositiveInteger ( elementName , attributeName , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates if a given { [CODESPLIT] private static Double validateDouble ( String elementName , String attributeName , String value ) { try { return Double . parseDouble ( value ) ; } catch ( NumberFormatException e ) { throw new ParsingException ( \"The \" + elementName + \" \" + attributeName + \"  attribute should be a numeric value.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates if a given { [CODESPLIT] public static Double validateRequiredDouble ( String elementName , String attributeName , String value ) { if ( value == null ) throw new ParsingException ( attributeMissingMessage ( elementName , attributeName ) ) ; return validateDouble ( elementName , attributeName , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the default value of the { [CODESPLIT] static String getFormDefaultValue ( XsdAbstractElement parent ) { if ( parent == null ) return null ; if ( parent instanceof XsdSchema ) { return ( ( XsdSchema ) parent ) . getElementFormDefault ( ) ; } return getFormDefaultValue ( parent . getParent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the default value of the { [CODESPLIT] static String getFinalDefaultValue ( XsdAbstractElement parent ) { if ( parent == null ) return null ; if ( parent instanceof XsdSchema ) { return ( ( XsdSchema ) parent ) . getFinalDefault ( ) ; } return getFinalDefaultValue ( parent . getParent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the default value of the { [CODESPLIT] static String getBlockDefaultValue ( XsdAbstractElement parent ) { if ( parent == null ) return null ; if ( parent instanceof XsdSchema ) { return ( ( XsdSchema ) parent ) . getBlockDefault ( ) ; } return getBlockDefaultValue ( parent . getParent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method creates a ReferenceBase object that serves as a wrapper to { [CODESPLIT] public static ReferenceBase createFromXsd ( XsdAbstractElement element ) { String ref = getRef ( element ) ; String name = getName ( element ) ; if ( ! ( element instanceof XsdNamedElements ) ) { return new ConcreteElement ( element ) ; } if ( ref == null ) { if ( name == null ) { return new ConcreteElement ( element ) ; } else { return new NamedConcreteElement ( ( XsdNamedElements ) element , name ) ; } } else { return new UnsolvedReference ( ( XsdNamedElements ) element ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method should always receive two elements one to replace the { [CODESPLIT] @ Override public void replaceUnsolvedElements ( NamedConcreteElement element ) { super . replaceUnsolvedElements ( element ) ; XsdNamedElements elem = element . getElement ( ) ; String elemName = elem . getRawName ( ) ; boolean isComplexOrSimpleType = elem instanceof XsdComplexType || elem instanceof XsdSimpleType ; if ( this . base instanceof UnsolvedReference && isComplexOrSimpleType && ( ( UnsolvedReference ) this . base ) . getRef ( ) . equals ( elemName ) ) { this . base = element ; } if ( this . childElement instanceof UnsolvedReference && elem instanceof XsdGroup && ( ( UnsolvedReference ) this . childElement ) . getRef ( ) . equals ( elemName ) ) { this . childElement = element ; } visitor . replaceUnsolvedAttributes ( element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If T is assignable from value then return the value . Otherwise tries to create an instance of this type using the provided argument . [CODESPLIT] @ Override public T convert ( final Object value ) { if ( value == null ) { return null ; } else if ( isIterable ( ) && Iterable . class . isAssignableFrom ( value . getClass ( ) ) ) { return convertIterable ( value ) ; } else if ( reflectedKlass . assignableFromObject ( value ) ) { return ( T ) value ; } else if ( reflectedKlass . canBeUnboxed ( value . getClass ( ) ) ) { return ( T ) value ; } else if ( reflectedKlass . canBeBoxed ( value . getClass ( ) ) ) { return ( T ) value ; } FluentClass < ? > klassToCreate ; if ( reflectedKlass . isPrimitive ( ) ) { klassToCreate = reflectedKlass . boxedType ( ) ; } else { klassToCreate = reflectedKlass ; } return ( T ) convertValueTo ( value , klassToCreate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Cli from an annotated interface definition [CODESPLIT] public static < O > Cli < O > createCli ( final Class < O > klass ) throws InvalidOptionSpecificationException { return new CliInterfaceImpl < O > ( klass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a Cli from an annotated class [CODESPLIT] public static < O > Cli < O > createCliUsingInstance ( final O options ) throws InvalidOptionSpecificationException { return new CliInstanceImpl < O > ( options ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse arguments from an annotated interface definition [CODESPLIT] public static < O > O parseArguments ( final Class < O > klass , final String ... arguments ) throws ArgumentValidationException , InvalidOptionSpecificationException { return createCli ( klass ) . parseArguments ( arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse arguments from an annotated class instance [CODESPLIT] public static < O > O parseArgumentsUsingInstance ( final O options , final String ... arguments ) throws ArgumentValidationException , InvalidOptionSpecificationException { return createCliUsingInstance ( options ) . parseArguments ( arguments ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void parseArguments ( final ParsedArguments parsedArguments , final String ... arguments ) throws ArgumentValidationException { boolean finishedOptions = false ; for ( final String argument : arguments ) { if ( finishedOptions ) { parsedArguments . addValue ( argument ) ; } else { finishedOptions = add ( parsedArguments , argument ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Note : The following methods are used to get a String representation of the different POJO ( while handling null value ) [CODESPLIT] private static String getEventDate ( Date dates ) { return Optional . ofNullable ( dates ) . map ( Date :: getStart ) . map ( Start :: getDateTime ) . map ( dt -> dt . toString ( ) ) . orElse ( \"No date\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Package protected for testing purposess [CODESPLIT] Builder urlBuilder ( String path ) { Builder builder = baseUrlBuilder ( ) . addPathSegment ( configuration . getApiPackage ( ) ) . addPathSegment ( configuration . getApiVersion ( ) ) . addPathSegment ( path ) ; if ( configuration . getPathModifier ( ) != DiscoveryApiConfiguration . PathModifier . NONE ) { builder . addPathSegment ( configuration . getPathModifier ( ) . getModifier ( ) ) ; } return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a fixed view to appear at the top of the list . If this method is called more than once the views will appear in the order they were added . Views added using this call can take focus if they want . <p > Note : When first introduced this method could only be called before setting the adapter with { @link #setAdapter ( ListAdapter ) } . Starting with { @link android . os . Build . VERSION_CODES#KITKAT } this method may be called at any time . If the ListView s adapter does not extend { @link FooterViewGridAdapter } it will be wrapped with a supporting instance of { @link android . widget . WrapperListAdapter } . [CODESPLIT] public void addHeaderView ( View v , Object data , boolean isSelectable ) { final FixedViewInfo info = new FixedViewInfo ( ) ; FrameLayout fl = new FullWidthFixedViewLayout ( getContext ( ) ) ; fl . addView ( v ) ; info . view = v ; info . viewContainer = fl ; info . data = data ; info . isSelectable = isSelectable ; mHeaderViewInfos . add ( info ) ; // Wrap the adapter if it wasn't already wrapped. if ( mAdapter != null ) { if ( ! ( mAdapter instanceof FooterViewGridAdapter ) ) { mAdapter = new FooterViewGridAdapter ( mHeaderViewInfos , mFooterViewInfos , mAdapter ) ; } // Do not know if this really helps notifiyChanged ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a previously - added footer view . [CODESPLIT] public boolean removeFooterView ( View v ) { if ( mFooterViewInfos . size ( ) > 0 ) { boolean result = false ; if ( mAdapter != null && ( ( FooterViewGridAdapter ) mAdapter ) . removeFooter ( v ) ) { notifiyChanged ( ) ; result = true ; } removeFixedViewInfo ( v , mFooterViewInfos ) ; return result ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the position ( @a x @a y @a z ) of the start of the line segment to choose values along . [CODESPLIT] public void setStartPoint ( double x , double y , double z ) { this . x0 = x ; this . y0 = y ; this . z0 = z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the position ( @a x @a y @a z ) of the end of the line segment to choose values along . [CODESPLIT] public void setEndPoint ( double x , double y , double z ) { this . x1 = x ; this . y1 = y ; this . z1 = z ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the output value from the noise module given the one - dimensional coordinate of the specified input value located on the line segment . [CODESPLIT] public double getValue ( double p ) { if ( module == null ) { throw new NoModuleException ( ) ; } double x = ( x1 - x0 ) * p + x0 ; double y = ( y1 - y0 ) * p + y0 ; double z = ( z1 - z0 ) * p + z0 ; double value = module . getValue ( x , y , z ) ; if ( attenuate ) { return p * ( 1.0 - p ) * 4 * value ; } else { return value ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the output value from the noise module given the ( @a x @a z ) coordinates of the specified input value located on the surface of the plane . [CODESPLIT] public double getValue ( double x , double z ) { if ( module == null ) { throw new NoModuleException ( ) ; } return module . getValue ( x , 0 , z ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a gradient - coherent - noise value from the coordinates of a three - dimensional input value . [CODESPLIT] public static double gradientCoherentNoise3D ( double x , double y , double z , int seed , NoiseQuality quality ) { // Create a unit-length cube aligned along an integer boundary.  This cube // surrounds the input point. int x0 = ( ( x > 0.0 ) ? ( int ) x : ( int ) x - 1 ) ; int x1 = x0 + 1 ; int y0 = ( ( y > 0.0 ) ? ( int ) y : ( int ) y - 1 ) ; int y1 = y0 + 1 ; int z0 = ( ( z > 0.0 ) ? ( int ) z : ( int ) z - 1 ) ; int z1 = z0 + 1 ; // Map the difference between the coordinates of the input value and the // coordinates of the cube's outer-lower-left vertex onto an S-curve. double xs , ys , zs ; if ( quality == NoiseQuality . FAST ) { xs = ( x - ( double ) x0 ) ; ys = ( y - ( double ) y0 ) ; zs = ( z - ( double ) z0 ) ; } else if ( quality == NoiseQuality . STANDARD ) { xs = Utils . sCurve3 ( x - ( double ) x0 ) ; ys = Utils . sCurve3 ( y - ( double ) y0 ) ; zs = Utils . sCurve3 ( z - ( double ) z0 ) ; } else { xs = Utils . sCurve5 ( x - ( double ) x0 ) ; ys = Utils . sCurve5 ( y - ( double ) y0 ) ; zs = Utils . sCurve5 ( z - ( double ) z0 ) ; } // Now calculate the noise values at each vertex of the cube.  To generate // the coherent-noise value at the input point, interpolate these eight // noise values using the S-curve value as the interpolant (trilinear // interpolation.) double n0 , n1 , ix0 , ix1 , iy0 , iy1 ; n0 = gradientNoise3D ( x , y , z , x0 , y0 , z0 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y0 , z0 , seed ) ; ix0 = Utils . linearInterp ( n0 , n1 , xs ) ; n0 = gradientNoise3D ( x , y , z , x0 , y1 , z0 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y1 , z0 , seed ) ; ix1 = Utils . linearInterp ( n0 , n1 , xs ) ; iy0 = Utils . linearInterp ( ix0 , ix1 , ys ) ; n0 = gradientNoise3D ( x , y , z , x0 , y0 , z1 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y0 , z1 , seed ) ; ix0 = Utils . linearInterp ( n0 , n1 , xs ) ; n0 = gradientNoise3D ( x , y , z , x0 , y1 , z1 , seed ) ; n1 = gradientNoise3D ( x , y , z , x1 , y1 , z1 , seed ) ; ix1 = Utils . linearInterp ( n0 , n1 , xs ) ; iy1 = Utils . linearInterp ( ix0 , ix1 , ys ) ; return Utils . linearInterp ( iy0 , iy1 , zs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a gradient - noise value from the coordinates of a three - dimensional input value and the integer coordinates of a nearby three - dimensional value . [CODESPLIT] public static double gradientNoise3D ( double fx , double fy , double fz , int ix , int iy , int iz , int seed ) { // Randomly generate a gradient vector given the integer coordinates of the // input value.  This implementation generates a random number and uses it // as an index into a normalized-vector lookup table. int vectorIndex = ( X_NOISE_GEN * ix + Y_NOISE_GEN * iy + Z_NOISE_GEN * iz + SEED_NOISE_GEN * seed ) ; vectorIndex ^= ( vectorIndex >> SHIFT_NOISE_GEN ) ; vectorIndex &= 0xff ; double xvGradient = Utils . RANDOM_VECTORS [ ( vectorIndex << 2 ) ] ; double yvGradient = Utils . RANDOM_VECTORS [ ( vectorIndex << 2 ) + 1 ] ; double zvGradient = Utils . RANDOM_VECTORS [ ( vectorIndex << 2 ) + 2 ] ; // Set up us another vector equal to the distance between the two vectors // passed to this function. double xvPoint = ( fx - ix ) ; double yvPoint = ( fy - iy ) ; double zvPoint = ( fz - iz ) ; // Now compute the dot product of the gradient vector with the distance // vector.  The resulting value is gradient noise.  Apply a scaling and // offset value so that this noise value ranges from 0 to 1. return ( ( xvGradient * xvPoint ) + ( yvGradient * yvPoint ) + ( zvGradient * zvPoint ) ) + 0.5 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates an integer - noise value from the coordinates of a three - dimensional input value . [CODESPLIT] public static int intValueNoise3D ( int x , int y , int z , int seed ) { // All constants are primes and must remain prime in order for this noise // function to work correctly. int n = ( X_NOISE_GEN * x + Y_NOISE_GEN * y + Z_NOISE_GEN * z + SEED_NOISE_GEN * seed ) & 0x7fffffff ; n = ( n >> 13 ) ^ n ; return ( n * ( n * n * 60493 + 19990303 ) + 1376312589 ) & 0x7fffffff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a value - noise value from the coordinates of a three - dimensional input value . [CODESPLIT] public static double valueNoise3D ( int x , int y , int z , int seed ) { return intValueNoise3D ( x , y , z , seed ) / 2147483647.0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the output value from the noise module given the ( angle height ) coordinates of the specified input value located on the surface of the cylinder . [CODESPLIT] public double getValue ( double angle , double height ) { if ( module == null ) { throw new NoModuleException ( ) ; } double x , y , z ; x = Math . cos ( Math . toRadians ( angle ) ) ; y = height ; z = Math . sin ( Math . toRadians ( angle ) ) ; return module . getValue ( x , y , z ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the output value from the noise module given the ( latitude longitude ) coordinates of the specified input value located on the surface of the sphere . [CODESPLIT] public double getValue ( double lat , double lon ) { if ( module == null ) { throw new NoModuleException ( ) ; } double [ ] vec = Utils . latLonToXYZ ( lat , lon ) ; return module . getValue ( vec [ 0 ] , vec [ 1 ] , vec [ 2 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs cubic interpolation between two values bound between two other values [CODESPLIT] public static double cubicInterp ( double n0 , double n1 , double n2 , double n3 , double a ) { double p = ( n3 - n2 ) - ( n0 - n1 ) ; double q = ( n0 - n1 ) - p ; double r = n2 - n0 ; return p * a * a * a + q * a * a + r * a + n1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "maps a value onto a quitnic S - Curve [CODESPLIT] public static double sCurve5 ( double a ) { double a3 = a * a * a ; double a4 = a3 * a ; double a5 = a4 * a ; return ( 6.0 * a5 ) - ( 15.0 * a4 ) + ( 10.0 * a3 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Calculate the scale and biased to be a applied during Range#getValue ( int x int y int z ) Should be called when the bounds are modified [CODESPLIT] private void recalculateScaleBias ( ) { scale = ( getNewUpperBound ( ) - getNewLowerBound ( ) ) / ( getCurrentUpperBound ( ) - getCurrentLowerBound ( ) ) ; bias = getNewLowerBound ( ) - getCurrentLowerBound ( ) * scale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure bounds for range module [CODESPLIT] public void setBounds ( double currentLower , double currentUpper , double newLower , double newUpper ) { if ( currentLower == currentUpper ) { throw new IllegalArgumentException ( \"currentLower must not equal currentUpper. Both are \" + currentUpper ) ; } if ( newLower == newUpper ) { throw new IllegalArgumentException ( \"newLowerBound must not equal newUpperBound. Both are \" + newUpper ) ; } currentLowerBound = currentLower ; currentUpperBound = currentUpper ; newLowerBound = newLower ; newUpperBound = newUpper ; recalculateScaleBias ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes an single event by looping available plugins . [CODESPLIT] protected void doProcess ( final CloudTrailEvent event ) { for ( final FullstopPlugin plugin : getPluginsForEvent ( event ) ) { doProcess ( event , plugin ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes a specific event on specified plugin . [CODESPLIT] protected void doProcess ( final CloudTrailEvent event , final FullstopPlugin plugin ) { try { plugin . processEvent ( event ) ; } catch ( HystrixRuntimeException | HttpServerErrorException e ) { log . warn ( e . getMessage ( ) , e ) ; } catch ( final Exception e ) { log . error ( e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts list of instanceIds from { [CODESPLIT] public static List < String > getInstanceIds ( final CloudTrailEvent event ) { final CloudTrailEventData eventData = getEventData ( event ) ; final String responseElements = eventData . getResponseElements ( ) ; if ( isNullOrEmpty ( responseElements ) ) { return newArrayList ( ) ; } return read ( responseElements , INSTANCE_ID_JSON_PATH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the accountId . [CODESPLIT] public static String getAccountId ( final CloudTrailEvent event ) { final CloudTrailEventData eventData = getEventData ( event ) ; final UserIdentity userIdentity = checkNotNull ( eventData . getUserIdentity ( ) , USER_IDENTITY_SHOULD_NEVER_BE_NULL ) ; final String value = ofNullable ( userIdentity . getAccountId ( ) ) . orElse ( eventData . getRecipientAccountId ( ) ) ; return checkNotNull ( value , ACCOUNT_ID_OR_RECIPIENT_SHOULD_NEVER_BE_NULL ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the given responseElements and extracts information based on given pattern . <br / > If responseElements is null or empty you can handle the { [CODESPLIT] public static List < String > read ( final String responseElements , final String pattern , final boolean emptyListOnNullOrEmptyResponse ) { if ( isNullOrEmpty ( responseElements ) && emptyListOnNullOrEmptyResponse ) { return emptyList ( ) ; } try { return JsonPath . read ( responseElements , pattern ) ; } catch ( final PathNotFoundException e ) { if ( emptyListOnNullOrEmptyResponse ) { return emptyList ( ) ; } else { throw e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the given responseElements and extracts information based on given pattern . <br / > If responseElements is null or empty raises { [CODESPLIT] public static List < String > read ( final String responseElements , final String pattern ) { return read ( responseElements , pattern , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "true if rule matches a violation and should be whitelisted . [CODESPLIT] @ Override public Boolean apply ( final RuleEntity ruleEntity , final ViolationEntity violationEntity ) { final List < Predicate < ViolationEntity > > predicates = newArrayList ( ) ; trimOptional ( ruleEntity . getAccountId ( ) ) . map ( WhitelistRulesEvaluator :: accountIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getRegion ( ) ) . map ( WhitelistRulesEvaluator :: regionIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getViolationTypeEntityId ( ) ) . map ( WhitelistRulesEvaluator :: violationTypeIdIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getImageName ( ) ) . map ( WhitelistRulesEvaluator :: imageNameMatches ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getImageOwner ( ) ) . map ( WhitelistRulesEvaluator :: imageOwnerIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getApplicationId ( ) ) . map ( WhitelistRulesEvaluator :: applicationIdIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getApplicationVersion ( ) ) . map ( WhitelistRulesEvaluator :: applicationVersionIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getMetaInfoJsonPath ( ) ) . map ( this :: metaInfoJsonPathExists ) . ifPresent ( predicates :: add ) ; final Optional < Predicate < ViolationEntity > > whiteListTest = predicates . stream ( ) . reduce ( Predicate :: and ) ; return whiteListTest . isPresent ( ) && whiteListTest . get ( ) . test ( violationEntity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds the prefix that will be prepended to the bucketname <br / > Something like 123456789 / eu - west - 1 / 2015 / 06 / 12 / [CODESPLIT] static String build ( final String accountId , final String region , final DateTime instanceLaunchTime ) { return Paths . get ( accountId , region , instanceLaunchTime . toString ( \"YYYY\" ) , instanceLaunchTime . toString ( \"MM\" ) , instanceLaunchTime . toString ( \"dd\" ) ) . toString ( ) + \"/\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the EventSerializer based on user s configuration . [CODESPLIT] private EventSerializer getEventSerializer ( final GZIPInputStream inputStream , final CloudTrailLog ctLog ) throws IOException { final EventSerializer serializer ; if ( isEnableRawEventInfo ) { final String logFileContent = new String ( LibraryUtils . toByteArray ( inputStream ) , StandardCharsets . UTF_8 ) ; final JsonParser jsonParser = this . mapper . getFactory ( ) . createParser ( logFileContent ) ; serializer = new RawLogDeliveryEventSerializer ( logFileContent , ctLog , jsonParser ) ; } else { final JsonParser jsonParser = this . mapper . getFactory ( ) . createParser ( inputStream ) ; serializer = new DefaultEventSerializer ( ctLog , jsonParser ) ; } return serializer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void validate ( ) { LibraryUtils . checkArgumentNotNull ( this . getAwsCredentialsProvider ( ) , ERROR_CREDENTIALS_PROVIDER_NULL ) ; LibraryUtils . checkArgumentNotNull ( this . getSqsUrl ( ) , \"SQS URL is null.\" ) ; LibraryUtils . checkArgumentNotNull ( this . getSqsRegion ( ) , \"SQS Region is null.\" ) ; LibraryUtils . checkArgumentNotNull ( this . getVisibilityTimeout ( ) , \"Visibility Timeout is null.\" ) ; LibraryUtils . checkArgumentNotNull ( this . getS3Region ( ) , \"S3 Region is null.\" ) ; LibraryUtils . checkArgumentNotNull ( this . getThreadCount ( ) , \"Thread Count is null.\" ) ; LibraryUtils . checkArgumentNotNull ( this . getThreadTerminationDelaySeconds ( ) , \"Thread Termination Delay Seconds is null.\" ) ; LibraryUtils . checkArgumentNotNull ( this . getMaxEventsPerEmit ( ) , \"Maximum Events Per Emit is null.\" ) ; LibraryUtils . checkArgumentNotNull ( this . isEnableRawEventInfo ( ) , \"Is Enable Raw Event Information is null.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure scopes for specific controller / httpmethods / roles here . [CODESPLIT] @ Override public void configure ( final HttpSecurity http ) throws Exception { http . sessionManagement ( ) . sessionCreationPolicy ( NEVER ) // configure form login . and ( ) . formLogin ( ) . disable ( ) // configure logout . logout ( ) . disable ( ) . authorizeRequests ( ) . antMatchers ( HttpMethod . OPTIONS ) . permitAll ( ) // Allow preflight CORS requests from browsers . antMatchers ( \"/\" ) . access ( \"#oauth2.hasUidScopeAndAnyRealm('/employees', '/services')\" ) . antMatchers ( \"/api/**\" ) . access ( \"#oauth2.hasUidScopeAndAnyRealm('/employees', '/services')\" ) . antMatchers ( \"/s3/**\" ) . access ( \"#oauth2.hasUidScopeAndAnyRealm('/employees', '/services')\" ) . antMatchers ( \"/webjars/**\" ) . permitAll ( ) . antMatchers ( \"/swagger-resources\" ) . permitAll ( ) . antMatchers ( \"/api-docs\" ) . permitAll ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this extension support injection for parameters of the type described by the given { @code parameterContext } ? [CODESPLIT] @ Override public boolean supportsParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { return parameterContext . getParameter ( ) . getAnnotation ( Random . class ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a value for any parameter context which has passed the { @link #supportsParameter ( ParameterContext ExtensionContext ) } gate . [CODESPLIT] @ Override public Object resolveParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { return resolve ( parameterContext . getParameter ( ) . getType ( ) , parameterContext . getParameter ( ) . getAnnotation ( Random . class ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the random requirements expressed by the given { @code annotation } to invocations on { @link #random } . [CODESPLIT] private Object resolve ( Class < ? > targetType , Random annotation ) { if ( targetType . isAssignableFrom ( List . class ) || targetType . isAssignableFrom ( Collection . class ) ) { return random . objects ( annotation . type ( ) , annotation . size ( ) , annotation . excludes ( ) ) . collect ( Collectors . toList ( ) ) ; } else if ( targetType . isAssignableFrom ( Set . class ) ) { return random . objects ( annotation . type ( ) , annotation . size ( ) , annotation . excludes ( ) ) . collect ( Collectors . toSet ( ) ) ; } else if ( targetType . isAssignableFrom ( Stream . class ) ) { return random . objects ( annotation . type ( ) , annotation . size ( ) , annotation . excludes ( ) ) ; } else { return random . nextObject ( targetType , annotation . excludes ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a file within the temporary folder root . [CODESPLIT] public File createFile ( String fileName ) throws IOException { Path path = Paths . get ( rootFolder . getPath ( ) , fileName ) ; return Files . createFile ( path ) . toFile ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a directory within the temporary folder root . [CODESPLIT] public File createDirectory ( String directoryName ) { Path path = Paths . get ( rootFolder . getPath ( ) , directoryName ) ; try { return Files . createDirectory ( path ) . toFile ( ) ; } catch ( IOException ex ) { throw new TemporaryFolderException ( String . format ( \"Failed to create directory: '%s'\" , path . toString ( ) ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the { @link #rootFolder } and all of its contents . This is package protected because a { @link TemporaryFolder } s lifecycle is expected to be controlled by its associated extension . [CODESPLIT] void destroy ( ) throws IOException { if ( rootFolder . exists ( ) ) { // walk the contents deleting each Files . walkFileTree ( rootFolder . toPath ( ) , new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attributes ) throws IOException { return delete ( file ) ; } @ Override public FileVisitResult postVisitDirectory ( Path directory , IOException exception ) throws IOException { return delete ( directory ) ; } @ SuppressWarnings ( \"SameReturnValue\" ) private FileVisitResult delete ( Path file ) throws IOException { Files . delete ( file ) ; return CONTINUE ; } } ) ; if ( rootFolder . exists ( ) ) { // delete the parent, if it still exists Files . delete ( rootFolder . toPath ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Does this extension support injection for parameters of the type described by the given { @code parameterContext } ? [CODESPLIT] @ Override public boolean supportsParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { return appliesTo ( parameterContext . getParameter ( ) . getType ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a value for any parameter context which has passed the { @link #supportsParameter ( ParameterContext ExtensionContext ) } gate . [CODESPLIT] @ Override public Object resolveParameter ( ParameterContext parameterContext , ExtensionContext extensionContext ) throws ParameterResolutionException { return extensionContext . getStore ( NAMESPACE ) . getOrComputeIfAbsent ( parameterContext , key -> new TemporaryFolder ( ) , TemporaryFolder . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the expectations expressed in the given { @code annotation } to a { @link Predicate } . [CODESPLIT] private Predicate < String > getPredicate ( ExpectedException annotation ) { if ( has ( annotation . messageStartsWith ( ) ) ) { return s -> s . startsWith ( annotation . messageStartsWith ( ) ) ; } else if ( has ( annotation . messageContains ( ) ) ) { return s -> s . contains ( annotation . messageContains ( ) ) ; } else if ( has ( annotation . messageIs ( ) ) ) { return s -> s . equals ( annotation . messageIs ( ) ) ; } else { // the default return s -> true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ExtensionContext . Store } for a given { @code extensionContext } . A { @link ExtensionContext . Store } is bound to an { @link ExtensionContext } so different test invocations do not share the same store . For example a test invocation on { @code ClassA . testMethodA } will have a different { @link ExtensionContext . Store } instance to that associated with a test invocation on { @code ClassA . testMethodB } or test invocation on { @code ClassC . testMethodC } . [CODESPLIT] public static ExtensionContext . Store getStore ( ExtensionContext extensionContext , Class clazz ) { return extensionContext . getStore ( namespace ( extensionContext , clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link ExtensionContext . Namespace } in which extension state is stored on creation for post execution destruction . Storing data in a custom namespace prevents accidental cross pollination of data between extensions and between different invocations within the lifecycle of a single extension . [CODESPLIT] private static ExtensionContext . Namespace namespace ( ExtensionContext extensionContext , Class clazz ) { return ExtensionContext . Namespace . create ( clazz , extensionContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If the current test class has a system property annotation ( s ) then create a { @link RestoreContext } representing the annotation ( s ) . This causes the requested system properties to be set and retains a copy of pre - set values for reinstatement after test execution . [CODESPLIT] @ Override public void beforeAll ( ExtensionContext extensionContext ) throws Exception { List < SystemProperty > systemProperties = getSystemProperties ( extensionContext . getRequiredTestClass ( ) ) ; if ( ! systemProperties . isEmpty ( ) ) { RestoreContext . Builder builder = RestoreContext . createBuilder ( ) ; for ( SystemProperty systemProperty : systemProperties ) { builder . addPropertyName ( systemProperty . name ( ) ) ; if ( System . getProperty ( systemProperty . name ( ) ) != null ) { builder . addRestoreProperty ( systemProperty . name ( ) , System . getProperty ( systemProperty . name ( ) ) ) ; } set ( systemProperty ) ; } writeRestoreContext ( extensionContext , builder . build ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a { @link RestoreContext } exists for the given { @code extensionContext } then restore it i . e . unset any system properties which were set in { @link #beforeAll ( ExtensionContext ) } for this { @code extensionContext } and reinstate original value if applicable . [CODESPLIT] @ Override public void afterAll ( ExtensionContext extensionContext ) throws Exception { RestoreContext restoreContext = readRestoreContext ( extensionContext ) ; if ( restoreContext != null ) { restoreContext . restore ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a collection of { @link SystemProperty } for the given { @code annotatedElement } . If the given { @code annotatedElement } has no such annotations then an empty list is returned if the given { @code annotatedElement } is annotated with { @link SystemProperty } then a list with one element is returned if the given { @code annotatedElement } is annotated with { @link SystemProperties } then a list with one element for each of the repeated { @link SystemProperty } values is returned . [CODESPLIT] private List < SystemProperty > getSystemProperties ( AnnotatedElement annotatedElement ) { List < SystemProperty > systemProperties = new ArrayList <> ( ) ; if ( isAnnotated ( annotatedElement , SystemProperties . class ) ) { // gather the repeating system property values systemProperties . addAll ( Arrays . asList ( annotatedElement . getAnnotation ( SystemProperties . class ) . value ( ) ) ) ; } if ( isAnnotated ( annotatedElement , SystemProperty . class ) ) { // add the single system property value systemProperties . add ( annotatedElement . getAnnotation ( SystemProperty . class ) ) ; } return systemProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reverse the system property sets performed on behalf of this restore context . [CODESPLIT] public void restore ( ) { for ( String propertyName : propertyNames ) { if ( restoreProperties . containsKey ( propertyName ) ) { // reinstate the original value System . setProperty ( propertyName , restoreProperties . get ( propertyName ) ) ; } else { // remove the (previously unset) property System . clearProperty ( propertyName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static Stream < JarEntry > asStream ( final JarInputStream pInputStream ) { return StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( new Iterator < JarEntry > ( ) { JarEntry entry = null ; public boolean hasNext ( ) { try { if ( entry == null ) { entry = pInputStream . getNextJarEntry ( ) ; } return entry != null ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } public JarEntry next ( ) { try { JarEntry result = entry != null ? entry : pInputStream . getNextJarEntry ( ) ; entry = null ; return result ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } , Spliterator . IMMUTABLE ) , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * public static Set<String > getDependenciesOfJar ( final InputStream pInputStream ) throws IOException { [CODESPLIT] public static Set < String > getDependenciesOfClass ( final InputStream pInputStream ) throws IOException { final DependenciesClassAdapter v = new DependenciesClassAdapter ( ) ; new ClassReader ( pInputStream ) . accept ( v , ClassReader . EXPAND_FRAMES ) ; final Set < String > depNames = v . getDependencies ( ) ; return depNames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "__ / __ / __ / __ / __ / __ / __ / __ / __ / __ / [CODESPLIT] public static < T extends AbsListView > RxAction < T , String > setFilterText ( ) { return new RxAction < T , String > ( ) { @ Override public void call ( T view , String filterText ) { if ( TextUtils . isEmpty ( filterText ) ) { view . clearTextFilter ( ) ; } else { view . setFilterText ( filterText ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "__ / __ / __ / __ / __ / __ / __ / __ / __ / __ / [CODESPLIT] public static < T extends ImageView > RxAction < T , Integer > setImageLevel ( ) { return new RxAction < T , Integer > ( ) { @ Override public void call ( T view , Integer level ) { view . setImageLevel ( level ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "__ / __ / __ / __ / __ / __ / __ / __ / __ / __ / [CODESPLIT] public static < T extends TextView > RxAction < T , Float > setTextSize ( ) { return new RxAction < T , Float > ( ) { @ Override public void call ( T view , Float size ) { view . setTextSize ( TypedValue . COMPLEX_UNIT_SP , size ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "__ / __ / __ / __ / __ / __ / __ / __ / __ / __ / [CODESPLIT] public static < T extends View > RxAction < T , Integer > setBackgroundColor ( ) { return new RxAction < T , Integer > ( ) { @ Override public void call ( T view , Integer color ) { view . setBackgroundColor ( color ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the map implementation [CODESPLIT] private Map < K , V > createImplementation ( ) { if ( delegate instanceof HashMap == false ) return new HashMap < K , V > ( delegate ) ; return delegate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an object to the collection . [CODESPLIT] public boolean add ( final Object obj ) { maintain ( ) ; SoftObject soft = SoftObject . create ( obj , queue ) ; return collection . add ( soft ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a <tt > SoftObject< / tt > for the given object . [CODESPLIT] public static SoftObject create ( final Object obj , final ReferenceQueue queue ) { if ( obj == null ) return null ; else return new SoftObject ( obj , queue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a property [CODESPLIT] public static String set ( String name , String value ) { return PropertyManager . setProperty ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a property [CODESPLIT] public static String get ( String name , String defaultValue ) { return PropertyManager . getProperty ( name , defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array style property [CODESPLIT] public static String [ ] getArray ( String base , String [ ] defaultValues ) { return PropertyManager . getArrayProperty ( base , defaultValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transition to the next state given the name of a valid transition . [CODESPLIT] public State nextState ( String actionName ) throws IllegalTransitionException { Transition t = currentState . getTransition ( actionName ) ; if ( t == null ) { String msg = \"No transition for action: '\" + actionName + \"' from state: '\" + currentState . getName ( ) + \"'\" ; throw new IllegalTransitionException ( msg ) ; } State nextState = t . getTarget ( ) ; log . trace ( \"nextState(\" + actionName + \") = \" + nextState ) ; currentState = nextState ; return currentState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Iterate through the gcqueue for for any cleared reference remove the associated value from the underlying set . [CODESPLIT] private void processQueue ( ) { ComparableSoftReference cr ; while ( ( cr = ( ComparableSoftReference ) gcqueue . poll ( ) ) != null ) { map . remove ( cr . getKey ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the information for a type [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"cast\" } ) public T get ( Type type ) { if ( type == null ) throw new IllegalArgumentException ( \"Null type\" ) ; if ( type instanceof ParameterizedType ) return getParameterizedType ( ( ParameterizedType ) type ) ; else if ( type instanceof Class ) return getClass ( ( Class < ? > ) type ) ; else if ( type instanceof TypeVariable ) // TODO Figure out why we need this cast with the Sun compiler?  return ( T ) getTypeVariable ( ( TypeVariable ) type ) ; else if ( type instanceof GenericArrayType ) return getGenericArrayType ( ( GenericArrayType ) type ) ; else if ( type instanceof WildcardType ) return getWildcardType ( ( WildcardType ) type ) ; else throw new UnsupportedOperationException ( \"Unknown type: \" + type + \" class=\" + type . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the information for a class [CODESPLIT] public T get ( String name , ClassLoader cl ) throws ClassNotFoundException { if ( name == null ) throw new IllegalArgumentException ( \"Null name\" ) ; if ( cl == null ) throw new IllegalArgumentException ( \"Null classloader\" ) ; Class < ? > clazz = cl . loadClass ( name ) ; return get ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the information for a parameterized type [CODESPLIT] protected T getParameterizedType ( ParameterizedType type ) { // First check if we already have it T result = peek ( type ) ; if ( result != null ) return result ; // Instantiate result = instantiate ( type ) ; // Put the perlimanary result into the cache put ( type , result ) ; // Generate the details generate ( type , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the information for a type variable [CODESPLIT] protected < D extends GenericDeclaration > T getTypeVariable ( TypeVariable < D > type ) { // TODO JBMICROCONT-131 improve this return get ( type . getBounds ( ) [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peek into the cache [CODESPLIT] protected T peek ( ParameterizedType type ) { Class < ? > rawType = ( Class < ? > ) type . getRawType ( ) ; ClassLoader cl = SecurityActions . getClassLoader ( rawType ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { return classLoaderCache . get ( type . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a result into the cache [CODESPLIT] protected void put ( ParameterizedType type , T result ) { Class < ? > rawType = ( Class < ? > ) type . getRawType ( ) ; ClassLoader cl = SecurityActions . getClassLoader ( rawType ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { // TODO JBMICROCONT-131 something better than toString()? classLoaderCache . put ( type . toString ( ) , result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the information for a class [CODESPLIT] protected T getClass ( Class < ? > clazz ) { // First check if we already have it T result = peek ( clazz ) ; if ( result != null ) return result ; // Instantiate result = instantiate ( clazz ) ; // Put the preliminary result into the cache put ( clazz , result ) ; // Generate the details generate ( clazz , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peek into the cache [CODESPLIT] protected T peek ( Class < ? > clazz ) { ClassLoader cl = SecurityActions . getClassLoader ( clazz ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { return classLoaderCache . get ( clazz . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put a result into the cache [CODESPLIT] protected void put ( Class < ? > clazz , T result ) { ClassLoader cl = SecurityActions . getClassLoader ( clazz ) ; Map < String , T > classLoaderCache = getClassLoaderCache ( cl ) ; synchronized ( classLoaderCache ) { classLoaderCache . put ( clazz . getName ( ) , result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cache for the classloader [CODESPLIT] protected Map < String , T > getClassLoaderCache ( ClassLoader cl ) { synchronized ( cache ) { Map < String , T > result = cache . get ( cl ) ; if ( result == null ) { result = new WeakValueHashMap < String , T > ( ) ; cache . put ( cl , result ) ; } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the composite message and the embedded stack trace to the specified print stream . [CODESPLIT] public void printStackTrace ( final PrintStream stream ) { if ( nested == null || NestedThrowable . PARENT_TRACE_ENABLED ) { super . printStackTrace ( stream ) ; } NestedThrowable . Util . print ( nested , stream ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the composite message and the embedded stack trace to the specified print writer . [CODESPLIT] public void printStackTrace ( final PrintWriter writer ) { if ( nested == null || NestedThrowable . PARENT_TRACE_ENABLED ) { super . printStackTrace ( writer ) ; } NestedThrowable . Util . print ( nested , writer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a Class [] from a comma / whitespace seperated list of classes [CODESPLIT] public void setAsText ( final String text ) throws IllegalArgumentException { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; StringTokenizer tokenizer = new StringTokenizer ( text , \", \\t\\r\\n\" ) ; ArrayList < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; while ( tokenizer . hasMoreTokens ( ) == true ) { String name = tokenizer . nextToken ( ) ; try { Class < ? > c = loader . loadClass ( name ) ; classes . add ( c ) ; } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException ( \"Failed to find class: \" + name ) ; } } Class < ? > [ ] theValue = new Class [ classes . size ( ) ] ; classes . toArray ( theValue ) ; setValue ( theValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Override replaceObject to check for Remote objects that are not RemoteStubs . [CODESPLIT] protected Object replaceObject ( Object obj ) throws IOException { if ( ( obj instanceof Remote ) && ! ( obj instanceof RemoteStub ) ) { Remote remote = ( Remote ) obj ; try { obj = RemoteObject . toStub ( remote ) ; } catch ( IOException ignore ) { // Let the Serialization layer try with the orignal obj } } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by the thread pool executor [CODESPLIT] public void run ( ) { // Get the execution thread this . runThread = Thread . currentThread ( ) ; // Check for a start timeout long runTime = getElapsedTime ( ) ; if ( startTimeout > 0l && runTime >= startTimeout ) { taskRejected ( new StartTimeoutException ( \"Start Timeout exceeded for task \" + taskString ) ) ; return ; } // We are about to start, check for a stop boolean stopped = false ; synchronized ( stateLock ) { if ( state == TASK_STOPPED ) { stopped = true ; } else { state = TASK_STARTED ; taskStarted ( ) ; if ( waitType == Task . WAIT_FOR_START ) stateLock . notifyAll ( ) ; } } if ( stopped ) { taskRejected ( new TaskStoppedException ( \"Task stopped for task \" + taskString ) ) ; return ; } // Run the task Throwable throwable = null ; try { task . execute ( ) ; } catch ( Throwable t ) { throwable = t ; } // It is complete taskCompleted ( throwable ) ; // We are completed synchronized ( stateLock ) { state = TASK_COMPLETED ; if ( waitType == Task . WAIT_FOR_COMPLETE ) stateLock . notifyAll ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set thetask for this wrapper [CODESPLIT] protected void setTask ( Task task ) { if ( task == null ) throw new IllegalArgumentException ( \"Null task\" ) ; this . task = task ; this . taskString = task . toString ( ) ; this . startTime = System . currentTimeMillis ( ) ; this . waitType = task . getWaitType ( ) ; this . priority = task . getPriority ( ) ; this . startTimeout = task . getStartTimeout ( ) ; this . completionTimeout = task . getCompletionTimeout ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify the task it has been accepted [CODESPLIT] protected boolean taskAccepted ( ) { try { task . accepted ( getElapsedTime ( ) ) ; return true ; } catch ( Throwable t ) { log . warn ( \"Unexpected error during 'accepted' for task: \" + taskString , t ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify the task it has been rejected [CODESPLIT] protected boolean taskRejected ( RuntimeException e ) { try { task . rejected ( getElapsedTime ( ) , e ) ; return true ; } catch ( Throwable t ) { log . warn ( \"Unexpected error during 'rejected' for task: \" + taskString , t ) ; if ( e != null ) log . warn ( \"Original reason for rejection of task: \" + taskString , e ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify the task it has started [CODESPLIT] protected boolean taskStarted ( ) { try { task . started ( getElapsedTime ( ) ) ; return true ; } catch ( Throwable t ) { log . warn ( \"Unexpected error during 'started' for task: \" + taskString , t ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify the task it has completed [CODESPLIT] protected boolean taskCompleted ( Throwable throwable ) { try { task . completed ( getElapsedTime ( ) , throwable ) ; return true ; } catch ( Throwable t ) { log . warn ( \"Unexpected error during 'completed' for task: \" + taskString , t ) ; if ( throwable != null ) log . warn ( \"Original error during 'run' for task: \" + taskString , throwable ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop the task [CODESPLIT] protected boolean taskStop ( ) { try { task . stop ( ) ; return true ; } catch ( Throwable t ) { log . warn ( \"Unexpected error during 'stop' for task: \" + taskString , t ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by a thread that is not the WorkerQueue thread this method queues the job and if necessary wakes up this worker queue that is waiting in { [CODESPLIT] public synchronized void putJob ( Executable job ) { // Preconditions if ( m_queueThread == null || ! m_queueThread . isAlive ( ) ) { throw new IllegalStateException ( \"Can't put job, thread is not alive or not present\" ) ; } if ( isInterrupted ( ) ) { throw new IllegalStateException ( \"Can't put job, thread was interrupted\" ) ; } putJobImpl ( job ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Never call this method only override in subclasses to perform job getting in a specific way normally tied to the data structure holding the jobs . [CODESPLIT] protected Executable getJobImpl ( ) throws InterruptedException { // While the queue is empty, wait(); // when notified take an event from the queue and return it. while ( m_currentJob == null ) { wait ( ) ; } // This one is the job to return JobItem item = m_currentJob ; // Go on to the next object for the next call.  m_currentJob = m_currentJob . m_next ; return item . m_job ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Never call this method only override in subclasses to perform job adding in a specific way normally tied to the data structure holding the jobs . [CODESPLIT] protected void putJobImpl ( Executable job ) { JobItem posted = new JobItem ( job ) ; if ( m_currentJob == null ) { // The queue is empty, set the current job to process and // wake up the thread waiting in method getJob m_currentJob = posted ; notifyAll ( ) ; } else { JobItem item = m_currentJob ; // The queue is not empty, find the end of the queue ad add the // posted job at the end while ( item . m_next != null ) { item = item . m_next ; } item . m_next = posted ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A utility method to convert a string name to a BlockingMode [CODESPLIT] public static final BlockingMode toBlockingMode ( String name ) { BlockingMode mode = null ; if ( name == null ) { mode = null ; } else if ( name . equalsIgnoreCase ( \"run\" ) ) { mode = RUN ; } else if ( name . equalsIgnoreCase ( \"wait\" ) ) { mode = WAIT ; } else if ( name . equalsIgnoreCase ( \"discard\" ) ) { mode = DISCARD ; } else if ( name . equalsIgnoreCase ( \"discardOldest\" ) ) { mode = DISCARD_OLDEST ; } else if ( name . equalsIgnoreCase ( \"abort\" ) ) { mode = ABORT ; } return mode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overriden to return the indentity instance of BlockingMode based on the stream type int value . This ensures that BlockingMode enums can be compared using == . [CODESPLIT] Object readResolve ( ) throws ObjectStreamException { // Replace the marshalled instance type with the local instance BlockingMode mode = ABORT ; switch ( type ) { case RUN_TYPE : mode = RUN ; break ; case WAIT_TYPE : mode = RUN ; break ; case DISCARD_TYPE : mode = RUN ; break ; case DISCARD_OLDEST_TYPE : mode = RUN ; break ; case ABORT_TYPE : mode = RUN ; break ; } return mode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a <tt > WeakObject< / tt > for the given object . [CODESPLIT] public static WeakObject create ( final Object obj , final ReferenceQueue queue ) { if ( obj == null ) return null ; else return new WeakObject ( obj , queue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public -------------------------------------------------------- [CODESPLIT] public Collection listMembers ( URL baseUrl , URLFilter filter ) throws IOException { return listMembers ( baseUrl , filter , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starting from baseUrl that should point to a directory populate the resultList with the contents that pass the filter ( in the form of URLs ) and possibly recurse into subdris not containing a . in their name . [CODESPLIT] private void listFiles ( final URL baseUrl , final URLFilter filter , boolean scanNonDottedSubDirs , ArrayList < URL > resultList ) throws IOException { // List the files at the current dir level, using the provided filter final File baseDir = new File ( baseUrl . getPath ( ) ) ; String [ ] filenames = baseDir . list ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { try { return filter . accept ( baseUrl , name ) ; } catch ( Exception e ) { log . debug ( \"Unexpected exception filtering entry '\" + name + \"' in directory '\" + baseDir + \"'\" , e ) ; return true ; } } } ) ; if ( filenames == null ) { // This happens only when baseDir not a directory (but this is already // checked by the caller) or some unknown IOException happens internally // (e.g. run out of file descriptors?). Unfortunately the File API // doesn't provide a way to know. throw new IOException ( \"Could not list directory '\" + baseDir + \"', reason unknown\" ) ; } else { String baseUrlString = baseUrl . toString ( ) ; for ( int i = 0 ; i < filenames . length ; i ++ ) { String filename = filenames [ i ] ; // Find out if this is a directory File file = new File ( baseDir , filename ) ; boolean isDir = file . isDirectory ( ) ; // The subUrl URL subUrl = createURL ( baseUrlString , filename , isDir ) ; // If scanning subdirs and we have a directory, not containing a '.' in // the name, recurse into it. This is to allow recursing into grouping // dirs like ./deploy/jms, ./deploy/management, etc., avoiding // at the same time exploded packages, like .sar, .war, etc. if ( scanNonDottedSubDirs && isDir && ( filename . indexOf ( ' ' ) == - 1 ) ) { // recurse into it listFiles ( subUrl , filter , scanNonDottedSubDirs , resultList ) ; } else { // just add to the list resultList . add ( subUrl ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a URL by concatenating the baseUrlString that should end at / the filename and a trailing slash if it points to a directory [CODESPLIT] private URL createURL ( String baseUrlString , String filename , boolean isDirectory ) { try { return new URL ( baseUrlString + filename + ( isDirectory ? \"/\" : \"\" ) ) ; } catch ( MalformedURLException e ) { // shouldn't happen throw new IllegalStateException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup readers . [CODESPLIT] public void setupReaders ( ) { SAXParserFactory spf = SAXParserFactory . newInstance ( ) ; spf . setNamespaceAware ( true ) ; spf . setValidating ( false ) ; SAXCatalogReader saxReader = new SAXCatalogReader ( spf ) ; saxReader . setCatalogParser ( null , \"XMLCatalog\" , \"org.apache.xml.resolver.readers.XCatalogReader\" ) ; saxReader . setCatalogParser ( OASISXMLCatalogReader . namespaceName , \"catalog\" , \"org.apache.xml.resolver.readers.OASISXMLCatalogReader\" ) ; addReader ( \"application/xml\" , saxReader ) ; TR9401CatalogReader textReader = new TR9401CatalogReader ( ) ; addReader ( \"text/plain\" , textReader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new CatalogReader to the Catalog . [CODESPLIT] public void addReader ( String mimeType , CatalogReader reader ) { if ( readerMap . containsKey ( mimeType ) ) { Integer pos = ( Integer ) readerMap . get ( mimeType ) ; readerArr . set ( pos . intValue ( ) , reader ) ; } else { readerArr . add ( reader ) ; Integer pos = new Integer ( readerArr . size ( ) - 1 ) ; readerMap . put ( mimeType , pos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the reader list from the current Catalog to a new Catalog . [CODESPLIT] protected void copyReaders ( Catalog newCatalog ) { // Have to copy the readers in the right order...convert hash to arr Vector mapArr = new Vector ( readerMap . size ( ) ) ; // Pad the mapArr out to the right length for ( int count = 0 ; count < readerMap . size ( ) ; count ++ ) { mapArr . add ( null ) ; } Enumeration enumt = readerMap . keys ( ) ; while ( enumt . hasMoreElements ( ) ) { String mimeType = ( String ) enumt . nextElement ( ) ; Integer pos = ( Integer ) readerMap . get ( mimeType ) ; mapArr . set ( pos . intValue ( ) , mimeType ) ; } for ( int count = 0 ; count < mapArr . size ( ) ; count ++ ) { String mimeType = ( String ) mapArr . get ( count ) ; Integer pos = ( Integer ) readerMap . get ( mimeType ) ; newCatalog . addReader ( mimeType , ( CatalogReader ) readerArr . get ( pos . intValue ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new Catalog object . [CODESPLIT] protected Catalog newCatalog ( ) { String catalogClass = this . getClass ( ) . getName ( ) ; try { Catalog c = ( Catalog ) ( Class . forName ( catalogClass ) . newInstance ( ) ) ; c . setCatalogManager ( catalogManager ) ; copyReaders ( c ) ; return c ; } catch ( ClassNotFoundException cnfe ) { catalogManager . debug . message ( 1 , \"Class Not Found Exception: \" + catalogClass ) ; } catch ( IllegalAccessException iae ) { catalogManager . debug . message ( 1 , \"Illegal Access Exception: \" + catalogClass ) ; } catch ( InstantiationException ie ) { catalogManager . debug . message ( 1 , \"Instantiation Exception: \" + catalogClass ) ; } catch ( ClassCastException cce ) { catalogManager . debug . message ( 1 , \"Class Cast Exception: \" + catalogClass ) ; } catch ( Exception e ) { catalogManager . debug . message ( 1 , \"Other Exception: \" + catalogClass ) ; } Catalog c = new Catalog ( ) ; c . setCatalogManager ( catalogManager ) ; copyReaders ( c ) ; return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the system catalog files . [CODESPLIT] public void loadSystemCatalogs ( ) throws MalformedURLException , IOException { Vector catalogs = catalogManager . getCatalogFiles ( ) ; if ( catalogs != null ) { for ( int count = 0 ; count < catalogs . size ( ) ; count ++ ) { catalogFiles . addElement ( catalogs . elementAt ( count ) ) ; } } if ( catalogFiles . size ( ) > 0 ) { // This is a little odd. The parseCatalog() method expects // a filename, but it adds that name to the end of the // catalogFiles vector, and then processes that vector. // This allows the system to handle CATALOG entries // correctly. // // In this init case, we take the last element off the // catalogFiles vector and pass it to parseCatalog. This // will \"do the right thing\" in the init case, and allow // parseCatalog() to do the right thing in the non-init // case. Honest. // String catfile = ( String ) catalogFiles . lastElement ( ) ; catalogFiles . removeElement ( catfile ) ; parseCatalog ( catfile ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a catalog file augmenting internal data structures . [CODESPLIT] public synchronized void parseCatalog ( String fileName ) throws MalformedURLException , IOException { default_override = catalogManager . getPreferPublic ( ) ; catalogManager . debug . message ( 4 , \"Parse catalog: \" + fileName ) ; // Put the file into the list of catalogs to process... // In all cases except the case when initCatalog() is the // caller, this will be the only catalog initially in the list... catalogFiles . addElement ( fileName ) ; // Now process all the pending catalogs... parsePendingCatalogs ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a catalog file augmenting internal data structures . [CODESPLIT] public synchronized void parseCatalog ( String mimeType , InputStream is ) throws IOException , CatalogException { default_override = catalogManager . getPreferPublic ( ) ; catalogManager . debug . message ( 4 , \"Parse \" + mimeType + \" catalog on input stream\" ) ; CatalogReader reader = null ; if ( readerMap . containsKey ( mimeType ) ) { int arrayPos = ( ( Integer ) readerMap . get ( mimeType ) ) . intValue ( ) ; reader = ( CatalogReader ) readerArr . get ( arrayPos ) ; } if ( reader == null ) { String msg = \"No CatalogReader for MIME type: \" + mimeType ; catalogManager . debug . message ( 2 , msg ) ; throw new CatalogException ( CatalogException . UNPARSEABLE , msg ) ; } reader . readCatalog ( this , is ) ; // Now process all the pending catalogs... parsePendingCatalogs ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a catalog document augmenting internal data structures . [CODESPLIT] public synchronized void parseCatalog ( URL aUrl ) throws IOException { catalogCwd = aUrl ; base = aUrl ; default_override = catalogManager . getPreferPublic ( ) ; catalogManager . debug . message ( 4 , \"Parse catalog: \" + aUrl . toString ( ) ) ; DataInputStream inStream = null ; boolean parsed = false ; for ( int count = 0 ; ! parsed && count < readerArr . size ( ) ; count ++ ) { CatalogReader reader = ( CatalogReader ) readerArr . get ( count ) ; try { inStream = new DataInputStream ( aUrl . openStream ( ) ) ; } catch ( FileNotFoundException fnfe ) { // No catalog; give up! break ; } try { reader . readCatalog ( this , inStream ) ; parsed = true ; } catch ( CatalogException ce ) { if ( ce . getExceptionType ( ) == CatalogException . PARSE_FAILED ) { // give up! break ; } else { // try again! } } try { inStream . close ( ) ; } catch ( IOException e ) { //nop } } if ( parsed ) parsePendingCatalogs ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse all of the pending catalogs . [CODESPLIT] protected synchronized void parsePendingCatalogs ( ) throws MalformedURLException , IOException { if ( ! localCatalogFiles . isEmpty ( ) ) { // Move all the localCatalogFiles into the front of // the catalogFiles queue Vector newQueue = new Vector ( ) ; Enumeration q = localCatalogFiles . elements ( ) ; while ( q . hasMoreElements ( ) ) { newQueue . addElement ( q . nextElement ( ) ) ; } // Put the rest of the catalogs on the end of the new list for ( int curCat = 0 ; curCat < catalogFiles . size ( ) ; curCat ++ ) { String catfile = ( String ) catalogFiles . elementAt ( curCat ) ; newQueue . addElement ( catfile ) ; } catalogFiles = newQueue ; localCatalogFiles . clear ( ) ; } // Suppose there are no catalog files to process, but the // single catalog already parsed included some delegate // entries? Make sure they don't get lost. if ( catalogFiles . isEmpty ( ) && ! localDelegate . isEmpty ( ) ) { Enumeration e = localDelegate . elements ( ) ; while ( e . hasMoreElements ( ) ) { catalogEntries . addElement ( e . nextElement ( ) ) ; } localDelegate . clear ( ) ; } // Now process all the files on the catalogFiles vector. This // vector can grow during processing if CATALOG entries are // encountered in the catalog while ( ! catalogFiles . isEmpty ( ) ) { String catfile = ( String ) catalogFiles . elementAt ( 0 ) ; try { catalogFiles . remove ( 0 ) ; } catch ( ArrayIndexOutOfBoundsException e ) { // can't happen } if ( catalogEntries . size ( ) == 0 && catalogs . size ( ) == 0 ) { // We haven't parsed any catalogs yet, let this // catalog be the first... try { parseCatalogFile ( catfile ) ; } catch ( CatalogException ce ) { System . out . println ( \"FIXME: \" + ce . toString ( ) ) ; } } else { // This is a subordinate catalog. We save its name, // but don't bother to load it unless it's necessary. catalogs . addElement ( catfile ) ; } if ( ! localCatalogFiles . isEmpty ( ) ) { // Move all the localCatalogFiles into the front of // the catalogFiles queue Vector newQueue = new Vector ( ) ; Enumeration q = localCatalogFiles . elements ( ) ; while ( q . hasMoreElements ( ) ) { newQueue . addElement ( q . nextElement ( ) ) ; } // Put the rest of the catalogs on the end of the new list for ( int curCat = 0 ; curCat < catalogFiles . size ( ) ; curCat ++ ) { catfile = ( String ) catalogFiles . elementAt ( curCat ) ; newQueue . addElement ( catfile ) ; } catalogFiles = newQueue ; localCatalogFiles . clear ( ) ; } if ( ! localDelegate . isEmpty ( ) ) { Enumeration e = localDelegate . elements ( ) ; while ( e . hasMoreElements ( ) ) { catalogEntries . addElement ( e . nextElement ( ) ) ; } localDelegate . clear ( ) ; } } // We've parsed them all, reinit the vector... catalogFiles . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse a single catalog file augmenting internal data structures . [CODESPLIT] protected synchronized void parseCatalogFile ( String fileName ) throws MalformedURLException , IOException , CatalogException { // The base-base is the cwd. If the catalog file is specified // with a relative path, this assures that it gets resolved // properly... try { // tack on a basename because URLs point to files not dirs String userdir = fixSlashes ( System . getProperty ( \"user.dir\" ) ) ; catalogCwd = new URL ( \"file:\" + userdir + \"/basename\" ) ; } catch ( MalformedURLException e ) { String userdir = fixSlashes ( System . getProperty ( \"user.dir\" ) ) ; catalogManager . debug . message ( 1 , \"Malformed URL on cwd\" , userdir ) ; catalogCwd = null ; } // The initial base URI is the location of the catalog file try { base = new URL ( catalogCwd , fixSlashes ( fileName ) ) ; } catch ( MalformedURLException e ) { try { base = new URL ( \"file:\" + fixSlashes ( fileName ) ) ; } catch ( MalformedURLException e2 ) { catalogManager . debug . message ( 1 , \"Malformed URL on catalog filename\" , fixSlashes ( fileName ) ) ; base = null ; } } catalogManager . debug . message ( 2 , \"Loading catalog\" , fileName ) ; catalogManager . debug . message ( 4 , \"Default BASE\" , base . toString ( ) ) ; fileName = base . toString ( ) ; DataInputStream inStream = null ; boolean parsed = false ; boolean notFound = false ; for ( int count = 0 ; ! parsed && count < readerArr . size ( ) ; count ++ ) { CatalogReader reader = ( CatalogReader ) readerArr . get ( count ) ; try { notFound = false ; inStream = new DataInputStream ( base . openStream ( ) ) ; } catch ( FileNotFoundException fnfe ) { // No catalog; give up! notFound = true ; break ; } try { reader . readCatalog ( this , inStream ) ; parsed = true ; } catch ( CatalogException ce ) { if ( ce . getExceptionType ( ) == CatalogException . PARSE_FAILED ) { // give up! break ; } else { // try again! } } try { inStream . close ( ) ; } catch ( IOException e ) { //nop } } if ( ! parsed ) { if ( notFound ) { catalogManager . debug . message ( 3 , \"Catalog does not exist\" , fileName ) ; } else { catalogManager . debug . message ( 1 , \"Failed to parse catalog\" , fileName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleanup and process a Catalog entry . [CODESPLIT] public void addEntry ( CatalogEntry entry ) { int type = entry . getEntryType ( ) ; if ( type == BASE ) { String value = entry . getEntryArg ( 0 ) ; URL newbase = null ; catalogManager . debug . message ( 5 , \"BASE CUR\" , base . toString ( ) ) ; catalogManager . debug . message ( 4 , \"BASE STR\" , value ) ; try { value = fixSlashes ( value ) ; newbase = new URL ( base , value ) ; } catch ( MalformedURLException e ) { try { newbase = new URL ( \"file:\" + value ) ; } catch ( MalformedURLException e2 ) { catalogManager . debug . message ( 1 , \"Malformed URL on base\" , value ) ; newbase = null ; } } if ( newbase != null ) { base = newbase ; } catalogManager . debug . message ( 5 , \"BASE NEW\" , base . toString ( ) ) ; } else if ( type == CATALOG ) { String fsi = makeAbsolute ( entry . getEntryArg ( 0 ) ) ; catalogManager . debug . message ( 4 , \"CATALOG\" , fsi ) ; localCatalogFiles . addElement ( fsi ) ; } else if ( type == PUBLIC ) { String publicid = PublicId . normalize ( entry . getEntryArg ( 0 ) ) ; String systemid = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 0 , publicid ) ; entry . setEntryArg ( 1 , systemid ) ; catalogManager . debug . message ( 4 , \"PUBLIC\" , publicid , systemid ) ; catalogEntries . addElement ( entry ) ; } else if ( type == SYSTEM ) { String systemid = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"SYSTEM\" , systemid , fsi ) ; catalogEntries . addElement ( entry ) ; } else if ( type == URI ) { String uri = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String altURI = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , altURI ) ; catalogManager . debug . message ( 4 , \"URI\" , uri , altURI ) ; catalogEntries . addElement ( entry ) ; } else if ( type == DOCUMENT ) { String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 0 ) ) ) ; entry . setEntryArg ( 0 , fsi ) ; catalogManager . debug . message ( 4 , \"DOCUMENT\" , fsi ) ; catalogEntries . addElement ( entry ) ; } else if ( type == OVERRIDE ) { catalogManager . debug . message ( 4 , \"OVERRIDE\" , entry . getEntryArg ( 0 ) ) ; catalogEntries . addElement ( entry ) ; } else if ( type == SGMLDECL ) { // meaningless in XML String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 0 ) ) ) ; entry . setEntryArg ( 0 , fsi ) ; catalogManager . debug . message ( 4 , \"SGMLDECL\" , fsi ) ; catalogEntries . addElement ( entry ) ; } else if ( type == DELEGATE_PUBLIC ) { String ppi = PublicId . normalize ( entry . getEntryArg ( 0 ) ) ; String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 0 , ppi ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"DELEGATE_PUBLIC\" , ppi , fsi ) ; addDelegate ( entry ) ; } else if ( type == DELEGATE_SYSTEM ) { String psi = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 0 , psi ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"DELEGATE_SYSTEM\" , psi , fsi ) ; addDelegate ( entry ) ; } else if ( type == DELEGATE_URI ) { String pui = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 0 , pui ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"DELEGATE_URI\" , pui , fsi ) ; addDelegate ( entry ) ; } else if ( type == REWRITE_SYSTEM ) { String psi = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String rpx = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 0 , psi ) ; entry . setEntryArg ( 1 , rpx ) ; catalogManager . debug . message ( 4 , \"REWRITE_SYSTEM\" , psi , rpx ) ; catalogEntries . addElement ( entry ) ; } else if ( type == REWRITE_URI ) { String pui = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String upx = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 0 , pui ) ; entry . setEntryArg ( 1 , upx ) ; catalogManager . debug . message ( 4 , \"REWRITE_URI\" , pui , upx ) ; catalogEntries . addElement ( entry ) ; } else if ( type == DOCTYPE ) { String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"DOCTYPE\" , entry . getEntryArg ( 0 ) , fsi ) ; catalogEntries . addElement ( entry ) ; } else if ( type == DTDDECL ) { // meaningless in XML String fpi = PublicId . normalize ( entry . getEntryArg ( 0 ) ) ; entry . setEntryArg ( 0 , fpi ) ; String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"DTDDECL\" , fpi , fsi ) ; catalogEntries . addElement ( entry ) ; } else if ( type == ENTITY ) { String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"ENTITY\" , entry . getEntryArg ( 0 ) , fsi ) ; catalogEntries . addElement ( entry ) ; } else if ( type == LINKTYPE ) { // meaningless in XML String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"LINKTYPE\" , entry . getEntryArg ( 0 ) , fsi ) ; catalogEntries . addElement ( entry ) ; } else if ( type == NOTATION ) { String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"NOTATION\" , entry . getEntryArg ( 0 ) , fsi ) ; catalogEntries . addElement ( entry ) ; } else { catalogEntries . addElement ( entry ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle unknown CatalogEntry types . [CODESPLIT] public void unknownEntry ( Vector strings ) { if ( strings != null && strings . size ( ) > 0 ) { String keyword = ( String ) strings . elementAt ( 0 ) ; catalogManager . debug . message ( 2 , \"Unrecognized token parsing catalog\" , keyword ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse all subordinate catalogs . [CODESPLIT] public void parseAllCatalogs ( ) throws MalformedURLException , IOException { // Parse all the subordinate catalogs for ( int catPos = 0 ; catPos < catalogs . size ( ) ; catPos ++ ) { Catalog c = null ; try { c = ( Catalog ) catalogs . elementAt ( catPos ) ; } catch ( ClassCastException e ) { String catfile = ( String ) catalogs . elementAt ( catPos ) ; c = newCatalog ( ) ; c . parseCatalog ( catfile ) ; catalogs . setElementAt ( c , catPos ) ; c . parseAllCatalogs ( ) ; } } // Parse all the DELEGATE catalogs Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == DELEGATE_PUBLIC || e . getEntryType ( ) == DELEGATE_SYSTEM || e . getEntryType ( ) == DELEGATE_URI ) { Catalog dcat = newCatalog ( ) ; dcat . parseCatalog ( e . getEntryArg ( 1 ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable DOCTYPE system identifier . [CODESPLIT] public String resolveDoctype ( String entityName , String publicId , String systemId ) throws MalformedURLException , IOException { String resolved = null ; catalogManager . debug . message ( 3 , \"resolveDoctype(\" + entityName + \",\" + publicId + \",\" + systemId + \")\" ) ; systemId = normalizeURI ( systemId ) ; if ( publicId != null && publicId . startsWith ( \"urn:publicid:\" ) ) { publicId = PublicId . decodeURN ( publicId ) ; } if ( systemId != null && systemId . startsWith ( \"urn:publicid:\" ) ) { systemId = PublicId . decodeURN ( systemId ) ; if ( publicId != null && ! publicId . equals ( systemId ) ) { catalogManager . debug . message ( 1 , \"urn:publicid: system identifier differs from public identifier; using public identifier\" ) ; systemId = null ; } else { publicId = systemId ; systemId = null ; } } if ( systemId != null ) { // If there's a SYSTEM entry in this catalog, use it resolved = resolveLocalSystem ( systemId ) ; if ( resolved != null ) { return resolved ; } } if ( publicId != null ) { // If there's a PUBLIC entry in this catalog, use it resolved = resolveLocalPublic ( DOCTYPE , entityName , publicId , systemId ) ; if ( resolved != null ) { return resolved ; } } // If there's a DOCTYPE entry in this catalog, use it boolean over = default_override ; Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == OVERRIDE ) { over = e . getEntryArg ( 0 ) . equalsIgnoreCase ( \"YES\" ) ; continue ; } if ( e . getEntryType ( ) == DOCTYPE && e . getEntryArg ( 0 ) . equals ( entityName ) ) { if ( over || systemId == null ) { return e . getEntryArg ( 1 ) ; } } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs ( DOCTYPE , entityName , publicId , systemId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable DOCUMENT entry . [CODESPLIT] public String resolveDocument ( ) throws MalformedURLException , IOException { // If there's a DOCUMENT entry, return it catalogManager . debug . message ( 3 , \"resolveDocument\" ) ; Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == DOCUMENT ) { return e . getEntryArg ( 1 ) ; //FIXME check this } } return resolveSubordinateCatalogs ( DOCUMENT , null , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable PUBLIC or SYSTEM identifier . [CODESPLIT] public String resolvePublic ( String publicId , String systemId ) throws MalformedURLException , IOException { catalogManager . debug . message ( 3 , \"resolvePublic(\" + publicId + \",\" + systemId + \")\" ) ; systemId = normalizeURI ( systemId ) ; if ( publicId != null && publicId . startsWith ( \"urn:publicid:\" ) ) { publicId = PublicId . decodeURN ( publicId ) ; } if ( systemId != null && systemId . startsWith ( \"urn:publicid:\" ) ) { systemId = PublicId . decodeURN ( systemId ) ; if ( publicId != null && ! publicId . equals ( systemId ) ) { catalogManager . debug . message ( 1 , \"urn:publicid: system identifier differs from public identifier; using public identifier\" ) ; systemId = null ; } else { publicId = systemId ; systemId = null ; } } // If there's a SYSTEM entry in this catalog, use it if ( systemId != null ) { String resolved = resolveLocalSystem ( systemId ) ; if ( resolved != null ) { return resolved ; } } // If there's a PUBLIC entry in this catalog, use it String resolved = resolveLocalPublic ( PUBLIC , null , publicId , systemId ) ; if ( resolved != null ) { return resolved ; } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs ( PUBLIC , null , publicId , systemId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable PUBLIC or SYSTEM identifier . [CODESPLIT] protected synchronized String resolveLocalPublic ( int entityType , String entityName , String publicId , String systemId ) throws MalformedURLException , IOException { // Always normalize the public identifier before attempting a match publicId = PublicId . normalize ( publicId ) ; // If there's a SYSTEM entry in this catalog, use it if ( systemId != null ) { String resolved = resolveLocalSystem ( systemId ) ; if ( resolved != null ) { return resolved ; } } // If there's a PUBLIC entry in this catalog, use it boolean over = default_override ; Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == OVERRIDE ) { over = e . getEntryArg ( 0 ) . equalsIgnoreCase ( \"YES\" ) ; continue ; } if ( e . getEntryType ( ) == PUBLIC && e . getEntryArg ( 0 ) . equals ( publicId ) ) { if ( over || systemId == null ) { return e . getEntryArg ( 1 ) ; } } } // If there's a DELEGATE_PUBLIC entry in this catalog, use it over = default_override ; enumt = catalogEntries . elements ( ) ; Vector delCats = new Vector ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == OVERRIDE ) { over = e . getEntryArg ( 0 ) . equalsIgnoreCase ( \"YES\" ) ; continue ; } if ( e . getEntryType ( ) == DELEGATE_PUBLIC && ( over || systemId == null ) ) { String p = e . getEntryArg ( 0 ) ; if ( p . length ( ) <= publicId . length ( ) && p . equals ( publicId . substring ( 0 , p . length ( ) ) ) ) { // delegate this match to the other catalog delCats . addElement ( e . getEntryArg ( 1 ) ) ; } } } if ( delCats . size ( ) > 0 ) { Enumeration enumCats = delCats . elements ( ) ; if ( catalogManager . debug . getDebug ( ) > 1 ) { catalogManager . debug . message ( 2 , \"Switching to delegated catalog(s):\" ) ; while ( enumCats . hasMoreElements ( ) ) { String delegatedCatalog = ( String ) enumCats . nextElement ( ) ; catalogManager . debug . message ( 2 , \"\\t\" + delegatedCatalog ) ; } } Catalog dcat = newCatalog ( ) ; enumCats = delCats . elements ( ) ; while ( enumCats . hasMoreElements ( ) ) { String delegatedCatalog = ( String ) enumCats . nextElement ( ) ; dcat . parseCatalog ( delegatedCatalog ) ; } return dcat . resolvePublic ( publicId , null ) ; } // Nada! return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable SYSTEM system identifier . [CODESPLIT] public String resolveSystem ( String systemId ) throws MalformedURLException , IOException { catalogManager . debug . message ( 3 , \"resolveSystem(\" + systemId + \")\" ) ; systemId = normalizeURI ( systemId ) ; if ( systemId != null && systemId . startsWith ( \"urn:publicid:\" ) ) { systemId = PublicId . decodeURN ( systemId ) ; return resolvePublic ( systemId , null ) ; } // If there's a SYSTEM entry in this catalog, use it if ( systemId != null ) { String resolved = resolveLocalSystem ( systemId ) ; if ( resolved != null ) { return resolved ; } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs ( SYSTEM , null , null , systemId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable SYSTEM system identifier in this catalog . [CODESPLIT] protected String resolveLocalSystem ( String systemId ) throws MalformedURLException , IOException { String osname = System . getProperty ( \"os.name\" ) ; boolean windows = ( osname . indexOf ( \"Windows\" ) >= 0 ) ; Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == SYSTEM && ( e . getEntryArg ( 0 ) . equals ( systemId ) || ( windows && e . getEntryArg ( 0 ) . equalsIgnoreCase ( systemId ) ) ) ) { return e . getEntryArg ( 1 ) ; } } // If there's a REWRITE_SYSTEM entry in this catalog, use it enumt = catalogEntries . elements ( ) ; String startString = null ; String prefix = null ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == REWRITE_SYSTEM ) { String p = e . getEntryArg ( 0 ) ; if ( p . length ( ) <= systemId . length ( ) && p . equals ( systemId . substring ( 0 , p . length ( ) ) ) ) { // Is this the longest prefix? if ( startString == null || p . length ( ) > startString . length ( ) ) { startString = p ; prefix = e . getEntryArg ( 1 ) ; } } } if ( prefix != null ) { // return the systemId with the new prefix return prefix + systemId . substring ( startString . length ( ) ) ; } } // If there's a DELEGATE_SYSTEM entry in this catalog, use it enumt = catalogEntries . elements ( ) ; Vector delCats = new Vector ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == DELEGATE_SYSTEM ) { String p = e . getEntryArg ( 0 ) ; if ( p . length ( ) <= systemId . length ( ) && p . equals ( systemId . substring ( 0 , p . length ( ) ) ) ) { // delegate this match to the other catalog delCats . addElement ( e . getEntryArg ( 1 ) ) ; } } } if ( delCats . size ( ) > 0 ) { Enumeration enumCats = delCats . elements ( ) ; if ( catalogManager . debug . getDebug ( ) > 1 ) { catalogManager . debug . message ( 2 , \"Switching to delegated catalog(s):\" ) ; while ( enumCats . hasMoreElements ( ) ) { String delegatedCatalog = ( String ) enumCats . nextElement ( ) ; catalogManager . debug . message ( 2 , \"\\t\" + delegatedCatalog ) ; } } Catalog dcat = newCatalog ( ) ; enumCats = delCats . elements ( ) ; while ( enumCats . hasMoreElements ( ) ) { String delegatedCatalog = ( String ) enumCats . nextElement ( ) ; dcat . parseCatalog ( delegatedCatalog ) ; } return dcat . resolveSystem ( systemId ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable URI . [CODESPLIT] public String resolveURI ( String uri ) throws MalformedURLException , IOException { catalogManager . debug . message ( 3 , \"resolveURI(\" + uri + \")\" ) ; uri = normalizeURI ( uri ) ; if ( uri != null && uri . startsWith ( \"urn:publicid:\" ) ) { uri = PublicId . decodeURN ( uri ) ; return resolvePublic ( uri , null ) ; } // If there's a URI entry in this catalog, use it if ( uri != null ) { String resolved = resolveLocalURI ( uri ) ; if ( resolved != null ) { return resolved ; } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs ( URI , null , null , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable URI in this catalog . [CODESPLIT] protected String resolveLocalURI ( String uri ) throws MalformedURLException , IOException { Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == URI && ( e . getEntryArg ( 0 ) . equals ( uri ) ) ) { return e . getEntryArg ( 1 ) ; } } // If there's a REWRITE_URI entry in this catalog, use it enumt = catalogEntries . elements ( ) ; String startString = null ; String prefix = null ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == REWRITE_URI ) { String p = e . getEntryArg ( 0 ) ; if ( p . length ( ) <= uri . length ( ) && p . equals ( uri . substring ( 0 , p . length ( ) ) ) ) { // Is this the longest prefix? if ( startString == null || p . length ( ) > startString . length ( ) ) { startString = p ; prefix = e . getEntryArg ( 1 ) ; } } } if ( prefix != null ) { // return the systemId with the new prefix return prefix + uri . substring ( startString . length ( ) ) ; } } // If there's a DELEGATE_URI entry in this catalog, use it enumt = catalogEntries . elements ( ) ; Vector delCats = new Vector ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == DELEGATE_URI ) { String p = e . getEntryArg ( 0 ) ; if ( p . length ( ) <= uri . length ( ) && p . equals ( uri . substring ( 0 , p . length ( ) ) ) ) { // delegate this match to the other catalog delCats . addElement ( e . getEntryArg ( 1 ) ) ; } } } if ( delCats . size ( ) > 0 ) { Enumeration enumCats = delCats . elements ( ) ; if ( catalogManager . debug . getDebug ( ) > 1 ) { catalogManager . debug . message ( 2 , \"Switching to delegated catalog(s):\" ) ; while ( enumCats . hasMoreElements ( ) ) { String delegatedCatalog = ( String ) enumCats . nextElement ( ) ; catalogManager . debug . message ( 2 , \"\\t\" + delegatedCatalog ) ; } } Catalog dcat = newCatalog ( ) ; enumCats = delCats . elements ( ) ; while ( enumCats . hasMoreElements ( ) ) { String delegatedCatalog = ( String ) enumCats . nextElement ( ) ; dcat . parseCatalog ( delegatedCatalog ) ; } return dcat . resolveURI ( uri ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the subordinate catalogs in order looking for a match . [CODESPLIT] protected synchronized String resolveSubordinateCatalogs ( int entityType , String entityName , String publicId , String systemId ) throws MalformedURLException , IOException { for ( int catPos = 0 ; catPos < catalogs . size ( ) ; catPos ++ ) { Catalog c = null ; try { c = ( Catalog ) catalogs . elementAt ( catPos ) ; } catch ( ClassCastException e ) { String catfile = ( String ) catalogs . elementAt ( catPos ) ; c = newCatalog ( ) ; try { c . parseCatalog ( catfile ) ; } catch ( MalformedURLException mue ) { catalogManager . debug . message ( 1 , \"Malformed Catalog URL\" , catfile ) ; } catch ( FileNotFoundException fnfe ) { catalogManager . debug . message ( 1 , \"Failed to load catalog, file not found\" , catfile ) ; } catch ( IOException ioe ) { catalogManager . debug . message ( 1 , \"Failed to load catalog, I/O error\" , catfile ) ; } catalogs . setElementAt ( c , catPos ) ; } String resolved = null ; // Ok, now what are we supposed to call here? if ( entityType == DOCTYPE ) { resolved = c . resolveDoctype ( entityName , publicId , systemId ) ; } else if ( entityType == DOCUMENT ) { resolved = c . resolveDocument ( ) ; } else if ( entityType == ENTITY ) { resolved = c . resolveEntity ( entityName , publicId , systemId ) ; } else if ( entityType == NOTATION ) { resolved = c . resolveNotation ( entityName , publicId , systemId ) ; } else if ( entityType == PUBLIC ) { resolved = c . resolvePublic ( publicId , systemId ) ; } else if ( entityType == SYSTEM ) { resolved = c . resolveSystem ( systemId ) ; } else if ( entityType == URI ) { resolved = c . resolveURI ( systemId ) ; } if ( resolved != null ) { return resolved ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct an absolute URI from a relative one using the current base URI . [CODESPLIT] protected String makeAbsolute ( String sysid ) { URL local = null ; sysid = fixSlashes ( sysid ) ; try { local = new URL ( base , sysid ) ; } catch ( MalformedURLException e ) { catalogManager . debug . message ( 1 , \"Malformed URL on system identifier\" , sysid ) ; } if ( local != null ) { return local . toString ( ) ; } else { return sysid ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform character normalization on a URI reference . [CODESPLIT] protected String normalizeURI ( String uriref ) { String newRef = \"\" ; byte [ ] bytes ; if ( uriref == null ) { return null ; } try { bytes = uriref . getBytes ( \"UTF-8\" ) ; } catch ( UnsupportedEncodingException uee ) { // this can't happen catalogManager . debug . message ( 1 , \"UTF-8 is an unsupported encoding!?\" ) ; return uriref ; } for ( int count = 0 ; count < bytes . length ; count ++ ) { int ch = bytes [ count ] & 0xFF ; if ( ( ch <= 0x20 ) // ctrl || ( ch > 0x7F ) // high ascii || ( ch == 0x22 ) // \" || ( ch == 0x3C ) // < || ( ch == 0x3E ) // > || ( ch == 0x5C ) // \\ || ( ch == 0x5E ) // ^ || ( ch == 0x60 ) // ` || ( ch == 0x7B ) // { || ( ch == 0x7C ) // | || ( ch == 0x7D ) // } || ( ch == 0x7F ) ) { newRef += encodedByte ( ch ) ; } else { newRef += ( char ) bytes [ count ] ; } } return newRef ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform % - encoding on a single byte . [CODESPLIT] protected String encodedByte ( int b ) { String hex = Integer . toHexString ( b ) . toUpperCase ( ) ; if ( hex . length ( ) < 2 ) { return \"%0\" + hex ; } else { return \"%\" + hex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add to the current list of delegated catalogs . [CODESPLIT] protected void addDelegate ( CatalogEntry entry ) { int pos = 0 ; String partial = entry . getEntryArg ( 0 ) ; Enumeration local = localDelegate . elements ( ) ; while ( local . hasMoreElements ( ) ) { CatalogEntry dpe = ( CatalogEntry ) local . nextElement ( ) ; String dp = dpe . getEntryArg ( 0 ) ; if ( dp . equals ( partial ) ) { // we already have this prefix return ; } if ( dp . length ( ) > partial . length ( ) ) { pos ++ ; } if ( dp . length ( ) < partial . length ( ) ) { break ; } } // now insert partial into the vector at [pos] if ( localDelegate . size ( ) == 0 ) { localDelegate . addElement ( entry ) ; } else { localDelegate . insertElementAt ( entry , pos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a server socket on the specified port ( port 0 indicates an anonymous port ) . [CODESPLIT] public Socket createSocket ( String host , int port ) throws IOException { Socket s = new Socket ( host , port ) ; s . setSoTimeout ( 1000 ) ; TimeoutSocket ts = new TimeoutSocket ( s ) ; return ts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a int [] from comma or eol seperated elements [CODESPLIT] public void setAsText ( final String text ) { StringTokenizer stok = new StringTokenizer ( text , \",\\r\\n\" ) ; int [ ] theValue = new int [ stok . countTokens ( ) ] ; int i = 0 ; while ( stok . hasMoreTokens ( ) ) { theValue [ i ++ ] = Integer . decode ( stok . nextToken ( ) ) . intValue ( ) ; } setValue ( theValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Safely create a new SoftValueRef [CODESPLIT] static < K , V > SoftValueRef < K , V > create ( K key , V val , ReferenceQueue < V > q ) { if ( val == null ) return null ; else return new SoftValueRef < K , V > ( key , val , q ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Properties object initialized with current getAsText value interpretted as a . properties file contents . This replaces any references of the form $ { x } with the corresponding system property . [CODESPLIT] public Object getValue ( ) { try { // Load the current key=value properties into a Properties object String propsText = getAsText ( ) ; Properties rawProps = new Properties ( System . getProperties ( ) ) ; ByteArrayInputStream bais = new ByteArrayInputStream ( propsText . getBytes ( ) ) ; rawProps . load ( bais ) ; // Now go through the rawProps and replace any ${x} refs Properties props = new Properties ( ) ; Iterator keys = rawProps . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String key = ( String ) keys . next ( ) ; String value = rawProps . getProperty ( key ) ; String value2 = StringPropertyReplacer . replaceProperties ( value , rawProps ) ; props . setProperty ( key , value2 ) ; } rawProps . clear ( ) ; return props ; } catch ( IOException e ) { throw new NestedRuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire onThrowable to all registered listeners . [CODESPLIT] protected static void fireOnThrowable ( int type , Throwable t ) { Object [ ] list = listeners . toArray ( ) ; for ( int i = 0 ; i < list . length ; i ++ ) { ( ( ThrowableListener ) list [ i ] ) . onThrowable ( type , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a throwable that is to be handled . [CODESPLIT] public static void add ( int type , Throwable t ) { // don't add null throwables if ( t == null ) return ; try { fireOnThrowable ( type , t ) ; } catch ( Throwable bad ) { // don't let these propagate, that could introduce unwanted side-effects System . err . println ( \"Unable to handle throwable: \" + t + \" because of:\" ) ; bad . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the list implementation [CODESPLIT] private List < T > createImplementation ( ) { if ( delegate instanceof ArrayList == false ) return new ArrayList < T > ( delegate ) ; return delegate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an element to the set . [CODESPLIT] public boolean add ( final Object obj ) { boolean added = false ; if ( ! list . contains ( obj ) ) { added = list . add ( obj ) ; } return added ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a server socket on the specified port ( port 0 indicates an anonymous port ) . [CODESPLIT] public Socket createSocket ( String host , int port ) throws IOException { try { permits . acquire ( ) ; return new Socket ( host , port ) ; } catch ( InterruptedException ex ) { throw new IOException ( \"Failed to acquire FIFOSemaphore for ClientSocketFactory\" ) ; } finally { permits . release ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a server socket on the specified port ( port 0 indicates an anonymous port ) . [CODESPLIT] public Socket createSocket ( String host , int port ) throws IOException { InetAddress addr = null ; if ( bindAddress != null ) addr = bindAddress ; else addr = InetAddress . getByName ( host ) ; Socket s = new Socket ( addr , port ) ; return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A TimerTask is less than another if it will be scheduled before . [CODESPLIT] public int compareTo ( Object other ) { if ( other == this ) return 0 ; TimerTask t = ( TimerTask ) other ; long diff = getNextExecutionTime ( ) - t . getNextExecutionTime ( ) ; return ( int ) diff ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a InetAddress for the input object converted to a string . [CODESPLIT] public Object getValue ( ) { try { String text = getAsText ( ) ; if ( text == null ) { return null ; } if ( text . startsWith ( \"/\" ) ) { // seems like localhost sometimes will look like: // /127.0.0.1 and the getByNames barfs on the slash - JGH text = text . substring ( 1 ) ; } return InetAddress . getByName ( StringPropertyReplacer . replaceProperties ( text ) ) ; } catch ( UnknownHostException e ) { throw new NestedRuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a file is acceptible . [CODESPLIT] public boolean accept ( final File file ) { boolean success = false ; for ( int i = 0 ; i < suffixes . length && ! success ; i ++ ) { if ( ignoreCase ) success = file . getName ( ) . toLowerCase ( ) . endsWith ( suffixes [ i ] ) ; else success = file . getName ( ) . endsWith ( suffixes [ i ] ) ; } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dereference the object at the given index . [CODESPLIT] private Object getObject ( final int index ) { Object obj = list . get ( index ) ; return Objects . deref ( obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the element at the specified position in this list with the specified element . [CODESPLIT] public Object set ( final int index , final Object obj ) { maintain ( ) ; SoftObject soft = SoftObject . create ( obj , queue ) ; soft = ( SoftObject ) list . set ( index , soft ) ; return Objects . deref ( soft ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the specified element at the specified position in this list ( optional operation ) . Shifts the element currently at that position ( if any ) and any subsequent elements to the right ( adds one to their indices ) . [CODESPLIT] public void add ( final int index , final Object obj ) { maintain ( ) ; SoftObject soft = SoftObject . create ( obj , queue ) ; list . add ( index , soft ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the element at the specified position in this list ( optional operation ) . Shifts any subsequent elements to the left ( subtracts one from their indices ) . Returns the element that was removed from the list . [CODESPLIT] public Object remove ( final int index ) { maintain ( ) ; Object obj = list . remove ( index ) ; return Objects . deref ( obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maintains the collection by removing garbage collected objects . [CODESPLIT] private void maintain ( ) { SoftObject obj ; int count = 0 ; while ( ( obj = ( SoftObject ) queue . poll ( ) ) != null ) { count ++ ; list . remove ( obj ) ; } if ( count != 0 ) { // some temporary debugging fluff System . err . println ( \"vm reclaimed \" + count + \" objects\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new catalog entry type . [CODESPLIT] public static int addEntryType ( String name , int numArgs ) { entryTypes . put ( name , new Integer ( nextEntry ) ) ; entryArgs . add ( nextEntry , new Integer ( numArgs ) ) ; nextEntry ++ ; return nextEntry - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup an entry type [CODESPLIT] public static int getEntryType ( String name ) throws CatalogException { if ( ! entryTypes . containsKey ( name ) ) { throw new CatalogException ( CatalogException . INVALID_ENTRY_TYPE ) ; } Integer iType = ( Integer ) entryTypes . get ( name ) ; if ( iType == null ) { throw new CatalogException ( CatalogException . INVALID_ENTRY_TYPE ) ; } return iType . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find out how many arguments an entry is required to have . [CODESPLIT] public static int getEntryArgCount ( int type ) throws CatalogException { try { Integer iArgs = ( Integer ) entryArgs . get ( type ) ; return iArgs . intValue ( ) ; } catch ( ArrayIndexOutOfBoundsException e ) { throw new CatalogException ( CatalogException . INVALID_ENTRY_TYPE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an entry argument . [CODESPLIT] public String getEntryArg ( int argNum ) { try { String arg = ( String ) args . get ( argNum ) ; return arg ; } catch ( ArrayIndexOutOfBoundsException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the given element in this heap . @param obj [CODESPLIT] public void insert ( Object obj ) { int length = m_nodes . length ; // Expand if necessary if ( m_count == length ) { Object [ ] newNodes = new Object [ length + length ] ; System . arraycopy ( m_nodes , 0 , newNodes , 0 , length ) ; m_nodes = newNodes ; } // Be cur_slot the first unused slot index; be par_slot its parent index. // Start from cur_slot and walk up the tree comparing the object to  // insert with the object at par_slot; if it's smaller move down the object at par_slot, // otherwise cur_slot is the index where insert the object. If not done,  // shift up the tree so that now cur_slot is the old par_slot and  // par_slot is the parent index of the new cur_slot (so the grand-parent // index of the old cur_slot) and compare again. int k = m_count ; while ( k > 0 ) { int par = parent ( k ) ; if ( compare ( obj , m_nodes [ par ] ) < 0 ) { m_nodes [ k ] = m_nodes [ par ] ; k = par ; } else break ; } m_nodes [ k ] = obj ; ++ m_count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes and returns the least element of this heap . @return the extracted object [CODESPLIT] public Object extract ( ) { if ( m_count < 1 ) { return null ; } else { int length = m_nodes . length >> 1 ; // Shrink if necessary if ( length > 5 && m_count < ( length >> 1 ) ) { Object [ ] newNodes = new Object [ length ] ; System . arraycopy ( m_nodes , 0 , newNodes , 0 , length ) ; m_nodes = newNodes ; } // int k = 0 ; Object ret = m_nodes [ k ] ; -- m_count ; Object last = m_nodes [ m_count ] ; for ( ; ; ) { int l = left ( k ) ; if ( l >= m_count ) { break ; } else { int r = right ( k ) ; int child = ( r >= m_count || compare ( m_nodes [ l ] , m_nodes [ r ] ) < 0 ) ? l : r ; if ( compare ( last , m_nodes [ child ] ) > 0 ) { m_nodes [ k ] = m_nodes [ child ] ; k = child ; } else { break ; } } } m_nodes [ k ] = last ; m_nodes [ m_count ] = null ; return ret ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the argument text into and Byte using Byte . decode . [CODESPLIT] public void setAsText ( final String text ) { if ( PropertyEditors . isNull ( text , false , false ) ) { setValue ( null ) ; return ; } Object newValue = text . getBytes ( ) ; setValue ( newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the context classloader for the given thread [CODESPLIT] public void setContextClassLoader ( final Thread thread , final ClassLoader cl ) { AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { thread . setContextClassLoader ( cl ) ; return null ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A new node has been added at index <code > index< / code > . Normalize the tree by moving the new node up the tree . [CODESPLIT] private boolean normalizeUp ( int index ) { // INV: assertExpr(index > 0); // INV: assertExpr(index <= size); // INV: assertExpr(queue[index] != null); if ( index == 1 ) return false ; // at root boolean ret = false ; long t = queue [ index ] . time ; int p = index >> 1 ; while ( queue [ p ] . time > t ) { // INV: assertExpr(queue[index].time == t); swap ( p , index ) ; ret = true ; if ( p == 1 ) break ; // at root index = p ; p >>= 1 ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swap two nodes in the tree . [CODESPLIT] private void swap ( int a , int b ) { // INV: assertExpr(a > 0); // INV: assertExpr(a <= size); // INV: assertExpr(b > 0); // INV: assertExpr(b <= size); // INV: assertExpr(queue[a] != null); // INV: assertExpr(queue[b] != null); // INV: assertExpr(queue[a].index == a); // INV: assertExpr(queue[b].index == b); TimeoutExtImpl temp = queue [ a ] ; queue [ a ] = queue [ b ] ; queue [ a ] . index = a ; queue [ b ] = temp ; queue [ b ] . index = b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a node from the tree and normalize . [CODESPLIT] private TimeoutExtImpl removeNode ( int index ) { // INV: assertExpr(index > 0); // INV: assertExpr(index <= size); TimeoutExtImpl res = queue [ index ] ; // INV: assertExpr(res != null); // INV: assertExpr(res.index == index); if ( index == size ) { -- size ; queue [ index ] = null ; return res ; } swap ( index , size ) ; // Exchange removed node with last leaf node -- size ; // INV: assertExpr(res.index == size + 1); queue [ res . index ] = null ; if ( normalizeUp ( index ) ) return res ; // Node moved up, so it shouldn't move down long t = queue [ index ] . time ; int c = index << 1 ; while ( c <= size ) { // INV: assertExpr(q[index].time == t); TimeoutExtImpl l = queue [ c ] ; // INV: assertExpr(l != null); // INV: assertExpr(l.index == c); if ( c + 1 <= size ) { // two children, swap with smallest TimeoutExtImpl r = queue [ c + 1 ] ; // INV: assertExpr(r != null); // INV: assertExpr(r.index == c+1); if ( l . time <= r . time ) { if ( t <= l . time ) break ; // done swap ( index , c ) ; index = c ; } else { if ( t <= r . time ) break ; // done swap ( index , c + 1 ) ; index = c + 1 ; } } else { // one child if ( t <= l . time ) break ; // done swap ( index , c ) ; index = c ; } c = index << 1 ; } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursive cleanup of a TimeoutImpl [CODESPLIT] private TimeoutExtImpl cleanupTimeoutExtImpl ( TimeoutExtImpl timeout ) { if ( timeout != null ) timeout . target = null ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check invariants of the queue . [CODESPLIT] void checkTree ( ) { assertExpr ( size >= 0 ) ; assertExpr ( size < queue . length ) ; assertExpr ( queue [ 0 ] == null ) ; if ( size > 0 ) { assertExpr ( queue [ 1 ] != null ) ; assertExpr ( queue [ 1 ] . index == 1 ) ; for ( int i = 2 ; i <= size ; ++ i ) { assertExpr ( queue [ i ] != null ) ; assertExpr ( queue [ i ] . index == i ) ; assertExpr ( queue [ i >> 1 ] . time <= queue [ i ] . time ) ; // parent fires first } for ( int i = size + 1 ; i < queue . length ; ++ i ) assertExpr ( queue [ i ] == null ) ; } } /**\n    * Debugging helper.\n    */ private void assertExpr ( boolean expr ) { if ( ! expr ) throw new IllegalStateException ( \"***** assert failed *****\" ) ; } /**\n    *  Our private Timeout implementation.\n    */ private class TimeoutExtImpl implements TimeoutExt { /** Done */ static final int DONE = - 1 ; /** In timeout */ static final int TIMEOUT = - 2 ; /** Index in the queue */ int index ; /** Time of the timeout */ long time ; /** The timeout target */ TimeoutTarget target ; public long getTime ( ) { return time ; } public TimeoutTarget getTimeoutTarget ( ) { return target ; } public void done ( ) { index = DONE ; } public boolean cancel ( ) { return remove ( this ) ; } } } ", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a class by asking the parent [CODESPLIT] protected Class < ? > loadClass ( String className , boolean resolve ) throws ClassNotFoundException { // Revert to standard rules if ( standard ) return super . loadClass ( className , resolve ) ; // Ask the parent Class < ? > clazz = null ; try { clazz = parent . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { // Not found in parent, // maybe it is a proxy registered against this classloader? clazz = findLoadedClass ( className ) ; if ( clazz == null ) throw e ; } // Link the class if ( resolve ) resolveClass ( clazz ) ; return clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Preload the JBoss specific protocol handlers so that URL knows about them even if the handler factory is changed . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static void preload ( ) { for ( int i = 0 ; i < PROTOCOLS . length ; i ++ ) { try { URL url = new URL ( PROTOCOLS [ i ] , \"\" , - 1 , \"\" ) ; log . trace ( \"Loaded protocol: \" + PROTOCOLS [ i ] ) ; } catch ( Exception e ) { log . warn ( \"Failed to load protocol: \" + PROTOCOLS [ i ] , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the handlerPkgs for URLStreamHandler classes matching the pkg + protocol + . Handler naming convention . [CODESPLIT] public URLStreamHandler createURLStreamHandler ( final String protocol ) { // Check the handler map URLStreamHandler handler = ( URLStreamHandler ) handlerMap . get ( protocol ) ; if ( handler != null ) return handler ; // Validate that createURLStreamHandler is not recursing String prevProtocol = ( String ) createURLStreamHandlerProtocol . get ( ) ; if ( prevProtocol != null && prevProtocol . equals ( protocol ) ) return null ; createURLStreamHandlerProtocol . set ( protocol ) ; // See if the handler pkgs definition has changed checkHandlerPkgs ( ) ; // Search the handlerPkgs for a matching protocol handler ClassLoader ctxLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; for ( int p = 0 ; p < handlerPkgs . length ; p ++ ) { try { // Form the standard protocol handler class name String classname = handlerPkgs [ p ] + \".\" + protocol + \".Handler\" ; Class < ? > type = null ; try { type = ctxLoader . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { // Try our class loader type = Class . forName ( classname ) ; } if ( type != null ) { handler = ( URLStreamHandler ) type . newInstance ( ) ; handlerMap . put ( protocol , handler ) ; log . trace ( \"Found protocol:\" + protocol + \" handler:\" + handler ) ; } } catch ( Throwable ignore ) { } } createURLStreamHandlerProtocol . set ( null ) ; return handler ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "See if the java . protocol . handler . pkgs system property has changed and if it has parse it to update the handlerPkgs array . [CODESPLIT] private synchronized void checkHandlerPkgs ( ) { String handlerPkgsProp = System . getProperty ( \"java.protocol.handler.pkgs\" ) ; if ( handlerPkgsProp != null && handlerPkgsProp . equals ( lastHandlerPkgs ) == false ) { // Update the handlerPkgs[] from the handlerPkgsProp StringTokenizer tokeninzer = new StringTokenizer ( handlerPkgsProp , \"|\" ) ; ArrayList < String > tmp = new ArrayList < String > ( ) ; while ( tokeninzer . hasMoreTokens ( ) ) { String pkg = tokeninzer . nextToken ( ) . intern ( ) ; if ( tmp . contains ( pkg ) == false ) tmp . add ( pkg ) ; } // Include the JBoss default protocol handler pkg if ( tmp . contains ( PACKAGE_PREFIX ) == false ) tmp . add ( PACKAGE_PREFIX ) ; handlerPkgs = new String [ tmp . size ( ) ] ; tmp . toArray ( handlerPkgs ) ; lastHandlerPkgs = handlerPkgsProp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a Class for the input object converted to a string . [CODESPLIT] public Object getValue ( ) { try { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String classname = getAsText ( ) ; Class < ? > type = loader . loadClass ( classname ) ; return type ; } catch ( Exception e ) { throw new NestedRuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the set implementation [CODESPLIT] private Set < T > createImplementation ( ) { if ( delegate instanceof HashSet == false ) return new HashSet < T > ( delegate ) ; return delegate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to close an array of <tt > InputStream< / tt > s . [CODESPLIT] public static boolean close ( final InputStream [ ] streams ) { boolean success = true ; for ( int i = 0 ; i < streams . length ; i ++ ) { boolean rv = close ( streams [ i ] ) ; if ( ! rv ) success = false ; } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a synchronized counter . [CODESPLIT] public static LongCounter makeSynchronized ( final LongCounter counter ) { return new Wrapper ( counter ) { /** The serialVersionUID */ private static final long serialVersionUID = 8903330696503363758L ; public synchronized long increment ( ) { return this . counter . increment ( ) ; } public synchronized long decrement ( ) { return this . counter . decrement ( ) ; } public synchronized long getCount ( ) { return this . counter . getCount ( ) ; } public synchronized void reset ( ) { this . counter . reset ( ) ; } public synchronized int hashCode ( ) { return this . counter . hashCode ( ) ; } public synchronized boolean equals ( final Object obj ) { return this . counter . equals ( obj ) ; } public synchronized String toString ( ) { return this . counter . toString ( ) ; } public synchronized Object clone ( ) { return this . counter . clone ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a directional counter . [CODESPLIT] public static LongCounter makeDirectional ( final LongCounter counter , final boolean increasing ) { LongCounter temp ; if ( increasing ) { temp = new Wrapper ( counter ) { /** The serialVersionUID */ private static final long serialVersionUID = - 8902748795144754375L ; public long decrement ( ) { throw new UnsupportedOperationException ( ) ; } public void reset ( ) { throw new UnsupportedOperationException ( ) ; } } ; } else { temp = new Wrapper ( counter ) { /** The serialVersionUID */ private static final long serialVersionUID = 2584758778978644599L ; public long increment ( ) { throw new UnsupportedOperationException ( ) ; } } ; } return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Are we in an extension namespace? [CODESPLIT] protected boolean inExtensionNamespace ( ) { boolean inExtension = false ; Enumeration elements = namespaceStack . elements ( ) ; while ( ! inExtension && elements . hasMoreElements ( ) ) { String ns = ( String ) elements . nextElement ( ) ; if ( ns == null ) { inExtension = true ; } else { inExtension = ( ! ns . equals ( tr9401NamespaceName ) && ! ns . equals ( namespaceName ) ) ; } } return inExtension ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > startDocument< / code > method does nothing . [CODESPLIT] public void startDocument ( ) throws SAXException { baseURIStack . push ( catalog . getCurrentBase ( ) ) ; overrideStack . push ( catalog . getDefaultOverride ( ) ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > startElement< / code > method recognizes elements from the plain catalog format and instantiates CatalogEntry objects for them . [CODESPLIT] public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { int entryType = - 1 ; Vector entryArgs = new Vector ( ) ; namespaceStack . push ( namespaceURI ) ; boolean inExtension = inExtensionNamespace ( ) ; if ( namespaceURI != null && namespaceName . equals ( namespaceURI ) && ! inExtension ) { // This is an XML Catalog entry if ( atts . getValue ( \"xml:base\" ) != null ) { String baseURI = atts . getValue ( \"xml:base\" ) ; entryType = Catalog . BASE ; entryArgs . add ( baseURI ) ; baseURIStack . push ( baseURI ) ; debug . message ( 4 , \"xml:base\" , baseURI ) ; try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry (base)\" , localName ) ; } } entryType = - 1 ; entryArgs = new Vector ( ) ; } else { baseURIStack . push ( baseURIStack . peek ( ) ) ; } if ( ( localName . equals ( \"catalog\" ) || localName . equals ( \"group\" ) ) && atts . getValue ( \"prefer\" ) != null ) { String override = atts . getValue ( \"prefer\" ) ; if ( override . equals ( \"public\" ) ) { override = \"yes\" ; } else if ( override . equals ( \"system\" ) ) { override = \"no\" ; } else { debug . message ( 1 , \"Invalid prefer: must be 'system' or 'public'\" , localName ) ; override = catalog . getDefaultOverride ( ) ; } entryType = Catalog . OVERRIDE ; entryArgs . add ( override ) ; overrideStack . push ( override ) ; debug . message ( 4 , \"override\" , override ) ; try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry (override)\" , localName ) ; } } entryType = - 1 ; entryArgs = new Vector ( ) ; } else { overrideStack . push ( overrideStack . peek ( ) ) ; } if ( localName . equals ( \"delegatePublic\" ) ) { if ( checkAttributes ( atts , \"publicIdStartString\" , \"catalog\" ) ) { entryType = Catalog . DELEGATE_PUBLIC ; entryArgs . add ( atts . getValue ( \"publicIdStartString\" ) ) ; entryArgs . add ( atts . getValue ( \"catalog\" ) ) ; debug . message ( 4 , \"delegatePublic\" , PublicId . normalize ( atts . getValue ( \"publicIdStartString\" ) ) , atts . getValue ( \"catalog\" ) ) ; } } else if ( localName . equals ( \"delegateSystem\" ) ) { if ( checkAttributes ( atts , \"systemIdStartString\" , \"catalog\" ) ) { entryType = Catalog . DELEGATE_SYSTEM ; entryArgs . add ( atts . getValue ( \"systemIdStartString\" ) ) ; entryArgs . add ( atts . getValue ( \"catalog\" ) ) ; debug . message ( 4 , \"delegateSystem\" , atts . getValue ( \"systemIdStartString\" ) , atts . getValue ( \"catalog\" ) ) ; } } else if ( localName . equals ( \"delegateURI\" ) ) { if ( checkAttributes ( atts , \"uriStartString\" , \"catalog\" ) ) { entryType = Catalog . DELEGATE_URI ; entryArgs . add ( atts . getValue ( \"uriStartString\" ) ) ; entryArgs . add ( atts . getValue ( \"catalog\" ) ) ; debug . message ( 4 , \"delegateURI\" , atts . getValue ( \"uriStartString\" ) , atts . getValue ( \"catalog\" ) ) ; } } else if ( localName . equals ( \"rewriteSystem\" ) ) { if ( checkAttributes ( atts , \"systemIdStartString\" , \"rewritePrefix\" ) ) { entryType = Catalog . REWRITE_SYSTEM ; entryArgs . add ( atts . getValue ( \"systemIdStartString\" ) ) ; entryArgs . add ( atts . getValue ( \"rewritePrefix\" ) ) ; debug . message ( 4 , \"rewriteSystem\" , atts . getValue ( \"systemIdStartString\" ) , atts . getValue ( \"rewritePrefix\" ) ) ; } } else if ( localName . equals ( \"rewriteURI\" ) ) { if ( checkAttributes ( atts , \"uriStartString\" , \"rewritePrefix\" ) ) { entryType = Catalog . REWRITE_URI ; entryArgs . add ( atts . getValue ( \"uriStartString\" ) ) ; entryArgs . add ( atts . getValue ( \"rewritePrefix\" ) ) ; debug . message ( 4 , \"rewriteURI\" , atts . getValue ( \"uriStartString\" ) , atts . getValue ( \"rewritePrefix\" ) ) ; } } else if ( localName . equals ( \"nextCatalog\" ) ) { if ( checkAttributes ( atts , \"catalog\" ) ) { entryType = Catalog . CATALOG ; entryArgs . add ( atts . getValue ( \"catalog\" ) ) ; debug . message ( 4 , \"nextCatalog\" , atts . getValue ( \"catalog\" ) ) ; } } else if ( localName . equals ( \"public\" ) ) { if ( checkAttributes ( atts , \"publicId\" , \"uri\" ) ) { entryType = Catalog . PUBLIC ; entryArgs . add ( atts . getValue ( \"publicId\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; debug . message ( 4 , \"public\" , PublicId . normalize ( atts . getValue ( \"publicId\" ) ) , atts . getValue ( \"uri\" ) ) ; } } else if ( localName . equals ( \"system\" ) ) { if ( checkAttributes ( atts , \"systemId\" , \"uri\" ) ) { entryType = Catalog . SYSTEM ; entryArgs . add ( atts . getValue ( \"systemId\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; debug . message ( 4 , \"system\" , atts . getValue ( \"systemId\" ) , atts . getValue ( \"uri\" ) ) ; } } else if ( localName . equals ( \"uri\" ) ) { if ( checkAttributes ( atts , \"name\" , \"uri\" ) ) { entryType = Catalog . URI ; entryArgs . add ( atts . getValue ( \"name\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; debug . message ( 4 , \"uri\" , atts . getValue ( \"name\" ) , atts . getValue ( \"uri\" ) ) ; } } else if ( localName . equals ( \"catalog\" ) ) { // nop, start of catalog } else if ( localName . equals ( \"group\" ) ) { // nop, a group } else { // This is equivalent to an invalid catalog entry type debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } if ( entryType >= 0 ) { try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry\" , localName ) ; } } } } if ( namespaceURI != null && tr9401NamespaceName . equals ( namespaceURI ) && ! inExtension ) { // This is a TR9401 Catalog entry if ( atts . getValue ( \"xml:base\" ) != null ) { String baseURI = atts . getValue ( \"xml:base\" ) ; entryType = Catalog . BASE ; entryArgs . add ( baseURI ) ; baseURIStack . push ( baseURI ) ; debug . message ( 4 , \"xml:base\" , baseURI ) ; try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry (base)\" , localName ) ; } } entryType = - 1 ; entryArgs = new Vector ( ) ; } else { baseURIStack . push ( baseURIStack . peek ( ) ) ; } if ( localName . equals ( \"doctype\" ) ) { entryType = catalog . DOCTYPE ; entryArgs . add ( atts . getValue ( \"name\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; } else if ( localName . equals ( \"document\" ) ) { entryType = catalog . DOCUMENT ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; } else if ( localName . equals ( \"dtddecl\" ) ) { entryType = catalog . DTDDECL ; entryArgs . add ( atts . getValue ( \"publicId\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; } else if ( localName . equals ( \"entity\" ) ) { entryType = Catalog . ENTITY ; entryArgs . add ( atts . getValue ( \"name\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; } else if ( localName . equals ( \"linktype\" ) ) { entryType = Catalog . LINKTYPE ; entryArgs . add ( atts . getValue ( \"name\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; } else if ( localName . equals ( \"notation\" ) ) { entryType = Catalog . NOTATION ; entryArgs . add ( atts . getValue ( \"name\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; } else if ( localName . equals ( \"sgmldecl\" ) ) { entryType = Catalog . SGMLDECL ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; } else { // This is equivalent to an invalid catalog entry type debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } if ( entryType >= 0 ) { try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry\" , localName ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > endElement< / code > method does nothing . [CODESPLIT] public void endElement ( String namespaceURI , String localName , String qName ) throws SAXException { int entryType = - 1 ; Vector entryArgs = new Vector ( ) ; boolean inExtension = inExtensionNamespace ( ) ; if ( namespaceURI != null && ! inExtension && ( namespaceName . equals ( namespaceURI ) || tr9401NamespaceName . equals ( namespaceURI ) ) ) { String popURI = ( String ) baseURIStack . pop ( ) ; String baseURI = ( String ) baseURIStack . peek ( ) ; if ( ! baseURI . equals ( popURI ) ) { entryType = catalog . BASE ; entryArgs . add ( baseURI ) ; debug . message ( 4 , \"(reset) xml:base\" , baseURI ) ; try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry (rbase)\" , localName ) ; } } } } if ( namespaceURI != null && namespaceName . equals ( namespaceURI ) && ! inExtension ) { if ( localName . equals ( \"catalog\" ) || localName . equals ( \"group\" ) ) { String popOverride = ( String ) overrideStack . pop ( ) ; String override = ( String ) overrideStack . peek ( ) ; if ( ! override . equals ( popOverride ) ) { entryType = catalog . OVERRIDE ; entryArgs . add ( override ) ; overrideStack . push ( override ) ; debug . message ( 4 , \"(reset) override\" , override ) ; try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry (roverride)\" , localName ) ; } } } } } namespaceStack . pop ( ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether a notification is required and notifies as appropriate [CODESPLIT] public void checkNotification ( int result ) { // Is a notification required? chunk += result ; if ( chunk >= chunkSize ) { if ( listener != null ) listener . onStreamNotification ( this , chunk ) ; // Start a new chunk chunk = 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup a value from the NonSerializableFactory map . [CODESPLIT] public static Object lookup ( String key ) { Object value = wrapperMap . get ( key ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup a value from the NonSerializableFactory map . [CODESPLIT] public static Object lookup ( Name name ) { String key = name . toString ( ) ; Object value = wrapperMap . get ( key ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A convenience method that simplifies the process of rebinding a non - serializable object into a JNDI context . [CODESPLIT] public static synchronized void rebind ( Context ctx , String key , Object target ) throws NamingException { NonSerializableFactory . rebind ( key , target ) ; // Bind a reference to target using NonSerializableFactory as the ObjectFactory String className = target . getClass ( ) . getName ( ) ; String factory = NonSerializableFactory . class . getName ( ) ; StringRefAddr addr = new StringRefAddr ( \"nns\" , key ) ; Reference memoryRef = new Reference ( className , addr , factory , null ) ; ctx . rebind ( key , memoryRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A convenience method that simplifies the process of rebinding a non - serializable object into a JNDI context . [CODESPLIT] public static synchronized void rebind ( Context ctx , String key , Object target , boolean createSubcontexts ) throws NamingException { Name name = ctx . getNameParser ( \"\" ) . parse ( key ) ; if ( createSubcontexts == true && name . size ( ) > 1 ) { int size = name . size ( ) - 1 ; Util . createSubcontext ( ctx , name . getPrefix ( size ) ) ; } rebind ( ctx , key , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A convenience method that simplifies the process of rebinding a non - serializable object into a JNDI context . This version binds the target object into the default IntitialContext using name path . [CODESPLIT] public static synchronized void rebind ( Name name , Object target , boolean createSubcontexts ) throws NamingException { String key = name . toString ( ) ; InitialContext ctx = new InitialContext ( ) ; if ( createSubcontexts == true && name . size ( ) > 1 ) { int size = name . size ( ) - 1 ; Util . createSubcontext ( ctx , name . getPrefix ( size ) ) ; } rebind ( ctx , key , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform the obj Reference bound into the JNDI namespace into the actual non - Serializable object . [CODESPLIT] public Object getObjectInstance ( Object obj , Name name , Context nameCtx , Hashtable env ) throws Exception { // Get the nns value from the Reference obj and use it as the map key Reference ref = ( Reference ) obj ; RefAddr addr = ref . get ( \"nns\" ) ; String key = ( String ) addr . getContent ( ) ; Object target = wrapperMap . get ( key ) ; return target ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Substitute sub - strings in side of a string . [CODESPLIT] public static String subst ( final StringBuffer buff , final String string , final Map map , final String beginToken , final String endToken ) { int begin = 0 , rangeEnd = 0 ; Range range ; while ( ( range = rangeOf ( beginToken , endToken , string , rangeEnd ) ) != null ) { // append the first part of the string buff . append ( string . substring ( begin , range . begin ) ) ; // Get the string to replace from the map String key = string . substring ( range . begin + beginToken . length ( ) , range . end ) ; Object value = map . get ( key ) ; // if mapping does not exist then use empty; if ( value == null ) value = EMPTY ; // append the replaced string buff . append ( value ) ; // update positions begin = range . end + endToken . length ( ) ; rangeEnd = begin ; } // append the rest of the string buff . append ( string . substring ( begin , string . length ( ) ) ) ; return buff . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Split up a string into multiple strings based on a delimiter . [CODESPLIT] public static String [ ] split ( final String string , final String delim , final int limit ) { // get the count of delim in string, if count is > limit  // then use limit for count.  The number of delimiters is less by one // than the number of elements, so add one to count. int count = count ( string , delim ) + 1 ; if ( limit > 0 && count > limit ) { count = limit ; } String strings [ ] = new String [ count ] ; int begin = 0 ; for ( int i = 0 ; i < count ; i ++ ) { // get the next index of delim int end = string . indexOf ( delim , begin ) ; // if the end index is -1 or if this is the last element // then use the string's length for the end index if ( end == - 1 || i + 1 == count ) end = string . length ( ) ; // if end is 0, then the first element is empty if ( end == 0 ) strings [ i ] = EMPTY ; else strings [ i ] = string . substring ( begin , end ) ; // update the begining index begin = end + 1 ; } return strings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert and join an array of bytes into one string . [CODESPLIT] public static String join ( final byte array [ ] ) { Byte bytes [ ] = new Byte [ array . length ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { bytes [ i ] = new Byte ( array [ i ] ) ; } return join ( bytes , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default toString implementation of an object [CODESPLIT] public static final void defaultToString ( JBossStringBuilder buffer , Object object ) { if ( object == null ) buffer . append ( \"null\" ) ; else { buffer . append ( object . getClass ( ) . getName ( ) ) ; buffer . append ( ' ' ) ; buffer . append ( Integer . toHexString ( System . identityHashCode ( object ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trim all occurences of the supplied leading character from the given String . [CODESPLIT] public static String trimLeadingCharacter ( String str , final char leadingCharacter ) { return trimLeadingCharacter ( str , new CharacterChecker ( ) { public boolean isCharacterLegal ( char character ) { return character == leadingCharacter ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trim all occurences of the supplied leading character from the given String . [CODESPLIT] public static String trimLeadingCharacter ( String str , CharacterChecker checker ) { if ( hasLength ( str ) == false ) { return str ; } if ( checker == null ) throw new IllegalArgumentException ( \"Null character checker\" ) ; StringBuffer buf = new StringBuffer ( str ) ; while ( buf . length ( ) > 0 && checker . isCharacterLegal ( buf . charAt ( 0 ) ) ) { buf . deleteCharAt ( 0 ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a BlockingMode for the input object converted to a string . [CODESPLIT] public Object getValue ( ) { String text = getAsText ( ) ; BlockingMode mode = BlockingMode . toBlockingMode ( text ) ; return mode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a file is acceptible . [CODESPLIT] public boolean accept ( final File dir , final String name ) { if ( ignoreCase ) { return name . toLowerCase ( ) . endsWith ( suffix ) ; } else { return name . endsWith ( suffix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the cache for use . Prior to this the cache has no store . [CODESPLIT] public void create ( ) { if ( threadSafe ) entryMap = Collections . synchronizedMap ( new HashMap ( ) ) ; else entryMap = new HashMap ( ) ; now = System . currentTimeMillis ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cache value for key if it has not expired . If the TimedEntry is expired its destroy method is called and then removed from the cache . [CODESPLIT] public Object get ( Object key ) { TimedEntry entry = ( TimedEntry ) entryMap . get ( key ) ; if ( entry == null ) return null ; if ( entry . isCurrent ( now ) == false ) { // Try to refresh the entry if ( entry . refresh ( ) == false ) { // Failed, remove the entry and return null entry . destroy ( ) ; entryMap . remove ( key ) ; return null ; } } Object value = entry . getValue ( ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cache value for key . This method does not check to see if the entry has expired . [CODESPLIT] public Object peek ( Object key ) { TimedEntry entry = ( TimedEntry ) entryMap . get ( key ) ; Object value = null ; if ( entry != null ) value = entry . getValue ( ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a value into the cache . In order to have the cache entry reshresh itself value would have to implement TimedEntry and implement the required refresh () method logic . [CODESPLIT] public void insert ( Object key , Object value ) { if ( entryMap . containsKey ( key ) ) throw new IllegalStateException ( \"Attempt to insert duplicate entry\" ) ; TimedEntry entry = null ; if ( ( value instanceof TimedEntry ) == false ) { // Wrap the value in a DefaultTimedEntry entry = new DefaultTimedEntry ( defaultLifetime , value ) ; } else { entry = ( TimedEntry ) value ; } entry . init ( now ) ; entryMap . put ( key , entry ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the entry associated with key and call destroy on the entry if found . [CODESPLIT] public void remove ( Object key ) { TimedEntry entry = ( TimedEntry ) entryMap . remove ( key ) ; if ( entry != null ) entry . destroy ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove all entries from the cache . [CODESPLIT] public void flush ( ) { Map tmpMap = null ; synchronized ( this ) { tmpMap = entryMap ; if ( threadSafe ) entryMap = Collections . synchronizedMap ( new HashMap ( ) ) ; else entryMap = new HashMap ( ) ; } // Notify the entries of their removal Iterator iter = tmpMap . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { TimedEntry entry = ( TimedEntry ) iter . next ( ) ; entry . destroy ( ) ; } tmpMap . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the list of keys for entries that are not expired . [CODESPLIT] public List getValidKeys ( ) { ArrayList validKeys = new ArrayList ( ) ; synchronized ( entryMap ) { Iterator iter = entryMap . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; TimedEntry value = ( TimedEntry ) entry . getValue ( ) ; if ( value . isCurrent ( now ) == true ) validKeys . add ( entry . getKey ( ) ) ; } } return validKeys ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the cache timer resolution [CODESPLIT] public synchronized void setResolution ( int resolution ) { if ( resolution <= 0 ) resolution = 60 ; if ( resolution != this . resolution ) { this . resolution = resolution ; theTimer . cancel ( ) ; theTimer = new ResolutionTimer ( ) ; resolutionTimer . scheduleAtFixedRate ( theTimer , 0 , 1000 * resolution ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the raw TimedEntry for key without performing any expiration check . [CODESPLIT] public TimedEntry peekEntry ( Object key ) { TimedEntry entry = ( TimedEntry ) entryMap . get ( key ) ; return entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an iterator over the children of the given element with the given tag name . [CODESPLIT] public static Iterator getChildrenByTagName ( Element element , String tagName ) { if ( element == null ) return null ; // getElementsByTagName gives the corresponding elements in the whole  // descendance. We want only children NodeList children = element . getChildNodes ( ) ; ArrayList goodChildren = new ArrayList ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node currentChild = children . item ( i ) ; if ( currentChild . getNodeType ( ) == Node . ELEMENT_NODE && ( ( Element ) currentChild ) . getTagName ( ) . equals ( tagName ) ) { goodChildren . add ( currentChild ) ; } } return goodChildren . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the child of the specified element having the specified unique name . If there are more than one children elements with the same name and exception is thrown . [CODESPLIT] public static Element getUniqueChild ( Element element , String tagName ) throws Exception { Iterator goodChildren = getChildrenByTagName ( element , tagName ) ; if ( goodChildren != null && goodChildren . hasNext ( ) ) { Element child = ( Element ) goodChildren . next ( ) ; if ( goodChildren . hasNext ( ) ) { throw new Exception ( \"expected only one \" + tagName + \" tag\" ) ; } return child ; } else { throw new Exception ( \"expected one \" + tagName + \" tag\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the child of the specified element having the specified name . If the child with this name doesn t exist then null is returned instead . [CODESPLIT] public static Element getOptionalChild ( Element element , String tagName ) throws Exception { return getOptionalChild ( element , tagName , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the content of the given element . [CODESPLIT] public static String getElementContent ( Element element , String defaultStr ) throws Exception { if ( element == null ) return defaultStr ; NodeList children = element . getChildNodes ( ) ; String result = \"\" ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { if ( children . item ( i ) . getNodeType ( ) == Node . TEXT_NODE || children . item ( i ) . getNodeType ( ) == Node . CDATA_SECTION_NODE ) { result += children . item ( i ) . getNodeValue ( ) ; } else if ( children . item ( i ) . getNodeType ( ) == Node . COMMENT_NODE ) { // Ignore comment nodes } } return result . trim ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Macro to get the content of a unique child element . [CODESPLIT] public static String getUniqueChildContent ( Element element , String tagName ) throws Exception { return getElementContent ( getUniqueChild ( element , tagName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Macro to get the content of an optional child element . [CODESPLIT] public static String getOptionalChildContent ( Element element , String tagName ) throws Exception { return getElementContent ( getOptionalChild ( element , tagName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ThreadPool ---------------------------------------------------- [CODESPLIT] public void stop ( boolean immediate ) { log . debug ( \"stop, immediate=\" + immediate ) ; stopped . set ( true ) ; if ( immediate ) executor . shutdownNow ( ) ; else executor . shutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This resets the work queue capacity . This requires recreating the work queue and ThreadPoolExecutor so this needs to be called before doing any work with the pool . [CODESPLIT] public void setMaximumQueueSize ( int size ) { // Reset the executor work queue ArrayList tmp = new ArrayList ( ) ; queue . drainTo ( tmp ) ; queue = new LinkedBlockingQueue ( size ) ; queue . addAll ( tmp ) ; ThreadFactory tf = executor . getThreadFactory ( ) ; RejectedExecutionHandler handler = executor . getRejectedExecutionHandler ( ) ; long keepAlive = executor . getKeepAliveTime ( TimeUnit . SECONDS ) ; int cs = executor . getCorePoolSize ( ) ; int mcs = executor . getMaximumPoolSize ( ) ; executor = new ThreadPoolExecutor ( cs , mcs , keepAlive , TimeUnit . SECONDS , queue ) ; executor . setThreadFactory ( tf ) ; executor . setRejectedExecutionHandler ( handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For backward compatibility with the previous string based mode [CODESPLIT] public void setBlockingMode ( String name ) { blockingMode = BlockingMode . toBlockingMode ( name ) ; if ( blockingMode == null ) blockingMode = BlockingMode . ABORT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For backward compatibility with the previous string based mode This is needed for microcontainer as it gets confused with overloaded setters . [CODESPLIT] public void setBlockingModeString ( String name ) { blockingMode = BlockingMode . toBlockingMode ( name ) ; if ( blockingMode == null ) blockingMode = BlockingMode . ABORT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a task [CODESPLIT] protected void execute ( TaskWrapper wrapper ) { if ( trace ) log . trace ( \"execute, wrapper=\" + wrapper ) ; try { executor . execute ( wrapper ) ; } catch ( Throwable t ) { wrapper . rejectTask ( new ThreadPoolFullException ( \"Error scheduling work: \" + wrapper , t ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > startElement< / code > method recognizes elements from the plain catalog format and instantiates CatalogEntry objects for them . [CODESPLIT] public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { int entryType = - 1 ; Vector entryArgs = new Vector ( ) ; if ( localName . equals ( \"Base\" ) ) { entryType = catalog . BASE ; entryArgs . add ( atts . getValue ( \"HRef\" ) ) ; catalog . getCatalogManager ( ) . debug . message ( 4 , \"Base\" , atts . getValue ( \"HRef\" ) ) ; } else if ( localName . equals ( \"Delegate\" ) ) { entryType = catalog . DELEGATE_PUBLIC ; entryArgs . add ( atts . getValue ( \"PublicId\" ) ) ; entryArgs . add ( atts . getValue ( \"HRef\" ) ) ; catalog . getCatalogManager ( ) . debug . message ( 4 , \"Delegate\" , PublicId . normalize ( atts . getValue ( \"PublicId\" ) ) , atts . getValue ( \"HRef\" ) ) ; } else if ( localName . equals ( \"Extend\" ) ) { entryType = catalog . CATALOG ; entryArgs . add ( atts . getValue ( \"HRef\" ) ) ; catalog . getCatalogManager ( ) . debug . message ( 4 , \"Extend\" , atts . getValue ( \"HRef\" ) ) ; } else if ( localName . equals ( \"Map\" ) ) { entryType = catalog . PUBLIC ; entryArgs . add ( atts . getValue ( \"PublicId\" ) ) ; entryArgs . add ( atts . getValue ( \"HRef\" ) ) ; catalog . getCatalogManager ( ) . debug . message ( 4 , \"Map\" , PublicId . normalize ( atts . getValue ( \"PublicId\" ) ) , atts . getValue ( \"HRef\" ) ) ; } else if ( localName . equals ( \"Remap\" ) ) { entryType = catalog . SYSTEM ; entryArgs . add ( atts . getValue ( \"SystemId\" ) ) ; entryArgs . add ( atts . getValue ( \"HRef\" ) ) ; catalog . getCatalogManager ( ) . debug . message ( 4 , \"Remap\" , atts . getValue ( \"SystemId\" ) , atts . getValue ( \"HRef\" ) ) ; } else if ( localName . equals ( \"XMLCatalog\" ) ) { // nop, start of catalog } else { // This is equivalent to an invalid catalog entry type catalog . getCatalogManager ( ) . debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } if ( entryType >= 0 ) { try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Invalid catalog entry\" , localName ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Schedule the given TimerTask to be executed after <code > delay< / code > milliseconds . [CODESPLIT] public void schedule ( TimerTask t , long delay ) { if ( t == null ) throw new IllegalArgumentException ( \"Can't schedule a null TimerTask\" ) ; if ( delay < 0 ) delay = 0 ; t . setNextExecutionTime ( System . currentTimeMillis ( ) + delay ) ; putJob ( t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "WorkerQueue overrides --------------------------------------------------- [CODESPLIT] protected void putJobImpl ( Executable task ) { m_heap . insert ( task ) ; ( ( TimerTask ) task ) . setState ( TimerTask . SCHEDULED ) ; notifyAll ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the argument text into and Integer using Integer . valueOf . [CODESPLIT] public void setAsText ( final String text ) { Object newValue = Float . valueOf ( text ) ; setValue ( newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cleanup and process a Catalog entry . [CODESPLIT] public void addEntry ( CatalogEntry entry ) { int type = entry . getEntryType ( ) ; if ( type == URISUFFIX ) { String suffix = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"URISUFFIX\" , suffix , fsi ) ; } else if ( type == SYSTEMSUFFIX ) { String suffix = normalizeURI ( entry . getEntryArg ( 0 ) ) ; String fsi = makeAbsolute ( normalizeURI ( entry . getEntryArg ( 1 ) ) ) ; entry . setEntryArg ( 1 , fsi ) ; catalogManager . debug . message ( 4 , \"SYSTEMSUFFIX\" , suffix , fsi ) ; } super . addEntry ( entry ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable URI . [CODESPLIT] public String resolveURI ( String uri ) throws MalformedURLException , IOException { String resolved = super . resolveURI ( uri ) ; if ( resolved != null ) { return resolved ; } Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == RESOLVER ) { resolved = resolveExternalSystem ( uri , e . getEntryArg ( 0 ) ) ; if ( resolved != null ) { return resolved ; } } else if ( e . getEntryType ( ) == URISUFFIX ) { String suffix = e . getEntryArg ( 0 ) ; String result = e . getEntryArg ( 1 ) ; if ( suffix . length ( ) <= uri . length ( ) && uri . substring ( uri . length ( ) - suffix . length ( ) ) . equals ( suffix ) ) { return result ; } } } // Otherwise, look in the subordinate catalogs return resolveSubordinateCatalogs ( Catalog . URI , null , null , uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable SYSTEM system identifier resorting to external RESOLVERs if necessary . [CODESPLIT] public String resolveSystem ( String systemId ) throws MalformedURLException , IOException { String resolved = super . resolveSystem ( systemId ) ; if ( resolved != null ) { return resolved ; } Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == RESOLVER ) { resolved = resolveExternalSystem ( systemId , e . getEntryArg ( 0 ) ) ; if ( resolved != null ) { return resolved ; } } else if ( e . getEntryType ( ) == SYSTEMSUFFIX ) { String suffix = e . getEntryArg ( 0 ) ; String result = e . getEntryArg ( 1 ) ; if ( suffix . length ( ) <= systemId . length ( ) && systemId . substring ( systemId . length ( ) - suffix . length ( ) ) . equals ( suffix ) ) { return result ; } } } return resolveSubordinateCatalogs ( Catalog . SYSTEM , null , null , systemId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable PUBLIC or SYSTEM identifier resorting to external resolvers if necessary . [CODESPLIT] public String resolvePublic ( String publicId , String systemId ) throws MalformedURLException , IOException { String resolved = super . resolvePublic ( publicId , systemId ) ; if ( resolved != null ) { return resolved ; } Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == RESOLVER ) { if ( systemId != null ) { resolved = resolveExternalSystem ( systemId , e . getEntryArg ( 0 ) ) ; if ( resolved != null ) { return resolved ; } } resolved = resolveExternalPublic ( publicId , e . getEntryArg ( 0 ) ) ; if ( resolved != null ) { return resolved ; } } } return resolveSubordinateCatalogs ( Catalog . PUBLIC , null , publicId , systemId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query an external RFC2483 resolver for a system identifier . [CODESPLIT] protected String resolveExternalSystem ( String systemId , String resolver ) throws MalformedURLException , IOException { Resolver r = queryResolver ( resolver , \"i2l\" , systemId , null ) ; if ( r != null ) { return r . resolveSystem ( systemId ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query an external RFC2483 resolver for a public identifier . [CODESPLIT] protected String resolveExternalPublic ( String publicId , String resolver ) throws MalformedURLException , IOException { Resolver r = queryResolver ( resolver , \"fpi2l\" , publicId , null ) ; if ( r != null ) { return r . resolvePublic ( publicId , null ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query an external RFC2483 resolver . [CODESPLIT] protected Resolver queryResolver ( String resolver , String command , String arg1 , String arg2 ) { String RFC2483 = resolver + \"?command=\" + command + \"&format=tr9401&uri=\" + arg1 + \"&uri2=\" + arg2 ; try { URL url = new URL ( RFC2483 ) ; URLConnection urlCon = url . openConnection ( ) ; urlCon . setUseCaches ( false ) ; Resolver r = ( Resolver ) newCatalog ( ) ; String cType = urlCon . getContentType ( ) ; // I don't care about the character set or subtype if ( cType . indexOf ( \";\" ) > 0 ) { cType = cType . substring ( 0 , cType . indexOf ( \";\" ) ) ; } r . parseCatalog ( cType , urlCon . getInputStream ( ) ) ; return r ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . UNPARSEABLE ) { catalogManager . debug . message ( 1 , \"Unparseable catalog: \" + RFC2483 ) ; } else if ( cex . getExceptionType ( ) == CatalogException . UNKNOWN_FORMAT ) { catalogManager . debug . message ( 1 , \"Unknown catalog format: \" + RFC2483 ) ; } return null ; } catch ( MalformedURLException mue ) { catalogManager . debug . message ( 1 , \"Malformed resolver URL: \" + RFC2483 ) ; return null ; } catch ( IOException ie ) { catalogManager . debug . message ( 1 , \"I/O Exception opening resolver: \" + RFC2483 ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append two vectors returning the result . [CODESPLIT] private Vector appendVector ( Vector vec , Vector appvec ) { if ( appvec != null ) { for ( int count = 0 ; count < appvec . size ( ) ; count ++ ) { vec . addElement ( appvec . elementAt ( count ) ) ; } } return vec ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the URNs for a given system identifier in all catalogs . [CODESPLIT] public Vector resolveAllSystemReverse ( String systemId ) throws MalformedURLException , IOException { Vector resolved = new Vector ( ) ; // If there's a SYSTEM entry in this catalog, use it if ( systemId != null ) { Vector localResolved = resolveLocalSystemReverse ( systemId ) ; resolved = appendVector ( resolved , localResolved ) ; } // Otherwise, look in the subordinate catalogs Vector subResolved = resolveAllSubordinateCatalogs ( SYSTEMREVERSE , null , null , systemId ) ; return appendVector ( resolved , subResolved ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the URN for a given system identifier . [CODESPLIT] public String resolveSystemReverse ( String systemId ) throws MalformedURLException , IOException { Vector resolved = resolveAllSystemReverse ( systemId ) ; if ( resolved != null && resolved . size ( ) > 0 ) { return ( String ) resolved . elementAt ( 0 ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the applicable SYSTEM system identifiers . [CODESPLIT] public Vector resolveAllSystem ( String systemId ) throws MalformedURLException , IOException { Vector resolutions = new Vector ( ) ; // If there are SYSTEM entries in this catalog, start with them if ( systemId != null ) { Vector localResolutions = resolveAllLocalSystem ( systemId ) ; resolutions = appendVector ( resolutions , localResolutions ) ; } // Then look in the subordinate catalogs Vector subResolutions = resolveAllSubordinateCatalogs ( SYSTEM , null , null , systemId ) ; resolutions = appendVector ( resolutions , subResolutions ) ; if ( resolutions . size ( ) > 0 ) { return resolutions ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all applicable SYSTEM system identifiers in this catalog . [CODESPLIT] private Vector resolveAllLocalSystem ( String systemId ) { Vector map = new Vector ( ) ; String osname = System . getProperty ( \"os.name\" ) ; boolean windows = ( osname . indexOf ( \"Windows\" ) >= 0 ) ; Enumeration enumt = catalogEntries . elements ( ) ; while ( enumt . hasMoreElements ( ) ) { CatalogEntry e = ( CatalogEntry ) enumt . nextElement ( ) ; if ( e . getEntryType ( ) == SYSTEM && ( e . getEntryArg ( 0 ) . equals ( systemId ) || ( windows && e . getEntryArg ( 0 ) . equalsIgnoreCase ( systemId ) ) ) ) { map . addElement ( e . getEntryArg ( 1 ) ) ; } } if ( map . size ( ) == 0 ) { return null ; } else { return map ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the subordinate catalogs in order looking for all match . [CODESPLIT] private synchronized Vector resolveAllSubordinateCatalogs ( int entityType , String entityName , String publicId , String systemId ) throws MalformedURLException , IOException { Vector resolutions = new Vector ( ) ; for ( int catPos = 0 ; catPos < catalogs . size ( ) ; catPos ++ ) { Resolver c = null ; try { c = ( Resolver ) catalogs . elementAt ( catPos ) ; } catch ( ClassCastException e ) { String catfile = ( String ) catalogs . elementAt ( catPos ) ; c = ( Resolver ) newCatalog ( ) ; try { c . parseCatalog ( catfile ) ; } catch ( MalformedURLException mue ) { catalogManager . debug . message ( 1 , \"Malformed Catalog URL\" , catfile ) ; } catch ( FileNotFoundException fnfe ) { catalogManager . debug . message ( 1 , \"Failed to load catalog, file not found\" , catfile ) ; } catch ( IOException ioe ) { catalogManager . debug . message ( 1 , \"Failed to load catalog, I/O error\" , catfile ) ; } catalogs . setElementAt ( c , catPos ) ; } String resolved = null ; // Ok, now what are we supposed to call here? if ( entityType == DOCTYPE ) { resolved = c . resolveDoctype ( entityName , publicId , systemId ) ; if ( resolved != null ) { // Only find one DOCTYPE resolution resolutions . addElement ( resolved ) ; return resolutions ; } } else if ( entityType == DOCUMENT ) { resolved = c . resolveDocument ( ) ; if ( resolved != null ) { // Only find one DOCUMENT resolution resolutions . addElement ( resolved ) ; return resolutions ; } } else if ( entityType == ENTITY ) { resolved = c . resolveEntity ( entityName , publicId , systemId ) ; if ( resolved != null ) { // Only find one ENTITY resolution resolutions . addElement ( resolved ) ; return resolutions ; } } else if ( entityType == NOTATION ) { resolved = c . resolveNotation ( entityName , publicId , systemId ) ; if ( resolved != null ) { // Only find one NOTATION resolution resolutions . addElement ( resolved ) ; return resolutions ; } } else if ( entityType == PUBLIC ) { resolved = c . resolvePublic ( publicId , systemId ) ; if ( resolved != null ) { // Only find one PUBLIC resolution resolutions . addElement ( resolved ) ; return resolutions ; } } else if ( entityType == SYSTEM ) { Vector localResolutions = c . resolveAllSystem ( systemId ) ; resolutions = appendVector ( resolutions , localResolutions ) ; break ; } else if ( entityType == SYSTEMREVERSE ) { Vector localResolutions = c . resolveAllSystemReverse ( systemId ) ; resolutions = appendVector ( resolutions , localResolutions ) ; } } if ( resolutions != null ) { return resolutions ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the SAXCatalogParser class for the given namespace / root element type . [CODESPLIT] public void setCatalogParser ( String namespaceURI , String rootElement , String parserClass ) { if ( namespaceURI == null ) { namespaceMap . put ( rootElement , parserClass ) ; } else { namespaceMap . put ( \"{\" + namespaceURI + \"}\" + rootElement , parserClass ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the SAXCatalogParser class for the given namespace / root element type . [CODESPLIT] public String getCatalogParser ( String namespaceURI , String rootElement ) { if ( namespaceURI == null ) { return ( String ) namespaceMap . get ( rootElement ) ; } else { return ( String ) namespaceMap . get ( \"{\" + namespaceURI + \"}\" + rootElement ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an XML Catalog file . [CODESPLIT] public void readCatalog ( Catalog catalog , String fileUrl ) throws MalformedURLException , IOException , CatalogException { URL url = null ; try { url = new URL ( fileUrl ) ; } catch ( MalformedURLException e ) { url = new URL ( \"file:///\" + fileUrl ) ; } debug = catalog . getCatalogManager ( ) . debug ; try { URLConnection urlCon = url . openConnection ( ) ; readCatalog ( catalog , urlCon . getInputStream ( ) ) ; } catch ( FileNotFoundException e ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Failed to load catalog, file not found\" , url . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an XML Catalog stream . [CODESPLIT] public void readCatalog ( Catalog catalog , InputStream is ) throws IOException , CatalogException { // Create an instance of the parser if ( parserFactory == null && parserClass == null ) { debug . message ( 1 , \"Cannot read SAX catalog without a parser\" ) ; throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } debug = catalog . getCatalogManager ( ) . debug ; EntityResolver bResolver = catalog . getCatalogManager ( ) . getBootstrapResolver ( ) ; this . catalog = catalog ; try { if ( parserFactory != null ) { SAXParser parser = parserFactory . newSAXParser ( ) ; SAXParserHandler spHandler = new SAXParserHandler ( ) ; spHandler . setContentHandler ( this ) ; if ( bResolver != null ) { spHandler . setEntityResolver ( bResolver ) ; } parser . parse ( new InputSource ( is ) , spHandler ) ; } else { Parser parser = ( Parser ) Class . forName ( parserClass ) . newInstance ( ) ; parser . setDocumentHandler ( this ) ; if ( bResolver != null ) { parser . setEntityResolver ( bResolver ) ; } parser . parse ( new InputSource ( is ) ) ; } } catch ( ClassNotFoundException cnfe ) { throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } catch ( IllegalAccessException iae ) { throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } catch ( InstantiationException ie ) { throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } catch ( ParserConfigurationException pce ) { throw new CatalogException ( CatalogException . UNKNOWN_FORMAT ) ; } catch ( SAXException se ) { Exception e = se . getException ( ) ; // FIXME: there must be a better way UnknownHostException uhe = new UnknownHostException ( ) ; FileNotFoundException fnfe = new FileNotFoundException ( ) ; if ( e != null ) { if ( e . getClass ( ) == uhe . getClass ( ) ) { throw new CatalogException ( CatalogException . PARSE_FAILED , e . toString ( ) ) ; } else if ( e . getClass ( ) == fnfe . getClass ( ) ) { throw new CatalogException ( CatalogException . PARSE_FAILED , e . toString ( ) ) ; } } throw new CatalogException ( se ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > startElement< / code > method . [CODESPLIT] public void startElement ( String name , AttributeList atts ) throws SAXException { if ( abandonHope ) { return ; } if ( saxParser == null ) { String prefix = \"\" ; if ( name . indexOf ( ' ' ) > 0 ) { prefix = name . substring ( 0 , name . indexOf ( ' ' ) ) ; } String localName = name ; if ( localName . indexOf ( ' ' ) > 0 ) { localName = localName . substring ( localName . indexOf ( ' ' ) + 1 ) ; } String namespaceURI = null ; if ( prefix . equals ( \"\" ) ) { namespaceURI = atts . getValue ( \"xmlns\" ) ; } else { namespaceURI = atts . getValue ( \"xmlns:\" + prefix ) ; } String saxParserClass = getCatalogParser ( namespaceURI , localName ) ; if ( saxParserClass == null ) { abandonHope = true ; if ( namespaceURI == null ) { debug . message ( 2 , \"No Catalog parser for \" + name ) ; } else { debug . message ( 2 , \"No Catalog parser for \" + \"{\" + namespaceURI + \"}\" + name ) ; } return ; } try { saxParser = ( SAXCatalogParser ) Class . forName ( saxParserClass ) . newInstance ( ) ; saxParser . setCatalog ( catalog ) ; saxParser . startDocument ( ) ; saxParser . startElement ( name , atts ) ; } catch ( ClassNotFoundException cnfe ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , cnfe . toString ( ) ) ; } catch ( InstantiationException ie ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , ie . toString ( ) ) ; } catch ( IllegalAccessException iae ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , iae . toString ( ) ) ; } catch ( ClassCastException cce ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , cce . toString ( ) ) ; } } else { saxParser . startElement ( name , atts ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX2 <code > startElement< / code > method . [CODESPLIT] public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { if ( abandonHope ) { return ; } if ( saxParser == null ) { String saxParserClass = getCatalogParser ( namespaceURI , localName ) ; if ( saxParserClass == null ) { abandonHope = true ; if ( namespaceURI == null ) { debug . message ( 2 , \"No Catalog parser for \" + localName ) ; } else { debug . message ( 2 , \"No Catalog parser for \" + \"{\" + namespaceURI + \"}\" + localName ) ; } return ; } try { saxParser = ( SAXCatalogParser ) Class . forName ( saxParserClass ) . newInstance ( ) ; saxParser . setCatalog ( catalog ) ; saxParser . startDocument ( ) ; saxParser . startElement ( namespaceURI , localName , qName , atts ) ; } catch ( ClassNotFoundException cnfe ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , cnfe . toString ( ) ) ; } catch ( InstantiationException ie ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , ie . toString ( ) ) ; } catch ( IllegalAccessException iae ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , iae . toString ( ) ) ; } catch ( ClassCastException cce ) { saxParser = null ; abandonHope = true ; debug . message ( 2 , cce . toString ( ) ) ; } } else { saxParser . startElement ( namespaceURI , localName , qName , atts ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX2 <code > endElement< / code > method . Does nothing . [CODESPLIT] public void endElement ( String namespaceURI , String localName , String qName ) throws SAXException { if ( saxParser != null ) { saxParser . endElement ( namespaceURI , localName , qName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > processingInstruction< / code > method . Does nothing . [CODESPLIT] public void processingInstruction ( String target , String data ) throws SAXException { if ( saxParser != null ) { saxParser . processingInstruction ( target , data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > startPrefixMapping< / code > method . Does nothing . [CODESPLIT] public void startPrefixMapping ( String prefix , String uri ) throws SAXException { if ( saxParser != null ) { saxParser . startPrefixMapping ( prefix , uri ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Entity Resolver [CODESPLIT] public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException { if ( er != null ) { try { return er . resolveEntity ( publicId , systemId ) ; } catch ( IOException e ) { System . out . println ( \"resolveEntity threw IOException!\" ) ; return null ; } } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sync implementation ---------------------------------------------- [CODESPLIT] public void acquire ( ) throws InterruptedException { synchronized ( this ) { logAcquire ( ) ; // One user more called acquire, increase users ++ m_users ; boolean waitSuccessful = false ; while ( m_allowed <= 0 ) { waitSuccessful = waitImpl ( this ) ; if ( ! waitSuccessful ) { // Dealock was detected, restore status, 'cause it's like a release() // that will probably be never called -- m_users ; ++ m_allowed ; } } -- m_allowed ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Protected ----------------------------------------------------- [CODESPLIT] protected boolean waitImpl ( Object lock ) throws InterruptedException { // Wait (forever) until notified. To discover deadlocks, // turn on debugging of this class long start = System . currentTimeMillis ( ) ; lock . wait ( DEADLOCK_TIMEOUT ) ; long end = System . currentTimeMillis ( ) ; if ( ( end - start ) > ( DEADLOCK_TIMEOUT - 1000 ) ) { logDeadlock ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the underlying file for this connection exists . [CODESPLIT] public void connect ( ) throws IOException { if ( connected ) return ; if ( ! file . exists ( ) ) { throw new FileNotFoundException ( file . getPath ( ) ) ; } connected = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "We should probably disallow this? [CODESPLIT] public OutputStream getOutputStream ( ) throws IOException { connect ( ) ; SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { // Check for write access FilePermission p = new FilePermission ( file . getPath ( ) , \"write\" ) ; sm . checkPermission ( p ) ; } return new FileOutputStream ( file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides support for the following headers : [CODESPLIT] public String getHeaderField ( final String name ) { String headerField = null ; if ( name . equalsIgnoreCase ( \"last-modified\" ) ) { long lastModified = getLastModified ( ) ; if ( lastModified != 0 ) { // return the last modified date formatted according to RFC 1123 Date modifiedDate = new Date ( lastModified ) ; SimpleDateFormat sdf = new SimpleDateFormat ( \"EEE, dd MMM yyyy HH:mm:ss 'GMT'\" , Locale . US ) ; sdf . setTimeZone ( TimeZone . getTimeZone ( \"GMT\" ) ) ; headerField = sdf . format ( modifiedDate ) ; } } else if ( name . equalsIgnoreCase ( \"content-length\" ) ) { headerField = String . valueOf ( file . length ( ) ) ; } else if ( name . equalsIgnoreCase ( \"content-type\" ) ) { if ( file . isDirectory ( ) ) { headerField = \"text/plain\" ; } else { headerField = getFileNameMap ( ) . getContentTypeFor ( file . getName ( ) ) ; if ( headerField == null ) { try { InputStream is = getInputStream ( ) ; BufferedInputStream bis = new BufferedInputStream ( is ) ; headerField = URLConnection . guessContentTypeFromStream ( bis ) ; bis . close ( ) ; } catch ( IOException e ) { // ignore } } } } else if ( name . equalsIgnoreCase ( \"date\" ) ) { headerField = String . valueOf ( getLastModified ( ) ) ; } else { // This always returns null currently headerField = super . getHeaderField ( name ) ; } return headerField ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compareAndSet next field [CODESPLIT] boolean casNext ( Node < K , V > cmp , Node < K , V > val ) { return nextUpdater . compareAndSet ( this , cmp , val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helps out a deletion by appending marker or unlinking from predecessor . This is called during traversals when value field seen to be null . [CODESPLIT] void helpDelete ( Node < K , V > b , Node < K , V > f ) { /*\n             * Rechecking links and then doing only one of the\n             * help-out stages per call tends to minimize CAS\n             * interference among helping threads.\n             */ if ( f == next && this == b . next ) { if ( f == null || f . value != f ) // not already marked appendMarker ( f ) ; else b . casNext ( this , f . next ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return value if this node contains a valid key - value pair else null . [CODESPLIT] V getValidValue ( ) { Object v = value ; if ( v == this || v == BASE_HEADER ) return null ; return ( V ) v ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create and return a new SnapshotEntry holding current mapping if this node holds a valid value else null [CODESPLIT] SnapshotEntry < K , V > createSnapshot ( ) { V v = getValidValue ( ) ; if ( v == null ) return null ; return new SnapshotEntry ( key , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "compareAndSet right field [CODESPLIT] final boolean casRight ( Index < K , V > cmp , Index < K , V > val ) { return rightUpdater . compareAndSet ( this , cmp , val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to CAS right field to skip over apparent successor succ . Fails ( forcing a retraversal by caller ) if this node is known to be deleted . [CODESPLIT] final boolean unlink ( Index < K , V > succ ) { return ! indexesDeletedNode ( ) && casRight ( succ , succ . right ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create logger . [CODESPLIT] private Logger createLog ( ) { Class < ? > clazz = getClass ( ) ; Logger logger = loggers . get ( clazz ) ; if ( logger == null ) { logger = Logger . getLogger ( clazz ) ; loggers . put ( clazz , logger ) ; } return logger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "List the set of JBossObjects [CODESPLIT] public static void list ( JBossStringBuilder buffer , Collection objects ) { if ( objects == null ) return ; buffer . append ( ' ' ) ; if ( objects . isEmpty ( ) == false ) { for ( Iterator i = objects . iterator ( ) ; i . hasNext ( ) ; ) { Object object = i . next ( ) ; if ( object instanceof JBossObject ) ( ( JBossObject ) object ) . toShortString ( buffer ) ; else buffer . append ( object . toString ( ) ) ; if ( i . hasNext ( ) ) buffer . append ( \", \" ) ; } } buffer . append ( ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the class short name [CODESPLIT] public String getClassShortName ( ) { String longName = getClass ( ) . getName ( ) ; int dot = longName . lastIndexOf ( ' ' ) ; if ( dot != - 1 ) return longName . substring ( dot + 1 ) ; return longName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of String [CODESPLIT] protected String toStringImplementation ( ) { JBossStringBuilder buffer = new JBossStringBuilder ( ) ; buffer . append ( getClassShortName ( ) ) . append ( ' ' ) ; buffer . append ( Integer . toHexString ( System . identityHashCode ( this ) ) ) ; buffer . append ( ' ' ) ; toString ( buffer ) ; buffer . append ( ' ' ) ; return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the default <tt > PropertyMap< / tt > . [CODESPLIT] public static PropertyMap getDefaultPropertyMap ( ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a property listener . [CODESPLIT] public static void addPropertyListener ( final PropertyListener listener ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; props . addPropertyListener ( listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an array of property listeners . [CODESPLIT] public static void addPropertyListeners ( final PropertyListener [ ] listeners ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; props . addPropertyListeners ( listeners ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a map . [CODESPLIT] public static void load ( final String prefix , final Map map ) throws PropertyException { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; props . load ( prefix , map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a map . [CODESPLIT] public static void load ( final Map map ) throws PropertyException , IOException { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; props . load ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a <tt > PropertyReader< / tt > . [CODESPLIT] public static void load ( final PropertyReader reader ) throws PropertyException , IOException { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; props . load ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a <tt > PropertyReader< / tt > specifed by the given class name . [CODESPLIT] public static void load ( final String classname ) throws PropertyException , IOException { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; props . load ( classname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a property . [CODESPLIT] public static String setProperty ( final String name , final String value ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertyAccess ( name ) ; return ( String ) props . setProperty ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a property . [CODESPLIT] public static String removeProperty ( final String name ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertyAccess ( name ) ; return props . removeProperty ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array style property . [CODESPLIT] public static String [ ] getArrayProperty ( final String base , final String [ ] defaultValues ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; return props . getArrayProperty ( base , defaultValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an iterator over all contained property names . [CODESPLIT] public static Iterator names ( ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; return props . names ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a property group for the given property base . [CODESPLIT] public static PropertyGroup getPropertyGroup ( final String basename ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) sm . checkPropertiesAccess ( ) ; return props . getPropertyGroup ( basename ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a compatible constructor for the given value type [CODESPLIT] public static Constructor getCompatibleConstructor ( final Class type , final Class valueType ) { // first try and find a constructor with the exact argument type try { return type . getConstructor ( new Class [ ] { valueType } ) ; } catch ( Exception ignore ) { // if the above failed, then try and find a constructor with // an compatible argument type // get an array of compatible types Class [ ] types = type . getClasses ( ) ; for ( int i = 0 ; i < types . length ; i ++ ) { try { return type . getConstructor ( new Class [ ] { types [ i ] } ) ; } catch ( Exception ignore2 ) { } } } // if we get this far, then we can't find a compatible constructor return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy an serializable object deeply . [CODESPLIT] public static Object copy ( final Serializable obj ) throws IOException , ClassNotFoundException { ObjectOutputStream out = null ; ObjectInputStream in = null ; Object copy = null ; try { // write the object ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; out = new ObjectOutputStream ( baos ) ; out . writeObject ( obj ) ; out . flush ( ) ; // read in the copy byte data [ ] = baos . toByteArray ( ) ; ByteArrayInputStream bais = new ByteArrayInputStream ( data ) ; in = new ObjectInputStream ( bais ) ; copy = in . readObject ( ) ; } finally { Streams . close ( out ) ; Streams . close ( in ) ; } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dereference the given object if it is <i > non - null< / i > and is an instance of <code > Reference< / code > . If the object is <i > null< / i > then <i > null< / i > is returned . If the object is not an instance of <code > Reference< / code > then the object is returned . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Object deref ( final Object obj ) { if ( obj != null && obj instanceof Reference ) { Reference ref = ( Reference ) obj ; return ref . get ( ) ; } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dereference an object [CODESPLIT] public static < T > T deref ( final Object obj , Class < T > expected ) { Object result = deref ( obj ) ; if ( result == null ) return null ; return expected . cast ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return an Object array for the given object . [CODESPLIT] public static Object [ ] toArray ( final Object obj ) { // if the object is an array, the cast and return it. if ( obj instanceof Object [ ] ) { return ( Object [ ] ) obj ; } // if the object is an array of primitives then wrap the array Class type = obj . getClass ( ) ; Object array ; if ( type . isArray ( ) ) { int length = Array . getLength ( obj ) ; Class componentType = type . getComponentType ( ) ; array = Array . newInstance ( componentType , length ) ; for ( int i = 0 ; i < length ; i ++ ) { Array . set ( array , i , Array . get ( obj , i ) ) ; } } else { array = Array . newInstance ( type , 1 ) ; Array . set ( array , 0 , obj ) ; } return ( Object [ ] ) array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialized listener lists and the JNDI properties cache map [CODESPLIT] private void init ( ) { unboundListeners = Collections . synchronizedList ( new ArrayList ( ) ) ; boundListeners = Collections . synchronizedMap ( new HashMap ( ) ) ; jndiMap = new HashMap ( ) ; PrivilegedAction action = new PrivilegedAction ( ) { public Object run ( ) { Object value = System . getProperty ( Context . PROVIDER_URL ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . PROVIDER_URL , value ) ; value = System . getProperty ( Context . INITIAL_CONTEXT_FACTORY ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . INITIAL_CONTEXT_FACTORY , value ) ; value = System . getProperty ( Context . OBJECT_FACTORIES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . OBJECT_FACTORIES , value ) ; value = System . getProperty ( Context . URL_PKG_PREFIXES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . URL_PKG_PREFIXES , value ) ; value = System . getProperty ( Context . STATE_FACTORIES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . STATE_FACTORIES , value ) ; value = System . getProperty ( Context . DNS_URL ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( Context . DNS_URL , value ) ; value = System . getProperty ( LdapContext . CONTROL_FACTORIES ) ; if ( value == null ) value = NULL_VALUE ; jndiMap . put ( LdapContext . CONTROL_FACTORIES , value ) ; return null ; } } ; AccessController . doPrivileged ( action ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by setProperty to update the jndiMap cache values . [CODESPLIT] private void updateJndiCache ( String name , String value ) { if ( name == null ) return ; boolean isJndiProperty = name . equals ( Context . PROVIDER_URL ) || name . equals ( Context . INITIAL_CONTEXT_FACTORY ) || name . equals ( Context . OBJECT_FACTORIES ) || name . equals ( Context . URL_PKG_PREFIXES ) || name . equals ( Context . STATE_FACTORIES ) || name . equals ( Context . DNS_URL ) || name . equals ( LdapContext . CONTROL_FACTORIES ) ; if ( isJndiProperty == true ) jndiMap . put ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a property . [CODESPLIT] public Object put ( Object name , Object value ) { if ( name == null ) throw new NullArgumentException ( \"name\" ) ; // value can be null // check if this is a new addition or not prior to updating the hash boolean add = ! containsKey ( name ) ; Object prev = super . put ( name , value ) ; PropertyEvent event = new PropertyEvent ( this , name . toString ( ) , value . toString ( ) ) ; // fire propertyAdded or propertyChanged if ( add ) { firePropertyAdded ( event ) ; } else { firePropertyChanged ( event ) ; } return prev ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a property . [CODESPLIT] public Object remove ( Object name ) { if ( name == null ) throw new NullArgumentException ( \"name\" ) ; // check if there is a property with this name boolean contains = containsKey ( name ) ; Object value = null ; if ( contains ) { value = super . remove ( name ) ; if ( defaults != null ) { Object obj = defaults . remove ( name ) ; if ( value == null ) { value = obj ; } } // Remove any JNDI property value jndiMap . remove ( name ) ; PropertyEvent event = new PropertyEvent ( this , name . toString ( ) , value . toString ( ) ) ; firePropertyRemoved ( event ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set of keys for all entries in this group and optionally all of the keys in the defaults map . [CODESPLIT] public Set keySet ( final boolean includeDefaults ) { if ( includeDefaults ) { Set set = new HashSet ( ) ; set . addAll ( defaults . keySet ( ) ) ; set . addAll ( super . keySet ( ) ) ; return Collections . synchronizedSet ( set ) ; } return super . keySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set of entrys for all entries in this group and optionally all of the entrys in the defaults map . [CODESPLIT] public Set entrySet ( final boolean includeDefaults ) { if ( includeDefaults ) { Set set = new HashSet ( ) ; set . addAll ( defaults . entrySet ( ) ) ; set . addAll ( super . entrySet ( ) ) ; return Collections . synchronizedSet ( set ) ; } return super . entrySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a property listener . [CODESPLIT] public void addPropertyListener ( PropertyListener listener ) { if ( listener == null ) throw new NullArgumentException ( \"listener\" ) ; if ( listener instanceof BoundPropertyListener ) { addPropertyListener ( ( BoundPropertyListener ) listener ) ; } else { // only add the listener if it is not in the list already if ( ! unboundListeners . contains ( listener ) ) unboundListeners . add ( listener ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an array of property listeners . [CODESPLIT] public void addPropertyListeners ( PropertyListener [ ] listeners ) { if ( listeners == null ) throw new NullArgumentException ( \"listeners\" ) ; for ( int i = 0 ; i < listeners . length ; i ++ ) { addPropertyListener ( listeners [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a property listener . [CODESPLIT] public boolean removePropertyListener ( PropertyListener listener ) { if ( listener == null ) throw new NullArgumentException ( \"listener\" ) ; boolean removed = false ; if ( listener instanceof BoundPropertyListener ) { removed = removePropertyListener ( ( BoundPropertyListener ) listener ) ; } else { removed = unboundListeners . remove ( listener ) ; } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire a property added event to the given list of listeners . [CODESPLIT] private void firePropertyAdded ( List list , PropertyEvent event ) { if ( list == null ) return ; int size = list . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyListener listener = ( PropertyListener ) list . get ( i ) ; listener . propertyAdded ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire a property removed event to the given list of listeners . [CODESPLIT] private void firePropertyRemoved ( List list , PropertyEvent event ) { if ( list == null ) return ; int size = list . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyListener listener = ( PropertyListener ) list . get ( i ) ; listener . propertyRemoved ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire a property changed event to the given list of listeners . [CODESPLIT] private void firePropertyChanged ( List list , PropertyEvent event ) { if ( list == null ) return ; int size = list . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { PropertyListener listener = ( PropertyListener ) list . get ( i ) ; listener . propertyChanged ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fire a property changed event to all listeners . [CODESPLIT] protected void firePropertyChanged ( PropertyEvent event ) { // fire all bound listeners (if any) first if ( boundListeners != null ) { List list = ( List ) boundListeners . get ( event . getPropertyName ( ) ) ; if ( list != null ) { firePropertyChanged ( list , event ) ; } } // next fire all unbound listeners firePropertyChanged ( unboundListeners , event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make a optionaly prefixed property name . [CODESPLIT] protected String makePrefixedPropertyName ( String base , String prefix ) { String name = base ; if ( prefix != null ) { StringBuffer buff = new StringBuffer ( base ) ; if ( prefix != null ) { buff . insert ( 0 , PROPERTY_NAME_SEPARATOR ) ; buff . insert ( 0 , prefix ) ; } return buff . toString ( ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a map . [CODESPLIT] public void load ( String prefix , Map map ) throws PropertyException { // prefix can be null if ( map == null ) throw new NullArgumentException ( \"map\" ) ; // set properties for each key in map Iterator iter = map . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { // make a string key with optional prefix String key = String . valueOf ( iter . next ( ) ) ; String name = makePrefixedPropertyName ( key , prefix ) ; String value = String . valueOf ( map . get ( name ) ) ; // set the property setProperty ( name , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a PropertyReader . [CODESPLIT] public void load ( PropertyReader reader ) throws PropertyException , IOException { if ( reader == null ) throw new NullArgumentException ( \"reader\" ) ; load ( reader . readProperties ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a PropertyReader specifed by the given class name . [CODESPLIT] public void load ( String className ) throws PropertyException , IOException { if ( className == null ) throw new NullArgumentException ( \"className\" ) ; PropertyReader reader = null ; try { Class type = Class . forName ( className ) ; reader = ( PropertyReader ) type . newInstance ( ) ; } catch ( Exception e ) { throw new PropertyException ( e ) ; } // load the properties from the source load ( reader ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a property . [CODESPLIT] public synchronized Object setProperty ( String name , String value ) { updateJndiCache ( name , value ) ; return put ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array style property . [CODESPLIT] public String [ ] getArrayProperty ( String base , String [ ] defaultValues ) { if ( base == null ) throw new NullArgumentException ( \"base\" ) ; // create a new list to store indexed values into List list = new LinkedList ( ) ; int i = 0 ; while ( true ) { // make the index property name String name = makeIndexPropertyName ( base , i ) ; // see if there is a value for this property String value = getProperty ( name ) ; if ( value != null ) { list . add ( value ) ; } else if ( i >= 0 ) { break ; // no more index properties } i ++ ; } String values [ ] = defaultValues ; // if the list is not empty, then return it as an array if ( list . size ( ) != 0 ) { values = ( String [ ] ) list . toArray ( new String [ list . size ( ) ] ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a property group for the given property base at the given index . [CODESPLIT] public PropertyGroup getPropertyGroup ( String basename , int index ) { String name = makeIndexPropertyName ( basename , index ) ; return getPropertyGroup ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register the mapping from the public id / system id to the dtd / xsd file name . This overwrites any existing mapping . [CODESPLIT] public synchronized void registerLocalEntity ( String id , String dtdOrSchema ) { if ( localEntities == null ) localEntities = new ConcurrentHashMap ( ) ; localEntities . put ( id , dtdOrSchema ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns DTD / Schema inputSource . The resolution logic is : [CODESPLIT] public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { entityResolved . set ( Boolean . FALSE ) ; // nothing to resolve if ( publicId == null && systemId == null ) return null ; boolean trace = log . isTraceEnabled ( ) ; boolean resolvePublicIdFirst = true ; if ( publicId != null && systemId != null ) { String registeredSystemId = null ; if ( localEntities != null ) registeredSystemId = ( String ) localEntities . get ( publicId ) ; if ( registeredSystemId == null ) registeredSystemId = ( String ) entities . get ( publicId ) ; if ( registeredSystemId != null && ! registeredSystemId . equals ( systemId ) ) { resolvePublicIdFirst = false ; if ( trace ) log . trace ( \"systemId argument '\" + systemId + \"' for publicId '\" + publicId + \"' is different from the registered systemId '\" + registeredSystemId + \"', resolution will be based on the argument\" ) ; } } InputSource inputSource = null ; if ( resolvePublicIdFirst ) { // Look for a registered publicID inputSource = resolvePublicID ( publicId , trace ) ; } if ( inputSource == null ) { // Try to resolve the systemID from the registry inputSource = resolveSystemID ( systemId , trace ) ; } if ( inputSource == null ) { // Try to resolve the systemID as a classpath reference under dtd or schema inputSource = resolveClasspathName ( systemId , trace ) ; } if ( inputSource == null ) { // Try to resolve the systemID as a absolute URL inputSource = resolveSystemIDasURL ( systemId , trace ) ; } entityResolved . set ( new Boolean ( inputSource != null ) ) ; if ( inputSource == null ) log . debug ( \"Cannot resolve [publicID=\" + publicId + \",systemID=\" + systemId + \"]\" ) ; return inputSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the boolean value to inform id DTD was found in the XML file or not [CODESPLIT] public boolean isEntityResolved ( ) { Boolean value = entityResolved . get ( ) ; return value != null ? value . booleanValue ( ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the schema from the class entity to schema file mapping . @see #registerEntity ( String String ) [CODESPLIT] protected InputSource resolvePublicID ( String publicId , boolean trace ) { if ( publicId == null ) return null ; if ( trace ) log . trace ( \"resolvePublicID, publicId=\" + publicId ) ; InputSource inputSource = null ; String filename = null ; if ( localEntities != null ) filename = ( String ) localEntities . get ( publicId ) ; if ( filename == null ) filename = ( String ) entities . get ( publicId ) ; if ( filename != null ) { if ( trace ) log . trace ( \"Found entity from publicId=\" + publicId + \" fileName=\" + filename ) ; InputStream ins = loadClasspathResource ( filename , trace ) ; if ( ins != null ) { inputSource = new InputSource ( ins ) ; inputSource . setPublicId ( publicId ) ; } else { log . trace ( \"Cannot load publicId from classpath resource: \" + filename ) ; // Try the file name as a URI inputSource = resolveSystemIDasURL ( filename , trace ) ; if ( inputSource == null ) log . warn ( \"Cannot load publicId from resource: \" + filename ) ; } } return inputSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to use the systemId as a URL from which the schema can be read . This checks to see whether the systemId is a key to an entry in the class entity map . [CODESPLIT] protected InputSource resolveSystemID ( String systemId , boolean trace ) { if ( systemId == null ) return null ; if ( trace ) log . trace ( \"resolveSystemID, systemId=\" + systemId ) ; InputSource inputSource = null ; // Try to resolve the systemId as an entity key String filename = null ; if ( localEntities != null ) filename = ( String ) localEntities . get ( systemId ) ; if ( filename == null ) filename = ( String ) entities . get ( systemId ) ; if ( filename != null ) { if ( trace ) log . trace ( \"Found entity systemId=\" + systemId + \" fileName=\" + filename ) ; InputStream ins = loadClasspathResource ( filename , trace ) ; if ( ins != null ) { inputSource = new InputSource ( ins ) ; inputSource . setSystemId ( systemId ) ; } else { log . warn ( \"Cannot load systemId from resource: \" + filename ) ; } } return inputSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to use the systemId as a URL from which the schema can be read . This uses the systemID as a URL . [CODESPLIT] protected InputSource resolveSystemIDasURL ( String systemId , boolean trace ) { if ( systemId == null ) return null ; if ( trace ) log . trace ( \"resolveSystemIDasURL, systemId=\" + systemId ) ; InputSource inputSource = null ; // Try to use the systemId as a URL to the schema try { if ( trace ) log . trace ( \"Trying to resolve systemId as a URL\" ) ; // Replace any system property refs if isReplaceSystemProperties is true if ( isReplaceSystemProperties ( ) ) systemId = StringPropertyReplacer . replaceProperties ( systemId ) ; URL url = new URL ( systemId ) ; if ( warnOnNonFileURLs && url . getProtocol ( ) . equalsIgnoreCase ( \"file\" ) == false && url . getProtocol ( ) . equalsIgnoreCase ( \"vfszip\" ) == false ) { log . warn ( \"Trying to resolve systemId as a non-file URL: \" + systemId ) ; } InputStream ins = url . openStream ( ) ; if ( ins != null ) { inputSource = new InputSource ( ins ) ; inputSource . setSystemId ( systemId ) ; } else { log . warn ( \"Cannot load systemId as URL: \" + systemId ) ; } if ( trace ) log . trace ( \"Resolved systemId as a URL\" ) ; } catch ( MalformedURLException ignored ) { if ( trace ) log . trace ( \"SystemId is not a url: \" + systemId , ignored ) ; } catch ( IOException e ) { if ( trace ) log . trace ( \"Failed to obtain URL.InputStream from systemId: \" + systemId , e ) ; } return inputSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve the systemId as a classpath resource . If not found the systemId is simply used as a classpath resource name . [CODESPLIT] protected InputSource resolveClasspathName ( String systemId , boolean trace ) { if ( systemId == null ) return null ; if ( trace ) log . trace ( \"resolveClasspathName, systemId=\" + systemId ) ; String filename = systemId ; // Parse the systemId as a uri to get the final path component try { URI url = new URI ( systemId ) ; String path = url . getPath ( ) ; if ( path == null ) path = url . getSchemeSpecificPart ( ) ; int slash = path . lastIndexOf ( ' ' ) ; if ( slash >= 0 ) filename = path . substring ( slash + 1 ) ; else filename = path ; if ( filename . length ( ) == 0 ) return null ; if ( trace ) log . trace ( \"Mapped systemId to filename: \" + filename ) ; } catch ( URISyntaxException e ) { if ( trace ) log . trace ( \"systemId: is not a URI, using systemId as resource\" , e ) ; } // Resolve the filename as a classpath resource InputStream is = loadClasspathResource ( filename , trace ) ; InputSource inputSource = null ; if ( is != null ) { inputSource = new InputSource ( is ) ; inputSource . setSystemId ( systemId ) ; } return inputSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look for the resource name on the thread context loader resource path . This first simply tries the resource name as is and if not found the resource is prepended with either dtd / or schema / depending on whether the resource ends in . dtd or . xsd . [CODESPLIT] protected InputStream loadClasspathResource ( String resource , boolean trace ) { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; URL url = loader . getResource ( resource ) ; if ( url == null ) { /* Prefix the simple filename with the schema type patch as this is the\n               naming convention for the jboss bundled schemas.\n            */ if ( resource . endsWith ( \".dtd\" ) ) resource = \"dtd/\" + resource ; else if ( resource . endsWith ( \".xsd\" ) ) resource = \"schema/\" + resource ; url = loader . getResource ( resource ) ; } InputStream inputStream = null ; if ( url != null ) { if ( trace ) log . trace ( resource + \" maps to URL: \" + url ) ; try { inputStream = url . openStream ( ) ; } catch ( IOException e ) { log . debug ( \"Failed to open url stream\" , e ) ; } } return inputStream ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets as an Element created by a String . [CODESPLIT] public void setAsText ( String text ) { Document d = getAsDocument ( text ) ; setValue ( d . getDocumentElement ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize a public identifier . [CODESPLIT] public static String normalize ( String publicId ) { String normal = publicId . replace ( ' ' , ' ' ) ; normal = normal . replace ( ' ' , ' ' ) ; normal = normal . replace ( ' ' , ' ' ) ; normal = normal . trim ( ) ; int pos ; while ( ( pos = normal . indexOf ( \"  \" ) ) >= 0 ) { normal = normal . substring ( 0 , pos ) + normal . substring ( pos + 1 ) ; } return normal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode a public identifier as a publicid URN . [CODESPLIT] public static String encodeURN ( String publicId ) { String urn = PublicId . normalize ( publicId ) ; urn = PublicId . stringReplace ( urn , \"%\" , \"%25\" ) ; urn = PublicId . stringReplace ( urn , \";\" , \"%3B\" ) ; urn = PublicId . stringReplace ( urn , \"'\" , \"%27\" ) ; urn = PublicId . stringReplace ( urn , \"?\" , \"%3F\" ) ; urn = PublicId . stringReplace ( urn , \"#\" , \"%23\" ) ; urn = PublicId . stringReplace ( urn , \"+\" , \"%2B\" ) ; urn = PublicId . stringReplace ( urn , \" \" , \"+\" ) ; urn = PublicId . stringReplace ( urn , \"::\" , \";\" ) ; urn = PublicId . stringReplace ( urn , \":\" , \"%3A\" ) ; urn = PublicId . stringReplace ( urn , \"//\" , \":\" ) ; urn = PublicId . stringReplace ( urn , \"/\" , \"%2F\" ) ; return \"urn:publicid:\" + urn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode a publicid URN into a public identifier . [CODESPLIT] public static String decodeURN ( String urn ) { String publicId = \"\" ; if ( urn . startsWith ( \"urn:publicid:\" ) ) { publicId = urn . substring ( 13 ) ; } else { return urn ; } publicId = PublicId . stringReplace ( publicId , \"%2F\" , \"/\" ) ; publicId = PublicId . stringReplace ( publicId , \":\" , \"//\" ) ; publicId = PublicId . stringReplace ( publicId , \"%3A\" , \":\" ) ; publicId = PublicId . stringReplace ( publicId , \";\" , \"::\" ) ; publicId = PublicId . stringReplace ( publicId , \"+\" , \" \" ) ; publicId = PublicId . stringReplace ( publicId , \"%2B\" , \"+\" ) ; publicId = PublicId . stringReplace ( publicId , \"%23\" , \"#\" ) ; publicId = PublicId . stringReplace ( publicId , \"%3F\" , \"?\" ) ; publicId = PublicId . stringReplace ( publicId , \"%27\" , \"'\" ) ; publicId = PublicId . stringReplace ( publicId , \"%3B\" , \";\" ) ; publicId = PublicId . stringReplace ( publicId , \"%25\" , \"%\" ) ; return publicId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace one string with another . [CODESPLIT] private static String stringReplace ( String str , String oldStr , String newStr ) { String result = \"\" ; int pos = str . indexOf ( oldStr ) ; //    System.out.println(str + \": \" + oldStr + \" => \" + newStr); while ( pos >= 0 ) { //      System.out.println(str + \" (\" + pos + \")\"); result += str . substring ( 0 , pos ) ; result += newStr ; str = str . substring ( pos + 1 ) ; pos = str . indexOf ( oldStr ) ; } return result + str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start the watch . [CODESPLIT] public void start ( final boolean reset ) { if ( ! running ) { if ( reset ) reset ( ) ; start = System . currentTimeMillis ( ) ; running = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stop the watch . [CODESPLIT] public long stop ( ) { long lap = 0 ; if ( running ) { count ++ ; stop = System . currentTimeMillis ( ) ; lap = stop - start ; total += lap ; running = false ; } return lap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a synchronized stop watch . [CODESPLIT] public static StopWatch makeSynchronized ( final StopWatch watch ) { return new Wrapper ( watch ) { /** The serialVersionUID */ private static final long serialVersionUID = - 6284244000894114817L ; public synchronized void start ( final boolean reset ) { this . watch . start ( reset ) ; } public synchronized void start ( ) { this . watch . start ( ) ; } public synchronized long stop ( ) { return this . watch . stop ( ) ; } public synchronized void reset ( ) { this . watch . reset ( ) ; } public synchronized long getLapTime ( ) { return this . watch . getLapTime ( ) ; } public synchronized long getAverageLapTime ( ) { return this . watch . getAverageLapTime ( ) ; } public synchronized int getLapCount ( ) { return this . watch . getLapCount ( ) ; } public synchronized long getTime ( ) { return this . watch . getTime ( ) ; } public synchronized boolean isRunning ( ) { return this . watch . isRunning ( ) ; } public synchronized String toString ( ) { return this . watch . toString ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this object with the specified object for order . [CODESPLIT] public int compareTo ( final Object obj ) throws ClassCastException { HashCode hashCode = ( HashCode ) obj ; return compareTo ( hashCode . value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a hash code for a byte array . [CODESPLIT] public static int generate ( final byte [ ] bytes ) { int hashcode = 0 ; for ( int i = 0 ; i < bytes . length ; i ++ ) { hashcode <<= 1 ; hashcode ^= bytes [ i ] ; } return hashcode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a hash code for an object array . [CODESPLIT] public static int generate ( final Object array [ ] , final boolean deep ) { int hashcode = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( deep && ( array [ i ] instanceof Object [ ] ) ) { hashcode ^= generate ( ( Object [ ] ) array [ i ] , true ) ; } else { hashcode ^= array [ i ] . hashCode ( ) ; } } return hashcode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the cache creating all required objects and initializing their values . [CODESPLIT] public void create ( ) { m_map = createMap ( ) ; m_list = createList ( ) ; m_list . m_maxCapacity = m_maxCapacity ; m_list . m_minCapacity = m_minCapacity ; m_list . m_capacity = m_maxCapacity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coerce and set specified value to field . [CODESPLIT] protected void setFieldValue ( String value ) { try { // filter property value value = filterValue ( value ) ; // coerce value to field type Class < ? > type = fieldInstance . getField ( ) . getType ( ) ; PropertyEditor editor = PropertyEditors . findEditor ( type ) ; editor . setAsText ( value ) ; Object coerced = editor . getValue ( ) ; // bind value to field fieldInstance . set ( coerced ) ; } catch ( IllegalAccessException e ) { throw new PropertyException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies that this listener was bound to a property . [CODESPLIT] public void propertyBound ( final PropertyMap map ) { // only set the field if the map contains the property already if ( map . containsProperty ( propertyName ) ) { setFieldValue ( map . getProperty ( propertyName ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start parsing a text catalog file . The file is actually read and parsed as needed by <code > nextEntry< / code > . < / p > [CODESPLIT] public void readCatalog ( Catalog catalog , String fileUrl ) throws MalformedURLException , IOException { URL catURL = null ; try { catURL = new URL ( fileUrl ) ; } catch ( MalformedURLException e ) { catURL = new URL ( \"file:///\" + fileUrl ) ; } URLConnection urlCon = catURL . openConnection ( ) ; try { readCatalog ( catalog , urlCon . getInputStream ( ) ) ; } catch ( FileNotFoundException e ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Failed to load catalog, file not found\" , catURL . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the next token in the catalog file . [CODESPLIT] protected String nextToken ( ) throws IOException { String token = \"\" ; int ch , nextch ; if ( ! tokenStack . empty ( ) ) { return ( String ) tokenStack . pop ( ) ; } // Skip over leading whitespace and comments while ( true ) { // skip leading whitespace ch = catfile . read ( ) ; while ( ch <= ' ' ) { // all ctrls are whitespace ch = catfile . read ( ) ; if ( ch < 0 ) { return null ; } } // now 'ch' is the current char from the file nextch = catfile . read ( ) ; if ( nextch < 0 ) { return null ; } if ( ch == ' ' && nextch == ' ' ) { // we've found a comment, skip it... ch = ' ' ; nextch = nextChar ( ) ; while ( ch != ' ' || nextch != ' ' ) { ch = nextch ; nextch = nextChar ( ) ; } // Ok, we've found the end of the comment, // loop back to the top and start again... } else { stack [ ++ top ] = nextch ; stack [ ++ top ] = ch ; break ; } } ch = nextChar ( ) ; if ( ch == ' ' || ch == ' ' ) { int quote = ch ; while ( ( ch = nextChar ( ) ) != quote ) { char [ ] chararr = new char [ 1 ] ; chararr [ 0 ] = ( char ) ch ; String s = new String ( chararr ) ; token = token . concat ( s ) ; } return token ; } else { // return the next whitespace or comment delimited // string while ( ch > ' ' ) { nextch = nextChar ( ) ; if ( ch == ' ' && nextch == ' ' ) { stack [ ++ top ] = ch ; stack [ ++ top ] = nextch ; return token ; } else { char [ ] chararr = new char [ 1 ] ; chararr [ 0 ] = ( char ) ch ; String s = new String ( chararr ) ; token = token . concat ( s ) ; ch = nextch ; } } return token ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an Iterator containing the <i > union< / i > of all of the elements in the given iterator array . [CODESPLIT] public static Iterator union ( final Iterator iters [ ] ) { Map map = new HashMap ( ) ; for ( int i = 0 ; i < iters . length ; i ++ ) { if ( iters [ i ] != null ) { while ( iters [ i ] . hasNext ( ) ) { Object obj = iters [ i ] . next ( ) ; if ( ! map . containsKey ( obj ) ) { map . put ( obj , Null . VALUE ) ; } } } } return map . keySet ( ) . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Setup the parsing formats . Offered as a separate static method to allow testing of locale changes since SimpleDateFormat will use the default locale upon construction . Should not be normally used! [CODESPLIT] public static void initialize ( ) { PrivilegedAction action = new PrivilegedAction ( ) { public Object run ( ) { String defaultFormat = System . getProperty ( \"org.jboss.util.propertyeditor.DateEditor.format\" , \"MMM d, yyyy\" ) ; String defaultLocale = System . getProperty ( \"org.jboss.util.propertyeditor.DateEditor.locale\" ) ; DateFormat defaultDateFormat ; if ( defaultLocale == null || defaultLocale . length ( ) == 0 ) { defaultDateFormat = new SimpleDateFormat ( defaultFormat ) ; } else { defaultDateFormat = new SimpleDateFormat ( defaultFormat , Strings . parseLocaleString ( defaultLocale ) ) ; } formats = new DateFormat [ ] { defaultDateFormat , // Tue Jan 04 00:00:00 PST 2005 new SimpleDateFormat ( \"EEE MMM d HH:mm:ss z yyyy\" ) , // Wed, 4 Jul 2001 12:08:56 -0700 new SimpleDateFormat ( \"EEE, d MMM yyyy HH:mm:ss Z\" ) } ; return null ; } } ; AccessController . doPrivileged ( action ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the text into a java . util . Date by trying one by one the registered DateFormat ( s ) . [CODESPLIT] public void setAsText ( String text ) { ParseException pe = null ; for ( int i = 0 ; i < formats . length ; i ++ ) { try { // try to parse the date DateFormat df = formats [ i ] ; Date date = df . parse ( text ) ; // store the date in both forms this . text = text ; super . setValue ( date ) ; // done return ; } catch ( ParseException e ) { // remember the last seen exception pe = e ; } } // couldn't parse throw new NestedRuntimeException ( pe ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a vertex to the graph [CODESPLIT] public boolean addVertex ( Vertex < T > v ) { if ( verticies . containsValue ( v ) == false ) { verticies . put ( v . getName ( ) , v ) ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a root vertex . If root does no exist in the graph it is added . [CODESPLIT] public void setRootVertex ( Vertex < T > root ) { this . rootVertex = root ; if ( verticies . containsValue ( root ) == false ) addVertex ( root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a directed weighted Edge<T > into the graph . [CODESPLIT] public boolean addEdge ( Vertex < T > from , Vertex < T > to , int cost ) throws IllegalArgumentException { if ( verticies . containsValue ( from ) == false ) throw new IllegalArgumentException ( \"from is not in graph\" ) ; if ( verticies . containsValue ( to ) == false ) throw new IllegalArgumentException ( \"to is not in graph\" ) ; Edge < T > e = new Edge < T > ( from , to , cost ) ; if ( from . findEdge ( to ) != null ) return false ; else { from . addEdge ( e ) ; to . addEdge ( e ) ; edges . add ( e ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert a bidirectional Edge<T > in the graph [CODESPLIT] public boolean insertBiEdge ( Vertex < T > from , Vertex < T > to , int cost ) throws IllegalArgumentException { return addEdge ( from , to , cost ) && addEdge ( to , from , cost ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a vertex from the graph [CODESPLIT] public boolean removeVertex ( Vertex < T > v ) { if ( ! verticies . containsValue ( v ) ) return false ; verticies . remove ( v . getName ( ) ) ; if ( v == rootVertex ) rootVertex = null ; // Remove the edges associated with v for ( int n = 0 ; n < v . getOutgoingEdgeCount ( ) ; n ++ ) { Edge < T > e = v . getOutgoingEdge ( n ) ; v . remove ( e ) ; Vertex < T > to = e . getTo ( ) ; to . remove ( e ) ; edges . remove ( e ) ; } for ( int n = 0 ; n < v . getIncomingEdgeCount ( ) ; n ++ ) { Edge < T > e = v . getIncomingEdge ( n ) ; v . remove ( e ) ; Vertex < T > predecessor = e . getFrom ( ) ; predecessor . remove ( e ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an Edge<T > from the graph [CODESPLIT] public boolean removeEdge ( Vertex < T > from , Vertex < T > to ) { Edge < T > e = from . findEdge ( to ) ; if ( e == null ) return false ; else { from . remove ( e ) ; to . remove ( e ) ; edges . remove ( e ) ; return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a depth first serach using recursion . [CODESPLIT] public void depthFirstSearch ( Vertex < T > v , final Visitor < T > visitor ) { VisitorEX < T , RuntimeException > wrapper = new VisitorEX < T , RuntimeException > ( ) { public void visit ( Graph < T > g , Vertex < T > v ) throws RuntimeException { if ( visitor != null ) visitor . visit ( g , v ) ; } } ; this . depthFirstSearch ( v , wrapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a depth first serach using recursion . The search may be cut short if the visitor throws an exception . @param <E > exception type [CODESPLIT] public < E extends Exception > void depthFirstSearch ( Vertex < T > v , VisitorEX < T , E > visitor ) throws E { if ( visitor != null ) visitor . visit ( this , v ) ; v . visit ( ) ; for ( int i = 0 ; i < v . getOutgoingEdgeCount ( ) ; i ++ ) { Edge < T > e = v . getOutgoingEdge ( i ) ; if ( ! e . getTo ( ) . visited ( ) ) { depthFirstSearch ( e . getTo ( ) , visitor ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform a breadth first search of this graph starting at v . The vist may be cut short if visitor throws an exception during a vist callback . @param <E > exception type [CODESPLIT] public < E extends Exception > void breadthFirstSearch ( Vertex < T > v , VisitorEX < T , E > visitor ) throws E { LinkedList < Vertex < T >> q = new LinkedList < Vertex < T > > ( ) ; q . add ( v ) ; if ( visitor != null ) visitor . visit ( this , v ) ; v . visit ( ) ; while ( q . isEmpty ( ) == false ) { v = q . removeFirst ( ) ; for ( int i = 0 ; i < v . getOutgoingEdgeCount ( ) ; i ++ ) { Edge < T > e = v . getOutgoingEdge ( i ) ; Vertex < T > to = e . getTo ( ) ; if ( ! to . visited ( ) ) { q . add ( to ) ; if ( visitor != null ) visitor . visit ( this , to ) ; to . visit ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the spanning tree using a DFS starting from v . [CODESPLIT] public void dfsSpanningTree ( Vertex < T > v , DFSVisitor < T > visitor ) { v . visit ( ) ; if ( visitor != null ) visitor . visit ( this , v ) ; for ( int i = 0 ; i < v . getOutgoingEdgeCount ( ) ; i ++ ) { Edge < T > e = v . getOutgoingEdge ( i ) ; if ( ! e . getTo ( ) . visited ( ) ) { if ( visitor != null ) visitor . visit ( this , v , e ) ; e . mark ( ) ; dfsSpanningTree ( e . getTo ( ) , visitor ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the verticies for one with data . [CODESPLIT] public Vertex < T > findVertexByData ( T data , Comparator < T > compare ) { Vertex < T > match = null ; for ( Vertex < T > v : verticies . values ( ) ) { if ( compare . compare ( data , v . getData ( ) ) == 0 ) { match = v ; break ; } } return match ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the graph for cycles . In order to detect cycles we use a modified depth first search called a colored DFS . All nodes are initially marked white . When a node is encountered it is marked grey and when its descendants are completely visited it is marked black . If a grey node is ever encountered then there is a cycle . [CODESPLIT] public Edge < T > [ ] findCycles ( ) { ArrayList < Edge < T >> cycleEdges = new ArrayList < Edge < T > > ( ) ; // Mark all verticies as white for ( int n = 0 ; n < verticies . size ( ) ; n ++ ) { Vertex < T > v = getVertex ( n ) ; v . setMarkState ( VISIT_COLOR_WHITE ) ; } for ( int n = 0 ; n < verticies . size ( ) ; n ++ ) { Vertex < T > v = getVertex ( n ) ; visit ( v , cycleEdges ) ; } Edge < T > [ ] cycles = new Edge [ cycleEdges . size ( ) ] ; cycleEdges . toArray ( cycles ) ; return cycles ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > startElement< / code > method recognizes elements from the plain catalog format and instantiates CatalogEntry objects for them . [CODESPLIT] public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { // Check before calling the super because super will report our // namespace as an extension namespace, but that doesn't count // for this element. boolean inExtension = inExtensionNamespace ( ) ; super . startElement ( namespaceURI , localName , qName , atts ) ; int entryType = - 1 ; Vector entryArgs = new Vector ( ) ; if ( namespaceURI != null && extendedNamespaceName . equals ( namespaceURI ) && ! inExtension ) { // This is an Extended XML Catalog entry if ( atts . getValue ( \"xml:base\" ) != null ) { String baseURI = atts . getValue ( \"xml:base\" ) ; entryType = Catalog . BASE ; entryArgs . add ( baseURI ) ; baseURIStack . push ( baseURI ) ; debug . message ( 4 , \"xml:base\" , baseURI ) ; try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry (base)\" , localName ) ; } } entryType = - 1 ; entryArgs = new Vector ( ) ; } else { baseURIStack . push ( baseURIStack . peek ( ) ) ; } if ( localName . equals ( \"uriSuffix\" ) ) { if ( checkAttributes ( atts , \"suffix\" , \"uri\" ) ) { entryType = Resolver . URISUFFIX ; entryArgs . add ( atts . getValue ( \"suffix\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; debug . message ( 4 , \"uriSuffix\" , atts . getValue ( \"suffix\" ) , atts . getValue ( \"uri\" ) ) ; } } else if ( localName . equals ( \"systemSuffix\" ) ) { if ( checkAttributes ( atts , \"suffix\" , \"uri\" ) ) { entryType = Resolver . SYSTEMSUFFIX ; entryArgs . add ( atts . getValue ( \"suffix\" ) ) ; entryArgs . add ( atts . getValue ( \"uri\" ) ) ; debug . message ( 4 , \"systemSuffix\" , atts . getValue ( \"suffix\" ) , atts . getValue ( \"uri\" ) ) ; } } else { // This is equivalent to an invalid catalog entry type debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } if ( entryType >= 0 ) { try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry\" , localName ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SAX <code > endElement< / code > method does nothing . [CODESPLIT] public void endElement ( String namespaceURI , String localName , String qName ) throws SAXException { super . endElement ( namespaceURI , localName , qName ) ; // Check after popping the stack so we don't erroneously think we // are our own extension namespace... boolean inExtension = inExtensionNamespace ( ) ; int entryType = - 1 ; Vector entryArgs = new Vector ( ) ; if ( namespaceURI != null && ( extendedNamespaceName . equals ( namespaceURI ) ) && ! inExtension ) { String popURI = ( String ) baseURIStack . pop ( ) ; String baseURI = ( String ) baseURIStack . peek ( ) ; if ( ! baseURI . equals ( popURI ) ) { entryType = catalog . BASE ; entryArgs . add ( baseURI ) ; debug . message ( 4 , \"(reset) xml:base\" , baseURI ) ; try { CatalogEntry ce = new CatalogEntry ( entryType , entryArgs ) ; catalog . addEntry ( ce ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { debug . message ( 1 , \"Invalid catalog entry type\" , localName ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { debug . message ( 1 , \"Invalid catalog entry (rbase)\" , localName ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalizes the given string . [CODESPLIT] public static String normalize ( String s , boolean canonical ) { StringBuffer str = new StringBuffer ( ) ; int len = ( s != null ) ? s . length ( ) : 0 ; for ( int i = 0 ; i < len ; i ++ ) { char ch = s . charAt ( i ) ; switch ( ch ) { case ' ' : { str . append ( \"&lt;\" ) ; break ; } case ' ' : { str . append ( \"&gt;\" ) ; break ; } case ' ' : { str . append ( \"&amp;\" ) ; break ; } case ' ' : { str . append ( \"&quot;\" ) ; break ; } case ' ' : { str . append ( \"&apos;\" ) ; break ; } case ' ' : case ' ' : { if ( canonical ) { str . append ( \"&#\" ) ; str . append ( Integer . toString ( ch ) ) ; str . append ( ' ' ) ; break ; } // else, default append char } default : { str . append ( ch ) ; } } } return ( str . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given XML string and return the root Element [CODESPLIT] public static Element parse ( String xmlString ) throws IOException { try { return parse ( new ByteArrayInputStream ( xmlString . getBytes ( \"UTF-8\" ) ) ) ; } catch ( IOException e ) { log . error ( \"Cannot parse: \" + xmlString ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given XML stream and return the root Element [CODESPLIT] public static Element parse ( InputStream xmlStream ) throws IOException { try { Document doc = getDocumentBuilder ( ) . parse ( xmlStream ) ; Element root = doc . getDocumentElement ( ) ; return root ; } catch ( SAXException e ) { throw new IOException ( e . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the given input source and return the root Element [CODESPLIT] public static Element parse ( InputSource source ) throws IOException { try { Document doc = getDocumentBuilder ( ) . parse ( source ) ; Element root = doc . getDocumentElement ( ) ; return root ; } catch ( SAXException e ) { throw new IOException ( e . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an Element for a given name [CODESPLIT] public static Element createElement ( String localPart ) { Document doc = getOwnerDocument ( ) ; log . trace ( \"createElement {}\" + localPart ) ; return doc . createElement ( localPart ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform the giveen qualified name into a QName [CODESPLIT] public static QName resolveQName ( Element el , String qualifiedName ) { QName qname ; String prefix = \"\" ; String namespaceURI = \"\" ; String localPart = qualifiedName ; int colIndex = qualifiedName . indexOf ( \":\" ) ; if ( colIndex > 0 ) { prefix = qualifiedName . substring ( 0 , colIndex ) ; localPart = qualifiedName . substring ( colIndex + 1 ) ; if ( \"xmlns\" . equals ( prefix ) ) { namespaceURI = \"URI:XML_PREDEFINED_NAMESPACE\" ; } else { Element nsElement = el ; while ( namespaceURI . equals ( \"\" ) && nsElement != null ) { namespaceURI = nsElement . getAttribute ( \"xmlns:\" + prefix ) ; if ( namespaceURI . equals ( \"\" ) ) nsElement = getParentElement ( nsElement ) ; } } if ( namespaceURI . equals ( \"\" ) ) throw new IllegalArgumentException ( \"Cannot find namespace uri for: \" + qualifiedName ) ; } qname = new QName ( namespaceURI , localPart , prefix ) ; return qname ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value from the given attribute @param el @param attrName [CODESPLIT] public static String getAttributeValue ( Element el , String attrName ) { return getAttributeValue ( el , new QName ( attrName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the value from the given attribute @param el @param attrName [CODESPLIT] public static String getAttributeValue ( Element el , QName attrName ) { String attr = null ; if ( \"\" . equals ( attrName . getNamespaceURI ( ) ) ) attr = el . getAttribute ( attrName . getLocalPart ( ) ) ; else attr = el . getAttributeNS ( attrName . getNamespaceURI ( ) , attrName . getLocalPart ( ) ) ; if ( \"\" . equals ( attr ) ) attr = null ; return attr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy attributes between elements [CODESPLIT] public static void copyAttributes ( Element destElement , Element srcElement ) { NamedNodeMap attribs = srcElement . getAttributes ( ) ; for ( int i = 0 ; i < attribs . getLength ( ) ; i ++ ) { Attr attr = ( Attr ) attribs . item ( i ) ; String uri = attr . getNamespaceURI ( ) ; String qname = attr . getName ( ) ; String value = attr . getNodeValue ( ) ; // Prevent DOMException: NAMESPACE_ERR: An attempt is made to create or  // change an object in a way which is incorrect with regard to namespaces. if ( uri == null && qname . startsWith ( \"xmlns\" ) ) { log . trace ( \"Ignore attribute: [uri=\" + uri + \",qname=\" + qname + \",value=\" + value + \"]\" ) ; } else { destElement . setAttributeNS ( uri , qname , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "True if the node has child elements [CODESPLIT] public static boolean hasChildElements ( Node node ) { NodeList nlist = node . getChildNodes ( ) ; for ( int i = 0 ; i < nlist . getLength ( ) ; i ++ ) { Node child = nlist . item ( i ) ; if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets child elements [CODESPLIT] public static Iterator getChildElements ( Node node ) { ArrayList list = new ArrayList ( ) ; NodeList nlist = node . getChildNodes ( ) ; for ( int i = 0 ; i < nlist . getLength ( ) ; i ++ ) { Node child = nlist . item ( i ) ; if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) list . add ( child ) ; } return list . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the concatenated text content or null . [CODESPLIT] public static String getTextContent ( Node node , boolean replaceProps ) { boolean hasTextContent = false ; StringBuffer buffer = new StringBuffer ( ) ; NodeList nlist = node . getChildNodes ( ) ; for ( int i = 0 ; i < nlist . getLength ( ) ; i ++ ) { Node child = nlist . item ( i ) ; if ( child . getNodeType ( ) == Node . TEXT_NODE ) { buffer . append ( child . getNodeValue ( ) ) ; hasTextContent = true ; } } String text = ( hasTextContent ? buffer . toString ( ) : null ) ; if ( text != null && replaceProps ) text = StringPropertyReplacer . replaceProperties ( text ) ; return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the child elements for a given local name without namespace [CODESPLIT] public static Iterator getChildElements ( Node node , String nodeName ) { return getChildElementsIntern ( node , new QName ( nodeName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets parent element or null if there is none [CODESPLIT] public static Element getParentElement ( Node node ) { Node parent = node . getParentNode ( ) ; return ( parent instanceof Element ? ( Element ) parent : null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a transaction waiting for a lock [CODESPLIT] public void addWaiting ( Object holder , Resource resource ) { synchronized ( waiting ) { waiting . put ( holder , resource ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a catalog from an input stream . [CODESPLIT] public void readCatalog ( Catalog catalog , InputStream is ) throws IOException , CatalogException { DocumentBuilderFactory factory = null ; DocumentBuilder builder = null ; factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( false ) ; factory . setValidating ( false ) ; try { builder = factory . newDocumentBuilder ( ) ; } catch ( ParserConfigurationException pce ) { throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } Document doc = null ; try { doc = builder . parse ( is ) ; } catch ( SAXException se ) { throw new CatalogException ( CatalogException . UNKNOWN_FORMAT ) ; } Element root = doc . getDocumentElement ( ) ; String namespaceURI = Namespaces . getNamespaceURI ( root ) ; String localName = Namespaces . getLocalName ( root ) ; String domParserClass = getCatalogParser ( namespaceURI , localName ) ; if ( domParserClass == null ) { if ( namespaceURI == null ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"No Catalog parser for \" + localName ) ; } else { catalog . getCatalogManager ( ) . debug . message ( 1 , \"No Catalog parser for \" + \"{\" + namespaceURI + \"}\" + localName ) ; } return ; } DOMCatalogParser domParser = null ; try { domParser = ( DOMCatalogParser ) Class . forName ( domParserClass ) . newInstance ( ) ; } catch ( ClassNotFoundException cnfe ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Cannot load XML Catalog Parser class\" , domParserClass ) ; throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } catch ( InstantiationException ie ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Cannot instantiate XML Catalog Parser class\" , domParserClass ) ; throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } catch ( IllegalAccessException iae ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Cannot access XML Catalog Parser class\" , domParserClass ) ; throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } catch ( ClassCastException cce ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Cannot cast XML Catalog Parser class\" , domParserClass ) ; throw new CatalogException ( CatalogException . UNPARSEABLE ) ; } Node node = root . getFirstChild ( ) ; while ( node != null ) { domParser . parseCatalogEntry ( catalog , node ) ; node = node . getNextSibling ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the catalog behind the specified URL . [CODESPLIT] public void readCatalog ( Catalog catalog , String fileUrl ) throws MalformedURLException , IOException , CatalogException { URL url = new URL ( fileUrl ) ; URLConnection urlCon = url . openConnection ( ) ; readCatalog ( catalog , urlCon . getInputStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the current host internet address . [CODESPLIT] private static byte [ ] getHostAddress ( ) { return ( byte [ ] ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { try { return InetAddress . getLocalHost ( ) . getAddress ( ) ; } catch ( Exception e ) { return UNKNOWN_HOST ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to resolve the entity using the thread specific catolog resolvers [CODESPLIT] public InputSource resolveEntity ( String publicId , String systemId ) throws MalformedURLException , IOException { String resolvedURI = catologResolver . resolveSystem ( systemId ) ; if ( resolvedURI == null ) { resolvedURI = catologResolver . resolvePublic ( publicId , systemId ) ; } if ( resolvedURI != null ) { final InputSource is = new InputSource ( ) ; is . setPublicId ( publicId ) ; is . setSystemId ( systemId ) ; is . setByteStream ( this . loadResource ( resolvedURI ) ) ; this . isLastEntityResolved = true ; return is ; } else { //resource could�t be resloved this . isLastEntityResolved = false ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Seach the path for oasis catalog files . The classpath of <code > Thread . currentThread () . getContextClassLoader () < / code > is used for the lookup . @return the url where the <code > jax - ws - catalog . xml< / code > is located @throws IOException if the catalog files cannot be loaded [CODESPLIT] public static URL lookupCatalogFiles ( ) throws IOException { URL url = null ; //JAXWS-2.-0 spec, Line 27:the current context class loader MUST be used to //retrieve all the resources with the specified name ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; for ( int i = 0 ; i < catalogFilesNames . length ; i ++ ) { url = loader . getResource ( catalogFilesNames [ i ] ) ; //use the first hit if ( url != null ) { break ; } } return url ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JBoss lifecycle [CODESPLIT] public void create ( ) { Throwable error = setSystemPropertyClassValue ( property , className ) ; if ( error != null ) log . trace ( \"Error loading class \" + className + \" property \" + property + \" not set.\" , error ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the system property to a class when the class is available . [CODESPLIT] public static Throwable setSystemPropertyClassValue ( String property , String className ) { // Validation if ( property == null || property . trim ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( \"Null or empty property\" ) ; if ( className == null || className . trim ( ) . length ( ) == 0 ) throw new IllegalArgumentException ( \"Null or empty class name\" ) ; // Is the class available? try { Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( Throwable problem ) { return problem ; } // The class is there, set the property. System . setProperty ( property , className ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format a string buffer containing the Class Interfaces CodeSource and ClassLoader information for the given object clazz . [CODESPLIT] public static void displayClassInfo ( Class clazz , StringBuffer results ) { // Print out some codebase info for the clazz ClassLoader cl = clazz . getClassLoader ( ) ; results . append ( \"\\n\" ) ; results . append ( clazz . getName ( ) ) ; results . append ( \"(\" ) ; results . append ( Integer . toHexString ( clazz . hashCode ( ) ) ) ; results . append ( \").ClassLoader=\" ) ; results . append ( cl ) ; ClassLoader parent = cl ; while ( parent != null ) { results . append ( \"\\n..\" ) ; results . append ( parent ) ; URL [ ] urls = getClassLoaderURLs ( parent ) ; int length = urls != null ? urls . length : 0 ; for ( int u = 0 ; u < length ; u ++ ) { results . append ( \"\\n....\" ) ; results . append ( urls [ u ] ) ; } if ( parent != null ) parent = parent . getParent ( ) ; } CodeSource clazzCS = clazz . getProtectionDomain ( ) . getCodeSource ( ) ; if ( clazzCS != null ) { results . append ( \"\\n++++CodeSource: \" ) ; results . append ( clazzCS ) ; } else results . append ( \"\\n++++Null CodeSource\" ) ; results . append ( \"\\nImplemented Interfaces:\" ) ; Class [ ] ifaces = clazz . getInterfaces ( ) ; for ( int i = 0 ; i < ifaces . length ; i ++ ) { Class iface = ifaces [ i ] ; results . append ( \"\\n++\" ) ; results . append ( iface ) ; results . append ( \"(\" ) ; results . append ( Integer . toHexString ( iface . hashCode ( ) ) ) ; results . append ( \")\" ) ; ClassLoader loader = ifaces [ i ] . getClassLoader ( ) ; results . append ( \"\\n++++ClassLoader: \" ) ; results . append ( loader ) ; ProtectionDomain pd = ifaces [ i ] . getProtectionDomain ( ) ; CodeSource cs = pd . getCodeSource ( ) ; if ( cs != null ) { results . append ( \"\\n++++CodeSource: \" ) ; results . append ( cs ) ; } else results . append ( \"\\n++++Null CodeSource\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use reflection to access a URL [] getURLs or URL [] getClasspath method so that non - URLClassLoader class loaders or class loaders that override getURLs to return null or empty can provide the true classpath info . [CODESPLIT] public static URL [ ] getClassLoaderURLs ( ClassLoader cl ) { URL [ ] urls = { } ; try { Class returnType = urls . getClass ( ) ; Class [ ] parameterTypes = { } ; Class clClass = cl . getClass ( ) ; Method getURLs = clClass . getMethod ( \"getURLs\" , parameterTypes ) ; if ( returnType . isAssignableFrom ( getURLs . getReturnType ( ) ) ) { Object [ ] args = { } ; urls = ( URL [ ] ) getURLs . invoke ( cl , args ) ; } if ( urls == null || urls . length == 0 ) { Method getCp = clClass . getMethod ( \"getClasspath\" , parameterTypes ) ; if ( returnType . isAssignableFrom ( getCp . getReturnType ( ) ) ) { Object [ ] args = { } ; urls = ( URL [ ] ) getCp . invoke ( cl , args ) ; } } } catch ( Exception ignore ) { } return urls ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Describe the class of an object [CODESPLIT] public static String getDescription ( Object object ) { StringBuffer buffer = new StringBuffer ( ) ; describe ( buffer , object ) ; return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Describe the class of an object [CODESPLIT] public static void describe ( StringBuffer buffer , Object object ) { if ( object == null ) buffer . append ( \"**null**\" ) ; else describe ( buffer , object . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Describe the class [CODESPLIT] public static void describe ( StringBuffer buffer , Class clazz ) { if ( clazz == null ) buffer . append ( \"**null**\" ) ; else { buffer . append ( \"{class=\" ) . append ( clazz . getName ( ) ) ; Class [ ] intfs = clazz . getInterfaces ( ) ; if ( intfs . length > 0 ) { buffer . append ( \" intfs=\" ) ; for ( int i = 0 ; i < intfs . length ; ++ i ) { buffer . append ( intfs [ i ] . getName ( ) ) ; if ( i < intfs . length - 1 ) buffer . append ( \", \" ) ; } } buffer . append ( \"}\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the short name of the specified class by striping off the package name . [CODESPLIT] public static String stripPackageName ( final String classname ) { int idx = classname . lastIndexOf ( PACKAGE_SEPARATOR ) ; if ( idx != - 1 ) return classname . substring ( idx + 1 , classname . length ( ) ) ; return classname ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the package name of the specified class . [CODESPLIT] public static String getPackageName ( final String classname ) { if ( classname . length ( ) == 0 ) throw new EmptyStringException ( ) ; int index = classname . lastIndexOf ( PACKAGE_SEPARATOR ) ; if ( index != - 1 ) return classname . substring ( 0 , index ) ; return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Force the given class to be loaded fully . [CODESPLIT] public static void forceLoad ( final Class type ) { if ( type == null ) throw new NullArgumentException ( \"type\" ) ; // don't attempt to force primitives to load if ( type . isPrimitive ( ) ) return ; // don't attempt to force java.* classes to load String packageName = Classes . getPackageName ( type ) ; // System.out.println(\"package name: \" + packageName); if ( packageName . startsWith ( \"java.\" ) || packageName . startsWith ( \"javax.\" ) ) { return ; } // System.out.println(\"forcing class to load: \" + type); try { Method methods [ ] = type . getDeclaredMethods ( ) ; Method method = null ; for ( int i = 0 ; i < methods . length ; i ++ ) { int modifiers = methods [ i ] . getModifiers ( ) ; if ( Modifier . isStatic ( modifiers ) ) { method = methods [ i ] ; break ; } } if ( method != null ) { method . invoke ( null , ( Object [ ] ) null ) ; } else { type . newInstance ( ) ; } } catch ( Exception ignore ) { ThrowableHandler . add ( ignore ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the wrapper class for the given primitive type . [CODESPLIT] public static Class getPrimitiveWrapper ( final Class type ) { if ( ! type . isPrimitive ( ) ) { throw new IllegalArgumentException ( \"type is not a primitive class\" ) ; } for ( int i = 0 ; i < PRIMITIVE_WRAPPER_MAP . length ; i += 2 ) { if ( type . equals ( PRIMITIVE_WRAPPER_MAP [ i ] ) ) return PRIMITIVE_WRAPPER_MAP [ i + 1 ] ; } // should never get here, if we do then PRIMITIVE_WRAPPER_MAP // needs to be updated to include the missing mapping throw new UnreachableStatementException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populates a list with all the interfaces implemented by the argument class c and all its superclasses . [CODESPLIT] public static void getAllInterfaces ( List allIfaces , Class c ) { while ( c != null ) { Class [ ] ifaces = c . getInterfaces ( ) ; for ( int n = 0 ; n < ifaces . length ; n ++ ) { allIfaces . add ( ifaces [ n ] ) ; } c = c . getSuperclass ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array containing all the unique interfaces implemented by the argument class c and all its superclasses . Interfaces that appear multiple times through inheritence are only accounted for once . [CODESPLIT] public static Class [ ] getAllUniqueInterfaces ( Class c ) { Set uniqueIfaces = new HashSet ( ) ; while ( c != null ) { Class [ ] ifaces = c . getInterfaces ( ) ; for ( int n = 0 ; n < ifaces . length ; n ++ ) { uniqueIfaces . add ( ifaces [ n ] ) ; } c = c . getSuperclass ( ) ; } return ( Class [ ] ) uniqueIfaces . toArray ( new Class [ uniqueIfaces . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given class is a primitive wrapper class . [CODESPLIT] public static boolean isPrimitiveWrapper ( final Class type ) { for ( int i = 0 ; i < PRIMITIVE_WRAPPER_MAP . length ; i += 2 ) { if ( type . equals ( PRIMITIVE_WRAPPER_MAP [ i + 1 ] ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiate a java class object [CODESPLIT] public static Object instantiate ( Class expected , String property , String defaultClassName ) { String className = getProperty ( property , defaultClassName ) ; Class clazz = null ; try { clazz = loadClass ( className ) ; } catch ( ClassNotFoundException e ) { throw new NestedRuntimeException ( \"Cannot load class \" + className , e ) ; } Object result = null ; try { result = clazz . newInstance ( ) ; } catch ( InstantiationException e ) { throw new NestedRuntimeException ( \"Error instantiating \" + className , e ) ; } catch ( IllegalAccessException e ) { throw new NestedRuntimeException ( \"Error instantiating \" + className , e ) ; } if ( expected . isAssignableFrom ( clazz ) == false ) throw new NestedRuntimeException ( \"Class \" + className + \" from classloader \" + clazz . getClassLoader ( ) + \" is not of the expected class \" + expected + \" loaded from \" + expected . getClassLoader ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method acts equivalently to invoking <code > Thread . currentThread () . getContextClassLoader () . loadClass ( className ) ; < / code > but it also supports primitive types and array classes of object types or primitive types . [CODESPLIT] public static Class loadClass ( String className ) throws ClassNotFoundException { return loadClass ( className , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method acts equivalently to invoking classLoader . loadClass ( className ) but it also supports primitive types and array classes of object types or primitive types . [CODESPLIT] public static Class loadClass ( String className , ClassLoader classLoader ) throws ClassNotFoundException { // ClassLoader.loadClass() does not handle primitive types: // //   B            byte //   C            char //   D            double //   F            float //   I            int //   J            long //   S            short //   Z            boolean //   V\t         void // if ( className . length ( ) == 1 ) { char type = className . charAt ( 0 ) ; if ( type == ' ' ) return Byte . TYPE ; if ( type == ' ' ) return Character . TYPE ; if ( type == ' ' ) return Double . TYPE ; if ( type == ' ' ) return Float . TYPE ; if ( type == ' ' ) return Integer . TYPE ; if ( type == ' ' ) return Long . TYPE ; if ( type == ' ' ) return Short . TYPE ; if ( type == ' ' ) return Boolean . TYPE ; if ( type == ' ' ) return Void . TYPE ; // else throw... throw new ClassNotFoundException ( className ) ; } // Check for a primative type if ( isPrimitive ( className ) == true ) return ( Class ) Classes . PRIMITIVE_NAME_TYPE_MAP . get ( className ) ; // Check for the internal vm format: Lclassname; if ( className . charAt ( 0 ) == ' ' && className . charAt ( className . length ( ) - 1 ) == ' ' ) return classLoader . loadClass ( className . substring ( 1 , className . length ( ) - 1 ) ) ; // first try - be optimistic // this will succeed for all non-array classes and array classes that have already been resolved // try { return classLoader . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { // if it was non-array class then throw it if ( className . charAt ( 0 ) != ' ' ) throw e ; } // we are now resolving array class for the first time // count opening braces int arrayDimension = 0 ; while ( className . charAt ( arrayDimension ) == ' ' ) arrayDimension ++ ; // resolve component type - use recursion so that we can resolve primitive types also Class componentType = loadClass ( className . substring ( arrayDimension ) , classLoader ) ; // construct array class return Array . newInstance ( componentType , new int [ arrayDimension ] ) . getClass ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a list of Strings from an Interator into an array of Classes ( the Strings are taken as classnames ) . [CODESPLIT] public final static Class < ? > [ ] convertToJavaClasses ( Iterator < String > it , ClassLoader cl ) throws ClassNotFoundException { ArrayList < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; while ( it . hasNext ( ) ) { classes . add ( convertToJavaClass ( it . next ( ) , cl ) ) ; } return classes . toArray ( new Class [ classes . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns attribute s getter method . If the method not found then NoSuchMethodException will be thrown . [CODESPLIT] public final static Method getAttributeGetter ( Class cls , String attr ) throws NoSuchMethodException { StringBuffer buf = new StringBuffer ( attr . length ( ) + 3 ) ; buf . append ( \"get\" ) ; if ( Character . isLowerCase ( attr . charAt ( 0 ) ) ) { buf . append ( Character . toUpperCase ( attr . charAt ( 0 ) ) ) . append ( attr . substring ( 1 ) ) ; } else { buf . append ( attr ) ; } try { return cls . getMethod ( buf . toString ( ) , ( Class [ ] ) null ) ; } catch ( NoSuchMethodException e ) { buf . replace ( 0 , 3 , \"is\" ) ; return cls . getMethod ( buf . toString ( ) , ( Class [ ] ) null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns attribute s setter method . If the method not found then NoSuchMethodException will be thrown . [CODESPLIT] public final static Method getAttributeSetter ( Class cls , String attr , Class type ) throws NoSuchMethodException { StringBuffer buf = new StringBuffer ( attr . length ( ) + 3 ) ; buf . append ( \"set\" ) ; if ( Character . isLowerCase ( attr . charAt ( 0 ) ) ) { buf . append ( Character . toUpperCase ( attr . charAt ( 0 ) ) ) . append ( attr . substring ( 1 ) ) ; } else { buf . append ( attr ) ; } return cls . getMethod ( buf . toString ( ) , new Class [ ] { type } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a given String into the appropriate Class . [CODESPLIT] private final static Class convertToJavaClass ( String name , ClassLoader cl ) throws ClassNotFoundException { int arraySize = 0 ; while ( name . endsWith ( \"[]\" ) ) { name = name . substring ( 0 , name . length ( ) - 2 ) ; arraySize ++ ; } // Check for a primitive type Class c = ( Class ) PRIMITIVE_NAME_TYPE_MAP . get ( name ) ; if ( c == null ) { // No primitive, try to load it from the given ClassLoader try { c = cl . loadClass ( name ) ; } catch ( ClassNotFoundException cnfe ) { throw new ClassNotFoundException ( \"Parameter class not found: \" + name ) ; } } // if we have an array get the array class if ( arraySize > 0 ) { int [ ] dims = new int [ arraySize ] ; for ( int i = 0 ; i < arraySize ; i ++ ) { dims [ i ] = 1 ; } c = Array . newInstance ( c , dims ) . getClass ( ) ; } return c ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a system property [CODESPLIT] private static String getProperty ( final String name , final String defaultValue ) { return ( String ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { return System . getProperty ( name , defaultValue ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the argument text into and Byte using Byte . decode . [CODESPLIT] public void setAsText ( final String text ) { if ( PropertyEditors . isNull ( text ) ) { setValue ( null ) ; return ; } Object newValue = Byte . decode ( text ) ; setValue ( newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array of filenames to load . [CODESPLIT] public static String [ ] getFilenames ( final String propertyName ) throws PropertyException { String filenames [ ] ; // check for singleton property first Object filename = PropertyManager . getProperty ( propertyName ) ; if ( filename != null ) { filenames = new String [ ] { String . valueOf ( filename ) } ; } else { // if no singleton property exists then look for array props filenames = PropertyManager . getArrayProperty ( propertyName ) ; } return filenames ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a file is acceptible . [CODESPLIT] public boolean accept ( final File dir , final String name ) { if ( ignoreCase ) { return name . toLowerCase ( ) . startsWith ( prefix ) ; } else { return name . startsWith ( prefix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maintain the elements in the set . Removes objects from the set that have been reclaimed due to GC . [CODESPLIT] protected final void maintain ( ) { WeakObject weak ; while ( ( weak = ( WeakObject ) queue . poll ( ) ) != null ) { set . remove ( weak ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an iteration over the elements in the set . [CODESPLIT] public Iterator iterator ( ) { return new Iterator ( ) { /** The set's iterator */ Iterator iter = set . iterator ( ) ; /** JBCOMMON-24, handle null values and multiple invocations of hasNext() */ Object UNKNOWN = new Object ( ) ; /** The next available object. */ Object next = UNKNOWN ; public boolean hasNext ( ) { if ( next != UNKNOWN ) { return true ; } while ( iter . hasNext ( ) ) { WeakObject weak = ( WeakObject ) iter . next ( ) ; Object obj = null ; if ( weak != null && ( obj = weak . get ( ) ) == null ) { // object has been reclaimed by the GC continue ; } next = obj ; return true ; } return false ; } public Object next ( ) { if ( ( next == UNKNOWN ) && ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } Object obj = next ; next = UNKNOWN ; return obj ; } public void remove ( ) { iter . remove ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an element to the set . [CODESPLIT] public boolean add ( final Object obj ) { maintain ( ) ; return set . add ( WeakObject . create ( obj , queue ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a URL lister for the supplied protocol [CODESPLIT] public URLLister createURLLister ( String protocol ) throws MalformedURLException { try { String className = ( String ) classes . get ( protocol ) ; if ( className == null ) { throw new MalformedURLException ( \"No lister class defined for protocol \" + protocol ) ; } Class < ? > clazz = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; return ( URLLister ) clazz . newInstance ( ) ; } catch ( ClassNotFoundException e ) { throw new MalformedURLException ( e . getMessage ( ) ) ; } catch ( InstantiationException e ) { throw new MalformedURLException ( e . getMessage ( ) ) ; } catch ( IllegalAccessException e ) { throw new MalformedURLException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if a file is acceptible . [CODESPLIT] public boolean accept ( final File file ) { if ( ignoreCase ) { return file . getName ( ) . toLowerCase ( ) . startsWith ( prefix ) ; } else { return file . getName ( ) . startsWith ( prefix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print debug message ( if the debug level is high enough ) . [CODESPLIT] public void message ( int level , String message ) { if ( debug >= level ) { System . out . println ( message ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print debug message ( if the debug level is high enough ) . [CODESPLIT] public void message ( int level , String message , String spec1 , String spec2 ) { if ( debug >= level ) { System . out . println ( message + \": \" + spec1 ) ; System . out . println ( \"\\t\" + spec2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a property . [CODESPLIT] public Object put ( final Object name , final Object value ) { if ( name == null ) throw new NullArgumentException ( \"name\" ) ; return super . put ( makePropertyName ( name ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a property [CODESPLIT] public Object get ( final Object name ) { if ( name == null ) throw new NullArgumentException ( \"name\" ) ; return super . get ( makePropertyName ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a property . [CODESPLIT] public Object remove ( final Object name ) { if ( name == null ) throw new NullArgumentException ( \"name\" ) ; return super . remove ( makePropertyName ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an entry set for all properties in this group . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Set entrySet ( ) { final Set superSet = super . entrySet ( true ) ; return new java . util . AbstractSet ( ) { private boolean isInGroup ( Map . Entry entry ) { String key = ( String ) entry . getKey ( ) ; return key . startsWith ( basename ) ; } public int size ( ) { Iterator iter = superSet . iterator ( ) ; int count = 0 ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; if ( isInGroup ( entry ) ) { count ++ ; } } return count ; } public Iterator iterator ( ) { return new Iterator ( ) { private Iterator iter = superSet . iterator ( ) ; private Object next ; public boolean hasNext ( ) { if ( next != null ) return true ; while ( next == null ) { if ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; if ( isInGroup ( entry ) ) { next = entry ; return true ; } } else { break ; } } return false ; } public Object next ( ) { if ( next == null ) throw new java . util . NoSuchElementException ( ) ; Object obj = next ; next = null ; return obj ; } public void remove ( ) { iter . remove ( ) ; } } ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a bound property listener . [CODESPLIT] protected void addPropertyListener ( final BoundPropertyListener listener ) { // get the bound property name String name = makePropertyName ( listener . getPropertyName ( ) ) ; // get the bound listener list for the property List list = ( List ) boundListeners . get ( name ) ; // if list is null, then add a new list if ( list == null ) { list = new ArrayList ( ) ; boundListeners . put ( name , list ) ; } // if listener is not in the list already, then add it if ( ! list . contains ( listener ) ) { list . add ( listener ) ; // notify listener that is is bound listener . propertyBound ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove a bound property listener . [CODESPLIT] protected boolean removePropertyListener ( final BoundPropertyListener listener ) { // get the bound property name String name = makePropertyName ( listener . getPropertyName ( ) ) ; // get the bound listener list for the property List list = ( List ) boundListeners . get ( name ) ; boolean removed = false ; if ( list != null ) { removed = list . remove ( listener ) ; // notify listener that is was unbound if ( removed ) listener . propertyUnbound ( this ) ; } return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link FieldBoundPropertyListener } for the field and property name and adds it the underlying property group . [CODESPLIT] protected void bindField ( final String name , final String propertyName ) { if ( name == null || name . equals ( \"\" ) ) throw new IllegalArgumentException ( \"name\" ) ; if ( propertyName == null || propertyName . equals ( \"\" ) ) throw new IllegalArgumentException ( \"propertyName\" ) ; addPropertyListener ( new FieldBoundPropertyListener ( this , name , propertyName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a { @link MethodBoundPropertyListener } for the method and property name and adds it the underlying property group . [CODESPLIT] protected void bindMethod ( final String name , final String propertyName ) { if ( name == null || name . equals ( \"\" ) ) throw new IllegalArgumentException ( \"name\" ) ; if ( propertyName == null || propertyName . equals ( \"\" ) ) throw new IllegalArgumentException ( \"propertyName\" ) ; addPropertyListener //                opposite of field bound =( ( new MethodBoundPropertyListener ( this , propertyName , name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start parsing an OASIS TR9401 Open Catalog file . The file is actually read and parsed as needed by <code > nextEntry< / code > . [CODESPLIT] public void readCatalog ( Catalog catalog , InputStream is ) throws MalformedURLException , IOException { catfile = is ; if ( catfile == null ) { return ; } Vector unknownEntry = null ; while ( true ) { String token = nextToken ( ) ; if ( token == null ) { if ( unknownEntry != null ) { catalog . unknownEntry ( unknownEntry ) ; unknownEntry = null ; } catfile . close ( ) ; catfile = null ; return ; } String entryToken = null ; if ( caseSensitive ) { entryToken = token ; } else { entryToken = token . toUpperCase ( ) ; } if ( entryToken . equals ( \"DELEGATE\" ) ) { entryToken = \"DELEGATE_PUBLIC\" ; } try { int type = CatalogEntry . getEntryType ( entryToken ) ; int numArgs = CatalogEntry . getEntryArgCount ( type ) ; Vector args = new Vector ( ) ; if ( unknownEntry != null ) { catalog . unknownEntry ( unknownEntry ) ; unknownEntry = null ; } for ( int count = 0 ; count < numArgs ; count ++ ) { args . addElement ( nextToken ( ) ) ; } catalog . addEntry ( new CatalogEntry ( entryToken , args ) ) ; } catch ( CatalogException cex ) { if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY_TYPE ) { if ( unknownEntry == null ) { unknownEntry = new Vector ( ) ; } unknownEntry . addElement ( token ) ; } else if ( cex . getExceptionType ( ) == CatalogException . INVALID_ENTRY ) { catalog . getCatalogManager ( ) . debug . message ( 1 , \"Invalid catalog entry\" , token ) ; unknownEntry = null ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the information for a class [CODESPLIT] public T get ( Class < ? > clazz ) { if ( clazz == null ) throw new IllegalArgumentException ( \"Null class\" ) ; Map < String , WeakReference < T > > classLoaderCache = getClassLoaderCache ( clazz . getClassLoader ( ) ) ; WeakReference < T > weak = classLoaderCache . get ( clazz . getName ( ) ) ; if ( weak != null ) { T result = weak . get ( ) ; if ( result != null ) return result ; } T result = instantiate ( clazz ) ; weak = new WeakReference < T > ( result ) ; classLoaderCache . put ( clazz . getName ( ) , weak ) ; generate ( clazz , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the cache for the classloader [CODESPLIT] protected Map < String , WeakReference < T > > getClassLoaderCache ( ClassLoader cl ) { synchronized ( cache ) { Map < String , WeakReference < T > > result = cache . get ( cl ) ; if ( result == null ) { result = CollectionsFactory . createConcurrentReaderMap ( ) ; cache . put ( cl , result ) ; } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Whether a string is interpreted as the null value [CODESPLIT] public static final boolean isNull ( final String value , final boolean trim , final boolean empty ) { // For backwards compatibility if ( disableIsNull ) return false ; // No value? if ( value == null ) return true ; // Trim the text when requested String trimmed = trim ? value . trim ( ) : value ; // Is the empty string null? if ( empty && trimmed . length ( ) == 0 ) return true ; // Just check it. return NULL . equalsIgnoreCase ( trimmed ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locate a value editor for a given target type . [CODESPLIT] public static PropertyEditor findEditor ( final String typeName ) throws ClassNotFoundException { // see if it is a primitive type first Class < ? > type = Classes . getPrimitiveTypeForName ( typeName ) ; if ( type == null ) { // nope try look up ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; type = loader . loadClass ( typeName ) ; } return PropertyEditorManager . findEditor ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a value editor for a given target type . [CODESPLIT] public static PropertyEditor getEditor ( final Class < ? > type ) { PropertyEditor editor = findEditor ( type ) ; if ( editor == null ) { throw new RuntimeException ( \"No property editor for type: \" + type ) ; } return editor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a value editor for a given target type . [CODESPLIT] public static PropertyEditor getEditor ( final String typeName ) throws ClassNotFoundException { PropertyEditor editor = findEditor ( typeName ) ; if ( editor == null ) { throw new RuntimeException ( \"No property editor for type: \" + typeName ) ; } return editor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register an editor class to be used to editor values of a given target class . [CODESPLIT] public static void registerEditor ( final String typeName , final String editorTypeName ) throws ClassNotFoundException { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Class < ? > type = loader . loadClass ( typeName ) ; Class < ? > editorType = loader . loadClass ( editorTypeName ) ; PropertyEditorManager . registerEditor ( type , editorType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a string value into the true value for typeName using the PropertyEditor associated with typeName . [CODESPLIT] public static Object convertValue ( String text , String typeName ) throws ClassNotFoundException , IntrospectionException { // see if it is a primitive type first Class < ? > typeClass = Classes . getPrimitiveTypeForName ( typeName ) ; if ( typeClass == null ) { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; typeClass = loader . loadClass ( typeName ) ; } PropertyEditor editor = PropertyEditorManager . findEditor ( typeClass ) ; if ( editor == null ) { throw new IntrospectionException ( \"No property editor for type=\" + typeClass ) ; } editor . setAsText ( text ) ; return editor . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method takes the properties found in the given beanProps to the bean using the property editor registered for the property . Any property in beanProps that does not have an associated java bean property will result in an IntrospectionException . The string property values are converted to the true java bean property type using the java bean PropertyEditor framework . If a property in beanProps does not have a PropertyEditor registered it will be ignored . [CODESPLIT] public static void mapJavaBeanProperties ( Object bean , Properties beanProps ) throws IntrospectionException { mapJavaBeanProperties ( bean , beanProps , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method takes the properties found in the given beanProps to the bean using the property editor registered for the property . Any property in beanProps that does not have an associated java bean property will result in an IntrospectionException . The string property values are converted to the true java bean property type using the java bean PropertyEditor framework . If a property in beanProps does not have a PropertyEditor registered it will be ignored . [CODESPLIT] public static void mapJavaBeanProperties ( Object bean , Properties beanProps , boolean isStrict ) throws IntrospectionException { HashMap < String , PropertyDescriptor > propertyMap = new HashMap < String , PropertyDescriptor > ( ) ; BeanInfo beanInfo = Introspector . getBeanInfo ( bean . getClass ( ) ) ; PropertyDescriptor [ ] props = beanInfo . getPropertyDescriptors ( ) ; for ( int p = 0 ; p < props . length ; p ++ ) { String fieldName = props [ p ] . getName ( ) ; propertyMap . put ( fieldName , props [ p ] ) ; } boolean trace = log . isTraceEnabled ( ) ; Iterator keys = beanProps . keySet ( ) . iterator ( ) ; if ( trace ) log . trace ( \"Mapping properties for bean: \" + bean ) ; while ( keys . hasNext ( ) ) { String name = ( String ) keys . next ( ) ; String text = beanProps . getProperty ( name ) ; PropertyDescriptor pd = propertyMap . get ( name ) ; if ( pd == null ) { /* Try the property name with the first char uppercased to handle\n            a property name like dLQMaxResent whose expected introspected\n            property name would be DLQMaxResent since the JavaBean\n            Introspector would view setDLQMaxResent as the setter for a\n            DLQMaxResent property whose Introspector.decapitalize() method\n            would also return \"DLQMaxResent\".\n            */ if ( name . length ( ) > 1 ) { char first = name . charAt ( 0 ) ; String exName = Character . toUpperCase ( first ) + name . substring ( 1 ) ; pd = propertyMap . get ( exName ) ; // Be lenient and check the other way around, e.g. ServerName -> serverName if ( pd == null ) { exName = Character . toLowerCase ( first ) + name . substring ( 1 ) ; pd = propertyMap . get ( exName ) ; } } if ( pd == null ) { if ( isStrict ) { String msg = \"No property found for: \" + name + \" on JavaBean: \" + bean ; throw new IntrospectionException ( msg ) ; } else { // since is not strict, ignore that this property was not found continue ; } } } Method setter = pd . getWriteMethod ( ) ; if ( trace ) log . trace ( \"Property editor found for: \" + name + \", editor: \" + pd + \", setter: \" + setter ) ; if ( setter != null ) { Class < ? > ptype = pd . getPropertyType ( ) ; PropertyEditor editor = PropertyEditorManager . findEditor ( ptype ) ; if ( editor == null ) { if ( trace ) log . trace ( \"Failed to find property editor for: \" + name ) ; } try { editor . setAsText ( text ) ; Object args [ ] = { editor . getValue ( ) } ; setter . invoke ( bean , args ) ; } catch ( Exception e ) { if ( trace ) log . trace ( \"Failed to write property\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a server socket on the specified port ( port 0 indicates an anonymous port ) . [CODESPLIT] public ServerSocket createServerSocket ( int port ) throws IOException { ServerSocket activeSocket = new TimeoutServerSocket ( port , backlog , bindAddress ) ; return activeSocket ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the context classloader for the given thread [CODESPLIT] public ClassLoader getContextClassLoader ( final Thread thread ) { return ( ClassLoader ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { return thread . getContextClassLoader ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detects exception contains is or a ApplicationDeadlockException . [CODESPLIT] public static ApplicationDeadlockException isADE ( Throwable t ) { while ( t != null ) { if ( t instanceof ApplicationDeadlockException ) { return ( ApplicationDeadlockException ) t ; } else { t = t . getCause ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Schedules a new timeout . [CODESPLIT] public Timeout schedule ( long time , TimeoutTarget target ) { if ( cancelled . get ( ) ) throw new IllegalStateException ( \"TimeoutFactory has been cancelled\" ) ; if ( time < 0 ) throw new IllegalArgumentException ( \"Negative time\" ) ; if ( target == null ) throw new IllegalArgumentException ( \"Null timeout target\" ) ; return queue . offer ( time , target ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Timeout worker method . [CODESPLIT] private void doWork ( ) { while ( cancelled . get ( ) == false ) { TimeoutExt work = queue . take ( ) ; // Do work, if any if ( work != null ) { // Wrap the TimeoutExt with a runnable that invokes the target callback TimeoutWorker worker = new TimeoutWorker ( work ) ; try { threadPool . run ( worker ) ; } catch ( Throwable t ) { // protect the worker thread from pool enqueue errors ThrowableHandler . add ( ThrowableHandler . Type . ERROR , t ) ; } synchronized ( work ) { work . done ( ) ; } } } // TimeoutFactory was cancelled queue . cancel ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a subcontext including any intermediate contexts . [CODESPLIT] public static Context createSubcontext ( Context ctx , String name ) throws NamingException { Name n = ctx . getNameParser ( \"\" ) . parse ( name ) ; return createSubcontext ( ctx , n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbinds a name from ctx and removes parents if they are empty [CODESPLIT] public static void unbind ( Context ctx , Name name ) throws NamingException { ctx . unbind ( name ) ; //unbind the end node in the name int sz = name . size ( ) ; // walk the tree backwards, stopping at the domain while ( -- sz > 0 ) { Name pname = name . getPrefix ( sz ) ; try { ctx . destroySubcontext ( pname ) ; } catch ( NamingException e ) { log . trace ( \"Unable to remove context \" + pname , e ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup an object in the default initial context [CODESPLIT] public static Object lookup ( String name , Class < ? > clazz ) throws Exception { InitialContext ctx = new InitialContext ( ) ; try { return lookup ( ctx , name , clazz ) ; } finally { ctx . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup an object in the given context [CODESPLIT] public static Object lookup ( Context context , String name , Class clazz ) throws Exception { Object result = context . lookup ( name ) ; checkObject ( context , name , result , clazz ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup an object in the given context [CODESPLIT] public static Object lookup ( Context context , Name name , Class clazz ) throws Exception { Object result = context . lookup ( name ) ; checkObject ( context , name . toString ( ) , result , clazz ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a link [CODESPLIT] public static void createLinkRef ( String fromName , String toName ) throws NamingException { InitialContext ctx = new InitialContext ( ) ; createLinkRef ( ctx , fromName , toName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a link [CODESPLIT] public static void createLinkRef ( Context ctx , String fromName , String toName ) throws NamingException { LinkRef link = new LinkRef ( toName ) ; Context fromCtx = ctx ; Name name = ctx . getNameParser ( \"\" ) . parse ( fromName ) ; String atom = name . get ( name . size ( ) - 1 ) ; for ( int n = 0 ; n < name . size ( ) - 1 ; n ++ ) { String comp = name . get ( n ) ; try { fromCtx = ( Context ) fromCtx . lookup ( comp ) ; } catch ( NameNotFoundException e ) { fromCtx = fromCtx . createSubcontext ( comp ) ; } } log . debug ( \"atom: \" + atom ) ; log . debug ( \"link: \" + link ) ; fromCtx . rebind ( atom , link ) ; log . debug ( \"Bound link \" + fromName + \" to \" + toName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the link ref [CODESPLIT] public static void removeLinkRef ( String name ) throws NamingException { InitialContext ctx = new InitialContext ( ) ; removeLinkRef ( ctx , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove the link ref [CODESPLIT] public static void removeLinkRef ( Context ctx , String name ) throws NamingException { log . debug ( \"Unbinding link \" + name ) ; ctx . unbind ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks an object implements the given class [CODESPLIT] protected static void checkObject ( Context context , String name , Object object , Class clazz ) throws Exception { Class objectClass = object . getClass ( ) ; if ( clazz . isAssignableFrom ( objectClass ) == false ) { StringBuffer buffer = new StringBuffer ( 100 ) ; buffer . append ( \"Object at '\" ) . append ( name ) ; buffer . append ( \"' in context \" ) . append ( context . getEnvironment ( ) ) ; buffer . append ( \" is not an instance of \" ) ; appendClassInfo ( buffer , clazz ) ; buffer . append ( \" object class is \" ) ; appendClassInfo ( buffer , object . getClass ( ) ) ; throw new ClassCastException ( buffer . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append Class Info [CODESPLIT] protected static void appendClassInfo ( StringBuffer buffer , Class clazz ) { buffer . append ( \"[class=\" ) . append ( clazz . getName ( ) ) ; buffer . append ( \" classloader=\" ) . append ( clazz . getClassLoader ( ) ) ; buffer . append ( \" interfaces={\" ) ; Class [ ] interfaces = clazz . getInterfaces ( ) ; for ( int i = 0 ; i < interfaces . length ; ++ i ) { if ( i > 0 ) buffer . append ( \", \" ) ; buffer . append ( \"interface=\" ) . append ( interfaces [ i ] . getName ( ) ) ; buffer . append ( \" classloader=\" ) . append ( interfaces [ i ] . getClassLoader ( ) ) ; } buffer . append ( \"}]\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup an allowed transition given its name . [CODESPLIT] public Transition getTransition ( String name ) { Transition t = ( Transition ) allowedTransitions . get ( name ) ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load the properties from the propertyFile and build the resources from it . [CODESPLIT] private synchronized void readProperties ( ) { try { propertyFileURI = CatalogManager . class . getResource ( \"/\" + propertyFile ) ; InputStream in = CatalogManager . class . getResourceAsStream ( \"/\" + propertyFile ) ; if ( in == null ) { if ( ! ignoreMissingProperties ) { System . err . println ( \"Cannot find \" + propertyFile ) ; // there's no reason to give this warning more than once ignoreMissingProperties = true ; } return ; } resources = new PropertyResourceBundle ( in ) ; } catch ( MissingResourceException mre ) { if ( ! ignoreMissingProperties ) { System . err . println ( \"Cannot read \" + propertyFile ) ; } } catch ( java . io . IOException e ) { if ( ! ignoreMissingProperties ) { System . err . println ( \"Failure trying to read \" + propertyFile ) ; } } // This is a bit of a hack. After we've successfully read the properties, // use them to set the default debug level, if the user hasn't already set // the default debug level. if ( verbosity == null ) { try { String verbStr = resources . getString ( \"verbosity\" ) ; int verb = Integer . parseInt ( verbStr . trim ( ) ) ; debug . setDebug ( verb ) ; verbosity = new Integer ( verb ) ; } catch ( Exception e ) { // nop } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the verbosity setting from the properties . [CODESPLIT] private int queryVerbosity ( ) { String verbStr = System . getProperty ( pVerbosity ) ; if ( verbStr == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultVerbosity ; try { verbStr = resources . getString ( \"verbosity\" ) ; } catch ( MissingResourceException e ) { return defaultVerbosity ; } } try { int verb = Integer . parseInt ( verbStr . trim ( ) ) ; return verb ; } catch ( Exception e ) { System . err . println ( \"Cannot parse verbosity: \\\"\" + verbStr + \"\\\"\" ) ; return defaultVerbosity ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the relativeCatalogs setting from the properties . [CODESPLIT] private boolean queryRelativeCatalogs ( ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultRelativeCatalogs ; try { String allow = resources . getString ( \"relative-catalogs\" ) ; return ( allow . equalsIgnoreCase ( \"true\" ) || allow . equalsIgnoreCase ( \"yes\" ) || allow . equalsIgnoreCase ( \"1\" ) ) ; } catch ( MissingResourceException e ) { return defaultRelativeCatalogs ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the list of catalog files from the properties . [CODESPLIT] private String queryCatalogFiles ( ) { String catalogList = System . getProperty ( pFiles ) ; fromPropertiesFile = false ; if ( catalogList == null ) { if ( resources == null ) readProperties ( ) ; if ( resources != null ) { try { catalogList = resources . getString ( \"catalogs\" ) ; fromPropertiesFile = true ; } catch ( MissingResourceException e ) { System . err . println ( propertyFile + \": catalogs not found.\" ) ; catalogList = null ; } } } if ( catalogList == null ) { catalogList = defaultCatalogFiles ; } return catalogList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the current list of catalog files . [CODESPLIT] public Vector getCatalogFiles ( ) { if ( catalogFiles == null ) { catalogFiles = queryCatalogFiles ( ) ; } StringTokenizer files = new StringTokenizer ( catalogFiles , \";\" ) ; Vector catalogs = new Vector ( ) ; while ( files . hasMoreTokens ( ) ) { String catalogFile = files . nextToken ( ) ; URL absURI = null ; if ( fromPropertiesFile && ! relativeCatalogs ( ) ) { try { absURI = new URL ( propertyFileURI , catalogFile ) ; catalogFile = absURI . toString ( ) ; } catch ( MalformedURLException mue ) { absURI = null ; } } catalogs . add ( catalogFile ) ; } return catalogs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the preferPublic setting from the properties . [CODESPLIT] private boolean queryPreferPublic ( ) { String prefer = System . getProperty ( pPrefer ) ; if ( prefer == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultPreferPublic ; try { prefer = resources . getString ( \"prefer\" ) ; } catch ( MissingResourceException e ) { return defaultPreferPublic ; } } if ( prefer == null ) { return defaultPreferPublic ; } return ( prefer . equalsIgnoreCase ( \"public\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the static - catalog setting from the properties . [CODESPLIT] private boolean queryUseStaticCatalog ( ) { String staticCatalog = System . getProperty ( pStatic ) ; if ( useStaticCatalog == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultUseStaticCatalog ; try { staticCatalog = resources . getString ( \"static-catalog\" ) ; } catch ( MissingResourceException e ) { return defaultUseStaticCatalog ; } } if ( staticCatalog == null ) { return defaultUseStaticCatalog ; } return ( staticCatalog . equalsIgnoreCase ( \"true\" ) || staticCatalog . equalsIgnoreCase ( \"yes\" ) || staticCatalog . equalsIgnoreCase ( \"1\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return a new catalog instance . [CODESPLIT] public Catalog getPrivateCatalog ( ) { Catalog catalog = staticCatalog ; if ( useStaticCatalog == null ) { useStaticCatalog = new Boolean ( getUseStaticCatalog ( ) ) ; } if ( catalog == null || ! useStaticCatalog . booleanValue ( ) ) { try { String catalogClassName = getCatalogClassName ( ) ; if ( catalogClassName == null ) { catalog = new Catalog ( ) ; } else { try { catalog = ( Catalog ) Class . forName ( catalogClassName ) . newInstance ( ) ; } catch ( ClassNotFoundException cnfe ) { debug . message ( 1 , \"Catalog class named '\" + catalogClassName + \"' could not be found. Using default.\" ) ; catalog = new Catalog ( ) ; } catch ( ClassCastException cnfe ) { debug . message ( 1 , \"Class named '\" + catalogClassName + \"' is not a Catalog. Using default.\" ) ; catalog = new Catalog ( ) ; } } catalog . setCatalogManager ( this ) ; catalog . setupReaders ( ) ; catalog . loadSystemCatalogs ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } if ( useStaticCatalog . booleanValue ( ) ) { staticCatalog = catalog ; } } return catalog ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return a catalog instance . [CODESPLIT] public Catalog getCatalog ( ) { Catalog catalog = staticCatalog ; if ( useStaticCatalog == null ) { useStaticCatalog = new Boolean ( getUseStaticCatalog ( ) ) ; } if ( catalog == null || ! useStaticCatalog . booleanValue ( ) ) { catalog = getPrivateCatalog ( ) ; if ( useStaticCatalog . booleanValue ( ) ) { staticCatalog = catalog ; } } return catalog ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Obtain the oasisXMLCatalogPI setting from the properties . < / p > [CODESPLIT] public boolean queryAllowOasisXMLCatalogPI ( ) { String allow = System . getProperty ( pAllowPI ) ; if ( allow == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultOasisXMLCatalogPI ; try { allow = resources . getString ( \"allow-oasis-xml-catalog-pi\" ) ; } catch ( MissingResourceException e ) { return defaultOasisXMLCatalogPI ; } } if ( allow == null ) { return defaultOasisXMLCatalogPI ; } return ( allow . equalsIgnoreCase ( \"true\" ) || allow . equalsIgnoreCase ( \"yes\" ) || allow . equalsIgnoreCase ( \"1\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain the Catalog class name setting from the properties . @return the name [CODESPLIT] public String queryCatalogClassName ( ) { String className = System . getProperty ( pClassname ) ; if ( className == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return null ; try { return resources . getString ( \"catalog-class-name\" ) ; } catch ( MissingResourceException e ) { return null ; } } return className ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SAX resolveEntity API . [CODESPLIT] public InputSource resolveEntity ( String publicId , String systemId ) { String resolved = null ; if ( systemId != null && systemMap . containsKey ( systemId ) ) { resolved = ( String ) systemMap . get ( systemId ) ; } else if ( publicId != null && publicMap . containsKey ( publicId ) ) { resolved = ( String ) publicMap . get ( publicId ) ; } if ( resolved != null ) { try { InputSource iSource = new InputSource ( resolved ) ; iSource . setPublicId ( publicId ) ; // Ideally this method would not attempt to open the // InputStream, but there is a bug (in Xerces, at least) // that causes the parser to mistakenly open the wrong // system identifier if the returned InputSource does // not have a byteStream. // // It could be argued that we still shouldn't do this here, // but since the purpose of calling the entityResolver is // almost certainly to open the input stream, it seems to // do little harm. // URL url = new URL ( resolved ) ; InputStream iStream = url . openStream ( ) ; iSource . setByteStream ( iStream ) ; return iSource ; } catch ( Exception e ) { // FIXME: silently fail? return null ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transformer resolve API . [CODESPLIT] public Source resolve ( String href , String base ) throws TransformerException { String uri = href ; int hashPos = href . indexOf ( \"#\" ) ; if ( hashPos >= 0 ) { uri = href . substring ( 0 , hashPos ) ; } String result = null ; if ( href != null && uriMap . containsKey ( href ) ) { result = ( String ) uriMap . get ( href ) ; } if ( result == null ) { try { URL url = null ; if ( base == null ) { url = new URL ( uri ) ; result = url . toString ( ) ; } else { URL baseURL = new URL ( base ) ; url = ( href . length ( ) == 0 ? baseURL : new URL ( baseURL , uri ) ) ; result = url . toString ( ) ; } } catch ( java . net . MalformedURLException mue ) { // try to make an absolute URI from the current base String absBase = makeAbsolute ( base ) ; if ( ! absBase . equals ( base ) ) { // don't bother if the absBase isn't different! return resolve ( href , absBase ) ; } else { throw new TransformerException ( \"Malformed URL \" + href + \"(base \" + base + \")\" , mue ) ; } } } SAXSource source = new SAXSource ( ) ; source . setInputSource ( new InputSource ( result ) ) ; return source ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to construct an absolute URI [CODESPLIT] private String makeAbsolute ( String uri ) { if ( uri == null ) { uri = \"\" ; } try { URL url = new URL ( uri ) ; return url . toString ( ) ; } catch ( MalformedURLException mue ) { String dir = System . getProperty ( \"user.dir\" ) ; String file = \"\" ; if ( dir . endsWith ( \"/\" ) ) { file = \"file://\" + dir + uri ; } else { file = \"file://\" + dir + \"/\" + uri ; } try { URL fileURL = new URL ( file ) ; return fileURL . toString ( ) ; } catch ( MalformedURLException mue2 ) { // bail return uri ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Use the thread context class loader to resolve the class [CODESPLIT] protected Class < ? > resolveClass ( ObjectStreamClass v ) throws IOException , ClassNotFoundException { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; String className = v . getName ( ) ; try { // JDK 6, by default, only supports array types (ex. [[B)  using Class.forName() return Class . forName ( className , false , loader ) ; } catch ( ClassNotFoundException cnfe ) { Class cl = primClasses . get ( className ) ; if ( cl == null ) throw cnfe ; else return cl ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the <tt > PropertyDescriptor< / tt > for the given bean property name . [CODESPLIT] private PropertyDescriptor getPropertyDescriptor ( final String beanPropertyName ) throws IntrospectionException { Class < ? > instanceType = instance . getClass ( ) ; BeanInfo beanInfo = Introspector . getBeanInfo ( instanceType ) ; PropertyDescriptor descriptors [ ] = beanInfo . getPropertyDescriptors ( ) ; PropertyDescriptor descriptor = null ; for ( int i = 0 ; i < descriptors . length ; i ++ ) { if ( descriptors [ i ] . getName ( ) . equals ( beanPropertyName ) ) { descriptor = descriptors [ i ] ; break ; } } return descriptor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Coerce and invoke the property setter method on the instance . [CODESPLIT] protected void invokeSetter ( String value ) { try { // coerce value to field type Class < ? > type = descriptor . getPropertyType ( ) ; PropertyEditor editor = PropertyEditors . findEditor ( type ) ; editor . setAsText ( value ) ; Object coerced = editor . getValue ( ) ; // System.out.println(\"type: \" + type); // System.out.println(\"coerced: \" + coerced); // invoke the setter method setter . invoke ( instance , new Object [ ] { coerced } ) ; } catch ( InvocationTargetException e ) { Throwable target = e . getTargetException ( ) ; if ( target instanceof PropertyException ) { throw ( PropertyException ) target ; } else { throw new PropertyException ( target ) ; } } catch ( Exception e ) { throw new PropertyException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies that this listener was bound to a property . [CODESPLIT] public void propertyBound ( final PropertyMap map ) { // only set the field if the map contains the property already if ( map . containsProperty ( propertyName ) ) { invokeSetter ( map . getProperty ( propertyName ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the prefix part of a QName or the empty string ( not null ) if the name has no prefix . [CODESPLIT] public static String getPrefix ( Element element ) { String name = element . getTagName ( ) ; String prefix = \"\" ; if ( name . indexOf ( ' ' ) > 0 ) { prefix = name . substring ( 0 , name . indexOf ( ' ' ) ) ; } return prefix ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the localname part of a QName which is the whole name if it has no prefix . [CODESPLIT] public static String getLocalName ( Element element ) { String name = element . getTagName ( ) ; if ( name . indexOf ( ' ' ) > 0 ) { name = name . substring ( name . indexOf ( ' ' ) + 1 ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the namespace URI for the specified prefix at the specified context node . [CODESPLIT] public static String getNamespaceURI ( Node node , String prefix ) { if ( node == null || node . getNodeType ( ) != Node . ELEMENT_NODE ) { return null ; } if ( prefix . equals ( \"\" ) ) { if ( ( ( Element ) node ) . hasAttribute ( \"xmlns\" ) ) { return ( ( Element ) node ) . getAttribute ( \"xmlns\" ) ; } } else { String nsattr = \"xmlns:\" + prefix ; if ( ( ( Element ) node ) . hasAttribute ( nsattr ) ) { return ( ( Element ) node ) . getAttribute ( nsattr ) ; } } return getNamespaceURI ( node . getParentNode ( ) , prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the namespace URI for the namespace to which the element belongs . [CODESPLIT] public static String getNamespaceURI ( Element element ) { String prefix = getPrefix ( element ) ; return getNamespaceURI ( element , prefix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Map the argument text into and Integer using Integer . valueOf . [CODESPLIT] public void setAsText ( final String text ) { if ( PropertyEditors . isNull ( text ) ) { setValue ( null ) ; return ; } Object newValue = Long . valueOf ( text ) ; setValue ( newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a list from an enumeration [CODESPLIT] public static List list ( Enumeration e ) { ArrayList result = new ArrayList ( ) ; while ( e . hasMoreElements ( ) ) result . add ( e . nextElement ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an input stream for the given filename . [CODESPLIT] protected InputStream getInputStream ( String filename ) throws IOException { File file = new File ( filename ) ; return new FileInputStream ( file ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load properties from a file into a properties map . [CODESPLIT] protected void loadProperties ( Properties props , String filename ) throws IOException { if ( filename == null ) throw new NullArgumentException ( \"filename\" ) ; if ( filename . equals ( \"\" ) ) throw new IllegalArgumentException ( \"filename\" ) ; InputStream in = new BufferedInputStream ( getInputStream ( filename ) ) ; props . load ( in ) ; in . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read properties from each specified filename [CODESPLIT] public Map readProperties ( ) throws PropertyException , IOException { Properties props = new Properties ( ) ; // load each specified property file for ( int i = 0 ; i < filenames . length ; i ++ ) { loadProperties ( props , filenames [ i ] ) ; } return props ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an edge to the vertex . If edge . from is this vertex its an outgoing edge . If edge . to is this vertex its an incoming edge . If neither from or to is this vertex the edge is not added . [CODESPLIT] public boolean addEdge ( Edge < T > e ) { if ( e . getFrom ( ) == this ) outgoingEdges . add ( e ) ; else if ( e . getTo ( ) == this ) incomingEdges . add ( e ) ; else return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an outgoing edge ending at to . [CODESPLIT] public void addOutgoingEdge ( Vertex < T > to , int cost ) { Edge < T > out = new Edge < T > ( this , to , cost ) ; outgoingEdges . add ( out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add an incoming edge starting at from [CODESPLIT] public void addIncomingEdge ( Vertex < T > from , int cost ) { Edge < T > out = new Edge < T > ( this , from , cost ) ; incomingEdges . add ( out ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the vertex for either an incoming or outgoing edge mathcing e . [CODESPLIT] public boolean hasEdge ( Edge < T > e ) { if ( e . getFrom ( ) == this ) return outgoingEdges . contains ( e ) ; else if ( e . getTo ( ) == this ) return incomingEdges . contains ( e ) ; else return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove an edge from this vertex [CODESPLIT] public boolean remove ( Edge < T > e ) { if ( e . getFrom ( ) == this ) outgoingEdges . remove ( e ) ; else if ( e . getTo ( ) == this ) incomingEdges . remove ( e ) ; else return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the outgoing edges looking for an edge whose s edge . to == dest . [CODESPLIT] public Edge < T > findEdge ( Vertex < T > dest ) { for ( Edge < T > e : outgoingEdges ) { if ( e . getTo ( ) == dest ) return e ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search the outgoing edges for a match to e . [CODESPLIT] public Edge < T > findEdge ( Edge < T > e ) { if ( outgoingEdges . contains ( e ) ) return e ; else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "What is the cost from this vertext to the dest vertex . [CODESPLIT] public int cost ( Vertex < T > dest ) { if ( dest == this ) return 0 ; Edge < T > e = findEdge ( dest ) ; int cost = Integer . MAX_VALUE ; if ( e != null ) cost = e . getCost ( ) ; return cost ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<P > This function will create a Jar archive containing the src file / directory . The archive will be written to the specified OutputStream . < / P > [CODESPLIT] public static void jar ( OutputStream out , File src ) throws IOException { jar ( out , new File [ ] { src } , null , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<P > This function will create a Jar archive containing the src file / directory . The archive will be written to the specified OutputStream . Directories are processed recursively applying the specified filter if it exists . [CODESPLIT] public static void jar ( OutputStream out , File [ ] src , FileFilter filter ) throws IOException { jar ( out , src , filter , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<P > This function will create a Jar archive containing the src file / directory . The archive will be written to the specified OutputStream . Directories are processed recursively applying the specified filter if it exists . [CODESPLIT] public static void jar ( OutputStream out , File [ ] src , FileFilter filter , String prefix , Manifest man ) throws IOException { for ( int i = 0 ; i < src . length ; i ++ ) { if ( ! src [ i ] . exists ( ) ) { throw new FileNotFoundException ( src . toString ( ) ) ; } } JarOutputStream jout ; if ( man == null ) { jout = new JarOutputStream ( out ) ; } else { jout = new JarOutputStream ( out , man ) ; } if ( prefix != null && prefix . length ( ) > 0 && ! prefix . equals ( \"/\" ) ) { // strip leading '/' if ( prefix . charAt ( 0 ) == ' ' ) { prefix = prefix . substring ( 1 ) ; } // ensure trailing '/' if ( prefix . charAt ( prefix . length ( ) - 1 ) != ' ' ) { prefix = prefix + \"/\" ; } } else { prefix = \"\" ; } JarInfo info = new JarInfo ( jout , filter ) ; for ( int i = 0 ; i < src . length ; i ++ ) { jar ( src [ i ] , prefix , info ) ; } jout . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This recursive method writes all matching files and directories to the jar output stream . [CODESPLIT] private static void jar ( File src , String prefix , JarInfo info ) throws IOException { JarOutputStream jout = info . out ; if ( src . isDirectory ( ) ) { // create / init the zip entry prefix = prefix + src . getName ( ) + \"/\" ; ZipEntry entry = new ZipEntry ( prefix ) ; entry . setTime ( src . lastModified ( ) ) ; entry . setMethod ( JarOutputStream . STORED ) ; entry . setSize ( 0L ) ; entry . setCrc ( 0L ) ; jout . putNextEntry ( entry ) ; jout . closeEntry ( ) ; // process the sub-directories File [ ] files = src . listFiles ( info . filter ) ; for ( int i = 0 ; i < files . length ; i ++ ) { jar ( files [ i ] , prefix , info ) ; } } else if ( src . isFile ( ) ) { // get the required info objects byte [ ] buffer = info . buffer ; // create / init the zip entry ZipEntry entry = new ZipEntry ( prefix + src . getName ( ) ) ; entry . setTime ( src . lastModified ( ) ) ; jout . putNextEntry ( entry ) ; // dump the file FileInputStream in = new FileInputStream ( src ) ; int len ; while ( ( len = in . read ( buffer , 0 , buffer . length ) ) != - 1 ) { jout . write ( buffer , 0 , len ) ; } in . close ( ) ; jout . closeEntry ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a URL check if its a jar url ( jar : <url > ! / archive ) and if it is extract the archive entry into the given dest directory and return a file URL to its location . If jarURL is not a jar url then it is simply returned as the URL for the jar . [CODESPLIT] public static URL extractNestedJar ( URL jarURL , File dest ) throws IOException { // This may not be a jar URL so validate the protocol  if ( jarURL . getProtocol ( ) . equals ( \"jar\" ) == false ) return jarURL ; String destPath = dest . getAbsolutePath ( ) ; URLConnection urlConn = jarURL . openConnection ( ) ; JarURLConnection jarConn = ( JarURLConnection ) urlConn ; // Extract the archive to dest/jarName-contents/archive String parentArchiveName = jarConn . getJarFile ( ) . getName ( ) ; // Find the longest common prefix between destPath and parentArchiveName int length = Math . min ( destPath . length ( ) , parentArchiveName . length ( ) ) ; int n = 0 ; while ( n < length ) { char a = destPath . charAt ( n ) ; char b = parentArchiveName . charAt ( n ) ; if ( a != b ) break ; n ++ ; } // Remove any common prefix from parentArchiveName parentArchiveName = parentArchiveName . substring ( n ) ; File archiveDir = new File ( dest , parentArchiveName + \"-contents\" ) ; if ( archiveDir . exists ( ) == false && archiveDir . mkdirs ( ) == false ) throw new IOException ( \"Failed to create contents directory for archive, path=\" + archiveDir . getAbsolutePath ( ) ) ; String archiveName = jarConn . getEntryName ( ) ; File archiveFile = new File ( archiveDir , archiveName ) ; File archiveParentDir = archiveFile . getParentFile ( ) ; if ( archiveParentDir . exists ( ) == false && archiveParentDir . mkdirs ( ) == false ) throw new IOException ( \"Failed to create parent directory for archive, path=\" + archiveParentDir . getAbsolutePath ( ) ) ; InputStream archiveIS = jarConn . getInputStream ( ) ; FileOutputStream fos = new FileOutputStream ( archiveFile ) ; BufferedOutputStream bos = new BufferedOutputStream ( fos ) ; byte [ ] buffer = new byte [ 4096 ] ; int read ; while ( ( read = archiveIS . read ( buffer ) ) > 0 ) { bos . write ( buffer , 0 , read ) ; } archiveIS . close ( ) ; bos . close ( ) ; // Return the file url to the extracted jar return archiveFile . toURL ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if there are more elements . [CODESPLIT] public boolean hasNext ( ) { for ( ; index < iters . length ; index ++ ) { if ( iters [ index ] != null && iters [ index ] . hasNext ( ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forwards an event into state machine . State machine will deliver the event to a handler methods responsible for its processing . If there is no handler method found then event gets silently ignored and this call has no effect . [CODESPLIT] public void fireEvent ( Object event ) { if ( event == null ) { throw new IllegalArgumentException ( \"Event must not be null.\" ) ; } mTaskQueue . offer ( Task . obtainTask ( Task . CODE_FIRE_EVENT , event , - 1 ) ) ; if ( ! mQueueProcessed ) processTaskQueue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Moves state machine in a new given state . If state machine is already in that state then this method has no effect . Otherwise if exists <code > Type . OnExit< / code > event handler for the current state is called first and then <code > Type . OnEntry< / code > event handler for new state is called . [CODESPLIT] public void transitionTo ( int state ) { mTaskQueue . offer ( Task . obtainTask ( Task . CODE_TRANSITION , null , state ) ) ; if ( ! mQueueProcessed ) processTaskQueue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables traces and sets tag to be used for <code > Log . d () < / code > output . <code > TinyMachine< / code > will trace all processed events and state transitions including events for which handlers in current state are missed . [CODESPLIT] public TinyMachine setTraceTag ( String tag ) { mTraceTag = tag ; if ( mTraceTag != null ) { log ( \"current state\" , null ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-- implementation [CODESPLIT] private void processTaskQueue ( ) { mQueueProcessed = true ; try { Task task ; while ( ( task = mTaskQueue . poll ( ) ) != null ) { switch ( task . code ) { case Task . CODE_FIRE_EVENT : { Object event = task . event ; final Class < ? extends Object > clazz = event . getClass ( ) ; fire ( clazz , event , StateHandler . STATE_ANY ) ; fire ( clazz , event , mCurrentState ) ; break ; } case Task . CODE_TRANSITION : { int state = task . state ; if ( mCurrentState != state ) { fire ( OnExit . class , null , StateHandler . STATE_ANY ) ; fire ( OnExit . class , null , mCurrentState ) ; mCurrentState = state ; if ( mTraceTag != null ) { log ( \"new state\" , null ) ; } fire ( OnEntry . class , null , StateHandler . STATE_ANY ) ; fire ( OnEntry . class , null , mCurrentState ) ; } break ; } default : throw new IllegalStateException ( \"wrong code: \" + task . code ) ; } task . recycle ( ) ; } } finally { mQueueProcessed = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs the complete JvmTypeProvider including index access into the { @link ResourceSet } . The lookup classpath is enhanced with the given tmp directory . [CODESPLIT] @ Deprecated protected void installJvmTypeProvider ( XtextResourceSet resourceSet , File tmpClassDirectory ) { internalInstallJvmTypeProvider ( resourceSet , tmpClassDirectory , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Installs the JvmTypeProvider optionally including index access into the { [CODESPLIT] protected void installJvmTypeProvider ( XtextResourceSet resourceSet , File tmpClassDirectory , boolean skipIndexLookup ) { if ( skipIndexLookup ) { internalInstallJvmTypeProvider ( resourceSet , tmpClassDirectory , skipIndexLookup ) ; } else { // delegate to the deprecated signature in case it was overridden by // clients installJvmTypeProvider ( resourceSet , tmpClassDirectory ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the actual installation of the JvmTypeProvider . [CODESPLIT] private void internalInstallJvmTypeProvider ( XtextResourceSet resourceSet , File tmpClassDirectory , boolean skipIndexLookup ) { Iterable < String > classPathEntries = concat ( getClassPathEntries ( ) , getSourcePathDirectories ( ) , asList ( tmpClassDirectory . toString ( ) ) ) ; classPathEntries = filter ( classPathEntries , new Predicate < String > ( ) { public boolean apply ( String input ) { return ! Strings . isEmpty ( input . trim ( ) ) ; } } ) ; Function < String , URL > toUrl = new Function < String , URL > ( ) { public URL apply ( String from ) { try { return new File ( from ) . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } ; Iterable < URL > classPathUrls = Iterables . transform ( classPathEntries , toUrl ) ; log . debug ( \"classpath used for Struct compilation : \" + classPathUrls ) ; ClassLoader parentClassLoader ; if ( useCurrentClassLoaderAsParent ) { parentClassLoader = currentClassLoader ; } else { if ( isEmpty ( bootClassPath ) ) { parentClassLoader = ClassLoader . getSystemClassLoader ( ) . getParent ( ) ; } else { Iterable < URL > bootClassPathUrls = Iterables . transform ( getBootClassPathEntries ( ) , toUrl ) ; parentClassLoader = new BootClassLoader ( toArray ( bootClassPathUrls , URL . class ) ) ; } } ClassLoader urlClassLoader = new URLClassLoader ( toArray ( classPathUrls , URL . class ) , parentClassLoader ) ; new ClasspathTypeProvider ( urlClassLoader , resourceSet , skipIndexLookup ? null : indexedJvmTypeAccess ) ; resourceSet . setClasspathURIContext ( urlClassLoader ) ; // for annotation processing we need to have the compiler's classpath as // a parent. URLClassLoader urlClassLoaderForAnnotationProcessing = new URLClassLoader ( toArray ( classPathUrls , URL . class ) , currentClassLoader ) ; resourceSet . eAdapters ( ) . add ( new ProcessorClassloaderAdapter ( urlClassLoaderForAnnotationProcessing ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "version 2 . 2 . x [CODESPLIT] protected static boolean cleanFolder ( File parentFolder , FileFilter filter , boolean continueOnError , boolean deleteParentFolder ) { if ( ! parentFolder . exists ( ) ) { return true ; } if ( filter == null ) filter = ACCEPT_ALL_FILTER ; log . debug ( \"Cleaning folder \" + parentFolder . toString ( ) ) ; final File [ ] contents = parentFolder . listFiles ( filter ) ; for ( int j = 0 ; j < contents . length ; j ++ ) { final File file = contents [ j ] ; if ( file . isDirectory ( ) ) { if ( ! cleanFolder ( file , filter , continueOnError , true ) && ! continueOnError ) return false ; } else { if ( ! file . delete ( ) ) { log . warn ( \"Couldn't delete \" + file . getAbsolutePath ( ) ) ; if ( ! continueOnError ) return false ; } } } if ( deleteParentFolder ) { if ( parentFolder . list ( ) . length == 0 && ! parentFolder . delete ( ) ) { log . warn ( \"Couldn't delete \" + parentFolder . getAbsolutePath ( ) ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dispatch the given action . Dispatching is always done on the JavaFX application thread even if this method is called from another thread . [CODESPLIT] public void dispatchOnFxThread ( Action action ) { if ( Platform . isFxApplicationThread ( ) ) { actionStream . push ( action ) ; } else { Platform . runLater ( ( ) -> actionStream . push ( action ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A filtered event - stream of actions of the given type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) < T extends Action > EventStream < T > getActionStream ( Class < T > actionType ) { return Dispatcher . getInstance ( ) . getActionStream ( ) . filter ( action -> action . getClass ( ) . equals ( actionType ) ) . map ( action -> ( T ) action ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Taken from mvvmFX [CODESPLIT] private static String createFxmlPath ( Class < ? > viewType ) { final StringBuilder pathBuilder = new StringBuilder ( ) ; pathBuilder . append ( \"/\" ) ; if ( viewType . getPackage ( ) != null ) { pathBuilder . append ( viewType . getPackage ( ) . getName ( ) . replaceAll ( \"\\\\.\" , \"/\" ) ) ; pathBuilder . append ( \"/\" ) ; } pathBuilder . append ( viewType . getSimpleName ( ) ) ; pathBuilder . append ( \".fxml\" ) ; return pathBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update all views by invoking the update function ( { [CODESPLIT] public void updateViews ( ) { cache . entrySet ( ) . forEach ( entry -> updateFunction . accept ( entry . getKey ( ) , entry . getValue ( ) . getController ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update all views that match the given predicate by invoking the update function ( { [CODESPLIT] public void updateViews ( Predicate < T > predicate ) { cache . entrySet ( ) . stream ( ) . filter ( entry -> predicate . test ( entry . getKey ( ) ) ) . forEach ( entry -> updateFunction . accept ( entry . getKey ( ) , entry . getValue ( ) . getController ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method can be used to subscribe to actions of a given type . The subscription is managed by the { @link Dispatcher } . [CODESPLIT] protected < T extends Action > void subscribe ( Class < T > actionType , Consumer < T > actionConsumer ) { Dispatcher . getInstance ( ) . getActionStream ( actionType ) . subscribe ( actionConsumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an appropriate { [CODESPLIT] public Logger getLogger ( String name ) { String tag = name == null ? ANONYMOUS_TAG : name ; Logger logger = loggerMap . get ( tag ) ; if ( logger == null ) { Logger newInstance = new TimberAndroidLoggerAdapter ( tag ) ; Logger oldInstance = loggerMap . putIfAbsent ( tag , newInstance ) ; logger = oldInstance == null ? newInstance : oldInstance ; } return logger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level VERBOSE according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for level VERBOSE . < / p > [CODESPLIT] public void trace ( String format , Object arg ) { formatAndLog ( Log . VERBOSE , format , arg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level VERBOSE according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the VERBOSE level . < / p > [CODESPLIT] public void trace ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . VERBOSE , format , arg1 , arg2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level VERBOSE according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the VERBOSE level . < / p > [CODESPLIT] public void trace ( String format , Object ... argArray ) { formatAndLog ( Log . VERBOSE , format , argArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log an exception ( throwable ) at level VERBOSE with an accompanying message . [CODESPLIT] public void trace ( String msg , Throwable t ) { log ( Log . VERBOSE , msg , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level DEBUG according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for level DEBUG . < / p > [CODESPLIT] public void debug ( String format , Object arg ) { formatAndLog ( Log . DEBUG , format , arg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level DEBUG according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the DEBUG level . < / p > [CODESPLIT] public void debug ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . DEBUG , format , arg1 , arg2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level DEBUG according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the DEBUG level . < / p > [CODESPLIT] public void debug ( String format , Object ... argArray ) { formatAndLog ( Log . DEBUG , format , argArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log an exception ( throwable ) at level DEBUG with an accompanying message . [CODESPLIT] public void debug ( String msg , Throwable t ) { log ( Log . DEBUG , msg , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level INFO according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for the INFO level . < / p > [CODESPLIT] public void info ( String format , Object arg ) { formatAndLog ( Log . INFO , format , arg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the INFO level according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the INFO level . < / p > [CODESPLIT] public void info ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . INFO , format , arg1 , arg2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level INFO according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the INFO level . < / p > [CODESPLIT] public void info ( String format , Object ... argArray ) { formatAndLog ( Log . INFO , format , argArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log an exception ( throwable ) at the INFO level with an accompanying message . [CODESPLIT] public void info ( String msg , Throwable t ) { log ( Log . INFO , msg , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the WARN level according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for the WARN level . < / p > [CODESPLIT] public void warn ( String format , Object arg ) { formatAndLog ( Log . WARN , format , arg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the WARN level according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the WARN level . < / p > [CODESPLIT] public void warn ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . WARN , format , arg1 , arg2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level WARN according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the WARN level . < / p > [CODESPLIT] public void warn ( String format , Object ... argArray ) { formatAndLog ( Log . WARN , format , argArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log an exception ( throwable ) at the WARN level with an accompanying message . [CODESPLIT] public void warn ( String msg , Throwable t ) { log ( Log . WARN , msg , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the ERROR level according to the specified format and argument . <p > <p > This form avoids superfluous object creation when the logger is disabled for the ERROR level . < / p > [CODESPLIT] public void error ( String format , Object arg ) { formatAndLog ( Log . ERROR , format , arg ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at the ERROR level according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the ERROR level . < / p > [CODESPLIT] public void error ( String format , Object arg1 , Object arg2 ) { formatAndLog ( Log . ERROR , format , arg1 , arg2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log a message at level ERROR according to the specified format and arguments . <p > <p > This form avoids superfluous object creation when the logger is disabled for the ERROR level . < / p > [CODESPLIT] public void error ( String format , Object ... argArray ) { formatAndLog ( Log . ERROR , format , argArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log an exception ( throwable ) at the ERROR level with an accompanying message . [CODESPLIT] public void error ( String msg , Throwable t ) { log ( Log . ERROR , msg , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "One to many [CODESPLIT] public Stream < Record > oneToMany ( Collection < ? extends Record > rights , ListKey < Record > manyKey ) { return oneToMany ( rights . stream ( ) , manyKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strict one to many [CODESPLIT] public Stream < Record > strictOneToMany ( Collection < ? extends Record > rights , ListKey < Record > manyKey ) { return strictOneToMany ( rights . stream ( ) , manyKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Many to one [CODESPLIT] public Stream < T2 < L , R > > manyToOne ( Collection < ? extends R > rights ) { return manyToOne ( rights . stream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strict many to one [CODESPLIT] public Stream < T2 < L , R > > strictManyToOne ( Collection < ? extends R > rights ) { return strictManyToOne ( rights . stream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strict one to many [CODESPLIT] public Stream < T2 < L , Set < R > > > strictOneToMany ( Collection < ? extends R > rights ) { return strictOneToMany ( rights . stream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Strict one to one [CODESPLIT] public Stream < T2 < L , R > > strictOneToOne ( Collection < ? extends R > rights ) { return strictOneToOne ( rights . stream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bootstrap the SLF4J root logger with a configured { @link com . getsentry . raven . logback . SentryAppender } . [CODESPLIT] public static void bootstrap ( final String dsn , Optional < String > tags , boolean cleanRootLogger ) { bootstrap ( dsn , tags , Optional . empty ( ) , Optional . empty ( ) , cleanRootLogger ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bootstrap the SLF4J root logger with a configured { @link com . getsentry . raven . logback . SentryAppender } . [CODESPLIT] public static void bootstrap ( final String dsn , Optional < String > tags , Optional < String > environment , Optional < String > release , boolean cleanRootLogger ) { bootstrap ( dsn , tags , environment , release , Optional . empty ( ) , cleanRootLogger ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bootstrap the SLF4J root logger with a configured { @link com . getsentry . raven . logback . SentryAppender } . [CODESPLIT] public static void bootstrap ( final String dsn , Optional < String > tags , Optional < String > environment , Optional < String > release , Optional < String > serverName , boolean cleanRootLogger ) { final RavenAppenderFactory raven = new RavenAppenderFactory ( ) ; raven . setThreshold ( Level . ERROR ) ; raven . setDsn ( dsn ) ; raven . setTags ( tags ) ; raven . setEnvironment ( environment ) ; raven . setRelease ( release ) ; raven . setServerName ( serverName ) ; registerAppender ( dsn , cleanRootLogger , raven ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The last modified time of a page is the most recent of : <ol > <li > { [CODESPLIT] @ Override public ReadableInstant getLastModified ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { return AoArrays . maxNonNull ( page . getDateCreated ( ) , page . getDatePublished ( ) , page . getDateModified ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the page settings . [CODESPLIT] @ Override public boolean getAllowRobots ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { return PageUtils . findAllowRobots ( servletContext , request , response , page ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assert that the generated command matches the specified command . [CODESPLIT] @ Then ( \"^the instruction generated should be \\\"([^\\\"]*)\\\"$\" ) public void the_instruction_generated_should_be ( String command ) throws Throwable { verify ( context . getDrinkMaker ( ) ) . executeCommand ( eq ( command ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempt to retrieve the parameter ( <code > [CODESPLIT] private DocletTag findParamDocByNameOrIndex ( String name , int paramIndex , List < DocletTag > tags ) { for ( DocletTag tag : tags ) { if ( name . equals ( tag . getParameters ( ) . get ( 0 ) ) ) { return tag ; } } if ( paramIndex < tags . size ( ) ) { return tags . get ( paramIndex ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "尝试合并 sogou（去除了没有词性的） 与 rmmseg 的词库。 [CODESPLIT] public static void main ( String [ ] args ) throws IOException { FileInputStream fis = new FileInputStream ( new File ( \"dic/word-with-attr.dic\" ) ) ; final Set < String > words = new TreeSet < String > ( ) ; final int [ ] num = { 0 } ; FileLoading fl = new FileLoading ( ) { public void row ( String line , int n ) { words . add ( line . trim ( ) ) ; num [ 0 ] ++ ; } } ; Dictionary . load ( fis , fl ) ; fis = new FileInputStream ( new File ( \"dic/words-rmmseg.dic\" ) ) ; Dictionary . load ( fis , fl ) ; WriterRow wr = new WriterRow ( new File ( \"dic/words-marge-sogou-no-attr-and-rmmseg.dic\" ) ) ; for ( String word : words ) { wr . writerRow ( word ) ; } wr . close ( ) ; System . out . println ( \"rows=\" + num [ 0 ] + \", size=\" + words . size ( ) + \", same=\" + ( num [ 0 ] - words . size ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- Dmode = simple default is complex [CODESPLIT] public static void main ( String [ ] args ) throws Exception { int n = 1 ; if ( args . length < 1 ) { usage ( ) ; return ; } Properties analyzers = new Properties ( ) ; analyzers . load ( new FileInputStream ( new File ( \"analyzer.properties\" ) ) ) ; String mode = System . getProperty ( \"mode\" , \"complex\" ) ; String a = System . getProperty ( \"analyzer\" , \"mmseg4j\" ) ; Analyzer analyzer = null ; String an = ( String ) analyzers . get ( a ) ; if ( an != null ) { analyzer = ( Analyzer ) Class . forName ( an ) . newInstance ( ) ; mode = a ; } else { usage ( ) ; return ; } if ( args . length > 1 ) { try { n = Integer . parseInt ( args [ 1 ] ) ; } catch ( NumberFormatException e ) { } } File path = new File ( args [ 0 ] ) ; System . out . println ( \"analyzer=\" + analyzer . getClass ( ) . getName ( ) ) ; Effect ef = new Effect ( path , analyzer ) ; ef . run ( mode , n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "只要 wordsXXX . dic的文件 [CODESPLIT] protected File [ ] listWordsFiles ( ) { return dicPath . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . startsWith ( \"words\" ) && name . endsWith ( \".dic\" ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加载词文件的模板 [CODESPLIT] public static int load ( InputStream fin , FileLoading loading ) throws IOException { BufferedReader br = new BufferedReader ( new InputStreamReader ( new BufferedInputStream ( fin ) , \"UTF-8\" ) ) ; String line = null ; int n = 0 ; while ( ( line = br . readLine ( ) ) != null ) { if ( line == null || line . startsWith ( \"#\" ) ) { continue ; } n ++ ; loading . row ( line , n ) ; } return n ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取得 str 除去第一个char的部分 [CODESPLIT] private static char [ ] tail ( String str ) { char [ ] cs = new char [ str . length ( ) - 1 ] ; str . getChars ( 1 , str . length ( ) , cs , 0 ) ; return cs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "把 wordsFile 文件的最后更新时间加记录下来 . [CODESPLIT] private synchronized void addLastTime ( File wordsFile ) { if ( wordsFile != null ) { wordsLastTime . put ( wordsFile , wordsFile . lastModified ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "词典文件是否有修改过 [CODESPLIT] public synchronized boolean wordsFileIsChange ( ) { //检查是否有修改文件,包括删除的\r for ( Entry < File , Long > flt : wordsLastTime . entrySet ( ) ) { File words = flt . getKey ( ) ; if ( ! words . canRead ( ) ) { //可能是删除了\r return true ; } if ( words . lastModified ( ) > flt . getValue ( ) ) { //更新了文件\r return true ; } } //检查是否有新文件\r File [ ] words = listWordsFiles ( ) ; if ( words != null ) { for ( File wordsFile : words ) { if ( ! wordsLastTime . containsKey ( wordsFile ) ) { //有新词典文件\r return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "全新加载词库，没有成功加载会回滚。<P / > 注意：重新加载时，务必有两倍的词库树结构的内存，默认词库是 50M / 个 左右。否则抛出 OOM。 [CODESPLIT] public synchronized boolean reload ( ) { Map < File , Long > oldWordsLastTime = new HashMap < File , Long > ( wordsLastTime ) ; Map < Character , CharNode > oldDict = dict ; Map < Character , Object > oldUnit = unit ; try { wordsLastTime . clear ( ) ; dict = loadDic ( dicPath ) ; unit = loadUnit ( dicPath ) ; lastLoadTime = System . currentTimeMillis ( ) ; } catch ( IOException e ) { //rollback\r wordsLastTime . putAll ( oldWordsLastTime ) ; dict = oldDict ; unit = oldUnit ; if ( log . isLoggable ( Level . WARNING ) ) { log . log ( Level . WARNING , \"reload dic error! dic=\" + dicPath + \", and rollbacked.\" , e ) ; } return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "word 能否在词库里找到 [CODESPLIT] public boolean match ( String word ) { if ( word == null || word . length ( ) < 2 ) { return false ; } CharNode cn = dict . get ( word . charAt ( 0 ) ) ; return search ( cn , word . toCharArray ( ) , 0 , word . length ( ) - 1 ) >= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sen [ offset ] 后 tailLen 长的词是否存在 . [CODESPLIT] public int search ( CharNode node , char [ ] sen , int offset , int tailLen ) { if ( node != null ) { return node . indexOf ( sen , offset , tailLen ) ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "当 words . dic 是从 jar 里加载时 可能 defalut 不存在 [CODESPLIT] public static File getDefalutPath ( ) { if ( defalutPath == null ) { String defPath = System . getProperty ( \"mmseg.dic.path\" ) ; log . info ( \"look up in mmseg.dic.path=\" + defPath ) ; if ( defPath == null ) { URL url = Dictionary . class . getClassLoader ( ) . getResource ( \"data\" ) ; if ( url != null ) { defPath = url . getFile ( ) ; log . info ( \"look up in classpath=\" + defPath ) ; } else { defPath = System . getProperty ( \"user.dir\" ) + \"/data\" ; log . info ( \"look up in user.dir=\" + defPath ) ; } } defalutPath = new File ( defPath ) ; if ( ! defalutPath . exists ( ) ) { log . warning ( \"defalut dic path=\" + defalutPath + \" not exist\" ) ; } } return defalutPath ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "读取下一串指定类型的字符放到 bufSentence 中 . [CODESPLIT] private int readChars ( StringBuilder bufSentence , ReadChar readChar ) throws IOException { int num = 0 ; int data = - 1 ; while ( ( data = readNext ( ) ) != - 1 ) { int d = readChar . transform ( data ) ; if ( readChar . isRead ( d ) ) { bufSentence . appendCodePoint ( d ) ; num ++ ; } else { //不是数字回压,要下一步操作\r pushBack ( data ) ; break ; } } return num ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从 StringBuilder 里复制出 char [] [CODESPLIT] private static char [ ] toChars ( StringBuilder bufSentence ) { char [ ] chs = new char [ bufSentence . length ( ) ] ; bufSentence . getChars ( 0 , bufSentence . length ( ) , chs , 0 ) ; return chs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "双角转单角 [CODESPLIT] private static int toAscii ( int codePoint ) { if ( ( codePoint >= 65296 && codePoint <= 65305 ) //０-９\r || ( codePoint >= 65313 && codePoint <= 65338 ) //Ａ-Ｚ\r || ( codePoint >= 65345 && codePoint <= 65370 ) //ａ-ｚ\r ) { codePoint -= 65248 ; } return codePoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- Dmode = simple default is complex - Dfile . encode = utf - 8 or other [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length < 1 ) { System . out . println ( \"Usage:\" ) ; System . out . println ( \"\\t-Dmode=simple, defalut is complex\" ) ; System . out . println ( \"\\tPerformance <txt path> - is a directory that contain *.txt\" ) ; return ; } String mode = System . getProperty ( \"mode\" , \"complex\" ) ; Seg seg = null ; Dictionary dic = Dictionary . getInstance ( ) ; if ( \"simple\" . equals ( mode ) ) { seg = new SimpleSeg ( dic ) ; } else { seg = new ComplexSeg ( dic ) ; } File path = new File ( args [ 0 ] ) ; File [ ] txts = path . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( \".txt\" ) ; } } ) ; long time = 0 ; for ( File txt : txts ) { MMSeg mmSeg = new MMSeg ( new InputStreamReader ( new FileInputStream ( txt ) ) , seg ) ; Word word = null ; OutputStreamWriter osw = new OutputStreamWriter ( new FileOutputStream ( new File ( txt . getAbsoluteFile ( ) + \".\" + mode + \".word\" ) ) ) ; BufferedWriter bw = new BufferedWriter ( osw ) ; long start = System . currentTimeMillis ( ) ; while ( ( word = mmSeg . next ( ) ) != null ) { bw . append ( new String ( word . getString ( ) ) ) . append ( \"\\r\\n\" ) ; } time += System . currentTimeMillis ( ) - start ; bw . close ( ) ; } System . out . println ( \"use \" + time + \"ms\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Word Length [CODESPLIT] public int getLen ( ) { if ( len < 0 ) { len = 0 ; count = 0 ; for ( Word word : words ) { if ( word != null ) { len += word . getLength ( ) ; count ++ ; } } } return len ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "有多少个词，最多3个。 [CODESPLIT] public int getCount ( ) { if ( count < 0 ) { count = 0 ; for ( Word word : words ) { if ( word != null ) { count ++ ; } } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Variance of Word Lengths 就是 标准差的平方 [CODESPLIT] public double getVariance ( ) { if ( variance < 0 ) { double sum = 0 ; for ( Word word : words ) { if ( word != null ) { sum += Math . pow ( word . getLength ( ) - getAvgLen ( ) , 2 ) ; } } variance = sum / getCount ( ) ; } return variance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sum of Degree of Morphemic Freedom of One - Character [CODESPLIT] public int getSumDegree ( ) { if ( sumDegree < 0 ) { int sum = 0 ; for ( Word word : words ) { if ( word != null && word . getDegree ( ) > - 1 ) { sum += word . getDegree ( ) ; } } sumDegree = sum ; } return sumDegree ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "输出 chunks 调试用 . [CODESPLIT] protected void printChunk ( List < Chunk > chunks ) { for ( Chunk ck : chunks ) { System . out . println ( ck + \" -> \" + ck . toFactorString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查找chs [ offset ] 后面的 tailLen个char是否为词 . [CODESPLIT] protected int search ( char [ ] chs , int offset , int tailLen ) { if ( tailLen == 0 ) { return - 1 ; } CharNode cn = dic . head ( chs [ offset ] ) ; return search ( cn , chs , offset , tailLen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "没有数组的复制 . [CODESPLIT] protected int search ( CharNode cn , char [ ] chs , int offset , int tailLen ) { if ( tailLen == 0 || cn == null ) { return - 1 ; } return dic . search ( cn , chs , offset , tailLen ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "最大匹配<br / > 从 chs [ offset ] 开始匹配 同时把 chs [ offset ] 的字符结点保存在 cns [ cnIdx ] [CODESPLIT] protected int maxMatch ( CharNode [ ] cns , int cnIdx , char [ ] chs , int offset ) { CharNode cn = null ; if ( offset < chs . length ) { cn = dic . head ( chs [ offset ] ) ; } cns [ cnIdx ] = cn ; return dic . maxMatch ( cn , chs , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "匹配 同时找出长度 . <br / > 从 chs [ offset ] 开始找所有匹配的词 找到的放到 tailLens [ tailLensIdx ] 中 . <br / > 同时把 chs [ offset ] 的字符结点保存在 cns [ cnIdx ] . [CODESPLIT] protected void maxMatch ( CharNode [ ] cns , int cnIdx , char [ ] chs , int offset , ArrayList < Integer > [ ] tailLens , int tailLensIdx ) { CharNode cn = null ; if ( offset < chs . length ) { cn = dic . head ( chs [ offset ] ) ; } cns [ cnIdx ] = cn ; dic . maxMatch ( cn , tailLens [ tailLensIdx ] , chs , offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "词库转换 [CODESPLIT] public static void main ( String [ ] args ) throws IOException { String words = \"sogou/SogouLabDic.dic\" ; String charset = \"GBK\" ; if ( args . length > 0 ) { words = args [ 0 ] ; } File file = new File ( words ) ; //File path = file.getParentFile();\r //File dist = new File(\"dic/words.dic\");\r File dist = new File ( \"dic/word-with-attr.dic\" ) ; DicTransform dt = new DicTransform ( ) ; //只要词,不频率\r //dt.transform(file, charset, dist, new DeFreq());\r //只要两或三个字的词.\r //dt.transform(file, charset, dist, new TwoOrThreeChar());\r dt . transform ( file , charset , dist , new NoAttr ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "You can take this and extend for your setup if you need more . [CODESPLIT] @ NotNull public static Mode minimal ( @ NotNull String apiKey , @ NotNull Host host , @ NotNull RestPortUrlFactory portUrlFactory ) { return Mode . create ( ) . with ( RestKeys . REST_PORT_URL_FACTORY , portUrlFactory ) //                .with(ExceptionTranslationExtension.TRANSLATOR, new CombinedExceptionTranslator(new DefaultClientExceptionTranslator(), new SoapFaultExceptionTranslator())) . with ( Keys . HOST , host ) . with ( NameApiKeys . API_KEY , apiKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overloaded method that uses for host : { [CODESPLIT] @ NotNull public static Mode minimal ( @ NotNull String apiKey ) { return minimal ( apiKey , DEFAULT_HOST , DEFAULT_PORT_FACTORY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "You can take this and extend for your setup if you need more . [CODESPLIT] @ NotNull public static Mode withContext ( @ NotNull String apiKey , @ NotNull Context context , @ NotNull Host host , @ NotNull RestPortUrlFactory portUrlFactory ) { return minimal ( apiKey , host , portUrlFactory ) . with ( NameApiKeys . CONTEXT , context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overloaded method that uses for host : { [CODESPLIT] @ NotNull public static Mode withContext ( @ NotNull String apiKey , @ NotNull Context context ) { return withContext ( apiKey , context , DEFAULT_HOST , DEFAULT_PORT_FACTORY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a map which contains only those arguments that the superclass understands . [CODESPLIT] private static Map < String , String > superclassArgs ( Map < String , String > args ) { Map < String , String > result = new HashMap <> ( ) ; // resource loading does not take place if no file has been configured. if ( ! result . containsKey ( \"dictionary\" ) ) { result . put ( \"dictionary\" , JdbcResourceLoader . DATABASE ) ; } for ( String arg : ImmutableList . of ( \"dictionary\" , \"ignoreCase\" ) ) { String value = args . get ( arg ) ; if ( value != null ) { result . put ( arg , value ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load words from jdbc [CODESPLIT] @ Override public void inform ( ResourceLoader loader ) throws IOException { super . inform ( new JdbcResourceLoader ( loader , reader , StandardCharsets . UTF_8 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the datasource is able to provide connections . [CODESPLIT] protected final void checkDatasource ( ) { // Check database connection information of data source if ( dataSource != null ) { //noinspection unused,EmptyTryBlock try ( Connection connection = dataSource . getConnection ( ) ) { // Just get the connection to check if data source parameters are configured correctly. } catch ( SQLException e ) { dataSource = null ; logger . error ( \"Failed to connect to database of data source: {}.\" , e . getMessage ( ) ) ; if ( ! ignore ) { throw new IllegalArgumentException ( \"Failed to connect to the database.\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Reader getReader ( ) { if ( dataSource == null ) { if ( ignore ) { return new StringReader ( \"\" ) ; } throw new IllegalArgumentException ( \"Missing data source.\" ) ; } QueryRunner runner = new QueryRunner ( dataSource ) ; try { logger . info ( \"Querying for data using {}\" , sql ) ; List < String > content = runner . query ( sql , SINGLE_LINE_RESULT_SET_HANDLER ) ; logger . info ( \"Loaded {} lines\" , content . size ( ) ) ; // return joined return new StringReader ( Joiner . on ( ' ' ) . join ( content ) ) ; } catch ( SQLException e ) { throw new IllegalArgumentException ( \"Failed to load data from the database\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public QueryRunner getJdbcRunner ( ) { if ( dataSource == null ) { if ( ignore ) { logger . warn ( \"Could not load Jdbc Datasource!\" ) ; return null ; } throw new IllegalArgumentException ( \"Missing data source.\" ) ; } return new QueryRunner ( dataSource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inform { @link SearcherAware } about a new searcher . [CODESPLIT] private void inform ( String type , String name , Object o , SolrIndexSearcher searcher ) { if ( o instanceof SearcherAware ) { logger . info ( \"Informing searcher aware {} ({}) of field type {} about a new searcher.\" , type , o . getClass ( ) . getName ( ) , name ) ; try { ( ( SearcherAware ) o ) . inform ( searcher ) ; } catch ( IOException e ) { logger . error ( \"Failed to inform {} ({}) of field type {} about a new searcher.\" , type , o . getClass ( ) . getName ( ) , name , e ) ; throw new IllegalArgumentException ( \"Failed to inform about a new searcher.\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inform { @link SearcherAware } filter factories in a { @link TokenizerChain } about a new searcher . [CODESPLIT] private void inform ( String name , TokenizerChain tokenizers , SolrIndexSearcher searcher ) { for ( TokenFilterFactory factory : tokenizers . getTokenFilterFactories ( ) ) { inform ( \"token filter factory\" , name , factory , searcher ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookup data source . [CODESPLIT] public static DataSource getDataSource ( Map < ? , ? > config ) { String ignoreString = ( String ) config . remove ( JdbcReaderFactoryParams . IGNORE ) ; boolean ignore = ! \"false\" . equals ( ignoreString ) ; String dataSourceName = ( String ) config . remove ( JdbcReaderFactoryParams . DATASOURCE ) ; DataSource dataSource = null ; if ( dataSourceName != null ) { dataSource = jndiDataSource ( fixJndiName ( dataSourceName ) ) ; if ( dataSource == null ) { log . error ( \"Data source {} not found.\",   ataSourceName) ;  if ( ! ignore ) { throw new IllegalArgumentException ( \"No data source found.\" ) ; } } } else { log . error ( \"No data source configured.\" ) ; if ( ! ignore ) { throw new IllegalArgumentException ( \"No data source configured.\" ) ; } } return dataSource ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the database and lookups a { @linkplain DataSource } in JNDI . [CODESPLIT] private static DataSource jndiDataSource ( String jndiName ) { try { Context ctx = new InitialContext ( ) ; log . info ( \"Looking up data source {} in JNDI.\" , jndiName ) ; DataSource dataSource = ( DataSource ) ctx . lookup ( jndiName ) ; ctx . close ( ) ; return dataSource ; } catch ( NameNotFoundException e ) { return null ; } catch ( NamingException e ) { log . error ( \"JNDI error: {}.\" , e . getMessage ( ) ) ; throw new IllegalArgumentException ( \"JNDI error.\" , e ) ; } catch ( ClassCastException e ) { log . error ( \"The JNDI resource {} is no data source: {}.\" , jndiName , e . getMessage ( ) ) ; throw new IllegalArgumentException ( \"The JNDI resource is no data source.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the { @link JdbcReader } from configuration . [CODESPLIT] public static JdbcReader createFromSolrParams ( Map < String , String > config , String originalParamName ) { Preconditions . checkNotNull ( config ) ; // Set a fixed synonyms \"file\". // This \"file\" will be loaded from the database by the JdbcResourceLoader. if ( originalParamName != null ) { config . put ( originalParamName , JdbcResourceLoader . DATABASE ) ; } DataSource dataSource = JdbcDataSourceFactory . getDataSource ( config ) ; String sql = config . remove ( JdbcReaderFactoryParams . SQL ) ; String ignoreString = config . remove ( JdbcReaderFactoryParams . IGNORE ) ; boolean ignore = ! \"false\" . equals ( ignoreString ) ; return new SimpleJdbcReader ( dataSource , sql , ignore ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ITERABLES - complete [CODESPLIT] @ NonNull public static < T > Iterable < T > iterableOf ( final InstanceOf < T > type ) { return PrivateGenerate . FIXTURE . createMany ( type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "ARRAYS - complete [CODESPLIT] @ NonNull public static < T > T [ ] arrayOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( \"arrayOf\" ) ) ; return PrivateGenerate . manyAsArrayOf ( TypeToken . of ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "LISTS - complete [CODESPLIT] @ NonNull public static < T > List < T > listOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( \"listOf\" ) ) ; return PrivateGenerate . manyAsListOf ( TypeToken . of ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "COLLECTIONS - complete [CODESPLIT] @ NonNull public static < T > Collection < T > collectionOf ( final InstanceOf < T > typeToken , final InlineConstrainedGenerator < T > omittedValues ) { return PrivateGenerate . manyAsListOf ( typeToken , omittedValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO variations [CODESPLIT] @ NonNull public static < T > Set < T > setOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( \"setOf\" ) ) ; return PrivateGenerate . manyAsSetOf ( TypeToken . of ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO UT [CODESPLIT] @ NonNull public static < T > Set < T > setOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( \"setOf\" ) ) ; return PrivateGenerate . manyAsSetOf ( TypeToken . of ( type ) , omittedValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "queues : incomplete [CODESPLIT] @ NonNull public static < T > Queue < T > queueOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( \"queueOf\" ) ) ; return PrivateGenerate . manyAsQueueOf ( TypeToken . of ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO UT [CODESPLIT] @ NonNull public static < T > Queue < T > queueOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( \"queueOf\" ) ) ; return PrivateGenerate . manyAsQueueOf ( TypeToken . of ( type ) , omittedValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deques : incomplete [CODESPLIT] @ NonNull public static < T > Deque < T > dequeOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( \"dequeOf\" ) ) ; return PrivateGenerate . manyAsDequeOf ( TypeToken . of ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO UT [CODESPLIT] @ NonNull public static < T > Deque < T > dequeOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( \"dequeOf\" ) ) ; return PrivateGenerate . manyAsDequeOf ( TypeToken . of ( type ) , omittedValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sorted sets : incomplete [CODESPLIT] @ NonNull public static < T > SortedSet < T > sortedSetOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( \"sortedSetOf\" ) ) ; return PrivateGenerate . manyAsSortedSetOf ( TypeToken . of ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO UT [CODESPLIT] @ NonNull public static < T > SortedSet < T > sortedSetOf ( final Class < T > type , final InlineConstrainedGenerator < T > omittedValues ) { assertIsNotParameterized ( type , ErrorMessages . msgInline ( \"sortedSetOf\" ) ) ; return PrivateGenerate . manyAsSortedSetOf ( TypeToken . of ( type ) , omittedValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO variations and UT [CODESPLIT] @ NonNull public static < T , V > SortedMap < T , V > sortedMapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , \"generic key types are not allowed for this method.\" ) ; assertIsNotParameterized ( valueClass , \"generic value types are not allowed for this method.\" ) ; return PrivateGenerate . manyAsSortedMapBetween ( TypeToken . of ( keyClass ) , TypeToken . of ( valueClass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO variations [CODESPLIT] @ NonNull public static < T , V > Map < T , V > mapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , \"generic key types are not allowed for this method.\" ) ; assertIsNotParameterized ( valueClass , \"generic value types are not allowed for this method.\" ) ; return PrivateGenerate . manyAsMapBetween ( TypeToken . of ( keyClass ) , TypeToken . of ( valueClass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ optionals [CODESPLIT] @ NonNull public static < T > Optional < T > optional ( Class < T > type ) { return Optional . of ( Any . anonymous ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO rethink putting this into the Fixture class [CODESPLIT] static < T > List < T > manyAsListOf ( final TypeToken < T > typeToken , final InlineConstrainedGenerator < T > generator ) { final List < T > result = CollectionFactory . createList ( ) ; result . add ( any ( typeToken , generator ) ) ; result . add ( any ( typeToken , generator ) ) ; result . add ( any ( typeToken , generator ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO check case when new X<Integer > () . GetValue () and new X<String > () . GetValue () afterwards - does this work? [CODESPLIT] private Object generateFreshValueFor ( final Object proxy , final Method method , final TypeToken < ? > returnType ) { final Optional < Object > freshReturnValue = createReturnValue ( fixture , returnType ) ; if ( freshReturnValue . isPresent ( ) ) { methodsInvocationResultCache . setFor ( proxy , method , freshReturnValue . get ( ) ) ; } return freshReturnValue . orNull ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "todo add generics checks [CODESPLIT] @ NonNull public static < T > List < T > listOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( \"listOf\" ) ) ; return io . vavr . collection . List . ofAll ( Any . listOf ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////// arrays [CODESPLIT] @ NonNull public static < T > Array < T > arrayOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( \"arrayOf\" ) ) ; return Array . ofAll ( Any . listOf ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////// hashsets [CODESPLIT] @ NonNull public static < T > HashSet < T > hashSetOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( \"hashSetOf\" ) ) ; return HashSet . ofAll ( Any . listOf ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////// tree sets [CODESPLIT] @ NonNull public static < T > TreeSet < T > treeSetOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( \"treeSetOf\" ) ) ; return TreeSet . ofAll ( ( Iterable ) Any . iterableOf ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////// sets [CODESPLIT] @ NonNull public static < T > Set < T > setOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( \"setOf\" ) ) ; return hashSetOf ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///// sorted sets [CODESPLIT] @ NonNull public static < T > SortedSet < T > sortedSetOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( \"sortedSetOf\" ) ) ; return treeSetOf ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////// hash maps [CODESPLIT] @ NonNull public static < T , V > HashMap < T , V > hashMapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , \"generic key types are not allowed for this method.\" ) ; assertIsNotParameterized ( valueClass , \"generic value types are not allowed for this method.\" ) ; return HashMap . ofAll ( Any . mapBetween ( keyClass , valueClass ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "///////////////////////////// maps [CODESPLIT] @ NonNull public static < T , V > Map < T , V > mapBetween ( final Class < T > keyClass , final Class < V > valueClass ) { assertIsNotParameterized ( keyClass , \"generic key types are not allowed for this method.\" ) ; assertIsNotParameterized ( valueClass , \"generic value types are not allowed for this method.\" ) ; return hashMapBetween ( keyClass , valueClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "////////////////// queues [CODESPLIT] @ NonNull public static < T > Queue < T > queueOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( \"queueOf\" ) ) ; return Queue . ofAll ( Any . queueOf ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "options [CODESPLIT] @ NonNull public static < T > Option < T > option ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( \"option\" ) ) ; return Option . of ( Any . instanceOf ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eithers - left [CODESPLIT] @ NonNull public static < T , U > Either < T , U > left ( final Class < T > leftType ) { assertIsNotParameterized ( leftType , msgInline ( \"left\" ) ) ; return Either . left ( Any . instanceOf ( leftType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "eithers - right [CODESPLIT] @ NonNull public static < T , U > Either < T , U > right ( final Class < U > rightType ) { assertIsNotParameterized ( rightType , msgInline ( \"right\" ) ) ; return Either . right ( Any . instanceOf ( rightType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "validations - failures [CODESPLIT] @ NonNull public static < T , U > Validation < T , U > validationFailed ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( \"validationFailed\" ) ) ; return Validation . invalid ( Any . instanceOf ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "validations - successful [CODESPLIT] @ NonNull public static < T , U > Validation < T , U > validationSuccess ( final Class < U > type ) { assertIsNotParameterized ( type , msgInline ( \"validationSuccess\" ) ) ; return Validation . valid ( Any . instanceOf ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "try - successful [CODESPLIT] @ NonNull public static < T > Try < T > trySuccess ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( \"trySuccess\" ) ) ; return Try . success ( Any . instanceOf ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a database to further execute SQL commands [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public boolean connectJdbcOnWithUrlAndDriverAndUsernameAndPassword ( String dataBaseId , String url , String driverClassName , String username , String password ) throws ReflectiveOperationException { SimpleDriverDataSource dataSource = new SimpleDriverDataSource ( ) ; dataSource . setUrl ( url ) ; dataSource . setDriverClass ( ( Class < Driver > ) Class . forName ( driverClassName ) ) ; dataSource . setUsername ( username ) ; dataSource . setPassword ( password ) ; this . templateMap . put ( dataBaseId , new JdbcTemplate ( dataSource ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Simply runs a SQL command used for udpates inserts which the result doesn t matter . [CODESPLIT] public boolean runInTheSql ( String database , final String sql ) { getDatabaseJdbcTemplate ( database ) . update ( sql ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Used generally when the result is assigned to a variable [CODESPLIT] public String queryInWithSql ( String database , String sql ) { JdbcTemplate template = getDatabaseJdbcTemplate ( database ) ; if ( sql != null && ! sql . trim ( ) . toUpperCase ( ) . startsWith ( JdbcFixture . SELECT_COMMAND_PREFIX ) ) { return Objects . toString ( template . update ( sql ) ) ; } List < String > results = template . queryForList ( sql , String . class ) ; if ( results == null || results . isEmpty ( ) ) { return null ; } return results . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interprets a strongly - typed number array to array of booleans . If a value found in the array is greater than 0 return true false otherwise . [CODESPLIT] public boolean [ ] asBoolArray ( ) { boolean [ ] retval ; UBArray array = asArray ( ) ; switch ( array . getStrongType ( ) ) { case Int8 : { byte [ ] data = ( ( UBInt8Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int16 : { short [ ] data = ( ( UBInt16Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int32 : { int [ ] data = ( ( UBInt32Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Int64 : { long [ ] data = ( ( UBInt64Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Float32 : { float [ ] data = ( ( UBFloat32Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } case Float64 : { double [ ] data = ( ( UBFloat64Array ) array ) . getValues ( ) ; retval = new boolean [ data . length ] ; for ( int i = 0 ; i < data . length ; i ++ ) { retval [ i ] = data [ i ] > 0 ; } break ; } default : throw new RuntimeException ( \"not an int32[] type\" ) ; } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a query which returns all rows in the entity table that match the fields of the example object having values other than the defaults . [CODESPLIT] public Query < T > byExample ( T obj ) { if ( obj != null ) { return dao . getTableHelper ( ) . buildFilter ( this , obj ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Convenience methods for comparing equality of each wrapper type [CODESPLIT] public Query < T > eq ( Column colName , Boolean param ) { Integer sqlValue = BooleanConverter . GET . toSql ( param ) ; where . append ( \" AND \" + colName + \"=?\" ) ; params . add ( BooleanConverter . GET . toString ( sqlValue ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upgrades the table that represents the associated entity . This will typically be an ALTER TABLE statement . [CODESPLIT] protected void onUpgrade ( final SQLiteDatabase db , final int oldVersion , final int newVersion ) { db . execSQL ( upgradeSql ( oldVersion , newVersion ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Backs up the current table to a CSV file . [CODESPLIT] public boolean backup ( SQLiteDatabase db , Context ctx , String suffix ) { try { new CsvTableWriter ( this ) . dumpToCsv ( ctx , db , suffix ) ; } catch ( SQLException e ) { if ( e . getMessage ( ) . contains ( \"no such table\" ) ) { Log . w ( TAG , \"Table \" + this . getTableName ( ) + \" doesn't exist. This is expected if the table is new in this db version.\" ) ; } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restores a table from a text file . [CODESPLIT] public void restore ( SQLiteDatabase db , Context ctx , String suffix ) { new CsvTableReader ( this ) . importFromCsv ( ctx , db , suffix ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Cursor wrapper methods which bind to primitive type columns and return the corresponding wrapper type which may be null [CODESPLIT] protected byte [ ] getBlobOrNull ( Cursor c , int col ) { return c . isNull ( col ) ? null : c . getBlob ( col ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The default content for this Activity has a TextView that is shown when the list is empty . If you would like to change the text call this method to supply the text it should use . [CODESPLIT] public void setEmptyText ( CharSequence emptyText ) { if ( mListView != null ) { View emptyView = mListView . getEmptyView ( ) ; if ( emptyText instanceof TextView ) { ( ( TextView ) emptyView ) . setText ( emptyText ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dumps a database table to a CSV file in the default location . Returns the number of rows written to the file . [CODESPLIT] public int dumpToCsv ( Context ctx , SQLiteDatabase db , String suffix ) throws FileNotFoundException { int numRowsWritten = 0 ; Cursor c ; String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; c = db . query ( th . getTableName ( ) , null , null , null , null , null , null ) ; FileOutputStream fos ; fos = ctx . openFileOutput ( filename , 0 ) ; PrintWriter printWriter = new PrintWriter ( fos ) ; String headerRow = buildHeaderRow ( ) ; printWriter . println ( headerRow ) ; for ( boolean hasItem = c . moveToFirst ( ) ; hasItem ; hasItem = c . moveToNext ( ) ) { String csv = buildCsvRow ( c ) ; printWriter . println ( csv ) ; numRowsWritten ++ ; } printWriter . flush ( ) ; printWriter . close ( ) ; return numRowsWritten ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an expression to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final Class < T > constructorClass , final String expression ) { return add ( ( String ) null , constructorClass , expression ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an expression to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final String lhsStatement , final Class < T > constructorClass , final String expression ) { StringBuilder itemBuilder = new StringBuilder ( ) ; if ( lhsStatement != null ) { itemBuilder . append ( lhsStatement ) ; itemBuilder . append ( \" \" ) ; } itemBuilder . append ( \"NEW \" ) ; itemBuilder . append ( constructorClass . getName ( ) ) ; itemBuilder . append ( \"(\" ) ; itemBuilder . append ( expression ) ; itemBuilder . append ( \")\" ) ; items . add ( itemBuilder . toString ( ) ) ; return builder ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds expressions to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final Class < T > constructorClass , final String ... expressions ) { return add ( ( String ) null , constructorClass , expressions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds expressions to this Select Clause with support for Constructor Expressions . [CODESPLIT] public < T > QueryBuilder add ( final String lhsStatement , final Class < T > constructorClass , final String ... expressions ) { return add ( lhsStatement , constructorClass , StringUtils . join ( expressions ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a { @link String } for a CSV column enclosed in double quotes if required . [CODESPLIT] public static String escapeCsv ( String str ) { if ( str == null ) return \"\" ; if ( containsNone ( str , CSV_SEARCH_CHARS ) ) return str ; StringWriter out = new StringWriter ( ) ; out . write ( QUOTE ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char c = str . charAt ( i ) ; if ( c == QUOTE ) out . write ( QUOTE ) ; out . write ( c ) ; } out . write ( QUOTE ) ; return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes enclosing quotes and unescapes double quotes [CODESPLIT] public static String unescapeCsv ( String str ) { if ( str == null ) return null ; if ( ! ( str . charAt ( 0 ) == QUOTE && str . charAt ( str . length ( ) - 1 ) == QUOTE ) ) return str ; String quoteless = str . substring ( 1 , str . length ( ) - 1 ) ; return quoteless . replace ( QUOTE_STR + QUOTE_STR , QUOTE_STR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns values from a CSV String . [CODESPLIT] public static List < String > getValues ( String csvRow ) { List < String > values = new ArrayList < String > ( ) ; StringReader in = new StringReader ( csvRow ) ; String value ; try { value = nextValue ( in ) ; while ( true ) { values . add ( value ) ; value = nextValue ( in ) ; } } catch ( IOException e ) { // TODO handle case of final null value better? if ( csvRow . lastIndexOf ( ' ' ) == csvRow . length ( ) - 1 ) values . add ( null ) ; return values ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the next value from a { @link StringReader } . [CODESPLIT] public static String nextValue ( StringReader in ) throws IOException { StringWriter w = new StringWriter ( ) ; boolean inQuotedValue = false ; boolean openQuote = false ; int c = in . read ( ) ; if ( c == QUOTE ) inQuotedValue = true ; else if ( c == DELIMITER ) { return null ; } else if ( c >= 0 ) { w . write ( c ) ; } else { throw new IOException ( \"End of line reached\" ) ; } c = in . read ( ) ; while ( c >= 0 ) { if ( c == QUOTE ) { if ( inQuotedValue ) { if ( openQuote ) { openQuote = false ; w . write ( QUOTE ) ; } else { openQuote = true ; } } else // invalid return w . toString ( ) ; } else if ( c == DELIMITER ) { if ( openQuote ) return w . toString ( ) ; else if ( inQuotedValue ) w . write ( c ) ; else // invalid return w . toString ( ) ; } else w . write ( c ) ; c = in . read ( ) ; } return w . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a CSV row containing name = value pairs . [CODESPLIT] public static Map < String , String > getAsMap ( String csvPairs ) { Map < String , String > map = new HashMap < String , String > ( ) ; String [ ] pairs = csvPairs . split ( \",\" ) ; for ( String pair : pairs ) { String [ ] split = pair . split ( \"=\" ) ; map . put ( split [ 0 ] , split [ 1 ] ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String containing a comma - separated list of name = value pairs from a map . [CODESPLIT] public static String mapToCsv ( Map < String , String > map ) { StringBuilder sb = new StringBuilder ( ) ; for ( String key : map . keySet ( ) ) { sb . append ( \",\" ) ; String val = map . get ( key ) ; sb . append ( key + \"=\" + val ) ; } return sb . toString ( ) . substring ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins items of a text list separating items by comma . [CODESPLIT] public static String join ( final List < String > list ) { // zero, empty or one element if ( list == null ) { return null ; } else if ( list . size ( ) == 0 ) { return \"\" ; } else if ( list . size ( ) == 1 ) { return list . get ( 0 ) ; } // two or more elements final StringBuilder builder = new StringBuilder ( ) ; for ( String item : list ) { if ( builder . length ( ) > 0 ) { builder . append ( \", \" ) ; } builder . append ( item ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Joins items of a text array separating items by comma . [CODESPLIT] public static String join ( final String [ ] list ) { // zero, empty or one element if ( list == null ) { return null ; } else if ( list . length == 0 ) { return \"\" ; } else if ( list . length == 1 ) { return list [ 0 ] ; } // two or more elements final StringBuilder builder = new StringBuilder ( ) ; for ( String item : list ) { if ( builder . length ( ) > 0 ) { builder . append ( \", \" ) ; } builder . append ( item ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders this object as { @literal JPQL } fragment . [CODESPLIT] public String render ( ) { StringBuilder builder = new StringBuilder ( column ) ; if ( order != null ) { builder . append ( \" \" ) . append ( getOrder ( ) . name ( ) ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Populate the model of a database and its associated tables from a file in support of incremental compilation . [CODESPLIT] public static DatabaseModel readFromIndex ( BufferedReader reader , ProcessorLogger logger ) throws IOException { String dbInfo = reader . readLine ( ) ; logger . info ( dbInfo ) ; Map < String , String > props = CsvUtils . getAsMap ( dbInfo ) ; String dbName = props . get ( \"dbName\" ) ; int dbVersion = Integer . parseInt ( props . get ( \"dbVersion\" ) ) ; String helperClass = props . get ( \"helperClass\" ) ; DatabaseModel dbModel = new DatabaseModel ( dbName , dbVersion , helperClass ) ; // read TableHelpers List < String > tables = new ArrayList < String > ( ) ; String th = reader . readLine ( ) ; while ( th != null && ! th . equals ( StormEnvironment . END_DATABASE ) ) { tables . add ( th ) ; th = reader . readLine ( ) ; } dbModel . tableHelpers = tables ; return dbModel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the database info and associated tables to a file in support of incremental compilation . [CODESPLIT] public void writeToIndex ( PrintWriter out ) { out . println ( StormEnvironment . BEGIN_DATABASE ) ; Map < String , String > dbMap = new HashMap < String , String > ( ) ; dbMap . put ( \"dbName\" , this . getDbName ( ) ) ; dbMap . put ( \"dbVersion\" , String . valueOf ( this . getDbVersion ( ) ) ) ; dbMap . put ( \"helperClass\" , this . getQualifiedClassName ( ) ) ; String dbInfo = CsvUtils . mapToCsv ( dbMap ) ; out . println ( dbInfo ) ; // write TableHelpers for ( String th : this . tableHelpers ) { out . println ( th ) ; } out . println ( StormEnvironment . END_DATABASE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verifies that the entity has exactly one id field of type long . [CODESPLIT] private void inspectId ( ) { if ( entityModel . getIdField ( ) == null ) { // Default to field named \"id\" List < FieldModel > fields = entityModel . getFields ( ) ; for ( FieldModel f : fields ) { if ( EntityModel . DEFAULT_ID_FIELD . equals ( f . getFieldName ( ) ) ) { entityModel . setIdField ( f ) ; } } } FieldModel idField = entityModel . getIdField ( ) ; if ( idField != null && \"long\" . equals ( idField . getJavaType ( ) ) ) { return ; } else { abort ( \"Entity must contain a field named id or annotated with @Id of type long\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trying to get Class<? > from an annotation raises an exception see http : // stackoverflow . com / questions / 7687829 / java - 6 - annotation - processing - getting - a - class - from - an - annotation [CODESPLIT] private static TypeMirror getBaseDaoTypeMirror ( Entity entity ) { if ( entity != null ) { try { entity . baseDaoClass ( ) ; } catch ( MirroredTypeException mte ) { return mte . getTypeMirror ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a BaseDaoModel from the class passed as attribute baseDaoClass of the annotation Entity [CODESPLIT] private static BaseDaoModel getBaseDaoClass ( Entity entity ) { String qualifiedName = SQLiteDao . class . getName ( ) ; TypeMirror typeMirror = getBaseDaoTypeMirror ( entity ) ; if ( typeMirror != null ) qualifiedName = typeMirror . toString ( ) ; return new BaseDaoModel ( qualifiedName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Morph bind type like INT == > Int so it can be used in a Cursor getXxx method name . Never called at runtime . [CODESPLIT] public String getBindType ( ) { String bindType = getConverter ( ) . getBindType ( ) . name ( ) ; return bindType . charAt ( 0 ) + bindType . toLowerCase ( ) . substring ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Capitalizes the first letter to create a valid getter / setter name . [CODESPLIT] private String capFirst ( String anyName ) { // obscure Java convention: // if second letter capitalized, leave it alone if ( anyName . length ( ) > 1 ) if ( anyName . charAt ( 1 ) >= ' ' && anyName . charAt ( 1 ) <= ' ' ) return anyName ; String capFirstLetter = anyName . substring ( 0 , 1 ) . toUpperCase ( ) ; return capFirstLetter + anyName . substring ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to import a database table from a CSV file in the default location . [CODESPLIT] public int importFromCsv ( Context ctx , SQLiteDatabase db , String suffix ) { String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; FileInputStream fileInputStream ; try { fileInputStream = ctx . openFileInput ( filename ) ; return importFromCsv ( db , fileInputStream ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to import a database table from an { @link InputStream } formatted as a CSV file . Does all inserts in a single transaction for efficiency and so that all inserts will succeed or fail together . [CODESPLIT] public int importFromCsv ( SQLiteDatabase db , InputStream is ) { int numInserts = 0 ; db . beginTransaction ( ) ; insertHelper = new DatabaseUtils . InsertHelper ( db , th . getTableName ( ) ) ; try { InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader reader = new BufferedReader ( isr ) ; String headerRow = reader . readLine ( ) ; String csvRow = reader . readLine ( ) ; while ( csvRow != null ) { long rowId = parseAndInsertRow ( csvRow ) ; if ( rowId == - 1L ) { throw new RuntimeException ( \"Error after row \" + numInserts ) ; } numInserts ++ ; csvRow = reader . readLine ( ) ; } db . setTransactionSuccessful ( ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { db . endTransaction ( ) ; } return numInserts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the values in a CSV row map them to the table column order and insert . Uses { @link InsertHelper } so it may be called repeatedly within a transaction for max performance . [CODESPLIT] private long parseAndInsertRow ( String csvRow ) { List < String > textValues = CsvUtils . getValues ( csvRow ) ; insertHelper . prepareForInsert ( ) ; String [ ] rowValues = textValues . toArray ( new String [ textValues . size ( ) ] ) ; th . bindRowValues ( insertHelper , rowValues ) ; return insertHelper . execute ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls { @link TableHelper#onCreate ( SQLiteDatabase ) } for each TableHelper . [CODESPLIT] @ Override public void onCreate ( SQLiteDatabase db ) { for ( TableHelper th : getTableHelpers ( ) ) { th . onCreate ( db ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a method on each TableHelper depending on the { @link UpgradeStrategy } . In order to prevent recursive calls to getDatabase () this method must pass the db parameter through to any other methods that need it . [CODESPLIT] @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { switch ( getUpgradeStrategy ( ) ) { case DROP_CREATE : this . dropAndCreate ( db ) ; break ; case BACKUP_RESTORE : this . backupAndRestore ( this . getContext ( ) , db ) ; break ; case UPGRADE : this . upgrade ( db , oldVersion , newVersion ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls { @link TableHelper#onUpgrade ( SQLiteDatabase int int ) } for each TableHelper . Override this method to implement your own upgrade strategy . [CODESPLIT] public void upgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { for ( TableHelper th : getTableHelpers ( ) ) { th . onUpgrade ( db , oldVersion , newVersion ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Backs up all tables to CSV drops and recreates them then restores them from CSV . By default creates CSV filenames with no suffix . You could override this method to supply a timestamp suffix ( make sure it s the same for both backup and restore ) but beware that this could cause backup files to proliferate . Ideally this method should clean up backup files after the database has been restored . [CODESPLIT] public void backupAndRestore ( Context ctx , SQLiteDatabase db ) { if ( backupAllTablesToCsv ( ctx , db , null ) ) { dropAndCreate ( db ) ; restoreAllTablesFromCsv ( ctx , db , null ) ; } else { throw new RuntimeException ( \"Backup of \" + getDatabaseName ( ) + \" failed, aborting upgrade\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Backup all tables to CSV files one per table [CODESPLIT] public boolean backupAllTablesToCsv ( Context ctx , SQLiteDatabase db , String suffix ) { boolean allSucceeded = true ; for ( TableHelper table : getTableHelpers ( ) ) { allSucceeded &= table . backup ( db , ctx , suffix ) ; } return allSucceeded ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restore all tables from CSV files one per table [CODESPLIT] public void restoreAllTablesFromCsv ( Context ctx , SQLiteDatabase db , String suffix ) { for ( TableHelper table : getTableHelpers ( ) ) { table . restore ( db , ctx , suffix ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the current model state from a file in support of incremental compilation . This is necessary because the annotation processor has access to only classes which have been annotated ( and any resulting generated classes on subsequent rounds ) but DatabaseHelper classes aren t available when doing incremental compilation on a new @Entity . [CODESPLIT] void readIndex ( Filer filer ) { StandardLocation location = StandardLocation . SOURCE_OUTPUT ; FileObject indexFile ; try { indexFile = filer . getResource ( location , \"com.turbomanage.storm\" , ENV_FILE ) ; logger . info ( \"Reading index \" + indexFile . toUri ( ) ) ; // indexFile.openReader() not implemented on all platforms Reader fileReader = new InputStreamReader ( indexFile . openInputStream ( ) ) ; BufferedReader reader = new BufferedReader ( fileReader ) ; String line = reader . readLine ( ) ; // BEGIN_CONVERTERS line = reader . readLine ( ) ; while ( line != null && ! line . startsWith ( END_CONVERTERS ) ) { ConverterModel converter = ConverterModel . readFromIndex ( line , logger ) ; this . addConverter ( converter ) ; line = reader . readLine ( ) ; } line = reader . readLine ( ) ; while ( line != null && line . startsWith ( BEGIN_DATABASE ) ) { DatabaseModel dbModel = DatabaseModel . readFromIndex ( reader , logger ) ; this . addDatabase ( dbModel ) ; line = reader . readLine ( ) ; } reader . close ( ) ; } catch ( IOException e ) { // gulp--only way to catch not yet existing file on first run } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write the current model state to a file in support of incremental compilation . [CODESPLIT] void writeIndex ( Filer filer ) { StandardLocation location = StandardLocation . SOURCE_OUTPUT ; FileObject indexFile ; try { indexFile = filer . createResource ( location , \"com.turbomanage.storm\" , ENV_FILE ) ; OutputStream fos = indexFile . openOutputStream ( ) ; PrintWriter out = new PrintWriter ( fos ) ; // Dump converters out . println ( BEGIN_CONVERTERS ) ; for ( ConverterModel converter : converters ) { converter . writeToIndex ( out ) ; } out . println ( END_CONVERTERS ) ; // Dump databases for ( DatabaseModel dbModel : dbModels . values ( ) ) { dbModel . writeToIndex ( out ) ; } out . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register a custom { @link TypeConverter } for a given data ( field ) type . This method is called at compile time by the annotation processor . In order for the TypeConverter to be visible it must be in a jar on the client project s annotation factory classpath . [CODESPLIT] public boolean addConverter ( ConverterModel converter ) { if ( converters . contains ( converter ) ) return true ; for ( String type : converter . getConvertibleTypes ( ) ) { // TODO what if already put the 1st type? if ( typeMap . containsKey ( type ) && ! typeMap . get ( type ) . equals ( converter ) ) return false ; typeMap . put ( type , converter ) ; } converters . add ( converter ) ; logger . info ( \"Added \" + converter . getQualifiedClassName ( ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a JPA Query with all previously specified parameters added . [CODESPLIT] public Query createQuery ( final EntityManager manager ) { if ( manager == null ) { throw new NullPointerException ( \"Entity Manager required\" ) ; } final Query query = manager . createQuery ( render ( ) ) ; for ( Parameter < ? > parameter : parameters ) { parameter . apply ( query ) ; } return query ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a JPA TypedQuery with all previously specified parameters added . [CODESPLIT] public < T > TypedQuery < T > createQuery ( final EntityManager manager , Class < T > type ) { if ( manager == null ) { throw new NullPointerException ( \"Entity Manager required\" ) ; } TypedQuery < T > result = manager . createQuery ( render ( ) , type ) ; for ( Parameter < ? > parameter : parameters ) { parameter . apply ( result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given parameter to the builder . All parameters will added to the JPA Query returned by a call to { @link #createQuery ( EntityManager ) } or { @link #createQuery ( EntityManager Class ) } . [CODESPLIT] public QueryBuilder setParameter ( final String name , final Calendar value , TemporalType temporalType ) { return setParameter ( new ParameterCalendar ( name , value , temporalType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given parameter to the builder . All parameters will added to the JPA Query returned by a call to { @link #createQuery ( EntityManager ) } or { @link #createQuery ( EntityManager Class ) } . [CODESPLIT] public QueryBuilder setParameter ( final String name , final Date value , final TemporalType temporalType ) { return setParameter ( new ParameterDate ( name , value , temporalType ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the given parameter to the builder . All parameters will added to the JPA Query returned by a call to { @link #createQuery ( EntityManager ) } or { @link #createQuery ( EntityManager Class ) } . [CODESPLIT] public QueryBuilder setParameter ( final String name , final Object value ) { return setParameter ( new ParameterObject ( name , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds given parameter to the builder . All parameters will added to the JPA Query returned by a call to { @link #createQuery ( EntityManager ) } or { @link #createQuery ( EntityManager Class ) } . [CODESPLIT] public QueryBuilder setParameter ( final Parameter < ? > parameter ) { if ( parent == null ) { parameters . add ( parameter ) ; } else { parent . setParameter ( parameter ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all given parameters to the builder . All parameters will added to the JPA Query returned by a call to { @link #createQuery ( EntityManager ) } or { @link #createQuery ( EntityManager Class ) } . [CODESPLIT] public QueryBuilder setParameters ( final List < Parameter < ? > > parameters ) { if ( parent == null ) { this . parameters . addAll ( parameters ) ; } else { parent . setParameters ( parameters ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders this object as JPQL query string . [CODESPLIT] public String render ( ) { StringBuilder query = new StringBuilder ( ) ; if ( ! select . isEmpty ( ) ) { query . append ( \"SELECT \" ) ; query . append ( StringUtils . join ( select . items ) ) ; } if ( ! deleteFrom . isEmpty ( ) ) { query . append ( \"DELETE FROM \" ) ; query . append ( deleteFrom . item ) ; } if ( ! update . isEmpty ( ) ) { query . append ( \"UPDATE \" ) ; query . append ( update . item ) ; if ( ! set . isEmpty ( ) ) { query . append ( \" SET \" ) ; query . append ( StringUtils . join ( set . items ) ) ; } } if ( ! from . isEmpty ( ) ) { query . append ( \" FROM \" ) ; query . append ( StringUtils . join ( from . items ) ) ; } if ( ! where . isEmpty ( ) ) { query . append ( \" WHERE \" ) ; query . append ( where . render ( ) ) ; } if ( ! group . isEmpty ( ) ) { query . append ( \" GROUP BY \" ) ; query . append ( StringUtils . join ( group . items ) ) ; } if ( order . isEmpty ( ) == false ) { query . append ( \" ORDER BY \" ) ; query . append ( StringUtils . join ( order . items ) ) ; } return query . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes a single row by ID . Returns the number of rows deleted or 0 if unsuccessful . [CODESPLIT] public int delete ( Long id ) { if ( id != null ) { return getWritableDb ( ) . delete ( th . getTableName ( ) , th . getIdCol ( ) + \"=?\" , new String [ ] { id . toString ( ) } ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a single object by ID or null if no match found . If more than one match is found throws { @link TooManyResultsException } . [CODESPLIT] public T get ( Long id ) { return load ( ) . eq ( th . getIdCol ( ) , id ) . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a row for the provided entity . If the entity s id is the default long ( 0 ) the database generates an id and populates the entity s ID field . Returns the generated ID or - 1 if error . [CODESPLIT] public long insert ( T obj ) { ContentValues cv = th . getEditableValues ( obj ) ; if ( th . getId ( obj ) == 0 ) { // the default, remove from ContentValues to allow autoincrement cv . remove ( th . getIdCol ( ) . toString ( ) ) ; } long id = getWritableDb ( ) . insertOrThrow ( th . getTableName ( ) , null , cv ) ; th . setId ( obj , id ) ; return id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Efficiently insert a collection of entities using { @link InsertHelper } . [CODESPLIT] public long insertMany ( Iterable < T > many ) { long numInserted = 0 ; InsertHelper insertHelper = new DatabaseUtils . InsertHelper ( getWritableDb ( ) , th . getTableName ( ) ) ; getWritableDb ( ) . beginTransaction ( ) ; try { for ( T obj : many ) { ContentValues cv = th . getEditableValues ( obj ) ; if ( th . getId ( obj ) == 0 ) { // the default, remove from ContentValues to allow autoincrement cv . remove ( th . getIdCol ( ) . toString ( ) ) ; } long id = insertHelper . insert ( cv ) ; if ( id == - 1 ) return - 1 ; numInserted ++ ; } getWritableDb ( ) . setTransactionSuccessful ( ) ; } finally { getWritableDb ( ) . endTransaction ( ) ; } return numInserted ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert or update . [CODESPLIT] public long save ( T obj ) { if ( th . getId ( obj ) == 0 ) { return insert ( obj ) ; } long updated = update ( obj ) ; if ( updated == 1 ) { return 0 ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update all columns for the row having the ID matching the provided entity s ID . [CODESPLIT] public long update ( T obj ) { ContentValues cv = th . getEditableValues ( obj ) ; Long id = th . getId ( obj ) ; int numRowsUpdated = getWritableDb ( ) . update ( th . getTableName ( ) , cv , th . getIdCol ( ) + \"=?\" , new String [ ] { id . toString ( ) } ) ; return numRowsUpdated ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method queries the entity table using the provided WHERE clause and parameters and returns a { @link Cursor } . [CODESPLIT] public Cursor query ( String where , String [ ] params ) { return query ( where , params , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method queries the entity table using the provided WHERE clause and parameters and returns a { @link Cursor } . [CODESPLIT] public Cursor query ( String where , String [ ] params , String orderBy ) { return getReadableDb ( ) . query ( th . getTableName ( ) , null , where , params , null , null , orderBy ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts all rows in a { @link Cursor } to a List of objects . [CODESPLIT] public List < T > asList ( Cursor c ) { // TODO consider returning Iterable<T> instead try { ArrayList < T > resultList = new ArrayList < T > ( ) ; for ( boolean hasItem = c . moveToFirst ( ) ; hasItem ; hasItem = c . moveToNext ( ) ) { T obj = th . newInstance ( c ) ; resultList . add ( obj ) ; } return resultList ; } finally { c . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @link Cursor } to an object . If there is more than one row in the Cursor throws { @link TooManyResultsException } . [CODESPLIT] public T asObject ( Cursor c ) { try { if ( c . getCount ( ) == 1 ) { c . moveToFirst ( ) ; return th . newInstance ( c ) ; } else if ( c . getCount ( ) > 1 ) { throw new TooManyResultsException ( \"Cursor returned \" + c . getCount ( ) + \" rows\" ) ; } return null ; } finally { c . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associate given { @link QueryBuilder } with this object and all of its items . [CODESPLIT] void setBuilder ( final QueryBuilder builder ) { super . setBuilder ( builder ) ; for ( WhereItem item : items ) { item . setBuilder ( builder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a { @link WhereItem } to this object . [CODESPLIT] public WhereItem add ( final WhereItem item ) { items . add ( item ) ; item . setBuilder ( builder ( ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an { @literal SQL } { @code AND } clause . [CODESPLIT] public WhereAnd and ( ) { final WhereAnd and = new WhereAnd ( builder ( ) ) ; items . add ( and ) ; return and ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an { @literal SQL } { @code OR } clause . [CODESPLIT] public WhereOr or ( ) { final WhereOr or = new WhereOr ( builder ( ) ) ; items . add ( or ) ; return or ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an { @literal SQL } { @code IN } predicate . [CODESPLIT] public < V extends Object > WhereItems in ( final String expression , final Collection < V > collection ) { items . add ( new WhereIn ( builder ( ) , expression , false , collection ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an { @literal SQL } { @code IN } predicate . [CODESPLIT] public < V extends Object > WhereItems in ( final String expression , final V ... array ) { items . add ( new WhereIn ( builder ( ) , expression , false , array ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a { @code NOT IN } predicate . [CODESPLIT] public < V extends Object > WhereItems notIn ( final String expression , final Collection < V > collection ) { items . add ( new WhereIn ( builder ( ) , expression , true , collection ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a NOT IN predicate . [CODESPLIT] public < V extends Object > WhereItems notIn ( final String expression , final V ... array ) { items . add ( new WhereIn ( builder ( ) , expression , true , array ) ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a sub - query predicate . [CODESPLIT] public QueryBuilder subquery ( final String lhsPredicate ) { final WhereSubquery subquery = new WhereSubquery ( builder ( ) , lhsPredicate ) ; items . add ( subquery ) ; return subquery . getQueryBuilder ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean context ( ) { int myid = getAgent ( ) . getId ( ) ; Token2 goal = ( Token2 ) getGoal ( ) ; return ( myid == goal . getAgent ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * package [CODESPLIT] void log ( ) { Board board = ( ( Player ) getAgent ( ) ) . getBoard ( ) ; Player . out . println ( \"Moving disc \" + solve . disc + \" from pin \" + solve . src + \" to \" + solve . dest ) ; board . move ( solve . src , solve . dest ) ; Player . out . println ( board . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes the next intentions stack active using a round robin scheme . [CODESPLIT] Stack255 nextActiveStack ( ) { activeStack = ( activeStack + 1 ) % stacks . size ( ) ; return ( Stack255 ) stacks . get ( activeStack ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an empty intentions stack . Creates a new intentions stack and adds it to the list of stacks if needed . [CODESPLIT] Stack255 getEmptyIntentionStack ( ) { // If the active stack is empty then return it (don't check other stacks) if ( ! stacks . isEmpty ( ) && getActiveStack ( ) . isEmpty ( ) ) { return getActiveStack ( ) ; } // else create an empty stack, add it to the list ot stacks, and return it Stack255 stack = new Stack255 ( ( byte ) 8 , ( byte ) 2 ) ; stacks . push ( stack ) ; return stack ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add the set of bindings for a given plan to this store . Any previously stored bindings for this plan will be replaced . [CODESPLIT] public void add ( Plan plan , Set < Belief > planBindings ) { if ( plan == null ) { return ; } // remove any old bindings, making sure to decrement the cached size if ( this . bindings . containsKey ( plan ) ) { Set < Belief > oldBindings = this . bindings . remove ( plan ) ; if ( oldBindings == null || oldBindings . isEmpty ( ) ) { cachedsize -- ; } else { cachedsize -= oldBindings . size ( ) ; } } // add this binding and update the cached size this . bindings . put ( plan , planBindings ) ; if ( planBindings == null || planBindings . isEmpty ( ) ) { cachedsize ++ ; } else { cachedsize += planBindings . size ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects a plan instance from the set of plan bindings using the given policy . [CODESPLIT] public Plan selectPlan ( PlanSelectionPolicy policy ) { Plan plan = null ; int index = 0 ; switch ( policy ) { case FIRST : case LAST : Plan [ ] plans = bindings . keySet ( ) . toArray ( new Plan [ 0 ] ) ; plan = ( policy == PlanSelectionPolicy . FIRST ) ? plans [ 0 ] : plans [ plans . length - 1 ] ; index = ( policy == PlanSelectionPolicy . FIRST ) ? 0 : plans . length - 1 ; setPlanVariables ( plan . getAgent ( ) , plan , bindings . get ( plan ) , index ) ; break ; case RANDOM : plan = selectPlanAtRandom ( ) ; break ; default : // TODO: ignore remaining polic break ; } return plan ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selects a plan instance at random from the set of plan bindings . [CODESPLIT] private Plan selectPlanAtRandom ( ) { Plan plan = null ; Set < Belief > vars = null ; int index = rand . nextInt ( size ( ) ) ; int idx = 0 ; boolean bindingsExist = false ; for ( Plan p : bindings . keySet ( ) ) { vars = bindings . get ( p ) ; bindingsExist = ( vars != null && ! vars . isEmpty ( ) ) ; idx += bindingsExist ? vars . size ( ) : 1 ; if ( idx > index ) { plan = p ; if ( bindingsExist ) { index = index - ( idx - vars . size ( ) ) ; setPlanVariables ( plan . getAgent ( ) , plan , vars , index ) ; } break ; } } return plan ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the plan instance variables using the given results set . [CODESPLIT] private final void setPlanVariables ( Agent agent , Plan planInstance , Set < Belief > results , int choice ) { if ( agent == null || planInstance == null ) { return ; } Belief belief = getResultAtIndex ( results , choice ) ; if ( belief == null ) { return ; } Object [ ] tuple = belief . getTuple ( ) ; if ( tuple == null ) { return ; } int index = 0 ; HashMap < String , Object > vars = new HashMap < String , Object > ( ) ; for ( Object o : belief . getTuple ( ) ) { try { String fieldname = ABeliefStore . getFieldName ( agent . getId ( ) , belief . getBeliefset ( ) , index ) ; vars . put ( fieldname , o ) ; } catch ( BeliefBaseException e ) { Log . error ( \"Agent \" + agent . getId ( ) + \" could not retrive belief set field: \" + e . getMessage ( ) ) ; } index ++ ; } planInstance . setPlanVariables ( vars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the result at the given index from the results set . [CODESPLIT] private Belief getResultAtIndex ( Set < Belief > results , int index ) { Belief belief = null ; if ( ! ( results == null || index < 0 || index >= results . size ( ) ) ) { int idx = 0 ; for ( Belief b : results ) { if ( idx == index ) { belief = b ; break ; } idx ++ ; } } return belief ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the parents of this object in the Goal - Plan tree . [CODESPLIT] public byte [ ] getParents ( ) { if ( parents == null ) { return null ; } byte [ ] arr = new byte [ parents . length ] ; System . arraycopy ( parents , 0 , arr , 0 , arr . length ) ; return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets all the children of this object in the Goal - Plan tree . [CODESPLIT] public byte [ ] getChildren ( ) { if ( children == null ) { return null ; } byte [ ] arr = new byte [ children . length ] ; System . arraycopy ( children , 0 , arr , 0 , arr . length ) ; return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grows the given array by the given size . [CODESPLIT] public static byte [ ] grow ( byte [ ] bytes , int increment ) { if ( bytes == null ) { return new byte [ 1 ] ; } byte [ ] temp = new byte [ bytes . length + increment ] ; System . arraycopy ( bytes , 0 , temp , 0 , bytes . length ) ; return temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new logger . [CODESPLIT] public static Logger createLogger ( String name , Level level , String file ) { LoggerContext lc = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; PatternLayoutEncoder ple = new PatternLayoutEncoder ( ) ; ple . setPattern ( \"%date %level [%thread] %logger{10} [%file:%line]%n%msg%n%n\" ) ; ple . setContext ( lc ) ; ple . start ( ) ; FileAppender < ILoggingEvent > fileAppender = new FileAppender < ILoggingEvent > ( ) ; fileAppender . setFile ( file ) ; fileAppender . setEncoder ( ple ) ; fileAppender . setAppend ( false ) ; fileAppender . setContext ( lc ) ; fileAppender . start ( ) ; logger = ( Logger ) LoggerFactory . getLogger ( name ) ; logger . detachAndStopAllAppenders ( ) ; // detach console (doesn't seem to work) logger . addAppender ( fileAppender ) ; // attach file appender logger . setLevel ( level ) ; logger . setAdditive ( true ) ; // set to true if root should log too return logger ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs a single step of this plan i . e . progresses this intention . [CODESPLIT] public void step ( ) { if ( body == null || body . length == 0 || index < 0 || index >= body . length ) { return ; } body [ index ++ ] . step ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the list of goals for this agent . [CODESPLIT] public void setGoals ( byte [ ] arr ) { if ( arr == null ) { goals = null ; return ; } goals = new byte [ arr . length ] ; System . arraycopy ( arr , 0 , goals , 0 , goals . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > addGoal . < / p > [CODESPLIT] public void addGoal ( byte goal ) { goals = GoalPlanType . grow ( goals , 1 ) ; goals [ goals . length - 1 ] = goal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits for user to press a key before continuing . Useful for connecting to a profiler [CODESPLIT] static void pauseForUserInput ( ) { System . out . println ( \"Press the Enter/Return key to continue..\" ) ; Scanner in = new Scanner ( System . in ) ; in . nextLine ( ) ; in . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialises the intention selection pools . [CODESPLIT] public static void initIntentionSelectionPools ( int nagents , int ncores ) { Main . poolsize = ( nagents > ncores ) ? ( nagents / ncores ) : 1 ; Main . npools = ( nagents > ncores ) ? ncores : nagents ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the intention selection threads that each handle a pool of agents . [CODESPLIT] static void initIntentionSelectionThreads ( Config config ) { int ncores = config . getNumThreads ( ) ; Main . intentionSelectors = new IntentionSelector [ ncores ] ; for ( int i = 0 ; i < Main . npools ; i ++ ) { Main . intentionSelectors [ i ] = new IntentionSelector ( i , config . getRandomSeed ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the intention selection threads . [CODESPLIT] static void startIntentionSelectionThreads ( ) { for ( int i = 0 ; i < Main . npools ; i ++ ) { Thread thread = new Thread ( Main . intentionSelectors [ i ] ) ; thread . setName ( \"jill-\" + i ) ; thread . start ( ) ; // start and wait at the entry barrier } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stops the intention selection threads . [CODESPLIT] static void shutdownIntentionSelectionThreads ( ) { for ( int i = 0 ; i < Main . npools ; i ++ ) { Main . intentionSelectors [ i ] . shutdown ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads any configured extensions ( see { @link JillExtension } ) . [CODESPLIT] static boolean loadExtensions ( Config config ) { if ( config . getExtensions ( ) == null ) { return true ; } for ( Config . ExtensionData extensionData : config . getExtensions ( ) ) { JillExtension extension = ProgramLoader . loadExtension ( extensionData . getClassname ( ) ) ; if ( extension != null ) { Program . registerExtension ( extension ) ; extension . init ( extensionData . getArgs ( ) . toArray ( new String [ 0 ] ) ) ; } else { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a new Jill extension . [CODESPLIT] public static void registerExtension ( JillExtension extension ) { if ( extension != null ) { GlobalState . eventHandlers . add ( extension ) ; Main . logger . info ( \"Registered Jill extension: \" + extension ) ; } else { Main . logger . warn ( \"Cannot register null extension; will ignore.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( PrintStream writer , String [ ] params ) { parse ( params ) ; out = writer ; // Create a new belief set about neighbours BeliefSetField [ ] fields = { new BeliefSetField ( \"name\" , String . class , true ) , } ; try { // Attach this belief set to this agent this . createBeliefSet ( beliefset , fields ) ; int numAgents = GlobalState . agents . size ( ) ; // Cannot have more neighbours than agents if ( neighbourhood >= numAgents ) { Log . error ( \"Agent \" + getName ( ) + \" cannot add \" + neighbourhood + \" neighbours, when there are only \" + numAgents + \" agents all up\" ) ; System . exit ( - 1 ) ; } // Add beliefs about neighbours for ( int i = 1 ; i <= neighbourhood ; i ++ ) { int neighbour = ( getId ( ) + i ) % numAgents ; this . addBelief ( beliefset , Integer . toString ( neighbour ) ) ; Log . debug ( \"Agent \" + getName ( ) + \" added neighbour \" + neighbour ) ; } Log . debug ( \"Agent \" + getName ( ) + \" is initialising with neighbourhood size of \" + neighbourhood + \" on each side (so \" + ( neighbourhood * 2 ) + \" neighbours)\" ) ; // Let Agent 0 start the token passing if ( getId ( ) == 0 ) { Log . debug ( \"round 1\" ) ; Token3 token = new Token3 ( 1 , 1 ) ; token . setHops ( 1 ) ; send ( 1 , token ) ; } } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the command line arguments . [CODESPLIT] public static void parse ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { switch ( args [ i ] ) { case \"-neighbourhood\" : if ( i + 1 < args . length ) { i ++ ; try { neighbourhood = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( \"Value '\" + args [ i ] + \"' is not a number\" ) ; } } break ; case \"-rounds\" : if ( i + 1 < args . length ) { i ++ ; try { rounds = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( \"Value '\" + args [ i ] + \"' is not a number\" ) ; } } break ; default : // Ignore all other arguments break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the global state . [CODESPLIT] public static void reset ( ) { agentTypes = new AObjectCatalog ( \"agentTypes\" , 5 , 5 ) ; goalTypes = new AObjectCatalog ( \"goalTypes\" , 10 , 5 ) ; planTypes = new AObjectCatalog ( \"planTypes\" , 20 , 5 ) ; agents = null ; beliefbase = null ; eventHandlers = new HashSet < JillExtension > ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a given number of agents of a given Class and adds the newly created agents to the given store . [CODESPLIT] public static boolean loadAgent ( String className , int num , AObjectCatalog agents ) { // Load the Agent class Class < ? > aclass = loadClass ( className , Agent . class ) ; if ( aclass == null ) { return false ; } // Save this agent type to the catalog of known agent types AgentType atype = new AgentType ( className ) ; atype . setAgentClass ( aclass ) ; GlobalState . agentTypes . push ( atype ) ; // Find the goals that this agent has String [ ] goals = getGoalsFromAgentInfoAnnotation ( aclass ) ; if ( goals . length == 0 ) { return false ; } // First pass: get the goals and their plans (flat goal-plan list) loadGoalPlanNodes ( atype , goals ) ; // Second pass: complete the goal-plan hierarchy completeGoalPlanHierarchy ( ) ; // Now create the specified number of instances of this agent type createAgentsInCatalog ( agents , atype , aclass , num ) ; // return success return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the given plan classes and sets up parent - child links with the given goal type . [CODESPLIT] private static boolean processPlansForGoal ( GoalType gtype , String [ ] plans ) { for ( int j = 0 ; j < plans . length ; j ++ ) { // Load the Plan class Class < ? > pclass = loadClass ( plans [ j ] , Plan . class ) ; if ( pclass == null ) { return false ; } // Found the plan class, so add this plan to the catalog of known plan types logger . info ( \"Found Plan \" + pclass . getName ( ) + \" that handles Goal \" + gtype . getName ( ) ) ; PlanType ptype = new PlanType ( pclass . getName ( ) ) ; ptype . setPlanClass ( pclass ) ; GlobalState . planTypes . push ( ptype ) ; // Set up the parent/child links between them (makings of a goal-plan tree) ptype . addParent ( ( byte ) gtype . getId ( ) ) ; gtype . addChild ( ( byte ) ptype . getId ( ) ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Completes the Goal - Plan hierarchy linkages between all { @link GlobalState#goalTypes } and { @link GlobalState#planTypes } . [CODESPLIT] private static boolean completeGoalPlanHierarchy ( ) { for ( int i = 0 ; i < GlobalState . planTypes . size ( ) ; i ++ ) { PlanType ptype = ( PlanType ) GlobalState . planTypes . get ( i ) ; String [ ] postsGoals = getGoalsFromPlanInfoAnnotation ( ptype . getPlanClass ( ) ) ; // A @PlanInfo is optional, and only present if this plan posts goals if ( postsGoals == null ) { continue ; } // But if @PlanInfo was given then it cannot be incomplete if ( postsGoals . length == 0 ) { return false ; } // All good, so find the goals that this plan posts and set up the Goal-Plan tree links for ( String goalname : postsGoals ) { GoalType gtype = ( GoalType ) GlobalState . goalTypes . find ( goalname ) ; if ( gtype == null ) { logger . error ( \"Plan \" + ptype . getName ( ) + \" posts goal \" + goalname + \"which is not a known goal type.\" ) ; return false ; } // Found a goal posted by the plan, so setup the parent-child links ptype . addChild ( ( byte ) gtype . getId ( ) ) ; gtype . addParent ( ( byte ) ptype . getId ( ) ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the specified number of agent instances of the given type and adds them to the catalog . [CODESPLIT] private static void createAgentsInCatalog ( AObjectCatalog agents , AgentType atype , Class < ? > aclass , int num ) { int added = 0 ; try { for ( int i = 0 ; i < num ; i ++ ) { // Create a new instance (name prefix 'a' for agents) Agent agent = ( Agent ) ( aclass . getConstructor ( String . class ) . newInstance ( \"a\" + Integer . toString ( i ) ) ) ; // Assign the static goal plan tree hierarchy to this instance agent . setGoals ( atype . getGoals ( ) ) ; // Add this instance to the catalog of agent instances agents . push ( agent ) ; added ++ ; } logger . info ( \"Finished loading {} agents\" , added ) ; } catch ( NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { logger . error ( \"Could not create instance of class \" + aclass . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the list of goals specified in the @AgentInfo annotation of the given agent class . [CODESPLIT] private static String [ ] getGoalsFromAgentInfoAnnotation ( Class < ? > aclass ) { // Find the goals that this agent has Annotation annotation = aclass . getAnnotation ( AgentInfo . class ) ; if ( annotation == null ) { logger . error ( \"Agent \" + aclass . getName ( ) + \" is missing the \" + \"@AgentInfo(hasGoals={\\\"package.GoalClass1, package.GoalClass2, ...\\\"}) \" + knowsNothing + \"about this agent's goals and plans.\" ) ; return new String [ 0 ] ; } AgentInfo ainfo = ( AgentInfo ) annotation ; String [ ] goals = ainfo . hasGoals ( ) ; if ( goals . length == 0 ) { logger . error ( \"Agent \" + aclass . getName ( ) + \" does not have any goals defined. Was expecting something like \" + \"@AgentInfo(hasGoals={\\\"package.GoalClass1, package.GoalClass2, ...\\\"}) \" + knowsNothing + \"about this agent's goals and plans.\" ) ; } return goals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the list of plans specified in the @GoalInfo annotation of the given goal class . [CODESPLIT] private static String [ ] getPlansFromGoalsInfoAnnotation ( Class < ? > gclass ) { // Find the plans that this goal has Annotation annotation = gclass . getAnnotation ( GoalInfo . class ) ; if ( annotation == null ) { logger . error ( \"Goal \" + gclass . getName ( ) + \" is missing the \" + \"@GoalInfo(hasPlans={\\\"package.PlanClass1, package.PlanClass2, ...\\\"}) \" + knowsNothing + \"about which plans can handle this goal.\" ) ; return new String [ 0 ] ; } GoalInfo ginfo = ( GoalInfo ) annotation ; String [ ] plans = ginfo . hasPlans ( ) ; if ( plans . length == 0 ) { logger . error ( \"Goal \" + gclass . getName ( ) + \" does not have any plans defined. Was expecting something like \" + \"@GoalInfo(hasPlans={\\\"package.PlanClass1, package.PlanClass2, ...\\\"}) \" + knowsNothing + \"about which plans can handle this goal.\" ) ; } return plans ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the list of goals specified in the @PlanInfo annotation of the given plan class . [CODESPLIT] private static String [ ] getGoalsFromPlanInfoAnnotation ( Class < ? > pclass ) { Annotation annotation = pclass . getAnnotation ( PlanInfo . class ) ; PlanInfo pinfo = ( PlanInfo ) annotation ; // A @PlanInfo is optional, and only present if this plan posts goals if ( pinfo == null ) { return null ; } String [ ] postsGoals = pinfo . postsGoals ( ) ; if ( postsGoals . length == 0 ) { logger . error ( \"Plan \" + pclass . getName ( ) + \" has incomplete \" + \"@PlanInfo(postsGoals={\\\"package.GoalClass1\\\", \\\"package.GoalClass2\\\", ...})) \" + \"annotation\" ) ; } else { logger . info ( \"Plan \" + pclass . getName ( ) + \" posts \" + postsGoals . length + \" goals\" ) ; } return postsGoals ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the class of given name and type . [CODESPLIT] private static Class < ? > loadClass ( String className , Class < ? > classType ) { Class < ? > aclass = null ; try { aclass = Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { logger . error ( \"Class not found: \" + className , e ) ; return null ; } if ( ! classType . isAssignableFrom ( aclass ) ) { logger . error ( \"Class '\" + className + \"' is not of type \" + classType . getName ( ) ) ; return null ; } logger . info ( \"Found class \" + className + \" of type \" + classType . getName ( ) ) ; return aclass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a Jill extension . [CODESPLIT] public static JillExtension loadExtension ( String className ) { JillExtension extension = null ; Class < ? > eclass ; try { // Check that we have the extension class, else abort eclass = Class . forName ( className ) ; if ( ! JillExtension . class . isAssignableFrom ( eclass ) ) { logger . error ( \"Class '\" + className + \"' does not implement \" + JillExtension . class . getName ( ) ) ; return null ; } logger . info ( \"Loading extension \" + className ) ; extension = ( JillExtension ) ( eclass . newInstance ( ) ) ; } catch ( ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e ) { logger . error ( \"Could not load extension \" + className , e ) ; } return extension ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if two objects have the same name . The check is case sensitive . [CODESPLIT] public static boolean isNameEqual ( AObject obj1 , AObject obj2 ) { // Not equal if the names are null, or empty, or not the same size if ( obj1 . name == null || obj2 . name == null || obj1 . name . length != obj2 . name . length || obj1 . name . length == 0 ) { return false ; } // Not equal if any name character is different for ( int i = 0 ; i < obj1 . name . length ; i ++ ) { if ( obj1 . name [ i ] != obj2 . name [ i ] ) { return false ; } } // Else equal return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a usage string for the Jill command line arguments . [CODESPLIT] public static String usage ( ) { return GlobalConstant . APP_HEADER + \"\\n\\n\" + \"usage: \" + Main . class . getName ( ) + \"  [options] --agent-class <agentclass> --num-agents <numagents>\" + \"\\n\" + \"   --config <string>                 load configuration from string\" + \"\\n\" + \"   --configfile <file>               load configuration from file\" + \"\\n\" + \"   --exit-on-idle <boolean>          forces system exit when all agents are \" + \"idle (default is '\" + GlobalConstant . EXIT_ON_IDLE + \"')\\n\" + \"   --help                            print this usage message and exit \\n\" + \"   --plan-selection-policy <policy>  policy for selecting from plan instances \" + \"(FIRST, RANDOM, or LAST (default is '\" + GlobalConstant . PLAN_SELECTION_POLICY + \"')\\n\" + \"   --plan-instances-limit <number>   maximum number of applicable plan instances \" + \"to consider (default is '\" + GlobalConstant . PLAN_INSTANCES_LIMIT + \"')\\n\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given command line arguments . [CODESPLIT] public static void parse ( String [ ] args ) { for ( int i = 0 ; args != null && i < args . length ; i ++ ) { // First parse args that don't require an option if ( \"--help\" . equals ( args [ i ] ) ) { abort ( null ) ; } // Now parse args that must be accompanied by an option if ( i + 1 < args . length ) { parseArgumentWithOption ( args [ i ] , args [ ++ i ] ) ; // force increment the counter } } // Abort if required args were not given if ( config == null ) { abort ( \"Configuration file or string was not given\" ) ; } else if ( config . getAgents ( ) == null || config . getAgents ( ) . isEmpty ( ) ) { abort ( \"Configuration is missing agents specification\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given command line argument and associated option . Will abort if an unrecoverable error occurs . [CODESPLIT] private static void parseArgumentWithOption ( String arg , String opt ) { switch ( arg ) { case \"--config\" : config = loadConfigFromString ( opt ) ; break ; case \"--configfile\" : config = loadConfigFromFile ( opt ) ; break ; case \"--exit-on-idle\" : GlobalConstant . EXIT_ON_IDLE = Boolean . parseBoolean ( opt ) ; break ; case \"--plan-selection-policy\" : try { GlobalConstant . PLAN_SELECTION_POLICY = GlobalConstant . PlanSelectionPolicy . valueOf ( opt ) ; } catch ( IllegalArgumentException e ) { abort ( \"Unknown plan selection policy '\" + opt + \"'\" ) ; } break ; case \"--plan-instances-limit\" : try { GlobalConstant . PLAN_INSTANCES_LIMIT = Integer . parseInt ( opt ) ; } catch ( NumberFormatException e ) { abort ( \"Option value '\" + opt + \"' is not a number\" ) ; } break ; default : // Ignore any other arguments (which may be used by components external to Jill) break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the Jill startup configuration object . <p > Configuration is specified at run time via one of the following two options : <ul > <li > { @code -- config <string > } < / li > <li > { @code -- configfile <file > } < / li > < / ul > The contents of { @code <string > } or { @code <file > } are parsed in exactly the same way . The expected syntax is JSON format . If both options are specified then last specified option will overrule . < / p > [CODESPLIT] static Config loadConfigFromString ( String str ) { Gson gson = new Gson ( ) ; Config config = null ; try { config = gson . fromJson ( str , Config . class ) ; } catch ( JsonSyntaxException e ) { abort ( \"Invalid JSON syntax in \" + str + \": \" + e . getMessage ( ) ) ; } return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sample program to test belief base evaluation speeds . [CODESPLIT] public static void main ( String [ ] args ) throws BeliefBaseException { // Configure logging Log . createLogger ( \"\" , Level . INFO , \"BeliefBase.log\" ) ; // BeliefBase bb = new H2BeliefBase(\"jdbc:h2:mem:agents;CACHE_SIZE=1048576\"); String bs1 = \"neighbour\" ; String bs2 = \"hascar\" ; long t0 ; long t1 ; int numAgents = 10000 ; int numNeighbours = 1000 ; BeliefBase bb = new ABeliefStore ( numAgents , 4 ) ; Log . info ( \"Initialising \" + numAgents + \" agents with \" + numNeighbours + \" beliefs each\" ) ; BeliefSetField [ ] fields1 = { new BeliefSetField ( \"name\" , String . class , true ) , new BeliefSetField ( \"gender\" , String . class , false ) , } ; BeliefSetField [ ] fields2 = { new BeliefSetField ( \"name\" , String . class , true ) , new BeliefSetField ( \"car\" , Boolean . class , false ) , } ; long t2 = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < numAgents ; i ++ ) { t0 = System . currentTimeMillis ( ) ; bb . createBeliefSet ( i , bs1 , fields1 ) ; t1 = System . currentTimeMillis ( ) ; Log . debug ( \"Created belief set '\" + bs1 + \"' \" + Log . formattedDuration ( t0 , t1 ) ) ; t0 = System . currentTimeMillis ( ) ; for ( int j = 0 ; j < numNeighbours ; j ++ ) { bb . addBelief ( i , bs1 , \"agent\" + j , ( ( j % 2 ) == 0 ) ? \"male\" : \"female\" ) ; } t1 = System . currentTimeMillis ( ) ; Log . debug ( \"Agent \" + i + \" added \" + numNeighbours + \" beliefs to belief set '\" + bs1 + \"' (\" + ( t1 - t0 ) + \" ms)\" ) ; } long t3 = System . currentTimeMillis ( ) ; Log . info ( \"Finished initialising \" + numAgents + \" agents with \" + numNeighbours + \" beliefs each for belief set '\" + bs1 + \"' \" + Log . formattedDuration ( t2 , t3 ) ) ; t2 = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < numAgents ; i ++ ) { t0 = System . currentTimeMillis ( ) ; bb . createBeliefSet ( i , bs2 , fields2 ) ; t1 = System . currentTimeMillis ( ) ; Log . debug ( \"Created belief set '\" + bs2 + \"' \" + Log . formattedDuration ( t0 , t1 ) ) ; t0 = System . currentTimeMillis ( ) ; for ( int j = 0 ; j < numNeighbours ; j ++ ) { bb . addBelief ( i , bs2 , \"agent\" + j , ( ( j % 2 ) == 0 ) ? true : false ) ; } t1 = System . currentTimeMillis ( ) ; Log . debug ( \"Agent \" + i + \" added \" + numNeighbours + \" beliefs to belief set '\" + bs2 + \"' (\" + ( t1 - t0 ) + \" ms)\" ) ; } t3 = System . currentTimeMillis ( ) ; Log . info ( \"Finished initialising \" + numAgents + \" agents with \" + numNeighbours + \" beliefs each for belief set '\" + bs2 + \"' \" + Log . formattedDuration ( t2 , t3 ) ) ; final String opstr = \".name=agent\" ; int agentId = 0 ; int neighbourId = 0 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = 0 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = numAgents - 1 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = 0 ; neighbourId = 0 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = 0 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; agentId = numAgents - 1 ; neighbourId = numNeighbours - 1 ; doEval ( bb , agentId , bs1 + opstr + neighbourId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given query on the given belief base for the agent . [CODESPLIT] public static void doEval ( BeliefBase bb , int agentId , String query ) throws BeliefBaseException { final long t0 = System . currentTimeMillis ( ) ; bb . eval ( agentId , query ) ; final long t1 = System . currentTimeMillis ( ) ; Log . info ( \"Agent \" + agentId + \" searched for '\" + query + \"' \" + Log . formattedDuration ( t0 , t1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the object at the given index of the catalog . [CODESPLIT] public AObject get ( int index ) { if ( index >= 0 && index < objects . length ) { return objects [ index ] ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an object by name . Can be very expensive for large catalogs since a name comparison is performed in sequence on the objects in the catalog until a match is found . Search is case sensitive . [CODESPLIT] public AObject find ( String name ) { for ( int i = 0 ; i < nextid ; i ++ ) { if ( objects [ i ] . getName ( ) . equals ( name ) ) { return objects [ i ] ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes a new object to the top of the catalog . [CODESPLIT] public void push ( AObject obj ) { if ( obj == null || obj . getId ( ) != GlobalConstant . NULLID ) { return ; } // Grow if we are at capacity if ( nextid == objects . length ) { grow ( ) ; } obj . setId ( nextid ) ; objects [ nextid ++ ] = obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops ( removes ) the object at the top of the catalog . [CODESPLIT] public AObject pop ( ) { if ( nextid > GlobalConstant . NULLID ) { nextid -- ; AObject obj = objects [ nextid ] ; objects [ nextid ] = null ; return obj ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grows the Catalog by a factor of { [CODESPLIT] private void grow ( ) { AObject [ ] temp = new AObject [ objects . length + increment ] ; System . arraycopy ( objects , 0 , temp , 0 , objects . length ) ; objects = temp ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean context ( ) { Agent agent = getAgent ( ) ; int myid = agent . getId ( ) ; int goalid = ( ( Token3 ) getGoal ( ) ) . getAgent ( ) ; try { return ( myid == goalid ) && agent . eval ( \"neighbour.name = *\" ) ; } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void setPlanVariables ( Map < String , Object > vars ) { for ( String attribute : vars . keySet ( ) ) { if ( \"name\" . equals ( attribute ) ) { neighbour = ( String ) ( vars . get ( attribute ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the object at the given index in the catalog . [CODESPLIT] public Object get ( int idx ) { int index = idx & 0xff ; if ( isEmpty ( ) ) { // System.err.println(\"index \"+index+\" is invalid as stack is empty\"); return null ; } else if ( index < 0 || index >= size ) { // System.err.println(\"index \"+index+\" is outside of range [0,\"+(size-1)+\"]\"); return null ; } return objects [ index ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes an object on to the top of the stack . [CODESPLIT] public boolean push ( Object obj ) { // Cannot add beyond maximum capacity if ( isFull ( ) ) { return false ; } // Grow if we are at capacity if ( size == objects . length ) { grow ( ) ; } objects [ size ++ ] = obj ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops the Object at the top of the stack . [CODESPLIT] public Object pop ( ) { if ( isEmpty ( ) ) { return null ; } size -- ; Object obj = objects [ size ] ; objects [ size ] = null ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Grows the stack capacity by { @link #increment } up to the maximum capacity of 255 ( byte size ) . [CODESPLIT] private boolean grow ( ) { if ( objects . length == MAXIMUM_CAPACITY ) { // Cannot grow beyond the maximum capacity return false ; } int newsize = objects . length + increment ; if ( newsize > MAXIMUM_CAPACITY ) { newsize = MAXIMUM_CAPACITY ; } Object [ ] temp = new Object [ newsize ] ; System . arraycopy ( objects , 0 , temp , 0 , objects . length ) ; objects = temp ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( PrintStream writer , String [ ] params ) { out = writer ; // Parse the arguments parse ( params ) ; // Create the board board = new Board ( ndiscs ) ; out . println ( \"Initialised hanoi board with \" + ndiscs + \" discs:\" ) ; out . println ( board . toString ( ) ) ; // Solve the board post ( new Solve ( \"s\" , ndiscs , 0 , 2 , 1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean createBeliefSet ( int agentid , String name , BeliefSetField [ ] fields ) throws BeliefBaseException { if ( beliefsets . containsKey ( name ) ) { return false ; } // Add the beliefset to the list of beliefsets BeliefSet bs = new BeliefSet ( beliefsets . size ( ) , name , fields ) ; beliefsets . put ( name , bs ) ; beliefsetsByID . put ( bs . getId ( ) , bs ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean addBelief ( int agentid , String beliefsetName , Object ... tuple ) throws BeliefBaseException { // Check that the beliefset exists if ( ! beliefsets . containsKey ( beliefsetName ) ) { throw new BeliefBaseException ( \"Belief set '\" + beliefsetName + \"' does not exist\" ) ; } // Create a new Belief Belief belief = new Belief ( beliefs . size ( ) , beliefsets . get ( beliefsetName ) . getId ( ) , tuple ) ; // Add it to the list of beliefs int id ; if ( ! beliefs . containsKey ( belief ) ) { id = beliefs . size ( ) ; beliefs . put ( belief , id ) ; beliefsByID . put ( belief . getId ( ) , belief ) ; } else { id = beliefs . get ( belief ) ; } // Add it to the agents beliefs SparseBitSet bits = agents2beliefs [ agentid ] ; if ( bits == null ) { bits = new SparseBitSet ( ) ; } bits . set ( id ) ; agents2beliefs [ agentid ] = bits ; // Update the cached results for ( String query : cachedresults . keySet ( ) ) { Set < Belief > results = cachedresults . get ( query ) ; if ( match ( belief , queries . get ( query ) ) ) { results . add ( belief ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean eval ( int agentid , String key ) throws BeliefBaseException { return ! query ( agentid , key ) . isEmpty ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Set < Belief > query ( int agentid , String key ) throws BeliefBaseException { // Get the cached query if we have seen it before, else parse it AQuery query = null ; if ( queries . containsKey ( key ) ) { query = queries . get ( key ) ; } else { // Valid queries have the following syntax // beliefset.field OP value // where OP is one of =, !=, <, or > if ( key == null ) { throw new BeliefBaseException ( logsuffix ( agentid ) + \"'null' query\" ) ; } Pattern pattern = Pattern . compile ( \"(\\\\w+)\\\\.(\\\\w+)\\\\s*([=<>(!=)])\\\\s*(.+)\" ) ; Matcher matcher = pattern . matcher ( key ) ; if ( ! matcher . matches ( ) ) { throw new BeliefBaseException ( logsuffix ( agentid ) + \"invalid query '\" + key + \"' : syntax not of the form beliefset.field <op> value\" ) ; } String strBeliefset = matcher . group ( 1 ) ; String strField = matcher . group ( 2 ) ; String strOp = matcher . group ( 3 ) ; String strVal = matcher . group ( 4 ) ; try { query = parseQuery ( agentid , strBeliefset , strField , strOp , strVal ) ; queries . put ( key , query ) ; } catch ( BeliefBaseException e ) { throw new BeliefBaseException ( logsuffix ( agentid ) + \"could not parse query: \" + key , e ) ; } } // Get the cached results if they exist, // else perform the query and cache the results Set < Belief > results = null ; if ( cachedresults . containsKey ( key ) ) { results = cachedresults . get ( key ) ; } else { results = performQuery ( query , beliefs ) ; cachedresults . put ( key , results ) ; } // Finally, filter the results for this agent Set < Belief > matches = filterResultsForAgent ( agentid , results ) ; Log . debug ( \"Agent \" + agentid + \" found \" + matches . size ( ) + \" matches for the query\" ) ; return matches ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the type of the given object . [CODESPLIT] public static String getType ( Object obj ) { if ( obj == null ) { return null ; } String type = null ; if ( obj instanceof String || obj instanceof Integer || obj instanceof Double || obj instanceof Boolean ) { type = obj . getClass ( ) . getName ( ) ; } return type ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the given query run on the given belief returns a match . [CODESPLIT] private static boolean match ( Belief belief , AQuery query ) { assert ( belief != null ) ; assert ( query != null ) ; if ( belief . getBeliefset ( ) != query . getBeliefset ( ) ) { return false ; } switch ( query . getOp ( ) ) { case EQ : Object lhs = belief . getTuple ( ) [ query . getField ( ) ] ; Object rhs = query . getValue ( ) ; // Match wildcard or exact string return \"*\" . equals ( rhs ) || lhs . equals ( rhs ) ; case GT : // TODO: Handle Operator.GT case LT : // TODO: Handle Operator.LT default : break ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sample program to test pattern matching . [CODESPLIT] public static void main ( String [ ] args ) throws BeliefBaseException { BeliefBase bb = new ABeliefStore ( 100 , 4 ) ; bb . eval ( 0 , \"neighbour.age < 31\" ) ; Console console = System . console ( ) ; if ( console == null ) { System . err . println ( \"No console.\" ) ; System . exit ( 1 ) ; } while ( true ) { Pattern pattern = Pattern . compile ( console . readLine ( \"%nEnter your regex: \" ) ) ; Matcher matcher = pattern . matcher ( console . readLine ( \"Enter input string to search: \" ) ) ; boolean found = false ; while ( matcher . find ( ) ) { console . format ( \"I found the text\" + \" \\\"%s\\\" starting at \" + \"index %d and ending at index %d.%n\" , matcher . group ( ) , matcher . start ( ) , matcher . end ( ) ) ; found = true ; } if ( ! found ) { console . format ( \"No match found.%n\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the belief set field name ( see { @link io . github . agentsoz . jill . core . beliefbase . BeliefSetField } ) for the given belief set for the given agent . [CODESPLIT] public static String getFieldName ( int agentid , int beliefset , int index ) throws BeliefBaseException { if ( beliefset < 0 || beliefset > beliefsets . size ( ) ) { throw new BeliefBaseException ( \"belief set id \" + beliefset + \" is invalid\" ) ; } BeliefSetField [ ] bsf = beliefsetsByID . get ( beliefset ) . getFields ( ) ; if ( index < 0 || index >= bsf . length ) { throw new BeliefBaseException ( \"belief set field id \" + index + \" is invalid\" ) ; } return bsf [ index ] . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes the String str into a sequence of bytes using the character set specified in CHARSET storing the result into a new byte array . [CODESPLIT] public static byte [ ] toBytes ( String str ) { if ( str == null ) { return new byte [ 0 ] ; } byte [ ] val = null ; try { val = str . getBytes ( CHARSET ) ; } catch ( UnsupportedEncodingException e ) { // NOPMD - ignore empty catch // Can never occur since CHARSET is correct and final } return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push the given goal to the given stack . [CODESPLIT] private void post ( Stack255 stack , Goal goal ) { synchronized ( stack ) { logger . debug ( \"{} posting goal {}\" , Log . logPrefix ( getId ( ) ) , goal . getClass ( ) . getSimpleName ( ) ) ; stack . push ( goal ) ; Main . setAgentIdle ( getId ( ) , false ) ; } Main . flagMessageTo ( Main . poolid ( getId ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a message to an agent . [CODESPLIT] public boolean send ( int id , Goal msg ) { AObject obj = agents . get ( id ) ; if ( obj == null ) { logger . warn ( \"{} attempted to send a message to unknown agent id '{}'\" , Log . logPrefix ( getId ( ) ) , id ) ; return false ; } logger . debug ( \"{} is sending message of type {} to agent {}\" , Log . logPrefix ( getId ( ) ) , msg . getClass ( ) . getSimpleName ( ) , id ) ; ( ( Agent ) obj ) . post ( msg ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a message to this agent . [CODESPLIT] public boolean send ( String name , Goal msg ) { AObject obj = agents . find ( name ) ; if ( obj == null ) { logger . warn ( \"{} attempted to send a message to unknown agent '{}'\" , Log . logPrefix ( getId ( ) ) , name ) ; return false ; } ( ( Agent ) obj ) . post ( msg ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > start . < / p > [CODESPLIT] public void start ( PrintStream writer , String [ ] params ) { logger . debug ( \"{} is starting\" , Log . logPrefix ( getId ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns this agent s top level goals . [CODESPLIT] public byte [ ] getGoals ( ) { byte [ ] arr = new byte [ goals . length ] ; System . arraycopy ( goals , 0 , arr , 0 , arr . length ) ; return arr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set s this agent s top level goals i . e . { @link #goals } . [CODESPLIT] public void setGoals ( byte [ ] bs ) { goals = new byte [ bs . length ] ; System . arraycopy ( bs , 0 , goals , 0 , goals . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new belief set with the given fields . [CODESPLIT] public void createBeliefSet ( String name , BeliefSetField [ ] fields ) throws BeliefBaseException { beliefbase . createBeliefSet ( getId ( ) , name , fields ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new belief to the specified belief set . [CODESPLIT] public void addBelief ( String beliefsetName , Object ... tuple ) throws BeliefBaseException { beliefbase . addBelief ( getId ( ) , beliefsetName , tuple ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the given query against this agent s belief base . [CODESPLIT] public boolean eval ( String query ) throws BeliefBaseException { boolean result = beliefbase . eval ( getId ( ) , query ) ; lastresult = ( result ) ? beliefbase . query ( getId ( ) , query ) : new HashSet < Belief > ( ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forces this agent to enter an idle state irrespective of whether it has any active intentions or not . The agent will continue to remain in the suspected state until some event forces it to become active again at which point it will resume operation . [CODESPLIT] public void suspend ( boolean val ) { Main . setAgentIdle ( getId ( ) , val ) ; Main . flagMessageTo ( Main . poolid ( getId ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean context ( ) { try { return getAgent ( ) . eval ( \"neighbour.gender = male\" ) ; } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the field of this belief set that has the given name . [CODESPLIT] public BeliefSetField getFieldByName ( String name ) { BeliefSetField field = null ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( name . equals ( fields [ i ] . getName ( ) ) ) { field = fields [ i ] ; break ; } } return field ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the index ( column ) of the given field in this belief set . [CODESPLIT] public int getIndex ( BeliefSetField field ) { int index = - 1 ; for ( int i = 0 ; i < fields . length ; i ++ ) { if ( field . equals ( fields [ i ] ) ) { index = i ; } } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( PrintStream writer , String [ ] params ) { parse ( params ) ; out = writer ; if ( getId ( ) == 0 ) { Log . debug ( \"round 1\" ) ; send ( 1 , new Token2 ( 1 , 1 ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the command line arguments . [CODESPLIT] public static void parse ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( \"-rounds\" . equals ( args [ i ] ) && i + 1 < args . length ) { i ++ ; try { rounds = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( \"Value '\" + args [ i ] + \"' is not a number\" ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void start ( PrintStream writer , String [ ] params ) { // Parse the arguments parse ( params ) ; // Create a new belief set about neighbours BeliefSetField [ ] fields = { new BeliefSetField ( \"name\" , String . class , true ) , new BeliefSetField ( \"gender\" , String . class , false ) , } ; try { // Attach this belief set to this agent this . createBeliefSet ( beliefset , fields ) ; // Add beliefs about neighbours registerNeighbours ( rand , numNeighbours ) ; Log . debug ( \"Agent \" + getName ( ) + \" is initialising with \" + numNeighbours + \" neighbours\" ) ; // Post the goal to be friendly post ( new BeFriendly ( \"BeFriendly\" ) ) ; } catch ( BeliefBaseException e ) { Log . error ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper function to add beliefs about neighbours . [CODESPLIT] private void registerNeighbours ( Random rand , int count ) throws BeliefBaseException { int size = ( count < 0 ) ? 0 : count ; for ( int i = 0 ; i < size ; i ++ ) { boolean male = ( rand . nextDouble ( ) < 0.5 ) ? true : false ; this . addBelief ( beliefset , buildName ( male ) , male ? \"male\" : \"female\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a new name . [CODESPLIT] private static String buildName ( boolean male ) { StringBuilder name = new StringBuilder ( ) ; name . append ( male ? males [ rand . nextInt ( males . length ) ] : females [ rand . nextInt ( females . length ) ] ) . append ( ' ' ) . append ( middle [ rand . nextInt ( middle . length ) ] ) . append ( ' ' ) . append ( surnames [ rand . nextInt ( surnames . length ) ] ) ; return name . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the command line arguments . [CODESPLIT] public static void parse ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { switch ( args [ i ] ) { case \"-seed\" : if ( i + 1 < args . length ) { i ++ ; int seed = 0 ; try { seed = Integer . parseInt ( args [ i ] ) ; rand = new Random ( seed ) ; } catch ( NumberFormatException e ) { Log . warn ( \"Seed value '\" + args [ i ] + \"' is not a number\" ) ; } } break ; case \"-neighbourhoodSize\" : if ( i + 1 < args . length ) { i ++ ; try { numNeighbours = Integer . parseInt ( args [ i ] ) ; } catch ( NumberFormatException e ) { Log . warn ( \"Neighbourhood size value '\" + args [ i ] + \"' is not a number\" ) ; } } break ; default : // Ignore any other arguments break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs this intentions selction thread . [CODESPLIT] public void run ( ) { Set < Integer > toRemove = new HashSet < Integer > ( ) ; do { boolean idle = true ; // Remove agents that have have become idle due to an external event removeInactiveAgents ( ) ; // Add agents that have have become active due to an external event addActiveAgents ( ) ; for ( Integer i : activeAgents ) { Agent agent = ( Agent ) GlobalState . agents . get ( i ) ; Stack255 agentExecutionStack = ( Stack255 ) ( agent ) . getExecutionStack ( ) ; if ( ! isStackValid ( agent , agentExecutionStack ) ) { // Mark this agent for removal toRemove . add ( i ) ; continue ; } // At least one agent is active idle = false ; // Get the item at the top of the stack Object node = ( Object ) agentExecutionStack . get ( ( byte ) ( agentExecutionStack . size ( ) - 1 ) ) ; if ( node instanceof Plan ) { // If it is a plan then execute a plan step; and if it finished then remove it managePlan ( i , agentExecutionStack , ( Plan ) node , toRemove ) ; } else if ( node instanceof Goal ) { // If it is a goal then find a plan for it and put it on the stack manageGoal ( i , agent , agentExecutionStack , ( Goal ) node ) ; } agent . nextActiveStack ( ) ; // select the next active stack for next time } // remove agents that have finished executing plans and have gone idle in this cycle removeFinishedAgents ( toRemove ) ; if ( idle ) { waitOnExternalMessage ( ) ; if ( shutdown ) { break ; } } } while ( true ) ; logger . debug ( \"Pool {} is exiting\" , poolid ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if this agent s execution stack is valid . The stack is valid if it is not null or empty and has not exceeded the maximum size limit of 255 . [CODESPLIT] private boolean isStackValid ( Agent agent , Stack255 agentExecutionStack ) { if ( agentExecutionStack == null ) { return false ; } final int esSize = agentExecutionStack . size ( ) ; logger . trace ( \"{} execution stack is {}/255 full\" , Log . logPrefix ( agent . getId ( ) ) , esSize ) ; if ( esSize == 0 ) { return false ; } if ( esSize >= 255 ) { logger . error ( \"{} execution stack reached size limit of 255. Cannot continue.\" , Log . logPrefix ( agent . getId ( ) ) ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the given list of agents from the list of active agents . [CODESPLIT] private void removeFinishedAgents ( Set < Integer > toRemove ) { if ( ! toRemove . isEmpty ( ) ) { for ( int i : toRemove ) { activeAgents . remove ( i ) ; } toRemove . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manages the goal at the top of the execution stack of an agent . All relevant plans are evaluated to see if their context conditions hold . Plans deemed applicable are then added to the list of bindings from which a plan instane will be eventually selected . [CODESPLIT] private boolean manageGoal ( int agentIndex , Agent agent , Stack255 agentExecutionStack , Goal node ) { // Get the goal type for this goal GoalType gtype = ( GoalType ) GlobalState . goalTypes . find ( node . getClass ( ) . getName ( ) ) ; byte [ ] ptypes = gtype . getChildren ( ) ; assert ( ptypes != null ) ; // Clear any previous plan bindings before adding any new ones bindings . clear ( ) ; for ( int p = 0 ; p < ptypes . length ; p ++ ) { PlanType ptype = ( PlanType ) GlobalState . planTypes . get ( ptypes [ p ] ) ; try { // Create an object of this Plan type, so we can // access its context condition Plan planInstance = ( Plan ) ( ptype . getPlanClass ( ) . getConstructor ( Agent . class , Goal . class , String . class ) . newInstance ( GlobalState . agents . get ( agentIndex ) , node , \"p\" ) ) ; // Clear previously buffered context results if any agent . clearLastResults ( ) ; // Evaluate the context condition if ( planInstance . context ( ) ) { // Get the results of context query just performed Set < Belief > results = agent . getLastResults ( ) ; // Add the results to the bindings bindings . add ( planInstance , ( results == null ) ? null : new LinkedHashSet < Belief > ( results ) ) ; } } catch ( NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { logger . error ( \"Could not create plan object of type \" + ptype . getClass ( ) . getName ( ) , e ) ; } } int numBindings = bindings . size ( ) ; if ( numBindings == 0 ) { // No plan options for this goal at this point in time, so move to the next agent logger . debug ( Log . logPrefix ( agent . getId ( ) ) + \" has no applicable plans for goal \" + gtype + \" and will continue to wait indefinitely\" ) ; return false ; } // Call the meta-level planning prior to plan selection agent . notifyAgentPrePlanSelection ( bindings ) ; // Pick a plan option using specified policy Plan planInstance = bindings . selectPlan ( GlobalConstant . PLAN_SELECTION_POLICY ) ; // Now push the plan on to the intention stack synchronized ( agentExecutionStack ) { logger . debug ( Log . logPrefix ( agent . getId ( ) ) + \" choose an instance of plan \" + planInstance . getClass ( ) . getSimpleName ( ) + \" to handle goal \" + node . getClass ( ) . getSimpleName ( ) ) ; agentExecutionStack . push ( planInstance ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Manages the plan at the top of this agent s execution stack . If the plan has finished it is removed else it is progresses by a single { @link PlanStep } . [CODESPLIT] private void managePlan ( int agentIndex , Stack255 agentExecutionStack , Plan node , Set < Integer > toRemove ) { // If done then pop this plan/goal if ( node . hasfinished ( ) ) { logger . debug ( Log . logPrefix ( agentIndex ) + \" finished executing plan \" + node . getClass ( ) . getSimpleName ( ) ) ; synchronized ( agentExecutionStack ) { // Pop the plan off the stack agentExecutionStack . pop ( ) ; // Pop the goal off the stack agentExecutionStack . pop ( ) ; if ( agentExecutionStack . isEmpty ( ) ) { // remove empty intention stacks Agent agent = ( Agent ) GlobalState . agents . get ( agentIndex ) ; int size = agent . cleanupStacks ( ) ; // If we are left with only one stack and that is empty, then agent is idle if ( size == 1 && agent . getExecutionStack ( ) . isEmpty ( ) ) { // Mark this agent as idle // Main.setAgentIdle(i, true); toRemove . add ( agentIndex ) ; } } } } else { logger . debug ( Log . logPrefix ( agentIndex ) + \" is executing a step of plan \" + node . getClass ( ) . getSimpleName ( ) ) ; node . step ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes from { [CODESPLIT] private void removeInactiveAgents ( ) { synchronized ( extToRemove ) { if ( ! extToRemove . isEmpty ( ) ) { for ( int i : extToRemove ) { activeAgents . remove ( i ) ; } extToRemove . clear ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds to { [CODESPLIT] private void addActiveAgents ( ) { synchronized ( extToAdd ) { if ( ! extToAdd . isEmpty ( ) ) { for ( int i : extToAdd ) { activeAgents . add ( i ) ; } extToAdd . clear ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits on { [CODESPLIT] private void waitOnExternalMessage ( ) { synchronized ( lock ) { while ( ! hasMessage ) { try { logger . debug ( \"Pool {} is idle; will wait on external message\" , poolid ) ; // Main.incrementPoolsIdle(); isIdle = true ; Main . flagPoolIdle ( ) ; lock . wait ( ) ; isIdle = false ; // Main.decrementPoolsIdle(); logger . debug ( \"Pool {} just woke up on external message\" , poolid ) ; } catch ( InterruptedException e ) { logger . error ( \"Pool \" + poolid + \" failed to wait on external message: \" , e ) ; } } hasMessage = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Terminates this intention selector thread . [CODESPLIT] public void shutdown ( ) { synchronized ( lock ) { logger . debug ( \"Pool {} received shutdown message\" , poolid ) ; shutdown = true ; hasMessage = true ; lock . notify ( ) ; // NOPMD - ignore notifyall() warning } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "and this thread is still iterating over activeagents [CODESPLIT] public void setAgentIdle ( int agentId , boolean idle ) { // If agent is becoming active, and not already active if ( ! idle /* && !activeAgents.contains(agentId) */ ) { synchronized ( extToAdd ) { extToAdd . add ( agentId ) ; } } // If agent is becoming idle, and not already idle if ( idle /* && activeAgents.contains(agentId) */ ) { synchronized ( extToRemove ) { extToRemove . add ( agentId ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move a disc from pin A to pin B . [CODESPLIT] public boolean move ( int pinA , int pinB ) { // Nothing to do if the pin number is invalid if ( pinA < 0 || pinA >= pins . length || pinB < 0 || pinB >= pins . length ) { Log . warn ( \"Invalid board pin specified \" + pinA + \". Should be between 0..\" + ( pins . length - 1 ) + \" (inclusive).\" ) ; return false ; } else if ( pins [ pinA ] . isEmpty ( ) ) { Log . warn ( \"No disc on pin\" + pinA ) ; return false ; } else if ( pinA == pinB ) { Log . info ( \"Moving disc from pin\" + pinA + \" on to itself (means the board will not change)\" ) ; return true ; } int discOnA = pins [ pinA ] . get ( pins [ pinA ] . size ( ) - 1 ) ; int discOnB = ( pins [ pinB ] . isEmpty ( ) ) ? Integer . MAX_VALUE : pins [ pinB ] . get ( pins [ pinB ] . size ( ) - 1 ) ; if ( discOnB < discOnA ) { Log . warn ( \"Cannot move disc\" + discOnA + \" (pin\" + pinA + \") on to smaller disc\" + discOnB + \" (pin\" + pinB + \")\" ) ; return false ; } pins [ pinB ] . add ( pins [ pinA ] . remove ( pins [ pinA ] . size ( ) - 1 ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Program entry [CODESPLIT] public static void main ( String [ ] args ) { // Parse the command line options ArgumentsLoader . parse ( args ) ; // Load the configuration Config config = ArgumentsLoader . getConfig ( ) ; // Initialise the system with the given arguments if ( ! init ( config ) ) { return ; } // load all extensions if ( ! Program . loadExtensions ( config ) ) { return ; } // Start the engine start ( config ) ; // Wait until the agents become idle waitUntilIdle ( ) ; // finish up finish ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialises the Jill engine . [CODESPLIT] public static boolean init ( Config config ) { // Pause for key press from user if requested if ( config . isDoPauseForUserInput ( ) ) { Program . pauseForUserInput ( ) ; } // Configure logging Log . createLogger ( Main . LOGGER_NAME , config . getLogLevel ( ) , config . getLogFile ( ) ) ; logger = LoggerFactory . getLogger ( Main . LOGGER_NAME ) ; int numAgents = 0 ; for ( Config . AgentTypeData agentType : config . getAgents ( ) ) { numAgents += agentType . getCount ( ) ; } final int increment = 10000 ; GlobalState . reset ( ) ; GlobalState . agents = new AObjectCatalog ( \"agents\" , numAgents , increment ) ; // Create the central belief base GlobalState . beliefbase = new ABeliefStore ( numAgents , config . getNumThreads ( ) ) ; long t0 ; // Create the agents t0 = System . currentTimeMillis ( ) ; for ( Config . AgentTypeData agentType : config . getAgents ( ) ) { if ( ! ProgramLoader . loadAgent ( agentType . getClassname ( ) , agentType . getCount ( ) , GlobalState . agents ) ) { // return unsuccessful return false ; } } long t1 = System . currentTimeMillis ( ) ; logger . info ( \"Created \" + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ; // Initialise the thread pools Program . initIntentionSelectionPools ( numAgents , config . getNumThreads ( ) ) ; // Redirect the agent program output if specified if ( config . getProgramOutputFile ( ) != null ) { try { writer = new PrintStream ( config . getProgramOutputFile ( ) , \"UTF-8\" ) ; } catch ( FileNotFoundException | UnsupportedEncodingException e ) { logger . error ( \"Could not open program outout file \" + config . getProgramOutputFile ( ) , e ) ; } } else { writer = System . out ; } // Initialise the intention selection threads Program . initIntentionSelectionThreads ( config ) ; // return success return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the Jill engine . Must have previously been initialised ( see { @link #init ( Config ) } ) . [CODESPLIT] public static void start ( Config config ) { // Start the agents long t0 = System . currentTimeMillis ( ) ; int index = 0 ; int subIndex = 0 ; for ( Config . AgentTypeData agentType : config . getAgents ( ) ) { index = subIndex ; String [ ] args = ( agentType . getArgs ( ) == null || agentType . getArgs ( ) . isEmpty ( ) ) ? new String [ 0 ] : agentType . getArgs ( ) . toArray ( new String [ agentType . getArgs ( ) . size ( ) ] ) ; for ( subIndex = index ; subIndex < index + agentType . getCount ( ) ; subIndex ++ ) { // Get the agent Agent agent = ( Agent ) GlobalState . agents . get ( subIndex ) ; // Start the agent agent . start ( writer , args ) ; } } long t1 = System . currentTimeMillis ( ) ; logger . info ( \"Started \" + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ; // Start the intention selection threads Program . startIntentionSelectionThreads ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Blocks until all agents have finished executing plans and have gone idle . [CODESPLIT] public static void waitUntilIdle ( ) { // Wait till we are all done long t0 = System . currentTimeMillis ( ) ; synchronized ( poolsIdle ) { while ( ! arePoolsIdle ( ) ) { try { poolsIdle . wait ( ) ; } catch ( InterruptedException e ) { logger . error ( \"Failed to wait on termination condition: \" + e . getMessage ( ) ) ; } } } long t1 = System . currentTimeMillis ( ) ; logger . info ( \"Finished running \" + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Termiantes the Jill engine . [CODESPLIT] public static void finish ( ) { // Terminate the extensions first for ( JillExtension extension : GlobalState . eventHandlers ) { extension . finish ( ) ; } // Now shut down the threads Program . shutdownIntentionSelectionThreads ( ) ; // Finish the agents long t0 = System . currentTimeMillis ( ) ; for ( int i = 0 ; i < GlobalState . agents . size ( ) ; i ++ ) { // Get the agent Agent agent = ( Agent ) GlobalState . agents . get ( i ) ; // Terminate the agent agent . finish ( ) ; } // Close the writer if ( writer != null ) { writer . close ( ) ; } long t1 = System . currentTimeMillis ( ) ; logger . info ( \"Terminated \" + GlobalState . agents . size ( ) + agentsIn + Log . formattedDuration ( t0 , t1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the system is idle i . e . all the agents pools are idle [CODESPLIT] public static boolean arePoolsIdle ( ) { boolean idle = true ; for ( int i = 0 ; i < npools ; i ++ ) { idle &= ( intentionSelectors [ i ] == null ) || intentionSelectors [ i ] . isIdle ( ) ; } return idle ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the { @link io . github . agentsoz . jill . core . IntentionSelector } pools have finished i . e . all agents in the pools are idle . [CODESPLIT] public static boolean arePoolsFinished ( ) { boolean finished = true ; for ( int i = 0 ; i < intentionSelectors . length ; i ++ ) { finished &= ( intentionSelectors [ i ] == null ) ; } return finished ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a bit in the agentsIdle cache to mark if this agent is idle ( or not ) . [CODESPLIT] public static void setAgentIdle ( int agentId , boolean isIdle ) { int poolid = poolid ( agentId ) ; intentionSelectors [ poolid ] . setAgentIdle ( agentId , isIdle ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the ID of the intention selection pool to which the given agent belongs . [CODESPLIT] public static int poolid ( int agentid ) { int poolid = agentid / poolsize ; if ( poolid + 1 > npools ) { poolid = npools - 1 ; } return poolid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the expression currently active in the building context . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public < E > Expression < E > pickExpression ( ) { Preconditions . checkState ( this . expression != null , \"No expression has been set\" ) ; Expression < E > result = ( Expression < E > ) this . expression ; expression = null ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the expression currently active in the building context . [CODESPLIT] public < E > void setExpression ( Expression < E > expression ) { Preconditions . checkState ( this . expression == null , \"An expression is already set\" ) ; this . expression = expression ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new join or find an existing join on the specified attribute . [CODESPLIT] public static Expression < ? > join ( String attribute , From < ? , ? > from ) { Expression < ? > path ; try { String [ ] properties = attribute . split ( \"\\\\.\" ) ; if ( properties . length > 1 ) { path = joinRecursively ( properties , findOrCreateJoin ( properties [ 0 ] , from ) , 1 ) . get ( properties [ properties . length - 1 ] ) ; } else { path = from . get ( properties [ 0 ] ) ; } } catch ( IllegalArgumentException e ) { throw SeedException . wrap ( e , JpaErrorCode . UNABLE_TO_CREATE_JPA_JOIN_FOR_SPECIFICATION ) . put ( \"property\" , attribute ) ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Join recursively using the split property path . [CODESPLIT] private static Join < ? , ? > joinRecursively ( String [ ] properties , Join < ? , ? > join , int index ) { if ( index < properties . length - 1 ) { return joinRecursively ( properties , findOrCreateJoin ( properties [ index ] , join ) , index + 1 ) ; } else { return join ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find an existing join for the property or create a new join . [CODESPLIT] private static Join < ? , ? > findOrCreateJoin ( String property , From < ? , ? > from ) { for ( Join < ? , ? > rootJoin : from . getJoins ( ) ) { if ( rootJoin . getAttribute ( ) . getName ( ) . equals ( property ) ) { return rootJoin ; } } return from . join ( property ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump managed instance of { @link InstanceType#PROXY } type and with { @link InstanceScope#APPLICATION } scope to container logger . For managed instance of other scope / type combinations this method does nothing . [CODESPLIT] @ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { if ( ! managedClass . getInstanceScope ( ) . equals ( InstanceScope . APPLICATION ) ) { return ; } if ( ! managedClass . getInstanceType ( ) . equals ( InstanceType . PROXY ) ) { return ; } Class < ? > [ ] interfaceClasses = managedClass . getInterfaceClasses ( ) ; StringBuilder interfaceNames = new StringBuilder ( interfaceClasses [ 0 ] . getName ( ) ) ; for ( int i = 1 ; i < interfaceClasses . length ; ++ i ) { interfaceNames . append ( \", \" ) ; interfaceNames . append ( interfaceClasses [ i ] . getName ( ) ) ; } log . debug ( \"Create managed container proxy:\\r\\n\" + //\r \"\\t- implementation: %s\\r\\n\" + //\r \"\\t- interface(s): %s\\r\\n\" + //\r \"\\t- scope: %s\\r\\n\" + //\r \"\\t- type: %s\\r\\n\" + //\r \"\\t- transactional: %s\\r\\n\" + //\r \"\\t- remote: %s\" , managedClass . getImplementationClass ( ) , interfaceNames . toString ( ) , managedClass . getInstanceScope ( ) , managedClass . getInstanceType ( ) , managedClass . isTransactional ( ) , managedClass . isRemotelyAccessible ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates whether the response reaches the end of the elements available on the server . [CODESPLIT] public boolean isEndReached ( ) { if ( to == null || from == null ) { // No range specified, must be complete response return true ; } if ( length == null ) { // No lenth specified, can't be end return false ; } return to == length - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse multipart form from HTTP request create object instance of requested type and fill it with form field value ( s ) . If formal type is a stream store it to local thread so that to be able to close it after arguments processed by application code . [CODESPLIT] @ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { if ( formalParameters . length != 1 ) { throw new IllegalArgumentException ( \"Bad parameters count. Should be exactly one but is |%d|.\" , formalParameters . length ) ; } if ( formalParameters [ 0 ] instanceof ParameterizedType ) { throw new IllegalArgumentException ( \"Parameterized type |%s| is not supported.\" , formalParameters [ 0 ] ) ; } Class < ? > type = ( Class < ? > ) formalParameters [ 0 ] ; Object [ ] arguments = new Object [ 1 ] ; if ( type . equals ( Form . class ) ) { arguments [ 0 ] = new FormImpl ( httpRequest ) ; } else if ( type . equals ( FormIterator . class ) ) { arguments [ 0 ] = new FormIteratorImpl ( httpRequest ) ; } else if ( type . equals ( UploadedFile . class ) ) { Form form = new FormImpl ( httpRequest ) ; // Form#getUploadedFile() throws IlegalArgumentException if form has not a single file upload part\r arguments [ 0 ] = form . getUploadedFile ( ) ; } else if ( type . equals ( UploadStream . class ) ) { threadLocal . set ( ( Closeable ) ( arguments [ 0 ] = getUploadStream ( httpRequest , formalParameters ) ) ) ; } else if ( type . equals ( InputStream . class ) ) { threadLocal . set ( ( Closeable ) ( arguments [ 0 ] = getUploadStream ( httpRequest , formalParameters ) . openStream ( ) ) ) ; } else { arguments [ 0 ] = new FormObject ( httpRequest , type ) . getValue ( ) ; } return arguments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get upload stream from given HTTP request . This method expects on HTTP request a multipart form with a single part of byte stream type . Returns an upload stream instance wrapping the form stream part . [CODESPLIT] private static UploadStream getUploadStream ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException { FormIterator form = new FormIteratorImpl ( httpRequest ) ; if ( ! form . hasNext ( ) ) { throw new IllegalArgumentException ( \"Empty form.\" ) ; } Part part = form . next ( ) ; if ( ! ( part instanceof UploadStream ) ) { throw new IllegalArgumentException ( \"Illegal form. Expected uploaded stream but got field |%s|.\" , part . getName ( ) ) ; } return ( UploadStream ) part ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up a class in the alias map . If <code > className< / code > exists as an alias it is resolved and returned . If the alias doesn t exist the original String is returned . [CODESPLIT] public String getClazz ( final String className ) { String realName = className ; while ( classMapper . containsKey ( realName ) ) { realName = classMapper . get ( realName ) ; } return realName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performed super - initialization by { @link AppServlet#init ( ServletConfig ) } and loads REST methods cache . A REST method is a remotely accessible method that does not return a { @link Resource } . Map storage key is generated by { @link #key ( ManagedMethodSPI ) } based on managed class and REST method request paths and is paired with retrieval key - { @link #key ( String ) } generated from request path info when method invocation occurs . [CODESPLIT] @ Override public void init ( ServletConfig config ) throws UnavailableException { super . init ( config ) ; for ( ManagedMethodSPI managedMethod : container . getManagedMethods ( ) ) { if ( ! managedMethod . isRemotelyAccessible ( ) ) { continue ; } if ( ! Types . isKindOf ( managedMethod . getReturnType ( ) , Resource . class ) ) { restMethods . put ( key ( managedMethod ) , managedMethod ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle request for a REST resource . Locate REST method based on request path info execute method and serialize back to client returned value if any . See class description for general behavior . [CODESPLIT] @ Override protected void handleRequest ( RequestContext context ) throws IOException { HttpServletRequest httpRequest = context . getRequest ( ) ; HttpServletResponse httpResponse = context . getResponse ( ) ; ArgumentsReader argumentsReader = null ; Object value = null ; ManagedMethodSPI method = null ; try { method = restMethods . get ( key ( httpRequest . getPathInfo ( ) ) ) ; if ( method == null ) { throw new NoSuchMethodException ( ) ; } Type [ ] formalParameters = method . getParameterTypes ( ) ; argumentsReader = argumentsReaderFactory . getArgumentsReader ( httpRequest , formalParameters ) ; Object [ ] arguments = argumentsReader . read ( httpRequest , formalParameters ) ; Object instance = container . getInstance ( method . getDeclaringClass ( ) ) ; value = method . invoke ( instance , arguments ) ; } catch ( AuthorizationException e ) { sendUnauthorized ( context ) ; return ; } catch ( NoSuchMethodException e ) { sendNotFound ( context , e ) ; return ; } catch ( IllegalArgumentException e ) { // there are opinions that 422 UNPROCESSABLE ENTITY is more appropriate response\r // see https://httpstatuses.com/422\r sendBadRequest ( context ) ; return ; } catch ( InvocationException e ) { sendError ( context , e ) ; return ; } finally { if ( argumentsReader != null ) { argumentsReader . clean ( ) ; } } httpResponse . setCharacterEncoding ( \"UTF-8\" ) ; if ( method . isVoid ( ) ) { // expected servlet container behavior:\r // since there is nothing written to respond to output stream, container either set content length to zero\r // or closes connection signaling end of content\r httpResponse . setStatus ( HttpServletResponse . SC_NO_CONTENT ) ; return ; } // expected servlet container behavior:\r // if client request connection header is close container uses an internal buffer for serialized JSON, add content\r // length response header based on buffer size and closes connection\r // if client request connection header is not explicitly set to close, container uses an internal buffer for serialized\r // JSON but with limited capacity; if capacity is not exceeded set response content length; if capacity is exceeded\r // switch to chunked transfer\r ContentType contentType = valueWriterFactory . getContentTypeForValue ( value ) ; httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; httpResponse . setContentType ( contentType . getValue ( ) ) ; ValueWriter valueWriter = valueWriterFactory . getValueWriter ( contentType ) ; valueWriter . write ( httpResponse , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate retrieval key for REST methods cache . This key is used by request routing logic to locate REST method about to invoke . It is based on request path extracted from request URI see { @link RequestPreprocessor } and { @link RequestContext#getRequestPath () } - and should be identical with storage key . <p > Retrieval key syntax is identical with storage key but is based on request path that on its turn is extracted from request URI . In fact this method just trim query parameters and extension if any . [CODESPLIT] private static String key ( String requestPath ) { int queryParametersIndex = requestPath . lastIndexOf ( ' ' ) ; if ( queryParametersIndex == - 1 ) { queryParametersIndex = requestPath . length ( ) ; } int extensionIndex = requestPath . lastIndexOf ( ' ' , queryParametersIndex ) ; if ( extensionIndex == - 1 ) { extensionIndex = queryParametersIndex ; } return requestPath . substring ( 0 , extensionIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a content type instance suitable to represent requested file . It is a trivial a approach using a map of common used file extension . Recognizes only couple most used types ; if extension is not recognized returns { @link #TEXT_HTML } . [CODESPLIT] public static ContentType forFile ( File file ) { Params . notNull ( file , \"File\" ) ; ContentType contentType = FILE_TYPES . get ( Files . getExtension ( file ) ) ; if ( contentType == null ) { log . debug ( \"Unknown content type for |%s|. Replace with default |%s|.\" , file , TEXT_HTML ) ; contentType = TEXT_HTML ; } return contentType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses content type value and returns newly created instance . Given value should obey syntax described by this class . This factory method just delegates { @link #ContentType ( String ) } . If <code > value< / code > argument is null uses { @link #APPLICATION_JSON } as default . [CODESPLIT] public static ContentType valueOf ( String value ) { if ( value == null ) { return ContentType . APPLICATION_JSON ; } return new ContentType ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if content type has a parameter with requested name and value . [CODESPLIT] public boolean hasParameter ( String name , String value ) { Params . notNullOrEmpty ( name , \"Parameter name\" ) ; Params . notNullOrEmpty ( value , \"Parameter value\" ) ; return value . equals ( parameters . get ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get parameter value or null if parameter does not exist . [CODESPLIT] public String getParameter ( String name ) { Params . notNullOrEmpty ( name , \"Parameter name\" ) ; return parameters . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse content type parameters . Given parameters expression should be valid accordingly grammar from class description ; it should not start with parameters separator that is semicolon . [CODESPLIT] private static Map < String , String > parseParameters ( String expression ) { // charset = UTF-8\r Map < String , String > parameters = new HashMap <> ( ) ; int parametersSeparatorIndex = 0 ; for ( ; ; ) { int valueSeparatorIndex = expression . indexOf ( ' ' , parametersSeparatorIndex ) ; if ( valueSeparatorIndex == - 1 ) { break ; } String name = expression . substring ( parametersSeparatorIndex , valueSeparatorIndex ) . trim ( ) ; ++ valueSeparatorIndex ; parametersSeparatorIndex = expression . indexOf ( ' ' , valueSeparatorIndex ) ; if ( parametersSeparatorIndex == - 1 ) { parametersSeparatorIndex = expression . length ( ) ; } if ( valueSeparatorIndex == parametersSeparatorIndex ) { throw new SyntaxException ( \"Invalid content type parameters |%s|. Value is empty.\" , expression ) ; } if ( parameters . put ( name , expression . substring ( valueSeparatorIndex , parametersSeparatorIndex ) . trim ( ) ) != null ) { throw new SyntaxException ( \"Invalid content type parameters |%s|. Name override |%s|.\" , expression , name ) ; } ++ parametersSeparatorIndex ; } if ( parameters . isEmpty ( ) ) { throw new SyntaxException ( \"Invalid content type parameters |%s|. Missing name/value separator.\" , expression ) ; } return parameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure underlying transaction manager . [CODESPLIT] @ Override public void config ( Config config ) throws Exception { log . trace ( \"config(Config.Element)\" ) ; log . debug ( \"Configure transaction manager |%s|.\" , transactionManager . getClass ( ) ) ; transactionManager . config ( config ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the target file for a given artifact type and filename . This method takes care about eventually creating non existing directories or protect existing files to be overridden . [CODESPLIT] protected final GeneratedFile getTargetFile ( final String artifactName , final String filename , final String logInfo ) { final Folder folder = getGeneratorConfig ( ) . findTargetFolder ( artifactName ) ; final File dir = folder . getCanonicalDir ( ) ; final File file = new File ( dir , filename ) ; // Make sure the folder exists\r if ( ! dir . exists ( ) ) { if ( folder . isCreate ( ) ) { dir . mkdirs ( ) ; } else { throw new IllegalStateException ( \"Directory '\" + dir + \"' does not exist, but configuration does not allow creation: \" + \"<folder name=\\\"\" + folder . getName ( ) + \"\\\" create=\\\"false\\\" ... />\" ) ; } } // Make sure the parent directory for the file exists\r if ( ! file . getParentFile ( ) . exists ( ) ) { file . getParentFile ( ) . mkdirs ( ) ; } if ( file . exists ( ) && ! folder . overrideAllowed ( file ) ) { // Skip file because override is not allowed\r return new GeneratedFile ( file , logInfo , true ) ; } return new GeneratedFile ( file , logInfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a generated artifact to a file . [CODESPLIT] protected final void write ( @ NotNull final GeneratedArtifact artifact ) throws GenerateException { Contract . requireArgNotNull ( \"artifact\" , artifact ) ; final GeneratedFile genFile = getTargetFile ( artifact . getName ( ) , artifact . getPathAndName ( ) , null ) ; if ( genFile . isSkip ( ) ) { LOG . debug ( \"Omitted already existing file: {} [{}]\" , genFile , artifact ) ; } else { LOG . debug ( \"Writing file:  {} [{}]\" , genFile , artifact ) ; try { final OutputStream out = new BufferedOutputStream ( new FileOutputStream ( genFile . getTmpFile ( ) ) ) ; try { out . write ( artifact . getData ( ) ) ; } finally { out . close ( ) ; } genFile . persist ( ) ; } catch ( final IOException ex ) { throw new GenerateException ( \"Error writing artifact '\" + artifact + \"' to '\" + artifact . getPathAndName ( ) + \"'!\" , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize instance fields from managed class configuration object . [CODESPLIT] @ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { Config config = managedClass . getConfig ( ) ; if ( config == null ) { return ; } List < Config > fields = config . findChildren ( \"instance-field\" ) ; if ( ! fields . isEmpty ( ) && ! InstanceType . POJO . equals ( managedClass . getInstanceType ( ) ) ) { throw new BugError ( \"Cannot assign instance field on non %s type.\" , InstanceType . POJO ) ; } for ( Config field : fields ) { Classes . setFieldValue ( instance , field . getAttribute ( \"name\" ) , field . getAttribute ( \"value\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan annotations for managed classes that requires implementation . Annotations are processed only for managed classes that have { @link #implementationClass } that is primary source scanned for annotation . If an annotation is not present into implementation class try to find it on interface ( s ) . See <a href = #annotations > Annotations< / a > section from class description . [CODESPLIT] private void scanAnnotations ( ) { // set remote type and request URI path from @Remote, @Controller or @Service\r boolean remoteType = false ; Controller controllerAnnotation = getAnnotation ( implementationClass , Controller . class ) ; if ( controllerAnnotation != null ) { remoteType = true ; requestPath = controllerAnnotation . value ( ) ; } Service serviceAnnotation = getAnnotation ( implementationClass , Service . class ) ; if ( serviceAnnotation != null ) { remoteType = true ; requestPath = serviceAnnotation . value ( ) ; } Remote remoteAnnotation = getAnnotation ( implementationClass , Remote . class ) ; if ( remoteAnnotation != null ) { remoteType = true ; } RequestPath requestPathAnnotation = getAnnotation ( implementationClass , RequestPath . class ) ; if ( requestPathAnnotation != null ) { requestPath = requestPathAnnotation . value ( ) ; } if ( requestPath != null && requestPath . isEmpty ( ) ) { requestPath = null ; } if ( remoteType ) { remotelyAccessible = true ; } // set transactional and immutable type\r boolean transactionalType = hasAnnotation ( implementationClass , Transactional . class ) ; boolean immutableType = hasAnnotation ( implementationClass , Immutable . class ) ; if ( ! transactionalType && immutableType ) { throw new BugError ( \"@Immutable annotation without @Transactional on class |%s|.\" , implementationClass . getName ( ) ) ; } if ( transactionalType && ! instanceType . isPROXY ( ) ) { throw new BugError ( \"@Transactional requires |%s| type but found |%s| on |%s|.\" , InstanceType . PROXY , instanceType , implementationClass ) ; } Class < ? extends Interceptor > classInterceptor = getInterceptorClass ( implementationClass ) ; boolean publicType = hasAnnotation ( implementationClass , Public . class ) ; // managed classes does not support public inheritance\r for ( Method method : implementationClass . getDeclaredMethods ( ) ) { final int modifiers = method . getModifiers ( ) ; if ( Modifier . isStatic ( modifiers ) || ! Modifier . isPublic ( modifiers ) ) { // scans only public and non-static methods\r continue ; } Method interfaceMethod = getInterfaceMethod ( method ) ; ManagedMethod managedMethod = null ; boolean remoteMethod = hasAnnotation ( method , Remote . class ) ; if ( ! remoteMethod ) { remoteMethod = remoteType ; } if ( hasAnnotation ( method , Local . class ) ) { if ( ! remoteMethod ) { throw new BugError ( \"@Local annotation on not remote method |%s|.\" , method ) ; } remoteMethod = false ; } if ( remoteMethod ) { // if at least one owned managed method is remote this managed class become remote too\r remotelyAccessible = true ; } // load method interceptor annotation and if missing uses class annotation; is legal for both to be null\r Class < ? extends Interceptor > methodInterceptor = getInterceptorClass ( method ) ; if ( methodInterceptor == null ) { methodInterceptor = classInterceptor ; } // if method is intercepted, either by method or class annotation, create intercepted managed method\r if ( methodInterceptor != null ) { if ( ! instanceType . isPROXY ( ) && ! remotelyAccessible ) { throw new BugError ( \"@Intercepted method |%s| supported only on PROXY type or remote accessible classes.\" , method ) ; } managedMethod = new ManagedMethod ( this , methodInterceptor , interfaceMethod ) ; } // handle remote accessible methods\r boolean publicMethod = hasAnnotation ( method , Public . class ) ; if ( publicMethod && ! remotelyAccessible ) { throw new BugError ( \"@Public annotation on not remote method |%s|.\" , method ) ; } if ( ! publicMethod ) { publicMethod = publicType ; } if ( hasAnnotation ( method , Private . class ) ) { if ( ! remotelyAccessible ) { throw new BugError ( \"@Private annotation on not remote method |%s|.\" , method ) ; } publicMethod = false ; } RequestPath methodPath = getAnnotation ( method , RequestPath . class ) ; if ( ! remotelyAccessible && methodPath != null ) { throw new BugError ( \"@MethodPath annotation on not remote method |%s|.\" , method ) ; } if ( remoteMethod ) { if ( managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } managedMethod . setRequestPath ( methodPath != null ? methodPath . value ( ) : null ) ; managedMethod . setRemotelyAccessible ( remoteMethod ) ; managedMethod . setAccess ( publicMethod ? Access . PUBLIC : Access . PRIVATE ) ; } // handle declarative transaction\r // 1. allow transactional only on PROXY\r // 2. do not allow immutable on method if not transactional\r // 3. do not allow mutable on method if not transactional\r // 4. if PROXY create managed method if not already created from above remote method logic\r if ( ! transactionalType ) { transactionalType = hasAnnotation ( method , Transactional . class ) ; } if ( transactionalType ) { transactional = true ; if ( ! instanceType . isPROXY ( ) ) { throw new BugError ( \"@Transactional requires |%s| type but found |%s|.\" , InstanceType . PROXY , instanceType ) ; } } boolean immutable = hasAnnotation ( method , Immutable . class ) ; if ( immutable && ! transactional ) { log . debug ( \"@Immutable annotation without @Transactional on method |%s|.\" , method ) ; } if ( ! immutable ) { immutable = immutableType ; } if ( hasAnnotation ( method , Mutable . class ) ) { if ( ! transactional ) { log . debug ( \"@Mutable annotation without @Transactional on method |%s|.\" , method ) ; } immutable = false ; } if ( instanceType . isPROXY ( ) && managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } if ( transactional ) { managedMethod . setTransactional ( true ) ; managedMethod . setImmutable ( immutable ) ; } // handle asynchronous mode\r // 1. instance type should be PROXY or managed class should be flagged for remote access\r // 2. transactional method cannot be executed asynchronously\r // 3. asynchronous method should be void\r boolean asynchronousMethod = hasAnnotation ( method , Asynchronous . class ) ; if ( asynchronousMethod ) { if ( ! instanceType . isPROXY ( ) && ! remotelyAccessible ) { throw new BugError ( \"Not supported instance type |%s| for asynchronous method |%s|.\" , instanceType , method ) ; } if ( transactional ) { throw new BugError ( \"Transactional method |%s| cannot be executed asynchronous.\" , method ) ; } if ( ! Types . isVoid ( method . getReturnType ( ) ) ) { throw new BugError ( \"Asynchronous method |%s| must be void.\" , method ) ; } // at this point either instance type is PROXY or remote flag is true; checked by above bug error\r // both conditions has been already processed with managed method creation\r // so managed method must be already created\r managedMethod . setAsynchronous ( asynchronousMethod ) ; } Cron cronMethod = getAnnotation ( method , Cron . class ) ; if ( cronMethod != null ) { // if (!instanceType.isPROXY()) {\r // throw new BugError(\"Not supported instance type |%s| for cron method |%s|.\", instanceType, method);\r // }\r if ( remotelyAccessible ) { throw new BugError ( \"Remote accessible method |%s| cannot be executed by cron.\" , method ) ; } if ( transactional ) { throw new BugError ( \"Transactional method |%s| cannot be executed by cron.\" , method ) ; } if ( ! Types . isVoid ( method . getReturnType ( ) ) ) { throw new BugError ( \"Cron method |%s| must be void.\" , method ) ; } if ( managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } managedMethod . setCronExpression ( cronMethod . value ( ) ) ; cronMethodsPool . add ( managedMethod ) ; autoInstanceCreation = true ; } // store managed method, if created, to managed methods pool\r if ( managedMethod != null ) { methodsPool . put ( interfaceMethod , managedMethod ) ; if ( managedMethod . isRemotelyAccessible ( ) && netMethodsPool . put ( method . getName ( ) , managedMethod ) != null ) { throw new BugError ( \"Overloading is not supported for net method |%s|.\" , managedMethod ) ; } } } for ( Field field : implementationClass . getDeclaredFields ( ) ) { ContextParam contextParam = field . getAnnotation ( ContextParam . class ) ; if ( contextParam != null ) { field . setAccessible ( true ) ; contextParamFields . put ( contextParam . value ( ) , field ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load optional implementation class from class descriptor and applies insanity checks . Load implementation class from <code > class< / code > attribute from descriptor . If <code > class< / code > attribute not present return null . <p > Beside loading implementation class this utility method performs sanity checks and throws configuration exception if : <ul > <li > instance type requires implementation but <code > class< / code > attribute is missing <li > instance type does not require implementation but <code > class< / code > attribute is present <li > class not found on run - time class path <li > implementation class is a Java interface <li > implementation class is abstract <li > implementation class implements managed life cycle but instance scope is not { @link InstanceScope#APPLICATION } . < / ul > [CODESPLIT] private Class < ? > loadImplementationClass ( Config descriptor ) throws ConfigException { String implementationName = descriptor . getAttribute ( \"class\" ) ; if ( implementationName == null ) { if ( instanceType . requiresImplementation ( ) ) { throw new ConfigException ( \"Managed type |%s| requires <class> attribute. See class descriptor |%s|.\" , instanceType , descriptor ) ; } return null ; } if ( ! instanceType . requiresImplementation ( ) ) { throw new ConfigException ( \"Managed type |%s| forbids <class> attribute. See class descriptor |%s|.\" , instanceType , descriptor ) ; } Class < ? > implementationClass = Classes . forOptionalName ( implementationName ) ; if ( implementationClass == null ) { throw new ConfigException ( \"Managed class implementation |%s| not found.\" , implementationName ) ; } if ( implementationClass . isInterface ( ) ) { throw new ConfigException ( \"Managed class implementation |%s| cannot be an interface. See class descriptor |%s|.\" , implementationClass , descriptor ) ; } int implementationModifiers = implementationClass . getModifiers ( ) ; if ( Modifier . isAbstract ( implementationModifiers ) ) { throw new ConfigException ( \"Managed class implementation |%s| cannot be abstract. See class descriptor |%s|.\" , implementationClass , descriptor ) ; } if ( Types . isKindOf ( implementationClass , ManagedLifeCycle . class ) && ! InstanceScope . APPLICATION . equals ( instanceScope ) ) { throw new ConfigException ( \"Bad scope |%s| used with managed life cycle. See class descriptor |%s|.\" , instanceScope , descriptor ) ; } return implementationClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load interface classes from class descriptor . Attempt to load interface classes from <code > interface< / code > attribute or child elements . If none found returns implementation class that should be already initialized . <p > Perform sanity checks on loaded interface classes and throws configuration exception is : <ul > <li > instance type requires interface but none found <li > <code > name< / code > attribute is missing from child element <li > interface class not found on run - time class path <li > implementation class is not implemented by already configured implementation class . < / ul > <p > This utility method should be loaded after { @link #loadImplementationClass ( Config ) } otherwise behavior is not defined . [CODESPLIT] private Class < ? > [ ] loadInterfaceClasses ( Config descriptor ) throws ConfigException { List < String > interfaceNames = new ArrayList <> ( ) ; if ( ! descriptor . hasChildren ( ) ) { if ( ! descriptor . hasAttribute ( \"interface\" ) ) { if ( instanceType . requiresInterface ( ) ) { throw new ConfigException ( \"Managed type |%s| requires <interface> attribute. See class descriptor |%s|.\" , instanceType , descriptor ) ; } // if interface is not required and is missing uses implementation class\r return new Class < ? > [ ] { implementationClass } ; } interfaceNames . add ( descriptor . getAttribute ( \"interface\" ) ) ; if ( \"REMOTE\" . equals ( descriptor . getAttribute ( \"type\" ) ) ) { String url = descriptor . getAttribute ( \"url\" ) ; if ( url == null || url . isEmpty ( ) ) { throw new ConfigException ( \"Managed type REMOTE requires <url> attribute. See class descriptor |%s|.\" , descriptor ) ; } if ( url . startsWith ( \"${\" ) ) { throw new ConfigException ( \"Remote implementation <url> property not resolved. See class descriptor |%s|.\" , descriptor ) ; } } } else { for ( int i = 0 ; i < descriptor . getChildrenCount ( ) ; ++ i ) { String interfaceName = descriptor . getChild ( i ) . getAttribute ( \"name\" ) ; if ( interfaceName == null ) { throw new ConfigException ( \"Missing <name> attribute from interface declaration. See class descriptor |%s|.\" , descriptor ) ; } interfaceNames . add ( interfaceName ) ; } } Class < ? > [ ] interfaceClasses = new Class < ? > [ interfaceNames . size ( ) ] ; for ( int i = 0 ; i < interfaceNames . size ( ) ; ++ i ) { final String interfaceName = interfaceNames . get ( i ) ; final Class < ? > interfaceClass = Classes . forOptionalName ( interfaceName ) ; if ( interfaceClass == null ) { throw new ConfigException ( \"Managed class interface |%s| not found.\" , interfaceName ) ; } if ( Types . isKindOf ( interfaceClass , ManagedLifeCycle . class ) ) { autoInstanceCreation = true ; } if ( instanceType . requiresInterface ( ) && ! interfaceClass . isInterface ( ) ) { throw new ConfigException ( \"Managed type |%s| requires interface to make Java Proxy happy but got |%s|.\" , instanceType , interfaceClass ) ; } if ( implementationClass != null && ! Types . isKindOf ( implementationClass , interfaceClass ) ) { throw new ConfigException ( \"Implementation |%s| is not a kind of interface |%s|.\" , implementationClass , interfaceClass ) ; } interfaceClasses [ i ] = interfaceClass ; } return interfaceClasses ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return instance scope loaded from class descriptor <code > scope< / code > attribute . If scope is not defined use { @link InstanceScope#APPLICATION } as default value . [CODESPLIT] private InstanceScope loadInstanceScope ( Config descriptor ) throws ConfigException { InstanceScope instanceScope = descriptor . getAttribute ( \"scope\" , InstanceScope . class , InstanceScope . APPLICATION ) ; if ( ! container . hasScopeFactory ( instanceScope ) ) { throw new ConfigException ( \"Not registered managed instance scope value |%s|. See class descriptor |%s|.\" , instanceScope , descriptor ) ; } return instanceScope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return instance type loaded from class descriptor <code > type< / code > attribute . If type is not defined uses { @link InstanceType#POJO } as default value . [CODESPLIT] private InstanceType loadInstanceType ( Config descriptor ) throws ConfigException { InstanceType instanceType = descriptor . getAttribute ( \"type\" , InstanceType . class , InstanceType . POJO ) ; if ( ! container . hasInstanceFactory ( instanceType ) ) { throw new ConfigException ( \"Not registered managed instance type value |%s|. See class descriptor |%s|.\" , instanceType , descriptor ) ; } return instanceType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load remote class URL from class descriptor <code > url< / code > attribute . This getter does not perform URL validation ; it returns URL value as declared by attribute . [CODESPLIT] private String loadImplementationURL ( Config descriptor ) throws ConfigException { String implementationURL = descriptor . getAttribute ( \"url\" ) ; if ( instanceType . equals ( InstanceType . REMOTE ) && implementationURL == null ) { throw new ConfigException ( \"Remote managed class requires <url> attribute. See class descriptor |%s|.\" , descriptor ) ; } return implementationURL ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get implementation class constructor . Managed class mandates a single constructor with parameters no matter if private or formal parameters count . If both default constructor and constructor with parameters are defined this method returns constructor with parameters . Returns null if implementation class is missing . [CODESPLIT] private static Constructor < ? > getDeclaredConstructor ( Class < ? > implementationClass ) { if ( implementationClass == null ) { return null ; } Constructor < ? > [ ] declaredConstructors = ( Constructor < ? > [ ] ) implementationClass . getDeclaredConstructors ( ) ; if ( declaredConstructors . length == 0 ) { throw new BugError ( \"Invalid implementation class |%s|. Missing constructor.\" , implementationClass ) ; } Constructor < ? > constructor = null ; for ( Constructor < ? > declaredConstructor : declaredConstructors ) { // synthetic constructors are created by compiler to circumvent JVM limitations, JVM that is not evolving with\r // the same speed as the language; for example, to allow outer class to access private members on a nested class\r // compiler creates a constructor with a single argument of very nested class type\r if ( declaredConstructor . isSynthetic ( ) ) { continue ; } if ( declaredConstructor . getParameterTypes ( ) . length == 0 ) { continue ; } if ( declaredConstructor . getAnnotation ( Test . class ) != null ) { continue ; } if ( constructor != null ) { throw new BugError ( \"Implementation class |%s| has not a single constructor with parameters.\" , implementationClass ) ; } constructor = declaredConstructor ; } if ( constructor == null ) { constructor = declaredConstructors [ 0 ] ; } constructor . setAccessible ( true ) ; return constructor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan class dependencies declared by { @link Inject } annotation . This method scans all fields no matter private protected or public . Anyway it is considered a bug if inject annotation is found on final or static field . <p > Returns a collection of reflective fields with accessibility set but in not particular order . If given class argument is null returns empty collection . [CODESPLIT] private static Collection < Field > scanDependencies ( Class < ? > clazz ) { if ( clazz == null ) { return Collections . emptyList ( ) ; } Collection < Field > dependencies = new ArrayList <> ( ) ; for ( Field field : clazz . getDeclaredFields ( ) ) { if ( ! field . isAnnotationPresent ( Inject . class ) ) { continue ; } if ( Modifier . isFinal ( field . getModifiers ( ) ) ) { throw new BugError ( \"Attempt to inject final field |%s|.\" , field . getName ( ) ) ; } if ( Modifier . isStatic ( field . getModifiers ( ) ) ) { throw new BugError ( \"Attempt to inject static field |%s|.\" , field . getName ( ) ) ; } field . setAccessible ( true ) ; dependencies . add ( field ) ; } return dependencies ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize implementation class static not final fields . Static initializer reads name / value pairs from <code > static - field< / code > configuration element see sample below . String value is converted to instance field type using { @link Converter#asObject ( String Class ) } utility . This means that configured value should be convertible to field type otherwise { @link ConverterException } is thrown . <p > In sample there is a <code > person< / code > managed instance that has a configuration section . Configuration declares three static fields that will be initialized with defined values when managed class is created . [CODESPLIT] private void initializeStaticFields ( ) throws ConfigException { if ( config == null ) { return ; } for ( Config config : config . findChildren ( \"static-field\" ) ) { String fieldName = config . getAttribute ( \"name\" ) ; if ( fieldName == null ) { throw new ConfigException ( \"Missing <name> attribute from static field initialization |%s|.\" , config . getParent ( ) ) ; } if ( ! config . hasAttribute ( \"value\" ) ) { throw new ConfigException ( \"Missing <value> attribute from static field initialization |%s|.\" , config . getParent ( ) ) ; } Field field = Classes . getOptionalField ( implementationClass , fieldName ) ; if ( field == null ) { throw new ConfigException ( \"Missing managed class static field |%s#%s|.\" , implementationClass , fieldName ) ; } int modifiers = field . getModifiers ( ) ; if ( ! Modifier . isStatic ( modifiers ) ) { throw new ConfigException ( \"Attempt to execute static initialization on instance field |%s#%s|.\" , implementationClass , fieldName ) ; } Object value = config . getAttribute ( \"value\" , field . getType ( ) ) ; log . debug ( \"Intialize static field |%s#%s| |%s|\" , implementationClass , fieldName , value ) ; Classes . setFieldValue ( null , field , config . getAttribute ( \"value\" , field . getType ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build and return this managed class string representation . [CODESPLIT] private String buildStringRepresentation ( Config descriptor ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( descriptor . getName ( ) ) ; builder . append ( ' ' ) ; if ( implementationClass != null ) { builder . append ( implementationClass . getName ( ) ) ; builder . append ( ' ' ) ; } for ( Class < ? > interfaceClass : interfaceClasses ) { builder . append ( interfaceClass . getName ( ) ) ; builder . append ( ' ' ) ; } builder . append ( instanceType ) ; builder . append ( ' ' ) ; builder . append ( instanceScope ) ; builder . append ( ' ' ) ; builder . append ( remotelyAccessible ? \"NET\" : \"LOCAL\" ) ; if ( implementationURL != null ) { builder . append ( ' ' ) ; builder . append ( implementationURL ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get class annotation or null if none found . This getter uses extended annotation searching scope : it searches first on given class then tries with all class interfaces . Note that only interfaces are used as alternative for annotation search . Super class is not included . <p > Returns null if no annotation found on base class or interfaces . [CODESPLIT] private static < T extends Annotation > T getAnnotation ( Class < ? > clazz , Class < T > annotationClass ) { T annotation = clazz . getAnnotation ( annotationClass ) ; if ( annotation == null ) { for ( Class < ? > interfaceClass : clazz . getInterfaces ( ) ) { annotation = interfaceClass . getAnnotation ( annotationClass ) ; if ( annotation != null ) { break ; } } } return annotation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if class has requested annotation . This predicate uses extended annotation searching scope : it searches first on given class then tries with all class interfaces . Note that only interfaces are used as alternative for annotation search . Super class is not included . <p > Returns false if no annotation found on base class or interfaces . [CODESPLIT] private static boolean hasAnnotation ( Class < ? > clazz , Class < ? extends Annotation > annotationClass ) { Annotation annotation = clazz . getAnnotation ( annotationClass ) ; if ( annotation != null ) { return true ; } for ( Class < ? > interfaceClass : clazz . getInterfaces ( ) ) { annotation = interfaceClass . getAnnotation ( annotationClass ) ; if ( annotation != null ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get method annotation or null if none found . This getter uses extended annotation searching scope : it searches first on given method declaring class then tries with all class interfaces . Note that only interfaces are used as alternative for method annotation search . Super class is not included . <p > Returns null if no method annotation found on base class or interfaces . [CODESPLIT] private static < T extends Annotation > T getAnnotation ( Method method , Class < T > annotationClass ) { T annotation = method . getAnnotation ( annotationClass ) ; if ( annotation == null ) { for ( Class < ? > interfaceClass : method . getDeclaringClass ( ) . getInterfaces ( ) ) { try { annotation = interfaceClass . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) . getAnnotation ( annotationClass ) ; if ( annotation != null ) { return annotation ; } } catch ( NoSuchMethodException unused ) { } } } return annotation ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Java reflective method from interface . This getter attempt to locate a method with the same signature as requested base class method in any interface the declaring class may have . If no method found in interfaces or no interface present return given base class method . If requested base class method is declared in multiple interfaces this getter returns the first found but there is no guarantee for order . [CODESPLIT] private static Method getInterfaceMethod ( Method method ) { for ( Class < ? > interfaceClass : method . getDeclaringClass ( ) . getInterfaces ( ) ) { try { return interfaceClass . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; } catch ( NoSuchMethodException unused ) { } } return method ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get class value of intercepted annotation of a given class . Returns null if given class has no { @link Intercepted } annotation . [CODESPLIT] private static Class < ? extends Interceptor > getInterceptorClass ( Class < ? > clazz ) { Intercepted intercepted = getAnnotation ( clazz , Intercepted . class ) ; return intercepted != null ? intercepted . value ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get class value of intercepted annotation of a given method . Returns null if given method has no { @link Intercepted } annotation . [CODESPLIT] private static Class < ? extends Interceptor > getInterceptorClass ( Method method ) { Intercepted intercepted = getAnnotation ( method , Intercepted . class ) ; return intercepted != null ? intercepted . value ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new instance of <class > typeAdapter< / class > passing <class > baseTypeAdapter< / class > as the only constructor argument . [CODESPLIT] private TypeHandler < ? > instantiate ( Class < ? extends TypeHandler < ? > > typeAdapter , String parameter ) { try { final Constructor < ? extends TypeHandler < ? > > constructor = typeAdapter . getConstructor ( String . class ) ; return constructor . newInstance ( parameter ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Instantiates a new { @code TypeAdapter } which is capable of handling { @code type } . <p > If no such adapter exists the old one is returned . [CODESPLIT] public TypeHandler getHandler ( Class < ? > type , String parameter ) { if ( type == null ) { return null ; } else if ( type . isArray ( ) ) { return new ArrayTypeHandler ( parameter , getHandler ( type . getComponentType ( ) , parameter ) ) ; } else if ( adapters . containsKey ( type ) ) { return instantiate ( adapters . get ( type ) , parameter ) ; } else { throw new IllegalArgumentException ( \"Unknown type: \" + type . getName ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a new { @code AbstractTypeAdapter } . <p > After registering an adapter { @link #getHandler ( Class String ) } is able to return it . [CODESPLIT] public void register ( Class < ? extends TypeHandler < ? > > adapterClass ) { final Class < ? > targetType = ( ( TypeHandler < ? > ) instantiate ( adapterClass , null ) ) . getType ( ) ; adapters . put ( targetType , adapterClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes { @code inputFile } write output to { @code outputFile } and return the resulting counts using most of fit s default components . [CODESPLIT] @ Override public final Counts run ( final File inputFile , final File outputFile ) { Counts result = null ; FileSystemDirectoryHelper dirHelper = new FileSystemDirectoryHelper ( ) ; RunnerHelper currentRunner = DependencyManager . getOrCreate ( RunnerHelper . class ) ; RunnerHelper helper = new RunnerHelper ( ) ; DependencyManager . inject ( RunnerHelper . class , helper ) ; helper . setFile ( dirHelper . rel2abs ( System . getProperty ( \"user.dir\" ) , inputFile . toString ( ) ) ) ; helper . setResultFile ( dirHelper . rel2abs ( System . getProperty ( \"user.dir\" ) , outputFile . toString ( ) ) ) ; helper . setRunner ( this ) ; helper . setHelper ( dirHelper ) ; try { result = process ( inputFile , outputFile ) ; } catch ( Exception e ) { System . err . printf ( \"%s while processing %s -> %s%n\" , e , inputFile , outputFile ) ; System . err . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } finally { DependencyManager . inject ( RunnerHelper . class , currentRunner ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set value to object field identified by object property path . Form this class perspective an object is a graph of value types . A value type is a primitive value or a related boxing class . Also any class that can be converted to a primitive are included ; for example { @link File } or { @link URL } are value types since can be converted to / from strings . Opposite to value types are compound entities that is objects arrays and collections that aggregates value types or other compound entities . <p > To sum up an object is a graph with compound entities and value types as nodes where value types are leafs . The <code > propertyPath< / code > is the path through graph nodes till reach the value type and basically is a dot separated field names list . [CODESPLIT] private void setValue ( String propertyPath , Object value ) throws ConverterException , IllegalAccessException { List < String > nodeIDs = Strings . split ( propertyPath , ' ' ) ; int lastNodeIndex = nodeIDs . size ( ) - 1 ; Node node = new ObjectNode ( object ) ; for ( int index = 0 ; index < lastNodeIndex ; index ++ ) { node = node . getChild ( nodeIDs . get ( index ) ) ; if ( node == null ) { return ; } } node . setValue ( nodeIDs . get ( lastNodeIndex ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return field class or actual type argument if given field is a list . [CODESPLIT] private static Class < ? > type ( Field field ) { if ( Types . isKindOf ( field . getType ( ) , List . class ) ) { // for the purpose of this implementation only first parameterized\r // type matters, as result from list declaration List<E>\r return ( Class < ? > ) ( ( ParameterizedType ) field . getGenericType ( ) ) . getActualTypeArguments ( ) [ 0 ] ; } return field . getType ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get dependency value of requested type . See class description for a discussion about supported types and circular dependencies . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected static Object getDependencyValue ( ManagedClassSPI hostManagedClass , Class < ? > type ) { Stack < Class < ? > > stackTrace = dependenciesStack . get ( ) ; if ( stackTrace == null ) { stackTrace = new Stack <> ( ) ; dependenciesStack . set ( stackTrace ) ; } ContainerSPI container = hostManagedClass . getContainer ( ) ; if ( stackTrace . contains ( type ) ) { try { // add current dependency class to reveal what dependency from stack is circular\r stackTrace . add ( type ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( \"Circular dependency. Dependencies trace follows:\\r\\n\" ) ; for ( Class < ? > stackTraceClass : stackTrace ) { builder . append ( \"\\t- \" ) ; builder . append ( stackTraceClass . getName ( ) ) ; builder . append ( \"\\r\\n\" ) ; } log . error ( builder . toString ( ) ) ; throw new BugError ( \"Circular dependency for |%s|.\" , type . getName ( ) ) ; } finally { // takes care to current thread stack trace is removed\r dependenciesStack . remove ( ) ; } } stackTrace . push ( type ) ; try { ManagedClassSPI dependencyManagedClass = container . getManagedClass ( type ) ; if ( isProxyRequired ( hostManagedClass , dependencyManagedClass ) ) { // if scope proxy is required returns a Java Proxy handled by ScopeProxyHandler\r ScopeProxyHandler < ? > handler = new ScopeProxyHandler <> ( container , type ) ; return Proxy . newProxyInstance ( dependencyManagedClass . getImplementationClass ( ) . getClassLoader ( ) , dependencyManagedClass . getInterfaceClasses ( ) , handler ) ; } Object value = container . getOptionalInstance ( ( Class < ? super Object > ) type ) ; if ( value != null ) { // if dependency type is a managed class returns it value from factory\r return value ; } if ( Types . isKindOf ( type , AppFactory . class ) ) { // handle ApFactory and its hierarchy since it is a special case\r return container ; } if ( Classes . isInstantiable ( type ) ) { // if requested type is instantiable POJO create a new empty instance of requested type\r return Classes . newInstance ( type ) ; } // TODO: test value instance of\r // if FactoryBean consider it as factory and substitute value\r // e.g. value = ((FactoryBean)value).getInstance(value.getClass())\r // all attempts to create dependency value has fallen\r throw new BugError ( \"Dependency |%s| not resolved for |%s|.\" , type . getName ( ) , hostManagedClass ) ; } finally { stackTrace . pop ( ) ; // do not remove stack trace after outermost call finished, i.e. when stack trace is empty\r // leave it on thread local for reuse, in order to avoid unnecessary object creation\r } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare host and dependency managed classes scope and decide if scope proxy is required . Current implementation enable scope proxy only when dependency has { @link InstanceScope#SESSION } scope . [CODESPLIT] private static boolean isProxyRequired ( ManagedClassSPI hostManagedClass , ManagedClassSPI dependencyManagedClass ) { if ( dependencyManagedClass != null ) { InstanceScope dependencyScope = dependencyManagedClass . getInstanceScope ( ) ; if ( InstanceScope . THREAD . equals ( dependencyScope ) ) { return InstanceScope . APPLICATION . equals ( hostManagedClass . getInstanceScope ( ) ) ; } return InstanceScope . SESSION . equals ( dependencyScope ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the content of the temporary file with the possibly existing target file . If both are equal the temporary file is deleted . Otherwise the old target file is deleted and the new generated file is renamed . This prevents time stamp changes for the target file if nothing changed since the last generation . [CODESPLIT] public final void persist ( ) { if ( persisted ) { // Do nothing if already done\r return ; } try { // Compare new and old file\r if ( FileUtils . contentEquals ( tmpFile , file ) ) { LOG . debug ( \"Omitted: {} {}\" , getPath ( ) , logInfo ) ; if ( ! tmpFile . delete ( ) ) { tmpFile . deleteOnExit ( ) ; } } else { if ( file . exists ( ) && ! file . delete ( ) ) { throw new IOException ( \"Wasn't able to delete file \" + file ) ; } if ( ! tmpFile . renameTo ( file ) ) { throw new IOException ( \"Wasn't able to rename temporary file \" + tmpFile + \" to \" + file ) ; } LOG . info ( \"Generated: {} {}\" , getPath ( ) , logInfo ) ; } persisted = true ; } catch ( final IOException ex ) { throw new RuntimeException ( \"Error comparing content: tmp=\" + tmpFile + \", target=\" + file + logInfo , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an observable stream of element states . Compares entities using { @link Object#equals ( java . lang . Object ) } to detect changes . [CODESPLIT] StoppableObservable < TEntity > getObservable ( Scheduler scheduler ) { return runAsync ( scheduler , ( rx . Observer < ? super TEntity > observer , Subscription subscription ) -> { TEntity previousEntity ; try { previousEntity = read ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException ex ) { observer . onError ( ex ) ; return ; } observer . onNext ( previousEntity ) ; while ( endCondition == null || ! endCondition . test ( previousEntity ) ) { try { sleep ( pollingInterval * 1000 ) ; } catch ( InterruptedException ex ) { } if ( subscription . isUnsubscribed ( ) ) { break ; } TEntity newEntity ; try { newEntity = read ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException ex ) { observer . onError ( ex ) ; return ; } if ( ! newEntity . equals ( previousEntity ) ) { observer . onNext ( newEntity ) ; } previousEntity = newEntity ; } observer . onCompleted ( ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers one or more default links for a specific relation type . These links are used when no links with this relation type are provided by the server . [CODESPLIT] public final void setDefaultLink ( String rel , String ... hrefs ) { if ( hrefs == null || hrefs . length == 0 ) { defaultLinks . remove ( rel ) ; } else { defaultLinks . put ( rel , stream ( hrefs ) . map ( uri :: resolve ) . collect ( toSet ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a default link template for a specific relation type . This template is used when no template with this relation type is provided by the server . [CODESPLIT] public final void setDefaultLinkTemplate ( String rel , String href ) { if ( href == null ) { defaultLinkTemplates . remove ( rel ) ; } else { defaultLinkTemplates . put ( rel , href ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a REST request and wraps HTTP status codes in appropriate { @link Exception } types . [CODESPLIT] protected HttpResponse executeAndHandle ( Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { HttpResponse response = execute ( request ) ; handleResponse ( response , request ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a REST request adding any configured { @link #defaultHeaders } . [CODESPLIT] protected HttpResponse execute ( Request request ) throws IOException { defaultHeaders . forEach ( request :: addHeader ) ; return executor . execute ( request ) . returnResponse ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles the response of a REST request and wraps HTTP status codes in appropriate { @link Exception } types . [CODESPLIT] protected void handleResponse ( HttpResponse response , Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { handleLinks ( response ) ; handleCapabilities ( response ) ; handleErrors ( response , request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps HTTP status codes in appropriate { @link Exception } types . [CODESPLIT] protected void handleErrors ( HttpResponse response , Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { StatusLine statusLine = response . getStatusLine ( ) ; if ( statusLine . getStatusCode ( ) <= 299 ) { return ; } String message = request + \" responded with \" + statusLine . getStatusCode ( ) + \" \" + statusLine . getReasonPhrase ( ) ; HttpEntity entity = response . getEntity ( ) ; String body ; if ( entity == null ) { body = null ; } else { body = EntityUtils . toString ( entity ) ; Header contentType = entity . getContentType ( ) ; if ( ( contentType != null ) && contentType . getValue ( ) . startsWith ( \"application/json\" ) ) { try { JsonNode messageNode = serializer . readTree ( body ) . get ( \"message\" ) ; if ( messageNode != null ) { message = messageNode . asText ( ) ; } } catch ( JsonProcessingException ex ) { } } } Exception inner = ( body == null ) ? null : new HttpException ( body ) ; switch ( statusLine . getStatusCode ( ) ) { case HttpStatus . SC_BAD_REQUEST : throw new IllegalArgumentException ( message , inner ) ; case HttpStatus . SC_UNAUTHORIZED : //throw new InvalidCredentialException(message); throw new IllegalAccessException ( message ) ; case HttpStatus . SC_FORBIDDEN : throw new IllegalAccessException ( message ) ; case HttpStatus . SC_NOT_FOUND : case HttpStatus . SC_GONE : throw new FileNotFoundException ( message ) ; case HttpStatus . SC_CONFLICT : throw new IllegalStateException ( message , inner ) ; case HttpStatus . SC_PRECONDITION_FAILED : //throw new VersionNotFoundException(message, inner); throw new IllegalStateException ( message , inner ) ; case HttpStatus . SC_REQUESTED_RANGE_NOT_SATISFIABLE : //throw new IndexOutOfBoundsException(message); throw new IllegalStateException ( message , inner ) ; case HttpStatus . SC_REQUEST_TIMEOUT : //throw new TimeoutException(message); default : throw new RuntimeException ( message , inner ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles links embedded in an HTTP response . [CODESPLIT] @ SuppressWarnings ( \"LocalVariableHidesMemberVariable\" ) private void handleLinks ( HttpResponse response ) { Map < String , Map < URI , String > > links = new HashMap <> ( ) ; Map < String , String > linkTemplates = new HashMap <> ( ) ; handleHeaderLinks ( response , links , linkTemplates ) ; HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { Header contentType = entity . getContentType ( ) ; if ( ( contentType != null ) && contentType . getValue ( ) . startsWith ( \"application/json\" ) ) { try { handleBodyLinks ( serializer . readTree ( entity . getContent ( ) ) , links , linkTemplates ) ; } catch ( IOException ex ) { throw new RuntimeException ( ) ; // Body error handling is done elsewhere } } } this . links = unmodifiableMap ( links ) ; this . linkTemplates = unmodifiableMap ( linkTemplates ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles links embedded in HTTP response headers . [CODESPLIT] protected void handleHeaderLinks ( HttpResponse response , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { getLinkHeaders ( response ) . forEach ( header -> { if ( header . getRel ( ) == null ) { return ; } if ( header . isTemplated ( ) ) { linkTemplates . put ( header . getRel ( ) , header . getHref ( ) ) ; } else { getOrAdd ( links , header . getRel ( ) ) . put ( uri . resolve ( header . getHref ( ) ) , header . getTitle ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles links embedded in JSON response bodies . [CODESPLIT] protected void handleBodyLinks ( JsonNode jsonBody , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { if ( jsonBody . getNodeType ( ) != JsonNodeType . OBJECT ) { return ; } JsonNode linksNode = jsonBody . get ( \"_links\" ) ; if ( linksNode == null ) { linksNode = jsonBody . get ( \"links\" ) ; } if ( linksNode == null ) { return ; } linksNode . fields ( ) . forEachRemaining ( x -> { String rel = x . getKey ( ) ; Map < URI , String > linksForRel = getOrAdd ( links , rel ) ; switch ( x . getValue ( ) . getNodeType ( ) ) { case ARRAY : x . getValue ( ) . forEach ( subobj -> { if ( subobj . getNodeType ( ) == JsonNodeType . OBJECT ) { parseLinkObject ( rel , ( ObjectNode ) subobj , linksForRel , linkTemplates ) ; } } ) ; break ; case OBJECT : parseLinkObject ( rel , ( ObjectNode ) x . getValue ( ) , linksForRel , linkTemplates ) ; break ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a JSON object for link information . [CODESPLIT] private void parseLinkObject ( String rel , ObjectNode obj , Map < URI , String > linksForRel , Map < String , String > linkTemplates ) { JsonNode href = obj . findValue ( \"href\" ) ; if ( href == null ) { return ; } JsonNode templated = obj . findValue ( \"templated\" ) ; if ( templated != null && templated . isBoolean ( ) && templated . asBoolean ( ) ) { linkTemplates . put ( rel , href . asText ( ) ) ; } else { JsonNode title = obj . findValue ( \"title\" ) ; linksForRel . put ( uri . resolve ( href . asText ( ) ) , ( title != null && title . getNodeType ( ) == JsonNodeType . STRING ) ? title . asText ( ) : null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the element with the specified key from the map . Creates adds and returns a new element if no match was found . [CODESPLIT] private static Map < URI , String > getOrAdd ( Map < String , Map < URI , String > > map , String key ) { Map < URI , String > value = map . get ( key ) ; if ( value == null ) { map . put ( key , value = new HashMap <> ( ) ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles allowed HTTP methods and other capabilities reported by the server . [CODESPLIT] protected void handleCapabilities ( HttpResponse response ) { allowedMethods = unmodifiableSet ( stream ( response . getHeaders ( \"Allow\" ) ) . filter ( x -> x . getName ( ) . equals ( \"Allow\" ) ) . flatMap ( x -> stream ( x . getElements ( ) ) ) . map ( x -> x . getName ( ) ) . collect ( toSet ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shows whether the server has indicated that a specific HTTP method is currently allowed . [CODESPLIT] protected Optional < Boolean > isMethodAllowed ( String method ) { if ( allowedMethods . isEmpty ( ) ) { return Optional . empty ( ) ; } return Optional . of ( allowedMethods . contains ( method ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates an array which represents the whole { @code ResultSet } . Each element equates to one row in the { @code ResultSet } . The elements have public fields with the same name as the { @code ResultSet } columns . The { @link ScientificDouble } class is automatically used . They can be read them using reflections . [CODESPLIT] public final Object [ ] getRows ( ) throws SQLException { List < Object > result = new ArrayList <> ( ) ; while ( rows . size ( ) > 0 ) { Object [ ] copy = rows . remove ( 0 ) ; Object o = createContainerObject ( ) ; for ( int i = 0 ; i < columnCount ; ++ i ) { setObjectValue ( o , names . get ( i ) , copy [ i ] ) ; } result . add ( o ) ; } while ( resultSet . next ( ) ) { Object o = createContainerObject ( ) ; for ( int col = 0 ; col < columnCount ; ++ col ) { setObjectValue ( o , names . get ( col ) , resultSet . getObject ( col + 1 ) ) ; } result . add ( o ) ; } return result . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Concatenates the { @link Throwable#getLocalizedMessage () } s of the entire { @link Throwable#getCause () } tree . [CODESPLIT] @ SuppressWarnings ( \"ThrowableResultIgnored\" ) public static String getFullMessage ( Throwable throwable ) { StringBuilder builder = new StringBuilder ( ) ; do { builder . append ( throwable . getLocalizedMessage ( ) ) . append ( \"\\n\" ) ; throwable = throwable . getCause ( ) ; } while ( throwable != null ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new instance for given remote managed class . Managed class should be declared as remote into class descriptor . Also { @link ManagedClassSPI#getImplementationURL () } should be not null that is implementation URL should be present into class descriptor . Returned value is a Java proxy that delegates a HTTP - RMI client . <p > This factory method does not check managed class argument validity . It should be not null and configured for remote invocation . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public < T > T newInstance ( ManagedClassSPI managedClass , Object ... args ) { if ( args . length > 0 ) { throw new IllegalArgumentException ( \"REMOTE instance factory does not support arguments.\" ) ; } return getRemoteInstance ( managedClass . getImplementationURL ( ) , ( Class < ? super T > ) managedClass . getInterfaceClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Alternative to { @link #newInstance ( ManagedClassSPI Object ... ) } when implementation URL is obtained at run - time perhaps from user interface . Returned value is a Java proxy that delegates a HTTP - RMI client . This method is designed specifically for { @link AppFactory#getRemoteInstance ( String Class ) } . <p > This factory method does not check arguments validity . Both should be not null and interface class should be an actual Java interface . [CODESPLIT] @ Override public < T > T getRemoteInstance ( String implementationURL , Class < ? super T > interfaceClass ) throws UnsupportedProtocolException { if ( implementationURL == null ) { throw new UnsupportedProtocolException ( new NullPointerException ( \"Null remote implementation URL.\" ) ) ; } String protocol = Strings . getProtocol ( implementationURL ) ; if ( protocol == null ) { throw new UnsupportedProtocolException ( new MalformedURLException ( \"Protocol not found on \" + implementationURL ) ) ; } RemoteFactory remoteFactory = remoteFactories . get ( protocol ) ; if ( remoteFactory == null ) { throw new UnsupportedProtocolException ( \"No remote factory registered for protocol |%s|.\" , protocol ) ; } return remoteFactory . getRemoteInstance ( implementationURL , interfaceClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register all instance post - processors . [CODESPLIT] protected void registerInstanceProcessor ( ) { registerInstanceProcessor ( new InstanceFieldsInjectionProcessor ( ) ) ; registerInstanceProcessor ( new InstanceFieldsInitializationProcessor ( ) ) ; registerInstanceProcessor ( new ConfigurableInstanceProcessor ( ) ) ; registerInstanceProcessor ( new PostConstructInstanceProcessor ( ) ) ; registerInstanceProcessor ( new CronMethodsProcessor ( cronManager ) ) ; registerInstanceProcessor ( new LoggerInstanceProcessor ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register scope factory for the instance scope returned by { @link ScopeFactory#getInstanceScope () } . [CODESPLIT] protected void registerScopeFactory ( ScopeFactory scopeFactory ) { if ( scopeFactory == null ) { log . debug ( \"Register null scope factory to |%s|.\" , InstanceScope . LOCAL ) ; scopeFactories . put ( InstanceScope . LOCAL , null ) ; return ; } final InstanceScope instanceScope = scopeFactory . getInstanceScope ( ) ; log . debug ( \"Register scope factory |%s| to |%s|.\" , scopeFactory . getClass ( ) , instanceScope ) ; if ( scopeFactories . put ( instanceScope , scopeFactory ) != null ) { throw new BugError ( \"Attempt to override instance scope |%s|.\" , instanceScope ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register instance factory to requested instance type . [CODESPLIT] protected void registerInstanceFactory ( InstanceType instanceType , InstanceFactory instanceFactory ) { log . debug ( \"Register instance factory |%s| to |%s|.\" , instanceFactory . getClass ( ) , instanceType ) ; if ( instanceFactories . put ( instanceType , instanceFactory ) != null ) { throw new BugError ( \"Attempt to override instance type |%s|.\" , instanceType ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register instance processor . Only a single instance per processor class is allowed . [CODESPLIT] protected void registerInstanceProcessor ( InstanceProcessor instanceProcessor ) { for ( InstanceProcessor existingInstanceProcessoor : instanceProcessors ) { if ( existingInstanceProcessoor . getClass ( ) . equals ( instanceProcessor . getClass ( ) ) ) { throw new BugError ( \"Attempt to override instance processor |%s|.\" , instanceProcessor . getClass ( ) ) ; } } log . debug ( \"Register instance processor |%s|.\" , instanceProcessor . getClass ( ) ) ; instanceProcessors . add ( instanceProcessor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Register global processors for managed classes . Post - processors are singletons and only one post - processor instance of a type is allowed . [CODESPLIT] protected void registerClassProcessor ( ClassProcessor classProcessor ) { for ( ClassProcessor existingClassProcessoor : classProcessors ) { if ( existingClassProcessoor . getClass ( ) . equals ( classProcessor . getClass ( ) ) ) { throw new BugError ( \"Attempt to override class processor |%s|.\" , classProcessor . getClass ( ) ) ; } } log . debug ( \"Register class processor |%s|.\" , classProcessor . getClass ( ) ) ; classProcessors . add ( classProcessor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create all managed instances registered to this container via external application descriptor . See <a href = #descriptors > Descriptors< / a > for details about application and class descriptors . [CODESPLIT] @ Override public void config ( Config config ) throws ConfigException { log . trace ( \"config(Config)\" ) ; // normalized class descriptors with overrides resolves; should preserve order from external files\r // it is legal for application descriptor to override already defined class descriptor\r // for example user defined ro.gnotis.Fax2MailApp overrides library declared js.core.App\r // <app interface='js.core.App' class='ro.gnotis.Fax2MailApp' />\r // when found an overridden class descriptor replace it with most recent version\r // only class descriptors with single interface can be overridden\r List < Config > classDescriptors = new ArrayList <> ( ) ; for ( Config descriptorsSection : config . findChildren ( \"managed-classes\" , \"web-sockets\" ) ) { CLASS_DESCRIPTORS : for ( Config classDescriptor : descriptorsSection . getChildren ( ) ) { if ( ! classDescriptor . hasChildren ( ) ) { if ( ! classDescriptor . hasAttribute ( \"interface\" ) ) { classDescriptor . setAttribute ( \"interface\" , classDescriptor . getAttribute ( \"class\" ) ) ; } String interfaceClass = classDescriptor . getAttribute ( \"interface\" ) ; for ( int i = 0 ; i < classDescriptors . size ( ) ; ++ i ) { if ( classDescriptors . get ( i ) . hasAttribute ( \"interface\" , interfaceClass ) ) { log . debug ( \"Override class descriptor for interface |%s|.\" , interfaceClass ) ; classDescriptors . set ( i , classDescriptor ) ; continue CLASS_DESCRIPTORS ; } } } classDescriptors . add ( classDescriptor ) ; } } // second step is to actually populate the classes pool from normalized class descriptors list\r for ( Config classDescriptor : classDescriptors ) { // create managed class, a single one per class descriptor, even if there are multiple interfaces\r // if multiple interfaces register the same managed class multiple times, once per interface\r // this way, no mater which interface is used to retrieve the instance it uses in the end the same managed class\r ManagedClass managedClass = new ManagedClass ( this , classDescriptor ) ; log . debug ( \"Register managed class |%s|.\" , managedClass ) ; for ( Class < ? > interfaceClass : managedClass . getInterfaceClasses ( ) ) { classesPool . put ( interfaceClass , managedClass ) ; } for ( ClassProcessor classProcessor : classProcessors ) { classProcessor . postProcessClass ( managedClass ) ; } } convertersInitialization ( config ) ; pojoStaticInitialization ( config ) ; // special handling for this container instance accessed via application context\r // need to ensure this container instance is reused and not to create a new one\r ManagedClassSPI appContext = classesPool . get ( AppContext . class ) ; // application context can be null on tests\r // also on tests application context interface can be implemented by mock class not in container hierarchy\r if ( appContext != null && Types . isKindOf ( appContext . getImplementationClass ( ) , ContainerSPI . class ) ) { log . debug ( \"Persist container instance on application scope.\" ) ; scopeFactories . get ( InstanceScope . APPLICATION ) . persistInstance ( new InstanceKey ( appContext . getKey ( ) ) , this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensure all managed classes with managed life cycle are instantiated . Invoked at a final stage of container initialization this method checks every managed class that implements { [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void start ( ) { log . trace ( \"start()\" ) ; // classes pool is not sorted; it is a hash map for performance reasons\r // also, a managed class may appear multiple times if have multiple interfaces\r // bellow sorted set is used to ensure ascending order on managed classes instantiation\r // comparison is based on managed class key that is created incrementally\r Set < ManagedClassSPI > sortedClasses = new TreeSet <> ( new Comparator < ManagedClassSPI > ( ) { @ Override public int compare ( ManagedClassSPI o1 , ManagedClassSPI o2 ) { // compare first with second to ensure ascending sorting\r return o1 . getKey ( ) . compareTo ( o2 . getKey ( ) ) ; } } ) ; for ( ManagedClassSPI managedClass : classesPool . values ( ) ) { if ( managedClass . isAutoInstanceCreation ( ) ) { sortedClasses . add ( managedClass ) ; } // process only implementations of managed life cycle interface\r // if (Types.isKindOf(managedClass.getImplementationClass(), ManagedLifeCycle.class)) {\r // sortedClasses.add(managedClass);\r // }\r } for ( ManagedClassSPI managedClass : sortedClasses ) { // call getInstance to ensure managed instance with managed life cycle is started\r // if there are more than one single interface peek one, no matter which; the simple way is to peek the first\r // getInstance() will create instance only if not already exist; returned value is ignored\r log . debug ( \"Create managed instance with managed life cycle |%s|.\" , managedClass . getInterfaceClass ( ) ) ; getInstance ( ( Class < ? super Object > ) managedClass . getInterfaceClass ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Destroy container and release caches factories and processors . This is container global clean - up invoked at application unload ; after executing this method no managed instance can be created or reused . Attempting to use { [CODESPLIT] public void destroy ( ) { log . trace ( \"destroy()\" ) ; // cron manager should be destroyed first to avoid invoking cron methods on cleaned managed instance\r cronManager . destroy ( ) ; // classes pool is not sorted; it is a hash map for performance reasons\r // also, a managed class may appear multiple times if have multiple interfaces\r // bellow sorted set is used to ensure reverse order on managed classes destruction\r // comparison is based on managed class key that is created incrementally\r Set < ManagedClassSPI > sortedClasses = new TreeSet <> ( new Comparator < ManagedClassSPI > ( ) { @ Override public int compare ( ManagedClassSPI o1 , ManagedClassSPI o2 ) { // compare second with first to ensure descending sorting\r return o2 . getKey ( ) . compareTo ( o1 . getKey ( ) ) ; } } ) ; for ( ManagedClassSPI managedClass : classesPool . values ( ) ) { // process only implementations of managed pre-destroy interface\r if ( Types . isKindOf ( managedClass . getImplementationClass ( ) , ManagedPreDestroy . class ) ) { sortedClasses . add ( managedClass ) ; } } for ( ManagedClassSPI managedClass : sortedClasses ) { ScopeFactory scopeFactory = scopeFactories . get ( managedClass . getInstanceScope ( ) ) ; InstanceKey instanceKey = new InstanceKey ( managedClass . getKey ( ) ) ; Object instance = scopeFactory . getInstance ( instanceKey ) ; if ( instance == null ) { continue ; } // sorted managed classes contains only implementations of pre-destroy interface\r // in case instance is a Java Proxy takes care to execute pre-destroy hook on wrapped instance\r // in order to avoid adding container services to this finalization hook\r ManagedPreDestroy managedInstance = ( ManagedPreDestroy ) Classes . unproxy ( instance ) ; log . debug ( \"Pre-destroy managed instance |%s|.\" , managedInstance . getClass ( ) ) ; try { managedInstance . preDestroy ( ) ; } catch ( Throwable t ) { log . dump ( String . format ( \"Managed instance |%s| pre-destroy fail:\" , instance . getClass ( ) ) , t ) ; } } for ( ScopeFactory scopeFactory : scopeFactories . values ( ) ) { // local scope has null factory\r if ( scopeFactory != null ) { scopeFactory . clear ( ) ; } } classesPool . clear ( ) ; instanceProcessors . clear ( ) ; scopeFactories . clear ( ) ; instanceFactories . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "INSTANCE RETRIEVAL ALGORITHM [CODESPLIT] @ Override public < T > T getInstance ( Class < ? super T > interfaceClass , Object ... args ) { Params . notNull ( interfaceClass , \"Interface class\" ) ; ManagedClassSPI managedClass = classesPool . get ( interfaceClass ) ; if ( managedClass == null ) { throw new BugError ( \"No managed class associated with interface class |%s|.\" , interfaceClass ) ; } InstanceKey instanceKey = new InstanceKey ( managedClass . getKey ( ) ) ; return getInstance ( managedClass , instanceKey , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method that implements the core of managed instances retrieval algorithm . This method gets existing managed instance from container caches or creates a new instance . If instance is fresh created add instance services via registered instance processors . <p > Here is managed instance retrieval algorithm part implemented by this method . <ol > <li > get scope and instance factories for managed class instance scope and type ; if managed class instance scope is local there is no scope factory <li > if scope factory is null execute local instance factory that creates a new instance and returns it ; applies arguments processing on local instance but not instance processors <li > if there is scope factory do next steps into synchronized block <li > try to retrieve instance from scope factory cache <li > if no cached instance pre - process arguments create a new instance using instance factory and persist instance on scope factory <li > end synchronized block <li > arguments pre - processing takes care to inject constructor dependencies <li > if new instance is created execute instance post - processors into registration order . < / ol > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private < T > T getInstance ( ManagedClassSPI managedClass , InstanceKey instanceKey , Object ... args ) { // if(managedClass.getInstanceType().isREMOTE()) {\r // return getRemoteInstance(new URL(managedClass.getImplementationURL()), (Class<? super T>)\r // managedClass.getInterfaceClass());\r // }\r ScopeFactory scopeFactory = scopeFactories . get ( managedClass . getInstanceScope ( ) ) ; InstanceFactory instanceFactory = instanceFactories . get ( managedClass . getInstanceType ( ) ) ; if ( scopeFactory == null ) { args = argumentsProcessor . preProcessArguments ( managedClass , args ) ; return instanceFactory . newInstance ( managedClass , args ) ; } boolean postProcessingEnabled = false ; Object instance = null ; synchronized ( scopeMutex ) { instance = scopeFactory . getInstance ( instanceKey ) ; if ( instance == null ) { postProcessingEnabled = true ; args = argumentsProcessor . preProcessArguments ( managedClass , args ) ; instance = instanceFactory . newInstance ( managedClass , args ) ; scopeFactory . persistInstance ( instanceKey , instance ) ; } } if ( ! postProcessingEnabled ) { return ( T ) instance ; } // post-processors operate on bare POJO instances but is possible for instance factory to return a Java Proxy\r // if instance is a Java Proxy that uses InstanceInvocationHandler extract wrapped POJO instance\r // if instance is a Java Proxy that does not use InstanceInvocationHandler post-processing is not performed at all\r // if instance is not a Java Proxy execute post-processing on it\r Object pojoInstance = null ; if ( instance instanceof Proxy ) { if ( Proxy . getInvocationHandler ( instance ) instanceof InstanceInvocationHandler ) { InstanceInvocationHandler < T > handler = ( InstanceInvocationHandler < T > ) Proxy . getInvocationHandler ( instance ) ; pojoInstance = handler . getWrappedInstance ( ) ; } } else { pojoInstance = instance ; } if ( pojoInstance != null ) { for ( InstanceProcessor instanceProcessor : instanceProcessors ) { instanceProcessor . postProcessInstance ( managedClass , pojoInstance ) ; } } return ( T ) instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Declarative converters registration . This utility scans for <code > converters< / code > section into given configuration object and register converters via { @link ConverterRegistry#registerConverter ( Class Class ) } . <p > Configuration converter section should respect below syntax . [CODESPLIT] private static void convertersInitialization ( Config config ) throws ConfigException { Config section = config . getChild ( \"converters\" ) ; if ( section == null ) { return ; } for ( Config el : section . findChildren ( \"type\" ) ) { String className = el . getAttribute ( \"class\" ) ; Class < ? > valueType = Classes . forOptionalName ( className ) ; if ( valueType == null ) { throw new ConfigException ( \"Invalid converter configuration. Value type class |%s| not found.\" , className ) ; } String converterName = el . getAttribute ( \"converter\" ) ; Class < ? extends Converter > converterClass = Classes . forOptionalName ( converterName ) ; if ( converterClass == null ) { throw new ConfigException ( \"Invalid converter configuration. Converter class |%s| not found.\" , converterName ) ; } ConverterRegistry . getInstance ( ) . registerConverter ( valueType , converterClass ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Plain Java objects static initialization . Inject static fields value into arbitrary Java classes . Note that this mechanism is not related to managed classes ; it acts on regular Java classes and only on static fields . <p > Here is a sample configuration for Java objects static injection . There is <code > pojo - classes< / code > section that list all involved classes with aliases . For every Java class alias there is a section with the same name that has <code > static< / code > name / value elements related by name to class static fields . [CODESPLIT] private static void pojoStaticInitialization ( Config config ) throws ConfigException { Config pojoClassesSection = config . getChild ( \"pojo-classes\" ) ; if ( pojoClassesSection == null ) { return ; } for ( Config pojoClassElement : pojoClassesSection . getChildren ( ) ) { String pojoClassName = pojoClassElement . getAttribute ( \"class\" ) ; if ( pojoClassName == null ) { throw new ConfigException ( \"Invalid POJO class element. Missing <class> attribute.\" ) ; } Config configSection = config . getChild ( pojoClassElement . getName ( ) ) ; Class < ? > pojoClass = Classes . forOptionalName ( pojoClassName ) ; if ( pojoClass == null ) { throw new ConfigException ( \"Missing configured POJO class |%s|.\" , pojoClassName ) ; } if ( configSection == null ) { continue ; } for ( Config staticElement : configSection . findChildren ( \"static-field\" ) ) { String fieldName = staticElement . getAttribute ( \"name\" ) ; if ( fieldName == null ) { throw new ConfigException ( \"Missing <name> attribute from static field initialization |%s|.\" , configSection ) ; } if ( ! staticElement . hasAttribute ( \"value\" ) ) { throw new ConfigException ( \"Missing <value> attribute from static field initialization |%s|.\" , configSection ) ; } Field staticField = Classes . getOptionalField ( pojoClass , fieldName ) ; if ( staticField == null ) { throw new ConfigException ( \"Missing POJO static field |%s#%s|.\" , pojoClassName , fieldName ) ; } int modifiers = staticField . getModifiers ( ) ; if ( ! Modifier . isStatic ( modifiers ) ) { throw new ConfigException ( \"Attempt to execute POJO |%s| static initialization on instance field |%s|.\" , pojoClassName , fieldName ) ; } Object value = staticElement . getAttribute ( \"value\" , staticField . getType ( ) ) ; log . debug ( \"Intialize static field |%s#%s| |%s|\" , pojoClassName , fieldName , value ) ; Classes . setFieldValue ( null , staticField , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an argument to the template . If the list of arguments does not exist it will be created . [CODESPLIT] public final void addArgument ( @ NotNull final Argument argument ) { if ( arguments == null ) { arguments = new ArrayList < Argument > ( ) ; } arguments . add ( argument ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the list of target files . Either by using the producer or by simply returning the internal list . [CODESPLIT] public final List < TargetFile > createTargetFileList ( ) { if ( tflProducerConfig == null ) { LOG . info ( \"Using target file list: {} elements\" , targetFiles . size ( ) ) ; return targetFiles ; } final TargetFileListProducer producer = tflProducerConfig . getTargetFileListProducer ( ) ; LOG . info ( \"Using target file list producer: {}\" , producer . getClass ( ) . getName ( ) ) ; return producer . createTargetFiles ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marshals the object to XML . [CODESPLIT] public final void writeToXml ( final File file ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; helper . write ( this , file , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marshals the object to an XML String . [CODESPLIT] public final String toXml ( ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; return helper . write ( this , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marshals the object to XML . [CODESPLIT] public final void writeToXml ( final Writer writer ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; helper . write ( this , writer , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the model . [CODESPLIT] public final void init ( final SrcGen4JContext context , final Map < String , String > vars ) { if ( template != null ) { template = Utils4J . replaceVars ( template , vars ) ; } if ( arguments != null ) { for ( final Argument argument : arguments ) { argument . init ( vars ) ; } } if ( targetFiles != null ) { for ( final TargetFile targetFile : targetFiles ) { targetFile . init ( vars ) ; } } if ( tflProducerConfig != null ) { tflProducerConfig . init ( context , this , vars ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if this model has a reference to the given template file . [CODESPLIT] public final boolean hasReferenceTo ( final File templateDir , final File templateFile ) { final String p1 = Utils4J . getCanonicalPath ( new File ( templateDir , template ) ) ; final String p2 = Utils4J . getCanonicalPath ( templateFile ) ; return p1 . equals ( p2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance by reading the XML from a reader . [CODESPLIT] public static ParameterizedTemplateModel create ( final Reader reader ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; final ParameterizedTemplateModel pc = helper . create ( reader , createJaxbContext ( ) ) ; Contract . requireValid ( pc ) ; return pc ; } catch ( final UnmarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance by reading the XML from a file . [CODESPLIT] public static ParameterizedTemplateModel create ( final File file ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; final ParameterizedTemplateModel pc = helper . create ( file , createJaxbContext ( ) ) ; pc . setFile ( file ) ; Contract . requireValid ( pc ) ; return pc ; } catch ( final UnmarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inject dependencies described by given managed class into related managed instance . For every dependency field retrieve its value using { @link DependencyProcessor#getDependencyValue ( ManagedClassSPI Class ) } and inject it reflexively . [CODESPLIT] @ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { if ( instance == null ) { // null instance is silently ignored since container ensure not null instance argument\r return ; } for ( Field dependency : managedClass . getDependencies ( ) ) { if ( dependency . isSynthetic ( ) ) { // it seems there can be injected fields, created via byte code manipulation, when run with test coverage active\r // not clear why and how but was consistently observed on mock object from unit test run with coverage\r continue ; } Classes . setFieldValue ( instance , dependency , getDependencyValue ( managedClass , dependency . getType ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set this method request URI path that is the path component by which this method is referred into request URI . If given request URI path is null uses method name converted to dashed case . [CODESPLIT] void setRequestPath ( String requestPath ) { this . requestPath = requestPath != null ? requestPath : Strings . toDashCase ( method . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke managed method and applies method level services . Delegates this managed method { @link #invoker } ; accordingly selected strategy invoker can be { @link DefaultInvoker } or { @link InterceptedInvoker } if this managed method is annotated with { @link Interceptor } . Also takes care to update { @link #meter } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public < T > T invoke ( Object object , Object ... args ) throws AuthorizationException , IllegalArgumentException , InvocationException { if ( remotelyAccessible && ! isPublic ( ) && ! container . isAuthenticated ( ) ) { log . info ( \"Reject not authenticated access to |%s|.\" , method ) ; throw new AuthorizationException ( ) ; } // arguments processor converts <args> to empty array if it is null\r // it can be null if on invocation chain there is Proxy invoked with no arguments\r args = argumentsProcessor . preProcessArguments ( this , args ) ; if ( object instanceof Proxy ) { // if object is a Java Proxy does not apply method services implemented by below block\r // instead directly invoke Java method on the Proxy instance\r // container will call again this method but with the real object instance, in which case executes the next logic\r try { return ( T ) method . invoke ( object , args ) ; } catch ( InvocationTargetException e ) { throw new InvocationException ( e . getTargetException ( ) ) ; } catch ( IllegalAccessException e ) { throw new BugError ( \"Illegal access on method with accessibility set true.\" ) ; } } if ( meter == null ) { try { return ( T ) invoker . invoke ( object , args ) ; } catch ( InvocationTargetException e ) { throw new InvocationException ( e . getTargetException ( ) ) ; } catch ( IllegalAccessException e ) { throw new BugError ( \"Illegal access on method with accessibility set true.\" ) ; } } meter . incrementInvocationsCount ( ) ; meter . startProcessing ( ) ; T returnValue = null ; try { returnValue = ( T ) invoker . invoke ( object , args ) ; } catch ( InvocationTargetException e ) { meter . incrementExceptionsCount ( ) ; throw new InvocationException ( e . getTargetException ( ) ) ; } catch ( IllegalAccessException e ) { // this condition is a bug; do not increment exceptions count\r throw new BugError ( \"Illegal access on method with accessibility set true.\" ) ; } meter . stopProcessing ( ) ; return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes the method multiple times either until it returns true or until maxtime is over . After each invoke the class waits { @code sleepTime } milliseconds . [CODESPLIT] public void wait ( Object target , Method method , long maxTime , long sleepTime ) { long remaining = maxTime ; lastCallWasSuccessful = invokeMethod ( target , method ) ; while ( ! lastCallWasSuccessful && remaining > 0 ) { systemTime . sleep ( sleepTime ) ; remaining -= sleepTime ; lastCallWasSuccessful = invokeMethod ( target , method ) ; } lastElapsedTime = maxTime - remaining ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if there are more parts on this form iterator . This implementation has side effects : it takes care to close form parts while traversing form iterator . [CODESPLIT] @ Override public boolean hasNext ( ) { try { if ( currentPart != null ) { currentPart . close ( ) ; } if ( ! fileItemIterator . hasNext ( ) ) { return false ; } FileItemStream fileItemStream = fileItemIterator . next ( ) ; if ( fileItemStream . isFormField ( ) ) { currentPart = new FormFieldImpl ( fileItemStream ) ; } else { currentPart = new UploadStreamImpl ( fileItemStream ) ; } return true ; } catch ( IOException | FileUploadException e ) { log . error ( e ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get arguments reader able to process arguments from HTTP request accordingly expected argument types . If HTTP request has no content type returns { @link EncoderKey#APPLICATION_JSON } reader that is tiny container default content type is JSON . This departs from HTTP standard that mandates using bytes stream when no content type is provided on request . <p > If formal parameters are empty returns { @link EmptyArgumentsReader } . If formal parameters are provided attempts to retrieve a reader for expected argument types . If none found try using content type solely . [CODESPLIT] @ Override public ArgumentsReader getArgumentsReader ( HttpServletRequest httpRequest , Type [ ] formalParameters ) { if ( formalParameters . length == 0 ) { return EmptyArgumentsReader . getInstance ( ) ; } if ( httpRequest . getQueryString ( ) != null ) { return readers . get ( null ) ; } return getArgumentsReader ( httpRequest . getContentType ( ) , formalParameters [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get arguments reader for requested content and parameter types . This factory method tries to retrieve a reader for expected parameter type . If none found it tries using content type solely . <p > If content type is null this utility method returns { @link EncoderKey#APPLICATION_JSON } reader since tiny container default content type is JSON . This departs from HTTP standard that mandates using bytes stream when no content type is provided on request . [CODESPLIT] private ArgumentsReader getArgumentsReader ( String contentType , Type parameterType ) { if ( contentType == null ) { return readers . get ( EncoderKey . APPLICATION_JSON ) ; } EncoderKey key = new EncoderKey ( ContentType . valueOf ( contentType ) , parameterType ) ; ArgumentsReader reader = readers . get ( key ) ; if ( reader != null ) { return reader ; } key = new EncoderKey ( ContentType . valueOf ( contentType ) ) ; reader = readers . get ( key ) ; if ( reader == null ) { throw new IllegalArgumentException ( \"Unsupported content type |%s|. There is no arguments reader registered for it.\" , key ) ; } return reader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine content type usable to retrieve a writer able to handle given object value . This method is used in tandem with { @link #getValueWriter ( ContentType ) } . <p > There is a heuristic to determine content type based on object value class . If no suitable content type found returns { @link ContentType#APPLICATION_JSON } . [CODESPLIT] @ Override public ContentType getContentTypeForValue ( Object value ) { if ( value instanceof Document ) { return ContentType . TEXT_XML ; } if ( value instanceof StreamHandler ) { return ContentType . APPLICATION_STREAM ; } return ContentType . APPLICATION_JSON ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get return value writer able to handle requested content type . Content type argument should identify a registered value writer . If no writer found throws bug error . <p > Recommend way to use this method is to provide content type instance returned by { @link #getContentTypeForValue ( Object ) } . [CODESPLIT] @ Override public ValueWriter getValueWriter ( ContentType contentType ) { ValueWriter writer = writers . get ( contentType ) ; if ( writer == null ) { throw new BugError ( \"No return value writer for content type |%s|.\" , contentType ) ; } return writer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "answer comparisons /////////////////////// [CODESPLIT] public void check ( FitCell cell , String value ) { if ( cell . getFitValue ( ) . equals ( value ) ) { cell . right ( ) ; } else { cell . wrong ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an observable stream of elements . [CODESPLIT] StoppableObservable < TEntity > getObservable ( final long startIndex , Scheduler scheduler ) { return runAsync ( scheduler , ( rx . Observer < ? super TEntity > observer , Subscription subscription ) -> { long currentStartIndex = startIndex ; while ( ! subscription . isUnsubscribed ( ) ) { PartialResponse < TEntity > response ; try { response = ( currentStartIndex >= 0 ) ? readRange ( currentStartIndex , null ) : readRange ( null , - currentStartIndex ) ; } catch ( IllegalStateException ex ) { // No new data available yet, keep polling continue ; } catch ( IOException | IllegalArgumentException | IllegalAccessException error ) { observer . onError ( error ) ; return ; } response . getElements ( ) . stream ( ) . forEach ( observer :: onNext ) ; if ( response . isEndReached ( ) ) { observer . onCompleted ( ) ; return ; } // Continue polling for more data currentStartIndex = response . getTo ( ) + 1 ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a scope instance from its string value . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) { return ( T ) new InstanceScope ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a string and converts it into a { @code java . util . Date } object . [CODESPLIT] @ Override public final Date unsafeParse ( final String s ) throws ParseException { return dateFitDateHelper . parse ( s , parameter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize field from named context parameter . [CODESPLIT] private void setField ( Field field , String parameterName , Object instance ) { final Object value = context . getProperty ( parameterName , field . getType ( ) ) ; try { field . set ( instance , value ) ; } catch ( Exception e ) { throw new BugError ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save dialog requested ( unsupported content ) . [CODESPLIT] public void save ( QNetworkReply reply ) { m_logger . info ( \"Unsupported Content : \" + reply . url ( ) . toString ( ) + \" - Download request\" ) ; m_factory . save ( reply ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new CaptureAppender to an existing logger . [CODESPLIT] public void addCaptureToLogger ( final AppenderAttachable logger , final String appenderName ) { Appender currentAppender = logger . getAppender ( appenderName ) ; Appender captureAppender = CaptureAppender . newAppenderFrom ( currentAppender ) ; logger . addAppender ( captureAppender ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the CaptureAppender which captures <code > appenderName< / code > . [CODESPLIT] public Appender getCaptureAppender ( final AppenderAttachable logger , final String appenderName ) { return logger . getAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a CaptureAppender from a logger . [CODESPLIT] public void remove ( final AppenderAttachable logger , final String appenderName ) { logger . removeAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes all cached log entries . [CODESPLIT] public void clear ( final AppenderAttachable logger , final String appenderName ) { ( ( CaptureAppender ) logger . getAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ) . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read mixed body entities from HTTP request creating and initializing arguments accordingly given formal parameters . The number and order of arguments from multipart mixed message should respect formal parameter types . Also stream argument if present should be a single one and the last on arguments list . [CODESPLIT] @ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { try { Object [ ] arguments = new Object [ formalParameters . length ] ; int argumentIndex = 0 ; ServletFileUpload multipart = new ServletFileUpload ( ) ; FileItemIterator iterator = multipart . getItemIterator ( httpRequest ) ; FileItemStream fileItemStream = null ; while ( iterator . hasNext ( ) ) { fileItemStream = iterator . next ( ) ; String contentType = fileItemStream . getContentType ( ) ; Type parameterType = formalParameters [ argumentIndex ] ; ArgumentPartReader reader = argumentsReaderFactory . getArgumentPartReader ( contentType , parameterType ) ; boolean streamArgument = StreamFactory . isStream ( parameterType ) ; ArgumentPartReader argumentPartReader = ( ArgumentPartReader ) reader ; InputStream inputStream = streamArgument ? new LazyFileItemStream ( fileItemStream ) : fileItemStream . openStream ( ) ; arguments [ argumentIndex ] = argumentPartReader . read ( inputStream , parameterType ) ; ++ argumentIndex ; // stream argument should be last on mixed arguments list\r // save it to local thread storage for clean-up after arguments processed by application\r if ( streamArgument ) { threadLocal . set ( inputStream ) ; break ; } inputStream . close ( ) ; } if ( argumentIndex != formalParameters . length ) { throw new IllegalArgumentException ( \"Not all parameters processed due to stream argument that is not the last on arguments list.\" ) ; } return arguments ; } catch ( FileUploadException e ) { throw new IOException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "AutoCloseable [CODESPLIT] @ Override public void close ( ) throws java . sql . SQLException { if ( ! this . conn . isClosed ( ) ) { ConnectionImpl outer = this . outer ; this . conn . close ( ) ; this . outer = null ; CONNECTION_HOLDER . set ( outer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses all model files in the directories and all resources . y [CODESPLIT] protected final void parseModel ( ) { if ( ( fileExtensions == null ) || ( fileExtensions . size ( ) == 0 ) ) { throw new IllegalStateException ( \"No file extensions for EMF model files set!\" ) ; } // Drop previous resource set\r resourceSet = new ResourceSetImpl ( ) ; error = false ; parseDirs ( ) ; parseResources ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to resolve all proxies . [CODESPLIT] protected final void resolveProxies ( ) { final List < String > unresolved = new ArrayList < String > ( ) ; if ( ! resolvedAllProxies ( unresolved , 0 ) ) { LOG . warn ( \"Could not resolve the following proxies ({}):\" , unresolved . size ( ) ) ; for ( final String ref : unresolved ) { LOG . warn ( \"Not found: {}\" , ref ) ; } final Iterator < Notifier > it = resourceSet . getAllContents ( ) ; while ( it . hasNext ( ) ) { final Notifier next = it . next ( ) ; if ( next instanceof EObject ) { final EObject obj = ( EObject ) next ; if ( obj . eIsProxy ( ) ) { try { it . remove ( ) ; } catch ( final UnsupportedOperationException ex ) { LOG . error ( \"Could not remove proxy: \" + obj , ex ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns files that end with java and all directories . Files and directories started with a . are excluded . [CODESPLIT] private File [ ] getFiles ( final File dir ) { final File [ ] files = dir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( final File file ) { final boolean pointFile = file . getName ( ) . startsWith ( \".\" ) ; final String extension = FilenameUtils . getExtension ( file . getName ( ) ) ; return ( ! pointFile && fileExtensions . contains ( extension ) ) || file . isDirectory ( ) ; } } ) ; return files ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the directory and it s sub directory . [CODESPLIT] private void parseDir ( final File dir ) { LOG . debug ( \"Parse: {}\" , dir ) ; final File [ ] files = getFiles ( dir ) ; if ( ( files == null ) || ( files . length == 0 ) ) { LOG . debug ( \"No files found in directory: {}\" , dir ) ; } else { for ( final File file : files ) { if ( file . isFile ( ) ) { final Resource resource = resourceSet . getResource ( URI . createFileURI ( Utils4J . getCanonicalPath ( file ) ) , true ) ; final EList < Diagnostic > diagnostics = resource . getErrors ( ) ; if ( diagnostics . size ( ) == 0 ) { LOG . debug ( \"Parsed {}\" , file ) ; } else { error = true ; LOG . error ( \"Parsed {} with errors: {}\" , file , diagnostics ) ; } } else { parseDir ( file ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if all proxies in the model are resolved . [CODESPLIT] public boolean isModelFullyResolved ( ) { boolean resolved = true ; final Set < EObject > eObjects = findAllEObjects ( resourceSet ) ; final Iterator < EObject > it = eObjects . iterator ( ) ; while ( it . hasNext ( ) ) { final EObject eObj = it . next ( ) ; if ( eObj instanceof InternalEObject ) { final InternalEObject iObj = ( InternalEObject ) eObj ; for ( final EObject crossRef : iObj . eCrossReferences ( ) ) { if ( crossRef . eIsProxy ( ) ) { LOG . error ( \"Unresolved: {}\" , crossRef ) ; resolved = false ; } } } } return resolved ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of all objects . [CODESPLIT] private static Set < EObject > findAllEObjects ( final ResourceSet resourceSet ) { final Set < EObject > list = new HashSet < EObject > ( ) ; for ( final Iterator < Notifier > i = resourceSet . getAllContents ( ) ; i . hasNext ( ) ; ) { final Notifier next = i . next ( ) ; if ( next instanceof EObject ) { list . add ( ( EObject ) next ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the model directories to parse . If no list exists internally it will be created if necessary . [CODESPLIT] protected final void setModelDirs ( final File ... modelDirs ) { if ( modelDirs == null ) { this . modelDirs = null ; } else { this . modelDirs = new ArrayList < File > ( ) ; this . modelDirs . addAll ( Arrays . asList ( modelDirs ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the list of file extensions . If no list exists internally it will be created if necessary . [CODESPLIT] protected final void setFileExtensions ( final String ... fileExtensions ) { if ( fileExtensions == null ) { this . fileExtensions = null ; } else { this . fileExtensions = new ArrayList < String > ( ) ; this . fileExtensions . addAll ( Arrays . asList ( fileExtensions ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the model resources to parse . If no list exists internally it will be created if necessary . [CODESPLIT] protected final void setModelResources ( final URI ... modelResources ) { if ( modelResources == null ) { this . modelResources = null ; } else { this . modelResources = new ArrayList < URI > ( ) ; this . modelResources . addAll ( Arrays . asList ( modelResources ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the next row . [CODESPLIT] @ Override public final boolean nextRecord ( ) throws IOException { final String line = reader . readLine ( ) ; if ( line == null ) { parts = null ; return false ; } final List < String > newParts = splitLine ( line ) ; parts = newParts . toArray ( new String [ newParts . size ( ) ] ) ; partIndex = 0 ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sorts and compare two lists . It is assumed that all items in { [CODESPLIT] private void multiLevelMatch ( List < FitRow > expected , List < Object > computed , int col ) { boolean cantGoDeeper = col >= columnNames . length ; if ( cantGoDeeper ) { check ( expected , computed ) ; } else { boolean isComment = isComment ( col ) ; if ( isComment ) { multiLevelMatch ( expected , computed , col + 1 ) ; } else { groupAndMatch ( expected , computed , col ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Groups both lists by column { [CODESPLIT] private void groupAndMatch ( List < FitRow > expected , List < Object > computed , int col ) { Map < Object , List < FitRow > > expectedMap = groupExpectedByColumn ( expected , col ) ; Map < Object , List < Object > > computedMap = groupComputedByColumn ( computed , col ) ; Set keys = union ( expectedMap . keySet ( ) , computedMap . keySet ( ) ) ; for ( Object key : keys ) { List < FitRow > expectedList = expectedMap . get ( key ) ; List < Object > computedList = computedMap . get ( key ) ; boolean isAmbiguous = hasMultipleEntries ( expectedList ) && hasMultipleEntries ( computedList ) ; if ( isAmbiguous ) { multiLevelMatch ( expectedList , computedList , col + 1 ) ; } else { check ( expectedList , computedList ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two lists . <ul > <li > if { @code expectedList } is empty all { @code computedList } items are surplus< / li > <li > if { @code computedList } is empty all { @code expectedList } items are missing< / li > <li > otherwise match the first rows and compare the rest recursively< / li > < / ul > [CODESPLIT] protected void check ( List < FitRow > expectedList , List < Object > computedList ) { if ( expectedList == null || expectedList . size ( ) == 0 ) { surplus . addAll ( computedList ) ; } else if ( computedList == null || computedList . size ( ) == 0 ) { missing . addAll ( expectedList ) ; } else { Object computedRow = computedList . remove ( 0 ) ; List < FitCell > expectedRow = expectedList . remove ( 0 ) . cells ( ) ; compareRow ( computedRow , expectedRow ) ; check ( expectedList , computedList ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two rows item by item using { [CODESPLIT] private void compareRow ( Object computedRow , List < FitCell > expectedCells ) { for ( int i = 0 ; i < columnNames . length && expectedCells != null ; i ++ ) { try { ValueReceiver valueReceiver ; if ( isComment ( i ) ) { valueReceiver = null ; } else { valueReceiver = createReceiver ( computedRow , columnNames [ i ] ) ; } String columnParameter = FitUtils . saveGet ( i , columnParameters ) ; check ( expectedCells . get ( i ) , valueReceiver , columnParameter ) ; } catch ( NoSuchMethodException | NoSuchFieldException e ) { expectedCells . indexOf ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > This method performs property variable substitution on the specified value . If the specified value contains the syntax <tt > $ { &lt ; prop - name&gt ; } < / tt > where <tt > &lt ; prop - name&gt ; < / tt > refers to either a configuration property or a system property then the corresponding property value is substituted for the variable placeholder . Multiple variable placeholders may exist in the specified value as well as nested variable placeholders which are substituted from inner most to outer most . Configuration properties override system properties . < / p > [CODESPLIT] @ SuppressWarnings ( { \"rawtypes\" , \"unchecked\" } ) public static String substVars ( String val , String currentKey , Map cycleMap , Properties configProps ) throws IllegalArgumentException { // If there is currently no cycle map, then create // one for detecting cycles for this invocation. if ( cycleMap == null ) { cycleMap = new HashMap ( ) ; } // Put the current key in the cycle map. cycleMap . put ( currentKey , currentKey ) ; // Assume we have a value that is something like: // \"leading ${foo.${bar}} middle ${baz} trailing\" // Find the first ending '}' variable delimiter, which // will correspond to the first deepest nested variable // placeholder. int stopDelim = - 1 ; int startDelim = - 1 ; do { stopDelim = val . indexOf ( DELIM_STOP , stopDelim + 1 ) ; // If there is no stopping delimiter, then just return // the value since there is no variable declared. if ( stopDelim < 0 ) { return val ; } // Try to find the matching start delimiter by // looping until we find a start delimiter that is // greater than the stop delimiter we have found. startDelim = val . indexOf ( DELIM_START ) ; // If there is no starting delimiter, then just return // the value since there is no variable declared. if ( startDelim < 0 ) { return val ; } while ( stopDelim >= 0 ) { int idx = val . indexOf ( DELIM_START , startDelim + DELIM_START . length ( ) ) ; if ( ( idx < 0 ) || ( idx > stopDelim ) ) { break ; } else if ( idx < stopDelim ) { startDelim = idx ; } } } while ( ( startDelim > stopDelim ) && ( stopDelim >= 0 ) ) ; // At this point, we have found a variable placeholder so // we must perform a variable substitution on it. // Using the start and stop delimiter indices, extract // the first, deepest nested variable placeholder. String variable = val . substring ( startDelim + DELIM_START . length ( ) , stopDelim ) ; // Verify that this is not a recursive variable reference. if ( cycleMap . get ( variable ) != null ) { throw new IllegalArgumentException ( \"recursive variable reference: \" + variable ) ; } // Get the value of the deepest nested variable placeholder. // Try to configuration properties first. String substValue = ( configProps != null ) ? configProps . getProperty ( variable , null ) : null ; if ( substValue == null ) { // Ignore unknown property values. substValue = System . getProperty ( variable , \"\" ) ; } // Remove the found variable from the cycle map, since // it may appear more than once in the value and we don't // want such situations to appear as a recursive reference. cycleMap . remove ( variable ) ; // Append the leading characters, the substituted value of // the variable, and the trailing characters to get the new // value. val = val . substring ( 0 , startDelim ) + substValue + val . substring ( stopDelim + DELIM_STOP . length ( ) , val . length ( ) ) ; // Now perform substitution again, since there could still // be substitutions to make. val = substVars ( val , currentKey , cycleMap , configProps ) ; // Return the value. return val ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a { @code String } into a { @code Array } . [CODESPLIT] @ Override public Object unsafeParse ( final String s ) throws ParseException { final StringTokenizer t = new StringTokenizer ( s , \",\" ) ; final Object array = Array . newInstance ( componentAdapter . getType ( ) , t . countTokens ( ) ) ; for ( int i = 0 ; t . hasMoreTokens ( ) ; i ++ ) { Array . set ( array , i , componentAdapter . parse ( t . nextToken ( ) . trim ( ) ) ) ; } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether two Arrays { @code a } and { @code b } are equal . <p > A type specific { @code TypeAdapter } is used to compare the items . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public boolean unsafeEquals ( Object a , Object b ) { final int length = Array . getLength ( a ) ; if ( length != Array . getLength ( b ) ) { return false ; } for ( int i = 0 ; i < length ; i ++ ) { if ( ! componentAdapter . unsafeEquals ( Array . get ( a , i ) , Array . get ( b , i ) ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a LogEventAnalyzer which is capable to analyze the events { @code events } using the condition defined in { @code conditionCell } . [CODESPLIT] public LogEventAnalyzer getLogEventAnalyzerFor ( Validator validator , FitCell conditionCell , LoggingEvent [ ] events ) { return new LogEventAnalyzer ( validator , conditionCell , events ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses template engine to inject model and serialize view on HTTP response . If meta - view contains { @link #OPERATOR_SERIALIZATION } property enable engine operators serialization . [CODESPLIT] @ Override protected void serialize ( OutputStream outputStream ) throws IOException { // refrain to use HttpResponse#getWriter()\r // this library always uses output stream since servlet response API does not allow mixing characters and bytes streams\r Writer writer = new BufferedWriter ( new OutputStreamWriter ( outputStream , \"UTF-8\" ) ) ; TemplateEngine templateEngine = Classes . loadService ( TemplateEngine . class ) ; Template template = templateEngine . getTemplate ( meta . getTemplateFile ( ) ) ; boolean operatorSerialization = Boolean . parseBoolean ( meta . getProperty ( OPERATOR_SERIALIZATION ) ) ; if ( operatorSerialization ) { template . setProperty ( \"js.template.serialize.operator\" , true ) ; } // if model is null template serializes itself skipping injection operation\r template . serialize ( model , writer ) ; // there is no need to flush response stream on error so no need for try/finally\r writer . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute Results [CODESPLIT] public < K , V > Map < K , V > executeMap ( ResultSetMapper < K > key , ResultSetMapper < V > value , Map < K , V > newMap ) throws java . sql . SQLException { try ( ResultSetImpl rs = this . executeResult ( ) ) { while ( rs . next ( ) ) { K k = key . map ( rs ) ; V v = value . map ( rs ) ; newMap . put ( k , v ) ; } return newMap ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "type IN ( [CODESPLIT] public void setStringArray ( String parameterName , String ... values ) throws java . sql . SQLException { int arrayLen = this . getSql ( ) . getArrayLen ( parameterName ) ; AssertUtils . assertTrue ( values . length <= arrayLen ) ; for ( int i = 0 ; i < arrayLen ; i ++ ) { setString2 ( Sql . toParamName ( parameterName , i ) , ( i < values . length ) ? values [ i ] : null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set Nullable Parameters [CODESPLIT] public void setBoolean2 ( String parameterName , Boolean value ) throws java . sql . SQLException { if ( value == null ) { setNull ( parameterName , Types . BIT ) ; } else { setBoolean ( parameterName , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "java . sql . Statement [CODESPLIT] @ Override public long executeLargeUpdate ( java . lang . String sql , int [ ] columnIndexes ) throws java . sql . SQLException { return this . stat . executeLargeUpdate ( sql , columnIndexes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the arguments contains the argument <code > arg< / code > . [CODESPLIT] public static boolean containsArgument ( String [ ] args , String arg ) { if ( args == null || arg == null || arg . length ( ) == 0 || args . length == 0 ) { return false ; } else { for ( String a : args ) { if ( a . equalsIgnoreCase ( arg ) ) { return true ; } else if ( a . startsWith ( arg + \"=\" ) ) { return true ; } } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the argument value . <ul > <li > for arg = value it returns value < / li > <li > for arg value it returns value < / li > [CODESPLIT] public static String getArgumentValue ( String args [ ] , String arg ) { if ( args == null || arg == null || arg . length ( ) == 0 || args . length == 0 ) { return null ; } else { for ( int i = 0 ; i < args . length ; i ++ ) { String a = args [ i ] ; if ( a . equalsIgnoreCase ( arg ) ) { // Case 'arg value' : Look for arg + 1; if ( args . length > i + 1 ) { return args [ i + 1 ] ; } } else if ( a . startsWith ( arg + \"=\" ) ) { // Case 'arg=value' : Parse the value int index = a . indexOf ( ' ' ) + 1 ; return a . substring ( index ) ; } } return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create an instance type from its string value . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) throws IllegalArgumentException , ConverterException { return ( T ) new InstanceType ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Merges the template and context into a file . If the directory of the file does not exists the full directory path to it will be created . [CODESPLIT] protected final void merge ( final VelocityContext context , final String artifactName , final String templateName , final String filename ) throws GenerateException { final GeneratedFile genFile = getTargetFile ( artifactName , filename , templateName ) ; if ( genFile . isSkip ( ) ) { LOG . debug ( \"Omitted already existing file: {} [{}]\" , genFile , templateName ) ; } else { LOG . debug ( \"Start merging velocity template: {} [{}]\" , genFile , templateName ) ; // Merge content\r try { final Writer writer = new FileWriter ( genFile . getTmpFile ( ) ) ; try { final Template template = ve . getTemplate ( templateName ) ; template . merge ( context , writer ) ; } finally { writer . close ( ) ; } genFile . persist ( ) ; } catch ( final IOException ex ) { throw new GenerateException ( \"Error merging template '\" + templateName + \"' to '\" + filename + \"'!\" , ex ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle XML input stream from HTTP request . This method expects a single formal parameter current implementation supporting { @link Document } and { @link InputStream } . [CODESPLIT] @ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { if ( formalParameters . length != 1 ) { throw new IllegalArgumentException ( \"Bad parameters count. Should be exactly one but is |%d|.\" , formalParameters . length ) ; } if ( formalParameters [ 0 ] instanceof ParameterizedType ) { throw new IllegalArgumentException ( \"Parameterized type |%s| is not supported.\" , formalParameters [ 0 ] ) ; } return new Object [ ] { read ( httpRequest . getInputStream ( ) , formalParameters [ 0 ] ) } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process XML input stream accordingly requested type . Current implementation supports two type : XML { @link Document } and XML input stream . [CODESPLIT] @ Override public Object read ( InputStream inputStream , Type type ) throws IOException { if ( Types . isKindOf ( type , Document . class ) ) { return documentBuilder . loadXML ( inputStream ) ; } else if ( Types . isKindOf ( type , InputStream . class ) ) { threadLocal . set ( inputStream ) ; return inputStream ; } else { throw new IllegalArgumentException ( \"Unsupported formal parameter type |%s| for XML content type.\" , type ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the model directory . [CODESPLIT] public final File getModelDir ( ) { if ( ( modelDir == null ) && ( modelPath != null ) ) { modelDir = Utils4J . getCanonicalFile ( new File ( modelPath ) ) ; } return modelDir ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the template directory . [CODESPLIT] public final File getTemplateDir ( ) { if ( ( templateDir == null ) && ( templatePath != null ) ) { try { templateDir = new File ( templatePath ) . getCanonicalFile ( ) ; } catch ( final IOException ex ) { throw new RuntimeException ( \"Couldn't determine canonical template file: \" + templatePath , ex ) ; } } return templateDir ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "number of seconds from 1970 - 01 - 01T00 : 00 : 00Z UTC until the specified UTC date / time [CODESPLIT] public static Long toNumericDate ( Date value ) { if ( value == null ) { return null ; } return DateUtils . clearMs ( value ) . getTime ( ) / 1000 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize XML document to output stream of given HTTP response . [CODESPLIT] @ Override public void write ( HttpServletResponse httpResponse , Object value ) throws IOException { final Document document = ( Document ) value ; document . serialize ( new OutputStreamWriter ( httpResponse . getOutputStream ( ) , \"UTF-8\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configuration Property : set the initial URL . This property is <b > mandatory< / b > . If the browser is already created this web view loads this new url . [CODESPLIT] @ Property ( name = \"url\" ) public synchronized void setURL ( final String url ) { this . m_url = url ; if ( m_browser != null ) { QApplication . invokeLater ( new Runnable ( ) { public void run ( ) { m_browser . open ( url ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the browser and loads the set url in the web view . [CODESPLIT] @ Validate public void start ( ) { QApplication . invokeLater ( new Runnable ( ) { public void run ( ) { configureApplication ( ) ; m_logger . info ( \"Creating a web ui...\" ) ; synchronized ( WebViewFactory . this ) { m_browser = new WebWindow ( m_url , WebViewFactory . this ) ; configureWindow ( m_browser ) ; m_browser . show ( ) ; } m_logger . info ( \"Web UI created.\" ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures the application : <ul > <li > sets the application name ( default : akquinet ChameRIA ) < / li > <li > sets the application version ( default : current web view factory version ) < / li > <li > sets the application icon ( default : no icon ) < / li > < / ul > [CODESPLIT] private void configureApplication ( ) { if ( m_appName != null ) { QApplication . setApplicationName ( m_appName ) ; } else { QApplication . setApplicationName ( \"akquinet ChameRIA\" ) ; } if ( m_appVersion != null ) { QApplication . setApplicationVersion ( m_appVersion ) ; } else { QApplication . setApplicationVersion ( m_context . getBundle ( ) . getVersion ( ) . toString ( ) ) ; } if ( m_icon != null ) { QFile file = new QFile ( m_icon ) ; QIcon icon = new QIcon ( file . fileName ( ) ) ; QApplication . setWindowIcon ( icon ) ; } QApplication . setOrganizationName ( \"akquinet A.G.\" ) ; // Configure the proxy if ( m_proxyType != null ) { m_logger . warn ( \"Set application proxy : \" + m_proxyType ) ; if ( m_proxyHostName == null || m_proxyPort == 0 ) { m_logger . error ( \"Cannot configure proxy : hostname or port not set : \" + m_proxyHostName + \":\" + m_proxyPort ) ; } else { QNetworkProxy proxy = new QNetworkProxy ( m_proxyType , m_proxyHostName , m_proxyPort ) ; QNetworkProxy . setApplicationProxy ( proxy ) ; m_logger . warn ( \"Application proxy set \" + m_proxyType + \" on \" + m_proxyHostName + \":\" + m_proxyPort ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures the browser window . [CODESPLIT] private void configureWindow ( WebWindow web ) { if ( m_fullscreen ) { // We need to store the previous width and height values m_width = web . width ( ) ; m_height = web . height ( ) ; web . showFullScreen ( ) ; } else { web . showNormal ( ) ; if ( ! m_resizable ) { web . setFixedSize ( new QSize ( m_width , m_height ) ) ; } else { web . setBaseSize ( new QSize ( m_width , m_height ) ) ; } web . resize ( m_width , m_height ) ; } if ( ! m_bar ) { web . menuBar ( ) . setVisible ( false ) ; } else { web . menuBar ( ) . setVisible ( true ) ; if ( m_icon != null ) { QIcon icon = new QIcon ( m_icon ) ; web . setWindowIcon ( icon ) ; } web . setWindowTitle ( m_appName ) ; } if ( ! m_contextMenu ) { web . setContextMenuPolicy ( ContextMenuPolicy . PreventContextMenu ) ; } else { web . setContextMenuPolicy ( ContextMenuPolicy . DefaultContextMenu ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print callback . Checks if the print feature is enabled . If so launch the system print job . [CODESPLIT] public void print ( QWebView view ) { if ( m_print ) { QPrinter printer = new QPrinter ( ) ; QPrintDialog printDialog = new QPrintDialog ( printer , view ) ; if ( printDialog . exec ( ) == QDialog . DialogCode . Accepted . value ( ) ) { // print ... view . print ( printer ) ; } } else { m_logger . warn ( \"Print disabled\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save callback ( for unsupported content ) . Checks if the save feature is enabled . If so launch the system save dialog . [CODESPLIT] public void save ( QNetworkReply reply ) { if ( m_download ) { String fn = QFileDialog . getSaveFileName ( ) ; if ( fn != null && fn . length ( ) > 0 ) { m_logger . info ( \"File name : \" + fn ) ; try { URL u = new URL ( reply . url ( ) . toString ( ) ) ; FileOutputStream out = new FileOutputStream ( new File ( fn ) ) ; InputStream in = u . openStream ( ) ; write ( in , out ) ; } catch ( IOException e ) { m_logger . error ( \"Cannot download file \" + e . getMessage ( ) , e ) ; } } else { m_logger . warn ( \"No File Name - Download request cancelled\" ) ; } } else { m_logger . warn ( \"Download disabled\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility method to copy a stream to another stream . [CODESPLIT] public static void write ( InputStream in , OutputStream out ) throws IOException { byte [ ] b = new byte [ 4096 ] ; for ( int n ; ( n = in . read ( b ) ) != - 1 ; ) { out . write ( b , 0 , n ) ; } in . close ( ) ; out . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open callback ( <code > window . open< / code > ) . Checks if the open new window feature is enabled . If so creates the web view [CODESPLIT] public QWebView openWindow ( ) { if ( m_window_open ) { // We share the same factory QWebView newwindow = new ChameriaWebView ( this ) ; return newwindow ; } else { m_logger . warn ( \"Open new window disabled\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve managed instance from application factory and invoke given method on that instance . [CODESPLIT] @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { T instance = appFactory . getInstance ( interfaceClass ) ; return method . invoke ( instance , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attach this instance to HTTP servlet request . Load this instance state from HTTP servlet request and mark it as attached . [CODESPLIT] public void attach ( HttpServletRequest httpRequest , HttpServletResponse httpResponse ) { // takes care to not override request URL, locale and request path values if set by request pre-processor\r if ( requestURL == null ) { requestURL = httpRequest . getRequestURI ( ) ; } if ( locale == null ) { locale = httpRequest . getLocale ( ) ; } if ( requestPath == null ) { // request URI and context path cannot ever be null\r requestPath = httpRequest . getRequestURI ( ) . substring ( httpRequest . getContextPath ( ) . length ( ) ) ; } this . httpRequest = httpRequest ; this . httpResponse = httpResponse ; this . attached = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detach request context instance from HTTP servlet request . Invoking getters on this instance after detaching is considered a bug . [CODESPLIT] public void detach ( ) { attached = false ; locale = null ; securityDomain = null ; cookies = null ; requestPath = null ; requestURL = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get request cookies . [CODESPLIT] public Cookies getCookies ( ) { assertAttached ( ) ; if ( cookies == null ) { cookies = new Cookies ( httpRequest , httpResponse ) ; } return cookies ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get HTTP session this request context is part of or null if session is not or could not be created . If <code > create< / code > flag is not provided this method return current HTTP session as it is that is return it if already created or null if not . <p > If <code > create< / code > flag is present and is true this method returns current HTTP session if there is one associated with current request or create a new one . This method never returns null if requested to create session but can throw illegal state exception if attempt to create session after response commit . [CODESPLIT] public HttpSession getSession ( boolean ... create ) { assertAttached ( ) ; if ( create . length == 0 ) { return httpRequest . getSession ( ) ; } // if create flag is true next call can throw IllegalStateException if HTTP response is committed\r return httpRequest . getSession ( create [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump this request context state to error logger . If this instance is not attached this method is NOP . [CODESPLIT] public void dump ( ) { if ( ! attached ) { return ; } StringBuilder message = new StringBuilder ( ) ; message . append ( \"Request context |\" ) ; message . append ( httpRequest . getRequestURI ( ) ) ; message . append ( \"|:\" ) ; message . append ( System . lineSeparator ( ) ) ; message . append ( \"\\t- remote-address: \" ) ; message . append ( httpRequest . getRemoteHost ( ) ) ; message . append ( System . lineSeparator ( ) ) ; message . append ( \"\\t- method: \" ) ; message . append ( httpRequest . getMethod ( ) ) ; message . append ( System . lineSeparator ( ) ) ; message . append ( \"\\t- query-string: \" ) ; if ( httpRequest . getQueryString ( ) != null ) { message . append ( httpRequest . getQueryString ( ) ) ; } Enumeration < String > headerNames = httpRequest . getHeaderNames ( ) ; while ( headerNames . hasMoreElements ( ) ) { message . append ( System . lineSeparator ( ) ) ; String headerName = headerNames . nextElement ( ) ; message . append ( \"\\t- \" ) ; message . append ( headerName ) ; message . append ( \": \" ) ; message . append ( httpRequest . getHeader ( headerName ) ) ; } log . error ( message . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the { @link TypeHandler } which is provided by { @code className } . After processing this row the TypeAdapter will be automatically used when the destination type matches { @link TypeHandler#getType () } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public void load ( final String className ) throws Exception { Class < ? extends TypeHandler < ? > > clazz = ( Class < ? extends TypeHandler < ? > > ) Class . forName ( className ) ; TypeHandlerFactory helper = DependencyManager . getOrCreate ( TypeHandlerFactory . class ) ; helper . register ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Collect invocation meters from application managed classes . [CODESPLIT] private static List < InvocationMeter > getMeters ( ) { List < InvocationMeter > invocationMeters = new ArrayList < InvocationMeter > ( ) ; ContainerSPI container = ( ContainerSPI ) Factory . getAppFactory ( ) ; for ( ManagedMethodSPI managedMethod : container . getManagedMethods ( ) ) { invocationMeters . add ( ( ( ManagedMethod ) managedMethod ) . getMeter ( ) ) ; } return invocationMeters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure events stream instance from configuration object . [CODESPLIT] protected void config ( EventStreamConfig config ) { if ( config . hasSecretKey ( ) ) { secretKey = config . getSecretKey ( ) ; } if ( config . hasKeepAlivePeriod ( ) ) { keepAlivePeriod = config . getKeepAlivePeriod ( ) ; } parameters = config . getParameters ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Push event to this events stream client . This method just stores the event on { @link #eventsQueue events queue } being executed into invoker thread . This events stream thread is blocked on the events queue ; after this method execution it will unblock and process the event see { @link #loop () } method . <p > Queue offer operation is guarded by { @link #EVENTS_QUEUE_PUSH_TIMEOUT } . This timeout can occur only in a very improbable condition of events flood combined with system resources starvation . For this reason there is no attempt to recover ; event is simple lost with warning on application logger . [CODESPLIT] public void push ( Event event ) { if ( ! active . get ( ) ) { throw new BugError ( \"Event stream |%s| is closed.\" , this ) ; } // BlockingQueue is thread safe so we do not need to synchronize this method\r try { if ( ! eventsQueue . offer ( event , EVENTS_QUEUE_PUSH_TIMEOUT , TimeUnit . MILLISECONDS ) ) { log . warn ( \"Timeout trying to push event on events queue. Event |%s| not processed.\" , event ) ; } } catch ( InterruptedException unused ) { log . warn ( \"Thread interruption on event stream |%s| while trying to push event to queue. Event |%s| not processed.\" , this , event ) ; Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close this event stream loop and waits for associated { [CODESPLIT] @ Override public void close ( ) { if ( ! active . get ( ) ) { return ; } log . debug ( \"Closing event stream |%s| ...\" , this ) ; push ( new ShutdownEvent ( ) ) ; active . set ( false ) ; log . debug ( \"Event stream |%s| was closed.\" , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the host address for client connected to this event stream . [CODESPLIT] protected void setRemoteHost ( String remoteHost ) { if ( string == null ) { string = Strings . concat ( ' ' , STREAM_ID ++ , ' ' , remoteHost ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Event stream main loop repeated for every event . Waits for an event and push it to the client via { @link #writer } writer initialized by { @link EventStreamServlet } on this event stream creation . Note that this logic is executed into HTTP request thread ; it blocks the thread till an event become available . This method always returns true allowing event stream to continue . It returns false only when got { @link ShutdownEvent } pushed on queue by { @link #close () } method or there is an error on print writer . Checking for print writer errors is especially useful to detect that remote client closes its socket and to gracefully close this stream and release parent servlet instance . <p > Also this method takes care to periodically send keep alive events see { @link #keepAlivePeriod } . Keep alive is used to ensure server side and client logic that peer is still running and to avoid connection drop due to routers idle connection timeout . [CODESPLIT] protected boolean loop ( ) { Event event = null ; try { event = eventsQueue . poll ( keepAlivePeriod , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException unused ) { if ( ! active . get ( ) ) { log . debug ( \"Events stream |%s| thread is interrupted. Break events stream loop.\" , this ) ; return false ; } // in a perfect world, now would be the right moment to stop the events stream, returning false...\r // but i'm not sure interruption occurs only when current thread is interrupted\r // for now i play safe, allowing events stream to continue and use shutdown event to break it\r log . warn ( \"Events stream |%s| thread is interrupted. Continue events stream loop.\" , this ) ; return true ; } if ( event == null ) { // we are here due to keep-alive period expiration\r // returns true to signal event stream should continue\r sendKeepAlive ( ) ; log . debug ( \"Keep-alive was sent to event stream |%s|.\" , this ) ; return ! writer . checkError ( ) ; } // close method puts this event into queue; returns false to break this events stream loop\r if ( event instanceof ShutdownEvent ) { log . debug ( \"Got shutdown event. Break event stream loop.\" ) ; return false ; } sendEvent ( event ) ; onSent ( event ) ; log . debug ( \"Event |%s| was sent to event stream |%s|.\" , event , this ) ; return ! writer . checkError ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get named parameter throwing exception if not found . [CODESPLIT] protected < T > T getParameter ( String name , Class < T > type ) { if ( parameters == null ) { throw new BugError ( \"Event stream |%s| parameters not configured.\" , this ) ; } String value = parameters . get ( name ) ; if ( value == null ) { throw new BugError ( \"Missing event stream parameter |%s| of expected type |%s|.\" , name , type ) ; } return ConverterRegistry . getConverter ( ) . asObject ( value , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send event instance to this event stream consumer . Compile a W3C Server - Sent event from <code > event< / code > instance argument and write it to this { @link #writer } . This event stream implementation does not use all W3C server - sent event fields : only <code > event< / code > and <code > data< / code > as folows : <ul > <li > event field stores event argument canonical class name <li > data field value is event argument instance serialized JSON . < / ul > Just for those curious here is an sample of a serialized hypothetical event as it is on wire : [CODESPLIT] protected void sendEvent ( Event event ) { write ( \"data:\" ) ; if ( secretKey == null ) { json . serialize ( writer , event ) ; } else { try { Cipher cipher = Cipher . getInstance ( secretKey . getAlgorithm ( ) ) ; cipher . init ( Cipher . ENCRYPT_MODE , secretKey ) ; // this overload of doFinal from Cipher class is able to perform single step encrypting\r // excerpt from API:\r // Encrypts or decrypts data in a single-part operation, or finishes a multiple-part operation.\r byte [ ] encryptedMessage = cipher . doFinal ( json . serialize ( event ) ) ; // encode encrypted event message with Base64 since content type should be text\r write ( Base64 . encode ( encryptedMessage ) ) ; } catch ( InvalidKeyException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e ) { // we step here only for bugs on encryption provider:\r // secret key size is incorrect or key is not properly initialized\r // single step encryption using directly Cipher#doFinal is supposed to process all input at once\r // missing JVM default padding mechanism\r // bad padding occurring on encryption\r throw new BugError ( e ) ; } catch ( NoSuchAlgorithmException e ) { throw new BugError ( \"Missing support for |%s| cryptographic algorithm.\" , secretKey . getAlgorithm ( ) ) ; } } // end data field\r crlf ( ) ; // single end of line is the mark for event end\r crlf ( ) ; flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a prefix from a path . If the path does not start with the prefix the unchanged path is returned . [CODESPLIT] public String removePrefix ( final String path , final String prefix ) { String pathWithoutPrefix = path ; if ( pathWithoutPrefix . startsWith ( prefix ) ) { pathWithoutPrefix = pathWithoutPrefix . substring ( prefix . length ( ) ) ; while ( pathWithoutPrefix . startsWith ( \"/\" ) || pathWithoutPrefix . startsWith ( \"\\\\\" ) ) { pathWithoutPrefix = pathWithoutPrefix . substring ( 1 ) ; } } return pathWithoutPrefix ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether { @code subDir } is a sub directory of { @code parentDir } . Note : the comparison is case sensitive . [CODESPLIT] public boolean isSubDir ( final File subDir , final File parentDir ) throws IOException { int parentDirLength = parentDir . getCanonicalFile ( ) . getAbsolutePath ( ) . length ( ) ; File currentDir = subDir . getCanonicalFile ( ) . getAbsoluteFile ( ) ; while ( currentDir . getAbsolutePath ( ) . length ( ) > parentDirLength ) { currentDir = currentDir . getParentFile ( ) ; } return currentDir . equals ( parentDir . getAbsoluteFile ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all directory paths between { @code fromDir } and { @code toDir } . [CODESPLIT] public File [ ] getParentDirs ( final File fromDir , final File toDir ) throws IOException { List < File > result = new LinkedList <> ( ) ; final File fromDirCanonical = fromDir . getCanonicalFile ( ) ; for ( File current = toDir . getCanonicalFile ( ) . getAbsoluteFile ( ) ; ! current . equals ( fromDirCanonical ) ; current = current . getParentFile ( ) ) { result . add ( 0 , current ) ; } return result . toArray ( new File [ result . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the longest common parent directory path of two paths . [CODESPLIT] public File getCommonDir ( final File dir1 , final File dir2 ) throws IOException { List < File > parts1 = getParentDirs ( dir1 ) ; List < File > parts2 = getParentDirs ( dir2 ) ; File matched = null ; final int maxCommonSize = Math . min ( parts1 . size ( ) , parts2 . size ( ) ) ; for ( int i = 0 ; i < maxCommonSize ; ++ i ) { if ( parts1 . get ( i ) . equals ( parts2 . get ( i ) ) ) { matched = parts1 . get ( i ) ; } else { break ; } } return matched ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an absolute path into a relative one . [CODESPLIT] public String abs2rel ( final String basePath , final String absPath ) { if ( ! isAbsolutePath ( absPath ) ) { return absPath ; } if ( isWindowsDrive ( absPath ) && isWindowsDrive ( basePath ) && absPath . charAt ( 0 ) != basePath . charAt ( 0 ) ) { return absPath ; } StringBuilder result = new StringBuilder ( ) ; String [ ] baseParts = getParts ( basePath ) ; String [ ] absParts = getParts ( absPath ) ; // extract common prefix int start = 0 ; for ( int i = 0 ; i < Math . min ( baseParts . length , absParts . length ) ; ++ i ) { if ( baseParts [ i ] . equals ( absParts [ i ] ) ) { start = i + 1 ; } } for ( int i = start ; i < baseParts . length ; ++ i ) { if ( result . length ( ) > 0 ) { result . append ( File . separator ) ; } result . append ( \"..\" ) ; } for ( int i = start ; i < absParts . length ; ++ i ) { if ( result . length ( ) > 0 ) { result . append ( File . separator ) ; } result . append ( absParts [ i ] ) ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an relative path into an absolute one . [CODESPLIT] public File rel2abs ( final String basePath , final String relPath ) { String [ ] baseParts = getParts ( basePath ) ; String [ ] relParts = getParts ( relPath ) ; if ( isAbsolutePath ( relPath ) ) { return new File ( relPath ) ; } List < String > parts = new ArrayList <> ( ) ; for ( int i = 0 ; i < baseParts . length ; ++ i ) { if ( i > 0 || ! isWindowsDrive ( basePath ) ) { parts . add ( baseParts [ i ] ) ; } } for ( String part : relParts ) { if ( part . equals ( \"..\" ) && parts . size ( ) > 0 ) { parts . remove ( parts . size ( ) - 1 ) ; } else if ( ! part . equals ( \".\" ) && ! part . equals ( \"..\" ) ) { parts . add ( part ) ; } } StringBuilder result = new StringBuilder ( ) ; if ( isWindowsDrive ( basePath ) ) { result . append ( baseParts [ 0 ] ) ; } for ( String part : parts ) { result . append ( File . separator ) ; result . append ( part ) ; } return new File ( result . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Counts the number of directories in a given path . [CODESPLIT] public int dirDepth ( final File path ) { final String stringPath = path . getPath ( ) ; return stringPath . length ( ) - stringPath . replaceAll ( \"[/\\\\\\\\]\" , \"\" ) . length ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Servlet life cycle callback executed at this servlet instance initialization . Mainly takes care to initialize parent container reference . If there is no servlet context attribute with the name { @link TinyContainer#ATTR_INSTANCE } this initialization fails with servlet permanently unavailable . <p > Parent container instance has application life span and its reference is valid for entire life span of this servlet instance . [CODESPLIT] @ Override public void init ( ServletConfig config ) throws UnavailableException { container = ( ContainerSPI ) config . getServletContext ( ) . getAttribute ( TinyContainer . ATTR_INSTANCE ) ; if ( container == null ) { log . fatal ( \"Tiny container instance not properly created, probably misconfigured. Servlet |%s| permanently unvailable.\" , config . getServletName ( ) ) ; throw new UnavailableException ( \"Tiny container instance not properly created, probably misconfigured.\" ) ; } servletName = Strings . concat ( config . getServletContext ( ) . getServletContextName ( ) , ' ' , config . getServletName ( ) ) ; log . trace ( \"Initialize servlet |%s|.\" , servletName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare execution context and delegates the actual HTTP request processing to abstract handler . Initialize request context bound to current thread and delegates { @link #handleRequest ( RequestContext ) } . After request handler execution takes care to cleanup request context . <p > This method also initialize logger context see { @link #logContext } with remote address of current request so that logging utility can include contextual diagnostic data into log messages . Just before exiting this service request cleanups the logger context . [CODESPLIT] @ Override protected void service ( HttpServletRequest httpRequest , HttpServletResponse httpResponse ) throws IOException , ServletException { // push context path and remote address of the requested processed by this thread to logger diagnostic context\r logContext . put ( LOG_CONTEXT_APP , httpRequest . getContextPath ( ) . isEmpty ( ) ? TinyContainer . ROOT_CONTEXT : httpRequest . getContextPath ( ) . substring ( 1 ) ) ; logContext . put ( LOG_CONTEXT_IP , httpRequest . getRemoteHost ( ) ) ; logContext . put ( LOG_CONTEXT_ID , Integer . toString ( requestID . getAndIncrement ( ) , Character . MAX_RADIX ) ) ; if ( isEmptyUriRequest ( httpRequest ) ) { log . debug ( \"Empty URI request for |%s|. Please check for <img> with empty 'src' or <link>, <script> with empty 'href' in HTML source or script resulting in such condition.\" , httpRequest . getRequestURI ( ) ) ; return ; } String requestURI = httpRequest . getRequestURI ( ) ; long start = System . currentTimeMillis ( ) ; Factory . bind ( container ) ; // request context has THREAD scope and this request thread may be reused by servlet container\r // takes care to properly initialize request context for every HTTP request\r RequestContext context = container . getInstance ( RequestContext . class ) ; context . attach ( httpRequest , httpResponse ) ; log . trace ( \"Processing request |%s|.\" , requestURI ) ; try { handleRequest ( context ) ; } catch ( IOException | ServletException | Error | RuntimeException t ) { // last line of defense; dump request context and throwable then dispatch exception to servlet container\r // servlet container will generate response page using internal templates or <error-page>, if configured\r dumpError ( context , t ) ; throw t ; } finally { log . trace ( \"%s %s processed in %d msec.\" , httpRequest . getMethod ( ) , context . getRequestURL ( ) , System . currentTimeMillis ( ) - start ) ; // cleanup remote address from logger context and detach request context instance from this request\r logContext . clear ( ) ; context . detach ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Detect self - referenced request URI . It seems there are browsers considering empty string as valid URL pointing to current loaded page . If we have an <code > img< / code > element with empty <code > src< / code > attribute browser will try to load that image from current URL that is the content of current page . This means is possible to invoke a controller many times for a single page request . <p > To avoid such condition check if this request comes from the same page i . e . referrer is current request . Note that this is also true for <code > link< / code > and <code > script< / code > with empty <code > href< / code > . Finally worthy to mention is that this check is not performed on request accepting <code > text / html< / code > . [CODESPLIT] private static boolean isEmptyUriRequest ( HttpServletRequest httpRequest ) { if ( ! \"GET\" . equals ( httpRequest . getMethod ( ) ) ) { return false ; } String acceptValue = httpRequest . getHeader ( HttpHeader . ACCEPT ) ; if ( acceptValue != null && acceptValue . contains ( ContentType . TEXT_HTML . getMIME ( ) ) ) { return false ; } String referer = httpRequest . getHeader ( HttpHeader . REFERER ) ; if ( referer == null ) { return false ; } StringBuilder uri = new StringBuilder ( httpRequest . getRequestURI ( ) ) ; String query = httpRequest . getQueryString ( ) ; if ( query != null ) { if ( query . charAt ( 0 ) != ' ' ) { uri . append ( ' ' ) ; } uri . append ( query ) ; } return referer . toLowerCase ( ) . endsWith ( uri . toString ( ) . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send unauthorized access response . This method send back a response with status code { @link HttpServletResponse#SC_UNAUTHORIZED } and response header { @link HttpHeader#WWW_AUTHENTICATE } set to basic authentication method and { @link ContainerSPI#getLoginRealm () } authentication realm . <p > If request is from an agent using XHR this method behaves a little different . XHR specification mandates that unauthorized access to be handled transparently by client agent that usually displays client agent login form not very well integrated with application . Below is a snippet from this framework script library . <p > For not authorized XHR requests this method sends { @link HttpServletResponse#SC_OK } and custom response header { @link HttpHeader#X_HEADER_LOCATION } set to application login page see { @link ContainerSPI#getLoginPage () } . Client script can handle this response and redirect to given login page . [CODESPLIT] protected static void sendUnauthorized ( RequestContext context ) { final ContainerSPI container = context . getContainer ( ) ; final HttpServletResponse httpResponse = context . getResponse ( ) ; if ( httpResponse . isCommitted ( ) ) { log . fatal ( \"Abort HTTP transaction. Attempt to send reponse after response already commited.\" ) ; return ; } log . error ( \"Reject unauthorized request for private resource or service: |%s|.\" , context . getRequestURI ( ) ) ; String loginPage = container . getLoginPage ( ) ; if ( HttpHeader . isXHR ( context . getRequest ( ) ) && loginPage != null ) { // XMLHttpRequest specs mandates that redirection codes to be performed transparently by user agent\r // this means redirect from server does not reach script counterpart\r // as workaround uses 200 OK and X-JSLIB-Location extension header\r log . trace ( \"Send X-JSLIB-Location |%s| for rejected XHR request: |%s|\" , container . getLoginPage ( ) , context . getRequestURI ( ) ) ; httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; httpResponse . setHeader ( HttpHeader . X_HEADER_LOCATION , container . getLoginPage ( ) ) ; return ; } log . trace ( \"Send WWW-Authenticate |Basic realm=%s| for rejected request: |%s|\" , container . getLoginRealm ( ) , context . getRequestURI ( ) ) ; httpResponse . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; httpResponse . setHeader ( HttpHeader . WWW_AUTHENTICATE , String . format ( \"Basic realm=%s\" , container . getLoginRealm ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send response for bad request with request URI as message . This utility method is used when a request URI is not well formed as expected by concrete servlet implementation . It dumps request context and delegates servlet container { @link HttpServletResponse#sendError ( int String ) } to send { @link HttpServletResponse#SC_BAD_REQUEST } . [CODESPLIT] protected static void sendBadRequest ( RequestContext context ) throws IOException { log . error ( \"Bad request format for resource or service: |%s|.\" , context . getRequestURI ( ) ) ; context . dump ( ) ; context . getResponse ( ) . sendError ( HttpServletResponse . SC_BAD_REQUEST , context . getRequestURI ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send response for resource or service not found containing the exception that describes missing entity . This method sends back exception object wrapped in { @link RemoteException } . Response is encoded JSON and status code is { @link HttpServletResponse#SC_NOT_FOUND } . [CODESPLIT] protected static void sendNotFound ( RequestContext context , Exception exception ) throws IOException { log . error ( \"Request for missing resource or service: |%s|.\" , context . getRequestURI ( ) ) ; sendJsonObject ( context , new RemoteException ( exception ) , HttpServletResponse . SC_NOT_FOUND ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send server error response with given exception serialized JSON . This utility method dumps stack trace and request context to application logger and send back throwable object . Response is encoded JSON and status code is { @link HttpServletResponse#SC_INTERNAL_SERVER_ERROR } . If given exception argument is { @link InvocationException } or { @link InvocationTargetException } extract the cause . <p > There is a special case for { @link BusinessException } . This exception signals broken business constrain and is send back also as JSON object but with status code { @link HttpServletResponse#SC_BAD_REQUEST } . Also does not dump exception stack trace or request context . [CODESPLIT] protected static void sendError ( RequestContext context , Throwable throwable ) throws IOException { if ( throwable instanceof InvocationException && throwable . getCause ( ) != null ) { throwable = throwable . getCause ( ) ; } if ( throwable instanceof InvocationTargetException ) { throwable = ( ( InvocationTargetException ) throwable ) . getTargetException ( ) ; } if ( throwable instanceof BusinessException ) { // business constrains exception is generated by user space code and sent to client using HTTP response\r // status 400 - HttpServletResponse.SC_BAD_REQUEST, as JSON serialized object\r log . debug ( \"Send business constrain exception |%d|.\" , ( ( BusinessException ) throwable ) . getErrorCode ( ) ) ; sendJsonObject ( context , throwable , HttpServletResponse . SC_BAD_REQUEST ) ; } else { dumpError ( context , throwable ) ; sendJsonObject ( context , new RemoteException ( throwable ) , HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dump throwable stack trace and request context to application logger . [CODESPLIT] protected static void dumpError ( RequestContext context , Throwable throwable ) { log . dump ( \"Error on HTTP request:\" , throwable ) ; context . dump ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send object back to client encoded JSON with given HTTP status code . Take care to set content type length and language . Content language is extracted from request context locale . [CODESPLIT] protected static void sendJsonObject ( RequestContext context , Object object , int statusCode ) throws IOException { final HttpServletResponse httpResponse = context . getResponse ( ) ; if ( httpResponse . isCommitted ( ) ) { log . fatal ( \"Abort HTTP transaction. Attempt to send JSON object after reponse commited.\" ) ; return ; } log . trace ( \"Send response object |%s|.\" , object . toString ( ) ) ; Json json = Classes . loadService ( Json . class ) ; String buffer = json . stringify ( object ) ; byte [ ] bytes = buffer . getBytes ( \"UTF-8\" ) ; httpResponse . setStatus ( statusCode ) ; httpResponse . setContentType ( ContentType . APPLICATION_JSON . getValue ( ) ) ; httpResponse . setContentLength ( bytes . length ) ; httpResponse . setHeader ( \"Content-Language\" , context . getLocale ( ) . toLanguageTag ( ) ) ; httpResponse . getOutputStream ( ) . write ( bytes ) ; httpResponse . getOutputStream ( ) . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds another template to the list . If the list does not exist it will be created . [CODESPLIT] public final void addParamTemplate ( final ParameterizedTemplateModel paramTemplate ) { if ( paramTemplates == null ) { paramTemplates = new ArrayList < ParameterizedTemplateModel > ( ) ; } paramTemplates . add ( paramTemplate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all templates to the list . If the list does not exist it will be created . [CODESPLIT] public final void addParamTemplates ( final List < ParameterizedTemplateModel > list ) { if ( list != null ) { for ( final ParameterizedTemplateModel template : list ) { addParamTemplate ( template ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initalizes the object . [CODESPLIT] public final void init ( final SrcGen4JContext context , final Map < String , String > vars ) { if ( paramTemplates != null ) { for ( final ParameterizedTemplateModel paramTemplate : paramTemplates ) { paramTemplate . init ( context , vars ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list that contains all models that reference the given template . [CODESPLIT] public final List < ParameterizedTemplateModel > findReferencesTo ( final File templateDir , final File templateFile ) { final List < ParameterizedTemplateModel > result = new ArrayList < ParameterizedTemplateModel > ( ) ; if ( ( paramTemplates != null ) && Utils4J . fileInsideDirectory ( templateDir , templateFile ) ) { for ( final ParameterizedTemplateModel paramTemplate : paramTemplates ) { if ( paramTemplate . hasReferenceTo ( templateDir , templateFile ) ) { result . add ( paramTemplate ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether two StringBuilder { @code a } and { @code b } are equal . <p > This method removes whitespaces around both strings first . [CODESPLIT] @ Override public final boolean unsafeEquals ( final StringBuilder a , Object b ) { return a . toString ( ) . trim ( ) . equals ( b . toString ( ) . trim ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write bytes to output stream of HTTP response . This method invokes { @link StreamHandler#invokeHandler ( OutputStream ) } with HTTP response output stream . Stream handler instance is created by application and allows application logic access to HTTP response stream . [CODESPLIT] @ Override public void write ( HttpServletResponse httpResponse , Object value ) throws IOException { ( ( StreamHandler < ? > ) value ) . invokeHandler ( httpResponse . getOutputStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Controls whether a save button is shown and fields are editable . [CODESPLIT] public void setSaveEnabled ( boolean val ) { saveButton . setVisible ( val ) ; setReadOnly ( ! val ) ; entityForm . setReadOnly ( ! val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the element . [CODESPLIT] protected void delete ( ) { String question = \"Are you sure you want to delete \" + getCaption ( ) + \"?\" ; ConfirmDialog . show ( getUI ( ) , question , ( ConfirmDialog cd ) -> { if ( cd . isConfirmed ( ) ) { try { onDelete ( ) ; close ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex ) { onError ( ex ) ; } catch ( RuntimeException ex ) { // Must explicitly send unhandled exceptions to error handler. // Would otherwise get swallowed silently within callback handler. getUI ( ) . getErrorHandler ( ) . error ( new com . vaadin . server . ErrorEvent ( ex ) ) ; } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for deleting the element . [CODESPLIT] protected void onDelete ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { endpoint . delete ( ) ; eventBus . post ( new ElementDeletedEvent <> ( endpoint ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces variables ( if defined ) in the path name and arguments . [CODESPLIT] public final void init ( final Map < String , String > vars ) { path = Utils4J . replaceVars ( path , vars ) ; name = Utils4J . replaceVars ( name , vars ) ; if ( arguments != null ) { for ( final Argument argument : arguments ) { argument . init ( vars ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens the file and returns a { @code BufferedReader } object using the given encoding . [CODESPLIT] public BufferedReader openBufferedReader ( final String encoding ) throws IOException { final InputStream fis = openInputStream ( ) ; final InputStreamReader isr = new InputStreamReader ( fis , encoding ) ; return new BufferedReader ( isr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses managed class constructor to create new instance with provided arguments . Arguments should be in order types and number required by constructor signature . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public < T > T newInstance ( ManagedClassSPI managedClass , Object ... args ) { Constructor < ? > constructor = managedClass . getConstructor ( ) ; if ( constructor == null ) { throw new BugError ( \"Local instance factory cannot instantiate |%s|. Missing constructor.\" , managedClass ) ; } Object instance = null ; try { instance = constructor . newInstance ( args ) ; } catch ( IllegalArgumentException e ) { log . error ( \"Wrong number of arguments or bad types for |%s|: [%s].\" , constructor , Strings . join ( Classes . getParameterTypes ( args ) ) ) ; throw e ; } catch ( InstantiationException e ) { // managed class implementation is already validated, i.e. is not abstract and\r // test for existing constructor is performed... so no obvious reasons for instantiation exception\r throw new BugError ( e ) ; } catch ( IllegalAccessException e ) { // constructor has accessibility true and class is tested for public access modifier\r // so there is no reason for illegal access exception\r throw new BugError ( e ) ; } catch ( InvocationTargetException e ) { log . error ( \"Managed instance constructor |%s| fail due to: %s.\" , constructor , e . getCause ( ) ) ; throw new InvocationException ( e ) ; } if ( managedClass . getInstanceType ( ) . equals ( InstanceType . PROXY ) ) { // there are two proxy handlers: one transactional and one not\r // the difference is that transactional proxy handler gets a reference to an external transactional resource\r ManagedProxyHandler handler = null ; if ( managedClass . isTransactional ( ) ) { TransactionalResource transactionalResource = managedClass . getContainer ( ) . getInstance ( TransactionalResource . class ) ; handler = new ManagedProxyHandler ( transactionalResource , managedClass , instance ) ; } else { handler = new ManagedProxyHandler ( managedClass , instance ) ; } final ClassLoader classLoader = managedClass . getImplementationClass ( ) . getClassLoader ( ) ; final Class < ? > [ ] interfaceClasses = managedClass . getInterfaceClasses ( ) ; return ( T ) Proxy . newProxyInstance ( classLoader , interfaceClasses , handler ) ; } return ( T ) instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and initializes a SrcGen4J configuration from a configuration file that contains ONLY generators / parsers of type { @link ParameterizedTemplateParser } and { @link ParameterizedTemplateGenerator } . [CODESPLIT] public static SrcGen4JConfig createAndInit ( final SrcGen4JContext context , final File configFile ) throws UnmarshalObjectException { try { final JaxbHelper helper = new JaxbHelper ( ) ; final SrcGen4JConfig config = helper . create ( configFile , JAXBContext . newInstance ( SrcGen4JConfig . class , VelocityGeneratorConfig . class , ParameterizedTemplateParserConfig . class , ParameterizedTemplateGeneratorConfig . class ) ) ; config . init ( context , Utils4J . getCanonicalFile ( configFile . getParentFile ( ) ) ) ; return config ; } catch ( final JAXBException ex ) { throw new UnmarshalObjectException ( \"Error reading the configuration: \" + configFile , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "PEM : Privacy - enhanced Electronic Mail [CODESPLIT] public static String toPemEncoded ( byte [ ] der , String label ) { StringWriter pem = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( pem ) ; pw . append ( \"-----BEGIN \" ) . append ( label ) . println ( \"-----\" ) ; pw . write ( new String ( Base64Delegate . getDefault ( ) . mimeEncode ( der ) , CharsetUtils . US_ASCII ) ) ; pw . println ( ) ; pw . append ( \"-----END \" ) . append ( label ) . println ( \"-----\" ) ; pw . close ( ) ; return pem . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all Link headers listed in an { @link HttpResponse } . [CODESPLIT] public static Iterable < LinkHeader > getLinkHeaders ( HttpResponse response ) { return stream ( response . getHeaders ( \"Link\" ) ) . flatMap ( x -> stream ( x . getElements ( ) ) . map ( LinkHeader :: new ) ) . collect ( toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads invocation arguments from HTTP request URL parameters accordingly formal parameters list . This arguments reader implementation delegates { @link QueryParametersParser } for URL parameters parsing . [CODESPLIT] @ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { try { QueryParametersParser queryParameters = new QueryParametersParser ( httpRequest . getInputStream ( ) ) ; return queryParameters . getArguments ( formalParameters ) ; } catch ( SyntaxException e ) { throw new IllegalArgumentException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves the result <code > result< / code > of the file { @code file } . [CODESPLIT] @ Override public void put ( final File file , final Counts result ) { FileCount fileCount = new FileCount ( file , result ) ; if ( results . contains ( fileCount ) ) { results . remove ( fileCount ) ; } results . add ( fileCount ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the { @code Counts } of a filename . [CODESPLIT] public Counts get ( final File file ) { int index = results . indexOf ( new FileCount ( file , null ) ) ; if ( index == - 1 ) { return null ; } else { return results . get ( index ) . getCounts ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all saved filenames . [CODESPLIT] public File [ ] getFiles ( ) { List < File > result = new ArrayList <> ( ) ; for ( FileCount fileCount : results ) { result . add ( fileCount . getFile ( ) ) ; } Collections . sort ( result , new FitFileComparator ( ) ) ; return result . toArray ( new File [ result . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the sum of all results . [CODESPLIT] public Counts getSummary ( ) { Counts result = new Counts ( ) ; for ( FileCount fileCount : results ) { if ( fileCount . getCounts ( ) != null ) { result . tally ( fileCount . getCounts ( ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a single HTML Table row representing the results of the file { @code file } . [CODESPLIT] public String getRow ( final File file ) { StringBuilder builder = new StringBuilder ( ) ; Counts counts = get ( file ) ; builder . append ( \"<tr bgcolor=\\\"\" ) ; builder . append ( color ( counts ) ) ; builder . append ( \"\\\"><td>\" ) ; int depth = dirHelper . dirDepth ( file ) ; indent ( depth , builder ) ; builder . append ( \"<a href=\\\"\" ) ; builder . append ( FitUtils . htmlSafeFile ( file ) ) ; builder . append ( \"\\\">\" ) ; builder . append ( file . getName ( ) ) ; builder . append ( \"</a>\" ) ; builder . append ( \"</td><td>\" ) ; if ( counts == null ) { builder . append ( \"(none)\" ) ; } else { builder . append ( counts . toString ( ) ) ; } builder . append ( \"</td></tr>\" ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a summary row for a whole test run . [CODESPLIT] public String getSummaryRow ( final File directory ) { StringBuilder builder = new StringBuilder ( ) ; Counts counts = getSummary ( ) ; builder . append ( \"<tr bgcolor=\\\"\" ) ; builder . append ( color ( counts ) ) ; builder . append ( \"\\\"><th style=\\\"text-align: left\\\">\" ) ; builder . append ( directory . getName ( ) ) ; builder . append ( \"</th><th style=\\\"text-align: left\\\">\" ) ; builder . append ( counts . toString ( ) ) ; builder . append ( \"</th></tr>\" ) ; return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints out a table to { @code stream } which contains all saved results including all summary rows . [CODESPLIT] @ Override public void print ( final File directory , final OutputStream stream ) throws IOException { OutputStreamWriter osw = new OutputStreamWriter ( stream ) ; BufferedWriter bw = new BufferedWriter ( osw ) ; bw . write ( \"<table>\" ) ; bw . write ( getSummaryRow ( directory ) ) ; bw . write ( \"<tr><td colspan=\\\"2\\\"></td></tr>\" ) ; File [ ] files = getFiles ( ) ; if ( files . length == 0 ) { bw . write ( \"<tr><td colspan=\\\"2\\\">no files found</td></tr>\" ) ; } else { File currentDir = directory ; for ( File file : files ) { File newDir = file . getAbsoluteFile ( ) . getParentFile ( ) ; if ( ! newDir . equals ( currentDir ) && ! dirHelper . isSubDir ( currentDir , newDir ) ) { for ( File tmpDir : dirHelper . getParentDirs ( dirHelper . getCommonDir ( currentDir , file ) , newDir ) ) { bw . write ( getSubSummaryRow ( tmpDir ) ) ; } } currentDir = newDir ; bw . write ( getRow ( file ) ) ; } } bw . write ( \"</table>\" ) ; bw . flush ( ) ; osw . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a HTML summary row for a subdirectory . [CODESPLIT] public String getSubSummaryRow ( final File path ) throws IOException { Counts sum = subDirSum ( path ) ; return String . format ( \"<tr bgcolor=\\\"%s\\\"><th style=\\\"text-align: left\\\">%s</th><td>%s</td></tr>\" , color ( sum ) , FitUtils . htmlSafeFile ( dirHelper . abs2rel ( new File ( \"\" ) . getAbsolutePath ( ) , path . getAbsolutePath ( ) ) ) , sum . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize return value to HTTP response using JSON encoding . This method delegates { @link Json#stringify ( java . io . Writer Object ) } for value serialization . [CODESPLIT] @ Override public void write ( HttpServletResponse httpResponse , Object value ) throws IOException { json . stringify ( new OutputStreamWriter ( httpResponse . getOutputStream ( ) , \"UTF-8\" ) , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegates { @link AppFactory#getInstance ( Class Object ... ) } . [CODESPLIT] public static < T > T getInstance ( Class < T > interfaceClass , Object ... args ) { return getAppFactory ( ) . getInstance ( interfaceClass , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegates { @link AppFactory#getInstance ( String Class Object ... ) } . [CODESPLIT] public static < T > T getInstance ( String instanceName , Class < T > interfaceClass , Object ... args ) { return getAppFactory ( ) . getInstance ( instanceName , interfaceClass , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegates { @link AppFactory#getOptionalInstance ( Class Object ... ) } . [CODESPLIT] public static < T > T getOptionalInstance ( Class < T > interfaceClass , Object ... args ) { return getAppFactory ( ) . getOptionalInstance ( interfaceClass , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delegates { @link AppFactory#getRemoteInstance ( String Class ) } . [CODESPLIT] public static < T > T getRemoteInstance ( String implementationURL , Class < ? super T > interfaceClass ) { return getAppFactory ( ) . getRemoteInstance ( implementationURL , interfaceClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to retrieve application factory bound to current thread . Retrieve application factory from current thread local storage . In order to be successfully this method must be preceded by { @link #bind ( AppFactory ) } called from current thread ; otherwise bug error is thrown . [CODESPLIT] public static AppFactory getAppFactory ( ) { AppFactory appFactory = tls . get ( ) ; if ( appFactory == null ) { throw new BugError ( \"No application factory bound to current thread |%s|. See #bind(AppFactory).\" , Thread . currentThread ( ) ) ; } return appFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a row of filter text boxes to a Vaadin { @link Grid } . [CODESPLIT] public static void addFilterRow ( Grid grid ) { if ( grid . getHeaderRowCount ( ) < 2 ) { grid . appendHeaderRow ( ) ; } Grid . HeaderRow headerRow = grid . getHeaderRow ( 1 ) ; Container . Indexed container = grid . getContainerDataSource ( ) ; container . getContainerPropertyIds ( ) . forEach ( pid -> { TextField filterField = new TextField ( ) ; filterField . setInputPrompt ( \"Filter\" ) ; filterField . addStyleName ( ValoTheme . TEXTFIELD_SMALL ) ; filterField . setWidth ( 100 , Sizeable . Unit . PERCENTAGE ) ; filterField . addTextChangeListener ( event -> { ( ( Container . SimpleFilterable ) container ) . removeContainerFilters ( pid ) ; if ( ! event . getText ( ) . isEmpty ( ) ) { ( ( Container . Filterable ) container ) . addContainerFilter ( new SimpleStringFilter ( pid , event . getText ( ) , true , false ) ) ; } } ) ; headerRow . getCell ( pid ) . setComponent ( filterField ) ; } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load service defined by managed class interface and return service instance . This factory does not support arguments . Service provider should be present into run - time otherwise no provider exception is thrown . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ Override public < I > I newInstance ( ManagedClassSPI managedClass , Object ... args ) { if ( args . length > 0 ) { throw new IllegalArgumentException ( \"Service instances factory does not support arguments.\" ) ; } Class < ? > [ ] interfaceClasses = managedClass . getInterfaceClasses ( ) ; if ( interfaceClasses == null ) { throw new BugError ( \"Invalid managed class. Null interface classes.\" ) ; } if ( interfaceClasses . length != 1 ) { throw new BugError ( \"Invalid managed class. It should have exactly one interface class.\" ) ; } return ( I ) Classes . loadService ( interfaceClasses [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the setup class . [CODESPLIT] public final Class < ? > getSetupClass ( ) { if ( setupClass != null ) { return setupClass ; } LOG . info ( \"Creating setup class: {}\" , setupClassName ) ; try { setupClass = Class . forName ( setupClassName , true , context . getClassLoader ( ) ) ; } catch ( final ClassNotFoundException ex ) { throw new RuntimeException ( \"Couldn't load setup class: \" + setupClassName , ex ) ; } return setupClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of model directories to parse . [CODESPLIT] public final List < File > getModelDirs ( ) { if ( ( modelDirs == null ) && ( modelPath != null ) ) { modelDirs = paths ( ) . stream ( ) . filter ( XtextParserConfig :: isFile ) . map ( XtextParserConfig :: asFile ) . collect ( Collectors . toList ( ) ) ; } return modelDirs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of model resources to parse . [CODESPLIT] public final List < URI > getModelResources ( ) { if ( ( modelResources == null ) && ( modelPath != null ) ) { modelResources = new ArrayList <> ( ) ; modelResources = paths ( ) . stream ( ) . filter ( XtextParserConfig :: isResource ) . map ( XtextParserConfig :: asResource ) . collect ( Collectors . toList ( ) ) ; } return modelResources ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a row which contains two cells and registers an alias . <p > The first cell must contain the alias the second one must contains the fully qualified class name . Using another alias as class name is not permitted . <p > Cross references are resolved . [CODESPLIT] @ Override protected void doRow ( FitRow row ) { if ( row . size ( ) < 2 ) { row . cells ( ) . get ( 0 ) . ignore ( ) ; return ; } alias = validator . preProcess ( row . cells ( ) . get ( 0 ) ) ; className = validator . preProcess ( row . cells ( ) . get ( 1 ) ) ; AliasHelper aliasHelper = DependencyManager . getOrCreate ( AliasHelper . class ) ; aliasHelper . register ( alias , className ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a set of candidates for selection . [CODESPLIT] public void setCandidates ( Collection < T > candidates ) { twinColSelect . setContainerDataSource ( container = new BeanItemContainer <> ( entityType , candidates ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the file { @code fileName } using the current runner and replaces the current row with the results . [CODESPLIT] public void file ( final String fileName ) throws Exception { String in = thisDir . getAbsolutePath ( ) ; File out = outDir . getAbsoluteFile ( ) ; //noinspection ResultOfMethodCallIgnored out . mkdirs ( ) ; File inputFile = dirHelper . rel2abs ( in , fileName ) ; File outputFile = dirHelper . subdir ( out , inputFile . getName ( ) ) ; Counts result = runner . run ( inputFile , outputFile ) ; appendResults ( row , inputFile . getName ( ) , result ) ; row . getTable ( ) . getCounts ( ) . tally ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : not tested? [CODESPLIT] public void directory ( final String dir ) throws Exception { File srcDir = dirHelper . rel2abs ( thisDir . getAbsolutePath ( ) , dir ) ; List < FileInformation > files = new DirectoryFilter ( srcDir , dirHelper ) . getSelectedFiles ( ) ; RunConfiguration runConfiguration = new RunConfiguration ( ) ; runConfiguration . setEncoding ( runner . getEncoding ( ) ) ; runConfiguration . setBaseDir ( srcDir ) ; runConfiguration . setDestination ( outDir . getPath ( ) ) ; runConfiguration . setSource ( files . toArray ( new FileInformation [ files . size ( ) ] ) ) ; System . out . println ( \"Run: \" + files + \" in \" + srcDir + \" to \" + outDir ) ; final FitRunner fitRunner = new FitRunner ( dirHelper , runConfiguration ) ; FitParseResult results = new FitParseResult ( ) ; fitRunner . run ( results ) ; results . insertAndReplace ( row ) ; row . getTable ( ) . getCounts ( ) . tally ( results . getCounts ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load configuration document from file . [CODESPLIT] protected static void loadXML ( InputStream inputStream , Loader loader ) throws ConfigException { try { SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; SAXParser parser = factory . newSAXParser ( ) ; XMLReader reader = parser . getXMLReader ( ) ; reader . setContentHandler ( loader ) ; reader . parse ( new InputSource ( inputStream ) ) ; } catch ( Exception e ) { throw new ConfigException ( \"Fail to load configuration document from file |%s|: %s\" , inputStream , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for errors reported by REST endpoints . [CODESPLIT] protected void onError ( Exception ex ) { Notification . show ( \"Error\" , ex . getLocalizedMessage ( ) , Notification . Type . ERROR_MESSAGE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a form layout with fields for all properties exposed by the entity . [CODESPLIT] protected Component buildAndBind ( Class < TEntity > entityType ) { FormLayout layout = new FormLayout ( ) ; getPropertiesWithoutAnnotation ( entityType , EditorHidden . class ) . forEach ( ( property ) - > { if ( property . getWriteMethod ( ) == null ) { return ; } Component component = buildAndBind ( property ) ; component . setWidth ( 100 , Unit . PERCENTAGE ) ; if ( component . getCaption ( ) == null ) { component . setCaption ( propertyIdToHumanFriendly ( property . getName ( ) ) ) ; } if ( component instanceof DateField ) { ( ( DateField ) component ) . setResolution ( Resolution . SECOND ) ; } layout . addComponent ( component ) ; getAnnotation ( entityType , property , Description . class ) . ifPresent ( x -> layout . addComponent ( buildDescriptionComponent ( property , x . value ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse URL query parameters provided by source reader . Detect query parameters name and and value and update a list of parsed parameters . Takes care to decode escaped characters from both parameter names and values . <p > This parser expect UTF - 8 for text encoding and throws unsupported encoding for different codes . [CODESPLIT] private static List < Parameter > parse ( Reader reader ) throws IOException { List < Parameter > parameters = new ArrayList < Parameter > ( ) ; Parameter parameter = new Parameter ( ) ; State state = State . NAME ; for ( ; ; ) { int b = reader . read ( ) ; if ( b == - 1 ) { // conclude last parameter value\r if ( parameter . isEmpty ( ) ) { break ; } if ( parameters . isEmpty ( ) && parameter . isRawValue ( ) ) { parameter . commitRawValue ( ) ; } else { parameter . commitValue ( ) ; } parameters . add ( parameter ) ; break ; } char c = ( char ) b ; switch ( state ) { case NAME : switch ( c ) { case ' ' : state = State . VALUE ; parameter . commitName ( ) ; break ; case ' ' : if ( parameter . getBuilder ( ) . isEmpty ( ) ) { throw new SyntaxException ( \"Invalid query string. Empty parameter name.\" ) ; } else { throw new SyntaxException ( \"Invalid query string parameter |%s|. Missing name/value separator.\" , parameter . getBuilder ( ) ) ; } default : parameter . append ( c ) ; } break ; case VALUE : switch ( c ) { case ' ' : state = State . NAME ; parameter . commitValue ( ) ; parameters . add ( parameter ) ; parameter = new Parameter ( ) ; break ; case ' ' : throw new SyntaxException ( \"Invalid query string parameter |%s|. Unescaped '=' character.\" , parameter . getBuilder ( ) ) ; default : parameter . append ( c ) ; } } } return parameters ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get an array of arguments suitable for a method invocation . This method did its best to fill the arguments array . The logic is simple : ignore query extra parameters and set to null the missing ones . Both cases are recorded to debug log . Returned arguments array has the same size as requested formal parameters array . <p > Parameter values from parsed { @link #parameters } are converted to requested type using { @link #asObject ( String Type ) } utility method . If formal parameters has a single type that has no converter uses reflection to map query parameters to object field by name . <p > Note that because parameter names are not preserved on run - time query parameters are mapped by position to invocation arguments . This means is caller responsibility to match formal parameters order and type with actual query string parameters . [CODESPLIT] public Object [ ] getArguments ( Type [ ] formalParameters ) { if ( formalParameters . length == 0 ) { return new Object [ 0 ] ; } Object [ ] arguments = new Object [ formalParameters . length ] ; if ( isObject ( formalParameters ) ) { // if there is single formal parameter and it is not a value type create object instance and initialize fields from\r // request parameters; object class should have no arguments constructor\r Class < ? > type = ( Class < ? > ) formalParameters [ 0 ] ; Object object = Classes . newInstance ( type ) ; for ( Parameter parameter : parameters ) { Field field = Classes . getField ( type , Strings . toMemberName ( parameter . getName ( ) ) ) ; Classes . setFieldValue ( object , field , asObject ( parameter . getValue ( ) , field . getType ( ) ) ) ; } return new Object [ ] { object } ; } int i = 0 , argumentsCount = Math . min ( formalParameters . length , parameters . size ( ) ) ; for ( i = 0 ; i < argumentsCount ; ++ i ) { arguments [ i ] = asObject ( parameters . get ( i ) . getValue ( ) , formalParameters [ i ] ) ; } for ( ; i < formalParameters . length ; ++ i ) { log . debug ( \"Missing request parameter |%s|. Set it to null.\" , i , formalParameters [ i ] ) ; arguments [ i ] = null ; } for ( ; i < parameters . size ( ) ; ++ i ) { log . debug ( \"Unused request parameter |%s|. Ignore it.\" , parameters . get ( i ) ) ; } return arguments ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to convert string parameter to an instance of a given type . Requested <code > type< / code > should be a value type as accepted by converter package or an array / collection of value types . In the later case <code > value< / code > should be a comma separated string of items . If given <code > value< / code > is null returns an empty value as defined by { @link Types#getEmptyValue ( Type ) } . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static < T > T asObject ( String value , Type type ) { if ( value == null ) { return ( T ) Types . getEmptyValue ( type ) ; } if ( ! Types . isArrayLike ( type ) ) { if ( ! ( type instanceof Class ) ) { throw new BugError ( \"Generic value types are not supported.\" ) ; } if ( ConverterRegistry . hasType ( type ) ) { return ConverterRegistry . getConverter ( ) . asObject ( value , ( Class < T > ) type ) ; } log . debug ( \"Missing converter for query parameter of type |%s|.\" , type ) ; return ( T ) Types . getEmptyValue ( type ) ; } // here we have an array/collection represented as comma separated primitives\r List < String > strings = Strings . split ( value , ' ' ) ; if ( type == String [ ] . class ) { return ( T ) strings . toArray ( new String [ strings . size ( ) ] ) ; } if ( Types . isKindOf ( type , Collection . class ) ) { Type collectionType = type ; Class < ? > itemType = String . class ; if ( type instanceof ParameterizedType ) { collectionType = ( ( ParameterizedType ) type ) . getRawType ( ) ; itemType = ( Class < ? > ) ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; } Collection < Object > collection = Classes . newCollection ( collectionType ) ; Converter converter = ConverterRegistry . getConverter ( ) ; for ( String s : strings ) { collection . add ( converter . asObject ( s . trim ( ) , itemType ) ) ; } return ( T ) collection ; } throw new BugError ( \"Type not supported |%s|.\" , type ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if method formal parameters designates a strict object that is is not primitive array collection or map . [CODESPLIT] private static boolean isObject ( Type [ ] formalParameters ) { if ( formalParameters . length != 1 ) { return false ; } final Type type = formalParameters [ 0 ] ; if ( ! ( type instanceof Class ) ) { return false ; } if ( Types . isPrimitive ( type ) ) { return false ; } if ( Types . isArrayLike ( type ) ) { return false ; } if ( Types . isMap ( type ) ) { return false ; } if ( ConverterRegistry . hasType ( type ) ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses JSON deserializer to parse method invocation arguments accordingly formal parameters list . [CODESPLIT] @ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { JsonReader reader = new JsonReader ( httpRequest . getInputStream ( ) , expectedStartSequence ( formalParameters ) ) ; try { return json . parse ( reader , formalParameters ) ; } catch ( JsonException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } finally { reader . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse JSON from input stream accordingly given type . Return parsed object . [CODESPLIT] @ Override public Object read ( InputStream inputStream , Type type ) throws IOException { try { return json . parse ( new InputStreamReader ( inputStream , \"UTF-8\" ) , type ) ; } catch ( JsonException | ClassCastException | UnsupportedEncodingException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pre - process constructor arguments for local managed classes . A managed class is <code > local< / code > if is of { @link InstanceType#POJO } or { @link InstanceType#PROXY } type . Attempting to pre - process arguments for other managed class types is silently ignored . This method delegates { @link #preProcessArguments ( ManagedClassSPI Member Class [] Object ... ) } . [CODESPLIT] public Object [ ] preProcessArguments ( ManagedClassSPI managedClass , Object ... args ) { // arguments can be null if on invocations chain there is Proxy handler invoked with no arguments\r if ( args == null ) { args = EMPTY_ARGS ; } if ( managedClass . getImplementationClass ( ) == null ) { return args ; } Constructor < ? > constructor = managedClass . getConstructor ( ) ; // managed class constructor parameters have the same limitation as injected fields: they must be a managed\r // class on their turn; it is considered a bug trying to use not managed classes as constructor argument\r // because managed class is not generic is safe to use getParameterTypes instead of getGenericParameterTypes\r final Class < ? > [ ] types = constructor . getParameterTypes ( ) ; return preProcessArguments ( managedClass , constructor , types , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pre - process managed method invocation arguments . This processor prepares invocation arguments for given managed method ; it just delegates { @link #preProcessArguments ( ManagedClassSPI Member Class [] Object ... ) } . [CODESPLIT] public Object [ ] preProcessArguments ( ManagedMethodSPI managedMethod , Object ... args ) { // arguments can be null if on invocations chain there is Proxy handler invoked with no arguments\r if ( args == null ) { args = EMPTY_ARGS ; } final ManagedClassSPI managedClass = managedMethod . getDeclaringClass ( ) ; final Method method = managedMethod . getMethod ( ) ; final Class < ? > [ ] types = method . getParameterTypes ( ) ; return preProcessArguments ( managedClass , method , types , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Update and validate invocation arguments against given formal parameter types . If formal parameters is not empty but no invocation arguments this method will inject dependency using { @link #getDependencyValue ( ManagedClassSPI Class ) } . This method also performs arguments validity check against formal parameters throwing illegal arguments if validation fails . [CODESPLIT] private static Object [ ] preProcessArguments ( ManagedClassSPI managedClass , Member member , Class < ? > [ ] formalParameters , Object ... args ) { switch ( args . length ) { case 0 : args = new Object [ formalParameters . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) { args [ i ] = getDependencyValue ( managedClass , formalParameters [ i ] ) ; } break ; case 1 : // TODO: refine variable arguments: test for formal parameters type, document and test\r if ( args [ 0 ] instanceof VarArgs && formalParameters . length == 1 && formalParameters [ 0 ] . isArray ( ) ) { args [ 0 ] = ( ( VarArgs < ? > ) args [ 0 ] ) . getArguments ( ) ; } break ; } // arguments validity test against formal parameters: count and types\r if ( formalParameters . length != args . length ) { throw new IllegalArgumentException ( \"Invalid arguments count on method |%s|. Expected |%d| but got |%d|.\" , member , formalParameters . length , args . length ) ; } for ( int i = 0 ; i < formalParameters . length ; ++ i ) { if ( args [ i ] != null && ! Types . isInstanceOf ( args [ i ] , formalParameters [ i ] ) ) { throw new IllegalArgumentException ( \"Invalid argument type at position |%d| on method |%s|. Expected |%s| but got |%s|.\" , i , member , formalParameters [ i ] , args [ i ] . getClass ( ) ) ; } } return args ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extracts and removes parameters from a cell . [CODESPLIT] public static String extractCellParameter ( FitCell cell ) { final Matcher matcher = PARAMETER_PATTERN . matcher ( cell . getFitValue ( ) ) ; if ( matcher . matches ( ) ) { cell . setFitValue ( matcher . group ( 1 ) ) ; return matcher . group ( 2 ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "javax . persistence . Query & javax . persistence . TypedQuery [CODESPLIT] @ Override public java . util . Map < java . lang . String , java . lang . Object > getHints ( ) { return this . q . getHints ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Altered by Rick Mugridge to dispatch on the first Fixture [CODESPLIT] public void doDocument ( FitDocument document ) { summary . put ( \"run date\" , new Date ( ) ) ; summary . put ( \"run elapsed time\" , new RunTime ( ) ) ; if ( document != null ) { interpretTables ( document ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Added by Rick Mugridge [CODESPLIT] private void interpretTables ( FitDocument documents ) { for ( FitTable table : documents . tables ( ) ) { try { Fixture fixture = getLinkedFixtureWithArgs ( table ) ; fixture . doTable ( table ) ; counts . tally ( table . getCounts ( ) ) ; } catch ( Throwable e ) { table . exception ( e ) ; counts . exceptions ++ ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Added from FitNesse [CODESPLIT] protected Fixture getLinkedFixtureWithArgs ( FitTable table ) { Fixture fixture = loadFixture ( table . getFixtureClass ( ) ) ; fixture . setParams ( getArgsForTable ( table ) ) ; return fixture ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a fixutre by its fully quallified { @code className } . If the { @code className } is an alias the referenced class is used . [CODESPLIT] private Fixture loadFixture ( final String fixtureName ) { AliasHelper helper = DependencyManager . getOrCreate ( AliasHelper . class ) ; String realName = helper . getClazz ( fixtureName ) ; return loadFixtureByName ( realName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the SSL parameter of the mail { @link SetupHelper } . [CODESPLIT] public void ssl ( final String ssl ) { DependencyManager . getOrCreate ( SetupHelper . class ) . setSSL ( BooleanTypeHandler . parseBool ( ssl ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the port parameter of the mail { @link SetupHelper } . [CODESPLIT] public void port ( final String port ) { DependencyManager . getOrCreate ( SetupHelper . class ) . setPort ( Integer . parseInt ( port ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if given HTTP request is performed via XMLHttpRequest . [CODESPLIT] public static boolean isXHR ( HttpServletRequest httpRequest ) { String requestedWith = httpRequest . getHeader ( X_REQUESTED_WITH ) ; return requestedWith != null ? requestedWith . equalsIgnoreCase ( XML_HTTP_REQUEST ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if HTTP request is from Android . [CODESPLIT] public static boolean isAndroid ( HttpServletRequest httpRequest ) { String requestedWith = httpRequest . getHeader ( X_REQUESTED_WITH ) ; return requestedWith != null ? requestedWith . equalsIgnoreCase ( ANDROID_USER_AGENT ) : false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is enacted for empty formal parameters . It just return { @link #EMPTY_ARGUMENTS } . [CODESPLIT] @ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { return EMPTY_ARGUMENTS ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traversal //////////////////////////////// [CODESPLIT] @ Override protected void doRow ( FitRow row ) throws Exception { Date start = time ( ) ; super . doRow ( row ) ; long split = time ( ) . getTime ( ) - start . getTime ( ) ; FitCell cell = row . append ( ) ; cell . setDisplayValue ( format . format ( start ) ) ; cell . info ( \"time\" ) ; cell = row . append ( ) ; cell . setDisplayValueRaw ( split < 1000 ? \"&nbsp;\" : Double . toString ( ( split ) / 1000.0 ) ) ; cell . info ( \"split\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FIXME : test! [CODESPLIT] public void remove ( int index ) { table . select ( TAG ) . get ( index + contentStartPosition ) . remove ( ) ; rows . remove ( index ) ; updateIndices ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "FIXME : test! [CODESPLIT] public FitRow insert ( int index ) { Element tr = new Element ( Tag . valueOf ( TAG ) , table . baseUri ( ) ) ; FitRow row = new FitRow ( this , tr ) ; Element tbody = table . select ( \"tbody\" ) . first ( ) ; tbody . insertChildren ( index + contentStartPosition , Collections . singleton ( tr ) ) ; rows . add ( index , row ) ; updateIndices ( ) ; return row ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is a this wrapper for { @link StreamFactory#getInstance ( InputStream Type ) } . [CODESPLIT] @ Override public Object read ( InputStream inputStream , Type type ) throws IOException { Closeable closeable = StreamFactory . getInstance ( inputStream , type ) ; threadLocal . set ( closeable ) ; return closeable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persist instance bound to given managed instance key . This method simply uses provided <code > instanceKey< / code > argument to add instance to { @link #instancesPool } . Both arguments should to be not null . [CODESPLIT] @ Override public void persistInstance ( InstanceKey instanceKey , Object instance ) { // at this point managed class and instance are guaranteed to be non null\r instancesPool . put ( instanceKey , instance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Refresh when child elements are created or updated [CODESPLIT] @ Subscribe public void handle ( ElementEvent < TEntity > message ) { if ( message . getEndpoint ( ) . getEntityType ( ) == this . endpoint . getEntityType ( ) ) { refresh ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the content of { @code cells } . [CODESPLIT] @ Override protected void doCells ( List < FitCell > cells ) { String name = cells . get ( 0 ) . getFitValue ( ) ; processRowWithCommand ( cells , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists all properties on a bean type . Ensures properties annotated with { @link Id } or called name are always listed first . [CODESPLIT] @ SneakyThrows public static List < PropertyDescriptor > getProperties ( Class < ? > beanType ) { LinkedList < PropertyDescriptor > properties = new LinkedList <> ( ) ; for ( PropertyDescriptor property : Introspector . getBeanInfo ( beanType ) . getPropertyDescriptors ( ) ) { if ( getAnnotation ( beanType , property , Id . class ) . isPresent ( ) || property . getName ( ) . equals ( \"name\" ) ) { properties . addFirst ( property ) ; } else { properties . add ( property ) ; } } return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists all properties on a bean type that have a specific annotation on their getter or backing field . [CODESPLIT] public static < TAnnotation extends Annotation > List < PropertyDescriptor > getPropertiesWithAnnotation ( Class < ? > beanType , Class < TAnnotation > annotationType ) { LinkedList < PropertyDescriptor > result = new LinkedList <> ( ) ; getProperties ( beanType ) . forEach ( property -> { if ( property . getReadMethod ( ) != null && property . getReadMethod ( ) . getAnnotation ( annotationType ) != null || isFieldAnnotated ( beanType , property . getName ( ) , annotationType ) ) { result . add ( property ) ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an annotation of a specific type on a property s getter or its backing field . [CODESPLIT] public static < TAnnotation extends Annotation > Optional < TAnnotation > getAnnotation ( Class < ? > beanType , PropertyDescriptor property , Class < TAnnotation > annotationType ) { Optional < TAnnotation > annotation = stream ( property . getReadMethod ( ) . getAnnotationsByType ( annotationType ) ) . findAny ( ) ; return annotation . isPresent ( ) ? annotation : getAnnotationOnField ( beanType , property . getName ( ) , annotationType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the filename pattern to { @code pattern } . [CODESPLIT] public void pattern ( final String pattern ) { FileFixtureHelper helper = DependencyManager . getOrCreate ( FileFixtureHelper . class ) ; helper . setPattern ( pattern ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the directory to { @code directory } . [CODESPLIT] public void directory ( final String directory ) { FileFixtureHelper helper = DependencyManager . getOrCreate ( FileFixtureHelper . class ) ; helper . setDirectory ( new File ( directory ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the encoding to { @code encoding } . [CODESPLIT] public void encoding ( final String encoding ) { FileFixtureHelper helper = DependencyManager . getOrCreate ( FileFixtureHelper . class ) ; helper . setEncoding ( encoding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log formatted message to Java logger since framework logger is not yet initialized . [CODESPLIT] private static String log ( String message , Object ... args ) { message = String . format ( message , args ) ; java . util . logging . Logger . getLogger ( Server . class . getCanonicalName ( ) ) . log ( java . util . logging . Level . SEVERE , message ) ; return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the Ruby Whois gem to perform a whois lookup [CODESPLIT] public WhoisResult lookup ( String domain , int timeout ) { container . put ( \"domain\" , domain ) ; container . put ( \"timeout_param\" , timeout ) ; try { return ( WhoisResult ) container . runScriptlet ( JRubyWhois . class . getResourceAsStream ( \"jruby-whois.rb\" ) , \"jruby-whois.rb\" ) ; } catch ( EvalFailedException e ) { if ( e . getMessage ( ) . startsWith ( \"(ServerNotFound)\" ) ) { throw new ServerNotFoundException ( e ) ; } if ( e . getMessage ( ) . startsWith ( \"(WebInterfaceError\" ) ) { throw new WebInterfaceErrorException ( e ) ; } throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if Ruby Whois gem has a parser for a specific registrar [CODESPLIT] public boolean hasParserForWhoisHost ( String whoisHost ) { container . put ( \"host\" , whoisHost ) ; return ( Boolean ) container . runScriptlet ( JRubyWhois . class . getResourceAsStream ( \"jruby-has-parser.rb\" ) , \"jruby-has-parser.rb\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HTTP - RMI request service . This is the implementation of the { @link AppServlet#service ( javax . servlet . ServletRequest javax . servlet . ServletResponse ) } abstract method . It locates remote managed method addressed by request path deserialize actual parameters from HTTP request reflexively invoke the method and serialize method returned value to HTTP response . <p > Actual parameters are transported into HTTP request body and are encoded accordingly <code > Content - Type< / code > request header ; for supported parameters encodings please see { @link ServerEncoders#getArgumentsReader ( HttpServletRequest Type [] ) } factory method . On its side returned value is transported into HTTP response body too and is encoded accordingly its type - see { @link ServerEncoders#getValueWriter ( ContentType ) } for supported encodings for returned value . [CODESPLIT] @ Override public void handleRequest ( RequestContext context ) throws IOException { HttpServletRequest httpRequest = context . getRequest ( ) ; HttpServletResponse httpResponse = context . getResponse ( ) ; Matcher matcher = REQUEST_PATH_PATTERN . matcher ( context . getRequestPath ( ) ) ; if ( ! matcher . find ( ) ) { sendBadRequest ( context ) ; return ; } String interfaceName = className ( matcher . group ( 1 ) ) ; String methodName = matcher . group ( 2 ) ; ManagedMethodSPI managedMethod = null ; ArgumentsReader argumentsReader = null ; Object value = null ; try { ManagedClassSPI managedClass = getManagedClass ( container , interfaceName , httpRequest . getRequestURI ( ) ) ; managedMethod = getManagedMethod ( managedClass , methodName , httpRequest . getRequestURI ( ) ) ; final Type [ ] formalParameters = managedMethod . getParameterTypes ( ) ; argumentsReader = argumentsReaderFactory . getArgumentsReader ( httpRequest , formalParameters ) ; Object [ ] arguments = argumentsReader . read ( httpRequest , formalParameters ) ; Object instance = container . getInstance ( managedClass ) ; value = managedMethod . invoke ( instance , arguments ) ; } catch ( AuthorizationException e ) { sendUnauthorized ( context ) ; return ; } catch ( Throwable t ) { // all exception, including class not found, no such method and illegal argument are send back to client as they are\r sendError ( context , t ) ; return ; } finally { if ( argumentsReader != null ) { argumentsReader . clean ( ) ; } } httpResponse . setCharacterEncoding ( \"UTF-8\" ) ; if ( managedMethod . isVoid ( ) ) { httpResponse . setStatus ( HttpServletResponse . SC_NO_CONTENT ) ; return ; } ContentType contentType = valueWriterFactory . getContentTypeForValue ( value ) ; httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; httpResponse . setContentType ( contentType . getValue ( ) ) ; ValueWriter valueWriter = valueWriterFactory . getValueWriter ( contentType ) ; valueWriter . write ( httpResponse , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get remotely accessible managed class registered to a certain interface class . [CODESPLIT] private static ManagedClassSPI getManagedClass ( ContainerSPI container , String interfaceName , String requestURI ) throws ClassNotFoundException { Class < ? > interfaceClass = Classes . forOptionalName ( interfaceName ) ; if ( interfaceClass == null ) { log . error ( \"HTTP-RMI request for not existing class |%s|.\" , interfaceName ) ; throw new ClassNotFoundException ( requestURI ) ; } ManagedClassSPI managedClass = container . getManagedClass ( interfaceClass ) ; if ( managedClass == null ) { log . error ( \"HTTP-RMI request for not existing managed class |%s|.\" , interfaceName ) ; throw new ClassNotFoundException ( requestURI ) ; } if ( ! managedClass . isRemotelyAccessible ( ) ) { log . error ( \"HTTP-RMI request for local managed class |%s|. See @Remote annotation.\" , interfaceName ) ; throw new ClassNotFoundException ( requestURI ) ; } return managedClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get managed method that is remotely accessible and has requested name . [CODESPLIT] private static ManagedMethodSPI getManagedMethod ( ManagedClassSPI managedClass , String methodName , String requestURI ) throws NoSuchMethodException { ManagedMethodSPI managedMethod = managedClass . getNetMethod ( methodName ) ; if ( managedMethod == null ) { log . error ( \"HTTP-RMI request for not existing managed method |%s#%s|.\" , managedClass . getInterfaceClass ( ) . getName ( ) , methodName ) ; throw new NoSuchMethodException ( requestURI ) ; } if ( ! managedMethod . isRemotelyAccessible ( ) ) { log . error ( \"HTTP-RMI request for local managed method |%s#%s|. See @Remote annotation.\" , managedClass . getInterfaceClass ( ) . getName ( ) , methodName ) ; throw new NoSuchMethodException ( requestURI ) ; } if ( Types . isKindOf ( managedMethod . getReturnType ( ) , Resource . class ) ) { log . error ( \"HTTP-RMI request for managed method |%s#%s| returning a resource.\" , managedClass . getInterfaceClass ( ) . getName ( ) , methodName ) ; throw new NoSuchMethodException ( requestURI ) ; } return managedMethod ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract qualified class name including inner classes from class path part of the request path . Class path parameter is the class name but with slash as separator e . g . <code > / sixqs / site / controller / ParticipantController< / code > . This helper handles inner classes using standard notation with $ separator ; for example <code > / js / test / net / RmiController / Query< / code > is converted to <code > js . test . net . RmiController$Query< / code > . <p > Class nesting is not restricted to a single level . For example <code > / js / test / net / RmiController / Query / Item< / code > is converted to <code > js . test . net . RmiController$Query$Item< / code > . <p > It is expected that class path argument to be well formed . If class path argument is not valid this method behavior is not defined . [CODESPLIT] private static String className ( String classPath ) { StringBuilder className = new StringBuilder ( ) ; char separator = ' ' ; char c = classPath . charAt ( 1 ) ; // i = 1 to skip leading path separator\r for ( int i = 1 ; ; ) { if ( c == ' ' ) { c = separator ; } className . append ( c ) ; if ( ++ i == classPath . length ( ) ) { break ; } c = classPath . charAt ( i ) ; // after first class detected change separator to dollar since rest are inner classes\r // this solution copes well with not restricted inner level\r if ( Character . isUpperCase ( c ) ) { separator = ' ' ; } } return className . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the log messages contain the expected exception . [CODESPLIT] public void processNotContainsException ( Map < String , String > parameters ) { LoggingEvent match = getMessageWithException ( parameters ) ; if ( match == null ) { cell . right ( ) ; } else { cell . wrong ( match . getThrowableInformation ( ) . getThrowableStrRep ( ) [ 0 ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the log messages do not contain the expected text . [CODESPLIT] public void processNotContains ( Map < String , String > parameters ) { LoggingEvent match = getMessageWithString ( parameters ) ; if ( match == null ) { cell . right ( ) ; } else { cell . wrong ( match . getMessage ( ) . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Primitive Wrappers [CODESPLIT] public Boolean getBoolean2 ( String columnLabel ) throws java . sql . SQLException { boolean value = this . rs . getBoolean ( columnLabel ) ; return ! this . rs . wasNull ( ) ? value : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "java . sql . Wrapper [CODESPLIT] @ Override public boolean isWrapperFor ( java . lang . Class < ? > arg0 ) throws java . sql . SQLException { return this . rs . isWrapperFor ( arg0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces variables ( if defined ) in the value . [CODESPLIT] public final void init ( final Map < String , String > vars ) { value = Utils4J . replaceVars ( getValue ( ) , vars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set common HTTP response headers and delegates actual serialization to subclass . This method disables cache and set content type to value returned by subclass . [CODESPLIT] @ Override public void serialize ( HttpServletResponse httpResponse ) throws IOException { httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setContentType ( getContentType ( ) . getValue ( ) ) ; serialize ( httpResponse . getOutputStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get value of the named cookie or null if cookie does not exist . [CODESPLIT] public String get ( String name ) { Params . notNullOrEmpty ( name , \"Cookie name\" ) ; if ( cookies == null ) { return null ; } for ( Cookie cookie : cookies ) { if ( name . equals ( cookie . getName ( ) ) ) { return cookie . getValue ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add cookie to HTTP response of the current request context . Override cookie value if already exists . [CODESPLIT] public void add ( String name , String value ) { Params . notNullOrEmpty ( name , \"Cookie name\" ) ; Params . notNull ( value , \"Cookie value\" ) ; Cookie cookie = new Cookie ( name , value ) ; cookie . setPath ( \"/\" ) ; httpResponse . addCookie ( cookie ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert value object to string and delegates { @link #add ( String String ) } . String conversion is performed by { @link Converter } and may throw { @link ConverterException } . [CODESPLIT] public void add ( String name , Object value ) { add ( name , ConverterRegistry . getConverter ( ) . asString ( value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove cookie from HTTP response . If named cookie does not exist this method does nothing . [CODESPLIT] public void remove ( String name ) { Params . notNullOrEmpty ( name , \"Cookie name\" ) ; if ( cookies == null ) { return ; } for ( Cookie cookie : cookies ) { if ( name . equals ( cookie . getName ( ) ) ) { cookie . setMaxAge ( 0 ) ; cookie . setValue ( \"\" ) ; cookie . setPath ( \"/\" ) ; httpResponse . addCookie ( cookie ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get cookies iterator . Return empty iterator if not cookies on HTTP request . [CODESPLIT] public Iterator < Cookie > iterator ( ) { if ( cookies == null ) { return Collections . emptyIterator ( ) ; } return Arrays . asList ( cookies ) . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure instance with configuration object provided by instance managed class . In order to perform instance configuration instance should implement { @link Configurable } and managed class should have configuration object see { @link ManagedClassSPI#getConfig () } . If both conditions are satisfied this method executes { @link Configurable#config ( Config ) } on instance . [CODESPLIT] @ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { if ( ! ( instance instanceof Configurable ) ) { return ; } Config config = managedClass . getConfig ( ) ; if ( config == null ) { if ( ! ( instance instanceof OptionalConfigurable ) ) { return ; } log . info ( \"Default configuration for managed class |%s|.\" , managedClass ) ; } try { ( ( Configurable ) instance ) . config ( config ) ; } catch ( ConfigException e ) { throw new BugError ( \"Invalid configuration for managed class |%s|:\\r\\n\\t- %s\" , managedClass , e ) ; } catch ( Throwable t ) { throw new BugError ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an existing target file list producer instance or creates a new one if it s the first call to this method . [CODESPLIT] public final TargetFileListProducer getTargetFileListProducer ( ) { if ( tflProducer != null ) { return tflProducer ; } final Object obj = Utils4J . createInstance ( className ) ; if ( ! ( obj instanceof TargetFileListProducer ) ) { throw new IllegalStateException ( \"Expected class to be of type '\" + TargetFileListProducer . class . getName ( ) + \"', but was: \" + className ) ; } tflProducer = ( TargetFileListProducer ) obj ; return tflProducer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a public field to the constructed class . [CODESPLIT] public void add ( final Class < ? > type , final String name ) throws ClassNotFoundException { FieldGen fg ; if ( result != null ) { throw new IllegalStateException ( \"Class already generated\" ) ; } fg = new FieldGen ( Constants . ACC_PUBLIC | Constants . ACC_SUPER , Type . getType ( type ) , name , cg . getConstantPool ( ) ) ; cg . addField ( fg . getField ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the class and returns a class object which contains all added fields . [CODESPLIT] public final Class < ? > compile ( ) { if ( result == null ) { loader . loadJavaClass ( cg . getClassName ( ) , cg . getJavaClass ( ) ) ; try { result = loader . loadClass ( cg . getClassName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test that selected image identified by given token is the right response . [CODESPLIT] public boolean verifyResponse ( String token ) throws NullPointerException { return value . equals ( getValue ( tokenedImageFiles . get ( token ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Challenge value associated with image file . File name is converted to lower case extension removed and non letter characters replaces with space that is non letters are considered words separators . [CODESPLIT] private static String getValue ( File file ) throws NullPointerException { if ( file == null ) { return null ; } return file . getName ( ) . toLowerCase ( ) . replaceAll ( EXTENSION_REX , \"\" ) . replaceAll ( NOT_LETTERS_REX , \" \" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a trailing slash to the URI if it does not already have one . [CODESPLIT] @ SneakyThrows public static URI ensureTrailingSlash ( URI uri ) { URIBuilder builder = new URIBuilder ( uri ) ; if ( ! builder . getPath ( ) . endsWith ( \"/\" ) ) { builder . setPath ( builder . getPath ( ) + \"/\" ) ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a properties object which can be used by { @link de . cologneintelligence . fitgoodies . mail . providers . JavaMailMessageProvider } . Default values are not set . [CODESPLIT] public Properties generateProperties ( ) { Properties result = new Properties ( ) ; if ( proto == null ) { throw new RuntimeException ( \"no protocol selected\" ) ; } String protocol = proto . toLowerCase ( ) ; setProperty ( result , \"mail.store.protocol\" , protocol ) ; setProperty ( result , \"mail.\" + protocol + \".host\" , host ) ; setProperty ( result , \"mail.username\" , user ) ; setProperty ( result , \"mail.password\" , pass ) ; if ( port != 0 ) { setProperty ( result , \"mail.\" + protocol + \".port\" , Integer . toString ( port ) ) ; } if ( ssl ) { setProperty ( result , \"mail.\" + protocol + \".ssl\" , \"true\" ) ; } if ( protocol . equals ( \"pop3\" ) ) { setProperty ( result , \"mail.inbox\" , \"INBOX\" ) ; } else { if ( inbox == null ) { throw new RuntimeException ( \"no inbox selected\" ) ; } setProperty ( result , \"mail.inbox\" , inbox ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements tiny container boostrap logic . See class description for overall performed steps . Also loads context parameters from external descriptors using { @link ServletContext#getInitParameter ( String ) } . <p > Context initialized listener is not allowed to throw exceptions and it seems there is no standard way to ask servlet container to abort launching the web application . Tiny container solution is to leave servlet context attribute { @link #ATTR_INSTANCE } null . On { @link AppServlet#init ( javax . servlet . ServletConfig ) } mentioned attribute is tested for null and if so permanently mark servlet unavailable . <p > <b > Implementation note : < / b > bootstrap process logic is based on assumption that this <code > contextInitialized< / code > handler is called before servlets initialization . Here is the relevant excerpt from API - DOC : <em > All ServletContextListeners are notified of context initialization before any filter or servlet in the web application is initialized . < / em > [CODESPLIT] @ Override public void contextInitialized ( ServletContextEvent contextEvent ) { final ServletContext servletContext = contextEvent . getServletContext ( ) ; /** Logger diagnostic context stores contextual information regarding current request. */ LogContext logContext = LogFactory . getLogContext ( ) ; logContext . put ( LOG_CONTEXT_APP , servletContext . getContextPath ( ) . isEmpty ( ) ? TinyContainer . ROOT_CONTEXT : servletContext . getContextPath ( ) . substring ( 1 ) ) ; final long start = System . currentTimeMillis ( ) ; log . debug ( \"Starting application |%s| container...\" , servletContext . getContextPath ( ) ) ; Enumeration < String > parameterNames = servletContext . getInitParameterNames ( ) ; while ( parameterNames . hasMoreElements ( ) ) { final String name = parameterNames . nextElement ( ) ; final String value = servletContext . getInitParameter ( name ) ; contextParameters . setProperty ( name , value ) ; log . debug ( \"Load context parameter |%s| value |%s|.\" , name , value ) ; } try { ConfigBuilder builder = new TinyConfigBuilder ( servletContext , contextParameters ) ; config ( builder . build ( ) ) ; Factory . bind ( this ) ; start ( ) ; // set tiny container reference on servlet context attribute ONLY if no exception\r servletContext . setAttribute ( TinyContainer . ATTR_INSTANCE , this ) ; log . info ( \"Application |%s| container started in %d msec.\" , appName , System . currentTimeMillis ( ) - start ) ; } catch ( ConfigException e ) { log . error ( e ) ; log . fatal ( \"Bad container |%s| configuration.\" , appName ) ; } catch ( Throwable t ) { log . dump ( String . format ( \"Fatal error on container |%s| start:\" , appName ) , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Release resources used by this tiny container instance . After execution this method no HTTP requests can be handled . <p > <b > Implementation note : < / b > tiny container destruction logic is based on assumption that this <code > contextDestroyed< / code > handler is called after all web application s servlets destruction . Here is the relevant excerpt from API - DOC : <em > All servlets and filters have been destroy () ed before any ServletContextListeners are notified of context destruction . < / em > [CODESPLIT] @ Override public void contextDestroyed ( ServletContextEvent contextEvent ) { log . debug ( \"Context |%s| destroying.\" , appName ) ; try { destroy ( ) ; } catch ( Throwable t ) { log . dump ( String . format ( \"Fatal error on container |%s| destroy:\" , appName ) , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SECURITY CONTEXT INTERFACE [CODESPLIT] @ Override public boolean login ( String username , String password ) { try { getHttpServletRequest ( ) . login ( username , password ) ; } catch ( ServletException e ) { // exception is thrown if request is already authenticated, servlet container authentication is not enabled or\r // credentials are not accepted\r // consider all these conditions as login fail but record the event to application logger\r log . debug ( e ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get HTTP request from current request context . [CODESPLIT] private HttpServletRequest getHttpServletRequest ( ) { RequestContext context = getInstance ( RequestContext . class ) ; HttpServletRequest request = context . getRequest ( ) ; if ( request == null ) { throw new BugError ( \"Attempt to use not initialized HTTP request.\" ) ; } return request ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invocation handler implementation . Every method invocation on managed class interface is routed to this point . Here actual container services are implemented and method is invoked against wrapped instance . [CODESPLIT] @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { final ManagedMethodSPI managedMethod = managedClass . getManagedMethod ( method ) ; log . trace ( \"Invoke |%s|.\" , managedMethod ) ; if ( ! managedMethod . isTransactional ( ) ) { // execute managed method that is not included within transactional boundaries\r try { return managedMethod . invoke ( managedInstance , args ) ; } catch ( Throwable t ) { throw throwable ( t , \"Non transactional method |%s| invocation fails.\" , managedMethod ) ; } } if ( managedMethod . isImmutable ( ) ) { return executeImmutableTransaction ( managedMethod , args ) ; } return executeMutableTransaction ( managedMethod , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for mutable transaction execution . [CODESPLIT] private Object executeMutableTransaction ( ManagedMethodSPI managedMethod , Object [ ] args ) throws Throwable { // store transaction session on current thread via transactional resource utility\r // it may happen to have multiple nested transaction on current thread\r // since all are created by the same transactional resource, all are part of the same session\r // and there is no harm if storeSession is invoked multiple times\r // also performance penalty is comparable with the effort to prevent this multiple write\r Transaction transaction = transactionalResource . createTransaction ( ) ; transactionalResource . storeSession ( transaction . getSession ( ) ) ; try { Object result = managedMethod . invoke ( managedInstance , args ) ; transaction . commit ( ) ; if ( transaction . unused ( ) ) { log . debug ( \"Method |%s| superfluously declared transactional.\" , managedMethod ) ; } return result ; } catch ( Throwable throwable ) { transaction . rollback ( ) ; throw throwable ( throwable , \"Mutable transactional method |%s| invocation fail.\" , managedMethod ) ; } finally { if ( transaction . close ( ) ) { // it may happen to have multiple nested transaction on this thread\r // if this is the case, remove session from current thread only if outermost transaction is closed\r // of course if not nested transactions, remove at once\r transactionalResource . releaseSession ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for immutable transaction execution . [CODESPLIT] private Object executeImmutableTransaction ( ManagedMethodSPI managedMethod , Object [ ] args ) throws Throwable { Transaction transaction = transactionalResource . createReadOnlyTransaction ( ) ; // see mutable transaction comment\r transactionalResource . storeSession ( transaction . getSession ( ) ) ; try { Object result = managedMethod . invoke ( managedInstance , args ) ; if ( transaction . unused ( ) ) { log . debug ( \"Method |%s| superfluously declared transactional.\" , managedMethod ) ; } return result ; } catch ( Throwable throwable ) { throw throwable ( throwable , \"Immutable transactional method |%s| invocation fail.\" , managedMethod ) ; } finally { if ( transaction . close ( ) ) { // see mutable transaction comment\r transactionalResource . releaseSession ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare given throwable and dump it to logger with formatted message . Return prepared throwable . If throwable is { @link InvocationTargetException } or its unchecked related version { @link InvocationException } replace it with root cause . [CODESPLIT] private static Throwable throwable ( Throwable throwable , String message , Object ... args ) { Throwable t = throwable ; if ( t instanceof InvocationException && t . getCause ( ) != null ) { t = t . getCause ( ) ; } if ( t instanceof InvocationTargetException && ( ( InvocationTargetException ) t ) . getTargetException ( ) != null ) { t = ( ( InvocationTargetException ) t ) . getTargetException ( ) ; } message = String . format ( message , args ) ; log . dump ( message , t ) ; return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the only file that matches the pattern . If no file matches a <code > null< / code > . If more than one file matches a { @link FilenameNotUniqueException } is thrown . [CODESPLIT] public File getUniqueFile ( ) throws FilenameNotUniqueException , FileNotFoundException { File [ ] files = directory . listFiles ( filter ) ; if ( files == null || files . length == 0 ) { throw new FileNotFoundException ( ) ; } if ( files . length > 1 ) { throw new FilenameNotUniqueException ( filter . getPattern ( ) ) ; } return files [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of all matching files . [CODESPLIT] public File [ ] getFiles ( ) { final File [ ] files = directory . listFiles ( filter ) ; if ( files == null ) { return new File [ 0 ] ; } else { return files ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the last matching file . [CODESPLIT] public File getLastFile ( ) throws FileNotFoundException { File [ ] files = directory . listFiles ( filter ) ; if ( files == null || files . length == 0 ) { throw new FileNotFoundException ( ) ; } return files [ files . length - 1 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the table row { @code cells } . [CODESPLIT] @ Override protected void doCells ( List < FitCell > cells ) { this . cells = cells ; this . appender = getAppender ( ) ; if ( appender != null ) { try { executeCommand ( ) ; } catch ( final IllegalArgumentException e ) { cells . get ( COMMAND_COLUMN ) . exception ( \"Illegal Format\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve instance from current thread bound to given managed class or null if none found . Uses provided managed instance key to get instance from { @link #instancesPool } . Instance key argument should be not null . [CODESPLIT] @ Override public Object getInstance ( InstanceKey instanceKey ) { // at this point managed class is guaranteed to be non null\r ThreadLocal < Object > tls = instancesPool . get ( instanceKey ) ; if ( tls == null ) { synchronized ( instancesPool ) { tls = instancesPool . get ( instanceKey ) ; if ( tls == null ) { tls = new ThreadLocal <> ( ) ; instancesPool . put ( instanceKey , tls ) ; } } return null ; } return tls . get ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persist instance on current thread bound to given managed class . This method simply uses provided instance key argument to add instance to { @link #instancesPool } . Both arguments should to be not null . [CODESPLIT] @ Override public void persistInstance ( InstanceKey instanceKey , Object instance ) { // at this point managed class and instance are guaranteed to be non null\r ThreadLocal < Object > tls = instancesPool . get ( instanceKey ) ; if ( tls == null ) { throw new BugError ( \"Invalid methods invocation sequence. Ensure getInstance() is invoked before and is executed in the same thread.\" ) ; } tls . set ( instance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear all threads local storage and { [CODESPLIT] @ Override public void clear ( ) { for ( ThreadLocal < Object > threadLocal : instancesPool . values ( ) ) { threadLocal . remove ( ) ; } instancesPool . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Beside initialization inherited from { @link AppServlet#init ( ServletConfig ) } this method takes care to initialize event stream manager reference . [CODESPLIT] @ Override public void init ( ServletConfig config ) throws UnavailableException { super . init ( config ) ; log . trace ( \"init(ServletConfig)\" ) ; eventStreamManager = container . getInstance ( EventStreamManager . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create { @link EventStream } for session ID from request URI and run { @link EventStream#loop () } as far it returns true . This method takes also care to handle connections errors due to network or client failure . At event stream loop exit graceful or due to error unbind event stream from manager . <p > If event stream cannot be created due to bad session ID responds with bad request error code 400 . <p > Note that this method does not return as long client requesting for event stream is connected keeping HTTP request thread and servlet allocated even there is no event to send for this particular client . [CODESPLIT] @ Override protected void handleRequest ( RequestContext context ) throws IOException { log . trace ( \"handleRequest(RequestContext)\" ) ; final HttpServletResponse httpResponse = context . getResponse ( ) ; final String sessionID = getEventStreamSessionID ( context . getRequestPath ( ) ) ; EventStream eventStream = eventStreamManager . createEventStream ( sessionID ) ; if ( eventStream == null ) { // a bad or heavy loaded client may send this request after session expiration or attempt to reuse old session ID\r sendBadRequest ( context ) ; return ; } // 1. headers and content type should be initialized before response commit\r // 2. it seems that ServletResponse#getWriter() updates character set\r // excerpt from apidoc:\r // If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method\r // just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1.\r // so need to be sure headers are updated before writer opened\r httpResponse . setContentType ( \"text/event-stream;charset=UTF-8\" ) ; // no need to explicitly set character encoding since is already set by content type\r // httpResponse.setCharacterEncoding(\"UTF-8\");\r httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setHeader ( HttpHeader . CONNECTION , HttpHeader . KEEP_ALIVE ) ; eventStream . setRemoteHost ( context . getRemoteHost ( ) ) ; eventStream . setWriter ( httpResponse . getWriter ( ) ) ; try { eventStream . onOpen ( ) ; log . debug ( \"Event stream |%s| opened.\" , eventStream ) ; while ( eventStream . loop ( ) ) { } } finally { eventStream . onClose ( ) ; eventStreamManager . destroyEventStream ( eventStream ) ; log . debug ( \"Event stream |%s| closed.\" , sessionID ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract event stream session ID from request path . This method extracts last path component from request path with extension removed if present . It is a sort of <code > basename< / code > from file path . All next request paths with return the same session ID <code > 1234< / code > : <ul > <li > / 1234 . event <li > / event / 1234 <li > / 1234 <li > / admin / 1234 . event <li > / admin / event / 1234 < / ul > This allows for flexible event stream servlet mapping on deployment descriptor . Both mapping by path and extension can be used . Also extension can be anything . Anyway this flexibility comes with a constraint : session ID cannot contain slash ( / ) or dot ( . ) . <p > Session ID is generated by event stream manager when client subscribes see { @link EventStreamManager#subscribe ( EventStreamConfig ) } then client sends session ID back to this servlet as a HTTP request . [CODESPLIT] private static String getEventStreamSessionID ( String requestPath ) { int extensionSeparator = requestPath . lastIndexOf ( ' ' ) ; if ( extensionSeparator == - 1 ) { extensionSeparator = requestPath . length ( ) ; } // request URI is guaranteed to start with path separator\r // anyway, if missing below pathSeparator will be -1 + 1 = 0, pointing to entire request URI\r int pathSeparator = requestPath . lastIndexOf ( ' ' , extensionSeparator ) + 1 ; return requestPath . substring ( pathSeparator , extensionSeparator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Saves the input and closes the { [CODESPLIT] public void save ( ) { try { onSave ( ) ; close ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | Validator . InvalidValueException ex ) { onError ( ex ) ; } catch ( IllegalStateException ex ) { // This usually inidicates a \"lost update\" ConfirmDialog . show ( getUI ( ) , ex . getLocalizedMessage ( ) + \"\\nDo you want to refresh this page loosing any changes you have made?\" , ( ConfirmDialog cd ) -> { if ( cd . isConfirmed ( ) ) { refresh ( ) ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the database driver . { @code driverName } must be a fully qualified class name and the class must be in java s class path . Unless the driver is already registered { @code setProvider } registers it at the { @code java . sql . DriverManager } . [CODESPLIT] public static void setProvider ( final String driverName ) throws Exception { Driver driver = ( Driver ) Class . forName ( driverName ) . newInstance ( ) ; Enumeration < Driver > drivers = DriverManager . getDrivers ( ) ; while ( drivers . hasMoreElements ( ) ) { if ( drivers . nextElement ( ) . getClass ( ) . equals ( driver . getClass ( ) ) ) { return ; } } DriverManager . registerDriver ( driver ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the parser configuration . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected final CONFIG_TYPE getConcreteConfig ( final ParserConfig config ) { final Config < ParserConfig > cfg = config . getConfig ( ) ; if ( cfg == null ) { throw new IllegalStateException ( \"The configuration is expected to be of type '\" + concreteConfigClass . getName ( ) + \"', but was: null\" ) ; } else { if ( ! ( concreteConfigClass . isAssignableFrom ( cfg . getConfig ( ) . getClass ( ) ) ) ) { throw new IllegalStateException ( \"The configuration is expected to be of type '\" + concreteConfigClass . getName ( ) + \"', but was: \" + cfg . getConfig ( ) . getClass ( ) . getName ( ) + \" - Did you add the configuration class to the JXB context?\" ) ; } } return ( CONFIG_TYPE ) cfg . getConfig ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load locale codes and security domains lists from filter parameters . Filter parameter is a list of command separated items . If related filter parameter is not declared field is initialized to empty list . <p > This filter loads tiny container reference from servlet context attribute { @link TinyContainer#ATTR_INSTANCE } . If there is no servlet context attribute with the that name this initialization fails with filter permanently unavailable . [CODESPLIT] @ Override public void init ( FilterConfig config ) throws UnavailableException { log . trace ( \"init(FilterConfig)\" ) ; // is safe to store container reference on filter instance since container has application life span\r container = ( ContainerSPI ) config . getServletContext ( ) . getAttribute ( TinyContainer . ATTR_INSTANCE ) ; if ( container == null ) { log . fatal ( \"Tiny container instance not properly created, probably misconfigured. Request preprocessor permanently unvailable.\" ) ; throw new UnavailableException ( \"Tiny container instance not properly created, probably misconfigured.\" ) ; } String localeParameter = config . getInitParameter ( PARAM_LOCALE ) ; if ( localeParameter != null ) { locales = Strings . split ( localeParameter , ' ' ) ; for ( String locale : locales ) { log . debug ( \"Register locale |%s| for request pre-processing.\" , locale ) ; } } String securityDomainParameter = config . getInitParameter ( PARAM_SECURITY_DOMAIN ) ; if ( securityDomainParameter != null ) { securityDomains = Strings . split ( securityDomainParameter , ' ' ) ; for ( String securityDomain : securityDomains ) { log . debug ( \"Register security domain |%s| for request pre-processing.\" , securityDomain ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search request URI for locale and security domain by comparing with internal lists and remove found values . Update locale security domain and request path on context request from current thread see { @link RequestContext#setLocale ( Locale ) } { @link RequestContext#setSecurityDomain ( String ) } and { @link RequestContext#setRequestPath ( String ) } . <p > Remove locale and security context from current request URI and forward it . If current request URI is for a static resource that is an existing file this filter does nothing . <p > It is considered a resource not found and rejected with 404 if a request URI contains a locale code that is not listed into filter parameter . If <code > locale< / code > filter parameter is not declared all locale code that may be present into request URI are passed unprocessed . If request URI contains a security domain that is not listed into <code > security - domain< / code > filter parameter it is forwarded unprocessed . [CODESPLIT] @ Override public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { HttpServletRequest httpRequest = ( HttpServletRequest ) request ; String requestURI = httpRequest . getRequestURI ( ) ; String contextPath = httpRequest . getContextPath ( ) ; String requestPath = requestURI . substring ( contextPath . length ( ) ) ; // request-uri = context-path request-path\r // context-path = \"/\" path-component\r // request-path = 1*(\"/\" path-component)\r File file = new File ( request . getServletContext ( ) . getRealPath ( requestPath ) ) ; if ( file . exists ( ) ) { chain . doFilter ( request , response ) ; return ; } // request-path = [\"/\" locale] [\"/\" security-domain] 1*(\"/\" path-component)\r RequestContext context = container . getInstance ( RequestContext . class ) ; String queryString = httpRequest . getQueryString ( ) ; context . setRequestURL ( queryString != null ? Strings . concat ( requestURI , ' ' , queryString ) : requestURI ) ; if ( ! locales . isEmpty ( ) ) { for ( String locale : locales ) { if ( startsWith ( requestPath , locale ) ) { requestPath = requestPath . substring ( locale . length ( ) + 1 ) ; context . setLocale ( new Locale ( locale ) ) ; break ; } } } for ( String securityDomain : securityDomains ) { if ( startsWith ( requestPath , securityDomain ) ) { requestPath = requestPath . substring ( securityDomain . length ( ) + 1 ) ; context . setSecurityDomain ( securityDomain ) ; break ; } } context . setRequestPath ( requestPath ) ; request . getRequestDispatcher ( requestPath ) . forward ( request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Test if request path starts with path component . This predicate returns true if first path component from given request path equals requested path component . Comparison is not case sensitive . Request path should start with path separator otherwise this predicate returns false . [CODESPLIT] private static boolean startsWith ( String requestPath , String pathComponent ) { if ( requestPath . charAt ( 0 ) != ' ' ) { return false ; } int i = 1 ; for ( int j = 0 ; i < requestPath . length ( ) ; ++ i , ++ j ) { if ( requestPath . charAt ( i ) == ' ' ) { return j == pathComponent . length ( ) ; } if ( j == pathComponent . length ( ) ) { return false ; } if ( Character . toLowerCase ( requestPath . charAt ( i ) ) != Character . toLowerCase ( pathComponent . charAt ( j ) ) ) { return false ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of factories for the given model type . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) @ NotNull public final < MODEL > List < ArtifactFactory < MODEL > > getFactories ( final Class < MODEL > modelType ) { final List < ArtifactFactory < MODEL > > list = new ArrayList < ArtifactFactory < MODEL > > ( ) ; if ( factories == null ) { factories = new ArrayList < ArtifactFactory < ? > > ( ) ; if ( factoryConfigs != null ) { for ( final ArtifactFactoryConfig factoryConfig : factoryConfigs ) { factories . add ( factoryConfig . getFactory ( ) ) ; } } } for ( final ArtifactFactory < ? > factory : factories ) { if ( modelType . isAssignableFrom ( factory . getModelType ( ) ) ) { list . add ( ( ArtifactFactory < MODEL > ) factory ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses { @code string } and returns a valid Date object . For parsing a { @link SimpleDateFormat } object is used . [CODESPLIT] public Date getDate ( final String string ) throws ParseException { return getDateFormat ( format , locale ) . parse ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses { @code string } and returns a valid Date object . For parsing a { @link SimpleDateFormat } object is used . [CODESPLIT] public Date getDate ( final String string , final String formatString , final String localeName ) throws ParseException { return getDateFormat ( formatString , parseLocale ( localeName ) ) . parse ( string ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the control in a { @link Window } . [CODESPLIT] protected Window asWindow ( ) { if ( containingWindow == null ) { containingWindow = new Window ( getCaption ( ) , this ) ; containingWindow . setWidth ( 80 , Unit . PERCENTAGE ) ; containingWindow . setHeight ( 80 , Unit . PERCENTAGE ) ; containingWindow . center ( ) ; } return containingWindow ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve instance from current HTTP session bound to given instance key or null if none found . Uses provided instance key argument as HTTP session attribute name . Managed instance key argument should be not null . <p > Access to HTTP session is obtained from HTTP request ; therefore it is considered a bug if attempt to use this method outside a HTTP request thread . <p > Implementation note : this method could have side effect . It <b > creates the HTTP session< / b > if there is none on current HTTP request . [CODESPLIT] @ Override public Object getInstance ( InstanceKey instanceKey ) { // at this point managed instance key is guaranteed to be non null\r // SESSION instances are stored on current HTTP session as named attribute value, using provided instance key\r // HTTP session is created on the fly if necessary\r // if HTTP session exists and possesses an attribute with instance key, simply returns stored instance\r // when HTTP session expires attribute values are removed and SESSION instances are garbage collected\r HttpSession httpSession = getSession ( instanceKey ) ; return httpSession . getAttribute ( instanceKey . getValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Persist instance on current HTTP session bound to given managed instance key . This method simply uses <code > instanceKey< / code > to add instance as HTTP session attribute . Both arguments should to be not null . <p > Access to HTTP session is obtained from HTTP request ; therefore it is considered a bug if attempt to use this method outside a HTTP request thread . <p > Implementation note : this method could have side effect . It <b > creates the HTTP session< / b > if there is none on current HTTP request . [CODESPLIT] @ Override public void persistInstance ( InstanceKey instanceKey , Object instance ) { // at this point key and instance arguments are guaranteed to be non null\r HttpSession httpSession = getSession ( instanceKey ) ; httpSession . setAttribute ( instanceKey . getValue ( ) , instance ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get HTTP session from current request creating it if necessary . This method should be call inside a request context otherwise bug error is thrown . [CODESPLIT] private HttpSession getSession ( InstanceKey instanceKey ) { RequestContext requestContext = appFactory . getInstance ( RequestContext . class ) ; HttpServletRequest httpRequest = requestContext . getRequest ( ) ; if ( httpRequest == null ) { throw new BugError ( \"Invalid web context due to null HTTP request. Cannot create managed instance for |%s| with scope SESSION.\" , instanceKey ) ; } // create HTTP session if missing; accordingly API httpSession is never null if 'create' flag is true\r return httpRequest . getSession ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize this file resource to HTTP response . Disable cache and set content type and content length . [CODESPLIT] @ Override public void serialize ( HttpServletResponse httpResponse ) throws IOException { httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setContentType ( contentType ) ; httpResponse . setHeader ( HttpHeader . CONTENT_LENGTH , Long . toString ( file . length ( ) ) ) ; Files . copy ( file , httpResponse . getOutputStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replacement of { @code doRows ( Parse ) } which resolves question marks in the first row and calls fit . ColumnFixture . doRows ( Parse ) . <p > Question marks represent method calls so getValue () and getValue? are equivalent . [CODESPLIT] @ Override protected void doRows ( final List < FitRow > rows ) throws Exception { FitRow headerRow = rows . get ( 0 ) ; columnParameters = extractColumnParameters ( headerRow ) ; bind ( headerRow ) ; super . doRows ( rows . subList ( 1 , rows . size ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replacement of { @code doCell } which resolves cross - references before calling the original { @code doCell } method of fit . [CODESPLIT] @ Override protected void doCell ( final FitCell cell , final int column ) { ValueReceiver receiver = columnBindings [ column ] ; String currentCellParameter = saveGet ( column , columnParameters ) ; if ( receiver != null && ! cell . getFitValue ( ) . trim ( ) . isEmpty ( ) && receiver . canSet ( ) ) { setValue ( cell , receiver , currentCellParameter ) ; } else { check ( cell , receiver , currentCellParameter ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility ////////////////////////////////// [CODESPLIT] protected void bind ( FitRow heads ) { columnBindings = new ValueReceiver [ heads . size ( ) ] ; for ( int i = 0 ; i < columnBindings . length ; i ++ ) { FitCell cell = heads . cells ( ) . get ( i ) ; String name = cell . getFitValue ( ) ; try { columnBindings [ i ] = createReceiver ( this , name ) ; } catch ( Exception e ) { cell . exception ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches meta data such as links from the server . [CODESPLIT] public void readMeta ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { executeAndHandle ( Request . Get ( uri ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements Serializable [CODESPLIT] private void writeObject ( ObjectOutputStream out ) throws IOException { out . writeInt ( this . blockSize ) ; out . writeLong ( this . count ) ; out . writeInt ( this . lastLen ) ; out . writeInt ( getNodeCount ( ) ) ; Node n = this . nodeList . first ; while ( n != null ) { out . writeObject ( n . buf ) ; n = n . next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Beside initialization performed by { @link AppServlet#init ( ServletConfig ) } this method takes care to load resource methods cache . A resource method is a remotely accessible method that returns a { @link Resource } . Map storage key is generated by { @link #key ( ManagedMethodSPI ) } based on controller and resource method request paths and is paired with retrieval key - { @link #key ( String ) } generated from request path when method invocation occurs . [CODESPLIT] @ Override public void init ( ServletConfig config ) throws UnavailableException { super . init ( config ) ; for ( ManagedMethodSPI method : container . getManagedMethods ( ) ) { if ( Types . isKindOf ( method . getReturnType ( ) , Resource . class ) ) { resourceMethods . put ( key ( method ) , method ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle request for a resource . Locate resource method based on request path from request context execute method and serialize back to client returned resource . See class description for general behavior . [CODESPLIT] @ Override protected void handleRequest ( RequestContext context ) throws ServletException , IOException { // for exceptions generated before response commit uses HttpServletResponse.sendError\r // on send error, servlet container prepares error response using container internal HTML for response body\r // if <error-page> is configured into deployment descriptor servlet container uses that HTML for response body\r final HttpServletRequest httpRequest = context . getRequest ( ) ; final HttpServletResponse httpResponse = context . getResponse ( ) ; ArgumentsReader argumentsReader = null ; Resource resource = null ; try { ManagedMethodSPI method = resourceMethods . get ( key ( context . getRequestPath ( ) ) ) ; if ( method == null ) { throw new NoSuchMethodException ( httpRequest . getRequestURI ( ) ) ; } final Type [ ] formalParameters = method . getParameterTypes ( ) ; argumentsReader = argumentsReaderFactory . getArgumentsReader ( httpRequest , formalParameters ) ; Object [ ] arguments = argumentsReader . read ( httpRequest , formalParameters ) ; Object controller = container . getInstance ( method . getDeclaringClass ( ) ) ; resource = method . invoke ( controller , arguments ) ; if ( resource == null ) { throw new BugError ( \"Null resource |%s|.\" , httpRequest . getRequestURI ( ) ) ; } } catch ( AuthorizationException e ) { // at this point, resource is private and need to redirect to a login page\r // if application provides one, tiny container is configured with, and use it\r // otherwise servlet container should have one\r // if no login page found send back servlet container error - that could be custom error page, if declared\r String loginPage = container . getLoginPage ( ) ; if ( loginPage != null ) { httpResponse . sendRedirect ( loginPage ) ; } else { // expected servlet container behavior:\r // if <login-config> section exist into web.xml do what is configured there\r // else send back internal page with message about SC_UNAUTHORIZED\r // authenticate can throw ServletException if fails, perhaps because is not configured\r // let servlet container handle this error, that could be custom error page is configured\r httpRequest . authenticate ( httpResponse ) ; } return ; } catch ( NoSuchMethodException | IllegalArgumentException e ) { // do not use AppServlet#sendError since it is encoded JSON and for resources need HTML\r dumpError ( context , e ) ; httpResponse . sendError ( HttpServletResponse . SC_NOT_FOUND , httpRequest . getRequestURI ( ) ) ; return ; } catch ( InvocationException e ) { // do not use AppServlet#sendError since it is encoded JSON and for resources need HTML\r dumpError ( context , e ) ; if ( e . getCause ( ) instanceof NoSuchResourceException ) { httpResponse . sendError ( HttpServletResponse . SC_NOT_FOUND , httpRequest . getRequestURI ( ) ) ; } else { httpResponse . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , e . getCause ( ) . getMessage ( ) ) ; } return ; } finally { if ( argumentsReader != null ) { argumentsReader . clean ( ) ; } } // once serialization process started response becomes committed\r // and is not longer possible to use HttpServletResponse#sendError\r // let servlet container handle IO exceptions but since client already start rendering\r // there is no so much to do beside closing or reseting connection\r httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; resource . serialize ( httpResponse ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate storage key for resource methods cache . This key is create from controller and resource method request paths and is used on cache initialization . It is paired with { @link #key ( String ) } created from request path on actual method invocation . <p > Here is storage key syntax that should be identical with retrieval key . Key has optional controller path - missing if use default controller and resource method path . Controller path is the declaring class request path { @link ManagedClassSPI#getRequestPath () } and resource path is managed method request path { @link ManagedMethodSPI#getRequestPath () } . [CODESPLIT] private static String key ( ManagedMethodSPI resourceMethod ) { StringBuilder key = new StringBuilder ( ) ; if ( resourceMethod . getDeclaringClass ( ) . getRequestPath ( ) != null ) { key . append ( ' ' ) ; key . append ( resourceMethod . getDeclaringClass ( ) . getRequestPath ( ) ) ; } key . append ( ' ' ) ; key . append ( resourceMethod . getRequestPath ( ) ) ; return key . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP GET request on the { @link Endpoint#getUri () } and caches the response if the server sends an ETag header . [CODESPLIT] protected HttpEntity getContent ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { Request request = Request . Get ( uri ) ; if ( last != null ) { request = request . addHeader ( IF_NONE_MATCH , last . etag ) ; } HttpResponse response = execute ( request ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == SC_NOT_MODIFIED && last != null ) { return last . content ; } handleResponse ( response , request ) ; Header etagHeader = response . getFirstHeader ( HttpHeaders . ETAG ) ; last = ( etagHeader == null ) ? null : new Memory ( etagHeader . getValue ( ) , response . getEntity ( ) ) ; return response . getEntity ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP PUT request on the { @link Endpoint#getUri () } . Sets { @link HttpHeaders#IF_MATCH } if there is a cached ETag to detect lost updates . [CODESPLIT] protected HttpResponse putContent ( HttpEntity content ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { Request request = Request . Put ( uri ) . body ( content ) ; if ( last != null ) { request . addHeader ( HttpHeaders . IF_MATCH , last . etag ) ; } return executeAndHandle ( request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an HTTP DELETE request on the { @link Endpoint#getUri () } . Sets { @link HttpHeaders#IF_MATCH } if there is a cached ETag to detect lost updates . [CODESPLIT] protected HttpResponse deleteContent ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { Request request = Request . Delete ( uri ) ; if ( last != null ) { request . addHeader ( HttpHeaders . IF_MATCH , last . etag ) ; } return executeAndHandle ( request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare two <code > FileInformation< / code > objects . See { @link FitFilenameComparator } for more information . [CODESPLIT] @ Override public final int compare ( final T lhs , final T rhs ) { int c = compareDirectoryNames ( lhs , rhs ) ; if ( c == EQUAL ) { if ( isSetupFile ( lhs ) || isTearDownFile ( rhs ) ) { return LEFT_IS_SMALLER ; } else if ( isSetupFile ( rhs ) || isTearDownFile ( lhs ) ) { return RIGHT_IS_SMALLER ; } else { return compareFullnames ( lhs , rhs ) ; } } else if ( c <= LEFT_IS_SMALLER ) { return subCompare ( lhs , rhs ) ; } else { return - subCompare ( rhs , lhs ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the SQL statement . [CODESPLIT] @ Override public void tearDown ( ) throws Exception { if ( statement != null ) { statement . close ( ) ; statement = null ; } super . tearDown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a { @code java . sql . ResultSet } by using the saved connection . This method queries the table { @code tableName } and appends { @code where } as an optional where clause . [CODESPLIT] protected ResultSet getResultSet ( ) { if ( table == null ) { throw new IllegalArgumentException ( \"missing parameter: table\" ) ; } String whereClause = \"\" ; if ( where != null ) { whereClause = \" WHERE \" + where ; } try { statement = connection . createStatement ( ) ; return statement . executeQuery ( \"SELECT * FROM \" + table + whereClause ) ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute post - construct on managed instance . In order to perform instance post - construction managed instance should implement { @link ManagedPostConstruct } interface . [CODESPLIT] @ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { if ( ! ( instance instanceof ManagedPostConstruct ) ) { return ; } ManagedPostConstruct managedInstance = ( ManagedPostConstruct ) instance ; log . debug ( \"Post-construct managed instance |%s|\" , managedInstance . getClass ( ) ) ; try { managedInstance . postConstruct ( ) ; } catch ( Throwable t ) { throw new BugError ( \"Managed instance |%s| post-construct fail: %s\" , instance , t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes all event streams still opened when event stream manager is destroyed . [CODESPLIT] @ Override public void preDestroy ( ) { if ( eventStreams . isEmpty ( ) ) { return ; } // EventStream#close signals stream loop that breaks\r // as a consequence, EventStreamServlet ends current request processing and call this#closeEventStream\r // this#closeEventStream removes event stream from this#eventStreams list resulting in concurrent change\r // to cope with this concurrent change uses a temporary array\r // toArray API is a little confusing for me regarding returned array\r // to be on safe side let toArray to determine array size\r // also I presume returned array is not altered by list updates\r for ( EventStream eventStream : eventStreams . toArray ( new EventStream [ 0 ] ) ) { log . debug ( \"Force close stale event stream |%s|.\" , eventStream ) ; eventStream . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes to events stream and returns session ID . This method is remote accessible and public . It returns a session ID with a short life time for about 10 seconds . <p > This method creates a new { @link SessionID } and stores given configuration object to { @link #sessions } map with created session ID as key . Session storage is ephemere . It lasts only for { @link #SUBSCRIBE_TTL } period of time ; after that session ID becomes stale . <p > This method should be followed by { @link #createEventStream ( String ) } with returned session ID as argument . [CODESPLIT] @ Remote @ Public public String subscribe ( EventStreamConfig config ) { SessionID sessionID = new SessionID ( ) ; log . debug ( \"Store event stream parameters for session |%s|.\" , sessionID ) ; sessions . put ( sessionID , config ) ; return sessionID . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enables or disabled buttons based on the Allow HTTP header . [CODESPLIT] protected void handleAllowedMethods ( ) { endpoint . isDownloadAllowed ( ) . ifPresent ( this :: setDownloadEnabled ) ; endpoint . isUploadAllowed ( ) . ifPresent ( this :: setUploadEnabled ) ; endpoint . isDeleteAllowed ( ) . ifPresent ( this :: setDeleteEnabled ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called to upload new blob data to the server . [CODESPLIT] protected void upload ( ) { try { onUpload ( ) ; eventBus . post ( new BlobUploadEvent ( endpoint ) ) ; Notification . show ( \"Success\" , \"Upload complete\" , Notification . Type . TRAY_NOTIFICATION ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex ) { onError ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deletes the blob . [CODESPLIT] protected void delete ( ) { String question = \"Are you sure you want to delete the data from the server?\" ; ConfirmDialog . show ( getUI ( ) , question , new ConfirmDialog . Listener ( ) { @ Override public void onClose ( ConfirmDialog cd ) { if ( cd . isConfirmed ( ) ) { try { endpoint . delete ( ) ; close ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex ) { onError ( ex ) ; } catch ( RuntimeException ex ) { // Must explicitly send unhandled exceptions to error handler. // Would otherwise get swallowed silently within callback handler. getUI ( ) . getErrorHandler ( ) . error ( new com . vaadin . server . ErrorEvent ( ex ) ) ; } } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a string and converts it into a { @code java . sql . Timestamp } object . [CODESPLIT] @ Override public final Timestamp unsafeParse ( final String s ) throws ParseException { try { return Timestamp . valueOf ( s ) ; } catch ( final IllegalArgumentException e ) { return new Timestamp ( dateFitDateHelper . parse ( s , parameter ) . getTime ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds an argument in an given argument list . <p > The search for an argument is case - insensitive and whitespaces at the beginning and the end are ignored . The argument s name and its value are separated by an equal sign . All these inputs will result in &quot ; world&quot ; if you look up &quot ; hello&quot ; : <p > &quot ; hello = world&quot ; &quot ; hello = world &quot ; &quot ; HeLLo = world&quot ; . < / p > <p > Note : the case of the value is unchanged . [CODESPLIT] public String getArg ( final String argName , final String defaultValue ) { if ( args == null || ! args . containsKey ( argName ) ) { return defaultValue ; } else { return validator . preProcess ( args . get ( argName ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the fixture arguments call { @code setUp } { @code fit . Fixture . doTable ( Parse ) } and { @code tearDown () } . [CODESPLIT] public void doTable ( FitTable table ) { copyParamsToFixture ( ) ; try { setUp ( ) ; try { doRows ( table . rows ( ) ) ; } catch ( Exception e ) { table . exception ( e ) ; } tearDown ( ) ; } catch ( final Exception e ) { table . exception ( e ) ; } table . finishExecution ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "extracts and removes parameters from a row . [CODESPLIT] protected String [ ] extractColumnParameters ( FitRow row ) { final List < String > result = new ArrayList <> ( ) ; for ( FitCell cell : row . cells ( ) ) { result . add ( FitUtils . extractCellParameter ( cell ) ) ; } return result . toArray ( new String [ result . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the argument list and copies all values in public members with the same name . <p > If these members do not exist the argument is skipped . You can still read the values using { @link #getArg ( String String ) } . [CODESPLIT] public void copyParamsToFixture ( ) { for ( final String fieldName : getArgNames ( ) ) { ValueReceiver valueReceiver ; try { valueReceiver = valueReceiverFactory . createReceiver ( this , fieldName ) ; } catch ( NoSuchMethodException | NoSuchFieldException e ) { continue ; } TypeHandler handler = createTypeHandler ( valueReceiver , null ) ; String fieldValueString = getArg ( fieldName , null ) ; try { Object fieldValue = handler . parse ( fieldValueString ) ; valueReceiver . set ( this , fieldValue ) ; } catch ( Exception ignored ) { } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all argument names . [CODESPLIT] protected String [ ] getArgNames ( ) { if ( args == null ) { return new String [ ] { } ; } return args . keySet ( ) . toArray ( new String [ args . keySet ( ) . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replacement of { @code check } which resolves cross - references before calling the original check method of fit . [CODESPLIT] public void check ( final FitCell cell , ValueReceiver valueReceiver , String currentCellParameter ) { validator . process ( cell , valueReceiver , currentCellParameter , typeHandlerFactory ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Schedule periodic task execution . [CODESPLIT] public synchronized void period ( final PeriodicTask periodicTask , long period ) { TimerTask task = new PeriodicTaskImpl ( periodicTask ) ; this . tasks . put ( periodicTask , task ) ; this . timer . schedule ( task , 0L , period ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Schedule timeout task reseting timeout period if given timeout task is already pending . [CODESPLIT] public synchronized void timeout ( final TimeoutTask timeoutTask , long timeout ) { TimerTask task = this . tasks . get ( timeoutTask ) ; if ( task != null ) { task . cancel ( ) ; this . tasks . values ( ) . remove ( task ) ; } task = new TimeoutTaskImpl ( timeoutTask ) ; this . tasks . put ( timeoutTask , task ) ; this . timer . schedule ( task , timeout ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Purge task helper method . If given <code > task< / code > is not scheduled this method does nothing . [CODESPLIT] private void purgeTask ( Object task ) { TimerTask timerTask = this . tasks . get ( task ) ; if ( timerTask != null ) { timerTask . cancel ( ) ; this . tasks . values ( ) . remove ( timerTask ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create views meta pool from given managed view configuration object . Configuration object is described on class description . [CODESPLIT] @ Override public void config ( Config config ) throws ConfigException , IOException { for ( Config repositorySection : config . findChildren ( \"repository\" ) ) { // view manager configuration section is named <views>\r // a <views> configuration section has one or many <repository> child sections\r // scan every repository files accordingly files pattern and add meta views to views meta pool\r // load repository view implementation class and perform insanity checks\r String className = repositorySection . getAttribute ( \"class\" , DEF_IMPLEMENTATION ) ; Class < ? > implementation = Classes . forOptionalName ( className ) ; if ( implementation == null ) { throw new ConfigException ( \"Unable to load view implementation |%s|.\" , className ) ; } if ( ! Types . isKindOf ( implementation , View . class ) ) { throw new ConfigException ( \"View implementation |%s| is not of proper type.\" , className ) ; } if ( ! Classes . isInstantiable ( implementation ) ) { throw new ConfigException ( \"View implementation |%s| is not instantiable. Ensure is not abstract or interface and have default constructor.\" , implementation ) ; } @ SuppressWarnings ( \"unchecked\" ) Class < ? extends View > viewImplementation = ( Class < ? extends View > ) implementation ; // load repository path and files pattern and create I18N repository instance\r String repositoryPath = repositorySection . getAttribute ( \"path\" ) ; if ( repositoryPath == null ) { throw new ConfigException ( \"Invalid views repository configuration. Missing <path> attribute.\" ) ; } String filesPattern = repositorySection . getAttribute ( \"files-pattern\" ) ; if ( filesPattern == null ) { throw new ConfigException ( \"Invalid views repository configuration. Missing <files-pattern> attribute.\" ) ; } ConfigBuilder builder = new I18nRepository . ConfigBuilder ( repositoryPath , filesPattern ) ; I18nRepository repository = new I18nRepository ( builder . build ( ) ) ; if ( viewsMetaPool == null ) { // uses first repository to initialize i18n pool\r // limitation for this solution is that all repositories should be the kind: locale sensitive or not\r viewsMetaPool = repository . getPoolInstance ( ) ; } Properties properties = repositorySection . getProperties ( ) ; // traverses all files from I18N repository instance and register view meta instance\r // builder is used by view meta to load the document template\r for ( I18nFile template : repository ) { ViewMeta meta = new ViewMeta ( template . getFile ( ) , viewImplementation , properties ) ; if ( viewsMetaPool . put ( meta . getName ( ) , meta , template . getLocale ( ) ) ) { log . warn ( \"Override view |%s|\" , meta ) ; } else { log . debug ( \"Register view |%s|\" , meta ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create view instance based on view meta data identified by name and request locale . View instance is created from view implementation class - { @link ViewMeta#getImplementation () } . [CODESPLIT] @ Override public View getView ( String viewName ) { RequestContext context = Factory . getInstance ( RequestContext . class ) ; ViewMeta meta = viewsMetaPool . get ( viewName , context . getLocale ( ) ) ; if ( meta == null ) { throw new BugError ( \"View |%s| not found. View name may be misspelled, forgot to add template file or template name doesn't match views files pattern.\" , viewName ) ; } AbstractView view = ( AbstractView ) Classes . newInstance ( meta . getImplementation ( ) ) ; view . setMeta ( meta ) ; return view ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the iteration has more elements . ( In other words returns <code > true< / code > if <code > next< / code > would return an element rather than throwing an exception . ) [CODESPLIT] @ Override public final boolean hasNext ( ) { if ( files == null ) { return false ; } else if ( fileIndex < files . length ) { return true ; } else { return cacheNext ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next matching file . [CODESPLIT] @ Override public final File next ( ) { if ( files == null || fileIndex >= files . length ) { if ( ! cacheNext ( ) ) { throw new NoSuchElementException ( ) ; } } return files [ fileIndex ++ ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the given parameters and initializes the values of { @link #getEncoding () } and { @link #getFile () } . [CODESPLIT] @ Override public void setUp ( ) throws Exception { super . setUp ( ) ; FileFixtureHelper helper = DependencyManager . getOrCreate ( FileFixtureHelper . class ) ; if ( encoding == null ) { encoding = helper . getEncoding ( ) ; } String fileName = getArg ( \"file\" ) ; if ( fileName == null ) { File provider = helper . getDirectory ( ) ; String dir = getArg ( \"dir\" ) ; if ( dir != null ) { provider = new File ( dir ) ; } if ( provider == null ) { throw new RuntimeException ( \"No directory selected\" ) ; } String pattern = helper . getPattern ( ) ; pattern = getArg ( \"pattern\" , pattern ) ; FileSelector fs = new FileSelector ( provider , pattern ) ; file = wrapper . wrap ( fs . getFirstFile ( ) ) ; } else { file = wrapper . wrap ( new File ( fileName ) . getAbsoluteFile ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the first table row and generates an { @code int } array which contains the length of each record field . [CODESPLIT] public final int [ ] extractWidth ( FitRow row ) { int [ ] width = new int [ row . size ( ) ] ; int i = 0 ; for ( FitCell cell : row . cells ( ) ) { try { String value = validator . preProcess ( cell . getFitValue ( ) ) ; TypeHandler handler = typeHandlerFactory . getHandler ( Integer . class , null ) ; width [ i ++ ] = ( Integer ) handler . parse ( value ) ; } catch ( Exception e ) { cell . exception ( e ) ; return null ; } } return width ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the database username to { @code userName } . The username can be received using { @link SetupHelper#getUser () } . [CODESPLIT] public void user ( final String userName ) { SetupHelper helper = DependencyManager . getOrCreate ( SetupHelper . class ) ; helper . setUser ( userName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the database password to { @code password } . The password can be received using { @link SetupHelper#getPassword () } . [CODESPLIT] public void password ( final String password ) { SetupHelper helper = DependencyManager . getOrCreate ( SetupHelper . class ) ; helper . setPassword ( password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the database connection string to { @code uri } . The connection string can be received using { @link SetupHelper#getConnectionString () } . [CODESPLIT] public void connectionString ( final String uri ) { SetupHelper helper = DependencyManager . getOrCreate ( SetupHelper . class ) ; helper . setConnectionString ( uri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configure Simple CAPTCHA service provider . See class description for configuration object properties . <p > Note that images repository should contain only images related to CAPTCHA ; sub - directories are not scanned only direct child files . [CODESPLIT] @ Override public void config ( Config config ) throws ConfigException { imagesRepositoryDir = config . getProperty ( \"captcha.repository.path\" , File . class ) ; if ( imagesRepositoryDir == null ) { throw new ConfigException ( \"Missing <captcha.repository.path> property from CAPTCHA configuration.\" ) ; } challengeSetSize = config . getProperty ( \"captcha.set.size\" , int . class , 6 ) ; if ( ! imagesRepositoryDir . exists ( ) ) { throw new ConfigException ( \"CAPTCHA images repository |%s| does not exist.\" , imagesRepositoryDir ) ; } if ( ! imagesRepositoryDir . isDirectory ( ) ) { throw new ConfigException ( \"CAPTCHA images repository |%s| is not a directory.\" , imagesRepositoryDir ) ; } if ( ! imagesRepositoryDir . isAbsolute ( ) ) { throw new ConfigException ( \"CAPTCHA images repository |%s| is not absolute path.\" , imagesRepositoryDir ) ; } int imagesCount = imagesRepositoryDir . list ( ) . length ; if ( imagesCount == 0 ) { throw new ConfigException ( \"CAPTCHA images repository |%s| is empty.\" , imagesRepositoryDir ) ; } if ( imagesCount <= challengeSetSize ) { throw new ConfigException ( \"Challenge set size is larger that avaliable images count from CAPTCHA repository.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new challenge and store it on HTTP session . If HTTP session does not exist create it . This challenge is used by client to update user interface accordingly . It is called on initial form rendering and every time user choose to load another challenge if current one cannot be solved . <p > Client is free to display multiple Simple CAPTCHA instances but all instances should have distinct index generated in sequence starting from zero . [CODESPLIT] @ Remote public Challenge getChallenge ( int captchaIndex ) { if ( imagesRepositoryDir == null ) { log . debug ( \"Simple CAPTCHA not properly initialized. Missing <captcha> section from application descriptor:\\r\\n\" + //\r \"\\t<captcha>\\r\\n\" + //\r \"\\t\\t<property name=\\\"captcha.repository.path\\\" value=\\\"/path/to/captcha/images\\\" />\\r\\n\" + //\r \"\\t\\t<property name=\\\"captcha.set.size\\\" value=\\\"5\\\" />\\r\\n\" + //\r \"\\t</captcha>\" ) ; throw new BugError ( \"Missing CAPTCHA images repository. Most probably <captcha> section is missing from application descriptor.\" ) ; } Challenge challenge = new Challenge ( imagesRepositoryDir , challengeSetSize ) ; getChallenges ( ) . put ( captchaIndex , challenge ) ; return challenge ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Verify challenge response . If response is not correct returns a new challenge used by client to update user interface . It is highly recommended to refresh challenge on wrong answer to prevent response guessing . <p > Instance index should be the same provided to { @link #getChallenge ( int ) } . This is critical and client should consider this constrain . Anyway using wrong CAPTCHA instance index is not a security breach ; it always consider response as invalid . [CODESPLIT] @ Remote public Challenge verifyResponse ( int captchaIndex , String challengeResponse ) throws IllegalArgumentException , IllegalStateException { Params . notNullOrEmpty ( challengeResponse , \"Challenge response\" ) ; Challenge challenge = getChallenges ( ) . get ( captchaIndex ) ; if ( challenge == null ) { throw new IllegalStateException ( \"Invalid challenge on session.\" ) ; } return challenge . verifyResponse ( challengeResponse ) ? null : getChallenge ( captchaIndex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the image identified by given token so that client is able to display it . In order to protect against recording attack a challenge image is identified by a token that is valid only once . <p > If given token does not identify a valid challenge image this method throws { @link NoSuchResourceException } and container responds with 404 Not Found . [CODESPLIT] @ Remote @ RequestPath ( \"image\" ) public Resource getImage ( String token ) throws IllegalArgumentException , NoSuchResourceException { Params . notNullOrEmpty ( token , \"Image token\" ) ; for ( Challenge challenge : getChallenges ( ) . values ( ) ) { File image = challenge . getImage ( token ) ; if ( image != null ) { return new FileResource ( image ) ; } } throw new NoSuchResourceException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get challenge instances storage bound to current HTTP request . Challenges storage is kept on HTTP session . It is legal to have multiple Simple CAPTCHA instances on a single page but client should use zero based numeric index to identify instances . <p > This method has side effects : it creates HTTP session if is not already created . [CODESPLIT] private Map < Integer , Challenge > getChallenges ( ) { // here is a circular package dependency that is hard to avoid\r // js.servlet package depends on js.http packages and this js.http.captcha package depends on js.servlet\r // as a consequence js.http.captcha package cannot be used externally without js.servlet\r HttpSession session = context . getInstance ( RequestContext . class ) . getSession ( true ) ; @ SuppressWarnings ( \"unchecked\" ) Map < Integer , Challenge > challenges = ( Map < Integer , Challenge > ) session . getAttribute ( CHALENGES_KEY ) ; if ( challenges == null ) { challenges = new HashMap <> ( ) ; session . setAttribute ( CHALENGES_KEY , challenges ) ; } return challenges ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Configures the application . [CODESPLIT] private static void configureApplication ( ) { // Try to load the file. File file = new File ( \"chameria.props\" ) ; if ( file . exists ( ) ) { Properties props = new Properties ( ) ; InputStream is = null ; try { is = new FileInputStream ( file ) ; props . load ( is ) ; String n = props . getProperty ( \"application.name\" ) ; if ( n != null ) { QApplication . setApplicationName ( n ) ; } else { QApplication . setApplicationName ( \"akquinet ChameRIA\" ) ; } n = props . getProperty ( \"application.version\" ) ; if ( n != null ) { QApplication . setApplicationVersion ( n ) ; } n = props . getProperty ( \"application.icon\" ) ; if ( n != null ) { QIcon icon = new QIcon ( n ) ; QApplication . setWindowIcon ( icon ) ; } } catch ( Exception e ) { System . err . println ( \"Cannot read the application configuration \" + e . getMessage ( ) ) ; e . printStackTrace ( ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( IOException e ) { // Ignored } } } } QApplication . setOrganizationName ( \"akquinet A.G.\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints Welcome Banner . [CODESPLIT] private static void printWelcomeBanner ( ) { StringBuffer banner = new StringBuffer ( ) ; banner . append ( \"\\n\" ) ; banner . append ( \"\\t============================\\n\" ) ; banner . append ( \"\\t|                          |\\n\" ) ; banner . append ( \"\\t|   Welcome to ChameRIA    |\\n\" ) ; banner . append ( \"\\t|                          |\\n\" ) ; banner . append ( \"\\t============================\\n\" ) ; banner . append ( \"\\n\" ) ; System . out . println ( banner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints Stopped Banner . [CODESPLIT] private static void printStoppedBanner ( ) { System . out . println ( \"\\n\" ) ; System . out . println ( \"\\t=========================\" ) ; System . out . println ( \"\\t|   ChameRIA  stopped   |\" ) ; System . out . println ( \"\\t=========================\" ) ; System . out . println ( \"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the Chameleon instance . The instance is not started . [CODESPLIT] public static ChameRIA createChameleon ( String [ ] args ) throws Exception { boolean debug = isDebugModeEnabled ( args ) ; String core = getCore ( args ) ; String app = getApp ( args ) ; String runtime = getRuntime ( args ) ; String fileinstall = getDeployDirectory ( args ) ; String config = getProps ( args ) ; if ( config == null || ! new File ( config ) . exists ( ) ) { return new ChameRIA ( core , debug , app , runtime , fileinstall , null ) ; } else { return new ChameRIA ( core , debug , app , runtime , fileinstall , config ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the -- deploy parameter . [CODESPLIT] private static String getDeployDirectory ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { String arg = args [ i ] ; if ( StringUtils . contains ( arg , \"--deploy=\" ) ) { return arg . substring ( \"--deploy=\" . length ( ) ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a shutdown hook to stop nicely the embedded framework . [CODESPLIT] private static void registerShutdownHook ( final ChameRIA chameleon ) { Runtime runtime = Runtime . getRuntime ( ) ; Runnable hook = new Runnable ( ) { public void run ( ) { try { if ( chameleon != null ) { chameleon . stop ( ) ; printStoppedBanner ( ) ; } } catch ( BundleException e ) { System . err . println ( \"Cannot stop Chameleon correctly : \" + e . getMessage ( ) ) ; } catch ( InterruptedException e ) { System . err . println ( \"Unexpected Exception : \" + e . getMessage ( ) ) ; // nothing to do } } } ; runtime . addShutdownHook ( new Thread ( hook ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the -- debug parameter . [CODESPLIT] private static boolean isDebugModeEnabled ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { String arg = args [ i ] ; if ( arg . equalsIgnoreCase ( \"--debug\" ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traversal //////////////////////////////// [CODESPLIT] @ Override protected void doRow ( FitRow row ) throws Exception { currentCellParameter = FitUtils . extractCellParameter ( row . cells ( ) . get ( 0 ) ) ; this . row = row ; super . doRow ( row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Actions ////////////////////////////////// [CODESPLIT] public void start ( ) throws Exception { actor = Class . forName ( row . cells ( ) . get ( 1 ) . getFitValue ( ) ) . newInstance ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Utility ////////////////////////////////// [CODESPLIT] protected Method method ( int args ) throws NoSuchMethodException { return method ( FitUtils . camel ( row . cells ( ) . get ( 1 ) . getFitValue ( ) ) , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits until a method returns true . The command takes a method name without parameters and a return value of { @code Boolean } as the first parameter and a timeout in ms as the second parameter . <br > The method is called every { @code sleepTime } ms until it returns true or the timeout is exceeded . [CODESPLIT] public void waitFor ( ) throws ParseException , NoSuchMethodException { Method method = method ( 0 ) ; long maxTime = parse ( Long . class , row . cells ( ) . get ( 2 ) . getFitValue ( ) ) ; long sleepTime = getSleepTime ( ) ; waitForResult . wait ( actor , method , maxTime , sleepTime ) ; writeResultIntoCell ( waitForResult ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms the selected row into an &quot ; enter&quot ; command and reinterprets it . <p > Example : Row content : { @code setEncoding | utf - 8 } <br > Code in the fixture : { @code public void setEncoding () throws Exception { transformAndEnter () ; } } <p > { @code public void setEncoding ( String encoding ) { // do stuff with encoding here } } [CODESPLIT] protected final void transformAndEnter ( ) throws Exception { FitCell cell = row . insert ( 0 ) ; cell . setFitValue ( \"enter\" ) ; Object oldActor = actor ; actor = this ; enter ( ) ; actor = oldActor ; row . remove ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Triggers the action . [CODESPLIT] public void trigger ( ) { try { onTrigger ( ) ; Notification . show ( getCaption ( ) , \"Successful.\" , Notification . Type . TRAY_NOTIFICATION ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex ) { onError ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler for triggering the action . [CODESPLIT] protected void onTrigger ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { endpoint . trigger ( ) ; eventBus . post ( new TriggerEvent ( endpoint ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the first matching event which matches { @link #matches ( LoggingEvent ) } and the given parameters . [CODESPLIT] public final LoggingEvent getFirstMatchingEvent ( final LoggingEvent [ ] events , final Map < String , String > parameters ) { for ( LoggingEvent event : events ) { if ( matchesParameters ( event , parameters ) && matches ( event ) ) { return event ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces a row with one or more results . [CODESPLIT] public void insertAndReplace ( final FitRow row ) { if ( results . isEmpty ( ) ) { return ; } int index = row . getIndex ( ) ; FitTable table = row . getTable ( ) ; table . remove ( index ) ; addRows ( table , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the sum of all results . [CODESPLIT] public Counts getCounts ( ) { Counts counts = new Counts ( ) ; for ( FileCount fileCount : results ) { counts . tally ( fileCount . getCounts ( ) ) ; } return counts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the locale value to { @code locale } . [CODESPLIT] public void locale ( final String locale ) { FitDateHelper helper = DependencyManager . getOrCreate ( FitDateHelper . class ) ; helper . setLocale ( locale ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the format value to { @code format } . [CODESPLIT] public void format ( final String format ) { FitDateHelper helper = DependencyManager . getOrCreate ( FitDateHelper . class ) ; helper . setFormat ( format ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for score - sets The score associated with the answer . [CODESPLIT] public void setScore ( double v ) { if ( Summary_Type . featOkTst && ( ( Summary_Type ) jcasType ) . casFeat_score == null ) jcasType . jcas . throwFeatMissing ( \"score\" , \"edu.cmu.lti.oaqa.type.answer.Summary\" ) ; jcasType . ll_cas . ll_setDoubleValue ( addr , ( ( Summary_Type ) jcasType ) . casFeatCode_score , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for variants - gets List of alternative answer summaries . [CODESPLIT] public StringList getVariants ( ) { if ( Summary_Type . featOkTst && ( ( Summary_Type ) jcasType ) . casFeat_variants == null ) jcasType . jcas . throwFeatMissing ( \"variants\" , \"edu.cmu.lti.oaqa.type.answer.Summary\" ) ; return ( StringList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Summary_Type ) jcasType ) . casFeatCode_variants ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for variants - sets List of alternative answer summaries . [CODESPLIT] public void setVariants ( StringList v ) { if ( Summary_Type . featOkTst && ( ( Summary_Type ) jcasType ) . casFeat_variants == null ) jcasType . jcas . throwFeatMissing ( \"variants\" , \"edu.cmu.lti.oaqa.type.answer.Summary\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Summary_Type ) jcasType ) . casFeatCode_variants , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for questionType - gets The class of the question determined by either an automatic question classification process or human judgment . [CODESPLIT] public String getQuestionType ( ) { if ( Question_Type . featOkTst && ( ( Question_Type ) jcasType ) . casFeat_questionType == null ) jcasType . jcas . throwFeatMissing ( \"questionType\" , \"edu.cmu.lti.oaqa.type.input.Question\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Question_Type ) jcasType ) . casFeatCode_questionType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for questionType - sets The class of the question determined by either an automatic question classification process or human judgment . [CODESPLIT] public void setQuestionType ( String v ) { if ( Question_Type . featOkTst && ( ( Question_Type ) jcasType ) . casFeat_questionType == null ) jcasType . jcas . throwFeatMissing ( \"questionType\" , \"edu.cmu.lti.oaqa.type.input.Question\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Question_Type ) jcasType ) . casFeatCode_questionType , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public void registered ( ResteasyProviderFactory factory ) { System . out . println ( \"registered - factory = \" + factory ) ; ResourceConstructor constructor = this . resourceClass . getConstructor ( ) ; if ( constructor == null ) { final Class < ? > clazz = this . resourceClass . getClazz ( ) ; final Class < ? > aClass = DI . getSubTypesWithoutInterfacesAndGeneratedOf ( clazz ) . stream ( ) . findFirst ( ) . get ( ) ; constructor = ResourceBuilder . constructor ( aClass ) ; } // if ( constructor == null ) { throw new RuntimeException ( Messages . MESSAGES . unableToFindPublicConstructorForClass ( this . scannableClass . getName ( ) ) ) ; } else { this . constructorInjector = factory . getInjectorFactory ( ) . createConstructor ( constructor , factory ) ; this . propertyInjector = factory . getInjectorFactory ( ) . createPropertyInjector ( this . resourceClass , factory ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for token - gets The corresponding token for the focus . [CODESPLIT] public Token getToken ( ) { if ( Focus_Type . featOkTst && ( ( Focus_Type ) jcasType ) . casFeat_token == null ) jcasType . jcas . throwFeatMissing ( \"token\" , \"edu.cmu.lti.oaqa.type.nlp.Focus\" ) ; return ( Token ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Focus_Type ) jcasType ) . casFeatCode_token ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for depLabel - gets The dependency label of the token with respect to its head . [CODESPLIT] public String getDepLabel ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_depLabel == null ) jcasType . jcas . throwFeatMissing ( \"depLabel\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_depLabel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for depLabel - sets The dependency label of the token with respect to its head . [CODESPLIT] public void setDepLabel ( String v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_depLabel == null ) jcasType . jcas . throwFeatMissing ( \"depLabel\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_depLabel , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for semanticType - gets A semantic type typically the name of an Entity Annotation type . [CODESPLIT] public String getSemanticType ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_semanticType == null ) jcasType . jcas . throwFeatMissing ( \"semanticType\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_semanticType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for semanticType - sets A semantic type typically the name of an Entity Annotation type . [CODESPLIT] public void setSemanticType ( String v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_semanticType == null ) jcasType . jcas . throwFeatMissing ( \"semanticType\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_semanticType , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for partOfSpeech - gets Coarse - grained part of speech . --- Example : noun verb adj cord [CODESPLIT] public String getPartOfSpeech ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_partOfSpeech == null ) jcasType . jcas . throwFeatMissing ( \"partOfSpeech\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_partOfSpeech ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for partOfSpeech - sets Coarse - grained part of speech . --- Example : noun verb adj cord [CODESPLIT] public void setPartOfSpeech ( String v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_partOfSpeech == null ) jcasType . jcas . throwFeatMissing ( \"partOfSpeech\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_partOfSpeech , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for lemmaForm - gets A canonical / lemmatized form of the covered text . [CODESPLIT] public String getLemmaForm ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_lemmaForm == null ) jcasType . jcas . throwFeatMissing ( \"lemmaForm\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_lemmaForm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for lemmaForm - sets A canonical / lemmatized form of the covered text . [CODESPLIT] public void setLemmaForm ( String v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_lemmaForm == null ) jcasType . jcas . throwFeatMissing ( \"lemmaForm\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_lemmaForm , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for isMainReference - gets If true then this is the main reference to the first argument . Modifiers and anaphoric references do not have isMainReference set . --- Example : A dark blue [ hat ] [CODESPLIT] public boolean getIsMainReference ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_isMainReference == null ) jcasType . jcas . throwFeatMissing ( \"isMainReference\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; return jcasType . ll_cas . ll_getBooleanValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_isMainReference ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for isMainReference - sets If true then this is the main reference to the first argument . Modifiers and anaphoric references do not have isMainReference set . --- Example : A dark blue [ hat ] [CODESPLIT] public void setIsMainReference ( boolean v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_isMainReference == null ) jcasType . jcas . throwFeatMissing ( \"isMainReference\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; jcasType . ll_cas . ll_setBooleanValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_isMainReference , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for isVariable - gets True iff the token expresses some unknown entity typically the focus of a question : --- Example : [ Who ] shot JR? What [ city ] was JR born in? [CODESPLIT] public boolean getIsVariable ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_isVariable == null ) jcasType . jcas . throwFeatMissing ( \"isVariable\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; return jcasType . ll_cas . ll_getBooleanValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_isVariable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for isVariable - sets True iff the token expresses some unknown entity typically the focus of a question : --- Example : [ Who ] shot JR? What [ city ] was JR born in? [CODESPLIT] public void setIsVariable ( boolean v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_isVariable == null ) jcasType . jcas . throwFeatMissing ( \"isVariable\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; jcasType . ll_cas . ll_setBooleanValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_isVariable , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for determiner - gets The determiner attached to the node if any --- Example : [ the ] book [CODESPLIT] public String getDeterminer ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_determiner == null ) jcasType . jcas . throwFeatMissing ( \"determiner\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_determiner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for determiner - sets The determiner attached to the node if any --- Example : [ the ] book [CODESPLIT] public void setDeterminer ( String v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_determiner == null ) jcasType . jcas . throwFeatMissing ( \"determiner\" , \"edu.cmu.lti.oaqa.type.nlp.Token\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_determiner , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for sections - gets Content of sections in the document . [CODESPLIT] public StringArray getSections ( ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sections == null ) jcasType . jcas . throwFeatMissing ( \"sections\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; return ( StringArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sections ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for sections - sets Content of sections in the document . [CODESPLIT] public void setSections ( StringArray v ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sections == null ) jcasType . jcas . throwFeatMissing ( \"sections\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sections , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed getter for sections - gets an indexed value - Content of sections in the document . [CODESPLIT] public String getSections ( int i ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sections == null ) jcasType . jcas . throwFeatMissing ( \"sections\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sections ) , i ) ; return jcasType . ll_cas . ll_getStringArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sections ) , i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed setter for sections - sets an indexed value - Content of sections in the document . [CODESPLIT] public void setSections ( int i , String v ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sections == null ) jcasType . jcas . throwFeatMissing ( \"sections\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sections ) , i ) ; jcasType . ll_cas . ll_setStringArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sections ) , i , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for sectionLabels - gets Section labels in the document e . g . sections . 0 sections1 etc . [CODESPLIT] public StringArray getSectionLabels ( ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sectionLabels == null ) jcasType . jcas . throwFeatMissing ( \"sectionLabels\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; return ( StringArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sectionLabels ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for sectionLabels - sets Section labels in the document e . g . sections . 0 sections1 etc . [CODESPLIT] public void setSectionLabels ( StringArray v ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sectionLabels == null ) jcasType . jcas . throwFeatMissing ( \"sectionLabels\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sectionLabels , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed getter for sectionLabels - gets an indexed value - Section labels in the document e . g . sections . 0 sections1 etc . [CODESPLIT] public String getSectionLabels ( int i ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sectionLabels == null ) jcasType . jcas . throwFeatMissing ( \"sectionLabels\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sectionLabels ) , i ) ; return jcasType . ll_cas . ll_getStringArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sectionLabels ) , i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed setter for sectionLabels - sets an indexed value - Section labels in the document e . g . sections . 0 sections1 etc . [CODESPLIT] public void setSectionLabels ( int i , String v ) { if ( Document_Type . featOkTst && ( ( Document_Type ) jcasType ) . casFeat_sectionLabels == null ) jcasType . jcas . throwFeatMissing ( \"sectionLabels\" , \"edu.cmu.lti.oaqa.type.retrieval.Document\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sectionLabels ) , i ) ; jcasType . ll_cas . ll_setStringArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Document_Type ) jcasType ) . casFeatCode_sectionLabels ) , i , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for names - gets All name variants ( preferred / default name synonyms lexicial variants etc ) of the concept . [CODESPLIT] public StringList getNames ( ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_names == null ) jcasType . jcas . throwFeatMissing ( \"names\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; return ( StringList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_names ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for uris - gets Array of uris that identify this named entity . There may be more than one uri if this named entity is ambiguous . [CODESPLIT] public StringList getUris ( ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_uris == null ) jcasType . jcas . throwFeatMissing ( \"uris\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; return ( StringList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_uris ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for uris - sets Array of uris that identify this named entity . There may be more than one uri if this named entity is ambiguous . [CODESPLIT] public void setUris ( StringList v ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_uris == null ) jcasType . jcas . throwFeatMissing ( \"uris\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_uris , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for ids - gets A list of IDs ( e . g . UI in UMLS ) associated with this concept . [CODESPLIT] public StringList getIds ( ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_ids == null ) jcasType . jcas . throwFeatMissing ( \"ids\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; return ( StringList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_ids ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for ids - sets A list of IDs ( e . g . UI in UMLS ) associated with this concept . [CODESPLIT] public void setIds ( StringList v ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_ids == null ) jcasType . jcas . throwFeatMissing ( \"ids\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_ids , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for mentions - gets A list of ConceptMentions ( text spans ) that might be surface forms to this concept . [CODESPLIT] public FSList getMentions ( ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_mentions == null ) jcasType . jcas . throwFeatMissing ( \"mentions\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; return ( FSList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_mentions ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for mentions - sets A list of ConceptMentions ( text spans ) that might be surface forms to this concept . [CODESPLIT] public void setMentions ( FSList v ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_mentions == null ) jcasType . jcas . throwFeatMissing ( \"mentions\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_mentions , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for types - gets A list of concept types that the concept belongs to . [CODESPLIT] public FSList getTypes ( ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_types == null ) jcasType . jcas . throwFeatMissing ( \"types\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; return ( FSList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_types ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for types - sets A list of concept types that the concept belongs to . [CODESPLIT] public void setTypes ( FSList v ) { if ( Concept_Type . featOkTst && ( ( Concept_Type ) jcasType ) . casFeat_types == null ) jcasType . jcas . throwFeatMissing ( \"types\" , \"edu.cmu.lti.oaqa.type.kb.Concept\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Concept_Type ) jcasType ) . casFeatCode_types , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for targetType - gets The actual target type annotation . [CODESPLIT] public Annotation getTargetType ( ) { if ( AnswerType_Type . featOkTst && ( ( AnswerType_Type ) jcasType ) . casFeat_targetType == null ) jcasType . jcas . throwFeatMissing ( \"targetType\" , \"edu.cmu.lti.oaqa.type.answer.AnswerType\" ) ; return ( Annotation ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( AnswerType_Type ) jcasType ) . casFeatCode_targetType ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for targetType - sets The actual target type annotation . [CODESPLIT] public void setTargetType ( Annotation v ) { if ( AnswerType_Type . featOkTst && ( ( AnswerType_Type ) jcasType ) . casFeat_targetType == null ) jcasType . jcas . throwFeatMissing ( \"targetType\" , \"edu.cmu.lti.oaqa.type.answer.AnswerType\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( AnswerType_Type ) jcasType ) . casFeatCode_targetType , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for rank - gets Rank of this result in the original hit - list . [CODESPLIT] public int getRank ( ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_rank == null ) jcasType . jcas . throwFeatMissing ( \"rank\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; return jcasType . ll_cas . ll_getIntValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_rank ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for rank - sets Rank of this result in the original hit - list . [CODESPLIT] public void setRank ( int v ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_rank == null ) jcasType . jcas . throwFeatMissing ( \"rank\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; jcasType . ll_cas . ll_setIntValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_rank , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for queryString - gets The query string associated with the hit . [CODESPLIT] public String getQueryString ( ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_queryString == null ) jcasType . jcas . throwFeatMissing ( \"queryString\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_queryString ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for queryString - sets The query string associated with the hit . [CODESPLIT] public void setQueryString ( String v ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_queryString == null ) jcasType . jcas . throwFeatMissing ( \"queryString\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_queryString , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for candidateAnswers - gets CandidateAnswerVariants generated from this SearchResult . [CODESPLIT] public FSArray getCandidateAnswers ( ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_candidateAnswers == null ) jcasType . jcas . throwFeatMissing ( \"candidateAnswers\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; return ( FSArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_candidateAnswers ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for candidateAnswers - sets CandidateAnswerVariants generated from this SearchResult . [CODESPLIT] public void setCandidateAnswers ( FSArray v ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_candidateAnswers == null ) jcasType . jcas . throwFeatMissing ( \"candidateAnswers\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_candidateAnswers , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed getter for candidateAnswers - gets an indexed value - CandidateAnswerVariants generated from this SearchResult . [CODESPLIT] public CandidateAnswerVariant getCandidateAnswers ( int i ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_candidateAnswers == null ) jcasType . jcas . throwFeatMissing ( \"candidateAnswers\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_candidateAnswers ) , i ) ; return ( CandidateAnswerVariant ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_candidateAnswers ) , i ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed setter for candidateAnswers - sets an indexed value - CandidateAnswerVariants generated from this SearchResult . [CODESPLIT] public void setCandidateAnswers ( int i , CandidateAnswerVariant v ) { if ( SearchResult_Type . featOkTst && ( ( SearchResult_Type ) jcasType ) . casFeat_candidateAnswers == null ) jcasType . jcas . throwFeatMissing ( \"candidateAnswers\" , \"edu.cmu.lti.oaqa.type.retrieval.SearchResult\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_candidateAnswers ) , i ) ; jcasType . ll_cas . ll_setRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( SearchResult_Type ) jcasType ) . casFeatCode_candidateAnswers ) , i , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for query - gets The query in the native syntax of the corresponding search engine . [CODESPLIT] public String getQuery ( ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_query == null ) jcasType . jcas . throwFeatMissing ( \"query\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_query ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for query - sets The query in the native syntax of the corresponding search engine . [CODESPLIT] public void setQuery ( String v ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_query == null ) jcasType . jcas . throwFeatMissing ( \"query\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_query , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for hitList - gets Hit list of search results sorted in descreasing order of relevance score . [CODESPLIT] public FSArray getHitList ( ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_hitList == null ) jcasType . jcas . throwFeatMissing ( \"hitList\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; return ( FSArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_hitList ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for hitList - sets Hit list of search results sorted in descreasing order of relevance score . [CODESPLIT] public void setHitList ( FSArray v ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_hitList == null ) jcasType . jcas . throwFeatMissing ( \"hitList\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_hitList , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed getter for hitList - gets an indexed value - Hit list of search results sorted in descreasing order of relevance score . [CODESPLIT] public SearchResult getHitList ( int i ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_hitList == null ) jcasType . jcas . throwFeatMissing ( \"hitList\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_hitList ) , i ) ; return ( SearchResult ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_hitList ) , i ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "indexed setter for hitList - sets an indexed value - Hit list of search results sorted in descreasing order of relevance score . [CODESPLIT] public void setHitList ( int i , SearchResult v ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_hitList == null ) jcasType . jcas . throwFeatMissing ( \"hitList\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_hitList ) , i ) ; jcasType . ll_cas . ll_setRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_hitList ) , i , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for abstractQuery - gets The abstract query from which this actual query was generated . [CODESPLIT] public AbstractQuery getAbstractQuery ( ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_abstractQuery == null ) jcasType . jcas . throwFeatMissing ( \"abstractQuery\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; return ( AbstractQuery ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_abstractQuery ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for abstractQuery - sets The abstract query from which this actual query was generated . [CODESPLIT] public void setAbstractQuery ( AbstractQuery v ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_abstractQuery == null ) jcasType . jcas . throwFeatMissing ( \"abstractQuery\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_abstractQuery , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for searchId - gets An identifier for this search result . Used to collect hit - list objects that belong to this search result after they ve been split out for parallel processing then gathered up again . [CODESPLIT] public String getSearchId ( ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_searchId == null ) jcasType . jcas . throwFeatMissing ( \"searchId\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_searchId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for searchId - sets An identifier for this search result . Used to collect hit - list objects that belong to this search result after they ve been split out for parallel processing then gathered up again . [CODESPLIT] public void setSearchId ( String v ) { if ( Search_Type . featOkTst && ( ( Search_Type ) jcasType ) . casFeat_searchId == null ) jcasType . jcas . throwFeatMissing ( \"searchId\" , \"edu.cmu.lti.oaqa.type.retrieval.Search\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Search_Type ) jcasType ) . casFeatCode_searchId , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for docId - sets A unique identifier for the document that conatins this passage . [CODESPLIT] public void setDocId ( String v ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_docId == null ) jcasType . jcas . throwFeatMissing ( \"docId\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_docId , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for offsetInBeginSection - gets Character offset of the start of this passage within the section that contains this passage . [CODESPLIT] public int getOffsetInBeginSection ( ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_offsetInBeginSection == null ) jcasType . jcas . throwFeatMissing ( \"offsetInBeginSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; return jcasType . ll_cas . ll_getIntValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_offsetInBeginSection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for offsetInBeginSection - sets Character offset of the start of this passage within the section that contains this passage . [CODESPLIT] public void setOffsetInBeginSection ( int v ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_offsetInBeginSection == null ) jcasType . jcas . throwFeatMissing ( \"offsetInBeginSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; jcasType . ll_cas . ll_setIntValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_offsetInBeginSection , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for offsetInEndSection - gets Character offset of the end of this passage within the section that contains this passage . [CODESPLIT] public int getOffsetInEndSection ( ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_offsetInEndSection == null ) jcasType . jcas . throwFeatMissing ( \"offsetInEndSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; return jcasType . ll_cas . ll_getIntValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_offsetInEndSection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for offsetInEndSection - sets Character offset of the end of this passage within the section that contains this passage . [CODESPLIT] public void setOffsetInEndSection ( int v ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_offsetInEndSection == null ) jcasType . jcas . throwFeatMissing ( \"offsetInEndSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; jcasType . ll_cas . ll_setIntValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_offsetInEndSection , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for beginSection - gets The start section of this passage within the document that contains this passage . [CODESPLIT] public String getBeginSection ( ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_beginSection == null ) jcasType . jcas . throwFeatMissing ( \"beginSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_beginSection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for beginSection - sets The start section of this passage within the document that contains this passage . [CODESPLIT] public void setBeginSection ( String v ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_beginSection == null ) jcasType . jcas . throwFeatMissing ( \"beginSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_beginSection , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for endSection - gets The end section of this passage within the document that contains this passage . [CODESPLIT] public String getEndSection ( ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_endSection == null ) jcasType . jcas . throwFeatMissing ( \"endSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_endSection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for endSection - sets The end section of this passage within the document that contains this passage . [CODESPLIT] public void setEndSection ( String v ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_endSection == null ) jcasType . jcas . throwFeatMissing ( \"endSection\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_endSection , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for aspects - gets Aspects of the gold standard passage . [CODESPLIT] public String getAspects ( ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_aspects == null ) jcasType . jcas . throwFeatMissing ( \"aspects\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_aspects ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for aspects - sets Aspects of the gold standard passage . [CODESPLIT] public void setAspects ( String v ) { if ( Passage_Type . featOkTst && ( ( Passage_Type ) jcasType ) . casFeat_aspects == null ) jcasType . jcas . throwFeatMissing ( \"aspects\" , \"edu.cmu.lti.oaqa.type.retrieval.Passage\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Passage_Type ) jcasType ) . casFeatCode_aspects , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for triple - gets The relevant triple searched in the RDF store . [CODESPLIT] public Triple getTriple ( ) { if ( TripleSearchResult_Type . featOkTst && ( ( TripleSearchResult_Type ) jcasType ) . casFeat_triple == null ) jcasType . jcas . throwFeatMissing ( \"triple\" , \"edu.cmu.lti.oaqa.type.retrieval.TripleSearchResult\" ) ; return ( Triple ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( TripleSearchResult_Type ) jcasType ) . casFeatCode_triple ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for triple - sets The relevant triple searched in the RDF store . [CODESPLIT] public void setTriple ( Triple v ) { if ( TripleSearchResult_Type . featOkTst && ( ( TripleSearchResult_Type ) jcasType ) . casFeat_triple == null ) jcasType . jcas . throwFeatMissing ( \"triple\" , \"edu.cmu.lti.oaqa.type.retrieval.TripleSearchResult\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( TripleSearchResult_Type ) jcasType ) . casFeatCode_triple , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for sourceRelation - gets The triple from which the search result was generated [CODESPLIT] public Triple getSourceRelation ( ) { if ( PassageFromRelation_Type . featOkTst && ( ( PassageFromRelation_Type ) jcasType ) . casFeat_sourceRelation == null ) jcasType . jcas . throwFeatMissing ( \"sourceRelation\" , \"edu.cmu.lti.oaqa.type.retrieval.PassageFromRelation\" ) ; return ( Triple ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( PassageFromRelation_Type ) jcasType ) . casFeatCode_sourceRelation ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for sourceRelation - sets The triple from which the search result was generated [CODESPLIT] public void setSourceRelation ( Triple v ) { if ( PassageFromRelation_Type . featOkTst && ( ( PassageFromRelation_Type ) jcasType ) . casFeat_sourceRelation == null ) jcasType . jcas . throwFeatMissing ( \"sourceRelation\" , \"edu.cmu.lti.oaqa.type.retrieval.PassageFromRelation\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( PassageFromRelation_Type ) jcasType ) . casFeatCode_sourceRelation , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for subject - gets The subject of the triple - always a URI . [CODESPLIT] public String getSubject ( ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_subject == null ) jcasType . jcas . throwFeatMissing ( \"subject\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_subject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for subject - sets The subject of the triple - always a URI . [CODESPLIT] public void setSubject ( String v ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_subject == null ) jcasType . jcas . throwFeatMissing ( \"subject\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_subject , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for predicate - gets The predicate of the triple - always a URI . [CODESPLIT] public String getPredicate ( ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_predicate == null ) jcasType . jcas . throwFeatMissing ( \"predicate\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for predicate - sets The predicate of the triple - always a URI . [CODESPLIT] public void setPredicate ( String v ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_predicate == null ) jcasType . jcas . throwFeatMissing ( \"predicate\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_predicate , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for object - gets The object of the triple - may be a URI or an xml datatype ( string int etc . ) . See isObjeUri to determine if object is a URI . [CODESPLIT] public String getObject ( ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_object == null ) jcasType . jcas . throwFeatMissing ( \"object\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_object ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for object - sets The object of the triple - may be a URI or an xml datatype ( string int etc . ) . See isObjeUri to determine if object is a URI . [CODESPLIT] public void setObject ( String v ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_object == null ) jcasType . jcas . throwFeatMissing ( \"object\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_object , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for isObjUri - gets Boolean flag - true of object field is a URI false otherwise . [CODESPLIT] public boolean getIsObjUri ( ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_isObjUri == null ) jcasType . jcas . throwFeatMissing ( \"isObjUri\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; return jcasType . ll_cas . ll_getBooleanValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_isObjUri ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for isObjUri - sets Boolean flag - true of object field is a URI false otherwise . [CODESPLIT] public void setIsObjUri ( boolean v ) { if ( Triple_Type . featOkTst && ( ( Triple_Type ) jcasType ) . casFeat_isObjUri == null ) jcasType . jcas . throwFeatMissing ( \"isObjUri\" , \"edu.cmu.lti.oaqa.type.kb.Triple\" ) ; jcasType . ll_cas . ll_setBooleanValue ( addr , ( ( Triple_Type ) jcasType ) . casFeatCode_isObjUri , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for operator - gets The operator associated with this concept . [CODESPLIT] public QueryOperator getOperator ( ) { if ( ComplexQueryConcept_Type . featOkTst && ( ( ComplexQueryConcept_Type ) jcasType ) . casFeat_operator == null ) jcasType . jcas . throwFeatMissing ( \"operator\" , \"edu.cmu.lti.oaqa.type.retrieval.ComplexQueryConcept\" ) ; return ( QueryOperator ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( ComplexQueryConcept_Type ) jcasType ) . casFeatCode_operator ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for operator - sets The operator associated with this concept . [CODESPLIT] public void setOperator ( QueryOperator v ) { if ( ComplexQueryConcept_Type . featOkTst && ( ( ComplexQueryConcept_Type ) jcasType ) . casFeat_operator == null ) jcasType . jcas . throwFeatMissing ( \"operator\" , \"edu.cmu.lti.oaqa.type.retrieval.ComplexQueryConcept\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( ComplexQueryConcept_Type ) jcasType ) . casFeatCode_operator , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for operatorArgs - gets The operator arguments in a complex query concept . [CODESPLIT] public FSList getOperatorArgs ( ) { if ( ComplexQueryConcept_Type . featOkTst && ( ( ComplexQueryConcept_Type ) jcasType ) . casFeat_operatorArgs == null ) jcasType . jcas . throwFeatMissing ( \"operatorArgs\" , \"edu.cmu.lti.oaqa.type.retrieval.ComplexQueryConcept\" ) ; return ( FSList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( ComplexQueryConcept_Type ) jcasType ) . casFeatCode_operatorArgs ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for operatorArgs - sets The operator arguments in a complex query concept . [CODESPLIT] public void setOperatorArgs ( FSList v ) { if ( ComplexQueryConcept_Type . featOkTst && ( ( ComplexQueryConcept_Type ) jcasType ) . casFeat_operatorArgs == null ) jcasType . jcas . throwFeatMissing ( \"operatorArgs\" , \"edu.cmu.lti.oaqa.type.retrieval.ComplexQueryConcept\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( ComplexQueryConcept_Type ) jcasType ) . casFeatCode_operatorArgs , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "activate Metrics [CODESPLIT] @ GET ( ) @ Path ( ACTIVATE_METRICS_FOR_CLASS ) public String activateMetricsForClass ( @ QueryParam ( QUERY_PARAM_CLASS_FQ_NAME ) final String classFQN ) { if ( classFQN != null && ! classFQN . isEmpty ( ) ) { try { final Class < ? > aClass = Class . forName ( classFQN ) ; DI . activateMetrics ( aClass ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; return e . getMessage ( ) ; } } return OK ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "deactivate Metrics [CODESPLIT] @ GET ( ) @ Path ( DE_ACTIVATE_METRICS_FOR_CLASS ) public String deActivateMetricsForClass ( @ QueryParam ( QUERY_PARAM_CLASS_FQ_NAME ) final String classFQN ) { if ( classFQN != null && ! classFQN . isEmpty ( ) ) { try { final Class < ? > aClass = Class . forName ( classFQN ) ; DI . deActivateMetrics ( aClass ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; return e . getMessage ( ) ; } return OK ; } return NOT_OK ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for concept - gets The abstract concept that the text span conveys . [CODESPLIT] public Concept getConcept ( ) { if ( ConceptMention_Type . featOkTst && ( ( ConceptMention_Type ) jcasType ) . casFeat_concept == null ) jcasType . jcas . throwFeatMissing ( \"concept\" , \"edu.cmu.lti.oaqa.type.kb.ConceptMention\" ) ; return ( Concept ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( ConceptMention_Type ) jcasType ) . casFeatCode_concept ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for matchedName - gets A synonym of the concept that best matches the concept mention ( similar to conceptMatched in metamap ) . [CODESPLIT] public String getMatchedName ( ) { if ( ConceptMention_Type . featOkTst && ( ( ConceptMention_Type ) jcasType ) . casFeat_matchedName == null ) jcasType . jcas . throwFeatMissing ( \"matchedName\" , \"edu.cmu.lti.oaqa.type.kb.ConceptMention\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( ConceptMention_Type ) jcasType ) . casFeatCode_matchedName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for matchedName - sets A synonym of the concept that best matches the concept mention ( similar to conceptMatched in metamap ) . [CODESPLIT] public void setMatchedName ( String v ) { if ( ConceptMention_Type . featOkTst && ( ( ConceptMention_Type ) jcasType ) . casFeat_matchedName == null ) jcasType . jcas . throwFeatMissing ( \"matchedName\" , \"edu.cmu.lti.oaqa.type.kb.ConceptMention\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( ConceptMention_Type ) jcasType ) . casFeatCode_matchedName , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for score - gets The confidence score that the concept mention matches the concept . [CODESPLIT] public double getScore ( ) { if ( ConceptMention_Type . featOkTst && ( ( ConceptMention_Type ) jcasType ) . casFeat_score == null ) jcasType . jcas . throwFeatMissing ( \"score\" , \"edu.cmu.lti.oaqa.type.kb.ConceptMention\" ) ; return jcasType . ll_cas . ll_getDoubleValue ( addr , ( ( ConceptMention_Type ) jcasType ) . casFeatCode_score ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for text - gets The candidate answer string . [CODESPLIT] public String getText ( ) { if ( CandidateAnswerOccurrence_Type . featOkTst && ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeat_text == null ) jcasType . jcas . throwFeatMissing ( \"text\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerOccurrence\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeatCode_text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for text - sets The candidate answer string . [CODESPLIT] public void setText ( String v ) { if ( CandidateAnswerOccurrence_Type . featOkTst && ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeat_text == null ) jcasType . jcas . throwFeatMissing ( \"text\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerOccurrence\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeatCode_text , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for mentionType - gets The manner in which covered text refers to some entity e . g . NAME NOMINAL PRONOUN [CODESPLIT] public String getMentionType ( ) { if ( CandidateAnswerOccurrence_Type . featOkTst && ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeat_mentionType == null ) jcasType . jcas . throwFeatMissing ( \"mentionType\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerOccurrence\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeatCode_mentionType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for mentionType - sets The manner in which covered text refers to some entity e . g . NAME NOMINAL PRONOUN [CODESPLIT] public void setMentionType ( String v ) { if ( CandidateAnswerOccurrence_Type . featOkTst && ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeat_mentionType == null ) jcasType . jcas . throwFeatMissing ( \"mentionType\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerOccurrence\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( CandidateAnswerOccurrence_Type ) jcasType ) . casFeatCode_mentionType , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for id - gets The id of the concept type . [CODESPLIT] public String getId ( ) { if ( ConceptType_Type . featOkTst && ( ( ConceptType_Type ) jcasType ) . casFeat_id == null ) jcasType . jcas . throwFeatMissing ( \"id\" , \"edu.cmu.lti.oaqa.type.kb.ConceptType\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( ConceptType_Type ) jcasType ) . casFeatCode_id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for id - sets The id of the concept type . [CODESPLIT] public void setId ( String v ) { if ( ConceptType_Type . featOkTst && ( ( ConceptType_Type ) jcasType ) . casFeat_id == null ) jcasType . jcas . throwFeatMissing ( \"id\" , \"edu.cmu.lti.oaqa.type.kb.ConceptType\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( ConceptType_Type ) jcasType ) . casFeatCode_id , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for name - gets A human readable concept label . [CODESPLIT] public String getName ( ) { if ( ConceptType_Type . featOkTst && ( ( ConceptType_Type ) jcasType ) . casFeat_name == null ) jcasType . jcas . throwFeatMissing ( \"name\" , \"edu.cmu.lti.oaqa.type.kb.ConceptType\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( ConceptType_Type ) jcasType ) . casFeatCode_name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for abbreviation - gets The abbreviation of the name label . [CODESPLIT] public String getAbbreviation ( ) { if ( ConceptType_Type . featOkTst && ( ( ConceptType_Type ) jcasType ) . casFeat_abbreviation == null ) jcasType . jcas . throwFeatMissing ( \"abbreviation\" , \"edu.cmu.lti.oaqa.type.kb.ConceptType\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( ConceptType_Type ) jcasType ) . casFeatCode_abbreviation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for abbreviation - sets The abbreviation of the name label . [CODESPLIT] public void setAbbreviation ( String v ) { if ( ConceptType_Type . featOkTst && ( ( ConceptType_Type ) jcasType ) . casFeat_abbreviation == null ) jcasType . jcas . throwFeatMissing ( \"abbreviation\" , \"edu.cmu.lti.oaqa.type.kb.ConceptType\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( ConceptType_Type ) jcasType ) . casFeatCode_abbreviation , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for concept - sets The relevant concept searched in the ontology . [CODESPLIT] public void setConcept ( Concept v ) { if ( ConceptSearchResult_Type . featOkTst && ( ( ConceptSearchResult_Type ) jcasType ) . casFeat_concept == null ) jcasType . jcas . throwFeatMissing ( \"concept\" , \"edu.cmu.lti.oaqa.type.retrieval.ConceptSearchResult\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( ConceptSearchResult_Type ) jcasType ) . casFeatCode_concept , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for variants - gets List of candidate answer variants that were merged into this final answer . [CODESPLIT] public FSList getVariants ( ) { if ( Answer_Type . featOkTst && ( ( Answer_Type ) jcasType ) . casFeat_variants == null ) jcasType . jcas . throwFeatMissing ( \"variants\" , \"edu.cmu.lti.oaqa.type.answer.Answer\" ) ; return ( FSList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Answer_Type ) jcasType ) . casFeatCode_variants ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for variants - sets List of candidate answer variants that were merged into this final answer . [CODESPLIT] public void setVariants ( FSList v ) { if ( Answer_Type . featOkTst && ( ( Answer_Type ) jcasType ) . casFeat_variants == null ) jcasType . jcas . throwFeatMissing ( \"variants\" , \"edu.cmu.lti.oaqa.type.answer.Answer\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Answer_Type ) jcasType ) . casFeatCode_variants , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for namedEntityTypes - gets List of Named Entity types associated with this concept . [CODESPLIT] public StringList getNamedEntityTypes ( ) { if ( QueryConcept_Type . featOkTst && ( ( QueryConcept_Type ) jcasType ) . casFeat_namedEntityTypes == null ) jcasType . jcas . throwFeatMissing ( \"namedEntityTypes\" , \"edu.cmu.lti.oaqa.type.retrieval.QueryConcept\" ) ; return ( StringList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( QueryConcept_Type ) jcasType ) . casFeatCode_namedEntityTypes ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for namedEntityTypes - sets List of Named Entity types associated with this concept . [CODESPLIT] public void setNamedEntityTypes ( StringList v ) { if ( QueryConcept_Type . featOkTst && ( ( QueryConcept_Type ) jcasType ) . casFeat_namedEntityTypes == null ) jcasType . jcas . throwFeatMissing ( \"namedEntityTypes\" , \"edu.cmu.lti.oaqa.type.retrieval.QueryConcept\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( QueryConcept_Type ) jcasType ) . casFeatCode_namedEntityTypes , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for conceptType - gets The type of this concept . [CODESPLIT] public String getConceptType ( ) { if ( QueryConcept_Type . featOkTst && ( ( QueryConcept_Type ) jcasType ) . casFeat_conceptType == null ) jcasType . jcas . throwFeatMissing ( \"conceptType\" , \"edu.cmu.lti.oaqa.type.retrieval.QueryConcept\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( QueryConcept_Type ) jcasType ) . casFeatCode_conceptType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for conceptType - sets The type of this concept . [CODESPLIT] public void setConceptType ( String v ) { if ( QueryConcept_Type . featOkTst && ( ( QueryConcept_Type ) jcasType ) . casFeat_conceptType == null ) jcasType . jcas . throwFeatMissing ( \"conceptType\" , \"edu.cmu.lti.oaqa.type.retrieval.QueryConcept\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( QueryConcept_Type ) jcasType ) . casFeatCode_conceptType , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO extend for a Vaadin App Version [CODESPLIT] private static DeploymentInfo createServletDeploymentInfos ( ) { final Set < Class < ? > > typesAnnotatedWith = DI . getTypesAnnotatedWith ( WebServlet . class , true ) ; final List < ServletInfo > servletInfos = typesAnnotatedWith . stream ( ) . filter ( s -> new ReflectionUtils ( ) . checkInterface ( s , HttpServlet . class ) ) . map ( c -> { Class < HttpServlet > servletClass = ( Class < HttpServlet > ) c ; final ServletInfo servletInfo = servlet ( c . getSimpleName ( ) , servletClass , new ServletInstanceFactory <> ( servletClass ) ) ; if ( c . isAnnotationPresent ( WebInitParam . class ) ) { final WebInitParam [ ] annotationsByType = c . getAnnotationsByType ( WebInitParam . class ) ; for ( WebInitParam webInitParam : annotationsByType ) { final String value = webInitParam . value ( ) ; final String name = webInitParam . name ( ) ; servletInfo . addInitParam ( name , value ) ; } } final WebServlet annotation = c . getAnnotation ( WebServlet . class ) ; final String [ ] urlPatterns = annotation . urlPatterns ( ) ; for ( String urlPattern : urlPatterns ) { servletInfo . addMapping ( urlPattern ) ; } servletInfo . setAsyncSupported ( annotation . asyncSupported ( ) ) ; return servletInfo ; } ) . filter ( servletInfo -> ! servletInfo . getMappings ( ) . isEmpty ( ) ) . collect ( Collectors . toList ( ) ) ; final Set < Class < ? > > weblisteners = DI . getTypesAnnotatedWith ( WebListener . class ) ; final List < ListenerInfo > listenerInfos = weblisteners . stream ( ) . map ( c -> new ListenerInfo ( ( Class < ? extends EventListener > ) c ) ) . collect ( Collectors . toList ( ) ) ; final DeploymentInfo deploymentInfo = deployment ( ) . setClassLoader ( Main . class . getClassLoader ( ) ) . setContextPath ( MYAPP ) . setDeploymentName ( \"ROOT\" + \".war\" ) . setDefaultEncoding ( \"UTF-8\" ) ; final Boolean shiroActive = Boolean . valueOf ( System . getProperty ( SHIRO_ACTIVE_PROPERTY , \"false\" ) ) ; final Boolean stagemonitorActive = Boolean . valueOf ( System . getProperty ( STAGEMONITOR_ACTIVE_PROPERTY , \"false\" ) ) ; if ( shiroActive ) addShiroFilter ( ) . apply ( deploymentInfo , DEFAULT_SHIRO_FILTER_NAME , DEFAULT_FILTER_MAPPING ) ; if ( stagemonitorActive ) addStagemonitor ( ) . apply ( deploymentInfo ) ; return deploymentInfo . addListeners ( listenerInfos ) . addServletContextAttribute ( WebSocketDeploymentInfo . ATTRIBUTE_NAME , new WebSocketDeploymentInfo ( ) ) . addServlets ( servletInfos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for occurrences - gets The occurrences of this variant . [CODESPLIT] public FSList getOccurrences ( ) { if ( CandidateAnswerVariant_Type . featOkTst && ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeat_occurrences == null ) jcasType . jcas . throwFeatMissing ( \"occurrences\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerVariant\" ) ; return ( FSList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeatCode_occurrences ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for occurrences - sets The occurrences of this variant . [CODESPLIT] public void setOccurrences ( FSList v ) { if ( CandidateAnswerVariant_Type . featOkTst && ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeat_occurrences == null ) jcasType . jcas . throwFeatMissing ( \"occurrences\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerVariant\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeatCode_occurrences , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for names - sets Names for a given candidate answer variant e . g . Tandy Tandy Inc . for candidate answer Variant Tandy Incorporated . [CODESPLIT] public void setNames ( StringList v ) { if ( CandidateAnswerVariant_Type . featOkTst && ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeat_names == null ) jcasType . jcas . throwFeatMissing ( \"names\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerVariant\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeatCode_names , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for docId - gets The unique id of the document ( if any ) from which this candidate answer was generated . [CODESPLIT] public String getDocId ( ) { if ( CandidateAnswerVariant_Type . featOkTst && ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeat_docId == null ) jcasType . jcas . throwFeatMissing ( \"docId\" , \"edu.cmu.lti.oaqa.type.answer.CandidateAnswerVariant\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( CandidateAnswerVariant_Type ) jcasType ) . casFeatCode_docId ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for concepts - gets The list of query concepts that make up this abstract query . The list is ordered . [CODESPLIT] public FSList getConcepts ( ) { if ( AbstractQuery_Type . featOkTst && ( ( AbstractQuery_Type ) jcasType ) . casFeat_concepts == null ) jcasType . jcas . throwFeatMissing ( \"concepts\" , \"edu.cmu.lti.oaqa.type.retrieval.AbstractQuery\" ) ; return ( FSList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( AbstractQuery_Type ) jcasType ) . casFeatCode_concepts ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for concepts - sets The list of query concepts that make up this abstract query . The list is ordered . [CODESPLIT] public void setConcepts ( FSList v ) { if ( AbstractQuery_Type . featOkTst && ( ( AbstractQuery_Type ) jcasType ) . casFeat_concepts == null ) jcasType . jcas . throwFeatMissing ( \"concepts\" , \"edu.cmu.lti.oaqa.type.retrieval.AbstractQuery\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( AbstractQuery_Type ) jcasType ) . casFeatCode_concepts , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for originalText - gets The lexical string in the question . [CODESPLIT] public String getOriginalText ( ) { if ( AtomicQueryConcept_Type . featOkTst && ( ( AtomicQueryConcept_Type ) jcasType ) . casFeat_originalText == null ) jcasType . jcas . throwFeatMissing ( \"originalText\" , \"edu.cmu.lti.oaqa.type.retrieval.AtomicQueryConcept\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( AtomicQueryConcept_Type ) jcasType ) . casFeatCode_originalText ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for originalText - sets The lexical string in the question . [CODESPLIT] public void setOriginalText ( String v ) { if ( AtomicQueryConcept_Type . featOkTst && ( ( AtomicQueryConcept_Type ) jcasType ) . casFeat_originalText == null ) jcasType . jcas . throwFeatMissing ( \"originalText\" , \"edu.cmu.lti.oaqa.type.retrieval.AtomicQueryConcept\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( AtomicQueryConcept_Type ) jcasType ) . casFeatCode_originalText , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for args - gets The arguments for the operator . [CODESPLIT] public StringList getArgs ( ) { if ( QueryOperator_Type . featOkTst && ( ( QueryOperator_Type ) jcasType ) . casFeat_args == null ) jcasType . jcas . throwFeatMissing ( \"args\" , \"edu.cmu.lti.oaqa.type.retrieval.QueryOperator\" ) ; return ( StringList ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( QueryOperator_Type ) jcasType ) . casFeatCode_args ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for args - sets The arguments for the operator . [CODESPLIT] public void setArgs ( StringList v ) { if ( QueryOperator_Type . featOkTst && ( ( QueryOperator_Type ) jcasType ) . casFeat_args == null ) jcasType . jcas . throwFeatMissing ( \"args\" , \"edu.cmu.lti.oaqa.type.retrieval.QueryOperator\" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( QueryOperator_Type ) jcasType ) . casFeatCode_args , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "getter for label - gets The semantic role label . [CODESPLIT] public String getLabel ( ) { if ( SemanticRole_Type . featOkTst && ( ( SemanticRole_Type ) jcasType ) . casFeat_label == null ) jcasType . jcas . throwFeatMissing ( \"label\" , \"edu.cmu.lti.oaqa.type.nlp.SemanticRole\" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( SemanticRole_Type ) jcasType ) . casFeatCode_label ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "setter for label - sets The semantic role label . [CODESPLIT] public void setLabel ( String v ) { if ( SemanticRole_Type . featOkTst && ( ( SemanticRole_Type ) jcasType ) . casFeat_label == null ) jcasType . jcas . throwFeatMissing ( \"label\" , \"edu.cmu.lti.oaqa.type.nlp.SemanticRole\" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( SemanticRole_Type ) jcasType ) . casFeatCode_label , v ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Find the next clear bit in the bit set . [CODESPLIT] public int nextClearBit ( int index ) { int i = index >> 6 ; if ( i >= wlen ) return - 1 ; int subIndex = index & 0x3f ; // index within the word long word = ~ bits . get ( i ) >> subIndex ; // skip all the bits to the right of // index if ( word != 0 ) { return ( i << 6 ) + subIndex + Long . numberOfTrailingZeros ( word ) ; } while ( ++ i < wlen ) { word = ~ bits . get ( i ) ; if ( word != 0 ) { return ( i << 6 ) + Long . numberOfTrailingZeros ( word ) ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Thread safe set operation that will set the bit if and only if the bit was not previously set . [CODESPLIT] public boolean set ( int index ) { int wordNum = index >> 6 ; // div 64 int bit = index & 0x3f ; // mod 64 long bitmask = 1L << bit ; long word , oword ; do { word = bits . get ( wordNum ) ; // if set another thread stole the lock if ( ( word & bitmask ) != 0 ) { return false ; } oword = word ; word |= bitmask ; } while ( ! bits . compareAndSet ( wordNum , oword , word ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "toString [CODESPLIT] private String selectToString ( ) { StringBuilder sql = new StringBuilder ( \"select \" ) ; sql . append ( Seq . join ( fields , \", \" ) ) . append ( \" from \" ) . append ( Seq . join ( tables , \" join \" ) ) ; if ( ! conditions . isEmpty ( ) ) { sql . append ( \" where \" ) . append ( Seq . join ( conditions , \" and \" ) ) ; } if ( ! groups . isEmpty ( ) ) { sql . append ( \" group by \" ) . append ( Seq . join ( groups , \", \" ) ) ; if ( ! having . isEmpty ( ) ) { sql . append ( \" having \" ) . append ( Seq . join ( having , \" and \" ) ) ; } } if ( ! orders . isEmpty ( ) ) { sql . append ( \" order by \" ) . append ( Seq . join ( orders , \", \" ) ) ; } if ( limit > 0 ) { sql . append ( \" limit \" ) . append ( Integer . toString ( limit ) ) ; } if ( offset > - 1 ) { sql . append ( \" offset \" ) . append ( Integer . toString ( offset ) ) ; } return sql . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Transaction [CODESPLIT] public void batch ( Runnable transaction ) { // TODO: 不支持嵌套事务 try ( Connection c = pool . getConnection ( ) ) { boolean commit = c . getAutoCommit ( ) ; try { c . setAutoCommit ( false ) ; } catch ( SQLException e ) { throw new TransactionException ( \"transaction setAutoCommit(false)\" , e ) ; } base . set ( c ) ; try { transaction . run ( ) ; } catch ( RuntimeException e ) { try { c . rollback ( ) ; c . setAutoCommit ( commit ) ; } catch ( SQLException ex ) { throw new TransactionException ( \"transaction rollback: \" + ex . getMessage ( ) , e ) ; } throw e ; } try { c . commit ( ) ; } catch ( SQLException e ) { throw new TransactionException ( \"transaction commit\" , e ) ; } c . setAutoCommit ( commit ) ; } catch ( SQLException e ) { throw new DBOpenException ( e ) ; } finally { base . set ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This code was copied form MMAPDirectory in Lucene . [CODESPLIT] protected void freeBuffer ( final ByteBuffer buffer ) throws IOException { if ( buffer == null ) { return ; } if ( UNMAP_SUPPORTED ) { try { AccessController . doPrivileged ( new PrivilegedExceptionAction < Void > ( ) { @ Override public Void run ( ) throws Exception { final Method getCleanerMethod = buffer . getClass ( ) . getMethod ( \"cleaner\" ) ; getCleanerMethod . setAccessible ( true ) ; final Object cleaner = getCleanerMethod . invoke ( buffer ) ; if ( cleaner != null ) { cleaner . getClass ( ) . getMethod ( \"clean\" ) . invoke ( cleaner ) ; } return null ; } } ) ; } catch ( PrivilegedActionException e ) { final IOException ioe = new IOException ( \"unable to unmap the mapped buffer\" ) ; ioe . initCause ( e . getCause ( ) ) ; throw ioe ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of CacheValue the cache capacity should be used for the given file . [CODESPLIT] public CacheValue newInstance ( CacheDirectory directory , String fileName ) { return newInstance ( directory , fileName , getCacheBlockSize ( directory , fileName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "继承给定的JavaBean，扩展Record对象的get和set方法。 [CODESPLIT] public Table extend ( Object bean ) { Class < ? > type = bean . getClass ( ) ; for ( Method method : type . getDeclaredMethods ( ) ) { Class < ? > returnType = method . getReturnType ( ) ; Class < ? > [ ] params = method . getParameterTypes ( ) ; String key = method . getName ( ) ; if ( params . length == 2 && key . length ( ) > 3 && ( key . startsWith ( \"get\" ) || key . startsWith ( \"set\" ) ) && params [ 0 ] . isAssignableFrom ( Record . class ) && params [ 1 ] . isAssignableFrom ( Object . class ) && Object . class . isAssignableFrom ( returnType ) ) { key = key . replaceAll ( \"(?=[A-Z])\" , \"_\" ) . toLowerCase ( ) ; hooks . put ( key , new Lambda ( bean , method ) ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Association [CODESPLIT] private Association assoc ( String name , boolean onlyOne , boolean ancestor ) { name = DB . parseKeyParameter ( name ) ; Association assoc = new Association ( relations , name , onlyOne , ancestor ) ; relations . put ( name , assoc ) ; return assoc ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * CRUD [CODESPLIT] public Record create ( Object ... args ) { Map < String , Object > data = new HashMap <> ( ) ; data . putAll ( foreignKeys ) ; for ( int i = 0 ; i < args . length ; i += 2 ) { String key = DB . parseKeyParameter ( args [ i ] . toString ( ) ) ; if ( ! columns . containsKey ( key ) ) { throw new IllegalFieldNameException ( key ) ; } Object value = args [ i + 1 ] ; data . put ( key , value ) ; } String [ ] fields = new String [ data . size ( ) + 2 ] ; int [ ] types = new int [ data . size ( ) + 2 ] ; Object [ ] values = new Object [ data . size ( ) + 2 ] ; int index = 0 ; for ( Map . Entry < String , Object > e : data . entrySet ( ) ) { fields [ index ] = e . getKey ( ) ; types [ index ] = columns . get ( e . getKey ( ) ) ; values [ index ] = e . getValue ( ) ; index ++ ; } Seq . assignAt ( fields , Seq . array ( - 2 , - 1 ) , \"created_at\" , \"updated_at\" ) ; Seq . assignAt ( types , Seq . array ( - 2 , - 1 ) , Types . TIMESTAMP , Types . TIMESTAMP ) ; Seq . assignAt ( values , Seq . array ( - 2 , - 1 ) , DB . now ( ) , DB . now ( ) ) ; SqlBuilder sql = new TSqlBuilder ( ) ; sql . insert ( ) . into ( name ) . values ( fields ) ; PreparedStatement call = dbo . prepare ( sql . toString ( ) , values , types ) ; try { int id = 0 ; if ( call . executeUpdate ( ) > 0 ) { ResultSet rs = call . getGeneratedKeys ( ) ; if ( rs != null && rs . next ( ) ) { id = rs . getInt ( 1 ) ; rs . close ( ) ; } } return id > 0 ? find ( id ) : null ; } catch ( SQLException e ) { throw new SqlExecuteException ( sql . toString ( ) , e ) ; } finally { dbo . close ( call ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据现有的Record创建新的Record . 为跨数据库之间导数据提供便捷接口；同时也方便根据模板创建多条相似的纪录。 [CODESPLIT] public Record create ( Record o ) { List < Object > params = new LinkedList <> ( ) ; for ( String key : columns . keySet ( ) ) { if ( ! foreignKeys . containsKey ( key ) ) { params . add ( key ) ; params . add ( o . get ( key ) ) ; } } return create ( params . toArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据指定列，返回符合条件的第一条记录 . [CODESPLIT] public Record findA ( String key , Object value ) { key = DB . parseKeyParameter ( key ) ; if ( value != null ) { return first ( key . concat ( \" = ?\" ) , value ) ; } else { return first ( key . concat ( \" is null\" ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断当前数据库的名称里是否包含hsql（忽略大小写）。 [CODESPLIT] @ Override public boolean accept ( Connection c ) { try { DatabaseMetaData d = c . getMetaData ( ) ; String name = d . getDatabaseProductName ( ) ; // HSQL Database Engine return name . toLowerCase ( ) . contains ( \"hsql\" ) ; } catch ( SQLException e ) { throw new DBOpenException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flushes the in - memory bufer to the given output copying at most <code > numBytes< / code > . <p > <b > NOTE : < / b > this method does not refill the buffer however it does advance the buffer position . [CODESPLIT] protected final int flushBuffer ( IndexOutput out , long numBytes ) throws IOException { int toCopy = bufferLength - bufferPosition ; if ( toCopy > numBytes ) { toCopy = ( int ) numBytes ; } if ( toCopy > 0 ) { out . writeBytes ( buffer , bufferPosition , toCopy ) ; bufferPosition += toCopy ; } return toCopy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一系列对象组装成List。 [CODESPLIT] public static < E > List < E > list ( E ... args ) { List < E > list = new ArrayList <> ( ) ; list . addAll ( Arrays . asList ( args ) ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "追加任意多个新元素到数组末尾。 [CODESPLIT] public static < E > E [ ] concat ( E [ ] a , E ... b ) { return merge ( a , b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将数组连接成字符串。 [CODESPLIT] public static String join ( String delimiter , Object ... args ) { return join ( Arrays . asList ( args ) , delimiter ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将容器里的元素连接成字符串。 [CODESPLIT] public static String join ( Collection < ? > list , String delimiter ) { if ( list == null || list . isEmpty ( ) ) { return \"\" ; } if ( delimiter == null ) { delimiter = \"\" ; } StringBuilder s = new StringBuilder ( ) ; boolean first = true ; for ( Object e : list ) { if ( first ) { first = false ; } else { s . append ( delimiter ) ; } s . append ( e ) ; } return s . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "合并两个数组。 [CODESPLIT] public static < E > E [ ] merge ( E [ ] a , E [ ] b ) { List < E > list = merge ( Arrays . asList ( a ) , Arrays . asList ( b ) ) ; return list . toArray ( a ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "合并两个List。 [CODESPLIT] public static < E > List < E > merge ( List < E > a , List < E > b ) { List < E > list = new ArrayList <> ( ) ; list . addAll ( a ) ; list . addAll ( b ) ; return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从数组中删除所有与给定对象equals的元素。 [CODESPLIT] public static < E > E [ ] remove ( E [ ] a , E e ) { List < E > list = remove ( Arrays . asList ( a ) , e ) ; return ( E [ ] ) list . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从List中删除所有与给定对象equals的元素。 [CODESPLIT] public static < E > List < E > remove ( List < E > a , E e ) { List < E > list = new ArrayList <> ( ) ; for ( E o : a ) { if ( ! o . equals ( e ) ) { list . add ( o ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据给定的下标，选出多个元素，并组成新的数组。 [CODESPLIT] public static < E > E [ ] valuesAt ( E [ ] a , int ... indexes ) { List < E > list = valuesAt ( Arrays . asList ( a ) , indexes ) ; return ( E [ ] ) list . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据给定的下标，选出多个元素，并组成新的List。 [CODESPLIT] public static < E > List < E > valuesAt ( List < E > from , int ... indexes ) { List < E > list = new ArrayList <> ( ) ; for ( int i : indexes ) { if ( 0 <= i && i < from . size ( ) ) { list . add ( from . get ( i ) ) ; } else if ( - from . size ( ) <= i && i < 0 ) { list . add ( from . get ( from . size ( ) + i ) ) ; } else { list . add ( null ) ; } } return list ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "同时给int数组中多个位置同时赋值。 [CODESPLIT] public static int [ ] assignAt ( int [ ] a , Integer [ ] indexes , int ... values ) { if ( indexes . length != values . length ) { throw new IllegalArgumentException ( String . format ( \"index.length(%d) != values.length(%d)\" , indexes . length , values . length ) ) ; } for ( int i = 0 ; i < indexes . length ; i ++ ) { int index = indexes [ i ] ; if ( 0 <= index && index < a . length ) { a [ index ] = values [ i ] ; } else if ( - a . length <= index && index < 0 ) { a [ a . length + index ] = values [ i ] ; } else { throw new ArrayIndexOutOfBoundsException ( index ) ; } } return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据规定格式，对容器中的每个元素进行格式化，并返回格式化后的结果。 [CODESPLIT] public static List < String > map ( Collection < ? > from , String format ) { List < String > to = new ArrayList <> ( from . size ( ) ) ; for ( Object e : from ) { to . add ( String . format ( format , e ) ) ; } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "拆分容器，每份至多包含n个元素，将每堆元素连接成一个独立字符串。 [CODESPLIT] public static List < String > partition ( Collection < String > from , int n , String delimiter ) { List < String > to = new ArrayList <> ( ) ; List < String > buffer = new ArrayList <> ( n ) ; for ( String e : from ) { buffer . add ( e ) ; if ( buffer . size ( ) >= n ) { to . add ( join ( buffer , delimiter ) ) ; buffer . clear ( ) ; } } return to ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rebuild the backing array with a different size . [CODESPLIT] private static Object [ ] rehash ( final Object [ ] values , final int newSize ) { Object [ ] newArray = new Object [ newSize ] ; for ( Object value : values ) { if ( value == null ) { continue ; } newArray [ predictedPosition ( newArray , value , value . hashCode ( ) ) ] = value ; } return newArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the position of the given element in the given array . The value at the calculated position will be <code > null< / code > if the element doesn t exist in the array otherwise the position will point to the element . [CODESPLIT] private static int predictedPosition ( final Object [ ] array , final Object object , final int hash ) { int arraySize = array . length ; int i = Math . abs ( hash ) % arraySize ; Object element = array [ i ] ; while ( element != null ) // the load factor guarantees that there is always at least one free slot { if ( element . equals ( object ) ) { // already in the array return i ; } // the position is taken, try the next slot i = ( i + 1 ) % arraySize ; element = array [ i ] ; } return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move { [CODESPLIT] private void findNextSeparator ( ) { mLastSeparatorPos = mNextSeparatorPos ; while ( ++ mNextSeparatorPos < mValue . length ( ) ) { char c = mValue . charAt ( mNextSeparatorPos ) ; if ( c == mSeparator ) { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move { [CODESPLIT] private void findNextSeparator ( ) { boolean isQuoted = false ; mLastSeparatorPos = mNextSeparatorPos ; while ( ++ mNextSeparatorPos < mValue . length ( ) ) { char c = mValue . charAt ( mNextSeparatorPos ) ; if ( c == mSeparator ) { if ( ! isQuoted ) { return ; } // else: ignore quoted speparator } else if ( c == ' ' ) { isQuoted = ! isQuoted ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate a valid HELM2 of this object [CODESPLIT] public String toHELM2 ( ) { StringBuilder notation = new StringBuilder ( ) ; for ( int i = 0 ; i < listMonomerNotations . size ( ) ; i ++ ) { notation . append ( listMonomerNotations . get ( i ) . toHELM2 ( ) + \".\" ) ; } notation . setLength ( notation . length ( ) - 1 ) ; return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@return PolymerElments in HELM format @throws HELM1ConverterException if one single object can not be downgraded to HELM1 - Format [CODESPLIT] public String toHELM ( ) throws HELM1ConverterException { StringBuilder notation = new StringBuilder ( ) ; for ( int i = 0 ; i < listMonomerNotations . size ( ) ; i ++ ) { notation . append ( listMonomerNotations . get ( i ) . toHELM ( ) + \".\" ) ; } notation . setLength ( notation . length ( ) - 1 ) ; return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public void doAction ( char cha ) throws ConnectionSectionException , NotationException { /* list of connections is empty */ if ( cha == ' ' ) { if ( sourcepolymerid == \"\" && _parser . notationContainer . getListOfConnections ( ) . size ( ) == 0 ) { LOG . info ( \"Connection section is empty:\" ) ; LOG . info ( \"Transition to group section:\" ) ; _parser . setState ( new GroupingParser ( _parser ) ) ; } else { LOG . error ( \"Missing target polymer ID in connection section:\" ) ; throw new ConnectionSectionException ( \"Missing target polymer id in connection section. Source of connection is \" + sourcepolymerid ) ; } } /* target polymer ID is starting */ else if ( cha == ' ' && checkBracketsParenthesis ( ) ) { if ( _parser . checkPolymeridConnection ( sourcepolymerid ) ) { LOG . info ( \"Target polymer ID is read:\" ) ; _parser . notationContainer . addConnection ( new ConnectionNotation ( sourcepolymerid ) ) ; _parser . setState ( new ConnectionsReadSecondIDParser ( _parser ) ) ; } else { LOG . error ( \"Source polymer ID is not correct in the connection section: \" + sourcepolymerid ) ; throw new ConnectionSectionException ( \"Source polymer id is not correct in the connection section: \" + sourcepolymerid ) ; } } else { sourcepolymerid += cha ; if ( cha == ' ' ) { parenthesisCounterOpen += 1 ; } if ( cha == ' ' ) { parenthesisCounterClose += 1 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String toHELM2 ( ) { DecimalFormat d = new DecimalFormat ( \"#.##\" ) ; StringBuilder notation = new StringBuilder ( ) ; for ( int i = 0 ; i < elements . size ( ) ; i ++ ) { if ( ! ( elements . get ( i ) . isDefaultValue ( ) ) ) { String value = d . format ( elements . get ( i ) . getValue ( ) . get ( 0 ) ) . replace ( ' ' , ' ' ) ; if ( elements . get ( i ) . getValue ( ) . size ( ) > 1 ) { value += \"-\" + d . format ( elements . get ( i ) . getValue ( ) . get ( 1 ) ) . replace ( ' ' , ' ' ) ; } notation . append ( elements . get ( i ) . getID ( ) + \":\" + value + \",\" ) ; } else { notation . append ( elements . get ( i ) . getID ( ) + \",\" ) ; } } notation . setLength ( notation . length ( ) - 1 ) ; return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws AnnotationSectionException { /* list of attributes is finished */ if ( cha == ' ' ) { if ( checkBracketsParenthesis ( ) ) { LOG . info ( \"Annotation section is finished:\" ) ; if ( annotation != \"\" ) { _parser . notationContainer . addAnnotation ( new AnnotationNotation ( annotation ) ) ; } LOG . info ( \"Transition to FinalState:\" ) ; _parser . setState ( new FinalState ( ) ) ; } else { LOG . info ( \"Annotation section is not valid: \" + annotation ) ; throw new AnnotationSectionException ( \"Annotation section is not valid: \" + annotation ) ; } } else if ( cha == ' ' ) { if ( checkBracketsParenthesis ( ) ) { LOG . info ( \" new annotation is starting\" ) ; if ( annotation != \"\" ) { _parser . notationContainer . addAnnotation ( new AnnotationNotation ( annotation ) ) ; _parser . setState ( new AnnotationsParser ( _parser ) ) ; } else { LOG . info ( \"Annotation section is not valid: \" ) ; throw new AnnotationSectionException ( \"Annotation section is not valid: \" ) ; } } } else { annotation += cha ; if ( cha == ' ' ) { curlyBracketCounterOpen ++ ; } if ( cha == ' ' ) { curlyBracketCounterClose ++ ; } if ( cha == ' ' ) { bracketCounterOpen ++ ; } if ( cha == ' ' ) { bracketCounterClose ++ ; } if ( cha == ' ' ) { parenthesisCounterOpen ++ ; } if ( cha == ' ' ) { parenthesisCounterClose ++ ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to check if all open brackets are closed [CODESPLIT] private boolean checkBracketsParenthesis ( ) { LOG . debug ( \"Check of brackets in the annotation section:\" ) ; if ( bracketCounterOpen == bracketCounterClose && parenthesisCounterOpen == parenthesisCounterClose && curlyBracketCounterOpen == curlyBracketCounterClose ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to set the details of the current connection [CODESPLIT] private void addDetails ( String str ) throws NotationException { String [ ] parts = str . split ( \"-\" ) ; /* MonomerUnit */ sourceUnit = parts [ 0 ] . split ( \":\" ) [ 0 ] . toUpperCase ( ) ; targetUnit = parts [ 1 ] . split ( \":\" ) [ 0 ] . toUpperCase ( ) ; /* R-group */ rGroupSource = parts [ 0 ] . split ( \":\" ) [ 1 ] ; rGroupTarget = parts [ 1 ] . split ( \":\" ) [ 1 ] ; Pattern r = Pattern . compile ( \"R\\\\d\" , Pattern . CASE_INSENSITIVE ) ; Pattern pair = Pattern . compile ( \"pair\" , Pattern . CASE_INSENSITIVE ) ; Matcher mR = r . matcher ( rGroupSource ) ; Matcher mPair = pair . matcher ( rGroupTarget ) ; if ( mR . matches ( ) ) { rGroupSource = rGroupSource . toUpperCase ( ) ; } else { rGroupSource = rGroupSource . toLowerCase ( ) ; } if ( mPair . matches ( ) ) { rGroupTarget = rGroupTarget . toLowerCase ( ) ; } else { rGroupTarget = rGroupTarget . toUpperCase ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get a valid HELM2 of the connection notation [CODESPLIT] public String toHELM2 ( ) { if ( isAnnotationTrue ( ) ) { return sourceId . getId ( ) + \",\" + targetId . getId ( ) + \",\" + sourceUnit + \":\" + rGroupSource + \"-\" + targetUnit + \":\" + rGroupTarget + \"\\\"\" + annotation + \"\\\"\" ; } else { return sourceId . getId ( ) + \",\" + targetId . getId ( ) + \",\" + sourceUnit + \":\" + rGroupSource + \"-\" + targetUnit + \":\" + rGroupTarget ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to add a single element to the group [CODESPLIT] public void addElement ( String str , String type , double one , double two , boolean interval , boolean isDefault ) throws NotationException { this . elements . add ( ValidationMethod . decideWhichMonomerNotationInGroup ( str , type , one , two , interval , isDefault ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws ConnectionSectionException { /* new connection is starting */ if ( cha == ' ' ) { LOG . info ( \"A new connection is starting:\" ) ; _parser . setState ( new ConnectionsParser ( _parser ) ) ; } /* grouping section is starting */ else if ( cha == ' ' ) { LOG . info ( \"Transition to group section\" ) ; LOG . info ( \"Group section is starting:\" ) ; _parser . setState ( new GroupingParser ( _parser ) ) ; } /* invalid character */ else { LOG . error ( \"Invalid character after inline annotation in connection section: \" + cha ) ; throw new ConnectionSectionException ( \"Invalid character after inline annotation in connection section: \" + cha ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws SimplePolymerSectionException { /* repeating information is finished */ if ( cha == ' ' ) { if ( _parser . checkRepeating ( repeating ) ) { String [ ] range = repeating . split ( \"-\" ) ; int first = Integer . parseInt ( range [ 0 ] ) ; if ( range . length > 1 ) { int second = Integer . parseInt ( range [ 1 ] ) ; /* range is wrong */ if ( second - first <= 0 ) { LOG . error ( \"Information about repeating is wrong: \" + repeating ) ; throw new SimplePolymerSectionException ( \"Information about repeating is wrong: \" + repeating ) ; } else { LOG . info ( \"Monomer unit is repeated:\" ) ; _parser . notationContainer . getCurrentPolymer ( ) . getPolymerElements ( ) . getCurrentMonomerNotation ( ) . setCount ( repeating ) ; _parser . setState ( new BetweenMonomerParser ( _parser ) ) ; } } else { LOG . info ( \"Monomer unit is repeated:\" ) ; _parser . notationContainer . getCurrentPolymer ( ) . getPolymerElements ( ) . getCurrentMonomerNotation ( ) . setCount ( repeating ) ; _parser . setState ( new BetweenMonomerParser ( _parser ) ) ; } } else { LOG . error ( \"Information about repeating is wrong: \" + repeating ) ; throw new SimplePolymerSectionException ( \"Information about repeating is wrong: \" + repeating ) ; } } /* add characters to repeating information */ else { repeating += cha ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main method to run a single HELM2Parser from the command line [CODESPLIT] public static void main ( String [ ] args ) throws ParseException , ExceptionState , IOException { /* options for the program */ Options options = new Options ( ) ; /* add helm string */ options . addOption ( \"inputHELM\" , true , \"HELM1 or HELM2 string in a file\" ) ; /* add output option */ options . addOption ( \"output\" , true , \"output can be in JSON- or HELM2-format\" ) ; /* add translate option */ options . addOption ( \"translate\" , false , \"translate HELM1 to HELM2\" ) ; CommandLineParser parameter = new DefaultParser ( ) ; try { CommandLine cmd = parameter . parse ( options , args ) ; String filename = cmd . getOptionValue ( \"inputHELM\" ) ; ParserHELM2 parser = new ParserHELM2 ( ) ; FileReader in = new FileReader ( filename ) ; BufferedReader br = new BufferedReader ( in ) ; String line ; String helm ; try { while ( ( line = br . readLine ( ) ) != null ) { helm = line ; /* HELM1 notation has to be translated into HELM2 */ if ( cmd . hasOption ( \"translate\" ) ) { ConverterHELM1ToHELM2 converter = new ConverterHELM1ToHELM2 ( ) ; helm = converter . doConvert ( helm ) ; LOG . info ( \"HELM1 is translated to HELM2\" ) ; } parser . parse ( helm ) ; /* There are two different output options */ String output = \"\" ; if ( cmd . getOptionValue ( \"output\" ) . equals ( \"HELM2\" ) ) { output = parser . getHELM2Notation ( ) . toHELM2 ( ) ; } else if ( cmd . getOptionValue ( \"output\" ) . equals ( \"JSON\" ) ) { output = parser . getJSON ( ) ; } System . out . println ( output ) ; } } finally { br . close ( ) ; } } catch ( NullPointerException e ) { System . out . println ( \"Please call the program with the following arguments: \" + \"\\n\" + \"-inputHELM  <\" + options . getOption ( \"inputHELM\" ) . getDescription ( ) + \">\\n\" + \"-output <\" + options . getOption ( \"output\" ) . getDescription ( ) + \">\\n-translate(optional) <\" + options . getOption ( \"translate\" ) . getDescription ( ) + \">\" ) ; } catch ( ParseException exp ) { System . out . println ( \"Unexpected exception: \" + exp . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws SimplePolymerSectionException , NotationException { /* simple polymer notation is finished; can also be empty */ if ( cha == ' ' && checkBracketsParenthesis ( ) ) { // initialize object - normal monomer type\r if ( ! ( monomer . equals ( \"\" ) ) ) { LOG . info ( \"Monomer unit is read:\" ) ; _parser . notationContainer . getCurrentPolymer ( ) . getPolymerElements ( ) . addMonomerNotation ( monomer ) ; _parser . setState ( new BetweenParser ( _parser ) ) ; } else { throw new SimplePolymerSectionException ( \"Monomer unit is missing: \" ) ; } } else if ( cha == ' ' && checkBracketsParenthesis ( ) ) { /*\r\n       * a new monomer unit is starting. This is only valid for peptide and rna\r\n       * not for chem and blob\r\n       */ if ( monomer != \"\" ) { if ( _parser . isPeptideOrRna ( ) ) { LOG . info ( \"Monomer unit is read: \" + monomer ) ; LOG . info ( \"New monomer unit is starting:\" ) ; _parser . notationContainer . getCurrentPolymer ( ) . getPolymerElements ( ) . addMonomerNotation ( monomer ) ; _parser . setState ( new SimplePolymersNotationParser ( _parser ) ) ; } else { LOG . error ( \"Only one monomer unit is allowed: \" + monomer ) ; throw new SimplePolymerSectionException ( \"Only one monomer unit is allowed: \" + monomer ) ; } } else { LOG . error ( \"Monomer unit is missing: \" + monomer ) ; throw new SimplePolymerSectionException ( \"Monomer unit is missing: \" + monomer ) ; } } /* an additional annotation is given */ else if ( cha == ' ' && checkBracketsParenthesis ( ) ) { if ( monomer != \"\" ) { LOG . info ( \"Monomer unit is read: \" + monomer ) ; LOG . info ( \"Annotation for monomer unit is starting:\" ) ; _parser . notationContainer . getCurrentPolymer ( ) . getPolymerElements ( ) . addMonomerNotation ( monomer ) ; _parser . setState ( new InlineAnnotationsParser ( _parser , 11 ) ) ; } else { LOG . error ( \"Monomer unit is missing:\" ) ; throw new SimplePolymerSectionException ( \"Monomer unit is missing:\" ) ; } } else if ( cha == ' ' && checkBracketsParenthesis ( ) ) { /*\r\n       * the monomer unit is being repeated. This is only valid for peptide and\r\n       * rna not for chem and blob\r\n       */ if ( monomer != \"\" ) { if ( _parser . isPeptideOrRna ( ) ) { LOG . info ( \"Monomer unit is read: \" + monomer ) ; _parser . notationContainer . getCurrentPolymer ( ) . getPolymerElements ( ) . addMonomerNotation ( monomer ) ; _parser . setState ( new RepeatingMonomerParser ( _parser ) ) ; } else { LOG . error ( \"Monomer unit shall be not repeated: \" ) ; throw new SimplePolymerSectionException ( \"Monomer unit shall be not repeated: \" ) ; } } else { LOG . error ( \"Monomer unit is missing\" ) ; throw new SimplePolymerSectionException ( \"Monomer unit is missing\" ) ; } } /* check all brackets */ else if ( cha == ' ' || cha == ' ' || cha == ' ' || cha == ' ' ) { monomer += cha ; if ( cha == ' ' ) { bracketCounterOpen += 1 ; } else if ( cha == ' ' ) { bracketCounterClose += 1 ; } else if ( cha == ' ' ) { parenthesisCounterOpen += 1 ; } else { parenthesisCounterClose += 1 ; } } /* add characters */ else { monomer += cha ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to validate the polymer id in the simple polymer section the id can be peptide rna chem or blob [CODESPLIT] public boolean checkPolymerId ( String polymerId ) { LOG . debug ( \"Validation of polymerID: \" + polymerId ) ; String pattern = \"PEPTIDE[1-9][0-9]*|RNA[1-9][0-9]*|CHEM[1-9][0-9]*|BLOB[1-9][0-9]*\" ; Pattern p = Pattern . compile ( pattern , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( polymerId ) ; if ( m . matches ( ) ) { LOG . debug ( \"PolymerID is valid: \" + polymerId ) ; return true ; } LOG . debug ( \"PolymerID is not valid: \" + polymerId ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to validate the polymer id in the connection section the id can be peptide rna chem or blob the ratio + range was also included the ambiguity is also proven [CODESPLIT] public boolean checkPolymeridConnection ( String polymerId ) { LOG . debug ( \"Validation of polymerID in the connection section:\" ) ; String ratio = \"(:[1-9][0-9]*(\\\\.[0-9]+)?)?\" ; String id = \"(PEPTIDE[1-9][0-9]*|RNA[1-9][0-9]*|CHEM[1-9][0-9]*|BLOB[1-9][0-9]*|G[1-9][0-9]*)\" ; String pattern = \"(\\\\(\" + id + ratio + \"(,\" + id + ratio + \")+\\\\)\" + ratio + \"|\" + id + ratio + \")\" ; Pattern p = Pattern . compile ( pattern , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( polymerId ) ; if ( m . matches ( ) ) { LOG . debug ( \"PolymerID in the connection section is valid:\" ) ; return true ; } LOG . debug ( \"PolymerID in the connection section is not valid: \" + polymerId ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to validate the details about the connections ; hydrogen bonds are here included [CODESPLIT] public boolean checkDetailsConnections ( String d ) { LOG . debug ( \"Validation of connection's details:\" ) ; String group = \"\\\\((\\\\D|\\\\d)((,|\\\\+)(\\\\D|\\\\d))+\\\\)\" ; String partOne = \"([1-9][0-9]*|\\\\D|\\\\?|\" + group + \")\" ; String partTwo = \"(R[1-9][0-9]*+|\\\\?)\" ; String element = partOne + \":\" + partTwo ; String patternConnection = element + \"-\" + element ; String hydrogenBondPartner = partOne + \":pair\" ; String hydrogenBondPattern = hydrogenBondPartner + \"-\" + hydrogenBondPartner ; Pattern pConnection = Pattern . compile ( patternConnection , Pattern . CASE_INSENSITIVE ) ; Matcher mConnection = pConnection . matcher ( d ) ; Pattern pHydrogen = Pattern . compile ( hydrogenBondPattern , Pattern . CASE_INSENSITIVE ) ; Matcher mHydrogen = pHydrogen . matcher ( d ) ; if ( mConnection . matches ( ) || mHydrogen . matches ( ) ) { LOG . debug ( \"Connection's details are valid:\" ) ; return true ; } LOG . debug ( \"Connection's details are not valid: \" + d ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to validate the group id [CODESPLIT] public boolean checkGroupId ( String d ) { Pattern p = Pattern . compile ( \"G[1-9][0-9]*\" , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( d ) ; LOG . debug ( \"Validation of groupID:\" ) ; if ( m . matches ( ) ) { LOG . debug ( \"GroupID is valid:\" ) ; return true ; } LOG . debug ( \"GroupID is not valid:\" ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to validate the details about the group information ; this part can be separated after + to get the id for each single group element : to get the ratio for each single group element [CODESPLIT] public boolean checkDetailsGroup ( String d ) { LOG . debug ( \"Validation of group's details:\" ) ; String id = \"(PEPTIDE[1-9][0-9]*+|RNA[1-9][0-9]*|CHEM[1-9][0-9]*|BLOB[1-9][0-9]*|G[1-9][0-9]*)\" ; String number = \"[1-9][0-9]*(\\\\.[0-9]+)?\" ; String ratio = number + \"(-\" + number + \")?\" ; String pattern = id + \"(:\" + ratio + \")?((\\\\+|,)\" + id + \"(:\" + ratio + \")?)+\" ; Pattern p = Pattern . compile ( pattern , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( d ) ; if ( m . matches ( ) ) { LOG . debug ( \"Group's details are valid:\" ) ; return true ; } LOG . debug ( \"Group's details are not valid: \" + d ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to validate the repeating section it can be a single number or a range [CODESPLIT] public boolean checkRepeating ( String str ) { String pattern = \"\\\\d+|\\\\d+-\\\\d+\" ; if ( str . matches ( pattern ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to check if the last added polymer element is a peptide or a rna [CODESPLIT] public boolean isPeptideOrRna ( ) throws SimplePolymerSectionException { if ( polymerElements . size ( ) >= 1 ) { if ( polymerElements . get ( polymerElements . size ( ) - 1 ) . matches ( \"(PEPTIDE[1-9][0-9]*+|RNA[1-9][0-9]*)\" ) ) { return true ; } return false ; } else { throw new SimplePolymerSectionException ( \"No Polymer Id is found\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate a JSON - Object from the NotationContainer [CODESPLIT] protected String toJSON ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; try { String jsonINString = mapper . writeValueAsString ( notationContainer ) ; jsonINString = mapper . writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( notationContainer ) ; return jsonINString ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) { if ( cha == ' ' ) { /* annotation for first section:simple polymer section */ if ( sectionCounter == 1 ) { LOG . info ( \"Add annotation to simple polymer:\" ) ; PolymerNotation current = _parser . notationContainer . getCurrentPolymer ( ) ; _parser . notationContainer . changeLastPolymerNotation ( new PolymerNotation ( current . getPolymerID ( ) , current . getPolymerElements ( ) , comment ) ) ; _parser . setState ( new BetweenParser ( _parser ) ) ; } /* annotation for second section:connection section */ else if ( sectionCounter == 2 ) { LOG . info ( \"Add annotation to connection section:\" ) ; ConnectionNotation current = _parser . notationContainer . getCurrentConnection ( ) ; _parser . notationContainer . changeConnectionNotation ( new ConnectionNotation ( current . getSourceId ( ) , current . getTargetId ( ) , current . getSourceUnit ( ) , current . getTargetUnit ( ) , current . getrGroupSource ( ) , current . getrGroupTarget ( ) , comment ) ) ; _parser . setState ( new BetweenInlineConnectionParser ( _parser ) ) ; } /* annotation for a single monomer in the first section */ else if ( sectionCounter == 11 ) { LOG . info ( \"Add annotation to a single monomer:\" ) ; _parser . notationContainer . getCurrentPolymer ( ) . getPolymerElements ( ) . getCurrentMonomerNotation ( ) . setAnnotation ( comment ) ; _parser . setState ( new BetweenInlineMonomerParser ( _parser ) ) ; } } else { comment += ( cha ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws SimplePolymerSectionException { /* a new monomer section starts */ if ( cha == ' ' ) { LOG . info ( \"new monomer unit is starting:\" ) ; _parser . setState ( new SimplePolymersNotationParser ( _parser ) ) ; } /* polymer is finished */ else if ( cha == ' ' ) { LOG . info ( \"simple polymer is read:\" ) ; _parser . setState ( new BetweenParser ( _parser ) ) ; } /* inline annotation */ else if ( cha == ' ' ) { LOG . info ( \"annotation for simple polymer is starting:\" ) ; _parser . setState ( new InlineAnnotationsParser ( _parser , 11 ) ) ; } else { LOG . error ( \"Error in the simple polymers notation section:\" ) ; throw new SimplePolymerSectionException ( \"Error in the simple polymers notation section:\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String toHELM2 ( ) { StringBuilder notation = new StringBuilder ( ) ; DecimalFormat d = new DecimalFormat ( \"#.##\" ) ; notation . append ( \"(\" ) ; for ( int i = 0 ; i < elements . size ( ) ; i ++ ) { String text = elements . get ( i ) . getMonomerNotation ( ) . getUnit ( ) ; if ( ! ( elements . get ( i ) . isDefaultValue ( ) ) ) { String value = d . format ( elements . get ( i ) . getValue ( ) . get ( 0 ) ) . replace ( ' ' , ' ' ) ; if ( elements . get ( i ) . isInterval ( ) ) { value += \"-\" + d . format ( elements . get ( i ) . getValue ( ) . get ( 1 ) ) . replace ( ' ' , ' ' ) ; } if ( value . equals ( \"-1\" ) ) { value = \"?\" ; } text += \":\" + value ; } notation . append ( text + \",\" ) ; } notation . setLength ( notation . length ( ) - 1 ) ; notation . append ( \")\" ) ; if ( ! ( isDefault ) ) { notation . append ( \"'\" + count + \"'\" ) ; } if ( isAnnotationHere ) { notation . append ( \"\\\"\" + annotation + \"\\\"\" ) ; } return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get the simple polymer type [CODESPLIT] public PolymerNotation getSimplePolymer ( String string ) { for ( PolymerNotation polymer : listOfPolymers ) { if ( polymer . getPolymerID ( ) . getId ( ) . equals ( string ) ) { return polymer ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get the current grouping notation [CODESPLIT] @ JsonIgnore public GroupingNotation getCurrentGroupingNotation ( ) { if ( listOfGroupings . size ( ) == 0 ) { return null ; } return listOfGroupings . get ( listOfGroupings . size ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate for all sections a HELM2 string [CODESPLIT] public String toHELM2 ( ) { String output = \"\" ; /* first section: simple polymer section */ output += polymerToHELM2 ( ) + \"$\" ; /* second section: connection section */ output += connectionToHELM2 ( ) + \"$\" ; /* third section: grouping section */ output += groupingToHELM2 ( ) + \"$\" ; /* fourth section: annotation section */ output += annotationToHELM2 ( ) + \"$\" ; /* add version number */ output += \"V2.0\" ; return output ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate a valid HELM2 string for the first section [CODESPLIT] public String polymerToHELM2 ( ) { StringBuilder notation = new StringBuilder ( ) ; for ( int i = 0 ; i < listOfPolymers . size ( ) ; i ++ ) { if ( listOfPolymers . get ( i ) . isAnnotationHere ( ) ) { notation . append ( listOfPolymers . get ( i ) . getPolymerID ( ) + \"{\" + listOfPolymers . get ( i ) . toHELM2 ( ) + \"}\\\"\" + listOfPolymers . get ( i ) . getAnnotation ( ) + \"\\\"|\" ) ; } else { notation . append ( listOfPolymers . get ( i ) . getPolymerID ( ) + \"{\" + listOfPolymers . get ( i ) . toHELM2 ( ) + \"}\" + \"|\" ) ; } } notation . setLength ( notation . length ( ) - 1 ) ; return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate a valid HELM2 string for the second section [CODESPLIT] public String connectionToHELM2 ( ) { if ( listOfConnections . size ( ) == 0 ) { return \"\" ; } StringBuilder notation = new StringBuilder ( ) ; for ( int i = 0 ; i < listOfConnections . size ( ) ; i ++ ) { notation . append ( listOfConnections . get ( i ) . toHELM2 ( ) + \"|\" ) ; } notation . setLength ( notation . length ( ) - 1 ) ; return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate a valid HELM2 string for the third section [CODESPLIT] public String groupingToHELM2 ( ) { if ( listOfGroupings . size ( ) == 0 ) { return \"\" ; } StringBuilder notation = new StringBuilder ( ) ; for ( int i = 0 ; i < listOfGroupings . size ( ) ; i ++ ) { notation . append ( listOfGroupings . get ( i ) . toHELM2 ( ) + \"|\" ) ; } notation . setLength ( notation . length ( ) - 1 ) ; return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate a valid HELM2 string for the fourth section [CODESPLIT] public String annotationToHELM2 ( ) { if ( ! ( annotationSection . isEmpty ( ) ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < annotationSection . size ( ) ; i ++ ) { sb . append ( annotationSection . get ( i ) . toHELM2 ( ) + \"|\" ) ; } sb . setLength ( sb . length ( ) - 1 ) ; return sb . toString ( ) ; } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get the ID s from all polymers and groups [CODESPLIT] @ JsonIgnore public List < String > getPolymerAndGroupingIDs ( ) { List < String > listOfIDs = new ArrayList < String > ( ) ; for ( PolymerNotation polymer : listOfPolymers ) { listOfIDs . add ( polymer . getPolymerID ( ) . getId ( ) ) ; } for ( GroupingNotation grouping : listOfGroupings ) { listOfIDs . add ( grouping . getGroupID ( ) . getId ( ) ) ; } return listOfIDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get the ID s from all polymers [CODESPLIT] @ JsonIgnore public List < String > getPolymerIDs ( ) { List < String > listOfIDs = new ArrayList < String > ( ) ; for ( PolymerNotation polymer : listOfPolymers ) { listOfIDs . add ( polymer . getPolymerID ( ) . getId ( ) ) ; } return listOfIDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get the ID s from all polymers [CODESPLIT] @ JsonIgnore public List < String > getGroupIDs ( ) { List < String > listOfIDs = new ArrayList < String > ( ) ; for ( GroupingNotation grouping : listOfGroupings ) { listOfIDs . add ( grouping . getGroupID ( ) . getId ( ) ) ; } return listOfIDs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get a specific polymer by its id [CODESPLIT] @ JsonIgnore public PolymerNotation getPolymerNotation ( String id ) { for ( PolymerNotation polymer : listOfPolymers ) { if ( polymer . getPolymerID ( ) . getId ( ) . equals ( id ) ) { return polymer ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to generate the right PolymerElements in the case of Chem and Blob only one Monomer is allowed [CODESPLIT] private void setPolymerElements ( ) { if ( polymerID instanceof RNAEntity || polymerID instanceof PeptideEntity ) { this . polymerElements = new PolymerListElements ( polymerID ) ; } else { this . polymerElements = new PolymerSingleElements ( polymerID ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public void doAction ( char cha ) throws SimplePolymerSectionException , NotationException { /* list of simple polymers is finished */ if ( cha == ' ' ) { // id has to be empty\r if ( polymerId == \"\" ) { if ( ! ( _parser . isEmpty ( ) ) ) { LOG . info ( \"Simple polymer section is finished:\" ) ; LOG . info ( \"Transition to connection section:\" ) ; _parser . setState ( new ConnectionsParser ( _parser ) ) ; } else { LOG . error ( \"Simple polymer ID has to be defined:\" ) ; throw new SimplePolymerSectionException ( \"A simple polymer has to be defined\" ) ; } } else { LOG . error ( \"Incorrect input in the simple polymer section:\" ) ; throw new SimplePolymerSectionException ( \"Incorrect input in the simple polymer section:\" ) ; } } /* simple polymer notation is starting */ else if ( cha == ' ' ) { if ( ( _parser . checkPolymerId ( polymerId ) ) && polymerId != \"\" ) { LOG . info ( \"Simple polymer ID is read:\" ) ; _parser . notationContainer . addPolymer ( new PolymerNotation ( polymerId ) ) ; _parser . addPolymer ( polymerId ) ; _parser . setState ( new SimplePolymersNotationParser ( _parser ) ) ; } else { LOG . error ( \"Polymer ID is not correct: \" + polymerId ) ; throw new SimplePolymerSectionException ( \"Polymer ID is not correct: \" + polymerId ) ; } } /* add characters to polymer id */ else { polymerId += cha ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String toHELM2 ( ) { DecimalFormat d = new DecimalFormat ( \"#.##\" ) ; StringBuilder notation = new StringBuilder ( ) ; for ( GroupingElement groupingElement : elements ) { if ( ! ( groupingElement . isDefaultValue ( ) ) ) { String value = d . format ( groupingElement . getValue ( ) . get ( 0 ) ) . replace ( ' ' , ' ' ) ; if ( groupingElement . getValue ( ) . size ( ) > 1 ) { value += \"-\" + d . format ( groupingElement . getValue ( ) . get ( 1 ) ) . replace ( ' ' , ' ' ) ; } notation . append ( groupingElement . getID ( ) + \":\" + value + \"+\" ) ; } else { notation . append ( groupingElement . getID ( ) + \"+\" ) ; } } notation . setLength ( notation . length ( ) - 1 ) ; return notation . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to convert the given string into the HELM2 format [CODESPLIT] public String doConvert ( String str ) { //check for just missing V2.0\r ParserHELM2 parser = new ParserHELM2 ( ) ; try { parser . parse ( str + \"V2.0\" ) ; return str + \"V2.0\" ; } catch ( Exception e ) { /* Use String Builder */ /* simple add character -> split works then */ String helm1 = str + \"f\" ; StringBuilder helm2 = new StringBuilder ( ) ; String [ ] sections = helm1 . split ( \"}\\\\$\" ) ; /* Section 1 is accepted in full, no changes necessary, Section 1 has to be there */ helm2 . append ( sections [ 0 ] + \"}$\" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 1 ; i < sections . length ; i ++ ) { sb . append ( sections [ i ] + \"}$\" ) ; } helm1 = \"$\" + sb . toString ( ) ; sections = helm1 . split ( \"\\\\$\" ) ; /*\r\n     * Section 2 connection section; section 3 is added to the second section,\r\n     * Section 2 is not necessary, is this section really there\r\n     */ if ( sections . length >= 2 ) { if ( ! ( sections [ 1 ] . isEmpty ( ) ) ) { helm2 . append ( sections [ 1 ] ) ; } } /* Add hydrogen bonds to the connection section */ if ( sections . length >= 3 ) { if ( ! ( sections [ 2 ] . isEmpty ( ) ) ) { if ( ! ( sections [ 1 ] . isEmpty ( ) ) ) { helm2 . append ( \"|\" + sections [ 2 ] ) ; } else { helm2 . append ( sections [ 2 ] ) ; } } /*Group section*/ helm2 . append ( \"$\" ) ; helm2 . append ( \"$\" ) ; /*Add annotation to the annotation section*/ if ( sections . length >= 4 ) { if ( ! ( sections [ 3 ] . isEmpty ( ) ) ) { helm2 . append ( sections [ 3 ] ) ; } } } /* Add version number to indicate HELM2 notation */ helm2 . append ( \"$V2.0\" ) ; return helm2 . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to add annotation to this monomer [CODESPLIT] public void setAnnotation ( String str ) { if ( str != null ) { annotation = str ; isAnnotationHere = true ; } else { annotation = null ; isAnnotationHere = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to change the default count of one to the user - defined [CODESPLIT] public void setCount ( String str ) { isDefault = false ; if ( str . equals ( \"1\" ) ) { isDefault = true ; } count = str ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to decide which of the MonomerNotation classes should be initialized [CODESPLIT] public static MonomerNotation decideWhichMonomerNotation ( String str , String type ) throws NotationException { MonomerNotation mon ; /* group ? */ if ( str . startsWith ( \"(\" ) && str . endsWith ( \")\" ) ) { String str2 = str . substring ( 1 , str . length ( ) - 1 ) ; Pattern patternAND = Pattern . compile ( \"\\\\+\" ) ; Pattern patternOR = Pattern . compile ( \",\" ) ; /* Mixture of elements */ if ( patternAND . matcher ( str ) . find ( ) ) { mon = new MonomerNotationGroupMixture ( str2 , type ) ; } /* or - groups */ else if ( patternOR . matcher ( str ) . find ( ) ) { mon = new MonomerNotationGroupOr ( str2 , type ) ; } else { if ( str . contains ( \".\" ) ) { mon = new MonomerNotationList ( str2 , type ) ; } else { /* monomer unit is just in brackets */ if ( type == \"RNA\" ) { mon = new MonomerNotationUnitRNA ( str2 , type ) ; } else { if ( str2 . length ( ) > 1 ) { if ( ! ( str2 . startsWith ( \"[\" ) && str2 . endsWith ( \"]\" ) ) ) { throw new NotationException ( \"Monomers have to be in brackets: \" + str ) ; } } mon = new MonomerNotationUnit ( str2 , type ) ; } } } } else { if ( type == \"RNA\" ) { // if (str.startsWith(\"[\") && str.endsWith(\"]\")) {\r // mon = new MonomerNotationUnitRNA(str, type);\r // }\r mon = new MonomerNotationUnitRNA ( str , type ) ; } else if ( type != \"BLOB\" ) { if ( str . length ( ) > 1 ) { if ( ! ( str . startsWith ( \"[\" ) && str . endsWith ( \"]\" ) ) ) { throw new NotationException ( \"Monomers have to be in brackets: \" + str ) ; } } mon = new MonomerNotationUnit ( str , type ) ; } else { mon = new MonomerNotationUnit ( str , type ) ; } } return mon ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to decide which of the two Constructors of MonomerNotationGroupElement should be called [CODESPLIT] public static MonomerNotationGroupElement decideWhichMonomerNotationInGroup ( String str , String type , double one , double two , boolean interval , boolean isDefault ) throws NotationException { MonomerNotation element ; element = decideWhichMonomerNotation ( str , type ) ; if ( interval ) { return new MonomerNotationGroupElement ( element , one , two ) ; } else { return new MonomerNotationGroupElement ( element , one , isDefault ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to decide which of the Entities classes should be initialized [CODESPLIT] public static HELMEntity decideWhichEntity ( String str ) throws NotationException { HELMEntity item ; if ( str . toUpperCase ( ) . matches ( \"PEPTIDE[1-9][0-9]*\" ) ) { item = new PeptideEntity ( str . toUpperCase ( ) ) ; } else if ( str . toUpperCase ( ) . matches ( \"RNA[1-9][0-9]*\" ) ) { item = new RNAEntity ( str . toUpperCase ( ) ) ; } else if ( str . toUpperCase ( ) . matches ( \"BLOB[1-9][0-9]*\" ) ) { item = new BlobEntity ( str . toUpperCase ( ) ) ; } else if ( str . toUpperCase ( ) . matches ( \"CHEM[1-9][0-9]*\" ) ) { item = new ChemEntity ( str . toUpperCase ( ) ) ; } else if ( str . toUpperCase ( ) . matches ( \"G[1-9][0-9]*\" ) ) { item = new GroupEntity ( str . toUpperCase ( ) ) ; } else { throw new NotationException ( \"ID is wrong: \" + str ) ; } return item ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws ConnectionSectionException , NotationException { /* a new connection is starting */ if ( cha == ' ' ) { if ( _parser . checkDetailsConnections ( details ) ) { LOG . info ( \"A new connection is starting:\" ) ; ConnectionNotation current = _parser . notationContainer . getCurrentConnection ( ) ; _parser . notationContainer . changeConnectionNotation ( new ConnectionNotation ( current . getSourceId ( ) , current . getTargetId ( ) , details ) ) ; _parser . setState ( new ConnectionsParser ( _parser ) ) ; } else { LOG . error ( \"Details about the connection are not corret: \" + details ) ; throw new ConnectionSectionException ( \"Details about the connection are not correct: \" + details ) ; } } /* connection section is finished */ else if ( cha == ' ' ) { if ( _parser . checkDetailsConnections ( details ) ) { LOG . info ( \"Connection section is finished:\" ) ; ConnectionNotation current = _parser . notationContainer . getCurrentConnection ( ) ; _parser . notationContainer . changeConnectionNotation ( new ConnectionNotation ( current . getSourceId ( ) , current . getTargetId ( ) , details ) ) ; LOG . info ( \"Transition to group section\" ) ; _parser . setState ( new GroupingParser ( _parser ) ) ; } else { throw new ConnectionSectionException ( \"Details about the connection are not correct: \" + details ) ; } } /* start of an annotation */ else if ( cha == ' ' ) { if ( _parser . checkDetailsConnections ( details ) ) { LOG . info ( \"Add annotation to connection:\" ) ; ConnectionNotation current = _parser . notationContainer . getCurrentConnection ( ) ; _parser . notationContainer . changeConnectionNotation ( new ConnectionNotation ( current . getSourceId ( ) , current . getTargetId ( ) , details ) ) ; _parser . setState ( new InlineAnnotationsParser ( _parser , 2 ) ) ; } else { LOG . error ( \"Details about the connection are not corret: \" + details ) ; throw new ConnectionSectionException ( \"Details about the connection are not correct: \" + details ) ; } } /* add characters to connection description */ else { details += cha ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public void doAction ( char cha ) throws GroupingSectionException , NotationException { /*\r\n     * group section is finished: section was empty: annotation section starts\r\n     */ if ( cha == ' ' ) { /* no details */ if ( groupId == \"\" && _parser . notationContainer . getListOfGroupings ( ) . size ( ) == 0 ) { LOG . info ( \"Group section is empty:\" ) ; LOG . info ( \"Transition to annotation section:\" ) ; _parser . setState ( new AnnotationsParser ( _parser ) ) ; } else { throw new GroupingSectionException ( \"Missing details about the group: \" + groupId ) ; } } /* detailed information about the group is starting */ else if ( cha == ' ' ) { if ( _parser . checkGroupId ( groupId ) ) { LOG . info ( \"Group ID is read:\" ) ; _parser . notationContainer . addGrouping ( new GroupingNotation ( groupId ) ) ; _parser . setState ( new GroupingDetailedInformationParser ( _parser ) ) ; } else { LOG . error ( \"Invalid group ID: \" + groupId ) ; throw new GroupingSectionException ( \"Invalid group Id: \" + groupId ) ; } } /* add characters to the group id */ else { groupId += cha ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to get the ratio or the interval of this group in the case of an interval it returns a list of two values [CODESPLIT] public List < Double > getValue ( ) { if ( this . isInterval ) { return new ArrayList < Double > ( Arrays . asList ( numberOne , numberTwo ) ) ; } else { return new ArrayList < Double > ( Arrays . asList ( numberOne ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to parse the given HELM2 string in the case of an invalid HELM2 notation exception is thrown [CODESPLIT] public void parse ( String test ) throws ExceptionState { parser = new StateMachineParser ( ) ; test = test . trim ( ) ; if ( test . substring ( test . length ( ) - 4 ) . matches ( \"V2\\\\.0\" ) || test . substring ( test . length ( ) - 4 ) . matches ( \"v2\\\\.0\" ) ) { for ( int i = 0 ; i < test . length ( ) - 4 ; i ++ ) { parser . doAction ( test . charAt ( i ) ) ; } if ( ! ( parser . getState ( ) instanceof FinalState ) ) { LOG . error ( \"Invalid input: Final State was not reached:\" ) ; throw new FinalStateException ( \"Invalid input: Final State was not reached\" ) ; } } else { LOG . error ( \"Invalid input: HELM2 standard is missing:\" ) ; throw new NotValidHELM2Exception ( \"Invalid input: HELM2 standard is missing\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public void doAction ( char cha ) throws GroupingSectionException , NotationException { /*\r\n     * detailed information about the group is finished: annotation section\r\n     * starts\r\n     */ if ( cha == ' ' ) { if ( _parser . checkDetailsGroup ( details ) ) { LOG . info ( \"Group description is finished:\" ) ; LOG . info ( \"Transition to annotation section:\" ) ; GroupingNotation current = _parser . notationContainer . getCurrentGroupingNotation ( ) ; _parser . notationContainer . changeLastGroupingNotation ( new GroupingNotation ( current . getGroupID ( ) , details ) ) ; _parser . setState ( new BetweenGroupingParser ( _parser ) ) ; } else { LOG . error ( \"Group information is wrong: \" + details ) ; throw new GroupingSectionException ( \"Group information is wrong: \" + details ) ; } } /* add characters to the details */ else { details += cha ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public void addMonomerNotation ( String str ) throws SimplePolymerSectionException , NotationException { if ( this . listMonomerNotations . size ( ) < 1 ) { this . listMonomerNotations . add ( ValidationMethod . decideWhichMonomerNotation ( str , entity . getType ( ) ) ) ; } else { throw new SimplePolymerSectionException ( \"Only one Monomer unit is allowed for CHEM and BLOB\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to set for each nucleotide the sugar the base and the phosphat [CODESPLIT] private void setRNAContents ( String str ) throws NotationException { /* Nucleotide with all contents */ String [ ] list ; // if (str.contains(\"(\")) {\r List < String > items = extractContents ( str ) ; for ( String item : items ) { if ( item . length ( ) > 1 ) { if ( ! ( item . startsWith ( \"[\" ) && item . endsWith ( \"]\" ) ) ) { throw new NotationException ( \"Monomers have to be in brackets \" + item ) ; } } contents . add ( new MonomerNotationUnit ( item , type ) ) ; } // } /* nucleotide contains no base, but a modified sugar or phosphat */\r // else if (str.contains(\"[\")) {\r // if (str.startsWith(\"[\")) {\r // str = str.replace(\"]\", \"]$\");\r // } else {\r // str = str.replace(\"[\", \"$[\");\r // }\r // list = str.split(\"\\\\$\");\r // for (int i = 0; i < list.length; i++) {\r // contents.add(new MonomerNotationUnit(list[i], type));\r // }\r // } /* nucleotide contains only standard sugar and/or phosphat */ else {\r // for (int i = 0; i < str.length(); i++) {\r // contents.add(new MonomerNotationUnit(Character.toString(str.charAt(i)),\r // type));\r // }\r // }\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws ExceptionState { /*\r\n     * third part of the connection is starting. It contains information about\r\n     * the connection in detail\r\n     */ if ( cha == ' ' ) { if ( _parser . checkPolymeridConnection ( targetpolymerid ) ) { LOG . info ( \"Target polmyer ID is read:\" ) ; ConnectionNotation current = _parser . notationContainer . getCurrentConnection ( ) ; _parser . notationContainer . changeConnectionNotation ( new ConnectionNotation ( current . getSourceId ( ) , targetpolymerid ) ) ; _parser . setState ( new ConnectionsDetailsParser ( _parser ) ) ; } else { LOG . error ( \"Target polymer ID is not correct in the connection section: \" + targetpolymerid ) ; throw new ConnectionSectionException ( \"Target polymer ID is not correct in the connection section: \" + targetpolymerid ) ; } } /* Read the id of the target polymer id */ else { targetpolymerid += cha ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws SimplePolymerSectionException { /* an additional annotation is starting */ if ( cha == ' ' ) { LOG . info ( \"Annotation for simple polymer is starting:\" ) ; _parser . setState ( new InlineAnnotationsParser ( _parser , 1 ) ) ; } /* a new unit is starting */ else if ( cha == ' ' ) { LOG . info ( \"One simple polymer is finished:\" ) ; LOG . info ( \"New simple polymer is starting:\" ) ; _parser . setState ( new SimplePolymersParser ( _parser ) ) ; } /* a new section is starting */ else if ( cha == ' ' ) { LOG . info ( \"One simple polymer is finished:\" ) ; LOG . info ( \"Simple polymer section is finished:\" ) ; LOG . info ( \"Transition to connection section:\" ) ; _parser . setState ( new ConnectionsParser ( _parser ) ) ; } else { LOG . error ( \"Invalid syntax in simple polymer section: \" + cha ) ; throw new SimplePolymerSectionException ( \"Invalid syntax in simple polymer section: \" + cha ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public String toHELM2 ( ) { String text = unit ; if ( isDefault == false ) { if ( unit . length ( ) > 1 ) { text = \"(\" + unit + \")\" ; } text += \"'\" + count + \"'\" ; } if ( isAnnotationHere ) { text += \"\\\"\" + annotation + \"\\\"\" ; } return text ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void doAction ( char cha ) throws GroupingSectionException { /* a new group is starting */ if ( cha == ' ' ) { LOG . info ( \"A new group is starting;\" ) ; _parser . setState ( new GroupingParser ( _parser ) ) ; } /* group section is finished: start of the annotation section */ else if ( cha == ' ' ) { LOG . info ( \"Group section is finished:\" ) ; LOG . info ( \"Transition to annotation section:\" ) ; _parser . setState ( new AnnotationsParser ( _parser ) ) ; } /* add characters to the grouping section */ else { LOG . error ( \"Group section is not valid: \" + cha ) ; throw new GroupingSectionException ( \"Group section is not valid: \" + cha ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called from within the constructor to initialize the form . WARNING : Do NOT modify this code . The content of this method is always regenerated by the Form Editor . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private void initComponents ( ) { jScrollPane1 = new javax . swing . JScrollPane ( ) ; input = new javax . swing . JTextArea ( ) ; inputLabel = new javax . swing . JLabel ( ) ; outputLabel = new javax . swing . JLabel ( ) ; jScrollPane2 = new javax . swing . JScrollPane ( ) ; output = new javax . swing . JTextArea ( ) ; jRadioHELM = new javax . swing . JRadioButton ( ) ; jRadioJSON = new javax . swing . JRadioButton ( ) ; jButton1 = new javax . swing . JButton ( ) ; bg = new javax . swing . ButtonGroup ( ) ; setDefaultCloseOperation ( javax . swing . WindowConstants . EXIT_ON_CLOSE ) ; setTitle ( \"HELMNotationParser\" ) ; input . setColumns ( 20 ) ; input . setRows ( 5 ) ; jScrollPane1 . setViewportView ( input ) ; inputLabel . setText ( \"HELM-Input:\" ) ; inputLabel . setFont ( new Font ( \"Arial\" , Font . BOLD , 20 ) ) ; inputLabel . setHorizontalAlignment ( JLabel . CENTER ) ; inputLabel . setVerticalAlignment ( JLabel . CENTER ) ; outputLabel . setText ( \"Output:\" ) ; outputLabel . setFont ( new Font ( \"Arial\" , Font . BOLD , 20 ) ) ; outputLabel . setHorizontalAlignment ( JLabel . CENTER ) ; outputLabel . setVerticalAlignment ( JLabel . CENTER ) ; output . setColumns ( 20 ) ; output . setRows ( 5 ) ; jScrollPane2 . setViewportView ( output ) ; jRadioHELM . setText ( \"HELM2\" ) ; jRadioHELM . addActionListener ( new java . awt . event . ActionListener ( ) { @ Override public void actionPerformed ( java . awt . event . ActionEvent evt ) { jRadioButton1ActionPerformed ( evt ) ; } } ) ; jRadioJSON . setText ( \"JSON\" ) ; jRadioJSON . addActionListener ( new java . awt . event . ActionListener ( ) { @ Override public void actionPerformed ( java . awt . event . ActionEvent evt ) { jRadioButton2ActionPerformed ( evt ) ; } } ) ; bg . add ( jRadioHELM ) ; bg . add ( jRadioJSON ) ; jRadioHELM . setSelected ( true ) ; jButton1 . setText ( \"Translate\" ) ; jButton1 . addActionListener ( new java . awt . event . ActionListener ( ) { @ Override public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton1ActionPerformed ( evt ) ; } } ) ; javax . swing . GroupLayout layout = new javax . swing . GroupLayout ( getContentPane ( ) ) ; getContentPane ( ) . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING , false ) . addComponent ( inputLabel , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addComponent ( jScrollPane1 , javax . swing . GroupLayout . DEFAULT_SIZE , 438 , Short . MAX_VALUE ) ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 31 , 31 , 31 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jRadioHELM , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addComponent ( jButton1 ) . addComponent ( jRadioJSON , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addComponent ( jScrollPane2 , javax . swing . GroupLayout . PREFERRED_SIZE , 458 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) . addGroup ( javax . swing . GroupLayout . Alignment . TRAILING , layout . createSequentialGroup ( ) . addGap ( 132 , 132 , 132 ) . addComponent ( outputLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 458 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) ) . addContainerGap ( ) ) ) ; layout . setVerticalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 0 , 0 , 0 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . BASELINE ) . addComponent ( inputLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 28 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( outputLabel , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 9 , 9 , 9 ) . addComponent ( jRadioHELM ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jRadioJSON ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . UNRELATED ) . addComponent ( jButton1 ) . addContainerGap ( 778 , Short . MAX_VALUE ) ) . addComponent ( jScrollPane1 ) . addComponent ( jScrollPane2 ) ) ) ) ; pack ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "< / editor - fold > [CODESPLIT] private void jButton1ActionPerformed ( java . awt . event . ActionEvent evt ) { String helmInput = input . getText ( ) ; if ( ! ( helmInput . contains ( \"V2.0\" ) ) ) { /* Translate into HELM2-format */ helmInput = converter . doConvert ( helmInput ) ; } /* read input */ try { parser . parse ( helmInput ) ; writeOutputmessage ( ) ; } catch ( ExceptionState e ) { output . setText ( \"Invalid HELM-String (\" + e . getMessage ( ) + \")\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method to add ambiguity to the group [CODESPLIT] private void defineAmbiguity ( String a ) throws NotationException { Pattern patternAND = Pattern . compile ( \"\\\\+\" ) ; Matcher m = patternAND . matcher ( a ) ; /* mixture */ if ( m . find ( ) ) { setAmbiguity ( new GroupingMixture ( a ) ) ; } /* or case */ else { setAmbiguity ( new GroupingOr ( a ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Construct a default fraction using the default agent URL of http : // localhost : 8500 / . [CODESPLIT] @ Override public void initialize ( InitContext initContext ) { if ( initContext . projectStage ( ) . isPresent ( ) ) { try { StageConfig stageConfig = initContext . projectStage ( ) . get ( ) ; String configvalue = stageConfig . resolve ( SwarmProperties . CONSUL_URL ) . withDefault ( null ) . getValue ( ) ; this . url = configvalue != null ? new URL ( configvalue ) : DEFAULT_URL ; } catch ( MalformedURLException e ) { throw new RuntimeException ( \"Faile to resolve property 'swarm.consul.url'\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns an approximation of this thread s execution statistics for the entire period since the thread was started . Writes are done without memory barriers to minimize the performance impact of statistics gathering so some or all returned data may be arbitrarily stale and some fields may be far staler than others . For long - running pools however even approximate data may provide useful insights . Your mileage may vary however you have been warned ; - ) [CODESPLIT] AWorkerThreadStatistics getStatistics ( ) { return new AWorkerThreadStatistics ( getState ( ) , getId ( ) , stat_numTasksExecuted , stat_numSharedTasksExecuted , stat_numSteals , stat_numExceptions , stat_numParks , stat_numFalseAlarmUnparks , stat_numSharedQueueSwitches , stat_numLocalSubmits , localQueue . approximateSize ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new task to the top of the shared queue incrementing top . [CODESPLIT] @ Override public void push ( Runnable task ) { lock ( ) ; final long _base ; final long _top ; try { _base = UNSAFE . getLongVolatile ( this , OFFS_BASE ) ; _top = UNSAFE . getLongVolatile ( this , OFFS_TOP ) ; if ( _top == _base + mask ) { throw new RejectedExecutionExceptionWithoutStacktrace ( \"Shared queue overflow\" ) ; } // We hold a lock here, so there can be no concurrent modifications of 'top', and there is no need for CAS. We must however ensure that //  no concurrently reading thread sees the incremented 'top' without the task being present in the array, therefore the 'ordered' put. UNSAFE . putObjectVolatile ( tasks , taskOffset ( _top ) , task ) ; UNSAFE . putLongVolatile ( this , OFFS_TOP , _top + 1 ) ; } finally { unlock ( ) ; } pool . onAvailableTask ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a convenience factory method that extracts the list of nodes from the edges . It assumes that every node has at least one edge going from or to it . [CODESPLIT] public static < N , E extends AEdge < N > > ADiGraph < N , E > create ( Collection < E > edges ) { final Set < N > result = new HashSet <> ( ) ; for ( E edge : edges ) { result . add ( edge . getFrom ( ) ) ; result . add ( edge . getTo ( ) ) ; } return create ( result , edges ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This factory method creates a graph with the given nodes and edges . It expressly allows nodes that have no edges attached to them . [CODESPLIT] public static < N , E extends AEdge < N > > ADiGraph < N , E > create ( Collection < N > nodes , Collection < E > edges ) { final Object [ ] nodeArr = new Object [ nodes . size ( ) ] ; final AEdge [ ] edgeArr = new AEdge [ edges . size ( ) ] ; int idx = 0 ; for ( N node : nodes ) { nodeArr [ idx ] = node ; idx += 1 ; } idx = 0 ; for ( E edge : edges ) { edgeArr [ idx ] = edge ; idx += 1 ; } return new ADiGraph < N , E > ( nodeArr , edgeArr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method does the reachability analysis in a way that is useful for many other methods . [CODESPLIT] private void initPathsInternal ( ) { synchronized ( LOCK ) { if ( _incomingPathsInternal == null ) { AMap < N , AList < AEdgePath < N , E > > > incomingPaths = AHashMap . empty ( ) ; //noinspection unchecked incomingPaths = incomingPaths . withDefaultValue ( AList . nil ) ; AMap < N , AList < AEdgePath < N , E > > > outgoingPaths = AHashMap . empty ( ) ; //noinspection unchecked outgoingPaths = outgoingPaths . withDefaultValue ( AList . nil ) ; AList < AEdgePath < N , E > > cycles = AList . nil ( ) ; for ( N curNode : nodes ( ) ) { // iterate over nodes, treat 'curNode' as a target final Iterable < E > curIncoming = incomingEdges ( curNode ) ; List < AEdgePath < N , E > > unfinishedBusiness = new ArrayList <> ( ) ; for ( E incomingEdge : curIncoming ) { unfinishedBusiness . add ( AEdgePath . create ( incomingEdge ) ) ; } AList < AEdgePath < N , E > > nonCycles = AList . nil ( ) ; while ( unfinishedBusiness . size ( ) > 0 ) { final List < AEdgePath < N , E > > curBusiness = unfinishedBusiness ; for ( AEdgePath < N , E > p : unfinishedBusiness ) { if ( ! p . hasCycle ( ) || p . isMinimalCycle ( ) ) nonCycles = nonCycles . cons ( p ) ; if ( p . isMinimalCycle ( ) ) cycles = cycles . cons ( p ) ; } unfinishedBusiness = new ArrayList <> ( ) ; for ( AEdgePath < N , E > curPath : curBusiness ) { final Iterable < E > l = incomingEdges ( curPath . getFrom ( ) ) ; for ( E newEdge : l ) { final AEdgePath < N , E > pathCandidate = curPath . prepend ( newEdge ) ; if ( ! pathCandidate . hasNonMinimalCycle ( ) ) { unfinishedBusiness . add ( pathCandidate ) ; } } } } incomingPaths = incomingPaths . updated ( curNode , nonCycles ) ; for ( AEdgePath < N , E > p : nonCycles ) { outgoingPaths = outgoingPaths . updated ( p . getFrom ( ) , outgoingPaths . getRequired ( p . getFrom ( ) ) . cons ( p ) ) ; } } _incomingPathsInternal = incomingPaths ; _outgoingPathsInternal = outgoingPaths ; _cyclesInternal = cycles ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A directed graph defines a partial order through reachability and this method sorts the graph s nodes based on that partial order . [CODESPLIT] public List < N > sortedNodesByReachability ( ) throws AGraphCircularityException { if ( hasCycles ( ) ) { throw new AGraphCircularityException ( ) ; } final Object [ ] result = new Object [ nodes . length ] ; int nextIdx = 0 ; final Set < N > unprocessed = new HashSet <> ( ) ; for ( Object node : nodes ) { //noinspection unchecked unprocessed . add ( ( N ) node ) ; } //TODO Map<N,Integer> with 'remaining' incoming edges, decrement when a node is 'processed' --> JMH while ( ! unprocessed . isEmpty ( ) ) { final Set < N > nextBatch = ACollectionHelper . filter ( unprocessed , new APredicateNoThrow < N > ( ) { @ Override public boolean apply ( N n ) { for ( E e : incomingEdges ( n ) ) { if ( unprocessed . contains ( e . getFrom ( ) ) ) { return false ; } } return true ; } } ) ; unprocessed . removeAll ( nextBatch ) ; for ( N n : nextBatch ) { result [ nextIdx ] = n ; nextIdx += 1 ; } } return new ArrayIterable <> ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unbuffered output is with API . err . format () etc . [CODESPLIT] private static PrintStream unbuffered ( final PrintStream stream ) { try { return new PrintStream ( stream , true , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { return new PrintStream ( stream , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes an object method to a service name pattern . [CODESPLIT] public void subscribe ( final String pattern , final Object instance , final String methodName ) throws NoSuchMethodException { this . subscribe ( pattern , new FunctionObject9 ( instance , methodName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes a static method to a service name pattern . [CODESPLIT] public void subscribe ( final String pattern , final Class < ? > clazz , final String methodName ) throws NoSuchMethodException { this . subscribe ( pattern , new FunctionObject9 ( this , clazz , methodName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Subscribes an object method to a service name pattern . [CODESPLIT] public void subscribe ( final String pattern , final FunctionInterface9 callback ) { final String s = this . prefix + pattern ; LinkedList < FunctionInterface9 > callback_list = this . callbacks . get ( s ) ; if ( callback_list == null ) { callback_list = new LinkedList < FunctionInterface9 > ( ) ; callback_list . addLast ( callback ) ; this . callbacks . put ( s , callback_list ) ; } else { callback_list . addLast ( callback ) ; } OtpOutputStream subscribe = new OtpOutputStream ( ) ; subscribe . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"subscribe\" ) , new OtpErlangString ( pattern ) } ; subscribe . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( subscribe ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine how may service name pattern subscriptions have occurred . [CODESPLIT] public int subscribe_count ( final String pattern ) throws InvalidInputException , TerminateException { OtpOutputStream subscribe_count = new OtpOutputStream ( ) ; subscribe_count . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"subscribe_count\" ) , new OtpErlangString ( pattern ) } ; subscribe_count . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( subscribe_count ) ; try { return ( Integer ) poll_request ( null , false ) ; } catch ( MessageDecodingException e ) { e . printStackTrace ( API . err ) ; return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unsubscribes from a service name pattern . [CODESPLIT] public void unsubscribe ( final String pattern ) throws InvalidInputException { final String s = this . prefix + pattern ; LinkedList < FunctionInterface9 > callback_list = this . callbacks . get ( s ) ; if ( callback_list == null ) { throw new InvalidInputException ( ) ; } else { callback_list . removeFirst ( ) ; if ( callback_list . isEmpty ( ) ) { this . callbacks . remove ( s ) ; } } OtpOutputStream unsubscribe = new OtpOutputStream ( ) ; unsubscribe . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"unsubscribe\" ) , new OtpErlangString ( pattern ) } ; unsubscribe . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( unsubscribe ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronous point - to - point communication to a service subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public TransId send_async ( final String name , final byte [ ] request ) throws InvalidInputException , MessageDecodingException , TerminateException { return send_async ( name , ( \"\" ) . getBytes ( ) , request , this . timeout_async , this . priority_default ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous point - to - point communication to a service subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public Response send_sync ( final String name , final byte [ ] request ) throws InvalidInputException , MessageDecodingException , TerminateException { return send_sync ( name , ( \"\" ) . getBytes ( ) , request , this . timeout_sync , this . priority_default ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronous point - to - point communication to a service subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public Response send_sync ( final String name , final byte [ ] request_info , final byte [ ] request , final Integer timeout , final Byte priority ) throws InvalidInputException , MessageDecodingException , TerminateException { try { OtpOutputStream send_sync = new OtpOutputStream ( ) ; send_sync . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"send_sync\" ) , new OtpErlangString ( name ) , new OtpErlangBinary ( request_info ) , new OtpErlangBinary ( request ) , new OtpErlangUInt ( timeout ) , new OtpErlangInt ( priority ) } ; send_sync . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( send_sync ) ; return ( Response ) poll_request ( null , false ) ; } catch ( OtpErlangRangeException e ) { e . printStackTrace ( API . err ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronous point - multicast communication to services subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public ArrayList < TransId > mcast_async ( final String name , final byte [ ] request ) throws InvalidInputException , MessageDecodingException , TerminateException { return mcast_async ( name , new byte [ 0 ] , request , this . timeout_async , this . priority_default ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forward a message to another service subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public void forward_ ( final Integer request_type , final String name , final byte [ ] request_info , final byte [ ] request , final Integer timeout , final Byte priority , final byte [ ] trans_id , final OtpErlangPid pid ) throws ForwardAsyncException , ForwardSyncException , InvalidInputException { if ( request_type == API . ASYNC ) forward_async ( name , request_info , request , timeout , priority , trans_id , pid ) ; else if ( request_type == API . SYNC ) forward_sync ( name , request_info , request , timeout , priority , trans_id , pid ) ; else throw new InvalidInputException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously forward a message to another service subscribed that matches the destination service <code > name< / code > . [CODESPLIT] public void forward_async ( final String name , final byte [ ] request_info , final byte [ ] request , Integer timeout , final Byte priority , final byte [ ] trans_id , final OtpErlangPid pid ) throws ForwardAsyncException { try { OtpOutputStream forward_async = new OtpOutputStream ( ) ; forward_async . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"forward_async\" ) , new OtpErlangString ( name ) , new OtpErlangBinary ( request_info ) , new OtpErlangBinary ( request ) , new OtpErlangUInt ( timeout ) , new OtpErlangInt ( priority ) , new OtpErlangBinary ( trans_id ) , pid } ; forward_async . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( forward_async ) ; } catch ( OtpErlangRangeException e ) { e . printStackTrace ( API . err ) ; return ; } throw new ForwardAsyncException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a response from a service request . [CODESPLIT] public void return_ ( final Integer request_type , final String name , final String pattern , final byte [ ] response_info , final byte [ ] response , final Integer timeout , final byte [ ] trans_id , final OtpErlangPid pid ) throws ReturnAsyncException , ReturnSyncException , InvalidInputException { if ( request_type == API . ASYNC ) return_async ( name , pattern , response_info , response , timeout , trans_id , pid ) ; else if ( request_type == API . SYNC ) return_sync ( name , pattern , response_info , response , timeout , trans_id , pid ) ; else throw new InvalidInputException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Synchronously returns a response from a service request . [CODESPLIT] public void return_sync ( final String name , final String pattern , byte [ ] response_info , byte [ ] response , Integer timeout , final byte [ ] trans_id , final OtpErlangPid pid ) throws ReturnSyncException { try { OtpOutputStream return_sync = new OtpOutputStream ( ) ; return_sync . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"return_sync\" ) , new OtpErlangString ( name ) , new OtpErlangString ( pattern ) , new OtpErlangBinary ( response_info ) , new OtpErlangBinary ( response ) , new OtpErlangUInt ( timeout ) , new OtpErlangBinary ( trans_id ) , pid } ; return_sync . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( return_sync ) ; } catch ( OtpErlangRangeException e ) { e . printStackTrace ( API . err ) ; return ; } throw new ReturnSyncException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final Integer timeout ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( timeout , TransIdNull , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final byte [ ] trans_id ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( this . timeout_sync , trans_id , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( this . timeout_sync , TransIdNull , consume ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final byte [ ] trans_id , final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { return recv_async ( this . timeout_sync , trans_id , consume ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Asynchronously receive a response . [CODESPLIT] public Response recv_async ( final Integer timeout , final byte [ ] trans_id , final boolean consume ) throws InvalidInputException , MessageDecodingException , TerminateException { try { OtpOutputStream recv_async = new OtpOutputStream ( ) ; recv_async . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"recv_async\" ) , new OtpErlangUInt ( timeout ) , new OtpErlangBinary ( trans_id ) , consume ? new OtpErlangAtom ( \"true\" ) : new OtpErlangAtom ( \"false\" ) } ; recv_async . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( recv_async ) ; return ( Response ) poll_request ( null , false ) ; } catch ( OtpErlangRangeException e ) { e . printStackTrace ( API . err ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Blocks to process incoming CloudI service requests [CODESPLIT] public boolean poll ( final int timeout ) throws InvalidInputException , MessageDecodingException , TerminateException { if ( Boolean . TRUE == poll_request ( timeout , true ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shutdown the service successfully [CODESPLIT] public void shutdown ( final String reason ) { OtpOutputStream shutdown = new OtpOutputStream ( ) ; shutdown . write ( OtpExternal . versionTag ) ; final OtpErlangObject [ ] tuple = { new OtpErlangAtom ( \"shutdown\" ) , new OtpErlangString ( reason ) } ; shutdown . write_any ( new OtpErlangTuple ( tuple ) ) ; send ( shutdown ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO make specific Throwables contributable? [CODESPLIT] public static boolean requiresNonLocalHandling ( Throwable th ) { return th instanceof VirtualMachineError || th instanceof ThreadDeath || th instanceof InterruptedException || th instanceof LinkageError ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method checks if a given Throwable is fit for local handling returning it if it is and throwing it otherwise . [CODESPLIT] public static < T extends Throwable > T forLocalHandling ( T th ) { if ( requiresNonLocalHandling ( th ) ) { AUnchecker . throwUnchecked ( th ) ; } return th ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Acquires the runState lock ; returns current ( locked ) runState . [CODESPLIT] private int lockRunState ( ) { int rs ; return ( ( ( ( rs = runState ) & RSLOCK ) != 0 || ! U . compareAndSwapInt ( this , RUNSTATE , rs , rs |= RSLOCK ) ) ? awaitRunStateLock ( ) : rs ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Spins and / or blocks until runstate lock is available . See above for explanation . [CODESPLIT] private int awaitRunStateLock ( ) { Object lock ; boolean wasInterrupted = false ; for ( int spins = SPINS , r = 0 , rs , ns ; ; ) { if ( ( ( rs = runState ) & RSLOCK ) == 0 ) { if ( U . compareAndSwapInt ( this , RUNSTATE , rs , ns = rs | RSLOCK ) ) { if ( wasInterrupted ) { try { Thread . currentThread ( ) . interrupt ( ) ; } catch ( SecurityException ignore ) { } } return ns ; } } else if ( r == 0 ) r = ThreadLocalRandomHelper . nextSecondarySeed ( ) ; else if ( spins > 0 ) { r ^= r << 6 ; r ^= r >>> 21 ; r ^= r << 7 ; // xorshift if ( r >= 0 ) -- spins ; } else if ( ( rs & STARTED ) == 0 || ( lock = stealCounter ) == null ) Thread . yield ( ) ; // initialization race else if ( U . compareAndSwapInt ( this , RUNSTATE , rs , rs | RSIGNAL ) ) { synchronized ( lock ) { if ( ( runState & RSIGNAL ) != 0 ) { try { lock . wait ( ) ; } catch ( InterruptedException ie ) { if ( ! ( Thread . currentThread ( ) instanceof ForkJoinWorkerThread ) ) wasInterrupted = true ; } } else lock . notifyAll ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unlocks and sets runState to newRunState . [CODESPLIT] private void unlockRunState ( int oldRunState , int newRunState ) { if ( ! U . compareAndSwapInt ( this , RUNSTATE , oldRunState , newRunState ) ) { Object lock = stealCounter ; runState = newRunState ; // clears RSIGNAL bit if ( lock != null ) synchronized ( lock ) { lock . notifyAll ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to construct and start one worker . Assumes that total count has already been incremented as a reservation . Invokes deregisterWorker on any failure . [CODESPLIT] private boolean createWorker ( ) { ForkJoinWorkerThreadFactory fac = factory ; Throwable ex = null ; ForkJoinWorkerThread wt = null ; try { if ( fac != null && ( wt = fac . newThread ( this ) ) != null ) { wt . start ( ) ; return true ; } } catch ( Throwable rex ) { ex = rex ; } deregisterWorker ( wt , ex ) ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to add one worker incrementing ctl counts before doing so relying on createWorker to back out on failure . [CODESPLIT] private void tryAddWorker ( long c ) { boolean add = false ; do { long nc = ( ( AC_MASK & ( c + AC_UNIT ) ) | ( TC_MASK & ( c + TC_UNIT ) ) ) ; if ( ctl == c ) { int rs , stop ; // check if terminating if ( ( stop = ( rs = lockRunState ( ) ) & STOP ) == 0 ) add = U . compareAndSwapLong ( this , CTL , c , nc ) ; unlockRunState ( rs , rs & ~ RSLOCK ) ; if ( stop != 0 ) break ; if ( add ) { createWorker ( ) ; break ; } } } while ( ( ( c = ctl ) & ADD_WORKER ) != 0L && ( int ) c == 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Callback from ForkJoinWorkerThread constructor to establish and record its WorkQueue . [CODESPLIT] final WorkQueue registerWorker ( ForkJoinWorkerThread wt ) { UncaughtExceptionHandler handler ; wt . setDaemon ( true ) ; // configure thread if ( ( handler = ueh ) != null ) wt . setUncaughtExceptionHandler ( handler ) ; WorkQueue w = new WorkQueue ( this , wt ) ; int i = 0 ; // assign a pool index int mode = config & MODE_MASK ; int rs = lockRunState ( ) ; try { WorkQueue [ ] ws ; int n ; // skip if no array if ( ( ws = workQueues ) != null && ( n = ws . length ) > 0 ) { int s = indexSeed += SEED_INCREMENT ; // unlikely to collide int m = n - 1 ; i = ( ( s << 1 ) | 1 ) & m ; // odd-numbered indices if ( ws [ i ] != null ) { // collision int probes = 0 ; // step by approx half n int step = ( n <= 4 ) ? 2 : ( ( n >>> 1 ) & EVENMASK ) + 2 ; while ( ws [ i = ( i + step ) & m ] != null ) { if ( ++ probes >= n ) { workQueues = ws = Arrays . copyOf ( ws , n <<= 1 ) ; m = n - 1 ; probes = 0 ; } } } w . hint = s ; // use as random seed w . config = i | mode ; w . scanState = i ; // publication fence ws [ i ] = w ; } } finally { unlockRunState ( rs , rs & ~ RSLOCK ) ; } wt . setName ( workerNamePrefix . concat ( Integer . toString ( i >>> 1 ) ) ) ; return w ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Final callback from terminating worker as well as upon failure to construct or start a worker . Removes record of worker from array and adjusts counts . If pool is shutting down tries to complete termination . [CODESPLIT] final void deregisterWorker ( ForkJoinWorkerThread wt , Throwable ex ) { WorkQueue w = null ; if ( wt != null && ( w = wt . workQueue ) != null ) { WorkQueue [ ] ws ; // remove index from array int idx = w . config & SMASK ; int rs = lockRunState ( ) ; if ( ( ws = workQueues ) != null && ws . length > idx && ws [ idx ] == w ) ws [ idx ] = null ; unlockRunState ( rs , rs & ~ RSLOCK ) ; } long c ; // decrement counts do { } while ( ! U . compareAndSwapLong ( this , CTL , c = ctl , ( ( AC_MASK & ( c - AC_UNIT ) ) | ( TC_MASK & ( c - TC_UNIT ) ) | ( SP_MASK & c ) ) ) ) ; if ( w != null ) { w . qlock = - 1 ; // ensure set w . transferStealCount ( this ) ; w . cancelAll ( ) ; // cancel remaining tasks } for ( ; ; ) { // possibly replace WorkQueue [ ] ws ; int m , sp ; if ( tryTerminate ( false , false ) || w == null || w . array == null || ( runState & STOP ) != 0 || ( ws = workQueues ) == null || ( m = ws . length - 1 ) < 0 ) // already terminating break ; if ( ( sp = ( int ) ( c = ctl ) ) != 0 ) { // wake up replacement if ( tryRelease ( c , ws [ sp & m ] , AC_UNIT ) ) break ; } else if ( ex != null && ( c & ADD_WORKER ) != 0L ) { tryAddWorker ( c ) ; // create replacement break ; } else // don't need replacement break ; } if ( ex == null ) // help clean on way out ForkJoinTask . helpExpungeStaleExceptions ( ) ; else // rethrow ForkJoinTask . rethrow ( ex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to create or activate a worker if too few are active . [CODESPLIT] final void signalWork ( WorkQueue [ ] ws , WorkQueue q ) { long c ; int sp , i ; WorkQueue v ; Thread p ; while ( ( c = ctl ) < 0L ) { // too few active if ( ( sp = ( int ) c ) == 0 ) { // no idle workers if ( ( c & ADD_WORKER ) != 0L ) // too few workers tryAddWorker ( c ) ; break ; } if ( ws == null ) // unstarted/terminated break ; if ( ws . length <= ( i = sp & SMASK ) ) // terminated break ; if ( ( v = ws [ i ] ) == null ) // terminating break ; int vs = ( sp + SS_SEQ ) & ~ INACTIVE ; // next scanState int d = sp - v . scanState ; // screen CAS long nc = ( UC_MASK & ( c + AC_UNIT ) ) | ( SP_MASK & v . stackPred ) ; if ( d == 0 && U . compareAndSwapLong ( this , CTL , c , nc ) ) { v . scanState = vs ; // activate v if ( ( p = v . parker ) != null ) U . unpark ( p ) ; break ; } if ( q != null && q . base == q . top ) // no more work break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals and releases worker v if it is top of idle worker stack . This performs a one - shot version of signalWork only if there is ( apparently ) at least one idle worker . [CODESPLIT] private boolean tryRelease ( long c , WorkQueue v , long inc ) { int sp = ( int ) c , vs = ( sp + SS_SEQ ) & ~ INACTIVE ; Thread p ; if ( v != null && v . scanState == sp ) { // v is at top of stack long nc = ( UC_MASK & ( c + inc ) ) | ( SP_MASK & v . stackPred ) ; if ( U . compareAndSwapLong ( this , CTL , c , nc ) ) { v . scanState = vs ; if ( ( p = v . parker ) != null ) U . unpark ( p ) ; return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Top - level runloop for workers called by ForkJoinWorkerThread . run . [CODESPLIT] final void runWorker ( WorkQueue w ) { w . growArray ( ) ; // allocate queue int seed = w . hint ; // initially holds randomization hint int r = ( seed == 0 ) ? 1 : seed ; // avoid 0 for xorShift for ( ForkJoinTask < ? > t ; ; ) { if ( ( t = scan ( w , r ) ) != null ) w . runTask ( t ) ; else if ( ! awaitWork ( w , r ) ) break ; r ^= r << 13 ; r ^= r >>> 17 ; r ^= r << 5 ; // xorshift } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans for and tries to steal a top - level task . Scans start at a random location randomly moving on apparent contention otherwise continuing linearly until reaching two consecutive empty passes over all queues with the same checksum ( summing each base index of each queue that moves on each steal ) at which point the worker tries to inactivate and then re - scans attempting to re - activate ( itself or some other worker ) if finding a task ; otherwise returning null to await work . Scans otherwise touch as little memory as possible to reduce disruption on other scanning threads . [CODESPLIT] private ForkJoinTask < ? > scan ( WorkQueue w , int r ) { WorkQueue [ ] ws ; int m ; if ( ( ws = workQueues ) != null && ( m = ws . length - 1 ) > 0 && w != null ) { int ss = w . scanState ; // initially non-negative for ( int origin = r & m , k = origin , oldSum = 0 , checkSum = 0 ; ; ) { WorkQueue q ; ForkJoinTask < ? > [ ] a ; ForkJoinTask < ? > t ; int b , n ; long c ; if ( ( q = ws [ k ] ) != null ) { if ( ( n = ( b = q . base ) - q . top ) < 0 && ( a = q . array ) != null ) { // non-empty long i = ( ( ( a . length - 1 ) & b ) << ASHIFT ) + ABASE ; if ( ( t = ( ( ForkJoinTask < ? > ) U . getObjectVolatile ( a , i ) ) ) != null && q . base == b ) { if ( ss >= 0 ) { if ( U . compareAndSwapObject ( a , i , t , null ) ) { q . base = b + 1 ; if ( n < - 1 ) // signal others signalWork ( ws , q ) ; return t ; } } else if ( oldSum == 0 && // try to activate w . scanState < 0 ) tryRelease ( c = ctl , ws [ m & ( int ) c ] , AC_UNIT ) ; } if ( ss < 0 ) // refresh ss = w . scanState ; r ^= r << 1 ; r ^= r >>> 3 ; r ^= r << 10 ; origin = k = r & m ; // move and rescan oldSum = checkSum = 0 ; continue ; } checkSum += b ; } if ( ( k = ( k + 1 ) & m ) == origin ) { // continue until stable if ( ( ss >= 0 || ( ss == ( ss = w . scanState ) ) ) && oldSum == ( oldSum = checkSum ) ) { if ( ss < 0 || w . qlock < 0 ) // already inactive break ; int ns = ss | INACTIVE ; // try to inactivate long nc = ( ( SP_MASK & ns ) | ( UC_MASK & ( ( c = ctl ) - AC_UNIT ) ) ) ; w . stackPred = ( int ) c ; // hold prev stack top U . putInt ( w , QSCANSTATE , ns ) ; if ( U . compareAndSwapLong ( this , CTL , c , nc ) ) ss = ns ; else w . scanState = ss ; // back out } checkSum = 0 ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Possibly blocks worker w waiting for a task to steal or returns false if the worker should terminate . If inactivating w has caused the pool to become quiescent checks for pool termination and so long as this is not the only worker waits for up to a given duration . On timeout if ctl has not changed terminates the worker which will in turn wake up another worker to possibly repeat this process . [CODESPLIT] private boolean awaitWork ( WorkQueue w , int r ) { if ( w == null || w . qlock < 0 ) // w is terminating return false ; for ( int pred = w . stackPred , spins = SPINS , ss ; ; ) { if ( ( ss = w . scanState ) >= 0 ) break ; else if ( spins > 0 ) { r ^= r << 6 ; r ^= r >>> 21 ; r ^= r << 7 ; if ( r >= 0 && -- spins == 0 ) { // randomize spins WorkQueue v ; WorkQueue [ ] ws ; int s , j ; AtomicLong sc ; if ( pred != 0 && ( ws = workQueues ) != null && ( j = pred & SMASK ) < ws . length && ( v = ws [ j ] ) != null && // see if pred parking ( v . parker == null || v . scanState >= 0 ) ) spins = SPINS ; // continue spinning } } else if ( w . qlock < 0 ) // recheck after spins return false ; else if ( ! Thread . interrupted ( ) ) { long c , prevctl , parkTime , deadline ; int ac = ( int ) ( ( c = ctl ) >> AC_SHIFT ) + ( config & SMASK ) ; if ( ( ac <= 0 && tryTerminate ( false , false ) ) || ( runState & STOP ) != 0 ) // pool terminating return false ; if ( ac <= 0 && ss == ( int ) c ) { // is last waiter prevctl = ( UC_MASK & ( c + AC_UNIT ) ) | ( SP_MASK & pred ) ; int t = ( short ) ( c >>> TC_SHIFT ) ; // shrink excess spares if ( t > 2 && U . compareAndSwapLong ( this , CTL , c , prevctl ) ) return false ; // else use timed wait parkTime = IDLE_TIMEOUT * ( ( t >= 0 ) ? 1 : 1 - t ) ; deadline = System . nanoTime ( ) + parkTime - TIMEOUT_SLOP ; } else prevctl = parkTime = deadline = 0L ; Thread wt = Thread . currentThread ( ) ; U . putObject ( wt , PARKBLOCKER , this ) ; // emulate LockSupport w . parker = wt ; if ( w . scanState < 0 && ctl == c ) // recheck before park U . park ( false , parkTime ) ; U . putOrderedObject ( w , QPARKER , null ) ; U . putObject ( wt , PARKBLOCKER , null ) ; if ( w . scanState >= 0 ) break ; if ( parkTime != 0L && ctl == c && deadline - System . nanoTime ( ) <= 0L && U . compareAndSwapLong ( this , CTL , c , prevctl ) ) return false ; // shrink pool } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to steal and run tasks within the target s computation . Uses a variant of the top - level algorithm restricted to tasks with the given task as ancestor : It prefers taking and running eligible tasks popped from the worker s own queue ( via popCC ) . Otherwise it scans others randomly moving on contention or execution deciding to give up based on a checksum ( via return codes frob pollAndExecCC ) . The maxTasks argument supports external usages ; internal calls use zero allowing unbounded steps ( external calls trap non - positive values ) . [CODESPLIT] final int helpComplete ( WorkQueue w , CountedCompleter < ? > task , int maxTasks ) { WorkQueue [ ] ws ; int s = 0 , m ; if ( ( ws = workQueues ) != null && ( m = ws . length - 1 ) >= 0 && task != null && w != null ) { int mode = w . config ; // for popCC int r = w . hint ^ w . top ; // arbitrary seed for origin int origin = r & m ; // first queue to scan int h = 1 ; // 1:ran, >1:contended, <0:hash for ( int k = origin , oldSum = 0 , checkSum = 0 ; ; ) { CountedCompleter < ? > p ; WorkQueue q ; if ( ( s = task . status ) < 0 ) break ; if ( h == 1 && ( p = w . popCC ( task , mode ) ) != null ) { p . doExec ( ) ; // run local task if ( maxTasks != 0 && -- maxTasks == 0 ) break ; origin = k ; // reset oldSum = checkSum = 0 ; } else { // poll other queues if ( ( q = ws [ k ] ) == null ) h = 0 ; else if ( ( h = q . pollAndExecCC ( task ) ) < 0 ) checkSum += h ; if ( h > 0 ) { if ( h == 1 && maxTasks != 0 && -- maxTasks == 0 ) break ; r ^= r << 13 ; r ^= r >>> 17 ; r ^= r << 5 ; // xorshift origin = k = r & m ; // move and restart oldSum = checkSum = 0 ; } else if ( ( k = ( k + 1 ) & m ) == origin ) { if ( oldSum == ( oldSum = checkSum ) ) break ; checkSum = 0 ; } } } } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to decrement active count ( sometimes implicitly ) and possibly release or create a compensating worker in preparation for blocking . Returns false ( retryable by caller ) on contention detected staleness instability or termination . [CODESPLIT] private boolean tryCompensate ( WorkQueue w ) { boolean canBlock ; WorkQueue [ ] ws ; long c ; int m , pc , sp ; if ( w == null || w . qlock < 0 || // caller terminating ( ws = workQueues ) == null || ( m = ws . length - 1 ) <= 0 || ( pc = config & SMASK ) == 0 ) // parallelism disabled canBlock = false ; else if ( ( sp = ( int ) ( c = ctl ) ) != 0 ) // release idle worker canBlock = tryRelease ( c , ws [ sp & m ] , 0L ) ; else { int ac = ( int ) ( c >> AC_SHIFT ) + pc ; int tc = ( short ) ( c >> TC_SHIFT ) + pc ; int nbusy = 0 ; // validate saturation for ( int i = 0 ; i <= m ; ++ i ) { // two passes of odd indices WorkQueue v ; if ( ( v = ws [ ( ( i << 1 ) | 1 ) & m ] ) != null ) { if ( ( v . scanState & SCANNING ) != 0 ) break ; ++ nbusy ; } } if ( nbusy != ( tc << 1 ) || ctl != c ) canBlock = false ; // unstable or stale else if ( tc >= pc && ac > 1 && w . isEmpty ( ) ) { long nc = ( ( AC_MASK & ( c - AC_UNIT ) ) | ( ~ AC_MASK & c ) ) ; // uncompensated canBlock = U . compareAndSwapLong ( this , CTL , c , nc ) ; } else if ( tc >= MAX_CAP || ( this == common && tc >= pc + commonMaxSpares ) ) throw new RejectedExecutionException ( \"Thread limit exceeded replacing blocked worker\" ) ; else { // similar to tryAddWorker boolean add = false ; int rs ; // CAS within lock long nc = ( ( AC_MASK & c ) | ( TC_MASK & ( c + TC_UNIT ) ) ) ; if ( ( ( rs = lockRunState ( ) ) & STOP ) == 0 ) add = U . compareAndSwapLong ( this , CTL , c , nc ) ; unlockRunState ( rs , rs & ~ RSLOCK ) ; canBlock = add && createWorker ( ) ; // throws on exception } } return canBlock ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a cheap heuristic guide for task partitioning when programmers frameworks tools or languages have little or no idea about task granularity . In essence by offering this method we ask users only about tradeoffs in overhead vs expected throughput and its variance rather than how finely to partition tasks . [CODESPLIT] static int getSurplusQueuedTaskCount ( ) { Thread t ; ForkJoinWorkerThread wt ; ForkJoinPool pool ; WorkQueue q ; if ( ( ( t = Thread . currentThread ( ) ) instanceof ForkJoinWorkerThread ) ) { int p = ( pool = ( wt = ( ForkJoinWorkerThread ) t ) . pool ) . config & SMASK ; int n = ( q = wt . workQueue ) . top - q . base ; int a = ( int ) ( pool . ctl >> AC_SHIFT ) + p ; return n - ( a > ( p >>>= 1 ) ? 0 : a > ( p >>>= 1 ) ? 1 : a > ( p >>>= 1 ) ? 2 : a > ( p >>>= 1 ) ? 4 : 8 ) ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Possibly initiates and / or completes termination . [CODESPLIT] private boolean tryTerminate ( boolean now , boolean enable ) { int rs ; if ( this == common ) // cannot shut down return false ; if ( ( rs = runState ) >= 0 ) { if ( ! enable ) return false ; rs = lockRunState ( ) ; // enter SHUTDOWN phase unlockRunState ( rs , ( rs & ~ RSLOCK ) | SHUTDOWN ) ; } if ( ( rs & STOP ) == 0 ) { if ( ! now ) { // check quiescence for ( long oldSum = 0L ; ; ) { // repeat until stable WorkQueue [ ] ws ; WorkQueue w ; int m , b ; long c ; long checkSum = ctl ; if ( ( int ) ( checkSum >> AC_SHIFT ) + ( config & SMASK ) > 0 ) return false ; // still active workers if ( ( ws = workQueues ) == null || ( m = ws . length - 1 ) <= 0 ) break ; // check queues for ( int i = 0 ; i <= m ; ++ i ) { if ( ( w = ws [ i ] ) != null ) { if ( ( b = w . base ) != w . top || w . scanState >= 0 || w . currentSteal != null ) { tryRelease ( c = ctl , ws [ m & ( int ) c ] , AC_UNIT ) ; return false ; // arrange for recheck } checkSum += b ; if ( ( i & 1 ) == 0 ) w . qlock = - 1 ; // try to disable external } } if ( oldSum == ( oldSum = checkSum ) ) break ; } } if ( ( runState & STOP ) == 0 ) { rs = lockRunState ( ) ; // enter STOP phase unlockRunState ( rs , ( rs & ~ RSLOCK ) | STOP ) ; } } int pass = 0 ; // 3 passes to help terminate for ( long oldSum = 0L ; ; ) { // or until done or stable WorkQueue [ ] ws ; WorkQueue w ; ForkJoinWorkerThread wt ; int m ; long checkSum = ctl ; if ( ( short ) ( checkSum >>> TC_SHIFT ) + ( config & SMASK ) <= 0 || ( ws = workQueues ) == null || ( m = ws . length - 1 ) <= 0 ) { if ( ( runState & TERMINATED ) == 0 ) { rs = lockRunState ( ) ; // done unlockRunState ( rs , ( rs & ~ RSLOCK ) | TERMINATED ) ; synchronized ( this ) { notifyAll ( ) ; } // for awaitTermination } break ; } for ( int i = 0 ; i <= m ; ++ i ) { if ( ( w = ws [ i ] ) != null ) { checkSum += w . base ; w . qlock = - 1 ; // try to disable if ( pass > 0 ) { w . cancelAll ( ) ; // clear queue if ( pass > 1 && ( wt = w . owner ) != null ) { if ( ! wt . isInterrupted ( ) ) { try { // unblock join wt . interrupt ( ) ; } catch ( Throwable ignore ) { } } if ( w . scanState < 0 ) U . unpark ( wt ) ; // wake up } } } } if ( checkSum != oldSum ) { // unstable oldSum = checkSum ; pass = 0 ; } else if ( pass > 3 && pass > m ) // can't further help break ; else if ( ++ pass > 1 ) { // try to dequeue long c ; int j = 0 , sp ; // bound attempts while ( j ++ <= m && ( sp = ( int ) ( c = ctl ) ) != 0 ) tryRelease ( c , ws [ sp & m ] , AC_UNIT ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Full version of externalPush handling uncommon cases as well as performing secondary initialization upon the first submission of the first task to the pool . It also detects first submission by an external thread and creates a new shared queue if the one at index if empty or contended . [CODESPLIT] private void externalSubmit ( ForkJoinTask < ? > task ) { int r ; // initialize caller's probe if ( ( r = ThreadLocalRandomHelper . getProbe ( ) ) == 0 ) { ThreadLocalRandomHelper . localInit ( ) ; r = ThreadLocalRandomHelper . getProbe ( ) ; } for ( ; ; ) { WorkQueue [ ] ws ; WorkQueue q ; int rs , m , k ; boolean move = false ; if ( ( rs = runState ) < 0 ) { tryTerminate ( false , false ) ; // help terminate throw new RejectedExecutionException ( ) ; } else if ( ( rs & STARTED ) == 0 || // initialize ( ( ws = workQueues ) == null || ( m = ws . length - 1 ) < 0 ) ) { int ns = 0 ; rs = lockRunState ( ) ; try { if ( ( rs & STARTED ) == 0 ) { U . compareAndSwapObject ( this , STEALCOUNTER , null , new AtomicLong ( ) ) ; // create workQueues array with size a power of two int p = config & SMASK ; // ensure at least 2 slots int n = ( p > 1 ) ? p - 1 : 1 ; n |= n >>> 1 ; n |= n >>> 2 ; n |= n >>> 4 ; n |= n >>> 8 ; n |= n >>> 16 ; n = ( n + 1 ) << 1 ; workQueues = new WorkQueue [ n ] ; ns = STARTED ; } } finally { unlockRunState ( rs , ( rs & ~ RSLOCK ) | ns ) ; } } else if ( ( q = ws [ k = r & m & SQMASK ] ) != null ) { if ( q . qlock == 0 && U . compareAndSwapInt ( q , QLOCK , 0 , 1 ) ) { ForkJoinTask < ? > [ ] a = q . array ; int s = q . top ; boolean submitted = false ; // initial submission or resizing try { // locked version of push if ( ( a != null && a . length > s + 1 - q . base ) || ( a = q . growArray ( ) ) != null ) { int j = ( ( ( a . length - 1 ) & s ) << ASHIFT ) + ABASE ; U . putOrderedObject ( a , j , task ) ; U . putOrderedInt ( q , QTOP , s + 1 ) ; submitted = true ; } } finally { U . compareAndSwapInt ( q , QLOCK , 1 , 0 ) ; } if ( submitted ) { signalWork ( ws , q ) ; return ; } } move = true ; // move on failure } else if ( ( ( rs = runState ) & RSLOCK ) == 0 ) { // create new queue q = new WorkQueue ( this , null ) ; q . hint = r ; q . config = k | SHARED_QUEUE ; q . scanState = INACTIVE ; rs = lockRunState ( ) ; // publish index if ( rs > 0 && ( ws = workQueues ) != null && k < ws . length && ws [ k ] == null ) ws [ k ] = q ; // else terminated unlockRunState ( rs , rs & ~ RSLOCK ) ; } else move = true ; // move if busy if ( move ) r = ThreadLocalRandomHelper . advanceProbe ( r ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to add the given task to a submission queue at submitter s current queue . Only the ( vastly ) most common path is directly handled in this method while screening for need for externalSubmit . [CODESPLIT] final void externalPush ( ForkJoinTask < ? > task ) { WorkQueue [ ] ws ; WorkQueue q ; int m ; int r = ThreadLocalRandomHelper . getProbe ( ) ; int rs = runState ; if ( ( ws = workQueues ) != null && ( m = ( ws . length - 1 ) ) >= 0 && ( q = ws [ m & r & SQMASK ] ) != null && r != 0 && rs > 0 && U . compareAndSwapInt ( q , QLOCK , 0 , 1 ) ) { ForkJoinTask < ? > [ ] a ; int am , n , s ; if ( ( a = q . array ) != null && ( am = a . length - 1 ) > ( n = ( s = q . top ) - q . base ) ) { int j = ( ( am & s ) << ASHIFT ) + ABASE ; U . putOrderedObject ( a , j , task ) ; U . putOrderedInt ( q , QTOP , s + 1 ) ; U . putIntVolatile ( q , QLOCK , 0 ) ; if ( n <= 1 ) signalWork ( ws , q ) ; return ; } U . compareAndSwapInt ( q , QLOCK , 1 , 0 ) ; } externalSubmit ( task ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns common pool queue for an external thread . [CODESPLIT] static WorkQueue commonSubmitterQueue ( ) { ForkJoinPool p = common ; int r = ThreadLocalRandomHelper . getProbe ( ) ; WorkQueue [ ] ws ; int m ; return ( p != null && ( ws = p . workQueues ) != null && ( m = ws . length - 1 ) >= 0 ) ? ws [ m & r & SQMASK ] : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs tryUnpush for an external submitter : Finds queue locks if apparently non - empty validates upon locking and adjusts top . Each check can fail but rarely does . [CODESPLIT] final boolean tryExternalUnpush ( ForkJoinTask < ? > task ) { WorkQueue [ ] ws ; WorkQueue w ; ForkJoinTask < ? > [ ] a ; int m , s ; int r = ThreadLocalRandomHelper . getProbe ( ) ; if ( ( ws = workQueues ) != null && ( m = ws . length - 1 ) >= 0 && ( w = ws [ m & r & SQMASK ] ) != null && ( a = w . array ) != null && ( s = w . top ) != w . base ) { long j = ( ( ( a . length - 1 ) & ( s - 1 ) ) << ASHIFT ) + ABASE ; if ( U . compareAndSwapInt ( w , QLOCK , 0 , 1 ) ) { if ( w . top == s && w . array == a && U . getObject ( a , j ) == task && U . compareAndSwapObject ( a , j , task , null ) ) { U . putOrderedInt ( w , QTOP , s - 1 ) ; U . putOrderedInt ( w , QLOCK , 0 ) ; return true ; } U . compareAndSwapInt ( w , QLOCK , 1 , 0 ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs helpComplete for an external submitter . [CODESPLIT] final int externalHelpComplete ( CountedCompleter < ? > task , int maxTasks ) { WorkQueue [ ] ws ; int n ; int r = ThreadLocalRandomHelper . getProbe ( ) ; return ( ( ws = workQueues ) == null || ( n = ws . length ) == 0 ) ? 0 : helpComplete ( ws [ ( n - 1 ) & r & SQMASK ] , task , maxTasks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the given task returning its result upon completion . If the computation encounters an unchecked Exception or Error it is rethrown as the outcome of this invocation . Rethrown exceptions behave in the same way as regular exceptions but when possible contain stack traces ( as displayed for example using { @code ex . printStackTrace () } ) of both the current thread as well as the thread actually encountering the exception ; minimally only the latter . [CODESPLIT] public < T > T invoke ( ForkJoinTask < T > task ) { if ( task == null ) throw new NullPointerException ( ) ; externalPush ( task ) ; return task . join ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Submits a ForkJoinTask for execution . [CODESPLIT] public < T > ForkJoinTask < T > submit ( ForkJoinTask < T > task ) { if ( task == null ) throw new NullPointerException ( ) ; externalPush ( task ) ; return task ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an estimate of the total number of tasks stolen from one thread s work queue by another . The reported value underestimates the actual total number of steals when the pool is not quiescent . This value may be useful for monitoring and tuning fork / join programs : in general steal counts should be high enough to keep threads busy but low enough to avoid overhead and contention across threads . [CODESPLIT] public long getStealCount ( ) { AtomicLong sc = stealCounter ; long count = ( sc == null ) ? 0L : sc . get ( ) ; WorkQueue [ ] ws ; WorkQueue w ; if ( ( ws = workQueues ) != null ) { for ( int i = 1 ; i < ws . length ; i += 2 ) { if ( ( w = ws [ i ] ) != null ) count += w . nsteals ; } } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates and returns the common pool respecting user settings specified via system properties . [CODESPLIT] private static ForkJoinPool makeCommonPool ( ) { int parallelism = - 1 ; ForkJoinWorkerThreadFactory factory = null ; UncaughtExceptionHandler handler = null ; try { // ignore exceptions in accessing/parsing properties String pp = System . getProperty ( \"java.util.concurrent.ForkJoinPool.common.parallelism\" ) ; String fp = System . getProperty ( \"java.util.concurrent.ForkJoinPool.common.threadFactory\" ) ; String hp = System . getProperty ( \"java.util.concurrent.ForkJoinPool.common.exceptionHandler\" ) ; String mp = System . getProperty ( \"java.util.concurrent.ForkJoinPool.common.maximumSpares\" ) ; if ( pp != null ) parallelism = Integer . parseInt ( pp ) ; if ( fp != null ) factory = ( ( ForkJoinWorkerThreadFactory ) ClassLoader . getSystemClassLoader ( ) . loadClass ( fp ) . newInstance ( ) ) ; if ( hp != null ) handler = ( ( UncaughtExceptionHandler ) ClassLoader . getSystemClassLoader ( ) . loadClass ( hp ) . newInstance ( ) ) ; if ( mp != null ) commonMaxSpares = Integer . parseInt ( mp ) ; } catch ( Exception ignore ) { } if ( factory == null ) { if ( System . getSecurityManager ( ) == null ) factory = defaultForkJoinWorkerThreadFactory ; else // use security-managed default factory = new InnocuousForkJoinWorkerThreadFactory ( ) ; } if ( parallelism < 0 && // default 1 less than #cores ( parallelism = Runtime . getRuntime ( ) . availableProcessors ( ) - 1 ) <= 0 ) parallelism = 1 ; if ( parallelism > MAX_CAP ) parallelism = MAX_CAP ; return new ForkJoinPool ( parallelism , factory , handler , LIFO_QUEUE , \"ForkJoinPool.commonPool-worker-\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] public static < R , T , E extends Throwable > AFuture < AList < R > > traverse ( AThreadPool tp , Iterable < T > values , AFunction1 < T , AFuture < R > , E > f ) throws E { final List < AFuture < R > > result = new ArrayList <> ( ) ; for ( T o : values ) { result . add ( f . apply ( o ) ) ; } return lift ( tp , result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new task to the top of the shared queue incrementing top . [CODESPLIT] @ Override public void push ( Runnable task ) { while ( true ) { final long _base = UNSAFE . getLongVolatile ( this , OFFS_BASE ) ; final long _top = top ; if ( _top == _base + mask ) { throw new RejectedExecutionExceptionWithoutStacktrace ( \"Queue overflow\" ) ; } final long taskOffset = taskOffset ( _top ) ; if ( UNSAFE . compareAndSwapObject ( tasks , taskOffset , null , task ) ) { // if the publishing thread is interrupted here, other publishers will effectively do a spin wait if ( ! UNSAFE . compareAndSwapLong ( this , OFFS_TOP , _top , _top + 1 ) ) { // there was a buffer wrap-around in the meantime --> undo the CAS 'put' operation and try again UNSAFE . putObjectVolatile ( tasks , taskOffset , null ) ; continue ; } if ( _top - _base <= 1 ) { pool . onAvailableTask ( ) ; } break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits if necessary for at most the given time for the computation to complete and then retrieves its result if available . [CODESPLIT] public final V get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { int s ; long nanos = unit . toNanos ( timeout ) ; if ( Thread . interrupted ( ) ) throw new InterruptedException ( ) ; if ( ( s = status ) >= 0 && nanos > 0L ) { long d = System . nanoTime ( ) + nanos ; long deadline = ( d == 0L ) ? 1L : d ; // avoid 0 Thread t = Thread . currentThread ( ) ; if ( t instanceof ForkJoinWorkerThread ) { ForkJoinWorkerThread wt = ( ForkJoinWorkerThread ) t ; s = wt . pool . awaitJoin ( wt . workQueue , this , deadline ) ; } else if ( ( s = ( ( this instanceof CountedCompleter ) ? ForkJoinPool . common . externalHelpComplete ( ( CountedCompleter < ? > ) this , 0 ) : ForkJoinPool . common . tryExternalUnpush ( this ) ? doExec ( ) : 0 ) ) >= 0 ) { long ns , ms ; // measure in nanosecs, but wait in millisecs while ( ( s = status ) >= 0 && ( ns = deadline - System . nanoTime ( ) ) > 0L ) { if ( ( ms = TimeUnit . NANOSECONDS . toMillis ( ns ) ) > 0L && U . compareAndSwapInt ( this , STATUS , s , s | SIGNAL ) ) { synchronized ( this ) { if ( status >= 0 ) wait ( ms ) ; // OK to throw InterruptedException else notifyAll ( ) ; } } } } } if ( s >= 0 ) s = status ; if ( ( s &= DONE_MASK ) != NORMAL ) { Throwable ex ; if ( s == CANCELLED ) throw new CancellationException ( ) ; if ( s != EXCEPTIONAL ) throw new TimeoutException ( ) ; if ( ( ex = getThrowableException ( ) ) != null ) throw new ExecutionException ( ex ) ; } return getRawResult ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "intentionally not volatile : This class is immutable so recalculating per thread works [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < K , V > ABTreeMap < K , V > empty ( ABTreeSpec spec ) { return new LeafNode ( spec , new Object [ 0 ] , new Object [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public Iterable<V > values ( K keyMin K keyMax ) ; [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public ABTreeMap < K , V > updated ( K key , V value ) { final UpdateResult result = _updated ( key , value ) ; if ( result . optRight == null ) { return result . left ; } // This is the only place where the tree depth can grow. // The 'minimum number of children' constraint does not apply to root nodes. return new IndexNode ( spec , new Object [ ] { result . separator } , new ABTreeMap [ ] { result . left , result . optRight } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "} [CODESPLIT] @ Override public < S > AFuture < S > map ( AThreadPool tp , AFunction1 < T , S , ? > f ) { final AFutureImpl < S > result = new AFutureImpl <> ( tp ) ; onComplete ( tp , v -> { try { result . complete ( v . map ( f ) ) ; } catch ( Throwable th ) { result . completeAsFailure ( th ) ; } } ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a convenience method for building simple JSON strings . It passes an AJsonSerHelper to a callback and builds a string based on what the callback does with it . [CODESPLIT] public static < E extends Throwable > String buildString ( AStatement1 < AJsonSerHelper , E > code ) throws E { final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; code . apply ( new AJsonSerHelper ( baos ) ) ; return new String ( baos . toByteArray ( ) , UTF_8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method returns an approximation of statistical data for all worker threads since the pool was started . Updates of the statistical data is done without synchronization so some or all of the data may be stale and some numbers may be pretty outdated while others are very current even for the same thread . For long - running pools however the data may be useful in analyzing behavior in general and performance anomalies in particular . Your mileage may vary you have been warned! ; - ) [CODESPLIT] @ Override public AThreadPoolStatistics getStatistics ( ) { final AWorkerThreadStatistics [ ] workerStats = new AWorkerThreadStatistics [ localQueues . length ] ; for ( int i = 0 ; i < localQueues . length ; i ++ ) { //noinspection ConstantConditions workerStats [ i ] = localQueues [ i ] . thread . getStatistics ( ) ; } final ASharedQueueStatistics [ ] sharedQueueStats = new ASharedQueueStatistics [ sharedQueues . length ] ; for ( int i = 0 ; i < sharedQueues . length ; i ++ ) { sharedQueueStats [ i ] = new ASharedQueueStatistics ( sharedQueues [ i ] . approximateSize ( ) ) ; } return new AThreadPoolStatistics ( workerStats , sharedQueueStats ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method shuts down the thread pool . The method finishes immediately returning a separate AFuture for every worker thread . In order to combine them into a single AFuture for all worker threads use { [CODESPLIT] @ Override public List < AFuture < Void > > shutdown ( ShutdownMode shutdownMode ) { if ( ! shutdown . compareAndSet ( false , true ) ) { throw new IllegalStateException ( \"pool can be shut down only once\" ) ; } if ( shutdownMode == ShutdownMode . SkipUnstarted || shutdownMode == ShutdownMode . InterruptRunning ) { for ( ASharedQueue sharedQueue : sharedQueues ) { sharedQueue . clear ( ) ; } for ( LocalQueue queue : localQueues ) { //noinspection StatementWithEmptyBody while ( queue . popFifo ( ) != null ) { // do nothing, just drain the queue } } if ( shutdownMode == ShutdownMode . InterruptRunning ) { for ( LocalQueue queue : localQueues ) { queue . thread . interrupt ( ) ; } } } final List < AFuture < Void > > result = new ArrayList <> ( ) ; for ( LocalQueue localQueue : localQueues ) { final ASettableFuture < Void > f = ASettableFuture . create ( ) ; sharedQueues [ 0 ] . push ( ( ) -> { workerThreadLifecycleCallback . onPreDie ( localQueue . thread ) ; throw new PoolShutdown ( f ) ; } ) ; UNSAFE . unpark ( localQueue . thread ) ; result . add ( f ) ; f . onComplete ( AThreadPool . SYNC_THREADPOOL , x -> workerThreadLifecycleCallback . onPostDie ( localQueue . thread ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an AList based on the contents of an existing <code > java . util . Iterable< / code > copying its contents . [CODESPLIT] public static < T > AList < T > create ( Iterable < T > elements ) { if ( elements instanceof AList ) { return ( AList < T > ) elements ; } if ( elements instanceof List ) { return create ( ( List < T > ) elements ) ; } AList < T > result = nil ( ) ; for ( T el : elements ) { result = result . cons ( el ) ; } return result . reverse ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an AList based on the contents of an existing <code > java . util . List< / code > copying its content . [CODESPLIT] public static < T > AList < T > create ( List < T > elements ) { AList < T > result = nil ( ) ; for ( int i = elements . size ( ) - 1 ; i >= 0 ; i -- ) { result = result . cons ( elements . get ( i ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an AList from a given list of elements . [CODESPLIT] @ SafeVarargs public static < T > AList < T > create ( T ... elements ) { return create ( Arrays . asList ( elements ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of this AList with elements in reversed order . [CODESPLIT] public AList < T > reverse ( ) { AList < T > remaining = this ; AList < T > result = nil ( ) ; while ( ! remaining . isEmpty ( ) ) { result = result . cons ( remaining . head ( ) ) ; remaining = remaining . tail ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > java . util . Iterator< / code > over this AList s elements allowing ALists to be used with Java s <code > for ( ... : list ) < / code > syntax introduced in version 1 . 5 . [CODESPLIT] @ Override public Iterator < T > iterator ( ) { return new Iterator < T > ( ) { AList < T > pos = AList . this ; @ Override public boolean hasNext ( ) { return pos . nonEmpty ( ) ; } @ Override public T next ( ) { final T result = pos . head ( ) ; pos = pos . tail ( ) ; return result ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] public static < T > Set < T > createSet ( Iterator < T > elements ) { final Set < T > result = new HashSet <> ( ) ; while ( elements . hasNext ( ) ) result . add ( elements . next ( ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] public static < T > Set < T > createSet ( Iterable < T > elements ) { return createSet ( elements . iterator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] public static < T , U , E extends Throwable > Set < U > createSet ( Iterator < T > elements , AFunction1 < T , U , E > f ) throws E { final Set < U > result = new HashSet <> ( ) ; while ( elements . hasNext ( ) ) result . add ( f . apply ( elements . next ( ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { [CODESPLIT] public static < T , U , E extends Throwable > Set < U > createSet ( Iterable < T > elements , AFunction1 < T , U , E > f ) throws E { return createSet ( elements . iterator ( ) , f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of a collection separating elements with a <code > separator< / code > and putting <code > prefix< / code > before the first and a <code > suffix< / code > after the last element . [CODESPLIT] public static String mkString ( Iterable < ? > iterable , String prefix , String separator , String suffix ) { final StringBuilder result = new StringBuilder ( prefix ) ; boolean first = true ; for ( Object o : iterable ) { if ( first ) { first = false ; } else { result . append ( separator ) ; } result . append ( o ) ; } result . append ( suffix ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an element of a collection that matches a predicate if any or AOption . none () if there is no match . [CODESPLIT] public static < T , E extends Throwable > AOption < T > find ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { for ( T o : coll ) { if ( pred . apply ( o ) ) { return AOption . some ( o ) ; } } return AOption . none ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches a predicate against collection elements and returns true iff it matches them all . [CODESPLIT] public static < T , E extends Throwable > boolean forAll ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { for ( T o : coll ) { if ( ! pred . apply ( o ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a transformation function to all elements of a collection creating a new collection from the results . [CODESPLIT] public static < T , X , E extends Throwable > List < X > map ( List < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { final List < X > result = createEmptyListOfType ( coll , true ) ; for ( T o : coll ) { result . add ( f . apply ( o ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a transformation function to all elements of a collection creating a new collection from the results . [CODESPLIT] public static < T , X , E extends Throwable > Set < X > map ( Set < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { final Set < X > result = createEmptySetOfType ( coll , true ) ; for ( T o : coll ) { result . add ( f . apply ( o ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as <code > map () < / code > except that the transformation function returns collections and all the results are flattened into a single collection . [CODESPLIT] public static < T , X , E extends Throwable > Collection < X > flatMap ( Iterable < T > coll , AFunction1 < ? super T , ? extends Iterable < X > , E > f ) throws E { final List < X > result = new ArrayList <> ( ) ; for ( T o : coll ) { for ( X el : f . apply ( o ) ) { result . add ( el ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as <code > map () < / code > except that the transformation function returns collections and all the results are flattened into a single collection . [CODESPLIT] public static < T , X , E extends Throwable > Set < X > flatMapSet ( Iterable < T > coll , AFunction1 < ? super T , ? extends Iterable < X > , E > f ) throws E { final Set < X > result = new HashSet <> ( ) ; for ( T o : coll ) { for ( X el : f . apply ( o ) ) { result . add ( el ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a collection of collections and creates a new collection from the elements leaving out the innermost level of collection . [CODESPLIT] public static < T > Collection < T > flatten ( Iterable < ? extends Iterable < T > > coll ) { final List < T > result = new ArrayList <> ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a collection of collections and creates a new collection from the elements leaving out the innermost level of collection . [CODESPLIT] public static < T > List < T > flattenList ( Iterable < ? extends Iterable < T > > coll ) { final List < T > result = new ArrayList <> ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes a collection of collections and creates a new collection from the elements leaving out the innermost level of collection . [CODESPLIT] public static < T > Set < T > flattenSet ( Iterable < ? extends Iterable < T > > coll ) { final Set < T > result = new HashSet <> ( ) ; for ( Iterable < T > o : coll ) { for ( T el : o ) { result . add ( el ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a transformation function to all elements of a collection where the partial function is defined for . Creates a new collection of the transformed elements only . So the number of result elements may be less than the number of elements in the source collection . [CODESPLIT] public static < T , X , E extends Throwable > Collection < X > collect ( Iterable < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { final List < X > result = new ArrayList <> ( ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a transformation function to all elements of a collection where the partial function is defined for . Creates a new collection of the transformed elements only . So the number of result elements may be less than the number of elements in the source collection . [CODESPLIT] public static < T , X , E extends Throwable > List < X > collect ( List < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { final List < X > result = createEmptyListOfType ( coll , true ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a transformation function to all elements of a collection where the partial function is defined for . Creates a new collection of the transformed elements only . So the number of result elements may be less than the number of elements in the source collection . [CODESPLIT] public static < T , X , E extends Throwable > Set < X > collect ( Set < T > coll , APartialFunction < ? super T , ? extends X , E > pf ) throws E { final Set < X > result = createEmptySetOfType ( coll , true ) ; for ( T o : coll ) { if ( pf . isDefinedAt ( o ) ) { result . add ( pf . apply ( o ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches all elements of a collection against a predicate creating a new collection from those that match . [CODESPLIT] public static < T , E extends Throwable > Collection < T > filter ( Iterable < T > coll , APredicate < ? super T , E > pred ) throws E { final List < T > result = new ArrayList <> ( ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches all elements of a collection against a predicate creating a new collection from those that match . [CODESPLIT] public static < T , E extends Throwable > List < T > filter ( List < T > coll , APredicate < ? super T , E > pred ) throws E { final List < T > result = createEmptyListOfType ( coll , false ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches all elements of a collection against a predicate creating a new collection from those that match . [CODESPLIT] public static < T , E extends Throwable > Set < T > filter ( Set < T > coll , APredicate < ? super T , E > pred ) throws E { final Set < T > result = createEmptySetOfType ( coll , false ) ; for ( T o : coll ) { if ( pred . apply ( o ) ) { result . add ( o ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Map from a collection . Each element s key is determined by applying a function to the element . All elements with the same key are stored as that key s value in the returned Map . [CODESPLIT] public static < T , X , E extends Throwable > Map < X , Collection < T > > groupBy ( Iterable < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { final Map < X , Collection < T > > result = new HashMap <> ( ) ; for ( T o : coll ) { final X key = f . apply ( o ) ; Collection < T > perKey = result . get ( key ) ; if ( perKey == null ) { perKey = new ArrayList <> ( ) ; result . put ( key , perKey ) ; } perKey . add ( o ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Map from a collection . Each element s key is determined by applying a function to the element . All elements with the same key are stored as that key s value in the returned Map . [CODESPLIT] public static < T , X , E extends Throwable > Map < X , List < T > > groupBy ( List < T > coll , AFunction1 < ? super T , ? extends X , E > f ) throws E { final Map < X , List < T > > result = new HashMap <> ( ) ; for ( T o : coll ) { final X key = f . apply ( o ) ; List < T > perKey = result . get ( key ) ; if ( perKey == null ) { perKey = createEmptyListOfType ( coll , false ) ; result . put ( key , perKey ) ; } perKey . add ( o ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a binary operator to a start value and all elements of this sequence going left to right . [CODESPLIT] public static < T , R , E extends Throwable > R foldLeft ( Iterable < T > coll , R startValue , AFunction2 < R , ? super T , R , E > f ) throws E { R result = startValue ; for ( T e : coll ) { result = f . apply ( result , e ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a binary operator to a start value and all elements of this list going left to right . [CODESPLIT] public static < T , R , E extends Throwable > R foldRight ( List < T > coll , R startValue , AFunction2 < R , ? super T , R , E > f ) throws E { R result = startValue ; ListIterator < T > i = coll . listIterator ( coll . size ( ) ) ; while ( i . hasPrevious ( ) ) { result = f . apply ( result , i . previous ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of an <code > Iterable< / code > into an ( immutable ) <code > ACollection< / code > instance . Subsequent changes to the underlying collection have no effect on the returned <code > ACollection< / code > instance . <p > [CODESPLIT] public static < T > ACollectionWrapper < T > asACollectionCopy ( Collection < T > c ) { return asACollectionView ( new ArrayList <> ( c ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the content of a <code > java . util . Collection< / code > in an <code > ACollection< / code > instance . While the returned instance itself has no mutator methods changes to the underlying collection are reflected in the wrapping <code > ACollection< / code > instance . <p > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > ACollectionWrapper < T > asACollectionView ( Collection < T > c ) { return new ACollectionWrapper ( c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps the content of a <code > java . util . Set< / code > in an <code > ASet< / code > instance . While the returned instance itself has no mutator methods changes to the underlying collection are reflected in the wrapping <code > ASet< / code > instance . <p > [CODESPLIT] public static < T > ASetWrapper < T > asASetView ( Collection < T > c ) { if ( c instanceof Set ) { return new ASetWrapper <> ( ( Set < T > ) c ) ; } return new ASetWrapper <> ( new HashSet <> ( c ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the content of an array into an ( immutable ) <code > ACollection< / code > instance . Subsequent changes to the underlying array have no effect on the returned <code > ACollection< / code > instance . <p > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > AArrayWrapper < T > asArrayCopy ( T [ ] c ) { final T [ ] newArray = ( T [ ] ) Array . newInstance ( c . getClass ( ) . getComponentType ( ) , c . length ) ; System . arraycopy ( c , 0 , newArray , 0 , c . length ) ; return new AArrayWrapper <> ( newArray ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > Collection< / code > with the exact same elements as an <code > Iterable< / code > copying only if the parameter is not a collection . [CODESPLIT] public static < T > List < T > asJavaUtilList ( Iterable < T > c ) { if ( c instanceof List ) { return ( List < T > ) c ; } return asJavaUtilCollection ( c . iterator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a <code > Collection< / code > with the exact same elements as an <code > Iterable< / code > copying only if the parameter is not a collection . [CODESPLIT] public static < T > Collection < T > asJavaUtilCollection ( Iterable < T > c ) { if ( c instanceof Collection ) { return ( Collection < T > ) c ; } return asJavaUtilCollection ( c . iterator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies the elements from an <code > Iterator< / code > into a <code > Collection< / code > . [CODESPLIT] public static < T > List < T > asJavaUtilCollection ( Iterator < T > c ) { final List < T > result = new ArrayList <> ( ) ; while ( c . hasNext ( ) ) { result . add ( c . next ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AHashMap instance with default ( i . e . equals - based ) equalityForEquals initializing it from the contents of a given <code > java . util . Map< / code > . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static < K , V > AHashMap < K , V > fromJavaUtilMap ( Map < K , V > map ) { return fromJavaUtilMap ( DEFAULT_EQUALITY , map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AHashMap instance for a given equalityForEquals initializing it from the contents of a given <code > java . util . Map< / code > . [CODESPLIT] public static < K , V > AHashMap < K , V > fromJavaUtilMap ( AEquality equality , Map < K , V > map ) { AHashMap < K , V > result = empty ( equality ) ; for ( Map . Entry < K , V > entry : map . entrySet ( ) ) { result = result . updated ( entry . getKey ( ) , entry . getValue ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AHashMap instance with default ( i . e . equals - based ) equalityForEquals initializing it from separate keys and values collections . Both collections are iterated exactly once and are expected to have the same size . [CODESPLIT] public static < K , V > AHashMap < K , V > fromKeysAndValues ( Iterable < K > keys , Iterable < V > values ) { return fromKeysAndValues ( DEFAULT_EQUALITY , keys , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AHashMap instance with default ( i . e . equals - based ) equalityForEquals initializing it from a collection of keys and a function . For each element of the <code > keys< / code > collection the function is called once to determine the corresponding value and the pair is then stored in the map . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static < K , V , E extends Throwable > AHashMap < K , V > fromKeysAndFunction ( Iterable < K > keys , AFunction1 < ? super K , ? extends V , E > f ) throws E { return fromKeysAndFunction ( DEFAULT_EQUALITY , keys , f ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AHashMap instance with a given equalityForEquals initializing it from a collection of keys and a function . For each element of the <code > keys< / code > collection the function is called once to determine the corresponding value and the pair is then stored in the map . [CODESPLIT] public static < K , V , E extends Throwable > AHashMap < K , V > fromKeysAndFunction ( AEquality equality , Iterable < K > keys , AFunction1 < ? super K , ? extends V , E > f ) throws E { final Iterator < K > ki = keys . iterator ( ) ; AHashMap < K , V > result = AHashMap . empty ( equality ) ; while ( ki . hasNext ( ) ) { final K key = ki . next ( ) ; final V value = f . apply ( key ) ; result = result . updated ( key , value ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "very internal method . It assumes hash0 ! = hash1 . [CODESPLIT] private static < K , V > HashTrieMap < K , V > mergeLeafMaps ( int hash0 , AHashMap < K , V > elem0 , int hash1 , AHashMap < K , V > elem1 , int level , int size , AEquality equality ) { final int index0 = ( hash0 >>> level ) & 0x1f ; final int index1 = ( hash1 >>> level ) & 0x1f ; if ( index0 != index1 ) { final int bitmap = ( 1 << index0 ) | ( 1 << index1 ) ; final AHashMap < K , V > [ ] elems = createArray ( 2 ) ; if ( index0 < index1 ) { elems [ 0 ] = elem0 ; elems [ 1 ] = elem1 ; } else { elems [ 0 ] = elem1 ; elems [ 1 ] = elem0 ; } return new HashTrieMap <> ( bitmap , elems , size , equality ) ; } else { final AHashMap < K , V > [ ] elems = createArray ( 1 ) ; final int bitmap = ( 1 << index0 ) ; // try again, based on the elems [ 0 ] = mergeLeafMaps ( hash0 , elem0 , hash1 , elem1 , level + LEVEL_INCREMENT , size , equality ) ; return new HashTrieMap <> ( bitmap , elems , size , equality ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new task to the top of the shared queue incrementing top . [CODESPLIT] @ Override public void push ( Runnable task ) { final long _base ; final long _top ; synchronized ( PUSH_LOCK ) { _base = base ; _top = top ; if ( _top == _base + mask ) { throw new RejectedExecutionExceptionWithoutStacktrace ( \"Shared queue overflow\" ) ; } tasks [ asArrayIndex ( _top ) ] = task ; // volatile put for atomicity and to ensure ordering wrt. storing the task UNSAFE . putLongVolatile ( this , OFFS_TOP , _top + 1 ) ; } pool . onAvailableTask ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new task to the top of the localQueue incrementing top . This is only ever called from the owning thread . [CODESPLIT] void push ( Runnable task ) { final long _base = UNSAFE . getLongVolatile ( this , OFFS_BASE ) ; // read base first (and only once) final long _top = top ; if ( _top == _base + mask ) { throw new RejectedExecutionExceptionWithoutStacktrace ( \"local queue overflow\" ) ; } tasks [ asArrayindex ( _top ) ] = task ; // 'top' is only ever modified by the owning thread, so we need no CAS here. Storing 'top' with volatile semantics publishes the task and ensures that changes to the task //  can never overtake changes to 'top' wrt visibility. UNSAFE . putLongVolatile ( this , OFFS_TOP , _top + 1 ) ; // Notify pool only for the first added item per queue. if ( _top - _base <= 1 ) { pool . onAvailableTask ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch ( and remove ) a task from the top of the queue i . e . LIFO semantics . This is only ever called from the owning thread removing ( or at least reducing ) contention at the top of the queue : No other thread operates there . [CODESPLIT] Runnable popLifo ( ) { final long _top = top ; final Runnable result = tasks [ asArrayindex ( _top - 1 ) ] ; if ( result == null ) { // The queue is empty. It is possible for the queue to be empty even if the previous unprotected read does not return null, but //  it will only ever return null if the queue really is empty: New entries are only added by the owning thread, and this method //  'popLifo()' is also only ever called by the owning thread. return null ; } if ( ! UNSAFE . compareAndSwapObject ( tasks , taskOffset ( _top - 1 ) , result , null ) ) { // The CAS operation failing means that another thread pulled the top-most item from the queue, so the queue is now definitely //  empty. It also null'ed out the task in the array if it was previously available, allowing to to be GC'ed when processing is //  finished. return null ; } // Since 'result' is not null, and was not previously consumed by another thread, we can safely consume it --> decrement 'top' UNSAFE . putOrderedLong ( this , OFFS_TOP , _top - 1 ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetch ( and remove ) a task from the bottom of the queue i . e . FIFO semantics . This method can be called by any thread . [CODESPLIT] Runnable popFifo ( ) { long _base , _top ; while ( true ) { // reading 'base' with volatile semantics emits the necessary barriers to ensure visibility of 'top' _base = UNSAFE . getLongVolatile ( this , OFFS_BASE ) ; _top = top ; if ( _base == _top ) { // Terminate the loop: the queue is empty. //TODO verify that Hotspot optimizes this kind of return-from-the-middle well return null ; } // a regular read is OK here: 'push()' emits a store barrier after storing the task, 'popLifo()' modifies it with CAS, and 'popFifo()' does //  a volatile read of 'base' before reading the task final Runnable result = tasks [ asArrayindex ( _base ) ] ; // result == null means that another thread concurrently fetched the task from under our nose. // checking _base against a re-read 'base' with volatile semantics avoids wrap-around race - 'base' could have incremented by a multiple of the queue's size between //   our first reading it and fetching the task at that offset, which would cause the increment inside the following if block to significantly decrement it and //   wreak havoc. // CAS ensures that only one thread gets the task, and allows GC when processing is finished if ( result != null && _base == UNSAFE . getLongVolatile ( this , OFFS_BASE ) && UNSAFE . compareAndSwapObject ( tasks , taskOffset ( _base ) , result , null ) ) { UNSAFE . putLongVolatile ( this , OFFS_BASE , _base + 1 ) ; //TODO is 'putOrdered' sufficient? return result ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a convenience method that creates an AOption based on Java conventions . [CODESPLIT] public static < T > AOption < T > fromNullable ( T nullable ) { return nullable != null ? some ( nullable ) : AOption . < T > none ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an ALongHashMap initialized from separate keys and values collections . Both collections are iterated exactly once and are expected to have the same size . [CODESPLIT] public static < V > ALongHashMap < V > fromKeysAndValues ( Iterable < ? extends Number > keys , Iterable < V > values ) { final Iterator < ? extends Number > ki = keys . iterator ( ) ; final Iterator < V > vi = values . iterator ( ) ; ALongHashMap < V > result = ALongHashMap . empty ( ) ; while ( ki . hasNext ( ) ) { final Number key = ki . next ( ) ; final V value = vi . next ( ) ; result = result . updated ( key . longValue ( ) , value ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an ALongHashMap instance initialized from a collection of keys and a function . For each element of the <code > keys< / code > collection the function is called once to determine the corresponding value and the pair is then stored in the map . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static < K extends Number , V , E extends Throwable > ALongHashMap < V > fromKeysAndFunction ( Iterable < K > keys , AFunction1 < ? super K , ? extends V , E > f ) throws E { final Iterator < K > ki = keys . iterator ( ) ; ALongHashMap < V > result = empty ( ) ; while ( ki . hasNext ( ) ) { final K key = ki . next ( ) ; final V value = f . apply ( key ) ; result = result . updated ( key . longValue ( ) , value ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "very internal method . It assumes hash0 ! = hash1 . [CODESPLIT] private static < V > LongHashTrieMap < V > mergeLeafMaps ( long hash0 , ALongHashMap < V > elem0 , long hash1 , ALongHashMap < V > elem1 , int level , int size ) { final int index0 = ( int ) ( ( hash0 >>> level ) & 0x3f ) ; final int index1 = ( int ) ( ( hash1 >>> level ) & 0x3f ) ; if ( index0 != index1 ) { final long bitmap = ( 1L << index0 ) | ( 1L << index1 ) ; final ALongHashMap < V > [ ] elems = createArray ( 2 ) ; if ( index0 < index1 ) { elems [ 0 ] = elem0 ; elems [ 1 ] = elem1 ; } else { elems [ 0 ] = elem1 ; elems [ 1 ] = elem0 ; } return new LongHashTrieMap <> ( bitmap , elems , size ) ; } else { final ALongHashMap < V > [ ] elems = createArray ( 1 ) ; final long bitmap = ( 1L << index0 ) ; // try again, based on the elems [ 0 ] = mergeLeafMaps ( hash0 , elem0 , hash1 , elem1 , level + LEVEL_INCREMENT , size ) ; return new LongHashTrieMap <> ( bitmap , elems , size ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an empty AListMap instance with a given equalityForEquals . Calling this factory method instead of the constructor allows internal reuse of empty map instances since they are immutable . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < K , V > AListMap < K , V > empty ( AEquality equality ) { if ( equality == AEquality . EQUALS ) return ( AListMap < K , V > ) emptyEquals ; if ( equality == AEquality . IDENTITY ) return ( AListMap < K , V > ) emptyIdentity ; return new AListMap <> ( equality ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AListMap instance with default ( i . e . equals - based ) equalityForEquals initializing it from separate keys and values collections . Both collections are iterated exactly once and are expected to have the same size . [CODESPLIT] public static < K , V > AListMap < K , V > fromKeysAndValues ( Iterable < ATuple2 < K , V > > elements ) { return fromKeysAndValues ( DEFAULT_EQUALITY , elements ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AHashMap instance with a given equalityForEquals initializing it from separate keys and values collections . Both collections are iterated exactly once and are expected to have the same size . [CODESPLIT] public static < K , V > AListMap < K , V > fromKeysAndValues ( AEquality equality , Iterable < ATuple2 < K , V > > elements ) { AListMap < K , V > result = empty ( equality ) ; for ( ATuple2 < K , V > el : elements ) { result = result . updated ( el . _1 , el . _2 ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an AListMap instance with a given equalityForEquals initializing it from separate keys and values collections . Both collections are iterated exactly once and are expected to have the same size . [CODESPLIT] public static < K , V > AListMap < K , V > fromKeysAndValues ( AEquality equality , Iterable < K > keys , Iterable < V > values ) { final Iterator < K > ki = keys . iterator ( ) ; final Iterator < V > vi = values . iterator ( ) ; AListMap < K , V > result = empty ( equality ) ; while ( ki . hasNext ( ) ) { final K key = ki . next ( ) ; final V value = vi . next ( ) ; result = result . updated ( key , value ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method combines two separate sub - trees into a single ( balanced ) tree . It assumes that both subtrees are balanced and that all elements in tl are smaller than all elements in tr . This situation occurs when a node is deleted and its child nodes must be combined into a resulting tree . [CODESPLIT] private static < K , V > Tree < K , V > append ( Tree < K , V > tl , Tree < K , V > tr ) { if ( tl == null ) return tr ; if ( tr == null ) return tl ; if ( isRedTree ( tl ) && isRedTree ( tr ) ) { final Tree < K , V > bc = append ( tl . right , tr . left ) ; return isRedTree ( bc ) ? new RedTree <> ( bc . key , bc . value , new RedTree <> ( tl . key , tl . value , tl . left , bc . left ) , new RedTree <> ( tr . key , tr . value , bc . right , tr . right ) ) : new RedTree <> ( tl . key , tl . value , tl . left , new RedTree <> ( tr . key , tr . value , bc , tr . right ) ) ; } if ( isBlackTree ( tl ) && isBlackTree ( tr ) ) { final Tree < K , V > bc = append ( tl . right , tr . left ) ; return isRedTree ( bc ) ? new RedTree <> ( bc . key , bc . value , new BlackTree <> ( tl . key , tl . value , tl . left , bc . left ) , new BlackTree <> ( tr . key , tr . value , bc . right , tr . right ) ) : balanceLeft ( tl . key , tl . value , tl . left , new BlackTree <> ( tr . key , tr . value , bc , tr . right ) ) ; } if ( isRedTree ( tr ) ) { return new RedTree <> ( tr . key , tr . value , append ( tl , tr . left ) , tr . right ) ; } if ( isRedTree ( tl ) ) { return new RedTree <> ( tl . key , tl . value , tl . left , append ( tl . right , tr ) ) ; } throw new IllegalStateException ( \"invariant violation: unmatched tree on append: \" + tl + \", \" + tr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------- shutdown handling below this point --------------------- [CODESPLIT] @ Override public void shutdown ( ) { if ( poolWithAdmin == null ) throw new UnsupportedOperationException ( \"shutdown only supported for AThreadPoolWithAdmin\" ) ; shutdown . set ( AFuture . lift ( AThreadPool . SYNC_THREADPOOL , poolWithAdmin . shutdown ( AThreadPoolWithAdmin . ShutdownMode . ExecuteSubmitted ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------------------------------------- collection transformations [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected < X > ASet < X > createInternal ( Iterable < X > elements ) { AMap result = inner . clear ( ) ; for ( X el : elements ) { result = result . updated ( el , Boolean . TRUE ) ; } return ( ASet ) wrapAsSet ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "There is usually a performance gain to be had by overriding this default implementation [CODESPLIT] @ Override public Set < K > keySet ( ) { return new AbstractSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new Iterator < K > ( ) { final Iterator < AMapEntry < K , V > > it = inner . iterator ( ) ; @ Override public boolean hasNext ( ) { return it . hasNext ( ) ; } @ Override public K next ( ) { return it . next ( ) . getKey ( ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } @ Override public int size ( ) { return inner . size ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO save all included ramls of a raml . when any of them changes reparse! [CODESPLIT] public RamlModelResult loadRaml ( String name ) { final File file = new File ( CACHE_DIR , escaped ( loader . config ( ) ) + \"-\" + escaped ( simpleName ( name ) ) + \".braml\" ) ; if ( ! file . exists ( ) ) { return parseAndSave ( loader , name , file ) ; } final InputStream in = loader . fetchResource ( name , file . lastModified ( ) ) ; if ( in != null ) { final byte [ ] data = loadedData ( name , in ) ; return parseAndSave ( new PreloadedLoader ( loader , name , data ) , name , file ) ; } try { return load ( file ) ; } catch ( IOException | ClassNotFoundException e ) { return parseAndSave ( loader , name , file ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- > hack to undo this [CODESPLIT] private String normalizeResourceName ( String name ) { if ( name . startsWith ( \"//\" ) ) { return \"classpath:\" + name ; } final int firstProtocol = name . indexOf ( \"://\" ) ; final int secondProtocol = name . indexOf ( \"://\" , firstProtocol + 1 ) ; final int protocol = secondProtocol < 0 ? firstProtocol : secondProtocol ; final int endOfFirst = name . lastIndexOf ( \"/\" , protocol ) ; if ( endOfFirst >= 0 ) { return name . substring ( endOfFirst + 1 ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Marshals the specified user - defined value type object to single XML value string representation . [CODESPLIT] @ Override public String marshal ( BoundType v ) throws Exception { Class < ? extends Object > type = v . getClass ( ) ; if ( ! Types . isUserDefinedValueType ( type ) ) { throw new IllegalArgumentException ( \"Type [\" + type + \"] must be an user-defined value type; \" + \"@XmlJavaTypeAdapter(ValueTypeXmlAdapter.class) \" + \"can be annotated to user-defined value type and field only\" ) ; } Converter converter = ConvertUtils . lookup ( type ) ; if ( ( converter != null && converter instanceof AbstractConverter ) ) { String string = ( String ) ConvertUtils . convert ( v , String . class ) ; if ( string != null ) { return string ; } } return v . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a new { @code XMLRequest } from the current { @code WebContext } . [CODESPLIT] public void from ( WebContext context ) { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; try { DocumentBuilder builder = factory . newDocumentBuilder ( ) ; Document document = builder . parse ( new InputSource ( context . request ( ) . getReader ( ) ) ) ; node = document . getDocumentElement ( ) ; } catch ( Exception e ) { logger . warn ( \"Cannot parse XML document into DOM object\" , e ) ; throw new UncheckedException ( e ) ; } super . from ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Web endpoint method parameter value from the current HTTP request body sent as XML format . This method supports the following parameter declaration independently . Other than them are the same as { @link AbstractRequest } . <ol > <li > Named collection of user - defined object type< / li > <li > Named user - defined object type< / li > < / ol > [CODESPLIT] @ Override protected Object body ( Type type , String name ) { return body ( type , name , node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the specified object to the specified type . The object to be converted must be a { @code Node } that has no child or this method return <code > null< / code > . [CODESPLIT] @ Override protected Object convert ( Object object , Class < ? > type ) { if ( object instanceof Node ) { Node node = ( Node ) object ; NodeList nodes = node . getChildNodes ( ) ; Text text = null ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node child = nodes . item ( i ) ; if ( child . getNodeType ( ) == Node . TEXT_NODE ) { text = ( Text ) child ; } } if ( text == null ) { logger . warn ( \"Parameter [\" + object + \"] cannot be converted to [\" + type + \"]; Converted 'object' must have one child [\" + Text . class + \"] node\" ) ; return null ; } return super . convert ( text . getNodeValue ( ) , type ) ; } else { logger . warn ( \"Parameter [\" + object + \"] cannot be converted to [\" + type + \"]; Converted 'object' must be a [\" + Node . class + \"]\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends <code > char< / code > array to buffer . [CODESPLIT] public FastCharBuffer append ( char [ ] array , int off , int len ) { int end = off + len ; if ( ( off < 0 ) || ( len < 0 ) || ( end > array . length ) ) { throw new IndexOutOfBoundsException ( ) ; } if ( len == 0 ) { return this ; } int newSize = size + len ; int remaining = len ; if ( currentBuffer != null ) { // first try to fill current buffer int part = Math . min ( remaining , currentBuffer . length - offset ) ; System . arraycopy ( array , end - remaining , currentBuffer , offset , part ) ; remaining -= part ; offset += part ; size += part ; } if ( remaining > 0 ) { // still some data left // ask for new buffer needNewBuffer ( newSize ) ; // then copy remaining // but this time we are sure that it will fit int part = Math . min ( remaining , currentBuffer . length - offset ) ; System . arraycopy ( array , end - remaining , currentBuffer , offset , part ) ; offset += part ; size += part ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates <code > char< / code > subarray from buffered content . [CODESPLIT] public char [ ] toArray ( int start , int len ) { int remaining = len ; int pos = 0 ; char [ ] array = new char [ len ] ; if ( len == 0 ) { return array ; } int i = 0 ; while ( start >= buffers [ i ] . length ) { start -= buffers [ i ] . length ; i ++ ; } while ( i < buffersCount ) { char [ ] buf = buffers [ i ] ; int c = Math . min ( buf . length - start , remaining ) ; System . arraycopy ( buf , start , array , pos , c ) ; pos += c ; remaining -= c ; if ( remaining == 0 ) { break ; } start = 0 ; i ++ ; } return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > char< / code > element at given index . [CODESPLIT] public char get ( int index ) { if ( ( index >= size ) || ( index < 0 ) ) { throw new IndexOutOfBoundsException ( ) ; } int ndx = 0 ; while ( true ) { char [ ] b = buffers [ ndx ] ; if ( index < b . length ) { return b [ index ] ; } ndx ++ ; index -= b . length ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns sub sequence . [CODESPLIT] public CharSequence subSequence ( int start , int end ) { int len = end - start ; return new StringBuilder ( len ) . append ( toArray ( start , len ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends string content to buffer . [CODESPLIT] public FastCharBuffer append ( String string ) { int len = string . length ( ) ; if ( len == 0 ) { return this ; } int end = offset + len ; int newSize = size + len ; int remaining = len ; int start = 0 ; if ( currentBuffer != null ) { // first try to fill current buffer int part = Math . min ( remaining , currentBuffer . length - offset ) ; string . getChars ( 0 , part , currentBuffer , offset ) ; remaining -= part ; offset += part ; size += part ; start += part ; } if ( remaining > 0 ) { // still some data left // ask for new buffer needNewBuffer ( newSize ) ; // then copy remaining // but this time we are sure that it will fit int part = Math . min ( remaining , currentBuffer . length - offset ) ; string . getChars ( start , start + part , currentBuffer , offset ) ; offset += part ; size += part ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates binary search wrapper over a list of comparable elements . [CODESPLIT] public static < T extends Comparable > BinarySearch < T > forList ( final List < T > list ) { return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { \"unchecked\" } ) protected int compare ( int index , T element ) { return list . get ( index ) . compareTo ( element ) ; } @ Override protected int getLastIndex ( ) { return list . size ( ) - 1 ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates binary search wrapper over a list with given comparator . [CODESPLIT] public static < T > BinarySearch < T > forList ( final List < T > list , final Comparator < T > comparator ) { return new BinarySearch < T > ( ) { @ Override @ SuppressWarnings ( { \"unchecked\" } ) protected int compare ( int index , T element ) { return comparator . compare ( list . get ( index ) , element ) ; } @ Override protected int getLastIndex ( ) { return list . size ( ) - 1 ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds very first index of given element in inclusive index range . Returns negative value if element is not found . [CODESPLIT] public int findFirst ( E o , int low , int high ) { int ndx = - 1 ; while ( low <= high ) { int mid = ( low + high ) >>> 1 ; int delta = compare ( mid , o ) ; if ( delta < 0 ) { low = mid + 1 ; } else { if ( delta == 0 ) { ndx = mid ; } high = mid - 1 ; } } if ( ndx == - 1 ) { return - ( low + 1 ) ; } return ndx ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serializes the specified user - defined value type object to <code > JsonPrimitive< / code > representation . [CODESPLIT] public JsonElement serialize ( T src , Type typeOfSrc , JsonSerializationContext context ) { Class < ? > type = Types . getRawType ( typeOfSrc ) ; Converter converter = ConvertUtils . lookup ( type ) ; if ( ( converter != null && converter instanceof AbstractConverter ) ) { String string = ( String ) ConvertUtils . convert ( src , String . class ) ; if ( string != null ) { return new JsonPrimitive ( string ) ; } } return new JsonPrimitive ( src . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads the class of the specified name from the specified { @code InputStream } and returns loaded class representation as { @code javassist . CtClass } . [CODESPLIT] @ Override protected CtClass load ( String clazz , InputStream stream ) { try { return pool . makeClass ( stream ) ; } catch ( Exception e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the classes that is annotated by the specified annotation as { @code javassist . CtClass } . [CODESPLIT] @ Override public Set < CtClass > resolveByAnnotation ( final Class < ? extends Annotation > annotation ) throws IOException { Matcher < CtClass > matcher = new Matcher < CtClass > ( ) { @ Override public boolean matches ( CtClass ctClass ) { try { for ( Object object : ctClass . getAnnotations ( ) ) { Annotation a = ( Annotation ) object ; if ( a . annotationType ( ) . equals ( annotation ) ) { return true ; } } } catch ( Exception e ) { } ctClass . detach ( ) ; return false ; } } ; return resolve ( matcher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the classes that implements the specified interface as { @code javassist . CtClass } . [CODESPLIT] @ Override public Set < CtClass > resolveByInterface ( final Class < ? > interfaceClass ) throws IOException { Matcher < CtClass > matcher = new Matcher < CtClass > ( ) { @ Override public boolean matches ( CtClass ctClass ) { try { for ( CtClass c : ctClass . getInterfaces ( ) ) { if ( c . getName ( ) . equals ( interfaceClass . getName ( ) ) ) { return true ; } } CtClass superclass = ctClass . getSuperclass ( ) ; if ( superclass != null ) { return matches ( superclass ) ; } } catch ( Exception e ) { } ctClass . detach ( ) ; return false ; } } ; return resolve ( matcher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves the classes that contains the specified name as { @code javassist . CtClass } . [CODESPLIT] @ Override public Set < CtClass > resolveByName ( final String name ) throws IOException { Matcher < CtClass > matcher = new Matcher < CtClass > ( ) { @ Override public boolean matches ( CtClass ctClass ) { if ( ctClass . getName ( ) . contains ( name ) ) { return true ; } ctClass . detach ( ) ; return false ; } } ; return resolve ( matcher ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds URL routing pattern . The routing pattern can be specified as URI template format and the path variables can be passed to Web endpoint method like this : <pre > { @code @Override } public void routing ( Routing routing ) { routing . add ( / user / { id } / * User . class handle ) ; } < / pre > <pre > { @code } public class User { [CODESPLIT] public void add ( String pattern , Class < ? > endpoint , String method ) { add ( null , pattern , endpoint , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds URL routing pattern . The routing pattern can be specified as URI template format and the path variables can be passed to Web endpoint method like this : <pre > { @code @Override } public void routing ( Routing routing ) { routing . add ( / user / { id } / * User . class handle ) ; } < / pre > <pre > { @code } public class User { [CODESPLIT] public void add ( Verb verb , String pattern , Class < ? > endpoint , String method ) { Preconditions . checkArgument ( pattern != null , \"Parameter 'pattern' must not be [\" + pattern + \"]\" ) ; Preconditions . checkArgument ( pattern . startsWith ( \"/\" ) , \"Parameter 'pattern' must start with [/]\" ) ; Preconditions . checkArgument ( endpoint != null , \"Parameter 'endpoint' must not be [\" + endpoint + \"]\" ) ; Preconditions . checkArgument ( method != null , \"Parameter 'method' must not be [\" + method + \"]\" ) ; for ( Method m : endpoint . getMethods ( ) ) { if ( m . getName ( ) . equals ( method ) ) { URITemplate template = null ; if ( templates . containsKey ( pattern ) ) { template = templates . get ( pattern ) ; } else { template = new URITemplate ( pattern ) ; templates . put ( pattern , template ) ; } Map < Verb , Method > methods = null ; if ( routes . containsKey ( template ) ) { methods = routes . get ( template ) ; } else { methods = new HashMap < Verb , Method > ( ) ; routes . put ( template , methods ) ; } methods . put ( verb , m ) ; return ; } } throw new IllegalArgumentException ( \"Method [\" + method + \"] does not exist on Web endpoint [\" + endpoint + \"]\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds ignore - routing patterns . The requested URL that matches to the patterns is not handled by Bootleg . <code > * < / code > ( meta character ) can be used in the pattern ( e . g . <code > * . png< / code > ) . <br > <b > Note< / b > : Ignore - routing patterns are in preference to routing patterns . [CODESPLIT] public void ignore ( String ... patterns ) { Preconditions . checkArgument ( patterns != null , \"Parameter 'patterns' must not be [\" + patterns + \"]\" ) ; for ( String pattern : patterns ) { Preconditions . checkArgument ( pattern != null && ! pattern . isEmpty ( ) , \"Parameter 'patterns' must not include [null] or empty entry\" ) ; ignores . add ( Pattern . compile ( pattern . replaceAll ( \"\\\\.\" , Matcher . quoteReplacement ( \"\\\\.\" ) ) . replaceAll ( \"\\\\*\" , \".*?\" ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send an email [CODESPLIT] public static Future < Boolean > send ( Email email ) { try { email = buildMessage ( email ) ; if ( GojaConfig . getProperty ( \"mail.smtp\" , StringPool . EMPTY ) . equals ( \"mock\" ) && GojaConfig . getApplicationMode ( ) . isDev ( ) ) { Mock . send ( email ) ; return new Future < Boolean > ( ) { @ Override public boolean cancel ( boolean mayInterruptIfRunning ) { return false ; } @ Override public boolean isCancelled ( ) { return false ; } @ Override public boolean isDone ( ) { return true ; } @ Override public Boolean get ( ) throws InterruptedException , ExecutionException { return true ; } @ Override public Boolean get ( long timeout , final TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return true ; } } ; } email . setMailSession ( getSession ( ) ) ; return sendMessage ( email ) ; } catch ( EmailException ex ) { throw new MailException ( \"Cannot send email\" , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a JavaMail message [CODESPLIT] public static Future < Boolean > sendMessage ( final Email msg ) { if ( asynchronousSend ) { return executor . submit ( new Callable < Boolean > ( ) { public Boolean call ( ) { try { msg . setSentDate ( new Date ( ) ) ; msg . send ( ) ; return true ; } catch ( Throwable e ) { MailException me = new MailException ( \"Error while sending email\" , e ) ; logger . error ( \"The email has not been sent\" , me ) ; return false ; } } } ) ; } else { final StringBuffer result = new StringBuffer ( ) ; try { msg . setSentDate ( new Date ( ) ) ; msg . send ( ) ; } catch ( Throwable e ) { MailException me = new MailException ( \"Error while sending email\" , e ) ; logger . error ( \"The email has not been sent\" , me ) ; result . append ( \"oops\" ) ; } return new Future < Boolean > ( ) { public boolean cancel ( boolean mayInterruptIfRunning ) { return false ; } public boolean isCancelled ( ) { return false ; } public boolean isDone ( ) { return true ; } public Boolean get ( ) throws InterruptedException , ExecutionException { return result . length ( ) == 0 ; } public Boolean get ( long timeout , TimeUnit unit ) throws InterruptedException , ExecutionException , TimeoutException { return result . length ( ) == 0 ; } } ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a handler that will be called for all HTTP methods [CODESPLIT] public void bind ( final RouteBinding handler ) { final Method method = handler . getMethod ( ) ; logger . info ( \"Using appId: {} and default version: {}\" , appAcceptId , defaultVersion ) ; List < String > versions = handler . getVersions ( ) ; if ( versions == null || versions . isEmpty ( ) ) { versions = Collections . singletonList ( defaultVersion ) ; } for ( final String version : versions ) { final Set < Method > methods = new HashSet <> ( ) ; if ( method == Method . ANY ) { for ( final Method m : Method . values ( ) ) { methods . add ( m ) ; } } else { methods . add ( method ) ; } for ( final Method m : methods ) { final BindingKey key = new BindingKey ( m , version ) ; List < PatternRouteBinding > b = routeBindings . get ( key ) ; if ( b == null ) { b = new ArrayList <> ( ) ; routeBindings . put ( key , b ) ; } logger . info ( \"ADD: {}, Pattern: {}, Route: {}\\n\" , key , handler . getPath ( ) , handler ) ; addPattern ( handler , b ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specify a filter handler that will be used to wrap route executions [CODESPLIT] public void bind ( final FilterBinding handler ) { final Method method = handler . getMethod ( ) ; final String path = handler . getPath ( ) ; logger . info ( \"Using appId: {} and default version: {}\" , appAcceptId , defaultVersion ) ; List < String > versions = handler . getVersions ( ) ; if ( versions == null || versions . isEmpty ( ) ) { versions = Collections . singletonList ( defaultVersion ) ; } for ( final String version : versions ) { final Set < Method > methods = new HashSet <> ( ) ; if ( method == Method . ANY ) { for ( final Method m : Method . values ( ) ) { methods . add ( m ) ; } } else { methods . add ( method ) ; } for ( final Method m : methods ) { final BindingKey key = new BindingKey ( m , version ) ; logger . info ( \"ADD: {}, Pattern: {}, Filter: {}\\n\" , key , path , handler ) ; List < PatternFilterBinding > allFilterBindings = this . filterBindings . get ( key ) ; if ( allFilterBindings == null ) { allFilterBindings = new ArrayList <> ( ) ; this . filterBindings . put ( key , allFilterBindings ) ; } boolean found = false ; for ( final PatternFilterBinding binding : allFilterBindings ) { if ( binding . getPattern ( ) . pattern ( ) . equals ( handler . getPath ( ) ) ) { binding . addFilter ( handler ) ; found = true ; break ; } } if ( ! found ) { final PatternFilterBinding binding = new PatternFilterBinding ( handler . getPath ( ) , handler ) ; allFilterBindings . add ( binding ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据浏览器If - Modified - Since Header 计算文件是否已被修改 . <p / > 如果无修改 checkIfModify返回false 设置304 not modify status . [CODESPLIT] public static boolean checkIfModifiedSince ( HttpServletRequest request , HttpServletResponse response , long lastModified ) { long ifModifiedSince = request . getDateHeader ( HttpHeaders . IF_MODIFIED_SINCE ) ; if ( ( ifModifiedSince != - 1 ) && ( lastModified < ( ifModifiedSince + 1000 ) ) ) { response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据浏览器 If - None - Match Header 计算Etag是否已无效 . <p / > 如果Etag有效 checkIfNoneMatch返回false 设置304 not modify status . [CODESPLIT] public static boolean checkIfNoneMatchEtag ( HttpServletRequest request , HttpServletResponse response , String etag ) { String headerValue = request . getHeader ( HttpHeaders . IF_NONE_MATCH ) ; if ( headerValue != null ) { boolean conditionSatisfied = false ; if ( ! StringPool . ASTERISK . equals ( headerValue ) ) { StringTokenizer commaTokenizer = new StringTokenizer ( headerValue , StringPool . COMMA ) ; while ( ! conditionSatisfied && commaTokenizer . hasMoreTokens ( ) ) { String currentToken = commaTokenizer . nextToken ( ) ; if ( currentToken . trim ( ) . equals ( etag ) ) { conditionSatisfied = true ; } } } else { conditionSatisfied = true ; } if ( conditionSatisfied ) { response . setStatus ( HttpServletResponse . SC_NOT_MODIFIED ) ; response . setHeader ( HttpHeaders . ETAG , etag ) ; return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置让浏览器弹出下载对话框的Header . [CODESPLIT] public static void setFileDownloadHeader ( HttpServletResponse response , String fileName ) { try { // 中文文件名支持 String encodedfileName = new String ( fileName . getBytes ( ) , \"ISO8859-1\" ) ; response . setHeader ( HttpHeaders . CONTENT_DISPOSITION , \"attachment; filename=\\\"\" + encodedfileName + StringPool . QUOTE ) ; } catch ( UnsupportedEncodingException ignored ) { } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取得带相同前缀的Request Parameters copy from spring WebUtils . <p / > 返回的结果的Parameter名已去除前缀 . [CODESPLIT] public static Map < String , Object > getParametersStartingWith ( ServletRequest request , String prefix ) { Validate . notNull ( request , \"Request must not be null\" ) ; Enumeration paramNames = request . getParameterNames ( ) ; Map < String , Object > params = new TreeMap < String , Object > ( ) ; if ( prefix == null ) { prefix = \"\" ; } while ( ( paramNames != null ) && paramNames . hasMoreElements ( ) ) { String paramName = ( String ) paramNames . nextElement ( ) ; if ( \"\" . equals ( prefix ) || paramName . startsWith ( prefix ) ) { String unprefixed = paramName . substring ( prefix . length ( ) ) ; String [ ] values = request . getParameterValues ( paramName ) ; if ( ( values == null ) || ( values . length == 0 ) ) { // Do nothing, no values found at all. } else if ( values . length > 1 ) { params . put ( unprefixed , values ) ; } else { params . put ( unprefixed , values [ 0 ] ) ; } } } return params ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "组合Parameters生成Query String的Parameter部分 并在paramter name上加上prefix . [CODESPLIT] public static String encodeParameterStringWithPrefix ( Map < String , Object > params , String prefix ) { if ( ( params == null ) || ( params . size ( ) == 0 ) ) { return \"\" ; } if ( prefix == null ) { prefix = \"\" ; } StringBuilder queryStringBuilder = new StringBuilder ( ) ; Iterator < Map . Entry < String , Object > > it = params . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Map . Entry < String , Object > entry = it . next ( ) ; queryStringBuilder . append ( prefix ) . append ( entry . getKey ( ) ) . append ( ' ' ) . append ( entry . getValue ( ) ) ; if ( it . hasNext ( ) ) { queryStringBuilder . append ( ' ' ) ; } } return queryStringBuilder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "客户端对Http Basic验证的 Header进行编码 . [CODESPLIT] public static String encodeHttpBasic ( String userName , String password ) { String encode = userName + StringPool . COLON + password ; return \"Basic \" + EncodeKit . encodeBase64 ( encode . getBytes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delimeter that separates role names in tag attribute [CODESPLIT] @ Override protected boolean showTagBody ( String roleName ) { boolean hasAnyRole = false ; Subject subject = getSubject ( ) ; if ( subject != null ) { // Iterate through roles and check to see if the user has one of the roles for ( String role : roleName . split ( StringPool . COMMA ) ) { if ( subject . hasRole ( role . trim ( ) ) ) { hasAnyRole = true ; break ; } } } return hasAnyRole ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "appConfig配置所有参数 重写freemarker中的 reader方法，读取该配置文件 [CODESPLIT] private static Configuration getAppConfiguration ( ) { if ( appConfig == null ) { //从freemarker 视图中获取所有配置 appConfig = ( Configuration ) FreeMarkerRender . getConfiguration ( ) . clone ( ) ; try { //设置模板路径 appConfig . setDirectoryForTemplateLoading ( new File ( PathKit . getWebRootPath ( ) + Goja . viewPath ) ) ; appConfig . setObjectWrapper ( new BeansWrapperBuilder ( Configuration . VERSION_2_3_21 ) . build ( ) ) ; } catch ( IOException e ) { logger . error ( \"The Freemarkers has error!\" , e ) ; } } return appConfig ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "渲染模版为字符串，并制定参数 [CODESPLIT] public static String processString ( String tpl , Map < String , Object > renderParams ) { if ( appConfig == null ) { getAppConfiguration ( ) ; } StringWriter result = new StringWriter ( ) ; try { Template template = appConfig . getTemplate ( tpl ) ; template . process ( renderParams , result ) ; } catch ( IOException e ) { throw new RenderException ( e ) ; } catch ( TemplateException e ) { throw new RenderException ( e ) ; } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将Freemakrer的字符串模版，渲染参数为字符串形式的结果。 [CODESPLIT] public static String renderStrTemplate ( String strTemplat , Map < String , Object > renderParams ) { stringLoader . putTemplate ( UPDATE_RESPONSE_TEMPLATE , strTemplat ) ; stringConfig . setTemplateLoader ( stringLoader ) ; Writer out = new StringWriter ( 2048 ) ; try { Template tpl = stringConfig . getTemplate ( UPDATE_RESPONSE_TEMPLATE , StringPool . UTF_8 ) ; tpl . process ( renderParams , out ) ; } catch ( IOException e ) { Logger . error ( \"Get update response template occurs error.\" , e ) ; } catch ( TemplateException e ) { Logger . error ( \"Process template occurs error.template content is:\\n {}\" , e , strTemplat ) ; throw new IllegalArgumentException ( \"Error update response template.\" , e ) ; } return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "生成HTML [CODESPLIT] public static void makeHtml ( String tlDirectory , String tlName , Map < String , Object > paramMap , String htmlPath ) { FileOutputStream fileOutputStream = null ; OutputStreamWriter outputStreamWriter = null ; try { Configuration configuration = new Configuration ( Configuration . VERSION_2_3_22 ) ; File file = new File ( tlDirectory ) ; // .ftl模板目录 configuration . setDirectoryForTemplateLoading ( file ) ; configuration . setObjectWrapper ( new DefaultObjectWrapper ( Configuration . VERSION_2_3_22 ) ) ; Template template = configuration . getTemplate ( tlName , StringPool . UTF_8 ) ; File file2 = new File ( htmlPath ) ; // 生成html目录 fileOutputStream = new FileOutputStream ( file2 ) ; outputStreamWriter = new OutputStreamWriter ( fileOutputStream , StringPool . UTF_8 ) ; BufferedWriter bufferedWriter = new BufferedWriter ( outputStreamWriter ) ; template . process ( paramMap , bufferedWriter ) ; bufferedWriter . flush ( ) ; outputStreamWriter . close ( ) ; fileOutputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( TemplateException e ) { e . printStackTrace ( ) ; } finally { if ( null != fileOutputStream ) { try { fileOutputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } if ( null != outputStreamWriter ) { try { outputStreamWriter . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts packing Long Int [CODESPLIT] public static int getInt ( Long l ) { return ( l == null || l > Integer . MAX_VALUE ) ? 0 : l . intValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the filename from the given path e . g . mypath / myfile . txt - > myfile . txt . [CODESPLIT] public static String getFilename ( String path ) { if ( path == null ) { return null ; } int separatorIndex = path . lastIndexOf ( StringPool . SLASH ) ; return ( separatorIndex != - 1 ? path . substring ( separatorIndex + 1 ) : path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extract the filename extension from the given path e . g . mypath / myfile . txt - > txt . [CODESPLIT] public static String getFilenameExtension ( String path ) { if ( path == null ) { return null ; } int extIndex = path . lastIndexOf ( EXTENSION_SEPARATOR ) ; if ( extIndex == - 1 ) { return null ; } int folderIndex = path . lastIndexOf ( StringPool . SLASH ) ; if ( folderIndex > extIndex ) { return null ; } return path . substring ( extIndex + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Apply the given relative path to the given path assuming standard Java folder separation ( i . e . / separators ) . [CODESPLIT] public static String applyRelativePath ( String path , String relativePath ) { int separatorIndex = path . lastIndexOf ( StringPool . SLASH ) ; if ( separatorIndex != - 1 ) { String newPath = path . substring ( 0 , separatorIndex ) ; if ( ! relativePath . startsWith ( StringPool . SLASH ) ) { newPath += StringPool . SLASH ; } return newPath + relativePath ; } else { return relativePath ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Normalize the path by suppressing sequences like path / .. and inner simple dots . <p > The result is convenient for path comparison . For other uses notice that Windows separators ( \\ ) are replaced by simple slashes . [CODESPLIT] public static String cleanPath ( String path ) { if ( path == null ) { return null ; } String pathToUse = replace ( path , StringPool . BACK_SLASH , StringPool . SLASH ) ; // Strip prefix from path to analyze, to not treat it as part of the // first path element. This is necessary to correctly parse paths like // \"file:core/../core/io/Resource.class\", where the \"..\" should just // strip the first \"core\" directory while keeping the \"file:\" prefix. int prefixIndex = pathToUse . indexOf ( \":\" ) ; String prefix = \"\" ; if ( prefixIndex != - 1 ) { prefix = pathToUse . substring ( 0 , prefixIndex + 1 ) ; if ( prefix . contains ( \"/\" ) ) { prefix = \"\" ; } else { pathToUse = pathToUse . substring ( prefixIndex + 1 ) ; } } if ( pathToUse . startsWith ( StringPool . SLASH ) ) { prefix = prefix + StringPool . SLASH ; pathToUse = pathToUse . substring ( 1 ) ; } String [ ] pathArray = delimitedListToStringArray ( pathToUse , StringPool . SLASH ) ; List < String > pathElements = new LinkedList < String > ( ) ; int tops = 0 ; for ( int i = pathArray . length - 1 ; i >= 0 ; i -- ) { String element = pathArray [ i ] ; //            if (StringPool.DOT.equals(element)) { // Points to current directory - drop it. //            } /* else*/ if ( StringPool . DOTDOT . equals ( element ) ) { // Registering top path found. tops ++ ; } else { if ( tops > 0 ) { // Merging path element with element corresponding to top path. tops -- ; } else { // Normal path element found. pathElements . add ( 0 , element ) ; } } } // Remaining top paths need to be retained. for ( int i = 0 ; i < tops ; i ++ ) { pathElements . add ( 0 , StringPool . DOTDOT ) ; } return prefix + collectionToDelimitedString ( pathElements , StringPool . SLASH ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trim the elements of the given String array calling { @code String . trim () } on each of them . [CODESPLIT] public static String [ ] trimArrayElements ( String [ ] array ) { if ( ObjectKit . isEmpty ( array ) ) { return new String [ 0 ] ; } String [ ] result = new String [ array . length ] ; for ( int i = 0 ; i < array . length ; i ++ ) { String element = array [ i ] ; result [ i ] = ( element != null ? element . trim ( ) : null ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove duplicate Strings from the given array . Also sorts the array as it uses a TreeSet . [CODESPLIT] public static String [ ] removeDuplicateStrings ( String [ ] array ) { if ( ObjectKit . isEmpty ( array ) ) { return array ; } Set < String > set = new TreeSet < String > ( ) ; for ( String element : array ) { set . add ( element ) ; } return toStringArray ( set ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take an array Strings and split each element based on the given delimiter . A { @code Properties } instance is then generated with the left of the delimiter providing the key and the right of the delimiter providing the value . <p > Will trim both the key and value before adding them to the { @code Properties } instance . [CODESPLIT] public static Properties splitArrayElementsIntoProperties ( String [ ] array , String delimiter , String charsToDelete ) { if ( ObjectKit . isEmpty ( array ) ) { return null ; } Properties result = new Properties ( ) ; for ( String element : array ) { if ( charsToDelete != null ) { element = deleteAny ( element , charsToDelete ) ; } String [ ] splittedElement = split ( element , delimiter ) ; if ( splittedElement == null ) { continue ; } result . setProperty ( splittedElement [ 0 ] . trim ( ) , splittedElement [ 1 ] . trim ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convenience method to return a Collection as a delimited ( e . g . CSV ) String . E . g . useful for { @code toString () } implementations . [CODESPLIT] public static String collectionToDelimitedString ( Collection < ? > coll , String delim , String prefix , String suffix ) { if ( CollectionKit . isEmpty ( coll ) ) { return \"\" ; } StringBuilder sb = new StringBuilder ( ) ; Iterator < ? > it = coll . iterator ( ) ; while ( it . hasNext ( ) ) { sb . append ( prefix ) . append ( it . next ( ) ) . append ( suffix ) ; if ( it . hasNext ( ) ) { sb . append ( delim ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个整数转换成最小长度为某一固定数值的十进制形式字符串 [CODESPLIT] public static String fillDigit ( int d , int width ) { return Strs . alignRight ( String . valueOf ( d ) , width , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个整数转换成最小长度为某一固定数值的十六进制形式字符串 [CODESPLIT] public static String fillHex ( int d , int width ) { return Strs . alignRight ( Integer . toHexString ( d ) , width , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个整数转换成最小长度为某一固定数值的二进制形式字符串 [CODESPLIT] public static String fillBinary ( int d , int width ) { return Strs . alignRight ( Integer . toBinaryString ( d ) , width , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个整数转换成固定长度的十进制形式字符串 [CODESPLIT] public static String toDigit ( int d , int width ) { return Strs . cutRight ( String . valueOf ( d ) , width , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个整数转换成固定长度的十六进制形式字符串 [CODESPLIT] public static String toHex ( int d , int width ) { return Strs . cutRight ( Integer . toHexString ( d ) , width , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个整数转换成固定长度的二进制形式字符串 [CODESPLIT] public static String toBinary ( int d , int width ) { return Strs . cutRight ( Integer . toBinaryString ( d ) , width , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "保证字符串为一固定长度。超过长度，切除右侧字符，否则右侧填补字符。 [CODESPLIT] public static String cutLeft ( String s , int width , char c ) { if ( null == s ) return null ; int len = s . length ( ) ; if ( len == width ) return s ; if ( len < width ) return s + Strs . dup ( c , width - len ) ; return s . substring ( 0 , width ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "如果str中第一个字符和 c一致 则删除 否则返回 str <p / > 比如 : <ul > <li > removeFirst ( 12345 1 ) = > 2345 <li > removeFirst ( ABC B ) = > ABC <li > removeFirst ( A B ) = > A <li > removeFirst ( A A ) = > < / ul > [CODESPLIT] public static String removeFirst ( String str , char c ) { return ( Strs . isEmpty ( str ) || c != str . charAt ( 0 ) ) ? str : str . substring ( 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断一个字符串数组是否包括某一字符串 [CODESPLIT] public static boolean isin ( String [ ] ss , String s ) { if ( null == ss || ss . length == 0 || Strs . isBlank ( s ) ) return false ; for ( String w : ss ) if ( s . equals ( w ) ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个字符串出现的HMTL元素进行转义，比如 <p / > <pre > escapeHtml ( &lt ; script&gt ; alert ( hello world ) ; &lt ; / script&gt ; ) = > &amp ; lt ; script&amp ; gt ; alert ( &amp ; quot ; hello world&amp ; quot ; ) ; &amp ; lt ; / script&amp ; gt ; < / pre > <p / > 转义字符对应如下 <ul > <li > & = > &amp ; amp ; <li > < = > &amp ; lt ; <li >> = > &amp ; gt ; <li > = > &amp ; #x27 ; <li > = > &amp ; quot ; < / ul > [CODESPLIT] public static String escapeHtml ( CharSequence cs ) { if ( null == cs ) return null ; char [ ] cas = cs . toString ( ) . toCharArray ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( char c : cas ) { switch ( c ) { case ' ' : sb . append ( \"&amp;\" ) ; break ; case ' ' : sb . append ( \"&lt;\" ) ; break ; case ' ' : sb . append ( \"&gt;\" ) ; break ; case ' ' : sb . append ( \"&#x27;\" ) ; break ; case ' ' : sb . append ( \"&quot;\" ) ; break ; default : sb . append ( c ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将一个字节数变成人类容易识别的显示字符串，比如 1 . 5M 等 [CODESPLIT] private static String _formatSizeForRead ( long size , double SZU ) { if ( size < SZU ) { return String . format ( \"%d bytes\" , size ) ; } double n = ( double ) size / SZU ; if ( n < SZU ) { return String . format ( \"%5.2f KB\" , n ) ; } n = n / SZU ; if ( n < SZU ) { return String . format ( \"%5.2f MB\" , n ) ; } n = n / SZU ; return String . format ( \"%5.2f GB\" , n ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Stitching LIKE SQL percent . [CODESPLIT] public static String like ( String value ) { return StringPool . PERCENT + Strings . nullToEmpty ( value ) + StringPool . PERCENT ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run from the web interface . [CODESPLIT] public void doRun ( ) throws Exception { if ( inProgress . compareAndSet ( false , true ) ) { try { run ( ) ; } finally { inProgress . set ( false ) ; } } else { throw new IllegalStateException ( \"Another run is already in progress\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "该方法调用无效果 [CODESPLIT] @ Override public void putInfo ( String name , String val ) { this . infoMap . put ( name , val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the user s password and execute the login request [CODESPLIT] public static < T extends Model > boolean login ( T user , String password , boolean remember , HttpServletRequest request , HttpServletResponse response ) { boolean matcher = SecurityKit . checkPassword ( user . getStr ( \"salt\" ) , user . getStr ( \"password\" ) , password ) ; if ( matcher ) { SecurityKit . setLoginMember ( request , response , user , remember ) ; } return matcher ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "logout [CODESPLIT] public static < T extends Model > void logout ( HttpServletRequest req , HttpServletResponse response ) { CookieUser cookie_user = getUserFromCookie ( req ) ; Requests . deleteCookie ( req , response , COOKIE_LOGIN , true ) ; // 清理Cache if ( cookie_user != null ) { CacheKit . remove ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + cookie_user . getId ( ) ) ; } else { T user = getLoginUser ( req ) ; if ( user != null ) { CacheKit . remove ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + user . getNumber ( StringPool . PK_COLUMN ) ) ; } } //清除session Enumeration < String > em = req . getSession ( ) . getAttributeNames ( ) ; while ( em . hasMoreElements ( ) ) { final String key = em . nextElement ( ) ; req . getSession ( ) . removeAttribute ( key ) ; } req . getSession ( ) . invalidate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get user login information if the session does not exist then try to obtain from the Cookie if cookie exists then decrypt obtain user information . [CODESPLIT] public static < T extends Model > T getLoginWithDb ( HttpServletRequest req , HttpServletResponse response , Function < Long , T > function ) { T loginUser = getLoginUser ( req ) ; if ( loginUser == null ) { //从Cookie中解析出用户id CookieUser cookie_user = getUserFromCookie ( req ) ; if ( cookie_user == null ) return null ; T user = CacheKit . get ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + cookie_user . getId ( ) ) ; if ( user == null ) { user = function . apply ( cookie_user . getId ( ) ) ; CacheKit . put ( LOGIN_CACHE_SESSION , LOGIN_CACHE_SESSION + cookie_user . getId ( ) , user ) ; } // 用户密码和cookie中存储的密码一致 if ( user != null && StringUtils . equalsIgnoreCase ( user . getStr ( \"password\" ) , cookie_user . getPassword ( ) ) ) { setLoginMember ( req , response , user , true ) ; return user ; } else { return null ; } } else { return loginUser ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain user information from the Session [CODESPLIT] public static < T extends Model > T getLoginUser ( HttpServletRequest req ) { return ( T ) req . getSession ( ) . getAttribute ( LOGIN_SESSION_KEY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sign settings [CODESPLIT] private static < T extends Model > void setLoginMember ( HttpServletRequest request , HttpServletResponse response , T user , boolean remember ) { request . getSession ( ) . setAttribute ( LOGIN_SESSION_KEY , user ) ; request . getSession ( ) . setAttribute ( LOGIN_MEMBER_ID , user . getNumber ( StringPool . PK_COLUMN ) ) ; saveMemberInCookie ( user , remember , request , response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check Password salt password planpassword . [CODESPLIT] public static boolean checkPassword ( String salt , String password , String plainPassword ) { byte [ ] saltHex = EncodeKit . decodeHex ( salt ) ; byte [ ] hashPassword = DigestsKit . sha1 ( plainPassword . getBytes ( ) , saltHex , EncodeKit . HASH_INTERATIONS ) ; return StringUtils . equals ( EncodeKit . encodeHex ( hashPassword ) , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Store user information in a cookie logged in . [CODESPLIT] public static < T extends Model > void saveMemberInCookie ( T user , boolean save , HttpServletRequest request , HttpServletResponse response ) { String new_value = getLoginKey ( user , Requests . remoteIP ( request ) , request . getHeader ( \"user-agent\" ) ) ; int max_age = save ? MAX_AGE : - 1 ; Requests . deleteCookie ( request , response , COOKIE_LOGIN , true ) ; Requests . setCookie ( request , response , COOKIE_LOGIN , new_value , max_age , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generating system user login ID string . [CODESPLIT] private static < T extends Model > String getLoginKey ( T user , String ip , String user_agent ) { return encrypt ( String . valueOf ( user . getNumber ( StringPool . PK_COLUMN ) ) + ' ' + user . getStr ( \"password\" ) + ' ' + ip + ' ' + ( ( user_agent == null ) ? 0 : user_agent . hashCode ( ) ) + ' ' + System . currentTimeMillis ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从cookie中读取保存的用户信息 [CODESPLIT] private static CookieUser getUserFromCookie ( HttpServletRequest req ) { try { Cookie cookie = Requests . getCookie ( req , COOKIE_LOGIN ) ; if ( cookie != null && StringUtils . isNotBlank ( cookie . getValue ( ) ) ) { return userForCookie ( cookie . getValue ( ) , req ) ; } } catch ( Exception ignored ) { } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "encrypt [CODESPLIT] private static String encrypt ( String value ) { byte [ ] data = encrypt ( value . getBytes ( ) , E_KEY ) ; try { return URLEncoder . encode ( new String ( Base64 . encodeBase64 ( data ) ) , StringPool . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain user information from the Cookie [CODESPLIT] private static CookieUser userForCookie ( String uuid , HttpServletRequest request ) { if ( StringUtils . isBlank ( uuid ) ) { return null ; } String ck = decrypt ( uuid ) ; final String [ ] items = StringUtils . split ( ck , ' ' ) ; if ( items . length == 5 ) { String ua = request . getHeader ( \"user-agent\" ) ; int ua_code = ( ua == null ) ? 0 : ua . hashCode ( ) ; int old_ua_code = Integer . parseInt ( items [ 3 ] ) ; if ( ua_code == old_ua_code ) { return new CookieUser ( NumberUtils . toLong ( items [ 0 ] , - 1L ) , items [ 1 ] , false ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "decrypt [CODESPLIT] private static String decrypt ( String value ) { try { value = URLDecoder . decode ( value , StringPool . UTF_8 ) ; if ( StringUtils . isBlank ( value ) ) return null ; byte [ ] data = Base64 . decodeBase64 ( value . getBytes ( ) ) ; return new String ( decrypt ( data , E_KEY ) ) ; } catch ( UnsupportedEncodingException excp ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "decrypt [CODESPLIT] private static byte [ ] decrypt ( byte [ ] src , byte [ ] key ) throws RuntimeException { try { //\t\tDES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom ( ) ; // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec ( key ) ; // 创建一个密匙工厂，然后用它把DESKeySpec对象转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory . getInstance ( DES ) ; SecretKey securekey = keyFactory . generateSecret ( dks ) ; // Cipher对象实际完成解密操作 Cipher cipher = Cipher . getInstance ( DES ) ; // 用密匙初始化Cipher对象 cipher . init ( Cipher . DECRYPT_MODE , securekey , sr ) ; // 现在，获取数据并解密 // 正式执行解密操作 return cipher . doFinal ( src ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回处理正常的消息内容 [CODESPLIT] public static < E > AjaxMessage ok ( String message , E data ) { return new AjaxMessage < E > ( data , message , MessageStatus . OK ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回没有数据的消息内容 [CODESPLIT] public static < E > AjaxMessage nodata ( E data ) { return new AjaxMessage < E > ( data , EMPTY , MessageStatus . NODATA ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回没有数据的消息内容 [CODESPLIT] public static < E > AjaxMessage nodata ( String message , E data ) { return new AjaxMessage < E > ( data , message , MessageStatus . NODATA ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回没有登录时消息内容 [CODESPLIT] public static < E > AjaxMessage nologin ( E data ) { return new AjaxMessage < E > ( data , EMPTY , MessageStatus . NOLOGIN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回禁止访问消息内容 [CODESPLIT] public static < E > AjaxMessage forbidden ( E data ) { return new AjaxMessage < E > ( data , EMPTY , MessageStatus . FORBIDDEN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回禁止访问消息内容 [CODESPLIT] public static < E > AjaxMessage forbidden ( String message , E data ) { return new AjaxMessage < E > ( data , message , MessageStatus . FORBIDDEN ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回处理错误的消息内容 [CODESPLIT] public static AjaxMessage error ( String message , Exception exception ) { return error ( message , null , exception ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回处理错误的消息内容 [CODESPLIT] public static < E > AjaxMessage error ( String message , E data , Exception exception ) { return new AjaxMessage < E > ( data , message , MessageStatus . ERROR , exception ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回处理失败的消息内容 [CODESPLIT] public static AjaxMessage failure ( String message , Exception exception ) { return failure ( message , null , exception ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回处理失败的消息内容 [CODESPLIT] public static < E > AjaxMessage failure ( String message , E data , Exception exception ) { return new AjaxMessage < E > ( data , message , MessageStatus . FAILURE , exception ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "产品序列号前10位 + KEY前5位 + 5位随机数字和字符（大小写） + 时间戳 MD5 加密 [CODESPLIT] public static String generateKeyCode ( String productSerialNo , String codeKey ) { return digestPassword ( StringUtils . leftPad ( productSerialNo , 10 , StringPool . ZERO ) + StringUtils . leftPad ( codeKey , 5 , StringPool . ZERO ) + RandomStringUtils . randomAlphanumeric ( 5 ) + DateTime . now ( ) . getMillis ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "加密 [CODESPLIT] private static String digestPassword ( String password ) { try { SecureRandom random = new SecureRandom ( ) ; byte [ ] salt = new byte [ EncodeKit . SALT_SIZE ] ; random . nextBytes ( salt ) ; MessageDigest md = MessageDigest . getInstance ( \"MD5\" ) ; md . update ( salt ) ; md . update ( password . getBytes ( ) ) ; byte [ ] digest = md . digest ( ) ; BASE64Encoder encoder = new BASE64Encoder ( ) ; return encoder . encode ( salt ) + encoder . encode ( digest ) ; } catch ( NoSuchAlgorithmException ne ) { System . err . println ( ne . toString ( ) ) ; return null ; } catch ( Exception e ) { System . err . println ( e . toString ( ) ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "启动插件 [CODESPLIT] @ Override public boolean start ( ) { Set < String > excludedMethodName = buildExcludedMethodName ( ) ; ConcurrentMap < String , AuthzHandler > authzMaps = Maps . newConcurrentMap ( ) ; //逐个访问所有注册的Controller，解析Controller及action上的所有Shiro注解。 //并依据这些注解，actionKey提前构建好权限检查处理器。 final List < Routes . Route > routeItemList = routes . getRouteItemList ( ) ; for ( Routes . Route route : routeItemList ) { final Class < ? extends Controller > controllerClass = route . getControllerClass ( ) ; String controllerKey = route . getControllerKey ( ) ; // 获取Controller的所有Shiro注解。 List < Annotation > controllerAnnotations = getAuthzAnnotations ( controllerClass ) ; // 逐个遍历方法。 Method [ ] methods = controllerClass . getMethods ( ) ; for ( Method method : methods ) { //排除掉Controller基类的所有方法，并且只关注没有参数的Action方法。 if ( ! excludedMethodName . contains ( method . getName ( ) ) && method . getParameterTypes ( ) . length == 0 ) { //若该方法上存在ClearShiro注解，则对该action不进行访问控制检查。 if ( isClearShiroAnnotationPresent ( method ) ) { continue ; } //获取方法的所有Shiro注解。 List < Annotation > methodAnnotations = getAuthzAnnotations ( method ) ; //依据Controller的注解和方法的注解来生成访问控制处理器。 AuthzHandler authzHandler = createAuthzHandler ( controllerAnnotations , methodAnnotations ) ; //生成访问控制处理器成功。 if ( authzHandler != null ) { //构建ActionKey，参考ActionMapping中实现 String actionKey = createActionKey ( controllerClass , method , controllerKey ) ; //添加映射 authzMaps . put ( actionKey , authzHandler ) ; } } } } //注入到ShiroKit类中。ShiroKit类以单例模式运行。 ShiroKit . init ( authzMaps ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从Controller方法中构建出需要排除的方法列表 [CODESPLIT] private Set < String > buildExcludedMethodName ( ) { Set < String > excludedMethodName = new HashSet <> ( ) ; Method [ ] methods = Controller . class . getMethods ( ) ; for ( Method m : methods ) { if ( m . getParameterTypes ( ) . length == 0 ) { excludedMethodName . add ( m . getName ( ) ) ; } } return excludedMethodName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "依据Controller的注解和方法的注解来生成访问控制处理器。 [CODESPLIT] private AuthzHandler createAuthzHandler ( List < Annotation > controllerAnnotations , List < Annotation > methodAnnotations ) { //没有注解 if ( controllerAnnotations . size ( ) == 0 && methodAnnotations . size ( ) == 0 ) { return null ; } //至少有一个注解 List < AuthzHandler > authzHandlers = Lists . newArrayListWithCapacity ( 5 ) ; for ( int index = 0 ; index < 5 ; index ++ ) { authzHandlers . add ( null ) ; } // 逐个扫描注解，若是相应的注解则在相应的位置赋值。 scanAnnotation ( authzHandlers , controllerAnnotations ) ; // 逐个扫描注解，若是相应的注解则在相应的位置赋值。函数的注解优先级高于Controller scanAnnotation ( authzHandlers , methodAnnotations ) ; // 去除空值 List < AuthzHandler > finalAuthzHandlers = Lists . newArrayList ( ) ; for ( AuthzHandler a : authzHandlers ) { if ( a != null ) { finalAuthzHandlers . add ( a ) ; } } authzHandlers = null ; // 存在多个，则构建组合AuthzHandler if ( finalAuthzHandlers . size ( ) > 1 ) { return new CompositeAuthzHandler ( finalAuthzHandlers ) ; } // 一个的话直接返回 return finalAuthzHandlers . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "逐个扫描注解，若是相应的注解则在相应的位置赋值。 注解的处理是有顺序的，依次为RequiresRoles，RequiresPermissions， RequiresAuthentication，RequiresUser，RequiresGuest [CODESPLIT] private void scanAnnotation ( List < AuthzHandler > authzArray , List < Annotation > annotations ) { if ( null == annotations || 0 == annotations . size ( ) ) { return ; } for ( Annotation a : annotations ) { if ( a instanceof RequiresRoles ) { authzArray . set ( 0 , new RoleAuthzHandler ( a ) ) ; } else if ( a instanceof RequiresPermissions ) { authzArray . set ( 1 , new PermissionAuthzHandler ( a ) ) ; } else if ( a instanceof RequiresAuthentication ) { authzArray . set ( 2 , AuthenticatedAuthzHandler . me ( ) ) ; } else if ( a instanceof RequiresUser ) { authzArray . set ( 3 , UserAuthzHandler . me ( ) ) ; } else if ( a instanceof RequiresGuest ) { authzArray . set ( 4 , GuestAuthzHandler . me ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "构建actionkey，参考ActionMapping中的实现。 [CODESPLIT] private String createActionKey ( Class < ? extends Controller > controllerClass , Method method , String controllerKey ) { String methodName = method . getName ( ) ; String actionKey ; ActionKey ak = method . getAnnotation ( ActionKey . class ) ; if ( ak != null ) { actionKey = ak . value ( ) . trim ( ) ; if ( Strings . isNullOrEmpty ( actionKey ) ) { throw new IllegalArgumentException ( controllerClass . getName ( ) + \".\" + methodName + \"(): The argument of ActionKey can not be blank.\" ) ; } if ( ! actionKey . startsWith ( SLASH ) ) { actionKey = SLASH + actionKey ; } } else if ( methodName . equals ( \"index\" ) ) { actionKey = controllerKey ; } else { actionKey = controllerKey . equals ( SLASH ) ? SLASH + methodName : controllerKey + SLASH + methodName ; } return actionKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回该方法的所有访问控制注解 [CODESPLIT] private List < Annotation > getAuthzAnnotations ( Method method ) { List < Annotation > annotations = Lists . newArrayList ( ) ; for ( Class < ? extends Annotation > annClass : AUTHZ_ANNOTATION_CLASSES ) { Annotation a = method . getAnnotation ( annClass ) ; if ( a != null ) { annotations . add ( a ) ; } } return annotations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回该Controller的所有访问控制注解 [CODESPLIT] private List < Annotation > getAuthzAnnotations ( Class < ? extends Controller > targetClass ) { List < Annotation > annotations = Lists . newArrayList ( ) ; for ( Class < ? extends Annotation > annClass : AUTHZ_ANNOTATION_CLASSES ) { Annotation a = targetClass . getAnnotation ( annClass ) ; if ( a != null ) { annotations . add ( a ) ; } } return annotations ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "该方法上是否有ClearShiro注解 [CODESPLIT] private boolean isClearShiroAnnotationPresent ( Method method ) { Annotation a = method . getAnnotation ( ClearShiro . class ) ; return a != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "触发Shiro的登录请求 . [CODESPLIT] public static void login ( String username , String password , boolean rememberMe ) throws AuthenticationException { UsernamePasswordToken token = new UsernamePasswordToken ( username , password , rememberMe ) ; final Subject subject = SecurityUtils . getSubject ( ) ; subject . login ( token ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "触发Shiro的登录请求 . 默认的不记住我 . [CODESPLIT] public static void login ( String username , String password ) throws AuthenticationException { login ( username , password , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forwards HTTP request to the specified path . [CODESPLIT] public void to ( WebContext context ) { HttpServletRequest request = context . request ( ) ; HttpServletResponse response = context . response ( ) ; try { request . getRequestDispatcher ( path ) . forward ( request , response ) ; } catch ( ServletException e ) { throw new UncheckedException ( e ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add File Separator [CODESPLIT] public String appendFileSeparator ( String path ) { if ( null == path ) { return File . separator ; } // add \"/\" prefix if ( ! path . startsWith ( StringPool . SLASH ) && ! path . startsWith ( StringPool . BACK_SLASH ) ) { path = File . separator + path ; } // add \"/\" postfix if ( ! path . endsWith ( StringPool . SLASH ) && ! path . endsWith ( StringPool . BACK_SLASH ) ) { path = path + File . separator ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取客户端浏览器信息 [CODESPLIT] public static String browserInfo ( HttpServletRequest req ) { String browserInfo = \"other\" ; String ua = req . getHeader ( \"User-Agent\" ) . toLowerCase ( ) ; String s ; String version ; String msieP = \"msie ([\\\\d.]+)\" ; String ieheighP = \"rv:([\\\\d.]+)\" ; String firefoxP = \"firefox\\\\/([\\\\d.]+)\" ; String chromeP = \"chrome\\\\/([\\\\d.]+)\" ; String operaP = \"opr.([\\\\d.]+)\" ; String safariP = \"version\\\\/([\\\\d.]+).*safari\" ; Pattern pattern = Pattern . compile ( msieP ) ; Matcher mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( \" \" ) [ 1 ] ; browserInfo = \"ie \" + version . substring ( 0 , version . indexOf ( \".\" ) ) ; return browserInfo ; } } pattern = Pattern . compile ( firefoxP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( \"/\" ) [ 1 ] ; browserInfo = \"firefox \" + version . substring ( 0 , version . indexOf ( \".\" ) ) ; return browserInfo ; } } pattern = Pattern . compile ( ieheighP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( \":\" ) [ 1 ] ; browserInfo = \"ie \" + version . substring ( 0 , version . indexOf ( \".\" ) ) ; return browserInfo ; } } pattern = Pattern . compile ( operaP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( \"/\" ) [ 1 ] ; browserInfo = \"opera \" + version . substring ( 0 , version . indexOf ( \".\" ) ) ; return browserInfo ; } } pattern = Pattern . compile ( chromeP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( \"/\" ) [ 1 ] ; browserInfo = \"chrome \" + version . substring ( 0 , version . indexOf ( \".\" ) ) ; return browserInfo ; } } pattern = Pattern . compile ( safariP ) ; mat = pattern . matcher ( ua ) ; if ( mat . find ( ) ) { s = mat . group ( ) ; if ( s != null ) { version = s . split ( \"/\" ) [ 1 ] . split ( \" \" ) [ 0 ] ; browserInfo = \"safari \" + version . substring ( 0 , version . indexOf ( \".\" ) ) ; return browserInfo ; } } return browserInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取客户端操作系统信息 [CODESPLIT] public static String clientOS ( HttpServletRequest req ) { String userAgent = req . getHeader ( \"User-Agent\" ) ; String cos = \"unknow os\" ; Pattern p = Pattern . compile ( \".*(Windows NT 6\\\\.2).*\" ) ; Matcher m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"Win 8\" ; return cos ; } p = Pattern . compile ( \".*(Windows NT 6\\\\.1).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"Win 7\" ; return cos ; } p = Pattern . compile ( \".*(Windows NT 5\\\\.1|Windows XP).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"WinXP\" ; return cos ; } p = Pattern . compile ( \".*(Windows NT 5\\\\.2).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"Win2003\" ; return cos ; } p = Pattern . compile ( \".*(Win2000|Windows 2000|Windows NT 5\\\\.0).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"Win2000\" ; return cos ; } p = Pattern . compile ( \".*(Mac|apple|MacOS8).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"MAC\" ; return cos ; } p = Pattern . compile ( \".*(WinNT|Windows NT).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"WinNT\" ; return cos ; } p = Pattern . compile ( \".*Linux.*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"Linux\" ; return cos ; } p = Pattern . compile ( \".*(68k|68000).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"Mac68k\" ; return cos ; } p = Pattern . compile ( \".*(9x 4.90|Win9(5|8)|Windows 9(5|8)|95/NT|Win32|32bit).*\" ) ; m = p . matcher ( userAgent ) ; if ( m . find ( ) ) { cos = \"Win9x\" ; return cos ; } return cos ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取客户端IP地址，此方法用在proxy环境中 [CODESPLIT] public static String remoteIP ( HttpServletRequest request ) { String ipAddress ; ipAddress = request . getHeader ( \"x-forwarded-for\" ) ; if ( ( ipAddress == null ) || ( ipAddress . length ( ) == 0 ) || ( \"unknown\" . equalsIgnoreCase ( ipAddress ) ) ) { ipAddress = request . getHeader ( \"Proxy-Client-IP\" ) ; } if ( ( ipAddress == null ) || ( ipAddress . length ( ) == 0 ) || ( \"unknown\" . equalsIgnoreCase ( ipAddress ) ) ) { ipAddress = request . getHeader ( \"WL-Proxy-Client-IP\" ) ; } if ( ( ipAddress == null ) || ( ipAddress . length ( ) == 0 ) || ( \"unknown\" . equalsIgnoreCase ( ipAddress ) ) ) { ipAddress = request . getRemoteAddr ( ) ; if ( ipAddress . equals ( \"127.0.0.1\" ) ) { InetAddress inet ; try { inet = InetAddress . getLocalHost ( ) ; ipAddress = inet . getHostAddress ( ) ; } catch ( UnknownHostException e ) { e . printStackTrace ( ) ; } } } if ( ( ipAddress != null ) && ( ipAddress . length ( ) > 15 ) ) { if ( ipAddress . indexOf ( \",\" ) > 0 ) { ipAddress = ipAddress . substring ( 0 , ipAddress . indexOf ( \",\" ) ) ; } } return ipAddress ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断是否为搜索引擎 [CODESPLIT] public static boolean robot ( HttpServletRequest request ) { String ua = request . getHeader ( \"user-agent\" ) ; return ! StringUtils . isBlank ( ua ) && ( ( ua . contains ( \"Baiduspider\" ) || ua . contains ( \"Googlebot\" ) || ua . contains ( \"sogou\" ) || ua . contains ( \"sina\" ) || ua . contains ( \"iaskspider\" ) || ua . contains ( \"ia_archiver\" ) || ua . contains ( \"Sosospider\" ) || ua . contains ( \"YoudaoBot\" ) || ua . contains ( \"yahoo\" ) || ua . contains ( \"yodao\" ) || ua . contains ( \"MSNBot\" ) || ua . contains ( \"spider\" ) || ua . contains ( \"Twiceler\" ) || ua . contains ( \"Sosoimagespider\" ) || ua . contains ( \"naver.com/robots\" ) || ua . contains ( \"Nutch\" ) || ua . contains ( \"spider\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取COOKIE [CODESPLIT] public static Cookie getCookie ( HttpServletRequest request , String name ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies == null ) return null ; for ( Cookie ck : cookies ) { if ( StringUtils . equalsIgnoreCase ( name , ck . getName ( ) ) ) { return ck ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置COOKIE [CODESPLIT] public static void setCookie ( HttpServletRequest request , HttpServletResponse response , String name , String value , int maxAge , boolean all_sub_domain ) { Cookie cookie = new Cookie ( name , value ) ; cookie . setMaxAge ( maxAge ) ; if ( all_sub_domain ) { String serverName = request . getServerName ( ) ; String domain = domainOfServerName ( serverName ) ; if ( domain != null && domain . indexOf ( ' ' ) != - 1 ) { cookie . setDomain ( ' ' + domain ) ; } } cookie . setPath ( StringPool . SLASH ) ; response . addCookie ( cookie ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取用户访问URL中的根域名 例如 : www . dlog . cn - > dlog . cn [CODESPLIT] public static String domainOfServerName ( String host ) { if ( isIPAddr ( host ) ) { return null ; } String [ ] names = StringUtils . split ( host , ' ' ) ; if ( names == null ) return null ; int len = names . length ; if ( len == 1 ) return null ; if ( len == 3 ) { return makeup ( names [ len - 2 ] , names [ len - 1 ] ) ; } if ( len > 3 ) { String dp = names [ len - 2 ] ; if ( dp . equalsIgnoreCase ( \"com\" ) || dp . equalsIgnoreCase ( \"gov\" ) || dp . equalsIgnoreCase ( \"net\" ) || dp . equalsIgnoreCase ( \"edu\" ) || dp . equalsIgnoreCase ( \"org\" ) ) { return makeup ( names [ len - 3 ] , names [ len - 2 ] , names [ len - 1 ] ) ; } else { return makeup ( names [ len - 2 ] , names [ len - 1 ] ) ; } } return host ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断字符串是否是一个IP地址 [CODESPLIT] public static boolean isIPAddr ( String addr ) { if ( StringUtils . isEmpty ( addr ) ) { return false ; } String [ ] ips = StringUtils . split ( addr , ' ' ) ; if ( ips == null || ips . length != 4 ) { return false ; } try { int ipa = Integer . parseInt ( ips [ 0 ] ) ; int ipb = Integer . parseInt ( ips [ 1 ] ) ; int ipc = Integer . parseInt ( ips [ 2 ] ) ; int ipd = Integer . parseInt ( ips [ 3 ] ) ; return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0 && ipc <= 255 && ipd >= 0 && ipd <= 255 ; } catch ( Exception ignored ) { } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取HTTP端口 [CODESPLIT] public static int httpPort ( HttpServletRequest request ) { try { return new URL ( request . getRequestURL ( ) . toString ( ) ) . getPort ( ) ; } catch ( MalformedURLException excp ) { return 80 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取浏览器提交的整形参数 [CODESPLIT] public static int param ( HttpServletRequest request , String param , int defaultValue ) { return NumberUtils . toInt ( request . getParameter ( param ) , defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取浏览器提交的字符串参 [CODESPLIT] public static String param ( HttpServletRequest request , String param , String defaultValue ) { String value = request . getParameter ( param ) ; return ( StringUtils . isEmpty ( value ) ) ? defaultValue : value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get shaping parameters submitted by the browser [CODESPLIT] public static long param ( HttpServletRequest request , String param , long defaultValue ) { return NumberUtils . toLong ( request . getParameter ( param ) , defaultValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断当前Request是否位Ajax请求，通过消息头来进行判断 . [CODESPLIT] public static boolean ajax ( HttpServletRequest request ) { String x_requested = request . getHeader ( \"x-requested-with\" ) ; return ! Strings . isNullOrEmpty ( x_requested ) && \"XMLHttpRequest\" . equals ( x_requested ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "去html [CODESPLIT] public static String replaceTagHTML ( String src ) { String regex = \"\\\\<(.+?)\\\\>\" ; return StringUtils . isNotEmpty ( src ) ? src . replaceAll ( regex , \"\" ) : \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Log with DEBUG level [CODESPLIT] public static void debug ( String message , Object ... args ) { if ( recordCaller ) { LoggerFactory . getLogger ( getCallerClassName ( ) ) . debug ( message , args ) ; } else { slf4j . debug ( message , args ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Examine stack trace to get caller [CODESPLIT] static CallInfo getCallerInformations ( int level ) { StackTraceElement [ ] callStack = Thread . currentThread ( ) . getStackTrace ( ) ; StackTraceElement caller = callStack [ level ] ; return new CallInfo ( caller . getClassName ( ) , caller . getMethodName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置错误修正等级。其定义如下 <p / > <ul > <li > L : 有 7% 的内容可被修正< / li > <li > M : 有15% 的内容可被修正< / li > <li > Q : 有 25% 的内容可被修正< / li > <li > H : 有 30% 的内容可被修正< / li > < / ul > [CODESPLIT] public QRCodeFormat setErrorCorrectionLevel ( char errorCorrectionLevel ) { switch ( Character . toUpperCase ( errorCorrectionLevel ) ) { case ' ' : this . errorCorrectionLevel = ErrorCorrectionLevel . L ; break ; case ' ' : this . errorCorrectionLevel = ErrorCorrectionLevel . M ; break ; case ' ' : this . errorCorrectionLevel = ErrorCorrectionLevel . Q ; break ; case ' ' : this . errorCorrectionLevel = ErrorCorrectionLevel . H ; break ; default : this . errorCorrectionLevel = ErrorCorrectionLevel . M ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置前景色。值为十六进制的颜色值（与 CSS 定义颜色的值相同，不支持简写），可以忽略「#」符号。 [CODESPLIT] public QRCodeFormat setForeGroundColor ( String foreGroundColor ) { try { this . foreGroundColor = getColor ( foreGroundColor ) ; } catch ( NumberFormatException e ) { this . foreGroundColor = Color . BLACK ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "设置背景色。值为十六进制的颜色值（与 CSS 定义颜色的值相同，不支持简写），可以忽略「#」符号。 [CODESPLIT] public QRCodeFormat setBackGroundColor ( String backGroundColor ) { try { this . backGroundColor = getColor ( backGroundColor ) ; } catch ( NumberFormatException e ) { this . backGroundColor = Color . WHITE ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回提供给编码器额外的参数。 [CODESPLIT] public Hashtable < EncodeHintType , ? > getHints ( ) { hints . clear ( ) ; hints . put ( EncodeHintType . ERROR_CORRECTION , getErrorCorrectionLevel ( ) ) ; hints . put ( EncodeHintType . CHARACTER_SET , getEncode ( ) ) ; hints . put ( EncodeHintType . MARGIN , getMargin ( ) ) ; return hints ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes { @code JSONResponse } to the current { @code WebContext } . [CODESPLIT] public void to ( WebContext context ) { if ( entity == null ) { return ; } HttpServletResponse response = context . response ( ) ; try { response . setCharacterEncoding ( \"UTF-8\" ) ; response . setHeader ( \"Content-Type\" , mediaType ) ; if ( status > 0 ) { response . setStatus ( status ) ; } if ( entity instanceof String ) { response . getWriter ( ) . write ( ( String ) entity ) ; return ; } GsonBuilder builder = new GsonBuilder ( ) ; Set < Class < ? > > classes = new HashSet < Class < ? > > ( ) ; parse ( entity . getClass ( ) , classes ) ; for ( Class < ? > clazz : classes ) { builder . registerTypeAdapter ( clazz , new ValueTypeJsonSerializer < Object > ( ) ) ; } // XXX: Any options? Gson gson = builder . create ( ) ; response . getWriter ( ) . write ( gson . toJson ( entity ) ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets the input validator for this cell editor . < / p > <p > The validator is given the ( integer ) value to be validated and must return a string indicating whether the given value is valid ; <code > null< / code > means valid and non - <code > null< / code > means invalid with the result being the error message to display to the end user . < / p > <p > This is simply a better - typed version of { @link #setValidator ( Function ) } . < / p > [CODESPLIT] public void setIntegerValidator ( Function < Integer , String > valueToErrorMessage ) { setValidator ( valueToErrorMessage . compose ( v -> Integer . valueOf ( v ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将文本头与数据共同转成csv字符串 [CODESPLIT] @ SuppressWarnings ( { \"unchecked\" , \"rawtypes\" } ) public static String createCSV ( List headers , List data , List columns ) { StringBuffer strOut = new StringBuffer ( \"\" ) ; if ( null != headers && ! headers . isEmpty ( ) ) { // 如果文本不为空则添加到csv字符串中 listToCSV ( strOut , headers ) ; } if ( null == data || data . isEmpty ( ) ) { return strOut . toString ( ) ; } Iterator itr = data . iterator ( ) ; while ( itr . hasNext ( ) ) { Object obj = itr . next ( ) ; // 将数据添加到csv字符串 Class cls = obj . getClass ( ) ; if ( cls != null && cls . isArray ( ) ) { Object [ ] objs = ( Object [ ] ) obj ; for ( Object obj1 : objs ) { createCol ( strOut , obj1 ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; // 去点多余逗号 strOut . append ( NEWLINE ) ; } else if ( obj instanceof List ) { List objlist = ( List ) obj ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制，默认全部显示 listToCSV ( strOut , objlist ) ; } else { for ( Object column : columns ) { createCol ( strOut , objlist . get ( ( Integer ) column ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else if ( obj instanceof Map ) { Map objmap = ( Map ) obj ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制，默认全部显示 Set keyset = objmap . keySet ( ) ; for ( Object key : keyset ) { createCol ( strOut , objmap . get ( key ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } else { for ( Object column : columns ) { createCol ( strOut , objmap . get ( column ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else if ( obj instanceof Model ) { Model objmodel = ( Model ) obj ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制，默认全部显示 Set < Entry < String , Object > > entries = objmodel . _getAttrsEntrySet ( ) ; for ( Entry entry : entries ) { createCol ( strOut , entry . getValue ( ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } else { for ( Object column : columns ) { createCol ( strOut , objmodel . get ( column + EMPTY ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else if ( obj instanceof Record ) { Record objrecord = ( Record ) obj ; Map < String , Object > map = objrecord . getColumns ( ) ; if ( null == columns || columns . isEmpty ( ) ) { // 如果没有限制，默认全部显示 Set < String > keys = map . keySet ( ) ; for ( String key : keys ) { createCol ( strOut , objrecord . get ( key ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } else { for ( Object column : columns ) { createCol ( strOut , objrecord . get ( column + EMPTY ) ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } } else { while ( itr . hasNext ( ) ) { Object objs = itr . next ( ) ; if ( objs != null ) { createCol ( strOut , objs ) ; strOut . append ( NEWLINE ) ; } } } obj = null ; } return strOut . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "把单纯的集合转化成csv字符串 [CODESPLIT] public static void listToCSV ( StringBuffer strOut , List < ? > list ) { if ( null != list && ! list . isEmpty ( ) ) { // 如果文本不为空则添加到csv字符串中 for ( Object aList : list ) { createCol ( strOut , aList ) ; strOut . append ( COMMA ) ; } strOut = strOut . deleteCharAt ( strOut . length ( ) - 1 ) ; strOut . append ( NEWLINE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "把单个元素转化 [CODESPLIT] public static void createCol ( StringBuffer strOut , Object obj ) { if ( obj != null ) { strOut . append ( QUOTE ) ; String content ; if ( obj instanceof Boolean ) { content = obj . toString ( ) ; } else if ( obj instanceof Calendar ) { content = obj . toString ( ) ; } else if ( obj instanceof Timestamp ) { content = DP_YYYY_MM_DD_HH_MM . format ( new Date ( ( ( Timestamp ) obj ) . getTime ( ) ) ) ; } else if ( obj instanceof Date ) { content = DP_YYYY_MM_DD_HH_MM . format ( ( Date ) obj ) ; } else { content = write ( String . valueOf ( obj ) ) ; } strOut . append ( content ) ; strOut . append ( QUOTE ) ; } else { strOut . append ( \"\\\" \\\" \" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "特殊字符的转换 \\ t - > \\\\ t [CODESPLIT] public static String replace ( String original , String pattern , String replace ) { final int len = pattern . length ( ) ; int found = original . indexOf ( pattern ) ; if ( found > - 1 ) { StringBuilder sb = new StringBuilder ( ) ; int start = 0 ; while ( found != - 1 ) { sb . append ( original . substring ( start , found ) ) ; sb . append ( replace ) ; start = found + len ; found = original . indexOf ( pattern , start ) ; } sb . append ( original . substring ( start ) ) ; return sb . toString ( ) ; } else { return original ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts char array into byte array by stripping the high byte of each character . [CODESPLIT] public static byte [ ] toSimpleByteArray ( char [ ] carr ) { byte [ ] barr = new byte [ carr . length ] ; for ( int i = 0 ; i < carr . length ; i ++ ) { barr [ i ] = ( byte ) carr [ i ] ; } return barr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts char sequence into byte array . [CODESPLIT] public static byte [ ] toSimpleByteArray ( CharSequence charSequence ) { byte [ ] barr = new byte [ charSequence . length ( ) ] ; for ( int i = 0 ; i < barr . length ; i ++ ) { barr [ i ] = ( byte ) charSequence . charAt ( i ) ; } return barr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts byte array to char array by simply extending bytes to chars . [CODESPLIT] public static char [ ] toSimpleCharArray ( byte [ ] barr ) { char [ ] carr = new char [ barr . length ] ; for ( int i = 0 ; i < barr . length ; i ++ ) { carr [ i ] = ( char ) ( barr [ i ] & 0xFF ) ; } return carr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts char array into { [CODESPLIT] public static byte [ ] toAsciiByteArray ( char [ ] carr ) { byte [ ] barr = new byte [ carr . length ] ; for ( int i = 0 ; i < carr . length ; i ++ ) { barr [ i ] = ( byte ) ( ( int ) ( carr [ i ] <= 0xFF ? carr [ i ] : 0x3F ) ) ; } return barr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts char sequence into ASCII byte array . [CODESPLIT] public static byte [ ] toAsciiByteArray ( CharSequence charSequence ) { byte [ ] barr = new byte [ charSequence . length ( ) ] ; for ( int i = 0 ; i < barr . length ; i ++ ) { char c = charSequence . charAt ( i ) ; barr [ i ] = ( byte ) ( ( int ) ( c <= 0xFF ? c : 0x3F ) ) ; } return barr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates whether the given character is in the <i > sub - delims< / i > set . [CODESPLIT] protected static boolean isSubDelimiter ( int c ) { return c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' || c == ' ' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates whether the given character is in the <i > unreserved< / i > set . [CODESPLIT] protected static boolean isUnreserved ( char c ) { return isAlpha ( c ) || isDigit ( c ) || c == ' ' || c == ' ' || c == ' ' || c == ' ' ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the very first index of any char from provided string starting from specified index offset . Returns index of founded char or <code > - 1< / code > if nothing found . [CODESPLIT] public static int indexOfChars ( String string , String chars , int startindex ) { int stringLen = string . length ( ) ; int charsLen = chars . length ( ) ; if ( startindex < 0 ) { startindex = 0 ; } for ( int i = startindex ; i < stringLen ; i ++ ) { char c = string . charAt ( i ) ; for ( int j = 0 ; j < charsLen ; j ++ ) { if ( c == chars . charAt ( j ) ) { return i ; } } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the very first index of any char from provided string starting from specified index offset . Returns index of founded char or <code > - 1< / code > if nothing found . [CODESPLIT] public static int indexOfChars ( String string , char [ ] chars , int startindex ) { int stringLen = string . length ( ) ; for ( int i = startindex ; i < stringLen ; i ++ ) { char c = string . charAt ( i ) ; for ( char aChar : chars ) { if ( c == aChar ) { return i ; } } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if string { [CODESPLIT] public static boolean containsOnlyDigitsAndSigns ( String string ) { int size = string . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { char c = string . charAt ( i ) ; if ( ( ! CharKit . isDigit ( c ) ) && ( c != ' ' ) && ( c != ' ' ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Splits a string in several parts ( tokens ) that are separated by delimiter characters . Delimiter may contains any number of character and it is always surrounded by two strings . [CODESPLIT] public static String [ ] splitc ( String src , String d ) { if ( ( d . length ( ) == 0 ) || ( src . length ( ) == 0 ) ) { return new String [ ] { src } ; } char [ ] delimiters = d . toCharArray ( ) ; char [ ] srcc = src . toCharArray ( ) ; int maxparts = srcc . length + 1 ; int [ ] start = new int [ maxparts ] ; int [ ] end = new int [ maxparts ] ; int count = 0 ; start [ 0 ] = 0 ; int s = 0 , e ; if ( CharKit . equalsOne ( srcc [ 0 ] , delimiters ) ) { // string starts with delimiter end [ 0 ] = 0 ; count ++ ; s = CharKit . findFirstDiff ( srcc , 1 , delimiters ) ; if ( s == - 1 ) { // nothing after delimiters return new String [ ] { StringUtils . EMPTY , StringUtils . EMPTY } ; } start [ 1 ] = s ; // new start } while ( true ) { // find new end e = CharKit . findFirstEqual ( srcc , s , delimiters ) ; if ( e == - 1 ) { end [ count ] = srcc . length ; break ; } end [ count ] = e ; // find new start count ++ ; s = CharKit . findFirstDiff ( srcc , e , delimiters ) ; if ( s == - 1 ) { start [ count ] = end [ count ] = srcc . length ; break ; } start [ count ] = s ; } count ++ ; String [ ] result = new String [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { result [ i ] = src . substring ( start [ i ] , end [ i ] ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for locale data and creates new if it doesn t exist . [CODESPLIT] protected static LocaleData lookupLocaleData ( String code ) { LocaleData localeData = locales . get ( code ) ; if ( localeData == null ) { String [ ] data = decodeLocaleCode ( code ) ; localeData = new LocaleData ( new Locale ( data [ 0 ] , data [ 1 ] , data [ 2 ] ) ) ; locales . put ( code , localeData ) ; } return localeData ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Locale from cache . [CODESPLIT] public static Locale getLocale ( String language , String country , String variant ) { LocaleData localeData = lookupLocaleData ( resolveLocaleCode ( language , country , variant ) ) ; return localeData . locale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Locale from cache where Locale may be specified also using language code . Converts a locale string like en en_US or en_US_win to <b > new< / b > Java locale object . [CODESPLIT] public static Locale getLocale ( String languageCode ) { LocaleData localeData = lookupLocaleData ( languageCode ) ; return localeData . locale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms locale data to locale code . <code > null< / code > values are allowed . [CODESPLIT] public static String resolveLocaleCode ( String lang , String country , String variant ) { StringBuilder code = new StringBuilder ( lang ) ; if ( ! StringUtils . isEmpty ( country ) ) { code . append ( ' ' ) . append ( country ) ; if ( ! StringUtils . isEmpty ( variant ) ) { code . append ( ' ' ) . append ( variant ) ; } } return code . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes locale code in string array that can be used for <code > Locale< / code > constructor . [CODESPLIT] public static String [ ] decodeLocaleCode ( String localeCode ) { String result [ ] = new String [ 3 ] ; String [ ] data = CharKit . splitc ( localeCode , ' ' ) ; result [ 0 ] = data [ 0 ] ; result [ 1 ] = result [ 2 ] = StringPool . EMPTY ; if ( data . length >= 2 ) { result [ 1 ] = data [ 1 ] ; if ( data . length >= 3 ) { result [ 2 ] = data [ 2 ] ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns cached <code > NumberFormat< / code > instance for specified locale . [CODESPLIT] public static NumberFormat getNumberFormat ( Locale locale ) { LocaleData localeData = lookupLocaleData ( locale ) ; NumberFormat nf = localeData . numberFormat ; if ( nf == null ) { nf = NumberFormat . getInstance ( locale ) ; localeData . numberFormat = nf ; } return nf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes { @code XMLResponse } to the current { @code WebContext } . [CODESPLIT] public void to ( WebContext context ) { if ( entity == null ) { return ; } HttpServletResponse response = context . response ( ) ; try { response . setCharacterEncoding ( \"UTF-8\" ) ; response . setHeader ( \"Content-Type\" , mediaType ) ; if ( status > 0 ) { response . setStatus ( status ) ; } if ( entity instanceof String ) { response . getWriter ( ) . write ( ( String ) entity ) ; return ; } Marshaller marshaller = JAXBContext . newInstance ( entity . getClass ( ) ) . createMarshaller ( ) ; marshaller . setAdapter ( new ValueTypeXmlAdapter < Object > ( ) ) ; marshaller . marshal ( entity , response . getWriter ( ) ) ; } catch ( Exception e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called by { [CODESPLIT] public void init ( Class < ? extends T > impl , Class < T > extensionPoint ) { this . impl = impl ; this . extensionPoint = extensionPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "渲染模板 [CODESPLIT] public static String render ( String templateContent , Map < String , Object > paramMap ) { StringWriter writer = new StringWriter ( ) ; try { Configuration cfg = new Configuration ( Configuration . VERSION_2_3_22 ) ; cfg . setTemplateLoader ( new StringTemplateLoader ( templateContent ) ) ; cfg . setDefaultEncoding ( \"UTF-8\" ) ; Template template = cfg . getTemplate ( \"\" ) ; template . process ( paramMap , writer ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; log . error ( e . getMessage ( ) ) ; } catch ( TemplateException e ) { e . printStackTrace ( ) ; log . error ( e . getMessage ( ) ) ; } return writer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start this job now ( well ASAP ) [CODESPLIT] public Promise < V > now ( ) { final Promise < V > smartFuture = new Promise < V > ( ) ; JobsPlugin . executor . submit ( getJobCallingCallable ( smartFuture ) ) ; return smartFuture ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start this job in several seconds [CODESPLIT] public Promise < V > in ( int seconds ) { final Promise < V > smartFuture = new Promise < V > ( ) ; JobsPlugin . executor . schedule ( getJobCallingCallable ( smartFuture ) , seconds , TimeUnit . SECONDS ) ; return smartFuture ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Customize Invocation [CODESPLIT] @ Override public void onException ( Throwable e ) { wasError = true ; lastException = e ; try { super . onException ( e ) ; } catch ( Throwable ex ) { logger . error ( \"Error during job execution (%s)\" , this , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "hidden [CODESPLIT] public static Resource createResource ( String resourcePath ) throws IOException { if ( resourcePath . startsWith ( ResourceUtils . CLASSPATH_URL_PREFIX ) ) { return Resource . newClassPathResource ( resourcePath . substring ( ResourceUtils . CLASSPATH_URL_PREFIX . length ( ) ) ) ; } else if ( resourcePath . startsWith ( ResourceUtils . FILE_URL_PREFIX ) ) { return Resource . newResource ( new File ( resourcePath . substring ( ResourceUtils . FILE_URL_PREFIX . length ( ) ) ) ) ; } else if ( resourcePath . startsWith ( \"/\" ) ) { return Resource . newResource ( new File ( resourcePath ) ) ; } try { if ( Files . exists ( Paths . get ( resourcePath ) ) ) { return Resource . newResource ( new File ( resourcePath ) ) ; } // path seem to be valid but nothing exists there throw new IOException ( \"Missing file at resourcePath=\" + resourcePath ) ; } catch ( InvalidPathException e ) { throw new IOException ( \"Invalid path or unknown protocol in resourcePath=\" + resourcePath , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "VisibleForTesting [CODESPLIT] static MediaType getMediaType ( HttpServletRequest request , String headerName ) { final String mediaTypeName = request . getHeader ( headerName ) ; if ( mediaTypeName == null ) { return null ; } try { return MediaType . valueOf ( mediaTypeName ) ; } catch ( InvalidMediaTypeException ignored ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resize an image [CODESPLIT] public static void resize ( File originalImage , File to , int w , int h ) { resize ( originalImage , to , w , h , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resize an image [CODESPLIT] public static void resize ( File originalImage , File to , int w , int h , boolean keepRatio ) { try { BufferedImage source = ImageIO . read ( originalImage ) ; int owidth = source . getWidth ( ) ; int oheight = source . getHeight ( ) ; double ratio = ( double ) owidth / oheight ; int maxWidth = w ; int maxHeight = h ; if ( w < 0 && h < 0 ) { w = owidth ; h = oheight ; } if ( w < 0 && h > 0 ) { w = ( int ) ( h * ratio ) ; } if ( w > 0 && h < 0 ) { h = ( int ) ( w / ratio ) ; } if ( keepRatio ) { h = ( int ) ( w / ratio ) ; if ( h > maxHeight ) { h = maxHeight ; w = ( int ) ( h * ratio ) ; } if ( w > maxWidth ) { w = maxWidth ; h = ( int ) ( w / ratio ) ; } } String mimeType = \"image/jpeg\" ; if ( to . getName ( ) . endsWith ( \".png\" ) ) { mimeType = \"image/png\" ; } if ( to . getName ( ) . endsWith ( \".gif\" ) ) { mimeType = \"image/gif\" ; } // out BufferedImage dest = new BufferedImage ( w , h , BufferedImage . TYPE_INT_RGB ) ; Image srcSized = source . getScaledInstance ( w , h , Image . SCALE_SMOOTH ) ; Graphics graphics = dest . getGraphics ( ) ; graphics . setColor ( Color . WHITE ) ; graphics . fillRect ( 0 , 0 , w , h ) ; graphics . drawImage ( srcSized , 0 , 0 , null ) ; ImageWriter writer = ImageIO . getImageWritersByMIMEType ( mimeType ) . next ( ) ; ImageWriteParam params = writer . getDefaultWriteParam ( ) ; FileImageOutputStream toFs = new FileImageOutputStream ( to ) ; writer . setOutput ( toFs ) ; IIOImage image = new IIOImage ( dest , null , null ) ; writer . write ( null , image , params ) ; toFs . flush ( ) ; toFs . close ( ) ; writer . dispose ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Crop an image [CODESPLIT] public static void crop ( File originalImage , File to , int x1 , int y1 , int x2 , int y2 ) { try { BufferedImage source = ImageIO . read ( originalImage ) ; String mimeType = \"image/jpeg\" ; if ( to . getName ( ) . endsWith ( \".png\" ) ) { mimeType = \"image/png\" ; } if ( to . getName ( ) . endsWith ( \".gif\" ) ) { mimeType = \"image/gif\" ; } int width = x2 - x1 ; int height = y2 - y1 ; // out BufferedImage dest = new BufferedImage ( width , height , BufferedImage . TYPE_INT_RGB ) ; Image croppedImage = source . getSubimage ( x1 , y1 , width , height ) ; Graphics graphics = dest . getGraphics ( ) ; graphics . setColor ( Color . WHITE ) ; graphics . fillRect ( 0 , 0 , width , height ) ; graphics . drawImage ( croppedImage , 0 , 0 , null ) ; ImageWriter writer = ImageIO . getImageWritersByMIMEType ( mimeType ) . next ( ) ; ImageWriteParam params = writer . getDefaultWriteParam ( ) ; writer . setOutput ( new FileImageOutputStream ( to ) ) ; IIOImage image = new IIOImage ( dest , null , null ) ; writer . write ( null , image , params ) ; writer . dispose ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode an image to base64 using a data : URI [CODESPLIT] public static String toBase64 ( File image ) throws IOException { return \"data:\" + MimeTypes . getMimeType ( image . getName ( ) ) + \";base64,\" + Codec . encodeBASE64 ( IO . readContent ( image ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将指定的图片加入到当前图片中的指定位置 . 即向图片中打水印 . [CODESPLIT] public void add ( File dest , File file , int position ) { if ( dest . exists ( ) && ! dest . isDirectory ( ) ) { String fn = file . getName ( ) . toLowerCase ( ) ; int opacityType = fn . endsWith ( \".png\" ) || fn . endsWith ( \"gif\" ) ? BufferedImage . TYPE_INT_ARGB : BufferedImage . TYPE_INT_RGB ; Image destImg ; try { destImg = ImageIO . read ( dest ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } int width = destImg . getWidth ( null ) ; int height = destImg . getHeight ( null ) ; final BufferedImage image = new BufferedImage ( width , height , opacityType ) ; Image src ; try { src = ImageIO . read ( file ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } int ww = src . getWidth ( null ) ; int hh = src . getHeight ( null ) ; int WW , HH ; switch ( position ) { case 1 : WW = 0 ; HH = 0 ; break ; case 2 : WW = ( width - ww ) / 2 ; HH = 0 ; break ; case 3 : WW = width - ww ; HH = 0 ; break ; case 4 : WW = 0 ; HH = ( height - hh ) / 2 ; break ; case 5 : WW = ( width - ww ) / 2 ; HH = ( height - hh ) / 2 ; break ; case 6 : WW = width - ww ; HH = ( height - hh ) / 2 ; break ; case 7 : WW = 0 ; HH = height - hh ; break ; case 8 : WW = ( width - ww ) / 2 ; HH = height - hh ; break ; default : WW = width - ww ; HH = height - hh ; } Graphics g = image . createGraphics ( ) ; g . drawImage ( src , WW , HH , ww , hh , null ) ; g . dispose ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates commonly used { [CODESPLIT] public static MacroResolver createMapMacroResolver ( final Map map ) { return new MacroResolver ( ) { @ Override public String resolve ( String macroName ) { Object value = map . get ( macroName ) ; if ( value == null ) { return null ; } return value . toString ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses string template and replaces macros with resolved values . [CODESPLIT] public String parse ( String template , MacroResolver macroResolver ) { StringBuilder result = new StringBuilder ( template . length ( ) ) ; int i = 0 ; int len = template . length ( ) ; int startLen = macroStart . length ( ) ; int endLen = macroEnd . length ( ) ; while ( i < len ) { int ndx = template . indexOf ( macroStart , i ) ; if ( ndx == - 1 ) { result . append ( i == 0 ? template : template . substring ( i ) ) ; break ; } // check escaped int j = ndx - 1 ; boolean escape = false ; int count = 0 ; while ( ( j >= 0 ) && ( template . charAt ( j ) == escapeChar ) ) { escape = ! escape ; if ( escape ) { count ++ ; } j -- ; } if ( resolveEscapes ) { result . append ( template . substring ( i , ndx - count ) ) ; } else { result . append ( template . substring ( i , ndx ) ) ; } if ( escape ) { result . append ( macroStart ) ; i = ndx + startLen ; continue ; } // find macros end ndx += startLen ; int ndx2 = template . indexOf ( macroEnd , ndx ) ; if ( ndx2 == - 1 ) { throw new IllegalArgumentException ( \"Invalid template, unclosed macro at: \" + ( ndx - startLen ) ) ; } // detect inner macros, there is no escaping int ndx1 = ndx ; while ( ndx1 < ndx2 ) { int n = indexOf ( template , macroStart , ndx1 , ndx2 ) ; if ( n == - 1 ) { break ; } ndx1 = n + startLen ; } String name = template . substring ( ndx1 , ndx2 ) ; // find value and append Object value ; if ( missingKeyReplacement != null || ! replaceMissingKey ) { try { value = macroResolver . resolve ( name ) ; } catch ( Exception ignore ) { value = null ; } if ( value == null ) { if ( replaceMissingKey ) { value = missingKeyReplacement ; } else { value = template . substring ( ndx1 - startLen , ndx2 + 1 ) ; } } } else { value = macroResolver . resolve ( name ) ; if ( value == null ) { value = StringPool . EMPTY ; } } if ( ndx == ndx1 ) { String stringValue = value . toString ( ) ; if ( parseValues ) { if ( stringValue . contains ( macroStart ) ) { stringValue = parse ( stringValue , macroResolver ) ; } } result . append ( stringValue ) ; i = ndx2 + endLen ; } else { // inner macro template = template . substring ( 0 , ndx1 - startLen ) + value . toString ( ) + template . substring ( ndx2 + endLen ) ; len = template . length ( ) ; i = ndx - startLen ; } } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the code in a new thread after a delay [CODESPLIT] public static Future < ? > invoke ( final Invocation invocation , long millis ) { return executor . schedule ( invocation , millis , TimeUnit . MILLISECONDS ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Run the code in the same thread than caller . [CODESPLIT] public static void invokeInThread ( DirectInvocation invocation ) { boolean retry = true ; while ( retry ) { invocation . run ( ) ; if ( invocation . retry == null ) { retry = false ; } else { try { if ( invocation . retry . task != null ) { invocation . retry . task . get ( ) ; } else { Thread . sleep ( invocation . retry . timeout ) ; } } catch ( Exception e ) { throw new UnexpectedException ( e ) ; } retry = true ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets credentials for use when accessing service APIs . Note that multiple calls to this method override previously set credentials . [CODESPLIT] public void setCredentials ( @ Nonnull List < ServiceClientCredentials > credentials ) { credentialsProvider . clear ( ) ; for ( final ServiceClientCredentials cred : credentials ) { final URI uri = cred . getBaseUri ( ) ; credentialsProvider . setCredentials ( new AuthScope ( new HttpHost ( uri . getHost ( ) , uri . getPort ( ) , uri . getScheme ( ) ) ) , new UsernamePasswordCredentials ( cred . getUsername ( ) , cred . getPassword ( ) . toString ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns rest operations object suitable for use with the specified credentials [CODESPLIT] @ Nonnull public RestOperations getRestOperations ( ) { final HttpClientBuilder builder = HttpClientBuilder . create ( ) ; initDefaultHttpClientBuilder ( builder ) ; httpRequestFactory = new HttpComponentsClientHttpRequestFactory ( builder . build ( ) ) ; final RestTemplate restTemplate = new RestTemplate ( messageConverters ) ; restTemplate . setRequestFactory ( httpRequestFactory ) ; return restTemplate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rendering errors information in Json format . [CODESPLIT] protected void renderAjaxError ( String error , Exception e ) { renderJson ( AjaxMessage . error ( error , e ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "In the form of JSON rendering forbidden information . [CODESPLIT] protected < T > void renderAjaxForbidden ( String message , T data ) { renderJson ( AjaxMessage . forbidden ( message , data ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Render view as a string [CODESPLIT] protected String template ( String view ) { final Enumeration < String > attrs = getAttrNames ( ) ; final Map < String , Object > root = Maps . newHashMap ( ) ; while ( attrs . hasMoreElements ( ) ) { String attrName = attrs . nextElement ( ) ; root . put ( attrName , getAttr ( attrName ) ) ; } return Freemarkers . processString ( view , root ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Based on the current path structure is going to jump full Action of the path [CODESPLIT] protected String parsePath ( String currentActionPath , String url ) { if ( url . startsWith ( SLASH ) ) { return url . split ( \"\\\\?\" ) [ 0 ] ; } else if ( ! url . contains ( SLASH ) ) { return SLASH + currentActionPath . split ( SLASH ) [ 1 ] + SLASH + url . split ( \"\\\\?\" ) [ 0 ] ; } else if ( url . contains ( \"http:\" ) || url . contains ( \"https:\" ) ) { return null ; } ///abc/def\",\"bcd/efg?abc return currentActionPath + SLASH + url . split ( \"\\\\?\" ) [ 0 ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "According to the request information of jquery . Datatables the results of the query and returns the JSON data to the client . <p / > The specified query set the data . [CODESPLIT] protected < E > void renderDataTables ( DTCriterias criterias , Page < E > datas ) { Preconditions . checkNotNull ( criterias , \"datatable criterias is must be not null.\" ) ; DTResponse < E > response = DTResponse . build ( criterias , datas . getList ( ) , datas . getTotalRow ( ) , datas . getTotalPage ( ) ) ; renderJson ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "According to the request information of jquery . Datatables the results of the query and returns the JSON data to the client . <p / > According to the SQL configuration file in accordance with the Convention model_name . coloumns \\ model_name . where \\ model_name . order configured SQL to query and returns the results to the client . [CODESPLIT] protected void renderDataTables ( DTCriterias criterias , String model_name ) { Preconditions . checkNotNull ( criterias , \"datatable criterias is must be not null.\" ) ; final Page < Record > datas = DTDao . paginate ( model_name , criterias ) ; DTResponse response = DTResponse . build ( criterias , datas . getList ( ) , datas . getTotalRow ( ) , datas . getTotalRow ( ) ) ; renderJson ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "According to the request information of jquery . Datatables the results of the query and returns the JSON data to the client . <p / > According to the SQL configuration file in accordance with the Convention model_name . coloumns \\ model_name . where \\ model_name . order configured SQL to query and specify the parameters and return results to the client . [CODESPLIT] protected void renderDataTables ( DTCriterias criterias , String sqlGroupName , List < Object > params ) { Preconditions . checkNotNull ( criterias , \"datatable criterias is must be not null.\" ) ; final Page < Record > datas = DTDao . paginate ( sqlGroupName , criterias , params ) ; DTResponse response = DTResponse . build ( criterias , datas . getList ( ) , datas . getTotalRow ( ) , datas . getTotalRow ( ) ) ; renderJson ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The source of data for rendering the jQuery Datatables [CODESPLIT] protected void renderDataTables ( Class < ? extends Model > m_cls ) { DTCriterias criterias = getCriterias ( ) ; Preconditions . checkNotNull ( criterias , \"datatable criterias is must be not null.\" ) ; DTResponse response = criterias . response ( m_cls ) ; renderJson ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "rendering the empty datasource . [CODESPLIT] protected void renderEmptyDataTables ( DTCriterias criterias ) { Preconditions . checkNotNull ( criterias , \"datatable criterias is must be not null.\" ) ; DTResponse response = DTResponse . build ( criterias , Collections . EMPTY_LIST , 0 , 0 ) ; renderJson ( response ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "渲染DataGrid的表格展示，支持排序和搜索 [CODESPLIT] protected void renderEasyUIDataGrid ( Class < ? extends Model > modelClass ) { final Optional < DataGridReq > reqOptional = EuiDataGrid . req ( getRequest ( ) ) ; if ( reqOptional . isPresent ( ) ) { renderJson ( EuiDataGrid . rsp ( reqOptional . get ( ) , modelClass ) ) ; } else { renderJson ( EuiDataGrid . EMPTY_DATAGRID ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "渲染DataGrid的表格展示，支持排序和搜索 [CODESPLIT] protected void renderEasyUIDataGrid ( DataGridReq gridReq , String sqlGroupName ) { Preconditions . checkNotNull ( gridReq , \"参数不能为空\");   renderJson ( EuiDataGrid . rsp ( gridReq , sqlGroupName ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "渲染DataGrid的表格展示，支持排序和搜索 [CODESPLIT] protected void renderEasyUIDataGrid ( final Page < Record > paginate ) { Preconditions . checkNotNull ( paginate , \"参数不能为空\");   renderJson ( EuiDataGrid . rsp ( paginate ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "渲染DataGrid的表格展示，支持排序和搜索 [CODESPLIT] protected void renderEasyUIDataGrid ( String sqlGroupName , List < Object > params ) { Preconditions . checkNotNull ( sqlGroupName , \"sql Group Name 不能为空\");   final Optional < DataGridReq > reqOptional = EuiDataGrid . req ( getRequest ( ) ) ; if ( reqOptional . isPresent ( ) ) { renderJson ( EuiDataGrid . rsp ( reqOptional . get ( ) , sqlGroupName , params ) ) ; } else { renderJson ( EuiDataGrid . EMPTY_DATAGRID ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For information on the logged in user . <p / > This access is through the way the Cookie and Sessionw [CODESPLIT] protected < M extends Model > Optional < M > getLogin ( ) { final HttpServletRequest request = getRequest ( ) ; if ( SecurityKit . isLogin ( request ) ) { final M user = SecurityKit . getLoginUser ( request ) ; return Optional . of ( user ) ; } else { return Optional . absent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The current Shiro login user . <p / > If it opens the secruity function can call this method to obtain the logged in user . [CODESPLIT] protected < U extends Model > Optional < AppUser < U > > getPrincipal ( ) { if ( Securitys . isLogin ( ) ) { final AppUser < U > appUser = Securitys . getLogin ( ) ; return Optional . of ( appUser ) ; } return Optional . absent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JodaTime time request [CODESPLIT] protected DateTime getDate ( String name , DateTime defaultValue ) { String value = getRequest ( ) . getParameter ( name ) ; if ( Strings . isNullOrEmpty ( value ) ) { return defaultValue ; } return DateKit . parseDashYMDDateTime ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JodaTime time request [CODESPLIT] protected DateTime getDateTime ( String name , DateTime defaultValue ) { String value = getRequest ( ) . getParameter ( name ) ; if ( Strings . isNullOrEmpty ( value ) ) { return defaultValue ; } return DateKit . parseDashYMDHMSDateTime ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the input items to the underlying ComboBoxCellEditor . [CODESPLIT] public void setItems ( List < V > items ) { final List < V > its = items == null ? ImmutableList . of ( ) : items ; this . items = its ; getComboBoxCellEditor ( ) . setInput ( items ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes this HTTP response to the specified Web context . [CODESPLIT] public void to ( WebContext context ) { HttpServletResponse response = context . response ( ) ; if ( ! mediaType . isEmpty ( ) ) { response . setHeader ( \"Content-Type\" , mediaType ) ; } if ( status > 0 ) { response . setStatus ( status ) ; } try { response . sendRedirect ( response . encodeRedirectURL ( url ) ) ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends Web endpoint invocation result to the client as HTTP response . This method processes the response as the following steps : <ol > <li > If the Web endpoint invocation result is instance of { @code Response } sends the HTTP response to the client by invoking { @code Response#to ( WebContext ) } method with the current Web context . < / li > <li > ( If it does not so ) If the Web endpoint method is qualified by { @code @Generates } annotation this class determines the { @code Response } type from the specified MIME media type by invoking { @code Configuration#responseType ( String ) } . < / li > <li > If the Web endpoint method is qualified by { @code @Negotiated } annotation this class determines the { @code Response } type from the MIME media type specified on Accept HTTP request header by invoking { @code Configuration#responseType ( String ) } . < / li > <li > ( If it does not so ) If the Web endpoint method is qualified neither by { @code @Generates } nor { @code @Negotiated } annotation this class determines the { @code Response } type by invoking { @code Configuration#responseType ( String ) } with empty string . < / li > <li > Constructs { @code Response } instance and sets the MIME media type and Web endpoint invocation result then sends the HTTP response to the client by invoking { @code Response#to ( WebContext ) } method with the current Web context . < / li > < / ol > [CODESPLIT] public boolean apply ( WebContext context ) { Object result = context . result ( ) ; if ( result instanceof Response ) { Response response = ( Response ) result ; response . to ( context ) ; return true ; } try { Method method = context . method ( ) ; String contentType = \"\" ; Generates generates = method . getAnnotation ( Generates . class ) ; Negotiated negotiated = method . getAnnotation ( Negotiated . class ) ; if ( generates != null ) { logger . debug ( \"Web endpoint [\" + method . getDeclaringClass ( ) . getName ( ) + \"#\" + method . getName ( ) + \"] is qualified by [\" + generates + \"]\" ) ; contentType = generates . value ( ) ; } else if ( negotiated != null ) { logger . debug ( \"Web endpoint [\" + method . getDeclaringClass ( ) . getName ( ) + \"#\" + method . getName ( ) + \"] is qualified by [\" + negotiated + \"]\" ) ; String header = context . request ( ) . getHeader ( \"Accept\" ) ; if ( header != null ) { // TODO: Parse. contentType = header ; } } logger . debug ( \"MIME media type is [\" + contentType + \"]\" ) ; Class < ? extends Response > responseType = context . configuration ( ) . responseTypes ( ) . get ( contentType ) ; if ( responseType == null ) { throw new CannotSendResponseException ( HttpServletResponse . SC_UNSUPPORTED_MEDIA_TYPE , \"Configuration [\" + context . configuration ( ) . getClass ( ) . getName ( ) + \"] does not provide a response type corresponding to [\" + contentType + \"] media type\" ) ; } Response response = responseType . newInstance ( ) ; response . mediaType ( contentType ) ; response . entity ( result ) ; response . to ( context ) ; return true ; } catch ( CannotSendResponseException exception ) { logger . warn ( \"Failed to send HTTP response\" , exception ) ; try { context . response ( ) . sendError ( exception . status ( ) ) ; return false ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } catch ( Exception e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encapsulates the logic for associating property source with a given servlet . [CODESPLIT] @ Nonnull public static AutoCloseable register ( @ Nonnull ServletInitializer servletInitializer , @ Nonnull PropertySource < ? > source ) { final BigInteger bigInteger = new BigInteger ( 64 , ThreadLocalRandom . current ( ) ) ; final String key = bigInteger . toString ( 16 ) ; if ( PROPERTIES . containsKey ( key ) ) { return register ( servletInitializer , source ) ; // shouldn't happen } // associate this key with the context parameter servletInitializer . setInitParameter ( PROPERTY_SOURCE_SERVLET_CONFIG_KEY , key ) ; // ... and put it to the globally visible properties map PROPERTIES . put ( key , source ) ; return new AutoCloseable ( ) { @ Override public void close ( ) { PROPERTIES . remove ( key ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hex解码 . [CODESPLIT] public static byte [ ] decodeHex ( String input ) { try { return Hex . decodeHex ( input . toCharArray ( ) ) ; } catch ( DecoderException e ) { throw ExceptionKit . unchecked ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Base62编码。 [CODESPLIT] public static String encodeBase62 ( byte [ ] input ) { char [ ] chars = new char [ input . length ] ; for ( int i = 0 ; i < input . length ; i ++ ) { chars [ i ] = BASE62 [ ( ( input [ i ] & 0xFF ) % BASE62 . length ) ] ; } return new String ( chars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "URL 编码 Encode默认为UTF - 8 . [CODESPLIT] public static String urlEncode ( String part ) { try { return URLEncoder . encode ( part , StringPool . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { throw ExceptionKit . unchecked ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "URL 解码 Encode默认为UTF - 8 . [CODESPLIT] public static String urlDecode ( String part ) { try { return URLDecoder . decode ( part , StringPool . UTF_8 ) ; } catch ( UnsupportedEncodingException e ) { throw ExceptionKit . unchecked ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all the extension implementations in the specified injector . [CODESPLIT] public List < T > list ( Injector injector ) { List < T > r = new ArrayList < T > ( ) ; for ( Injector i = injector ; i != null ; i = i . getParent ( ) ) { for ( Entry < Key < ? > , Binding < ? > > e : i . getBindings ( ) . entrySet ( ) ) { if ( e . getKey ( ) . getTypeLiteral ( ) . equals ( type ) ) r . add ( ( T ) e . getValue ( ) . getProvider ( ) . get ( ) ) ; } } return r ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns current method signature . [CODESPLIT] public static String currentMethod ( ) { StackTraceElement [ ] ste = new Exception ( ) . getStackTrace ( ) ; int ndx = ( ste . length > 1 ) ? 1 : 0 ; return new Exception ( ) . getStackTrace ( ) [ ndx ] . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compacts memory as much as possible by allocating huge memory block and then forcing garbage collection . [CODESPLIT] public static void compactMemory ( ) { try { final byte [ ] [ ] unused = new byte [ 128 ] [  ] ; for ( int i = unused . length ; i -- != 0 ; ) { unused [ i ] = new byte [ 2000000000 ] ; } } catch ( OutOfMemoryError ignore ) { } System . gc ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagates metrics entry to the local metrics collection or ( if unavailable ) logs immediately [CODESPLIT] public static void propagateOrLogInfo ( Metrics metrics , Logger log ) { final MetricsCollection metricsCollection = propagate ( metrics ) ; if ( metricsCollection == null ) { logInfo ( metrics , log ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Propagates metrics entry to the thread local metrics collection does nothing if local metrics collection is missing . [CODESPLIT] @ Nullable public static MetricsCollection propagate ( Metrics metrics ) { final MetricsCollection metricsCollection = getLocalMetricsCollection ( ) ; if ( metricsCollection != null ) { metricsCollection . add ( metrics ) ; } return metricsCollection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates that passed request vector is valid . This function is used to prevent the potential attacker to send garbage request vectors into the service . If passed request vector is invalid it should be discarded . [CODESPLIT] public static boolean isValidRequestVector ( @ Nullable String requestVector ) { if ( requestVector == null || requestVector . isEmpty ( ) || requestVector . length ( ) > MAX_REQUEST_VECTOR_LENGTH ) { return false ; } // verify, that each character is within the allowed bounds for ( int i = 0 ; i < requestVector . length ( ) ; ++ i ) { final char ch = requestVector . charAt ( i ) ; if ( ch <= 32 || ch >= 127 ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a value so that it won t contain spaces commas and equal signs . [CODESPLIT] public static String encodeString ( String value ) { int estimatedSize = 0 ; final int len = value . length ( ) ; // estimate output string size to find out whether encoding is required and avoid reallocations in string builder for ( int i = 0 ; i < len ; ++ i ) { final char ch = value . charAt ( i ) ; if ( ch <= ' ' || ch == ' ' ) { estimatedSize += 3 ; continue ; } ++ estimatedSize ; } if ( value . length ( ) == estimatedSize ) { return value ; // return value as is - it does not contain any special characters } final StringBuilder builder = new StringBuilder ( estimatedSize ) ; for ( int i = 0 ; i < len ; ++ i ) { final char ch = value . charAt ( i ) ; if ( ch <= ' ' ) { builder . append ( \"%20\" ) ; continue ; } if ( ch == ' ' ) { builder . append ( \"%2c\" ) ; continue ; } builder . append ( ch ) ; } return builder . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将CheckedException转换为UncheckedException . [CODESPLIT] public static RuntimeException unchecked ( Exception e ) { if ( e instanceof RuntimeException ) { return ( RuntimeException ) e ; } else { return new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将ErrorStack转化为String . [CODESPLIT] public static String getStackTraceAsString ( Exception e ) { StringWriter stringWriter = new StringWriter ( ) ; e . printStackTrace ( new PrintWriter ( stringWriter ) ) ; return stringWriter . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断异常是否由某些底层的异常引起 . [CODESPLIT] public static boolean isCausedBy ( Exception ex , Class < ? extends Exception > ... causeExceptionClasses ) { Throwable cause = ex . getCause ( ) ; while ( cause != null ) { for ( Class < ? extends Exception > causeClass : causeExceptionClasses ) { if ( causeClass . isInstance ( cause ) ) { return true ; } } cause = cause . getCause ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Paging retrieve default sorted by id you need to specify the datatables request parameters . [CODESPLIT] public static Page < Record > paginate ( String model_name , DTCriterias criterias ) { return paginate ( model_name , criterias , Lists . newArrayListWithCapacity ( 1 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Paging retrieve default sorted by id you need to specify the datatables request parameters . [CODESPLIT] public static Page < Record > paginate ( String sqlPaginatePrefix , DTCriterias criterias , List < Object > params ) { SqlNode sqlNode = SqlKit . sqlNode ( sqlPaginatePrefix + \".paginate\" ) ; Preconditions . checkNotNull ( sqlNode , \"[\" + sqlPaginatePrefix + \".paginate]分页Sql不存在,无法执行分页\");   return DTDao . paginate ( sqlNode , criterias , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Paging retrieve default sorted by id you need to specify the datatables request parameters . [CODESPLIT] public static Page < Record > paginate ( String where , String sql_columns , DTCriterias criterias , List < Object > params ) { int pageSize = criterias . getLength ( ) ; int start = criterias . getStart ( ) / pageSize + 1 ; StringBuilder where_sql = new StringBuilder ( where ) ; final List < Triple < String , Condition , Object > > custom_params = criterias . getParams ( ) ; if ( ! custom_params . isEmpty ( ) ) { boolean append_and = StringUtils . containsIgnoreCase ( where , \"WHERE\" ) ; if ( ! append_and ) { where_sql . append ( SQL_WHERE ) ; } itemCustomParamSql ( params , where_sql , custom_params , append_and ) ; } final List < DTOrder > order = criterias . getOrder ( ) ; if ( order != null && ! order . isEmpty ( ) ) { StringBuilder orderBy = new StringBuilder ( ) ; for ( DTOrder _order : order ) orderBy . append ( _order . getColumn ( ) ) . append ( StringPool . SPACE ) . append ( _order . getDir ( ) ) ; final String byColumns = orderBy . toString ( ) ; if ( ! Strings . isNullOrEmpty ( byColumns ) ) { where_sql . append ( \" ORDER BY \" ) . append ( byColumns ) ; } } if ( params == null || params . isEmpty ( ) ) { return Db . paginate ( start , pageSize , sql_columns , where_sql . toString ( ) ) ; } else { return Db . paginate ( start , pageSize , sql_columns , where_sql . toString ( ) , params . toArray ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "分页检索，默认按照id进行排序，需要指定datatables的请求参数。 [CODESPLIT] public static Page < Record > paginate ( Class < ? extends Model > model , DTCriterias criterias ) { int pageSize = criterias . getLength ( ) ; int start = criterias . getStart ( ) / pageSize + 1 ; final Table table = TableMapping . me ( ) . getTable ( model ) ; final String tableName = table . getName ( ) ; final List < DTColumn > columns = criterias . getColumns ( ) ; String sql_columns = null ; if ( ! ( columns == null || columns . isEmpty ( ) ) ) { StringBuilder sql_builder = new StringBuilder ( \"SELECT \" ) ; boolean first = false ; for ( DTColumn column : columns ) { if ( column != null ) { if ( first ) { sql_builder . append ( COMMA ) . append ( SPACE ) . append ( column . getData ( ) ) ; } else { sql_builder . append ( column . getData ( ) ) ; first = true ; } } } sql_columns = sql_builder . toString ( ) ; } StringBuilder where = new StringBuilder ( \" FROM \" ) ; where . append ( tableName ) . append ( SPACE ) ; //        final DTSearch search = criterias.getSearch(); final List < Triple < String , Condition , Object > > custom_params = criterias . getParams ( ) ; final List < Object > params = Lists . newArrayList ( ) ; appendWhereSql ( params , where , custom_params ) ; final List < DTOrder > order = criterias . getOrder ( ) ; if ( ! ( order == null || order . isEmpty ( ) ) ) { StringBuilder orderBy = new StringBuilder ( ) ; for ( DTOrder _order : order ) orderBy . append ( _order . getColumn ( ) ) . append ( SPACE ) . append ( _order . getDir ( ) ) ; final String byColumns = orderBy . toString ( ) ; if ( ! Strings . isNullOrEmpty ( byColumns ) ) { where . append ( \" ORDER BY \" ) . append ( byColumns ) ; } } return Db . paginate ( start , pageSize , sql_columns , where . toString ( ) , params . toArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get coding format file . [CODESPLIT] public static Optional < Charset > charset ( File file ) { if ( ! file . exists ( ) ) { logger . error ( \"The file [ {} ] is not exist.\" , file . getAbsolutePath ( ) ) ; return Optional . absent ( ) ; } FileInputStream fileInputStream = null ; BufferedInputStream bin = null ; try { fileInputStream = new FileInputStream ( file ) ; bin = new BufferedInputStream ( fileInputStream ) ; int p = ( bin . read ( ) << 8 ) + bin . read ( ) ; Optional < Charset > charset ; //其中的 0xefbb、0xfffe、0xfeff、0x5c75这些都是这个文件的前面两个字节的16进制数 switch ( p ) { case 0xefbb : charset = Optional . of ( Charsets . UTF_8 ) ; break ; case 0xfffe : charset = Optional . of ( Charset . forName ( \"Unicode\" ) ) ; break ; case 0xfeff : charset = Optional . of ( Charsets . UTF_16BE ) ; break ; case 0x5c75 : charset = Optional . of ( Charsets . US_ASCII ) ; break ; default : charset = Optional . of ( Charset . forName ( \"GBK\" ) ) ; } return charset ; } catch ( FileNotFoundException e ) { logger . error ( \"The file [ {} ] is not exist.\" , file . getAbsolutePath ( ) , e ) ; } catch ( IOException e ) { logger . error ( \"Read file has error, {}.\" , file . getAbsolutePath ( ) , e ) ; } finally { IOUtils . closeQuietly ( fileInputStream ) ; IOUtils . closeQuietly ( bin ) ; } return Optional . absent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据ID查找 [CODESPLIT] public static List < DBObject > findById ( String collectionName , String id ) { DBCollection c = MongoKit . getCollection ( collectionName ) ; return c . find ( new BasicDBObject ( \"_id\" , new ObjectId ( id ) ) ) . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据条件对象查找 [CODESPLIT] public static List < DBObject > findByQuery ( String collectionName , MongoQuery query ) { DBCollection c = MongoKit . getCollection ( collectionName ) ; return c . find ( query . get ( ) ) . toArray ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据条件对象查找并删除 [CODESPLIT] public static DBObject findAndRemove ( String collectionName , MongoQuery query ) { DBCollection c = MongoKit . getCollection ( collectionName ) ; return c . findAndRemove ( query . get ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes an output stream and releases any system resources associated with this stream . No exception will be thrown if an I / O error occurs . [CODESPLIT] public static void close ( OutputStream out ) { if ( out != null ) { try { out . flush ( ) ; } catch ( IOException ioex ) { // ignore } try { out . close ( ) ; } catch ( IOException ioex ) { // ignore } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes a character - output stream and releases any system resources associated with this stream . No exception will be thrown if an I / O error occurs . [CODESPLIT] public static void close ( Writer out ) { if ( out != null ) { try { out . flush ( ) ; } catch ( IOException ioex ) { // ignore } try { out . close ( ) ; } catch ( IOException ioex ) { // ignore } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies input stream to output stream using buffer . Streams don t have to be wrapped to buffered since copying is already optimized . [CODESPLIT] public static int copy ( InputStream input , OutputStream output ) throws IOException { byte [ ] buffer = new byte [ ioBufferSize ] ; int count = 0 ; int read ; while ( true ) { read = input . read ( buffer , 0 , ioBufferSize ) ; if ( read == - 1 ) { break ; } output . write ( buffer , 0 , read ) ; count += read ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies specified number of bytes from input stream to output stream using buffer . [CODESPLIT] public static int copy ( InputStream input , OutputStream output , int byteCount ) throws IOException { byte buffer [ ] = new byte [ ioBufferSize ] ; int count = 0 ; int read ; while ( byteCount > 0 ) { if ( byteCount < ioBufferSize ) { read = input . read ( buffer , 0 , byteCount ) ; } else { read = input . read ( buffer , 0 , ioBufferSize ) ; } if ( read == - 1 ) { break ; } byteCount -= read ; count += read ; output . write ( buffer , 0 , read ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies input stream to writer using buffer . [CODESPLIT] public static void copy ( InputStream input , Writer output ) throws IOException { copy ( input , output , Const . DEFAULT_ENCODING ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies reader to writer using buffer . Streams don t have to be wrapped to buffered since copying is already optimized . [CODESPLIT] public static int copy ( Reader input , Writer output ) throws IOException { char [ ] buffer = new char [ ioBufferSize ] ; int count = 0 ; int read ; while ( ( read = input . read ( buffer , 0 , ioBufferSize ) ) >= 0 ) { output . write ( buffer , 0 , read ) ; count += read ; } output . flush ( ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies specified number of characters from reader to writer using buffer . [CODESPLIT] public static int copy ( Reader input , Writer output , int charCount ) throws IOException { char buffer [ ] = new char [ ioBufferSize ] ; int count = 0 ; int read ; while ( charCount > 0 ) { if ( charCount < ioBufferSize ) { read = input . read ( buffer , 0 , charCount ) ; } else { read = input . read ( buffer , 0 , ioBufferSize ) ; } if ( read == - 1 ) { break ; } charCount -= read ; count += read ; output . write ( buffer , 0 , read ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies reader to output stream using buffer . [CODESPLIT] public static void copy ( Reader input , OutputStream output ) throws IOException { copy ( input , output , Const . DEFAULT_ENCODING ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies reader to output stream using buffer and specified encoding . [CODESPLIT] public static void copy ( Reader input , OutputStream output , String encoding ) throws IOException { Writer out = new OutputStreamWriter ( output , encoding ) ; copy ( input , out ) ; out . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads all available bytes from InputStream as a byte array . Uses <code > in . available () < / code > to determine the size of input stream . This is the fastest method for reading input stream to byte array but depends on stream implementation of <code > available () < / code > . Buffered internally . [CODESPLIT] public static byte [ ] readAvailableBytes ( InputStream in ) throws IOException { int l = in . available ( ) ; byte byteArray [ ] = new byte [ l ] ; int i = 0 , j ; while ( ( i < l ) && ( j = in . read ( byteArray , i , l - i ) ) >= 0 ) { i += j ; } if ( i < l ) { throw new IOException ( \"Failed to completely read input stream\" ) ; } return byteArray ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the content of two byte streams . [CODESPLIT] public static boolean compare ( InputStream input1 , InputStream input2 ) throws IOException { if ( ! ( input1 instanceof BufferedInputStream ) ) { input1 = new BufferedInputStream ( input1 ) ; } if ( ! ( input2 instanceof BufferedInputStream ) ) { input2 = new BufferedInputStream ( input2 ) ; } int ch = input1 . read ( ) ; while ( ch != - 1 ) { int ch2 = input2 . read ( ) ; if ( ch != ch2 ) { return false ; } ch = input1 . read ( ) ; } int ch2 = input2 . read ( ) ; return ( ch2 == - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the content of two character streams . [CODESPLIT] public static boolean compare ( Reader input1 , Reader input2 ) throws IOException { if ( ! ( input1 instanceof BufferedReader ) ) { input1 = new BufferedReader ( input1 ) ; } if ( ! ( input2 instanceof BufferedReader ) ) { input2 = new BufferedReader ( input2 ) ; } int ch = input1 . read ( ) ; while ( ch != - 1 ) { int ch2 = input2 . read ( ) ; if ( ch != ch2 ) { return false ; } ch = input1 . read ( ) ; } int ch2 = input2 . read ( ) ; return ( ch2 == - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts pipeline with the specified stream object that flows through this pipeline . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public T apply ( T io ) { logger . debug ( \"Pipeline began\" ) ; try { for ( int i = 0 ; i < stages . size ( ) ; i ++ ) { Object stage = stages . get ( i ) ; String name = names . get ( stage ) ; logger . debug ( \"Stage-\" + i + ( ( name != null && ! name . isEmpty ( ) ) ? \" [\" + name + \"] \" : \" \" ) + \"processing\" ) ; if ( stage instanceof Function ) { if ( ( io = ( ( Function < T , T > ) stage ) . apply ( io ) ) == null ) { return io ; } } else if ( stage instanceof Predicate ) { if ( ! ( ( Predicate < T > ) stage ) . apply ( io ) ) { return io ; } } } return io ; } finally { logger . debug ( \"Pipeline ended\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Function } to the next processing stage with the class name of the { @code Function } as the stage name . [CODESPLIT] public Pipeline < T > set ( Function < T , T > function ) { return set ( stages . size ( ) , function . getClass ( ) . getName ( ) , function ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Function } to the next processing stage with the specified index and the class name of the { @code Function } as the stage name . [CODESPLIT] public Pipeline < T > set ( int index , Function < T , T > function ) { return set ( index , function . getClass ( ) . getName ( ) , function ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Function } to the next processing stage with the specified stage name . [CODESPLIT] public Pipeline < T > set ( String name , Function < T , T > function ) { return set ( stages . size ( ) , name , function ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Function } to the next processing stage with the specified index and stage name . [CODESPLIT] public Pipeline < T > set ( int index , String name , Function < T , T > function ) { Preconditions . checkArgument ( function != null , \"Parameter 'function' must not be [\" + function + \"]\" ) ; stages . add ( index , function ) ; names . put ( function , name ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Predicate } to the next processing stage with the class name of the { @code Predicate } as the stage name . [CODESPLIT] public Pipeline < T > set ( Predicate < T > predicate ) { return set ( stages . size ( ) , predicate . getClass ( ) . getName ( ) , predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Predicate } to the next processing stage with the specified index and the class name of the { @code Predicate } as the stage name . [CODESPLIT] public Pipeline < T > set ( int index , Predicate < T > predicate ) { return set ( index , predicate . getClass ( ) . getName ( ) , predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Predicate } to the next processing stage with the specified stage name . [CODESPLIT] public Pipeline < T > set ( String name , Predicate < T > predicate ) { return set ( stages . size ( ) , name , predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified { @code Predicate } to the next processing stage with the specified index and stage name . [CODESPLIT] public Pipeline < T > set ( int index , String name , Predicate < T > predicate ) { Preconditions . checkArgument ( predicate != null , \"Parameter 'predicate' must not be [\" + predicate + \"]\" ) ; stages . add ( index , predicate ) ; names . put ( predicate , name ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes { @code Function } or { @code Predicate } at the specified index . [CODESPLIT] public Pipeline < T > remove ( int index ) { Object object = stages . remove ( index ) ; names . remove ( object ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To obtain a configuration of SQL . [CODESPLIT] public static String sql ( String groupNameAndsqlId ) { final SqlNode sqlNode = SQL_MAP . get ( groupNameAndsqlId ) ; return sqlNode == null ? StringPool . EMPTY : sqlNode . sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "string - > object [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < T > T unmarshal ( String src , Class < T > clazz ) { T result = null ; try { Unmarshaller avm = JAXBContext . newInstance ( clazz ) . createUnmarshaller ( ) ; result = ( T ) avm . unmarshal ( new StringReader ( src ) ) ; } catch ( JAXBException e ) { Throwables . propagate ( e ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Validates HTTP request and constructs Web endpoint method parameters . This method processes the request as the following steps : <ol > <li > Checks the requested HTTP method is allowable . If the Web endpoint method is qualified by { @code @Allows } this class allows only the HTTP methods qualified in it . < / li > <li > Checks the requested MIME media type is acceptable . If the Web endpoint method is qualified by { @code @Accepts } this class accepts only the qualified MIME media types . < / li > <li > Determines { @code Request } type from the content type on HTTP request header by invoking { @code Configuration#requestType ( String ) } method with the content type . < / li > <li > Constructs Web endpoint method parameters by invoking { @code Request#get () } methods and sets them to the current HTTP request processing context . < / li > < / ol > [CODESPLIT] public boolean apply ( WebContext context ) { Method method = context . method ( ) ; try { Verb verb = null ; try { verb = Verb . valueOf ( context . request ( ) . getMethod ( ) ) ; } catch ( Exception e ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_METHOD_NOT_ALLOWED , \"HTTP verb [\" + context . request ( ) . getMethod ( ) + \"] is not supported\" ) ; } // Is the HTTP method allowable? if ( method . isAnnotationPresent ( Allows . class ) ) { Allows allows = method . getAnnotation ( Allows . class ) ; List < Verb > verbs = Arrays . asList ( allows . value ( ) ) ; if ( ! verbs . contains ( verb ) ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_METHOD_NOT_ALLOWED , \"Endpoint method [\" + method . getDeclaringClass ( ) . getName ( ) + \"#\" + method . getName ( ) + \"] is not capable of accepting [\" + verb + \"] method\" ) ; } } // Is the MIME media type of the request acceptable? Accepts accepts = method . getAnnotation ( Accepts . class ) ; String type = context . request ( ) . getContentType ( ) ; if ( accepts != null ) { boolean acceptable = false ; for ( String value : accepts . value ( ) ) { if ( type . startsWith ( value ) ) { acceptable = true ; break ; } } if ( ! acceptable ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_UNSUPPORTED_MEDIA_TYPE , \"Endpoint method [\" + method . getDeclaringClass ( ) . getName ( ) + \"#\" + method . getName ( ) + \"] is not capable of accepting [\" + type + \"] media type\" ) ; } } Class < ? extends Request > requestType = context . configuration ( ) . requestTypes ( ) . get ( type ) ; if ( requestType == null ) { throw new CannotAcceptRequestException ( HttpServletResponse . SC_UNSUPPORTED_MEDIA_TYPE , \"Configuration [\" + context . configuration ( ) . getClass ( ) . getName ( ) + \"] does not provide a request type corresponding to [\" + type + \"] media type\" ) ; } Request request = requestType . newInstance ( ) ; request . from ( context ) ; // Parameter construction. List < Object > parameters = new ArrayList < Object > ( ) ; Annotation [ ] [ ] parameterAnnotations = method . getParameterAnnotations ( ) ; Type [ ] parameterTypes = method . getGenericParameterTypes ( ) ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { List < Annotation > sources = new ArrayList < Annotation > ( ) ; for ( Annotation annotation : parameterAnnotations [ i ] ) { if ( annotation . annotationType ( ) . isAnnotationPresent ( Source . class ) ) { sources . add ( annotation ) ; } } parameters . add ( request . get ( parameterTypes [ i ] , sources ) ) ; } context . parameters ( parameters ) ; return true ; } catch ( CannotAcceptRequestException exception ) { logger . warn ( \"Failed to accept HTTP request\" , exception ) ; try { context . response ( ) . sendError ( exception . status ( ) ) ; return false ; } catch ( IOException e ) { throw new UncheckedException ( e ) ; } } catch ( Exception e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve the given resource location to a { @code java . io . File } i . e . to a file in the file system . <p > Does not check whether the file actually exists ; simply returns the File that the given location would correspond to . [CODESPLIT] public static File getFile ( String resourceLocation ) throws FileNotFoundException { Preconditions . checkNotNull ( resourceLocation , \"Resource location must not be null\" ) ; if ( resourceLocation . startsWith ( CLASSPATH_URL_PREFIX ) ) { String path = resourceLocation . substring ( CLASSPATH_URL_PREFIX . length ( ) ) ; String description = \"class path resource [\" + path + \"]\" ; URL url = ClassKit . getDefaultClassLoader ( ) . getResource ( path ) ; if ( url == null ) { throw new FileNotFoundException ( description + \" cannot be resolved to absolute file path \" + \"because it does not reside in the file system\" ) ; } return getFile ( url , description ) ; } try { // try URL return getFile ( new URL ( resourceLocation ) ) ; } catch ( MalformedURLException ex ) { // no URL -> treat as file path return new File ( resourceLocation ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the given URL points to a resource in a jar file that is has protocol jar zip wsjar or code - source . <p > zip and wsjar are used by WebLogic Server and WebSphere respectively but can be treated like jar files . [CODESPLIT] public static boolean isJarURL ( URL url ) { String up = url . getProtocol ( ) ; return ( URL_PROTOCOL_JAR . equals ( up ) || URL_PROTOCOL_ZIP . equals ( up ) || URL_PROTOCOL_WSJAR . equals ( up ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the default HTTP request processing pipeline . HTTP request processing pipeline consists of [ Route ] - &gt ; [ Receive ] - &gt ; [ Invoke ] - &gt ; [ Send ] by default . [CODESPLIT] public Pipeline < WebContext > pipeline ( ) { return new Pipeline < WebContext > ( ) . set ( Route . class . getSimpleName ( ) , new Route ( ) ) . set ( Receive . class . getSimpleName ( ) , new Receive ( ) ) . set ( Invoke . class . getSimpleName ( ) , new Invoke ( ) ) . set ( Send . class . getSimpleName ( ) , new Send ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Zips a file or a folder . If adding a folder all its content will be added . [CODESPLIT] public static void zip ( File file ) throws IOException { String zipFile = file . getAbsolutePath ( ) + ZIP_EXT ; ZipOutputStream zos = null ; try { zos = createZip ( zipFile ) ; addToZip ( zos ) . file ( file ) . recursive ( ) . add ( ) ; } finally { StreamUtil . close ( zos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts zip file to the target directory . If patterns are provided only matched paths are extracted . [CODESPLIT] public static void unzip ( File zipFile , File destDir , String ... patterns ) throws IOException { ZipFile zip = new ZipFile ( zipFile ) ; Enumeration zipEntries = zip . entries ( ) ; while ( zipEntries . hasMoreElements ( ) ) { ZipEntry entry = ( ZipEntry ) zipEntries . nextElement ( ) ; String entryName = entry . getName ( ) ; if ( patterns != null && patterns . length > 0 ) { if ( Wildcard . matchPathOne ( entryName , patterns ) == - 1 ) { continue ; } } File file = ( destDir != null ) ? new File ( destDir , entryName ) : new File ( entryName ) ; if ( entry . isDirectory ( ) ) { if ( ! file . mkdirs ( ) ) { if ( ! file . isDirectory ( ) ) { throw new IOException ( \"Failed to create directory: \" + file ) ; } } } else { File parent = file . getParentFile ( ) ; if ( parent != null && ! parent . exists ( ) ) { if ( ! parent . mkdirs ( ) ) { if ( ! file . isDirectory ( ) ) { throw new IOException ( \"Failed to create directory: \" + parent ) ; } } } InputStream in = zip . getInputStream ( entry ) ; OutputStream out = null ; try { out = new FileOutputStream ( file ) ; StreamUtil . copy ( in , out ) ; } finally { StreamUtil . close ( out ) ; StreamUtil . close ( in ) ; } } } close ( zip ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes HTTP response representation to output stream . This method determines the response form as the following convention : <ul > <li > If the MIME media type ( { @code #mediaType } ) is not empty set it to Content - Type HTTP response header . < / li > <li > If the status ( { @code #status } ) is greater than 0 set it to HTTP response code . < / li > <li > If { @code #entity } is an instance of { @code String } this method writes it to the HTTP response directly . If MIME media type has not been specified text / plain is used . < / li > <li > If { @code #entity } is an instance of { @code Externalizable } this method writes it to the HTTP response as { @code ObjectOutputStream } by invoking { @code Externalizable#writeExternal ( java . io . ObjectOutput ) } . < / li > <li > If { @code #entity } is an instance of { @code Serializable } this method writes it to the HTTP response as { @code ObjectOutputStream } . < / li > <li > The other this method write it to the HTTP response as plain text by invoking { @code #value#toString () } . If MIME media type has not been specified text / plain is used . < / li > < / ul > UTF - 8 is used for the character encoding ( MIME charset ) at any time . [CODESPLIT] public void to ( WebContext context ) { HttpServletResponse response = context . response ( ) ; if ( ! mediaType . isEmpty ( ) ) { response . setHeader ( \"Content-Type\" , mediaType ) ; } if ( status > 0 ) { response . setStatus ( status ) ; } if ( entity == null ) { return ; } try { if ( entity instanceof String ) { if ( mediaType . isEmpty ( ) ) { response . setHeader ( \"Content-Type\" , MediaType . TEXT_PLAIN ) ; } response . setCharacterEncoding ( \"UTF-8\" ) ; response . getWriter ( ) . write ( ( String ) entity ) ; } else if ( entity instanceof Serializable ) { new ObjectOutputStream ( response . getOutputStream ( ) ) . writeObject ( entity ) ; } else { if ( mediaType . isEmpty ( ) ) { response . setHeader ( \"Content-Type\" , MediaType . TEXT_PLAIN ) ; } response . setCharacterEncoding ( \"UTF-8\" ) ; response . getWriter ( ) . write ( entity . toString ( ) ) ; } } catch ( IOException e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "日志控件初始化 [CODESPLIT] public static void init ( ) { URL slf4jConf = LoggerInit . class . getResource ( slf4jPath ) ; final String app_name = GojaConfig . getAppName ( ) ; final String app_version = GojaConfig . getVersion ( ) ; if ( slf4jConf == null ) { LoggerContext lc = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; lc . reset ( ) ; AppLogConfigurator . configure ( lc ) ; Logger . slf4j = LoggerFactory . getLogger ( app_name + StringPool . AT + app_version ) ; } else if ( Logger . slf4j == null ) { if ( slf4jConf . getFile ( ) . indexOf ( PathKit . getWebRootPath ( ) ) == 0 ) { Logger . configuredManually = true ; } Logger . slf4j = LoggerFactory . getLogger ( app_name + StringPool . AT + app_version ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A static dialog fragment instance creator method . [CODESPLIT] public static PermissionDialogFragment getInstance ( PermBean bean , int requestCode ) { if ( bean == null ) throw new NullPointerException ( \"Permission Beans cannot be null !\" ) ; Bundle extras = new Bundle ( 3 ) ; // convert map to two arrays. HashMap < Permission , String > map = ( HashMap < Permission , String > ) bean . getPermissions ( ) ; // put arrays in extras. extras . putSerializable ( PERMISSION , map ) ; extras . putInt ( REQUEST , requestCode ) ; // set extras in fragment and return. PermissionDialogFragment fragment = new PermissionDialogFragment ( ) ; fragment . setArguments ( extras ) ; return fragment ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Work around for dialog not to dismiss on back button press . [CODESPLIT] @ Override public void onResume ( ) { super . onResume ( ) ; getDialog ( ) . setOnKeyListener ( new DialogInterface . OnKeyListener ( ) { @ Override public boolean onKey ( DialogInterface dialog , int keyCode , KeyEvent keyEvent ) { return keyCode != KeyEvent . ACTION_DOWN ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if two strings are equals or if they { [CODESPLIT] public static boolean equalsOrMatch ( String string , String pattern ) { return string . equals ( pattern ) || match ( string , pattern , 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the specified <code > type< / code > is a built - in type . [CODESPLIT] public static boolean isBuiltinType ( Type type ) { Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : builtins . contains ( rawType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the specified <code > type< / code > is an instance of { @code Collection } . [CODESPLIT] public static boolean isCollection ( Type type ) { Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : ( rawType . equals ( Collection . class ) || ClassUtils . getAllInterfaces ( rawType ) . contains ( Collection . class ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the specified <code > type< / code > is an instance of supported { @code Collection } . <br > <br > Supported collections are : <pre > java . util . Collection java . util . List java . util . Set java . util . SortedSet java . util . NavigableSet java . util . Queue java . util . Deque [CODESPLIT] public static boolean isSupportedCollection ( Type type ) { Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : collections . contains ( rawType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the specified <code > type< / code > is an array type . [CODESPLIT] public static boolean isArray ( Type type ) { if ( type instanceof GenericArrayType ) { return true ; } else if ( type instanceof Class < ? > ) { return ( ( Class < ? > ) type ) . isArray ( ) ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the element type of the specified collection type . The specified type must be collection or array . To make it sure use { @code #isCollection ( Type ) } method or { @code #isArray ( Type ) } method . [CODESPLIT] public static Class < ? > getElementType ( Type type ) { if ( isCollection ( type ) ) { if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; return ( Class < ? > ) parameterizedType . getActualTypeArguments ( ) [ 0 ] ; } else { return Object . class ; } } else if ( isArray ( type ) ) { if ( type instanceof GenericArrayType ) { GenericArrayType genericArrayType = ( GenericArrayType ) type ; return ( Class < ? > ) genericArrayType . getGenericComponentType ( ) ; } else { Class < ? > clazz = ( Class < ? > ) type ; return clazz . getComponentType ( ) ; } } else { throw new IllegalArgumentException ( \"'type' must be a collection or array\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the default implementation type of the specified collection interface type . The specified type must be an supported collection . To make it sure use { @code #isSupportedCollection ( Type ) } . If the specified collection type is <b > not< / b > an interface this method returns the specified implementation type directly . <br > <br > The default implementations are : <pre > java . util . Collection - > java . util . ArrayList java . util . List - > java . util . ArrayList java . util . Set - > java . util . HashSet java . util . SortedSet - > java . util . TreeSet java . util . NavigableSet - > java . util . TreeSet java . util . Queue - > java . util . PriorityQueue java . util . Deque - > java . util . ArrayDeque < / pre > [CODESPLIT] public static Class < ? > getDefaultImplementationType ( Type type ) { Class < ? > clazz = getRawType ( type ) ; return ( clazz . isInterface ( ) ) ? implementations . get ( clazz ) : clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the specified <code > type< / code > is a supported core value type . <br > <br > Supported core value types are : <pre > boolean byte char double float int long short java . math . BigDecimal java . math . BigInteger Boolean Byte Character Double Float Integer Long Short String Class java . util . Date java . util . Calendar java . io . File java . sql . Date java . sql . Time java . sql . Timestamp java . net . URL Object < / pre > [CODESPLIT] public static boolean isCoreValueType ( Type type ) { Class < ? > rawType = getRawType ( type ) ; return ( rawType == null ) ? false : values . contains ( rawType ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if the specified type is an user define value type . User defined value type must satisfy either of the following condition . <ol > <li > ( The class ) has a public constructor that takes one String . class parameter . < / li > <li > Has a public static factory method that named valueOf and takes one String . class parameter . < / li > < / ol > [CODESPLIT] public static boolean isUserDefinedValueType ( Type type ) { Class < ? > rawType = getRawType ( type ) ; if ( rawType == null ) { return false ; } for ( Constructor < ? > constructor : rawType . getConstructors ( ) ) { Class < ? > [ ] parameterTypes = constructor . getParameterTypes ( ) ; if ( parameterTypes . length == 1 && parameterTypes [ 0 ] . equals ( String . class ) ) { return true ; } } for ( Method method : rawType . getMethods ( ) ) { if ( method . getName ( ) . equals ( \"valueOf\" ) && Modifier . isStatic ( method . getModifiers ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds supported core value type . [CODESPLIT] public static void addCoreValueType ( Class < ? > clazz , Converter converter ) { ConvertUtils . register ( converter , clazz ) ; values . add ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the raw type of the specified type . This method supports { @code ParameterizedType } or raw { @code Class } ( just returns it directly ) . The other types such as array type are not supported . If the specified type is not supported this method returns <code > null< / code > . [CODESPLIT] public static Class < ? > getRawType ( Type type ) { if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; return ( Class < ? > ) parameterizedType . getRawType ( ) ; } else if ( type instanceof Class < ? > ) { Class < ? > clazz = ( Class < ? > ) type ; return ( clazz . isArray ( ) ) ? null : clazz ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches the regular expression [CODESPLIT] public static boolean match ( String regex , String value ) { Pattern pattern = Pattern . compile ( regex ) ; return pattern . matcher ( value ) . find ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Email validation [CODESPLIT] public static boolean isEmail ( String value ) { String check = \"^([a-z0-9A-Z]+[-|\\\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\\\.)+[a-zA-Z]{2,}$\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Phone number verification [CODESPLIT] public static boolean isMobile ( String value ) { String check = \"^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\\\d{8})$\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Phone verification [CODESPLIT] public static boolean isTel ( String value ) { String check = \"^\\\\d{3,4}-?\\\\d{7,9}$\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Telephone number including mobile phones and landlines [CODESPLIT] public static boolean isPhone ( String value ) { String telcheck = \"^\\\\d{3,4}-?\\\\d{7,9}$\" ; String mobilecheck = \"^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\\\d{8})$\" ; return match ( telcheck , Pattern . CASE_INSENSITIVE , value ) || match ( mobilecheck , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Judge whether it is birthday [CODESPLIT] public static boolean isBirthDay ( String value ) { String check = \"(\\\\d{4})(/|-|\\\\.)(\\\\d{1,2})(/|-|\\\\.)(\\\\d{1,2})$\" ; if ( match ( check , Pattern . CASE_INSENSITIVE , value ) ) { int year = Integer . parseInt ( value . substring ( 0 , 4 ) ) ; int month = Integer . parseInt ( value . substring ( 5 , 7 ) ) ; int day = Integer . parseInt ( value . substring ( 8 , 10 ) ) ; if ( month < 1 || month > 12 ) { return false ; } if ( day < 1 || day > 31 ) { return false ; } if ( ( month == 4 || month == 6 || month == 9 || month == 11 ) && day == 31 ) { return false ; } if ( month == 2 ) { boolean isleap = ( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) ) ; if ( day > 29 || ( day == 29 && ! isleap ) ) { return false ; } } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identity verification [CODESPLIT] public static boolean isIdentityCard ( String value ) { String check = \"(^\\\\d{15}$)|(^\\\\d{17}([0-9]|X)$)\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Postal Code [CODESPLIT] public static boolean isZipCode ( String value ) { String check = \"^[0-9]{6}$\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Currency validation [CODESPLIT] public static boolean isCurrency ( String value ) { String check = \"^(\\\\d+(?:\\\\.\\\\d{1,2})?)$\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Chinese [CODESPLIT] public static boolean isChinese ( String value ) { String check = \"^[\\\\u2E80-\\\\u9FFF]+$\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches are linked [CODESPLIT] public static boolean isUrl ( String value ) { String check = \"^((https?|ftp):\\\\/\\\\/)?(((([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(%[\\\\da-f]{2})|[!\\\\$&'\\\\(\\\\)\\\\*\\\\+,;=]|:)*@)?(((\\\\d|[1-9]\\\\d|1\\\\d\\\\d|2[0-4]\\\\d|25[0-5])\\\\.(\\\\d|[1-9]\\\\d|1\\\\d\\\\d|2[0-4]\\\\d|25[0-5])\\\\.(\\\\d|[1-9]\\\\d|1\\\\d\\\\d|2[0-4]\\\\d|25[0-5])\\\\.(\\\\d|[1-9]\\\\d|1\\\\d\\\\d|2[0-4]\\\\d|25[0-5]))|((([a-z]|\\\\d|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(([a-z]|\\\\d|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])*([a-z]|\\\\d|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])))\\\\.)+(([a-z]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(([a-z]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])*([a-z]|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])))\\\\.?)(:\\\\d*)?)(\\\\/((([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(%[\\\\da-f]{2})|[!\\\\$&'\\\\(\\\\)\\\\*\\\\+,;=]|:|@)+(\\\\/(([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(%[\\\\da-f]{2})|[!\\\\$&'\\\\(\\\\)\\\\*\\\\+,;=]|:|@)*)*)?)?(\\\\?((([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(%[\\\\da-f]{2})|[!\\\\$&'\\\\(\\\\)\\\\*\\\\+,;=]|:|@)|[\\\\uE000-\\\\uF8FF]|\\\\/|\\\\?)*)?(\\\\#((([a-z]|\\\\d|-|\\\\.|_|~|[\\\\u00A0-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF])|(%[\\\\da-f]{2})|[!\\\\$&'\\\\(\\\\)\\\\*\\\\+,;=]|:|@)|\\\\/|\\\\?)*)?$\" ; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tell the time [CODESPLIT] public static boolean isDateTime ( String value ) { String check = \"^(\\\\d{4})(/|-|\\\\.|年)(\\\\d{1,2})(/|-|\\\\.|月)(\\\\d{1,2})(日)?(\\\\s+\\\\d{1,2}(:|时)\\\\d{1,2}(:|分)?(\\\\d{1,2}(秒)?)?)?$\";// check =  \" ^(\\\\d{4})(/|-|\\\\.)(\\\\d{1,2})(/|-|\\\\.)(\\\\d{1,2})$\"; return match ( check , Pattern . CASE_INSENSITIVE , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Blank [CODESPLIT] public static boolean isBlank ( Object value ) { if ( value instanceof Collection ) { return ( ( Collection ) value ) . isEmpty ( ) ; } else if ( value instanceof String ) { return \"\" . equals ( value . toString ( ) . trim ( ) ) ; } else { return value == null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用指定的「QRCode 生成器格式」来创建一个 QRCode 处理器。 [CODESPLIT] public static QRCode create ( final String content , QRCodeFormat format ) { QRCode qrcode = new QRCode ( ) ; qrcode . format = format ; qrcode . qrcodeImage = toQRCode ( content , format ) ; return qrcode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用指定的「QRCode生成器格式」，把指定的内容生成为一个 QRCode 的图像对象。 [CODESPLIT] public static BufferedImage toQRCode ( String content , QRCodeFormat format ) { if ( format == null ) { format = QRCodeFormat . NEW ( ) ; } content = new String ( content . getBytes ( Charset . forName ( format . getEncode ( ) ) ) ) ; BitMatrix matrix ; try { matrix = new QRCodeWriter ( ) . encode ( content , BarcodeFormat . QR_CODE , format . getSize ( ) , format . getSize ( ) , format . getHints ( ) ) ; } catch ( WriterException e ) { throw new RuntimeException ( e ) ; } int width = matrix . getWidth ( ) ; int height = matrix . getHeight ( ) ; int fgColor = format . getForeGroundColor ( ) . getRGB ( ) ; int bgColor = format . getBackGroundColor ( ) . getRGB ( ) ; BufferedImage image = new BufferedImage ( width , height , ColorSpace . TYPE_RGB ) ; for ( int x = 0 ; x < width ; x ++ ) { for ( int y = 0 ; y < height ; y ++ ) { image . setRGB ( x , y , matrix . get ( x , y ) ? fgColor : bgColor ) ; } } return image ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从指定的 QRCode 图片文件中解析出其内容。 [CODESPLIT] public static String from ( String qrcodeFile ) { if ( qrcodeFile . startsWith ( \"http://\" ) || qrcodeFile . startsWith ( \"https://\" ) ) { try { return from ( new URL ( qrcodeFile ) ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } else { return from ( new File ( qrcodeFile ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从指定的 QRCode 图片文件中解析出其内容。 [CODESPLIT] public static String from ( File qrcodeFile ) { if ( ! qrcodeFile . exists ( ) ) { return null ; } try { BufferedImage image = ImageIO . read ( qrcodeFile ) ; return from ( image ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从指定的 QRCode 图片链接中解析出其内容。 [CODESPLIT] public static String from ( URL qrcodeUrl ) { try { BufferedImage image = ImageIO . read ( qrcodeUrl ) ; return from ( image ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从指定的 QRCode 图像对象中解析出其内容。 [CODESPLIT] public static String from ( BufferedImage qrcodeImage ) { final LuminanceSource source = new BufferedImageLuminanceSource ( qrcodeImage ) ; final BinaryBitmap bitmap = new BinaryBitmap ( new HybridBinarizer ( source ) ) ; String content ; try { Result result = new QRCodeReader ( ) . decode ( bitmap ) ; content = result . getText ( ) ; } catch ( NotFoundException e ) { throw new RuntimeException ( e ) ; } catch ( ChecksumException e ) { throw new RuntimeException ( e ) ; } catch ( FormatException e ) { throw new RuntimeException ( e ) ; } return content ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "把指定的内容生成为一个 QRCode 的图片，之后保存到指定的文件中。 [CODESPLIT] public QRCode toFile ( File qrcodeFile ) { try { if ( ! qrcodeFile . exists ( ) ) { Files . createParentDirs ( qrcodeFile ) ; qrcodeFile . createNewFile ( ) ; } if ( ! ImageIO . write ( this . qrcodeImage , getSuffixName ( qrcodeFile ) , qrcodeFile ) ) { throw new RuntimeException ( ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } this . qrcodeFile = qrcodeFile ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "把指定的内容生成为一个 QRCode 的图片，并在该图片中间添加上指定的图片；之后保存到指定的文件内。 [CODESPLIT] public QRCode toFile ( String qrcodeFile , String appendFile ) { return toFile ( new File ( qrcodeFile ) , new File ( appendFile ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "把指定的内容生成为一个 QRCode 的图片，并在该图片中间添加上指定的图片；之后保存到指定的文件内。 [CODESPLIT] public QRCode toFile ( File qrcodeFile , File appendFile ) { try { if ( ! qrcodeFile . exists ( ) ) { Files . createParentDirs ( qrcodeFile ) ; qrcodeFile . createNewFile ( ) ; } appendImage ( this . qrcodeImage , ImageIO . read ( appendFile ) , this . format ) ; if ( ! ImageIO . write ( this . qrcodeImage , getSuffixName ( qrcodeFile ) , qrcodeFile ) ) { throw new RuntimeException ( \"Unexpected error writing image\" ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } this . qrcodeFile = qrcodeFile ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs a new { @code JSONRequest } from the current { @code WebContext } . [CODESPLIT] public void from ( WebContext context ) { try { element = new JsonParser ( ) . parse ( context . request ( ) . getReader ( ) ) ; } catch ( Exception e ) { logger . warn ( \"Cannot parse JSON string into a parse tree\" , e ) ; throw new UncheckedException ( e ) ; } super . from ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Web endpoint method parameter value from the current HTTP request body sent as JSON format . This method supports the following parameter declaration independently . Other than them are the same as { @link AbstractRequest } . <ol > <li > Named collection of user - defined object type< / li > <li > Named user - defined object type< / li > <li > No - named collection of core value type< / li > <li > No - named collection of user - defined value type< / li > <li > No - named collection of user - defined object type< / li > < / ol > [CODESPLIT] @ Override protected Object body ( Type type , String name ) { return body ( type , name , element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the specified object to the specified user - defined value type . The object to be converted must be a { @code JsonPrimitive } or this method return <code > null< / code > . [CODESPLIT] @ Override protected Object convertUserDefinedValueType ( Object object , Class < ? > type ) { if ( object instanceof JsonPrimitive ) { JsonPrimitive primitive = ( JsonPrimitive ) object ; return super . convertUserDefinedValueType ( primitive . getAsString ( ) , type ) ; } else { logger . warn ( \"Parameter [\" + object + \"] cannot be converted to [\" + type + \"]; Converted 'object' must be a [\" + JsonPrimitive . class + \"]\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes this filter with the specified configuration . Constructs the { @code Configuration } and sets up the HTTP request processing pipeline . If the custom configuration class has not been specified { @link DefaultConfiguration } is used by default . [CODESPLIT] public void init ( FilterConfig filterConfig ) throws ServletException { logger . info ( \"Starting Bootleg on the Servlet [\" + filterConfig . getServletContext ( ) . getMajorVersion ( ) + \".\" + filterConfig . getServletContext ( ) . getMinorVersion ( ) + \"] environment\" ) ; Configuration configuration = configuration ( filterConfig ) ; if ( configuration == null ) { configuration = new DefaultConfiguration ( ) ; configuration . init ( filterConfig . getServletContext ( ) ) ; logger . info ( \"Default configuration [\" + DefaultConfiguration . class + \"] loaded\" ) ; } Pipeline < WebContext > pipeline = configuration . pipeline ( ) ; if ( pipeline == null ) { throw new ServletException ( \"Pipeline must not be [\" + pipeline + \"]: Configuration [\" + configuration + \"]\" ) ; } else { logger . debug ( \"HTTP request processing pipeline \" + pipeline + \" constructed\" ) ; } this . configuration = configuration ; this . pipeline = pipeline ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the Web request in Bootleg . [CODESPLIT] public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { try { pipeline . apply ( new WebContext ( configuration , ( HttpServletRequest ) request , ( HttpServletResponse ) response , chain ) ) ; } catch ( Exception e ) { logger . warn ( \"Failed to process HTTP request\" , e ) ; ( ( HttpServletResponse ) response ) . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs the { @code Configuration } . This method attempts to get custom configuration class from { @code ServletContext } init parameter and instantiate and initialize it . If the custom configuration class has not been specified as the { @code ServletContext } init parameter this method returns <code > null< / code > . [CODESPLIT] protected Configuration configuration ( FilterConfig config ) throws ServletException { ServletContext context = config . getServletContext ( ) ; String clazz = context . getInitParameter ( CONFIGURATION ) ; Configuration configuration = null ; if ( clazz != null ) { try { configuration = ( Configuration ) Class . forName ( clazz ) . newInstance ( ) ; configuration . init ( config . getServletContext ( ) ) ; logger . info ( \"Custom configuration [\" + clazz + \"] loaded\" ) ; } catch ( Exception e ) { logger . error ( \"Failed to load custom configuration [\" + clazz + \"]\" , e ) ; throw new ServletException ( \"Failed to load custom configuration [\" + clazz + \"]\" , e ) ; } } return configuration ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the full version string of the present Goja Boot codebase or { [CODESPLIT] public static String getVersion ( ) { Package pkg = GojaBootVersion . class . getPackage ( ) ; return ( pkg != null ? pkg . getImplementationVersion ( ) : null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取得模板路径的地址 [CODESPLIT] private String getTemplatePath ( Environment env ) { String templateName = env . getTemplate ( ) . getName ( ) ; return templateName . lastIndexOf ( ' ' ) == - 1 ? \"\" : templateName . substring ( 0 , templateName . lastIndexOf ( ' ' ) + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encode a String to base64 [CODESPLIT] public static String encodeBASE64 ( String value ) { try { return new String ( Base64 . encodeBase64 ( value . getBytes ( StringPool . UTF_8 ) ) ) ; } catch ( UnsupportedEncodingException ex ) { throw new UnexpectedException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decode a base64 value [CODESPLIT] public static byte [ ] decodeBASE64 ( String value ) { try { return Base64 . decodeBase64 ( value . getBytes ( StringPool . UTF_8 ) ) ; } catch ( UnsupportedEncodingException ex ) { throw new UnexpectedException ( ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transform an hexadecimal String to a byte array . [CODESPLIT] public static byte [ ] hexStringToByte ( String hexString ) { try { return Hex . decodeHex ( hexString . toCharArray ( ) ) ; } catch ( DecoderException e ) { throw new UnexpectedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read a properties file with the utf - 8 encoding [CODESPLIT] public static Properties readUtf8Properties ( InputStream is ) { Properties properties = new OrderSafeProperties ( ) ; try { properties . load ( is ) ; is . close ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the Stream content as a string [CODESPLIT] public static String readContentAsString ( InputStream is , String encoding ) { String res = null ; try { res = IOUtils . toString ( is , encoding ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { try { is . close ( ) ; } catch ( Exception e ) { // } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read file content to a String [CODESPLIT] public static String readContentAsString ( File file , String encoding ) { InputStream is = null ; try { is = new FileInputStream ( file ) ; StringWriter result = new StringWriter ( ) ; PrintWriter out = new PrintWriter ( result ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( is , encoding ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { out . println ( line ) ; } return result . toString ( ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Exception e ) { // } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read binary content of a file ( warning does not use on large file ! ) [CODESPLIT] public static byte [ ] readContent ( File file ) { InputStream is = null ; try { is = new FileInputStream ( file ) ; byte [ ] result = new byte [ ( int ) file . length ( ) ] ; is . read ( result ) ; return result ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( Exception e ) { // } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read binary content of a stream ( warning does not use on large file ! ) [CODESPLIT] public static byte [ ] readContent ( InputStream is ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; int read = 0 ; byte [ ] buffer = new byte [ 8096 ] ; while ( ( read = is . read ( buffer ) ) > 0 ) { baos . write ( buffer , 0 , read ) ; } return baos . toByteArray ( ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Write binay data to a file [CODESPLIT] public static void write ( byte [ ] data , File file ) { OutputStream os = null ; try { os = new FileOutputStream ( file ) ; os . write ( data ) ; os . flush ( ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { try { if ( os != null ) os . close ( ) ; } catch ( Exception e ) { // } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy an stream to another one . [CODESPLIT] public static void write ( InputStream is , OutputStream os ) { try { int read = 0 ; byte [ ] buffer = new byte [ 8096 ] ; while ( ( read = is . read ( buffer ) ) > 0 ) { os . write ( buffer , 0 , read ) ; } } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { try { is . close ( ) ; } catch ( Exception e ) { // } try { os . close ( ) ; } catch ( Exception e ) { // } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy an stream to another one . [CODESPLIT] public static void write ( InputStream is , File f ) { OutputStream os = null ; try { os = new FileOutputStream ( f ) ; int read = 0 ; byte [ ] buffer = new byte [ 8096 ] ; while ( ( read = is . read ( buffer ) ) > 0 ) { os . write ( buffer , 0 , read ) ; } } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } finally { try { is . close ( ) ; } catch ( Exception e ) { // } try { if ( os != null ) os . close ( ) ; } catch ( Exception e ) { // } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If targetLocation does not exist it will be created . [CODESPLIT] public static void copyDirectory ( File source , File target ) { if ( source . isDirectory ( ) ) { if ( ! target . exists ( ) ) { target . mkdir ( ) ; } for ( String child : source . list ( ) ) { copyDirectory ( new File ( source , child ) , new File ( target , child ) ) ; } } else { try { write ( new FileInputStream ( source ) , new FileOutputStream ( target ) ) ; } catch ( IOException e ) { throw new UnexpectedException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Executes this method on permission result . Get boolean result as method parameter . Granted = True && Denied = False . < / p > [CODESPLIT] @ OPermission ( value = Permission . WRITE_EXTERNAL_STORAGE ) void onStoragePermission ( @ Result boolean isGranted ) { if ( isGranted ) { updateView ( \"\\n Write Storage Granted\" ) ; } else { updateView ( \"\\n Write Storage Denied\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Executes this method on permission results . Get boolean result as method parameter . < / p > [CODESPLIT] @ OPermission ( values = { Permission . ACCESS_COARSE_LOCATION , Permission . ACCESS_FINE_LOCATION } ) void onLocationPermission ( @ Result boolean isGranted ) { if ( isGranted ) { updateView ( \"\\n Location status Granted\" ) ; } else { updateView ( \"\\n Location status Denied\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "货币比较。 <p / > <p / > 比较本货币对象与另一货币对象的大小。 如果待比较的两个货币对象的币种不同，则抛出<code > java . lang . IllegalArgumentException< / code > 。 如果本货币对象的金额少于待比较货币对象，则返回 - 1。 如果本货币对象的金额等于待比较货币对象，则返回0。 如果本货币对象的金额大于待比较货币对象，则返回1。 [CODESPLIT] public int compareTo ( MoneyKit other ) { assertSameCurrencyAs ( other ) ; if ( cent < other . cent ) { return - 1 ; } else if ( cent == other . cent ) { return 0 ; } else { return 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "货币加法。 <p / > <p / > 如果两货币币种相同，则返回一个新的相同币种的货币对象，其金额为 两货币对象金额之和，本货币对象的值不变。 如果两货币对象币种不同，抛出<code > java . lang . IllegalArgumentException< / code > 。 [CODESPLIT] public MoneyKit add ( MoneyKit other ) { assertSameCurrencyAs ( other ) ; return newMoneyWithSameCurrency ( cent + other . cent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "货币减法。 <p / > <p / > 如果两货币币种相同，则返回一个新的相同币种的货币对象，其金额为 本货币对象的金额减去参数货币对象的金额。本货币对象的值不变。 如果两货币币种不同，抛出<code > java . lang . IllegalArgumentException< / code > 。 [CODESPLIT] public MoneyKit subtract ( MoneyKit other ) { assertSameCurrencyAs ( other ) ; return newMoneyWithSameCurrency ( cent - other . cent ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "货币乘法。 <p / > <p / > 返回一个新的货币对象，币种与本货币对象相同，金额为本货币对象的金额乘以乘数。 本货币对象的值不变。如果相乘后的金额不能转换为整数分，使用指定的取整方式 <code > roundingMode< / code > 进行取整。 [CODESPLIT] public MoneyKit multiply ( BigDecimal val , int roundingMode ) { BigDecimal newCent = BigDecimal . valueOf ( cent ) . multiply ( val ) ; return newMoneyWithSameCurrency ( rounding ( newCent , roundingMode ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "货币除法。 <p / > <p / > 返回一个新的货币对象，币种与本货币对象相同，金额为本货币对象的金额除以除数。 本货币对象的值不变。如果相除后的金额不能转换为整数分，使用指定的取整模式 <code > roundingMode< / code > 进行取整。 [CODESPLIT] public MoneyKit divide ( BigDecimal val , int roundingMode ) { BigDecimal newCent = BigDecimal . valueOf ( cent ) . divide ( val , roundingMode ) ; return newMoneyWithSameCurrency ( newCent . longValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "货币分配。 <p / > <p / > 将本货币对象尽可能平均分配成<code > targets< / code > 份。 如果不能平均分配尽，则将零头放到开始的若干份中。分配 运算能够确保不会丢失金额零头。 [CODESPLIT] public MoneyKit [ ] allocate ( int targets ) { MoneyKit [ ] results = new MoneyKit [ targets ] ; MoneyKit lowResult = newMoneyWithSameCurrency ( cent / targets ) ; MoneyKit highResult = newMoneyWithSameCurrency ( lowResult . cent + 1 ) ; int remainder = ( int ) cent % targets ; for ( int i = 0 ; i < remainder ; i ++ ) { results [ i ] = highResult ; } for ( int i = remainder ; i < targets ; i ++ ) { results [ i ] = lowResult ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "货币分配。 <p / > <p / > 将本货币对象按照规定的比例分配成若干份。分配所剩的零头 从第一份开始顺序分配。分配运算确保不会丢失金额零头。 [CODESPLIT] public MoneyKit [ ] allocate ( long [ ] ratios ) { MoneyKit [ ] results = new MoneyKit [ ratios . length ] ; long total = 0 ; for ( long ratio : ratios ) { total += ratio ; } long remainder = cent ; for ( int i = 0 ; i < results . length ; i ++ ) { results [ i ] = newMoneyWithSameCurrency ( ( cent * ratios [ i ] ) / total ) ; remainder -= results [ i ] . cent ; } for ( int i = 0 ; i < remainder ; i ++ ) { results [ i ] . cent ++ ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "创建一个币种相同，具有指定金额的货币对象。 [CODESPLIT] protected MoneyKit newMoneyWithSameCurrency ( long cent ) { MoneyKit money = new MoneyKit ( 0 , currency ) ; money . cent = cent ; return money ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a handler for jetty server with the given list of users . The list of users can be conveniently loaded by using the other method in this utility class : { @link #loadUsers ( PropertySource String ) } . [CODESPLIT] public static SecurityHandler newSecurityHandler ( List < SimpleServiceUser > users ) { final HashLoginService loginService = new HashLoginService ( ) ; final Set < String > roles = new HashSet <> ( ) ; for ( final SimpleServiceUser user : users ) { final List < String > authorities = user . getAuthorities ( ) ; loginService . putUser ( user . getUsername ( ) , Credential . getCredential ( user . getPassword ( ) ) , authorities . toArray ( new String [ authorities . size ( ) ] ) ) ; roles . addAll ( authorities ) ; } loginService . setName ( DEFAULT_REALM ) ; final Constraint constraint = new Constraint ( ) ; constraint . setName ( Constraint . __BASIC_AUTH ) ; constraint . setRoles ( roles . toArray ( new String [ roles . size ( ) ] ) ) ; constraint . setAuthenticate ( true ) ; final ConstraintMapping constraintMapping = new ConstraintMapping ( ) ; constraintMapping . setConstraint ( constraint ) ; constraintMapping . setPathSpec ( \"/*\" ) ; final ConstraintSecurityHandler csh = new ConstraintSecurityHandler ( ) ; csh . setAuthenticator ( new BasicAuthenticator ( ) ) ; csh . setRealmName ( DEFAULT_REALM_NAME ) ; csh . addConstraintMapping ( constraintMapping ) ; csh . setLoginService ( loginService ) ; return csh ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads user records from a given reader . The text stream produced by reader should contain records in java properties format ( see also { @link Properties } ) . Each property related to authorization entries should be prefixed . This prefix should be passed as a second parameter to this method { @code authPropertiesPrefix } . [CODESPLIT] public static List < SimpleServiceUser > loadUsers ( PropertySource < ? > propertySource , String authPropertiesPrefix ) { if ( propertySource instanceof EnumerablePropertySource ) { final EnumerablePropertySource < ? > enumPropSource = ( EnumerablePropertySource ) propertySource ; final String [ ] propertyNames = enumPropSource . getPropertyNames ( ) ; final PropertyEntrySink sink = new PropertyEntrySink ( authPropertiesPrefix ) ; for ( final String propertyName : propertyNames ) { final Object value = propertySource . getProperty ( propertyName ) ; if ( value instanceof String ) { sink . putEntry ( propertyName , value . toString ( ) ) ; } } return sink . getUserList ( ) ; } LoggerFactory . getLogger ( SimpleAuthenticatorUtil . class ) . warn ( \"propertySource={} is not of type EnumerablePropertySource\" , propertySource ) ; return Collections . emptyList ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialize to XML String [CODESPLIT] public static String serialize ( Document document ) { StringWriter writer = new StringWriter ( ) ; try { TransformerFactory factory = TransformerFactory . newInstance ( ) ; Transformer transformer = factory . newTransformer ( ) ; DOMSource domSource = new DOMSource ( document ) ; StreamResult streamResult = new StreamResult ( writer ) ; transformer . transform ( domSource , streamResult ) ; } catch ( TransformerException e ) { throw new RuntimeException ( \"Error when serializing XML document.\" , e ) ; } return writer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an XML file to DOM [CODESPLIT] public static Document getDocument ( File file ) { try { return newDocumentBuilder ( ) . parse ( file ) ; } catch ( SAXException e ) { logger . warn ( \"Parsing error when building Document object from xml file '\" + file + \"'.\" , e ) ; } catch ( IOException e ) { logger . warn ( \"Reading error when building Document object from xml file '\" + file + \"'.\" , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an XML string content to DOM [CODESPLIT] public static Document getDocument ( String xml ) { InputSource source = new InputSource ( new StringReader ( xml ) ) ; try { return newDocumentBuilder ( ) . parse ( source ) ; } catch ( SAXException e ) { logger . warn ( \"Parsing error when building Document object from xml data.\" , e ) ; } catch ( IOException e ) { logger . warn ( \"Reading error when building Document object from xml data.\" , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse an XML coming from an input stream to DOM [CODESPLIT] public static Document getDocument ( InputStream stream ) { try { return newDocumentBuilder ( ) . parse ( stream ) ; } catch ( SAXException e ) { logger . warn ( \"Parsing error when building Document object from xml data.\" , e ) ; } catch ( IOException e ) { logger . warn ( \"Reading error when building Document object from xml data.\" , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check the xmldsig signature of the XML document . [CODESPLIT] public static boolean validSignature ( Document document , Key publicKey ) { Node signatureNode = document . getElementsByTagNameNS ( XMLSignature . XMLNS , \"Signature\" ) . item ( 0 ) ; KeySelector keySelector = KeySelector . singletonKeySelector ( publicKey ) ; try { String providerName = System . getProperty ( \"jsr105Provider\" , \"org.jcp.xml.dsig.internal.dom.XMLDSigRI\" ) ; XMLSignatureFactory fac = XMLSignatureFactory . getInstance ( \"DOM\" , ( Provider ) Class . forName ( providerName ) . newInstance ( ) ) ; DOMValidateContext valContext = new DOMValidateContext ( keySelector , signatureNode ) ; XMLSignature signature = fac . unmarshalXMLSignature ( valContext ) ; return signature . validate ( valContext ) ; } catch ( Exception e ) { logger . warn ( \"Error validating an XML signature.\" , e ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sign the XML document using xmldsig . [CODESPLIT] public static Document sign ( Document document , RSAPublicKey publicKey , RSAPrivateKey privateKey ) { XMLSignatureFactory fac = XMLSignatureFactory . getInstance ( \"DOM\" ) ; KeyInfoFactory keyInfoFactory = fac . getKeyInfoFactory ( ) ; try { Reference ref = fac . newReference ( \"\" , fac . newDigestMethod ( DigestMethod . SHA1 , null ) , Collections . singletonList ( fac . newTransform ( Transform . ENVELOPED , ( TransformParameterSpec ) null ) ) , null , null ) ; SignedInfo si = fac . newSignedInfo ( fac . newCanonicalizationMethod ( CanonicalizationMethod . INCLUSIVE , ( C14NMethodParameterSpec ) null ) , fac . newSignatureMethod ( SignatureMethod . RSA_SHA1 , null ) , Collections . singletonList ( ref ) ) ; DOMSignContext dsc = new DOMSignContext ( privateKey , document . getDocumentElement ( ) ) ; KeyValue keyValue = keyInfoFactory . newKeyValue ( publicKey ) ; KeyInfo ki = keyInfoFactory . newKeyInfo ( Collections . singletonList ( keyValue ) ) ; XMLSignature signature = fac . newXMLSignature ( si , ki ) ; signature . sign ( dsc ) ; } catch ( Exception e ) { logger . warn ( \"Error while signing an XML document.\" , e ) ; } return document ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the default ClassLoader to use : typically the thread context ClassLoader if available ; the ClassLoader that loaded the ClassUtils class will be used as fallback . <p > Call this method if you intend to use the thread context ClassLoader in a scenario where you clearly prefer a non - null ClassLoader reference : for example for class path resource loading ( but not necessarily for { @code Class . forName } which accepts a { @code null } ClassLoader reference as well ) . [CODESPLIT] public static ClassLoader getDefaultClassLoader ( ) { ClassLoader cl = null ; try { cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; } catch ( Throwable ex ) { // Cannot access thread context ClassLoader - falling back... } if ( cl == null ) { // No thread context class loader -> use class loader of this class. cl = ClassKit . class . getClassLoader ( ) ; if ( cl == null ) { // getClassLoader() returning null indicates the bootstrap ClassLoader try { cl = ClassLoader . getSystemClassLoader ( ) ; } catch ( Throwable ex ) { // Cannot access system ClassLoader - oh well, maybe the caller can live with null... } } } return cl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replacement for { @code Class . forName () } that also returns Class instances for primitives ( e . g . int ) and array class names ( e . g . String [] ) . Furthermore it is also capable of resolving inner class names in Java source style ( e . g . java . lang . Thread . State instead of java . lang . Thread$State ) . [CODESPLIT] public static Class < ? > forName ( String name , ClassLoader classLoader ) throws ClassNotFoundException , LinkageError { Preconditions . checkNotNull ( name , \"Name must not be null\" ) ; Class < ? > clazz = resolvePrimitiveClassName ( name ) ; if ( clazz == null ) { clazz = commonClassCache . get ( name ) ; } if ( clazz != null ) { return clazz ; } // \"java.lang.String[]\" style arrays if ( name . endsWith ( ARRAY_SUFFIX ) ) { String elementClassName = name . substring ( 0 , name . length ( ) - ARRAY_SUFFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementClassName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } // \"[Ljava.lang.String;\" style arrays if ( name . startsWith ( NON_PRIMITIVE_ARRAY_PREFIX ) && name . endsWith ( \";\" ) ) { String elementName = name . substring ( NON_PRIMITIVE_ARRAY_PREFIX . length ( ) , name . length ( ) - 1 ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } // \"[[I\" or \"[[Ljava.lang.String;\" style arrays if ( name . startsWith ( INTERNAL_ARRAY_PREFIX ) ) { String elementName = name . substring ( INTERNAL_ARRAY_PREFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } ClassLoader clToUse = classLoader ; if ( clToUse == null ) { clToUse = getDefaultClassLoader ( ) ; } try { return ( clToUse != null ? clToUse . loadClass ( name ) : Class . forName ( name ) ) ; } catch ( ClassNotFoundException ex ) { int lastDotIndex = name . lastIndexOf ( PACKAGE_SEPARATOR ) ; if ( lastDotIndex != - 1 ) { String innerClassName = name . substring ( 0 , lastDotIndex ) + INNER_CLASS_SEPARATOR + name . substring ( lastDotIndex + 1 ) ; try { return ( clToUse != null ? clToUse . loadClass ( innerClassName ) : Class . forName ( innerClassName ) ) ; } catch ( ClassNotFoundException ex2 ) { // Swallow - let original exception get through } } throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the user - defined class for the given instance : usually simply the class of the given instance but the original class in case of a CGLIB - generated subclass . [CODESPLIT] public static Class < ? > getUserClass ( Object instance ) { Preconditions . checkNotNull ( instance , \"Instance must not be null\" ) ; return getUserClass ( instance . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check whether the given class is cache - safe in the given context i . e . whether it is loaded by the given ClassLoader or a parent of it . [CODESPLIT] public static boolean isCacheSafe ( Class < ? > clazz , ClassLoader classLoader ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; try { ClassLoader target = clazz . getClassLoader ( ) ; if ( target == null ) { return true ; } ClassLoader cur = classLoader ; if ( cur == target ) { return true ; } while ( cur != null ) { cur = cur . getParent ( ) ; if ( cur == target ) { return true ; } } return false ; } catch ( SecurityException ex ) { // Probably from the system ClassLoader - let's consider it safe. return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the name of the class file relative to the containing package : e . g . String . class [CODESPLIT] public static String getClassFileName ( Class < ? > clazz ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; String className = clazz . getName ( ) ; int lastDotIndex = className . lastIndexOf ( PACKAGE_SEPARATOR ) ; return className . substring ( lastDotIndex + 1 ) + CLASS_FILE_SUFFIX ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the name of the package of the given class e . g . java . lang for the { @code java . lang . String } class . [CODESPLIT] public static String getPackageName ( Class < ? > clazz ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; return getPackageName ( clazz . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine the name of the package of the given fully - qualified class name e . g . java . lang for the { @code java . lang . String } class name . [CODESPLIT] public static String getPackageName ( String fqClassName ) { Preconditions . checkNotNull ( fqClassName , \"Class name must not be null\" ) ; int lastDotIndex = fqClassName . lastIndexOf ( PACKAGE_SEPARATOR ) ; return ( lastDotIndex != - 1 ? fqClassName . substring ( 0 , lastDotIndex ) : \"\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the qualified name of the given class : usually simply the class name but component type class name + [] for arrays . [CODESPLIT] public static String getQualifiedName ( Class < ? > clazz ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; if ( clazz . isArray ( ) ) { return getQualifiedNameForArray ( clazz ) ; } else { return clazz . getName ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the qualified name of the given method consisting of fully qualified interface / class name + . + method name . [CODESPLIT] public static String getQualifiedMethodName ( Method method ) { Preconditions . checkNotNull ( method , \"Method must not be null\" ) ; return method . getDeclaringClass ( ) . getName ( ) + \".\" + method . getName ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the given class has a public constructor with the given signature and return it if available ( else return { @code null } ) . <p > Essentially translates { @code NoSuchMethodException } to { @code null } . [CODESPLIT] public static < T > Constructor < T > getConstructorIfAvailable ( Class < T > clazz , Class < ? > ... paramTypes ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; try { return clazz . getConstructor ( paramTypes ) ; } catch ( NoSuchMethodException ex ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the number of methods with a given name ( with any argument types ) for the given class and / or its superclasses . Includes non - public methods . [CODESPLIT] public static int getMethodCountForName ( Class < ? > clazz , String methodName ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; Preconditions . checkNotNull ( methodName , \"Method name must not be null\" ) ; int count = 0 ; Method [ ] declaredMethods = clazz . getDeclaredMethods ( ) ; for ( Method method : declaredMethods ) { if ( methodName . equals ( method . getName ( ) ) ) { count ++ ; } } Class < ? > [ ] ifcs = clazz . getInterfaces ( ) ; for ( Class < ? > ifc : ifcs ) { count += getMethodCountForName ( ifc , methodName ) ; } if ( clazz . getSuperclass ( ) != null ) { count += getMethodCountForName ( clazz . getSuperclass ( ) , methodName ) ; } return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the given method is declared by the user or at least pointing to a user - declared method . <p > Checks { @link Method#isSynthetic () } ( for implementation methods ) as well as the { @code GroovyObject } interface ( for interface methods ; on an implementation class implementations of the { @code GroovyObject } methods will be marked as synthetic anyway ) . Note that despite being synthetic bridge methods ( { @link Method#isBridge () } ) are considered as user - level methods since they are eventually pointing to a user - declared generic method . [CODESPLIT] public static boolean isUserLevelMethod ( Method method ) { Preconditions . checkNotNull ( method , \"Method must not be null\" ) ; return ( method . isBridge ( ) || ( ! method . isSynthetic ( ) && ! isGroovyObjectMethod ( method ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given class represents a primitive ( i . e . boolean byte char short int long float or double ) or a primitive wrapper ( i . e . Boolean Byte Character Short Integer Long Float or Double ) . [CODESPLIT] public static boolean isPrimitiveOrWrapper ( Class < ? > clazz ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; return ( clazz . isPrimitive ( ) || isPrimitiveWrapper ( clazz ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given class represents an array of primitives i . e . boolean byte char short int long float or double . [CODESPLIT] public static boolean isPrimitiveArray ( Class < ? > clazz ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; return ( clazz . isArray ( ) && clazz . getComponentType ( ) . isPrimitive ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the given class represents an array of primitive wrappers i . e . Boolean Byte Character Short Integer Long Float or Double . [CODESPLIT] public static boolean isPrimitiveWrapperArray ( Class < ? > clazz ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; return ( clazz . isArray ( ) && isPrimitiveWrapper ( clazz . getComponentType ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolve the given class if it is a primitive class returning the corresponding primitive wrapper type instead . [CODESPLIT] public static Class < ? > resolvePrimitiveIfNecessary ( Class < ? > clazz ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; return ( clazz . isPrimitive ( ) && clazz != void . class ? primitiveTypeToWrapperMap . get ( clazz ) : clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if the right - hand side type may be assigned to the left - hand side type assuming setting by reflection . Considers primitive wrapper classes as assignable to the corresponding primitive types . [CODESPLIT] public static boolean isAssignable ( Class < ? > lhsType , Class < ? > rhsType ) { Preconditions . checkNotNull ( lhsType , \"Left-hand side type must not be null\" ) ; Preconditions . checkNotNull ( rhsType , \"Right-hand side type must not be null\" ) ; if ( lhsType . isAssignableFrom ( rhsType ) ) { return true ; } if ( lhsType . isPrimitive ( ) ) { Class < ? > resolvedPrimitive = primitiveWrapperTypeMap . get ( rhsType ) ; if ( resolvedPrimitive != null && lhsType . equals ( resolvedPrimitive ) ) { return true ; } } else { Class < ? > resolvedWrapper = primitiveTypeToWrapperMap . get ( rhsType ) ; if ( resolvedWrapper != null && lhsType . isAssignableFrom ( resolvedWrapper ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given type is assignable from the given value assuming setting by reflection . Considers primitive wrapper classes as assignable to the corresponding primitive types . [CODESPLIT] public static boolean isAssignableValue ( Class < ? > type , Object value ) { Preconditions . checkNotNull ( type , \"Type must not be null\" ) ; return ( value != null ? isAssignable ( type , value . getClass ( ) ) : ! type . isPrimitive ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a / - based resource path to a . - based fully qualified class name . [CODESPLIT] public static String convertResourcePathToClassName ( String resourcePath ) { Preconditions . checkNotNull ( resourcePath , \"Resource path must not be null\" ) ; return resourcePath . replace ( PATH_SEPARATOR , PACKAGE_SEPARATOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a . - based fully qualified class name to a / - based resource path . [CODESPLIT] public static String convertClassNameToResourcePath ( String className ) { Preconditions . checkNotNull ( className , \"Class name must not be null\" ) ; return className . replace ( PACKAGE_SEPARATOR , PATH_SEPARATOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a path suitable for use with { @code ClassLoader . getResource } ( also suitable for use with { @code Class . getResource } by prepending a slash ( / ) to the return value ) . Built by taking the package of the specified class file converting all dots ( . ) to slashes ( / ) adding a trailing slash if necessary and concatenating the specified resource name to this . [CODESPLIT] public static String addResourcePathToPackagePath ( Class < ? > clazz , String resourceName ) { Preconditions . checkNotNull ( resourceName , \"Resource name must not be null\" ) ; if ( ! resourceName . startsWith ( \"/\" ) ) { return classPackageAsResourcePath ( clazz ) + \"/\" + resourceName ; } return classPackageAsResourcePath ( clazz ) + resourceName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all interfaces that the given instance implements as array including ones implemented by superclasses . [CODESPLIT] public static Class < ? > [ ] getAllInterfaces ( Object instance ) { Preconditions . checkNotNull ( instance , \"Instance must not be null\" ) ; return getAllInterfacesForClass ( instance . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all interfaces that the given instance implements as Set including ones implemented by superclasses . [CODESPLIT] public static Set < Class < ? > > getAllInterfacesAsSet ( Object instance ) { Preconditions . checkNotNull ( instance , \"Instance must not be null\" ) ; return getAllInterfacesForClassAsSet ( instance . getClass ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return all interfaces that the given class implements as Set including ones implemented by superclasses . <p > If the class itself is an interface it gets returned as sole interface . [CODESPLIT] public static Set < Class < ? > > getAllInterfacesForClassAsSet ( Class < ? > clazz , ClassLoader classLoader ) { Preconditions . checkNotNull ( clazz , \"Class must not be null\" ) ; if ( clazz . isInterface ( ) && isVisible ( clazz , classLoader ) ) { return Collections . < Class < ? > > singleton ( clazz ) ; } Set < Class < ? > > interfaces = new LinkedHashSet < Class < ? > > ( ) ; while ( clazz != null ) { Class < ? > [ ] ifcs = clazz . getInterfaces ( ) ; for ( Class < ? > ifc : ifcs ) { interfaces . addAll ( getAllInterfacesForClassAsSet ( ifc , classLoader ) ) ; } clazz = clazz . getSuperclass ( ) ; } return interfaces ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a composite interface Class for the given interfaces implementing the given interfaces in one single Class . <p > This implementation builds a JDK proxy class for the given interfaces . [CODESPLIT] public static Class < ? > createCompositeInterface ( Class < ? > [ ] interfaces , ClassLoader classLoader ) { Preconditions . checkNotNull ( interfaces , \"Interfaces must not be empty\" ) ; Preconditions . checkNotNull ( classLoader , \"ClassLoader must not be null\" ) ; return Proxy . getProxyClass ( classLoader , interfaces ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method initializes servlet filters . <p > Default implementation adds request vector filter by default . < / p > <p > Overrides of this method can also do things like enforcing UTF - 8 encoding . Here is an example of how it can be done : <code > final FilterHolder encFilterHolder = contextHandler . addFilter ( CharacterEncodingFilter . class / * EnumSet . allOf ( DispatcherType . class )) ; encFilterHolder . setInitParameter ( encoding UTF - 8 ) ; encFilterHolder . setInitParameter ( forceEncoding true ) ; // this line instructs filter to add encoding < / code > However this is usually not something < / p > [CODESPLIT] protected void initContextFilters ( @ Nonnull ServletContextHandler contextHandler ) { if ( springSecurityEnabled ) { initSpringSecurity ( contextHandler ) ; } if ( requestVectorOperationsEnabled ) { initRequestVectorOperations ( contextHandler ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes properties to the temporary file that will be deleted on process exit and returns file URL as a result . [CODESPLIT] public URL writeToTempFile ( ) throws IOException { final File tempConfigFile = File . createTempFile ( \"brikar-tempconfig-\" , \".properties\" ) ; tempConfigFile . deleteOnExit ( ) ; // store properties final Properties props = new Properties ( ) ; props . putAll ( properties ) ; try ( final FileOutputStream fileOutputStream = new FileOutputStream ( tempConfigFile ) ) { props . store ( fileOutputStream , \"[brikar-maintenance] TempConfiguration - Autogenerated properties\" ) ; } return tempConfigFile . toURI ( ) . toURL ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "数组 [CODESPLIT] public void add ( String key , Object value ) { list . add ( new BasicDBObject ( key , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identifies Web endpoint method to be invoked from the HTTP request s URI . This method processes the request as the following steps : <ol > <li > Gets Web endpoint classes from the { @code ServletContext } . If they have not been set on the { @code ServletContext } this method loads them by invoking { @code Loader#load () } on the loader that the { @code Configuration } returns . < / li > <li > Determines if the requested URI is ignored by { @link Routing } . If the requested URI is matched to the pattern specified by { @code Routing#ignore ( String ... ) } the request is forwarded to the next filter chain . < / li > <li > Determines if the requested URI is matched to the URI template specified by { @code Routing#add ( String Class String ) } . If the requested URI is matched to the URI template the corresponding Web endpoint method is set to the current HTTP request processing context . < / li > <li > If the requested URI is not matched to any URI template identifies Web endpoint class and method according to the default URI convention ( URI ends with / ... / &lt ; simple - name - of - the - endpoint - class&gt ; / &lt ; endpoint - method&gt ; ) . < / li > <li > If any Web endpoint method is not identified the request is forwarded to the next filter chain . < / li > < / ol > [CODESPLIT] public boolean apply ( WebContext context ) { Configuration configuration = context . configuration ( ) ; if ( endpoints == null ) { synchronized ( lock ) { if ( endpoints == null ) { endpoints = new HashMap < String , Class < ? > > ( ) ; for ( Class < ? > endpoint : configuration . endpoints ( ) ) { String name = endpoint . getSimpleName ( ) . toLowerCase ( ) ; if ( endpoints . containsKey ( name ) ) { logger . warn ( \"Web endpoint class name is duplicated: [\" + endpoints . get ( name ) + \"] is overwritten by [\" + endpoint + \"]\" ) ; } endpoints . put ( name , endpoint ) ; } } } } if ( routing == null ) { synchronized ( lock ) { if ( routing == null ) { routing = configuration . routing ( ) ; } } } HttpServletRequest request = context . request ( ) ; String uri = request . getRequestURI ( ) . substring ( ( request . getContextPath ( ) ) . length ( ) ) ; try { if ( routing . ignores ( uri ) ) { logger . debug ( \"URI [\" + request . getRequestURI ( ) + \"] is ignored by routing configuration\" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } Verb verb = null ; try { verb = Verb . valueOf ( request . getMethod ( ) ) ; } catch ( Exception e ) { logger . warn ( \"HTTP verb [\" + request . getMethod ( ) + \"] is not supported\" ) ; } List < Entry < URITemplate , Map < Verb , Method > > > route = routing . route ( uri ) ; for ( Entry < URITemplate , Map < Verb , Method > > r : route ) { Method method = r . getValue ( ) . get ( verb ) ; if ( method == null ) { method = r . getValue ( ) . get ( null ) ; } if ( method != null ) { context . method ( method ) ; request . setAttribute ( Request . PATH , r . getKey ( ) . variables ( uri ) ) ; logger . debug ( \"Web endpoint method is [\" + method . getDeclaringClass ( ) . getName ( ) + \"#\" + method . getName ( ) + \"]\" ) ; return true ; } } if ( uri . endsWith ( \"/\" ) ) { logger . debug ( \"URI [\" + request . getRequestURI ( ) + \"] is not correlated with any Web endpoint\" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } String [ ] segments = uri . split ( \"/\" ) ; if ( segments . length < 2 ) { logger . debug ( \"URI [\" + request . getRequestURI ( ) + \"] is not correlated with any Web endpoint\" ) ; logger . debug ( \"The requested URI pattern must end with \" + \"[/.../<simple-name-of-the-endpoint-class>/<endpoint-method>] or \" + \"correlated with any Web endpoint in the routing configuration\" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } Class < ? > endpoint = endpoints . get ( segments [ segments . length - 2 ] . toLowerCase ( ) ) ; if ( endpoint == null ) { logger . warn ( \"Web endpoint class is not found: Simple class name [\" + segments [ segments . length - 2 ] + \"]\" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } for ( Method method : endpoint . getMethods ( ) ) { if ( method . getName ( ) . compareToIgnoreCase ( segments [ segments . length - 1 ] ) == 0 ) { context . method ( method ) ; logger . debug ( \"Web endpoint method is [\" + method . getDeclaringClass ( ) . getName ( ) + \"#\" + method . getName ( ) + \"]\" ) ; return true ; } } logger . warn ( \"Web endpoint method is not found: Method name [\" + segments [ segments . length - 1 ] + \"]\" ) ; context . chain ( ) . doFilter ( request , context . response ( ) ) ; return false ; } catch ( Exception e ) { throw new UncheckedException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到当时进程PID 如果没有得到，返回 - 1 [CODESPLIT] public static int getPid ( ) { String name = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; int indexOf = name . indexOf ( StringPool . AT ) ; if ( indexOf > 0 ) { return Integer . parseInt ( name . substring ( 0 , indexOf ) ) ; } else { return - 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "锁定一个临时文件，以便实现一台服务器只能启动一个进程 [CODESPLIT] public static void lockFileForOnlyProcess ( String lockName ) { File file = new File ( System . getProperty ( \"java.io.tmpdir\" ) , lockName + \".lock\" ) ; try { FileOutputStream output = new FileOutputStream ( file ) ; FileLock fileLock = output . getChannel ( ) . tryLock ( ) ; if ( fileLock == null ) { logger . warn ( \"文件:'\" + f l  + \" 已 被lock,进程已经启动,系统将退出\");   System . exit ( 1 ) ; } PrintStream printStream = new PrintStream ( output ) ; printStream . println ( getPid ( ) ) ; printStream . flush ( ) ; jvmFile . add ( fileLock ) ; logger . info ( \"成功lock文件:'\" + file    ',用以 免 序被多次启动,pid:\" + getPid());       } catch ( IOException e ) { logger . warn ( \"获得文件lock时异常:'\" + file + \"',系 退 \", e ;      System . exit ( 2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns template variable name and value pairs extracted from the specified actual URI . [CODESPLIT] public Map < String , String > variables ( String uri ) { Map < String , String > variables = new HashMap < String , String > ( ) ; Matcher matcher = pattern . matcher ( uri ) ; if ( matcher . matches ( ) ) { for ( int i = 0 ; i < matcher . groupCount ( ) ; i ++ ) { variables . put ( this . variables . get ( i ) , matcher . group ( i + 1 ) ) ; } } return variables ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this URI template to the specified one . Returns <code > &lt ; 0< / code > if this URI template s segment ( split by / ) count is <b > greater< / b > than the specified one <code > &gt ; 0< / code > if this URI template s segment count is <b > less< / b > than the specified one or this URI template s segment count is equivalent to the specified one . This method is used for sorting URI templates according to the priority { @code URITemplate#matches ( String ) } method is tested by { @link Routing } class so a stricter template ( which has more segments ) is prior to a less one . [CODESPLIT] public int compareTo ( URITemplate o ) { if ( template . equals ( o . template ) ) { return 0 ; } int difference = template . split ( \"/\" ) . length - o . template . split ( \"/\" ) . length ; return ( difference == 0 ) ? 1 : difference * - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add permission and message one by one . [CODESPLIT] public PermBean put ( Permission permission , String message ) { if ( permission == null ) throw new IllegalArgumentException ( \"Permission can't be null\" ) ; mPermissions . put ( permission , message ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines if first class match the destination and simulates kind of <code > instanceof< / code > . All subclasses and interface of first class are examined against second class . Method is not symmetric . [CODESPLIT] public static boolean isSubclass ( Class thisClass , Class target ) { if ( target . isInterface ( ) ) { return isInterfaceImpl ( thisClass , target ) ; } for ( Class x = thisClass ; x != null ; x = x . getSuperclass ( ) ) { if ( x == target ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <code > true< / code > if provided class is interface implementation . [CODESPLIT] public static boolean isInterfaceImpl ( Class thisClass , Class targetInterface ) { for ( Class x = thisClass ; x != null ; x = x . getSuperclass ( ) ) { Class [ ] interfaces = x . getInterfaces ( ) ; for ( Class i : interfaces ) { if ( i == targetInterface ) { return true ; } if ( isInterfaceImpl ( i , targetInterface ) ) { return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get a Map containing field names and wrapped values for the fields values . <p / > If the wrapped object is a { @link Class } then this will return static fields . If the wrapped object is any other { @link Object } then this will return instance fields . <p / > These two calls are equivalent <code > <pre > on ( object ) . field ( myField ) ; on ( object ) . fields () . get ( myField ) ; < / pre > < / code > [CODESPLIT] public Map < String , Reflect > fields ( ) { Map < String , Reflect > result = Maps . newLinkedHashMap ( ) ; for ( Field field : type ( ) . getFields ( ) ) { if ( ! isClass ^ Modifier . isStatic ( field . getModifiers ( ) ) ) { String name = field . getName ( ) ; result . put ( name , field ( name ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The configuration database specify the name of the database . [CODESPLIT] public static DruidPlugin druidPlugin ( Properties dbProp ) { String dbUrl = dbProp . getProperty ( GojaPropConst . DBURL ) , username = dbProp . getProperty ( GojaPropConst . DBUSERNAME ) , password = dbProp . getProperty ( GojaPropConst . DBPASSWORD ) ; if ( ! Strings . isNullOrEmpty ( dbUrl ) ) { String dbtype = JdbcUtils . getDbType ( dbUrl , StringUtils . EMPTY ) ; String driverClassName ; try { driverClassName = JdbcUtils . getDriverClassName ( dbUrl ) ; } catch ( SQLException e ) { throw new DatabaseException ( e . getMessage ( ) , e ) ; } final DruidPlugin druidPlugin = new DruidPlugin ( dbUrl , username , password , driverClassName ) ; // set validator setValidatorQuery ( dbtype , druidPlugin ) ; druidPlugin . addFilter ( new StatFilter ( ) ) ; final String initialSize = dbProp . getProperty ( GojaPropConst . DB_INITIAL_SIZE ) ; if ( ! Strings . isNullOrEmpty ( initialSize ) ) { druidPlugin . setInitialSize ( MoreObjects . firstNonNull ( Ints . tryParse ( initialSize ) , 6 ) ) ; } final String initial_minidle = dbProp . getProperty ( GojaPropConst . DB_INITIAL_MINIDLE ) ; if ( ! Strings . isNullOrEmpty ( initial_minidle ) ) { druidPlugin . setMinIdle ( MoreObjects . firstNonNull ( Ints . tryParse ( initial_minidle ) , 5 ) ) ; } final String initial_maxwait = dbProp . getProperty ( GojaPropConst . DB_INITIAL_MAXWAIT ) ; if ( ! Strings . isNullOrEmpty ( initial_maxwait ) ) { druidPlugin . setMaxWait ( MoreObjects . firstNonNull ( Ints . tryParse ( initial_maxwait ) , 5 ) ) ; } final String initial_active = dbProp . getProperty ( GojaPropConst . DB_INITIAL_ACTIVE ) ; if ( ! Strings . isNullOrEmpty ( initial_active ) ) { druidPlugin . setMaxActive ( MoreObjects . firstNonNull ( Ints . tryParse ( initial_active ) , 5 ) ) ; } final String timeBetweenEvictionRunsMillis = dbProp . getProperty ( GojaPropConst . DB_TIME_BETWEEN_EVICTION_RUNS_MILLIS ) ; if ( ! Strings . isNullOrEmpty ( timeBetweenEvictionRunsMillis ) ) { final Integer millis = MoreObjects . firstNonNull ( Ints . tryParse ( timeBetweenEvictionRunsMillis ) , 10000 ) ; druidPlugin . setTimeBetweenEvictionRunsMillis ( millis ) ; } final String minEvictableIdleTimeMillis = dbProp . getProperty ( GojaPropConst . DB_MIN_EVICTABLE_IDLE_TIME_MILLIS ) ; if ( ! Strings . isNullOrEmpty ( minEvictableIdleTimeMillis ) ) { final Integer idleTimeMillis = MoreObjects . firstNonNull ( Ints . tryParse ( minEvictableIdleTimeMillis ) , 10000 ) ; druidPlugin . setMinEvictableIdleTimeMillis ( idleTimeMillis ) ; } final WallFilter wall = new WallFilter ( ) ; wall . setDbType ( dbtype ) ; druidPlugin . addFilter ( wall ) ; if ( GojaConfig . getPropertyToBoolean ( GojaPropConst . DBLOGFILE , false ) ) { // 增加 LogFilter 输出JDBC执行的日志 druidPlugin . addFilter ( new Slf4jLogFilter ( ) ) ; } return druidPlugin ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows the subtype to be selective about what to bind . [CODESPLIT] protected < T > void bind ( Class < ? extends T > impl , Class < T > extensionPoint ) { ExtensionLoaderModule < T > lm = createLoaderModule ( extensionPoint ) ; lm . init ( impl , extensionPoint ) ; install ( lm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new instance of { [CODESPLIT] protected < T > ExtensionLoaderModule < T > createLoaderModule ( Class < T > extensionPoint ) { ExtensionPoint ep = extensionPoint . getAnnotation ( ExtensionPoint . class ) ; if ( ep != null ) { if ( ep . loader ( ) != ExtensionLoaderModule . Default . class ) { try { return ( ExtensionLoaderModule ) ep . loader ( ) . newInstance ( ) ; } catch ( InstantiationException e ) { throw ( Error ) new InstantiationError ( ) . initCause ( e ) ; } catch ( IllegalAccessException e ) { throw ( Error ) new IllegalAccessError ( ) . initCause ( e ) ; } } } return new ExtensionLoaderModule . Default < T > ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds all the supertypes that are annotated with { [CODESPLIT] private Set < Class > listExtensionPoint ( Class e , Set < Class > result ) { if ( e . isAnnotationPresent ( ExtensionPoint . class ) ) result . add ( e ) ; Class s = e . getSuperclass ( ) ; if ( s != null ) listExtensionPoint ( s , result ) ; for ( Class c : e . getInterfaces ( ) ) { listExtensionPoint ( c , result ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine if the given objects are equal returning { @code true } if both are { @code null } or { @code false } if only one is { @code null } . <p > Compares arrays with { @code Arrays . equals } performing an equality check based on the array elements rather than the array reference . [CODESPLIT] public static boolean nullSafeEquals ( Object o1 , Object o2 ) { if ( o1 == o2 ) { return true ; } if ( o1 == null || o2 == null ) { return false ; } if ( o1 . equals ( o2 ) ) { return true ; } if ( o1 . getClass ( ) . isArray ( ) && o2 . getClass ( ) . isArray ( ) ) { if ( o1 instanceof Object [ ] && o2 instanceof Object [ ] ) { return Arrays . equals ( ( Object [ ] ) o1 , ( Object [ ] ) o2 ) ; } if ( o1 instanceof boolean [ ] && o2 instanceof boolean [ ] ) { return Arrays . equals ( ( boolean [ ] ) o1 , ( boolean [ ] ) o2 ) ; } if ( o1 instanceof byte [ ] && o2 instanceof byte [ ] ) { return Arrays . equals ( ( byte [ ] ) o1 , ( byte [ ] ) o2 ) ; } if ( o1 instanceof char [ ] && o2 instanceof char [ ] ) { return Arrays . equals ( ( char [ ] ) o1 , ( char [ ] ) o2 ) ; } if ( o1 instanceof double [ ] && o2 instanceof double [ ] ) { return Arrays . equals ( ( double [ ] ) o1 , ( double [ ] ) o2 ) ; } if ( o1 instanceof float [ ] && o2 instanceof float [ ] ) { return Arrays . equals ( ( float [ ] ) o1 , ( float [ ] ) o2 ) ; } if ( o1 instanceof int [ ] && o2 instanceof int [ ] ) { return Arrays . equals ( ( int [ ] ) o1 , ( int [ ] ) o2 ) ; } if ( o1 instanceof long [ ] && o2 instanceof long [ ] ) { return Arrays . equals ( ( long [ ] ) o1 , ( long [ ] ) o2 ) ; } if ( o1 instanceof short [ ] && o2 instanceof short [ ] ) { return Arrays . equals ( ( short [ ] ) o1 , ( short [ ] ) o2 ) ; } } return false ; } /**\n     * Return as hash code for the given object; typically the value of {@code Object#hashCode()}}. If\n     * the object is an array, this method will delegate to any of the {@code nullSafeHashCode}\n     * methods for arrays in this class. If the object is {@code null}, this method returns 0.\n     *\n     * @see #nullSafeHashCode(Object[])\n     * @see #nullSafeHashCode(boolean[])\n     * @see #nullSafeHashCode(byte[])\n     * @see #nullSafeHashCode(char[])\n     * @see #nullSafeHashCode(double[])\n     * @see #nullSafeHashCode(float[])\n     * @see #nullSafeHashCode(int[])\n     * @see #nullSafeHashCode(long[])\n     * @see #nullSafeHashCode(short[])\n     */ public static int nullSafeHashCode ( Object obj ) { if ( obj == null ) { return 0 ; } if ( obj . getClass ( ) . isArray ( ) ) { if ( obj instanceof Object [ ] ) { return nullSafeHashCode ( ( Object [ ] ) obj ) ; } if ( obj instanceof boolean [ ] ) { return nullSafeHashCode ( ( boolean [ ] ) obj ) ; } if ( obj instanceof byte [ ] ) { return nullSafeHashCode ( ( byte [ ] ) obj ) ; } if ( obj instanceof char [ ] ) { return nullSafeHashCode ( ( char [ ] ) obj ) ; } if ( obj instanceof double [ ] ) { return nullSafeHashCode ( ( double [ ] ) obj ) ; } if ( obj instanceof float [ ] ) { return nullSafeHashCode ( ( float [ ] ) obj ) ; } if ( obj instanceof int [ ] ) { return nullSafeHashCode ( ( int [ ] ) obj ) ; } if ( obj instanceof long [ ] ) { return nullSafeHashCode ( ( long [ ] ) obj ) ; } if ( obj instanceof short [ ] ) { return nullSafeHashCode ( ( short [ ] ) obj ) ; } } return obj . hashCode ( ) ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( Object [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( Object element : array ) { hash = MULTIPLIER * hash + nullSafeHashCode ( element ) ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( boolean [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( boolean element : array ) { hash = MULTIPLIER * hash + hashCode ( element ) ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( byte [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( byte element : array ) { hash = MULTIPLIER * hash + element ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( char [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( char element : array ) { hash = MULTIPLIER * hash + element ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( double [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( double element : array ) { hash = MULTIPLIER * hash + hashCode ( element ) ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( float [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( float element : array ) { hash = MULTIPLIER * hash + hashCode ( element ) ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( int [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( int element : array ) { hash = MULTIPLIER * hash + element ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( long [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( long element : array ) { hash = MULTIPLIER * hash + hashCode ( element ) ; } return hash ; } /**\n     * Return a hash code based on the contents of the specified array. If {@code array} is {@code\n     * null}, this method returns 0.\n     */ public static int nullSafeHashCode ( short [ ] array ) { if ( array == null ) { return 0 ; } int hash = INITIAL_HASH ; for ( short element : array ) { hash = MULTIPLIER * hash + element ; } return hash ; } /**\n     * Return the same value as {@link Boolean#hashCode()}}.\n     *\n     * @see Boolean#hashCode()\n     */ public static int hashCode ( boolean bool ) { return ( bool ? 1231 : 1237 ) ; } /**\n     * Return the same value as {@link Double#hashCode()}}.\n     *\n     * @see Double#hashCode()\n     */ public static int hashCode ( double dbl ) { return hashCode ( Double . doubleToLongBits ( dbl ) ) ; } /**\n     * Return the same value as {@link Float#hashCode()}}.\n     *\n     * @see Float#hashCode()\n     */ public static int hashCode ( float flt ) { return Float . floatToIntBits ( flt ) ; } /**\n     * Return the same value as {@link Long#hashCode()}}.\n     *\n     * @see Long#hashCode()\n     */ public static int hashCode ( long lng ) { return ( int ) ( lng ^ ( lng >>> 32 ) ) ; } //--------------------------------------------------------------------- // Convenience methods for toString output //--------------------------------------------------------------------- /**\n     * Return a String representation of the specified Object. <p>Builds a String representation of\n     * the contents in case of an array. Returns {@code \"null\"} if {@code obj} is {@code null}.\n     *\n     * @param obj the object to build a String representation for\n     * @return a String representation of {@code obj}\n     */ public static String nullSafeToString ( Object obj ) { if ( obj == null ) { return NULL_STRING ; } if ( obj instanceof String ) { return ( String ) obj ; } if ( obj instanceof Object [ ] ) { return nullSafeToString ( ( Object [ ] ) obj ) ; } if ( obj instanceof boolean [ ] ) { return nullSafeToString ( ( boolean [ ] ) obj ) ; } if ( obj instanceof byte [ ] ) { return nullSafeToString ( ( byte [ ] ) obj ) ; } if ( obj instanceof char [ ] ) { return nullSafeToString ( ( char [ ] ) obj ) ; } if ( obj instanceof double [ ] ) { return nullSafeToString ( ( double [ ] ) obj ) ; } if ( obj instanceof float [ ] ) { return nullSafeToString ( ( float [ ] ) obj ) ; } if ( obj instanceof int [ ] ) { return nullSafeToString ( ( int [ ] ) obj ) ; } if ( obj instanceof long [ ] ) { return nullSafeToString ( ( long [ ] ) obj ) ; } if ( obj instanceof short [ ] ) { return nullSafeToString ( ( short [ ] ) obj ) ; } return obj . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( Object [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( String . valueOf ( array [ i ] ) ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( boolean [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( array [ i ] ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( byte [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( array [ i ] ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( char [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( \" ' \" ) . append ( array [ i ] ) . append ( \" ' \" ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( double [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( array [ i ] ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( float [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( array [ i ] ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( int [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( array [ i ] ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( long [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( array [ i ] ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } /**\n     * Return a String representation of the contents of the specified array. <p>The String\n     * representation consists of a list of the array's elements, enclosed in curly braces ({@code\n     * \"{}\"}). Adjacent elements are separated by the characters {@code \", \"} (a comma followed by a\n     * space). Returns {@code \"null\"} if {@code array} is {@code null}.\n     *\n     * @param array the array to build a String representation for\n     * @return a String representation of {@code array}\n     */ public static String nullSafeToString ( short [ ] array ) { if ( array == null ) { return NULL_STRING ; } int length = array . length ; if ( length == 0 ) { return EMPTY_ARRAY ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i == 0 ) { sb . append ( ARRAY_START ) ; } else { sb . append ( ARRAY_ELEMENT_SEPARATOR ) ; } sb . append ( array [ i ] ) ; } sb . append ( ARRAY_END ) ; return sb . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs Web endpoint parameter from the specified source list or type . This method is invoked for every Web endpoint method parameter by { @link Receive } . This method processes according to the following steps : <ol > <li > If the specified type is an array type returns <code > null< / code > . An array type is not supported in this class . < / li > <li > If the specified type is built - in type ( See { @link Types#isBuiltinType ( Type ) } ) returns the built - in instance . < / li > <li > Constructs the value as the specified type from the specified sources and names . If the Web endpoint parameter is declared without any source annotation except built - in type this method always returns <code > null< / code > . < / li > <li > If the construction result is not <code > null< / code > returns the result to the client . < / li > <li > If the result is <code > null< / code > of primitive type returns the default value of each primitive type to the client . < / li > <li > If the result is <code > null< / code > of supported collection type ( See { @link Types#isSupportedCollection ( Type ) } ) returns the empty collection of the specified type to the client . < / li > <li > Otherwise returns <code > null< / code > . < / li > < / ol > [CODESPLIT] public Object get ( Type type , List < Annotation > sources ) { if ( Types . isArray ( type ) ) { logger . warn ( \"Array type is not supported in [\" + getClass ( ) + \"]\" ) ; return null ; } else if ( Types . isBuiltinType ( type ) ) { return builtin ( type ) ; } for ( Annotation source : sources ) { Object parameter = null ; if ( source instanceof Query ) { Query query = ( Query ) source ; parameter = query ( type , query . value ( ) ) ; } else if ( source instanceof Body ) { Body body = ( Body ) source ; parameter = body ( type , body . value ( ) ) ; } else if ( source instanceof Header ) { Header header = ( Header ) source ; parameter = header ( type , header . value ( ) ) ; } else if ( source instanceof org . eiichiro . bootleg . annotation . Cookie ) { org . eiichiro . bootleg . annotation . Cookie cookie = ( org . eiichiro . bootleg . annotation . Cookie ) source ; parameter = cookie ( type , cookie . value ( ) ) ; } else if ( source instanceof Session ) { Session session = ( Session ) source ; parameter = session ( type , session . value ( ) ) ; } else if ( source instanceof Application ) { Application application = ( Application ) source ; parameter = application ( type , application . value ( ) ) ; } else if ( source instanceof Path ) { Path path = ( Path ) source ; parameter = path ( type , path . value ( ) ) ; } else { logger . warn ( \"Unknown source [\" + source + \"]\" ) ; } if ( parameter != null ) { return parameter ; } } if ( Types . isPrimitive ( type ) ) { logger . debug ( \"Cannot construct [\" + type + \"] primitive; Returns the default value\" ) ; return primitive ( type ) ; } else if ( Types . isCollection ( type ) ) { if ( Types . isSupportedCollection ( type ) ) { logger . debug ( \"Cannot construct [\" + type + \"] collection; Returns the empty colleciton\" ) ; return Types . getEmptyCollection ( type ) ; } else { logger . warn ( \"Collection type \" + type + \" is not supported in [\" + getClass ( ) + \"]\" ) ; return null ; } } StringBuilder builder = new StringBuilder ( ) ; for ( Annotation source : sources ) { builder . append ( source + \" \" ) ; } logger . debug ( \"Cannot construct Web endpoint method parameter [\" + builder + type + \"]\" ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of built - in type . [CODESPLIT] protected Object builtin ( Type type ) { Class < ? > rawType = Types . getRawType ( type ) ; if ( rawType . equals ( WebContext . class ) ) { return context ; } else if ( rawType . equals ( HttpServletRequest . class ) ) { return context . request ( ) ; } else if ( rawType . equals ( HttpServletResponse . class ) ) { return context . response ( ) ; } else if ( rawType . equals ( HttpSession . class ) ) { return context . session ( ) ; } else if ( rawType . equals ( ServletContext . class ) ) { return context . application ( ) ; } else { // org.eiichiro.bootleg.Request. return this ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the default value of the specified primitive type . [CODESPLIT] protected Object primitive ( Type type ) { Class < ? > rawType = Types . getRawType ( type ) ; if ( rawType . equals ( Boolean . TYPE ) ) { return ( boolean ) false ; } else if ( rawType . equals ( Character . TYPE ) ) { return ( char ) 0 ; } else if ( rawType . equals ( Byte . TYPE ) ) { return ( byte ) 0 ; } else if ( rawType . equals ( Double . TYPE ) ) { return ( double ) 0.0 ; } else if ( rawType . equals ( Float . TYPE ) ) { return ( float ) 0.0 ; } else if ( rawType . equals ( Integer . TYPE ) ) { return ( int ) 0 ; } else { // short. return ( short ) 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Constructs the value of Web endpoint parameter . Web endpoint parameter declaration falls into the several patterns and each pattern has the own construction logic as below : <ol > <li > Named array type - Unsupported . Always returns <code > null< / code > . < / li > <li > Named collection of core value type - Supported . The collection instance is constructed according to the default implementation type ( See { @code Types#getDefaultImplementationType ( Type ) } ) . If the collection type is not supported ( See { @code Types#isSupportedCollection ( Type ) } ) this method returns <code > null< / code > . Each of the collection elements is constructed from the values that { @code values } has returned as the same way of the following core value type . If the constructed collection has no element this method returns <code > null< / code > . < / li > <li > Named collection of user - defined value type - Supported . The collection instance is constructed according to the default implementation type ( as the same as collection of core value type ) . Each of the collection elements is constructed from the values that { @code values } has returned as the same way of following user - defined value type . < / li > <li > Named collection of user - defined object type - Unsupported . Always returns <code > null< / code > . < / li > <li > Named core value type - Supported . The value that { @code value } has returned is converted to the core value type . If the conversion failed returns <code > null< / code > < / li > <li > Named user - defined value type - Supported . If the value that { @code value } has returned is assignable to the user - defined value type returns it . If the value that { @code value } has returned is { @code String . class } this method constructs the user - defined value type with public constructor that takes one String . class parameter or public static <code > valueOf ( String . class ) < / code > method . If the conversion failed returns <code > null< / code > . < / li > <li > Named user - defined object type - Partially supported . If the value that { @code value } method has returned is assignable to the user - defined object type returns it . Otherwise returns <code > null< / code > ( does not any type conversion ) . < / li > <li > Not named array type - Unsupported . Always returns <code > null< / code > . < / li > <li > Not named collection of core value type - Unsupported . Always returns <code > null< / code > . < / li > <li > Not named collection of user - defined value type - Unsupported . Always returns <code > null< / code > . < / li > <li > Not named collection of user - defined object type - Unsupported . Always returns <code > null< / code > . < / li > <li > Not named core value type - Unsupported . Always returns <code > null< / code > . < / li > <li > Not named user - defined value type - Unsupported . Always returns <code > null< / code > . < / li > <li > Not named user - defined object type - Supported . First this method instantiates the user - defined object instance form public default constructor and then constructs each of the instances fields value according to the named type construction described above ( by invoking { @code #newParameter ( WebContext Type String ) } with the field type and field name ) . If the instantiation is failed returns <code > null < / code > . < / li > < / ol > This method is overridable . You can provide your own value construction to Web endpoint parameter by overriding this method . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected Object parameter ( Type type , String name , Function < String , Object > value , Function < String , Collection < Object > > values ) { if ( name != null && ! name . isEmpty ( ) ) { // Named parameter construction. if ( Types . isArray ( type ) ) { // Named array type. logger . debug ( \"Array type [\" + type + \"] is not supported in [\" + getClass ( ) + \"]\" ) ; } else if ( Types . isCollection ( type ) ) { // Named collection type. if ( Types . isSupportedCollection ( type ) ) { Collection < Object > objects = values . apply ( name ) ; if ( objects == null ) { logger . debug ( \"Collection named [\" + name + \"] not found\" ) ; } else { Class < ? > elementType = Types . getElementType ( type ) ; boolean coreValueType = Types . isCoreValueType ( elementType ) ; if ( ! coreValueType && ! Types . isUserDefinedValueType ( elementType ) ) { // Named collection of user-defined object. logger . debug ( \"Collection element type [\" + elementType + \"] is not supported in [\" + getClass ( ) + \"]\" ) ; } else { try { Class < ? > implementationType = Types . getDefaultImplementationType ( type ) ; Collection < Object > collection = ( Collection < Object > ) implementationType . newInstance ( ) ; for ( Object object : objects ) { // Named collection of core value type. // Named collection of user-defined value type. Object convert = ( coreValueType ) ? convert ( object , elementType ) : convertUserDefinedValueType ( object , elementType ) ; if ( convert != null && ClassUtils . primitiveToWrapper ( elementType ) . isAssignableFrom ( convert . getClass ( ) ) ) { collection . add ( convert ) ; } else { logger . debug ( \"Parameter [\" + convert + \"] cannot be converted to [\" + elementType + \"]\" ) ; } } return ( ! collection . isEmpty ( ) ) ? collection : null ; } catch ( Exception e ) { logger . debug ( \"Cannot instantiate [\" + Types . getDefaultImplementationType ( type ) + \"] (Default implementation type of [\" + type + \"])\" , e ) ; } } } } else { logger . debug ( \"Parameter type [\" + type + \"] is not supported in [\" + getClass ( ) + \"]\" ) ; } } else if ( Types . isCoreValueType ( type ) ) { // Named core value type. Class < ? > rawType = Types . getRawType ( type ) ; Object object = value . apply ( name ) ; if ( object == null ) { logger . debug ( \"Value named [\" + name + \"] not found\" ) ; } else { Object convert = convert ( object , rawType ) ; if ( convert != null && ClassUtils . primitiveToWrapper ( rawType ) . isAssignableFrom ( convert . getClass ( ) ) ) { return convert ; } else { logger . warn ( \"Parameter [\" + convert + \"] cannot be converted to [\" + type + \"]\" ) ; } } } else if ( Types . isUserDefinedValueType ( type ) ) { // Named user-defined value type. Object object = value . apply ( name ) ; Class < ? > rawType = Types . getRawType ( type ) ; if ( object == null ) { logger . debug ( \"Value named [\" + name + \"] not found\" ) ; } else { Object userDefinedValueType = convertUserDefinedValueType ( object , rawType ) ; if ( userDefinedValueType == null ) { logger . warn ( \"Parameter [\" + object + \"] cannot be converted to [\" + type + \"]\" ) ; } return userDefinedValueType ; } } else { // Named user-defined object type. Object object = value . apply ( name ) ; if ( object == null ) { logger . debug ( \"Value named [\" + name + \"] not found\" ) ; } else if ( Types . getRawType ( type ) . isAssignableFrom ( object . getClass ( ) ) ) { return object ; } else { logger . warn ( \"Parameter [\" + object + \"] cannot be converted to [\" + type + \"]\" ) ; } } } else { // Non-named parameter construction. if ( Types . isArray ( type ) || Types . isCollection ( type ) || Types . isCoreValueType ( type ) || Types . isUserDefinedValueType ( type ) ) { // Not named array type. // Not named collection (of core value type or user-defined object type). // Not named core value type. // Not named user-defined value type. logger . debug ( \"Non-named parameter type [\" + type + \"] is not supported in [\" + getClass ( ) + \"]\" ) ; } else { // Not named user-defined object type. Class < ? > rawType = Types . getRawType ( type ) ; try { Object instance = rawType . newInstance ( ) ; for ( Field field : rawType . getDeclaredFields ( ) ) { Object object = parameter ( field . getGenericType ( ) , field . getName ( ) , value , values ) ; if ( object != null ) { field . setAccessible ( true ) ; field . set ( instance , object ) ; } } return instance ; } catch ( Exception e ) { logger . warn ( \"Cannot instantiate [\" + type + \"]\" , e ) ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the specified object to the specified type . This method is overridable . You can provide your own conversion to the parameter construction by overriding this method . [CODESPLIT] protected Object convert ( Object object , Class < ? > type ) { try { return ConvertUtils . convert ( object , type ) ; } catch ( Exception e ) { logger . warn ( \"Cannot convert [\" + object + \"] to [\" + type + \"]\" , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the specified object to the specified user - defined value type . This method is overridable . You can provide your own conversion to the parameter construction by overriding this method . [CODESPLIT] protected Object convertUserDefinedValueType ( Object object , Class < ? > type ) { if ( type . isAssignableFrom ( object . getClass ( ) ) ) { return object ; } else if ( object instanceof String ) { try { Constructor < ? > constructor = type . getConstructor ( String . class ) ; return constructor . newInstance ( object ) ; } catch ( Exception e ) { logger . debug ( \"Cannot invoke [public \" + type . getName ( ) + \"(String.class)] constrcutor on [\" + type + \"]\" , e ) ; } try { return type . getMethod ( \"valueOf\" , String . class ) . invoke ( null , object ) ; } catch ( Exception e1 ) { logger . debug ( \"Cannot invoke [public static \" + type . getName ( ) + \".valueOf(String.class)]\" + \"method on [\" + type + \"]\" , e1 ) ; } } else { logger . warn ( \"Parameter [\" + object + \"] cannot be converted to [\" + type + \"]\" ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Web endpoint method parameter from query string . [CODESPLIT] protected Object query ( Type type , String name ) { return parameter ( type , name , new Function < String , Object > ( ) { public Object apply ( String name ) { return context . request ( ) . getParameter ( name ) ; } } , new Function < String , Collection < Object > > ( ) { @ SuppressWarnings ( \"unchecked\" ) public Collection < Object > apply ( String name ) { HttpServletRequest request = context . request ( ) ; Map < String , Object > map = new TreeMap < String , Object > ( ) ; for ( Object object : Collections . list ( request . getParameterNames ( ) ) ) { String key = ( String ) object ; if ( key . startsWith ( name + \"[\" ) ) { map . put ( key , request . getParameter ( key ) ) ; } } return ( map . isEmpty ( ) ) ? null : map . values ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Web endpoint method parameter from cookie in the HTTP request . [CODESPLIT] protected Object cookie ( Type type , String name ) { return parameter ( type , name , new Function < String , Object > ( ) { public Object apply ( String name ) { Cookie [ ] cookies = context . request ( ) . getCookies ( ) ; if ( cookies != null ) { for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( name ) ) { return cookie . getValue ( ) ; } } } return null ; } } , new Function < String , Collection < Object > > ( ) { public Collection < Object > apply ( String name ) { HttpServletRequest request = context . request ( ) ; Map < String , Object > map = new TreeMap < String , Object > ( ) ; Cookie [ ] cookies = request . getCookies ( ) ; if ( cookies != null ) { for ( Cookie cookie : cookies ) { String key = cookie . getName ( ) ; if ( key . startsWith ( name + \"[\" ) ) { map . put ( key , cookie . getValue ( ) ) ; } } } return ( map . isEmpty ( ) ) ? null : map . values ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the Web endpoint method parameter from HTTP session . [CODESPLIT] protected Object session ( Type type , String name ) { return parameter ( type , name , new Function < String , Object > ( ) { public Object apply ( String name ) { return context . session ( ) . getAttribute ( name ) ; } } , new Function < String , Collection < Object > > ( ) { @ SuppressWarnings ( \"unchecked\" ) public Collection < Object > apply ( String name ) { HttpSession session = context . session ( ) ; Object attribute = session . getAttribute ( name ) ; if ( attribute instanceof Collection < ? > ) { return ( Collection < Object > ) attribute ; } Map < String , Object > map = new TreeMap < String , Object > ( ) ; for ( Object object : Collections . list ( session . getAttributeNames ( ) ) ) { String key = ( String ) object ; if ( key . startsWith ( name + \"[\" ) ) { map . put ( key , session . getAttribute ( key ) ) ; } } return ( map . isEmpty ( ) ) ? null : map . values ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对字符串进行散列 支持md5与sha1算法 . [CODESPLIT] private static byte [ ] digest ( byte [ ] input , String algorithm , byte [ ] salt , int iterations ) { try { MessageDigest digest = MessageDigest . getInstance ( algorithm ) ; if ( salt != null ) { digest . update ( salt ) ; } byte [ ] result = digest . digest ( input ) ; for ( int i = 1 ; i < iterations ; i ++ ) { digest . reset ( ) ; result = digest . digest ( result ) ; } return result ; } catch ( GeneralSecurityException e ) { throw ExceptionKit . unchecked ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "init databases . [CODESPLIT] private void initDataSource ( final Plugins plugins ) { final Map < String , Properties > dbConfig = GojaConfig . loadDBConfig ( GojaConfig . getConfigProps ( ) ) ; for ( String db_config : dbConfig . keySet ( ) ) { final Properties db_props = dbConfig . get ( db_config ) ; if ( db_props != null && ! db_props . isEmpty ( ) ) { DruidDbIntializer . init ( db_config , plugins , db_props ) ; } } if ( GojaConfig . getPropertyToBoolean ( GojaPropConst . DB_SQLINXML , true ) ) { plugins . add ( new SqlInXmlPlugin ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set freemarker variable . [CODESPLIT] private void setFtlSharedVariable ( ) { // custmer variable final Configuration config = FreeMarkerRender . getConfiguration ( ) ; config . setSharedVariable ( \"block\" , new BlockDirective ( ) ) ; config . setSharedVariable ( \"extends\" , new ExtendsDirective ( ) ) ; config . setSharedVariable ( \"override\" , new OverrideDirective ( ) ) ; config . setSharedVariable ( \"super\" , new SuperDirective ( ) ) ; // 增加日期美化指令（类似 几分钟前） config . setSharedVariable ( \"prettytime\" , new PrettyTimeDirective ( ) ) ; if ( GojaConfig . isSecurity ( ) ) { config . setSharedVariable ( \"shiro\" , new ShiroTags ( config . getObjectWrapper ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adding custom query condition and value [CODESPLIT] public void setParam ( String field , Condition condition , Object value ) { this . params . add ( Triple . of ( field , condition , value ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adding custom query equal value . [CODESPLIT] public void setParam ( String field , Object value ) { this . setParam ( field , Condition . EQ , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support for a single entity with the integration of Datatables plugin。 [CODESPLIT] public DTResponse response ( Class < ? extends Model > model ) { Preconditions . checkNotNull ( this , \"datatable criterias is must be not null.\" ) ; final Page < Record > datas = DTDao . paginate ( model , this ) ; return DTResponse . build ( this , datas . getList ( ) , datas . getTotalRow ( ) , datas . getTotalRow ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates generic { @code Response } that has the specified entity as message body . [CODESPLIT] public static Response response ( Object value ) { GenericResponse response = new GenericResponse ( ) ; response . entity ( value ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @code JSONResponse } to send the specified entity to the client as JSON format response . [CODESPLIT] public static JSONResponse json ( Object value ) { JSONResponse response = new JSONResponse ( ) ; response . entity ( value ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates { @code XMLResponse } to send the specified entity to the client as XML format response . [CODESPLIT] public static XMLResponse xml ( Object value ) { XMLResponse response = new XMLResponse ( ) ; response . entity ( value ) ; return response ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将15位身份证号码转换为18位 [CODESPLIT] public static String conver15CardTo18 ( String idCard ) { String idCard18 ; if ( idCard . length ( ) != CHINA_ID_MIN_LENGTH ) { return null ; } if ( isNum ( idCard ) ) { // 获取出生年月日 String birthday = idCard . substring ( 6 , 12 ) ; Date birthDate = null ; try { birthDate = new SimpleDateFormat ( \"yyMMdd\" ) . parse ( birthday ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } Calendar cal = Calendar . getInstance ( ) ; if ( birthDate != null ) { cal . setTime ( birthDate ) ; } // 获取出生年(完全表现形式,如：2010) String sYear = String . valueOf ( cal . get ( Calendar . YEAR ) ) ; idCard18 = idCard . substring ( 0 , 6 ) + sYear + idCard . substring ( 8 ) ; // 转换字符数组 char [ ] cArr = idCard18 . toCharArray ( ) ; int [ ] iCard = converCharToInt ( cArr ) ; int iSum17 = getPowerSum ( iCard ) ; // 获取校验位 String sVal = getCheckCode18 ( iSum17 ) ; if ( sVal . length ( ) > 0 ) { idCard18 += sVal ; } else { return null ; } } else { return null ; } return idCard18 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证身份证是否合法 [CODESPLIT] public static boolean validateCard ( String idCard ) { String card = idCard . trim ( ) ; if ( validateIdCard18 ( card ) ) { return true ; } if ( validateIdCard15 ( card ) ) { return true ; } String [ ] cardval = validateIdCard10 ( card ) ; if ( cardval != null ) { if ( cardval [ 2 ] . equals ( \"true\" ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证18位身份编码是否合法 [CODESPLIT] public static boolean validateIdCard18 ( String idCard ) { boolean bTrue = false ; if ( idCard . length ( ) == CHINA_ID_MAX_LENGTH ) { // 前17位 String code17 = idCard . substring ( 0 , 17 ) ; // 第18位 String code18 = idCard . substring ( 17 , CHINA_ID_MAX_LENGTH ) ; if ( isNum ( code17 ) ) { char [ ] cArr = code17 . toCharArray ( ) ; int [ ] iCard = converCharToInt ( cArr ) ; int iSum17 = getPowerSum ( iCard ) ; // 获取校验位 String val = getCheckCode18 ( iSum17 ) ; if ( val . length ( ) > 0 ) { if ( val . equalsIgnoreCase ( code18 ) ) { bTrue = true ; } } } } return bTrue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证15位身份编码是否合法 [CODESPLIT] public static boolean validateIdCard15 ( String idCard ) { if ( idCard . length ( ) != CHINA_ID_MIN_LENGTH ) { return false ; } if ( isNum ( idCard ) ) { String proCode = idCard . substring ( 0 , 2 ) ; if ( cityCodes . get ( proCode ) == null ) { return false ; } String birthCode = idCard . substring ( 6 , 12 ) ; Date birthDate = null ; try { birthDate = new SimpleDateFormat ( \"yy\" ) . parse ( birthCode . substring ( 0 , 2 ) ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } Calendar cal = Calendar . getInstance ( ) ; if ( birthDate != null ) { cal . setTime ( birthDate ) ; } if ( ! valiDate ( cal . get ( Calendar . YEAR ) , Integer . valueOf ( birthCode . substring ( 2 , 4 ) ) , Integer . valueOf ( birthCode . substring ( 4 , 6 ) ) ) ) { return false ; } } else { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证10位身份编码是否合法 [CODESPLIT] public static String [ ] validateIdCard10 ( String idCard ) { String [ ] info = new String [ 3 ] ; String card = idCard . replaceAll ( \"[\\\\(|\\\\)]\" , \"\" ) ; if ( card . length ( ) != 8 && card . length ( ) != 9 && idCard . length ( ) != 10 ) { return null ; } if ( idCard . matches ( \"^[a-zA-Z][0-9]{9}$\" ) ) { // 台湾 info [ 0 ] = \"台湾\";  System . out . println ( \"11111\" ) ; String char2 = idCard . substring ( 1 , 2 ) ; if ( char2 . equals ( \"1\" ) ) { info [ 1 ] = \"M\" ; System . out . println ( \"MMMMMMM\" ) ; } else if ( char2 . equals ( \"2\" ) ) { info [ 1 ] = \"F\" ; System . out . println ( \"FFFFFFF\" ) ; } else { info [ 1 ] = \"N\" ; info [ 2 ] = \"false\" ; System . out . println ( \"NNNN\" ) ; return info ; } info [ 2 ] = validateTWCard ( idCard ) ? \"true\" : \"false\" ; } else if ( idCard . matches ( \"^[1|5|7][0-9]{6}\\\\(?[0-9A-Z]\\\\)?$\" ) ) { // 澳门 info [ 0 ] = \"澳门\";  info [ 1 ] = \"N\" ; // TODO } else if ( idCard . matches ( \"^[A-Z]{1,2}[0-9]{6}\\\\(?[0-9A]\\\\)?$\" ) ) { // 香港 info [ 0 ] = \"香港\";  info [ 1 ] = \"N\" ; info [ 2 ] = validateHKCard ( idCard ) ? \"true\" : \"false\" ; } else { return null ; } return info ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证台湾身份证号码 [CODESPLIT] public static boolean validateTWCard ( String idCard ) { String start = idCard . substring ( 0 , 1 ) ; String mid = idCard . substring ( 1 , 9 ) ; String end = idCard . substring ( 9 , 10 ) ; Integer iStart = twFirstCode . get ( start ) ; Integer sum = iStart / 10 + ( iStart % 10 ) * 9 ; char [ ] chars = mid . toCharArray ( ) ; Integer iflag = 8 ; for ( char c : chars ) { sum = sum + Integer . valueOf ( c + \"\" ) * iflag ; iflag -- ; } return ( sum % 10 == 0 ? 0 : ( 10 - sum % 10 ) ) == Integer . valueOf ( end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证香港身份证号码 ( 存在Bug，部份特殊身份证无法检查 ) <p > 身份证前2位为英文字符，如果只出现一个英文字符则表示第一位是空格，对应数字58 前2位英文字符A - Z分别对应数字10 - 35 最后一位校验码为0 - 9的数字加上字符 A ， A 代表10 < / p > <p > 将身份证号码全部转换为数字，分别对应乘9 - 1相加的总和，整除11则证件号码有效 < / p > [CODESPLIT] public static boolean validateHKCard ( String idCard ) { String card = idCard . replaceAll ( \"[\\\\(|\\\\)]\" , \"\" ) ; Integer sum ; if ( card . length ( ) == 9 ) { sum = ( ( int ) card . substring ( 0 , 1 ) . toUpperCase ( ) . toCharArray ( ) [ 0 ] - 55 ) * 9 + ( ( int ) card . substring ( 1 , 2 ) . toUpperCase ( ) . toCharArray ( ) [ 0 ] - 55 ) * 8 ; card = card . substring ( 1 , 9 ) ; } else { sum = 522 + ( ( int ) card . substring ( 0 , 1 ) . toUpperCase ( ) . toCharArray ( ) [ 0 ] - 55 ) * 8 ; } String mid = card . substring ( 1 , 7 ) ; String end = card . substring ( 7 , 8 ) ; char [ ] chars = mid . toCharArray ( ) ; Integer iflag = 7 ; for ( char c : chars ) { sum = sum + Integer . valueOf ( c + \"\" ) * iflag ; iflag -- ; } if ( end . toUpperCase ( ) . equals ( \"A\" ) ) { sum = sum + 10 ; } else { sum = sum + Integer . valueOf ( end ) ; } return ( sum % 11 == 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将字符数组转换成数字数组 [CODESPLIT] public static int [ ] converCharToInt ( char [ ] ca ) { int len = ca . length ; int [ ] iArr = new int [ len ] ; try { for ( int i = 0 ; i < len ; i ++ ) { iArr [ i ] = Integer . parseInt ( String . valueOf ( ca [ i ] ) ) ; } } catch ( NumberFormatException e ) { e . printStackTrace ( ) ; } return iArr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将身份证的每位和对应位的加权因子相乘之后，再得到和值 [CODESPLIT] public static int getPowerSum ( int [ ] iArr ) { int iSum = 0 ; if ( power . length == iArr . length ) { for ( int i = 0 ; i < iArr . length ; i ++ ) { for ( int j = 0 ; j < power . length ; j ++ ) { if ( i == j ) { iSum = iSum + iArr [ i ] * power [ j ] ; } } } } return iSum ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将power和值与11取模获得余数进行校验码判断 [CODESPLIT] public static String getCheckCode18 ( int iSum ) { String sCode = \"\" ; switch ( iSum % 11 ) { case 10 : sCode = \"2\" ; break ; case 9 : sCode = \"3\" ; break ; case 8 : sCode = \"4\" ; break ; case 7 : sCode = \"5\" ; break ; case 6 : sCode = \"6\" ; break ; case 5 : sCode = \"7\" ; break ; case 4 : sCode = \"8\" ; break ; case 3 : sCode = \"9\" ; break ; case 2 : sCode = \"x\" ; break ; case 1 : sCode = \"0\" ; break ; case 0 : sCode = \"1\" ; break ; } return sCode ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据身份编号获取年龄 [CODESPLIT] public static int getAgeByIdCard ( String idCard ) { int iAge ; if ( idCard . length ( ) == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } String year = idCard . substring ( 6 , 10 ) ; Calendar cal = Calendar . getInstance ( ) ; int iCurrYear = cal . get ( Calendar . YEAR ) ; iAge = iCurrYear - Integer . valueOf ( year ) ; return iAge ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据身份编号获取生日 [CODESPLIT] public static String getBirthByIdCard ( String idCard ) { Integer len = idCard . length ( ) ; if ( len < CHINA_ID_MIN_LENGTH ) { return null ; } else if ( len == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } return idCard . substring ( 6 , 14 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据身份编号获取生日年 [CODESPLIT] public static Short getYearByIdCard ( String idCard ) { Integer len = idCard . length ( ) ; if ( len < CHINA_ID_MIN_LENGTH ) { return null ; } else if ( len == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } return Short . valueOf ( idCard . substring ( 6 , 10 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据身份编号获取性别 [CODESPLIT] public static String getGenderByIdCard ( String idCard ) { String sGender = \"N\" ; if ( idCard . length ( ) == CHINA_ID_MIN_LENGTH ) { idCard = conver15CardTo18 ( idCard ) ; } String sCardNum = idCard . substring ( 16 , 17 ) ; if ( Integer . parseInt ( sCardNum ) % 2 != 0 ) { sGender = \"M\" ; } else { sGender = \"F\" ; } return sGender ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据身份编号获取户籍省份 [CODESPLIT] public static String getProvinceByIdCard ( String idCard ) { int len = idCard . length ( ) ; String sProvince ; String sProvinNum = \"\" ; if ( len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH ) { sProvinNum = idCard . substring ( 0 , 2 ) ; } sProvince = cityCodes . get ( sProvinNum ) ; return sProvince ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "验证小于当前日期 是否有效 [CODESPLIT] private static boolean valiDate ( int iYear , int iMonth , int iDate ) { Calendar cal = Calendar . getInstance ( ) ; int year = cal . get ( Calendar . YEAR ) ; int datePerMonth ; if ( iYear < MIN || iYear >= year ) { return false ; } if ( iMonth < 1 || iMonth > 12 ) { return false ; } switch ( iMonth ) { case 4 : case 6 : case 9 : case 11 : datePerMonth = 30 ; break ; case 2 : boolean dm = ( ( iYear % 4 == 0 && iYear % 100 != 0 ) || ( iYear % 400 == 0 ) ) && ( iYear > MIN && iYear < year ) ; datePerMonth = dm ? 29 : 28 ; break ; default : datePerMonth = 31 ; } return ( iDate >= 1 ) && ( iDate <= datePerMonth ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取得参数<code > params< / code > 中必须存在的指定Key的值，如果不存在，抛出异常 [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static String getRequiredParam ( Map params , String key ) throws TemplateException { Object value = params . get ( key ) ; if ( value == null || StringUtils . isEmpty ( value . toString ( ) ) ) { throw new TemplateModelException ( \"not found required parameter:\" + key + \" for directive\" ) ; } return value . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取得<code > params< / code > 中指定Key的值，如果不存在返回默认信息 [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public static String getParam ( Map params , String key , String defaultValue ) { Object value = params . get ( key ) ; return value == null ? defaultValue : value . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从Freemarker的运行环境中，取得指定名称的覆盖内容渲染器 [CODESPLIT] public static TemplateDirectiveBodyOverrideWraper getOverrideBody ( Environment env , String name ) throws TemplateModelException { return ( TemplateDirectiveBodyOverrideWraper ) env . getVariable ( DirectiveKit . getOverrideVariableName ( name ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "对指定的Body的渲染器，指定其父亲的内容区域 [CODESPLIT] public static void setTopBodyForParentBody ( TemplateDirectiveBodyOverrideWraper topBody , TemplateDirectiveBodyOverrideWraper overrideBody ) { TemplateDirectiveBodyOverrideWraper parent = overrideBody ; while ( parent . parentBody != null ) { parent = parent . parentBody ; } parent . parentBody = topBody ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes Web endpoint method . This method processes the request as the following steps : <ol > <li > Gets Web endpoint class by invoking { @code Method#getDeclaringClass () } of the Web endpoint method set on the current HTTP request processing context and instantiates it with the { @link Instantiator } that the { @link Configuration#instantiator () } returns . < / li > <li > Invokes Web endpoint method on the constructed instance with the parameters set on the current HTTP request processing context and sets the invocation result to the current HTTP request processing context . < / li > <li > If the invocation is failed with { @code WebException } this method sends HTTP response with the status code the exception has . < / li > <li > If the invocation is failed for any reasons this method sends HTTP response with the status code 500 ( INTERNAL_SERVER_ERROR ) . < / li > < / ol > [CODESPLIT] public boolean apply ( WebContext context ) { WebException e = null ; try { context . result ( new MethodInvocation < Object > ( context . method ( ) , instantiate ( context . method ( ) . getDeclaringClass ( ) ) , context . parameters ( ) . toArray ( ) ) . proceed ( ) ) ; return true ; } catch ( WebException exception ) { e = exception ; } catch ( Throwable throwable ) { e = new EndpointInvocationFailedException ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , throwable ) ; } logger . warn ( \"Failed to invoke Web endpoint\" , e ) ; try { context . response ( ) . sendError ( e . status ( ) ) ; return false ; } catch ( IOException exception ) { throw new UncheckedException ( exception ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a permission and message wrapper class { @link PermBean } with desired permission / s and respective messages . [CODESPLIT] public RequestPermission with ( PermBean permBean ) { if ( permBean . getPermissions ( ) . isEmpty ( ) ) { throw new NullPointerException ( \"Permission and Message collection cannot be null !\" ) ; } RequestPermission . permBean = permBean ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Execute request for all provided permissions . It checks if permissions are already granted or required to grant . < / p > <p > Only if only API is greater than 23 ( i . e . Marshmallows or later ) . < / p > [CODESPLIT] public void request ( ) { mLog . i ( TAG , \"Requesting.........\" ) ; resultMap = new LinkedHashMap <> ( permBean . size ( ) ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M && isPermissionRequired ( permBean ) ) { // if result target is not set use activity as default. if ( RequestPermission . mBase == null ) { RequestPermission . mBase = mActivity ; } mLog . i ( TAG , \"On permission result \" + mBase . getClass ( ) . getSimpleName ( ) + \" class methods will be executed.\" ) ; PermBean bean = new PermBean ( ) ; Map < Permission , String > map = permBean . getPermissions ( ) ; for ( Map . Entry < Permission , String > m : map . entrySet ( ) ) { if ( mActivity . checkSelfPermission ( m . getKey ( ) . toString ( ) ) != PackageManager . PERMISSION_GRANTED ) { bean . put ( m . getKey ( ) , m . getValue ( ) ) ; mLog . i ( TAG , m . getKey ( ) . name ( ) + \" requires permission\" ) ; } else { resultMap . put ( m . getKey ( ) , Result . GRANTED ) ; } } // ask permissions for granted methods. if ( bean . size ( ) > 0 ) { showDialog ( bean ) ; } } else { for ( Map . Entry < Permission , String > m : permBean . getPermissions ( ) . entrySet ( ) ) { resultMap . put ( m . getKey ( ) , Result . GRANTED ) ; } try { invokeAnnotatedMethods ( resultMap ) ; } catch ( InvocationTargetException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } mLog . i ( TAG , \"request: Redundant\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Check weather single or multiple permissions requires grant . < / p > Use instead { @link RequestPermission#request () } directly . [CODESPLIT] private static boolean isPermissionRequired ( PermBean permBean ) { if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . M ) { return false ; } if ( permBean . size ( ) > 0 ) { Map < Permission , String > map = permBean . getPermissions ( ) ; for ( Permission permission : map . keySet ( ) ) { int status = mActivity . checkSelfPermission ( permission . toString ( ) ) ; if ( status != PackageManager . PERMISSION_GRANTED ) return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Show dialog fragment to show dialogs before asking permission . Or you can set to show dialogs only when user denied permission earlier . [CODESPLIT] private void showDialog ( PermBean permBean ) { PermissionDialogFragment fragment = PermissionDialogFragment . getInstance ( permBean , requestCode ) ; fragment . show ( mActivity . getSupportFragmentManager ( ) , TAG ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get on Request Permissions Results invoke annotated methods and send a local broadcast of results . [CODESPLIT] public static void onResult ( int requestCode , @ NonNull String [ ] permissions , @ NonNull int [ ] grantResults ) { if ( RequestPermission . requestCode == requestCode ) { /* Sort granted and denied permissions in array list */ int count = permissions . length ; List < String > granted = new ArrayList <> ( count ) ; List < String > denied = new ArrayList <> ( count ) ; for ( int k = 0 ; k < count ; k ++ ) { resultMap . put ( Permission . get ( permissions [ k ] ) , Result . get ( grantResults [ k ] ) ) ; if ( grantResults [ k ] == PackageManager . PERMISSION_GRANTED ) { granted . add ( permissions [ k ] ) ; } else if ( grantResults [ k ] == PackageManager . PERMISSION_DENIED ) { denied . add ( permissions [ k ] ) ; } } String [ ] grantedArray = granted . toArray ( new String [ granted . size ( ) ] ) ; String [ ] deniedArray = denied . toArray ( new String [ denied . size ( ) ] ) ; // forward to invoke annotated methods. try { invokeAnnotatedMethods ( resultMap ) ; } catch ( IllegalAccessException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { mLog . e ( TAG , e . getMessage ( ) , e ) ; } /* Send local broadcast on permissions result. */ Intent intent = new Intent ( PERMISSION_RESULT_BROADCAST ) ; intent . putExtra ( GRANTED , grantedArray ) ; intent . putExtra ( DENIED , deniedArray ) ; LocalBroadcastManager . getInstance ( mActivity ) . sendBroadcast ( intent ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoke annotated methods in provided class . [CODESPLIT] private static void invokeAnnotatedMethods ( HashMap < Permission , Result > resultMap ) throws InvocationTargetException , IllegalAccessException { Method [ ] methods = getBase ( ) . getClass ( ) . getDeclaredMethods ( ) ; // check all methods from provided class or by default provided activity. for ( Method method : methods ) { if ( method != null && method . isAnnotationPresent ( GrantedPermission . class ) ) { GrantedPermission granted = method . getAnnotation ( GrantedPermission . class ) ; if ( granted != null ) { /* Check single value annotations */ if ( ! granted . permission ( ) . equals ( \"\" ) || granted . value ( ) != Permission . NONE ) { for ( Map . Entry < Permission , Result > permResult : resultMap . entrySet ( ) ) { // invoke method if String permission is annotated. if ( ( granted . permission ( ) . equals ( permResult . getKey ( ) . toString ( ) ) || granted . value ( ) == permResult . getKey ( ) ) && Result . GRANTED == permResult . getValue ( ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , \"invoking grant method: \" + method . getName ( ) ) ; } } continue ; } /* Check array fields in annotations */ if ( granted . values ( ) . length > 0 ) { if ( allValuesGranted ( granted . values ( ) , resultMap ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , \"invoking grant method: \" + method . getName ( ) ) ; } continue ; } if ( granted . permissions ( ) . length > 0 ) { if ( allValuesGranted ( granted . permissions ( ) , resultMap ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , \"invoking grant method: \" + method . getName ( ) ) ; } } } } else if ( method != null && method . isAnnotationPresent ( DeniedPermission . class ) ) { DeniedPermission denied = method . getAnnotation ( DeniedPermission . class ) ; if ( denied != null ) { /* Check single value annotations */ if ( ! denied . permission ( ) . equals ( \"\" ) || denied . value ( ) != Permission . NONE ) { for ( Map . Entry < Permission , Result > permResult : resultMap . entrySet ( ) ) { // invoke method if String permission is annotated. if ( ( denied . permission ( ) . equals ( permResult . getKey ( ) . toString ( ) ) || denied . value ( ) == permResult . getKey ( ) ) && Result . DENIED == permResult . getValue ( ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , \"invoking denied method: \" + method . getName ( ) ) ; } } continue ; } /* Check array fields in annotations */ if ( denied . values ( ) . length > 0 ) { if ( anyValueDenied ( denied . values ( ) , resultMap ) ) { method . invoke ( getBase ( ) ) ; mLog . i ( TAG , \"invoking denied method: \" + method . getName ( ) ) ; } continue ; } if ( denied . permissions ( ) . length > 0 ) { if ( anyValueDenied ( denied . permissions ( ) , resultMap ) ) { mLog . i ( TAG , \"invoking denied method: \" + method . getName ( ) ) ; method . invoke ( getBase ( ) ) ; } } } } else if ( method != null && method . isAnnotationPresent ( OPermission . class ) ) { OPermission oPermission = method . getAnnotation ( OPermission . class ) ; final Annotation [ ] [ ] paramAnnotations = method . getParameterAnnotations ( ) ; final Class [ ] paramTypes = method . getParameterTypes ( ) ; if ( oPermission != null && paramAnnotations [ 0 ] [ 0 ] instanceof co . omkar . utility . opermission . annotation . Result && ( paramTypes [ 0 ] == boolean . class || paramTypes [ 0 ] == Boolean . class ) ) { /* Check single value annotations */ for ( Map . Entry < Permission , Result > permResult : resultMap . entrySet ( ) ) { // invoke method if String permission is annotated. if ( oPermission . permission ( ) . equals ( permResult . getKey ( ) . toString ( ) ) || oPermission . value ( ) . equals ( permResult . getKey ( ) ) ) { switch ( permResult . getValue ( ) ) { // Permission is granted. case GRANTED : method . invoke ( getBase ( ) , true ) ; mLog . i ( TAG , \"invoking method: \" + method . getName ( ) ) ; break ; // Permission is denied. case DENIED : method . invoke ( getBase ( ) , false ) ; mLog . i ( TAG , \"invoking method: \" + method . getName ( ) ) ; break ; } } } /* Check array fields in annotations */ if ( oPermission . values ( ) . length > 0 ) { if ( allValuesGranted ( oPermission . values ( ) , resultMap ) ) { method . invoke ( getBase ( ) , true ) ; mLog . i ( TAG , \"invoking as granted method: \" + method . getName ( ) ) ; } else { method . invoke ( getBase ( ) , false ) ; mLog . i ( TAG , \"invoking as denied method: \" + method . getName ( ) ) ; } continue ; } if ( oPermission . permissions ( ) . length > 0 ) { if ( allValuesGranted ( oPermission . permissions ( ) , resultMap ) ) { method . invoke ( getBase ( ) , true ) ; mLog . i ( TAG , \"invoking as granted method: \" + method . getName ( ) ) ; } else { method . invoke ( getBase ( ) , false ) ; mLog . i ( TAG , \"invoking as denied method: \" + method . getName ( ) ) ; } } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if annotated result permissions contains all values from annotated array . Then it also check if all permissions in annotated method value array are granted . [CODESPLIT] private static boolean allValuesGranted ( Object [ ] values , HashMap < Permission , Result > resultMap ) { if ( values instanceof Permission [ ] ) { Set < Permission > valueSet = new HashSet <> ( Arrays . asList ( ( Permission [ ] ) values ) ) ; if ( resultMap . keySet ( ) . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . GRANTED != resultMap . get ( ( Permission ) value ) ) { mLog . i ( TAG , \"denied - \" + value . toString ( ) ) ; return false ; } } return true ; } } else if ( values instanceof String [ ] ) { Set < String > valueSet = new HashSet <> ( Arrays . asList ( ( String [ ] ) values ) ) ; Set < String > permission = new HashSet <> ( ) ; for ( Permission perm : resultMap . keySet ( ) ) { permission . add ( perm . toString ( ) ) ; } if ( permission . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . GRANTED != resultMap . get ( Permission . get ( String . valueOf ( value ) ) ) ) { mLog . i ( TAG , \"denied - \" + value ) ; return false ; } } return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check if annotated result permissions contains all values from annotated array . Then it also check if any permission in annotated method value array is denied . [CODESPLIT] private static boolean anyValueDenied ( Object [ ] values , HashMap < Permission , Result > resultMap ) { if ( values instanceof Permission [ ] ) { Set < Permission > valueSet = new LinkedHashSet <> ( Arrays . asList ( ( Permission [ ] ) values ) ) ; if ( resultMap . keySet ( ) . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . DENIED == resultMap . get ( ( Permission ) value ) ) { mLog . i ( TAG , \"denied - \" + value . toString ( ) ) ; return true ; } } } } else if ( values instanceof String [ ] ) { Set < String > valueSet = new HashSet <> ( Arrays . asList ( ( String [ ] ) values ) ) ; Set < String > permissionSet = new HashSet <> ( ) ; for ( Permission perm : resultMap . keySet ( ) ) { permissionSet . add ( perm . toString ( ) ) ; } if ( permissionSet . containsAll ( valueSet ) ) { for ( Object value : values ) { if ( Result . DENIED == resultMap . get ( Permission . get ( ( String ) value ) ) ) { mLog . i ( TAG , \"denied - \" + value ) ; return true ; } } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates an instance of an interface which is supposed to handle method calls in the proxy . [CODESPLIT] @ Nonnull private MethodInvocationHandler getMethodInvocationHandler ( @ Nonnull Method method , @ Nonnull final Class < ? > clazz , @ Nonnull String serviceBaseUrl ) { // toString+hashCode+equals if ( method . getName ( ) . equals ( \"toString\" ) && method . getParameterTypes ( ) . length == 0 ) { return ( proxy , method1 , args ) -> clazz . getSimpleName ( ) ; } else if ( method . getName ( ) . equals ( \"hashCode\" ) && method . getParameterTypes ( ) . length == 0 ) { return new MethodInvocationHandler ( ) { @ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return this . hashCode ( ) ; } } ; } else if ( method . getName ( ) . equals ( \"equals\" ) && method . getParameterTypes ( ) . length == 1 && method . getParameterTypes ( ) [ 0 ] == Object . class ) { return ( proxy , method12 , args ) -> proxy == args [ 0 ] ; } return createRequestMappingHandler ( method , serviceBaseUrl ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取SQL，动态SQL [CODESPLIT] public static Pair < String , List < Object > > dynamicSql ( String sqlId , Map < String , Object > param ) { String sqlTemplete = SqlKit . sql ( sqlId ) ; if ( null == sqlTemplete || sqlTemplete . isEmpty ( ) ) { logger . error ( \"sql语句不存在：sql id是\" + sqlId);     return null ; } if ( param == null ) { param = Maps . newHashMap ( ) ; } String sql = Freemarkers . render ( sqlTemplete , param ) ; List < Object > params = Lists . newArrayList ( ) ; Set < String > keySet = param . keySet ( ) ; for ( String key : keySet ) { if ( param . get ( key ) == null ) { break ; } Object paramValue = param . get ( key ) ; final String placeChar = StringPool . HASH + key + StringPool . HASH ; if ( StringUtils . containsIgnoreCase ( sql , placeChar ) ) { sql = StringUtils . replace ( sql , placeChar , StringPool . QUESTION_MARK ) ; params . add ( paramValue ) ; } } return Pair . of ( sql . replaceAll ( \"[\\\\s]{2,}\" , \" \" ) , params ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "According to the default primary key <code > id< / code > is for the new data and entity . [CODESPLIT] public static < M extends Model > boolean isNew ( M m ) { final Table table = TableMapping . me ( ) . getTable ( m . getClass ( ) ) ; final String [ ] pks = table . getPrimaryKey ( ) ; return isNew ( m , pks [ 0 ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query the database record set . [CODESPLIT] public static List < Record > findBy ( SqlSelect sqlSelect ) { Preconditions . checkNotNull ( sqlSelect , \"The Query SqlNode is must be not null.\" ) ; return Db . find ( sqlSelect . toString ( ) , sqlSelect . getParams ( ) . toArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Query a data record . [CODESPLIT] public static Record findOne ( SqlSelect sqlSelect ) { Preconditions . checkNotNull ( sqlSelect , \"The Query SqlNode is must be not null.\" ) ; return Db . findFirst ( sqlSelect . toString ( ) , sqlSelect . getParams ( ) . toArray ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据多个数据通过主键批量删除数据 [CODESPLIT] public static < M extends Model > boolean deleteByIds ( Serializable [ ] ids , Class < M > modelClass ) { final Table table = TableMapping . me ( ) . getTable ( modelClass ) ; final String [ ] primaryKey = table . getPrimaryKey ( ) ; if ( primaryKey == null || primaryKey . length < 1 || ids == null ) { throw new IllegalArgumentException ( \"需要删除的表数据主键不存在，无法删除!\");   } // 暂时支持单主键的，多主键的后续在说吧。 final String question_mark = StringUtils . repeat ( StringPool . QUESTION_MARK , StringPool . COMMA , ids . length ) ; String deleteSql = \"DELETE FROM \" + table . getName ( ) + \" WHERE \" + primaryKey [ 0 ] + \" IN (\" + question_mark + \")\" ; return Db . update ( deleteSql , ids ) >= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "According to the primary key and entity determine whether for the new entity . [CODESPLIT] public static < M extends Model > boolean isNew ( M m , String pk_column ) { final Object val = m . get ( pk_column ) ; return val == null || val instanceof Number && ( ( Number ) val ) . intValue ( ) <= 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Paging retrieve default sorted by id you need to specify the datatables request parameters . [CODESPLIT] public static Page < Record > paginate ( String sqlPaginatePrefix , PageDto pageDto ) { SqlNode sqlNode = SqlKit . sqlNode ( sqlPaginatePrefix + \".paginate\" ) ; Preconditions . checkNotNull ( sqlNode , \"[\" + sqlPaginatePrefix + \".paginate]分页Sql不存在,无法执行分页\");   String where = sqlNode . whereSql ; int pageSize = pageDto . pageSize ; int p = pageDto . page ; int start = ( ( p - 1 ) * pageSize ) + 1 ; final List < RequestParam > params = pageDto . params ; final List < Object > query_params = pageDto . query_params ; if ( ( params . isEmpty ( ) ) && ( query_params . isEmpty ( ) ) ) { return Db . paginate ( start , pageSize , sqlNode . selectSql , where ) ; } else { if ( ! params . isEmpty ( ) ) { where += ( sqlNode . condition ? StringPool . SPACE : \" WHERE 1=1 \" ) ; } for ( RequestParam param : pageDto . params ) { where += param . toSql ( ) ; } return Db . paginate ( start , pageSize , sqlNode . selectSql , where , query_params . toArray ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "取得系统的运行模式 [CODESPLIT] private static ApplicationMode getApplicationModel ( ) { final String mode = getProperty ( GojaPropConst . APPMODE , \"dev\" ) . toUpperCase ( ) ; return ApplicationMode . valueOf ( mode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether the given method explicitly declares the given exception or one of its superclasses which means that an exception of that type can be propagated as - is within a reflective invocation . [CODESPLIT] public static boolean declaresException ( Method method , Class < ? > exceptionType ) { Preconditions . checkNotNull ( method , \"Method must not be null\" ) ; Class < ? > [ ] declaredExceptions = method . getExceptionTypes ( ) ; for ( Class < ? > declaredException : declaredExceptions ) { if ( declaredException . isAssignableFrom ( exceptionType ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Traverses the ReferenceQueue and removes garbage - collected SoftValue objects from the backing map by looking them up using the SoftValue . key data member . [CODESPLIT] private void processQueue ( ) { SoftValue < ? , ? > sv ; while ( ( sv = ( SoftValue < ? , ? > ) queue . poll ( ) ) != null ) { //noinspection SuspiciousMethodCalls map . remove ( sv . key ) ; // we can access private data! } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new entry but wraps the value in a SoftValue instance to enable auto garbage collection . [CODESPLIT] @ Override public V put ( K key , V value ) { processQueue ( ) ; // throw out garbage collected values first SoftValue < V , K > sv = new SoftValue < V , K > ( value , key , queue ) ; SoftValue < V , K > previous = map . put ( key , sv ) ; addToStrongReferences ( value ) ; return previous != null ? previous . get ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @code LoginException } with a cause . [CODESPLIT] public static LoginException newLoginException ( final String message , final Throwable cause ) { Validate . notBlank ( message , \"The validated character sequence 'message' is null or empty\" ) ; Validate . notNull ( cause , \"The validated object 'cause' is null\" ) ; final LoginException loginException = new LoginException ( message ) ; loginException . initCause ( cause ) ; return loginException ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用 ASM 获取参数名称 [CODESPLIT] private static void receiveParameterNames ( final KlassInfo declaringklass ) { if ( declaringklass . getType ( ) . getClassLoader ( ) == null ) { // We can not find parameter name for class which is in JDK return ; } ClassReader cr = null ; try { InputStream stream = ClassLoaderUtils . getClassAsStream ( declaringklass . getType ( ) ) ; cr = new ClassReader ( stream ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } cr . accept ( new ClassVisitor ( Opcodes . ASM5 ) { @ Override public MethodVisitor visitMethod ( final int access , final String name , final String desc , final String signature , final String [ ] exceptions ) { final MethodInfo method = searchMethod ( declaringklass , name , desc ) ; if ( method == null ) { return super . visitMethod ( access , name , desc , signature , exceptions ) ; } MethodVisitor mv = super . visitMethod ( access , name , desc , signature , exceptions ) ; return new MethodVisitor ( Opcodes . ASM5 , mv ) { List < ParameterInfo > parameters = method . getParameters ( ) ; boolean isStatic = method . isStatic ( ) ; @ Override public void visitLocalVariable ( String name , String desc , String signature , Label start , Label end , int index ) { int offset = isStatic ? index : index - 1 ; if ( offset >= 0 && offset < parameters . size ( ) ) { parameters . get ( offset ) . name = name ; } super . visitLocalVariable ( name , desc , signature , start , end , index ) ; } int visitParameterIndex = 0 ; // JDK8 parameter name 是按照循序存储的，这里需要一个计数器 @ Override public void visitParameter ( String name , int access ) { parameters . get ( visitParameterIndex ++ ) . name = name ; super . visitParameter ( name , access ) ; } } ; } private MethodInfo searchMethod ( KlassInfo declaringklass , String name , String desc ) { if ( \"<cinit>\" . equals ( name ) ) return null ; if ( \"<init>\" . equals ( name ) ) return null ; jetbrick . asm . Type [ ] argumentTypes = jetbrick . asm . Type . getArgumentTypes ( desc ) ; for ( MethodInfo method : declaringklass . getDeclaredMethods ( ) ) { if ( method . getName ( ) . equals ( name ) && argumentTypes . length == method . getParameterCount ( ) ) { Class < ? > [ ] types = method . getParameterTypes ( ) ; boolean matched = true ; for ( int i = 0 ; i < argumentTypes . length ; i ++ ) { if ( ! jetbrick . asm . Type . getType ( types [ i ] ) . equals ( argumentTypes [ i ] ) ) { matched = false ; break ; } } if ( matched ) { return method ; } } } return null ; } } , ClassReader . SKIP_FRAMES ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > It prepares database after import . < / p > [CODESPLIT] @ Override public final void make ( final Map < String , Object > pAddParams ) throws Exception { this . factoryAppBeans . releaseBeans ( ) ; Writer htmlWriter = ( Writer ) pAddParams . get ( \"htmlWriter\" ) ; if ( htmlWriter != null ) { htmlWriter . write ( \"<h4>\" + new Date ( ) . toString ( ) + \", \" + PrepareDbAfterGetCopy . class . getSimpleName ( ) + \", app-factory beans has released\" + \"</h4>\" ) ; } this . logger . info ( null , PrepareDbAfterGetCopy . class , \"app-factory beans has released\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether a string matches a given wildcard pattern . [CODESPLIT] public static boolean match ( String string , String pattern ) { if ( string . equals ( pattern ) ) { // speed-up return true ; } return match ( string , pattern , 0 , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Constructor . [CODESPLIT] public void init ( String title ) { super . init ( title ) ; Container contentPane = this . getContentPane ( ) ; contentPane . setLayout ( new BorderLayout ( ) ) ; m_properties = AppUtilities . readProperties ( m_strFileName = System . getProperty ( PROPERTY_FILENAME_PARAM , DEFAULT_PROPERTY_FILENAME ) ) ; JPanel panel = this . getPropertyView ( m_properties ) ; contentPane . add ( panel , BorderLayout . CENTER ) ; JPanel panelButtons = new JPanel ( ) ; contentPane . add ( panelButtons , BorderLayout . SOUTH ) ; panelButtons . setLayout ( new BorderLayout ( ) ) ; panelButtons . add ( m_buttonGo = new JButton ( \"GO!\" ) , BorderLayout . EAST ) ; m_buttonGo . addActionListener ( this ) ; panelButtons . add ( progressBar = new JProgressBar ( 0 , 1 ) , BorderLayout . CENTER ) ; panelButtons . add ( m_buttonSave = new JButton ( \"Save\" ) , BorderLayout . WEST ) ; m_buttonSave . addActionListener ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Main method . [CODESPLIT] public static void main ( String [ ] args ) { try { JBackup applet = new JBackup ( \"JBackup\" ) ; if ( ! Boolean . TRUE . toString ( ) . equalsIgnoreCase ( System . getProperty ( PROPERTY_QUIET_PARAM ) ) ) { JFrame frame = applet . addAppToFrame ( ) ; frame . setVisible ( true ) ; } else { Scanner scanner = new Scanner ( applet . m_properties ) ; scanner . run ( ) ; AppUtilities . writeProperties ( applet . m_strFileName , applet . m_properties ) ; System . exit ( 0 ) ; } } catch ( Throwable t ) { System . out . println ( \"uncaught exception: \" + t ) ; t . printStackTrace ( ) ; } //+\t\tSystem.exit(0); }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * User pressed a button . [CODESPLIT] public void actionPerformed ( ActionEvent e ) { if ( e . getSource ( ) == m_buttonGo ) { Scanner scanner = new Scanner ( m_properties ) ; // Fit them on floppys progressBar . setIndeterminate ( true ) ; // For now scanner . run ( ) ; progressBar . setIndeterminate ( false ) ; AppUtilities . writeProperties ( m_strFileName , m_properties ) ; } if ( e . getSource ( ) == m_buttonSave ) { AppUtilities . writeProperties ( m_strFileName , m_properties ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------- register / lookup ----------------------------------------------------------- [CODESPLIT] @ SuppressWarnings ( \"rawtypes\" ) public < T > void register ( Class < ? > type , Convertor < ? > convertor ) { pool . put ( type , convertor ) ; if ( type . isPrimitive ( ) ) { primitiveArrayPool . put ( type , new PrimitiveArrayConvertor ( type ) ) ; } else { objectArrayPool . put ( type , new ArrayConvertor ( type , convertor ) ) ; listPool . put ( type , new ListConvertor ( type , convertor ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "-------- convert string ----------------------------------------------------------- [CODESPLIT] public < T > T convert ( String value , Class < T > type ) { // fast-path if ( value == null ) { return null ; } if ( type == String . class ) { return ( T ) value ; } // normal-path Convertor < T > c = ( Convertor < T > ) pool . get ( type ) ; if ( c != null ) { return c . convert ( value ) ; } if ( type . isArray ( ) ) { return ( T ) convertToArray ( value , type . getComponentType ( ) ) ; } throw new IllegalStateException ( \"Unsupported cast class: \" + type . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strPathname = m_tfRootPathname . getText ( ) ; m_properties . setProperty ( DEST_ROOT_PATHNAME_PARAM , strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strPathname = m_properties . getProperty ( DEST_ROOT_PATHNAME_PARAM ) ; m_tfRootPathname . setText ( strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This methods uses <code > AnnotatedInterfaceArguments< / code > to return an instance of the specified class with methods returning values from the arguments of this Handler . [CODESPLIT] public < I > I getInstance ( Class < I > interfaceClass ) throws InvalidArgumentsException { I instance ; instance = AnnotatedInterfaceArguments . getInstance ( interfaceClass , this ) . getValueObject ( ) ; return instance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an instance of A if the arguments could be correctly parsed and A was not a subclass of ArgumentsWithHelp or no help was requested null otherwise . [CODESPLIT] public static < A > A readArguments ( Class < A > interfaceClass , String [ ] args ) { A result = null ; try { final ArgumentHandler argumentHandler = new ArgumentHandler ( args ) ; result = argumentHandler . getInstance ( interfaceClass ) ; argumentHandler . processArguments ( new ArgumentProcessor ( ) { @ Override public void process ( List < String > remaining ) throws InvalidArgumentsException { if ( remaining . size ( ) > 0 ) { throw new InvalidArgumentsException ( \"The following arguments could not be understood: \" + remaining ) ; } } } ) ; } catch ( InvalidArgumentsException e ) { System . out . println ( e . getMessage ( ) ) ; showUsage ( interfaceClass ) ; result = null ; } if ( result instanceof ArgumentsWithHelp ) { if ( ( ( ArgumentsWithHelp ) result ) . getHelp ( ) ) { showUsage ( interfaceClass ) ; result = null ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public int read ( ) throws IOException { if ( currentReader == null ) { try { getNextReader ( ) ; } catch ( StreamFinishedException e ) { return - 1 ; } } int result = currentReader . read ( ) ; while ( result == - 1 ) { try { getNextReader ( ) ; } catch ( StreamFinishedException e ) { return - 1 ; } result = currentReader . read ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public V put ( K key , V value ) { //remove possible existing with same value if ( backward . containsKey ( value ) ) { K oldKey = backward . get ( value ) ; forward . remove ( oldKey ) ; } if ( forward . containsKey ( key ) ) { V oldValue = forward . get ( key ) ; backward . remove ( oldValue ) ; } backward . put ( value , key ) ; return forward . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public V remove ( Object key ) { V value = forward . remove ( key ) ; backward . remove ( value ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the ProtobufClass based on the POJO value . The returned value may get converted as the Protobuf builders / setters use primitives . For example if user has declared <code > Integer< / code > this get s converted to <code > int< / code > . [CODESPLIT] public static final Class < ? extends Object > getProtobufClass ( Object value , Class < ? extends Object > protobufClass ) { if ( value instanceof Integer ) { return Integer . TYPE ; } if ( value instanceof Boolean ) { return Boolean . TYPE ; } if ( value instanceof Double ) { return Double . TYPE ; } if ( value instanceof Long || value instanceof Date ) { return Long . TYPE ; } if ( value instanceof List ) { return Iterable . class ; } return protobufClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a ProtobufEntity annotation from any object sent null if there is none . [CODESPLIT] public static final ProtobufEntity getProtobufEntity ( Class < ? > clazz ) { final ProtobufEntity protoBufEntity = clazz . getAnnotation ( ProtobufEntity . class ) ; if ( protoBufEntity != null ) { return protoBufEntity ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if there is a ProtobufEntity annotation on this class . [CODESPLIT] public static final boolean isProtbufEntity ( Class < ? > clazz ) { final ProtobufEntity protoBufEntity = getProtobufEntity ( clazz ) ; if ( protoBufEntity != null ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the Protobuf Class based on the pojo class i . e . grab the value from the ProtobufEntity annotation . [CODESPLIT] public static final Class < ? extends GeneratedMessage > getProtobufClassFromPojoAnno ( Class < ? > clazz ) { final ProtobufEntity annotation = getProtobufEntity ( clazz ) ; final Class < ? extends GeneratedMessage > gpbClazz = ( Class < ? extends GeneratedMessage > ) annotation . value ( ) ; if ( gpbClazz == null ) { return null ; } return gpbClazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a full mapping of all Protobuf fields from the POJO class . Essentially the only fields that will be returned if they have the ProtobufAttribute annotation . [CODESPLIT] public static final Map < Field , ProtobufAttribute > getAllProtbufFields ( Class < ? extends Object > fromClazz ) { Map < Field , ProtobufAttribute > protoBufFields = CLASS_TO_FIELD_MAP_CACHE . get ( fromClazz . getCanonicalName ( ) ) ; if ( protoBufFields != null ) { return protoBufFields ; } else { protoBufFields = new HashMap <> ( ) ; } final List < Field > fields = JReflectionUtils . getAllFields ( new ArrayList < Field > ( ) , fromClazz ) ; for ( Field field : fields ) { final Annotation annotation = field . getAnnotation ( ProtobufAttribute . class ) ; if ( annotation == null ) { continue ; } final ProtobufAttribute gpbAnnotation = ( ProtobufAttribute ) annotation ; protoBufFields . put ( field , gpbAnnotation ) ; } // Caching to increase speed CLASS_TO_FIELD_MAP_CACHE . put ( fromClazz . getCanonicalName ( ) , protoBufFields ) ; return protoBufFields ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the setter for the Protobuf builder . <br > 1 . Defaults to just set + upper case the first character of the fieldName . 2 . If it s a collection use the addAll type method Protobuf has 3 . Otherwise use the override value from the user s ProtobufAttribute annotation <br > [CODESPLIT] public static final String getProtobufSetter ( ProtobufAttribute protobufAttribute , Field field , Object fieldValue ) { final String fieldName = field . getName ( ) ; final String upperClassName = field . getDeclaringClass ( ) . getCanonicalName ( ) ; // Look at the cache first Map < String , String > map = CLASS_TO_FIELD_SETTERS_MAP_CACHE . get ( upperClassName ) ; if ( map != null ) { if ( ! map . isEmpty ( ) && map . containsKey ( fieldName ) ) { return map . get ( fieldName ) ; } } else { map = new ConcurrentHashMap <> ( ) ; } String setter = \"set\" + JStringUtils . upperCaseFirst ( fieldName ) ; if ( fieldValue instanceof Collection ) { setter = \"addAll\" + JStringUtils . upperCaseFirst ( fieldName ) ; } // Finally override setter with a value that is configured in ProtobufAttribute annotation final String configedSetter = protobufAttribute . protobufSetter ( ) ; if ( ! configedSetter . equals ( JStringUtils . EMPTY ) ) { setter = configedSetter ; } map . put ( fieldName , setter ) ; CLASS_TO_FIELD_SETTERS_MAP_CACHE . put ( upperClassName , map ) ; return setter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the getter against the Protobuf class ; default is to is get plus upper case first character of the field name . [CODESPLIT] public static final String getProtobufGetter ( ProtobufAttribute protobufAttribute , Field field ) { final String fieldName = field . getName ( ) ; final String upperClassName = field . getDeclaringClass ( ) . getCanonicalName ( ) ; // Look at the cache first Map < String , String > map = CLASS_TO_FIELD_GETTERS_MAP_CACHE . get ( upperClassName ) ; if ( map != null ) { if ( ! map . isEmpty ( ) && map . containsKey ( fieldName ) ) { return map . get ( fieldName ) ; } } else { map = new ConcurrentHashMap <> ( ) ; } final String upperCaseFirstFieldName = JStringUtils . upperCaseFirst ( field . getName ( ) ) ; String getter = \"get\" + upperCaseFirstFieldName ; if ( Collection . class . isAssignableFrom ( field . getType ( ) ) ) { getter += \"List\" ; } if ( ! protobufAttribute . protobufGetter ( ) . isEmpty ( ) ) { return protobufAttribute . protobufGetter ( ) ; } map . put ( fieldName , getter ) ; CLASS_TO_FIELD_GETTERS_MAP_CACHE . put ( upperClassName , map ) ; return getter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the setter on the POJO class ; default is to is set plus upper case first character of the field name . [CODESPLIT] public static final String getPojoSetter ( ProtobufAttribute protobufAttribute , Field field ) { final String fieldName = field . getName ( ) ; final String upperClassName = field . getDeclaringClass ( ) . getCanonicalName ( ) ; // Look at the cache first Map < String , String > map = CLASS_TO_FIELD_SETTERS_MAP_CACHE . get ( upperClassName ) ; if ( map != null ) { if ( ! map . isEmpty ( ) && map . containsKey ( fieldName ) ) { return map . get ( fieldName ) ; } } else { map = new ConcurrentHashMap <> ( ) ; } final String upperCaseFirstFieldName = JStringUtils . upperCaseFirst ( field . getName ( ) ) ; String setter = \"set\" + upperCaseFirstFieldName ; if ( ! protobufAttribute . pojoSetter ( ) . isEmpty ( ) ) { return protobufAttribute . pojoSetter ( ) ; } map . put ( fieldName , setter ) ; CLASS_TO_FIELD_SETTERS_MAP_CACHE . put ( upperClassName , map ) ; return setter ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a singleton fully initialized instance of a { @link PasswordValidator } class to use for JAAS authentication . <p > Retrieving a singleton by this method will cause the factory to keep state and store a reference to the singleton for later use . You may reset the factory state using the { @code reset () } method to retrieve a new / different singleton the next time this method is called .. <p > Note that any properties of the singleton ( e . g . configuration ) cannot necessarily be changed easily . You may call the singleton s { @code init () } method but depending on the implementation provided by the respective class this may or may not have the expected effect . <p > If you need tight control over the singleton including its lifecycle and configuration or you require more than one singleton that are different in their internal state ( e . g . with different configurations ) then you should create such objects with the { @code getInstance () } method and maintain their state as singletons in your application s business logic . <p > Classes implementing the { @link PasswordValidator } interface <b > must< / b > be thread safe . [CODESPLIT] @ SuppressWarnings ( \"PMD.NonThreadSafeSingleton\" ) public static PasswordValidator getSingleton ( final String className , final CommonProperties properties ) throws FactoryException { Validate . notBlank ( className , \"The validated character sequence 'className' is null or empty\" ) ; Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; if ( passwordValidatorInstance == null ) { synchronized ( PasswordValidatorFactory . class ) { if ( passwordValidatorInstance == null ) { passwordValidatorInstance = getInstance ( className , properties ) ; } } } return passwordValidatorInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Filter that make SQL WHERE filter for entities with <b > itsVersion< / b > and <b > changed time< / b > algorithm . < / p > [CODESPLIT] @ Override public final String makeFilter ( final Class < ? > pEntityClass , final Map < String , Object > pAddParam ) throws Exception { return pEntityClass . getSimpleName ( ) . toUpperCase ( ) + \".ITSVERSION>\" + this . lastReplicatedDateEvaluator . evalData ( pAddParam ) . getTime ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strPathname = m_tfRootPathname . getText ( ) ; m_properties . setProperty ( BASE_URL_PARAM , strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strPathname = m_properties . getProperty ( BASE_URL_PARAM ) ; m_tfRootPathname . setText ( strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到字符串对应的拼音 ( 默认小写 不带声调 ) 不可识别的字符原样返回 . [CODESPLIT] public String getFullPinyin ( String str ) { if ( str == null ) return null ; StringBuffer sb = new StringBuffer ( ) ; String [ ] item = null ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str . charAt ( i ) ; item = getPinyinFromChar ( ch ) ; if ( item == null ) { sb . append ( ch ) ; } else { sb . append ( item [ 0 ] . substring ( 0 , item [ 0 ] . length ( ) - 1 ) ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return a ObjectMapper if exist else new ObjectMapper [CODESPLIT] public static ObjectMapper getMapper ( ) { ObjectMapper mapper = threadMapper . get ( ) ; if ( mapper == null ) { mapper = initMapper ( ) ; threadMapper . set ( mapper ) ; } return mapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize mapper [CODESPLIT] private static ObjectMapper initMapper ( ) { ObjectMapper mapper = new ObjectMapper ( ) ; // to enable standard indentation (\"pretty-printing\"): mapper . enable ( SerializationFeature . INDENT_OUTPUT ) ; // to allow serialization of \"empty\" POJOs (no properties to serialize) // (without this setting, an exception is thrown in those cases) mapper . disable ( SerializationFeature . FAIL_ON_EMPTY_BEANS ) ; // set writer flush after writer value mapper . enable ( SerializationFeature . FLUSH_AFTER_WRITE_VALUE ) ; // ObjectMapper will call close() and root values that implement // java.io.Closeable; // including cases where exception is thrown and serialization does not // completely succeed. mapper . enable ( SerializationFeature . CLOSE_CLOSEABLE ) ; // to write java.util.Date, Calendar as number (timestamp): mapper . disable ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS ) ; // disable default date to timestamp mapper . disable ( SerializationFeature . WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS ) ; // DeserializationFeature for changing how JSON is read as POJOs: // to prevent exception when encountering unknown property: mapper . disable ( DeserializationFeature . FAIL_ON_UNKNOWN_PROPERTIES ) ; // disable default date to timestamp mapper . disable ( DeserializationFeature . READ_DATE_TIMESTAMPS_AS_NANOSECONDS ) ; // to allow coercion of JSON empty String (\"\") to null Object value: mapper . enable ( DeserializationFeature . ACCEPT_EMPTY_STRING_AS_NULL_OBJECT ) ; DateFormat df = new SimpleDateFormat ( \"yyyyMMddHHmmssSSS\" ) ; // Set Default date fromat mapper . setDateFormat ( df ) ; return mapper ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "return a JsonFactory if exist else new JsonFactory [CODESPLIT] public static JsonFactory getJsonFactory ( ) { JsonFactory jsonFactory = threadJsonFactory . get ( ) ; if ( jsonFactory == null ) { jsonFactory = new JsonFactory ( ) ; // JsonParser.Feature for configuring parsing settings: // to allow C/C++ style comments in JSON (non-standard, disabled by // default) jsonFactory . enable ( JsonParser . Feature . ALLOW_COMMENTS ) ; // to allow (non-standard) unquoted field names in JSON: jsonFactory . disable ( JsonParser . Feature . ALLOW_UNQUOTED_FIELD_NAMES ) ; // to allow use of apostrophes (single quotes), non standard jsonFactory . disable ( JsonParser . Feature . ALLOW_SINGLE_QUOTES ) ; // JsonGenerator.Feature for configuring low-level JSON generation: // no escaping of non-ASCII characters: jsonFactory . disable ( JsonGenerator . Feature . ESCAPE_NON_ASCII ) ; threadJsonFactory . set ( jsonFactory ) ; } return jsonFactory ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > List Array Map < / p > <pre > clazz = new TypeReference&lt ; List&lt ; MyBean&gt ; &gt ; () {} ; [CODESPLIT] public static < T > T toBean ( String jsonStr , TypeReference < T > valueTypeRef ) { if ( valueTypeRef == null || jsonStr == null ) return null ; return toBean ( new MyJsonParser ( jsonStr ) , valueTypeRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > List Array Map < / p > <pre > clazz = new TypeReference&lt ; List&lt ; MyBean&gt ; &gt ; () {} ; [CODESPLIT] public static < T > T toBean ( byte [ ] jsonBytes , TypeReference < T > valueTypeRef ) { if ( valueTypeRef == null || jsonBytes == null ) return null ; return toBean ( new MyJsonParser ( jsonBytes ) , valueTypeRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > List Array Map < / p > <pre > clazz = new TypeReference&lt ; List&lt ; MyBean&gt ; &gt ; () {} ; [CODESPLIT] public static < T > T toBean ( Reader jsonReader , TypeReference < T > valueTypeRef ) { if ( valueTypeRef == null || jsonReader == null ) return null ; return toBean ( new MyJsonParser ( jsonReader ) , valueTypeRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > List Array Map < / p > <pre > clazz = new TypeReference&lt ; List&lt ; MyBean&gt ; &gt ; () {} ; [CODESPLIT] public static < T > T toBean ( URL jsonURL , TypeReference < T > valueTypeRef ) { if ( valueTypeRef == null || jsonURL == null ) return null ; return toBean ( new MyJsonParser ( jsonURL ) , valueTypeRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > List Array Map < / p > <pre > clazz = new TypeReference&lt ; List&lt ; MyBean&gt ; &gt ; () {} ; [CODESPLIT] public static < T > T toBean ( File jsonFile , TypeReference < T > valueTypeRef ) { if ( valueTypeRef == null || jsonFile == null ) return null ; return toBean ( new MyJsonParser ( jsonFile ) , valueTypeRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > call { @link MyJsonParser#getJsonParser () } return a JsonParser < / p > [CODESPLIT] protected static < T > T toBean ( MyJsonParser myJsonParser , TypeReference < T > valueTypeRef ) { if ( myJsonParser . getJsonParser ( ) == null ) return null ; return toBean ( myJsonParser . getJsonParser ( ) , valueTypeRef ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > e . g : < / p > <pre > { id : idValue name : nameValue aBean : { aBeanId : aBeanIdValue ... }} < / pre > <p > List Array Map ... see { @link #toBean ( String TypeReference ) } < / p > [CODESPLIT] public static < T > T toBean ( String jsonStr , Class < T > clazz ) { if ( clazz == null || jsonStr == null ) return null ; return toBean ( new MyJsonParser ( jsonStr ) , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > e . g : < / p > <pre > { id : idValue name : nameValue aBean : { aBeanId : aBeanIdValue ... }} < / pre > <p > List Array Map ... see { @link #toBean ( byte [] TypeReference ) } < / p > [CODESPLIT] public static < T > T toBean ( byte [ ] jsonBytes , Class < T > clazz ) { if ( clazz == null || jsonBytes == null ) return null ; return toBean ( new MyJsonParser ( jsonBytes ) , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > e . g : < / p > <pre > { id : idValue name : nameValue aBean : { aBeanId : aBeanIdValue ... }} < / pre > <p > List Array Map ... see { @link #toBean ( Reader TypeReference ) } < / p > [CODESPLIT] public static < T > T toBean ( Reader jsonReader , Class < T > clazz ) { if ( clazz == null || jsonReader == null ) return null ; return toBean ( new MyJsonParser ( jsonReader ) , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > e . g : < / p > <pre > { id : idValue name : nameValue aBean : { aBeanId : aBeanIdValue ... }} < / pre > <p > List Array Map ... see { @link #toBean ( URL TypeReference ) } < / p > [CODESPLIT] public static < T > T toBean ( URL jsonURL , Class < T > clazz ) { if ( clazz == null || jsonURL == null ) return null ; return toBean ( new MyJsonParser ( jsonURL ) , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > e . g : < / p > <pre > { id : idValue name : nameValue aBean : { aBeanId : aBeanIdValue ... }} < / pre > <p > List Array Map ... see { @link #toBean ( File TypeReference ) } < / p > [CODESPLIT] public static < T > T toBean ( File jsonFile , Class < T > clazz ) { if ( clazz == null || jsonFile == null ) return null ; return toBean ( new MyJsonParser ( jsonFile ) , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > call { @link MyJsonParser#getJsonParser () } return a JsonParser < / p > [CODESPLIT] protected static < T > T toBean ( MyJsonParser myJsonParser , Class < T > clazz ) { if ( myJsonParser . getJsonParser ( ) == null ) return null ; return toBean ( myJsonParser . getJsonParser ( ) , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Json string to java bean <br > <p > e . g : < / p > <pre > { id : idValue name : nameValue aBean : { aBeanId : aBeanIdValue ... }} < / pre > <p > List Array Map ... see { @link #toBean ( String TypeReference ) } < / p > [CODESPLIT] public static < T > T toBean ( JsonParser jsonParser , Class < T > clazz ) { if ( clazz == null || jsonParser == null ) return null ; T obj = null ; try { obj = getMapper ( ) . readValue ( jsonParser , clazz ) ; } catch ( JsonParseException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( JsonMappingException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( IOException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } finally { try { jsonParser . close ( ) ; } catch ( IOException e ) { } } return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bean to json string [CODESPLIT] public static < T > String toJson ( T obj ) { StringWriter writer = new StringWriter ( ) ; String jsonStr = \"\" ; JsonGenerator gen = null ; try { gen = getJsonFactory ( ) . createGenerator ( writer ) ; getMapper ( ) . writeValue ( gen , obj ) ; writer . flush ( ) ; jsonStr = writer . toString ( ) ; } catch ( IOException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } finally { if ( gen != null ) { try { gen . close ( ) ; } catch ( IOException e ) { } } } return jsonStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close a { @code Connection } and log any SQLExceptions that occur . [CODESPLIT] public static void close ( final Connection conn ) { if ( conn != null ) { try { conn . close ( ) ; } catch ( SQLException e ) { final String error = \"Error closing JDBC connection. This may indicate a resource leak.\" ; LOG . warn ( error , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close a { @code PreparedStatement } and log any SQLExceptions that occur . [CODESPLIT] public static void close ( final PreparedStatement statement ) { if ( statement != null ) { try { statement . close ( ) ; } catch ( SQLException e ) { final String error = \"Error closing JDBC prepared statement. This may indicate a resource leak.\" ; LOG . warn ( error , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Close a { @code ResultSet } and log any SQLExceptions that occur . [CODESPLIT] public static void close ( final ResultSet resultSet ) { if ( resultSet != null ) { try { resultSet . close ( ) ; } catch ( SQLException e ) { final String error = \"Error closing JDBC result set. This may indicate a resource leak.\" ; LOG . warn ( error , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "注入配置文件中自定义的属性字段 [CODESPLIT] public static List < PropertyInjector > doGetPropertyInjectors ( Ioc ioc , KlassInfo klass , Configuration properties ) { if ( properties == null || properties . size ( ) == 0 ) { return Collections . emptyList ( ) ; } List < PropertyInjector > injectors = new ArrayList < PropertyInjector > ( ) ; for ( String name : properties . keySet ( ) ) { PropertyInfo prop = klass . getProperty ( name ) ; if ( prop == null ) { throw new IllegalStateException ( \"Property not found: \" + klass + \"#\" + name ) ; } if ( ! prop . writable ( ) ) { throw new IllegalStateException ( \"Property not writable: \" + prop ) ; } Object value ; Class < ? > rawType = prop . getRawType ( klass . getType ( ) ) ; if ( List . class . isAssignableFrom ( rawType ) ) { value = properties . getValueList ( prop . getName ( ) , prop . getRawComponentType ( klass . getType ( ) , 0 ) ) ; } else { value = properties . getValue ( prop . getName ( ) , rawType , null ) ; } injectors . add ( new PropertyInjector ( prop , value ) ) ; } return injectors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Fill given field of given entity according value represented as string . < / p > [CODESPLIT] @ Override public final void fill ( final Map < String , Object > pAddParam , final Object pEntity , final String pFieldName , final String pFieldStrValue ) throws Exception { Field rField = getUtlReflection ( ) . retrieveField ( pEntity . getClass ( ) , pFieldName ) ; rField . setAccessible ( true ) ; if ( \"NULL\" . equals ( pFieldStrValue ) ) { rField . set ( pEntity , null ) ; return ; } boolean isFilled = true ; try { if ( rField . getType ( ) == Double . class ) { rField . set ( pEntity , Double . valueOf ( pFieldStrValue ) ) ; } else if ( rField . getType ( ) == Float . class ) { rField . set ( pEntity , Float . valueOf ( pFieldStrValue ) ) ; } else if ( rField . getType ( ) == BigDecimal . class ) { rField . set ( pEntity , new BigDecimal ( pFieldStrValue ) ) ; } else if ( rField . getType ( ) == Date . class ) { rField . set ( pEntity , new Date ( Long . parseLong ( pFieldStrValue ) ) ) ; } else if ( Enum . class . isAssignableFrom ( rField . getType ( ) ) ) { Integer intVal = Integer . valueOf ( pFieldStrValue ) ; Enum val = null ; if ( intVal != null ) { val = ( Enum ) rField . getType ( ) . getEnumConstants ( ) [ intVal ] ; } rField . set ( pEntity , val ) ; } else if ( rField . getType ( ) == Boolean . class ) { rField . set ( pEntity , Boolean . valueOf ( pFieldStrValue ) ) ; } else if ( Integer . class == rField . getType ( ) ) { rField . set ( pEntity , Integer . valueOf ( pFieldStrValue ) ) ; } else if ( Long . class == rField . getType ( ) ) { rField . set ( pEntity , Long . valueOf ( pFieldStrValue ) ) ; } else if ( String . class == rField . getType ( ) ) { String unescaped = this . utilXml . unescapeXml ( pFieldStrValue ) ; rField . set ( pEntity , unescaped ) ; } else { isFilled = false ; } } catch ( Exception ex ) { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , \"Can not fill field: \" + pEntity + \"/\" + pFieldName + \"/\" + pFieldStrValue + \", \" + ex . getMessage ( ) , ex ) ; } if ( ! isFilled ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"There is no rule to fill field: \" + pEntity + \"/\" + pFieldName + \"/\" + pFieldStrValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets all the border values . [CODESPLIT] public void setBorders ( int top , int right , int bottom , int left ) { setTopBorder ( top ) ; setRightBorder ( right ) ; setBottomBorder ( bottom ) ; setLeftBorder ( left ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将 Constructor 对象转成 ConstructorInfo 对象 . [CODESPLIT] public static ConstructorInfo create ( Constructor < ? > constructor ) { KlassInfo klass = KlassInfo . create ( constructor . getDeclaringClass ( ) ) ; return klass . getDeclaredConstructor ( constructor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain an access token . If previously a token was created and persisted will be returned after validation ( a real call is made to validate ) . <p > If no token previously persisted the method will create a new token using the authentication provider ( AuthProvider ) [CODESPLIT] public Token getAccessToken ( ) { Token accessToken = authPersistence . getToken ( ) ; if ( isTokenValid ( accessToken ) ) { return accessToken ; } // authorize accessToken = authorize ( ) ; // save authPersistence . saveToken ( accessToken ) ; return accessToken ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with explicit params [CODESPLIT] public static String send ( String target , RequestMethod method ) throws IOException { return send ( target , \"\" , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with explicit params [CODESPLIT] public static String send ( String target , Map < String , String > headers , RequestMethod method ) throws IOException { return send ( target , ENCODING , headers , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with explicit params [CODESPLIT] public static String send ( String target , String proxy , RequestMethod method ) throws IOException { return send ( target , proxy , ENCODING , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with explicit params [CODESPLIT] public static String send ( UsernamePasswordCredentials upc , String target , RequestMethod method ) throws IOException { return send ( upc , target , ENCODING , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with explicit params [CODESPLIT] public static String send ( UsernamePasswordCredentials upc , InputStream keystore , char [ ] password , String target , String proxy , String encoding , Map < String , String > headers , RequestMethod method ) throws IOException { // TargetHost Object [ ] tmp = resolveUrl ( target ) ; HttpHost targetHost = ( HttpHost ) tmp [ 0 ] ; // URI String uri = ( String ) tmp [ 1 ] ; // ProxyHost HttpHost proxyHost = null ; if ( ! CommUtil . isBlank ( proxy ) ) { Object [ ] tmp1 = resolveUrl ( proxy ) ; proxyHost = ( HttpHost ) tmp1 [ 0 ] ; } Header [ ] _headers = null ; if ( headers != null && headers . size ( ) > 0 ) { _headers = new Header [ headers . size ( ) ] ; for ( Map . Entry < String , String > header : headers . entrySet ( ) ) { Header h = new BasicHeader ( header . getKey ( ) , header . getValue ( ) ) ; ArrayUtil . add ( _headers , h ) ; } } return send ( upc , keystore , password , targetHost , uri , proxyHost , encoding , method , _headers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with explicit params [CODESPLIT] public static String send ( UsernamePasswordCredentials upc , InputStream keystore , char [ ] password , HttpHost targetHost , String uri , HttpHost proxyHost , String encoding , RequestMethod method , Header ... headers ) throws IOException { if ( ! uri . startsWith ( \"/\" ) ) { uri = \"/\" + uri ; } HttpRequest hm = getHttpMethod ( method , uri ) ; if ( headers != null && headers . length > 0 ) { hm . setHeaders ( headers ) ; } log . debug ( \"url: {} method: {}\" , getURL ( targetHost , uri ) , method ) ; return execute ( targetHost , proxyHost , hm , encoding , upc , keystore , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with implicit params [CODESPLIT] public static String sendBody ( String target , byte [ ] body ) throws IOException { return sendBody ( target , body , RequestMethod . POST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with implicit params [CODESPLIT] public static String sendBody ( String target , byte [ ] body , String proxy , RequestMethod method ) throws IOException { return sendBody ( target , body , proxy , ENCODING , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with implicit params [CODESPLIT] public static String sendBody ( InputStream keystore , char [ ] password , String target , byte [ ] body , String proxy , RequestMethod method ) throws IOException { return sendBody ( keystore , password , target , body , proxy , ENCODING , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with implicit params [CODESPLIT] public static String sendBody ( UsernamePasswordCredentials upc , String target , byte [ ] body , String proxy , String encoding , Map < String , String > headers , RequestMethod method ) throws IOException { return sendBody ( upc , null , null , target , body , proxy , encoding , headers , method ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with implicit params [CODESPLIT] public static String sendBody ( UsernamePasswordCredentials upc , InputStream keystore , char [ ] password , HttpHost targetHost , String uri , byte [ ] body , HttpHost proxyHost , String encoding , RequestMethod method , Header ... headers ) throws IOException { return sendBody ( upc , keystore , password , targetHost , uri , new ByteArrayEntity ( body ) , proxyHost , encoding , method , headers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with implicit params [CODESPLIT] public static String sendBody ( UsernamePasswordCredentials upc , InputStream keystore , char [ ] password , HttpHost targetHost , String uri , List < NameValuePair > params , HttpHost proxyHost , String encoding , RequestMethod method , Header ... headers ) throws IOException { return sendBody ( upc , keystore , password , targetHost , uri , new UrlEncodedFormEntity ( params ) , proxyHost , encoding , method , headers ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Send a http request with implicit params [CODESPLIT] public static String sendBody ( UsernamePasswordCredentials upc , InputStream keystore , char [ ] password , HttpHost targetHost , String uri , HttpEntity entity , HttpHost proxyHost , String encoding , RequestMethod method , Header ... headers ) throws IOException { if ( ! uri . startsWith ( \"/\" ) ) { uri = \"/\" + uri ; } HttpEntityEnclosingRequestBase hm = getHttpEntityMethod ( method , uri ) ; if ( headers != null && headers . length > 0 ) { hm . setHeaders ( headers ) ; } if ( entity != null ) { hm . setEntity ( entity ) ; } log . debug ( \"url: {} method: {}\" , getURL ( targetHost , uri ) , method ) ; return execute ( targetHost , proxyHost , hm , encoding , upc , keystore , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Http method instance by { @link com . rockagen . commons . http . RequestMethod } [CODESPLIT] private static HttpRequestBase getHttpMethod ( RequestMethod method , String uri ) { HttpRequestBase hm ; if ( method != null ) { switch ( method ) { case POST : hm = new HttpPost ( uri ) ; break ; case GET : hm = new HttpGet ( uri ) ; break ; case PUT : hm = new HttpPut ( uri ) ; break ; case DELETE : hm = new HttpDelete ( uri ) ; break ; case HEAD : hm = new HttpHead ( uri ) ; break ; case OPTIONS : hm = new HttpOptions ( uri ) ; break ; case TRACE : hm = new HttpTrace ( uri ) ; break ; case PATCH : hm = new HttpPatch ( uri ) ; break ; default : hm = new HttpGet ( uri ) ; break ; } } else hm = new HttpGet ( uri ) ; return hm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get Http method instance by { @link com . rockagen . commons . http . RequestMethod } [CODESPLIT] private static HttpEntityEnclosingRequestBase getHttpEntityMethod ( RequestMethod method , String uri ) { HttpEntityEnclosingRequestBase hm ; if ( method != null ) { switch ( method ) { case POST : hm = new HttpPost ( uri ) ; break ; case PUT : hm = new HttpPut ( uri ) ; break ; case PATCH : hm = new HttpPatch ( uri ) ; break ; default : hm = new HttpPost ( uri ) ; break ; } } else hm = new HttpPost ( uri ) ; return hm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handler main [CODESPLIT] protected static String execute ( HttpHost targetHost , HttpHost proxyHost , HttpRequest httpRequestMethod , String encoding , UsernamePasswordCredentials upc , InputStream keystore , char [ ] password ) throws IOException { HttpClientBuilder hcb = HttpClients . custom ( ) ; hcb . setDefaultRequestConfig ( getRequestConfig ( ) ) ; if ( proxyHost != null ) { hcb . setProxy ( proxyHost ) ; } if ( keystore != null ) { try { KeyStore trustStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; trustStore . load ( keystore , password ) ; SSLContext sslcontext = SSLContexts . custom ( ) . loadTrustMaterial ( trustStore , new TrustSelfSignedStrategy ( ) ) . build ( ) ; SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory ( sslcontext ) ; hcb . setSSLSocketFactory ( ssf ) ; } catch ( KeyStoreException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( CertificateException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( NoSuchAlgorithmException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( KeyManagementException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } finally { keystore . close ( ) ; } } if ( upc != null ) { CredentialsProvider cp = new BasicCredentialsProvider ( ) ; AuthScope as = new AuthScope ( targetHost ) ; cp . setCredentials ( as , upc ) ; hcb . setDefaultCredentialsProvider ( cp ) ; } CloseableHttpClient chc = hcb . build ( ) ; try { CloseableHttpResponse response = chc . execute ( targetHost , httpRequestMethod ) ; return getResponse ( response , encoding ) ; } finally { chc . close ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handle response ( resolve response to String httpClient close etc . ) [CODESPLIT] public static String getResponse ( HttpResponse response , String encoding ) throws IOException { log . debug ( \"status: {}\" , response . getStatusLine ( ) . getStatusCode ( ) ) ; HttpEntity entity = response . getEntity ( ) ; String retval = \"\" ; if ( entity != null ) { try { if ( CommUtil . isBlank ( encoding ) ) { encoding = ENCODING ; } retval = IOUtil . toString ( entity . getContent ( ) , encoding ) ; } finally { EntityUtils . consume ( entity ) ; } } return retval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get UsernamePasswordCredentials [CODESPLIT] public static UsernamePasswordCredentials getUPC ( String usernameSamePassword ) { if ( CommUtil . isBlank ( usernameSamePassword ) ) { return null ; } return new UsernamePasswordCredentials ( usernameSamePassword ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get UsernamePasswordCredentials [CODESPLIT] public static UsernamePasswordCredentials getUPC ( String username , String password ) { if ( CommUtil . isBlank ( username ) && CommUtil . isBlank ( password ) ) { return null ; } return new UsernamePasswordCredentials ( username , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get url [CODESPLIT] public static String getURL ( HttpHost targetHost , String uri ) { if ( targetHost != null && ! CommUtil . isBlank ( targetHost . getSchemeName ( ) ) && ! CommUtil . isBlank ( targetHost . getHostName ( ) ) && targetHost . getPort ( ) > 0 ) { return targetHost + uri ; } return \"null\" + uri ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Resolve String to Object Array < / p > <p > Array length is 2 by default return http : // localhost : 80 / < / p > <li > [ 0 ] -- > HttpHost< / li > <li > [ 1 ] -- > URI< / li > [CODESPLIT] private static Object [ ] resolveUrl ( String str ) { String scheme = \"http\" , host = \"localhost\" , uri = \"/\" ; int port = 80 ; Object [ ] obj = new Object [ 2 ] ; try { if ( str . length ( ) >= 10 ) { String temp = str . substring ( 0 , str . indexOf ( \":\" ) ) ; if ( ! CommUtil . isBlank ( temp ) ) { if ( temp . equalsIgnoreCase ( \"HTTP\" ) || temp . equalsIgnoreCase ( \"HTTPS\" ) ) { scheme = temp ; String temp1 = str . substring ( temp . length ( ) + 3 ) ; if ( temp1 . indexOf ( \"/\" ) > 0 ) { String temp2 = temp1 . substring ( 0 , temp1 . indexOf ( \"/\" ) ) ; if ( temp2 . indexOf ( \":\" ) > 0 ) { String [ ] temp3 = temp2 . split ( \":\" ) ; if ( temp3 . length > 1 && temp3 [ 1 ] . matches ( \"[0-9]*\" ) ) { port = Integer . parseInt ( temp3 [ 1 ] ) ; host = temp3 [ 0 ] ; } } else { host = temp2 ; if ( temp . equalsIgnoreCase ( \"HTTP\" ) ) { port = 80 ; } else if ( temp . equalsIgnoreCase ( \"HTTPS\" ) ) { port = 443 ; } } uri = temp1 . substring ( temp2 . length ( ) ) ; } else { if ( temp1 . indexOf ( \":\" ) > 0 ) { String [ ] temp3 = temp1 . split ( \":\" ) ; if ( temp3 [ 1 ] . matches ( \"[0-9]*\" ) ) { port = Integer . parseInt ( temp3 [ 1 ] ) ; host = temp3 [ 0 ] ; } } else { host = temp1 ; if ( temp . equalsIgnoreCase ( \"HTTP\" ) ) { port = 80 ; } else if ( temp . equalsIgnoreCase ( \"HTTPS\" ) ) { port = 443 ; } } uri = \"/\" ; } } } } } catch ( Exception e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } HttpHost targetHost = new HttpHost ( host , port , scheme ) ; obj [ 0 ] = targetHost ; obj [ 1 ] = uri ; log . debug ( \"The parsed Object Array {}\" , Arrays . toString ( obj ) ) ; return obj ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes targetKinds and E are sensible . [CODESPLIT] private static < E extends Element , F extends E , C extends Collection < F > > C collectionFilter ( C collection , Iterable < ? extends E > elements , Class < F > clazz , ElementKind ... kinds ) { for ( E e : elements ) { ElementKind findKind = e . getKind ( ) ; for ( ElementKind kind : kinds ) if ( kind == findKind ) { collection . add ( clazz . cast ( e ) ) ; break ; } } return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes targetKinds and E are sensible . [CODESPLIT] public static < E extends Element , F extends E > List < F > listFilter ( Iterable < ? extends E > elements , Class < F > clazz , ElementKind ... kinds ) { return collectionFilter ( new ArrayList < F > ( ) , elements , clazz , kinds ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes targetKinds and E are sensible . [CODESPLIT] public static < E extends Element , F extends E > Set < F > setFilter ( Iterable < ? extends E > elements , Class < F > clazz , ElementKind ... kinds ) { // Return set preserving iteration order of input set.\r return collectionFilter ( new LinkedHashSet < F > ( ) , elements , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public final void init ( final CommonProperties properties ) { Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; // no need for defensive copies here, as all internal config values are calculated // some caching would be nice, but then we would have to allow resets in case the application wants to reload // its configuration at some point - seems not worth the hassle at this point. LOG . info ( \"Parsing connection properties configuration\" ) ; connProps . set ( JaasBasedConnPropsBuilder . build ( properties . getAdditionalProperties ( ) ) ) ; // same statement about caching :) LOG . info ( \"Parsing database properties configuration\" ) ; dbProps . set ( JaasBasedDbPropsBuilder . build ( properties . getAdditionalProperties ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "CHECKSTYLE : OFF [CODESPLIT] @ SuppressWarnings ( { \"PMD.CyclomaticComplexity\" , \"PMD.NPathComplexity\" } ) // CHECKSTYLE:ON public final Subject authenticate ( final String domain , final String userName , final char [ ] password , final PasswordValidator passwordValidator ) throws LoginException { // make sure the credentials are not null if ( domain == null || userName == null || password == null ) { throw new LoginException ( \"The credentials cannot be null\" ) ; } // SQL query is required if ( StringUtils . isBlank ( dbProps . get ( ) . getSqlUserQuery ( ) ) ) { final String error = \"Invalid SQL user authentication query (query is null or empty)\" ; LOG . warn ( error ) ; throw new LoginException ( error ) ; } final UserRecord userRecord = getUserRecord ( domain , userName ) ; if ( userRecord . getUserId ( ) == null || userRecord . getUserId ( ) . length ( ) == 0 ) { final String error = \"User ID for username '\" + userName + \"' is null or empty in the database\" ; LOG . warn ( error ) ; throw new LoginException ( error ) ; } if ( userRecord . getCredential ( ) == null || userRecord . getCredential ( ) . length ( ) == 0 ) { final String error = \"Credential for username '\" + userName + \"' / user ID '\" + userRecord . getUserId ( ) + \"' is null or empty in the database\" ; LOG . warn ( error ) ; throw new LoginException ( error ) ; } // no need for defensive copies of Strings, but create a defensive copy of the password final char [ ] myPassword = password . clone ( ) ; // convert the credential string to a char array final char [ ] myCredential = userRecord . getCredential ( ) . toCharArray ( ) ; if ( ! passwordValidator . validate ( myPassword , myCredential ) ) { final String error = \"Invalid password for username '\" + userName + \"'\" ; LOG . info ( error ) ; throw new FailedLoginException ( error ) ; } // The authentication was successful! // Create the subject and clean up confidential data as far as possible. // clear the char representation of the credential Cleanser . wipe ( myCredential ) ; // clear the defensive copy of the password created earlier Cleanser . wipe ( myPassword ) ; // create a principal that includes the username and domain name that were used to authenticate the user final UserPrincipal userPrincipal = new UserPrincipal ( userRecord . getUserId ( ) , domain , userName ) ; // wrap the principal in a Subject final Subject subject = new Subject ( ) ; subject . getPrincipals ( ) . add ( userPrincipal ) ; return subject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The SQL statement is retrieved from the configuration and the admin is trusted [CODESPLIT] @ edu . umd . cs . findbugs . annotations . SuppressWarnings ( \"SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING\" ) private UserRecord getUserRecord ( final String domain , final String userName ) throws LoginException { String userId ; String credential ; Connection connection = null ; PreparedStatement statement = null ; ResultSet resultSet = null ; try { connection = getDatabaseConnection ( ) ; statement = connection . prepareStatement ( dbProps . get ( ) . getSqlUserQuery ( ) ) ; statement . setString ( 1 , domain ) ; statement . setString ( 2 , userName ) ; resultSet = statement . executeQuery ( ) ; if ( resultSet . next ( ) ) { userId = resultSet . getString ( 1 ) ; credential = resultSet . getString ( 2 ) ; } else { final String error = \"Username '\" + userName + \"' does not exist (query returned zero results)\" ; LOG . warn ( error ) ; throw new LoginException ( error ) ; } resultSet . close ( ) ; statement . close ( ) ; } catch ( SQLException e ) { final String error = \"Error executing SQL query\" ; LOG . warn ( error , e ) ; throw Util . newLoginException ( error , e ) ; } finally { DbUtil . close ( resultSet ) ; DbUtil . close ( statement ) ; DbUtil . close ( connection ) ; } return new UserRecord ( domain , userName , userId , credential ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a database connection - either a JNDI connection ( directly from the factory ) or a pooled JDBC connection [CODESPLIT] private Connection getDatabaseConnection ( ) throws LoginException { Connection connection ; if ( StringUtils . isNotEmpty ( dbProps . get ( ) . getJndiConnectionName ( ) ) ) { try { connection = ConnectionFactory . getConnection ( dbProps . get ( ) . getJndiConnectionName ( ) ) ; } catch ( FactoryException e ) { final String error = \"Could not retrieve JNDI database connection\" ; LOG . warn ( error , e ) ; throw Util . newLoginException ( error , e ) ; } } else { try { // connection spec is required if ( connProps . get ( ) == null ) { final String error = \"Database connection pool configuration has not been provided or initialized\" ; LOG . warn ( error ) ; throw new FactoryException ( error ) ; } // driver is required if ( StringUtils . isBlank ( connProps . get ( ) . getDriver ( ) ) ) { final String error = \"Invalid database driver (driver name is null or empty)\" ; LOG . warn ( error ) ; throw new FactoryException ( error ) ; } // url is required if ( StringUtils . isBlank ( connProps . get ( ) . getUrl ( ) ) ) { final String error = \"Invalid database URL (URL is null or empty)\" ; LOG . warn ( error ) ; throw new FactoryException ( error ) ; } connection = ConnectionFactory . getConnection ( connProps . get ( ) ) ; } catch ( FactoryException e ) { final String error = \"Could not create pooled database connection\" ; LOG . warn ( error , e ) ; throw Util . newLoginException ( error , e ) ; } } return connection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add [CODESPLIT] public static float addF ( final float v1 , final float v2 ) { BigDecimal b1 = new BigDecimal ( Float . toString ( v1 ) ) ; BigDecimal b2 = new BigDecimal ( Float . toString ( v2 ) ) ; return b1 . add ( b2 ) . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sub [CODESPLIT] public static double sub ( final double v1 , final double v2 ) { BigDecimal b1 = new BigDecimal ( Double . toString ( v1 ) ) ; BigDecimal b2 = new BigDecimal ( Double . toString ( v2 ) ) ; return b1 . subtract ( b2 ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sub [CODESPLIT] public static float subF ( final float v1 , final float v2 ) { BigDecimal b1 = new BigDecimal ( Float . toString ( v1 ) ) ; BigDecimal b2 = new BigDecimal ( Float . toString ( v2 ) ) ; return b1 . subtract ( b2 ) . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mul [CODESPLIT] public static double mul ( final double v1 , final double v2 ) { BigDecimal b1 = new BigDecimal ( Double . toString ( v1 ) ) ; BigDecimal b2 = new BigDecimal ( Double . toString ( v2 ) ) ; return b1 . multiply ( b2 ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "mul [CODESPLIT] public static float mul ( final float v1 , final float v2 ) { BigDecimal b1 = new BigDecimal ( Float . toString ( v1 ) ) ; BigDecimal b2 = new BigDecimal ( Float . toString ( v2 ) ) ; return b1 . multiply ( b2 ) . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "div [CODESPLIT] public static double div ( final double v1 , final double v2 , int scale , int roundingMode ) { if ( scale < 0 ) { scale = DIV_SCALE ; } if ( roundingMode < 0 ) { roundingMode = ROUNDING_MODE ; } BigDecimal b1 = new BigDecimal ( Double . toString ( v1 ) ) ; BigDecimal b2 = new BigDecimal ( Double . toString ( v2 ) ) ; return b1 . divide ( b2 , scale , roundingMode ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "div [CODESPLIT] public static float div ( final float v1 , final float v2 , int scale , int roundingMode ) { if ( scale < 0 ) { scale = DIV_SCALE ; } if ( roundingMode < 0 ) { roundingMode = ROUNDING_MODE ; } BigDecimal b1 = new BigDecimal ( Float . toString ( v1 ) ) ; BigDecimal b2 = new BigDecimal ( Float . toString ( v2 ) ) ; return b1 . divide ( b2 , scale , roundingMode ) . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "random [CODESPLIT] public static double round ( final double v , int scale , int roundingMode ) { if ( scale < 0 ) { scale = DIV_SCALE ; } if ( roundingMode < 0 ) { roundingMode = ROUNDING_MODE ; } BigDecimal b = new BigDecimal ( Double . toString ( v ) ) ; BigDecimal one = new BigDecimal ( \"1\" ) ; return b . divide ( one , scale , roundingMode ) . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "random [CODESPLIT] public static float round ( final float v , int scale , int roundingMode ) { if ( scale < 0 ) { scale = DIV_SCALE ; } if ( roundingMode < 0 ) { roundingMode = ROUNDING_MODE ; } BigDecimal b = new BigDecimal ( Float . toString ( v ) ) ; BigDecimal one = new BigDecimal ( \"1\" ) ; return b . divide ( one , scale , roundingMode ) . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to double [CODESPLIT] public static float toFloat ( final double d ) { BigDecimal b = new BigDecimal ( Double . toString ( d ) ) ; return b . floatValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "to float [CODESPLIT] public static double toDouble ( final float f ) { BigDecimal b = new BigDecimal ( Float . toString ( f ) ) ; return b . doubleValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据 annotation，获取所有的 Action [CODESPLIT] @ Override public void registerController ( Class < ? > clazz ) { Controller controller = clazz . getAnnotation ( Controller . class ) ; Validate . notNull ( controller ) ; String ctrlPath = ValueConstants . trimToEmpty ( controller . value ( ) ) ; ControllerInfo ctrlInfo = new ControllerInfo ( clazz , controller ) ; ResultHandlerResolver resultHandlerResolver = WebConfig . getInstance ( ) . getResultHandlerResolver ( ) ; KlassInfo klass = KlassInfo . create ( clazz ) ; for ( MethodInfo actionMethod : klass . getMethods ( ) ) { if ( ! klass . isPublic ( ) || actionMethod . isStatic ( ) ) { continue ; } Action action = actionMethod . getAnnotation ( Action . class ) ; if ( action == null ) { continue ; } String actionPath = ValueConstants . defaultValue ( action . value ( ) , actionMethod . getName ( ) ) ; String url = StringUtils . removeEnd ( ctrlPath , \"/\" ) + StringUtils . prefix ( actionPath , \"/\" ) ; // validate the action result type Class < ? > returnClass = actionMethod . getRawReturnType ( clazz ) ; if ( ! resultHandlerResolver . validate ( returnClass ) ) { throw new IllegalStateException ( \"Unsupported result class: \" + returnClass . getName ( ) + \" of \" + actionMethod ) ; } HttpMethod [ ] httpMethods = action . method ( ) ; Validate . isTrue ( httpMethods . length > 0 ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( \"found action: {} {}\" , ArrayUtils . toString ( httpMethods ) , url ) ; } ActionInfo actionInfo = new ActionInfo ( ctrlInfo , actionMethod , url ) ; for ( HttpMethod method : httpMethods ) { RestfulMatcher matcher = matchers [ method . getIndex ( ) ] ; if ( matcher == null ) { matcher = new RestfulMatcher ( ) ; matchers [ method . getIndex ( ) ] = matcher ; } matcher . register ( actionInfo , url ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "用尝试多种格式解析日期时间 . [CODESPLIT] public static Date parse ( String date ) { Date d = parseUsingPatterns ( date , STD_PATTERNS ) ; if ( d == null ) { d = parseRFC822Date ( date ) ; } if ( d == null ) { d = parseW3CDateTime ( date ) ; } if ( d == null ) { try { d = DateFormat . getInstance ( ) . parse ( date ) ; } catch ( ParseException e ) { d = null ; } } return d ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "用指定的格式解析日期时间 . [CODESPLIT] public static Date parseUsingPattern ( String date , String pattern ) { SimpleDateFormat df = new SimpleDateFormat ( pattern ) ; df . setLenient ( false ) ; try { ParsePosition pp = new ParsePosition ( 0 ) ; Date d = df . parse ( date , pp ) ; if ( d != null && pp . getIndex ( ) != date . length ( ) ) { return d ; } } catch ( Exception e ) { } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a JMX MBean idenfitied by an ObjectName copy the values of the given attributes into the target object using the specified setter methods mapped by attribute name . [CODESPLIT] public void copyOutAttributes ( Object target , List < Attribute > jmxAttributeValues , Map < String , Method > attributeSetters , ObjectName objectName ) { this . copyOutAttributes ( target , jmxAttributeValues , attributeSetters , \"oname\" , objectName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the values of the given attributes into the target object using the specified setter methods mapped by attribute name . [CODESPLIT] protected void copyOutAttributes ( Object target , List < Attribute > jmxAttributeValues , Map < String , Method > attributeSetters , String identifierKey , Object identifier ) { for ( Attribute oneAttribute : jmxAttributeValues ) { String attributeName = oneAttribute . getName ( ) ; Method setter = attributeSetters . get ( attributeName ) ; Object value = oneAttribute . getValue ( ) ; try { // // Automatically down-convert longs to integers as-needed. // if ( ( setter . getParameterTypes ( ) [ 0 ] . isAssignableFrom ( Integer . class ) ) || ( setter . getParameterTypes ( ) [ 0 ] . isAssignableFrom ( int . class ) ) ) { if ( value instanceof Long ) { value = ( ( Long ) value ) . intValue ( ) ; } } setter . invoke ( target , value ) ; } catch ( InvocationTargetException invocationExc ) { this . log . info ( \"invocation exception storing mbean results: {}={}; attributeName={}\" , identifierKey , identifier , attributeName , invocationExc ) ; } catch ( IllegalAccessException illegalAccessExc ) { this . log . info ( \"illegal access exception storing mbean results: {}={}; attributeName={}\" , identifierKey , identifier , attributeName , illegalAccessExc ) ; } catch ( IllegalArgumentException illegalArgumentExc ) { this . log . info ( \"illegal argument exception storing mbean results: {}={}; attributeName={}\" , identifierKey , identifier , attributeName , illegalArgumentExc ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* [CODESPLIT] public static void browse ( String url ) throws Exception { if ( OS_NAME . startsWith ( \"Mac OS\" ) ) { Method openURL = ClassUtil . getDeclaredMethod ( Class . forName ( \"com.apple.eio.FileManager\" ) , true , \"openURL\" , String . class ) ; openURL . invoke ( null , url ) ; } else if ( OS_NAME . startsWith ( \"Windows\" ) ) { Runtime . getRuntime ( ) . exec ( \"rundll32 url.dll,FileProtocolHandler \" + url ) ; } else { // assume Unix or Linux String [ ] browsers = { \"firefox\" , \"opera\" , \"konqueror\" , \"epiphany\" , \"mozilla\" , \"netscape\" } ; String browser = null ; for ( int count = 0 ; count < browsers . length && browser == null ; count ++ ) if ( Runtime . getRuntime ( ) . exec ( new String [ ] { \"which\" , browsers [ count ] } ) . waitFor ( ) == 0 ) browser = browsers [ count ] ; if ( browser == null ) throw new NoSuchMethodException ( \"Could not find web browser\" ) ; else Runtime . getRuntime ( ) . exec ( new String [ ] { browser , url } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a type declaration . [CODESPLIT] public void visitTypeDeclaration ( TypeDeclaration d ) { d . accept ( pre ) ; SortedSet < Declaration > decls = new TreeSet < Declaration > ( SourceOrderDeclScanner . comparator ) ; for ( TypeParameterDeclaration tpDecl : d . getFormalTypeParameters ( ) ) { decls . add ( tpDecl ) ; } for ( FieldDeclaration fieldDecl : d . getFields ( ) ) { decls . add ( fieldDecl ) ; } for ( MethodDeclaration methodDecl : d . getMethods ( ) ) { decls . add ( methodDecl ) ; } for ( TypeDeclaration typeDecl : d . getNestedTypes ( ) ) { decls . add ( typeDecl ) ; } for ( Declaration decl : decls ) decl . accept ( this ) ; d . accept ( post ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Fill given field of given entity according value represented as string . < / p > [CODESPLIT] @ Override public final void fill ( final Map < String , Object > pAddParam , final Object pEntity , final String pFieldName , final String pFieldStrValue ) throws Exception { if ( ! UserRoleTomcat . class . isAssignableFrom ( pEntity . getClass ( ) ) ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"It's wrong service to fill that field: \" + pEntity + \"/\" + pFieldName + \"/\" + pFieldStrValue ) ; } UserRoleTomcat userRoleTomcat = ( UserRoleTomcat ) pEntity ; if ( \"NULL\" . equals ( pFieldStrValue ) ) { userRoleTomcat . setItsUser ( null ) ; return ; } try { UserTomcat ownedEntity = new UserTomcat ( ) ; ownedEntity . setItsUser ( pFieldStrValue ) ; userRoleTomcat . setItsUser ( ownedEntity ) ; } catch ( Exception ex ) { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , \"Can not fill field: \" + pEntity + \"/\" + pFieldName + \"/\" + pFieldStrValue + \", \" + ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accept this file? [CODESPLIT] public boolean accept ( File dir , String filename ) { String strPath = dir . getPath ( ) . toLowerCase ( ) ; if ( strPath . indexOf ( m_strOkayPath ) != - 1 ) return true ; return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override // Check is broken [LOG.info()]: PMD reports issues although log stmt is guarded. @todo revisit when upgrading PMD. @ SuppressWarnings ( \"PMD.GuardLogStatementJavaUtil\" ) public final void audit ( final Events event , final String domain , final String username ) { Validate . notNull ( event , \"The validated object 'event' is null\" ) ; Validate . notBlank ( domain , \"The validated character sequence 'domain' is null or empty\" ) ; Validate . notBlank ( username , \"The validated character sequence 'username' is null or empty\" ) ; // PMD does not recognize the guarded log statement if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"[AUDIT] \" + event . getValue ( ) + \". User name '\" + username + \"', domain '\" + domain + \"'\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public static < T > T [ ] asArray ( Collection < T > items , Class < T > elementType ) { if ( items == null ) { return null ; } @ SuppressWarnings ( \"unchecked\" ) T [ ] results = ( T [ ] ) Array . newInstance ( elementType , items . size ( ) ) ; int i = 0 ; for ( T item : items ) { results [ i ++ ] = item ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes targetKinds and E are sensible . [CODESPLIT] private static < E , F extends E , C extends Collection < F > > C collectionFilter ( C collection , Iterable < ? extends E > elements , Class < F > clazz ) { for ( E e : elements ) { //if (clazz.isAssignableFrom(e.getClass()))\r if ( clazz . isInstance ( e ) ) collection . add ( clazz . cast ( e ) ) ; } return collection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes targetKinds and E are sensible . [CODESPLIT] public static < E , F extends E > List < F > listFilter ( Iterable < ? extends E > elements , Class < F > clazz ) { return collectionFilter ( new ArrayList < F > ( ) , elements , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assumes targetKinds and E are sensible . [CODESPLIT] public static < E , F extends E > Set < F > setFilter ( Iterable < ? extends E > elements , Class < F > clazz ) { // Return set preserving iteration order of input set.\r return collectionFilter ( new LinkedHashSet < F > ( ) , elements , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Copy the input stream to the output stream . [CODESPLIT] public static int copyStream ( InputStream inStream , OutputStream outStream ) throws IOException { return Util . copyStream ( inStream , outStream , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Copy the input stream to the output stream . [CODESPLIT] public static int copyStream ( InputStream inStream , OutputStream outStream , boolean bCountInBytes , boolean bCountOutBytes ) throws IOException { byte rgBytes [ ] = new byte [ 8192 ] ; int iTotalLength = 0 ; int iStartInByte = 0 ; int iStartOutByte = 0 ; while ( true ) { int iLength = rgBytes . length ; if ( bCountInBytes ) iStartInByte = iTotalLength ; iLength = inStream . read ( rgBytes , iStartInByte , iLength ) ; if ( DEBUG ) System . out . println ( \"inLen = \" + iLength ) ; if ( iLength <= 0 ) break ; if ( bCountOutBytes ) iStartOutByte = iTotalLength ; outStream . write ( rgBytes , iStartOutByte , iLength ) ; iTotalLength += iLength ; } return iTotalLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create a new object using this class name . Conform to the standardized classname format : com . tourgeek . terminal . src / dest . name . namesrc / dest [CODESPLIT] public static Object makeObjectFromClassName ( String interfaceName , String strPackage , String strClassName ) { if ( strClassName == null ) return null ; if ( strClassName . indexOf ( ' ' ) == - 1 ) if ( strPackage != null ) { // Use default structure strClassName = org . jbundle . jbackup . JBackupConstants . ROOT_PACKAGE + \"jbackup.\" + strPackage . toLowerCase ( ) + ' ' + strClassName + strPackage . substring ( 0 , 1 ) . toUpperCase ( ) + strPackage . substring ( 1 ) ; } Object objClass = null ; try { if ( strClassName . indexOf ( ' ' ) == 0 ) strClassName = org . jbundle . jbackup . JBackupConstants . ROOT_PACKAGE + strClassName . substring ( 1 ) ; Class < ? > c = Class . forName ( strClassName ) ; if ( c != null ) { objClass = c . newInstance ( ) ; } } catch ( Exception ex ) { System . out . println ( \"Error on attempt to make class: \" + strClassName ) ; ex . printStackTrace ( ) ; System . exit ( 0 ) ; } return objClass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Convert this date string to a date object . [CODESPLIT] public static Date stringToDate ( String strDate ) { Date dateLastBackup = null ; if ( ( strDate != null ) && ( strDate . length ( ) > 0 ) ) { try { dateLastBackup = DateFormat . getInstance ( ) . parse ( strDate ) ; } catch ( ParseException ex ) { dateLastBackup = null ; } } return dateLastBackup ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Convert this date object to a string . [CODESPLIT] public static String dateToString ( Date date ) { if ( date == null ) return \"\" ; try { return DateFormat . getInstance ( ) . format ( date ) ; } catch ( Exception ex ) { } return \"\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create a filter from these properties . [CODESPLIT] public static FilenameFilter makeFilter ( Properties properties ) { String strFilter = properties . getProperty ( JBackupConstants . FILTER_PARAM ) ; if ( strFilter != null ) if ( strFilter . indexOf ( ' ' ) != - 1 ) return ( FilenameFilter ) Util . makeObjectFromClassName ( Object . class . getName ( ) , null , strFilter ) ; else return new PathFilter ( strFilter ) ; return null ; // Add+++ Make the filename filter! }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get property . [CODESPLIT] public String getProperty ( String key ) { if ( m_properties == null ) return null ; return m_properties . getProperty ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set property . [CODESPLIT] public void setProperty ( String key , String value ) { if ( m_properties == null ) m_properties = new Properties ( ) ; m_properties . setProperty ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add this applet to a frame and initialize . [CODESPLIT] public JFrame addAppToFrame ( ) { JFrame frame = new JFrame ( ) ; frame . setTitle ( this . getTitle ( ) ) ; frame . setBackground ( Color . lightGray ) ; frame . getContentPane ( ) . setLayout ( new BorderLayout ( ) ) ; frame . getContentPane ( ) . add ( this , BorderLayout . CENTER ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ) ; frame . pack ( ) ; frame . setSize ( frame . getPreferredSize ( ) . width , frame . getPreferredSize ( ) . height ) ; return frame ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a copy of the key / values in the map at the point of calling . However setValue still sets the value in the actual SoftHashMap . [CODESPLIT] @ Override public Set < Entry < K , V > > entrySet ( ) { processQueue ( ) ; Set < Entry < K , V > > result = new LinkedHashSet < Entry < K , V > > ( ) ; for ( final Entry < K , SoftValue < V > > entry : map . entrySet ( ) ) { final V value = entry . getValue ( ) . get ( ) ; if ( value != null ) { result . add ( new Entry < K , V > ( ) { @ Override public K getKey ( ) { return entry . getKey ( ) ; } @ Override public V getValue ( ) { return value ; } @ Override public V setValue ( V v ) { entry . setValue ( new SoftValue < V > ( v , entry . getKey ( ) , queue ) ) ; return value ; } } ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value . The result has one of the following types : <ul > <li > a wrapper class ( such as { @link Integer } ) for a primitive type <li > { @code String } <li > { @code TypeMirror } <li > { @code EnumConstantDeclaration } <li > { @code AnnotationMirror } <li > { @code Collection<AnnotationValue > } ( representing the elements in order if the value is an array ) <p / > internal . getValue returns : * <ul > <li > a wrapper class ( such as { @link Integer } ) for a primitive type <li > { @code String } <li > { @code TypeMirror } <li > { @code VariableElement } ( representing an enum constant ) <li > { @code AnnotationMirror } <li > { @code List<? extends AnnotationValue > } ( representing the elements in declared order if the value is an array ) < / ul > [CODESPLIT] @ Override @ SuppressWarnings ( { \"unchecked\" } ) public Object getValue ( ) { Debug . implemented ( \"Object\" ) ; Object ret = internal . getValue ( ) ; if ( ret instanceof VariableElement && ( ( VariableElement ) ret ) . getKind ( ) == ElementKind . ENUM_CONSTANT ) ret = ConvertDeclaration . convert ( ( VariableElement ) ret ) ; else if ( ret instanceof javax . lang . model . element . AnnotationMirror ) ret = ConvertAnnotationMirror . convert ( ( javax . lang . model . element . AnnotationMirror ) ret ) ; else if ( ret instanceof javax . lang . model . type . TypeMirror ) ret = ConvertTypeMirror . convert ( ( javax . lang . model . type . TypeMirror ) ret ) ; else if ( ret instanceof List ) ret = convert ( ( List < ? extends AnnotationValue > ) ret ) ; // else, we are hoping it's a String or wrapper for a primitive type, just return it\r if ( Debug . debug ) System . err . println ( \"!!!!!!!!!!!!ret: \" + ret ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Print the help for <code > options< / code > with the specified command line syntax . This method prints help information to System . out . [CODESPLIT] public static void printHelp ( String cmdLineSyntax , String header , Options options , String footer ) { HelpFormatter hf = new HelpFormatter ( ) ; if ( CommUtil . isBlank ( cmdLineSyntax ) ) { cmdLineSyntax = \"Command [options]...\" ; } header = header + SysUtil . LINE_SEPARATOR + \"Options:\" ; footer = SysUtil . LINE_SEPARATOR + footer ; hf . printHelp ( cmdLineSyntax , header , options , footer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a commandLine object by specifies { @link Parser } { @link Options } <code > arguments< / code > <code > stopAtNonOption< / code > [CODESPLIT] public static CommandLine parse ( Parser parser , Options options , String [ ] arguments , boolean stopAtNonOption ) throws ParseException { CommandLine line = parser . parse ( options , arguments , stopAtNonOption ) ; return line ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get ready to start processing . [CODESPLIT] public void init ( Properties properties ) { super . init ( properties ) ; String strPathname = properties . getProperty ( SOURCE_ROOT_PATHNAME_PARAM ) ; if ( strPathname == null ) { strPathname = \"c:\\\\My Documents\" ; properties . setProperty ( SOURCE_ROOT_PATHNAME_PARAM , strPathname ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { super . initTransfer ( properties ) ; m_strRootPath = properties . getProperty ( SOURCE_ROOT_PATHNAME_PARAM ) ; m_iCurrentLevel = - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next element in the iteration . ( Returns a SourceFileObject ) . [CODESPLIT] public SourceFile next ( ) { if ( this . isPend ( ) ) return this . getPend ( ) ; if ( m_iCurrentLevel == - 1 ) { // First time File fileDir = new File ( m_strRootPath ) ; m_iCurrentLevel ++ ; if ( ! fileDir . isDirectory ( ) ) return null ; // Never\t// pend(don) Return 1 file? m_rgfileCurrentFilelist [ m_iCurrentLevel ] = fileDir . listFiles ( ) ; m_rgstrCurrentPath [ m_iCurrentLevel ] = JBackupConstants . BLANK ; // Root (relative) m_rgiCurrentFile [ m_iCurrentLevel ] = 0 ; } while ( true ) { File [ ] fileList = m_rgfileCurrentFilelist [ m_iCurrentLevel ] ; // Current list int iCurrentIndex = m_rgiCurrentFile [ m_iCurrentLevel ] ; if ( iCurrentIndex >= fileList . length ) { // End of directory, go up a level m_rgfileCurrentFilelist [ m_iCurrentLevel ] = null ; // Free m_rgstrCurrentPath [ m_iCurrentLevel ] = null ; m_rgiCurrentFile [ m_iCurrentLevel ] = 0 ; m_iCurrentLevel -- ; // End of directory if ( m_iCurrentLevel < 0 ) return null ; // End of files! } else { File file = fileList [ iCurrentIndex ] ; String strPath = m_rgstrCurrentPath [ m_iCurrentLevel ] ; m_rgiCurrentFile [ m_iCurrentLevel ] ++ ; // Bump for next time if ( file . isDirectory ( ) ) { // This is a directory, go down a level strPath += file . getName ( ) + gchSeparator ; m_iCurrentLevel ++ ; if ( m_Filter == null ) fileList = file . listFiles ( ) ; else fileList = file . listFiles ( m_Filter ) ; m_rgfileCurrentFilelist [ m_iCurrentLevel ] = fileList ; m_rgstrCurrentPath [ m_iCurrentLevel ] = strPath ; // Relative path to this directory m_rgiCurrentFile [ m_iCurrentLevel ] = 0 ; if ( fileList == null ) m_iCurrentLevel -- ; // Special case - skip windows linked directory } else if ( file . isFile ( ) ) { String strName = file . getName ( ) ; if ( m_Filter != null ) { if ( ! m_Filter . accept ( file , strName ) ) continue ; // HACK - The filter should do this } if ( this . skipFile ( file ) ) continue ; String strRelativeFileName = strPath + strName ; long lStreamLength = file . length ( ) ; return new StreamSourceFile ( file , null , strRelativeFileName , strName , lStreamLength ) ; // Return the file } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Save the token using java preferences . [CODESPLIT] @ Override public void saveToken ( Token token ) { set ( ACCESS_TOKEN_TOKEN_PREF , token . getToken ( ) ) ; set ( ACCESS_TOKEN_SECRET_PREF , token . getSecret ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the persisted token using java preferences . [CODESPLIT] @ Override public Token getToken ( ) { String token = get ( ACCESS_TOKEN_TOKEN_PREF ) ; String secret = get ( ACCESS_TOKEN_SECRET_PREF ) ; return token != null ? new Token ( token , secret ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void init ( Properties properties ) { super . init ( properties ) ; String strPathname = properties . getProperty ( LOG_FILENAME_PARAM ) ; if ( strPathname == null ) { strPathname = \"\" ; properties . setProperty ( LOG_FILENAME_PARAM , strPathname ) ; } String strGetFileLength = properties . getProperty ( CALC_FILE_LENGTH_PARAM ) ; if ( strGetFileLength == null ) { strGetFileLength = TRUE ; properties . setProperty ( CALC_FILE_LENGTH_PARAM , strGetFileLength ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { super . initTransfer ( properties ) ; String strPathname = properties . getProperty ( LOG_FILENAME_PARAM ) ; if ( strPathname != null ) if ( strPathname . length ( ) > 0 ) { try { FileOutputStream fileOut = new FileOutputStream ( strPathname ) ; streamOut = new PrintStream ( fileOut ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } } if ( streamOut == null ) streamOut = System . out ; String strSelected = properties . getProperty ( CALC_FILE_LENGTH_PARAM ) ; if ( FALSE . equalsIgnoreCase ( strSelected ) ) getFileLength = false ; else getFileLength = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add this file to the destination . Note : Only supply the file or the stream not both . Supply the object that is easier given the source . This dual option is given to allow destinations that require File objects from ( such as FTP or HTTP ) Having to write the inStream to a physical file before processing it . [CODESPLIT] public long addNextFile ( SourceFile source ) { String strPath = source . getFilePath ( ) ; String strFilename = source . getFileName ( ) ; long lTotalLength = 0 ; if ( getFileLength ) { byte rgBytes [ ] = new byte [ 8192 ] ; InputStream inStream = source . makeInStream ( ) ; try { while ( true ) { int iLength = rgBytes . length ; iLength = inStream . read ( rgBytes , 0 , iLength ) ; if ( iLength <= 0 ) break ; lTotalLength += iLength ; } } catch ( IOException ex ) { streamOut . println ( \"Error on next file: \" + ex . getMessage ( ) ) ; } } streamOut . println ( \"Filename: \" + strFilename + \" Path: \" + strPath + \" length: \" + lTotalLength ) ; return lTotalLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; JPanel panelMain = this . makeNewPanel ( panel , BorderLayout . CENTER ) ; panelMain . setLayout ( new GridLayout ( 5 , 2 ) ) ; panelMain . add ( new JLabel ( \"Ftp Host: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfHost = new JTextField ( ) ) ; panelMain . add ( new JLabel ( \"Ftp Port: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfPort = new JTextField ( ) ) ; panelMain . add ( new JLabel ( \"User name: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfUser = new JTextField ( ) ) ; panelMain . add ( new JLabel ( \"Password: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfPassword = new JTextField ( ) ) ; panelMain . add ( new JLabel ( \"Initial directory: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfDir = new JTextField ( ) ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strHost = m_tfHost . getText ( ) ; m_properties . setProperty ( FTP_HOST , strHost ) ; String strPort = m_tfPort . getText ( ) ; m_properties . setProperty ( FTP_PORT , strPort ) ; String strUser = m_tfUser . getText ( ) ; m_properties . setProperty ( USER_NAME , strUser ) ; String strPassword = m_tfPassword . getText ( ) ; m_properties . setProperty ( PASSWORD , strPassword ) ; String strDir = m_tfDir . getText ( ) ; m_properties . setProperty ( ROOT_DIR , strDir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strHost = m_properties . getProperty ( FTP_HOST ) ; m_tfHost . setText ( strHost ) ; String strPort = m_properties . getProperty ( FTP_PORT ) ; m_tfPort . setText ( strPort ) ; String strUser = m_properties . getProperty ( USER_NAME ) ; m_tfUser . setText ( strUser ) ; String strPassword = m_properties . getProperty ( PASSWORD ) ; m_tfPassword . setText ( strPassword ) ; String strDir = m_properties . getProperty ( ROOT_DIR ) ; if ( strDir == null ) strDir = DEFAULT_ROOT_DIR ; m_tfDir . setText ( strDir ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据 classLoader 获取所有的 Classpath URLs . [CODESPLIT] public static Collection < URL > getClasspathURLs ( final ClassLoader classLoader ) { Collection < URL > urls = new LinkedHashSet < URL > ( 32 ) ; ClassLoader loader = classLoader ; while ( loader != null ) { String className = loader . getClass ( ) . getName ( ) ; if ( EXT_CLASS_LOADER_NAME . equals ( className ) ) { break ; } if ( loader instanceof URLClassLoader ) { for ( URL url : ( ( URLClassLoader ) loader ) . getURLs ( ) ) { urls . add ( url ) ; } } else if ( className . startsWith ( \"weblogic.utils.classloaders.\" ) ) { // 该死的 WebLogic，只能特殊处理 // GenericClassLoader, FilteringClassLoader, ChangeAwareClassLoader try { Method method = loader . getClass ( ) . getMethod ( \"getClassPath\" ) ; Object result = method . invoke ( loader ) ; if ( result != null ) { String [ ] paths = StringUtils . split ( result . toString ( ) , File . pathSeparatorChar ) ; for ( String path : paths ) { urls . add ( URLUtils . fromFile ( path ) ) ; } } } catch ( NoSuchMethodException e ) { } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } else if ( className . startsWith ( \"org.jboss.modules.ModuleClassLoader\" ) ) { // 该死的 Jboss/Wildfly 8，只能特殊处理 try { Set < URL > urlSet = JBossModuleUtils . getClasspathURLs ( loader , false ) ; urls . addAll ( urlSet ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } loader = loader . getParent ( ) ; } // moved jsp classpath from ServletContext.attributes to System.properties String jsp_classpath = System . getProperty ( \"org.apache.catalina.jsp_classpath\" ) ; String classpath = System . getProperty ( \"java.class.path\" ) ; classpath = StringUtils . trimToEmpty ( classpath ) + File . pathSeparatorChar + StringUtils . trimToEmpty ( jsp_classpath ) ; if ( classpath . length ( ) > 1 ) { String [ ] paths = StringUtils . split ( classpath , File . pathSeparatorChar ) ; for ( String path : paths ) { path = path . trim ( ) ; if ( path . length ( ) > 0 ) { URL url = URLUtils . fromFile ( path ) ; urls . add ( url ) ; } } } // 添加包含所有的 META-INF/MANIFEST.MF 的 jar 文件 try { Enumeration < URL > paths = classLoader . getResources ( \"META-INF/MANIFEST.MF\" ) ; while ( paths . hasMoreElements ( ) ) { URL url = paths . nextElement ( ) ; File file = URLUtils . toFileObject ( url ) ; urls . add ( file . toURI ( ) . toURL ( ) ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } // 删除 jdk 自带的 jar Iterator < URL > it = urls . iterator ( ) ; while ( it . hasNext ( ) ) { String path = it . next ( ) . getPath ( ) ; if ( path . contains ( \"/jre/lib/\" ) ) { it . remove ( ) ; } } return urls ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据 classLoader 获取指定 package 对应的 URLs . [CODESPLIT] public static Collection < URL > getClasspathURLs ( ClassLoader classLoader , String packageName ) { if ( packageName == null ) { throw new IllegalArgumentException ( \"PackageName must be not null.\" ) ; } Collection < URL > urls = new ArrayList < URL > ( ) ; String dirname = packageName . replace ( ' ' , ' ' ) ; try { Enumeration < URL > dirs = classLoader . getResources ( dirname ) ; while ( dirs . hasMoreElements ( ) ) { urls . add ( dirs . nextElement ( ) ) ; } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return urls ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a singleton fully initialized instance of an { @link PasswordAuthenticator } class to use for JAAS authentication . <p > Retrieving a singleton by this method will cause the factory to keep state and store a reference to the singleton for later use . You may reset the factory state using the { @code reset () } method to retrieve a new / different singleton the next time this method is called .. <p > Note that any properties of the singleton ( e . g . configuration ) cannot necessarily be changed easily . You may call the singleton s { @code init () } method but depending on the implementation provided by the respective class this may or may not have the expected effect . <p > If you need tight control over the singleton including its lifecycle and configuration or you require more than one singleton that are different in their internal state ( e . g . with different configurations ) then you should create such objects with the { @code getInstance () } method and maintain their state as singletons in your application s business logic . <p > Classes implementing the { @link PasswordAuthenticator } interface <b > must< / b > be thread safe . [CODESPLIT] @ SuppressWarnings ( \"PMD.NonThreadSafeSingleton\" ) public static PasswordAuthenticator getSingleton ( final String className , final CommonProperties properties ) throws FactoryException { Validate . notBlank ( className , \"The validated character sequence 'className' is null or empty\" ) ; Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; if ( passwordAuthenticatorInstance == null ) { synchronized ( PasswordAuthenticatorFactory . class ) { if ( passwordAuthenticatorInstance == null ) { passwordAuthenticatorInstance = getInstance ( className , properties ) ; } } } return passwordAuthenticatorInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns current thread s context class loader [CODESPLIT] public static ClassLoader getDefault ( ) { ClassLoader loader = null ; try { loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; } catch ( Exception e ) { } if ( loader == null ) { loader = ClassLoaderUtils . class . getClassLoader ( ) ; if ( loader == null ) { loader = ClassLoader . getSystemClassLoader ( ) ; } } return loader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用默认的 ClassLoader 去载入类 . [CODESPLIT] public static Class < ? > loadClass ( final String qualifiedClassName , ClassLoader loader ) { try { return loadClassEx ( qualifiedClassName , loader ) ; } catch ( ClassNotFoundException e ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "使用指定的 ClassLoader 去载入类 . [CODESPLIT] public static Class < ? > loadClassEx ( final String qualifiedClassName , final ClassLoader classLoader ) throws ClassNotFoundException { Validate . notNull ( qualifiedClassName , \"qualifiedClassName must be not null\" ) ; ClassLoader loader = ( classLoader == null ) ? getDefault ( ) : classLoader ; // 尝试基本类型 if ( abbreviationMap . containsKey ( qualifiedClassName ) ) { String className = ' ' + abbreviationMap . get ( qualifiedClassName ) ; return Class . forName ( className , false , loader ) . getComponentType ( ) ; } // 尝试用 Class.forName() try { String className = getCanonicalClassName ( qualifiedClassName ) ; return Class . forName ( className , false , loader ) ; } catch ( ClassNotFoundException e ) { } // 尝试当做一个内部类去识别 if ( qualifiedClassName . indexOf ( ' ' ) == - 1 ) { int ipos = qualifiedClassName . lastIndexOf ( ' ' ) ; if ( ipos > 0 ) { try { String className = qualifiedClassName . substring ( 0 , ipos ) + ' ' + qualifiedClassName . substring ( ipos + 1 ) ; className = getCanonicalClassName ( className ) ; return Class . forName ( className , false , loader ) ; } catch ( ClassNotFoundException e ) { } } } throw new ClassNotFoundException ( qualifiedClassName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将 Java 类名转为 { [CODESPLIT] public static String getCanonicalClassName ( String qualifiedClassName ) { Validate . notNull ( qualifiedClassName , \"qualifiedClassName must be not null\" ) ; String name = StringUtils . deleteWhitespace ( qualifiedClassName ) ; if ( name . endsWith ( \"[]\" ) ) { StringBuilder sb = new StringBuilder ( ) ; while ( name . endsWith ( \"[]\" ) ) { name = name . substring ( 0 , name . length ( ) - 2 ) ; sb . append ( ' ' ) ; } String abbreviation = abbreviationMap . get ( name ) ; if ( abbreviation != null ) { sb . append ( abbreviation ) ; } else { sb . append ( ' ' ) . append ( name ) . append ( ' ' ) ; } name = sb . toString ( ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the resource with the given name . [CODESPLIT] public static URL getResource ( String name , ClassLoader classLoader ) { Validate . notNull ( name , \"resourceName must be not null\" ) ; if ( name . startsWith ( \"/\" ) ) { name = name . substring ( 1 ) ; } if ( classLoader != null ) { URL url = classLoader . getResource ( name ) ; if ( url != null ) { return url ; } } ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( loader != null && loader != classLoader ) { URL url = loader . getResource ( name ) ; if ( url != null ) { return url ; } } return ClassLoader . getSystemResource ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an input stream for reading the specified resource . [CODESPLIT] public static InputStream getResourceAsStream ( String name , ClassLoader classLoader ) throws IOException { URL url = getResource ( name , classLoader ) ; if ( url != null ) { return url . openStream ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an input stream for reading the specified class . [CODESPLIT] public static InputStream getClassAsStream ( Class < ? > clazz ) throws IOException { return getResourceAsStream ( getClassFileName ( clazz ) , clazz . getClassLoader ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取一个 class 所代表的文件名 [CODESPLIT] public static String getClassFileName ( Class < ? > clazz ) { if ( clazz . isArray ( ) ) { clazz = clazz . getComponentType ( ) ; } return getClassFileName ( clazz . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize all fields of this URI from another URI . [CODESPLIT] private void initialize ( URI p_other ) { m_scheme = p_other . getScheme ( ) ; m_userinfo = p_other . getUserinfo ( ) ; m_host = p_other . getHost ( ) ; m_port = p_other . m_port ; n_port = p_other . n_port ; m_path = p_other . getPath ( ) ; m_queryString = p_other . getQueryString ( ) ; m_fragment = p_other . getFragment ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes this URI from a base URI and a URI specification string . See RFC 2396 Section 4 and Appendix B for specifications on parsing the URI and Section 5 for specifications on resolving relative URIs and relative paths . [CODESPLIT] private void initialize ( URI p_base , String p_uriSpec ) throws MalformedURIException { if ( p_base == null && ( p_uriSpec == null || p_uriSpec . length ( ) == 0 ) ) { throw new RelativeURIException ( \"Cannot initialize URI with empty parameters.\" ) ; } // just make a copy of the base if spec is empty\r if ( p_uriSpec == null || p_uriSpec . length ( ) == 0 ) { initialize ( p_base ) ; return ; } String uriSpec = p_uriSpec ; int uriSpecLen = uriSpec . length ( ) ; int index = 0 ; // Check for scheme, which must be before '/', '?' or '#'. Also handle\r // names with DOS drive letters ('D:'), so 1-character schemes are not\r // allowed.\r int colonIdx = uriSpec . indexOf ( ' ' ) ; int slashIdx = uriSpec . indexOf ( ' ' ) ; int queryIdx = uriSpec . indexOf ( ' ' ) ; int fragmentIdx = uriSpec . indexOf ( ' ' ) ; if ( ( colonIdx < 2 ) || ( colonIdx > slashIdx && slashIdx != - 1 ) || ( colonIdx > queryIdx && queryIdx != - 1 ) || ( colonIdx > fragmentIdx && fragmentIdx != - 1 ) ) { // We need to do the relative URI algorithm:\r // jjc: the spec says:\r // 'URI-reference = [ absoluteURI | relativeURI ] [ \"#\" fragment ]'\r // My understanding is that if there is only the fragment\r // then this is a relative URI.\r if ( p_base == null // del jjc: && fragmentIdx != 0\r ) { // Nothing to be relative against.\r throw new RelativeURIException ( \"No scheme found in URI.\" + p_uriSpec ) ; } else { if ( ( ! p_base . isGenericURI ( ) ) && fragmentIdx != 0 ) // Can't be relative against opaque URI (except using the #frag).\r throw new MalformedURIException ( \"Cannot apply relative URI to an opaque URI\" ) ; } } else { initializeScheme ( uriSpec ) ; index = m_scheme . length ( ) + 1 ; } // two slashes means generic URI syntax, so we get the authority\r if ( ( ( index + 1 ) < uriSpecLen ) && ( uriSpec . substring ( index ) . startsWith ( \"//\" ) ) ) { index += 2 ; int startPos = index ; // get authority - everything up to path, query or fragment\r char testChar = ' ' ; while ( index < uriSpecLen ) { testChar = uriSpec . charAt ( index ) ; if ( testChar == ' ' || testChar == ' ' || testChar == ' ' ) { break ; } index ++ ; } // if we found authority, parse it out, otherwise we set the\r // host to empty string\r if ( index > startPos ) { initializeAuthority ( uriSpec . substring ( startPos , index ) ) ; } else { m_host = \"\" ; } } initializePath ( uriSpec . substring ( index ) ) ; // Resolve relative URI to base URI - see RFC 2396 Section 5.2\r // In some cases, it might make more sense to throw an exception\r // (when scheme is specified is the string spec and the base URI\r // is also specified, for example), but we're just following the\r // RFC specifications\r if ( p_base != null ) { // check to see if this is the current doc - RFC 2396 5.2 #2\r // note that this is slightly different from the RFC spec in that\r // we don't include the check for query string being null\r // - this handles cases where the urispec is just a query\r // string or a fragment (e.g. \"?y\" or \"#s\") -\r // see <http://www.ics.uci.edu/~fielding/url/test1.html> which\r // identified this as a bug in the RFC\r if ( m_path . length ( ) == 0 && m_scheme == null && m_host == null ) { m_scheme = p_base . getScheme ( ) ; m_userinfo = p_base . getUserinfo ( ) ; m_host = p_base . getHost ( ) ; m_port = p_base . m_port ; n_port = p_base . getPort ( ) ; m_path = p_base . getPath ( ) ; if ( m_queryString == null ) { m_queryString = p_base . getQueryString ( ) ; } return ; } // check for scheme - RFC 2396 5.2 #3\r // if we found a scheme, it means absolute URI, so we're done\r if ( m_scheme == null ) { m_scheme = p_base . getScheme ( ) ; } else { return ; } // check for authority - RFC 2396 5.2 #4\r // if we found a host, then we've got a network path, so we're done\r if ( m_host == null ) { m_userinfo = p_base . getUserinfo ( ) ; m_host = p_base . getHost ( ) ; m_port = p_base . m_port ; n_port = p_base . getPort ( ) ; } else { return ; } // check for absolute path - RFC 2396 5.2 #5\r if ( m_path . length ( ) > 0 && m_path . startsWith ( \"/\" ) ) { return ; } // if we get to this point, we need to resolve relative path\r // RFC 2396 5.2 #6\r String path = // jjc new String();\r \"/\" ; // jjc ins\r String basePath = p_base . getPath ( ) ; // 6a - get all but the last segment of the base URI path\r if ( basePath != null ) { int lastSlash = basePath . lastIndexOf ( ' ' ) ; if ( lastSlash != - 1 ) { path = basePath . substring ( 0 , lastSlash + 1 ) ; } } // 6b - append the relative URI path\r path = path . concat ( m_path ) ; // 6c - remove all \"./\" where \".\" is a complete path segment\r index = - 1 ; while ( ( index = path . indexOf ( \"/./\" ) ) != - 1 ) { path = path . substring ( 0 , index + 1 ) . concat ( path . substring ( index + 3 ) ) ; } // 6d - remove \".\" if path ends with \".\" as a complete path segment\r if ( path . endsWith ( \"/.\" ) ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } // 6e - remove all \"<segment>/../\" where \"<segment>\" is a complete\r // path segment not equal to \"..\"\r index = 1 ; int segIndex = - 1 ; while ( ( index = path . indexOf ( \"/../\" , index ) ) > 0 ) { segIndex = path . lastIndexOf ( ' ' , index - 1 ) ; if ( segIndex != - 1 && ! path . substring ( segIndex + 1 , index ) . equals ( \"..\" ) ) { path = path . substring ( 0 , segIndex ) . concat ( path . substring ( index + 3 ) ) ; index = segIndex ; } else { index += 4 ; } } // 6f - remove ending \"<segment>/..\" where \"<segment>\" is a\r // complete path segment\r if ( path . endsWith ( \"/..\" ) ) { index = path . length ( ) - 3 ; segIndex = path . lastIndexOf ( ' ' , index - 1 ) ; if ( segIndex != - 1 && ! path . substring ( segIndex + 1 , index ) . equals ( \"..\" ) ) { path = path . substring ( 0 , segIndex + 1 ) ; } } m_path = path ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the scheme for this URI from a URI string spec . [CODESPLIT] private void initializeScheme ( String p_uriSpec ) throws MalformedURIException { int uriSpecLen = p_uriSpec . length ( ) ; int index = p_uriSpec . indexOf ( ' ' ) ; if ( index < 1 ) throw new MalformedURIException ( \"No scheme found in URI.\" ) ; if ( index == uriSpecLen - 1 ) throw new MalformedURIException ( \"A bare scheme name is not a URI.\" ) ; setScheme ( p_uriSpec . substring ( 0 , index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the authority ( userinfo host and port ) for this URI from a URI string spec . [CODESPLIT] private void initializeAuthority ( String p_uriSpec ) throws MalformedURIException { int index = 0 ; int start = 0 ; int end = p_uriSpec . length ( ) ; char testChar = ' ' ; String userinfo = null ; // userinfo is everything up @\r if ( p_uriSpec . indexOf ( ' ' , start ) != - 1 ) { while ( index < end ) { testChar = p_uriSpec . charAt ( index ) ; if ( testChar == ' ' ) { break ; } index ++ ; } userinfo = p_uriSpec . substring ( start , index ) ; index ++ ; } // host is everything up to ':'\r String host = null ; start = index ; while ( index < end ) { testChar = p_uriSpec . charAt ( index ) ; if ( testChar == ' ' ) { break ; } index ++ ; } host = p_uriSpec . substring ( start , index ) ; int port = - 1 ; if ( host . length ( ) > 0 ) { // port\r if ( testChar == ' ' ) { index ++ ; start = index ; while ( index < end ) { index ++ ; } String portStr = p_uriSpec . substring ( start , index ) ; if ( portStr . length ( ) > 0 ) { for ( int i = 0 ; i < portStr . length ( ) ; i ++ ) { if ( ! isDigit ( portStr . charAt ( i ) ) ) { throw new MalformedURIException ( portStr + \" is invalid. Port should only contain digits!\" ) ; } } try { port = Integer . parseInt ( portStr ) ; m_port = portStr ; } catch ( NumberFormatException nfe ) { // can't happen\r } } } } setHost ( host ) ; setPort ( port ) ; setUserinfo ( userinfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the path for this URI from a URI string spec . [CODESPLIT] private void initializePath ( String p_uriSpec ) throws MalformedURIException { if ( p_uriSpec == null ) { throw new MalformedURIException ( \"Cannot initialize path from null string!\" ) ; } int index = 0 ; int start = 0 ; int end = p_uriSpec . length ( ) ; char testChar = ' ' ; // path - everything up to query string or fragment\r while ( index < end ) { testChar = p_uriSpec . charAt ( index ) ; if ( testChar == ' ' || testChar == ' ' ) { break ; } // check for valid escape sequence\r if ( testChar == ' ' ) { if ( index + 2 >= end || ! isHex ( p_uriSpec . charAt ( index + 1 ) ) || ! isHex ( p_uriSpec . charAt ( index + 2 ) ) ) { throw new MalformedURIException ( \"Path contains invalid escape sequence!\" ) ; } } else if ( ! isReservedCharacter ( testChar ) && ! isUnreservedCharacter ( testChar ) ) { throw new MalformedURIException ( \"Path contains invalid character: \" + testChar ) ; } index ++ ; } m_path = p_uriSpec . substring ( start , index ) ; // query - starts with ? and up to fragment or end\r if ( testChar == ' ' ) { index ++ ; start = index ; while ( index < end ) { testChar = p_uriSpec . charAt ( index ) ; if ( testChar == ' ' ) { break ; } if ( testChar == ' ' ) { if ( index + 2 >= end || ! isHex ( p_uriSpec . charAt ( index + 1 ) ) || ! isHex ( p_uriSpec . charAt ( index + 2 ) ) ) { throw new MalformedURIException ( \"Query string contains invalid escape sequence!\" ) ; } } else if ( ! isReservedCharacter ( testChar ) && ! isUnreservedCharacter ( testChar ) ) { throw new MalformedURIException ( \"Query string contains invalid character:\" + testChar ) ; } index ++ ; } m_queryString = p_uriSpec . substring ( start , index ) ; } // fragment - starts with #\r if ( testChar == ' ' ) { index ++ ; start = index ; while ( index < end ) { testChar = p_uriSpec . charAt ( index ) ; if ( testChar == ' ' ) { if ( index + 2 >= end || ! isHex ( p_uriSpec . charAt ( index + 1 ) ) || ! isHex ( p_uriSpec . charAt ( index + 2 ) ) ) { throw new MalformedURIException ( \"Fragment contains invalid escape sequence!\" ) ; } } else if ( ! isReservedCharacter ( testChar ) && ! isUnreservedCharacter ( testChar ) ) { throw new MalformedURIException ( \"Fragment contains invalid character:\" + testChar ) ; } index ++ ; } m_fragment = p_uriSpec . substring ( start , index ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the scheme - specific part for this URI ( everything following the scheme and the first colon ) . See RFC 2396 Section 5 . 2 for spec . [CODESPLIT] public String getSchemeSpecificPart ( ) { StringBuffer schemespec = new StringBuffer ( ) ; if ( m_userinfo != null || m_host != null || m_port != null ) { schemespec . append ( \"//\" ) ; } if ( m_userinfo != null ) { schemespec . append ( m_userinfo ) ; schemespec . append ( ' ' ) ; } if ( m_host != null ) { schemespec . append ( m_host ) ; } if ( m_port != null ) { schemespec . append ( ' ' ) ; schemespec . append ( m_port ) ; } if ( m_path != null ) { schemespec . append ( ( m_path ) ) ; } if ( m_queryString != null ) { schemespec . append ( ' ' ) ; schemespec . append ( m_queryString ) ; } if ( m_fragment != null ) { schemespec . append ( ' ' ) ; schemespec . append ( m_fragment ) ; } return schemespec . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the scheme for this URI . The scheme is converted to lowercase before it is set . [CODESPLIT] private void setScheme ( String p_scheme ) throws MalformedURIException { if ( p_scheme == null ) { throw new MalformedURIException ( \"Cannot set scheme from null string!\" ) ; } if ( ! isConformantSchemeName ( p_scheme ) ) { throw new MalformedURIException ( \"The scheme is not conformant.\" ) ; } m_scheme = p_scheme ; //.toLowerCase();\r }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the userinfo for this URI . If a non - null value is passed in and the host value is null then an exception is thrown . [CODESPLIT] private void setUserinfo ( String p_userinfo ) throws MalformedURIException { if ( p_userinfo == null ) { m_userinfo = null ; } else { if ( m_host == null ) { throw new MalformedURIException ( \"Userinfo cannot be set when host is null!\" ) ; } // userinfo can contain alphanumerics, mark characters, escaped\r // and ';',':','&','=','+','$',','\r int index = 0 ; int end = p_userinfo . length ( ) ; char testChar = ' ' ; while ( index < end ) { testChar = p_userinfo . charAt ( index ) ; if ( testChar == ' ' ) { if ( index + 2 >= end || ! isHex ( p_userinfo . charAt ( index + 1 ) ) || ! isHex ( p_userinfo . charAt ( index + 2 ) ) ) { throw new MalformedURIException ( \"Userinfo contains invalid escape sequence!\" ) ; } } else if ( ! isUnreservedCharacter ( testChar ) && USERINFO_CHARACTERS . indexOf ( testChar ) == - 1 ) { throw new MalformedURIException ( \"Userinfo contains invalid character:\" + testChar ) ; } index ++ ; } } m_userinfo = p_userinfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the host for this URI . If null is passed in the userinfo field is also set to null and the port is set to - 1 . [CODESPLIT] private void setHost ( String p_host ) throws MalformedURIException { if ( p_host == null || p_host . length ( ) == 0 ) { m_host = p_host ; m_userinfo = null ; m_port = null ; n_port = - 1 ; } else if ( ! isWellFormedAddress ( p_host ) ) { throw new MalformedURIException ( \"Host is not a well formed address!\" ) ; } m_host = p_host ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the port for this URI . - 1 is used to indicate that the port is not specified otherwise valid port numbers are between 0 and 65535 . If a valid port number is passed in and the host field is null an exception is thrown . [CODESPLIT] private void setPort ( int p_port ) throws MalformedURIException { if ( p_port >= 0 && p_port <= 65535 ) { if ( m_host == null ) { throw new MalformedURIException ( \"Port cannot be set when host is null!\" ) ; } } else if ( p_port != - 1 ) { throw new MalformedURIException ( \"Invalid port number!\" ) ; } n_port = p_port ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the path for this URI . If the supplied path is null then the query string and fragment are set to null as well . If the supplied path includes a query string and / or fragment these fields will be parsed and set as well . Note that for URIs following the generic URI syntax the path specified should start with a slash . For URIs that do not follow the generic URI syntax this method sets the scheme - specific part . [CODESPLIT] private void setPath ( String p_path ) throws MalformedURIException { if ( p_path == null ) { m_path = null ; m_queryString = null ; m_fragment = null ; } else { initializePath ( p_path ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Append to the end of the path of this URI . If the current path does not end in a slash and the path to be appended does not begin with a slash a slash will be appended to the current path before the new segment is added . Also if the current path ends in a slash and the new segment begins with a slash the extra slash will be removed before the new segment is appended . [CODESPLIT] private void appendPath ( String p_addToPath ) throws MalformedURIException { if ( p_addToPath == null || p_addToPath . length ( ) == 0 ) { return ; } if ( ! isURIString ( p_addToPath ) ) { throw new MalformedURIException ( \"Path contains invalid character!\" ) ; } if ( m_path == null || m_path . length ( ) == 0 ) { if ( p_addToPath . startsWith ( \"/\" ) ) { m_path = p_addToPath ; } else { m_path = \"/\" + p_addToPath ; } } else if ( m_path . endsWith ( \"/\" ) ) { if ( p_addToPath . startsWith ( \"/\" ) ) { m_path = m_path . concat ( p_addToPath . substring ( 1 ) ) ; } else { m_path = m_path . concat ( p_addToPath ) ; } } else { if ( p_addToPath . startsWith ( \"/\" ) ) { m_path = m_path . concat ( p_addToPath ) ; } else { m_path = m_path . concat ( \"/\" + p_addToPath ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the query string for this URI . A non - null value is valid only if this is an URI conforming to the generic URI syntax and the path value is not null . [CODESPLIT] private void setQueryString ( String p_queryString ) throws MalformedURIException { if ( p_queryString == null ) { m_queryString = null ; } else if ( ! isGenericURI ( ) ) { throw new MalformedURIException ( \"Query string can only be set for a generic URI!\" ) ; } else if ( getPath ( ) == null ) { throw new MalformedURIException ( \"Query string cannot be set when path is null!\" ) ; } else if ( ! isURIString ( p_queryString ) ) { throw new MalformedURIException ( \"Query string contains invalid character!\" ) ; } else { m_queryString = p_queryString ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the fragment for this URI . A non - null value is valid only if this is a URI conforming to the generic URI syntax and the path value is not null . [CODESPLIT] public void setFragment ( String p_fragment ) throws MalformedURIException { if ( p_fragment == null ) { m_fragment = null ; } else if ( ! isGenericURI ( ) ) { throw new MalformedURIException ( \"Fragment can only be set for a generic URI!\" ) ; } else if ( getPath ( ) == null ) { throw new MalformedURIException ( \"Fragment cannot be set when path is null!\" ) ; } else if ( ! isURIString ( p_fragment ) ) { throw new MalformedURIException ( \"Fragment contains invalid character!\" ) ; } else { m_fragment = p_fragment ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the URI as a string specification . See RFC 2396 Section 5 . 2 . [CODESPLIT] public String getURIString ( ) { StringBuffer uriSpecString = new StringBuffer ( ) ; if ( m_scheme != null ) { uriSpecString . append ( m_scheme ) ; uriSpecString . append ( ' ' ) ; } uriSpecString . append ( getSchemeSpecificPart ( ) ) ; return uriSpecString . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether a string is syntactically capable of representing a valid IPv4 address or the domain name of a network host . A valid IPv4 address consists of four decimal digit groups separated by a . . A hostname consists of domain labels ( each of which must begin and end with an alphanumeric but may contain - ) separated & by a . . See RFC 2396 Section 3 . 2 . 2 . [CODESPLIT] public static boolean isWellFormedAddress ( String p_address ) { if ( p_address == null ) { return false ; } String address = p_address ; int addrLength = address . length ( ) ; if ( addrLength == 0 || addrLength > 255 ) { return false ; } if ( address . startsWith ( \".\" ) || address . startsWith ( \"-\" ) ) { return false ; } // rightmost domain label starting with digit indicates IP address\r // since top level domain label can only start with an alpha\r // see RFC 2396 Section 3.2.2\r int index = address . lastIndexOf ( ' ' ) ; if ( address . endsWith ( \".\" ) ) { index = address . substring ( 0 , index ) . lastIndexOf ( ' ' ) ; } if ( index + 1 < addrLength && isDigit ( p_address . charAt ( index + 1 ) ) ) { char testChar ; int numDots = 0 ; // make sure that 1) we see only digits and dot separators, 2) that\r // any dot separator is preceded and followed by a digit and\r // 3) that we find 3 dots\r for ( int i = 0 ; i < addrLength ; i ++ ) { testChar = address . charAt ( i ) ; if ( testChar == ' ' ) { if ( ! isDigit ( address . charAt ( i - 1 ) ) || ( i + 1 < addrLength && ! isDigit ( address . charAt ( i + 1 ) ) ) ) { return false ; } numDots ++ ; } else if ( ! isDigit ( testChar ) ) { return false ; } } if ( numDots != 3 ) { return false ; } } else { // domain labels can contain alphanumerics and '-\"\r // but must start and end with an alphanumeric\r char testChar ; for ( int i = 0 ; i < addrLength ; i ++ ) { testChar = address . charAt ( i ) ; if ( testChar == ' ' ) { if ( ! isAlphanum ( address . charAt ( i - 1 ) ) ) { return false ; } if ( i + 1 < addrLength && ! isAlphanum ( address . charAt ( i + 1 ) ) ) { return false ; } } else if ( ! isAlphanum ( testChar ) && testChar != ' ' ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- byte [CODESPLIT] public static byte [ ] encodeToByte ( String s ) { try { return encodeToByte ( s . getBytes ( ENCODING ) , false ) ; } catch ( UnsupportedEncodingException ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------- string [CODESPLIT] public static String encodeToString ( String s ) { try { return new String ( encodeToChar ( s . getBytes ( ENCODING ) , false ) ) ; } catch ( UnsupportedEncodingException ignore ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Write standard field of entity into a stream ( writer - file or pass it through network ) . < / p > [CODESPLIT] @ Override public final void write ( final Map < String , Object > pAddParam , final Object pField , final String pFieldName , final Writer pWriter ) throws Exception { String fieldValue ; if ( pField == null ) { fieldValue = \"NULL\" ; } else if ( Enum . class . isAssignableFrom ( pField . getClass ( ) ) ) { fieldValue = String . valueOf ( ( ( Enum ) pField ) . ordinal ( ) ) ; } else if ( pField . getClass ( ) == Date . class ) { fieldValue = String . valueOf ( ( ( Date ) pField ) . getTime ( ) ) ; } else { fieldValue = pField . toString ( ) ; if ( pField instanceof String ) { fieldValue = getUtilXml ( ) . escapeXml ( fieldValue ) ; } } pWriter . write ( \" \" + pFieldName + \"=\\\"\" + fieldValue + \"\\\"\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support ? as parameter [CODESPLIT] protected static PreparedStatement createByIterator ( Connection conn , String sql , Iterator < ? > parameters ) throws SQLException { PreparedStatement ps = conn . prepareStatement ( sql ) ; if ( parameters != null ) { int index = 1 ; while ( parameters . hasNext ( ) ) { Object parameter = parameters . next ( ) ; if ( parameter == null ) { ps . setObject ( index , null ) ; } else { ps . setObject ( index , parameter ) ; } index ++ ; } } return ps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Support : name as parameter and Array or Collection type [CODESPLIT] protected static PreparedStatement createByMap ( Connection conn , String sql , Map < String , ? > parameters ) throws SQLException { StringBuffer sb = new StringBuffer ( ) ; List < Object > params = new ArrayList < Object > ( ) ; Matcher m = namedParameterPattern . matcher ( sql ) ; while ( m . find ( ) ) { String key = m . group ( 1 ) ; Object value = parameters . get ( key ) ; if ( value == null ) { params . add ( null ) ; m . appendReplacement ( sb , \"?\" ) ; } else if ( value instanceof Object [ ] ) { Object [ ] array = ( Object [ ] ) value ; if ( array . length == 0 ) { params . add ( null ) ; m . appendReplacement ( sb , \"?\" ) ; } else { for ( Object one : array ) { params . add ( one ) ; } m . appendReplacement ( sb , StringUtils . repeat ( \"?\" , \",\" , array . length ) ) ; } } else if ( value instanceof Collection ) { Collection < ? > collection = ( Collection < ? > ) value ; if ( collection . size ( ) == 0 ) { params . add ( null ) ; m . appendReplacement ( sb , \"?\" ) ; } else { for ( Object one : collection ) { params . add ( one ) ; } m . appendReplacement ( sb , StringUtils . repeat ( \"?\" , \",\" , collection . size ( ) ) ) ; } } else { params . add ( value ) ; m . appendReplacement ( sb , \"?\" ) ; } } m . appendTail ( sb ) ; return createByIterator ( conn , sb . toString ( ) , params . iterator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates new MuffinManager . [CODESPLIT] public void init ( Object applet ) { try { m_ps = ( PersistenceService ) ServiceManager . lookup ( \"javax.jnlp.PersistenceService\" ) ; m_bs = ( BasicService ) ServiceManager . lookup ( \"javax.jnlp.BasicService\" ) ; m_strCodeBase = m_bs . getCodeBase ( ) . toString ( ) ; } catch ( UnavailableServiceException e ) { m_ps = null ; m_bs = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the current value for this muffin . [CODESPLIT] public String getMuffin ( String strParam ) { try { URL url = new URL ( m_strCodeBase + strParam ) ; FileContents fc = m_ps . get ( url ) ; if ( fc == null ) return null ; // read in the contents of a muffin byte [ ] buf = new byte [ ( int ) fc . getLength ( ) ] ; InputStream is = fc . getInputStream ( ) ; int pos = 0 ; while ( ( pos = is . read ( buf , pos , buf . length - pos ) ) > 0 ) { // just loop } is . close ( ) ; String strValue = new String ( buf , ENCODING ) ; return strValue ; } catch ( Exception ex ) { // Return null for any exception } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the current value for this muffin . [CODESPLIT] public void setMuffin ( String strParam , String strValue ) { FileContents fc = null ; URL url = null ; try { url = new URL ( m_strCodeBase + strParam ) ; } catch ( Exception ex ) { return ; } try { fc = m_ps . get ( url ) ; fc . getMaxLength ( ) ; // This will throw an exception if there is no muffin yet. } catch ( Exception ex ) { fc = null ; } try { if ( fc == null ) { m_ps . create ( url , 100 ) ; fc = m_ps . get ( url ) ; } // don't append if ( strValue != null ) { OutputStream os = fc . getOutputStream ( false ) ; byte [ ] buf = strValue . getBytes ( ENCODING ) ; os . write ( buf ) ; os . close ( ) ; m_ps . setTag ( url , PersistenceService . DIRTY ) ; } else m_ps . delete ( url ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; // Return null for any exception } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get data from the system clipboard . [CODESPLIT] public Transferable getClipboardContents ( ) { if ( ( clipboardReadStatus & CLIPBOARD_DISABLED ) == CLIPBOARD_DISABLED ) return null ; // Rejected it last time, don't ask again clipboardReadStatus = CLIPBOARD_DISABLED ; if ( cs == null ) { try { cs = ( ClipboardService ) ServiceManager . lookup ( \"javax.jnlp.ClipboardService\" ) ; } catch ( UnavailableServiceException e ) { cs = null ; } } if ( cs != null ) { // get the contents of the system clipboard and print them  Transferable tr = cs . getContents ( ) ; if ( tr != null ) clipboardReadStatus = CLIPBOARD_ENABLED ; return tr ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set the global clipboard contents . [CODESPLIT] public boolean setClipboardContents ( Transferable data ) { if ( data == null ) return false ; if ( ( clipboardWriteStatus & CLIPBOARD_DISABLED ) == CLIPBOARD_DISABLED ) return false ; // Rejected it last time, don't ask again clipboardWriteStatus = CLIPBOARD_ENABLED ; if ( cs == null ) { try { cs = ( ClipboardService ) ServiceManager . lookup ( \"javax.jnlp.ClipboardService\" ) ; } catch ( UnavailableServiceException e ) { cs = null ; } } if ( cs != null ) { // set the system clipboard contents to a string selection  try { cs . setContents ( data ) ; clipboardWriteStatus = CLIPBOARD_ENABLED ; return true ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace the clipboard cut / cut / paste command with this command . [CODESPLIT] public boolean replaceClipboardAction ( JComponent component , String actionName ) { Action action = ( Action ) component . getActionMap ( ) . get ( actionName ) ; if ( action != null ) component . getActionMap ( ) . put ( actionName , new LinkedClipboardAction ( actionName , action ) ) ; return ( action != null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Open this file . [CODESPLIT] public InputStream openFileStream ( String pathHint , String [ ] extensions ) { if ( fos == null ) { try { fos = ( FileOpenService ) ServiceManager . lookup ( \"javax.jnlp.FileOpenService\" ) ; } catch ( UnavailableServiceException e ) { fos = null ; } } if ( fos != null ) { try { // ask user to select a file through this service  FileContents fc = fos . openFileDialog ( pathHint , extensions ) ; return fc . getInputStream ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discovers the registered services of the given class . [CODESPLIT] public static < T extends Service > Map < String , T > loadServicesByType ( Class < T > clazz ) { ServiceLoader < T > loader = ServiceLoader . load ( clazz ) ; Iterator < T > it = loader . iterator ( ) ; Map < String , T > ret = new HashMap < String , T > ( ) ; while ( it . hasNext ( ) ) { T op = it . next ( ) ; ret . put ( op . getId ( ) , op ) ; if ( op instanceof ParametrizedOperation ) addParametrizedService ( op . getId ( ) , ( ParametrizedOperation ) op ) ; if ( op instanceof ScriptObject ) addScriptObject ( ( ( ScriptObject ) op ) . getVarName ( ) , ( ScriptObject ) op ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the operation parametres based on a map of values . [CODESPLIT] public static void setServiceParams ( ParametrizedOperation op , Map < String , Object > params ) { if ( params != null ) { for ( Map . Entry < String , Object > entry : params . entrySet ( ) ) { op . setParam ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the values of all the parametres of the given operation . [CODESPLIT] public static Map < String , Object > getServiceParams ( ParametrizedOperation op ) { Map < String , Object > ret = new HashMap < String , Object > ( ) ; for ( Parameter param : op . getParams ( ) ) { ret . put ( param . getName ( ) , op . getParam ( param . getName ( ) ) ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a parametrized service based on its ID . [CODESPLIT] public static ParametrizedOperation findParmetrizedService ( String id ) { if ( parametrizedServices == null ) return null ; else return parametrizedServices . get ( id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a service in a collection of services based on its class . [CODESPLIT] public static < T > T findByClass ( Collection < ? > services , Class < T > clazz ) { for ( Object serv : services ) { if ( clazz . isInstance ( serv ) ) return clazz . cast ( serv ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rebuilds the { [CODESPLIT] public static void debug ( ) { service = new ServiceBuilder ( ) . debug ( ) . provider ( CubeSensorsAuthApi . class ) . apiKey ( CubeSensorsProperties . getAppKey ( ) ) . apiSecret ( CubeSensorsProperties . getAppSecret ( ) ) . signatureType ( SignatureType . QueryString ) . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the results of a query and handles any errors . [CODESPLIT] private < T > T parseQuery ( final String response , final Class < T > responseClass ) { T queryResponse ; try { /*\r\n\t\t\t * Possible exceptions:\r\n\t\t\t *\r\n\t\t\t * IOException - if the underlying input source has problems during parsing\r\n\t\t\t *\r\n\t\t\t * JsonParseException - if parser has problems parsing content\r\n\t\t\t *\r\n\t\t\t * JsonMappingException - if the parser does not have any more content to map (note: Json \"null\" value is considered content; enf-of-stream not)\r\n\t\t\t */ queryResponse = MAPPER . readValue ( response , responseClass ) ; } catch ( JsonParseException | JsonMappingException e ) { try { final ErrorResponse error = MAPPER . readValue ( response , ErrorResponse . class ) ; LOGGER . error ( \"Query returned an error: {}\" , error ) ; return null ; } catch ( final IOException e1 ) { LOGGER . error ( \"Failed to read error response.\" , e1 ) ; } LOGGER . error ( \"Error reading response.\" , e ) ; return null ; } catch ( final IOException e ) { LOGGER . error ( \"Error reading response.\" , e ) ; return null ; } return queryResponse ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the { [CODESPLIT] private Device extractDevice ( final JsonDevice device ) { final Map < ExtraMapping , String > extras = new EnumMap <> ( ExtraMapping . class ) ; final Set < String > keys = new HashSet <> ( device . extra . keySet ( ) ) ; for ( final ExtraMapping extra : ExtraMapping . values ( ) ) { extras . put ( extra , device . extra . get ( extra . name ( ) ) ) ; if ( keys . contains ( extra . name ( ) ) ) { keys . remove ( extra . name ( ) ) ; } else { LOGGER . debug ( \"\\\"extra\\\" missing key \\\"{}\\\": {}\" , extra . name ( ) , device . extra . toString ( ) ) ; } } for ( final String key : keys ) { LOGGER . debug ( \"Unexpected key in \\\"extra\\\": {}\" , key ) ; } return new Device ( device , extras ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Queries for a list of states over the time span specified . Leaving a field { @code null } will default to the API defaults . [CODESPLIT] public List < State > getSpan ( final String uid , final ZonedDateTime start , final ZonedDateTime end , final Integer resolution ) { final String queryUrl = RESOURCES_ROOT + DEVICES_PATH + uid + \"/span\" ; LOGGER . trace ( \"Querying: {}\" , queryUrl ) ; final OAuthRequest request = new OAuthRequest ( Verb . GET , queryUrl ) ; request . getHeaders ( ) . put ( HTTP_HEADER_ACCEPT , MEDIA_TYPE_APPLICATION_JSON ) ; if ( start != null ) { final ZonedDateTime startUtc = start . withZoneSameInstant ( ZoneId . of ( \"Z\" ) ) . truncatedTo ( ChronoUnit . SECONDS ) ; request . addQuerystringParameter ( \"start\" , startUtc . toString ( ) ) ; LOGGER . trace ( \"Adding querystring parameter {}={}\" , \"start\" , startUtc ) ; } if ( end != null ) { final ZonedDateTime endUtc = end . withZoneSameInstant ( ZoneId . of ( \"Z\" ) ) . truncatedTo ( ChronoUnit . SECONDS ) ; request . addQuerystringParameter ( \"end\" , endUtc . toString ( ) ) ; LOGGER . trace ( \"Adding querystring parameter {}={}\" , \"end\" , endUtc ) ; } if ( resolution != null ) { request . addQuerystringParameter ( \"resolution\" , resolution . toString ( ) ) ; LOGGER . trace ( \"Adding querystring parameter {}={}\" , \"resolution\" , resolution ) ; } service . signRequest ( accessToken , request ) ; final Response response = request . send ( ) ; LOGGER . trace ( \"Response: {}\" , response . getBody ( ) ) ; if ( ! response . isSuccessful ( ) ) { throw new CubeSensorsException ( response . getBody ( ) ) ; } final JsonSpanResponse queryResponse = parseQuery ( response . getBody ( ) , JsonSpanResponse . class ) ; if ( queryResponse == null ) { return new ArrayList <> ( ) ; } final List < State > states = StateParser . parseState ( queryResponse . fieldList , queryResponse . results ) ; LOGGER . debug ( \"Retrieved {} states.\" , states . size ( ) ) ; return states ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepares next chunk to match new size . The minimal length of new chunk is <code > minChunkLen< / code > . [CODESPLIT] private void needNewBuffer ( int newSize ) { int delta = newSize - size ; int newBufferSize = Math . max ( minChunkLen , delta ) ; currentBufferIndex ++ ; currentBuffer = ( E [ ] ) new Object [ newBufferSize ] ; offset = 0 ; // add buffer if ( currentBufferIndex >= buffers . length ) { int newLen = buffers . length << 1 ; E [ ] [ ] newBuffers = ( E [ ] [ ] ) new Object [ newLen ] [  ] ; System . arraycopy ( buffers , 0 , newBuffers , 0 , buffers . length ) ; buffers = newBuffers ; } buffers [ currentBufferIndex ] = currentBuffer ; buffersCount ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends single <code > E< / code > to buffer . [CODESPLIT] public FastBuffer < E > append ( E element ) { if ( ( currentBuffer == null ) || ( offset == currentBuffer . length ) ) { needNewBuffer ( size + 1 ) ; } currentBuffer [ offset ] = element ; offset ++ ; size ++ ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastBuffer < E > append ( FastBuffer < E > buff ) { if ( buff . size == 0 ) { return this ; } for ( int i = 0 ; i < buff . currentBufferIndex ; i ++ ) { append ( buff . buffers [ i ] ) ; } append ( buff . currentBuffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates <code > E< / code > array from buffered content . [CODESPLIT] public E [ ] toArray ( ) { int pos = 0 ; E [ ] array = ( E [ ] ) new Object [ size ] ; if ( currentBufferIndex == - 1 ) { return array ; } for ( int i = 0 ; i < currentBufferIndex ; i ++ ) { int len = buffers [ i ] . length ; System . arraycopy ( buffers [ i ] , 0 , array , pos , len ) ; pos += len ; } System . arraycopy ( buffers [ currentBufferIndex ] , 0 , array , pos , offset ) ; return array ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an iterator over buffer elements . [CODESPLIT] @ Override public Iterator < E > iterator ( ) { return new Iterator < E > ( ) { int iteratorIndex ; int iteratorBufferIndex ; int iteratorOffset ; @ Override public boolean hasNext ( ) { return iteratorIndex < size ; } @ Override public E next ( ) { if ( iteratorIndex >= size ) { throw new NoSuchElementException ( ) ; } E [ ] buf = buffers [ iteratorBufferIndex ] ; E result = buf [ iteratorOffset ] ; // increment iteratorIndex ++ ; iteratorOffset ++ ; if ( iteratorOffset >= buf . length ) { iteratorOffset = 0 ; iteratorBufferIndex ++ ; } return result ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format xml { @link OutputFormat#createPrettyPrint () } [CODESPLIT] public static String formatPretty ( String xmlStr , String enc ) { return formatPretty ( xmlStr , enc , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format xml { @link OutputFormat#createPrettyPrint () } [CODESPLIT] public static String formatPretty ( String xmlStr , String enc , boolean isSuppressDeclaration ) { if ( CommUtil . isBlank ( xmlStr ) ) return xmlStr ; if ( enc == null ) enc = ENCODING ; OutputFormat formater = OutputFormat . createPrettyPrint ( ) ; formater . setEncoding ( enc ) ; formater . setSuppressDeclaration ( isSuppressDeclaration ) ; return format ( xmlStr , formater ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format xml { @link OutputFormat#createCompactFormat () } [CODESPLIT] public static String formatCompact ( String xmlStr , String enc ) { return formatCompact ( xmlStr , enc , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format xml { @link OutputFormat#createCompactFormat () } [CODESPLIT] public static String formatCompact ( String xmlStr , String enc , boolean isSuppressDeclaration ) { if ( CommUtil . isBlank ( xmlStr ) ) return xmlStr ; if ( enc == null ) enc = ENCODING ; OutputFormat formater = OutputFormat . createCompactFormat ( ) ; formater . setEncoding ( enc ) ; formater . setSuppressDeclaration ( isSuppressDeclaration ) ; return format ( xmlStr , formater ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Format xml [CODESPLIT] public static String format ( String xmlStr , OutputFormat formater ) { if ( CommUtil . isBlank ( xmlStr ) ) return xmlStr ; SAXReader reader = new SAXReader ( ) ; StringReader sr = new StringReader ( xmlStr ) ; Document doc ; XMLWriter writer = null ; StringWriter sw = new StringWriter ( ) ; try { doc = reader . read ( sr ) ; writer = new XMLWriter ( sw , formater ) ; writer . write ( doc ) ; return sw . toString ( ) ; } catch ( DocumentException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( IOException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException ignored ) { } } } return xmlStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain xml file encoding attribute [CODESPLIT] public static String getEncoding ( String xmlStr ) { String result ; String xml = xmlStr . trim ( ) ; if ( xml . startsWith ( \"<?xml\" ) ) { int end = xml . indexOf ( \"?>\" ) ; int encIndex = xml . indexOf ( \"encoding=\" ) ; if ( encIndex != - 1 ) { String sub = xml . substring ( encIndex + 9 , end ) ; result = CommUtil . substringBetween ( sub , \"\\\"\" , \"\\\"\" ) ; return result ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bean to xml . <p > Using XStream library from serialize objects to XML . < / p > example : <pre > XAlias [] xa = { new XAlias ( Foo Foo . class ) } ; XAliasField [] xaf = { new XAliasField ( Bar Bar . class bar ) } ; XAliasAttribute [] xaa = { new XAliasAttribute ( Name User . class name ) } ; XOmitField [] xf = { new XOmitField ( V . class v ) } [CODESPLIT] public static < T > String toXml ( T obj , XAlias [ ] xAlias , XAliasField [ ] xAliasFields , XAliasAttribute [ ] xAliasAttributes , XOmitField [ ] xOmitFields ) { return toXml ( obj , xAlias , xAliasFields , xAliasAttributes , xOmitFields , null , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bean to xml . <p > Using XStream library from serialize objects to XML . < / p > example : <pre > XAlias [] xa = { new XAlias ( Foo Foo . class ) } ; XAliasField [] xaf = { new XAliasField ( Bar Bar . class bar ) } ; XAliasAttribute [] xaa = { new XAliasAttribute ( Name User . class name ) } ; XOmitField [] xf = { new XOmitField ( V . class v ) } XImplicitCollection [] xic = null ; XImmutableType [] xit = null ; XConverter [] xc = null ; then toXml ( bean xa xaf xaa xf xic xit xc ) ; < / pre > <b > Note : XStream Mode is { @link XStream#NO_REFERENCES } < / b > [CODESPLIT] public static < T > String toXml ( T obj , XAlias [ ] xAlias , XAliasField [ ] xAliasFields , XAliasAttribute [ ] xAliasAttributes , XOmitField [ ] xOmitFields , XImplicitCollection [ ] xImplicitCollection , XImmutableType [ ] xImmutableTypes , XConverter [ ] xConverters ) { return ( String ) parse ( 0 , XStream . NO_REFERENCES , obj , xAlias , xAliasFields , xAliasAttributes , xOmitFields , xImplicitCollection , xImmutableTypes , xConverters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bean to xml . <p > Using XStream library from xml to serialize objects . < / p > example : <pre > XAlias [] xa = { new XAlias ( Foo Foo . class ) } ; XAliasField [] xaf = { new XAliasField ( Bar Bar . class bar ) } ; XAliasAttribute [] xaa = { new XAliasAttribute ( Name User . class name ) } ; XOmitField [] xf = { new XOmitField ( V . class v ) } [CODESPLIT] public static Object toBean ( String xmlStr , XAlias [ ] xAlias , XAliasField [ ] xAliasFields , XAliasAttribute [ ] xAliasAttributes , XOmitField [ ] xOmitFields ) { return toBean ( xmlStr , xAlias , xAliasFields , xAliasAttributes , xOmitFields , null , null , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bean to xml . <p > Using XStream library from xml to serialize objects . < / p > example : <pre > XAlias [] xa = { new XAlias ( Foo Foo . class ) } ; XAliasField [] xaf = { new XAliasField ( Bar Bar . class bar ) } ; XAliasAttribute [] xaa = { new XAliasAttribute ( Name User . class name ) } ; XOmitField [] xf = { new XOmitField ( V . class v ) } ; XImplicitCollection [] xic = null ; XImmutableType [] xit = null ; XConverter [] xc = null ; then toBean ( xmlStr xa xaf xaa xf xic xit xc ) ; < / pre > <b > Note : XStream Mode is { @link XStream#ID_REFERENCES } < / b > [CODESPLIT] public static Object toBeanWithIdRef ( String xmlStr , XAlias [ ] xAlias , XAliasField [ ] xAliasFields , XAliasAttribute [ ] xAliasAttributes , XOmitField [ ] xOmitFields , XImplicitCollection [ ] xImplicitCollection , XImmutableType [ ] xImmutableTypes , XConverter [ ] xConverters ) { return parse ( 1 , XStream . ID_REFERENCES , xmlStr , xAlias , xAliasFields , xAliasAttributes , xOmitFields , xImplicitCollection , xImmutableTypes , xConverters ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parser [CODESPLIT] private static Object parse ( int parseMod , int mode , Object value , XAlias [ ] xAlias , XAliasField [ ] xAliasFields , XAliasAttribute [ ] xAliasAttributes , XOmitField [ ] xOmitFields , XImplicitCollection [ ] xImplicitCollection , XImmutableType [ ] xImmutableTypes , XConverter [ ] xConverters ) { if ( value == null ) { return null ; } if ( value instanceof String ) { if ( value . equals ( \"\" ) ) { return null ; } } final XStream xstream = new XStream ( ) ; xstream . setMode ( mode ) ; initXstream ( xstream , xAlias , xAliasFields , xAliasAttributes , xOmitFields , xImplicitCollection , xImmutableTypes , xConverters ) ; if ( parseMod == 0 ) { return xstream . toXML ( value ) ; } else { return xstream . fromXML ( ( String ) value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "XStream Alias [CODESPLIT] protected static void initXstream ( XStream xstream , XAlias [ ] xAlias , XAliasField [ ] xAliasFields , XAliasAttribute [ ] xAliasAttributes , XOmitField [ ] xOmitFields , XImplicitCollection [ ] xImplicitCollection , XImmutableType [ ] xImmutableTypes , XConverter [ ] xConverters ) { if ( xOmitFields != null ) { for ( XOmitField xof : xOmitFields ) { xstream . omitField ( xof . classType , xof . fieldName ) ; } } if ( xImplicitCollection != null ) { for ( XImplicitCollection xic : xImplicitCollection ) { xstream . addImplicitCollection ( xic . ownerType , xic . fieldName , xic . itemFieldName , xic . itemType ) ; } } if ( xImmutableTypes != null ) { for ( XImmutableType xit : xImmutableTypes ) { xstream . addImmutableType ( xit . type ) ; } } if ( xConverters != null ) { for ( XConverter xc : xConverters ) { xstream . registerConverter ( xc . converter , xc . priority ) ; } } if ( xAlias != null ) { for ( XAlias xa : xAlias ) { xstream . alias ( xa . aliasName , xa . classType ) ; } } if ( xAliasFields != null ) { for ( XAliasField xaf : xAliasFields ) { xstream . aliasField ( xaf . aliasName , xaf . fieldType , xaf . fieldName ) ; } } if ( xAliasAttributes != null ) { for ( XAliasAttribute xaa : xAliasAttributes ) { xstream . useAttributeFor ( xaa . attributeType , xaa . attributeName ) ; xstream . aliasAttribute ( xaa . attributeType , xaa . attributeName , xaa . aliasName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "url pattern = JdbcLog : [ DriverClassName ] : ConnectionUrl [CODESPLIT] private String getDriverClassName ( String url ) { String driverClassName = null ; if ( url . startsWith ( CONNECTION_URL_SUFFIX ) ) { url = url . substring ( CONNECTION_URL_SUFFIX . length ( ) ) ; driverClassName = url . substring ( 0 , url . indexOf ( \":\" ) ) ; if ( driverClassName . length ( ) > 0 ) { return driverClassName ; } url = url . substring ( url . indexOf ( \":\" ) + 1 ) ; } if ( url . startsWith ( \"jdbc:oracle:thin:\" ) ) { driverClassName = \"oracle.jdbc.driver.OracleDriver\" ; } else if ( url . startsWith ( \"jdbc:mysql:\" ) ) { driverClassName = \"com.mysql.jdbc.Driver\" ; } else if ( url . startsWith ( \"jdbc:jtds:\" ) ) { // SQL Server or SyBase driverClassName = \"net.sourceforge.jtds.jdbc.Driver\" ; } else if ( url . startsWith ( \"jdbc:db2:\" ) ) { driverClassName = \"com.ibm.db2.jdbc.net.DB2Driver\" ; } else if ( url . startsWith ( \"jdbc:microsoft:sqlserver:\" ) ) { // SQL Server 7.0/2000 driverClassName = \"com.microsoft.jdbc.sqlserver.SQLServerDriver\" ; } else if ( url . startsWith ( \"jdbc:sqlserver:\" ) ) { // SQL Server 2005 driverClassName = \"com.microsoft.sqlserver.jdbc.SQLServerDriver\" ; } else if ( url . startsWith ( \"jdbc:postgresql:\" ) ) { driverClassName = \"org.postgresql.Driver\" ; } else if ( url . startsWith ( \"jdbc:hsqldb:\" ) ) { driverClassName = \"org.hsqldb.jdbcDriver\" ; } else if ( url . startsWith ( \"jdbc:derby://\" ) ) { driverClassName = \"org.apache.derby.jdbc.ClientDriver\" ; } else if ( url . startsWith ( \"jdbc:derby:\" ) ) { driverClassName = \"org.apache.derby.jdbc.EmbeddedDriver\" ; } else if ( url . startsWith ( \"jdbc:sybase:Tds:\" ) ) { driverClassName = \"com.sybase.jdbc.SybDriver\" ; } else if ( url . startsWith ( \"jdbc:informix-sqli:\" ) ) { driverClassName = \"com.informix.jdbc.IfxDriver\" ; } else if ( url . startsWith ( \"jdbc:odbc:\" ) ) { driverClassName = \"sun.jdbc.odbc.JdbcOdbcDriver\" ; } else if ( url . startsWith ( \"jdbc:timesten:client:\" ) ) { driverClassName = \"com.timesten.jdbc.TimesTenDriver\" ; } else if ( url . startsWith ( \"jdbc:as400:\" ) ) { driverClassName = \"com.ibm.as400.access.AS400JDBCDriver\" ; } else if ( url . startsWith ( \"jdbc:sapdb:\" ) ) { driverClassName = \"com.sap.dbtech.jdbc.DriverSapDB\" ; } else if ( url . startsWith ( \"jdbc:interbase:\" ) ) { driverClassName = \"interbase.interclient.Driver\" ; } return driverClassName ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "JDK 1 . 7 [CODESPLIT] @ Override public java . util . logging . Logger getParentLogger ( ) throws SQLFeatureNotSupportedException { if ( drivers . size ( ) == 1 ) { return getFirstDriver ( ) . getParentLogger ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "返回最终的 map [CODESPLIT] public Map < String , String > map ( ) { Map < String , String > map = new HashMap < String , String > ( ) ; int i = 0 ; while ( i < size ) { map . put ( items [ i ] , items [ i + 1 ] ) ; i += 2 ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Date getLastModified ( ) { try { long time = file . getEntry ( entryName ) . getTime ( ) ; if ( time > - 1 ) { return new Date ( time ) ; } else { return null ; } } catch ( NullPointerException ex ) { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Post a message queue event ( during a login workflow ) . <p > If { @code messageQ } is { @code null } then messaging is considered disabled . [CODESPLIT] public static void postMessage ( final MessageQ messageQ , final String domain , final String username , final Events event , final String error ) throws LoginException { // \"messageQ\" may be null, not validating here (see below) Validate . notBlank ( domain , \"The validated character sequence 'domain' is null or empty\" ) ; Validate . notBlank ( username , \"The validated character sequence 'username' is null or empty\" ) ; Validate . notNull ( event , \"The validated object 'event' is null\" ) ; Validate . notBlank ( error , \"The validated character sequence 'error' is null or empty\" ) ; // if message queues are disabled, the messageQ object will not have been initialized if ( messageQ == null ) { // string concatenation is only executed if log level is actually enabled if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Messages queues have been disabled, not creating event '\" + event . getValue ( ) + \"' for '\" + username + \"@\" + domain + \"'\" ) ; } } else { try { messageQ . create ( event , domain , username ) ; } catch ( MessageQException e ) { LOG . warn ( error , e ) ; throw Util . newLoginException ( error , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve or display the information requested in the provided Callbacks . <p > The { @code handle } method implementation checks the instance ( s ) of the { @code Callback } object ( s ) passed in to retrieve or display the requested information . [CODESPLIT] @ Override // Cannot change the interface to use varags, this interface is owned by javax.security @ SuppressWarnings ( \"PMD.UseVarargs\" ) public final void handle ( final Callback [ ] callbacks ) throws IOException , UnsupportedCallbackException { Validate . notNull ( callbacks , \"The validated object 'callbacks' is null\" ) ; for ( final Callback callback : callbacks ) { if ( callback instanceof NameCallback ) { final NameCallback nameCallback = ( NameCallback ) callback ; nameCallback . setName ( username ) ; } else if ( callback instanceof PasswordCallback ) { final PasswordCallback passwordCallback = ( PasswordCallback ) callback ; passwordCallback . setPassword ( password ) ; } else if ( callback instanceof TextInputCallback ) { final TextInputCallback textInputCallback = ( TextInputCallback ) callback ; textInputCallback . setText ( domain ) ; } else { final String error = \"Unsupported callback: \" + callback . getClass ( ) . getCanonicalName ( ) + \" Allowed callbacks are: \" + NameCallback . class . getCanonicalName ( ) + \" OR \" + PasswordCallback . class . getCanonicalName ( ) + \" OR \" + TextInputCallback . class . getCanonicalName ( ) ; LOG . warn ( error ) ; throw new UnsupportedCallbackException ( callback , error ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Write entity into a stream ( writer - file or pass it through network ) . < / p > [CODESPLIT] @ Override public final void write ( final Map < String , Object > pAddParam , final Object pEntity , final Writer pWriter ) throws Exception { Map < String , Map < String , String > > fieldsSettingsMap = getMngSettings ( ) . lazFldsSts ( pEntity . getClass ( ) ) ; pWriter . write ( \"<entity class=\\\"\" + pEntity . getClass ( ) . getCanonicalName ( ) + \"\\\"\\n\" ) ; for ( Map . Entry < String , Map < String , String > > entry : fieldsSettingsMap . entrySet ( ) ) { if ( \"true\" . equals ( entry . getValue ( ) . get ( \"isEnabled\" ) ) ) { Field field = getUtlReflection ( ) . retrieveField ( pEntity . getClass ( ) , entry . getKey ( ) ) ; field . setAccessible ( true ) ; Object fieldValue = field . get ( pEntity ) ; ISrvFieldWriter srvFieldWriter = getFieldsWritersMap ( ) . get ( entry . getValue ( ) . get ( \"ISrvFieldWriter\" ) ) ; if ( srvFieldWriter == null ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"There is no ISrvFieldWriter \" + entry . getValue ( ) . get ( \"ISrvFieldWriter\" ) + \" for \" + pEntity . getClass ( ) + \" / \" + field . getName ( ) ) ; } srvFieldWriter . write ( pAddParam , fieldValue , field . getName ( ) , pWriter ) ; } } pWriter . write ( \"/>\\n\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断一个 Class 是否存在并且可用 . [CODESPLIT] public static boolean available ( String qualifiedClassName , ClassLoader loader ) { return ClassLoaderUtils . loadClass ( qualifiedClassName , loader ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Class . isAssignableFrom () 的增强版本。 支持 null 自动装箱 以及数字类型的隐私转换 . [CODESPLIT] public static boolean isAssignable ( Class < ? > lhs , Class < ? > rhs ) { if ( lhs == null ) return false ; if ( rhs == null ) return ( ! ( lhs . isPrimitive ( ) ) ) ; if ( unboxed_class_set . contains ( lhs ) ) { lhs = boxed_class_map . get ( lhs ) ; } if ( unboxed_class_set . contains ( rhs ) ) { rhs = boxed_class_map . get ( rhs ) ; } if ( lhs . isAssignableFrom ( rhs ) ) { return true ; } lhs = unboxed_class_map . get ( lhs ) ; rhs = unboxed_class_map . get ( rhs ) ; if ( lhs == null || rhs == null ) { return false ; } if ( Integer . TYPE . equals ( rhs ) ) { return ( Long . TYPE . equals ( lhs ) || Float . TYPE . equals ( lhs ) || Double . TYPE . equals ( lhs ) ) ; } if ( Long . TYPE . equals ( rhs ) ) { return ( Float . TYPE . equals ( lhs ) || Double . TYPE . equals ( lhs ) ) ; } if ( Float . TYPE . equals ( rhs ) ) { return Double . TYPE . equals ( lhs ) ; } if ( Double . TYPE . equals ( rhs ) ) { return false ; } if ( Boolean . TYPE . equals ( rhs ) ) { return false ; } if ( Byte . TYPE . equals ( rhs ) ) { return ( Short . TYPE . equals ( lhs ) || Integer . TYPE . equals ( lhs ) || Long . TYPE . equals ( lhs ) || Float . TYPE . equals ( lhs ) || Double . TYPE . equals ( lhs ) ) ; } if ( Short . TYPE . equals ( rhs ) ) { return ( Integer . TYPE . equals ( lhs ) || Long . TYPE . equals ( lhs ) || Float . TYPE . equals ( lhs ) || Double . TYPE . equals ( lhs ) ) ; } if ( Character . TYPE . equals ( rhs ) ) { return ( Integer . TYPE . equals ( lhs ) || Long . TYPE . equals ( lhs ) || Float . TYPE . equals ( lhs ) || Double . TYPE . equals ( lhs ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a logging version of a connection [CODESPLIT] public static Connection getInstance ( Connection conn ) { InvocationHandler handler = new JdbcLogConnection ( conn ) ; ClassLoader cl = Connection . class . getClassLoader ( ) ; return ( Connection ) Proxy . newProxyInstance ( cl , new Class [ ] { Connection . class } , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints the authorizationUrl the user will open the url and obtain an authorization key . When prompted the user should provide the authorization key . [CODESPLIT] @ Override public String getAuthorization ( String authorizationUrl ) throws CubeSensorsException { System . out . println ( \"authorizationUrl:\" + authorizationUrl ) ; System . out . print ( \"provide authorization code:\" ) ; try ( Scanner in = new Scanner ( System . in ) ) { String authorization = in . nextLine ( ) ; return authorization ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a logging version of a PreparedStatement [CODESPLIT] public static CallableStatement getInstance ( CallableStatement stmt , String sql ) { InvocationHandler handler = new JdbcLogCallableStatement ( stmt , sql ) ; ClassLoader cl = CallableStatement . class . getClassLoader ( ) ; return ( CallableStatement ) Proxy . newProxyInstance ( cl , new Class [ ] { CallableStatement . class } , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "OrderedMap interface [CODESPLIT] public Entry < K , V > getEntry ( int index ) { if ( index < 0 || index >= size ( ) ) { throw new IndexOutOfBoundsException ( ) ; } LinkedEntry < K , V > entry = header . next ; for ( int i = 0 ; i < index ; i ++ ) { entry = entry . next ; } return entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Retrieve requested entities from DB then write them into a stream by given writer . < / p > [CODESPLIT] @ Override public final < T > int retrieveAndWriteEntities ( final Map < String , Object > pAddParam , final Class < T > pEntityClass , final Writer pWriter ) throws Exception { //e.g. \"limit 20 offset 19\": //e.g. \"where (ITSID>0 and IDDATABASEBIRTH=2135) limit 20 offset 19\": String conditions = ( String ) pAddParam . get ( \"conditions\" ) ; int requestingDatabaseVersion = Integer . parseInt ( ( String ) pAddParam . get ( \"requestingDatabaseVersion\" ) ) ; int databaseVersion = this . srvDatabase . getVersionDatabase ( ) ; List < T > entities = null ; int entitiesCount = 0 ; DatabaseInfo di ; if ( requestingDatabaseVersion == databaseVersion ) { try { this . srvDatabase . setIsAutocommit ( false ) ; this . srvDatabase . setTransactionIsolation ( ISrvDatabase . TRANSACTION_READ_UNCOMMITTED ) ; this . srvDatabase . beginTransaction ( ) ; di = getSrvOrm ( ) . retrieveEntityWithConditions ( pAddParam , DatabaseInfo . class , \"\" ) ; String requestedDatabaseIdStr = ( String ) pAddParam . get ( \"requestedDatabaseId\" ) ; if ( requestedDatabaseIdStr != null ) { int requestedDatabaseId = Integer . parseInt ( requestedDatabaseIdStr ) ; if ( requestedDatabaseId != di . getDatabaseId ( ) ) { String error = \"Different requested database ID! required/is: \" + requestedDatabaseId + \"/\" + di . getDatabaseId ( ) ; this . logger . error ( null , DatabaseWriterXml . class , error ) ; pWriter . write ( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" ) ; pWriter . write ( \"<message error=\\\"\" + error + \"\\\">\\n\" ) ; pWriter . write ( \"</message>\\n\" ) ; return entitiesCount ; } } if ( conditions == null ) { entities = getSrvOrm ( ) . retrieveList ( pAddParam , pEntityClass ) ; } else { entities = getSrvOrm ( ) . retrieveListWithConditions ( pAddParam , pEntityClass , conditions ) ; } entitiesCount = entities . size ( ) ; this . srvDatabase . commitTransaction ( ) ; } catch ( Exception ex ) { this . srvDatabase . rollBackTransaction ( ) ; throw ex ; } finally { this . srvDatabase . releaseResources ( ) ; } this . logger . info ( null , DatabaseWriterXml . class , \"Start write entities of \" + pEntityClass . getCanonicalName ( ) + \" count=\" + entitiesCount ) ; pWriter . write ( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" ) ; pWriter . write ( \"<message databaseId=\\\"\" + di . getDatabaseId ( ) + \"\\\" databaseVersion=\\\"\" + di . getDatabaseVersion ( ) + \"\\\" description=\\\"\" + di . getDescription ( ) + \"\\\" entitiesCount=\\\"\" + entitiesCount + \"\\\">\\n\" ) ; for ( T entity : entities ) { this . srvEntityWriter . write ( pAddParam , entity , pWriter ) ; } pWriter . write ( \"</message>\\n\" ) ; this . logger . info ( null , DatabaseWriterXml . class , \"Entities has been wrote\" ) ; } else { this . logger . error ( null , DatabaseWriterXml . class , \"Send error message - Different database version!\" ) ; pWriter . write ( \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" ) ; pWriter . write ( \"<message error=\\\"Different database version!\\\">\\n\" ) ; pWriter . write ( \"</message>\\n\" ) ; } return entitiesCount ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a singleton fully initialized instance of an { @link Audit } class to use for JAAS event auditing . <p > Retrieving a singleton by this method will cause the factory to keep state and store a reference to the singleton for later use . You may reset the factory state using the { @code reset () } method to retrieve a new / different singleton the next time this method is called .. <p > Note that any properties of the singleton ( e . g . configuration ) cannot necessarily be changed easily . You may call the singleton s { @code init () } method but depending on the implementation provided by the respective class this may or may not have the expected effect . <p > If you need tight control over the singleton including its lifecycle and configuration or you require more than one singleton that are different in their internal state ( e . g . with different configurations ) then you should create such objects with the { @code getInstance () } method and maintain their state as singletons in your application s business logic . <p > Classes implementing the { @link Audit } interface <b > must< / b > be thread safe . [CODESPLIT] @ SuppressWarnings ( \"PMD.NonThreadSafeSingleton\" ) public static Audit getSingleton ( final String className , final CommonProperties properties ) throws FactoryException { Validate . notBlank ( className , \"The validated character sequence 'className' is null or empty\" ) ; Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; // The double-check idiom is safe and acceptable here (Bloch, 2nd ed. p 284) if ( auditInstance == null ) { synchronized ( AuditFactory . class ) { if ( auditInstance == null ) { auditInstance = getInstance ( className , properties ) ; } } } return auditInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > It prepares database after import . < / p > [CODESPLIT] @ Override public final void make ( final Map < String , Object > pAddParams ) throws Exception { int preparedEntitiesCount = 0 ; try { this . srvDatabase . setIsAutocommit ( false ) ; this . srvDatabase . setTransactionIsolation ( ISrvDatabase . TRANSACTION_READ_UNCOMMITTED ) ; this . srvDatabase . beginTransaction ( ) ; for ( Class < ? > entityClass : this . classes ) { if ( APersistableBase . class . isAssignableFrom ( entityClass ) ) { preparedEntitiesCount ++ ; String queryMaxId = \"select max(ITSID) as MAXID from \" + entityClass . getSimpleName ( ) . toUpperCase ( ) + \";\" ; Integer maxId = this . srvDatabase . evalIntegerResult ( queryMaxId , \"MAXID\" ) ; if ( maxId != null ) { maxId ++ ; String querySec = \"alter sequence \" + entityClass . getSimpleName ( ) . toUpperCase ( ) + \"_ITSID_SEQ restart with \" + maxId + \";\" ; this . srvDatabase . executeQuery ( querySec ) ; } } } this . srvDatabase . commitTransaction ( ) ; } catch ( Exception ex ) { this . srvDatabase . rollBackTransaction ( ) ; throw ex ; } finally { this . srvDatabase . releaseResources ( ) ; } this . factoryAppBeans . releaseBeans ( ) ; Writer htmlWriter = ( Writer ) pAddParams . get ( \"htmlWriter\" ) ; if ( htmlWriter != null ) { htmlWriter . write ( \"<h4>\" + new Date ( ) . toString ( ) + \", \" + PrepareDbAfterGetCopyPostgresql . class . getSimpleName ( ) + \", app-factory beans has released\" + \"</h4>\" ) ; } this . logger . info ( null , PrepareDbAfterGetCopyPostgresql . class , \"Total sequence prepared: \" + preparedEntitiesCount + \", app-factory beans has released\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a package declaration . [CODESPLIT] public void visitPackageDeclaration ( PackageDeclaration d ) { d . accept ( pre ) ; for ( ClassDeclaration classDecl : d . getClasses ( ) ) { classDecl . accept ( this ) ; } for ( InterfaceDeclaration interfaceDecl : d . getInterfaces ( ) ) { interfaceDecl . accept ( this ) ; } d . accept ( post ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a type declaration . [CODESPLIT] public void visitTypeDeclaration ( TypeDeclaration d ) { d . accept ( pre ) ; for ( TypeParameterDeclaration tpDecl : d . getFormalTypeParameters ( ) ) { tpDecl . accept ( this ) ; } for ( FieldDeclaration fieldDecl : d . getFields ( ) ) { fieldDecl . accept ( this ) ; } for ( MethodDeclaration methodDecl : d . getMethods ( ) ) { methodDecl . accept ( this ) ; } for ( TypeDeclaration typeDecl : d . getNestedTypes ( ) ) { typeDecl . accept ( this ) ; } d . accept ( post ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a class declaration . [CODESPLIT] public void visitClassDeclaration ( ClassDeclaration d ) { d . accept ( pre ) ; for ( TypeParameterDeclaration tpDecl : d . getFormalTypeParameters ( ) ) { tpDecl . accept ( this ) ; } for ( FieldDeclaration fieldDecl : d . getFields ( ) ) { fieldDecl . accept ( this ) ; } for ( MethodDeclaration methodDecl : d . getMethods ( ) ) { methodDecl . accept ( this ) ; } for ( TypeDeclaration typeDecl : d . getNestedTypes ( ) ) { typeDecl . accept ( this ) ; } for ( ConstructorDeclaration ctorDecl : d . getConstructors ( ) ) { ctorDecl . accept ( this ) ; } d . accept ( post ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Visits a method or constructor declaration . [CODESPLIT] public void visitExecutableDeclaration ( ExecutableDeclaration d ) { d . accept ( pre ) ; for ( TypeParameterDeclaration tpDecl : d . getFormalTypeParameters ( ) ) { tpDecl . accept ( this ) ; } for ( ParameterDeclaration pDecl : d . getParameters ( ) ) { pDecl . accept ( this ) ; } d . accept ( post ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; JPanel panelMain = this . makeNewPanel ( panel , BorderLayout . CENTER ) ; panelMain . setLayout ( new GridLayout ( 2 , 3 ) ) ; String strSource = m_properties . getProperty ( SOURCE_PARAM ) ; if ( strSource == null ) strSource = m_rgstrSources [ 0 ] ; panelMain . add ( new JLabel ( \"Source: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_comboSource = ( JComboBox ) this . makeControlPopup ( m_rgstrSources , strSource ) ) ; panelMain . add ( m_buttonSource = ( JButton ) new JButton ( \"Change settings...\" ) ) ; String strDestination = m_properties . getProperty ( DESTINATION_PARAM ) ; if ( strDestination == null ) strDestination = m_rgstrDestinations [ 0 ] ; panelMain . add ( new JLabel ( \"Destination: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_comboDestination = ( JComboBox ) this . makeControlPopup ( m_rgstrDestinations , strDestination ) ) ; panelMain . add ( m_buttonDestination = ( JButton ) new JButton ( \"Change settings...\" ) ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add listeners to the controls . [CODESPLIT] public void addListeners ( ) { super . addListeners ( ) ; m_buttonSource . addActionListener ( this ) ; m_comboSource . addItemListener ( this ) ; m_buttonDestination . addActionListener ( this ) ; m_comboDestination . addItemListener ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { String strSelection = ( String ) m_comboSource . getSelectedItem ( ) ; m_properties . setProperty ( SOURCE_PARAM , strSelection ) ; strSelection = ( String ) m_comboDestination . getSelectedItem ( ) ; m_properties . setProperty ( DESTINATION_PARAM , strSelection ) ; super . controlsToProperties ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { m_comboSource . setSelectedItem ( m_properties . getProperty ( SOURCE_PARAM ) ) ; if ( m_comboSource . getSelectedIndex ( ) == - 1 ) { m_comboSource . setSelectedIndex ( 0 ) ; m_properties . setProperty ( SOURCE_PARAM , m_comboSource . getSelectedItem ( ) . toString ( ) ) ; } m_comboDestination . setSelectedItem ( m_properties . getProperty ( DESTINATION_PARAM ) ) ; if ( m_comboDestination . getSelectedIndex ( ) == - 1 ) { m_comboDestination . setSelectedIndex ( 0 ) ; m_properties . setProperty ( DESTINATION_PARAM , m_comboDestination . getSelectedItem ( ) . toString ( ) ) ; } super . propertiesToControls ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * User pressed a button . [CODESPLIT] public void actionPerformed ( ActionEvent e ) { PropertyOwner propOwner = null ; String strClass = null ; Object objClass = null ; if ( e . getSource ( ) == m_buttonSource ) { strClass = m_properties . getProperty ( Scanner . SOURCE_PARAM ) ; objClass = Util . makeObjectFromClassName ( Object . class . getName ( ) , SOURCE_PARAM , strClass ) ; if ( objClass instanceof BaseSource ) // Always ( ( BaseSource ) objClass ) . init ( m_properties ) ; } else if ( e . getSource ( ) == m_buttonDestination ) { strClass = m_properties . getProperty ( Scanner . DESTINATION_PARAM ) ; objClass = Util . makeObjectFromClassName ( Object . class . getName ( ) , DESTINATION_PARAM , strClass ) ; if ( objClass instanceof BaseDestination ) // Always ( ( BaseDestination ) objClass ) . init ( m_properties ) ; } if ( objClass instanceof PropertyOwner ) propOwner = ( PropertyOwner ) objClass ; if ( propOwner != null ) { this . controlsToProperties ( ) ; PropertyView panel = propOwner . getPropertyView ( m_properties ) ; if ( panel == null ) // Default panel = new PropertyView ( m_propOwner , m_properties ) ; if ( JOptionPane . showConfirmDialog ( null , panel , panel . getDescription ( ) , JOptionPane . OK_CANCEL_OPTION ) == JOptionPane . OK_OPTION ) { panel . controlsToProperties ( ) ; propOwner . setProperties ( m_properties ) ; // Send the property owner the new settings } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "suppress warnings about this method being too complex ( can t extract a generic subroutine to reduce exec paths ) [CODESPLIT] @ SuppressWarnings ( { \"PMD.ExcessiveMethodLength\" , \"PMD.NPathComplexity\" , \"PMD.CyclomaticComplexity\" , \"PMD.StdCyclomaticComplexity\" , \"PMD.ModifiedCyclomaticComplexity\" } ) // CHECKSTYLE:ON public static CommonProperties build ( final Map < String , ? > properties ) { Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; final CommonProperties commonProps = new CommonProperties ( ) ; String tmp = getOption ( KEY_AUDIT_CLASS_NAME , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setAuditClassName ( tmp ) ; logValue ( KEY_AUDIT_CLASS_NAME , tmp ) ; } else { commonProps . setAuditClassName ( DEFAULT_AUDIT_CLASS_NAME ) ; logDefault ( KEY_AUDIT_CLASS_NAME , DEFAULT_AUDIT_CLASS_NAME ) ; } tmp = getOption ( KEY_AUDIT_IS_ENABLED , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setAuditEnabled ( Boolean . parseBoolean ( tmp ) ) ; logValue ( KEY_AUDIT_IS_ENABLED , tmp ) ; } else { commonProps . setAuditEnabled ( DEFAULT_AUDIT_IS_ENABLED ) ; logDefault ( KEY_AUDIT_IS_ENABLED , String . valueOf ( DEFAULT_AUDIT_IS_ENABLED ) ) ; } tmp = getOption ( KEY_AUDIT_IS_SINGLETON , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setAuditSingleton ( Boolean . parseBoolean ( tmp ) ) ; logValue ( KEY_AUDIT_IS_SINGLETON , tmp ) ; } else { commonProps . setAuditSingleton ( DEFAULT_AUDIT_IS_SINGLETON ) ; logDefault ( KEY_AUDIT_IS_SINGLETON , String . valueOf ( DEFAULT_AUDIT_IS_SINGLETON ) ) ; } tmp = getOption ( KEY_MESSAGEQ_CLASS_NAME , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setMessageQueueClassName ( tmp ) ; logValue ( KEY_MESSAGEQ_CLASS_NAME , tmp ) ; } else { commonProps . setMessageQueueClassName ( DEFAULT_MESSAGEQ_CLASS_NAME ) ; logDefault ( KEY_MESSAGEQ_CLASS_NAME , DEFAULT_MESSAGEQ_CLASS_NAME ) ; } tmp = getOption ( KEY_MESSAGEQ_IS_ENABLED , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setMessageQueueEnabled ( Boolean . parseBoolean ( tmp ) ) ; logValue ( KEY_MESSAGEQ_IS_ENABLED , tmp ) ; } else { commonProps . setMessageQueueEnabled ( DEFAULT_MESSAGEQ_IS_ENABLED ) ; logDefault ( KEY_MESSAGEQ_IS_ENABLED , String . valueOf ( DEFAULT_MESSAGEQ_IS_ENABLED ) ) ; } tmp = getOption ( KEY_MESSAGEQ_IS_SINGLETON , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setMessageQueueSingleton ( Boolean . parseBoolean ( tmp ) ) ; logValue ( KEY_MESSAGEQ_IS_SINGLETON , tmp ) ; } else { commonProps . setMessageQueueSingleton ( DEFAULT_MESSAGEQ_IS_SINGLETON ) ; logDefault ( KEY_MESSAGEQ_IS_SINGLETON , String . valueOf ( DEFAULT_MESSAGEQ_IS_SINGLETON ) ) ; } tmp = getOption ( KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setPasswordAuthenticatorClassName ( tmp ) ; logValue ( KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME , tmp ) ; } else { commonProps . setPasswordAuthenticatorClassName ( DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME ) ; logDefault ( KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME , DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME ) ; } tmp = getOption ( KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setPasswordAuthenticatorSingleton ( Boolean . parseBoolean ( tmp ) ) ; logValue ( KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON , tmp ) ; } else { commonProps . setPasswordAuthenticatorSingleton ( DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON ) ; logDefault ( KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON , String . valueOf ( DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON ) ) ; } tmp = getOption ( KEY_PASSWORD_VALIDATOR_CLASS_NAME , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setPasswordValidatorClassName ( tmp ) ; logValue ( KEY_PASSWORD_VALIDATOR_CLASS_NAME , tmp ) ; } else { commonProps . setPasswordValidatorClassName ( DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME ) ; logDefault ( KEY_PASSWORD_VALIDATOR_CLASS_NAME , DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME ) ; } tmp = getOption ( KEY_PASSWORD_VALIDATOR_IS_SINGLETON , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { commonProps . setPasswordValidatorSingleton ( Boolean . parseBoolean ( tmp ) ) ; logValue ( KEY_PASSWORD_VALIDATOR_IS_SINGLETON , tmp ) ; } else { commonProps . setPasswordValidatorSingleton ( DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON ) ; logDefault ( KEY_PASSWORD_VALIDATOR_IS_SINGLETON , String . valueOf ( DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON ) ) ; } // set the additional properties, preserving the originally provided properties // create a defensive copy of the map and all its properties // the code looks a little more complicated than a simple \"putAll()\", but it catches situations // where a Map is provided that supports null values (e.g. a HashMap) vs Map implementations // that do not (e.g. ConcurrentHashMap). final Map < String , String > tempMap = new ConcurrentHashMap <> ( ) ; try { for ( final Map . Entry < String , ? > entry : properties . entrySet ( ) ) { final String key = entry . getKey ( ) ; final String value = ( String ) entry . getValue ( ) ; if ( value != null ) { tempMap . put ( key , value ) ; } } } catch ( ClassCastException e ) { final String error = \"The values of the configured JAAS properties must be Strings. \" + \"Sorry, but we do not support anything else here!\" ; throw new IllegalArgumentException ( error , e ) ; } commonProps . setAdditionalProperties ( tempMap ) ; return commonProps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the value of a JAAS configuration parameter . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private static < T > T getOption ( final String key , final Map < String , ? > properties ) { // private method asserts assert key != null : \"The key cannot be null\" ; return ( T ) properties . get ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Synchronize IHasVersion . < / p > [CODESPLIT] @ Override public final boolean sync ( final Map < String , Object > pAddParam , final Object pEntity ) throws Exception { IHasVersion entityPb = ( IHasVersion ) pEntity ; IHasVersion entityPbDb = getSrvOrm ( ) . retrieveEntity ( pAddParam , entityPb ) ; boolean isNew = true ; if ( entityPbDb != null ) { entityPb . setItsVersion ( entityPbDb . getItsVersion ( ) ) ; isNew = false ; } return isNew ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a filter that selects declarations containing all of a collection of modifiers . [CODESPLIT] public static DeclarationFilter getFilter ( final Collection < Modifier > mods ) { return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return d . getModifiers ( ) . containsAll ( mods ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a filter that selects declarations of a particular kind . For example there may be a filter that selects only class declarations or only fields . The filter will select declarations of the specified kind and also any subtypes of that kind ; for example a field filter will also select enum constants . [CODESPLIT] public static DeclarationFilter getFilter ( final Class < ? extends Declaration > kind ) { return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return kind . isInstance ( d ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a filter that selects those declarations selected by both this filter and another . [CODESPLIT] public DeclarationFilter and ( DeclarationFilter f ) { final DeclarationFilter f1 = this ; final DeclarationFilter f2 = f ; return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return f1 . matches ( d ) && f2 . matches ( d ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a filter that selects those declarations selected by either this filter or another . [CODESPLIT] public DeclarationFilter or ( DeclarationFilter f ) { final DeclarationFilter f1 = this ; final DeclarationFilter f2 = f ; return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return f1 . matches ( d ) || f2 . matches ( d ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the declarations matched by this filter . The result is a collection of the same type as the argument ; the { @linkplain #filter ( Collection Class ) two - parameter version } of <tt > filter< / tt > offers control over the result type . [CODESPLIT] public < D extends Declaration > Collection < D > filter ( Collection < D > decls ) { ArrayList < D > res = new ArrayList < D > ( decls . size ( ) ) ; for ( D d : decls ) { if ( matches ( d ) ) { res . add ( d ) ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the declarations matched by this filter with the result being restricted to declarations of a given kind . Similar to the simpler { @linkplain #filter ( Collection ) single - parameter version } of <tt > filter< / tt > but the result type is specified explicitly . [CODESPLIT] public < D extends Declaration > Collection < D > filter ( Collection < ? extends Declaration > decls , Class < D > resType ) { ArrayList < D > res = new ArrayList < D > ( decls . size ( ) ) ; for ( Declaration d : decls ) { if ( resType . isInstance ( d ) && matches ( d ) ) { res . add ( resType . cast ( d ) ) ; } } return res ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "double check for map [CODESPLIT] protected Map < String , V > getAsMap ( ) { Map < String , V > result = map ; if ( result == null ) { synchronized ( this ) { result = map ; if ( result == null ) { map = ( result = initialize ( ) ) ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Direct writing the object attribute values the private / protected modifiers will be ignoring if setter function exist return setter function value . <p > If recursively is true will looking from all class hierarchy< / p > [CODESPLIT] public static void setFieldValue ( final Object object , String fieldName , final Object value , boolean recursively ) { if ( object == null ) return ; Field field = ClassUtil . getDeclaredField ( object . getClass ( ) , fieldName , recursively ) ; if ( field == null ) { log . debug ( \"Could not find field [ {} ] on target [ {} ]\" , fieldName , object . getClass ( ) . getSimpleName ( ) ) ; return ; } String methodName = \"set\" + CommUtil . capitalize ( fieldName ) ; Method method = ClassUtil . getDeclaredMethod ( object . getClass ( ) , recursively , methodName , value == null ? Object . class : value . getClass ( ) ) ; if ( method != null ) { try { makeAccessible ( method ) ; method . invoke ( object , value ) ; return ; } catch ( InvocationTargetException e ) { log . debug ( \"Could not find method [ {} ] on target [ {} ]\" , methodName , object . getClass ( ) . getSimpleName ( ) ) ; } catch ( NullPointerException e ) { log . debug ( \"{} field: [ {} ] is null\" , object . getClass ( ) . getSimpleName ( ) , fieldName ) ; } catch ( IllegalAccessException e ) { // Will not happen } } makeAccessible ( field ) ; try { field . set ( object , value ) ; } catch ( NullPointerException e ) { log . debug ( \"{} field: [ {} ] is null\" , object . getClass ( ) . getSimpleName ( ) , fieldName ) ; } catch ( IllegalAccessException e ) { // Will not happen } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set constructor is accessible [CODESPLIT] public static < T > void makeAccessible ( final Constructor < T > constructor ) { if ( ! Modifier . isPublic ( constructor . getModifiers ( ) ) || ! Modifier . isPublic ( constructor . getDeclaringClass ( ) . getModifiers ( ) ) ) { constructor . setAccessible ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtained the parent class generic parameter types <p > for example : < / p > <code > ClassB&lt ; T&gt ; extends ClassA&lt ; T&gt ; < / code > [CODESPLIT] public static Type [ ] getSuperClassGenricTypes ( final Class < ? > clazz ) { Type [ ] temp = { Object . class } ; // eg: ClassA<T> if ( clazz == null ) return null ; Type type = clazz . getGenericSuperclass ( ) ; if ( type instanceof ParameterizedType ) { return ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ; } else { log . warn ( \"{} 's superclass not ParameterizedType\" , clazz ) ; return temp ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtained the parent class generic parameter type <p > for example : < / p > <code > ClassB&lt ; T&gt ; extends ClassA&lt ; T&gt ; < / code > [CODESPLIT] public static Type getSuperClassGenricType ( final Class < ? > clazz , int index ) { Type [ ] types = getSuperClassGenricTypes ( clazz ) ; if ( index < 0 ) { log . warn ( \"{}'s index must be greater than 0,return the 0\" , clazz == null ? Object . class . getSimpleName ( ) : clazz . getSimpleName ( ) ) ; return types [ 0 ] ; } else if ( index > types . length ) { log . warn ( \"{}'s index in {} not found,return the last\" , clazz == null ? Object . class . getSimpleName ( ) : clazz . getSimpleName ( ) , index ) ; return types [ types . length - 1 ] ; } else { return types [ index ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtained the parent class generic parameter classes <p > for example : < / p > <code > ClassB&lt ; T&gt ; extends ClassA&lt ; T&gt ; < / code > [CODESPLIT] public static Class < ? > [ ] getSuperClassGenricClasses ( final Class < ? > clazz ) { Type [ ] types = getSuperClassGenricTypes ( clazz ) ; Class < ? > [ ] clazzs = new Class < ? > [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { clazzs [ i ] = ( Class < ? > ) types [ i ] ; } return clazzs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtained the interface generic parameter types <p > for example : < / p > <code > ClassB&lt ; T&gt ; implements ClassA&lt ; T&gt ; < / code > [CODESPLIT] public static Type [ ] getInterfacesGenricTypes ( final Class < ? > clazz ) { if ( clazz == null ) return null ; Type [ ] types = clazz . getGenericInterfaces ( ) ; Type [ ] gtypes = new Type [ 0 ] ; for ( Type t : types ) { if ( t instanceof ParameterizedType ) { Type [ ] gts = ( ( ParameterizedType ) t ) . getActualTypeArguments ( ) ; int olen = gtypes . length ; int ilen = gts . length ; Type [ ] tmp = new Type [ olen + ilen ] ; System . arraycopy ( gtypes , 0 , tmp , 0 , olen ) ; System . arraycopy ( gts , 0 , tmp , olen , ilen ) ; gtypes = tmp ; } } return gtypes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtained the interface generic parameter type <p > for example : < / p > <code > ClassB&lt ; T&gt ; implements ClassA&lt ; T&gt ; < / code > [CODESPLIT] public static Type getInterfacesGenricType ( final Class < ? > clazz , int index ) { Type [ ] types = getInterfacesGenricTypes ( clazz ) ; if ( index < 0 ) { log . warn ( \"{}'s index must be greater than 0,return the 0\" , clazz == null ? Object . class . getSimpleName ( ) : clazz . getSimpleName ( ) ) ; return types [ 0 ] ; } else if ( index > types . length ) { log . warn ( \"{}'s index in {} not found,return the last\" , clazz == null ? Object . class . getSimpleName ( ) : clazz . getSimpleName ( ) , index ) ; return types [ types . length - 1 ] ; } else { return types [ index ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtained the interface generic parameter classes <p > for example : < / p > <code > ClassB&lt ; T&gt ; implements ClassA&lt ; T&gt ; < / code > [CODESPLIT] public static Class < ? > [ ] getInterfacesGenricClasses ( final Class < ? > clazz ) { Type [ ] types = getInterfacesGenricTypes ( clazz ) ; Class < ? > [ ] clazzs = new Class < ? > [ types . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) { clazzs [ i ] = ( Class < ? > ) types [ i ] ; } return clazzs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new instance of specified class and type from a map <p > <b > note : clazz must write setter< / b > < / p > [CODESPLIT] public static < T > T getBasicInstance ( final Class < T > clazz , final Map < String , Object > paramsMap , boolean accessible ) { if ( clazz != null && paramsMap != null && paramsMap . size ( ) > 0 ) { T instance = ClassUtil . getInstance ( clazz , accessible ) ; for ( Map . Entry < String , Object > entry : paramsMap . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( CommUtil . isBlank ( key ) ) { continue ; } key = CommUtil . uncapitalize ( key ) ; setFieldValue ( instance , key , entry . getValue ( ) , false ) ; } return instance ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; JPanel panelMain = this . makeNewPanel ( panel , BorderLayout . CENTER ) ; panelMain . setLayout ( new GridLayout ( 3 , 2 ) ) ; panelMain . add ( new JLabel ( \"Zip directory: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfRootPathname = new JTextField ( ) ) ; panelMain . add ( new JLabel ( \"Zip filename: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfFilename = new JTextField ( ) ) ; panelMain . add ( new JLabel ( \"Max size: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfMaxSize = new JTextField ( ) ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strPathname = m_tfRootPathname . getText ( ) ; m_properties . setProperty ( ZIPOUT_PATHNAME_PARAM , strPathname ) ; String strFilename = m_tfFilename . getText ( ) ; m_properties . setProperty ( ZIPOUT_FILENAME_PARAM , strFilename ) ; String strMaxSize = m_tfMaxSize . getText ( ) ; m_properties . setProperty ( MAX_SIZE_PARAM , strMaxSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strPathname = m_properties . getProperty ( ZIPOUT_PATHNAME_PARAM ) ; m_tfRootPathname . setText ( strPathname ) ; String strFilename = m_properties . getProperty ( ZIPOUT_FILENAME_PARAM ) ; m_tfFilename . setText ( strFilename ) ; String strMaxSize = m_properties . getProperty ( MAX_SIZE_PARAM ) ; m_tfMaxSize . setText ( strMaxSize ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void init ( Properties properties ) { super . init ( properties ) ; String strPathname = properties . getProperty ( DEST_ROOT_PATHNAME_PARAM ) ; if ( strPathname == null ) { strPathname = System . getProperties ( ) . getProperty ( \"java.io.tmpdir\" , \"c:/Temp\" ) ; if ( strPathname != null ) if ( ! strPathname . endsWith ( File . separator ) ) strPathname += File . separator ; properties . setProperty ( DEST_ROOT_PATHNAME_PARAM , strPathname ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { super . initTransfer ( properties ) ; m_strPathname = properties . getProperty ( DEST_ROOT_PATHNAME_PARAM ) ; if ( ( m_strPathname == null ) || ( m_strPathname . length ( ) == 0 ) ) m_strPathname = \"\" ; // No prefix else if ( ( m_strPathname . lastIndexOf ( System . getProperties ( ) . getProperty ( \"file.separator\" ) ) != m_strPathname . length ( ) - 1 ) && ( m_strPathname . lastIndexOf ( ' ' ) != m_strPathname . length ( ) - 1 ) ) m_strPathname += System . getProperties ( ) . getProperty ( \"file.separator\" ) ; // Must end in a path separator }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add this file to the destination . Note : Only supply the file or the stream not both . Supply the object that is easier given the source . This dual option is given to allow destinations that require File objects from ( such as FTP or HTTP ) Having to write the inStream to a physical file before processing it . [CODESPLIT] public long addNextFile ( SourceFile source ) { String strPath = source . getFilePath ( ) ; long lStreamLength = source . getStreamLength ( ) ; InputStream inStream = source . makeInStream ( ) ; try { strPath = m_strPathname + strPath ; File file = new File ( strPath ) ; file . mkdirs ( ) ; if ( file . exists ( ) ) file . delete ( ) ; file . createNewFile ( ) ; OutputStream outStream = new FileOutputStream ( file ) ; lStreamLength = Util . copyStream ( inStream , outStream ) ; outStream . close ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } return lStreamLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { boolean bIncremental = false ; String strSelected = properties . getProperty ( BACKUP_INCREMENTAL_PARAM ) ; if ( TRUE . equalsIgnoreCase ( strSelected ) ) bIncremental = true ; String strDate = properties . getProperty ( BACKUPDATE_PARAM ) ; if ( bIncremental ) // If incremental, set the \"filter date\". m_dateLastBackup = Util . stringToDate ( strDate ) ; m_Filter = Util . makeFilter ( properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Close everything down after processing . [CODESPLIT] public void finishTransfer ( Properties properties ) { String strDateLastBackup = Util . dateToString ( new Date ( ) ) ; properties . setProperty ( BACKUPDATE_PARAM , strDateLastBackup ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <tt > true< / tt > if the iteration has more elements . ( In other words returns <tt > true< / tt > if <tt > next< / tt > would return an element rather than throwing an exception . ) [CODESPLIT] public boolean hasNext ( ) { if ( m_nextPend != null ) return true ; m_nextPend = this . next ( ) ; if ( m_nextPend == null ) return false ; else return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Should I skip this file? Override this . [CODESPLIT] public boolean skipFile ( File inFile ) { if ( m_dateLastBackup != null ) { // Check the date Date dateLastMod = new Date ( inFile . lastModified ( ) ) ; if ( dateLastMod . before ( m_dateLastBackup ) ) return true ; // Skip it } return false ; // Don't skip it }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; JPanel panelMain = this . makeNewPanel ( panel , BorderLayout . CENTER ) ; panelMain . setLayout ( new GridLayout ( 1 , 2 ) ) ; panelMain . add ( new JLabel ( \"Log filename: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfLogFilename = new JTextField ( ) ) ; panelMain . add ( m_cbFileLength = new JCheckBox ( \"Calc file length?\" ) ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strPathname = m_tfLogFilename . getText ( ) ; m_properties . setProperty ( LOG_FILENAME_PARAM , strPathname ) ; boolean bSelected = m_cbFileLength . isSelected ( ) ; if ( bSelected ) m_properties . setProperty ( CALC_FILE_LENGTH_PARAM , TRUE ) ; else m_properties . setProperty ( CALC_FILE_LENGTH_PARAM , FALSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strPathname = m_properties . getProperty ( LOG_FILENAME_PARAM ) ; m_tfLogFilename . setText ( strPathname ) ; boolean bSelected = true ; String strSelected = m_properties . getProperty ( CALC_FILE_LENGTH_PARAM ) ; if ( FALSE . equalsIgnoreCase ( strSelected ) ) bSelected = false ; m_cbFileLength . setSelected ( bSelected ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "启动一个事务 ( 默认支持子事务 ) [CODESPLIT] public Transaction transaction ( ) { if ( transationHandler . get ( ) != null ) { if ( ALLOW_NESTED_TRANSACTION ) { return new JdbcNestedTransaction ( transationHandler . get ( ) . getConnection ( ) ) ; } throw new TransactionException ( \"Can't begin a nested transaction.\" ) ; } try { JdbcTransaction tx = new JdbcTransaction ( dataSource . getConnection ( ) , transationHandler ) ; transationHandler . set ( tx ) ; return tx ; } catch ( SQLException e ) { throw new TransactionException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取一个当前线程的连接 ( 事务中 ) ，如果没有，则新建一个。 [CODESPLIT] private Connection getConnection ( ) { JdbcTransaction tx = transationHandler . get ( ) ; try { if ( tx == null ) { return dataSource . getConnection ( ) ; } else { return tx . getConnection ( ) ; } } catch ( SQLException e ) { throw new DbException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断表是否已经存在 [CODESPLIT] public boolean tableExist ( String name ) { Connection conn = null ; ResultSet rs = null ; try { conn = getConnection ( ) ; DatabaseMetaData metaData = conn . getMetaData ( ) ; rs = metaData . getTables ( null , null , name . toUpperCase ( ) , new String [ ] { \"TABLE\" } ) ; return rs . next ( ) ; } catch ( SQLException e ) { throw new DbException ( e ) ; } finally { DbUtils . closeQuietly ( rs ) ; closeConnection ( conn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a set of connection properties based on key / values in a <code > HashMap< / code > . [CODESPLIT] public static ConnectionProperties build ( final Map < String , ? > properties ) { Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; // tmpConfig now holds all the configuration values with the keys expected by the Util libs connection // properties builder. We will let that library do all the hard work of setting reasonable defaults and // dealing with null values. // For this, we first try to copy the entire map to a Map<String, String> map (because this is what the builder // we will be using requires), and then ALSO copy the values that are in the Map and that we care about to the // same map, potentially overwriting values that may already be there (e.g. if the user has configured them // under a key that coincidentally collides with a key that we care about). final Map < String , String > tmpConfig = new ConcurrentHashMap <> ( ) ; // first try to copy all the values in the map. We know that they are all of the same type, but we do not know // what that type is. Let's reasonably assume that they are Strings (not sure if the JAAS configuration // mechanism allows anything else), and just cast them. If the cast fails, we will fail the entire operation: try { for ( final Map . Entry < String , ? > entry : properties . entrySet ( ) ) { final String key = entry . getKey ( ) ; final String value = ( String ) entry . getValue ( ) ; if ( value != null ) { tmpConfig . put ( key , value ) ; } } } catch ( ClassCastException e ) { final String error = \"The values of the configured JAAS properties must be Strings. \" + \"Sorry, but we do not support anything else here!\" ; throw new IllegalArgumentException ( error , e ) ; } // second, we copy the values that we care about from the \"JAAS config namespace\" to the \"Connection namespace\": copyValue ( properties , KEY_DRIVER , tmpConfig , MapBasedConnPropsBuilder . KEY_DRIVER ) ; copyValue ( properties , KEY_URL , tmpConfig , MapBasedConnPropsBuilder . KEY_URL ) ; copyValue ( properties , KEY_USERNAME , tmpConfig , MapBasedConnPropsBuilder . KEY_USERNAME ) ; copyValue ( properties , KEY_PASSWORD , tmpConfig , MapBasedConnPropsBuilder . KEY_PASSWORD ) ; copyValue ( properties , KEY_MAX_TOTAL , tmpConfig , MapBasedConnPropsBuilder . KEY_MAX_TOTAL ) ; copyValue ( properties , KEY_MAX_IDLE , tmpConfig , MapBasedConnPropsBuilder . KEY_MAX_IDLE ) ; copyValue ( properties , KEY_MIN_IDLE , tmpConfig , MapBasedConnPropsBuilder . KEY_MIN_IDLE ) ; copyValue ( properties , KEY_MAX_WAIT_MILLIS , tmpConfig , MapBasedConnPropsBuilder . KEY_MAX_WAIT_MILLIS ) ; copyValue ( properties , KEY_TEST_ON_CREATE , tmpConfig , MapBasedConnPropsBuilder . KEY_TEST_ON_CREATE ) ; copyValue ( properties , KEY_TEST_ON_BORROW , tmpConfig , MapBasedConnPropsBuilder . KEY_TEST_ON_BORROW ) ; copyValue ( properties , KEY_TEST_ON_RETURN , tmpConfig , MapBasedConnPropsBuilder . KEY_TEST_ON_RETURN ) ; copyValue ( properties , KEY_TEST_WHILE_IDLE , tmpConfig , MapBasedConnPropsBuilder . KEY_TEST_WHILE_IDLE ) ; copyValue ( properties , KEY_TIME_BETWEEN_EVICTION_RUNS_MILLIS , tmpConfig , MapBasedConnPropsBuilder . KEY_TIME_BETWEEN_EVICTION_RUNS_MILLIS ) ; copyValue ( properties , KEY_NUM_TESTS_PER_EVICITON_RUN , tmpConfig , MapBasedConnPropsBuilder . KEY_NUM_TESTS_PER_EVICITON_RUN ) ; copyValue ( properties , KEY_MIN_EVICTABLE_IDLE_TIME_MILLIS , tmpConfig , MapBasedConnPropsBuilder . KEY_MIN_EVICTABLE_IDLE_TIME_MILLIS ) ; copyValue ( properties , KEY_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS , tmpConfig , MapBasedConnPropsBuilder . KEY_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS ) ; copyValue ( properties , KEY_LIFO , tmpConfig , MapBasedConnPropsBuilder . KEY_LIFO ) ; copyValue ( properties , KEY_AUTO_COMMIT , tmpConfig , MapBasedConnPropsBuilder . KEY_AUTO_COMMIT ) ; copyValue ( properties , KEY_READ_ONLY , tmpConfig , MapBasedConnPropsBuilder . KEY_READ_ONLY ) ; copyValue ( properties , KEY_TRANSACTION_ISOLATION , tmpConfig , MapBasedConnPropsBuilder . KEY_TRANSACTION_ISOLATION ) ; copyValue ( properties , KEY_CACHE_STATE , tmpConfig , MapBasedConnPropsBuilder . KEY_CACHE_STATE ) ; copyValue ( properties , KEY_VALIDATION_QUERY , tmpConfig , MapBasedConnPropsBuilder . KEY_VALIDATION_QUERY ) ; copyValue ( properties , KEY_MAX_CONN_LIFETIME_MILLIS , tmpConfig , MapBasedConnPropsBuilder . KEY_MAX_CONN_LIFETIME_MILLIS ) ; return MapBasedConnPropsBuilder . build ( tmpConfig ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy the value of a specific key in a source map to a specific key in a target map . <p > The method checks if the value assigned to the source key is <code > null< / code > and does not copy it if it is <code > null< / code > . [CODESPLIT] private static void copyValue ( final Map < String , ? > sourceMap , final String sourceKey , final Map < String , String > targetMap , final String targetKey ) { if ( getOption ( sourceKey , sourceMap ) != null && String . class . isInstance ( getOption ( sourceKey , sourceMap ) ) ) { targetMap . put ( targetKey , ( String ) getOption ( sourceKey , sourceMap ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get everything ready . [CODESPLIT] public void init ( Properties properties ) { super . init ( properties ) ; String strPathname = properties . getProperty ( ZIPOUT_PATHNAME_PARAM ) ; if ( strPathname == null ) { strPathname = System . getProperties ( ) . getProperty ( \"java.io.tmpdir\" , \"c:/Temp\" ) ; properties . setProperty ( ZIPOUT_PATHNAME_PARAM , strPathname ) ; } String strFilename = properties . getProperty ( ZIPOUT_FILENAME_PARAM ) ; if ( strFilename == null ) { strFilename = \"[automatic]\" ; properties . setProperty ( ZIPOUT_FILENAME_PARAM , strFilename ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { super . initTransfer ( properties ) ; String strPathname = properties . getProperty ( ZIPOUT_PATHNAME_PARAM ) ; if ( ( strPathname != null ) && ( strPathname . length ( ) > 0 ) && ( strPathname . lastIndexOf ( System . getProperties ( ) . getProperty ( \"file.separator\" ) ) == strPathname . length ( ) - 1 ) && ( strPathname . lastIndexOf ( ' ' ) == strPathname . length ( ) - 1 ) ) strPathname += System . getProperties ( ) . getProperty ( \"file.separator\" ) ; m_strZipFilename = properties . getProperty ( ZIPOUT_FILENAME_PARAM ) ; if ( ( m_strZipFilename == null ) || ( m_strZipFilename . length ( ) == 0 ) || ( m_strZipFilename . equals ( \"[automatic]\" ) ) ) m_strZipFilename = this . getBackupFilename ( ) ; if ( strPathname != null ) m_strZipFilename = strPathname + m_strZipFilename ; String strMaxSize = properties . getProperty ( MAX_SIZE_PARAM ) ; m_lMaxZipFileSize = 0 ; try { if ( strMaxSize != null ) m_lMaxZipFileSize = Long . parseLong ( strMaxSize ) ; } catch ( NumberFormatException ex ) { m_lMaxZipFileSize = 0 ; } m_lCurrentLength = 0 ; m_iFileNumber = 0 ; try { FileOutputStream outStream = new FileOutputStream ( m_strZipFilename ) ; m_outZip = new ZipOutputStream ( outStream ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Close everything down after processing . [CODESPLIT] public void finishTransfer ( Properties properties ) { try { m_outZip . flush ( ) ; m_outZip . close ( ) ; } catch ( FileNotFoundException ex ) { ex . printStackTrace ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } super . finishTransfer ( properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add this file to the destination . Note : Only supply the file or the stream not both . Supply the object that is easier given the source . This dual option is given to allow destinations that require File objects from ( such as FTP or HTTP ) Having to write the inStream to a physical file before processing it . [CODESPLIT] public long addNextFile ( SourceFile source ) { String strPath = source . getFilePath ( ) ; long lStreamLength = source . getStreamLength ( ) ; InputStream inStream = source . makeInStream ( ) ; long lLength = 0 ; try { if ( m_lMaxZipFileSize > 0 ) //?\t\t\t\tif (lLength != File.OL) { // Check to make sure this file will fit if ( m_lCurrentLength + lStreamLength > m_lMaxZipFileSize ) { // Writing this file would push me past the file length limit try { m_outZip . flush ( ) ; m_outZip . close ( ) ; m_lCurrentLength = 0 ; m_iFileNumber ++ ; int iPosDot = m_strZipFilename . lastIndexOf ( ' ' ) ; if ( iPosDot == - 1 ) iPosDot = m_strZipFilename . length ( ) ; String strZipFilename = m_strZipFilename . substring ( 0 , iPosDot ) ; strZipFilename += Integer . toString ( m_iFileNumber ) ; if ( iPosDot != m_strZipFilename . length ( ) ) strZipFilename += m_strZipFilename . substring ( iPosDot ) ; FileOutputStream outStream = new FileOutputStream ( strZipFilename ) ; m_outZip = new ZipOutputStream ( outStream ) ; } catch ( FileNotFoundException ex ) { ex . printStackTrace ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } } } ZipEntry zipEntry = new ZipEntry ( strPath ) ; if ( DEBUG ) System . out . println ( strPath ) ; m_outZip . putNextEntry ( zipEntry ) ; lLength = Util . copyStream ( inStream , m_outZip ) ; m_lCurrentLength += lLength ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } return lLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add the files to the backup file [CODESPLIT] public String getBackupFilename ( ) { Date now = new Date ( ) ; String strDate = Util . dateToString ( now ) ; for ( int i = 0 ; i < strDate . length ( ) ; i ++ ) { char ch = strDate . charAt ( i ) ; if ( ! Character . isLetterOrDigit ( ch ) ) strDate = strDate . substring ( 0 , i ) + ' ' + strDate . substring ( i + 1 , strDate . length ( ) ) ; } return \"backup\" + strDate + \".zip\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Adds the provided key and value to this map . [CODESPLIT] @ Override public V put ( K key , V value ) { synchronized ( this ) { Map < K , V > newMap = new HashMap < K , V > ( internalMap ) ; V val = newMap . put ( key , value ) ; internalMap = newMap ; return val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "* Removed the value and key from this map based on the provided key . [CODESPLIT] @ Override public V remove ( Object key ) { synchronized ( this ) { Map < K , V > newMap = new HashMap < K , V > ( internalMap ) ; V val = newMap . remove ( key ) ; internalMap = newMap ; return val ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "和实际的 URL 进行匹配，并返回成功匹配的参数 ( pathVariables ) [CODESPLIT] public boolean match ( String [ ] urlSegments , PathVariables pathVariables ) { Validate . isTrue ( urlSegments . length == matchers . length ) ; for ( int i = 1 ; i < matchers . length ; i ++ ) { if ( ! matchers [ i ] . match ( urlSegments [ i ] , pathVariables ) ) { pathVariables . clear ( ) ; // 注意：不匹配的情况下，需要清除此次匹配的内容 return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Audit an event ( during a login workflow ) . <p > If { @code audit } is { @code null } then auditing is considered disabled [CODESPLIT] public static void auditEvent ( final Audit audit , final String domain , final String username , final Events event , final String error ) throws LoginException { // \"audit\" may be null, not validating here (see below) Validate . notBlank ( domain , \"The validated character sequence 'domain' is null or empty\" ) ; Validate . notBlank ( username , \"The validated character sequence 'username' is null or empty\" ) ; Validate . notNull ( event , \"The validated object 'event' is null\" ) ; Validate . notBlank ( error , \"The validated character sequence 'error' is null or empty\" ) ; // if auditing is disabled, the audit object will not have been initialized if ( audit == null ) { // string concatenation is only executed if log level is actually enabled if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Auditing has been disabled, not creating event '\" + event . getValue ( ) + \"' for '\" + username + \"@\" + domain + \"'\" ) ; } } else { try { audit . audit ( event , domain , username ) ; } catch ( AuditException e ) { LOG . warn ( error , e ) ; throw Util . newLoginException ( error , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Standalone support . Usually you specify a property file to use ( ie . property . filename = c : \\\\ temp \\\\ updatesite . properties ) [CODESPLIT] public static void main ( String [ ] args ) { Properties properties = new Properties ( ) ; if ( args != null ) { // Move the args to a property file for ( int i = 0 ; i < args . length ; i ++ ) { int iEquals = args [ i ] . indexOf ( ' ' ) ; if ( iEquals != - 1 ) if ( iEquals < args [ i ] . length ( ) - 1 ) properties . setProperty ( args [ i ] . substring ( 0 , iEquals ) , args [ i ] . substring ( iEquals + 1 ) ) ; } } String strPropertyFileName = properties . getProperty ( PROPERTY_FILENAME_PARAM ) ; if ( strPropertyFileName != null ) { Properties propertiesRead = AppUtilities . readProperties ( strPropertyFileName ) ; propertiesRead . putAll ( properties ) ; // Add the read-in properties properties = propertiesRead ; } Scanner scanner = new Scanner ( properties ) ; scanner . run ( ) ; AppUtilities . writeProperties ( strPropertyFileName , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move files from the source to the destination . [CODESPLIT] public void run ( ) { if ( m_properties == null ) { System . out . println ( \"Must supply properties.\" ) ; return ; } String strSourceClass = m_properties . getProperty ( SOURCE_PARAM ) ; String strDestinationClass = m_properties . getProperty ( DESTINATION_PARAM ) ; if ( ( strSourceClass == null ) || ( strDestinationClass == null ) ) { System . out . println ( \"Must supply source and destination class names.\" ) ; return ; } SourceFileList sourceList = ( SourceFileList ) Util . makeObjectFromClassName ( Object . class . getName ( ) , \"source\" , strSourceClass ) ; DestinationFile destination = ( DestinationFile ) Util . makeObjectFromClassName ( Object . class . getName ( ) , \"destination\" , strDestinationClass ) ; this . process ( sourceList , destination ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Move files from the source to the destination . [CODESPLIT] public void process ( SourceFileList sourceList , DestinationFile destination ) { sourceList . initTransfer ( m_properties ) ; destination . initTransfer ( m_properties ) ; //FilesystemSource(\"c:\\\\My Documents\"); //DebugDestination(null); //ZipDestination(\"test.zip\", -1); while ( sourceList . hasNext ( ) ) { SourceFile source = sourceList . next ( ) ; this . moveFile ( source , destination ) ; //?                        source.close(); //\t\t\tSystem.out.println(source.getFileName()); } destination . finishTransfer ( m_properties ) ; sourceList . finishTransfer ( m_properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prepare to query the given object . [CODESPLIT] public ObjectQueryInfo prepareObjectQuery ( Object obj ) throws MalformedObjectNameException { ObjectQueryInfo result ; // // Extract the mbean info from the object (TBD: cache this information ahead of time) // String onamePattern = MBeanAnnotationUtil . getLocationONamePattern ( obj ) ; if ( onamePattern != null ) { // // Locate the setters and continue only if at least one was found. // Map < String , Method > attributeSetters = MBeanAnnotationUtil . getAttributes ( obj ) ; if ( attributeSetters . size ( ) > 0 ) { String onameString ; if ( obj instanceof MBeanLocationParameterSource ) { onameString = this . parameterReplacer . replaceObjectNameParameters ( onamePattern , ( MBeanLocationParameterSource ) obj ) ; } else { onameString = onamePattern ; } ObjectName oname = new ObjectName ( onameString ) ; result = new ObjectQueryInfo ( obj , oname , attributeSetters ) ; } else { this . logNoAttributeThrottle . warn ( log , \"ignoring attempt to prepare to poll an MBean object with no attributes: onamePattern={}\" , onamePattern ) ; result = null ; } } else { log . warn ( \"ignoring attempt to prepare to poll object that has no MBeanLocation\" ) ; result = null ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "replaces slashes with hyphens and removes padding = [CODESPLIT] public static String replaceSlashWithHyphen ( String origin ) { char [ ] resulltChars = origin . toCharArray ( ) ; for ( int i = 0 ; i < resulltChars . length - 1 ; i ++ ) { if ( resulltChars [ i ] == ' ' ) { resulltChars [ i ] = ' ' ; } } return new String ( resulltChars , 0 , resulltChars . length - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of bytes to a string of two digits hex - representations [CODESPLIT] public static String bytes2HexString ( byte [ ] bytes ) { StringBuffer resultBuffer = new StringBuffer ( ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { resultBuffer . append ( byte2Hex ( bytes [ i ] ) ) ; } return resultBuffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Read entity ( fill fields ) from a stream ( reader - file or through network ) . It is invoked when it s start of &lt ; entity < / p > [CODESPLIT] @ Override public final Object read ( final Map < String , Object > pAddParam , final Reader pReader ) throws Exception { Map < String , String > attributesMap = readAttributes ( pAddParam , pReader ) ; if ( attributesMap . get ( \"class\" ) == null ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"There is no class attribute for entity!\" ) ; } Class entityClass = Class . forName ( attributesMap . get ( \"class\" ) ) ; @ SuppressWarnings ( \"unchecked\" ) Constructor constructor = entityClass . getDeclaredConstructor ( ) ; Object entity = constructor . newInstance ( ) ; Map < String , Map < String , String > > fieldsSettingsMap = getMngSettings ( ) . lazFldsSts ( entityClass ) ; for ( Map . Entry < String , Map < String , String > > entry : fieldsSettingsMap . entrySet ( ) ) { if ( \"true\" . equals ( entry . getValue ( ) . get ( \"isEnabled\" ) ) && attributesMap . get ( entry . getKey ( ) ) != null ) { ISrvEntityFieldFiller srvEntityFieldFiller = getFieldsFillersMap ( ) . get ( entry . getValue ( ) . get ( \"ISrvEntityFieldFiller\" ) ) ; if ( srvEntityFieldFiller == null ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"There is no ISrvEntityFieldFiller \" + entry . getValue ( ) . get ( \"ISrvEntityFieldFiller\" ) + \" for \" + entityClass + \" / \" + entry . getKey ( ) ) ; } srvEntityFieldFiller . fill ( pAddParam , entity , entry . getKey ( ) , attributesMap . get ( entry . getKey ( ) ) ) ; } } return entity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Read entity attributes from stream . < / p > [CODESPLIT] @ Override public final Map < String , String > readAttributes ( final Map < String , Object > pAddParam , final Reader pReader ) throws Exception { return this . utilXml . readAttributes ( pReader , pAddParam ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the indexes for a parameter . [CODESPLIT] private List < Integer > getIndexes ( String name ) { List < Integer > indexes = nameIndexMap . get ( name ) ; if ( indexes == null ) { throw new IllegalArgumentException ( \"Parameter not found: \" + name ) ; } return indexes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a sql with named parameters . The parameter - index mappings are put into the map and the parsed sql is returned . [CODESPLIT] private static String parseNamedSql ( String sql , Map < String , List < Integer > > nameIndexMap ) { // I was originally using regular expressions, but they didn't work well for ignoring // parameter-like strings inside quotes. int length = sql . length ( ) ; StringBuffer parsedSql = new StringBuffer ( length ) ; boolean inSingleQuote = false ; boolean inDoubleQuote = false ; int index = 1 ; for ( int i = 0 ; i < length ; i ++ ) { char c = sql . charAt ( i ) ; if ( inSingleQuote ) { if ( c == ' ' ) { inSingleQuote = false ; } } else if ( inDoubleQuote ) { if ( c == ' ' ) { inDoubleQuote = false ; } } else { if ( c == ' ' ) { inSingleQuote = true ; } else if ( c == ' ' ) { inDoubleQuote = true ; } else if ( c == ' ' && i + 1 < length && Character . isJavaIdentifierStart ( sql . charAt ( i + 1 ) ) ) { int j = i + 2 ; while ( j < length && Character . isJavaIdentifierPart ( sql . charAt ( j ) ) ) { j ++ ; } String name = sql . substring ( i + 1 , j ) ; c = ' ' ; // replace the parameter with a question mark i += name . length ( ) ; // skip past the end if the parameter List < Integer > indexList = nameIndexMap . get ( name ) ; if ( indexList == null ) { indexList = new LinkedList < Integer > ( ) ; nameIndexMap . put ( name , indexList ) ; } indexList . add ( index ) ; index ++ ; } } parsedSql . append ( c ) ; } return parsedSql . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---- parameters ------------------------------------------------ [CODESPLIT] public < T > T getForm ( T form ) { RequestIntrospectUtils . introspect ( form , request ) ; return form ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---- model ------------------------------------------------ [CODESPLIT] public Model getModel ( ) { Model model = ( Model ) request . getAttribute ( Model . NAME_IN_REQUEST ) ; if ( model == null ) { model = new Model ( ) ; request . setAttribute ( Model . NAME_IN_REQUEST , model ) ; } return model ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "============================================================================== [CODESPLIT] @ Override public LogicalArea findArea ( Area area ) { LogicalArea ret = null ; //scan the subtree for ( int i = 0 ; i < getChildCount ( ) && ret == null ; i ++ ) { ret = getChildAt ( i ) . findArea ( area ) ; } //not in the subtree -- is it this area? if ( ret == null && getAreas ( ) . contains ( area ) ) ret = this ; //in our area nodes return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Filter for immutable entities of type APersistableBase . < / p > [CODESPLIT] @ Override public final String makeFilter ( final Class < ? > pEntityClass , final Map < String , Object > pAddParam ) throws Exception { if ( ! APersistableBase . class . isAssignableFrom ( pEntityClass ) ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"This class not descendant of APersistableBase: \" + pEntityClass ) ; } int requestedDatabaseId ; try { requestedDatabaseId = Integer . parseInt ( pAddParam . get ( \"requestedDatabaseId\" ) . toString ( ) ) ; } catch ( Exception e ) { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , \"Wrong or missing parameter requestedDatabaseId (in pAddParam): \" + pAddParam . get ( \"requestedDatabaseId\" ) ) ; } String queryMaxIdBirth = \"select max(IDBIRTH) as MAX_IDBIRTH from \" + pEntityClass . getSimpleName ( ) . toUpperCase ( ) + \" where IDDATABASEBIRTH=\" + requestedDatabaseId + \";\" ; Long maxIdBirth = this . srvDatabase . evalLongResult ( queryMaxIdBirth , \"MAX_IDBIRTH\" ) ; if ( maxIdBirth == null ) { maxIdBirth = 0L ; } String tblNm = pEntityClass . getSimpleName ( ) . toUpperCase ( ) ; return \"(\" + tblNm + \".ITSID>\" + maxIdBirth + \" and \" + tblNm + \".IDDATABASEBIRTH=\" + requestedDatabaseId + \")\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void process ( List argumentList ) throws InvalidArgumentsException { Set < Method > requiredArguments = new HashSet < Method > ( ) ; NamedAttributeProcessor namedAttributeProcessor = new NamedAttributeProcessor ( ) ; for ( final Method m : annotated . getMethods ( ) ) { if ( m . isAnnotationPresent ( CommandLine . class ) ) { final CommandLine cl = m . getAnnotation ( CommandLine . class ) ; if ( cl . required ( ) ) { requiredArguments . add ( m ) ; } for ( final String longName : cl . longName ( ) ) { namedAttributeProcessor . addLongNameAttributeProcessor ( new MySingleNamedAttributeProcessor ( longName , cl , m ) ) ; } for ( final String shortName : cl . shortName ( ) ) { namedAttributeProcessor . addNamedAttributeProcessor ( new MySingleNamedAttributeProcessor ( shortName , cl , m ) ) ; } } } Set < CommandLine > missingArguments = new HashSet < CommandLine > ( ) ; namedAttributeProcessor . process ( argumentList ) ; for ( Iterator < Method > iter = requiredArguments . iterator ( ) ; iter . hasNext ( ) ; ) { Method current = iter . next ( ) ; if ( ! valueMap . containsKey ( current ) ) { missingArguments . add ( current . getAnnotation ( CommandLine . class ) ) ; } } if ( missingArguments . size ( ) > 0 ) { throw new MissingArgumentException ( missingArguments ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Authenticate a user by validating the user s password returning a Subject with one or more { @code Principal } s set ( if validation was successful ) or throw a { @code LoginException } ( if validation fails ) <p / > This method checks whether the provided username matches the provided password . This requires a suitable plain text password validator to work as the actual validation is performed by the provided { @code PasswordValidator } ) . The method also checks that the domain is not { @code null } ( but it does allow an empty String value ) . <p / > If the validation is successful a { @code Subject } is populated with three principals is returned : The user s ID as a concatenation of the username with the string ID : and both the user provided domain and the user provided principal ( i . e . the the identifiers used to authenticate the users ) . [CODESPLIT] public final Subject authenticate ( final String domain , final String userName , final char [ ] password , final PasswordValidator passwordValidator ) throws LoginException { // make sure the credentials are not null if ( domain == null ) { throw new LoginException ( \"The domain cannot be null\" ) ; } if ( userName == null ) { throw new LoginException ( \"The username cannot be null\" ) ; } if ( password == null ) { throw new LoginException ( \"The password cannot be null\" ) ; } // no need for defensive copies of Strings, but create a defensive copy of the password final char [ ] myPassword = password . clone ( ) ; // convert the username string to a char array final char [ ] myCredential = userName . toCharArray ( ) ; // perform the password validation if ( ! passwordValidator . validate ( myPassword , myCredential ) ) { final String error = \"Invalid password for username '\" + userName + \"'\" ; LOG . info ( error ) ; throw new FailedLoginException ( error ) ; } // The authentication was successful! // Create the subject and clean up confidential data as far as possible. // clear the char representation of the credential Cleanser . wipe ( myCredential ) ; // clear the defensive copy of the password created earlier Cleanser . wipe ( myPassword ) ; // create a principal that includes the username and domain name that were used to authenticate the user final UserPrincipal userPrincipal = new UserPrincipal ( \"ID:\" + userName , domain , userName ) ; // wrap the principal in a Subject final Subject subject = new Subject ( ) ; subject . getPrincipals ( ) . add ( userPrincipal ) ; return subject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Read entities from stream ( by given reader ) and synchronize them into DB . < / p > [CODESPLIT] @ Override public final void readAndStoreEntities ( final Map < String , Object > pAddParam , final Reader pReader ) throws Exception { try { this . srvDatabase . setIsAutocommit ( false ) ; this . srvDatabase . setTransactionIsolation ( ISrvDatabase . TRANSACTION_READ_UNCOMMITTED ) ; this . srvDatabase . beginTransaction ( ) ; while ( this . utilXml . readUntilStart ( pReader , \"entity\" ) ) { Object entity = this . srvEntityReader . read ( pAddParam , pReader ) ; String nameEntitySync = this . mngSettings . lazClsSts ( entity . getClass ( ) ) . get ( \"ISrvEntitySync\" ) ; ISrvEntitySync srvEntitySync = this . srvEntitySyncMap . get ( nameEntitySync ) ; if ( srvEntitySync == null ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"There is no ISrvEntitySync \" + nameEntitySync + \" for \" + entity . getClass ( ) ) ; } boolean isNew = srvEntitySync . sync ( pAddParam , entity ) ; if ( isNew ) { this . srvOrm . insertEntity ( pAddParam , entity ) ; } else { this . srvOrm . updateEntity ( pAddParam , entity ) ; } } this . srvDatabase . commitTransaction ( ) ; } catch ( Exception ex ) { this . srvDatabase . rollBackTransaction ( ) ; throw ex ; } finally { this . srvDatabase . releaseResources ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void init ( Properties properties ) { super . init ( properties ) ; if ( client == null ) client = new HttpClient ( ) ; String strBaseURL = properties . getProperty ( BASE_URL_PARAM ) ; if ( strBaseURL == null ) { strBaseURL = \"http://localhost/uploads/\" ; properties . setProperty ( BASE_URL_PARAM , strBaseURL ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { super . initTransfer ( properties ) ; String strBaseURL = properties . getProperty ( BASE_URL_PARAM ) ; if ( strBaseURL . length ( ) > 0 ) if ( strBaseURL . lastIndexOf ( ' ' ) != strBaseURL . length ( ) - 1 ) strBaseURL += ' ' ; m_strBaseURL = strBaseURL ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add this file to the destination . Note : Only supply the file or the stream not both . Supply the object that is easier given the source . This dual option is given to allow destinations that require File objects from ( such as FTP or HTTP ) Having to write the inStream to a physical file before processing it . [CODESPLIT] public long addNextFile ( SourceFile source ) { String strPath = source . getFilePath ( ) ; long lStreamLength = source . getStreamLength ( ) ; HttpClient client = new HttpClient ( ) ; File fileIn = source . makeInFile ( ) ; String furl = m_strBaseURL + this . encodeURL ( strPath ) ; PutMethod put = new PutMethod ( furl ) ; try { RequestEntity entity = new InputStreamRequestEntity ( new FileInputStream ( fileIn ) ) ; put . setRequestEntity ( entity ) ; int response = client . executeMethod ( put ) ; if ( response != 201 ) System . out . println ( \"Error Response: \" + response ) ; } catch ( HttpException e ) { e . printStackTrace ( ) ; } catch ( FileNotFoundException ex ) { ex . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return lStreamLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Convert the URL to the proper format . [CODESPLIT] public String encodeURL ( String strURL ) { String furl = JBackupConstants . BLANK ; try { int iStart = 0 ; for ( int i = iStart ; i <= strURL . length ( ) ; i ++ ) { if ( ( i == strURL . length ( ) ) || ( strURL . charAt ( i ) == ' ' ) ) { if ( iStart != i ) furl += URLEncoder . encode ( strURL . substring ( iStart , i ) , ENCODING ) ; if ( i != strURL . length ( ) ) furl += ' ' ; iStart = i + 1 ; } } } catch ( UnsupportedEncodingException ex ) { ex . printStackTrace ( ) ; } return furl ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "哪些数据库字段运行指定长度 . [CODESPLIT] public boolean supportsColumnLength ( String type ) { Set < String > columnSet = new HashSet < String > ( ) ; columnSet . add ( \"char\" ) ; columnSet . add ( \"nchar\" ) ; columnSet . add ( \"varchar\" ) ; columnSet . add ( \"nvarchar\" ) ; columnSet . add ( \"varchar2\" ) ; columnSet . add ( \"nvarchar2\" ) ; columnSet . add ( \"number\" ) ; columnSet . add ( \"numeric\" ) ; columnSet . add ( \"dec\" ) ; columnSet . add ( \"decimal\" ) ; return columnSet . contains ( type . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "哪些数据库字段运行指定精度 . [CODESPLIT] public boolean supportsColumnScale ( String type ) { Set < String > columnSet = new HashSet < String > ( ) ; columnSet . add ( \"number\" ) ; columnSet . add ( \"numeric\" ) ; columnSet . add ( \"dec\" ) ; columnSet . add ( \"decimal\" ) ; return columnSet . contains ( type . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将数据库无关的 SubStyleType 转换成具体数据库的字段名称。特殊的字段类型由子类实现。 [CODESPLIT] public String asSqlType ( String type , Integer length , Integer scale ) { if ( SubStyleType . UID . equals ( type ) ) { return \"bigint\" ; } else if ( SubStyleType . UUID . equals ( type ) ) { return \"char(16)\" ; } else if ( SubStyleType . ENUM . equals ( type ) ) { return \"integer\" ; } else if ( SubStyleType . INT . equals ( type ) ) { return \"integer\" ; } else if ( SubStyleType . LONG . equals ( type ) ) { return \"bigint\" ; } else if ( SubStyleType . BIGINT . equals ( type ) ) { return \"decimal(38, 0)\" ; } else if ( SubStyleType . DOUBLE . equals ( type ) ) { return \"double\" ; } else if ( SubStyleType . DECIMAL . equals ( type ) ) { return new SqlType ( \"decimal\" , length , scale ) . toString ( ) ; } else if ( SubStyleType . CHAR . equals ( type ) ) { return new SqlType ( \"char\" , length , null ) . toString ( ) ; } else if ( SubStyleType . VARCHAR . equals ( type ) ) { return new SqlType ( \"varchar\" , length , null ) . toString ( ) ; } else if ( SubStyleType . TEXT . equals ( type ) ) { return new SqlType ( \"longvarchar\" , Integer . MAX_VALUE , null ) . toString ( ) ; } else if ( SubStyleType . BOOLEAN . equals ( type ) ) { return \"tinyint(1)\" ; } else if ( SubStyleType . DATETIME_STRING . equals ( type ) ) { return \"char(19)\" ; } else if ( SubStyleType . DATE_STRING . equals ( type ) ) { return \"char(10)\" ; } else if ( SubStyleType . TIME_STRING . equals ( type ) ) { return \"char(8)\" ; } else if ( SubStyleType . DATETIME . equals ( type ) ) { return \"timestamp\" ; } else if ( SubStyleType . TIMESTAMP . equals ( type ) ) { return \"timestamp\" ; } else if ( SubStyleType . DATE . equals ( type ) ) { return \"date\" ; } else if ( SubStyleType . TIME . equals ( type ) ) { return \"time\" ; } else if ( SubStyleType . CLOB . equals ( type ) ) { return \"clob\" ; } else if ( SubStyleType . BLOB . equals ( type ) ) { return \"blob\" ; } else if ( SubStyleType . INPUTSTREAM . equals ( type ) ) { return \"longvarbinary\" ; } else { return new SqlType ( type , length , scale ) . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将字段名 / 表名与SQL保留字冲突的名称进行 Wrapper [CODESPLIT] public String getIdentifier ( String name ) { String upperCaseName = name . toUpperCase ( ) ; if ( iso_reservedWords . contains ( upperCaseName ) ) { return getQuotedIdentifier ( name ) ; } if ( reservedWords . contains ( upperCaseName ) ) { return getQuotedIdentifier ( name ) ; } return name ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查找完全匹配的方法或者构造函数 . [CODESPLIT] public static < T extends Executable > T getExecutable ( List < T > executables , String name , Class < ? > ... parameterTypes ) { for ( T info : executables ) { if ( name == null || info . getName ( ) . equals ( name ) ) { Class < ? > [ ] types = info . getParameterTypes ( ) ; if ( parameterTypes . length == types . length ) { boolean match = true ; for ( int i = 0 ; i < parameterTypes . length ; i ++ ) { if ( types [ i ] != parameterTypes [ i ] ) { match = false ; break ; } } if ( match ) { return info ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "查找最佳匹配的方法或者构造函数。 [CODESPLIT] public static < T extends Executable > T searchExecutable ( List < T > executables , String name , Class < ? > ... parameterTypes ) { T best = null ; Class < ? > [ ] bestParametersTypes = null ; for ( T execute : executables ) { if ( name != null && ! execute . getName ( ) . equals ( name ) ) continue ; Class < ? > [ ] types = execute . getParameterTypes ( ) ; if ( isParameterTypesCompatible ( types , parameterTypes , execute . isVarArgs ( ) , false ) ) { // 可能有多个方法与实际参数类型兼容。采用就近兼容原则。 if ( best == null ) { best = execute ; bestParametersTypes = types ; } else if ( best . isVarArgs ( ) && ( ! execute . isVarArgs ( ) ) ) { best = execute ; // 不可变参数的函数优先 bestParametersTypes = types ; } else if ( ( ! best . isVarArgs ( ) ) && execute . isVarArgs ( ) ) { // no change } else { if ( isParameterTypesCompatible ( bestParametersTypes , types , best . isVarArgs ( ) , execute . isVarArgs ( ) ) ) { best = execute ; bestParametersTypes = types ; } } } } return best ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断参数列表是否兼容 支持可变参数 . [CODESPLIT] public static boolean isParameterTypesCompatible ( Class < ? > [ ] lhs , Class < ? > [ ] rhs , boolean lhsVarArgs , boolean rhsVarArgs ) { if ( lhs == null ) { return rhs == null || rhs . length == 0 ; } if ( rhs == null ) { return lhs . length == 0 ; } if ( lhsVarArgs && rhsVarArgs ) { if ( lhs . length != rhs . length ) { return false ; } //校验前面的固定参数 for ( int i = 0 ; i < lhs . length - 1 ; i ++ ) { if ( ! ClassUtils . isAssignable ( lhs [ i ] , rhs [ i ] ) ) { return false ; } } // 校验最后一个可变参数 Class < ? > c1 = lhs [ lhs . length - 1 ] . getComponentType ( ) ; Class < ? > c2 = rhs [ rhs . length - 1 ] . getComponentType ( ) ; if ( ! ClassUtils . isAssignable ( c1 , c2 ) ) { return false ; } } else if ( lhsVarArgs ) { if ( lhs . length - 1 > rhs . length ) { return false ; } //校验前面的固定参数 for ( int i = 0 ; i < lhs . length - 1 ; i ++ ) { if ( ! ClassUtils . isAssignable ( lhs [ i ] , rhs [ i ] ) ) { return false ; } } // 校验最后一个可变参数 Class < ? > varType = lhs [ lhs . length - 1 ] . getComponentType ( ) ; for ( int i = lhs . length - 1 ; i < rhs . length ; i ++ ) { if ( ! ClassUtils . isAssignable ( varType , rhs [ i ] ) ) { return false ; } } } else { if ( lhs . length != rhs . length ) { return false ; } for ( int i = 0 ; i < lhs . length ; i ++ ) { if ( ! ClassUtils . isAssignable ( lhs [ i ] , rhs [ i ] ) ) { return false ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void write ( char [ ] cbuf , int off , int len ) throws IOException { int posInSeparatorChars = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( identBeforeNextChar ) { base . write ( ' ' ) ; identBeforeNextChar = false ; } base . write ( cbuf [ i ] ) ; if ( cbuf [ i ] == separatorChars [ posInSeparatorChars ] ) { posInSeparatorChars ++ ; if ( posInSeparatorChars == separatorChars . length ) { identBeforeNextChar = true ; posInSeparatorChars = 0 ; } } else { posInSeparatorChars = 0 ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns normalized <code > path< / code > ( or simply the <code > path< / code > if it is already in normalized form ) . Normalized path does not contain any empty or . segments or .. segments preceded by other segment than .. . [CODESPLIT] public static String normalize ( final String path ) { if ( path == null ) { return null ; } if ( path . indexOf ( ' ' ) == - 1 && path . indexOf ( ' ' ) == - 1 ) { return path ; } boolean wasNormalized = true ; // 1. count number of nonempty segments in path // Note that this step is not really necessary because we could simply // estimate the number of segments as path.length() and do the empty // segment check in step two ;-). int numSegments = 0 ; int lastChar = path . length ( ) - 1 ; for ( int src = lastChar ; src >= 0 ; ) { int slash = path . lastIndexOf ( ' ' , src ) ; if ( slash != - 1 ) { // empty segment? (two adjacent slashes?) if ( slash == src ) { if ( src != lastChar ) { // ignore the first slash occurence // (when numSegments == 0) wasNormalized = false ; } } else { numSegments ++ ; } } else { numSegments ++ ; } src = slash - 1 ; } // 2. split path to segments skipping empty segments int [ ] segments = new int [ numSegments ] ; char [ ] chars = new char [ path . length ( ) ] ; path . getChars ( 0 , chars . length , chars , 0 ) ; numSegments = 0 ; for ( int src = 0 ; src < chars . length ; ) { // skip empty segments while ( src < chars . length && chars [ src ] == ' ' ) { src ++ ; } if ( src < chars . length ) { // note the segment start segments [ numSegments ++ ] = src ; // seek to the end of the segment while ( src < chars . length && chars [ src ] != ' ' ) { src ++ ; } } } // assert (numSegments == segments.length); // 3. scan segments and remove all \".\" segments and \"foo\",\"..\" segment pairs final int DELETED = - 1 ; for ( int segment = 0 ; segment < numSegments ; segment ++ ) { int src = segments [ segment ] ; if ( chars [ src ++ ] == ' ' ) { if ( src == chars . length || chars [ src ] == ' ' ) { // \".\" or\"./\" // delete the \".\" segment segments [ segment ] = DELETED ; wasNormalized = false ; } else { // \".something\" if ( chars [ src ++ ] == ' ' && ( src == chars . length || chars [ src ] == ' ' ) ) { // \"..\" or \"../\" // we have the \"..\" segment scan backwards for segment to delete together with \"..\" for ( int toDelete = segment - 1 ; toDelete >= 0 ; toDelete -- ) { if ( segments [ toDelete ] != DELETED ) { if ( chars [ segments [ toDelete ] ] != ' ' ) { // delete the two segments segments [ toDelete ] = DELETED ; segments [ segment ] = DELETED ; wasNormalized = false ; } break ; } } } } } } // 4. join the result, if necessary if ( wasNormalized ) { // already normalized? nothing to do... return path ; } else { // join the resulting normalized path, retain the leading and ending slash int dst = ( chars [ 0 ] == ' ' ) ? 1 : 0 ; for ( int segment = 0 ; segment < numSegments ; segment ++ ) { int segmentStart = segments [ segment ] ; if ( segmentStart != DELETED ) { // if we remembered segment lengths in step 2, we could use // System.arraycopy method now but we had to allocate one // more array for ( int src = segmentStart ; src < chars . length ; src ++ ) { char ch = chars [ src ] ; chars [ dst ++ ] = ch ; if ( ch == ' ' ) { break ; } } } } return new String ( chars , 0 , dst ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "组合路径 . [CODESPLIT] public static String concat ( final String parent , final String child ) { if ( parent == null ) { return normalize ( child ) ; } if ( child == null ) { return normalize ( parent ) ; } return normalize ( parent + ' ' + child ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "计算相对路径 . [CODESPLIT] public static String getRelativePath ( final String path , final String relativePath ) { if ( relativePath . startsWith ( \"/\" ) ) { return normalize ( relativePath ) ; } int separatorIndex = path . lastIndexOf ( ' ' ) ; if ( separatorIndex != - 1 ) { String newPath = path . substring ( 0 , separatorIndex + 1 ) ; return normalize ( newPath + relativePath ) ; } else { return normalize ( relativePath ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "转为 Unix 样式的路径 . [CODESPLIT] public static String separatorsToUnix ( String path ) { if ( path == null || path . indexOf ( ' ' ) == - 1 ) { return path ; } return path . replace ( ' ' , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "转为 Windows 样式的路径 . [CODESPLIT] public static String separatorsToWindows ( String path ) { if ( path == null || path . indexOf ( ' ' ) == - 1 ) { return path ; } return path . replace ( ' ' , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "转为系统默认样式的路径 . [CODESPLIT] public static String separatorsToSystem ( String path ) { if ( path == null ) { return null ; } if ( File . separatorChar == ' ' ) { return separatorsToWindows ( path ) ; } return separatorsToUnix ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "将 Class 对象转成 KlassInfo 对象 ( 有缓存 ) . [CODESPLIT] public static KlassInfo create ( final Class < ? > clazz ) { KlassInfo klass = pool . get ( clazz ) ; if ( klass == null ) { klass = new KlassInfo ( clazz ) ; KlassInfo old = pool . putIfAbsent ( clazz , klass ) ; if ( old != null ) { klass = old ; } } return klass ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据目标参数类型，查找完全匹配的构造函数 . [CODESPLIT] public ConstructorInfo getDeclaredConstructor ( Class < ? > ... parameterTypes ) { return ExecutableUtils . getExecutable ( declaredConstructorsGetter . get ( ) , null , parameterTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据目标参数类型，查找最佳匹配的构造函数 . [CODESPLIT] public ConstructorInfo searchDeclaredConstructor ( Class < ? > ... parameterTypes ) { ConstructorInfo constructor = ExecutableUtils . getExecutable ( declaredConstructorsGetter . get ( ) , null , parameterTypes ) ; if ( constructor == null ) { constructor = ExecutableUtils . searchExecutable ( declaredConstructorsGetter . get ( ) , null , parameterTypes ) ; } return constructor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据目标参数类型，查找完全匹配的方法 . [CODESPLIT] public MethodInfo getMethod ( String name , Class < ? > ... parameterTypes ) { return ExecutableUtils . getExecutable ( methodsGetter . get ( ) , name , parameterTypes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "根据目标参数类型，查找最佳匹配的方法 . [CODESPLIT] public MethodInfo searchMethod ( String name , Class < ? > ... parameterTypes ) { MethodInfo method = ExecutableUtils . getExecutable ( methodsGetter . get ( ) , name , parameterTypes ) ; if ( method == null ) { method = ExecutableUtils . searchExecutable ( methodsGetter . get ( ) , name , parameterTypes ) ; } return method ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "反射调用计数器，超过阈值，则使用 ASM 字节码增强技术 [CODESPLIT] protected ASMAccessor getASMAccessor ( ) { if ( asmAccessor == null ) { if ( asmCallNumber >= ASMFactory . getThreshold ( ) ) { asmAccessor = ASMFactory . generateAccessor ( this ) ; } else { asmCallNumber ++ ; } } return asmAccessor ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "调用默认的构造函数生成对象实例 . [CODESPLIT] public Object newInstance ( ) throws IllegalStateException { ASMAccessor accessor = getASMAccessor ( ) ; if ( accessor == null ) { ConstructorInfo ctor = getDefaultConstructor ( ) ; if ( ctor != null ) { return ctor . newInstance ( ) ; } throw new IllegalStateException ( \"No default constructor\" ) ; } else { return accessor . newInstance ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the field value from the supplied <code > pojo< / code > object . If a <code > pojoGetter< / code has been set in the { @link ProtobufAttribute } then use that otherwise try getting the field value directly . [CODESPLIT] private static final Object getPojoFieldValue ( Object pojo , ProtobufAttribute protobufAttribute , Field field ) throws ProtobufAnnotationException { final String getter = protobufAttribute . pojoGetter ( ) ; Object value = null ; if ( ! getter . isEmpty ( ) ) { try { return JReflectionUtils . runMethod ( pojo , getter ) ; } catch ( Exception e ) { throw new ProtobufAnnotationException ( \"Could not get a value for field \" + field . getName ( ) + \" using configured getter of \" + getter , e ) ; } } try { value = JReflectionUtils . runGetter ( pojo , field ) ; } catch ( Exception ee ) { throw new ProtobufAnnotationException ( \"Could not execute getter \" + getter + \" on class \" + pojo . getClass ( ) . getCanonicalName ( ) + \": \" + ee , ee ) ; } if ( value == null && protobufAttribute . required ( ) ) { throw new ProtobufAnnotationException ( \"Required field \" + field . getName ( ) + \" on class \" + pojo . getClass ( ) . getCanonicalName ( ) + \" is null\" ) ; } return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new serializer and serializes the supplied object / attribute . [CODESPLIT] private static final Object serializeToProtobufEntity ( Object pojo ) throws JException { final ProtobufEntity protoBufEntity = ProtobufSerializerUtils . getProtobufEntity ( pojo . getClass ( ) ) ; if ( protoBufEntity == null ) { return pojo ; } return new ProtobufSerializer ( ) . toProtobuf ( pojo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new serializer and ( de ) serializes the supplied Protobu / attribute to a POJO of type <i > pojoClazz< / i > . [CODESPLIT] private static final Object serializeFromProtobufEntity ( Message protoBuf , Class < ? > pojoClazz ) throws JException { final ProtobufEntity protoBufEntity = ProtobufSerializerUtils . getProtobufEntity ( pojoClazz ) ; if ( protoBufEntity == null ) { return protoBuf ; } return new ProtobufSerializer ( ) . fromProtobuf ( protoBuf , pojoClazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loops through the collection of objects and serializes them iff they have ProtobufEntity annotations . [CODESPLIT] private static final Object convertCollectionToProtobufs ( Collection < Object > collectionOfNonProtobufs ) throws JException { if ( collectionOfNonProtobufs . isEmpty ( ) ) { return collectionOfNonProtobufs ; } final Object first = collectionOfNonProtobufs . toArray ( ) [ 0 ] ; if ( ! ProtobufSerializerUtils . isProtbufEntity ( first ) ) { return collectionOfNonProtobufs ; } final Collection < Object > newCollectionValues ; /**\n     * Maintain the Collection type of value at this stage (if it is a Set), and if conversion is required to a\n     * different Collection type, that will be handled by a converter later on\n     */ if ( collectionOfNonProtobufs instanceof Set ) { newCollectionValues = new HashSet <> ( ) ; } else { newCollectionValues = new ArrayList <> ( ) ; } for ( Object iProtobufGenObj : collectionOfNonProtobufs ) { newCollectionValues . add ( serializeToProtobufEntity ( iProtobufGenObj ) ) ; } return newCollectionValues ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method does the actual set on the Protobuf builder . If the user specified a converter then use that right before we actually try and set the value . [CODESPLIT] private static final void setProtobufFieldValue ( ProtobufAttribute protobufAttribute , Builder protoObjBuilder , String setter , Object fieldValue ) throws NoSuchMethodException , SecurityException , ProtobufAnnotationException , InstantiationException , IllegalAccessException , IllegalArgumentException , InvocationTargetException { Class < ? extends Object > fieldValueClass = fieldValue . getClass ( ) ; Class < ? extends Object > gpbClass = fieldValueClass ; final Class < ? extends IProtobufConverter > converterClazz = protobufAttribute . converter ( ) ; if ( converterClazz != NullConverter . class ) { final IProtobufConverter protoBufConverter = ( IProtobufConverter ) converterClazz . newInstance ( ) ; fieldValue = protoBufConverter . convertToProtobuf ( fieldValue ) ; gpbClass = fieldValue . getClass ( ) ; fieldValueClass = gpbClass ; } // Need to convert the argument class from non-primitives to primitives, as Protobuf uses these. gpbClass = ProtobufSerializerUtils . getProtobufClass ( fieldValue , gpbClass ) ; final Method gpbMethod = protoObjBuilder . getClass ( ) . getDeclaredMethod ( setter , gpbClass ) ; gpbMethod . invoke ( protoObjBuilder , fieldValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method does the actual set on the POJO instance . If the user specified a converter then use that right before we actually try and set the value . [CODESPLIT] private static final void setPojoFieldValue ( Object pojo , String setter , Object protobufValue , ProtobufAttribute protobufAttribute ) throws InstantiationException , IllegalAccessException , JException { /**\n     * convertCollectionFromProtoBufs() above returns an ArrayList, and we may have a converter to convert to a Set,\n     * so we are performing the conversion there\n     */ final Class < ? extends IProtobufConverter > fromProtoBufConverter = protobufAttribute . converter ( ) ; if ( fromProtoBufConverter != NullConverter . class ) { final IProtobufConverter converter = fromProtoBufConverter . newInstance ( ) ; protobufValue = converter . convertFromProtobuf ( protobufValue ) ; } Class < ? extends Object > argClazz = protobufValue . getClass ( ) ; JReflectionUtils . runSetter ( pojo , setter , protobufValue , argClazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests whether or not the specified abstract pathname should be included in a pathname list . [CODESPLIT] public boolean accept ( File pathname ) { String name = pathname . getName ( ) ; int iLastDot = name . lastIndexOf ( ' ' ) ; String strExtension = \"\" ; if ( ( iLastDot != - 1 ) && ( iLastDot != name . length ( ) - 1 ) ) strExtension = name . substring ( iLastDot + 1 ) ; if ( m_rgstrIncludeExtensions != null ) { for ( int i = 0 ; i < m_rgstrIncludeExtensions . length ; i ++ ) { if ( m_rgstrIncludeExtensions [ i ] . equalsIgnoreCase ( strExtension ) ) return true ; // Accept } return false ; // Not in included - return } if ( m_rgstrExcludeExtensions != null ) { for ( int i = 0 ; i < m_rgstrExcludeExtensions . length ; i ++ ) { if ( m_rgstrExcludeExtensions [ i ] . equalsIgnoreCase ( strExtension ) ) return false ; // Don't accept } } return true ; // Accept this file }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override // It would be pretty dumb to use varargs for the credential... @ SuppressWarnings ( \"PMD.UseVarargs\" ) public final boolean validate ( final char [ ] providedPassword , final char [ ] storedCredential ) { if ( providedPassword == null || storedCredential == null ) { return false ; } else { return Arrays . equals ( providedPassword , storedCredential ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Read entities from stream ( by given reader ) and insert them into DB with no changes . DB must be emptied before coping . < / p > [CODESPLIT] @ Override public final void readAndStoreEntities ( final Map < String , Object > pAddParam , final Reader pReader ) throws Exception { try { this . srvDatabase . setIsAutocommit ( false ) ; this . srvDatabase . setTransactionIsolation ( ISrvDatabase . TRANSACTION_READ_UNCOMMITTED ) ; this . srvDatabase . beginTransaction ( ) ; while ( this . utilXml . readUntilStart ( pReader , \"entity\" ) ) { Object entity = this . srvEntityReader . read ( pAddParam , pReader ) ; this . srvOrm . insertEntity ( pAddParam , entity ) ; } this . srvDatabase . commitTransaction ( ) ; } catch ( Exception ex ) { this . srvDatabase . rollBackTransaction ( ) ; throw ex ; } finally { this . srvDatabase . releaseResources ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a logging version of a ResultSet [CODESPLIT] public static ResultSet getInstance ( ResultSet rs ) { InvocationHandler handler = new JdbcLogResultSet ( rs ) ; ClassLoader cl = ResultSet . class . getClassLoader ( ) ; return ( ResultSet ) Proxy . newProxyInstance ( cl , new Class [ ] { ResultSet . class } , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Produces a mapping of label to index for use in parsing state values to the appropriate slot in the state object . [CODESPLIT] private static Map < ExpectedLabels , Integer > mapLabels ( final List < String > labels ) { final Map < ExpectedLabels , Integer > map = new EnumMap <> ( ExpectedLabels . class ) ; final List < ExpectedLabels > unusedLabels = new ArrayList <> ( Arrays . asList ( ExpectedLabels . values ( ) ) ) ; for ( int index = 0 ; index < labels . size ( ) ; index ++ ) { final String next = labels . get ( index ) ; ExpectedLabels labelValue ; try { labelValue = ExpectedLabels . valueOf ( next ) ; unusedLabels . remove ( labelValue ) ; if ( map . containsKey ( labelValue ) ) { LOGGER . warn ( \"Duplicate state label: {} ({})\" , next , labels ) ; } map . put ( labelValue , index ) ; } catch ( final IllegalArgumentException e ) { LOGGER . warn ( \"Unexpected state label: {}\" , next ) ; } } for ( final ExpectedLabels label : unusedLabels ) { LOGGER . warn ( \"Unused label: {}\" , label ) ; } return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Uses the provided label - index mapping to extract state values and create a new State object . [CODESPLIT] private static State extractValues ( final List < Object > values , final Map < ExpectedLabels , Integer > map ) { final ZonedDateTime time = ZonedDateTime . parse ( ( String ) values . get ( map . get ( ExpectedLabels . time ) ) ) ; final int temp = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . temp ) ) ) ; final int pressure = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . pressure ) ) ) ; final int humidity = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . humidity ) ) ) ; final int voc = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . voc ) ) ) ; final int light = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . light ) ) ) ; final int noise = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . noise ) ) ) ; final int noisedba = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . noisedba ) ) ) ; final int battery = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . battery ) ) ) ; final boolean shake = safeBoolean ( ( Boolean ) values . get ( map . get ( ExpectedLabels . shake ) ) ) ; final boolean cable = safeBoolean ( ( Boolean ) values . get ( map . get ( ExpectedLabels . cable ) ) ) ; final int vocResistance = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . voc_resistance ) ) ) ; final int rssi = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . rssi ) ) ) ; return new State ( time , temp , pressure , humidity , voc , light , noise , noisedba , battery , shake , cable , vocResistance , rssi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > It will clear current database . < / p > [CODESPLIT] @ Override public final void make ( final Map < String , Object > pAddParams ) throws Exception { ArrayList < Class < ? > > classesArr = new ArrayList < Class < ? > > ( this . mngSettings . getClasses ( ) ) ; try { this . srvDatabase . setIsAutocommit ( false ) ; this . srvDatabase . setTransactionIsolation ( ISrvDatabase . TRANSACTION_READ_UNCOMMITTED ) ; this . srvDatabase . beginTransaction ( ) ; this . logger . info ( null , SrvClearDatabase . class , \"Start clear database.\" ) ; for ( int i = classesArr . size ( ) - 1 ; i >= 0 ; i -- ) { Class < ? > entityClass = classesArr . get ( i ) ; this . srvDatabase . executeDelete ( entityClass . getSimpleName ( ) . toUpperCase ( ) , null ) ; } this . srvDatabase . commitTransaction ( ) ; Writer htmlWriter = ( Writer ) pAddParams . get ( \"htmlWriter\" ) ; if ( htmlWriter != null ) { htmlWriter . write ( \"<h4>\" + new Date ( ) . toString ( ) + \", \" + SrvClearDatabase . class . getSimpleName ( ) + \", database has been cleared\" + \"</h4>\" ) ; } this . logger . info ( null , SrvClearDatabase . class , \"Finish clear database.\" ) ; } catch ( Exception ex ) { this . srvDatabase . rollBackTransaction ( ) ; throw ex ; } finally { this . srvDatabase . releaseResources ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns raw class for given <code > type< / code > when implementation class is known and it makes difference . [CODESPLIT] public static Class < ? > getRawType ( Type type , Class < ? > implClass ) { if ( type instanceof Class ) { return ( Class < ? > ) type ; } if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; return getRawType ( pType . getRawType ( ) , implClass ) ; } if ( type instanceof WildcardType ) { WildcardType wType = ( WildcardType ) type ; Type [ ] lowerTypes = wType . getLowerBounds ( ) ; if ( lowerTypes . length > 0 ) { return getRawType ( lowerTypes [ 0 ] , implClass ) ; } Type [ ] upperTypes = wType . getUpperBounds ( ) ; if ( upperTypes . length != 0 ) { return getRawType ( upperTypes [ 0 ] , implClass ) ; } return Object . class ; } if ( type instanceof GenericArrayType ) { Type genericComponentType = ( ( GenericArrayType ) type ) . getGenericComponentType ( ) ; Class < ? > rawType = getRawType ( genericComponentType , implClass ) ; return Array . newInstance ( rawType , 0 ) . getClass ( ) ; } if ( type instanceof TypeVariable ) { TypeVariable < ? > varType = ( TypeVariable < ? > ) type ; if ( implClass != null ) { Type resolvedType = resolveVariable ( varType , implClass ) ; if ( resolvedType != null ) { return getRawType ( resolvedType , null ) ; } } Type [ ] boundsTypes = varType . getBounds ( ) ; if ( boundsTypes . length == 0 ) { return Object . class ; } return getRawType ( boundsTypes [ 0 ] , implClass ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves <code > TypeVariable< / code > with given implementation class . [CODESPLIT] public static Type resolveVariable ( TypeVariable < ? > variable , Class < ? > implClass ) { Class < ? > rawType = getRawType ( implClass , null ) ; int index = ArrayUtils . indexOf ( rawType . getTypeParameters ( ) , variable ) ; if ( index >= 0 ) { return variable ; } Class < ? > [ ] interfaces = rawType . getInterfaces ( ) ; Type [ ] genericInterfaces = rawType . getGenericInterfaces ( ) ; for ( int i = 0 ; i <= interfaces . length ; i ++ ) { Class < ? > rawInterface ; if ( i < interfaces . length ) { rawInterface = interfaces [ i ] ; } else { rawInterface = rawType . getSuperclass ( ) ; if ( rawInterface == null ) { continue ; } } Type resolved = resolveVariable ( variable , rawInterface ) ; if ( resolved instanceof Class || resolved instanceof ParameterizedType ) { return resolved ; } if ( resolved instanceof TypeVariable ) { TypeVariable < ? > typeVariable = ( TypeVariable < ? > ) resolved ; index = ArrayUtils . indexOf ( rawInterface . getTypeParameters ( ) , typeVariable ) ; if ( index < 0 ) { throw new IllegalArgumentException ( \"Can't resolve type variable:\" + typeVariable ) ; } Type type = i < genericInterfaces . length ? genericInterfaces [ i ] : rawType . getGenericSuperclass ( ) ; if ( type instanceof Class ) { return Object . class ; } if ( type instanceof ParameterizedType ) { return ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ index ] ; } throw new IllegalArgumentException ( \"Unsupported type: \" + type ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the component type of the given type . Returns <code > null< / code > if given type does not have a single component type . For example the following types all have the component - type MyClass : <ul > <li > MyClass [] < / li > <li > List&lt ; MyClass&gt ; < / li > <li > Foo&lt ; ? extends MyClass&gt ; < / li > <li > Bar&lt ; ? super MyClass&gt ; < / li > <li > &lt ; T extends MyClass&gt ; T [] < / li > < / ul > [CODESPLIT] public static Class < ? > getComponentType ( Type type , Class < ? > implClass , int index ) { if ( type instanceof Class ) { Class < ? > clazz = ( Class < ? > ) type ; if ( clazz . isArray ( ) ) { return clazz . getComponentType ( ) ; } } else if ( type instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) type ; Type [ ] generics = pt . getActualTypeArguments ( ) ; if ( index < 0 ) { index = generics . length + index ; } if ( index < generics . length ) { return getRawType ( generics [ index ] , implClass ) ; } } else if ( type instanceof GenericArrayType ) { GenericArrayType gat = ( GenericArrayType ) type ; return getRawType ( gat . getGenericComponentType ( ) , implClass ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns generic supertype for given class and 0 - based index . [CODESPLIT] public static Class < ? > getGenericSupertype ( Class < ? > type , int index ) { return getComponentType ( type . getGenericSuperclass ( ) , null , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Fill given field of given entity according value represented as string . < / p > [CODESPLIT] @ Override public final void fill ( final Map < String , Object > pAddParam , final Object pEntity , final String pFieldName , final String pFieldStrValue ) throws Exception { Field rField = getUtlReflection ( ) . retrieveField ( pEntity . getClass ( ) , pFieldName ) ; rField . setAccessible ( true ) ; if ( ! AHasIdString . class . isAssignableFrom ( rField . getType ( ) ) ) { throw new ExceptionWithCode ( ExceptionWithCode . CONFIGURATION_MISTAKE , \"It's wrong service to fill that field: \" + pEntity + \"/\" + pFieldName + \"/\" + pFieldStrValue ) ; } if ( \"NULL\" . equals ( pFieldStrValue ) ) { rField . set ( pEntity , null ) ; return ; } try { @ SuppressWarnings ( \"unchecked\" ) Constructor constructor = rField . getType ( ) . getDeclaredConstructor ( ) ; Object ownedEntity = constructor . newInstance ( ) ; ( ( AHasIdString ) ownedEntity ) . setItsId ( pFieldStrValue ) ; rField . set ( pEntity , ownedEntity ) ; } catch ( Exception ex ) { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , \"Can not fill field: \" + pEntity + \"/\" + pFieldName + \"/\" + pFieldStrValue + \", \" + ex . getMessage ( ) , ex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public Date getLastModified ( ) { Date lastModified = null ; for ( int i = 0 ; i < nodes . length ; i ++ ) { PathNode node = nodes [ i ] ; Date currentLastModified = node . getLastModified ( ) ; if ( currentLastModified != null ) { if ( ( lastModified == null ) || ( currentLastModified . after ( lastModified ) ) ) { lastModified = currentLastModified ; } } } return lastModified ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get everything ready . [CODESPLIT] public void init ( Properties properties ) { super . init ( properties ) ; String strHost = properties . getProperty ( FTP_HOST ) ; if ( strHost == null ) properties . setProperty ( FTP_HOST , \"localhost\" ) ; String strUsername = properties . getProperty ( USER_NAME ) ; if ( strUsername == null ) properties . setProperty ( USER_NAME , \"anonymous\" ) ; String strPassword = properties . getProperty ( PASSWORD ) ; if ( strPassword == null ) properties . setProperty ( PASSWORD , \"name@mailhost.com\" ) ; String m_strRootFTPDirectory = properties . getProperty ( ROOT_DIR ) ; if ( m_strRootFTPDirectory == null ) properties . setProperty ( ROOT_DIR , DEFAULT_ROOT_DIR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { super . initTransfer ( properties ) ; FTPClient client = new FTPClient ( ) ; if ( DEBUG ) System . out . println ( \"Connecting\" ) ; String strHost = properties . getProperty ( FTP_HOST , \"hd2-12.irv.zyan.com\" ) ; String strPort = properties . getProperty ( FTP_PORT , \"21\" ) ; int port = Integer . parseInt ( strPort ) ; String strUsername = properties . getProperty ( USER_NAME , \"anonymous\" ) ; String strPassword = properties . getProperty ( PASSWORD , \"doncorley@zyan.com\" ) ; m_strRootFTPDirectory = properties . getProperty ( ROOT_DIR , DEFAULT_ROOT_DIR ) ; if ( m_strRootFTPDirectory . endsWith ( \"/\" ) ) m_strRootFTPDirectory = m_strRootFTPDirectory . substring ( 0 , m_strRootFTPDirectory . length ( ) - 1 ) ; if ( m_strRootFTPDirectory . startsWith ( \"/\" ) ) m_strRootFTPDirectory = m_strRootFTPDirectory . substring ( 1 ) ; properties . setProperty ( FTP_HOST , strHost ) ; properties . setProperty ( USER_NAME , strUsername ) ; properties . setProperty ( PASSWORD , strPassword ) ; properties . setProperty ( ROOT_DIR , m_strRootFTPDirectory ) ; try { client . connect ( strHost , port ) ; if ( DEBUG ) System . out . println ( \"Connected to \" + strHost + \".\" ) ; // After connection attempt, you should check the reply code to verify // success. int reply = client . getReplyCode ( ) ; if ( FTPReply . isPositiveCompletion ( reply ) ) { client . login ( strUsername , strPassword ) ; client . enterLocalPassiveMode ( ) ; m_client = client ; // Flag success } else { // Error if ( DEBUG ) System . out . println ( \"FTP connect Error: \" + reply ) ; client . disconnect ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Cleanup . [CODESPLIT] public void finishTransfer ( Properties properties ) { if ( DEBUG ) System . out . println ( \"Disconnecting\" ) ; try { if ( m_client != null ) m_client . disconnect ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } m_client = null ; super . finishTransfer ( properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add this file to the destination . Note : Only supply the file or the stream not both . Supply the object that is easier given the source . This dual option is given to allow destinations that require File objects from ( such as FTP or HTTP ) Having to write the inStream to a physical file before processing it . [CODESPLIT] public long addNextFile ( SourceFile source ) { String strPath = source . getFilePath ( ) ; String strFilename = source . getFileName ( ) ; long lStreamLength = source . getStreamLength ( ) ; if ( m_client != null ) { // Success try { int reply = this . changeDirectory ( strPath ) ; if ( ! FTPReply . isPositiveCompletion ( reply ) ) { System . out . println ( \"Error on change dir: \" + reply ) ; } else { File fileIn = source . makeInFile ( false ) ; FileInputStream inStream = new FileInputStream ( fileIn ) ; if ( DEBUG ) System . out . println ( \"Sending File: \" + strFilename ) ; if ( m_client . storeFile ( strFilename , inStream ) ) // Upload this file { // Success } else { // Error } inStream . close ( ) ; } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return lStreamLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Change to this directory . [CODESPLIT] public int changeDirectory ( String strPath ) throws IOException { int iLastSlash = strPath . lastIndexOf ( ' ' ) ; if ( iLastSlash != - 1 ) strPath = strPath . substring ( 0 , iLastSlash ) ; else strPath = \"\" ; String strFTPPath = \"\" ; if ( m_strRootFTPDirectory . length ( ) > 0 ) { if ( ! strFTPPath . startsWith ( File . separator ) ) strFTPPath = File . separator + m_strRootFTPDirectory ; if ( strPath . length ( ) > 0 ) if ( ! strFTPPath . endsWith ( File . separator ) ) strFTPPath += File . separator ; } strFTPPath += strPath ; if ( strFTPPath . equals ( m_strLastPath ) ) return FTPReply . COMMAND_OK ; // Already in the current directory. if ( DEBUG ) System . out . println ( \"Change working directory to: \" + strFTPPath ) ; int iError = FTPReply . COMMAND_OK ; if ( ! m_client . changeWorkingDirectory ( strFTPPath ) ) { if ( ! m_client . makeDirectory ( strFTPPath ) ) iError = FTPReply . FILE_ACTION_NOT_TAKEN ; else if ( ! m_client . changeWorkingDirectory ( strFTPPath ) ) iError = FTPReply . FILE_ACTION_NOT_TAKEN ; } m_strLastPath = strFTPPath ; return iError ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll the configured objects now and store the results in the objects themselves . [CODESPLIT] public void poll ( ) throws IOException { synchronized ( this ) { // Make sure not to check and create a connection if shutting down. if ( shutdownInd ) { return ; } // Atomically indicate polling is active now so a caller can determine with certainty whether polling is //  completely shutdown. pollActiveInd = true ; } try { this . checkConnection ( ) ; this . concurrencyTestHooks . beforePollProcessorStart ( ) ; if ( this . mBeanAccessConnection instanceof MBeanBatchCapableAccessConnection ) { this . batchPollProcessor . pollBatch ( ( MBeanBatchCapableAccessConnection ) this . mBeanAccessConnection , this . polledObjects ) ; } else { this . pollIndividually ( ) ; } } catch ( IOException ioExc ) { this . safeClose ( this . mBeanAccessConnection ) ; this . mBeanAccessConnection = null ; throw ioExc ; } finally { this . concurrencyTestHooks . afterPollProcessorFinish ( ) ; synchronized ( this ) { pollActiveInd = false ; this . notifyAll ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Poll all of the objects one at a time . [CODESPLIT] protected boolean pollIndividually ( ) throws IOException { this . concurrencyTestHooks . onStartPollIndividually ( ) ; List < SchedulerProcessExecutionSlip > processExecutionSlipList = new LinkedList <> ( ) ; for ( final Object onePolledObject : this . polledObjects ) { // Stop as soon as possible if shutting down. if ( shutdownInd ) { return true ; } SchedulerProcess process = new PollOneObjectSchedulerProcess ( onePolledObject ) ; SchedulerProcessExecutionSlip executionSlip = this . scheduler . startProcess ( process ) ; processExecutionSlipList . add ( executionSlip ) ; } for ( SchedulerProcessExecutionSlip oneExecutionSlip : processExecutionSlipList ) { try { // // Wait for this process to complete // oneExecutionSlip . waitUntilComplete ( ) ; // // Check for a failure // PollOneObjectSchedulerProcess process = ( PollOneObjectSchedulerProcess ) oneExecutionSlip . getSchedulerProcess ( ) ; Exception exc = process . getFailureException ( ) ; if ( exc != null ) { log . warn ( \"failed to poll object\" , exc ) ; // Propagate IOExceptions since they most likely mean that the connection needs to be recovered. if ( exc instanceof IOException ) { throw ( IOException ) exc ; } } } catch ( InterruptedException intExc ) { log . info ( \"interrupted while polling object\" ) ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new instance of specified class and type [CODESPLIT] public static < T > T getInstance ( Class < T > clazz , boolean accessible , Class < ? > [ ] parameterTypes , Object [ ] paramValue ) { if ( clazz == null ) return null ; T t = null ; try { if ( parameterTypes != null && paramValue != null ) { Constructor < T > constructor = clazz . getDeclaredConstructor ( parameterTypes ) ; Object [ ] obj = new Object [ parameterTypes . length ] ; System . arraycopy ( paramValue , 0 , obj , 0 , parameterTypes . length ) ; constructor . setAccessible ( accessible ) ; t = constructor . newInstance ( obj ) ; } } catch ( SecurityException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( NoSuchMethodException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( InstantiationException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create new instance of specified class and type [CODESPLIT] public static < T > T getInstance ( Class < T > clazz , boolean accessible ) { if ( clazz == null ) return null ; T t = null ; try { Constructor < T > constructor = clazz . getDeclaredConstructor ( ) ; constructor . setAccessible ( accessible ) ; t = constructor . newInstance ( ) ; } catch ( InstantiationException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( SecurityException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( NoSuchMethodException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( IllegalArgumentException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } return t ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtain field If recursively is true obtain fields from all class hierarchy [CODESPLIT] public static Field getDeclaredField ( Class < ? > clazz , String fieldName , boolean recursively ) { try { return clazz . getDeclaredField ( fieldName ) ; } catch ( NoSuchFieldException e ) { Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { return getDeclaredField ( superClass , fieldName , true ) ; } } catch ( SecurityException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtain methods list of specified class If recursively is true obtain methods from all class hierarchy [CODESPLIT] public static Method [ ] getDeclaredMethods ( Class < ? > clazz , boolean recursively ) { List < Method > methods = new LinkedList < Method > ( ) ; Method [ ] declaredMethods = clazz . getDeclaredMethods ( ) ; Collections . addAll ( methods , declaredMethods ) ; Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { Method [ ] declaredMethodsOfSuper = getDeclaredMethods ( superClass , true ) ; if ( declaredMethodsOfSuper . length > 0 ) Collections . addAll ( methods , declaredMethodsOfSuper ) ; } return methods . toArray ( new Method [ methods . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtain method list of specified class If recursively is true obtain method from all class hierarchy [CODESPLIT] public static Method getDeclaredMethod ( Class < ? > clazz , boolean recursively , String methodName , Class < ? > ... parameterTypes ) { try { return clazz . getDeclaredMethod ( methodName , parameterTypes ) ; } catch ( NoSuchMethodException e ) { Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { return getDeclaredMethod ( superClass , true , methodName , parameterTypes ) ; } } catch ( SecurityException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtain constructor list of specified class If recursively is true obtain constructor from all class hierarchy [CODESPLIT] public static Constructor < ? > [ ] getDeclaredConstructors ( Class < ? > clazz , boolean recursively ) { List < Constructor < ? > > constructors = new LinkedList < Constructor < ? > > ( ) ; Constructor < ? > [ ] declaredConstructors = clazz . getDeclaredConstructors ( ) ; Collections . addAll ( constructors , declaredConstructors ) ; Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { Constructor < ? > [ ] declaredConstructorsOfSuper = getDeclaredConstructors ( superClass , true ) ; if ( declaredConstructorsOfSuper . length > 0 ) Collections . addAll ( constructors , declaredConstructorsOfSuper ) ; } return constructors . toArray ( new Constructor < ? > [ constructors . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtain constructor list of specified class If recursively is true obtain constructor from all class hierarchy [CODESPLIT] public static Constructor < ? > getDeclaredConstructor ( Class < ? > clazz , boolean recursively , Class < ? > ... parameterTypes ) { try { return clazz . getDeclaredConstructor ( parameterTypes ) ; } catch ( NoSuchMethodException e ) { Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { return getDeclaredConstructor ( superClass , true , parameterTypes ) ; } } catch ( SecurityException e ) { log . error ( \"{}\" , e . getMessage ( ) , e ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtain methods list of specified class and which are annotated by incoming annotation class If recursively is true obtain methods from all class hierarchy [CODESPLIT] public static Method [ ] getAnnotatedDeclaredMethods ( Class < ? > clazz , Class < ? extends Annotation > annotationClass , boolean recursively ) { Method [ ] allMethods = getDeclaredMethods ( clazz , recursively ) ; List < Method > annotatedMethods = new LinkedList < Method > ( ) ; for ( Method method : allMethods ) { if ( method . isAnnotationPresent ( annotationClass ) ) annotatedMethods . add ( method ) ; } return annotatedMethods . toArray ( new Method [ annotatedMethods . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "obtain constructors list of specified class and which are annotated by incoming annotation class If recursively is true obtain constructors from all class hierarchy [CODESPLIT] public static Constructor < ? > [ ] getAnnotatedDeclaredConstructors ( Class < ? > clazz , Class < ? extends Annotation > annotationClass , boolean recursively ) { Constructor < ? > [ ] allConstructors = getDeclaredConstructors ( clazz , recursively ) ; List < Constructor < ? > > annotatedConstructors = new LinkedList < Constructor < ? > > ( ) ; for ( Constructor < ? > field : allConstructors ) { if ( field . isAnnotationPresent ( annotationClass ) ) annotatedConstructors . add ( field ) ; } return annotatedConstructors . toArray ( new Constructor < ? > [ annotatedConstructors . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "回滚一个事务 [CODESPLIT] @ Override public void rollback ( ) { try { if ( conn . isClosed ( ) ) { throw new TransactionException ( \"the connection is closed in transaction.\" ) ; } conn . rollback ( savepoint ) ; } catch ( SQLException e ) { throw new TransactionException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "回滚一个事务 [CODESPLIT] @ Override public void rollback ( ) { try { if ( conn . isClosed ( ) ) { throw new TransactionException ( \"the connection is closed in transaction.\" ) ; } conn . rollback ( ) ; conn . setAutoCommit ( true ) ; } catch ( SQLException e ) { throw new TransactionException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "结束一个事务 [CODESPLIT] @ Override public void close ( ) { try { if ( conn . isClosed ( ) ) { throw new TransactionException ( \"the connection is closed in transaction.\" ) ; } DbUtils . closeQuietly ( conn ) ; } catch ( SQLException e ) { throw new TransactionException ( e ) ; } finally { transationHandler . set ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a logging version of a PreparedStatement [CODESPLIT] public static PreparedStatement getInstance ( PreparedStatement stmt , String sql ) { InvocationHandler handler = new JdbcLogPreparedStatement ( stmt , sql ) ; ClassLoader cl = PreparedStatement . class . getClassLoader ( ) ; return ( PreparedStatement ) Proxy . newProxyInstance ( cl , new Class [ ] { PreparedStatement . class } , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "是否支持该 resultClass [CODESPLIT] public boolean validate ( Class < ? > resultClass ) { // 查找：已经注册的类 if ( mapping . containsKey ( resultClass ) ) { return true ; } // 查找：用 annotation 标注，但是没有注册的 ResultHandler ManagedWith with = resultClass . getAnnotation ( ManagedWith . class ) ; if ( with != null && ResultHandler . class . isAssignableFrom ( with . value ( ) ) ) { register ( resultClass , with . value ( ) ) ; // 发现后注册 return true ; } // 查找：使用了已经注册的类的子类 for ( Map . Entry < Class < ? > , ResultHandler < ? > > entry : mapping . entrySet ( ) ) { Class < ? > targetClass = entry . getKey ( ) ; if ( targetClass != Object . class && targetClass . isAssignableFrom ( resultClass ) ) { mapping . put ( resultClass , entry . getValue ( ) ) ; // 发现后关联 return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; JPanel panelMain = this . makeNewPanel ( panel , BorderLayout . CENTER ) ; panelMain . setLayout ( new GridLayout ( 1 , 2 ) ) ; panelMain . add ( new JLabel ( \"Zip filename: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfRootPathname = new JTextField ( ) ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strPathname = m_tfRootPathname . getText ( ) ; m_properties . setProperty ( ZIPIN_FILENAME_PARAM , strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strPathname = m_properties . getProperty ( ZIPIN_FILENAME_PARAM ) ; m_tfRootPathname . setText ( strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "从一个标准的select语句中，生成一个 select count ( * ) 语句 [CODESPLIT] public static String get_sql_select_count ( String sql ) { String count_sql = sql . replaceAll ( \"\\\\s+\" , \" \" ) ; int pos = count_sql . toLowerCase ( ) . indexOf ( \" from \" ) ; count_sql = count_sql . substring ( pos ) ; pos = count_sql . toLowerCase ( ) . lastIndexOf ( \" order by \" ) ; int lastpos = count_sql . toLowerCase ( ) . lastIndexOf ( \")\" ) ; if ( pos != - 1 && pos > lastpos ) { count_sql = count_sql . substring ( 0 , pos ) ; } String regex = \"(left|right|inner) join (fetch )?\\\\w+(\\\\.\\\\w+)*\" ; Pattern p = Pattern . compile ( regex , Pattern . CASE_INSENSITIVE ) ; count_sql = p . matcher ( count_sql ) . replaceAll ( \"\" ) ; count_sql = \"select count(*) \" + count_sql ; return count_sql ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Accept this file? [CODESPLIT] public boolean accept ( File dir , String filename ) { String strPath = dir . getPath ( ) ; //\t\tif ((strPath.indexOf(\"mediumpics\") != -1) //\t\t\t|| (strPath.indexOf(\"smallpics\") != -1) //\t\t\t\t|| (strPath.indexOf(\"thumbpics\") != -1)) //\t\t\treturn false; //\t\tif (strPath.indexOf(\"\\\\trips\\\\\") != -1) if ( ( strPath . indexOf ( \"\\\\html\\\\pics\\\\pictures\\\\\" ) != - 1 ) && ( filename . indexOf ( \".html\" ) != - 1 ) && ( strPath . indexOf ( \"\\\\html\\\\pics\\\\pictures\\\\donandannie\\\\trips\" ) == - 1 ) ) return false ; // Don't replicate the html files, except the trip if ( ( strPath . indexOf ( \"\\\\html\\\\pics\\\\smallpics\\\\pictures\" ) != - 1 ) && ( filename . indexOf ( \".html\" ) != - 1 ) && ( strPath . indexOf ( \"\\\\html\\\\pics\\\\smallpics\\\\pictures\\\\donandannie\\\\trips\" ) == - 1 ) ) return false ; // Don't replicate the html files, except the trip return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Get ready to start processing . [CODESPLIT] public void init ( Properties properties ) { super . init ( properties ) ; String strPathname = properties . getProperty ( ZIPIN_FILENAME_PARAM ) ; if ( ( strPathname == null ) || ( strPathname . length ( ) == 0 ) ) { strPathname = \"in.zip\" ; properties . setProperty ( ZIPIN_FILENAME_PARAM , strPathname ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set up everything to start processing [CODESPLIT] public void initTransfer ( Properties properties ) { super . initTransfer ( properties ) ; m_strZipFilename = properties . getProperty ( ZIPIN_FILENAME_PARAM ) ; try { FileInputStream inStream = new FileInputStream ( m_strZipFilename ) ; m_inZip = new ZipInputStream ( inStream ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Close everything down after processing . [CODESPLIT] public void finishTransfer ( Properties properties ) { try { m_inZip . close ( ) ; } catch ( FileNotFoundException ex ) { ex . printStackTrace ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } super . finishTransfer ( properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next element in the interation . ( Returns a SourceFileObject ) . [CODESPLIT] public SourceFile next ( ) { if ( this . isPend ( ) ) return this . getPend ( ) ; try { ZipEntry entry = m_inZip . getNextEntry ( ) ; if ( entry == null ) return null ; // EOF String strPath = entry . getName ( ) ; String strFilename = strPath ; if ( strPath . lastIndexOf ( gchSeparator ) != - 1 ) if ( strPath . lastIndexOf ( gchSeparator ) + 1 < strPath . length ( ) ) strFilename = strPath . substring ( strPath . lastIndexOf ( gchSeparator ) + 1 ) ; long lStreamLength = entry . getSize ( ) ; if ( DEBUG ) System . out . println ( \"Name: \" + entry . getName ( ) + \" size: \" + entry . getSize ( ) ) ; return new StreamSourceFile ( null , m_inZip , strPath , strFilename , lStreamLength ) ; // Return the file } catch ( IOException ex ) { ex . printStackTrace ( ) ; } return null ; // pend(don) Don't do this! }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > It will clear current database then copy data from another with XML messages trough HTTPS connection . < / p > [CODESPLIT] @ Override public final void replicate ( final Map < String , Object > pAddParams ) throws Exception { Writer htmlWriter = ( Writer ) pAddParams . get ( \"htmlWriter\" ) ; try { //URL must be String urlSourceStr = \"https://\" + ( String ) pAddParams . get ( \"urlSource\" ) ; if ( urlSourceStr == null || urlSourceStr . length ( ) < 10 ) { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , \"Where is no urlSource!!!\" ) ; } URL url = new URL ( urlSourceStr ) ; String authMethod = ( String ) pAddParams . get ( \"authMethod\" ) ; if ( \"base\" . equals ( authMethod ) ) { final String userName = ( String ) pAddParams . get ( \"userName\" ) ; final String userPass = ( String ) pAddParams . get ( \"userPass\" ) ; Authenticator . setDefault ( new Authenticator ( ) { @ Override protected PasswordAuthentication getPasswordAuthentication ( ) { return new PasswordAuthentication ( userName , userPass . toCharArray ( ) ) ; } } ) ; } else if ( \"form\" . equals ( authMethod ) ) { CookieManager cookieManager = new CookieManager ( ) ; CookieHandler . setDefault ( cookieManager ) ; cookieManager . setCookiePolicy ( CookiePolicy . ACCEPT_ALL ) ; requestCookiesGet ( pAddParams ) ; authForm ( pAddParams , cookieManager ) ; } Map < String , Integer > classesCounts = makeJob ( url , pAddParams ) ; if ( htmlWriter != null ) { String statusString = \", replication has been done.\" ; htmlWriter . write ( \"<h4>\" + new Date ( ) . toString ( ) + statusString + \"</h4>\" ) ; pAddParams . put ( \"statusString\" , new Date ( ) . toString ( ) + \", \" + ReplicatorXmlHttp . class . getSimpleName ( ) + statusString ) ; this . logger . info ( null , ReplicatorXmlHttp . class , statusString ) ; htmlWriter . write ( \"<table>\" ) ; htmlWriter . write ( \"<tr><th style=\\\"padding: 5px;\\\">Class</th><th style=\\\"padding: 5px;\\\">Total records</th></tr>\" ) ; for ( Map . Entry < String , Integer > entry : classesCounts . entrySet ( ) ) { htmlWriter . write ( \"<tr>\" ) ; htmlWriter . write ( \"<td>\" + entry . getKey ( ) + \"</td>\" ) ; htmlWriter . write ( \"<td>\" + entry . getValue ( ) + \"</td>\" ) ; htmlWriter . write ( \"</tr>\" ) ; } htmlWriter . write ( \"</table>\" ) ; } } catch ( ExceptionWithCode ex ) { if ( htmlWriter != null ) { htmlWriter . write ( new Date ( ) . toString ( ) + \", \" + ReplicatorXmlHttp . class . getSimpleName ( ) + \", \" + ex . getShortMessage ( ) ) ; } this . logger . error ( null , ReplicatorXmlHttp . class , ex . getShortMessage ( ) ) ; throw ex ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > It copy data from another with XML messages through given HTTP connection . < / p > [CODESPLIT] public final Map < String , Integer > makeJob ( final URL pUrl , final Map < String , Object > pAddParams ) throws Exception { String requestedDatabaseId = ( String ) pAddParams . get ( \"requestedDatabaseId\" ) ; String maxRecordsStr = ( String ) pAddParams . get ( \"maxRecords\" ) ; if ( maxRecordsStr == null || maxRecordsStr . length ( ) == 0 ) { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , \"Where is no maxRecords!!!\" ) ; } int maxRecords = Integer . parseInt ( maxRecordsStr ) ; Map < String , Integer > classesCounts = new LinkedHashMap < String , Integer > ( ) ; Integer classCount = 0 ; boolean isDbPreparedBefore = false ; int databaseVersion = this . srvDatabase . getVersionDatabase ( ) ; for ( Class < ? > entityClass : this . mngSettings . getClasses ( ) ) { int entitiesReceived = 0 ; int firstRecord = 0 ; do { // HttpsURLConnection is single request connection HttpsURLConnection urlConnection = ( HttpsURLConnection ) pUrl . openConnection ( ) ; if ( ! pUrl . getHost ( ) . equals ( urlConnection . getURL ( ) . getHost ( ) ) ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , \"You should sign-in in browser first!\" ) ; } OutputStreamWriter writer = null ; BufferedReader reader = null ; try { urlConnection . setDoOutput ( true ) ; urlConnection . setRequestMethod ( \"POST\" ) ; if ( getCookies ( ) != null ) { urlConnection . addRequestProperty ( \"Cookie\" , getCookies ( ) ) ; } writer = new OutputStreamWriter ( urlConnection . getOutputStream ( ) , Charset . forName ( \"UTF-8\" ) . newEncoder ( ) ) ; String nameFilterEntities = this . mngSettings . lazClsSts ( entityClass ) . get ( \"filter\" ) ; String conditions = \"\" ; if ( nameFilterEntities != null ) { IFilterEntities filterEntities = this . filtersEntities . get ( nameFilterEntities ) ; if ( filterEntities != null ) { String cond = filterEntities . makeFilter ( entityClass , pAddParams ) ; if ( cond != null ) { conditions = \" where \" + cond ; } } } conditions += \" limit \" + maxRecords + \" offset \" + firstRecord ; String requestedDatabaseIdStr = \"\" ; if ( requestedDatabaseId != null ) { if ( Integer . parseInt ( requestedDatabaseId ) == getSrvDatabase ( ) . getIdDatabase ( ) ) { throw new ExceptionWithCode ( ExceptionWithCode . WRONG_PARAMETER , \"requested_database_must_be_different\" ) ; } requestedDatabaseIdStr = \"&requestedDatabaseId=\" + requestedDatabaseId ; } writer . write ( \"entityName=\" + entityClass . getCanonicalName ( ) + \"&conditions=\" + conditions + \"&requestingDatabaseVersion=\" + databaseVersion + requestedDatabaseIdStr ) ; writer . write ( \"&writerName=\" + pAddParams . get ( \"writerName\" ) ) ; writer . flush ( ) ; if ( HttpsURLConnection . HTTP_OK == urlConnection . getResponseCode ( ) ) { reader = new BufferedReader ( new InputStreamReader ( urlConnection . getInputStream ( ) , Charset . forName ( \"UTF-8\" ) . newDecoder ( ) ) ) ; if ( ! this . utilXml . readUntilStart ( reader , \"message\" ) ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , \"Wrong XML response without message tag!!!\" ) ; } Map < String , String > msgAttrsMap = this . srvEntityReaderXml . readAttributes ( pAddParams , reader ) ; String error = msgAttrsMap . get ( \"error\" ) ; if ( error != null ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , error ) ; } String entitiesCountStr = msgAttrsMap . get ( \"entitiesCount\" ) ; if ( entitiesCountStr == null ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , \"Wrong XML response without entitiesCount in message!!!\" ) ; } entitiesReceived = Integer . parseInt ( entitiesCountStr ) ; if ( entitiesReceived > 0 ) { classCount += entitiesReceived ; this . logger . info ( null , ReplicatorXmlHttp . class , \"Try to parse entities total: \" + entitiesReceived + \" of \" + entityClass . getCanonicalName ( ) ) ; if ( ! isDbPreparedBefore ) { if ( this . databasePrepearerBefore != null ) { this . databasePrepearerBefore . make ( pAddParams ) ; } isDbPreparedBefore = true ; } this . databaseReader . readAndStoreEntities ( pAddParams , reader ) ; if ( entitiesReceived == maxRecords ) { firstRecord += maxRecords ; } else { firstRecord = 0 ; entitiesReceived = 0 ; } } else { firstRecord = 0 ; } } else { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , \"Can't receive data!!! Response code=\" + urlConnection . getResponseCode ( ) ) ; } } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( writer != null ) { try { writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } urlConnection . disconnect ( ) ; } } while ( entitiesReceived > 0 ) ; classesCounts . put ( entityClass . getCanonicalName ( ) , classCount ) ; classCount = 0 ; } if ( this . databasePrepearerAfter != null ) { this . databasePrepearerAfter . make ( pAddParams ) ; } return classesCounts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Connect to secure address with method GET to receive authenticate cookies . < / p > [CODESPLIT] public final void requestCookiesGet ( final Map < String , Object > pAddParams ) throws Exception { String urlGetAuthCookStr = ( String ) pAddParams . get ( \"urlGetAuthCookies\" ) ; URL urlGetAuthCookies = new URL ( urlGetAuthCookStr ) ; HttpsURLConnection urlConnection = null ; BufferedReader reader = null ; try { urlConnection = ( HttpsURLConnection ) urlGetAuthCookies . openConnection ( ) ; urlConnection . setRequestMethod ( \"GET\" ) ; urlConnection . addRequestProperty ( \"Connection\" , \"keep-alive\" ) ; if ( HttpsURLConnection . HTTP_OK == urlConnection . getResponseCode ( ) ) { reader = new BufferedReader ( new InputStreamReader ( urlConnection . getInputStream ( ) , Charset . forName ( \"UTF-8\" ) . newDecoder ( ) ) ) ; while ( reader . read ( ) != - 1 ) { //NOPMD //just read out } } else { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , \"requestCookiesGet Can't receive data!!! Response code=\" + urlConnection . getResponseCode ( ) ) ; } } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( urlConnection != null ) { urlConnection . disconnect ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > It authenticate by post simulate form . < / p > [CODESPLIT] public final void authForm ( final Map < String , Object > pAddParams , final CookieManager pCookieManager ) throws Exception { String authUrl = ( String ) pAddParams . get ( \"authUrl\" ) ; String authUserName = ( String ) pAddParams . get ( \"authUserName\" ) ; String authUserPass = ( String ) pAddParams . get ( \"authUserPass\" ) ; String userName = ( String ) pAddParams . get ( \"userName\" ) ; String userPass = ( String ) pAddParams . get ( \"userPass\" ) ; URL url = new URL ( authUrl ) ; HttpsURLConnection urlConnection = ( HttpsURLConnection ) url . openConnection ( ) ; if ( ! url . getHost ( ) . equals ( urlConnection . getURL ( ) . getHost ( ) ) ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , \"You should sign-in in browser first!\" ) ; } OutputStreamWriter writer = null ; BufferedReader reader = null ; try { urlConnection . setDoOutput ( true ) ; urlConnection . setRequestMethod ( \"POST\" ) ; String paramStr = authUserName + \"=\" + userName + \"&\" + authUserPass + \"=\" + userPass ; StringBuffer cookiesSb = new StringBuffer ( ) ; for ( HttpCookie cookie : pCookieManager . getCookieStore ( ) . getCookies ( ) ) { cookiesSb . append ( cookie . getName ( ) + \"=\" + cookie . getValue ( ) + \";\" ) ; } setCookies ( cookiesSb . toString ( ) ) ; urlConnection . addRequestProperty ( \"Cookie\" , getCookies ( ) ) ; urlConnection . addRequestProperty ( \"Connection\" , \"keep-alive\" ) ; urlConnection . addRequestProperty ( \"Content-Type\" , \"application/x-www-form-urlencoded\" ) ; urlConnection . addRequestProperty ( \"Content-Length\" , String . valueOf ( paramStr . length ( ) ) ) ; boolean isDbgSh = this . logger . getDbgSh ( this . getClass ( ) ) && this . logger . getDbgFl ( ) < 8001 && this . logger . getDbgCl ( ) > 8003 ; if ( isDbgSh ) { getLogger ( ) . debug ( null , ReplicatorXmlHttp . class , \"Request before flush auth:\" ) ; for ( Map . Entry < String , List < String > > entry : urlConnection . getRequestProperties ( ) . entrySet ( ) ) { this . logger . debug ( null , ReplicatorXmlHttp . class , \"  Request entry key: \" + entry . getKey ( ) ) ; for ( String val : entry . getValue ( ) ) { this . logger . debug ( null , ReplicatorXmlHttp . class , \"   Request entry value: \" + val ) ; } } } writer = new OutputStreamWriter ( urlConnection . getOutputStream ( ) , Charset . forName ( \"UTF-8\" ) . newEncoder ( ) ) ; writer . write ( paramStr ) ; writer . flush ( ) ; reader = new BufferedReader ( new InputStreamReader ( urlConnection . getInputStream ( ) , Charset . forName ( \"UTF-8\" ) . newDecoder ( ) ) ) ; while ( reader . read ( ) != - 1 ) { //NOPMD //just read out } } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( writer != null ) { try { writer . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } urlConnection . disconnect ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Dumps single byte to output stream . [CODESPLIT] protected void dumpByte ( int b ) { if ( passThrough == true ) { System . out . print ( ' ' ) ; } if ( b < 0 ) { b += 128 ; } if ( b < 0x10 ) { System . out . print ( ' ' ) ; } System . out . print ( ' ' ) ; System . out . print ( Integer . toHexString ( b ) . toUpperCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "longvarbinary [CODESPLIT] public static Class < ? > getJavaClass ( String typeName ) { Class < ? > clazz = javaClassMapping . get ( typeName . toLowerCase ( ) ) ; return clazz == null ? Object . class : clazz ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check is broken [ LOG . info () ] : PMD reports issues although log stmt is guarded . [CODESPLIT] @ SuppressWarnings ( \"PMD.GuardLogStatementJavaUtil\" ) @ Override public final void create ( final Events event , final String userId ) { Validate . notNull ( event , \"The validated object 'event' is null\" ) ; Validate . notBlank ( userId , \"The validated character sequence 'userId' is null or empty\" ) ; // PMD does not recognize the guarded log statement if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"[MESSAGEQ] \" + event . getValue ( ) + \". User ID '\" + userId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Setter for lastDateReplication . < / p > [CODESPLIT] public final void setLastDateReplication ( final Date pLastDateReplication ) { if ( pLastDateReplication == null ) { this . lastDateReplication = null ; } else { this . lastDateReplication = new Date ( pLastDateReplication . getTime ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inspect the given ( Java ) class file in streaming mode . [CODESPLIT] private boolean readClassFile ( final ClassFileDataInput di ) throws IOException { if ( ! readMagicCode ( di ) ) { return false ; } if ( ! readVersion ( di ) ) { return false ; } readConstantPoolEntries ( di ) ; if ( ! readAccessFlags ( di ) ) { return false ; } readThisClass ( di ) ; readSuperClass ( di ) ; readInterfaces ( di ) ; readFields ( di ) ; readMethods ( di ) ; return readAttributes ( di , ElementType . TYPE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Look up the String value identified by the u2 index value from constant pool ( direct or indirect ) . [CODESPLIT] private String resolveUtf8 ( final DataInput di ) throws IOException { final int index = di . readUnsignedShort ( ) ; final Object value = constantPool [ index ] ; final String s ; if ( value instanceof Integer ) { s = ( String ) constantPool [ ( Integer ) value ] ; } else { s = ( String ) value ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Removes control characters ( char &lt ; = 32 ) from both ends of this String returning { @code null } if the String is empty ( ) after the trim or if it is { @code null } . [CODESPLIT] public static String trimToNull ( final String s ) { final String ts = trim ( s ) ; return ts == null || ts . length ( ) == 0 ? null : ts ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns either the passed in String or if the String is { @code null } the value of { @code defaultStr } . < / p > [CODESPLIT] public static String defaultIfNull ( final String s , final String defaultStr ) { return s == null ? defaultStr : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns either the passed in String or if the String is empty or { @code null } the value of { @code defaultStr } . < / p > [CODESPLIT] public static String defaultIfEmpty ( final String s , final String defaultStr ) { return isEmpty ( s ) ? defaultStr : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns either the passed in String or if the String is whitespace empty ( ) or { @code null } the value of { @code defaultStr } . < / p > [CODESPLIT] public static String defaultIfBlank ( final String s , final String defaultStr ) { return isBlank ( s ) ? defaultStr : s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Compares two CharSequences returning { @code true } if they represent equal sequences of characters ignoring case . < / p > [CODESPLIT] public static boolean equalsIgnoreCase ( final String s1 , final String s2 ) { if ( s1 == null || s2 == null ) { return s1 == s2 ; } else if ( s1 == s2 ) { return true ; } else if ( s1 . length ( ) != s2 . length ( ) ) { return false ; } else { return s1 . equals ( s2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Check if a String starts with a specified prefix ( optionally case insensitive ) . < / p > [CODESPLIT] private static boolean startsWith ( final String s , final String prefix , final boolean ignoreCase ) { if ( s == null || prefix == null ) { return s == null && prefix == null ; } if ( prefix . length ( ) > s . length ( ) ) { return false ; } return s . toString ( ) . regionMatches ( ignoreCase , 0 , prefix . toString ( ) , 0 , prefix . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Check if a String ends with a specified suffix ( optionally case insensitive ) . < / p > [CODESPLIT] private static boolean endsWith ( final String s , final String suffix , final boolean ignoreCase ) { if ( s == null || suffix == null ) { return s == null && suffix == null ; } if ( suffix . length ( ) > s . length ( ) ) { return false ; } final int strOffset = s . length ( ) - suffix . length ( ) ; return s . toString ( ) . regionMatches ( ignoreCase , strOffset , suffix . toString ( ) , 0 , suffix . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds first occurrence of a substring in the given source but within limited range [ start end ) . It is fastest possible code but still original <code > String . indexOf ( String int ) < / code > is much faster ( since it uses char [] value directly ) and should be used when no range is needed . [CODESPLIT] public static int indexOf ( String s , String substr , int startIndex , int endIndex ) { if ( startIndex < 0 ) { startIndex = 0 ; } int srclen = s . length ( ) ; if ( endIndex > srclen ) { endIndex = srclen ; } int sublen = substr . length ( ) ; if ( sublen == 0 ) { return startIndex > srclen ? srclen : startIndex ; } int total = endIndex - sublen + 1 ; char c = substr . charAt ( 0 ) ; mainloop : for ( int i = startIndex ; i < total ; i ++ ) { if ( s . charAt ( i ) != c ) { continue ; } int j = 1 ; int k = i + 1 ; while ( j < sublen ) { if ( substr . charAt ( j ) != s . charAt ( k ) ) { continue mainloop ; } j ++ ; k ++ ; } return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds first index of a substring in the given source string with ignored case . [CODESPLIT] public static int indexOfIgnoreCase ( String s , String substr ) { return indexOfIgnoreCase ( s , substr , 0 , s . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds first index of a substring in the given source string and range with ignored case . [CODESPLIT] public static int indexOfIgnoreCase ( String s , String substr , int startIndex , int endIndex ) { if ( startIndex < 0 ) { startIndex = 0 ; } int srclen = s . length ( ) ; if ( endIndex > srclen ) { endIndex = srclen ; } int sublen = substr . length ( ) ; if ( sublen == 0 ) { return startIndex > srclen ? srclen : startIndex ; } substr = substr . toLowerCase ( ) ; int total = endIndex - sublen + 1 ; char c = substr . charAt ( 0 ) ; mainloop : for ( int i = startIndex ; i < total ; i ++ ) { if ( Character . toLowerCase ( s . charAt ( i ) ) != c ) { continue ; } int j = 1 ; int k = i + 1 ; while ( j < sublen ) { char source = Character . toLowerCase ( s . charAt ( k ) ) ; if ( substr . charAt ( j ) != source ) { continue mainloop ; } j ++ ; k ++ ; } return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the very first index of a char from the specified array . It returns an int [ 2 ] where int [ 0 ] represents the char index and int [ 1 ] represents position where char was found . Returns <code > null< / code > if noting found . [CODESPLIT] public static int [ ] indexOf ( String s , char c [ ] , int start ) { int arrLen = c . length ; int index = Integer . MAX_VALUE ; int last = - 1 ; for ( int j = 0 ; j < arrLen ; j ++ ) { int i = s . indexOf ( c [ j ] , start ) ; if ( i != - 1 ) { if ( i < index ) { index = i ; last = j ; } } } return last == - 1 ? null : new int [ ] { last , index } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds last index of a substring in the given source string with ignored case . [CODESPLIT] public static int lastIndexOfIgnoreCase ( String s , String substr ) { return lastIndexOfIgnoreCase ( s , substr , s . length ( ) , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds last index of a substring in the given source string with ignored case . [CODESPLIT] public static int lastIndexOfIgnoreCase ( String s , String substr , int startIndex ) { return lastIndexOfIgnoreCase ( s , substr , startIndex , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds last index of a character in the given source string in specified range [ end start ] [CODESPLIT] public static int lastIndexOfIgnoreCase ( String s , char c , int startIndex , int endIndex ) { int total = s . length ( ) - 1 ; if ( total < 0 ) { return - 1 ; } if ( startIndex >= total ) { startIndex = total ; } if ( endIndex < 0 ) { endIndex = 0 ; } c = Character . toLowerCase ( c ) ; for ( int i = startIndex ; i >= endIndex ; i -- ) { if ( Character . toLowerCase ( s . charAt ( i ) ) == c ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the very last index of a substring from the specified array . It returns an int [ 2 ] where int [ 0 ] represents the substring index and int [ 1 ] represents position where substring was found . Returns <code > null< / code > if noting found . [CODESPLIT] public static int [ ] lastIndexOf ( String s , String arr [ ] ) { return lastIndexOf ( s , arr , s . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the very last index of a substring from the specified array . It returns an int [ 2 ] where int [ 0 ] represents the substring index and int [ 1 ] represents position where substring was found . Returns <code > null< / code > if noting found . [CODESPLIT] public static int [ ] lastIndexOf ( String s , String arr [ ] , int fromIndex ) { int arrLen = arr . length ; int index = - 1 ; int last = - 1 ; for ( int j = 0 ; j < arrLen ; j ++ ) { int i = s . lastIndexOf ( arr [ j ] , fromIndex ) ; if ( i != - 1 ) { if ( i > index ) { index = i ; last = j ; } } } return last == - 1 ? null : new int [ ] { last , index } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets a substring from the specified String avoiding exceptions . < / p > [CODESPLIT] public static String substring ( final String s , int start ) { if ( s == null ) { return null ; } // handle negatives, which means last n characters if ( start < 0 ) { start = s . length ( ) + start ; // remember start is negative } if ( start < 0 ) { start = 0 ; } if ( start > s . length ( ) ) { return \"\" ; } return s . substring ( start ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets a substring from the specified String avoiding exceptions . < / p > [CODESPLIT] public static String substring ( final String s , int start , int end ) { if ( s == null ) { return null ; } // handle negatives if ( end < 0 ) { end = s . length ( ) + end ; // remember end is negative } if ( start < 0 ) { start = s . length ( ) + start ; // remember start is negative } // check length next if ( end > s . length ( ) ) { end = s . length ( ) ; } // if start is greater than end, return \"\" if ( start > end ) { return \"\" ; } if ( start < 0 ) { start = 0 ; } if ( end < 0 ) { end = 0 ; } return s . substring ( start , end ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the substring before the first occurrence of a separator . The separator is not returned . < / p > [CODESPLIT] public static String substringBefore ( final String s , final String separator ) { if ( isEmpty ( s ) || separator == null ) { return s ; } if ( separator . isEmpty ( ) ) { return \"\" ; } final int pos = s . indexOf ( separator ) ; if ( pos < 0 ) { return s ; } return s . substring ( 0 , pos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the substring after the first occurrence of a separator . The separator is not returned . < / p > [CODESPLIT] public static String substringAfter ( final String s , final String separator ) { if ( isEmpty ( s ) ) { return s ; } if ( separator == null ) { return \"\" ; } final int pos = s . indexOf ( separator ) ; if ( pos < 0 ) { return \"\" ; } return s . substring ( pos + separator . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the substring before the last occurrence of a separator . The separator is not returned . < / p > [CODESPLIT] public static String substringBeforeLast ( final String s , final String separator ) { if ( isEmpty ( s ) || isEmpty ( separator ) ) { return s ; } final int pos = s . lastIndexOf ( separator ) ; if ( pos < 0 ) { return s ; } return s . substring ( 0 , pos ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the substring after the last occurrence of a separator . The separator is not returned . < / p > [CODESPLIT] public static String substringAfterLast ( final String s , final String separator ) { if ( isEmpty ( s ) ) { return s ; } if ( isEmpty ( separator ) ) { return \"\" ; } final int pos = s . lastIndexOf ( separator ) ; if ( pos < 0 || pos == s . length ( ) - separator . length ( ) ) { return \"\" ; } return s . substring ( pos + separator . length ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the String that is nested in between two instances of the same String . < / p > [CODESPLIT] public static String substringBetween ( final String s , final String tag ) { return substringBetween ( s , tag , tag ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the leftmost { @code len } characters of a String . < / p > [CODESPLIT] public static String left ( final String s , final int len ) { if ( s == null ) { return null ; } if ( len < 0 ) { return \"\" ; } if ( s . length ( ) <= len ) { return s ; } return s . substring ( 0 , len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets the rightmost { @code len } characters of a String . < / p > [CODESPLIT] public static String right ( final String s , final int len ) { if ( s == null ) { return null ; } if ( len < 0 ) { return \"\" ; } if ( s . length ( ) <= len ) { return s ; } return s . substring ( s . length ( ) - len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Gets { @code len } characters from the middle of a String . < / p > [CODESPLIT] public static String mid ( final String s , int pos , final int len ) { if ( s == null ) { return null ; } if ( len < 0 || pos > s . length ( ) ) { return \"\" ; } if ( pos < 0 ) { pos = 0 ; } if ( s . length ( ) <= pos + len ) { return s . substring ( pos ) ; } return s . substring ( pos , pos + len ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Repeat a String { @code repeat } times to form a new String . < / p > [CODESPLIT] public static String repeat ( final String s , final int repeat ) { if ( s == null ) { return null ; } if ( repeat <= 0 ) { return \"\" ; } final int inputLength = s . length ( ) ; if ( repeat == 1 || inputLength == 0 ) { return s ; } final int outputLength = inputLength * repeat ; switch ( inputLength ) { case 1 : return repeat ( s . charAt ( 0 ) , repeat ) ; case 2 : final char ch0 = s . charAt ( 0 ) ; final char ch1 = s . charAt ( 1 ) ; final char [ ] output2 = new char [ outputLength ] ; for ( int i = repeat * 2 - 2 ; i >= 0 ; i -- , i -- ) { output2 [ i ] = ch0 ; output2 [ i + 1 ] = ch1 ; } return new String ( output2 ) ; default : final StringBuilder buf = new StringBuilder ( outputLength ) ; for ( int i = 0 ; i < repeat ; i ++ ) { buf . append ( s ) ; } return buf . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Repeat a String { @code repeat } times to form a new String with a String separator injected each time . < / p > [CODESPLIT] public static String repeat ( final String s , final String separator , final int repeat ) { if ( s == null || separator == null ) { return repeat ( s , repeat ) ; } // given that repeat(String, int) is quite optimized, better to rely on // it than try and splice this into it final String result = repeat ( s + separator , repeat ) ; return removeEnd ( result , separator ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Deletes all whitespaces from a String as defined by { @link Character#isWhitespace ( char ) } . < / p > [CODESPLIT] public static String deleteWhitespace ( final String s ) { if ( isEmpty ( s ) ) { return s ; } final int sz = s . length ( ) ; final char [ ] chs = new char [ sz ] ; int count = 0 ; for ( int i = 0 ; i < sz ; i ++ ) { if ( ! Character . isWhitespace ( s . charAt ( i ) ) ) { chs [ count ++ ] = s . charAt ( i ) ; } } if ( count == sz ) { return s ; } return new String ( chs , 0 , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Removes a substring only if it is at the beginning of a source string otherwise returns the source string . < / p > [CODESPLIT] public static String removeStart ( final String s , final String remove ) { if ( isEmpty ( s ) || isEmpty ( remove ) ) { return s ; } if ( s . startsWith ( remove ) ) { return s . substring ( remove . length ( ) ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Case insensitive removal of a substring if it is at the beginning of a source string otherwise returns the source string . < / p > [CODESPLIT] public static String removeStartIgnoreCase ( final String s , final String remove ) { if ( isEmpty ( s ) || isEmpty ( remove ) ) { return s ; } if ( startsWithIgnoreCase ( s , remove ) ) { return s . substring ( remove . length ( ) ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Removes a substring only if it is at the end of a source string otherwise returns the source string . < / p > [CODESPLIT] public static String removeEnd ( final String s , final String remove ) { if ( isEmpty ( s ) || isEmpty ( remove ) ) { return s ; } if ( s . endsWith ( remove ) ) { return s . substring ( 0 , s . length ( ) - remove . length ( ) ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Case insensitive removal of a substring if it is at the end of a source string otherwise returns the source string . < / p > [CODESPLIT] public static String removeEndIgnoreCase ( final String s , final String remove ) { if ( isEmpty ( s ) || isEmpty ( remove ) ) { return s ; } if ( endsWithIgnoreCase ( s , remove ) ) { return s . substring ( 0 , s . length ( ) - remove . length ( ) ) ; } return s ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Removes all occurrences of a substring from within the source string . < / p > [CODESPLIT] public static String remove ( final String s , final String remove ) { if ( isEmpty ( s ) || isEmpty ( remove ) ) { return s ; } return replace ( s , remove , \"\" , - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all characters contained in provided string . [CODESPLIT] public static String removeChars ( String s , String chars ) { int i = s . length ( ) ; StringBuilder sb = new StringBuilder ( i ) ; for ( int j = 0 ; j < i ; j ++ ) { char c = s . charAt ( j ) ; if ( chars . indexOf ( c ) == - 1 ) { sb . append ( c ) ; } } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "按逗号分隔，两边加引号的不分割（CSV 规则） . [CODESPLIT] public static String [ ] splitCSV ( String str ) { if ( str == null ) return null ; String [ ] parts = StringUtils . split ( str , ' ' ) ; List < String > results = new ArrayList < String > ( ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { String s = parts [ i ] . trim ( ) ; if ( s . length ( ) == 0 ) { results . add ( s ) ; } else { char c = s . charAt ( 0 ) ; if ( c == ' ' || c == ' ' || c == ' ' ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( s ) ; while ( i + 1 < parts . length ) { if ( sb . length ( ) > 1 && s . length ( ) > 0 && s . charAt ( s . length ( ) - 1 ) == c ) { break ; } s = parts [ ++ i ] ; sb . append ( ' ' ) . append ( s ) ; } s = sb . toString ( ) . trim ( ) ; if ( s . charAt ( s . length ( ) - 1 ) == c ) { s = s . substring ( 1 , s . length ( ) - 1 ) ; } results . add ( s ) ; } else { results . add ( s ) ; } } } return results . toArray ( new String [ results . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override public final void initialize ( final Subject subject , final CallbackHandler callbackHandler , final Map < String , ? > sharedState , final Map < String , ? > options ) { LOG . debug ( \"Initializing\" ) ; Validate . notNull ( subject , \"The validated object 'subject' is null\" ) ; Validate . notNull ( callbackHandler , \"The validated object 'callbackHandler' is null\" ) ; Validate . notNull ( sharedState , \"The validated object 'sharedState' is null\" ) ; Validate . notNull ( options , \"The validated object 'options' is null\" ) ; // keep a reference to the originally provided arguments (no defensive copy) this . pSubject = subject ; this . pCallbackHandler = callbackHandler ; // It would be nice to parse the configuration only once, and store it for later use. However, we are // deliberately NOT caching the parsed configuration, as JAAS does not offer a standard way to to reset the // cached variable, and allow users of the login module to reset the parsed config in case an app does need to // re-read its configuration. final CommonProperties commonProps = JaasBasedCommonPropsBuilder . build ( options ) ; // initialize the audit object initAudit ( commonProps ) ; // initialize the message object initMessageQueue ( commonProps ) ; // initialize the validator object initPwValidator ( commonProps ) ; // initialize the authenticator object initPwAuthenticator ( commonProps ) ; LOG . info ( \"Initialization complete\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ Override // Check is broken [LOG.info()]: PMD reports issues although log stmt is guarded. @todo revisit when upgrading PMD. @ SuppressWarnings ( \"PMD.GuardLogStatementJavaUtil\" ) public final boolean login ( ) throws LoginException { LOG . debug ( \"Attempting login\" ) ; if ( pCallbackHandler == null ) { final String error = \"No CallbackHandler available to garner authentication information from the user\" ; LOG . error ( error ) ; throw new LoginException ( error ) ; } Callback [ ] callbacks = new Callback [ 3 ] ; callbacks [ 0 ] = new TextInputCallback ( \"j_domain\" ) ; callbacks [ 1 ] = new NameCallback ( \"j_username\" ) ; callbacks [ 2 ] = new PasswordCallback ( \"j_password\" , false ) ; try { pCallbackHandler . handle ( callbacks ) ; // store the domain domain = ( ( TextInputCallback ) callbacks [ 0 ] ) . getText ( ) ; // store the username username = ( ( NameCallback ) callbacks [ 1 ] ) . getName ( ) ; // store the password (i.e. a copy of the password) final char [ ] tempPassword = ( ( PasswordCallback ) callbacks [ 2 ] ) . getPassword ( ) ; password = tempPassword . clone ( ) ; // clear the password in the callback ( ( PasswordCallback ) callbacks [ 2 ] ) . clearPassword ( ) ; } catch ( java . io . IOException e ) { cleanState ( ) ; final String error = \"Encountered an I/O exception during login\" ; LOG . warn ( error , e ) ; throw Util . newLoginException ( error , e ) ; } catch ( UnsupportedCallbackException e ) { cleanState ( ) ; final String error = e . getCallback ( ) . toString ( ) + \" not available to garner authentication information from the user\" ; LOG . warn ( error , e ) ; throw Util . newLoginException ( error , e ) ; } LOG . debug ( \"Attempting login - discovered user '\" + username + \"@\" + domain + \"'\" ) ; // Using a try/catch construct for managing control flows is really a bad idea. // Unfortunately, this is how JAAS works :-( try { // authenticate, and update state and pending subject if successful pendingSubject = pwAuthenticator . authenticate ( domain , username , password , pwValidator ) ; // then clear the password Cleanser . wipe ( password ) ; final String baseError = new StringBuilder ( ) . append ( \"Login successful for '\" ) . append ( username ) . append ( \"@\" ) . append ( domain ) . toString ( ) ; AuditHelper . auditEvent ( audit , domain , username , Events . AUTHN_ATTEMPT , baseError + \"', but cannot audit login attempt, and hence fail the operation\" ) ; MessageHelper . postMessage ( messageQ , domain , username , Events . AUTHN_ATTEMPT , baseError + \"', but cannot post MQ login attempt event, and hence fail the operation\" ) ; // string concatenation is only executed if log level is actually enabled if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"Login complete for '\" + username + \"@\" + domain + \"'\" ) ; } return true ; } catch ( LoginException e ) { // the login failed // cache the username and domain, for they will be purged by \"cleanState()\" final String tempUsername = username ; final String tempDomain = domain ; cleanState ( ) ; final String baseError = new StringBuilder ( ) . append ( \"Login failed for '\" ) . append ( tempUsername ) . append ( \"@\" ) . append ( tempDomain ) . toString ( ) ; AuditHelper . auditEvent ( audit , tempDomain , tempUsername , Events . AUTHN_FAILURE , baseError + \"', but cannot audit login attempt\" ) ; MessageHelper . postMessage ( messageQ , tempDomain , tempUsername , Events . AUTHN_FAILURE , baseError + \"', but cannot post MQ login attempt event\" ) ; final String error = \"Login failed for '\" + tempUsername + \"@\" + tempDomain + \"'\" ; LOG . info ( error , e ) ; throw e ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override // Check is broken [LOG.info()]: PMD reports issues although log stmt is guarded. @todo revisit when upgrading PMD. @ SuppressWarnings ( \"PMD.GuardLogStatementJavaUtil\" ) public final boolean commit ( ) throws LoginException { LOG . debug ( \"Committing authentication\" ) ; if ( pendingSubject == null ) { // the login method of this module has failed earlier, hence we do not need to clean up anything // return 'false' to indicate that this module's login and/or commit method failed // As the login method failed, the state of the module has already been cleared and we do not know // the username / domain anymore. Hence no auditing / message queue notification, and not verbose logging. LOG . debug ( \"Not committing authentication, as the authentication has failed earlier (login method)\" ) ; return false ; } else { // The login has succeeded! // Store the principals from the pending subject both in the 'subject' object (because this is what JAAS // will use later on), but also create a new 'committedSubject' object that this module uses to a) keep // state and b) being able to remove the principals later LOG . debug ( \"Committing authentication: '\" + username + \"@\" + domain + \"'\" ) ; if ( committedSubject == null ) { committedSubject = new Subject ( ) ; } else { // cache the username and domain, for they will be purged by \"cleanState()\" final String tempUsername = username ; final String tempDomain = domain ; cleanState ( ) ; final String baseError = new StringBuilder ( ) . append ( \"Login post-processing failed for '\" ) . append ( tempUsername ) . append ( \"@\" ) . append ( tempDomain ) . toString ( ) ; AuditHelper . auditEvent ( audit , tempDomain , tempUsername , Events . AUTHN_ERROR , baseError + \"', but cannot audit login attempt\" ) ; MessageHelper . postMessage ( messageQ , tempDomain , tempUsername , Events . AUTHN_ERROR , baseError + \"', but cannot post MQ login attempt event\" ) ; final String error = \"Expected the committed subject to be 'null' (yes, really <null>), but this was \" + \"not the case! Has the commit method been called multiple times on the same object instance?\" ; LOG . warn ( error ) ; throw new LoginException ( error ) ; } for ( final Principal p : pendingSubject . getPrincipals ( ) ) { // 1. Add the principals to the 'subject' object if ( ! pSubject . getPrincipals ( ) . contains ( p ) ) { LOG . debug ( \"Added principal \" + p . getName ( ) + \" to subject\" ) ; pSubject . getPrincipals ( ) . add ( p ) ; } // 2. Add the principals to the 'committedSubject' object if ( ! committedSubject . getPrincipals ( ) . contains ( p ) ) { LOG . debug ( \"Added principal \" + p . getName ( ) + \" to committed subject\" ) ; committedSubject . getPrincipals ( ) . add ( p ) ; } } final String baseError = new StringBuilder ( ) . append ( \"Login succeeded for '\" ) . append ( username ) . append ( \"@\" ) . append ( domain ) . toString ( ) ; AuditHelper . auditEvent ( audit , domain , username , Events . AUTHN_SUCCESS , baseError + \"', but cannot audit login success, and hence fail the operation\" ) ; MessageHelper . postMessage ( messageQ , domain , username , Events . AUTHN_SUCCESS , baseError + \"', but cannot post MQ login success event, and hence fail the operation\" ) ; // string concatenation is only executed if log level is actually enabled if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"Authentication committed for '\" + username + \"@\" + domain + \"'\" ) ; } // do not clean the state here, as we may still need it in case of an abort() return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override // Check is broken [LOG.info()]: PMD reports issues although log stmt is guarded. @todo revisit when upgrading PMD. @ SuppressWarnings ( \"PMD.GuardLogStatementJavaUtil\" ) public final boolean abort ( ) throws LoginException { if ( pendingSubject == null ) { // the login method of this module has failed earlier, hence we do not need to clean up anything // return 'false' to indicate that this module's login and/or commit method failed // As the login method failed, the state of the module has already been cleared and we do not know // the username / domain anymore. Hence no auditing / message queue notification, and not verbose logging. LOG . debug ( \"Aborting authentication, as the authentication has failed earlier (login method)\" ) ; return false ; } else if ( committedSubject == null ) { // the login method of this module succeeded, but the overall authentication failed // string concatenation is only executed if log level is actually enabled if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Aborting authentication: '\" + username + \"@\" + domain + \"'\" ) ; } // cache the username and domain, for they will be purged by \"cleanState()\" final String tempUsername = username ; final String tempDomain = domain ; cleanState ( ) ; final String baseError = new StringBuilder ( ) . append ( \"Login post-processing failed after abort for '\" ) . append ( tempUsername ) . append ( \"@\" ) . append ( tempDomain ) . toString ( ) ; AuditHelper . auditEvent ( audit , tempDomain , tempUsername , Events . AUTHN_ABORT_COMMIT , baseError + \"', but cannot audit login attempt\" ) ; MessageHelper . postMessage ( messageQ , tempDomain , tempUsername , Events . AUTHN_ABORT_COMMIT , baseError + \"', but cannot post MQ login attempt event\" ) ; // string concatenation is only executed if log level is actually enabled if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"Authentication aborted for '\" + tempUsername + \"@\" + tempDomain + \"'\" ) ; } return true ; } else { // overall authentication succeeded and commit succeeded, but someone else's commit failed final String baseError = new StringBuilder ( ) . append ( \"Login post-processing failed after abort for '\" ) . append ( username ) . append ( \"@\" ) . append ( domain ) . toString ( ) ; AuditHelper . auditEvent ( audit , domain , username , Events . AUTHN_ABORT_CHAIN , baseError + \"', but cannot audit login attempt\" ) ; MessageHelper . postMessage ( messageQ , domain , username , Events . AUTHN_ABORT_CHAIN , baseError + \"', but cannot post MQ login attempt event\" ) ; // cache the username and domain, for they will be purged by \"logout()\" final String tempUsername = username ; final String tempDomain = domain ; logout ( ) ; // string concatenation is only executed if log level is actually enabled if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"Authentication aborted for '\" + tempUsername + \"@\" + tempDomain + \"'\" ) ; } return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override // Check is broken [LOG.info()]: PMD reports issues although log stmt is guarded. @todo revisit when upgrading PMD. @ SuppressWarnings ( \"PMD.GuardLogStatementJavaUtil\" ) public final boolean logout ( ) throws LoginException { final StringBuilder principals = new StringBuilder ( \":\" ) ; // remove all the principals that we added in the commit() method from the 'subject' object // (that's why we stored our principals in the 'committedSubject' object...) if ( committedSubject != null && committedSubject . getPrincipals ( ) != null ) { final StringBuilder stringBuilder = new StringBuilder ( ) ; for ( final Principal p : committedSubject . getPrincipals ( ) ) { pSubject . getPrincipals ( ) . remove ( p ) ; // string concatenation is only executed if log level is actually enabled if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( \"Logging out subject: '\" + p . getName ( ) + \"'\" ) ; } principals . append ( p . getName ( ) ) . append ( ' ' ) ; stringBuilder . delete ( 0 , stringBuilder . length ( ) ) ; final String baseError = stringBuilder . append ( \"Logout successful for '\" ) . append ( username ) . append ( \"@\" ) . append ( domain ) . toString ( ) ; AuditHelper . auditEvent ( audit , domain , username , Events . AUTHN_LOGOUT , baseError + \"', but cannot audit logout attempt\" ) ; MessageHelper . postMessage ( messageQ , domain , username , Events . AUTHN_LOGOUT , baseError + \"', but cannot post MQ logout attempt event\" ) ; } } cleanState ( ) ; // string concatenation is only executed if log level is actually enabled if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"Principals logged out: '\" + principals + \"'\" ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean up any state associated with the current login attempt . [CODESPLIT] @ SuppressWarnings ( \"PMD.NullAssignment\" ) private void cleanState ( ) { // null-assignments for de-referencing objects are okay domain = null ; username = null ; Cleanser . wipe ( password ) ; pendingSubject = null ; committedSubject = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the instance - global audit object [CODESPLIT] @ SuppressWarnings ( \"PMD.ConfusingTernary\" ) private void initAudit ( final CommonProperties commonProps ) { try { final String auditClassName = commonProps . getAuditClassName ( ) ; // this would be harder to read when following PMD's advice - ignoring the PMD warning if ( ! commonProps . isAuditEnabled ( ) ) { final String error = \"Auditing has been disabled in the JAAS configuration\" ; LOG . info ( error ) ; } else if ( auditClassName == null ) { final String error = \"Auditing has been enabled in the JAAS configuration, but no audit class has been configured\" ; LOG . error ( error ) ; throw new IllegalStateException ( error ) ; } else { if ( commonProps . isAuditSingleton ( ) ) { LOG . debug ( \"Requesting singleton audit class instance of '\" + auditClassName + \"' from the audit factory\" ) ; this . audit = AuditFactory . getSingleton ( auditClassName , commonProps ) ; } else { LOG . debug ( \"Requesting non-singleton audit class instance of '\" + auditClassName + \"' from the audit factory\" ) ; this . audit = AuditFactory . getInstance ( auditClassName , commonProps ) ; } } } catch ( FactoryException e ) { final String error = \"The audit class cannot be instantiated. This is most likely a configuration\" + \" problem. Is the configured class available in the classpath?\" ; LOG . error ( error , e ) ; throw new IllegalStateException ( error , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the instance - global message queue object [CODESPLIT] @ SuppressWarnings ( \"PMD.ConfusingTernary\" ) private void initMessageQueue ( final CommonProperties commonProps ) { try { final String messageClassName = commonProps . getMessageQueueClassName ( ) ; // this would be harder to read when following PMD's advice - ignoring the PMD warning if ( ! commonProps . isMessageQueueEnabled ( ) ) { final String error = \"Message queue has been disabled in the JAAS configuration\" ; LOG . info ( error ) ; } else if ( messageClassName == null ) { final String error = \"Message queue has been enabled in the JAAS configuration, \" + \"but no message queue class has been configured\" ; LOG . error ( error ) ; throw new IllegalStateException ( error ) ; } else { if ( commonProps . isMessageQueueSingleton ( ) ) { LOG . debug ( \"Requesting singleton message class instance of '\" + messageClassName + \"' from the message factory\" ) ; this . messageQ = MessageQFactory . getSingleton ( messageClassName , commonProps ) ; } else { LOG . debug ( \"Requesting non-singleton message class instance of '\" + messageClassName + \"' from the message factory\" ) ; this . messageQ = MessageQFactory . getInstance ( messageClassName , commonProps ) ; } } } catch ( FactoryException e ) { final String error = \"The message class cannot be instantiated. This is most likely a configuration\" + \" problem. Is the configured class available in the classpath?\" ; LOG . error ( error , e ) ; throw new IllegalStateException ( error , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the instance - global password validator object [CODESPLIT] private void initPwValidator ( final CommonProperties commonProps ) { try { final String validatorClass = commonProps . getPasswordValidatorClassName ( ) ; if ( validatorClass == null ) { final String error = \"No password validator class has been configured in the JAAS configuration\" ; LOG . error ( error ) ; throw new IllegalStateException ( error ) ; } else { if ( commonProps . isPasswordValidatorSingleton ( ) ) { // Fortify will report a violation here because of disclosure of potentially confidential // information. However, the class name is not confidential, which makes this a non-issue / false // positive. LOG . debug ( \"Requesting singleton validator class instance of '\" + validatorClass + \"' from the validator factory\" ) ; this . pwValidator = PasswordValidatorFactory . getSingleton ( validatorClass , commonProps ) ; } else { // Fortify will report a violation here because of disclosure of potentially confidential // information. However, the class name is not confidential, which makes this a non-issue / false // positive. LOG . debug ( \"Requesting non-singleton validator class instance of '\" + validatorClass + \"' from the validator factory\" ) ; this . pwValidator = PasswordValidatorFactory . getInstance ( validatorClass , commonProps ) ; } } } catch ( FactoryException e ) { final String error = \"The validator class cannot be instantiated. This is most likely a configuration\" + \" problem. Is the configured class available in the classpath?\" ; LOG . error ( error , e ) ; throw new IllegalStateException ( error , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the instance - global password authenticator object [CODESPLIT] private void initPwAuthenticator ( final CommonProperties commonProps ) { try { final String authNticatorClass = commonProps . getPasswordAuthenticatorClassName ( ) ; if ( authNticatorClass == null ) { final String error = \"No password authenticator class has been configured in the JAAS configuration\" ; LOG . error ( error ) ; throw new IllegalStateException ( error ) ; } else { if ( commonProps . isPasswordAuthenticatorSingleton ( ) ) { // Fortify will report a violation here because of disclosure of potentially confidential // information. However, the class name is not confidential, which makes this a non-issue / false // positive. LOG . debug ( \"Requesting singleton authenticator class instance of '\" + authNticatorClass + \"' from the authenticator factory\" ) ; this . pwAuthenticator = PasswordAuthenticatorFactory . getSingleton ( authNticatorClass , commonProps ) ; } else { // Fortify will report a violation here because of disclosure of potentially confidential // information. However, the class name is not confidential, which makes this a non-issue / false // positive. LOG . debug ( \"Requesting non-singleton authenticator class instance of '\" + authNticatorClass + \"' from the authenticator factory\" ) ; this . pwAuthenticator = PasswordAuthenticatorFactory . getInstance ( authNticatorClass , commonProps ) ; } } } catch ( FactoryException e ) { final String error = \"The validator class cannot be instantiated. This is most likely a configuration\" + \" problem. Is the configured class available in the classpath?\" ; LOG . error ( error , e ) ; throw new IllegalStateException ( error , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Synchronize entity ( that just read ) with entity in database . It just check if it s new . < / p > [CODESPLIT] @ Override public final boolean sync ( final Map < String , Object > pAddParam , final Object pEntity ) throws Exception { Object entityPbDb = getSrvOrm ( ) . retrieveEntity ( pAddParam , pEntity ) ; return entityPbDb == null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the parameter using the appropriate setter method ( if present ) . [CODESPLIT] @ Override public boolean setParam ( String name , Object value ) { String sname = \"set\" + name . substring ( 0 , 1 ) . toUpperCase ( ) + name . substring ( 1 ) ; Method m ; try { if ( value instanceof Integer ) { m = getClass ( ) . getMethod ( sname , int . class ) ; m . invoke ( this , value ) ; } else if ( value instanceof Double ) { try { m = getClass ( ) . getMethod ( sname , float . class ) ; m . invoke ( this , ( ( Double ) value ) . floatValue ( ) ) ; } catch ( NoSuchMethodException e ) { //no float version found, try the int version m = getClass ( ) . getMethod ( sname , int . class ) ; m . invoke ( this , ( ( Double ) value ) . intValue ( ) ) ; } } else if ( value instanceof Float ) { try { m = getClass ( ) . getMethod ( sname , float . class ) ; m . invoke ( this , value ) ; } catch ( NoSuchMethodException e ) { //no float version found, try the int version m = getClass ( ) . getMethod ( sname , int . class ) ; m . invoke ( this , ( ( Double ) value ) . intValue ( ) ) ; } } else if ( value instanceof Boolean ) { m = getClass ( ) . getMethod ( sname , boolean . class ) ; m . invoke ( this , value ) ; } else { m = getClass ( ) . getMethod ( sname , String . class ) ; m . invoke ( this , value . toString ( ) ) ; } return true ; } catch ( NoSuchMethodException e ) { log . warn ( \"Setting unknown parameter: \" + e . getMessage ( ) ) ; return false ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; return false ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; return false ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtains the parameter using the appropriate getter method ( if present ) . [CODESPLIT] @ Override public Object getParam ( String name ) { String sname = \"get\" + name . substring ( 0 , 1 ) . toUpperCase ( ) + name . substring ( 1 ) ; try { Method m = getClass ( ) . getMethod ( sname ) ; return m . invoke ( this ) ; } catch ( NoSuchMethodException e ) { return null ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; return null ; } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; return null ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; return null ; } catch ( InvocationTargetException e ) { e . printStackTrace ( ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; JPanel panelMain = this . makeNewPanel ( panel , BorderLayout . CENTER ) ; panelMain . setLayout ( new GridLayout ( 3 , 2 ) ) ; panelMain . add ( new JLabel ( \"Last backup: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfDate = new JTextField ( ) ) ; panelMain . add ( new JLabel ( \"Filter: \" , JLabel . RIGHT ) ) ; panelMain . add ( m_tfFilter = new JTextField ( ) ) ; panelMain . add ( new JPanel ( ) ) ; panelMain . add ( m_cbIncremental = new JCheckBox ( \"Incremental\" ) ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strDate = m_tfDate . getText ( ) ; m_properties . setProperty ( BACKUPDATE_PARAM , strDate ) ; String strFilter = m_tfFilter . getText ( ) ; m_properties . setProperty ( FILTER_PARAM , strFilter ) ; boolean bSelected = m_cbIncremental . isSelected ( ) ; if ( bSelected ) m_properties . setProperty ( BACKUP_INCREMENTAL_PARAM , TRUE ) ; else m_properties . setProperty ( BACKUP_INCREMENTAL_PARAM , FALSE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strDate = m_properties . getProperty ( BACKUPDATE_PARAM ) ; m_tfDate . setText ( strDate ) ; String strFilter = m_properties . getProperty ( FILTER_PARAM ) ; m_tfFilter . setText ( strFilter ) ; boolean bSelected = false ; String strSelected = m_properties . getProperty ( BACKUP_INCREMENTAL_PARAM ) ; if ( TRUE . equalsIgnoreCase ( strSelected ) ) bSelected = true ; m_cbIncremental . setSelected ( bSelected ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Locale from cache . [CODESPLIT] public static Locale getLocale ( final String language , final String country , final String variant ) { LocaleInfo info = lookupLocaleInfo ( resolveLocaleCode ( language , country , variant ) ) ; return info . locale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Locale from cache . [CODESPLIT] public static Locale getLocale ( final String language , final String country ) { return getLocale ( language , country , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns Locale from cache where Locale may be specified also using language code . Converts a locale string like en en_US or en_US_win to <b > new< / b > Java locale object . [CODESPLIT] public static Locale getLocale ( final String languageCode ) { LocaleInfo info = lookupLocaleInfo ( languageCode ) ; return info . locale ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms locale data to locale code . <code > null< / code > values are allowed . [CODESPLIT] public static String resolveLocaleCode ( final String lang , final String country , final String variant ) { StringBuilder code = new StringBuilder ( lang ) ; if ( country != null && country . length ( ) > 0 ) { code . append ( ' ' ) . append ( country ) ; if ( variant != null && variant . length ( ) > 0 ) { code . append ( ' ' ) . append ( variant ) ; } } return code . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resolves locale code from locale . [CODESPLIT] public static String resolveLocaleCode ( final Locale locale ) { return resolveLocaleCode ( locale . getLanguage ( ) , locale . getCountry ( ) , locale . getVariant ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes locale code in string array that can be used for <code > Locale< / code > constructor . [CODESPLIT] public static String [ ] decodeLocaleCode ( final String localeCode ) { String [ ] data = StringUtils . split ( localeCode , ' ' ) ; String [ ] result = new String [ ] { data [ 0 ] , \"\" , \"\" } ; if ( data . length >= 2 ) { result [ 1 ] = data [ 1 ] ; if ( data . length >= 3 ) { result [ 2 ] = data [ 2 ] ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns cached <code > DateFormatSymbols< / code > instance for specified locale . [CODESPLIT] public static DateFormatSymbols getDateFormatSymbols ( Locale locale ) { LocaleInfo info = lookupLocaleInfo ( locale ) ; DateFormatSymbols dfs = info . dateFormatSymbols ; if ( dfs == null ) { dfs = new DateFormatSymbols ( locale ) ; info . dateFormatSymbols = dfs ; } return dfs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns cached <code > NumberFormat< / code > instance for specified locale . [CODESPLIT] public static NumberFormat getNumberFormat ( Locale locale ) { LocaleInfo info = lookupLocaleInfo ( locale ) ; NumberFormat nf = info . numberFormat ; if ( nf == null ) { nf = NumberFormat . getInstance ( locale ) ; info . numberFormat = nf ; } return nf ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lookups for locale info and creates new if it doesn t exist . [CODESPLIT] protected static LocaleInfo lookupLocaleInfo ( final String code ) { LocaleInfo info = locales . get ( code ) ; if ( info == null ) { String [ ] data = decodeLocaleCode ( code ) ; info = new LocaleInfo ( new Locale ( data [ 0 ] , data [ 1 ] , data [ 2 ] ) ) ; locales . put ( code , info ) ; } return info ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a logging version of a Statement [CODESPLIT] public static Statement getInstance ( Statement stmt ) { InvocationHandler handler = new JdbcLogStatement ( stmt ) ; ClassLoader cl = Statement . class . getClassLoader ( ) ; return ( Statement ) Proxy . newProxyInstance ( cl , new Class [ ] { Statement . class } , handler ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all of the elements from this stack . [CODESPLIT] public void clear ( ) { int i = size ; Object [ ] els = elements ; while ( i -- > 0 ) { els [ i ] = null ; } this . size = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pushes an item onto the top of this stack . [CODESPLIT] public T push ( T element ) { int i ; Object [ ] els ; if ( ( i = size ++ ) >= ( els = elements ) . length ) { System . arraycopy ( els , 0 , els = elements = new Object [ i << 1 ] , 0 , i ) ; } els [ i ] = element ; return element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the object at the top of this stack and returns that object as the value of this function . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public T pop ( ) throws EmptyStackException { int i ; if ( ( i = -- size ) >= 0 ) { T element = ( T ) elements [ i ] ; elements [ i ] = null ; return element ; } else { size = 0 ; throw new EmptyStackException ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If there is no input stream use the file to create one . [CODESPLIT] public InputStream makeInStream ( ) { if ( m_InputStream != null ) return m_InputStream ; try { return new FileInputStream ( m_inputFile ) ; } catch ( FileNotFoundException ex ) { System . out . println ( \"Warning: scanned file does not exist: \" + m_inputFile . getPath ( ) ) ; // Skip this file } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a cached thread - local { [CODESPLIT] public static CharsetEncoder getEncoder ( Charset charset ) { if ( charset == null ) { throw new NullPointerException ( \"charset\" ) ; } Map < Charset , CharsetEncoder > map = encoders . get ( ) ; CharsetEncoder e = map . get ( charset ) ; if ( e != null ) { e . reset ( ) ; e . onMalformedInput ( CodingErrorAction . REPLACE ) ; e . onUnmappableCharacter ( CodingErrorAction . REPLACE ) ; return e ; } e = charset . newEncoder ( ) ; e . onMalformedInput ( CodingErrorAction . REPLACE ) ; e . onUnmappableCharacter ( CodingErrorAction . REPLACE ) ; map . put ( charset , e ) ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Open and read the properties file . [CODESPLIT] public static Properties readProperties ( String strFileName ) { Properties properties = new Properties ( ) ; File fileProperties = new File ( strFileName ) ; try { if ( ! fileProperties . exists ( ) ) fileProperties . createNewFile ( ) ; InputStream inStream = new FileInputStream ( fileProperties ) ; properties . load ( inStream ) ; inStream . close ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Write out the properties . [CODESPLIT] public static void writeProperties ( String strFileName , Properties properties ) { try { OutputStream out = new FileOutputStream ( strFileName ) ; properties . store ( out , \"JBackup preferences\" ) ; out . flush ( ) ; out . close ( ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse this URL formatted string into properties . [CODESPLIT] public static Properties parseArgs ( Properties properties , String [ ] args ) { if ( properties == null ) properties = new Properties ( ) ; if ( args == null ) return properties ; for ( int i = 0 ; i < args . length ; i ++ ) AppUtilities . addParam ( properties , args [ i ]  , false ) ; return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the param line and add it to this properties object . ( ie . key = value ) . [CODESPLIT] public static void addParam ( Properties properties , String strParams , boolean bDecodeString ) { int iIndex = strParams . indexOf ( ' ' ) ; int iEndIndex = strParams . length ( ) ; if ( iIndex != - 1 ) { String strParam = strParams . substring ( 0 , iIndex ) ; String strValue = strParams . substring ( iIndex + 1 , iEndIndex ) ; if ( bDecodeString ) { try { strParam = URLDecoder . decode ( strParam , URL_ENCODING ) ; strValue = URLDecoder . decode ( strValue , URL_ENCODING ) ; } catch ( java . io . UnsupportedEncodingException ex ) { ex . printStackTrace ( ) ; } } properties . put ( strParam , strValue ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "按照长度分组 [CODESPLIT] public void register ( ActionInfo action , String url ) { if ( url . indexOf ( ' ' ) == - 1 ) { staticUrls . put ( url , new RouteInfo ( action ) ) ; } else { String [ ] urlSegments = StringUtils . split ( url . substring ( 1 ) , ' ' ) ; if ( urlSegments . length >= MAX_PATH_PARTS ) { throw new IllegalStateException ( \"exceed max url parts: \" + url ) ; } OneByOneMatcher matcher = matchers [ urlSegments . length ] ; if ( matcher == null ) { matcher = new OneByOneMatcher ( ) ; matchers [ urlSegments . length ] = matcher ; } matcher . register ( action , urlSegments ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------- [CODESPLIT] public < T > T getValue ( String name , Class < T > type ) { return getValue ( name , type , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Constructor . [CODESPLIT] public void init ( PropertyOwner propOwner , Properties properties ) { m_propOwner = propOwner ; m_properties = properties ; this . setLayout ( new BorderLayout ( ) ) ; // Default this . addControlsToView ( this ) ; // Add the controls to this view this . propertiesToControls ( ) ; this . addListeners ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Create a combobox with all the values in this string array . [CODESPLIT] public JComponent makeControlPopup ( String [ ] rgstrValue , String strControl ) { JComboBox comboBox = new JComboBox ( ) ; comboBox . setEditable ( true ) ; this . addItems ( comboBox , rgstrValue , strControl ) ; return comboBox ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add all the items in this array to the combobox and set the default . [CODESPLIT] public void addItems ( JComboBox comboBox , String [ ] rgstrValue , String strDefault ) { for ( int i = 0 ; i < rgstrValue . length ; i ++ ) { comboBox . addItem ( rgstrValue [ i ] ) ; if ( rgstrValue [ i ] . equalsIgnoreCase ( strDefault ) ) strDefault = rgstrValue [ i ] ; } comboBox . setSelectedItem ( strDefault ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Utility to create a new panel and add it to this parent panel . [CODESPLIT] public JPanel makeNewPanel ( JPanel panel , Object constraints ) { JPanel panelNew = new JPanel ( ) ; panelNew . setLayout ( new BorderLayout ( ) ) ; panel . add ( panelNew , constraints ) ; return panelNew ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取相对 ContextPath 的 requestURI [CODESPLIT] public static String getPathInfo ( HttpServletRequest request ) { String path = request . getPathInfo ( ) ; if ( path == null ) { path = request . getServletPath ( ) ; } else { path = request . getServletPath ( ) + path ; } if ( path == null || path . length ( ) == 0 ) { path = \"/\" ; } return path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "客户端对Http Basic验证的 Header进行编码 . [CODESPLIT] public static String encodeHttpBasic ( String userName , String password ) { String encode = userName + \":\" + password ; return \"Basic \" + Base64 . encodeToString ( encode . getBytes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "是否是Flash请求数据 [CODESPLIT] public static boolean isFlashRequest ( HttpServletRequest request ) { return \"Shockwave Flash\" . equals ( request . getHeader ( \"User-Agent\" ) ) || StringUtils . isNotEmpty ( request . getHeader ( \"x-flash-version\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "判断是否为搜索引擎 [CODESPLIT] public static boolean isRobot ( HttpServletRequest request ) { String ua = request . getHeader ( \"user-agent\" ) ; if ( StringUtils . isBlank ( ua ) ) return false ; //@formatter:off return ( ua != null && ( ua . contains ( \"Baiduspider\" ) || ua . contains ( \"Googlebot\" ) || ua . contains ( \"sogou\" ) || ua . contains ( \"sina\" ) || ua . contains ( \"iaskspider\" ) || ua . contains ( \"ia_archiver\" ) || ua . contains ( \"Sosospider\" ) || ua . contains ( \"YoudaoBot\" ) || ua . contains ( \"yahoo\" ) || ua . contains ( \"yodao\" ) || ua . contains ( \"MSNBot\" ) || ua . contains ( \"spider\" ) || ua . contains ( \"Twiceler\" ) || ua . contains ( \"Sosoimagespider\" ) || ua . contains ( \"naver.com/robots\" ) || ua . contains ( \"Nutch\" ) || ua . contains ( \"spider\" ) ) ) ; //@formatter:on }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Sets a parameter for this request . The parameter is actually separate from the request parameters but calling on the getParameter () methods of this class will work as if they weren t . < / p > [CODESPLIT] public void setParameter ( String name , String value ) { String [ ] values = parameters . get ( name ) ; if ( values == null ) { values = new String [ ] { value } ; parameters . put ( name , values ) ; } else { String [ ] newValues = new String [ values . length + 1 ] ; System . arraycopy ( values , 0 , newValues , 0 , values . length ) ; newValues [ values . length ] = value ; parameters . put ( name , newValues ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Returns the values of a parameter in this request . It first looks in the underlying HttpServletRequest object for the parameter and if that doesn t exist it looks for the parameter retrieved from the multipart request . < / p > [CODESPLIT] @ Override public String [ ] getParameterValues ( String name ) { String [ ] values = getRequest ( ) . getParameterValues ( name ) ; if ( values == null ) { values = parameters . get ( name ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Combines the parameters stored here with those in the underlying request . If paramater values in the underlying request take precedence over those stored here . < / p > [CODESPLIT] @ Override public Map < String , String [ ] > getParameterMap ( ) { Map < String , String [ ] > map = new HashMap < String , String [ ] > ( parameters ) ; map . putAll ( getRequest ( ) . getParameterMap ( ) ) ; return map ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize a set of database properties based on key / values in a <code > HashMap< / code > . [CODESPLIT] public static DbProperties build ( final Map < String , ? > properties ) { Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; final DbProperties dbProps = new DbProperties ( ) ; String tmp = getOption ( KEY_JNDI_CONNECTION_NAME , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { // JNDI connection name can be null or empty dbProps . setJndiConnectionName ( tmp ) ; logValue ( KEY_JNDI_CONNECTION_NAME , tmp ) ; } else { dbProps . setJndiConnectionName ( DEFAULT_JNDI_NAME ) ; logDefault ( KEY_JNDI_CONNECTION_NAME , DEFAULT_JNDI_NAME ) ; } tmp = getOption ( KEY_SQL_USER_QUERY , properties ) ; if ( StringUtils . isNotEmpty ( tmp ) ) { // sql query cannot be null or empty, defaulting to null to catch it dbProps . setSqlUserQuery ( tmp ) ; logValue ( KEY_SQL_USER_QUERY , tmp ) ; } else { dbProps . setSqlUserQuery ( DEFAULT_SQL_USER_QUERY ) ; logDefault ( KEY_SQL_USER_QUERY , DEFAULT_SQL_USER_QUERY ) ; } // set the additional properties, preserving the originally provided properties // create a defensive copy of the map and all its properties // the code looks a little more complicated than a simple \"putAll()\", but it catches situations // where a Map is provided that supports null values (e.g. a HashMap) vs Map implementations // that do not (e.g. ConcurrentHashMap). final Map < String , String > tempMap = new ConcurrentHashMap <> ( ) ; try { for ( final Map . Entry < String , ? > entry : properties . entrySet ( ) ) { final String key = entry . getKey ( ) ; final String value = ( String ) entry . getValue ( ) ; if ( value != null ) { tempMap . put ( key , value ) ; } } } catch ( ClassCastException e ) { final String error = \"The values of the configured JAAS properties must be Strings. \" + \"Sorry, but we do not support anything else here!\" ; throw new IllegalArgumentException ( error , e ) ; } dbProps . setAdditionalProperties ( tempMap ) ; return dbProps ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches path against pattern using * ? and ** wildcards . Both path and the pattern are tokenized on path separators ( both \\ and / ) . ** represents deep tree wildcard as in Ant . [CODESPLIT] public static boolean matchPath ( String path , String pattern ) { String [ ] pathElements = StringUtils . splitChars ( path , PATH_SEPARATORS ) ; String [ ] patternElements = StringUtils . splitChars ( pattern , PATH_SEPARATORS ) ; return matchTokens ( pathElements , patternElements ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Matches path to at least one pattern . Returns index of matched pattern or <code > - 1< / code > otherwise . [CODESPLIT] public static int matchPathOne ( String path , String [ ] patterns ) { for ( int i = 0 ; i < patterns . length ; i ++ ) { if ( matchPath ( path , patterns [ i ] ) == true ) { return i ; } } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Match tokenized string and pattern . [CODESPLIT] protected static boolean matchTokens ( String [ ] tokens , String [ ] patterns ) { int patNdxStart = 0 ; int patNdxEnd = patterns . length - 1 ; int tokNdxStart = 0 ; int tokNdxEnd = tokens . length - 1 ; while ( patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd ) { // find first ** String patDir = patterns [ patNdxStart ] ; if ( patDir . equals ( PATH_MATCH ) ) { break ; } if ( ! WildcharUtils . match ( tokens [ tokNdxStart ] , patDir ) ) { return false ; } patNdxStart ++ ; tokNdxStart ++ ; } if ( tokNdxStart > tokNdxEnd ) { for ( int i = patNdxStart ; i <= patNdxEnd ; i ++ ) { // string is finished if ( ! patterns [ i ] . equals ( PATH_MATCH ) ) { return false ; } } return true ; } if ( patNdxStart > patNdxEnd ) { return false ; // string is not finished, but pattern is } while ( patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd ) { // to the last ** String patDir = patterns [ patNdxEnd ] ; if ( patDir . equals ( PATH_MATCH ) ) { break ; } if ( ! WildcharUtils . match ( tokens [ tokNdxEnd ] , patDir ) ) { return false ; } patNdxEnd -- ; tokNdxEnd -- ; } if ( tokNdxStart > tokNdxEnd ) { for ( int i = patNdxStart ; i <= patNdxEnd ; i ++ ) { // string is finished if ( ! patterns [ i ] . equals ( PATH_MATCH ) ) { return false ; } } return true ; } while ( ( patNdxStart != patNdxEnd ) && ( tokNdxStart <= tokNdxEnd ) ) { int patIdxTmp = - 1 ; for ( int i = patNdxStart + 1 ; i <= patNdxEnd ; i ++ ) { if ( patterns [ i ] . equals ( PATH_MATCH ) ) { patIdxTmp = i ; break ; } } if ( patIdxTmp == patNdxStart + 1 ) { patNdxStart ++ ; // skip **/** situation continue ; } // find the pattern between padIdxStart & padIdxTmp in str between strIdxStart & strIdxEnd int patLength = ( patIdxTmp - patNdxStart - 1 ) ; int strLength = ( tokNdxEnd - tokNdxStart + 1 ) ; int ndx = - 1 ; strLoop : for ( int i = 0 ; i <= strLength - patLength ; i ++ ) { for ( int j = 0 ; j < patLength ; j ++ ) { String subPat = patterns [ patNdxStart + j + 1 ] ; String subStr = tokens [ tokNdxStart + i + j ] ; if ( ! WildcharUtils . match ( subStr , subPat ) ) { continue strLoop ; } } ndx = tokNdxStart + i ; break ; } if ( ndx == - 1 ) { return false ; } patNdxStart = patIdxTmp ; tokNdxStart = ndx + patLength ; } for ( int i = patNdxStart ; i <= patNdxEnd ; i ++ ) { if ( ! patterns [ i ] . equals ( PATH_MATCH ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the rectangle coordinates by adding the specified X and Y offsets [CODESPLIT] public void move ( int xofs , int yofs ) { x1 += xofs ; y1 += yofs ; x2 += xofs ; y2 += yofs ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if this rectangle entirely contains another rectangle . [CODESPLIT] public boolean encloses ( Rectangular other ) { return x1 <= other . x1 && y1 <= other . y1 && x2 >= other . x2 && y2 >= other . y2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if this rectangle contains a point . [CODESPLIT] public boolean contains ( int x , int y ) { return x1 <= x && y1 <= y && x2 >= x && y2 >= y ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the intersection of this rectangle with another one . [CODESPLIT] public Rectangular intersection ( Rectangular other ) { if ( this . intersects ( other ) ) { return new Rectangular ( Math . max ( x1 , other . x1 ) , Math . max ( y1 , other . y1 ) , Math . min ( x2 , other . x2 ) , Math . min ( y2 , other . y2 ) ) ; } else { return new Rectangular ( ) ; //an empty rectangle } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the union of this rectangle with another one . [CODESPLIT] public Rectangular union ( Rectangular other ) { return new Rectangular ( Math . min ( x1 , other . x1 ) , Math . min ( y1 , other . y1 ) , Math . max ( x2 , other . x2 ) , Math . max ( y2 , other . y2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the X coordinates of the rectangle with the X coordinates of another one . [CODESPLIT] public Rectangular replaceX ( Rectangular other ) { Rectangular ret = new Rectangular ( this ) ; ret . x1 = other . x1 ; ret . x2 = other . x2 ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the Y coordinates of the rectangle with the Y coordinates of another one . [CODESPLIT] public Rectangular replaceY ( Rectangular other ) { Rectangular ret = new Rectangular ( this ) ; ret . y1 = other . y1 ; ret . y2 = other . y2 ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this rectangle intersets with the other one splits this rectangle horizontally so that it does not intersect with the other one anymore . [CODESPLIT] public Rectangular hsplit ( Rectangular other ) { if ( this . intersects ( other ) ) { Rectangular a = new Rectangular ( this ) ; Rectangular b = new Rectangular ( this ) ; if ( a . x2 > other . x1 - 1 ) a . x2 = other . x1 - 1 ; if ( b . x1 < other . x2 + 1 ) b . x1 = other . x2 + 1 ; if ( a . isEmpty ( ) ) { x1 = b . x1 ; return null ; } else { x2 = a . x2 ; if ( b . isEmpty ( ) ) return null ; else return b ; } } else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If this rectangle intersets with the other one splits this rectangle horizontally so that it does not intersect with the other one anymore . [CODESPLIT] public Rectangular vsplit ( Rectangular other ) { if ( this . intersects ( other ) ) { Rectangular a = new Rectangular ( this ) ; Rectangular b = new Rectangular ( this ) ; if ( a . y2 > other . y1 - 1 ) a . y2 = other . y1 - 1 ; if ( b . y1 < other . y2 + 1 ) b . y1 = other . y2 + 1 ; if ( a . isEmpty ( ) ) { y1 = b . y1 ; return null ; } else { y2 = a . y2 ; if ( b . isEmpty ( ) ) return null ; else return b ; } } else return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到文件名 . [CODESPLIT] public static String getFilename ( final String path ) { if ( path == null ) { return null ; } int separatorIndex = getFileSeparatorIndex ( path ) ; return separatorIndex == - 1 ? path . substring ( separatorIndex + 1 ) : path ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "得到文件扩展名 . [CODESPLIT] public static String getFileExtension ( final String path ) { if ( path == null ) { return null ; } int extIndex = path . lastIndexOf ( ' ' ) ; if ( extIndex == - 1 ) { return null ; } int folderIndex = getFileSeparatorIndex ( path ) ; if ( folderIndex > extIndex ) { return null ; } return path . substring ( extIndex + 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void controlsToProperties ( ) { super . controlsToProperties ( ) ; String strPathname = m_tfRootPathname . getText ( ) ; m_properties . setProperty ( SOURCE_ROOT_PATHNAME_PARAM , strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Set the properties to the current control values . [CODESPLIT] public void propertiesToControls ( ) { super . propertiesToControls ( ) ; String strPathname = m_properties . getProperty ( SOURCE_ROOT_PATHNAME_PARAM ) ; m_tfRootPathname . setText ( strPathname ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the offset of the specified column from the grid origin . [CODESPLIT] public int getColOfs ( int col ) throws ArrayIndexOutOfBoundsException { if ( col < width ) { int ofs = 0 ; for ( int i = 0 ; i < col ; i ++ ) ofs += cols [ i ] ; return ofs ; } else if ( col == width ) return abspos . getWidth ( ) ; else throw new ArrayIndexOutOfBoundsException ( col + \">\" + width ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the offset of the specified row from the grid origin . [CODESPLIT] public int getRowOfs ( int row ) throws ArrayIndexOutOfBoundsException { if ( row < height ) { int ofs = 0 ; for ( int i = 0 ; i < row ; i ++ ) ofs += rows [ i ] ; return ofs ; } else if ( row == height ) return abspos . getHeight ( ) ; else throw new ArrayIndexOutOfBoundsException ( row + \">\" + height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the coordinates of the specified grid cell relatively to the area top left corner . [CODESPLIT] public Rectangular getCellBoundsRelative ( int x , int y ) { int x1 = getColOfs ( x ) ; int y1 = getRowOfs ( y ) ; int x2 = ( x == width - 1 ) ? abspos . getWidth ( ) - 1 : x1 + cols [ x ] - 1 ; int y2 = ( y == height - 1 ) ? abspos . getHeight ( ) - 1 : y1 + rows [ y ] - 1 ; return new Rectangular ( x1 , y1 , x2 , y2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the absolute coordinates of the specified area in the grid . [CODESPLIT] public Rectangular getAreaBoundsAbsolute ( int x1 , int y1 , int x2 , int y2 ) { final Rectangular end = getCellBoundsAbsolute ( x2 , y2 ) ; return new Rectangular ( abspos . getX1 ( ) + getColOfs ( x1 ) , abspos . getY1 ( ) + getRowOfs ( y1 ) , end . getX2 ( ) , end . getY2 ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the absolute coordinates of the specified area in the grid . [CODESPLIT] public Rectangular getAreaBoundsAbsolute ( Rectangular area ) { return getAreaBoundsAbsolute ( area . getX1 ( ) , area . getY1 ( ) , area . getX2 ( ) , area . getY2 ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a grid cell that contains the specified point [CODESPLIT] public int findCellX ( int x ) { int ofs = abspos . getX1 ( ) ; for ( int i = 0 ; i < cols . length ; i ++ ) { ofs += cols [ i ] ; if ( x < ofs ) return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a grid cell that contains the specified point [CODESPLIT] public int findCellY ( int y ) { int ofs = 0 ; for ( int i = 0 ; i < rows . length ; i ++ ) { ofs += rows [ i ] ; if ( y < ofs + abspos . getY1 ( ) ) return i ; } return - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Goes through the child areas and creates a list of collumns [CODESPLIT] private void calculateColumns ( ) { //create the sorted list of points GridPoint points [ ] = new GridPoint [ areas . size ( ) * 2 ] ; int pi = 0 ; for ( Area area : areas ) { points [ pi ] = new GridPoint ( area . getX1 ( ) , area , true ) ; points [ pi + 1 ] = new GridPoint ( area . getX2 ( ) + 1 , area , false ) ; pi += 2 ; //X2+1 ensures that the end of one box will be on the same point //as the start of the following box } Arrays . sort ( points ) ; //calculate the number of columns int cnt = 0 ; int last = abspos . getX1 ( ) ; for ( int i = 0 ; i < points . length ; i ++ ) if ( ! theSame ( points [ i ] . value , last ) ) { last = points [ i ] . value ; cnt ++ ; } if ( ! theSame ( last , abspos . getX2 ( ) ) ) cnt ++ ; //last column finishes the whole area width = cnt ; //calculate the column widths and the layout maxindent = 0 ; minindent = - 1 ; cols = new int [ width ] ; cnt = 0 ; last = abspos . getX1 ( ) ; for ( int i = 0 ; i < points . length ; i ++ ) { if ( ! theSame ( points [ i ] . value , last ) ) { cols [ cnt ] = points [ i ] . value - last ; last = points [ i ] . value ; cnt ++ ; } if ( points [ i ] . begin ) { target . getPosition ( points [ i ] . area ) . setX1 ( cnt ) ; maxindent = cnt ; if ( minindent == - 1 ) minindent = maxindent ; //points[i].node.getArea().setX1(parent.getArea().getX1() + getColOfs(cnt)); } else { Rectangular pos = target . getPosition ( points [ i ] . area ) ; pos . setX2 ( cnt - 1 ) ; if ( pos . getX2 ( ) < pos . getX1 ( ) ) pos . setX2 ( pos . getX1 ( ) ) ; //points[i].node.getArea().setX2(parent.getArea().getX1() + getColOfs(pos.getX2()+1)); } } if ( ! theSame ( last , abspos . getX2 ( ) ) ) cols [ cnt ] = abspos . getX2 ( ) - last ; if ( minindent == - 1 ) minindent = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Goes through the child areas and creates a list of rows [CODESPLIT] private void calculateRows ( ) { //create the sorted list of points GridPoint points [ ] = new GridPoint [ areas . size ( ) * 2 ] ; int pi = 0 ; for ( Area area : areas ) { points [ pi ] = new GridPoint ( area . getY1 ( ) , area , true ) ; points [ pi + 1 ] = new GridPoint ( area . getY2 ( ) + 1 , area , false ) ; pi += 2 ; //Y2+1 ensures that the end of one box will be on the same point //as the start of the following box } Arrays . sort ( points ) ; //calculate the number of rows int cnt = 0 ; int last = abspos . getY1 ( ) ; for ( int i = 0 ; i < points . length ; i ++ ) if ( ! theSame ( points [ i ] . value , last ) ) { last = points [ i ] . value ; cnt ++ ; } if ( ! theSame ( last , abspos . getY2 ( ) ) ) cnt ++ ; //last row finishes the whole area height = cnt ; //calculate the row heights and the layout rows = new int [ height ] ; cnt = 0 ; last = abspos . getY1 ( ) ; for ( int i = 0 ; i < points . length ; i ++ ) { if ( ! theSame ( points [ i ] . value , last ) ) { rows [ cnt ] = points [ i ] . value - last ; last = points [ i ] . value ; cnt ++ ; } if ( points [ i ] . begin ) { target . getPosition ( points [ i ] . area ) . setY1 ( cnt ) ; //points[i].node.getArea().setY1(parent.getArea().getY1() + getRowOfs(cnt)); } else { Rectangular pos = target . getPosition ( points [ i ] . area ) ; pos . setY2 ( cnt - 1 ) ; if ( pos . getY2 ( ) < pos . getY1 ( ) ) pos . setY2 ( pos . getY1 ( ) ) ; //points[i].node.getArea().setY2(parent.getArea().getY1() + getRowOfs(pos.getY2()+1)); } } if ( ! theSame ( last , abspos . getY2 ( ) ) ) rows [ cnt ] = abspos . getY2 ( ) - last ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a string potentially containing one or more copies of the replacement pattern $ { name } where name may be any value identifier ( e . g . home_dir1 ) replace each occurrence with the value of the parameter with the enclosed name . [CODESPLIT] public String replaceObjectNameParameters ( String pattern , MBeanLocationParameterSource parameterSource ) { Matcher matcher = replaceParamPattern . matcher ( pattern ) ; StringBuffer result = new StringBuffer ( ) ; while ( matcher . find ( ) ) { String name = matcher . group ( \"paramName\" ) ; String value = parameterSource . getParameter ( name ) ; if ( value != null ) { matcher . appendReplacement ( result , value ) ; } else { matcher . appendReplacement ( result , Matcher . quoteReplacement ( matcher . group ( ) ) ) ; } } matcher . appendTail ( result ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a new fully initialized instance of a { @link MessageQ } class to use for JAAS event messageing . <p > Classes implementing the { @link MessageQ } interface <b > must< / b > be thread safe . [CODESPLIT] public static MessageQ getInstance ( final String className , final CommonProperties properties ) throws FactoryException { Validate . notBlank ( className , \"The validated character sequence 'className' is null or empty\" ) ; Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; final Class < ? extends MessageQ > messageClazz ; try { messageClazz = Class . forName ( className ) . asSubclass ( MessageQ . class ) ; } catch ( ClassNotFoundException e ) { final String error = \"Class not found: \" + className ; LOG . warn ( error ) ; throw new FactoryException ( error , e ) ; } catch ( ClassCastException e ) { final String error = \"The provided registry factory class name ('\" + className + \"') is not a subclass of '\" + MessageQ . class . getCanonicalName ( ) + \"'\" ; LOG . warn ( error ) ; throw new FactoryException ( error , e ) ; } final MessageQ messageQ ; try { final Constructor < ? extends MessageQ > constructor = messageClazz . getDeclaredConstructor ( ) ; if ( ! constructor . isAccessible ( ) ) { final String error = \"Constructor of class '\" + messageClazz . getCanonicalName ( ) + \"' is not accessible, changing the accessible flag to instantiate the class\" ; LOG . info ( error ) ; constructor . setAccessible ( true ) ; } messageQ = constructor . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | IllegalArgumentException e ) { final String error = \"Cannot instantiate class '\" + messageClazz . getCanonicalName ( ) + \"'\" ; LOG . warn ( error , e ) ; throw new FactoryException ( error , e ) ; } messageQ . init ( properties ) ; return messageQ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a singleton fully initialized instance of a { @link MessageQ } class to use for JAAS event messageing . <p > Retrieving a singleton by this method will cause the factory to keep state and store a reference to the singleton for later use . You may reset the factory state using the { @code reset () } method to retrieve a new / different singleton the next time this method is called .. <p > Note that any properties of the singleton ( e . g . configuration ) cannot necessarily be changed easily . You may call the singleton s { @code init () } method but depending on the implementation provided by the respective class this may or may not have the expected effect . <p > If you need tight control over the singleton including its lifecycle and configuration or you require more than one singleton that are different in their internal state ( e . g . with different configurations ) then you should create such objects with the { @code getInstance () } method and maintain their state as singletons in your application s business logic . <p > Classes implementing the { @link MessageQ } interface <b > must< / b > be thread safe . [CODESPLIT] @ SuppressWarnings ( \"PMD.NonThreadSafeSingleton\" ) public static MessageQ getSingleton ( final String className , final CommonProperties properties ) throws FactoryException { Validate . notBlank ( className , \"The validated character sequence 'className' is null or empty\" ) ; Validate . notNull ( properties , \"The validated object 'properties' is null\" ) ; // The double-check idiom is safe and acceptable here (Bloch, 2nd ed. p 284) if ( messageQInstance == null ) { synchronized ( MessageQFactory . class ) { if ( messageQInstance == null ) { messageQInstance = getInstance ( className , properties ) ; } } } return messageQInstance ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Synchronize APersistableBaseVersion ( itsVersion changed time ) . < / p > [CODESPLIT] @ Override public final boolean sync ( final Map < String , Object > pAddParam , final Object pEntity ) throws Exception { APersistableBaseVersion entityPb = ( APersistableBaseVersion ) pEntity ; int currDbId = getSrvOrm ( ) . getIdDatabase ( ) ; if ( currDbId == entityPb . getIdDatabaseBirth ( ) ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , \"Foreign entity born in this database! {ID, ID BIRTH, DB BIRTH}:\" + \" {\" + entityPb . getItsId ( ) + \", \" + entityPb . getIdBirth ( ) + \",\" + entityPb . getIdDatabaseBirth ( ) ) ; } String tblNm = pEntity . getClass ( ) . getSimpleName ( ) . toUpperCase ( ) ; String whereStr = \" where \" + tblNm + \".IDBIRTH=\" + entityPb . getItsId ( ) + \" and \" + tblNm + \".IDDATABASEBIRTH=\" + entityPb . getIdDatabaseBirth ( ) ; APersistableBaseVersion entityPbDb = getSrvOrm ( ) . retrieveEntityWithConditions ( pAddParam , entityPb . getClass ( ) , whereStr ) ; entityPb . setIdBirth ( entityPb . getItsId ( ) ) ; entityPb . setItsId ( null ) ; boolean isNew = true ; if ( entityPbDb != null ) { entityPb . setItsVersion ( entityPbDb . getItsVersion ( ) ) ; entityPb . setItsId ( entityPbDb . getItsId ( ) ) ; isNew = false ; } return isNew ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Add your property controls to this panel . Remember to set your own layout manager . Also remember to create a new JPanel and pass it to the super class so controls of the superclass can be included . You have a 3 x 3 grid so add three columns for each control [CODESPLIT] public void addControlsToView ( JPanel panel ) { panel . setLayout ( new BorderLayout ( ) ) ; this . makeNewPanel ( panel , BorderLayout . CENTER ) ; JPanel panelSub = this . makeNewPanel ( panel , BorderLayout . SOUTH ) ; super . addControlsToView ( panelSub ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Examines a Throwable object and gets it s root cause [CODESPLIT] protected Throwable unwrapThrowable ( Throwable t ) { Throwable e = t ; while ( true ) { if ( e instanceof InvocationTargetException ) { e = ( ( InvocationTargetException ) t ) . getTargetException ( ) ; } else if ( t instanceof UndeclaredThrowableException ) { e = ( ( UndeclaredThrowableException ) t ) . getUndeclaredThrowable ( ) ; } else { return e ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends single <code > byte< / code > to buffer . [CODESPLIT] public FastByteBuffer append ( byte element ) { if ( ( currentBuffer == null ) || ( offset == currentBuffer . length ) ) { needNewBuffer ( size + 1 ) ; } currentBuffer [ offset ] = element ; offset ++ ; size ++ ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends another fast buffer to this one . [CODESPLIT] public FastByteBuffer append ( FastByteBuffer buff ) { if ( buff . size == 0 ) { return this ; } for ( int i = 0 ; i < buff . currentBufferIndex ; i ++ ) { append ( buff . buffers [ i ] ) ; } append ( buff . currentBuffer , 0 , buff . offset ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Final wrapup - pad to 64 - byte boundary with the bit pattern 1 0 * ( 64 - bit count of bits processed MSB - first ) [CODESPLIT] public void md5final ( byte [ ] digest ) { /* \"final\" is a poor method name in Java. :v) */ int count ; int p ; // in original code, this is a pointer; in this java code // it's an index into the array this->in. /* Compute number of bytes mod 64 */ count = ( int ) ( ( bits >>> 3 ) & 0x3F ) ; /* Set the first char of padding to 0x80.  This is safe since there is\n\t       always at least one byte free */ p = count ; in [ p ++ ] = ( byte ) 0x80 ; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count ; /* Pad out to 56 mod 64 */ if ( count < 8 ) { /* Two lots of padding:  Pad the first block to 64 bytes */ zeroByteArray ( in , p , count ) ; transform ( ) ; /* Now fill the next block with 56 bytes */ zeroByteArray ( in , 0 , 56 ) ; } else { /* Pad block to 56 bytes */ zeroByteArray ( in , p , count - 8 ) ; } /* Append length in bits and transform */ // Could use a PUT_64BIT... func here. This is a fairly // direct translation from the C code, where bits was an array // of two 32-bit ints. int lowbits = ( int ) bits ; int highbits = ( int ) ( bits >>> 32 ) ; PUT_32BIT_LSB_FIRST ( in , 56 , lowbits ) ; PUT_32BIT_LSB_FIRST ( in , 60 , highbits ) ; transform ( ) ; PUT_32BIT_LSB_FIRST ( digest , 0 , buf [ 0 ] ) ; PUT_32BIT_LSB_FIRST ( digest , 4 , buf [ 1 ] ) ; PUT_32BIT_LSB_FIRST ( digest , 8 , buf [ 2 ] ) ; PUT_32BIT_LSB_FIRST ( digest , 12 , buf [ 3 ] ) ; /* zero sensitive data */ /* notice this misses any sneaking out on the stack. The C\n\t\t * version uses registers in some spots, perhaps because\n\t\t * they care about this.\n\t\t */ zeroByteArray ( in ) ; zeroIntArray ( buf ) ; bits = 0 ; zeroIntArray ( inint ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * private void debugStatus ( String m ) { System . out . println ( m + : ) ; System . out . println ( in : + dumpBytes ( in )) ; System . out . println ( bits : + bits ) ; System . out . println ( buf : + Integer . toHexString ( buf [ 0 ] ) + + Integer . toHexString ( buf [ 1 ] ) + + Integer . toHexString ( buf [ 2 ] ) + + Integer . toHexString ( buf [ 3 ] )) ; } [CODESPLIT] public static String dumpBytes ( byte [ ] bytes ) { int i ; StringBuffer sb = new StringBuffer ( ) ; for ( i = 0 ; i < bytes . length ; i ++ ) { if ( i % 32 == 0 && i != 0 ) { sb . append ( \"\\n\" ) ; } String s = Integer . toHexString ( bytes [ i ] ) ; if ( s . length ( ) < 2 ) { s = \"0\" + s ; } if ( s . length ( ) > 2 ) { s = s . substring ( s . length ( ) - 2 ) ; } sb . append ( s ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "multipart / form - data [CODESPLIT] private static MultipartRequest asMultipartRequest ( HttpServletRequest request ) throws Exception { String encoding = request . getCharacterEncoding ( ) ; MultipartRequest req = new MultipartRequest ( request ) ; ServletFileUpload upload = new ServletFileUpload ( ) ; upload . setHeaderEncoding ( encoding ) ; FileItemIterator it = upload . getItemIterator ( request ) ; while ( it . hasNext ( ) ) { FileItemStream item = it . next ( ) ; String fieldName = item . getFieldName ( ) ; InputStream stream = item . openStream ( ) ; try { if ( item . isFormField ( ) ) { req . setParameter ( fieldName , Streams . asString ( stream , encoding ) ) ; } else { String originalFilename = item . getName ( ) ; File diskFile = getTempFile ( originalFilename ) ; OutputStream fos = new FileOutputStream ( diskFile ) ; try { IoUtils . copy ( stream , fos ) ; } finally { IoUtils . closeQuietly ( fos ) ; } FilePart filePart = new FilePart ( fieldName , originalFilename , diskFile ) ; req . addFile ( filePart ) ; } } finally { IoUtils . closeQuietly ( stream ) ; } } return req ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "application / octet - stream [CODESPLIT] private static MultipartRequest asHtml5Request ( HttpServletRequest request ) throws Exception { String originalFilename = request . getHeader ( \"content-disposition\" ) ; if ( originalFilename == null ) { throw new ServletException ( \"The request is not a html5 file upload request.\" ) ; } originalFilename = new String ( originalFilename . getBytes ( \"iso8859-1\" ) , request . getCharacterEncoding ( ) ) ; originalFilename = StringUtils . substringAfter ( originalFilename , \"; filename=\" ) ; originalFilename = StringUtils . remove ( originalFilename , \"\\\"\" ) ; originalFilename = URLDecoder . decode ( originalFilename , \"utf-8\" ) ; File diskFile = getTempFile ( originalFilename ) ; InputStream fis = request . getInputStream ( ) ; OutputStream fos = new FileOutputStream ( diskFile ) ; try { IoUtils . copy ( fis , fos ) ; } finally { IoUtils . closeQuietly ( fis ) ; IoUtils . closeQuietly ( fos ) ; } MultipartRequest req = new MultipartRequest ( request ) ; FilePart filePart = new FilePart ( \"file\" , originalFilename , diskFile ) ; req . addFile ( filePart ) ; return req ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "添加用户自定义的对象 [CODESPLIT] public void addBean ( Object beanObject ) { Validate . notNull ( beanObject ) ; addBean ( beanObject . getClass ( ) . getName ( ) , beanObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "添加用户自定义的对象 [CODESPLIT] public void addBean ( Class < ? > beanClass , Object beanObject ) { Validate . notNull ( beanClass ) ; addBean ( beanClass . getName ( ) , beanObject ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "添加用户自定义的对象 [CODESPLIT] public void addBean ( String name , Object beanObject ) { Validate . notNull ( beanObject ) ; addBean ( name , new ValueObject ( beanObject ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "添加用户自定义的对象 [CODESPLIT] public void addBean ( String name , IocObject object ) { Validate . notNull ( name ) ; Validate . notNull ( object ) ; log . debug ( \"addBean: {}\" , name ) ; if ( pool . put ( name , object ) != null ) { log . warn ( \"Duplicated Bean: {}\" , name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "注册 [CODESPLIT] public void addBean ( Class < ? > beanClass , Configuration properties , boolean singleton ) { Validate . notNull ( beanClass ) ; addBean ( beanClass . getName ( ) , beanClass , properties , singleton ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "注册 [CODESPLIT] public void addBean ( String name , Class < ? > beanClass , Configuration properties , boolean singleton ) { Validate . notNull ( name ) ; Validate . notNull ( beanClass ) ; Validate . isFalse ( beanClass . isInterface ( ) , \"Must not be interface: %s\" , beanClass . getName ( ) ) ; Validate . isFalse ( Modifier . isAbstract ( beanClass . getModifiers ( ) ) , \"Must not be abstract class: %s\" , beanClass . getName ( ) ) ; log . debug ( \"addBean: {}\" , name , beanClass . getName ( ) ) ; IocObject iocObject = doGetIocObject ( beanClass , properties , singleton ) ; if ( pool . put ( name , iocObject ) != null ) { log . warn ( \"Duplicated Bean: {}\" , name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取一个 Bean [CODESPLIT] @ Override @ SuppressWarnings ( \"unchecked\" ) public < T > T getBean ( Class < T > beanClass ) { Validate . notNull ( beanClass ) ; return ( T ) getBean ( beanClass . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "获取一个 Bean [CODESPLIT] @ Override public Object getBean ( String name ) { IocObject iocObject = pool . get ( name ) ; if ( iocObject == null ) { return null ; } return iocObject . getObject ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public < T > T unwrap ( Class < T > type ) { checkArgument ( Element . class . equals ( type ) , \"Cannot unwrap to: %s\" , type ) ; return type . cast ( element ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Launches the debugger as a stand - alone Swing application . [CODESPLIT] public static void main ( String [ ] args ) { try { Main main = new Main ( ) ; main . start ( ) ; Runtime . getRuntime ( ) . addShutdownHook ( main . getShutdownHook ( ) ) ; main . awaitTermination ( 1 , TimeUnit . DAYS ) ; } catch ( InterruptedException e ) { e = null ; Thread . currentThread ( ) . interrupt ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Should be notified every time byte - code is added to the machine . [CODESPLIT] public void onCodeUpdate ( ByteBuffer codeBuffer , int start , int length , VariableAndFunctorInterner interner , WAMCodeView codeView ) { log . fine ( \"public void onCodeUpdate(ByteBuffer codeBuffer, int start = \" + start + \", int length = \" + length + \", VariableAndFunctorInterner interner, WAMCodeView codeView): called\" ) ; // Take a copy of the new bytecode. copyAndResizeCodeBuffer ( codeBuffer , start , length ) ; // Disassemble the new area of byte code. SizeableList < WAMInstruction > instructions = WAMInstruction . disassemble ( start , length , this . codeBuffer , interner , codeView ) ; // Figure out where to start writing the disassembled code into the table. Map . Entry < Integer , Integer > entry = addressToRow . floorEntry ( start ) ; int firstRow = ( entry == null ) ? 0 : ( entry . getValue ( ) + 1 ) ; int address = start ; int row = firstRow ; // Build the mapping between addresses and rows. for ( WAMInstruction instruction : instructions ) { addressToRow . put ( address , row ) ; rowToAddress . add ( row , address ) ; row ++ ; address += instruction . sizeof ( ) ; } // Render the instructions into the table to be displayed. renderInstructions ( instructions , firstRow , start ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies code from the specified code buffer into the internal one resizing the internal code buffer if necessary to make enough room . [CODESPLIT] private void copyAndResizeCodeBuffer ( ByteBuffer codeBuffer , int start , int length ) { // Check the internal code buffer is large enough or resize it, then copy in the new instructions. int max = start + length ; if ( this . codeBuffer . limit ( ) <= max ) { ByteBuffer newCodeBuffer = ByteBuffer . allocate ( max * 2 ) ; newCodeBuffer . put ( this . codeBuffer . array ( ) , 0 , this . codeBuffer . limit ( ) ) ; log . fine ( \"Re-sized code buffer to \" + ( max * 2 ) ) ; } codeBuffer . position ( start ) ; codeBuffer . get ( this . codeBuffer . array ( ) , start , length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders disassembled instructions into the code table starting at the specified row and instruction address . [CODESPLIT] private void renderInstructions ( Iterable < WAMInstruction > instructions , int row , int address ) { for ( WAMInstruction instruction : instructions ) { WAMLabel label = instruction . getLabel ( ) ; labeledTable . put ( ADDRESS , row , String . format ( \"%08X\" , address ) ) ; labeledTable . put ( LABEL , row , ( label == null ) ? \"\" : ( label . toPrettyString ( ) + \":\" ) ) ; labeledTable . put ( MNEMONIC , row , instruction . getMnemonic ( ) . getPretty ( ) ) ; int fieldMask = instruction . getMnemonic ( ) . getFieldMask ( ) ; String arg = \"\" ; for ( int i = 2 ; i < 32 ; i = i * 2 ) { if ( ( fieldMask & i ) != 0 ) { if ( ! \"\" . equals ( arg ) ) { arg += \", \" ; } switch ( i ) { case 2 : arg += Integer . toString ( instruction . getReg1 ( ) ) ; break ; case 4 : arg += Integer . toString ( instruction . getReg2 ( ) ) ; break ; case 8 : FunctorName fn = instruction . getFn ( ) ; if ( fn != null ) { arg += fn . getName ( ) + \"/\" + fn . getArity ( ) ; } break ; case 16 : WAMLabel target1 = instruction . getTarget1 ( ) ; if ( target1 != null ) { arg += target1 . getName ( ) + \"/\" + target1 . getArity ( ) + \"_\" + target1 . getId ( ) ; } break ; } } } labeledTable . put ( ARG_1 , row , arg ) ; row ++ ; address += instruction . sizeof ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Functor functor ) { // functor is ground if all of its arguments are ground. boolean ground = true ; if ( functor . getArguments ( ) != null ) { for ( Term argument : functor . getArguments ( ) ) { SymbolKey symbolKey = argument . getSymbolKey ( ) ; TermDomain annotation = ( TermDomain ) symbolTable . get ( symbolKey , TERM_DOMAIN ) ; if ( ( annotation == null ) || ! annotation . ground ) { ground = false ; break ; } } } /*log.fine((ground ? \"ground \" : \"non-ground \") + functor.toString(interner, true, false));*/ symbolTable . put ( functor . getSymbolKey ( ) , TERM_DOMAIN , new TermDomain ( ground ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Variable variable ) { SymbolKey symbolKey = variable . getSymbolKey ( ) ; // Check if the variable has already been annotated. TermDomain annotation = ( TermDomain ) symbolTable . get ( symbolKey , TERM_DOMAIN ) ; if ( annotation == null ) { // variable is ground if it appears in a call to a predicate that always grounds that argument. /*log.fine(\"non-ground \" + variable.toString(interner, true, false));*/ symbolTable . put ( symbolKey , TERM_DOMAIN , new TermDomain ( false ) ) ; } else { /*log.fine(\"already seen \" + variable.toString(interner, true, false));*/ } // Check if the variable domain has already been annotated for a previous occurrence of the variable. VarDomain varDomain = ( VarDomain ) symbolTable . get ( symbolKey , VARIABLE_DOMAIN ) ; if ( varDomain == null ) { varDomain = new VarDomain ( traverser . isInHead ( ) ) ; symbolTable . put ( symbolKey , VARIABLE_DOMAIN , varDomain ) ; } else { varDomain . isTemporary = traverser . isInHead ( ) && varDomain . isTemporary ( ) ; } /*log.fine(variable.toString(interner, true, false) +\n            (varDomain.isTemporary() ? \" may be temporary.\" : \" is not temporary.\"));*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( LiteralType literal ) { // literal is ground. /*log.fine(\"ground \" + literal.toString(interner, true, false));*/ symbolTable . put ( literal . getSymbolKey ( ) , TERM_DOMAIN , new TermDomain ( true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the actual value of a term which is a numeric type equal in value to the arithmetic operator applied to its arguments . This method checks that both arguments produce values which are fully instantiated and numeric when their { @link Term#getValue () } methods are invoked . [CODESPLIT] public Term getValue ( ) { Term firstArgValue = arguments [ 0 ] . getValue ( ) ; Term secondArgValue = arguments [ 1 ] . getValue ( ) ; // Check that the arguments to operate on are both numeric values. if ( firstArgValue . isNumber ( ) && secondArgValue . isNumber ( ) ) { return evaluate ( ( NumericType ) firstArgValue , ( NumericType ) secondArgValue ) ; } else { return this ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a properties file and stores it in the application context . The property resource name and the application scope variable name are passed as initialization parameters in the servlet config in the web . xml . [CODESPLIT] public void init ( ) { log . fine ( \"public void init(): called\" ) ; // Get the name of the property file resource to load and the application variable name to store it under String propertyResource = getInitParameter ( PROPERTY_RESOURCE ) ; String varName = getInitParameter ( APP_VAR_NAME ) ; log . fine ( \"varName = \" + varName ) ; // Use the default property reader to load the resource Properties properties = DefaultPropertyReader . getProperties ( propertyResource ) ; log . fine ( \"properties = \" + properties ) ; // Store the properties under the specified variable name in the application scope getServletContext ( ) . setAttribute ( varName , properties ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; Term leftArg = goalTerm . getArgument ( 0 ) ; Term rightArg = goalTerm . getArgument ( 1 ) ; // This is used to record variables bound during the unification, so that they may be undone if the resolution // state is backtracked over. List < Variable > boundVariables = new LinkedList < Variable > ( ) ; // Unify the current query goal with the possibly matching clause, creating variable bindings. boolean matched = state . getUnifier ( ) . unifyInternal ( leftArg , rightArg , boundVariables , boundVariables ) ; if ( matched ) { if ( TRACE ) { /*trace.fine(state.getTraceIndenter().generateTraceIndent() + \"Unify \" +\n                    leftArg.toString(state.getInterner(), true, true) + \" against \" +\n                    rightArg.toString(state.getInterner(), true, true) + \", ok.\");*/ } for ( Variable binding : boundVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } } return matched ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a QueryParameter which contains reference to the original elements except for those from the exception list . [CODESPLIT] public QueryParameter partialCopy ( final QueryParameterKind ... excludedElements ) { List < QueryParameterKind > excludedList = Arrays . asList ( excludedElements ) ; QueryParameter returnValue = new QueryParameter ( ) ; if ( ! excludedList . contains ( QueryParameterKind . CONSTRAINTS ) ) { returnValue . rawConstraints = this . rawConstraints ; } if ( ! excludedList . contains ( QueryParameterKind . GROUPS ) ) { returnValue . groups = this . groups ; } if ( ! excludedList . contains ( QueryParameterKind . ORDERS ) ) { returnValue . orders = this . orders ; } if ( ! excludedList . contains ( QueryParameterKind . PAGE ) ) { returnValue . pageSize = this . pageSize ; returnValue . page = this . page ; } if ( ! excludedList . contains ( QueryParameterKind . TIMEZONE ) ) { returnValue . timezoneName = this . timezoneName ; } return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a child tree to the children of this point in the tree . If this is already a node then it remains as a node . If this is a leaf then adding a child to it must promote it to become a node . This implementation supports turning leaves into nodes . [CODESPLIT] public void addChild ( Tree < E > child ) { initChildren ( ) ; // Add the new child to the collection of children. children . add ( child ) ; // Set the type of this point in the tree to a node as it now has children. nodeOrLeaf = Type . Node ; // Set the new childs parent to this. child . setParent ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears all the children of this point in the tree . If this point is a leaf it will have no children so this operation does nothing . If this point is a node it will be reduced to a leaf by this operation . This implementation supports turning nodes into leaves . [CODESPLIT] public void clearChildren ( ) { // Check that their are children to clear. if ( children != null ) { // Loop over all the children setting their parent to null. for ( Tree < E > child : children ) { child . setParent ( null ) ; } // Clear out the children collection. children . clear ( ) ; // Mark this as a leaf node. nodeOrLeaf = Type . Leaf ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the next element from the sequence if one is available . The difference between this method and { @link #nextInSequence } is that this method consumes any cached solution so subsequent calls advance onto subsequent solutions . [CODESPLIT] public E next ( ) { // Consume the next element in the sequence, if one is available. E result = nextInternal ( ) ; if ( exhausted ) { throw new NoSuchElementException ( ) ; } nextSolution = null ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the next element from the sequence the cached one if one has already been generated or creating and caching a new one if not . If the cached element from a previous call has not been consumed then subsequent calls to this method will not advance the iterator . [CODESPLIT] private E nextInternal ( ) { // Check if the next soluation has already been cached, because of a call to hasNext. if ( nextSolution != null ) { return nextSolution ; } // Otherwise, generate the next solution, if possible. nextSolution = nextInSequence ( ) ; // Check if the solution was null, which indicates that the search space is exhausted. if ( nextSolution == null ) { exhausted = true ; } return nextSolution ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a conjunctive body functor or head functor to this clause along with the instructions that implement it . [CODESPLIT] public void addInstructions ( Functor body , SizeableList < WAMInstruction > instructions ) { int oldLength ; if ( this . body == null ) { oldLength = 0 ; this . body = new Functor [ 1 ] ; } else { oldLength = this . body . length ; this . body = Arrays . copyOf ( this . body , oldLength + 1 ) ; } this . body [ oldLength ] = body ; addInstructionsAndThisToParent ( instructions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds some instructions to the parent predicate and also adds this as a clause on the parent if it has not already been added . [CODESPLIT] private void addInstructionsAndThisToParent ( SizeableList < WAMInstruction > instructions ) { if ( ! addedToParent ) { parent . addInstructions ( this , instructions ) ; addedToParent = true ; } else { parent . addInstructions ( instructions ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the arithmetic operator on its two numeric arguments . [CODESPLIT] protected NumericType evaluate ( NumericType firstNumber , NumericType secondNumber ) { // If either of the arguments is a real number, then use real number arithmetic, otherwise use integer arithmetic. if ( firstNumber . isInteger ( ) && secondNumber . isInteger ( ) ) { return new IntLiteral ( firstNumber . intValue ( ) - secondNumber . intValue ( ) ) ; } else { return new DoubleLiteral ( firstNumber . doubleValue ( ) - secondNumber . doubleValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when a property in the WorkPanelState is changed . This method calls initPanels to rebuild the user interface to reflect the current application state . [CODESPLIT] public void propertyChange ( PropertyChangeEvent event ) { /*log.fine(\"void propertyChange(PropertyChangeEvent): called\");*/ // Check that the property change was sent by a WorkPanelState if ( event . getSource ( ) instanceof WorkPanelState ) { // Get the state String state = ( ( WorkPanelState ) event . getSource ( ) ) . getState ( ) ; // Check what the state to set is if ( state . equals ( WorkPanelState . NOT_SAVED ) ) { // Set the Cancel and Apply buttons to enabled cancelButton . setEnabled ( true ) ; applyButton . setEnabled ( true ) ; } else if ( state . equals ( WorkPanelState . READY ) ) { // Set the Cancel and Apply buttons to disabled cancelButton . setEnabled ( false ) ; applyButton . setEnabled ( false ) ; } else if ( state . equals ( WorkPanelState . NOT_INITIALIZED ) ) { // Disable all the buttons okButton . setEnabled ( false ) ; cancelButton . setEnabled ( false ) ; applyButton . setEnabled ( false ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified work panel to listen to the button press events for all of the OK Cancel and Apply buttons . Regisers this object to listen for changes to the work panels state . [CODESPLIT] public void registerWorkPanel ( WorkPanel panel ) { // Set the work panel to listen for actions generated by the buttons okButton . addActionListener ( panel ) ; cancelButton . addActionListener ( panel ) ; applyButton . addActionListener ( panel ) ; // Register this to listen for changes to the work panels state panel . getWorkPanelState ( ) . addPropertyChangeListener ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The { [CODESPLIT] public Result process ( Result parent , InputStream input ) throws IOException { ValueStack < Node > stack = new DefaultValueStack < Node > ( ) ; // Make the scope of each parent result accessible for variable and mixin resolution during parsing ScopeNode parentScope = null ; if ( parent != null ) { parentScope = parent . getScope ( ) ; stack . push ( parentScope ) ; } // Parse the input ParseRunner < Node > parseRunner = new ReportingParseRunner < Node > ( Parboiled . createParser ( Parser . class , _translationEnabled ) . Document ( ) ) . withValueStack ( stack ) ; ParsingResult < Node > result = parseRunner . run ( IOUtils . toString ( input , \"UTF-8\" ) ) ; if ( result . hasErrors ( ) ) { throw new LessTranslationException ( \"An error occurred while parsing a LESS input file:\\n\" + ErrorUtils . printParseErrors ( result ) ) ; } // Retrieve the processed result ScopeNode scope = ( ScopeNode ) stack . pop ( ) ; // Link the new scope to the last parent for later variable resolution if ( parentScope != null ) { scope . setParentScope ( parentScope ) ; } return new Result ( scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void addLayoutComponent ( String name , Component comp ) { componentMap . put ( name , comp ) ; reverseMap . put ( comp , name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void removeLayoutComponent ( Component comp ) { String name = reverseMap . remove ( comp ) ; if ( name != null ) { componentMap . remove ( name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Dimension preferredLayoutSize ( Container parent ) { Insets insets = parent . getInsets ( ) ; return new Dimension ( insets . left + insets . right , insets . top + insets . bottom ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void layoutContainer ( Container parent ) { // Get the available area to layout within. Insets insets = parent . getInsets ( ) ; int maxWidth = parent . getWidth ( ) - ( insets . left + insets . right ) ; int maxHeight = parent . getHeight ( ) - ( insets . top + insets . bottom ) ; // Check which optional components are present. updatePresentComponentFlags ( ) ; int centerHeight = maxHeight - ( ( hasConsole ? consoleHeight : 0 ) + ( hasStatusBar ? DEFAULT_STATUS_BAR_HEIGHT : 0 ) ) ; int statusBarTop = centerHeight ; int consoleTop = statusBarTop + DEFAULT_STATUS_BAR_HEIGHT ; int centerLeft = ( hasLeftPane ? leftPaneWidth : 0 ) + ( hasLeftBar ? DEFAULT_VBAR_WIDTH : 0 ) ; int centerRight = maxWidth - ( hasRightPane ? rightPaneWidth : 0 ) - ( hasRightBar ? DEFAULT_VBAR_WIDTH : 0 ) ; int centerWidth = centerRight - centerLeft ; int leftBarRight = centerLeft ; int leftBarLeft = leftBarRight - DEFAULT_VBAR_WIDTH ; int leftPaneRight = leftBarLeft ; int rightBarLeft = centerRight ; int rightPaneLeft = rightBarLeft + DEFAULT_VBAR_WIDTH ; for ( Component component : parent . getComponents ( ) ) { String type = reverseMap . get ( component ) ; int left = 0 ; int top = 0 ; int width = maxWidth ; int height = maxHeight ; if ( CENTER . equals ( type ) ) { left = centerLeft ; width = centerWidth ; height = centerHeight ; } else if ( STATUS_BAR . equals ( type ) ) { top = statusBarTop ; height = DEFAULT_STATUS_BAR_HEIGHT ; } else if ( CONSOLE . equals ( type ) ) { top = consoleTop ; height = consoleHeight ; } else if ( LEFT_PANE . equals ( type ) ) { width = leftPaneRight ; height = centerHeight ; } else if ( LEFT_VERTICAL_BAR . equals ( type ) ) { left = leftBarLeft ; width = DEFAULT_VBAR_WIDTH ; height = centerHeight ; } else if ( RIGHT_VERTICAL_BAR . equals ( type ) ) { left = rightBarLeft ; width = DEFAULT_VBAR_WIDTH ; height = centerHeight ; } else if ( RIGHT_PANE . equals ( type ) ) { left = rightPaneLeft ; width = rightPaneWidth ; height = centerHeight ; } component . setBounds ( left , top , width , height ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Keeps the set of flags indicating which window components are present up - to - date . [CODESPLIT] private void updatePresentComponentFlags ( ) { hasConsole = componentMap . containsKey ( CONSOLE ) ; hasStatusBar = componentMap . containsKey ( STATUS_BAR ) ; hasLeftBar = componentMap . containsKey ( LEFT_VERTICAL_BAR ) ; hasLeftPane = componentMap . containsKey ( LEFT_PANE ) ; hasRightBar = componentMap . containsKey ( RIGHT_VERTICAL_BAR ) ; hasRightPane = componentMap . containsKey ( RIGHT_PANE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public MicrodataDocument get ( String url ) { newUrl ( url ) ; driver . get ( url ) ; return new SeleniumMicrodataDocument ( driver ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new decimal type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , int precision , int scale , String min , String max ) { synchronized ( DECIMAL_TYPES ) { // Add the newly created type to the map of all types. BigDecimalTypeImpl newType = new BigDecimalTypeImpl ( name , precision , scale , min , max ) ; // Ensure that the named type does not already exist, unless it has an identical definition already, in which // case the old definition can be re-used and the new one discarded. BigDecimalTypeImpl oldType = DECIMAL_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( \"The type '\" + name + \"' already exists and cannot be redefined.\" ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { DECIMAL_TYPES . put ( name , newType ) ; return newType ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void acceptVisitor ( TypeVisitor visitor ) { if ( visitor instanceof BigDecimalTypeVisitor ) { ( ( BigDecimalTypeVisitor ) visitor ) . visit ( this ) ; } else { super . acceptVisitor ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void submitSubmitsRequest ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( String . format ( \"<html><body>\" + \"<form name='f' method='%s' action='/x'>\" + \"<input type='submit'/>\" + \"</form>\" + \"</body></html>\" , getMethod ( ) ) ) ) ; server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . submit ( ) ; server ( ) . takeRequest ( ) ; assertThat ( \"request\" , takeRequest ( server ( ) ) , is ( method ( \"/x\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determine whether a term is a free variable . [CODESPLIT] public boolean evaluate ( Term term ) { if ( term . isVar ( ) && ( term instanceof Variable ) ) { Variable var = ( Variable ) term ; return ! var . isBound ( ) && ! var . isAnonymous ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public < T extends WAMOptimizeableListing > T apply ( WAMOptimizeableListing listing ) { SizeableList < WAMInstruction > optListing = optimize ( listing . getInstructions ( ) ) ; listing . setOptimizedInstructions ( optListing ) ; return ( T ) listing ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs an optimization pass for specialized instructions . [CODESPLIT] private SizeableList < WAMInstruction > optimize ( List < WAMInstruction > instructions ) { StateMachine optimizeConstants = new OptimizeInstructions ( symbolTable , interner ) ; Iterable < WAMInstruction > matcher = new Matcher < WAMInstruction , WAMInstruction > ( instructions . iterator ( ) , optimizeConstants ) ; SizeableList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; for ( WAMInstruction instruction : matcher ) { result . add ( instruction ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two collections using lexicographic ordering based on a comparator of their elements . [CODESPLIT] public int compare ( Collection < T > c1 , Collection < T > c2 ) { // Simultaneously iterator over both collections until one runs out. Iterator < T > i1 = c1 . iterator ( ) ; Iterator < T > i2 = c2 . iterator ( ) ; while ( i1 . hasNext ( ) && i2 . hasNext ( ) ) { T t1 = i1 . next ( ) ; T t2 = i2 . next ( ) ; // Compare t1 and t2. int comp = comparator . compare ( t1 , t2 ) ; // Check if t1 < t2 in which case c1 < c2. if ( comp < 0 ) { return - 1 ; } // Check if t2 < t1 in which case c2 < c1. else if ( comp > 0 ) { return 1 ; } // Otherwise t1 = t2 in which case further elements must be examined in order to determine the ordering. } // If this point is reached then one of the collections ran out of elements before the ordering was determined. // Check if c1 ran out and c2 still has elements, in which case c1 < c2. if ( ! i1 . hasNext ( ) && i2 . hasNext ( ) ) { return - 1 ; } // Check if c2 ran out and c1 still has elements, in which case c2 < c1. if ( i1 . hasNext ( ) && ! i2 . hasNext ( ) ) { return 1 ; } // Otherwise both ran out in which case c1 = c2. return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getNameReturnsName ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<p itemprop='x'/>\" + \"</div>\" + \"</body></html>\" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"x\" ) . getName ( ) ; assertThat ( \"item property name\" , actual , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getValueWhenMetaReturnsContent ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<meta itemprop='p' content='x'/>\" + \"</div>\" + \"</body></html>\" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"p\" ) . getValue ( ) ; assertThat ( \"item property value\" , actual , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : fix for Selenium [CODESPLIT] @ Ignore @ Test public void getValueWhenObjectReturnsAbsoluteUrl ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<object itemprop='p' data='x'/>\" + \"</div>\" + \"</body></html>\" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"p\" ) . getValue ( ) ; assertThat ( \"item property value\" , actual , equalToIgnoringCase ( url ( server ( ) , \"/x\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getBooleanValueWhenTrueReturnsTrue ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<p itemprop='p'>true</p>\" + \"</div>\" + \"</body></html>\" ) ) ; boolean actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"p\" ) . getBooleanValue ( ) ; assertThat ( \"item property value\" , actual , is ( true ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getLongValueReturnsLong ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<p itemprop='p'>1</p>\" + \"</div>\" + \"</body></html>\" ) ) ; long actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"p\" ) . getLongValue ( ) ; assertThat ( \"item property value\" , actual , is ( 1L ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getFloatValueReturnsFloat ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<p itemprop='p'>1</p>\" + \"</div>\" + \"</body></html>\" ) ) ; float actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"p\" ) . getFloatValue ( ) ; assertThat ( \"item property value\" , actual , is ( 1f ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getDoubleValueReturnsDouble ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<p itemprop='p'>1</p>\" + \"</div>\" + \"</body></html>\" ) ) ; double actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"p\" ) . getDoubleValue ( ) ; assertThat ( \"item property value\" , actual , is ( 1d ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<p itemprop='x'/>\" + \"</div>\" + \"</body></html>\" ) ) ; MicrodataProperty property = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"x\" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( \"Cannot unwrap to: class java.lang.Void\" ) ; property . unwrap ( Void . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the http request that is directed to this servlet . [CODESPLIT] public void service ( HttpServletRequest request , HttpServletResponse response ) throws IOException { log . fine ( \"void service(HttpServletRequest, HttpServletResponse): called\" ) ; // Read the parameters and attributes from the request String contentType = ( String ) request . getAttribute ( \"contentType\" ) ; String contentDisposition = ( String ) request . getAttribute ( \"contentDisposition\" ) ; InputStream inputStream = ( InputStream ) request . getAttribute ( \"inputStream\" ) ; // Build the response header // response.addHeader(\"Content-disposition\", \"attachment; filename=\" + fileName); if ( contentType != null ) { response . setContentType ( contentType ) ; } if ( contentDisposition != null ) { response . addHeader ( \"Content-disposition\" , contentDisposition ) ; } // response.setContentLength((int)f.length()); // Create a stream to write the data out to BufferedOutputStream outputStream = new BufferedOutputStream ( response . getOutputStream ( ) ) ; // Read the entire input stream until no more bytes can be read and write the results into the response // This is done in chunks of 8k at a time. int length = - 1 ; byte [ ] chunk = new byte [ 8192 ] ; while ( ( length = inputStream . read ( chunk ) ) != - 1 ) { outputStream . write ( chunk , 0 , length ) ; } // Clear up any open stream and ensure that they are flushed outputStream . flush ( ) ; inputStream . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the paging control . [CODESPLIT] public int doStartTag ( ) throws JspException { log . fine ( \"public int doStartTag(): called\" ) ; TagUtils tagUtils = TagUtils . getInstance ( ) ; // Get a reference to the PagedList. PagedList list = ( PagedList ) tagUtils . lookup ( pageContext , name , property , scope ) ; log . fine ( \"list = \" + list ) ; // Work out what the URL of the action to handle the paging events is. String url ; try { url = tagUtils . computeURL ( pageContext , null , null , null , action , null , null , null , false ) ; } catch ( MalformedURLException e ) { throw new JspException ( \"Got malformed URL exception: \" , e ) ; } // Optionally render the first page button. renderButton ( renderFirst , 0 , 0 , openDelimFirst , url , firstText , list . getCurrentPage ( ) != 0 ) ; // Optionally render the back button. renderButton ( renderBack , list . getCurrentPage ( ) - 1 , ( ( list . getCurrentPage ( ) - 1 ) < list . getCurrentIndex ( ) ) ? ( list . getCurrentIndex ( ) - maxPages ) : list . getCurrentIndex ( ) , openDelimBack , url , backText , ( list . getCurrentPage ( ) - 1 ) >= 0 ) ; // Render links for pages from the current index to the current index plus the maximum number of pages. int from = list . getCurrentIndex ( ) ; int to = list . getCurrentIndex ( ) + maxPages ; for ( int i = from ; ( i < list . size ( ) ) && ( i < to ) ; i ++ ) { renderButton ( true , i , list . getCurrentIndex ( ) , ( i == list . getCurrentPage ( ) ) ? openDelimCurrent : openDelimNumber , url , \"\" + ( i + 1 ) , i != list . getCurrentPage ( ) ) ; } // Optionally render a more button. The more button should only be rendered if the current index plus // the maximum number of pages is less than the total number of pages so there are pages beyond those that // have numeric link to them already. renderButton ( ( list . getCurrentIndex ( ) + maxPages ) < list . size ( ) , list . getCurrentPage ( ) + maxPages , list . getCurrentPage ( ) + maxPages , openDelimMore , url , moreText , true ) ; // Optionally render a forward button. renderButton ( renderForward , list . getCurrentPage ( ) + 1 , ( ( list . getCurrentPage ( ) + 1 ) >= ( list . getCurrentIndex ( ) + maxPages ) ) ? ( list . getCurrentIndex ( ) + maxPages ) : list . getCurrentIndex ( ) , openDelimForward , url , forwardText , ( list . getCurrentPage ( ) + 1 ) < list . size ( ) ) ; // Optionally render a last page button. renderButton ( renderLast , list . size ( ) - 1 , ( list . size ( ) / maxPages ) * maxPages , openDelimLast , url , lastText , list . getCurrentPage ( ) != ( list . size ( ) - 1 ) ) ; return SKIP_BODY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders a button control as a hyperlink for the page control . [CODESPLIT] private void renderButton ( boolean render , int page , int index , String openDelim , String url , String text , boolean active ) throws JspException { log . fine ( \"private void renderButton(boolean render, int page, int index, String openDelim, String url, String text, boolean active): called\" ) ; log . fine ( \"render = \" + render ) ; log . fine ( \"page = \" + page ) ; log . fine ( \"index = \" + index ) ; log . fine ( \"openDelim = \" + openDelim ) ; log . fine ( \"url = \" + url ) ; log . fine ( \"text = \" + text ) ; log . fine ( \"active = \" + active ) ; TagUtils tagUtils = TagUtils . getInstance ( ) ; if ( render ) { tagUtils . write ( pageContext , openDelim ) ; // Only render the button as active if the active flag is set. if ( active ) { tagUtils . write ( pageContext , \"<a href=\\\"\" + url + \"?varName=\" + name + \"&number=\" + page + \"&index=\" + index + \"\\\">\" + text + \"</a>\" ) ; } // Render an inactive button. else { tagUtils . write ( pageContext , text ) ; } tagUtils . write ( pageContext , closeDelim ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int internFunctorName ( String name , int numArgs ) { FunctorName functorName = new FunctorName ( name , numArgs ) ; return getFunctorInterner ( ) . createIdAttribute ( functorName ) . ordinal ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; Term argument = goalTerm . getArgument ( 0 ) . getValue ( ) ; // Check that the argument is not a free variable. if ( argument . isVar ( ) ) { throw new IllegalStateException ( \"instantiation_error, 'call' expects a fully instantiated term to unify against.\" ) ; } // Check that the argument is callable. if ( ! argument . isFunctor ( ) && ! argument . isAtom ( ) ) { throw new IllegalStateException ( \"type_error, callable expected as argument to 'call'.\" ) ; } // Set up the argument to call as a new goal. state . getGoalStack ( ) . offer ( state . getBuiltInTransform ( ) . apply ( ( Functor ) argument ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the learning method . This should clear all the examples properties to learn from and for and the input machine to train . [CODESPLIT] public void reset ( ) { maxSteps = 0 ; machineToTrain = null ; inputExamples = new ArrayList < State > ( ) ; inputProperties = new HashSet < String > ( ) ; outputProperties = new HashSet < String > ( ) ; inputPropertiesSet = false ; outputPropertiesSet = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This should be called at the start of the learn method to initialize the input and output property sets . [CODESPLIT] protected void initialize ( ) throws LearningFailureException { // Check that at least one training example has been set. if ( inputExamples . isEmpty ( ) ) { throw new LearningFailureException ( \"No training examples to learn from.\" , null ) ; } // Check if an output property set to override the default was not set. if ( ! outputPropertiesSet ) { // Set the 'goal' property as the default. addGoalProperty ( \"goal\" ) ; } // Check if an input property set to override the default was not set. if ( ! inputPropertiesSet ) { // Extract all properties from the first example in the training data set as the input property set, // automatically excluding any properties which are in the output set. State example = inputExamples . iterator ( ) . next ( ) ; Set < String > allProperties = example . getComponentType ( ) . getAllPropertyNames ( ) ; inputProperties = new HashSet < String > ( allProperties ) ; inputProperties . removeAll ( outputProperties ) ; inputPropertiesSet = true ; } // Check all the training examples have all the required input and output properties. for ( State example : inputExamples ) { Set < String > properties = example . getComponentType ( ) . getAllPropertyNames ( ) ; String errorMessage = \"\" ; for ( String inputProperty : inputProperties ) { if ( ! properties . contains ( inputProperty ) ) { errorMessage += \"The training example, \" + example + \" does not contain the specified input property, \" + inputProperty + \"\\n\" ; } } for ( String outputProperty : outputProperties ) { if ( ! properties . contains ( outputProperty ) ) { errorMessage += \"The training example, \" + example + \" does not contain the specified output property, \" + outputProperty + \"\\n\" ; } } if ( ! \"\" . equals ( errorMessage ) ) { throw new LearningFailureException ( errorMessage , null ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which this map maps the specified key . [CODESPLIT] public V get ( Object key ) { // Get the index from the map Integer index = keyToIndex . get ( key ) ; // Check that the key is in the map if ( index == null ) { return null ; } // Get the data from the array return data . get ( index . intValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the index to which this map maps the specified key . [CODESPLIT] public int getIndexOf ( Object key ) { // Get the index from the map Integer index = keyToIndex . get ( key ) ; // Check that the key is in the map and return -1 if it is not. if ( index == null ) { return - 1 ; } return index ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified key in this map . [CODESPLIT] public V put ( K key , V value ) { // Remove any existing matching key from the data V removedObject = remove ( key ) ; // Insert the data into the array data . add ( value ) ; // Insert a key into the map that points to the end of the array keyToIndex . put ( key , data . size ( ) - 1 ) ; // Create an entry in the key set to track the insertion order of the keys (automatically goes at the end of // a linked hash set) keySet . add ( key ) ; // Return the replaced value if there was one return removedObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the element at the specified index . This only works if this index already exists . [CODESPLIT] public V set ( int index , V value ) throws IndexOutOfBoundsException { // Check if the index does not already exist if ( index >= data . size ( ) ) { throw new IndexOutOfBoundsException ( ) ; } return data . set ( index , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the mapping for the specified key from this map if present . [CODESPLIT] public V remove ( Object key ) { // Check if the key is in the map Integer index = keyToIndex . get ( key ) ; if ( index == null ) { return null ; } // Leave the data in the array but remove its key keyToIndex . remove ( key ) ; keySet . remove ( key ) ; // Remove the data from the array V removedValue = data . remove ( index . intValue ( ) ) ; // Go through the whole key to index map reducing by one the value of any indexes greater that the removed index for ( K nextKey : keyToIndex . keySet ( ) ) { Integer nextIndex = keyToIndex . get ( nextKey ) ; if ( nextIndex > index ) { keyToIndex . put ( nextKey , nextIndex - 1 ) ; } } // Return the removed object return removedValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified index from the data structure . This only works if the index already exists . [CODESPLIT] public V remove ( int index ) throws IndexOutOfBoundsException { // Check that the index is not too large if ( index >= data . size ( ) ) { throw new IndexOutOfBoundsException ( ) ; } // Get the key for the index by scanning through the key to index mapping for ( K nextKey : keyToIndex . keySet ( ) ) { int nextIndex = keyToIndex . get ( nextKey ) ; // Found the key for the index, now remove it if ( index == nextIndex ) { return remove ( nextKey ) ; } } // No matching index was found throw new IndexOutOfBoundsException ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the bean has a named property . Note that if the property value is set to null on the bean this method will still return true it tests for the existance of a named property including null ones . [CODESPLIT] public boolean hasProperty ( String property ) { // Check if a getter method exists for the property. Method getterMethod = getters . get ( property ) ; return getterMethod != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of a property of the bean by name . [CODESPLIT] protected void setProperty ( Object callee , String property , Object value ) { // Initialize this meta bean if it has not already been initialized. if ( ! initialized ) { initialize ( callee ) ; } // Check that at least one setter method exists for the property. Method [ ] setterMethods = setters . get ( property ) ; if ( ( setterMethods == null ) || ( setterMethods . length == 0 ) ) { throw new IllegalArgumentException ( \"No setter method for the property \" + property + \" exists.\" ) ; } // Choose which setter method to call based on the type of the value argument. If the value argument is null // then call the first available one. Method setterMethod = null ; Class valueType = ( value == null ) ? null : value . getClass ( ) ; // Check if the value is null and use the first available setter if so, as type cannot be extracted. if ( value == null ) { setterMethod = setterMethods [ 0 ] ; } // Loop through the available setter methods for one that matches the arguments type. else { for ( Method method : setterMethods ) { Class argType = method . getParameterTypes ( ) [ 0 ] ; if ( argType . isAssignableFrom ( valueType ) ) { setterMethod = method ; break ; } // Check if the arg type is primitive but the value type is a wrapper type that matches it. else if ( argType . isPrimitive ( ) && ! valueType . isPrimitive ( ) && isAssignableFromPrimitive ( valueType , argType ) ) { setterMethod = method ; break ; } // Check if the arg type is a wrapper but the value type is a primitive type that matches it. else if ( valueType . isPrimitive ( ) && ! argType . isPrimitive ( ) && isAssignableFromPrimitive ( argType , valueType ) ) { setterMethod = method ; break ; } } // Check if this point has been reached but no matching setter method could be found, in which case raise // an exception. if ( setterMethod == null ) { Class calleeType = ( callee == null ) ? null : callee . getClass ( ) ; throw new IllegalArgumentException ( \"No setter method for property \" + property + \", of type, \" + calleeType + \" will accept the type of value specified, \" + valueType + \".\" ) ; } } // Call the setter method with the value. try { Object [ ] args = new Object [ ] { value } ; setterMethod . invoke ( callee , args ) ; } catch ( InvocationTargetException e ) { throw new IllegalArgumentException ( \"The setter method for the property \" + property + \" threw an invocation target exception.\" , e ) ; } // This should never happen as the initiliazed method should already have checked this. catch ( IllegalAccessException e ) { throw new IllegalStateException ( \"The setter method for the property \" + property + \" cannot be accessed.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a single named property of the bean . [CODESPLIT] protected Object getProperty ( Object callee , String property ) { // Initialize this meta bean if it has not already been initialized. if ( ! initialized ) { initialize ( callee ) ; } // Check if a getter method exists for the property being fetched. Method getterMethod = getters . get ( property ) ; if ( getterMethod == null ) { throw new IllegalArgumentException ( \"No getter method for the property \" + property + \" exists.\" ) ; } // Fetch the value by calling the getter method. Object result ; try { result = getterMethod . invoke ( callee ) ; } // This should never happen as the initiliazation method should already have checked this. catch ( InvocationTargetException e ) { throw new IllegalStateException ( \"The getter method for the property \" + property + \" threw an invocation target exception.\" , e ) ; } // This should never happen as the initiliazation method should already have checked this. catch ( IllegalAccessException e ) { throw new IllegalStateException ( \"The getter method for the property \" + property + \" cannot be accessed.\" , e ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a wrapper type is assignable from a primtive type . [CODESPLIT] private boolean isAssignableFromPrimitive ( Class wrapperType , Class primitiveType ) { boolean result = false ; if ( primitiveType . equals ( boolean . class ) && wrapperType . equals ( Boolean . class ) ) { result = true ; } else if ( primitiveType . equals ( byte . class ) && wrapperType . equals ( Byte . class ) ) { result = true ; } else if ( primitiveType . equals ( char . class ) && wrapperType . equals ( Character . class ) ) { result = true ; } else if ( primitiveType . equals ( short . class ) && wrapperType . equals ( Short . class ) ) { result = true ; } else if ( primitiveType . equals ( int . class ) && wrapperType . equals ( Integer . class ) ) { result = true ; } else if ( primitiveType . equals ( long . class ) && wrapperType . equals ( Long . class ) ) { result = true ; } else if ( primitiveType . equals ( float . class ) && wrapperType . equals ( Float . class ) ) { result = true ; } else if ( primitiveType . equals ( double . class ) && wrapperType . equals ( Double . class ) ) { result = true ; } else { result = false ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialized this property introspector on a specified object building the caches of getter and setter methods . [CODESPLIT] private void initialize ( Object callee ) { // This is used to build up all the setter methods in. Map < String , List < Method > > settersTemp = new HashMap < String , List < Method > > ( ) ; // Get all the property getters and setters on this class. Method [ ] methods = callee . getClass ( ) . getMethods ( ) ; for ( Method nextMethod : methods ) { String methodName = nextMethod . getName ( ) ; // Check if it is a getter method. if ( methodName . startsWith ( \"get\" ) && ( methodName . length ( ) >= 4 ) && Character . isUpperCase ( methodName . charAt ( 3 ) ) && Modifier . isPublic ( nextMethod . getModifiers ( ) ) && ( nextMethod . getParameterTypes ( ) . length == 0 ) ) { String propertyName = methodName . substring ( 3 , 4 ) . toLowerCase ( ) + methodName . substring ( 4 ) ; getters . put ( propertyName , nextMethod ) ; } // Check if it is a setter method. else if ( methodName . startsWith ( \"set\" ) && Modifier . isPublic ( nextMethod . getModifiers ( ) ) && ( nextMethod . getParameterTypes ( ) . length == 1 ) ) { /*log.fine(\"Found setter method.\");*/ String propertyName = methodName . substring ( 3 , 4 ) . toLowerCase ( ) + methodName . substring ( 4 ) ; /*log.fine(\"propertyName = \" + propertyName);*/ // Check the setter to see if any for this name already exist, and start a new list if not. List < Method > setterMethodsForName = settersTemp . get ( propertyName ) ; if ( setterMethodsForName == null ) { setterMethodsForName = new ArrayList < Method > ( ) ; settersTemp . put ( propertyName , setterMethodsForName ) ; } // Add the setter method to the list of setter methods for the named property. setterMethodsForName . add ( nextMethod ) ; } } // Convert all the lists of setter methods into arrays. for ( Map . Entry < String , List < Method > > entries : settersTemp . entrySet ( ) ) { String nextPropertyName = entries . getKey ( ) ; List < Method > nextMethodList = entries . getValue ( ) ; Method [ ] methodArray = nextMethodList . toArray ( new Method [ nextMethodList . size ( ) ] ) ; setters . put ( nextPropertyName , methodArray ) ; } // Initialization completed, set the initialized flag. initialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void propertyChange ( PropertyChangeEvent evt ) { String hex = String . format ( \"%08X\" , evt . getNewValue ( ) ) ; labeledTable . put ( evt . getPropertyName ( ) , hex ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; Term argument = goalTerm . getArgument ( 0 ) . getValue ( ) ; // Check that the argument is not a free variable. return argument . isNumber ( ) && ( ( NumericType ) argument . getValue ( ) ) . isReal ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the actual decision based on a property of the state . If the quick lookup table has been initialized then the decision is taken straight from it . If not then the supplied reference to the decision tree at this point is used to find the outcome by scanning over its children . [CODESPLIT] public DecisionTree decide ( State state ) { // Extract the value of the property being decided from state to be classified. OrdinalAttribute attributeValue = ( OrdinalAttribute ) state . getProperty ( propertyName ) ; // Extract the child decision tree that matches the property value, using the attributes ordinal for a quick // look up. return decisions [ attributeValue . ordinal ( ) ] ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the lookup table for this decision node . The specified decision tree that corresponds to this node is used to extract all the possible outcomes for this decision and these are stored in a lookup table so that future decisions made with this tree will run faster . [CODESPLIT] public void initializeLookups ( DecisionTree thisNode ) { // Scan over all the decision trees children at this point inserting them into the lookup table depending // on the ordinal of the attribute value that matches them. for ( Iterator < Tree < DecisionTreeElement > > i = thisNode . getChildIterator ( ) ; i . hasNext ( ) ; ) { DecisionTree nextChildTree = ( DecisionTree ) i . next ( ) ; // Get the matching attribute value from the childs decision tree element. OrdinalAttribute matchingValue = nextChildTree . getElement ( ) . getAttributeValue ( ) ; // Insert the matching sub-tree into the lookup table. decisions [ matchingValue . ordinal ( ) ] = nextChildTree ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unifies two terms and produces a list of bound variables that form the unification when it it possible . [CODESPLIT] public List < Variable > unify ( Term query , Term statement ) { /*log.fine(\"unify(Term left = \" + query + \", Term right = \" + statement + \"): called\");*/ // Find all free variables in the query. Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( query ) ; // Build up all the variable bindings in both sides of the unification in these bindings. List < Variable > queryBindings = new LinkedList < Variable > ( ) ; List < Variable > statementBindings = new LinkedList < Variable > ( ) ; // Fund the most general unifier, if possible. boolean unified = unifyInternal ( query , statement , queryBindings , statementBindings ) ; List < Variable > results = null ; // If a unification was found, only retain the free variables in the query in the results returned. if ( unified ) { queryBindings . retainAll ( freeVars ) ; results = new ArrayList < Variable > ( queryBindings ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to unify one term with another against a background of already unified variables in both terms . In the case where two terms are being unified from scratch the variable assignments will be empty . [CODESPLIT] public boolean unifyInternal ( Term left , Term right , List < Variable > leftTrail , List < Variable > rightTrail ) { /*log.fine(\"public boolean unifyInternal(Term left = \" + left + \", Term right = \" + right +\n            \", List<Variable> trail = \" + leftTrail + \"): called\");*/ if ( left == right ) { /*log.fine(\"Terms are identical objects.\");*/ return true ; } if ( ! left . isVar ( ) && ! right . isVar ( ) && left . isConstant ( ) && right . isConstant ( ) && left . equals ( right ) ) { /*log.fine(\"Terms are equal atoms or literals.\");*/ return true ; } else if ( left . isVar ( ) ) { /*log.fine(\"Left is a variable.\");*/ return unifyVar ( ( Variable ) left , right , leftTrail , rightTrail ) ; } else if ( right . isVar ( ) ) { /*log.fine(\"Right is a variable.\");*/ return unifyVar ( ( Variable ) right , left , rightTrail , leftTrail ) ; } else if ( left . isFunctor ( ) && right . isFunctor ( ) ) { /*log.fine(\"Terms are functors, at least one of which is not an atom.\");*/ Functor leftFunctor = ( Functor ) left ; Functor rightFunctor = ( Functor ) right ; // Check if the functors may be not be equal (that is, they do not have the same name and arity), in // which case they cannot possibly be unified. if ( ! left . equals ( right ) ) { return false ; } /*log.fine(\"Terms are functors with same name and arity, both are compound.\");*/ // Pairwise unify all of the arguments of the functor. int arity = leftFunctor . getArity ( ) ; for ( int i = 0 ; i < arity ; i ++ ) { Term leftArgument = leftFunctor . getArgument ( i ) ; Term rightArgument = rightFunctor . getArgument ( i ) ; boolean result = unifyInternal ( leftArgument , rightArgument , leftTrail , rightTrail ) ; if ( ! result ) { /*log.fine(\"Non unifying arguments in functors encountered, left = \" + leftArgument + \", right = \" +\n                        rightArgument);*/ return false ; } } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unifies a variable with a term . If the variable is bound then the bound value is unified with the term . If the term is a bound variable and the variable is free then the vairable is unified with the bound value of the term . Otherwise the variable is free and is bound to the value of the term . [CODESPLIT] protected boolean unifyVar ( Variable leftVar , Term rightTerm , List < Variable > leftTrail , List < Variable > rightTrail ) { /*log.fine(\"protected boolean unifyVar(Variable var = \" + leftVar + \", Term term = \" + rightTerm +\n            \", List<Variable> trail = \" + leftTrail + \"): called\");*/ // Check if the variable is bound (in the trail, but no need to explicitly check the trail as the binding is // already held against the variable). if ( leftVar . isBound ( ) ) { /*log.fine(\"Variable is bound.\");*/ return unifyInternal ( leftVar . getValue ( ) , rightTerm , leftTrail , rightTrail ) ; } else if ( rightTerm . isVar ( ) && ( ( Variable ) rightTerm ) . isBound ( ) ) { // The variable is free, but the term itself is a bound variable, in which case unify againt the value // of the term. /*log.fine(\"Term is a bound variable.\");*/ return unifyInternal ( leftVar , rightTerm . getValue ( ) , leftTrail , rightTrail ) ; } else { // Otherwise, unify by binding the variable to the value of the term. /*log.fine(\"Variable is free, substituting in the term for it.\");*/ leftVar . setSubstitution ( rightTerm ) ; leftTrail . add ( leftVar . getStorageCell ( leftVar ) ) ; //leftTrail.add(leftVar); return true ; } // Occurs can go above if desired. /*else if (var occurs anywhere in x)\n        {\n            return false;\n        }*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void endScope ( ) throws SourceCodeException { // Loop over all predicates in the current scope, found in the symbol table, and consume and compile them. for ( SymbolKey predicateKey = predicatesInScope . poll ( ) ; predicateKey != null ; predicateKey = predicatesInScope . poll ( ) ) { List < Clause > clauseList = ( List < Clause > ) scopeTable . get ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; // Used to keep track of where within the predicate the current clause is. int size = clauseList . size ( ) ; int current = 0 ; boolean multipleClauses = size > 1 ; // Used to build up the compiled predicate in. WAMCompiledPredicate result = null ; for ( Iterator < Clause > iterator = clauseList . iterator ( ) ; iterator . hasNext ( ) ; iterator . remove ( ) ) { Clause clause = iterator . next ( ) ; if ( result == null ) { result = new WAMCompiledPredicate ( clause . getHead ( ) . getName ( ) ) ; } // Compile the single clause, adding it to the parent compiled predicate. compileClause ( clause , result , current == 0 , current >= ( size - 1 ) , multipleClauses , current ) ; current ++ ; } // Run the optimizer on the output. result = optimizer . apply ( result ) ; displayCompiledPredicate ( result ) ; observer . onCompilation ( result ) ; // Move up the low water mark on the predicates table. symbolTable . setLowMark ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; } // Clear up the symbol table, and bump the compilation scope up by one. symbolTable . clearUpToLowMark ( SymbolTableKeys . SYMKEY_PREDICATES ) ; scopeTable = null ; scope ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void compile ( Sentence < Clause > sentence ) throws SourceCodeException { /*log.fine(\"public WAMCompiledClause compile(Sentence<Term> sentence = \" + sentence + \"): called\");*/ // Extract the clause to compile from the parsed sentence. Clause clause = sentence . getT ( ) ; // Classify the sentence to compile by the different sentence types in the language. if ( clause . isQuery ( ) ) { compileQuery ( clause ) ; } else { // Initialise a nested symbol table for the current compilation scope, if it has not already been. if ( scopeTable == null ) { scopeTable = symbolTable . enterScope ( scope ) ; } // Check in the symbol table, if a compiled predicate with name matching the program clause exists, and if // not create it. SymbolKey predicateKey = scopeTable . getSymbolKey ( clause . getHead ( ) . getName ( ) ) ; Collection < Clause > clauseList = ( List < Clause > ) scopeTable . get ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; if ( clauseList == null ) { clauseList = new LinkedList < Clause > ( ) ; scopeTable . put ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES , clauseList ) ; predicatesInScope . offer ( predicateKey ) ; } // Add the clause to compile to its parent predicate for compilation at the end of the current scope. clauseList . add ( clause ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles a program clause and adds its instructions to a compiled predicate . [CODESPLIT] private void compileClause ( Clause clause , WAMCompiledPredicate compiledPredicate , boolean isFirst , boolean isLast , boolean multipleClauses , int clauseNumber ) throws SourceCodeException { // Used to build up the compiled clause in. WAMCompiledClause result = new WAMCompiledClause ( compiledPredicate ) ; // Check if the clause to compile is a fact (no body). boolean isFact = clause . getBody ( ) == null ; // Check if the clause to compile is a chain rule, (one called body). boolean isChainRule = ( clause . getBody ( ) != null ) && ( clause . getBody ( ) . length == 1 ) ; // Used to keep track of registers as they are seen during compilation. The first time a variable is seen, // a variable is written onto the heap, subsequent times its value. The first time a functor is seen, // its structure is written onto the heap, subsequent times it is compared with. seenRegisters = new TreeSet < Integer > ( ) ; // This is used to keep track of the next temporary register available to allocate. lastAllocatedTempReg = findMaxArgumentsInClause ( clause ) ; // This is used to keep track of the number of permanent variables. numPermanentVars = 0 ; // This is used to keep track of the allocation slot for the cut level variable, when needed. -1 means it is // not needed, so it is initialized to this. cutLevelVarSlot = - 1 ; // These are used to generate pre and post instructions for the clause, for example, for the creation and // clean-up of stack frames. SizeableList < WAMInstruction > preFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableList < WAMInstruction > postFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Find all the free non-anonymous variables in the clause. Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( clause ) ; Collection < Integer > freeVarNames = new TreeSet < Integer > ( ) ; for ( Variable var : freeVars ) { freeVarNames . add ( var . getName ( ) ) ; } // Allocate permanent variables for a program clause. Program clauses only use permanent variables when really // needed to preserve variables across calls. allocatePermanentProgramRegisters ( clause ) ; // Gather information about the counts and positions of occurrence of variables and constants within the clause. gatherPositionAndOccurrenceInfo ( clause ) ; // Labels the entry point to each choice point. FunctorName fn = interner . getFunctorFunctorName ( clause . getHead ( ) ) ; WAMLabel entryLabel = new WAMLabel ( fn , clauseNumber ) ; // Label for the entry point to the next choice point, to backtrack to. WAMLabel retryLabel = new WAMLabel ( fn , clauseNumber + 1 ) ; // Create choice point instructions for the clause, depending on its position within the containing predicate. // The choice point instructions are only created when a predicate is built from multiple clauses, as otherwise // there are no choices to be made. if ( isFirst && ! isLast && multipleClauses ) { // try me else. preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TryMeElse , retryLabel ) ) ; } else if ( ! isFirst && ! isLast && multipleClauses ) { // retry me else. preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . RetryMeElse , retryLabel ) ) ; } else if ( isLast && multipleClauses ) { // trust me. preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TrustMe ) ) ; } // Generate the prefix code for the clause. // Rules may chain multiple, so require stack frames to preserve registers across calls. // Facts are always leafs so can use the global continuation point register to return from calls. // Chain rules only make one call, so also do not need a stack frame. if ( ! ( isFact || isChainRule ) ) { // Allocate a stack frame at the start of the clause. /*log.fine(\"ALLOCATE \" + numPermanentVars);*/ preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Allocate ) ) ; } // Deep cuts require the current choice point to be kept in a permanent variable, so that it can be recovered // once deeper choice points or environments have been reached. if ( cutLevelVarSlot >= 0 ) { /*log.fine(\"GET_LEVEL \"+ cutLevelVarSlot);*/ preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetLevel , ( byte ) cutLevelVarSlot ) ) ; } result . addInstructions ( preFixInstructions ) ; // Compile the clause head. Functor expression = clause . getHead ( ) ; SizeableLinkedList < WAMInstruction > instructions = compileHead ( expression ) ; result . addInstructions ( expression , instructions ) ; // Compile all of the conjunctive parts of the body of the clause, if there are any. if ( ! isFact ) { Functor [ ] expressions = clause . getBody ( ) ; for ( int i = 0 ; i < expressions . length ; i ++ ) { expression = expressions [ i ] ; boolean isLastBody = i == ( expressions . length - 1 ) ; boolean isFirstBody = i == 0 ; Integer permVarsRemaining = ( Integer ) symbolTable . get ( expression . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_PERM_VARS_REMAINING ) ; // Select a non-default built-in implementation to compile the functor with, if it is a built-in. BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = this ; } // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule. instructions = builtIn . compileBodyArguments ( expression , i == 0 , fn , i ) ; result . addInstructions ( expression , instructions ) ; // Call the body. The number of permanent variables remaining is specified for environment trimming. instructions = builtIn . compileBodyCall ( expression , isFirstBody , isLastBody , isChainRule , permVarsRemaining ) ; result . addInstructions ( expression , instructions ) ; } } // Generate the postfix code for the clause. Rules may chain, so require stack frames. // Facts are always leafs so can use the global continuation point register to return from calls. if ( isFact ) { /*log.fine(\"PROCEED\");*/ postFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Proceed ) ) ; } result . addInstructions ( postFixInstructions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles a clause as a query . The clause should have no head only a body . [CODESPLIT] private void compileQuery ( Clause clause ) throws SourceCodeException { // Used to build up the compiled result in. WAMCompiledQuery result ; // A mapping from top stack frame slots to interned variable names is built up in this. // This is used to track the stack positions that variables in a query are assigned to. Map < Byte , Integer > varNames = new TreeMap < Byte , Integer > ( ) ; // Used to keep track of registers as they are seen during compilation. The first time a variable is seen, // a variable is written onto the heap, subsequent times its value. The first time a functor is seen, // its structure is written onto the heap, subsequent times it is compared with. seenRegisters = new TreeSet < Integer > ( ) ; // This is used to keep track of the next temporary register available to allocate. lastAllocatedTempReg = findMaxArgumentsInClause ( clause ) ; // This is used to keep track of the number of permanent variables. numPermanentVars = 0 ; // This is used to keep track of the allocation slot for the cut level variable, when needed. -1 means it is // not needed, so it is initialized to this. cutLevelVarSlot = - 1 ; // These are used to generate pre and post instructions for the clause, for example, for the creation and // clean-up of stack frames. SizeableList < WAMInstruction > preFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableList < WAMInstruction > postFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Find all the free non-anonymous variables in the clause. Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( clause ) ; Set < Integer > freeVarNames = new TreeSet < Integer > ( ) ; for ( Variable var : freeVars ) { freeVarNames . add ( var . getName ( ) ) ; } // Allocate permanent variables for a query. In queries all variables are permanent so that they are preserved // on the stack upon completion of the query. allocatePermanentQueryRegisters ( clause , varNames ) ; // Gather information about the counts and positions of occurrence of variables and constants within the clause. gatherPositionAndOccurrenceInfo ( clause ) ; result = new WAMCompiledQuery ( varNames , freeVarNames ) ; // Generate the prefix code for the clause. Queries require a stack frames to hold their environment. /*log.fine(\"ALLOCATE \" + numPermanentVars);*/ preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . AllocateN , REG_ADDR , ( byte ) ( numPermanentVars & 0xff ) ) ) ; // Deep cuts require the current choice point to be kept in a permanent variable, so that it can be recovered // once deeper choice points or environments have been reached. if ( cutLevelVarSlot >= 0 ) { /*log.fine(\"GET_LEVEL \"+ cutLevelVarSlot);*/ preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetLevel , STACK_ADDR , ( byte ) cutLevelVarSlot ) ) ; } result . addInstructions ( preFixInstructions ) ; // Compile all of the conjunctive parts of the body of the clause, if there are any. Functor [ ] expressions = clause . getBody ( ) ; // The current query does not have a name, so invent one for it. FunctorName fn = new FunctorName ( \"tq\" , 0 ) ; for ( int i = 0 ; i < expressions . length ; i ++ ) { Functor expression = expressions [ i ] ; boolean isFirstBody = i == 0 ; // Select a non-default built-in implementation to compile the functor with, if it is a built-in. BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = this ; } // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule, which it // never is for a query. SizeableLinkedList < WAMInstruction > instructions = builtIn . compileBodyArguments ( expression , false , fn , i ) ; result . addInstructions ( expression , instructions ) ; // Queries are never chain rules, and as all permanent variables are preserved, bodies are never called // as last calls. instructions = builtIn . compileBodyCall ( expression , isFirstBody , false , false , numPermanentVars ) ; result . addInstructions ( expression , instructions ) ; } // Generate the postfix code for the clause. /*log.fine(\"DEALLOCATE\");*/ postFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Suspend ) ) ; postFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; result . addInstructions ( postFixInstructions ) ; // Run the optimizer on the output. result = optimizer . apply ( result ) ; displayCompiledQuery ( result ) ; observer . onQueryCompilation ( result ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Examines all top - level functors within a clause including any head and body and determines which functor has the highest number of arguments . [CODESPLIT] private int findMaxArgumentsInClause ( Clause clause ) { int result = 0 ; Functor head = clause . getHead ( ) ; if ( head != null ) { result = head . getArity ( ) ; } Functor [ ] body = clause . getBody ( ) ; if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { int arity = body [ i ] . getArity ( ) ; result = ( arity > result ) ? arity : result ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compiles the head of a clause into an instruction listing in WAM . [CODESPLIT] private SizeableLinkedList < WAMInstruction > compileHead ( Functor expression ) { // Used to build up the results in. SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Allocate argument registers on the body, to all functors as outermost arguments. // Allocate temporary registers on the body, to all terms not already allocated. allocateArgumentRegisters ( expression ) ; allocateTemporaryRegisters ( expression ) ; // Program instructions are generated in the same order as the registers are assigned, the postfix // ordering used for queries is not needed. SearchMethod outInSearch = new BreadthFirstSearch < Term , Term > ( ) ; outInSearch . reset ( ) ; outInSearch . addStartState ( expression ) ; Iterator < Term > treeWalker = Searches . allSolutions ( outInSearch ) ; // Skip the outermost functor. treeWalker . next ( ) ; // Allocate argument registers on the body, to all functors as outermost arguments. // Allocate temporary registers on the body, to all terms not already allocated. // Keep track of processing of the arguments to the outermost functor as get_val and get_var instructions // need to be output for variables encountered in the arguments only. int numOutermostArgs = expression . getArity ( ) ; for ( int j = 0 ; treeWalker . hasNext ( ) ; j ++ ) { Term nextTerm = treeWalker . next ( ) ; /*log.fine(\"nextTerm = \" + nextTerm);*/ // For each functor encountered: get_struc. if ( nextTerm . isFunctor ( ) ) { Functor nextFunctor = ( Functor ) nextTerm ; int allocation = ( Integer ) symbolTable . get ( nextFunctor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; // Ouput a get_struc instruction, except on the outermost functor. /*log.fine(\"GET_STRUC \" + interner.getFunctorName(nextFunctor) + \"/\" + nextFunctor.getArity() +\n                    ((addrMode == REG_ADDR) ? \", X\" : \", Y\") + address);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetStruc , addrMode , address , interner . getFunctorFunctorName ( nextFunctor ) , nextFunctor ) ; instructions . add ( instruction ) ; // For each argument of the functor. int numArgs = nextFunctor . getArity ( ) ; for ( int i = 0 ; i < numArgs ; i ++ ) { Term nextArg = nextFunctor . getArgument ( i ) ; allocation = ( Integer ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; /*log.fine(\"nextArg = \" + nextArg);*/ // If it is register not seen before: unify_var. // If it is register seen before: unify_val. if ( ! seenRegisters . contains ( allocation ) ) { /*log.fine(\"UNIFY_VAR \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address);*/ seenRegisters . add ( allocation ) ; instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyVar , addrMode , address , nextArg ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Unify ) ; } else { // Check if the variable is 'local' and use a local instruction on the first occurrence. VarIntroduction introduction = ( VarIntroduction ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO ) ; if ( isLocalVariable ( introduction , addrMode ) ) { /*log.fine(\"UNIFY_LOCAL_VAL \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") +\n                                address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyLocalVal , addrMode , address , nextArg ) ; symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , null ) ; } else { /*log.fine(\"UNIFY_VAL \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyVal , addrMode , address , nextArg ) ; } } instructions . add ( instruction ) ; } } else if ( j < numOutermostArgs ) { Term nextVar = ( Variable ) nextTerm ; int allocation = ( Integer ) symbolTable . get ( nextVar . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; WAMInstruction instruction ; // If it is register not seen before: get_var. // If it is register seen before: get_val. if ( ! seenRegisters . contains ( allocation ) ) { /*log.fine(\"GET_VAR \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address + \", A\" + j);*/ seenRegisters . add ( allocation ) ; instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetVar , addrMode , address , ( byte ) ( j & 0xff ) ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextVar . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Get ) ; } else { /*log.fine(\"GET_VAL \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address + \", A\" + j);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; } instructions . add ( instruction ) ; } } return instructions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocates stack slots where needed to the variables in a program clause . The algorithm here is fairly complex . [CODESPLIT] private void allocatePermanentProgramRegisters ( Clause clause ) { // A bag to hold variable occurrence counts in. Map < Variable , Integer > variableCountBag = new HashMap < Variable , Integer > ( ) ; // A mapping from variables to the body number in which they appear last. Map < Variable , Integer > lastBodyMap = new HashMap < Variable , Integer > ( ) ; // Holds the variable that are in the head and first clause body argument. Collection < Variable > firstGroupVariables = new HashSet < Variable > ( ) ; // Get the occurrence counts of variables in all clauses after the initial head and first body grouping. // In the same pass, pick out which body variables last occur in. if ( ( clause . getBody ( ) != null ) ) { for ( int i = clause . getBody ( ) . length - 1 ; i >= 1 ; i -- ) { Set < Variable > groupVariables = TermUtils . findFreeVariables ( clause . getBody ( ) [ i ] ) ; // Add all their counts to the bag and update their last occurrence positions. for ( Variable variable : groupVariables ) { Integer count = variableCountBag . get ( variable ) ; variableCountBag . put ( variable , ( count == null ) ? 1 : ( count + 1 ) ) ; if ( ! lastBodyMap . containsKey ( variable ) ) { lastBodyMap . put ( variable , i ) ; } // If the cut level variable is seen, automatically add it to the first group variables, // so that it will be counted as a permanent variable, and assigned a stack slot. This // will only occur for deep cuts, that is where the cut comes after the first group. if ( variable instanceof Cut . CutLevelVariable ) { firstGroupVariables . add ( variable ) ; } } } } // Get the set of variables in the head and first clause body argument. if ( clause . getHead ( ) != null ) { Set < Variable > headVariables = TermUtils . findFreeVariables ( clause . getHead ( ) ) ; firstGroupVariables . addAll ( headVariables ) ; } if ( ( clause . getBody ( ) != null ) && ( clause . getBody ( ) . length > 0 ) ) { Set < Variable > firstArgVariables = TermUtils . findFreeVariables ( clause . getBody ( ) [ 0 ] ) ; firstGroupVariables . addAll ( firstArgVariables ) ; } // Add their counts to the bag, and set their last positions of occurrence as required. for ( Variable variable : firstGroupVariables ) { Integer count = variableCountBag . get ( variable ) ; variableCountBag . put ( variable , ( count == null ) ? 1 : ( count + 1 ) ) ; if ( ! lastBodyMap . containsKey ( variable ) ) { lastBodyMap . put ( variable , 0 ) ; } } // Sort the variables by reverse position of last occurrence. List < Map . Entry < Variable , Integer > > lastBodyList = new ArrayList < Map . Entry < Variable , Integer > > ( lastBodyMap . entrySet ( ) ) ; Collections . sort ( lastBodyList , new Comparator < Map . Entry < Variable , Integer > > ( ) { public int compare ( Map . Entry < Variable , Integer > o1 , Map . Entry < Variable , Integer > o2 ) { return o2 . getValue ( ) . compareTo ( o1 . getValue ( ) ) ; } } ) ; // Holds counts of permanent variable last appearances against the body in which they last occur. int [ ] permVarsRemainingCount = new int [ ( clause . getBody ( ) != null ) ? clause . getBody ( ) . length : 0 ] ; // Search the count bag for all variable occurrences greater than one, and assign them to stack slots. // The variables are examined by reverse position of last occurrence, to ensure that later variables // are assigned to lower permanent allocation slots for environment trimming purposes. for ( Map . Entry < Variable , Integer > entry : lastBodyList ) { Variable variable = entry . getKey ( ) ; Integer count = variableCountBag . get ( variable ) ; int body = entry . getValue ( ) ; if ( ( count != null ) && ( count > 1 ) ) { /*log.fine(\"Variable \" + variable + \" is permanent, count = \" + count);*/ int allocation = ( numPermanentVars ++ & ( 0xff ) ) | ( WAMInstruction . STACK_ADDR << 8 ) ; symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; // Check if the variable is the cut level variable, and cache its stack slot in 'cutLevelVarSlot', so that // the clause compiler knows which variable to use for the get_level instruction. if ( variable instanceof Cut . CutLevelVariable ) { //cutLevelVarSlot = allocation; cutLevelVarSlot = numPermanentVars - 1 ; /*log.fine(\"cutLevelVarSlot = \" + cutLevelVarSlot);*/ } permVarsRemainingCount [ body ] ++ ; } } // Roll up the permanent variable remaining counts from the counts of last position of occurrence and // store the count of permanent variables remaining against the body. int permVarsRemaining = 0 ; for ( int i = permVarsRemainingCount . length - 1 ; i >= 0 ; i -- ) { symbolTable . put ( clause . getBody ( ) [ i ] . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_PERM_VARS_REMAINING , permVarsRemaining ) ; permVarsRemaining += permVarsRemainingCount [ i ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocates stack slots to all free variables in a query clause . [CODESPLIT] private void allocatePermanentQueryRegisters ( Term clause , Map < Byte , Integer > varNames ) { // Allocate local variable slots for all variables in a query. QueryRegisterAllocatingVisitor allocatingVisitor = new QueryRegisterAllocatingVisitor ( symbolTable , varNames , null ) ; PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( allocatingVisitor ) ; TermWalker walker = new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , allocatingVisitor ) ; walker . walk ( clause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gather information about variable counts and positions of occurrence of constants and variable within a clause . [CODESPLIT] private void gatherPositionAndOccurrenceInfo ( Term clause ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; PositionAndOccurrenceVisitor positionAndOccurrenceVisitor = new PositionAndOccurrenceVisitor ( interner , symbolTable , positionalTraverser ) ; positionalTraverser . setContextChangeVisitor ( positionAndOccurrenceVisitor ) ; TermWalker walker = new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , positionAndOccurrenceVisitor ) ; walker . walk ( clause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty prints a compiled predicate . [CODESPLIT] private void displayCompiledPredicate ( Term predicate ) { // Pretty print the clause. StringBuffer result = new StringBuffer ( ) ; PositionalTermVisitor displayVisitor = new WAMCompiledPredicatePrintingVisitor ( interner , symbolTable , result ) ; TermWalkers . positionalWalker ( displayVisitor ) . walk ( predicate ) ; /*log.fine(result.toString());*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty prints a compiled query . [CODESPLIT] private void displayCompiledQuery ( Term query ) { // Pretty print the clause. StringBuffer result = new StringBuffer ( ) ; PositionalTermVisitor displayVisitor = new WAMCompiledQueryPrintingVisitor ( interner , symbolTable , result ) ; TermWalkers . positionalWalker ( displayVisitor ) . walk ( query ) ; /*log.fine(result.toString());*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the specified integer value as an ASCII string into the specified byte buffer . If the integer value is shorted than the specified length the number will be padded with leading zeros so that it fills the required length . If there is insufficient space in the buffer to write the value into then the buffer size is increased using the supplied byte buffer pool . [CODESPLIT] public static ByteBuffer putPaddedInt32AsString ( ByteBuffer buffer , int value , int length ) { // Ensure there is sufficient space in the buffer to hold the result. int charsRequired = BitHackUtils . getCharacterCountInt32 ( value ) ; length = ( charsRequired < length ) ? length : charsRequired ; // Take an explicit index into the buffer to start writing to, as the numbers will be written backwards. int index = buffer . position ( ) + length - 1 ; // Record the start position, to remember if a minus sign was written or not, so that it does not get // overwritten by the zero padding. int start = buffer . position ( ) ; // Advance the buffer position manually, as the characters will be written to specific indexes backwards. buffer . position ( buffer . position ( ) + length ) ; // Take care of the minus sign for negative numbers. if ( value < 0 ) { buffer . put ( MINUS_ASCII ) ; start ++ ; // Stop padding code overwriting minus sign. } else { value = - value ; } // Write the digits least significant to most significant into the buffer. As the number was converted to be // negative the remainders will be negative too. do { int remainder = value % 10 ; value = value / 10 ; buffer . put ( index -- , ( ( byte ) ( ZERO_ASCII - remainder ) ) ) ; } while ( value != 0 ) ; // Write out the padding zeros. while ( index >= start ) { buffer . put ( index -- , ZERO_ASCII ) ; } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the contents of a buffer as a string converting ASCII characters in the buffer into unicode string characters . [CODESPLIT] public static String asString ( ByteBuffer buffer , int length ) { char [ ] chars = new char [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { chars [ i ] = ( char ) buffer . get ( i ) ; } return String . valueOf ( chars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the integer id of the attribute . If the attribute class is finalized this will change the value of this attribute to that of the matched id or raise an exception if no matching id exists . If the attribute class is unfinalized this will change the id value of this attribute within the attribute class to the new id provided that the id has not already been assigned to another attribute value . If it has been assigned to another attribute value then an exception is raised . [CODESPLIT] public void setId ( long id ) { // Find the enumeration node for this enumeration value. EnumerationNode node = null ; // Check if the attribute class has been finalized yet. if ( attributeClass . finalized ) { // Fetch the string value from the attribute class array of finalized values. node = attributeClass . lookupValue [ value ] ; } else { // The attribute class has not been finalized yet. // Fetch the string value from the attribute class list of unfinalized values. node = attributeClass . lookupValueList . get ( value ) ; } // Extract the id from it. long existingId = node . id ; // Do nothing if the new id matches the existing one. if ( id == existingId ) { return ; } // Check if the type is finalized. if ( attributeClass . finalized ) { // Raise an illegal argument exception if the id is not known. EnumeratedStringAttribute newValue = attributeClass . getAttributeFromId ( id ) ; // Otherwise, change the value of this attribute to that of the new id. this . value = newValue . value ; } else { // The type is un-finalized. // Check if another instance of the type already has the id and raise an exception if so. EnumerationNode existingNode = attributeClass . idMap . get ( id ) ; if ( existingNode != null ) { throw new IllegalArgumentException ( \"The id value, \" + id + \", cannot be set because another instance of this type with that \" + \"id already exists.\" ) ; } // Assign it to this instance if the type is unfinalized. Also removing the old id mapping from the id // map and replacing it with the new one. node . id = id ; attributeClass . idMap . remove ( existingId ) ; attributeClass . idMap . put ( id , node ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the string value of a string attribute . [CODESPLIT] public String getStringValue ( ) { // Check if the attribute class has been finalized yet. if ( attributeClass . finalized ) { // Fetch the string value from the attribute class. return attributeClass . lookupValue [ value ] . label ; } else { return attributeClass . lookupValueList . get ( value ) . label ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified string as the value of this attribute . The value to set must be a legitimate member of this attributes type when the type has been finalized . If the type has yet to be finalized then the new value is added to the set of possible values for the type . [CODESPLIT] public void setStringValue ( String value ) throws IllegalArgumentException { Byte b = attributeClass . lookupByte . get ( value ) ; // Check if the value is not already a memeber of the attribute class. if ( b == null ) { // Check if the attribute class has been finalized yet. if ( attributeClass . finalized ) { throw new IllegalArgumentException ( \"The value to set, \" + value + \", is not already a member of the finalized EnumeratedStringType, \" + attributeClass . attributeClassName + \".\" ) ; } else { // Add the new value to the attribute class. Delegate to the factory to do this so that strings are // interned and so on. EnumeratedStringAttribute newAttribute = attributeClass . createStringAttribute ( value ) ; b = newAttribute . value ; } } // Set the new value as the value of this attribute. this . value = b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the next sentence from the current token source . [CODESPLIT] public Sentence < Term > parse ( ) throws SourceCodeException { try { return new SentenceImpl < Term > ( parser . termSentence ( ) ) ; } catch ( SourceCodeException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a Lojix term and invoked appropriate methods on the content handler to describe its structure and contents to it . [CODESPLIT] private void read ( Term term ) { if ( term . isNumber ( ) ) { NumericType numericType = ( NumericType ) term ; if ( numericType . isInteger ( ) ) { IntLiteral jplInteger = ( IntLiteral ) term ; getContentHandler ( ) . startIntegerTerm ( jplInteger . longValue ( ) ) ; } else if ( numericType . isFloat ( ) ) { FloatLiteral jplFloat = ( FloatLiteral ) term ; getContentHandler ( ) . startFloatTerm ( jplFloat . doubleValue ( ) ) ; } } else if ( term . isVar ( ) ) { Variable var = ( Variable ) term ; getContentHandler ( ) . startVariable ( interner . getVariableName ( var . getName ( ) ) ) ; } else if ( term . isAtom ( ) ) { Functor atom = ( Functor ) term ; getContentHandler ( ) . startAtom ( interner . getFunctorName ( atom . getName ( ) ) ) ; } else if ( term . isCompound ( ) ) { Functor functor = ( Functor ) term ; getContentHandler ( ) . startCompound ( ) ; getContentHandler ( ) . startAtom ( interner . getFunctorName ( functor . getName ( ) ) ) ; for ( com . thesett . aima . logic . fol . Term child : functor . getArguments ( ) ) { read ( child ) ; } getContentHandler ( ) . endCompound ( ) ; } else { throw new IllegalStateException ( \"Unrecognized Lojix term: \" + term ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public final MicrodataItem getItem ( String type ) { List < MicrodataItem > items = getItems ( type ) ; if ( items . isEmpty ( ) ) { throw new MicrodataItemNotFoundException ( newUrl ( type ) ) ; } return items . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the named class exists and is loadable . [CODESPLIT] public static boolean classExistsAndIsLoadable ( String className ) { try { Class . forName ( className ) ; return true ; } catch ( ClassNotFoundException e ) { // Exception noted and ignored. e = null ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the named class exists and is loadable and is a sub - type of the specified class . [CODESPLIT] public static boolean isSubTypeOf ( Class parent , String className ) { try { Class cls = Class . forName ( className ) ; return parent . isAssignableFrom ( cls ) ; } catch ( ClassNotFoundException e ) { // Exception noted and ignored. e = null ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the named child class is the same type or a sub - type of the named parent class . [CODESPLIT] public static boolean isSubTypeOf ( String parent , String child ) { try { return isSubTypeOf ( Class . forName ( parent ) , Class . forName ( child ) ) ; } catch ( ClassNotFoundException e ) { // Exception noted so can be ignored. e = null ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that the child class is the same type or a sub - type of the parent class . [CODESPLIT] public static boolean isSubTypeOf ( Class parentClass , Class childClass ) { try { // Check that the child class can be cast as a sub-type of the parent. childClass . asSubclass ( parentClass ) ; return true ; } catch ( ClassCastException e ) { // Exception noted so can be ignored. e = null ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the Class object for a named class . [CODESPLIT] public static Class < ? > forName ( String className ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new ReflectionUtilsException ( \"ClassNotFoundException whilst finding class: \" + className + \".\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of a Class instantiated through its no - args constructor . [CODESPLIT] public static < T > T newInstance ( Class < T > cls ) { try { return cls . newInstance ( ) ; } catch ( InstantiationException e ) { throw new ReflectionUtilsException ( \"InstantiationException whilst instantiating class.\" , e ) ; } catch ( IllegalAccessException e ) { throw new ReflectionUtilsException ( \"IllegalAccessException whilst instantiating class.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a constuctor with the specified arguments . [CODESPLIT] public static < T > T newInstance ( Constructor < T > constructor , Object [ ] args ) { try { return constructor . newInstance ( args ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a named method on an object with a specified set of parameters any Java access modifier are overridden . [CODESPLIT] public static Object callMethodOverridingIllegalAccess ( Object o , String method , Object [ ] params , Class [ ] paramClasses ) { // Get the objects class. Class cls = o . getClass ( ) ; // Get the classes of the parameters. /*Class[] paramClasses = new Class[params.length];\n\n        for (int i = 0; i < params.length; i++)\n        {\n            paramClasses[i] = params[i].getClass();\n        }*/ try { // Try to find the matching method on the class. Method m = cls . getDeclaredMethod ( method , paramClasses ) ; // Make it accessible. m . setAccessible ( true ) ; // Invoke it with the parameters. return m . invoke ( o , params ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a named method on an object with a specified set of parameters . [CODESPLIT] public static Object callMethod ( Object o , String method , Object [ ] params ) { // Get the objects class. Class cls = o . getClass ( ) ; // Get the classes of the parameters. Class [ ] paramClasses = new Class [ params . length ] ; for ( int i = 0 ; i < params . length ; i ++ ) { paramClasses [ i ] = params [ i ] . getClass ( ) ; } try { // Try to find the matching method on the class. Method m = cls . getMethod ( method , paramClasses ) ; // Invoke it with the parameters. return m . invoke ( o , params ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calls a named static method on a class with a specified set of parameters . [CODESPLIT] public static Object callStaticMethod ( Method method , Object [ ] params ) { try { return method . invoke ( null , params ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the constructor of a class that takes the specified set of arguments if any matches . If no matching constructor is found then a runtime exception is raised . [CODESPLIT] public static < T > Constructor < T > getConstructor ( Class < T > cls , Class [ ] args ) { try { return cls . getConstructor ( args ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the argument types of all setter methods on a bean for a given property name . For a method to be a setter method it must have a void return type be public and accept only a single argument . Its name must be set followed by the property name . [CODESPLIT] public static Set < Class > findMatchingSetters ( Class obClass , String propertyName ) { /*log.fine(\"private Set<Class> findMatchingSetters(Object ob, String propertyName): called\");*/ Set < Class > types = new HashSet < Class > ( ) ; // Convert the first letter of the property name to upper case to match against the upper case version of // it that will be in the setter method name. For example the property test will have a setter method called // setTest. String upperPropertyName = Character . toUpperCase ( propertyName . charAt ( 0 ) ) + propertyName . substring ( 1 ) ; // Scan through all the objects methods. Method [ ] methods = obClass . getMethods ( ) ; for ( Method nextMethod : methods ) { // Get the next method. /*log.fine(\"nextMethod = \" + nextMethod.getName());*/ // Check if a method has the correct name, accessibility and the correct number of arguments to be a setter // method for the property. String methodName = nextMethod . getName ( ) ; if ( methodName . equals ( \"set\" + upperPropertyName ) && Modifier . isPublic ( nextMethod . getModifiers ( ) ) && ( nextMethod . getParameterTypes ( ) . length == 1 ) ) { /*log.fine(methodName + \" is a valid setter method for the property \" + propertyName +\n                        \" with argument of type \" + nextMethod.getParameterTypes()[0]);*/ // Add its argument type to the array of setter types. types . add ( nextMethod . getParameterTypes ( ) [ 0 ] ) ; } } return types ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the table . [CODESPLIT] public void renderTable ( ) { for ( int i = 0 ; i < tableModel . getRowCount ( ) ; i ++ ) { int colOffset = 0 ; for ( int j = 0 ; j < tableModel . getColumnCount ( ) ; j ++ ) { // Print the contents of the table cell. String valueToPrint = tableModel . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? \"\" : valueToPrint ; gridModel . insert ( valueToPrint , colOffset , i ) ; // Pad spaces up to the column width if the contents are shorted. Integer maxColumnSize = tableModel . getMaxColumnSize ( j ) ; int spaces = maxColumnSize - valueToPrint . length ( ) ; while ( spaces > 0 ) { gridModel . insert ( \" \" , colOffset + valueToPrint . length ( ) + spaces -- - 1 , i ) ; } // Shift to the next column. colOffset += maxColumnSize ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private URL getAction ( ) { String action = element . getAttribute ( \"action\" ) ; if ( action . isEmpty ( ) ) { action = driver . getCurrentUrl ( ) ; } return newUrlOrNull ( action ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps a java . util . concurrent . BlockingQueue as a { @link com . thesett . common . util . concurrent . BlockingQueue } implementation . [CODESPLIT] public static < E > BlockingQueue < E > getBlockingQueue ( java . util . concurrent . BlockingQueue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps a java . util . concurrent . BlockingQueue as a { @link com . thesett . common . util . concurrent . BlockingQueue } implementation . [CODESPLIT] public static < E > SizeableBlockingQueue < E > getSizeableBlockingQueue ( java . util . concurrent . BlockingQueue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps queue as a sizeable atomically counted queue as per the { @link #getSizeableQueue } and { @link #getAtomicCountedQueue } methods . [CODESPLIT] public static < E extends Sizeable > SizeableQueue < E > getAtomicCountedSizeableQueue ( java . util . Queue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , true , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a transactional queue that delays all queue manipulation operations until the transaction is committed or erases them if it is rolled back . [CODESPLIT] public static < E > Queue < E > getTransactionalQueue ( java . util . Queue < E > queue ) { return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , true , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a transactional requeue that delays all queue manipulation operations until the transaction is committed or erases them if it is rolled back . As this is a requeue the requeue buffer may be examined directly and the queue fully supports browsing with iterators . [CODESPLIT] public static < E > Queue < E > getTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { return new WrapperQueue < E > ( queue , requeue , true , false , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps queue as a sizeable transactional requeue as per the { @link #getSizeableQueue } and { @link #getTransactionalReQueue } methods . [CODESPLIT] public static < E extends Sizeable > SizeableQueue < E > getSizeableTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { return new WrapperQueue < E > ( queue , requeue , true , true , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wraps queue as a sizeable atomically counted queue transactional requeue as per the { @link #getSizeableQueue } { @link #getAtomicCountedQueue } and { @link #getTransactionalReQueue } methods . [CODESPLIT] public static < E extends Sizeable > Queue < E > getAtomicCountedSizeableTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { return new WrapperQueue < E > ( queue , requeue , true , true , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the type of a specified object . [CODESPLIT] public static Type getTypeFromObject ( Object o ) { // Check if the object is null, in which case its type cannot be derived. if ( o == null ) { return new UnknownType ( ) ; } // Check if the object is an attribute a and get its type that way if possible. if ( o instanceof Attribute ) { return ( ( Attribute ) o ) . getType ( ) ; } // Return an approproate Type for the java primitive, wrapper or class type of the argument. return new JavaType ( o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the search clearing out the queue and setting it to contain just the start state node . [CODESPLIT] public void reset ( ) { // Clear out the start states. startStates . clear ( ) ; enqueuedOnce = false ; // Reset the queue to a fresh empty queue. queue = createQueue ( ) ; // Clear the goal predicate. goalPredicate = null ; // Reset the maximum steps limit maxSteps = 0 ; // Reset the number of steps taken searchSteps = 0 ; // Reset the repeated state filter if there is one. if ( repeatedStateFilter != null ) { repeatedStateFilter . reset ( ) ; } // Reset the search alogorithm if it requires resettting. searchAlgorithm . reset ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This logic enqueues all the start states calling the { @link #createSearchNode } method that concrete sub - classes implement to specify the search node type . If there is a repeated state filter set up then this is attached to the search nodes . This is called at the start of the search method to set up the queue into a state which is ready for the search algorithm . [CODESPLIT] public Queue < SearchNode < O , T > > enqueueStartStates ( Collection < T > startStates ) { // Check that there are some start states if ( ! startStates . isEmpty ( ) ) { // Only enqueue the start states if they have not already been enqueued. if ( ! enqueuedOnce ) { // Enqueue all the start states for ( T nextStartState : startStates ) { // If the goal predicate has not been defined, try to set up the default from the initial search // states. if ( goalPredicate == null ) { goalPredicate = nextStartState . getDefaultGoalPredicate ( ) ; } // Make search nodes out of the start states using the abstract search node creation method, // subclasses override this to create different kinds of search node. SearchNode newStartNode = createSearchNode ( nextStartState ) ; // Check if a repeated state filter has been applied and attach it to the start node if so. if ( repeatedStateFilter != null ) { // Attach it to the start node. newStartNode . setRepeatedStateFilter ( repeatedStateFilter ) ; } // Insert the new start search node onto the queue. queue . offer ( newStartNode ) ; } } } else { // There are no start states so raise an exception because the search cannot be run without a start state. throw new IllegalStateException ( \"Cannot start the search because there are no start states defined. \" + \"Queue searches require some start states.\" , null ) ; } // Check that a goal predicate is set up. if ( goalPredicate == null ) { throw new IllegalStateException ( \"Cannot start the search because there is no goal predicate.\" , null ) ; } // Set the enqueuedOnce flag to indicate that the start states have already been enqueued. enqueuedOnce = true ; return queue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the general queue search . The basic algorithm is simple : take the next element from the queue and goal test it . If it is a goal then return it and stop the search . If it is not a goal then expand its successor states and enqueue them and then repeat the procedure . [CODESPLIT] public SearchNode < O , T > findGoalPath ( ) throws SearchNotExhaustiveException { // Delegate the search to the pluggable search algorithm. return searchAlgorithm . search ( this , startStates , maxSteps , searchSteps ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Perform the search . This can be called multiple times to get successive results where more than one goal can be found if the algorithm supports this . In this case it should return null once no more goals can be found . [CODESPLIT] public T search ( ) throws SearchNotExhaustiveException { SearchNode < O , T > path = findGoalPath ( ) ; if ( path != null ) { return path . getState ( ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor isOp = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; // Evaluate the second argument as a fully instantiated numeric value. Term expressionValue = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 1 ) ) ; // This is used to record variables bound during the unification, so that they may be undone if the resolution // state is backtracked over. List < Variable > boundVariables = new LinkedList < Variable > ( ) ; // Unify against the LHS. boolean matched = state . getUnifier ( ) . unifyInternal ( isOp . getArgument ( 0 ) , expressionValue , boundVariables , boundVariables ) ; for ( Variable binding : boundVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } return matched ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new int range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , int min , int max ) { // Ensure that min is less than or equal to max. if ( min > max ) { throw new IllegalArgumentException ( \"'min' must be less than or equal to 'max'.\" ) ; } synchronized ( INT_RANGE_TYPES ) { // Add the newly created type to the map of all types. IntRangeType newType = new IntRangeType ( name , min , max ) ; // Ensure that the named type does not already exist, unless it has an identical definition already, in which // case the old definition can be re-used and the new one discarded. IntRangeType oldType = INT_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( \"The type '\" + name + \"' already exists and cannot be redefined.\" ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { INT_RANGE_TYPES . put ( name , newType ) ; return newType ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public Set < Integer > getAllPossibleValuesSet ( ) throws InfiniteValuesException { Set < Integer > results = new HashSet < Integer > ( ) ; for ( int i = minValue ; i <= maxValue ; i ++ ) { results . add ( i ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < Integer > getAllPossibleValuesIterator ( ) throws InfiniteValuesException { return new Iterator < Integer > ( ) { int current = minValue ; /** {@inheritDoc} */ public boolean hasNext ( ) { return current <= maxValue ; } /** {@inheritDoc} */ public Integer next ( ) { if ( hasNext ( ) ) { int result = current ; current ++ ; return result ; } else { throw new NoSuchElementException ( \"No more elements less than or equal to max.\" ) ; } } /** {@inheritDoc} */ public void remove ( ) { throw new UnsupportedOperationException ( \"This iterator does not support 'remove'.\" ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the arithmetic operator on its two numeric arguments . [CODESPLIT] protected NumericType evaluate ( NumericType firstNumber , NumericType secondNumber ) { // If either of the arguments is a real number, then use real number arithmetic, otherwise use integer arithmetic. if ( firstNumber . isInteger ( ) && secondNumber . isInteger ( ) ) { int n1 = firstNumber . intValue ( ) ; int n2 = secondNumber . intValue ( ) ; int result = 1 ; for ( int i = 0 ; i < n2 ; i ++ ) { result *= n1 ; } return new IntLiteral ( result ) ; } else { return new DoubleLiteral ( Math . pow ( firstNumber . doubleValue ( ) , secondNumber . doubleValue ( ) ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { // Flatten the head goal on the disjunction operator to produce a series of choice points. Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; disjuncts = TermUtils . flattenTerm ( goalTerm , Functor . class , state . getInterner ( ) . internFunctorName ( \";\" , 2 ) ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void createContinuationStates ( ResolutionState state ) { for ( Functor disjunct : disjuncts ) { BuiltInFunctor newGoal = state . getBuiltInTransform ( ) . apply ( disjunct ) ; newGoal . setParentChoicePointState ( state ) ; state . createContinuationStatesForGoal ( newGoal ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public boolean areLinked ( SqlTable table1 , SqlTable table2 ) { return predecessorRelation . get ( table1 . getTableName ( ) ) . containsKey ( table2 . getTableName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public DimensionTable getDimensionByName ( String dimensionName , String tzNameAlias ) { DimensionTable dimensionTable ; if ( StringUtils . isBlank ( tzNameAlias ) || ( StringUtils . isNotBlank ( tzNameAlias ) && tzNameAlias . equals ( getDefaultTimezone ( ) ) ) ) { dimensionTable = dimensions . get ( dimensionName . toUpperCase ( ) ) ; } else { if ( ! isTimeZoneSupported ( tzNameAlias ) ) { LOG . error ( tzNameAlias + \" TZ is not supported, do not consider it.\" ) ; dimensionTable = dimensions . get ( dimensionName . toUpperCase ( ) ) ; } else { String tzName = tzNamesAliases . get ( tzNameAlias ) ; dimensionTable = alternateDimensions . get ( Pair . of ( dimensionName . toUpperCase ( ) , tzName ) ) ; if ( dimensionTable == null ) { // No alternateTable for this dimension/tz pair dimensionTable = dimensions . get ( dimensionName . toUpperCase ( ) ) ; } } } if ( dimensionTable == null ) { throw new IllegalArgumentException ( \"Invalid SqlTable for the dimension: \" + dimensionName ) ; } return dimensionTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public List < AbstractSqlColumn > getMeasuresColumn ( ) { return Collections . unmodifiableList ( Lists . newArrayList ( factTable . getMeasuresColumn ( ) . values ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Optional < AbstractSqlColumn > getMeasuresByName ( String informationName ) { for ( AbstractSqlColumn column : factTable . getMeasuresColumn ( ) . values ( ) ) { if ( column . getBusinessName ( ) . equalsIgnoreCase ( informationName ) ) { return Optional . of ( column ) ; } } return Optional . absent ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public AbstractSqlColumn getInformationColumn ( DimensionTable dimension , String informationName ) { final AbstractSqlColumn sqlTableColumn = dimension . getSqlTableColumnByInformationName ( informationName ) ; if ( sqlTableColumn == null ) { throw new IllegalArgumentException ( \"Invalid sqlTableColumn for the informationName: \" + informationName ) ; } return sqlTableColumn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public boolean isValidDimension ( String dimensionName , String informationName ) { if ( StringUtils . isNotBlank ( dimensionName ) ) { DimensionTable dim = dimensions . get ( dimensionName . toUpperCase ( ) ) ; if ( dim == null ) { return false ; } if ( StringUtils . isBlank ( informationName ) ) { return true ; } if ( dim . getSqlTableColumnByInformationName ( informationName . toUpperCase ( ) ) != null ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public boolean isMandatoryDimension ( String dimensionName ) { if ( isValidDimension ( dimensionName , null ) ) { return mandatoryDimensionNames . contains ( dimensionName . toUpperCase ( Locale . ENGLISH ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public ColumnDataType getInformationType ( String dimensionName , String informationName ) { if ( StringUtils . isNotBlank ( dimensionName ) ) { DimensionTable dim = dimensions . get ( dimensionName . toUpperCase ( ) ) ; if ( dim == null ) { throw new IllegalArgumentException ( \"Unknown dimension named \" + dimensionName + \".\" ) ; } if ( StringUtils . isBlank ( informationName ) ) { return dim . getDefaultSearchColumn ( ) . getColumnType ( ) ; } AbstractSqlColumn information = dim . getSqlTableColumnByInformationName ( informationName ) ; if ( information == null ) { throw new IllegalArgumentException ( \"Unknown information named \" + informationName + \" for dimension \" + dimensionName + \".\" ) ; } return information . getColumnType ( ) ; } throw new IllegalArgumentException ( \"Dimension name can't be null or blank\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new supported tz . Add one aliase with the same name [CODESPLIT] public void addSupportedTZ ( String tzName ) { if ( ! StringUtils . isBlank ( tzName ) && ! tzNamesAliases . containsKey ( tzName . trim ( ) ) ) { tzNamesAliases . put ( tzName . trim ( ) , tzName . trim ( ) ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"Endpoint \" + this . getEndPointName ( ) + \" - add support of TZ: \" + tzName ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Timezone is case sensitive [CODESPLIT] public void addTZAlternateDimension ( String orignalDimensionName , DimensionTable alternateDimension , String tzName ) { addSupportedTZ ( tzName ) ; if ( tzNamesAliases . containsValue ( tzName ) ) { sqlTables . put ( alternateDimension . getTableName ( ) , alternateDimension ) ; alternateDimensions . put ( Pair . of ( orignalDimensionName . toUpperCase ( ) , tzName ) , alternateDimension ) ; } else { LOG . error ( \"Unsuported timezone: \" + tzName ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a dimension as mandatory . Mandatory dimension names are stored in upper case . [CODESPLIT] public void addDimension ( DimensionTable table , boolean mandatory ) { sqlTables . put ( table . getTableName ( ) , table ) ; dimensions . put ( table . getDimensionName ( ) . toUpperCase ( ) , table ) ; if ( mandatory ) { mandatoryDimensionNames . add ( table . getDimensionName ( ) . toUpperCase ( Locale . ENGLISH ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build the configuration links ( ie Foreigns key ) . Checks the validity of the configuration . [CODESPLIT] public Collection < Error > buildAndValidateConfig ( ) { Collection < Error > returnValue = new ArrayList < Error > ( ) ; // Check default TZ if ( defaultTimezone == null ) { returnValue . add ( new Error ( \"No default Timezone configured\" ) ) ; } for ( Pair < Pair < String , String > , Pair < String , String > > fkRelationship : fkRelationshipSet ) { Optional < PhysicalSqlColumn > left = getColumnByPair ( fkRelationship . getLeft ( ) ) ; Optional < PhysicalSqlColumn > right = getColumnByPair ( fkRelationship . getRight ( ) ) ; if ( ! left . isPresent ( ) ) { returnValue . add ( new Error ( \"Column \" + fkRelationship . getLeft ( ) . getRight ( ) + \" in table \" + fkRelationship . getLeft ( ) . getLeft ( ) + \" doesn't exist.\" ) ) ; } else if ( ! right . isPresent ( ) ) { returnValue . add ( new Error ( \"Column \" + fkRelationship . getRight ( ) . getRight ( ) + \" in table \" + fkRelationship . getRight ( ) . getLeft ( ) + \" doesn't exist.\" ) ) ; } else { buildSqlForeignKey ( left . get ( ) , right . get ( ) ) ; } } // Check Alternate Tables for ( Entry < Pair < String , String > , DimensionTable > entry : alternateDimensions . entrySet ( ) ) { DimensionTable dim = dimensions . get ( entry . getKey ( ) . getLeft ( ) ) ; if ( dim == null ) { returnValue . add ( new Error ( \"Original dimension \" + entry . getKey ( ) . getLeft ( ) + \" does not exist.\" ) ) ; } else { if ( ! dim . isEquivalent ( entry . getValue ( ) , returnValue ) ) { returnValue . add ( new Error ( \"Dimension \" + entry . getValue ( ) . getDimensionName ( ) + \" is not equivalent to \" + dim . getDimensionName ( ) + \".\" ) ) ; } } } return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public boolean isValidMeasure ( String name ) { for ( AbstractSqlColumn column : factTable . getMeasuresColumn ( ) . values ( ) ) { if ( column . getBusinessName ( ) . equals ( name ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the set of free variables in a term . [CODESPLIT] public static Set < Variable > findFreeVariables ( Term query ) { QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the set of free and non - anonymous variables in a term . This is the set of variables that a user query usually wants to be made aware of . [CODESPLIT] public static Set < Variable > findFreeNonAnonymousVariables ( Term query ) { QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeNonAnonymousVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens a sequence of terms as a symbol seperated argument list . Terms that have been parsed as a bracketed expressions will not be flattened . All of the terms in the list must sub sub - classes of a specified super class . This is usefull for example when parsing a sequence of functors in a clause body in order to check that all of the body members really are functors and not just terms . [CODESPLIT] public static < T extends Term > List < T > flattenTerm ( Term term , Class < T > superClass , String symbolToFlattenOn , VariableAndFunctorInterner interner ) throws SourceCodeException { List < T > terms = new LinkedList < T > ( ) ; // Used to hold the next term to examine as operators are flattened. Term nextTerm = term ; // Used to indicate when there are no more operators to flatten. boolean mayBeMoreCommas = true ; // Get the functor name of the symbol to flatten on. int symbolName = interner . internFunctorName ( symbolToFlattenOn , 2 ) ; // Walk down the terms matching symbols and flattening them into a list of terms. while ( mayBeMoreCommas ) { if ( ! nextTerm . isBracketed ( ) && ( nextTerm instanceof Functor ) && ( symbolName == ( ( ( Functor ) nextTerm ) . getName ( ) ) ) ) { Functor op = ( Functor ) nextTerm ; Term termToExtract = op . getArgument ( 0 ) ; if ( superClass . isInstance ( termToExtract ) ) { terms . add ( superClass . cast ( termToExtract ) ) ; nextTerm = op . getArgument ( 1 ) ; } else { throw new SourceCodeException ( \"The term \" + termToExtract + \" is expected to extend \" + superClass + \" but does not.\" , null , null , null , termToExtract . getSourceCodePosition ( ) ) ; } } else { if ( superClass . isInstance ( nextTerm ) ) { terms . add ( superClass . cast ( nextTerm ) ) ; mayBeMoreCommas = false ; } else { throw new SourceCodeException ( \"The term \" + nextTerm + \" is expected to extend \" + superClass + \" but does not.\" , null , null , null , nextTerm . getSourceCodePosition ( ) ) ; } } } return terms ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Flattens a sequence of terms as a symbol seperated argument list . Terms that have been parsed as a bracketed expressions will not be flattened . All of the terms in the list must sub sub - classes of a specified super class . This is usefull for example when parsing a sequence of functors in a clause body in order to check that all of the body members really are functors and not just terms . [CODESPLIT] public static < T extends Term > List < T > flattenTerm ( Term term , Class < T > superClass , int internedName ) { List < T > terms = new LinkedList < T > ( ) ; // Used to hold the next term to examine as operators are flattened. Term nextTerm = term ; // Used to indicate when there are no more operators to flatten. boolean mayBeMore = true ; // Walk down the terms matching symbols and flattening them into a list of terms. while ( mayBeMore ) { if ( ! nextTerm . isBracketed ( ) && ( nextTerm instanceof Functor ) && ( internedName == ( ( ( Functor ) nextTerm ) . getName ( ) ) ) ) { Functor op = ( Functor ) nextTerm ; Term termToExtract = op . getArgument ( 0 ) ; if ( superClass . isInstance ( termToExtract ) ) { terms . add ( superClass . cast ( termToExtract ) ) ; nextTerm = op . getArgument ( 1 ) ; } else { throw new IllegalStateException ( \"The term \" + termToExtract + \" is expected to extend \" + superClass + \" but does not.\" ) ; } } else { if ( superClass . isInstance ( nextTerm ) ) { terms . add ( superClass . cast ( nextTerm ) ) ; mayBeMore = false ; } else { throw new IllegalStateException ( \"The term \" + nextTerm + \" is expected to extend \" + superClass + \" but does not.\" ) ; } } } return terms ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a term into a clause . The term must be a functor . If it is a functor corresponding to the : - symbol it is a clause with a head and a body . If it is a functor corresponding to the ? - symbol it is a query clause with no head but must have a body . If it is neither but is a functor it is interpreted as a program clause : - with no body that is a fact . [CODESPLIT] public static Clause convertToClause ( Term term , VariableAndFunctorInterner interner ) throws SourceCodeException { // Check if the top level term is a query, an implication or neither and reduce the term into a clause // accordingly. if ( term instanceof OpSymbol ) { OpSymbol symbol = ( OpSymbol ) term ; if ( \":-\" . equals ( symbol . getTextName ( ) ) ) { List < Functor > flattenedArgs = flattenTerm ( symbol . getArgument ( 1 ) , Functor . class , \",\" , interner ) ; return new Clause < Functor > ( ( Functor ) symbol . getArgument ( 0 ) , flattenedArgs . toArray ( new Functor [ flattenedArgs . size ( ) ] ) ) ; } else if ( \"?-\" . equals ( symbol . getTextName ( ) ) ) { List < Functor > flattenedArgs = flattenTerm ( symbol . getArgument ( 0 ) , Functor . class , \",\" , interner ) ; return new Clause < Functor > ( null , flattenedArgs . toArray ( new Functor [ flattenedArgs . size ( ) ] ) ) ; } } if ( term instanceof Functor ) { return new Clause < Functor > ( ( Functor ) term , null ) ; } else { throw new SourceCodeException ( \"Only functors can for a clause body, not \" + term + \".\" , null , null , null , term . getSourceCodePosition ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two heuristic search nodes by their heuristic values . [CODESPLIT] public int compare ( SearchNode object1 , SearchNode object2 ) { float h1 = ( ( HeuristicSearchNode ) object1 ) . getH ( ) ; float h2 = ( ( HeuristicSearchNode ) object2 ) . getH ( ) ; return ( h1 > h2 ) ? 1 : ( ( h1 < h2 ) ? - 1 : 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a text file as a string . [CODESPLIT] public static String readFileAsString ( String filename ) { BufferedInputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( filename ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalStateException ( e ) ; } return readStreamAsString ( is ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads a text file as a string . [CODESPLIT] public static String readFileAsString ( File file ) { BufferedInputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( file ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalStateException ( e ) ; } return readStreamAsString ( is ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an object using its toString method to the named file . The object may optionally be appended to the file or may overwrite it . [CODESPLIT] public static void writeObjectToFile ( String outputFileName , Object toWrite , boolean append ) { // Open the output file. Writer resultWriter ; try { resultWriter = new FileWriter ( outputFileName , append ) ; } catch ( IOException e ) { throw new IllegalStateException ( \"Unable to open the output file '\" + outputFileName + \"' for writing.\" , e ) ; } // Write the object into the output file. try { resultWriter . write ( toWrite . toString ( ) ) ; resultWriter . flush ( ) ; resultWriter . close ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( \"There was an error whilst writing to the output file '\" + outputFileName + \"'.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the contents of a reader one line at a time until the end of stream is encountered and returns all together as a string . [CODESPLIT] private static String readStreamAsString ( BufferedInputStream is ) { try { byte [ ] data = new byte [ 4096 ] ; StringBuffer inBuffer = new StringBuffer ( ) ; int read ; while ( ( read = is . read ( data ) ) != - 1 ) { String s = new String ( data , 0 , read ) ; inBuffer . append ( s ) ; } return inBuffer . toString ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the specified element to the end of this list ( optional operation ) . [CODESPLIT] public boolean add ( T o ) { boolean result = super . add ( o ) ; sizeOf += ( result ) ? o . sizeof ( ) : 0 ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the first occurrence in this list of the specified element ( optional operation ) . If this list does not contain the element it is unchanged . More formally removes the element with the lowest index i such that <tt > ( o == null ? get ( i ) == null : o . equals ( get ( i ))) < / tt > ( if such an element exists ) . [CODESPLIT] public boolean remove ( Object o ) { boolean result = super . remove ( o ) ; sizeOf -= ( ( o instanceof Sizeable ) && result ) ? ( ( Sizeable ) o ) . sizeof ( ) : 0 ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the specified element at the specified position in this list ( optional operation ) . Shifts the element currently at that position ( if any ) and any subsequent elements to the right ( adds one to their indices ) . [CODESPLIT] public void add ( int index , T element ) { super . add ( index , element ) ; sizeOf += element . sizeof ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the element at the specified position in this list ( optional operation ) . Shifts any subsequent elements to the left ( subtracts one from their indices ) . Returns the element that was removed from the list . [CODESPLIT] public T remove ( int index ) { T result = super . remove ( index ) ; sizeOf += ( result != null ) ? result . sizeof ( ) : 0 ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends all of the elements in the specified collection to the end of this list in the order that they are returned by the specified collection s iterator ( optional operation ) . The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress . ( Note that this will occur if the specified collection is this list and it s nonempty . ) [CODESPLIT] public boolean addAll ( Collection < ? extends T > c ) { if ( c instanceof Sizeable ) { sizeOf += ( ( Sizeable ) c ) . sizeof ( ) ; } return super . addAll ( c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterClause ( Clause clause ) { if ( clause instanceof WAMCompiledQuery ) { WAMOptimizeableListing query = ( WAMCompiledQuery ) clause ; for ( WAMInstruction instruction : query . getUnoptimizedInstructions ( ) ) { addLineToRow ( instruction . toString ( ) ) ; nextRow ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterPredicate ( Predicate predicate ) { if ( predicate instanceof WAMCompiledPredicate ) { WAMOptimizeableListing compiledPredicate = ( WAMCompiledPredicate ) predicate ; for ( WAMInstruction instruction : compiledPredicate . getUnoptimizedInstructions ( ) ) { addLineToRow ( instruction . toString ( ) ) ; nextRow ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the correct type of search nodes for this search . This search uses heuristic search nodes . [CODESPLIT] public SearchNode < O , T > createSearchNode ( T state ) { return new HeuristicSearchNode < O , T > ( state , heuristic ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a built - in replacement transformation to functors . If the functor matches built - in a { @link BuiltInFunctor } is created with a mapping to the functors built - in implementation and the functors arguments are copied into this new functor . If the functor does not match a built - in it is returned unmodified . [CODESPLIT] public BuiltInFunctor apply ( Functor functor ) { FunctorName functorName = interner . getFunctorFunctorName ( functor ) ; Class < ? extends BuiltInFunctor > builtInClass ; if ( builtIns . containsKey ( functorName ) ) { builtInClass = builtIns . get ( functorName ) ; } else { builtInClass = DefaultBuiltIn . class ; } return ReflectionUtils . newInstance ( ReflectionUtils . getConstructor ( builtInClass , new Class [ ] { Functor . class } ) , new Object [ ] { functor } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a sequence of spaces to indent debugging output with . [CODESPLIT] public String generateTraceIndent ( int delta ) { if ( ! useIndent ) { return \"\" ; } else { if ( delta >= 1 ) { indentStack . push ( delta ) ; } else if ( delta < 0 ) { indentStack . pop ( ) ; } StringBuffer result = new StringBuffer ( ) ; traceIndent += ( delta < 0 ) ? delta : 0 ; for ( int i = 0 ; i < traceIndent ; i ++ ) { result . append ( \" \" ) ; } traceIndent += ( delta > 0 ) ? delta : 0 ; return result . toString ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { // Used to build up the results in. SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Generate the call or tail-call instructions, followed by the call address, which is f_n of the // called program. if ( isLastBody ) { // Deallocate the stack frame at the end of the clause, but prior to calling the last // body predicate. // This is not required for chain rules, as they do not need a stack frame. if ( ! chainRule ) { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; } instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Execute , interner . getFunctorFunctorName ( expression ) ) ) ; } else { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Call , ( byte ) ( permVarsRemaining & 0xff ) , interner . getFunctorFunctorName ( expression ) ) ) ; } return instructions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { // Used to build up the results in. SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Allocate argument registers on the body, to all functors as outermost arguments. // Allocate temporary registers on the body, to all terms not already allocated. /*if (!isFirstBody)\n        {\n            lastAllocatedRegister = 0;\n        }*/ allocateArgumentRegisters ( expression ) ; allocateTemporaryRegisters ( expression ) ; // Loop over all of the arguments to the outermost functor. int numOutermostArgs = expression . getArity ( ) ; for ( int j = 0 ; j < numOutermostArgs ; j ++ ) { Term nextOutermostArg = expression . getArgument ( j ) ; int allocation = ( Integer ) symbolTable . get ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; // On the first occurrence of a variable output a put_var. // On a subsequent variable occurrence output a put_val. if ( nextOutermostArg . isVar ( ) && ! seenRegisters . contains ( allocation ) ) { seenRegisters . add ( allocation ) ; // The variable has been moved into an argument register. //varNames.remove((byte) allocation); //varNames.put((byte) j, ((Variable) nextOutermostArg).getName()); /*log.fine(\"PUT_VAR \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address + \", A\" + j);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutVar , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Put ) ; } else if ( nextOutermostArg . isVar ( ) ) { // Check if this is the last body functor in which this variable appears, it does so only in argument // position, and this is the first occurrence of these conditions. In which case, an unsafe put is to // be used. if ( isLastBodyTermInArgPositionOnly ( ( Variable ) nextOutermostArg , expression ) && ( addrMode == WAMInstruction . STACK_ADDR ) ) { /*log.fine(\"PUT_UNSAFE_VAL \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address + \", A\" +\n                        j);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutUnsafeVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; symbolTable . put ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR , null ) ; } else { /*log.fine(\"PUT_VAL \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address + \", A\" + j);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; } } // When a functor is encountered, output a put_struc. else if ( nextOutermostArg . isFunctor ( ) ) { Term nextFunctorArg = ( Functor ) nextOutermostArg ; // Heap cells are to be created in an order such that no heap cell can appear before other cells that it // refers to. A postfix traversal of the functors in the term to compile is used to achieve this, as // child functors in a head will be visited first. // Walk over the query term in post-fix order, picking out just the functors. QueueBasedSearchMethod < Term , Term > postfixSearch = new PostFixSearch < Term , Term > ( ) ; postfixSearch . reset ( ) ; postfixSearch . addStartState ( nextFunctorArg ) ; postfixSearch . setGoalPredicate ( new FunctorTermPredicate ( ) ) ; Iterator < Term > treeWalker = Searches . allSolutions ( postfixSearch ) ; // For each functor encountered: put_struc. while ( treeWalker . hasNext ( ) ) { Functor nextFunctor = ( Functor ) treeWalker . next ( ) ; allocation = ( Integer ) symbolTable . get ( nextFunctor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; // Ouput a put_struc instuction, except on the outermost functor. /*log.fine(\"PUT_STRUC \" + interner.getFunctorName(nextFunctor) + \"/\" + nextFunctor.getArity() +\n                        ((addrMode == REG_ADDR) ? \", X\" : \", Y\") + address);*/ WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutStruc , addrMode , address , interner . getDeinternedFunctorName ( nextFunctor . getName ( ) ) , nextFunctor ) ; instructions . add ( instruction ) ; // For each argument of the functor. int numArgs = nextFunctor . getArity ( ) ; for ( int i = 0 ; i < numArgs ; i ++ ) { Term nextArg = nextFunctor . getArgument ( i ) ; allocation = ( Integer ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; // If it is new variable: set_var or put_var. // If it is variable or functor already seen: set_val or put_val. if ( nextArg . isVar ( ) && ! seenRegisters . contains ( allocation ) ) { seenRegisters . add ( allocation ) ; /*log.fine(\"SET_VAR \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetVar , addrMode , address , nextArg ) ; // Record the way in which this variable was introduced into the clause. symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Set ) ; } else { // Check if the variable is 'local' and use a local instruction on the first occurrence. VarIntroduction introduction = ( VarIntroduction ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO ) ; if ( isLocalVariable ( introduction , addrMode ) ) { /*log.fine(\"SET_LOCAL_VAL \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") +\n                                    address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetLocalVal , addrMode , address , nextArg ) ; symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , null ) ; } else { /*log.fine(\"SET_VAL \" + ((addrMode == REG_ADDR) ? \"X\" : \"Y\") + address);*/ instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetVal , addrMode , address , nextArg ) ; } } instructions . add ( instruction ) ; } } } } return instructions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a predicate of arity n the first n registers are used to receive its arguments in . [CODESPLIT] protected void allocateArgumentRegisters ( Functor expression ) { // Assign argument registers to functors appearing directly in the argument of the outermost functor. // Variables are never assigned directly to argument registers. int reg = 0 ; for ( ; reg < expression . getArity ( ) ; reg ++ ) { Term term = expression . getArgument ( reg ) ; if ( term instanceof Functor ) { /*log.fine(\"X\" + lastAllocatedTempReg + \" = \" + interner.getFunctorFunctorName((Functor) term));*/ int allocation = ( reg & 0xff ) | ( REG_ADDR << 8 ) ; symbolTable . put ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allocates terms within a functor expression to registers . The outermost functor itself is not assigned to a register in WAM ( only in l0 ) . Functors already directly assigned to argument registers will not be re - assigned by this . Variables as arguments will be assigned but not as argument registers . [CODESPLIT] protected void allocateTemporaryRegisters ( Term expression ) { // Need to assign registers to the whole syntax tree, working in from the outermost functor. The outermost // functor itself is not assigned to a register in l3 (only in l0). Functors already directly assigned to // argument registers will not be re-assigned by this, variables as arguments will be assigned. SearchMethod outInSearch = new BreadthFirstSearch < Term , Term > ( ) ; outInSearch . reset ( ) ; outInSearch . addStartState ( expression ) ; Iterator < Term > treeWalker = Searches . allSolutions ( outInSearch ) ; // Discard the outermost functor from the variable allocation. treeWalker . next ( ) ; // For each term encountered: set X++ = term. while ( treeWalker . hasNext ( ) ) { Term term = treeWalker . next ( ) ; if ( symbolTable . get ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) == null ) { int allocation = ( lastAllocatedTempReg ++ & 0xff ) | ( REG_ADDR << 8 ) ; symbolTable . put ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Determines whether a variable is local that is it may only exist on the stack . When variables are introduced into clauses the way in which they are introduced is recorded using the { @link VarIntroduction } enum . When a variable is being written to the heap for the first time this check may be used to see if a local variant of an instruction is needed in order to globalize the variable on the heap . [CODESPLIT] protected boolean isLocalVariable ( VarIntroduction introduction , byte addrMode ) { if ( WAMInstruction . STACK_ADDR == addrMode ) { return ( introduction == VarIntroduction . Get ) || ( introduction == VarIntroduction . Put ) ; } else { return introduction == VarIntroduction . Get ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a variable is appearing within the last body functor in which it occurs and only does so within argument position . [CODESPLIT] private boolean isLastBodyTermInArgPositionOnly ( Term var , Functor body ) { return body == symbolTable . get ( var . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds a decision tree by repeatedly selecting the best property of the data examples to split on . The best property is chosen to be the one that reveals the most information about the target property to learn . [CODESPLIT] public ClassifyingMachine learn ( ) throws LearningFailureException { /*log.fine(\"public ClassifyingMachine learn(): called\");*/ // Call the initialize method to ensure that input and output properties are correctly set up. initialize ( ) ; // Check that there is only one output property to learn for. Decision trees can only output a single // property classification (although mutliple trees could be built for multiple properties). if ( outputProperties . size ( ) != 1 ) { throw new LearningFailureException ( \"Decision trees can only learn a classification for a single property, \" + \"but \" + outputProperties . size ( ) + \" have been set as outputs.\" , null ) ; } // Extract the single output property to learn for. String outputProperty = outputProperties . iterator ( ) . next ( ) ; // Check that the output property to be learnt is one with a finite number of values. Decision trees // cannot learn infinite valued attributes, such as real numbers etc. int numValues = inputExamples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( outputProperty ) . getNumPossibleValues ( ) ; if ( numValues < 1 ) { throw new LearningFailureException ( \"Decision trees can only learn a classification for a \" + \"property with a finite number of values. The property, \" + outputProperty + \" can have an infinite number of values and should be \" + \"discretized prior to being learned by decision trees.\" , null ) ; } // Used to queue nodes that are pending construction. Queue < DecisionTree > pendingNodes = new LinkedList < DecisionTree > ( ) ; // Create a pending node,(an empty tree, the examples, the attributes, the default classification). Pending startNode = new Pending ( inputExamples , inputProperties , getMajorityClassification ( outputProperty , inputExamples ) , null ) ; // Create the root of the decision tree out of this start pending node. DecisionTree decisionTree = new DecisionTree ( startNode ) ; // Push this new pending node onto the construction queue. pendingNodes . offer ( decisionTree ) ; // Loop until the queue of nodes pending construction is empty. while ( ! pendingNodes . isEmpty ( ) ) { /*log.fine(\"Got next pending node.\");*/ // Get the tree fragment for the next pending node. The data element should always be safe to cast to a // Pending node as this algorithm only pushes pending nodes onto the queue. DecisionTree currentTreePendingNode = pendingNodes . remove ( ) ; DecisionTreeElement currentTreePendingNodeElement = currentTreePendingNode . getElement ( ) ; Pending currentNode = ( Pending ) currentTreePendingNodeElement ; // Extract the examples, the attributes, the default classification, and the attribute to be matched, // for this pending node. Collection < State > examples = currentNode . getExamples ( ) ; Collection < String > undecidedProperties = currentNode . getUndecidedProperties ( ) ; OrdinalAttribute defaultAttribute = currentNode . getDefault ( ) ; OrdinalAttribute matchingAttribute = currentNode . getAttributeValue ( ) ; /*log.fine(\"Pending node corresponds to \" + examples.size() + \" examples.\");*/ /*log.fine(\"Pending node has \" + undecidedProperties.size() + \" undecided properties left.\");*/ // Used to hold the decision tree fragment (decision node, pending node or assignment leaf) that will // be inserted into the decision tree to replace the current pending node. DecisionTree newTreeFragment = null ; // If the set of examples is empty then set the default as the leaf. if ( examples . isEmpty ( ) ) { /*log.fine(\"Examples is empty.\");*/ newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , defaultAttribute , matchingAttribute ) ) ; } // Else if undecided properties is empty then set the majority value of the classification of // examples as the leaf. else if ( undecidedProperties . isEmpty ( ) ) { /*log.fine(\"No undecided properties left.\");*/ // Work out what the majority classification is and create a leaf with that assignment. OrdinalAttribute majority = getMajorityClassification ( outputProperty , inputExamples ) ; newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , majority , matchingAttribute ) ) ; } // Else if all the examples have the same classification then set that classification as the leaf. else if ( allHaveSameClassification ( outputProperty , examples ) ) { /*log.fine(\"All examples have the same classification.\");*/ newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , allClassification , matchingAttribute ) ) ; } // Else choose the best attribute (with the largest estimated information gain) on the classification. else { /*log.fine(\"Choosing the best property to split on.\");*/ String bestProperty = chooseBestPropertyToDecideOn ( outputProperty , examples , inputProperties ) ; // Check if a best property could not be found, in which case behave as if there are no // input properties left to work with. if ( bestProperty == null ) { /*log.fine(\"Couldn't find a best property to split on.\");*/ // Put the pending node back onto the construction queue but with zero input properties. Pending newPendingNode = new Pending ( examples , new ArrayList < String > ( ) , defaultAttribute , matchingAttribute ) ; newTreeFragment = new DecisionTree ( newPendingNode ) ; pendingNodes . offer ( newTreeFragment ) ; } else { // Extract an attribute with this property name from the first example and use this to get // a listing of all the possible values of that attribute. Attribute bestAttribute = ( OrdinalAttribute ) examples . iterator ( ) . next ( ) . getProperty ( bestProperty ) ; /*log.fine(\"bestProperty = \" + bestProperty);*/ /*log.fine(\"bestAttribute = \" + bestAttribute);*/ // Create a decision node that decides on the best property. New pending nodes will be created // as children of this node and added to it. newTreeFragment = new DecisionTree ( new Decision ( bestProperty , bestAttribute . getType ( ) . getNumPossibleValues ( ) , matchingAttribute ) ) ; // Produce a cut down input property set equal to the old one but with the selected best property // removed as a decision node is to be created for it. Set < String > newInputProperties = new HashSet < String > ( inputProperties ) ; newInputProperties . remove ( bestProperty ) ; // For each possible value of the best attribute. for ( Iterator < ? extends Attribute > i = bestAttribute . getType ( ) . getAllPossibleValuesIterator ( ) ; i . hasNext ( ) ; ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) i . next ( ) ; // Extract just those examples with the current value. To implement this efficiently first sort // the examples by their attribute value for the best property to split on using a range sort // (O(n) time as num possible values is limited and they are already indexed by their order). // Create the new example collection as simply a pair of indexes into the sorted list. Collection < State > matchingExamples = new ArrayList < State > ( ) ; for ( State example : examples ) { // Extract the attribute value for the property to decide on. OrdinalAttribute testAttribute = ( OrdinalAttribute ) example . getProperty ( bestProperty ) ; // Check if it matches the current value being extracted and add it to the collection of // extracted examples if so. if ( nextAttribute . equals ( testAttribute ) ) { matchingExamples . add ( example ) ; } } // Push onto the queue, a child node for this value, the subset of examples (or the value to // select that subset on), attributes without the best one (or an exclusion list of attributes // used so far), default majority-value of classification of these examples. Pending newPendingNode = new Pending ( matchingExamples , newInputProperties , getMajorityClassification ( outputProperty , matchingExamples ) , nextAttribute ) ; DecisionTree newPendingNodeTreeFragment = new DecisionTree ( newPendingNode ) ; pendingNodes . offer ( newPendingNodeTreeFragment ) ; /*log.fine(\"Created new pending node below the split, for \" + matchingExamples.size() +\n                            \" examples and \" + newInputProperties.size() + \" undecided properties.\");*/ // Add the new pending node as a child of the parent decision node for the best property. newTreeFragment . addChild ( newPendingNodeTreeFragment ) ; } } } // Remove the current pending node from the decision tree and replace it with the new element that the // algorithm has selected. Tree . Node parentTree = ( DecisionTree ) currentTreePendingNode . getParent ( ) ; // Check if the current pending node has a parent (if not it is the real tree root and the first pending // node created). if ( parentTree != null ) { // Remove the pending node from its parents child list. parentTree . getChildren ( ) . remove ( currentTreePendingNode ) ; // Replace the pending node with the newly built tree fragment in its parent child list. parentTree . addChild ( newTreeFragment ) ; } else { // Update the root tree pointer to point to the newly built tree fragment. decisionTree = newTreeFragment ; } /*log.fine(\"There are now \" + pendingNodes.size() + \" pending nodes on the construction queue.\");*/ } // Loop over the whole decision tree initializing its quick lookup tables for all the decisions it contains. for ( Iterator < SimpleTree < DecisionTreeElement > > i = decisionTree . iterator ( Tree . IterationOrder . PreOrder ) ; i . hasNext ( ) ; ) { DecisionTree nextTreeFragment = ( DecisionTree ) i . next ( ) ; DecisionTreeElement nextElement = nextTreeFragment . getElement ( ) ; // Check if it is a decision and build its lookup table if so. if ( nextElement instanceof Decision ) { Decision decision = ( Decision ) nextElement ; decision . initializeLookups ( nextTreeFragment ) ; } } // Create a new decisition tree machine out of the fully constructed decision tree. ProtoDTMachine dtMachine = new ProtoDTMachine ( ) ; dtMachine . setDecisionTree ( decisionTree ) ; // Return the trained decision tree classifying machine. return dtMachine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This helper method works out how the majority of the specified examples are classified by the named property . The property should always be the goal property that the algorithm is learning and must always take on a finite number of different values . [CODESPLIT] private OrdinalAttribute getMajorityClassification ( String property , Iterable < State > examples ) throws LearningFailureException { /*log.fine(\"private OrdinalAttribute getMajorityClassification(String property, Collection<State> examples): called\");*/ /*log.fine(\"property = \" + property);*/ // Flag used to indicate that the map to hold the value counts in has been initialized. Map < OrdinalAttribute , Integer > countMap = null ; // Used to hold the biggest count found so far. int biggestCount = 0 ; // Used to hold the value with the biggest count found so far. OrdinalAttribute biggestAttribute = null ; // Loop over all the examples counting the number of occurences of each possible classification by the // named property. for ( State example : examples ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) example . getProperty ( property ) ; /*log.fine(\"nextAttribute = \" + nextAttribute);*/ // If this is the first attribute then find out how many possible values it can take on. if ( countMap == null ) { // A check has already been performed at the start of the learning method to ensure that the output // property only takes on a finite number of values. countMap = new HashMap < OrdinalAttribute , Integer > ( ) ; } int count ; // Increment the count for the number of occurences of this classification. if ( ! countMap . containsKey ( nextAttribute ) ) { count = 1 ; countMap . put ( nextAttribute , count ) ; } else { count = countMap . get ( nextAttribute ) ; countMap . put ( nextAttribute , count ++ ) ; } // Compare it to the biggest score found so far to see if it is bigger. if ( count > biggestCount ) { // Update the biggest score. biggestCount = count ; // Update the value of the majority classification. biggestAttribute = nextAttribute ; } } // Return the majority classification found. return biggestAttribute ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if a property of a set of examples has the same value for all the examples . This algorithm works by iterating through the examples until two different values are found or the end of the collection is reached having found only one value . [CODESPLIT] private boolean allHaveSameClassification ( String property , Iterable < State > examples ) { // Used to hold the value of the first attribute seen. OrdinalAttribute firstAttribute = null ; // Flag used to indicate that the test passed successfully. boolean success = true ; // Loop over all the examples. for ( State example : examples ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) example . getProperty ( property ) ; // If this is the first example just store its attribute value. if ( firstAttribute == null ) { firstAttribute = nextAttribute ; } // Otherwise check if the attribute value does not match the first one in which case the test fails. else if ( ! nextAttribute . equals ( firstAttribute ) ) { success = false ; break ; } } // If the test passed then store the matching classification that all the examples have in a memeber variable // from where it can be accessed. if ( success ) { allClassification = firstAttribute ; } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given set of examples input properties and an output property this method chooses the input property that provides the largest information gain on the value of the output property . [CODESPLIT] private String chooseBestPropertyToDecideOn ( String outputProperty , Iterable < State > examples , Iterable < String > inputProperties ) { /*log.fine(\"private String chooseBestPropertyToDecideOn(String outputProperty, Collection<State> examples, \" +\n         \"Collection<String> inputProperties): called\");*/ // for (State e : examples) /*log.fine(e);*/ // Determine how many possible values (symbols) the output property can have. int numOutputValues = examples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( outputProperty ) . getNumPossibleValues ( ) ; // Used to hold the largest information gain found so far. double largestGain = 0.0d ; // Used to hold the input property that gives the largest gain found so far. String largestGainProperty = null ; // Loop over all the input properties. for ( String inputProperty : inputProperties ) { // let G = the set of goal property values. // let A = the set of property values that the input property can have. // Determine how many possible values (symbols) the input property can have. int numInputValues = examples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( inputProperty ) . getNumPossibleValues ( ) ; // Create an array to hold the counts of the output symbols. int [ ] outputCounts = new int [ numOutputValues ] ; // Create arrays to hold the counts of the input symbols and the joint input/output counts. int [ ] inputCounts = new int [ numInputValues ] ; int [ ] [ ] jointCounts = new int [ numInputValues ] [ numOutputValues ] ; // Loop over all the examples. for ( State example : examples ) { // Extract the output property attribute value. OrdinalAttribute outputAttribute = ( OrdinalAttribute ) example . getProperty ( outputProperty ) ; // Extract the input property attribute value. OrdinalAttribute inputAttribute = ( OrdinalAttribute ) example . getProperty ( inputProperty ) ; // Increment the count for the occurence of this value of the output property. outputCounts [ outputAttribute . ordinal ( ) ] ++ ; // Increment the count for the occurence of this value of the input property. inputCounts [ inputAttribute . ordinal ( ) ] ++ ; // Increment the count for the joint occurrence of this input/output value pair. jointCounts [ inputAttribute . ordinal ( ) ] [ outputAttribute . ordinal ( ) ] ++ ; } // Calculate the estimated probability distribution of G from the occurrence counts over the examples. double [ ] pForG = InformationTheory . pForDistribution ( outputCounts ) ; // Calculate the estimated probability distribution of A from the occurrence counts over the examples. double [ ] pForA = InformationTheory . pForDistribution ( inputCounts ) ; // Calculate the estimated probability distribution p(g|a) from the joint occurrence counts over the // examples. double [ ] [ ] pForGGivenA = InformationTheory . pForJointDistribution ( jointCounts ) ; // Calculate the information gain on G by knowing A. double gain = InformationTheory . gain ( pForG , pForA , pForGGivenA ) ; // Check if the gain is larger than the best found so far and update the best if so. if ( gain > largestGain ) { largestGain = gain ; largestGainProperty = inputProperty ; } } return largestGainProperty ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a functor . [CODESPLIT] public Functor functor ( String name , Term ... args ) { int internedName = interner . internFunctorName ( name , args . length ) ; return new Functor ( internedName , args ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an atom ( functor with no arguments ) . [CODESPLIT] public Functor atom ( String name ) { int internedName = interner . internFunctorName ( name , 0 ) ; return new Functor ( internedName , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a variable . If the variable name begins with an underscore _ it will be anonymous otherwise it will be named . [CODESPLIT] public Variable var ( String name ) { boolean isAnonymous = name . startsWith ( \"_\" ) ; int internedName = interner . internVariableName ( name ) ; return new Variable ( internedName , null , isAnonymous ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles an HTTP request sent to this action by struts . This simply forwards to the location specified by the redirect request parameter . [CODESPLIT] public ActionForward executeWithErrorHandling ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response , ActionErrors errors ) { log . fine ( \"public ActionForward performWithErrorHandling(ActionMapping mapping, ActionForm form,\" + \"HttpServletRequest request, HttpServletResponse response, \" + \"ActionErrors errors): called\" ) ; HttpSession session = request . getSession ( ) ; DynaBean dynaForm = ( DynaActionForm ) form ; // Redirect to the specified location String redirect = ( String ) dynaForm . get ( REDIRECT ) ; log . fine ( \"redirect = \" + redirect ) ; return new ActionForward ( redirect , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the sub - list at the specified page index . The returned list will have size equal to the page size unless it is the last page in which case it may not be a full page . [CODESPLIT] public List < E > get ( int index ) { /*log.fine(\"public List<E> get(int index): called\");*/ // Check that the index is not to large. int originalSize = original . size ( ) ; int size = ( originalSize / pageSize ) + ( ( ( originalSize % pageSize ) == 0 ) ? 0 : 1 ) ; /*log.fine(\"originalSize = \" + originalSize);*/ /*log.fine(\"size = \" + size);*/ // Check if the size of the underlying list is zero, in which case return an empty list, so long as page zero // was requested. if ( ( index == 0 ) && ( originalSize == 0 ) ) { return new ArrayList < E > ( ) ; } // Check if the requested index exceeds the number of pages, or is an illegal negative value. if ( ( index >= size ) || ( index < 0 ) ) { /*log.fine(\"(index >= size) || (index < 0), throwing out of bounds exception.\");*/ throw new IndexOutOfBoundsException ( \"Index \" + index + \" is less than zero or more than the number of pages: \" + size ) ; } // Extract the appropriate sub-list. // Note that if this is the last page it may not be a full page. Just up to the last page will be returned. /*log.fine(\"Requesting sublist from, \" + (pageSize * index) + \", to ,\" +\n            (((pageSize * (index + 1)) >= originalSize) ? originalSize : (pageSize * (index + 1))) + \".\");*/ List < E > result = original . subList ( pageSize * index , ( ( pageSize * ( index + 1 ) ) >= originalSize ) ? originalSize : ( pageSize * ( index + 1 ) ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void paintTrack ( Graphics g , JComponent c , Rectangle bounds ) { g . setColor ( colorScheme . getToolingBackground ( ) ) ; g . fillRect ( bounds . x , bounds . y , bounds . width , bounds . height ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void paintThumb ( Graphics g , JComponent c , Rectangle thumbBounds ) { if ( thumbBounds . isEmpty ( ) || ! scrollbar . isEnabled ( ) ) { return ; } g . translate ( thumbBounds . x , thumbBounds . y ) ; boolean vertical = isVertical ( ) ; int hgap = vertical ? 2 : 1 ; int vgap = vertical ? 1 : 2 ; int w = thumbBounds . width - ( hgap * 2 ) ; int h = thumbBounds . height - ( vgap * 2 ) ; // leave one pixel between thumb and right or bottom edge if ( vertical ) { h -= 1 ; } else { w -= 1 ; } g . setColor ( colorScheme . getToolingActiveBackground ( ) ) ; g . fillRect ( hgap + 1 , vgap + 1 , w - 1 , h - 1 ) ; g . setColor ( colorScheme . getToolingActiveBackground ( ) ) ; g . drawRoundRect ( hgap , vgap , w , h , 3 , 3 ) ; g . translate ( - thumbBounds . x , - thumbBounds . y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected Dimension getMinimumThumbSize ( ) { int thickness = THICKNESS ; return isVertical ( ) ? new Dimension ( thickness , thickness * 2 ) : new Dimension ( thickness * 2 , thickness ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the kind of paint to use . For the image background? [CODESPLIT] public void setTexture ( Paint obj ) { if ( obj instanceof GradientPaint ) { texture = new GradientPaint ( 0 , 0 , Color . white , getSize ( ) . width * 2 , 0 , Color . green ) ; } else { texture = obj ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Immediately repaints the surface . [CODESPLIT] public void paintImmediately ( int x , int y , int w , int h ) { RepaintManager repaintManager = null ; boolean save = true ; if ( ! isDoubleBuffered ( ) ) { repaintManager = RepaintManager . currentManager ( this ) ; save = repaintManager . isDoubleBufferingEnabled ( ) ; repaintManager . setDoubleBufferingEnabled ( false ) ; } super . paintImmediately ( x , y , w , h ) ; if ( repaintManager != null ) { repaintManager . setDoubleBufferingEnabled ( save ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the surface . This method will create a buffered image to render in if one does not already exist . If rendering is to be done directly to the screen no buffered image will be generated . If the size of the buffered image does not match the Graphics context size then a new buffered image will be generated of the correct size before rendering . The { @link #render } method will be called to do the actual drawing . [CODESPLIT] public void paint ( Graphics g ) { // Get the size of the surface Dimension d = getSize ( ) ; // Check if direct to screen rendering is to be used if ( imageType == 1 ) { // Use no buffered image for direct rendering bimg = null ; } // Check if no buffered image has been created yet or if the existing one has the wrong size else if ( ( bimg == null ) || ( biw != d . width ) || ( bih != d . height ) ) { // Create a new bufferd image. Note that imageType has two subtracted for it as type 0 stands for auto // selection and type 1 for direct to screen. Subtracting two corresponds to the image types in the // BufferedImage class. bimg = createBufferedImage ( d . width , d . height , imageType - 2 ) ; // Set clear once flag to clear the new image on the first pass clearOnce = true ; } // Build a Graphics2D context for the image Graphics2D g2 = createGraphics2D ( d . width , d . height , bimg , g ) ; // Call the subclass to perform rendering render ( d . width , d . height , g2 ) ; // Clear up the Graphics2D context g2 . dispose ( ) ; // Check if a buffered image was used (and not direct to screen rendering) if ( bimg != null ) { // Copy the buffered image onto the screen g . drawImage ( bimg , 0 , 0 , null ) ; // Ensure screen is up to date toolkit . sync ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a fresh buffered image of the appropriate type . [CODESPLIT] protected BufferedImage createBufferedImage ( int w , int h , int imgType ) { BufferedImage bi = null ; if ( imgType == 0 ) { bi = ( BufferedImage ) createImage ( w , h ) ; } else if ( ( imgType > 0 ) && ( imgType < 14 ) ) { bi = new BufferedImage ( w , h , imgType ) ; } else if ( imgType == 14 ) { bi = createBinaryImage ( w , h , 2 ) ; } else if ( imgType == 15 ) { bi = createBinaryImage ( w , h , 4 ) ; } else if ( imgType == 16 ) { bi = createSGISurface ( w , h , 32 ) ; } else if ( imgType == 17 ) { bi = createSGISurface ( w , h , 16 ) ; } // Store the buffered image size biw = w ; bih = h ; return bi ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a Graphics2D drawing context from a BufferedImage or Graphics context . The graphics context is built using the properties defined for the surface . This method is used to generate the Graphics2D context that subclasses will render in . IF the buffered image is null then the passed in Graphics context will be used to generate the Graphics2D context . This is the case when no buffered image is used and the subclass renders straight to the screen . [CODESPLIT] protected Graphics2D createGraphics2D ( int width , int height , BufferedImage bi , Graphics g ) { Graphics2D g2 = null ; // Check if the buffered image is null if ( bi != null ) { // Create Graphics2D context for the buffered image g2 = bi . createGraphics ( ) ; } else { // The buffered image is null so create Graphics2D context for the Graphics context g2 = ( Graphics2D ) g ; } // @todo what is this for? g2 . setBackground ( getBackground ( ) ) ; // Set the rendering properties of the graphics context g2 . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , antiAlias ) ; g2 . setRenderingHint ( RenderingHints . KEY_RENDERING , rendering ) ; // Check the clear flags to see if the graphics context should be cleared if ( clearSurface || clearOnce ) { // Clear the image g2 . clearRect ( 0 , 0 , width , height ) ; // Reset the clear once flag to show that clearing has been done clearOnce = false ; } // Check if a background fill texture is to be used if ( texture != null ) { // set composite to opaque for texture fills g2 . setComposite ( AlphaComposite . SrcOver ) ; g2 . setPaint ( texture ) ; g2 . fillRect ( 0 , 0 , width , height ) ; } // Check if alpha compositing is to be used if ( composite != null ) { // Set the alpha compositing algorithm g2 . setComposite ( composite ) ; } return g2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a custom grey - scale binary image format . [CODESPLIT] private BufferedImage createBinaryImage ( int w , int h , int pixelBits ) { int bytesPerRow = w * pixelBits / 8 ; if ( ( w * pixelBits % 8 ) != 0 ) { bytesPerRow ++ ; } byte [ ] imageData = new byte [ h * bytesPerRow ] ; IndexColorModel cm = null ; switch ( pixelBits ) { case 1 : { cm = new IndexColorModel ( pixelBits , lut1Arr . length , lut1Arr , lut1Arr , lut1Arr ) ; break ; } case 2 : { cm = new IndexColorModel ( pixelBits , lut2Arr . length , lut2Arr , lut2Arr , lut2Arr ) ; break ; } case 4 : { cm = new IndexColorModel ( pixelBits , lut4Arr . length , lut4Arr , lut4Arr , lut4Arr ) ; break ; } default : { new Exception ( \"Invalid # of bit per pixel\" ) . printStackTrace ( ) ; } } DataBuffer db = new DataBufferByte ( imageData , imageData . length ) ; WritableRaster r = Raster . createPackedRaster ( db , w , h , pixelBits , null ) ; return new BufferedImage ( cm , r , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a custom colour image format . [CODESPLIT] private BufferedImage createSGISurface ( int w , int h , int pixelBits ) { int rMask32 = 0xFF000000 ; int rMask16 = 0xF800 ; int gMask32 = 0x00FF0000 ; int gMask16 = 0x07C0 ; int bMask32 = 0x0000FF00 ; int bMask16 = 0x003E ; DirectColorModel dcm = null ; DataBuffer db = null ; WritableRaster wr = null ; switch ( pixelBits ) { case 16 : { short [ ] imageDataUShort = new short [ w * h ] ; dcm = new DirectColorModel ( 16 , rMask16 , gMask16 , bMask16 ) ; db = new DataBufferUShort ( imageDataUShort , imageDataUShort . length ) ; wr = Raster . createPackedRaster ( db , w , h , w , new int [ ] { rMask16 , gMask16 , bMask16 } , null ) ; break ; } case 32 : { int [ ] imageDataInt = new int [ w * h ] ; dcm = new DirectColorModel ( 32 , rMask32 , gMask32 , bMask32 ) ; db = new DataBufferInt ( imageDataInt , imageDataInt . length ) ; wr = Raster . createPackedRaster ( db , w , h , w , new int [ ] { rMask32 , gMask32 , bMask32 } , null ) ; break ; } default : { new Exception ( \"Invalid # of bit per pixel\" ) . printStackTrace ( ) ; } } return new BufferedImage ( dcm , wr , false , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Predicate predicate ) { if ( traverser . isEnteringContext ( ) ) { initializePrinters ( ) ; } else if ( traverser . isLeavingContext ( ) ) { printTable ( ) ; } super . visit ( predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Workaround MockWebServer issue #11 . [CODESPLIT] public static RecordedRequest takeRequest ( MockWebServer server ) throws InterruptedException { RecordedRequest request = server . takeRequest ( ) ; while ( \"GET /favicon.ico HTTP/1.1\" . equals ( request . getRequestLine ( ) ) ) { request = server . takeRequest ( ) ; } return request ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean isValid ( EnumeratedStringAttribute value , ConstraintValidatorContext context ) { if ( value == null ) { return true ; } return value . getId ( ) != - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Handles requests that accept application / json . < / p > [CODESPLIT] @ RequestMapping ( value = { \"/{schema:[^\\\\.]+}\" , \"/{schema}.json\" } , produces = \"application/json\" , headers = { \"Accept=application/json\" } ) @ ResponseBody public Report processJsonRequest ( @ PathVariable String schema , HttpServletRequest request ) throws ServiceException , InvalidParameterException , InvalidSchemaException { LOG . info ( \"Processing JSON request for parameters \" + request . getQueryString ( ) ) ; return processRequest ( schema , request ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Generic processor of all types of requests . < / p > <p > Validates schema availability mandatory fields for the specified schema and creates chains of { @link QueryParameterAware } to be processed by the underlying { @link GenericSchemaService } . < / p > [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private Report processRequest ( String schema , HttpServletRequest request ) throws ServiceException , InvalidParameterException , InvalidSchemaException { long begin = System . currentTimeMillis ( ) ; SchemaDefinition config = schemaRepository . getStarSchemaConfig ( schema ) ; if ( config == null ) { LOG . warn ( \"Invalid endpoint \\\"\" + schema + \"\\\"\" ) ; throw new InvalidSchemaException ( \"Invalid endpoint\" ) ; } Map < String , String [ ] > params = request . getParameterMap ( ) ; for ( String mandatory : MANDATORY_FIELDS ) { if ( ! params . containsKey ( mandatory ) ) { // mandatory fields are case sensitive LOG . error ( \"Mandatory field \\\"\" + mandatory + \"\\\" missing\" ) ; throw new InvalidParameterException ( \"Missing mandatory field \" + mandatory ) ; } } QueryParameterEnvelope queryParameterDto = new QueryParameterEnvelope ( ) ; for ( String key : params . keySet ( ) ) { if ( DOMAIN_PARAMETERS . contains ( key ) ) { String domainParameter = params . get ( key ) [ 0 ] ; final DomainParserAware systemParameter = SystemParameter . valueOf ( key ) ; systemParameter . parseValue ( domainParameter , config , queryParameterDto ) ; } else { Pair < String , String > pair = splitKey ( key ) ; if ( ! config . isValidDimension ( pair . getLeft ( ) , pair . getRight ( ) ) ) { LOG . warn ( \"Invalid parameter \\\"\" + key + \"\\\" for endpoint \\\"\" + schema + \"\\\".\" ) ; throw new InvalidParameterException ( \"Invalid parameter \" + key + \" for endpoint \" + schema + \"\" ) ; } String [ ] multiParam = request . getParameterValues ( key ) ; for ( String param : multiParam ) { queryParameterDto . addConstraints ( new HttpQueryConstraint ( config , key , param ) ) ; } } } final Report report = schemaService . generateReport ( config , queryParameterDto ) ; report . setRecords ( inMemoryPagination ( report . getRecords ( ) , queryParameterDto ) ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"Query successfully processed for schema \" + schema + \" in \" + ( System . currentTimeMillis ( ) - begin ) + \"s.\" ) ; } return report ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Handles { @link ServiceException } generated by the underlying layer . < / p > [CODESPLIT] @ ExceptionHandler ( ServiceException . class ) @ ResponseBody public ResponseEntity < String > handleServiceException ( ServiceException exception ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . INTERNAL_SERVER_ERROR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Handles { @link InvalidParameterException } generated by the controller itself when receives an invalid parameter . < / p > [CODESPLIT] @ ExceptionHandler ( InvalidParameterException . class ) @ ResponseBody public ResponseEntity < String > handleControllerException ( InvalidParameterException exception ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . BAD_REQUEST ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Handles { @link InvalidSchemaException } generated by the controller itself when receives a request to a non existing schema configuration . < / p > [CODESPLIT] @ ExceptionHandler ( InvalidSchemaException . class ) @ ResponseBody public ResponseEntity < String > handleInvalidSchemaException ( InvalidSchemaException exception ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . NOT_FOUND ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Creates a { @link Pair } composed of Dimension and Information required by the { @link GenericSchemaService } . < / p > [CODESPLIT] private static Pair < String , String > splitKey ( String key ) { String dimension = null ; String info = null ; if ( ! key . contains ( \".\" ) ) { dimension = key ; } else { dimension = key . substring ( 0 , key . indexOf ( ' ' ) ) ; info = key . substring ( key . indexOf ( ' ' ) + 1 , key . length ( ) ) ; } return Pair . of ( dimension , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO to be removed [CODESPLIT] private List < ReportRecord > inMemoryPagination ( final List < ReportRecord > recordList , QueryParameterEnvelope queryParameterEnvelope ) { final QueryParameterAware pageSize = queryParameterEnvelope . getPageSize ( ) ; final QueryParameterAware pageNumber = queryParameterEnvelope . getPageNumber ( ) ; if ( pageSize != null && pageNumber != null ) { final Integer pageSizeValue = ( ( PageSizeConstraint ) pageSize ) . getPageSizeValue ( ) ; final Integer pageValue = ( ( PageNumberConstraint ) pageNumber ) . getPageNumberValue ( ) - 1 ; int offset = pageValue * pageSizeValue ; return recordList . subList ( offset > recordList . size ( ) ? recordList . size ( ) : offset , offset + pageSizeValue > recordList . size ( ) ? recordList . size ( ) : offset + pageSizeValue ) ; } return recordList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void restore ( ) { boolean foundSavePoint = false ; while ( ! foundSavePoint && ! undoStack . isEmpty ( ) ) { Undoable undoable = undoStack . poll ( ) ; undoable . undo ( ) ; foundSavePoint = ( undoable instanceof SavePoint ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the give column exist ( by name ) [CODESPLIT] public final boolean containsColumn ( String columnName ) { if ( StringUtils . isNotBlank ( columnName ) ) { return sqlTableColumns . containsKey ( columnName ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterClause ( Clause clause ) { if ( clause instanceof WAMCompiledQuery ) { WAMOptimizeableListing query = ( WAMCompiledQuery ) clause ; for ( WAMInstruction instruction : query . getUnoptimizedInstructions ( ) ) { WAMLabel label = instruction . getLabel ( ) ; addLineToRow ( ( label != null ) ? ( label . toPrettyString ( ) + \":\" ) : \"\" ) ; nextRow ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterPredicate ( Predicate predicate ) { if ( predicate instanceof WAMCompiledPredicate ) { WAMOptimizeableListing compiledPredicate = ( WAMCompiledPredicate ) predicate ; for ( WAMInstruction instruction : compiledPredicate . getUnoptimizedInstructions ( ) ) { WAMLabel label = instruction . getLabel ( ) ; addLineToRow ( ( label != null ) ? ( label . toPrettyString ( ) + \":\" ) : \"\" ) ; nextRow ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Allows different queue search algorithms to replace the default one . This overidden method ensures that the peek at head flag is always set on the search algorithm and that it expands it successor nodes in reverse as for depth first searches . [CODESPLIT] protected void setQueueSearchAlgorithm ( QueueSearchAlgorithm < O , T > algorithm ) { algorithm . setPeekAtHead ( true ) ; algorithm . setReverseEnqueueOrder ( true ) ; super . setQueueSearchAlgorithm ( algorithm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search iteratively on increasing maximum bound limits until the search space is exhausted or a goal state is found . [CODESPLIT] public SearchNode search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { // Iteratively increase the bound until a search succeeds. for ( float bound = startBound ; ; ) { // Set up the maximum bound for this iteration. maxBound = bound ; // Use a try block as the depth bounded search will throw a MaxBoundException if it fails but there // are successors states known to exist beyond the current max depth fringe. try { // Get the number of search steps taken so far and pass this into the underlying depth bounded search // so that the step count limit carries over between successive iterations. int numStepsSoFar = initSearch . getStepsTaken ( ) ; // Call the super class search method to perform a depth bounded search on this maximum bound starting // from the initial search state. initSearch . resetEnqueuedOnceFlag ( ) ; SearchNode node = super . search ( initSearch , startStates , maxSteps , numStepsSoFar ) ; // Check if the current depth found a goal node if ( node != null ) { return node ; } // The depth bounded search returned null, so it has exhausted the search space. Return with null. else { return null ; } } // The depth bounded search failed but it knows that there are more successor states at deeper levels. catch ( MaxBoundException e ) { // Do nothing, no node found at this depth so continue at the next depth level e = null ; } // Check if the bound should be increased by epsilon or to the next smallest bound property value // beyond the fringe and update the bound for the next iteration. if ( useEpsilon ) { bound = bound + epsilon ; } else { bound = getMinBeyondBound ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void open ( ) { // Build a text grid panel in the left position. grid = componentFactory . createTextGrid ( ) ; grid . insertVerticalSeparator ( 9 , 10 ) ; grid . insertVerticalSeparator ( 17 , 10 ) ; grid . insertVerticalSeparator ( 26 , 10 ) ; mainWindow . showConsole ( componentFactory . createTextGridPanel ( grid ) ) ; // Build a table model on the text grid, and construct a register monitor on the table. table = ( EnhancedTextTable ) grid . createTable ( 0 , 0 , 20 , 20 ) ; monitor = new MemoryLayoutMonitor ( table ) ; // Attach a listener for updates to the register table. table . addTextTableListener ( new TableUpdateHandler ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getRelWhenAnchorReturnsRelationship ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<a rel='x'/>\" + \"</body></html>\" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( \"x\" ) . getRel ( ) ; assertThat ( \"link rel\" , actual , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getHrefWhenAnchorAndAbsoluteHrefReturnsUrl ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<a rel='r' href='http://x/'/>\" + \"</body></html>\" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( \"r\" ) . getHref ( ) ; assertThat ( \"link href\" , actual , is ( new URL ( \"http://x/\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void followWhenAnchorSubmitsRequest ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<a rel='r' href='/x'>a</a>\" + \"</body></html>\" ) ) ; server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( \"r\" ) . follow ( ) ; server ( ) . takeRequest ( ) ; assertThat ( \"request\" , takeRequest ( server ( ) ) . getPath ( ) , is ( \"/x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<a rel='x'/>\" + \"</body></html>\" ) ) ; Link link = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( \"x\" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( \"Cannot unwrap to: class java.lang.Void\" ) ; link . unwrap ( Void . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search until a goal state is found or the maximum allowed number of steps is reached . [CODESPLIT] public SearchNode search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { // Initialize the queue with the start states set up in search nodes if this has not already been done. // This will only be done on the first call to this method, as enqueueStartStates sets a flag when it is // done. Subsequent searches continue from where the previous search left off. Have to call reset on // the search method to really start the search again from the start states. Queue < SearchNode < O , T > > queue = initSearch . enqueueStartStates ( startStates ) ; // Get the goal predicate configured as part of the enqueueing start states process. UnaryPredicate < T > goalPredicate = initSearch . getGoalPredicate ( ) ; // Keep running until the queue becomes empty or a goal state is found. while ( ! queue . isEmpty ( ) ) { // Extract or peek at the head element from the queue. SearchNode < O , T > headNode = peekAtHead ? queue . peek ( ) : queue . remove ( ) ; // Expand the successors into the queue whether the current node is a goal state or not. // This prepares the queue for subsequent searches, ensuring that goal states do not block // subsequent goal states that exist beyond them. if ( ! headNode . isExpanded ( ) ) { headNode . expandSuccessors ( queue , reverseEnqueue ) ; } // Get the node to be goal checked, either the head node or the new top of queue, depending on the // peek at head flag. Again this is only a peek, the node is only to be removed if it is to be // goal checked. SearchNode < O , T > currentNode = peekAtHead ? queue . peek ( ) : headNode ; // Only goal check leaves, or nodes already expanded. (The expanded flag will be set on leaves anyway). if ( currentNode . isExpanded ( ) ) { // If required, remove the node to goal check from the queue. currentNode = peekAtHead ? queue . remove ( ) : headNode ; // Check if the current node is a goal state. if ( goalPredicate . evaluate ( currentNode . getState ( ) ) ) { return currentNode ; } } // Check if there is a maximum number of steps limit and increase the step count and check the limit if so. if ( maxSteps > 0 ) { searchSteps ++ ; // Update the search state with the number of steps taken so far. initSearch . setStepsTaken ( searchSteps ) ; if ( searchSteps >= maxSteps ) { // The maximum number of steps has been reached, however if the queue is now empty then the search // has just completed within the maximum. Check if the queue is empty and return null if so. if ( queue . isEmpty ( ) ) { return null ; } // Quit without a solution as the max number of steps has been reached but because there are still // more states in the queue then raise a search failure exception. else { throw new SearchNotExhaustiveException ( \"Maximum number of steps reached.\" , null ) ; } } } } // No goal state was found so return null return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void reset ( ) { // Reset the resolver to completely clear out its domain. resolver . reset ( ) ; // Create a token source to load the model rules from. Source < Token > tokenSource = TokenSource . getTokenSourceForInputStream ( WAMEngine . class . getClassLoader ( ) . getResourceAsStream ( BUILT_IN_LIB ) ) ; // Set up a parser on the token source. Parser < Clause , Token > libParser = new SentenceParser ( interner ) ; libParser . setTokenSource ( tokenSource ) ; // Load the built-ins into the domain. try { while ( true ) { Sentence < Clause > sentence = libParser . parse ( ) ; if ( sentence == null ) { break ; } compiler . compile ( sentence ) ; } compiler . endScope ( ) ; } catch ( SourceCodeException e ) { // There should not be any errors in the built in library, if there are then the prolog engine just // isn't going to work, so report this as a bug. throw new IllegalStateException ( \"Got an exception whilst loading the built-in library.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses statements and print the parse tree to the console for quick interactive testing of the parser . [CODESPLIT] public static void main ( String [ ] args ) { try { SimpleCharStream inputStream = new SimpleCharStream ( System . in , null , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; Source < Token > tokenSource = new TokenSource ( tokenManager ) ; PrologParser parser = new PrologParser ( tokenSource , new VariableAndFunctorInternerImpl ( \"Prolog_Variable_Namespace\" , \"Prolog_Functor_Namespace\" ) ) ; while ( true ) { // Parse the next sentence or directive. Object nextParsing = parser . clause ( ) ; console . info ( nextParsing . toString ( ) ) ; } } catch ( Exception e ) { console . log ( Level . SEVERE , e . getMessage ( ) , e ) ; System . exit ( 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses many consecutive sentences until an <EOF > is reached . This method is intended to aid with consulting files . [CODESPLIT] public List < Clause > sentences ( ) throws SourceCodeException { List < Clause > results = new LinkedList < Clause > ( ) ; // Loop consuming clauses until end of file is encounterd. while ( true ) { if ( peekAndConsumeEof ( ) ) { break ; } else { results . add ( sentence ( ) ) ; } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a single sentence in first order logic . A sentence consists of a term followed by a full stop . [CODESPLIT] public Clause clause ( ) throws SourceCodeException { // Each new sentence provides a new scope in which to make variables unique. variableContext . clear ( ) ; Term term = term ( ) ; Clause clause = TermUtils . convertToClause ( term , interner ) ; if ( clause == null ) { throw new SourceCodeException ( \"Only queries and clauses are valid sentences in Prolog, not \" + term + \".\" , null , null , null , term . getSourceCodePosition ( ) ) ; } return clause ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses multiple sequential terms and if more than one is encountered then the flat list of terms encountered must contain operators in order to be valid Prolog syntax . In that case the flat list of terms is passed to the { @link DynamicOperatorParser#parseOperators ( Term [] ) } method for deferred decision parsing of dynamic operators . [CODESPLIT] public Term term ( ) throws SourceCodeException { List < Term > terms ; terms = terms ( new LinkedList < Term > ( ) ) ; Term [ ] flatTerms = terms . toArray ( new Term [ terms . size ( ) ] ) ; if ( flatTerms . length > 1 ) { return operatorParser . parseOperators ( flatTerms ) ; } else { Term result = flatTerms [ 0 ] ; // If a single candidate op symbol has been parsed, promote it to a constant. if ( result instanceof CandidateOpSymbol ) { CandidateOpSymbol candidate = ( CandidateOpSymbol ) result ; int nameId = interner . internFunctorName ( candidate . getTextName ( ) , 0 ) ; result = new Functor ( nameId , null ) ; } return result ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recursively parses terms which may be functors atoms variables literals or operators into a flat list in the order in which they are encountered . [CODESPLIT] public List < Term > terms ( List < Term > terms ) throws SourceCodeException { Term term ; Token nextToken = tokenSource . peek ( ) ; switch ( nextToken . kind ) { case FUNCTOR : term = functor ( ) ; break ; case LSQPAREN : term = listFunctor ( ) ; break ; case VAR : term = variable ( ) ; break ; case INTEGER_LITERAL : term = intLiteral ( ) ; break ; case FLOATING_POINT_LITERAL : term = doubleLiteral ( ) ; break ; case STRING_LITERAL : term = stringLiteral ( ) ; break ; case ATOM : term = atom ( ) ; break ; case LPAREN : consumeToken ( LPAREN ) ; term = term ( ) ; // Mark the term as bracketed to ensure that this is its final parsed form. In particular the // #arglist method will not break it up if it contains commas. term . setBracketed ( true ) ; consumeToken ( RPAREN ) ; break ; default : throw new SourceCodeException ( \"Was expecting one of \" + BEGIN_TERM_TOKENS + \" but got \" + tokenImage [ nextToken . kind ] + \".\" , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } terms . add ( term ) ; switch ( tokenSource . peek ( ) . kind ) { case LPAREN : case LSQPAREN : case INTEGER_LITERAL : case FLOATING_POINT_LITERAL : case STRING_LITERAL : case VAR : case FUNCTOR : case ATOM : terms ( terms ) ; break ; default : } return terms ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a single atom in first order logic . If the operator has been set up which has the same name as the atom then the atom may actually be a functor expressed as a prefix postfix or infix operator . If this is the case the value returned by this method will be a { @link CandidateOpSymbol } . Otherwise it will be a { @link Functor } of arity zero . [CODESPLIT] public Term atom ( ) throws SourceCodeException { Token name = consumeToken ( ATOM ) ; Term result ; // Used to build the possible set of operators that this symbol could be parsed as. EnumMap < OpSymbol . Fixity , OpSymbol > possibleOperators = operatorTable . getOperatorsMatchingNameByFixity ( name . image ) ; // Check if the symbol mapped onto any candidate operators and if not create a constant for it. if ( ( possibleOperators == null ) || possibleOperators . isEmpty ( ) ) { int nameId = interner . internFunctorName ( name . image , 0 ) ; result = new Functor ( nameId , null ) ; } else { // Set the possible associativities of the operator on the candidate. result = new CandidateOpSymbol ( name . image , possibleOperators ) ; } // Set the position that the name was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( name . beginLine , name . beginColumn , name . endLine , name . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a single functor in first order logic with its arguments . [CODESPLIT] public Term functor ( ) throws SourceCodeException { Token name = consumeToken ( FUNCTOR ) ; Term [ ] args = arglist ( ) ; consumeToken ( RPAREN ) ; int nameId = interner . internFunctorName ( ( args == null ) ? name . image : name . image . substring ( 0 , name . image . length ( ) - 1 ) , ( args == null ) ? 0 : args . length ) ; Functor result = new Functor ( nameId , args ) ; SourceCodePosition position = new SourceCodePositionImpl ( name . beginLine , name . beginColumn , name . endLine , name . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a list expressed as a sequence of functors in first order logic . The empty list consists of the atom nil and a non - empty list consists of the functor cons with arguments the head of the list and the remainder of the list . [CODESPLIT] public Term listFunctor ( ) throws SourceCodeException { // Get the interned names of the nil and cons functors. int nilId = interner . internFunctorName ( \"nil\" , 0 ) ; int consId = interner . internFunctorName ( \"cons\" , 2 ) ; // A list always starts with a '['. Token leftDelim = consumeToken ( LSQPAREN ) ; // Check if the list contains any arguments and parse them if so. Term [ ] args = null ; Token nextToken = tokenSource . peek ( ) ; switch ( nextToken . kind ) { case LPAREN : case LSQPAREN : case INTEGER_LITERAL : case FLOATING_POINT_LITERAL : case STRING_LITERAL : case VAR : case FUNCTOR : case ATOM : args = arglist ( ) ; break ; default : } // Work out what the terminal element in the list is. It will be 'nil' unless an explicit cons '|' has // been used to specify a different terminal element. In the case where cons is used explciitly, the // list prior to the cons must not be empty. Term accumulator ; if ( tokenSource . peek ( ) . kind == CONS ) { if ( args == null ) { throw new SourceCodeException ( \"Was expecting one of \" + BEGIN_TERM_TOKENS + \" but got \" + tokenImage [ nextToken . kind ] + \".\" , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } consumeToken ( CONS ) ; accumulator = term ( ) ; } else { accumulator = new Nil ( nilId , null ) ; } // A list is always terminated with a ']'. Token rightDelim = consumeToken ( RSQPAREN ) ; // Walk down all of the lists arguments joining them together with cons/2 functors. if ( args != null ) // 'args' will contain one or more elements if not null. { for ( int i = args . length - 1 ; i >= 0 ; i -- ) { Term previousAccumulator = accumulator ; //accumulator = new Functor(consId.ordinal(), new Term[] { args[i], previousAccumulator }); accumulator = new Cons ( consId , new Term [ ] { args [ i ] , previousAccumulator } ) ; } } // Set the position that the list was parsed from, as being the region between the '[' and ']' brackets. SourceCodePosition position = new SourceCodePositionImpl ( leftDelim . beginLine , leftDelim . beginColumn , rightDelim . endLine , rightDelim . endColumn ) ; accumulator . setSourceCodePosition ( position ) ; // The cast must succeed because arglist must return at least one argument, therefore the cons generating // loop must have been run at least once. If arglist is not called at all because an empty list was // encountered, then the accumulator will contain the 'nil' constant which is a functor of arity zero. return ( Functor ) accumulator ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a sequence of terms as a comma seperated argument list . The operator in prolog can be used as an operator when it behaves as a functor of arity 2 or it can be used to separate a sequence of terms that are arguments to a functor or list . The sequence of functors must first be parsed as a term using the operator precedence of to form the term . This method takes such a term and flattens it back into a list of terms breaking it only on a sequence of commas . Terms that have been parsed as a bracketed expression will not be broken up . [CODESPLIT] public Term [ ] arglist ( ) throws SourceCodeException { Term term = term ( ) ; List < Term > result = TermUtils . flattenTerm ( term , Term . class , \",\" , interner ) ; return result . toArray ( new Term [ result . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a variable in first order logic . Variables are scoped within the current sentence being parsed so if the variable has been seen previously in the sentence it is returned rather than a new one being created . [CODESPLIT] public Term variable ( ) throws SourceCodeException { Token name = consumeToken ( VAR ) ; // Intern the variables name. int nameId = interner . internVariableName ( name . image ) ; // Check if the variable already exists in this scope, or create a new one if it does not. // If the variable is the unidentified anonymous variable '_', a fresh one will always be created. Variable var = null ; if ( ! \"_\" . equals ( name . image ) ) { var = variableContext . get ( nameId ) ; } if ( var != null ) { return var ; } else { var = new Variable ( nameId , null , name . image . equals ( \"_\" ) ) ; variableContext . put ( nameId , var ) ; return var ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses an integer literal . [CODESPLIT] public Term intLiteral ( ) throws SourceCodeException { Token valToken = consumeToken ( INTEGER_LITERAL ) ; NumericType result = new IntLiteral ( Integer . parseInt ( valToken . image ) ) ; // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a real number literal . [CODESPLIT] public Term doubleLiteral ( ) throws SourceCodeException { Token valToken = consumeToken ( FLOATING_POINT_LITERAL ) ; NumericType result = new DoubleLiteral ( Double . parseDouble ( valToken . image ) ) ; // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a string literal . [CODESPLIT] public Term stringLiteral ( ) throws SourceCodeException { Token valToken = consumeToken ( STRING_LITERAL ) ; String valWithQuotes = valToken . image ; StringLiteral result = new StringLiteral ( valWithQuotes . substring ( 1 , valWithQuotes . length ( ) - 1 ) ) ; // Set the position that the literal was parsed from. SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peeks at the next token to see if it is an { @link #ATOM } which is equal to ; and if it is consumes it . If the symbol is consumed then the return value indicates that this has happened . This is intended to be usefull for interactive interpreters when querying the user to see if they want more solutions to be found . [CODESPLIT] public boolean peekAndConsumeMore ( ) { Token nextToken = tokenSource . peek ( ) ; if ( ( nextToken . kind == ATOM ) && \";\" . equals ( nextToken . image ) ) { try { consumeToken ( ATOM ) ; } catch ( SourceCodeException e ) { // If the peek ahead kind can not be consumed then something strange has gone wrong so report this // as a bug rather than try to recover from it. throw new IllegalStateException ( e ) ; } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peeks and consumes the next interactive system directive . [CODESPLIT] public Directive peekAndConsumeDirective ( ) throws SourceCodeException { if ( peekAndConsumeTrace ( ) ) { return Directive . Trace ; } if ( peekAndConsumeInfo ( ) ) { return Directive . Info ; } if ( peekAndConsumeUser ( ) ) { return Directive . User ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interns an operators name as a functor of appropriate arity for the operators fixity and sets the operator in the operator table . [CODESPLIT] public void internOperator ( String operatorName , int priority , OpSymbol . Associativity associativity ) { int arity ; if ( ( associativity == XFY ) | ( associativity == YFX ) | ( associativity == XFX ) ) { arity = 2 ; } else { arity = 1 ; } int name = interner . internFunctorName ( operatorName , arity ) ; operatorTable . setOperator ( name , operatorName , priority , associativity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Interns and inserts into the operator table all of the built in operators and functors in Prolog . [CODESPLIT] protected void initializeBuiltIns ( ) { // Initializes the operator table with the standard ISO prolog built-in operators. internOperator ( \":-\" , 1200 , XFX ) ; internOperator ( \":-\" , 1200 , FX ) ; internOperator ( \"-->\" , 1200 , XFX ) ; internOperator ( \"?-\" , 1200 , FX ) ; internOperator ( \";\" , 1100 , XFY ) ; internOperator ( \"->\" , 1050 , XFY ) ; internOperator ( \",\" , 1000 , XFY ) ; internOperator ( \"\\\\+\" , 900 , FY ) ; internOperator ( \"=\" , 700 , XFX ) ; internOperator ( \"\\\\=\" , 700 , XFX ) ; internOperator ( \"==\" , 700 , XFX ) ; internOperator ( \"\\\\==\" , 700 , XFX ) ; internOperator ( \"@<\" , 700 , XFX ) ; internOperator ( \"@=<\" , 700 , XFX ) ; internOperator ( \"@>\" , 700 , XFX ) ; internOperator ( \"@>=\" , 700 , XFX ) ; internOperator ( \"=..\" , 700 , XFX ) ; internOperator ( \"is\" , 700 , XFX ) ; internOperator ( \"=:=\" , 700 , XFX ) ; internOperator ( \"=\\\\=\" , 700 , XFX ) ; internOperator ( \"<\" , 700 , XFX ) ; internOperator ( \"=<\" , 700 , XFX ) ; internOperator ( \">\" , 700 , XFX ) ; internOperator ( \">=\" , 700 , XFX ) ; internOperator ( \"+\" , 500 , YFX ) ; internOperator ( \"-\" , 500 , YFX ) ; internOperator ( \"\\\\/\" , 500 , YFX ) ; internOperator ( \"/\\\\\" , 500 , YFX ) ; internOperator ( \"/\" , 400 , YFX ) ; internOperator ( \"//\" , 400 , YFX ) ; internOperator ( \"*\" , 400 , YFX ) ; internOperator ( \">>\" , 400 , YFX ) ; internOperator ( \"<<\" , 400 , YFX ) ; internOperator ( \"rem\" , 400 , YFX ) ; internOperator ( \"mod\" , 400 , YFX ) ; internOperator ( \"-\" , 200 , FY ) ; internOperator ( \"^\" , 200 , YFX ) ; internOperator ( \"**\" , 200 , YFX ) ; internOperator ( \"\\\\\" , 200 , FY ) ; // Intern all built in functors. interner . internFunctorName ( \"nil\" , 0 ) ; interner . internFunctorName ( \"cons\" , 2 ) ; interner . internFunctorName ( \"true\" , 0 ) ; interner . internFunctorName ( \"fail\" , 0 ) ; interner . internFunctorName ( \"!\" , 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consumes a token of the expected kind from the token sequence . If the next token in the sequence is not of the expected kind an error will be raised . [CODESPLIT] protected Token consumeToken ( int kind ) throws SourceCodeException { Token nextToken = tokenSource . peek ( ) ; if ( nextToken . kind != kind ) { throw new SourceCodeException ( \"Was expecting \" + tokenImage [ kind ] + \" but got \" + tokenImage [ nextToken . kind ] + \".\" , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } else { nextToken = tokenSource . poll ( ) ; return nextToken ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Peeks ahead for the given token type and if one is foudn with that type it is consumed . [CODESPLIT] private boolean peekAndConsume ( int kind ) { Token nextToken = tokenSource . peek ( ) ; if ( nextToken . kind == kind ) { try { consumeToken ( kind ) ; } catch ( SourceCodeException e ) { // If the peek ahead kind can not be consumed then something strange has gone wrong so report this // as a bug rather than try to recover from it. throw new IllegalStateException ( e ) ; } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds the session as a transactional context to the current thread if it is not already bound . [CODESPLIT] public void bind ( ) { // If necessary create a fresh transaction id. if ( ( txId == null ) || ! txId . isValid ( ) ) { txId = TxManager . createTxId ( ) ; } // Bind the transaction to the current thread. TxManager . assignTxIdToThread ( txId ) ; // Bind this session to the current thread. threadSession . set ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Forgets pending operations . [CODESPLIT] public void rollback ( ) { // Rollback all soft resources. for ( Transactional enlist : enlists ) { enlist . rollback ( ) ; } // Clear all of the rolled back resources. enlists . clear ( ) ; // Invalidate the transaction id, so that a fresh transaction is begun. txId = TxManager . removeTxIdFromThread ( ) ; TxManager . invalidateTxId ( txId ) ; bind ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts all elements from an iterator usually created from a filterator and adds them into the target collection returning that collection as the result . [CODESPLIT] public static < T > Collection < T > collectIterator ( Iterator < T > iterator , Collection < T > targetCollection ) { while ( iterator . hasNext ( ) ) { targetCollection . add ( iterator . next ( ) ) ; } return targetCollection ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void emmitCode ( C compiled ) throws LinkageException { /*log.fine(\"public void emmitCode(C compiled): called\");*/ SizeableList < I > instructions = compiled . getInstructions ( ) ; // Get the call point for the code to write. CallPoint callPoint = resolveCallPoint ( compiled . getName ( ) ) ; if ( callPoint == null ) { /*log.fine(\"call point not resolved, reserving new one.\");*/ callPoint = reserveCallPoint ( compiled . getName ( ) , ( int ) instructions . sizeof ( ) ) ; } /*log.fine(\"insertion point = \" + getCodeInsertionPoint());*/ // Pass a reference to a buffer set to write to the call point in the code buffer on the encoder. instructionEncoder . setCodeBuffer ( getCodeBuffer ( callPoint ) ) ; // Loop over all instructions encoding them to byte code in the machines code buffer. for ( I instruction : instructions ) { instruction . accept ( instructionEncoder ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reserves a call point for a block of named callable code . The size of the block of code must be known fully in advance . If the named block already has a call point this will replace it with a new one . [CODESPLIT] public CallPoint reserveCallPoint ( int name , int length ) { // Work out where the code will go and advance the insertion point beyond its end, so that additional code // will be added beyond the reserved space. int address = getCodeInsertionPoint ( ) ; advanceCodeInsertionPoint ( length ) ; // Create a call point for the reserved space. CallPoint callPoint = new CallPoint ( address , length , name ) ; // Add the call point to the symbol table under the interned name. symbolTable . put ( name , getCallPointSymbolField ( ) , callPoint ) ; return callPoint ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a field by field timestamp into millisecond ticks . [CODESPLIT] public static long timestampToTicks ( int year , int month , int day , int hours , int minutes , int seconds , int milliseconds ) { boolean isLeapYear = isLeapYear ( year ) ; long dayComponent = ( long ) ( day - 1 ) * MILLIS_PER_DAY ; long monthComponent = millisToStartOfMonth ( month , isLeapYear ) ; long yearComponent = millisToYearStart ( year ) ; long hoursComponent = ( long ) hours * MILLIS_PER_HOUR ; long minutesComponent = ( long ) minutes * MILLIS_PER_MINUTE ; long secondsComponent = ( long ) seconds * MILLIS_PER_SECOND ; return dayComponent + monthComponent + yearComponent + hoursComponent + minutesComponent + secondsComponent + milliseconds ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a field by field timestamp into millisecond ticks . [CODESPLIT] public static long timestampToTicks ( int year , int month , int day ) { boolean isLeapYear = isLeapYear ( year ) ; long dayComponent = ( long ) ( day - 1 ) * MILLIS_PER_DAY ; long monthComponent = millisToStartOfMonth ( month , isLeapYear ) ; long yearComponent = millisToYearStart ( year ) ; return dayComponent + monthComponent + yearComponent ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a field by field time of day into millisecond ticks . [CODESPLIT] public static long timeOfDayToTicks ( int hour , int minute , int second , int millisecond ) { return millisecond + ( MILLIS_PER_SECOND * second ) + ( MILLIS_PER_MINUTE * minute ) + ( MILLIS_PER_HOUR * hour ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the years component of a time in millisecond ticks . [CODESPLIT] public static int ticksToYears ( long ticks ) { // The number of years is ticks floor divided by number of milliseconds in 365 1/4 days. //return flooredDiv(ticks, MILLIS_PER_REAL_YEAR) + 1970; //return flooredDiv(ticks + ((long)DAYS_TO_1970 * MILLIS_PER_DAY), MILLIS_PER_REAL_YEAR); long unitMillis = MILLIS_PER_YEAR / 2 ; long i2 = ( ticks >> 1 ) + ( ( 1970L * MILLIS_PER_YEAR ) / 2 ) ; if ( i2 < 0 ) { i2 = i2 - unitMillis + 1 ; } int year = ( int ) ( i2 / unitMillis ) ; long yearStart = millisToYearStart ( year ) ; long diff = ticks - yearStart ; if ( diff < 0 ) { year -- ; } else if ( diff >= ( MILLIS_PER_DAY * 365L ) ) { // One year may need to be added to fix estimate. long oneYear ; if ( isLeapYear ( year ) ) { oneYear = MILLIS_PER_DAY * 366L ; } else { oneYear = MILLIS_PER_DAY * 365L ; } yearStart += oneYear ; if ( yearStart <= ticks ) { year ++ ; } } return year ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the date ( day in month ) component of a time in millisecond ticks . [CODESPLIT] public static int ticksToDate ( long ticks ) { int year = ticksToYears ( ticks ) ; int month = ticksToMonths ( ticks ) ; long dayOffset = ticks ; dayOffset -= millisToYearStart ( year ) ; dayOffset -= isLeapYear ( year ) ? ( ( long ) LEAP_DAYS_IN_YEAR_PRIOR_TO_MONTH [ month - 1 ] * MILLIS_PER_DAY ) : ( ( long ) USUAL_DAYS_IN_YEAR_PRIOR_TO_MONTH [ month - 1 ] * MILLIS_PER_DAY ) ; return ( int ) ( dayOffset / MILLIS_PER_DAY ) + 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithHoursSetTo ( long ticks , int hours ) { long oldHours = ticksToHours ( ticks ) ; return ticks - ( oldHours * MILLIS_PER_HOUR ) + ( hours * MILLIS_PER_HOUR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the minutes component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithMinutesSetTo ( long ticks , int minutes ) { long oldMinutes = ticksToMinutes ( ticks ) ; return ticks - ( oldMinutes * MILLIS_PER_MINUTE ) + ( minutes * MILLIS_PER_MINUTE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the seconds component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithSecondsSetTo ( long ticks , int seconds ) { long oldSeconds = ticksToSeconds ( ticks ) ; return ticks - ( oldSeconds * MILLIS_PER_SECOND ) + ( seconds * MILLIS_PER_SECOND ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the year component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithYearSetTo ( long ticks , int year ) { int oldYear = ticksToYears ( ticks ) ; return ticks - millisToYearStart ( oldYear ) + millisToYearStart ( year ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the month component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithMonthSetTo ( long ticks , int month ) { int year = ticksToYears ( ticks ) ; boolean isLeapYear = isLeapYear ( year ) ; int oldMonth = ticksToMonths ( ticks ) ; return ticks - millisToStartOfMonth ( oldMonth , isLeapYear ) + millisToStartOfMonth ( month , isLeapYear ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the date component of the timestamp returning the new timestamp with updated component . [CODESPLIT] public static long ticksWithDateSetTo ( long ticks , int date ) { int oldDays = ticksToDate ( ticks ) ; return ticks - ( oldDays * MILLIS_PER_DAY ) + ( date * MILLIS_PER_DAY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the number of milliseconds to the start of the specified year taking 1970 as zero . [CODESPLIT] public static long millisToYearStart ( int year ) { // Calculate how many leap years elapsed prior to the year in question. int leapYears = year / 100 ; if ( year < 0 ) { leapYears = ( ( year + 3 ) >> 2 ) - leapYears + ( ( leapYears + 3 ) >> 2 ) - 1 ; } else { leapYears = ( year >> 2 ) - leapYears + ( leapYears >> 2 ) ; if ( isLeapYear ( year ) ) { leapYears -- ; } } return ( ( year * 365L ) + leapYears - DAYS_TO_1970 ) * MILLIS_PER_DAY ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a time of day with milliseconds in the format HH : MM : SS [ . sss ] into a byte buffer . The specified buffer will be enlarged if necessary using the specified byte buffer pool . [CODESPLIT] public static ByteBuffer putTimeOnlyAsString ( ByteBuffer buffer , long value ) { buffer = putTimeOnlyAsString ( buffer , value , true ) ; return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes only the time component of a time of day timestamp to a byte array in the following format : HH : MM : SS [ . sss ] . The millisecond value is optional and is only written if requested . If there is insufficient space in the buffer to write the value into then the buffer size is increased using the supplied byte buffer pool . [CODESPLIT] public static ByteBuffer putTimeOnlyAsString ( ByteBuffer buffer , long value , boolean includeMilliseconds ) { // Ensure there is sufficient space in the buffer for the date. int charsRequired = includeMilliseconds ? TIME_ONLY_LENGTH_WITH_MILLISECONDS : TIME_ONLY_LENGTH_WIHTOUT_MILLISECONDS ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToHours ( value ) , 2 ) ; buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ' ' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToMinutes ( value ) , 2 ) ; buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ' ' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToSeconds ( value ) , 2 ) ; if ( includeMilliseconds ) { buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ' ' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToMilliseconds ( value ) , 3 ) ; } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a millisecond timestamp that lands in a specified year calculate what month the timestamp corresponds to . [CODESPLIT] private static int getMonthOfYear ( long ticks , int year ) { int i = ( int ) ( ( ticks - millisToYearStart ( year ) ) >> 10 ) ; return ( isLeapYear ( year ) ) ? ( ( i < ( 182 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 91 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 31 * MILLIS_PER_DAY_OVER_1024 ) ) ? 1 : ( ( i < ( 60 * MILLIS_PER_DAY_OVER_1024 ) ) ? 2 : 3 ) ) : ( ( i < ( 121 * MILLIS_PER_DAY_OVER_1024 ) ) ? 4 : ( ( i < ( 152 * MILLIS_PER_DAY_OVER_1024 ) ) ? 5 : 6 ) ) ) : ( ( i < ( 274 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 213 * MILLIS_PER_DAY_OVER_1024 ) ) ? 7 : ( ( i < ( 244 * MILLIS_PER_DAY_OVER_1024 ) ) ? 8 : 9 ) ) : ( ( i < ( 305 * MILLIS_PER_DAY_OVER_1024 ) ) ? 10 : ( ( i < ( 335 * MILLIS_PER_DAY_OVER_1024 ) ) ? 11 : 12 ) ) ) ) : ( ( i < ( 181 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 90 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 31 * MILLIS_PER_DAY_OVER_1024 ) ) ? 1 : ( ( i < ( 59 * MILLIS_PER_DAY_OVER_1024 ) ) ? 2 : 3 ) ) : ( ( i < ( 120 * MILLIS_PER_DAY_OVER_1024 ) ) ? 4 : ( ( i < ( 151 * MILLIS_PER_DAY_OVER_1024 ) ) ? 5 : 6 ) ) ) : ( ( i < ( 273 * MILLIS_PER_DAY_OVER_1024 ) ) ? ( ( i < ( 212 * MILLIS_PER_DAY_OVER_1024 ) ) ? 7 : ( ( i < ( 243 * MILLIS_PER_DAY_OVER_1024 ) ) ? 8 : 9 ) ) : ( ( i < ( 304 * MILLIS_PER_DAY_OVER_1024 ) ) ? 10 : ( ( i < ( 334 * MILLIS_PER_DAY_OVER_1024 ) ) ? 11 : 12 ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads some number of bytes from the input stream and stores them into the buffer array b . The bytes are also returned wrapped in a byte block so that they can be returnd over RMI . [CODESPLIT] public ByteBlock read ( byte [ ] b ) throws IOException { int count = source . read ( b ) ; return new ByteBlock ( b , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads up to len bytes of data from the input stream into an array of bytes . [CODESPLIT] public ByteBlock read ( byte [ ] b , int off , int len ) throws IOException { int count = source . read ( b , off , len ) ; return new ByteBlock ( b , count ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean containsKey ( K key ) { int keyHashCode = key . hashCode ( ) ; int hash1 = hash1 ( keyHashCode ) ; Entry < K > entry = hashTable [ indexFor ( hash1 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return true ; } entry = hashTable [ indexFor ( hash2 ( hash1 , keyHashCode ) ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Integer remove ( Object objectKey ) { K key = ( K ) objectKey ; int keyHashCode = key . hashCode ( ) ; int hash1 = hash1 ( keyHashCode ) ; int index1 = indexFor ( hash1 ) ; Entry < K > entry = hashTable [ index1 ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { hashTable [ index1 ] = null ; return entry . seq ; } int hash2 = hash2 ( hash1 , keyHashCode ) ; int index2 = indexFor ( hash2 ) ; entry = hashTable [ index2 ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { hashTable [ index2 ] = null ; return entry . seq ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void clear ( ) { count = 0 ; nextSequenceNumber = 0 ; hashTable = ( Entry < K > [ ] ) new Entry [ hashTableSize ] ; length = hashTable . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up the specified key in hash table using cuckoo hashing . If the key cannot be found in the table then the next available sequence number is allocated to it and a new entry is added to the hash table for the key again using cuckoo hashing . [CODESPLIT] private Integer applyWithEntry ( K key , Entry < K > entry , boolean tryRehashing ) { // Used to hold a new entry if one has to be created, or can re-use an entry passed in as a parameter. Entry < K > uninsertedEntry = entry ; // Holds a flag to indicate that a new sequence number has been taken. boolean createdNewEntry = false ; // Check if there is already an entry for the key, and return it if so. Entry < K > existingEntry = entryForKey ( key ) ; Integer result = null ; if ( existingEntry != null ) { result = existingEntry . seq ; } else { // Create a new entry, if one has not already been created and cached. if ( uninsertedEntry == null ) { uninsertedEntry = new Entry < K > ( ) ; uninsertedEntry . key = key ; uninsertedEntry . seq = nextSequenceNumber ; nextSequenceNumber ++ ; count ++ ; createdNewEntry = true ; result = uninsertedEntry . seq ; } // Attempt to insert the new entry. The sequence number is only incremented when this succeeds for a new // entry. Existing entries that are being re-hashed into a new table will not increment the sequence // number. while ( true ) { // Hash the entry for the current hash functions. int keyHashCode = uninsertedEntry . key . hashCode ( ) ; uninsertedEntry . hash1 = hash1 ( keyHashCode ) ; uninsertedEntry . hash2 = hash2 ( uninsertedEntry . hash1 , keyHashCode ) ; // Try and insert the entry, checking that no entry is left uninserted as a result. uninsertedEntry = cuckoo ( uninsertedEntry ) ; if ( uninsertedEntry == null ) { result = createdNewEntry ? result : - 1 ; break ; } // If the cuckoo algorithm fails then change the hash function/table size and try again. if ( tryRehashing ) { rehash ( ) ; } else { result = null ; break ; } } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the specified key can be found in the set and returns its entry if so . [CODESPLIT] private Entry < K > entryForKey ( K key ) { int keyHashCode = key . hashCode ( ) ; int hash1 = hash1 ( keyHashCode ) ; Entry < K > entry = hashTable [ indexFor ( hash1 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return entry ; } int hash2 = hash2 ( hash1 , keyHashCode ) ; entry = hashTable [ indexFor ( hash2 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return entry ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new entry to a hash table using the cuckoo algorithm . [CODESPLIT] private Entry < K > cuckoo ( Entry < K > entry ) { // Holds the entry currently being placed in the hash table. Entry < K > currentEntry = entry ; // Holds the index into the hash table where the current entry will be placed. int hash = entry . hash1 ; int index = indexFor ( hash ) ; Entry < K > nextEntry = hashTable [ index ] ; int previousFlag = 0 ; int [ ] previousIndex = new int [ 2 ] ; int [ ] previousSeq = new int [ 2 ] ; for ( int i = 0 ; i < hashTableSize ; i ++ ) { // Check the current index, to see if it is an empty slot. If it is an empty slot then the current // entry is placed there and the algorithm completes. if ( nextEntry == null ) { hashTable [ index ] = currentEntry ; return null ; } // If the current index does not point to an empty slot, the current entry is placed there anyway, but the // displaced entry (the egg displaced by the cuckoo) becomes the current entry for placing. hashTable [ index ] = currentEntry ; currentEntry = nextEntry ; // A new index is selected depending on whether the entry is currently at its primary or secondary hashing. int firstPosition = indexFor ( currentEntry . hash1 ) ; hash = ( index == firstPosition ) ? currentEntry . hash2 : currentEntry . hash1 ; index = indexFor ( hash ) ; // A check for infinite loops of size 2 is made here, to circumvent the simplest and most common infinite // looping condition. previousIndex [ previousFlag ] = index ; previousSeq [ previousFlag ] = nextEntry . seq ; previousFlag = ( previousFlag == 1 ) ? 0 : 1 ; nextEntry = hashTable [ index ] ; if ( ( nextEntry != null ) && ( index == previousIndex [ previousFlag ] ) && ( nextEntry . seq == previousSeq [ previousFlag ] ) ) { break ; } } return currentEntry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new hashtable that is twice the size of the old one then re - hashes everything from the old table into the new table . [CODESPLIT] private void rehash ( ) { // Increase the table size, to keep the load factory < 0.5. int newSize = hashTableSize ; if ( hashTableSize < ( count * 2 ) ) { newSize = hashTableSize * 2 ; if ( newSize > maxSize ) { throw new IllegalStateException ( \"'newSize' of \" + newSize + \" would put the table over the maximum size limit of \" + maxSize ) ; } } // Keep hold of the old table, until a new one is succesfully buily. Entry < K > [ ] oldTable = hashTable ; hashTableSize = newSize ; length = hashTable . length ; // Keep rehashing the table until it is succesfully rebuilt. boolean rehashedOk ; do { // Start by assuming that this will work. rehashedOk = true ; // Alter the hash functions. changeHashFunctions ( ) ; // Create a new table from the old one, to rehash everything into. hashTable = ( Entry < K > [ ] ) new Entry [ hashTableSize ] ; for ( Entry < K > entry : oldTable ) { if ( entry != null ) { // Add the entry to the new table, dropping out if this fails. if ( applyWithEntry ( entry . key , entry , false ) == null ) { rehashedOk = false ; break ; } } } } while ( ! rehashedOk ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements Robert Jenkins 32 - bit integer hash function . <a href = http : // www . concentric . net / ~Ttwang / tech / inthash . htm / > http : // www . concentric . net / ~Ttwang / tech / inthash . htm< / a > [CODESPLIT] private int hash1 ( int key ) { key += hash1seed ; key = ( key + 0x7ed55d16 ) + ( key << 12 ) ; key = ( key ^ 0xc761c23c ) ^ ( key >> 19 ) ; key = ( key + 0x165667b1 ) + ( key << 5 ) ; key = ( key + 0xd3a2646c ) ^ ( key << 9 ) ; key = ( key + 0xfd7046c5 ) + ( key << 3 ) ; key = ( key ^ 0xb55a4f09 ) ^ ( key >> 16 ) ; return key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Thomas Wang s 32 - bit shift hash function . <a href = http : // www . concentric . net / ~Ttwang / tech / inthash . htm / > http : // www . concentric . net / ~Ttwang / tech / inthash . htm< / a > [CODESPLIT] private int hash32shift ( int key ) { key += hash2seed ; key = ~ key + ( key << 15 ) ; key = key ^ ( key >>> 12 ) ; key = key + ( key << 2 ) ; key = key ^ ( key >>> 4 ) ; key = key * 2057 ; key = key ^ ( key >>> 16 ) ; return key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements a secondary hash . This uses the 32 - bit shift hash implemented by { @link #hash32shift ( int ) } and then successively applies { @link #hash1 ( int ) } if the generated hash code is not different to the hash code generated by running { @link #hash1 ( int ) } on the key . This ensures that the hash code returned by this will be different to the one generated by { @link #hash1 ( int ) } . [CODESPLIT] private int hash2 ( int hash1 , int key ) { key = hash32shift ( key ) ; while ( key == hash1 ) { key = hash32shift ( key ) ; } return key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void layoutContainer ( Container parent ) { JViewport vp = ( JViewport ) parent ; Component view = vp . getView ( ) ; if ( view == null ) { return ; } Point viewPosition = vp . getViewPosition ( ) ; Dimension viewPrefSize = view . getPreferredSize ( ) ; Dimension vpSize = vp . getSize ( ) ; Dimension viewSize = new Dimension ( viewPrefSize ) ; if ( ( viewPosition . x == 0 ) && ( vpSize . width > viewPrefSize . width ) ) { viewSize . width = vpSize . width ; } if ( ( viewPosition . y == 0 ) && ( vpSize . height > viewPrefSize . height ) ) { viewSize . height = vpSize . height ; } if ( ! viewSize . equals ( viewPrefSize ) ) { vp . setViewSize ( viewSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listens for the button events Ok Cancel and Apply . If the event is Ok or Apply the saveWork method is triggered . If the event is Cancel then the discardWork method is triggered . [CODESPLIT] public void actionPerformed ( ActionEvent event ) { /*log.fine(\"void actionPerformed(ActionEvent): called\");*/ /*log.fine(\"Action is \" + event.getActionCommand());*/ // Check which action was performed String action = event . getActionCommand ( ) ; if ( \"OK\" . equals ( action ) ) { // Check if the state is NOT_SAVED if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Save the work saveWork ( ) ; } } else if ( \"Cancel\" . equals ( action ) ) { // Check if the state is NOT_SAVED if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Discard the work discardWork ( ) ; } } else if ( \"Apply\" . equals ( action ) ) { // Check if the state is NOT_SAVED if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Save the work saveWork ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the state of the next available flag and notifies any listeners of this change . [CODESPLIT] public void setNextAvailable ( boolean avail ) { // Check if the state has changed if ( nextAvailable != avail ) { // Keep the new state nextAvailable = avail ; // Notify any listeners fo the change in state firePropertyChange ( new PropertyChangeEvent ( this , \"nextAvailable\" , ! avail , avail ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the state of the previous available flag and notifies any listeners of this change . [CODESPLIT] public void setPrevAvailable ( boolean avail ) { // Check if the state has changed if ( prevAvailable != avail ) { // Keep the new state prevAvailable = avail ; // Notify any listeners fo the change in state firePropertyChange ( new PropertyChangeEvent ( this , \"prevAvailable\" , ! avail , avail ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the state of the finished and notifies any listeners of this change . [CODESPLIT] public void setFinished ( boolean avail ) { /*log.fine(\"void setFinished(boolean): called\");*/ // Check if the state has changed if ( finished != avail ) { // Keep the new state finished = avail ; // Notify any listeners fo the change in state firePropertyChange ( new PropertyChangeEvent ( this , \"finished\" , ! avail , avail ) ) ; /*log.fine(\"fired property change event\");*/ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of this machine loading and checking for availability of the native implementation library as required . [CODESPLIT] public static WAMResolvingNativeMachine getInstance ( SymbolTableImpl < Integer , String , Object > symbolTable ) throws ImplementationUnavailableException { try { if ( ! libraryLoadAttempted ) { libraryLoadAttempted = true ; System . loadLibrary ( \"aima_native\" ) ; libraryFound = true ; } if ( libraryFound ) { return new WAMResolvingNativeMachine ( symbolTable ) ; } else { throw new ImplementationUnavailableException ( \"The native library could not be found.\" , null , null , null ) ; } } catch ( UnsatisfiedLinkError e ) { libraryFound = false ; throw new ImplementationUnavailableException ( \"The native library could not be found.\" , e , null , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an iterator that generates all solutions on demand as a sequence of variable bindings . [CODESPLIT] public Iterator < Set < Variable > > iterator ( ) { return new SequenceIterator < Set < Variable > > ( ) { public Set < Variable > nextInSequence ( ) { return resolve ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given set of probabilities of the occurences of symbols this function calculates the expected information content of a set of symbols given its probability distribution . The answer is expressed as a positive number of bits . [CODESPLIT] public static double expectedI ( double [ ] probabilities ) { double result = 0.0d ; // Loop over the probabilities for all the symbols calculating the contribution of each to the expected value. for ( double p : probabilities ) { // Calculate the information in each symbol. I(p) = - ln p and weight this by its probability of occurence // to get that symbols contribution to the expected value over all symbols. if ( p > 0.0d ) { result -= p * Math . log ( p ) ; } } // Convert the result from nats to bits by dividing by ln 2. return result / LN2 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supposing a stream generates pairs of symbols . Let the first be A and the second be G . A ranges over a set of symbols { h1 ... hv } and G ranges over a set of symbols { g1 ... gn } . [CODESPLIT] public static double remainder ( double [ ] pA , double [ ] [ ] pGgivenA ) { double result = 0.0d ; // Loop over the probabilities for all the symbols of A calculating the contribution of each to // the expected value. for ( int v = 0 ; v < pA . length ; v ++ ) { double phv = pA [ v ] ; // Calculate the expected information content of the distribution of the symbols of G given the symbol hv // and scale its contribution to the total by the probability of hv occuring. result += phv * expectedI ( pGgivenA [ v ] ) ; } // There is no need to convert the result from nats to bits and the expected information function is // already in bits. return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Estimates probabilities given a set of counts of occurrences of symbols . [CODESPLIT] public static double [ ] pForDistribution ( int [ ] counts ) { double [ ] probabilities = new double [ counts . length ] ; int total = 0 ; // Loop over the counts for all symbols adding up the total number. for ( int c : counts ) { total += c ; } // Loop over the counts for all symbols dividing by the total number to provide a probability estimate. for ( int i = 0 ; i < probabilities . length ; i ++ ) { if ( total > 0 ) { probabilities [ i ] = ( ( double ) counts [ i ] ) / total ; } else { probabilities [ i ] = 0.0d ; } } return probabilities ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supposing a stream generates pairs of symbols . Let the first be A and the second be G . A ranges over a set of symbols { h1 ... hv } and G ranges over a set of symbols { g1 ... gn } . [CODESPLIT] public static double [ ] [ ] pForJointDistribution ( int [ ] [ ] counts ) { double [ ] [ ] results = new double [ counts . length ] [  ] ; // Loop over all the symbols of A for ( int i = 0 ; i < counts . length ; i ++ ) { // Extract the next distribution array of the symbols of G given A. int [ ] countsGgivenA = counts [ i ] ; // Convert the frequency distribution into a probability distribution and add it to the results. results [ i ] = pForDistribution ( countsGgivenA ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof LiteralTypeVisitor ) { ( ( LiteralTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int compareTo ( DateOnly o ) { if ( year < o . year ) { return - 1 ; } else if ( year > o . year ) { return 1 ; } else if ( month < o . month ) { return - 1 ; } else if ( month > o . month ) { return 1 ; } else if ( day < o . day ) { return - 1 ; } else if ( day > o . day ) { return 1 ; } else { return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets this date from a milliseconds timestamp . [CODESPLIT] void setTicks ( long ticks ) { year = TimeUtils . ticksToYears ( ticks ) ; month = TimeUtils . ticksToMonths ( ticks ) ; day = TimeUtils . ticksToDate ( ticks ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recreate internal state before children are cloned . [CODESPLIT] @ Override protected void cloneChildren ( InternalNode node ) { SelectorNode selector = ( SelectorNode ) node ; // Reset internal state selector . setAdditionVisitor ( ) ; super . cloneChildren ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the action . [CODESPLIT] public ActionForward perform ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { log . fine ( \"perform: called\" ) ; // Reference the SortForm as a SortForm rather than the generic ActionForm SortForm sortForm = ( SortForm ) form ; // Get a reference to the session scope HttpSession session = request . getSession ( ) ; // Get a reference to the application scope ServletContext application = session . getServletContext ( ) ; log . fine ( \"variables in the servlet context: \" ) ; for ( Enumeration e = application . getAttributeNames ( ) ; e . hasMoreElements ( ) ; ) { log . fine ( e . nextElement ( ) . toString ( ) ) ; } // Get a reference to the list to be sorted List list = ( List ) session . getAttribute ( sortForm . getList ( ) ) ; // Get a reference to the comparator from the application scope to use to perform the sort Comparator comparator = ( Comparator ) application . getAttribute ( sortForm . getComparator ( ) ) ; log . fine ( \"comparator = \" + comparator ) ; // Get a reference to the current sort state (if there is one) SortStateBean sortStateBean = ( SortStateBean ) session . getAttribute ( sortForm . getSortState ( ) ) ; // Check if there is no sort state bean and create one if so if ( sortStateBean == null ) { log . fine ( \"There is no sort state bean\" ) ; sortStateBean = new SortStateBean ( ) ; } // Determine whether a forward or reverse sort is to be done // If its reverse sorted, unsorted or not sorted by the current sort property then forward sort it if ( ! sortStateBean . getState ( ) . equals ( SortStateBean . FORWARD ) || ! sortStateBean . getSortProperty ( ) . equals ( sortForm . getSortStateProperty ( ) ) ) { // Sort the list Collections . sort ( list , comparator ) ; // Update the current sort state sortStateBean . setState ( SortStateBean . FORWARD ) ; } // If its already forward sorted then reverse sort it else { // Sort the list Collections . sort ( list , comparator ) ; // Reverse the list Collections . reverse ( list ) ; // Update the current sort state sortStateBean . setState ( SortStateBean . REVERSE ) ; } // Store the sorted list in the variable from which the original list was taken session . setAttribute ( sortForm . getList ( ) , list ) ; // Store the new sort state, setting the property that has been sorted by in the sort state sortStateBean . setSortProperty ( sortForm . getSortStateProperty ( ) ) ; session . setAttribute ( sortForm . getSortState ( ) , sortStateBean ) ; // Forward to the success page return ( mapping . findForward ( \"success\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks but does not enforce the throttle rate . When this method is called it checks if a length of time greater than that equal to the inverse of the throttling rate has passed since it was last called and returned <tt > true< / tt > . If the length of time still to elapse to the next throttle allow point is zero or less this method will return a negative value if there is still time to pass until the throttle allow point this method will return a positive value indicating the amount of time still to pass . A thread can wait for that period of time before rechecking the throttle condition . [CODESPLIT] public long timeToThrottleNanos ( ) { // Work out how long ago the last throttle query was. long currentTimeNanos = System . nanoTime ( ) ; long delay = currentTimeNanos - lastTimeNanos ; // Regenerate the tokens allowed since the last query. float numTokens = ( delay * 1.0e9f ) * targetRate ; tokenCount -= numTokens ; if ( tokenCount < 0f ) { tokenCount = 0f ; } // Update the last time stamp for next time around. lastTimeNanos = currentTimeNanos ; // Check if there are tokens available to consume, and consume one if so. if ( tokenCount <= ( depth - 1.0 ) ) { tokenCount += 1.0 ; return 0 ; } else { // There are no tokens to consume, so return an estimate of how long it will take to generate one token. return ( long ) ( 1.0e9 / targetRate ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a URL for the specified string representation . [CODESPLIT] public static URL newUrl ( String spec ) { try { return new URL ( spec ) ; } catch ( MalformedURLException exception ) { throw new IllegalArgumentException ( \"Invalid URL: \" + spec ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all basic request information in an HTML table . [CODESPLIT] public String getRequestInfo ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; info . put ( \"authType\" , nullToString ( req . getAuthType ( ) ) ) ; info . put ( \"characterEncoding\" , nullToString ( req . getCharacterEncoding ( ) ) ) ; info . put ( \"contentLength\" , Integer . toString ( req . getContentLength ( ) ) ) ; info . put ( \"contentType\" , nullToString ( req . getContentType ( ) ) ) ; info . put ( \"contextPath\" , nullToString ( req . getContextPath ( ) ) ) ; info . put ( \"pathInfo\" , nullToString ( req . getPathInfo ( ) ) ) ; info . put ( \"protocol\" , nullToString ( req . getProtocol ( ) ) ) ; info . put ( \"queryString\" , nullToString ( req . getQueryString ( ) ) ) ; info . put ( \"remoteAddr\" , nullToString ( req . getRemoteAddr ( ) ) ) ; info . put ( \"remoteHost\" , nullToString ( req . getRemoteHost ( ) ) ) ; info . put ( \"remoteUser\" , nullToString ( req . getRemoteUser ( ) ) ) ; info . put ( \"requestURI\" , nullToString ( req . getRequestURI ( ) ) ) ; info . put ( \"scheme\" , nullToString ( req . getScheme ( ) ) ) ; info . put ( \"serverName\" , nullToString ( req . getServerName ( ) ) ) ; info . put ( \"serverPort\" , Integer . toString ( req . getServerPort ( ) ) ) ; info . put ( \"servletPath\" , nullToString ( req . getServletPath ( ) ) ) ; return toHTMLTable ( \"request properties\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all header information as an HTML table . [CODESPLIT] public String getHeaders ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getHeaderNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Enumeration values = req . getHeaders ( name ) ; StringBuffer sb = new StringBuffer ( ) ; boolean first = true ; while ( values . hasMoreElements ( ) ) { if ( ! first ) { sb . append ( \" | \" ) ; } first = false ; sb . append ( values . nextElement ( ) ) ; } info . put ( name , sb . toString ( ) ) ; } return toHTMLTable ( \"headers\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all cookie information as an HTML table . [CODESPLIT] public String getCookies ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Cookie [ ] cookies = req . getCookies ( ) ; // check that cookies is not null which it may be if there are no cookies if ( cookies != null ) { for ( int i = 0 ; i < cookies . length ; i ++ ) { Cookie cooky = cookies [ i ] ; info . put ( cooky . getName ( ) , cooky . getValue ( ) ) ; } } return toHTMLTable ( \"cookies\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all request parameter information . [CODESPLIT] public String getParameters ( ) { Map info = new TreeMap ( ) ; ServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getParameterNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; String [ ] values = req . getParameterValues ( name ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < values . length ; i ++ ) { if ( i != 0 ) { sb . append ( \" | \" ) ; } sb . append ( values [ i ] ) ; } info . put ( name , sb . toString ( ) ) ; } return toHTMLTable ( \"request parameters\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all request scope variables . [CODESPLIT] public String getRequestScope ( ) { Map info = new TreeMap ( ) ; ServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = req . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( \"request scope\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all page scope variables . [CODESPLIT] public String getPageScope ( ) { Map info = new TreeMap ( ) ; Enumeration names = pageContext . getAttributeNamesInScope ( PageContext . PAGE_SCOPE ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = pageContext . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( \"page scope\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all session scope variables . [CODESPLIT] public String getSessionScope ( ) { Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; HttpSession session = req . getSession ( ) ; Enumeration names = session . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = session . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( \"session scope\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a String with all application scope variables . [CODESPLIT] public String getApplicationScope ( ) { Map info = new TreeMap ( ) ; ServletContext context = pageContext . getServletContext ( ) ; Enumeration names = context . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = context . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( \"application scope\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the user principal name . [CODESPLIT] public String getUserPrincipal ( ) { // Create a hash table to hold the results in Map info = new TreeMap ( ) ; // Extract the request from the page context HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; // Get the principal from the request Principal principal = request . getUserPrincipal ( ) ; // Check if there is a principal if ( principal != null ) { info . put ( \"principal name\" , principal . getName ( ) ) ; } else { info . put ( \"principal name\" , \"no principal\" ) ; } // Convert the results to an HTML table return toHTMLTable ( \"container security\" , info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the debugging message . [CODESPLIT] public int doStartTag ( ) throws JspException { log . fine ( \"doStartTag: called\" ) ; try { // Write out the beggining of the debug table pageContext . getResponse ( ) . getWriter ( ) . write ( \"<table class=\\\"debug\\\" width=\\\"100%\\\" border=\\\"1\\\">\" ) ; // Write out the debugging info for all categories pageContext . getResponse ( ) . getWriter ( ) . write ( getRequestInfo ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getHeaders ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getCookies ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getParameters ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getRequestScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getPageScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getSessionScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getApplicationScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getUserPrincipal ( ) ) ; // Write out the closing of the debug table pageContext . getResponse ( ) . getWriter ( ) . write ( \"</table>\" ) ; } catch ( IOException e ) { throw new JspException ( \"Got an IOException whilst writing the debug tag to the page.\" , e ) ; } // Continue processing the page return ( EVAL_BODY_INCLUDE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an HTML table with all the values of the specified property . [CODESPLIT] private String toHTMLTable ( String propName , Map values ) { StringBuffer tableSB = new StringBuffer ( ) ; tableSB . append ( \"<tr class=\\\"debug\\\"><th class=\\\"debug\\\">\" ) . append ( propName ) . append ( \"</th></tr>\" ) ; for ( Iterator it = values . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Object o = it . next ( ) ; String key = ( String ) o ; tableSB . append ( \"<tr class=\\\"debug\\\"><td class=\\\"debug\\\">\" ) . append ( key ) . append ( \"</td><td>\" ) . append ( values . get ( key ) ) . append ( \"</td></tr>\" ) ; } return tableSB . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a string representation of the specified object in a format suitable for debug output . If the object is an array all its elements are extracted and displayed seperated by commas . Other objects are converted to strings by their toString methods . [CODESPLIT] private String toStringValue ( Object value ) { // Check if the value is null if ( value == null ) { return \"null\" ; } StringBuffer sb = new StringBuffer ( ) ; Class type = value . getClass ( ) ; if ( type . isArray ( ) ) { Class componentType = type . getComponentType ( ) ; sb . append ( componentType . getName ( ) ) ; sb . append ( \"[]: {\" ) ; if ( ! componentType . isPrimitive ( ) ) { Object [ ] arr = ( Object [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Boolean . TYPE ) { boolean [ ] arr = ( boolean [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Byte . TYPE ) { byte [ ] arr = ( byte [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Character . TYPE ) { char [ ] arr = ( char [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Double . TYPE ) { double [ ] arr = ( double [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Float . TYPE ) { float [ ] arr = ( float [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Integer . TYPE ) { int [ ] arr = ( int [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Long . TYPE ) { long [ ] arr = ( long [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Short . TYPE ) { short [ ] arr = ( short [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( \", \" ) ; } sb . append ( arr [ i ] ) ; } } sb . append ( \"}\" ) ; } else { // Obtain the objects value using toString, but protect this against null pointer exceptions, to harden // this implementation. String stringValue = null ; try { stringValue = value . toString ( ) ; } catch ( NullPointerException e ) { stringValue = \"\" ; } sb . append ( value . getClass ( ) . getName ( ) ) . append ( \": \" ) . append ( stringValue ) ; } return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Searches all SearchNodes less than the maximum bound for some property of the nodes . [CODESPLIT] public SearchNode search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { // Initialize the queue with the start states set up in search nodes. Queue < SearchNode < O , T > > queue = initSearch . enqueueStartStates ( startStates ) ; // Get the goal predicate configured as part of the enqueueing start states process. UnaryPredicate < T > goalPredicate = initSearch . getGoalPredicate ( ) ; // Flag used to indicate whether there are unexplored successor states known to exist beyond the max depth // fringe. boolean beyondFringe = false ; // Reset the minimum beyond the fringe boundary value. minBeyondBound = Float . POSITIVE_INFINITY ; // Keep running until the queue becomes empty or a goal state is found. while ( ! queue . isEmpty ( ) ) { // Extract the head element from the queue. SearchNode < O , T > headNode = peekAtHead ? queue . peek ( ) : queue . remove ( ) ; // Expand the successors into the queue whether the current node is a goal state or not. // This prepares the queue for subsequent searches, ensuring that goal states do not block // subsequent goal states that exist beyond them. // Add the successors to the queue provided that they are below or at the maximum bounded property. // Get all the successor states. Queue < SearchNode < O , T > > successors = new LinkedList < SearchNode < O , T > > ( ) ; headNode . expandSuccessors ( successors , reverseEnqueue ) ; // Loop over all the successor states checking how they stand with respect to the bounded property. for ( SearchNode < O , T > successor : successors ) { // Get the value of the bound property for the successor node. float boundProperty = boundPropertyExtractor . getBoundProperty ( successor ) ; // Check if the successor is below or on the bound. if ( boundProperty <= maxBound ) { // Add it to the queue to be searched. queue . offer ( successor ) ; } // The successor state is above the bound. else { // Set the flag to indicate that there is at least one search node known to exist beyond the // bound. beyondFringe = true ; // Compare to the best minimum beyond the bound property found so far to see if // this is a new minimum and update the minimum to the new minimum if so. minBeyondBound = ( boundProperty < minBeyondBound ) ? boundProperty : minBeyondBound ; } } // Get the node to be goal checked, either the head node or the new top of queue, depending on the // peek at head flag. SearchNode < O , T > currentNode = peekAtHead ? queue . remove ( ) : headNode ; // Check if the current node is a goal state. // Only goal check leaves, or nodes already expanded. (The expanded flag will be set on leaves anyway). if ( currentNode . isExpanded ( ) && goalPredicate . evaluate ( currentNode . getState ( ) ) ) { return currentNode ; } // Check if there is a maximum number of steps limit and increase the step count and check the limit if so. if ( maxSteps > 0 ) { // Increase the search step count because a goal test was performed. searchSteps ++ ; // Update the search state with the number of steps taken so far. initSearch . setStepsTaken ( searchSteps ) ; if ( searchSteps >= maxSteps ) { // The maximum number of steps has been reached, however if the queue is now empty then the search // has just completed within the maximum. Check if the queue is empty and return null if so. if ( queue . isEmpty ( ) ) { return null ; } // Quit without a solution as the max number of steps has been reached but because there are still // more states in the queue then raise a search failure exception. else { throw new SearchNotExhaustiveException ( \"Maximum number of steps reached.\" , null ) ; } } } } // No goal state was found. Check if there known successors beyond the max depth fringe and if so throw // a SearchNotExhaustiveException to indicate that the search failed rather than exhausted the search space. if ( beyondFringe ) { throw new MaxBoundException ( \"Max bound reached.\" , null ) ; } else { // The search space was exhausted so return null to indicate that no goal could be found. return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the new current screen state and notifies all listeners of the change in screen state . [CODESPLIT] public void setCurrentScreenState ( WorkFlowScreenState state ) { /*log.fine(\"void setCurrentScreenState(WorkFlowScreenState): called\");*/ WorkFlowScreenState oldState = currentScreenState ; // Keep the new state. currentScreenState = state ; // Notify all listeners of the change of current screen. firePropertyChange ( new PropertyChangeEvent ( this , \"currentScreenState\" , oldState , state ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walks over the supplied term . [CODESPLIT] public void walk ( Term term ) { // Set up the traverser on the term to walk over. term . setTermTraverser ( traverser ) ; // Create a fresh search starting from the term. search . reset ( ) ; if ( goalPredicate != null ) { search . setGoalPredicate ( goalPredicate ) ; } search . addStartState ( term ) ; Iterator < Term > treeWalker = Searches . allSolutions ( search ) ; // If the traverser is a term visitor, allow it to visit the top-level term in the walk to establish // an initial context. if ( traverser instanceof TermVisitor ) { term . accept ( ( TermVisitor ) traverser ) ; } // Visit every goal node discovered in the walk over the term. while ( treeWalker . hasNext ( ) ) { Term nextTerm = treeWalker . next ( ) ; nextTerm . accept ( visitor ) ; } // Remote the traverser on the term to walk over. term . setTermTraverser ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two heuristic search nodes by their f values . [CODESPLIT] public int compare ( SearchNode object1 , SearchNode object2 ) { float f1 = ( ( HeuristicSearchNode ) object1 ) . getF ( ) ; float f2 = ( ( HeuristicSearchNode ) object2 ) . getF ( ) ; return ( f1 > f2 ) ? 1 : ( ( f1 < f2 ) ? - 1 : 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the register file with a new set of registers . [CODESPLIT] public void updateRegisters ( WAMInternalRegisters registers ) { List < PropertyChangeEvent > changes = delta ( this , registers ) ; ip = registers . ip ; hp = registers . hp ; hbp = registers . hbp ; sp = registers . sp ; up = registers . up ; ep = registers . ep ; bp = registers . bp ; b0 = registers . b0 ; trp = registers . trp ; writeMode = registers . writeMode ; notifyChanges ( changes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the current register file with a new set and creates a list property change notifications for any that have changed value . [CODESPLIT] private List < PropertyChangeEvent > delta ( WAMInternalRegisters oldRegisters , WAMInternalRegisters newRegisters ) { List < PropertyChangeEvent > result = new LinkedList < PropertyChangeEvent > ( ) ; if ( oldRegisters . ip != newRegisters . ip ) { result . add ( new PropertyChangeEvent ( this , \"IP\" , oldRegisters . ip , newRegisters . ip ) ) ; } if ( oldRegisters . hp != newRegisters . hp ) { result . add ( new PropertyChangeEvent ( this , \"HP\" , oldRegisters . hp , newRegisters . hp ) ) ; } if ( oldRegisters . hbp != newRegisters . hbp ) { result . add ( new PropertyChangeEvent ( this , \"HBP\" , oldRegisters . hbp , newRegisters . hbp ) ) ; } if ( oldRegisters . sp != newRegisters . sp ) { result . add ( new PropertyChangeEvent ( this , \"SP\" , oldRegisters . sp , newRegisters . sp ) ) ; } if ( oldRegisters . up != newRegisters . up ) { result . add ( new PropertyChangeEvent ( this , \"UP\" , oldRegisters . up , newRegisters . up ) ) ; } if ( oldRegisters . ep != newRegisters . ep ) { result . add ( new PropertyChangeEvent ( this , \"EP\" , oldRegisters . ep , newRegisters . ep ) ) ; } if ( oldRegisters . bp != newRegisters . bp ) { result . add ( new PropertyChangeEvent ( this , \"BP\" , oldRegisters . bp , newRegisters . bp ) ) ; } if ( oldRegisters . b0 != newRegisters . b0 ) { result . add ( new PropertyChangeEvent ( this , \"B0\" , oldRegisters . b0 , newRegisters . b0 ) ) ; } if ( oldRegisters . trp != newRegisters . trp ) { result . add ( new PropertyChangeEvent ( this , \"TRP\" , oldRegisters . trp , newRegisters . trp ) ) ; } if ( oldRegisters . writeMode != newRegisters . writeMode ) { result . add ( new PropertyChangeEvent ( this , \"writeMode\" , oldRegisters . writeMode , newRegisters . writeMode ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires off a list of property change events to any interested listeners . [CODESPLIT] private void notifyChanges ( Iterable < PropertyChangeEvent > changes ) { List < PropertyChangeListener > activeListeners = listeners . getActiveListeners ( ) ; if ( activeListeners != null ) { for ( PropertyChangeListener listener : activeListeners ) { for ( PropertyChangeEvent event : changes ) { listener . propertyChange ( event ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void insert ( char character , int c , int r ) { parent . insert ( character , c + column , r + row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void insert ( String string , int c , int r ) { parent . insert ( string , c + column , r + row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public TextGridModel createInnerGrid ( int c , int r , int w , int h ) { return parent . createInnerGrid ( c + column , r + row , w , h ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public TextTableModel createTable ( int c , int r , int w , int h ) { return parent . createTable ( c + column , r + row , w , h ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] protected void enterVariable ( Variable variable ) { // Initialize the count to one or add one to an existing count. Integer count = ( Integer ) symbolTable . get ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_OCCURRENCE_COUNT ) ; count = ( count == null ) ? 1 : ( count + 1 ) ; symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_OCCURRENCE_COUNT , count ) ; /*log.fine(\"Variable \" + variable + \" has count \" + count + \".\");*/ // Get the nonArgPosition flag, or initialize it to true. Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_NON_ARG ) ; nonArgPositionOnly = ( nonArgPositionOnly == null ) ? true : nonArgPositionOnly ; // Clear the nonArgPosition flag if the variable occurs in an argument position. nonArgPositionOnly = inTopLevelFunctor ( traverser ) ? false : nonArgPositionOnly ; symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_NON_ARG , nonArgPositionOnly ) ; /*log.fine(\"Variable \" + variable + \" nonArgPosition is \" + nonArgPositionOnly + \".\");*/ // If in an argument position, record the parent body functor against the variable, as potentially being // the last one it occurs in, in a purely argument position. // If not in an argument position, clear any parent functor recorded against the variable, as this current // last position of occurrence is not purely in argument position. if ( inTopLevelFunctor ( traverser ) ) { symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR , topLevelBodyFunctor ) ; } else { symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] protected void enterFunctor ( Functor functor ) { /*log.fine(\"Functor: \" + functor.getName() + \" <- \" + symbolTable.getSymbolKey(functor.getName()));*/ // Only check position of occurrence for constants. if ( functor . getArity ( ) == 0 ) { // Add the constant to the set of all constants encountered. List < SymbolKey > constantSymKeys = constants . get ( functor . getName ( ) ) ; if ( constantSymKeys == null ) { constantSymKeys = new LinkedList < SymbolKey > ( ) ; constants . put ( functor . getName ( ) , constantSymKeys ) ; } constantSymKeys . add ( functor . getSymbolKey ( ) ) ; // If the constant ever appears in argument position, take note of this. if ( inTopLevelFunctor ( traverser ) ) { argumentConstants . add ( functor . getName ( ) ) ; } } // Keep track of the current top-level body functor. if ( isTopLevel ( traverser ) && ! traverser . isInHead ( ) ) { topLevelBodyFunctor = functor ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Upon leaving the clause sets the nonArgPosition flag on any constants that need it . [CODESPLIT] protected void leaveClause ( Clause clause ) { // Remove the set of constants appearing in argument positions, from the set of all constants, to derive // the set of constants that appear in non-argument positions only. constants . keySet ( ) . removeAll ( argumentConstants ) ; // Set the nonArgPosition flag on all symbol keys for all constants that only appear in non-arg positions. for ( List < SymbolKey > symbolKeys : constants . values ( ) ) { for ( SymbolKey symbolKey : symbolKeys ) { symbolTable . put ( symbolKey , SymbolTableKeys . SYMKEY_FUNCTOR_NON_ARG , true ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the current position is immediately within a top - level functor . [CODESPLIT] private boolean inTopLevelFunctor ( PositionalContext context ) { PositionalContext parentContext = context . getParentContext ( ) ; return parentContext . isTopLevel ( ) || isTopLevel ( parentContext ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Functors are considered top - level when they appear at the top - level within a clause or directly beneath a parent conjunction or disjunction that is considered to be top - level . [CODESPLIT] private boolean isTopLevel ( PositionalContext context ) { Term term = context . getTerm ( ) ; if ( term . getSymbolKey ( ) == null ) { return false ; } Boolean isTopLevel = ( Boolean ) symbolTable . get ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR ) ; return ( isTopLevel == null ) ? false : isTopLevel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all of the elements in the specified collection to this heap . Attempts to addAll of a queue to itself result in <tt > IllegalArgumentException< / tt > . Further the behavior of this operation is undefined if the specified collection is modified while the operation is in progress . [CODESPLIT] public boolean addAll ( Collection < ? extends E > collection ) { if ( collection == null ) { throw new IllegalArgumentException ( \"The 'collection' parameter may not be null.\" ) ; } if ( collection == this ) { throw new IllegalArgumentException ( ) ; } boolean modified = false ; for ( E aC : collection ) { if ( add ( aC ) ) { modified = true ; } } return modified ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a single instance of the specified element from this heap if it is present . ( optional operation ) . More formally removes an element <tt > e< / tt > such that <tt > ( o == null ? e == null : o . equals ( e )) < / tt > if the collection contains one or more such elements . Returns <tt > true< / tt > if the collection contained the specified element ( or equivalently if the collection changed as a result of the call ) . [CODESPLIT] public boolean remove ( Object o ) { Iterator < E > e = iterator ( ) ; if ( o == null ) { while ( e . hasNext ( ) ) { if ( e . next ( ) == null ) { e . remove ( ) ; return true ; } } } else { while ( e . hasNext ( ) ) { if ( o . equals ( e . next ( ) ) ) { e . remove ( ) ; return true ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array containing all of the elements in this heap . If the collection makes any guarantees as to what order its elements are returned by its iterator this method must return the elements in the same order . The returned array will be safe in that no references to it are maintained by the collection . ( In other words this method must allocate a new array even if the collection is backed by an Array ) . The caller is thus free to modify the returned array . [CODESPLIT] public Object [ ] toArray ( ) { Object [ ] result = new Object [ size ( ) ] ; Iterator < E > e = iterator ( ) ; for ( int i = 0 ; e . hasNext ( ) ; i ++ ) { result [ i ] = e . next ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an array containing all of the elements in this heap ; the runtime type of the returned array is that of the specified array . If the collection fits in the specified array it is returned therein . Otherwise a new array is allocated with the runtime type of the specified array and the size of this collection . [CODESPLIT] public < T > T [ ] toArray ( T [ ] a ) { int size = size ( ) ; if ( a . length < size ) { a = ( T [ ] ) java . lang . reflect . Array . newInstance ( a . getClass ( ) . getComponentType ( ) , size ) ; } Iterator < E > it = iterator ( ) ; Object [ ] result = a ; for ( int i = 0 ; i < size ; i ++ ) { result [ i ] = it . next ( ) ; } if ( a . length > size ) { a [ size ] = null ; } return a ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a look at the last object placed on the stack since it will be the first one out . This method does not change the contents of the stack . Because this class is unsynchronized applications using this class are responsible for making sure that a <CODE > peek () < / CODE > followed by a <CODE > pop () < / CODE > returns the same value . [CODESPLIT] public E peek ( ) { int last = size ( ) - 1 ; E ob ; if ( last == - 1 ) { return null ; } ob = get ( last ) ; return ob ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public MicrodataDocument get ( String url ) { newUrl ( url ) ; try { Response response = Jsoup . connect ( url ) . method ( Method . GET ) . ignoreHttpErrors ( true ) . execute ( ) ; return new JsoupMicrodataDocument ( Collections . < String , String > emptyMap ( ) , response ) ; } catch ( IOException exception ) { throw new MicrobrowserException ( \"Error fetching page: \" + url , exception ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof PredicateVisitor ) { ( ( PredicateVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a built - in replacement transformation to functors . If the functor matches built - in a { @link BuiltInFunctor } is created with a mapping to the functors built - in implementation and the functors arguments are copied into this new functor . If the functor does not match a built - in it is returned unmodified . [CODESPLIT] public Functor apply ( Functor functor ) { FunctorName functorName = defaultBuiltIn . getInterner ( ) . getFunctorFunctorName ( functor ) ; Class < ? extends BuiltInFunctor > builtInClass ; builtInClass = builtIns . get ( functorName ) ; if ( builtInClass != null ) { return ReflectionUtils . newInstance ( ReflectionUtils . getConstructor ( builtInClass , new Class [ ] { Functor . class , DefaultBuiltIn . class } ) , new Object [ ] { functor , defaultBuiltIn } ) ; } else { return functor ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the arguments of this operator . It can be convenient to be able to set the outside of the constructor for example when parsing may want to create the operator first and fill in its arguments later . [CODESPLIT] public void setArguments ( Term [ ] arguments ) { // Check that there is at least one and at most two arguments. if ( ( arguments == null ) || ( arguments . length < 1 ) || ( arguments . length > 2 ) ) { throw new IllegalArgumentException ( \"An operator has minimum 1 and maximum 2 arguments.\" ) ; } this . arguments = arguments ; this . arity = arguments . length ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides the symbols fixity derived from its associativity . [CODESPLIT] public Fixity getFixity ( ) { switch ( associativity ) { case FX : case FY : return Fixity . Pre ; case XF : case YF : return Fixity . Post ; case XFX : case XFY : case YFX : return Fixity . In ; default : throw new IllegalStateException ( \"Unknown associativity.\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports whether this operator is an infix operator . [CODESPLIT] public boolean isInfix ( ) { return ( ( associativity == Associativity . XFY ) || ( associativity == Associativity . YFX ) || ( associativity == Associativity . XFX ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this object with the specified object for order providing a negative integer zero or a positive integer as this symbols priority is less than equal to or greater than the comparator . If this symbol is less than another that means that it has a lower priority value which means that it binds more tightly . [CODESPLIT] public int compareTo ( Object o ) { OpSymbol opSymbol = ( OpSymbol ) o ; return ( priority < opSymbol . priority ) ? - 1 : ( ( priority > opSymbol . priority ) ? 1 : 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Called when a property in the work flow state is changed . [CODESPLIT] public void propertyChange ( PropertyChangeEvent event ) { /*log.fine(\"void propertyChange(PropertyChangeEvent): called\");*/ /*log.fine(\"source class = \" + event.getSource().getClass());*/ /*log.fine(\"source object = \" + event.getSource());*/ /*log.fine(\"property name = \" + event.getPropertyName());*/ /*log.fine(\"new value = \" + event.getNewValue());*/ /*log.fine(\"old value = \" + event.getOldValue());*/ Object source = event . getSource ( ) ; Object oldValue = event . getOldValue ( ) ; String propertyName = event . getPropertyName ( ) ; // Check if the event source is an individual screen state if ( source instanceof WorkFlowScreenState ) { WorkFlowScreenState wfsState = ( WorkFlowScreenState ) source ; // Update the buttons to reflect the change in screen state updateButtonsForScreen ( wfsState ) ; } // Check if the event source is the whole work flow if ( source instanceof WorkFlowState ) { WorkFlowState wfState = ( WorkFlowState ) source ; // Check if the event cause is a change in current screen if ( \"currentScreenState\" . equals ( propertyName ) ) { WorkFlowScreenState newScreenState = wfState . getCurrentScreenState ( ) ; WorkFlowScreenState oldScreenState = ( WorkFlowScreenState ) oldValue ; // De-register this as a listener for the old current screen state if ( oldScreenState != null ) { oldScreenState . removePropertyChangeListener ( this ) ; } // Register this as a listener for the new current screen state if ( newScreenState != null ) { newScreenState . addPropertyChangeListener ( this ) ; } // Update the buttons to reflect the current screen state updateButtonsForScreen ( newScreenState ) ; } // Check if the event cause is a change in the work flow state else if ( \"state\" . equals ( propertyName ) ) { // Update the buttons to reflect the change in state updateButtonsForWorkFlow ( wfState ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the buttons enabled / disabled status to reflect the current screen state . [CODESPLIT] public void updateButtonsForScreen ( WorkFlowScreenState state ) { // Check if it is in the READY or NOT_SAVED state if ( state . getState ( ) . equals ( WorkFlowScreenState . READY ) || state . getState ( ) . equals ( WorkFlowScreenState . NOT_SAVED ) ) { backButton . setEnabled ( state . isPrevAvailable ( ) ) ; nextButton . setEnabled ( state . isNextAvailable ( ) ) ; finishButton . setEnabled ( state . isFinished ( ) ) ; } // Check if it is in the NOT_INITIALIZED state if ( state . getState ( ) . equals ( WorkFlowScreenState . NOT_INITIALIZED ) ) { backButton . setEnabled ( false ) ; nextButton . setEnabled ( false ) ; finishButton . setEnabled ( false ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the buttons enabled / disabled status to reflect the current work flow state . [CODESPLIT] public void updateButtonsForWorkFlow ( WorkFlowState state ) { // Check if it is in the NOT_INITIALIZED state if ( state . getState ( ) . equals ( WorkFlowState . NOT_INITIALIZED ) ) { backButton . setEnabled ( false ) ; nextButton . setEnabled ( false ) ; finishButton . setEnabled ( false ) ; cancelButton . setEnabled ( false ) ; } // Check if it is in the READY state if ( state . getState ( ) . equals ( WorkFlowState . READY ) ) { finishButton . setEnabled ( false ) ; cancelButton . setEnabled ( true ) ; // Update buttons for the current screen state updateButtonsForScreen ( state . getCurrentScreenState ( ) ) ; } // Check if it is in the NOT_SAVED state if ( state . getState ( ) . equals ( WorkFlowState . NOT_SAVED ) ) { finishButton . setEnabled ( true ) ; cancelButton . setEnabled ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers the work flow button panel with the specified work flow controller . This will cause the work flow controller to receive button press events from the panel and register the button panel to receive state changes from the underlying work flow model . [CODESPLIT] public void registerWorkFlowController ( WorkFlowController controller ) { // Set the work flow controller to listen for button events backButton . addActionListener ( controller ) ; nextButton . addActionListener ( controller ) ; finishButton . addActionListener ( controller ) ; cancelButton . addActionListener ( controller ) ; // Register this to listen for changes to the work flow state controller . getWorkFlowState ( ) . addPropertyChangeListener ( this ) ; // Register this to listen for changes to the state for the current screen if it is not null WorkFlowScreenState currentScreenState = controller . getWorkFlowState ( ) . getCurrentScreenState ( ) ; if ( currentScreenState != null ) { currentScreenState . addPropertyChangeListener ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor goalTerm = state . getGoalStack ( ) . peek ( ) . getFunctor ( ) ; Functor matchTerm = state . getCurrentClause ( ) . getHead ( ) ; // This is used to record variables bound on the domain side of the unificiation. This information seems // like is does not need to be kept because usually all of these bindings are in the stack frame. // However, this is not always the case as unification can capture a variable on the domain side. // These variables need to be unbound on backtracking too. List < Variable > domainVariables = new LinkedList < Variable > ( ) ; // This is used to record variables bound on the query goal side of the unification. This information // must be kept so that the undo operation can unbind these variables before placing the goal back // onto the stack when backtracking. List < Variable > boundVariables = new LinkedList < Variable > ( ) ; // Unify the current query goal with the possibly matching clause, creating variable bindings. boolean matched = state . getUnifier ( ) . unifyInternal ( goalTerm , matchTerm , boundVariables , domainVariables ) ; // Even if unification fails, any partial bindings created are remembered, to ensure that they are cleaned // up when this proof steps state is undone. for ( Variable binding : boundVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } for ( Variable binding : domainVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } // If the unification succeeded, establish a new state with the unified query removed from the goal stack, the // body of the unified with clause added to it for resolution, and the variable binding trail extended with // any additional bindings resulting from the unification. if ( matched ) { if ( TRACE ) { /*trace.fine(state.getTraceIndenter().generateTraceIndent() + \"Unify \" +\n                    goalTerm.toString(state.getInterner(), true, true) + \" against \" +\n                    matchTerm.toString(state.getInterner(), true, true) + \", ok.\");*/ } // Consume the successfully unified goal from the goal stack. state . getGoalStack ( ) . poll ( ) ; // Add all functors on the body side of the unified clause onto the goal stack for resolution. Functor [ ] body = state . getCurrentClause ( ) . getBody ( ) ; if ( ( body != null ) && ( body . length != 0 ) ) { // The new goals are placed onto the goal stack backwards. It is a stack, hence they get // explored first, depth first, but their insertion order is reversed for an intuitive // left-to-right evaluation order. for ( int i = body . length - 1 ; i >= 0 ; i -- ) { BuiltInFunctor newGoal = state . getBuiltInTransform ( ) . apply ( body [ i ] ) ; newGoal . setParentChoicePointState ( state . getLastChoicePoint ( ) ) ; state . getGoalStack ( ) . offer ( newGoal ) ; } } return true ; } else { if ( TRACE ) { /*trace.fine(state.getTraceIndenter().generateTraceIndent() + \"Failed to unify \" +\n                    goalTerm.toString(state.getInterner(), true, true) + \" against \" +\n                    matchTerm.toString(state.getInterner(), true, true) + \".\");*/ } return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a factory for building enum attributes of the specified enum class . [CODESPLIT] public static EnumAttributeFactory getFactoryForClass ( Class cls ) { // Check that the requested class is actually an enum. if ( ! cls . isEnum ( ) ) { throw new IllegalArgumentException ( \"Can only create enum attribute factories for classes that are enums.\" ) ; } return EnumClassImpl . getInstance ( cls ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void changeColor ( C color ) { AttributeSet aset = new AttributeSet ( ) ; aset . put ( AttributeSet . BACKGROUND_COLOR , color ) ; grid . insertRowAttribute ( aset , row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an instance of the named component factory . [CODESPLIT] public static ComponentFactory createComponentFactory ( String className ) { return ( ComponentFactory ) ReflectionUtils . newInstance ( ReflectionUtils . forName ( className ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides the storage cell for the specified variable . Some types of variable may defer their storage onto a storage cell other than themselves other variable types may simply return themselves as their own storage cells . [CODESPLIT] public Variable getStorageCell ( Variable variable ) { VariableBindingContext < Variable > context = getBindingContext ( ) ; if ( context == null ) { return null ; } else { return context . getStorageCell ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports whether or not this variable is bound to a value . [CODESPLIT] public boolean isBound ( ) { VariableBindingContext < Variable > context = getBindingContext ( ) ; // The variable can only be bound if it has a binding context and is bound in that context. return ( context != null ) && context . getStorageCell ( this ) . isBound ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public AttributeSet getAttributeAt ( int c , int r ) { AttributeSet attributeSet = cellAttributes . get ( ( long ) c , ( long ) r ) ; attributeSet = ( attributeSet == null ) ? getColumnAttributeOrNull ( c ) : attributeSet ; attributeSet = ( attributeSet == null ) ? getRowAttributeOrNull ( r ) : attributeSet ; return attributeSet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a column attribute adding padding to the underlying array as necessary to ensure it is large enough to hold the attribute at the requested position . [CODESPLIT] private void setColumnAttribute ( AttributeSet attributes , int c ) { if ( c >= columnAttributes . size ( ) ) { for ( int i = columnAttributes . size ( ) ; i <= c ; i ++ ) { columnAttributes . add ( null ) ; } } columnAttributes . set ( c , attributes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a row attribute adding padding to the underlying array as necessary to ensure it is large enough to hold the attribute at the requested position . [CODESPLIT] private void setRowAttribute ( AttributeSet attributes , int r ) { if ( r >= rowAttributes . size ( ) ) { for ( int i = rowAttributes . size ( ) ; i <= r ; i ++ ) { rowAttributes . add ( null ) ; } } rowAttributes . set ( r , attributes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a columns attribute if possible without overflowing the underlying array . [CODESPLIT] private AttributeSet getColumnAttributeOrNull ( int c ) { if ( ( c >= 0 ) && ( c < columnAttributes . size ( ) ) ) { return columnAttributes . get ( c ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets a rows attribute if possible without overflowing the underlying array . [CODESPLIT] private AttributeSet getRowAttributeOrNull ( int r ) { if ( ( r >= 0 ) && ( r < rowAttributes . size ( ) ) ) { return rowAttributes . get ( r ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a set of attributes into the grid at the specified location . This is a private insert method that does not notify model listeners so that the public insert methods can do that as a separate step . [CODESPLIT] private void internalInsert ( AttributeSet attributes , int c , int r ) { cellAttributes . put ( ( long ) c , ( long ) r , attributes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the actual value of a term which is a numeric type equal in value to the arithmetic operator applied to its argument . This method checks that the argument produces a value which is fully instantiated and numeric when its { @link Term#getValue () } methods is invoked . [CODESPLIT] public NumericType getValue ( ) { Term firstArgValue = arguments [ 0 ] . getValue ( ) ; // Check that the argument to operate on is a numeric values. if ( ! firstArgValue . isNumber ( ) ) { throw new IllegalStateException ( \"instantiation_error, 'arithmetic/2' expects numeric arguments, but the first argument is non-numeric.\" ) ; } return evaluate ( ( NumericType ) firstArgValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public JComponent createTextGridPanel ( EnhancedTextGrid model ) { JTextGrid textPane = new JTextGrid ( ) ; textPane . setBackground ( colorScheme . getBackground ( ) ) ; textPane . setForeground ( colorScheme . getMainText ( ) ) ; textPane . setAutoscrolls ( true ) ; Font font = new Font ( \"DejaVu Sans Mono\" , Font . PLAIN , 12 ) ; textPane . setFont ( font ) ; textPane . setModel ( model ) ; textPane . initializeStandardMouseHandling ( ) ; JScrollPane scrollPane = new JScrollPane ( textPane , ScrollPaneConstants . VERTICAL_SCROLLBAR_AS_NEEDED , ScrollPaneConstants . HORIZONTAL_SCROLLBAR_AS_NEEDED ) ; scrollPane . getVerticalScrollBar ( ) . setUI ( new DiscreetScrollBarUI ( toolingColorScheme ) ) ; scrollPane . getHorizontalScrollBar ( ) . setUI ( new DiscreetScrollBarUI ( toolingColorScheme ) ) ; scrollPane . setBorder ( BorderFactory . createEmptyBorder ( ) ) ; scrollPane . getViewport ( ) . setLayout ( new FillViewportLayout ( ) ) ; return scrollPane ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public JComponent createGripPanel ( MotionDelta motionDelta , boolean vertical ) { JPanel vbar = new JPanel ( ) ; vbar . setBackground ( toolingColorScheme . getToolingBackground ( ) ) ; GripComponentMouseMover resizer = new GripComponentMouseMover ( vbar , motionDelta , vertical ? VERTICAL_RESIZE_CURSOR : HORIZONTAL_RESIZE_CURSOR , GRIP_CURSOR ) ; vbar . addMouseMotionListener ( resizer ) ; vbar . addMouseListener ( resizer ) ; return vbar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public JComponent createBlankPanel ( ) { JPanel vbar = new JPanel ( ) ; vbar . setBackground ( colorScheme . getBackground ( ) ) ; vbar . setForeground ( colorScheme . getDisabledText ( ) ) ; return vbar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new time range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , TimeOnly min , TimeOnly max ) { // Ensure that min is less than or equal to max. if ( ( min != null ) && ( max != null ) && ( min . compareTo ( max ) > 0 ) ) { throw new IllegalArgumentException ( \"'min' must be less than or equal to 'max'.\" ) ; } synchronized ( INT_RANGE_TYPES ) { // Add the newly created type to the map of all types. TimeRangeType newType = new TimeRangeType ( name , min , max ) ; // Ensure that the named type does not already exist, unless it has an identical definition already, in which // case the old definition can be re-used and the new one discarded. TimeRangeType oldType = INT_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( \"The type '\" + name + \"' already exists and cannot be redefined.\" ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { INT_RANGE_TYPES . put ( name , newType ) ; return newType ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public TimeOnly createRandomInstance ( ) { int start = minValue . getMilliseconds ( ) ; int end = maxValue . getMilliseconds ( ) ; return new TimeOnly ( ( long ) ( start + random . nextInt ( end - start ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void acceptVisitor ( TypeVisitor visitor ) { if ( visitor instanceof TimeRangeTypeVisitor ) { ( ( TimeRangeTypeVisitor ) visitor ) . visit ( this ) ; } else { super . acceptVisitor ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new string pattern type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , int maxLength , String pattern ) { synchronized ( STRING_PATTERN_TYPES ) { StringPatternType newType = new StringPatternType ( name , maxLength , pattern ) ; // Ensure that the named type does not already exist. StringPatternType oldType = STRING_PATTERN_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( \"The type '\" + name + \"' already exists and cannot be redefined.\" ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { // Add the newly created type to the map of all types. STRING_PATTERN_TYPES . put ( name , newType ) ; return newType ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks a string value against this type to see if it is a valid instance of the type . [CODESPLIT] public boolean isInstance ( CharSequence value ) { // Check the value is under the maximum if one is set. // Check the value matches the pattern if one is set. return ( ( maxLength <= 0 ) || ( value . length ( ) <= maxLength ) ) && compiledPattern . matcher ( value ) . matches ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean isTopLevel ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isTopLevel ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean isInHead ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isInHead ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean isLastBodyFunctor ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isLastBodyFunctor ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Term getTerm ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getTerm ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int getPosition ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getPosition ( ) : - 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public PositionalContext getParentContext ( ) { PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getParentContext ( ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected StackableOperator createHeadOperator ( Functor head , Clause clause ) { return new PositionalContextOperator ( head , - 1 , true , true , false , null , contextStack . peek ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected StackableOperator createBodyOperator ( Functor bodyFunctor , int pos , Functor [ ] body , Clause clause ) { return new PositionalContextOperator ( bodyFunctor , pos , true , false , pos == ( body . length - 1 ) , null , contextStack . peek ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected StackableOperator createTermOperator ( Term argument , int pos , Functor functor ) { return new PositionalContextOperator ( argument , pos , false , null , false , null , contextStack . peek ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected StackableOperator createClauseOperator ( Clause bodyClause , int pos , Clause [ ] body , Predicate predicate ) { return new PositionalContextOperator ( bodyClause , pos , false , false , false , null , contextStack . peek ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up the initial context once at the start of a traversal . [CODESPLIT] private void createInitialContext ( Term term ) { if ( ! initialContextCreated ) { PositionalContextOperator initialContext = new PositionalContextOperator ( term , - 1 , false , false , false , null , contextStack . peek ( ) ) ; contextStack . offer ( initialContext ) ; term . setReversable ( initialContext ) ; initialContextCreated = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the layout register file with a new set of layout registers . [CODESPLIT] public void updateRegisters ( WAMMemoryLayout layout ) { List < PropertyChangeEvent > changes = delta ( this , layout ) ; regBase = layout . regBase ; regSize = layout . regSize ; heapBase = layout . heapBase ; heapSize = layout . heapSize ; stackBase = layout . stackBase ; stackSize = layout . stackSize ; trailBase = layout . trailBase ; trailSize = layout . trailSize ; pdlBase = layout . pdlBase ; pdlSize = layout . pdlSize ; notifyChanges ( changes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the current register file with a new set and creates a list property change notifications for any that have changed value . [CODESPLIT] private List < PropertyChangeEvent > delta ( WAMMemoryLayout oldRegisters , WAMMemoryLayout newRegisters ) { List < PropertyChangeEvent > result = new LinkedList < PropertyChangeEvent > ( ) ; if ( oldRegisters . regBase != newRegisters . regBase ) { result . add ( new PropertyChangeEvent ( this , \"regBase\" , oldRegisters . regBase , newRegisters . regBase ) ) ; } if ( oldRegisters . regSize != newRegisters . regSize ) { result . add ( new PropertyChangeEvent ( this , \"regSize\" , oldRegisters . regSize , newRegisters . regSize ) ) ; } if ( oldRegisters . heapBase != newRegisters . heapBase ) { result . add ( new PropertyChangeEvent ( this , \"heapBase\" , oldRegisters . heapBase , newRegisters . heapBase ) ) ; } if ( oldRegisters . heapSize != newRegisters . heapSize ) { result . add ( new PropertyChangeEvent ( this , \"heapSize\" , oldRegisters . heapSize , newRegisters . heapSize ) ) ; } if ( oldRegisters . stackBase != newRegisters . stackBase ) { result . add ( new PropertyChangeEvent ( this , \"stackBase\" , oldRegisters . stackBase , newRegisters . stackBase ) ) ; } if ( oldRegisters . stackSize != newRegisters . stackSize ) { result . add ( new PropertyChangeEvent ( this , \"stackSize\" , oldRegisters . stackSize , newRegisters . stackSize ) ) ; } if ( oldRegisters . trailBase != newRegisters . trailBase ) { result . add ( new PropertyChangeEvent ( this , \"trailBase\" , oldRegisters . trailBase , newRegisters . trailBase ) ) ; } if ( oldRegisters . trailSize != newRegisters . trailSize ) { result . add ( new PropertyChangeEvent ( this , \"trailSize\" , oldRegisters . trailSize , newRegisters . trailSize ) ) ; } if ( oldRegisters . pdlBase != newRegisters . pdlBase ) { result . add ( new PropertyChangeEvent ( this , \"pdlBase\" , oldRegisters . pdlBase , newRegisters . pdlBase ) ) ; } if ( oldRegisters . pdlSize != newRegisters . pdlSize ) { result . add ( new PropertyChangeEvent ( this , \"pdlSize\" , oldRegisters . pdlSize , newRegisters . pdlSize ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Search up the scope tree to locate the variable s value . The parser has already verified that the variable is defined . [CODESPLIT] public String getValue ( ) { for ( ScopeNode scope = NodeTreeUtils . getParentScope ( this ) ; scope != null ; scope = NodeTreeUtils . getParentScope ( scope ) ) { ExpressionGroupNode value = scope . getVariable ( _name ) ; if ( value == null ) { continue ; } return value . toString ( ) ; } return _name ; // Unable to find the variable's value, return the name for now (helpful for debugging) }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the general bi - dircetional search . The search alternated between taking a forward and a reverse step . [CODESPLIT] public SearchNode < O , T > findGoalPath ( ) throws SearchNotExhaustiveException { // Keep running until the queue becomes empty or a goal state is found while ( ! forwardQueue . isEmpty ( ) || ! reverseQueue . isEmpty ( ) ) { // Only run the forward step of the search if the forward queue is not empty if ( ! forwardQueue . isEmpty ( ) ) { // Extract the next node from the forward queue SearchNode < O , T > currentForwardNode = forwardQueue . remove ( ) ; // Remove this node from the forward fringe map as it will soon be replaced by more fringe members forwardFringe . remove ( currentForwardNode . getState ( ) ) ; // Check the reverse fringe against the next forward node for a match. if ( reverseFringe . containsKey ( currentForwardNode . getState ( ) ) ) { // A path from start to the goal has been found. Walk backwards along the reverse path adding all // nodes encountered to the forward path until the goal is reached. return joinBothPaths ( currentForwardNode , reverseFringe . get ( currentForwardNode . getState ( ) ) ) ; } // There was no match so a path to the goal has not been found else { // Get all of the successor states to the current node Queue < SearchNode < O , T > > newStates = new LinkedList < SearchNode < O , T > > ( ) ; currentForwardNode . expandSuccessors ( newStates , false ) ; // Expand all the successors to the current forward node into the buffer to be searched. forwardQueue . addAll ( newStates ) ; // Also add all the successors to the current forward fringe map. for ( SearchNode < O , T > nextSearchNode : newStates ) { forwardFringe . put ( nextSearchNode . getState ( ) , nextSearchNode ) ; } } } // Only run the reverse step of the search if the reverse queue is not empty if ( ! reverseQueue . isEmpty ( ) ) { // Extract the next node from the reverse queue SearchNode < O , T > currentReverseNode = reverseQueue . remove ( ) ; // Remove this node from the reverse fringe set as it will soon be replaced by more fringe members reverseFringe . remove ( currentReverseNode . getState ( ) ) ; // Check the forward fringe against the next reverse node for a match. if ( forwardFringe . containsKey ( currentReverseNode . getState ( ) ) ) { // A path from start to goal has been found. // Walk backwards along the reverse path adding all nodes encountered to the foward path until the // goal is reached. return joinBothPaths ( forwardFringe . get ( currentReverseNode . getState ( ) ) , currentReverseNode ) ; } // There was no match so a path to the goal has not been found else { // Get all of the successor states to the current node (really predecessor state) Queue < SearchNode < O , T > > newStates = new LinkedList < SearchNode < O , T > > ( ) ; currentReverseNode . expandSuccessors ( newStates , false ) ; // Expand all the successors to the current reverse node into the reverse buffer to be searched. reverseQueue . addAll ( newStates ) ; // Add all the successors to the current reverse fringe set for ( SearchNode < O , T > nextSearchNode : newStates ) { reverseFringe . put ( nextSearchNode . getState ( ) , nextSearchNode ) ; } } } } // No goal state was found so return null return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Once a match has been found between the forward and reverse fringes of the search a path is known to exist from the start to the goal . The path is not complete at this stage because it remains to reverse all of the steps in the backward half of the path and add them to the forward half of the path to produce the complete forward path from start to the goal . [CODESPLIT] private SearchNode < O , T > joinBothPaths ( SearchNode < O , T > forwardPath , SearchNode < O , T > reversePath ) throws SearchNotExhaustiveException { // Check if an alternative path join algorithm has been set and delegate to it if so if ( pathJoiner != null ) { return pathJoiner . joinBothPaths ( forwardPath , reversePath ) ; } // No alternative path join algorithm has been supplied so use this default one else { // Used to hold the current position along the reverse path of search nodes SearchNode < O , T > currentReverseNode = reversePath ; // Used to hold the current position along the forward path of search nodes SearchNode < O , T > currentForwardNode = forwardPath ; // Loop over all nodes in the reverse path checking if the current reverse node is the // goal state to terminate on. while ( ! goalPredicate . evaluate ( currentReverseNode . getState ( ) ) ) { // Create a new forward node from the parent state of the current reverse node, the current reverse // nodes applied operation and cost, and an increment of one to the path depth SearchNode < O , T > reverseParentNode = currentReverseNode . getParent ( ) ; T state = currentReverseNode . getParent ( ) . getState ( ) ; Operator < O > operation = currentReverseNode . getAppliedOp ( ) ; float cost = currentReverseNode . getPathCost ( ) - reverseParentNode . getPathCost ( ) ; currentForwardNode = currentForwardNode . makeNode ( new Successor < O > ( state , operation , cost ) ) ; // Move one step up the reverse path currentReverseNode = reverseParentNode ; } // Return the last forward search node found return currentForwardNode ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public Variable transform ( Variable variable ) { StackVariable stackVar = varMapping . get ( variable ) ; // Check if a stack variable for the variable has not been created yet, and if so create a new stack variable, // setting the clause that it is in as its binding context supplier. if ( stackVar == null ) { stackVar = new StackVariable ( variable . getName ( ) , null , variable . isAnonymous ( ) , offset ++ , context ) ; varMapping . put ( variable , stackVar ) ; } return stackVar ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the element from the list at the specified index . If the indexes block is not currently cached then a call is made to the { @link #getBlock } method to fetch it . [CODESPLIT] public T get ( int index ) { /*log.fine(\"public T get(int index): called\");*/ /*log.fine(\"index = \" + index);*/ // Turn the absolute index into a block and offset. int block = index / blockSize ; int offset = index % blockSize ; /*log.fine(\"block = \" + block);*/ /*log.fine(\"offset = \" + offset);*/ // Check if the desired block is already cached. List < T > blockList = blockMap . get ( block ) ; // Fetch the block if it is not already cached and cache it. if ( blockList == null ) { blockList = cacheBlock ( block ) ; } // Get the element from the offset within the cached block. return blockList . get ( offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches and caches the specified block . [CODESPLIT] public List < T > cacheBlock ( int block ) { /*log.fine(\"public List<T> cacheBlock(int block): called\");*/ // Get the new block. List < T > blockList = getBlock ( block * blockSize , blockSize ) ; // Cache it. blockMap . put ( block , blockList ) ; /*log.fine(\"Cached block \" + block + \" with list of size \" + blockList.size());*/ return blockList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Static factory method that locates an existing instance or creates a new property reader for a named resource . [CODESPLIT] public static synchronized Properties getProperties ( String resourceName ) { /*log.fine(\"public static synchronized Properties getProperties(String resourceName): called\");*/ /*log.fine(\"resourceName = \" + resourceName);*/ // Try to find an already created singleton property reader for the resource PropertyReaderBase propertyReader = ( PropertyReaderBase ) propertyReaders . get ( resourceName ) ; if ( propertyReader != null ) { /*log.fine(\"found property reader in the cache for resource: \" + resourceName);*/ return propertyReader . getProperties ( ) ; } /*log.fine(\"did not find property reader in the cache for resource: \" + resourceName);*/ // There is not already a singleton for the named resource so create a new one propertyReader = new DefaultPropertyReader ( resourceName ) ; // Keep the newly created singleton for next time propertyReaders . put ( resourceName , propertyReader ) ; return propertyReader . getProperties ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the throttling rate in operations per second . [CODESPLIT] public void setRate ( float hertz ) { // Pass the rate unaltered down to the base implementation, for the check method. super . setRate ( hertz ) ; // Log base 10 over 2 is used here to get a feel for what power of 100 the total rate is. // As the total rate goes up the powers of 100 the batch size goes up by powers of 100 to keep the // throttle rate in the range 1 to 100. int x = ( int ) ( Math . log10 ( hertz ) / 2 ) ; batchSize = ( int ) Math . pow ( 100 , x ) ; float throttleRate = hertz / batchSize ; // Reset the call count. callCount = 0 ; // Set the sleep throttle wrapped implementation at a rate within its abilities. batchRateThrottle . setRate ( throttleRate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads some number of bytes from the input stream and stores them into the buffer array b . [CODESPLIT] public int read ( byte [ ] b ) throws IOException { try { ByteBlock block = source . read ( b ) ; System . arraycopy ( block . data , 0 , b , 0 , block . count ) ; return block . count ; } catch ( RemoteException e ) { throw new IOException ( \"There was a Remote Exception.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads up to len bytes of data from the input stream into an array of bytes . [CODESPLIT] public int read ( byte [ ] b , int off , int len ) throws IOException { try { ByteBlock block = source . read ( b , off , len ) ; System . arraycopy ( block . data , off , b , off , len ) ; return block . count ; } catch ( RemoteException e ) { throw new IOException ( \"There was a Remote Exception.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Skips over and discards n bytes of data from this input stream . [CODESPLIT] public long skip ( long n ) throws IOException { try { return source . skip ( n ) ; } catch ( RemoteException e ) { throw new IOException ( \"There was a Remote Exception.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor functor , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { SizeableLinkedList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableLinkedList < WAMInstruction > instructions ; // Invent some unique names for choice points within a clause. clauseName = new FunctorName ( clauseName . getName ( ) + \"_\" + bodyNumber , 0 ) ; FunctorName choicePointRootName = new FunctorName ( clauseName . getName ( ) + \"_ilc\" , 0 ) ; FunctorName continuationPointName = new FunctorName ( clauseName . getName ( ) + \"_cnt\" , 0 ) ; // Labels the continuation point to jump to, when a choice point succeeds. WAMLabel continueLabel = new WAMLabel ( continuationPointName , 0 ) ; // Do a loop over the children of this disjunction, and any child disjunctions encountered. This could be a // search? or just recursive exploration. I think it will need to be a DFS. List < Term > expressions = new ArrayList < Term > ( ) ; gatherDisjunctions ( ( Disjunction ) functor , expressions ) ; for ( int i = 0 ; i < expressions . size ( ) ; i ++ ) { Functor expression = ( Functor ) expressions . get ( i ) ; boolean isFirst = i == 0 ; boolean isLast = i == ( expressions . size ( ) - 1 ) ; // Labels the entry point to each choice point. WAMLabel entryLabel = new WAMLabel ( choicePointRootName , i ) ; // Label for the entry point to the next choice point, to backtrack to. WAMLabel retryLabel = new WAMLabel ( choicePointRootName , i + 1 ) ; if ( isFirst && ! isLast ) { // try me else. result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TryMeElse , retryLabel ) ) ; } else if ( ! isFirst && ! isLast ) { // retry me else. result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . RetryMeElse , retryLabel ) ) ; } else if ( isLast ) { // trust me. result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TrustMe ) ) ; } Integer permVarsRemaining = ( Integer ) defaultBuiltIn . getSymbolTable ( ) . get ( expression . getSymbolKey ( ) , SYMKEY_PERM_VARS_REMAINING ) ; // Select a non-default built-in implementation to compile the functor with, if it is a built-in. BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = defaultBuiltIn ; } // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule. instructions = builtIn . compileBodyArguments ( expression , false , clauseName , i ) ; result . addAll ( instructions ) ; // Call the body. The number of permanent variables remaining is specified for environment trimming. instructions = builtIn . compileBodyCall ( expression , false , false , false , 0 /*permVarsRemaining*/ ) ; result . addAll ( instructions ) ; // Proceed if this disjunctive branch completes successfully. This does not need to be done for the last // branch, as the continuation point will come immediately after. if ( ! isLast ) { result . add ( new WAMInstruction ( null , WAMInstruction . WAMInstructionSet . Continue , continueLabel ) ) ; } } result . add ( new WAMInstruction ( continueLabel , WAMInstruction . WAMInstructionSet . NoOp ) ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { return new SizeableLinkedList < WAMInstruction > ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gathers the functors to compile as a sequence of choice points . These exist as the arguments to disjunctions recursively below the supplied disjunction . They are flattened into a list by performing a left - to - right depth first traversal over the disjunctions and adding their arguments into a list . [CODESPLIT] private void gatherDisjunctions ( Disjunction disjunction , List < Term > expressions ) { // Left argument. gatherDisjunctionsExploreArgument ( disjunction . getArguments ( ) [ 0 ] , expressions ) ; // Right argument. gatherDisjunctionsExploreArgument ( disjunction . getArguments ( ) [ 1 ] , expressions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Explores one argument of a disjunction as part of the { @link #gatherDisjunctions ( Disjunction List ) } function . [CODESPLIT] private void gatherDisjunctionsExploreArgument ( Term term , List < Term > expressions ) { if ( term instanceof Disjunction ) { gatherDisjunctions ( ( Disjunction ) term , expressions ) ; } else { expressions . add ( term ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Functor isOp = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; // Evaluate both sides of the comparison, checking that they are fully instantiated numbers. NumericType n1 = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 0 ) ) ; NumericType n2 = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 1 ) ) ; // Evaluate the comparison operator. return evaluate ( n1 , n2 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Clause clause ) { if ( traverser . isEnteringContext ( ) ) { initializePrinters ( ) ; } else if ( traverser . isLeavingContext ( ) ) { printTable ( ) ; } super . visit ( clause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the first ( lowest ) key currently in this priority map . [CODESPLIT] public K pollKey ( ) { // Scan through the buckets until a non empty one is found. int i = 0 ; for ( ; i < n ; i ++ ) { if ( ! maps [ i ] . isEmpty ( ) ) { break ; } // If all maps are empty then the whole data structure is emtpy. if ( i == ( n - 1 ) ) { return null ; } } return maps [ i ] . keySet ( ) . iterator ( ) . next ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value of the first ( lowest ) key currently in this priority map . [CODESPLIT] public V pollValue ( ) { K lowestKey = pollKey ( ) ; if ( lowestKey == null ) { return null ; } else { return maps [ p . apply ( lowestKey ) ] . get ( lowestKey ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts an int from an array of bytes . [CODESPLIT] public static int getIntFromBytes ( byte [ ] buf , int offset ) { int result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ++ ] & 0xFF ) << 8 ) ; result += ( ( buf [ offset ++ ] & 0xFF ) << 16 ) ; result += ( ( buf [ offset ] ) << 24 ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Outputs an int into a byte array . [CODESPLIT] public static void writeIntToByteArray ( byte [ ] buf , int offset , int value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x00ff0000 ) >> 16 ) ; buf [ offset ] = ( byte ) ( ( value & 0xff000000 ) >> 24 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Outputs an int into a byte array copying only the bottom 24 bits of the integer . The top sign bit is lost by this operation so this only works on positive ints below 2^24 . [CODESPLIT] public static void write24BitIntToByteArray ( byte [ ] buf , int offset , int value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; buf [ offset ] = ( byte ) ( ( value & 0x00ff0000 ) >> 16 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts an int from an array of bytes . Only three bytes are pulled together from the array to make a 24 bit integer albeit returned as a java 32 bit int . [CODESPLIT] public static int get24BitIntFromBytes ( byte [ ] buf , int offset ) { int i = 0 ; offset ++ ; i += buf [ offset ++ ] & 0xFF ; i += ( ( buf [ offset ++ ] & 0xFF ) << 8 ) ; i += ( ( buf [ offset ] & 0xFF ) << 16 ) ; return i ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts a short from an array of bytes . [CODESPLIT] public static short getShortFromBytes ( byte [ ] buf , int offset ) { short result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ] ) << 8 ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Outputs a short into a byte array . [CODESPLIT] public static void writeShortToByteArray ( byte [ ] buf , int offset , short value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Execute , new FunctorName ( \"__fail__\" , 0 ) ) ) ; return instructions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an implementation of the { @link BoundProperty } interface to extract the cost as the bound property . [CODESPLIT] public float getBoundProperty ( SearchNode < O , T > searchNode ) { return ( ( HeuristicSearchNode < O , T > ) searchNode ) . getF ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the state obtained by applying the specified operation . If the operation is not valid then this should return null . [CODESPLIT] public TreeSearchState < E > getChildStateForOperator ( Operator < Tree < E > > op ) { /*log.fine(\"public Traversable getChildStateForOperator(Operator op): called\");*/ // Extract the child tree from the operator and create a new tree search state from it. return new TreeSearchState < E > ( op . getOp ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets all operators valid from this state . If the current tree to search has any children these are encoded as operators to access those child trees as tree search states . If the current tree is a leaf then an empty iterator is returned . [CODESPLIT] public Iterator < Operator < Tree < E > > > validOperators ( boolean reverse ) { /*log.fine(\"public Iterator<Operator> validOperators(): called\");*/ // Check if the tree is a leaf and return an empty iterator if so. if ( tree . isLeaf ( ) ) { /*log.fine(\"is leaf\");*/ return new ArrayList < Operator < Tree < E > > > ( ) . iterator ( ) ; } // Generate an iterator over the child trees of the current node, encapsulating them as operators. else { /*log.fine(\"is node\");*/ Tree . Node < E > node = tree . getAsNode ( ) ; return new TreeSearchOperatorIterator < E > ( node . getChildIterator ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the integer id of the attribute . [CODESPLIT] public long getId ( ) { // Check if the attribute class has been finalized yet. if ( attributeClass . finalized ) { // Fetch the object value from the attribute class array of finalized values. return attributeClass . lookupValue [ value ] . id ; } // The attribute class has not been finalized yet. else { // Fetch the object value from the attribute class list of unfinalized values. return attributeClass . lookupValueList . get ( value ) . id ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the object value of a object attribute . [CODESPLIT] public T getValue ( ) { // Check if the attribute class has been finalized yet. if ( attributeClass . finalized ) { // Fetch the object value from the attribute class. return attributeClass . lookupValue [ value ] . label ; } else { return attributeClass . lookupValueList . get ( value ) . label ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the specified object as the value of this attribute . The value to set must be a legitimate member of this attributes type when the type has been finalized . If the type has yet to be finalized then the new value is added to the set of possible values for the type . [CODESPLIT] public void setValue ( T value ) throws IllegalArgumentException { Integer b = attributeClass . lookupInt . get ( value ) ; // Check if the value is not already a memeber of the attribute class. if ( b == null ) { // Check if the attribute class has been finalized yet. if ( attributeClass . finalized ) { throw new IllegalArgumentException ( \"The value to set, \" + value + \", is not already a member of the finalized IdType, \" + attributeClass . attributeClassName + \".\" ) ; } else { // Add the new value to the attribute class. Delegate to the factory to do this so that strings are // interned and so on. IdAttribute newAttribute = attributeClass . createIdAttribute ( value ) ; b = newAttribute . value ; } } // Set the new value as the value of this attribute. this . value = b ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a string listing sub - strings seperated by a delimeter into an array of strings . [CODESPLIT] public static String [ ] listToArray ( String value , String delim ) { List < String > result = new ArrayList < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( value , delim ) ; while ( tokenizer . hasMoreTokens ( ) ) { result . add ( tokenizer . nextToken ( ) ) ; } return result . toArray ( new String [ result . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an array of strings into a delimeter seperated string . [CODESPLIT] public static String arrayToList ( String [ ] array , String delim ) { String result = \"\" ; for ( int i = 0 ; i < array . length ; i ++ ) { result += array [ i ] + ( ( i == ( array . length - 1 ) ) ? \"\" : delim ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a string to camel case . [CODESPLIT] public static String toCamelCase ( String name ) { String [ ] parts = name . split ( \"_\" ) ; String result = parts [ 0 ] ; for ( int i = 1 ; i < parts . length ; i ++ ) { if ( parts [ i ] . length ( ) > 0 ) { result += upperFirstChar ( parts [ i ] ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts string between various case forms such as camel case snake case or kebab case . [CODESPLIT] public static String convertCase ( String value , String separator , boolean firstLetterUpper , boolean firstLetterOfWordUpper ) { final StringBuffer result = new StringBuffer ( ) ; boolean firstWord = true ; boolean firstLetter = true ; boolean upper = false ; WordMachineState state = WordMachineState . Initial ; Function2 < Character , Boolean , StringBuffer > writeChar = new Function2 < Character , Boolean , StringBuffer > ( ) { public StringBuffer apply ( Character nextChar , Boolean upper ) { if ( upper ) result . append ( Character . toUpperCase ( nextChar ) ) ; else result . append ( Character . toLowerCase ( nextChar ) ) ; return result ; } } ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char nextChar = value . charAt ( i ) ; if ( Character . isUpperCase ( nextChar ) ) { switch ( state ) { case Initial : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; if ( ! firstWord ) { result . append ( separator ) ; } firstWord = false ; break ; case StartWord : case ContinueWordCaps : state = WordMachineState . ContinueWordCaps ; upper = false ; break ; case ContinueWordLower : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; result . append ( separator ) ; break ; } writeChar . apply ( nextChar , ( ! firstLetter && upper ) || ( firstLetter & firstLetterUpper ) ) ; firstLetter = false ; } else if ( Character . isLetterOrDigit ( nextChar ) ) { switch ( state ) { case Initial : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; if ( ! firstWord ) { result . append ( separator ) ; } firstWord = false ; break ; case StartWord : case ContinueWordLower : case ContinueWordCaps : state = WordMachineState . ContinueWordLower ; upper = false ; break ; } writeChar . apply ( nextChar , ( ! firstLetter && upper ) || ( firstLetter & firstLetterUpper ) ) ; firstLetter = false ; } else { switch ( state ) { case Initial : state = WordMachineState . Initial ; break ; case StartWord : case ContinueWordCaps : case ContinueWordLower : state = WordMachineState . Initial ; break ; } upper = false ; } } return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < MicrodataItem > getItems ( String type ) { List < WebElement > elements = driver . findElements ( byItemType ( newUrl ( type ) ) ) ; return Lists . transform ( elements , new Function < WebElement , MicrodataItem > ( ) { public MicrodataItem apply ( WebElement element ) { return new SeleniumMicrodataItem ( driver , element ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public < T > T unwrap ( Class < T > type ) { checkArgument ( WebDriver . class . equals ( type ) , \"Cannot unwrap to: %s\" , type ) ; return type . cast ( driver ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a string containing information about the configured logging set up . [CODESPLIT] public static String currentConfiguration ( ) { StringBuffer rtn = new StringBuffer ( 1024 ) ; String loggingConfigClass = System . getProperty ( \"java.util.logging.config.class\" ) ; String loggingConfigFile = System . getProperty ( \"java.util.logging.config.file\" ) ; boolean configClassOK = false ; if ( loggingConfigClass == null ) { rtn . append ( \"No java.util.logging.config.class class is set.\\n\" ) ; } else { rtn . append ( \"java.util.logging.config.class is set to '\" ) . append ( loggingConfigClass ) . append ( \"'\\n\" ) ; try { Class c = Class . forName ( loggingConfigClass ) ; c . newInstance ( ) ; rtn . append ( \"This class was loaded and a new instance was sucessfully created.\\n\" ) ; configClassOK = true ; } catch ( ClassNotFoundException e ) { e = null ; rtn . append ( loggingConfigClass ) . append ( \" could not be found.\" ) ; } catch ( InstantiationException e ) { e = null ; rtn . append ( loggingConfigClass ) . append ( \" could not be instantiated.\" ) ; } catch ( IllegalAccessException e ) { e = null ; rtn . append ( loggingConfigClass ) . append ( \" could not be accessed.\" ) ; } } if ( loggingConfigFile == null ) { rtn . append ( \"No java.util.logging.config.file file is set.\\n\" ) ; } else { rtn . append ( \"java.util.logging.config.file is set to '\" ) . append ( loggingConfigFile ) . append ( \"'\\n\" ) ; File loggingFile = new File ( loggingConfigFile ) ; rtn . append ( loggingFile . getAbsolutePath ( ) ) . append ( \"\\n\" ) ; if ( ! loggingFile . exists ( ) || ! loggingFile . isFile ( ) ) { rtn . append ( \"This file does NOT EXIST.\\n\" ) ; } if ( loggingConfigClass != null ) { if ( configClassOK ) { rtn . append ( \"This file is ignored because java.util.logging.config.class is set.\\n\" ) ; } } } Handler [ ] handlers = Logger . getLogger ( \"\" ) . getHandlers ( ) ; listHandlers ( handlers , rtn ) ; return rtn . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists information about logging handlers . [CODESPLIT] private static StringBuffer listHandlers ( Handler [ ] handlers , StringBuffer buffer ) { for ( Handler handler : handlers ) { Class < ? extends Handler > handlerClass = handler . getClass ( ) ; Formatter formatter = handler . getFormatter ( ) ; buffer . append ( \"Handler:\" ) . append ( handlerClass . getName ( ) ) . append ( \"\\n\" ) ; buffer . append ( \"Level:\" ) . append ( handler . getLevel ( ) . toString ( ) ) . append ( \"\\n\" ) ; if ( formatter != null ) { buffer . append ( \"Formatter:\" ) . append ( formatter . getClass ( ) . getName ( ) ) . append ( \"\\n\" ) ; } } return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void setValueWhenHiddenControlThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='hidden' name='c' value='x'/>\" + \"</form>\" + \"</body></html>\" ) ) ; Control control = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . getControl ( \"c\" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( \"Cannot set hidden control value: c\" ) ; control . setValue ( \"y\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='text' name='x'/>\" + \"</form>\" + \"</body></html>\" ) ) ; Control control = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . getControl ( \"x\" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( \"Cannot unwrap to: class java.lang.Void\" ) ; control . unwrap ( Void . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Term term ) { if ( traverser . isEnteringContext ( ) ) { enterTerm ( term ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveTerm ( term ) ; term . setTermTraverser ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Functor functor ) { if ( traverser . isEnteringContext ( ) ) { enterFunctor ( functor ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveFunctor ( functor ) ; functor . setTermTraverser ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Variable variable ) { if ( traverser . isEnteringContext ( ) ) { enterVariable ( variable ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveVariable ( variable ) ; variable . setTermTraverser ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Predicate predicate ) { if ( traverser . isEnteringContext ( ) ) { enterPredicate ( predicate ) ; } else if ( traverser . isLeavingContext ( ) ) { leavePredicate ( predicate ) ; predicate . setTermTraverser ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Clause clause ) { if ( traverser . isEnteringContext ( ) ) { enterClause ( clause ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveClause ( clause ) ; clause . setTermTraverser ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( IntegerType literal ) { if ( traverser . isEnteringContext ( ) ) { enterIntLiteral ( literal ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveIntLiteral ( literal ) ; literal . setTermTraverser ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( LiteralType literal ) { if ( traverser . isEnteringContext ( ) ) { enterLiteral ( literal ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveLiteral ( literal ) ; literal . setTermTraverser ( null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up the offset of the start of the code for the named functor . [CODESPLIT] public WAMCallPoint resolveCallPoint ( int functorName ) { /*log.fine(\"public WAMCallPoint resolveCallPoint(int functorName): called\");*/ WAMCallPoint result = ( WAMCallPoint ) symbolTable . get ( functorName , SYMKEY_CALLPOINTS ) ; if ( result == null ) { result = new WAMCallPoint ( - 1 , 0 , functorName ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void reserveReferenceToLabel ( int labelName , int offset ) { // Create call point with label name if it does not already exist. WAMReservedLabel label = ( WAMReservedLabel ) symbolTable . get ( labelName , SYMKEY_CALLPOINTS ) ; if ( label == null ) { label = new WAMReservedLabel ( labelName ) ; symbolTable . put ( labelName , SYMKEY_CALLPOINTS , label ) ; } // Add to the mapping from the label to referenced from addresses to fill in later. label . referenceList . add ( offset ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void resolveLabelPoint ( int labelName , int address ) { // Create the label with resolved address, if it does not already exist. WAMReservedLabel label = ( WAMReservedLabel ) symbolTable . get ( labelName , SYMKEY_CALLPOINTS ) ; if ( label == null ) { label = new WAMReservedLabel ( labelName ) ; symbolTable . put ( labelName , SYMKEY_CALLPOINTS , label ) ; } label . entryPoint = address ; // Fill in all references to the label with the correct value. This does nothing if the label was just created. for ( Integer offset : label . referenceList ) { emmitCode ( offset , label . entryPoint ) ; } // Keep a reverse lookup from address to label name. reverseTable . put ( address , labelName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records the offset of the start of the code for the named functor . [CODESPLIT] protected WAMCallPoint setCodeAddress ( int functorName , int offset , int length ) { WAMCallPoint entry = new WAMCallPoint ( offset , length , functorName ) ; symbolTable . put ( functorName , SYMKEY_CALLPOINTS , entry ) ; // Keep a reverse lookup from address to functor name. reverseTable . put ( offset , functorName ) ; return entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records the id of an internal function for the named functor . The method name uses the word address but this is not really accurate the address field is used to hold an id of the internal function to be invoked . This method differs from { @link #setCodeAddress ( int int int ) } as it does not set the reverse mapping from the address to the functor name since an address is not really being used . [CODESPLIT] protected WAMCallPoint setInternalCodeAddress ( int functorName , int id ) { WAMCallPoint entry = new WAMCallPoint ( id , 0 , functorName ) ; symbolTable . put ( functorName , SYMKEY_CALLPOINTS , entry ) ; return entry ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if another hierarchy attribute is strict a sub - category of this one . It is a sub - category if it has the same sequence of path labels as this one as a prefix of its whole path label . [CODESPLIT] public boolean isSubCategory ( HierarchyAttribute comp ) { // Check that the comparator is of the same type class as this one. if ( ! comp . attributeClass . attributeClassName . equals ( attributeClass . attributeClassName ) ) { return false ; } // Extract the path labels from this and the comparator. List < String > otherPath = comp . getPathValue ( ) ; List < String > path = getPathValue ( ) ; // Check that the path length of the comparator is the same as this plus one or longer. if ( otherPath . size ( ) <= path . size ( ) ) { return false ; } // Start by assuming that the paths prefixes are the same, then walk down both paths checking they are // the same. boolean subcat = true ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { // Check that the labels really are equal. if ( ! otherPath . get ( i ) . equals ( path . get ( i ) ) ) { subcat = false ; break ; } } return subcat ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the long id of the attribute . [CODESPLIT] public long getId ( ) { // Find the category for this hierarchy attribute value. Tree < CategoryNode > category = attributeClass . lookup . get ( value ) ; // Extract and return the id. return category . getElement ( ) . id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the integer id of the attribute . If the attribute class is finalized this will change the value of this attribute to that of the matched id or raise an exception if no matching id exists . If the attribute class is unfinalized this will change the id value of this attribute within the attribute class to the new id provided that the id has not already been assigned to another attribute value . If it has been assigned to another attribute value then an exception is raised . [CODESPLIT] public void setId ( long id ) throws IllegalArgumentException { // Find the category for this hierarchy attribute value. Tree < CategoryNode > category = attributeClass . lookup . get ( value ) ; // Extract the id. long existingId = category . getElement ( ) . id ; // Do nothing if the new id matches the existing one. if ( id == existingId ) { return ; } // The type is finalized. if ( attributeClass . finalized ) { // Raise an illegal argument exception if the id is not known. HierarchyAttribute newValue = attributeClass . getAttributeFromId ( id ) ; // Otherwise, change the value of this attribute to that of the new id. this . value = newValue . value ; } // The type is unfinalized. else { // Check if another instance of the type already has the id and raise an exception if so. Tree < CategoryNode > existingNode = attributeClass . idMap . get ( id ) ; if ( existingNode != null ) { throw new IllegalArgumentException ( \"The id value, \" + id + \", cannot be set because another instance of this type with that \" + \"id already exists.\" ) ; } // Assign it to this instance if the type is unfinalized. Also removing the old id mapping from the id // map and replacing it with the new one. category . getElement ( ) . id = id ; attributeClass . idMap . remove ( existingId ) ; attributeClass . idMap . put ( id , category ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the label value at the named level of the hierarchy . [CODESPLIT] public String getValueAtLevel ( String level ) { /*log.fine(\"public String getValueAtLevel(String level): called\");*/ /*log.fine(\"level = \" + level);*/ int index = attributeClass . levels . indexOf ( level ) ; /*log.fine(\"index = \" + index);*/ if ( index == - 1 ) { throw new IllegalArgumentException ( \"Level name \" + level + \" is not known to this hierarchy attribute type.\" ) ; } return getValueAtLevel ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the label value at the last level of the hierarchy . [CODESPLIT] public String getLastValue ( ) { List < String > pathValue = getPathValue ( ) ; return pathValue . get ( pathValue . size ( ) - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Serialized a hierarchy attribute . [CODESPLIT] private void writeObject ( ObjectOutputStream out ) throws IOException { // Print out some information about the serialized object. /*log.fine(\"Serialized hierarchy attribute = \" + this);*/ /*log.fine(\"Serialized hierarchy attribute class = \" + attributeClass);*/ /*log.fine(\"Serialized attribute classes in static class map are: \");*/ for ( HierarchyClassImpl attributeClass : attributeClasses . values ( ) ) { /*log.fine(attributeClass.toString());*/ } // Perform default serialization. // out.defaultWriteObject(); // Serialized the attribute by value, that is, its full path and the name of its attribute class. List < String > pathValue = getPathValue ( ) ; String [ ] pathArrayValue = pathValue . toArray ( new String [ pathValue . size ( ) ] ) ; out . writeObject ( pathArrayValue ) ; out . writeObject ( attributeClass . getName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Deserializes a hierarchy attribute . [CODESPLIT] private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { // Perform default de-serialization. // in.defaultReadObject(); // Deserialize the attribute by value, from its attribute class and full path. String [ ] pathArrayValue = ( String [ ] ) in . readObject ( ) ; String attributeClassName = ( String ) in . readObject ( ) ; // Re-create the attribute from its value representation. HierarchyAttribute attr = getFactoryForClass ( attributeClassName ) . createHierarchyAttribute ( pathArrayValue ) ; // Copy the fields from the freshly constructed attribute into this one. value = attr . value ; attributeClass = attr . attributeClass ; // Print out some information about the deserialized object. /*log.fine(\"Deserialized hierarchy attribute = \" + this);*/ /*log.fine(\"Deserialized hierarchy attribute class = \" + attributeClass);*/ /*log.fine(\"Deserialized attribute classes in static class map are: \");*/ for ( HierarchyClassImpl attributeClass : attributeClasses . values ( ) ) { /*log.fine(attributeClass.toString());*/ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns heuristic evaluation of an eight puzzle board position as the manhattan distance of all tiles from their correct positions . [CODESPLIT] public float computeH ( EightPuzzleState state , HeuristicSearchNode searchNode ) { // Get the parent heuristic search node. HeuristicSearchNode parentNode = ( HeuristicSearchNode ) searchNode . getParent ( ) ; // Check if there is no parent, in which case this is the start state so the complete heuristic needs // to be calculated. if ( parentNode == null ) { // Used to hold the running total. int h = 0 ; // Loop over the whole board. for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { char nextTile = state . getTileAt ( i , j ) ; // Look up the board position of the tile in the solution. int goalX = state . getGoalXForTile ( nextTile ) ; int goalY = state . getGoalYForTile ( nextTile ) ; // Compute the manhattan distance and add it to the total. int diffX = goalX - i ; diffX = ( diffX < 0 ) ? - diffX : diffX ; int diffY = goalY - j ; diffY = ( diffY < 0 ) ? - diffY : diffY ; h += diffX + diffY ; } } // Convert the result to a float and return it return ( float ) h ; } // There is a parent node so calculate the heuristic incrementally from it. else { // Get the parent board state. EightPuzzleState parentState = ( EightPuzzleState ) parentNode . getState ( ) ; // Get the parent heurstic value. float h = parentNode . getH ( ) ; // Get the move that was played. char playedMove = ( ( String ) searchNode . getAppliedOp ( ) . getOp ( ) ) . charAt ( 0 ) ; // Get the position of the empty tile on the parent board. int emptyX = parentState . getEmptyX ( ) ; int emptyY = parentState . getEmptyY ( ) ; // Work out which tile has been moved, this is the tile that now sits where the empty tile was. char movedTile = state . getTileAt ( emptyX , emptyY ) ; // The tile has either moved one step closer to its goal location or one step further away, decide which it // is. Calculate the X or Y position that the tile moved from. int oldX = 0 ; int oldY = 0 ; switch ( playedMove ) { case ' ' : { oldX = emptyX - 1 ; break ; } case ' ' : { oldX = emptyX + 1 ; break ; } case ' ' : { oldY = emptyY - 1 ; break ; } case ' ' : { oldY = emptyY + 1 ; break ; } default : { throw new IllegalStateException ( \"Unkown operator: \" + playedMove + \".\" ) ; } } // Calculate the change in heuristic. int change = 0 ; switch ( playedMove ) { // Catch the case where a horizontal move was made. case ' ' : case ' ' : { // Get the X position of the tile in the goal state and current state int goalX = state . getGoalXForTile ( movedTile ) ; int newX = emptyX ; // Calculate the change in the heuristic int oldDiffX = oldX - goalX ; oldDiffX = ( oldDiffX < 0 ) ? - oldDiffX : oldDiffX ; int newDiffX = newX - goalX ; newDiffX = ( newDiffX < 0 ) ? - newDiffX : newDiffX ; change = newDiffX - oldDiffX ; break ; } // Catch the case where a vertical move was made. case ' ' : case ' ' : { // Get the Y position of the tile in the goal state and current state int goalY = state . getGoalYForTile ( movedTile ) ; int newY = emptyY ; // Calculate the change in the heuristic int oldDiffY = oldY - goalY ; oldDiffY = ( oldDiffY < 0 ) ? - oldDiffY : oldDiffY ; int newDiffY = newY - goalY ; newDiffY = ( newDiffY < 0 ) ? - newDiffY : newDiffY ; change = newDiffY - oldDiffY ; break ; } default : { throw new IllegalStateException ( \"Unkown operator: \" + playedMove + \".\" ) ; } } // Return the parent heuristic plus or minus one. return ( change > 0 ) ? ( h + 1.0f ) : ( h - 1.0f ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified key in this map . [CODESPLIT] public V put ( K key , V value ) { // Remove any existing matching key from the data V removedObject = remove ( key ) ; // Insert the data into the map. dataMap . put ( key , value ) ; // If the key is fresh, enqueue it. if ( removedObject != null ) { keys . offer ( key ) ; } // Return the replaced value if there was one return removedObject ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns <tt > true< / tt > if this map contains a mapping for the specified coordinates . [CODESPLIT] public boolean containsKey ( Long x , Long y ) { // Extract the region containing the coordinates from the hash table Bucket region = ( Bucket ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the whole region is empty if ( region == null ) { return false ; } // Check if the coordinates within the region contain data return ( region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] != null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified coordinate in this map ( optional operation ) . If the map previously contained a mapping for this coordinate the old value is replaced . [CODESPLIT] public E put ( Long x , Long y , E value ) { // Check that the value is not null as this data structure does not allow nulls if ( value == null ) { throw new IllegalArgumentException ( \"Null values not allowed in HashMapXY data structure.\" ) ; } // Extract the region containing the coordinates from the hash table Bucket < E > region = ( Bucket < E > ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the region does not exist yet and create it if so if ( region == null ) { region = new Bucket < E > ( bucketSize ) ; regions . put ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) , region ) ; } // Take a reference to the old value if there is one E old = region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] ; // Insert the new value into the bucket region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] = value ; // Increment the bucket and whole data structure item counts to reflect the true size size ++ ; region . itemCount ++ ; // Return the replaced value return old ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the mapping for this coordinate from this map if present ( optional operation ) . [CODESPLIT] public E remove ( Long x , Long y ) { // Extract the region containing the coordinates from the hash table Bucket < E > region = ( Bucket < E > ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the whole region is empty if ( region == null ) { // Return null as nothing to remove return null ; } // Get the coordinates within the region E removed = ( region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] ) ; // Clear the coordinate within the region region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] = null ; // Decrement the bucket and whole data strucutre item counts to reflect the true size size -- ; region . itemCount -- ; // Return the removed data item return removed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the modulo of a coordinate with the bucket size . Correctly calculates this module for negative coordinates such the the first negative bucket is - 1 with element 0 corresponding to - 100 running to 99 corresponding to - 1 . [CODESPLIT] private int mod ( long c , int bucketSize ) { return ( int ) ( ( c < 0 ) ? ( ( bucketSize + ( c % bucketSize ) ) % bucketSize ) : ( c % bucketSize ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds another user readable error message to this exception . [CODESPLIT] public void addErrorMessage ( String key , String userMessage ) { /*log.fine(\"addErrorMessage(String key, String userMessage): called\");*/ /*log.fine(\"userMessage = \" + userMessage);*/ errors . add ( new UserReadableErrorImpl ( key , userMessage ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts an exception into struts action errors . The exception stack trace is stored under the exception message key . The message resource error . internalerror is stored under the message key generalerror . The stack trace is pretty printed in HTML . [CODESPLIT] public static void handleErrors ( Throwable exception , ActionErrors errors ) { // Log the error. log . log ( Level . SEVERE , exception . getMessage ( ) , exception ) ; if ( exception . getCause ( ) == null ) { log . fine ( \"Exception.getCause() is null\" ) ; } // Unwrap the exception if it is a WrappedStrutsServletException, which is a place holder for returning // other throwables from struts actions. // See BaseAction and WrappedStrutsServletException for more information. if ( ( exception instanceof WrappedStrutsServletException ) && ( exception . getCause ( ) != null ) ) { exception = exception . getCause ( ) ; log . fine ( \"Unwrapped WrappedStrutsServletException\" ) ; } // Create an error called 'exception' in the Struts errors for debugging purposes // Debugging code can print this piece of html containing the exception stack trace at the bottom // of the page for convenience. Writer stackTrace = new StringWriter ( ) ; exception . printStackTrace ( new PrintWriter ( new HTMLFilter ( stackTrace ) ) ) ; errors . add ( \"exception\" , new ActionError ( \"error.general\" , stackTrace ) ) ; // Check if the exception is a user readable exception if ( exception instanceof UserReadableError ) { UserReadableError userError = ( UserReadableError ) exception ; // Check that it contains a user readable message if ( userError . isUserReadable ( ) ) { // Check if there is an error message key to use if ( userError . getUserMessageKey ( ) != null ) { errors . add ( \"generalerror\" , new ActionError ( userError . getUserMessageKey ( ) , userError . getUserMessageKey ( ) ) ) ; } // There is no error message key to use so default to error.general and pass the error message as an // argument so that it will be displayed else { errors . add ( \"generalerror\" , new ActionError ( \"error.general\" , userError . getUserMessage ( ) ) ) ; } return ; } } // Not a user reable exception so print a standard error message errors . add ( \"generalerror\" , new ActionError ( \"error.internalerror\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes a string of characters to the filtered writer . Any newline characters \\ n are replaced with an HTML break tag &lt ; br&gt ; . [CODESPLIT] public void write ( String str , int off , int len ) throws IOException { // Get just the portion of the input string to display String inputString = str . substring ( off , off + len ) ; StringBuffer outputString = new StringBuffer ( ) ; // Build a string tokenizer that uses '\\n' as its splitting character // Cycle through all tokens for ( StringTokenizer tokenizer = new StringTokenizer ( inputString , \"\\n\" , true ) ; tokenizer . hasMoreTokens ( ) ; ) { // Replace '\\n' token with a <br> String nextToken = tokenizer . nextToken ( ) ; if ( \"\\n\" . equals ( nextToken ) ) { outputString . append ( \"<br>\" ) ; } else { outputString . append ( nextToken ) ; } } // Write out the generated string out . write ( outputString . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Perform any handshaking processing . <P > If a SelectionKey is passed register for selectable operations . <P > In the blocking case our caller will keep calling us until we finish the handshake . Our reads / writes will block as expected . <P > In the non - blocking case we just received the selection notification that this channel is ready for whatever the operation is so give it a try . <P > return : true when handshake is done . false while handshake is in progress [CODESPLIT] boolean doHandshake ( SelectionKey sk ) throws IOException { SSLEngineResult result ; if ( initialHSComplete ) { return true ; } /*\n     * Flush out the outgoing buffer, if there's anything left in\n\t * it.\n\t */ if ( outNetBB . hasRemaining ( ) ) { if ( ! tryFlush ( outNetBB ) ) { return false ; } // See if we need to switch from write to read mode. switch ( initialHSStatus ) { /*\n         * Is this the last buffer?\n\t     */ case FINISHED : initialHSComplete = true ; // Fall-through to reregister need for a Read. case NEED_UNWRAP : if ( sk != null ) { sk . interestOps ( SelectionKey . OP_READ ) ; } break ; } return initialHSComplete ; } switch ( initialHSStatus ) { case NEED_UNWRAP : if ( sc . read ( inNetBB ) == - 1 ) { sslEngine . closeInbound ( ) ; return initialHSComplete ; } needIO : while ( initialHSStatus == HandshakeStatus . NEED_UNWRAP ) { /*\n         * Don't need to resize requestBB, since no app data should\n\t\t * be generated here.\n\t\t */ inNetBB . flip ( ) ; result = sslEngine . unwrap ( inNetBB , requestBB ) ; inNetBB . compact ( ) ; initialHSStatus = result . getHandshakeStatus ( ) ; switch ( result . getStatus ( ) ) { case OK : switch ( initialHSStatus ) { case NOT_HANDSHAKING : throw new IOException ( \"Not handshaking during initial handshake\" ) ; case NEED_TASK : initialHSStatus = doTasks ( ) ; break ; case FINISHED : initialHSComplete = true ; break needIO ; } break ; case BUFFER_UNDERFLOW : /*\n             * Need to go reread the Channel for more data.\n\t\t     */ if ( sk != null ) { sk . interestOps ( SelectionKey . OP_READ ) ; } break needIO ; default : // BUFFER_OVERFLOW/CLOSED: throw new IOException ( \"Received\" + result . getStatus ( ) + \"during initial handshaking\" ) ; } } // \"needIO\" block. /*\n         * Just transitioned from read to write.\n\t     */ if ( initialHSStatus != HandshakeStatus . NEED_WRAP ) { break ; } // Fall through and fill the write buffers. case NEED_WRAP : /*\n         * The flush above guarantees the out buffer to be empty\n\t     */ outNetBB . clear ( ) ; result = sslEngine . wrap ( hsBB , outNetBB ) ; outNetBB . flip ( ) ; initialHSStatus = result . getHandshakeStatus ( ) ; switch ( result . getStatus ( ) ) { case OK : if ( initialHSStatus == HandshakeStatus . NEED_TASK ) { initialHSStatus = doTasks ( ) ; } if ( sk != null ) { sk . interestOps ( SelectionKey . OP_WRITE ) ; } break ; default : // BUFFER_OVERFLOW/BUFFER_UNDERFLOW/CLOSED: throw new IOException ( \"Received\" + result . getStatus ( ) + \"during initial handshaking\" ) ; } break ; default : // NOT_HANDSHAKING/NEED_TASK/FINISHED throw new RuntimeException ( \"Invalid Handshaking State\" + initialHSStatus ) ; } // switch return initialHSComplete ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Read the channel for more information then unwrap the ( hopefully application ) data we get . <P > If we run out of data we ll return to our caller ( possibly using a Selector ) to get notification that more is available . <P > Each call to this method will perform at most one underlying read () . [CODESPLIT] ByteBuffer read ( ) throws IOException { SSLEngineResult result ; if ( ! initialHSComplete ) { throw new IllegalStateException ( ) ; } int pos = requestBB . position ( ) ; if ( sc . read ( inNetBB ) == - 1 ) { sslEngine . closeInbound ( ) ; // probably throws exception throw new EOFException ( ) ; } do { resizeRequestBB ( inNetBB . remaining ( ) ) ; // guarantees enough room for unwrap inNetBB . flip ( ) ; result = sslEngine . unwrap ( inNetBB , requestBB ) ; inNetBB . compact ( ) ; /*\n         * Could check here for a renegotation, but we're only\n\t     * doing a simple read/write, and won't have enough state\n\t     * transitions to do a complete handshake, so ignore that\n\t     * possibility.\n\t     */ switch ( result . getStatus ( ) ) { case BUFFER_UNDERFLOW : case OK : if ( result . getHandshakeStatus ( ) == HandshakeStatus . NEED_TASK ) { doTasks ( ) ; } break ; default : throw new IOException ( \"sslEngine error during data read: \" + result . getStatus ( ) ) ; } } while ( ( inNetBB . position ( ) != 0 ) && result . getStatus ( ) != Status . BUFFER_UNDERFLOW ) ; int readLength = requestBB . position ( ) - pos ; ByteBuffer byteBuffer = ByteBuffer . allocate ( readLength ) ; byteBuffer . put ( BytesUtil . subBytes ( requestBB . array ( ) , pos , readLength ) ) ; return byteBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Try to flush out any existing outbound data then try to wrap anything new contained in the src buffer . <P > Return the number of bytes actually consumed from the buffer but the data may actually be still sitting in the output buffer waiting to be flushed . [CODESPLIT] private int doWrite ( ByteBuffer src ) throws IOException { int retValue = 0 ; if ( outNetBB . hasRemaining ( ) && ! tryFlush ( outNetBB ) ) { return retValue ; } /*\n     * The data buffer is empty, we can reuse the entire buffer.\n\t */ outNetBB . clear ( ) ; SSLEngineResult result = sslEngine . wrap ( src , outNetBB ) ; retValue = result . bytesConsumed ( ) ; outNetBB . flip ( ) ; switch ( result . getStatus ( ) ) { case OK : if ( result . getHandshakeStatus ( ) == HandshakeStatus . NEED_TASK ) { doTasks ( ) ; } break ; default : throw new IOException ( \"sslEngine error during data write: \" + result . getStatus ( ) ) ; } /*\n     * Try to flush the data, regardless of whether or not\n\t * it's been selected.  Odds of a write buffer being full\n\t * is less than a read buffer being empty.\n\t */ tryFlush ( src ) ; if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return retValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Flush any remaining data . <P > Return true when the fileChannelBB and outNetBB are empty . [CODESPLIT] boolean dataFlush ( ) throws IOException { boolean fileFlushed = true ; if ( ( fileChannelBB != null ) && fileChannelBB . hasRemaining ( ) ) { doWrite ( fileChannelBB ) ; fileFlushed = ! fileChannelBB . hasRemaining ( ) ; } else if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return ( fileFlushed && ! outNetBB . hasRemaining ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Begin the shutdown process . <P > Close out the SSLEngine if not already done so then wrap our outgoing close_notify message and try to send it on . <P > Return true when we re done passing the shutdown messsages . [CODESPLIT] boolean shutdown ( ) throws IOException { if ( ! shutdown ) { sslEngine . closeOutbound ( ) ; shutdown = true ; } if ( outNetBB . hasRemaining ( ) && tryFlush ( outNetBB ) ) { return false ; } /*\n     * By RFC 2616, we can \"fire and forget\" our close_notify\n\t * message, so that's what we'll do here.\n\t */ outNetBB . clear ( ) ; SSLEngineResult result = sslEngine . wrap ( hsBB , outNetBB ) ; if ( result . getStatus ( ) != Status . CLOSED ) { throw new SSLException ( \"Improper close state\" ) ; } outNetBB . flip ( ) ; /*\n     * We won't wait for a select here, but if this doesn't work,\n\t * we'll cycle back through on the next select.\n\t */ if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return ( ! outNetBB . hasRemaining ( ) && ( result . getHandshakeStatus ( ) != HandshakeStatus . NEED_WRAP ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < Operator < Term > > traverse ( Predicate predicate , boolean reverse ) { /*log.fine(\"Traversing predicate \" + predicate.toString());*/ Clause [ ] body = predicate . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // For the predicate bodies. if ( body != null ) { for ( int i = leftToRightPredicateBodies ? 0 : ( body . length - 1 ) ; leftToRightPredicateBodies ? ( i < body . length ) : ( i >= 0 ) ; i = i + ( leftToRightPredicateBodies ? 1 : - 1 ) ) { Clause bodyClause = body [ i ] ; bodyClause . setReversable ( createClauseOperator ( bodyClause , i , body , predicate ) ) ; bodyClause . setTermTraverser ( this ) ; queue . offer ( bodyClause ) ; } } return queue . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < Operator < Term > > traverse ( Clause clause , boolean reverse ) { /*log.fine(\"Traversing clause \" + clause.toString());*/ Functor head = clause . getHead ( ) ; Functor [ ] body = clause . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // For the head functor, set the top-level flag, set in head context. if ( head != null ) { head . setReversable ( createHeadOperator ( head , clause ) ) ; head . setTermTraverser ( this ) ; queue . offer ( head ) ; } // For the body functors, set the top-level flag, clear in head context. if ( body != null ) { for ( int i = leftToRightClauseBodies ? 0 : ( body . length - 1 ) ; leftToRightClauseBodies ? ( i < body . length ) : ( i >= 0 ) ; i = i + ( leftToRightClauseBodies ? 1 : - 1 ) ) { Functor bodyFunctor = body [ i ] ; bodyFunctor . setReversable ( createBodyOperator ( bodyFunctor , i , body , clause ) ) ; bodyFunctor . setTermTraverser ( this ) ; queue . offer ( bodyFunctor ) ; } } return queue . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < Operator < Term > > traverse ( Functor functor , boolean reverse ) { /*log.fine(\"Traversing functor \" + functor.toString());*/ Queue < Operator < Term >> queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; Term [ ] arguments = functor . getArguments ( ) ; // For a top-level functor clear top-level flag, so that child functors are not taken as top-level. if ( arguments != null ) { for ( int i = leftToRightFunctorArgs ? 0 : ( arguments . length - 1 ) ; leftToRightFunctorArgs ? ( i < arguments . length ) : ( i >= 0 ) ; i = i + ( leftToRightFunctorArgs ? 1 : - 1 ) ) { Term argument = arguments [ i ] ; argument . setReversable ( createTermOperator ( argument , i , functor ) ) ; argument . setTermTraverser ( this ) ; queue . offer ( argument ) ; } } return queue . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] protected void enterFunctor ( Functor functor ) { if ( isTopLevel ( ) ) { symbolTable . put ( functor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR , true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Functors are considered top - level when they appear at the top - level within a clause or directly beneath a parent conjunction or disjunction that is considered to be top - level . [CODESPLIT] private boolean isTopLevel ( ) { if ( traverser . isTopLevel ( ) ) { return true ; } else { PositionalContext parentContext = traverser . getParentContext ( ) ; if ( parentContext != null ) { Term parentTerm = parentContext . getTerm ( ) ; if ( ( parentTerm instanceof Conjunction ) || ( parentTerm instanceof Disjunction ) ) { Boolean isTopLevel = ( Boolean ) symbolTable . get ( parentTerm . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR ) ; return ( isTopLevel == null ) ? false : isTopLevel ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void insertAttribute ( AttributeSet attributes , int c , int r ) { attributeGrid . insertAttribute ( attributes , c , r ) ; updateListeners ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void select ( int row , int col ) { for ( TextGridSelectionListener listener : textGridSelectionListeners ) { listener . select ( new TextGridEvent ( this , row , col ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public EnhancedTextTable createTable ( int c , int r , int w , int h ) { // Supply a text table, with this grid set up to listen for updates to the table, and to be re-rendered as the // table changes. EnhancedTextTable textTable = new EnhancedTextTableImpl ( ) ; textTable . addTextTableListener ( new EnhancedTableListener ( ) ) ; return textTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Classifies a state using the decision tree . [CODESPLIT] public Map < String , OrdinalAttribute > classify ( State state ) throws ClassifyingFailureException { // Start at the root of the decision tree. DecisionTree currentNode = dt ; // Loop down the decision tree until a leaf node is found. while ( true ) // !currentNode.isLeaf()) { DecisionTreeElement element = currentNode . getElement ( ) ; // Check that the current element really is a decision. if ( element instanceof Decision ) { Decision decision = ( Decision ) element ; // Apply the decision at the current node to the state to be classified to get a new tree. currentNode = decision . decide ( state ) ; // , currentNode); } else if ( element instanceof Assignment ) { // Cast the element to an Assignment as this is the only type of leaf that is possible. Assignment assignment = ( Assignment ) element ; // Return the assignment in a map. Map < String , OrdinalAttribute > assignmentMap = new HashMap < String , OrdinalAttribute > ( ) ; assignmentMap . put ( assignment . getPropertyName ( ) , assignment . getAttribute ( ) ) ; return assignmentMap ; } // It is possible that a node may be of type Pending if an incomplete tree has been used to // run this classification on. else { // Throw a classification exception due to an incomplete decision tree. throw new ClassifyingFailureException ( \"A node which is not a decision was encountered.\" , null ) ; } // What happens if the decision could not operate on the state, either because of a missing property or // because its property was not of the type that the decision was expecting? Can either throw an exception, // return an empty assignment, or implement an algorithm for coping with missing properties. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getIdReturnsId ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://y' itemid='http://x'/>\" + \"</body></html>\" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://y\" ) . getId ( ) ; assertThat ( \"item id\" , actual , is ( new URL ( \"http://x\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getTypeReturnsType ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://x'/>\" + \"</body></html>\" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://x\" ) . getType ( ) ; assertThat ( \"item type\" , actual , is ( new URL ( \"http://x\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getPropertyReturnsProperty ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'>\" + \"<p itemprop='x'/>\" + \"</div>\" + \"</body></html>\" ) ) ; MicrodataProperty actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) . getProperty ( \"x\" ) ; assertThat ( \"item property\" , actual . getName ( ) , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://i'/>\" + \"</body></html>\" ) ) ; MicrodataItem item = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( \"http://i\" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( \"Cannot unwrap to: class java.lang.Void\" ) ; item . unwrap ( Void . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Translates the partial order into the + 1 0 - 1 convention needed by Comparators . [CODESPLIT] public int compare ( T a , T b ) { boolean aRb = partialOrdering . evaluate ( a , b ) ; if ( ! aRb ) { return - 1 ; } boolean bRa = partialOrdering . evaluate ( b , a ) ; return ( aRb && bRa ) ? 0 : 1 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a priority queue with an { @link AStarComparator } to control the search ordering of the basic queue search algorithm . [CODESPLIT] public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new AStarComparator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < Operator < Term > > traverse ( Clause clause , boolean reverse ) { /*log.fine(\"Traversing clause \" + clause.toString(interner, true, false));*/ Functor head = clause . getHead ( ) ; Functor [ ] body = clause . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // Create a nested scope in the symbol table for the clause, under its functor name/arity. int predicateName ; int clauseIndex ; if ( clause . isQuery ( ) ) { predicateName = - 1 ; } else { predicateName = head . getName ( ) ; } Integer numberOfClauses = ( Integer ) rootSymbolTable . get ( predicateName , CLAUSE_NO_SYMBOL_FIELD ) ; if ( numberOfClauses == null ) { numberOfClauses = 0 ; } rootSymbolTable . put ( predicateName , CLAUSE_NO_SYMBOL_FIELD , numberOfClauses + 1 ) ; clauseIndex = numberOfClauses ; SymbolTable < Integer , String , Object > predicateScopedSymbolTable = rootSymbolTable . enterScope ( predicateName ) ; /*log.fine(indenter.generateTraceIndent(2) + \"Enter predicate scope \" + predicateName);*/ clauseScopedSymbolTable = predicateScopedSymbolTable . enterScope ( clauseIndex ) ; /*log.fine(indenter.generateTraceIndent(2) + \"Enter clause scope \" + clauseIndex);*/ // For the head functor, clear the top-level flag, set in head context. if ( head != null ) { head . setReversable ( new ContextOperator ( clauseScopedSymbolTable , 0 , createHeadOperator ( head , clause ) ) ) ; head . setTermTraverser ( this ) ; queue . offer ( head ) ; /*log.fine(\"Set SKT as traverser on \" + head.toString(interner, true, false));*/ /*log.fine(\"Created: \" + (\"head operator \" + 0 + \" on \" + head.toString(interner, true, false)));*/ } // For the body functors, set the top-level flag, clear in head context. if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { Functor bodyFunctor = body [ i ] ; bodyFunctor . setReversable ( new ContextOperator ( clauseScopedSymbolTable , i + 1 , createBodyOperator ( bodyFunctor , i , body , clause ) ) ) ; bodyFunctor . setTermTraverser ( this ) ; queue . offer ( bodyFunctor ) ; /*log.fine(\"Set SKT as traverser on \" + bodyFunctor.toString(interner, true, false));*/ /*log.fine(\"Created: \" +\n                    (\"body operator \" + (i + 1) + \" on \" + bodyFunctor.toString(interner, true, false)));*/ } } return queue . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < Operator < Term > > traverse ( Functor functor , boolean reverse ) { /*log.fine(\"Traversing functor \" + functor.toString(interner, true, false));*/ Queue < Operator < Term >> queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; Term [ ] arguments = functor . getArguments ( ) ; // For a top-level functor clear top-level flag, so that child functors are not taken as top-level. if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { Term argument = arguments [ i ] ; // When navigating onto a variable, the variable is scoped within a clause, and may appear many times // within it. Therefore it always uses its unique id relative to the root symbol table for the // clause as its contextual position. Other terms use their position path and are relative to the // the current positions symbol table. SymbolTable < Integer , String , Object > contextSymbolTable ; if ( argument . isVar ( ) ) { contextSymbolTable = clauseScopedSymbolTable . enterScope ( CLAUSE_FREEVAR_INDEX ) ; /*log.fine(\"Enter freevar scope\");*/ argument . setReversable ( new ContextOperator ( contextSymbolTable , createTermOperator ( argument , i , functor ) ) ) ; argument . setTermTraverser ( this ) ; queue . offer ( argument ) ; /*log.fine(\"Created: \" +\n                        (\"var argument operator on \" + argument.toString(interner, true, false)));*/ } else { contextSymbolTable = null ; argument . setReversable ( new ContextOperator ( contextSymbolTable , i , createTermOperator ( argument , i , functor ) ) ) ; argument . setTermTraverser ( this ) ; queue . offer ( argument ) ; /*log.fine(\"Created: \" +\n                        (\"argument operator \" + i + \" on \" + argument.toString(interner, true, false)));*/ } } } return queue . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void visit ( Term term ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( currentPosition ) ; term . setSymbolKey ( key ) ; } if ( delegate != null ) { delegate . visit ( term ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void visit ( Variable variable ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( variable . getId ( ) ) ; variable . setSymbolKey ( key ) ; /*log.fine(variable.toString(interner, true, false) + \" assigned \" + key);*/ } else if ( isLeavingContext ( ) ) { variable . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( variable ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Predicate predicate ) { if ( isEnteringContext ( ) ) { super . visit ( predicate ) ; } else if ( isLeavingContext ( ) ) { predicate . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( predicate ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Clause clause ) { if ( isEnteringContext ( ) ) { super . visit ( clause ) ; } else if ( isLeavingContext ( ) ) { clause . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( clause ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Functor functor ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( currentPosition ) ; functor . setSymbolKey ( key ) ; /*log.fine(functor.toString(interner, true, false) + \" assigned \" + key);*/ } else if ( isLeavingContext ( ) ) { functor . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( functor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( IntegerType literal ) { if ( isEnteringContext ( ) ) { SymbolKey key = currentSymbolTable . getSymbolKey ( currentPosition ) ; literal . setSymbolKey ( key ) ; } else if ( isLeavingContext ( ) ) { literal . setTermTraverser ( null ) ; } if ( delegate != null ) { delegate . visit ( literal ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a distriubuted iterator that can provide elements of the list on demand over a remote connection . [CODESPLIT] public Iterator iterator ( ) { try { DistributedIteratorImpl di ; di = new DistributedIteratorImpl ( super . iterator ( ) ) ; return new ClientIterator ( di ) ; } catch ( RemoteException e ) { // Rethrow the RemoteException as a RuntimeException so as not to conflict with the interface of ArrayList throw new IllegalStateException ( \"There was a RemoteExcpetion.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calcalates the log base 2 of an integer . This code is tuned to uniformly distributed output values longer numbers are slightly favoured . [CODESPLIT] public static int intLogBase2 ( int value ) { int temp1 ; int temp2 = value >> 16 ; if ( temp2 > 0 ) { temp1 = temp2 >> 8 ; return ( temp1 > 0 ) ? ( 24 + LOG_TABLE_256 [ temp1 ] ) : ( 16 + LOG_TABLE_256 [ temp2 ] ) ; } else { temp1 = value >> 8 ; return ( temp1 > 0 ) ? ( 8 + LOG_TABLE_256 [ temp1 ] ) : LOG_TABLE_256 [ value ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calcalates the log base 2 of an integer . This code is tuned to uniformly distributed input values longer numbers are favoured . [CODESPLIT] public static int intLogBase2v2 ( int value ) { int temp ; if ( ( temp = value >> 24 ) > 0 ) { return 24 + LOG_TABLE_256 [ temp ] ; } else if ( ( temp = value >> 16 ) > 0 ) { return 16 + LOG_TABLE_256 [ temp ] ; } else if ( ( temp = value >> 8 ) > 0 ) { return 8 + LOG_TABLE_256 [ temp ] ; } else { return LOG_TABLE_256 [ value ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calcalates the log base 2 of an integer in O ( log ( N )) steps ; shorter numbers are favoured . [CODESPLIT] public static int intLogBase2v3 ( int value ) { int result = 0 ; if ( ( value & LOG2_V3_BRANCH_VALUES [ 4 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 4 ] ; result |= LOG2_V3_SHIFT_VALUES [ 4 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 3 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 3 ] ; result |= LOG2_V3_SHIFT_VALUES [ 3 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 2 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 2 ] ; result |= LOG2_V3_SHIFT_VALUES [ 2 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 1 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 1 ] ; result |= LOG2_V3_SHIFT_VALUES [ 1 ] ; } if ( ( value & LOG2_V3_BRANCH_VALUES [ 0 ] ) > 0 ) { value >>= LOG2_V3_SHIFT_VALUES [ 0 ] ; result |= LOG2_V3_SHIFT_VALUES [ 0 ] ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calcalates the log base 10 of an integer . This produces results faster for longer numbers . [CODESPLIT] public static int intLogBase10v2 ( int value ) { return ( value >= 1000000000 ) ? 9 : ( ( value >= 100000000 ) ? 8 : ( ( value >= 10000000 ) ? 7 : ( ( value >= 1000000 ) ? 6 : ( ( value >= 100000 ) ? 5 : ( ( value >= 10000 ) ? 4 : ( ( value >= 1000 ) ? 3 : ( ( value >= 100 ) ? 2 : ( ( value >= 10 ) ? 1 : 0 ) ) ) ) ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calcalates the log base 10 of an integer . This produces results faster for shorter numbers . [CODESPLIT] public static int intLogBase10v3 ( int value ) { return ( value < 10 ) ? 0 : ( ( value < 100 ) ? 1 : ( ( value < 1000 ) ? 2 : ( ( value < 10000 ) ? 3 : ( ( value < 100000 ) ? 4 : ( ( value < 1000000 ) ? 5 : ( ( value < 10000000 ) ? 6 : ( ( value < 100000000 ) ? 7 : ( ( value < 1000000000 ) ? 8 : 9 ) ) ) ) ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calcalates the log base 10 of an integer . This method favours shorter numbers . [CODESPLIT] public static int intLogBase10 ( long value ) { return ( value >= 1000000000000000000L ) ? 18 : ( ( value >= 100000000000000000L ) ? 17 : ( ( value >= 10000000000000000L ) ? 16 : ( ( value >= 1000000000000000L ) ? 15 : ( ( value >= 100000000000000L ) ? 14 : ( ( value >= 10000000000000L ) ? 13 : ( ( value >= 1000000000000L ) ? 12 : ( ( value >= 100000000000L ) ? 11 : ( ( value >= 10000000000L ) ? 10 : ( ( value >= 1000000000L ) ? 9 : ( ( value >= 100000000L ) ? 8 : ( ( value >= 10000000L ) ? 7 : ( ( value >= 1000000L ) ? 6 : ( ( value >= 100000L ) ? 5 : ( ( value >= 10000L ) ? 4 : ( ( value >= 1000L ) ? 3 : ( ( value >= 100L ) ? 2 : ( ( value >= 10L ) ? 1 : 0 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calcalates the log base 10 of an integer . This method favours longer numbers or evenly distributed input . [CODESPLIT] public static int intLogBase10v2 ( long value ) { return ( value < 10 ) ? 0 : ( ( value < 100 ) ? 1 : ( ( value < 1000 ) ? 2 : ( ( value < 10000 ) ? 3 : ( ( value < 100000 ) ? 4 : ( ( value < 1000000 ) ? 5 : ( ( value < 10000000 ) ? 6 : ( ( value < 100000000 ) ? 7 : ( ( value < 1000000000L ) ? 8 : ( ( value < 10000000000L ) ? 9 : ( ( value < 100000000000L ) ? 10 : ( ( value < 1000000000000L ) ? 11 : ( ( value < 10000000000000L ) ? 12 : ( ( value < 100000000000000L ) ? 13 : ( ( value < 1000000000000000L ) ? 14 : ( ( value < 10000000000000000L ) ? 15 : ( ( value < 100000000000000000L ) ? 16 : ( ( value < 1000000000000000000L ) ? 17 : 18 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the number of ASCII characters that will be needed to represent a specifed signed 32 - bit integer . [CODESPLIT] public static int getCharacterCountInt32 ( int value ) { if ( value >= 0 ) { return getCharacterCountUInt32 ( value ) ; } else if ( value == Integer . MIN_VALUE ) { return getCharacterCountUInt32 ( Integer . MAX_VALUE ) + 1 ; } else { return getCharacterCountUInt32 ( - value ) + 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the number of ASCII characters that will be needed to represent a specifed signed 64 - bit integer . [CODESPLIT] public static int getCharacterCountInt64 ( long value ) { if ( value >= 0 ) { return getCharacterCountUInt64 ( value ) ; } else if ( value == Long . MIN_VALUE ) { return getCharacterCountUInt64 ( Long . MAX_VALUE ) + 1 ; } else { return getCharacterCountUInt64 ( - value ) + 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the number of ASCII characters that will be needed to represent a specified signed decimal number . [CODESPLIT] public static int getCharacterCountDecimal ( long integerValue , int scale ) { boolean isNeg = integerValue < 0 ; // Work out how many digits will be needed for the number, adding space for the minus sign, the decimal // point and leading zeros if needed. int totalDigits = BitHackUtils . getCharacterCountInt64 ( integerValue ) ; int totalLength = totalDigits ; if ( isNeg ) { totalDigits -- ; // Minus sign already accounted for. } if ( scale > 0 ) { totalLength ++ ; // For the decimal point. if ( scale >= totalDigits ) { // For the leading zeros (+ 1 for the zero before decimal point). totalLength += ( scale - totalDigits ) + 1 ; } } else { // Add a zero for each negative point in scale totalLength -= scale ; } return totalLength ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Fader < Color > createFader ( Color startColor , Color endColor ) { return new FaderImpl ( startColor , endColor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void changeColor ( C color ) { AttributeSet aset = new AttributeSet ( ) ; aset . put ( AttributeSet . BACKGROUND_COLOR , color ) ; grid . insertAttribute ( aset , col , row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { Clause query = state . getCurrentClause ( ) ; // The query goals are placed onto the goal stack backwards so that their insertion order is reversed for an // intuitive left-to-right evaluation order. for ( int i = query . getBody ( ) . length - 1 ; i >= 0 ; i -- ) { BuiltInFunctor newGoal = state . getBuiltInTransform ( ) . apply ( query . getBody ( ) [ i ] ) ; state . getGoalStack ( ) . offer ( newGoal ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a compiled head functor to this clause . [CODESPLIT] public void setHead ( Functor head , SizeableList < WAMInstruction > instructions ) { this . head = head ; addInstructions ( instructions ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Emmits the binary byte code for the clause into a machine writing into the specified byte array . The state of this clause is changed to Linked to indicate that it has been linked into a binary machine . [CODESPLIT] public void emmitCode ( ByteBuffer buffer , WAMMachine machine , WAMCallPoint callPoint ) throws LinkageException { // Ensure that the size of the instruction listing does not exceed max int (highly unlikely). if ( sizeof ( ) > Integer . MAX_VALUE ) { throw new IllegalStateException ( \"The instruction listing size exceeds Integer.MAX_VALUE.\" ) ; } // Used to keep track of the size of the emitted code, in bytes, as it is written. int length = 0 ; // Insert the compiled code into the byte code machine's code area. for ( WAMInstruction instruction : instructions ) { instruction . emmitCode ( buffer , machine ) ; length += instruction . sizeof ( ) ; } // Keep record of the machine that the code is hosted in, and the call point of the functor within the machine. this . machine = machine ; this . callPoint = callPoint ; // Record the fact that the code is now linked into a machine. this . status = LinkStatus . Linked ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Listens for events from back next finish and cancel inputs . If the event is finish the { @link #saveWork } method is triggered . If the event is cancel the { @link #discardWork } method is called . If the event is back or next then the { @link #prevPage } or { @link #nextPage } methods are called . [CODESPLIT] public void actionPerformed ( ActionEvent event ) { /*log.fine(\"void actionPerformed(ActionEvent): called\");*/ /*log.fine(\"Action is \" + event.getActionCommand());*/ // Check which action event was performed String action = event . getActionCommand ( ) ; // Check if the finish button was pressed if ( \"Finish\" . equals ( action ) ) { // Save the work in progress saveWorkFlow ( ) ; } // Check if the cancel button was pressed if ( \"Cancel\" . equals ( action ) ) { // Discard the work in progress discardWorkFlow ( ) ; } // Check if the next page button was pressed if ( \"Next |>\" . equals ( action ) ) { // Notify implementing class of transition to the next page nextPage ( ) ; } // Check if the prev page button was pressed if ( \"<| Prev\" . equals ( action ) ) { // Notify implementing class of transition to the previous page prevPage ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the order in which the saveWork or dicardWork methods of the individual screens encountered in a work flow are called . On of the constants { @link #FORWARD_ORDERING } or { @link #REVERSE_ORDERING } should be passed as the value to this method to specify which ordering to use . [CODESPLIT] public void setCommitOrder ( String order ) { // Check that the specified order matches one of the ordering constants if ( ! order . equals ( FORWARD_ORDERING ) && ! order . equals ( REVERSE_ORDERING ) ) { return ; } // Check that the new ordering is different from the existing one so that some work needs to be done to change // it if ( order . equals ( FORWARD_ORDERING ) && ( accessedScreens instanceof LifoStack ) ) { // Copy the screens into a forward ordered stack accessedScreens = new FifoStack ( accessedScreens ) ; } else if ( order . equals ( REVERSE_ORDERING ) && ( accessedScreens instanceof LifoStack ) ) { // Copy the screens into a reverse ordered stack accessedScreens = new LifoStack ( accessedScreens ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method called when the finish button is pressed . It works through all the screens in the order in which they were accessed ( or reverse order depending on the order set by the { [CODESPLIT] protected void saveWorkFlow ( ) { /*log.fine(\"void saveWorkFlow(): called\");*/ // Cycle through all the accessed screens in the work flow while ( ! accessedScreens . isEmpty ( ) ) { WorkFlowScreenPanel nextScreen = ( WorkFlowScreenPanel ) accessedScreens . pop ( ) ; // Check if the screen has unsaved state and call its save work method if so if ( nextScreen . getState ( ) . getState ( ) . equals ( WorkFlowScreenState . NOT_SAVED ) ) { nextScreen . saveWork ( ) ; } } // Call the save work method for the entire work flow controller to finalize the work flow saveWork ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method called when the cancel button is pressed . It works through all the screens in the order in which they were accessed ( or reverse order depending on the order set by the { [CODESPLIT] protected void discardWorkFlow ( ) { /*log.fine(\"void discardWorkFlow(): called\");*/ // Cycle through all the accessed screens in the work flow while ( ! accessedScreens . isEmpty ( ) ) { WorkFlowScreenPanel nextScreen = ( WorkFlowScreenPanel ) accessedScreens . pop ( ) ; // Check if the screen has unsaved state and call its discard work method if so if ( nextScreen . getState ( ) . getState ( ) . equals ( WorkFlowScreenState . NOT_SAVED ) ) { nextScreen . discardWork ( ) ; } } // Call the discard work method for the entire work flow controller to finalize the work flow discardWork ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is a helper method that controller implementations may find useful for moving to a new screen . It places the screen into the panel that this controller was built with replacing any existing screen changes the underlying state to reflect the change to a new current screen and calls the new screens initialize method . [CODESPLIT] protected void setCurrentScreen ( WorkFlowScreenPanel screen ) { // Remove any existing screen from the panel panel . removeAll ( ) ; // Place the new screen into the panel panel . add ( screen ) ; // Check if the screen is not already in the stack of accessed screens. It may be if this is the second time // the screen is visited foir example if the back button is used. if ( ! accessedScreens . contains ( screen ) ) { // Add the screen to the stack of accessed screens accessedScreens . push ( screen ) ; } // Update the work flow state to reflect the change to a new screen state state . setCurrentScreenState ( screen . getState ( ) ) ; // Keep track of the current screen in a local member variable currentScreen = screen ; // Initialize the new screen screen . initialize ( ) ; // Force the panel to redraw panel . validate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a logical predicate . [CODESPLIT] public boolean evaluate ( T t ) { // Start by assuming that the candidate will be a member of the predicate. boolean passed = true ; // Loop through all predicates and fail if any one of them does. for ( UnaryPredicate < T > predicate : chain ) { if ( ! predicate . evaluate ( t ) ) { passed = false ; break ; } } return passed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up a property value relative to the environment callers class and method . The default environment will be checked for a matching property if defaults are being used . In order to work out the callers class and method this method throws an exception and then searches one level up its stack frames . [CODESPLIT] public String getProperty ( String key ) { // Try to get the callers class name and method name by examing the stack. String className = null ; String methodName = null ; // Java 1.4 onwards only. /*try\n        {\n            throw new Exception();\n        }\n        catch (Exception e)\n        {\n            StackTraceElement[] stack = e.getStackTrace();\n\n            // Check that the stack trace contains at least two elements, one for this method and one for the caller.\n            if (stack.length >= 2)\n            {\n                className = stack[1].getClassName();\n                methodName = stack[1].getMethodName();\n            }\n        }*/ // Java 1.5 onwards only. StackTraceElement [ ] stack = Thread . currentThread ( ) . getStackTrace ( ) ; // Check that the stack trace contains at least two elements, one for this method and one for the caller. if ( stack . length >= 2 ) { className = stack [ 1 ] . getClassName ( ) ; methodName = stack [ 1 ] . getMethodName ( ) ; } // Java 1.3 and before? Not sure, some horrible thing that parses the text spat out by printStackTrace? return getProperty ( className , methodName , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up a property value relative to the environment base class and modifier . The default environment will be checked for a matching property if defaults are being used . [CODESPLIT] public String getProperty ( Object base , String modifier , String key ) { return getProperty ( base . getClass ( ) . getName ( ) , modifier , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up a property value relative to the environment base class and modifier . The default environment will be checked for a matching property if defaults are being used . [CODESPLIT] public String getProperty ( String base , String modifier , String key ) { String result = null ; // Loop over the key orderings, from the most specific to the most general, until a matching value is found. for ( Iterator i = getKeyIterator ( base , modifier , key ) ; i . hasNext ( ) ; ) { String nextKey = ( String ) i . next ( ) ; result = super . getProperty ( nextKey ) ; if ( result != null ) { break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up an array property value relative to the environment callers class and method . The default environment will be checked for a matching array property if defaults are being used . In order to work out the callers class and method this method throws an exception and then searches one level up its stack frames . [CODESPLIT] public String [ ] getProperties ( String key ) { // Try to get the callers class name and method name by throwing an exception an searching the stack frames. String className = null ; String methodName = null ; /* Java 1.4 onwards only.\n           try {\n             throw new Exception();\n           } catch (Exception e) {\n             StackTraceElement[] stack = e.getStackTrace();\n             // Check that the stack trace contains at least two elements, one for this method and one for the caller.\n             if (stack.length >= 2) {\n               className = stack[1].getClassName();\n               methodName = stack[1].getMethodName();\n             }\n           }*/ return getProperties ( className , methodName , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up an array property value relative to the environment base class and modifier . The default environment will be checked for a matching array property if defaults are being used . [CODESPLIT] public String [ ] getProperties ( Object base , String modifier , String key ) { return getProperties ( base . getClass ( ) . getName ( ) , modifier , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks up an array property value relative to the environment base class and modifier . The default environment will be checked for a matching array property if defaults are being used . [CODESPLIT] public String [ ] getProperties ( String base , String modifier , String key ) { String [ ] result = null ; // Loop over the key orderings, from the most specific to the most general, until a matching value is found. for ( Iterator i = getKeyIterator ( base , modifier , key ) ; i . hasNext ( ) ; ) { String nextKey = ( String ) i . next ( ) ; Collection arrayList = ( ArrayList ) arrayProperties . get ( nextKey ) ; if ( arrayList != null ) { result = ( String [ ] ) arrayList . toArray ( new String [ ] { } ) ; break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a given environment base modifier and key and setting of the use of default environments feature this generates an iterator that walks over the order in which to try and access properties . [CODESPLIT] protected Iterator getKeyIterator ( final String base , final String modifier , final String key ) { return new Iterator ( ) { // The key ordering count always begins at the start of the ORDER array. private int i ; public boolean hasNext ( ) { return ( useDefaults ? ( ( i < ORDER . length ) && ( ORDER [ i ] > ENVIRONMENT_DEFAULTS_CUTOFF ) ) : ( i < ORDER . length ) ) ; } public Object next ( ) { // Check that there is a next element and return null if not. if ( ! hasNext ( ) ) { return null ; } // Get the next ordering count. int o = ORDER [ i ] ; // Do bit matching on the count to choose which elements to include in the key. String result = ( ( ( o & E ) != 0 ) ? ( environment + \".\" ) : \"\" ) + ( ( ( o & B ) != 0 ) ? ( base + \".\" ) : \"\" ) + ( ( ( o & M ) != 0 ) ? ( modifier + \".\" ) : \"\" ) + key ; // Increment the iterator to get the next key on the next call. i ++ ; return result ; } public void remove ( ) { // This method is not supported. throw new UnsupportedOperationException ( \"remove() is not supported on this key order iterator as \" + \"the ordering cannot be changed\" ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scans all the properties in the parent Properties object and creates arrays for any array property definitions . [CODESPLIT] protected void createArrayProperties ( ) { // Scan through all defined properties. for ( Object o : keySet ( ) ) { String key = ( String ) o ; String value = super . getProperty ( key ) ; // Split the property key into everything before the last '.' and after it. int lastDotIndex = key . lastIndexOf ( ' ' ) ; String keyEnding = key . substring ( lastDotIndex + 1 , key . length ( ) ) ; String keyStart = key . substring ( 0 , ( lastDotIndex == - 1 ) ? 0 : lastDotIndex ) ; // Check if the property key ends in an integer, in which case it is an array property. int index = 0 ; try { index = Integer . parseInt ( keyEnding ) ; } catch ( NumberFormatException e ) { // The ending is not an integer so its not an array. // Exception can be ignored as it means this property is not an array. e = null ; continue ; } // Check if an array property already exists for this base name and create one if not. ArrayList propArray = ( ArrayList ) arrayProperties . get ( keyStart ) ; if ( propArray == null ) { propArray = new ArrayList ( ) ; arrayProperties . put ( keyStart , propArray ) ; } // Add the new property value to the array property for the index. propArray . set ( index , value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Term build ( ) { Term result ; if ( ! isCompound ( ) ) { result = getFunctor ( ) ; } else { if ( getFunctor ( ) . isAtom ( ) ) { List < Term > args = getArgs ( ) ; int arity = args . size ( ) ; Functor functor = ( Functor ) getFunctor ( ) ; int name = interner . internFunctorName ( interner . getFunctorName ( functor . getName ( ) ) , arity ) ; result = new Functor ( name , args . toArray ( new Term [ arity ] ) ) ; } else { throw new IllegalStateException ( \"Invalid functor type.\" ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Specifies the throttling rate in operations per second . This must be called with with a value the inverse of which is a measurement in nano seconds such that the number of nano seconds do not overflow a long integer . The value must also be larger than zero . [CODESPLIT] public void setRate ( float hertz ) { // Check that the argument is above zero. if ( hertz <= 0.0f ) { throw new IllegalArgumentException ( \"The throttle rate must be above zero.\" ) ; } // Calculate the cycle time. cycleTimeNanos = ( long ) ( 1000000000f / hertz ) ; // Reset the first pass flag. firstCall = false ; firstCheckCall = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method can only be called at the rate set by the { @link #setRate } method if it is called faster than this it will inject short pauses to restrict the call rate to that rate . [CODESPLIT] public void throttle ( ) throws InterruptedException { // Don't introduce any pause on the first call. if ( ! firstCall ) { // Check if there is any time left in the cycle since the last throttle call to this method and introduce a // short pause to fill that time if there is. long remainingTimeNanos = timeToThrottleNanos ( ) ; while ( remainingTimeNanos > 0 ) { long milliPause = remainingTimeNanos / 1000000 ; int nanoPause = ( int ) ( remainingTimeNanos % 1000000 ) ; Thread . sleep ( milliPause , nanoPause ) ; remainingTimeNanos = timeToThrottleNanos ( ) ; } } else { firstCall = false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks but does not enforce the throttle rate . When this method is called it checks if a length of time greater than that equal to the inverse of the throttling rate has passed since it was last called and returned <tt > true< / tt > . If the length of time still to elapse to the next throttle allow point is zero or less this method will return a negative value if there is still time to pass until the throttle allow point this method will return a positive value indicating the amount of time still to pass . A thread can wait for that period of time before rechecking the throttle condition . [CODESPLIT] public long timeToThrottleNanos ( ) { long now = System . nanoTime ( ) ; long remainingNanos = ( cycleTimeNanos + lastCheckTimeNanos ) - now ; if ( ( remainingNanos <= 0 ) ) { firstCheckCall = false ; lastCheckTimeNanos = now ; return remainingNanos ; } else if ( firstCheckCall ) { firstCheckCall = false ; lastCheckTimeNanos = now ; return 0 ; } else { return remainingNanos ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setProperty ( String name , Object value ) { // Set the type of the new property in the state type mapping. componentType . addPropertyType ( name , TypeHelper . getTypeFromObject ( value ) ) ; // Add the new property to the property map. properties . put ( name , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the arithmetic operator on its numeric argument . [CODESPLIT] protected NumericType evaluate ( NumericType firstNumber ) { // If the argument is a real number, then use real number arithmetic, otherwise use integer arithmetic. if ( firstNumber . isInteger ( ) ) { return new IntLiteral ( - firstNumber . intValue ( ) ) ; } else { return new DoubleLiteral ( - firstNumber . doubleValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This methods attempts to load the properties from a file or URL referenced by the system property with the same name as the properties resource name from a resource on the classpath with the same name as the properties resource name or from a properties file name relative to the current working directory . It tries these methods sequentially one after the other until one succeeds . [CODESPLIT] protected void findProperties ( ) { /*log.fine(\"findProperties: called\");*/ // Try to load the properties from a file referenced by the system property matching // the properties file name. properties = getPropertiesUsingSystemProperty ( ) ; if ( properties != null ) { /*log.fine(\"loaded properties using the system property\");*/ // The properties were succesfully located and loaded return ; } /*log.fine(\"failed to get properties from the system properties\");*/ // Try to load the properties from a resource on the classpath using the current // class loader properties = getPropertiesUsingClasspath ( ) ; if ( properties != null ) { /*log.fine(\"loaded properties from the class path\");*/ // The properties were succesfully located and loaded return ; } /*log.fine(\"failed to get properties from the classpath\");*/ // Try to load the properties from a file relative to the current working directory properties = getPropertiesUsingCWD ( ) ; if ( properties != null ) { /*log.fine(\"loaded properties from the current working directory\");*/ // The properties were succesfully located and loaded return ; } /*log.fine(\"failed to get properties from the current working directory\");*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to load the properties from the file or URL named by the system property with name mathching the properties resource name . [CODESPLIT] protected Properties getPropertiesUsingSystemProperty ( ) { /*log.fine(\"getPropertiesUsingSystemProperty: called\");*/ // Get the path to the file from the system properties /*log.fine(\"getPropertiesResourceName() = \" + getPropertiesResourceName());*/ String path = System . getProperty ( getPropertiesResourceName ( ) ) ; /*log.fine(\"properties resource name = \" + getPropertiesResourceName());*/ /*log.fine(\"path = \" + path);*/ // Use PropertiesHelper to try to load the properties from the path try { return PropertiesHelper . getProperties ( path ) ; } catch ( IOException e ) { /*log.fine(\"Could not load properties from path \" + path);*/ // Failure of this method is noted, so exception is ignored. e = null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to load the properties from the classpath using the classloader for this class . [CODESPLIT] protected Properties getPropertiesUsingClasspath ( ) { /*log.fine(\"getPropertiesUsingClasspath: called\");*/ // Try to open the properties resource name as an input stream from the classpath InputStream is = this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( getPropertiesResourceName ( ) ) ; // Use PropertiesHelper to try to load the properties from the input stream if one was succesfully created if ( is != null ) { try { return PropertiesHelper . getProperties ( is ) ; } catch ( IOException e ) { /*log.fine(\"Could not load properties from classpath\");*/ // Failure of this method is noted, so exception is ignored. e = null ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries to load the properties as a file or URL matching the properties resource name . File names will be taken relative to the current working directory . [CODESPLIT] protected Properties getPropertiesUsingCWD ( ) { /*log.fine(\"getPropertiesUsingCWD: called\");*/ // Use PropertiesHelper to try to load the properties from a file or URl try { return PropertiesHelper . getProperties ( getPropertiesResourceName ( ) ) ; } catch ( IOException e ) { /*log.fine(\"Could not load properties from file or URL \" + getPropertiesResourceName());*/ // Failure of this method is noted, so exception is ignored. e = null ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies the built - in transform during a post - fix visit of a term . [CODESPLIT] protected void leaveFunctor ( Functor functor ) { int pos = traverser . getPosition ( ) ; if ( ! traverser . isInHead ( ) && ( pos >= 0 ) ) { Functor transformed = builtInTransform . apply ( functor ) ; if ( functor != transformed ) { /*log.fine(\"Transformed: \" + functor + \" to \" + transformed.getClass());*/ BuiltInFunctor builtInFunctor = ( BuiltInFunctor ) transformed ; Term parentTerm = traverser . getParentContext ( ) . getTerm ( ) ; if ( parentTerm instanceof Clause ) { Clause parentClause = ( Clause ) parentTerm ; parentClause . getBody ( ) [ pos ] = builtInFunctor ; } else if ( parentTerm instanceof Functor ) { Functor parentFunctor = ( Functor ) parentTerm ; parentFunctor . getArguments ( ) [ pos ] = builtInFunctor ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the actual value of a term which is either the term itself or in the case of variables the value that is currently assigned to the variable . When the variable is free the variable term itself is returned . [CODESPLIT] public Term getValue ( ) { Term result = this ; Term assignment = this . substitution ; // If the variable is assigned, loops down the chain of assignments until no more can be found. Whatever term // is found at the end of the chain of assignments is the value of this variable. while ( assignment != null ) { result = assignment ; if ( ! assignment . isVar ( ) ) { break ; } else { assignment = ( ( Variable ) assignment ) . substitution ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds this variable to the specified value . [CODESPLIT] public void setSubstitution ( Term term ) { Term termToBindTo = term ; // When binding against a variable, always bind to its storage cell and not the variable itself. if ( termToBindTo instanceof Variable ) { Variable variableToBindTo = ( Variable ) term ; termToBindTo = variableToBindTo . getStorageCell ( variableToBindTo ) ; } substitution = termToBindTo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof VariableVisitor ) { ( ( VariableVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Variable acceptTransformer ( TermTransformer transformer ) { if ( transformer instanceof VariableTransformer ) { return ( ( VariableTransformer ) transformer ) . transform ( this ) ; } else { return ( Variable ) super . acceptTransformer ( transformer ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this term for structural equality with another . Two terms are structurally equal if they are the same functor with the same arguments or are the same unbound variable or the bound values of the left or right variable operands are structurally equal . Structural equality is a stronger equality than unification and unlike unification it does not produce any variable bindings . Two unified terms will always be structurally equal . [CODESPLIT] public boolean structuralEquals ( Term term ) { Term comparator = term . getValue ( ) ; Term value = getValue ( ) ; // Check if this is an unbound variable in which case the comparator must be the same variable. if ( value == this ) { return this . equals ( comparator ) ; } else { return value . structuralEquals ( comparator ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public CharSequence subSequence ( int start , int end ) { return new ASCIIByteBufferString ( data , offset + start , end - start ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public int compareTo ( ASCIIString comparator ) { int n = Math . min ( length , comparator . length ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { byte b1 = get ( i ) ; byte b2 = comparator . get ( i ) ; if ( b1 == b2 ) { continue ; } if ( b1 < b2 ) { return - 1 ; } return 1 ; } return length - comparator . length ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes and caches in the { [CODESPLIT] private void computeStringValue ( ) { char [ ] chars = new char [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { chars [ i ] = ( char ) data . get ( i + offset ) ; } stringValue = new String ( chars ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes and caches in the { [CODESPLIT] private void computeHashCode ( ) { hashCode = 0 ; for ( int i = 0 ; i < length ; i ++ ) { hashCode = ( 31 * hashCode ) + data . get ( i + offset ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the correct type of queue for this search . This search uses a priority queue ordered by heuristic value . [CODESPLIT] public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new GreedyComparator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Drop the connection to the remote host and release the underlying connector thread if it has been created . [CODESPLIT] public void cleanUp ( ) { if ( oos != null ) { try { oos . close ( ) ; } catch ( IOException e ) { LogLog . error ( \"Could not close oos.\" , e ) ; } oos = null ; } if ( connector != null ) { // LogLog.debug(\"Interrupting the connector.\"); connector . interrupted = true ; connector = null ; // allow gc } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends a logging event to the remote event reciever . [CODESPLIT] public void append ( LoggingEvent event ) { if ( event == null ) { return ; } if ( address == null ) { errorHandler . error ( \"No remote host is set for SocketAppender named \\\"\" + this . name + \"\\\".\" ) ; return ; } if ( oos != null ) { try { if ( locationInfo ) { event . getLocationInformation ( ) ; } oos . writeObject ( event ) ; // LogLog.debug(\"=========Flushing.\"); oos . flush ( ) ; if ( ++ counter >= RESET_FREQUENCY ) { counter = 0 ; // Failing to reset the object output stream every now and // then creates a serious memory leak. // System.err.println(\"Doing oos.reset()\"); oos . reset ( ) ; } } catch ( IOException e ) { oos = null ; LogLog . warn ( \"Detected problem with connection: \" + e ) ; if ( reconnectionDelay > 0 ) { fireConnector ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Connects to remote server at <code > address< / code > and <code > port< / code > . [CODESPLIT] void connect ( InetAddress address , int port ) { if ( this . address == null ) { return ; } try { // First, close the previous connection if any. cleanUp ( ) ; Socket socket = new Socket ( ) ; SocketAddress socketAddr = new InetSocketAddress ( address , port ) ; socket . connect ( socketAddr , 10 ) ; oos = new ObjectOutputStream ( socket . getOutputStream ( ) ) ; } catch ( IOException e ) { // Silently fail and do not retry later. // Exception noted so can be ignored. e = null ; /*\n             * String msg = \"Could not connect to remote log4j server at [\" +address.getHostName()+\"].\";\n             * if(reconnectionDelay > 0) { msg += \" We will try again later.\"; fireConnector(); // fire the connector\n             * thread } LogLog.error(msg, e); */ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts a new connector thread to do? [CODESPLIT] void fireConnector ( ) { if ( connector == null ) { LogLog . debug ( \"Starting a new connector thread.\" ) ; connector = new Connector ( ) ; connector . setDaemon ( true ) ; connector . setPriority ( Thread . MIN_PRIORITY ) ; connector . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Predicate predicate ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( predicate ) ; } super . visit ( predicate ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Clause clause ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( clause ) ; } super . visit ( clause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Functor functor ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( functor ) ; } super . visit ( functor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void visit ( Variable variable ) { for ( AllTermsVisitor printer : printers ) { printer . visit ( variable ) ; } super . visit ( variable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up the stack of column printers . [CODESPLIT] protected void initializePrinters ( ) { int maxColumns = 0 ; printers . add ( new SourceClausePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new PositionPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new UnoptimizedLabelPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new UnoptimizedByteCodePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new LabelPrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; printers . add ( new ByteCodePrinter ( interner , symbolTable , traverser , maxColumns ++ , printTable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Assembles the accumulated output in all rows and columns into a table . The table is appended onto { [CODESPLIT] protected void printTable ( ) { for ( int i = 0 ; i < printTable . getRowCount ( ) ; i ++ ) { for ( int j = 0 ; j < printTable . getColumnCount ( ) ; j ++ ) { String valueToPrint = printTable . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? \"\" : valueToPrint ; result . append ( valueToPrint ) ; Integer maxColumnSize = printTable . getMaxColumnSize ( j ) ; int padding = ( ( maxColumnSize == null ) ? 0 : maxColumnSize ) - valueToPrint . length ( ) ; padding = ( padding < 0 ) ? 0 : padding ; for ( int s = 0 ; s < padding ; s ++ ) { result . append ( \" \" ) ; } result . append ( \" % \" ) ; } result . append ( \"\\n\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getItemsWhenItemReturnsItem ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<div itemscope='itemscope' itemtype='http://x' itemid='http://y'/>\" + \"</body></html>\" ) ) ; List < MicrodataItem > actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItems ( \"http://x\" ) ; assertThat ( \"items\" , actual , contains ( item ( \"http://y\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getLinkWhenAnchorReturnsLink ( ) throws MalformedURLException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<a rel='x' href='http://y/'/>\" + \"</body></html>\" ) ) ; Link actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( \"x\" ) ; assertThat ( \"link\" , actual , is ( link ( \"x\" , \"http://y/\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getFormReturnsForm ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='x'/>\" + \"</body></html>\" ) ) ; Form actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"x\" ) ; assertThat ( \"form\" , actual . getName ( ) , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body/></html>\" ) ) ; MicrodataDocument document = newBrowser ( ) . get ( url ( server ( ) ) ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( \"Cannot unwrap to: class java.lang.Void\" ) ; document . unwrap ( Void . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getControlReturnsControl ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='text' name='x'/>\" + \"</form>\" + \"</body></html>\" ) ) ; Control actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . getControl ( \"x\" ) ; assertThat ( \"form control\" , actual . getName ( ) , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getControlValueReturnsInitialValue ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='text' name='x' value='y'/>\" + \"</form>\" + \"</body></html>\" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . getControlValue ( \"x\" ) ; assertThat ( \"form control value\" , actual , is ( \"y\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void setControlValueSetsValue ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='text' name='x' value='y'/>\" + \"</form>\" + \"</body></html>\" ) ) ; Form form = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) ; form . setControlValue ( \"x\" , \"y\" ) ; assertThat ( \"form control value\" , form . getControlValue ( \"x\" ) , is ( \"y\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getControlGroupReturnsControlGroup ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='text' name='x'/>\" + \"<input type='text' name='x'/>\" + \"</form>\" + \"</body></html>\" ) ) ; ControlGroup actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . getControlGroup ( \"x\" ) ; assertThat ( \"form control group\" , actual . getName ( ) , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void submitWhenSubmitInputSubmitsRequest ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f' action='/x'>\" + \"<input type='submit'/>\" + \"</form>\" + \"</body></html>\" ) ) ; server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . submit ( ) ; server ( ) . takeRequest ( ) ; assertThat ( \"request\" , takeRequest ( server ( ) ) . getPath ( ) , is ( \"/x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void unwrapWithUnknownTypeThrowsException ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='x'/>\" + \"</body></html>\" ) ) ; Form form = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"x\" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( \"Cannot unwrap to: class java.lang.Void\" ) ; form . unwrap ( Void . class ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterFunctor ( Functor functor ) { String showContextAs = interner . getFunctorName ( functor ) + ( functor . isAtom ( ) ? \"\" : \"(\" ) ; int delta = showContextAs . length ( ) ; addLineToRow ( indent + showContextAs ) ; nextRow ( ) ; indent = indenter . generateTraceIndent ( delta ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void leaveFunctor ( Functor functor ) { String toAppend = indent ; boolean addData = false ; if ( functor . isCompound ( ) ) { toAppend += \")\" ; addData = true ; } if ( ! traverser . isInHead ( ) && ! traverser . isLastBodyFunctor ( ) && traverser . isTopLevel ( ) ) { toAppend += \",\" ; addData = true ; } if ( traverser . isInHead ( ) && traverser . isTopLevel ( ) ) { toAppend += \" :-\" ; addData = true ; } if ( addData ) { addLineToRow ( toAppend ) ; nextRow ( ) ; } indent = indenter . generateTraceIndent ( - indenter . getLastDelta ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterVariable ( Variable variable ) { String showContextAs = interner . getVariableName ( variable ) ; int delta = showContextAs . length ( ) ; addLineToRow ( indent + showContextAs ) ; nextRow ( ) ; indent = indenter . generateTraceIndent ( delta ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private static String getCheckedValue ( Control control ) { if ( control instanceof CheckableControl ) { return ( ( CheckableControl ) control ) . getCheckedValue ( ) ; } return control . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { SizeableLinkedList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; if ( isLastBody ) { if ( ! chainRule ) { result . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; } result . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Proceed ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When operating in transactional mode causes any changes since the last commit to be made visible to the search method . [CODESPLIT] public void commit ( ) { TxId txId = null ; // Check if in a higher transactional mode than none, otherwise commit does nothing. if ( ! getIsolationLevel ( ) . equals ( IsolationLevel . None ) ) { // Extract the current transaction id. txId = TxManager . getTxIdFromThread ( ) ; // Wait until the global write lock can be acquired by this transaction. try { acquireGlobalWriteLock ( txId ) ; } catch ( InterruptedException e ) { // The commit was interrupted, so cannot succeed. throw new IllegalStateException ( \"Interrupted whilst commit is waiting for global write lock.\" , e ) ; } // Check that this transaction has made changes to be committed. List < TxOperation > alterations = txWrites . get ( txId ) ; try { if ( alterations != null ) { // Loop through all the writes that the transaction wants to apply to the resource. for ( TxOperation nextAlteration : alterations ) { // Apply the change and update the term resource. nextAlteration . execute ( ) ; } // Clear the write behind cache for this transaction as its work has been completed. txWrites . remove ( txId ) ; } } finally { // Release the global write lock. releaseGlobalWriteLock ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When operation in transactional mode causes any changes since the last commit to be dropped and never made visible to the search method . [CODESPLIT] public void rollback ( ) { TxId txId = null ; // Check if in a higher transactional mode than none, otherwise commit does nothing. if ( ! getIsolationLevel ( ) . equals ( IsolationLevel . None ) ) { // Extract the current transaction id. txId = TxManager . getTxIdFromThread ( ) ; // Check that this transaction has made changes to be rolled back. List < TxOperation > alterations = txWrites . get ( txId ) ; if ( alterations != null ) { // Loop through all the writes that the transaction wants to apply to the resource. for ( TxOperation nextAlteration : alterations ) { // Cancel the operation. nextAlteration . cancel ( false ) ; } } // Discard all the changes that the transaction was going to make. txWrites . remove ( txId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests an operation that alters the transactional resource . This may be blocked until an appropriate lock can be acquired delayed until commit time or actioned upon a copy of the data structure private to a transaction branch . [CODESPLIT] public void requestWriteOperation ( TxOperation op ) { // Check if in a higher transactional mode than none and capture the transaction id if so. TxId txId = null ; if ( getIsolationLevel ( ) . compareTo ( IsolationLevel . None ) > 0 ) { // Extract the current transaction id. txId = TxManager . getTxIdFromThread ( ) ; // Ensure that this resource is enlisted with the current session. enlistWithSession ( ) ; } // For non-transactional isolation levels, apply the requested operation immediately. if ( getIsolationLevel ( ) . equals ( IsolationLevel . None ) ) { op . execute ( ) ; } // Add the operation to the transaction write-behind cache for the transaction id, if using transactional // isolation, to defer the operation untill commit time. else { addCachedOperation ( txId , op ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a transactional operation to the transactional write - behind cache for the specified transaction . If no cache exists for the specified transaction id a new one is created . [CODESPLIT] private void addCachedOperation ( TxId txId , TxOperation cachedWriteOperation ) { List < TxOperation > writeCache = txWrites . get ( txId ) ; if ( writeCache == null ) { writeCache = new ArrayList < TxOperation > ( ) ; txWrites . put ( txId , writeCache ) ; } writeCache . add ( cachedWriteOperation ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Waits until the global write lock can be acquired by the specified transaction . [CODESPLIT] private void acquireGlobalWriteLock ( TxId txId ) throws InterruptedException { // Get the global write lock to ensure only one thread at a time can execute this code. globalLock . writeLock ( ) . lock ( ) ; // Use a try block so that the corresponding finally block guarantees release of the thread lock. try { // Check that this transaction does not already own the lock. if ( ! txId . equals ( globalWriteLockTxId ) ) { // Wait until the write lock becomes free. while ( globalWriteLockTxId != null ) { globalWriteLockFree . await ( ) ; } // Assign the global write lock to this transaction. globalWriteLockTxId = txId ; } } finally { // Ensure that the thread lock is released once assignment of the write lock to the transaction is complete. globalLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Releases the global write lock from being assigned to a transaction . [CODESPLIT] private void releaseGlobalWriteLock ( ) { // Get the global write lock to ensure only one thread at a time can execute this code. globalLock . writeLock ( ) . lock ( ) ; // Use a try block so that the corresponding finally block guarantees release of the thread lock. try { // Release the global write lock, assigning it to no transaction. globalWriteLockTxId = null ; // Signal that the write lock is now free. globalWriteLockFree . signal ( ) ; } // Ensure that the thread lock is released once assignment of the write lock to the transaction is complete. finally { globalLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enlists this transactional resource with the current session . If no session exists this will fail . [CODESPLIT] private void enlistWithSession ( ) { TxSession session = TxSessionImpl . getCurrentSession ( ) ; // Ensure that this resource is being used within a session. if ( session == null ) { throw new IllegalStateException ( \"Cannot access transactional resource outside of a session.\" ) ; } // Ensure that this resource is enlisted with the session. session . enlist ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates nested MediaQueryNode inside RuleSetNode separates RuleSetNode and MediaQueryNode [CODESPLIT] @ Override public boolean enter ( RuleSetNode ruleSetNode ) { ScopeNode scopeNode = NodeTreeUtils . getFirstChild ( ruleSetNode , ScopeNode . class ) ; SelectorGroupNode selectorGroupNode = NodeTreeUtils . getFirstChild ( ruleSetNode , SelectorGroupNode . class ) ; if ( selectorGroupNode == null ) { return true ; } List < SelectorNode > selectorNodes = NodeTreeUtils . getChildren ( selectorGroupNode , SelectorNode . class ) ; if ( selectorNodes . size ( ) < 0 ) { return true ; } List < MediaQueryNode > mediaQueryNodes = NodeTreeUtils . getAndRemoveChildren ( scopeNode , MediaQueryNode . class ) ; for ( MediaQueryNode mediaQueryNode : mediaQueryNodes ) { ScopeNode mediaScopeNode = NodeTreeUtils . getFirstChild ( mediaQueryNode , ScopeNode . class ) ; List < RuleSetNode > nestedRuleSets = NodeTreeUtils . getAndRemoveChildren ( mediaScopeNode , RuleSetNode . class ) ; // if scope node for media query has anything more but whitespaces and rule sets than wrap it with rule set with the same selector group as outer rule set has if ( mediaScopeNode . getChildren ( ) . size ( ) > NodeTreeUtils . getChildren ( mediaScopeNode , WhiteSpaceCollectionNode . class ) . size ( ) ) { RuleSetNode newRuleSetNode = new RuleSetNode ( ) ; ScopeNode newScopeNode = new ScopeNode ( ) ; newRuleSetNode . addChild ( selectorGroupNode . clone ( ) ) ; newRuleSetNode . addChild ( newScopeNode ) ; NodeTreeUtils . moveChildren ( mediaScopeNode , newScopeNode ) ; mediaScopeNode . clearChildren ( ) ; mediaScopeNode . addChild ( newRuleSetNode ) ; } // adding outer selectors to every nested selectors for ( RuleSetNode nestedRuleSet : nestedRuleSets ) { List < SelectorGroupNode > nestedSelectorGroupNodes = NodeTreeUtils . getChildren ( nestedRuleSet , SelectorGroupNode . class ) ; for ( SelectorGroupNode nestedSelectorGroupNode : nestedSelectorGroupNodes ) { List < SelectorNode > nestedSelectorNodes = NodeTreeUtils . getAndRemoveChildren ( nestedSelectorGroupNode , SelectorNode . class ) ; NodeTreeUtils . getAndRemoveChildren ( nestedSelectorGroupNode , SpacingNode . class ) ; for ( SelectorNode selectorNode : selectorNodes ) { for ( SelectorNode nestedSelectorNode : nestedSelectorNodes ) { if ( nestedSelectorNode . getChildren ( ) . get ( 0 ) != null ) { if ( nestedSelectorNode . getChildren ( ) . get ( 0 ) instanceof SelectorSegmentNode ) { SelectorSegmentNode selectorSegmentNode = ( SelectorSegmentNode ) nestedSelectorNode . getChildren ( ) . get ( 0 ) ; selectorSegmentNode . setCombinator ( \" \" ) ; } } for ( int j = selectorNode . getChildren ( ) . size ( ) - 1 ; j >= 0 ; j -- ) { if ( selectorNode . getChildren ( ) . get ( j ) instanceof SelectorSegmentNode ) { SelectorSegmentNode selectorSegmentNode = ( SelectorSegmentNode ) selectorNode . getChildren ( ) . get ( j ) . clone ( ) ; nestedSelectorNode . addChild ( 0 , selectorSegmentNode ) ; } } nestedSelectorGroupNode . addChild ( nestedSelectorNode ) ; nestedSelectorGroupNode . addChild ( new SpacingNode ( \" \" ) ) ; } } } mediaScopeNode . addChild ( nestedRuleSet ) ; } if ( ruleSetNode . getParent ( ) != null ) { ruleSetNode . getParent ( ) . addChild ( new SpacingNode ( \"\\n\" ) ) ; ruleSetNode . getParent ( ) . addChild ( mediaQueryNode ) ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the specified element into this queue if possible . When using queues that may impose insertion restrictions ( for example capacity bounds ) method <tt > offer< / tt > is generally preferable to method { @link java . util . Collection#add } which can fail to insert an element only by throwing an exception . [CODESPLIT] public boolean offer ( E e ) { if ( e == null ) { throw new IllegalArgumentException ( \"The 'e' parameter may not be null.\" ) ; } ReentrantLock lock = this . lock ; lock . lock ( ) ; try { return insert ( e , false ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the specified element into this queue waiting if necessary up to the specified wait time for space to become available . [CODESPLIT] public boolean offer ( E e , long timeout , TimeUnit unit ) throws InterruptedException { if ( e == null ) { throw new IllegalArgumentException ( \"The 'e' parameter may not be null.\" ) ; } ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; long nanos = unit . toNanos ( timeout ) ; try { do { if ( insert ( e , false ) ) { return true ; } try { nanos = notFull . awaitNanos ( nanos ) ; } catch ( InterruptedException ie ) { // Wake up another thread waiting on notFull, as the condition may be true, but this thread // was interrupted so cannot make use of it. notFull . signal ( ) ; throw ie ; } } while ( nanos > 0 ) ; return false ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves and removes the head of this queue or <tt > null< / tt > if this queue is empty . [CODESPLIT] public E poll ( ) { ReentrantLock lock = this . lock ; lock . lock ( ) ; try { if ( count == 0 ) { return null ; } return extract ( true , true ) . getElement ( ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves and removes the head of this queue waiting if necessary up to the specified wait time if no elements are present on this queue . [CODESPLIT] public E poll ( long timeout , TimeUnit unit ) throws InterruptedException { ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { long nanos = unit . toNanos ( timeout ) ; do { if ( count != 0 ) { return extract ( true , true ) . getElement ( ) ; } try { nanos = notEmpty . awaitNanos ( nanos ) ; } catch ( InterruptedException ie ) { notEmpty . signal ( ) ; // propagate to non-interrupted thread throw ie ; } } while ( nanos > 0 ) ; return null ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves but does not remove the head of this queue returning <tt > null< / tt > if this queue is empty . [CODESPLIT] public E peek ( ) { ReentrantLock lock = this . lock ; lock . lock ( ) ; try { return peekAtBufferHead ( ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the specified element to this queue waiting if necessary for space to become available . [CODESPLIT] public void put ( E e ) throws InterruptedException { try { tryPut ( e ) ; } catch ( SynchException ex ) { // This exception is deliberately ignored. See the method comment for information about this. ex = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tries a synchronous put into the queue . If a consumer encounters an exception condition whilst processing the data that is put then this is returned to the caller wrapped inside a { @link SynchException } . [CODESPLIT] public void tryPut ( E e ) throws InterruptedException , SynchException { if ( e == null ) { throw new IllegalArgumentException ( \"The 'e' parameter may not be null.\" ) ; } // final Queue<E> items = this.buffer; ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { while ( getBufferRemainingCapacity ( ) == 0 ) { // Release the lock and wait until the queue is not full. notFull . await ( ) ; } } catch ( InterruptedException ie ) { notFull . signal ( ) ; // propagate to non-interrupted thread throw ie ; } // There is room in the queue so insert must succeed. Insert into the queu, release the lock and block // the producer until its data is taken. insert ( e , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves and removes the head of this queue waiting if no elements are present on this queue . Any producer that has its data element taken by this call will be immediately unblocked . To keep the producer blocked whilst taking just a single item use the { @link #drainTo ( java . util . Collection< SynchRecord <E >> int boolean ) } method . There is no take method to do that because there is not usually any advantage in a synchronous hand off design that consumes data one item at a time . It is normal to consume data in chunks to ammortize consumption latencies accross many producers where possible . [CODESPLIT] public E take ( ) throws InterruptedException { ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { try { while ( count == 0 ) { // Release the lock and wait until the queue becomes non-empty. notEmpty . await ( ) ; } } catch ( InterruptedException ie ) { notEmpty . signal ( ) ; // propagate to non-interrupted thread throw ie ; } // There is data in the queue so extraction must succeed. Notify any waiting threads that the queue is // not full, and unblock the producer that owns the data item that is taken. return extract ( true , true ) . getElement ( ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes at most the given number of available elements from this queue and adds them into the given collection . A failure encountered while attempting to <tt > add< / tt > elements to collection <tt > c< / tt > may result in elements being in neither either or both collections when the associated exception is thrown . Attempts to drain a queue to itself result in <tt > IllegalArgumentException< / tt > . Further the behavior of this operation is undefined if the specified collection is modified while the operation is in progress . [CODESPLIT] public int drainTo ( Collection < ? super E > collection , int maxElements ) { if ( collection == null ) { throw new IllegalArgumentException ( \"The 'collection' parameter may not be null.\" ) ; } if ( collection == this ) { throw new IllegalArgumentException ( \"The 'collection' parameter may not be this object.\" ) ; } // final Queue<E> items = this.buffer; ReentrantLock lock = this . lock ; lock . lock ( ) ; try { int n = 0 ; for ( int max = ( ( maxElements >= count ) || ( maxElements < 0 ) ) ? count : maxElements ; n < max ; n ++ ) { // Take items from the queue, do unblock the producers, but don't send not full signals yet. collection . add ( extract ( true , false ) . getElement ( ) ) ; } if ( n > 0 ) { // count -= n; notFull . signalAll ( ) ; } return n ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes all available data items from the queue or blocks until some become available . The returned items are wrapped in a { @link SynchRecord } which provides an interface to requeue them or send errors to their producers where the producers are still blocked . [CODESPLIT] public SynchRef drainTo ( Collection < SynchRecord < E > > c , boolean unblock ) { return drainTo ( c , - 1 , unblock ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes up to maxElements available data items from the queue or blocks until some become available . The returned items are wrapped in a { @link SynchRecord } which provides an interface to requeue them or send errors to their producers where the producers are still blocked . [CODESPLIT] public SynchRef drainTo ( Collection < SynchRecord < E > > collection , int maxElements , boolean unblock ) { if ( collection == null ) { throw new IllegalArgumentException ( \"The 'collection' parameter may not be null.\" ) ; } if ( collection == this ) { throw new IllegalArgumentException ( \"The 'collection' parameter may not be this object.\" ) ; } // final Queue<E> items = this.buffer; ReentrantLock lock = this . lock ; lock . lock ( ) ; try { int n = 0 ; for ( int max = ( ( maxElements >= count ) || ( maxElements < 0 ) ) ? count : maxElements ; n < max ; n ++ ) { // Extract the next record from the queue, don't signal the not full condition yet and release // producers depending on whether the caller wants to or not. collection . add ( extract ( false , unblock ) ) ; } if ( n > 0 ) { // count -= n; notFull . signalAll ( ) ; } return new SynchRefImpl ( n , collection ) ; } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Insert element into the queue then possibly signal that the queue is not empty and block the producer on the element until permission to procede is given . [CODESPLIT] protected boolean insert ( E element , boolean unlockAndBlock ) { // Create a new record for the data item. SynchRecordImpl < E > record = new SynchRecordImpl < E > ( element ) ; boolean result = buffer . offer ( record ) ; if ( result ) { count ++ ; // Tell any waiting consumers that the queue is not empty. notEmpty . signal ( ) ; if ( unlockAndBlock ) { // Allow other threads to read/write the queue. lock . unlock ( ) ; // Wait until a consumer takes this data item. record . waitForConsumer ( ) ; } return true ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes an element from the buffer and optionally unblocks the producer of the element if it is waiting and optionally signals that the { @link #notFull } condition may now be true . [CODESPLIT] protected SynchRecordImpl < E > extract ( boolean unblock , boolean signal ) { SynchRecordImpl < E > result = buffer . remove ( ) ; count -- ; if ( signal ) { notFull . signal ( ) ; } if ( unblock ) { result . releaseImmediately ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fetches the next element from this iterator . [CODESPLIT] public Object next ( ) { try { Object ob = source . next ( ) ; return ob ; } catch ( RemoteException e ) { throw new IllegalStateException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static boolean setSysPropertyIfNull ( String propname , boolean value ) { return Boolean . parseBoolean ( setSysPropertyIfNull ( propname , Boolean . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static short setSysPropertyIfNull ( String propname , short value ) { return Short . parseShort ( setSysPropertyIfNull ( propname , Short . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static int setSysPropertyIfNull ( String propname , int value ) { return Integer . parseInt ( setSysPropertyIfNull ( propname , Integer . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static long setSysPropertyIfNull ( String propname , long value ) { return Long . parseLong ( setSysPropertyIfNull ( propname , Long . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static float setSysPropertyIfNull ( String propname , float value ) { return Float . parseFloat ( setSysPropertyIfNull ( propname , Float . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static double setSysPropertyIfNull ( String propname , double value ) { return Double . parseDouble ( setSysPropertyIfNull ( propname , Double . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting system properties to defaults when they are not already set . [CODESPLIT] public static String setSysPropertyIfNull ( String propname , String value ) { String property = System . getProperty ( propname ) ; if ( property == null ) { System . setProperty ( propname , value ) ; return value ; } else { return property ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public boolean setPropertyIfNull ( String propname , boolean value ) { return Boolean . parseBoolean ( setPropertyIfNull ( propname , Boolean . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public short setPropertyIfNull ( String propname , short value ) { return Short . parseShort ( setPropertyIfNull ( propname , Short . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public int setPropertyIfNull ( String propname , int value ) { return Integer . parseInt ( setPropertyIfNull ( propname , Integer . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public long setPropertyIfNull ( String propname , long value ) { return Long . parseLong ( setPropertyIfNull ( propname , Long . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public float setPropertyIfNull ( String propname , float value ) { return Float . parseFloat ( setPropertyIfNull ( propname , Float . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public double setPropertyIfNull ( String propname , double value ) { return Double . parseDouble ( setPropertyIfNull ( propname , Double . toString ( value ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties to defaults when they are not already set . [CODESPLIT] public String setPropertyIfNull ( String propname , String value ) { String property = super . getProperty ( propname ) ; if ( property == null ) { super . setProperty ( propname , value ) ; return value ; } else { return property ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties . [CODESPLIT] public boolean setProperty ( String propname , boolean value ) { setProperty ( propname , Boolean . toString ( value ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties . [CODESPLIT] public short setProperty ( String propname , short value ) { setProperty ( propname , Short . toString ( value ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties . [CODESPLIT] public int setProperty ( String propname , int value ) { setProperty ( propname , Integer . toString ( value ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties . [CODESPLIT] public long setProperty ( String propname , long value ) { setProperty ( propname , Long . toString ( value ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties . [CODESPLIT] public float setProperty ( String propname , float value ) { setProperty ( propname , Float . toString ( value ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method for setting properties . [CODESPLIT] public double setProperty ( String propname , double value ) { setProperty ( propname , Double . toString ( value ) ) ; return value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a property as a boolean . [CODESPLIT] public boolean getPropertyAsBoolean ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) && Boolean . parseBoolean ( prop ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a property as an integer . [CODESPLIT] public Integer getPropertyAsInteger ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) ? Integer . valueOf ( prop ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a property as a long . [CODESPLIT] public Long getPropertyAsLong ( String propName ) { String prop = getProperty ( propName ) ; return ( prop != null ) ? Long . valueOf ( prop ) : null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a clone of this scope to be attached to the tree at the site of a mixin reference . If an ArgumentsNode is passed each of its values override those defined by the mixin s parameters . [CODESPLIT] public ScopeNode callMixin ( String name , ArgumentsNode arguments ) { List < ExpressionGroupNode > argumentList = ( arguments != null ) ? NodeTreeUtils . getChildren ( arguments , ExpressionGroupNode . class ) : Collections . < ExpressionGroupNode > emptyList ( ) ; if ( argumentList . size ( ) > _parameterDefinitions . size ( ) ) { throw new IllegalMixinArgumentException ( name , _parameterDefinitions . size ( ) ) ; } // Clone scope and filter out any white space ScopeNode mixinScope = clone ( ) ; NodeTreeUtils . filterLineBreaks ( mixinScope ) ; // If arguments were passed, apply them for ( int i = 0 ; i < argumentList . size ( ) ; i ++ ) { ExpressionGroupNode argument = argumentList . get ( i ) ; // Replace the value of the definition VariableDefinitionNode parameter = mixinScope . _parameterDefinitions . get ( i ) ; parameter . clearChildren ( ) ; parameter . addChild ( argument ) ; } // Mark this scope's containing rule set as invisible since it has been used as a mixin getParent ( ) . setVisible ( false ) ; return mixinScope ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Some nodes are captured in additional structures to aid later resolution . [CODESPLIT] private void setAdditionVisitor ( ) { setAdditionVisitor ( new InclusiveNodeVisitor ( ) { /**\n             * Add parameter set as a child for printing input, but also add each defined value to the variable map.\n             */ @ Override public boolean add ( ParametersNode node ) { for ( VariableDefinitionNode variable : NodeTreeUtils . getChildren ( node , VariableDefinitionNode . class ) ) { _parameterDefinitions . add ( variable ) ; add ( variable ) ; } return super . add ( node ) ; } /**\n             * Store the rule set's scope by selector group\n             */ @ Override public boolean add ( RuleSetNode node ) { SelectorGroupNode selectorGroup = NodeTreeUtils . getFirstChild ( node , SelectorGroupNode . class ) ; for ( SelectorNode selectorNode : NodeTreeUtils . getChildren ( selectorGroup , SelectorNode . class ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( Node selectorChild : selectorNode . getChildren ( ) ) { sb . append ( selectorChild . toString ( ) ) ; } String selector = sb . toString ( ) ; // Mixins lock on first definition if ( ! _selectorToRuleSetMap . containsKey ( selector ) ) { _selectorToRuleSetMap . put ( selector , node ) ; } } return super . add ( node ) ; } /**\n             * Absorb all children of the given scope. This assumes that cloning is not necessary.\n             */ @ Override public boolean add ( ScopeNode node ) { NodeTreeUtils . moveChildren ( node , ScopeNode . this ) ; return false ; // Don't add the original scope itself } /**\n             * Store variable definitions in a map by name\n             */ @ Override public boolean add ( VariableDefinitionNode node ) { String name = node . getName ( ) ; // \"Variables\" lock on first definition if ( ! _variableNameToValueMap . containsKey ( name ) ) { _variableNameToValueMap . put ( name , NodeTreeUtils . getFirstChild ( node , ExpressionGroupNode . class ) ) ; } return super . add ( node ) ; } /**\n             * Store property nodes by name. If there are multiple properties for a given name, only retain the last one.\n             */ @ Override public boolean add ( PropertyNode node ) { String name = node . getName ( ) ; // If this is the IE-specific \"filter\" property, always add it if ( name . equals ( FILTER_PROPERTY ) ) { return super . add ( node ) ; } // If the value of this property node is a vendor-specific keyword, always add it if ( node . getChildren ( ) . get ( 0 ) . toString ( ) . startsWith ( \"-\" ) ) { return super . add ( node ) ; } // Check if this property has been seen before if ( _propertyNameToNodeMap . containsKey ( name ) ) { PropertyNode oldPropertyNode = _propertyNameToNodeMap . get ( name ) ; int oldPropertyIndex = getChildren ( ) . indexOf ( oldPropertyNode ) ; if ( oldPropertyNode . isVisible ( ) ) { // Hide the unneeded property oldPropertyNode . setVisible ( false ) ; // Attempt to hide one surrounding white space node if ( ! hideWhiteSpaceNode ( oldPropertyIndex - 1 ) ) { hideWhiteSpaceNode ( oldPropertyIndex + 1 ) ; } } } // Store the property as the latest for this name _propertyNameToNodeMap . put ( name , node ) ; return super . add ( node ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Recreate internal state before children are cloned . [CODESPLIT] @ Override protected void cloneChildren ( InternalNode node ) { ScopeNode scope = ( ScopeNode ) node ; // Reset internal state scope . _variableNameToValueMap = new HashMap < String , ExpressionGroupNode > ( ) ; scope . _selectorToRuleSetMap = new HashMap < String , RuleSetNode > ( ) ; scope . _parameterDefinitions = new ArrayList < VariableDefinitionNode > ( ) ; scope . _propertyNameToNodeMap = new HashMap < String , PropertyNode > ( ) ; scope . setAdditionVisitor ( ) ; super . cloneChildren ( node ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private Connection getConnection ( ) { URL href = getHref ( ) ; checkArgument ( href != null , \"Invalid URL: \" + element . attr ( \"href\" ) ) ; return Jsoup . connect ( href . toString ( ) ) . method ( Method . GET ) . cookies ( document . getCookies ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SearchNode < O , T > search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { // Initialize the queue with the start states set up in search nodes if this has not already been done. // This will only be done on the first call to this method, as enqueueStartStates sets a flag when it is // done. Subsequent searches continue from where the previous search left off. Have to call reset on // the search method to really start the search again from the start states. Queue < SearchNode < O , T > > queue = initSearch . enqueueStartStates ( startStates ) ; // Get the goal predicate configured as part of the enqueueing start states process. UnaryPredicate goalPredicate = initSearch . getGoalPredicate ( ) ; // Backtrack the most recent goal state, if one has been established. if ( mostRecentGoalNode != null ) { backtrack ( mostRecentGoalNode ) ; // Clear the most recent goal, now that it has been backtracked if required. mostRecentGoalNode = null ; } // Keep running until the queue becomes empty or a goal state is found. while ( ! queue . isEmpty ( ) ) { // Extract or peek at the head element from the queue. SearchNode headNode = queue . remove ( ) ; // Apply the current nodes operator to establish its shared state. Reversable reversableState = ( ReTraversable ) headNode . getState ( ) ; reversableState . applyOperator ( ) ; // Expand the successors into the queue whether the current node is a goal state or not. // This prepares the queue for subsequent searches, ensuring that goal states do not block // subsequent goal states that exist beyond them. headNode . unexaminedSuccessorCount = headNode . expandSuccessors ( queue , reverseEnqueue ) ; // As the head node is about to be goal tested, reduce the unexamined successor count of its predecessor. if ( headNode . getParent ( ) != null ) { headNode . getParent ( ) . unexaminedSuccessorCount -- ; } // Check if the current node is a goal state. if ( goalPredicate . evaluate ( headNode . getState ( ) ) ) { // Remember this goal node so that subsequent searches remember to backtrack over it. mostRecentGoalNode = headNode ; return headNode ; } // Backtrack over all fully exhausted nodes from the current position, as required. backtrack ( headNode ) ; // Check if there is a maximum number of steps limit and increase the step count and check the limit if so. if ( maxSteps > 0 ) { searchSteps ++ ; // Update the search state with the number of steps taken so far. initSearch . setStepsTaken ( searchSteps ) ; if ( searchSteps >= maxSteps ) { // The maximum number of steps has been reached, however if the queue is now empty then the search // has just completed within the maximum. Check if the queue is empty and return null if so. if ( queue . isEmpty ( ) ) { return null ; } // Quit without a solution as the max number of steps has been reached but because there are still // more states in the queue then raise a search failure exception. else { throw new SearchNotExhaustiveException ( \"Maximum number of steps reached.\" , null ) ; } } } } // No goal state was found so return null return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Back - tracks from the specified node moving succesively upwards through the chain of parent nodes until a node is encountered that has unexamined successors . This method implements the backtracking searches reverse direction . By checking for the presence of unexamined successors this method only backtracks where necessary . [CODESPLIT] protected void backtrack ( SearchNode checkNode ) { while ( ( checkNode != null ) && ( checkNode . unexaminedSuccessorCount == 0 ) ) { Reversable undoState = ( ReTraversable ) checkNode . getState ( ) ; undoState . undoOperator ( ) ; checkNode = checkNode . getParent ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void emmitCode ( WAMCompiledPredicate predicate ) throws LinkageException { // Keep track of the offset into which the code was loaded. int entryPoint = codeBuffer . position ( ) ; int length = ( int ) predicate . sizeof ( ) ; // If the code is for a program clause, store the programs entry point in the call table. WAMCallPoint callPoint = setCodeAddress ( predicate . getName ( ) , entryPoint , length ) ; // Emmit code for the clause into this machine. predicate . emmitCode ( codeBuffer , this , callPoint ) ; // Notify the native machine of the addition of new code. codeAdded ( codeBuffer , entryPoint , length ) ; // Notify any attached DPI monitor of the addition of new code. if ( monitor != null ) { monitor . onCodeUpdate ( this , entryPoint , length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void emmitCode ( WAMCompiledQuery query ) throws LinkageException { // Keep track of the offset into which the code was loaded. int entryPoint = codeBuffer . position ( ) ; int length = ( int ) query . sizeof ( ) ; // If the code is for a program clause, store the programs entry point in the call table. WAMCallPoint callPoint = new WAMCallPoint ( entryPoint , length , - 1 ) ; // Emmit code for the clause into this machine. query . emmitCode ( codeBuffer , this , callPoint ) ; // Notify the native machine of the addition of new code. codeAdded ( codeBuffer , entryPoint , length ) ; // Notify any attached DPI monitor of the addition of new code. if ( monitor != null ) { monitor . onCodeUpdate ( this , entryPoint , length ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Extracts the raw byte code from the machine for a given call table entry . [CODESPLIT] public byte [ ] retrieveCode ( WAMCallPoint callPoint ) { byte [ ] result = new byte [ callPoint . length ] ; codeBuffer . get ( result , callPoint . entryPoint , callPoint . length ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public ByteBuffer getCodeBuffer ( int start , int length ) { // Take a read only slice onto an appropriate section of the code buffer. ByteBuffer readOnlyBuffer = codeBuffer . asReadOnlyBuffer ( ) ; readOnlyBuffer . position ( start ) ; readOnlyBuffer . limit ( start + length ) ; return readOnlyBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a query and for every non - anonymous variable in the query decodes its binding value from the heap and returns it in a set of variable bindings . [CODESPLIT] protected Set < Variable > executeAndExtractBindings ( WAMCompiledQuery query ) { // Execute the query and program. The starting point for the execution is the first functor in the query // body, this will follow on to the subsequent functors and make calls to functors in the compiled programs. boolean success = execute ( query . getCallPoint ( ) ) ; // Used to collect the results in. Set < Variable > results = null ; // Collect the results only if the resolution was successfull. if ( success ) { results = new HashSet < Variable > ( ) ; // The same variable context is used accross all of the results, for common use of variables in the // results. Map < Integer , Variable > varContext = new HashMap < Integer , Variable > ( ) ; // For each of the free variables in the query, extract its value from the location on the heap pointed to // by the register that holds the variable. /*log.fine(\"query.getVarNames().size() =  \" + query.getVarNames().size());*/ for ( byte reg : query . getVarNames ( ) . keySet ( ) ) { int varName = query . getVarNames ( ) . get ( reg ) ; if ( query . getNonAnonymousFreeVariables ( ) . contains ( varName ) ) { int addr = derefStack ( reg ) ; Term term = decodeHeap ( addr , varContext ) ; results . add ( new Variable ( varName , term , false ) ) ; } } } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes a term from the raw byte representation on the machines heap into an abstract syntax tree . [CODESPLIT] protected Term decodeHeap ( int start , Map < Integer , Variable > variableContext ) { /*log.fine(\"private Term decodeHeap(int start = \" + start + \", Map<Integer, Variable> variableContext = \" +\n            variableContext + \"): called\");*/ // Used to hold the decoded argument in. Term result = null ; // Dereference the initial heap pointer. int addr = deref ( start ) ; byte tag = getDerefTag ( ) ; int val = getDerefVal ( ) ; /*log.fine(\"addr = \" + addr);*/ /*log.fine(\"tag = \" + tag);*/ /*log.fine(\"val = \" + val);*/ switch ( tag ) { case REF : { // Check if a variable for the address has already been created in this context, and use it if so. Variable var = variableContext . get ( val ) ; if ( var == null ) { var = new Variable ( varNameId . decrementAndGet ( ) , null , false ) ; variableContext . put ( val , var ) ; } result = var ; break ; } case STR : { // Decode f/n from the STR data. int fn = getHeap ( val ) ; int f = fn & 0x00ffffff ; /*log.fine(\"fn = \" + fn);*/ /*log.fine(\"f = \" + f);*/ // Look up and initialize this functor name from the symbol table. FunctorName functorName = getDeinternedFunctorName ( f ) ; // Fill in this functors name and arity and allocate storage space for its arguments. int arity = functorName . getArity ( ) ; Term [ ] arguments = new Term [ arity ] ; // Loop over all of the functors arguments, recursively decoding them. for ( int i = 0 ; i < arity ; i ++ ) { arguments [ i ] = decodeHeap ( val + 1 + i , variableContext ) ; } // Create a new functor to hold the decoded data. result = new Functor ( f , arguments ) ; break ; } case WAMInstruction . CON : { //Decode f/n from the CON data. int f = val & 0x3fffffff ; /*log.fine(\"f = \" + f);*/ // Create a new functor to hold the decoded data. result = new Functor ( f , null ) ; break ; } case WAMInstruction . LIS : { FunctorName functorName = new FunctorName ( \"cons\" , 2 ) ; int f = internFunctorName ( functorName ) ; // Fill in this functors name and arity and allocate storage space for its arguments. int arity = functorName . getArity ( ) ; Term [ ] arguments = new Term [ arity ] ; // Loop over all of the functors arguments, recursively decoding them. for ( int i = 0 ; i < arity ; i ++ ) { arguments [ i ] = decodeHeap ( val + i , variableContext ) ; } // Create a new functor to hold the decoded data. result = new Functor ( f , arguments ) ; break ; } default : throw new IllegalStateException ( \"Encountered unknown tag type on the heap.\" ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Captures an objects state in this memento . [CODESPLIT] public void capture ( ) { // Get the class of the object to build a memento for. Class cls = ob . getClass ( ) ; // Iterate through the classes whole inheritence chain. while ( ! cls . equals ( Object . class ) ) { // Get the classes fields. Field [ ] attrs = cls . getDeclaredFields ( ) ; // Build a new map to put the fields in for the current class. HashMap map = new HashMap ( ) ; // Cache the field values by the class name. values . put ( cls , map ) ; // Loop over all the fields in the current class. for ( Field attr : attrs ) { // Make the field accessible (it may be protected or private). attr . setAccessible ( true ) ; // Check that the field should be captured. if ( shouldBeSaved ( attr ) ) { // Use a try block as access to the field may fail, although this should not happen because // even private, protected and package fields have been made accessible. try { // Cache the field by its name. map . put ( attr . getName ( ) , attr . get ( ob ) ) ; } catch ( IllegalAccessException e ) { // The field could not be accessed but all fields have been made accessible so this should // not happen. throw new IllegalStateException ( \"Field '\" + attr . getName ( ) + \"' could not be accessed but the 'setAccessible(true)' method was invoked on it.\" , e ) ; } } } // Get the superclass for the next step of the iteration over the whole inheritence chain. cls = cls . getSuperclass ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restores the values currently in this memento to the specified object . [CODESPLIT] public void restore ( Object ob ) throws NoSuchFieldException { /*log.fine(\"public void map(Object ob): called\");*/ /*log.fine(\"class is \" + ob.getClass());*/ // Iterate over the whole inheritence chain. for ( Object key : values . keySet ( ) ) { // Get the next class from the cache. Class cls = ( Class ) key ; // Get the cache of field values for the class. Map vals = ( HashMap ) values . get ( cls ) ; // Loop over all fields in the class. for ( Object o : vals . keySet ( ) ) { // Get the next field name. String attr = ( String ) o ; // Get the next field value. Object val = vals . get ( attr ) ; // Get a reference to the field in the object. Field f = cls . getDeclaredField ( attr ) ; // Make the field accessible (it may be protected, package or private). f . setAccessible ( true ) ; // Use a try block as writing to the field may fail. try { // Write to the field. f . set ( ob , val ) ; } catch ( IllegalAccessException e ) { // The field could not be written to but all fields have been made accessible so this should // not happen. throw new IllegalStateException ( \"Field '\" + f . getName ( ) + \"' could not be accessed but the 'setAccessible(true)' method was invoked on it.\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the named field of the specified class . [CODESPLIT] public Object get ( Class cls , String attr ) { HashMap map ; // See if the class exists in the cache. if ( ! values . containsKey ( cls ) ) { // Class not in cache so return null. return null ; } // Get the cache of field values for the class. map = ( HashMap ) values . get ( cls ) ; // Extract the specified field from the cache. return map . get ( attr ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Places the specified value into the memento based on the field s declaring class and name . [CODESPLIT] public void put ( Class cls , String attr , Object val ) { /*log.fine(\"public void put(Class cls, String attr, Object val): called\");*/ /*log.fine(\"class name is \" + cls.getName());*/ /*log.fine(\"attribute is \" + attr);*/ /*log.fine(\"value to set is \" + val);*/ HashMap map ; // Check that the cache for the class exists in the cache. if ( values . containsKey ( cls ) ) { // Get the cache of field for the class. map = ( HashMap ) values . get ( cls ) ; } else { // The class does not already exist in the cache to create a new cache for its fields. map = new HashMap ( ) ; // Cache the new field cache against the class. values . put ( cls , map ) ; } // Store the attribute in the field cache for the class. map . put ( attr , val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a list of all the fields of the object that this memento maps for a given class . [CODESPLIT] public Collection getAllFieldNames ( Class cls ) { /*log.fine(\"public Collection getAllFieldNames(Class cls): called\");*/ // See if the class exists in the cache if ( ! values . containsKey ( cls ) ) { // Class not in cache so return null return null ; } // Get the cache of fields for the class Map map = ( HashMap ) values . get ( cls ) ; // Return all the keys from cache of fields return map . keySet ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the interpreter and launches its top - level run loop . [CODESPLIT] public static void main ( String [ ] args ) { try { VariableAndFunctorInterner interner = new VariableAndFunctorInternerImpl ( \"Prolog_Variable_Namespace\" , \"Prolog_Functor_Namespace\" ) ; PrologCompiler compiler = new PrologCompiler ( interner ) ; PrologResolver resolver = new PrologResolver ( interner ) ; Parser < Clause , Token > parser = new InteractiveParser ( interner ) ; PrologEngine engine = new PrologEngine ( parser , interner , compiler , resolver ) ; engine . reset ( ) ; ResolutionInterpreter < PrologCompiledClause , PrologCompiledClause > interpreter = new ResolutionInterpreter < PrologCompiledClause , PrologCompiledClause > ( engine ) ; interpreter . interpreterLoop ( ) ; } catch ( Exception e ) { /*log.log(Level.SEVERE, e.getMessage(), e);*/ e . printStackTrace ( new PrintStream ( System . err ) ) ; System . exit ( - 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the prod - script goal . [CODESPLIT] public void execute ( ) throws MojoExecutionException , MojoFailureException { //log.debug(\"public void execute() throws MojoExecutionException: called\"); // Turn each of the test runner command lines into a script. for ( String commandName : commands . keySet ( ) ) { if ( prodScriptOutDirectory != null ) { writeUnixScript ( commandName , prodScriptOutDirectory ) ; writeWindowsScript ( commandName , prodScriptOutDirectory ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected String appendClasspath ( String commandLine , boolean unix ) { String pathSeperator ; String seperator ; String classpathDirPrefix ; if ( unix ) { pathSeperator = \"/\" ; seperator = \":\" ; classpathDirPrefix = JAR_DIR_PREFIX_UNIX ; } else { pathSeperator = \"\\\\\" ; seperator = \";\" ; classpathDirPrefix = JAR_DIR_PREFIX_WINDOWS ; } for ( Iterator i = classpathElements . iterator ( ) ; i . hasNext ( ) ; ) { String cpPath = ( String ) i . next ( ) ; int lastSlash = cpPath . lastIndexOf ( \"/\" ) ; int lastBackslash = cpPath . lastIndexOf ( \"\\\\\" ) ; int lastPathSeperator = ( lastSlash > lastBackslash ) ? lastSlash : lastBackslash ; if ( lastPathSeperator != - 1 ) { cpPath = cpPath . substring ( lastPathSeperator + 1 ) ; } //cpPath = cpPath.replace(\"/\", pathSeperator); if ( cpPath . endsWith ( \".jar\" ) ) { commandLine += classpathDirPrefix + pathSeperator + cpPath + seperator ; } } commandLine += classpathDirPrefix + pathSeperator + outputJar + \".jar\" ; return commandLine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setup ( ByteBuffer buffer , int t , int n ) { this . buffer = buffer ; this . offset = t ; this . size = ( n >> 3 ) ; // Shift by 3 as key and value must be stored as a pair, making 8 bytes per entry. }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int get ( int key ) { int addr = addr ( hash ( key ) ) ; while ( true ) { int tableKey = buffer . getInt ( addr ) ; if ( key == tableKey ) { return buffer . getInt ( addr + 4 ) ; } if ( tableKey == 0 ) { return 0 ; } addr += 8 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void put ( int key , int val ) { int addr = addr ( hash ( key ) ) ; while ( true ) { int tableKey = buffer . getInt ( addr ) ; if ( key == tableKey ) { break ; } if ( tableKey == 0 ) { break ; } addr += 8 ; } buffer . putInt ( addr , key ) ; buffer . putInt ( addr + 4 , val ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the specified element onto the tail of this queue . [CODESPLIT] public boolean offer ( E o ) { /*log.fine(\"public boolean offer(E o): called\");*/ /*log.fine(\"o = \" + o);*/ // Ensure that the item to add is not null. if ( o == null ) { throw new IllegalArgumentException ( \"The 'o' parameter may not be null.\" ) ; } // Derive the integer priority of the element using the priority function, shift it into this queues range if // necessary and adjust it to any offset caused by lowest priority not equal to zero. int level = priorityToLevel ( p . apply ( o ) ) ; /*log.fine(\"offer level = \" + level);*/ // Create a new node to hold the new data element. Node < E > newNode = new DataNode < E > ( o , markers [ level + 1 ] ) ; // Add the element to the tail of the queue with matching level, looping until this can complete as an atomic // operation. while ( true ) { // Get tail and next ref. Would expect next ref to be null, but other thread may update it. Node < E > t = markers [ level + 1 ] . getTail ( ) ; Node < E > s = t . getNext ( ) ; /*log.fine(\"t = \" + t);*/ /*log.fine(\"s = \" + s);*/ // Recheck the tail ref, to ensure other thread has not already moved it. This can potentially prevent // a relatively expensive compare and set from failing later on, if another thread has already shited // the tail. if ( t == markers [ level + 1 ] . getTail ( ) ) { /*log.fine(\"t is still the tail.\");*/ // Check that the next element reference on the tail is the tail marker, to confirm that another thread // has not updated it. Again, this may prevent a cas from failing later. if ( s == markers [ level + 1 ] ) { /*log.fine(\"s is  the tail marker.\");*/ // Try to join the new tail onto the old one. if ( t . casNext ( s , newNode ) ) { // The tail join was succesfull, so now update the queues tail reference. No conflict should // occurr here as the tail join was succesfull, so its just a question of updating the tail // reference. A compare and set is still used because ... markers [ level + 1 ] . casTail ( t , newNode ) ; // Increment the queue size count. count . incrementAndGet ( ) ; return true ; } } // Update the tail reference, other thread may also be doing the same. else { // Why bother doing this at all? I suppose, because another thread may be stalled and doing this // will enable this one to keep running. // Update the tail reference for the queue because another thread has already added a new tail // but not yet managed to update the tail reference. markers [ level + 1 ] . casTail ( t , s ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves and removes the head of this queue or null if this queue is empty . [CODESPLIT] public E poll ( ) { /*log.fine(\"public E poll(): called\");*/ // This is used to keep track of the level of the list that is found to have data in it. int currentLevel = 0 ; while ( true ) { // This is used to locate the marker head of a list that contains data. Marker < E > h = null ; // This is used to locate the potential data node of a list with data in it. Another thread may already // have taken this data. Node < E > first = null ; // Second data item, may also be tail marker, first data item of next list, or null at end of last list. Node < E > second = null ; // Loop down any empty lists at the front of the queue until a list with data in it is found. for ( ; currentLevel < n ; currentLevel ++ ) { h = markers [ currentLevel ] ; first = h . getNext ( ) ; second = first . getNext ( ) ; // Check if the list at the current level is not empty and should be tried for data. if ( ! h . isEmpty ( markers [ currentLevel + 1 ] ) ) { break ; } // Check if the current level is empty and is the last level, in which case return null. else if ( currentLevel == ( n - 1 ) ) { // log.info(\"returning null from level loop.\"); return null ; } // Else if the current level is empty loop to the next one to see if it has data. } /*log.fine(\"current poll level = \" + currentLevel);*/ // This is used to locate the tail of the list that has been found with data in it. Node < E > t = markers [ currentLevel + 1 ] . getTail ( ) ; // Check that the first data item has not yet been taken. Another thread may already have taken it, // in which case performing a relatively expensive cas on the head will fail. If first is still intact // then second will be intact too. if ( first == h . getNext ( ) ) { // Check if the queue has become empty. if ( h . isEmpty ( markers [ currentLevel + 1 ] ) ) { // Another thread has managed to take data from the queue, leaving it empty. // First won't be null. It may point to tail though... if ( first == null ) { // Don't want to return here, want to try the next list. The list loop has a return null // once it gets to the end to take care of that. // log.info(\"returning null as first == null\"); return null ; } else { // Not sure yet why castail here? Does this repair a broken tail ref left after the last item // was taken? markers [ currentLevel + 1 ] . casTail ( t , first ) ; } } // The queue contains data, so try to move its head marker reference from the first data item, onto the // second item (which may be data, or the tail marker). If this succeeds, then the first data node // has been atomically extracted from the head of the queue. else if ( h . casNext ( first , second ) ) { // h Does not refer to an empty queue, so first must be a data node. DataNode < E > firstDataNode = ( ( DataNode < E > ) first ) ; E item = firstDataNode . getItem ( ) ; // Even though the empty test did not indicate that the list was empty, it may contain null // data items, because the remove method doesn't extract nodes on a remove. These need to be skipped // over. Could they be removed here? if ( item != null ) { firstDataNode . setItem ( null ) ; /*log.fine(\"returing item = \" + item);*/ // Decrement the queue size count. count . decrementAndGet ( ) ; return item ; } // else skip over deleted item, continue trying at this level. Go back an retry starting from same // level. List at this level may now be empty, or may get the next item from it. // else skip over marker element. just make markers return null for item to skip them? No, because // need to advance currentLevel and get head and tail markers for the next level. but then, next // level advance will occur when this level is retried and found to be empty won't it? } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the correct type of search nodes for this search . This search uses ordinary search nodes . [CODESPLIT] public SearchNode < O , T > createSearchNode ( T state ) { return new SearchNode < O , T > ( state ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the correct type of queue for this search . This search uses a priority queue ordered by path cost . [CODESPLIT] public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new UniformCostComparator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void open ( ) { // Build a text grid panel in the left position. grid = componentFactory . createTextGrid ( ) ; grid . insertVerticalSeparator ( 3 , 10 ) ; mainWindow . showLeftPane ( componentFactory . createTextGridPanel ( grid ) ) ; // Build a table model on the text grid, and construct a register monitor on the table. table = grid . createTable ( 0 , 0 , 20 , 20 ) ; monitor = new RegisterSetMonitor ( table ) ; // Attach a listener for updates to the register table. table . addTextTableListener ( new TableUpdateHandler ( ) ) ; grid . addTextGridSelectionListener ( new SelectionHandler ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a simple depth first walk over a term . [CODESPLIT] public static TermWalker simpleWalker ( TermVisitor visitor ) { DepthFirstBacktrackingSearch < Term , Term > search = new DepthFirstBacktrackingSearch < Term , Term > ( ) ; return new TermWalker ( search , new DefaultTraverser ( ) , visitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a depth first walk over a term visiting only when a goal predicate matches . [CODESPLIT] public static TermWalker goalWalker ( UnaryPredicate < Term > unaryPredicate , TermVisitor visitor ) { TermWalker walker = simpleWalker ( visitor ) ; walker . setGoalPredicate ( unaryPredicate ) ; return walker ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a positional depth first walk over a term . [CODESPLIT] public static TermWalker positionalWalker ( PositionalTermVisitor visitor ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( visitor ) ; visitor . setPositionalTraverser ( positionalTraverser ) ; return new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , visitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a positional depth first walk over a term visiting only when a goal predicate matches . [CODESPLIT] public static TermWalker positionalGoalWalker ( UnaryPredicate < Term > unaryPredicate , PositionalTermVisitor visitor ) { TermWalker walker = positionalWalker ( visitor ) ; walker . setGoalPredicate ( unaryPredicate ) ; return walker ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides a positional postfix walk over a term . [CODESPLIT] public static TermWalker positionalPostfixWalker ( PositionalTermVisitor visitor ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( visitor ) ; visitor . setPositionalTraverser ( positionalTraverser ) ; return new TermWalker ( new PostFixSearch < Term , Term > ( ) , positionalTraverser , visitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void addToDomain ( PrologCompiledClause term ) { List < PrologCompiledClause > predicate = domain . get ( term . getHead ( ) . getName ( ) ) ; if ( predicate == null ) { predicate = new LinkedList < PrologCompiledClause > ( ) ; domain . put ( term . getHead ( ) . getName ( ) , predicate ) ; } predicate . add ( term ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setQuery ( PrologCompiledClause query ) { // Reset the search in order to initialize it. resolutionSearch . reset ( ) ; // Keep a reference to the current query. currentQuery = query ; // Create the starting point for the resolution, consisting of the queries to resolve as the intial goal stack, // and an empty list of bindings. goalStack = new StackQueue < BuiltInFunctor > ( ) ; // Create a fresh list to hold the results of the resolution in. bindings = new StackQueue < Variable > ( ) ; // Create the initial state of the proof search. ResolutionState initialState = new ResolutionStateImpl ( query ) ; addStartState ( initialState ) ; // If printing execution traces, ensure the execution indenter starts from zero. /*if (TRACE)\n        {\n            indenter.reset();\n        }*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Set < Variable > resolve ( ) { // Find all free variables in the query. Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( currentQuery ) ; // Used to collect the results in. Set < Variable > results = null ; // Search for the next available solution. SearchNode solution ; try { solution = findGoalPath ( ) ; } catch ( SearchNotExhaustiveException e ) { // The search may fail if the maximum number of search steps is reached. This limit is not turned on by // default. If this happens, null is returned, indicating that no solution was found. // Exception ignored as empty search results are noted and dealt with by returning null. e = null ; solution = null ; results = null ; } // Check that a solution was found and return the variable bindings from it if so. Only the variable bindings // that were free and non-anonymous in the original query are returned. if ( solution != null ) { results = new HashSet < Variable > ( freeVars ) ; } return results ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void reset ( ) { // Empty the knowledge base and clear the current query. domain = new HashMap < Integer , List < PrologCompiledClause > > ( ) ; currentQuery = null ; // Reset the underlying search. resolutionSearch . reset ( ) ; // If printing execution traces, ensure the execution indenter starts from zero. /*if (TRACE)\n        {\n            indenter.reset();\n        }*/ }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public ResolutionState search ( ) throws SearchNotExhaustiveException { SearchNode < ResolutionState , ResolutionState > path = findGoalPath ( ) ; if ( path != null ) { return path . getState ( ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < Set < Variable > > iterator ( ) { // Find all free variables in the query. final Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( currentQuery ) ; Function < ResolutionState , Set < Variable > > listFunction = new Function < ResolutionState , Set < Variable > > ( ) { public Set < Variable > apply ( ResolutionState state ) { return freeVars ; } } ; return new Filterator < ResolutionState , Set < Variable > > ( Searches . allSolutions ( this ) , listFunction ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get properties from an input stream . [CODESPLIT] public static Properties getProperties ( InputStream is ) throws IOException { /*log.fine(\"getProperties(InputStream): called\");*/ // Create properties object laoded from input stream Properties properties = new Properties ( ) ; properties . load ( is ) ; return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get properties from a file . [CODESPLIT] public static Properties getProperties ( File file ) throws IOException { /*log.fine(\"getProperties(File): called\");*/ // Open the file as an input stream InputStream is = new FileInputStream ( file ) ; // Create properties object loaded from the stream Properties properties = getProperties ( is ) ; // Close the file is . close ( ) ; return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get properties from a url . [CODESPLIT] public static Properties getProperties ( URL url ) throws IOException { /*log.fine(\"getProperties(URL): called\");*/ // Open the URL as an input stream InputStream is = url . openStream ( ) ; // Create properties object loaded from the stream Properties properties = getProperties ( is ) ; // Close the url is . close ( ) ; return properties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get properties from a path name . The path name may refer to either a file or a URL . [CODESPLIT] public static Properties getProperties ( String pathname ) throws IOException { /*log.fine(\"getProperties(String): called\");*/ // Check that the path is not null if ( pathname == null ) { return null ; } // Check if the path is a URL if ( isURL ( pathname ) ) { // The path is a URL return getProperties ( new URL ( pathname ) ) ; } else { // Assume the path is a file name return getProperties ( new File ( pathname ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Trims whitespace from property values . This method returns a new set of properties the same as the properties specified as an argument but with any white space removed by the { @link java . lang . String#trim } method . [CODESPLIT] public static Properties trim ( Properties properties ) { Properties trimmedProperties = new Properties ( ) ; // Loop over all the properties for ( Object o : properties . keySet ( ) ) { String next = ( String ) o ; String nextValue = properties . getProperty ( next ) ; // Trim the value if it is not null if ( nextValue != null ) { nextValue . trim ( ) ; } // Store the trimmed value in the trimmed properties trimmedProperties . setProperty ( next , nextValue ) ; } return trimmedProperties ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method . Guesses whether a string is a URL or not . A String is considered to be a url if it begins with http : ftp : or uucp : . [CODESPLIT] private static boolean isURL ( String name ) { return ( name . toLowerCase ( ) . startsWith ( \"http:\" ) || name . toLowerCase ( ) . startsWith ( \"ftp:\" ) || name . toLowerCase ( ) . startsWith ( \"uucp:\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] protected void paintComponent ( Graphics g ) { Graphics2D graphics2D = ( Graphics2D ) g . create ( ) ; Rectangle clipRect = ( Rectangle ) g . getClip ( ) ; // Work out the area to be painted in grid coordinates against the clipping rectangle. int startCol = xToCol ( clipRect . x ) ; int startRow = yToRow ( clipRect . y ) ; int cols = xToCol ( clipRect . x + clipRect . width ) ; int rows = yToRow ( clipRect . y + clipRect . height ) ; graphics2D . setFont ( getFont ( ) ) ; graphics2D . setColor ( getBackground ( ) ) ; graphics2D . fillRect ( clipRect . x , clipRect . y , clipRect . width , clipRect . height ) ; initializeFontMetrics ( ) ; if ( useAntiAliasing ) { graphics2D . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; graphics2D . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_QUALITY ) ; } SortedMap < Integer , Integer > hSeps = model . getHorizontalSeparators ( ) ; int hSepOffset = 0 ; for ( int row = 0 ; row <= rows ; row ++ ) { Integer hNextSep = null ; if ( ! hSeps . isEmpty ( ) ) { hNextSep = hSeps . firstKey ( ) ; } if ( ( hNextSep != null ) && ( hNextSep == row ) ) { hSepOffset += hSeps . get ( hNextSep ) ; hSeps . remove ( hNextSep ) ; } SortedMap < Integer , Integer > vSeps = model . getVerticalSeparators ( ) ; int vSepOffset = 0 ; for ( int col = 0 ; col <= cols ; col ++ ) { Integer vNextSep = null ; if ( ! vSeps . isEmpty ( ) ) { vNextSep = vSeps . firstKey ( ) ; } if ( ( vNextSep != null ) && ( vNextSep == col ) ) { int vSepWidth = vSeps . get ( vNextSep ) ; vSepOffset += vSepWidth ; vSeps . remove ( vNextSep ) ; // If adding a vertical separator row attributes should be rendered within it to fill the space // left by the separator. AttributeSet attributes = model . getRowAttribute ( row ) ; Color bgColor = ( attributes != null ) ? ( Color ) attributes . get ( AttributeSet . BACKGROUND_COLOR ) : null ; bgColor = ( bgColor == null ) ? getBackground ( ) : bgColor ; graphics2D . setColor ( bgColor ) ; graphics2D . fillRect ( colToX ( col ) + vSepOffset - vSepWidth , rowToY ( row ) + hSepOffset , colToX ( col ) + vSepOffset , charHeight ) ; } // Only render if within the clip rectangle if ( ( col >= startCol ) && ( row >= startRow ) ) { char character = model . getCharAt ( col , row ) ; AttributeSet attributes = model . getAttributeAt ( col , row ) ; Color bgColor = ( attributes != null ) ? ( Color ) attributes . get ( AttributeSet . BACKGROUND_COLOR ) : null ; bgColor = ( bgColor == null ) ? getBackground ( ) : bgColor ; graphics2D . setColor ( bgColor ) ; graphics2D . fillRect ( colToX ( col ) + vSepOffset , rowToY ( row ) + hSepOffset , charWidth , charHeight ) ; graphics2D . setColor ( getForeground ( ) ) ; graphics2D . drawString ( Character . toString ( character ) , colToX ( col ) + vSepOffset , ( rowToY ( ( row + 1 ) ) ) - descent + hSepOffset ) ; } } } graphics2D . dispose ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the rendered dimensions of the text grid model on screen . Used for sizing this component . [CODESPLIT] protected Dimension computeGridSize ( ) { int cols = model . getWidth ( ) ; int rows = model . getHeight ( ) ; int horizSeparatorSize = 0 ; for ( int size : model . getHorizontalSeparators ( ) . values ( ) ) { horizSeparatorSize += size ; } int vertSeparatorSize = 0 ; for ( int size : model . getVerticalSeparators ( ) . values ( ) ) { vertSeparatorSize += size ; } return new Dimension ( vertSeparatorSize + colToX ( cols ) , horizSeparatorSize + rowToY ( rows ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up metrics relating to the size of the font used to display the text grid . This only needs to be done once but this method can be called many times as it is guarded by an initialization flag to prevent these being calculated many times . [CODESPLIT] private void initializeFontMetrics ( ) { if ( ! fontMetricsInitialized ) { FontMetrics fontMetrics = getFontMetrics ( getFont ( ) ) ; charWidth = fontMetrics . charWidth ( ' ' ) ; charHeight = fontMetrics . getHeight ( ) ; descent = fontMetrics . getDescent ( ) ; fontMetricsInitialized = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a property changed listener to be notified of changes to the application state . [CODESPLIT] public void addPropertyChangeListener ( PropertyChangeListener l ) { // Check if the listneres list has been initialized if ( listeners == null ) { // Listeneres list not intialized so create a new list listeners = new ArrayList ( ) ; } synchronized ( listeners ) { // Add the new listener to the list listeners . add ( l ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a property changed listener to be notified of changes to the named property . [CODESPLIT] public void addPropertyChangeListener ( String p , PropertyChangeListener l ) { // Check if the listeneres list has been initialized if ( listeners == null ) { // Listeneres list not initialized so create a new list listeners = new ArrayList ( ) ; } synchronized ( listeners ) { // Add the new listener to the list listeners . add ( l ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified property change listener from the list of active listeners . [CODESPLIT] public void removePropertyChangeListener ( String p , PropertyChangeListener l ) { if ( listeners == null ) { return ; } synchronized ( listeners ) { listeners . remove ( l ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies all property change listeners of the given PropertyChangeEvent . [CODESPLIT] protected void firePropertyChange ( PropertyChangeEvent evt ) { /*log.fine(\"firePropertyChange: called\");*/ // Take a copy of the event as a final variable so that it can be used in an inner class final PropertyChangeEvent finalEvent = evt ; Iterator it ; // Check if the list of listeners is empty if ( listeners == null ) { // There are no listeners so simply return without doing anything return ; } // synchronize on the list of listeners to prevent comodification synchronized ( listeners ) { // Cycle through all listeners and notify them it = listeners . iterator ( ) ; while ( it . hasNext ( ) ) { // Get the next listener from the list final PropertyChangeListener l = ( PropertyChangeListener ) it . next ( ) ; // Notify the listener of the property change event Runnable r = new Runnable ( ) { public void run ( ) { // Fire a property change event l . propertyChange ( finalEvent ) ; } } ; // Run the property change event in the Swing event queue SwingUtilities . invokeLater ( r ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new double range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , double min , double max ) { // Ensure that min is less than or equal to max. if ( min > max ) { throw new IllegalArgumentException ( \"'min' must be less than or equal to 'max'.\" ) ; } synchronized ( DOUBLE_RANGE_TYPES ) { // Add the newly created type to the map of all types. DoubleRangeType newType = new DoubleRangeType ( name , min , max ) ; // Ensure that the named type does not already exist, unless it has an identical definition already, in which // case the old definition can be re-used and the new one discarded. DoubleRangeType oldType = DOUBLE_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( \"The type '\" + name + \"' already exists and cannot be redefined.\" ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { DOUBLE_RANGE_TYPES . put ( name , newType ) ; return newType ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor functor , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { SizeableLinkedList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableLinkedList < WAMInstruction > instructions ; Term [ ] expressions = functor . getArguments ( ) ; for ( int i = 0 ; i < expressions . length ; i ++ ) { Functor expression = ( Functor ) expressions [ i ] ; Integer permVarsRemaining = ( Integer ) defaultBuiltIn . getSymbolTable ( ) . get ( expression . getSymbolKey ( ) , SYMKEY_PERM_VARS_REMAINING ) ; // Select a non-default built-in implementation to compile the functor with, if it is a built-in. BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = defaultBuiltIn ; } // The 'isFirstBody' parameter is only set to true, when this is the first functor of a rule. instructions = builtIn . compileBodyArguments ( expression , false , clauseName , bodyNumber ) ; result . addAll ( instructions ) ; // Call the body. The number of permanent variables remaining is specified for environment trimming. instructions = builtIn . compileBodyCall ( expression , false , false , false , 0 /*permVarsRemaining*/ ) ; result . addAll ( instructions ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void actionPerformed ( ActionEvent e ) { String groupName = e . getActionCommand ( ) ; FadeState fadeState = timers . get ( groupName ) ; if ( fadeState . interpolator . hasNext ( ) ) { Color color = fadeState . interpolator . next ( ) ; fadeState . target . changeColor ( color ) ; fadeState . timer . setInitialDelay ( 0 ) ; fadeState . timer . restart ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Requests a color fade against the specified target under a group name . [CODESPLIT] public void doFade ( ColorDelta target , String groupName ) { FadeState fadeState = timers . get ( groupName ) ; // Set up the color interpolator. Iterator < Color > interpolator = new ColorInterpolator ( startColor , endColor , 8 ) . iterator ( ) ; if ( fadeState == null ) { // Create a new fade state for the target group, and a timer to run it. Timer timer = new Timer ( 20 , this ) ; fadeState = new FadeState ( timer , target , interpolator ) ; timers . put ( groupName , fadeState ) ; } else { // Kill any previous fade and replace the target with the new one. fadeState . timer . stop ( ) ; fadeState . target = target ; fadeState . interpolator = interpolator ; } // Iterate to the initial color. Color firstColor = fadeState . interpolator . next ( ) ; fadeState . target . changeColor ( firstColor ) ; // Kick off the fade timer. fadeState . timer . setActionCommand ( groupName ) ; fadeState . timer . setInitialDelay ( 400 ) ; fadeState . timer . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private static CombinableMatcher < RecordedRequest > recordedRequest ( String expectedMethod , String expectedPath ) { return Matchers . < RecordedRequest > both ( hasProperty ( \"method\" , is ( expectedMethod ) ) ) . and ( hasProperty ( \"path\" , is ( expectedPath ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof NumericTypeVisitor ) { ( ( NumericTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void showMainWindow ( ) { frame = new JFrame ( ) ; frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; frame . setMinimumSize ( new Dimension ( 800 , 600 ) ) ; frame . setPreferredSize ( new Dimension ( 1000 , 800 ) ) ; layout = new DesktopAppLayout ( ) ; frame . getContentPane ( ) . setLayout ( layout ) ; frame . setVisible ( true ) ; JRootPane rootPane = frame . getRootPane ( ) ; rootPane . getInputMap ( ) . put ( KeyStroke . getKeyStroke ( \"SPACE\" ) , \"pressed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void showCentrePane ( JComponent component ) { frame . getContentPane ( ) . add ( component , DesktopAppLayout . CENTER ) ; frame . pack ( ) ; centreComponent = component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void showConsole ( JComponent component ) { showHorizontalBar ( ) ; frame . getContentPane ( ) . add ( component , DesktopAppLayout . CONSOLE ) ; frame . pack ( ) ; consoleComponent = component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void showLeftPane ( JComponent component ) { showLeftBar ( ) ; frame . getContentPane ( ) . add ( component , DesktopAppLayout . LEFT_PANE ) ; frame . pack ( ) ; leftComponent = component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void showRightPane ( JComponent component ) { showRightBar ( ) ; frame . getContentPane ( ) . add ( component , DesktopAppLayout . RIGHT_PANE ) ; frame . pack ( ) ; rightComponent = component ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setKeyShortcut ( KeyStroke keyCombination , String actionName , Runnable action ) { frame . getRootPane ( ) . getInputMap ( JComponent . WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ) . put ( keyCombination , actionName ) ; frame . getRootPane ( ) . getActionMap ( ) . put ( actionName , new RunnableAction ( action ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a horizontal grip - able bar for adjusting the console height . [CODESPLIT] private void showHorizontalBar ( ) { // Left vertical bar. Component bar = factory . createGripPanel ( layout . getConsoleHeightResizer ( ) , false ) ; frame . getContentPane ( ) . add ( bar , DesktopAppLayout . STATUS_BAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a vertical grip - able bar for adjusting the left panel width . [CODESPLIT] private void showLeftBar ( ) { // Left vertical bar. Component bar = factory . createGripPanel ( layout . getLeftPaneWidthResizer ( ) , true ) ; frame . getContentPane ( ) . add ( bar , DesktopAppLayout . LEFT_VERTICAL_BAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a vertical grip - able bar for adjusting the right panel width . [CODESPLIT] private void showRightBar ( ) { // Right vertical bar. Component bar = factory . createGripPanel ( layout . getRightPaneWidthResizer ( ) , true ) ; frame . getContentPane ( ) . add ( bar , DesktopAppLayout . RIGHT_VERTICAL_BAR ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < MicrodataItem > getItems ( String type ) { Elements elements = document . select ( byItemType ( newUrl ( type ) ) ) ; return Lists . transform ( elements , new Function < Element , MicrodataItem > ( ) { public MicrodataItem apply ( Element element ) { return new JsoupMicrodataItem ( JsoupMicrodataDocument . this , element ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < Link > getLinks ( String rel ) { Elements elements = document . select ( byLink ( rel ) ) ; return Lists . transform ( elements , new Function < Element , Link > ( ) { public Link apply ( Element element ) { return new JsoupLink ( JsoupMicrodataDocument . this , element ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public < T > T unwrap ( Class < T > type ) { checkArgument ( Document . class . equals ( type ) , \"Cannot unwrap to: %s\" , type ) ; return type . cast ( document ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] private static Document sanitize ( Document document ) { for ( FormElement form : document . getAllElements ( ) . forms ( ) ) { sanitizeRadioControls ( form ) ; } return document ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ensures that radio controls are mutually exclusive within control groups . [CODESPLIT] private static void sanitizeRadioControls ( FormElement form ) { Map < String , Element > controlsByName = new HashMap < String , Element > ( ) ; for ( Element control : form . elements ( ) ) { // cannot use Element.select since Element.hashCode collapses like elements if ( \"radio\" . equals ( control . attr ( \"type\" ) ) && control . hasAttr ( \"checked\" ) ) { String name = control . attr ( \"name\" ) ; if ( controlsByName . containsKey ( name ) ) { controlsByName . get ( name ) . attr ( \"checked\" , false ) ; } controlsByName . put ( name , control ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait for the predicate to become true on the specified object . [CODESPLIT] public void await ( T t ) throws InterruptedException { synchronized ( monitor ) { long waitNanos = evaluateWithWaitTimeNanos ( t ) ; // Loop forever until all conditions pass or the thread is interrupted. while ( waitNanos > 0 ) { // If some conditions failed, then wait for the shortest wait time, or until the thread is woken up by // a signal, before re-evaluating conditions. long milliPause = waitNanos / 1000000 ; int nanoPause = ( int ) ( waitNanos % 1000000 ) ; monitor . wait ( milliPause , nanoPause ) ; waitNanos = evaluateWithWaitTimeNanos ( t ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Wait for up to a timeout limit for the predicate to become true on the specified object . [CODESPLIT] public boolean await ( T t , long timeout , TimeUnit unit ) throws InterruptedException { synchronized ( monitor ) { // Holds the absolute time when the timeout expires. long expiryTimeNanos = System . nanoTime ( ) + unit . toNanos ( timeout ) ; // Used to hold the estimated wait time until the condition may pass. long waitNanos = evaluateWithWaitTimeNanos ( t ) ; // Loop forever until all conditions pass, the timeout expires, or the thread is interrupted. while ( waitNanos > 0 ) { // Check how much time remains until the timeout expires. long remainingTimeNanos = expiryTimeNanos - System . nanoTime ( ) ; // Check if the timeout has expired. if ( remainingTimeNanos <= 0 ) { return false ; } // If some conditions failed, then wait for the shortest of the wait time or the remaining time until the // timout expires, or until the thread is woken up by a signal, before re-evaluating conditions. long timeToPauseNanos = ( waitNanos < remainingTimeNanos ) ? waitNanos : remainingTimeNanos ; long milliPause = timeToPauseNanos / 1000000 ; int nanoPause = ( int ) ( timeToPauseNanos % 1000000 ) ; monitor . wait ( milliPause , nanoPause ) ; // Re-evelaute the condition and obtain a new estimate of how long until it may pass. waitNanos = evaluateWithWaitTimeNanos ( t ) ; } } // All conditions have passed when the above loop terminates. return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implementation of the script goal . [CODESPLIT] public void execute ( ) throws MojoExecutionException , MojoFailureException { //log.debug(\"public void execute() throws MojoExecutionException: called\"); // Turn each of the test runner command lines into a script. for ( String commandName : commands . keySet ( ) ) { if ( scriptOutDirectory != null ) { writeUnixScript ( commandName , scriptOutDirectory ) ; writeWindowsScript ( commandName , scriptOutDirectory ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends the classpath onto the command line . [CODESPLIT] protected String appendClasspath ( String commandLine , boolean unix ) { String pathSeperator ; String seperator ; if ( unix ) { pathSeperator = \"/\" ; seperator = \":\" ; } else { pathSeperator = \"\\\\\" ; seperator = \";\" ; } for ( Iterator i = classpathElements . iterator ( ) ; i . hasNext ( ) ; ) { String cpPath = ( String ) i . next ( ) ; cpPath = cpPath . replace ( \"/\" , pathSeperator ) ; commandLine += cpPath + ( i . hasNext ( ) ? seperator : \"\" ) ; } return commandLine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new date range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , DateOnly from , DateOnly to ) { // Ensure that min is less than or equal to max. if ( ( from != null ) && ( to != null ) && ( from . compareTo ( to ) > 0 ) ) { throw new IllegalArgumentException ( \"'min' must be less than or equal to 'max'.\" ) ; } synchronized ( DATE_RANGE_TYPES ) { // Add the newly created type to the map of all types. DateRangeType newType = new DateRangeType ( name , from , to ) ; // Ensure that the named type does not already exist, unless it has an identical definition already, in which // case the old definition can be re-used and the new one discarded. DateRangeType oldType = DATE_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( \"The type '\" + name + \"' already exists and cannot be redefined.\" ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { DATE_RANGE_TYPES . put ( name , newType ) ; return newType ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void acceptVisitor ( TypeVisitor visitor ) { if ( visitor instanceof DateRangeTypeVisitor ) { ( ( DateRangeTypeVisitor ) visitor ) . visit ( this ) ; } else { super . acceptVisitor ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Frees all variables held in this stack frame and sets all the stack slots to <tt > null< / tt > . Note that as the stack slots are <tt > null< / tt > the { [CODESPLIT] public void free ( ) { for ( int i = 0 ; i < bindings . length ; i ++ ) { if ( bindings [ i ] != null ) { bindings [ i ] . free ( ) ; bindings [ i ] = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public List < Link > getLinks ( String rel ) { List < WebElement > elements = element . findElements ( byLink ( rel ) ) ; return Lists . transform ( elements , new Function < WebElement , Link > ( ) { public Link apply ( WebElement element ) { return new SeleniumLink ( driver , element ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements the top - level interpreter loop . This will parse and evaluate sentences until it encounters an CTRL - D in query mode at which point the interpreter will terminate . [CODESPLIT] public void interpreterLoop ( ) throws IOException { // Display the welcome message. printIntroduction ( ) ; // Initialize the JLine console. consoleReader = initializeCommandLineReader ( ) ; // Used to buffer input, and only feed it to the parser when a PERIOD is encountered. TokenBuffer tokenBuffer = new TokenBuffer ( ) ; // Used to hold the currently buffered lines of input, for the purpose of presenting this back to the user // in the event of a syntax or other error in the input. ArrayList < String > inputLines = new ArrayList < String > ( ) ; // Used to count the number of lines entered. int lineNo = 0 ; while ( true ) { String line = null ; try { line = consoleReader . readLine ( mode . prompt ) ; inputLines . add ( line ) ; // JLine returns null if CTRL-D is pressed. Exit program mode back to query mode, or exit the // interpreter completely from query mode. if ( ( line == null ) && ( ( mode == Mode . Query ) || ( mode == Mode . QueryMultiLine ) ) ) { /*log.fine(\"CTRL-D in query mode, exiting.\");*/ System . out . println ( ) ; break ; } else if ( ( line == null ) && ( ( mode == Mode . Program ) || ( mode == Mode . ProgramMultiLine ) ) ) { /*log.fine(\"CTRL-D in program mode, returning to query mode.\");*/ System . out . println ( ) ; mode = Mode . Query ; continue ; } // Check the input to see if a system directive was input. This is only allowed in query mode, and is // handled differently to normal queries. if ( mode == Mode . Query ) { Source < Token > tokenSource = new OffsettingTokenSource ( TokenSource . getTokenSourceForString ( line ) , lineNo ) ; parser . setTokenSource ( tokenSource ) ; PrologParser . Directive directive = parser . peekAndConsumeDirective ( ) ; if ( directive != null ) { switch ( directive ) { case Trace : /*log.fine(\"Got trace directive.\");*/ break ; case Info : /*log.fine(\"Got info directive.\");*/ break ; case User : /*log.fine(\"Got user directive, entering program mode.\");*/ mode = Mode . Program ; break ; } inputLines . clear ( ) ; continue ; } } // For normal queries, the query functor '?-' begins every statement, this is not passed back from // JLine even though it is used as the command prompt. if ( mode == Mode . Query ) { line = QUERY_PROMPT + line ; inputLines . set ( inputLines . size ( ) - 1 , line ) ; } // Buffer input tokens until EOL is reached, of the input is terminated with a PERIOD. Source < Token > tokenSource = new OffsettingTokenSource ( TokenSource . getTokenSourceForString ( line ) , lineNo ) ; Token nextToken ; while ( true ) { nextToken = tokenSource . poll ( ) ; if ( nextToken == null ) { break ; } if ( nextToken . kind == PrologParserConstants . PERIOD ) { /*log.fine(\"Token was PERIOD.\");*/ mode = ( mode == Mode . QueryMultiLine ) ? Mode . Query : mode ; mode = ( mode == Mode . ProgramMultiLine ) ? Mode . Program : mode ; tokenBuffer . offer ( nextToken ) ; break ; } else if ( nextToken . kind == PrologParserConstants . EOF ) { /*log.fine(\"Token was EOF.\");*/ mode = ( mode == Mode . Query ) ? Mode . QueryMultiLine : mode ; mode = ( mode == Mode . Program ) ? Mode . ProgramMultiLine : mode ; lineNo ++ ; break ; } tokenBuffer . offer ( nextToken ) ; } // Evaluate the current token buffer, whenever the input is terminated with a PERIOD. if ( ( nextToken != null ) && ( nextToken . kind == PrologParserConstants . PERIOD ) ) { parser . setTokenSource ( tokenBuffer ) ; // Parse the next clause. Sentence < Clause > nextParsing = parser . parse ( ) ; /*log.fine(nextParsing.toString());*/ evaluate ( nextParsing ) ; inputLines . clear ( ) ; } } catch ( SourceCodeException e ) { SourceCodePosition sourceCodePosition = e . getSourceCodePosition ( ) . asZeroOffsetPosition ( ) ; int startLine = sourceCodePosition . getStartLine ( ) ; int endLine = sourceCodePosition . getEndLine ( ) ; int startColumn = sourceCodePosition . getStartColumn ( ) ; int endColumn = sourceCodePosition . getEndColumn ( ) ; System . out . println ( \"[(\" + startLine + \", \" + startColumn + \"), (\" + endLine + \", \" + endColumn + \")]\" ) ; for ( int i = 0 ; i < inputLines . size ( ) ; i ++ ) { String errorLine = inputLines . get ( i ) ; System . out . println ( errorLine ) ; // Check if the line has the error somewhere in it, and mark the part of it that contains the error. int pos = 0 ; if ( i == startLine ) { for ( ; pos < startColumn ; pos ++ ) { System . out . print ( \" \" ) ; } } if ( i == endLine ) { for ( ; pos <= endColumn ; pos ++ ) { System . out . print ( \"^\" ) ; } System . out . println ( ) ; } if ( ( i > startLine ) && ( i < endLine ) ) { for ( ; pos < errorLine . length ( ) ; pos ++ ) { System . out . print ( \"^\" ) ; } System . out . println ( ) ; } } System . out . println ( ) ; System . out . println ( e . getMessage ( ) ) ; System . out . println ( ) ; inputLines . clear ( ) ; tokenBuffer . clear ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a welcome message . [CODESPLIT] private void printIntroduction ( ) { System . out . println ( \"| LoJiX Prolog.\" ) ; System . out . println ( \"| Copyright The Sett Ltd.\" ) ; System . out . println ( \"| Licensed under the Apache License, Version 2.0.\" ) ; System . out . println ( \"| //www.apache.org/licenses/LICENSE-2.0\" ) ; System . out . println ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up the JLine console reader . [CODESPLIT] private ConsoleReader initializeCommandLineReader ( ) throws IOException { ConsoleReader reader = new ConsoleReader ( ) ; reader . setBellEnabled ( false ) ; return reader ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a query against the resolver or adds a clause to the resolvers domain . [CODESPLIT] private void evaluate ( Sentence < Clause > sentence ) throws SourceCodeException { Clause clause = sentence . getT ( ) ; if ( clause . isQuery ( ) ) { engine . endScope ( ) ; engine . compile ( sentence ) ; evaluateQuery ( ) ; } else { // Check if the program clause is new, or a continuation of the current predicate. int name = clause . getHead ( ) . getName ( ) ; if ( ( currentPredicateName == null ) || ( currentPredicateName != name ) ) { engine . endScope ( ) ; currentPredicateName = name ; } addProgramClause ( sentence ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a query . In the case of queries the interner is used to recover textual names for the resulting variable bindings . The user is queried through the parser to if more than one solution is required . [CODESPLIT] private void evaluateQuery ( ) { /*log.fine(\"Read query from input.\");*/ // Create an iterator to generate all solutions on demand with. Iteration will stop if the request to // the parser for the more ';' token fails. Iterator < Set < Variable >> i = engine . iterator ( ) ; if ( ! i . hasNext ( ) ) { System . out . println ( \"false. \" ) ; return ; } for ( ; i . hasNext ( ) ; ) { Set < Variable > solution = i . next ( ) ; if ( solution . isEmpty ( ) ) { System . out . print ( \"true\" ) ; } else { for ( Iterator < Variable > j = solution . iterator ( ) ; j . hasNext ( ) ; ) { Variable nextVar = j . next ( ) ; String varName = engine . getVariableName ( nextVar . getName ( ) ) ; System . out . print ( varName + \" = \" + nextVar . getValue ( ) . toString ( engine , true , false ) ) ; if ( j . hasNext ( ) ) { System . out . println ( ) ; } } } // Finish automatically if there are no more solutions. if ( ! i . hasNext ( ) ) { System . out . println ( \".\" ) ; break ; } // Check if the user wants more solutions. try { int key = consoleReader . readVirtualKey ( ) ; if ( key == SEMICOLON ) { System . out . println ( \" ;\" ) ; } else { System . out . println ( ) ; break ; } } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a boolean into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( boolean b ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Boolean . toString ( b ) ) ; result . nativeType = BOOLEAN ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a byte into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( byte b ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Byte . toString ( b ) ) ; result . nativeType = BYTE ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a char into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( char c ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Character . toString ( c ) ) ; result . nativeType = CHAR ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a short into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( short s ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Short . toString ( s ) ) ; result . nativeType = SHORT ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a int into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( int i ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Integer . toString ( i ) ) ; result . nativeType = INT ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a long into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( long l ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Long . toString ( l ) ) ; result . nativeType = LONG ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a float into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( float f ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Float . toString ( f ) ) ; result . nativeType = FLOAT ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a double into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( double d ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( Double . toString ( d ) ) ; result . nativeType = DOUBLE ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a String into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( String s ) { MultiTypeData result = new MultiTypeData ( ) ; // Start by assuming that the String can only be converted to a String. result . typeFlags = STRING ; result . stringValue = s ; // Assume that the native type is String. It is up to methods that call this one to override this if this is // not the case. result . nativeType = STRING ; // Check if the string can be converted to a boolean. if ( \"true\" . equals ( s ) ) { result . booleanValue = true ; result . typeFlags |= BOOLEAN ; } else if ( \"false\" . equals ( s ) ) { result . booleanValue = false ; result . typeFlags |= BOOLEAN ; } // Check if the string can be converted to an int. try { result . intValue = Integer . parseInt ( s ) ; result . typeFlags |= INT ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags &= ( Integer . MAX_VALUE - INT ) ; } // Check if the string can be converted to a byte. try { result . byteValue = Byte . parseByte ( s ) ; result . typeFlags |= BYTE ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - BYTE ) ; } // Check if the string can be converted to a char. if ( s . length ( ) == 1 ) { result . charValue = s . charAt ( 0 ) ; result . typeFlags |= CHAR ; } // Check if the string can be converted to a short. try { result . shortValue = Short . parseShort ( s ) ; result . typeFlags |= SHORT ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - SHORT ) ; } // Check if the string can be converted to a long. try { result . longValue = Long . parseLong ( s ) ; result . typeFlags |= LONG ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - LONG ) ; } // Check if the string can be converted to a float. try { result . floatValue = Float . parseFloat ( s ) ; result . typeFlags |= FLOAT ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - FLOAT ) ; } // Check if the string can be converted to a double. try { result . doubleValue = Double . parseDouble ( s ) ; result . typeFlags |= DOUBLE ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; result . typeFlags = ( Integer . MAX_VALUE - DOUBLE ) ; } // Assume the string can never be converted to an object. return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a Object into a multi type data object . [CODESPLIT] public static MultiTypeData getMultiTypeData ( Object o ) { // Convert the value to a String and return the set of types that that String can be converted to. MultiTypeData result = getMultiTypeData ( o . toString ( ) ) ; result . nativeType = OBJECT ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a multi type data object and a class representing a type this method attemps to return an object of that class created from the multi type data . The exception to this rule is if the specified data type is a primtive type such as int . clas then the returned object will be of the equivalent wrapper class type Integer . class in this case . This is because a primitive cannot be returned under an Object return type . [CODESPLIT] public static Object convert ( MultiTypeData d , Class c ) { // Check if it is an boolean convertion. if ( ( ( d . typeFlags & BOOLEAN ) != 0 ) && ( Boolean . TYPE . equals ( c ) || Boolean . class . equals ( c ) ) ) { return d . booleanValue ; } // Check if it is an int convertion. else if ( ( ( d . typeFlags & INT ) != 0 ) && ( Integer . TYPE . equals ( c ) || Integer . class . equals ( c ) ) ) { return d . intValue ; } // Check if it is an char convertion. else if ( ( ( d . typeFlags & CHAR ) != 0 ) && ( Character . TYPE . equals ( c ) || Character . class . equals ( c ) ) ) { return d . charValue ; } // Check if it is an byte convertion. else if ( ( ( d . typeFlags & BYTE ) != 0 ) && ( Byte . TYPE . equals ( c ) || Byte . class . equals ( c ) ) ) { return d . byteValue ; } // Check if it is an short convertion. else if ( ( ( d . typeFlags & SHORT ) != 0 ) && ( Short . TYPE . equals ( c ) || Short . class . equals ( c ) ) ) { return d . shortValue ; } // Check if it is an long convertion. else if ( ( ( d . typeFlags & LONG ) != 0 ) && ( Long . TYPE . equals ( c ) || Long . class . equals ( c ) ) ) { return d . longValue ; } // Check if it is an float convertion. else if ( ( ( d . typeFlags & FLOAT ) != 0 ) && ( Float . TYPE . equals ( c ) || Float . class . equals ( c ) ) ) { return d . floatValue ; } // Check if it is an double convertion. else if ( ( ( d . typeFlags & DOUBLE ) != 0 ) && ( Double . TYPE . equals ( c ) || Double . class . equals ( c ) ) ) { return d . doubleValue ; } // Check if it is a string convertion. else if ( ( ( d . typeFlags & STRING ) != 0 ) && String . class . equals ( c ) ) { return d . stringValue ; } // Check if it is an object convertion and th object types match. else if ( ( ( d . typeFlags & OBJECT ) != 0 ) && d . objectValue . getClass ( ) . equals ( c ) ) { return d . objectValue ; } // Throw a class cast exception if the multi data type cannot be converted to the specified class. else { throw new ClassCastException ( \"The multi data type, \" + d + \", cannot be converted to the class, \" + c + \".\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For a set of types this method selects the best type to convert a given multi type data object into . This method can be usefull when deciding which of several setter methods on a bean is the best one to convert the multi type data obejct into before calling the beans setter method . [CODESPLIT] public static Class bestMatchingConversion ( MultiTypeData d , Collection < Class > types ) { /*log.fine(\"public static Class bestMatchingConvertion(MultiTypeData d, Set<Class> types): called\");*/ /*log.fine(\"d = \" + d);*/ /*log.fine(\"types = \" + types);*/ // Try to match the native type first before trying the convertions. switch ( d . nativeType ) { case OBJECT : { // Check if the matching Object class can be found in the set of possible classes. if ( types . contains ( d . objectValue . getClass ( ) ) ) { return d . objectValue . getClass ( ) ; } break ; } case BOOLEAN : { // Check if boolean is in the set of possible classes to match. if ( types . contains ( boolean . class ) ) { return boolean . class ; } else if ( types . contains ( Boolean . class ) ) { return Boolean . class ; } break ; } case CHAR : { // Check if char is in the set of possible classes to match. if ( types . contains ( char . class ) ) { return char . class ; } else if ( types . contains ( Character . class ) ) { return Character . class ; } break ; } case BYTE : { // Check if byte is in the set of possible classes to match. if ( types . contains ( byte . class ) ) { return byte . class ; } else if ( types . contains ( Byte . class ) ) { return Byte . class ; } break ; } case SHORT : { // Check if short is in the set of possible classes to match. if ( types . contains ( short . class ) ) { return short . class ; } else if ( types . contains ( Short . class ) ) { return Short . class ; } break ; } case INT : { // Check if int is in the set of possible classes to match. if ( types . contains ( int . class ) ) { return int . class ; } else if ( types . contains ( Integer . class ) ) { return Integer . class ; } break ; } case LONG : { // Check if long is in the set of possible classes to match. if ( types . contains ( long . class ) ) { return long . class ; } else if ( types . contains ( Long . class ) ) { return Long . class ; } break ; } case FLOAT : { // Check if float is in the set of possible classes to match. if ( types . contains ( float . class ) ) { return float . class ; } else if ( types . contains ( Float . class ) ) { return Float . class ; } break ; } case DOUBLE : { // Check if double is in the set of possible classes to match. if ( types . contains ( double . class ) ) { return double . class ; } else if ( types . contains ( Double . class ) ) { return Double . class ; } break ; } case STRING : { // Check if String is in the set of possible classes to match. if ( types . contains ( String . class ) ) { return String . class ; } break ; } default : { throw new IllegalStateException ( \"Unknown MultiTypeData type.\" ) ; } } // Check if the multi type can be converted to a boolean and boolean is in the set of possible convertions. if ( ( ( d . typeFlags & BOOLEAN ) != 0 ) && types . contains ( boolean . class ) ) { return boolean . class ; } else if ( ( ( d . typeFlags & BOOLEAN ) != 0 ) && types . contains ( Boolean . class ) ) { return Boolean . class ; } // Check if the multi type can be converted to a byte and byte is in the set of possible convertions. else if ( ( ( d . typeFlags & BYTE ) != 0 ) && types . contains ( byte . class ) ) { return byte . class ; } else if ( ( ( d . typeFlags & BYTE ) != 0 ) && types . contains ( Byte . class ) ) { return Byte . class ; } // Check if the multi type can be converted to a char and char is in the set of possible convertions. else if ( ( ( d . typeFlags & CHAR ) != 0 ) && types . contains ( char . class ) ) { return char . class ; } else if ( ( ( d . typeFlags & CHAR ) != 0 ) && types . contains ( Character . class ) ) { return Character . class ; } // Check if the multi type can be converted to a short and short is in the set of possible convertions. else if ( ( ( d . typeFlags & SHORT ) != 0 ) && types . contains ( short . class ) ) { return short . class ; } else if ( ( ( d . typeFlags & SHORT ) != 0 ) && types . contains ( Short . class ) ) { return Short . class ; } // Check if the multi type can be converted to a int and int is in the set of possible convertions. else if ( ( ( d . typeFlags & INT ) != 0 ) && types . contains ( int . class ) ) { return int . class ; } else if ( ( ( d . typeFlags & INT ) != 0 ) && types . contains ( Integer . class ) ) { return Integer . class ; } // Check if the multi type can be converted to a long and long is in the set of possible convertions. else if ( ( ( d . typeFlags & LONG ) != 0 ) && types . contains ( long . class ) ) { return long . class ; } else if ( ( ( d . typeFlags & LONG ) != 0 ) && types . contains ( Long . class ) ) { return Long . class ; } // Check if the multi type can be converted to a float and float is in the set of possible convertions. else if ( ( ( d . typeFlags & FLOAT ) != 0 ) && types . contains ( float . class ) ) { return float . class ; } else if ( ( ( d . typeFlags & FLOAT ) != 0 ) && types . contains ( Float . class ) ) { return Float . class ; } // Check if the multi type can be converted to a double and double is in the set of possible convertions. else if ( ( ( d . typeFlags & DOUBLE ) != 0 ) && types . contains ( double . class ) ) { return double . class ; } else if ( ( ( d . typeFlags & DOUBLE ) != 0 ) && types . contains ( Double . class ) ) { return Double . class ; } // Check if the multi type can be converted to a String and String is in the set of possible convertions. else if ( ( ( d . typeFlags & STRING ) != 0 ) && types . contains ( String . class ) ) { return String . class ; } // No matching type convertion found so return null. else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts an object into the scope . [CODESPLIT] public void put ( String name , Object value ) { pageContext . setAttribute ( name , value , scope ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks is the specified dimension is equivalent . Equivalent means same informations ( including type ) same defaults same links [CODESPLIT] public boolean isEquivalent ( DimensionTable otherDim , Collection < Error > errors ) { if ( this . informationNameToColumn . size ( ) != otherDim . informationNameToColumn . size ( ) ) { errors . add ( new Error ( \"[\" + this . getDimensionName ( ) + \"-\" + otherDim . getDimensionName ( ) + \"] - Not the same number of informations.\" ) ) ; return false ; } for ( Entry < String , AbstractSqlColumn > entry : this . informationNameToColumn . entrySet ( ) ) { AbstractSqlColumn otherCol = otherDim . informationNameToColumn . get ( entry . getKey ( ) ) ; if ( otherCol == null ) { errors . add ( new Error ( \"[\" + this . getDimensionName ( ) + \"-\" + otherDim . getDimensionName ( ) + \"] - Information named \" + entry . getKey ( ) + \" not found in \" + otherDim . getDimensionName ( ) + \".\" ) ) ; return false ; } if ( ! otherCol . getBusinessName ( ) . equals ( entry . getValue ( ) . getBusinessName ( ) ) ) { errors . add ( new Error ( \"[\" + this . getDimensionName ( ) + \"-\" + otherDim . getDimensionName ( ) + \"] - Information named \" + entry . getKey ( ) + \" have not the same name.\" ) ) ; return false ; } if ( otherCol . getColumnType ( ) != entry . getValue ( ) . getColumnType ( ) ) { errors . add ( new Error ( \"[\" + this . getDimensionName ( ) + \"-\" + otherDim . getDimensionName ( ) + \"] - Information named \" + entry . getKey ( ) + \" are not the same type.\" ) ) ; return false ; } } if ( ! otherDim . getDefaultSearchColumn ( ) . getBusinessName ( ) . equals ( this . getDefaultSearchColumn ( ) . getBusinessName ( ) ) ) { errors . add ( new Error ( \"[\" + this . getDimensionName ( ) + \"-\" + otherDim . getDimensionName ( ) + \"] - \\\"default search\\\" are not the same.\" ) ) ; return false ; } if ( ! otherDim . getDefaultGroupByColumn ( ) . getBusinessName ( ) . equals ( this . getDefaultGroupByColumn ( ) . getBusinessName ( ) ) ) { errors . add ( new Error ( \"[\" + this . getDimensionName ( ) + \"-\" + otherDim . getDimensionName ( ) + \"] - \\\"default group by\\\" are not the same.\" ) ) ; return false ; } if ( ! otherDim . getLinkedTables ( ) . equals ( this . getLinkedTables ( ) ) ) { errors . add ( new Error ( \"[\" + this . getDimensionName ( ) + \"-\" + otherDim . getDimensionName ( ) + \"] - Have not the same linked tables.\" ) ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterFunctor ( Functor functor ) { String head = traverser . isInHead ( ) ? \"/head\" : \"\" ; String last = traverser . isLastBodyFunctor ( ) ? \"/last\" : \"\" ; String symKey = functor . getSymbolKey ( ) . toString ( ) ; if ( traverser . isTopLevel ( ) ) { addLineToRow ( \"functor(\" + symKey + \")\" + head + last ) ; } else { addLineToRow ( \"arg(\" + symKey + \")\" ) ; } nextRow ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected void enterVariable ( Variable variable ) { Integer allocation = ( Integer ) symbolTable . get ( variable . getSymbolKey ( ) , \"allocation\" ) ; String symKey = variable . getSymbolKey ( ) . toString ( ) ; String allocString = \"\" ; if ( allocation != null ) { int slot = ( allocation & ( 0xff ) ) ; int mode = allocation >> 8 ; allocString = ( ( mode == STACK_ADDR ) ? \"Y\" : \"X\" ) + slot ; } addLineToRow ( \"arg/var(\" + symKey + \") \" + allocString ) ; nextRow ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public boolean containsKey ( Object objectKey ) { int key = ( Integer ) objectKey ; return keyInRange ( key ) && ( data [ offset ( key ) ] != null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public V get ( Object objectKey ) { int key = ( Integer ) objectKey ; if ( keyInRange ( key ) ) { return ( V ) data [ offset ( key ) ] ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public V put ( Integer key , V value ) { if ( keyTooLarge ( key ) ) { expand ( key ) ; } int offset = offset ( key ) ; V oldValue = ( V ) data [ offset ] ; data [ offset ] = value ; // If the key is beyond the current end of the array, then move the end up. if ( key >= end ) { end = key + 1 ; } // Increment the count only if a new value was inserted. if ( oldValue == null ) { count ++ ; } return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears entries up to and including the specified key from the map . This is a simple garbage collection operation to clear consumed data from the circular buffer . [CODESPLIT] public void clearUpTo ( int key ) { if ( ( ( start <= key ) && ( key < ( end - 1 ) ) ) ) { // Loop from the start of the data, up to the key to clear up to, clearing all data encountered in-between. int newStart ; for ( newStart = start ; ( newStart <= end ) && ( newStart <= key ) ; newStart ++ ) { int offset = offset ( newStart ) ; if ( data [ offset ] != null ) { data [ offset ] = null ; count -- ; } } // Continue on after the clear up to point, until the first non-null entry or end of array is encountered, // and make that the new start. for ( ; newStart <= end ; newStart ++ ) { if ( data [ offset ( newStart ) ] != null ) { break ; } } start = newStart ; } else { // The key does not lie between the start and end markers, so clear the entire map up to the end int newStart ; for ( newStart = start ; ( newStart <= end ) ; newStart ++ ) { int offset = offset ( newStart ) ; if ( data [ offset ] != null ) { data [ offset ] = null ; count -- ; } } start = newStart ; offset = - start ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public V remove ( Object objectKey ) { int key = ( Integer ) objectKey ; if ( keyInRange ( key ) ) { // Check if the key is the first element in the list, and walk forward to find the next non-empty element // in order to advance the start to. if ( key == start ) { int newStart = start + 1 ; while ( ( data [ offset ( newStart ) ] == null ) && ( newStart <= end ) ) { newStart ++ ; } start = newStart ; } int offset = offset ( key ) ; V result = ( V ) data [ offset ] ; data [ offset ] = null ; // Decrement the count only if a value was removed. if ( result != null ) { count -- ; } return result ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void clear ( ) { data = new Object [ data . length ] ; length = data . length ; lowMark = - 1 ; start = 0 ; end = 0 ; count = 0 ; offset = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Iterator < V > iterator ( ) { return new Iterator < V > ( ) { /** Holds the current offset into the data. */ int current = start ; /** {@inheritDoc} */ public boolean hasNext ( ) { return current < end ; } /** {@inheritDoc} */ public V next ( ) { return ( V ) data [ current ++ ] ; } /** {@inheritDoc} */ public void remove ( ) { throw new UnsupportedOperationException ( \"'remove' not supported on this iterator.\" ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands the size of the storage to whichever is the larger of 1 . 5 times the old size or an array large enough to hold the proposed key that caused the expansion copying the old data into a new array . [CODESPLIT] private void expand ( int key ) { // Set the new size to whichever is the larger of 1.5 times the old size, or an array large enough to hold // the proposed key that caused the expansion. int newFactorSize = ( ( length * 3 ) / 2 ) + 1 ; int newSpaceSize = spaceRequired ( key ) ; int newSize = ( newSpaceSize > newFactorSize ) ? newSpaceSize : newFactorSize ; Object [ ] oldData = data ; data = new Object [ newSize ] ; // The valid data in the old array runs from offset(start) to offset(end) when offset(start) < offset(end), and // from offset(start) to length - 1 and 0 to offset(end) when offset(start) >= offset(end). int offsetStart = offset ( start ) ; int offsetEnd = offset ( end ) ; if ( offsetStart < offsetEnd ) { System . arraycopy ( oldData , offsetStart , data , 0 , end - start ) ; } else { System . arraycopy ( oldData , offsetStart , data , 0 , length - offsetStart ) ; System . arraycopy ( oldData , 0 , data , length - offsetStart , offsetEnd ) ; } offset = - start ; length = newSize ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Override public void setValue ( String value ) { checkArgument ( ! UNCHECKED_VALUE . equals ( value ) , \"Cannot uncheck radio control\" ) ; super . setValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void insert ( String string , int c , int r ) { for ( char character : string . toCharArray ( ) ) { internalInsert ( character , c ++ , r ) ; } updateListeners ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public char getCharAt ( int c , int r ) { Character character = data . get ( ( long ) c , ( long ) r ) ; if ( character == null ) { return ' ' ; } else { return character ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public TextGridModel createInnerGrid ( int c , int r , int w , int h ) { return new NestedTextGridImpl ( c , r , w , h , this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public TextTableModel createTable ( int c , int r , int w , int h ) { // Supply a text table, with this grid set up to listen for updates to the table, and to be re-rendered as the // table changes. TextTableModel textTable = new TextTableImpl ( ) ; textTable . addTextTableListener ( new TableListener ( ) ) ; return textTable ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies all interested listeners of an update to this model . [CODESPLIT] protected void updateListeners ( ) { TextGridEvent event = new TextGridEvent ( this ) ; for ( TextGridListener listener : listeners ) { listener . changedUpdate ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a single character into the grid at the specified location . This is a private insert method that does not notify model listeners so that the public insert methods can do that as a separate step . [CODESPLIT] private void internalInsert ( char character , int c , int r ) { maxColumn = ( c > maxColumn ) ? c : maxColumn ; maxRow = ( r > maxRow ) ? r : maxRow ; data . put ( ( long ) c , ( long ) r , character ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the next sentence from the current token source . [CODESPLIT] public Sentence < Clause > parse ( ) throws SourceCodeException { if ( parser . peekAndConsumeEof ( ) ) { return null ; } else { return new SentenceImpl < Clause > ( parser . sentence ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean proofStep ( ResolutionState state ) { if ( TRACE ) { /*trace.fine(state.getTraceIndenter().generateTraceIndent() + \"Cutting choice points...\");*/ } Queue < ResolutionState > choicePointStates = parentChoicePointState . getChoicePoints ( ) ; if ( choicePointStates != null ) { for ( ResolutionState choicePointState : choicePointStates ) { choicePointState . cut ( ) ; } } state . getGoalStack ( ) . poll ( ) ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two search nodes by their path cost . [CODESPLIT] public int compare ( SearchNode object1 , SearchNode object2 ) { float cost1 = object1 . getPathCost ( ) ; float cost2 = object2 . getPathCost ( ) ; return ( cost1 > cost2 ) ? 1 : ( ( cost1 < cost2 ) ? - 1 : 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof IntegerTypeVisitor ) { ( ( IntegerTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a flat list of terms which are literals variables functors or operators into a tree in such a way that the operators associativity and precendence is obeyed . [CODESPLIT] public Term parseOperators ( Term [ ] terms ) throws SourceCodeException { // Initialize the parsers state. stack . offer ( 0 ) ; state = 0 ; position = 0 ; nextTerm = null ; // Consume the terms from left to right. for ( position = 0 ; position <= terms . length ; ) { Symbol nextSymbol ; // Decide what the next symbol to parse is; candidate op, term or final. if ( position < terms . length ) { nextTerm = terms [ position ] ; if ( nextTerm instanceof CandidateOpSymbol ) { nextSymbol = Symbol . Op ; } else { nextSymbol = Symbol . Term ; } } else { nextSymbol = Symbol . Final ; } // Look in the action table to find the action associated with the current symbol and state. Action action = actionTable [ state ] [ nextSymbol . ordinal ( ) ] ; // Apply the action. action . apply ( ) ; } return ( Functor ) outputStack . poll ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the priority and associativity of a named operator in this table . This method may be used to remove operators by some implementations through a special setting of the priority value . A priority value of zero will remove any existing operator matching the fixity of the one specified ( that is pre or post / infix ) . To be accepted the operator must have a priority between 0 and 1200 inclusive and can only be a postfix operator when an infix is not already defined with the same name and similarly for infix operators when a postfix operator is already defined . [CODESPLIT] public void setOperator ( int name , String textName , int priority , OpSymbol . Associativity associativity ) { // Check that the name of the operator is valid. // Check that the priority of the operator is valid. if ( ( priority < 0 ) || ( priority > 1200 ) ) { throw new IllegalArgumentException ( \"Operator priority must be between 0 and 1200 inclusive.\" ) ; } OpSymbol opSymbol = new OpSymbol ( name , textName , associativity , priority ) ; // Consult the defined operators to see if there are any already defined that match the name of the // new definition, otherwise a map of operators by fixity needs to be created. EnumMap < OpSymbol . Fixity , OpSymbol > operatorMap = operators . get ( textName ) ; // Check if the priority is non-zero in which case the operator is being added or redefined. if ( priority > 0 ) { if ( operatorMap == null ) { operatorMap = new EnumMap < OpSymbol . Fixity , OpSymbol > ( OpSymbol . Fixity . class ) ; operators . put ( textName , operatorMap ) ; } // Check if the operators fixity to see if further rules regarding simultaneous definition of post and // infix operators need to be applied. if ( opSymbol . isPostfix ( ) ) { // Postfix, so check if an infix definition already exists, which is not allowed. if ( operatorMap . containsKey ( OpSymbol . Fixity . In ) ) { throw new IllegalArgumentException ( \"Cannot define a postfix operator when an infix one with the same name already exists.\" ) ; } } else if ( opSymbol . isInfix ( ) ) { // Infix, so check if a postfix definition already exists, which is not allowed. if ( operatorMap . containsKey ( OpSymbol . Fixity . Post ) ) { throw new IllegalArgumentException ( \"Cannot define an infix operator when an postfix one with the same name already exists.\" ) ; } } // Add the operator to the table replacing any previous definition of the same fixity. operatorMap . put ( opSymbol . getFixity ( ) , opSymbol ) ; } else { // The priority is zero, in which case the operator is to be removed. if ( ( operatorMap != null ) && opSymbol . isPrefix ( ) ) { // Remove it from the prefix table, if it exists there. operatorMap . remove ( OpSymbol . Fixity . Pre ) ; } else if ( ( operatorMap != null ) && ( opSymbol . isPostfix ( ) || opSymbol . isInfix ( ) ) ) { // Remove it from the postfix/infix table, if it exists there. operatorMap . remove ( OpSymbol . Fixity . Post ) ; operatorMap . remove ( OpSymbol . Fixity . In ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the operator table for all possible operators matching a given name . [CODESPLIT] public EnumMap < OpSymbol . Fixity , OpSymbol > getOperatorsMatchingNameByFixity ( String name ) { return operators . get ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if a candidate operator symbol can have one of the specified fixities and resolve it to an oeprator with that fixity if so . If it cannot be resolved an exception is raised . [CODESPLIT] protected static OpSymbol checkAndResolveToFixity ( CandidateOpSymbol candidate , OpSymbol . Fixity ... fixities ) throws SourceCodeException { OpSymbol result = null ; for ( OpSymbol . Fixity fixity : fixities ) { result = candidate . getPossibleOperators ( ) . get ( fixity ) ; if ( result != null ) { break ; } } if ( result == null ) { throw new SourceCodeException ( \"Operator \" + candidate + \" must be one of \" + Arrays . toString ( fixities ) + \", but does not have the required form.\" , null , null , null , candidate . getSourceCodePosition ( ) ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expands a node into its successors . The successors are added to the specified collection which is returned as the result of this function . The reason that the collection is passed as an argument is that there are many different styles of buffer ( fifo lifo etc ) that search functions can use to implement different kinds of search and it is more efficient to expand directly into the buffer than to have to copy the results into it after this method is called which would be the case if this method returned a collection . [CODESPLIT] public int expandSuccessors ( Queue < SearchNode < O , T > > expandInto , boolean reverse ) throws SearchNotExhaustiveException { // Used to keep count of the number of successors. int numSuccessors = 0 ; for ( Iterator < Successor < O > > successors = getState ( ) . successors ( reverse ) ; successors . hasNext ( ) ; ) { numSuccessors ++ ; // Get the next successor state Successor < O > next = successors . next ( ) ; // Check if a repeated state filter is to be applied if ( repeatedStateFilter != null ) { // Filter the successor state and check if it should be accepted if ( repeatedStateFilter . evaluate ( ( T ) next . getState ( ) , this ) ) { // Add the filtered state to the successors expandInto . offer ( makeNode ( next ) ) ; } } // No repeated state filter is to be applied so add the successor state else { expandInto . offer ( makeNode ( next ) ) ; } } // Successors have been expanded. expanded = true ; return numSuccessors ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a new node of the same type as this one from a Successor state . [CODESPLIT] public SearchNode < O , T > makeNode ( Successor successor ) throws SearchNotExhaustiveException { SearchNode newNode ; try { // Create a new instance of this class newNode = getClass ( ) . newInstance ( ) ; // Set the state, operation, parent, depth and cost for the new search node newNode . state = successor . getState ( ) ; newNode . parent = this ; newNode . appliedOp = successor . getOperator ( ) ; newNode . depth = depth + 1 ; newNode . pathCost = pathCost + successor . getCost ( ) ; // Check if there is a repeated state filter and copy the reference to it into the new node if so if ( repeatedStateFilter != null ) { newNode . setRepeatedStateFilter ( repeatedStateFilter ) ; } return newNode ; } catch ( InstantiationException e ) { // In practice this should never happen but may if the nodes if some class loader error were to occur whilst // using a custom node implementation. Rethrow this as a RuntimeException. throw new IllegalStateException ( \"InstantiationException during creation of new search node.\" , e ) ; } catch ( IllegalAccessException e ) { // In practice this should never happen but may if the nodes to use are not public whilst using a custom node // implementation. Rethrow this as a RuntimeException. throw new IllegalStateException ( \"IllegalAccessException during creation of new search node.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the specified byte <code > b< / code > to this output stream . [CODESPLIT] public void write ( int b ) throws IOException { try { sink . write ( b ) ; } catch ( RemoteException e ) { throw new IOException ( \"There was a Remote Exception.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes bytes from the specified byte array <code > b< / code > starting from index specified by <code > off< / code > and continuing for <code > len< / code > bytes to this output stream . [CODESPLIT] public void write ( byte [ ] b , int off , int len ) throws IOException { try { sink . write ( b , off , len ) ; } catch ( RemoteException e ) { throw new IOException ( \"There was a Remote Exception.\" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Right pads a string with a given string to a given size . This method will repeat the padder string as many times as is necessary until the exact specified size is reached . If the specified size is less than the size of the original string then the original string is returned unchanged . [CODESPLIT] public static String rightPad ( String stringToPad , String padder , int size ) { if ( padder . length ( ) == 0 ) { return stringToPad ; } StringBuffer strb = new StringBuffer ( stringToPad ) ; CharacterIterator sci = new StringCharacterIterator ( padder ) ; while ( strb . length ( ) < size ) { for ( char ch = sci . first ( ) ; ch != CharacterIterator . DONE ; ch = sci . next ( ) ) { if ( strb . length ( ) < size ) { strb . append ( String . valueOf ( ch ) ) ; } } } return strb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists all the parsing errors from the most recent parsing in a string . [CODESPLIT] public String getErrors ( ) { // Return the empty string if there are no errors. if ( parsingErrors . isEmpty ( ) ) { return \"\" ; } // Concatenate all the parsing errors together. String result = \"\" ; for ( String s : parsingErrors ) { result += s ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet . [CODESPLIT] public String getOptionsInForce ( ) { // Check if there are no properties to report and return and empty string if so. if ( parsedProperties == null ) { return \"\" ; } // List all the properties. String result = \"Options in force:\\n\" ; for ( Map . Entry < Object , Object > property : parsedProperties . entrySet ( ) ) { result += property . getKey ( ) + \" = \" + property . getValue ( ) + \"\\n\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a usage string consisting of the name of each option and each options argument description and comment . [CODESPLIT] public String getUsage ( ) { String result = \"Options:\\n\" ; int optionWidth = 0 ; int argumentWidth = 0 ; // Calculate the column widths required for aligned layout. for ( CommandLineOption optionInfo : optionMap . values ( ) ) { int oWidth = optionInfo . option . length ( ) ; int aWidth = ( optionInfo . argument != null ) ? ( optionInfo . argument . length ( ) ) : 0 ; optionWidth = ( oWidth > optionWidth ) ? oWidth : optionWidth ; argumentWidth = ( aWidth > argumentWidth ) ? aWidth : argumentWidth ; } // Print usage on each of the command line options. for ( CommandLineOption optionInfo : optionMap . values ( ) ) { String argString = ( ( optionInfo . argument != null ) ? ( optionInfo . argument ) : \"\" ) ; String optionString = optionInfo . option ; argString = rightPad ( argString , \" \" , argumentWidth ) ; optionString = rightPad ( optionString , \" \" , optionWidth ) ; result += \"-\" + optionString + \" \" + argString + \" \" + optionInfo . comment + \"\\n\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a set of command line arguments into a set of properties keyed by the argument flag . The free arguments are keyed by integers as strings starting at 1 and then 2 ... and so on . [CODESPLIT] public Properties parseCommandLine ( String [ ] args ) throws IllegalArgumentException { Properties options = new Properties ( ) ; // Used to keep count of the current 'free' argument. int free = 1 ; // Used to indicate that the most recently parsed option is expecting arguments. boolean expectingArgs = false ; // The option that is expecting arguments from the next element of the command line. String optionExpectingArgs = null ; // Used to indicate that the most recently parsed option is a duplicate and should be ignored. // boolean ignore = false; // Create the regular expression matcher for the command line options. String regexp = \"^(\" ; int optionsAdded = 0 ; for ( Iterator < String > i = optionMap . keySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { String nextOption = i . next ( ) ; // Check that the option is not a free argument definition. boolean notFree = false ; try { Integer . parseInt ( nextOption ) ; } catch ( NumberFormatException e ) { notFree = true ; } // Add the option to the regular expression matcher if it is not a free argument definition. if ( notFree ) { regexp += nextOption + ( i . hasNext ( ) ? \"|\" : \"\" ) ; optionsAdded ++ ; } } // There has to be more that one option in the regular expression or else the compiler complains that the close // cannot be nullable if the '?' token is used to make the matched option string optional. regexp += \")\" + ( ( optionsAdded > 0 ) ? \"?\" : \"\" ) + \"(.*)\" ; Pattern pattern = Pattern . compile ( regexp ) ; // Loop through all the command line arguments. for ( String arg1 : args ) { // Check if the next command line argument begins with a '-' character and is therefore the start of // an option. if ( arg1 . startsWith ( \"-\" ) ) { // Extract the value of the option without the leading '-'. String arg = arg1 . substring ( 1 ) ; // Match up to the longest matching option. optionMatcher = pattern . matcher ( arg ) ; optionMatcher . matches ( ) ; String matchedOption = optionMatcher . group ( 1 ) ; // Match any argument directly appended onto the longest matching option. String matchedArg = optionMatcher . group ( 2 ) ; // Check that a known option was matched. if ( ( matchedOption != null ) && ! \"\" . equals ( matchedOption ) ) { // Get the command line option information for the matched option. CommandLineOption optionInfo = optionMap . get ( matchedOption ) ; // Check if this option is expecting arguments. if ( optionInfo . expectsArgs ) { // The option is expecting arguments so swallow the next command line argument as an // argument to this option. expectingArgs = true ; optionExpectingArgs = matchedOption ; // In the mean time set this options argument to the empty string in case no argument is ever // supplied. // options.put(matchedOption, \"\"); } // Check if the option was matched on its own and is a flag in which case set that flag. if ( \"\" . equals ( matchedArg ) && ! optionInfo . expectsArgs ) { options . put ( matchedOption , \"true\" ) ; } // The option was matched as a substring with its argument appended to it or is a flag that is // condensed together with other flags. else if ( ! \"\" . equals ( matchedArg ) ) { // Check if the option is a flag and therefore is allowed to be condensed together // with other flags. if ( ! optionInfo . expectsArgs ) { // Set the first matched flag. options . put ( matchedOption , \"true\" ) ; // Repeat the longest matching process on the remainder but ensure that the remainder // consists only of flags as only flags may be condensed together in this fashion. do { // Match the remainder against the options. optionMatcher = pattern . matcher ( matchedArg ) ; optionMatcher . matches ( ) ; matchedOption = optionMatcher . group ( 1 ) ; matchedArg = optionMatcher . group ( 2 ) ; // Check that an option was matched. if ( matchedOption != null ) { // Get the command line option information for the next matched option. optionInfo = optionMap . get ( matchedOption ) ; // Ensure that the next option is a flag or raise an error if not. if ( optionInfo . expectsArgs ) { parsingErrors . add ( \"Option \" + matchedOption + \" cannot be combined with flags.\\n\" ) ; } options . put ( matchedOption , \"true\" ) ; } // The remainder could not be matched against a flag it is either an unknown flag // or an illegal argument to a flag. else { parsingErrors . add ( \"Illegal argument to a flag in the option \" + arg + \"\\n\" ) ; break ; } } // Continue until the remainder of the argument has all been matched with flags. while ( ! \"\" . equals ( matchedArg ) ) ; } // The option is expecting an argument, so store the unmatched portion against it // as its argument. else { // Check the arguments format is correct against any specified format. checkArgumentFormat ( optionInfo , matchedArg ) ; // Store the argument against its option (regardless of its format). options . put ( matchedOption , matchedArg ) ; // The argument to this flag has already been supplied to it. Do not swallow the // next command line argument as an argument to this flag. expectingArgs = false ; } } } else // No matching option was found. { // Add this to the list of parsing errors if errors on unkowns is being used. if ( errorsOnUnknowns ) { parsingErrors . add ( \"Option \" + matchedOption + \" is not a recognized option.\\n\" ) ; } } } // The command line argument did not being with a '-' so it is an argument to the previous flag or it // is a free argument. else { // Check if a previous flag is expecting to swallow this next argument as its argument. if ( expectingArgs ) { // Get the option info for the option waiting for arguments. CommandLineOption optionInfo = optionMap . get ( optionExpectingArgs ) ; // Check the arguments format is correct against any specified format. checkArgumentFormat ( optionInfo , arg1 ) ; // Store the argument against its option (regardless of its format). options . put ( optionExpectingArgs , arg1 ) ; // Clear the expecting args flag now that the argument has been swallowed. expectingArgs = false ; optionExpectingArgs = null ; } // This command line option is not an argument to any option. Add it to the set of 'free' options. else { // Get the option info for the free option, if there is any. CommandLineOption optionInfo = optionMap . get ( Integer . toString ( free ) ) ; if ( optionInfo != null ) { // Check the arguments format is correct against any specified format. checkArgumentFormat ( optionInfo , arg1 ) ; } // Add to the list of free options. options . put ( Integer . toString ( free ) , arg1 ) ; // Move on to the next free argument. free ++ ; } } } // Scan through all the specified options to check that all mandatory options have been set and that all flags // that were not set are set to false in the set of properties. for ( CommandLineOption optionInfo : optionMap . values ( ) ) { // Check if this is a flag. if ( ! optionInfo . expectsArgs ) { // Check if the flag is not set in the properties and set it to false if so. if ( ! options . containsKey ( optionInfo . option ) ) { options . put ( optionInfo . option , \"false\" ) ; } } // Check if this is a mandatory option and was not set. else if ( optionInfo . mandatory && ! options . containsKey ( optionInfo . option ) ) { // Create an error for the missing option. parsingErrors . add ( \"Option \" + optionInfo . option + \" is mandatory but not was not specified.\\n\" ) ; } } // Check if there were any errors. if ( ! parsingErrors . isEmpty ( ) ) { // Throw an illegal argument exception to signify that there were parsing errors. throw new IllegalArgumentException ( ) ; } // Convert any name/value pairs in the free arguments into properties in the parsed options. trailingProperties = takeFreeArgsAsProperties ( options , 1 ) ; parsedProperties = options ; return options ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a command line has been parsed calling this method sets all of its free arguments that were name = value pairs on the specified properties . [CODESPLIT] public void addTrailingPairsToProperties ( Properties properties ) { if ( trailingProperties != null ) { for ( Object propKey : trailingProperties . keySet ( ) ) { String name = ( String ) propKey ; String value = trailingProperties . getProperty ( name ) ; properties . setProperty ( name , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "If a command line has been parsed calling this method sets all of its options that were set to the specified properties . [CODESPLIT] public void addOptionsToProperties ( Properties properties ) { if ( parsedProperties != null ) { for ( Object propKey : parsedProperties . keySet ( ) ) { String name = ( String ) propKey ; String value = parsedProperties . getProperty ( name ) ; // This filters out all trailing items. if ( ! name . matches ( \"^[0-9]+$\" ) ) { properties . setProperty ( name , value ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds the option to list of available command line options . [CODESPLIT] protected void addOption ( String option , String comment , String argument , boolean mandatory , String formatRegexp ) { // Check if usage text has been set in which case this option is expecting arguments. boolean expectsArgs = ( ! ( ( argument == null ) || \"\" . equals ( argument ) ) ) ; // Add the option to the map of command line options. CommandLineOption opt = new CommandLineOption ( option , expectsArgs , comment , argument , mandatory , formatRegexp ) ; optionMap . put ( option , opt ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the free arguments into property declarations . After parsing the command line the free arguments are numbered from 1 such that the parsed properties contain values for the keys 1 2 ... This method converts any free arguments declared using the name = value syntax into properties with key name value value . [CODESPLIT] private Properties takeFreeArgsAsProperties ( Properties properties , int from ) { Properties result = new Properties ( ) ; for ( int i = from ; true ; i ++ ) { String nextFreeArg = properties . getProperty ( Integer . toString ( i ) ) ; // Terminate the loop once all free arguments have been consumed. if ( nextFreeArg == null ) { break ; } // Split it on the =, strip any whitespace and set it as a system property. String [ ] nameValuePair = nextFreeArg . split ( \"=\" ) ; if ( nameValuePair . length == 2 ) { result . setProperty ( nameValuePair [ 0 ] , nameValuePair [ 1 ] ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the format of an argument to an option against its specified regular expression format if one has been set . Any errors are added to the list of parsing errors . [CODESPLIT] private void checkArgumentFormat ( CommandLineOption optionInfo , CharSequence matchedArg ) { // Check if this option enforces a format for its argument. if ( optionInfo . argumentFormatRegexp != null ) { Pattern pattern = Pattern . compile ( optionInfo . argumentFormatRegexp ) ; Matcher argumentMatcher = pattern . matcher ( matchedArg ) ; // Check if the argument does not meet its required format. if ( ! argumentMatcher . matches ( ) ) { // Create an error for this badly formed argument. parsingErrors . add ( \"The argument to option \" + optionInfo . option + \" does not meet its required format.\\n\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Walks down two iterators comparing them element by element using the equals method . [CODESPLIT] public static < T , U > String compareIterators ( Iterator < U > iterator , Iterator < T > expectedIterator , Function < U , T > mapping ) { String errorMessage = \"\" ; while ( iterator . hasNext ( ) ) { U next = iterator . next ( ) ; T nextMapped = mapping . apply ( next ) ; T nextExpected = expectedIterator . next ( ) ; if ( ! nextMapped . equals ( nextExpected ) ) { errorMessage += \"Expecting \" + nextExpected + \" but got \" + nextMapped ; } } return errorMessage ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an enumeration describing the available options . [CODESPLIT] public Enumeration listOptions ( ) { Vector < Option > result ; String desc ; SelectedTag tag ; int i ; result = new Vector < Option > ( ) ; desc = \"\" ; for ( i = 0 ; i < TAGS_STEMMERS . length ; i ++ ) { tag = new SelectedTag ( TAGS_STEMMERS [ i ] . getID ( ) , TAGS_STEMMERS ) ; desc += \"\\t\" + tag . getSelectedTag ( ) . getIDStr ( ) + \" = \" + tag . getSelectedTag ( ) . getReadable ( ) + \"\\n\" ; } result . addElement ( new Option ( \"\\tThe type of stemmer algorithm to use:\\n\" + desc + \"\\t(default: \" + new SelectedTag ( STEMMER_ORENGO , TAGS_STEMMERS ) + \")\" , \"S\" , 1 , \"-S \" + Tag . toOptionList ( TAGS_STEMMERS ) ) ) ; result . addElement ( new Option ( \"\\tThe file with the named entities to ignore (optional).\\n\" + \"\\tFile format: simple text file with one entity per line.\\n\" + \"\\t(default: none)\\n\" , \"N\" , 1 , \"-N <file>\" ) ) ; result . addElement ( new Option ( \"\\tThe file with the stopwords (optional).\\n\" + \"\\tFile format: simple text file with one stopword per line.\\n\" + \"\\t(default: none)\\n\" , \"W\" , 1 , \"-W <file>\" ) ) ; result . addElement ( new Option ( \"\\tThe size of the cache. Disable with 0.\\n\" + \"\\t(default: 1000)\\n\" , \"C\" , 1 , \"-C <int>\" ) ) ; return result . elements ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the options . <p / > [CODESPLIT] public void setOptions ( String [ ] options ) throws Exception { String tmpStr ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setStemmer ( new SelectedTag ( tmpStr , TAGS_STEMMERS ) ) ; else setStemmer ( new SelectedTag ( STEMMER_ORENGO , TAGS_STEMMERS ) ) ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setNamedEntities ( new File ( tmpStr ) ) ; else setNamedEntities ( new File ( \".\" ) ) ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setStopwords ( new File ( tmpStr ) ) ; else setStopwords ( new File ( \".\" ) ) ; tmpStr = Utils . getOption ( ' ' , options ) ; if ( tmpStr . length ( ) != 0 ) setCache ( Integer . parseInt ( tmpStr ) ) ; else setCache ( 1000 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the current settings of the classifier . [CODESPLIT] public String [ ] getOptions ( ) { Vector < String > result ; result = new Vector < String > ( ) ; result . add ( \"-S\" ) ; result . add ( \"\" + getStemmer ( ) ) ; result . add ( \"-N\" ) ; result . add ( \"\" + getNamedEntities ( ) ) ; result . add ( \"-W\" ) ; result . add ( \"\" + getStopwords ( ) ) ; result . add ( \"-C\" ) ; result . add ( \"\" + getCache ( ) ) ; return result . toArray ( new String [ result . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the stemmer type to use [CODESPLIT] public void setStemmer ( SelectedTag value ) { if ( value . getTags ( ) == TAGS_STEMMERS ) { m_Stemmer = value . getSelectedTag ( ) . getID ( ) ; invalidate ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stemmer to use . [CODESPLIT] protected synchronized ptstemmer . Stemmer getActualStemmer ( ) throws PTStemmerException { if ( m_ActualStemmer == null ) { // stemmer algorithm if ( m_Stemmer == STEMMER_ORENGO ) m_ActualStemmer = new OrengoStemmer ( ) ; else if ( m_Stemmer == STEMMER_PORTER ) m_ActualStemmer = new PorterStemmer ( ) ; else if ( m_Stemmer == STEMMER_SAVOY ) m_ActualStemmer = new SavoyStemmer ( ) ; else throw new IllegalStateException ( \"Unhandled stemmer type: \" + m_Stemmer ) ; // named entities if ( ! m_NamedEntities . isDirectory ( ) ) m_ActualStemmer . ignore ( PTStemmerUtilities . fileToSet ( m_NamedEntities . getAbsolutePath ( ) ) ) ; // stopwords if ( ! m_Stopwords . isDirectory ( ) ) m_ActualStemmer . ignore ( PTStemmerUtilities . fileToSet ( m_Stopwords . getAbsolutePath ( ) ) ) ; // cache if ( m_Cache > 0 ) m_ActualStemmer . enableCaching ( m_Cache ) ; else m_ActualStemmer . disableCaching ( ) ; } return m_ActualStemmer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the stemmed version of the given word . Word is converted to lower case before stemming . [CODESPLIT] public String stem ( String word ) { String ret = null ; try { ret = getActualStemmer ( ) . getWordStem ( word ) ; } catch ( PTStemmerException e ) { e . printStackTrace ( ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the stemmer with the given options . [CODESPLIT] public static void main ( String [ ] args ) { try { Stemming . useStemmer ( new PTStemmer ( ) , args ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates a term by invoking its { @link Term#getValue () } method ( which may cause a recursive evaluation for example in the case of arithmetic expressions ) and checks that the result is a fully instantiated numeric value . [CODESPLIT] static NumericType evaluateAsNumeric ( Term numeric ) { // Evaluate the expression. Term expressionValue = numeric . getValue ( ) ; // Ensure that the result of evaluating the expression is a number. if ( expressionValue . isVar ( ) ) { throw new IllegalStateException ( \"instantiation_error, 'is' expects a fully instantiated term to unify against.\" ) ; } if ( ! expressionValue . isNumber ( ) ) { throw new IllegalStateException ( \"arithmetic_error, 'is' expectes a numeric expression to unify against.\" ) ; } return ( NumericType ) expressionValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new float range type with the specified name if it does not already exist . [CODESPLIT] public static Type createInstance ( String name , float min , float max ) { // Ensure that min is less than or equal to max. if ( min > max ) { throw new IllegalArgumentException ( \"'min' must be less than or equal to 'max'.\" ) ; } synchronized ( FLOAT_RANGE_TYPES ) { // Add the newly created type to the map of all types. FloatRangeType newType = new FloatRangeType ( name , min , max ) ; // Ensure that the named type does not already exist, unless it has an identical definition already, in which // case the old definition can be re-used and the new one discarded. FloatRangeType oldType = FLOAT_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( \"The type '\" + name + \"' already exists and cannot be redefined.\" ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { FLOAT_RANGE_TYPES . put ( name , newType ) ; return newType ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the state of the work panel . State must be one of the defined constants : NOT_INITIALIZED READY or NOT_SAVED . [CODESPLIT] public void setState ( String state ) { /*log.fine(\"void setState(String): called\");*/ /*log.fine(\"state is \" + state);*/ // Check if the state has changed if ( ! this . state . equals ( state ) ) { String oldState = this . state ; // Keep the new state this . state = state ; // Notify any listeners of the change in state firePropertyChange ( new PropertyChangeEvent ( this , \"state\" , oldState , state ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the machine to its initial state . This clears any programs from the machine and clears all of its stacks and heaps . [CODESPLIT] public void reset ( ) { // Create fresh heaps, code areas and stacks. data = ByteBuffer . allocateDirect ( TOP << 2 ) . order ( ByteOrder . LITTLE_ENDIAN ) . asIntBuffer ( ) ; codeBuffer = ByteBuffer . allocateDirect ( CODE_SIZE ) ; codeBuffer . order ( ByteOrder . LITTLE_ENDIAN ) ; // Registers are on the top of the data area, the heap comes next. hp = HEAP_BASE ; hbp = HEAP_BASE ; sp = HEAP_BASE ; // The stack comes after the heap. Pointers are zero initially, since no stack frames exist yet. ep = 0 ; bp = 0 ; b0 = 0 ; // The trail comes after the stack. trp = TRAIL_BASE ; // The unification stack (PDL) is a push down stack at the end of the data area. up = TOP ; // Turn off write mode. writeMode = false ; // Reset the instruction pointer to that start of the code area, ready for fresh code to be loaded there. ip = 0 ; // Could probably not bother resetting these, but will do it anyway just to be sure. derefTag = 0 ; derefVal = 0 ; // The machine is initially not suspended. suspended = false ; // Ensure that the overridden reset method of WAMBaseMachine is run too, to clear the call table. super . reset ( ) ; // Put the internal functions in the call table. setInternalCodeAddress ( internFunctorName ( \"call\" , 1 ) , CALL_1_ID ) ; setInternalCodeAddress ( internFunctorName ( \"execute\" , 1 ) , EXECUTE_1_ID ) ; // Notify any debug monitor that the machine has been reset. if ( monitor != null ) { monitor . onReset ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public WAMInternalRegisters getInternalRegisters ( ) { return new WAMInternalRegisters ( ip , hp , hbp , sp , up , ep , bp , b0 , trp , writeMode ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public WAMMemoryLayout getMemoryLayout ( ) { return new WAMMemoryLayout ( 0 , REG_SIZE , HEAP_BASE , HEAP_SIZE , STACK_BASE , STACK_SIZE , TRAIL_BASE , TRAIL_SIZE , TOP - PDL_SIZE , PDL_SIZE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected boolean execute ( WAMCallPoint callPoint ) { /*log.fine(\"protected boolean execute(WAMCallPoint callPoint): called\");*/ boolean failed ; // Check if the machine is being woken up from being suspended, in which case immediately fail in order to // trigger back-tracking to find more solutions. if ( suspended ) { failed = true ; suspended = false ; } else { ip = callPoint . entryPoint ; uClear ( ) ; failed = false ; } int numOfArgs = 0 ; // Holds the current continuation point. cp = codeBuffer . position ( ) ; // Notify any debug monitor that execution is starting. if ( monitor != null ) { monitor . onExecute ( this ) ; } //while (!failed && (ip < code.length)) while ( true ) { // Attempt to backtrack on failure. if ( failed ) { failed = backtrack ( ) ; if ( failed ) { break ; } } // Grab next instruction and switch on it. byte instruction = codeBuffer . get ( ip ) ; switch ( instruction ) { // put_struc Xi, f/n: case PUT_STRUC : { // grab addr, f/n byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /*trace.fine(ip + \": PUT_STRUC \" + printSlot(xi, mode) + \", \" + fn);*/ // heap[h] <- STR, h + 1 data . put ( hp , fn ) ; // Xi <- heap[h] data . put ( xi , structureAt ( hp ) ) ; // h <- h + 2 hp += 1 ; // P <- instruction_size(P) ip += 7 ; break ; } // set_var Xi: case SET_VAR : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": SET_VAR \" + printSlot(xi, mode));*/ // heap[h] <- REF, h data . put ( hp , refTo ( hp ) ) ; // Xi <- heap[h] data . put ( xi , data . get ( hp ) ) ; // h <- h + 1 hp ++ ; // P <- instruction_size(P) ip += 3 ; break ; } // set_val Xi: case SET_VAL : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": SET_VAL \" + printSlot(xi, mode));*/ // heap[h] <- Xi data . put ( hp , data . get ( xi ) ) ; // h <- h + 1 hp ++ ; // P <- instruction_size(P) ip += 3 ; break ; } // get_struc Xi, case GET_STRUC : { // grab addr, f/n byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /*trace.fine(ip + \": GET_STRUC \" + printSlot(xi, mode) + \", \" + fn);*/ // addr <- deref(Xi); int addr = deref ( xi ) ; byte tag = derefTag ; int a = derefVal ; // switch STORE[addr] switch ( tag ) { // case REF: case REF : { // heap[h] <- STR, h + 1 data . put ( hp , structureAt ( hp + 1 ) ) ; // heap[h+1] <- f/n data . put ( hp + 1 , fn ) ; // bind(addr, h) bind ( addr , hp ) ; // h <- h + 2 hp += 2 ; // mode <- write writeMode = true ; /*trace.fine(\"-> write mode\");*/ break ; } // case STR, a: case STR : { // if heap[a] = f/n if ( data . get ( a ) == fn ) { // s <- a + 1 sp = a + 1 ; // mode <- read writeMode = false ; /*trace.fine(\"-> read mode\");*/ } else { // fail failed = true ; } break ; } default : { // fail failed = true ; } } // P <- instruction_size(P) ip += 7 ; break ; } // unify_var Xi: case UNIFY_VAR : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": UNIFY_VAR \" + printSlot(xi, mode));*/ // switch mode if ( ! writeMode ) { // case read: // Xi <- heap[s] data . put ( xi , data . get ( sp ) ) ; } else { // case write: // heap[h] <- REF, h data . put ( hp , refTo ( hp ) ) ; // Xi <- heap[h] data . put ( xi , data . get ( hp ) ) ; // h <- h + 1 hp ++ ; } // s <- s + 1 sp ++ ; // P <- P + instruction_size(P) ip += 3 ; break ; } // unify_val Xi: case UNIFY_VAL : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": UNIFY_VAL \" + printSlot(xi, mode));*/ // switch mode if ( ! writeMode ) { // case read: // unify (Xi, s) failed = ! unify ( xi , sp ) ; } else { // case write: // heap[h] <- Xi data . put ( hp , data . get ( xi ) ) ; // h <- h + 1 hp ++ ; } // s <- s + 1 sp ++ ; // P <- P + instruction_size(P) ip += 3 ; break ; } // put_var Xn, Ai: case PUT_VAR : { // grab addr, Ai byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /*trace.fine(ip + \": PUT_VAR \" + printSlot(xi, mode) + \", A\" + ai);*/ if ( mode == WAMInstruction . REG_ADDR ) { // heap[h] <- REF, H data . put ( hp , refTo ( hp ) ) ; // Xn <- heap[h] data . put ( xi , data . get ( hp ) ) ; // Ai <- heap[h] data . put ( ai , data . get ( hp ) ) ; } else { // STACK[addr] <- REF, addr data . put ( xi , refTo ( xi ) ) ; // Ai <- STACK[addr] data . put ( ai , data . get ( xi ) ) ; } // h <- h + 1 hp ++ ; // P <- P + instruction_size(P) ip += 4 ; break ; } // put_val Xn, Ai: case PUT_VAL : { // grab addr, Ai byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /*trace.fine(ip + \": PUT_VAL \" + printSlot(xi, mode) + \", A\" + ai);*/ // Ai <- Xn data . put ( ai , data . get ( xi ) ) ; // P <- P + instruction_size(P) ip += 4 ; break ; } // get var Xn, Ai: case GET_VAR : { // grab addr, Ai byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /*trace.fine(ip + \": GET_VAR \" + printSlot(xi, mode) + \", A\" + ai);*/ // Xn <- Ai data . put ( xi , data . get ( ai ) ) ; // P <- P + instruction_size(P) ip += 4 ; break ; } // get_val Xn, Ai: case GET_VAL : { // grab addr, Ai byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /*trace.fine(ip + \": GET_VAL \" + printSlot(xi, mode) + \", A\" + ai);*/ // unify (Xn, Ai) failed = ! unify ( xi , ai ) ; // P <- P + instruction_size(P) ip += 4 ; break ; } case PUT_CONST : { // grab addr, f/n byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /*trace.fine(ip + \": PUT_CONST \" + printSlot(xi, mode) + \", \" + fn);*/ // Xi <- heap[h] data . put ( xi , constantCell ( fn ) ) ; // P <- instruction_size(P) ip += 7 ; break ; } case GET_CONST : { // grab addr, Ai byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; int fn = codeBuffer . getInt ( ip + 3 ) ; /*trace.fine(ip + \": GET_CONST \" + printSlot(xi, mode) + \", \" + fn);*/ // addr <- deref(Xi) int addr = deref ( xi ) ; int tag = derefTag ; int val = derefVal ; failed = ! unifyConst ( fn , xi ) ; // P <- P + instruction_size(P) ip += 7 ; break ; } case SET_CONST : { int fn = codeBuffer . getInt ( ip + 1 ) ; /*trace.fine(ip + \": SET_CONST \" + fn);*/ // heap[h] <- <CON, c> data . put ( hp , constantCell ( fn ) ) ; // h <- h + 1 hp ++ ; // P <- instruction_size(P) ip += 5 ; break ; } case UNIFY_CONST : { int fn = codeBuffer . getInt ( ip + 1 ) ; /*trace.fine(ip + \": UNIFY_CONST \" + fn);*/ // switch mode if ( ! writeMode ) { // case read: // addr <- deref(S) // unifyConst(fn, addr) failed = ! unifyConst ( fn , sp ) ; } else { // case write: // heap[h] <- <CON, c> data . put ( hp , constantCell ( fn ) ) ; // h <- h + 1 hp ++ ; } // s <- s + 1 sp ++ ; // P <- P + instruction_size(P) ip += 5 ; break ; } case PUT_LIST : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": PUT_LIST \" + printSlot(xi, mode));*/ // Xi <- <LIS, H> data . put ( xi , listCell ( hp ) ) ; // P <- P + instruction_size(P) ip += 3 ; break ; } case GET_LIST : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": GET_LIST \" + printSlot(xi, mode));*/ int addr = deref ( xi ) ; int tag = derefTag ; int val = derefVal ; // case STORE[addr] of switch ( tag ) { case REF : { // <REF, _> : // HEAP[H] <- <LIS, H+1> data . put ( hp , listCell ( hp + 1 ) ) ; // bind(addr, H) bind ( addr , hp ) ; // H <- H + 1 hp += 1 ; // mode <- write writeMode = true ; /*trace.fine(\"-> write mode\");*/ break ; } case LIS : { // <LIS, a> : // S <- a sp = val ; // mode <- read writeMode = false ; /*trace.fine(\"-> read mode\");*/ break ; } default : { // other: fail <- true; failed = true ; } } // P <- P + instruction_size(P) ip += 3 ; break ; } case SET_VOID : { // grab N int n = ( int ) codeBuffer . get ( ip + 1 ) ; /*trace.fine(ip + \": SET_VOID \" + n);*/ // for i <- H to H + n - 1 do //  HEAP[i] <- <REF, i> for ( int addr = hp ; addr < ( hp + n ) ; addr ++ ) { data . put ( addr , refTo ( addr ) ) ; } // H <- H + n hp += n ; // P <- P + instruction_size(P) ip += 2 ; break ; } case UNIFY_VOID : { // grab N int n = ( int ) codeBuffer . get ( ip + 1 ) ; /*trace.fine(ip + \": UNIFY_VOID \" + n);*/ // case mode of if ( ! writeMode ) { //  read: S <- S + n sp += n ; } else { //  write: //   for i <- H to H + n -1 do //    HEAP[i] <- <REF, i> for ( int addr = hp ; addr < ( hp + n ) ; addr ++ ) { data . put ( addr , refTo ( addr ) ) ; } //   H <- H + n hp += n ; } // P <- P + instruction_size(P) ip += 2 ; break ; } // put_unsafe_val Yn, Ai: case PUT_UNSAFE_VAL : { // grab addr, Ai byte mode = codeBuffer . get ( ip + 1 ) ; int yi = ( int ) codeBuffer . get ( ip + 2 ) + ( ep + 3 ) ; byte ai = codeBuffer . get ( ip + 3 ) ; /*trace.fine(ip + \": PUT_UNSAFE_VAL \" + printSlot(yi, WAMInstruction.STACK_ADDR) + \", A\" + ai);*/ int addr = deref ( yi ) ; if ( addr < ep ) { // Ai <- Xn data . put ( ai , data . get ( addr ) ) ; } else { data . put ( hp , refTo ( hp ) ) ; bind ( addr , hp ) ; data . put ( ai , data . get ( hp ) ) ; hp ++ ; } // P <- P + instruction_size(P) ip += 4 ; break ; } // set_local_val Xi: case SET_LOCAL_VAL : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": SET_LOCAL_VAL \" + printSlot(xi, mode));*/ int addr = deref ( xi ) ; if ( addr < ep ) { data . put ( hp , data . get ( addr ) ) ; } else { data . put ( hp , refTo ( hp ) ) ; bind ( addr , hp ) ; } // h <- h + 1 hp ++ ; // P <- P + instruction_size(P) ip += 3 ; break ; } // unify_local_val Xi: case UNIFY_LOCAL_VAL : { // grab addr byte mode = codeBuffer . get ( ip + 1 ) ; int xi = getRegisterOrStackSlot ( mode ) ; /*trace.fine(ip + \": UNIFY_LOCAL_VAL \" + printSlot(xi, mode));*/ // switch mode if ( ! writeMode ) { // case read: // unify (Xi, s) failed = ! unify ( xi , sp ) ; } else { // case write: int addr = deref ( xi ) ; if ( addr < ep ) { data . put ( hp , data . get ( addr ) ) ; } else { data . put ( hp , refTo ( hp ) ) ; bind ( addr , hp ) ; } // h <- h + 1 hp ++ ; } // s <- s + 1 sp ++ ; // P <- P + instruction_size(P) ip += 3 ; break ; } // call @(p/n), perms: case CALL : { // grab @(p/n), perms int pn = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . get ( ip + 5 ) ; int numPerms = ( int ) codeBuffer . get ( ip + 6 ) ; // num_of_args <- n numOfArgs = n ; // Ensure that the predicate to call is known and linked in, otherwise fail. if ( pn == - 1 ) { failed = true ; break ; } // STACK[E + 2] <- numPerms data . put ( ep + 2 , numPerms ) ; // CP <- P + instruction_size(P) cp = ip + 7 ; /*trace.fine(ip + \": CALL \" + pn + \"/\" + n + \", \" + numPerms + \" (cp = \" + cp + \")]\");*/ // B0 <- B b0 = bp ; // P <- @(p/n) ip = pn ; break ; } // execute @(p/n): case EXECUTE : { // grab @(p/n) int pn = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . get ( ip + 5 ) ; // num_of_args <- n numOfArgs = n ; /*trace.fine(ip + \": EXECUTE \" + pn + \"/\" + n + \" (cp = \" + cp + \")]\");*/ // Ensure that the predicate to call is known and linked in, otherwise fail. if ( pn == - 1 ) { failed = true ; break ; } // B0 <- B b0 = bp ; // P <- @(p/n) ip = pn ; break ; } // proceed: case PROCEED : { /*trace.fine(ip + \": PROCEED\" + \" (cp = \" + cp + \")]\");*/ // P <- CP ip = cp ; break ; } // allocate: case ALLOCATE : { // if E > B //  then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame ( ) ; // STACK[newE] <- E data . put ( esp , ep ) ; // STACK[E + 1] <- CP data . put ( esp + 1 , cp ) ; // STACK[E + 2] <- N data . put ( esp + 2 , 0 ) ; // E <- newE // newE <- E + n + 3 ep = esp ; /*trace.fine(ip + \": ALLOCATE\");*/ /*trace.fine(\"-> env @ \" + ep + \" \" + traceEnvFrame());*/ // P <- P + instruction_size(P) ip += 1 ; break ; } // allocate N: case ALLOCATE_N : { // grab N int n = ( int ) codeBuffer . get ( ip + 1 ) ; // if E > B //  then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame ( ) ; // STACK[newE] <- E data . put ( esp , ep ) ; // STACK[E + 1] <- CP data . put ( esp + 1 , cp ) ; // STACK[E + 2] <- N data . put ( esp + 2 , n ) ; // E <- newE // newE <- E + n + 3 ep = esp ; /*trace.fine(ip + \": ALLOCATE_N \" + n);*/ /*trace.fine(\"-> env @ \" + ep + \" \" + traceEnvFrame());*/ // P <- P + instruction_size(P) ip += 2 ; break ; } // deallocate: case DEALLOCATE : { int newip = data . get ( ep + 1 ) ; // E <- STACK[E] ep = data . get ( ep ) ; /*trace.fine(ip + \": DEALLOCATE\");*/ /*trace.fine(\"<- env @ \" + ep + \" \" + traceEnvFrame());*/ // CP <- STACK[E + 1] cp = newip ; // P <- P + instruction_size(P) ip += 1 ; break ; } // try me else L: case TRY_ME_ELSE : { // grab L int l = codeBuffer . getInt ( ip + 1 ) ; // if E > B //  then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame ( ) ; // STACK[newB] <- num_of_args // n <- STACK[newB] int n = numOfArgs ; data . put ( esp , n ) ; // for i <- 1 to n do STACK[newB + i] <- Ai for ( int i = 0 ; i < n ; i ++ ) { data . put ( esp + i + 1 , data . get ( i ) ) ; } // STACK[newB + n + 1] <- E data . put ( esp + n + 1 , ep ) ; // STACK[newB + n + 2] <- CP data . put ( esp + n + 2 , cp ) ; // STACK[newB + n + 3] <- B data . put ( esp + n + 3 , bp ) ; // STACK[newB + n + 4] <- L data . put ( esp + n + 4 , l ) ; // STACK[newB + n + 5] <- TR data . put ( esp + n + 5 , trp ) ; // STACK[newB + n + 6] <- H data . put ( esp + n + 6 , hp ) ; // STACK[newB + n + 7] <- B0 data . put ( esp + n + 7 , b0 ) ; // B <- new B bp = esp ; // HB <- H hbp = hp ; /*trace.fine(ip + \": TRY_ME_ELSE\");*/ /*trace.fine(\"-> chp @ \" + bp + \" \" + traceChoiceFrame());*/ // P <- P + instruction_size(P) ip += 5 ; break ; } // retry me else L: case RETRY_ME_ELSE : { // grab L int l = codeBuffer . getInt ( ip + 1 ) ; // n <- STACK[B] int n = data . get ( bp ) ; // for i <- 1 to n do Ai <- STACK[B + i] for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E <- STACK[B + n + 1] ep = data . get ( bp + n + 1 ) ; // CP <- STACK[B + n + 2] cp = data . get ( bp + n + 2 ) ; // STACK[B + n + 4] <- L data . put ( bp + n + 4 , l ) ; // unwind_trail(STACK[B + n + 5], TR) unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR <- STACK[B + n + 5] trp = data . get ( bp + n + 5 ) ; // H <- STACK[B + n + 6] hp = data . get ( bp + n + 6 ) ; // HB <- H hbp = hp ; /*trace.fine(ip + \": RETRY_ME_ELSE\");*/ /*trace.fine(\"-- chp @ \" + bp + \" \" + traceChoiceFrame());*/ // P <- P + instruction_size(P) ip += 5 ; break ; } // trust me (else fail): case TRUST_ME : { // n <- STACK[B] int n = data . get ( bp ) ; // for i <- 1 to n do Ai <- STACK[B + i] for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E <- STACK[B + n + 1] ep = data . get ( bp + n + 1 ) ; // CP <- STACK[B + n + 2] cp = data . get ( bp + n + 2 ) ; // unwind_trail(STACK[B + n + 5], TR) unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR <- STACK[B + n + 5] trp = data . get ( bp + n + 5 ) ; // H <- STACK[B + n + 6] hp = data . get ( bp + n + 6 ) ; // HB <- STACK[B + n + 6] hbp = hp ; // B <- STACK[B + n + 3] bp = data . get ( bp + n + 3 ) ; /*trace.fine(ip + \": TRUST_ME\");*/ /*trace.fine(\"<- chp @ \" + bp + \" \" + traceChoiceFrame());*/ // P <- P + instruction_size(P) ip += 1 ; break ; } case SWITCH_ON_TERM : { // grab labels int v = codeBuffer . getInt ( ip + 1 ) ; int c = codeBuffer . getInt ( ip + 5 ) ; int l = codeBuffer . getInt ( ip + 9 ) ; int s = codeBuffer . getInt ( ip + 13 ) ; int addr = deref ( 1 ) ; int tag = derefTag ; // case STORE[deref(A1)] of switch ( tag ) { case REF : // <REF, _> : P <- V ip = v ; break ; case CON : // <CON, _> : P <- C ip = c ; break ; case LIS : // <LIS, _> : P <- L ip = l ; break ; case STR : // <STR, _> : P <- S ip = s ; break ; } break ; } case SWITCH_ON_CONST : { // grab labels int t = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . getInt ( ip + 5 ) ; // <tag, val> <- STORE[deref(A1)] deref ( 1 ) ; int val = derefVal ; // <found, inst> <- get_hash(val, T, N) int inst = getHash ( val , t , n ) ; // if found if ( inst > 0 ) { // then P <- inst ip = inst ; } else { // else backtrack failed = true ; } break ; } case SWITCH_ON_STRUC : { // grab labels int t = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . getInt ( ip + 5 ) ; // <tag, val> <- STORE[deref(A1)] deref ( 1 ) ; int val = derefVal ; // <found, inst> <- get_hash(val, T, N) int inst = getHash ( val , t , n ) ; // if found if ( inst > 0 ) { // then P <- inst ip = inst ; } else { // else backtrack failed = true ; } break ; } case TRY : { // grab L int l = codeBuffer . getInt ( ip + 1 ) ; // if E > B //  then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 int esp = nextStackFrame ( ) ; // STACK[newB] <- num_of_args // n <- STACK[newB] int n = numOfArgs ; data . put ( esp , n ) ; // for i <- 1 to n do STACK[newB + i] <- Ai for ( int i = 0 ; i < n ; i ++ ) { data . put ( esp + i + 1 , data . get ( i ) ) ; } // STACK[newB + n + 1] <- E data . put ( esp + n + 1 , ep ) ; // STACK[newB + n + 2] <- CP data . put ( esp + n + 2 , cp ) ; // STACK[newB + n + 3] <- B data . put ( esp + n + 3 , bp ) ; // STACK[newB + n + 4] <- L data . put ( esp + n + 4 , ip + 5 ) ; // STACK[newB + n + 5] <- TR data . put ( esp + n + 5 , trp ) ; // STACK[newB + n + 6] <- H data . put ( esp + n + 6 , hp ) ; // STACK[newB + n + 7] <- B0 data . put ( esp + n + 7 , b0 ) ; // B <- new B bp = esp ; // HB <- H hbp = hp ; /*trace.fine(ip + \": TRY\");*/ /*trace.fine(\"-> chp @ \" + bp + \" \" + traceChoiceFrame());*/ // P <- L ip = l ; break ; } case RETRY : { // grab L int l = codeBuffer . getInt ( ip + 1 ) ; // n <- STACK[B] int n = data . get ( bp ) ; // for i <- 1 to n do Ai <- STACK[B + i] for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E <- STACK[B + n + 1] ep = data . get ( bp + n + 1 ) ; // CP <- STACK[B + n + 2] cp = data . get ( bp + n + 2 ) ; // STACK[B + n + 4] <- L data . put ( bp + n + 4 , ip + 5 ) ; // unwind_trail(STACK[B + n + 5], TR) unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR <- STACK[B + n + 5] trp = data . get ( bp + n + 5 ) ; // H <- STACK[B + n + 6] hp = data . get ( bp + n + 6 ) ; // HB <- H hbp = hp ; /*trace.fine(ip + \": RETRY\");*/ /*trace.fine(\"-- chp @ \" + bp + \" \" + traceChoiceFrame());*/ // P <- L ip = l ; break ; } case TRUST : { // grab L int l = codeBuffer . getInt ( ip + 1 ) ; // n <- STACK[B] int n = data . get ( bp ) ; // for i <- 1 to n do Ai <- STACK[B + i] for ( int i = 0 ; i < n ; i ++ ) { data . put ( i , data . get ( bp + i + 1 ) ) ; } // E <- STACK[B + n + 1] ep = data . get ( bp + n + 1 ) ; // CP <- STACK[B + n + 2] cp = data . get ( bp + n + 2 ) ; // unwind_trail(STACK[B + n + 5], TR) unwindTrail ( data . get ( bp + n + 5 ) , trp ) ; // TR <- STACK[B + n + 5] trp = data . get ( bp + n + 5 ) ; // H <- STACK[B + n + 6] hp = data . get ( bp + n + 6 ) ; // HB <- STACK[B + n + 6] hbp = hp ; // B <- STACK[B + n + 3] bp = data . get ( bp + n + 3 ) ; /*trace.fine(ip + \": TRUST\");*/ /*trace.fine(\"<- chp @ \" + bp + \" \" + traceChoiceFrame());*/ // P <- L ip = l ; break ; } case NECK_CUT : { if ( bp > b0 ) { bp = b0 ; tidyTrail ( ) ; } /*trace.fine(ip + \": NECK_CUT\");*/ /*trace.fine(\"<- chp @ \" + bp + \" \" + traceChoiceFrame());*/ ip += 1 ; break ; } case GET_LEVEL : { int yn = ( int ) codeBuffer . get ( ip + 1 ) + ( ep + 3 ) ; data . put ( yn , b0 ) ; /*trace.fine(ip + \": GET_LEVEL \" + codeBuffer.get(ip + 1));*/ ip += 2 ; break ; } case CUT : { int yn = ( int ) codeBuffer . get ( ip + 1 ) + ( ep + 3 ) ; int cbp = data . get ( yn ) ; if ( bp > cbp ) { bp = cbp ; tidyTrail ( ) ; } /*trace.fine(ip + \": CUT \" + codeBuffer.get(ip + 1));*/ /*trace.fine(\"<- chp @ \" + bp + \" \" + traceChoiceFrame());*/ ip += 2 ; break ; } case CONTINUE : { // grab L int l = codeBuffer . getInt ( ip + 1 ) ; /*trace.fine(ip + \": CONTINUE \" + l);*/ ip = l ; break ; } case NO_OP : { /*trace.fine(ip + \": NO_OP\");*/ ip += 1 ; break ; } // call_internal @(p/n), perms: case CALL_INTERNAL : { // grab @(p/n), perms int pn = codeBuffer . getInt ( ip + 1 ) ; int n = codeBuffer . get ( ip + 5 ) ; int numPerms = ( int ) codeBuffer . get ( ip + 6 ) ; // num_of_args <- n numOfArgs = n ; /*trace.fine(ip + \": CALL_INTERNAL \" + pn + \"/\" + n + \", \" + numPerms + \" (cp = \" + cp + \")]\");*/ boolean callOk = callInternal ( pn , n , numPerms ) ; failed = ! callOk ; break ; } // suspend on success: case SUSPEND : { /*trace.fine(ip + \": SUSPEND\");*/ ip += 1 ; suspended = true ; return true ; } } // Notify any debug monitor that the machine has been stepped. if ( monitor != null ) { monitor . onStep ( this ) ; } } return ! failed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty prints the current environment frame for debugging purposes . [CODESPLIT] protected String traceEnvFrame ( ) { return \"env: [ ep = \" + data . get ( ep ) + \", cp = \" + data . get ( ep + 1 ) + \", n = \" + data . get ( ep + 2 ) + \"]\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty prints the current choice point frame for debugging purposes . [CODESPLIT] protected String traceChoiceFrame ( ) { if ( bp == 0 ) { return \"\" ; } int n = data . get ( bp ) ; return \"choice: [ n = \" + data . get ( bp ) + \", ep = \" + data . get ( bp + n + 1 ) + \", cp = \" + data . get ( bp + n + 2 ) + \", bp = \" + data . get ( bp + n + 3 ) + \", l = \" + data . get ( bp + n + 4 ) + \", trp = \" + data . get ( bp + n + 5 ) + \", hp = \" + data . get ( bp + n + 6 ) + \", b0 = \" + data . get ( bp + n + 7 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected int deref ( int a ) { // tag, value <- STORE[a] int addr = a ; int tmp = data . get ( a ) ; derefTag = ( byte ) ( tmp >>> TSHIFT ) ; derefVal = tmp & AMASK ; // while tag = REF and value != a while ( ( derefTag == WAMInstruction . REF ) ) { // tag, value <- STORE[a] addr = derefVal ; tmp = data . get ( derefVal ) ; derefTag = ( byte ) ( tmp >>> TSHIFT ) ; tmp = tmp & AMASK ; // Break on free var. if ( derefVal == tmp ) { break ; } derefVal = tmp ; } return addr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invokes an internal function . [CODESPLIT] private boolean callInternal ( int function , int arity , int numPerms ) { switch ( function ) { case CALL_1_ID : return internalCall_1 ( numPerms ) ; case EXECUTE_1_ID : return internalExecute_1 ( ) ; default : throw new IllegalStateException ( \"Unknown internal function id: \" + function ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements the call / 1 predicate . [CODESPLIT] private boolean internalCall_1 ( int numPerms ) { int pn = setupCall_1 ( ) ; if ( pn == - 1 ) { return false ; } // Make the call. // STACK[E + 2] <- numPerms data . put ( ep + 2 , numPerms ) ; // CP <- P + instruction_size(P) cp = ip + 7 ; /*trace.fine(ip + \": (CALL) \" + pn + \", \" + numPerms + \" (cp = \" + cp + \")]\");*/ // B0 <- B b0 = bp ; // P <- @(p/n) ip = pn ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Implements the execute variant of the call / 1 predicate . [CODESPLIT] private boolean internalExecute_1 ( ) { int pn = setupCall_1 ( ) ; if ( pn == - 1 ) { return false ; } // Make the call. /*trace.fine(ip + \": (EXECUTE) \" + pn + \" (cp = \" + cp + \")]\");*/ // B0 <- B b0 = bp ; // P <- @(p/n) ip = pn ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets up the registers to make a call for implementing call / 1 . The first register should reference a structure to be turned into a predicate call . The arguments of this structure will be set up in the registers and the entry point of the predicate to call will be returned . [CODESPLIT] private int setupCall_1 ( ) { // Get X0. int addr = deref ( 0 ) ; byte tag = derefTag ; int val = derefVal ; // Check it points to a structure. int fn ; if ( tag == STR ) { fn = getHeap ( val ) ; } else if ( tag == CON ) { fn = val ; } else { /*trace.fine(\"call/1 not invoked against structure.\");*/ return - 1 ; } // Look up the call point of the matching functor. int f = fn & 0x00ffffff ; WAMCallPoint callPoint = resolveCallPoint ( f ) ; if ( callPoint . entryPoint == - 1 ) { /*trace.fine(\"call/1 to unknown call point.\");*/ return - 1 ; } int pn = callPoint . entryPoint ; // Set registers X0... to ref to args... FunctorName functorName = getDeinternedFunctorName ( f ) ; int arity = functorName . getArity ( ) ; for ( int i = 0 ; i < arity ; i ++ ) { data . put ( i , refTo ( val + 1 + i ) ) ; } return pn ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Computes the start of the next stack frame . This depends on whether the most recent stack frame is an environment frame or a choice point frame as these have different sizes . The size of the most recent type of frame is computed and added to the current frame pointer to give the start of the next frame . [CODESPLIT] private int nextStackFrame ( ) { // if E > B // then newB <- E + STACK[E + 2] + 3 // else newB <- B + STACK[B] + 7 if ( ep == bp ) { return STACK_BASE ; } else if ( ep > bp ) { return ep + data . get ( ep + 2 ) + 3 ; } else { return bp + data . get ( bp ) + 8 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Backtracks to the continuation label stored in the current choice point frame if there is one . Otherwise returns a fail to indicate that there are no more choice points so no backtracking can be done . [CODESPLIT] private boolean backtrack ( ) { // if B = bottom_of_stack if ( bp == 0 ) { //  then fail_and_exit_program return true ; } else { // B0 <- STACK[B + STACK[B} + 7] b0 = data . get ( bp + data . get ( bp ) + 7 ) ; // P <- STACK[B + STACK[B] + 4] ip = data . get ( bp + data . get ( bp ) + 4 ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a binding of one variable onto another . One of the supplied addresses must be an unbound variable . If both are unbound variables the higher ( newer ) address is bound to the lower ( older ) one . [CODESPLIT] private void bind ( int a1 , int a2 ) { // <t1, _> <- STORE[a1] int t1 = ( byte ) ( data . get ( a1 ) >>> TSHIFT ) ; // <t2, _> <- STORE[a2] int t2 = ( byte ) ( data . get ( a2 ) >>> TSHIFT ) ; // if (t1 = REF) /\\ ((t2 != REF) \\/ (a2 < a1)) if ( ( t1 == WAMInstruction . REF ) && ( ( t2 != WAMInstruction . REF ) || ( a2 < a1 ) ) ) { //  STORE[a1] <- STORE[a2] //data.put(a1, refTo(a2)); data . put ( a1 , data . get ( a2 ) ) ; //  trail(a1) trail ( a1 ) ; } else if ( t2 == WAMInstruction . REF ) { //  STORE[a2] <- STORE[a1] //data.put(a2, refTo(a1)); data . put ( a2 , data . get ( a1 ) ) ; //  tail(a2) trail ( a2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Records the address of a binding onto the trail . The trail pointer is advanced by one as part of this operation . [CODESPLIT] private void trail ( int addr ) { // if (a < HB) \\/ ((H < a) /\\ (a < B)) if ( ( addr < hbp ) || ( ( hp < addr ) && ( addr < bp ) ) ) { //  TRAIL[TR] <- a data . put ( trp , addr ) ; //  TR <- TR + 1 trp ++ ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Undoes variable bindings that have been recorded on the trail . Addresses recorded on the trail are reset to REF to self . [CODESPLIT] private void unwindTrail ( int a1 , int a2 ) { // for i <- a1 to a2 - 1 do for ( int addr = a1 ; addr < a2 ; addr ++ ) { //  STORE[TRAIL[i]] <- <REF, TRAIL[i]> int tmp = data . get ( addr ) ; data . put ( tmp , refTo ( tmp ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tidies trail when a choice point is being discarded and a previous choice point it being made the current one . [CODESPLIT] private void tidyTrail ( ) { int i ; // Check that there is a current choice point to tidy down to, otherwise tidy down to the root of the trail. if ( bp == 0 ) { i = TRAIL_BASE ; } else { i = data . get ( bp + data . get ( bp ) + 5 ) ; } while ( i < trp ) { int addr = data . get ( i ) ; if ( ( addr < hbp ) || ( ( hp < addr ) && ( addr < bp ) ) ) { i ++ ; } else { data . put ( i , data . get ( trp - 1 ) ) ; trp -- ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Attempts to unify structures or references on the heap given two references to them . Structures are matched element by element free references become bound . [CODESPLIT] private boolean unify ( int a1 , int a2 ) { // pdl.push(a1) // pdl.push(a2) uPush ( a1 ) ; uPush ( a2 ) ; // fail <- false boolean fail = false ; // while !empty(PDL) and not failed while ( ! uEmpty ( ) && ! fail ) { // d1 <- deref(pdl.pop()) // d2 <- deref(pdl.pop()) // t1, v1 <- STORE[d1] // t2, v2 <- STORE[d2] int d1 = deref ( uPop ( ) ) ; int t1 = derefTag ; int v1 = derefVal ; int d2 = deref ( uPop ( ) ) ; int t2 = derefTag ; int v2 = derefVal ; // if (d1 != d2) if ( d1 != d2 ) { // if (t1 = REF or t2 = REF) // bind(d1, d2) if ( ( t1 == WAMInstruction . REF ) ) { bind ( d1 , d2 ) ; } else if ( t2 == WAMInstruction . REF ) { bind ( d1 , d2 ) ; } else if ( t2 == WAMInstruction . STR ) { // f1/n1 <- STORE[v1] // f2/n2 <- STORE[v2] int fn1 = data . get ( v1 ) ; int fn2 = data . get ( v2 ) ; byte n1 = ( byte ) ( fn1 >>> 24 ) ; // if f1 = f2 and n1 = n2 if ( fn1 == fn2 ) { // for i <- 1 to n1 for ( int i = 1 ; i <= n1 ; i ++ ) { // pdl.push(v1 + i) // pdl.push(v2 + i) uPush ( v1 + i ) ; uPush ( v2 + i ) ; } } else { // fail <- true fail = true ; } } else if ( t2 == WAMInstruction . CON ) { if ( ( t1 != WAMInstruction . CON ) || ( v1 != v2 ) ) { fail = true ; } } else if ( t2 == WAMInstruction . LIS ) { if ( t1 != WAMInstruction . LIS ) { fail = true ; } else { uPush ( v1 ) ; uPush ( v2 ) ; uPush ( v1 + 1 ) ; uPush ( v2 + 1 ) ; } } } } return ! fail ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A simplified unification algorithm for unifying against a constant . [CODESPLIT] private boolean unifyConst ( int fn , int addr ) { boolean success ; int deref = deref ( addr ) ; int tag = derefTag ; int val = derefVal ; // case STORE[addr] of switch ( tag ) { case REF : { // <REF, _> : // STORE[addr] <- <CON, c> data . put ( deref , constantCell ( fn ) ) ; // trail(addr) trail ( deref ) ; success = true ; break ; } case CON : { // <CON, c'> : // fail <- (c != c'); success = val == fn ; break ; } default : { // other: fail <- true; success = false ; } } return success ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty prints a variable allocation slot for tracing purposes . [CODESPLIT] private String printSlot ( int xi , int mode ) { return ( ( mode == STACK_ADDR ) ? \"Y\" : \"X\" ) + ( ( mode == STACK_ADDR ) ? ( xi - ep - 3 ) : xi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a random starting position . [CODESPLIT] public static EightPuzzleState getRandomStartState ( ) { EightPuzzleState newState ; // Turn the goal string into a list of characters. List < Character > charList = stringToCharList ( GOAL_STRING ) ; // Generate random puzzles until a solvable one is found. do { // Shuffle the list. Collections . shuffle ( charList ) ; // Turn the shuffled list into a proper eight puzzle state object. newState = charListToState ( charList ) ; // Check that the puzzle is solvable and if not then repeat the shuffling process. } while ( ! isSolvable ( newState ) ) ; return newState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "To check for solvability the empty tile is moved to its goal position and then the number of swaps needed to put the other tiles in position is counted . For an odd number of rows on a square puzzle there must be an even number of swaps for an even number of rows an odd number of swaps . [CODESPLIT] public static boolean isSolvable ( EightPuzzleState state ) { // Take a copy of the puzzle to check. This is done because this puzzle will be updated in-place and the // original is to be preserved. EightPuzzleState checkState ; try { checkState = ( EightPuzzleState ) state . clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new IllegalStateException ( \"Puzzle state could not be cloned.\" , e ) ; } // Create the goal state to check against when swapping tiles into position. EightPuzzleState goalState = getGoalState ( ) ; // Count the number of illegal swaps needed to put the puzzle in order. int illegalSwaps = 0 ; // Loop over the whole board, left to right, to to bottom for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { // Find out from the goal state what tile should be at this position. char t = goalState . getTileAt ( i , j ) ; // Swap the tile into its goal position keeping count of the total number of illegal swaps. illegalSwaps += checkState . swapTileToLocationCountingIllegal ( t , i , j ) ; } } // Check if the number of illegal swaps is even in which case the puzzle is solvable, or odd in which case it // is not solvable. return ( illegalSwaps % 2 ) == 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a move to generate a new board position . This creates a new state object and updates its board position . The board position in this object is not changed . [CODESPLIT] public EightPuzzleState getChildStateForOperator ( Operator op ) { // Create a copy of the existing board state EightPuzzleState newState ; try { newState = ( EightPuzzleState ) clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new IllegalStateException ( \"Puzzle state could not be cloned.\" , e ) ; } // Update the new board state using the in-place operator application newState . updateWithOperator ( op ) ; return newState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Supplies the valid moves for a board position . [CODESPLIT] public Iterator < Operator < String > > validOperators ( boolean reverse ) { // Used to hold a list of valid moves List < Operator < String >> moves = new ArrayList < Operator < String > > ( 4 ) ; // Check if the up move is valid if ( emptyY != 0 ) { moves . add ( new OperatorImpl < String > ( \"U\" ) ) ; } // Check if the down move is valid if ( emptyY != 2 ) { moves . add ( new OperatorImpl < String > ( \"D\" ) ) ; } // Check if the left move is valid if ( emptyX != 0 ) { moves . add ( new OperatorImpl < String > ( \"L\" ) ) ; } // Check if the right move is valid if ( emptyX != 2 ) { moves . add ( new OperatorImpl < String > ( \"R\" ) ) ; } return moves . iterator ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty prints the board as 3 lines of characters with a space for the empty square . [CODESPLIT] public String prettyPrint ( ) { String result = \"\" ; for ( int j = 0 ; j < 3 ; j ++ ) { result += new String ( board [ j ] ) + \"\\n\" ; } result = result . replace ( ' ' , ' ' ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repeatedly swaps a tile with its neighbours until it reaches the specified location . If the tile is swapped with the empty tile then this is a legal move . If the tile is swapped with another non - empty tile then this is an illegal move and the total number of illegal moves is counted . [CODESPLIT] protected int swapTileToLocationCountingIllegal ( char t , int x , int y ) { // Used to hold the count of illegal swaps int illegal = 0 ; // Find out where the tile to move is int tileX = getXForTile ( t ) ; int tileY = getYForTile ( t ) ; // Shift the tile into the correct column by repeatedly moving it left or right. while ( tileX != x ) { if ( ( tileX - x ) > 0 ) { if ( swapTiles ( tileX , tileY , tileX - 1 , tileY ) ) { illegal ++ ; } tileX -- ; } else { if ( swapTiles ( tileX , tileY , tileX + 1 , tileY ) ) { illegal ++ ; } tileX ++ ; } } // Shift the tile into the correct row by repeatedly moving it up or down. while ( tileY != y ) { // Commented out because tiles never swap down the board during the solvability test because tiles are // swapped into place left to right, top to bottom. The top row is always filled first so tiles cannot be // swapped down into it. Then the next row is filled but ones from the row above are never swapped down // into it because they are alrady in place and never move again and so on. /* if (tileY - y > 0)\n             *{*/ if ( swapTiles ( tileX , tileY , tileX , tileY - 1 ) ) { illegal ++ ; } tileY -- ; /*}\n             * else { if (swapTiles(tileX, tileY, tileX, tileY + 1)) illegal++; tileY++;}*/ } return illegal ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a move to the board position . This changes the board position stored in this object . This is different from the { @link #getChildStateForOperator } method which updates the board position in a new object . [CODESPLIT] protected void updateWithOperator ( Operator op ) { // Get the operator as a character by taking the first character of the operator string char opc = ( ( String ) op . getOp ( ) ) . charAt ( 0 ) ; // Move the empty tile according to the specified operation switch ( opc ) { // Swap the empty tile with the one above it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX , emptyY - 1 ) ; break ; } // Swap the empty tile with the one below it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX , emptyY + 1 ) ; break ; } // Swap the empty tile with the one to the left of it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX - 1 , emptyY ) ; break ; } // Swap the empty tile with the one to the right of it. case ' ' : { swapTiles ( emptyX , emptyY , emptyX + 1 , emptyY ) ; break ; } default : { throw new IllegalStateException ( \"Unkown operator: \" + opc + \".\" ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Swaps the two tiles at the specified coordinates . One of the tiles may be the empty tile and the empty tile position will be correctly updated . If neither of the tiles is empty then this is an illegal swap in which case the method returns true . [CODESPLIT] protected boolean swapTiles ( int x1 , int y1 , int x2 , int y2 ) { // Used to indicate that one of the swapped tiles was the empty tile boolean swappedEmpty = false ; // Get the tile at the first position char tile1 = board [ y1 ] [ x1 ] ; // Store the tile from the second position at the first position char tile2 = board [ y2 ] [ x2 ] ; board [ y1 ] [ x1 ] = tile2 ; // Store the first tile in the second position board [ y2 ] [ x2 ] = tile1 ; // Check if the first tile was the empty tile and update the empty tile coordinates if so if ( tile1 == ' ' ) { emptyX = x2 ; emptyY = y2 ; swappedEmpty = true ; } // Else check if the second tile was the empty tile and update the empty tile coordinates if so else if ( tile2 == ' ' ) { emptyX = x1 ; emptyY = y1 ; swappedEmpty = true ; } return ! swappedEmpty ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns a string representation of the board into a list of characters . [CODESPLIT] private static List < Character > stringToCharList ( String boardString ) { // Turn the goal state into a list of characters char [ ] chars = new char [ 9 ] ; boardString . getChars ( 0 , 9 , chars , 0 ) ; List < Character > charList = new ArrayList < Character > ( ) ; for ( int l = 0 ; l < 9 ; l ++ ) { charList . add ( chars [ l ] ) ; } return charList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns a list of characters representation of the board into a proper state . [CODESPLIT] private static EightPuzzleState charListToState ( List < Character > charList ) { // Create a new empty puzzle state EightPuzzleState newState = new EightPuzzleState ( ) ; // Loop over the board inserting the characters into it from the character list Iterator < Character > k = charList . iterator ( ) ; for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { char nextChar = k . next ( ) ; // Check if this is the empty tile and if so then take note of its position if ( nextChar == ' ' ) { newState . emptyX = i ; newState . emptyY = j ; } newState . board [ j ] [ i ] = nextChar ; } } return newState ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void publish ( LogRecord record ) { org . apache . log4j . Logger log4j = getTargetLogger ( record . getLoggerName ( ) ) ; Priority priority = toLog4j ( record . getLevel ( ) ) ; if ( ! priority . equals ( org . apache . log4j . Level . OFF ) ) { log4j . log ( priority , toLog4jMessage ( record ) , record . getThrown ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms a java . util . logging . LogRecord to a message printable on Log4J . [CODESPLIT] private String toLog4jMessage ( LogRecord record ) { String message = record . getMessage ( ) ; // Format message Object [ ] parameters = record . getParameters ( ) ; if ( ( parameters != null ) && ( parameters . length != 0 ) ) { // Check for the first few parameters ? if ( ( message . indexOf ( \"{0}\" ) >= 0 ) || ( message . indexOf ( \"{1}\" ) >= 0 ) || ( message . indexOf ( \"{2}\" ) >= 0 ) || ( message . indexOf ( \"{3}\" ) >= 0 ) ) { message = MessageFormat . format ( message , parameters ) ; } } return message ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts java . util . logging levels to Log4J logging levels . [CODESPLIT] private org . apache . log4j . Level toLog4j ( Level level ) { if ( Level . SEVERE == level ) { return org . apache . log4j . Level . ERROR ; } else if ( Level . WARNING == level ) { return org . apache . log4j . Level . WARN ; } else if ( Level . INFO == level ) { return org . apache . log4j . Level . INFO ; } else if ( Level . FINE == level ) { return org . apache . log4j . Level . DEBUG ; } else if ( Level . FINER == level ) { return org . apache . log4j . Level . TRACE ; } else if ( Level . OFF == level ) { return org . apache . log4j . Level . OFF ; } return org . apache . log4j . Level . OFF ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean offer ( E o ) { if ( transactional ) { // Delegate the offer operation to the wrapped queue. txMethod . requestWriteOperation ( new EnqueueRecord ( o ) ) ; // return success; return true ; } else { boolean success = queue . offer ( o ) ; // Update the queue size if the offer was succesfull. if ( success ) { incrementSizeAndCount ( o ) ; } return success ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E poll ( ) { Object owner ; if ( transactional ) { owner = TxManager . getCurrentSession ( ) ; } else { owner = null ; } // Attempt to acquire an available element from the queue for the current transaction. return pollAccept ( owner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E pollAccept ( Object owner ) { if ( transactional ) { E element = null ; RequeueElementWrapper < E > record = null ; // Find an element on the requeue that is free, or has already been acquired by the owner but not accepted. // Mark the element as acquired by the owner as necessary. if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { record = nextRecord ; record . state = AcquireState . Acquired ; record . owner = owner ; element = record . element ; break ; } else if ( AcquireState . Acquired . equals ( nextRecord . state ) && owner . equals ( nextRecord . owner ) ) { record = nextRecord ; element = record . element ; break ; } } } // If an element cannot be found on the requeue, poll an element from the main queue, and place it onto the // requeue. if ( record == null ) { element = queue . poll ( ) ; } // If no element at all can be found return null. if ( element == null ) { return element ; } // Check that an element was actually available on the queue before creating a new acquired record for it // on the requeue. if ( record == null ) { record = requeue ( element , owner , AcquireState . Acquired ) ; } // Accept the element and create a transaction operation to remove it upon commit or unnaccept it upon // rollback. record . state = AcquireState . Accepted ; txMethod . requestWriteOperation ( new AcceptRecord ( record ) ) ; return record . element ; } else { E element ; // Find an element on the requeue that is free. Remove it and return it. if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { requeue . remove ( nextRecord ) ; requeuedElementMap . remove ( nextRecord . element ) ; return nextRecord . element ; } } } // Or poll an element from the main queue and return it. element = queue . poll ( ) ; if ( element != null ) { decrementSizeAndCount ( element ) ; } return element ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E pollAcquire ( Object owner ) { E element ; // Find an element on the requeue that is free and return it. if ( ! requeue . isEmpty ( ) ) { for ( RequeueElementWrapper < E > nextRecord : requeue ) { if ( AcquireState . Free . equals ( nextRecord . state ) ) { nextRecord . state = AcquireState . Acquired ; nextRecord . owner = owner ; return nextRecord . element ; } } } // Nothing could be found on the requeue, so attempt to poll an element off the main queue and acquire // it on the requeue. element = queue . poll ( ) ; if ( element != null ) { requeue ( element , owner , AcquireState . Acquired ) ; } return element ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean acquire ( Object owner , Object o ) { // Look up the element wrapper record for the element to be accepted. RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; // Check if the element is currently free, and acquire it if so. if ( AcquireState . Free . equals ( record . state ) ) { record . state = AcquireState . Acquired ; record . owner = owner ; return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void release ( Object owner , Object o ) { // Look up the element wrapper record for the element to be released, and release it. RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; if ( record != null ) { record . state = AcquireState . Free ; record . owner = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( Object owner , Object o ) { // Look up the element wrapper record for the element to be accepted. RequeueElementWrapper < E > record = requeuedElementMap . get ( o ) ; if ( record != null ) { // If running in a transaction, create an accept operation to accept the item only upon commit of the // transaction. if ( transactional ) { record . state = AcquireState . Accepted ; txMethod . requestWriteOperation ( new AcceptRecord ( record ) ) ; } else { requeuedElementMap . remove ( o ) ; requeue . remove ( record ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E take ( ) throws InterruptedException { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( \"This operation is only supported on blocking queues.\" ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . take ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int drainTo ( Collection < ? super E > c ) { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( \"This operation is only supported on blocking queues.\" ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . drainTo ( c ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean offer ( E o , long timeout , TimeUnit unit ) throws InterruptedException { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( \"This operation is only supported on blocking queues.\" ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . offer ( o , timeout , unit ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void put ( E o ) throws InterruptedException { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( \"This operation is only supported on blocking queues.\" ) ; } ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . put ( o ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int remainingCapacity ( ) { if ( ! isBlockingQueue ) { throw new UnsupportedOperationException ( \"This operation is only supported on blocking queues.\" ) ; } return ( ( java . util . concurrent . BlockingQueue < E > ) queue ) . remainingCapacity ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Places an element onto the requeue buffer . [CODESPLIT] private void requeue ( E element ) { RequeueElementWrapper < E > record = new RequeueElementWrapper < E > ( element ) ; requeue . add ( record ) ; requeuedElementMap . put ( element , record ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Places an element onto the requeue buffer in the acquired state by the specified owner . [CODESPLIT] private RequeueElementWrapper < E > requeue ( E element , Object owner , AcquireState acquired ) { RequeueElementWrapper < E > record = new RequeueElementWrapper < E > ( element ) ; record . state = acquired ; record . owner = owner ; requeue . add ( record ) ; requeuedElementMap . put ( element , record ) ; return record ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically adds to the size and count if the queue is running in atomic counting mode or sizeable mode and the element is sizeable . [CODESPLIT] private void incrementSizeAndCount ( E record ) { // Update the count for atomically counted queues. if ( atomicallyCounted ) { count . incrementAndGet ( ) ; } // Update the size for sizeable elements and sizeable queues. if ( sizeable && ( record instanceof Sizeable ) ) { dataSize . addAndGet ( ( ( Sizeable ) record ) . sizeof ( ) ) ; } else if ( sizeable ) { dataSize . incrementAndGet ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Atomically subtracts from the size and count if the queue is running in atomic counting mode or sizeable mode and the element is sizeable . [CODESPLIT] private void decrementSizeAndCount ( E record ) { // Update the count for atomically counted queues. if ( atomicallyCounted ) { count . decrementAndGet ( ) ; } // Update the size for sizeable elements and sizeable queues. if ( sizeable && ( record instanceof Sizeable ) ) { long recordSize = - ( ( Sizeable ) record ) . sizeof ( ) ; long oldSize = dataSize . getAndAdd ( recordSize ) ; long newSize = oldSize + recordSize ; signalOnSizeThresholdCrossing ( oldSize , newSize ) ; } else if ( sizeable ) { long oldSize = dataSize . getAndDecrement ( ) ; long newSize = oldSize - 1 ; signalOnSizeThresholdCrossing ( oldSize , newSize ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Signals the signallable resource if the size crosses a threshold boundary in a downward direction . [CODESPLIT] private void signalOnSizeThresholdCrossing ( long oldSize , long newSize ) { if ( signalable != null ) { if ( ( oldSize >= lowWaterSizeThreshold ) && ( newSize < lowWaterSizeThreshold ) ) { signalable . signalAll ( ) ; } else if ( ( oldSize >= highWaterSizeThreshold ) && ( newSize < highWaterSizeThreshold ) ) { signalable . signal ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves the named object . If name is empty returns a new instance of this context ( which represents the same naming context as this context but its environment may be modified independently and it may be accessed concurrently ) . [CODESPLIT] public Object lookup ( String name ) throws NamingException { if ( \"\" . equals ( name ) ) { // Asking to look up this context itself.  Create and return // a new instance with its own independent environment. return ( new SimpleContext ( myEnv ) ) ; } Object answer = bindings . get ( name ) ; if ( answer == null ) { throw new NameNotFoundException ( name + \" not found\" ) ; } return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a name to an object . All intermediate contexts and the target context ( that named by all but terminal atomic component of the name ) must already exist . [CODESPLIT] public void bind ( String name , Object obj ) throws NamingException { if ( \"\" . equals ( name ) ) { throw new InvalidNameException ( \"Cannot bind empty name\" ) ; } if ( bindings . get ( name ) != null ) { throw new NameAlreadyBoundException ( \"Use rebind to override\" ) ; } bindings . put ( name , obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a name to an object . All intermediate contexts and the target context ( that named by all but terminal atomic component of the name ) must already exist . [CODESPLIT] public void bind ( Name name , Object obj ) throws NamingException { // Flat namespace; no federation; just call string version bind ( name . toString ( ) , obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a name to an object overwriting any existing binding . All intermediate contexts and the target context ( that named by all but terminal atomic component of the name ) must already exist . [CODESPLIT] public void rebind ( String name , Object obj ) throws NamingException { if ( \"\" . equals ( name ) ) { throw new InvalidNameException ( \"Cannot bind empty name\" ) ; } bindings . put ( name , obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unbinds the named object . Removes the terminal atomic name in name from the target context -- that named by all but the terminal atomic part of name . [CODESPLIT] public void unbind ( String name ) throws NamingException { if ( \"\" . equals ( name ) ) { throw new InvalidNameException ( \"Cannot unbind empty name\" ) ; } bindings . remove ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a new name to the object bound to an old name and unbinds the old name . Both names are relative to this context . Any attributes associated with the old name become associated with the new name . Intermediate contexts of the old name are not changed . [CODESPLIT] public void rename ( String oldname , String newname ) throws NamingException { if ( \"\" . equals ( oldname ) || \"\" . equals ( newname ) ) { throw new InvalidNameException ( \"Cannot rename empty name\" ) ; } // Check if new name exists if ( bindings . get ( newname ) != null ) { throw new NameAlreadyBoundException ( newname + \" is already bound\" ) ; } // Check if old name is bound Object oldBinding = bindings . remove ( oldname ) ; if ( oldBinding == null ) { throw new NameNotFoundException ( oldname + \" not bound\" ) ; } bindings . put ( newname , oldBinding ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Binds a new name to the object bound to an old name and unbinds the old name . Both names are relative to this context . Any attributes associated with the old name become associated with the new name . Intermediate contexts of the old name are not changed . [CODESPLIT] public void rename ( Name oldname , Name newname ) throws NamingException { // Flat namespace; no federation; just call string version rename ( oldname . toString ( ) , newname . toString ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enumerates the names bound in the named context along with the class names of objects bound to them . The contents of any subcontexts are not included . If a binding is added to or removed from this context its effect on an enumeration previously returned is undefined . [CODESPLIT] public NamingEnumeration list ( String name ) throws NamingException { if ( \"\" . equals ( name ) ) { // listing this context return new FlatNames ( bindings . keys ( ) ) ; } // Perhaps `name' names a context Object target = lookup ( name ) ; if ( target instanceof Context ) { return ( ( Context ) target ) . list ( \"\" ) ; } throw new NotContextException ( name + \" cannot be listed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Enumerates the names bound in the named context along with the objects bound to them . The contents of any subcontexts are not included . [CODESPLIT] public NamingEnumeration listBindings ( String name ) throws NamingException { if ( \"\" . equals ( name ) ) { // listing this context return new FlatBindings ( bindings . keys ( ) ) ; } // Perhaps `name' names a context Object target = lookup ( name ) ; if ( target instanceof Context ) { return ( ( Context ) target ) . listBindings ( \"\" ) ; } throw new NotContextException ( name + \" cannot be listed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Composes the name of this context with a name relative to this context . Given a name ( name ) relative to this context and the name ( prefix ) of this context relative to one of its ancestors this method returns the composition of the two names using the syntax appropriate for the naming system ( s ) involved . That is if name names an object relative to this context the result is the name of the same object but relative to the ancestor context . None of the names may be null . [CODESPLIT] public String composeName ( String name , String prefix ) throws NamingException { Name result = composeName ( new CompositeName ( name ) , new CompositeName ( prefix ) ) ; return result . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new environment property to the environment of this context . If the property already exists its value is overwritten . See class description for more details on environment properties . [CODESPLIT] public Object addToEnvironment ( String propName , Object propVal ) { if ( myEnv == null ) { myEnv = new Hashtable ( 5 , 0.75f ) ; } return myEnv . put ( propName , propVal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes an environment property from the environment of this context . See class description for more details on environment properties . [CODESPLIT] public Object removeFromEnvironment ( String propName ) { if ( myEnv == null ) { return null ; } return myEnv . remove ( propName ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Repeatedly runs the garbage collector and finalization method of the JVM runtime system until the used memory count becomes stable or 500 iterations occur whichever happens soonest . If other threads are active then this method is not likely to work as the used memory count will continually be changing . [CODESPLIT] private static void runGCTillStable ( ) { // Possibly add another iteration in here to run this whole method 3 or 4 times. long usedMem1 = usedMemory ( ) ; long usedMem2 = Long . MAX_VALUE ; // Repeatedly garbage collection until the used memory count becomes stable, or 500 iterations occur. for ( int i = 0 ; ( usedMem1 < usedMem2 ) && ( i < 500 ) ; i ++ ) { // Force finalisation of all object pending finalisation. RUNTIME . runFinalization ( ) ; // Return unused memory to the heap. RUNTIME . gc ( ) ; // Allow other threads to run. Thread . currentThread ( ) . yield ( ) ; // Keep the old used memory count from the last iteration and get a fresh reading. usedMem2 = usedMem1 ; usedMem1 = usedMemory ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the high - level rule at some scope ( either the root document or within a rule set / mixin ) . Future : Imports [CODESPLIT] Rule Scope ( ) { return Sequence ( push ( new ScopeNode ( ) ) , ZeroOrMore ( FirstOf ( Declaration ( ) , MediaQuery ( ) , RuleSet ( ) , MixinReference ( ) , Sequence ( push ( new WhiteSpaceCollectionNode ( ) ) , Sp1Nodes ( ) ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "media type name Optional ( and ( Css property ) ) [CODESPLIT] Rule MediaType ( ) { return Sequence ( push ( new MediaTypeNode ( ) ) , MediaTypeName ( ) , peek ( 1 ) . addChild ( pop ( ) ) , FirstOf ( Sequence ( MediaTypeRestriction ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Optional ( Ws0 ( ) , push ( new SpacingNode ( \" \" ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sequence ( Whitespace and Whitespace ( Css Property ) ) [CODESPLIT] Rule MediaTypeRestriction ( ) { return Sequence ( push ( new MediaTypeRestriction ( ) ) , Ws0 ( ) , \"and\" , Ws0 ( ) , ' ' , Sequence ( Ident ( ) , peek ( ) . addChild ( new SimpleNode ( match ( ) ) ) , ' ' , peek ( ) . addChild ( new SimpleNode ( \":\" ) ) , Optional ( Ws0 ( ) ) , peek ( ) . addChild ( new SpacingNode ( \" \" ) ) , ExpressionPhrase ( ) ) , ' ' , peek ( 1 ) . addChild ( pop ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "only Whitespace [CODESPLIT] Rule OnlyIndicator ( ) { return Sequence ( \"only\" , peek ( ) . addChild ( new SimpleNode ( match ( ) ) ) , peek ( ) . addChild ( new SimpleNode ( \" \" ) ) , Ws0 ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Selectors { Ws0 / Class Ws0 Parameters Ws0 { Ws0 ) Scope Ws0 } Ws0 [CODESPLIT] Rule RuleSet ( ) { return Sequence ( FirstOf ( // Standard CSS rule set Sequence ( SelectorGroup ( ) , push ( new RuleSetNode ( pop ( ) ) ) , ' ' , Scope ( ) , peek ( 1 ) . addChild ( pop ( ) ) , Ws0 ( ) ) , // Mixin rule set, with possible arguments Sequence ( ClassSelectorGroup ( ) , push ( new RuleSetNode ( pop ( ) ) ) , Ws0 ( ) , Parameters ( ) , Ws0 ( ) , ' ' , Scope ( ) , peek ( 1 ) . addChild ( pop ( ) ) , peek ( 1 ) . addChild ( pop ( ) ) , Ws0 ( ) ) ) , ' ' , Ws0Nodes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Parameter Ws0 ( Ws0 Parameter ) * ) [CODESPLIT] Rule Parameters ( ) { return Sequence ( ' ' , Parameter ( ) , push ( new ParametersNode ( pop ( ) ) ) , Ws0 ( ) , ZeroOrMore ( ' ' , Ws0 ( ) , Parameter ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , ' ' , push ( new ScopeNode ( pop ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Variable Ws0 : Ws0 ExpressionPhrase [CODESPLIT] Rule Parameter ( ) { return Sequence ( Variable ( ) , push ( new VariableDefinitionNode ( match ( ) ) ) , peek ( ) . setVisible ( ! isParserTranslationEnabled ( ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( new ExpressionGroupNode ( pop ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SelectorGroup ; Ws0 / Class Arguments ; Ws0 [CODESPLIT] @ MemoMismatches Rule MixinReference ( ) { Var < String > name = new Var < String > ( ) ; return FirstOf ( // No arguments, reference an existing rule set's properties Sequence ( SelectorGroup ( ) , ' ' , resolveMixinReference ( NodeTreeUtils . getFirstChild ( ( InternalNode ) pop ( ) , SelectorNode . class ) . toString ( ) , null ) , Ws0Nodes ( ) ) , // Call a mixin, passing along some arguments Sequence ( Class ( ) , name . set ( match ( ) ) , Arguments ( ) , Ws0 ( ) , ' ' , resolveMixinReference ( name . get ( ) , ( ArgumentsNode ) pop ( ) ) , Ws0Nodes ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Selector Ws0 ( Ws0 Selector ) * Ws0 [CODESPLIT] @ MemoMismatches Rule SelectorGroup ( ) { return Sequence ( Selector ( ) , push ( new SelectorGroupNode ( pop ( ) ) ) , Ws0Nodes ( ) , ZeroOrMore ( ' ' , Ws0Nodes ( ) , Selector ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Ws0Nodes ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "SimpleSelector ( Combinator SimpleSelector ) * [CODESPLIT] Rule Selector ( ) { Var < SelectorSegmentNode > selectorSegmentNode = new Var < SelectorSegmentNode > ( ) ; return Sequence ( push ( new SelectorNode ( ) ) , // First selector segment may have a combinator (with nested rule sets) Optional ( SymbolCombinator ( ) ) , selectorSegmentNode . set ( new SelectorSegmentNode ( match ( ) ) ) , SimpleSelector ( selectorSegmentNode ) , selectorSegmentNode . get ( ) . setSimpleSelector ( match ( ) ) , peek ( ) . addChild ( selectorSegmentNode . getAndClear ( ) ) , // Additional selector segments must have a combinator ZeroOrMore ( Combinator ( ) , selectorSegmentNode . set ( new SelectorSegmentNode ( match ( ) ) ) , SimpleSelector ( selectorSegmentNode ) , selectorSegmentNode . get ( ) . setSimpleSelector ( match ( ) ) , peek ( ) . addChild ( selectorSegmentNode . getAndClear ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Ident / Variable ) Ws0 : Ws0 ExpressionPhrase ( Ws0 Ws0 ExpressionPhrase ) * Sp0 ( ; / Ws0 & } ) / Ident Ws0 : Ws0 ; [CODESPLIT] Rule Declaration ( ) { return FirstOf ( Sequence ( FirstOf ( Sequence ( PropertyName ( ) , push ( new PropertyNode ( match ( ) ) ) ) , Sequence ( Variable ( ) , push ( new VariableDefinitionNode ( match ( ) ) ) , peek ( ) . setVisible ( ! isParserTranslationEnabled ( ) ) ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , push ( new ExpressionGroupNode ( ) ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( pop ( ) ) , ZeroOrMore ( Ws0 ( ) , ' ' , Ws0Nodes ( ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Sp0 ( ) , FirstOf ( ' ' , Sequence ( Ws0 ( ) , Test ( ' ' ) ) ) , peek ( 1 ) . addChild ( pop ( ) ) ) , // Empty rules are ignored Sequence ( Ident ( ) , push ( new PlaceholderNode ( ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , ' ' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Expression ( Operator Expression ) + Future : Operations / Expression ( Ws1 Expression ) * Important? [CODESPLIT] Rule ExpressionPhrase ( ) { // Space-separated expressions return Sequence ( Expression ( ) , push ( new ExpressionPhraseNode ( pop ( ) ) ) , ZeroOrMore ( Ws1 ( ) , Expression ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) , Optional ( Ws0 ( ) , Important ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ident Arguments [CODESPLIT] Rule Function ( ) { return Sequence ( Ident ( ) , push ( new FunctionNode ( match ( ) ) ) , Arguments ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Ws0 ExpressionPhrase Ws0 ( Ws0 ExpressionPhrase Ws0 ) * ) / ( Ws0 ) [CODESPLIT] Rule Arguments ( ) { return FirstOf ( Sequence ( Ws0 ( ) , ' ' , Ws0 ( ) , ExpressionPhrase ( ) , push ( new ArgumentsNode ( new ExpressionGroupNode ( pop ( ) ) ) ) , Ws0 ( ) , ZeroOrMore ( ' ' , Ws0 ( ) , ExpressionPhrase ( ) , peek ( 1 ) . addChild ( new ExpressionGroupNode ( pop ( ) ) ) , Ws0 ( ) ) , ' ' ) , Sequence ( Ws0 ( ) , ' ' , Ws0 ( ) , ' ' , push ( new ArgumentsNode ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ex : progid : DXImageTransform . Microsoft . gradient ( startColorstr = [CODESPLIT] Rule FilterFunction ( ) { return Sequence ( Sequence ( \"progid:\" , OneOrMore ( FirstOf ( ' ' , Ident ( ) ) ) ) , push ( new FunctionNode ( match ( ) ) ) , FilterArguments ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Ws0 FilterArgument Ws0 ( Ws0 FilterArgument Ws0 ) * ) / ( Ws0 ) [CODESPLIT] Rule FilterArguments ( ) { return FirstOf ( Sequence ( ' ' , Ws0 ( ) , FilterArgument ( ) , push ( new ArgumentsNode ( pop ( ) ) ) , Ws0 ( ) , ZeroOrMore ( ' ' , Ws0 ( ) , FilterArgument ( ) , peek ( 1 ) . addChild ( pop ( ) ) , Ws0 ( ) ) , ' ' ) , Sequence ( ' ' , Ws0 ( ) , ' ' , push ( new ArgumentsNode ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ex : startColorstr = [CODESPLIT] Rule FilterArgument ( ) { return Sequence ( Ident ( ) , push ( new FilterArgumentNode ( match ( ) ) ) , Ws0 ( ) , ' ' , Ws0 ( ) , Value ( ) , peek ( 1 ) . addChild ( pop ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Any token used as a value in an expression Future : Accessors [CODESPLIT] Rule Value ( ) { return FirstOf ( Keyword ( ) , Literal ( ) , Function ( ) , VariableReference ( ) , URL ( ) , Font ( ) , AlphaFilter ( ) , ExpressionFunction ( ) , FilterFunction ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "url ( ( String / [ - _%$ / . & = : ; # + ?Alphanumeric ] + ) ) [CODESPLIT] Rule URL ( ) { return Sequence ( Sequence ( \"url(\" , Ws0 ( ) , FirstOf ( String ( ) , OneOrMore ( FirstOf ( AnyOf ( \"-_%$/.&=:;#+?\" ) , Alphanumeric ( ) ) ) ) , Ws0 ( ) , ' ' ) , push ( new SimpleNode ( match ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "alpha ( Ws0 opacity Ws0 = Ws0 Digit1 Ws0 ) [CODESPLIT] Rule AlphaFilter ( ) { return Sequence ( Sequence ( \"alpha(\" , Ws0 ( ) , \"opacity\" , Ws0 ( ) , ' ' , Ws0 ( ) , Digit1 ( ) , Ws0 ( ) , ' ' ) , push ( new SimpleNode ( match ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "expression ( ( ! ( ) Ws0 [ ; } ] ) . ) * ) ; [CODESPLIT] Rule ExpressionFunction ( ) { return Sequence ( Sequence ( \"expression(\" , ZeroOrMore ( TestNot ( ' ' , Ws0 ( ) , AnyOf ( \";}\" ) ) , ANY ) , ' ' ) , push ( new SimpleNode ( match ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ident &Delimiter [CODESPLIT] Rule Keyword ( ) { return Sequence ( Sequence ( Ident ( ) , Test ( Delimiter ( ) ) ) , push ( new SimpleNode ( match ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tokens that don t need to evaluated [CODESPLIT] Rule Literal ( ) { return Sequence ( FirstOf ( Color ( ) , MultiDimension ( ) , Dimension ( ) , String ( ) ) , push ( new SimpleNode ( match ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Alpha [ - Alphanumeric ] * &Delimiter / String [CODESPLIT] Rule Font ( ) { return Sequence ( FirstOf ( Sequence ( Alpha ( ) , ZeroOrMore ( FirstOf ( ' ' , Alphanumeric ( ) ) ) , Test ( Delimiter ( ) ) ) , String ( ) ) , push ( new SimpleNode ( match ( ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ex : hello / hello [CODESPLIT] Rule String ( ) { return FirstOf ( Sequence ( ' ' , ZeroOrMore ( TestNot ( ' ' ) , ANY ) , ' ' ) , Sequence ( ' ' , ZeroOrMore ( TestNot ( ' ' ) , ANY ) , ' ' ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "- ? Digit * . Digit + / - ? Digit + [CODESPLIT] Rule Number ( ) { return FirstOf ( Sequence ( Optional ( ' ' ) , Digit0 ( ) , ' ' , Digit1 ( ) ) , Sequence ( Optional ( ' ' ) , Digit1 ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Ex : 0099dd / 09d [CODESPLIT] Rule RGB ( ) { return FirstOf ( Sequence ( Hex ( ) , Hex ( ) , Hex ( ) , Hex ( ) , Hex ( ) , Hex ( ) ) , Sequence ( Hex ( ) , Hex ( ) , Hex ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "\\ [ 0 - 9a - fA - F ] { 1 6 } wc? [CODESPLIT] Rule Unicode ( ) { return Sequence ( ' ' , Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) , Optional ( Hex ( ) ) ) ) ) ) , Optional ( Whitespace ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "unicode | \\ [ ^ \\ x0 - \\ x1F ] [CODESPLIT] Rule Escape ( ) { return Sequence ( Test ( ' ' ) , // for performance FirstOf ( Unicode ( ) , Sequence ( ' ' , Sequence ( TestNot ( CharRange ( ( char ) 0 , ( char ) 31 ) ) , ANY ) ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Locates the referenced mixin in one of the scope nodes on the stack . If found the mixin s scope is cloned and placed onto the stack in place of the mixin reference . Additionally any arguments are applied to the mixin s scope . [CODESPLIT] boolean resolveMixinReference ( String name , ArgumentsNode arguments ) { if ( ! isParserTranslationEnabled ( ) ) { return push ( new PlaceholderNode ( new SimpleNode ( name ) ) ) ; } // Walk down the stack, looking for a scope node that knows about a given rule set for ( Node node : getContext ( ) . getValueStack ( ) ) { if ( ! ( node instanceof ScopeNode ) ) { continue ; } ScopeNode scope = ( ScopeNode ) node ; RuleSetNode ruleSet = scope . getRuleSet ( name ) ; if ( ruleSet == null ) { continue ; } // Get the scope of the rule set we located and call it as a mixin ScopeNode ruleSetScope = NodeTreeUtils . getFirstChild ( ruleSet , ScopeNode . class ) . callMixin ( name , arguments ) ; return push ( ruleSetScope ) ; } // Record error location throw new UndefinedMixinException ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Looks for a variable definition that matches the reference in the scope nodes on the stack . If found a reference node that can repeat this lookup later is placed on the stack not the current value itself . This is done because the value may change if the variable reference is inside a mixin . [CODESPLIT] boolean pushVariableReference ( String name ) { if ( ! isParserTranslationEnabled ( ) ) { return push ( new SimpleNode ( name ) ) ; } // Walk down the stack, looking for a scope node that knows about a given variable for ( Node node : getContext ( ) . getValueStack ( ) ) { if ( ! ( node instanceof ScopeNode ) ) { continue ; } // Ensure that the variable exists ScopeNode scope = ( ScopeNode ) node ; if ( ! scope . isVariableDefined ( name ) ) { continue ; } return push ( new VariableReferenceNode ( name ) ) ; } // Record error location throw new UndefinedVariableException ( name ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "记录完善的异常日志信息 ( 包括堆栈信息 ) [CODESPLIT] public static String recordStackTraceMsg ( Exception e ) { StringWriter stringWriter = new StringWriter ( ) ; PrintWriter writer = new PrintWriter ( stringWriter ) ; e . printStackTrace ( writer ) ; StringBuffer buffer = stringWriter . getBuffer ( ) ; return buffer . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the maximum row height for a row of the data table . [CODESPLIT] public void setMaxRowHeight ( int row , int height ) { Integer previousValue = maxRowSizes . get ( row ) ; if ( previousValue == null ) { maxRowSizes . put ( row , height ) ; } else if ( previousValue < height ) { maxRowSizes . put ( row , height ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String put ( Integer col , Integer row , String value ) { maxColumns = ( col > maxColumns ) ? col : maxColumns ; maxRows = ( row > maxRows ) ? row : maxRows ; updateMaxColumnWidth ( col , value . length ( ) ) ; String result = grid . put ( ( long ) col , ( long ) row , value ) ; updateListeners ( col , row ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String get ( Integer col , Integer row ) { return grid . get ( ( long ) col , ( long ) row ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public String remove ( Integer col , Integer row ) { String result = grid . remove ( ( long ) col , ( long ) row ) ; updateListeners ( col , row ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public int getMaxColumnSize ( int col ) { Integer result = maxColumnSizes . get ( col ) ; return ( result == null ) ? 0 : result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void labelCell ( String label , int col , int row ) { cellLabels . put ( label , new Pair < Integer , Integer > ( col , row ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies all interested listeners of an update to this model . [CODESPLIT] protected void updateListeners ( int col , int row ) { TextTableEvent event = new TextTableEvent ( this , row , col ) ; for ( TextTableListener listener : listeners ) { listener . changedUpdate ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the maximum column width for a column of the data table . [CODESPLIT] private void updateMaxColumnWidth ( int column , int width ) { Integer previousValue = maxColumnSizes . get ( column ) ; if ( previousValue == null ) { maxColumnSizes . put ( column , width ) ; } else if ( previousValue < width ) { maxColumnSizes . put ( column , width ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the current page or index offset of a paged list in the session scope . [CODESPLIT] public ActionForward executeWithErrorHandling ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response , ActionErrors errors ) throws Exception { // Get a reference to the session. HttpSession session = request . getSession ( false ) ; // Extract the page form. DynaActionForm pageForm = ( DynaActionForm ) form ; log . fine ( \"pageForm = \" + pageForm ) ; // Get the paged list object from the session. String listingVarName = pageForm . getString ( VAR_NAME_PARAM ) ; log . fine ( \"listingVarName = \" + listingVarName ) ; PagedList pagedList = ( PagedList ) session . getAttribute ( listingVarName ) ; // Set its current page. pagedList . setCurrentPage ( ( Integer ) pageForm . get ( NUMBER_PARAM ) ) ; // Set its index offset if one is specified. Integer index = ( Integer ) pageForm . get ( INDEX_PARAM ) ; if ( index != null ) { pagedList . setCurrentIndex ( index ) ; } // Forward to the success location. return mapping . findForward ( SUCCESS_FORWARD ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void compile ( Sentence < Clause > clauseSentence ) throws SourceCodeException { Clause clause = clauseSentence . getT ( ) ; PrologCompiledClause result = new PrologCompiledClause ( clause . getHead ( ) , clause . getBody ( ) ) ; // Create stack frame slots for all variables in a program. if ( ! clause . isQuery ( ) ) { StackVariableTransform stackVariableTransform = new StackVariableTransform ( 0 , result ) ; result = ( PrologCompiledClause ) result . acceptTransformer ( stackVariableTransform ) ; // Set the required stack frame size on the compiled clause. result . setStackSize ( stackVariableTransform . offset ) ; } // Apply the built-in transformation to map any built-ins to their implementations. TermTransformer builtInTransformation = new BuiltInExpressionTransform ( interner ) ; result = ( PrologCompiledClause ) result . acceptTransformer ( builtInTransformation ) ; // Return the compiled version of the clause. if ( clause . isQuery ( ) ) { observer . onQueryCompilation ( result ) ; } else { observer . onCompilation ( result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Applies a built - in replacement transformation to functors . If the functor matches built - in a { @link BuiltInFunctor } is created with a mapping to the functors built - in implementation and the functors arguments are copied into this new functor . If the functor does not match a built - in it is returned unmodified . [CODESPLIT] public Functor transform ( Functor functor ) { FunctorName functorName = interner . getFunctorFunctorName ( functor ) ; if ( builtInExpressions . containsKey ( functorName ) ) { Class < ? extends Functor > builtInExpressionClass = builtInExpressions . get ( functorName ) ; return ReflectionUtils . newInstance ( ReflectionUtils . getConstructor ( builtInExpressionClass , new Class [ ] { Integer . TYPE , Term [ ] . class } ) , new Object [ ] { functor . getName ( ) , functor . getArguments ( ) } ) ; } else { return functor ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a new node based on a successor of this node . This new node will also be a HeuristicSearchNode . [CODESPLIT] public HeuristicSearchNode < O , T > makeNode ( Successor successor ) throws SearchNotExhaustiveException { HeuristicSearchNode < O , T > node = ( HeuristicSearchNode < O , T > ) super . makeNode ( successor ) ; // Make sure the new node has a reference to the heuristic evaluator node . heuristic = this . heuristic ; // Compute h for the new node node . computeH ( ) ; return node ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes the action providing default error handling . Implementation should override this method to provide their own error handling if the default is not to be used . [CODESPLIT] public ActionForward execute ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { log . fine ( \"ActionForward perform(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse): called\" ) ; // Build an ActionErrors object to hold any errors that occurr ActionErrors errors = new ActionErrors ( ) ; // Create reference to the session HttpSession session = request . getSession ( ) ; // Use a try block to catch any errors that may occur try { return executeWithErrorHandling ( mapping , form , request , response , errors ) ; } // Catch all exceptions here. This will forward to the error page in the event of // any exception that falls through to this top level handler. // Don't catch Throwable here as Errors should fall through to the JVM top level and will result in // termination of the application. catch ( Exception t ) { log . log ( Level . WARNING , \"Caught a Throwable\" , t ) ; // Don't Forward the error to the error handler to interpret it as a Struts error as the exception will // automatically be translated by the error page. // @todo Could add code here to check if there is a 'error' forward page defined. If there is then call // the error handler to translate the throwable into Struts errors and then forward to the 'error' page. // This would mean that the error page defined in web.xml would be the default unless an action explicitly // defined an alternative 'error' forward. // handleErrors(t, errors); // Save all the error messages in the request so that they will be displayed // request.setAttribute(Action.ERROR_KEY, errors); // Rethrow the error as a ServletException here to cause forwarding to error page defined in web.xml throw new WrappedStrutsServletException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void compile ( Sentence < Clause > sentence ) throws SourceCodeException { Clause clause = sentence . getT ( ) ; substituteBuiltIns ( clause ) ; initialiseSymbolTable ( clause ) ; topLevelCheck ( clause ) ; if ( observer != null ) { if ( clause . isQuery ( ) ) { observer . onQueryCompilation ( sentence ) ; } else { observer . onCompilation ( sentence ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Substitutes built - ins within a clause with their built - in definitions . [CODESPLIT] private void substituteBuiltIns ( Term clause ) { TermWalker walk = TermWalkers . positionalWalker ( new BuiltInTransformVisitor ( interner , symbolTable , null , builtInTransform ) ) ; walk . walk ( clause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs a symbol key traverser over the clause to be compiled to ensure that all of its terms and sub - terms have their symbol keys initialised . [CODESPLIT] private void initialiseSymbolTable ( Term clause ) { // Run the symbol key traverser over the clause, to ensure that all terms have their symbol keys correctly // set up. SymbolKeyTraverser symbolKeyTraverser = new SymbolKeyTraverser ( interner , symbolTable , null ) ; symbolKeyTraverser . setContextChangeVisitor ( symbolKeyTraverser ) ; TermWalker symWalker = new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , symbolKeyTraverser , symbolKeyTraverser ) ; symWalker . walk ( clause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds and marks all functors within the clause that are considered to be top - level . [CODESPLIT] private void topLevelCheck ( Term clause ) { TermWalker walk = TermWalkers . positionalWalker ( new TopLevelCheckVisitor ( interner , symbolTable , null ) ) ; walk . walk ( clause ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; if ( isFirstBody ) { instructions . add ( new WAMInstruction ( NeckCut ) ) ; } else { Integer cutLevelVarAllocation = ( Integer ) defaultBuiltIn . getSymbolTable ( ) . get ( CutLevelVariable . CUT_LEVEL_VARIABLE . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; instructions . add ( new WAMInstruction ( Cut , ( byte ) ( cutLevelVarAllocation & 0xff ) ) ) ; } return instructions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty prints a term relative to the symbol namings provided by the specified interner . [CODESPLIT] private String listToString ( VariableAndFunctorInterner interner , boolean isFirst , boolean printVarName , boolean printBindings ) { String result = \"\" ; if ( isFirst ) { result += \"[\" ; } result += arguments [ 0 ] . toString ( interner , printVarName , printBindings ) ; Term consArgument = arguments [ 1 ] . getValue ( ) ; if ( consArgument instanceof Cons ) { result += \", \" + ( ( Cons ) consArgument ) . listToString ( interner , false , printVarName , printBindings ) ; } if ( isFirst ) { result += \"]\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void clear ( ) { // Clea all fields and records from the table. fieldMap = new LinkedHashMap < L , CircularArrayMap < E > > ( ) ; hashFunction = new SequentialCuckooFunction < CompositeKey < K > > ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean containsKey ( K primaryKey , L secondaryKey ) { // Check that the field exists in the table. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { return false ; } // Check that the symbol exists in the table. CompositeKey < K > compositeKey = new CompositeKey < K > ( parentSequenceKey , primaryKey ) ; SymbolTableImpl < K , L , E > nextParentScope = parentScope ; while ( true ) { if ( hashFunction . containsKey ( compositeKey ) ) { break ; } if ( nextParentScope != null ) { compositeKey = new CompositeKey ( nextParentScope . parentSequenceKey , primaryKey ) ; nextParentScope = nextParentScope . parentScope ; } else { return false ; } } // Calculate the symbols index in the table, and use it to check if a value for that field exists. E value = field . get ( hashFunction . apply ( compositeKey ) ) ; return value != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E put ( K primaryKey , L secondaryKey , E value ) { // Create the field column for the secondary key, if it does not already exist. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { field = new CircularArrayMap < E > ( DEFAULT_INITIAL_FIELD_SIZE ) ; fieldMap . put ( secondaryKey , field ) ; } // Create the mapping for the symbol if it does not already exist. Integer index = hashFunction . apply ( new CompositeKey < K > ( parentSequenceKey , primaryKey ) ) ; // Insert the new value for the field into the field map. E oldValue = field . put ( index , value ) ; count ++ ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E remove ( K primaryKey , L secondaryKey ) { CompositeKey < K > compositeKey = new CompositeKey < K > ( parentSequenceKey , primaryKey ) ; // Check that the symbol exists in the table, and return null if not. if ( ! hashFunction . containsKey ( compositeKey ) ) { return null ; } // Check that the field for the secondary key exists, and return null if not. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { return null ; } // Calculate the symbols index in the table, and use it to fetch remove a value for the field if one exists. E oldValue = field . remove ( hashFunction . apply ( compositeKey ) ) ; // Check if the fields size has been reduced to zero, in which case purge that whole field from the symbol // table. if ( field . isEmpty ( ) ) { fieldMap . remove ( secondaryKey ) ; } // Check if an item was really removed from the table, and decrement the size count if so. if ( oldValue != null ) { count -- ; } return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SymbolTable < K , L , E > enterScope ( K key ) { // Create an entry in the sequence function for the key, if one does not already exist. int scopeSequenceKey = hashFunction . apply ( new CompositeKey < K > ( parentSequenceKey , key ) ) ; // Create a new child table for the symbol within this table at depth one greater than this. return new SymbolTableImpl < K , L , E > ( this , fieldMap , hashFunction , depth , scopeSequenceKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SymbolKey getSymbolKey ( K key ) { // Create an entry in the sequence function for the key, if one does not already exist. int scopeSequenceKey = hashFunction . apply ( new CompositeKey < K > ( parentSequenceKey , key ) ) ; return new SymbolKeyImpl ( scopeSequenceKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E get ( SymbolKey key , L secondaryKey ) { // Extract the sequence key from the symbol key. int sequenceKey = ( ( SymbolKeyImpl ) key ) . sequenceKey ; // Check that the field for the secondary key exists, and return null if not. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { return null ; } // Look up the value directly by its sequence key. return field . get ( sequenceKey ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public E put ( SymbolKey key , L secondaryKey , E value ) { // Extract the sequence key from the symbol key. int sequenceKey = ( ( SymbolKeyImpl ) key ) . sequenceKey ; // Create the field column for the secondary key, if it does not already exist. CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field == null ) { field = new CircularArrayMap < E > ( DEFAULT_INITIAL_FIELD_SIZE ) ; fieldMap . put ( secondaryKey , field ) ; } // Insert the new value for the field into the field map. E oldValue = field . put ( sequenceKey , value ) ; count ++ ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void clearUpToLowMark ( L secondaryKey ) { CircularArrayMap < E > field = fieldMap . get ( secondaryKey ) ; if ( field != null ) { field . clearUpToLowMark ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Override public void setValue ( String value ) { checkArgument ( ! UNCHECKED_VALUE . equals ( value ) , \"Cannot uncheck radio control\" ) ; getForm ( ) . elements ( ) . select ( byControlGroup ( ) ) . removeAttr ( \"checked\" ) ; super . setValue ( value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void open ( ) { // Set up colors. componentFactory . setColorScheme ( new DarkColorScheme ( componentFactory . getColorFactory ( ) ) ) ; // Build the main window frame. mainWindow = componentFactory . createMainWindow ( ) ; mainWindow . showMainWindow ( ) ; // Create and initialize the register monitor. registerMonitorController = new RegisterMonitorController ( componentFactory , mainWindow ) ; registerMonitorController . open ( ) ; // Create and initialize the memory layout monitor. memoryLayoutMonitorController = new MemoryLayoutMonitorController ( componentFactory , mainWindow ) ; memoryLayoutMonitorController . open ( ) ; // Create and initialize the byte code view and breakpoint monitor. codeStepController = new CodeStepController ( componentFactory , mainWindow ) ; codeStepController . open ( ) ; // Build the top-level machine monitor, hooking it up to the child components. RegisterSetMonitor registerMonitor = registerMonitorController . getRegisterMonitor ( ) ; MemoryLayoutMonitor layoutMonitor = memoryLayoutMonitorController . getLayoutMonitor ( ) ; BreakpointMonitor breakpointMonitor = codeStepController . getBreakpointMonitor ( ) ; ByteCodeMonitor byteCodeMonitor = codeStepController . getByteCodeMonitor ( ) ; machineMonitor = new MachineMonitor ( registerMonitor , layoutMonitor , breakpointMonitor , byteCodeMonitor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Evaluates the arithmetic comparison on its two numeric arguments . [CODESPLIT] protected boolean evaluate ( NumericType firstNumber , NumericType secondNumber ) { // If either of the arguments is a real number, then use real number arithmetic, otherwise use integer arithmetic. if ( firstNumber . isInteger ( ) && secondNumber . isInteger ( ) ) { return firstNumber . intValue ( ) < secondNumber . intValue ( ) ; } else { return firstNumber . doubleValue ( ) < secondNumber . doubleValue ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a transaction from the Initial state to the Running state or no transition if the current state is not Initial . [CODESPLIT] public void running ( ) { try { stateLock . writeLock ( ) . lock ( ) ; if ( state == State . Initial ) { state = State . Running ; stateChange . signalAll ( ) ; } } finally { stateLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a transaction from the Running state to the Shutdown state or no transition if the current state is not Running . [CODESPLIT] public void terminating ( ) { try { stateLock . writeLock ( ) . lock ( ) ; if ( state == State . Running ) { state = State . Shutdown ; stateChange . signalAll ( ) ; } } finally { stateLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a transaction from the Running or Shutdown state to the Terminated state or no transition if the current state is not Running or Shutdown . [CODESPLIT] public void terminated ( ) { try { stateLock . writeLock ( ) . lock ( ) ; if ( ( state == State . Shutdown ) || ( state == State . Running ) ) { state = State . Terminated ; stateChange . signalAll ( ) ; } } finally { stateLock . writeLock ( ) . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { try { stateLock . writeLock ( ) . lock ( ) ; while ( state != State . Terminated ) { if ( ! stateChange . await ( timeout , unit ) ) { return false ; } } } finally { stateLock . writeLock ( ) . unlock ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void addListener ( L listener ) { // Ensure update to the list, and rebuilding the active array happens atomically. synchronized ( listenersLock ) { listeners . add ( listener ) ; activeListeners = new ArrayList < L > ( listeners ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void removeListener ( L listener ) { // Ensure update to the list, and rebuilding the active array happens atomically. synchronized ( listenersLock ) { listeners . remove ( listener ) ; activeListeners = new ArrayList < L > ( listeners ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void createContinuationStates ( ResolutionState state ) { BuiltInFunctor nextGoal = state . getGoalStack ( ) . peek ( ) ; state . createContinuationStatesForGoal ( nextGoal ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts the specified element into this heap . [CODESPLIT] public boolean offer ( E o ) { // Make a new node out of the new data element. Node newNode = new Node ( o ) ; // Check if there is already a minimum element. if ( minNode != null ) { // There is already a minimum element, so add this new element to its right. newNode . next = minNode . next ; newNode . prev = minNode ; minNode . next . prev = newNode ; minNode . next = newNode ; // Compare the new element with the minimum and update the minimum if neccessary. updateMinimum ( newNode ) ; } // There is not already a minimum element. else { // Update the new element previous and next references to refer to itself so that it forms a doubly linked // list with only one element. This leaves the data structure in a suitable condition for adding more // elements. newNode . next = newNode ; newNode . prev = newNode ; // Set the minimum element to be the new data element. minNode = newNode ; } // Increment the count of data elements in this collection. size ++ ; // Return true to indicate that the new data element was accepted into the heap. return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves and removes the ( head ) minimum element of this heap or null if this heap is empty . [CODESPLIT] public E poll ( ) { // Check if there is only one element in the heap. if ( size == 1 ) { E result = minNode . element ; // Set the minimum to null. minNode = null ; // Decrease the count of elements in the heap. size -- ; return result ; } // Check that there is a minimum element to return. else if ( minNode != null ) { // Get the minimum value that is to be returned. E result = minNode . element ; // Promote the minimum nodes children into the root list but don't update their parent references. Updating // their parent references will be done later. if ( minNode . degree > 0 ) { insertNodes ( minNode , minNode . child ) ; } // Cut the minimum node out of the root list and update the minimum to be old minimums next node. This // node may not really be the minimum but it is taken to be the initial candidate for a new minimum. The // real minimum will be scanned for later. minNode . next . prev = minNode . prev ; minNode . prev . next = minNode . next ; minNode = minNode . next ; // The consolidation process will merge all the binomial trees of the same order until there are none // of duplicate size left. As each binomial tree of order k, Bk, holds 2^k nodes the biggest tree // possible for a heap of n nodes will be log to the base 2 of the next biggest power of 2 above or // equal to n. The next section of code creates an array with this many elements, indexed by the order // of the binomial tree, that is used to keep track of what tree orders currently exist during the // consolidation process. Node [ ] tree = ( Node [ ] ) Array . newInstance ( minNode . getClass ( ) , ceilingLog2 ( size - 1 ) + 1 ) ; // Loop through the root list, setting parent references to null and consolidating the remainder of the heap // into binomial trees. The loop begins at the next node after the min node and finishes on the min node // itself. This means that the min node is always the very last in the root list to be examined and // consolidated ensuring that it cannot have been removed from the root list before the loop gets to it. The // terminal min node is explicitly referenced because the consolidation process will update the min node // during the loop. Node nextNode = null ; Node nextNextNode = minNode . next ; Node terminalNode = minNode ; do { // Move on to the next node. nextNode = nextNextNode ; // Work out what the next next node will be at the start of the loop as manipulations durings // the loop may override the next node reference of the current next node. nextNextNode = nextNode . next ; // Update parent references to null. nextNode . parent = null ; // Update the minimum if the current root list element is smaller than the current best candidate. updateMinimum ( nextNode ) ; // Consolidate the remainder of the heap into binomial trees by merging duplicate trees of equal size. // Loop until no tree with the same size as the current one exists. int degree = nextNode . degree ; Node parentNode = nextNode ; while ( tree [ degree ] != null ) { // Clear the binomial tree of this size from the tree array as it is about to be merged with the // current node and a new tree of twice the size created. Node mergeNode = tree [ degree ] ; tree [ degree ] = null ; // Compare the roots of the two trees to be merged to decide which is the smaller and should form // the single root of the merged tree. if ( compare ( mergeNode , parentNode ) < 0 ) { // Swap the two nodes. Node temp = mergeNode ; mergeNode = parentNode ; parentNode = temp ; } // Cut the tree rooted by the larger root node from the root list. mergeNode . next . prev = mergeNode . prev ; mergeNode . prev . next = mergeNode . next ; mergeNode . next = mergeNode ; mergeNode . prev = mergeNode ; // Paste the tree rooted by the larger root node into the tree with the smaller root node. mergeNode . parent = parentNode ; // Check if the smaller node (the parent) already has some children. if ( parentNode . child != null ) { // Stitch the larger node into the circular doubly linked list of children. insertNodes ( parentNode . child , mergeNode ) ; // Update all the parent references of the newly added children. } // The smaller node does not already have children. else { // Set the larger node (of degree 1) as its first child. parentNode . child = mergeNode ; // Make sure the child node forms a doubly linked list with itself. mergeNode . next = mergeNode ; mergeNode . prev = mergeNode ; } // Bump up by one the order of the smaller root node to which the other tree of equal size was // added. parentNode . degree ++ ; // Continue the scan for duplicate trees on the next larger degree. degree ++ ; } tree [ degree ] = parentNode ; } while ( nextNode != terminalNode ) ; /*\n             * String out = \"At End: [\"; for (int i = 0; i < tree.length; i++) out += (i == tree.length - 1) ? tree[i] :\n             * tree[i] + \", \"; out += \"]\"; log.info(out);\n             */ // Decrease the count of elements in the heap. size -- ; // Return the minimum element. return result ; } // There is no minimum element so return null. else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the smallest integer value m such that m^2 > = n . The ceiling log2 of n . [CODESPLIT] private static int ceilingLog2 ( int n ) { int oa ; int i ; int b ; oa = n ; b = 32 / 2 ; i = 0 ; while ( b != 0 ) { i = ( i << 1 ) ; if ( n >= ( 1 << b ) ) { n /= ( 1 << b ) ; i = i | 1 ; } else { n &= ( 1 << b ) - 1 ; } b /= 2 ; } if ( ( 1 << i ) == oa ) { return i ; } else { return i + 1 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares the specified node with the minimum and updates the minimum if neccessary . If a comparator was used to create this heap then this comparator is used to perform the comparison . If no comparator was set then the natural ordering of the element type is used . The element must implement the Comparable interface to support a natural ordering . If it does not there will be a class cast exception thrown . [CODESPLIT] private void updateMinimum ( Node node ) { // Check if a comparator was set. if ( entryComparator != null ) { // Use the comparator to compare the candidate new minimum with the current one and check if the new one // should be set. if ( entryComparator . compare ( node . element , minNode . element ) < 0 ) { // Update the minimum node. minNode = node ; } } // No comparator was set so use the natural ordering. else { // Cast the candidate new minimum element into a Comparable and compare it with the existing minimum // to check if the new one should be set. if ( ( ( Comparable ) node . element ) . compareTo ( minNode . element ) < 0 ) { // Update the minimum node. minNode = node ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two heap nodes . The comparison performed is dependant on whether a comparator has been set or the natural ordering is to be used . [CODESPLIT] private int compare ( Node node1 , Node node2 ) { // Check if a comparator was set. if ( entryComparator != null ) { // Use the comparator to compare. return entryComparator . compare ( node1 . element , node2 . element ) ; } // No comparator was set so use the natural ordering. else { // Cast one of the elements into a Comparable and compare it with the other. return ( ( Comparable ) node1 . element ) . compareTo ( node2 . element ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Inserts a single node or a circular doubly linked list of nodes into a list next to the specified node . I does not matter if the specified nodes are singletons or part of a chain as they will be correctly linked in in either case so long as their prev and next references form a loop with themselves . [CODESPLIT] private void insertNodes ( Node node , Node newNode ) { // Keep a reference to the next node in the node's chain as this will be overwritten when attaching the node // or chain into the root list. Node oldNodeNext = newNode . next ; // Break open the node's chain and attach it into the root list. newNode . next . prev = node ; newNode . next = node . next ; // Break open the root list chain and attach it to the new node or chain. node . next . prev = newNode ; node . next = oldNodeNext ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pauses any calling thread until { [CODESPLIT] public void pause ( ) { try { lock . lock ( ) ; try { released . await ( ) ; } catch ( InterruptedException e ) { // Exception set to null as compensation action of returning immediately with current thread interrupted // is taken. e = null ; Thread . currentThread ( ) . interrupt ( ) ; return ; } } finally { lock . unlock ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restarts the sweep alogirithm . Useful after a kill has stopped it . [CODESPLIT] public void restart ( ) { // Clear the sweep thread kill flag. sweepThreadKillFlag = false ; // Start the sweep thread running with low priority. cacheSweepThread = new Thread ( ) { public void run ( ) { sweep ( ) ; } } ; cacheSweepThread . setPriority ( Thread . MIN_PRIORITY ) ; cacheSweepThread . start ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which this map maps the specified key . Returns <tt > null< / tt > if the map contains no mapping for this key . A return value of <tt > null< / tt > does not <i > necessarily< / i > indicate that the map contains no mapping for the key ; it s also possible that the map explicitly maps the key to <tt > null< / tt > . The <tt > containsKey< / tt > operation may be used to distinguish these two cases . [CODESPLIT] public Object get ( Object key ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Try to extract the matching element as an ElementMonitor, ElementMonitor monitor = ( ElementMonitor ) cache . get ( key ) ; // If the element is not null then return its value, else null. // Also upgrade the timestamp of the matching element to the present to show that it has been recently // accessed. if ( monitor != null ) { // Upgrade the timestamp. long t = System . currentTimeMillis ( ) ; monitor . lastTouched = t ; // Return the element. return monitor . element ; } else { return null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified key in this map ( optional operation ) . If the map previously contained a mapping for this key the old value is replaced by the specified value . ( A map <tt > m< / tt > is said to contain a mapping for a key <tt > k< / tt > if and only if { @link #containsKey ( Object ) m . containsKey ( k ) } would return <tt > true< / tt > . )) [CODESPLIT] public Object put ( Object key , Object value ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Create a new ElementMonitor in the cache for the new element. // Timestamp the new element with the present time. long t = System . currentTimeMillis ( ) ; // Extract the element value out of the replaced element monitor if any. ElementMonitor replaced = ( ElementMonitor ) cache . put ( key , new ElementMonitor ( value , t ) ) ; if ( replaced != null ) { return replaced . element ; } else { return null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the mapping for this key from this map if it is present ( optional operation ) . More formally if this map contains a mapping from key <tt > k< / tt > to value <tt > v< / tt > such that <code > ( key == null ? k == null : key . equals ( k )) < / code > that mapping is removed . ( The map can contain at most one such mapping . ) [CODESPLIT] public Object remove ( Object key ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Remove the element from the marked heap (if it exists in the heap) and from the cache. marked . remove ( key ) ; return cache . remove ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all of the mappings from the specified map to this map ( optional operation ) . The effect of this call is equivalent to that of calling { @link #put ( Object Object ) put ( k v ) } on this map once for each mapping from key <tt > k< / tt > to value <tt > v< / tt > in the specified map . The behavior of this operation is unspecified if the specified map is modified while the operation is in progress . [CODESPLIT] public void putAll ( Map t ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Iterate over all elements in the map to add, placing each of them into an ElementMonitor before // putting them into the cache. for ( Object nextKey : t . keySet ( ) ) { Object nextValue = t . get ( nextKey ) ; // Delegate to the put method to wrap the new item in an ElementMonitor. cache . put ( nextKey , nextValue ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Garbage collects the cache sweeping out any elements that have timed out . This method should really only be invoked in a seperate thread as it does not return ( at least not until the { @link #sweepThreadKillFlag } is set ) . [CODESPLIT] private void sweep ( ) { /*log.fine(\"private void sweep(): called\");*/ // Loop until the thread is terminated. while ( true ) { // Take a marked copy of the cache to examine for timed out elements. // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { /*log.fine(\"\\tMarking \" + cache.size() + \" objects.\");*/ // Take a copy of everything in the cache into the marked heap. marked . putAll ( cache ) ; } // Use synchronized block to own this objects monitor so that it can be waited on. // This is needed so that the kill method, and other methods, can wake this thread up. synchronized ( this ) { // Use a try block as the thread may be woken up during the pause time between sweeps. try { // Halt the thread between sweeps, configured by the sweepTime property. wait ( sweepTime ) ; } catch ( InterruptedException e ) { // Ignore this, interuption conditions will be tested later. } } // TODO: Should really check that sweepTime has expired. // Check the sweep thread kill flag to see if the sweep algorithm has been stopped. if ( sweepThreadKillFlag ) { return ; } // Create a counter to count the number of elements removed from the cache. int i = 0 ; // Create a map to copy the marked heap into. This is done because the following code must iterate // over the marked heap whilst modifying it. A copy is used to generate all the keys to iterate over so // that the iterator is not disturbed by its underlying data structure being simultaneously modified. Map copy = new HashMap ( ) ; // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Put everything in the marked cache into the copy. copy . putAll ( marked ) ; } // Loop over the copy of the marked heap looking for timed out elements. for ( Object nextKey : copy . keySet ( ) ) { // Get the key of the next element from the copy of the marked heap. // Extract the current element from the copy of the marked heap as an ElementMonitor object. ElementMonitor nextMonitor = ( ElementMonitor ) copy . get ( nextKey ) ; // Get the current time in milliseconds. long t = System . currentTimeMillis ( ) ; // Check if the current element has not been accessed for a while, configured by the // sweepExpiryTime property. if ( ( t - nextMonitor . lastTouched ) > sweepExpiryTime ) { // Synchronize on the cache to ensure its integrity in a multi-threaded environment. synchronized ( cache ) { // Remove the out of date element from the marked heap and from the cache. marked . remove ( nextKey ) ; cache . remove ( nextKey ) ; /*log.fine(\"Element removed from the cache \" + nextKey);*/ // Increment the count of invalidated elements. i ++ ; } } } /*log.fine(i + \" objects removed.\");*/ } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getNameReturnsName ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='text' name='x'/>\" + \"</form>\" + \"</body></html>\" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . getControlGroup ( \"x\" ) . getName ( ) ; assertThat ( \"form control group name\" , actual , is ( \"x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getControlsReturnsControl ( ) { server ( ) . enqueue ( new MockResponse ( ) . setBody ( \"<html><body>\" + \"<form name='f'>\" + \"<input type='text' name='x'/>\" + \"</form>\" + \"</body></html>\" ) ) ; List < Control > actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( \"f\" ) . getControlGroup ( \"x\" ) . getControls ( ) ; assertThat ( \"form control group control\" , actual , contains ( control ( \"x\" ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an iterator over a search method that returns successive search solutions on demand . [CODESPLIT] public static < T > Iterator < T > allSolutions ( SearchMethod < T > method ) { //return new Filterator<SearchNode<O, T>, T>(allSolutionNodes(method), new ExtractSearchNode<O, T>()); // Take a final reference to the search method to use from within the inner class. final SearchMethod < T > search = method ; return new SequenceIterator < T > ( ) { /**\n                 * Generates the next element in the search.\n                 *\n                 * @return The next solution from the search if one is available, or <tt>null</tt> if the search is\n                 *         complete.\n                 */ public T nextInSequence ( ) { try { return search . search ( ) ; } catch ( SearchNotExhaustiveException e ) { // SearchNotExhaustiveException means that the search has completed within its designed parameters // without exhausting the search space. Consequently there are no more solutions to find, // the exception can be ignored and the sequence correctly terminated. e = null ; return null ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds the set of all goals of a search . [CODESPLIT] public static < T > Set < T > setOf ( SearchMethod < T > method ) { Set < T > result = new HashSet < T > ( ) ; findAll ( result , method ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finds a bag of all goals of a search . [CODESPLIT] public static < T > Collection < T > bagOf ( SearchMethod < T > method ) { Collection < T > result = new ArrayList < T > ( ) ; findAll ( result , method ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an iterator over a search method that returns successive search solutions on demand . [CODESPLIT] public static < O , T extends Traversable < O > > Iterator < SearchNode < O , T > > allSolutionPaths ( QueueBasedSearchMethod < O , T > method ) { // Take a final reference to the search method to use from within the inner class. final QueueBasedSearchMethod < O , T > search = method ; return new SequenceIterator < SearchNode < O , T > > ( ) { /**\n                 * Generates the next element in the search.\n                 *\n                 * @return The next solution from the search if one is available, or <tt>null</tt> if the search is\n                 *         complete.\n                 */ public SearchNode < O , T > nextInSequence ( ) { try { return search . findGoalPath ( ) ; } catch ( SearchNotExhaustiveException e ) { // SearchNotExhaustiveException means that the search has completed within its designed parameters // without exhausting the search space. Consequently there are no more solutions to find, // the exception can be ignored and the sequence correctly terminated. e = null ; return null ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Finals all solutions to a search and inserts them into the specified collection . [CODESPLIT] private static < T > void findAll ( Collection < T > result , SearchMethod < T > method ) { for ( Iterator < T > i = allSolutions ( method ) ; i . hasNext ( ) ; ) { T nextSoltn = i . next ( ) ; result . add ( nextSoltn ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void open ( ) { // Build a text grid panel in the central position. grid = componentFactory . createTextGrid ( ) ; mainWindow . showCentrePane ( componentFactory . createTextGridPanel ( grid ) ) ; paneController = mainWindow . getCentreController ( ) ; paneController . showVerticalScrollBar ( ) ; // Build a table model on the text grid, to display the code in. table = ( EnhancedTextTable ) grid . createTable ( 0 , 0 , 20 , 20 ) ; breakpointMonitor = new BreakpointMonitorImpl ( ) ; byteCodeMonitor = new ByteCodeMonitor ( table ) ; // Attach listeners for user events on the table. grid . addTextGridSelectionListener ( new SelectionHandler ( ) ) ; // Register some keyboard shortcuts to control the code stepping. KeyShortcutMap shortcutMap = componentFactory . getKeyShortcutMap ( ) ; mainWindow . setKeyShortcut ( shortcutMap . getStep ( ) , \"step\" , new Step ( ) ) ; mainWindow . setKeyShortcut ( shortcutMap . getStepOver ( ) , \"step_over\" , new StepOver ( ) ) ; mainWindow . setKeyShortcut ( shortcutMap . getResume ( ) , \"resume\" , new Resume ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates the next element in the sequence . [CODESPLIT] public T nextInSequence ( ) { T result = null ; // Loop until a filtered element is found, or the source iterator is exhausted. while ( source . hasNext ( ) ) { S next = source . next ( ) ; result = mapping . apply ( next ) ; if ( result != null ) { break ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public ByteBuffer getCodeBuffer ( CallPoint callPoint ) { ByteBuffer buffer = ByteBuffer . wrap ( code , callPoint . entryPoint , callPoint . length ) ; buffer . order ( ByteOrder . LITTLE_ENDIAN ) ; return buffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { // Build the argument to call in the usual way. return defaultBuiltIn . compileBodyArguments ( expression , isFirstBody , clauseName , bodyNumber ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { // Used to build up the results in. SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Generate the call or tail-call instructions, followed by the call address, which is f_n of the // called program. if ( isLastBody ) { // Deallocate the stack frame at the end of the clause, but prior to calling the last // body predicate. // This is not required for chain rules, as they do not need a stack frame. if ( ! chainRule ) { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; } instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . CallInternal , ( byte ) ( permVarsRemaining & 0xff ) , new FunctorName ( \"execute\" , 1 ) ) ) ; } else { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . CallInternal , ( byte ) ( permVarsRemaining & 0xff ) , new FunctorName ( \"call\" , 1 ) ) ) ; } return instructions ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Restores the properties currently in this memento to the specified object . [CODESPLIT] public static void restoreValues ( Object ob , Map < String , Object > values ) throws NoSuchFieldException { /*log.fine(\"public void restore(Object ob): called\");*/ /*log.fine(\"Object to restore to has the type: \" + ob.getClass());*/ // Get the class of th object to restore to. Class obClass = ob . getClass ( ) ; // Loop over all the stored properties. for ( String propName : values . keySet ( ) ) { // Get the cached property from this mementos store. Object nextValue = values . get ( propName ) ; /*log.fine(\"Next property to restore is: \" + propName);*/ /*log.fine(\"Next value to restore is: \" + nextValue);*/ // Used to hold the value to set. Object paramValue ; // Used to hold the type of the value to set. Class paramType ; // Check if the value store is a null. if ( nextValue == null ) { paramValue = null ; paramType = null ; } // Check if the value to store is a multi type data object. else if ( nextValue instanceof TypeConverter . MultiTypeData ) { /*log.fine(\"The value to restore is a multi typed data object.\");*/ TypeConverter . MultiTypeData multiValue = ( TypeConverter . MultiTypeData ) nextValue ; // Get the types (classes) of all the possible 'setter' methods for the property. Set < Class > setterTypes = ReflectionUtils . findMatchingSetters ( ob . getClass ( ) , propName ) ; /*log.fine(\"setterTypes = \" + setterTypes);*/ // Use the type converter to get the best matching type with the multi data. paramType = TypeConverter . bestMatchingConversion ( multiValue , setterTypes ) ; // Convert the multi data to an object of the appropriate type. paramValue = TypeConverter . convert ( multiValue , paramType ) ; } // The value to store is not a multi type. else { /*log.fine(\"The value to restore is a simply typed data object.\");*/ // Get the type and value of the plain type to set. paramValue = nextValue ; paramType = nextValue . getClass ( ) ; } /*log.fine(\"paramValue = \" + paramValue);*/ /*log.fine(\"paramType = \" + paramType);*/ // Call the setter method with the new property value, checking first that the property has a matching // 'setter' method. Method setterMethod ; try { // Convert the first letter of the property name to upper case to match against the upper case version // of it that will be in the setter method name. For example the property test will have a setter method // called setTest. String upperPropertyName = Character . toUpperCase ( propName . charAt ( 0 ) ) + propName . substring ( 1 ) ; // Try to find an appropriate setter method on the object to call. setterMethod = obClass . getMethod ( \"set\" + upperPropertyName , paramType ) ; // Call the setter method with the new property value. Object [ ] params = new Object [ ] { paramValue } ; setterMethod . invoke ( ob , params ) ; } catch ( NoSuchMethodException e ) { // Do nothing as properties may have getters but no setter for read only properties. /*log.log(java.util.logging.Level.FINE, \"A setter method could not be found for \" + propName + \".\", e);*/ /*\n                // The object does not have a matching setter method for the type.\n                NoSuchFieldException nsfe = new NoSuchFieldException(\"The object does not have a matching setter \" +\n                                                                     \"method 'set\" + propName + \"'.\");\n                nsfe.initCause(e);\n                throw nsfe;\n                */ } catch ( IllegalAccessException e ) { /*log.log(java.util.logging.Level.FINE, \"IllegalAccessException during call to setter method.\", e);*/ } catch ( InvocationTargetException e ) { /*log.log(java.util.logging.Level.FINE, \"InvocationTargetException during call to setter method.\", e);*/ } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value of the named property of the specified class . [CODESPLIT] public Object get ( Class cls , String property ) throws NoSuchFieldException { // Check that the field exists. if ( ! values . containsKey ( property ) ) { throw new NoSuchFieldException ( \"The property, \" + property + \", does not exist on the underlying class.\" ) ; } // Try to find a matching property cached in this memento. return values . get ( property ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value of the named property as a multi type object . [CODESPLIT] public void put ( Class cls , String property , TypeConverter . MultiTypeData value ) { /*log.fine(\"public void put(String property, TypeConverter.MultiTypeData value): called\");*/ /*log.fine(\"property  = \" + property);*/ /*log.fine(\"value = \" + value);*/ // Store the multi typed data under the specified property name. values . put ( property , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Places the specified value into the memento based on the property s declaring class and name . [CODESPLIT] public void put ( Class cls , String property , Object value ) { // Store the new data under the specified property name. values . put ( property , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Captures the fields of the associated object . [CODESPLIT] private void capture ( boolean ignoreNull ) { // Get the class of the object to build a memento for. Class cls = ob . getClass ( ) ; // Iterate through all the public methods of the class including all super-interfaces and super-classes. Method [ ] methods = cls . getMethods ( ) ; for ( Method nextMethod : methods ) { // Get the next method. /*log.fine(\"nextMethod = \" + nextMethod.getName());*/ // Check if the method is a 'getter' method, is public and takes no arguments. String methodName = nextMethod . getName ( ) ; if ( methodName . startsWith ( \"get\" ) && ( methodName . length ( ) >= 4 ) && Character . isUpperCase ( methodName . charAt ( 3 ) ) && Modifier . isPublic ( nextMethod . getModifiers ( ) ) && ( nextMethod . getParameterTypes ( ) . length == 0 ) ) { String propName = Character . toLowerCase ( methodName . charAt ( 3 ) ) + methodName . substring ( 4 ) ; /*log.fine(methodName + \" is a valid getter method for the property \" + propName + \".\");*/ try { // Call the 'getter' method to extract the properties value. Object [ ] params = new Object [ ] { } ; Object value = nextMethod . invoke ( ob , params ) ; /*log.fine(\"The result of calling the getter method is: \" + value);*/ // Store the property value for the object. if ( ! ignoreNull || ( value != null ) ) { values . put ( propName , value ) ; } } catch ( IllegalAccessException e ) { /*log.log(java.util.logging.Level.FINE, \"IllegalAccessException during call to getter method.\", e);*/ throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { /*log.log(java.util.logging.Level.FINE, \"InvocationTargetException during call to getter method.\", e);*/ throw new IllegalStateException ( e ) ; } } // Should also check if the method is a 'setter' method, is public and takes exactly one argument. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the interpreter and launches its top - level run loop . [CODESPLIT] public static void main ( String [ ] args ) { try { SymbolTableImpl < Integer , String , Object > symbolTable = new SymbolTableImpl < Integer , String , Object > ( ) ; WAMResolvingMachine machine = new WAMResolvingNativeMachine ( symbolTable ) ; Parser < Clause , Token > parser = new SentenceParser ( machine ) ; parser . setTokenSource ( TokenSource . getTokenSourceForInputStream ( System . in ) ) ; LogicCompiler < Clause , WAMCompiledPredicate , WAMCompiledQuery > compiler = new WAMCompiler ( symbolTable , machine ) ; ResolutionEngine < Clause , WAMCompiledPredicate , WAMCompiledQuery > engine = new WAMEngine ( parser , machine , compiler , machine ) ; engine . reset ( ) ; ResolutionInterpreter < WAMCompiledPredicate , WAMCompiledQuery > interpreter = new ResolutionInterpreter < WAMCompiledPredicate , WAMCompiledQuery > ( engine ) ; interpreter . interpreterLoop ( ) ; } catch ( Exception e ) { /*log.log(java.util.logging.Level.SEVERE, e.getMessage(), e);*/ e . printStackTrace ( new PrintStream ( System . err ) ) ; System . exit ( - 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void mousePressed ( MouseEvent e ) { gripComponent . setCursor ( moveCursor ) ; pressed = true ; lastY = e . getYOnScreen ( ) ; lastX = e . getXOnScreen ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void mouseDragged ( MouseEvent e ) { if ( pressed ) { int deltaY = e . getYOnScreen ( ) - lastY ; lastY = e . getYOnScreen ( ) ; int deltaX = e . getXOnScreen ( ) - lastX ; lastX = e . getXOnScreen ( ) ; boolean revalidate = false ; if ( deltaY != 0 ) { resizeable . deltaY ( - deltaY ) ; revalidate = true ; } if ( deltaX != 0 ) { resizeable . deltaX ( - deltaX ) ; revalidate = true ; } if ( revalidate ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { gripComponent . getParent ( ) . revalidate ( ) ; } } ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] @ Test public void getRequestsPath ( ) throws InterruptedException { server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) , \"/x\" ) ) ; assertThat ( \"request path\" , server ( ) . takeRequest ( ) . getPath ( ) , is ( \"/x\" ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "---------------------------------------------------------------------------------------------------------------- [CODESPLIT] public final Link getLink ( String rel ) { List < Link > links = getLinks ( rel ) ; if ( links . isEmpty ( ) ) { throw new LinkNotFoundException ( rel ) ; } return links . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pops the first object placed on the stack off of it and returns it . [CODESPLIT] public E pop ( ) { E ob ; if ( size ( ) == 0 ) { return null ; } ob = get ( 0 ) ; remove ( 0 ) ; return ob ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public T nextInSequence ( ) { T result = null ; // Poll results from the buffer until no more are available, but only once the state machine has flushed // the buffer. if ( flushMode ) { result = buffer . poll ( ) ; if ( result != null ) { return result ; } flushMode = false ; } // Feed input from the source into the state machine, until some results become available on the buffer. while ( source . hasNext ( ) ) { S next = source . next ( ) ; fsm . apply ( next ) ; if ( flushMode ) { result = buffer . poll ( ) ; if ( result != null ) { return result ; } flushMode = false ; } } // Once the end of the input source is reached, inform the state machine of this, and try and poll any // buffered results. fsm . end ( ) ; if ( flushMode ) { result = buffer . poll ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onReset ( WAMResolvingMachineDPI dpi ) { System . out . println ( \"reset\" ) ; tableModel = new TextTableImpl ( ) ; layoutRegisters = new InternalMemoryLayoutBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) ; layoutRegisters . addPropertyChangeListener ( this ) ; layoutRegisters . updateRegisters ( layoutRegisters ) ; internalRegisters = new InternalRegisterBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , false ) ; internalRegisters . addPropertyChangeListener ( this ) ; internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onCodeUpdate ( WAMResolvingMachineDPI dpi , int start , int length ) { System . out . println ( \"Code updated, \" + length + \" bytes at \" + start + \".\" ) ; tableModel = new TextTableImpl ( ) ; ByteBuffer code = dpi . getCodeBuffer ( start , length ) ; SizeableList < WAMInstruction > instructions = WAMInstruction . disassemble ( start , length , code , dpi . getVariableAndFunctorInterner ( ) , dpi ) ; int row = 0 ; for ( WAMInstruction instruction : instructions ) { if ( instruction . getLabel ( ) != null ) { tableModel . put ( 0 , row , instruction . getLabel ( ) . toPrettyString ( ) ) ; } tableModel . put ( 1 , row , instruction . toString ( ) ) ; row ++ ; } printTable ( tableModel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the table . [CODESPLIT] protected void printTable ( TextTableModel printTable ) { for ( int i = 0 ; i < printTable . getRowCount ( ) ; i ++ ) { StringBuffer result = new StringBuffer ( ) ; for ( int j = 0 ; j < printTable . getColumnCount ( ) ; j ++ ) { String valueToPrint = printTable . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? \"\" : valueToPrint ; result . append ( valueToPrint ) ; Integer maxColumnSize = printTable . getMaxColumnSize ( j ) ; int padding = ( ( maxColumnSize == null ) ? 0 : maxColumnSize ) - valueToPrint . length ( ) ; padding = ( padding < 0 ) ? 0 : padding ; for ( int s = 0 ; s < padding ; s ++ ) { result . append ( \" \" ) ; } result . append ( \" % \" ) ; } result . append ( \"\\n\" ) ; System . out . print ( result ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public KeyStroke withKey ( String key ) { // Extract the modifiers as a specification string. String keyString = modifiersToString ( modifiers ) ; // Reset the modifiers so the builder can be used again. modifiers = 0 ; return KeyStroke . getKeyStroke ( keyString + key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts the modifiers to a specification string for KeyStroke . [CODESPLIT] private String modifiersToString ( int modifiers ) { String result = \"\" ; if ( ( modifiers & InputEvent . SHIFT_MASK ) != 0 ) { result += \"shift \" ; } if ( ( modifiers & InputEvent . CTRL_MASK ) != 0 ) { result += \"ctrl \" ; } if ( ( modifiers & InputEvent . META_MASK ) != 0 ) { result += \"meta \" ; } if ( ( modifiers & InputEvent . ALT_MASK ) != 0 ) { result += \"alt \" ; } if ( ( modifiers & InputEvent . ALT_GRAPH_MASK ) != 0 ) { result += \"altGraph \" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void insertAttribute ( AttributeSet attributes , int c , int r ) { attributeGrid . insertAttribute ( attributes , c , r ) ; updateListenersOnAttributeChange ( c , r ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void insertColumnAttribute ( AttributeSet attributes , int c ) { attributeGrid . insertColumnAttribute ( attributes , c ) ; updateListenersOnAttributeChange ( c , - 1 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void insertRowAttribute ( AttributeSet attributes , int r ) { attributeGrid . insertRowAttribute ( attributes , r ) ; updateListenersOnAttributeChange ( - 1 , r ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notifies all interested listeners of an update to this model . [CODESPLIT] protected void updateListenersOnAttributeChange ( int col , int row ) { TextTableEvent event = new TextTableEvent ( this , row , col , true ) ; for ( TextTableListener listener : listeners ) { listener . changedUpdate ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a string to an integer . The string must be a valid integer or the result will be zero . [CODESPLIT] public static int toInteger ( String s ) { try { return Integer . parseInt ( s ) ; } catch ( NumberFormatException e ) { // Exception noted so can be ignored. e = null ; return 0 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a string to a date . The string must be a date in the correct format or this method will return null . [CODESPLIT] public static Date toDate ( String s ) { // Build a date formatter using the format specified by dateFormat DateFormat dateFormatter = new SimpleDateFormat ( dateFormat ) ; try { return dateFormatter . parse ( s ) ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check that a string is a date in the format specified by dateFormat . [CODESPLIT] public static boolean isDate ( String s ) { // Build a date formatter using the format specified by dateFormat DateFormat dateFormatter = new SimpleDateFormat ( dateFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that a string is a time in the format specified by timeFormat . [CODESPLIT] public static boolean isTime ( String s ) { // Build a time formatter using the format specified by timeFormat DateFormat dateFormatter = new SimpleDateFormat ( timeFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that a string is a datetime in the format specified by dateTimeFormat . [CODESPLIT] public static boolean isDateTime ( String s ) { DateFormat dateFormatter = new SimpleDateFormat ( dateTimeFormat ) ; try { dateFormatter . parse ( s ) ; return true ; } catch ( ParseException e ) { // Exception noted so can be ignored. e = null ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a token source on a string . [CODESPLIT] public static TokenSource getTokenSourceForString ( String stringToTokenize ) { SimpleCharStream inputStream = new SimpleCharStream ( new StringReader ( stringToTokenize ) , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a token source on a file . [CODESPLIT] public static TokenSource getTokenSourceForFile ( File file ) throws FileNotFoundException { // Create a token source to load the model rules from. Reader ins = new FileReader ( file ) ; SimpleCharStream inputStream = new SimpleCharStream ( ins , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a token source on an input stream . [CODESPLIT] public static Source getTokenSourceForInputStream ( InputStream in ) { SimpleCharStream inputStream = new SimpleCharStream ( in , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; return new TokenSource ( tokenManager ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves and removes the head token or <tt > null< / tt > if there are no more tokens . [CODESPLIT] public Token poll ( ) { if ( token . next == null ) { token . next = tokenManager . getNextToken ( ) ; } token = token . next ; return token ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves but does not remove the head token returning <tt > null< / tt > if there are no more tokens . [CODESPLIT] public Token peek ( ) { if ( token . next == null ) { token . next = tokenManager . getNextToken ( ) ; } return token . next ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void apply ( WAMInstruction next ) { shift ( next ) ; // Anonymous or singleton variable optimizations. if ( ( UnifyVar == next . getMnemonic ( ) ) && isVoidVariable ( next ) ) { if ( state != State . UVE ) { voidCount = 0 ; } discard ( ( voidCount == 0 ) ? 1 : 2 ) ; WAMInstruction unifyVoid = new WAMInstruction ( UnifyVoid , WAMInstruction . REG_ADDR , ( byte ) ++ voidCount ) ; shift ( unifyVoid ) ; state = State . UVE ; /*log.fine(next + \" -> \" + unifyVoid);*/ } else if ( ( SetVar == next . getMnemonic ( ) ) && isVoidVariable ( next ) ) { if ( state != State . SVE ) { voidCount = 0 ; } discard ( ( voidCount == 0 ) ? 1 : 2 ) ; WAMInstruction setVoid = new WAMInstruction ( SetVoid , WAMInstruction . REG_ADDR , ( byte ) ++ voidCount ) ; shift ( setVoid ) ; state = State . SVE ; /*log.fine(next + \" -> \" + setVoid);*/ } else if ( ( GetVar == next . getMnemonic ( ) ) && ( next . getMode1 ( ) == WAMInstruction . REG_ADDR ) && ( next . getReg1 ( ) == next . getReg2 ( ) ) ) { discard ( 1 ) ; /*log.fine(next + \" -> eliminated\");*/ state = State . NM ; } // Constant optimizations. else if ( ( UnifyVar == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; FunctorName functorName = interner . getDeinternedFunctorName ( next . getFunctorNameReg1 ( ) ) ; WAMInstruction unifyConst = new WAMInstruction ( UnifyConstant , functorName ) ; shift ( unifyConst ) ; flush ( ) ; state = State . NM ; /*log.fine(next + \" -> \" + unifyConst);*/ } else if ( ( GetStruc == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; state = State . NM ; /*log.fine(next + \" -> eliminated\");*/ } else if ( ( GetStruc == next . getMnemonic ( ) ) && isConstant ( next ) && ! isNonArg ( next ) ) { discard ( 1 ) ; WAMInstruction getConst = new WAMInstruction ( GetConstant , next . getMode1 ( ) , next . getReg1 ( ) , next . getFn ( ) ) ; shift ( getConst ) ; flush ( ) ; state = State . NM ; /*log.fine(next + \" -> \" + getConst);*/ } else if ( ( PutStruc == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; state = State . NM ; /*log.fine(next + \" -> eliminated\");*/ } else if ( ( PutStruc == next . getMnemonic ( ) ) && isConstant ( next ) && ! isNonArg ( next ) ) { discard ( 1 ) ; WAMInstruction putConst = new WAMInstruction ( PutConstant , next . getMode1 ( ) , next . getReg1 ( ) , next . getFn ( ) ) ; shift ( putConst ) ; state = State . NM ; /*log.fine(next + \" -> \" + putConst);*/ } else if ( ( SetVal == next . getMnemonic ( ) ) && isConstant ( next ) && isNonArg ( next ) ) { discard ( 1 ) ; FunctorName functorName = interner . getDeinternedFunctorName ( next . getFunctorNameReg1 ( ) ) ; WAMInstruction setConst = new WAMInstruction ( SetConstant , functorName ) ; shift ( setConst ) ; flush ( ) ; state = State . NM ; /*log.fine(next + \" -> \" + setConst);*/ } // List optimizations. else if ( ( GetStruc == next . getMnemonic ( ) ) && ( \"cons\" . equals ( next . getFn ( ) . getName ( ) ) && ( next . getFn ( ) . getArity ( ) == 2 ) ) ) { discard ( 1 ) ; WAMInstruction getList = new WAMInstruction ( GetList , next . getMode1 ( ) , next . getReg1 ( ) ) ; shift ( getList ) ; state = State . NM ; /*log.fine(next + \" -> \" + getList);*/ } else if ( ( PutStruc == next . getMnemonic ( ) ) && ( \"cons\" . equals ( next . getFn ( ) . getName ( ) ) && ( next . getFn ( ) . getArity ( ) == 2 ) ) ) { discard ( 1 ) ; WAMInstruction putList = new WAMInstruction ( PutList , next . getMode1 ( ) , next . getReg1 ( ) ) ; shift ( putList ) ; state = State . NM ; /*log.fine(next + \" -> \" + putList);*/ } // Default. else { state = State . NM ; flush ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the term argument to an instruction was a constant . [CODESPLIT] public boolean isConstant ( WAMInstruction instruction ) { Integer name = instruction . getFunctorNameReg1 ( ) ; if ( name != null ) { FunctorName functorName = interner . getDeinternedFunctorName ( name ) ; if ( functorName . getArity ( ) == 0 ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the term argument to an instruction was a singleton non - argument position variable . The variable must also be non - permanent to ensure that singleton variables in queries are created . [CODESPLIT] private boolean isVoidVariable ( WAMInstruction instruction ) { SymbolKey symbolKey = instruction . getSymbolKeyReg1 ( ) ; if ( symbolKey != null ) { Integer count = ( Integer ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_VAR_OCCURRENCE_COUNT ) ; Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_VAR_NON_ARG ) ; Integer allocation = ( Integer ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_ALLOCATION ) ; boolean singleton = ( count != null ) && count . equals ( 1 ) ; boolean nonArgPosition = ( nonArgPositionOnly != null ) && TRUE . equals ( nonArgPositionOnly ) ; boolean permanent = ( allocation != null ) && ( ( byte ) ( ( allocation & 0xff00 ) >> 8 ) == WAMInstruction . STACK_ADDR ) ; if ( singleton && nonArgPosition && ! permanent ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the term argument to an instruction was in a non - argument position . [CODESPLIT] private boolean isNonArg ( WAMInstruction instruction ) { SymbolKey symbolKey = instruction . getSymbolKeyReg1 ( ) ; if ( symbolKey != null ) { Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( symbolKey , SymbolTableKeys . SYMKEY_FUNCTOR_NON_ARG ) ; if ( TRUE . equals ( nonArgPositionOnly ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] protected TermBuilder < com . thesett . aima . logic . fol . Term > createCompoundBuilder ( ) { return new LojixTermBuilder ( interner ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Renders the table . [CODESPLIT] public void renderTable ( ) { for ( int i = 0 ; i < tableModel . getRowCount ( ) ; i ++ ) { int colOffset = 0 ; for ( int j = 0 ; j < tableModel . getColumnCount ( ) ; j ++ ) { String valueToPrint = tableModel . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? \"\" : valueToPrint ; gridModel . insert ( valueToPrint , colOffset , i ) ; AttributeSet attributes = tableModel . getAttributeAt ( j , i ) ; int columnSize = tableModel . getMaxColumnSize ( j ) ; if ( attributes != null ) { for ( int k = 0 ; k < columnSize ; k ++ ) { gridModel . insertAttribute ( attributes , colOffset + k , i ) ; } } // Pad spaces up to the column width if the contents are shorter. int spaces = columnSize - valueToPrint . length ( ) ; while ( spaces > 0 ) { gridModel . insert ( \" \" , colOffset + valueToPrint . length ( ) + spaces -- - 1 , i ) ; } // Shift to the next column. colOffset += columnSize ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an iterator over the child terms if there are any . Only functors and clauses are compound and build across a list of child arguments . [CODESPLIT] public Iterator < Operator < Term > > getChildren ( boolean reverse ) { if ( ( traverser != null ) && ( traverser instanceof ClauseTraverser ) ) { return ( ( ClauseTraverser ) traverser ) . traverse ( this , reverse ) ; } else { LinkedList < Operator < Term >> resultList = null ; if ( ! reverse ) { resultList = new LinkedList < Operator < Term > > ( ) ; } else { resultList = new StackQueue < Operator < Term > > ( ) ; } if ( head != null ) { resultList . add ( head ) ; } if ( body != null ) { for ( Term bodyTerm : body ) { resultList . add ( bodyTerm ) ; } } return resultList . iterator ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a clone of the term converting its variables to refer directly to their storage cells . [CODESPLIT] public Clause queryConversion ( ) { Clause copy = ( Clause ) super . queryConversion ( ) ; if ( head != null ) { copy . head = head . queryConversion ( ) ; } if ( body != null ) { copy . body = new Functor [ body . length ] ; for ( int i = 0 ; i < body . length ; i ++ ) { copy . body [ i ] = body [ i ] . queryConversion ( ) ; } } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof ClauseVisitor ) { ( ( ClauseVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Clause acceptTransformer ( TermTransformer transformer ) { Clause result ; if ( transformer instanceof ClauseTransformer ) { result = ( ( ClauseTransformer ) transformer ) . transform ( this ) ; } else { result = ( Clause ) super . acceptTransformer ( transformer ) ; } if ( head != null ) { result . head = ( Functor ) head . acceptTransformer ( transformer ) ; } if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { result . body [ i ] = ( Functor ) body [ i ] . acceptTransformer ( transformer ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Works out all the possible successors by applying all the operators returned by the { @link Traversable#validOperators } method . [CODESPLIT] public Iterator < Successor < O > > successors ( boolean reverse ) { return new Filterator < Operator < O > , Successor < O > > ( validOperators ( reverse ) , new Function < Operator < O > , Successor < O > > ( ) { public Successor < O > apply ( Operator operator ) { return new Successor < O > ( getChildStateForOperator ( operator ) , operator , costOf ( operator ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reports whether or not this term is a ground term . Constants ( functors of arity zero ) and numbers are ground terms as are functors all of the arguments of which are ground term . [CODESPLIT] public boolean isGround ( ) { for ( int i = 0 ; i < arity ; i ++ ) { if ( ! arguments [ i ] . isGround ( ) ) { return false ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the argument within the functor with the specified index . [CODESPLIT] public Term getArgument ( int index ) { if ( ( arguments == null ) || ( index > ( arguments . length - 1 ) ) ) { return null ; } else { return arguments [ index ] ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares this term for structural equality with another . Two terms are structurally equal if they are the same functor with the same arguments or are the same unbound variable or the bound values of the left or right variable operands are structurally equal . Structural equality is a stronger equality than unification and unlike unification it does not produce any variable bindings . Two unified terms will always be structurally equal . [CODESPLIT] public boolean structuralEquals ( Term term ) { Term comparator = term . getValue ( ) ; if ( this == comparator ) { return true ; } if ( ( comparator == null ) || ! ( getClass ( ) . isAssignableFrom ( comparator . getClass ( ) ) ) ) { return false ; } Functor functor = ( Functor ) comparator ; if ( ( arity != functor . arity ) || ( name != functor . name ) ) { return false ; } // Check the arguments of this functor and the comparator for structural equality. boolean passedArgCheck = true ; if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { Term leftArg = arguments [ i ] ; Term rightArg = functor . arguments [ i ] ; if ( ! leftArg . structuralEquals ( rightArg ) ) { passedArgCheck = false ; break ; } } } return passedArgCheck ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Provides an iterator over the child terms if there are any . Only functors are compound and built across a list of child arguments . [CODESPLIT] public Iterator < Operator < Term > > getChildren ( boolean reverse ) { if ( ( traverser != null ) && ( traverser instanceof FunctorTraverser ) ) { return ( ( FunctorTraverser ) traverser ) . traverse ( this , reverse ) ; } else { if ( arguments == null ) { return new LinkedList < Operator < Term > > ( ) . iterator ( ) ; } else if ( ! reverse ) { return Arrays . asList ( ( Operator < Term > [ ] ) arguments ) . iterator ( ) ; } else { List < Operator < Term >> argList = new LinkedList < Operator < Term > > ( ) ; for ( int i = arity - 1 ; i >= 0 ; i -- ) { argList . add ( arguments [ i ] ) ; } return argList . iterator ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Makes a clone of the term converting its variables to refer directly to their storage cells . [CODESPLIT] public Functor queryConversion ( ) { /*log.fine(\"public Functor queryConversion(): called)\");*/ Functor copy = ( Functor ) super . queryConversion ( ) ; if ( arguments != null ) { copy . arguments = new Term [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; i ++ ) { copy . arguments [ i ] = arguments [ i ] . queryConversion ( ) ; } } return copy ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void accept ( TermVisitor visitor ) { if ( visitor instanceof FunctorVisitor ) { ( ( FunctorVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public Functor acceptTransformer ( TermTransformer transformer ) { Functor result ; if ( transformer instanceof FunctorTransformer ) { result = ( ( FunctorTransformer ) transformer ) . transform ( this ) ; } else { result = ( Functor ) super . acceptTransformer ( transformer ) ; } if ( arguments != null ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { result . arguments [ i ] = arguments [ i ] . acceptTransformer ( transformer ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a string representation of this functors arguments mostly used for debugging purposes . [CODESPLIT] protected String toStringArguments ( ) { String result = \"\" ; if ( arity > 0 ) { result += \"[ \" ; for ( int i = 0 ; i < arity ; i ++ ) { Term nextArg = arguments [ i ] ; result += ( ( nextArg != null ) ? nextArg . toString ( ) : \"<null>\" ) + ( ( i < ( arity - 1 ) ) ? \", \" : \" \" ) ; } result += \" ]\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a query to retrieve the summary . This do not have any group by element [CODESPLIT] public < T extends MeasureAppender > T retrieveSummary ( SchemaDefinition schemaDefinition , Class < T > resultClazz , QueryParameter queryParameter ) throws NovieRuntimeException { final SqlQueryBuilder < T > sqlQueryBuilder = new SqlQueryBuilder < T > ( schemaDefinition , resultClazz , queryParameter . partialCopy ( QueryParameterKind . GROUPS , QueryParameterKind . PAGE ) ) ; List < T > result = executeQuery ( sqlQueryBuilder ) ; if ( result . isEmpty ( ) ) { throw new NovieRuntimeException ( \"Summary doesn't return any result.\" ) ; } if ( result . size ( ) > 1 ) { throw new NovieRuntimeException ( \"Summary returns more than one result.\" ) ; } return result . get ( 0 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a query to retrieve the records . [CODESPLIT] public < T extends MeasureAppender > List < T > retrieveRecords ( SchemaDefinition schemaDefinition , Class < T > resultClazz , QueryParameter queryParameter ) throws NovieRuntimeException { final SqlQueryBuilder < T > sqlQueryBuilder = new SqlQueryBuilder < T > ( schemaDefinition , resultClazz , queryParameter ) ; return executeQuery ( sqlQueryBuilder ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Private methode called by the public ones to effectively run the query . [CODESPLIT] private < T extends MeasureAppender > List < T > executeQuery ( final SqlQueryBuilder < T > sqlQueryBuilder ) throws NovieRuntimeException { sqlQueryBuilder . buildQuery ( ) ; final String queryString = sqlQueryBuilder . getQueryString ( ) ; LOG . debug ( queryString ) ; long beforeQuery = System . currentTimeMillis ( ) ; List < T > returnValue = jdbcTemplate . query ( queryString , sqlQueryBuilder . getMapSqlParameterSource ( ) , sqlQueryBuilder ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( \"SQL query successfully ran in \" + ( System . currentTimeMillis ( ) - beforeQuery ) + \"ms.\" ) ; } if ( LOG . isDebugEnabled ( ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( Entry < String , Object > e : sqlQueryBuilder . getMapSqlParameterSource ( ) . getValues ( ) . entrySet ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( \",\" ) ; } sb . append ( e . getKey ( ) ) ; sb . append ( \"=\" ) ; sb . append ( e . getValue ( ) ) ; } sb . insert ( 0 , \"Parameters [\" ) ; sb . append ( \"]\" ) ; LOG . debug ( sb . toString ( ) ) ; } return returnValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onReset ( WAMResolvingMachineDPI dpi ) { internalRegisters = new InternalRegisterBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , false ) ; internalRegisters . addPropertyChangeListener ( registerSetMonitor ) ; internalRegisters . addPropertyChangeListener ( breakpointMonitor ) ; internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters = new InternalMemoryLayoutBean ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) ; layoutRegisters . addPropertyChangeListener ( layoutMonitor ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onCodeUpdate ( WAMResolvingMachineDPI dpi , int start , int length ) { ByteBuffer codeBuffer = dpi . getCodeBuffer ( start , length ) ; byteCodeMonitor . onCodeUpdate ( codeBuffer , start , length , dpi . getVariableAndFunctorInterner ( ) , dpi ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onExecute ( WAMResolvingMachineDPI dpi ) { internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onStep ( WAMResolvingMachineDPI dpi ) { internalRegisters . updateRegisters ( dpi . getInternalRegisters ( ) ) ; layoutRegisters . updateRegisters ( dpi . getMemoryLayout ( ) ) ; breakpointMonitor . pause ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Disassembles the instructions from the specified byte buffer starting at a given location ( ip ) . An interner for the functor names encountered in the instruction buffer must also be supplied in order to look up the functor names by encoded value . [CODESPLIT] public static SizeableList < WAMInstruction > disassemble ( int start , int length , ByteBuffer codeBuf , VariableAndFunctorInterner interner , WAMCodeView codeView ) { SizeableList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; int ip = start ; while ( ip < ( start + length ) ) { // Decode the instruction and its arguments. byte iCode = codeBuf . get ( ip ) ; WAMInstruction instruction = new WAMInstruction ( iCode ) ; instruction . mnemonic . disassembleArguments ( instruction , ip , codeBuf , interner ) ; // Restore any label on the instruction. Integer label = codeView . getNameForAddress ( ip ) ; if ( label != null ) { FunctorName name = interner . getDeinternedFunctorName ( label ) ; if ( name instanceof WAMLabel ) { instruction . label = ( WAMLabel ) name ; } } result . add ( instruction ) ; ip += instruction . mnemonic . length ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes out the instruction plus arguments in the byte code format to the specified location within a code buffer . [CODESPLIT] public void emmitCode ( ByteBuffer codeBuffer , WAMMachine machine ) throws LinkageException { mnemonic . emmitCode ( this , codeBuffer , machine ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public T getDefaultInstance ( ) { Object result ; // For basic Java types return the standard default value. For others, try the default constructor. switch ( type ) { case BOOLEAN : result = DEFAULT_BOOLEAN ; break ; case CHARACTER : result = DEFAULT_CHARACTER ; break ; case BYTE : result = DEFAULT_BYTE ; break ; case SHORT : result = DEFAULT_SHORT ; break ; case INTEGER : result = DEFAULT_INTEGER ; break ; case LONG : result = DEFAULT_LONG ; break ; case FLOAT : result = DEFAULT_FLOAT ; break ; case DOUBLE : result = DEFAULT_DOUBLE ; break ; case OTHER : default : try { result = underlyingClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } break ; } return ( T ) result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public T getRandomInstance ( ) throws RandomInstanceNotSupportedException { Object result = null ; // For basic Java types return the standard default value. For others, try the default constructor. switch ( type ) { case BOOLEAN : result = RANDOM . nextBoolean ( ) ; break ; case CHARACTER : result = ( char ) RANDOM . nextInt ( ) ; break ; case BYTE : result = ( byte ) RANDOM . nextInt ( ) ; break ; case SHORT : result = ( short ) RANDOM . nextInt ( ) ; break ; case INTEGER : result = RANDOM . nextInt ( ) ; break ; case LONG : result = RANDOM . nextLong ( ) ; break ; case FLOAT : result = RANDOM . nextFloat ( ) ; break ; case DOUBLE : result = RANDOM . nextDouble ( ) ; break ; case OTHER : default : if ( String . class . equals ( underlyingClass ) ) { byte [ ] bytes = new byte [ 6 ] ; RANDOM . nextBytes ( bytes ) ; result = new String ( bytes ) ; } break ; } if ( result != null ) { return ( T ) result ; } else { throw new RandomInstanceNotSupportedException ( \"Type does not support random instance creation.\" , null ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the basic type of this type depending on the class . [CODESPLIT] private void setBasicType ( Class c ) { if ( Boolean . class . equals ( c ) ) { type = BasicTypes . BOOLEAN ; } else if ( Character . class . equals ( c ) ) { type = BasicTypes . CHARACTER ; } else if ( Byte . class . equals ( c ) ) { type = BasicTypes . BYTE ; } else if ( Short . class . equals ( c ) ) { type = BasicTypes . SHORT ; } else if ( Integer . class . equals ( c ) ) { type = BasicTypes . INTEGER ; } else if ( Long . class . equals ( c ) ) { type = BasicTypes . LONG ; } else if ( Float . class . equals ( c ) ) { type = BasicTypes . FLOAT ; } else if ( Double . class . equals ( c ) ) { type = BasicTypes . DOUBLE ; } else { type = BasicTypes . OTHER ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Consults an input stream reading first order logic clauses from it and inserting them into the resolvers knowledge base . [CODESPLIT] public void consultInputStream ( InputStream stream ) throws SourceCodeException { // Create a token source to read from the specified input stream. Source < Token > tokenSource = TokenSource . getTokenSourceForInputStream ( stream ) ; getParser ( ) . setTokenSource ( tokenSource ) ; // Consult the type checking rules and add them to the knowledge base. while ( true ) { Sentence < S > sentence = getParser ( ) . parse ( ) ; if ( sentence == null ) { break ; } getCompiler ( ) . compile ( sentence ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints all of the logic variables in the results of a query . [CODESPLIT] public String printSolution ( Iterable < Variable > solution ) { String result = \"\" ; for ( Variable var : solution ) { result += printVariableBinding ( var ) + \"\\n\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints all of the logic variables in the results of a query . [CODESPLIT] public String printSolution ( Map < String , Variable > variables ) { String result = \"\" ; for ( Map . Entry < String , Variable > entry : variables . entrySet ( ) ) { result += printVariableBinding ( entry . getValue ( ) ) + \"\\n\" ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a variable binding in the form Var = value . [CODESPLIT] public String printVariableBinding ( Term var ) { return var . toString ( getInterner ( ) , true , false ) + \" = \" + var . getValue ( ) . toString ( getInterner ( ) , false , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Transforms an iterator over sets of variable bindings resulting from a query to an iterator over a map from the string name of variables to their bindings for the same sequence of query solutions . [CODESPLIT] public Iterable < Map < String , Variable > > expandResultSetToMap ( Iterator < Set < Variable > > solutions ) { return new Filterator < Set < Variable > , Map < String , Variable > > ( solutions , new Function < Set < Variable > , Map < String , Variable > > ( ) { public Map < String , Variable > apply ( Set < Variable > variables ) { Map < String , Variable > results = new HashMap < String , Variable > ( ) ; for ( Variable var : variables ) { String varName = getInterner ( ) . getVariableName ( var . getName ( ) ) ; results . put ( varName , var ) ; } return results ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void setOperator ( String operatorName , int priority , OpSymbol . Associativity associativity ) { parser . setOperator ( operatorName , priority , associativity ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "A dedicated thread loop for reading the stream and sending incoming packets to the appropriate router . [CODESPLIT] public void run ( ) { try { readStream ( ) ; } catch ( EOFException eof ) { // Normal disconnect } catch ( SocketException se ) { // Do nothing if the exception occured while shutting down the // component otherwise // log the error and try to establish a new connection if ( ! shutdown ) { component . getManager ( ) . getLog ( ) . error ( se ) ; component . connectionLost ( ) ; } } catch ( XmlPullParserException ie ) { component . getManager ( ) . getLog ( ) . error ( ie ) ; } catch ( Exception e ) { component . getManager ( ) . getLog ( ) . warn ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Read the incoming stream until it ends . [CODESPLIT] private void readStream ( ) throws Exception { while ( ! shutdown ) { Element doc = reader . parseDocument ( ) . getRootElement ( ) ; if ( doc == null ) { // Stop reading the stream since the server has sent an end of // stream element and // probably closed the connection return ; } Packet packet ; String tag = doc . getName ( ) ; if ( \"message\" . equals ( tag ) ) { packet = new Message ( doc ) ; } else if ( \"presence\" . equals ( tag ) ) { packet = new Presence ( doc ) ; } else if ( \"iq\" . equals ( tag ) ) { packet = getIQ ( doc ) ; } else { throw new XmlPullParserException ( \"Unknown packet type was read: \" + tag ) ; } // Request the component to process the received packet component . processPacket ( packet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Initializer for type 1 UUIDs . Creates random generator and genenerates the node portion of the UUID using the IP address . [CODESPLIT] private static synchronized void initializeForType1 ( ) { if ( type1Initialized == true ) { return ; } // note that secure random is very slow the first time // it is used; consider switching to a standard random RANDOM = new SecureRandom ( ) ; _seq = ( short ) RANDOM . nextInt ( MAX_14BIT ) ; byte [ ] ip = null ; try { ip = InetAddress . getLocalHost ( ) . getAddress ( ) ; } catch ( IOException ioe ) { throw new NestableRuntimeException ( ioe ) ; } IP = new byte [ 6 ] ; RANDOM . nextBytes ( IP ) ; System . arraycopy ( ip , 0 , IP , 2 , ip . length ) ; type1Initialized = true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Creates a type 1 UUID [CODESPLIT] public static byte [ ] next ( ) { if ( type1Initialized == false ) { initializeForType1 ( ) ; } // set ip addr byte [ ] uuid = new byte [ 16 ] ; System . arraycopy ( IP , 0 , uuid , 10 , IP . length ) ; // Set time info. Have to do this processing within a synchronized // block because of the statics... long now = 0 ; synchronized ( Type1UUID . class ) { // Get the time to use for this uuid. This method has the side // effect of modifying the clock sequence, as well. now = getTime ( ) ; // Insert the resulting clock sequence into the uuid uuid [ IDX_TIME_SEQ ] = ( byte ) ( ( _seq & 0x3F00 ) >>> 8 ) ; uuid [ IDX_VARIATION ] |= 0x80 ; uuid [ IDX_TIME_SEQ + 1 ] = ( byte ) ( _seq & 0xFF ) ; } // have to break up time because bytes are spread through uuid byte [ ] timeBytes = toBytes ( now ) ; // Copy time low System . arraycopy ( timeBytes , TS_TIME_LO_IDX , uuid , IDX_TIME_LO , TS_TIME_LO_LEN ) ; // Copy time mid System . arraycopy ( timeBytes , TS_TIME_MID_IDX , uuid , IDX_TIME_MID , TS_TIME_MID_LEN ) ; // Copy time hi System . arraycopy ( timeBytes , TS_TIME_HI_IDX , uuid , IDX_TIME_HI , TS_TIME_HI_LEN ) ; // Set version (time-based) uuid [ IDX_TYPE ] |= TYPE_TIME_BASED ; // 0001 0000 return uuid ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "package - visibility for testing [CODESPLIT] static long getTime ( ) { if ( RANDOM == null ) initializeForType1 ( ) ; long newTime = getUUIDTime ( ) ; if ( newTime <= _lastMillis ) { incrementSequence ( ) ; newTime = getUUIDTime ( ) ; } _lastMillis = newTime ; return newTime ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the appropriately modified timestamep for the UUID . Must be called from a synchronized block . [CODESPLIT] private static long getUUIDTime ( ) { if ( _currentMillis != System . currentTimeMillis ( ) ) { _currentMillis = System . currentTimeMillis ( ) ; _counter = 0 ; // reset counter } // check to see if we have created too many uuid's for this timestamp if ( _counter + 1 >= MILLI_MULT ) { // Original algorithm threw exception. Seemed like overkill. // Let's just increment the timestamp instead and start over... _currentMillis ++ ; _counter = 0 ; } // calculate time as current millis plus offset times 100 ns ticks long currentTime = ( _currentMillis + GREG_OFFSET ) * MILLI_MULT ; // return the uuid time plus the artificial tick counter incremented return currentTime + _counter ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stops the playing / indicates that the playing stopped . <p > this method has no effect if runsInPlay is enabled in the constructor . <br > < / p > [CODESPLIT] public void stopMusicPlayback ( ) { if ( runsInPlay || ! isPlaying ) return ; lock . lock ( ) ; try { if ( blockRequest != null ) blockRequest . signal ( ) ; } finally { lock . unlock ( ) ; } isPlaying = false ; stopSound ( ) ; endedSound ( ) ; rollBackToDefault ( ) ; super . stop ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks if the trackInfo is an update and fires the appropriate Event . This method should not be called without an active playlist or an NullPointerException will be thrown . this method : <br > - fires nothing if the trackInfo equals the current trackInfo . <br > - fires an trackInfoUpdate if the trackInfo contains information not found in the current . <br > [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public void updateCurrentTrackInfo ( TrackInfo trackInfo ) { if ( playlist . getCurrent ( ) . equals ( trackInfo ) || playlist . getCurrent ( ) . isNew ( trackInfo ) ) return ; this . playlist = playlist . update ( playlist . getCurrent ( ) , trackInfo ) ; trackInfoUpdate ( playlist , trackInfo ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call this method if the trackInfo object in the playlist was updated . Only the trackinfo object will be sent via Event [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public void trackInfoUpdate ( Playlist playlist , TrackInfo info ) { this . playlist = playlist ; updatePlayInfo ( info ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fires an update event which notifies that parameters have changed [CODESPLIT] @ Override public void updatePlayInfo ( Volume volume ) { if ( this . volume . equals ( volume ) ) return ; this . volume = volume ; MusicHelper . super . updatePlayInfo ( volume ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "updates the Info about the current song [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public void updatePlayInfo ( Playlist playlist , Progress progress , Volume volume ) { if ( playlist != null ) this . playlist = playlist ; if ( progress != null ) this . progress = progress ; if ( volume != null ) this . volume = volume ; updatePlayInfo ( playlist , progress , null , volume ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "fires an update event which notifies that parameters have changed [CODESPLIT] @ Override public void updatePlayInfo ( Playlist playlist , Progress progress , TrackInfo trackInfo , Volume volume ) { if ( playlist != null ) this . playlist = playlist ; if ( progress != null ) this . progress = progress ; if ( volume != null ) this . volume = volume ; MusicHelper . super . updatePlayInfo ( playlist , progress , null , volume ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called when an object wants to get a Resource . <p > Don t use the Resources provided as arguments they are just the requests . There is a timeout after 1 second . < / p > [CODESPLIT] @ Override public List < ResourceModel > provideResource ( List < ? extends ResourceModel > resources , Optional < EventModel > event ) { return informationProvider . provideResource ( resources , event ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "method that uses the data from the OutputExtensions to generate a final output that will then be rendered . [CODESPLIT] @ Override public void renderFinalOutput ( List < T > data , EventModel eventModel ) { if ( StartMusicRequest . verify ( eventModel , capabilities , this , activators ) ) { if ( isOutputRunning ( ) ) { playerError ( PlayerError . ERROR_ALREADY_PLAYING , eventModel . getSource ( ) ) ; } else { handleEventRequest ( eventModel ) ; } } else if ( eventModel . getListResourceContainer ( ) . providesResource ( Collections . singletonList ( MusicUsageResource . ID ) ) ) { if ( isOutputRunning ( ) ) { eventModel . getListResourceContainer ( ) . provideResource ( MusicUsageResource . ID ) . forEach ( resourceModel -> playerError ( PlayerError . ERROR_ALREADY_PLAYING , resourceModel . getProvider ( ) ) ) ; } else { handleResourceRequest ( eventModel ) ; } } else { handleCommands ( eventModel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles the a request to start playing music via Resource [CODESPLIT] private void handleResourceRequest ( EventModel eventModel ) { if ( MusicUsageResource . isPermanent ( eventModel ) ) { ResourceModel resourceModel = eventModel . getListResourceContainer ( ) . provideResource ( MusicUsageResource . ID ) . stream ( ) . filter ( MusicUsageResource :: isPermanent ) . findAny ( ) . orElse ( null ) ; //should not happen //a partially applied function which takes an Identification an returns an Optional StartMusicRequest Function < Identification , Optional < StartMusicRequest > > getStartMusicRequest = own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own ) ; //if we have a trackInfo we create it with the trackInfo as a parameter getStartMusicRequest = TrackInfoResource . getTrackInfo ( eventModel ) . map ( trackInfo -> ( Function < Identification , Optional < StartMusicRequest > > ) own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own , trackInfo ) ) . orElse ( getStartMusicRequest ) ; //if we have a trackInfo we create it with the playlist as a parameter getStartMusicRequest = PlaylistResource . getPlaylist ( eventModel ) . map ( playlist -> ( Function < Identification , Optional < StartMusicRequest > > ) own -> StartMusicRequest . createStartMusicRequest ( resourceModel . getProvider ( ) , own , playlist ) ) . orElse ( getStartMusicRequest ) ; //composes a new Function which appends the Volume to the result getStartMusicRequest = getStartMusicRequest . andThen ( VolumeResource . getVolume ( eventModel ) . flatMap ( volume -> IdentificationManagerM . getInstance ( ) . getIdentification ( this ) . map ( identification -> new VolumeResource ( identification , volume ) ) ) . map ( resource -> ( Function < Optional < StartMusicRequest > , Optional < StartMusicRequest > > ) opt -> opt . map ( event -> ( StartMusicRequest ) event . addResource ( resource ) ) ) . orElse ( Function . identity ( ) ) :: apply ) ; IdentificationManagerM . getInstance ( ) . getIdentification ( this ) . flatMap ( getStartMusicRequest :: apply ) . ifPresent ( this :: fire ) ; } else { play ( eventModel ) ; if ( ! runsInPlay ) { blockRequest = lock . newCondition ( ) ; lock . lock ( ) ; try { blockRequest . await ( 10 , TimeUnit . MINUTES ) ; } catch ( InterruptedException e ) { debug ( \"interrupted\" , e ) ; } finally { lock . unlock ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles the commands encoded as Resources / EventIds [CODESPLIT] private void handleCommands ( EventModel eventModel ) { Consumer < Runnable > checkOrCall = runnable -> { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { runnable . run ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> runnable . run ( ) ) ; } } ; if ( eventModel . containsDescriptor ( MuteEvent . ID ) ) { checkOrCall . accept ( this :: mute ) ; } if ( eventModel . containsDescriptor ( UnMuteEvent . ID ) ) { checkOrCall . accept ( this :: unMute ) ; } if ( eventModel . containsDescriptor ( StopEvent . ID ) ) { checkOrCall . accept ( this :: stopMusicPlayback ) ; } if ( StopMusic . verify ( eventModel , this ) ) { stopMusicPlayback ( ) ; } if ( PlayerCommand . verify ( eventModel , this ) ) { getCommandHandler ( ) . handleCommandResources ( eventModel ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles the a request to start playing music via Event [CODESPLIT] private void handleEventRequest ( EventModel eventModel ) { playingThread = submit ( ( Runnable ) ( ) -> { //noinspection RedundantIfStatement if ( runsInPlay ) { isRunning = false ; } else { isRunning = true ; } isPlaying = true ; fireStartMusicRequest ( eventModel ) ; } ) . thenRun ( ( ) -> play ( eventModel ) ) . thenRun ( ( ) -> { if ( runsInPlay ) { isRunning = false ; isPlaying = false ; endedSound ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method will be called to create and fire the StartMusicRequest [CODESPLIT] protected void fireStartMusicRequest ( EventModel eventModel ) { Optional < Playlist > playlist = PlaylistResource . getPlaylist ( eventModel ) ; Optional < Progress > progress = ProgressResource . getProgress ( eventModel ) ; Optional < TrackInfo > trackInfo = TrackInfoResource . getTrackInfo ( eventModel ) ; Optional < Volume > volume = VolumeResource . getVolume ( eventModel ) ; startedSound ( playlist . orElse ( null ) , progress . orElse ( null ) , trackInfo . orElse ( null ) , volume . orElse ( null ) , isUsingJava ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets every information into its default state ( playlist volume etc ... ) [CODESPLIT] public void rollBackToDefault ( ) { playlist = new Playlist ( new ArrayList <> ( ) ) ; volume = Volume . createVolume ( 50 ) . orElse ( null ) ; progress = new Progress ( 0 , 0 ) ; playbackState = PlaybackState . PLAY ; if ( playingThread != null ) playingThread . cancel ( true ) ; isRunning = false ; isPlaying = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the reader in order to be used . The reader is initialized during the first connection and when reconnecting due to an abruptly disconnection . [CODESPLIT] protected void init ( ) { done = false ; connectionID = null ; readerThread = new Thread ( ) { public void run ( ) { parsePackets ( this ) ; } } ; readerThread . setName ( \"Smack Packet Reader (\" + connection . connectionCounterValue + \")\" ) ; readerThread . setDaemon ( true ) ; // Create an executor to deliver incoming packets to listeners. We'll // use a single // thread with an unbounded queue. listenerExecutor = Executors . newSingleThreadExecutor ( new ThreadFactory ( ) { public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable , \"Smack Listener Processor (\" + connection . connectionCounterValue + \")\" ) ; thread . setDaemon ( true ) ; return thread ; } } ) ; resetParser ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts the packet reader thread and returns once a connection to the server has been established . A connection will be attempted for a maximum of five seconds . An XMPPException will be thrown if the connection fails . [CODESPLIT] synchronized public void startup ( ) throws XMPPException { final List < Exception > errors = new LinkedList < Exception > ( ) ; AbstractConnectionListener connectionErrorListener = new AbstractConnectionListener ( ) { @ Override public void connectionClosedOnError ( Exception e ) { errors . add ( e ) ; } } ; connection . addConnectionListener ( connectionErrorListener ) ; readerThread . start ( ) ; // Wait for stream tag before returning. We'll wait a couple of seconds // before // giving up and throwing an error. try { // A waiting thread may be woken up before the wait time or a notify // (although this is a rare thing). Therefore, we continue waiting // until either a connectionID has been set (and hence a notify was // made) or the total wait time has elapsed. int waitTime = SmackConfiguration . getPacketReplyTimeout ( ) ; wait ( 3 * waitTime ) ; } catch ( InterruptedException ie ) { // Ignore. } connection . removeConnectionListener ( connectionErrorListener ) ; if ( connectionID == null ) { throw new XMPPException ( \"Connection failed. No response from server.\" ) ; } else if ( ! errors . isEmpty ( ) ) { throw new XMPPException ( errors . iterator ( ) . next ( ) ) ; } else { connection . connectionID = connectionID ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shuts the packet reader down . [CODESPLIT] public void shutdown ( ) { // Notify connection listeners of the connection closing if done hasn't // already been set. if ( ! done ) { for ( ConnectionListener listener : connection . getConnectionListeners ( ) ) { try { listener . connectionClosed ( ) ; } catch ( Exception e ) { // Catch and print any exception so we can recover // from a faulty listener and finish the shutdown process LOGGER . log ( Level . ERROR , \"Error in listener while closing connection\" , e ) ; } } } done = true ; // Shut down the listener executor. listenerExecutor . shutdown ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Resets the parser using the latest connection s reader . Reseting the parser is necessary when the plain connection has been secured or when a new opening stream element is going to be sent by the server . [CODESPLIT] private void resetParser ( ) { try { innerReader = new XPPPacketReader ( ) ; innerReader . setXPPFactory ( XmlPullParserFactory . newInstance ( ) ) ; innerReader . getXPPParser ( ) . setInput ( connection . reader ) ; reset = true ; } catch ( Exception xppe ) { LOGGER . log ( Level . WARN , \"Error while resetting parser\" , xppe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse top - level packets in order to process them further . [CODESPLIT] private void parsePackets ( Thread thread ) { try { while ( ! done ) { if ( reset ) { startStream ( ) ; LOGGER . debug ( \"Started xmlstream...\" ) ; reset = false ; continue ; } Element doc = innerReader . parseDocument ( ) . getRootElement ( ) ; if ( doc == null ) { connection . disconnect ( ) ; LOGGER . debug ( \"End of xmlstream.\" ) ; continue ; } Packet packet = null ; LOGGER . debug ( \"Processing packet \" + doc . asXML ( ) ) ; packet = parseFromPlugins ( doc , packet ) ; if ( packet == null ) { packet = parseFromCore ( doc ) ; } if ( packet != null ) { processPacket ( packet ) ; } } } catch ( Exception e ) { if ( ! done && ! connection . isSocketClosed ( ) ) { connection . notifyConnectionError ( e ) ; if ( ! connection . isConnected ( ) ) { releaseConnectionIDLock ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes a packet after it s been fully parsed by looping through the installed packet collectors and listeners and letting them examine the packet to see if they are a match with the filter . [CODESPLIT] private void processPacket ( Packet packet ) { if ( packet == null ) { return ; } // Loop through all collectors and notify the appropriate ones. for ( PacketCollector collector : connection . getPacketCollectors ( ) ) { collector . processPacket ( packet ) ; } // Deliver the incoming packet to listeners. listenerExecutor . submit ( new ListenerNotification ( packet ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the CLI option . [CODESPLIT] protected final void setCliOption ( Option option ) { if ( option != null ) { this . cliOption = option ; } if ( this . cliOption . getDescription ( ) != null ) { this . descr = this . cliOption . getDescription ( ) ; } else { this . cliOption . setDescription ( this . descr ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new chat and returns it . [CODESPLIT] public Chat createChat ( String userJID , MessageListener listener ) { return createChat ( userJID , null , listener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to get a matching chat for the given user JID based on the { @link MatchMode } . <li > NONE - return null <li > SUPPLIED_JID - match the jid in the from field of the message exactly . <li > BARE_JID - if not match for from field try the bare jid . [CODESPLIT] private Chat getUserChat ( String userJID ) { if ( matchMode == MatchMode . NONE ) { return null ; } Chat match = jidChats . get ( userJID ) ; if ( match == null && ( matchMode == MatchMode . BARE_JID ) ) { match = baseJidChats . get ( StringUtils . parseBareAddress ( userJID ) ) ; } return match ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a list of HostAddresses under which the specified XMPP server can be reached at for server - to - server communication . A DNS lookup for a SRV record in the form _xmpp - server . _tcp . example . com is attempted according to section 14 . 4 of RFC 3920 . If that lookup fails a lookup in the older form of _jabber . _tcp . example . com is attempted since servers that implement an older version of the protocol may be listed using that notation . If that lookup fails as well it s assumed that the XMPP server lives at the host resolved by a DNS lookup at the specified domain on the default port of 5269 . <p > [CODESPLIT] public static List < HostAddress > resolveXMPPServerDomain ( final String domain ) { if ( dnsResolver == null ) { List < HostAddress > addresses = new ArrayList < HostAddress > ( 1 ) ; addresses . add ( new HostAddress ( domain , 5269 ) ) ; return addresses ; } return resolveDomain ( domain , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Convert a new content object to an internal version . [CODESPLIT] void internalize ( ContentManagerImpl contentManager , boolean readOnly ) { this . contentManager = contentManager ; updated = false ; newcontent = false ; this . readOnly = readOnly ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reset the object back to its last saved state . [CODESPLIT] public void reset ( Map < String , Object > updatedMap ) { if ( ! readOnly ) { this . content = ImmutableMap . copyOf ( updatedMap ) ; updatedContent . clear ( ) ; updated = false ; LOGGER . debug ( \"Reset to {} \" , updatedMap ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "set a property creating if it does not exist overwriting if it does . [CODESPLIT] public void setProperty ( String key , Object value ) { if ( readOnly ) { return ; } if ( value == null ) { throw new IllegalArgumentException ( \"value must not be null\" ) ; } Object o = content . get ( key ) ; if ( ! value . equals ( o ) ) { updatedContent . put ( key , value ) ; updated = true ; } else if ( updatedContent . containsKey ( key ) && ! value . equals ( updatedContent . get ( key ) ) ) { updatedContent . put ( key , value ) ; updated = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a filter to the filter list for the OR operation . A packet will pass the filter if any filter in the list accepts it . [CODESPLIT] public void addFilter ( PacketFilter filter ) { if ( filter == null ) { throw new IllegalArgumentException ( \"Parameter cannot be null.\" ) ; } // If there is no more room left in the filters array, expand it. if ( size == filters . length ) { PacketFilter [ ] newFilters = new PacketFilter [ filters . length + 2 ] ; for ( int i = 0 ; i < filters . length ; i ++ ) { newFilters [ i ] = filters [ i ] ; } filters = newFilters ; } // Add the new filter to the array. filters [ size ] = filter ; size ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process the request in a stream . [CODESPLIT] public void processRequest ( HttpServletRequest request ) throws IOException , FileUploadException , StorageClientException , AccessDeniedException { boolean debug = LOGGER . isDebugEnabled ( ) ; if ( ServletFileUpload . isMultipartContent ( request ) ) { if ( debug ) { LOGGER . debug ( \"Multipart POST \" ) ; } feedback . add ( \"Multipart Upload\" ) ; ServletFileUpload upload = new ServletFileUpload ( ) ; FileItemIterator iterator = upload . getItemIterator ( request ) ; while ( iterator . hasNext ( ) ) { FileItemStream item = iterator . next ( ) ; if ( debug ) { LOGGER . debug ( \"Got Item {}\" , item ) ; } String name = item . getFieldName ( ) ; InputStream stream = item . openStream ( ) ; if ( item . isFormField ( ) ) { ParameterType pt = ParameterType . typeOfRequestParameter ( name ) ; String propertyName = RequestUtils . propertyName ( pt . getPropertyName ( name ) ) ; RequestUtils . accumulate ( stores . get ( pt ) , propertyName , RequestUtils . toValue ( name , Streams . asString ( stream ) ) ) ; feedback . add ( pt . feedback ( propertyName ) ) ; } else { if ( streamProcessor != null ) { feedback . addAll ( streamProcessor . processStream ( name , StorageClientUtils . getObjectName ( item . getName ( ) ) , item . getContentType ( ) , stream , this ) ) ; } } } if ( debug ) { LOGGER . debug ( \"No More items \" ) ; } } else { if ( debug ) { LOGGER . debug ( \"Trad Post \" ) ; } // use traditional unstreamed operations. @ SuppressWarnings ( \"unchecked\" ) Map < String , String [ ] > parameters = request . getParameterMap ( ) ; if ( debug ) { LOGGER . debug ( \"Traditional POST {} \" , parameters ) ; } Set < Entry < String , String [ ] > > entries = parameters . entrySet ( ) ; for ( Entry < String , String [ ] > param : entries ) { String name = ( String ) param . getKey ( ) ; ParameterType pt = ParameterType . typeOfRequestParameter ( name ) ; String propertyName = RequestUtils . propertyName ( pt . getPropertyName ( name ) ) ; RequestUtils . accumulate ( stores . get ( pt ) , propertyName , RequestUtils . toValue ( name , param . getValue ( ) ) ) ; feedback . add ( pt . feedback ( propertyName ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clear the current set of properties to add and remove . [CODESPLIT] public void resetProperties ( ) { for ( Entry < ParameterType , Map < String , Object > > e : stores . entrySet ( ) ) { e . getValue ( ) . clear ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculate an RFC2104 compliant HMAC ( Hash - based Message Authentication Code ) [CODESPLIT] public static String calculateRFC2104HMAC ( String data , String key ) throws java . security . SignatureException { if ( data == null ) { throw new IllegalArgumentException ( \"String data == null\" ) ; } if ( key == null ) { throw new IllegalArgumentException ( \"String key == null\" ) ; } try { // Get an hmac_sha1 key from the raw key bytes byte [ ] keyBytes = key . getBytes ( \"UTF-8\" ) ; SecretKeySpec signingKey = new SecretKeySpec ( keyBytes , HMAC_SHA1_ALGORITHM ) ; // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac . getInstance ( HMAC_SHA1_ALGORITHM ) ; mac . init ( signingKey ) ; // Compute the hmac on input data bytes byte [ ] rawHmac = mac . doFinal ( data . getBytes ( \"UTF-8\" ) ) ; // Convert raw bytes to encoding return Base64 . encodeBase64URLSafeString ( rawHmac ) ; } catch ( NoSuchAlgorithmException e ) { throw new SignatureException ( \"Failed to generate HMAC : \" + e . getMessage ( ) , e ) ; } catch ( InvalidKeyException e ) { throw new SignatureException ( \"Failed to generate HMAC : \" + e . getMessage ( ) , e ) ; } catch ( UnsupportedEncodingException e ) { throw new SignatureException ( \"Failed to generate HMAC : \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes the original request and starts the batching . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) protected void batchRequest ( HttpServletRequest request , HttpServletResponse response , boolean allowModify ) throws IOException , ServletException { String json = request . getParameter ( REQUESTS_PARAMETER ) ; String template = request . getParameter ( REQUEST_TEMPLATE ) ; if ( template != null && template . length ( ) > 0 ) { if ( templateService . checkTemplateExists ( template ) ) { StringWriter processedTemplate = new StringWriter ( ) ; templateService . process ( request . getParameterMap ( ) , \"UTF-8\" , processedTemplate , template ) ; json = processedTemplate . toString ( ) ; } else { response . sendError ( HttpServletResponse . SC_BAD_REQUEST , \"Template specified in request parameter t does not exist\" ) ; } } batchProcessor . batchRequest ( request , response , json , allowModify ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static void addAcl ( boolean grant , Permission permssion , String key , List < AclModification > modifications ) { if ( grant ) { key = AclModification . grantKey ( key ) ; } else { key = AclModification . denyKey ( key ) ; } modifications . add ( new AclModification ( key , permssion . getPermission ( ) , AclModification . Operation . OP_OR ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static void removeAcl ( boolean grant , Permission permssion , String key , List < AclModification > modifications ) { if ( grant ) { key = AclModification . grantKey ( key ) ; } else { key = AclModification . denyKey ( key ) ; } modifications . add ( new AclModification ( key , ~ permssion . getPermission ( ) , AclModification . Operation . OP_AND ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static void filterAcl ( Map < String , Object > acl , boolean grant , Permission permission , boolean set , List < AclModification > modifications ) { int perm = permission . getPermission ( ) ; Operation op = Operation . OP_OR ; if ( ! set ) { perm = 0xffff ^ perm ; op = Operation . OP_AND ; } for ( Entry < String , Object > ace : acl . entrySet ( ) ) { String key = ace . getKey ( ) ; if ( AclModification . isGrant ( key ) == grant ) { // clear the bit if set. modifications . add ( new AclModification ( key , perm , op ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static String getPrincipal ( String principalKey ) { if ( principalKey == null ) { return principalKey ; } if ( principalKey . length ( ) <= GRANTED_MARKER . length ( ) ) { return null ; } if ( principalKey . endsWith ( GRANTED_MARKER ) ) { return principalKey . substring ( 0 , principalKey . length ( ) - GRANTED_MARKER . length ( ) ) ; } else if ( principalKey . endsWith ( DENIED_MARKER ) ) { return principalKey . substring ( 0 , principalKey . length ( ) - DENIED_MARKER . length ( ) ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static Permission [ ] listPermissions ( int perms ) { List < Permission > permissions = Lists . newArrayList ( ) ; for ( Permission p : Permissions . PRIMARY_PERMISSIONS ) { if ( ( perms & p . getPermission ( ) ) == p . getPermission ( ) ) { permissions . add ( p ) ; } } return permissions . toArray ( new Permission [ permissions . size ( ) ] ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > TransactionalSortedBidiMap < K , V > decorate ( TransactionalSortedBidiMap < K , V > map ) { return new SynchronizedTransactionalSortedBidiMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public void commit ( ) { SyncUtils . synchronizeWrite ( lock , new Callback < Object > ( ) { @ Override protected void doAction ( ) { getTransactionalSortedBidiMap ( ) . commit ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the writer in order to be used . It is called at the first connection and also is invoked if the connection is disconnected by an error . [CODESPLIT] protected void init ( ) { this . writer = connection . writer ; done = false ; writerThread = new Thread ( ) { public void run ( ) { writePackets ( this ) ; } } ; writerThread . setName ( \"Smack Packet Writer (\" + connection . connectionCounterValue + \")\" ) ; writerThread . setDaemon ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends the specified packet to the server . [CODESPLIT] public void sendPacket ( Packet packet ) { if ( ! done ) { // Invoke interceptors for the new packet that is about to be sent. // Interceptors // may modify the content of the packet. connection . firePacketInterceptors ( packet ) ; try { queue . put ( packet ) ; } catch ( InterruptedException ie ) { LOGGER . log ( Level . ERROR , \"Failed to queue packet to send to server: \" + packet . toString ( ) , ie ) ; return ; } synchronized ( queue ) { queue . notifyAll ( ) ; } // Process packet writer listeners. Note that we're using the // sending // thread so it's expected that listeners are fast. connection . firePacketSendingListeners ( packet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next available packet from the queue for writing . [CODESPLIT] private Packet nextPacket ( ) { Packet packet = null ; // Wait until there's a packet or we're done. while ( ! done && ( packet = queue . poll ( ) ) == null ) { try { synchronized ( queue ) { queue . wait ( ) ; } } catch ( InterruptedException ie ) { // Do nothing } } return packet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends to the server a new stream element . This operation may be requested several times so we need to encapsulate the logic in one place . This message will be sent while doing TLS SASL and resource binding . [CODESPLIT] void openStream ( ) throws IOException { StringBuilder stream = new StringBuilder ( ) ; stream . append ( \"<stream:stream\" ) ; stream . append ( \" to=\\\"\" ) . append ( connection . getServiceName ( ) ) . append ( \"\\\"\" ) ; stream . append ( \" xmlns=\\\"jabber:client\\\"\" ) ; stream . append ( \" xmlns:stream=\\\"http://etherx.jabber.org/streams\\\"\" ) ; stream . append ( \" version=\\\"1.0\\\">\" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the Goodwill schema associated to a schema name . < / p > Typical invocation : <pre > try { GoodwillSchema type = accessor . getSchema ( test ) . get () ; ... } catch ( Exception e ) { // Connection exception? Goodwill server down? } < / pre > [CODESPLIT] public Future < GoodwillSchema > getSchema ( final String schemaName ) { try { return client . prepareGet ( String . format ( \"%s/%s\" , url , schemaName ) ) . addHeader ( \"Accept\" , \"application/json\" ) . execute ( new AsyncCompletionHandler < GoodwillSchema > ( ) { @ Override public GoodwillSchema onCompleted ( final Response response ) throws Exception { if ( response . getStatusCode ( ) != 200 ) { return null ; } final InputStream in = response . getResponseBodyAsStream ( ) ; try { return mapper . readValue ( in , GoodwillSchema . class ) ; } finally { closeStream ( in ) ; } } @ Override public void onThrowable ( final Throwable t ) { log . warn ( \"Got exception looking up the schema\" , t ) ; } } ) ; } catch ( IOException e ) { log . warn ( \"Got exception looking up the schema\" , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get all schemata . <p / > Use schemata instead of schemas which is closer to the original σχήματα . [CODESPLIT] public Future < List < GoodwillSchema > > getSchemata ( ) { try { return client . prepareGet ( url ) . addHeader ( \"Accept\" , \"application/json\" ) . execute ( new AsyncCompletionHandler < List < GoodwillSchema > > ( ) { @ Override public List < GoodwillSchema > onCompleted ( final Response response ) throws Exception { if ( response . getStatusCode ( ) != 200 ) { return null ; } InputStream in = response . getResponseBodyAsStream ( ) ; try { final HashMap < String , List < GoodwillSchema > > map = mapper . readValue ( in , new TypeReference < HashMap < String , List < GoodwillSchema > > > ( ) { } ) ; return map . get ( \"types\" ) ; } finally { closeStream ( in ) ; } } @ Override public void onThrowable ( final Throwable t ) { log . warn ( \"Got exception looking up the schema list\" , t ) ; } } ) ; } catch ( IOException e ) { log . warn ( \"Got exception looking up the schema list\" , e ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "note : if called from base - class constructor couldn t sub - class ; hence just make static [CODESPLIT] private static AsyncHttpClient createHttpClient ( ) { // Don't limit the number of connections per host // See https://github.com/ning/async-http-client/issues/issue/28 final AsyncHttpClientConfig . Builder builder = new AsyncHttpClientConfig . Builder ( ) ; builder . setMaximumConnectionsPerHost ( - 1 ) ; return new AsyncHttpClient ( builder . build ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Event Object [CODESPLIT] public static Optional < Event > createEvent ( String type , Identification source ) { try { return Optional . of ( new Event ( type , source , new ArrayList <> ( ) ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Event Object [CODESPLIT] public static Optional < Event > createEvent ( String type , Identification source , List < String > descriptors ) { try { return Optional . of ( new Event ( type , source , descriptors ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a List containing all the Descriptors and the type . [CODESPLIT] @ Override public List < String > getAllInformations ( ) { ArrayList < String > strings = new ArrayList <> ( descriptors ) ; strings . add ( type ) ; return strings ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the Descriptors ( but not the Event - Type ) . [CODESPLIT] public Event addDescriptor ( String descriptor ) { List < String > newDescriptors = new ArrayList <> ( ) ; newDescriptors . addAll ( descriptors ) ; newDescriptors . add ( descriptor ) ; return new Event ( getType ( ) , getSource ( ) , newDescriptors ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns whether the event contains the specific descriptor . this method also checks whether it matches the type . [CODESPLIT] @ Override public boolean containsDescriptor ( String descriptor ) { return descriptors . contains ( descriptor ) || type . equals ( descriptor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the Consumer to the specified EventLifeCycle . In its current implementation the invocation of the Callback method is parallel but the notificaton of the listners not . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public Event addEventLifeCycleListener ( EventLifeCycle eventLifeCycle , Consumer < EventLifeCycle > cycleCallback ) { lifeCycleListeners . compute ( eventLifeCycle , ( unused , list ) -> { if ( list == null ) list = new ArrayList <> ( ) ; list . add ( cycleCallback ) ; return list ; } ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Default implementation waits until a new Event has been received and then processes it . <p > This method is made to be overwritten as seen fit by the developer [CODESPLIT] @ Override public EventModel blockingQueueHandling ( ) throws InterruptedException { EventModel eventModel = super . blockingQueueHandling ( ) ; if ( eventModel . containsDescriptor ( MuteEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { mute ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> mute ( ) ) ; } } if ( eventModel . containsDescriptor ( UnMuteEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { unMute ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> unMute ( ) ) ; } } if ( eventModel . containsDescriptor ( StopEvent . ID ) ) { List < ResourceModel > resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) ; if ( resourceModels . isEmpty ( ) ) { stopSound ( ) ; } else { resourceModels . stream ( ) . map ( resourceModel -> resourceModel . getResource ( ) instanceof Identification ? ( ( Identification ) resourceModel . getResource ( ) ) : null ) . filter ( Objects :: nonNull ) . filter ( this :: isOwner ) . findAny ( ) . ifPresent ( id -> stopSound ( ) ) ; } } return eventModel ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "use this method to start playing sound ( only plays sound if it is not already playing ) [CODESPLIT] public Optional < CompletableFuture < Void > > startPlaying ( Runnable function ) { if ( isCurrentlyPlayingSound ) return Optional . empty ( ) ; CompletableFuture < Void > voidCompletableFuture = submit ( ( Runnable ) ( ) -> startedSound ( isUsingJava ) ) . thenRun ( ( ) -> { try { isCurrentlyPlayingSound = true ; function . run ( ) ; } finally { submit ( ( Runnable ) this :: endedSound ) ; isCurrentlyPlayingSound = false ; } } ) ; return Optional . of ( voidCompletableFuture ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shuts down the task engine service . [CODESPLIT] public void shutdown ( ) { if ( executor != null ) { executor . shutdownNow ( ) ; executor = null ; } if ( timer != null ) { timer . cancel ( ) ; timer = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < E > FilterableCollection < E > decorate ( FilterableCollection < E > collection ) { return new SynchronizedFilterableCollection < E > ( collection ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public FilterableCollection < E > filteredCollection ( final Filter < ? super E > filter ) { return SyncUtils . synchronizeRead ( lock , new Callback < FilterableCollection < E > > ( ) { @ Override protected void doAction ( ) { FilterableCollection < E > _col = getFilterableCollection ( ) . filteredCollection ( filter ) ; _return ( new SynchronizedFilterableCollection < E > ( _col , lock ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Identical File Contents [CODESPLIT] public static Boolean contentEquals ( Path file1 , Path file2 ) throws IOException { if ( ! java . nio . file . Files . isRegularFile ( file1 ) ) throw new IllegalArgumentException ( file1 + \"is not a regular file\" ) ; if ( ! java . nio . file . Files . isRegularFile ( file2 ) ) throw new IllegalArgumentException ( file2 + \"is not a regular file\" ) ; FileChannel channel1 = null ; FileChannel channel2 = null ; MappedByteBuffer buffer1 = null ; MappedByteBuffer buffer2 = null ; try { long size1 = java . nio . file . Files . size ( file1 ) ; long size2 = java . nio . file . Files . size ( file2 ) ; if ( size1 != size2 ) return false ; long position = 0 ; long length = Math . min ( Integer . MAX_VALUE , size1 - position ) ; channel1 = FileChannel . open ( file1 ) ; channel2 = FileChannel . open ( file2 ) ; // Cannot map files larger than Integer.MAX_VALUE, // so we have to do it in pieces. while ( length > 0 ) { buffer1 = channel1 . map ( MapMode . READ_ONLY , position , length ) ; buffer2 = channel2 . map ( MapMode . READ_ONLY , position , length ) ; // if (!buffer1.equals(buffer2)) return false; // The line above is much slower than the line below. // It should not be, but it is, possibly because it is // loading the entire buffer into memory before comparing // the contents. See the corresponding unit test. EK for ( int i = 0 ; i < length ; i ++ ) if ( buffer1 . get ( ) != buffer2 . get ( ) ) return false ; position += length ; length = Math . min ( Integer . MAX_VALUE , size1 - position ) ; cleanDirectByteBuffer ( buffer1 ) ; buffer1 = null ; cleanDirectByteBuffer ( buffer2 ) ; buffer2 = null ; } } finally { // Is is important to clean up so we do not hold any // file locks, in case the caller wants to do something // else with the files. // In terms of functional programming, holding a lock after // returning to the caller would be an unwelcome side-effect. cleanDirectByteBuffer ( buffer1 ) ; cleanDirectByteBuffer ( buffer2 ) ; if ( channel1 != null ) try { channel1 . close ( ) ; } catch ( IOException e ) { if ( channel2 != null ) channel2 . close ( ) ; throw e ; } if ( channel2 != null ) channel2 . close ( ) ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clean or unmap a direct ByteBuffer [CODESPLIT] public static void cleanDirectByteBuffer ( final ByteBuffer byteBuffer ) { if ( byteBuffer == null ) return ; if ( ! byteBuffer . isDirect ( ) ) throw new IllegalArgumentException ( \"byteBuffer isn't direct!\" ) ; AccessController . doPrivileged ( new PrivilegedAction < Void > ( ) { public Void run ( ) { try { Method cleanerMethod = byteBuffer . getClass ( ) . getMethod ( \"cleaner\" ) ; cleanerMethod . setAccessible ( true ) ; Object cleaner = cleanerMethod . invoke ( byteBuffer ) ; Method cleanMethod = cleaner . getClass ( ) . getMethod ( \"clean\" ) ; cleanMethod . setAccessible ( true ) ; cleanMethod . invoke ( cleaner ) ; } catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new RuntimeException ( \"Could not clean MappedByteBuffer -- File may still be locked!\" ) ; } return null ; // nothing to return } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rolls back the changes to the map . [CODESPLIT] public void rollback ( ) { if ( auto_commit ) return ; String id = getCurrentThreadId ( ) ; Entry < K , V > tab [ ] = table ; for ( int i = 0 ; i < tab . length ; i ++ ) { Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . is ( Entry . ADDED , id ) ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; } else if ( e . is ( Entry . DELETED , id ) ) e . setStatus ( Entry . NO_CHANGE , null ) ; prev = e ; e = next ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that this entry is valid for the current thread [CODESPLIT] private boolean validEntry ( final Entry < K , V > entry ) { if ( auto_commit || entry == null ) return ( entry != null ) ; String id = getCurrentThreadId ( ) ; return ! ( ( entry . is ( Entry . DELETED , id ) ) || ( entry . is ( Entry . ADDED , null ) && entry . is ( Entry . NO_CHANGE , id ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns internal representation for key . Use NULL_KEY if key is null . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) static < T > T maskNull ( T key ) { return ( key == null ? ( T ) NULL_KEY : key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a hash value for the specified object . In addition to the object s own hashCode this method applies a supplemental hash function which defends against poor quality hash functions . This is critical because HashMap uses power - of two length hash tables . <p > [CODESPLIT] static int hash ( Object x ) { int h = x . hashCode ( ) ; h += ~ ( h << 9 ) ; h ^= ( h >>> 14 ) ; h += ( h << 4 ) ; h ^= ( h >>> 10 ) ; return h ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Check for equality of non - null reference x and possibly - null y . [CODESPLIT] static boolean eq ( Object x , Object y ) { return x == y || x . equals ( y ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which the specified key is mapped in this identity hash map or <tt > null< / tt > if the map contains no mapping for this key . A return value of <tt > null< / tt > does not <i > necessarily< / i > indicate that the map contains no mapping for the key ; it is also possible that the map explicitly maps the key to <tt > null< / tt > . The <tt > containsKey< / tt > method may be used to distinguish these two cases . [CODESPLIT] @ Override public V get ( Object key ) { Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > e = table [ i ] ; while ( true ) { if ( e == null ) return null ; if ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) return e . value ; e = e . next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the entry associated with the specified key in the HashMap . Returns null if the HashMap contains no mapping for this key . [CODESPLIT] Entry < K , V > getEntry ( Object key ) { Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > e = table [ i ] ; while ( e != null && ! ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) ) e = e . next ; return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified key in this map . If the map previously contained a mapping for this key the old value is replaced . [CODESPLIT] @ Override public V put ( K key , V value ) throws ConcurrentModificationException { K k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; V oldValue = null ; for ( Entry < K , V > e = table [ i ] ; e != null ; e = e . next ) { if ( e . hash == hash && eq ( k , e . key ) ) { //check if someone else has a pending add for the same key\r if ( e . is ( Entry . ADDED , null ) && ! e . is ( Entry . ADDED , getCurrentThreadId ( ) ) ) throw new ConcurrentModificationException ( ) ; if ( validEntry ( e ) ) { oldValue = e . value ; //if not transactional can reuse entries\r if ( auto_commit ) { e . value = value ; return oldValue ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; } } } modCount ++ ; addEntry ( hash , k , value , i ) ; return oldValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used instead of put by constructors and pseudoconstructors ( clone readObject ) . It does not resize the table check for comodification etc . It calls createEntry rather than addEntry . [CODESPLIT] private void putForCreate ( K key , V value ) { K k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; /**\r\n         * Look for preexisting entry for key.  This will never happen for\r\n         * clone or deserialize.  It will only happen for construction if the\r\n         * input Map is a sorted map whose ordering is inconsistent w/ equals.\r\n         */ for ( Entry < K , V > e = table [ i ] ; e != null ; e = e . next ) { if ( e . hash == hash && eq ( k , e . key ) ) { e . value = value ; return ; } } createEntry ( hash , k , value , i ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rehashes the contents of this map into a new array with a larger capacity . This method is called automatically when the number of keys in this map reaches its threshold . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) void resize ( int newCapacity ) { Entry < K , V > [ ] oldTable = table ; int oldCapacity = oldTable . length ; if ( oldCapacity == MAXIMUM_CAPACITY ) { threshold = Integer . MAX_VALUE ; return ; } Entry < K , V > [ ] newTable = new Entry [ newCapacity ] ; transfer ( newTable ) ; table = newTable ; threshold = ( int ) ( newCapacity * loadFactor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copies all of the mappings from the specified map to this map These mappings will replace any mappings that this map had for any of the keys currently in the specified map . [CODESPLIT] @ Override public void putAll ( Map < ? extends K , ? extends V > m ) { int numKeysToBeAdded = m . size ( ) ; if ( numKeysToBeAdded == 0 ) return ; /*\r\n         * Expand the map if the map if the number of mappings to be added\r\n         * is greater than or equal to threshold.  This is conservative; the\r\n         * obvious condition is (m.size() + size) >= threshold, but this\r\n         * condition could result in a map with twice the appropriate capacity,\r\n         * if the keys to be added overlap with the keys already in this map.\r\n         * By using the conservative calculation, we subject ourself\r\n         * to at most one extra resize.\r\n         */ if ( numKeysToBeAdded > threshold ) { int targetCapacity = ( int ) ( numKeysToBeAdded / loadFactor + 1 ) ; if ( targetCapacity > MAXIMUM_CAPACITY ) targetCapacity = MAXIMUM_CAPACITY ; int newCapacity = table . length ; while ( newCapacity < targetCapacity ) newCapacity <<= 1 ; if ( newCapacity > table . length ) resize ( newCapacity ) ; } for ( Iterator < ? extends Map . Entry < ? extends K , ? extends V > > i = m . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < ? extends K , ? extends V > e = i . next ( ) ; put ( e . getKey ( ) , e . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the mapping for this key from this map if present . [CODESPLIT] @ Override public V remove ( Object key ) throws ConcurrentModificationException { Entry < K , V > e = removeEntryForKey ( key ) ; return ( e == null ? null : e . value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes and returns the entry associated with the specified key in the HashMap . Returns null if the HashMap contains no mapping for this key . [CODESPLIT] Entry < K , V > removeEntryForKey ( Object key ) throws ConcurrentModificationException { Object k = maskNull ( key ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . hash == hash && validEntry ( e ) && eq ( k , e . key ) ) { if ( e . is ( Entry . DELETED , null ) && ! e . is ( Entry . DELETED , getCurrentThreadId ( ) ) ) throw new ConcurrentModificationException ( ) ; if ( auto_commit ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; return e ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; } prev = e ; e = next ; } return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Special version of remove for EntrySet . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) Entry < K , V > removeMapping ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) return null ; Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object k = maskNull ( entry . getKey ( ) ) ; int hash = hash ( k ) ; int i = indexFor ( hash , table . length ) ; Entry < K , V > prev = table [ i ] ; Entry < K , V > e = prev ; while ( e != null ) { Entry < K , V > next = e . next ; if ( e . hash == hash && validEntry ( e ) && e . equals ( entry ) ) { if ( auto_commit ) { modCount ++ ; size -- ; if ( prev == e ) table [ i ] = next ; else prev . next = next ; } else e . setStatus ( Entry . DELETED , getCurrentThreadId ( ) ) ; return e ; } prev = e ; e = next ; } return e ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all mappings from this map . [CODESPLIT] @ Override public void clear ( ) { modCount ++ ; Entry < K , V > tab [ ] = table ; for ( int i = 0 ; i < tab . length ; i ++ ) tab [ i ] = null ; size = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a new entry with the specified key value and hash code to the specified bucket . It is the responsibility of this method to resize the table if appropriate . [CODESPLIT] void addEntry ( int hash , K key , V value , int bucketIndex ) { table [ bucketIndex ] = new Entry < K , V > ( hash , key , value , table [ bucketIndex ] ) ; if ( ! auto_commit ) table [ bucketIndex ] . setStatus ( Entry . ADDED , getCurrentThreadId ( ) ) ; if ( size ++ >= threshold ) resize ( 2 * table . length ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Like addEntry except that this version is used when creating entries as part of Map construction or pseudo - construction ( cloning deserialization ) . This version needn t worry about resizing the table . [CODESPLIT] void createEntry ( int hash , K key , V value , int bucketIndex ) { table [ bucketIndex ] = new Entry < K , V > ( hash , key , value , table [ bucketIndex ] ) ; size ++ ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates map delegate . [CODESPLIT] private static < K , V > ImmutableMap < K , V > createDelegate ( final Map < K , V > base , final Set < ? extends K > keys , final Function < K , V > augmentation ) { final ImmutableMap . Builder < K , V > builder = ImmutableMap . builder ( ) ; builder . putAll ( base ) ; keys . stream ( ) . filter ( key -> ! base . containsKey ( key ) ) . forEach ( key -> builder . put ( key , augmentation . apply ( key ) ) ) ; return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given date string in either of the three profiles of <a href = http : // xmpp . org / extensions / xep - 0082 . html > XEP - 0082 - XMPP Date and Time Profiles< / a > or <a href = http : // xmpp . org / extensions / xep - 0091 . html > XEP - 0091 - Legacy Delayed Delivery< / a > format . <p > This method uses internal date formatters and is thus threadsafe . [CODESPLIT] public static Date parseDate ( String dateString ) throws ParseException { Matcher matcher = xep0091Pattern . matcher ( dateString ) ; /*\n         * if date is in XEP-0091 format handle ambiguous dates missing the\n         * leading zero in month and day\n         */ if ( matcher . matches ( ) ) { int length = dateString . split ( \"T\" ) [ 0 ] . length ( ) ; if ( length < 8 ) { Date date = handleDateWithMissingLeadingZeros ( dateString , length ) ; if ( date != null ) return date ; } else { synchronized ( xep0091Formatter ) { return xep0091Formatter . parse ( dateString ) ; } } } else { for ( PatternCouplings coupling : couplings ) { matcher = coupling . pattern . matcher ( dateString ) ; if ( matcher . matches ( ) ) { if ( coupling . needToConvertTimeZone ) { dateString = coupling . convertTime ( dateString ) ; } synchronized ( coupling . formatter ) { return coupling . formatter . parse ( dateString ) ; } } } } /*\n         * We assume it is the XEP-0082 DateTime profile with no milliseconds at\n         * this point. If it isn't, is is just not parseable, then we attempt to\n         * parse it regardless and let it throw the ParseException.\n         */ synchronized ( dateTimeNoMillisFormatter ) { return dateTimeNoMillisFormatter . parse ( dateString ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the given date string in different ways and returns the date that lies in the past and / or is nearest to the current date - time . [CODESPLIT] private static Date handleDateWithMissingLeadingZeros ( String stampString , int dateLength ) throws ParseException { if ( dateLength == 6 ) { synchronized ( xep0091Date6DigitFormatter ) { return xep0091Date6DigitFormatter . parse ( stampString ) ; } } Calendar now = Calendar . getInstance ( ) ; Calendar oneDigitMonth = parseXEP91Date ( stampString , xep0091Date7Digit1MonthFormatter ) ; Calendar twoDigitMonth = parseXEP91Date ( stampString , xep0091Date7Digit2MonthFormatter ) ; List < Calendar > dates = filterDatesBefore ( now , oneDigitMonth , twoDigitMonth ) ; if ( ! dates . isEmpty ( ) ) { return determineNearestDate ( now , dates ) . getTime ( ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name portion of a XMPP address . For example for the address matt@jivesoftware . com / Smack matt would be returned . If no username is present in the address the empty string will be returned . [CODESPLIT] public static String parseName ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int atIndex = XMPPAddress . lastIndexOf ( \"@\" ) ; if ( atIndex <= 0 ) { return \"\" ; } else { return XMPPAddress . substring ( 0 , atIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the server portion of a XMPP address . For example for the address matt@jivesoftware . com / Smack jivesoftware . com would be returned . If no server is present in the address the empty string will be returned . [CODESPLIT] public static String parseServer ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int atIndex = XMPPAddress . lastIndexOf ( \"@\" ) ; // If the String ends with '@', return the empty string. if ( atIndex + 1 > XMPPAddress . length ( ) ) { return \"\" ; } int slashIndex = XMPPAddress . indexOf ( \"/\" ) ; if ( slashIndex > 0 && slashIndex > atIndex ) { return XMPPAddress . substring ( atIndex + 1 , slashIndex ) ; } else { return XMPPAddress . substring ( atIndex + 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the resource portion of a XMPP address . For example for the address matt@jivesoftware . com / Smack Smack would be returned . If no resource is present in the address the empty string will be returned . [CODESPLIT] public static String parseResource ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int slashIndex = XMPPAddress . indexOf ( \"/\" ) ; if ( slashIndex + 1 > XMPPAddress . length ( ) || slashIndex < 0 ) { return \"\" ; } else { return XMPPAddress . substring ( slashIndex + 1 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the XMPP address with any resource information removed . For example for the address matt@jivesoftware . com / Smack matt@jivesoftware . com would be returned . [CODESPLIT] public static String parseBareAddress ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int slashIndex = XMPPAddress . indexOf ( \"/\" ) ; if ( slashIndex < 0 ) { return XMPPAddress ; } else if ( slashIndex == 0 ) { return \"\" ; } else { return XMPPAddress . substring ( 0 , slashIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if jid is a full JID ( i . e . a JID with resource part ) . [CODESPLIT] public static boolean isFullJID ( String jid ) { if ( parseName ( jid ) . length ( ) <= 0 || parseServer ( jid ) . length ( ) <= 0 || parseResource ( jid ) . length ( ) <= 0 ) { return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escapes the node portion of a JID according to JID Escaping ( JEP - 0106 ) . Escaping replaces characters prohibited by node - prep with escape sequences as follows : <p > [CODESPLIT] public static String escapeNode ( String node ) { if ( node == null ) { return null ; } StringBuilder buf = new StringBuilder ( node . length ( ) + 8 ) ; for ( int i = 0 , n = node . length ( ) ; i < n ; i ++ ) { char c = node . charAt ( i ) ; switch ( c ) { case ' ' : buf . append ( \"\\\\22\" ) ; break ; case ' ' : buf . append ( \"\\\\26\" ) ; break ; case ' ' : buf . append ( \"\\\\27\" ) ; break ; case ' ' : buf . append ( \"\\\\2f\" ) ; break ; case ' ' : buf . append ( \"\\\\3a\" ) ; break ; case ' ' : buf . append ( \"\\\\3c\" ) ; break ; case ' ' : buf . append ( \"\\\\3e\" ) ; break ; case ' ' : buf . append ( \"\\\\40\" ) ; break ; case ' ' : buf . append ( \"\\\\5c\" ) ; break ; default : { if ( Character . isWhitespace ( c ) ) { buf . append ( \"\\\\20\" ) ; } else { buf . append ( c ) ; } } } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Un - escapes the node portion of a JID according to JID Escaping ( JEP - 0106 ) . <p > Escaping replaces characters prohibited by node - prep with escape sequences as follows : <p > [CODESPLIT] public static String unescapeNode ( String node ) { if ( node == null ) { return null ; } char [ ] nodeChars = node . toCharArray ( ) ; StringBuilder buf = new StringBuilder ( nodeChars . length ) ; for ( int i = 0 , n = nodeChars . length ; i < n ; i ++ ) { compare : { char c = node . charAt ( i ) ; if ( c == ' ' && i + 2 < n ) { char c2 = nodeChars [ i + 1 ] ; char c3 = nodeChars [ i + 2 ] ; if ( c2 == ' ' ) { switch ( c3 ) { case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; } } else if ( c2 == ' ' ) { switch ( c3 ) { case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; case ' ' : buf . append ( ' ' ) ; i += 2 ; break compare ; } } else if ( c2 == ' ' ) { if ( c3 == ' ' ) { buf . append ( \"@\" ) ; i += 2 ; break compare ; } } else if ( c2 == ' ' ) { if ( c3 == ' ' ) { buf . append ( \"\\\\\" ) ; i += 2 ; break compare ; } } } buf . append ( c ) ; } } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a string for use in an XML attribute by escaping characters with a special meaning . In particular white spaces are encoded as character references such that they are not replaced by on parsing . [CODESPLIT] private static String xmlAttribEncodeBinary ( String value ) { StringBuilder s = new StringBuilder ( ) ; char buf [ ] = value . toCharArray ( ) ; for ( char c : buf ) { switch ( c ) { case ' ' : s . append ( \"&lt;\" ) ; break ; case ' ' : s . append ( \"&gt;\" ) ; break ; case ' ' : s . append ( \"&amp;\" ) ; break ; case ' ' : s . append ( \"&quot;\" ) ; break ; case ' ' : s . append ( \"&apos;\" ) ; break ; default : if ( c <= 0x1f || ( 0x7f <= c && c <= 0x9f ) ) { // includes \\t, \\n, // \\r s . append ( \"&#x\" ) ; s . append ( String . format ( \"%X\" , ( int ) c ) ) ; s . append ( ' ' ) ; } else { s . append ( c ) ; } } } return s . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hashes a String using the SHA - 1 algorithm and returns the result as a String of hexadecimal numbers . This method is synchronized to avoid excessive MessageDigest object creation . If calling this method becomes a bottleneck in your code you may wish to maintain a pool of MessageDigest objects instead of using this method . <p > A hash is a one - way function -- that is given an input an output is easily computed . However given the output the input is almost impossible to compute . This is useful for passwords since we can store the hash and a hacker will then have a very hard time determining the original password . [CODESPLIT] public synchronized static String hash ( String data ) { if ( digest == null ) { try { digest = MessageDigest . getInstance ( \"SHA-1\" ) ; } catch ( NoSuchAlgorithmException nsae ) { log . log ( Level . ERROR , \"Failed to load the SHA-1 MessageDigest. Smack will be unable to function normally.\" , nsae ) ; } } // Now, compute hash. try { digest . update ( data . getBytes ( \"UTF-8\" ) ) ; } catch ( UnsupportedEncodingException e ) { log . log ( Level . ERROR , \"Error computing hash\" , e ) ; } return encodeHex ( digest . digest ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes an array of bytes as String representation of hexadecimal . [CODESPLIT] public static String encodeHex ( byte [ ] bytes ) { StringBuilder hex = new StringBuilder ( bytes . length * 2 ) ; for ( byte aByte : bytes ) { if ( ( ( int ) aByte & 0xff ) < 0x10 ) { hex . append ( \"0\" ) ; } hex . append ( Integer . toString ( ( int ) aByte & 0xff , 16 ) ) ; } return hex . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a String as a base64 String . [CODESPLIT] public static String encodeBase64 ( String data ) { byte [ ] bytes = null ; try { bytes = data . getBytes ( \"ISO-8859-1\" ) ; } catch ( UnsupportedEncodingException uee ) { throw new IllegalStateException ( uee ) ; } return encodeBase64 ( bytes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Encodes a byte array into a bse64 String . [CODESPLIT] public static String encodeBase64 ( byte [ ] data , int offset , int len , boolean lineBreaks ) { return Base64 . encodeBytes ( data , offset , len , ( lineBreaks ? Base64 . NO_OPTIONS : Base64 . DONT_BREAK_LINES ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes a base64 String . Unlike Base64 . decode () this method does not try to detect and decompress a gzip - compressed input . [CODESPLIT] public static byte [ ] decodeBase64 ( String data ) { byte [ ] bytes ; try { bytes = data . getBytes ( \"UTF-8\" ) ; } catch ( java . io . UnsupportedEncodingException uee ) { bytes = data . getBytes ( ) ; } bytes = Base64 . decode ( bytes , 0 , bytes . length , Base64 . NO_OPTIONS ) ; return bytes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a random String of numbers and letters ( lower and upper case ) of the specified length . The method uses the Random class that is built - in to Java which is suitable for low to medium grade security uses . This means that the output is only pseudo random i . e . each number is mathematically generated so is not truly random . <p > [CODESPLIT] public static String randomString ( int length ) { if ( length < 1 ) { return null ; } // Create a char buffer to put random letters and numbers in. char [ ] randBuffer = new char [ length ] ; for ( int i = 0 ; i < randBuffer . length ; i ++ ) { randBuffer [ i ] = numbersAndLetters [ randGen . nextInt ( 71 ) ] ; } return new String ( randBuffer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Overridden to just get the count and nothing else . [CODESPLIT] @ Override public Integer iterate ( final FilterableCollection < ? extends T > c ) { checkUsed ( ) ; // No point doing the iteration. Just return size of collection.\r count = c . size ( ) ; return count ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the ability for the Play / Pause requests [CODESPLIT] public void setPlayPauseController ( Consumer < String > controller ) { if ( controller == null ) return ; this . playPause = controller ; capabilities . setPlayPauseControl ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the ability to select tracks [CODESPLIT] public void setTrackSelectorController ( Consumer < TrackInfo > controller ) { if ( controller == null ) return ; selectTrack = controller ; capabilities . setAbleToSelectTrack ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the ability to select the next / previous track [CODESPLIT] public void setNextPreviousController ( Consumer < String > controller ) { if ( controller == null ) return ; nextPrevious = controller ; capabilities . setNextPrevious ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the ability to jump to a specified position of the current track [CODESPLIT] public void setJumpProgressController ( Consumer < Progress > controller ) { if ( controller == null ) return ; jumpProgress = controller ; capabilities . setAbleToJump ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the ability to change the playback [CODESPLIT] public void setPlaybackChangeableController ( Consumer < String > controller ) { if ( controller == null ) return ; changePlayback = controller ; capabilities . setPlaybackChangeable ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the ability to change the volume from outside the player [CODESPLIT] public void setVolumeChangeableController ( Consumer < Volume > controller ) { if ( controller == null ) return ; changeVolume = controller ; capabilities . setChangeVolume ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "adds the ability to return the available playlists on request . [CODESPLIT] public void broadcastAvailablePlaylists ( Supplier < List < String > > availablePlaylist , Function < String , Playlist > playlistForNameFunction ) { if ( availablePlaylist == null || playlistForNameFunction == null ) return ; this . availablePlaylist = availablePlaylist ; this . playlistForNameFunction = playlistForNameFunction ; capabilities . setBroadcasting ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method gets called when a new Command was found . It automatically fires the update Event or an error [CODESPLIT] public void handleCommandResources ( EventModel eventModel ) { List < ResourceModel < String >> resourceModels = eventModel . getListResourceContainer ( ) . provideResource ( CommandResource . ResourceID ) . stream ( ) . filter ( resourceModel -> resourceModel . getResource ( ) instanceof String ) . map ( resourceModel -> { try { //noinspection unchecked return ( ResourceModel < String > ) resourceModel ; } catch ( ClassCastException e ) { return null ; } } ) . filter ( Objects :: nonNull ) . collect ( Collectors . toList ( ) ) ; for ( ResourceModel < String > resourceModel : resourceModels ) { if ( ! CommandResource . verifyCommand ( resourceModel . getResource ( ) ) ) continue ; if ( ! CommandResource . verifyCapabilities ( resourceModel . getResource ( ) , capabilities ) ) { musicHelper . playerError ( PlayerError . ERROR_NOT_ABLE + \"command: \" + resourceModel . getResource ( ) , resourceModel . getProvider ( ) ) ; continue ; } switch ( resourceModel . getResource ( ) ) { case CommandResource . PLAY : if ( ! musicProvider . isPlaying ( ) ) playPause . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . PAUSE : if ( musicProvider . isPlaying ( ) ) playPause . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . SELECT_TRACK : handleSelectTrack ( eventModel , resourceModel ) ; break ; case CommandResource . NEXT : nextPrevious . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . PREVIOUS : nextPrevious . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . JUMP : handleJump ( eventModel , resourceModel ) ; break ; case CommandResource . CHANGE_PLAYBACK : changePlayback . accept ( resourceModel . getResource ( ) ) ; break ; case CommandResource . CHANGE_VOLUME : handleVolume ( eventModel , resourceModel ) ; break ; case CommandResource . STOP : stopCallback . run ( ) ; break ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles the volume - command [CODESPLIT] private void handleVolume ( EventModel eventModel , ResourceModel < String > resourceModel ) { Optional < Volume > volumeResource = VolumeResource . getVolume ( eventModel ) ; if ( ! volumeResource . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + \"command: \" + resourceModel . getResource ( ) + \"missing resource\" , resourceModel . getProvider ( ) ) ; } changeVolume . accept ( volumeResource . get ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles the jump - command [CODESPLIT] private void handleJump ( EventModel eventModel , ResourceModel < String > resourceModel ) { Optional < Progress > progress = ProgressResource . getProgress ( eventModel ) ; if ( ! progress . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + \"command: \" + resourceModel . getResource ( ) + \"missing resource\" , resourceModel . getProvider ( ) ) ; } jumpProgress . accept ( progress . get ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "handles the select Track command [CODESPLIT] private void handleSelectTrack ( EventModel eventModel , ResourceModel < String > resourceModel ) { Optional < TrackInfo > trackInfo = TrackInfoResource . getTrackInfo ( eventModel ) ; if ( ! trackInfo . isPresent ( ) ) { musicHelper . playerError ( PlayerError . ERROR_ILLEGAL + \"command: \" + resourceModel . getResource ( ) + \"missing resource\" , resourceModel . getProvider ( ) ) ; } selectTrack . accept ( trackInfo . get ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public < V > Cache < V > getCache ( String name , CacheScope scope ) { switch ( scope ) { case INSTANCE : return getInstanceCache ( name ) ; case CLUSTERINVALIDATED : return getInstanceCache ( name ) ; case CLUSTERREPLICATED : return getInstanceCache ( name ) ; case REQUEST : return getRequestCache ( name ) ; case THREAD : return getThreadCache ( name ) ; default : return getInstanceCache ( name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a cache bound to the thread . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private < V > Cache < V > getThreadCache ( String name ) { Map < String , Cache < ? > > threadCacheMap = threadCacheMapHolder . get ( ) ; Cache < V > threadCache = ( Cache < V > ) threadCacheMap . get ( name ) ; if ( threadCache == null ) { threadCache = new MapCacheImpl < V > ( ) ; threadCacheMap . put ( name , threadCache ) ; } return threadCache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generate a cache bound to the request [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) private < V > Cache < V > getRequestCache ( String name ) { Map < String , Cache < ? > > requestCacheMap = requestCacheMapHolder . get ( ) ; Cache < V > requestCache = ( Cache < V > ) requestCacheMap . get ( name ) ; if ( requestCache == null ) { requestCache = new MapCacheImpl < V > ( ) ; requestCacheMap . put ( name , requestCache ) ; } return requestCache ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onDelete ( String zone , String path , String user , String resourceType , Map < String , Object > beforeEvent , String ... attributes ) { String topic = DEFAULT_DELETE_TOPIC ; if ( deleteTopics . containsKey ( zone ) ) { topic = deleteTopics . get ( zone ) ; } postEvent ( topic , path , user , resourceType , beforeEvent , attributes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void onUpdate ( String zone , String path , String user , String resourceType , boolean isNew , Map < String , Object > beforeEvent , String ... attributes ) { String topic = DEFAULT_UPDATE_TOPIC ; if ( isNew ) { topic = DEFAULT_CREATE_TOPIC ; if ( deleteTopics . containsKey ( zone ) ) { topic = createTopics . get ( zone ) ; } } else { if ( deleteTopics . containsKey ( zone ) ) { topic = updateTopics . get ( zone ) ; } } postEvent ( topic , path , user , resourceType , beforeEvent , attributes ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the name of an alternative field for an alternative stream . [CODESPLIT] public static String getAltField ( String field , String streamId ) { if ( streamId == null ) { return field ; } return field + \"/\" + streamId ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static String insecureHash ( String naked ) { try { return insecureHash ( naked . getBytes ( UTF8 ) ) ; } catch ( UnsupportedEncodingException e3 ) { LOGGER . error ( \"no UTF-8 Envoding, get a real JVM, nothing will work here. NPE to come\" ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts to an Immutable map with keys that are in the filter not transfered . Nested maps are also transfered . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static < K , V > Map < K , V > getFilterMap ( Map < K , V > source , Map < K , V > modified , Set < K > include , Set < K > exclude , boolean includingRemoveProperties ) { if ( ( modified == null || modified . size ( ) == 0 ) && ( include == null ) && ( exclude == null || exclude . size ( ) == 0 ) ) { if ( source instanceof ImmutableMap ) { return source ; } else { return ImmutableMap . copyOf ( source ) ; } } Builder < K , V > filteredMap = new ImmutableMap . Builder < K , V > ( ) ; for ( Entry < K , V > e : source . entrySet ( ) ) { K k = e . getKey ( ) ; if ( include == null || include . contains ( k ) ) { if ( exclude == null || ! exclude . contains ( k ) ) { if ( modified != null && modified . containsKey ( k ) ) { V o = modified . get ( k ) ; if ( o instanceof Map ) { filteredMap . put ( k , ( V ) getFilterMap ( ( Map < K , V > ) o , null , null , exclude , includingRemoveProperties ) ) ; } else if ( includingRemoveProperties ) { filteredMap . put ( k , o ) ; } else if ( ! ( o instanceof RemoveProperty ) ) { filteredMap . put ( k , o ) ; } } else { Object o = e . getValue ( ) ; if ( o instanceof Map ) { filteredMap . put ( k , ( V ) getFilterMap ( ( Map < K , V > ) e . getValue ( ) , null , null , exclude , includingRemoveProperties ) ) ; } else { filteredMap . put ( k , e . getValue ( ) ) ; } } } } } if ( modified != null ) { // process additions for ( Entry < K , V > e : modified . entrySet ( ) ) { K k = e . getKey ( ) ; if ( ! source . containsKey ( k ) ) { V v = e . getValue ( ) ; if ( ! ( v instanceof RemoveProperty ) && v != null ) { filteredMap . put ( k , v ) ; } } } } return filteredMap . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Converts a map into Map or byte [] values with String keys . No control over depth of nesting . Keys in the filter set are not transfered Resulting map is mutable . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Map < String , Object > getFilteredAndEcodedMap ( Map < String , Object > source , Set < String > filter ) { Map < String , Object > filteredMap = Maps . newHashMap ( ) ; for ( Entry < String , Object > e : source . entrySet ( ) ) { if ( ! filter . contains ( e . getKey ( ) ) ) { Object o = e . getValue ( ) ; if ( o instanceof Map ) { filteredMap . put ( e . getKey ( ) , getFilteredAndEcodedMap ( ( Map < String , Object > ) o , filter ) ) ; } else { filteredMap . put ( e . getKey ( ) , o ) ; } } } return filteredMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "For instance the SparsePrincipal uses it . [CODESPLIT] public static String shardPath ( String id ) { String hash = insecureHash ( id ) ; return hash . substring ( 0 , 2 ) + \"/\" + hash . substring ( 2 , 4 ) + \"/\" + hash . substring ( 4 , 6 ) + \"/\" + id ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static String arrayEscape ( String string ) { string = string . replaceAll ( \"%\" , \"%1\" ) ; string = string . replaceAll ( \",\" , \"%2\" ) ; return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public static String arrayUnEscape ( String string ) { string = string . replaceAll ( \"%2\" , \",\" ) ; string = string . replaceAll ( \"%1\" , \"%\" ) ; return string ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adapt an object to a session . I haven t used typing here becuase I don t want to bind to the Jars in question and create dependencies . [CODESPLIT] public static Session adaptToSession ( Object source ) { if ( source instanceof SessionAdaptable ) { return ( ( SessionAdaptable ) source ) . getSession ( ) ; } else { // assume this is a JCR session of someform, in which case there // should be a SparseUserManager Object userManager = safeMethod ( source , \"getUserManager\" , new Object [ 0 ] , new Class [ 0 ] ) ; if ( userManager != null ) { return ( Session ) safeMethod ( userManager , \"getSession\" , new Object [ 0 ] , new Class [ 0 ] ) ; } return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Make the method on the target object accessible and then invoke it . [CODESPLIT] private static Object safeMethod ( Object target , String methodName , Object [ ] args , @ SuppressWarnings ( \"rawtypes\" ) Class [ ] argsTypes ) { if ( target != null ) { try { Method m = target . getClass ( ) . getMethod ( methodName , argsTypes ) ; if ( ! m . isAccessible ( ) ) { m . setAccessible ( true ) ; } return m . invoke ( target , args ) ; } catch ( Throwable e ) { LOGGER . info ( \"Failed to invoke method \" + methodName + \" \" + target , e ) ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delete an entire tree starting from the deepest part of the tree and working back up . Will stop the moment a permission denied is encountered either for read or for delete . [CODESPLIT] public static void deleteTree ( ContentManager contentManager , String path ) throws AccessDeniedException , StorageClientException { Content content = contentManager . get ( path ) ; if ( content != null ) { for ( String childPath : content . listChildPaths ( ) ) { deleteTree ( contentManager , childPath ) ; } } contentManager . delete ( path ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to get existing [ key1 key2 key3 key4 ] value or create new one if it s absent . Needs implementation of create ( key1 key2 key3 key4 ) in order to work [CODESPLIT] public V getOrCreate ( K1 key1 , K2 key2 , K3 key3 , K4 key4 ) { // already got it?\r MultiKey multi_key = new MultiKey ( key1 , key2 , key3 , key4 ) ; if ( containsKey ( multi_key ) ) return get ( multi_key ) ; // if not, create and add it\r V result = create ( key1 , key2 , key3 , key4 ) ; put ( multi_key , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Only update specified properties of the Object [CODESPLIT] @ Override public void updateOne ( E object , String ... properties ) { if ( object . getId ( ) == null ) { throw new RuntimeException ( \"Not a Persisted entity\" ) ; } if ( properties == null || properties . length == 0 ) { entityManager . merge ( object ) ; return ; } // for performance reason its better to mix getting fields, their values\r // and making query all in one loop\r // in one iteration\r StringBuilder sb = new StringBuilder ( ) ; sb . append ( \"Update \" + clazz . getName ( ) + \" SET \" ) ; // cache of fieldName --> value\r Map < String , Object > cache = new HashMap < String , Object > ( ) ; for ( String prop : properties ) { try { Field field = object . getClass ( ) . getDeclaredField ( prop ) ; field . setAccessible ( true ) ; Object value = field . get ( object ) ; if ( value instanceof Collection ) { // value = new LinkedList<>((Collection< ? extends Object>) value);\r throw new RuntimeException ( \"Collection property is not suppotred.\" ) ; } cache . put ( prop , value ) ; // ignore first comma\r if ( cache . size ( ) > 1 ) { sb . append ( \" ,\" ) ; } sb . append ( prop ) ; sb . append ( \" = :\" ) ; sb . append ( prop ) ; } catch ( Exception e ) { // TODO: use fine grain exceptions\r // FIX: NEXT RELEASE I hope :)\r throw new RuntimeException ( e ) ; } } // this means nothing will be updated so hitting db is unnecessary\r if ( cache . size ( ) == 0 ) return ; sb . append ( \" WHERE id = \" + object . getId ( ) ) ; Query query = entityManager . createQuery ( sb . toString ( ) ) ; for ( Entry < String , Object > entry : cache . entrySet ( ) ) { query . setParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } query . executeUpdate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieves a { @link KeepAliveManager } for the specified { @link Connection } creating one if it doesn t already exist . [CODESPLIT] public synchronized static KeepAliveManager getInstanceFor ( Connection connection ) { KeepAliveManager pingManager = instances . get ( connection ) ; if ( pingManager == null ) { pingManager = new KeepAliveManager ( connection ) ; instances . put ( connection , pingManager ) ; } return pingManager ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Start the executor service if it hasn t been started yet . [CODESPLIT] private synchronized static void enableExecutorService ( ) { if ( periodicPingExecutorService == null ) { periodicPingExecutorService = new ScheduledThreadPoolExecutor ( 1 , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable runnable ) { Thread pingThread = new Thread ( runnable , \"Smack Keepalive\" ) ; pingThread . setDaemon ( true ) ; return pingThread ; } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Stop the executor service if all monitored connections are disconnected . [CODESPLIT] private synchronized static void handleDisconnect ( Connection con ) { if ( periodicPingExecutorService != null ) { instances . remove ( con ) ; if ( instances . isEmpty ( ) ) { periodicPingExecutorService . shutdownNow ( ) ; periodicPingExecutorService = null ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Call after every connection to add the packet listener . [CODESPLIT] private void handleConnect ( ) { Connection connection = weakRefConnection . get ( ) ; // Listen for all incoming packets and reset the scheduled ping whenever // one arrives. connection . addPacketListener ( new PacketListener ( ) { @ Override public void processPacket ( Packet packet ) { // reschedule the ping based on this last server contact lastSuccessfulContact = System . currentTimeMillis ( ) ; schedulePingServerTask ( ) ; } } , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the ping interval . [CODESPLIT] public void setPingInterval ( long newPingInterval ) { if ( pingInterval == newPingInterval ) return ; // Enable the executor service if ( newPingInterval > 0 ) enableExecutorService ( ) ; pingInterval = newPingInterval ; if ( pingInterval < 0 ) { stopPinging ( ) ; } else { schedulePingServerTask ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Cancels any existing periodic ping task if there is one and schedules a new ping task if pingInterval is greater then zero . [CODESPLIT] private synchronized void schedulePingServerTask ( ) { enableExecutorService ( ) ; stopPingServerTask ( ) ; if ( pingInterval > 0 ) { periodicPingTask = periodicPingExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { Ping ping = new Ping ( ) ; PacketFilter responseFilter = new PacketIDFilter ( ping . getID ( ) ) ; Connection connection = weakRefConnection . get ( ) ; final PacketCollector response = pingFailedListeners . isEmpty ( ) ? null : connection . createPacketCollector ( responseFilter ) ; connection . sendPacket ( ping ) ; if ( response != null ) { // Schedule a collector for the ping reply, // notify listeners if none is received. periodicPingExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { Packet result = response . nextResult ( 1 ) ; // Stop queuing results response . cancel ( ) ; // The actual result of the // reply can be ignored since we // only care if we actually got // one. if ( result == null ) { for ( PingFailedListener listener : pingFailedListeners ) { listener . pingFailed ( ) ; } } } } , SmackConfiguration . getPacketReplyTimeout ( ) , TimeUnit . MILLISECONDS ) ; } } } , getPingInterval ( ) , TimeUnit . MILLISECONDS ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public final Object makeObject ( ) { log . debug ( \" makeObject...\" ) ; WorkerThread thread = new WorkerThread ( ) ; initialiseThread ( thread ) ; thread . start ( ) ; return thread ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public final void destroyObject ( Object obj ) { log . debug ( \" !!! destroyObject... !!!\" + obj ) ; if ( obj instanceof WorkerThread ) { WorkerThread rt = ( WorkerThread ) obj ; rt . setStopped ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public final boolean validateObject ( Object obj ) { log . debug ( \" validateObject...\" + obj ) ; if ( obj instanceof WorkerThread ) { WorkerThread rt = ( WorkerThread ) obj ; if ( ! rt . isDone ( ) ) { //if the thread is running the previous task, get another one.\r return false ; } if ( rt . isRunning ( ) ) { if ( rt . getThreadGroup ( ) == null ) { return false ; } return true ; } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void remove ( String key ) { V o = super . remove ( key ) ; if ( o instanceof ThreadBound ) { ( ( ThreadBound ) o ) . unbind ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void clear ( ) { for ( String k : super . keySet ( ) ) { Object o = get ( k ) ; if ( o instanceof ThreadBound ) { ( ( ThreadBound ) o ) . unbind ( ) ; } } super . clear ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void removeChildren ( String key ) { super . remove ( key ) ; if ( ! key . endsWith ( \"/\" ) ) { key = key + \"/\" ; } Set < String > keys = super . keySet ( ) ; for ( String k : keys ) { if ( ( k ) . startsWith ( key ) ) { super . remove ( k ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CLI option to the parser . [CODESPLIT] public ExecS_CliParser addOption ( ApplicationOption < ? > option ) { if ( option != null && option . getCliOption ( ) != null ) { this . _addOption ( option . getCliOption ( ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds all given option ignoring null elements . [CODESPLIT] public ExecS_CliParser addAllOptions ( ApplicationOption < ? > [ ] options ) { if ( options != null ) { for ( ApplicationOption < ? > option : options ) { this . addOption ( option ) ; } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a CLI option to the parser . [CODESPLIT] protected void _addOption ( Option option ) { if ( option == null ) { return ; } if ( this . usedOptions . contains ( option . getOpt ( ) ) ) { throw new IllegalArgumentException ( \"ExecS Cli: short option <\" + option . getOpt ( ) + \"> already in use\" ) ; } if ( this . usedOptions . contains ( option . getLongOpt ( ) ) ) { throw new IllegalArgumentException ( \"ExecS Cli: long option <\" + option . getLongOpt ( ) + \"> already in use\" ) ; } this . options . addOption ( option ) ; if ( option . getOpt ( ) != null ) { this . usedOptions . add ( option . getOpt ( ) ) ; } if ( option . getLongOpt ( ) != null ) { this . usedOptions . add ( option . getLongOpt ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if an option is already added to the parser . [CODESPLIT] public boolean hasOption ( Option option ) { if ( option == null ) { return false ; } if ( this . usedOptions . contains ( option . getOpt ( ) ) ) { return true ; } if ( this . usedOptions . contains ( option . getLongOpt ( ) ) ) { return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses command line arguments and fills set options . [CODESPLIT] public ParseException parse ( String [ ] args ) { ParseException ret = null ; CommandLineParser parser = new DefaultParser ( ) ; try { this . cmdLine = parser . parse ( this . options , args ) ; } catch ( ParseException pe ) { ret = pe ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a usage screen based on set options . [CODESPLIT] public void usage ( String appName ) { HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( appName , null , this . options , null , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses command line arguments for a given CLI parser . [CODESPLIT] static int doParse ( String [ ] args , ExecS_CliParser cli , String appName ) { Exception err = cli . parse ( args ) ; if ( err != null ) { System . err . println ( appName + \": error parsing command line -> \" + err . getMessage ( ) ) ; return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Closes the connection by setting presence to unavailable then closing the stream to the XMPP server . The shutdown logic will be used during a planned disconnection or when dealing with an unexpected disconnection . Unlike { @link #disconnect () } the connection s packet reader packet writer and { @link UserRoster } will not be removed ; thus connection s state is kept . [CODESPLIT] protected void shutdown ( Presence unavailablePresence ) { // Set presence to offline. if ( packetWriter != null ) { packetWriter . sendPacket ( unavailablePresence ) ; } this . setWasAuthenticated ( authenticated ) ; authenticated = false ; if ( packetReader != null ) { packetReader . shutdown ( ) ; } if ( packetWriter != null ) { packetWriter . shutdown ( ) ; } // Wait 150 ms for processes to clean-up, then shutdown. try { Thread . sleep ( 150 ) ; } catch ( Exception e ) { // Ignore. } // Set socketClosed to true. This will cause the PacketReader // and PacketWriter to ignore any Exceptions that are thrown // because of a read/write from/to a closed stream. // It is *important* that this is done before socket.close()! socketClosed = true ; try { socket . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } for ( Plugin plugin : plugins ) { plugin . shutdown ( ) ; } // In most cases the close() should be successful, so set // connected to false here. connected = false ; reader = null ; writer = null ; saslAuthentication . init ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the connection by creating a packet reader and writer and opening a XMPP stream to the server . [CODESPLIT] private void initConnection ( ) throws XMPPException { boolean isFirstInitialization = packetReader == null || packetWriter == null ; compressionHandler = null ; serverAckdCompression = false ; // Set the reader and writer instance variables initReaderAndWriter ( ) ; try { if ( isFirstInitialization ) { packetWriter = new PacketWriter ( this ) ; packetReader = new PacketReader ( this ) ; // If debugging is enabled, we should start the thread that will // listen for // all packets and then log them. if ( config . isDebuggerEnabled ( ) ) { addPacketListener ( debugger . getReaderListener ( ) , null ) ; if ( debugger . getWriterListener ( ) != null ) { addPacketSendingListener ( debugger . getWriterListener ( ) , null ) ; } } } else { packetWriter . init ( ) ; packetReader . init ( ) ; } // Start the packet writer. This will open a XMPP stream to the // server packetWriter . startup ( ) ; // Start the packet reader. The startup() method will block until we // get an opening stream packet back from server. packetReader . startup ( ) ; // Make note of the fact that we're now connected. connected = true ; if ( isFirstInitialization ) { // Notify listeners that a new connection has been established for ( ConnectionCreationListener listener : getConnectionCreationListeners ( ) ) { listener . connectionCreated ( this ) ; } } } catch ( XMPPException ex ) { // An exception occurred in setting up the connection. Make sure we // shut down the // readers and writers and close the socket. if ( packetWriter != null ) { try { packetWriter . shutdown ( ) ; } catch ( Throwable ignore ) { /* ignore */ } packetWriter = null ; } if ( packetReader != null ) { try { packetReader . shutdown ( ) ; } catch ( Throwable ignore ) { /* ignore */ } packetReader = null ; } if ( reader != null ) { try { reader . close ( ) ; } catch ( Throwable ignore ) { /* ignore */ } reader = null ; } if ( writer != null ) { try { writer . close ( ) ; } catch ( Throwable ignore ) { /* ignore */ } writer = null ; } if ( socket != null ) { try { socket . close ( ) ; } catch ( Exception e ) { /* ignore */ } socket = null ; } this . setWasAuthenticated ( authenticated ) ; authenticated = false ; connected = false ; throw ex ; // Everything stoppped. Now throw the exception. } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notification message saying that the server supports TLS so confirm the server that we want to secure the connection . [CODESPLIT] void startTLSReceived ( boolean required ) { if ( required && config . getSecurityMode ( ) == ConnectionConfiguration . SecurityMode . disabled ) { notifyConnectionError ( new IllegalStateException ( \"TLS required by server but not allowed by connection configuration\" ) ) ; return ; } if ( config . getSecurityMode ( ) == ConnectionConfiguration . SecurityMode . disabled ) { // Do not secure the connection using TLS since TLS was disabled return ; } try { writer . write ( \"<starttls xmlns=\\\"urn:ietf:params:xml:ns:xmpp-tls\\\"/>\" ) ; writer . flush ( ) ; } catch ( IOException e ) { notifyConnectionError ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The server has indicated that TLS negotiation can start . We now need to secure the existing plain connection and perform a handshake . This method won t return until the connection has finished the handshake or an error occured while securing the connection . [CODESPLIT] void proceedTLSReceived ( ) throws Exception { SSLContext context = this . config . getCustomSSLContext ( ) ; KeyStore ks = null ; KeyManager [ ] kms = null ; PasswordCallback pcb = null ; if ( config . getCallbackHandler ( ) == null ) { ks = null ; } else if ( context == null ) { if ( config . getKeystoreType ( ) . equals ( \"NONE\" ) ) { ks = null ; pcb = null ; } else if ( config . getKeystoreType ( ) . equals ( \"PKCS11\" ) ) { try { Constructor < ? > c = Class . forName ( \"sun.security.pkcs11.SunPKCS11\" ) . getConstructor ( InputStream . class ) ; String pkcs11Config = \"name = SmartCard\\nlibrary = \" + config . getPKCS11Library ( ) ; ByteArrayInputStream config = new ByteArrayInputStream ( pkcs11Config . getBytes ( ) ) ; Provider p = ( Provider ) c . newInstance ( config ) ; Security . addProvider ( p ) ; ks = KeyStore . getInstance ( \"PKCS11\" , p ) ; pcb = new PasswordCallback ( \"PKCS11 Password: \" , false ) ; this . config . getCallbackHandler ( ) . handle ( new Callback [ ] { pcb } ) ; ks . load ( null , pcb . getPassword ( ) ) ; } catch ( Exception e ) { ks = null ; pcb = null ; } } else if ( config . getKeystoreType ( ) . equals ( \"Apple\" ) ) { ks = KeyStore . getInstance ( \"KeychainStore\" , \"Apple\" ) ; ks . load ( null , null ) ; // pcb = new PasswordCallback(\"Apple Keychain\",false); // pcb.setPassword(null); } else { ks = KeyStore . getInstance ( config . getKeystoreType ( ) ) ; try { pcb = new PasswordCallback ( \"Keystore Password: \" , false ) ; config . getCallbackHandler ( ) . handle ( new Callback [ ] { pcb } ) ; ks . load ( new FileInputStream ( config . getKeystorePath ( ) ) , pcb . getPassword ( ) ) ; } catch ( Exception e ) { ks = null ; pcb = null ; } } KeyManagerFactory kmf = KeyManagerFactory . getInstance ( \"SunX509\" ) ; try { if ( pcb == null ) { kmf . init ( ks , null ) ; } else { kmf . init ( ks , pcb . getPassword ( ) ) ; pcb . clearPassword ( ) ; } kms = kmf . getKeyManagers ( ) ; } catch ( NullPointerException npe ) { kms = null ; } } // Verify certificate presented by the server if ( context == null ) { context = SSLContext . getInstance ( \"TLS\" ) ; context . init ( kms , null , new java . security . SecureRandom ( ) ) ; } Socket plain = socket ; // Secure the plain connection socket = context . getSocketFactory ( ) . createSocket ( plain , plain . getInetAddress ( ) . getHostAddress ( ) , plain . getPort ( ) , true ) ; socket . setSoTimeout ( 0 ) ; socket . setKeepAlive ( true ) ; // Initialize the reader and writer with the new secured version initReaderAndWriter ( ) ; // Proceed to do the handshake ( ( SSLSocket ) socket ) . startHandshake ( ) ; // if (((SSLSocket) socket).getWantClientAuth()) { // System.err.println(\"Connection wants client auth\"); // } // else if (((SSLSocket) socket).getNeedClientAuth()) { // System.err.println(\"Connection needs client auth\"); // } // else { // System.err.println(\"Connection does not require client auth\"); // } // Set that TLS was successful usingTLS = true ; // Set the new writer to use packetWriter . setWriter ( writer ) ; // Send a new opening stream to the server packetWriter . openStream ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the compression handler that can be used for one compression methods offered by the server . [CODESPLIT] private XMPPInputOutputStream maybeGetCompressionHandler ( ) { if ( compressionMethods != null ) { for ( XMPPInputOutputStream handler : compressionHandlers ) { if ( ! handler . isSupported ( ) ) continue ; String method = handler . getCompressionMethod ( ) ; if ( compressionMethods . contains ( method ) ) return handler ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts using stream compression that will compress network traffic . Traffic can be reduced up to 90% . Therefore stream compression is ideal when using a slow speed network connection . However the server and the client will need to use more CPU time in order to un / compress network data so under high load the server performance might be affected . <p > <p / > Stream compression has to have been previously offered by the server . Currently only the zlib method is supported by the client . Stream compression negotiation has to be done before authentication took place . <p > <p / > Note : to use stream compression the smackx . jar file has to be present in the classpath . [CODESPLIT] private boolean useCompression ( ) { // If stream compression was offered by the server and we want to use // compression then send compression request to the server if ( authenticated ) { throw new IllegalStateException ( \"Compression should be negotiated before authentication.\" ) ; } if ( ( compressionHandler = maybeGetCompressionHandler ( ) ) != null ) { requestStreamCompression ( compressionHandler . getCompressionMethod ( ) ) ; // Wait until compression is being used or a timeout happened synchronized ( this ) { try { this . wait ( SmackConfiguration . getPacketReplyTimeout ( ) * 5 ) ; } catch ( InterruptedException e ) { // Ignore. } } return isUsingCompression ( ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Request the server that we want to start using stream compression . When using TLS then negotiation of stream compression can only happen after TLS was negotiated . If TLS compression is being used the stream compression should not be used . [CODESPLIT] private void requestStreamCompression ( String method ) { try { writer . write ( \"<compress xmlns='http://jabber.org/protocol/compress'>\" ) ; writer . write ( \"<method>\" + method + \"</method></compress>\" ) ; writer . flush ( ) ; } catch ( IOException e ) { notifyConnectionError ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Start using stream compression since the server has acknowledged stream compression . [CODESPLIT] void startStreamCompression ( ) throws Exception { serverAckdCompression = true ; // Initialize the reader and writer with the new secured version initReaderAndWriter ( ) ; // Set the new writer to use packetWriter . setWriter ( writer ) ; // Send a new opening stream to the server packetWriter . openStream ( ) ; // Notify that compression is being used synchronized ( this ) { this . notify ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Establishes a connection to the XMPP server and performs an automatic login only if the previous connection state was logged ( authenticated ) . It basically creates and maintains a socket connection to the server . <p > <p / > Listeners will be preserved from a previous connection if the reconnection occurs after an abrupt termination . [CODESPLIT] public void connect ( ) throws XMPPException { // Establishes the connection, readers and writers connectUsingConfiguration ( config ) ; // Automatically makes the login if the user was previously connected // successfully // to the server and the connection was terminated abruptly if ( connected && wasAuthenticated ) { // Make the login if ( isAnonymous ( ) ) { // Make the anonymous login loginAnonymously ( ) ; } else { login ( config . getUsername ( ) , config . getPassword ( ) , config . getResource ( ) ) ; } notifyReconnection ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends out a notification that there was an error with the connection and closes the connection . Also prints the stack trace of the given exception [CODESPLIT] synchronized void notifyConnectionError ( Exception e ) { // Listeners were already notified of the exception, return right here. if ( ( packetReader == null || packetReader . done ) && ( packetWriter == null || packetWriter . done ) ) return ; if ( packetReader != null ) packetReader . done = true ; if ( packetWriter != null ) packetWriter . done = true ; // Closes the connection temporary. A reconnection is possible shutdown ( new Presence ( Presence . Type . unavailable ) ) ; // Notify connection listeners of the error. for ( ConnectionListener listener : getConnectionListeners ( ) ) { try { listener . connectionClosedOnError ( e ) ; } catch ( Exception e2 ) { // Catch and print any exception so we can recover // from a faulty listener e2 . printStackTrace ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends a notification indicating that the connection was reconnected successfully . [CODESPLIT] protected void notifyReconnection ( ) { // Notify connection listeners of the reconnection. for ( ConnectionListener listener : getConnectionListeners ( ) ) { try { listener . reconnectionSuccessful ( ) ; } catch ( Exception e ) { // Catch and print any exception so we can recover // from a faulty listener e . printStackTrace ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a new SASL mechanism [CODESPLIT] public static void registerSASLMechanism ( String name , Class < ? extends SASLMechanism > mClass ) { implementedMechanisms . put ( name , mClass ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the registerd SASLMechanism classes sorted by the level of preference . [CODESPLIT] public static List < Class < ? extends SASLMechanism > > getRegisterSASLMechanisms ( ) { List < Class < ? extends SASLMechanism > > answer = new ArrayList < Class < ? extends SASLMechanism > > ( ) ; for ( String mechanismsPreference : mechanismsPreferences ) { answer . add ( implementedMechanisms . get ( mechanismsPreference ) ) ; } return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs SASL authentication of the specified user . If SASL authentication was successful then resource binding and session establishment will be performed . This method will return the full JID provided by the server while binding a resource to the connection . <p > [CODESPLIT] public String authenticate ( String username , String resource , CallbackHandler cbh ) throws XMPPException { // Locate the SASLMechanism to use String selectedMechanism = null ; for ( String mechanism : mechanismsPreferences ) { if ( implementedMechanisms . containsKey ( mechanism ) && serverMechanisms . contains ( mechanism ) ) { selectedMechanism = mechanism ; break ; } } if ( selectedMechanism != null ) { // A SASL mechanism was found. Authenticate using the selected // mechanism and then // proceed to bind a resource try { Class < ? extends SASLMechanism > mechanismClass = implementedMechanisms . get ( selectedMechanism ) ; Constructor < ? extends SASLMechanism > constructor = mechanismClass . getConstructor ( SASLAuthentication . class ) ; currentMechanism = constructor . newInstance ( this ) ; // Trigger SASL authentication with the selected mechanism. We // use // connection.getHost() since GSAPI requires the FQDN of the // server, which // may not match the XMPP domain. currentMechanism . authenticate ( username , connection . getHost ( ) , cbh ) ; // Wait until SASL negotiation finishes synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 30000 ) ; } catch ( InterruptedException e ) { // Ignore } } } if ( saslFailed ) { // SASL authentication failed and the server may have closed // the connection // so throw an exception if ( errorCondition != null ) { throw new XMPPException ( \"SASL authentication \" + selectedMechanism + \" failed: \" + errorCondition ) ; } else { throw new XMPPException ( \"SASL authentication failed using mechanism \" + selectedMechanism ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and return bindResourceAndEstablishSession ( resource ) ; } else { // SASL authentication failed } } catch ( XMPPException e ) { throw e ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else { throw new XMPPException ( \"SASL Authentication failed. No known authentication mechanisims.\" ) ; } throw new XMPPException ( \"SASL authentication failed\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs SASL authentication of the specified user . If SASL authentication was successful then resource binding and session establishment will be performed . This method will return the full JID provided by the server while binding a resource to the connection . <p > [CODESPLIT] public String authenticate ( String username , String password , String resource ) throws XMPPException { // Locate the SASLMechanism to use String selectedMechanism = null ; for ( String mechanism : mechanismsPreferences ) { if ( implementedMechanisms . containsKey ( mechanism ) && serverMechanisms . contains ( mechanism ) ) { selectedMechanism = mechanism ; break ; } } if ( selectedMechanism != null ) { // A SASL mechanism was found. Authenticate using the selected // mechanism and then // proceed to bind a resource try { Class < ? extends SASLMechanism > mechanismClass = implementedMechanisms . get ( selectedMechanism ) ; Constructor < ? extends SASLMechanism > constructor = mechanismClass . getConstructor ( SASLAuthentication . class ) ; currentMechanism = constructor . newInstance ( this ) ; // Trigger SASL authentication with the selected mechanism. We // use // connection.getHost() since GSAPI requires the FQDN of the // server, which // may not match the XMPP domain. // The serviceName is basically the value that XMPP server sends // to the client as being the location // of the XMPP service we are trying to connect to. This should // have the format: host [ \"/\" serv-name ] // as per RFC-2831 guidelines String serviceName = connection . getServiceName ( ) ; currentMechanism . authenticate ( username , connection . getHost ( ) , serviceName , password ) ; // Wait until SASL negotiation finishes synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 30000 ) ; } catch ( InterruptedException e ) { // Ignore } } } if ( saslFailed ) { // SASL authentication failed and the server may have closed // the connection // so throw an exception if ( errorCondition != null ) { throw new XMPPException ( \"SASL authentication \" + selectedMechanism + \" failed: \" + errorCondition ) ; } else { throw new XMPPException ( \"SASL authentication failed using mechanism \" + selectedMechanism ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and return bindResourceAndEstablishSession ( resource ) ; } else { // SASL authentication failed so try a Non-SASL // authentication return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } } catch ( XMPPException e ) { throw e ; } catch ( Exception e ) { e . printStackTrace ( ) ; // SASL authentication failed so try a Non-SASL authentication return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } } else { // No SASL method was found so try a Non-SASL authentication return new NonSASLAuthentication ( connection ) . authenticate ( username , password , resource ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs ANONYMOUS SASL authentication . If SASL authentication was successful then resource binding and session establishment will be performed . This method will return the full JID provided by the server while binding a resource to the connection . <p > [CODESPLIT] public String authenticateAnonymously ( ) throws XMPPException { try { currentMechanism = new SASLAnonymous ( this ) ; currentMechanism . authenticate ( null , null , null , \"\" ) ; // Wait until SASL negotiation finishes synchronized ( this ) { if ( ! saslNegotiated && ! saslFailed ) { try { wait ( 5000 ) ; } catch ( InterruptedException e ) { // Ignore } } } if ( saslFailed ) { // SASL authentication failed and the server may have closed the // connection // so throw an exception if ( errorCondition != null ) { throw new XMPPException ( \"SASL authentication failed: \" + errorCondition ) ; } else { throw new XMPPException ( \"SASL authentication failed\" ) ; } } if ( saslNegotiated ) { // Bind a resource for this connection and return bindResourceAndEstablishSession ( null ) ; } else { return new NonSASLAuthentication ( connection ) . authenticateAnonymously ( ) ; } } catch ( IOException e ) { return new NonSASLAuthentication ( connection ) . authenticateAnonymously ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "========= PROPFIND PROPPATCH Support =============================== [CODESPLIT] public Object getProperty ( QName name ) { String n = getFullName ( name ) ; Object o = content . getProperty ( n ) ; LOGGER . debug ( \"-------------- GETTING {} as {} --------------\" , n , o ) ; return o ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "========= LOCK Support =============================== [CODESPLIT] public LockToken createAndLock ( String name , LockTimeout timeout , LockInfo lockInfo ) throws NotAuthorizedException { LOGGER . debug ( \"Create And Lock {} {} \" , timeout , lockInfo ) ; try { String newPath = StorageClientUtils . newPath ( path , name ) ; LockHolder lockHolder = new LockHolder ( lockInfo , timeout ) ; String token = session . getLockManager ( ) . lock ( newPath , lockHolder . getTimeoutInSeconds ( ) , lockHolder . toString ( ) ) ; return new LockToken ( token , lockInfo , timeout ) ; } catch ( StorageClientException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new NotAuthorizedException ( this ) ; } catch ( AlreadyLockedException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new NotAuthorizedException ( this ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method sets the controls for the Output - Plugin Behaviour . <p > Supply a Function which controls the OutputPlugin - Behaviour . You can set Priorities . The output - plugin with the highest POSITIVE priority ( in int ) will be processed first . Negative priorities are processed last ( so outputPlugins with no priorities will be processed in between positive and negative priorities ) [CODESPLIT] public void controlOutputPluginBehaviour ( Function < List < Identification > , HashMap < Integer , List < Identification > > > outputPluginBehaviour ) { this . outputPluginBehaviour = outputPluginBehaviour ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generates the data to control the Event [CODESPLIT] @ Override public HashMap < Integer , List < Identification > > getOutputPluginBehaviour ( List < Identification > identifications ) { if ( outputPluginBehaviour == null ) return new HashMap <> ( ) ; return outputPluginBehaviour . apply ( identifications ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Define the sling . home parameter implementing the algorithme defined on the wiki page to find the setting according to this algorithm : <ol > <li > Command line option <code > - c< / code > < / li > <li > System property <code > sling . home< / code > < / li > <li > Environment variable <code > SLING_HOME< / code > < / li > <li > Default value <code > sling< / code > < / li > < / ol > [CODESPLIT] private static String getSlingHome ( Map < String , String > commandLine ) { String source = null ; String slingHome = commandLine . get ( \"c\" ) ; if ( slingHome != null ) { source = \"command line\" ; } else { slingHome = System . getProperty ( SharedConstants . SLING_HOME ) ; if ( slingHome != null ) { source = \"system property sling.home\" ; } else { slingHome = System . getenv ( ENV_SLING_HOME ) ; if ( slingHome != null ) { source = \"environment variable SLING_HOME\" ; } else { source = \"default\" ; slingHome = SharedConstants . SLING_HOME_DEFAULT ; } } } System . setProperty ( SharedConstants . SLING_HOME , slingHome ) ; info ( \"Setting sling.home=\" + slingHome + \" (\" + source + \")\" , null ) ; return slingHome ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses the command line arguments into a map of strings indexed by strings . This method suppports single character option names only at the moment . Each pair of an option name and its value is stored into the map . If a single dash - character is encountered the rest of the command line are interpreted as option names and are stored in the map unmodified as entries with the same key and value . <table > <tr > <th > Command Line< / th > <th > Mapping< / th > < / tr > <tr > <td > x< / td > <td > x - > x< / td > < / tr > <tr > <td > - y z< / td > <td > y - > z< / td > < / tr > <tr > <td > - yz< / td > <td > y - > z< / td > < / tr > <tr > <td > - y - z< / td > <td > y - > y z - > z< / td > < / tr > <tr > <td > - y x - - z a< / td > <td > y - > x - z - > - z a - > a< / td > < / tr > < / table > [CODESPLIT] static Map < String , String > parseCommandLine ( String [ ] args ) { Map < String , String > commandLine = new HashMap < String , String > ( ) ; boolean readUnparsed = false ; for ( int argc = 0 ; args != null && argc < args . length ; argc ++ ) { String arg = args [ argc ] ; if ( readUnparsed ) { commandLine . put ( arg , arg ) ; } else if ( arg . startsWith ( \"-\" ) ) { if ( arg . length ( ) == 1 ) { readUnparsed = true ; } else { String key = String . valueOf ( arg . charAt ( 1 ) ) ; if ( arg . length ( ) > 2 ) { commandLine . put ( key , arg . substring ( 2 ) ) ; } else { argc ++ ; if ( argc < args . length && ( args [ argc ] . equals ( \"-\" ) || ! args [ argc ] . startsWith ( \"-\" ) ) ) { commandLine . put ( key , args [ argc ] ) ; } else { commandLine . put ( key , key ) ; argc -- ; } } } } else { commandLine . put ( arg , arg ) ; } } return commandLine ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "emit an informational message to standard out [CODESPLIT] static void info ( String message , Throwable t ) { log ( System . out , \"*INFO*\" , message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "emit an error message to standard err [CODESPLIT] static void error ( String message , Throwable t ) { log ( System . err , \"*ERROR*\" , message , t ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the throwable if not - null is also prefixed line by line with the prefix [CODESPLIT] private static void log ( PrintStream out , String prefix , String message , Throwable t ) { final StringBuilder linePrefixBuilder = new StringBuilder ( ) ; synchronized ( fmt ) { linePrefixBuilder . append ( fmt . format ( new Date ( ) ) ) ; } linePrefixBuilder . append ( prefix ) ; linePrefixBuilder . append ( \" [\" ) ; linePrefixBuilder . append ( Thread . currentThread ( ) . getName ( ) ) ; linePrefixBuilder . append ( \"] \" ) ; final String linePrefix = linePrefixBuilder . toString ( ) ; out . print ( linePrefix ) ; out . println ( message ) ; if ( t != null ) { t . printStackTrace ( new PrintStream ( out ) { @ Override public void println ( String x ) { synchronized ( this ) { print ( linePrefix ) ; super . println ( x ) ; flush ( ) ; } } } ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StartEvent . Assumes the Output is using the java - sound output . [CODESPLIT] public static Optional < StartEvent > createStartEvent ( Identification source ) { try { StartEvent startRequest = new StartEvent ( source ) ; return Optional . of ( startRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StartEvent [CODESPLIT] public static Optional < StartEvent > createStartEvent ( Identification source , boolean isUsingJava ) { try { StartEvent startEvent ; if ( isUsingJava ) { startEvent = new StartEvent ( source ) ; } else { startEvent = new StartEvent ( source , IS_USING_NON_JAVA_OUTPUT ) ; } return Optional . of ( startEvent ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notify that a new string has been written . [CODESPLIT] private void notifyListeners ( String str ) { WriterListener [ ] writerListeners = null ; synchronized ( listeners ) { writerListeners = new WriterListener [ listeners . size ( ) ] ; listeners . toArray ( writerListeners ) ; } for ( int i = 0 ; i < writerListeners . length ; i ++ ) { writerListeners [ i ] . write ( str ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks whether it can provide the resource [CODESPLIT] @ Override public boolean providesResource ( ResourceModel resource ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourceS -> resourceS . equals ( resource . getResourceID ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks whether there are any resources registered from the source [CODESPLIT] @ Override public boolean containsResourcesFromSource ( String sourceID ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( source -> source . equals ( sourceID ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "checks whether the ResourceContainer can provide at least ONE resource [CODESPLIT] @ Override public boolean providesResource ( List < String > resourcesIDs ) { return resources . stream ( ) . map ( ResourceModel :: getResourceID ) . anyMatch ( resourcesIDs :: contains ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns all EXISTING resources for the ID . If there are no resources for the ID the ID will get skipped [CODESPLIT] @ Override public List < ResourceModel > provideResource ( String [ ] resourceIDs ) { return resources . stream ( ) . filter ( resource -> Arrays . stream ( resourceIDs ) . anyMatch ( resourceID -> resourceID . equals ( resource . getResourceID ( ) ) ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the resource ( if existing ) from the source [CODESPLIT] @ Override public List < ResourceModel > provideResourceFromSource ( String sourceID ) { return resources . stream ( ) . filter ( resource -> resource . getProvider ( ) . getID ( ) . equals ( sourceID ) ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > TransactionalSortedFilterableBidiMap < K , V > decorate ( TransactionalSortedFilterableBidiMap < K , V > map ) { return new SynchronizedTransactionalSortedFilterableBidiMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Try to retrieve an object from the cache . Has the side - effect of loading an uncached object into cache the first time . [CODESPLIT] protected Map < String , Object > getCached ( String keySpace , String columnFamily , String key ) throws StorageClientException { Map < String , Object > m = null ; String cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; CacheHolder cacheHolder = getFromCacheInternal ( cacheKey ) ; if ( cacheHolder != null ) { m = cacheHolder . get ( ) ; if ( m != null ) { LOGGER . debug ( \"Cache Hit {} {} {} \" , new Object [ ] { cacheKey , cacheHolder , m } ) ; } } if ( m == null ) { m = client . get ( keySpace , columnFamily , key ) ; if ( m != null ) { LOGGER . debug ( \"Cache Miss, Found Map {} {}\" , cacheKey , m ) ; } putToCacheInternal ( cacheKey , new CacheHolder ( m ) , true ) ; } return m ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Combine the parameters into a key suitable for storage and lookup in the cache . [CODESPLIT] private String getCacheKey ( String keySpace , String columnFamily , String key ) throws StorageClientException { if ( client instanceof RowHasher ) { return ( ( RowHasher ) client ) . rowHash ( keySpace , columnFamily , key ) ; } return keySpace + \":\" + columnFamily + \":\" + key ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Remove this object from the cache . Note StorageClient uses the word remove to mean delete . This method should do the same . [CODESPLIT] protected void removeCached ( String keySpace , String columnFamily , String key ) throws StorageClientException { if ( sharedCache != null ) { // insert a replacement. This should cause an invalidation message // to propagate in the cluster. final String cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; putToCacheInternal ( cacheKey , new CacheHolder ( null , managerId ) , false ) ; LOGGER . debug ( \"Marked as deleted in Cache {} \" , cacheKey ) ; if ( client instanceof Disposer ) { // we might want to change this to register the action as a // commit handler rather than a disposable. // it depends on if we think the delete is a transactional thing // or a operational cache thing. // at the moment, I am leaning towards an operational cache // thing, since regardless of if // the session commits or not, we want this to dispose when the // session is closed, or commits. ( ( Disposer ) client ) . registerDisposable ( new Disposable ( ) { @ Override public void setDisposer ( Disposer disposer ) { } @ Override public void close ( ) { CacheHolder ch = sharedCache . get ( cacheKey ) ; if ( ch != null && ch . wasLockedTo ( managerId ) ) { sharedCache . remove ( cacheKey ) ; LOGGER . debug ( \"Removed deleted marker from Cache {} \" , cacheKey ) ; } } } ) ; } } client . remove ( keySpace , columnFamily , key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Put an object in the cache [CODESPLIT] protected void putCached ( String keySpace , String columnFamily , String key , Map < String , Object > encodedProperties , boolean probablyNew ) throws StorageClientException { String cacheKey = null ; if ( sharedCache != null ) { cacheKey = getCacheKey ( keySpace , columnFamily , key ) ; } if ( sharedCache != null && ! probablyNew ) { CacheHolder ch = getFromCacheInternal ( cacheKey ) ; if ( ch != null && ch . isLocked ( this . managerId ) ) { LOGGER . debug ( \"Is Locked {} \" , ch ) ; return ; // catch the case where another method creates while // something is in the cache. // this is a big assumption since if the item is not in the // cache it will get updated // there is no difference in sparsemap between create and // update, they are all insert operations // what we are really saying here is that inorder to update the // item you have to have just got it // and if you failed to get it, your update must have been a // create operation. As long as the dwell time // in the cache is longer than the lifetime of an active session // then this will be true. // if the lifetime of an active session is longer (like with a // long running background operation) // then you should expect to see race conditions at this point // since the marker in the cache will have // gone, and the marker in the database has gone, so the put // operation, must be a create operation. // To change this behavior we would need to differentiate more // strongly between new and update and change // probablyNew into certainlyNew, but that would probably break // the BASIC assumption of the whole system. // Update 2011-12-06 related to issue 136 // I am not certain this code is correct. What happens if the // session wants to remove and then add items. // the session will never get past this point, since sitting in // the cache is a null CacheHolder preventing the session // removing then adding. // also, how long should the null cache holder be placed in // there for ? // I think the solution is to bind the null Cache holder to the // instance of the caching manager that created it, // let the null Cache holder last for 10s, and during that time // only the CachingManagerImpl that created it can remove it. } } LOGGER . debug ( \"Saving {} {} {} {} \" , new Object [ ] { keySpace , columnFamily , key , encodedProperties } ) ; client . insert ( keySpace , columnFamily , key , encodedProperties , probablyNew ) ; if ( sharedCache != null ) { // if we just added a value in, remove the key so that any stale // state (including a previously deleted object is removed) sharedCache . remove ( cacheKey ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a jar filter . [CODESPLIT] public CF_Locator setJarFilter ( List < String > jarFilter ) { this . jarFilter . clear ( ) ; if ( jarFilter != null ) { this . jarFilter . addAll ( jarFilter ) ; } this . needsReRun = true ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Runs the locator and collects all locations using the filters if set . The method can be called multiple times and will only result in a new map if any of the filters have been changed . If no filter has been changed the current map will be returned . [CODESPLIT] public Map < URI , String > getCfLocations ( ) { if ( this . needsReRun == true ) { this . locationMap . clear ( ) ; String pathSep = System . getProperty ( \"path.separator\" ) ; String classpath = System . getProperty ( \"java.class.path\" ) ; StringTokenizer st = new StringTokenizer ( classpath , pathSep ) ; File file = null ; while ( st . hasMoreTokens ( ) ) { String path = st . nextToken ( ) ; file = new File ( path ) ; this . include ( file ) ; } } this . needsReRun = false ; return this . locationMap ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include a name and file [CODESPLIT] protected final void include ( String name , File file ) { if ( ! file . exists ( ) ) { return ; } if ( ! file . isDirectory ( ) ) { if ( this . jarFilter . size ( ) > 0 ) { boolean ok = false ; for ( String s : this . jarFilter ) { if ( file . getName ( ) . startsWith ( s ) ) { ok = true ; } } if ( ok == false ) { return ; } } this . includeJar ( file ) ; return ; } if ( name == null ) { name = \"\" ; } else { name += \".\" ; } File [ ] dirs = file . listFiles ( CF_Utils . DIRECTORIES_ONLY ) ; for ( int i = 0 ; i < dirs . length ; i ++ ) { try { this . locationMap . put ( new URI ( \"file://\" + dirs [ i ] . getCanonicalPath ( ) ) , name + dirs [ i ] . getName ( ) ) ; } catch ( IOException ignore ) { return ; } catch ( URISyntaxException ignore ) { return ; } this . include ( name + dirs [ i ] . getName ( ) , dirs [ i ] ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Include from a jar file [CODESPLIT] private void includeJar ( File file ) { if ( file . isDirectory ( ) ) { return ; } URL jarURL = null ; JarFile jar = null ; try { jarURL = new URL ( \"jar:\" + new URL ( \"file:/\" + file . getCanonicalPath ( ) ) . toExternalForm ( ) + \"!/\" ) ; JarURLConnection conn = ( JarURLConnection ) jarURL . openConnection ( ) ; jar = conn . getJarFile ( ) ; } catch ( MalformedURLException ignore ) { return ; } catch ( IOException ignore ) { return ; } if ( jar == null ) { return ; } try { this . locationMap . put ( jarURL . toURI ( ) , \"\" ) ; } catch ( URISyntaxException ignore ) { } for ( Enumeration < JarEntry > e = jar . entries ( ) ; e . hasMoreElements ( ) ; ) { JarEntry entry = e . nextElement ( ) ; if ( this . pkgFilter != null && entry . getName ( ) . startsWith ( this . pkgFilter ) ) { continue ; } if ( entry . isDirectory ( ) ) { if ( entry . getName ( ) . toUpperCase ( Locale . ENGLISH ) . equals ( \"META-INF/\" ) ) { continue ; } try { this . locationMap . put ( new URI ( jarURL . toExternalForm ( ) + entry . getName ( ) ) , CF_Utils . getPkgName ( entry ) ) ; } catch ( URISyntaxException ignore ) { continue ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a SASL mechanism to the list to be used . [CODESPLIT] public static void addSaslMech ( String mech ) { initialize ( ) ; if ( ! defaultMechs . contains ( mech ) ) { defaultMechs . add ( mech ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Add a Collection of SASL mechanisms to the list to be used . [CODESPLIT] public static void addSaslMechs ( Collection < String > mechs ) { initialize ( ) ; for ( String mech : mechs ) { addSaslMech ( mech ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the listeners that will print in the console when new activity is detected . [CODESPLIT] private void createDebug ( ) { // Create a special Reader that wraps the main Reader and logs data to // the GUI. ObservableReader debugReader = new ObservableReader ( reader ) ; readerListener = new ReaderListener ( ) { public void read ( String str ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" RCV  (\" + connection . hashCode ( ) + \"): \" + str ) ; } } ; debugReader . addReaderListener ( readerListener ) ; // Create a special Writer that wraps the main Writer and logs data to // the GUI. ObservableWriter debugWriter = new ObservableWriter ( writer ) ; writerListener = new WriterListener ( ) { public void write ( String str ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" SENT (\" + connection . hashCode ( ) + \"): \" + str ) ; } } ; debugWriter . addWriterListener ( writerListener ) ; // Assign the reader/writer objects to use the debug versions. The // packet reader // and writer will use the debug versions when they are created. reader = debugReader ; writer = debugWriter ; // Create a thread that will listen for all incoming packets and write // them to // the GUI. This is what we call \"interpreted\" packet data, since it's // the packet // data as Smack sees it and not as it's coming in as raw XML. listener = new PacketListener ( ) { public void processPacket ( Packet packet ) { if ( printInterpreted ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" RCV PKT (\" + connection . hashCode ( ) + \"): \" + packet . toXML ( ) ) ; } } } ; connListener = new ConnectionListener ( ) { public void connectionClosed ( ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" Connection closed (\" + connection . hashCode ( ) + \")\" ) ; } public void connectionClosedOnError ( Exception e ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" Connection closed due to an exception (\" + connection . hashCode ( ) + \")\" ) ; e . printStackTrace ( ) ; } public void reconnectionFailed ( Exception e ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" Reconnection failed due to an exception (\" + connection . hashCode ( ) + \")\" ) ; e . printStackTrace ( ) ; } public void reconnectionSuccessful ( ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" Connection reconnected (\" + connection . hashCode ( ) + \")\" ) ; } public void reconnectingIn ( int seconds ) { System . out . println ( dateFormatter . format ( new Date ( ) ) + \" Connection (\" + connection . hashCode ( ) + \") will reconnect in \" + seconds ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create resources used by this component . [CODESPLIT] protected void activate ( Map < String , Object > properties ) throws Exception { configProperties = properties ; String [ ] safePostProcessorNames = ( String [ ] ) configProperties . get ( SAFE_POSTPROCESSORS ) ; if ( safePostProcessorNames == null ) { safeOpenProcessors . add ( \"rss\" ) ; safeOpenProcessors . add ( \"trustedLoginTokenProxyPostProcessor\" ) ; } else { for ( String pp : safePostProcessorNames ) { safeOpenProcessors . add ( pp ) ; } } // allow communications via a proxy server if command line // java parameters http.proxyHost,http.proxyPort,http.proxyUser, // http.proxyPassword have been provided. String proxyHost = System . getProperty ( \"http.proxyHost\" , \"\" ) ; if ( ! proxyHost . equals ( \"\" ) ) { useJreProxy = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes a HTTP call using a path in the JCR to point to a template and a map of properties to populate that template with . An example might be a SOAP call . [CODESPLIT] public ProxyResponse executeCall ( Map < String , Object > config , Map < String , Object > headers , Map < String , Object > input , InputStream requestInputStream , long requestContentLength , String requestContentType ) throws ProxyClientException { try { LOGGER . info ( \"Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] \" + \"RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] \" , new Object [ ] { config , headers , input , requestInputStream , requestContentLength , requestContentType } ) ; bindConfig ( config ) ; if ( config != null && config . containsKey ( CONFIG_REQUEST_PROXY_ENDPOINT ) ) { // setup the post request String endpointURL = ( String ) config . get ( CONFIG_REQUEST_PROXY_ENDPOINT ) ; if ( isUnsafeProxyDefinition ( config ) ) { try { URL u = new URL ( endpointURL ) ; String host = u . getHost ( ) ; if ( host . indexOf ( ' ' ) >= 0 ) { throw new ProxyClientException ( \"Invalid Endpoint template, relies on request to resolve valid URL \" + u ) ; } } catch ( MalformedURLException e ) { throw new ProxyClientException ( \"Invalid Endpoint template, relies on request to resolve valid URL\" , e ) ; } } LOGGER . info ( \"Valied Endpoint Def\" ) ; Map < String , Object > context = Maps . newHashMap ( input ) ; // add in the config properties from the bundle overwriting // everything else. context . put ( \"config\" , configProperties ) ; endpointURL = processUrlTemplate ( endpointURL , context ) ; LOGGER . info ( \"Calling URL {} \" , endpointURL ) ; ProxyMethod proxyMethod = ProxyMethod . GET ; if ( config . containsKey ( CONFIG_REQUEST_PROXY_METHOD ) ) { try { proxyMethod = ProxyMethod . valueOf ( ( String ) config . get ( CONFIG_REQUEST_PROXY_METHOD ) ) ; } catch ( Exception e ) { } } HttpClient client = getHttpClient ( ) ; HttpUriRequest method = null ; switch ( proxyMethod ) { case GET : if ( config . containsKey ( CONFIG_LIMIT_GET_SIZE ) ) { long maxSize = ( Long ) config . get ( CONFIG_LIMIT_GET_SIZE ) ; HttpHead h = new HttpHead ( endpointURL ) ; HttpParams params = h . getParams ( ) ; // make certain we reject the body of a head params . setBooleanParameter ( \"http.protocol.reject-head-body\" , true ) ; h . setParams ( params ) ; populateMessage ( method , config , headers ) ; HttpResponse response = client . execute ( h ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 200 ) { // Check if the content-length is smaller than the // maximum (if any). Header contentLengthHeader = response . getLastHeader ( \"Content-Length\" ) ; if ( contentLengthHeader != null ) { long length = Long . parseLong ( contentLengthHeader . getValue ( ) ) ; if ( length > maxSize ) { return new ProxyResponseImpl ( HttpServletResponse . SC_PRECONDITION_FAILED , \"Response too large\" , response ) ; } } } else { return new ProxyResponseImpl ( response ) ; } } method = new HttpGet ( endpointURL ) ; break ; case HEAD : method = new HttpHead ( endpointURL ) ; break ; case OPTIONS : method = new HttpOptions ( endpointURL ) ; break ; case POST : method = new HttpPost ( endpointURL ) ; break ; case PUT : method = new HttpPut ( endpointURL ) ; break ; default : method = new HttpGet ( endpointURL ) ; } populateMessage ( method , config , headers ) ; if ( requestInputStream == null && ! config . containsKey ( CONFIG_PROXY_REQUEST_TEMPLATE ) ) { if ( method instanceof HttpPost ) { HttpPost postMethod = ( HttpPost ) method ; MultipartEntity multipart = new MultipartEntity ( ) ; for ( Entry < String , Object > param : input . entrySet ( ) ) { String key = param . getKey ( ) ; Object value = param . getValue ( ) ; if ( value instanceof Object [ ] ) { for ( Object val : ( Object [ ] ) value ) { addPart ( multipart , key , val ) ; } } else { addPart ( multipart , key , value ) ; } postMethod . setEntity ( multipart ) ; } } } else { if ( method instanceof HttpEntityEnclosingRequestBase ) { String contentType = requestContentType ; if ( contentType == null && config . containsKey ( CONFIG_REQUEST_CONTENT_TYPE ) ) { contentType = ( String ) config . get ( CONFIG_REQUEST_CONTENT_TYPE ) ; } if ( contentType == null ) { contentType = APPLICATION_OCTET_STREAM ; } HttpEntityEnclosingRequestBase eemethod = ( HttpEntityEnclosingRequestBase ) method ; if ( requestInputStream != null ) { eemethod . setHeader ( HttpHeaders . CONTENT_TYPE , contentType ) ; eemethod . setEntity ( new InputStreamEntity ( requestInputStream , requestContentLength ) ) ; } else { // build the request StringWriter body = new StringWriter ( ) ; templateService . evaluate ( context , body , ( String ) config . get ( \"path\" ) , ( String ) config . get ( CONFIG_PROXY_REQUEST_TEMPLATE ) ) ; byte [ ] soapBodyContent = body . toString ( ) . getBytes ( \"UTF-8\" ) ; eemethod . setHeader ( HttpHeaders . CONTENT_TYPE , contentType ) ; eemethod . setEntity ( new InputStreamEntity ( new ByteArrayInputStream ( soapBodyContent ) , soapBodyContent . length ) ) ; } } } HttpResponse response = client . execute ( method ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == 302 && method instanceof HttpEntityEnclosingRequestBase ) { // handle redirects on post and put String url = response . getFirstHeader ( \"Location\" ) . getValue ( ) ; method = new HttpGet ( url ) ; response = client . execute ( method ) ; } return new ProxyResponseImpl ( response ) ; } } catch ( ProxyClientException e ) { throw e ; } catch ( Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new ProxyClientException ( \"The Proxy request specified by  \" + config + \" failed, cause follows:\" , e ) ; } finally { unbindConfig ( ) ; } throw new ProxyClientException ( \"The Proxy request specified by \" + config + \" does not contain a valid endpoint specification \" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "registers the standard - events [CODESPLIT] private void registerStandardEvents ( ) { CommonEvents . Descriptors . stopListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . generalListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . leavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . presenceListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictLeavingListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Presence . strictListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . fullResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . majorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Response . minorResponseListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . notificationListener ( this ) . ifPresent ( this :: registerEventListener ) ; CommonEvents . Type . responseListener ( this ) . ifPresent ( this :: registerEventListener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers or adds an event to the local_events . properties file with the informations found in the EventListener [CODESPLIT] public void registerEventListener ( EventListener eventListener ) { registerEventID ( eventListener . getDescription ( ) , eventListener . getDescriptorID ( ) , eventListener . getDescriptor ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers or adds an event to the local_events . properties file [CODESPLIT] public void registerEventID ( String description , String key , String value ) { BufferedWriter bufferedWriter ; FileOutputStream out = null ; try { out = new FileOutputStream ( eventPropertiesPath , true ) ; bufferedWriter = new BufferedWriter ( new OutputStreamWriter ( out ) ) ; doWithLock ( out . getChannel ( ) , lock -> { unlockedReloadFile ( ) ; if ( getEventID ( key ) != null ) { return ; } try { bufferedWriter . write ( \"\\n\\n\" + key + \"_DESCRIPTION = \" + description + \"\\n\" + key + \" = \" + value ) ; bufferedWriter . flush ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } ) ; } catch ( FileNotFoundException e ) { error ( \"Unable find file\" , e ) ; } finally { try { if ( out != null ) { out . close ( ) ; } } catch ( IOException e ) { error ( \"Unable to close lock\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "executes with a lock [CODESPLIT] private void doWithLock ( FileChannel channel , Consumer < FileLock > consumer ) { FileLock lock = null ; try { while ( lock == null ) { try { lock = channel . tryLock ( ) ; } catch ( OverlappingFileLockException e ) { Thread . sleep ( 500 ) ; } } consumer . accept ( lock ) ; } catch ( IOException | InterruptedException e ) { error ( \"Unable to write\" , e ) ; } finally { try { if ( lock != null ) { lock . release ( ) ; } } catch ( IOException e ) { error ( \"Unable to close lock\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Unregisters or deletes an event from the local_events . properties file [CODESPLIT] public void unregisterEventID ( String eventKey ) { properties . remove ( eventKey + \"_DESCRIPTION\" ) ; properties . remove ( eventKey ) ; FileOutputStream out = null ; BufferedReader reader = null ; BufferedWriter writer = null ; try { out = new FileOutputStream ( eventPropertiesPath , true ) ; final File tempFile = new File ( eventPropertiesPath + \"temp.properties\" ) ; final BufferedReader readerFinal = new BufferedReader ( new FileReader ( eventPropertiesPath ) ) ; final BufferedWriter writerFinal = new BufferedWriter ( new FileWriter ( tempFile ) ) ; doWithLock ( out . getChannel ( ) , lock -> { unlockedReloadFile ( ) ; if ( getEventID ( eventKey ) != null ) { return ; } try { String currentLine = readerFinal . readLine ( ) ; while ( currentLine != null ) { String trimmedLine = currentLine . trim ( ) ; if ( trimmedLine . equals ( eventKey + \"_DESCRIPTION\" ) || trimmedLine . equals ( eventKey ) ) continue ; writerFinal . write ( currentLine + System . getProperty ( \"line.separator\" ) ) ; currentLine = readerFinal . readLine ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } ) ; reader = readerFinal ; writer = writerFinal ; tempFile . renameTo ( new File ( eventPropertiesPath ) ) ; } catch ( IOException e ) { error ( \"Unable find file\" , e ) ; } finally { try { if ( out != null ) { out . close ( ) ; } if ( writer != null ) { writer . close ( ) ; } if ( reader != null ) { reader . close ( ) ; } } catch ( IOException e ) { error ( \"Unable to close lock\" , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks if the outputExtension can execute with the current event [CODESPLIT] @ Override public boolean canRun ( EventModel event ) { //noinspection SimplifiableIfStatement if ( event != null ) { return event . getListResourceContainer ( ) . providesResource ( getResourceIdWishList ( ) ) ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source ) { try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , Volume volume ) { if ( volume == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new VolumeResource ( source , volume ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , Playlist playlist ) { if ( playlist == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new PlaylistResource ( source , playlist ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Event Object [CODESPLIT] public static Optional < PlayerUpdate > createPlayerUpdate ( Identification source , TrackInfo trackInfo ) { if ( trackInfo == null ) return Optional . empty ( ) ; try { PlayerUpdate playerUpdate = new PlayerUpdate ( source ) ; playerUpdate . addResource ( new TrackInfoResource ( source , trackInfo ) ) ; return Optional . of ( playerUpdate ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get an instance of { @link ClusterIdentifier } . [CODESPLIT] public static ClusterIdentifier getInstance ( String hostsAndPorts , String username , String password ) { return getInstance ( hostsAndPorts , username , password , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get an instance of { @link ClusterIdentifier } . [CODESPLIT] public static ClusterIdentifier getInstance ( String hostsAndPorts , String username , String password , String authorizationId ) { String [ ] key = { hostsAndPorts , username , password , authorizationId } ; try { return cache . get ( key ) ; } catch ( ExecutionException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a new DSE cluster instance . [CODESPLIT] public static DseCluster newDseCluster ( String hostsAndPorts , String username , String password , String proxiedUser ) { return newDseCluster ( hostsAndPorts , username , password , proxiedUser , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Build a new DSE cluster instance . [CODESPLIT] public static DseCluster newDseCluster ( String hostsAndPorts , String username , String password , String proxiedUser , Configuration configuration ) { DseCluster . Builder builder = DseCluster . builder ( ) ; if ( ! StringUtils . isBlank ( username ) ) { AuthProvider authProvider ; if ( StringUtils . isBlank ( proxiedUser ) ) { authProvider = new DsePlainTextAuthProvider ( username , password ) ; } else { authProvider = new DsePlainTextAuthProvider ( username , password , proxiedUser ) ; } builder = builder . withAuthProvider ( authProvider ) ; } Collection < InetSocketAddress > contactPointsWithPorts = new HashSet < InetSocketAddress > ( ) ; String [ ] hostAndPortArr = StringUtils . split ( hostsAndPorts , \";, \" ) ; for ( String hostAndPort : hostAndPortArr ) { String [ ] tokens = StringUtils . split ( hostAndPort , ' ' ) ; String host = tokens [ 0 ] ; int port = tokens . length > 1 ? Integer . parseInt ( tokens [ 1 ] ) : DEFAULT_CASSANDRA_PORT ; contactPointsWithPorts . add ( new InetSocketAddress ( host , port ) ) ; } builder = builder . addContactPointsWithPorts ( contactPointsWithPorts ) ; buildPolicies ( configuration , builder ) ; buildOptions ( configuration , builder ) ; DseCluster cluster = builder . build ( ) ; return cluster ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a new session for a DSE cluster initializes it and sets the keyspace to the provided one . [CODESPLIT] public static DseSession newDseSession ( DseCluster cluster , String keyspace ) { return cluster . connect ( StringUtils . isBlank ( keyspace ) ? null : keyspace ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new MusicPlayerError [CODESPLIT] public static Optional < PlayerError > createMusicPlayerError ( Identification source , String error ) { if ( error == null || error . isEmpty ( ) ) return Optional . empty ( ) ; try { PlayerError playerError = new PlayerError ( source ) ; playerError . addResource ( new MusicErrorResource ( source , error ) ) ; return Optional . of ( playerError ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "starts the playing command [CODESPLIT] public void startPlaying ( TrackInfo trackInfo ) { Optional < Identification > ownIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( this ) ; Optional < Identification > playerIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( player ) ; if ( ! ownIdentification . isPresent ( ) || ! playerIdentification . isPresent ( ) ) { error ( \"unable to obtain identification\" ) ; return ; } StartMusicRequest . createStartMusicRequest ( ownIdentification . get ( ) , playerIdentification . get ( ) , trackInfo , player . isUsingJava ) . ifPresent ( event -> fire ( event , 5 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "stops the playing of the music [CODESPLIT] public void stopPlaying ( ) { Optional < Identification > ownIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( this ) ; Optional < Identification > playerIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( player ) ; if ( ! ownIdentification . isPresent ( ) || ! playerIdentification . isPresent ( ) ) { error ( \"unable to obtain id\" ) ; return ; } StopMusic . createStopMusic ( ownIdentification . get ( ) , playerIdentification . get ( ) ) . ifPresent ( event -> fire ( event , 5 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "commands the player to fulfill the command [CODESPLIT] public void command ( String command , Playlist playlist , Progress progress , TrackInfo trackInfo , Volume volume ) { Optional < Identification > ownIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( this ) ; Optional < Identification > playerIdentification = IdentificationManagerM . getInstance ( ) . getIdentification ( player ) ; if ( ! ownIdentification . isPresent ( ) || ! playerIdentification . isPresent ( ) ) { error ( \"unable to obtain id\" ) ; return ; } Optional < PlayerCommand > playerCommand = PlayerCommand . createPlayerCommand ( ownIdentification . get ( ) , playerIdentification . get ( ) , command , player . getCapabilities ( ) , getContext ( ) ) ; if ( playlist != null ) { playerCommand . get ( ) . addResource ( new PlaylistResource ( ownIdentification . get ( ) , playlist ) ) ; } if ( progress != null ) { playerCommand . get ( ) . addResource ( new ProgressResource ( ownIdentification . get ( ) , progress ) ) ; } if ( trackInfo != null ) { playerCommand . get ( ) . addResource ( new TrackInfoResource ( ownIdentification . get ( ) , trackInfo ) ) ; } if ( volume != null ) { playerCommand . get ( ) . addResource ( new VolumeResource ( ownIdentification . get ( ) , volume ) ) ; } fire ( playerCommand . get ( ) , 5 ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates the Playlist - Request [CODESPLIT] public static BroadcasterPlaylist createPlaylistRequest ( Identification provider , String playlistName ) { HashMap < String , Object > hashMap = new HashMap <> ( ) ; hashMap . put ( RESOURCE_ID , playlistName ) ; return new BroadcasterPlaylist ( provider , hashMap ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates the Playlist - Answer [CODESPLIT] public static BroadcasterPlaylist createPlaylistAnswer ( Identification provider , Playlist playlist ) { return new BroadcasterPlaylist ( provider , playlist . export ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StopEvent [CODESPLIT] public static Optional < UnMuteEvent > createUnMuteEvent ( Identification source , Identification target ) { if ( target == null || target . equals ( source ) ) return Optional . empty ( ) ; try { UnMuteEvent unmuteRequest = new UnMuteEvent ( source ) ; unmuteRequest . addResource ( new SelectorResource ( source , target ) ) ; return Optional . of ( unmuteRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void log ( int level , String msg ) { if ( inDebugMode ) { logger . info ( msg ) ; } switch ( level ) { case LogChute . DEBUG_ID : logger . debug ( msg ) ; break ; case LogChute . ERROR_ID : logger . error ( msg ) ; break ; case LogChute . INFO_ID : logger . info ( msg ) ; break ; case LogChute . TRACE_ID : logger . trace ( msg ) ; break ; case LogChute . WARN_ID : logger . warn ( msg ) ; break ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends one or more postfixes and separates them by slashes . [CODESPLIT] public UrlBuilder append ( boolean encode , String ... postFix ) { for ( String part : postFix ) { if ( StringUtils . isNotBlank ( part ) ) { if ( url . charAt ( url . length ( ) - 1 ) != ' ' && ! part . startsWith ( \"/\" ) ) { url . append ( ' ' ) ; } if ( encode ) { try { url . append ( URLEncoder . encode ( part , \"UTF-8\" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } else { url . append ( part ) ; } } } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a query parameter with a boolean value . [CODESPLIT] public UrlBuilder queryParam ( String name , Boolean value ) { if ( value != null ) { return queryParam ( name , value . toString ( ) ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a query parameter with a number value . [CODESPLIT] public UrlBuilder queryParam ( String name , Number value ) { if ( value != null ) { return queryParam ( name , value . toString ( ) ) ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a query parameter with a String value . The value will be urlencoded . [CODESPLIT] public UrlBuilder queryParam ( String name , String value ) { return queryParam ( name , value , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a query parameter with a String value . [CODESPLIT] public UrlBuilder queryParam ( String name , String value , boolean encode ) { if ( StringUtils . isNotEmpty ( value ) ) { if ( encode ) { try { value = URLEncoder . encode ( value , \"UTF-8\" ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( e ) ; } } params . add ( new EntryImpl ( name , value ) ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the first playlist if found in the EventModel [CODESPLIT] public static Optional < Playlist > getPlaylist ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . findAny ( ) . flatMap ( Playlist :: importResource ) ; } else { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is called from within the constructor to initialize the form . <p > Note : This code was generated by Netbeans . [CODESPLIT] private void initComponents ( ) { launchButton = new javax . swing . JButton ( ) ; statusLabel = new javax . swing . JLabel ( ) ; exitButton = new javax . swing . JButton ( ) ; headingLabel = new javax . swing . JLabel ( ) ; disclaimerLabel = new javax . swing . JLabel ( ) ; browserButton = new javax . swing . JButton ( ) ; setDefaultCloseOperation ( javax . swing . WindowConstants . EXIT_ON_CLOSE ) ; setTitle ( \"Launch Nakamura\" ) ; setName ( \"mainFrame\" ) ; // NOI18N setResizable ( false ) ; launchButton . setFont ( new java . awt . Font ( \"Arial\" , 0 , 13 ) ) ; // NOI18N launchButton . setText ( \"Launch\" ) ; launchButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { launchButtonActionPerformed ( evt ) ; } } ) ; statusLabel . setFont ( new java . awt . Font ( \"Arial\" , 0 , 12 ) ) ; // NOI18N statusLabel . setText ( \"Nakamura is not running.\" ) ; exitButton . setFont ( new java . awt . Font ( \"Arial\" , 0 , 13 ) ) ; // NOI18N exitButton . setText ( \"Exit\" ) ; exitButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { exitButtonActionPerformed ( evt ) ; } } ) ; headingLabel . setText ( \"SakaiOAE icon\" ) ; headingLabel . setBorder ( javax . swing . BorderFactory . createEtchedBorder ( ) ) ; disclaimerLabel . setFont ( new java . awt . Font ( \"Arial\" , 0 , 13 ) ) ; // NOI18N disclaimerLabel . setText ( \"jLabel1\" ) ; disclaimerLabel . setVerticalAlignment ( javax . swing . SwingConstants . TOP ) ; disclaimerLabel . setAutoscrolls ( true ) ; disclaimerLabel . setBorder ( javax . swing . BorderFactory . createTitledBorder ( \"Disclaimer\" ) ) ; browserButton . setText ( \"Open Sakai OAE\" ) ; browserButton . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { browserButtonActionPerformed ( evt ) ; } } ) ; javax . swing . GroupLayout layout = new javax . swing . GroupLayout ( getContentPane ( ) ) ; getContentPane ( ) . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 27 , 27 , 27 ) . addComponent ( launchButton ) . addGap ( 18 , 18 , 18 ) . addComponent ( statusLabel ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , 162 , Short . MAX_VALUE ) . addComponent ( browserButton ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( exitButton ) ) . addGroup ( javax . swing . GroupLayout . Alignment . CENTER , layout . createSequentialGroup ( ) . addContainerGap ( ) . addComponent ( headingLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 149 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addGap ( 18 , 18 , 18 ) . addComponent ( disclaimerLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 493 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) ) . addContainerGap ( ) ) ) ; layout . linkSize ( javax . swing . SwingConstants . HORIZONTAL , new java . awt . Component [ ] { exitButton , launchButton } ) ; layout . setVerticalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( javax . swing . GroupLayout . Alignment . TRAILING , layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( disclaimerLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 215 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( headingLabel , javax . swing . GroupLayout . PREFERRED_SIZE , 116 , javax . swing . GroupLayout . PREFERRED_SIZE ) ) . addGap ( 58 , 58 , 58 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . CENTER ) . addComponent ( browserButton ) . addComponent ( exitButton ) ) . addContainerGap ( ) ) . addGroup ( layout . createSequentialGroup ( ) . addGap ( 259 , 259 , 259 ) . addGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . BASELINE ) . addComponent ( launchButton , javax . swing . GroupLayout . PREFERRED_SIZE , 50 , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( statusLabel ) ) . addContainerGap ( javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) ; pack ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This is the launch button action method . This method launches the Apache Sling bootloader and informs the user to wait before accessing it in a browser . [CODESPLIT] private void launchButtonActionPerformed ( java . awt . event . ActionEvent evt ) { // Launch Nakamura if ( runStatus == APP_NOT_RUNNING ) { System . setSecurityManager ( null ) ; try { NakamuraMain . main ( savedArgs ) ; // Update label statusLabel . setText ( \"Nakamura is starting...\" ) ; // Notify the user JOptionPane . showMessageDialog ( this , \"Nakamura has been started.\\nPlease allow 30-60 seconds for it to be ready.\" , \"Information\" , JOptionPane . INFORMATION_MESSAGE ) ; runStatus = APP_RUNNING ; isStartupFinished ( ) ; } catch ( IOException e ) { statusLabel . setText ( \"Nakamura is startup failed \" + e . getMessage ( ) ) ; } } else { // Can't start it again... // custom title, warning icon JOptionPane . showMessageDialog ( this , \"Nakamura is already running.\" , \"Warning\" , JOptionPane . WARNING_MESSAGE ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pings the Apache Sling server URL every 5 seconds to see if it has finished booting . Once it receives an OK status it enables the button to launch the browser and disables the launch Nakamura button . [CODESPLIT] private void isStartupFinished ( ) { boolean started = false ; try { while ( ! started ) { if ( exists ( localhostURL ) ) started = true ; Thread . sleep ( 5 * 1000 ) ; } } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } if ( started ) { statusLabel . setText ( \"Nakamura is running.\" ) ; statusLabel . setForeground ( Color . green ) ; launchButton . setEnabled ( false ) ; browserButton . setEnabled ( true ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pings the Apache Sling server URL looking for an OK status . Returns true once that OK status is received . [CODESPLIT] public static boolean exists ( String URLName ) { try { HttpURLConnection . setFollowRedirects ( false ) ; // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = ( HttpURLConnection ) new URL ( URLName ) . openConnection ( ) ; con . setRequestMethod ( \"HEAD\" ) ; return ( con . getResponseCode ( ) == HttpURLConnection . HTTP_OK ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Performs the action when the browser button is pressed which is launch a web browser and browse to the server URL . [CODESPLIT] private void browserButtonActionPerformed ( java . awt . event . ActionEvent evt ) { try { Desktop . getDesktop ( ) . browse ( new URL ( localhostURL ) . toURI ( ) ) ; } catch ( IOException e ) { System . err . println ( \"IO Exception: \" + e . getMessage ( ) ) ; } catch ( URISyntaxException e ) { System . err . println ( \"URISyntaxException: \" + e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an ImageIcon or null if the path was invalid . [CODESPLIT] protected ImageIcon createImageIcon ( String path , String description ) { java . net . URL imgURL = getClass ( ) . getResource ( path ) ; if ( imgURL != null ) { return new ImageIcon ( imgURL , description ) ; } else { System . err . println ( \"Couldn't find file: \" + path ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the full contents of a ( assumed ) text file for use in a label . [CODESPLIT] protected String getLabelText ( String path ) throws IOException { InputStream is = this . getClass ( ) . getResourceAsStream ( path ) ; if ( is != null ) { Writer writer = new StringWriter ( ) ; char [ ] buffer = new char [ 1024 ] ; try { Reader reader = new BufferedReader ( new InputStreamReader ( is , \"UTF-8\" ) ) ; int n ; while ( ( n = reader . read ( buffer ) ) != - 1 ) { writer . write ( buffer , 0 , n ) ; } } finally { is . close ( ) ; } return writer . toString ( ) ; } else { System . err . println ( \"Couldn't find file: \" + path ) ; return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The Main method which executes the program . [CODESPLIT] public static void main ( String args [ ] ) { savedArgs = args ; java . awt . EventQueue . invokeLater ( new Runnable ( ) { public void run ( ) { new LaunchNakamura ( ) . setVisible ( true ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replace contents with given values [CODESPLIT] public IntArray with ( int ... values ) { if ( values . length != this . length ) throw new IllegalArgumentException ( \"Array size mismatch\" ) ; value = values . clone ( ) ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exports the Presence to a HashMap [CODESPLIT] public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; data . put ( LEVEL_DESCRIPTOR , level . name ( ) ) ; data . put ( PRESENT_DESCRIPTOR , present ) ; data . put ( STRICT_DESCRIPTOR , strict ) ; data . put ( KNOWN_DESCRIPTOR , known ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "imports ( if no errors occurred ) the Presence from the ResourceModel [CODESPLIT] public static Optional < Presence > importPresence ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { //noinspection unchecked HashMap < String , Object > data = ( HashMap < String , Object > ) resource ; PresenceIndicatorLevel level ; try { level = PresenceIndicatorLevel . valueOf ( ( String ) data . get ( LEVEL_DESCRIPTOR ) ) ; } catch ( IllegalArgumentException e ) { level = PresenceIndicatorLevel . VERY_WEAK ; } boolean present = ( boolean ) data . get ( PRESENT_DESCRIPTOR ) ; boolean strict = ( boolean ) data . get ( STRICT_DESCRIPTOR ) ; boolean known = ( boolean ) data . get ( KNOWN_DESCRIPTOR ) ; return Optional . of ( new Presence ( level , present , strict , known ) ) ; } catch ( Exception e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Advance current JSON value to specified element in JSON array . Set current JSON value to null otherwise . [CODESPLIT] public JSONResult get ( int index ) { if ( value instanceof JSONArray ) { JSONArray array = ( JSONArray ) value ; Object result = array . get ( index ) ; return new JSONResult ( result ) ; } else if ( value instanceof JSONObject ) { return get ( String . valueOf ( index ) ) ; } return new JSONResult ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Advance current JSON value to specified value of current JSON object . Set current JSON value to null otherwise . [CODESPLIT] public JSONResult get ( String key ) { if ( value instanceof JSONObject ) { JSONObject obj = ( JSONObject ) value ; Object result = obj . get ( key ) ; return new JSONResult ( result ) ; } else if ( value instanceof JSONArray ) { try { int index = Integer . parseInt ( key ) ; return get ( index ) ; } catch ( NumberFormatException e ) { throw createException ( \"Excpected JSONObject \" + key + \":\" ) ; } } return new JSONResult ( null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an integer for current JSON value parsing string values as required . [CODESPLIT] public Integer getInt ( Integer defaultValue ) { if ( value instanceof Number ) { return ( ( Number ) value ) . intValue ( ) ; } if ( value instanceof String ) { String s = ( String ) value ; return Integer . parseInt ( s ) ; } if ( value == null ) { return defaultValue ; } throw createException ( \"Expected integer:\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return a double number for current JSON value parsing string values as required . [CODESPLIT] public Double getDouble ( Double defaultValue ) { if ( value instanceof Number ) { return ( ( Number ) value ) . doubleValue ( ) ; } if ( value instanceof String ) { String s = ( String ) value ; return Double . parseDouble ( s ) ; } if ( value == null ) { return defaultValue ; } throw createException ( \"Expected number:\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return string value for current JSON value [CODESPLIT] public String getString ( String defaultValue ) { if ( value instanceof String || value instanceof Number ) { return value . toString ( ) ; } if ( value == null ) { return null ; } if ( value instanceof JSONArray ) { return ( ( JSONArray ) value ) . toJSONString ( ) ; } if ( value instanceof JSONObject ) { return ( ( JSONObject ) value ) . toJSONString ( ) ; } if ( value == null ) { return defaultValue ; } throw createException ( \"Expected string:\" ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new Resource . [CODESPLIT] public static Optional < CommandResource > createCommandResource ( Identification provider , String command , Capabilities capabilities , Context context ) { CommandResource commandResource = new CommandResource ( provider , command , capabilities ) ; if ( ! verifyCommand ( command ) ) { context . getLogger ( ) . error ( \"IllegalCommand!\" ) ; return Optional . empty ( ) ; } if ( ! verifyCapabilities ( command , capabilities ) ) { context . getLogger ( ) . error ( \"Player is not able to handle Command!\" ) ; return Optional . empty ( ) ; } return Optional . of ( commandResource ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verifies that an command is not malformed [CODESPLIT] public static boolean verifyCommand ( String command ) { return command . equals ( PLAY ) || command . equals ( PAUSE ) || command . equals ( STOP ) || command . equals ( SELECT_TRACK ) || command . equals ( NEXT ) || command . equals ( PREVIOUS ) || command . equals ( CHANGE_PLAYBACK ) || command . equals ( CHANGE_VOLUME ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verifies that the player is capable of handling the command [CODESPLIT] public static boolean verifyCapabilities ( String command , Capabilities capabilities ) { switch ( command ) { case PLAY : return capabilities . hasPlayPauseControl ( ) ; case PAUSE : return capabilities . hasPlayPauseControl ( ) ; case SELECT_TRACK : return capabilities . isAbleToSelectTrack ( ) ; case NEXT : return capabilities . hasNextPrevious ( ) ; case PREVIOUS : return capabilities . hasNextPrevious ( ) ; case JUMP : return capabilities . isAbleToJump ( ) ; case CHANGE_PLAYBACK : return capabilities . isPlaybackChangeable ( ) ; case CHANGE_VOLUME : return capabilities . canChangeVolume ( ) ; case STOP : return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verifies tha the command is legal and able to be executed [CODESPLIT] public static boolean verify ( String command , Capabilities capabilities ) { return verifyCommand ( command ) && verifyCapabilities ( command , capabilities ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Cluster } instance . [CODESPLIT] protected Cluster createCluster ( ClusterIdentifier ci ) { return CqlUtils . newCluster ( ci . hostsAndPorts , ci . username , ci . password , getConfiguration ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a { @link Session } instance . [CODESPLIT] protected Session createSession ( Cluster cluster , String keyspace ) { return CqlUtils . newSession ( cluster , keyspace ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a Cassandra cluster instance . [CODESPLIT] synchronized protected Cluster getCluster ( ClusterIdentifier key ) { Cluster cluster ; try { cluster = clusterCache . get ( key ) ; if ( cluster . isClosed ( ) ) { LOGGER . info ( \"Cluster [\" + cluster + \"] was closed, obtaining a new one...\" ) ; clusterCache . invalidate ( key ) ; cluster = clusterCache . get ( key ) ; } } catch ( ExecutionException e ) { Throwable t = e . getCause ( ) ; throw t instanceof RuntimeException ? ( RuntimeException ) t : new RuntimeException ( t ) ; } return cluster ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a Cassandra cluster instance . [CODESPLIT] public Cluster getCluster ( String hostsAndPorts , String username , String password ) { return getCluster ( ClusterIdentifier . getInstance ( hostsAndPorts , username , password ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a Cassandra session instance . [CODESPLIT] public Session getSession ( String hostsAndPorts , String username , String password , String keyspace ) { return getSession ( hostsAndPorts , username , password , keyspace , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a Cassandra session instance . [CODESPLIT] synchronized protected Session getSession ( SessionIdentifier si , boolean forceNew ) { /*\n         * Since 0.2.6: refresh cluster cache before obtaining the session to\n         * avoid exception\n         * \"You may have used a PreparedStatement that was created with another Cluster instance\"\n         */ Cluster cluster = getCluster ( si ) ; if ( cluster == null ) { return null ; } try { LoadingCache < SessionIdentifier , Session > cacheSessions = sessionCache . get ( si ) ; Session existingSession = cacheSessions . getIfPresent ( si ) ; if ( existingSession != null && existingSession . isClosed ( ) ) { LOGGER . info ( \"Session [\" + existingSession + \"] was closed, obtaining a new one...\" ) ; cacheSessions . invalidate ( si ) ; return cacheSessions . get ( si ) ; } if ( forceNew ) { if ( existingSession != null ) { cacheSessions . invalidate ( si ) ; } return cacheSessions . get ( si ) ; } return existingSession != null ? existingSession : cacheSessions . get ( si ) ; } catch ( ExecutionException e ) { Throwable t = e . getCause ( ) ; throw t instanceof RuntimeException ? ( RuntimeException ) t : new RuntimeException ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a Cassandra session instance . [CODESPLIT] public Session getSession ( String hostsAndPorts , String username , String password , String keyspace , boolean forceNew ) { return getSession ( SessionIdentifier . getInstance ( hostsAndPorts , username , password , keyspace ) , forceNew ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind values to a { @link PreparedStatement } . [CODESPLIT] public BoundStatement bindValues ( PreparedStatement stm , Object ... values ) { return CqlUtils . bindValues ( stm , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Bind values to a { @link PreparedStatement } . [CODESPLIT] public BoundStatement bindValues ( PreparedStatement stm , Map < String , Object > values ) { return CqlUtils . bindValues ( stm , values ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a SELECT query and returns the { @link ResultSet } . [CODESPLIT] public ResultSet execute ( String cql , Object ... bindValues ) { return CqlUtils . execute ( getSession ( ) , cql , bindValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a SELECT query and returns the { @link ResultSet } . [CODESPLIT] public ResultSet execute ( PreparedStatement stm , Map < String , Object > bindValues ) { return CqlUtils . execute ( getSession ( ) , stm , bindValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a SELECT query and returns the { @link ResultSet } . [CODESPLIT] public ResultSet execute ( Statement stm , ConsistencyLevel consistencyLevel ) { if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } return getSession ( ) . execute ( stm ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a SELECT query and returns just one row . [CODESPLIT] public Row executeOne ( String cql , ConsistencyLevel consistencyLevel , Map < String , Object > bindValues ) { return CqlUtils . executeOne ( getSession ( ) , cql , consistencyLevel , bindValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a SELECT query and returns just one row . [CODESPLIT] public Row executeOne ( PreparedStatement stm , Object ... bindValues ) { return CqlUtils . executeOne ( getSession ( ) , stm , bindValues ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a SELECT query and returns just one row . [CODESPLIT] public Row executeOne ( Statement stm , ConsistencyLevel consistencyLevel ) { if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } return getSession ( ) . execute ( stm ) . one ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ---------------------------------------------------------------------- [CODESPLIT] private FutureCallback < ResultSet > wrapCallbackResultSet ( FutureCallback < ResultSet > callback ) { return new FutureCallback < ResultSet > ( ) { @ Override public void onSuccess ( ResultSet result ) { try { callback . onSuccess ( result ) ; } finally { asyncSemaphore . release ( ) ; } } @ Override public void onFailure ( Throwable t ) { try { callback . onFailure ( t ) ; } finally { asyncSemaphore . release ( ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Async - execute a query . [CODESPLIT] public void executeAsync ( FutureCallback < ResultSet > callback , Statement stm ) throws ExceedMaxAsyncJobsException { executeAsync ( callback , stm , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Async - execute a query . [CODESPLIT] public void executeAsync ( FutureCallback < ResultSet > callback , Statement stm , ConsistencyLevel consistencyLevel ) throws ExceedMaxAsyncJobsException { if ( ! asyncSemaphore . tryAcquire ( ) ) { if ( callback == null ) { throw new ExceedMaxAsyncJobsException ( maxSyncJobs ) ; } else { callback . onFailure ( new ExceedMaxAsyncJobsException ( maxSyncJobs ) ) ; } } else { try { if ( consistencyLevel != null ) { if ( consistencyLevel == ConsistencyLevel . SERIAL || consistencyLevel == ConsistencyLevel . LOCAL_SERIAL ) { stm . setSerialConsistencyLevel ( consistencyLevel ) ; } else { stm . setConsistencyLevel ( consistencyLevel ) ; } } ResultSetFuture rsf = CqlUtils . executeAsync ( getSession ( ) , stm ) ; if ( callback != null ) { Futures . addCallback ( rsf , wrapCallbackResultSet ( callback ) , asyncExecutor ) ; } } catch ( Exception e ) { asyncSemaphore . release ( ) ; LOGGER . error ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ---------------------------------------------------------------------- [CODESPLIT] private FutureCallback < ResultSet > wrapCallbackRow ( FutureCallback < Row > callback ) { return new FutureCallback < ResultSet > ( ) { @ Override public void onSuccess ( ResultSet result ) { try { callback . onSuccess ( result . one ( ) ) ; } finally { asyncSemaphore . release ( ) ; } } @ Override public void onFailure ( Throwable t ) { try { callback . onFailure ( t ) ; } finally { asyncSemaphore . release ( ) ; } } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Async - execute a query . [CODESPLIT] public void executeOneAsync ( FutureCallback < Row > callback , Statement stm ) throws ExceedMaxAsyncJobsException { executeOneAsync ( callback , stm , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a batch statement . [CODESPLIT] public ResultSet executeBatch ( ConsistencyLevel consistencyLevel , Statement ... statements ) { return CqlUtils . executeBatch ( getSession ( ) , consistencyLevel , statements ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Execute a batch statement . [CODESPLIT] public ResultSet executeBatch ( BatchStatement . Type batchType , Statement ... statements ) { return CqlUtils . executeBatch ( getSession ( ) , batchType , statements ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Async - execute a batch statement . [CODESPLIT] public void executeBatchAsync ( FutureCallback < ResultSet > callback , Statement ... statements ) throws ExceedMaxAsyncJobsException { if ( ! asyncSemaphore . tryAcquire ( ) ) { if ( callback == null ) { throw new ExceedMaxAsyncJobsException ( maxSyncJobs ) ; } else { callback . onFailure ( new ExceedMaxAsyncJobsException ( maxSyncJobs ) ) ; } } else { try { ResultSetFuture rsf = CqlUtils . executeBatchAsync ( getSession ( ) , statements ) ; if ( callback != null ) { Futures . addCallback ( rsf , wrapCallbackResultSet ( callback ) , asyncExecutor ) ; } } catch ( Exception e ) { asyncSemaphore . release ( ) ; LOGGER . error ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets a jar filter . [CODESPLIT] public CF setJarFilter ( List < String > jarFilter ) { this . locator . setJarFilter ( jarFilter ) ; this . needsReRun = true ; return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all subclasses found for the given class . [CODESPLIT] public Set < Class < ? > > getSubclasses ( Class < ? > clazz ) { Set < Class < ? > > ret = new HashSet < Class < ? > > ( ) ; Set < Class < ? > > w = null ; if ( clazz != null ) { this . clear ( ) ; Map < URI , String > locations = this . locator . getCfLocations ( ) ; for ( Entry < URI , String > entry : locations . entrySet ( ) ) { try { w = search ( clazz , entry . getKey ( ) , locations . get ( entry . getKey ( ) ) ) ; if ( w != null && ( w . size ( ) > 0 ) ) { ret . addAll ( w ) ; } } catch ( MalformedURLException ex ) { } } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all subclasses found for the given fully qualified class name . [CODESPLIT] public Set < Class < ? > > getSubclasses ( String fqcn ) { if ( fqcn == null ) { return new HashSet < Class < ? > > ( ) ; } else if ( StringUtils . startsWith ( fqcn , \".\" ) || StringUtils . endsWith ( fqcn , \".\" ) ) { return new HashSet < Class < ? > > ( ) ; } Class < ? > clazz = null ; try { clazz = Class . forName ( fqcn ) ; } catch ( ClassNotFoundException ex ) { this . clear ( ) ; this . errors . add ( ex ) ; return new HashSet < Class < ? > > ( ) ; } return getSubclasses ( clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all known subclasses for a given class location and package name [CODESPLIT] private final Set < Class < ? > > search ( Class < ? > clazz , URI location , String packageName ) throws MalformedURLException { if ( clazz == null || location == null ) { return new HashSet < Class < ? > > ( ) ; } File directory = new File ( location . toURL ( ) . getFile ( ) ) ; if ( directory . exists ( ) ) { return this . searchDirectory ( clazz , directory , location , packageName ) . keySet ( ) ; } else { return this . searchJar ( clazz , location ) . keySet ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all known subclasses found in a given directory . [CODESPLIT] protected final Map < Class < ? > , URI > searchDirectory ( Class < ? > clazz , File directory , URI location , String packageName ) { Map < Class < ? > , URI > ret = new HashMap <> ( ) ; String [ ] files = directory . list ( ) ; for ( int i = 0 ; i < files . length ; i ++ ) { if ( files [ i ] . endsWith ( \".class\" ) ) { String classname = files [ i ] . substring ( 0 , files [ i ] . length ( ) - 6 ) ; try { Class < ? > c = Class . forName ( packageName + \".\" + classname ) ; if ( clazz . isAssignableFrom ( c ) && ! clazz . getName ( ) . equals ( packageName + \".\" + classname ) ) { ret . put ( c , location ) ; } } catch ( Exception ex ) { errors . add ( ex ) ; } } } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns all known subclasses found in a given location [CODESPLIT] protected final Map < Class < ? > , URI > searchJar ( Class < ? > clazz , URI location ) { Map < Class < ? > , URI > ret = new HashMap <> ( ) ; try { JarURLConnection conn = ( JarURLConnection ) location . toURL ( ) . openConnection ( ) ; JarFile jarFile = conn . getJarFile ( ) ; for ( Enumeration < JarEntry > e = jarFile . entries ( ) ; e . hasMoreElements ( ) ; ) { JarEntry entry = e . nextElement ( ) ; String entryname = entry . getName ( ) ; if ( this . processed . contains ( entryname ) ) { continue ; } this . processed . add ( entryname ) ; if ( ! entry . isDirectory ( ) && entryname . endsWith ( \".class\" ) ) { String classname = entryname . substring ( 0 , entryname . length ( ) - 6 ) ; if ( classname . startsWith ( \"/\" ) ) { classname = classname . substring ( 1 ) ; } classname = classname . replace ( ' ' , ' ' ) ; if ( ! StringUtils . startsWithAny ( classname , this . excludedNames ) ) { try { Class < ? > c = Class . forName ( classname ) ; if ( clazz . isAssignableFrom ( c ) && ! clazz . getName ( ) . equals ( classname ) ) { ret . put ( c , location ) ; } } catch ( Exception exception ) { errors . add ( exception ) ; } catch ( Error error ) { errors . add ( error ) ; } } } } } catch ( IOException ignore ) { errors . add ( ignore ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the Resource data . <p > Note! this Object is immutable! < / p > [CODESPLIT] public Resource < T > setResource ( T resource ) { return new Resource <> ( resourceID , provider , resource , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets who should or has provided the Resource Object . <p > Note! this Object is immutable! < / p > [CODESPLIT] public Resource < T > setProvider ( Identification provider ) { return new Resource <> ( resourceID , provider , resource , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets who should or has consumed the Resource Object . <p > Note! this Object is immutable! < / p > [CODESPLIT] public Resource < T > setConsumer ( Identification consumer ) { return new Resource <> ( resourceID , provider , resource , consumer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a list with this Element in it . [CODESPLIT] public List < Resource > toList ( ) { List < Resource > resourceList = new ArrayList <> ( ) ; resourceList . add ( this ) ; return resourceList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the accumulated size of all the bottom level maps . [CODESPLIT] public int size ( ) { int result = 0 ; // sum over all inner maps \r for ( Iterator < K1 > keys1 = maps . keySet ( ) . iterator ( ) ; keys1 . hasNext ( ) ; ) { Map2 < K2 , K3 , V > inner_map = maps . get ( keys1 . next ( ) ) ; result += inner_map . size ( ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method is called to register for what Events it wants to provide Resources . <p > The Event has to be in the following format : It should contain only one Descriptor and and one Resource with the ID description which contains an description of the Event . < / p > [CODESPLIT] @ Override public List < ? extends EventModel < ? > > announceEvents ( ) { return getTriggeredEvents ( ) . stream ( ) . map ( EventListener :: getEvent ) . collect ( Collectors . toList ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "this method is called when an object wants to get a Resource . <p > Don t use the Resources provided as arguments they are just the requests . There is a timeout after 1 second . < / p > [CODESPLIT] @ Override public List < ResourceModel > provideResource ( List < ? extends ResourceModel > list , Optional < EventModel > optional ) { //TODO: check arguments and return type here! Missing ID etc. Fail fast! return new ArrayList <> ( triggered ( list , optional ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the next available packet . The method call will block ( not return ) until a packet is available or the <tt > timeout< / tt > has elapased . If the timeout elapses without a result <tt > null< / tt > will be returned . [CODESPLIT] public Packet nextResult ( long timeout ) { try { return resultQueue . poll ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Processes a packet to see if it meets the criteria for this packet collector . If so the packet is added to the result queue . [CODESPLIT] protected void processPacket ( Packet packet ) { if ( packet == null ) { return ; } if ( packetFilter == null || packetFilter . accept ( packet ) ) { while ( ! resultQueue . offer ( packet ) ) { // Since we know the queue is full, this poll should never // actually block. resultQueue . poll ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < E > FilterableSet < E > decorate ( FilterableSet < E > set ) { return new SynchronizedFilterableSet < E > ( set ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the first Volume if found in the EventModel [CODESPLIT] public static Optional < Volume > getVolume ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( ob -> ob instanceof Integer ) . map ( ob -> ( Integer ) ob ) . findAny ( ) . flatMap ( Volume :: createVolume ) ; } else { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs the error and returns an IQ error response [CODESPLIT] public static IQ error ( IQ iq , String errorMessage , Logger logger ) { logger . error ( errorMessage ) ; return error ( iq , errorMessage ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs the error and returns an IQ error response [CODESPLIT] public static IQ error ( IQ iq , String errorMessage ) { return XMPPUtils . createErrorResponse ( iq , errorMessage , Condition . bad_request , Type . modify ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Logs the RSM page not found error and returns an IQ error response [CODESPLIT] public static IQ errorRSM ( IQ iq , Logger logger ) { String rsmMessage = \"RSM: Page Not Found\" ; logger . error ( rsmMessage + \" \" + iq ) ; return XMPPUtils . createErrorResponse ( iq , rsmMessage , Condition . item_not_found , Type . cancel ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an error response for a given IQ request . [CODESPLIT] public static IQ createErrorResponse ( final IQ request , final String message , Condition condition , Type type ) { final IQ result = request . createCopy ( ) ; result . setID ( request . getID ( ) ) ; result . setFrom ( request . getTo ( ) ) ; result . setTo ( request . getFrom ( ) ) ; PacketError e = new PacketError ( condition , type ) ; if ( message != null ) { e . setText ( message ) ; } result . setError ( e ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if the identifiable is the target of the EventModel [CODESPLIT] public static Optional < Boolean > isTarget ( EventModel eventModel , Identifiable identifiable ) { if ( eventModel . getListResourceContainer ( ) . providesResource ( Collections . singletonList ( SelectorResource . RESOURCE_ID ) ) ) { return Optional . of ( eventModel . getListResourceContainer ( ) . provideResource ( SelectorResource . RESOURCE_ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( resource -> resource instanceof Identification ) . map ( object -> ( Identification ) object ) . anyMatch ( identifiable :: isOwner ) ) ; } else { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > SortedMap < K , V > decorate ( SortedMap < K , V > map ) { return new SynchronizedSortedMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public Comparator < ? super K > comparator ( ) { return SyncUtils . synchronizeRead ( lock , new Callback < Comparator < ? super K > > ( ) { @ Override protected void doAction ( ) { _return ( getSortedMap ( ) . comparator ( ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public boolean allowImpersonate ( Subject impersSubject ) { String impersonators = ( String ) getProperty ( IMPERSONATORS_FIELD ) ; if ( impersonators == null ) { return false ; } Set < String > impersonatorSet = ImmutableSet . copyOf ( StringUtils . split ( impersonators , ' ' ) ) ; for ( Principal p : impersSubject . getPrincipals ( ) ) { if ( ADMIN_USER . equals ( p . getName ( ) ) || SYSTEM_USER . equals ( p . getName ( ) ) || impersonatorSet . contains ( p . getName ( ) ) ) { return true ; } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the login enabled time [CODESPLIT] public void setLoginEnabled ( long from , long to , boolean day , TimeZone timeZone ) { String enabledSetting = EnabledPeriod . getEnableValue ( from , to , day , timeZone ) ; if ( enabledSetting == null ) { removeProperty ( LOGIN_ENABLED_PERIOD_FIELD ) ; } else { setProperty ( LOGIN_ENABLED_PERIOD_FIELD , enabledSetting ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public boolean accept ( Packet packet ) { return ( packet instanceof IQ && ( ( IQ ) packet ) . getType ( ) . equals ( type ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized set . [CODESPLIT] public static < E > Set < E > decorate ( Set < E > set ) { return new SynchronizedSet < E > ( set ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the name associated with this entry . [CODESPLIT] public void setName ( String name ) { // Do nothing if the name hasn't changed. if ( name != null && name . equals ( this . name ) ) { return ; } this . name = name ; Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; packet . addItem ( new JID ( user ) , name , ask , subscription , getGroupNames ( ) ) ; connection . sendPacket ( packet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates the state of the entry with the new values . [CODESPLIT] void updateState ( String name , Subscription type , Ask status ) { this . name = name ; this . subscription = type ; this . ask = status ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an unmodifiable collection of the roster groups that this entry belongs to . [CODESPLIT] public Collection < RosterGroup > getGroups ( ) { List < RosterGroup > results = new ArrayList < RosterGroup > ( ) ; // Loop through all roster groups and find the ones that contain this // entry. This algorithm should be fine for ( RosterGroup group : roster . getGroups ( ) ) { if ( group . contains ( this ) ) { results . add ( group ) ; } } return Collections . unmodifiableCollection ( results ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Indicates whether some other object is equal to this by comparing all members . <p > The { @link #equals ( Object ) } method returns <code > true< / code > if the user JIDs are equal . [CODESPLIT] public boolean equalsDeep ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) != obj . getClass ( ) ) return false ; RosterEntry other = ( RosterEntry ) obj ; if ( name == null ) { if ( other . name != null ) return false ; } else if ( ! name . equals ( other . name ) ) return false ; if ( ask == null ) { if ( other . ask != null ) return false ; } else if ( ! ask . equals ( other . ask ) ) return false ; if ( subscription == null ) { if ( other . subscription != null ) return false ; } else if ( ! subscription . equals ( other . subscription ) ) return false ; if ( user == null ) { if ( other . user != null ) return false ; } else if ( ! user . equals ( other . user ) ) return false ; return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public V get ( String key ) { Element e = cache . get ( key ) ; if ( e == null ) { return stats ( null ) ; } return stats ( e . getObjectValue ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inherit - doc } [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public V put ( String key , V payload ) { V previous = null ; if ( cache . isKeyInCache ( key ) ) { Element e = cache . get ( key ) ; if ( e != null ) { previous = ( V ) e . getObjectValue ( ) ; } } cache . put ( new Element ( key , payload ) ) ; return previous ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void removeChildren ( String key ) { cache . remove ( key ) ; if ( ! key . endsWith ( \"/\" ) ) { key = key + \"/\" ; } List < ? > keys = cache . getKeys ( ) ; for ( Object k : keys ) { if ( ( ( String ) k ) . startsWith ( key ) ) { cache . remove ( k ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public List < V > list ( ) { List < String > keys = cache . getKeys ( ) ; List < V > values = new ArrayList < V > ( ) ; for ( String k : keys ) { Element e = cache . get ( k ) ; if ( e != null ) { values . add ( ( V ) e . getObjectValue ( ) ) ; } } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Appends RSM info to query response . [CODESPLIT] public static void appendRSMElement ( Element queryElement , RSM rsm ) { Element setElement = queryElement . addElement ( \"set\" , RSM . NAMESPACE ) ; if ( rsm . getFirst ( ) != null ) { Element firstElement = setElement . addElement ( \"first\" ) ; firstElement . addAttribute ( \"index\" , rsm . getIndex ( ) . toString ( ) ) ; firstElement . setText ( rsm . getFirst ( ) ) ; } if ( rsm . getLast ( ) != null ) { Element lastElement = setElement . addElement ( \"last\" ) ; lastElement . setText ( rsm . getLast ( ) ) ; } setElement . addElement ( \"count\" ) . setText ( String . valueOf ( rsm . getCount ( ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses an RSM from a query XML element [CODESPLIT] public static RSM parseRSM ( Element queryElement ) { RSM rsm = new RSM ( ) ; Element setElement = queryElement . element ( \"set\" ) ; if ( setElement == null ) { return rsm ; } Element after = setElement . element ( \"after\" ) ; if ( after != null ) { rsm . setAfter ( after . getText ( ) ) ; } Element before = setElement . element ( \"before\" ) ; if ( before != null ) { String beforeText = before . getText ( ) ; rsm . setBefore ( beforeText == null ? \"\" : beforeText ) ; } Element index = setElement . element ( \"index\" ) ; if ( index != null ) { rsm . setIndex ( Integer . parseInt ( index . getText ( ) ) ) ; } Element max = setElement . element ( \"max\" ) ; if ( max != null ) { rsm . setMax ( Integer . parseInt ( max . getText ( ) ) ) ; } return rsm ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Filters response objects based on the RSM parameters . Updates the RSM object with item count first and last jid [CODESPLIT] public static List < Identifiable > filterRSMResponse ( List < Identifiable > objects , RSM rsm ) throws IllegalArgumentException { String after = rsm . getAfter ( ) ; String before = rsm . getBefore ( ) ; int initialIndex = rsm . getIndex ( ) ; int lastIndex = objects . size ( ) ; if ( after != null || ( before != null && ! before . isEmpty ( ) ) ) { boolean afterItemFound = false ; boolean beforeItemFound = false ; int i = 0 ; for ( Identifiable object : objects ) { if ( after != null && after . equals ( object . getId ( ) ) ) { initialIndex = i + 1 ; afterItemFound = true ; } if ( before != null && before . equals ( object . getId ( ) ) ) { lastIndex = i ; beforeItemFound = true ; } i ++ ; } if ( after != null && ! afterItemFound ) { throw new IllegalArgumentException ( ) ; } if ( before != null && ! before . isEmpty ( ) && ! beforeItemFound ) { throw new IllegalArgumentException ( ) ; } } if ( rsm . getMax ( ) != null ) { if ( before != null ) { initialIndex = lastIndex - rsm . getMax ( ) ; } else { lastIndex = initialIndex + rsm . getMax ( ) ; } } boolean outOfRange = initialIndex > lastIndex || initialIndex < 0 || lastIndex > objects . size ( ) ; List < Identifiable > filteredList = outOfRange ? new LinkedList < Identifiable > ( ) : objects . subList ( initialIndex , lastIndex ) ; rsm . setCount ( objects . size ( ) ) ; rsm . setIndex ( initialIndex ) ; if ( ! filteredList . isEmpty ( ) ) { rsm . setFirst ( filteredList . get ( 0 ) . getId ( ) ) ; rsm . setLast ( filteredList . get ( filteredList . size ( ) - 1 ) . getId ( ) ) ; } return filteredList ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles an event from OSGi and indexes it . The indexing operation should only index metadata and not bodies . Indexing of bodies is performed by a seperate thread . [CODESPLIT] public void handleEvent ( Event event ) { String topic = event . getTopic ( ) ; Session session = ( Session ) event . getProperty ( Session . class . getName ( ) ) ; RepositorySession repositoryRession = null ; Thread thisThread = Thread . currentThread ( ) ; ClassLoader classloader = thisThread . getContextClassLoader ( ) ; // ES might load classes so we had better set the context classloader. try { thisThread . setContextClassLoader ( this . getClass ( ) . getClassLoader ( ) ) ; try { repositoryRession = new RepositorySessionImpl ( session , repository ) ; } catch ( ClientPoolException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } catch ( StorageClientException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } catch ( AccessDeniedException e1 ) { LOGGER . error ( e1 . getMessage ( ) , e1 ) ; return ; } LOGGER . debug ( \"Got Event {} {} \" , event , handlers ) ; Collection < IndexingHandler > contentIndexHandler = handlers . get ( topic ) ; if ( contentIndexHandler != null && contentIndexHandler . size ( ) > 0 ) { BulkRequestBuilder bulk = client . prepareBulk ( ) ; int added = 0 ; for ( IndexingHandler indexingHandler : contentIndexHandler ) { Collection < InputDocument > documents = indexingHandler . getDocuments ( repositoryRession , event ) ; for ( InputDocument in : documents ) { LOGGER . info ( \"Indexing {} \" , in ) ; if ( in . isDelete ( ) ) { bulk . add ( client . prepareDelete ( in . getIndexName ( ) , in . getDocumentType ( ) , in . getDocumentId ( ) ) ) ; added ++ ; } else { try { IndexRequestBuilder r = client . prepareIndex ( in . getIndexName ( ) , in . getDocumentType ( ) , in . getDocumentId ( ) ) ; XContentBuilder d = XContentFactory . jsonBuilder ( ) ; d = d . startObject ( ) ; for ( Entry < String , Object > e : in . getKeyData ( ) ) { d = d . field ( e . getKey ( ) , e . getValue ( ) ) ; } r . setSource ( d . endObject ( ) ) ; bulk . add ( r ) ; added ++ ; } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } } } } if ( added > 0 ) { BulkResponse resp = bulk . execute ( ) . actionGet ( ) ; if ( resp . hasFailures ( ) ) { for ( BulkItemResponse br : Iterables . adaptTo ( resp . iterator ( ) ) ) { if ( br . failed ( ) ) { LOGGER . error ( \"Failed {} {} \" , br . getId ( ) , br . getFailureMessage ( ) ) ; // not going to retry at the moment, just log. } } } } } } finally { if ( repositoryRession != null ) { repositoryRession . logout ( ) ; } thisThread . setContextClassLoader ( classloader ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new LeavingEvent [CODESPLIT] public static Optional < LeavingEvent > createLeavingEvent ( Identification source , boolean strict , List < String > descriptors ) { try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } descriptors . add ( ID ) ; descriptors . add ( CommonEvents . Descriptors . NOT_INTERRUPT ) ; LeavingEvent stopRequest = new LeavingEvent ( source , descriptors ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reloads the entire roster from the server . This is an asynchronous operation which means the method will return immediately and the roster will be reloaded at a later point when the server responds to the reload request . [CODESPLIT] public void reload ( ) { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( \"Not logged in to server.\" ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( \"Anonymous users can't have a roster.\" ) ; } Roster packet = new Roster ( ) ; if ( rosterStore != null && connection . isRosterVersioningSupported ( ) ) { packet . getElement ( ) . element ( \"query\" ) . addAttribute ( \"ver\" , rosterStore . getRosterVersion ( ) ) ; PacketFilter filter = new PacketIDFilter ( packet . getID ( ) ) ; connection . addPacketListener ( new RosterResultListener ( ) , filter ) ; } connection . sendPacket ( packet ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new group . <p > <p / > Note : you must add at least one entry to the group for the group to be kept after a logout / login . This is due to the way that XMPP stores group information . [CODESPLIT] public RosterGroup createGroup ( String name ) { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( \"Not logged in to server.\" ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( \"Anonymous users can't have a roster.\" ) ; } if ( groups . containsKey ( name ) ) { throw new IllegalArgumentException ( \"Group with name \" + name + \" alread exists.\" ) ; } RosterGroup group = new RosterGroup ( name , connection ) ; groups . put ( name , group ) ; return group ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new roster entry and presence subscription . The server will asynchronously update the roster with the subscription status . [CODESPLIT] public void createEntry ( String user , String name , String [ ] groups ) throws XMPPException { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( \"Not logged in to server.\" ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( \"Anonymous users can't have a roster.\" ) ; } // Create and send roster entry creation packet. Roster rosterPacket = new Roster ( ) ; rosterPacket . setType ( IQ . Type . set ) ; rosterPacket . addItem ( new JID ( user ) , name , null , null , Arrays . asList ( groups ) ) ; // Wait up to a certain number of seconds for a reply from the server. PacketCollector collector = connection . createPacketCollector ( new PacketIDFilter ( rosterPacket . getID ( ) ) ) ; connection . sendPacket ( rosterPacket ) ; IQ response = ( IQ ) collector . nextResult ( SmackConfiguration . getPacketReplyTimeout ( ) ) ; collector . cancel ( ) ; if ( response == null ) { throw new XMPPException ( \"No response from the server.\" ) ; } // If the server replied with an error, throw an exception. else if ( response . getType ( ) == IQ . Type . error ) { throw new XMPPException ( response . getError ( ) ) ; } // Create a presence subscription packet and send. Presence presencePacket = new Presence ( Presence . Type . subscribe ) ; presencePacket . setTo ( user ) ; connection . sendPacket ( presencePacket ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a roster entry from the roster . The roster entry will also be removed from the unfiled entries or from any roster group where it could belong and will no longer be part of the roster . Note that this is an asynchronous call -- Smack must wait for the server to send an updated subscription status . [CODESPLIT] public void removeEntry ( RosterEntry entry ) throws XMPPException { if ( ! connection . isAuthenticated ( ) ) { throw new IllegalStateException ( \"Not logged in to server.\" ) ; } if ( connection . isAnonymous ( ) ) { throw new IllegalStateException ( \"Anonymous users can't have a roster.\" ) ; } // Only remove the entry if it's in the entry list. // The actual removal logic takes place in // RosterPacketListenerprocess>>Packet(Packet) if ( ! entries . containsKey ( entry . getUser ( ) ) ) { return ; } Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; packet . addItem ( new JID ( entry . getUser ( ) ) , entry . getName ( ) , entry . getAsk ( ) , Subscription . remove , entry . getGroupNames ( ) ) ; PacketCollector collector = connection . createPacketCollector ( new PacketIDFilter ( packet . getID ( ) ) ) ; connection . sendPacket ( packet ) ; IQ response = ( IQ ) collector . nextResult ( SmackConfiguration . getPacketReplyTimeout ( ) ) ; collector . cancel ( ) ; if ( response == null ) { throw new XMPPException ( \"No response from the server.\" ) ; } // If the server replied with an error, throw an exception. else if ( response . getType ( ) == IQ . Type . error ) { throw new XMPPException ( response . getError ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an unmodifiable collection of all entries in the roster including entries that don t belong to any groups . [CODESPLIT] public Collection < RosterEntry > getEntries ( ) { Set < RosterEntry > allEntries = new HashSet < RosterEntry > ( ) ; // Loop through all roster groups and add their entries to the answer for ( RosterGroup rosterGroup : getGroups ( ) ) { allEntries . addAll ( rosterGroup . getEntries ( ) ) ; } // Add the roster unfiled entries to the answer allEntries . addAll ( unfiledEntries ) ; return Collections . unmodifiableCollection ( allEntries ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the roster entry associated with the given XMPP address or <tt > null< / tt > if the user is not an entry in the roster . [CODESPLIT] public RosterEntry getEntry ( String user ) { if ( user == null ) { return null ; } return entries . get ( user . toLowerCase ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the presence info for a particular user . If the user is offline or if no presence data is available ( such as when you are not subscribed to the user s presence updates ) unavailable presence will be returned . <p > <p / > If the user has several presences ( one for each resource ) then the presence with highest priority will be returned . If multiple presences have the same priority the one with the most available presence mode will be returned . In order that s { @link org . jivesoftware . smack . packet . Presence . Mode#chat free to chat } { @link org . jivesoftware . smack . packet . Presence . Mode#available available } { @link org . jivesoftware . smack . packet . Presence . Mode#away away } { @link org . jivesoftware . smack . packet . Presence . Mode#xa extended away } and { @link org . jivesoftware . smack . packet . Presence . Mode#dnd do not disturb } . <p > <p / > Note that presence information is received asynchronously . So just after logging in to the server presence values for users in the roster may be unavailable even if they are actually online . In other words the value returned by this method should only be treated as a snapshot in time and may not accurately reflect other user s presence instant by instant . If you need to track presence over time such as when showing a visual representation of the roster consider using a { @link RosterListener } . [CODESPLIT] public Presence getPresence ( String user ) { String key = getPresenceMapKey ( StringUtils . parseBareAddress ( user ) ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return presence ; } else { // Find the resource with the highest priority // Might be changed to use the resource with the highest // availability instead. Presence presence = null ; for ( String resource : userPresences . keySet ( ) ) { Presence p = userPresences . get ( resource ) ; if ( ! p . isAvailable ( ) ) { continue ; } // Chose presence with highest priority first. if ( presence == null || p . getPriority ( ) > presence . getPriority ( ) ) { presence = p ; } // If equal priority, choose \"most available\" by the mode value. else if ( p . getPriority ( ) == presence . getPriority ( ) ) { Presence . Show pMode = p . getShow ( ) ; // Default to presence mode of available. if ( pMode == null ) { pMode = Presence . Show . chat ; } Presence . Show presenceMode = presence . getShow ( ) ; // Default to presence mode of available. if ( presenceMode == null ) { presenceMode = Presence . Show . chat ; } if ( pMode . compareTo ( presenceMode ) < 0 ) { presence = p ; } } } if ( presence == null ) { presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return presence ; } else { return presence ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the presence info for a particular user s resource or unavailable presence if the user is offline or if no presence information is available such as when you are not subscribed to the user s presence updates . [CODESPLIT] public Presence getPresenceResource ( String userWithResource ) { String key = getPresenceMapKey ( userWithResource ) ; String resource = StringUtils . parseResource ( userWithResource ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { Presence presence = userPresences . get ( resource ) ; if ( presence == null ) { presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { return presence ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns an iterator ( of Presence objects ) for all of a user s current presences or an unavailable presence if the user is unavailable ( offline ) or if no presence information is available such as when you are not subscribed to the user s presence updates . [CODESPLIT] public Iterator < Presence > getPresences ( String user ) { String key = getPresenceMapKey ( user ) ; Map < String , Presence > userPresences = presenceMap . get ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return Arrays . asList ( presence ) . iterator ( ) ; } else { Collection < Presence > answer = new ArrayList < Presence > ( ) ; for ( Presence presence : userPresences . values ( ) ) { if ( presence . isAvailable ( ) ) { answer . add ( presence ) ; } } if ( ! answer . isEmpty ( ) ) { return answer . iterator ( ) ; } else { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( user ) ; return Arrays . asList ( presence ) . iterator ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the key to use in the presenceMap for a fully qualified XMPP ID . The roster can contain any valid address format such us domain / resource user@domain or user@domain / resource . If the roster contains an entry associated with the fully qualified XMPP ID then use the fully qualified XMPP ID as the key in presenceMap otherwise use the bare address . Note : When the key in presenceMap is a fully qualified XMPP ID the userPresences is useless since it will always contain one entry for the user . [CODESPLIT] private String getPresenceMapKey ( String user ) { if ( user == null ) { return null ; } String key = user ; if ( ! contains ( user ) ) { key = StringUtils . parseBareAddress ( user ) ; } return key . toLowerCase ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the presence of available contacts offline by simulating an unavailable presence sent from the server . After a disconnection every Presence is set to offline . [CODESPLIT] private void setOfflinePresences ( ) { Presence packetUnavailable ; for ( String user : presenceMap . keySet ( ) ) { Map < String , Presence > resources = presenceMap . get ( user ) ; if ( resources != null ) { for ( String resource : resources . keySet ( ) ) { packetUnavailable = new Presence ( Presence . Type . unavailable ) ; packetUnavailable . setFrom ( user + \"/\" + resource ) ; presencePacketListener . processPacket ( packetUnavailable ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires roster changed event to roster listeners indicating that the specified collections of contacts have been added updated or deleted from the roster . [CODESPLIT] private void fireRosterChangedEvent ( Collection < String > addedEntries , Collection < String > updatedEntries , Collection < String > deletedEntries ) { for ( RosterListener listener : rosterListeners ) { if ( ! addedEntries . isEmpty ( ) ) { listener . entriesAdded ( addedEntries ) ; } if ( ! updatedEntries . isEmpty ( ) ) { listener . entriesUpdated ( updatedEntries ) ; } if ( ! deletedEntries . isEmpty ( ) ) { listener . entriesDeleted ( deletedEntries ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the digest value using a connection ID and password . Password digests offer a more secure alternative for authentication compared to plain text . The digest is the hex - encoded SHA - 1 hash of the connection ID plus the user s password . If the digest and password are set digest authentication will be used . If only one value is set the respective authentication mode will be used . [CODESPLIT] public void setDigest ( String connectionID , String password ) { setDigest ( StringUtils . hash ( connectionID + password ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "generates the resources [CODESPLIT] @ Override public Optional < ? extends ResourceModel > generateResource ( ResourceModel resourceModel , Optional < EventModel > event ) { switch ( resourceModel . getResourceID ( ) ) { case BroadcasterAvailablePlaylists . RESOURCE_ID : return createBroadcasterAvailablePlaylists ( ) ; case BroadcasterPlaylist . RESOURCE_ID : return createBroadcasterPlaylist ( resourceModel ) ; default : return MusicResourceGenerator . super . generateResource ( resourceModel , event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the value stored in this Map Entry . <p / > This Map Entry is not connected to a Map so only the local data is changed . [CODESPLIT] public V setValue ( V value ) { V answer = this . value ; this . value = value ; return answer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Object borrowObject ( ) throws Exception { log . debug ( \" borrowing object..\" ) ; WorkerThread thread = ( WorkerThread ) super . borrowObject ( ) ; thread . setPool ( this ) ; return thread ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void returnObject ( Object obj ) throws Exception { log . debug ( \" returning object..\" + obj ) ; super . returnObject ( obj ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new PresenceEvent [CODESPLIT] public static Optional < PresenceEvent > createPresenceEvent ( Identification source , boolean strict , boolean known , boolean firstEncounter , List < String > descriptors ) { try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } if ( known ) { descriptors . add ( KNOWN_DESCRIPTOR ) ; } else { descriptors . add ( UNKNOWN_DESCRIPTOR ) ; } if ( firstEncounter ) descriptors . add ( FIRST_ENCOUNTER_DESCRIPTOR ) ; descriptors . add ( ID ) ; PresenceEvent stopRequest = new PresenceEvent ( source , descriptors ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new PresenceEvent [CODESPLIT] public static Optional < PresenceEvent > createPresenceEvent ( Identification source , boolean strict , boolean known , boolean firstEncounter , List < String > descriptors , Long timePassed ) { try { if ( strict ) { descriptors . add ( STRICT_DESCRIPTOR ) ; } else { descriptors . add ( GENERAL_DESCRIPTOR ) ; } if ( known ) { descriptors . add ( KNOWN_DESCRIPTOR ) ; } else { descriptors . add ( UNKNOWN_DESCRIPTOR ) ; } if ( firstEncounter ) descriptors . add ( FIRST_ENCOUNTER_DESCRIPTOR ) ; descriptors . add ( ID ) ; PresenceEvent presenceEvent = new PresenceEvent ( source , descriptors ) ; presenceEvent . addResource ( new LastEncountered ( source , timePassed ) ) ; return Optional . of ( presenceEvent ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > Map < K , V > decorate ( Map < K , V > map ) { return new SynchronizedMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public void clear ( ) { SyncUtils . synchronizeWrite ( lock , new Callback < Object > ( ) { @ Override protected void doAction ( ) { map . clear ( ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "tries to set the Volume of the PlayerRequest . <p > if the Player supports the Change of the Volume it will create a new PlayerRequest and return it if not it returns this . < / p > [CODESPLIT] public PlayerRequest trySetVolume ( Volume volume ) { if ( capabilities . canChangeVolume ( ) ) { return new PlayerRequest ( trackInfo , playlist , permanent , player , capabilities , context , identifiable , volume ) ; } return this ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a List of Resources that can be added to an already existing event . <p > This causes the Addon to block the Event in the OutputPlugin lifecycle of the Event . [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public List < ResourceModel > resourcesForExisting ( ) { List < ResourceModel > resourceModels = new ArrayList <> ( ) ; IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new MusicUsageResource ( id , true ) ) . ifPresent ( resourceModels :: add ) ; if ( volume != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new VolumeResource ( id , volume ) ) . ifPresent ( resourceModels :: add ) ; } if ( playlist != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new PlaylistResource ( id , playlist ) ) . ifPresent ( resourceModels :: add ) ; } if ( trackInfo != null ) { IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . map ( id -> new TrackInfoResource ( id , trackInfo ) ) . ifPresent ( resourceModels :: add ) ; } return resourceModels ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "helper method for PlaylistSelector [CODESPLIT] static PlayerRequest createPlayerRequest ( Playlist playlist , boolean permanent , Identification player , Capabilities capabilities , Context context , Identifiable identifiable ) { return new PlayerRequest ( null , playlist , permanent , player , capabilities , context , identifiable ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new PlayerRequest . <p > the resulting PlayerRequest is not permanent which means that it will mute all other sound but is limited to 10 minutes . <br > For this method to return a non - empty Optional the following criteria must be met : <br > <ul > <li > the player must exist and be support the standard defined through the sdk< / li > <li > the players - capabilities must allow requests from outside< / li > <li > the players - capabilities must allow a requests with specified a specified playlist / trackInfo< / li > < / ul > [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static Optional < PlayerRequest > createPlayerRequest ( TrackInfo trackInfo , Identification player , AddOnModule source ) { return createPlayerRequest ( trackInfo , false , player , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new PlayerRequest . <p > the resulting PlayerRequest is not permanent which means that it will mute all other sound but is limited to 10 minutes . <br > For this method to return a non - empty Optional the following criteria must be met : <br > <ul > <li > the player must exist and be support the standard defined through the sdk< / li > <li > the players - capabilities must allow requests from outside< / li > <li > the players - capabilities must allow a requests with specified a specified playlist / trackInfo< / li > < / ul > [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static Optional < PlayerRequest > createPlayerRequest ( Playlist playlist , Identification player , AddOnModule source ) { return createPlayerRequest ( playlist , false , player , source ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new PlayerRequest . <p > For this method to return a non - empty Optional the following criteria must be met : <br > <ul > <li > the player must exist and be support the standard defined through the sdk< / li > <li > the players - capabilities must allow requests from outside< / li > <li > the players - capabilities must allow a requests with specified a specified playlist / trackInfo< / li > < / ul > [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static Optional < PlayerRequest > createPlayerRequest ( Playlist playlist , boolean permanent , Identification player , AddOnModule source ) { if ( playlist == null || player == null || source == null ) return Optional . empty ( ) ; try { return source . getContext ( ) . getResources ( ) . generateResource ( new CapabilitiesResource ( player ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( list -> list . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( resource -> Capabilities . importFromResource ( resource , source . getContext ( ) ) ) ) . get ( 1 , TimeUnit . SECONDS ) . filter ( capabilities -> { if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { source . getContext ( ) . getLogger ( ) . error ( \"player does not handle play-request from outside\" ) ; return false ; } if ( ! capabilities . hasPlayRequestDetailed ( ) ) { source . getContext ( ) . getLogger ( ) . error ( \"player does not handle playlist-request from outside\" ) ; return false ; } if ( ! playlist . verify ( capabilities ) ) { source . getContext ( ) . getLogger ( ) . error ( \"player can not handle the playlist, probably illegal PlaybackModes\" ) ; return false ; } return true ; } ) . map ( capabilities -> new PlayerRequest ( null , playlist , permanent , player , capabilities , source . getContext ( ) , source ) ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { source . getContext ( ) . getLogger ( ) . debug ( \"unable to obtain capabilities\" ) ; return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the time passed if available [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static Optional < Long > getTimePassed ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( ob -> ob instanceof Long ) . map ( ob -> ( Long ) ob ) . findAny ( ) ; } else { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the listener will always be called when the Properties - file changes . [CODESPLIT] public void registerUpdateListener ( Consumer < PropertiesAssistant > listener ) { if ( listener != null ) listeners . add ( new WeakReference <> ( listener ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes properties in the addOn . Creates new properties file using default properties . [CODESPLIT] public void initProperties ( ) { propertiesPath = getContext ( ) . getFiles ( ) . getPropertiesLocation ( ) + File . separator + getContext ( ) . getAddOns ( ) . getAddOn ( ) . getID ( ) + \".properties\" ; this . propertiesFile = new File ( propertiesPath ) ; if ( ! this . propertiesFile . exists ( ) ) try { this . propertiesFile . createNewFile ( ) ; } catch ( IOException e ) { error ( \"Error while trying to create the new Properties file\" , e ) ; } try { BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( this . propertiesFile ) , \"UTF8\" ) ) ; try { properties . load ( in ) ; } catch ( IOException e ) { error ( \"unable to load the InputStream for the PropertiesFile\" , e ) ; } } catch ( FileNotFoundException | UnsupportedEncodingException e ) { error ( \"Error while trying to read Properties-File\" , e ) ; } if ( defaultPropertiesPath != null && new File ( defaultPropertiesPath ) . exists ( ) ) { @ SuppressWarnings ( \"unchecked\" ) Enumeration < String > keys = ( Enumeration < String > ) properties . propertyNames ( ) ; if ( ! keys . hasMoreElements ( ) ) { try { createDefaultPropertyFile ( defaultPropertiesPath ) ; } catch ( IOException e ) { error ( \"Error while trying to copy the Default-Properties File\" , e ) ; } if ( new File ( defaultPropertiesPath ) . exists ( ) && ! writeToPropertiesFile ( defaultPropertiesPath ) ) return ; reloadProperties ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "reloads the propertiesFile into the properties object [CODESPLIT] private void reloadProperties ( ) { Properties temp = new Properties ( ) ; BufferedReader bufferedReader = null ; try { File properties = new File ( propertiesPath ) ; bufferedReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( properties ) , \"UTF8\" ) ) ; temp . load ( bufferedReader ) ; this . properties = temp ; listeners . removeIf ( weakReference -> weakReference . get ( ) == null ) ; listeners . forEach ( weakReference -> { Consumer < PropertiesAssistant > consumer = weakReference . get ( ) ; if ( consumer != null ) consumer . accept ( this ) ; } ) ; } catch ( IOException e ) { error ( \"Error while trying to load the Properties-File: \" + propertiesPath , e ) ; } finally { if ( bufferedReader != null ) { try { bufferedReader . close ( ) ; } catch ( IOException e ) { error ( \"Unable to close input stream\" , e ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses stream error packets . [CODESPLIT] public static StreamError parseStreamError ( Element el ) throws IOException , XmlPullParserException { String code = null ; Element condEl = ( Element ) el . elements ( ) . iterator ( ) . next ( ) ; if ( condEl . getNamespace ( ) . getURI ( ) . equals ( StreamError . NAMESPACE ) ) { code = condEl . getName ( ) ; } String text = condEl . elementText ( \"text\" ) ; return new StreamError ( code , text ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the available SASL mechanisms reported from the server . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Collection < String > parseMechanisms ( Element mechanismsEl ) throws Exception { List < Element > mechanisms = mechanismsEl . elements ( \"mechanism\" ) ; List < String > mechanismsStr = new LinkedList < String > ( ) ; for ( Element mechanismEl : mechanisms ) { mechanismsStr . add ( mechanismEl . getText ( ) ) ; } return mechanismsStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parse the available compression methods reported from the server . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public static Collection < String > parseCompressionMethods ( Element compressionEl ) throws IOException , XmlPullParserException { List < Element > methodsEls = compressionEl . elements ( \"method\" ) ; List < String > methodsStr = new LinkedList < String > ( ) ; for ( Element methodEl : methodsEls ) { methodsStr . add ( methodEl . getText ( ) ) ; } return methodsStr ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Parses a packet extension sub - packet . [CODESPLIT] public static PacketExtension parsePacketExtension ( String elementName , String namespace , XmlPullParser parser ) throws Exception { DefaultPacketExtension extension = new DefaultPacketExtension ( elementName , namespace ) ; boolean done = false ; while ( ! done ) { int eventType = parser . next ( ) ; if ( eventType == XmlPullParser . START_TAG ) { String name = parser . getName ( ) ; // If an empty element, set the value with the empty string. if ( parser . isEmptyElementTag ( ) ) { extension . setValue ( name , \"\" ) ; } // Otherwise, get the the element text. else { eventType = parser . next ( ) ; if ( eventType == XmlPullParser . TEXT ) { String value = parser . getText ( ) ; extension . setValue ( name , value ) ; } } } else if ( eventType == XmlPullParser . END_TAG ) { if ( parser . getName ( ) . equals ( elementName ) ) { done = true ; } } } return extension ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes a String into an object of the specified type . If the object type is not supported null will be returned . [CODESPLIT] private static Object decode ( Class < ? > type , String value ) throws Exception { if ( type . getName ( ) . equals ( \"java.lang.String\" ) ) { return value ; } if ( type . getName ( ) . equals ( \"boolean\" ) ) { return Boolean . valueOf ( value ) ; } if ( type . getName ( ) . equals ( \"int\" ) ) { return Integer . valueOf ( value ) ; } if ( type . getName ( ) . equals ( \"long\" ) ) { return Long . valueOf ( value ) ; } if ( type . getName ( ) . equals ( \"float\" ) ) { return Float . valueOf ( value ) ; } if ( type . getName ( ) . equals ( \"double\" ) ) { return Double . valueOf ( value ) ; } if ( type . getName ( ) . equals ( \"java.lang.Class\" ) ) { return Class . forName ( value ) ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target ) { return createStartMusicRequest ( source , target , ( TrackInfo ) null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , TrackInfo trackInfo ) { return createStartMusicRequest ( source , target , trackInfo , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , TrackInfo trackInfo , boolean isUsingJava ) { if ( target . equals ( source ) ) return Optional . empty ( ) ; try { StartMusicRequest request = new StartMusicRequest ( source , isUsingJava ) ; request . addResource ( new SelectorResource ( source , target ) ) ; if ( trackInfo != null ) request . addResource ( new TrackInfoResource ( target , trackInfo , source ) ) ; return Optional . of ( request ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , Playlist playlist ) { return createStartMusicRequest ( source , target , playlist , true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StartRequest [CODESPLIT] public static Optional < StartMusicRequest > createStartMusicRequest ( Identification source , Identification target , Playlist playlist , boolean isUsingJava ) { if ( target . equals ( source ) ) return Optional . empty ( ) ; try { StartMusicRequest request = new StartMusicRequest ( source , isUsingJava ) ; request . addResource ( new SelectorResource ( source , target ) ) ; if ( playlist != null ) request . addResource ( new PlaylistResource ( target , playlist , source ) ) ; return Optional . of ( request ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verifies that the StartMusicRequest is correct and checks whether the you are meant to react to it [CODESPLIT] public static boolean verify ( EventModel eventModel , Capabilities capabilities , Identifiable player , List < Identifiable > activators ) { if ( ! eventModel . containsDescriptor ( StartMusicRequest . ID ) ) return false ; if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { if ( activators . stream ( ) . noneMatch ( identifiable -> identifiable . isOwner ( eventModel . getSource ( ) ) ) ) return false ; } if ( ! PlaylistResource . getPlaylist ( eventModel ) . map ( playlist -> playlist . verify ( capabilities ) ) . orElse ( true ) ) { return false ; } return SelectorResource . isTarget ( eventModel , player ) . orElse ( false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a filter where valid when an object in a collection is the <strong > same as< / strong > the base object . [CODESPLIT] public static < E > Filter < E > createSameAsFilter ( final E base ) { return new Filter < E > ( ) { public boolean isValid ( E obj ) { return ( base == obj ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a filter where valid when an object in a collection is the <strong > equal to< / strong > the base object . [CODESPLIT] public static < E > Filter < E > createEqualToFilter ( final Object base ) { return new Filter < E > ( ) { public boolean isValid ( E obj ) { return obj . equals ( base ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a filter where valid when an Comparable in a collection is considered <strong > less than< / strong > the base object . [CODESPLIT] public static < E extends Comparable < E > > Filter < E > createLessThanFilter ( final E base ) { return createLessThanFilter ( base , new Comparator < E > ( ) { public int compare ( E obj1 , E obj2 ) { return obj1 . compareTo ( obj2 ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a filter where valid when an Object in a collection is considered <strong > less than< / strong > the base object based on the given Comparator . [CODESPLIT] public static < E > Filter < E > createLessThanFilter ( final E base , final Comparator < E > comparator ) { return new Filter < E > ( ) { public boolean isValid ( E obj ) { return comparator . compare ( obj , base ) < 0 ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the PlaybackState from the resource [CODESPLIT] public static Optional < PlaybackState > getPlaybackStateFromResource ( ResourceModel x ) { if ( ! x . getResourceID ( ) . equals ( ID ) ) return Optional . empty ( ) ; Object resource = x . getResource ( ) ; if ( resource instanceof String ) { String state = ( String ) resource ; try { return Optional . of ( PlaybackState . valueOf ( state ) ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } } else { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the secret key for a sub - domain . If no key was found then the default secret key will be returned . [CODESPLIT] public String getSecretKey ( String subdomain ) { // Find the proper secret key to connect as the subdomain. String secretKey = secretKeys . get ( subdomain ) ; if ( secretKey == null ) { secretKey = defaultSecretKey ; } return secretKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns if we want components to be able to connect multiple times to the same JID . This is a custom Openfire extension and will not work with any other XMPP server . Other XMPP servers should ignore this extra setting . [CODESPLIT] public boolean isMultipleAllowed ( String subdomain ) { Boolean allowed = allowMultiple . get ( subdomain ) ; return allowed != null && allowed ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value mapped to the key specified . [CODESPLIT] public V get ( Object key ) { purgeBeforeRead ( ) ; Entry < K , V > entry = getEntry ( key ) ; if ( entry == null ) { return null ; } return entry . getValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a key - value mapping into this map . Neither the key nor the value may be null . [CODESPLIT] public V put ( K key , V value ) { if ( key == null ) { throw new NullPointerException ( \"null keys not allowed\" ) ; } if ( value == null ) { throw new NullPointerException ( \"null values not allowed\" ) ; } purgeBeforeWrite ( ) ; return super . put ( key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified mapping from this map . [CODESPLIT] public V remove ( Object key ) { if ( key == null ) { return null ; } purgeBeforeWrite ( ) ; return super . remove ( key ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set view of this map s entries . An iterator returned entry is valid until <code > next () < / code > is called again . The <code > setValue () < / code > method on the <code > toArray< / code > entries has no effect . [CODESPLIT] public Set < Map . Entry < K , V > > entrySet ( ) { if ( entrySet == null ) { entrySet = new ReferenceEntrySet < K , V > ( this ) ; } return entrySet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set view of this map s keys . [CODESPLIT] public Set < K > keySet ( ) { if ( keySet == null ) { keySet = new ReferenceKeySet < K , V > ( this ) ; } return keySet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection view of this map s values . [CODESPLIT] public Collection < V > values ( ) { if ( values == null ) { values = new ReferenceValues < K , V > ( this ) ; } return values ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Purges stale mappings from this map . <p / > Note that this method is not synchronized! Special care must be taken if for instance you want stale mappings to be removed on a periodic basis by some background thread . [CODESPLIT] protected void purge ( ) { Reference ref = queue . poll ( ) ; while ( ref != null ) { purge ( ref ) ; ref = queue . poll ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Purges the specified reference . [CODESPLIT] protected void purge ( Reference ref ) { // The hashCode of the reference is the hashCode of the // mapping key, even if the reference refers to the // mapping value... int hash = ref . hashCode ( ) ; int index = hashIndex ( hash , data . length ) ; HashEntry < K , V > previous = null ; HashEntry < K , V > entry = data [ index ] ; while ( entry != null ) { if ( ( ( ReferenceEntry < K , V > ) entry ) . purge ( ref ) ) { if ( previous == null ) { data [ index ] = entry . next ; } else { previous . next = entry . next ; } this . size -- ; return ; } previous = entry ; entry = entry . next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the entry mapped to the key specified . [CODESPLIT] protected HashEntry < K , V > getEntry ( Object key ) { if ( key == null ) { return null ; } else { return super . getEntry ( key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the hash code for a MapEntry . Subclasses can override this for example to use the identityHashCode . [CODESPLIT] protected int hashEntry ( Object key , Object value ) { return ( key == null ? 0 : key . hashCode ( ) ) ^ ( value == null ? 0 : value . hashCode ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a ReferenceEntry instead of a HashEntry . [CODESPLIT] public HashEntry < K , V > createEntry ( HashEntry < K , V > next , int hashCode , K key , V value ) { return new ReferenceEntry < K , V > ( this , ( ReferenceEntry < K , V > ) next , hashCode , key , value ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the superclass method to store the state of this class . <p / > Serialization is not one of the JDK s nicest topics . Normal serialization will initialise the superclass before the subclass . Sometimes however this isn t what you want as in this case the <code > put () < / code > method on read can be affected by subclass state . <p / > The solution adopted here is to serialize the state data of this class in this protected method . This method must be called by the <code > writeObject () < / code > of the first serializable subclass . <p / > Subclasses may override if they have a specific field that must be present on read before this implementation will work . Generally the read determines what must be serialized here if anything . [CODESPLIT] protected void doWriteObject ( ObjectOutputStream out ) throws IOException { out . writeInt ( keyType ) ; out . writeInt ( valueType ) ; out . writeBoolean ( purgeValues ) ; out . writeFloat ( loadFactor ) ; out . writeInt ( data . length ) ; for ( MapIterator it = mapIterator ( ) ; it . hasNext ( ) ; ) { out . writeObject ( it . next ( ) ) ; out . writeObject ( it . getValue ( ) ) ; } out . writeObject ( null ) ; // null terminate map // do not call super.doWriteObject() as code there doesn't work for // reference map }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Replaces the superclassm method to read the state of this class . <p / > Serialization is not one of the JDK s nicest topics . Normal serialization will initialise the superclass before the subclass . Sometimes however this isn t what you want as in this case the <code > put () < / code > method on read can be affected by subclass state . <p / > The solution adopted here is to deserialize the state data of this class in this protected method . This method must be called by the <code > readObject () < / code > of the first serializable subclass . <p / > Subclasses may override if the subclass has a specific field that must be present before <code > put () < / code > or <code > calculateThreshold () < / code > will work correctly . [CODESPLIT] protected void doReadObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { this . keyType = in . readInt ( ) ; this . valueType = in . readInt ( ) ; this . purgeValues = in . readBoolean ( ) ; this . loadFactor = in . readFloat ( ) ; int capacity = in . readInt ( ) ; init ( ) ; data = new HashEntry [ capacity ] ; while ( true ) { K key = ( K ) in . readObject ( ) ; if ( key == null ) { break ; } V value = ( V ) in . readObject ( ) ; put ( key , value ) ; } threshold = calculateThreshold ( data . length , loadFactor ) ; // do not call super.doReadObject() as code there doesn't work for // reference map }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Controls whether the fired Event should be dispatched to all the listeners . This method should execute quickly [CODESPLIT] @ Override public boolean controlEvents ( EventModel eventModel ) { if ( level . compareTo ( PresenceIndicatorLevel . WEAK ) >= 0 ) { return present ; } else //noinspection SimplifiableIfStatement if ( level . compareTo ( PresenceIndicatorLevel . WEAK ) < 0 && mostVague . get ( ) ) { return present ; } else { return true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "sets the presence [CODESPLIT] public void setPresence ( boolean present ) { if ( this . present == present ) return ; this . present = present ; updateVague ( ) ; if ( present ) { firePresence ( true ) ; } else { fireLeaving ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "updates the boolean whether it is the mode vague [CODESPLIT] private void updateVague ( ) { generateResource ( PresenceResource . ID ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenAccept ( list -> mostVague . set ( list . stream ( ) . map ( Presence :: importPresence ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . map ( Presence :: getLevel ) . noneMatch ( level -> level . compareTo ( getLevel ( ) ) > 0 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sends the specified text as a message to the other chat participant . This is a convenience method for : [CODESPLIT] public void sendMessage ( String text ) throws XMPPException { Message message = new Message ( ) ; message . setTo ( participant ) ; message . setType ( Type . chat ) ; message . setThread ( threadID ) ; message . setBody ( text ) ; chatManager . sendMessage ( this , message ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Delivers a message directly to this chat which will add the message to the collector and deliver it to all listeners registered with the Chat . This is used by the Connection class to deliver messages without a thread ID . [CODESPLIT] void deliver ( Message message ) { // Because the collector and listeners are expecting a thread ID with // a specific value, set the thread ID on the message even though it // probably never had one. message . setThread ( threadID ) ; for ( MessageListener listener : listeners ) { listener . processMessage ( this , message ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a script . [CODESPLIT] protected final ST generateScript ( String clazz , HashMap < String , Boolean > targetMap ) { ST ret = this . stg . getInstanceOf ( \"generateExec\" ) ; ret . add ( \"target\" , targetMap ) ; ret . add ( \"applicationHome\" , this . applicationDir ) ; ret . add ( \"runName\" , this . configuration . get ( PROP_RUN_SCRIPT_NAME ) ) ; ret . add ( \"class\" , clazz ) ; return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads and tests the configuration from configuration properties file . The default configuration file name is de / vandermeer / execs / configuration . properties . The file name can be overwritten using the -- property - file CLI option . The method will also test for some configuration keys to exist and fail if they are not defined . [CODESPLIT] protected final int initConfiguration ( ) { String propFile = this . optionPropFile . getValue ( ) ; this . configuration = this . loadProperties ( propFile ) ; if ( this . configuration == null ) { System . err . println ( this . getAppName ( ) + \": could not load configuration properties from file <\" + propFile + \">, exiting\" ) ; return - 1 ; } if ( this . configuration . get ( PROP_RUN_SCRIPT_NAME ) == null ) { System . err . println ( this . getAppName ( ) + \": configuration does not contain key <\" + PROP_RUN_SCRIPT_NAME + \">, exiting\" ) ; return - 1 ; } if ( this . configuration . get ( PROP_RUN_CLASS ) == null ) { System . err . println ( this . getAppName ( ) + \": configuration does not contain key <\" + PROP_RUN_CLASS + \">, exiting\" ) ; return - 1 ; } if ( this . configuration . get ( PROP_JAVA_CP ) == null ) { System . err . println ( this . getAppName ( ) + \": configuration does not contain key <\" + PROP_JAVA_CP + \">, exiting\" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + \": using configuration: \" ) ; System . out . println ( \"  - run script name: \" + this . configuration . get ( PROP_RUN_SCRIPT_NAME ) ) ; System . out . println ( \"  - run class      : \" + this . configuration . get ( PROP_RUN_CLASS ) ) ; System . out . println ( \"  - java cp        : \" + this . configuration . get ( PROP_JAVA_CP ) ) ; System . out . println ( \"  - auto-gen reg   : \" + this . configuration . get ( PROP_EXECS_AUTOGEN_REGISTERED ) ) ; for ( Object key : this . configuration . keySet ( ) ) { if ( StringUtils . startsWith ( key . toString ( ) , PROP_JAVAPROP_START ) ) { System . out . println ( \"  - java property  : \" + key + \" = \" + this . configuration . getProperty ( key . toString ( ) ) ) ; } } System . out . println ( ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets target for generation and initializes an STG object from an stg template file . The default template file name is de / vandermeer / execs / executable - script . stg . This default can be overwritten using the property stg . file in the configuration properties file . The default and the property file name can be overwritten using the -- stg - file CLI option . The set target ( CLI option -- target ) must be supported by the template file otherwise this method will fail . [CODESPLIT] protected final int initTargetAndStg ( ) { this . target = this . optionTarget . getValue ( ) ; if ( this . target == null ) { System . err . println ( this . getAppName ( ) + \": no target set\" ) ; return - 1 ; } String fileName = this . optionStgFile . getValue ( ) ; try { this . stg = new STGroupFile ( fileName ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + \": cannot load stg file <\" + fileName + \">, general exception\\n--> \" + e ) ; return - 1 ; } String [ ] availableTargets = null ; try { availableTargets = StringUtils . split ( this . stg . getInstanceOf ( \"supportedTargets\" ) . render ( ) , \" , \" ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + \": stg file <\" + fileName + \"> does not contain <supportedTargets> function\" ) ; return - 1 ; } if ( availableTargets . length == 0 ) { System . err . println ( this . getAppName ( ) + \": stg file <\" + fileName + \"> does not have a list of targets in <supportedTargets> function\" ) ; return - 1 ; } if ( ! ArrayUtils . contains ( availableTargets , this . target ) ) { System . err . println ( this . getAppName ( ) + \": target \" + this . target + \" not supported in stg file <\" + fileName + \">\" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + \": generating scripts for target: \" + this . target ) ; System . out . println ( ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initializes the application directory for the generator . There is no default set and no configuration property can be used . The application directory has to be set using the CLI option -- application - directory . Otherwise this method will fail . [CODESPLIT] protected final int initApplicationDir ( ) { this . applicationDir = this . optionAppHome . getValue ( ) ; if ( this . applicationDir == null ) { System . err . println ( this . getAppName ( ) + \": no application directory set\" ) ; return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads a classmap from a property file . A classmap maps class names to script names . A class name must be an implementation of the executable application interface { [CODESPLIT] protected final int initClassmap ( ) { this . optionClassMapFile . setPropertyValue ( this . configuration ) ; String fileName = this . optionClassMapFile . getValue ( ) ; if ( fileName == null ) { System . err . println ( this . getAppName ( ) + \": no classmap file name given\" ) ; return - 2 ; } this . classMap = this . loadProperties ( fileName ) ; if ( this . classMap == null ) { System . err . println ( this . getAppName ( ) + \": could not load classmap, exiting\" ) ; return - 1 ; } System . out . println ( this . getAppName ( ) + \": generating scripts for:\" ) ; for ( Object key : this . classMap . keySet ( ) ) { System . out . println ( \"  - \" + key + \" --> \" + this . classMap . getProperty ( key . toString ( ) ) ) ; } System . out . println ( ) ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests and if necessary creates an output directory . The root path is the current directory as given by the system property user . dir . The created output directory has the name of the specified target for the generator . The method fails if the output directory cannot be created or if it exists and is write protected . [CODESPLIT] protected final int initOutputDir ( ) { String parent = System . getProperty ( \"user.dir\" ) ; String target = parent + File . separator + this . target ; File targetDir = new File ( target ) ; File parentDir = targetDir . getParentFile ( ) ; if ( targetDir . exists ( ) ) { //target dir exists, let's see if it is what we want it to be if ( ! targetDir . isDirectory ( ) ) { System . err . println ( this . getAppName ( ) + \": target dir <\" + target + \"> exists but is not a directory, exiting\" ) ; return - 1 ; } if ( ! targetDir . canWrite ( ) ) { System . err . println ( this . getAppName ( ) + \": target dir <\" + target + \"> exists but but cannot write into it, exiting\" ) ; return - 1 ; } } else { //target dir does not exist, let's see if we can create it the way we need if ( ! parentDir . isDirectory ( ) ) { System . err . println ( this . getAppName ( ) + \": target dir parent <\" + parent + \"> exists but is not a directory, exiting\" ) ; return - 1 ; } if ( ! parentDir . canWrite ( ) ) { System . err . println ( this . getAppName ( ) + \": target dir parent <\" + parent + \"> exists but but cannot write into it, exiting\" ) ; return - 1 ; } if ( ! targetDir . mkdir ( ) ) { System . err . println ( this . getAppName ( ) + \": could not create target dir <\" + target + \">, exiting\" ) ; return - 1 ; } } this . outputDir = target ; return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Loads properties from a file . [CODESPLIT] protected final Properties loadProperties ( String filename ) { Properties ret = new Properties ( ) ; URL url = null ; File f = new File ( filename . toString ( ) ) ; if ( f . exists ( ) ) { try { url = f . toURI ( ) . toURL ( ) ; } catch ( Exception ignore ) { } } else { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; url = loader . getResource ( filename ) ; if ( url == null ) { loader = Gen_RunScripts . class . getClassLoader ( ) ; url = loader . getResource ( filename ) ; } } try { ret . load ( url . openStream ( ) ) ; } catch ( IOException e ) { System . err . println ( this . getAppName ( ) + \": cannot load property file <\" + filename + \">, IO exception\\n--><\" + e + \">\" ) ; } catch ( Exception e ) { System . err . println ( this . getAppName ( ) + \": cannot load property file <\" + filename + \">, general exception\\n--><\" + e + \">\" ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes an ST object to a file . [CODESPLIT] protected final int writeFile ( String fn , ST st ) { try { FileWriter fs = new FileWriter ( fn ) ; BufferedWriter bw = new BufferedWriter ( fs ) ; bw . write ( st . render ( ) ) ; bw . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return - 1 ; } return 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the first Progress if found in the EventModel [CODESPLIT] public static Optional < Progress > getProgress ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . findAny ( ) . flatMap ( Progress :: importResource ) ; } else { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized collection . [CODESPLIT] public static < E > Collection < E > decorate ( Collection < E > coll ) { return new SynchronizedCollection < E > ( coll ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public boolean add ( final E object ) { Boolean ret = SyncUtils . synchronizeWrite ( lock , new Callback < Boolean > ( ) { @ Override protected void doAction ( ) { _return ( collection . add ( object ) ? Boolean . TRUE : Boolean . FALSE ) ; } } ) ; return ret . booleanValue ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Discover FireREST services located in a range of IPv4 InetAddresses . E . g . The range of 256 addresses that starts with 10 . 0 . 1 . 128 ends with 10 . 0 . 2 . 127 . [CODESPLIT] public static Collection < ServiceResolver > discover ( InetAddress start , int count , int msTimeout ) { Collection < ServiceResolver > result = new ArrayList < ServiceResolver > ( ) ; Collection < InetAddress > hosts = IPv4Scanner . scanRange ( start , count , msTimeout ) ; for ( InetAddress host : hosts ) { ServiceResolver resolver = new ServiceResolver ( host ) ; logger . info ( \"resolving {} {}\" , host . getHostAddress ( ) , host . getCanonicalHostName ( ) ) ; JSONResult config = resolver . getConfig ( ) ; if ( config != null ) { result . add ( resolver ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "( Re - ) discover the service configuration [CODESPLIT] public void resolve ( ) { attempts ++ ; config = null ; Exception caughtException = null ; String host = address == null ? \"null\" : address . getCanonicalHostName ( ) ; if ( url == null ) { URL attemptUrl = null ; int [ ] ports = { 8080 , 80 } ; for ( int i = 0 ; i < ports . length ; i ++ ) { try { attemptUrl = new URL ( \"http\" , host , ports [ i ] , \"/firerest/config.json\" ) ; break ; } catch ( Exception e ) { attemptUrl = null ; caughtException = e ; } } if ( attemptUrl == null ) { throw new FireRESTException ( \"Could not resolve service at \" + host , caughtException ) ; } url = attemptUrl ; } if ( config == null ) { logger . info ( \"Resolving {}\" , url ) ; config = new FireREST ( ) . withTimeout ( msTimeout ) . getJSON ( url ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return the cached service configuration resolving the service if required . [CODESPLIT] public JSONResult getConfig ( ) { if ( attempts == 0 ) { try { resolve ( ) ; } catch ( Exception e ) { // discard exception } } if ( config == null ) { logger . info ( \"{} => no response\" , url ) ; return null ; } logger . info ( \"{} => {}\" , url , config . get ( \"FireREST\" ) . getString ( ) ) ; return config ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------------------- [CODESPLIT] @ Override public void invalidate ( String keySpace , String columnFamily , Map < String , Object > queryProperties ) { Map < String , CacheHolder > queryCache = client . getQueryCache ( ) ; if ( queryCache == null ) { return ; } String cacheKey = getCacheKey ( keySpace , columnFamily , queryProperties ) ; if ( cacheKey != null ) { LOGGER . debug ( \"Removing Cached Query {} \" , cacheKey ) ; queryCache . remove ( cacheKey ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the map of String key / value pairs of account attributes . [CODESPLIT] @ SuppressWarnings ( \"unchecked\" ) public Map < String , String > getAttributes ( ) { Map < String , String > attributes = null ; List < Element > elements = queryEl . elements ( ) ; for ( Element element : elements ) { if ( ! element . getName ( ) . equals ( \"instructions\" ) ) { if ( attributes == null ) { attributes = new HashMap < String , String > ( ) ; } attributes . put ( element . getName ( ) , element . getText ( ) ) ; } } return attributes ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the account attributes . The map must only contain String key / value pairs . [CODESPLIT] public void setAttributes ( Map < String , String > attributes ) { for ( Entry < String , String > attribute : attributes . entrySet ( ) ) { PacketParserUtils . updateText ( queryEl , attribute . getKey ( ) , attribute . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the API used to manage the ThreadPool [CODESPLIT] @ Override public org . intellimate . izou . sdk . specification . context . ThreadPool getThreadPool ( ) { return threadPool ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StopRequest [CODESPLIT] public static Optional < StopMusic > createStopMusic ( Identification source , Identification target ) { if ( target == null || target . equals ( source ) ) return Optional . empty ( ) ; try { StopMusic stopRequest = new StopMusic ( source ) ; stopRequest . addResource ( new SelectorResource ( source , target ) ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "verifies that the StopMusicRequest is correct and checks whether the you are meant to react to it [CODESPLIT] public static boolean verify ( EventModel eventModel , Identifiable player ) { if ( ! eventModel . containsDescriptor ( StopMusic . ID ) ) return false ; return SelectorResource . isTarget ( eventModel , player ) . orElse ( true ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected DseCluster createCluster ( ClusterIdentifier ci ) { return DseUtils . newDseCluster ( ci . hostsAndPorts , ci . username , ci . password , ci . authorizationId , getConfiguration ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override protected DseSession createSession ( Cluster cluster , String keyspace ) { return DseUtils . newDseSession ( ( DseCluster ) cluster , keyspace ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public DseCluster getCluster ( String hostsAndPorts , String username , String password ) { return getCluster ( hostsAndPorts , username , password , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a DSE cluster instance . [CODESPLIT] public DseCluster getCluster ( String hostsAndPorts , String username , String password , String authorizationId ) { return getCluster ( ClusterIdentifier . getInstance ( hostsAndPorts , username , password , authorizationId ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override synchronized protected DseSession getSession ( SessionIdentifier si , boolean forceNew ) { return ( DseSession ) super . getSession ( si , forceNew ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public DseSession getSession ( String hostsAndPorts , String username , String password , String keyspace ) { return getSession ( hostsAndPorts , username , password , null , keyspace , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a DSE session instance . [CODESPLIT] public DseSession getSession ( String hostsAndPorts , String username , String password , String authorizationId , String keyspace ) { return getSession ( hostsAndPorts , username , password , authorizationId , keyspace , false ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Obtain a DSE session instance . [CODESPLIT] public DseSession getSession ( String hostsAndPorts , String username , String password , String authorizationId , String keyspace , boolean forceNew ) { return getSession ( SessionIdentifier . getInstance ( hostsAndPorts , username , password , authorizationId , keyspace ) , forceNew ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public DseSession getSession ( boolean forceNew ) { return getSession ( getDefaultHostsAndPorts ( ) , getDefaultUsername ( ) , getDefaultPassword ( ) , defaultAuthorizationId , getDefaultKeyspace ( ) , forceNew ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a connection listener to this connection that will be notified when the connection closes or fails . [CODESPLIT] public void addConnectionListener ( ConnectionListener connectionListener ) { if ( connectionListener == null ) { return ; } if ( ! connectionListeners . contains ( connectionListener ) ) { connectionListeners . add ( connectionListener ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new packet collector for this connection . A packet filter determines which packets will be accumulated by the collector . A PacketCollector is more suitable to use than a { @link PacketListener } when you need to wait for a specific result . [CODESPLIT] public PacketCollector createPacketCollector ( PacketFilter packetFilter ) { PacketCollector collector = new PacketCollector ( this , packetFilter ) ; // Add the collector to the list of active collectors. collectors . add ( collector ) ; return collector ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a packet listener with this connection . A packet listener will be invoked only when an incoming packet is received . A packet filter determines which packets will be delivered to the listener . If the same packet listener is added again with a different filter only the new filter will be used . [CODESPLIT] public void addPacketListener ( PacketListener packetListener , PacketFilter packetFilter ) { if ( packetListener == null ) { throw new NullPointerException ( \"Packet listener is null.\" ) ; } ListenerWrapper wrapper = new ListenerWrapper ( packetListener , packetFilter ) ; recvListeners . put ( packetListener , wrapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a packet listener with this connection . The listener will be notified of every packet that this connection sends . A packet filter determines which packets will be delivered to the listener . Note that the thread that writes packets will be used to invoke the listeners . Therefore each packet listener should complete all operations quickly or use a different thread for processing . [CODESPLIT] public void addPacketSendingListener ( PacketListener packetListener , PacketFilter packetFilter ) { if ( packetListener == null ) { throw new NullPointerException ( \"Packet listener is null.\" ) ; } ListenerWrapper wrapper = new ListenerWrapper ( packetListener , packetFilter ) ; sendListeners . put ( packetListener , wrapper ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process all packet listeners for sending packets . [CODESPLIT] protected void firePacketSendingListeners ( Packet packet ) { // Notify the listeners of the new sent packet for ( ListenerWrapper listenerWrapper : sendListeners . values ( ) ) { listenerWrapper . notifyListener ( packet ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Registers a packet interceptor with this connection . The interceptor will be invoked every time a packet is about to be sent by this connection . Interceptors may modify the packet to be sent . A packet filter determines which packets will be delivered to the interceptor . [CODESPLIT] public void addPacketInterceptor ( PacketInterceptor packetInterceptor , PacketFilter packetFilter ) { if ( packetInterceptor == null ) { throw new NullPointerException ( \"Packet interceptor is null.\" ) ; } interceptors . put ( packetInterceptor , new InterceptorWrapper ( packetInterceptor , packetFilter ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Process interceptors . Interceptors may modify the packet that is about to be sent . Since the thread that requested to send the packet will invoke all interceptors it is important that interceptors perform their work as soon as possible so that the thread does not remain blocked for a long period . [CODESPLIT] protected void firePacketInterceptors ( Packet packet ) { if ( packet != null ) { for ( InterceptorWrapper interceptorWrapper : interceptors . values ( ) ) { interceptorWrapper . notifyListener ( packet ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Initialize the { @link #debugger } . You can specify a customized { @link SmackDebugger } by setup the system property <code > smack . debuggerClass< / code > to the implementation . [CODESPLIT] protected void initDebugger ( ) { if ( reader == null || writer == null ) { throw new NullPointerException ( \"Reader or writer isn't initialized.\" ) ; } // If debugging is enabled, we open a window and write out all network // traffic. if ( config . isDebuggerEnabled ( ) ) { if ( debugger == null ) { // Detect the debugger class to use. String className = null ; // Use try block since we may not have permission to get a // system // property (for example, when an applet). try { className = System . getProperty ( \"smack.debuggerClass\" ) ; } catch ( Throwable t ) { // Ignore. } Class < ? > debuggerClass = null ; if ( className != null ) { try { debuggerClass = Class . forName ( className ) ; } catch ( Exception e ) { log . warn ( \"Unabled to instantiate debugger class \" + className ) ; } } if ( debuggerClass == null ) { try { debuggerClass = Class . forName ( \"org.jivesoftware.smackx.debugger.EnhancedDebugger\" ) ; } catch ( Exception ex ) { try { debuggerClass = Class . forName ( \"org.jivesoftware.smack.debugger.LiteDebugger\" ) ; } catch ( Exception ex2 ) { log . warn ( \"Unabled to instantiate either Smack debugger class\" ) ; } } } // Create a new debugger instance. If an exception occurs then // disable the debugging // option try { Constructor < ? > constructor = debuggerClass . getConstructor ( Connection . class , Writer . class , Reader . class ) ; debugger = ( SmackDebugger ) constructor . newInstance ( this , writer , reader ) ; reader = debugger . getReader ( ) ; writer = debugger . getWriter ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( \"Can't initialize the configured debugger!\" , e ) ; } } else { // Obtain new reader and writer from the existing debugger reader = debugger . newConnectionReader ( reader ) ; writer = debugger . newConnectionWriter ( writer ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates the most suitable type . [CODESPLIT] public static Object toValue ( String name , Object value ) { String [ ] parts = StringUtils . split ( name , \"@\" , 2 ) ; String fieldName = null ; String fieldType = \"String\" ; if ( parts . length == 2 ) { fieldType = parts [ 1 ] ; fieldName = parts [ 0 ] ; } else if ( parts . length == 1 ) { fieldName = parts [ 0 ] ; } else { throw new IllegalArgumentException ( \"Invalid property name\" ) ; } try { int l = Array . getLength ( value ) ; RequestParameterType < ? > rpt = TYPES . get ( fieldType ) ; if ( rpt == null ) { rpt = TYPES . get ( RequestParameterType . STRING ) ; } if ( ! fieldName . endsWith ( \"[]\" ) && l == 1 ) { return rpt . newInstance ( Array . get ( value , 0 ) ) ; } Class < ? > componentType = rpt . getComponentType ( ) ; Object [ ] a = ( Object [ ] ) Array . newInstance ( componentType , l ) ; for ( int i = 0 ; i < l ; i ++ ) { a [ i ] = rpt . newInstance ( Array . get ( value , i ) ) ; } return a ; } catch ( IllegalArgumentException e ) { RequestParameterType < ? > rpt = TYPES . get ( fieldType ) ; if ( rpt == null ) { rpt = TYPES . get ( RequestParameterType . STRING ) ; } return rpt . newInstance ( value ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Generates a connection with the server and tries to authenticate . If an error occurs in any of the steps then a ComponentException is thrown . [CODESPLIT] public void connect ( String host , int port , String subdomain ) throws ComponentException { try { // Open a socket to the server this . socket = new Socket ( ) ; socket . connect ( new InetSocketAddress ( host , port ) , manager . getConnectTimeout ( ) ) ; if ( manager . getServerName ( ) != null ) { this . domain = subdomain + \".\" + manager . getServerName ( ) ; } else { this . domain = subdomain ; } this . subdomain = subdomain ; // Keep these variables that will be used in case a reconnection is // required this . host = host ; this . port = port ; try { factory = XmlPullParserFactory . newInstance ( ) ; reader = new XPPPacketReader ( ) ; reader . setXPPFactory ( factory ) ; reader . getXPPParser ( ) . setInput ( new InputStreamReader ( socket . getInputStream ( ) , CHARSET ) ) ; // Get a writer for sending the open stream tag writer = new BufferedWriter ( new OutputStreamWriter ( socket . getOutputStream ( ) , CHARSET ) ) ; // Open the stream. StringBuilder stream = new StringBuilder ( ) ; stream . append ( \"<stream:stream\" ) ; stream . append ( \" xmlns=\\\"jabber:component:accept\\\"\" ) ; stream . append ( \" xmlns:stream=\\\"http://etherx.jabber.org/streams\\\"\" ) ; if ( manager . isMultipleAllowed ( subdomain ) ) { stream . append ( \" allowMultiple=\\\"true\\\"\" ) ; } stream . append ( \" to=\\\"\" ) . append ( domain ) . append ( \"\\\">\" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; stream = null ; // Get the answer from the server XmlPullParser xpp = reader . getXPPParser ( ) ; for ( int eventType = xpp . getEventType ( ) ; eventType != XmlPullParser . START_TAG ; ) { eventType = xpp . next ( ) ; } // Set the streamID returned from the server connectionID = xpp . getAttributeValue ( \"\" , \"id\" ) ; if ( xpp . getAttributeValue ( \"\" , \"from\" ) != null ) { this . domain = xpp . getAttributeValue ( \"\" , \"from\" ) ; } xmlSerializer = new XMLWriter ( writer ) ; // Handshake with the server stream = new StringBuilder ( ) ; stream . append ( \"<handshake>\" ) ; stream . append ( StringUtils . hash ( connectionID + manager . getSecretKey ( subdomain ) ) ) ; stream . append ( \"</handshake>\" ) ; writer . write ( stream . toString ( ) ) ; writer . flush ( ) ; stream = null ; // Get the answer from the server try { Element doc = reader . parseDocument ( ) . getRootElement ( ) ; if ( \"error\" . equals ( doc . getName ( ) ) ) { StreamError error = new StreamError ( doc ) ; // Close the connection socket . close ( ) ; socket = null ; // throw the exception with the wrapped error throw new ComponentException ( error ) ; } // Everything went fine // Start keep alive thread to send every 30 seconds of // inactivity a heart beat keepAliveTask = new KeepAliveTask ( ) ; TaskEngine . getInstance ( ) . scheduleAtFixedRate ( keepAliveTask , 15000 , 30000 ) ; timeoutTask = new TimeoutTask ( ) ; TaskEngine . getInstance ( ) . scheduleAtFixedRate ( timeoutTask , 2000 , 2000 ) ; } catch ( DocumentException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing } throw new ComponentException ( e ) ; } catch ( XmlPullParserException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing } throw new ComponentException ( e ) ; } } catch ( XmlPullParserException e ) { try { socket . close ( ) ; } catch ( IOException ioe ) { // Do nothing } throw new ComponentException ( e ) ; } } catch ( UnknownHostException uhe ) { try { if ( socket != null ) socket . close ( ) ; } catch ( IOException e ) { // Do nothing } throw new ComponentException ( uhe ) ; } catch ( IOException ioe ) { try { if ( socket != null ) socket . close ( ) ; } catch ( IOException e ) { // Do nothing } throw new ComponentException ( ioe ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notification message that the connection with the server was lost unexpectedly . We will try to reestablish the connection for ever until the connection has been reestablished or this thread has been stopped . [CODESPLIT] public void connectionLost ( ) { // Ensure that only one thread will try to reconnect. synchronized ( this ) { if ( reconnecting ) { return ; } reconnecting = true ; } readerThread = null ; boolean isConnected = false ; if ( ! shutdown ) { // Notify the component that connection was lost so it needs to // shutdown. The component is // still registered in the local component manager but just not // connected to the server component . shutdown ( ) ; } while ( ! isConnected && ! shutdown ) { try { connect ( host , port , subdomain ) ; isConnected = true ; // It may be possible that while a new connection was being // established the // component was required to shutdown so in this case we need to // close the new // connection if ( shutdown ) { disconnect ( ) ; } else { // Component is back again working so start it up again start ( ) ; } } catch ( ComponentException e ) { manager . getLog ( ) . error ( \"Error trying to reconnect with the server\" , e ) ; // Wait for 5 seconds until the next retry try { Thread . sleep ( 5000 ) ; } catch ( InterruptedException e1 ) { // Do nothing } } } reconnecting = false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds an { @link IQResultListener } that will be invoked when an IQ result is sent to the server itself and is of type result or error . This is a nice way for the server to send IQ packets to other XMPP entities and be waked up when a response is received back . <p > [CODESPLIT] void addIQResultListener ( String id , IQResultListener listener , long timeoutmillis ) { // be generated by the server and simulate like the client sent it. This // will let listeners // react and be removed from the collection resultListeners . put ( id , listener ) ; resultTimeout . put ( id , System . currentTimeMillis ( ) + timeoutmillis ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Rolls back the changes to the map . [CODESPLIT] public void rollback ( ) { if ( auto_commit ) return ; String id = getCurrentThreadId ( ) ; ArrayList < Entry < K , V > > list = new ArrayList < Entry < K , V > > ( allEntrySet ( ) ) ; for ( Iterator < Entry < K , V >> i = list . iterator ( ) ; i . hasNext ( ) ; ) { final Node < K , V > node = ( Node < K , V > ) i . next ( ) ; if ( node . is ( Node . ADDED , id ) ) { doRedBlackDelete ( node ) ; if ( rollback_notifiers != null ) { SyncUtils . synchronizeRead ( rollback_notifiers , new Callback ( ) { @ Override protected void doAction ( ) { for ( Iterator i2 = rollback_notifiers . iterator ( ) ; i2 . hasNext ( ) ; )  ( ( TransactionNotifiable ) i2 . next ( ) ) . removedFromMap ( node . getKey ( ) , node . getValue ( ) ) ; } } ) ; } } if ( node . is ( Node . DELETED , id ) ) { node . setStatus ( Node . NO_CHANGE , null ) ; if ( rollback_notifiers != null ) { SyncUtils . synchronizeRead ( rollback_notifiers , new Callback ( ) { @ Override protected void doAction ( ) { for ( Iterator i2 = rollback_notifiers . iterator ( ) ; i2 . hasNext ( ) ; )  ( ( TransactionNotifiable ) i2 . next ( ) ) . addedToMap ( node . getKey ( ) , node . getValue ( ) ) ; } } ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Retrieve the current thread id for use by the transaction code . [CODESPLIT] protected String getCurrentThreadId ( ) { String attach_id = ( String ) ThreadSession . getValue ( getThreadSessionKey ( ) ) ; if ( attach_id != null ) return attach_id ; Thread thread = Thread . currentThread ( ) ; return thread . toString ( ) + \"(\" + thread . hashCode ( ) + \")\" ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks that this node is valid for the current thread [CODESPLIT] private boolean validNode ( final Node < K , V > node , final String thread_id ) { if ( auto_commit || node == null ) return ( node != null ) ; return ! ( ( node . is ( Node . DELETED , thread_id ) ) || ( node . is ( Node . ADDED , null ) && node . is ( Node . NO_CHANGE , thread_id ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the key to which this map maps the specified value . Returns null if the map contains no mapping for this value . [CODESPLIT] public K getKeyForValue ( final Object value ) throws ClassCastException , NullPointerException { return ( K ) doGet ( value , VALUE ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set view of the mappings contained in this map . Each element in the returned set is a Map . Entry . The set is backed by the map so changes to the map are reflected in the set and vice - versa . If the map is modified while an iteration over the set is in progress the results of the iteration are undefined . The set supports element removal which removes the corresponding mapping from the map via the Iterator . remove Set . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . <p > [CODESPLIT] public FilterableSet < Entry < K , V > > entrySetByValueDescending ( ) { return new AbstractFilterableSet < Entry < K , V > > ( ) { @ Override public Iterator < Entry < K , V > > iterator ( ) { return new TransactionalBidiTreeMapDescendingIterator < Entry < K , V > > ( VALUE ) { @ Override protected Entry < K , V > doGetNext ( ) { return lastReturnedNode ; } } ; } @ Override public boolean contains ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object key = entry . getKey ( ) ; Node < K , V > node = lookupValid ( entry . getValue ( ) , VALUE , getCurrentThreadId ( ) ) ; return ( node != null ) && node . getData ( KEY ) . equals ( key ) ; } @ Override public boolean remove ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } String thread_id = getCurrentThreadId ( ) ; Map . Entry < K , V > entry = ( Map . Entry < K , V > ) o ; Object key = entry . getKey ( ) ; Node < K , V > node = lookupValid ( entry . getValue ( ) , VALUE , thread_id ) ; if ( ( node != null ) && node . getData ( KEY ) . equals ( key ) ) { if ( auto_commit || node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else node . setStatus ( Node . DELETED , thread_id ) ; return true ; } return false ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set view of the keys contained in this map . The set is backed by the map so changes to the map are reflected in the set and vice - versa . If the map is modified while an iteration over the set is in progress the results of the iteration are undefined . The set supports element removal which removes the corresponding mapping from the map via the Iterator . remove Set . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . <p > [CODESPLIT] public FilterableSet < K > keySetByValue ( ) { if ( setOfKeysByValue == null ) { setOfKeysByValue = new AbstractFilterableSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new TransactionalBidiTreeMapIterator < K > ( VALUE ) { @ Override protected K doGetNext ( ) { return ( K ) lastReturnedNode . getData ( KEY ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsKey ( o ) ; } @ Override public boolean remove ( Object o ) { int oldnodeCount = nodeCount ; TransactionalBidiTreeMap . this . remove ( o ) ; return nodeCount != oldnodeCount ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfKeysByValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection view of the values contained in this map . The collection is backed by the map so changes to the map are reflected in the collection and vice - versa . If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined . The collection supports element removal which removes the corresponding mapping from the map via the Iterator . remove Collection . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . <p > [CODESPLIT] public FilterableCollection < V > valuesByValue ( ) { if ( collectionOfValuesByValue == null ) { collectionOfValuesByValue = new AbstractFilterableCollection < V > ( ) { @ Override public Iterator < V > iterator ( ) { return new TransactionalBidiTreeMapIterator < V > ( VALUE ) { @ Override protected V doGetNext ( ) { return ( V ) lastReturnedNode . getData ( VALUE ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsValue ( o ) ; } @ Override public boolean remove ( Object o ) { int oldnodeCount = nodeCount ; removeValue ( o ) ; return nodeCount != oldnodeCount ; } @ Override public boolean removeAll ( Collection < ? > c ) { boolean modified = false ; Iterator < ? > iter = c . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( removeValue ( iter . next ( ) ) != null ) { modified = true ; } } return modified ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return collectionOfValuesByValue ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "common remove logic ( remove by key or remove by value ) [CODESPLIT] private Object doRemove ( final Object o , final int index ) throws ConcurrentModificationException { checkNonNullComparable ( o , index ) ; String thread_id = getCurrentThreadId ( ) ; Node < K , V > node = lookupValid ( o , index , thread_id ) ; Object rval = null ; if ( validNode ( node , thread_id ) ) { if ( node != null && node . is ( Node . DELETED , null ) && ! node . is ( Node . DELETED , thread_id ) ) throw new ConcurrentModificationException ( ) ; rval = node . getData ( oppositeIndex ( index ) ) ; if ( auto_commit || node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else { node . setStatus ( Node . DELETED , thread_id ) ; } } return rval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "common get logic used to get by key or get by value [CODESPLIT] private Object doGet ( final Object o , final int index ) { checkNonNullComparable ( o , index ) ; Node < K , V > node = lookupValid ( o , index , getCurrentThreadId ( ) ) ; return ( node == null ) ? null : node . getData ( oppositeIndex ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "do the actual lookup of a piece of valid data [CODESPLIT] private Node < K , V > lookupValid ( final Object data , final int index , final String thread_id ) { return nextEqualValid ( getFloorEqualNode ( lookup ( data , index ) , index ) , index , thread_id ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "do the actual lookup of a piece of data [CODESPLIT] private Node < K , V > lookup ( final Object data , final int index ) { Node < K , V > rval = null ; Node < K , V > node = rootNode [ index ] ; while ( node != null ) { int cmp = compare ( Node . NO_CHANGE , data , node . getStatus ( ) , node . getData ( index ) , index ) ; if ( cmp == 0 ) { rval = node ; break ; } else { node = ( cmp < 0 ) ? node . getLeft ( index ) : node . getRight ( index ) ; } } return rval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compare two objects [CODESPLIT] private int compare ( final int o1_status , final Object o1 , final int o2_status , final Object o2 , final int index ) { if ( comparators [ index ] == null ) { if ( o1 instanceof TransactionalComparable ) return ( ( TransactionalComparable ) o1 ) . compareTo ( o1_status , o2 , o2_status ) ; else return ( ( Comparable ) o1 ) . compareTo ( o2 ) ; } else { return comparators [ index ] . compare ( o1 , o2 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the least node from a given node . very useful for starting a sorting iterator ... [CODESPLIT] private Node < K , V > leastNode ( final Node < K , V > node , final int index ) { Node < K , V > lval = node ; if ( lval != null ) { while ( lval . getLeft ( index ) != null ) { lval = lval . getLeft ( index ) ; } } return lval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the most node from a given node . [CODESPLIT] private Node < K , V > mostNode ( final Node < K , V > node , final int index ) { Node < K , V > rval = node ; if ( rval != null ) { while ( rval . getRight ( index ) != null ) { rval = rval . getRight ( index ) ; } } return rval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the next larger node from the specified node [CODESPLIT] private Node < K , V > nextGreater ( final Node < K , V > node , final int index ) { Node < K , V > rval ; if ( node == null ) { rval = null ; } else if ( node . getRight ( index ) != null ) { // everything to the node's right is larger. The least of\r // the right node's descendants is the next larger node\r rval = leastNode ( node . getRight ( index ) , index ) ; } else { // traverse up our ancestry until we find an ancestor that\r // is null or one whose left child is our ancestor. If we\r // find a null, then this node IS the largest node in the\r // tree, and there is no greater node. Otherwise, we are\r // the largest node in the subtree on that ancestor's left\r // ... and that ancestor is the next greatest node\r Node < K , V > parent = node . getParent ( index ) ; Node < K , V > child = node ; while ( ( parent != null ) && ( child == parent . getRight ( index ) ) ) { child = parent ; parent = parent . getParent ( index ) ; } rval = parent ; } return rval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the next smaller ( previous ) node from the specified node [CODESPLIT] private Node < K , V > nextSmaller ( final Node < K , V > node , final int index ) { Node < K , V > lval ; if ( node == null ) { lval = null ; } else if ( node . getLeft ( index ) != null ) { // everything to the node's left is smaller. The most of\r // the right node's descendants is the next smaller node\r lval = mostNode ( node . getLeft ( index ) , index ) ; } else { // traverse up our ancestry until we find an ancestor that\r // is null or one whose right child is our ancestor. If we\r // find a null, then this node IS the smallest node in the\r // tree, and there is no smaller node. Otherwise, we are\r // the smallest node in the subtree on that ancestor's right\r // ... and that ancestor is the next smallest node\r Node < K , V > parent = node . getParent ( index ) ; Node < K , V > child = node ; while ( ( parent != null ) && ( child == parent . getLeft ( index ) ) ) { child = parent ; parent = parent . getParent ( index ) ; } lval = parent ; } return lval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get the most valid node from the specified node [CODESPLIT] private Node < K , V > mostValidNode ( final Node < K , V > node , final int index , final String thread_id ) { Node < K , V > rval = node ; while ( rval != null && ! validNode ( rval , thread_id ) ) { rval = nextGreater ( rval , index ) ; } return rval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "find the least valid node from a given node . very useful for starting a sorting iterator ... [CODESPLIT] private Node < K , V > leastValidNode ( final Node < K , V > node , final int index , final String thread_id ) { Node < K , V > lval = node ; while ( lval != null && ! validNode ( lval , thread_id ) ) { lval = nextSmaller ( lval , index ) ; } return lval ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "copy the color from one node to another dealing with the fact that one or both nodes may in fact be null [CODESPLIT] private static < K , V > void copyColor ( final Node < K , V > from , final Node < K , V > to , final int index ) { if ( to != null ) { if ( from == null ) { // by default, make it black\r to . setBlack ( index ) ; } else { to . copyColor ( from , index ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is the specified node red? if the node does not exist no it s black thank you [CODESPLIT] private static < K , V > boolean isRed ( final Node < K , V > node , final int index ) { return ( ( node == null ) ? false : node . isRed ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is the specified black red? if the node does not exist sure it s black thank you [CODESPLIT] private static < K , V > boolean isBlack ( final Node < K , V > node , final int index ) { return ( ( node == null ) ? true : node . isBlack ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "force a node ( if it exists ) red [CODESPLIT] private static < K , V > void makeRed ( final Node < K , V > node , final int index ) { if ( node != null ) { node . setRed ( index ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "force a node ( if it exists ) black [CODESPLIT] private static < K , V > void makeBlack ( final Node < K , V > node , final int index ) { if ( node != null ) { node . setBlack ( index ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a node s grandparent . mind you the node its parent or its grandparent may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getGrandParent ( final Node < K , V > node , final int index ) { return getParent ( getParent ( node , index ) , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a node s parent . mind you the node or its parent may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getParent ( final Node < K , V > node , final int index ) { return ( ( node == null ) ? null : node . getParent ( index ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a node s right child . mind you the node may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getRightChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? null : node . getRight ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "get a node s left child . mind you the node may not exist . no problem [CODESPLIT] private static < K , V > Node < K , V > getLeftChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? null : node . getLeft ( index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is this node its parent s left child? mind you the node or its parent may not exist . no problem . if the node doesn t exist ... it s its non - existent parent s left child . If the node does exist but has no parent ... no we re not the non - existent parent s left child . Otherwise ( both the specified node AND its parent exist ) check . [CODESPLIT] private static < K , V > boolean isLeftChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? true : ( ( node . getParent ( index ) == null ) ? false : ( node == node . getParent ( index ) . getLeft ( index ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "is this node its parent s right child? mind you the node or its parent may not exist . no problem . if the node doesn t exist ... it s its non - existent parent s right child . If the node does exist but has no parent ... no we re not the non - existent parent s right child . Otherwise ( both the specified node AND its parent exist ) check . [CODESPLIT] private static < K , V > boolean isRightChild ( final Node < K , V > node , final int index ) { return ( node == null ) ? true : ( ( node . getParent ( index ) == null ) ? false : ( node == node . getParent ( index ) . getRight ( index ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "do a rotate left . standard fare in the world of balanced trees [CODESPLIT] private void rotateLeft ( final Node < K , V > node , final int index ) { Node < K , V > rightChild = node . getRight ( index ) ; node . setRight ( rightChild . getLeft ( index ) , index ) ; if ( rightChild . getLeft ( index ) != null ) { rightChild . getLeft ( index ) . setParent ( node , index ) ; } rightChild . setParent ( node . getParent ( index ) , index ) ; if ( node . getParent ( index ) == null ) { // node was the root ... now its right child is the root\r rootNode [ index ] = rightChild ; } else if ( node . getParent ( index ) . getLeft ( index ) == node ) { node . getParent ( index ) . setLeft ( rightChild , index ) ; } else { node . getParent ( index ) . setRight ( rightChild , index ) ; } rightChild . setLeft ( node , index ) ; node . setParent ( rightChild , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "do a rotate right . standard fare in the world of balanced trees [CODESPLIT] private void rotateRight ( final Node < K , V > node , final int index ) { Node < K , V > leftChild = node . getLeft ( index ) ; node . setLeft ( leftChild . getRight ( index ) , index ) ; if ( leftChild . getRight ( index ) != null ) { leftChild . getRight ( index ) . setParent ( node , index ) ; } leftChild . setParent ( node . getParent ( index ) , index ) ; if ( node . getParent ( index ) == null ) { // node was the root ... now its left child is the root\r rootNode [ index ] = leftChild ; } else if ( node . getParent ( index ) . getRight ( index ) == node ) { node . getParent ( index ) . setRight ( leftChild , index ) ; } else { node . getParent ( index ) . setLeft ( leftChild , index ) ; } leftChild . setRight ( node , index ) ; node . setParent ( leftChild , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "complicated red - black insert stuff . Based on Sun s TreeMap implementation though it s barely recognizable any more [CODESPLIT] private void doRedBlackInsert ( final Node < K , V > insertedNode , final int index ) { Node < K , V > currentNode = insertedNode ; makeRed ( currentNode , index ) ; while ( ( currentNode != null ) && ( currentNode != rootNode [ index ] ) && ( isRed ( currentNode . getParent ( index ) , index ) ) ) { if ( isLeftChild ( getParent ( currentNode , index ) , index ) ) { Node < K , V > y = getRightChild ( getGrandParent ( currentNode , index ) , index ) ; if ( isRed ( y , index ) ) { makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( y , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; currentNode = getGrandParent ( currentNode , index ) ; } else { if ( isRightChild ( currentNode , index ) ) { currentNode = getParent ( currentNode , index ) ; rotateLeft ( currentNode , index ) ; } makeBlack ( getParent ( currentNode , index ) , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; if ( getGrandParent ( currentNode , index ) != null ) { rotateRight ( getGrandParent ( currentNode , index ) , index ) ; } } } else { // just like clause above, except swap left for right\r Node < K , V > y = getLeftChild ( getGrandParent ( currentNode , index ) , index ) ; if ( isRed ( y , index ) ) { makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( y , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; currentNode = getGrandParent ( currentNode , index ) ; } else { if ( isLeftChild ( currentNode , index ) ) { currentNode = getParent ( currentNode , index ) ; rotateRight ( currentNode , index ) ; } makeBlack ( getParent ( currentNode , index ) , index ) ; makeRed ( getGrandParent ( currentNode , index ) , index ) ; if ( getGrandParent ( currentNode , index ) != null ) { rotateLeft ( getGrandParent ( currentNode , index ) , index ) ; } } } } makeBlack ( rootNode [ index ] , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "complicated red - black delete stuff . Based on Sun s TreeMap implementation though it s barely recognizable any more [CODESPLIT] private void doRedBlackDelete ( final Node < K , V > deletedNode ) { for ( int index = FIRST_INDEX ; index < NUMBER_OF_INDICES ; index ++ ) { // if deleted node has both left and children, swap with\r // the next greater node\r if ( ( deletedNode . getLeft ( index ) != null ) && ( deletedNode . getRight ( index ) != null ) ) { swapPosition ( nextGreater ( deletedNode , index ) , deletedNode , index ) ; } Node < K , V > replacement = ( ( deletedNode . getLeft ( index ) != null ) ? deletedNode . getLeft ( index ) : deletedNode . getRight ( index ) ) ; if ( replacement != null ) { replacement . setParent ( deletedNode . getParent ( index ) , index ) ; if ( deletedNode . getParent ( index ) == null ) { rootNode [ index ] = replacement ; } else if ( deletedNode == deletedNode . getParent ( index ) . getLeft ( index ) ) { deletedNode . getParent ( index ) . setLeft ( replacement , index ) ; } else { deletedNode . getParent ( index ) . setRight ( replacement , index ) ; } deletedNode . setLeft ( null , index ) ; deletedNode . setRight ( null , index ) ; deletedNode . setParent ( null , index ) ; if ( isBlack ( deletedNode , index ) ) { doRedBlackDeleteFixup ( replacement , index ) ; } } else { // replacement is null\r if ( deletedNode . getParent ( index ) == null ) { // empty tree\r rootNode [ index ] = null ; } else { // deleted node had no children\r if ( isBlack ( deletedNode , index ) ) { doRedBlackDeleteFixup ( deletedNode , index ) ; } if ( deletedNode . getParent ( index ) != null ) { if ( deletedNode == deletedNode . getParent ( index ) . getLeft ( index ) ) { deletedNode . getParent ( index ) . setLeft ( null , index ) ; } else { deletedNode . getParent ( index ) . setRight ( null , index ) ; } deletedNode . setParent ( null , index ) ; } } } } shrink ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "complicated red - black delete stuff . Based on Sun s TreeMap implementation though it s barely recognizable any more . This rebalances the tree ( somewhat as red - black trees are not perfectly balanced -- perfect balancing takes longer ) [CODESPLIT] private void doRedBlackDeleteFixup ( final Node < K , V > replacementNode , final int index ) { Node < K , V > currentNode = replacementNode ; while ( ( currentNode != rootNode [ index ] ) && ( isBlack ( currentNode , index ) ) ) { if ( isLeftChild ( currentNode , index ) ) { Node < K , V > siblingNode = getRightChild ( getParent ( currentNode , index ) , index ) ; if ( isRed ( siblingNode , index ) ) { makeBlack ( siblingNode , index ) ; makeRed ( getParent ( currentNode , index ) , index ) ; rotateLeft ( getParent ( currentNode , index ) , index ) ; siblingNode = getRightChild ( getParent ( currentNode , index ) , index ) ; } if ( isBlack ( getLeftChild ( siblingNode , index ) , index ) && isBlack ( getRightChild ( siblingNode , index ) , index ) ) { makeRed ( siblingNode , index ) ; currentNode = getParent ( currentNode , index ) ; } else { if ( isBlack ( getRightChild ( siblingNode , index ) , index ) ) { makeBlack ( getLeftChild ( siblingNode , index ) , index ) ; makeRed ( siblingNode , index ) ; rotateRight ( siblingNode , index ) ; siblingNode = getRightChild ( getParent ( currentNode , index ) , index ) ; } copyColor ( getParent ( currentNode , index ) , siblingNode , index ) ; makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( getRightChild ( siblingNode , index ) , index ) ; rotateLeft ( getParent ( currentNode , index ) , index ) ; currentNode = rootNode [ index ] ; } } else { Node < K , V > siblingNode = getLeftChild ( getParent ( currentNode , index ) , index ) ; if ( isRed ( siblingNode , index ) ) { makeBlack ( siblingNode , index ) ; makeRed ( getParent ( currentNode , index ) , index ) ; rotateRight ( getParent ( currentNode , index ) , index ) ; siblingNode = getLeftChild ( getParent ( currentNode , index ) , index ) ; } if ( isBlack ( getRightChild ( siblingNode , index ) , index ) && isBlack ( getLeftChild ( siblingNode , index ) , index ) ) { makeRed ( siblingNode , index ) ; currentNode = getParent ( currentNode , index ) ; } else { if ( isBlack ( getLeftChild ( siblingNode , index ) , index ) ) { makeBlack ( getRightChild ( siblingNode , index ) , index ) ; makeRed ( siblingNode , index ) ; rotateLeft ( siblingNode , index ) ; siblingNode = getLeftChild ( getParent ( currentNode , index ) , index ) ; } copyColor ( getParent ( currentNode , index ) , siblingNode , index ) ; makeBlack ( getParent ( currentNode , index ) , index ) ; makeBlack ( getLeftChild ( siblingNode , index ) , index ) ; rotateRight ( getParent ( currentNode , index ) , index ) ; currentNode = rootNode [ index ] ; } } } makeBlack ( currentNode , index ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "swap two nodes ( except for their content ) taking care of special cases where one is the other s parent ... hey it happens . [CODESPLIT] private void swapPosition ( final Node < K , V > x , final Node < K , V > y , final int index ) { // Save initial values.\r Node < K , V > xFormerParent = x . getParent ( index ) ; Node < K , V > xFormerLeftChild = x . getLeft ( index ) ; Node < K , V > xFormerRightChild = x . getRight ( index ) ; Node < K , V > yFormerParent = y . getParent ( index ) ; Node < K , V > yFormerLeftChild = y . getLeft ( index ) ; Node < K , V > yFormerRightChild = y . getRight ( index ) ; boolean xWasLeftChild = ( x . getParent ( index ) != null ) && ( x == x . getParent ( index ) . getLeft ( index ) ) ; boolean yWasLeftChild = ( y . getParent ( index ) != null ) && ( y == y . getParent ( index ) . getLeft ( index ) ) ; // Swap, handling special cases of one being the other's parent.\r if ( x == yFormerParent ) { // x was y's parent\r x . setParent ( y , index ) ; if ( yWasLeftChild ) { y . setLeft ( x , index ) ; y . setRight ( xFormerRightChild , index ) ; } else { y . setRight ( x , index ) ; y . setLeft ( xFormerLeftChild , index ) ; } } else { x . setParent ( yFormerParent , index ) ; if ( yFormerParent != null ) { if ( yWasLeftChild ) { yFormerParent . setLeft ( x , index ) ; } else { yFormerParent . setRight ( x , index ) ; } } y . setLeft ( xFormerLeftChild , index ) ; y . setRight ( xFormerRightChild , index ) ; } if ( y == xFormerParent ) { // y was x's parent\r y . setParent ( x , index ) ; if ( xWasLeftChild ) { x . setLeft ( y , index ) ; x . setRight ( yFormerRightChild , index ) ; } else { x . setRight ( y , index ) ; x . setLeft ( yFormerLeftChild , index ) ; } } else { y . setParent ( xFormerParent , index ) ; if ( xFormerParent != null ) { if ( xWasLeftChild ) { xFormerParent . setLeft ( y , index ) ; } else { xFormerParent . setRight ( y , index ) ; } } x . setLeft ( yFormerLeftChild , index ) ; x . setRight ( yFormerRightChild , index ) ; } // Fix children's parent pointers\r if ( x . getLeft ( index ) != null ) { x . getLeft ( index ) . setParent ( x , index ) ; } if ( x . getRight ( index ) != null ) { x . getRight ( index ) . setParent ( x , index ) ; } if ( y . getLeft ( index ) != null ) { y . getLeft ( index ) . setParent ( y , index ) ; } if ( y . getRight ( index ) != null ) { y . getRight ( index ) . setParent ( y , index ) ; } x . swapColors ( y , index ) ; // Check if root changed\r if ( rootNode [ index ] == x ) { rootNode [ index ] = y ; } else if ( rootNode [ index ] == y ) { rootNode [ index ] = x ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "check if an object is fit to be proper input ... has to be Comparable if the comparator has not been set and non - null [CODESPLIT] private void checkNonNullComparable ( final Object o , final int index ) { if ( o == null ) { throw new NullPointerException ( dataName [ index ] + \" cannot be null\" ) ; } if ( comparators [ index ] == null && ! ( o instanceof Comparable ) ) { throw new ClassCastException ( dataName [ index ] + \" must be Comparable\" ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "insert a node by its value [CODESPLIT] private void insertValue ( final Node < K , V > newNode , final String thread_id ) throws IllegalArgumentException { Node < K , V > node = rootNode [ VALUE ] ; while ( true ) { int cmp = compare ( Node . ADDED , newNode . getData ( VALUE ) , node . getStatus ( ) , node . getData ( VALUE ) , VALUE ) ; if ( cmp == 0 ) { if ( nextEqualValid ( getFloorEqualNode ( node , VALUE ) , VALUE , thread_id ) != null ) { String debug_message = \"Cannot store a duplicate value (\\\"\" + newNode . getData ( VALUE ) + \"\\\") in this Map. Value already exists for key \" + node . getKey ( ) ; log . debug ( debug_message ) ; throw new IllegalArgumentException ( debug_message ) ; } if ( node . is ( Node . ADDED , null ) ) throw new ConcurrentModificationException ( ) ; if ( node . getRight ( VALUE ) != null ) { node = node . getRight ( VALUE ) ; } else if ( node . getLeft ( VALUE ) != null ) { node = node . getLeft ( VALUE ) ; } else { node . setRight ( newNode , VALUE ) ; newNode . setParent ( node , VALUE ) ; doRedBlackInsert ( newNode , VALUE ) ; break ; } } else if ( cmp < 0 ) { if ( node . getLeft ( VALUE ) != null ) { node = node . getLeft ( VALUE ) ; } else { node . setLeft ( newNode , VALUE ) ; newNode . setParent ( node , VALUE ) ; doRedBlackInsert ( newNode , VALUE ) ; break ; } } else { // cmp > 0\r if ( node . getRight ( VALUE ) != null ) { node = node . getRight ( VALUE ) ; } else { node . setRight ( newNode , VALUE ) ; newNode . setParent ( node , VALUE ) ; doRedBlackInsert ( newNode , VALUE ) ; break ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this map contains a mapping for the specified key . [CODESPLIT] @ Override public boolean containsKey ( final Object key ) throws ClassCastException , NullPointerException { checkKey ( key ) ; return lookupValid ( key , KEY , getCurrentThreadId ( ) ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns true if this map maps one or more keys to the specified value . [CODESPLIT] @ Override public boolean containsValue ( final Object value ) { checkValue ( value ) ; return lookupValid ( value , VALUE , getCurrentThreadId ( ) ) != null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the value to which this map maps the specified key . Returns null if the map contains no mapping for this key . [CODESPLIT] @ Override public V get ( final Object key ) throws ClassCastException , NullPointerException { checkKey ( key ) ; return ( V ) doGet ( key , KEY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Associates the specified value with the specified key in this map . [CODESPLIT] @ Override public V put ( final K key , final V value ) throws ClassCastException , NullPointerException , IllegalArgumentException , ConcurrentModificationException { checkKeyAndValue ( key , value ) ; Node < K , V > node = rootNode [ KEY ] ; String thread_id = getCurrentThreadId ( ) ; if ( node == null ) { Node < K , V > root = new Node < K , V > ( key , value ) ; rootNode [ KEY ] = root ; rootNode [ VALUE ] = root ; if ( ! auto_commit ) root . setStatus ( Node . ADDED , thread_id ) ; grow ( ) ; } else { while ( true ) { int cmp = compare ( Node . ADDED , key , node . getStatus ( ) , node . getData ( KEY ) , KEY ) ; if ( cmp == 0 ) { if ( nextEqualValid ( getFloorEqualNode ( node , KEY ) , KEY , thread_id ) != null ) { String debug_message = \"Cannot store a duplicate key (\\\"\" + key + \"\\\") in this Map\" ; log . debug ( debug_message ) ; throw new IllegalArgumentException ( debug_message ) ; } if ( node . is ( Node . ADDED , null ) ) throw new ConcurrentModificationException ( ) ; if ( node . getRight ( KEY ) != null ) { node = node . getRight ( KEY ) ; } else if ( node . getLeft ( KEY ) != null ) { node = node . getLeft ( KEY ) ; } else { Node < K , V > newNode = new Node < K , V > ( key , value ) ; insertValue ( newNode , thread_id ) ; node . setRight ( newNode , KEY ) ; newNode . setParent ( node , KEY ) ; doRedBlackInsert ( newNode , KEY ) ; grow ( ) ; if ( ! auto_commit ) newNode . setStatus ( Node . ADDED , thread_id ) ; break ; } } else if ( cmp < 0 ) { if ( node . getLeft ( KEY ) != null ) { node = node . getLeft ( KEY ) ; } else { Node < K , V > newNode = new Node < K , V > ( key , value ) ; insertValue ( newNode , thread_id ) ; node . setLeft ( newNode , KEY ) ; newNode . setParent ( node , KEY ) ; doRedBlackInsert ( newNode , KEY ) ; grow ( ) ; if ( ! auto_commit ) newNode . setStatus ( Node . ADDED , thread_id ) ; break ; } } else { // cmp > 0\r if ( node . getRight ( KEY ) != null ) { node = node . getRight ( KEY ) ; } else { Node < K , V > newNode = new Node < K , V > ( key , value ) ; insertValue ( newNode , thread_id ) ; node . setRight ( newNode , KEY ) ; newNode . setParent ( node , KEY ) ; doRedBlackInsert ( newNode , KEY ) ; grow ( ) ; if ( ! auto_commit ) newNode . setStatus ( Node . ADDED , thread_id ) ; break ; } } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the mapping for this key from this map if present [CODESPLIT] @ Override public V remove ( final Object key ) throws ConcurrentModificationException { checkKey ( key ) ; return ( V ) doRemove ( key , KEY ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes all mappings from this map [CODESPLIT] @ Override public void clear ( ) { if ( auto_commit ) { modify ( ) ; nodeCount = 0 ; rootNode [ KEY ] = null ; rootNode [ VALUE ] = null ; } else { String thread_id = getCurrentThreadId ( ) ; ArrayList < Entry < K , V > > list = new ArrayList < Entry < K , V > > ( entrySet ( ) ) ; for ( Iterator < Entry < K , V > > i = list . iterator ( ) ; i . hasNext ( ) ; ) { Node < K , V > node = ( Node < K , V > ) i . next ( ) ; if ( node . is ( Node . ADDED , thread_id ) ) doRedBlackDelete ( node ) ; else { node . setStatus ( Node . DELETED , thread_id ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a set view of the keys contained in this map . The set is backed by the map so changes to the map are reflected in the set and vice - versa . If the map is modified while an iteration over the set is in progress the results of the iteration are undefined . The set supports element removal which removes the corresponding mapping from the map via the Iterator . remove Set . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . [CODESPLIT] @ Override public Set < K > keySet ( ) { if ( setOfKeysByKey == null ) { setOfKeysByKey = new AbstractFilterableSet < K > ( ) { @ Override public Iterator < K > iterator ( ) { return new TransactionalBidiTreeMapIterator < K > ( KEY ) { @ Override protected K doGetNext ( ) { return ( K ) lastReturnedNode . getData ( KEY ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsKey ( o ) ; } @ Override public boolean remove ( Object o ) { int oldNodeCount = nodeCount ; TransactionalBidiTreeMap . this . remove ( o ) ; return nodeCount != oldNodeCount ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfKeysByKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns a collection view of the values contained in this map . The collection is backed by the map so changes to the map are reflected in the collection and vice - versa . If the map is modified while an iteration over the collection is in progress the results of the iteration are undefined . The collection supports element removal which removes the corresponding mapping from the map via the Iterator . remove Collection . remove removeAll retainAll and clear operations . It does not support the add or addAll operations . [CODESPLIT] @ Override public Collection < V > values ( ) { if ( collectionOfValuesByKey == null ) { collectionOfValuesByKey = new AbstractFilterableCollection < V > ( ) { @ Override public Iterator < V > iterator ( ) { return new TransactionalBidiTreeMapIterator < V > ( KEY ) { @ Override protected V doGetNext ( ) { return ( V ) lastReturnedNode . getData ( VALUE ) ; } } ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( ) ; } @ Override public boolean contains ( Object o ) { return containsValue ( o ) ; } @ Override public boolean remove ( Object o ) { int oldNodeCount = nodeCount ; removeValue ( o ) ; return nodeCount != oldNodeCount ; } @ Override public boolean removeAll ( Collection < ? > c ) { boolean modified = false ; Iterator < ? > iter = c . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( removeValue ( iter . next ( ) ) != null ) { modified = true ; } } return modified ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return collectionOfValuesByKey ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "It is very rare that this method would be required . You probably want to use entrySet instead . This method returns all Entry s in this Map no matter what its transactional status . [CODESPLIT] public FilterableSet < Entry < K , V > > allEntrySet ( ) { if ( setOfAllEntries == null ) { setOfAllEntries = new AbstractFilterableSet < Entry < K , V > > ( ) { @ Override public Iterator < Entry < K , V > > iterator ( ) { return new TransactionalBidiTreeMapIterator < Entry < K , V > > ( KEY ) { @ Override protected Entry < K , V > doGetNext ( ) { return lastReturnedNode ; } @ Override protected Node < K , V > getNextValidNode ( Node < K , V > node , String thread_id ) { return node ; } } ; } //cannot have contains or remove methods \r //as we have ALL the nodes and so may have duplicates \r //which are in the provess of being deleted\r @ Override public boolean contains ( Object o ) { throw new UtilsjException ( \"method not supported\" ) ; } @ Override public boolean remove ( Object o ) { throw new UtilsjException ( \"method not supported\" ) ; } @ Override public int size ( ) { return TransactionalBidiTreeMap . this . size ( true ) ; } @ Override public void clear ( ) { TransactionalBidiTreeMap . this . clear ( ) ; } } ; } return setOfAllEntries ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Copy all entries including transaction statuses from this map into the supplied map . Do not use this method unless you know exactly what you are doing . The auto commit flag of the supplied map may be changed as a result of calling this method check that this is valid first . [CODESPLIT] public final void copyEntries ( TransactionalBidiTreeMap < K , V > new_map ) { K key ; V val ; int transaction_status ; String transaction_id ; new_map . setAutoCommit ( isAutoCommit ( ) ) ; if ( ! isAutoCommit ( ) ) { // Do committed and deleted first\r for ( Iterator < Entry < K , V > > i = allEntrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { TransactionalBidiTreeMap . Node < K , V > entry = ( TransactionalBidiTreeMap . Node < K , V > ) i . next ( ) ; key = entry . getKey ( ) ; val = entry . getValue ( ) ; transaction_status = entry . getStatus ( ) ; transaction_id = entry . getTransactionId ( ) ; if ( transaction_status != TransactionalBidiTreeMap . Node . ADDED ) { try { // Put the value against the key\r new_map . put ( key , val ) ; // As the transaction status is deleted or no change then we need to commit the entry now.\r new_map . commit ( ) ; } catch ( Exception e ) { } // Duplicate keys can be ignored, this means we already have the value\r try { // If transaction status is deleted we need to now attach to the transaction id and remove.\r if ( transaction_status == TransactionalBidiTreeMap . Node . DELETED ) { new_map . attach ( transaction_id ) ; new_map . remove ( key ) ; } } catch ( Exception e ) { } // The entry may have already been deleted \r // Finally detach\r new_map . detach ( ) ; } } // Then do added\r for ( Iterator < Entry < K , V > > i = allEntrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { TransactionalBidiTreeMap . Node < K , V > entry = ( TransactionalBidiTreeMap . Node < K , V > ) i . next ( ) ; key = entry . getKey ( ) ; val = entry . getValue ( ) ; transaction_status = entry . getStatus ( ) ; transaction_id = entry . getTransactionId ( ) ; if ( transaction_status == TransactionalBidiTreeMap . Node . ADDED ) { // As the transaction status is added then attach to the transaction id before putting.\r new_map . attach ( transaction_id ) ; try { // Put the value against the key\r new_map . put ( key , val ) ; } catch ( Exception e ) { } // Duplicate keys can be ignored, this means we already have the value\r // Finally detach\r new_map . detach ( ) ; } } } else { for ( Iterator < Entry < K , V > > i = allEntrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { TransactionalBidiTreeMap . Node < K , V > entry = ( TransactionalBidiTreeMap . Node < K , V > ) i . next ( ) ; key = entry . getKey ( ) ; val = entry . getValue ( ) ; try { new_map . put ( key , val ) ; } catch ( Exception e ) { } // Duplicate keys can be ignored, this means we already have the value\r } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the entry corresponding to the specified key ; if no such entry exists returns the entry for the least key greater than the specified key ; if no such entry exists ( i . e . the greatest key in the Tree is less than the specified key ) returns <tt > null< / tt > . [CODESPLIT] private Node < K , V > getCeilNode ( Object lookup , int type ) { Node < K , V > p = TransactionalBidiTreeMap . this . rootNode [ type ] ; Object compareval ; if ( p == null ) return null ; while ( true ) { compareval = type == KEY ? p . getKey ( ) : p . getValue ( ) ; int cmp = TransactionalBidiTreeMap . this . compare ( Node . NO_CHANGE , lookup , p . getStatus ( ) , compareval , type ) ; if ( cmp == 0 ) { return p ; } else if ( cmp < 0 ) { if ( p . getLeft ( type ) != null ) p = p . getLeft ( type ) ; else return p ; } else { if ( p . getRight ( type ) != null ) { p = p . getRight ( type ) ; } else { Node < K , V > parent = p . getParent ( type ) ; Node < K , V > ch = p ; while ( parent != null && ch == parent . getRight ( type ) ) { ch = parent ; parent = parent . getParent ( type ) ; } return parent ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * Remove operation with a flag so we can tell coherence if the remove was caused by cache internal processing such as eviction or loading [CODESPLIT] public synchronized V remove ( Object key , boolean internal ) { // noinspection SuspiciousMethodCalls CacheObject < V > cacheObject = map . remove ( key ) ; // If the object is not in cache, stop trying to remove it. if ( cacheObject == null ) { return null ; } // Remove from the cache order list cacheObject . lastAccessedListNode . remove ( ) ; cacheObject . ageListNode . remove ( ) ; // Remove references to linked list nodes cacheObject . ageListNode = null ; cacheObject . lastAccessedListNode = null ; return cacheObject . object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears all entries out of cache where the entries are older than the maximum defined age . [CODESPLIT] protected synchronized void deleteExpiredEntries ( ) { // Check if expiration is turned on. if ( maxLifetime <= 0 ) { return ; } // Remove all old entries. To do this, we remove objects from the end // of the linked list until they are no longer too old. We get to avoid // any hash lookups or looking at any more objects than is strictly // neccessary. LinkedListNode node = ageList . getLast ( ) ; // If there are no entries in the age list, return. if ( node == null ) { return ; } // Determine the expireTime, which is the moment in time that elements // should expire from cache. Then, we can do an easy check to see // if the expire time is greater than the expire time. long expireTime = System . currentTimeMillis ( ) - maxLifetime ; while ( expireTime > node . timestamp ) { if ( remove ( node . object , true ) == null ) { log . warn ( \"Error attempting to remove(\" + node . object . toString ( ) + \") - cacheObject not found in cache!\" ) ; // remove from the ageList node . remove ( ) ; } // Get the next node. node = ageList . getLast ( ) ; // If there are no more entries in the age list, return. if ( node == null ) { return ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the least recently used elements if the cache size is greater than or equal to the maximum allowed size until the cache is at least 10% empty . [CODESPLIT] protected synchronized void cullCache ( ) { // Check if a max cache size is defined. if ( maxCacheSize < 0 ) { return ; } // See if the cache is too big. If so, clean out cache until it's 10% // free. if ( map . size ( ) > maxCacheSize ) { // First, delete any old entries to see how much memory that frees. deleteExpiredEntries ( ) ; // Next, delete the least recently used elements until 10% of the // cache // has been freed. int desiredSize = ( int ) ( maxCacheSize * .90 ) ; for ( int i = map . size ( ) ; i > desiredSize ; i -- ) { // Get the key and invoke the remove method on it. if ( remove ( lastAccessedList . getLast ( ) . object , true ) == null ) { log . warn ( \"Error attempting to cullCache with remove(\" + lastAccessedList . getLast ( ) . object . toString ( ) + \") - cacheObject not found in cache!\" ) ; lastAccessedList . getLast ( ) . remove ( ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "When the bundle gets activated we retrieve the OSGi properties . [CODESPLIT] protected void activate ( Map < String , Object > props ) { // Get the properties from the console. sharedSecret = toString ( props . get ( \"sharedSecret\" ) , \"e2KS54H35j6vS5Z38nK40\" ) ; hostname = toString ( props . get ( \"hostname\" ) , \"localhost\" ) ; LOGGER . info ( \" Trusted hostname: \" + hostname ) ; port = toInteger ( props . get ( \"port\" ) , 80 ) ; LOGGER . info ( \"Trusted port: \" + port ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public Map < String , Object > getPropertiesForUpdate ( ) { if ( ! readOnly && membersModified ) { modifiedMap . put ( MEMBERS_FIELD , StringUtils . join ( members , ' ' ) ) ; } Map < String , Object > propertiesForUpdate = super . getPropertiesForUpdate ( ) ; return propertiesForUpdate ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override // TODO: Unit test public Map < String , Object > getSafeProperties ( ) { if ( ! readOnly && membersModified ) { modifiedMap . put ( MEMBERS_FIELD , StringUtils . join ( members , ' ' ) ) ; } return super . getSafeProperties ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] public void process ( Map < String , Object > config , Map < String , Object > templateParams , HttpServletResponse response , ProxyResponse proxyResponse ) throws IOException { for ( Entry < String , String [ ] > h : proxyResponse . getResponseHeaders ( ) . entrySet ( ) ) { for ( String v : h . getValue ( ) ) { response . setHeader ( h . getKey ( ) , v ) ; } } int code = proxyResponse . getResultCode ( ) ; response . setStatus ( code ) ; IOUtils . copy ( proxyResponse . getResponseBodyAsInputStream ( ) , response . getOutputStream ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "asks the Player for more information about the playlist . <p > This method may block for 1 second . [CODESPLIT] public Optional < Playlist > getPlaylist ( String playlistName ) { try { return context . getResources ( ) . generateResource ( BroadcasterPlaylist . createPlaylistRequest ( player , playlistName ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( list -> list . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( Playlist :: importResource ) ) . get ( 1 , TimeUnit . SECONDS ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { context . getLogger ( ) . error ( \"unable to get Playlist\" ) ; return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "asks the player for more information about the specified playlist and creates a PlayerRequest with the answer . [CODESPLIT] public Optional < PlayerRequest > getPlayerRequest ( String playlistName , boolean permanent ) { return getPlaylist ( playlistName ) . map ( playlist -> PlayerRequest . createPlayerRequest ( playlist , permanent , player , capabilities , context , identifiable ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new PlaylistSelector . <p > For this method to return a non - empty Optional the following criteria must be met : <br > <ul > <li > the player must exist< / li > <li > the players - capabilities must allow requests from outside< / li > <li > the players - capabilities must allow a requests with specified a specified playlist< / li > <li > the players - capabilities signal its broadcasting playlists< / li > < / ul > [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public static Optional < PlaylistSelector > getPlaylistsFromPlayer ( Identification player , AddOnModule addOnModule ) { if ( player == null || addOnModule == null ) return Optional . empty ( ) ; Function < Capabilities , CompletableFuture < Optional < PlaylistSelector > > > getPlaylistSelector = capabilities -> addOnModule . getContext ( ) . getResources ( ) . generateResource ( new BroadcasterAvailablePlaylists ( player ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( list -> list . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( BroadcasterAvailablePlaylists :: getPlaylists ) . map ( playlists -> new PlaylistSelector ( player , capabilities , playlists , addOnModule . getContext ( ) , addOnModule ) ) ) ; Function < List < ResourceModel > , Optional < Capabilities > > getCapabilities = resourceModels -> resourceModels . stream ( ) . filter ( resourceModel -> resourceModel . getProvider ( ) . equals ( player ) ) . findAny ( ) . flatMap ( resource -> Capabilities . importFromResource ( resource , addOnModule . getContext ( ) ) ) . filter ( capabilities -> { if ( ! capabilities . handlesPlayRequestFromOutside ( ) ) { addOnModule . getContext ( ) . getLogger ( ) . error ( \"player does not handle play-request from outside\" ) ; return false ; } if ( ! capabilities . hasPlayRequestDetailed ( ) ) { addOnModule . getContext ( ) . getLogger ( ) . error ( \"player does not handle trackInfo-request from outside\" ) ; return false ; } if ( ! capabilities . isBroadcasting ( ) ) { addOnModule . getContext ( ) . getLogger ( ) . error ( \"player is not broadcasting playlists\" ) ; return false ; } return true ; } ) ; try { return addOnModule . getContext ( ) . getResources ( ) . generateResource ( new CapabilitiesResource ( player ) ) . orElse ( CompletableFuture . completedFuture ( new ArrayList <> ( ) ) ) . thenApply ( getCapabilities :: apply ) . thenCompose ( capabilities -> capabilities . map ( getPlaylistSelector :: apply ) . orElseGet ( ( ) -> CompletableFuture . completedFuture ( Optional . < PlaylistSelector > empty ( ) ) ) ) . get ( 1 , TimeUnit . SECONDS ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { addOnModule . getContext ( ) . getLogger ( ) . error ( \"unable to get PlaylistSelector\" ) ; return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new roster store on disk [CODESPLIT] public static DefaultRosterStore init ( final File baseDir ) { DefaultRosterStore store = new DefaultRosterStore ( baseDir ) ; if ( store . setRosterVersion ( \"\" ) ) { return store ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Opens a roster store [CODESPLIT] public static DefaultRosterStore open ( final File baseDir ) { DefaultRosterStore store = new DefaultRosterStore ( baseDir ) ; String s = store . readFile ( store . getVersionFile ( ) ) ; if ( s != null && s . startsWith ( STORE_ID + \"\\n\" ) ) { return store ; } else { return null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Method to get existing [ key1 key2 ] value or create new one if it s absent . Needs implementation of create ( key1 key2 ) in order to work [CODESPLIT] public V getOrCreate ( K1 key1 , K2 key2 ) { // already got it?\r if ( containsKey ( key1 , key2 ) ) return get ( key1 , key2 ) ; // if not, create and add it\r V result = create ( key1 , key2 ) ; put ( key1 , key2 , result ) ; return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return list of InetAddress for localhost that are not loopback addresses ( e . g . 127 . 0 . 0 . 1 ) [CODESPLIT] public static List < InetAddress > localhostNetworkAddresses ( ) throws UnknownHostException , SocketException { List < InetAddress > result = new ArrayList < InetAddress > ( ) ; InetAddress localhost = null ; try { //    localhost = InetAddress.getLocalHost(); throw new UnknownHostException ( ) ; } catch ( UnknownHostException ex ) { logger . debug ( \"localhostNetworkAddresses InetAddress.getLocalHost() failed\" ) ; } if ( localhost == null || localhost . getHostAddress ( ) . startsWith ( \"127\" ) ) { Enumeration < NetworkInterface > n = NetworkInterface . getNetworkInterfaces ( ) ; while ( n . hasMoreElements ( ) ) { NetworkInterface e = n . nextElement ( ) ; Enumeration < InetAddress > a = e . getInetAddresses ( ) ; while ( a . hasMoreElements ( ) ) { localhost = a . nextElement ( ) ; if ( localhost . isLoopbackAddress ( ) ) { // ignore } else { result . add ( localhost ) ; } } } } if ( result . size ( ) == 0 ) { result . add ( localhost ) ; } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Scan a range of InetAddresses starting with the given address [CODESPLIT] public static Collection < InetAddress > scanRange ( InetAddress addr , int count , int msTimeout ) { Collection < InetAddress > addresses = new ArrayList < InetAddress > ( ) ; Collection < InetAddress > result = new ArrayList < InetAddress > ( ) ; if ( addr == null ) { try { addresses . addAll ( localhostNetworkAddresses ( ) ) ; } catch ( Exception e ) { throw new FireRESTException ( e ) ; // Should not happen } } else { addresses . add ( addr ) ; } for ( InetAddress a : addresses ) { if ( a instanceof Inet4Address ) { InetAddress start = subnetAddress0 ( a , 24 ) ; result . addAll ( scanRangeCore ( start , count , msTimeout ) ) ; } } return result ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return first address on subnet containing given address [CODESPLIT] public static InetAddress subnetAddress0 ( InetAddress addr , int subnetBits ) { if ( subnetBits < 1 || 32 <= subnetBits ) { throw new FireRESTException ( \"Expected subnetBits 1..31\" ) ; } long mask = 1 ; for ( int i = 0 ; i < 32 ; i ++ ) { mask <<= 1 ; mask |= i < subnetBits ? 1 : 0 ; } long host0 = asLongAddress ( addr ) & mask ; try { return asInetAddress ( host0 ) ; } catch ( UnknownHostException e ) { throw new FireRESTException ( e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > SortedBidiMap < K , V > decorate ( SortedBidiMap < K , V > map ) { return new SynchronizedSortedBidiMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public Set < Map . Entry < K , V > > entrySet ( ) { return SyncUtils . synchronizeRead ( lock , new Callback < Set < Map . Entry < K , V > > > ( ) { @ Override protected void doAction ( ) { FilterableSet < Map . Entry < K , V > > _set = ( FilterableSet < Map . Entry < K , V > > ) map . entrySet ( ) ; _return ( new SynchronizedFilterableSet < Map . Entry < K , V > > ( _set , lock ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ [CODESPLIT] @ Override public void onFailure ( Throwable t ) { if ( t instanceof ExceedMaxAsyncJobsException ) { try { if ( stm != null ) { sessionManager . executeAsync ( this , permitTimeoutMs , stm , consistencyLevel ) ; } else if ( pstm != null ) { if ( bindValuesArr != null ) { sessionManager . executeAsync ( this , permitTimeoutMs , pstm , consistencyLevel , bindValuesArr ) ; } else { sessionManager . executeAsync ( this , permitTimeoutMs , pstm , consistencyLevel , bindValuesMap ) ; } } else if ( ! StringUtils . isBlank ( cql ) ) { if ( bindValuesArr != null ) { sessionManager . executeAsync ( this , permitTimeoutMs , cql , consistencyLevel , bindValuesArr ) ; } else { sessionManager . executeAsync ( this , permitTimeoutMs , cql , consistencyLevel , bindValuesMap ) ; } } else { onError ( new Exception ( \"No query is defined to retry!\" ) ) ; } } catch ( Throwable _t ) { onError ( _t ) ; } } else { onError ( t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Reads a Document from the given <code > File< / code > < / p > [CODESPLIT] public Document read ( File file ) throws DocumentException , IOException , XmlPullParserException { String systemID = file . getAbsolutePath ( ) ; return read ( new BufferedReader ( new FileReader ( file ) ) , systemID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Reads a Document from the given <code > URL< / code > < / p > [CODESPLIT] public Document read ( URL url ) throws DocumentException , IOException , XmlPullParserException { String systemID = url . toExternalForm ( ) ; return read ( createReader ( url . openStream ( ) ) , systemID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Reads a Document from the given URL or filename . < / p > <p / > <p / > If the systemID contains a <code > : < / code > character then it is assumed to be a URL otherwise its assumed to be a file name . If you want finer grained control over this mechansim then please explicitly pass in either a { @link URL } or a { @link File } instance instead of a { @link String } to denote the source of the document . < / p > [CODESPLIT] public Document read ( String systemID ) throws DocumentException , IOException , XmlPullParserException { if ( systemID . indexOf ( ' ' ) >= 0 ) { // lets assume its a URL return read ( new URL ( systemID ) ) ; } else { // lets assume that we are given a file name return read ( new File ( systemID ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Reads a Document from the given <code > Reader< / code > < / p > [CODESPLIT] public Document read ( Reader reader ) throws DocumentException , IOException , XmlPullParserException { getXPPParser ( ) . setInput ( reader ) ; return parseDocument ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Reads a Document from the given array of characters < / p > [CODESPLIT] public Document read ( char [ ] text ) throws DocumentException , IOException , XmlPullParserException { getXPPParser ( ) . setInput ( new CharArrayReader ( text ) ) ; return parseDocument ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Reads a Document from the given stream < / p > [CODESPLIT] public Document read ( InputStream in , String systemID ) throws DocumentException , IOException , XmlPullParserException { return read ( createReader ( in ) , systemID ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "<p > Reads a Document from the given <code > Reader< / code > < / p > [CODESPLIT] public Document read ( Reader reader , String systemID ) throws DocumentException , IOException , XmlPullParserException { Document document = read ( reader ) ; document . setName ( systemID ) ; return document ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "------------------------------------------------------------------------- [CODESPLIT] public Document parseDocument ( ) throws DocumentException , IOException , XmlPullParserException { DocumentFactory df = getDocumentFactory ( ) ; Document document = df . createDocument ( ) ; Element parent = null ; XmlPullParser pp = getXPPParser ( ) ; int count = 0 ; while ( true ) { int type = - 1 ; type = pp . nextToken ( ) ; switch ( type ) { case XmlPullParser . PROCESSING_INSTRUCTION : { String text = pp . getText ( ) ; int loc = text . indexOf ( \" \" ) ; if ( loc >= 0 ) { document . addProcessingInstruction ( text . substring ( 0 , loc ) , text . substring ( loc + 1 ) ) ; } else document . addProcessingInstruction ( text , \"\" ) ; break ; } case XmlPullParser . COMMENT : { if ( parent != null ) parent . addComment ( pp . getText ( ) ) ; else document . addComment ( pp . getText ( ) ) ; break ; } case XmlPullParser . CDSECT : { String text = pp . getText ( ) ; if ( parent != null ) { parent . addCDATA ( text ) ; } else { if ( text . trim ( ) . length ( ) > 0 ) { throw new DocumentException ( \"Cannot have text content outside of the root document\" ) ; } } break ; } case XmlPullParser . ENTITY_REF : { String text = pp . getText ( ) ; if ( parent != null ) { parent . addText ( text ) ; } else { if ( text . trim ( ) . length ( ) > 0 ) { throw new DocumentException ( \"Cannot have an entityref outside of the root document\" ) ; } } break ; } case XmlPullParser . END_DOCUMENT : { return document ; } case XmlPullParser . START_TAG : { QName qname = ( pp . getPrefix ( ) == null ) ? df . createQName ( pp . getName ( ) , pp . getNamespace ( ) ) : df . createQName ( pp . getName ( ) , pp . getPrefix ( ) , pp . getNamespace ( ) ) ; Element newElement = null ; // Do not include the namespace if this is the start tag of a // new packet // This avoids including \"jabber:client\", \"jabber:server\" or // \"jabber:component:accept\" if ( \"jabber:client\" . equals ( qname . getNamespaceURI ( ) ) || \"jabber:server\" . equals ( qname . getNamespaceURI ( ) ) || \"jabber:component:accept\" . equals ( qname . getNamespaceURI ( ) ) || \"http://jabber.org/protocol/httpbind\" . equals ( qname . getNamespaceURI ( ) ) ) { newElement = df . createElement ( pp . getName ( ) ) ; } else { newElement = df . createElement ( qname ) ; } int nsStart = pp . getNamespaceCount ( pp . getDepth ( ) - 1 ) ; int nsEnd = pp . getNamespaceCount ( pp . getDepth ( ) ) ; for ( int i = nsStart ; i < nsEnd ; i ++ ) if ( pp . getNamespacePrefix ( i ) != null ) newElement . addNamespace ( pp . getNamespacePrefix ( i ) , pp . getNamespaceUri ( i ) ) ; for ( int i = 0 ; i < pp . getAttributeCount ( ) ; i ++ ) { QName qa = ( pp . getAttributePrefix ( i ) == null ) ? df . createQName ( pp . getAttributeName ( i ) ) : df . createQName ( pp . getAttributeName ( i ) , pp . getAttributePrefix ( i ) , pp . getAttributeNamespace ( i ) ) ; newElement . addAttribute ( qa , pp . getAttributeValue ( i ) ) ; } if ( parent != null ) { parent . add ( newElement ) ; } else { document . add ( newElement ) ; } parent = newElement ; count ++ ; break ; } case XmlPullParser . END_TAG : { if ( parent != null ) { parent = parent . getParent ( ) ; } count -- ; if ( count < 1 ) { return document ; } break ; } case XmlPullParser . TEXT : { String text = pp . getText ( ) ; if ( parent != null ) { parent . addText ( text ) ; } else { if ( text . trim ( ) . length ( ) > 0 ) { throw new DocumentException ( \"Cannot have text content outside of the root document\" ) ; } } break ; } default : { ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > FilterableBidiMap < K , V > decorate ( FilterableBidiMap < K , V > map ) { return new SynchronizedFilterableBidiMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "----------------------------------------------------------------------- [CODESPLIT] public FilterableMap < K , V > filteredMap ( final Filter < ? super K > filter ) { return SyncUtils . synchronizeRead ( lock , new Callback < FilterableMap < K , V > > ( ) { @ Override protected void doAction ( ) { FilterableMap < K , V > _map = getFilterableBidiMap ( ) . filteredMap ( filter ) ; _return ( new SynchronizedFilterableMap < K , V > ( _map , lock ) ) ; } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "retruns true if any of these arguments is already existing and would be overwritten otherwise retruns false . The method also returns true if everything is null except the albumCover - Format ( maybe known in advance ) . [CODESPLIT] public boolean isNew ( TrackInfo trackInfo ) { return isNew ( trackInfo . name , trackInfo . artist , trackInfo . album , trackInfo . albumCover , trackInfo . albumCoverFormat , trackInfo . data , trackInfo . year , trackInfo . genre , trackInfo . bmp , trackInfo . duration ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "retruns true if any of these arguments is already existing and would be overwritten otherwise retruns false . The method also returns true if everything is null except the albumCover - Format ( maybe known in advance ) . [CODESPLIT] public boolean isNew ( String name , String artist , String album , byte [ ] albumCover , String albumCoverFormat , String id , String year , String genre , String bmp , long duration ) { if ( name == null && artist == null && album == null && albumCover == null && id == null ) return true ; BiPredicate < String , String > compareStrings = ( newString , oldString ) -> oldString != null && newString != null && ! oldString . equals ( newString ) ; if ( compareStrings . test ( name , this . name ) ) { return true ; } if ( compareStrings . test ( artist , this . artist ) ) { return true ; } if ( compareStrings . test ( album , this . album ) ) { return true ; } if ( compareStrings . test ( id , this . data ) ) { return true ; } if ( compareStrings . test ( albumCoverFormat , this . albumCoverFormat ) ) { return true ; } if ( compareStrings . test ( year , this . year ) ) { return true ; } if ( compareStrings . test ( genre , this . genre ) ) { return true ; } if ( this . duration > 0 && duration > 0 && this . duration == duration ) { return true ; } if ( compareStrings . test ( bmp , this . bmp ) ) { return true ; } if ( albumCover != null ) { if ( this . albumCover == null || ! Arrays . equals ( albumCover , this . albumCover ) ) return true ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns a trackinfo if some information was added and not overwritten ( see isNew ) AND a change occurred . [CODESPLIT] public Optional < TrackInfo > update ( String name , String artist , String album , byte [ ] albumCover , String coverFormat , String data , String year , String genre , String bmp , long duration ) { if ( isNew ( name , artist , album , albumCover , albumCoverFormat , data , year , genre , bmp , duration ) ) return Optional . empty ( ) ; boolean change = false ; if ( name != null && ! name . equals ( this . name ) ) { change = true ; } if ( artist != null && ! artist . equals ( this . artist ) ) { change = true ; } if ( album != null && ! album . equals ( this . album ) ) { change = true ; } if ( name != null && ! name . equals ( this . name ) ) { change = true ; } if ( albumCoverFormat != null && ! albumCoverFormat . equals ( this . albumCoverFormat ) ) { change = true ; } if ( data != null && ! data . equals ( this . data ) ) { change = true ; } if ( year != null && ! year . equals ( this . year ) ) { change = true ; } if ( genre != null && ! genre . equals ( this . genre ) ) { change = true ; } if ( duration > 0 && duration != this . duration ) { change = true ; } if ( bmp != null && ! bmp . equals ( this . bmp ) ) { change = true ; } if ( ! change ) return Optional . empty ( ) ; return Optional . of ( new TrackInfo ( this . name == null ? name : this . name , this . artist == null ? artist : this . artist , this . album == null ? album : this . album , this . albumCover == null ? albumCover : this . albumCover , this . albumCoverFormat == null ? albumCoverFormat : this . albumCoverFormat , this . data == null ? data : this . data , this . year == null ? year : this . year , this . genre == null ? genre : this . genre , this . bmp == null ? bmp : this . bmp , this . duration < 0 ? duration : this . duration ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exports the TrackInfo to a Hashmap [CODESPLIT] public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; data . put ( nameDescriptor , name ) ; data . put ( artistDescriptor , artist ) ; data . put ( albumDescriptor , albumDescriptor ) ; data . put ( albumCoverDescriptor , albumCover ) ; data . put ( albumCoverFormatDescriptor , albumCoverFormatDescriptor ) ; data . put ( dataDescriptor , this . data ) ; data . put ( yearDescriptor , this . year ) ; data . put ( genreDescriptor , this . genre ) ; data . put ( durationDescriptor , this . duration ) ; data . put ( bmpDescriptor , this . bmp ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the optional TrackInfo if the HashMap contains no malformed data [CODESPLIT] public static Optional < TrackInfo > importFromHashMap ( HashMap < String , Object > hashMap ) { try { String name = ( String ) hashMap . get ( nameDescriptor ) ; String album = ( String ) hashMap . get ( albumDescriptor ) ; String artist = ( String ) hashMap . get ( artistDescriptor ) ; byte [ ] albumCover = ( byte [ ] ) hashMap . get ( albumCoverDescriptor ) ; String albumCoverFormat = ( String ) hashMap . get ( albumCoverFormatDescriptor ) ; String data = ( String ) hashMap . get ( dataDescriptor ) ; String year = ( String ) hashMap . get ( yearDescriptor ) ; String genre = ( String ) hashMap . get ( genreDescriptor ) ; long duration = ( Long ) hashMap . get ( durationDescriptor ) ; String bmp = ( String ) hashMap . get ( bmpDescriptor ) ; return Optional . of ( new TrackInfo ( name , artist , album , albumCover , albumCoverFormat , data , year , genre , bmp , duration ) ) ; } catch ( ClassCastException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a TrackInfo from the resourceModel [CODESPLIT] public static Optional < TrackInfo > importFromResource ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { @ SuppressWarnings ( \"unchecked\" ) HashMap < String , Object > hashMap = ( HashMap < String , Object > ) resource ; return importFromHashMap ( hashMap ) ; } catch ( ClassCastException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "a new map with just [ key -- &gt ; value ] maplet [CODESPLIT] public static < K , V > Map < K , V > map ( K key , V value ) { return new MapBuilder ( ) . put ( key , value ) . toMap ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the jar filter for the executor . This filter can contain any name of a jar file that should be considered during search . If not set no filter is applied . If the argument is null no filter is used . Otherwise all strings in the argument are used as jar files and only those jar files will be used in a search . Using filters can speed up the search process . Filters can be set any time a new filter will overwrite an existing one ( using null will disable filtering ) . [CODESPLIT] protected final void setJarFilter ( String [ ] filter ) { this . jarFilter = ( filter == null ) ? null : Collections . unmodifiableList ( Arrays . asList ( filter ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new application at runtime with name ( shortcut to start ) and related class . [CODESPLIT] protected final void addApplication ( String name , Class < ? extends ExecS_Application > clazz ) { this . classmap . put ( name , clazz ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a set of application at runtime as in all found applications that can be executed [CODESPLIT] protected final void addAllApplications ( Set < Class < ? > > set ) { for ( Class < ? > cls : set ) { if ( ! cls . isInterface ( ) && ! Modifier . isAbstract ( cls . getModifiers ( ) ) ) { if ( ! this . classmap . containsValue ( cls ) ) { this . classNames . add ( cls . getName ( ) ) ; } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Main method [CODESPLIT] public final int execute ( String [ ] args ) { String arguments = StringUtils . join ( args , ' ' ) ; StrTokenizer tokens = new StrTokenizer ( arguments ) ; String arg = tokens . nextToken ( ) ; int ret = 0 ; if ( arg == null || \"-?\" . equals ( arg ) || \"-h\" . equals ( arg ) || \"--help\" . equals ( arg ) ) { //First help: no arguments or -? or --help -> print usage and exit(0) this . printUsage ( ) ; return 0 ; } else if ( \"-v\" . equals ( arg ) || \"--version\" . equals ( arg ) ) { System . out . println ( this . appName + \" - \" + ExecS . APP_VERSION ) ; System . out . println ( ) ; } else if ( \"-l\" . equals ( arg ) || \"--list\" . equals ( arg ) ) { //Second list: if -l or --list -> trigger search and exit(0) CF cf = new CF ( ) . setJarFilter ( ( ArrayUtils . contains ( args , \"-j\" ) ) ? this . jarFilter : null ) . setPkgFilter ( ( ArrayUtils . contains ( args , \"-p\" ) ) ? this . packageFilter : null ) ; this . addAllApplications ( cf . getSubclasses ( ExecS_Application . class ) ) ; this . printList ( ) ; return 0 ; } else { Object svc = null ; if ( this . classmap . containsKey ( arg ) ) { try { svc = this . classmap . get ( arg ) . newInstance ( ) ; } catch ( IllegalAccessException | InstantiationException iex ) { System . err . println ( this . appName + \": tried to execute <\" + args [ 0 ] + \"> by registered name -> exception: \" + iex . getMessage ( ) ) ; //\t\t\t\t\tiex.printStackTrace(); ret = - 99 ; } } else { try { Class < ? > c = Class . forName ( arg ) ; svc = c . newInstance ( ) ; } catch ( ClassNotFoundException | IllegalAccessException | InstantiationException ex ) { System . err . println ( this . appName + \": tried to execute <\" + args [ 0 ] + \"> as class name -> exception: \" + ex . getMessage ( ) ) ; //\t\t\t\t\tex.printStackTrace(); ret = - 99 ; } } ret = this . executeApplication ( svc , args , arg ) ; } if ( ret == - 99 ) { //now we are in trouble, nothing we could do worked, so print that and quit System . err . println ( this . appName + \": no application could be started and nothing else could be done, try '-?' or '--help' for help\" ) ; System . err . println ( ) ; } return ret ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Executes an application . [CODESPLIT] protected int executeApplication ( Object svc , String [ ] args , String orig ) { if ( svc != null && ( svc instanceof ExecS_Application ) ) { if ( svc instanceof Gen_RunScripts ) { //hook for GenRunScripts to get current class map - registered applications ( ( Gen_RunScripts ) svc ) . setClassMap ( this . classmap ) ; } if ( svc instanceof Gen_ExecJarScripts ) { //hook for Gen_ExecJarScripts to get current class map - registered applications ( ( Gen_ExecJarScripts ) svc ) . setClassMap ( this . classmap ) ; } return ( ( ExecS_Application ) svc ) . executeApplication ( ArrayUtils . remove ( args , 0 ) ) ; } else if ( svc == null ) { System . err . println ( \"could not create object for class or application name <\" + orig + \">\" ) ; return - 1 ; } else if ( ! ( svc instanceof ExecS_Application ) ) { System . err . println ( \"given class or application name <\" + orig + \"> is not instance of \" + ExecS_Application . class . getName ( ) ) ; return - 2 ; } else { System . err . println ( \"unexpected error processing for class or application name <\" + orig + \">\" ) ; return - 3 ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints a list of pre - registered and found applications . [CODESPLIT] protected final void printList ( ) { ST list = this . stg . getInstanceOf ( \"list\" ) ; list . add ( \"appName\" , this . appName ) ; if ( this . classmap . size ( ) > 0 ) { List < Map < String , String > > l = new ArrayList <> ( ) ; for ( String key : this . classmap . keySet ( ) ) { Map < String , String > m = new HashMap <> ( ) ; m . put ( \"key\" , key ) ; m . put ( \"val\" , this . classmap . get ( key ) . getName ( ) ) ; l . add ( m ) ; } list . add ( \"classMap\" , l ) ; } list . add ( \"className\" , this . classNames ) ; System . out . println ( list . render ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Prints usage information to standard out . [CODESPLIT] protected final void printUsage ( ) { ST usage = this . stg . getInstanceOf ( \"usage\" ) ; usage . add ( \"appName\" , this . appName ) ; usage . add ( \"packageFilter\" , this . packageFilter ) ; usage . add ( \"jarFilter\" , this . jarFilter ) ; usage . add ( \"excludedNames\" , new TreeSet <> ( Arrays . asList ( new CF ( ) . excludedNames ) ) ) ; System . out . println ( usage . render ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Public main to start the application executor . [CODESPLIT] public static void main ( String [ ] args ) { ExecS run = new ExecS ( ) ; int ret = run . execute ( args ) ; System . exit ( ret ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new MuteEvent [CODESPLIT] public static Optional < MuteEvent > createMuteEvent ( Identification source , Identification target ) { if ( target == null || target . equals ( source ) ) return Optional . empty ( ) ; try { MuteEvent muteRequest = new MuteEvent ( source ) ; muteRequest . addResource ( new SelectorResource ( source , target ) ) ; return Optional . of ( muteRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new MuteEvent will mute everything [CODESPLIT] public static Optional < MuteEvent > createMuteEvent ( Identification source ) { if ( source == null ) return Optional . empty ( ) ; try { MuteEvent muteRequest = new MuteEvent ( source ) ; return Optional . of ( muteRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invalidate and refresh the cache <p / > This is blocking and returns when the cache has been updated [CODESPLIT] public void refreshSchemataCache ( ) { try { final List < GoodwillSchema > schemata = delegate . getSchemata ( ) . get ( ) ; // If Goodwill is down - keep the old cache around if ( schemata == null ) { return ; } final Map < String , GoodwillSchema > newSchemataCache = new ConcurrentHashMap < String , GoodwillSchema > ( ) ; for ( final GoodwillSchema schema : schemata ) { newSchemataCache . put ( schema . getName ( ) , schema ) ; } synchronized ( cacheMonitor ) { knownSchemata . clear ( ) ; knownSchemata . putAll ( newSchemataCache ) ; } } catch ( InterruptedException e ) { log . warn ( \"Interrupted while refreshing the cache\" ) ; Thread . currentThread ( ) . interrupt ( ) ; } catch ( ExecutionException e ) { log . warn ( \"Unable to refresh schemata cache: {}\" , e . getLocalizedMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a schema name get the associated GoodwillSchema . This method tries hard to find it i . e . it will refresh the cache if the schema is not in the cache . [CODESPLIT] public GoodwillSchema getSchema ( final String schemaName ) { GoodwillSchema schema = knownSchemata . get ( schemaName ) ; if ( schema == null ) { refreshSchemataCache ( ) ; schema = knownSchemata . get ( schemaName ) ; } return schema ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the given lines to the given file if possible . [CODESPLIT] public boolean writeFile ( File file , List < String > lines ) { if ( file . exists ( ) ) { file . delete ( ) ; } try { FileWriter out = new FileWriter ( file ) ; for ( String s : lines ) { out . write ( s ) ; out . write ( System . getProperty ( \"line.separator\" ) ) ; } out . close ( ) ; file . setExecutable ( true ) ; } catch ( IOException ex ) { System . err . println ( this . getAppName ( ) + \": IO exception while writing to file - \" + file + \" with message: \" + ex . getMessage ( ) ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Tests if the class is run from an executable JAR . [CODESPLIT] protected boolean inExecJar ( ) { Class < Gen_ExecJarScripts > clazz = Gen_ExecJarScripts . class ; String className = clazz . getSimpleName ( ) + \".class\" ; String classPath = clazz . getResource ( className ) . toString ( ) ; if ( ! classPath . startsWith ( \"jar\" ) ) { System . err . println ( this . getAppName ( ) + \": not started in a jar, cannot proceed\" ) ; return false ; } String manifestPath = classPath . substring ( 0 , classPath . lastIndexOf ( \"!\" ) + 1 ) + \"/META-INF/MANIFEST.MF\" ; Manifest manifest ; try { manifest = new Manifest ( new URL ( manifestPath ) . openStream ( ) ) ; } catch ( IOException ex ) { System . err . println ( this . getAppName ( ) + \": exception while retrieving manifest: \" + ex . getMessage ( ) ) ; return false ; } Attributes attr = manifest . getMainAttributes ( ) ; if ( StringUtils . isBlank ( attr . getValue ( \"Main-Class\" ) ) ) { System . err . println ( this . getAppName ( ) + \": no main class in manifest, probably not an executable JAR, cannot continue\" ) ; return false ; } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new option to CLI parser and option list . [CODESPLIT] protected void addOption ( ApplicationOption < ? > option ) { if ( option != null ) { this . getCli ( ) . addOption ( option ) ; this . options . add ( option ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Get the schema as a collection of fields . We guarantee the ordering by field id . [CODESPLIT] public ArrayList < GoodwillSchemaField > getSchema ( ) { final ArrayList < GoodwillSchemaField > items = new ArrayList < GoodwillSchemaField > ( thriftItems . values ( ) ) ; Collections . sort ( items , new Comparator < GoodwillSchemaField > ( ) { @ Override public int compare ( final GoodwillSchemaField left , final GoodwillSchemaField right ) { return Short . valueOf ( left . getId ( ) ) . compareTo ( right . getId ( ) ) ; } } ) ; return items ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Given a name return the field matching the name . [CODESPLIT] public GoodwillSchemaField getFieldByName ( final String name ) { for ( final GoodwillSchemaField field : thriftItems . values ( ) ) { if ( field . getName ( ) . equals ( name ) ) { return field ; } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the package name for a jar entry . [CODESPLIT] public final static String getPkgName ( JarEntry entry ) { if ( entry == null ) { return \"\" ; } String s = entry . getName ( ) ; if ( s == null ) { return \"\" ; } if ( s . length ( ) == 0 ) { return s ; } if ( s . startsWith ( \"/\" ) ) { s = s . substring ( 1 , s . length ( ) ) ; } if ( s . endsWith ( \"/\" ) ) { s = s . substring ( 0 , s . length ( ) - 1 ) ; } return s . replace ( ' ' , ' ' ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public InputStream getResponseBodyAsInputStream ( ) throws IOException { InputStream in = response . getEntity ( ) . getContent ( ) ; leakedInputStreams . add ( in ) ; return in ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public String getResponseBodyAsString ( ) throws IOException { HttpEntity entity = response . getEntity ( ) ; if ( entity == null ) { return null ; } String contentEncoding = getContentEncoding ( entity ) ; InputStream in = entity . getContent ( ) ; BufferedReader r = new BufferedReader ( new InputStreamReader ( in , contentEncoding ) ) ; StringBuilder sb = new StringBuilder ( ) ; for ( ; ; ) { String l = r . readLine ( ) ; if ( l == null ) { break ; } sb . append ( l ) . append ( \"\\n\" ) ; } r . close ( ) ; in . close ( ) ; return sb . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void close ( ) { for ( InputStream in : leakedInputStreams ) { try { in . close ( ) ; } catch ( IOException e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Maps the content of the base map to its values . [CODESPLIT] private ImmutableMap < C , V > mapContentToValues ( final ImmutableMap < K , V > base ) { final ImmutableMap . Builder < C , V > builder = ImmutableMap . builder ( ) ; for ( final Entry < K , V > entry : base . entrySet ( ) ) { builder . put ( this . key ( entry . getKey ( ) ) , entry . getValue ( ) ) ; } return builder . build ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public StorageClient getClient ( ) throws ClientPoolException { try { StorageClient client = ( StorageClient ) pool . borrowObject ( ) ; LOGGER . debug ( \"Borrowed storage client pool client:\" + client ) ; return client ; } catch ( Exception e ) { LOGGER . warn ( \"Failed To Borrow connection from pool {} \" , e . getMessage ( ) ) ; throw new ClientPoolException ( \"Failed To Borrow connection from pool \" , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] public void releaseClient ( StorageClient client ) { try { if ( client != null ) { pool . returnObject ( client ) ; LOGGER . debug ( \"Released storage client pool client:\" + client ) ; } } catch ( Exception e ) { LOGGER . warn ( \"Failed to close connection \" + e . getMessage ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create the EventListener . [CODESPLIT] public static Optional < EventListener > createEventListener ( String descriptor , String description , String descriptorID , Identifiable identifiable ) throws IllegalArgumentException { if ( ! descriptorID . matches ( \"[\\\\w\\\\-_]+\" ) ) throw new IllegalArgumentException ( \"descriptorID: \" + descriptorID + \" contains illegal characters\" ) ; return IdentificationManagerM . getInstance ( ) . getIdentification ( identifiable ) . flatMap ( id -> Event . createEvent ( CommonEvents . Type . NOTIFICATION_TYPE , id , Collections . singletonList ( descriptor ) ) ) . map ( event -> new EventListener ( event , descriptor , description , descriptorID ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the supplied state for this IterativeCallback . [CODESPLIT] public IterativeState < T , R > setState ( IterativeState < T , R > new_state ) { IterativeState < T , R > old_state = this . state ; this . state = new_state ; return old_state ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "public wrapper for the iteration [CODESPLIT] public R iterate ( final FilterableCollection < ? extends T > c ) { initState ( ) ; checkUsed ( ) ; // If collection is decorated with a syncronized wrapper then synchronize the iteration\r if ( c instanceof SynchronizedFilterableCollection ) { return SyncUtils . synchronizeRead ( c , new Callback < R > ( ) { @ Override protected void doAction ( ) { _return ( doIteration ( c . iterator ( ) ) ) ; } } ) ; } return doIteration ( c . iterator ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "do the actual iteration [CODESPLIT] private R doIteration ( Iterator < ? extends T > it ) { // save the iterator into member variable\r state . i = it ; state . iterations = 0 ; if ( state . do_break == true ) return state . return_object ; // do the iteration calling nextobject on each\r while ( state . i . hasNext ( ) ) { T o = state . i . next ( ) ; if ( delegate != null ) delegate . delegate ( o ) ; else iterateObject ( o ) ; if ( state . do_break == true ) return state . return_object ; } return state . amended_object ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the first TrackInfo if found in the EventModel [CODESPLIT] public static Optional < TrackInfo > getTrackInfo ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( RESOURCE_ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( RESOURCE_ID ) . stream ( ) . findAny ( ) . flatMap ( TrackInfo :: importFromResource ) ; } else { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exports the progress [CODESPLIT] public HashMap < String , Long > export ( ) { HashMap < String , Long > data = new HashMap <> ( ) ; data . put ( lengthDescriptor , length ) ; data . put ( knownPositionDescriptor , knownPosition ) ; data . put ( knownMillisTimeStampDescriptor , knownMillisTimeStamp ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a Progress - object from the resourceModel [CODESPLIT] public static Optional < Progress > importResource ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { //noinspection unchecked HashMap < String , Long > data = ( HashMap < String , Long > ) resource ; long length = data . get ( lengthDescriptor ) ; long knownPosition = data . get ( knownPositionDescriptor ) ; long knownTimestamp = data . get ( knownMillisTimeStampDescriptor ) ; return Optional . of ( new Progress ( length , knownPosition , knownTimestamp ) ) ; } catch ( Exception e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return an red image with the given text auto - sized to fit the current imageWidthximageHeight [CODESPLIT] public BufferedImage errorImage ( String ... lines ) { if ( imageBuffer == null || imageBuffer . getWidth ( ) != imageWidth || imageBuffer . getHeight ( ) != imageHeight ) { imageBuffer = new BufferedImage ( imageWidth , imageHeight , BufferedImage . TYPE_INT_RGB ) ; } Graphics2D g = ( Graphics2D ) imageBuffer . getGraphics ( ) ; g . setBackground ( new Color ( 64 , 32 , 32 ) ) ; g . setColor ( new Color ( 255 , 64 , 64 ) ) ; g . clearRect ( 0 , 0 , imageWidth , imageHeight ) ; int maxLen = 0 ; for ( String line : lines ) { if ( line != null ) { for ( String innerLine : line . split ( \"\\n\" ) ) { maxLen = Math . max ( innerLine . length ( ) , maxLen ) ; } } } int padding = 20 ; float sizeForWidth = 1.8f * ( imageWidth - padding - padding ) / maxLen ; // should use TextLayout float sizeForHeight = ( imageHeight - padding - padding ) / lines . length ; float lineHeight = Math . min ( 80 , Math . max ( 12 , Math . min ( sizeForWidth , sizeForHeight ) ) ) ; float fontSize = 0.8f * lineHeight ; Font font = g . getFont ( ) . deriveFont ( fontSize ) ; g . setFont ( font ) ; float y = fontSize + padding ; for ( String line : lines ) { if ( line != null ) { g . drawString ( line , padding , y ) ; y += lineHeight ; } } return imageBuffer ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Return image from given URL . [CODESPLIT] public BufferedImage getImage ( URL url ) { String now = new Date ( ) . toString ( ) ; if ( url == null ) { return errorImage ( now , \"(No image url)\" ) ; } try { HttpURLConnection urlconn = ( HttpURLConnection ) url . openConnection ( ) ; urlconn . setReadTimeout ( msTimeout ) ; urlconn . setConnectTimeout ( msTimeout ) ; urlconn . setRequestMethod ( \"GET\" ) ; urlconn . connect ( ) ; BufferedImage image = ImageIO . read ( urlconn . getInputStream ( ) ) ; if ( image == null ) { return errorImage ( now , \"(Null image read)\" ) ; } imageWidth = image . getWidth ( ) ; imageHeight = image . getHeight ( ) ; return image ; } catch ( SocketTimeoutException e ) { logger . warn ( \"getImage({}) => {} {}\" , url , e . getClass ( ) . getCanonicalName ( ) , e . getMessage ( ) ) ; return errorImage ( now , msTimeout + \"ms TIMEOUT\" ) ; } catch ( Exception e ) { logger . warn ( \"getImage({}) => {} {}\" , url , e . getClass ( ) . getCanonicalName ( ) , e . getMessage ( ) ) ; return errorImage ( now , \"(No image)\" , url . toString ( ) , e . getMessage ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load json from given file resource . This is a convenient equivalent to getJSON () with a file URL . [CODESPLIT] public JSONResult getJSON ( File file ) { try { String json = new Scanner ( file ) . useDelimiter ( \"\\\\Z\" ) . next ( ) ; return new JSONResult ( json ) ; } catch ( Throwable e ) { throw new FireRESTException ( file . toString ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "HTTP GET json from given URL resource . [CODESPLIT] public JSONResult getJSON ( URL url ) { try { logger . debug ( \"Requesting {}\" , url ) ; StringBuilder text = new StringBuilder ( ) ; String line ; HttpURLConnection urlconn = ( HttpURLConnection ) url . openConnection ( ) ; urlconn . setReadTimeout ( msTimeout ) ; urlconn . setConnectTimeout ( msTimeout ) ; urlconn . setRequestMethod ( \"GET\" ) ; urlconn . connect ( ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( urlconn . getInputStream ( ) ) ) ; while ( ( line = br . readLine ( ) ) != null ) { text . append ( line ) ; } return new JSONResult ( text . toString ( ) ) ; } catch ( Throwable e ) { throw new FireRESTException ( url . toString ( ) , e ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Property principals are stored with keys of the form _pp_<principal > [CODESPLIT] public PropertyAcl getPropertyAcl ( String objectType , String objectPath ) throws AccessDeniedException , StorageClientException { long t = System . currentTimeMillis ( ) ; checkOpen ( ) ; compilingPermissions . inc ( ) ; try { String key = this . getAclKey ( objectType , objectPath ) ; Map < String , Object > objectAcl = getCached ( keySpace , aclColumnFamily , key ) ; Set < String > orderedPrincipals = Sets . newLinkedHashSet ( ) ; { String principal = user . getId ( ) ; if ( principal . startsWith ( \"_\" ) ) { throw new StorageClientException ( \"Princials may not start with _ \" ) ; } orderedPrincipals . add ( principal ) ; } for ( String principal : getPrincipals ( user ) ) { if ( principal . startsWith ( \"_\" ) ) { throw new StorageClientException ( \"Princials may not start with _ \" ) ; } orderedPrincipals . add ( principal ) ; } // Everyone must be the last principal to be applied if ( ! User . ANON_USER . equals ( user . getId ( ) ) ) { orderedPrincipals . add ( Group . EVERYONE ) ; } // go through each principal Map < String , Integer > grants = Maps . newHashMap ( ) ; Map < String , Integer > denies = Maps . newHashMap ( ) ; for ( String principal : orderedPrincipals ) { // got through each property String ppk = PROPERTY_PRINCIPAL_STEM + principal ; for ( Entry < String , Object > e : objectAcl . entrySet ( ) ) { String k = e . getKey ( ) ; if ( k . startsWith ( ppk ) ) { String [ ] parts = StringUtils . split ( k . substring ( PROPERTY_PRINCIPAL_STEM . length ( ) ) , \"@\" ) ; String propertyName = parts [ 1 ] ; if ( AclModification . isDeny ( k ) ) { int td = toInt ( e . getValue ( ) ) ; denies . put ( propertyName , toInt ( denies . get ( propertyName ) ) | td ) ; } else if ( AclModification . isGrant ( k ) ) { int tg = toInt ( e . getValue ( ) ) ; grants . put ( propertyName , toInt ( grants . get ( propertyName ) ) | tg ) ; } } } } // if the property has been granted, then that should remove the // deny for ( Entry < String , Integer > g : grants . entrySet ( ) ) { String k = g . getKey ( ) ; if ( denies . containsKey ( k ) ) { denies . put ( k , toInt ( denies . get ( k ) ) & ~ g . getValue ( ) ) ; } } return new PropertyAcl ( denies ) ; } finally { compilingPermissions . dec ( ) ; statsService . apiCall ( AccessControlManagerImpl . class . getName ( ) , \"getPropertyAcl\" , System . currentTimeMillis ( ) - t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Content Tokens activate ACEs for a user that holds the content token . The token is signed by the secret key associated with the target Object / acl and the token is token content item is then returned for the caller to save . [CODESPLIT] public void signContentToken ( Content token , String securityZone , String objectPath ) throws StorageClientException , AccessDeniedException { long t = System . currentTimeMillis ( ) ; try { checkOpen ( ) ; check ( Security . ZONE_CONTENT , objectPath , Permissions . CAN_WRITE_ACL ) ; check ( Security . ZONE_CONTENT , objectPath , Permissions . CAN_READ_ACL ) ; String key = this . getAclKey ( securityZone , objectPath ) ; Map < String , Object > currentAcl = getCached ( keySpace , aclColumnFamily , key ) ; String secretKey = ( String ) currentAcl . get ( _SECRET_KEY ) ; principalTokenValidator . signToken ( token , secretKey ) ; // the caller must save the target. } finally { statsService . apiCall ( AccessControlManagerImpl . class . getName ( ) , \"signContentToken\" , System . currentTimeMillis ( ) - t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Take key and value pairs from source and create map from value to key in target . [CODESPLIT] public static < K , V > void reverse ( Map < K , V > source , Map < V , K > target ) { Iterator < K > i = source . keySet ( ) . iterator ( ) ; while ( i . hasNext ( ) ) { K key = i . next ( ) ; V value = source . get ( key ) ; target . put ( value , key ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "New empty collection with similar type to source . The known concrete types replicated exactly are { [CODESPLIT] public static < T > Collection < T > like ( Collection < T > source ) { // known concrete types\r if ( source instanceof FilterableArrayList ) return new FilterableArrayList ( ) ; if ( source instanceof ArrayList ) return new ArrayList ( ) ; if ( source instanceof LinkedList ) return new LinkedList ( ) ; if ( source instanceof TreeSet ) return new TreeSet ( ( ( TreeSet ) source ) . comparator ( ) ) ; if ( source instanceof LinkedHashSet ) return new LinkedHashSet ( ) ; if ( source instanceof HashSet ) return new HashSet ( ) ; if ( source instanceof Stack ) return new Stack ( ) ; if ( source instanceof PriorityQueue ) return new PriorityQueue ( 10 , ( ( PriorityQueue ) source ) . comparator ( ) ) ; if ( source instanceof Vector ) return new Vector ( ) ; // known abstract types\r if ( source instanceof Queue ) return new LinkedList ( ) ; if ( source instanceof SortedSet ) return new TreeSet ( ( ( SortedSet ) source ) . comparator ( ) ) ; if ( source instanceof Set ) return new HashSet ( ) ; if ( source instanceof List ) return new ArrayList ( ) ; throw new IllegalArgumentException ( \"Unknown collection type \" + source . getClass ( ) . getCanonicalName ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates Cartesian product of two lists . [CODESPLIT] private Set < R > multiplication ( ) { final Set < R > answer = new LinkedHashSet <> ( this . one . size ( ) * this . two . size ( ) ) ; for ( final A left : this . one ) { for ( final B right : this . two ) { final R element = this . function . apply ( left , right ) ; if ( answer . contains ( element ) ) { throw new IllegalStateException ( String . format ( \"Cartesian product result contains duplicated element %s\" , element ) ) ; } answer . add ( element ) ; } } return ImmutableSet . copyOf ( answer ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the thread running [CODESPLIT] @ Override public synchronized void start ( ) { if ( ! running && ! used ) { this . running = true ; this . used = true ; this . setDaemon ( true ) ; super . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "execute [CODESPLIT] public synchronized void execute ( Runnable runnable , Object synObj ) { this . runnable = runnable ; this . syncObject = synObj ; if ( ! running ) { //If this is the first time, then kick off the thread.\r start ( ) ; } else { // we already have a thread running so wakeup the waiting thread.\r this . notifyAll ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public void run ( ) { while ( running ) { Runnable _runnable = null ; synchronized ( this ) { while ( running && runnable == null ) { try { this . wait ( ) ; } catch ( InterruptedException e ) { } // Ignore, as interrupts are not used by the pool itself\r } _runnable = runnable ; } if ( _runnable != null ) { try { _runnable . run ( ) ; } catch ( Exception e ) { log . error ( \"\" , e ) ; } finally { synchronized ( this ) { if ( syncObject != null ) { synchronized ( syncObject ) { syncObject . notify ( ) ; } } reset ( ) ; returnToPool ( ) ; } } } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the thread to the pool . [CODESPLIT] private void returnToPool ( ) { if ( pool != null ) { try { pool . returnObject ( this ) ; } catch ( Exception e1 ) { log . error ( \"Exception :\" , e1 ) ; } this . pool = null ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > BidiMap < K , V > decorate ( BidiMap < K , V > map ) { return new SynchronizedBidiMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new EndedEvent [CODESPLIT] public static Optional < EndedEvent > createEndedEvent ( Identification source ) { try { EndedEvent stopRequest = new EndedEvent ( source ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the current played track or null [CODESPLIT] public TrackInfo getCurrent ( ) { TrackInfo trackInfo = null ; try { trackInfo = queue . get ( position ) ; } catch ( IndexOutOfBoundsException e ) { trackInfo = null ; } return trackInfo ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets the name ( optional ) <p > playlist doesn t need to have a name < / p > [CODESPLIT] public Optional < String > getName ( ) { if ( name == null ) { return Optional . empty ( ) ; } else { return Optional . of ( name ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns the associated data ( not really specified specified by implementation ) [CODESPLIT] public Optional < String > getData ( ) { if ( data == null ) { return Optional . empty ( ) ; } else { return Optional . of ( data ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "updates the TrackInfo - Object [CODESPLIT] public Playlist update ( TrackInfo old , TrackInfo newTrackInfo ) { List < TrackInfo > list = new ArrayList <> ( queue ) ; list . set ( list . indexOf ( old ) , newTrackInfo ) ; return new Playlist ( queue , name , playbackModes , position ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Shuffles the playlist and returns the shuffled playlist so the original stays intact . Only the part of the playlist after the current position is shuffled . [CODESPLIT] public Playlist shuffle ( ) { int position = getPosition ( ) ; long seed = System . nanoTime ( ) ; if ( position >= 0 && position < queue . size ( ) ) { List < TrackInfo > trackInfos = queue . subList ( 0 , position ) ; List < TrackInfo > notPlayed = queue . subList ( position , queue . size ( ) ) ; List < TrackInfo > shuffledNotPlayed = new ArrayList <> ( notPlayed ) ; Collections . shuffle ( shuffledNotPlayed , new Random ( seed ) ) ; trackInfos . addAll ( shuffledNotPlayed ) ; return new Playlist ( trackInfos ) ; } else { List < TrackInfo > trackInfos = new ArrayList <> ( queue ) ; Collections . shuffle ( trackInfos , new Random ( seed ) ) ; return new Playlist ( trackInfos ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if all the active playbackModes are supported [CODESPLIT] public boolean verify ( Capabilities capabilities ) { for ( PlaybackMode playbackMode : playbackModes ) { switch ( playbackMode ) { case REPEAT : if ( ! capabilities . canRepeatPlayback ( ) ) { return false ; } else { break ; } case REPEAT_SONG : if ( ! capabilities . canRepeatPlaybackOfSong ( ) ) { return false ; } else { break ; } case SHUFFLE : if ( ! capabilities . canShufflePlayback ( ) ) { return false ; } else { break ; } } } return true ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "exports the Playlist to a HashMap [CODESPLIT] public HashMap < String , Object > export ( ) { HashMap < String , Object > data = new HashMap <> ( ) ; for ( int i = 0 ; i < queue . size ( ) ; i ++ ) { data . put ( QUEUE_DESCRIPTOR + i , queue . get ( i ) . export ( ) ) ; } for ( int i = 0 ; i < playbackModes . size ( ) ; i ++ ) { data . put ( PLAYBACK_MODE_DESCRIPTOR + i , playbackModes . get ( i ) . name ( ) ) ; } data . put ( NAME_DESCRIPTOR , name ) ; data . put ( POSITION_DESCRIPTOR , position ) ; data . put ( DATA_DESCRIPTOR , this . data ) ; return data ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "constructs ( if no errors were found ) the Playlist from the Resource [CODESPLIT] public static Optional < Playlist > importResource ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { //noinspection unchecked HashMap < String , Object > data = ( HashMap < String , Object > ) resource ; ArrayList < TrackInfo > queue = new ArrayList <> ( ) ; ArrayList < PlaybackMode > playbackModes = new ArrayList <> ( ) ; final String [ ] name = { null } ; final int [ ] position = { - 1 } ; final String [ ] dataString = { null } ; data . entrySet ( ) . forEach ( entry -> { if ( entry . getKey ( ) . startsWith ( QUEUE_DESCRIPTOR ) ) { int index = Integer . parseInt ( entry . getKey ( ) . replace ( QUEUE_DESCRIPTOR , \"\" ) ) ; //noinspection unchecked TrackInfo . importFromHashMap ( ( HashMap < String , Object > ) entry . getValue ( ) ) . ifPresent ( trackInfo -> queue . add ( index , trackInfo ) ) ; } else if ( entry . getKey ( ) . startsWith ( PLAYBACK_MODE_DESCRIPTOR ) ) { try { int index = Integer . parseInt ( entry . getKey ( ) . replace ( PLAYBACK_MODE_DESCRIPTOR , \"\" ) ) ; //noinspection unchecked playbackModes . add ( index , PlaybackMode . valueOf ( ( String ) entry . getValue ( ) ) ) ; } catch ( IllegalArgumentException ignored ) { //happens when the name is not present...maybe future sdks define other playbackModes } } else if ( entry . getKey ( ) . equals ( NAME_DESCRIPTOR ) ) { name [ 0 ] = ( String ) entry . getValue ( ) ; } else if ( entry . getKey ( ) . equals ( POSITION_DESCRIPTOR ) ) { position [ 0 ] = ( int ) entry . getValue ( ) ; } else if ( entry . getKey ( ) . equals ( DATA_DESCRIPTOR ) ) { dataString [ 0 ] = ( String ) entry . getValue ( ) ; } } ) ; return Optional . of ( new Playlist ( queue , name [ 0 ] , playbackModes , position [ 0 ] , dataString [ 0 ] ) ) ; } catch ( ClassCastException | IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Decodes four bytes from array <var > source< / var > and writes the resulting bytes ( up to three of them ) to <var > destination< / var > . The source and destination arrays can be manipulated anywhere along their length by specifying <var > srcOffset< / var > and <var > destOffset< / var > . This method does not check to make sure your arrays are large enough to accomodate <var > srcOffset< / var > + 4 for the <var > source< / var > array or <var > destOffset< / var > + 3 for the <var > destination< / var > array . This method returns the actual number of bytes that were converted from the Base64 encoding . <p > This is the lowest level of the decoding methods with all possible parameters . < / p > [CODESPLIT] private static int decode4to3 ( byte [ ] source , int srcOffset , byte [ ] destination , int destOffset , int options ) { byte [ ] DECODABET = getDecodabet ( options ) ; // Example: Dk== if ( source [ srcOffset + 2 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET [ source [ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET [ source [ srcOffset + 1 ] ] & 0xFF ) << 12 ) ; destination [ destOffset ] = ( byte ) ( outBuff >>> 16 ) ; return 1 ; } // Example: DkL= else if ( source [ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 // ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET [ source [ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET [ source [ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET [ source [ srcOffset + 2 ] ] & 0xFF ) << 6 ) ; destination [ destOffset ] = ( byte ) ( outBuff >>> 16 ) ; destination [ destOffset + 1 ] = ( byte ) ( outBuff >>> 8 ) ; return 2 ; } // Example: DkLE else { try { // Two ways to do the same thing. Don't know which way I like // best. // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) // >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET [ source [ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET [ source [ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET [ source [ srcOffset + 2 ] ] & 0xFF ) << 6 ) | ( ( DECODABET [ source [ srcOffset + 3 ] ] & 0xFF ) ) ; destination [ destOffset ] = ( byte ) ( outBuff >> 16 ) ; destination [ destOffset + 1 ] = ( byte ) ( outBuff >> 8 ) ; destination [ destOffset + 2 ] = ( byte ) ( outBuff ) ; return 3 ; } catch ( Exception e ) { log . log ( Level . ERROR , e . getMessage ( ) , e ) ; log . error ( \"\" + source [ srcOffset ] + \": \" + ( DECODABET [ source [ srcOffset ] ] ) ) ; log . error ( \"\" + source [ srcOffset + 1 ] + \": \" + ( DECODABET [ source [ srcOffset + 1 ] ] ) ) ; log . error ( \"\" + source [ srcOffset + 2 ] + \": \" + ( DECODABET [ source [ srcOffset + 2 ] ] ) ) ; log . error ( \"\" + source [ srcOffset + 3 ] + \": \" + ( DECODABET [ source [ srcOffset + 3 ] ] ) ) ; return - 1 ; } // end catch } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Takes the original request and starts the batching . [CODESPLIT] protected void batchRequest ( HttpServletRequest request , HttpServletResponse response , String jsonRequest , boolean allowModify ) throws IOException , ServletException { JsonParser jsonParser = new JsonParser ( ) ; JsonElement element = jsonParser . parse ( jsonRequest ) ; if ( ! element . isJsonArray ( ) ) { response . sendError ( HttpServletResponse . SC_BAD_REQUEST , \"Failed to parse the requests parameter\" ) ; return ; } JsonArray arr = element . getAsJsonArray ( ) ; response . setContentType ( \"application/json\" ) ; response . setCharacterEncoding ( \"UTF-8\" ) ; String key = null ; try { MessageDigest md = MessageDigest . getInstance ( \"SHA-1\" ) ; key = Base64 . encodeBase64URLSafeString ( md . digest ( jsonRequest . getBytes ( \"UTF-8\" ) ) ) ; String cachedResult = responseCache . get ( key ) ; if ( cachedResult != null ) { LOGGER . debug ( \"Using Cache\" ) ; response . getWriter ( ) . write ( cachedResult ) ; return ; } } catch ( Exception e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } boolean cache = ( key != null ) ; CaptureResponseWriter captureResponseWriter = new CaptureResponseWriter ( response . getWriter ( ) ) ; JsonWriter write = new JsonWriter ( captureResponseWriter ) ; write . beginObject ( ) ; write . name ( \"results\" ) ; write . beginArray ( ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { JsonObject obj = arr . get ( i ) . getAsJsonObject ( ) ; try { RequestInfo r = new RequestInfo ( obj ) ; if ( r . isValid ( ) && ( allowModify || r . isSafe ( ) ) ) { cache = doRequest ( request , response , r , write ) && cache ; } else { outputFailure ( \"Bad request, ignored \" + obj . toString ( ) , write ) ; } } catch ( MalformedURLException e ) { outputFailure ( \"Bad request, ignored \" + obj . toString ( ) , write ) ; } } write . endArray ( ) ; write . endObject ( ) ; write . flush ( ) ; if ( cache ) { responseCache . put ( key , captureResponseWriter . toString ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a TrackInfo from the resourceModel [CODESPLIT] public static Optional < Capabilities > importFromResource ( ResourceModel resourceModel , Context context ) { Object resource = resourceModel . getResource ( ) ; try { @ SuppressWarnings ( \"unchecked\" ) HashMap < String , Boolean > hashMap = ( HashMap < String , Boolean > ) resource ; return Optional . of ( constructCapabilites ( hashMap , context ) ) ; } catch ( ClassCastException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StopEvent [CODESPLIT] public static Optional < StopEvent > createStopEvent ( Identification source , Identification target ) { if ( target == null || target . equals ( source ) ) return Optional . empty ( ) ; try { StopEvent stopRequest = new StopEvent ( source ) ; stopRequest . addResource ( new SelectorResource ( source , target ) ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "creates a new StopEvent [CODESPLIT] public static Optional < StopEvent > createStopEvent ( Identification source ) { try { StopEvent stopRequest = new StopEvent ( source ) ; return Optional . of ( stopRequest ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the name portion of a XMPP address . For example for the address matt@jivesoftware . com / Smack matt would be returned . If no username is present in the address the empty string will be returned . [CODESPLIT] public static String parseName ( String XMPPAddress ) { if ( XMPPAddress == null ) { return null ; } int atIndex = XMPPAddress . indexOf ( \"@\" ) ; if ( atIndex <= 0 ) { return \"\" ; } else { return XMPPAddress . substring ( 0 , atIndex ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Escapes all necessary characters in the String so that it can be used in an XML doc . [CODESPLIT] public static final String escapeForXML ( String string ) { if ( string == null ) { return null ; } char ch ; int i = 0 ; int last = 0 ; char [ ] input = string . toCharArray ( ) ; int len = input . length ; StringBuffer out = new StringBuffer ( ( int ) ( len * 1.3 ) ) ; for ( ; i < len ; i ++ ) { ch = input [ i ] ; if ( ch > ' ' ) { continue ; } else if ( ch == ' ' ) { if ( i > last ) { out . append ( input , last , i - last ) ; } last = i + 1 ; out . append ( LT_ENCODE ) ; } else if ( ch == ' ' ) { if ( i > last ) { out . append ( input , last , i - last ) ; } last = i + 1 ; out . append ( GT_ENCODE ) ; } else if ( ch == ' ' ) { if ( i > last ) { out . append ( input , last , i - last ) ; } // Do nothing if the string is of the form &#235; (unicode // value) if ( ! ( len > i + 5 && input [ i + 1 ] == ' ' && Character . isDigit ( input [ i + 2 ] ) && Character . isDigit ( input [ i + 3 ] ) && Character . isDigit ( input [ i + 4 ] ) && input [ i + 5 ] == ' ' ) ) { last = i + 1 ; out . append ( AMP_ENCODE ) ; } } else if ( ch == ' ' ) { if ( i > last ) { out . append ( input , last , i - last ) ; } last = i + 1 ; out . append ( QUOTE_ENCODE ) ; } } if ( last == 0 ) { return string ; } if ( i > last ) { out . append ( input , last , i - last ) ; } return out . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Hashes a String using the SHA - 1 algorithm and returns the result as a String of hexadecimal numbers . This method is synchronized to avoid excessive MessageDigest object creation . If calling this method becomes a bottleneck in your code you may wish to maintain a pool of MessageDigest objects instead of using this method . <p > A hash is a one - way function -- that is given an input an output is easily computed . However given the output the input is almost impossible to compute . This is useful for passwords since we can store the hash and a hacker will then have a very hard time determining the original password . [CODESPLIT] public synchronized static final String hash ( String data ) { if ( digest == null ) { try { digest = MessageDigest . getInstance ( \"SHA-1\" ) ; } catch ( NoSuchAlgorithmException nsae ) { System . err . println ( \"Failed to load the SHA-1 MessageDigest. \" + \"Jive will be unable to function normally.\" ) ; } } // Now, compute hash. try { digest . update ( data . getBytes ( \"UTF-8\" ) ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( e ) ; } return encodeHex ( digest . digest ( ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Turns an array of bytes into a String representing each byte as an unsigned hex number . <p > Method by Santeri Paavolainen Helsinki Finland 1996<br > ( c ) Santeri Paavolainen Helsinki Finland 1996<br > Distributed under LGPL . [CODESPLIT] public static final String encodeHex ( byte [ ] bytes ) { StringBuffer buf = new StringBuffer ( bytes . length * 2 ) ; int i ; for ( i = 0 ; i < bytes . length ; i ++ ) { if ( ( ( int ) bytes [ i ] & 0xff ) < 0x10 ) { buf . append ( \"0\" ) ; } buf . append ( Long . toString ( ( int ) bytes [ i ] & 0xff , 16 ) ) ; } return buf . toString ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds and sends the <tt > auth< / tt > stanza to the server . Note that this method of authentication is not recommended since it is very inflexable . Use { @link #authenticate ( String String CallbackHandler ) } whenever possible . [CODESPLIT] public void authenticate ( String username , String host , String serviceName , String password ) throws IOException , XMPPException { // Since we were not provided with a CallbackHandler, we will use our // own with the given // information // Set the authenticationID as the username, since they must be the same // in this case. this . authenticationId = username ; this . password = password ; this . hostname = host ; String [ ] mechanisms = { getName ( ) } ; Map < String , String > props = new HashMap < String , String > ( ) ; sc = Sasl . createSaslClient ( mechanisms , username , \"xmpp\" , serviceName , props , this ) ; authenticate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Same as { @link #authenticate ( String String String String ) } but with the hostname used as the serviceName . <p > Kept for backward compatibility only . [CODESPLIT] public void authenticate ( String username , String host , String password ) throws IOException , XMPPException { authenticate ( username , host , host , password ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Builds and sends the <tt > auth< / tt > stanza to the server . The callback handler will handle any additional information such as the authentication ID or realm if it is needed . [CODESPLIT] public void authenticate ( String username , String host , CallbackHandler cbh ) throws IOException , XMPPException { String [ ] mechanisms = { getName ( ) } ; Map < String , String > props = new HashMap < String , String > ( ) ; sc = Sasl . createSaslClient ( mechanisms , username , \"xmpp\" , host , props , cbh ) ; authenticate ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "The server is challenging the SASL mechanism for the stanza he just sent . Send a response to the server s challenge . [CODESPLIT] public void challengeReceived ( String challenge ) throws IOException { byte response [ ] ; if ( challenge != null ) { response = sc . evaluateChallenge ( StringUtils . decodeBase64 ( challenge ) ) ; } else { response = sc . evaluateChallenge ( new byte [ 0 ] ) ; } Packet responseStanza ; if ( response == null ) { responseStanza = new Response ( ) ; } else { responseStanza = new Response ( StringUtils . encodeBase64 ( response , false ) ) ; } // Send the authentication to the server getSASLAuthentication ( ) . send ( responseStanza ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Create a JSON representation of the GoodwillSchemaField . It will always contain the name type and position . Description and SQL attributes are however optional . [CODESPLIT] public ByteArrayOutputStream toJSON ( ) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; mapper . writeValue ( out , this ) ; return out ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Pretty print the SQL type . TODO : add layer of abstraction too Netezza specific [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public String getFullSQLType ( ) { String fullSQLType = null ; if ( sql . type == null ) { return null ; } else if ( sql . type . equals ( \"decimal\" ) || sql . type . equals ( \"numeric\" ) ) { if ( sql . precision != null ) { if ( sql . scale != null ) { fullSQLType = sql . type + \"(\" + sql . precision + \", \" + sql . scale + \")\" ; } else { fullSQLType = sql . type + \"(\" + sql . precision + \")\" ; } } } else { if ( sql . type . equals ( \"nvarchar\" ) || sql . type . equals ( \"varchar\" ) ) { if ( sql . length != null ) { fullSQLType = sql . type + \"(\" + sql . length + \")\" ; } } } if ( fullSQLType == null ) { fullSQLType = sql . type ; } return fullSQLType ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "main method for outputPlugin runs the data - conversion and output - renderer [CODESPLIT] @ Override public void run ( ) { while ( ! stop ) { EventModel event ; try { event = blockingQueueHandling ( ) ; //gets the new Event if one was added to the blockingQueue } catch ( InterruptedException e ) { getContext ( ) . getLogger ( ) . warn ( e ) ; continue ; } List < CompletableFuture < X > > outputExtensions = getContext ( ) . getOutput ( ) . generateAllOutputExtensions ( this , getArgument ( ) , event ) ; try { outputExtensions = timeOut ( outputExtensions , getTimeoutLimit ( ) ) ; } catch ( InterruptedException e ) { getContext ( ) . getLogger ( ) . warn ( e ) ; } handleFutures ( outputExtensions , event ) ; //notifies output-manager when done processing isDone ( event ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Handles an event from OSGi and places it in the appropriate queue . [CODESPLIT] public void handleEvent ( Event event ) { String topic = event . getTopic ( ) ; LOGGER . debug ( \"Got Event {} {} \" , event , handlers ) ; Collection < IndexingHandler > contentIndexHandler = handlers . get ( topic ) ; if ( contentIndexHandler != null && contentIndexHandler . size ( ) > 0 ) { try { int ttl = Utils . toInt ( event . getProperty ( TopicIndexer . TTL ) , Integer . MAX_VALUE ) ; for ( IndexingHandler indexingHandler : contentIndexHandler ) { if ( indexingHandler instanceof QoSIndexHandler ) { ttl = Math . min ( ttl , Utils . defaultMax ( ( ( QoSIndexHandler ) indexingHandler ) . getTtl ( event ) ) ) ; } } QueueManager q = null ; // queues is ordered by ascending ttl, so the fastest queue is queues[0], // if the ttl is less that that, we can't satisfy it, so we will put it // in the fastest queue if ( ttl < queues [ 0 ] . batchDelay ) { LOGGER . warn ( \"Unable to satisfy TTL of {} on event {}, posting to the highest priority queue. \" + \"If this message is logged a lot please adjust the queues or change the event ttl to something that can be satisfied. \" + \"Filling the highest priority queue is counter productive. \" , ttl , event ) ; queues [ 0 ] . saveEvent ( event ) ; } else { for ( QueueManager qm : queues ) { if ( ttl < qm . batchDelay ) { q . saveEvent ( event ) ; q = null ; break ; } q = qm ; } if ( q != null ) { q . saveEvent ( event ) ; } } } catch ( IOException e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "used only for testing [CODESPLIT] protected void joinAll ( ) throws InterruptedException { if ( queues != null ) { for ( QueueManager q : queues ) { q . getQueueDispatcher ( ) . join ( ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Set a property . The property will only be set if writable . If the property or this athorizable is read only nothing will happen . [CODESPLIT] public void setProperty ( String name , Object value ) { if ( ! readOnly && ! FILTER_PROPERTIES . contains ( name ) ) { Object cv = authorizableMap . get ( name ) ; if ( value == null ) { if ( cv != null && ! ( cv instanceof RemoveProperty ) ) { modifiedMap . put ( name , new RemoveProperty ( ) ) ; } } else if ( ! value . equals ( cv ) ) { modifiedMap . put ( name , value ) ; } else if ( modifiedMap . containsKey ( name ) && ! value . equals ( modifiedMap . get ( name ) ) ) { modifiedMap . put ( name , value ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove the property . [CODESPLIT] public void removeProperty ( String key ) { if ( ! readOnly && ( authorizableMap . containsKey ( key ) || modifiedMap . containsKey ( key ) ) ) { modifiedMap . put ( key , new RemoveProperty ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "add a principal to this authorizable . [CODESPLIT] public void addPrincipal ( String principal ) { if ( ! readOnly && ! principals . contains ( principal ) ) { principals . add ( principal ) ; principalsModified = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "remove a principal from this authorizable . [CODESPLIT] public void removePrincipal ( String principal ) { if ( ! readOnly && principals . contains ( principal ) ) { principals . remove ( principal ) ; principalsModified = true ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "@throws ComponentException [CODESPLIT] public void process ( boolean block ) { Runnable componentRunnable = new Runnable ( ) { @ Override public void run ( ) { try { mutex . acquire ( ) ; } catch ( InterruptedException e ) { LOGGER . fatal ( \"Main loop.\" , e ) ; } } } ; Thread t = new Thread ( componentRunnable , \"jamppa-hanging-thread\" ) ; if ( block ) { t . run ( ) ; } else { t . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates a new Event Object [CODESPLIT] public static Optional < PlayerCommand > createPlayerCommand ( Identification source , Identification target , String command , Capabilities capabilities , Context context ) { try { Optional < CommandResource > commandResource = CommandResource . createCommandResource ( source , command , capabilities , context ) ; if ( ! commandResource . isPresent ( ) ) { context . getLogger ( ) . error ( \"unable to obtain commandResource\" ) ; return Optional . empty ( ) ; } PlayerCommand playerCommand = new PlayerCommand ( source ) ; playerCommand . addResource ( new SelectorResource ( source , target ) ) ; playerCommand . addResource ( commandResource . get ( ) ) ; return Optional . of ( playerCommand ) ; } catch ( IllegalArgumentException e ) { return Optional . empty ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Notification that the root window is closing . Stop listening for received and transmitted packets . [CODESPLIT] public void rootWindowClosing ( WindowEvent evt ) { connection . removePacketListener ( listener ) ; ( ( ObservableReader ) reader ) . removeReaderListener ( readerListener ) ; ( ( ObservableWriter ) writer ) . removeWriterListener ( writerListener ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Factory method to create a synchronized map . [CODESPLIT] public static < K , V > FilterableMap < K , V > decorate ( FilterableMap < K , V > map ) { return new SynchronizedFilterableMap < K , V > ( map ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void process ( Map < String , Object > config , Map < String , Object > templateParams , HttpServletResponse response , ProxyResponse proxyResponse ) throws IOException { LOG . debug ( \"process(Map<String, Object> {}, SlingHttpServletResponse response, ProxyResponse proxyResponse)\" , templateParams ) ; if ( templateParams == null || ! tltppp . hostname . equals ( templateParams . get ( \"hostname\" ) ) || tltppp . port != ( Integer ) templateParams . get ( \"port\" ) ) { response . sendError ( HttpServletResponse . SC_BAD_REQUEST ) ; return ; } // just use DefaultProxyPostProcessorImpl behavior dpppi . process ( config , templateParams , response , proxyResponse ) ; return ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public void changePassword ( Authorizable authorizable , String password , String oldPassword ) throws StorageClientException , AccessDeniedException { long t = System . currentTimeMillis ( ) ; try { String id = authorizable . getId ( ) ; if ( thisUser . isAdmin ( ) || currentUserId . equals ( id ) ) { if ( ! thisUser . isAdmin ( ) ) { User u = authenticator . authenticate ( id , oldPassword ) ; if ( u == null ) { throw new IllegalArgumentException ( \"Unable to change passwords, old password does not match\" ) ; } } putCached ( keySpace , authorizableColumnFamily , id , ImmutableMap . of ( Authorizable . LASTMODIFIED_FIELD , ( Object ) System . currentTimeMillis ( ) , Authorizable . ID_FIELD , id , Authorizable . LASTMODIFIED_BY_FIELD , accessControlManager . getCurrentUserId ( ) , Authorizable . PASSWORD_FIELD , StorageClientUtils . secureHash ( password ) ) , false ) ; storeListener . onUpdate ( Security . ZONE_AUTHORIZABLES , id , currentUserId , getType ( authorizable ) , false , null , \"op:change-password\" ) ; } else { throw new AccessDeniedException ( Security . ZONE_ADMIN , id , \"Not allowed to change the password, must be the user or an admin user\" , currentUserId ) ; } } finally { statsService . apiCall ( AuthorizableManagerImpl . class . getName ( ) , \"changePassword\" , System . currentTimeMillis ( ) - t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Helper method to get an instance of { @link SessionIdentifier } . [CODESPLIT] public static SessionIdentifier getInstance ( String hostsAndPorts , String username , String password , String keyspace ) { return getInstance ( hostsAndPorts , username , password , null , keyspace ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "call this method when you have encountered the user [CODESPLIT] @ SuppressWarnings ( \"unused\" ) public void userEncountered ( ) { List < String > descriptors = new ArrayList <> ( ) ; /*\n        if (strict && ((!present && !fireUnknownIfNotPresent)|| !strictPresent) && addResponseDescriptors) {\n            if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMajorMinuteThresholdNotPresent()) {\n                descriptors.add(CommonEvents.Response.MAJOR_RESPONSE_DESCRIPTOR);\n            } else if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMinorMinuteThresholdNotPresent()) {\n                descriptors.add(CommonEvents.Response.MINOR_RESPONSE_DESCRIPTOR);\n            }\n        } else if (present && strict && addResponseDescriptors) {\n            if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMajorMinuteThresholdPresent()) {\n                descriptors.add(CommonEvents.Response.MAJOR_RESPONSE_DESCRIPTOR);\n            } else if (lastSeen.until(LocalDateTime.now(), ChronoUnit.MINUTES) > getMinorMinuteThresholdNotPresent()) {\n                descriptors.add(CommonEvents.Response.MINOR_RESPONSE_DESCRIPTOR);\n            }\n        }*/ descriptors . add ( CommonEvents . Descriptors . NOT_INTERRUPT ) ; boolean known = ! fireUnknownIfNotPresent || present ; boolean firstPresent = ( ! strict && ! present ) || ( strict && ! strictPresent ) ; long lastSeen = this . lastSeen . until ( LocalDateTime . now ( ) , ChronoUnit . SECONDS ) ; Optional < Event > presenceEvent = IdentificationManagerM . getInstance ( ) . getIdentification ( this ) . flatMap ( id -> PresenceEvent . createPresenceEvent ( id , strict , known , firstPresent , descriptors , lastSeen ) ) . map ( event -> event . addEventLifeCycleListener ( EventLifeCycle . APPROVED , lifeCycle -> { if ( known ) { this . lastSeen = LocalDateTime . now ( ) ; if ( strict ) this . strictPresent = true ; present = true ; } } ) ) ; if ( ! presenceEvent . isPresent ( ) ) { error ( \"unable to create PresenceEvent\" ) ; } else { fire ( presenceEvent . get ( ) , 5 ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Invoked when an activator - event occurs . [CODESPLIT] @ Override public void eventFired ( EventModel event ) { if ( event . containsDescriptor ( LeavingEvent . ID ) || event . containsDescriptor ( PresenceEvent . ID ) ) { if ( event . containsDescriptor ( LeavingEvent . ID ) ) { if ( event . containsDescriptor ( LeavingEvent . GENERAL_DESCRIPTOR ) ) { present = false ; strictPresent = false ; } else if ( event . containsDescriptor ( LeavingEvent . STRICT_DESCRIPTOR ) ) { nonStrictAvailable ( ) . thenAccept ( available -> { if ( ! available ) present = false ; strictPresent = false ; } ) ; } } else { present = true ; if ( event . containsDescriptor ( PresenceEvent . STRICT_DESCRIPTOR ) ) strictPresent = true ; } if ( event . containsDescriptor ( PresenceEvent . STRICT_DESCRIPTOR ) ) lastSeen = LocalDateTime . now ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "{ @inheritDoc } [CODESPLIT] public void copy ( String from , String to , boolean withStreams ) throws StorageClientException , AccessDeniedException , IOException { long ts = System . currentTimeMillis ( ) ; try { checkOpen ( ) ; // To Copy, get the to object out and copy everything over. Content f = get ( from ) ; if ( f == null ) { throw new StorageClientException ( \" Source content \" + from + \" does not exist\" ) ; } if ( f . getProperty ( UUID_FIELD ) == null ) { LOGGER . warn ( \"Bad Content item with no ID cant be copied {} \" , f ) ; throw new StorageClientException ( \" Source content \" + from + \"  Has no \" + UUID_FIELD ) ; } Content t = get ( to ) ; if ( t != null ) { LOGGER . debug ( \"Deleting {} \" , to ) ; delete ( to ) ; } Set < String > streams = Sets . newHashSet ( ) ; Map < String , Object > copyProperties = Maps . newHashMap ( ) ; if ( withStreams ) { for ( Entry < String , Object > p : f . getProperties ( ) . entrySet ( ) ) { // Protected fields (such as ID and path) will differ // between // the source and destination, so don't copy them. if ( ! PROTECTED_FIELDS . contains ( p . getKey ( ) ) ) { if ( p . getKey ( ) . startsWith ( BLOCKID_FIELD ) ) { streams . add ( p . getKey ( ) ) ; } else { copyProperties . put ( p . getKey ( ) , p . getValue ( ) ) ; } } } } else { copyProperties . putAll ( f . getProperties ( ) ) ; } copyProperties . put ( COPIED_FROM_PATH_FIELD , from ) ; copyProperties . put ( COPIED_FROM_ID_FIELD , f . getProperty ( UUID_FIELD ) ) ; copyProperties . put ( COPIED_DEEP_FIELD , withStreams ) ; t = new Content ( to , copyProperties ) ; update ( t ) ; LOGGER . debug ( \"Copy Updated {} {} \" , to , t ) ; for ( String stream : streams ) { String streamId = null ; if ( stream . length ( ) > BLOCKID_FIELD . length ( ) ) { streamId = stream . substring ( BLOCKID_FIELD . length ( ) + 1 ) ; } InputStream fromStream = getInputStream ( from , streamId ) ; writeBody ( to , fromStream ) ; fromStream . close ( ) ; } eventListener . onUpdate ( Security . ZONE_CONTENT , to , accessControlManager . getCurrentUserId ( ) , getResourceType ( f ) , true , null , \"op:copy\" ) ; } finally { statsService . apiCall ( ContentManagerImpl . class . getName ( ) , \"copy\" , System . currentTimeMillis ( ) - ts ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public void move ( String from , String to ) throws AccessDeniedException , StorageClientException { // to move, get the structure object out and modify, recreating parent // objects as necessary. long t = System . currentTimeMillis ( ) ; try { checkOpen ( ) ; accessControlManager . check ( Security . ZONE_CONTENT , from , Permissions . CAN_ANYTHING ) ; accessControlManager . check ( Security . ZONE_CONTENT , to , Permissions . CAN_READ . combine ( Permissions . CAN_WRITE ) ) ; Map < String , Object > fromStructure = Maps . newHashMap ( getCached ( keySpace , contentColumnFamily , from ) ) ; if ( ! exists ( fromStructure ) ) { throw new StorageClientException ( \"The source content to move from \" + from + \" does not exist, move operation failed\" ) ; } if ( exists ( fromStructure ) ) { String contentId = ( String ) fromStructure . get ( STRUCTURE_UUID_FIELD ) ; Map < String , Object > content = getCached ( keySpace , contentColumnFamily , contentId ) ; if ( content == null || content . size ( ) == 0 && TRUE . equals ( content . get ( DELETED_FIELD ) ) ) { throw new StorageClientException ( \"The source content to move from \" + from + \" does not exist, move operation failed\" ) ; } } Map < String , Object > toStructure = getCached ( keySpace , contentColumnFamily , to ) ; if ( exists ( toStructure ) ) { String contentId = ( String ) toStructure . get ( STRUCTURE_UUID_FIELD ) ; Map < String , Object > content = getCached ( keySpace , contentColumnFamily , contentId ) ; if ( exists ( content ) ) { throw new StorageClientException ( \"The destination content to move to \" + to + \"  exists, move operation failed\" ) ; } } String idStore = ( String ) fromStructure . get ( STRUCTURE_UUID_FIELD ) ; // move the content to the new location, then delete the old. if ( ! StorageClientUtils . isRoot ( to ) ) { // if not a root, modify the new parent location, creating the // structured if necessary String parent = StorageClientUtils . getParentObjectPath ( to ) ; Map < String , Object > parentToStructure = getCached ( keySpace , contentColumnFamily , parent ) ; if ( ! exists ( parentToStructure ) ) { // create a new parent Content content = new Content ( parent , null ) ; update ( content ) ; } } // update the content data to reflect the new primary location. putCached ( keySpace , contentColumnFamily , idStore , ImmutableMap . of ( PATH_FIELD , ( Object ) to ) , false ) ; // insert the new to Structure and remove the from fromStructure . put ( PATH_FIELD , to ) ; putCached ( keySpace , contentColumnFamily , to , fromStructure , true ) ; // remove the old from. putCached ( keySpace , contentColumnFamily , from , ImmutableMap . of ( DELETED_FIELD , ( Object ) TRUE ) , false ) ; // move does not add resourceTypes to events. eventListener . onDelete ( Security . ZONE_CONTENT , from , accessControlManager . getCurrentUserId ( ) , null , null , \"op:move\" ) ; eventListener . onUpdate ( Security . ZONE_CONTENT , to , accessControlManager . getCurrentUserId ( ) , null , true , null , \"op:move\" ) ; } finally { statsService . apiCall ( ContentManagerImpl . class . getName ( ) , \"move\" , System . currentTimeMillis ( ) - t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public void link ( String from , String to ) throws AccessDeniedException , StorageClientException { // a link places a pointer to the content in the parent of from, but // does not delete or modify the structure of to. // read from is required and write to. long t = System . currentTimeMillis ( ) ; try { checkOpen ( ) ; accessControlManager . check ( Security . ZONE_CONTENT , to , Permissions . CAN_READ ) ; accessControlManager . check ( Security . ZONE_CONTENT , from , Permissions . CAN_READ . combine ( Permissions . CAN_WRITE ) ) ; Map < String , Object > toStructure = getCached ( keySpace , contentColumnFamily , to ) ; if ( ! exists ( toStructure ) ) { throw new StorageClientException ( \"The source content to link from \" + to + \" does not exist, link operation failed\" ) ; } Map < String , Object > fromStructure = getCached ( keySpace , contentColumnFamily , from ) ; if ( exists ( fromStructure ) ) { throw new StorageClientException ( \"The destination content to link to \" + from + \"  exists, link operation failed\" ) ; } if ( StorageClientUtils . isRoot ( from ) ) { throw new StorageClientException ( \"The link \" + to + \"  is a root, not possible to create a soft link\" ) ; } // create a new structure object pointing back to the shared // location Object idStore = toStructure . get ( STRUCTURE_UUID_FIELD ) ; // if not a root, modify the new parent location, creating the // structured if necessary String parent = StorageClientUtils . getParentObjectPath ( from ) ; Map < String , Object > parentToStructure = getCached ( keySpace , contentColumnFamily , parent ) ; if ( ! exists ( parentToStructure ) ) { // create a new parent Content content = new Content ( parent , null ) ; update ( content ) ; } // create the new object for the path, pointing to the Object putCached ( keySpace , contentColumnFamily , from , ImmutableMap . of ( STRUCTURE_UUID_FIELD , idStore , PATH_FIELD , from , LINKED_PATH_FIELD , to , DELETED_FIELD , new RemoveProperty ( ) ) , true ) ; } finally { statsService . apiCall ( ContentManagerImpl . class . getName ( ) , \"link\" , System . currentTimeMillis ( ) - t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public InputStream getVersionInputStream ( String path , String versionId ) throws AccessDeniedException , StorageClientException , IOException { return getVersionInputStream ( path , versionId , null ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "TODO : Unit test [CODESPLIT] public InputStream getVersionInputStream ( String path , String versionId , String streamId ) throws AccessDeniedException , StorageClientException , IOException { long t = System . currentTimeMillis ( ) ; try { accessControlManager . check ( Security . ZONE_CONTENT , path , Permissions . CAN_READ ) ; checkOpen ( ) ; Map < String , Object > structure = getCached ( keySpace , contentColumnFamily , path ) ; if ( exists ( structure ) ) { String contentId = ( String ) structure . get ( STRUCTURE_UUID_FIELD ) ; Map < String , Object > content = getCached ( keySpace , contentColumnFamily , contentId ) ; if ( exists ( content ) ) { String versionHistoryId = ( String ) content . get ( VERSION_HISTORY_ID_FIELD ) ; if ( versionHistoryId != null ) { Map < String , Object > versionHistory = getCached ( keySpace , contentColumnFamily , versionHistoryId ) ; if ( versionHistory != null && versionHistory . containsKey ( versionId ) ) { return internalGetInputStream ( versionId , streamId ) ; } } } } return null ; } finally { statsService . apiCall ( ContentManagerImpl . class . getName ( ) , \"egtVersionInputStream\" , System . currentTimeMillis ( ) - t ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override protected void handleIQResult ( IQ iq ) { String packetCallbackId = iq . getID ( ) + \"@\" + iq . getFrom ( ) . toBareJID ( ) ; PacketCallback callback = packetCallbacks . get ( packetCallbackId ) ; if ( callback != null ) { callback . handle ( iq ) ; packetCallbacks . remove ( packetCallbackId ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "/ * ( non - Javadoc ) [CODESPLIT] @ Override public Packet syncSendPacket ( Packet packet ) { final BlockingQueue < Packet > queue = new ArrayBlockingQueue < Packet > ( 1 ) ; packetCallbacks . put ( packet . getID ( ) + \"@\" + packet . getTo ( ) . toBareJID ( ) , new PacketCallback ( ) { @ Override public void handle ( Packet packet ) { queue . add ( packet ) ; } } ) ; send ( packet ) ; try { return queue . poll ( timeOutMilliSeconds , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } finally { packetCallbacks . remove ( packet . getID ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "gets whether the request is permanent ( = permanent resource is available and true ) [CODESPLIT] public static boolean isPermanent ( EventModel eventModel ) { if ( eventModel . getListResourceContainer ( ) . containsResourcesFromSource ( ID ) ) { return eventModel . getListResourceContainer ( ) . provideResource ( ID ) . stream ( ) . map ( ResourceModel :: getResource ) . filter ( ob -> ob instanceof Boolean ) . map ( ob -> ( Boolean ) ob ) . findAny ( ) . orElse ( false ) ; } else { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "returns true if the resource is true otherwise returns false [CODESPLIT] public static boolean isPermanent ( ResourceModel resourceModel ) { Object resource = resourceModel . getResource ( ) ; try { return ( Boolean ) resource ; } catch ( ClassCastException e ) { return false ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Sets the name of the group . Changing the group s name is like moving all the group entries of the group to a new group specified by the new name . Since this group won t have entries it will be removed from the roster . This means that all the references to this object will be invalid and will need to be updated to the new group specified by the new name . [CODESPLIT] public void setName ( String name ) { synchronized ( entries ) { for ( RosterEntry entry : entries ) { Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; List < String > groupNames = new LinkedList < String > ( entry . getGroupNames ( ) ) ; groupNames . remove ( this . name ) ; groupNames . add ( name ) ; packet . addItem ( new JID ( entry . getUser ( ) ) , entry . getName ( ) , entry . getAsk ( ) , entry . getSubscription ( ) , groupNames ) ; connection . sendPacket ( packet ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Returns the roster entry associated with the given XMPP address or <tt > null< / tt > if the user is not an entry in the group . [CODESPLIT] public RosterEntry getEntry ( String user ) { if ( user == null ) { return null ; } // Roster entries never include a resource so remove the resource // if it's a part of the XMPP address. user = StringUtils . parseBareAddress ( user ) ; String userLowerCase = user . toLowerCase ( ) ; synchronized ( entries ) { for ( RosterEntry entry : entries ) { if ( entry . getUser ( ) . equals ( userLowerCase ) ) { return entry ; } } } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a roster entry to this group . If the entry was unfiled then it will be removed from the unfiled list and will be added to this group . Note that this is an asynchronous call -- Smack must wait for the server to receive the updated roster . [CODESPLIT] public void addEntry ( RosterEntry entry ) throws XMPPException { PacketCollector collector = null ; // Only add the entry if it isn't already in the list. synchronized ( entries ) { if ( ! entries . contains ( entry ) ) { Roster packet = new Roster ( ) ; packet . setType ( IQ . Type . set ) ; List < String > groupNames = new LinkedList < String > ( entry . getGroupNames ( ) ) ; groupNames . add ( getName ( ) ) ; packet . addItem ( new JID ( entry . getUser ( ) ) , entry . getName ( ) , entry . getAsk ( ) , entry . getSubscription ( ) , groupNames ) ; // Wait up to a certain number of seconds for a reply from the // server. collector = connection . createPacketCollector ( new PacketIDFilter ( packet . getID ( ) ) ) ; connection . sendPacket ( packet ) ; } } if ( collector != null ) { IQ response = ( IQ ) collector . nextResult ( SmackConfiguration . getPacketReplyTimeout ( ) ) ; collector . cancel ( ) ; if ( response == null ) { throw new XMPPException ( \"No response from the server.\" ) ; } // If the server replied with an error, throw an exception. else if ( response . getType ( ) == IQ . Type . error ) { throw new XMPPException ( response . getError ( ) ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the value mapped to the key specified . [CODESPLIT] public V get ( Object key ) { int hashCode = hash ( ( key == null ) ? NULL : key ) ; HashEntry < K , V > entry = data [ hashIndex ( hashCode , data . length ) ] ; // no // local // for // hash // index while ( entry != null ) { if ( entry . hashCode == hashCode && isEqualKey ( key , entry . key ) ) { return entry . getValue ( ) ; } entry = entry . next ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the map contains the specified key . [CODESPLIT] public boolean containsKey ( Object key ) { int hashCode = hash ( ( key == null ) ? NULL : key ) ; HashEntry entry = data [ hashIndex ( hashCode , data . length ) ] ; // no local // for hash // index while ( entry != null ) { if ( entry . hashCode == hashCode && isEqualKey ( key , entry . getKey ( ) ) ) { return true ; } entry = entry . next ; } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks whether the map contains the specified value . [CODESPLIT] public boolean containsValue ( Object value ) { if ( value == null ) { for ( int i = 0 , isize = data . length ; i < isize ; i ++ ) { HashEntry entry = data [ i ] ; while ( entry != null ) { if ( entry . getValue ( ) == null ) { return true ; } entry = entry . next ; } } } else { for ( int i = 0 , isize = data . length ; i < isize ; i ++ ) { HashEntry entry = data [ i ] ; while ( entry != null ) { if ( isEqualValue ( value , entry . getValue ( ) ) ) { return true ; } entry = entry . next ; } } } return false ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts a key - value mapping into this map . [CODESPLIT] public V put ( K key , V value ) { int hashCode = hash ( ( key == null ) ? NULL : key ) ; int index = hashIndex ( hashCode , data . length ) ; HashEntry < K , V > entry = data [ index ] ; while ( entry != null ) { if ( entry . hashCode == hashCode && isEqualKey ( key , entry . getKey ( ) ) ) { V oldValue = entry . getValue ( ) ; updateEntry ( entry , value ) ; return oldValue ; } entry = entry . next ; } addMapping ( index , hashCode , key , value ) ; return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Puts all the values from the specified map into this map . <p / > This implementation iterates around the specified map and uses { @link #put ( Object Object ) } . [CODESPLIT] public void putAll ( Map < ? extends K , ? extends V > map ) { int mapSize = map . size ( ) ; if ( mapSize == 0 ) { return ; } int newSize = ( int ) ( ( size + mapSize ) / loadFactor + 1 ) ; ensureCapacity ( calculateNewCapacity ( newSize ) ) ; // Have to cast here because of compiler inference problems. for ( Iterator it = map . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < ? extends K , ? extends V > entry = ( Map . Entry < ? extends K , ? extends V > ) it . next ( ) ; put ( entry . getKey ( ) , entry . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes the specified mapping from this map . [CODESPLIT] public V remove ( Object key ) { int hashCode = hash ( ( key == null ) ? NULL : key ) ; int index = hashIndex ( hashCode , data . length ) ; HashEntry < K , V > entry = data [ index ] ; HashEntry < K , V > previous = null ; while ( entry != null ) { if ( entry . hashCode == hashCode && isEqualKey ( key , entry . getKey ( ) ) ) { V oldValue = entry . getValue ( ) ; removeMapping ( entry , index , previous ) ; return oldValue ; } previous = entry ; entry = entry . next ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Clears the map resetting the size to zero and nullifying references to avoid garbage collection issues . [CODESPLIT] public void clear ( ) { modCount ++ ; HashEntry [ ] data = this . data ; for ( int i = data . length - 1 ; i >= 0 ; i -- ) { data [ i ] = null ; } size = 0 ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the hash code for the key specified . This implementation uses the additional hashing routine from JDK1 . 4 . Subclasses can override this to return alternate hash codes . [CODESPLIT] protected int hash ( Object key ) { // same as JDK 1.4 int h = key . hashCode ( ) ; h += ~ ( h << 9 ) ; h ^= ( h >>> 14 ) ; h += ( h << 4 ) ; h ^= ( h >>> 10 ) ; return h ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two keys in internal converted form to see if they are equal . This implementation uses the equals method . Subclasses can override this to match differently . [CODESPLIT] protected boolean isEqualKey ( Object key1 , Object key2 ) { return ( key1 == key2 || ( ( key1 != null ) && key1 . equals ( key2 ) ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Compares two values in external form to see if they are equal . This implementation uses the equals method and assumes neither value is null . Subclasses can override this to match differently . [CODESPLIT] protected boolean isEqualValue ( Object value1 , Object value2 ) { return ( value1 == value2 || value1 . equals ( value2 ) ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the entry mapped to the key specified . <p / > This method exists for subclasses that may need to perform a multi - step process accessing the entry . The public methods in this class don t use this method to gain a small performance boost . [CODESPLIT] protected HashEntry < K , V > getEntry ( Object key ) { int hashCode = hash ( ( key == null ) ? NULL : key ) ; HashEntry < K , V > entry = data [ hashIndex ( hashCode , data . length ) ] ; // no // local // for // hash // index while ( entry != null ) { if ( entry . hashCode == hashCode && isEqualKey ( key , entry . getKey ( ) ) ) { return entry ; } entry = entry . next ; } return null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Updates an existing key - value mapping to change the value . <p / > This implementation calls <code > setValue () < / code > on the entry . Subclasses could override to handle changes to the map . [CODESPLIT] protected void updateEntry ( HashEntry < K , V > entry , V newValue ) { entry . setValue ( newValue ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reuses an existing key - value mapping storing completely new data . <p / > This implementation sets all the data fields on the entry . Subclasses could populate additional entry fields . [CODESPLIT] protected void reuseEntry ( HashEntry < K , V > entry , int hashIndex , int hashCode , K key , V value ) { entry . next = data [ hashIndex ] ; entry . hashCode = hashCode ; entry . key = key ; entry . value = value ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Adds a new key - value mapping into this map . <p / > This implementation calls <code > createEntry () < / code > <code > addEntry () < / code > and <code > checkCapacity () < / code > . It also handles changes to <code > modCount< / code > and <code > size< / code > . Subclasses could override to fully control adds to the map . [CODESPLIT] protected void addMapping ( int hashIndex , int hashCode , K key , V value ) { modCount ++ ; HashEntry < K , V > entry = createEntry ( data [ hashIndex ] , hashCode , key , value ) ; addEntry ( entry , hashIndex ) ; size ++ ; checkCapacity ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes a mapping from the map . <p / > This implementation calls <code > removeEntry () < / code > and <code > destroyEntry () < / code > . It also handles changes to <code > modCount< / code > and <code > size< / code > . Subclasses could override to fully control removals from the map . [CODESPLIT] protected void removeMapping ( HashEntry < K , V > entry , int hashIndex , HashEntry < K , V > previous ) { modCount ++ ; removeEntry ( entry , hashIndex , previous ) ; size -- ; destroyEntry ( entry ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Removes an entry from the chain stored in a particular index . <p / > This implementation removes the entry from the data storage table . The size is not updated . Subclasses could override to handle changes to the map . [CODESPLIT] protected void removeEntry ( HashEntry < K , V > entry , int hashIndex , HashEntry < K , V > previous ) { if ( previous == null ) { data [ hashIndex ] = entry . next ; } else { previous . next = entry . next ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Kills an entry ready for the garbage collector . <p / > This implementation prepares the HashEntry for garbage collection . Subclasses can override this to implement caching ( override clear as well ) . [CODESPLIT] protected void destroyEntry ( HashEntry < K , V > entry ) { entry . next = null ; entry . key = null ; entry . value = null ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Checks the capacity of the map and enlarges it if necessary . <p / > This implementation uses the threshold to check if the map needs enlarging [CODESPLIT] protected void checkCapacity ( ) { if ( size >= threshold ) { int newCapacity = data . length * 2 ; if ( newCapacity <= MAXIMUM_CAPACITY ) { ensureCapacity ( newCapacity ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Changes the size of the data structure to the capacity proposed . [CODESPLIT] protected void ensureCapacity ( int newCapacity ) { int oldCapacity = data . length ; if ( newCapacity <= oldCapacity ) { return ; } if ( size == 0 ) { threshold = calculateThreshold ( newCapacity , loadFactor ) ; data = new HashEntry [ newCapacity ] ; } else { HashEntry < K , V > oldEntries [ ] = data ; HashEntry < K , V > newEntries [ ] = new HashEntry [ newCapacity ] ; modCount ++ ; for ( int i = oldCapacity - 1 ; i >= 0 ; i -- ) { HashEntry < K , V > entry = oldEntries [ i ] ; if ( entry != null ) { oldEntries [ i ] = null ; // gc do { HashEntry < K , V > next = entry . next ; int index = hashIndex ( entry . hashCode , newCapacity ) ; entry . next = newEntries [ index ] ; newEntries [ index ] = entry ; entry = next ; } while ( entry != null ) ; } } threshold = calculateThreshold ( newCapacity , loadFactor ) ; data = newEntries ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Calculates the new capacity of the map . This implementation normalizes the capacity to a power of two . [CODESPLIT] protected int calculateNewCapacity ( int proposedCapacity ) { int newCapacity = 1 ; if ( proposedCapacity > MAXIMUM_CAPACITY ) { newCapacity = MAXIMUM_CAPACITY ; } else { while ( newCapacity < proposedCapacity ) { newCapacity <<= 1 ; // multiply by two } if ( newCapacity > MAXIMUM_CAPACITY ) { newCapacity = MAXIMUM_CAPACITY ; } } return newCapacity ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the <code > next< / code > field from a <code > HashEntry< / code > . Used in subclasses that have no visibility of the field . [CODESPLIT] protected HashEntry < K , V > entryNext ( HashEntry < K , V > entry ) { return entry . next ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets an iterator over the map . Changes made to the iterator affect this map . <p / > A MapIterator returns the keys in the map . It also provides convenient methods to get the key and value and set the value . It avoids the need to create an entrySet / keySet / values object . It also avoids creating the Map . Entry object . [CODESPLIT] public MapIterator < K , V > mapIterator ( ) { if ( size == 0 ) { return EmptyMapIterator . INSTANCE ; } return new HashMapIterator < K , V > ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Creates an entry set iterator . Subclasses can override this to return iterators with different properties . [CODESPLIT] protected Iterator < Map . Entry < K , V > > createEntrySetIterator ( ) { if ( size ( ) == 0 ) { return EmptyIterator . INSTANCE ; } return new EntrySetIterator < K , V > ( this ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Gets the keySet view of the map . Changes made to the view affect this map . To simply iterate through the keys use { @link #mapIterator () } . [CODESPLIT] public Set < K > keySet ( ) { if ( keySet == null ) { keySet = new KeySet < K , V > ( this ) ; } return keySet ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Writes the map data to the stream . This method must be overridden if a subclass must be setup before <code > put () < / code > is used . <p / > Serialization is not one of the JDK s nicest topics . Normal serialization will initialise the superclass before the subclass . Sometimes however this isn t what you want as in this case the <code > put () < / code > method on read can be affected by subclass state . <p / > The solution adopted here is to serialize the state data of this class in this protected method . This method must be called by the <code > writeObject () < / code > of the first serializable subclass . <p / > Subclasses may override if they have a specific field that must be present on read before this implementation will work . Generally the read determines what must be serialized here if anything . [CODESPLIT] protected void doWriteObject ( ObjectOutputStream out ) throws IOException { out . writeFloat ( loadFactor ) ; out . writeInt ( data . length ) ; out . writeInt ( size ) ; for ( MapIterator it = mapIterator ( ) ; it . hasNext ( ) ; ) { out . writeObject ( it . next ( ) ) ; out . writeObject ( it . getValue ( ) ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Reads the map data from the stream . This method must be overridden if a subclass must be setup before <code > put () < / code > is used . <p / > Serialization is not one of the JDK s nicest topics . Normal serialization will initialise the superclass before the subclass . Sometimes however this isn t what you want as in this case the <code > put () < / code > method on read can be affected by subclass state . <p / > The solution adopted here is to deserialize the state data of this class in this protected method . This method must be called by the <code > readObject () < / code > of the first serializable subclass . <p / > Subclasses may override if the subclass has a specific field that must be present before <code > put () < / code > or <code > calculateThreshold () < / code > will work correctly . [CODESPLIT] protected void doReadObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { loadFactor = in . readFloat ( ) ; int capacity = in . readInt ( ) ; int size = in . readInt ( ) ; init ( ) ; data = new HashEntry [ capacity ] ; for ( int i = 0 ; i < size ; i ++ ) { K key = ( K ) in . readObject ( ) ; V value = ( V ) in . readObject ( ) ; put ( key , value ) ; } threshold = calculateThreshold ( data . length , loadFactor ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Load a Map from binary stream [CODESPLIT] public static void loadFromStream ( String key , Map < String , Object > output , InputStream binaryStream , String type ) throws IOException { DataInputStream dis = new DataInputStream ( binaryStream ) ; String ckey = dis . readUTF ( ) ; if ( ! key . equals ( ckey ) ) { throw new IOException ( \"Body Key does not match row key, unable to read\" ) ; } readMapFromStream ( output , dis ) ; String cftype = null ; try { cftype = dis . readUTF ( ) ; } catch ( IOException e ) { LOGGER . debug ( \"No type specified\" ) ; } if ( cftype != null && ! cftype . equals ( type ) ) { throw new IOException ( \"Object is not of expected column family, unable to read expected [\" + type + \"] was [\" + cftype + \"]\" ) ; } LOGGER . debug ( \"Finished Reading\" ) ; dis . close ( ) ; binaryStream . close ( ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the data isnt there . See the last writeUTF for an example . [CODESPLIT] public static InputStream storeMapToStream ( String key , Map < String , Object > m , String type ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; DataOutputStream dos = new DataOutputStream ( baos ) ; dos . writeUTF ( key ) ; writeMapToStream ( m , dos ) ; // add the type in dos . writeUTF ( type ) ; dos . flush ( ) ; baos . flush ( ) ; byte [ ] b = baos . toByteArray ( ) ; baos . close ( ) ; dos . close ( ) ; return new ByteArrayInputStream ( b ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "the data isnt there . See the last writeUTF for an example . [CODESPLIT] public static void writeMapToStream ( Map < String , Object > m , DataOutputStream dos ) throws IOException { int size = 0 ; for ( Entry < String , ? > e : m . entrySet ( ) ) { Object o = e . getValue ( ) ; if ( o != null && ! ( o instanceof RemoveProperty ) ) { size ++ ; } } dos . writeInt ( size ) ; LOGGER . debug ( \"Write {} items\" , size ) ; for ( Entry < String , ? > e : m . entrySet ( ) ) { Object o = e . getValue ( ) ; if ( o != null && ! ( o instanceof RemoveProperty ) ) { String k = e . getKey ( ) ; LOGGER . debug ( \"Write {} \" , k ) ; dos . writeUTF ( k ) ; Type < ? > t = getTypeOfObject ( o ) ; dos . writeInt ( t . getTypeId ( ) ) ; t . save ( dos , o ) ; } } LOGGER . debug ( \"Finished Writen {} items\" , size ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "This method is used to register the modules [CODESPLIT] @ Override public void register ( ) { prepare ( ) ; ContentGenerator [ ] contentGenerators = registerContentGenerator ( ) ; if ( contentGenerators != null ) { for ( ContentGenerator contentGenerator : contentGenerators ) { try { getContext ( ) . getContentGenerators ( ) . registerContentGenerator ( contentGenerator ) ; } catch ( IllegalIDException e ) { context . getLogger ( ) . fatal ( \"Illegal Id for Module: \" + contentGenerator . getID ( ) , e ) ; } } } EventsControllerModel [ ] eventsControllerModels = registerEventController ( ) ; if ( eventsControllerModels != null ) { for ( EventsControllerModel eventsController : eventsControllerModels ) { try { getContext ( ) . getEvents ( ) . distributor ( ) . registerEventsController ( eventsController ) ; } catch ( IllegalIDException e ) { context . getLogger ( ) . fatal ( \"Illegal Id for Module: \" + eventsController . getID ( ) , e ) ; } } } OutputPluginModel [ ] outputPluginModels = registerOutputPlugin ( ) ; if ( outputPluginModels != null ) { for ( OutputPluginModel outputPlugin : outputPluginModels ) { try { getContext ( ) . getOutput ( ) . addOutputPlugin ( outputPlugin ) ; } catch ( IllegalIDException e ) { context . getLogger ( ) . fatal ( \"Illegal Id for Module: \" + outputPlugin . getID ( ) , e ) ; } } } OutputExtensionModel [ ] outputExtensionModels = registerOutputExtension ( ) ; if ( outputExtensionModels != null ) { for ( OutputExtensionModel outputExtension : outputExtensionModels ) { try { getContext ( ) . getOutput ( ) . addOutputExtension ( outputExtension ) ; } catch ( IllegalIDException e ) { context . getLogger ( ) . fatal ( \"Illegal Id for Module: \" + outputExtension . getID ( ) , e ) ; } } } OutputControllerModel [ ] outputControllerModels = registerOutputController ( ) ; if ( outputControllerModels != null ) { for ( OutputControllerModel outputController : outputControllerModels ) { try { getContext ( ) . getOutput ( ) . addOutputController ( outputController ) ; } catch ( IllegalIDException e ) { context . getLogger ( ) . fatal ( \"Illegal Id for Module: \" + outputController . getID ( ) , e ) ; } } } ActivatorModel [ ] activatorModels = registerActivator ( ) ; getContext ( ) . getSystem ( ) . registerInitializedListener ( ( ) -> { if ( activatorModels != null ) { for ( ActivatorModel activator : activatorModels ) { try { getContext ( ) . getActivators ( ) . addActivator ( activator ) ; } catch ( IllegalIDException e ) { context . getLogger ( ) . fatal ( \"Illegal Id for Module: \" + activator . getID ( ) , e ) ; } } } } ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Internal initiation of addOn - fake constructor comes before prepare [CODESPLIT] @ Override public void initAddOn ( org . intellimate . izou . system . Context context ) { this . context = new Context ( context ) ; }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Starts a reconnection mechanism if it was configured to do that . The algorithm is been executed when the first connection error is detected . <p / > The reconnection mechanism will try to reconnect periodically in this way : <ol > <li > First it will try 6 times every 10 seconds . <li > Then it will try 10 times every 1 minute . <li > Finally it will try indefinitely every 5 minutes . < / ol > [CODESPLIT] synchronized protected void reconnect ( ) { if ( this . isReconnectionAllowed ( ) ) { // Since there is no thread running, creates a new one to attempt // the reconnection. // avoid to run duplicated reconnectionThread -- fd: 16/09/2010 if ( reconnectionThread != null && reconnectionThread . isAlive ( ) ) return ; reconnectionThread = new Thread ( ) { /**\n                 * Holds the current number of reconnection attempts\n                 */ private int attempts = 0 ; /**\n                 * Returns the number of seconds until the next reconnection\n                 * attempt.\n                 * \n                 * @return the number of seconds until the next reconnection\n                 *         attempt.\n                 */ private int timeDelay ( ) { attempts ++ ; if ( attempts > 13 ) { return randomBase * 6 * 5 ; // between 2.5 and 7.5 // minutes (~5 minutes) } if ( attempts > 7 ) { return randomBase * 6 ; // between 30 and 90 seconds (~1 // minutes) } return randomBase ; // 10 seconds } /**\n                 * The process will try the reconnection until the connection\n                 * succeed or the user cancell it\n                 */ public void run ( ) { // The process will try to reconnect until the connection is // established or // the user cancel the reconnection process {@link // Connection#disconnect()} while ( ReconnectionManager . this . isReconnectionAllowed ( ) ) { // Find how much time we should wait until the next // reconnection int remainingSeconds = timeDelay ( ) ; // Sleep until we're ready for the next reconnection // attempt. Notify // listeners once per second about how much time remains // before the next // reconnection attempt. while ( ReconnectionManager . this . isReconnectionAllowed ( ) && remainingSeconds > 0 ) { try { Thread . sleep ( 1000 ) ; remainingSeconds -- ; ReconnectionManager . this . notifyAttemptToReconnectIn ( remainingSeconds ) ; } catch ( InterruptedException e1 ) { log . warn ( \"Sleeping thread interrupted\" ) ; // Notify the reconnection has failed ReconnectionManager . this . notifyReconnectionFailed ( e1 ) ; } } // Makes a reconnection attempt try { if ( ReconnectionManager . this . isReconnectionAllowed ( ) ) { connection . connect ( ) ; } } catch ( XMPPException e ) { // Fires the failed reconnection notification ReconnectionManager . this . notifyReconnectionFailed ( e ) ; } } } } ; reconnectionThread . setName ( \"Smack Reconnection Manager\" ) ; reconnectionThread . setDaemon ( true ) ; reconnectionThread . start ( ) ; } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires listeners when a reconnection attempt has failed . [CODESPLIT] protected void notifyReconnectionFailed ( Exception exception ) { if ( isReconnectionAllowed ( ) ) { for ( ConnectionListener listener : connection . connectionListeners ) { listener . reconnectionFailed ( exception ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
{"input": "Fires listeners when The Connection will retry a reconnection . Expressed in seconds . [CODESPLIT] protected void notifyAttemptToReconnectIn ( int seconds ) { if ( isReconnectionAllowed ( ) ) { for ( ConnectionListener listener : connection . connectionListeners ) { listener . reconnectingIn ( seconds ) ; } } }", "target": 1, "target_options": ["no_match", "match"]}
